{"text": "Require Import compcert.lib.Coqlib.\nRequire Import List. Import ListNotations.\nRequire Import hmacdrbg.entropy.\nRequire Import VST.floyd.functional_base.\n\nDefinition DRBG_working_state: Type := (list byte * list byte * Z)%type. (* value * key * reseed_counter *)\nDefinition DRBG_state_handle: Type := (DRBG_working_state * Z * bool)%type. (* state, security_strength, prediction_resistance_flag *)\n\nDefinition DRBG_instantiate_function\n            (instantiate_algorithm: list byte -> list byte -> list byte -> Z -> DRBG_working_state)\n            (min_entropy_length max_entropy_length: Z) (provided_nonce: option (list byte))\n            (highest_supported_security_strength: Z) (max_personalization_string_length: Z)\n            (prediction_resistance_supported: bool) (entropy_stream: ENTROPY.stream)\n            (requested_instantiation_security_strength: Z) (prediction_resistance_flag: bool)\n            (personalization_string: list byte): ENTROPY.result DRBG_state_handle :=\n  if requested_instantiation_security_strength >? highest_supported_security_strength then ENTROPY.error ENTROPY.generic_error entropy_stream\n  else match prediction_resistance_flag, prediction_resistance_supported with\n         | true, false => ENTROPY.error ENTROPY.generic_error entropy_stream\n         | _,_ =>\n           if (Zlength personalization_string) >? max_personalization_string_length then ENTROPY.error ENTROPY.generic_error entropy_stream\n           else\n             let security_strength := if requested_instantiation_security_strength <=? 14 then Some 14\n                                      else if requested_instantiation_security_strength <=? 16 then Some 16\n                                      else if requested_instantiation_security_strength <=? 24 then Some 24\n                                      else if requested_instantiation_security_strength <=? 32 then Some 32\n                                      else None in\n             match security_strength with\n               | None => ENTROPY.error ENTROPY.generic_error entropy_stream\n               | Some security_strength =>\n               match get_entropy security_strength min_entropy_length max_entropy_length prediction_resistance_flag entropy_stream with\n                 | ENTROPY.error e s' => ENTROPY.error ENTROPY.catastrophic_error s'\n                 | ENTROPY.success entropy_input entropy_stream =>\n                   let nonce_result := match provided_nonce with\n                                         | Some n => ENTROPY.success n entropy_stream\n                                         | None => get_entropy (security_strength/2) (min_entropy_length/2) (max_entropy_length/2)\n                                                               prediction_resistance_flag entropy_stream\n                                       end in\n                   match nonce_result with\n                     | ENTROPY.error e s' => ENTROPY.error ENTROPY.catastrophic_error s'\n                     | ENTROPY.success nonce entropy_stream =>\n                       let initial_working_state := instantiate_algorithm entropy_input nonce personalization_string security_strength in\n                       ENTROPY.success (initial_working_state, security_strength, prediction_resistance_flag) entropy_stream\n                   end\n               end\n             end\n       end.\n\nDefinition DRBG_reseed_function (reseed_algorithm: DRBG_working_state -> list byte -> list byte -> DRBG_working_state)\n            (min_entropy_length max_entropy_length: Z) (max_additional_input_length: Z)\n            (entropy_stream: ENTROPY.stream) (state_handle: DRBG_state_handle)\n            (prediction_resistance_request: bool) (additional_input: list byte): ENTROPY.result DRBG_state_handle :=\n  match state_handle with (working_state, security_strength, prediction_resistance_flag) =>\n  if prediction_resistance_request && (negb prediction_resistance_flag) then ENTROPY.error ENTROPY.generic_error entropy_stream\n  else\n    if Zlength additional_input >? max_additional_input_length then ENTROPY.error ENTROPY.generic_error entropy_stream\n    else\n      match get_entropy security_strength min_entropy_length max_entropy_length prediction_resistance_request entropy_stream with\n        | ENTROPY.error _ s => ENTROPY.error ENTROPY.catastrophic_error s\n        | ENTROPY.success entropy_input entropy_stream =>\n          let new_working_state := reseed_algorithm working_state entropy_input additional_input in\n          ENTROPY.success (new_working_state, security_strength, prediction_resistance_flag) entropy_stream\n      end\n  end.\n\nInductive DRBG_generate_algorithm_result :=\n| generate_algorithm_reseed_required: DRBG_generate_algorithm_result\n| generate_algorithm_success: list byte -> DRBG_working_state -> DRBG_generate_algorithm_result.\n\nFixpoint DRBG_generate_function_helper (generate_algorithm: DRBG_working_state -> Z -> list byte -> DRBG_generate_algorithm_result)\n          (reseed_function: ENTROPY.stream -> DRBG_state_handle -> bool -> list byte -> ENTROPY.result DRBG_state_handle)\n          (entropy_stream: ENTROPY.stream) (state_handle: DRBG_state_handle) (requested_number_of_bytes: Z)\n          (prediction_resistance_request: bool) (additional_input: list byte) (should_reseed: bool) (count: nat): ENTROPY.result (list byte * DRBG_working_state) :=\n  let result := if should_reseed then\n                        match reseed_function entropy_stream state_handle prediction_resistance_request additional_input with\n                          | ENTROPY.success x entropy_stream => ENTROPY.success (x, []) entropy_stream\n                          | ENTROPY.error e entropy_stream => ENTROPY.error e entropy_stream\n                        end\n                      else ENTROPY.success (state_handle, additional_input) entropy_stream in\n  match result with\n    | ENTROPY.error e s => ENTROPY.error e s\n    | ENTROPY.success (state_handle, additional_input) entropy_stream =>\n      match state_handle with (working_state, security_strength, prediction_resistance_flag) =>\n        match generate_algorithm working_state requested_number_of_bytes additional_input with\n          | generate_algorithm_reseed_required =>\n            match count with\n              | O => ENTROPY.error ENTROPY.generic_error entropy_stream (* impossible *)\n              | S count' => DRBG_generate_function_helper generate_algorithm reseed_function\n                                entropy_stream state_handle requested_number_of_bytes\n                                prediction_resistance_request additional_input true count'\n            end\n          | generate_algorithm_success x y => ENTROPY.success (x, y) entropy_stream\n        end\n      end\n    end.\n\nDefinition DRBG_generate_function (generate_algorithm: Z -> DRBG_working_state -> Z -> list byte -> DRBG_generate_algorithm_result)\n             (reseed_function: ENTROPY.stream -> DRBG_state_handle -> bool -> list byte -> ENTROPY.result DRBG_state_handle)\n             (reseed_interval: Z) (max_number_of_bytes_per_request: Z) (max_additional_input_length: Z)\n             (entropy_stream: ENTROPY.stream) (state_handle: DRBG_state_handle)\n             (requested_number_of_bytes requested_security_strength: Z)\n             (prediction_resistance_request: bool) (additional_input: list byte): ENTROPY.result (list byte * DRBG_state_handle) :=\n  match state_handle with (working_state, security_strength, prediction_resistance_flag) =>\n    if requested_number_of_bytes >? max_number_of_bytes_per_request then ENTROPY.error ENTROPY.generic_error entropy_stream\n    else\n      if requested_security_strength >? security_strength then ENTROPY.error ENTROPY.generic_error entropy_stream\n      else\n        if (Zlength additional_input) >? max_additional_input_length then ENTROPY.error ENTROPY.generic_error entropy_stream\n        else\n          if prediction_resistance_request && (negb prediction_resistance_flag) then ENTROPY.error ENTROPY.generic_error entropy_stream\n          else\n            match DRBG_generate_function_helper (generate_algorithm reseed_interval) reseed_function\n                       entropy_stream state_handle requested_number_of_bytes prediction_resistance_request\n                       additional_input prediction_resistance_request 1%nat with\n              | ENTROPY.error e s => ENTROPY.error e s\n              | ENTROPY.success (output, new_working_state) entropy_stream =>\n                  ENTROPY.success (output, (new_working_state, security_strength, prediction_resistance_flag)) entropy_stream\n            end\n  end.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/hmacdrbg/DRBG_functions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.29746995506106744, "lm_q1q2_score": 0.19999848034099332}}
{"text": "(** Coq coding by choukh, July 2022 **)\n\nFrom ZF Require Import Basic Hierarchy Universe Finiteness.\n\nSection \u5b87\u5b99\u8574\u542b\u65e0\u7a77.\nContext {\ud835\udcdc : ZF}.\n\nDefinition V\u2099 := \u8fed\u4ee3 \u5e42 \u2205.\n(* V_<\u03c9 \u7c7b *)\nDefinition \u6709\u7a77\u5c42 x := \u2203 n, x = V\u2099 n.\n(* \u65e0\u7a77\u516c\u7406\u53d8\u4f53: V_<\u03c9 \u7c7b\u53ef\u96c6\u5316 *)\nDefinition Inf\u2c7d := setLike \u6709\u7a77\u5c42.\n(* \u5b58\u5728\u5b87\u5b99 *)\nDefinition Univ := \u2203 u, \u5b87\u5b99 u.\n\nFact \u5b87\u5b99\u8574\u542b\u65e0\u7a77 : Univ \u2192 Inf\u2c7d.\nProof.\n  intros [u U]. exists (u \u2229\u209a \u6709\u7a77\u5c42).\n  intros x. split; intros H.\n  - now apply \u5206\u79bb in H.\n  - destruct H as [n ->]. apply \u5206\u79bb. split. 2:now exists n.\n    induction n. now apply \u5b87\u5b99\u5bf9\u7a7a\u96c6\u5c01\u95ed. now apply \u5b87\u5b99\u5bf9\u5e42\u96c6\u5c01\u95ed.\nQed.\n\nEnd \u5b87\u5b99\u8574\u542b\u65e0\u7a77.\n\nSection \u65e0\u7a77\u8574\u542b\u5b87\u5b99.\nContext {\ud835\udcdc : ZF}.\n\nHypothesis inf : Inf\u2c7d.\n(* V_<\u03c9 \u96c6 *)\nDefinition Vlt\u03c9 := proj1_sig (\u96c6\u5316\u5927\u6d88\u9664 inf).\n(* Vlt\u03c9 =\u209a \u6709\u7a77\u5c42 *)\nDefinition \u65e0\u7a77 := proj2_sig (\u96c6\u5316\u5927\u6d88\u9664 inf).\n\nDefinition V\u03c9 := \u22c3 Vlt\u03c9.\n\nLemma Vn\u662f\u5c42 n : V\u2099 n \u2208\u209a \u5c42.\nProof. induction n. apply \u7a7a\u96c6\u5c42. now constructor. Qed.\n\nLemma V\u03c9\u662f\u5c42 : V\u03c9 \u2208\u209a \u5c42.\nProof.\n  constructor. intros x X.\n  apply \u65e0\u7a77 in X as [n ->]. apply Vn\u662f\u5c42.\nQed.\n\nLemma Vn\u5c5eVlt\u03c9 n : V\u2099 n \u2208 Vlt\u03c9.\nProof. apply \u65e0\u7a77. now exists n. Qed.\n\nLemma Vn\u5c5eV\u03c9 n : V\u2099 n \u2208 V\u03c9.\nProof.\n  apply \u5e76\u96c6. exists (V\u2099 (S n)).\n  split. now apply \u5e42\u96c6. apply Vn\u5c5eVlt\u03c9.\nQed.\n\nFact V\u03c9\u5bf9\u7a7a\u96c6\u5c01\u95ed : \u2205 \u2208 V\u03c9.\nProof. replace \u2205 with (V\u2099 0) by reflexivity. apply Vn\u5c5eV\u03c9. Qed.\n\nLemma V\u03c9\u6210\u5458\u5c5e\u67d0Vn x : x \u2208 V\u03c9 \u2192 \u2203 n, x \u2208 V\u2099 n.\nProof.\n  intros [y [xy yV]] % \u5e76\u96c6.\n  apply \u65e0\u7a77 in yV as [n ->]. now exists n.\nQed.\n\nLemma V\u03c9\u4e4b\u5e76 : V\u03c9 \u2286 \u22c3 V\u03c9.\nProof.\n  intros x X. apply V\u03c9\u6210\u5458\u5c5e\u67d0Vn in X as [n X].\n  apply \u5e76\u96c6. exists (V\u2099 n). split; trivial. apply Vn\u5c5eV\u03c9.\nQed.\n\nLemma V\u03c9\u662f\u6781\u9650\u5c42 : V\u03c9 \u2208\u209a \u6781\u9650\u5c42.\nProof. split. apply V\u03c9\u662f\u5c42. apply V\u03c9\u4e4b\u5e76. Qed.\n\nSection \u65e0\u7a77\u516c\u7406\u539f\u7248.\n\nDefinition \u5f52\u7eb3\u96c6 A := \u2205 \u2208 A \u2227 \u2200 a \u2208 A, a\u207a \u2208 A.\n(* \u65e0\u7a77\u516c\u7406: \u5b58\u5728\u5f52\u7eb3\u96c6 *)\nDefinition Inf := \u03a3 I, \u5f52\u7eb3\u96c6 I.\n\nLemma V\u03c9\u662f\u5f52\u7eb3\u96c6 : \u5f52\u7eb3\u96c6 V\u03c9.\nProof.\n  split. apply V\u03c9\u5bf9\u7a7a\u96c6\u5c01\u95ed.\n  intros. apply V\u03c9\u6210\u5458\u5c5e\u67d0Vn in H as [n an].\n  apply \u5e76\u96c6. exists (V\u2099 (S n)). split.\n  - cbn. apply \u540e\u7ee7_\u5347\u79e9. apply an. apply Vn\u662f\u5c42.\n  - apply Vn\u5c5eVlt\u03c9.\nQed.\n\nFact Inf\u2c7d_to_Inf : Inf.\nProof. exists V\u03c9. apply V\u03c9\u662f\u5f52\u7eb3\u96c6. Qed.\n\nEnd \u65e0\u7a77\u516c\u7406\u539f\u7248.\n\n(** V\u03c9\u96c6\u5316HF **)\n\nNotation HF := \u9057\u4f20\u6709\u7a77.\n\nLemma Vn\u662f\u9057\u4f20\u6709\u7a77\u96c6 n : HF (V\u2099 n).\nProof.\n  induction n as [|n IH].\n  - apply HF\u662f\u7a7a\u96c6\u5c01\u95ed\u7c7b.\n  - apply HF\u662f\u5e42\u96c6\u5c01\u95ed\u7c7b. apply IH.\nQed.\n\nLemma \u975e\u7a7a\u6709\u7a77\u94fe\u5c01\u95ed x : \u975e\u7a7a x \u2192 \u6709\u7a77 x \u2192 \u94fe x \u2192 \u22c3 x \u2208 x.\nProof.\n  induction 2 as [|x y _ IH]. destruct H. zf.\n  intros Ch. \u6392\u4e2d (y = \u2205) as [->|NEy%\u975e\u7a7aI].\n  - apply \u5e76\u5165. left. now rewrite \u5e76\u5165\u7a7a, \u5e76\u5355.\n  - assert (IH': \u22c3 y \u2208 y). {\n      apply IH; trivial. eapply \u94fe\u81a8\u80c0. 2:apply Ch.\n      intros z zy. apply \u5e76\u5165. auto.\n    }\n    assert (X: x \u2208 x \u2a2e y). apply \u5e76\u5165. auto.\n    assert (Y: \u22c3 y \u2208 x \u2a2e y). apply \u5e76\u5165. auto.\n    destruct (Ch _ X _ Y) as [XY|YX]; apply \u5e76\u5165.\n    + right. replace (\u22c3 (x \u2a2e y)) with (\u22c3 y). trivial. apply \u5916\u5ef6.\n      * apply \u5e76\u5f97\u7236\u96c6, \u5e76\u5165. auto.\n      * apply \u5e76\u5f97\u5b50\u96c6. intros z [->|Z]%\u5e76\u5165. zf. now apply \u5e76\u5f97\u7236\u96c6.\n    + left. apply \u5916\u5ef6.\n      * apply \u5e76\u5f97\u5b50\u96c6. intros z [->|Z]%\u5e76\u5165. zf.\n        intros w wz. apply YX, \u5e76\u96c6. eauto.\n      * apply \u5e76\u5f97\u7236\u96c6. apply \u5e76\u5165. auto.\nQed.\n\nLemma \u975e\u7a7a\u6709\u7a77\u96c6\u7684\u79e9\u5c42 x : \u975e\u7a7a x \u2192 \u6709\u7a77 x \u2192 \u03c1 x \u2208 \ud835\udcab[\u03c1[x]].\nProof.\n  intros [y yx] Fx. rewrite \u03c1\u7b49\u4e8e\u03c1'. apply \u975e\u7a7a\u6709\u7a77\u94fe\u5c01\u95ed.\n  - exists (\ud835\udcab (\u03c1 y)). now apply \u51fd\u6570\u5f0f\u66ff\u4ee32I.\n  - now repeat apply \u6709\u7a77\u96c6\u5bf9\u51fd\u6570\u5f0f\u66ff\u4ee3\u5c01\u95ed.\n  - intros a [a' [A ->]]%\u51fd\u6570\u5f0f\u66ff\u4ee32E b [b' [B ->]]%\u51fd\u6570\u5f0f\u66ff\u4ee32E.\n    apply \u5c42\u5f31\u7ebf\u5e8f; constructor; apply \u03c1\u89c4\u8303.\nQed.\n\nLemma \u9057\u4f20\u6709\u7a77\u96c6\u7684\u79e9\u5c42\u5728V\u03c9\u91cc x : HF x \u2192 \u03c1 x \u2208 V\u03c9.\nProof.\n  induction 1 as [x Fx _ IH].\n  \u6392\u4e2d (x = \u2205) as [->|[y yx]%\u975e\u7a7aI].\n  - replace (\u03c1 \u2205) with \u2205. apply V\u03c9\u5bf9\u7a7a\u96c6\u5c01\u95ed. now rewrite \u03c1_0.\n  - apply \u975e\u7a7a\u6709\u7a77\u96c6\u7684\u79e9\u5c42 in Fx as H. 2:now exists y.\n    apply \u51fd\u6570\u5f0f\u66ff\u4ee32E in H as [z [zx ->]].\n    apply \u6781\u9650\u5c42\u5bf9\u5e42\u96c6\u5c01\u95ed. apply V\u03c9\u662f\u6781\u9650\u5c42. now apply IH.\nQed.\n\nTheorem V\u03c9\u96c6\u5316HF : V\u03c9 =\u209a HF.\nProof.\n  intros x. split; intros H.\n  - apply V\u03c9\u6210\u5458\u5c5e\u67d0Vn in H as [n H].\n    apply HF\u662f\u6210\u5458\u5c01\u95ed\u7c7b with (V\u2099 n). trivial. apply Vn\u662f\u9057\u4f20\u6709\u7a77\u96c6.\n  - apply \u5c42\u81a8\u80c0 with (\u03c1 x). apply V\u03c9\u662f\u5c42.\n    apply \u03c1\u89c4\u8303. now apply \u9057\u4f20\u6709\u7a77\u96c6\u7684\u79e9\u5c42\u5728V\u03c9\u91cc.\nQed.\n\n(** V\u03c9\u662f\u5b87\u5b99 **)\n\nLemma V\u03c9\u5bf9\u66ff\u4ee3\u5c01\u95ed : \u66ff\u4ee3\u5c01\u95ed V\u03c9.\nProof.\n  intros R a Fun H A. apply V\u03c9\u96c6\u5316HF.\n  apply HF\u662f\u66ff\u4ee3\u5c01\u95ed\u7c7b. trivial. 2: now apply V\u03c9\u96c6\u5316HF.\n  intros x y Rxy xa. apply V\u03c9\u96c6\u5316HF. eapply H; eauto.\nQed.\n\nLemma V\u03c9\u662f\u5b87\u5b99 : V\u03c9 \u2208\u209a \u5b87\u5b99.\nProof.\n  apply \u5b87\u5b99\u7b49\u4ef7\u4e8e\u5bf9\u66ff\u4ee3\u5c01\u95ed\u7684\u975e\u7a7a\u6781\u9650\u5c42. split3.\n  apply V\u03c9\u5bf9\u66ff\u4ee3\u5c01\u95ed. exists \u2205. apply V\u03c9\u5bf9\u7a7a\u96c6\u5c01\u95ed. apply V\u03c9\u662f\u6781\u9650\u5c42.\nQed.\n\nLemma \u65e0\u7a77\u8574\u542b\u5b87\u5b99 : Univ.\nProof. exists V\u03c9. apply V\u03c9\u662f\u5b87\u5b99. Qed.\n\n(** \u6781\u5c0f\u5b87\u5b99 **)\n\nLemma V\u03c9\u4e0d\u5c5e\u4e8eVlt\u03c9 : V\u03c9 \u2209 Vlt\u03c9.\nProof.\n  intros H. apply \u65e0\u7a77 in H as [n H].\n  apply (\u65e0\u5faa\u73af1 (x:=V\u2099 n)). rewrite <- H at 2. apply Vn\u5c5eV\u03c9.\nQed.\n\nLemma Vlt\u03c9\u975e\u7a7a : \u975e\u7a7a Vlt\u03c9.\nProof. exists \u2205. apply \u65e0\u7a77. now exists 0. Qed.\n\nLemma Vlt\u03c9\u662f\u94fe : \u94fe Vlt\u03c9.\nProof.\n  intros x [n ->]%\u65e0\u7a77 y [m ->]%\u65e0\u7a77. apply \u5c42\u5f31\u7ebf\u5e8f; apply Vn\u662f\u5c42.\nQed.\n\nLemma Vlt\u03c9\u662f\u65e0\u7a77\u96c6 : \u00ac \u6709\u7a77 Vlt\u03c9.\nProof.\n  intros H. apply \u975e\u7a7a\u6709\u7a77\u94fe\u5c01\u95ed in H.\n  now apply V\u03c9\u4e0d\u5c5e\u4e8eVlt\u03c9. apply Vlt\u03c9\u975e\u7a7a. apply Vlt\u03c9\u662f\u94fe.\nQed.\n\nLemma \u975e\u7a7a\u6781\u9650\u5c42\u4e0d\u4f4e\u4e8eVlt\u03c9 x : \u975e\u7a7a x \u2192 \u6781\u9650\u5c42 x \u2192 Vlt\u03c9 \u2286 x.\nProof.\n  intros H1 H2 y Y. apply \u65e0\u7a77 in Y as [n ->].\n  induction n as [|n IH].\n  - apply \u975e\u7a7a\u5c42\u5bf9\u7a7a\u96c6\u5c01\u95ed; firstorder.\n  - apply \u6781\u9650\u5c42\u5bf9\u5e42\u96c6\u5c01\u95ed; trivial.\nQed.\n\nLemma \u975e\u7a7a\u6781\u9650\u5c42\u662f\u65e0\u7a77\u96c6 x : \u975e\u7a7a x \u2192 \u6781\u9650\u5c42 x \u2192 \u00ac \u6709\u7a77 x.\nProof.\n  intros H1 H2 H3. apply Vlt\u03c9\u662f\u65e0\u7a77\u96c6.\n  apply \u6709\u7a77\u96c6\u5bf9\u5b50\u96c6\u5c01\u95ed with x; trivial.\n  apply \u975e\u7a7a\u6781\u9650\u5c42\u4e0d\u4f4e\u4e8eVlt\u03c9; trivial.\nQed.\n\nLemma Vn\u662f\u6709\u7a77\u96c6 n : \u6709\u7a77 (V\u2099 n).\nProof. induction n. constructor. now apply \u6709\u7a77\u96c6\u5bf9\u5e42\u96c6\u5c01\u95ed. Qed.\n\nLemma V\u03c9\u53ea\u542b\u6709\u7a77\u96c6 : V\u03c9 \u2286\u209a \u6709\u7a77.\nProof.\n  intros x [n X]%V\u03c9\u6210\u5458\u5c5e\u67d0Vn. destruct n. cbn in X. zf.\n  eapply \u6709\u7a77\u96c6\u5bf9\u5b50\u96c6\u5c01\u95ed with (V\u2099 n). now apply \u5e42\u96c6. apply Vn\u662f\u6709\u7a77\u96c6.\nQed.\n\nLemma \u975e\u7a7a\u6781\u9650\u5c42\u4e0d\u4f4e\u4e8eV\u03c9 x : \u975e\u7a7a x \u2192 \u6781\u9650\u5c42 x \u2192 V\u03c9 \u2286 x.\nProof.\n  intros H1 H2. destruct (\u5c42\u7ebf\u5e8f V\u03c9\u662f\u5c42 (proj1 H2)); trivial.\n  exfalso. eapply \u975e\u7a7a\u6781\u9650\u5c42\u662f\u65e0\u7a77\u96c6; eauto. now apply V\u03c9\u53ea\u542b\u6709\u7a77\u96c6.\nQed.\n\nFact V\u03c9\u662f\u6781\u5c0f\u5b87\u5b99 u : \u5b87\u5b99 u \u2192 V\u03c9 \u2286 u.\nProof. intros H%\u5b87\u5b99\u662f\u975e\u7a7a\u6781\u9650\u5c42. apply \u975e\u7a7a\u6781\u9650\u5c42\u4e0d\u4f4e\u4e8eV\u03c9; firstorder. Qed.\n\nEnd \u65e0\u7a77\u8574\u542b\u5b87\u5b99.\n\nTheorem \u65e0\u7a77\u516c\u7406\u7b49\u4ef7\u4e8e\u5b58\u5728\u5b87\u5b99 (\ud835\udcdc : ZF) : Inf\u2c7d \u2194 Univ.\nProof. split. apply \u65e0\u7a77\u8574\u542b\u5b87\u5b99. apply \u5b87\u5b99\u8574\u542b\u65e0\u7a77. Qed.\n\nRemark \u53cd\u65e0\u7a77\u6a21\u578b\u7b49\u4ef7\u4e8e\u6781\u5c0f\u6a21\u578b (\ud835\udcdc : ZF) : \u00ac Inf\u2c7d \u2194 \u00ac Univ.\nProof. split; intros H1 H2; now apply \u65e0\u7a77\u516c\u7406\u7b49\u4ef7\u4e8e\u5b58\u5728\u5b87\u5b99 in H2. Qed.\n", "meta": {"author": "choukh", "repo": "MetaZF", "sha": "81211540e9307b98f2060a12a5a1ab9bb60a4cbc", "save_path": "github-repos/coq/choukh-MetaZF", "path": "github-repos/coq/choukh-MetaZF/MetaZF-81211540e9307b98f2060a12a5a1ab9bb60a4cbc/ZF/Infinity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.1999984716849534}}
{"text": "Require Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.ZArith.ZArith. Open Scope Z_scope.\nRequire Import Coq.Strings.String. Open Scope string_scope.\nRequire Import coqutil.Byte.\nRequire Import coqutil.Word.Interface coqutil.Word.Properties.\nRequire Import coqutil.Tactics.fwd.\nRequire Import bedrock2.ZnWords.\nRequire Import compiler.SeparationLogic.\nRequire Import Bedrock2Experiments.RiscvMachineWithCavaDevice.ExtraRiscvMachine.\nRequire Import Bedrock2Experiments.RiscvMachineWithCavaDevice.InternalMMIOMachine.\nRequire Import Bedrock2Experiments.IncrementWait.CavaIncrementDevice.\nRequire Import Bedrock2Experiments.IncrementWait.IncrementWaitToRiscV.\nRequire Import Bedrock2Experiments.IncrementWait.IncrementWaitToRiscVProperties.\nRequire Import Bedrock2Experiments.RiscvMachineWithCavaDevice.Bedrock2ToCava.\n\nDefinition binary: list byte := Eval compute in Pipeline.instrencode put_wait_get_asm.\n\nTheorem IncrementWait_end2end_correct: forall p_functions ret_addr mH (Rdata Rexec R: mem -> Prop)\n          (initialL: ExtraRiscvMachine counter_device) input sched,\n    word.unsigned (word.sub stack_pastend stack_start) mod 4 = 0 ->\n    word.unsigned p_functions mod 4 = 0 ->\n    word.unsigned ret_addr mod 4 = 0 ->\n    machine_ok p_functions stack_start stack_pastend binary mH Rdata Rexec initialL ->\n    R mH ->\n    map.get initialL.(getRegs) RegisterNames.a0 = Some input ->\n    map.get initialL.(getRegs) RegisterNames.ra = Some ret_addr ->\n    word.unsigned ret_addr mod 4 = 0 ->\n    initialL.(getLog) = [] ->\n    initialL.(getPc) = word.add p_functions (word.of_Z put_wait_get_relative_pos) ->\n    exists steps_remaining finalL mH',\n      run sched steps_remaining initialL = Some finalL /\\\n      machine_ok p_functions stack_start stack_pastend binary mH' Rdata Rexec finalL /\\\n      R mH' /\\\n      map.get finalL.(getRegs) RegisterNames.a0 = Some (word.add (word.of_Z 1) input) /\\\n      finalL.(getPc) = ret_addr.\nProof.\n  intros.\n  change binary with (Pipeline.instrencode put_wait_get_asm).\n  edestruct bedrock2_and_cava_system_correct with\n      (f_entry_name := \"put_wait_get\")\n      (stack_start := stack_start) (stack_pastend := stack_pastend)\n      (postH := fun m' retvals =>  R m' /\\ retvals = [word.add (word.of_Z 1) input])\n    as (steps_remaining & finalL & mH' & retvals & Rn & GM & A & Eq & M & HP & HL);\n    lazymatch goal with\n    | |- _ mod _ = _ => idtac\n    | |- _ => try eassumption\n    end.\n  { exact funcs_valid. }\n  { apply List.dedup_NoDup_iff. reflexivity. }\n  { exact put_wait_get_compile_result_eq. }\n  { (* check that the compiler emitted valid instructions: *)\n    repeat (apply Forall_cons || apply Forall_nil).\n    all: vm_compute; try intuition discriminate. }\n  { reflexivity. }\n  { vm_compute. discriminate. }\n  { assumption. }\n  { assumption. }\n  { assumption. }\n  { eapply WeakestPreconditionProperties.Proper_call.\n    2: eapply IncrementWaitProperties.put_wait_get_correct.\n    2: eassumption.\n    2: reflexivity.\n    unfold Morphisms.pointwise_relation, Basics.impl.\n    intros. fwd.\n    unfold IncrementWaitSemantics.proc.\n    split. 1: split; [assumption|reflexivity].\n    eexists; split; [eassumption|reflexivity]. }\n  { cbn -[map.get].\n    match goal with\n    | H: map.get _ RegisterNames.a0 = Some input |-\n      match ?x with _ => _ end = _ => replace x with (Some input)\n    end.\n    reflexivity. }\n  { eassumption. }\n  { cbn -[map.get] in GM. fwd. unfold run. do 3 eexists. rewrite Rn. eauto 10. }\nQed.\n\n(* Goal: bring this list down to only standard axioms like functional and propositional extensionality\nPrint Assumptions IncrementWait_end2end_correct.\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/firmware/IncrementWait/IncrementWaitToCava.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.1999737522715656}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv.simplepb Require Export admin.\nFrom Perennial.program_proof.grove_shared Require Import urpc_proof urpc_spec.\nFrom Perennial.goose_lang.lib Require Import waitgroup.\nFrom iris.base_logic Require Export lib.ghost_var mono_nat.\nFrom iris.algebra Require Import dfrac_agree mono_list.\nFrom Perennial.program_proof.simplepb Require Import pb_definitions config_proof pb_setstate_proof pb_getstate_proof pb_becomeprimary_proof pb_makeclerk_proof.\n\nSection config_global.\n\nContext {pb_record:PBRecord}.\nNotation pbG := (pbG (pb_record:=pb_record)).\nNotation OpType := (pb_OpType pb_record).\n\nContext `{!gooseGlobalGS \u03a3}.\nContext `{!configG \u03a3}.\nContext `{!pbG \u03a3}.\n\nDefinition adminN := nroot .@ \"admin\".\n\nDefinition is_conf_inv \u03b3pb \u03b3conf : iProp \u03a3 :=\n  inv adminN (\u2203 epoch conf (conf\u03b3s:list pb_server_names) epoch_lb,\n      \"Hepoch\" \u2237 config_proof.own_epoch \u03b3conf epoch \u2217\n      \"Hconf\" \u2237 own_config \u03b3conf conf \u2217\n      \"#His_conf\" \u2237 is_epoch_config \u03b3pb epoch_lb conf\u03b3s \u2217\n      \"#His_conf_prop\" \u2237 is_epoch_config_proposal \u03b3pb epoch_lb conf\u03b3s \u2217\n      \"#His_hosts\" \u2237 ([\u2217 list] \u03b3srv ; host \u2208 conf\u03b3s ; conf, is_pb_host host \u03b3pb \u03b3srv) \u2217\n      \"#His_lbs\" \u2237 (\u2200 \u03b3srv, \u231c\u03b3srv \u2208 conf\u03b3s\u231d \u2192 pb_ghost.is_epoch_lb \u03b3srv epoch_lb) \u2217\n      \"Hunused\" \u2237 ([\u2217 set] epoch' \u2208 (fin_to_set u64), \u231cint.nat epoch < int.nat epoch'\u231d \u2192 config_proposal_unset \u03b3pb epoch' \u2217 config_unset \u03b3pb epoch' \u2217 own_proposal_unused \u03b3pb epoch' \u2217 own_init_proposal_unused \u03b3pb epoch') \u2217\n      \"Hunset_or_set\" \u2237 (config_unset \u03b3pb epoch \u2228 \u231cint.nat epoch_lb = int.nat epoch\u231d) \u2217\n      \"#His_skip\" \u2237 (\u2200 epoch_skip, \u231cint.nat epoch_lb < int.nat epoch_skip\u231d \u2192 \u231cint.nat epoch_skip < int.nat epoch\u231d \u2192 is_epoch_skipped \u03b3pb epoch_skip)\n      )\n.\n\n(* before calling this lemma, have to already allocate pb ghost state *)\nLemma config_ghost_init_2 \u03b3sys conf conf\u03b3s :\n  ([\u2217 list] \u03b3srv ; host \u2208 conf\u03b3s ; conf, is_pb_host host \u03b3sys \u03b3srv) -\u2217\n  pb_init_config \u03b3sys conf\u03b3s\n  ={\u22a4}=\u2217 \u2203 \u03b3conf, is_conf_inv \u03b3sys \u03b3conf \u2217 makeConfigServer_pre \u03b3conf conf.\nProof.\n  iIntros \"#Hhosts Hinitconf\".\n  iMod (config_ghost_init conf) as (\u03b3conf) \"(Hconfpre & Hepoch & Hconf)\".\n  iExists _; iFrame \"Hconfpre\".\n  iMod (inv_alloc with \"[-]\") as \"$\"; last done.\n  iNext.\n  iExists (U64 0), conf, conf\u03b3s, (U64 0).\n  iFrame.\n  iNamed \"Hinitconf\".\n  iFrame \"\u2217#%\".\n  iSplitR.\n  { iRight. done. }\n  iIntros (???).\n  exfalso.\n  word.\nQed.\n\nEnd config_global.\n\nSection admin_proof.\n\nContext {pb_record:PBRecord}.\nNotation pbG := (pbG (pb_record:=pb_record)).\nNotation OpType := (pb_OpType pb_record).\nNotation has_op_encoding := (pb_has_op_encoding pb_record).\nNotation has_snap_encoding := (pb_has_snap_encoding pb_record).\nNotation compute_reply := (pb_compute_reply pb_record).\n\nNotation wp_Clerk__GetState := (wp_Clerk__GetState (pb_record:=pb_record)).\nNotation wp_Clerk__SetState := (wp_Clerk__SetState (pb_record:=pb_record)).\n\nContext `{!heapGS \u03a3}.\nContext `{!pbG \u03a3}.\nContext `{!configG \u03a3}.\nContext `{!waitgroupG \u03a3}.\n\nDefinition is_conf_host confHost \u03b3pb : iProp \u03a3 :=\n  \u2203 \u03b3conf,\n  config_proof.is_host confHost \u03b3conf \u2217 is_conf_inv \u03b3pb \u03b3conf.\n\nDefinition is_Clerk2 ck \u03b3pb : iProp \u03a3 :=\n  \u2203 \u03b3conf,\n    \"#Hinv\" \u2237 is_conf_inv \u03b3pb \u03b3conf \u2217\n    \"#Hck\" \u2237 is_Clerk ck \u03b3conf.\n\nLemma wp_MakeClerk2 (configHost:u64) \u03b3pb :\n  {{{\n        is_conf_host configHost \u03b3pb\n  }}}\n    config.MakeClerk #configHost\n  {{{\n      ck, RET #ck; is_Clerk2 ck \u03b3pb\n  }}}.\nProof.\n  iIntros (\u03a6) \"#Hhost H\u03a6\".\n  iDestruct \"Hhost\" as (?) \"[Hhost Hinv]\".\n  wp_apply (config_proof.wp_MakeClerk with \"[$Hhost]\").\n  iIntros.\n  iApply \"H\u03a6\".\n  iExists  _; iFrame \"#\".\nQed.\n\nLemma wp_Clerk__GetConfig2 ck \u03b3pb \u03a6 :\n  is_Clerk2 ck \u03b3pb -\u2217\n  \u25a1(\u2200 conf\u03b3s (conf:list u64) config_sl,\n  (is_slice_small config_sl uint64T 1 conf \u2217\n  ([\u2217 list] \u03b3srv ; host \u2208 conf\u03b3s ; conf, is_pb_host host \u03b3pb \u03b3srv) -\u2217\n   \u03a6 (slice_val config_sl)%V\n  )) -\u2217\n  WP config.Clerk__GetConfig #ck {{ \u03a6 }}\n.\nProof.\n  iIntros \"#Hck #H\u03a6\".\n  iNamed \"Hck\".\n  wp_apply (wp_Clerk__GetConfig with \"[$Hck]\").\n  iModIntro.\n  iIntros \"Hlc\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iMod (lc_fupd_elim_later with \"Hlc Hi\") as \"Hi\".\n  iApply fupd_mask_intro.\n  { set_solver. }\n  iIntros \"Hmask\".\n  iNamed \"Hi\".\n  iExists _.\n  iFrame.\n  iIntros \"Hconfig\".\n  iMod \"Hmask\".\n  iMod (\"Hclose\" with \"[-]\").\n  {\n    iNext. iExists _, _, _, _.\n    iFrame \"\u2217#%\".\n  }\n  iModIntro.\n  iIntros (?) \"Hconf\".\n  iApply \"H\u03a6\".\n  iFrame \"\u2217#\".\nQed.\n\nLemma wp_Clerk__GetEpochAndConfig2 ck \u03b3pb \u03a6 :\n  is_Clerk2 ck \u03b3pb -\u2217\n  \u25a1(\u2200 (epoch epoch_lb:u64) conf\u03b3s (conf:list u64) config_sl,\n  (is_slice_small config_sl uint64T 1 conf \u2217\n  config_proposal_unset \u03b3pb epoch \u2217\n  own_proposal_unused \u03b3pb epoch \u2217\n  own_init_proposal_unused \u03b3pb epoch \u2217\n  is_epoch_config \u03b3pb epoch_lb conf\u03b3s \u2217\n  (\u2200 epoch_skip, \u231cint.nat epoch_lb < int.nat epoch_skip\u231d \u2192 \u231cint.nat epoch_skip < int.nat epoch\u231d \u2192 is_epoch_skipped \u03b3pb epoch_skip) \u2217\n  ([\u2217 list] \u03b3srv ; host \u2208 conf\u03b3s ; conf, is_pb_host host \u03b3pb \u03b3srv) \u2217\n  (\u2200 \u03b3srv, \u231c\u03b3srv \u2208 conf\u03b3s\u231d \u2192 pb_ghost.is_epoch_lb \u03b3srv epoch_lb)) -\u2217\n   \u03a6 (#epoch, slice_val config_sl)%V\n  ) -\u2217\n  WP config.Clerk__GetEpochAndConfig #ck {{ \u03a6 }}\n.\nProof.\n  iIntros \"#Hck #H\u03a6\".\n  iNamed \"Hck\".\n  wp_apply (wp_Clerk__GetEpochAndConfig with \"[$Hck]\").\n  iModIntro.\n  iIntros \"Hlc\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iMod (lc_fupd_elim_later with \"Hlc Hi\") as \"Hi\".\n  iApply fupd_mask_intro.\n  { set_solver. }\n  iIntros \"Hmask\".\n  iNamed \"Hi\".\n  iExists _, _.\n  iFrame.\n  iIntros \"%Hno_overflow Hepoch Hconf\".\n  iMod \"Hmask\".\n\n  (* Hunset becomes skipped, and the first unused becomes unset. *)\n  iDestruct (big_sepS_elem_of_acc_impl (word.add epoch (U64 1)) with \"Hunused\") as \"[Hunset_new Hunused]\".\n  { set_solver. }\n\n  iSpecialize (\"Hunset_new\" with \"[]\").\n  { done. }\n  iDestruct \"Hunset_new\" as \"(Hunset_new & Hunset_new2 & Hprop)\".\n\n  iDestruct \"Hunset_or_set\" as \"[Hunset|%Hset]\".\n  {\n    iMod (own_update with \"Hunset\") as \"Hskip1\".\n    {\n      apply singleton_update.\n      apply dfrac_agree_persist.\n    }\n    iDestruct \"Hskip1\" as \"#Hskip1\".\n\n    iMod (\"Hclose\" with \"[Hunset_new2 Hunused Hepoch Hconf]\").\n    {\n      iNext. iExists _, _, _, _.\n      iFrame \"\u2217#\".\n      iSplitL \"Hunused\".\n      {\n        iApply \"Hunused\".\n        {\n          iModIntro.\n          iIntros (???) \"H\". iIntros.\n          iApply \"H\".\n          iPureIntro.\n          word.\n        }\n        {\n          iIntros. exfalso. word.\n        }\n      }\n      iIntros (???).\n      assert (int.nat epoch_skip = int.nat epoch \u2228 int.nat epoch_skip < int.nat epoch \u2228 int.nat epoch_skip >= int.nat (word.add epoch (U64 1))) as Hineq.\n      { word. }\n      destruct Hineq as [Heq|[Hineq|Hineq]].\n      {\n        replace (epoch_skip) with (epoch) by word.\n        iFrame \"Hskip1\".\n      }\n      {\n        iApply \"His_skip\".\n        { done. }\n        { done. }\n      }\n      { exfalso. word. }\n    }\n    iModIntro.\n    iIntros.\n    iApply \"H\u03a6\".\n    iDestruct \"Hprop\" as \"[$ $]\".\n    iFrame \"\u2217#\".\n\n    (* TODO: repetetive proof *)\n    iIntros.\n    assert (int.nat epoch_skip = int.nat epoch \u2228 int.nat epoch_skip < int.nat epoch \u2228 int.nat epoch_skip >= int.nat (word.add epoch (U64 1))) as Hineq.\n    { word. }\n    destruct Hineq as [Heq|[Hineq|Hineq]].\n    {\n      replace (epoch_skip) with (epoch) by word.\n      iFrame \"Hskip1\".\n    }\n    {\n      iApply \"His_skip\".\n      { done. }\n      { done. }\n    }\n    { exfalso. word. }\n  }\n  {\n    iClear \"His_skip\".\n\n    iMod (\"Hclose\" with \"[Hunset_new2 Hunused Hepoch Hconf]\").\n    {\n      iNext. iExists _, _, _, _.\n      iFrame \"\u2217#\".\n      iSplitL \"Hunused\".\n      {\n        iApply \"Hunused\".\n        {\n          iModIntro.\n          iIntros (???) \"H\". iIntros.\n          iApply \"H\".\n          iPureIntro.\n          word.\n        }\n        {\n          iIntros. exfalso. word.\n        }\n      }\n      iIntros (???).\n      exfalso.\n      rewrite Hset in H.\n      replace (int.nat (word.add epoch 1%Z)) with (int.nat epoch + 1) in H0 by word.\n      word.\n    }\n    iModIntro.\n    iIntros.\n    iApply \"H\u03a6\".\n    iDestruct \"Hprop\" as \"[$ $]\".\n    iFrame \"\u2217#\".\n    iIntros (???).\n    exfalso.\n    rewrite Hset in H.\n    replace (int.nat (word.add epoch 1%Z)) with (int.nat epoch + 1) in H0 by word.\n    word.\n  }\nQed.\n\nLemma wp_Clerk__WriteConfig2 ck \u03b3pb \u03a6 config_sl conf conf\u03b3 epoch :\n  is_Clerk2 ck \u03b3pb -\u2217\n  is_slice_small config_sl uint64T 1 conf -\u2217\n  is_epoch_config_proposal \u03b3pb epoch conf\u03b3 -\u2217\n  ([\u2217 list] \u03b3srv ; host \u2208 conf\u03b3 ; conf, is_pb_host host \u03b3pb \u03b3srv) -\u2217\n  (\u2200 \u03b3srv, \u231c\u03b3srv \u2208 conf\u03b3\u231d \u2192 pb_ghost.is_epoch_lb \u03b3srv epoch) -\u2217\n  \u25a1 (\u2200 (err:u64),\n      (if (decide (err = U64 0)) then\n        is_epoch_config \u03b3pb epoch conf\u03b3\n      else\n        True) -\u2217\n      is_slice_small config_sl uint64T 1 conf -\u2217\n      \u03a6 #err)\n  -\u2217\n  WP config.Clerk__WriteConfig #ck #epoch (slice_val config_sl) {{ \u03a6 }}\n.\nProof.\n  iIntros \"#Hck Hsl #Hconf_prop #Hhosts #Hlbs #H\u03a6\".\n  iNamed \"Hck\".\n  wp_apply (wp_Clerk__WriteConfig with \"Hck Hsl\"); last first.\n  {\n    iIntros.\n    iApply (\"H\u03a6\" with \"[] [$]\").\n    destruct (decide _).\n    { exfalso. done. }\n    done.\n  }\n  iModIntro.\n  iIntros \"Hlc\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iMod (lc_fupd_elim_later with \"Hlc Hi\") as \"Hi\".\n  iApply fupd_mask_intro.\n  { set_solver. }\n  iIntros \"Hmask\".\n  iNamed \"Hi\".\n  iExists _.\n  iFrame \"\u2217\".\n  destruct (decide (_)); last first.\n  { (* write failed because of stale epoch. *)\n    iIntros \"Hepoch\".\n    iMod \"Hmask\" as \"_\".\n    iMod (\"Hclose\" with \"[Hepoch Hconf Hunused Hunset_or_set]\").\n    {\n      iNext.  iExists _, _, _, _.\n      iFrame \"\u2217#\".\n    }\n    iModIntro.\n    iIntros (??) \"Hsl\".\n    wp_pures.\n    iApply (\"H\u03a6\" with \"[] Hsl\").\n    destruct (decide (_)).\n    { exfalso. done. }\n    done.\n  }\n  { (* successful write *)\n    rewrite e.\n    iExists _.\n    iFrame.\n    iIntros \"Hconf Hepoch\".\n    iMod \"Hmask\" as \"_\".\n\n    iDestruct \"Hunset_or_set\" as \"[Hunset|%Hset]\"; last first.\n    { (* config was already set before *)\n      replace (epoch) with (epoch_lb) by word.\n      iDestruct \"Hconf_prop\" as \"[Hconf_prop %Hle]\".\n      iDestruct \"His_conf_prop\" as \"[His_conf_prop _]\".\n      iDestruct (own_valid_2 with \"His_conf_prop Hconf_prop\") as %Hvalid.\n      rewrite singleton_op in Hvalid.\n      rewrite singleton_valid in Hvalid.\n      rewrite dfrac_agree_op_valid in Hvalid.\n      replace conf\u03b3 with conf\u03b3s in * by naive_solver.\n\n      iMod (\"Hclose\" with \"[Hepoch Hconf Hunused]\").\n      {\n        iNext.  iExists _, _, _, _.\n        iFrame \"\u2217#\".\n        iSplitL; first done.\n        by iRight.\n      }\n      iApply \"H\u03a6\".\n      iModIntro.\n      iFrame \"#\".\n    }\n    { (* config is being set for the first time *)\n      iMod (own_update with \"Hunset\") as \"Hset\".\n      {\n        apply singleton_update.\n        apply cmra_update_exclusive.\n        instantiate (1:=(to_dfrac_agree (DfracOwn 1) ((Some conf\u03b3) : (leibnizO _)))).\n        done.\n      }\n      iMod (own_update with \"Hset\") as \"Hset\".\n      { apply singleton_update. apply dfrac_agree_persist. }\n      iDestruct \"Hset\" as \"#Hset\".\n      iMod (\"Hclose\" with \"[Hconf Hepoch Hunused]\").\n      {\n        iNext. iExists _, _, _, _.\n        iFrame \"\u2217#\".\n        iDestruct \"Hconf_prop\" as \"[_ %Hineq]\".\n        iSplitR; first done.\n        iSplitL.\n        { by iRight. }\n        iIntros (???).\n        exfalso.\n        word.\n      }\n      iApply \"H\u03a6\".\n      iDestruct \"Hconf_prop\" as \"[_ %Hineq]\".\n      iFrame \"#\".\n      done.\n    }\n  }\nQed.\n\nLemma wp_Reconfig \u03b3 (configHost:u64) (servers:list u64) (servers_sl:Slice.t) server_\u03b3s :\n  {{{\n        \"Hservers_sl\" \u2237 is_slice servers_sl uint64T 1 servers \u2217\n        \"#Hhost\" \u2237 ([\u2217 list] \u03b3srv ; host \u2208 server_\u03b3s ; servers, is_pb_host host \u03b3 \u03b3srv) \u2217\n        \"#Hconf_host\" \u2237 is_conf_host configHost \u03b3\n  }}}\n    EnterNewConfig #configHost (slice_val servers_sl)\n  {{{\n        (err:u64), RET #err; True\n  }}}.\nProof using waitgroupG0.\n  iIntros (\u03a6) \"Hpre H\u03a6\".\n  iNamed \"Hpre\".\n  wp_call.\n\n  wp_apply (wp_slice_len).\n  wp_pures.\n  iDestruct (is_slice_sz with \"Hservers_sl\") as %Hservers_sz.\n  wp_if_destruct.\n  {\n    by iApply \"H\u03a6\".\n  }\n\n  wp_apply (wp_MakeClerk2 with \"Hconf_host\").\n  iIntros (ck) \"#Hck\".\n  wp_pures.\n  wp_bind (Clerk__GetEpochAndConfig _).\n  iApply (wp_frame_wand with \"[H\u03a6 Hservers_sl]\").\n  { iNamedAccu. }\n  wp_apply (wp_Clerk__GetEpochAndConfig2 with \"[$Hck]\").\n  iModIntro.\n  iIntros (?????) \"Hpost1\".\n  iNamed 1.\n  wp_pures.\n  unfold prelude.Data.randomUint64.\n  wp_pures.\n  set (s:=(u64_instance.u64.(word.add) (U64 0) (U64 1))).\n  generalize s as randId.\n  clear s.\n  intros randId.\n  wp_apply (wp_slice_len).\n  wp_pures.\n\n  iDestruct \"Hpost1\" as \"(Hconf_sl & Hconf_unset & Hprop & Hinit & #His_conf & #Hskip & #His_hosts & #Hlb)\".\n\n  iAssert (\u231clength conf \u2260 0\u231d)%I as %Hold_conf_ne.\n  {\n    iDestruct \"His_conf\" as \"[_ %Hconf\u03b3_nz]\".\n    iDestruct (big_sepL2_length with \"His_hosts\") as %Heq.\n    iPureIntro.\n    lia.\n  }\n  iDestruct (is_slice_small_sz with \"Hconf_sl\") as %Hconf_len.\n  set (oldNodeId:=word.modu randId config_sl.(Slice.sz)).\n  assert (int.nat oldNodeId < length conf) as Hlookup_conf.\n  { rewrite Hconf_len.\n    unfold oldNodeId.\n    enough (int.Z randId `mod` int.Z config_sl.(Slice.sz) < int.Z config_sl.(Slice.sz))%Z.\n    { word. }\n    apply Z.mod_pos_bound.\n    word.\n  }\n  apply lookup_lt_is_Some_2 in Hlookup_conf as [host Hlookup_conf].\n  wp_apply (wp_SliceGet with \"[$Hconf_sl]\").\n  { done. }\n  iIntros \"Hconf_sl\".\n  simpl.\n  (* FIXME: how does wp_MakeClerk work here? *)\n  iDestruct (big_sepL2_lookup_2_some with \"His_hosts\") as %HH.\n  { done. }\n  destruct HH as [\u03b3srv_old Hconf\u03b3_lookup].\n  wp_apply (wp_MakeClerk with \"[]\").\n  {\n    iDestruct (big_sepL2_lookup_acc with \"His_hosts\") as \"[$ _]\"; done.\n  }\n  iIntros (oldClerk) \"#HoldClerk\".\n  wp_pures.\n\n  (* Get the old state *)\n  wp_apply (wp_allocStruct).\n  { naive_solver. }\n  iIntros (args) \"Hargs\".\n  iDestruct (struct_fields_split with \"Hargs\") as \"HH\".\n  iNamed \"HH\".\n  wp_apply (wp_Clerk__GetState with \"[$HoldClerk $Epoch]\").\n  {\n    iApply \"Hlb\".\n    iPureIntro.\n    eapply elem_of_list_lookup_2.\n    done.\n  }\n  iIntros (reply err) \"Hpost\".\n  wp_pures.\n  destruct (decide (err = _)); last first.\n  { (* err \u2260 0; error. *)\n    iNamed \"Hpost\".\n    wp_loadField.\n    wp_pures.\n    rewrite bool_decide_false; last naive_solver.\n    wp_pures.\n    wp_loadField.\n    simpl.\n    iApply \"H\u03a6\".\n    done.\n  }\n  (* err = 0; keep going with reconfig *)\n  (* Got the old state now *)\n  iDestruct \"Hpost\" as (???) \"(%Hepoch_lb_ineq & %Hepoch_ub_ineq & #Hacc_ro & #Hprop_facts & #Hprop_lb & Hreply & %Henc & %Hlen_no_overflow)\".\n  destruct (decide (int.nat epochacc = int.nat epoch)) as [Heq|Hepochacc_ne_epoch].\n  {\n    replace (epochacc) with (epoch) by word.\n    iDestruct (own_valid_2 with \"Hprop Hprop_lb\") as %Hvalid.\n    exfalso.\n    rewrite singleton_op singleton_valid in Hvalid.\n    rewrite auth_map.Cinl_Cinr_op in Hvalid.\n    done.\n  }\n  iMod (ghost_init_primary with \"Hprop_lb Hprop_facts His_conf Hacc_ro Hskip Hprop Hinit\") as \"(Hprop & #Hprop_facts2 & #Hinit)\".\n  { by eapply elem_of_list_lookup_2. }\n  { word. }\n  { word. }\n\n  iNamed \"Hreply\".\n  wp_loadField.\n  simpl.\n  wp_pures.\n\n  wp_apply (wp_slice_len).\n  wp_apply (wp_NewSlice).\n  iIntros (clerks_sl) \"Hclerks_sl\".\n  wp_pures.\n\n  iDestruct (is_slice_to_small with \"Hservers_sl\") as \"Hservers_sl\".\n  rewrite -Hservers_sz.\n  iDestruct (is_slice_to_small with \"Hclerks_sl\") as \"Hclerks_sl\".\n  iDestruct (is_slice_small_sz with \"Hclerks_sl\") as %Hclerks_sz.\n  rewrite replicate_length in Hclerks_sz.\n  simpl.\n  wp_apply (wp_ref_to).\n  { eauto. }\n  iIntros (i_ptr) \"Hi\".\n  wp_pures.\n\n  (* weaken to loop invariant *)\n  iAssert (\n        \u2203 (i:u64) clerksComplete clerksLeft,\n          \"Hi\" \u2237 i_ptr \u21a6[uint64T] #i \u2217\n          \"%HcompleteLen\" \u2237 \u231clength clerksComplete = int.nat i\u231d \u2217\n          \"%Hlen\" \u2237 \u231clength (clerksComplete ++ clerksLeft) = length servers\u231d \u2217\n          \"Hclerks_sl\" \u2237 is_slice_small clerks_sl ptrT 1 (clerksComplete ++ clerksLeft) \u2217\n          \"Hservers_sl\" \u2237 is_slice_small servers_sl uint64T 1 servers \u2217\n          \"#Hclerks_is\" \u2237 ([\u2217 list] ck ; \u03b3srv \u2208 clerksComplete ; (take (length clerksComplete) server_\u03b3s),\n                              pb_definitions.is_Clerk ck \u03b3 \u03b3srv\n                              )\n          )%I with \"[Hclerks_sl Hservers_sl Hi]\" as \"HH\".\n  {\n    iExists _, [], _.\n    simpl.\n    iFrame \"\u2217#\".\n    iPureIntro.\n    split; first word.\n    apply replicate_length.\n  }\n  wp_forBreak_cond.\n\n  wp_pures.\n  iNamed \"HH\".\n  wp_load.\n  wp_apply (wp_slice_len).\n  wp_pures.\n  clear host Hlookup_conf.\n  wp_if_destruct.\n  { (* loop not finished *)\n    wp_pures.\n    wp_load.\n    assert (int.nat i < length servers) as Hlookup.\n    { word. }\n    apply list_lookup_lt in Hlookup as [host Hlookup].\n    wp_apply (wp_SliceGet with \"[$Hservers_sl]\").\n    { done. }\n\n    iIntros \"Hserver_sl\".\n\n    iDestruct (big_sepL2_lookup_2_some with \"Hhost\") as %HH.\n    { done. }\n    destruct HH as [\u03b3srv Hserver_\u03b3s_lookup].\n    wp_apply (wp_MakeClerk with \"[]\").\n    {\n      iDestruct (big_sepL2_lookup_acc with \"Hhost\") as \"[$ _]\"; done.\n    }\n    iIntros (pbCk) \"#HpbCk\".\n    wp_load.\n    wp_apply (wp_SliceSet (V:=loc) with \"[Hclerks_sl]\").\n    {\n      iFrame \"Hclerks_sl\".\n      iPureIntro.\n      apply list_lookup_lt.\n      word.\n    }\n    iIntros \"Hclerks_sl\".\n    wp_load.\n    wp_store.\n    iLeft.\n    iModIntro.\n    iSplitR; first done.\n    iFrame \"\u2217#\".\n    iExists _, _, _.\n    iFrame \"\u2217\".\n    instantiate (1:=clerksComplete ++ [pbCk]).\n    iSplitR.\n    {\n      iPureIntro.\n      rewrite app_length.\n      simpl.\n      word.\n    }\n    instantiate (2:=tail clerksLeft).\n    destruct clerksLeft.\n    {\n      exfalso.\n      rewrite app_nil_r in Hlen.\n      word.\n    }\n\n    iSplitR.\n    {\n      iPureIntro.\n      rewrite app_length.\n      rewrite app_length.\n      simpl.\n      rewrite -Hlen.\n      rewrite app_length.\n      simpl.\n      word.\n    }\n    iSplitL.\n    {\n      iApply to_named.\n      iExactEq \"Hclerks_sl\".\n      {\n        f_equal.\n        simpl.\n        rewrite -HcompleteLen.\n        replace (length _) with (length clerksComplete + 0) by lia.\n        rewrite insert_app_r.\n        simpl.\n        rewrite -app_assoc.\n        f_equal.\n      }\n    }\n    rewrite app_length.\n    simpl.\n    iDestruct (big_sepL2_length with \"Hhost\") as %Hserver_len_eq.\n    rewrite take_more; last first.\n    { lia. }\n\n    iApply (big_sepL2_app with \"Hclerks_is []\").\n\n    replace (take 1 (drop (_) server_\u03b3s)) with ([\u03b3srv]); last first.\n    {\n      apply ListSolver.list_eq_bounded.\n      {\n        simpl.\n        rewrite take_length.\n        rewrite drop_length.\n        word.\n      }\n      intros.\n      rewrite list_lookup_singleton.\n      destruct i0; last first.\n      {\n        exfalso. simpl in *. word.\n      }\n      rewrite lookup_take; last first.\n      { word. }\n      rewrite lookup_drop.\n      rewrite HcompleteLen.\n      rewrite -Hserver_\u03b3s_lookup.\n      f_equal.\n      word.\n      (* TODO: list_solver. *)\n    }\n    iApply big_sepL2_singleton.\n    iFrame \"#\".\n  }\n  (* done with for loop *)\n  iRight.\n  iSplitR; first done.\n  iModIntro.\n  assert (int.nat i = length servers) as Hi_done.\n  {\n    rewrite Hclerks_sz.\n    rewrite app_length in Hlen.\n    word.\n  }\n\n  wp_pures.\n  replace (clerksLeft) with ([] : list loc) in *; last first.\n  {\n    (* TODO: list_solver. pure fact *)\n    enough (length clerksLeft = 0).\n    {\n      symmetry.\n      apply nil_length_inv.\n      done.\n    }\n    rewrite app_length in Hlen.\n    word.\n  }\n  wp_apply (wp_NewWaitGroup_free).\n  iIntros (wg) \"Hwg\".\n  wp_pures.\n  wp_apply (wp_slice_len).\n\n  wp_apply (wp_new_slice). (* XXX: untyped *)\n  { done. }\n  clear err e.\n  iIntros (errs_sl) \"Herrs_sl\".\n  iDestruct (slice.is_slice_sz with \"Herrs_sl\") as \"%Herrs_sz\".\n  wp_pures.\n  wp_store.\n  wp_pures.\n\n  rewrite app_nil_r.\n  rename clerksComplete into clerks.\n  iApply fupd_wp.\n  iMod (fupd_mask_subseteq (\u2191adminN)) as \"Hmask\".\n  { set_solver. }\n  set (P:= (\u03bb i, \u2203 (err:u64) \u03b3srv',\n      \u231cserver_\u03b3s !! int.nat i = Some \u03b3srv'\u231d \u2217\n        readonly ((errs_sl.(Slice.ptr) +\u2097[uint64T] int.Z i)\u21a6[uint64T] #err) \u2217\n        \u25a1 if (decide (err = U64 0)) then\n            pb_ghost.is_epoch_lb \u03b3srv' epoch\n          else\n            True\n  )%I : u64 \u2192 iProp \u03a3).\n  iMod (free_WaitGroup_alloc adminN _ P with \"Hwg\") as (\u03b3wg) \"Hwg\".\n  iMod \"Hmask\" as \"_\".\n  iModIntro.\n\n  (* iMod (readonly_alloc_1 with \"Hreply_epoch\") as \"#Hreply_epoch\". *)\n  iMod (readonly_alloc_1 with \"Hreply_state\") as \"#Hreply_state\".\n  iMod (readonly_alloc_1 with \"Hreply_next_index\") as \"#Hreply_next_index\".\n  iDestruct \"Hreply_state_sl\" as \"#Hreply_state_sl\".\n\n  (* weaken to loop invariant *)\n  iAssert (\n        \u2203 (i:u64),\n          \"Hi\" \u2237 i_ptr \u21a6[uint64T] #i \u2217\n          \"%Hi_ineq\" \u2237 \u231cint.nat i \u2264 length clerks\u231d \u2217\n          \"Herrs\" \u2237 (errs_sl.(Slice.ptr) +\u2097[uint64T] int.Z i)\u21a6\u2217[uint64T] (replicate (int.nat clerks_sl.(Slice.sz)- int.nat i) #0) \u2217\n          \"Hwg\" \u2237 own_WaitGroup adminN wg \u03b3wg i P\n          )%I with \"[Herrs_sl Hi Hwg]\" as \"HH\".\n  {\n    unfold is_slice.\n    unfold slice.is_slice. unfold slice.is_slice_small.\n    clear Hlen.\n    iDestruct \"Herrs_sl\" as \"[[Herrs_sl %Hlen] _]\".\n    destruct Hlen as [Hlen _].\n    iExists _; iFrame.\n    iSplitR; first iPureIntro.\n    { word. }\n    simpl.\n    replace (1 * int.Z _)%Z with (0%Z) by word.\n    rewrite loc_add_0.\n    replace (int.nat _ - int.nat 0) with (int.nat clerks_sl.(Slice.sz)) by word.\n    iFrame \"Herrs_sl\".\n  } (* FIXME: copy/pasted from pb_apply_proof *)\n  wp_forBreak_cond.\n\n  clear i HcompleteLen Heqb0 Hi_done.\n  iNamed \"HH\".\n  wp_load.\n  wp_apply (wp_slice_len).\n  wp_pures.\n\n  iDestruct (ghost_get_propose_lb with \"Hprop\") as \"#Hprop_lb2\".\n  wp_if_destruct.\n  { (* loop continues *)\n    wp_pures.\n    wp_apply (wp_WaitGroup__Add with \"[$Hwg]\").\n    { word. }\n    iIntros \"[Hwg Hwg_tok]\".\n    wp_pures.\n    wp_load.\n\n    assert (int.nat i < int.nat clerks_sl.(Slice.sz)) as Hlookup by word.\n    rewrite -Hclerks_sz in Hlookup.\n    rewrite app_nil_r in Hlen.\n    rewrite -Hlen in Hlookup.\n    apply list_lookup_lt in Hlookup as [pbCk Hlookup].\n    wp_apply (wp_SliceGet with \"[$Hclerks_sl]\").\n    { done. }\n    iIntros \"Hclerks_sl\".\n\n    wp_pures.\n\n    replace (int.nat clerks_sl.(Slice.sz) - int.nat i) with (S (int.nat clerks_sl.(Slice.sz) - (int.nat (word.add i 1)))) by word.\n    rewrite replicate_S.\n    iDestruct (array_cons with \"Herrs\") as \"[Herr_ptr Herr_ptrs]\".\n    wp_load.\n    wp_pures.\n\n    iDestruct (own_WaitGroup_to_is_WaitGroup with \"[Hwg]\") as \"#His_wg\".\n    { by iExactEq \"Hwg\". }\n    wp_apply (wp_fork with \"[Hwg_tok Herr_ptr]\").\n    {\n      iNext.\n      wp_pures.\n      wp_loadField.\n      wp_loadField.\n      wp_apply (wp_allocStruct).\n      { repeat econstructor. done. }\n      iIntros (args_ptr) \"Hargs\".\n      iDestruct (struct_fields_split with \"Hargs\") as \"HH\".\n      iNamed \"HH\".\n\n      iDestruct (big_sepL2_lookup_1_some with \"Hclerks_is\") as %[\u03b3srv Hlookup2].\n      { done. }\n      iDestruct (big_sepL2_lookup_acc with \"Hclerks_is\") as \"[HH _]\".\n      { done. }\n      { done. }\n      wp_apply (wp_Clerk__SetState with \"[Epoch NextIndex State]\").\n      {\n        iFrame \"\u2217#\".\n        iSplitR.\n        {\n          iPureIntro.\n          done.\n        }\n        iSplitR.\n        {\n          iPureIntro.\n          done.\n        }\n        iExists _.\n        iFrame \"\u2217#\".\n      }\n      iIntros (err) \"#Hpost\".\n\n      unfold SliceSet.\n      unfold slice.ptr.\n      wp_pures.\n      wp_store.\n\n      iMod (readonly_alloc_1 with \"Herr_ptr\") as \"#Herr_ptr\".\n      wp_apply (wp_WaitGroup__Done with \"[$Hwg_tok $His_wg]\").\n      {\n        rewrite lookup_take_Some in Hlookup2.\n        destruct Hlookup2 as [Hlookup2 _].\n        iModIntro.\n        unfold P.\n        iExists _, _.\n        iSplitL; first done.\n        iFrame \"#\".\n      }\n      done.\n    }\n    wp_pures.\n    wp_load.\n    wp_store.\n\n    (* re-establish loop invariant *)\n    iModIntro.\n    iLeft.\n    iSplitR; first done.\n    iFrame \"\u2217\".\n    iExists _.\n    iFrame \"\u2217#\".\n    iSplitR.\n    { iPureIntro. word. }\n    iApply to_named.\n    iExactEq \"Herr_ptrs\".\n    f_equal.\n    rewrite loc_add_assoc.\n    f_equal.\n    simpl.\n    replace (int.Z (word.add i 1%Z)) with (int.Z i + 1)%Z by word.\n    word.\n  }\n  (* loop completed *)\n  iModIntro.\n  iRight.\n  iSplitR; first done.\n\n  wp_pures.\n  wp_apply (wp_WaitGroup__Wait with \"[$Hwg]\").\n  iIntros \"#Hwg_post\".\n  wp_pures.\n  replace (int.nat i) with (length clerks); last first.\n  {\n    rewrite app_nil_r in Hlen.\n    word.\n  }\n\n  wp_apply (wp_ref_to).\n  { eauto. }\n  iIntros (err_ptr) \"Herr\".\n  wp_pures.\n  wp_store.\n  wp_pures.\n\n  (* FIXME: *)\n  (* This was copy/pasted and modified from apply_proof *)\n  iAssert (\u2203 (i err:u64),\n              \"Hj\" \u2237 i_ptr \u21a6[uint64T] #i \u2217\n              \"%Hj_ub\" \u2237 \u231cint.nat i \u2264 length clerks\u231d \u2217\n              \"Herr\" \u2237 err_ptr \u21a6[uint64T] #err \u2217\n              \"#Hrest\" \u2237 \u25a1 if (decide (err = (U64 0)%Z)) then\n                (\u2200 (k:u64) \u03b3srv, \u231cint.nat k < int.nat i\u231d -\u2217 \u231cserver_\u03b3s !! (int.nat k) = Some \u03b3srv\u231d -\u2217 pb_ghost.is_epoch_lb \u03b3srv epoch)\n              else\n                True\n          )%I with \"[Hi Herr]\" as \"Hloop\".\n  {\n    iExists _, _.\n    iFrame \"\u2217\".\n    iSplitL.\n    { iPureIntro. word. }\n    iModIntro.\n    destruct (decide (_)); last first.\n    { done. }\n    iIntros.\n    exfalso. replace (int.nat 0%Z) with 0 in H by word.\n    word.\n  }\n\n  iClear \"Herrs\".\n  wp_forBreak_cond.\n  iNamed \"Hloop\".\n  wp_pures.\n  wp_load.\n  wp_apply (wp_slice_len).\n\n  rewrite replicate_length in Herrs_sz.\n  rewrite -Hclerks_sz in Herrs_sz.\n  rewrite app_nil_r in Hlen.\n\n  clear i Hi_ineq Heqb0.\n  wp_if_destruct.\n  { (* one loop iteration *)\n    wp_pures.\n    wp_load.\n    unfold SliceGet.\n    wp_call.\n    iDestruct (big_sepS_elem_of_acc _ _ i0 with \"Hwg_post\") as \"[HH _]\".\n    { set_solver. }\n\n    assert (int.nat i0 < int.nat errs_sl.(Slice.sz)) by word.\n\n    iDestruct \"HH\" as \"[%Hbad|HH]\".\n    { exfalso.\n      rewrite -Herrs_sz in H.\n      word.\n    }\n    iDestruct \"HH\" as (??) \"(%HbackupLookup & Herr2 & Hpost)\".\n    wp_apply (wp_slice_ptr).\n    wp_pure1.\n    iEval (simpl) in \"Herr2\".\n    iMod (readonly_load with \"Herr2\") as (?) \"Herr3\".\n    wp_load.\n    wp_pures.\n    destruct (bool_decide (_)) as [] eqn:Herr; wp_pures.\n    {\n      rewrite bool_decide_eq_true in Herr.\n      replace (err0) with (U64 0%Z) by naive_solver.\n      wp_pures.\n      wp_load; wp_store.\n      iLeft.\n      iModIntro.\n      iSplitL \"\"; first done.\n      iFrame \"\u2217\".\n      iExists _, _.\n      iFrame \"Hj Herr\".\n      iSplitL \"\".\n      { iPureIntro. word. }\n      iModIntro.\n      destruct (decide (err = 0%Z)).\n      {\n        iIntros.\n        assert (int.nat k < int.nat i0 \u2228 int.nat k = int.nat i0) as [|].\n        {\n          replace (int.nat (word.add i0 1%Z)) with (int.nat i0 + 1) in * by word.\n          word.\n        }\n        {\n          by iApply \"Hrest\".\n        }\n        {\n          destruct (decide (_)); last by exfalso.\n          replace (\u03b3srv') with (\u03b3srv); last first.\n          {\n            replace (int.nat i0) with (int.nat k) in * by word.\n            naive_solver.\n          }\n          iDestruct \"Hpost\" as \"#$\".\n        }\n      }\n      {\n        done.\n      }\n    }\n    {\n      wp_store.\n      wp_pures.\n      wp_load; wp_store.\n      iLeft.\n      iModIntro.\n      iSplitL \"\"; first done.\n      iFrame \"\u2217\".\n      iExists _, _.\n      iFrame \"Hj Herr\".\n      destruct (decide (err0 = _)).\n      { exfalso. naive_solver. }\n      iPureIntro.\n      split; last done.\n      word.\n    }\n  }\n  iRight.\n  iModIntro.\n  iSplitL \"\"; first done.\n  wp_pures.\n  wp_load.\n  wp_pures.\n  (* FIXME: *)\n  (* End copy/paste from apply_proof *)\n\n  wp_if_destruct.\n  { (* got some error *)\n    wp_load.\n    iApply \"H\u03a6\".\n    done.\n  }\n\n  (* no errors *)\n  replace (int.nat i0) with (length clerks); last first.\n  { word. }\n\n  destruct (decide (_)); last first.\n  { exfalso. done. }\n\n  iMod (own_update with \"Hconf_unset\") as \"Hconf_prop\".\n  {\n    apply singleton_update.\n    apply cmra_update_exclusive.\n    instantiate (1:=(to_dfrac_agree (DfracOwn 1) ((Some server_\u03b3s) : (leibnizO _)))).\n    done.\n  }\n  iMod (own_update with \"Hconf_prop\") as \"Hconf_prop\".\n  {\n    apply singleton_update.\n    apply dfrac_agree_persist.\n  }\n  iDestruct \"Hconf_prop\" as \"#Hconf_prop\".\n\n  wp_bind (Clerk__WriteConfig _ _ _).\n  iApply (wp_frame_wand with \"[H\u03a6 Hconf_sl Hprop Hclerks_sl]\").\n  { iNamedAccu. }\n  iDestruct (big_sepL2_length with \"Hhost\") as %Hserver_len_eq.\n\n  assert (length servers > 0) as Hserver_nz.\n  {\n    assert (length servers \u2260 0 \u2228 length servers = 0) as [|Hbad] by word.\n    { word. }\n    {\n      exfalso.\n      rewrite Hbad in Hservers_sz.\n      apply u64_nat_0 in Hservers_sz.\n      rewrite Hservers_sz in Heqb.\n      done.\n    }\n  }\n\n  wp_apply (wp_Clerk__WriteConfig2 with \"Hck Hservers_sl [$Hconf_prop] Hhost\").\n  {\n    iPureIntro.\n    word.\n  }\n  {\n    iIntros (?) \"%Hlookup\".\n    apply elem_of_list_lookup_1 in Hlookup as [i Hlookup].\n    iDestruct (big_sepS_elem_of_acc _ _ (U64 i) with \"Hwg_post\") as \"[HH _]\".\n    { set_solver. }\n\n    assert (i < length server_\u03b3s).\n    {\n      apply lookup_lt_is_Some_1.\n      eexists. done.\n    }\n    replace (length clerks) with (length server_\u03b3s) in * by word.\n    assert (int.nat i = i) as Hi.\n    { word. }\n\n    iDestruct \"HH\" as \"[%Hbad|HP]\".\n    {\n      exfalso.\n      word.\n    }\n    unfold P.\n    iDestruct \"HP\" as (??) \"(%Hlookup2 & _ & Hpost)\".\n    replace (\u03b3srv') with (\u03b3srv); last first.\n    {\n      rewrite Hi in Hlookup2.\n      rewrite Hlookup in Hlookup2.\n      by inversion Hlookup2.\n    }\n    iSpecialize (\"Hrest\" $! i \u03b3srv with \"[%] [%]\").\n    { word. }\n    { rewrite Hi. done. }\n    iFrame \"Hrest\".\n  }\n  iModIntro.\n  iIntros (err) \"Hpost Hservers_sl\".\n  iNamed 1.\n\n  wp_pures.\n  wp_if_destruct.\n  { (* WriteConfig failed *)\n    iApply \"H\u03a6\". done.\n  }\n  (* WriteConfig succeeded *)\n  destruct (decide (_)); last first.\n  { exfalso. done. }\n  iDestruct \"Hpost\" as \"#Hconf\".\n  wp_apply (wp_allocStruct).\n  { eauto. }\n  clear args.\n  iIntros (args) \"Hargs\".\n  assert (0 < length clerks) as Hclerk_lookup.\n  {\n    word.\n  }\n  apply list_lookup_lt in Hclerk_lookup as [primaryCk Hclerk_lookup].\n\n  wp_apply (wp_SliceGet with \"[$Hclerks_sl]\").\n  { done. }\n  iIntros \"Hclerks_sl\".\n  wp_pures.\n\n  iDestruct (big_sepL2_lookup_1_some with \"Hclerks_is\") as %[\u03b3srv Hlookup2].\n  { done. }\n  iDestruct (big_sepL2_lookup_acc with \"Hclerks_is\") as \"[HprimaryCk _]\".\n  { done. }\n  { done. }\n\n  iDestruct (struct_fields_split with \"Hargs\") as \"HH\".\n  iNamed \"HH\".\n\n  (* Get a list of \u03b3s just for backups *)\n  destruct (server_\u03b3s).\n  {\n    exfalso.\n    rewrite lookup_take /= in Hlookup2; last first.\n    { word. }\n    done.\n  }\n  replace (p) with (\u03b3srv) in *; last first.\n  {\n    rewrite lookup_take /= in Hlookup2; last first.\n    { word. }\n    naive_solver.\n  }\n  iAssert (|={\u22a4}=> become_primary_escrow \u03b3 \u03b3srv epoch \u03c3)%I with \"[Hprop]\" as \">#Hprimary_escrow\".\n  {\n    iMod (inv_alloc with \"[Hprop]\") as \"$\".\n    {\n      iNext.\n      iLeft.\n      iFrame \"Hprop Hprop_facts2 Hinit\".\n    }\n    done.\n  }\n\n  wp_apply (wp_Clerk__BecomePrimary with \"[$HprimaryCk Hconf Hhost Epoch Replicas Hservers_sl]\").\n  {\n\n    iFrame.\n    instantiate (1:=(pb_marshal_proof.BecomePrimaryArgs.mkC _ _)).\n    simpl.\n    iFrame \"#\".\n    iSplitR.\n    {\n      iDestruct (\"Hrest\" with \"[%] [%]\") as \"H\".\n      { instantiate (1:=0). word. }\n      { rewrite lookup_take in Hlookup2.\n        { done. }\n        word.\n      }\n      iFrame \"H\".\n    }\n    iSplitR.\n    {\n      iApply big_sepL2_forall.\n      instantiate (1:=servers).\n      iSplitL; first done.\n      iIntros.\n      iDestruct (big_sepL2_lookup_acc with \"Hhost\") as \"[$ HH]\".\n      { done. }\n      { done. }\n      iApply \"Hrest\"; last first.\n      {\n        iPureIntro.\n        instantiate (1:=k).\n        replace (int.nat k) with (k).\n        { done. }\n        assert (k < length servers).\n        { apply lookup_lt_Some in H. done. }\n        word.\n      }\n      { iPureIntro.\n        apply lookup_lt_Some in H.\n        replace (int.nat k) with (k).\n        { rewrite Hlen. done. }\n        assert (k < length servers). (* FIXME: why do I have to assert this when it's already in context? *)\n        { done. }\n        word.\n      }\n    }\n    {\n      iExists _.\n      iFrame.\n    }\n  }\n  iIntros.\n  wp_pures.\n  iApply \"H\u03a6\".\n  done.\nQed.\n\nEnd admin_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/simplepb/admin_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.19997375080243154}}
{"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\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.\nRequire Import depoolContract.DePoolConsts.\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\n\nRequire Import depoolContract.Lib.CommonStateProofs.\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope solidity_scope.\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\nModule ProofHelpers (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nImport dc.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\n *)\n\n\nLtac pr_numgoals := let n := numgoals in idtac \"There are\" n \"goals\".\n\n\nLemma if_fromValueValue: forall X (b: bool) (x y: XValueValue X),\nfromValueValue (if b then x else y) = if b then (fromValueValue x) else (fromValueValue y).\nProof.\n  intros.\n  destruct b; auto.\nQed.\n\n\nLemma 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\nTactic Notation \"destructLedger\" constr(l) := \nlet Ledger_\u03b9_ValidatorBase := fresh \"Ledger_\u03b9_ValidatorBase\" in\nlet Ledger_\u03b9_ProxyBase := fresh \"Ledger_\u03b9_ProxyBase\" in\nlet Ledger_\u03b9_ParticipantBase := fresh \"Ledger_\u03b9_ParticipantBase\" in\nlet Ledger_\u03b9_DePoolProxyContract := fresh \"Ledger_\u03b9_DePoolProxyContract\" in\nlet Ledger_\u03b9_RoundsBase := fresh \"Ledger_\u03b9_RoundsBase\" in\nlet Ledger_\u03b9_DePoolContract := fresh \"Ledger_\u03b9_DePoolContract\" in\nlet Ledger_\u03b9_VMState := fresh \"Ledger_\u03b9_VMState\" in\nlet Ledger_\u03b9_LocalState := fresh \"Ledger_\u03b9_LocalState\" in\n\ndestruct l as \n [Ledger_\u03b9_ValidatorBase Ledger_\u03b9_ProxyBase Ledger_\u03b9_ParticipantBase \n Ledger_\u03b9_DePoolProxyContract \nLedger_\u03b9_RoundsBase Ledger_\u03b9_DePoolContract  \nLedger_\u03b9_VMState Ledger_\u03b9_LocalState]; \n\ndestruct Ledger_\u03b9_ValidatorBase, Ledger_\u03b9_ProxyBase, Ledger_\u03b9_ParticipantBase, \nLedger_\u03b9_DePoolProxyContract, \nLedger_\u03b9_RoundsBase, Ledger_\u03b9_DePoolContract,  \nLedger_\u03b9_VMState, Ledger_\u03b9_LocalState.\n\n\nTactic Notation \"destructFunction0\" constr(f) := \nmatch goal with \n | |- ?G => match G with \n            | context [f] => \n                  let m := fresh \"m\" in\n                  let p := fresh \"p\" in\n                  remember f  as m;\n                  destruct m as (p) ;\n                  let r := fresh \"r\" in \n                  match goal with \n                    | |- ?G1 => match G1 with \n                                 | context [p ?l] => remember (p l) as r;\n                                                     let x := fresh \"x\" in \n                                                     let l := fresh \"l\" in\n                                                     destruct r as [x l] \n                                end                     \n                  end\n            end      \nend.\n\nTactic Notation \"destructFunction1\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\n\nTactic Notation \"destructFunction2\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\n\nTactic Notation \"destructFunction3\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\nTactic Notation \"destructFunction4\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c ?d] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c d) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\nTactic Notation \"destructFunction5\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c ?d ?e] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c d e) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\n\nTactic Notation \"destructFunction6\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c ?d ?e ?g] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c d e g) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\nTactic Notation \"destructFunction7\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c ?d ?e ?g ?h] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c d e g h) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\nTactic Notation \"destructFunction8\" constr(f) := \n match goal with \n  | |- ?G => match G with \n             | context [f ?a ?b ?c ?d ?e ?g ?h ?i] => \n                   let m := fresh \"m\" in\n                   let p := fresh \"p\" in\n                   remember (f a b c d e g h i) as m;\n                   destruct m as (p) ;\n                   let r := fresh \"r\" in \n                   match goal with \n                     | |- ?G1 => match G1 with \n                                  | context [p ?l] => remember (p l) as r;\n                                                      let x := fresh \"x\" in \n                                                      let l := fresh \"l\" in\n                                                      destruct r as [x l] \n                                 end                     \n                   end\n             end      \nend.\n\n\nTactic Notation \"destructIf_solve\" := \n\ntime match goal with\n      | |- ?G =>\n        match G with\n        | context [if ?b then _ else _] =>  idtac \"if...\" b; \n                                            repeat rewrite ifSimpleState ; \n                                            repeat rewrite ifFunApply ;\n                                            case_eq b ; \n                                            simpl ; \n                                            intros                                                                \n        | _ =>  idtac \"solving...\" G; \n                tryif solve [auto] then idtac \"solved\" else idtac \"not solved\"\n        end\nend.\n\n\nTactic Notation \"destructIf_solve2\" := \n\ntime match goal with\n      | |- ?G =>\n        match G with\n        | context [if ?b then _ else _] =>  idtac \"if...\" b; \n                                            repeat rewrite ifSimpleState ; \n                                            repeat rewrite ifFunApply ;\n                                            match goal with \n                                            | H : b = _ |- _ => first [ (idtac \"rewriting ->\" ; rewrite H) | (idtac \"destructing\" ; case_eq b ; (* simpl ; *) intros) ]\n                                            | H : _ = b |- _ => first [ (idtac \"rewriting <-\" ; rewrite <- H) | (idtac \"destructing\" ; case_eq b ; (* simpl ; *) intros) ]\n                                            | _ => idtac \"destructing\" ; case_eq b ; (* simpl ; *) intros\n                                            end\n        | _ =>  idtac \"solving...\" G; \n                tryif solve [auto] then idtac \"solved\" else idtac \"not solved\"\n        end\nend.\n\n(* repeat time match goal with\n  | H : ?P |- _ =>\n    match P with\n    | context [ (if ?b then _ else _ ) = _ ] =>  let HH:=fresh\"HH\" in idtac \"if...\" b; case_eq b ; intros HH; rewrite HH in H ; try discriminate; try congruence\n\n    end\n  end. *)\nEnd ProofHelpers.\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/ProofHelpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "(* Interpret a program according to the semantics of the ir *)\n\nRequire Export List.\nRequire Export Coqlib.\nRequire Export Maps.\nRequire Export String.\nRequire Export common.\nRequire Export specIR.\n\n(* Interpreting operands *)\nDefinition eval_op (o:op) (rm:reg_map): res value :=\n  match o with\n  | Reg r => try_op (PTree.get r rm) \"Unassigned register\"\n  | Cst n => OK n\n  end.\n\n\n(* Interpreting Binary operations *)\nDefinition eval_binop_values (bo:bin_operation) (v1:value) (v2:value) : res value :=\n  match v1 with\n  | Vint vi1 =>\n    match v2 with\n    | Vint vi2 =>\n      match bo with\n      | Plus => OK (Vint (vi1 + vi2))\n      | Minus => OK (Vint (vi1 - vi2))\n      | Mult => OK (Vint (vi1 * vi2))\n      | Gt => OK (bool_to_val(Z.gtb vi1 vi2))\n      | Lt => OK (bool_to_val(Z.ltb vi1 vi2))\n      | Geq => OK (bool_to_val(Z.geb vi1 vi2))\n      | Leq => OK (bool_to_val(Z.leb vi1 vi2))\n      | Eq => OK (bool_to_val(Z.eqb vi1 vi2))\n      end\n    end\n  end.\n\nDefinition eval_binop (bo:bin_operation) (o1:op) (o2:op) (rm:reg_map): res value :=\n  do v1 <- eval_op o1 rm;\n    do v2 <- eval_op o2 rm;\n    eval_binop_values bo v1 v2.\n\n(* Interpreting Unary operations *)\nDefinition eval_unop_value (u:un_operation) (v:value): res value :=\n  match u with\n  | UMinus => match v with\n             | Vint vi =>  OK (Vint (-vi))\n             end\n  | Neg => match v with\n          | Vint vi => OK (Vint (int_neg vi))\n          end\n  | Assign => OK v\n  end.\n\nDefinition eval_unop (u:un_operation) (o:op) (rm:reg_map): res value :=\n  do v <- eval_op o rm;\n    eval_unop_value u v.\n\n(* Interpreting expressions *)\nDefinition eval_expr (e:expr) (rm:reg_map): res value :=\n  match e with\n  | Binexpr binop o1 o2 => eval_binop binop o1 o2 rm\n  | Unexpr unop o => eval_unop unop o rm\n  end.\n\n(* Checks if a list of expressions are all true (!= 0) *)\nFixpoint eval_list_expr (le:list expr) (rm:reg_map): res bool :=\n  match le with\n  | nil => OK true\n  | ex::le' => do v <- eval_expr ex rm;\n                 match v with\n                 | Vint 0 => OK false\n                 | Vint _ => eval_list_expr le' rm\n                 end\n  end.\n\n(* In case there is an error in the evaluation of the guard of an Assume, we want to deoptimize *)\nDefinition safe_eval_list_expr (le:list expr) (rm:reg_map): bool :=\n  match eval_list_expr le rm with\n  | OK b => b\n  | Error _ => false             (* ignore the errors in guard evaluation *)\n  end.\n\n(* Interprets a list of expressions (arguments) *)\n(* lv is the list of values already evaluated *)\nFixpoint eval_list (le:list expr) (rm:reg_map): res (list value) :=\n  match le with\n  | nil => OK nil\n  | ex::le' => do v <- eval_expr ex rm;\n                 do lv <- eval_list le' rm;\n                 OK (v::lv)\n  end.\n\n(* Initialize the register map when calling a function *)\nFixpoint init_regs (valist:list value) (params:list reg): res reg_map :=\n  match valist with\n  | nil => match params with\n           | nil => OK empty_regmap\n           | _ => Error \"Not enough arguments\"\n           end\n  | val::valist' => match params with\n                   | nil => Error \"Too many arguments\"\n                   | par::params' => do rm' <- init_regs valist' params';\n                                       OK (rm' # par <- val)\n                    end\n  end.\n\n(* Updates the reg_map [rm] with the binding of [ml] *)\n(* rmeval is the original regmap, to evaluate all ops *)\nFixpoint update_movelist' (ml:movelist) (rmeval:reg_map) (rm:reg_map) : res reg_map :=\n  match ml with\n  | nil => OK rm\n  | (r,e)::ml' => do v <- eval_expr e rmeval;\n                  do rm' <- update_movelist' ml' rmeval rm;\n                  OK (rm' # r <- v)\n  end.\n\nDefinition update_movelist (ml:movelist) (rm:reg_map) : res reg_map :=\n  update_movelist' ml rm rm.\n\n(* Creating a new Register Mapping from a Varmap *)\nFixpoint update_regmap (vm:varmap) (rm:reg_map): res reg_map :=\n  match vm with\n  | nil => OK empty_regmap\n  | (r,e)::vm' =>\n    do v <- eval_expr e rm;\n      do rm' <- update_regmap vm' rm;\n      OK (rm' # r <- v)\n  end.\n\n(* [synthesize_frame p rm sl]: the stack synthesized by the list [sl] under [rm] and [p] *)\nFixpoint synthesize_frame (p:program) (rm:reg_map) (sl:list synth_frame): res stack :=\n  match sl with\n  | nil => OK nil\n  | ((f,l),r,vm)::sl' =>\n    do rmupdate <- update_regmap vm rm;\n      do version <- try_op (find_base_version f p) \"The version for the new stackframe does not exist\";\n      do stack <- synthesize_frame p rm sl';\n      OK ((Stackframe r version l rmupdate)::stack)\n  end.\n\n(* Returning states without any trace *)\nDefinition OK0 {A:Type} (s:A) := OK (s,E0).\n\nDefinition check_nil {X:Type} (l:list X) : res unit :=\n  match l with\n  | nil => OK tt\n  | _ => Error \"The main function should not require any arguments\"\n  end.\n\n(* Compute the initial state of a program *)\nDefinition initial_state (p:program) : res state :=\n  do f <- try_op (find_function (prog_main p) p) \"Can't find main function of the program\";\n    do check <- check_nil (fn_params f);\n    do v <- OK (current_version f);\n    OK (State nil v (ver_entry v) empty_regmap initial_memory).\n\n(** * Internal interpreter state *)\n(* The internal state of the interpreter. Does not need the stack, as it stops upon Call, Return and Deopt *)\nInductive interpreter_state: Type :=\n| Int_State: version -> label -> reg_map -> interpreter_state\n| Int_Final: value -> interpreter_state.\n\n(** * Synchronization states  *)\n(* The output of the interpreter and native calls *)\nInductive synchro_state:=\n| S_Call: fun_id -> list value -> option stackframe -> synchro_state\n| S_Return: value -> synchro_state\n| S_Deopt: deopt_target -> (list stackframe) -> reg_map -> synchro_state\n| Halt: interpreter_state -> synchro_state.\n(* The stack returned in the Deopt case is the new synthesized stackframes *)\n(* Halt allows the interpreter to go back to the JIT even when a synchro points hasn't been reached *)\n(* The interpreter synthesizes its own stackframe on a call *)\n\n(* Returning states without any trace, nor stackframe *)\nDefinition OK_ (sm:(synchro_state * mem_state)) : res (synchro_state * mem_state * trace) :=\n  OK (sm,E0).\n\n(** * Internal interpreter step  *)\nDefinition int_step (p:program) (ins:interpreter_state) (ms:mem_state): res (synchro_state * mem_state * trace) :=\n  match ins with\n  | Int_State v pc rm =>\n    do instr <- try_op ((ver_code v) ! pc) \"No code to execute\";\n      match instr with\n      | Nop oh next => OK_ (Halt (Int_State v next rm), ms)\n\n      | Op expr reg next =>\n        do val <- eval_expr expr rm;\n          OK_ (Halt (Int_State v next (rm # reg <- val)), ms)\n\n      | Move ml next =>\n        do newrm <- update_movelist ml rm;\n          OK_ (Halt (Int_State v next newrm), ms)\n\n      | Cond ex iftrue iffalse =>\n        do val <- eval_expr ex rm;\n          do nextlbl <- OK (pc_cond val iftrue iffalse);\n          OK_ (Halt (Int_State v nextlbl rm), ms)\n\n      | Printexpr ex next =>\n        do printval <- eval_expr ex rm;\n          OK (Halt (Int_State v next rm), ms, Valprint printval::E0)\n\n      | Printstring str next =>\n        OK (Halt (Int_State v next rm), ms, Stringprint str::E0)\n\n      | Store ex1 ex2 next =>\n        do val <- eval_expr ex1 rm;\n          do addr <- eval_expr ex2 rm;\n          do newms <- try_op (Store_ ms addr val) \"Store_ failed\";\n          OK_ (Halt (Int_State v next rm), newms) \n\n      | Load ex reg next =>\n        do addr <- eval_expr ex rm;\n          do val <- try_op (Load_ ms addr) \"Load_ failed\";\n          OK_ (Halt (Int_State v next (rm # reg <- val)), ms)\n\n      | Call fid args retreg next =>\n        do valist <- eval_list args rm;\n          (* to make sure the result can be forged *)\n          do func <- try_op (find_function fid p) \"Function doesn't exist\"; \n          do newrm <- init_regs valist (fn_params func);\n          OK (S_Call fid valist (Some (Stackframe retreg v next rm)), ms, E0)\n\n      | IReturn retex =>\n        do retval <- eval_expr retex rm;\n          OK_ (S_Return retval, ms)\n              \n      | Assume g (fa,la) vm sl next =>\n        do assertion <- eval_list_expr g rm; \n          match assertion with\n          | true => OK_ (Halt (Int_State v next rm), ms)\n          | false =>\n            do synth <- synthesize_frame p rm sl;\n              do newrm <- update_regmap vm rm;\n              (* to make sure the result can be forged *)\n              do newver <- try_op (find_base_version fa p) \"The version to deoptimize to does not exist\";\n              OK_ (S_Deopt (fa,la) synth newrm, ms)\n          end\n\n      | Framestate (fa,la) vm sl next =>\n        do findf <- try_op (find_base_version fa p) \"No deopt conditions\";\n        do synth <- synthesize_frame p rm sl;\n        do newrm <- update_regmap vm rm;\n        OK_ (Halt (Int_State v next rm), ms)\n      (* we give Framestate a behavior, just to make progress preservation proof easier *)\n      (* Actually, since Framestates are lowered, the interpreter will never see them *)\n\n      | Fail s => Error s        (* Fail should make the interpreter crash *)\n            \n      end\n  | Int_Final retval =>\n    Error \"Called interpreter on Final\"\n  end.\n  \n\n(** * Interpreter loop  *)\n\n(** Safe interpreter step  *)\n(*  version of the interpreter step that returns to the JIT when seeing an error *)\n(* The bool tells you if you should keep on interpreting if you still have fuel *)\n(* It also returns just after an event is outputed *)\nDefinition safe_int_step p ins ms : (synchro_state * mem_state * trace * bool) :=\n  match (int_step p ins ms) with\n  | OK (synchro, newms, t) => match t with\n                             | nil => (synchro, newms, t, true)\n                             | _ => (synchro, newms, t, false) (* stops after outputs *)\n                             end\n  | Error _ => (Halt ins, ms, E0, false) (* stops before errors *)\n  end.\n\n(* looping the safe_step and halting just before an error if there is one *)\nFixpoint interpreter_safe_loop (fuel: nat) (p:program) (ins:interpreter_state) (ms:mem_state): (synchro_state * mem_state * trace) :=\n  match fuel with\n  | O => (Halt ins, ms, E0)\n  | S fuel' =>\n    let '(synchro, newms, t, b) := safe_int_step p ins ms in\n    match b with\n    | false => (synchro, newms, t) (* the interpreter has encountered an error, time to return to the JIT *)\n    | true => \n      match synchro with\n      | Halt int_state => let '(synchro', newms', t') := interpreter_safe_loop fuel' p int_state newms in\n                         (synchro', newms', t++t')\n      | _ => (synchro, newms, t)\n      end\n    end\n  end.\n\nDefinition interpreter_loop (fuel: nat) (p:program) (ins:interpreter_state) (ms:mem_state): res (synchro_state * mem_state * trace) :=\n  do (synchro, newms, t) <- int_step p ins ms; (* first step may fail *)\n    match t with\n    | nil => \n      match synchro with\n      | Halt int_state =>           (* we may call the safe loop to go a bit further *)\n        let '(synchro', newms', t') := interpreter_safe_loop fuel p int_state newms in\n        OK (synchro', newms', t ++ t')\n      | _ => OK (synchro, newms, t) (* we reached a synchronization point *)\n      end\n    | _ => OK (synchro, newms, t) (* we outputed something in the very first step *)\n    end.\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/interpreter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Facade.CompileSafe.\nRequire Import Platform.Facade.CompileRunsTo.\nRequire Import Platform.Facade.CompileDFacadeCorrect.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Platform.Facade.DFacade.\n\n  Notation State := (@State ADTValue).\n  Notation Env := (@Env ADTValue).\n  Notation Value := (@Value ADTValue).\n  Notation FuncSpec := (@FuncSpec ADTValue).\n  Notation RunsTo := (@RunsTo ADTValue).\n  Notation Safe := (@Safe ADTValue).\n\n  Require Import Bedrock.Memory.\n  Require Import Platform.Cito.GLabel.\n\n  Notation CState := (@Semantics.State ADTValue).\n  Notation CCallee := (@Semantics.Callee ADTValue).\n  Notation CInternal := (@Semantics.Internal ADTValue).\n  Notation CRunsTo := (@Semantics.RunsTo ADTValue).\n  Notation CEnv := ((glabel -> option W) * (W -> option CCallee))%type.\n\n  Notation FEnv := (@Facade.Env ADTValue).\n\n  Require Import Platform.Cito.GLabelMap.\n\n  Notation compile s := (Compile.compile (compile s)).\n\n  Notation compile_spec s := (CompileRunsTo.compile_spec (@CompileDFacadeCorrect.compile_spec ADTValue s)).\n\n  Require Import Platform.Cito.Label2Word Platform.Cito.Label2WordFacts.\n\n  Require Import Platform.Cito.GLabelMap.\n  Import GLabelMap.\n  Require Import Platform.Cito.GLabelMapFacts.\n  Import FMapNotations.\n  Local Open Scope fmap_scope.\n\n  Definition cenv_impls_env (cenv : CEnv) (env : Env) :=\n    (forall lbl spec,\n      GLabelMap.find lbl env = Some spec ->\n      exists w,\n        fst cenv lbl = Some w /\\\n        snd cenv w = Some (compile_spec spec)) /\\\n    stn_injective (fun k => In k env) (fst cenv).\n\n  Require Import Bedrock.StringSet.\n\n  Require Import Platform.Cito.Option.\n\n  Require Import Platform.Cito.GeneralTactics.\n  Require Import Platform.Cito.GeneralTactics3.\n  Require Import Platform.Cito.GeneralTactics4.\n  Require Import Platform.Cito.GeneralTactics5.\n\n  Lemma cenv_impls_env_fenv cenv env : cenv_impls_env cenv env -> exists fenv, CompileRunsTo.cenv_impls_env cenv fenv /\\ fenv_impls_env fenv env.\n  Proof.\n    intros [H Hinj].\n    set (fenv :=\n           {|\n             Label2Word := fst cenv;\n             Word2Spec w := option_map (@CompileDFacadeCorrect.compile_spec _) (find_by_word (fst cenv) (elements env) w)\n           |} : FEnv).\n    unfold cenv_impls_env in *.\n    unfold CompileRunsTo.cenv_impls_env in *.\n    unfold fenv_impls_env in *.\n    exists fenv.\n    unfold_all; simpl in *.\n    split.\n    {\n      split.\n      {\n        eauto.\n      }\n      {\n        intros w fspec Hfw.\n        eapply option_map_some_elim in Hfw.\n        destruct Hfw as [spec [Hfw ?]].\n        subst.\n        eapply find_by_word_elements_elim in Hfw.\n        destruct Hfw as [lbl [Hflbl Hlblw]].\n        eapply H in Hflbl.\n        destruct Hflbl as [w' [Hlblw' Hw'spec]].\n        unif w'.\n        eauto.\n      }\n    }\n    {\n      intros lbl spec Hflbl.\n      copy_as Hflbl Hflbl'.\n      eapply H in Hflbl.\n      destruct Hflbl as [w [Hlblw Hwspec]].\n      exists w.\n      split; eauto.\n      eapply option_map_some_intro; eauto.\n      eapply find_by_word_elements_intro; eauto.\n    }\n  Qed.\n\n  Require Import Platform.Cito.StringMap.\n  Import StringMap.\n  Require Import Platform.Cito.StringMapFacts.\n  Import FMapNotations.\n  Local Open Scope fmap_scope.\n\n  Notation equivf := (equiv (StringSet.singleton fun_ptr_varname)).\n  Infix \"===\" := equivf (at level 70).\n\n  Require Import Coq.Strings.String.\n\n  Require Import Platform.Facade.NameDecoration.\n  Require Import Platform.Facade.FacadeFacts Platform.Facade.DFacadeFacts.\n\n  Existing Instance equiv_rel_Symmetric.\n  Existing Instance equiv_rel_Transitive.\n\n  Lemma equiv_related (st st' : State) cst : related st cst -> st' === st -> find fun_ptr_varname st' = None -> related st' cst.\n  Proof.\n    intros Hr Heqv Hfpv.\n    unfold related.\n    split.\n    {\n      intros k v Hfk.\n      destruct (string_dec k fun_ptr_varname) as [Heqk | Hnek].\n      {\n        subst.\n        rewrite Hfk in Hfpv; discriminate.\n      }\n      erewrite find_equiv_fpv in Hfk; eauto.\n      eapply Hr in Hfk.\n      eauto.\n    }\n    intros p a Hpa.\n    eapply Hr in Hpa.\n    destruct Hpa as [x [[Hxp Hxa] Huni]].\n    destruct (string_dec x fun_ptr_varname) as [Heqx | Hnex].\n    {\n      subst.\n      contradict Hxa.\n      eapply not_find_fpv_adt; eauto.\n    }\n    exists x.\n    split.\n    {\n      split; eauto.\n      erewrite find_equiv_fpv; eauto.\n    }\n    intros x' [Hx'p Hx'a].\n    destruct (string_dec x' fun_ptr_varname) as [Heqx' | Hnex'].\n    {\n      subst.\n      contradict Hx'a.\n      symmetry in Heqv.\n      eapply not_find_fpv_adt; eauto.\n    }\n    erewrite find_equiv_fpv in Hx'a; eauto.\n  Qed.\n\n  Require Import Platform.Cito.StringSetFacts.\n  Import StringSet.\n  Require Import Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Platform.Cito.WordMapFacts.\n  Import FMapNotations.\n  Local Open Scope fmap_scope.\n\n  Theorem compile_runsto t t_env t_st t_st' :\n    CRunsTo t_env t t_st t_st' -> \n    forall s, \n      t = compile s -> \n      is_syntax_ok s = true -> \n      (* h1 : the heap portion that this program is allowed to change *)\n      forall h1, \n        h1 <= snd t_st -> \n        forall s_st, \n          related s_st (fst t_st, h1) -> \n          StringMap.find fun_ptr_varname s_st = None ->\n          forall s_env, \n            cenv_impls_env t_env s_env -> \n            Safe s_env s s_st -> \n            exists s_st', \n              RunsTo s_env s s_st s_st' /\\ \n              (* h2 : the frame heap (the outside portion that won't be touched by this program *)\n              let h2 := snd t_st - h1 in \n              (* the frame heap will be intacked in the final state *)\n              h2 <= snd t_st' /\\ \n              (* main result: final source-level and target level states are related *)\n              related s_st' (fst t_st', snd t_st' - h2).\n  Proof.\n    intros Hcrt s Hcomp Hsyn h1 Hsm s_st Hr Hnotmp s_env Henv Hsf.\n    eapply cenv_impls_env_fenv in Henv.\n    destruct Henv as [fenv [Htenv Hfenv]].\n    eapply CompileRunsTo.compile_runsto in Hcrt; eauto.\n    - destruct Hcrt as [s_st' [Hfrt Hsst']]; simpl in *.\n      destruct Hsst' as [Hsm' [Hnoass [Hnocollide Hr']]].\n      eapply CompileDFacadeCorrect.compile_runsto in Hfrt; eauto.\n      + destruct Hfrt as [d_st' [Hdrt Heqv]].\n        exists d_st'.\n        repeat try_split.\n        * eauto.\n        * eauto.\n        * eapply equiv_related; eauto.\n          eapply not_free_vars_no_change in Hdrt; eauto.\n          erewrite Hdrt; eauto.\n          eapply syntax_ok_fptr_not_fv; eauto.\n      + eapply equiv_refl; eauto.\n        eapply find_none_not_mapsto_adt; eauto.\n    - eapply CompileDFacadeCorrect.compile_safe; eauto.\n      eapply equiv_refl; eauto.\n      eapply find_none_not_mapsto_adt; eauto.\n  Qed.\n\n  Notation CSafe := (@Semantics.Safe ADTValue).\n\n  Theorem compile_safe s_env s s_st :\n  Safe s_env s s_st ->\n  is_syntax_ok s = true ->\n  StringMap.find fun_ptr_varname s_st = None ->\n  (* h1 : the heap portion that this program is allowed to change *)\n  forall vs h h1, \n    h1 <= h -> \n    related s_st (vs, h1) -> \n    forall t_env t t_st,\n      cenv_impls_env t_env s_env ->\n      t = compile s ->\n      t_st = (vs, h) ->\n      CSafe t_env t t_st.\n  Proof.\n    simpl; intros Hsfs Hsyn Hsstok vs h h1 Hsm Hr t_env t t_st Henv Ht Htst.\n    subst.\n    eapply cenv_impls_env_fenv in Henv.\n    destruct Henv as [fenv [Htenv Hfenv]].\n    eapply CompileSafe.compile_safe; eauto.\n    eapply CompileDFacadeCorrect.compile_safe; eauto.\n    eapply equiv_refl.\n    eapply find_none_not_mapsto_adt; 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/Facade/CompileDFacadeToCito.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19997006613770815}}
{"text": "From iris.algebra Require Import auth agree excl gmap frac.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Import adequacy.\nRequire Import Eqdep_dec.\n\nFrom cap_machine Require Import\n     stdpp_extra iris_extra\n     logrel_binary fundamental_binary linking.\nFrom cap_machine.binary_model Require Import\n     macros_binary confidentiality region_invariants_binary_allocation.\nFrom cap_machine.examples Require Import\n     disjoint_regions_tactics.\n\nFrom cap_machine.binary_model Require Import\n     confidentiality_adequacy.\n\nDefinition is_initial_configuration_left `{memory_layout} c_adv prog :=\n  \u2203 stack_init p1, is_machine_context c_adv comp1 p1\n                   \u2227 (b_stk + length stack_init)%a = Some e_stk\n                   \u2227 prog = initial_state_stk b_stk e_stk stack_init p1.\n\nDefinition is_initial_configuration_right `{memory_layout} c_adv prog :=\n  \u2203 stack_init p2, is_machine_context c_adv comp2 p2\n                   \u2227 (b_stk + length stack_init)%a = Some e_stk\n                   \u2227 prog = initial_state_stk b_stk e_stk stack_init p2.\n\nDefinition soundness_binary\u03a3 : gFunctors :=\n  #[GFunctor (authR cfgUR); inv\u03a3; gen_heap\u03a3 Addr Word;\n   gen_heap\u03a3 RegName Word;\n   na_inv\u03a3;\n   STS_pre\u03a3 Addr region_invariants_binary.region_type; region_invariants_binary.heapPre\u03a3;\n   savedPred\u03a3 (((STS_std_states Addr region_invariants_binary.region_type)\n                * (STS_states * STS_rels)) * (Word * Word))].\n\nGlobal Instance inG_soundness_binary\u03a3 \u03a3 : subG soundness_binary\u03a3 \u03a3 \u2192 inG \u03a3 (authR cfgUR).\nProof. solve_inG. Qed.\n\n\nTheorem confidentiality_adequacy_l `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv reg' m' (es: list cap_lang.expr):\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  rtc erased_step prog1 (of_val HaltedV :: es, (reg', m')) \u2192\n  (\u2203 es' conf', rtc erased_step prog2 (of_val HaltedV :: es', conf')).\nProof.\n  set (\u03a3 := soundness_binary\u03a3).\n  intros [stack_init [p1 [? [? ->] ] ] ] [stack_init' [p2 [? [? ->] ] ] ] ? ?.\n  eapply (@confidentiality_adequacy_l' \u03a3);last eauto;eauto. all: try typeclasses eauto.\nQed.\n\nTheorem confidentiality_adequacy_r `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv reg' m' (es: list cap_lang.expr):\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  rtc erased_step prog2 (of_val HaltedV :: es, (reg', m')) \u2192\n  (\u2203 es' conf', rtc erased_step prog1 (of_val HaltedV :: es', conf')).\nProof.\n  set (\u03a3 := soundness_binary\u03a3).\n  intros [stack_init [p1 [? [? ->] ] ] ] [stack_init' [p2 [? [? ->] ] ] ] ? ?.\n  eapply (@confidentiality_adequacy_r' \u03a3);last eauto;eauto. all: try typeclasses eauto.\nQed.\n\nTheorem confidentiality_ctx_equivalent `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv :\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  (\u2203 es conf, rtc erased_step prog1 (of_val HaltedV :: es, conf)) \u2194\n  (\u2203 es conf, rtc erased_step prog2 (of_val HaltedV :: es, conf)).\nProof.\n  intros. split.\n  - intros (?&[? ?]&?). eapply confidentiality_adequacy_l;eauto.\n  - intros (?&[? ?]&?). eapply confidentiality_adequacy_r;eauto.\nQed.\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/confidentiality_adequacy_theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.199860318598717}}
{"text": "From iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import frac.\nFrom cap_machine Require Export rules_AddSubLt rules_binary_base.\n\nSection cap_lang_spec_rules. \n  Context `{cfgSG \u03a3, MachineParameters, invGS \u03a3}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03c3 : 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_AddSubLt Ep K i pc_p pc_b pc_e pc_a w dst arg1 arg2 regs :\n    decodeInstrW w = i \u2192\n    is_AddSubLt i dst arg1 arg2 \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) \u2192\n    regs !! PC = Some (WCap pc_p pc_b pc_e pc_a) \u2192\n    regs_of i \u2286 dom regs \u2192\n\n    nclose specN \u2286 Ep \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable) \u2217 \u25b7 pc_a \u21a3\u2090 w \u2217 \u25b7 ([\u2217 map] k\u21a6y \u2208 regs, k \u21a3\u1d63 y)\n    ={Ep}=\u2217 \u2203 retv regs', \u231c AddSubLt_spec (decodeInstrW w) regs dst arg1 arg2 regs' retv \u231d \u2217\n                            \u2907 fill K (of_val retv) \u2217 pc_a \u21a3\u2090 w \u2217 [\u2217 map] k\u21a6y \u2208 regs', k \u21a3\u1d63 y. \n  Proof.\n    iIntros (Hdecode Hinstr Hvpc HPC Dregs Hnclose) \"(Hinv & Hj & >Hpc_a & >Hmap)\".\n    iDestruct \"Hinv\" as (\u03c1) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [\u03c3r \u03c3m]) \"[Hown %] /=\".\n    iDestruct (regspec_heap_valid_inclSepM with \"Hown Hmap\") as %Hregs.\n    have ? := 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    specialize (normal_always_step (\u03c3r,\u03c3m)) as [c [ \u03c32 Hstep]].\n    eapply step_exec_inv in Hstep; eauto.\n    pose proof (Hstep' := Hstep). unfold exec in Hstep.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri.\n    erewrite regs_of_is_AddSubLt in Hri, Dregs; eauto.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n\n    destruct (z_of_argument regs arg1) as [n1|] eqn:Hn1;\n      pose proof Hn1 as Hn1'; cycle 1.\n    (* Failure: arg1 is not an integer *)\n    { unfold z_of_argument in Hn1. destruct arg1 as [| r0]; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hn1.\n      assert (c = Failed \u2227 \u03c32 = (\u03c3r, \u03c3m)) as (-> & ->).\n      { destruct_or! Hinstr; rewrite Hinstr /= in Hstep.\n        all: rewrite Hr0 in Hstep. all: repeat case_match; simplify_eq; eauto. }\n      iFailStep AddSubLt_fail_nonconst1.\n    }\n   apply (z_of_arg_mono _ \u03c3r) in Hn1; auto.\n\n    destruct (z_of_argument regs arg2) as [n2|] eqn:Hn2;\n      pose proof Hn2 as Hn2'; cycle 1.\n    (* Failure: arg2 is not an integer *)\n    { unfold z_of_argument in Hn2. destruct arg2 as [| r0]; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hn2.\n      assert (c = Failed \u2227 \u03c32 = (\u03c3r, \u03c3m)) as (-> & ->).\n      { destruct_or! Hinstr; rewrite Hinstr /= Hn1 /= in Hstep.\n        all: rewrite Hr0 in Hstep. all: repeat case_match; simplify_eq; eauto. }\n      iFailStep AddSubLt_fail_nonconst2. }\n    apply (z_of_arg_mono _ \u03c3r) in Hn2; auto.\n\n    assert (exec_opt i (\u03c3r, \u03c3m) = updatePC (update_reg (\u03c3r, \u03c3m) dst (WInt (denote i n1 n2)))) as HH.\n    { all: destruct_or! Hinstr; rewrite Hinstr /= /update_reg /= in Hstep |- *; auto.\n      all: by rewrite Hn1 Hn2; cbn. }\n    rewrite HH in Hstep. rewrite /update_reg /= in Hstep.\n\n    destruct (incrementPC (<[ dst := WInt (denote i n1 n2) ]> regs))\n      as [regs'|] eqn:Hregs'; pose proof Hregs' as H'regs'; cycle 1.\n    (* Failure: Cannot increment PC *)\n    { apply incrementPC_fail_updatePC with (m:=\u03c3m) in Hregs'.\n      eapply updatePC_fail_incl with (m':=\u03c3m) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      rewrite Hregs' in Hstep. inv Hstep.\n      iFailStep AddSubLt_fail_incrPC. }\n    \n    (* Success *)\n\n    eapply (incrementPC_success_updatePC _ \u03c3m) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & HuPC & ->).\n    eapply updatePC_success_incl with (m':=\u03c3m) in HuPC. 2: by eapply insert_mono; eauto. rewrite HuPC in Hstep.\n    simplify_pair_eq. iFrame.\n    iMod ((regspec_heap_update_inSepM _ _ _ dst) with \"Hown Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((regspec_heap_update_inSepM _ _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hr Hj\") as \"[Hown Hj]\".\n    iExists NextIV,_. iFrame.\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n      prim_step_from_exec. }\n    iModIntro. iPureIntro. econstructor; eauto.\n  Qed.\n\n  Lemma step_AddSubLt_fail E K ins dst n1 r2 w wdst pc_p pc_b pc_e pc_a p b e a :\n    decodeInstrW w = ins \u2192\n    is_AddSubLt ins dst (inl n1) (inr r2) \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) \u2192\n    nclose specN \u2286 E \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable) \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a \u2217 pc_a \u21a3\u2090 w \u2217 dst \u21a3\u1d63 wdst\n             \u2217 r2 \u21a3\u1d63 WCap p b e a\n    ={E}=\u2217 \u2907 fill K (of_val FailedV). \n  Proof.\n    iIntros (Hdecode Hinstr Hvpc Hnclose) \"(Hown & Hj & HPC & Hpc_a & Hdst & Hr2)\".\n    iDestruct (map_of_regs_3 with \"HPC Hdst Hr2\") as \"[Hmap (%&%&%)]\".\n    iMod (step_AddSubLt with \"[$Hmap $Hown $Hj Hpc_a]\") as (? ? Hspec) \"(Hj & HH)\"; eauto; simplify_map_eq; eauto.\n      by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    destruct Hspec as [* Hsucc |].\n    { (* Success (contradiction) *) by rewrite /= lookup_insert_ne// lookup_insert_ne// lookup_insert in H4. }\n    { (* Failure, done *) by iFrame. }\n  Qed.\n\n  Lemma step_add_sub_lt_success_z_r E K dst pc_p pc_b pc_e pc_a w wdst ins n1 r2 n2 pc_a' :\n    decodeInstrW w = ins \u2192\n    is_AddSubLt ins dst (inl n1) (inr r2) \u2192\n    (pc_a + 1)%a = Some pc_a' \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) ->\n    nclose specN \u2286 E \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable)\n             \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a\n             \u2217 pc_a \u21a3\u2090 w\n             \u2217 r2 \u21a3\u1d63 WInt n2\n             \u2217 dst \u21a3\u1d63 wdst\n    ={E}=\u2217\n             \u2907 fill K (of_val NextIV)\n             \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a'\n             \u2217 pc_a \u21a3\u2090 w\n             \u2217 r2 \u21a3\u1d63 WInt n2\n             \u2217 dst \u21a3\u1d63 WInt (denote ins n1 n2).\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc Hnlose) \"(#Hown & Hj & HPC & Hpc_a & Hr2 & Hdst)\".\n    iDestruct (map_of_regs_3 with \"HPC Hr2 Hdst\") as \"[Hmap (%&%&%)]\".\n    iMod (step_AddSubLt with \"[$Hmap $Hj $Hown $Hpc_a]\") as (retv regs' Hspec) \"(Hj & Hpc_a & Hmap)\"; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    \n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r2 dst) //\n              (insert_commute _ dst PC) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; by iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto. congruence. }\n  Qed.\n\n  Lemma step_add_sub_lt_success_dst_r E K dst pc_p pc_b pc_e pc_a w ins n1 r2 n2 pc_a' :\n    decodeInstrW w = ins \u2192\n    is_AddSubLt ins dst (inr dst) (inr r2) \u2192\n    (pc_a + 1)%a = Some pc_a' \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) ->\n\n    nclose specN \u2286 E \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable)\n             \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a\n             \u2217 pc_a \u21a3\u2090 w\n             \u2217 r2 \u21a3\u1d63 WInt n2\n             \u2217 dst \u21a3\u1d63 WInt n1\n    ={E}=\u2217 \u2907 fill K (Instr NextI)\n        \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a'\n        \u2217 pc_a \u21a3\u2090 w\n        \u2217 r2 \u21a3\u1d63 WInt n2\n        \u2217 dst \u21a3\u1d63 WInt (denote ins n1 n2).\n  Proof. \n    iIntros (Hdecode Hinstr Hpc_a Hvpc Hnclose) \"(Hown & Hj & HPC & Hpc_a & Hr2 & Hdst)\".\n    iDestruct (map_of_regs_3 with \"HPC Hr2 Hdst\") as \"[Hmap (%&%&%)]\".\n    iMod (step_AddSubLt with \"[$Hmap $Hj $Hown $Hpc_a]\") as (retv regs' Hspec) \"(Hj & Hpc_a & Hmap)\"; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    \n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iFrame. incrementPC_inv; simpl in *; simplify_map_eq_alt.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r2 dst) //\n              (insert_commute _ PC dst) // insert_insert. \n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; by iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; simpl in *; simplify_map_eq_alt. \n      incrementPC_inv;[|rewrite lookup_insert_ne// lookup_insert; eauto]. congruence. }\n  Qed.\n\n  Lemma step_add_sub_lt_success_z_dst E K dst pc_p pc_b pc_e pc_a w ins n1 n2 pc_a' :\n    decodeInstrW w = ins \u2192\n    is_AddSubLt ins dst (inl n1) (inr dst) \u2192\n    (pc_a + 1)%a = Some pc_a' \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) ->\n    nclose specN \u2286 E \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable)\n             \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a\n             \u2217 pc_a \u21a3\u2090 w\n             \u2217 dst \u21a3\u1d63 WInt n2\n    ={E}=\u2217 \u2907 fill K (Instr NextI)\n        \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a'\n        \u2217 pc_a \u21a3\u2090 w\n        \u2217 dst \u21a3\u1d63 WInt (denote ins n1 n2).\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc Hnclose) \"(Hown & Hj & HPC & Hpc_a & Hdst)\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iMod (step_AddSubLt with \"[$Hmap $Hj $Hown $Hpc_a]\") as (retv regs' Hspec) \"(Hj & Hpc_a & Hmap)\"; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iFrame. simpl in *. incrementPC_inv; simplify_map_eq_alt.\n      rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; by iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; simpl in *; simplify_map_eq_alt.\n      incrementPC_inv; [|rewrite lookup_insert_ne// lookup_insert; eauto]. congruence. }\n  Qed.\n\n  Lemma step_add_sub_lt_success_dst_z E K dst pc_p pc_b pc_e pc_a w ins n1 n2 pc_a' :\n    decodeInstrW w = ins \u2192\n    is_AddSubLt ins dst (inr dst) (inl n2) \u2192\n    (pc_a + 1)%a = Some pc_a' \u2192\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) ->\n    nclose specN \u2286 E \u2192\n\n    spec_ctx \u2217 \u2907 fill K (Instr Executable)\n             \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a\n             \u2217 pc_a \u21a3\u2090 w\n             \u2217 dst \u21a3\u1d63 WInt n1\n    ={E}=\u2217 \u2907 fill K (Instr NextI)\n        \u2217 PC \u21a3\u1d63 WCap pc_p pc_b pc_e pc_a'\n        \u2217 pc_a \u21a3\u2090 w\n        \u2217 dst \u21a3\u1d63 WInt (denote ins n1 n2).\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc Hnclose) \"(Hown & Hj & HPC & Hpc_a & Hdst)\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iMod (step_AddSubLt with \"[$Hmap $Hj $Hown $Hpc_a]\") as (retv regs' Hspec) \"(Hj & Hpc_a & Hmap)\"; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iFrame. simpl in *. incrementPC_inv; simplify_map_eq_alt.\n      rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; by iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail;simpl in *;simplify_map_eq_alt; eauto.\n      incrementPC_inv;[|rewrite lookup_insert_ne// lookup_insert;eauto]. congruence. }\n  Qed.\n\n  \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_AddSubLt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.19986031569777582}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*          for the C functions implemented in the MALT layer          *)\n(*                                                                     *)\n(*                        David Costanzo                               *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import MemWithData.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import LAsm.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import RealParams.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import ContainerGenSpec.\nRequire Import MALTCSource.\nRequire Import TacticsForTesting.\nRequire Import MALT.\n\nRequire Import AbstractDataType.\nRequire Import CommonTactic.\n\n(*Global Opaque compatdata_layerdata ldata_type.*)\n\nModule MALTCODE.\n\n  (* Helper lemmas related to struct *)\n  Open Scope Z_scope.\n\n  Lemma convert_quota :  forall i, Int.unsigned i < num_id ->\n    Int.unsigned (Int.mul i (Int.repr 20)) + Int.unsigned (Int.repr 0) = Int.unsigned i * CSIZE + QUOTA.\n  Proof.\n    intros i Hi.\n    assert (Hrange:= Int.unsigned_range_2 i).\n    rewrite Int.mul_signed.\n    rewrite 2 Int.signed_eq_unsigned; try rewrite max_signed_val; try omega.\n    rewrite 3 Int.unsigned_repr; eauto; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n  Qed.\n\n  Lemma convert_usage :  forall i, Int.unsigned i < num_id ->\n    Int.unsigned (Int.mul i (Int.repr 20)) + Int.unsigned (Int.repr 4) = Int.unsigned i * CSIZE + USAGE.\n  Proof.\n    intros i Hi.\n    assert (Hrange:= Int.unsigned_range_2 i).\n    rewrite Int.mul_signed.\n    rewrite 2 Int.signed_eq_unsigned; try rewrite max_signed_val; try omega.\n    rewrite 3 Int.unsigned_repr; eauto; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n  Qed.\n\n  Lemma convert_parent :  forall i, Int.unsigned i < num_id ->\n    Int.unsigned (Int.mul i (Int.repr 20)) + Int.unsigned (Int.repr 8) = Int.unsigned i * CSIZE + PARENT.\n  Proof.\n    intros i Hi.\n    assert (Hrange:= Int.unsigned_range_2 i).\n    rewrite Int.mul_signed.\n    rewrite 2 Int.signed_eq_unsigned; try rewrite max_signed_val; try omega.\n    rewrite 3 Int.unsigned_repr; eauto; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n  Qed.\n\n  Lemma convert_nchildren :  forall i, Int.unsigned i < num_id ->\n    Int.unsigned (Int.mul i (Int.repr 20)) + Int.unsigned (Int.repr 12) = Int.unsigned i * CSIZE + NCHILDREN.\n  Proof.\n    intros i Hi.\n    assert (Hrange:= Int.unsigned_range_2 i).\n    rewrite Int.mul_signed.\n    rewrite 2 Int.signed_eq_unsigned; try rewrite max_signed_val; try omega.\n    rewrite 3 Int.unsigned_repr; eauto; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n  Qed.\n\n  Lemma convert_used :  forall i, Int.unsigned i < num_id ->\n    Int.unsigned (Int.mul i (Int.repr 20)) + Int.unsigned (Int.repr 16) = Int.unsigned i * CSIZE + USED.\n  Proof.\n    intros i Hi.\n    assert (Hrange:= Int.unsigned_range_2 i).\n    rewrite Int.mul_signed.\n    rewrite 2 Int.signed_eq_unsigned; try rewrite max_signed_val; try omega.\n    rewrite 3 Int.unsigned_repr; eauto; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n    rewrite Int.unsigned_repr; try rewrite max_unsigned_val; try omega.\n  Qed.\n\n  Close Scope Z_scope.\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n    Opaque PTree.get PTree.set.\n\n    Local Open Scope Z_scope.\n\n    (* Helpers for omega *)\n    Let Hmax := max_unsigned_val.\n    Let Hnps_range := real_nps_range.\n    Let Hquota_range := real_quota_range.\n    Let Hstruct_size : sizeof t_struct_AC = 20. Proof. auto. Qed.\n\n    Section ContainerInit.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops) (cdata_prf:= malt_data_prf)) :=\n        AC_LOC \u21a6 container_loc_type \n               \u2295 mem_init \u21a6 gensem mem_init_spec\n               \u2295 get_nps \u21a6 gensem get_nps_spec\n               \u2295 is_norm \u21a6 gensem is_at_norm_spec\n               \u2295 at_get \u21a6 gensem get_at_u_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section InitBody.\n\n        Context `{Hwb: WritableBlockOps}.\n        Context `{Hwbg: WritableBlockAllowGlobals WB}.\n\n        Variables (s: stencil) (ge: genv).\n        Hypothesis Hstencil_matches: stencil_matches s ge.\n\n        (* AC_LOC *)\n        Variable b_ac: block.\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        (* mem_init *)\n        Variable b_mi : block.\n        Hypothesis hmem_init1 : Genv.find_symbol ge mem_init = Some b_mi. \n        Hypothesis hmem_init2 : Genv.find_funct_ptr ge b_mi =\n          Some (External (EF_external mem_init\n            (signature_of_type (Tcons tint Tnil) Tvoid cc_default)) (Tcons tint Tnil) Tvoid cc_default).\n\n        (* get_nps *)\n        Variable b_nps : block.\n        Hypothesis hnps1 : Genv.find_symbol ge get_nps = Some b_nps.\n        Hypothesis hnps2 : Genv.find_funct_ptr ge b_nps =\n          Some (External (EF_external get_nps\n            (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n         (* is_norm *)\n        Variable b_norm : block.\n        Hypothesis hnorm1 : Genv.find_symbol ge is_norm = Some b_norm. \n        Hypothesis hnorm2 : Genv.find_funct_ptr ge b_norm =\n          Some (External (EF_external is_norm\n            (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        (* at_get *)\n        Variable b_atget : block.\n        Hypothesis hatget1 : Genv.find_symbol ge at_get = Some b_atget.\n        Hypothesis hatget2 : Genv.find_funct_ptr ge b_atget =\n          Some (External (EF_external at_get\n            (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        Section Container_init_loop_proof.\n\n          Variables (minit : memb) (dinit dpreinit : RData).\n          Hypothesis ATinit : AT dinit = real_AT (AT dpreinit).\n          Hypotheses (ikerninit : ikern dinit = true) (ihostinit : ihost dinit = true).\n\n          Definition init_loop_body_P (le: temp_env) (m : mem) : Prop := \n            le ! t_nps = Some (Vint (Int.repr real_nps)) /\\\n            le ! t_rq = Some (Vint (Int.repr 0)) /\\\n            le ! t_i = Some (Vint (Int.repr 1)) /\\ m = (minit, dinit).\n\n          Definition init_loop_body_Q (le : temp_env) (m : mem): Prop :=\n            le ! t_rq = Some (Vint (Int.repr real_quota)) /\\ m = (minit, dinit).\n\n          Lemma container_init_loop_correct : \n            LoopProofSimpleWhile.t container_init_while_condition container_init_while_body \n                                   ge (PTree.empty _) init_loop_body_P init_loop_body_Q.\n          Proof.\n            apply LoopProofSimpleWhile.make with\n              (W := Z) (lt := fun z1 z2 => 0 <= z2 /\\  z1 < z2)\n              (I := fun le m w => \n                      exists i,\n                        0 < i <= real_nps /\\\n                        le ! t_i = Some (Vint (Int.repr i)) /\\\n                        le ! t_nps = Some (Vint (Int.repr real_nps)) /\\\n                        le ! t_rq = Some (Vint (Int.repr (unused_pages_AT (AT dinit) (Z.to_nat (i-1))))) /\\\n                        m = (minit, dinit) /\\ w = real_nps - i).\n            apply Zwf_well_founded.\n            unfold init_loop_body_P; intros le m Hle; decompose [and] Hle; clear Hle; subst.\n            exists (real_nps - 1), 1; repeat (apply conj; try omega; auto).\n            intros le m w [i Hle]; decompose [and] Hle; clear Hle; subst.\n            assert (Hcases: i = real_nps \\/ i < real_nps) by omega; destruct Hcases; subst.\n            {\n              (* while condition is false *)\n              eexists; exists false; repeat split; try discriminate.\n              repeat vcgen.\n              cases; simpl; auto; omega.\n              subrewrite'; repeat f_equal.\n              rewrite real_quota_convert; rewrite real_quota_unused_pages_AT; reflexivity.\n            }\n            {\n              (* while condition is true *)\n              assert (Hi_conv: i = Z.pos (Pos.of_succ_nat (Z.to_nat (i - 1)))).\n              {\n                change (Z.pos (Pos.of_succ_nat (Z.to_nat (i-1)))) with (Z.of_nat (S (Z.to_nat (i-1)))).\n                rewrite Nat2Z.inj_succ; rewrite <- Z.add_1_r.\n                rewrite Z2Nat.id; omega.\n              }\n              eexists; exists true; repeat split; intros; try discriminate.\n              repeat vcgen.\n              cases; simpl; auto.\n              clear Hdestruct; rewrite 2 Int.unsigned_repr in *; omega.\n              destruct (ZMap.get i (AT dinit)) as [[|] t v|] eqn:Hat;\n                try (destruct (ATType_dec t ATNorm); try subst t).\n\n              (* Case 1: u = true, t = ATNorm *)\n              eexists; exists (minit, dinit); repeat split.\n              unfold container_init_while_body; d3 vcgen.\n              (* call is_norm *)\n              repeat vcgen.\n              unfold is_at_norm_spec; rewrites; cases; try omega; try congruence.\n              change 1 with (Int.unsigned (Int.repr 1)); reflexivity.\n              d2 vcgen.\n              (* call at_get *)\n              repeat vcgen.\n              unfold get_at_u_spec; rewrites; cases; try omega.\n              change 1 with (Int.unsigned (Int.repr 1)); reflexivity.\n              d2 vcgen.\n              (* if statement (false) *)\n              repeat vcgen.\n              (* increment i *)\n              repeat vcgen.\n              (* reestablish loop invariant *)\n              exists (real_nps - i - 1); repeat vcgen.\n              exists (i + 1); repeat vcgen.\n              replace (Z.to_nat (i+1-1)) with (S (Z.to_nat (i-1))).\n              simpl; rewrite <- Hi_conv; rewrites; auto.\n              rewrite <- Z2Nat.inj_succ; f_equal; omega.\n\n              (* Case 2: u = true, t <> ATNorm *)\n              eexists; exists (minit, dinit); repeat split.\n              unfold container_init_while_body; d3 vcgen.\n              (* call is_norm *)\n              repeat vcgen.\n              unfold is_at_norm_spec; rewrites; cases; try omega; try congruence.\n              change 0 with (Int.unsigned (Int.repr 0)); reflexivity.\n              d2 vcgen.\n              (* call at_get *)\n              repeat vcgen.\n              unfold get_at_u_spec; rewrites; cases; try omega.\n              change 1 with (Int.unsigned (Int.repr 1)); reflexivity.\n              d2 vcgen.\n              (* if statement (false) *)\n              repeat vcgen.\n              (* increment i *)\n              repeat vcgen.\n              (* reestablish loop invariant *)\n              exists (real_nps - i - 1); repeat vcgen.\n              exists (i + 1); repeat vcgen.\n              replace (Z.to_nat (i+1-1)) with (S (Z.to_nat (i-1))).\n              simpl; rewrite <- Hi_conv; rewrites; auto.\n              rewrite <- Z2Nat.inj_succ; f_equal; omega.\n\n              (* Case 3: u = false, t = ATNorm *)\n              eexists; exists (minit, dinit); repeat split.\n              unfold container_init_while_body; d3 vcgen.\n              (* call is_norm *)\n              repeat vcgen.\n              unfold is_at_norm_spec; rewrites; cases; try omega; try congruence.\n              change 1 with (Int.unsigned (Int.repr 1)); reflexivity.\n              d2 vcgen.\n              (* call at_get *)\n              repeat vcgen.\n              unfold get_at_u_spec; rewrites; cases; try omega.\n              change 0 with (Int.unsigned (Int.repr 0)); reflexivity.\n              d2 vcgen.\n              (* if statement (true) *)\n              repeat vcgen.\n              (* increment i *)\n              assert (Hrange:= unused_pages_AT_range (Z.to_nat (i - 1)) (AT dinit)).\n              rewrite Z2Nat.id in Hrange by omega; repeat vcgen.\n              (* reestablish loop invariant *)\n              exists (real_nps - i - 1); repeat vcgen.\n              exists (i + 1); repeat split; try solve [repeat vcgen].\n              ptreesolve; repeat f_equal.\n              replace (Z.to_nat (i+1-1)) with (S (Z.to_nat (i-1))).\n              simpl; rewrite <- Hi_conv; rewrites; auto; omega.\n              rewrite <- Z2Nat.inj_succ; f_equal; omega.\n\n              (* Case 4: u = false, t <> ATNorm *)\n              eexists; exists (minit, dinit); repeat split.\n              unfold container_init_while_body; d3 vcgen.\n              (* call is_norm *)\n              repeat vcgen.\n              unfold is_at_norm_spec; rewrites; cases; try omega; try congruence.\n              change 0 with (Int.unsigned (Int.repr 0)); reflexivity.\n              d2 vcgen.\n              (* call at_get *)\n              repeat vcgen.\n              unfold get_at_u_spec; rewrites; cases; try omega.\n              change 0 with (Int.unsigned (Int.repr 0)); reflexivity.\n              d2 vcgen.\n              (* if statement (false) *)\n              repeat vcgen.\n              (* increment i *)\n              repeat vcgen.\n              (* reestablish loop invariant *)\n              exists (real_nps - i - 1); repeat vcgen.\n              exists (i + 1); repeat vcgen.\n              replace (Z.to_nat (i+1-1)) with (S (Z.to_nat (i-1))).\n              simpl; rewrite <- Hi_conv; rewrites; destruct t; try congruence; auto.\n              rewrite <- Z2Nat.inj_succ; f_equal; omega.\n              \n              (* Case 5: ATUndef (impossible) *)\n              assert (Hcases: (0 <= i < kern_low \\/ kern_high <= i < real_nps) \\/ \n                      kern_low <= i < Z.min kern_high real_nps) by (rewrite Zmin_spec; cases; omega).\n              rewrite ATinit in Hat; destruct Hcases as [Hi|Hi].\n              rewrite (real_at_kern_valid (AT dpreinit) _ Hi) in Hat; discriminate.\n              destruct (real_at_usr_valid (AT dpreinit) _ Hi) as [? [[? ?]|?]]; rewrites; discriminate.\n            }\n          Qed.\n\n        End Container_init_loop_proof.\n\n        Lemma container_init_while_correct: \n          forall m d pre_d le,\n            ikern d = true -> ihost d = true -> AT d = real_AT (AT pre_d) ->\n            le ! t_nps = Some (Vint (Int.repr real_nps)) ->\n            le ! t_rq = Some (Vint (Int.repr 0)) ->\n            le ! t_i = Some (Vint (Int.repr 1)) ->\n            exists le', \n              exec_stmt ge (PTree.empty _) le ((m, d) : mem) \n                (Swhile container_init_while_condition container_init_while_body) \n                E0 le' (m, d) Out_normal /\\ le' ! t_rq = Some (Vint (Int.repr real_quota)).\n        Proof.\n          intros m d pre_d le Hkern Hhost Hat Hnps Hrq Hi.\n          assert (Hloop:= container_init_loop_correct m _ _ Hat Hkern Hhost).\n          refine (_ (LoopProofSimpleWhile.termination _ _ _ _ _ _ Hloop le (m, d) _)).\n          intros [? [? [? [? ?]]]]; subst; eauto.\n          repeat split; auto.\n        Qed.\n\n        Lemma container_init_body_correct: \n          forall m m' (d d' : cdata RData) (m1 m2 m3 m4 : memb) env le mbi,\n            env = PTree.empty _ -> le ! _mbi = Some (Vint mbi) ->\n            mem_init_spec (Int.unsigned mbi) d = Some d' ->\n            Mem.store Mint32 (m,d') b_ac QUOTA (Vint (Int.repr real_quota)) = Some (m1,d') ->\n            Mem.store Mint32 (m1,d') b_ac USAGE (Vint Int.zero) = Some (m2,d') ->\n            Mem.store Mint32 (m2,d') b_ac PARENT (Vint Int.zero) = Some (m3,d') ->\n            Mem.store Mint32 (m3,d') b_ac NCHILDREN (Vint Int.zero) = Some (m4,d') ->\n            Mem.store Mint32 (m4,d') b_ac USED (Vint Int.one) = Some (m',d') ->\n            exists le',\n              exec_stmt ge env le (m, d) container_init_body E0 le' (m', d') Out_normal.\n        Proof.\n          intros; subst.\n          functional inversion H1; subst d'.\n\n          (* Obtain the final le from the while loop and instantiate based on that *)\n          destruct (container_init_while_correct m \n                      (d {MM : real_mm} {MMSize : real_size} {vmxinfo : real_vmxinfo} \n                         {AT : real_AT (AT d)} {nps : real_nps} {init : true}) d\n                      (PTree.set t_i (Vint (Int.repr 1))\n                         (PTree.set t_rq (Vint (Int.repr 0))\n                            (PTree.set t_nps (Vint (Int.repr real_nps)) le))))\n             as [le' [Hexec ?]]; auto; simpl; ptreesolve; exists le'.\n\n          unfold container_init_body; simpl; repeat vcgen.\n          unfold get_nps_spec; simpl; rewrites.\n          rewrite Int.unsigned_repr; try omega; reflexivity.\n        Qed.\n\n      End InitBody.\n\n      Theorem container_init_code_correct: \n        spec_le (container_init \u21a6 container_init_spec_low) \n                (\u301acontainer_init \u21a6 f_container_init\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_init_body_correct _ _ makeglobalenv _ H0 _ Hb2fs Hb2fp \n                    _ Hb3fs Hb3fp _ Hb4fs Hb4fp _ Hb5fs Hb5fp\n                    m0 m'0 labd labd' m1 m2 m3 m4 (PTree.empty _)\n                   (bind_parameter_temps' (fn_params f_container_init) (Vint mbi :: nil)\n                      (create_undef_temps (fn_temps f_container_init)))) tt.\n      Qed.\n\n    End ContainerInit.\n\n    Section ContainerGetParent.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section GetParentBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        Lemma container_get_parent_body_correct: \n          forall m d env le v i,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) -> 0 <= Int.unsigned i < num_id ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + PARENT) = Some (Vint v) ->\n            exec_stmt ge env le (m, d) container_get_parent_body E0 le (m, d) (Out_return (Some (Vint v, tint))).\n        Proof.\n          intros; subst; unfold PARENT in *.\n          unfold container_get_parent_body; simpl; repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n        Qed.\n\n      End GetParentBody.\n\n      Theorem container_get_parent_code_correct: \n        spec_le (container_get_parent \u21a6 container_get_parent_spec_low) \n                (\u301acontainer_get_parent \u21a6 f_container_get_parent\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_get_parent_body_correct _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_get_parent) (Vint i :: nil) (PTree.empty _))) m'.\n      Qed.\n\n    End ContainerGetParent.\n\n    Section ContainerGetNchildren.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section GetNchildrenBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        Lemma container_get_nchildren_body_correct: \n          forall m d env le v i,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) -> 0 <= Int.unsigned i < num_id ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + NCHILDREN) = Some (Vint v) ->\n            exec_stmt ge env le (m, d) container_get_nchildren_body E0 le (m, d) (Out_return (Some (Vint v, tint))).\n        Proof.\n          intros; subst; unfold NCHILDREN in *.\n          unfold container_get_nchildren_body; simpl; repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n        Qed.\n\n      End GetNchildrenBody.\n\n      Theorem container_get_nchildren_code_correct: \n        spec_le (container_get_nchildren \u21a6 container_get_nchildren_spec_low) \n                (\u301acontainer_get_nchildren \u21a6 f_container_get_nchildren\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_get_nchildren_body_correct _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_get_nchildren) (Vint i :: nil) (PTree.empty _))) m'.\n      Qed.\n\n    End ContainerGetNchildren.\n\n    Section ContainerGetQuota.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section GetQuotaBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        Lemma container_get_quota_body_correct: \n          forall m d env le v i,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) -> 0 <= Int.unsigned i < num_id ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + QUOTA) = Some (Vint v) ->\n            exec_stmt ge env le (m, d) container_get_quota_body E0 le (m, d) (Out_return (Some (Vint v, tint))).\n        Proof.\n          intros; subst; unfold QUOTA in *.\n          unfold container_get_quota_body; simpl; repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n        Qed.\n\n      End GetQuotaBody.\n\n      Theorem container_get_quota_code_correct: \n        spec_le (container_get_quota \u21a6 container_get_quota_spec_low) \n                (\u301acontainer_get_quota \u21a6 f_container_get_quota\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_get_quota_body_correct _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_get_quota) (Vint i :: nil) (PTree.empty _))) m'.\n      Qed.\n\n    End ContainerGetQuota.\n\n    Section ContainerGetUsage.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section GetUsageBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        Lemma container_get_usage_body_correct: \n          forall m d env le v i,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) -> 0 <= Int.unsigned i < num_id ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + USAGE) = Some (Vint v) ->\n            exec_stmt ge env le (m, d) container_get_usage_body E0 le (m, d) (Out_return (Some (Vint v, tint))).\n        Proof.\n          intros; subst; unfold USAGE in *.\n          unfold container_get_usage_body; simpl; repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n        Qed.\n\n      End GetUsageBody.\n\n      Theorem container_get_usage_code_correct: \n        spec_le (container_get_usage \u21a6 container_get_usage_spec_low) \n                (\u301acontainer_get_usage \u21a6 f_container_get_usage\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_get_usage_body_correct _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_get_usage) (Vint i :: nil) (PTree.empty _))) m'.\n      Qed.\n\n    End ContainerGetUsage.\n\n    Section ContainerCanConsume.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section CanConsumeBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        Lemma container_can_consume_body_correct: \n          forall m d env le i n q u,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) -> le ! _n = Some (Vint n) ->\n            0 <= Int.unsigned i < num_id ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + QUOTA) = Some (Vint q) ->\n            Mem.load Mint32 (m, d) b_ac (Int.unsigned i * CSIZE + USAGE) = Some (Vint u) ->\n            exec_stmt ge env le (m, d) container_can_consume_body E0 le (m, d) \n              (Out_return (Some (Vint \n                 (match (Int.unsigned n <=? Int.unsigned q, \n                         Int.unsigned u <=? Int.unsigned q - Int.unsigned n) with\n                  | (true, true) => Int.one \n                  | _ => Int.zero end), tint))).\n        Proof.\n          intros; subst.\n\n          assert (((Int.unsigned n <=? Int.unsigned q) = true /\\ \n                   (Int.unsigned u <=? Int.unsigned q - Int.unsigned n) = true) \\/\n                  ((Int.unsigned n <=? Int.unsigned q) = true /\\ \n                   (Int.unsigned u <=? Int.unsigned q - Int.unsigned n) = false) \\/\n                  (Int.unsigned n <=? Int.unsigned q) = false) as Hcases.\n          destruct (Int.unsigned n <=? Int.unsigned q); auto.\n          destruct (Int.unsigned u <=? Int.unsigned q - Int.unsigned n); auto.\n\n          destruct Hcases as [Hcase1|Hcase2].\n          (* Case 1: n <= q && u <= q - n *)\n          destruct Hcase1 as [Hle1 Hle2].\n          rewrite Hle1; rewrite Hle2.\n          vcgen; vcgen; try discriminate.\n          vcgen; simpl.\n          {\n            vcgen; vcgen; eauto.\n            vcgen; vcgen.\n            vcgen; vcgen; vcgen; vcgen; eauto.\n            apply deref_loc_reference; auto.\n            simpl; unfold sem_add; simpl; unfold align; simpl.\n            rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n            apply deref_loc_copy; auto.\n            apply deref_loc_value with (chunk := Mint32); auto.\n            unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n            rewrite Int.add_unsigned.\n            rewrite Int.unsigned_repr; rewrite convert_quota; try rewrite max_unsigned_val; eauto;\n              unfold CSIZE; unfold QUOTA; omega.\n            vcgen.\n          }\n          {\n            vcgen; simpl; unfold bool_val; simpl.\n            destruct (zlt (Int.unsigned q) (Int.unsigned n)); simpl; unfold Int.eq.\n            rewrite Z.leb_le in Hle1; omega.\n            destruct (zeq (Int.unsigned Int.one) (Int.unsigned Int.zero)); simpl.\n            inv e.\n            eauto.\n          }\n          {\n            vcgen; simpl.\n            vcgen.\n            vcgen.\n            vcgen.\n            vcgen; vcgen.\n            vcgen.\n            vcgen.\n            vcgen; eauto.\n            apply deref_loc_reference; auto.\n            vcgen; eauto.\n            simpl; unfold sem_add; simpl; unfold align; simpl.\n            rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n            apply deref_loc_copy; auto.\n            vcgen.\n            vcgen.\n            apply deref_loc_value with (chunk := Mint32); auto.\n            unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n            rewrite Int.add_unsigned.\n            rewrite Int.unsigned_repr; rewrite convert_usage; try rewrite max_unsigned_val; eauto;\n              unfold CSIZE; unfold USAGE; omega.\n            vcgen.\n            vcgen.\n            vcgen.\n            vcgen.\n            vcgen; vcgen.\n            vcgen.\n            vcgen; eauto.\n            apply deref_loc_reference; auto.\n            vcgen; eauto.\n            simpl; unfold sem_add; simpl; unfold align; simpl.\n            rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n            apply deref_loc_copy; auto.\n            vcgen.\n            vcgen.\n            apply deref_loc_value with (chunk := Mint32); auto.\n            unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n            rewrite Int.add_unsigned.\n            rewrite Int.unsigned_repr; rewrite convert_quota; try rewrite max_unsigned_val; eauto;\n              unfold CSIZE; unfold QUOTA; omega.\n            vcgen; eauto.\n            vcgen.\n            vcgen.\n            simpl.\n            rewrite Int.unsigned_repr.\n            destruct (zlt (Int.unsigned q - Int.unsigned n) (Int.unsigned u)).\n            rewrite Z.leb_le in Hle2; omega.\n            vcgen.\n            rewrite Z.leb_le in Hle1; assert (Hrange := Int.unsigned_range_2 q).\n            rewrite max_unsigned_val in Hrange |- *.\n            split; try omega.\n            apply Z.le_trans with (m := Int.unsigned q); try omega.\n            assert (Hrange' := Int.unsigned_range_2 n); omega.\n            simpl; vcgen; vcgen.\n          }\n\n          (* Case 2: (n <= q && u > q - n) || n > q *)\n          replace E0 with (E0 ** E0).\n          vcgen; vcgen.\n          {            \n            destruct Hcase2 as [[Hle1 Hle2]|Hle].\n\n            (* Case 2A: n <= q && u > q - n *)\n            vcgen.\n            {\n              vcgen; vcgen; eauto.\n              vcgen.\n              vcgen.\n              vcgen; vcgen.\n              vcgen; vcgen; eauto.\n              apply deref_loc_reference; auto.\n              vcgen; eauto.\n              simpl; unfold sem_add; simpl; unfold align; simpl.\n              rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n              apply deref_loc_copy; auto.\n              vcgen.\n              vcgen.\n              apply deref_loc_value with (chunk := Mint32); auto.\n              unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n              rewrite Int.add_unsigned.\n              rewrite Int.unsigned_repr; rewrite convert_quota; try rewrite max_unsigned_val; eauto;\n                unfold CSIZE; unfold QUOTA; omega.\n              vcgen; eauto.\n            }\n            {\n              simpl; destruct (zlt (Int.unsigned q) (Int.unsigned n)).\n              rewrite Z.leb_le in Hle1; omega.\n              vcgen.\n            }\n            {\n              vcgen.\n              vcgen; vcgen; eauto.\n              vcgen.\n              vcgen.\n              vcgen; vcgen.\n              vcgen; vcgen; eauto.\n              apply deref_loc_reference; auto.\n              vcgen; eauto.\n              simpl; unfold sem_add; simpl; unfold align; simpl.\n              rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n              apply deref_loc_copy; auto.\n              vcgen.\n              vcgen.\n              apply deref_loc_value with (chunk := Mint32); auto.\n              unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n              rewrite Int.add_unsigned.\n              rewrite Int.unsigned_repr; rewrite convert_usage; try rewrite max_unsigned_val; eauto;\n                unfold CSIZE; unfold USAGE; omega.\n              vcgen; eauto.\n              vcgen.\n              vcgen.\n              vcgen.\n              vcgen.\n              vcgen; vcgen.\n              vcgen.\n              vcgen; eauto.\n              apply deref_loc_reference; auto.\n              vcgen; eauto.\n              simpl; unfold sem_add; simpl; unfold align; simpl.\n              rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n              apply deref_loc_copy; auto.\n              vcgen.\n              vcgen.\n              apply deref_loc_value with (chunk := Mint32); auto.\n              unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n              rewrite Int.add_unsigned.\n              rewrite Int.unsigned_repr; rewrite convert_quota; try rewrite max_unsigned_val; eauto;\n                unfold CSIZE; unfold QUOTA; omega.\n              vcgen; eauto.\n              vcgen.\n              vcgen.\n              simpl.\n              rewrite Int.unsigned_repr.\n              destruct (zlt (Int.unsigned q - Int.unsigned n) (Int.unsigned u)).\n              vcgen.\n              rewrite Z.leb_nle in Hle2; omega.\n              rewrite Z.leb_le in Hle1; assert (Hrange := Int.unsigned_range_2 q).\n              rewrite max_unsigned_val in Hrange |- *.\n              split; try omega.\n              apply Z.le_trans with (m := Int.unsigned q); try omega.\n              assert (Hrange' := Int.unsigned_range_2 n); omega.\n              simpl; vcgen.\n            }\n\n            (* Case 2B: n > q *)\n            vcgen.\n            vcgen; vcgen; eauto.\n            vcgen.\n            vcgen.\n            vcgen; vcgen.\n            vcgen; vcgen; eauto.\n            apply deref_loc_reference; auto.\n            vcgen; eauto.\n            simpl; unfold sem_add; simpl; unfold align; simpl.\n            rewrite Int.add_zero_l; rewrite Int.mul_commut; auto.\n            apply deref_loc_copy; auto.\n            vcgen.\n            vcgen.\n            apply deref_loc_value with (chunk := Mint32); auto.\n            unfold Mem.loadv; unfold align; simpl; unfold lift; simpl.\n            rewrite Int.add_unsigned.\n            rewrite Int.unsigned_repr; rewrite convert_quota; try rewrite max_unsigned_val; eauto;\n              unfold CSIZE; unfold QUOTA; omega.\n            vcgen; eauto.\n            simpl.\n            destruct (zlt (Int.unsigned q) (Int.unsigned n)).            \n            vcgen.\n            rewrite Z.leb_nle in Hle; omega.\n            simpl; vcgen.\n          }\n          {\n            destruct Hcase2 as [[Hle1 Hle2]|Hle].\n            rewrite Hle1; rewrite Hle2; vcgen; vcgen.\n            rewrite Hle; vcgen; vcgen.\n          }\n          {\n            simpl; auto.\n          }\n        Qed.\n\n      End CanConsumeBody.\n\n      Theorem container_can_consume_code_correct: \n        spec_le (container_can_consume \u21a6 container_can_consume_spec_low) \n                (\u301acontainer_can_consume \u21a6 f_container_can_consume\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_can_consume_body_correct _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_can_consume) \n                   (Vint i :: Vint n :: nil) (PTree.empty _))) m'.\n      Qed.\n\n    End ContainerCanConsume.\n\n    Section ContainerSplit.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) :=\n        AC_LOC \u21a6 container_loc_type.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section SplitBody.\n\n        Context `{Hwb: WritableBlockOps}.\n        Context `{Hwbg: WritableBlockAllowGlobals WB}.\n\n        Variable (s: stencil).\n\n        Variables (ge: genv) (b_ac b_bl: block).\n\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        (* Parameters *)\n        Variables (i q : int).\n\n        Lemma container_split_body_correct: \n          forall m m' (d : cdata RData) env j u nc (m1 m2 m3 m4 m5 m6: memb),\n            env = PTree.empty _ -> 0 <= Int.unsigned i < num_id -> 0 <= Int.unsigned j < num_id ->\n            Int.unsigned j = Int.unsigned i * max_children + 1 + Int.unsigned nc -> \n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + USAGE) = Some (Vint u) ->\n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + NCHILDREN) = Some (Vint nc) ->\n            Mem.store Mint32 (m,d) b_ac (Int.unsigned j * CSIZE + USED) (Vint Int.one) = Some (m1,d) ->\n            Mem.store Mint32 (m1,d) b_ac (Int.unsigned j * CSIZE + QUOTA) (Vint q) = Some (m2,d) ->\n            Mem.store Mint32 (m2,d) b_ac (Int.unsigned j * CSIZE + USAGE) (Vint Int.zero) = Some (m3,d) ->\n            Mem.store Mint32 (m3,d) b_ac (Int.unsigned j * CSIZE + PARENT) (Vint i) = Some (m4,d) ->\n            Mem.store Mint32 (m4,d) b_ac (Int.unsigned j * CSIZE + NCHILDREN) (Vint Int.zero) = Some (m5,d) ->\n            Mem.store Mint32 (m5,d) b_ac (Int.unsigned i * CSIZE + USAGE) (Vint (Int.add u q)) = Some (m6,d) ->\n            Mem.store Mint32 (m6,d) b_ac (Int.unsigned i * CSIZE + NCHILDREN) (Vint (Int.add nc Int.one)) = Some (m',d) ->\n            exists le,\n              exec_stmt ge env (PTree.set _n (Vint q) (PTree.set _id (Vint i) (create_undef_temps (fn_temps f_container_split)))) \n                      (m, d) container_split_body E0 le (m', d) (Out_return (Some (Vint j, tint))).\n        Proof.\n          intros; subst.\n          rename H2 into Hj, H5 into Hs1, H6 into Hs2, H7 into Hs3, H8 into Hs4, H9 into Hs5,\n                 H10 into Hs6, H11 into Hs7.\n\n          assert (Hsep: forall m k1 k2 a b : Z, a <> b -> 0 <= m ->\n                      0 <= k1 -> k1 + size_chunk Mint32 <= m -> 0 <= k2 -> k2 + size_chunk Mint32 <= m -> \n                      a * m + k1 + size_chunk Mint32 <= b * m + k2 \\/ b * m + k2 + size_chunk Mint32 <= a * m + k1).\n          intros m0 k1 k2 a1 a2 Ha_neq Hm_0 Hk1_0 Hle1 Hk2_0 Hle2.\n          assert (a1 < a2 \\/ a2 < a1) as Ha; try omega.\n          destruct Ha; [left | right].\n          apply Z.le_trans with (m := a1 * m0 + m0); try omega.\n          replace (a1 * m0 + m0) with ((a1 + 1) * m0).\n          assert (a1 + 1 <= a2) as Hle_a; try omega.\n          apply Z.mul_le_mono_nonneg_r with (p := m0) in Hle_a; auto; omega.\n          rewrite Z.mul_add_distr_r; omega.\n          apply Z.le_trans with (m := a2 * m0 + m0); try omega.\n          replace (a2 * m0 + m0) with ((a2 + 1) * m0).\n          assert (a2 + 1 <= a1) as Hle_a; try omega.\n          apply Z.mul_le_mono_nonneg_r with (p := m0) in Hle_a; auto; omega.\n          rewrite Z.mul_add_distr_r; omega.\n          unfold CSIZE, QUOTA, USAGE, PARENT, NCHILDREN, USED in *.\n          unfold size_chunk in Hsep.\n\n          assert (Hneq: Int.unsigned i <> Int.unsigned j)\n            by (assert (Hrange:= Int.unsigned_range nc); omega).\n\n          exists ((PTree.set t_child (Vint j) (PTree.set t_nc (Vint nc) \n                  (PTree.set _n (Vint q) (PTree.set _id (Vint i)\n                     (create_undef_temps (fn_temps f_container_split))))))).\n          unfold container_split_body; simpl; d3 vcgen.\n          (* set t_nc *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* set t_child *)\n          repeat vcgen.\n          d3 vcgen.\n          (* set child's USED *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; rewrite Hj in *; repeat vcgen.\n          d2 vcgen.\n          (* set child's QUOTA *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; rewrite Hj in *; repeat vcgen.\n          d2 vcgen.\n          (* set child's USAGE *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; rewrite Hj in *; repeat vcgen.\n          d2 vcgen.\n          (* set child's PARENT *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; rewrite Hj in *; repeat vcgen.\n          d2 vcgen.\n          (* set child's NCHILDREN *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; rewrite Hj in *; repeat vcgen.\n          d2 vcgen.\n          (* increase parent's USAGE *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          rewrite (Mem.load_store_other _ _ _ _ _ _ Hs5); try solve [right; apply Hsep; auto; try omega].\n          rewrite (Mem.load_store_other _ _ _ _ _ _ Hs4); try solve [right; apply Hsep; auto; try omega].\n          rewrite (Mem.load_store_other _ _ _ _ _ _ Hs3); try solve [right; apply Hsep; auto; try omega].\n          rewrite (Mem.load_store_other _ _ _ _ _ _ Hs2); try solve [right; apply Hsep; auto; try omega].\n          rewrite (Mem.load_store_other _ _ _ _ _ _ Hs1); try solve [right; apply Hsep; auto; try omega]; eauto.\n          repeat vcgen.\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* increment parent's NCHILDREN *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; repeat vcgen.\n          replace j with (Int.repr (Int.unsigned i * 3 + 1 + Int.unsigned nc)).\n          repeat vcgen.\n          apply f_equal with (f:= Int.repr) in Hj.\n          rewrite Int.repr_unsigned in Hj; congruence.\n        Qed.\n\n      End SplitBody.\n\n      Theorem container_split_code_correct: \n        spec_le (container_split \u21a6 container_split_spec_low) \n                (\u301acontainer_split \u21a6 f_container_split\u301b L).\n      Proof.\n        fbigstep_pre L.\n        repeat (match goal with\n                | [ H : _ = _ /\\ _ = _ |- _ ] => destruct H\n                end).\n\n        fbigstep (container_split_body_correct _ _ H i n (fst m) (fst m') (snd m) (PTree.empty _)\n                     j u nc (fst m1) (fst m2) (fst m3) (fst m4) (fst m5) (fst m6)) m.\n        rewrite <- H22 in H24; rewrite <- H23 in H24; inv H24.\n        rewrite <- H22 in H24; rewrite <- H23 in H24; inv H24.\n        destruct m'; auto.\n      Qed.\n\n    End ContainerSplit.\n\n    Section ContainerAlloc.\n\n      Let L: compatlayer (cdata RData (cdata_ops:= malt_data_ops)) := \n        AC_LOC \u21a6 container_loc_type \u2295 palloc \u21a6 gensem palloc'_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section AllocBody.\n\n        Context `{Hwb: WritableBlockOps}.\n        Context `{Hwbg: WritableBlockAllowGlobals WB}.\n\n        Variables (s: stencil) (ge: genv).\n        Hypothesis Hstencil_matches: stencil_matches s ge.\n        \n        Variable b_ac: block.\n        Hypothesis hac_loc1 : Genv.find_symbol ge AC_LOC = Some b_ac.\n\n        (* palloc *)\n        Variable b_palloc : block.\n        Hypothesis hpalloc1 : Genv.find_symbol ge palloc = Some b_palloc.\n        Hypothesis hpalloc2 : Genv.find_funct_ptr ge b_palloc =\n          Some (External (EF_external palloc\n            (signature_of_type Tnil tint cc_default)) Tnil tint cc_default).\n\n        Lemma container_alloc_body_correct0: \n          forall m d env le i u,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) ->\n            0 <= Int.unsigned i < num_id -> \n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + USAGE) = Some (Vint u) ->\n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + QUOTA) = Some (Vint u) ->  \n            exec_stmt ge env le (m,d) container_alloc_body E0 \n                      (PTree.set t_q (Vint u) (PTree.set t_u (Vint u) le))\n                      (m,d) (Out_return (Some (Vzero,tint))).\n        Proof.\n          intros; subst.\n          unfold container_alloc_body; simpl.\n          d3 vcgen.     \n          (* load usage into u *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* load quota into q *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          (* evaluate if statement to true and return 0 *)\n          apply exec_Sseq_2; try discriminate; repeat vcgen.\n        Qed.\n\n        Lemma container_alloc_body_correct1: \n          forall m m' (d d' : cdata RData) env le i u q pi,\n            env = PTree.empty _ -> le ! _id = Some (Vint i) ->\n            0 <= Int.unsigned i < num_id -> Int.unsigned u < Int.unsigned q ->\n            0 <= pi <= Int.max_unsigned -> palloc'_spec d = Some (d', pi) ->\n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + USAGE) = Some (Vint u) ->\n            Mem.load Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + QUOTA) = Some (Vint q) ->\n            Mem.store Mint32 (m,d) b_ac (Int.unsigned i * CSIZE + USAGE) (Vint (Int.add u Int.one)) = Some (m',d) ->\n            exec_stmt ge env le (m,d) container_alloc_body E0\n                      (PTree.set t_i (Vint (Int.repr pi)) \n                         (PTree.set t_q (Vint q) \n                            (PTree.set t_u (Vint u) le)))\n                      (m',d') (Out_return (Some (Vint (Int.repr pi), tint))).\n        Proof.\n          intros; subst.\n          unfold container_alloc_body; simpl.\n          d3 vcgen.\n          (* load usage into u *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* load quota into q *)\n          repeat vcgen.\n          unfold Mem.loadv; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* evaluate if statement to false and skip over it *)\n          repeat vcgen.\n          d2 vcgen.\n          (* increment usage *)\n          repeat vcgen.\n          unfold Mem.storev; rewrite Z.mul_comm; repeat vcgen.\n          d2 vcgen.\n          (* call palloc *)\n          repeat vcgen.\n          (* return pi *)\n          repeat vcgen.\n        Qed.\n\n      End AllocBody.\n\n      Theorem container_alloc_code_correct: \n        spec_le (container_alloc \u21a6 container_alloc_spec_low) \n                (\u301acontainer_alloc \u21a6 f_container_alloc\u301b L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (container_alloc_body_correct0 _ _ H (fst m') (snd m') (PTree.empty _) \n                   (bind_parameter_temps' (fn_params f_container_alloc) (Vint i :: nil)\n                      (create_undef_temps (fn_temps f_container_alloc)))) m'.\n        fbigstep (container_alloc_body_correct1 _ _ makeglobalenv _ H0 _ Hb2fs Hb2fp \n                    m0 m'0 d d' (PTree.empty _) \n                    (bind_parameter_temps' (fn_params f_container_alloc) (Vint i :: nil)\n                      (create_undef_temps (fn_temps f_container_alloc)))) tt.\n      Qed.\n\n    End ContainerAlloc.\n\n  End WithPrimitives.\n\nEnd MALTCODE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MALTCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1998603136561916}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n\n(** Broke out the reasoning for the \"masked jumps\" used in the NaCL verifier\n    so I don't have to wait for long compile times on DFACorrectness.v\n*)\nRequire Import Coqlib.\nRequire Import Parser.\nRequire Import Ascii.\nRequire Import String.\nRequire Import List.\nRequire Import Bits.\nRequire Import Decode.\nRequire Import ReinsVerifierDFA.\nRequire Import Eqdep.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\nRequire ExtrOcamlNatInt.\nImport X86_PARSER_ARG.\nImport X86_PARSER.\nImport X86_BASE_PARSER.\nImport X86Syntax.\nRequire Import ReinsDFACorrectness.\nHint Constructors in_parser.\n\nImport ABSTRACT_MAKE_DFA.\n\nLemma reinsjmp_nonIAT_parser_splits' : \n  forall s v, \n    in_parser reinsjmp_nonIAT_mask (flat_map byte_explode s) v -> \n    exists s1, exists s2, exists r,\n      (r <> ESP /\\ \n      flat_map byte_explode s = s1 ++ s2 /\\\n      in_parser (reinsjmp_nonIAT_MASK_p r) s1 (fst v) /\\ \n      in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 (snd v)) \\/\n      (r = EAX /\\\n      flat_map byte_explode s = s1 ++ s2 /\\\n      in_parser reinsjmp_nonIAT_MASK_EAX25_p s1 (fst v) /\\\n      in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 (snd v)).\nProof.\n  unfold reinsjmp_nonIAT_mask, reinsjmp_nonIAT_p, reinsjmp_nonIAT_EAX25_p. simpl. unfold never.\n  intros.\n    repeat pinv ; \n      simpl ;\n      econstructor ; econstructor ; econstructor ; \n      (left ; repeat split ; eauto ; try congruence ;\n      match goal with \n      | [ H : in_parser (reinsjmp_nonIAT_JMP_p _) _ _ |- _ ] => eapply Alt_left_pi\n      | [ H : in_parser (reinsjmp_nonIAT_CALL_p _) _ _ |- _ ] => eapply Alt_right_pi\n      end ; exact H0) ||\n      (right ; repeat split ; eauto ; try congruence ; \n      match goal with \n      | [ H : in_parser (reinsjmp_nonIAT_JMP_p _) _ _ |- _ ] => eapply Alt_left_pi\n      | [ H : in_parser (reinsjmp_nonIAT_CALL_p _) _ _ |- _ ] => eapply Alt_right_pi\n      end ; exact H0).\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_parser_splits' : \n  forall s v, \n    in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode s) v -> \n    exists s1, exists s2,\n      flat_map byte_explode s = s1 ++ s2 /\\\n      in_parser (reinsjmp_IAT_or_RET_MASK_p) s1 (fst v) /\\ \n      in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s2 (snd v).\nProof.\n  unfold reinsjmp_IAT_JMP_or_RET_mask, reinsjmp_IAT_JMP_or_RET_p. simpl. unfold never.\n    intros. \n      repeat pinv ; simpl ; \n      econstructor ; econstructor ; econstructor ;\n      repeat split ; eauto ; try congruence ;\n      match goal with \n      | [ H : in_parser (reinsjmp_IAT_JMP_p) _ _ |- _ ] => eapply Alt_left_pi\n      | [ H : in_parser (RET_p) _ _ |- _ ] => eapply Alt_right_pi\n      end ; exact H0.\nQed.\n\nLemma byte_explode_bits b : \n  exists b1,exists b2,exists b3,exists b4,exists b5,exists b6,exists b7,exists b8,\n    byte_explode b = b1::b2::b3::b4::b5::b6::b7::b8::nil.\nProof.\n  unfold byte_explode. repeat econstructor.\nQed.\n\nLocal Open Scope nat_scope.\nLemma split_bytes_n : \n  forall n bs x1 x2,\n    flat_map byte_explode bs = x1 ++ x2 ->\n    length x1 = n * 8 -> \n    exists b1, exists b2, \n      bs = b1 ++ b2 /\\ flat_map byte_explode b1 = x1 /\\ flat_map byte_explode b2 = x2.\nProof.\n  induction n ; simpl ; intros.\n  destruct x1. simpl in *. exists nil. exists bs. simpl. auto.\n  simpl in H0. congruence.\n\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n  destruct x1. simpl in H0. assert False ; [omega | contradiction].\n\n  simpl in H0. assert (length x1 = n*8). omega.\n  destruct bs.\n    simpl in H. congruence.\n  \n    replace (flat_map byte_explode (i :: bs)) with \n      (byte_explode i ++ flat_map byte_explode bs) in H; auto.\n    generalize (byte_explode_bits i). t. rewrite H2 in *.\n    injection H . clear H. intros. subst.\n    specialize (IHn bs x1 x2 H H1). t. \n    exists (i::x). exists x0.\n    replace (flat_map byte_explode (i :: x)) with\n      (byte_explode i ++ (flat_map byte_explode x)) ; auto.\n    rewrite H2. split.\n      simpl. rewrite H3. reflexivity.\n      split.\n        rewrite H4. auto.\n        auto.\nQed.\n\nLemma reinsjmp_nonIAT_parser_splits : \n  forall bs v,\n    in_parser reinsjmp_nonIAT_mask (flat_map byte_explode bs) v -> \n    exists b1, exists b2, exists r,\n      (r <> ESP /\\ \n      bs = b1 ++ b2 /\\ \n      in_parser (reinsjmp_nonIAT_MASK_p r) (flat_map byte_explode b1) (fst v) /\\ \n      in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) (flat_map byte_explode b2) (snd v)) \\/\n      (r = EAX /\\ \n      bs = b1 ++ b2 /\\ \n      in_parser reinsjmp_nonIAT_MASK_EAX25_p (flat_map byte_explode b1) (fst v) /\\ \n      in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) (flat_map byte_explode b2) (snd v)).\nProof.\n  intros.\n  generalize (reinsjmp_nonIAT_parser_splits' _ H). t. destruct H0. t.\n  assert (length x = 48).\n    unfold reinsjmp_nonIAT_MASK_p in H2. unfold bitsleft in H2.\n    unfold int32_p in H2. simpl in H2. repeat pinv ; simpl.\n    reflexivity. reflexivity.\n  generalize (split_bytes_n 6 _ _ _ H1 H4). t.\n    exists x2. exists x3. exists x1.\n    left. repeat split ; auto.\n      rewrite H6. exact H2.\n      rewrite H7. exact H3.\n  t. assert (length x = 40).\n    unfold reinsjmp_nonIAT_MASK_EAX25_p in H2. unfold bitsleft in H2.\n    unfold int32_p in H2. simpl in H2. repeat pinv ; simpl.\n    reflexivity. reflexivity.\n  generalize (split_bytes_n 5 _ _ _ H1 H4). t.\n    exists x2. exists x3. exists x1.\n    right. repeat split ; auto.\n      rewrite H6. exact H2.\n      rewrite H7. exact H3.\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_parser_splits : \n  forall bs v,\n    in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode bs) v -> \n    exists b1, exists b2,\n      bs = b1 ++ b2 /\\ \n      in_parser reinsjmp_IAT_or_RET_MASK_p (flat_map byte_explode b1) (fst v) /\\ \n      in_parser (reinsjmp_IAT_JMP_p |+| RET_p) (flat_map byte_explode b2) (snd v).\nProof.\n  intros. generalize (reinsjmp_IAT_JMP_or_RET_parser_splits' _ H). t.\n  assert (length x = 56).\n    unfold reinsjmp_IAT_or_RET_MASK_p in H1. unfold bitsleft in H1.\n    unfold int32_p in H1. simpl in H1. repeat pinv ; simpl ; auto.\n  generalize (split_bytes_n 7 _ _ _ H0 H3). t. exists x1. exists x2.\n    repeat split ; auto.\n      rewrite H5. exact H1.\n      rewrite H6. exact H2.\nQed.\n\nImport CheckDeterministic.\n\nLemma byte2token_app xs n1 n2 :\n  List.map byte2token xs = n1 ++ n2 -> \n  exists b1, exists b2, \n    xs = b1 ++ b2 /\\ List.map byte2token b1 = n1 /\\ List.map byte2token b2 = n2.\nProof.\n  induction xs.\n    simpl. intros. generalize (nil_is_nil_app_nil _ _ H). t. subst.\n    exists nil. exists nil. auto.\n\n    simpl. intros. destruct n1.\n      simpl in *. destruct n2 ; try congruence.\n      injection H . clear H. intros. specialize (IHxs nil n2 H). t. subst.\n      exists x. exists (a::x0).\n      assert (x = nil).\n        destruct x ; auto. simpl in H2. congruence. subst. simpl. auto.\n     simpl in *. injection H. clear H. intros.\n     specialize (IHxs n1 n2 H). t.\n     exists (a::x). exists x0. rewrite H1.\n     split ; auto. simpl.\n     split.\n       rewrite H0. rewrite H2. reflexivity.\n       exact H3.\nQed.\n\nLemma nat2bools_byte2token_is_byte_explode xs : \n  flat_map nat2bools (List.map byte2token xs) = flat_map byte_explode xs.\nProof.\n  induction xs.\n    auto.\n    replace (flat_map byte_explode (a::xs)) with \n      (byte_explode a ++ (flat_map byte_explode xs)) ; auto.\n    replace (flat_map nat2bools (List.map byte2token (a::xs))) with\n      (nat2bools (byte2token a) ++ (flat_map nat2bools (List.map byte2token xs))) ; auto.\n    rewrite IHxs. replace (nat2bools (byte2token a)) with (byte_explode a) ; auto.\n    clear IHxs. unfold byte_explode, nat2bools.\n    replace (Z_of_nat (byte2token a)) with (Word.unsigned a) ; auto.\n    unfold byte2token.\n    rewrite inj_Zabs_nat. unfold Word.unsigned. generalize (Word.intrange _ a).\n    intros. rewrite (Zabs_eq _).  reflexivity. omega.\nQed.\n\nLemma reg_parser r s : \n  in_parser (bitslist (register_to_bools r)) s tt -> \n  in_parser reg s r.\nProof.\n  unfold reg, field. destruct r ; simpl ; intros ; repeat pinv ; \n  repeat econstructor ; eauto.\nQed.\n\nLemma mask_parser s : \n  in_parser (int32_p safeMask) s tt -> \n  in_parser (word @ (fun w : int32 => Imm_op w %% operand_t)) s (Imm_op safeMask).\nProof.\n  unfold word, byte, field, int32_p. simpl. intros.\n  repeat pinv.\n    repeat econstructor. repeat rewrite <- app_assoc.\n    repeat rewrite -> app_nil_l. eexists. vm_compute. reflexivity.\nQed.\n\nLemma mask_parser' s : \n  in_parser (int32_p safeMask) s tt -> \n  in_parser word s safeMask.\nProof.\n  unfold word, byte, field, int32_p. simpl. intros.\n  repeat pinv.\n    repeat econstructor. repeat rewrite <- app_assoc.\n    repeat rewrite -> app_nil_l. eexists. vm_compute. reflexivity.\nQed.\n\n\nLemma reinsjmp_nonIAT_MASK_subset r s i : \n  in_parser (reinsjmp_nonIAT_MASK_p r) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  unfold reinsjmp_nonIAT_MASK_p. intros.\n  unfold instruction_parser, instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts. replace s with (nil ++ s) ; auto.\n  econstructor ; eauto.\n    unfold prefix_parser_nooverride, option_perm2.\n    econstructor ; eauto.\n      eapply Alt_left_pi.\n      econstructor ; eauto. reflexivity.\n    unfold instr_parsers_nosize_pre. simpl.\n    \n    unfold bitsleft in H. repeat \n    match goal with \n    | [ H : in_parser (_  @  _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_  $  _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n    end ; subst.\n    repeat  match goal with \n      | [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi \n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n    end.\n    unfold AND_p, logic_or_arith_p. eapply Alt_right_pi. eapply Alt_right_pi.\n    eapply Alt_right_pi. eapply Alt_left_pi.\n    econstructor. econstructor. econstructor. eauto. \n    econstructor. econstructor. eauto.\n    econstructor. econstructor. eauto.\n    econstructor. econstructor. eauto.\n    econstructor. eapply reg_parser. destruct x21. eauto.\n    unfold imm_op. simpl. eapply mask_parser. destruct x22.\n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. simpl.\n    reflexivity.\nQed.\n\n\nLemma reinsjmp_nonIAT_MASK_EAX25_subset s i : \n  in_parser reinsjmp_nonIAT_MASK_EAX25_p s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  unfold reinsjmp_nonIAT_MASK_EAX25_p. intros.\n  unfold instruction_parser, instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts. replace s with (nil ++ s) ; auto.\n  econstructor ; eauto.\n    unfold prefix_parser_nooverride, option_perm2.\n    econstructor ; eauto.\n      eapply Alt_left_pi.\n      econstructor ; eauto. reflexivity.\n    unfold instr_parsers_nosize_pre. simpl.\n    unfold bitsleft in H. repeat \n    match goal with \n    | [ H : in_parser (_  @  _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_  $  _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n    end ; subst.\n    (*0x25 AND*)\n    repeat  match goal with \n      | [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi \n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n    end.\n    unfold AND_p , logic_or_arith_p. eapply Alt_right_pi. eapply Alt_right_pi.\n    eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_left_pi.\n    econstructor. econstructor. econstructor. eauto. \n    econstructor. econstructor. eauto.\n    unfold imm_op. simpl. eapply mask_parser. destruct x8.\n    eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    reflexivity.\nQed.\n\n\nLemma in_any_char :\n  forall s c i,\n    in_parser (Char_p c) s i ->\n    in_parser Any_p s i.\nProof.\n  intros. pinv. eauto.\nQed.\n\nLemma in_any_char2 :\n  forall s c1 c2 i,\n    in_parser (Cat_p (Char_p c1) (Cat_p (Char_p c2) Eps_p)) s i ->\n    in_parser (Cat_p Any_p (Cat_p Any_p Eps_p)) s i.\nProof.\n  intros. repeat pinv.\n  econstructor ; eauto.\nQed.\n\n\n\nDefinition string_to_register (str : string) : register :=\n  match str with\n  | \"000\"%string => EAX\n  | \"001\"%string => ECX\n  | \"010\"%string => EDX\n  | \"011\"%string => EBX\n  | \"100\"%string => ESP\n  | \"101\"%string => EBP\n  | \"110\"%string => ESI\n  | \"111\"%string => EDI\n  | _ => EAX\n  end.\n\nLemma bits_bitslist :\n  forall str s i c1 c2 c3,\n    c1 = \"0\" \\/ c1 = \"1\" ->\n    c2 = \"0\" \\/ c2 = \"1\" ->\n    c3 = \"0\" \\/ c3 = \"1\" ->\n    str = String c1 (String c2 (String c3 EmptyString)) ->\n    in_parser (bits str) s i ->\n    in_parser (bitslist (register_to_bools (string_to_register str))) s tt.\nProof.\n  intros.\n  repeat pinv ; psimp ; repeat pinv ; simpl ;\n    repeat (econstructor ; econstructor ; eauto).\nQed.\n\nLemma reinsjmp_IAT_or_RET_MASK_subset s i : \n  in_parser (reinsjmp_IAT_or_RET_MASK_p) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  unfold reinsjmp_IAT_or_RET_MASK_p. intros.\n  unfold instruction_parser, instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts. replace s with (nil ++ s) ; auto.\n  econstructor ; eauto.\n    unfold prefix_parser_nooverride, option_perm2.\n    econstructor ; eauto.\n      eapply Alt_left_pi.\n      econstructor ; eauto.\n    reflexivity.\n    unfold instr_parsers_nosize_pre. simpl.\n    repeat match goal with \n    | [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi \n    | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n    end.\n    unfold AND_p, logic_or_arith_p.\n    repeat eapply Alt_right_pi. unfold bitsleft in H.\n    repeat match goal with \n    | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n    end ; subst.\n    econstructor. econstructor. econstructor. eauto.\n    econstructor. econstructor. eauto.\n    econstructor. econstructor. econstructor. econstructor. eexact H11.\n    econstructor. eexact H15.\n    unfold rm00. eapply Alt_right_pi. eapply Alt_left_pi.\n    econstructor. econstructor. eexact H19.\n    econstructor. econstructor. econstructor. econstructor. econstructor.\n     unfold bits in H23. simpl in H23. unfold field'. eapply in_any_char2.\n     eauto. eauto. eauto. eapply reg_parser.\n     apply bits_bitslist with\n        (str := \"100\"%string) (c1 := \"1\") (c2 := \"0\") (c3 := \"0\")\n        (i := x33) ; auto.\n    eexact H27. eauto. eauto. eauto.\n    econstructor. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi.\n     eapply Alt_right_pi. eapply Alt_left_pi. eexact H30.\n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n    simpl. eauto.\n    econstructor. eapply mask_parser'. destruct x38. eexact H31.\n    eauto. eauto. eauto. eauto. eauto. eauto.\n    repeat rewrite <- app_assoc. reflexivity.\n    eauto. eauto.\n    simpl. assert (x37 = (true, (false, (false, tt)))).\n      unfold bits in H30. simpl in H30. repeat pinv. reflexivity.\n    rewrite -> H. simpl. reflexivity.\nQed.\n\n\nLemma reinsjmp_nonIAT_jump_subset r s i : \n  in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  intros. unfold instruction_parser, instruction_parser_list.\n  eapply in_alts_app. left. eapply in_map_alts.\n  replace s with (nil ++ s) ; auto.\n  econstructor ; eauto.\n    unfold prefix_parser_nooverride, option_perm2.\n    econstructor.\n      eapply Alt_left_pi.\n      econstructor ; eauto.\n    reflexivity.\n    unfold instr_parsers_nosize_pre. simpl.\n    repeat pinv.\n      repeat match goal with \n      | [ |- in_parser (JMP_p |+| _) _ _ ] => eapply Alt_left_pi\n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n      end. \n      unfold reinsjmp_nonIAT_JMP_p, JMP_p in *.\n      eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_left_pi.\n      unfold bitsleft in H.\n      repeat match goal with \n      | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n      | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n      end ; subst.\n      econstructor. econstructor. econstructor. eexact H3.\n      econstructor. econstructor. eexact H7.\n      unfold ext_op_modrm2.\n      econstructor. repeat eapply Alt_right_pi.\n      econstructor. eexact H11.\n      econstructor. eexact H14.\n      unfold rm11. econstructor. eapply reg_parser. destruct x18. eexact H15.\n      eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. auto. eauto.\n      eauto. simpl. reflexivity.\n    repeat match goal with \n    | [ |- in_parser (CALL_p |+| _) _ _ ] => eapply Alt_left_pi\n    | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n    end. \n    unfold reinsjmp_nonIAT_CALL_p, CALL_p in *. eapply Alt_right_pi.\n    eapply Alt_left_pi. unfold bitsleft in H.\n    repeat match goal with \n    | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n    end ; subst.\n    econstructor. econstructor. econstructor. eexact H3.\n    econstructor. econstructor. eexact H7.\n    unfold ext_op_modrm2. econstructor. repeat eapply Alt_right_pi.\n    econstructor. eexact H11.\n    econstructor. eexact H14.\n    unfold rm11. econstructor. eapply reg_parser. destruct x18. eexact H15.\n    eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. auto. eauto.\n    eauto. simpl. reflexivity.\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_jump_subset s i : \n  in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  intros. unfold instruction_parser, instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts.\n  replace s with (nil ++ s) ; auto.\n  econstructor ; eauto.\n    unfold prefix_parser_nooverride, option_perm2.\n    econstructor.\n      eapply Alt_left_pi.\n      econstructor ; eauto.\n      reflexivity.\n    unfold instr_parsers_nosize_pre. simpl.\n    repeat pinv.\n      repeat match goal with \n      | [ |- in_parser (JMP_p |+| _) _ _ ] => eapply Alt_left_pi\n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n      end. \n      unfold reinsjmp_IAT_JMP_p, JMP_p in *. eapply Alt_right_pi. eapply Alt_right_pi.\n      eapply Alt_left_pi. unfold bitsleft in H.\n      repeat match goal with \n      | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n      | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n      end ; subst.\n      econstructor. econstructor. econstructor. eexact H3.\n      econstructor. econstructor. eexact H7.\n      unfold ext_op_modrm2. econstructor. eapply Alt_left_pi.\n      econstructor. eexact H11.\n      econstructor. eexact H15.\n      unfold rm00. eapply Alt_right_pi. eapply Alt_right_pi. eapply Alt_right_pi.\n      econstructor. econstructor. eexact H19.\n      eexact H20. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n      eauto. eauto. eauto. eauto. eauto. eauto.\n      repeat match goal with \n      | [ |- in_parser (RET_p |+| _) _ _ ] => eapply Alt_left_pi\n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n      end.\n      exact H.\nQed.\n\nLemma reinsjmp_nonIAT_parser_inv r s1 s2 i1 i2:\n  r <> ESP ->\n  in_parser (reinsjmp_nonIAT_MASK_p r) s1 i1 ->\n  in_parser (reinsjmp_nonIAT_JMP_p r |+| reinsjmp_nonIAT_CALL_p r) s2 i2 ->\n  reinsjmp_nonIAT_mask_instr (mkPrefix None None false false) i1\n                     (mkPrefix None None false false) i2 = true.\nProof.\n  unfold reinsjmp_nonIAT_MASK_p, reinsjmp_nonIAT_JMP_p, reinsjmp_nonIAT_CALL_p.\n  intros.\n  repeat pinv  ; unfold reinsjmp_nonIAT_mask_instr ; simpl ;\n  destruct (register_eq_dec r ESP) ;\n  try congruence ;\n  destruct (register_eq_dec r r) ;\n  try congruence.\nQed.\n\n\nLemma reinsjmp_nonIAT_parser_EAX25_inv s1 s2 i1 i2:\n  in_parser reinsjmp_nonIAT_MASK_EAX25_p s1 i1 ->\n  in_parser (reinsjmp_nonIAT_JMP_p EAX |+| reinsjmp_nonIAT_CALL_p EAX) s2 i2 ->\n  reinsjmp_nonIAT_mask_instr (mkPrefix None None false false) i1\n                     (mkPrefix None None false false) i2 = true.\nProof.\n  unfold reinsjmp_nonIAT_MASK_EAX25_p, reinsjmp_nonIAT_JMP_p, reinsjmp_nonIAT_CALL_p.\n  intros.\n  repeat pinv  ;  unfold reinsjmp_nonIAT_mask_instr ;  simpl ; reflexivity.\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_parser_inv s1 s2 i1 i2:\n  in_parser (reinsjmp_IAT_or_RET_MASK_p) s1 i1 ->\n  in_parser (reinsjmp_IAT_JMP_p |+| RET_p) s2 i2 ->\n  reinsjmp_IAT_or_RET_mask_instr (mkPrefix None None false false) i1\n                        (mkPrefix None None false false) i2 = true.\nProof.\n  unfold reinsjmp_IAT_or_RET_MASK_p, reinsjmp_IAT_JMP_p, RET_p.\n  intros.\n  repeat pinv ; unfold reinsjmp_IAT_or_RET_mask_instr ; simpl ; reflexivity.\nQed.\n\nLemma reinsjmp_nonIAT_dfa_corr1 : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n,nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        in_parser reinsjmp_nonIAT_mask (flat_map byte_explode (bytes1 ++ bytes2))\n        (ins1,ins2) /\\\n        in_parser instruction_parser (flat_map byte_explode bytes1) (pfx1,ins1) /\\ \n        in_parser instruction_parser (flat_map byte_explode bytes2) (pfx2,ins2) /\\ \n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2) /\\ \n        reinsjmp_nonIAT_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        (forall ts3 ts4,\n          (length ts3 < length (bytes1 ++ bytes2))%nat -> \n          bytes = ts3 ++ ts4 ->\n          forall v0, ~ in_parser reinsjmp_nonIAT_mask (flat_map byte_explode ts3) v0).\nProof.\n  intros. subst.\n  rewrite build_dfa_eq in H.\n    generalize (dfa_recognize_corr _ _ _ _ H (List.map byte2token bytes)\n     (bytesLt256 _)).\n    clear H.\n  rewrite H0. clear H0.\n  mysimp.\n  generalize (byte2token_app _ _ _ H). t. subst.\n  rewrite (nat2bools_byte2token_is_byte_explode _) in H1.\n    generalize (reinsjmp_nonIAT_parser_splits _ H1). clear H1.\n  t. destruct H0. t. destruct x0. simpl in *.\n  exists x. exists (mkPrefix None None false false). exists i.\n  exists x3. exists (mkPrefix None None false false). exists i0.\n  split.\n    rewrite flat_map_app.\n    destruct x4  ; try congruence ;\n      repeat (try (eapply Alt_left_pi ; econstructor ; eauto ; fail)\n             ; eapply Alt_right_pi).\n  split. apply (reinsjmp_nonIAT_MASK_subset H3).\n  split. eapply (reinsjmp_nonIAT_jump_subset H4). \n  split. rewrite H1. rewrite map_length. reflexivity.\n  split. subst. rewrite app_assoc.\n    assert (x2 = List.map nat_to_byte (List.map byte2token x2))\n    ; [ idtac | congruence].\n    rewrite n2bs. reflexivity.\n  split. eapply reinsjmp_nonIAT_parser_inv ; eauto.\n  intros. rewrite H1 in H2.\n  specialize (H2 (List.map byte2token ts3) (List.map byte2token ts4)).\n  repeat rewrite map_length in H2.\n  specialize (H2 H5). subst. rewrite H6 in H2. rewrite map_app in H2.\n  specialize (H2 (eq_refl _)).\n  rewrite nat2bools_byte2token_is_byte_explode in H2.\n  intro. apply (H2 v0 H1).\n  t. destruct x0. simpl in *.\n  exists x. exists (mkPrefix None None false false). exists i.\n  exists x3. exists (mkPrefix None None false false). exists i0.\n  split.\n    rewrite flat_map_app.\n    destruct x4  ; try congruence ;\n      repeat (try (eapply Alt_left_pi ; econstructor ; eauto ; fail)\n             ; eapply Alt_right_pi).\n  split. apply (reinsjmp_nonIAT_MASK_EAX25_subset H3).\n  split. eapply (reinsjmp_nonIAT_jump_subset H4). \n  split. rewrite H1. rewrite map_length. reflexivity.\n  split. subst. rewrite app_assoc.\n    assert (x2 = List.map nat_to_byte (List.map byte2token x2))\n    ; [ idtac | congruence].\n    rewrite n2bs. reflexivity.\n  rewrite -> H0 in H4.\n  split. eapply reinsjmp_nonIAT_parser_EAX25_inv ; eauto.\n  intros. rewrite H1 in H2.\n  specialize (H2 (List.map byte2token ts3) (List.map byte2token ts4)).\n  repeat rewrite map_length in H2.\n  specialize (H2 H5). subst. rewrite H6 in H2. rewrite map_app in H2.\n  specialize (H2 (eq_refl _)).\n  rewrite nat2bools_byte2token_is_byte_explode in H2.\n  intro. apply (H2 v0 H0).\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_dfa_corr1 : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n,nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode (bytes1 ++ bytes2))\n        (ins1,ins2) /\\\n        in_parser instruction_parser (flat_map byte_explode bytes1) (pfx1,ins1) /\\ \n        in_parser instruction_parser (flat_map byte_explode bytes2) (pfx2,ins2) /\\ \n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2) /\\ \n        reinsjmp_IAT_or_RET_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        (forall ts3 ts4,\n          (length ts3 < length (bytes1 ++ bytes2))%nat -> \n          bytes = ts3 ++ ts4 ->\n          forall v0, ~ in_parser reinsjmp_IAT_JMP_or_RET_mask (flat_map byte_explode ts3) v0).\nProof.\n  intros. rewrite build_dfa_eq in H.\n  generalize (dfa_recognize_corr _ _ _ _ H (List.map byte2token bytes)\n    (bytesLt256 _)). clear H.\n  rewrite H0. clear H0. mysimp.\n  generalize (byte2token_app _ _ _ H). t. subst.\n  rewrite (nat2bools_byte2token_is_byte_explode _) in H1.\n  generalize (reinsjmp_IAT_JMP_or_RET_parser_splits _ H1). clear H1. t.\n  destruct x0. simpl in *.\n  exists x. exists (mkPrefix None None false false). exists i.\n    exists x3. exists (mkPrefix None None false false). exists i0.\n  split. rewrite flat_map_app. econstructor. eauto. eexact H3.\n    reflexivity. reflexivity.\n  split. apply (reinsjmp_IAT_or_RET_MASK_subset H1).\n  split. eapply (reinsjmp_IAT_JMP_or_RET_jump_subset H3). \n  split. rewrite H0. rewrite map_length. reflexivity.\n  split. subst. rewrite app_assoc.\n    assert (x2 = List.map nat_to_byte (List.map byte2token x2))\n    ; [ idtac | congruence].\n    rewrite n2bs. reflexivity.\n  split. eapply reinsjmp_IAT_JMP_or_RET_parser_inv ; eauto.\n  intros. rewrite H0 in H2. specialize (H2 (List.map byte2token ts3)\n  (List.map byte2token ts4)). repeat rewrite map_length in H2.\n  specialize (H2 H4). subst. rewrite H5 in H2. rewrite map_app in H2.\n  specialize (H2 (eq_refl _)). rewrite nat2bools_byte2token_is_byte_explode in H2.\n  intro. apply (H2 v0 H0).\nQed.\n\nLemma flat_map_nil_is_nil x : \n  flat_map byte_explode x = nil -> x = nil.\nProof.\n  induction x ; intros.\n    reflexivity.\n    replace (flat_map byte_explode (a :: x))\n      with (byte_explode a ++ (flat_map byte_explode x)) in H ; auto.\n    generalize (nil_is_nil_app_nil _ _ (eq_sym H)). t.\n    clear IHx H H1.\n    assert False ; try contradiction. \n      unfold byte_explode in H0. congruence.\nQed.\n\n(** This should get placed in DFACorrectness and used for the other 2 DFAs. *)\nLemma in_parser_implies_simple_parse\n  bytes1 pfx ins bytes2 :\n  in_parser instruction_parser (flat_map byte_explode bytes1) (pfx,ins) ->\n  simple_parse (bytes1 ++ bytes2) = Some (pfx, ins, bytes2).\nProof.\n  unfold simple_parse ; intros.\n  Opaque instruction_parser. \n  generalize (@simple_parse'_corr2 \n    instruction_parser (bytes1 ++ bytes2) initial_parser_state nil \n    (eq_refl _) (eq_refl _)).\n  simpl. intros. \n  assert (forall s1 s2, nil = s1 ++ s2 -> \n    apply_null (snd (parser2regexp instruction_parser))\n          (deriv_parse' (fst (parser2regexp instruction_parser))\n             (flat_map byte_explode s1))\n          (wf_derivs (snd (parser2regexp instruction_parser))\n             (flat_map byte_explode s1)\n             (fst (parser2regexp instruction_parser))\n             (p2r_wf instruction_parser initial_ctxt)) = nil).\n  intros. clear H0.\n  generalize (nil_is_nil_app_nil _ _ H1). t. subst.\n  generalize (min_count_not_null _ min_instruction_bits).\n  generalize instruction_parser.\n  clear H H1. simpl.\n  intro.\n  generalize (apply_null (snd(parser2regexp p)) (fst (parser2regexp p))).\n  assert (wf_derivs (snd (parser2regexp p)) nil (fst (parser2regexp p))\n         (p2r_wf p initial_ctxt) = p2r_wf p initial_ctxt). \n    apply Coqlib.proof_irrelevance. \n  generalize H. clear H.\n  unfold parser2regexp.\n  generalize (p2r_wf p initial_ctxt).\n  intros. rewrite <- H in H0. exact H0.\n  specialize (H0 H1). clear H1.\n  destruct (simple_parse' initial_parser_state (bytes1 ++ bytes2)).\n    destruct p. t. destruct p.\n    assert (length bytes1 >= length x).\n      assert (length bytes1 < length x -> False).\n        intros.\n        eapply (H2 bytes1 bytes2 (eq_refl _) H3 _ H). omega.\n    assert (exists s2, bytes1 = x ++ s2).\n      generalize bytes1 x H3 H0.\n      induction bytes0 ; destruct x0 ; simpl ; intros.\n        exists nil. reflexivity.\n        assert False.\n          omega.\n        contradiction.\n        subst. eauto.\n        injection H5 ; clear H5 ; t ; subst.\n        assert (length bytes0 >= length x0).\n          omega.\n        specialize (IHbytes0 _ H6 H5). t.\n        subst. eauto.\n    t. subst. rewrite app_ass in H0. generalize (app_inv_head _ _ _ H0).\n    intros. subst. rewrite flat_map_app in H. generalize (parser_determ H).\n    intros. specialize (H4 _ _ (p,i) (eq_refl _) H1). t.\n    injection H5 ; intros.\n    rewrite (flat_map_nil_is_nil _ H4). subst.  auto.\n    specialize (H0 bytes1 bytes2 (pfx,ins) (eq_refl _)). contradiction.\nQed.\n\nLemma reinsjmp_nonIAT_dfa_corr : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2) /\\\n        simple_parse (bytes2 ++ List.map nat_to_byte nats2) = \n            Some ((pfx2,ins2), List.map nat_to_byte nats2) /\\\n        reinsjmp_nonIAT_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).\nProof.\n  intros d H bytes n nats2 H1.\n  generalize (@reinsjmp_nonIAT_dfa_corr1 d H bytes n nats2 H1). t.\n  exists x. exists x0. exists x1. exists x2. exists x3. exists x4.\n  repeat split ; auto.\n    rewrite H5. apply in_parser_implies_simple_parse. exact H2.\n    apply in_parser_implies_simple_parse. exact H3.\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_dfa_corr : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2) /\\\n        simple_parse (bytes2 ++ List.map nat_to_byte nats2) = \n            Some ((pfx2,ins2), List.map nat_to_byte nats2) /\\\n        reinsjmp_IAT_or_RET_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).\nProof.\n  intros d H bytes n nats2 H1.\n  generalize (@reinsjmp_IAT_JMP_or_RET_dfa_corr1 d H bytes n nats2 H1). t.\n  exists x. exists x0. exists x1. exists x2. exists x3. exists x4.\n  repeat split ; auto.\n    rewrite H5. apply in_parser_implies_simple_parse. exact H2.\n    apply in_parser_implies_simple_parse. exact H3.\nQed.\n\nLemma reinsjmp_nonIAT_mask_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_nonIAT_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15). \nProof.\n  intros. apply reinsjmp_nonIAT_dfa_corr1 in H0.\n    destruct H0. destruct H0. destruct H0. destruct H0. \n    destruct H0. destruct H0. destruct H0.\n    destruct H1. destruct H2. destruct H3.\n    assert (max_bit_count reinsjmp_nonIAT_mask = Some 64).\n      vm_compute. reflexivity.\n    apply max_count_corr in H0.\n    rewrite H5 in H0.\n    rewrite byte_explode_mult_len in H0.\n    rewrite H3. omega.\n    auto.\nQed.\n\nLemma reinsjmp_IAT_JMP_or_RET_mask_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_build_dfa 256 nat2bools 400 (par2rec reinsjmp_IAT_JMP_or_RET_mask) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15). \nProof.\n  intros. apply reinsjmp_IAT_JMP_or_RET_dfa_corr1 in H0.\n    destruct H0. destruct H0. destruct H0. destruct H0. \n    destruct H0. destruct H0. destruct H0.\n    destruct H1. destruct H2. destruct H3.\n    assert (max_bit_count reinsjmp_IAT_JMP_or_RET_mask = Some 104).\n      vm_compute; trivial.\n    apply max_count_corr in H0.\n    rewrite H5 in H0.\n    rewrite byte_explode_mult_len in H0.\n    rewrite H3. omega.\n    auto.\nQed.\n", "meta": {"author": "mpettersson", "repo": "reins-verifier-proof", "sha": "44d0b8e0c29b07eb71b1d6d44b020648783409fb", "save_path": "github-repos/coq/mpettersson-reins-verifier-proof", "path": "github-repos/coq/mpettersson-reins-verifier-proof/reins-verifier-proof-44d0b8e0c29b07eb71b1d6d44b020648783409fb/REINS/REINSjmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.19985352561001243}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n *)\n\n\nRequire Export PBFTreceived_prepare_like2.\nRequire Export PBFTreceived_prepare_like8.\nRequire Export PBFTprepare_like2request_data.\n\n\nSection PBFTreceived_prepare_like9.\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 correct_in_intersection :\n    forall (eo : EventOrdering) (l1 l2 : list Rep) (E : list Event),\n      no_repeats l1\n      -> no_repeats l2\n      -> 2 * F + 1 <= length l1\n      -> 2 * F + 1 <= length l2\n      -> AXIOM_exists_at_most_f_faulty E F\n      -> exists good,\n          In good l1\n          /\\ In good l2\n          /\\ forall e, In e E -> node_has_correct_trace_before e good.\n  Proof.\n    introv nrep1 nrep2 len1 len2 atmost.\n    pose proof (two_quorums l1 l2) as quor; repeat (autodimp quor hyp).\n    exrepnd.\n    pose proof (there_is_one_good_guy_before eo l E) as gg.\n    repeat (autodimp gg hyp).\n    exrepnd.\n    exists good; dands; auto.\n  Qed.\n\n(*  Lemma prepare_like_in_log_from_good_replica :\n    forall (eo : EventOrdering) (e : Event) good pl i st,\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> loc e = PBFTreplica i\n      -> replica_has_correct_trace_before eo e good\n      -> prepare_like2sender pl = good\n      -> prepare_like_in_log pl (log st)\n      -> state_sm_on_event (PBFTreplicaSM i) eo e = Some st\n      ->\n      exists e' st,\n        e' \u227c e\n        /\\ loc e' = PBFTreplica good\n        /\\ state_sm_on_event (PBFTreplicaSM good) eo e' = Some st\n        /\\ prepare_like_in_log pl (log st).\n  Proof.\n    introv auth ckeys eqloc ctrace goodsender inlog eqst.\n\n    pose proof (correct_prepare_like_messages_are_sent _ pl i e st) as sent.\n    repeat (autodimp sent hyp);[].\n    exrepnd.\n\n    applydup localLe_implies_loc in sent1.\n    pose proof (ckeys e' i st1) as ck1; autodimp ck1 hyp.\n\n    repndors; repnd;[|].\n\n    - pose proof (prepare_like_received_from_good_replica_was_in_log eo e' good pl i) as h.\n      repeat (autodimp h hyp); allrw; eauto 3 with eo pbft; try congruence;[].\n\n      exrepnd.\n\n      exists e'0 st0; dands; auto; eauto 4 with eo.\n\n    - exists e st; dands; auto; eauto 3 with eo; try congruence.\n  Qed.*)\n\n  Lemma pbft_knows_prepare_like_propagates1 :\n    forall (eo : EventOrdering) (e : Event) good pl i st,\n      AXIOM_authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> AXIOM_PBFTcorrect_keys eo\n      -> loc e = PBFTreplica i\n      -> node_has_correct_trace_before e good\n      -> prepare_like2sender pl = good\n      -> prepare_like_in_log pl (log st)\n      -> state_sm_on_event (PBFTreplicaSM i) e = Some st\n      ->\n      exists e' st,\n        e' \u227c e\n        /\\ loc e' = PBFTreplica good\n        /\\ state_sm_on_event (PBFTreplicaSM good) e' = Some st\n        /\\ prepare_like_in_log pl (log st).\n  Proof.\n    introv auth ckeys eqloc ctrace goodsender inlog eqst.\n    pose proof (knows_propagates e pl) as q.\n    repeat (autodimp q hyp); eauto 3 with pbft;\n      try (complete (eexists; eexists; simpl; dands; eauto));\n      try (complete (simpl; allrw; subst; auto)).\n    exrepnd; unfold knows in *; simpl in *; exrepnd.\n    try unfold pbft_pl_data2loc in *.\n    rewrite goodsender in *.\n    rewrite q2 in *; ginv.\n    eexists; eexists; dands; eauto; try congruence.\n  Qed.\n\n  Lemma pbft_knows_prepare_like_propagates :\n    forall (eo : EventOrdering) (e : Event) pl,\n      AXIOM_authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> AXIOM_PBFTcorrect_keys eo\n      -> node_has_correct_trace_before e (prepare_like2sender pl)\n      -> knows e pl\n      ->\n      exists e',\n        e' \u227c e\n        /\\ loc e' = PBFTreplica (prepare_like2sender pl)\n        /\\ knows e' pl.\n  Proof.\n    introv auth ckeys ctrace kn.\n    apply knows_propagates in kn; eauto 3 with pbft.\n  Qed.\n\n  Lemma prepare_somewhere_in_log_not_from_primary :\n    forall p L,\n      well_formed_log L\n      -> prepare_somewhere_in_log p L = true\n      -> prepare2sender p <> PBFTprimary (prepare2view p).\n  Proof.\n    induction L; introv wf prep; simpl in *; tcsp;[].\n    inversion wf as [|? ? imp wf1 wf2]; subst; clear wf; smash_pbft.\n    repndors; tcsp;[].\n    applydup well_formed_log_entry_no_prepare_from_leader in wf1.\n    unfold prepare_in_entry in *; smash_pbft.\n    allrw existsb_exists; exrepnd.\n    intro e; destruct wf0.\n    apply in_map_iff.\n    eexists; dands; eauto.\n    unfold same_rep_tok in *; smash_pbft.\n    unfold is_prepare_for_entry, eq_request_data in *; smash_pbft.\n    destruct a, p, b; simpl in *; subst; simpl in *; tcsp.\n  Qed.\n  Hint Resolve prepare_somewhere_in_log_not_from_primary : pbft.\n\n  Lemma two_own_prepare_like_in_state :\n    forall (eo : EventOrdering) (e1 e2 : Event) i pl1 pl2 st1 st2,\n      loc e1 = loc e2\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some st1\n      -> state_sm_on_event (PBFTreplicaSM i) e2 = Some st2\n      -> prepare_like_in_log pl1 (log st1)\n      -> prepare_like_in_log pl2 (log st2)\n      -> prepare_like2sender pl1 = i\n      -> prepare_like2sender pl2 = i\n      -> prepare_like2seq pl1 = prepare_like2seq pl2\n      -> prepare_like2view pl1 = prepare_like2view pl2\n      -> prepare_like2digest pl1 = prepare_like2digest pl2.\n  Proof.\n    introv eqloc eqst1 eqst2 prep1 prep2 send1 send2 eqseq eqview.\n\n    apply prepare_like_in_log_implies_or in prep1.\n    apply prepare_like_in_log_implies_or in prep2.\n    repndors; exrepnd; subst; simpl in *.\n\n    - destruct prep3, prep, b, b0; simpl in *; ginv; subst; eauto 2 with pbft.\n\n    - destruct pp, prep, b, b0; simpl in *; subst.\n      apply prepare_somewhere_in_log_not_from_primary in prep0; eauto 2 with pbft.\n      simpl in *; tcsp.\n\n    - destruct pp, prep, b, b0; simpl in *; subst.\n      apply prepare_somewhere_in_log_not_from_primary in prep3; eauto 2 with pbft.\n      simpl in *; tcsp.\n\n    - destruct pp, pp0, b, b0; simpl in *; subst.\n\n      eapply pre_prepare_in_somewhere_in_log_implies_pre_prepare_in_log in prep2;[|eauto].\n      eapply pre_prepare_in_somewhere_in_log_implies_pre_prepare_in_log in prep1;[|eauto].\n\n      applydup well_formed_log_implies_correct_digest in prep1;[|eauto 2 with pbft].\n      applydup well_formed_log_implies_correct_digest in prep2;[|eauto 2 with pbft].\n\n      pose proof (PBFT_A_1_2_2_local\n                    eo e1 e2 (PBFTprimary v)\n                    s v d2 d1 a0 a d0 d st1 st2) as q.\n      repeat (autodimp q hyp); eauto 2 with pbft; subst; auto.\n  Qed.\n\n  Lemma two_know_own_prepare_like :\n    forall (eo : EventOrdering) (e1 e2 : Event) pl1 pl2,\n      loc e1 = loc e2\n      -> knows e1 pl1\n      -> knows e2 pl2\n      -> loc e1 = PBFTreplica (prepare_like2sender pl1)\n      -> loc e2 = PBFTreplica (prepare_like2sender pl2)\n      -> prepare_like2seq pl1 = prepare_like2seq pl2\n      -> prepare_like2view pl1 = prepare_like2view pl2\n      -> prepare_like2digest pl1 = prepare_like2digest pl2.\n  Proof.\n    introv eqloc kna knb send1 send2 eqseq eqview.\n    unfold knows in *; exrepnd; simpl in *.\n    assert (PBFTreplica n0 = PBFTreplica n) as xx by congruence; ginv.\n    eapply two_own_prepare_like_in_state;\n      try (exact eqloc); try (exact kna1); try (exact knb1); auto;\n        rewrite send1, send2 in *; ginv;\n          try (complete (inversion eqloc; auto)).\n  Qed.\n\n  Lemma similar_prepare_like2request_data_implies_same_seq :\n    forall pl1 pl2 v1 v2 n d1 d2,\n      prepare_like2request_data pl1 = request_data v1 n d1\n      -> prepare_like2request_data pl2 = request_data v2 n d2\n      -> prepare_like2seq pl1 = prepare_like2seq pl2.\n  Proof.\n    introv h q.\n    destruct pl1 as [p1|p1], pl2 as [p2|p2], p1 as [b1], p2 as [b2], b1, b2;\n      simpl in *; ginv; auto.\n  Qed.\n  Hint Resolve similar_prepare_like2request_data_implies_same_seq : pbft.\n\n  Lemma similar_prepare_like2request_data_implies_same_view :\n    forall pl1 pl2 v n1 n2 d1 d2,\n      prepare_like2request_data pl1 = request_data v n1 d1\n      -> prepare_like2request_data pl2 = request_data v n2 d2\n      -> prepare_like2view pl1 = prepare_like2view pl2.\n  Proof.\n    introv h q.\n    destruct pl1 as [p1|p1], pl2 as [p2|p2], p1 as [b1], p2 as [b2], b1, b2;\n      simpl in *; ginv; auto.\n  Qed.\n  Hint Resolve similar_prepare_like2request_data_implies_same_view : pbft.\n\n  Lemma implies_prepare_like_have_same_digests :\n    forall pl1 pl2 v1 v2 n1 n2 d1 d2,\n      prepare_like2request_data pl1 = request_data v1 n1 d1\n      -> prepare_like2request_data pl2 = request_data v2 n2 d2\n      -> prepare_like2digest pl1 = prepare_like2digest pl2\n      -> d1 = d2.\n  Proof.\n    introv h q.\n    destruct pl1 as [p1|p1], pl2 as [p2|p2], p1 as [b1], p2 as [b2], b1, b2;\n      simpl in *; ginv; auto.\n  Qed.\n\nEnd PBFTreceived_prepare_like9.\n\n\nHint Resolve prepare_somewhere_in_log_not_from_primary : pbft.\nHint Resolve similar_prepare_like2request_data_implies_same_seq : pbft.\nHint Resolve similar_prepare_like2request_data_implies_same_view : pbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/PBFT/PBFTreceived_prepare_like9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.19985351802157542}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition handle_ptimer_sysreg_write_spec (rec: Pointer) (esr: Z64) (adt: RData) : option RData :=\n    match esr with\n    | VZ64 esr =>\n      rely is_int64 esr;\n      rely (peq (base rec) buffer_loc);\n      rely (offset rec =? SLOT_REC);\n      when gidx == (buffer (priv adt)) @ (offset rec);\n      rely is_gidx gidx;\n      let gn := (gs (share adt)) @ gidx in\n      rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n      rely (ref_accessible gn CPU_ID);\n      let rt := __ESR_EL2_SYSREG_ISS_RT esr in\n      rely is_int rt;\n      let val := get_reg rt (g_regs (grec gn)) in\n      rely is_int64 val;\n      rely is_int (t_masked (g_ptimer (grec gn)));\n      rely is_int64 (r_cnthctl_el2 (g_regs (grec gn)));\n      let cnth' := Z.lor (r_cnthctl_el2 (g_regs (grec gn))) CNTHCTL_EL2_EL1PTEN in\n      let ec := Z.land esr ESR_EL2_SYSREG_MASK in\n      if ec =? ESR_EL2_SYSREG_TIMER_CNTP_TVAL_EL0 then\n        let cntp_ctl := r_cntp_ctl_el0 (cpu_regs (priv adt)) in\n        rely is_int64 cntp_ctl;\n        match t_masked (g_ptimer (grec gn)) =? 0, __timer_condition_met cntp_ctl with\n        | true, true =>\n          Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_tval_el0: val}}}\n        | _, _ =>\n          let r' := (grec gn) {g_ptimer: (g_ptimer (grec gn)) {t_asserted: 0}}\n                                  {g_regs: (g_regs (grec gn)) {r_cnthctl_el2: cnth'}} in\n          Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_tval_el0: val} {r_cnthctl_el2: cnth'}}}\n               {share: (share adt) {gs: (gs (share adt)) # gidx == (gn {grec: r'})}}\n        end\n      else\n        if ec =? ESR_EL2_SYSREG_TIMER_CNTP_CTL_EL0 then\n          let masked := Z.land val CNTx_CTL_IMASK in\n          let cntp_ctl := Z.lor val CNTx_CTL_IMASK in\n          match masked =? 0, __timer_condition_met cntp_ctl with\n          | true, true =>\n            let r' := (grec gn) {g_ptimer: (g_ptimer (grec gn)) {t_masked: Z.land val CNTx_CTL_IMASK}} in\n            Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_ctl_el0: (Z.lor val CNTx_CTL_IMASK)}}}\n                {share: (share adt) {gs: (gs (share adt)) # gidx == (gn {grec: r'})}}\n          | _, _=>\n            let cnth' := Z.lor (r_cnthctl_el2 (g_regs (grec gn))) CNTHCTL_EL2_EL1PTEN in\n            let r' := (grec gn) {g_ptimer: (g_ptimer (grec gn)) {t_asserted: 0} {t_masked: Z.land val CNTx_CTL_IMASK}}\n                                {g_regs: (g_regs (grec gn)) {r_cnthctl_el2: cnth'}} in\n            Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_ctl_el0: (Z.lor val CNTx_CTL_IMASK)}\n                                                                        {r_cnthctl_el2: cnth'}}}\n                {share: (share adt) {gs: (gs (share adt)) # gidx == (gn {grec: r'})}}\n          end\n        else\n          if ec =? ESR_EL2_SYSREG_TIMER_CNTP_CVAL_EL0 then\n            let cntp_ctl := r_cntp_ctl_el0 (cpu_regs (priv adt)) in\n            rely is_int64 cntp_ctl;\n            match t_masked (g_ptimer (grec gn)) =? 0, __timer_condition_met cntp_ctl with\n            | true, true =>\n              Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_cval_el0: val}}}\n            | _, _ =>\n              let r' := (grec gn) {g_ptimer: (g_ptimer (grec gn)) {t_asserted: 0}}\n                                      {g_regs: (g_regs (grec gn)) {r_cnthctl_el2: cnth'}} in\n              Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cntp_cval_el0: val} {r_cnthctl_el2: cnth'}}}\n                  {share: (share adt) {gs: (gs (share adt)) # gidx == (gn {grec: r'})}}\n            end\n          else\n            let cntp_ctl := r_cntp_ctl_el0 (cpu_regs (priv adt)) in\n            rely is_int64 cntp_ctl;\n            match t_masked (g_ptimer (grec gn)) =? 0, __timer_condition_met cntp_ctl with\n            | true, true =>\n              Some adt\n            | _, _ =>\n              let r' := (grec gn) {g_ptimer: (g_ptimer (grec gn)) {t_asserted: 0}}\n                                      {g_regs: (g_regs (grec gn)) {r_cnthctl_el2: cnth'}} in\n              Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_cnthctl_el2: cnth'}}}\n                  {share: (share adt) {gs: (gs (share adt)) # gidx == (gn {grec: r'})}}\n            end\n    end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmTimerHandler/Specs/handle_ptimer_sysreg_write.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.19969821638870588}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.lib.relation_list.\nRequire Import CertiGraph.msl_ext.log_normalize.\nRequire Import CertiGraph.msl_ext.iter_sepcon.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.dag.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import Coq.Logic.Classical.\n\nLocal Open Scope logic.\n\nSection PointwiseGraph_Mark.\n\nContext {V E: Type}.\nContext {GV GE Pred: Type}.\nContext {SGBA: PointwiseGraphBasicAssum V E}.\nContext {SGC: PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {L_SGC: Local_PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {SGP: PointwiseGraphPred V E GV GE Pred}.\nContext {SGA: PointwiseGraphAssum SGP}.\n\n#[global] Instance MGS: WeakMarkGraph.MarkGraphSetting bool.\nProof.\n  apply (WeakMarkGraph.Build_MarkGraphSetting _ (eq true)).\n  intros; destruct x; [left | right]; congruence.\nDefined.\n\nNotation Graph := (LabeledGraph V E bool unit unit).\nNotation SGraph := (PointwiseGraph V E GV GE).\n\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nDefinition mark1 x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark1 x G1 G2.\nDefinition mark x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark x G1 G2 /\\ G1 ~=~ G2.\n\nDefinition mark_list xs g1 g2 := relation_list (map mark xs) g1 g2.\n\nLemma mark_invalid_refl: forall (g: Graph) root, ~ vvalid g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_invalid_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_marked_root_refl: forall (g: Graph) root, WeakMarkGraph.marked g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_marked_root_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_list_eq: forall root xs g1 g2,\n  mark_list xs g1 g2 ->\n  WeakMarkGraph.componded_mark_list root xs g1 g2 /\\ g1 ~=~ g2.\nProof.\n  intros.\n  change (mark_list xs g1 g2) with\n    (relation_list (map (fun x => relation_conjunction (WeakMarkGraph.mark x) (respectful_relation pg_lg structurally_identical)) xs) g1 g2) in H.\n  eapply relation_list_conjunction in H.\n  rewrite relation_conjunction_iff in H.\n  split.\n  + destruct H as [? _].\n    eapply relation_list_inclusion; [| exact H].\n    intros ? _.\n    clear.\n    intros g1 g2 ?.\n    exists g2; [| apply WeakMarkGraph.eq_do_nothing; auto].\n    exists g1; [apply WeakMarkGraph.eq_do_nothing; auto |].\n    auto.\n  + eapply si_list.\n    exact (proj2 H).\nQed.\n\nLemma mark1_mark_list_mark: forall root l (g g': Graph),\n  vvalid g root ->\n  (WeakMarkGraph.unmarked g) root ->\n  step_list g root l ->\n  relation_list (mark1 root :: mark_list l :: nil) g g' ->\n  mark root g g'.\nProof.\n  intros.\n  destruct_relation_list g0 in H2.\n  eapply (mark_list_eq root) in H2.\n  destruct H2; simpl in H2.\n  split.\n  + eapply WeakMarkGraph.mark1_componded_mark_list_mark; eauto.\n    split_relation_list (g :: g0 :: g0 :: g' :: nil); auto;\n    apply WeakMarkGraph.eq_do_nothing; auto.\n  + destruct H3 as [? _].\n    rewrite H3; auto.\nQed.\n\nLemma mark_partial_labeled_graph_equiv: forall x (g g': Graph),\n  mark x g g' ->\n  ((predicate_partial_labeledgraph g (Complement _ (reachable g x))) ~=~\n  (predicate_partial_labeledgraph g' (Complement _ (reachable g x))))%LabeledGraph.\nProof.\n  intros.\n  split; [| split].\n  + destruct H.\n    simpl;\n    rewrite <- H0.\n    reflexivity.\n  + destruct H as [[? ?] _].\n    simpl in *; intros.\n    specialize (H0 v).\n    assert (~ g |= x ~o~> v satisfying (WeakMarkGraph.unmarked g)).\n    1: {\n      destruct H1.\n      intro; apply H3.\n      apply reachable_by_is_reachable in H4; auto.\n    }\n    clear - H0 H3.\n    destruct (vlabel g v), (vlabel g' v).\n    - auto.\n    - rewrite H0; auto.\n    - symmetry; tauto.\n    - auto.\n  + intros; simpl.\n    destruct (elabel g e), (elabel g' e); auto.\nQed.\n\nLemma root_stable_ramify: forall (g: Graph) (x: V) (gx: GV),\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vvalid g x ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx * (vertex_at x gx -* reachable_vertices_at x g)).\nProof. apply va_reachable_root_stable_ramify. Qed.\n\nLemma root_update_ramify: forall (g: Graph) (x: V) (lx: bool) (gx gx': GV),\n  vvalid g x ->\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vgamma (Graph_PointwiseGraph (labeledgraph_vgen g x lx)) x = gx' ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard g) ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard (labeledgraph_vgen g x lx)) ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -* reachable_vertices_at x (labeledgraph_vgen g x lx))).\nProof. apply va_reachable_root_update_ramify. Qed.\n\n(* TODO: remove this lemma? *)\nLemma exp_mark1: forall (g: Graph) (x: V) (lx: bool),\n  WeakMarkGraph.label_marked lx ->\n  @derives Pred _ (reachable_vertices_at x (labeledgraph_vgen g x lx)) (EX g': Graph, !! (mark1 x g g') && reachable_vertices_at x g').\nProof.\n  intros.\n  apply (exp_right (labeledgraph_vgen g x lx)).\n  apply andp_right; [apply prop_right | auto].\n  apply WeakMarkGraph.vertex_update_mark1; auto.\nQed.\n\nLemma mark_neighbor_ramify: forall {A} (g1: Graph) (g2: A -> Graph) x y,\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step g1 x y ->\n  Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y)))\n     (vguard g1) ->\n  (forall a, mark y g1 (g2 a) -> Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y))) (vguard (g2 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g1)\n    (reachable_vertices_at y g1 *\n      (ALL a: A, !! mark y g1 (g2 a) -->\n        (reachable_vertices_at y (g2 a) -*\n         reachable_vertices_at x (g2 a)))).\nProof.\n  intros.\n  assert (Included (reachable g1 y) (reachable g1 x)).\n  1: {\n    hnf; unfold Ensembles.In; intros.\n    apply step_reachable with y; auto.\n  }  \n  apply vertices_at_ramif_xQ. eexists. split; [|split].\n  + apply Ensemble_join_Intersection_Complement; auto. \n  + intros. destruct H5 as [_ ?].\n    rewrite <- H5; clear H5.\n    apply Ensemble_join_Intersection_Complement; auto.\n  + intros.\n    apply GSG_PartialGraphPreserve; auto.\n    - unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - destruct H5.\n      rewrite H6; clear H6.\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - apply mark_partial_labeled_graph_equiv in H5.\n      eapply si_stronger_partial_labeledgraph_simple; [| eassumption].\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6.\n      tauto.\nQed.\n\nLemma mark_list_mark_ramify: forall {A} (g1 g2: Graph) (g3: A -> Graph) x l y l',\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step_list g1 x (l ++ y :: l') ->\n  relation_list (mark1 x :: mark_list l :: nil) g1 g2 ->\n  Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y)))\n     (vguard g2) ->\n  (forall a, mark y g2 (g3 a) -> Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y))) (vguard (g3 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g2)\n    (reachable_vertices_at y g2 *\n      (ALL a: A, !! mark y g2 (g3 a) -->\n        (reachable_vertices_at y (g3 a) -*\n         reachable_vertices_at x (g3 a)))).\nProof.\n  intros. \n  destruct_relation_list g1' in H2.\n  destruct H5 as [? _].\n  apply (mark_list_eq x) in H2.\n  destruct H2 as [_ ?].\n  rewrite <- H5 in H2; clear g1' H5.\n  apply mark_neighbor_ramify; auto.\n  + destruct H2. rewrite <- (H2 x). auto.\n  + rewrite <- (step_si g1); auto. hnf in H1. rewrite <- H1.\n    rewrite in_app_iff. right. apply in_eq.\nQed.\n\nEnd PointwiseGraph_Mark.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/msl_application/Graph_Mark.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.19969820426236998}}
{"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.\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.\nRequire Import ReflectI1.\n\n\nImport ListNotations.\n\n\nModule PreInter (IdT: ModTyp) <: ModTyp.\n\nModule ReflectL := Reflect IdT.\nExport ReflectL.\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\nLemma Eval_vls (ts : list VTyp) (vs : list Value) :\n    Forall2T VTyping vs ts -> \n    tlist2type (map (fun t : VTyp => sVTyp t) ts).\n  intros.\n  induction X.\n  simpl.\n  exact tt.\n  simpl.\n  split.\n  inversion r; subst.\n  destruct x.\n  destruct v.\n  exact v.\n  exact IHX.\nDefined.  \n\n\n(*******************************************************************)\n\nProgram Definition SOS_Exp \n                   (fenv: funEnv) (env: valEnv)\n                   (e: Exp) (t: VTyp) (s: W) (n: nat)\n                   (k: SoundExp fenv env e t s n) :\n                              sVTyp t * (W * nat) := _.\n\nNext Obligation.\n  intros.\n  unfold SoundExp in k.\n  destruct k.\n  split.\n  - unfold VTyping in *.\n    rewrite <- v.\n    exact (sValue x).\n  - destruct s0.\n    exact x0.\nDefined.\n\n\nProgram Definition SOS_Exp1 \n                   (fenv: funEnv) (env: valEnv)\n                   (e: Exp) (t: VTyp) (s: W) (n: nat) \n                   (k: SoundExp fenv env e t s n) :\n  sVTyp t * (W * nat) :=\n  let (x, vt, s0) := k in\n  (match vt in (_ = y0) return (sVTyp y0) with\n   | eq_refl => sValue x\n   end, projT1 s0).\n\n\nDefinition ExpEvalSOS_TRN (fenv: funEnv)        \n           (k1: FEnvWT fenv) \n           (env: valEnv) (e: Exp) (t: VTyp) \n           (k3: ExpTyping (funEnv2funTC fenv) (valEnv2valTC env) e t)\n           (s: W) (n: nat) : (sVTyp t * (W * nat)) := \n  SOS_Exp1 fenv env e t s n \n  (ExpSoundness fenv k1 (funEnv2funTC fenv) (valEnv2valTC env) e t k3\n                eq_refl env eq_refl s n).\n\n\n\nProgram Definition SOS_Prms \n                   (fenv: funEnv) (env: valEnv)\n                   (ps: Prms) (pt: PTyp) (s: W) (n: nat)\n                   (k: SoundPrms fenv env ps pt s n) :\n                              PTyp_TRN pt * (W * nat) := _.\nNext Obligation.\n  intros.\n  destruct pt.\n  unfold SoundPrms in k.\n  destruct k as [es k].\n  destruct k as [vs k1 k2].\n  unfold isValueList2T in k1.\n  rewrite k1 in *.\n  clear k1.\n  clear es.  \n  destruct ps.\n  destruct k2 as [k2 k3].\n  destruct k3 as [s1 k3].\n  unfold PTyp_TRN.\n  unfold PTyp_ListTrans.\n  \n  split.\n\n  eapply matchListsAux02_T with (vs:=vs) in k2.\n  unfold vlsTyping in k2.\n  eapply Eval_vls.\n  exact k2.\n\n  constructor.\n  exact s1.\nDefined.  \n  \n\nDefinition PrmsEvalSOS_TRN (fenv: funEnv)        \n           (k1: FEnvWT fenv) \n           (env: valEnv) (ps: Prms) (pt: PTyp) \n           (k3: PrmsTyping (funEnv2funTC fenv) (valEnv2valTC env) ps pt)\n           (s: W) (n: nat) : (PTyp_TRN pt * (W * nat)) := \n  SOS_Prms fenv env ps pt s n \n  (PrmsSoundness fenv k1 (funEnv2funTC fenv) (valEnv2valTC env) ps pt k3\n                 eq_refl env eq_refl s n).\n\n\n(**********************************************************************)\n\n(* experiments *)\n\nProgram Definition noDupNil : @noDup Id Fun [] := _.\nNext Obligation.\n  constructor.\nDefined.  \n\nProgram Definition FEnvWTNil : FEnvWT [] := _.\nNext Obligation.\n  unfold FEnvWT.\n  intros.\n  unfold FunWT.\n  inversion H0.\nDefined.  \n\nProgram Definition ExpT1 (n: nat) :\n  ExpTyping [] [] (Val (existT ValueI Nat (Cst Nat n))) Nat := _.\nNext Obligation.\n  constructor.\n  unfold VTyping.\n  simpl.\n  auto.\nDefined.  \n\n\nLemma ExpAgree        \n           (n: nat) :\n   ExpEvalTRN nil FEnvWTNil noDupNil nil (Val (existT ValueI Nat (Cst Nat n))) Nat (ExpT1 n) = \n      fun w => ExpEvalSOS_TRN nil FEnvWTNil nil (Val (existT ValueI Nat (Cst Nat n))) Nat (ExpT1 n) (fst w) (snd w).\nProof.\n  eapply functional_extensionality_dep.\n  intro w.\n  destruct w.\n  simpl in *.\n  simpl.\n  induction n0.\n  compute.\n  auto.\n  compute.\n  auto.\nDefined.\n  \n\nProgram Definition ExpT11 (T: Type) (C: CTyp T)    \n           (n: T) :\n  ExpTyping [] [] (Val (existT ValueI (VT T C) (Cst (VT T C) n))) (VT T C) := _.\nNext Obligation.\n  constructor.\n  unfold VTyping.\n  simpl.\n  auto.\nDefined.  \n\n\nLemma ExpAgree1\n      (T: Type) (C: CTyp T) (n: T) :\n  ExpEvalTRN nil FEnvWTNil noDupNil nil (Val (existT ValueI (VT T C)\n            (Cst (VT T C) n))) (VT T C) (ExpT11 T C n) = \n  fun w => ExpEvalSOS_TRN nil FEnvWTNil nil (Val (existT ValueI (VT T C)\n       (Cst (VT T C) n))) (VT T C) (ExpT11 T C n) (fst w) (snd w).\nProof.\n  eapply functional_extensionality_dep.\n  intro w.\n  destruct w.\n  simpl in *.\n  induction n0.\n  compute.\n  auto.\n  compute.\n  auto.\nDefined.\n\n\nProgram Definition ExpT12 (T: Type) (C: CTyp T)        \n           (n: T) (fenv: funEnv) (env: valEnv) :\n  ExpTyping (funEnv2funTC fenv) (valEnv2valTC env)\n    (Val (existT ValueI (VT T C) (Cst (VT T C) n))) (VT T C) := _.\nNext Obligation.\n  constructor.\n  unfold VTyping.\n  simpl.\n  auto.\nDefined.  \n\n\nLemma ExpAgree2 (fenv: funEnv)        \n           (k1: FEnvWT fenv) (k2: noDup fenv)\n           (env: valEnv)\n      (T: Type) (C: CTyp T) (n: T) :\n  ExpEvalTRN fenv k1 k2 env (Val (existT ValueI (VT T C)\n        (Cst (VT T C) n))) (VT T C) (ExpT12 T C n fenv env) = \n  fun w => ExpEvalSOS_TRN fenv k1 env (Val (existT ValueI (VT T C)\n    (Cst (VT T C) n))) (VT T C) (ExpT12 T C n fenv env) (fst w) (snd w).\nProof.\n  eapply functional_extensionality_dep.\n  intro w.\n  destruct w.\n  simpl in *.\n  induction n0.\n  induction fenv.\n  compute.\n  auto.\n  compute.\n  auto.\n  induction fenv.\n  compute.\n  auto.\n  compute.\n  auto.\nDefined.\n\n  \nLemma ExpAgree2n (fenv: funEnv)        \n           (k1: FEnvWT fenv) (k2: noDup fenv)\n           (env: valEnv)\n      (T: Type) (C: CTyp T) (n: T) :\n  ExpEvalTRN fenv k1 k2 env (Val (existT ValueI (VT T C)\n      (Cst (VT T C) n))) (VT T C) (ExpT12 T C n fenv env) = ret n.\n  eapply functional_extensionality_dep.\n  intro w.\n  destruct w.\n  simpl in *.\n  induction n0.\n  induction fenv.\n  compute.\n  auto.\n  compute.\n  auto.\n  induction fenv.\n  compute.\n  auto.\n  compute.\n  auto.\nDefined.\n\nProgram Definition ExpT13 (T: Type) (C: CTyp T)    \n        (x: Id) (fenv: funEnv) (env: valEnv) \n        (H: findE (valEnv2valTC env) x = Some (VT T C)) :  \n  ExpTyping (funEnv2funTC fenv) (valEnv2valTC env) (Var x)\n            (VT T C) := _.\nNext Obligation.\n  constructor.\n  exact H.\nDefined.  \n\n\n\nLemma xxxAA (env: valEnv) (i0: Id) : (if IdT.IdEqDec i0 i0\n       then Some (VT nat (CInt nat eq_refl I32 Unsigned))\n       else findE (valEnv2valTC env) i0) = Some (VT nat (CInt nat eq_refl I32 Unsigned)).\n  destruct (IdT.IdEqDec i0 i0).\n  reflexivity.\n  intuition n.\nDefined.\n\n\nLemma ExpSoundnessA_Val : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (v : Value) \n    (t : VTyp) (v0 : VTyping v t),\n   forall (fenv: funEnv) (env: valEnv)\n           (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n   forall (s0 : W) (n0 : nat), n0 <= n -> SoundExp fenv env (Val v) t s0 n0.\n    unfold SoundExp.\n    intros.\n    constructor 1 with (x:=v).\n    assumption.\n    constructor 1 with (x:=(s0,n0)).\n    simpl.\n    constructor.\nDefined.\n\n\nLemma ExpSoundnessA1_Val : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (v : Value) \n    (t : VTyp) (v0 : VTyping v t),\n   forall (fenv: funEnv) (env: valEnv)\n           (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n   forall (s : W), SoundExp fenv env (Val v) t s n.\n    unfold SoundExp.\n    intros.\n    constructor 1 with (x:=v).\n    assumption.\n    constructor 1 with (x:=(s,n)).\n    simpl.\n    constructor.\nDefined.\n\n\nLemma ExpDenotA_Val : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (v : Value) \n    (t : VTyp) (v0 : VTyping v t),\n   forall (fenv: funEnv) (env: valEnv) (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n    valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t).  \n     intros.\n     inversion v0; subst.\n     exact (ret (sValue v)).\nDefined.    \n\n\n\n(**********************************************************************)\n\n\nLemma ExpSoundnessA_Var : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n   forall (fenv: funEnv) (env: valEnv)\n           (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n   forall (s0 : W) (n0 : nat), n0 <= n -> SoundExp fenv env (Var x) t s0 n0.\n    unfold SoundExp.\n    intros.\n    inversion i; subst.\n    inversion H0; subst.\n    unfold EnvTyping in H0.    \n    eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in H3.\n    destruct H3.\n    constructor 1 with (x:=x0).\n    unfold VTyping.\n    exact e0.\n    constructor 1 with (x:=(s0,n0)).\n    simpl.\n    eapply StepIsEClos.\n    constructor.\n    assumption.\n    assumption.\nDefined.\n\nLemma ExpSoundnessB_Var : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n   forall (fenv: funEnv) (env: valEnv)\n           (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n   forall (s0 : W) (n0 : nat), n0 <= n -> SoundExp fenv env (Var x) t s0 n0.\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold EnvTyping in H0.\n  unfold MatchEnvs in H0.\n  rewrite H0 in i.\n  clear H0.\n  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in i.\n  destruct i.\n  constructor 1 with (x:=x0).\n  unfold VTyping.\n  exact e0.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  constructor.\nDefined.\n    \nLemma ExpDenotA_Var : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n   forall (fenv: funEnv) (env: valEnv) (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n    valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t).  \n     intros.\n     inversion i; subst.\n     unfold MM.\n     intro.\n     split.\n     inversion H0; subst.\n     eapply (extract_from_valTC_TransB _ X0 x).\n     exact H2.\n     exact X1.\nDefined.\n\nLemma ExpDenotB_Var : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n   forall (fenv: funEnv) (env: valEnv) (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n    valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t).  \n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold MM.\n  intro.\n  split.\n  unfold EnvTyping in H0.\n  unfold MatchEnvs in H0.\n  rewrite H0 in i.\n  clear H0.\n  eapply (extract_from_valTC_TransB _ X0 x).\n  exact i.\n  exact X1.\nDefined.\n\n\nLemma ExpSoundnessDenotC_Var : forall (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t),\n   forall (fenv: funEnv) (env: valEnv)\n           (k1: FEnvWT fenv),                      \n   FEnvTyping fenv ftenv ->\n   EnvTyping env tenv ->    \n   forall (s0 : W) (n0 : nat), n0 <= n ->\n                   (SoundExp fenv env (Var x) t s0 n0 * sVTyp t).\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  rename H into X.\n  rename H0 into X0.\n  rename H1 into H.\n  unfold EnvTyping in X0.\n  unfold MatchEnvs in X0.\n  rewrite X0 in i.\n  clear X0.\n  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in i.\n  destruct i.\n  split.\n  constructor 1 with (x:=x0).\n  unfold VTyping.\n  exact e0.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  unfold valueVTyp in e0.\n  destruct x0.\n  rewrite <- e0.\n  simpl.\n  destruct v.\n  exact v.\n  constructor.\nDefined.\n\n\nLemma ExpSoundnessDenotE_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : IdTyping tenv x t) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n                   (SoundExp fenv env (Var x) t s0 n0 * sVTyp t).\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2 in i.\n  clear m2.\n(*  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in e. *)\n  split.\n  constructor 1 with (x:=v).\n  unfold VTyping.\n  exact mB.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  unfold valueVTyp in mB.\n  destruct v.\n  rewrite <- mB.\n  simpl.\n  destruct v.\n  exact v.\nDefined.\n\n\nLemma ExpSoundnessDenotF_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : IdTyping tenv x t) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n     sigT (fun I: SoundExp fenv env (Var x) t s0 n0 * sVTyp t => \n             SOS_Exp1 fenv env (Var x) t s0 n0 (fst I) = (snd I, (s0, n0))).\nProof.\n  intros.\n  econstructor 1 with (x:=ExpSoundnessDenotE_Var n ftenv tenv x v t i mB \n                                            fenv env mA k1 m1 m2 s0 n0 m3).\n  unfold SOS_Exp1.\n  simpl.\n  unfold valueVTyp in mB.\n  destruct v.\n  destruct v.\n  compute.\n  destruct mB.\n  reflexivity.\nDefined.  \n\n\nLemma ExpSoundnessDenotG_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n                   (SoundExp fenv env (Var x) t s0 n0 * sVTyp t).\n(*\n  sigT (fun I: SoundExp fenv env (Var x) t s0 n0 * sVTyp t => \n             SOS_Exp1 fenv env (Var x) t s0 n0 (fst I) = (snd I, (s0, n0))).\n*)\nProof.\n  unfold SoundExp.\n  intros.\n  intros.  \n  assert (IdTyping tenv x t) as i.\n  eapply (ExtRelTyp tenv x v t mB env m2 mA).    \n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2 in i.\n  clear m2.\n  split.\n  constructor 1 with (x:=v).\n  unfold VTyping.\n  exact mB.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  unfold valueVTyp in mB.\n  destruct v.\n  rewrite <- mB.\n  simpl.\n  destruct v.\n  exact v.\nDefined.\n\nLemma ExpSoundnessDenotG1_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n                   (SoundExp fenv env (Var x) t s0 n0 * sVTyp t).\nProof.\n  eapply (ExpSoundnessDenotE_Var n ftenv tenv x v t\n                                 (ExtRelTyp tenv x v t mB env m2 mA)\n                                 mB fenv env mA k1 m1 m2 s0 n0 m3).\nDefined.\n  \n\nLemma ExpSoundnessDenotH_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) (t: VTyp)\n    (i : IdTyping tenv x t) (*mB: valueVTyp v = t*)\n    (fenv: funEnv) (env: valEnv) (*mA: findE env x = Some v*)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n     sigT (fun I: SoundExp fenv env (Var x) t s0 n0 * sVTyp t => \n             SOS_Exp1 fenv env (Var x) t s0 n0 (fst I) = (snd I, (s0, n0))).\nProof.\n  intros.\n  unfold EnvTyping in m2.\n  econstructor 1 with (x:=ExpSoundnessDenotG1_Var n ftenv tenv x\n       (*v*)(ExtRelVal2A_1 valueVTyp tenv env x t m2 i) t\n       (*mB*)(ExtRelVal2A_4 valueVTyp tenv env x t m2 i)     \n        fenv env                                          \n       (*mA*)(ExtRelVal2A_2 valueVTyp tenv env x t m2 i) \n        k1 m1 m2 s0 n0 m3).\n  unfold ExpSoundnessDenotG1_Var.\n  unfold SOS_Exp1.\n  simpl.\n  remember (ExtRelVal2A valueVTyp tenv env x t m2 i) as K.\n  destruct K as [v mA mB].\n  unfold ExtRelVal2A_1.\n  unfold ExtRelVal2A_4.\n  unfold ExtRelVal2A_2.\n  rewrite <- HeqK.\n  \n  unfold valueVTyp.\n  destruct v.\n  destruct v.\n  compute.\n  destruct mB.\n  reflexivity.\nDefined.  \n\n\nDefinition FunEnvTRN2 (fenv : funEnv) (k1: FEnvWT fenv) (k2: noDup fenv)\n  (n: nat) : tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) :=\n  FunEnvTRN fenv k1 k2 n.  \n\nLemma ExpDenotI_Var' \n  (ftenv : funTC)\n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t)\n  (v: Value)\n  (mB : valueVTyp v = t) :\n  tlist2type (map snd (FunTC_ListTrans ftenv)) ->\n  valTC_Trans tenv -> MM WW (sVTyp t).\n  unfold valueVTyp in mB.\n  destruct v.\n(**)\n  destruct x0.\n  destruct v.\n  simpl in *.\n  inversion mB; subst.\n  clear H.\n  intros.\n  unfold MM.\n  intro.\n  simpl.\n  exact (v,X1).\nDefined.  \n(**)\n\nLemma ExpDenotI_Var'' \n  (ftenv : funTC)\n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t)\n  (v: Value)\n  (mB : valueVTyp v = t) :\n  tlist2type (map snd (FunTC_ListTrans ftenv)) ->\n  valTC_Trans tenv -> MM WW (sVTyp t).\n  unfold valueVTyp in mB.\n  destruct v.\n\n  rewrite <- mB.\n  simpl.\n  destruct v.\n  unfold MM.\n  intros.\n  exact (v, X1).\nDefined.\n\n\nLemma ExpDenotI_VarS \n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t)\n  (v: Value)\n  (mB : valueVTyp v = t) : MM WW (sVTyp t).\n  unfold valueVTyp in mB.\n  destruct v.\n(**)\n  destruct x0.\n  destruct v.\n  simpl in *.\n  inversion mB; subst.\n  clear H.\n  intros.\n  unfold MM.\n  intro.\n  simpl.\n  exact (v,X).\nDefined.  \n\n\nProgram Fixpoint ValEnvTRN2 (tenv: valTC) (env: valEnv)\n        (k: EnvTyping env tenv) :\n  valTC_Trans tenv := _.\nNext Obligation.\n  intros.\n  inversion k; subst.\n  eapply ValEnvTRN.\nDefined.  \n\nLemma valenvtrn_eq (env: valEnv) :\n    ((ValEnvTRN2 (map (thicken StaticSemL.Id valueVTyp) env) env\n                      eq_refl) = ValEnvTRN env).\n  induction env.\n  simpl.\n  unfold eq_rect_r.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  reflexivity.\n  simpl.\n  unfold eq_rect_r.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  reflexivity.\nDefined.\n\n\n(***** interesting for the proof *********************)\nLemma compare_den_var \n  (tenv : valTC)\n  (x : Id)\n  (t : VTyp)\n  (i :  IdTyping tenv x t)\n  (v: Value)\n  (env: valEnv)\n  (k: EnvTyping env tenv)\n  (mB : valueVTyp v = t)\n  (mA: findE env x = Some v)\n  (senv: valTC_Trans tenv)\n  (k1: senv = ValEnvTRN2 tenv env k)\n   :\n  (ExpDenI_Var tenv x t i) senv = ExpDenotI_VarS tenv x t i v mB.\n  destruct t.\n  destruct v.\n  destruct v.\n  destruct x0.\n  simpl in v.\n  simpl in mB.\n  inversion mB; subst.\n  inversion k; subst.\n  simpl in *.\n  dependent destruction mB.\n  simpl.\n  unfold ExpDenI_Var.\n  eapply functional_extensionality_dep.\n  intro.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  dependent induction env.\n  inversion mA.\n  destruct a.\n  simpl in mA.\n  simpl in i.\n  revert mA.\n  revert i.\n  simpl.\n  destruct (IdT.IdEqDec x i0).\n  intros.\n  inversion i; subst.\n  inversion mA; subst.\n  simpl in i.\n  simpl in H0.\n  clear H0.\n  clear mA.\n  dependent destruction i.\n  unfold eq_rect_r.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  f_equal.\n  unfold ValEnvTRN2_obligation_1.\n  unfold EnvTyping in k.\n  unfold MatchEnvs in k.\n  dependent destruction k.\n  unfold eq_rect_r.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  simpl.\n  reflexivity.\n\n(**)  \n\n  unfold EnvTyping in k.\n  unfold MatchEnvs in k.\n  dependent destruction k.\n  intros.\n  unfold ValEnvTRN2_obligation_1.\n  unfold eq_rect_r.\n  rewrite <- eq_rect_eq.\n  rewrite <- eq_rect_eq.\n  simpl.\n  specialize (IHenv eq_refl i v mA eq_refl x1).\n  rewrite valenvtrn_eq in IHenv.\n  exact IHenv.\nDefined.  \n\n\n(* senv not really used *)\nLemma ExpSoundnessDenotI_Var' (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : IdTyping tenv x t) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) -> \n    (* senv: *) valTC_Trans (valEnv2valTC env) ->\n    MM WW (sVTyp t))).\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2 in i.\n  clear m2.\n(*  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in e. *)\n  split.\n  constructor 1 with (x:=v).\n  unfold VTyping.\n  exact mB.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  intros.\n  eapply ExpDenotI_VarS.\n  exact i.\n  exact mB.\nDefined.\n\n    \nLemma ExpSoundnessDenotI_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : IdTyping tenv x t) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) -> \n                valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t))).\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2 in i.\n  clear m2.\n(*  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in e. *)\n  split.\n  constructor 1 with (x:=v).\n  unfold VTyping.\n  exact mB.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  eapply ExpDenotI_Var.\n  exact i.\nDefined.\n\n\nLemma ExpSoundnessDenotI1_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) -> \n                valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t))).\nProof.\n  eapply (ExpSoundnessDenotI_Var n ftenv tenv x v t\n                                 (ExtRelTyp tenv x v t mB env m2 mA)\n                                 mB fenv env mA k1 m1 m2 s0 n0 m3).\nDefined.\n\nLemma ExpSoundnessDenotI1_Var' (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) -> \n                valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t))).\nProof.\n  eapply (ExpSoundnessDenotI_Var' n ftenv tenv x v t\n                                 (ExtRelTyp tenv x v t mB env m2 mA)\n                                 mB fenv env mA k1 m1 m2 s0 n0 m3).\nDefined.\n\n\nLemma ExpSoundnessDenotJ_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) (t: VTyp)\n    (i : IdTyping tenv x t) (*mB: valueVTyp v = t*)\n    (fenv: funEnv) (env: valEnv) (*mA: findE env x = Some v*)\n    (k1: FEnvWT fenv)\n    (k2: noDup fenv)\n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  sigT (fun I: SoundExp fenv env (Var x) t s0 n0 *\n      (tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n         valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t)) => \n          SOS_Exp1 fenv env (Var x) t s0 n0 (fst I) =\n          (snd I) (FunEnvTRN2 fenv k1 k2 n) (ValEnvTRN env) (s0, n0)).\nProof.\n  intros.\n  unfold EnvTyping in m2.\n  econstructor 1 with (x:=ExpSoundnessDenotI1_Var' n ftenv tenv x\n       (*v*)(ExtRelVal2A_1 valueVTyp tenv env x t m2 i) t\n       (*mB*)(ExtRelVal2A_4 valueVTyp tenv env x t m2 i)     \n        fenv env                                          \n       (*mA*)(ExtRelVal2A_2 valueVTyp tenv env x t m2 i) \n        k1 m1 m2 s0 n0 m3).\n  unfold ExpSoundnessDenotG1_Var.\n(*  destruct i as [tenv x t i]. *)\n  unfold SOS_Exp1.\n  simpl.\n  remember (ExtRelVal2A valueVTyp tenv env x t m2 i) as K.\n  destruct K as [v mA mB].\n  unfold ExtRelVal2A_1.\n  unfold ExtRelVal2A_4.\n  unfold ExtRelVal2A_2.\n  rewrite <- HeqK.\n  \n  unfold valueVTyp.\n  destruct v.\n  destruct v.\n\n  unfold MatchEnvs in m2.\n  unfold FEnvTyping in m1.\n  unfold MatchEnvs in m1.\n  inversion m1; subst.\n  clear H.\n  simpl in mA.\n  destruct x0.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  simpl in v.\n  compute.\n  reflexivity.\nDefined.  \n\n\nLemma ExpSoundnessDenotI2_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (i : IdTyping tenv x t) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (valTC_Trans (valEnv2valTC env) -> nat -> W -> (sVTyp t * WW))).\n  unfold SoundExp.\n  intros.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  unfold EnvTyping in m2.\n  unfold MatchEnvs in m2.\n  rewrite m2 in i.\n  clear m2.\n(*  eapply ExtRelVal2 with (f:=valueVTyp) (venv:=env) in e. *)\n  split.\n  constructor 1 with (x:=v).\n  unfold VTyping.\n  exact mB.\n  constructor 1 with (x:=(s0,n0)).\n  simpl.\n  eapply StepIsEClos.\n  constructor.\n  assumption.\n  intros.\n  eapply ExpDenotI_VarS.\n  exact i.\n  exact mB.\n  exact (s0,n0).\nDefined.\n\nLemma ExpSoundnessDenotI2_VarA (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id)\n    (v : Value) \n    (t : VTyp) (mB: valueVTyp v = t)\n    (fenv: funEnv) (env: valEnv) (mA: findE env x = Some v)\n    (k1: FEnvWT fenv)                       \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  (SoundExp fenv env (Var x) t s0 n0 *\n   (valTC_Trans (valEnv2valTC env) -> nat -> W -> (sVTyp t * WW))).\nProof.\n  eapply (ExpSoundnessDenotI2_Var n ftenv tenv x v t\n                                 (ExtRelTyp tenv x v t mB env m2 mA)\n                                 mB fenv env mA k1 m1 m2 s0 n0 m3).\nDefined.\n\n\nLemma ExpSoundnessDenotJ2_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) (t: VTyp)\n    (i : IdTyping tenv x t) (*mB: valueVTyp v = t*)\n    (fenv: funEnv) (env: valEnv) (*mA: findE env x = Some v*)\n    (k1: FEnvWT fenv)\n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)    \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  sigT (fun I: SoundExp fenv env (Var x) t s0 n0 *\n      (valTC_Trans (valEnv2valTC env) -> nat -> W -> (sVTyp t * WW)) => \n          SOS_Exp1 fenv env (Var x) t s0 n0 (fst I) =\n          (snd I) (ValEnvTRN env) n0 s0).\nProof.\n  intros.\n(*  destruct i as [tenv x t i]. *)\n  unfold EnvTyping in m2.\n  econstructor 1 with (x:=ExpSoundnessDenotI2_VarA n ftenv tenv x\n       (*v*)(ExtRelVal2A_1 valueVTyp tenv env x t m2 i) t\n       (*mB*)(ExtRelVal2A_4 valueVTyp tenv env x t m2 i)     \n        fenv env                                          \n       (*mA*)(ExtRelVal2A_2 valueVTyp tenv env x t m2 i) \n        k1 m1 m2 s0 n0 m3).\n(*  destruct i as [tenv x t i]. *)\n  unfold SOS_Exp1.\n  simpl.\n  remember (ExtRelVal2A valueVTyp tenv env x t m2 i) as K.\n  destruct K as [v mA mB].\n  unfold ExtRelVal2A_1.\n  unfold ExtRelVal2A_4.\n  unfold ExtRelVal2A_2.\n  rewrite <- HeqK.\n  \n  unfold valueVTyp.\n  destruct v.\n  destruct v.\n\n  unfold MatchEnvs in m2.\n  unfold FEnvTyping in m1.\n  unfold MatchEnvs in m1.\n  inversion m1; subst.\n  clear H.\n  simpl in mA.\n  destruct x0.\n  unfold IdTyping in i.\n  unfold EnvrAssign in i.\n  simpl in v.\n  compute.\n  reflexivity.\nDefined.  \n\nDefinition ExpSoundnessJ2_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  SoundExp fenv env (Var x) t s0 n0 := fst (projT1\n  (ExpSoundnessDenotJ2_Var n ftenv tenv x t i fenv env k1 m1 m2 s0 n0 m3)).\n\nDefinition ExpDenotJ2_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  valTC_Trans (valEnv2valTC env) -> nat -> W -> (sVTyp t * WW) :=\n  snd (projT1 \n  (ExpSoundnessDenotJ2_Var n ftenv tenv x t i fenv env k1 m1 m2 s0 n0 m3)).\n\n\n(***************************************************************\n******************************************************************)\n\n\nDefinition ExpSoundnessH_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  SoundExp fenv env (Var x) t s0 n0 := fst (projT1\n  (ExpSoundnessDenotH_Var n ftenv tenv x t i fenv env k1 m1 m2 s0 n0 m3)).\n\nDefinition ExpDenotH_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n  valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) :=\n  fun stf sf s => (snd (projT1 \n  (ExpSoundnessDenotH_Var n ftenv tenv x t i fenv env k1 m1 m2 s0 n0 m3)), s).\n\nDefinition ExpSoundnessJ_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (k2: noDup fenv)\n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  SoundExp fenv env (Var x) t s0 n0 := fst (projT1\n  (ExpSoundnessDenotJ_Var n ftenv tenv x t i fenv env k1 k2 m1 m2 s0 n0 m3)).\n\nDefinition ExpDenotJ_Var (n: nat)\n    (ftenv : funTC) (tenv : valTC) (x : Id) \n    (t : VTyp) (i : IdTyping tenv x t) \n    (fenv: funEnv) (env: valEnv)\n    (k1: FEnvWT fenv)                      \n    (k2: noDup fenv)\n    (m1: FEnvTyping fenv ftenv)\n    (m2: EnvTyping env tenv)   \n    (s0 : W) (n0 : nat) (m3: n0 <= n) :\n  tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n  valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) :=\n  snd (projT1 \n  (ExpSoundnessDenotJ_Var n ftenv tenv x t i fenv env k1 k2 m1 m2 s0 n0 m3)).\n\n\n\nLemma PushOutForAll1 (ftenv : funTC) (tenv : valTC) \n  (e : Exp)\n  (t : VTyp)\n  (m : ExpTyping ftenv tenv e t)\n  (fenv : funEnv)\n  (env : valEnv)\n  (k1: FEnvWT fenv)                      \n  (k2: noDup fenv)\n  (m1: FEnvTyping fenv ftenv)\n  (m2: EnvTyping env tenv)   \n  (n: nat) :\n  {I1 : forall (s : W) (n0 : nat), n0 <= n -> SoundExp fenv env e t s n0\n      &\n      {I2\n      : tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n        valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) &\n      {FE : nat -> tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))\n      &\n      forall (s : W) (n0 : nat) (q : n0 <= n),\n      SOS_Exp1 fenv env e t s n0 (I1 s n0 q) =\n      I2 (FE n0) (ValEnvTRN env) (s, n0)}}} ->\n forall (s : W) (n0 : nat), n0 <= n ->  \n  {I3 : SoundExp fenv env e t s n0\n      &\n      {I4\n      : tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n        valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) &\n      {FE : nat -> tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))\n      &\n      SOS_Exp1 fenv env e t s n0 I3 =\n      I4 (FE n0) (ValEnvTRN env) (s, n0)}}}.\n  intros.\n  destruct X as [k4 X].\n  destruct X as [k5 X].\n  destruct X as [k6 X].\n  econstructor 1 with (x:=k4 s n0 H).\n  econstructor 1 with (x:=k5).\n  econstructor 1 with (x:=k6).\n  specialize (X s n0 H).\n  eapply X.\nDefined.  \n\nLemma PushOutForAll1aux (ftenv : funTC) (tenv : valTC) \n  (e : Exp)\n  (t : VTyp)\n  (m : ExpTyping ftenv tenv e t)\n  (fenv : funEnv)\n  (env : valEnv)\n  (k1: FEnvWT fenv)                      \n  (k2: noDup fenv)\n  (m1: FEnvTyping fenv ftenv)\n  (m2: EnvTyping env tenv)   \n  (n: nat) :\n( {I1 : forall (s0 : W) (n1 : nat), n1 <= n -> SoundExp fenv env e t s0 n1\n      &\n      {I2\n      : tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n        valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) &\n      {FE : nat -> tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))\n      &\n      forall (s : W) (n1 : nat) (q : n1 <= n),\n      SOS_Exp1 fenv env e t s n1 (I1 s n1 q) =\n      I2 (FE n1) (ValEnvTRN env) (s, n1)}}}) ->\n\n  {I1 : forall (s : W) (n0 : nat), n0 <= n -> SoundExp fenv env e t s n0\n      &\n      {I2\n      : tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv))) ->\n        valTC_Trans (valEnv2valTC env) -> MM WW (sVTyp t) &\n      {FE : nat -> tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))\n      &\n      forall (s: W) (n0 : nat) (q : n0 <= n),\n      SOS_Exp1 fenv env e t s n0 (I1 s n0 q) =\n      I2 (FE n0) (ValEnvTRN env) (s, n0)}}}.\n  intros.  \n  destruct X as [k4 X].\n  destruct X as [k5 X].\n  destruct X as [k6 X].\n  econstructor 1 with (x:=k4).\n  econstructor 1 with (x:=k5).\n  econstructor 1 with (x:=k6).\n  intros.\n  eapply X.\nDefined.  \n\n\n(************************************************************************)\n\nProgram Definition preSucc_Y\n    (fenv: funEnv)      \n    (ET : forall (tenv: valTC) (e: Exp) (t: VTyp) \n          (k: ExpTyping (funEnv2funTC fenv) tenv e t)\n  (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans (funEnv2funTC fenv)))),      (valTC_Trans tenv -> MM WW (sVTyp t)))\n         \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  \n  assert (ExpTyping ftenv tenv e t) as k1.\n  unfold FEnvWT in k.\n  specialize (k ftenv eq_refl 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\n  unfold FunTyp_TRN.\n  unfold FTyp_TRN2.\n  unfold FType_mk2.\n\n(* apply ET (the translation) to e (the function body) in shallow\n   environment sfenv *)  \n  specialize (ET tenv e t k1 sfenv). \n  unfold valTC_Trans in ET.\n  unfold VTList_Trans in ET.\n  destruct f.\n  subst tenv e t.\n  simpl in *.\n  intro.\n  specialize (ET X).    \n  exact ET.\nDefined.\n\n\nProgram Definition ZeroTRN4 (ftenv: funTC) (fenv: funEnv)\n        (m: FEnvTyping fenv ftenv) :\n  tlist2type (map snd (FunTC_ListTrans ftenv)) := _.\nNext Obligation.\n  intros.\n  inversion m; subst.\n  rewrite <- FunEnv_Trans_lemma.\n  eapply ZeroTRN1. \nDefined.\n\n\nProgram Definition preSucc_Z\n        (ftenv: funTC) (fenv: funEnv)\n        (m: FEnvTyping fenv ftenv)\n    (ET : forall (tenv: valTC) (e: Exp) (t: VTyp) \n          (k: ExpTyping ftenv tenv e t)\n          (sfenv: nat -> tlist2type (map snd (FunTC_ListTrans ftenv))),\n        (valTC_Trans tenv -> MM WW (sVTyp t)))\n         \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  inversion m; subst.\n  eapply preSucc_Y.\n  eassumption.\n  assumption.\n  eassumption.\n  assumption.\nDefined.  \n  \nEnd PreInter.\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/PreInterI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.19958119293562745}}
{"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.\n\nImport Clight Clightdefs.\nImport ITreeNotations.\nImport ActiveStandby.\n\nImport CtrlState.\n\nSet Nested Proofs Allowed.\n(* Arguments app : simpl nomatch. *)\nLocal Transparent Archi.ptr64.\nLocal Opaque Z.of_nat Z.to_nat.\n\n(* Arguments Nat.mul: simpl never. *)\nArguments Nat.mul: simpl never.\n\nOpaque globalenv.\n\nLocal Open Scope Z.\n\n\nDefinition ctrl_gvar_ids := map fst ctrl_gvar_ilist.\nDefinition ctrl_gfun_ids := map fst ctrl_gfun_ilist.\nDefinition ctrl_cenv_ids := map fst ctrl_cenv_ilist.\n\n\nLemma range_qrange_sanitize_prec i\n  : 0 <= qrange_sanitize i < 4.\nProof.\n  unfold qrange_sanitize.\n  destruct (Z.leb_spec 0 i);\n    destruct (Z.ltb_spec i QSIZE); ss.\nQed.\n\n\nLemma range_adv_qidx_prec i\n  : 0 <= adv_qidx i < 4.\nProof.\n  apply range_qrange_sanitize_prec.\nQed.\n\n\nLemma set_queue_mem\n      c e q q' m m' b ofs\n      (MEM_Q: Mem.loadbytes m b ofs 4 =\n              Some (inj_bytes (map Byte.repr q)))\n      (RANGE_C: 0 <= c < 4)\n      (RANGE_E: IntRange.sintz8 e)\n      (SET_Q: q' = set_queue c e q)\n      (STORE: Mem.store Mint8signed m b (ofs + c)\n                        (Vint (Int.repr e)) = Some m')\n  : Mem.loadbytes m' b ofs 4 =\n    Some (inj_bytes (map Byte.repr q')).\nProof.\n\n  assert (LEN_Q: length q = 4%nat).\n  { apply Mem.loadbytes_length in MEM_Q.\n    unfold inj_bytes in MEM_Q.\n    do 2 rewrite map_length in MEM_Q. nia. }\n\n  assert (CN: exists cn, Z.of_nat cn = c).\n  { exists (Z.to_nat c). nia. }\n  des.\n\n  assert (q' = firstn cn q ++ [e] ++ skipn (S cn) q).\n  { unfold set_queue in *.\n    generalize (replace_nth_spec _ q cn e).\n    i. des.\n    { exfalso. nia. }\n\n    cut (firstn cn q = l1 /\\ skipn (S cn) q = l2).\n    { i. des. subst.\n      rewrite firstn_app_exact by ss.\n      replace (l1 ++ [p] ++ l2) with ((l1 ++ [p]) ++ l2).\n      2: { rewrite app_assoc. ss. }\n\n      rewrite skipn_app_exact.\n      2: { rewrite app_length. ss. nia. }\n      rewrite Nat2Z.id.\n      rewrite <- app_assoc. ss.\n    }\n    split.\n    - subst.\n      rewrite firstn_app_exact; ss.\n    - subst.\n      replace (l1 ++ [p] ++ l2) with ((l1 ++ [p]) ++ l2).\n      2: { rewrite app_assoc. ss. }\n      rewrite skipn_app_exact.\n      2: { rewrite app_length. ss. nia. }\n      ss.\n  }\n  clear SET_Q.\n  subst q'.\n\n  rename MEM_Q into LBS.\n  replace 4 with (c + (1 + (3 - c))) in * by nia.\n  eapply Mem.loadbytes_split in LBS; try nia.\n  destruct LBS as (mvs1 & mvs2 & LBS1 & LBS2 & MVS_EQ).\n\n  assert (LEN_BS1: length mvs1 = cn).\n  { apply Mem.loadbytes_length in LBS1.\n    rewrite LBS1. nia. }\n\n  rewrite <- firstn_skipn with (l:= q) (n:=cn) in MVS_EQ.\n  unfold inj_bytes in MVS_EQ.\n  rewrite map_app in MVS_EQ.\n  rewrite map_app in MVS_EQ.\n  apply app_eqlen_inv in MVS_EQ.\n  2: { do 2 rewrite map_length.\n       rewrite firstn_length_le by nia.\n       ss. }\n\n  destruct MVS_EQ as (MVS_EQ1 & MVS_EQ2).\n\n  unfold inj_bytes.\n  do 2 rewrite map_app.\n  apply Mem.loadbytes_concat; try nia.\n  { rewrite MVS_EQ1.\n    eapply Mem.loadbytes_unchanged_on; eauto.\n    { eapply store_unchanged_on'; eauto. }\n    unfold mem_range.\n    ii. des; ss. nia.\n  }\n  clear mvs1 LBS1 MVS_EQ1 LEN_BS1.\n\n  (**)\n  eapply Mem.loadbytes_split in LBS2; try nia.\n  destruct LBS2 as (mvs3 & mvs4 & LBS3 & LBS4 & MVS_EQ').\n\n  assert (LEN_MVSS3: length mvs3 = 1%nat).\n  { apply Mem.loadbytes_length in LBS3.\n    rewrite LBS3. nia. }\n\n  subst mvs2.\n\n  assert (DIV_SKIPN: exists x, skipn cn q = x :: skipn (S cn) q).\n  { destruct (skipn cn q) as [| h t] eqn: DES.\n    { exfalso.\n      hexploit skipn_nil_implies; eauto.\n      nia.\n    }\n    erewrite skipn_nth_next; eauto.\n  }\n  des.\n  rewrite DIV_SKIPN in MVS_EQ2. ss.\n  destruct mvs3 as [| mvs3_h []]; ss.\n  clarify.\n\n  rewrite rw_cons_app.\n  apply Mem.loadbytes_concat; try nia.\n  - apply Mem.loadbytes_store_same in STORE.\n    ss. rewrite STORE.\n    unfold inj_bytes, encode_int. s.\n    rewrite rev_if_be_single. ss.\n\n    cut (Byte.repr e =\n         Byte.repr (Int.unsigned (Int.repr e))).\n    { congruence. }\n    apply signed_byte_int_unsigned_repr_eq.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    { eapply store_unchanged_on'; eauto. }\n    unfold mem_range. ii. des. ss. nia.\nQed.\n\n\n\nRecord mem_cst_blk (m: mem) (st: CtrlState.t) (b_cst: block): Prop :=\n  MemCtrlState {\n      (* mem_cst_load: *)\n      (*   Mem.loadbytes m b_cst 0 8 = *)\n      (*   Some (inj_bytes (CtrlState.to_bytes cst)); *)\n\n      mem_cst_mode: (* exists md_z, *)\n        (* Mem.loadbytes m b_cst 0 1 = Some [Byte (Byte.repr md_z)] /\\ *)\n        (* mode st = mode_of_Z md_z ; *)\n        Mem.loadbytes m b_cst 0 1 =\n        Some [Byte (Byte.repr (mode_to_Z (mode st)))] ;\n      mem_cst_tout: Mem.loadbytes m b_cst 1 1 =\n                    Some [Byte (Byte.repr (timeout st))] ;\n      mem_cst_qbgn: Mem.loadbytes m b_cst 2 1 =\n                    Some [Byte (Byte.repr (queue_begin st))] ;\n      mem_cst_qend: Mem.loadbytes m b_cst 3 1 =\n                    Some [Byte (Byte.repr (queue_end st))] ;\n      mem_cst_q: Mem.loadbytes m b_cst 4 4 =\n                 Some (inj_bytes (map Byte.repr (queue st))) ;\n\n      mem_cst_perm:\n        Mem.range_perm m b_cst 0 8 Cur Writable;\n    }.\n\nLemma loadbytes_mem_cst\n      m b_cst bs md st\n      (PERM: Mem.range_perm m b_cst 0 8 Cur Writable)\n      (LBS: Mem.loadbytes m b_cst 0 8 =\n            Some (Byte (Byte.repr (mode_to_Z md))\n                       :: inj_bytes (tl bs)))\n      (* (STATE: st = of_bytes bs) *)\n      (STATE: st = copy_state_from_hb md bs)\n  : mem_cst_blk m st b_cst.\nProof.\n  subst st.\n\n  replace 8 with (1 + 7) in LBS by ss.\n  eapply Mem.loadbytes_split in LBS; try nia.\n  destruct LBS as (mvs1 & mvs & LBS1 & LBS & MVS_EQ). ss.\n  hexploit Mem.loadbytes_length; try apply LBS1.\n  intros LEN_BS1.\n  destruct mvs1 as [| mv1 []]; ss. clarify.\n  destruct bs as [| b1 bs].\n  { exfalso. ss.\n    apply Mem.loadbytes_length in LBS. ss. }\n  ss.\n\n  replace 7 with (1 + 6) in LBS by ss.\n  eapply Mem.loadbytes_split in LBS; try nia.\n  destruct LBS as (mvs1 & mvs & LBS2 & LBS & MVS_EQ). ss.\n  hexploit Mem.loadbytes_length; try apply LBS2.\n  intros LEN_BS2.\n  destruct mvs1 as [| mv1 []]; ss.\n  destruct bs as [| b2 bs]; ss. clarify.\n\n  replace 6 with (1 + 5) in LBS by ss.\n  eapply Mem.loadbytes_split in LBS; try nia.\n  destruct LBS as (mvs1 & mvs & LBS3 & LBS & MVS_EQ). ss.\n  hexploit Mem.loadbytes_length; try apply LBS3.\n  intros LEN_BS3.\n  destruct mvs1 as [| mv1 []]; ss.\n  destruct bs as [| b3 bs]; ss. clarify.\n\n  replace 5 with (1 + 4) in LBS by ss.\n  eapply Mem.loadbytes_split in LBS; try nia.\n  destruct LBS as (mvs1 & mvs & LBS4 & LBS & MVS_EQ). ss.\n  hexploit Mem.loadbytes_length; try apply LBS4.\n  intros LEN_BS4.\n  destruct mvs1 as [| mv1 []]; ss.\n  destruct bs as [| b4 bs]; ss. clarify.\n\n  unfold of_bytes. ss.\n  econs; ss.\n  - rewrite Byte.repr_signed. ss.\n  - rewrite Byte.repr_signed. ss.\n  - rewrite Byte.repr_signed. ss.\n  - repeat rewrite Byte.repr_signed.\n    hexploit Mem.loadbytes_length; try apply LBS.\n    intro LEN_BS.\n    destruct bs as [| ? bs]; ss.\n    destruct bs as [| ? bs]; ss.\n    destruct bs as [| ? bs]; ss.\n    destruct bs as [| ? bs]; ss.\n    destruct bs as [| ? bs]; ss.\nQed.\n\nLemma mem_cst_loadbytes\n      m b_cst bs st\n      (MEM_CST: mem_cst_blk m st b_cst)\n      (WF_ST: wf st)\n      (TO_BYTES: bs = to_bytes st)\n  : Mem.loadbytes m b_cst 0 8 = Some (inj_bytes bs).\nProof.\n  subst bs.\n  inv WF_ST.\n  inv MEM_CST. ss. des.\n\n  replace 8 with (1 + 7) by ss.\n  rewrite rw_cons_app.\n  eapply Mem.loadbytes_concat; try nia; ss.\n\n  s. replace 7 with (1 + 6) by ss.\n  rewrite rw_cons_app.\n  eapply Mem.loadbytes_concat; try nia; ss.\n\n  s. replace 6 with (1 + 5) by ss.\n  rewrite rw_cons_app.\n  eapply Mem.loadbytes_concat; try nia; ss.\n\n  s. replace 5 with (1 + 4) by ss.\n  rewrite rw_cons_app.\n  eapply Mem.loadbytes_concat; try nia; ss.\nQed.\n\n\n\nLemma store_set_mode\n      md m m' st b\n      (MEM_CST: mem_cst_blk m st b)\n      (STORE: Mem.store Mint8signed m b\n                        0 (Vint (Int.repr (mode_to_Z md))) = Some m')\n  : mem_cst_blk m' (set_mode md st) b.\nProof.\n  destruct st as [md_p tout qb qe q].\n  inv MEM_CST.\n  unfold set_mode. ss.\n\n  hexploit store_unchanged_on'; eauto.\n  s. unfold mem_range. i.\n\n  econs; s.\n  - hexploit Mem.load_loadbytes.\n    { eapply Mem.load_store_same in STORE.\n      apply STORE. }\n    clear. ss.\n    intros (bs & LBS & VEQ).\n    rewrite LBS. f_equal.\n    apply Mem.loadbytes_length in LBS.\n    destruct bs as [| mv []]; ss.\n    f_equal.\n    rewrite sign_ext_byte_range in VEQ.\n    2: { destruct md; ss. }\n\n    destruct mv; ss. f_equal.\n    rewrite decode_val_signed_byte in VEQ.\n\n    assert (MODE_TO_Z_EQ: mode_to_Z md = Byte.signed i).\n    { apply Int_repr_eq_inv.\n      { destruct md; ss. }\n      { r. generalize (Byte.signed_range i).\n        range_stac. }\n\n      assert (AUX: forall x y, Vint x = Vint y -> x = y).\n      { inversion 1. ss. }\n      apply AUX. ss.\n    }\n    rewrite MODE_TO_Z_EQ.\n    rewrite Byte.repr_signed. ss.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold mem_range.\n    ii. nia.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold mem_range.\n    ii. nia.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold mem_range.\n    ii. nia.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold mem_range.\n    ii. nia.\n  - ii. eapply Mem.perm_store_1; eauto.\nQed.\n\n\nLemma init_zerobytes\n  : of_bytes (List.repeat Byte.zero 8) = init.\nProof.\n  unfold of_bytes, init. ss.\nQed.\n\n\nSection MEMORY_INV.\n\n  Variable ge: genv.\n\n  Let fsymb (id: ident) (bpred: block -> Prop): Prop :=\n    forall b (FIND_SYMB: Genv.find_symbol ge id = Some b),\n      bpred b.\n\n  Definition mem_cst (m: mem) (cst: CtrlState.t): Prop :=\n    fsymb _state (mem_cst_blk m cst).\n\n  Definition mem_grant (m: mem): Prop :=\n    fsymb _grant_msg\n          (fun b_gr => Mem.loadbytes m b_gr 0 8 =\n                    Some (inj_bytes grant_msg)).\n\n  Definition inv_ctrl\n             (ast: CtrlState.t) (m: mem): Prop :=\n    <<CST_WF: CtrlState.wf ast>> /\\\n    <<MEM_CST: mem_cst m ast>> /\\\n    <<MEM_GRANT: mem_grant m>>.\n\n  Lemma mem_cst_unch\n        ast m m'\n        (MEM_CST : mem_cst m ast)\n        (MEM_UNCH : Mem.unchanged_on (blocks_of ge [_state]) m m')\n    : mem_cst m' ast.\n  Proof.\n    rr. rr in MEM_CST. i.\n    hexploit MEM_CST.\n    { apply FIND_SYMB. }\n    inversion 1.\n\n    assert (forall i, blocks_of ge [_state] b i).\n    { unfold blocks_of. i.\n      exists _state.\n      split.\n      * clear. ss. eauto.\n      * apply FIND_SYMB.\n    }\n\n    econs;\n      try by eapply Mem.loadbytes_unchanged_on; eauto.\n    ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_cst_unch_diffblk\n        ast m m' b\n        (MEM_CST : mem_cst m ast)\n        (MEM_UNCH : mem_changed_block b m m')\n        (FSYMB: Genv.find_symbol ge _state <> Some b)\n    : mem_cst m' ast.\n  Proof.\n    eapply mem_cst_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of. i.\n    simpl in *. des; ss.\n    ii. subst. ss.\n  Qed.\n\n  Lemma mem_grant_unch\n        m m'\n        (MEM_GRANT : mem_grant m)\n        (MEM_UNCH : Mem.unchanged_on (blocks_of ge [_grant_msg]) m m')\n    : mem_grant m'.\n  Proof.\n    rr. rr in MEM_GRANT. i.\n    hexploit MEM_GRANT.\n    { apply FIND_SYMB. }\n    i. eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold blocks_of.\n    intros _ _.\n    exists _grant_msg.\n    splits.\n    - clear. ss. eauto.\n    - apply FIND_SYMB.\n  Qed.\n\n  Lemma mem_grant_unch_diffblk\n        m m' b\n        (MEM_CST : mem_grant m)\n        (MEM_UNCH : mem_changed_block b m m')\n        (FSYMB: Genv.find_symbol ge _grant_msg <> Some b)\n    : mem_grant m'.\n  Proof.\n    eapply mem_grant_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of. i.\n    simpl in *. des; ss.\n    ii. subst. ss.\n  Qed.\n\n  Lemma inv_ctrl_dep_app_blocks\n    : forall (ast : CtrlState.t) (m m' : mem)\n        (INV: inv_ctrl ast m)\n        (MEM_UNCH: Mem.unchanged_on (blocks_of ge ctrl_gvar_ids) m m'),\n      inv_ctrl ast m'.\n  Proof.\n    unfold inv_ctrl. i. des.\n    splits.\n    - ss.\n    - eapply mem_cst_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      unfold blocks_of. ss.\n      i. des; ss.\n      clarify. esplits; eauto.\n    - eapply mem_grant_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      unfold blocks_of. ss.\n      i. des; ss.\n      clarify.\n      exists _grant_msg. esplits; eauto.\n  Qed.\n\nEnd MEMORY_INV.\n\n\nSection MEM_INIT.\n\n  Variable tid: nat.\n  Variable cprog: Clight.program.\n\n  (* Hypothesis 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  Let GENV_PROPS\n    : genv_props (globalenv cprog)\n                 (main_gvar_ilist tid ++ ctrl_gvar_ilist)\n                 (main_gfun_ilist ++ ctrl_gfun_ilist)\n                 (main_cenv_ilist ++ ctrl_cenv_ilist).\n  Proof.\n    rewrite CPROG_EQ.\n    apply (genv_props_ctrl tid).\n  Qed.\n\n  Lemma inv_ctrl_init:\n    forall (m_i : mem),\n      Genv.init_mem cprog = Some m_i ->\n      inv_ctrl ge CtrlState.init m_i.\n  Proof.\n    intros m_i INIT_MEM. r.\n    split.\n    { apply CtrlState.wf_init. }\n\n    assert (DEFMAP: (prog_defmap cprog) ! _state = Some (Gvar v_state) /\\\n                    (prog_defmap cprog) ! _grant_msg = Some (Gvar v_grant_msg)).\n    { rewrite CPROG_EQ.\n      change (prog_defmap (prog_ctrl (Z.of_nat tid))) with\n          (PTree.combine Linking.link_prog_merge\n                         (prog_defmap prog_mw) (prog_defmap (ctrl.prog (Z.of_nat tid)))).\n      do 2 rewrite PTree.gcombine by ss.\n      split.\n      - replace ((prog_defmap prog_mw) ! _state) with\n            (@None (globdef fundef type)).\n        2: {\n          change (prog_defmap prog_mw) with\n              (PTree.combine Linking.link_prog_merge\n                             (prog_defmap config_prog)\n                             (prog_defmap main_prog)).\n          rewrite PTree.gcombine by ss.\n          ss.\n        }\n        ss.\n      - replace ((prog_defmap prog_mw) ! _grant_msg) with\n            (@None (globdef fundef type)).\n        2: {\n          change (prog_defmap prog_mw) with\n              (PTree.combine Linking.link_prog_merge\n                             (prog_defmap config_prog)\n                             (prog_defmap main_prog)).\n          rewrite PTree.gcombine by ss.\n          ss.\n        }\n        ss.\n    }\n    destruct DEFMAP as [DEFMAP1 DEFMAP2].\n\n    split.\n    - (* ctrl_state *)\n      intros b_cst FSYMB_CST.\n\n      apply Genv.find_def_symbol in DEFMAP1.\n      destruct DEFMAP1 as (b_cst' & FSYMB_CST' & FDEF_CST).\n\n      replace (Genv.globalenv cprog) with\n          (genv_genv (globalenv cprog)) in FSYMB_CST' by ss.\n      fold fundef in FSYMB_CST'.\n      rewrite FSYMB_CST in FSYMB_CST'.\n      symmetry in FSYMB_CST'. inv FSYMB_CST'.\n\n      eapply Genv.init_mem_characterization_gen in INIT_MEM.\n      r in INIT_MEM.\n      exploit INIT_MEM; eauto. s.\n      intros (RANGE_PERM & PERM & LOAD & LOADBYTES).\n\n      eapply loadbytes_mem_cst; cycle 2.\n      + rewrite <- init_zerobytes. ss.\n      + rewrite Z.max_l in RANGE_PERM by nia. ss.\n      + rewrite Z.max_l in LOADBYTES by nia.\n        rewrite LOADBYTES by ss.\n        clear. ss.\n\n    - intros b_gr FSYMB_GR.\n      apply Genv.find_def_symbol in DEFMAP2.\n      destruct DEFMAP2 as (b_gr' & FSYMB_GR' & FDEF_GR).\n\n      replace (Genv.globalenv cprog) with\n          (genv_genv (globalenv cprog)) in FSYMB_GR' by ss.\n      fold fundef in FSYMB_GR'.\n      rewrite FSYMB_GR in FSYMB_GR'.\n      symmetry in FSYMB_GR'. clarify.\n\n      eapply Genv.init_mem_characterization_gen in INIT_MEM.\n      r in INIT_MEM.\n      exploit INIT_MEM; eauto. s.\n      intros (RANGE_PERM & PERM & LOAD & LOADBYTES).\n\n      rewrite LOADBYTES by ss.\n      ss.\n  Qed.\n\nEnd MEM_INIT.\n\nSection SIM_FUNCS.\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 ge := (globalenv cprog).\n  Notation prog := (prog_of_clight 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\n  Definition idx_qs: nat := 20.\n\n  Lemma sim_qrange_sanitize\n        (itr: itree progE unit)\n        (m: mem) (k: cont)\n        (i: Z) (idx_ret: nat)\n        (CALL_CONT: is_call_cont k)\n        (RANGE_I: IntRange.sintz i)\n        (SIM_RET:\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate (Vint (Int.repr (qrange_sanitize i))) k m))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_qs)%nat itr\n            (Callstate (Internal f_qrange_sanitize)\n                       [Vint (Int.repr i)] k m).\n  Proof.\n    (* clear CPROG_EQ. *)\n    unfold idx_qs.\n    start_func.\n    { econs. }\n    ss.\n    fw. fw. fw.\n    { econs.\n      - eval_comput.\n        repr_tac. ss.\n      - rewrite bool_val_of_bool. ss.\n    }\n    unfold qrange_sanitize in SIM_RET.\n\n    destruct (Z.ltb_spec i 0).\n    - s.\n      fw.\n      { econs. eval_comput. ss. }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        - eval_comput. ss.\n        - ss.\n      }\n      rewrite Int.eq_true. s.\n      fw.\n      { econs.\n        - eval_comput. ss.\n        - eval_comput. ss.\n        - ss.\n      }\n      destruct (Z.leb_spec 0 i).\n      { exfalso. nia. }\n      rewrite andb_false_l in SIM_RET.\n\n      red_idx idx_ret.\n      rewrite call_cont_is_call_cont by ss.\n      apply SIM_RET.\n    - s.\n      fw.\n      { econs.\n        eval_comput.\n        repr_tac.\n        instantiate (1:= if i <? 4 then Vtrue else Vfalse).\n        destruct (Z.ltb_spec i 4); ss.\n      }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        - eval_comput. reflexivity.\n        - instantiate (1:= (i <? 4)).\n          clear. desf.\n      }\n\n      destruct (Z.leb_spec 0 i).\n      2: { exfalso. nia. }\n\n      unfold QSIZE in *.\n      destruct (Z.ltb_spec i 4); ss.\n      + (* safe value *)\n        fw.\n        { econs.\n          - eval_comput. reflexivity.\n          - eval_comput. reflexivity.\n          - ss.\n        }\n        rewrite call_cont_is_call_cont by ss.\n        red_idx idx_ret.\n        apply SIM_RET.\n      + (* return 0 *)\n        fw.\n        { econs.\n          - eval_comput. reflexivity.\n          - eval_comput. reflexivity.\n          - ss.\n        }\n        rewrite call_cont_is_call_cont by ss.\n        red_idx idx_ret.\n        apply SIM_RET.\n  Qed.\n\n\n  Opaque idx_qs.\n  Definition idx_aqi: nat := idx_qs + 20.\n\n  Lemma sim_adv_qidx\n        (itr: itree progE unit)\n        (m: mem) (k: cont)\n        (i: Z) (idx_ret: nat)\n        (CALL_CONT: is_call_cont k)\n        (RANGE_I: IntRange.sintz i)\n        (SIM_RET:\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate (Vint (Int.repr (adv_qidx i))) k m))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_aqi)%nat itr\n            (Callstate (Internal f_adv_qidx)\n                       [Vint (Int.repr i)] k m).\n  Proof.\n    (* clear CPROG_EQ. *)\n    unfold idx_aqi.\n    start_func.\n    { econs. }\n    simpl in *.\n\n    fw. fw. fw. fw. fw.\n    { econs.\n      eval_comput.\n      rewrite Int_add_repr_signed by range_stac.\n      reflexivity. }\n    upd_lenv.\n\n    fw. fw.\n    { econs.\n      eval_comput.\n      reflexivity. }\n    upd_lenv.\n\n    fw. fw.\n    { hexploit (in_gfun_ilist _qrange_sanitize); [sIn|].\n      i. des.\n      econs; eauto.\n      - ss.\n      - eval_comput. rewrite FDEF_SYMB. ss.\n      - eval_comput.\n        reflexivity.\n      - ss.\n    }\n\n    red_idx (idx_ret + 10 + idx_qs)%nat.\n    replace (Int.repr (i + 1)) with\n        (Int.repr (Int.signed (Int.repr (i + 1)))).\n    2: { rewrite Int.repr_signed. ss. }\n\n    eapply sim_qrange_sanitize; eauto.\n    { ss. }\n    { apply Int.signed_range. }\n\n    fw. upd_lenv.\n    fw. fw.\n    { econs.\n      - eval_comput.\n        replace (qrange_sanitize (Int.signed (Int.repr (i + 1))))\n          with (adv_qidx i).\n        2: { unfold adv_qidx.\n             unfold qrange_sanitize.\n\n             destruct (Z.ltb_spec i Int.max_signed).\n             - assert (IntRange.sintz (i + 1)).\n               { range_stac. }\n               rewrite Int.signed_repr by range_stac.\n               ss.\n             - assert (i = Int.max_signed).\n               { r in RANGE_I.\n                 nia. }\n               subst i. ss.\n        }\n        reflexivity.\n      - ss.\n      - ss.\n    }\n    ss.\n\n    rewrite call_cont_is_call_cont by ss.\n    red_idx (idx_ret)%nat.\n    apply SIM_RET.\n  Qed.\n\n\n  Opaque idx_aqi.\n\n  Definition idx_chdev: nat := 30.\n\n  Lemma sim_check_dev_id\n        (itr: itree progE unit)\n        (m: mem) (k: cont)\n        (tid_dev: Z) (idx_ret: nat)\n        (CALL_CONT: is_call_cont k)\n        (RANGE_TID_DEV: IntRange.sintz tid_dev)\n        (SIM_RET:\n           paco3 (_sim_itree prog) r\n                 idx_ret itr\n                 (Returnstate (Val.of_bool (check_dev_id tid_dev)) k m))\n    : paco3 (_sim_itree prog) r\n            (idx_ret + idx_chdev)%nat itr\n            (Callstate (Internal f_check_dev_id)\n                       [Vint (Int.repr tid_dev)] k m).\n  Proof.\n    (* clear CPROG_EQ. *)\n    unfold idx_chdev.\n    start_func.\n    { econs. }\n    unfold check_dev_id in SIM_RET. ss.\n\n    fw. fw. 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    change (Z.of_nat 3) with 3 in *.\n    change (Z.of_nat 4) with 4 in *.\n    change (Z.of_nat 5) with 5 in *.\n\n    destruct (Z.eqb tid_dev 3).\n    { (* tid_dev = 3 *)\n      fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        { eval_comput. reflexivity. }\n        ss. }\n      rewrite Int.eq_false by ss.\n      s.\n      fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs; ss.\n        - eval_comput. ss.\n        - ss. }\n\n      ss.\n      rewrite call_cont_is_call_cont by ss.\n\n      red_idx idx_ret.\n      eapply SIM_RET.\n    }\n    fw.\n    { econs.\n      eval_comput.\n      rewrite Int_eq_repr_signed by range_stac.\n      instantiate (1:= if tid_dev =? 4 then Vtrue else Vfalse).\n      destruct (Z.eqb_spec tid_dev 4); ss.\n    }\n    upd_lenv.\n    fw.\n\n    destruct (Z.eqb tid_dev 4).\n    { (* tid_dev = 4 *)\n      fw.\n      { econs.\n        - eval_comput. reflexivity.\n        - ss. }\n      rewrite Int.eq_false by ss.\n      s.\n      fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs; ss.\n        - eval_comput. ss.\n        - ss. }\n\n      ss.\n      rewrite call_cont_is_call_cont by ss.\n\n      red_idx idx_ret.\n      eapply SIM_RET.\n    }\n\n    fw.\n    { econs.\n      - eval_comput. ss.\n      - ss. }\n    rewrite Int.eq_true. s.\n\n    fw.\n    { econs.\n      eval_comput.\n      rewrite Int_eq_repr_signed by range_stac.\n      instantiate (1:= if tid_dev =? 5 then Vtrue else Vfalse).\n      destruct (Z.eqb_spec tid_dev 5); ss.\n    }\n    upd_lenv.\n    fw.\n\n    destruct (Z.eqb tid_dev 5).\n    { (* tid_dev = 5 *)\n      fw.\n      { econs.\n        eval_comput. reflexivity. }\n      upd_lenv.\n      fw. fw.\n      { econs; ss.\n        - eval_comput. ss.\n        - ss. }\n\n      ss.\n      rewrite call_cont_is_call_cont by ss.\n      red_idx idx_ret.\n      eapply SIM_RET.\n    }\n    (* false *)\n    fw.\n    { econs. eval_comput. ss. }\n    upd_lenv.\n    fw. fw.\n    { econs; ss.\n      - eval_comput. ss.\n      - ss. }\n    s. rewrite call_cont_is_call_cont by ss.\n    red_idx idx_ret.\n    eapply SIM_RET.\n  Qed.\n\nEnd SIM_FUNCS.\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_Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.1995602331535608}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import BaremoreHandler.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import RunSMC.Spec.\nRequire Import TableAux.Spec.\nRequire Import TableDataOpsIntro.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance TableDataOpsIntro_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance TableDataOpsIntro_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance table_create_inv: PreservesInvariants table_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance table_destroy_inv: PreservesInvariants table_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance table_map_inv: PreservesInvariants table_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance table_unmap_inv: PreservesInvariants table_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_create_inv: PreservesInvariants data_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_create_unknown_inv: PreservesInvariants data_create_unknown_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_destroy_inv: PreservesInvariants data_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_run_inv: PreservesInvariants smc_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance validate_table_commands_inv: PreservesInvariants validate_table_commands_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition TableDataOpsIntro_fresh : compatlayer (cdata RData) :=\n      _table_create \u21a6 gensem table_create_spec\n        \u2295 _table_destroy \u21a6 gensem table_destroy_spec\n        \u2295 _table_map \u21a6 gensem table_map_spec\n        \u2295 _table_unmap \u21a6 gensem table_unmap_spec\n        \u2295 _data_create \u21a6 gensem data_create_spec\n        \u2295 _data_create_unknown \u21a6 gensem data_create_unknown_spec\n        \u2295 _data_destroy \u21a6 gensem data_destroy_spec\n      .\n\n    Definition TableDataOpsIntro_passthrough : compatlayer (cdata RData) :=\n      _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _smc_rec_run \u21a6 gensem smc_rec_run_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _validate_table_commands \u21a6 gensem validate_table_commands_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n      .\n\n    Definition TableDataOpsIntro := TableDataOpsIntro_fresh \u2295 TableDataOpsIntro_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.19956023315356075}}
{"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 PKContext         *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Constant.\nRequire Import GlobIdent.\n\nRequire Import liblayers.compat.CompatLayers.\nRequire Import LAsm.\n\nSection ASM_CODE.\n\n  Definition AddrMake1 (r: ireg) :=\n    Addrmode (Some r) (Some (r, Int.repr 2)) (inl Int.zero).\n\n  Definition AddrMake2 (r: ireg) :=\n    Addrmode None (Some (r, Int.repr 8)) (inr (KCtxtPool_LOC, Int.zero)).\n\n  Definition AddrMake3 (r: ireg) (ofs:int) :=\n    Addrmode (Some r) None (inl ofs).\n\n  (*\t\n\t.globl cswitch\ncswitch:\n\t/* save the old kernel context */\n\tleal\t(%eax,%eax,2), %eax\n\tleal\tKCtxtPool_LOC(,%eax,8), %eax\n\tmovl\t%esp, (%eax)\n\tmovl\t%edi, 4(%eax)\n\tmovl\t%esi, 8(%eax)\n\tmovl\t%ebx, 12(%eax)\n\tmovl\t%ebp, 16(%eax)\n\n\tpopl\t%ecx\n\tmovl\t%ecx, 20(%eax)\n\n\t/* load the new kernel context */\n\tleal\t(%edx,%edx,2), %edx\n\tleal\tKCtxtPool_LOC(,%edx,8), %edx\n\tmovl\t(%edx), %esp\n\tmovl\t4(%edx), %edi\n\tmovl\t8(%edx), %esi\n\tmovl\t12(%edx), %ebx\n\tmovl\t16(%edx), %ebp\n\tmovl\t20(%edx), %ecx\n\tpushl\t%ecx\n\txorl\t%eax, %eax\n\tret\n\n   *)\n\n  Definition Im_cswitch : list instruction := \n    (*save the old kernel context*)\n    asm_instruction (Plea EAX (AddrMake1 EAX)) ::  (* EAX = EAX * 3 *)\n                    asm_instruction (Plea EAX (AddrMake2 EAX)) ::  (* EAX = KCtxtPool_LOC (EAX * 8) *)\n                    asm_instruction (Pmov_mr (AddrMake3 EAX Int.zero) Asm.ESP) ::\n                    asm_instruction (Pmov_mr (AddrMake3 EAX (Int.repr 4)) Asm.EDI) ::\n                    asm_instruction (Pmov_mr (AddrMake3 EAX (Int.repr 8)) Asm.ESI) ::\n                    asm_instruction (Pmov_mr (AddrMake3 EAX (Int.repr 12)) Asm.EBX) ::\n                    asm_instruction (Pmov_mr (AddrMake3 EAX (Int.repr 16)) Asm.EBP) ::\n                    Ppopl_RA ECX ::\n                    asm_instruction (Pmov_mr (AddrMake3 EAX (Int.repr 20)) ECX) ::\n                    \n                    (*load the new kernel context*)\n                    asm_instruction (Plea EDX (AddrMake1 EDX)) ::  (* EAX = EAX * 3 *)\n                    asm_instruction (Plea EDX (AddrMake2 EDX)) ::  (* EAX = KCtxtPool_LOC (EAX * 8) *)\n                    \n                    asm_instruction (Pmov_rm Asm.ESP (AddrMake3 EDX Int.zero)) ::\n                    asm_instruction (Pmov_rm Asm.EDI (AddrMake3 EDX (Int.repr 4))) ::\n                    asm_instruction (Pmov_rm Asm.ESI (AddrMake3 EDX (Int.repr 8))) ::\n                    asm_instruction (Pmov_rm Asm.EBX (AddrMake3 EDX (Int.repr 12))) ::\n                    asm_instruction (Pmov_rm Asm.EBP (AddrMake3 EDX (Int.repr 16))) ::\n                    asm_instruction (Pmov_rm Asm.ECX (AddrMake3 EDX (Int.repr 20))) ::\n                    Ppushl_RA ECX ::\n                    asm_instruction (Pxor_r EAX) ::\n                    asm_instruction (Pret) ::\n                    nil.\n\n  Definition cswitch_function: function := mkfunction null_signature Im_cswitch.\n  \nEnd ASM_CODE.\n\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/KContextGenAsmSource.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1995602291961257}}
{"text": "Require Import HoTT.\nRequire Import UnivalenceAxiom.\n\nRequire Import HoTTEx.\nRequire Import Denotation.\nRequire Import UnivalentSemantics.\n\nOpen Scope type.\n\nModule AggregationOptimization (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\n  Parameter integer : type.\n  Parameter count : forall {T}, aggregator T integer.\n  Notation \"'COUNT' ( e )\" := (aggregatorGroupByProj count e).\n  \n  Definition AggregationQuery : Type.\n    refine (forall (\u0393 : Schema) s (a : relation s) C0 (value : Column C0 s) C1 (label: Column C1 s) (l : constant C1), _).\n    pose (@variable C1 (\u0393 ++ s) (right\u22c5label)) as lbl.\n    pose (@variable C0 (\u0393 ++ s) (right\u22c5value)) as val.\n    pose (@variable C1 (\u0393 ++ (singleton C1 ++ singleton integer)) (right\u22c5left)) as lbl'. \n    refine (\u27e6 \u0393 \u22a2 (SELECT *\n                  FROM1\n                  (SELECT (combineGroupByProj PLAIN(lbl) COUNT(val)) FROM1 table a GROUP BY (right\u22c5label)) \n                  WHERE equal lbl' (constantExpr l)) : _ \u27e7 = \n            \u27e6 \u0393 \u22a2 SELECT (combineGroupByProj PLAIN(lbl) COUNT(val))\n                  FROM1 table a\n                  WHERE equal lbl (constantExpr l) \n                  GROUP BY (right\u22c5label) : _ \u27e7).\n  Defined.\n  Arguments AggregationQuery /.\n  \n  Lemma aggregationQuery : AggregationQuery. \n    start.\n    apply path_universe_uncurried.  \n    apply equiv_iff_hprop_uncurried.\n    constructor.\n    + intros [p u].  \n      strip_truncations.\n      destruct u as [t0 [a0 u]].\n      apply tr.\n      rewrite <- u in p.\n      refine (t0; (_,  _)).      \n      * refine (_, a0).\n        assumption. \n      * rewrite <- u.\n        rewrite p.\n        repeat f_ap.\n        by_extensionality t'.\n        f_ap.\n        by_extensionality t1.\n        rewrite (path_universe_uncurried (equiv_prod_assoc _ _ _)).\n        repeat f_ap.\n        rewrite (path_universe_uncurried (equiv_prod_symm _ _)).\n        apply path_universe_uncurried.\n        apply hprop_prod_l'.\n        intros.\n        symmetry.\n        assumption.\n    + intros p.\n      strip_truncations.\n      destruct p as [t0 [[c d] e]].\n      rewrite <- e.\n      cbn.\n      constructor; try apply tr; try assumption.\n      refine (t0; (d, _)).\n      repeat f_ap.\n      by_extensionality t'.\n      f_ap.\n      by_extensionality t1.\n      rewrite <- c.\n      f_ap.\n      rewrite (path_universe_uncurried (equiv_prod_assoc _ _ _)).\n      f_ap.\n      rewrite (path_universe_uncurried (equiv_prod_symm _ _)).\n      symmetry.\n      apply path_universe_uncurried.\n      apply hprop_prod_l'.\n      intros.\n      symmetry.\n      assumption.\n  Qed.\n  \nEnd AggregationOptimization.\n\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/Aggregation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.1995452764887075}}
{"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 BaremoreSMC.Spec.\nRequire Import RmiOps.Specs.granule_undelegate_ops.\nRequire Import RmiOps.LowSpecs.granule_undelegate_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       granule_set_state_spec\n       smc_mark_nonsecure_spec\n       granule_unlock_spec\n    .\n\n  Lemma granule_undelegate_ops_spec_exists:\n    forall habd habd'  labd g addr\n           (Hspec: granule_undelegate_ops_spec g addr habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', granule_undelegate_ops_spec0 g addr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. inv id_rdata. destruct g, addr.\n    unfold granule_undelegate_ops_spec, granule_undelegate_ops_spec0 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/granule_undelegate_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.1995452744815315}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Converted imports: *)\n\nRequire DynFlags.\nRequire FastString.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire Panic.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nInductive Width : Type\n  := W8 : Width\n  |  W16 : Width\n  |  W32 : Width\n  |  W64 : Width\n  |  W80 : Width\n  |  W128 : Width\n  |  W256 : Width\n  |  W512 : Width.\n\nDefinition Length :=\n  GHC.Num.Int%type.\n\nInductive ForeignHint : Type\n  := NoHint : ForeignHint\n  |  AddrHint : ForeignHint\n  |  SignedHint : ForeignHint.\n\nInductive CmmCat : Type\n  := GcPtrCat : CmmCat\n  |  BitsCat : CmmCat\n  |  FloatCat : CmmCat\n  |  VecCat : Length -> CmmCat -> CmmCat.\n\nInductive CmmType : Type := Mk_CmmType : CmmCat -> Width -> CmmType.\n\nInstance Default__Width : GHC.Err.Default Width := GHC.Err.Build_Default _ W8.\n\nInstance Default__ForeignHint : GHC.Err.Default ForeignHint :=\n  GHC.Err.Build_Default _ NoHint.\n\nInstance Default__CmmCat : GHC.Err.Default CmmCat :=\n  GHC.Err.Build_Default _ GcPtrCat.\n\n(* Midamble *)\n\nRequire Import GHC.Nat.\n\nInstance Default__CmmType : GHC.Err.Default CmmType :=\n\t { default := Mk_CmmType GHC.Err.default GHC.Err.default }.\n\n(* Converted value declarations: *)\n\nDefinition wordWidth : DynFlags.DynFlags -> Width :=\n  fun dflags =>\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #4 : bool then W32 else\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #8 : bool then W64 else\n    Panic.panic (GHC.Base.hs_string__ \"MachOp.wordRep: Unknown word size\").\n\nDefinition widthInLog : Width -> GHC.Num.Int :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | W8 => #0\n    | W16 => #1\n    | W32 => #2\n    | W64 => #3\n    | W128 => #4\n    | W256 => #5\n    | W512 => #6\n    | W80 => Panic.panic (GHC.Base.hs_string__ \"widthInLog: F80\")\n    end.\n\nDefinition widthInBytes : Width -> GHC.Num.Int :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | W8 => #1\n    | W16 => #2\n    | W32 => #4\n    | W64 => #8\n    | W128 => #16\n    | W256 => #32\n    | W512 => #64\n    | W80 => #10\n    end.\n\nDefinition widthInBits : Width -> GHC.Num.Int :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | W8 => #8\n    | W16 => #16\n    | W32 => #32\n    | W64 => #64\n    | W128 => #128\n    | W256 => #256\n    | W512 => #512\n    | W80 => #80\n    end.\n\nDefinition widthFromBytes : GHC.Num.Int -> Width :=\n  fun arg_0__ =>\n    let 'num_1__ := arg_0__ in\n    if num_1__ GHC.Base.== #1 : bool then W8 else\n    let 'num_2__ := arg_0__ in\n    if num_2__ GHC.Base.== #2 : bool then W16 else\n    let 'num_3__ := arg_0__ in\n    if num_3__ GHC.Base.== #4 : bool then W32 else\n    let 'num_4__ := arg_0__ in\n    if num_4__ GHC.Base.== #8 : bool then W64 else\n    let 'num_5__ := arg_0__ in\n    if num_5__ GHC.Base.== #16 : bool then W128 else\n    let 'num_6__ := arg_0__ in\n    if num_6__ GHC.Base.== #32 : bool then W256 else\n    let 'num_7__ := arg_0__ in\n    if num_7__ GHC.Base.== #64 : bool then W512 else\n    let 'num_8__ := arg_0__ in\n    if num_8__ GHC.Base.== #10 : bool then W80 else\n    let 'n := arg_0__ in\n    Panic.panicStr (GHC.Base.hs_string__ \"no width for given number of bytes\")\n    (Panic.someSDoc).\n\nDefinition vecLength : CmmType -> Length :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType (VecCat l _) _ => l\n    | _ => Panic.panic (GHC.Base.hs_string__ \"vecLength: not a vector\")\n    end.\n\nDefinition vec : Length -> CmmType -> CmmType :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | l, Mk_CmmType cat w =>\n        let vecw : Width := widthFromBytes (l GHC.Num.* widthInBytes w) in\n        Mk_CmmType (VecCat l cat) vecw\n    end.\n\nDefinition vec16 : CmmType -> CmmType :=\n  vec #16.\n\nDefinition vec2 : CmmType -> CmmType :=\n  vec #2.\n\nDefinition vec4 : CmmType -> CmmType :=\n  vec #4.\n\nDefinition vec8 : CmmType -> CmmType :=\n  vec #8.\n\nDefinition typeWidth : CmmType -> Width :=\n  fun '(Mk_CmmType _ w) => w.\n\nDefinition mrStr : Width -> FastString.LitString :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | W8 => FastString.sLit (GHC.Base.hs_string__ \"W8\")\n    | W16 => FastString.sLit (GHC.Base.hs_string__ \"W16\")\n    | W32 => FastString.sLit (GHC.Base.hs_string__ \"W32\")\n    | W64 => FastString.sLit (GHC.Base.hs_string__ \"W64\")\n    | W128 => FastString.sLit (GHC.Base.hs_string__ \"W128\")\n    | W256 => FastString.sLit (GHC.Base.hs_string__ \"W256\")\n    | W512 => FastString.sLit (GHC.Base.hs_string__ \"W512\")\n    | W80 => FastString.sLit (GHC.Base.hs_string__ \"W80\")\n    end.\n\nDefinition isWord64 : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType BitsCat W64 => true\n    | Mk_CmmType GcPtrCat W64 => true\n    | _other => false\n    end.\n\nDefinition isWord32 : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType BitsCat W32 => true\n    | Mk_CmmType GcPtrCat W32 => true\n    | _other => false\n    end.\n\nDefinition isVecType : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType (VecCat _ _) _ => true\n    | _ => false\n    end.\n\nDefinition isGcPtrType : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType GcPtrCat _ => true\n    | _other => false\n    end.\n\nDefinition isFloatType : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType FloatCat _ => true\n    | _other => false\n    end.\n\nDefinition isFloat64 : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType FloatCat W64 => true\n    | _other => false\n    end.\n\nDefinition isFloat32 : CmmType -> bool :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Mk_CmmType FloatCat W32 => true\n    | _other => false\n    end.\n\nDefinition halfWordWidth : DynFlags.DynFlags -> Width :=\n  fun dflags =>\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #4 : bool then W16 else\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #8 : bool then W32 else\n    Panic.panic (GHC.Base.hs_string__ \"MachOp.halfWordRep: Unknown word size\").\n\nDefinition halfWordMask : DynFlags.DynFlags -> GHC.Num.Integer :=\n  fun dflags =>\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #4 : bool then #65535 else\n    if DynFlags.wORD_SIZE dflags GHC.Base.== #8 : bool then #4294967295 else\n    Panic.panic (GHC.Base.hs_string__ \"MachOp.halfWordMask: Unknown word size\").\n\nDefinition gcWord : DynFlags.DynFlags -> CmmType :=\n  fun dflags => Mk_CmmType GcPtrCat (wordWidth dflags).\n\nDefinition cmmVec : GHC.Num.Int -> CmmType -> CmmType :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | n, Mk_CmmType cat w =>\n        Mk_CmmType (VecCat n cat) (widthFromBytes (n GHC.Num.* widthInBytes w))\n    end.\n\nDefinition cmmFloat : Width -> CmmType :=\n  Mk_CmmType FloatCat.\n\nDefinition f32 : CmmType :=\n  cmmFloat W32.\n\nDefinition vec4f32 : CmmType :=\n  vec #4 f32.\n\nDefinition f64 : CmmType :=\n  cmmFloat W64.\n\nDefinition vec2f64 : CmmType :=\n  vec #2 f64.\n\nLocal Definition Eq___CmmCat_op_zeze__ : CmmCat -> CmmCat -> bool :=\n  fun x y => true.\n\nLocal Definition Eq___CmmCat_op_zsze__ : CmmCat -> CmmCat -> bool :=\n  fun x y => negb (Eq___CmmCat_op_zeze__ x y).\n\nProgram Instance Eq___CmmCat : GHC.Base.Eq_ CmmCat :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___CmmCat_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___CmmCat_op_zsze__ |}.\n\nLocal Definition Eq___Width_op_zeze__ : Width -> Width -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | W8, W8 => true\n    | W16, W16 => true\n    | W32, W32 => true\n    | W64, W64 => true\n    | W80, W80 => true\n    | W128, W128 => true\n    | W256, W256 => true\n    | W512, W512 => true\n    | _, _ => false\n    end.\n\nLocal Definition Eq___Width_op_zsze__ : Width -> Width -> bool :=\n  fun x y => negb (Eq___Width_op_zeze__ x y).\n\nProgram Instance Eq___Width : GHC.Base.Eq_ Width :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___Width_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___Width_op_zsze__ |}.\n\nDefinition cmmEqType : CmmType -> CmmType -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | Mk_CmmType c1 w1, Mk_CmmType c2 w2 =>\n        andb (c1 GHC.Base.== c2) (w1 GHC.Base.== w2)\n    end.\n\nDefinition cmmEqType_ignoring_ptrhood : CmmType -> CmmType -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | Mk_CmmType c1 w1, Mk_CmmType c2 w2 =>\n        let weak_eq : CmmCat -> CmmCat -> bool :=\n          fix weak_eq arg_2__ arg_3__\n                := match arg_2__, arg_3__ with\n                   | FloatCat, FloatCat => true\n                   | FloatCat, _other => false\n                   | _other, FloatCat => false\n                   | VecCat l1 cat1, VecCat l2 cat2 => andb (l1 GHC.Base.== l2) (weak_eq cat1 cat2)\n                   | VecCat _ _, _other => false\n                   | _other, VecCat _ _ => false\n                   | _word1, _word2 => true\n                   end in\n        andb (weak_eq c1 c2) (w1 GHC.Base.== w2)\n    end.\n\nDefinition cmmBits : Width -> CmmType :=\n  Mk_CmmType BitsCat.\n\nDefinition bWord : DynFlags.DynFlags -> CmmType :=\n  fun dflags => cmmBits (wordWidth dflags).\n\nDefinition bHalfWord : DynFlags.DynFlags -> CmmType :=\n  fun dflags => cmmBits (halfWordWidth dflags).\n\nDefinition b8 : CmmType :=\n  cmmBits W8.\n\nDefinition vec16b8 : CmmType :=\n  vec #16 b8.\n\nDefinition b64 : CmmType :=\n  cmmBits W64.\n\nDefinition vec2b64 : CmmType :=\n  vec #2 b64.\n\nDefinition b512 : CmmType :=\n  cmmBits W512.\n\nDefinition b32 : CmmType :=\n  cmmBits W32.\n\nDefinition vec4b32 : CmmType :=\n  vec #4 b32.\n\nDefinition b256 : CmmType :=\n  cmmBits W256.\n\nDefinition b16 : CmmType :=\n  cmmBits W16.\n\nDefinition vec8b16 : CmmType :=\n  vec #8 b16.\n\nDefinition b128 : CmmType :=\n  cmmBits W128.\n\n(* Skipping instance `CmmType.Ord__Width' of class `GHC.Base.Ord' *)\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `CmmType.Show__Width' *)\n\nLocal Definition Eq___ForeignHint_op_zeze__\n   : ForeignHint -> ForeignHint -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | NoHint, NoHint => true\n    | AddrHint, AddrHint => true\n    | SignedHint, SignedHint => true\n    | _, _ => false\n    end.\n\nLocal Definition Eq___ForeignHint_op_zsze__\n   : ForeignHint -> ForeignHint -> bool :=\n  fun x y => negb (Eq___ForeignHint_op_zeze__ x y).\n\nProgram Instance Eq___ForeignHint : GHC.Base.Eq_ ForeignHint :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___ForeignHint_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___ForeignHint_op_zsze__ |}.\n\n(* Skipping all instances of class `Outputable.Outputable', including\n   `CmmType.Outputable__Width' *)\n\n(* Skipping all instances of class `Outputable.Outputable', including\n   `CmmType.Outputable__CmmCat' *)\n\n(* Skipping all instances of class `Outputable.Outputable', including\n   `CmmType.Outputable__CmmType' *)\n\n(* External variables:\n     andb bool false negb true DynFlags.DynFlags DynFlags.wORD_SIZE\n     FastString.LitString FastString.sLit GHC.Base.Eq_ GHC.Base.op_zeze__\n     GHC.Base.op_zeze____ GHC.Base.op_zsze____ GHC.Err.Build_Default GHC.Err.Default\n     GHC.Num.Int GHC.Num.Integer GHC.Num.fromInteger GHC.Num.op_zt__ Panic.panic\n     Panic.panicStr Panic.someSDoc\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/lib/CmmType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.19954527448153148}}
{"text": "From compcert Require Import Globalenvs Smallstep AST Integers Events Behaviors Errors Memory.\nRequire Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import STS Behavior.\nRequire Import Any.\nRequire Import ModSem.\nRequire Import Imp.\nRequire Import Imp2Csharpminor.\nRequire Import ImpProofs.\nRequire Import SimSTS2.\nRequire Import Mem0.\nRequire Import IRed.\nFrom Ordinal Require Import Ordinal Arithmetic.\n\nRequire Import Imp2CsharpminorMatch.\nRequire Import Imp2CsharpminorArith.\nRequire Import Imp2CsharpminorGenv.\nRequire Import Imp2CsharpminorLenv.\nRequire Import Imp2CsharpminorMem.\n\nFrom compcert Require Import Csharpminor.\n\nSet Implicit Arguments.\n\nLemma unbind_trigger E:\n  forall [X0 X1 A : Type] (ktr0 : X0 -> itree E A) (ktr1 : X1 -> itree E A) e0 e1,\n    (x <- trigger e0;; ktr0 x = x <- trigger e1;; ktr1 x) -> (X0 = X1 /\\ e0 ~= e1 /\\ ktr0 ~= ktr1).\nProof.\n  i. eapply f_equal with (f:=_observe) in H. cbn in H.\n  inv H. split; auto.\n  dependent destruction H3. dependent destruction H2.\n  cbv in x. subst. split; auto.\n  assert (ktr0 = ktr1); clarify.\n  extensionality x. eapply equal_f in x0.\n  rewrite ! subst_bind in *.\n  irw in x0. eauto.\nQed.\n\nLemma angelic_step :\n  forall (X : Prop) (ktr next : itree eventE Any.t),\n    ModSemL.step (trigger (Take X);;; ktr) None next -> (next = ktr /\\ X).\nProof.\n  i. dependent destruction H; try (irw in x; clarify; fail).\n  rewrite <- bind_trigger in x. apply unbind_trigger in x.\n  des. clarify.\nQed.\n\nLemma eval_exprlist_length :\n  forall a b c d l1 l2\n    (EE: eval_exprlist a b c d l1 l2),\n    <<EELEN: List.length l1 = List.length l2>>.\nProof.\n  i. induction EE; ss; clarify; eauto.\nQed.\n\n\n\nSection PROOF.\n\n\n  Create HintDb ord_step2.\n  Hint Resolve Nat.lt_succ_diag_r OrdArith.lt_from_nat OrdArith.lt_add_r: ord_step2.\n  Hint Extern 1000 => lia: ord_step2.\n  Ltac ord_step2 := eauto with ord_step2.\n\n  Import ModSemL.\n\n  Context `{\u03a3: GRA.t}.\n  Context `{builtins : builtinsTy}.\n\n  Variable srcprog : Imp.programL.\n\n\n\n  Definition compile_val md := @ModL.compile _ EMSConfigImp md.\n\n  Let _sim_mon := Eval simpl in (fun (src: ModL.t) (tgt: Csharpminor.program) => @sim_mon (compile_val src) (semantics tgt)).\n  Hint Resolve _sim_mon: paco.\n\n  Let _ordC_spec := Eval simpl in (fun (src: ModL.t) (tgt: Csharpminor.program) => @ordC_spec (compile_val src) (semantics tgt)).\n\n  Ltac sim_red := try red; Red.prw ltac:(_red_gen) 2 0.\n  Ltac sim_tau := (try sim_red); econs 3; ss; clarify; eexists; exists (step_tau _); eexists; split; [ord_step2|auto].\n  Ltac sim_ord := guclo _ordC_spec; econs.\n\n\n  Ltac solve_ub := des; irw in H; dependent destruction H; clarify.\n  Ltac sim_triggerUB := (try rename H into HH); gstep; ss; unfold triggerUB; try sim_red; econs 5; i; ss; auto;\n                        [solve_ub | irw in  STEP; dependent destruction STEP; clarify].\n\n  Ltac dtm H H0 := eapply angelic_step in H; eapply angelic_step in H0; des; rewrite H; rewrite H0; ss.\n\n\n\n  Fixpoint expr_ord (e: Imp.expr): Ord.t :=\n    match e with\n    | Imp.Var _ => 20\n    | Imp.Lit _ => 20\n    | Imp.Eq e0 e1 => (20 + expr_ord e1 + 20 + expr_ord e0 + 20)%ord\n    | Imp.Lt e0 e1 => (20 + expr_ord e1 + 20 + expr_ord e0 + 20)%ord\n    | Imp.Plus e0 e1 => (20 + expr_ord e1 + 20 + expr_ord e0 + 20)%ord\n    | Imp.Minus e0 e1 => (20 + expr_ord e1 + 20 + expr_ord e0 + 20)%ord\n    | Imp.Mult e0 e1 => (20 + expr_ord e1 + 20 + expr_ord e0 + 20)%ord\n    end.\n\n  Lemma expr_ord_omega e:\n    (expr_ord e < Ord.omega)%ord.\n  Proof.\n    assert (exists n: nat, (expr_ord e <= n)%ord).\n    { induction e; ss.\n      { eexists. refl. }\n      { eexists. refl. }\n      { des. eexists.\n        rewrite IHe1. rewrite IHe2.\n        rewrite <- ! OrdArith.add_from_nat. refl. }\n      { des. eexists.\n        rewrite IHe1. rewrite IHe2.\n        rewrite <- ! OrdArith.add_from_nat. refl. }\n      { des. eexists.\n        rewrite IHe1. rewrite IHe2.\n        rewrite <- ! OrdArith.add_from_nat. refl. }\n      { des. eexists.\n        rewrite IHe1. rewrite IHe2.\n        rewrite <- ! OrdArith.add_from_nat. refl. }\n      { des. eexists.\n        rewrite IHe1. rewrite IHe2.\n        rewrite <- ! OrdArith.add_from_nat. refl. }\n    }\n    des. eapply Ord.le_lt_lt; et. eapply Ord.omega_upperbound.\n  Qed.\n\n  Definition max_fuel := (Ord.omega * Ord.omega)%ord.\n\n  Lemma max_fuel_spec2 e0 e1 (n: Ord.t) :\n    (100 + expr_ord e0 + expr_ord e1 <= 100 + max_fuel + n)%ord.\n  Proof.\n    rewrite ! OrdArith.add_assoc. eapply OrdArith.le_add_r.\n    etrans.\n    2: { eapply OrdArith.add_base_l. }\n    unfold max_fuel. etrans.\n    2: {\n      eapply OrdArith.le_mult_r.\n      eapply Ord.lt_le. eapply Ord.omega_upperbound.\n    }\n    instantiate (1:=2). rewrite Ord.from_nat_S. rewrite Ord.from_nat_S.\n    rewrite OrdArith.mult_S. rewrite OrdArith.mult_S.\n    etrans.\n    2:{ rewrite OrdArith.add_assoc. eapply OrdArith.add_base_r. }\n    etrans.\n    { eapply OrdArith.le_add_l. eapply Ord.lt_le. eapply expr_ord_omega. }\n    { eapply OrdArith.le_add_r. eapply Ord.lt_le. eapply expr_ord_omega. }\n  Qed.\n\n  Lemma max_fuel_spec2' e0 e1 (n: Ord.t) :\n    (100 + expr_ord e0 + expr_ord e1 <= (100 + max_fuel) + 100 + Ord.omega + n)%ord.\n  Proof.\n    set (temp:=(100 + expr_ord e0 + expr_ord e1)%ord).\n    do 2 rewrite OrdArith.add_assoc.\n    subst temp. eapply max_fuel_spec2.\n  Qed.\n\n  Lemma max_fuel_spec1 e (n: Ord.t) :\n    (100 + expr_ord e <= 100 + max_fuel + n)%ord.\n  Proof.\n    etrans.\n    2: { eapply max_fuel_spec2. }\n    eapply OrdArith.add_base_l.\n    Unshelve. all: exact e.\n  Qed.\n\n  Lemma max_fuel_spec1' e (n: Ord.t) :\n    (100 + expr_ord e <= (100 + max_fuel) + 100 + Ord.omega + n)%ord.\n  Proof.\n    do 2 (rewrite OrdArith.add_assoc). eapply max_fuel_spec1.\n  Qed.\n\n  Lemma max_fuel_spec3 (args: list Imp.expr) (n: Ord.t) :\n    (100 + Ord.omega * Datatypes.length args <= 100 + max_fuel + n)%ord.\n  Proof.\n    rewrite ! OrdArith.add_assoc. eapply OrdArith.le_add_r.\n    etrans.\n    2: { eapply OrdArith.add_base_l. }\n    unfold max_fuel. eapply OrdArith.le_mult_r.\n    eapply Ord.lt_le. eapply Ord.omega_upperbound.\n  Qed.\n\n  Lemma max_fuel_spec3' (args: list Imp.expr) (n: Ord.t) :\n    (100 + Ord.omega * Datatypes.length args <= (100 + max_fuel) + 100 + Ord.omega + n)%ord.\n  Proof.\n    do 2 (rewrite OrdArith.add_assoc). eapply max_fuel_spec3.\n  Qed.\n\n  Lemma max_fuel_spec4 e (args: list Imp.expr) (n: Ord.t) :\n    ((100 + Ord.omega * Datatypes.length args) + 100 + (expr_ord e) <= (100 + max_fuel) + 100 + Ord.omega + n)%ord.\n  Proof.\n    rewrite ! OrdArith.add_assoc.\n    etrans.\n    2:{ repeat rewrite <- OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n    etrans.\n    2:{ instantiate (1:= (100 + (Ord.omega * Datatypes.length args) + (100 + Ord.omega))%ord).\n        rewrite <- OrdArith.add_assoc. do 2 eapply OrdArith.le_add_l.\n        eapply OrdArith.le_add_r. unfold max_fuel.\n        eapply OrdArith.le_mult_r. eapply Ord.lt_le. eapply Ord.omega_upperbound.\n    }\n    rewrite ! OrdArith.add_assoc.\n    do 3 eapply OrdArith.le_add_r. eapply Ord.lt_le. eapply expr_ord_omega.\n  Qed.\n\n  Lemma max_fuel_spec4' (args: list Imp.expr) (n: Ord.t) :\n    (100 + Ord.omega * Datatypes.length args <= 100 + Ord.omega * Datatypes.length args + n)%ord.\n  Proof.\n    apply OrdArith.add_base_l.\n  Qed.\n\n\n\n\n\n  Lemma step_expr\n        (src: ModL.t) (tgt: Csharpminor.program)\n        e te\n        tcode tf tcont tge tle tm\n        r rg ms mn ge le pstate ktr\n        i1\n        (MLE: match_le srcprog le tle)\n        (CEXP: compile_expr e = te)\n        (SIM:\n           forall rv trv,\n             eval_expr tge empty_env tle tm te trv ->\n             trv = map_val srcprog rv ->\n             gpaco3 (_sim (compile_val src) (semantics tgt))\n                    (cpn3 (_sim (compile_val src) (semantics tgt))) rg rg i1\n                    (ktr (pstate, (le, rv)))\n                    (State tf tcode tcont empty_env tle tm))\n    :\n      gpaco3 (_sim (compile_val src) (semantics tgt))\n             (cpn3 (_sim (compile_val src) (semantics tgt)))\n             r rg (i1 + expr_ord e)%ord\n             (r0 <- EventsL.interp_Es (prog ms) (transl_all mn (interp_imp ge (denote_expr e) le)) (pstate);; ktr r0)\n             (State tf tcode tcont empty_env tle tm).\n  Proof.\n    generalize dependent ktr. generalize dependent te.\n    move MLE before pstate. revert_until MLE. revert r rg.\n    generalize dependent e. Local Opaque Init.Nat.add. induction e; i; ss; des; clarify.\n    - rewrite interp_imp_expr_Var. sim_red.\n      destruct (alist_find v le) eqn:AFIND; try sim_red.\n      + do 2 (gstep; sim_tau). red. sim_red.\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        eapply SIM; auto.\n        econs. inv MLE. specialize ML with (x:=v) (sv:=v0).\n        hexploit ML; auto.\n      + sim_triggerUB.\n    - rewrite interp_imp_expr_Lit.\n      do 1 (gstep; sim_tau). red.\n      sim_red.\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      eapply SIM; eauto. econs. unfold map_val. ss.\n\n    - rewrite interp_imp_expr_Eq.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + 20 + expr_ord e2 + 20) + expr_ord e1)%ord).\n        rewrite <- ! OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n      eapply IHe1; auto. clear IHe1.\n      i. sim_red.\n      sim_ord.\n      { instantiate (1:=(i1 + 20 + expr_ord e2)%ord).\n        eapply OrdArith.add_base_l. }\n      eapply IHe2; auto. clear IHe2.\n      i. sim_red.\n      destruct (wf_val rv && wf_val rv0) eqn:WFVAL.\n      2: sim_triggerUB.\n      sim_red. destruct rv; destruct rv0; try sim_triggerUB.\n      2,3,4: gstep; ss; unfold triggerUB; try sim_red.\n      des_ifs; ss; try sim_triggerUB.\n      + sim_ord.\n        { eapply OrdArith.add_base_l. }\n        sim_red.\n        eapply SIM; eauto.\n        econs; eauto.\n        { econs; eauto. }\n        ss. f_equal. rewrite Z.eqb_eq in Heq. clarify.\n        rewrite Int64.eq_true. ss.\n      + sim_ord.\n        { eapply OrdArith.add_base_l. }\n        sim_red.\n        eapply SIM; eauto.\n        econs; eauto.\n        { econs; eauto. }\n        ss. f_equal.\n        bsimpl. des. unfold_intrange_64. bsimpl. des.\n        apply sumbool_to_bool_true in WFVAL.\n        apply sumbool_to_bool_true in WFVAL0.\n        apply sumbool_to_bool_true in WFVAL1.\n        apply sumbool_to_bool_true in WFVAL2.\n        rewrite Int64.signed_eq.\n        rewrite ! Int64.signed_repr.\n        2,3: unfold_Int64_max_signed; unfold_Int64_min_signed; lia.\n        rewrite Z.eqb_neq in Heq. unfold Coqlib.proj_sumbool. des_ifs.\n    - rewrite interp_imp_expr_Lt.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + 20 + expr_ord e2 + 20) + expr_ord e1)%ord).\n        rewrite <- ! OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n      eapply IHe1; auto. clear IHe1.\n      i. sim_red.\n      sim_ord.\n      { instantiate (1:=(i1 + 20 + expr_ord e2)%ord).\n        eapply OrdArith.add_base_l. }\n      eapply IHe2; auto. clear IHe2.\n      i. sim_red.\n      destruct (wf_val rv && wf_val rv0) eqn:WFVAL.\n      2: sim_triggerUB.\n      sim_red. destruct rv; destruct rv0; try sim_triggerUB.\n      2,3,4: gstep; ss; unfold triggerUB; try sim_red.\n      des_ifs; ss; try sim_triggerUB.\n      + sim_ord.\n        { eapply OrdArith.add_base_l. }\n        sim_red.        \n        eapply SIM; eauto.\n        econs; eauto.\n        { econs; eauto. }\n        ss. f_equal.\n        bsimpl. des. unfold_intrange_64. bsimpl. des.\n        apply sumbool_to_bool_true in WFVAL.\n        apply sumbool_to_bool_true in WFVAL0.\n        apply sumbool_to_bool_true in WFVAL1.\n        apply sumbool_to_bool_true in WFVAL2.\n        unfold Int64.lt. rewrite ! Int64.signed_repr.\n        2,3: unfold_Int64_max_signed; unfold_Int64_min_signed; lia.\n        des_ifs.\n      + sim_ord.\n        { eapply OrdArith.add_base_l. }\n        sim_red.        \n        eapply SIM; eauto.\n        econs; eauto.\n        { econs; eauto. }\n        ss. f_equal.\n        bsimpl. des. unfold_intrange_64. bsimpl. des.\n        apply sumbool_to_bool_true in WFVAL.\n        apply sumbool_to_bool_true in WFVAL0.\n        apply sumbool_to_bool_true in WFVAL1.\n        apply sumbool_to_bool_true in WFVAL2.\n        unfold Int64.lt. rewrite ! Int64.signed_repr.\n        2,3: unfold_Int64_max_signed; unfold_Int64_min_signed; lia.\n        des_ifs.\n\n    - rewrite interp_imp_expr_Plus.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + 20 + expr_ord e2 + 20) + expr_ord e1)%ord).\n        rewrite <- ! OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n      eapply IHe1; auto. clear IHe1.\n      i. sim_red.\n      sim_ord.\n      { instantiate (1:=(i1 + 20 + expr_ord e2)%ord).\n        eapply OrdArith.add_base_l. }\n      eapply IHe2; auto. clear IHe2.\n      i. sim_red.\n      unfold unwrapU. destruct (vadd rv rv0) eqn:VADD; ss; clarify.\n      + sim_red.\n        specialize SIM with (rv:=v) (trv:= @map_val builtins srcprog v).\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        apply SIM; auto.\n        econs; eauto. ss. f_equal. apply map_val_vadd_comm; auto.\n      + sim_triggerUB.\n    - rewrite interp_imp_expr_Minus.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + 20 + expr_ord e2 + 20) + expr_ord e1)%ord).\n        rewrite <- ! OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n      eapply IHe1; auto. clear IHe1.\n      i. sim_red.\n      sim_ord.\n      { instantiate (1:=(i1 + 20 + expr_ord e2)%ord).\n        eapply OrdArith.add_base_l. }\n      eapply IHe2; auto. clear IHe2.\n      i. sim_red.\n      unfold unwrapU. destruct (vsub rv rv0) eqn:VSUB; ss; clarify.\n      + sim_red.\n        specialize SIM with (rv:=v) (trv:= @map_val builtins srcprog v).\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        apply SIM; auto.\n        econs; eauto. ss. f_equal. apply map_val_vsub_comm; auto.\n      + sim_triggerUB.\n    - rewrite interp_imp_expr_Mult.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + 20 + expr_ord e2 + 20) + expr_ord e1)%ord).\n        rewrite <- ! OrdArith.add_assoc. eapply OrdArith.add_base_l. }\n      eapply IHe1; auto. clear IHe1.\n      i.\n      sim_red.\n      sim_ord.\n      { instantiate (1:=(i1 + 20 + expr_ord e2)%ord).\n        eapply OrdArith.add_base_l. }\n      eapply IHe2; auto. clear IHe2.\n      i. sim_red.\n      unfold unwrapU. destruct (vmul rv rv0) eqn:VMUL; ss; clarify.\n      + sim_red.\n        specialize SIM with (rv:=v) (trv:= @map_val builtins srcprog v).\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        apply SIM; auto.\n        econs; eauto. ss. f_equal. apply map_val_vmul_comm; auto.\n      + sim_triggerUB.\n  Qed.\n\n  Lemma step_exprs\n        (src: ModL.t) (tgt: Csharpminor.program)\n        es tes\n        tcode tf tcont tge tle tm\n        r rg ms mn ge le pstate ktr\n        i1\n        (MLE: match_le srcprog le tle)\n        (CEXP: compile_exprs es = tes)\n        (SIM:\n           forall rvs trvs,\n             (* Forall wf_val rvs -> *)\n             eval_exprlist tge empty_env tle tm tes trvs ->\n             trvs = List.map (map_val srcprog) rvs ->\n             gpaco3 (_sim (compile_val src) (semantics tgt)) (cpn3 (_sim (compile_val src) (semantics tgt))) r rg i1\n                   (ktr (pstate, (le, rvs)))\n                   (State tf tcode tcont empty_env tle tm))\n    :\n      gpaco3 (_sim (compile_val src) (semantics tgt))\n             (cpn3 (_sim (compile_val src) (semantics tgt)))\n             r rg (i1 + (Ord.omega * List.length es))%ord\n            (r0 <- EventsL.interp_Es (prog ms) (transl_all mn (interp_imp ge (denote_exprs es) le)) (pstate);; ktr r0)\n            (State tf tcode tcont empty_env tle tm).\n  Proof.\n    generalize dependent ktr. generalize dependent tes.\n    move MLE before pstate. revert_until MLE.\n    generalize dependent es. intros es. revert r rg. induction es; i; ss; des; clarify.\n    - rewrite interp_imp_Ret. sim_red. sim_ord.\n      { eapply OrdArith.add_base_l. }\n      eapply SIM; eauto. econs.\n    - eapply gpaco3_gen_guard.\n      rewrite interp_imp_bind. sim_red.\n      sim_ord.\n      { instantiate (1:=((i1 + (Ord.omega * Datatypes.length es)) + expr_ord a)%ord).\n        rewrite OrdArith.add_assoc. eapply OrdArith.le_add_r.\n        rewrite Ord.from_nat_S. rewrite OrdArith.mult_S.\n        eapply OrdArith.le_add_r. eapply Ord.lt_le. eapply expr_ord_omega. }\n      eapply step_expr; eauto.\n      i. rewrite interp_imp_bind. sim_red.\n      eapply IHes; auto.\n      i. rewrite interp_imp_Ret. sim_red.\n      eapply gpaco3_mon; [eapply SIM|..]; auto.\n      unfold compile_exprs in H2. econs; ss; clarify; eauto.\n  Qed.\n\n  Lemma compile_stmt_no_Sreturn\n        src e\n        (CSTMT: compile_stmt src = (Sreturn e))\n    :\n      False.\n  Proof. destruct src; ss; uo; des_ifs; clarify. Qed.\n\n\n\n\n\n  (**** At the moment, it suffices to support integer IO in our scenario,\n        and we simplify all the other aspects.\n        e.g., the system calls that we are aware of\n        (1) behaves irrelevant from Senv.t,\n        (2) does not allow arguments/return values other than integers,\n        (3) produces exactly one event (already in CompCert; see: ec_trace_length),\n        (4) does not change memory,\n        (5) always returns without stuck,\n        and (6) we also assume that it refines our notion of system call.\n   ****)\n  Axiom syscall_exists: forall fn sg se args_tgt m0, exists tr ret_tgt m1,\n        <<TGT: external_functions_sem fn sg se args_tgt m0 tr ret_tgt m1>>\n  .\n  Axiom syscall_refines:\n    forall fn sg args_tgt ret_tgt\n           se m0 tr m1\n           (TGT: external_functions_sem fn sg se args_tgt m0 tr ret_tgt m1)\n    ,\n      exists args_int ret_int ev,\n        (<<ARGS: args_tgt = (List.map Values.Vlong args_int)>>) /\\\n        (<<RET: ret_tgt = (Values.Vlong ret_int)>>) /\\\n        let args_src := List.map Int64.signed args_int in\n        let ret_src := Int64.signed ret_int in\n        (<<EV: tr = [ev] /\\ decompile_event ev = Some (event_sys fn args_src\u2191 ret_src\u2191)>>)\n        /\\ (<<SRC: syscall_sem (event_sys fn args_src\u2191 ret_src\u2191)>>)\n        /\\ (<<MEM: m0 = m1>>)\n  .\n\n\n\n\n\n  Hypothesis map_blk_after_init :\n    forall src blk\n      (COMP : exists tgt, Imp2Csharpminor.compile src = OK tgt)\n      (ALLOCED : blk >= (src_init_nb src)),\n      (<<ALLOCMAP: (map_blk src blk) = Pos.of_succ_nat (tgt_init_len + (ext_len src) + (int_len src - sk_len src) + blk)>>).\n\n  Hypothesis map_blk_inj :\n    forall src b1 b2\n      (COMP : exists tgt, Imp2Csharpminor.compile src = OK tgt)\n      (WFPROG: incl (name1 src.(defsL)) ((name1 src.(prog_varsL)) ++ (name2 src.(prog_funsL))))\n      (WFSK: Sk.wf src.(defsL)),\n      <<INJ: map_blk src b1 = map_blk src b2 -> b1 = b2>>.\n\n  (* Context {WFPROG: Permutation.Permutation *)\n  (*                    ((List.map fst srcprog.(prog_varsL)) ++ (List.map (compose fst snd) srcprog.(prog_funsL))) *)\n  (*                    (List.map fst srcprog.(defsL)) /\\ Sk.wf srcprog.(defsL)}. *)\n\n  Theorem match_states_sim\n          tgt\n          (modl: ModL.t) ge ms\n          ist cst\n          (MODL: modl = (ModL.add (Mod.lift (Mem (fun _ => false))) (ImpMod.get_modL srcprog)))\n          (MODSEML: ms = modl.(ModL.enclose))\n          (GENV: ge = Sk.load_skenv (Sk.sort modl.(ModL.sk)))\n          (MGENV: match_ge srcprog ge (Genv.globalenv tgt))\n          (COMP: Imp2Csharpminor.compile srcprog = OK tgt)\n          (MS: match_states ge ms srcprog ist cst)\n          (WFPROG: incl (name1 srcprog.(defsL)) ((name1 srcprog.(prog_varsL)) ++ (name2 srcprog.(prog_funsL))))\n          (WFPROG2: forall blk name, (ge.(SkEnv.blk2id) blk = Some name) -> call_ban name = false)\n          (WFSK: Sk.wf srcprog.(defsL))\n    :\n      <<SIM: sim (compile_val modl) (semantics tgt) ((100 + max_fuel) + 100 + Ord.omega + 100)%ord ist cst>>.\n  Proof.\n    red. red. ginit.\n    depgen ist. depgen cst. gcofix CIH. i.\n    assert (EXISTSCOMP: exists tgt, Imp2Csharpminor.compile srcprog = OK tgt); eauto.\n    inv MS. unfold Imp2Csharpminor.compile in COMP. des_ifs_safe.\n    match goal with | [ MGENV: match_ge _ _ (Genv.globalenv ?_tgt) |- _ ] => set (tgt:=_tgt) in * end.\n    destruct code.\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. ss; clarify.\n      destruct tcont; ss; clarify. inv MCONT; clarify.\n      { unfold itree_of_imp_ret, itree_of_imp_cont. unfold exit_stmt in *; ss; clarify.\n        destruct tcont; inv MSTACK; ss; clarify. sim_red. gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_skip_seq. }\n        eexists. exists (step_tau _). eexists. sim_red.\n\n        rewrite interp_imp_expr_Var. sim_red. unfold unwrapU. des_ifs.\n        2:{ sim_triggerUB. }\n        sim_red. gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_return_1; ss; eauto. econs; ss. econs; ss. inv ML; ss; clarify. hexploit ML0; i; eauto. }\n        eexists. exists (step_tau _). eexists.\n        do 1 (gstep; sim_tau). red. sim_red.\n        unfold itree_of_imp_pop_bottom. sim_red.\n        destruct v.\n        - destruct ((0 <=? n)%Z && (n <? two_power_nat 32)%Z) eqn:INT32; bsimpl; des.\n          + gstep. econs 1; eauto.\n            { unfold Int.max_unsigned. unfold_Int_modulus. instantiate (1:=n). lia. }\n            { ss. unfold state_sort; ss. rewrite Any.upcast_downcast. des_ifs. }\n            ss. unfold Int64.loword. rewrite Int64.unsigned_repr.\n            2:{ unfold Int64.max_unsigned. unfold_Int64_modulus. unfold two_power_nat in *. ss. lia. }\n            econs.\n          + gstep. econs 5; ss; eauto.\n            { unfold state_sort; ss. rewrite Any.upcast_downcast. des_ifs. }\n            { i. inv H. }\n            i. inv STEP.\n          + gstep. econs 5; ss; eauto.\n            { unfold state_sort; ss. rewrite Any.upcast_downcast. des_ifs. bsimpl. clarify. }\n            { i. inv H. }\n            i. inv STEP.\n\n        - gstep. econs 5; ss; eauto.\n          { unfold state_sort; ss. rewrite Any.upcast_downcast. des_ifs. }\n          { i. inv H. }\n          i. inv STEP.\n        - gstep. econs 5; ss; eauto.\n          { unfold state_sort; ss. rewrite Any.upcast_downcast. des_ifs. }\n          { i. inv H. }\n          i. inv STEP.\n      }\n\n      { unfold return_stmt in *; ss; clarify. destruct tcont; inv MSTACK; ss; clarify.\n        sim_red. gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_skip_seq. }\n        eexists. exists (step_tau _). eexists. unfold idK. sim_red.\n\n        rewrite interp_imp_expr_Var. sim_red.\n        unfold unwrapU. des_ifs.\n        2:{ sim_triggerUB. }\n        sim_red. gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_return_1; ss; eauto. econs; ss. inv ML; ss; clarify. hexploit ML0; i; eauto. }\n        eexists. exists (step_tau _). eexists.\n        do 4 (gstep; sim_tau). red. sim_red.\n        rewrite Any.upcast_downcast. sim_red.\n        gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_return. }\n        eexists. exists (step_tau _). eexists.\n        do 1 (gstep; sim_tau).\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        gbase. apply CIH.\n        unfold ret_call_cont in TPOP. unfold return_stmt in TPOP. ss; clarify.\n        hexploit match_states_intro.\n        { instantiate (2:=Skip). ss. }\n        2,3,4,5,6: eauto.\n        2: clarify.\n        2:{ i.\n            match goal with\n            | [ H : match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n              replace i1 with i0; eauto\n            end.\n            unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n        econs. i. eapply alist_update_le; eauto. }\n\n      sim_red. gstep. econs 6; clarify.\n      eexists. eexists.\n      { eapply step_skip_seq. }\n      eexists. eexists (step_tau _). eexists. sim_red. gbase. eapply CIH. hexploit match_states_intro; eauto.\n      all: (destruct (compile_stmt code) eqn: CST; eauto; apply compile_stmt_no_Sreturn in CST; clarify).\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Assign. sim_red. ss.\n      sim_ord.\n      { eapply max_fuel_spec1'. }\n      eapply step_expr; eauto. i.\n      (* tau point *)\n      do 1 (gstep; sim_tau). red. sim_red.\n      gstep. econs 6; auto.\n      eexists. eexists.\n      { eapply step_set. eapply H. }\n      eexists. eexists.\n      { eapply step_tau. }\n      eexists. gbase. apply CIH. hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      2,3,4,5,6,7:eauto.\n      2:{ unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. eauto. }\n      { econs. i. eapply alist_update_le; eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Seq. sim_red. ss.\n      (* tau point *)\n      gstep. econs 6; ss; clarify.\n      eexists. eexists.\n      { eapply step_seq. }\n      eexists. exists (step_tau _). eexists. gbase. eapply CIH. hexploit match_states_intro.\n      { instantiate (2:=code1). ss. }\n      4:{ instantiate (1:=Kseq (compile_stmt code2) tcont). ss. destruct (compile_stmt code2) eqn:CSC2; eauto.\n          eapply compile_stmt_no_Sreturn in CSC2; clarify. }\n      4:{ econs 3; eauto. }\n      all: eauto.\n      { ss. destruct (compile_stmt code2) eqn:CSC2; eauto. eapply compile_stmt_no_Sreturn in CSC2; clarify. }\n      i.\n      match goal with\n      | [ H: match_states _ _ _ ?it0 _ |- match_states _ _ _ ?it1 _ ] =>\n        replace it1 with it0; eauto\n      end.\n      unfold itree_of_cont_stmt, itree_of_imp_cont. Red.prw ltac:(_red_gen) 1 0. grind.\n\n    - unfold itree_of_cont_stmt in *; unfold itree_of_imp_cont in *. rewrite interp_imp_If. sim_red. ss.\n      sim_ord.\n      { eapply max_fuel_spec1'. }\n      eapply step_expr; eauto.\n      i. des_ifs.\n      2:{ sim_triggerUB. }\n\n      sim_red. destruct (is_true rv) eqn:COND; ss; clarify.\n      2:{ sim_triggerUB. }\n      sim_red. destruct rv; clarify. ss. destruct (n =? 0)%Z eqn:CZERO; ss; clarify.\n      { rewrite Z.eqb_eq in CZERO. clarify.\n        (* tau point *)\n        gstep. econs 6; ss.\n        eexists. eexists.\n        { eapply step_ifthenelse; ss. econs; eauto.\n          + econs. ss.\n          + ss. }\n        eexists. eexists.\n        { eapply step_tau. }\n        eexists. des_ifs. gbase. eapply CIH. hexploit match_states_intro; eauto. }\n      { rewrite Z.eqb_neq in CZERO.\n        (* tau point *)\n        gstep. econs 6; ss.\n        eexists. eexists.\n        { eapply step_ifthenelse.\n          - econs; eauto.\n            + econs. ss.\n            + ss.\n          - ss. destruct (negb (Int64.eq (Int64.repr n) Int64.zero)) eqn:CONTRA; ss; clarify.\n            rewrite negb_false_iff in CONTRA. apply Int64.same_if_eq in CONTRA.\n            unfold Int64.zero in CONTRA. unfold_intrange_64. bsimpl. des.\n            apply sumbool_to_bool_true in Heq.\n            apply sumbool_to_bool_true in Heq0.\n            hexploit Int64.signed_repr.\n            { unfold_Int64_max_signed. unfold_Int64_min_signed. instantiate (1:=n). nia. }\n            i. rewrite CONTRA in H0. rewrite Int64.signed_repr_eq in H0. des_ifs. }\n        eexists. exists (step_tau _).\n        eexists. des_ifs. gbase. eapply CIH. hexploit match_states_intro; eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_CallFun.\n      ss. des_ifs; sim_red.\n      { sim_triggerUB. }\n      assert (COMP2: Imp2Csharpminor.compile srcprog = OK tgt).\n      { unfold Imp2Csharpminor.compile. des_ifs; auto. }\n      sim_ord.\n      { eapply max_fuel_spec3'. }\n      eapply step_exprs; eauto.\n      i. sim_red.\n      grind. do 1 (gstep; sim_tau). sim_red.\n      match goal with\n      | [ |- gpaco3 _ _ _ _ _ (r0 <- unwrapU (?f);; _) _ ] => destruct f eqn:FSEM; ss\n      end.\n      2:{ sim_triggerUB. }\n      unfold call_ban in Heq. bsimpl; des. des_ifs; clarify.\n      rename Heq0 into NOTMAIN. apply neg_rel_dec_correct in NOTMAIN.\n      repeat match goal with | [ Heq: _ = false |- _ ] => clear Heq end.\n\n      grind. rewrite alist_find_find_some in FSEM. rewrite find_map in FSEM.\n      match goal with\n      | [ FSEM: o_map (?a) _ = _ |- _ ] => destruct a eqn:FOUND; ss; clarify\n      end.\n      destruct p. destruct p. clarify. \n      rewrite Sk.add_unit_l in FOUND.\n      eapply found_imp_function in FOUND. des; clarify.\n      hexploit in_tgt_prog_defs_ifuns; eauto. i.\n      des. rename H0 into COMPF.\n      (* assert (INTGT: In (s2p f, Gfun (Internal tf0)) (prog_defs tgtp)); auto. *)\n      rename s into mn2, f into fn, f0 into impf.\n      assert (COMPF2: In (compile_iFun (mn2, (fn, impf))) (prog_defs tgt)); auto.\n      eapply Globalenvs.Genv.find_symbol_exists in COMPF.\n      destruct COMPF as [b TGTFG].\n      assert (TGTGFIND: Globalenvs.Genv.find_def (Globalenvs.Genv.globalenv tgt) b = Some (snd (compile_iFun (mn2, (fn, impf))))).\n      { hexploit tgt_genv_find_def_by_blk; eauto. }\n\n      unfold cfunU. sim_red.\n      rewrite unfold_eval_imp_only.\n      grind. des_ifs.\n      2,3,4: sim_triggerUB.\n      rename n into WFFUN, Heq into ARGS. sim_red.\n      rewrite interp_imp_tau. sim_red.\n\n      gstep. econs 6; auto.\n      eexists. eexists.\n      { eapply step_call; eauto.\n        - econs. econs 2.\n          { apply Maps.PTree.gempty. }\n          eapply TGTFG.\n        - rewrite Globalenvs.Genv.find_funct_find_funct_ptr.\n          rewrite Globalenvs.Genv.find_funct_ptr_iff. ss. eapply TGTGFIND.\n        - ss. apply init_args_prop in ARGS. rewrite map_length. des. setoid_rewrite ARGS.\n          des_ifs; eauto.\n          { rewrite eq_rel_dec_correct in Heq. des_ifs. }\n          depgen H. clear. i.\n          apply eval_exprlist_length in H. des. unfold compile_exprs in H. rewrite ! map_length in H.\n          rewrite H. ss.\n      }\n      eexists. exists (step_tau _). eexists.\n\n      hexploit initial_lenv_match; eauto. i. des; ss; clarify. instantiate (1:=srcprog) in MLINIT.\n      gstep. econs 4.\n      eexists. eexists.\n      { rewrite <- NoDup_norepeat in WFFUN. apply Coqlib.list_norepet_app in WFFUN. des.\n        eapply step_internal_function; ss; eauto; try econs.\n        { apply Coqlib.list_map_norepet; eauto. i. ii. apply H2. apply s2p_inj; auto. }\n        { unfold Coqlib.list_disjoint in *. depgen WFFUN1. clear. i.\n          apply Coqlib.list_in_map_inv in H. apply in_app_or in H0. des.\n          - apply Coqlib.list_in_map_inv in H0. des. clarify.\n            ii. apply s2p_inj in H. hexploit WFFUN1; eauto. apply in_or_app. left; auto.\n          - ii. clarify. hexploit WFFUN1; eauto. apply in_or_app. right; auto.\n            match goal with\n            | [ H0: In _ ?ml |- In _ ?ll ] => replace ml with (List.map s2p ll) end; ss; des; eauto.\n            apply s2p_inj in H0; auto. apply s2p_inj in H0; auto.\n        }\n        rewrite map_app in BIND. ss. eapply BIND.\n      }\n      eexists; split; [ord_step2|].\n\n      des_ifs.\n      { rewrite rel_dec_correct in Heq; clarify. }\n      clear Heq.\n\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_seq. }\n      eexists; split; [ord_step2|].\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. eapply CIH.\n      match goal with\n      | [ |- match_states ?_ge _ _ _ _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ |- match_states _ ?_ms _ _ _ ] =>\n        set (ms:=_ms) in *\n      end.\n      match goal with\n      | [ |- match_states _ _ _ (?i) _] =>\n        replace i with\n    (` r0 : p_state * (lenv * val) <-\n     EventsL.interp_Es (prog ms)\n                       (transl_all mn2 (interp_imp ge (denote_stmt (Imp.fn_body impf)) l0))\n       (pstate);; x4 <- itree_of_imp_pop ge ms mn2 mn x le r0;; ` x : _ <- next x4;; stack x)\n      end.\n      2:{ rewrite interp_imp_bind. Red.prw ltac:(_red_gen) 1 0. grind.\n          Red.prw ltac:(_red_gen) 2 0. grind.\n          Red.prw ltac:(_red_gen) 2 0. Red.prw ltac:(_red_gen) 1 0. grind. }\n\n      hexploit match_states_intro.\n      5:{ instantiate (1:=Kseq (Sreturn (Some (Evar (s2p \"return\")))) (Kcall (Some (s2p x)) tf empty_env tle tcont)). ss. }\n      6:{ instantiate (1:= fun r0 =>\n                             ` x4 : p_state * (lenv * val) <- itree_of_imp_pop ge ms mn2 mn x le r0;;\n                                    ` x0 : p_state * (lenv * val) <- next x4;; stack x0).\n          instantiate (1:=mn2). instantiate (1:=srcprog). instantiate (1:=ms). instantiate (1:=ge).\n          econs 2; ss; eauto. }\n      3,4: eauto.\n      1:{ instantiate (2:= (Imp.fn_body impf)). ss. }\n      2:{ ss. econs 2. }\n      2:{ clarify. }\n      2:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. unfold idK. grind. }\n      { eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_CallPtr.\n      des_ifs.\n      2,3,4,5,6,7: sim_triggerUB.\n      clear Heq.\n      sim_red.\n      sim_ord.\n      { eapply max_fuel_spec4. }\n      grind. eapply step_expr; eauto. i. rename H0 into TGTEXPR. clarify.\n      des_ifs.\n      1,3,4,5,6: try sim_triggerUB.\n      gstep; sim_tau.\n\n      assert (COMP2: Imp2Csharpminor.compile srcprog = OK tgt).\n      { unfold Imp2Csharpminor.compile. des_ifs; auto. }\n      sim_ord.\n      { eapply max_fuel_spec4'. }\n      sim_red. eapply step_exprs; eauto.\n      i. sim_red.\n      grind. do 1 (gstep; sim_tau). sim_red.\n      match goal with\n      | [ |- gpaco3 _ _ _ _ _ (r0 <- unwrapU (?f);; _) _ ] => destruct f eqn:FSEM; ss\n      end.\n      2:{ sim_triggerUB. }\n\n      des_ifs; ss; clarify.\n      { apply rel_dec_correct in Heq0. unfold call_ban in WFPROG2. apply WFPROG2 in Heq. bsimpl. des.\n        apply neg_rel_dec_correct in Heq. clarify. }\n      { apply rel_dec_correct in Heq1. unfold call_ban in WFPROG2. apply WFPROG2 in Heq. bsimpl. des.\n        apply neg_rel_dec_correct in Heq6. clarify. }\n      { apply rel_dec_correct in Heq2. unfold call_ban in WFPROG2. apply WFPROG2 in Heq. bsimpl. des.\n        apply neg_rel_dec_correct in Heq6. clarify. }\n      { apply rel_dec_correct in Heq3. unfold call_ban in WFPROG2. apply WFPROG2 in Heq. bsimpl. des.\n        apply neg_rel_dec_correct in Heq6. clarify. }\n      { apply rel_dec_correct in Heq4. unfold call_ban in WFPROG2. apply WFPROG2 in Heq. bsimpl. des.\n        apply neg_rel_dec_correct in Heq6. clarify. }\n      repeat match goal with | [ Heq: _ = false |- _ ] => clear Heq end.\n\n      assert (NOTMAIN: s <> \"main\").\n      { depgen WFPROG2. depgen Heq. clear; i. apply WFPROG2 in Heq.\n        unfold call_ban in Heq. bsimpl; des.  apply neg_rel_dec_correct in Heq0. ss. }\n\n      grind. rewrite alist_find_find_some in FSEM. rewrite find_map in FSEM.\n      match goal with\n      | [ FSEM: o_map (?a) _ = _ |- _ ] => destruct a eqn:FOUND; ss; clarify\n      end.\n      destruct p. destruct p. clarify. \n      rewrite Sk.add_unit_l in FOUND.\n      eapply found_imp_function in FOUND. des; clarify.\n      hexploit in_tgt_prog_defs_ifuns; eauto. i.\n      des. rename H1 into COMPF. clear FOUND.\n      rename s0 into mn2, s into fn, f into impf.\n      assert (COMPF2: In (compile_iFun (mn2, (fn, impf))) (prog_defs tgt)); auto.\n      eapply Globalenvs.Genv.find_symbol_exists in COMPF.\n      destruct COMPF as [b TGTFG].\n      assert (TGTGFIND: Globalenvs.Genv.find_def (Globalenvs.Genv.globalenv tgt) b = Some (snd (compile_iFun (mn2, (fn, impf))))).\n      { hexploit tgt_genv_find_def_by_blk; eauto. }\n\n      unfold cfunU. sim_red.\n      rewrite unfold_eval_imp_only.\n      grind. des_ifs.\n      2,3,4: sim_triggerUB.\n      sim_red.\n      rename n into WFFUN. grind.\n      inv MGENV. apply Sk.sort_wf in WFSK.\n      assert (BBLK: (map_blk srcprog blk) = b).\n      { apply Sk.load_skenv_wf in WFSK. apply WFSK in Heq. apply MG in Heq. clarify. }\n      clarify.\n\n      rename Heq0 into ARGS.\n      rewrite interp_imp_tau. sim_red.\n      gstep. econs 6; auto.\n      eexists. eexists.\n      { eapply step_call; eauto.\n        - rewrite Globalenvs.Genv.find_funct_find_funct_ptr.\n          rewrite Globalenvs.Genv.find_funct_ptr_iff. ss. eapply TGTGFIND.\n        - ss. apply init_args_prop in ARGS. rewrite map_length. des. setoid_rewrite ARGS.\n          des_ifs.\n          { rewrite rel_dec_correct in Heq0; clarify. }\n          depgen H0. clear. i.\n          apply eval_exprlist_length in H0. des. unfold compile_exprs in H0. rewrite ! map_length in H0.\n          rewrite H0. ss.\n      }\n      eexists. exists (step_tau _). eexists.\n\n      hexploit initial_lenv_match; eauto. i. des; ss; clarify. instantiate (1:=srcprog) in MLINIT.\n      gstep. econs 4.\n      eexists. eexists.\n      { rewrite <- NoDup_norepeat in WFFUN. apply Coqlib.list_norepet_app in WFFUN. des.\n        eapply step_internal_function; ss; eauto; try econs.\n        { apply Coqlib.list_map_norepet; eauto. i. ii. apply H3. apply s2p_inj; auto. }\n        { unfold Coqlib.list_disjoint in *. depgen WFFUN1. clear. i.\n          apply Coqlib.list_in_map_inv in H. apply in_app_or in H0. des.\n          - apply Coqlib.list_in_map_inv in H0. des. clarify.\n            ii. apply s2p_inj in H. hexploit WFFUN1; eauto. apply in_or_app. left; auto.\n          - ii. clarify. hexploit WFFUN1; eauto. apply in_or_app. right; auto.\n            match goal with\n            | [ H0: In _ ?ml |- In _ ?ll ] => replace ml with (List.map s2p ll) end; ss; des; eauto.\n            apply s2p_inj in H0; auto. apply s2p_inj in H0; auto.\n        }\n        rewrite map_app in BIND. ss. eapply BIND.\n      }\n      eexists; split; [ord_step2|].\n\n      des_ifs.\n      { rewrite rel_dec_correct in Heq0; clarify. }\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_seq. }\n      eexists; split; [ord_step2|].\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. eapply CIH.\n      match goal with\n      | [ |- match_states ?_ge _ _ _ _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ |- match_states _ ?_ms _ _ _ ] =>\n        set (ms:=_ms) in *\n      end.\n      match goal with\n      | [ |- match_states _ _ _ (?i) _] =>\n        replace i with\n    (` r0 : p_state * (lenv * val) <-\n     EventsL.interp_Es (prog ms)\n                       (transl_all mn2 (interp_imp ge (denote_stmt (Imp.fn_body impf)) l0))\n       (pstate);; x4 <- itree_of_imp_pop ge ms mn2 mn x le r0;; ` x : _ <- next x4;; stack x)\n      end.\n      2:{ rewrite interp_imp_bind. Red.prw ltac:(_red_gen) 1 0. grind.\n          Red.prw ltac:(_red_gen) 2 0. grind.\n          Red.prw ltac:(_red_gen) 2 0. Red.prw ltac:(_red_gen) 1 0. grind. }\n\n      hexploit match_states_intro.\n      5:{ instantiate (1:=Kseq (Sreturn (Some (Evar (s2p \"return\")))) (Kcall (Some (s2p x)) tf empty_env tle tcont)). ss. }\n      6:{ instantiate (1:= fun r0 =>\n                             ` x4 : p_state * (lenv * val) <- itree_of_imp_pop ge ms mn2 mn x le r0;;\n                                    ` x0 : p_state * (lenv * val) <- next x4;; stack x0).\n          instantiate (1:=mn2). instantiate (1:=srcprog). instantiate (1:=ms). instantiate (1:=ge).\n          econs 2; ss; eauto. }\n      3,4: eauto.\n      1:{ instantiate (2:= (Imp.fn_body impf)). ss. }\n      2:{ ss. econs 2. }\n      2:{ clarify. }\n      2:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. unfold idK. grind. }\n      { eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_CallSys.\n      ss. sim_red. unfold unwrapU. des_ifs.\n      2:{ sim_triggerUB. }\n      rename Heq into FOUND.\n      sim_red.\n\n      apply alist_find_some in FOUND.\n      assert (COMP2: Imp2Csharpminor.compile srcprog = OK tgt).\n      { unfold Imp2Csharpminor.compile. des_ifs; ss; auto. }\n      hexploit in_tgt_prog_defs_c_sys; eauto. i. rename H into INTGT.\n      hexploit Genv.find_symbol_exists; eauto. i. des. rename H into FINDSYM.\n      hexploit tgt_genv_find_def_by_blk; eauto. i. rename H into FINDDEF.\n\n      des_ifs.\n      2: sim_triggerUB.\n      rewrite Nat.eqb_eq in Heq. clarify.\n      sim_red.\n      sim_ord.\n      { eapply max_fuel_spec3'. }\n      eapply step_exprs; eauto.\n      i.\n      des_ifs.\n      2,3,4: sim_triggerUB.\n      rename Heq0 into WFARGS.\n      sim_red.\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_call; eauto.\n        - econs. econs 2.\n          { eapply Maps.PTree.gempty. }\n          simpl. apply FINDSYM.\n        - simpl. des_ifs. unfold Genv.find_funct_ptr.\n          rewrite FINDDEF. ss.\n        - ss. }\n      eexists; split; [ord_step2|].\n\n      (* System call semantics *)\n      set (trvs:= List.map (map_val srcprog) rvs) in *.\n      pose (syscall_exists f (make_signature (List.length args)) (Genv.globalenv tgt) trvs tm) as TGTSYSSEM. des.\n      hexploit syscall_refines; eauto. i. ss. des. clarify.\n\n      gstep. econs 2; auto.\n      { eexists. eexists. eapply step_external_function. ss. eauto. }\n      clear TGT EV0 SRC ARGS ev ret_int args_int.\n      (* rename H into WFARGS. *)\n      rename H into TGTARGS.\n      i. inv STEP. ss. rename H5 into TGT.\n      hexploit syscall_refines; eauto. i; ss; des; clarify.\n\n      assert (SRCARGS: rvs = (List.map (Vint \u2218 Int64.signed) args_int)).\n      { depgen ARGS. depgen WFARGS. subst trvs. clear. depgen rvs. induction args_int; i; ss; clarify.\n        - apply map_eq_nil in ARGS. auto.\n        - destruct rvs; ss; clarify. bsimpl. des.\n          f_equal; ss; eauto.\n          unfold map_val in H1. des_ifs.\n          f_equal. hexploit Int64.signed_repr; eauto.\n          ss. unfold_intrange_64. bsimpl. des.\n          apply sumbool_to_bool_true in WFARGS.\n          apply sumbool_to_bool_true in WFARGS1.\n          unfold_Int64_max_signed; unfold_Int64_min_signed; lia.\n      }\n\n      eexists. eexists. eexists.\n      { hexploit step_syscall.\n        (* { eauto. } *)\n        (* { instantiate (1:=top1). ss. } *)\n        3:{ i. rename H into SYSSTEP.\n            match goal with\n            | [ SYSSTEP: step ?i0 _ _ |- step ?i1 _ _ ] =>\n              replace i1 with i0; eauto\n            end.\n            rewrite bind_trigger. ss. }\n        { match goal with\n          | [ SRC: syscall_sem (event_sys _ ?args0 _) |- syscall_sem (event_sys _ ?args1 _) ] =>\n            replace args1 with args0; eauto\n          end.\n          rewrite SRCARGS. rewrite List.map_map. ss. }\n        ss.\n      }\n\n      split.\n      { unfold decompile_event in EV0. des_ifs. uo; des_ifs; ss; clarify.\n        unfold decompile_eval in Heq2. des_ifs; ss; clarify. econs; auto.\n        apply Any.upcast_inj in H0. des; ss.\n        apply Any.upcast_inj in H1. des; ss.\n        econs.\n        2:{ rewrite <- EQ0. econs. }\n        generalize dependent Heq1. depgen EQ2. clear. generalize dependent args_int. depgen l1.\n        induction l0; i; ss; clarify.\n        { destruct args_int; ss; clarify. }\n        des_ifs. uo; des_ifs; ss. destruct args_int; ss; clarify.\n        econs; eauto. unfold decompile_eval in Heq. des_ifs. rewrite <- H0. econs. }\n\n      eexists.\n      do 5 (gstep; sim_tau).\n      sim_red. rewrite Any.upcast_downcast. sim_red.\n      do 2 (gstep; sim_tau).\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_return. }\n      eexists; split; [ord_step2|].\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. eapply CIH.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      2,3,4,5,6: eauto.\n      2: clarify.\n      2:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { econs. i. simpl. set (vv:=Vint (Int64.signed ret_int)) in *.\n        replace (Values.Vlong ret_int) with (map_val srcprog vv).\n        2:{ ss. rewrite Int64.repr_signed; ss. }\n        eapply alist_update_le; eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_AddrOf.\n      ss. unfold unwrapU. des_ifs.\n      2:{ sim_triggerUB. }\n      rename n into blk, Heq into SRCBLK.\n      do 2 (gstep; sim_tau). sim_red.\n      gstep. econs 6; ss.\n      eexists. eexists.\n      { eapply step_set. econs. econs 2.\n        { apply Maps.PTree.gempty. }\n        inv MGENV. specialize MG with (symb:=X) (blk:=blk). apply MG. auto. }\n      eexists. exists (step_tau _). eexists. gbase. apply CIH.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      2,3,4,5,6: eauto.\n      2: clarify.\n      2:{ i.\n          match goal with\n          | [ H: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { econs. i. set (vv:=Vptr blk 0) in *.\n        replace (Values.Vptr (map_blk srcprog blk) Ptrofs.zero) with (map_val srcprog vv).\n        2:{ ss. }\n        eapply alist_update_le; eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Malloc. sim_red.\n      ss.\n      sim_ord.\n      { eapply max_fuel_spec1'. }\n      eapply step_expr; eauto. i. rename H0 into MAPRV. sim_red.\n      do 1 (gstep; sim_tau). sim_red.\n      match goal with\n      | [ MCONT: match_code ?_ge _ _ _ _ |- _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ MCONT: match_code _ ?_ms _ _ _ |- _ ] =>\n        set (ms:=_ms) in *\n      end.\n      unfold cfunU.\n      unfold allocF. sim_red.\n      do 3 (gstep; sim_tau). sim_red.\n      rewrite PSTATE. rewrite Any.upcast_downcast. grind. unfold unint. des_ifs; sim_red.\n      2,3: sim_triggerUB.\n      des_ifs.\n      2: sim_triggerUB.\n      bsimpl. des. sim_red.\n      rename Heq into NRANGE1. apply sumbool_to_bool_true in NRANGE1.\n      rename Heq0 into NRANGE2. apply sumbool_to_bool_true in NRANGE2.\n\n      assert (COMP2: Imp2Csharpminor.compile srcprog = OK tgt).\n      { unfold Imp2Csharpminor.compile. des_ifs; ss; auto. }\n      assert (TGTDEFS: In (s2p \"malloc\", Gfun (External EF_malloc)) (prog_defs tgt)).\n      { eapply in_tgt_prog_defs_init_g; eauto.\n        Local Transparent init_g. Local Transparent init_g0.\n        unfold init_g, init_g0. rewrite map_app. rewrite in_app_iff. right. ss. eauto.\n        Local Opaque init_g. Local Opaque init_g0. }\n\n      assert (TGTMALLOC: exists blk, Genv.find_symbol (globalenv (semantics tgt)) (s2p \"malloc\") = Some blk).\n      { hexploit Genv.find_symbol_exists; eauto. }\n      des.\n      hexploit tgt_genv_find_def_by_blk; eauto. i. rename H0 into TGTFINDDEF.\n\n      gstep. econs 6; clarify.\n      eexists. eexists.\n      { eapply step_call.\n        - econs. econs 2.\n          { eapply Maps.PTree.gempty. }\n          apply TGTMALLOC.\n        - econs 2; eauto.\n          + econs 5; try econs; eauto.\n          + econs 1.\n        - ss. des_ifs. unfold Genv.find_funct_ptr. rewrite TGTFINDDEF. ss.\n        - ss. }\n      eexists. eexists.\n      { rewrite bind_trigger. eapply (step_choose _ 0). }\n      eexists.\n      do 9 (gstep; sim_tau). sim_red.\n      do 2 (gstep; sim_tau).\n\n      unfold Int64.mul. rewrite! Int64.unsigned_repr; ss.\n      2:{ split; ss. unfold_modrange_64. unfold Int64.max_unsigned. unfold_Int64_modulus. lia. }\n\n      assert (TGTALLOC: forall tm ch sz, Memory.Mem.alloc tm ch sz = (fst (Memory.Mem.alloc tm ch sz), snd (Memory.Mem.alloc tm ch sz))).\n      { clear. i. ss. }\n\n      pose (Mem.valid_access_store (fst (Memory.Mem.alloc tm (- size_chunk Mptr) (8 * n))) Mptr\n                                   (snd (Memory.Mem.alloc tm (- size_chunk Mptr) (8 * n))) (- size_chunk Mptr)\n                                   (Values.Vlong (Int64.repr (8 * n)))) as TGTM2.\n      match goal with\n      | [ TGTM2 := _ : ?_VACCESS -> _ |- _ ] => assert (VACCESS: _VACCESS)\n      end.\n      { eapply Mem.valid_access_freeable_any. unfold_modrange_64. unfold scale_ofs in *.\n        eapply Mem.valid_access_alloc_same; eauto; try nia. unfold align_chunk, size_chunk. des_ifs. exists (- 1)%Z. lia. }\n      apply TGTM2 in VACCESS. clear TGTM2. dependent destruction VACCESS. rename x0 into tm2. rename e into TGTM2.\n\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_external_function. ss.\n        assert (POSSIZE: Ptrofs.unsigned (Ptrofs.repr (8 * n)) = (8 * n)%Z).\n        { unfold_modrange_64. rewrite Ptrofs.unsigned_repr; auto. unfold Ptrofs.max_unsigned. unfold_Ptrofs_modulus.\n          unfold scale_ofs in *. des_ifs. nia. }\n        hexploit extcall_malloc_sem_intro.\n        3:{ unfold Values.Vptrofs. des_ifs. unfold Ptrofs.to_int64.\n            i. instantiate (4:= Ptrofs.repr (8 * n)) in H0. rewrite POSSIZE in H0. eapply H0. }\n        { rewrite POSSIZE. apply TGTALLOC. }\n        unfold Values.Vptrofs. des_ifs. unfold Ptrofs.to_int64. rewrite POSSIZE. eauto. }\n\n      eexists; split; [ord_step2|].\n      gstep. econs 4.\n      eexists. eexists.\n      { eapply step_return. }\n      eexists; split; [ord_step2|].\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. apply CIH.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      4,5,6: eauto.\n      4:{ clarify. }\n      4:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { econs. i.  specialize TGTALLOC with tm (- size_chunk Mptr)%Z (8 * n)%Z. apply Mem.alloc_result in TGTALLOC.\n        rewrite TGTALLOC. inv MM. rewrite NBLK. rename H0 into LENV. depgen LENV. depgen ML. clear; i.\n\n        set (vv:=Vptr (Mem.nb m + 0) 0) in *. simpl.\n        replace (Values.Vptr (map_blk srcprog (Mem.nb m)) Ptrofs.zero) with (map_val srcprog vv).\n        2:{ ss. repeat f_equal. lia. }\n        eapply alist_update_le; eauto. }\n      { clarify. }\n      eapply match_mem_malloc; eauto. unfold Mem.alloc; ss. f_equal. rewrite! Nat.add_0_r. ss.\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Free. sim_red.\n      ss.\n      sim_ord.\n      { eapply max_fuel_spec1'. }\n      eapply step_expr; eauto.\n      i. sim_red.\n      grind. do 1 (gstep; sim_tau). sim_red.\n      match goal with\n      | [ MCONT: match_code ?_ge _ _ _ _ |- _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ MCONT: match_code _ ?_ms _ _ _ |- _ ] =>\n        set (ms:=_ms) in *\n      end.\n      unfold cfunU. grind. unfold freeF. sim_red.\n      do 3 (gstep; sim_tau). sim_red.\n      rewrite PSTATE. rewrite Any.upcast_downcast. grind. unfold unptr. des_ifs; sim_red.\n      1,3: sim_triggerUB.\n      unfold Mem.free. destruct (Mem.cnts m blk ofs) eqn:MEMCNT; ss.\n      2:{ sim_triggerUB. }\n      sim_red.\n      gstep. econs 6; clarify.\n      eexists. eexists.\n      { econs. }\n      eexists. exists (step_tau _).\n      eexists. do 4 (gstep; sim_tau). sim_red.\n      gstep. econs 6; clarify.\n      eexists. eexists.\n      { econs. }\n      eexists. exists (step_tau _). eexists. gbase. eapply CIH.\n      rewrite Any.upcast_downcast. grind.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      1,4,5,6: eauto.\n      3:{ clarify. }\n      3:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { ss. }\n      eapply match_mem_free; eauto.\n      instantiate (1:=ofs). instantiate (1:=blk). unfold Mem.free. rewrite MEMCNT. ss.\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Load. sim_red.\n      ss.\n      sim_ord.\n      { eapply max_fuel_spec1'. }\n      eapply step_expr; eauto.\n      i.\n      des_ifs.\n      2: sim_triggerUB.\n      sim_red.\n      grind. do 1 (gstep; sim_tau). sim_red.\n      match goal with\n      | [ MCONT: match_code ?_ge _ _ _ _ |- _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ MCONT: match_code _ ?_ms _ _ _ |- _ ] =>\n        set (ms:=_ms) in *\n      end.\n      unfold cfunU.\n      grind. unfold loadF. sim_red.\n      do 3 (gstep; sim_tau). sim_red.\n      rewrite PSTATE. rewrite Any.upcast_downcast. grind. unfold unptr. des_ifs; sim_red.\n      1: sim_triggerUB.\n      unfold Mem.load. destruct (Mem.cnts m blk ofs) eqn:MEMCNT; ss.\n      2:{ sim_triggerUB. }\n      sim_red.\n      gstep. econs 6; clarify.\n      eexists. eexists.\n      { eapply step_set. econs; eauto. ss. inv MM. apply MMEM in MEMCNT. des.\n        unfold scale_ofs in *. unfold map_ofs in *. rewrite unwrap_Ptrofs_repr_z; try nia; eauto. }\n      eexists. exists (step_tau _).\n      eexists.\n      do 2 (gstep; sim_tau). sim_red. grind.\n      do 1 (gstep; sim_tau). gstep; sim_tau.\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. eapply CIH.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      2,3,4,5,6: eauto.\n      2: clarify.\n      2:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { econs. i. eapply alist_update_le; eauto. }\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Store. sim_red.\n      match goal with\n      | [ MCONT: match_code ?_ge _ _ _ _ |- _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ MCONT: match_code _ ?_ms _ _ _ |- _ ] =>\n        set (ms:=_ms) in *\n      end.\n      ss.\n      sim_ord.\n      { eapply max_fuel_spec2'. }\n      eapply step_expr; eauto. i.\n      des_ifs.\n      2: sim_triggerUB.\n      sim_red.\n      eapply step_expr; eauto. i. sim_red.\n      grind. do 1 (gstep; sim_tau). sim_red.\n      unfold cfunU.\n      grind. unfold storeF. sim_red.\n      do 3 (gstep; sim_tau). sim_red.\n      rewrite PSTATE. rewrite Any.upcast_downcast. grind. unfold unptr. des_ifs; sim_red.\n      2:{ sim_triggerUB. }\n      unfold Mem.store. destruct (Mem.cnts m blk ofs) eqn:MEMCNT; ss.\n      2:{ sim_triggerUB. }\n      sim_red.\n\n      hexploit match_mem_store; eauto.\n      { instantiate (2:=rv0); instantiate (2:=ofs); instantiate (2:=blk). unfold Mem.store. des_ifs. }\n      i. des.\n\n      gstep. econs 6; clarify.\n      eexists. eexists.\n      { eapply step_store; eauto. ss. inv MM. unfold scale_ofs in *; unfold map_ofs in *.\n        hexploit MMEM; eauto. i; des. rewrite unwrap_Ptrofs_repr_z; try nia; eauto. }\n      eexists. exists (step_tau _). eexists.\n      do 4 (gstep; sim_tau). sim_red. gstep; sim_tau.\n      sim_ord.\n      { eapply OrdArith.add_base_l. }\n      gbase. eapply CIH. rewrite Any.upcast_downcast. grind.\n      hexploit match_states_intro.\n      { instantiate (2:=Skip). ss. }\n      1,4,5,6: eauto.\n      3: clarify.\n      3:{ i.\n          match goal with\n          | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n            replace i1 with i0; eauto\n          end.\n          unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n      { ss. }\n      eauto.\n\n    - unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Cmp. sim_red.\n      match goal with\n      | [ MCONT: match_code ?_ge _ _ _ _ |- _ ] =>\n        set (ge:=_ge) in *\n      end.\n      match goal with\n      | [ MCONT: match_code _ ?_ms _ _ _ |- _ ] =>\n        set (ms:=_ms) in *\n      end.\n      ss.\n      sim_ord.\n      { eapply max_fuel_spec2'. }\n      eapply step_expr; eauto. i. sim_red.\n      eapply step_expr; eauto. i.\n      des_ifs.\n      2: sim_triggerUB.\n      bsimpl. des. rename Heq into WFA, Heq0 into WFB.\n      sim_red.\n      (* destruct rstate. ss. destruct l0; clarify. *)\n      grind. do 1 (gstep; sim_tau). sim_red.\n      (* unfold cfunU. *)\n      grind. unfold cmpF. sim_red.\n      do 3 (gstep; sim_tau). sim_red.\n      rewrite PSTATE. rewrite Any.upcast_downcast. grind.\n      destruct (vcmp m rv rv0) eqn:VCMP; sim_red.\n      2:{ sim_triggerUB. }\n      des_ifs.\n      + sim_red.\n        gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_set. econs; eauto. econs; eauto; ss. eapply match_mem_cmp in VCMP; eauto. }\n        eexists. exists (step_tau _).\n        eexists.\n        do 2 (gstep; sim_tau). sim_red. grind.\n        do 1 (gstep; sim_tau). gstep; sim_tau.\n        sim_ord.\n        { eapply OrdArith.add_base_l. }\n        gbase. eapply CIH.\n        hexploit match_states_intro.\n        { instantiate (2:=Skip). ss. }\n        2,3,4,5,6: eauto.\n        2: clarify.\n        2:{ i.\n            match goal with\n            | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n              replace i1 with i0; eauto\n            end.\n            unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n        { econs. i. unfold Int.one. rewrite Int.signed_repr.\n          2:{ unfold_Int_max_signed; unfold_Int_min_signed. ss. }\n          set (vv:=Vint 1) in *.\n          replace (Values.Vlong (Int64.repr 1)) with (map_val srcprog vv).\n          2:{ ss. }\n          eapply alist_update_le; eauto. }\n    + sim_red.\n        gstep. econs 6; clarify.\n        eexists. eexists.\n        { eapply step_set. econs; eauto. econs; eauto; ss. eapply match_mem_cmp in VCMP; eauto. }\n        eexists. exists (step_tau _).\n        eexists.\n        do 2 (gstep; sim_tau). sim_red. grind.\n        do 1 (gstep; sim_tau). gstep; sim_tau.\n        sim_ord.\n        { eapply OrdArith.add_base_l. } gbase. eapply CIH.\n        hexploit match_states_intro.\n        { instantiate (2:=Skip). ss. }\n        2,3,4,5,6: eauto.\n        2: clarify.\n        2:{ i.\n            match goal with\n            | [ H1: match_states _ _ _ ?i0 _ |- match_states _ _ _ ?i1 _ ] =>\n              replace i1 with i0; eauto\n            end.\n            unfold itree_of_cont_stmt, itree_of_imp_cont. rewrite interp_imp_Skip. grind. }\n        { econs. i. unfold Int.zero. rewrite Int.signed_repr.\n          2:{ unfold_Int_max_signed; unfold_Int_min_signed. ss. }\n          set (vv:=Vint 0) in *.\n          replace (Values.Vlong (Int64.repr 0)) with (map_val srcprog vv).\n          2:{ ss. }\n          eapply alist_update_le; eauto. }\n\n        Unshelve. all: try (exact Ord.O). all: try (exact 0%nat). all: ss.\n        { eapply (Genv.globalenv tgt). }\n  Qed.\n\n  Ltac rewriter :=\n    try match goal with\n        | H: _ = _ |- _ => rewrite H in *; clarify\n        end.\n\n  Lemma Csharpminor_eval_expr_determ a\n    :\n      forall v0 v1 ge e le m\n             (EXPR0: eval_expr ge e le m a v0)\n             (EXPR1: eval_expr ge e le m a v1),\n        v0 = v1.\n  Proof.\n    induction a; i; inv EXPR0; inv EXPR1; rewriter.\n    { inv H0; inv H1; rewriter. }\n    { exploit (IHa v2 v3); et. i. subst. rewriter. }\n    { exploit (IHa1 v2 v4); et. i. subst.\n      exploit (IHa2 v3 v5); et. i. subst. rewriter. }\n    { exploit (IHa v2 v3); et. i. subst. rewriter. }\n  Qed.\n\n  Lemma Csharpminor_eval_exprlist_determ a\n    :\n      forall v0 v1 ge e le m\n             (EXPR0: eval_exprlist ge e le m a v0)\n             (EXPR1: eval_exprlist ge e le m a v1),\n        v0 = v1.\n  Proof.\n    induction a; ss.\n    { i. inv EXPR0. inv EXPR1. auto. }\n    { i. inv EXPR0. inv EXPR1.\n      hexploit (@Csharpminor_eval_expr_determ a v2 v0); et. i.\n      hexploit (IHa vl vl0); et. i. clarify. }\n  Qed.\n\n  Lemma alloc_variables_determ vars\n    :\n      forall e0 e1 ee m m0 m1\n             (ALLOC0: alloc_variables ee m vars e0 m0)\n             (ALLOC1: alloc_variables ee m vars e1 m1),\n        e0 = e1 /\\ m0 = m1.\n  Proof.\n    induction vars; et.\n    { i. inv ALLOC0; inv ALLOC1; auto. }\n    { i. inv ALLOC0; inv ALLOC1; auto. rewriter.\n      eapply IHvars; et. }\n  Qed.\n\n  Lemma Csharpminor_wf_semantics prog\n    :\n      wf_semantics (Csharpminor.semantics prog).\n  Proof.\n    econs.\n    { i. inv STEP0; inv STEP1; ss; rewriter.\n      { hexploit (@Csharpminor_eval_expr_determ a v v0); et. i. rewriter. }\n      { hexploit (@Csharpminor_eval_expr_determ addr vaddr vaddr0); et. i. rewriter.\n        hexploit (@Csharpminor_eval_expr_determ a v v0); et. i. rewriter. }\n      { hexploit (@Csharpminor_eval_expr_determ a vf vf0); et. i. rewriter.\n        hexploit (@Csharpminor_eval_exprlist_determ bl vargs vargs0); et. i. rewriter. }\n      { hexploit (@Csharpminor_eval_exprlist_determ bl vargs vargs0); et. i. rewriter.\n        hexploit external_call_determ; [eapply H0|eapply H12|..]. i. des.\n        inv H1. hexploit H2; et. i. des. clarify. }\n      { hexploit (@Csharpminor_eval_expr_determ a v v0); et. i. rewriter.\n        inv H0; inv H12; auto. }\n      { hexploit (@Csharpminor_eval_expr_determ a v v0); et. i. rewriter.\n        inv H0; inv H12; et. }\n      { hexploit (@Csharpminor_eval_expr_determ a v v0); et. i. rewriter. }\n      { hexploit (@alloc_variables_determ (fn_vars f) e e0); et. i. des; clarify. }\n      { hexploit external_call_determ; [eapply H|eapply H6|..]. i. des.\n        inv H0. hexploit H1; et. i. des. clarify. }\n    }\n    { i. inv FINAL. inv STEP. }\n    { i. inv FINAL0. inv FINAL1. ss. }\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/imp/compiler_proof/Imp2CsharpminorSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import msl.base.\nRequire Import msl.sepalg.\nRequire Import msl.sepalg_generators.\nRequire Import msl.sepalg_functors.\nRequire Import msl.ageable.\nRequire Import msl.age_sepalg.\nRequire Import msl.knot.\nRequire Import msl.knot_lemmas.\nRequire Import msl.functors.\nRequire Import msl.sepalg_functors.\n\n\n\nModule Type TY_FUNCTOR_SA.\n  Declare Module TF:TY_FUNCTOR.\n  Import TF.\n\n  Parameter Join_T : Join T.  Existing Instance Join_T.\n  Parameter pa_T : Perm_alg T.  Existing Instance pa_T.\n(*   Parameter sa_T : Sep_alg T.  EXisting Instance sa_T. *)\n\n  Axiom T_bot_identity : identity T_bot.\n  Axiom T_bot_unit : unit_for T_bot T_bot.\n\n  Instance pa_TF (A : Type) : Perm_alg (A -> T) := Perm_fun _ _ _ pa_T.\n  Instance sa_TF (sa_T: Sep_alg T) (A : Type): Sep_alg (A -> T) := Sep_fun _ _ _ sa_T.\n  Instance ca_TF (ca_T: Canc_alg T) (A : Type): Canc_alg (A -> T) := Canc_fun _ _ _ ca_T.\n  Instance da_TF (da_T: Disj_alg T) (A : Type): Disj_alg (A -> T) := Disj_fun _ _ _ da_T.\n\n  Parameter J_F: forall A, Join (F (A -> T)).\n  Existing Instance J_F.\n  Parameter Perm_F: forall A, Perm_alg  (F (A -> T)).\n  Implicit Arguments Perm_F.   Existing Instance Perm_F.\n  Parameter Sep_F: forall A, Sep_alg  (F (A -> T)).\n  Implicit Arguments Sep_F.\n  Existing Instance Sep_F.\n  Parameter Canc_F: forall A, Canc_alg  (F (A -> T)).\n  Implicit Arguments Canc_F.\n  Existing Instance Canc_F.\n  Parameter Disj_F: forall A, Disj_alg  (F (A -> T)).\n  Implicit Arguments Disj_F.\n  Existing Instance Disj_F.\n\n  Axiom fmap_hom : forall A B (f: (A -> T) -> (B -> T)),\n    @join_hom  _ (Join_fun A T _) _ (Join_fun B T _) f ->\n    @join_hom _  (J_F A) _ (J_F B) (fmap f).\n  Implicit Arguments fmap_hom.\n\n  Axiom F_preserves_unmaps_left : forall A B (f : (A -> T) -> (B -> T)) \n    (Hhom : @join_hom  _ (Join_fun A T _) _ (Join_fun B T _) f ),\n    unmap_left (Join_fun A T Join_T) (Join_fun B T Join_T) f ->\n    unmap_left (J_F A) (J_F B) (fmap f).\n  Implicit Arguments F_preserves_unmaps_left.\n\n  Axiom F_preserves_unmaps_right : forall A B (f : (A -> T) -> (B -> T)) \n    (Hhom : @join_hom  _ (Join_fun A T _) _ (Join_fun B T _) f ),\n    unmap_right (Join_fun A T Join_T) (Join_fun B T Join_T) f ->\n    unmap_right (J_F A) (J_F B) (fmap f).\n  Implicit Arguments F_preserves_unmaps_right.\nEnd TY_FUNCTOR_SA.\n\nModule Type KNOT_SA.\n  Declare Module TFSA:TY_FUNCTOR_SA.\n  Declare Module K:KNOT with Module TF:=TFSA.TF.\n\n  Import TFSA.TF.\n  Import TFSA.\n  Import K.\n\n  Parameter Join_knot: Join knot.  Existing Instance Join_knot.\n  Parameter Perm_knot : Perm_alg knot.  Existing Instance Perm_knot.\n  Parameter Sep_knot: forall (sa_T: Sep_alg T), Sep_alg knot. Existing Instance Sep_knot.\n  Parameter Canc_knot: forall (sa_T: Canc_alg T), Canc_alg knot. Existing Instance Canc_knot.\n  Parameter Disj_knot: forall (sa_T: Disj_alg T), Disj_alg knot. Existing Instance Disj_knot.\n\n  Instance Join_nat_F: Join (nat * F predicate) := \n       Join_prod nat  (Join_equiv nat) (F predicate) _.\n\n  Instance Perm_nat_F : Perm_alg (nat * F predicate) := \n   @Perm_prod _ _ (F (knot * TF.other -> T)) (J_F (knot * TF.other)) (Perm_equiv nat) _.\n\n  Instance Sep_nat_F (sa_T: Sep_alg T) : Sep_alg (nat * F predicate) := \n   @Sep_prod _ _ (F (knot * TF.other -> T)) (J_F (knot * TF.other)) (Sep_equiv nat) _.\n  Instance Canc_nat_F (sa_T: Canc_alg T) : Canc_alg (nat * F predicate) := \n   @Canc_prod _ _ (F (knot * TF.other -> T)) (J_F (knot * TF.other)) (Canc_equiv nat) _.\n  Instance Disj_nat_F (sa_T: Disj_alg T) : Disj_alg (nat * F predicate) := \n   @Disj_prod _ _ (F (knot * TF.other -> T)) (J_F (knot * TF.other)) (Disj_equiv nat) _.\n\n  Axiom join_unsquash : forall x1 x2 x3 : knot,\n    join x1 x2 x3 = join (unsquash x1) (unsquash x2) (unsquash x3).\n\n  Axiom asa_knot : Sep_alg T -> @Age_alg knot _ K.ag_knot.\n\nEnd KNOT_SA.\n\nModule KnotSa (TFSA':TY_FUNCTOR_SA) (K':KNOT with Module TF:=TFSA'.TF)\n  : KNOT_SA with Module TFSA:=TFSA' with Module K:=K'.\n\n  Module TFSA:=TFSA'.\n  Module K:=K'.\n  Module KL := Knot_Lemmas(K).\n\n  Import TFSA.TF.\n  Import TFSA.\n  Import K.\n  Import KL.\n\n  Instance Join_pred : Join predicate := Join_fun (knot * other) T Join_T.\n  Instance pred_pa : Perm_alg predicate := pa_TF (knot * other).\n  Instance pred_sa (sa_T: Sep_alg T): Sep_alg predicate := sa_TF _ _.\n  Instance pred_ca (ca_T: Canc_alg T): Canc_alg predicate := ca_TF _ _.\n  Instance pred_da (da_T: Disj_alg T): Disj_alg predicate := da_TF _ _.\n\n  Lemma approx_join_hom : forall n, join_hom (approx n).\n  Proof.\n    unfold join_hom.\n    intros.\n    hnf in *.\n    intro x0.\n    spec H x0.\n    unfold K'.approx.\n    destruct (le_gt_dec n (level x0)).\n    generalize (T_bot_identity); intro.\n    apply T_bot_unit.\n    trivial.\n  Qed.\n  Lemma F_approx_join_hom : forall n,\n    join_hom (JA := J_F (knot * other)) (JB := J_F (knot * other)) (fmap (approx n)).\n  Proof.\n    intros; apply fmap_hom; apply approx_join_hom.\n  Qed.\n  \n  Instance Join_nat_F: Join (nat * F predicate) := \n         Join_prod nat (Join_equiv nat) (F (knot * other -> T))  (J_F (knot * other)).\n  Instance Perm_nat_F : Perm_alg (nat * F predicate) :=\n         Perm_prod (Perm_equiv nat) (Perm_F (knot * other)).\n  Instance Sep_nat_F (sa_T: Sep_alg T) : Sep_alg (nat * F predicate) :=\n         Sep_prod (Sep_equiv nat) (Sep_F (knot * other)).\n  Instance Canc_nat_F (ca_T: Canc_alg T) : Canc_alg (nat * F predicate) :=\n         Canc_prod _ _ _ _.\n  Instance Disj_nat_F (sa_T: Disj_alg T) : Disj_alg (nat * F predicate) :=\n         Disj_prod _ _ _ _.\n\n  Lemma unsquash_squash_join_hom : join_hom (unsquash oo squash).\n  Proof.\n    unfold compose.\n    intros [x1 x2] [y1 y2] [z1 z2] ?.\n    do 3 rewrite (unsquash_squash).\n    firstorder.\n    simpl in *.\n    subst y1.\n    subst z1.\n    apply F_approx_join_hom.\n    trivial.\n  Qed.\n\n  Instance Join_knot : Join knot :=  \n         Join_preimage knot (nat * F predicate) Join_nat_F unsquash.\n\n  Instance Perm_knot : Perm_alg knot := \n    Perm_preimage _ _ _  _ unsquash squash squash_unsquash unsquash_squash_join_hom.\n\n  Lemma join_unsquash : forall x1 x2 x3,\n    join x1 x2 x3 =\n    join (unsquash x1) (unsquash x2) (unsquash x3).\n  Proof.\n    intuition.\n  Qed.\n\n  Instance Sep_knot (sa_T: Sep_alg T): Sep_alg knot := \n    Sep_preimage _ _ _  unsquash squash squash_unsquash unsquash_squash_join_hom.\n  Instance Canc_knot (sa_T: Canc_alg T): Canc_alg knot.\n  Proof.\n     repeat intro.\n     do 3 red in H,H0. \n     apply unsquash_inj. apply (join_canc H H0).\n  Qed.\n  Instance Disj_knot (da_T: Disj_alg T): Disj_alg knot.\n  Proof.\n     repeat intro.\n     do 3 red in H. \n     apply unsquash_inj. apply (join_self H).\n  Qed.\n\n  Lemma age_join1 :\n    forall x y z x' : K'.knot,\n      join x y z ->\n      age x x' ->\n      exists y' : K'.knot,\n        exists z' : K'.knot, join x' y' z' /\\ age y y' /\\ age z z'.\n  Proof.\n    intros.\n    unfold age in *; simpl in *.\n    rewrite knot_age1 in H0.\n    repeat rewrite knot_age1.\n    do 3 red in H.\n    destruct (unsquash x).\n    destruct (unsquash y).\n    destruct (unsquash z).\n    destruct n; try discriminate.\n    inv H0.\n   simpl in H; destruct H.\n    simpl in H; destruct H.\n    subst n0 n1.\n    exists (squash (n,f0)).\n    exists (squash (n,f1)).\n    simpl in H0.\n    split; intuition. do 3  red.\n    repeat rewrite unsquash_squash.\n    split; auto. simpl snd.\n    apply F_approx_join_hom; auto.\n  Qed.\n\n  Lemma age_join2 :\n    forall x y z z' : K'.knot,\n      join x y z ->\n      age z z' ->\n      exists x' : K'.knot,\n        exists y' : K'.knot, join x' y' z' /\\ age x x' /\\ age y y'.\n  Proof.\n    intros.\n    unfold age in *; simpl in *.\n    rewrite knot_age1 in H0.\n    repeat rewrite knot_age1.\n    do 3 red in H.\n    destruct (unsquash x).\n    destruct (unsquash y).\n    destruct (unsquash z).\n    destruct n1; try discriminate.\n    inv H0.\n    destruct H; simpl in *.\n    destruct H; subst.\n    exists (squash (n1,f)).\n    exists (squash (n1,f0)).\n    split; intuition. do 3  red.\n    repeat rewrite unsquash_squash.\n    split; auto. simpl snd.\n    apply F_approx_join_hom; auto.\n  Qed.\n\n  Lemma pred_unmap_left_approx (sa_T: Sep_alg T):\n    forall n, unmap_left _ Join_pred (approx n).\n  Proof.\n    red; intros.\n    assert (x' = approx n x').\n      extensionality k.\n      spec H k.\n      unfold approx in *.\n      revert H.\n      elim (le_gt_dec n (level k)); intros; trivial.\n      apply T_bot_identity.\n      apply join_comm.\n      trivial.\n\n    exists (fun w => if le_gt_dec n (level w) then projT1 (join_ex_units (z w)) else x' w).\n    exists (fun w => if le_gt_dec n (level w) then z w else y w).\n    split.\n    intro w.\n    spec H w.\n    revert H.\n    rewrite H0.\n    unfold approx.\n    elim (le_gt_dec n (level w)); intros; trivial.\n    destruct (join_ex_units (z w)).\n    simpl. apply u.\n\n    split.\n    extensionality w.\n    spec H w.\n    revert H.\n    unfold approx.\n    elim (le_gt_dec n (level w)); intros; trivial.\n    apply join_unit2_e in H; auto.\n    apply T_bot_identity.\n    \n    unfold approx.\n    extensionality w.\n    elim (le_gt_dec n (level w)); intros; trivial.\n  Qed.\n\n  Lemma pred_unmap_right_approx (sa_T: Sep_alg T):\n    forall n, unmap_right _ Join_pred (approx n).\n  Proof.\n    red; intros.\n    exists (fun w => if le_gt_dec n (level w) then (projT1 (join_ex_units (x w))) else y w).\n    exists (fun w => if le_gt_dec n (level w) then x w else z' w).\n    split.\n    intro w.\n    spec H w.\n    revert H.\n    unfold approx.\n    elim (le_gt_dec n (level w)); intros; trivial.\n    destruct (join_ex_units (x w)).\n    simpl. apply join_comm; apply u.\n    \n    split.\n    unfold approx.\n    extensionality w.\n    elim (le_gt_dec n (level w)); intros; trivial.\n    \n    pattern z' at 2.\n    assert (z' = approx n z').\n      extensionality k.\n      spec H k.\n      unfold approx in *.\n      revert H.\n      elim (le_gt_dec n (level k)); intros; trivial.\n      symmetry.\n      apply (T_bot_identity _ _ H).\n    rewrite H0.\n    unfold approx.\n    extensionality w.\n    elim (le_gt_dec n (level w)); intros; trivial.\n  Qed.\n\n  Lemma unage_join1 (sa_T: Sep_alg T) : forall x x' y' z', join x' y' z' -> age x x' ->\n    exists y, exists z, join x y z /\\ age y y' /\\ age z z'.\n  Proof.\n(*    destruct F_preserves_unmaps as [_ fmap_commute1]. *)\n    intros.\n    unfold age in *; simpl in *.\n    rewrite knot_age1 in H0. do 3 red in H.\n    case_eq (unsquash x); intros.\n    rewrite H1 in H0.\n    destruct n; try discriminate.\n    inv H0.\n    revert H.\n    case_eq (unsquash y');\n    case_eq (unsquash z'); intros.\n    rewrite unsquash_squash in H2.\n    destruct H2; simpl in *.\n    destruct H2; subst.\n    rename n0 into n.\n(* new technique *)\n    destruct (@F_preserves_unmaps_right  _ _ _ (approx_join_hom n) (pred_unmap_right_approx _ _) f f1 f0) as [q [w [? [? ?]]]].\n    change (prod K'.knot TF.other -> TF.T) with predicate.\n(* end new technique *)\n    rewrite <- (unsquash_approx H0); auto.\n    exists (squash (S n,q)).\n    exists (squash (S n,w)). \n\n    split.\n    do 3 red. rewrite H1.     repeat rewrite unsquash_squash.\n    split; simpl; auto.\n    generalize (F_approx_join_hom (S n) _ _ _ H2).\n    rewrite <- (unsquash_approx H1); auto.\n\n    split.\n    rewrite knot_age1.\n    rewrite unsquash_squash.\n    replace y' with (squash (n,fmap (approx (S n)) q)); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H0.\n    apply injective_projections; simpl; auto.\n    rewrite (unsquash_approx H0).\n(* new technique *)\n    change (prod K'.knot TF.other -> TF.T) with predicate in H4.\n(* end new technique *)\n    rewrite <- H4.\n    change ((fmap (approx n) oo fmap (approx (S n))) q = fmap (approx n) q).\n    rewrite fmap_comp.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality a.\n    replace (S n) with (1 + n)%nat by trivial.\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n\n    rewrite knot_age1.\n    rewrite unsquash_squash.\n    replace z' with  (squash (n,fmap (approx (S n)) w)); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H.\n    apply injective_projections; simpl; auto.\n    rewrite <- H5.\n    change ((fmap (approx n) oo fmap (approx (S n))) w = fmap (approx n) w).\n    rewrite fmap_comp.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality a.\n    replace (S n) with (1 + n)%nat by trivial.\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n  Qed.\n\n  Lemma unage_join2 (sa_T: Sep_alg T):\n    forall z x' y' z', join x' y' z' -> age z z' ->\n      exists x, exists y, join x y z /\\ age x x' /\\ age y y'.\n  Proof.\n    intros.\n    rewrite join_unsquash in H.\n    revert H H0.\n    unfold age in *; simpl in *.\n    repeat rewrite knot_age1.\n    case_eq (unsquash x');\n    case_eq (unsquash y');\n    case_eq (unsquash z');\n    case_eq (unsquash z); intros.\n    destruct n; try discriminate.\n    inv H4.\n    rewrite unsquash_squash in H0.\n    inv H0.\n    destruct H3; simpl in *.\n    destruct H0; subst.\n    rename n0 into n.\n    destruct (@F_preserves_unmaps_left _ _ _ (approx_join_hom n) (pred_unmap_left_approx _ _) f2 f1 f)\n      as [wx [wy [? [? ?]]]]; auto.\n    change (prod K'.knot TF.other -> TF.T) with predicate.\n    unfold join, Join_knot, Join_preimage; simpl.\n    rewrite <- (unsquash_approx H1); auto.\n    unfold join, Join_knot, Join_preimage; simpl.\n    exists (squash (S n, wx)).\n    exists (squash (S n, wy)).\n    repeat rewrite unsquash_squash.\n    rewrite H.\n \n    split.\n    split; simpl; auto.    \n    rewrite (unsquash_approx H).\n    apply F_approx_join_hom; auto.\n    split; rewrite knot_age1; rewrite unsquash_squash.\n    replace x' with (squash (n,(fmap (approx (S n)) wx))); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H2.\n    apply injective_projections; simpl; auto.\n    change ((fmap (approx n) oo fmap (approx (S n))) wx = f2).\n    rewrite fmap_comp.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality x.\n    unfold compose.\n    change (approx n (approx (S n) x)) with ((approx n oo approx (1 + n)) x).\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n    replace y' with (squash (n,(fmap (approx (S n)) wy))); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H1.\n    apply injective_projections; simpl; auto.\n    change ((fmap (approx n) oo fmap (approx (S n))) wy = f1).\n    rewrite fmap_comp.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    change (prod K'.knot TF.other -> TF.T) with predicate in H5.\n    rewrite H5.\n    rewrite <- (unsquash_approx H1); auto.\n    extensionality x.\n    unfold compose.\n    change (approx n (approx (S n) x)) with ((approx n oo approx (1 + n)) x).\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n  Qed.\n\n  Theorem asa_knot(sa_T: Sep_alg T) : @Age_alg knot _ K.ag_knot.\n  Proof.\n    constructor.\n    exact age_join1.\n    exact age_join2.\n    exact (unage_join1 _).\n    exact (unage_join2 _).\n  Qed.\n\nEnd KnotSa.\n", "meta": {"author": "lexuanbach", "repo": "certified-permission-procedure", "sha": "f0ac470d8096b106ea03c22e95950bae684bcc86", "save_path": "github-repos/coq/lexuanbach-certified-permission-procedure", "path": "github-repos/coq/lexuanbach-certified-permission-procedure/certified-permission-procedure-f0ac470d8096b106ea03c22e95950bae684bcc86/msl/knot_sa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.msl.iter_sepcon.\nRequire Import Lia. (* for lia tactic (nonlinear integer arithmetic) *) \n\nRequire Import malloc_lemmas. (* background *)\nRequire Import malloc_shares. (* for comp_Ews *)\n\nLtac start_function_hint ::= idtac. (* no hint reminder *)\n\nRequire Import malloc. (* the program *)\n\n(* Note about clightgen:\nCompiling malloc.c triggers a warning, \"Unsupported compiler detected\",\nfrom the header file cdefs.h. This is ok.\n*)\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\n\n(*+ assumed specs *)\n\n(* Specifications for posix mmap0 and munmap as used by this memory manager.\n   Using wrapper mmap0 (in malloc.c) which returns 0 on failure, because \n   mmap returns -1, and pointer comparisons with non-zero literals violate \n   the C standard.   Aside from that, mmap0's spec is the same as mmap's.\n\nThe implementation of mmap0 ignores the flags (etc) so it's not essential\nfor the spec to mimic that of mmap.  Moreover different platforms seem to \nhave different values for MAP_PRIVATE or MAP_ANONYMOUS so we've commented-out\nthe precondition on flags.\n\nThe posix spec says the pointer will be aligned on page boundary.  Our\nspec uses malloc_compatible which says it's on the machine's natural alignment. \n*)\n\n\n(* TODO notes on new style spec:\nwhat do I do with unconstrained parameter?\n*)\nDefinition dummy := (Vint (Int.repr 0)).\n\n\nDefinition mmap0_spec := \n   DECLARE _mmap0\n   WITH n:Z\n   PRE [(*_addr*) (tptr tvoid), \n        (*_len*) tuint, \n        (*_prot*) tint,\n        (*_flags*) tint,\n        (*_fildes*) tint,\n        (*_off*) tlong ]\n     PROP (0 <= n <= Ptrofs.max_unsigned)\n     PARAMS (nullval; \n             Vptrofs (Ptrofs.repr n);\n             Vint (Int.repr 3); (* PROT_READ|PROT_WRITE *)\n             Vint (Int.repr 4098); (* MAP_PRIVATE|MAP_ANONYMOUS - platform-dependent *) \n             Vint (Int.repr (-1));\n            Vlong (Int64.repr 0))\n     GLOBALS () SEP ()\n   POST [ tptr tvoid ] EX p:_, \n     PROP ( if eq_dec p nullval\n            then True else malloc_compatible n p )\n     LOCAL (temp ret_temp p)\n     SEP ( if eq_dec p nullval\n           then emp else memory_block Tsh n p).\n\nDefinition munmap_spec := \n   DECLARE _munmap\n   WITH p:val, n:Z\n   PRE [ (*_addr*) (tptr tvoid), \n         (*_len*) tuint ]\n     PROP (0 <= n <= Ptrofs.max_unsigned)\n     PARAMS (p; (Vptrofs (Ptrofs.repr n)) ) GLOBALS ()\n     SEP ( memory_block Tsh n p )\n   POST [ tint ] EX res: Z,\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr res)))\n     SEP ( emp ).\n\n(*+ malloc token *)\n\n(* Accounts for the size field, alignment padding, \n   and a share of the allocated block so that malloc_token sh n p |- valid_pointer p\n   where p is the address returned by malloc.\n\nUnfolding the definition reveals the stored size value s, which \nis not the request size (n = sizeof t) but rather the size of the chunk \n(not counting the size field itself).\n\nThe constraint s + WA + WORD <= Ptrofs.max_unsigned caters for \npadding and is used e.g. in proof of body_free.\n(The conjunct (malloc_compatible s p) implies (s < Ptrofs.modulus) but \nthat's not enough.)\n\nAbout waste: for small chunks, there is waste at the beginning of each big \nblock used by fill_bin, and the module invariant mem_mgr accounts for it. \nIn addition, there is waste of size s - n at the end of each small chunk \n(as n gets rounded up to the nearest size2binZ), and each large chunk has \nwaste at the start, for alignment; these are accounted for by malloc_token.\n\nAbout the share: The idea is that one might want to be able to split tokens.\nTo do so, the API in floyd/library.v would need to include a splitting lemma.\nFor now, we keep parameter sh but do not provide a splitting lemma. \nMalloc and free are specified to use share Ews, anticipating what would be\nneeded for splittable token.\n\nThe 'retainer' (TODO term?) is needed to validate malloc_token_valid_pointer;\na small share of the user's block.\n\nNotes:\n\n- malloc_spec and free_spec \n  param on cs and on type (yes, free too)\n  use malloc_token param'd on cs and type\n\n- malloc_spec' and free_spec' \n  not param'd on anything (except implicit cs in malloc context)\n  use malloc_token' param'd on size and not on cs\n\n*)\n\nDefinition comp := VST.msl.shares.Share.comp.\n\nDefinition malloc_tok (sh: share) (n: Z) (s: Z) (p: val): mpred := \n   !! (0 <= n <= s /\\ s + WA + WORD <= Ptrofs.max_unsigned /\\ \n       (s <= bin2sizeZ(BINS-1) -> s = bin2sizeZ(size2binZ n)) /\\\n       (s > bin2sizeZ(BINS-1) -> s = n) /\\\n       malloc_compatible s p ) &&\n    data_at Tsh tuint (Vptrofs (Ptrofs.repr s)) (offset_val (- WORD) p) (* stored size *)\n  * memory_block (comp Ews) s p                               (* retainer *)\n  * memory_block Ews (s - n) (offset_val n p)                 (* waste at end of small *)\n  * (if zle s (bin2sizeZ(BINS-1))  \n    then emp\n    else memory_block Tsh WA (offset_val (-(WA+WORD)) p)).  (* waste at start of large *)\n\n(* for export *)\nDefinition malloc_token' (sh: share) (n: Z) (p: val): mpred := \n   EX s:Z, malloc_tok sh n s p.\n\n(* for export *)\nDefinition malloc_token {cs: compspecs} (sh: share) (t: type) (p: val): mpred := \n   !! field_compatible t [] p && \n   malloc_token' sh (sizeof t) p.\n\n\nLemma malloc_token'_valid_pointer_size: \n  forall sh n p, malloc_token sh n p |-- valid_pointer (offset_val (- WORD) p).\nProof.\n  intros; unfold malloc_token, malloc_token', malloc_tok; entailer!.\n  sep_apply (data_at_valid_ptr Tsh tuint (Vint (Int.repr s)) (offset_val(-WORD) p)).\n  apply top_share_nonidentity.\n  entailer!.\nQed.\n\n\nLemma malloc_token_valid_pointer_size: \n  forall sh t p, malloc_token sh t p |-- valid_pointer (offset_val (- WORD) p).\nProof.\n  intros; unfold malloc_token, malloc_token', malloc_tok; entailer!.\n  sep_apply (data_at_valid_ptr Tsh tuint (Vint (Int.repr s)) (offset_val(-WORD) p)).\n  apply top_share_nonidentity.\n  entailer!.\nQed.\n\n(* for export *)\nLemma malloc_token'_local_facts:\n  forall sh n p, malloc_token' sh n p \n  |-- !!( malloc_compatible n p /\\ 0 <= n <= Ptrofs.max_unsigned - (WA+WORD)).\nProof.\n  intros; unfold malloc_token, malloc_token'; Intro s; unfold malloc_tok; entailer!.\n  apply (malloc_compatible_prefix n s p); try omega; try assumption.\nQed.\n\n(* for export *)\nLemma malloc_token_local_facts:\n  forall {cs: compspecs} sh t p, malloc_token sh t p \n  |-- !!( malloc_compatible (sizeof t) p /\\ \n          0 <= (sizeof t) <= Ptrofs.max_unsigned - (WA+WORD) /\\\n          field_compatible t [] p).\nProof.\n  intros; unfold malloc_token, malloc_token'; Intro s; unfold malloc_tok; entailer!.\n  apply (malloc_compatible_prefix (sizeof t) s p); try omega; try assumption.\nQed.\n\n\n(* for export *)\nLemma malloc_token'_valid_pointer:\n  forall sh n p, malloc_token' sh n p |-- valid_pointer p.\nProof.\n  intros.  unfold malloc_token, malloc_token'.\n  entailer!.\n  unfold malloc_tok.\n  assert_PROP (s > 0). { \n    entailer!. bdestruct(bin2sizeZ (BINS-1) <? s). rep_omega.\n    match goal with | HA: not(bin2sizeZ _ < _) |- _ => \n      (apply Znot_lt_ge in HA; apply Z.ge_le in HA; apply H1 in HA) end.\n    pose proof (bin2size_range (size2binZ n)). subst.\n    pose proof (size2bin_range n). rep_omega.\n  }\n  sep_apply (memory_block_valid_pointer (comp Ews) s p 0); try omega.\n  apply nonidentity_comp_Ews.\n  entailer.\nQed.\n\n\n(* for export *)\nLemma malloc_token_valid_pointer:\n  forall {cs: compspecs} sh t p, malloc_token sh t p |-- valid_pointer p.\nProof.\n  intros.  unfold malloc_token, malloc_token'.\n  entailer!.\n  unfold malloc_tok.\n  assert_PROP (s > 0). { \n    entailer!. bdestruct(bin2sizeZ (BINS-1) <? s). rep_omega.\n    match goal with | HA: not(bin2sizeZ _ < _) |- _ => \n      (apply Znot_lt_ge in HA; apply Z.ge_le in HA; apply H2 in HA) end.\n    pose proof (bin2size_range (size2binZ (sizeof t))). subst.\n    pose proof (size2bin_range (sizeof t)). rep_omega.\n  }\n  sep_apply (memory_block_valid_pointer (comp Ews) s p 0); try omega.\n  apply nonidentity_comp_Ews.\n  entailer.\nQed.\n\nHint Resolve malloc_token_valid_pointer_size : valid_pointer.\nHint Resolve malloc_token'_valid_pointer_size : valid_pointer.\nHint Resolve malloc_token_valid_pointer : valid_pointer.\nHint Resolve malloc_token'_valid_pointer : valid_pointer.\nHint Resolve malloc_token_local_facts : saturate_local.\nHint Resolve malloc_token'_local_facts : saturate_local.\n\n(*+ free lists *)\n\n(* TODO 'link' versus 'nxt' in the comments *)\n\n(* linked list segment, for free chunks of a fixed size.\n\np points to a linked list of len chunks, terminated at r.\n\nChunks are viewed as (sz,nxt,remainder) where nxt points to the\nnext chunk in the list.  Each chunk begins with the stored size\nvalue sz.  Each pointer, including p, points to the nxt field, \nnot to sz.\nThe value of sz is the number of bytes in (nxt,remainder).\n\nA segment predicate is used, to cater for fill_bin which grows \nthe list at its tail. For non-empty segment, terminated at r means \nthat r is the value in the nxt field of the last chunk -- which \nmay be null or a valid pointer to not-necessarily-initialized memory. \n\nThe definition uses nat, for ease of termination check, at cost \nof Z conversions.  I tried using the Function mechanism, with len:Z\nand {measure Z.to_nat len}, but this didn't work.\n\nNote on range of sz:  Since the bins are for moderate sizes,\nthere's no need for sz > Int.max_unsigned, but the malloc/free API\nuses size_t for the size, and jumbo chunks need to be parsed by\nfree even though they won't be in a bin, so this spec uses \nPtrofs in conformance with the code's use of size_t.\nTODO - parsing of big chunks has nothing to do with mmlist. \n\nNote: in floyd/field_at.v there's a todo note related to revising\ndefs assoc'd with malloc_compatible.\n*)\n\nFixpoint mmlist (sz: Z) (len: nat) (p: val) (r: val): mpred :=\n match len with\n | O => !! (0 < sz <= bin2sizeZ(BINS - 1) /\\ p = r /\\ is_pointer_or_null p) && emp \n | (S n) => EX q:val, \n         !! (p <> r /\\ malloc_compatible sz p) &&  \n         data_at Tsh tuint (Vptrofs (Ptrofs.repr sz)) (offset_val (- WORD) p) *\n         data_at Tsh (tptr tvoid) q p *\n         memory_block Tsh (sz - WORD) (offset_val WORD p) *\n         mmlist sz n q r\n end.\n\n(* an uncurried variant, caters for use with iter_sepcon *)\nDefinition mmlist' (it: nat * val * Z) :=\n  mmlist (bin2sizeZ (snd it)) (fst (fst it)) (snd (fst it)) nullval. \n\n\n\n(*+ module invariant mem_mgr *)\n\n(* There is an array, its elements point to null-terminated lists \nof right size chunks, and there is some wasted memory.\n*) \n\n(* with Resource accounting *)\nDefinition mem_mgr_R (gv: globals) (rvec: resvec): mpred := \n  EX bins: list val, EX idxs: list Z, EX lens: list nat,\n    !! (Zlength bins = BINS /\\ Zlength lens = BINS /\\\n        lens = map Z.to_nat rvec /\\\n        idxs = map Z.of_nat (seq 0 (Z.to_nat BINS)) /\\  \n        no_neg rvec ) &&\n  data_at Ews (tarray (tptr tvoid) BINS) bins (gv _bin) * \n  iter_sepcon mmlist' (zip3 lens bins idxs) * \n  TT. (* waste, which arises due to alignment in bins *)\n\nDefinition mem_mgr (gv: globals): mpred := EX rvec: resvec, mem_mgr_R gv rvec.\n\n(*  This is meant to describe the extern global variables of malloc.c,\n    as they would appear as processed by CompCert and Floyd. *)\nDefinition initialized_globals (gv: globals) := \n   !! (headptr (gv malloc._bin)) &&\n   data_at Ews (tarray (tptr tvoid) BINS) (repeat nullval (Z.to_nat BINS)) (gv malloc._bin).\n\nLemma create_mem_mgr_R: \n  forall (gv: globals),\n  !! (headptr (gv malloc._bin)) &&\n   data_at Ews (tarray (tptr tvoid) BINS) (list_repeat (Z.to_nat BINS) nullval) (gv malloc._bin)\n     |-- mem_mgr_R gv emptyResvec.\nProof.\n intros.\n Intros.\n unfold mem_mgr_R.\n Exists (list_repeat (Z.to_nat BINS) nullval). EExists. EExists.\n entailer!.\n split.\n reflexivity.\n repeat constructor; omega.\n  unfold mmlist'.\n  erewrite iter_sepcon_func_strong with \n    (l := (zip3 (repeat 0%nat (Z.to_nat BINS)) (repeat nullval (Z.to_nat BINS)) (Zseq BINS)))\n    (Q := (fun it : nat * val * Z => emp)).\n  { rewrite iter_sepcon_emp'. entailer. intros. normalize. }\n  intros [[num p] sz] Hin.\n  pose proof (In_zip3 ((num,p),sz)\n                      (repeat 0%nat (Z.to_nat BINS))\n                      (repeat nullval (Z.to_nat BINS))\n                      (Zseq BINS)\n                      Hin) as [Hff [Hsf Hs]].\n  clear H H0 Hin.\n  assert (Hn: num = 0%nat) by (eapply repeat_spec; apply Hff). \n  rewrite Hn; clear Hn Hff.\n  assert (Hp: p = nullval) by (eapply repeat_spec; apply Hsf). \n  rewrite Hp; clear Hp Hsf.\n  assert (Hsz: 0 <= sz < BINS).\n  { assert (Hsx: 0 <= sz < BINS). \n    apply in_Zseq; try rep_omega; try assumption. assumption. }\n  simpl. unfold mmlist.\n  apply pred_ext; entailer!.\n  pose proof (bin2size_range sz Hsz). rep_omega.\nQed.\n\nLemma create_mem_mgr: \n  forall (gv: globals), initialized_globals gv |-- mem_mgr gv.\nProof.  \n  intros gv. unfold mem_mgr. Exists emptyResvec. apply (create_mem_mgr_R gv).\nQed.\n\n\n\n(*+ interfaces specs *)\n\n(* Notes: \nResourced specs are designed to subsume the non-resourced specs; so don't strengthen old precondition but rather post, which results in annoying set of cases for malloc.\n\nTODO _R resourced versions so far correspond to malloc_spec' and free_spec' with implicit compspecs; need to add the ones with explicit compspecs, for linking, and prove their subsumptions.\n*)\n\n(* public interface *)\n\n(* NOTES on describing the interface.\n\nStandard specs of malloc and free: malloc may return null, indicating failure; the representation invariant mem_mgr exposes nothing to the client about the implementation \n\nResourced specs describe the malloc-free system in terms of a standard implementation in which free lists (dubbed buckets) are maintained for a range of 'small' chunk sizes.  The resourced spec for malloc ensures that it succeeds if the requisite bucket is non-empty.  There is a resourced spec for the non-standard function pre_fill that lets a client provide a block of memory to be used for a particular bucket.  The representation invariant mem_mgr_R gives a lower bound on the current bucket sizes, as a list of naturals we dub 'resource vector'.  \nFor somewhat arbitrary reasons --simplicity and also compatibility with existing proofs of the non-resourced version-- the spec of pre_fill requires a specific fixed size for the 'big block' provided by the caller.\n\nThe resource vector corresponds exactly to the free list sizes: freeing a small chunk adds one to its free list, and if an allocation is guaranteed to succeed (because its free list is non-empty) then the size of the free list decreases by one.  However, a non-guaranteed allocation may succeed either because the chunk is available in its free list, thereby decreasing the list size by one, or because the free list has been renewed by a call to the operating system, in which case the bucket may have increased in size.  This is reflected in the postcondition of malloc.  (That postondition could be made slighly stronger, to reflect successful refilling of the bucket, but it doesn't seem worth doing since the situation isn't relevant to clients interested in guaranteed resources.)\n\nThe resourced specs say nothing about large chunks which are not stored in buckets.  A client that relies on availability of large chunks needs to allocate these upon initialization, either via the malloc-free system (which in turn relies on mmap), by direct calls to mmap, or using its own bss.    \n\nResource-sensitive clients will use malloc_spec_R_simple, free_spec_R, pre_fill_spec, and try_pre_fill_spec.\n\n*)\n\n(* the spec for the code *)\nDefinition malloc_spec_R' := \n   DECLARE _malloc\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((* _nbytes *) (Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R gv rvec )\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( if guaranteed rvec n\n             then mem_mgr_R gv (add_resvec rvec (size2binZ n) (-1)) *\n                  malloc_token' Ews n p * memory_block Ews n p\n             else if eq_dec p nullval \n                  then mem_mgr_R gv rvec\n                  else (if n <=? maxSmallChunk \n                        then (EX rvec':_, !!(eq_except rvec' rvec (size2binZ n))\n                                            && (mem_mgr_R gv rvec'))\n                        else mem_mgr_R gv rvec) *\n                       malloc_token' Ews n p * memory_block Ews n p).\n\n(* convenient specs for resource-conscious clients, first draft.\nFor completeness we need:\n- malloc large doesn't change the vector (and may not succeed)\n- malloc with guarantee (which implies small)\n- free large doesn't change vector, free small decreases\nWe might also want to eliminate conditional posts in favor of non-null preconditions.\n *)\nDefinition malloc_spec_R_simple' :=\n   DECLARE _malloc\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned - (WA+WORD) /\\\n            guaranteed rvec n = true)\n       PARAMS ((* _nbytes *) (Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R gv rvec )\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( mem_mgr_R gv (add_resvec rvec (size2binZ n) (-1)) *\n             malloc_token' Ews n p * memory_block Ews n p ).\n\n\nDefinition free_spec_R' :=\n DECLARE _free\n   WITH n:Z, p:val, gv:globals, rvec:resvec\n   PRE [ tptr tvoid ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (mem_mgr_R gv rvec;\n            if eq_dec p nullval then emp\n            else (malloc_token' Ews n p * memory_block Ews n p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (if eq_dec p nullval \n            then mem_mgr_R gv rvec\n            else if n <=? maxSmallChunk\n                 then mem_mgr_R gv (add_resvec rvec (size2binZ n) 1)\n                 else mem_mgr_R gv rvec ).\n\n\nDefinition pre_fill_spec' :=\n DECLARE _pre_fill \n   WITH n:Z, p:val, gv:globals, rvec:resvec\n   PRE [ tuint, tptr tvoid ]\n       PROP (0 <= n <= maxSmallChunk /\\ malloc_compatible BIGBLOCK p)\n       PARAMS ((Vptrofs (Ptrofs.repr n)); p) GLOBALS (gv) \n       SEP (mem_mgr_R gv rvec; memory_block Tsh BIGBLOCK p) \n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) \n                                     (chunks_from_block (size2binZ n)))).\n\nDefinition pre_fill_spec {cs: compspecs} := \n DECLARE _pre_fill \n   WITH n:Z, p:val, gv:globals, rvec:resvec\n   PRE [ tuint, tptr tvoid ]\n       PROP (0 <= n <= maxSmallChunk /\\ malloc_compatible BIGBLOCK p)\n       PARAMS ((Vptrofs (Ptrofs.repr n)); p) GLOBALS (gv) \n       SEP (mem_mgr_R gv rvec; memory_block Tsh BIGBLOCK p) \n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) \n                                     (chunks_from_block (size2binZ n)))).\n\nDefinition try_pre_fill_spec' :=\n DECLARE _try_pre_fill \n   WITH n:Z, req:Z, rvec:resvec, gv:globals\n   PRE [ tuint, tint ]\n       PROP (0 <= n <= maxSmallChunk /\\ 0 <= req <= Int.max_signed)\n       PARAMS ((Vint (Int.repr n)); (Vint (Int.repr req))) GLOBALS (gv) \n       SEP (mem_mgr_R gv rvec) \n   POST [ tint ] EX result: Z,\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr result)))\n     SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) result)).\n\n\nDefinition try_pre_fill_spec {cs: compspecs} := \n DECLARE _try_pre_fill \n   WITH n:Z, req:Z, rvec:resvec, gv:globals\n   PRE [ tuint, tint ]\n       PROP (0 <= n <= maxSmallChunk /\\ 0 <= req <= Int.max_signed)\n       PARAMS ((Vint (Int.repr n)); (Vint (Int.repr req))) GLOBALS (gv) \n       SEP (mem_mgr_R gv rvec) \n   POST [ tint ] EX result: Z,\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr result)))\n     SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) result)).\n\n\nDefinition malloc_spec' := \n   DECLARE _malloc\n   WITH n:Z, gv:globals\n   PRE [ size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr gv )\n   POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( mem_mgr gv;\n             if eq_dec p nullval then emp\n             else (malloc_token' Ews n p * memory_block Ews n p)).\n\n\nDefinition malloc_spec {cs: compspecs} (t: type):= \n   DECLARE _malloc\n   WITH gv:globals\n   PRE [ size_t ]\n       PROP (0 <= sizeof t <= Ptrofs.max_unsigned - (WA+WORD);\n             complete_legal_cosu_type t = true;\n             natural_aligned natural_alignment t = true)\n       PARAMS ((* _nbytes *) (Vptrofs (Ptrofs.repr (sizeof t)))) GLOBALS (gv)\n       SEP ( mem_mgr gv )\n   POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( mem_mgr gv;\n             if eq_dec p nullval then emp\n             else (malloc_token Ews t p * data_at_ Ews t p)).\n\n\nDefinition free_spec' :=\n DECLARE _free\n   WITH n:Z, p:val, gv: globals\n   PRE [ tptr tvoid ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (mem_mgr gv;\n              if eq_dec p nullval then emp\n              else (malloc_token' Ews n p * memory_block Ews n p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr gv).\n\nDefinition free_spec {cs:compspecs} (t: type) := \n   DECLARE _free\n   WITH p:val, gv:globals\n   PRE [ tptr tvoid ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (mem_mgr gv; \n            if eq_dec p nullval then emp\n            else (malloc_token Ews t p * data_at_ Ews t p))\n   POST [ Tvoid ]\n       PROP ()\n       LOCAL ( )\n       SEP (mem_mgr gv).\n\n(*+ subsumption for interface specs *)\n\nLemma malloc_spec_R_sub:\n forall {cs: compspecs},\n   funspec_sub (snd malloc_spec_R') (snd malloc_spec').\nProof.\ndo_funspec_sub. destruct w as [n gv]. clear H.\nunfold mem_mgr.\nIntros rvec.\nExists (n, gv, rvec) emp. (* empty frame *)\nsimpl; entailer!.\nintros tau ? ?. \nset (p:=eval_id ret_temp tau).\nExists p; entailer!.\ndestruct (guaranteed rvec n) eqn:guar.\n- (* guaranteed *)\n  if_tac; auto.\n  Exists (add_resvec rvec (size2binZ n) (-1)); entailer!.\n  rewrite H4; entailer!.\n  Exists (add_resvec rvec (size2binZ n) (-1)); entailer!.\n- (* not guaranteed *)\n  bdestruct (n <=? maxSmallChunk).\n  + if_tac; auto. Exists rvec; entailer!. Intros rvec'; Exists rvec'; entailer!.\n  + if_tac; auto; Exists rvec; entailer!.\nQed.\n\nLemma malloc_spec_R_simple_sub:\n forall {cs: compspecs},\n   funspec_sub (snd malloc_spec_R') (snd malloc_spec_R_simple').\nProof.\ndo_funspec_sub. \ndestruct w as [[n gv] rvec]. clear H.\nExists (n,gv,rvec) emp. simpl; entailer!.\nintros tau ? ?. \ndestruct (guaranteed rvec n) eqn:guar; try inversion H0.\nExists (eval_id ret_temp tau). entailer!.\nQed.\n\nLemma free_spec_R_sub:\n forall {cs: compspecs},\n   funspec_sub (snd free_spec_R') (snd free_spec').\nProof.\ndo_funspec_sub. \ndestruct w as [[n p] gv]. clear H.\nunfold mem_mgr.\nIntros rvec. Exists (n,p,gv,rvec) emp.\nsimpl; entailer!.\nintros tau ?.\nif_tac.\nExists rvec; entailer!.\nbdestruct (n <=? maxSmallChunk).\n- (* small *)\n  Exists (add_resvec rvec (size2binZ n) 1); entailer!.\n- (* large *)\n  Exists rvec; entailer!.\nQed.\n\n\n(*! subsumption lemmas to support linking *)\n\nLemma malloc_spec_sub:\n forall {cs: compspecs} (t: type), \n   funspec_sub (snd malloc_spec') (snd (malloc_spec t)).\nProof.\ndo_funspec_sub. rename w into gv. clear H.\nExists (sizeof t, gv) emp. simpl; entailer!.\nintros tau ? ?. Exists (eval_id ret_temp tau).\nentailer!.\nif_tac; auto.\nunfold malloc_token.\nassert_PROP (field_compatible t [] (eval_id ret_temp tau)).\n{ entailer!.\n  apply malloc_compatible_field_compatible; auto. }\nentailer!.\nrewrite memory_block_data_at_; auto.\nQed.\n\n\nLemma free_spec_sub:\n forall {cs: compspecs} (t: type), \n   funspec_sub (snd free_spec') (snd (free_spec t)).\nProof.\ndo_funspec_sub. destruct w as [p gv]. clear H.\nExists (sizeof t, p, gv) emp. simpl; entailer!.\nif_tac; trivial.\nsep_apply data_at__memory_block_cancel.\nunfold malloc_token; entailer!.\nQed.\n\n\nLemma pre_fill_spec_sub:\n forall {cs: compspecs},\n   funspec_sub (snd pre_fill_spec') (snd pre_fill_spec).\nProof.\ndo_funspec_sub. destruct w as [[[n p] gv] rvec]. clear H.\nExists (n,p,gv,rvec) emp. simpl. entailer!.\nQed.\n\n\nLemma try_pre_fill_spec_sub:\n forall {cs: compspecs},\n   funspec_sub (snd try_pre_fill_spec') (snd try_pre_fill_spec).\nProof.\ndo_funspec_sub. destruct w as [[[n r] gv] rvec]. clear H.\nExists (n,r,gv,rvec) emp. simpl. entailer!.\nintros. Exists x0. entailer!.\nQed. \n\n\n(*+ specs of private functions *)\n\nDefinition bin2size_spec :=\n DECLARE _bin2size\n  WITH b: Z\n  PRE [ tint ] \n     PROP( 0 <= b < BINS ) \n     PARAMS ((Vint (Int.repr b))) GLOBALS () SEP ()\n  POST [ tuint ] \n     PROP() LOCAL(temp ret_temp (Vptrofs (Ptrofs.repr (bin2sizeZ b)))) SEP ().\n\nDefinition size2bin_spec :=\n DECLARE _size2bin\n  WITH s: Z\n  PRE [ tuint ]    \n     PROP( 0 <= s <= Ptrofs.max_unsigned ) \n     PARAMS ((Vptrofs (Ptrofs.repr s))) GLOBALS () SEP ()\n  POST [ tint ]\n     PROP() LOCAL(temp ret_temp (Vint (Int.repr (size2binZ s)))) SEP ().\n\n\nDefinition list_from_block_spec :=\n DECLARE _list_from_block\n  WITH s: Z, p: val, tl: val, tlen: nat, b: Z\n  PRE [ tuint, tptr tschar, tptr tvoid ]    \n     PROP( 0 <= b < BINS /\\ s = bin2sizeZ b /\\ malloc_compatible BIGBLOCK p ) \n     PARAMS ((Vptrofs (Ptrofs.repr s)); p; tl) GLOBALS ()\n     SEP ( memory_block Tsh BIGBLOCK p; mmlist s tlen tl nullval )\n  POST [ tptr tvoid ] EX res:_,\n     PROP() \n     LOCAL(temp ret_temp res)\n     SEP ( mmlist s (Z.to_nat(chunks_from_block (size2binZ s)) + tlen) res nullval * TT ).\n\n\n(* The postcondition describes the list returned, together with\n   TT for the wasted space at the beginning and end of the big block from mmap. *)\n\nDefinition fill_bin_spec :=\n DECLARE _fill_bin\n  WITH b: _\n  PRE [ tint ]\n     PROP(0 <= b < BINS) PARAMS ((Vint (Int.repr b))) GLOBALS () SEP ()\n  POST [ (tptr tvoid) ] EX p:_, EX len:Z,\n     PROP( if eq_dec p nullval then True else len > 0 ) \n     LOCAL(temp ret_temp p)\n     SEP ( if eq_dec p nullval then emp\n           else mmlist (bin2sizeZ b) (Z.to_nat len) p nullval * TT).\n\nDefinition malloc_small_spec :=\n   DECLARE _malloc_small\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ] \n       PROP (0 <= n <= bin2sizeZ(BINS-1))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R gv rvec )\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( if guaranteed rvec n\n             then mem_mgr_R gv (add_resvec rvec (size2binZ n) (-1)) *\n                  malloc_token' Ews n p * memory_block Ews n p\n             else if eq_dec p nullval \n                  then mem_mgr_R gv rvec \n                  else (EX rvec':_, !!(eq_except rvec' rvec (size2binZ n))\n                                 && mem_mgr_R gv rvec' *\n                                    malloc_token' Ews n p * memory_block Ews n p) ).\n\n\nDefinition malloc_large_spec :=\n   DECLARE _malloc_large\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ]\n       PROP (bin2sizeZ(BINS-1) < n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R gv rvec )\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr_R gv rvec;\n            if eq_dec p nullval then emp \n            else malloc_token' Ews n p * memory_block Ews n p).\n\n(* s is the stored chunk size and n is the original request amount. *)\n(* Note: the role of n in free_small_spec is merely to facilitate proof for free itself *)\nDefinition free_small_spec :=\n   DECLARE _free_small\n   WITH p:_, s:_, n:_, gv:globals, rvec:resvec\n   PRE [ tptr tvoid, tuint ]\n       PROP (0 <= n <= bin2sizeZ(BINS-1) /\\ s = bin2sizeZ(size2binZ n) /\\ \n             malloc_compatible s p)\n       PARAMS (p; (Vptrofs (Ptrofs.repr s))) GLOBALS (gv)\n       SEP ( data_at Tsh tuint (Vptrofs (Ptrofs.repr s)) (offset_val (- WORD) p); \n            data_at_ Tsh (tptr tvoid) p;\n            memory_block Tsh (s - WORD) (offset_val WORD p);\n            mem_mgr_R gv rvec)\n   POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) 1)).\n\nDefinition free_large_spec :=\n   DECLARE _free_large\n   WITH p:_, s:_, gv:globals, rvec:resvec\n   PRE [ tptr tvoid, tuint ]\n       PROP (malloc_compatible s p /\\ maxSmallChunk < s <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS (p; (Vptrofs (Ptrofs.repr s))) GLOBALS (gv)\n       SEP ( data_at Tsh tuint (Vptrofs (Ptrofs.repr s)) (offset_val (- WORD) p); \n            data_at_ Tsh (tptr tvoid) p;\n            memory_block Tsh (s - WORD) (offset_val WORD p);\n            memory_block Tsh WA (offset_val (- (WA+WORD)) p);\n            mem_mgr_R gv rvec)\n   POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R gv rvec).\n\nDefinition external_specs := [mmap0_spec; munmap_spec].\nDefinition user_specs := [malloc_spec'; free_spec'].\nDefinition user_specs_R := [pre_fill_spec'; try_pre_fill_spec'; malloc_spec_R'; free_spec_R'].\nDefinition private_specs := [ malloc_large_spec; malloc_small_spec; free_large_spec; free_small_spec; bin2size_spec; size2bin_spec; list_from_block_spec; fill_bin_spec]. \n\n\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/memmgr/spec_malloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "(**********************************************************************************\n * The PEDANTIC (Proof Engine for Deductive Automation using Non-deterministic\n * Traversal of Instruction Code) verification framework\n *\n * Developed by Kenneth Roe\n * For more information, check out www.cs.jhu.edu/~roe\n *\n * TreeTraversal.v\n * This file contains the proof of correctness of a tree traversal algorithm using\n * the PEDANTIC verification framework.\n *\n **********************************************************************************)\n\nRequire Export SfLib.\nRequire Export SfLibExtras.\nRequire Export ImpHeap.\nRequire Export AbsState.\nRequire Export AbsExecute.\nRequire Export AbsStateInstance.\nRequire Export Simplify.\nRequire Export Eqdep.\nRequire Export StateImplication.\nRequire Export Classical.\nRequire Export Unfold.\nRequire Export Fold.\nRequire Export merge.\nRequire Export ProgramTactics.\nOpaque basicEval.\n\n(* **************************************************************************\n *\n * Here is the example from the paper.  We start with some definitions for\n * the variables in the program.\n *\n ***************************************************************************)\n\nNotation \"'clauses'\" := (Id 1) (at level 1).\nNotation \"'assignments_to_do_head'\" := (Id 2) (at level 1).\nNotation \"'assignments_to_do_tail'\" := (Id 3) (at level 1).\nNotation \"'stack'\" := (Id 4) (at level 1).\nNotation \"'assignments'\" := (Id 5) (at level 1).\nNotation \"'watches'\" := (Id 6) (at level 1).\nNotation \"'backtrack'\" := (Id 7) (at level 1).\nNotation \"'iiii'\" := (Id 8) (at level 1).\nNotation \"'varx'\" := (Id 9) (at level 1).\nNotation \"'valuex'\" := (Id 10) (at level 1).\nNotation \"'have_var'\" := (Id 11) (at level 1).\nNotation \"'prop'\" := (Id 12) (at level 1).\nNotation \"'todo'\" := (Id 13) (at level 1).\nNotation \"'clause'\" := (Id 14) (at level 1).\nNotation \"'ssss'\" := (Id 15) (at level 1).\nNotation \"'vvvv'\" := (Id 16) (at level 1).\nNotation \"'val'\" := (Id 17) (at level 1).\nNotation \"'kkkk'\" := (Id 18) (at level 1).\nNotation \"'nc'\" := (Id 19) (at level 1).\nNotation \"'jjjj'\" := (Id 20) (at level 1).\nNotation \"'non_watch'\" := (Id 21) (at level 1).\nNotation \"'has_non_watch'\" := (Id 22) (at level 1).\nNotation \"'skip'\" := (Id 22) (at level 1).\n\nDefinition var_count := 4.\n\nDefinition next_offset := 1.\nDefinition positive_lit_offset := 2.\nDefinition negative_lit_offset := var_count + 2.\nDefinition watch_var_offset := var_count * 2 + 2.\nDefinition watch_next_offset := var_count * 3 + 2.\nDefinition watch_prev_offset := var_count * 4 + 2.\n\nDefinition sizeof_clause := var_count * 5 + 1.\n\nDefinition prev_offset := 2.\nDefinition todo_var_offset := 3.\nDefinition todo_val_offset := 4.\nDefinition todo_unit_offset := 5.\n\nDefinition sizeof_assignments_to_do := 5.\n\nDefinition stack_var_offset := 2.\nDefinition stack_val_offset := 3.\nDefinition stack_prop_offset := 4.\n\nDefinition sizeof_assignment_stack := 4.\n\nDefinition level := 0.\nDefinition domain {ev} {eq} {f} (x : @absExp ev eq f) : (@absExp ev eq f) := #0.\n\n(*Notation \"'ForAllRecords' x 'in' r ',' y\" :=\n    (match level+1,v(level),(fun x => if beq_absExp x v(level) then r else domain x) with\n     | level,x,domain => (AbsAll TreeRecords(r) y)\n     | _,_,_ => AbsEmpty\n     end) (at level 10).\n\nDefinition D {ev} {eq} {f} := ForAllRecords a in v(0), ([find(a,@domain ev eq f a)====#0]).*)\n\n(*Notation \"x '====' y\" := (AbsFun (Id 5) (x::y::nil))\n  (at level 6).*)\n\nDefinition invariant: absStateBasic :=\n    (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (\n        TREE(!!clauses,v(0),#sizeof_clause,(#next_offset::nil)) **\n        TREE(!!assignments_to_do_head,v(1),#sizeof_assignment_stack,(#next_offset::nil)) **\n        TREE(!!stack,v(2),#sizeof_assignment_stack,(#next_offset::nil)) **\n        ARRAY(!!assignments,#var_count,v(3)) **\n        ARRAY(!!watches,#var_count,v(4)) **\n        (* Assertions that the stack and assignments array contain the same set\n           of assignments *)\n        (AbsAll TreeRecords(v(2))\n            ([--(v(2),v(5))-->stack_var_offset <<<< #var_count] **\n             ([--(v(2),v(5))-->stack_val_offset ==== #1] *\\/* [--(v(2),v(5))-->stack_val_offset ==== #2]) **\n             ([nth(v(3),--(v(2),v(5))-->stack_var_offset)====--(v(2),v(5))-->stack_val_offset]) **\n             (AbsAll TreeRecords(nth(find(v(2),v(5)),#2))\n                 ([~~(--(v(2),v(5))-->stack_var_offset====--(nth(find(v(2),v(5)),#2),v(6))-->stack_var_offset)])))) **\n        (AbsAll range(#0,#(var_count))\n            ([nth(v(3),v(5))====#0] *\\/*\n             AbsExists (TreeRecords(v(2)))\n                  ([(--(v(2),v(6))-->stack_var_offset====v(5) //\\\\\n                   --(v(2),v(6))-->stack_val_offset====nth(v(3),v(5)))]) )) **\n        (* Assertion defining the prev pointer in the assignments_to_do\n           doubly linked list *)\n        (AbsAll TreeRecords(v(1))\n            ([(--(v(1),v(5))-->prev_offset====#0 //\\\\ (!!assignments_to_do_head)====v(5)) \\\\//\n             (--(v(1),v(5))-->prev_offset inTree v(1) //\\\\\n              --(v(1),--(v(1),v(5))-->prev_offset)-->next_offset====v(5))])) **\n        (AbsEach range(#0,#(var_count))\n            (* Define the basic linked list connecting the watch variables\n               inside the clauses linked list *)\n            (AbsExistsT\n                ((Path((nth(v(4),v(5))), v(0), v(6), #sizeof_clause, ((#watch_next_offset++++v(5))::nil))) **\n                 (* Define the prev variable and the fact that if null we are at\n                    the head of the list *)\n                 (AbsAll TreeRecords(v(6))\n                     ([(--(v(6),v(7))--->(#watch_prev_offset++++v(5))====#0 //\\\\ nth(v(4),v(5))====v(6)) \\\\//\n                      (--(v(6),--(v(6),v(7))--->(#watch_prev_offset++++v(5)))--->(#watch_next_offset++++v(5)))====v(7)]))))) **\n        (AbsAll TreeRecords(v(0))\n            (* The current assignment is consistent with the clause *)\n           ((AbsExists range(#0,#(var_count))\n                ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\\n                    (nth(v(3),v(6))====#2 \\\\// nth(v(3),v(6))====#0)) \\\\//\n                  (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\\n                    (nth(v(3),v(6))====#1 \\\\// nth(v(3),v(6))====#0))])) **\n            (*\n             * make sure that if the watch_var field is non-zero (pointing to\n             * a variable) that watch_next and watch_prev put this clause into\n             * the linked list for the watch variable.\n             * Also, for all watch variables, either positive_lit or negative_lit\n             * is true.\n             *)\n            (AbsAll range(#0,#(var_count))\n                ([\n                 (--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0) \\\\//\n                  (--(v(0),v(5))--->(#positive_lit_offset++++v(6))) \\\\//\n                  (--(v(0),v(5))--->(#negative_lit_offset++++v(6)))])) **\n            (AbsAll range(#0,#(var_count))\n                ([\n                 (~~(--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0) //\\\\\n                 (~~(--(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0) \\\\//\n                   nth(v(4),v(6))====v(5))) \\\\//\n                 (--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 //\\\\\n                  --(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0 //\\\\\n                  ~~(nth(v(4),v(6))====v(5)))])) **\n            (* Make sure there are precisely two watch variables per clause or all variables are watches,\n               needs fixing? *)\n            (SUM(range(#0,#(var_count)),ite((--(v(0),v(5))--->(#watch_var_offset++++v(6))),(#1),(#0)),#2)) **\n            (* Watch variable invariant--case 1:  All but one variable in the\n               clause are assigned, any watch variable pointing to an assigned\n               variable is pointing to a variable that was assigned after all\n               other assigned variables in the clause.  Also, one of the two\n               watch variables points to the one unassigned variable *)\n            ((((SUM(range(#0,#(var_count)),\n              (((--(v(0),v(5))--->(#positive_lit_offset++++v(6))) \\\\// (--(v(0),v(5))--->(#negative_lit_offset++++v(6)))) //\\\\\n                   ite(nth(v(3),v(6))====#0,#1,#0)),\n               #1) **\n            (* The one unassigned literal is a watch--needs fixing? *)\n            (AbsAll range(#0,#(var_count))\n                 ([(#0<<<<--(v(0),v(5))--->(#watch_var_offset++++v(6)) //\\\\\n                   (nth(v(3),v(6))====#0)) \\\\//\n                   (\n                    ((#0<<<<nth(v(3),v(6))) \\\\// ((--(v(0),v(5))--->(#positive_lit_offset++++v(6))====#0 //\\\\\n                    --(v(0),v(5))--->(#negative_lit_offset++++v(6))====#0))))])) **\n            (AbsAll range(#0,#(var_count))\n                 (AbsAll range(#0,#(var_count))\n                     (([--(v(0),v(5))--->(#watch_var_offset++++v(6)) \\\\//\n                        ((((--(v(0),v(5))--->(#positive_lit_offset++++v(6)))====#0 //\\\\ (--(v(0),v(5))--->(#negative_lit_offset++++v(6))====#0)))) \\\\//\n                        ~~(--(v(0),v(5))--->(#watch_var_offset++++v(7))) \\\\//\n                        nth(v(3),v(6))====#0 \\\\// nth(v(3),v(7))====#0 \\\\// v(6)====v(7)]) *\\/*\n                      (AbsExists TreeRecords(v(2))\n                          (([--(v(2),v(8))-->stack_var_offset====v(7)]) **\n                           (AbsExists TreeRecords(find(v(2),v(8)))\n                              ([--(v(2),v(9))-->stack_var_offset====v(6)])))))))))) *\\/*\n            (* Watch variable invariant case 2: One of the assignments already\n               satisfies the clause, if a watch variable is assigned a value,\n               then that value must be a satisfying assignment or occured\n               after a satisfying assignment *)\n            ( (AbsExists range(#0,#(var_count))\n                ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#2) \\\\//\n                  (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#1)])) **\n              (AbsAll range(#0,#(var_count))\n                ((([#0====nth(v(3),v(6))]) *\\/*\n                  ([--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0]) **\n                  ([#0<<<<nth(v(3),v(6))])) *\\/*\n                  (AbsExists TreeRecords(v(2))\n                    (([--(v(2),v(7))-->stack_var_offset====v(6)]) **\n                      (AbsExists TreeRecords(find(v(2),v(7)))\n                        ([((#0 <<<< (--(v(0),v(5))--->(#positive_lit_offset++++ --(v(2),v(8))-->stack_var_offset))) //\\\\\n                          --(v(2),v(8))-->stack_val_offset====#2) \\\\//\n                        ((#0 <<<< --(v(0),v(5))--->(#negative_lit_offset++++ --(v(2),v(8))-->stack_var_offset)) //\\\\\n                         --(v(2),v(8))-->stack_val_offset====#1)]))))))) *\\/*\n\n         (* Watch variable invariant case 3: both watch variables point to\n            unassigned variables *)\n         (AbsAll range(#0,#(var_count))\n             ([--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 \\\\// nth(v(3),v(6))====#0]))\n))))))))).\n\nDefinition invariant1: absStateBasic :=\n    (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (\n        TREE(!!clauses,v(0),#sizeof_clause,(#next_offset::nil)) **\n        TREE(!!assignments_to_do_head,v(1),#sizeof_assignment_stack,(#next_offset::nil)) **\n        TREE(!!stack,v(2),#sizeof_assignment_stack,(#next_offset::nil)) **\n        ARRAY(!!assignments,#var_count,v(3)) **\n        ARRAY(!!watches,#var_count,v(4)) **\n        ([(!!valuex)====#1]) **\n        ([(~~ (!!have_var)) \\\\// (nth(v(3),!!varx)====#0 //\\\\ (((!!valuex)====#1) \\\\// ((!!valuex)====#2)))]) **\n        (* Assertions that the stack and assignments array contain the same set\n           of assignments *)\n        (AbsAll TreeRecords(v(2))\n            ([--(v(2),v(5))-->stack_var_offset <<<< #var_count] **\n             ([--(v(2),v(5))-->stack_val_offset ==== #1] *\\/* [--(v(2),v(5))-->stack_val_offset ==== #2]) **\n             ([nth(v(3),--(v(2),v(5))-->stack_var_offset)====--(v(2),v(5))-->stack_val_offset]) **\n             (AbsAll TreeRecords(nth(find(v(2),v(5)),#2))\n                 ([~~(--(v(2),v(5))-->stack_var_offset====--(nth(find(v(2),v(5)),#2),v(6))-->stack_var_offset)])))) **\n        (AbsAll range(#0,#(var_count))\n            ([nth(v(3),v(5))====#0] *\\/*\n             AbsExists (TreeRecords(v(2)))\n                  ([(--(v(2),v(6))-->stack_var_offset====v(5) //\\\\\n                   --(v(2),v(6))-->stack_val_offset====nth(v(3),v(5)))]) )) **\n        (* Assertion defining the prev pointer in the assignments_to_do\n           doubly linked list *)\n        (AbsAll TreeRecords(v(1))\n            ([(--(v(1),v(5))-->prev_offset====#0 //\\\\ (!!assignments_to_do_head)====v(5)) \\\\//\n             (--(v(1),v(5))-->prev_offset inTree v(1) //\\\\\n              --(v(1),--(v(1),v(5))-->prev_offset)-->next_offset====v(5))])) **\n        (AbsEach range(#0,#(var_count))\n            (* Define the basic linked list connecting the watch variables\n               inside the clauses linked list *)\n            (AbsExistsT\n                ((Path((nth(v(4),v(5))), v(0), v(6), #sizeof_clause, ((#watch_next_offset++++v(5))::nil))) **\n                 (* Define the prev variable and the fact that if null we are at\n                    the head of the list *)\n                 (AbsAll TreeRecords(v(6))\n                     ([(--(v(6),v(7))--->(#watch_prev_offset++++v(5))====#0 //\\\\ nth(v(4),v(5))====v(6)) \\\\//\n                      (--(v(6),--(v(6),v(7))--->(#watch_prev_offset++++v(5)))--->(#watch_next_offset++++v(5)))====v(7)]))))) **\n        (AbsAll TreeRecords(v(0))\n            (* The current assignment is consistent with the clause *)\n           ((AbsExists range(#0,#(var_count))\n                ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\\n                    (nth(v(3),v(6))====#2 \\\\// nth(v(3),v(6))====#0)) \\\\//\n                  (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\\n                    (nth(v(3),v(6))====#1 \\\\// nth(v(3),v(6))====#0))])) **\n            (*\n             * make sure that if the watch_var field is non-zero (pointing to\n             * a variable) that watch_next and watch_prev put this clause into\n             * the linked list for the watch variable.\n             *)\n            (AbsAll range(#0,#(var_count))\n                ([\n                 (--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0) \\\\//\n                  ~~ (--(v(0),v(5))--->(#positive_lit_offset++++v(6))) \\\\//\n                  ~~ (--(v(0),v(5))--->(#negative_lit_offset++++v(6)))])) **\n            (AbsAll range(#0,#(var_count))\n                ([\n                 (~~(--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0) //\\\\\n                 (~~(--(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0) \\\\//\n                   nth(v(4),v(6))====v(5))) \\\\//\n                 (--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 //\\\\\n                  --(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0 //\\\\\n                  ~~(nth(v(4),v(6))====v(5)))])) **\n            (* Make sure there are precisely two watch variables per clause *)\n            (SUM(range(#0,#(var_count)),ite((--(v(0),v(5))--->(#watch_var_offset++++v(6))),(#1),(#0)),#2)) **\n            (* Watch variable invariant--case 1:  All but one variable in the\n               clause are assigned, any watch variable pointing to an assigned\n               variable is pointing to a variable that was assigned after all\n               other assigned variables in the clause.  Also, one of the two\n               watch variables points to the one unassigned variable *)\n            ((((SUM(range(#0,#(var_count)),\n              (((--(v(0),v(5))--->(#positive_lit_offset++++v(6))) \\\\// (--(v(0),v(5))--->(#negative_lit_offset++++v(6)))) //\\\\\n                   ite(nth(v(3),v(6))====#0,#1,#0)),\n               #1) **\n            (* The one unassigned literal is a watch--needs fixing? *)\n            (AbsAll range(#0,#(var_count))\n                 ([(#0<<<<--(v(0),v(5))--->(#watch_var_offset++++v(6)) //\\\\\n                   (nth(v(3),v(6))====#0) \\\\//\n                    ((#0<<<<nth(v(3),v(6))) \\\\// ((--(v(0),v(5))--->(#positive_lit_offset++++v(6))====#0 //\\\\\n                    --(v(0),v(5))--->(#negative_lit_offset++++v(6))====#0))))])) **\n            (AbsAll range(#0,#(var_count))\n                 (AbsAll range(#0,#(var_count))\n                     (([--(v(0),v(5))--->(#watch_var_offset++++v(6)) \\\\//\n                        ((((--(v(0),v(5))--->(#positive_lit_offset++++v(6)))====#0 //\\\\ (--(v(0),v(5))--->(#negative_lit_offset++++v(6))====#0)))) \\\\//\n                        ~~(--(v(0),v(5))--->(#watch_var_offset++++v(7))) \\\\//\n                        nth(v(3),v(6))====#0 \\\\// nth(v(3),v(7))====#0 \\\\// v(6)====v(7)]) *\\/*\n                      (AbsExists TreeRecords(v(2))\n                          (([--(v(2),v(8))-->stack_var_offset====v(7)]) **\n                           (AbsExists TreeRecords(find(v(2),v(8)))\n                              ([--(v(2),v(9))-->stack_var_offset====v(6)])))))))))) *\\/*\n            (* Watch variable invariant case 2: One of the assignments already\n               satisfies the clause, if a watch variable is assigned a value,\n               then that value must be a satisfying assignment or occured\n               after a satisfying assignment *)\n            ( (AbsExists range(#0,#(var_count))\n                ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#2) \\\\//\n                  (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#1)])) **\n              (AbsAll range(#0,#(var_count))\n                (([#0====nth(v(3),v(6))] *\\/* \n                  [--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0] **\n                  [#0 <<<< nth(v(3),v(6))]) *\\/*\n                  (AbsExists TreeRecords(v(2))\n                    (([--(v(2),v(7))-->stack_var_offset====v(6)]) **\n                      (AbsExists TreeRecords(find(v(2),v(7)))\n                        ([((#0 <<<< (--(v(0),v(5))--->(#positive_lit_offset++++ --(v(2),v(8))-->stack_var_offset))) //\\\\\n                          --(v(2),v(8))-->stack_val_offset====#2) \\\\//\n                        ((#0 <<<< --(v(0),v(5))--->(#negative_lit_offset++++ --(v(2),v(8))-->stack_var_offset)) //\\\\\n                         --(v(2),v(8))-->stack_val_offset====#1)]))))))) *\\/*\n\n         (* Watch variable invariant case 3: both watch variables point to\n            unassigned variables *)\n         (AbsAll range(#0,#(var_count))\n             ([--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 \\\\// nth(v(3),v(6))====#0]))\n))))))))).\n\nDefinition finalState (x : nat) : absStateBasic :=\n    (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (AbsExistsT (\n        TREE(!!clauses,v(0),#sizeof_clause,(#next_offset::nil)) **\n        TREE(!!assignments_to_do_head,v(1),#sizeof_assignment_stack,(#next_offset::nil)) **\n        TREE(!!stack,v(2),#sizeof_assignment_stack,(#next_offset::nil)) **\n        ARRAY(!!assignments,#var_count,v(3)) **\n        ARRAY(!!watches,#var_count,v(4)) **\n        (* Assertions that the stack and assignments array contain the same set\n           of assignments *)\n        (AbsAll TreeRecords(v(2))\n            ([nth(v(3),--(v(2),v(5))-->stack_var_offset)====--(v(2),v(5))-->stack_val_offset])) **\n        (AbsAll range(#0,#(var_count-1))\n            ([nth(v(3),v(5))====#0] *\\/*\n             AbsExists (TreeRecords(v(2)))\n                  ([(--(v(2),v(6))-->stack_var_offset====v(5) //\\\\\n                   --(v(2),v(6))-->stack_val_offset====nth(v(3),v(5)))]) )) **\n        (* Assertion defining the prev pointer in the assignments_to_do\n           doubly linked list *)\n        (AbsAll TreeRecords(v(1))\n            ([(--(v(1),v(5))-->prev_offset====#0 //\\\\ (!!assignments_to_do_head)====v(5)) \\\\//\n             (--(v(1),v(5))-->prev_offset inTree v(1) //\\\\\n              --(v(1),--(v(1),v(5))-->prev_offset)-->next_offset====v(5))])) **\n        (AbsEach range(#0,#(var_count-1))\n            (* Define the basic linked list connecting the watch variables\n               inside the clauses linked list *)\n        (Path((nth(v(4),v(5))), v(0), v(6), #sizeof_clause, ((#watch_next_offset++++v(5))::nil)) **\n         (* Define the prev variable and the fact that if null we are at\n            the head of the list *)\n         (AbsAll TreeRecords(v(6))\n             ([(--(v(6),v(7))--->(#watch_prev_offset++++v(5))====#0 //\\\\ nth(v(4),v(5))====v(6)) \\\\//\n               (--(v(6),--(v(6),v(7))--->(#watch_prev_offset++++v(5)))--->(#watch_next_offset++++v(5)))====v(7)]))) **\n    (* All variables assigned (if x is non-zero) *)\n    (if beq_nat x 0 then AbsEmpty else\n    (AbsAll range(#0,#(var_count-1))\n        ([nth(v(3),v(6))====#1 \\\\// nth(v(3),v(6))====#2]))) **\n    (AbsEach TreeRecords(v(0))\n        (* The current assignment is consistent with the clause *)\n        (AbsExists range(#0,#(var_count-1))\n             ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\\n                  (nth(v(3),v(6))====#2 \\\\// nth(v(3),v(6))====#0)) \\\\//\n               (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\\n                  (nth(v(3),v(6))====#1 \\\\// nth(v(3),v(6))====#0))])) **\n        (*\n         * make sure that if the watch_var field is non-zero (pointing to\n         * a variable) that watch_next and watch_prev put this clause into\n         * the linked list for the watch variable.\n         *)\n        (AbsAll range(#0,#(var_count-1))\n             ([\n              (~~(--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0) //\\\\\n               (~~(--(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0) \\\\//\n                nth(v(4),v(6))====v(5))) \\\\//\n              (--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 //\\\\\n               --(v(0),v(5))--->(#watch_prev_offset++++v(6))====#0 //\\\\\n               ~~(nth(v(4),v(6))====v(5)))]) **\n        (* Make sure there are precisely two watch variables per clause or all variables are watches*)\n        (SUM(range(#0,#(var_count-1)),ite((--(v(5),v(0))--->(#watch_var_offset++++v(6))),(#1),(#0)),#2) *\\/*\n         (AbsAll range(#0,#(var_count-1)) ([(--(v(5),v(0))--->(#watch_var_offset++++v(6)))]))) **\n        (* Watch variable invariant--case 1:  All but one variable in the\n           clause are assigned, any watch variable pointing to an assigned\n           variable is pointing to a variable that was assigned after all\n           other assigned variables in the clause.  Also, one of the two\n           watch variables points to the one unassigned variable *)\n        ((((SUM(range(#0,#(var_count-1)),\n            ((--(v(0),v(5))--->(#positive_lit_offset++++v(6))) //\\\\\n                 ite(nth(v(3),v(6))====#1,#1,#0))++++\n            ((--(v(0),v(5))--->(#negative_lit_offset++++v(6))) //\\\\ ite(nth(v(3),v(6))====#2,#1,#0)),\n            (* Needs fixing *)\n            #(var_count-1)) **\n         (* The one unassigned literal is a watch *)\n         (AbsAll range(#0,#(var_count-1))\n             ([#0<<<<--(v(0),v(5))--->(#watch_var_offset++++v(6)) \\\\//\n             nth(v(3),v(6))====#0])) **\n         (AbsAll range(#0,#(var_count-1))\n             (AbsAll range(#0,#(var_count-1))\n                 (([--(v(0),v(5))--->(#watch_var_offset++++v(6)) \\\\//\n                   ~~(--(v(0),v(5))--->(#watch_var_offset++++v(7))) \\\\//\n                   nth(v(3),v(6))====#0 \\\\// nth(v(3),v(7))====#0 \\\\// v(6)====v(7)]) *\\/*\n                  (AbsExists TreeRecords(v(2))\n                      ([--(v(2),v(8))-->stack_var_offset====v(6)]) **\n                      (AbsExists TreeRecords(find(v(2),v(8)))\n                          ([--(v(2),v(9))-->stack_var_offset====v(7)]))))))))) *\\/*\n         (* Watch variable invariant case 2: One of the assignments already\n            satisfies the clause, if a watch variable is assigned a value,\n            then that value must be a satisfying assignment or occured\n            after a satisfying assignment *)\n         ( (AbsExists range(#0,#(var_count-1))\n            ([(--(v(0),v(5))--->(#positive_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#2) \\\\//\n              (--(v(0),v(5))--->(#negative_lit_offset++++v(6)) //\\\\ nth(v(3),v(6))====#1)])) **\n            (AbsAll range(#0,#(var_count-1))\n              (([--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0]) *\\/*\n                (AbsExists TreeRecords(v(2))\n                  (([--(v(2),v(7))-->stack_var_offset====v(6)]) **\n                   (AbsExists find(v(2),v(7))\n                       ([((#0 <<<< (--(v(0),v(5))--->(#positive_lit_offset++++ --(v(2),v(8))-->stack_var_offset))) //\\\\\n                          --(v(2),v(8))-->stack_val_offset====#2) \\\\//\n                         ((#0 <<<< --(v(0),v(5))--->(#negative_lit_offset++++ --(v(2),v(8))-->stack_var_offset)) //\\\\\n                          --(v(2),v(8))-->stack_val_offset====#1)]))))))) *\\/*\n\n         (* Watch variable invariant case 3: both watch variables point to\n            unassigned variables *)\n         (AbsAll range(#0,#(var_count-1))\n             ([--(v(0),v(5))--->(#watch_var_offset++++v(6))====#0 \\\\// nth(v(3),v(6))====#0]))\n\n)))))))))).\n\n\nDefinition Program :=\n    backtrack ::= ANum(0);\n    WHILE ANum(1) DO\n        have_var ::= ANum(0);\n        IF (!backtrack) THEN\n            backtrack ::= A0;\n            (CLoad varx (!stack+++ANum(stack_var_offset)));\n            (CLoad valuex (!stack+++ANum(stack_val_offset)));\n            (CLoad ssss (!stack+++ANum(next_offset)));\n            DELETE !stack,ANum(sizeof_assignment_stack);\n            stack ::= !ssss;\n            have_var ::= A1;\n            (CStore (!assignments+++!varx) A0)\n        ELSE\n            valuex ::= A1;\n            iiii ::= A0;\n            WHILE (!iiii <<= ANum(var_count-1)) DO\n                (CLoad ssss (!assignments+++!iiii));\n                IF (!ssss===A0) THEN\n                    varx ::= !iiii;\n                    have_var ::= A1\n                ELSE\n                    SKIP\n                FI;\n                iiii ::= !iiii +++ A1\n            LOOP\n        FI;\n        IF (!have_var===A0) THEN\n            RETURN A1\n        ELSE\n            SKIP\n        FI;\n        NEW todo,ANum(sizeof_assignments_to_do);\n        (CStore (!todo+++ANum(next_offset)) (!assignments_to_do_head));\n        (CStore (!todo+++ANum(prev_offset)) A0);\n        IF (!assignments_to_do_tail===A0) THEN\n            assignments_to_do_tail ::= !todo\n        ELSE\n            (CStore (!assignments_to_do_head+++ANum(prev_offset)) (!todo))\n        FI;\n        assignments_to_do_head ::= !todo;\n        (CStore (!todo+++ANum(todo_var_offset)) (!varx));\n        (CStore (!todo+++ANum(todo_val_offset)) (!valuex));\n        (CStore (!todo+++ANum(todo_unit_offset)) A0);\n        WHILE !assignments_to_do_tail DO\n            (CLoad varx (!assignments_to_do_tail+++ANum(todo_var_offset)));\n            (CLoad valuex (!assignments_to_do_tail+++ANum(todo_val_offset)));\n            (CLoad prop (!assignments_to_do_tail+++ANum(todo_unit_offset)));\n            (CLoad ssss (!assignments_to_do_tail+++ANum(prev_offset)));\n            IF !ssss THEN\n                DELETE !ssss,(ANum(sizeof_assignments_to_do));\n                assignments_to_do_tail ::= !ssss;\n                (CStore (!ssss+++ANum(next_offset)) A0)\n            ELSE\n                assignments_to_do_head ::= A0;\n                assignments_to_do_tail ::= A0\n            FI;\n            (CLoad ssss (!assignments+++!varx));\n            IF !ssss THEN\n                WHILE (!assignments_to_do_head) DO\n                    (CLoad todo (!assignments_to_do_head +++ ANum(next_offset)));\n                    DELETE !assignments_to_do_head,ANum(sizeof_assignments_to_do);\n                    assignments_to_do_head ::= !todo\n                LOOP;\n                assignments_to_do_tail ::= A0;\n                (CLoad ssss (!stack +++ ANum(stack_prop_offset)));\n                (CLoad vvvv (!stack +++ ANum(stack_val_offset)));\n                WHILE (ALand (!stack) (ALor (!ssss) (!vvvv===A2))) DO\n                    (CLoad kkkk (!stack +++ ANum(next_offset)));\n                    (CLoad vvvv (!stack +++ ANum(stack_var_offset)));\n                    (CStore (!assignments +++ !vvvv) A0);\n                    DELETE !stack,ANum(sizeof_assignment_stack);\n                    stack ::= !kkkk;\n                    (CLoad ssss (!stack +++ ANum(stack_prop_offset)));\n                    (CLoad vvvv (!stack +++ ANum(stack_val_offset)))\n                LOOP;\n                IF (!stack===A0) THEN\n                    RETURN A0\n                ELSE\n                    SKIP\n                FI;\n                (CStore (!stack +++ ANum(stack_val_offset)) A2);\n                (CLoad vvvv (!stack +++ ANum(stack_var_offset)));\n                (CStore (!assignments +++ !vvvv) A2);\n                backtrack ::= A1\n            ELSE\n                (CStore (!assignments+++!varx) (!valuex));\n                NEW ssss,ANum(sizeof_assignment_stack);\n                (CStore (!ssss+++ANum(next_offset)) (!stack));\n                stack ::= !ssss;\n                (CStore (!ssss+++ANum(stack_var_offset)) (!varx));\n                (CStore (!ssss+++ANum(stack_val_offset)) (!valuex));\n                (CStore (!ssss+++ANum(stack_prop_offset)) (!prop));\n                (CLoad clause (!watches+++!varx));\n                WHILE (!clause) DO\n                    (CLoad nc (!clause+++ANum(watch_next_offset)+++!varx));\n                    (CLoad ssss (!clause+++ANum(negative_lit_offset)+++!varx));\n                    (CLoad vvvv (!clause+++ANum(positive_lit_offset)+++!varx));\n                    IF (ALor (ALand (!valuex === A2) (!ssss))\n                             (ALand (!valuex === A1) (!vvvv))) THEN\n                        has_non_watch ::= A0;\n                        skip ::= A0;\n                        jjjj ::= A0;\n                        WHILE (!jjjj <<= ANum(var_count-1)) DO\n                            jjjj ::= !jjjj +++ A1;\n                            (CLoad ssss (!clause+++ANum(positive_lit_offset)+++!jjjj));\n                            (CLoad vvvv (!assignments+++!jjjj));\n                            IF (ALand (!ssss) (!vvvv===A2)) THEN\n                                skip ::= A1\n                            ELSE\n                                SKIP\n                            FI;\n                            (CLoad ssss (!clause+++ANum(negative_lit_offset)+++!jjjj));\n                            IF (ALand (!ssss) (!vvvv===A1)) THEN\n                                skip ::= A1\n                            ELSE\n                                SKIP\n                            FI;\n                            (CLoad ssss (!clause+++ANum(watch_var_offset)+++!jjjj));\n                            IF (ALand (!vvvv) (!ssss===A0)) THEN\n                                non_watch ::= !jjjj;\n                                has_non_watch ::= A1\n                            ELSE\n                                SKIP\n                            FI\n                        LOOP;\n                        IF (!skip) THEN\n                            SKIP\n                        ELSE\n                            SKIP;\n                            IF (!has_non_watch) THEN\n                                (CLoad ssss (!watches +++ !non_watch));\n                                (CStore (!clause +++ ANum(watch_next_offset) +++ !non_watch) (!ssss));\n                                (CStore (!clause +++ ANum(watch_var_offset) +++ !non_watch) A1);\n                                IF (!ssss) THEN\n                                    (CStore (!ssss +++ ANum(watch_prev_offset) +++ !non_watch) (!clause))\n                                ELSE\n                                    SKIP\n                                FI;\n                                (CStore (!watches +++ !non_watch) (!clause));\n                                (CStore (!clause +++ ANum(watch_var_offset) +++ !varx) A0);\n                                (CLoad ssss (!clause +++ ANum(watch_prev_offset) +++ !varx));\n                                (CLoad vvvv (!clause +++ ANum(watch_next_offset) +++ !varx));\n                                IF (!ssss) THEN\n                                    (CStore (!ssss +++ ANum(watch_next_offset) +++ !varx) (!vvvv))\n                                ELSE\n                                    (CStore (!watches +++ !varx) (!vvvv))\n                                FI;\n                                IF (!vvvv) THEN\n                                    (CStore (!vvvv +++ ANum(watch_prev_offset) +++ !varx) (!ssss))\n                                ELSE\n                                    SKIP\n                                FI\n                            ELSE\n                                kkkk ::= A0;\n                                WHILE (!kkkk <<= ANum(var_count-1)) DO\n                                    (CLoad ssss (!clause +++ ANum(watch_var_offset) +++ !kkkk));\n                                    (CLoad jjjj (!assignments +++ !kkkk));\n                                    IF (ALand (!ssss) (!jjjj)) THEN\n                                        vvvv ::= !kkkk;\n                                        (CLoad ssss (!clause +++ ANum(positive_lit_offset) +++ !vvvv));\n                                        IF (!ssss) THEN\n                                            val ::= A2\n                                        ELSE\n                                            SKIP\n                                        FI;\n                                        (CLoad ssss (!clause +++ ANum(negative_lit_offset) +++ !vvvv));\n                                        IF (!ssss) THEN\n                                            val ::= A1\n                                        ELSE\n                                            SKIP\n                                        FI\n                                    ELSE\n                                        SKIP\n                                    FI;\n                                    kkkk ::= !kkkk +++ A1\n                                LOOP;\n                                NEW todo,ANum(sizeof_assignments_to_do);\n                                (CStore (!todo +++ ANum(next_offset)) (!assignments_to_do_head));\n                                (CStore (!todo +++ ANum(prev_offset)) A0);\n                                IF (!assignments_to_do_tail) THEN\n                                    (CStore (!assignments_to_do_head +++ ANum(prev_offset)) (!todo))\n                                ELSE\n                                    assignments_to_do_tail ::= !todo\n                                FI;\n                                assignments_to_do_head ::= !todo;\n                                (CStore (!todo +++ ANum(todo_var_offset)) (!vvvv));\n                                (CStore (!todo +++ ANum(todo_val_offset)) (!val));\n                                (CStore (!todo +++ ANum(todo_unit_offset)) A1)\n                            FI\n                        FI\n                    ELSE\n                        SKIP\n                    FI;\n                    clause ::= !nc\n                LOOP\n            FI\n        LOOP\n    LOOP.\n\nSet Printing Depth 200.\n\nTheorem mergeTheorem1Aux8 : forall eee v v0 v1 v2 l v4 x x0 e n,\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, empty_heap) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4), #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)),\n           #2)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n  (forall x1 : Value,\n        NatValue 0 = x1 \\/\n        NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n            [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n           [--( v(2), v(6) )---> (#6 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n          (eee, empty_heap)) ->\n  In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n  NatValue 0 = nth (eee varx) l NoValue ->\n  e <> 0 ->\n  NatValue e =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else @NatValue unit 1) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsExists range(#0, #4)\n             (([--( v(2), v(6) )---> (#2 ++++ v(8))] **\n               [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #2] *\\/*\n               [--( v(2), v(6) )---> (#6 ++++ v(8))] **\n               [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #1]) **\n              AbsAll range(#0, #4)\n                (([#0 ==== nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))] *\\/*\n                  [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n                  [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))]) *\\/*\n                 ([!!(varx) ==== v(9)] **\n                  ([#0 <<<< --( v(2), v(6) )---> (#2 ++++ !!(varx))] **\n                   [!!(valuex) ==== #2] *\\/*\n                   [#0 <<<< --( v(2), v(6) )---> (#6 ++++ !!(varx))] **\n                   [!!(valuex) ==== #1]) *\\/*\n                  AbsExists TreeRecords(v(0))\n                    ([!!(varx) ==== v(9)] **\n                     ([#0 <<<<\n                       --( v(2), v(6)\n                       )---> (#2 ++++ nth(find(v(0), v(10)), #3))] **\n                      [nth(find(v(0), v(10)), #4) ==== #2] *\\/*\n                      [#0 <<<<\n                       --( v(2), v(6)\n                       )---> (#6 ++++ nth(find(v(0), v(10)), #3))] **\n                      [nth(find(v(0), v(10)), #4) ==== #1]))) *\\/*\n                 AbsExists TreeRecords(v(0))\n                   (AbsExists TreeRecords(find(v(0), v(10)))\n                      ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                       ([#0 <<<<\n                         --( v(2), v(6)\n                         )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                        [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                        [#0 <<<<\n                         --( v(2), v(6)\n                         )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                        [nth(find(v(0), v(11)), #4) ==== #1]))))))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n  (S n = @mapSum unit eq_unit (@basicEval unit) eee\n           (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n           (@NatValue unit 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil)\n           (--( v(2), v(6) )---> (#2 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #2 \\\\//\n           --( v(2), v(6) )---> (#6 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #1)) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (AbsExists range(#0, #4)\n        (([--( v(2), v(6) )---> (#2 ++++ v(8))] ** [nth(v(4), v(8)) ==== #2] *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(8))] ** [nth(v(4), v(8)) ==== #1]) **\n         AbsAll range(#0, #4)\n           (([#0 ==== nth(v(4), v(9))] *\\/*\n             [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n             [#0 <<<< nth(v(4), v(9))]) *\\/*\n            AbsExists TreeRecords(v(0))\n              (AbsExists TreeRecords(find(v(0), v(10)))\n                 ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                  ([#0 <<<<\n                    --( v(2), v(6) )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                   [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                   [#0 <<<<\n                    --( v(2), v(6) )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                   [nth(find(v(0), v(11)), #4) ==== #1]))))))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof. admit.\n    (*intros.\n\n    inversion H6. subst. clear H6. inversion H15. subst. clear H15. inversion H6. subst. clear H6.\n    Transparent basicEval. simpl in H12. Opaque basicEval. inversion H12. subst. clear H12.\n\n    inversion H10. subst. clear H10.\n    eapply concreteComposeEmpty in H16. inversion H16. subst. clear H16.\n    simpl in H12. simpl in H13.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H14. Opaque basicEval. inversion H14. subst. clear H14.\n\n    eapply mapSumExists in H7.\n    inversion H7. subst. clear H7.\n    inversion H6. subst. clear H6.\n    simplifyHyp H10. simplifyHyp H10.\n\n    eapply RSExists. Transparent basicEval. simpl. Opaque basicEval. reflexivity. reflexivity.\n    eapply ex_intro. split. apply H7.\n\n    eapply RSCompose.\n    Focus 3. eapply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n    simpl. apply H10.\n\n    simpl in H17.\n\n    eapply RSAll. Transparent basicEval. simpl. Opaque basicEval. reflexivity. reflexivity.\n    intros. simpl. apply H17 in H6.\n\n    destruct x3; hypSimp.\n    remember (beq_nat n0 (eee varx)).\n    destruct b.\n\n    eapply RSOrComposeL. eapply RSOrComposeL.\n    eapply RSR. Transparent basicEval. simpl. Opaque basicEval.\n    apply beq_nat_eq in Heqb. subst.\n    rewrite <- H3. reflexivity.\n\n    apply BTStatePredicate. omega. unfold empty_heap. reflexivity.\n\n    eapply removeReplace in H6. Focus 2. instantiate (1 := !!varx). instantiate (1 := v(9)).\n    instantiate (1 := (v\n          :: v0\n             :: v1\n                :: v2\n                   :: ListValue l\n                      :: v4 :: x :: x0 :: x1 :: NatValue n0 :: nil)). instantiate (1 := eee).\n    Transparent basicEval. simpl. rewrite <- Heqb. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H6. subst. clear H6.\n    eapply RSOrComposeL.\n    eapply dumpVar in H16. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H16.\n    eapply dumpVar2. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl.\n    apply H16.\n\n    subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H16. subst. clear H16.\n    apply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    apply RSOrComposeL. apply RSOrComposeL.\n\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    remember (beq_nat (eee varx) n0). destruct b. apply beq_nat_eq in Heqb0. subst.\n    rewrite <- beq_nat_refl in Heqb. inversion Heqb.\n    inversion H19. elim H11. reflexivity.\n    subst.\n    inversion H16. subst. clear H16.\n    inversion H20. subst. clear H20.\n    inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H22. inversion H22. subst. clear H22.\n    inversion H18. subst. clear H18.\n    Transparent basicEval. simpl in H22. Opaque basicEval.\n    remember (beq_nat (eee varx) n0).\n    destruct b. eapply beq_nat_eq in Heqb0. subst. rewrite <- beq_nat_refl in Heqb. inversion Heqb.\n    inversion H22. subst. clear H22. elim H13. reflexivity.\n\n    subst. eapply RSOrComposeR.\n    eapply dumpVar in H15. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H15.\n    eapply dumpVar2. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl.\n    apply H15.\n\n    inversion H6. subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    Transparent basicEval. simpl in H18. Opaque basicEval. inversion H18.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    destruct x; inversion H19.\n    destruct (findRecord n0 v1); inversion H6.\n    subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H16. subst. clear H16.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19.\n    subst. clear H15.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H14.\n    inversion H19. subst. clear H19. inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H21. inversion H21. subst. clear H21.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    inversion H21.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H19. subst. clear H19.\n    inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    inversion H21. subst. clear H21.\n    inversion H6. subst. clear H6.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n    inversion H19. subst. clear H19.\n    Transparent basicEval. simpl in H23.\n    destruct x3; inversion H23.\n    destruct (findRecord n0 v); inversion H6.\n    destruct (nth 3 l1 NoValue); inversion H22.\n\n    inversion H6. subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    Transparent basicEval. simpl in H18. Opaque basicEval. inversion H18.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    destruct x; inversion H19.\n    destruct (findRecord n0 v1); inversion H6.\n    subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H16. subst. clear H16.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19.\n    subst. clear H15.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H14.\n    inversion H19. subst. clear H19. inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H21. inversion H21. subst. clear H21.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    inversion H21.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H19. subst. clear H19.\n    inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    inversion H21. subst. clear H21.\n    inversion H6. subst. clear H6.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n    inversion H19. subst. clear H19.\n    Transparent basicEval. simpl in H23.\n    destruct x3; inversion H23.\n    destruct (findRecord n0 v); inversion H6.\n    destruct (nth 3 l0 NoValue); inversion H22.\n\n    inversion H6. subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    Transparent basicEval. simpl in H18. Opaque basicEval. inversion H18.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    destruct x; inversion H19.\n    destruct (findRecord n0 v1); inversion H6.\n    subst. clear H6.\n    inversion H16. subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H16. subst. clear H16.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19.\n    subst. clear H15.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H14.\n    inversion H19. subst. clear H19. inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H21. inversion H21. subst. clear H21.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    inversion H21.\n    subst. clear H16.\n    inversion H15. subst. clear H15.\n    inversion H19. subst. clear H19.\n    inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    inversion H21. subst. clear H21.\n    inversion H6. subst. clear H6.\n    inversion H15. subst. clear H15.\n    eapply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n    inversion H19. subst. clear H19.\n    Transparent basicEval. simpl in H23.\n    destruct x3; inversion H23.\n    destruct (findRecord n0 v); inversion H6.\n    destruct (nth 3 l0 NoValue); inversion H22.\nQed.\n\nTheorem mergeTheorem1Aux7 : forall eee v v0 v1 v2 l v4 x x0 e,\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (SUM(range(#0, #4), #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)),\n           #2)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n  (forall x1 : Value,\n        NatValue 0 = x1 \\/\n        NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n            [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n           [--( v(2), v(6) )---> (#6 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n          (eee, empty_heap)) ->\n  In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n  @NatValue unit 0 = nth (eee varx) l NoValue ->\n  e <> 0 ->\n  @NatValue unit e =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else NatValue 1) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       (AbsExists range(#0, #4)\n             (([--( v(2), v(6) )---> (#2 ++++ v(8))] **\n               [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #2] *\\/*\n               [--( v(2), v(6) )---> (#6 ++++ v(8))] **\n               [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #1]) **\n              AbsAll range(#0, #4)\n                (([#0 ==== nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))] *\\/*\n                  [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n                  [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))]) *\\/*\n                 ([!!(varx) ==== v(9)] **\n                  ([#0 <<<< --( v(2), v(6) )---> (#2 ++++ !!(varx))] **\n                   [!!(valuex) ==== #2] *\\/*\n                   [#0 <<<< --( v(2), v(6) )---> (#6 ++++ !!(varx))] **\n                   [!!(valuex) ==== #1]) *\\/*\n                  AbsExists TreeRecords(v(0))\n                    ([!!(varx) ==== v(9)] **\n                     ([#0 <<<<\n                       --( v(2), v(6)\n                       )---> (#2 ++++ nth(find(v(0), v(10)), #3))] **\n                      [nth(find(v(0), v(10)), #4) ==== #2] *\\/*\n                      [#0 <<<<\n                       --( v(2), v(6)\n                       )---> (#6 ++++ nth(find(v(0), v(10)), #3))] **\n                      [nth(find(v(0), v(10)), #4) ==== #1]))) *\\/*\n                 AbsExists TreeRecords(v(0))\n                   (AbsExists TreeRecords(find(v(0), v(10)))\n                      ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                       ([#0 <<<<\n                         --( v(2), v(6)\n                         )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                        [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                        [#0 <<<<\n                         --( v(2), v(6)\n                         )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                        [nth(find(v(0), v(11)), #4) ==== #1])))))) \n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n  0 =\n         @mapSum unit eq_unit (@basicEval unit) eee\n           (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n           (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil)\n           (--( v(2), v(6) )---> (#2 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #2 \\\\//\n           --( v(2), v(6) )---> (#6 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #1) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n        (AbsAll TreeRecords(v(0))\n            ([--(v(0),v(8))-->stack_var_offset <<<< #var_count]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n        (AbsAll TreeRecords(v(0))\n             ([nth(v(4),--(v(0),v(8))-->stack_var_offset)====--(v(0),v(8))-->stack_val_offset]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (AbsAll range(#0, #4)\n        ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n         [nth(v(4), v(8)) ==== #0]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof.\n    intros.\n\n    eapply RSAll. Transparent basicEval. simpl. Opaque basicEval. reflexivity. reflexivity.\n    intros. simpl.\n    destruct x1; hypSimp.\n    remember (beq_nat n (eee varx)).\n    destruct b.\n    apply beq_nat_eq in Heqb. subst.\n    eapply RSOrComposeR. eapply RSR.\n    Transparent basicEval. simpl. Opaque basicEval. rewrite <- H3. simpl.\n    reflexivity. apply BTStatePredicate. intro X. inversion X. unfold empty_heap. reflexivity.\n\n    inversion H6. subst. clear H6. inversion H18. subst. clear H18.\n    inversion H6. subst. clear H6. Transparent basicEval. simpl in H15. inversion H15. subst. clear H15.\n    simpl in H13.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    inversion H16. subst. clear H16. Transparent basicEval. simpl in H17. Opaque basicEval.\n    inversion H17. subst. clear H17. simpl in H20.\n    apply H20 in H11. clear H20.\n\n    eapply removeReplace in H11. Focus 2.\n    instantiate (1 := (!!varx)). instantiate (1 := v(9)). instantiate (1 := (v\n          :: v0\n             :: v1\n                :: v2\n                   :: ListValue l :: v4 :: x :: x0 :: x1 :: NatValue n :: nil)).\n    instantiate (1 := eee). Transparent basicEval. simpl. Opaque basicEval.\n    rewrite <- Heqb. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H11. subst. clear H11.\n    inversion H17. subst. clear H17.\n    eapply RSOrComposeR.\n    eapply dumpVar in H16. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H16.\n    eapply expressionSubGRSRL. apply H16. simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n    eapply RSR. Transparent basicEval. simpl. reflexivity. apply BTStatePredicate.\n    omega. unfold empty_heap. reflexivity.\n\n    subst. clear H17.\n    inversion H16. subst. clear H16.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    eapply RSOrComposeL.\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H13.\n    apply H13.\n\n    subst. clear H11.\n    inversion H17. subst. clear H17.\n    inversion H16. subst. clear H16.\n    inversion H17. subst. clear H17.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n    Transparent basicEval. simpl in H20. Opaque basicEval.\n    remember (beq_nat (eee varx) n). destruct b.\n    apply beq_nat_eq in Heqb0. subst.\n    erewrite <- beq_nat_refl in Heqb. inversion Heqb.\n    inversion H20. elim H11. reflexivity.\n\n    subst. clear H16.\n    inversion H17. subst. clear H17.\n    inversion H19. subst. clear H19.\n    inversion H6. subst. clear H6.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H21. inversion H21. subst. clear H21.\n    inversion H17. subst. clear H17.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    remember (beq_nat (eee varx) n). destruct b.\n    apply beq_nat_eq in Heqb0. subst.\n    erewrite <- beq_nat_refl in Heqb. inversion Heqb.\n    inversion H21. elim H13. reflexivity.\n\n    subst. clear H17.\n    inversion H16. subst. clear H16.\n    inversion H19. subst. clear H19.\n    inversion H6. subst. clear H6.\n    Transparent basicEval. simpl in H14. Opaque basicEval.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H18. Opaque basicEval. simpl in H21.\n    inversion H21. subst. clear H21.\n    inversion H6. subst. clear H6.\n    destruct x2; hypSimp.\n    inversion H16. subst. clear H16.\n    apply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n\n    eapply mapSumNeg in H7. Focus 2.\n    instantiate (1 :=\n        @absEval unit eq_unit (@basicEval unit) eee (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n                 nth(find(v(0),v(8)),#3)).\n    eapply subRangeSet in H13. Focus 2. apply H18. Focus 2. apply H11. Focus 2. apply H14.\n    inversion H9. subst. clear H9.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    rewrite H14 in H21. inversion H21. subst. clear H21. simpl in H24.\n    apply H24 in H13.\n    Transparent basicEval. simpl.\n    inversion H13. subst. clear H13. Transparent basicEval. simpl in H22. Opaque basicEval.\n    destruct (match\n               match x3 with\n               | NatValue x => findRecord x v\n               | ListValue _ => NoValue\n               | NoValue => NoValue\n               | OtherValue _ => NoValue\n               end\n             with\n             | NatValue _ => NoValue\n             | ListValue l => nth 3 l NoValue\n             | NoValue => NoValue\n             | OtherValue _ => NoValue\n             end); hypSimp.\n    destruct n1. left. reflexivity. destruct n1. right. left. reflexivity.\n    destruct n1. right. right. left. reflexivity. destruct n1. right. right. right. left. reflexivity.\n    inversion H22. elim H9. reflexivity.\n    Opaque absEval. simpl in H7. Transparent absEval.\n\n    eapply subBoundVar in H7.\n    Focus 2. instantiate (3 := 8). Opaque absEval. simpl. Transparent absEval. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    simplifyHyp H7. simplifyHyp H7.\n\n    inversion H10. subst. clear H10. Transparent basicEval. simpl in H21. Opaque basicEval.\n    rewrite H14 in H21. inversion H21. subst. clear H21.\n\n    eapply expressionSubRSLR in H7. Focus 2. eapply H24.\n\n    eapply subRangeSet in H13. Focus 2. apply H18. Focus 2. apply H11. apply H13. apply H14.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H7. subst. clear H7.\n    eapply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n    inversion H20. subst. clear H20.\n    inversion H22. subst. clear H22.\n    eapply concreteComposeEmpty in H25. inversion H25. subst. clear H25.\n    inversion H16.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply expressionSubRSNeg in H10. Focus 2. apply H23. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H10. subst. clear H10. Transparent basicEval. simpl in H30. Opaque basicEval.\n    inversion H30. subst. clear H30. elim H7. reflexivity.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply expressionSubRSLR in H23. Focus 2. apply H20. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H23. subst. clear H23. Transparent basicEval. simpl in H30. Opaque basicEval.\n    inversion H30. subst. clear H30. elim H7. reflexivity.\n\n    subst. clear H20.\n    inversion H22. subst. clear H22.\n    eapply concreteComposeEmpty in H25. inversion H25. subst. clear H25.\n    inversion H17. subst. clear H17.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply dumpVar in H10. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H10.\n    eapply expressionSubRSNeg in H10. Focus 2. apply H23. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H10. subst. clear H10. Transparent basicEval. simpl in H25. Opaque basicEval.\n    inversion H25. subst. clear H25. elim H7. reflexivity.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply expressionSubRSLR in H23. Focus 2. apply H20. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H23. subst. clear H23. Transparent basicEval. simpl in H30. Opaque basicEval.\n    inversion H30. subst. clear H30. elim H7. reflexivity.*)\nQed.\n\nTheorem mergeTheorem1Aux6 : forall e v v0 v1 v2 l v4 x x0 eee,\n  In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n  e <> 0 ->\n  NatValue e =\n      (if match eee varx with\n          | 0 => false\n          | 1 => false\n          | 2 => false\n          | 3 => false\n          | S (S (S (S _))) => true\n          end\n       then NatValue 0\n       else @NatValue unit 1) ->\n  NatValue 0 = nth (eee varx) l NoValue ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll range(#0, #4)\n             ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n              [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0]))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n         length l=4 ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (AbsAll range(#0, #4)\n        ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n         [nth(v(4), v(8)) ==== #0]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof. admit.\n    (*intros.\n\n    inversion H3. subst. clear H3. Transparent basicEval. simpl in H9. Opaque basicEval.\n    inversion H9. subst. clear H9.\n\n    eapply RSAll. Transparent basicEval. simpl. Opaque basicEval. simpl. reflexivity. reflexivity.\n    intros.\n    apply H12 in H3. clear H12.\n    simpl in H3. simpl.\n\n    inversion H3. subst. clear H3.\n    eapply RSOrComposeL. apply H10.\n\n    subst. clear H3.\n    inversion H10. subst. clear H10. Transparent basicEval. simpl in H11. Opaque basicEval.\n\n    destruct x1.\n\n    remember (beq_nat n (eee varx)).\n    destruct b.\n\n    apply beq_nat_eq in Heqb. subst.\n    rewrite nth_replace_same in H11.\n\n    inversion H4. subst. clear H4.\n    inversion H9. subst. clear H9. Transparent basicEval. simpl in H10. Opaque basicEval.\n    destruct (eee valuex). simpl in H10. inversion H10.\n\n    elim H4. reflexivity.\n\n    simpl in H11. inversion H11. subst. clear H11. elim H4. reflexivity.\n\n    subst. clear H4.\n\n    inversion H9. subst. clear H9. Transparent basicEval. simpl in H10. Opaque basicEval.\n    destruct (eee valuex). simpl in H10. inversion H10.\n    elim H4. reflexivity.\n\n    simpl in H11. inversion H11. subst. clear H11. elim H4. reflexivity.\n\n    reflexivity. rewrite H5.\n    destruct (eee varx). omega. destruct n. omega. destruct n. omega. destruct n. omega.\n    inversion H1. subst. elim H0. reflexivity.\n\n    apply beq_nat_neq in Heqb.\n\n    rewrite nth_replace_diff in H11.\n    inversion H11. subst. clear H11.\n\n    eapply RSOrComposeR.\n    eapply RSR. Transparent basicEval. simpl. Opaque basicEval.\n\n    rewrite <- H3. reflexivity. eapply BTStatePredicate. apply H6.\n\n    unfold empty_heap. simpl. reflexivity.\n    apply Heqb.\n\n    inversion H11. inversion H11. inversion H11.\nQed.\n\nTheorem mergeTheorem1Aux5 : forall eee v v0 v1 v2 l v4 x x0 e,\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, empty_heap) ->\n  In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n  e <> 0 ->\n  NatValue e =\n      (if match eee varx with\n          | 0 => false\n          | 1 => false\n          | 2 => false\n          | 3 => false\n          | S (S (S (S _))) => true\n          end\n       then NatValue 0\n       else @NatValue unit 1) ->\n  NatValue 0 = nth (eee varx) l NoValue ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n      ([nth(v(4), v(7)) ==== #2] *\\/* [nth(v(4), v(7)) ==== #0]) *\\/*\n      [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n      ([nth(v(4), v(7)) ==== #1] *\\/* [nth(v(4), v(7)) ==== #0]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) \n     (eee, empty_heap).\nProof.\n        Transparent basicEval.\n        intros.\n        destructState. hypSimp. inversion H; subst; clear H; hypSimp.\n        inversion H8. subst. clear H8.\n        eapply concreteComposeEmpty in H10. inversion H10; subst; clear H10.\n        eapply RSOrComposeL.\n        eapply RSCompose. apply H5.\n        inversion H6. subst. clear H6. destructState. hypSimp.\n        destruct x0; hypSimp.\n        remember (beq_nat n (eee varx)). destruct b. apply beq_nat_eq in Heqb. subst.\n        eapply RSOrComposeR. eapply RSR. simpl. reflexivity.\n        rewrite <- H3. simpl.\n        eapply BTStatePredicate. intro X. inversion X. instantiate (1 := (eee,empty_heap)).\n        unfold empty_heap. reflexivity.\n        apply beq_nat_neq in Heqb.\n        erewrite nth_replace_diff in HeqH.\n        apply RSOrComposeL. eapply RSR. simpl. reflexivity.\n        rewrite <- HeqH. simpl.\n        apply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity. apply Heqb.\n\n        subst. clear H6. destructState. hypSimp.\n        destruct x0; hypSimp.\n        remember (beq_nat n (eee varx)). destruct b. apply beq_nat_eq in Heqb. subst.\n        eapply RSOrComposeR. eapply RSR. simpl. reflexivity.\n        rewrite <- H3. simpl.\n        eapply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity.\n         apply beq_nat_neq in Heqb.\n        erewrite nth_replace_diff in HeqH.\n        apply RSOrComposeR. eapply RSR. Transparent basicEval. simpl. reflexivity.\n        rewrite <- HeqH. simpl.\n        apply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity. apply Heqb.\n        apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        inversion H8. subst. clear H8.\n        eapply concreteComposeEmpty in H10. inversion H10; subst; clear H10.\n        eapply RSOrComposeR.\n        eapply RSCompose. apply H5. \n        inversion H6. subst. clear H6. destructState. hypSimp.\n        destruct x0; hypSimp.\n        remember (beq_nat n (eee varx)). destruct b. apply beq_nat_eq in Heqb. subst.\n        eapply RSOrComposeR. eapply RSR. simpl. reflexivity.\n        rewrite <- H3. simpl.\n        eapply BTStatePredicate. intro X. inversion X. instantiate (1 := (eee,empty_heap)).\n        unfold empty_heap. reflexivity.\n        apply beq_nat_neq in Heqb.\n        erewrite nth_replace_diff in HeqH.\n        apply RSOrComposeL. eapply RSR. Transparent basicEval. simpl. reflexivity.\n        rewrite <- HeqH. simpl.\n        apply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity. apply Heqb.\n\n        subst. clear H6. Transparent basicEval. destructState.\n        hypSimp.\n        destruct x0; hypSimp.\n        remember (beq_nat n (eee varx)). destruct b. apply beq_nat_eq in Heqb. subst.\n        eapply RSOrComposeR. eapply RSR. simpl. reflexivity.\n        rewrite <- H3. simpl.\n        eapply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity.\n         apply beq_nat_neq in Heqb.\n        erewrite nth_replace_diff in HeqH.\n        apply RSOrComposeR. eapply RSR. Transparent basicEval. simpl. reflexivity. Opaque basicEval.\n        rewrite <- HeqH. simpl.\n        apply BTStatePredicate. intro X. inversion X.\n        unfold empty_heap. reflexivity. apply Heqb.\n        apply concreteComposeEmpty. split. reflexivity. reflexivity.\n        Opaque basicEval.\nQed.\n\nTheorem mergeTheorem1Aux4b : forall v v0 v1 v2 l v4 x x0 eee x1 x2,\n  (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n            [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n           [--( v(2), v(6) )---> (#6 ++++ v(8))])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n         (eee, empty_heap)) ->\n  (In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil)) ->\n  (@NatValue unit 1 =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else NatValue 1)) ->\n  (@NatValue unit 0 = nth (eee varx) l NoValue) ->\n  (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n             (AbsAll range(#0, #4)\n                      (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)]))))\n         ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n  (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n           [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n         (*([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n          [#0 ==== nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n          [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n          [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])*)\n         ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n  (false =\n       validPredicate\n         (@absEval unit eq_unit (@basicEval unit) eee\n            (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n            (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx))))) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n  length l = 4 ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (SUM(range(#0, #4),\n          #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)) //\\\\\n          ((--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n            --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n           nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0), \n          #1)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, fun _ : nat => None) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#1 ====\n            (v(8) ++++ v(9)) ++++\n            (#0 <<<< --( v(2), v(6) )---> (#10 ++++ !!(varx)) //\\\\\n             (~~ --( v(2), v(6) )---> (#2 ++++ !!(varx)) //\\\\\n              ~~ --( v(2), v(6) )---> (#6 ++++ !!(varx)) \\\\//\n              #0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), !!(varx))))])\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 ==== v(9)])\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 ==== v(8)])\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, empty_heap) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(!!(varx) ++++ #1, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           (~~ --( v(2), v(6) )---> (#2 ++++ v(10)) //\\\\\n            ~~ --( v(2), v(6) )---> (#6 ++++ v(10)) \\\\//\n            #0 <<<< nth(v(4), v(10))), #0))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n  @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           (~~ --( v(2), v(6) )---> (#2 ++++ v(10)) //\\\\\n            ~~ --( v(2), v(6) )---> (#6 ++++ v(10)) \\\\//\n            #0 <<<< nth(v(4), v(10))),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ !!(varx)) //\\\\\n           (~~ --( v(2), v(6) )---> (#2 ++++ !!(varx)) //\\\\\n            ~~ --( v(2), v(6) )---> (#6 ++++ !!(varx)))))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (AbsAll range(#0, #4)\n        ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n         [nth(v(4), v(8)) ==== #0]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof.\n    intros.\n\n    assert (forall x1 : Value,\n      In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n      @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n        (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n          [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n         [--( v(2), v(6) )---> (#6 ++++ v(8))])\n        (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n        (eee, empty_heap)).\n    apply H.\n\n    eapply expressionSubEvalEval in H.\n    Focus 2. instantiate (1 := v(8)). instantiate (2 := eee). instantiate (2 := (!!varx)).\n    Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n    Focus 2.\n    destruct (eee varx). simpl. left. reflexivity. destruct n. simpl. right. left. reflexivity.\n    destruct n. simpl. right. right. left. reflexivity. destruct n. simpl. right. right. right. left.\n    reflexivity. inversion H1.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply expressionNotEqualZero3 in H. Focus 2. apply H5. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. reflexivity. Focus 2. simpl. reflexivity.\n\n    simplifyHyp H.\n\n    assert (@absEval unit eq_unit (@basicEval unit) eee\n                     (v :: v0 :: v1 :: v2 :: ListValue l\n                        :: v4 :: x :: x0 :: NatValue (eee varx) :: nil)\n              (~~ --( v(2), v(6) )---> (#2 ++++ !!(varx)) //\\\\\n               ~~ --( v(2), v(6) )---> (#6 ++++ !!(varx)))=NatValue 0).\n    inversion H. subst. clear H.\n    erewrite expressionSubGRSNeg. Focus 2. apply H19. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n    simpl. reflexivity.\n\n    erewrite expressionSubGRSNeg. Focus 2. apply H19. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    erewrite <- simplifyAbsEval. Focus 2. compute. reflexivity.\n    Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n\n    simpl. reflexivity.\n\n    eapply expressionSubEval in H13.\n\n    Focus 2. instantiate (4 := 0). rewrite <- H15. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H13.\n\n    eapply resolveSum8x10 in H13.\n    Focus 2. intros. eapply H14. apply H16. Focus 2. simpl. reflexivity. Focus 2.\n    instantiate (1 := (#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n         #0 <<<< nth(v(4), v(10)))).\n    simpl. intros.\n    simplifyHyp H17. simplifyHyp H17.\n    inversion H17. subst. clear H17. inversion H22. subst. clear H22.\n    eapply expressionSubGRSLR. apply H21. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply RSEmpty. unfold empty_heap. reflexivity.\n    subst. clear H22.\n    eapply expressionSubGRSNeg1. apply H21. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply RSEmpty. unfold empty_heap. reflexivity.\n    subst. clear H17.\n    eapply expressionSubGRSNeg1. apply H22. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply RSEmpty. unfold empty_heap. reflexivity.\n\n    eapply sumAllConv in H13.\n    simplifyHyp H13. simplifyHyp H13. simplifyHyp H13. simplifyHyp H13.\n\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H13.\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity.\n    Focus 2. simpl. reflexivity. simpl in H13. simpl.\n    unfold empty_heap. apply H13.\n\n    Transparent basicEval. simpl. reflexivity. Opaque basicEval.\nGrab Existential Variables.\n    apply (fun a b c d e f => a=a). apply (fun a b c => a=a).\nQed.\n\nTheorem mergeTheorem1Aux4 : forall v v0 v1 v2 l v4 x x0 eee,\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (SUM(range(#0, #4), #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)),\n           #2)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, empty_heap) ->\n        (forall x1 : Value,\n        NatValue 0 = x1 \\/\n        NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n            [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n           [--( v(2), v(6) )---> (#6 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil) (eee, empty_heap)) ->\n      In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n      NatValue 1 =\n      (if match eee varx with\n          | 0 => false\n          | 1 => false\n          | 2 => false\n          | 3 => false\n          | S (S (S (S _))) => true\n          end\n       then @NatValue unit 0\n       else NatValue 1) ->\n       NatValue 0 = nth (eee varx) l NoValue ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n           (SUM(range(#0, #4),\n           (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n            --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n           nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0, \n           #1))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n     (forall x1 : Value,\n        In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll range(#0, #4)\n                      (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)]))))\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n           x1 :: nil) (eee, empty_heap)) ->\n     (forall x1 : Value,\n        In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n           [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n           x1 :: nil) (eee, empty_heap)) ->\n     false =\n         validPredicate\n           (@absEval unit eq_unit (@basicEval unit) eee\n              (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n              (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx)))) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n     length l=4 ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (AbsAll range(#0, #4)\n        ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n         [nth(v(4), v(8)) ==== #0]))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof.\n    intros.\n\n    eapply andSum8 in H4. Focus 2. apply H6. Focus 2. simpl. reflexivity. Focus 2.\n    Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n\n    simplifyHyp H4. simplifyHyp H4. simplifyHyp H4.\n    simplifyHyp H.\n\n    eapply sumDiff in H. Focus 2. eapply H4. Focus 2. simpl. reflexivity.\n\n    simplifyHyp H. simplifyHyp H.\n\n    eapply unfoldSum in H. Focus 2. simpl. reflexivity. Focus 2. instantiate (1 := (!!varx)). simpl. reflexivity.\n    Focus 2. Transparent basicEval. simpl. Opaque basicEval.\n    destruct (eee varx). reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n    destruct n. reflexivity. destruct n. reflexivity. inversion H2.\n\n    simpl in H. inversion H. subst. clear H. inversion H11. subst. clear H11.\n    inversion H. subst. clear H. inversion H11. subst. clear H11. inversion H. subst. clear H.\n    inversion H13. subst. clear H13.\n    eapply concreteComposeEmpty in H16. inversion H16. subst. clear H16.\n    eapply concreteComposeEmpty in H18. inversion H18. subst. clear H18.\n    simpl in H14.\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n           ([#1 ====\n            (v(8) ++++ v(9)) ++++\n            (#0 <<<< --( v(2), v(6) )---> (#10 ++++ !!(varx)))])\n           (v\n         :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n        (eee, empty_heap)).\n    eapply removeReplaceSame in H14. Focus 2. instantiate (1 := !!(varx)). instantiate (1 := v(4)).\n    simpl. reflexivity. Focus 2. Transparent basicEval. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Opaque basicEval.\n\n    inversion H8. subst. clear H8.\n    eapply expressionSubRSLR in H14. Focus 2. apply H16. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H14. simplifyHyp H14. simplifyHyp H14.\n    apply H14.\n    subst. clear H8.\n    eapply expressionSubRSLR in H14. Focus 2. apply H16. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H14. simplifyHyp H14. simplifyHyp H14.\n    apply H14.\n    rewrite H9. destruct (eee varx). omega. destruct n. omega. destruct n. omega. destruct n. omega.\n    inversion H2.\n\n    simplifyHyp H11. simplifyHyp H12.\n\n    eapply expressionNotEqualZero1 in H. Focus 2. apply H7. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. reflexivity. Focus 2. simpl. reflexivity.\n\n    simplifyHyp H. simplifyHyp H.\n\n    inversion H. subst. clear H.\n    eapply concreteComposeEmpty in H19. inversion H19. subst. clear H19.\n\n    eapply expressionSubRSRL in H11. Focus 2. apply H16. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply expressionSubRSRL in H12. Focus 2. apply H15. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply foldSum in H12. Focus 2. apply H11. Focus 2. simpl. reflexivity.\n    simplifyHyp H12.\n\n    eapply expressionSubEval in H12.\n    Focus 2. instantiate (1 := (nth(v(4), !!(varx)))). instantiate (2 := eee).\n    instantiate (1 := (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)).\n    Transparent basicEval. simpl. rewrite <- H3. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H12.\n\n    eapply mergeTheorem1Aux4b. apply H0. apply H1. apply H2. apply H3. apply H5. apply H6.\n    apply H7. apply H8. apply H9. apply H4. apply H14. apply H16. apply H15. apply H11.\n    apply H12.*)\nQed.\n\nTheorem mergeTheorem1Aux3 : forall eee l v v0 v1 v2 v4 x x0 x1 x2,\n        (match eee varx with\n          | 0 => true\n          | 1 => true\n          | 2 => true\n          | 3 => true\n          | S (S (S (S _))) => false\n          end=true) ->\n        NatValue 0 = nth (eee varx) l NoValue ->\n        true =\n         validPredicate\n           (@absEval unit eq_unit (@basicEval unit) eee\n              (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n              (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx)))) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n                       (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)])))\n         (v\n          :: v0\n             :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n         (eee, empty_heap) ->\n        length l=4 ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n        @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n          [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n         [nth(v(4), v(8)) ==== #0]) *\\/* [nth(v(4), v(9)) ==== #0]) *\\/*\n       [v(8) ==== v(9)]) *\\/*\n      AbsExists TreeRecords(v(0))\n        (AbsExists TreeRecords(find(v(0), v(10)))\n           ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n            [nth(find(v(0), v(11)), #3) ==== v(8)])))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n     (eee, empty_heap).\nProof. admit.\n    (*intros.\n\n    inversion H2. subst. clear H2.\n    inversion H9. subst. clear H9.\n    inversion H8. subst. clear H8.\n    inversion H9. subst. clear H9.\n    inversion H8. subst. clear H8.\n\n    eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL.\n    apply H9.\n\n    subst. clear H8.\n    eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeR.\n    apply H9.\n\n    subst. clear H9.\n\n    eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeR.\n\n    remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee\n                             (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n                             ( (!!varx) ==== (v(8)) ))).\n    destruct b.\n\n    eapply expressionSubRL in H8. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H8. subst. clear H8. Transparent basicEval. simpl in H10. Opaque basicEval.\n\n    erewrite nth_replace_same in H10.\n\n    inversion H4. subst. clear H4. inversion H8. subst. clear H8. Transparent basicEval. simpl in H9.\n    Opaque basicEval.\n\n    destruct (eee valuex). simpl in H9. inversion H9. elim H4. reflexivity.\n    simpl in H10. inversion H10. elim H4. reflexivity.\n\n    inversion H8. subst. clear H8. Transparent basicEval. simpl in H15.\n    Opaque basicEval.\n\n    destruct (eee valuex). simpl in H15. inversion H15. elim H5. reflexivity.\n    simpl in H10. inversion H10. elim H5. reflexivity. reflexivity.\n\n    rewrite H3.\n    destruct (eee varx). omega. destruct n. omega. destruct n. omega. destruct n. omega.\n    inversion H.\n\n    eapply removeReplace in H8. Focus 6. instantiate (1 := (!!varx)). instantiate (1 := v(8)).\n    simpl. reflexivity. Focus 2. rewrite validPredicateSymmetry. rewrite Heqb. reflexivity.\n\n    apply H8. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n\n    subst. clear H8.\n\n    eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeR.\n\n    remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee\n                             (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n                             ( (!!varx) ==== (v(9)) ))).\n    destruct b.\n\n    eapply expressionSubRL in H9. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H9. subst. clear H9. Transparent basicEval. simpl in H10. Opaque basicEval.\n\n    erewrite nth_replace_same in H10.\n\n    inversion H4. subst. clear H4. inversion H8. subst. clear H8. Transparent basicEval. simpl in H9.\n    Opaque basicEval.\n\n    destruct (eee valuex). simpl in H9. inversion H9. elim H4. reflexivity.\n    simpl in H10. inversion H10. elim H4. reflexivity.\n\n    inversion H8. subst. clear H8. Transparent basicEval. simpl in H15.\n    Opaque basicEval.\n\n    destruct (eee valuex). simpl in H15. inversion H15. elim H5. reflexivity.\n    simpl in H10. inversion H10. elim H5. reflexivity. reflexivity.\n\n    rewrite H3.\n    destruct (eee varx). omega. destruct n. omega. destruct n. omega. destruct n. omega.\n    inversion H.\n\n    eapply removeReplace in H9. Focus 6. instantiate (1 := (!!varx)). instantiate (1 := v(9)).\n    simpl. reflexivity. Focus 2. rewrite validPredicateSymmetry. rewrite Heqb. reflexivity.\n\n    apply H9. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n\n    eapply RSOrComposeL. eapply RSOrComposeR. apply H8.\n\n    subst.\n\n    inversion H9. subst. clear H9.\n    inversion H10. subst. clear H10.\n\n    inversion H9. subst. clear H9.\n\n    apply concreteComposeEmpty in H12. inversion H12. subst. clear H12.\n\n    apply RSOrComposeL. apply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeL.\n    apply RSOrComposeR.\n\n    eapply expressionSubGRSRL. apply H8. simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n\n    eapply expressionSubGRSRL. apply H7.  simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n\n    eapply expressionSubGRL. rewrite H1. reflexivity.  simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity. simpl. reflexivity.\n\n    eapply RSR. Transparent basicEval. simpl.\n\n reflexivity. eapply BTStatePredicate. omega. Opaque basicEval.\n    simpl. unfold empty_heap. reflexivity.\n\n    subst. clear H10.\n\n    eapply RSOrComposeL. eapply RSOrComposeL. eapply RSOrComposeR.\n\n    inversion H9. subst. clear H9. inversion H12. subst. clear H12. inversion H5. subst. clear H5.\n    inversion H7. subst. clear H7.\n\n    apply concreteComposeEmpty in H14. inversion H14. subst. clear H14.\n\n    eapply expressionSubGRSRL. apply H10. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n\n    Transparent basicEval. eapply RSR. simpl. rewrite <- H0. simpl. reflexivity.\n    apply BTStatePredicate. omega. unfold empty_heap. reflexivity.\n\n    subst. eapply RSOrComposeR. apply H10.\n\n    Opaque basicEval.\nQed.\n\nTheorem mergeTheorem1Aux2 : forall v v0 v1 v2 l v4 x x0 x1 eee,\n    true = validPredicate\n           (@absEval unit eq_unit (@basicEval unit) eee\n              (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n              (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!varx))) ->\n\n    @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n          [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n          [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n          [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n    (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil) (eee, empty_heap) ->\n    NatValue 0 = nth (eee varx) l NoValue ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n    length l=4 ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: nil) \n          (eee, empty_heap) ->\n    @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) \n     ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n      [nth(v(4), v(8)) ==== #0] *\\/*\n      [#0 <<<< nth(v(4), v(8))] *\\/*\n      [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n      [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n      (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil) (eee, empty_heap).\nProof.\n    intros.\n\n    inversion H0. subst. clear H0. inversion H9. subst. clear H9.\n    apply concreteComposeEmpty in H11. inversion H11. subst. clear H11.\n\n    remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n                                      ((!!varx)====v(8)))).\n    destruct b.\n\n    eapply expressionSubRL in H6. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply expressionSubRL in H6. Focus 2. rewrite H. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H6. subst. clear H6. Transparent basicEval. simpl in H11. Opaque basicEval.\n    inversion H11. elim H5. reflexivity.\n\n    eapply removeReplace in H7. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply RSOrComposeL. eapply RSCompose. apply H6. apply H7. apply concreteComposeEmpty.\n    split. reflexivity. reflexivity.\n\n    subst.\n\n    eapply expressionSubRL in H9. Focus 2. rewrite H. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply RSOrComposeR.\n\n    inversion H9. subst. clear H9.\n\n    remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n                                      ((!!varx)====v(8)))).\n    destruct b.\n\n    eapply expressionSubGRL. rewrite Heqb. reflexivity. simpl. reflexivity.\n    simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n\n    eapply RSOrComposeR.\n    eapply dumpVar2. Focus 2. instantiate (1 := 7). simpl. reflexivity. simpl.\n    eapply dumpVar2. Focus 2. instantiate (1 := 7). simpl. reflexivity. simpl.\n    apply H4.\n    Focus 2. simpl. reflexivity. simpl. reflexivity.\n\n    eapply removeReplace in H10. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply RSOrComposeL. apply H10.\n\n    subst.\n\n    eapply RSOrComposeR. apply H10.\nQed.\n\nTheorem mergeTheorem1Aux1 : forall eee v v0 v1 v2 l v4 x x0,\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4),\n           (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n            --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n           (nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0), #1))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n     (forall x1, In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n           [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 ::nil) (eee, empty_heap)) ->\n   true = validPredicate\n           (@absEval unit eq_unit (@basicEval unit) eee\n              (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n              (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx)))) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap) ->\n     ble_nat 4 (eee varx)=false ->\n     length l = 4 ->\n     NatValue 0 = nth (eee varx) l NoValue ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: nil) \n          (eee, empty_heap) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     (SUM(range(#0, #4),\n      (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n       --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\ nth(v(4), v(8)) ==== #0, \n      #1))\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n     (eee, empty_heap).\nProof.\n    intros.\n\n    eapply unfoldSum in H.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. instantiate (1 := (!!varx)) in H.\n    simpl in H.\n    destructState1.\n\n    simplifyHyp H8.\n    simplifyHyp H7.\n\n    eapply unfoldSum.\n    simpl. reflexivity. simpl. reflexivity. instantiate (1 := !!(varx)).\n\n    Transparent basicEval. simpl. Opaque basicEval.\n    simpl in H3. destruct (eee varx). reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n    destruct n. reflexivity. inversion H3.\n    eapply RSExistsU. eapply ex_intro. eapply RSExistsU. eapply ex_intro. simpl.\n    eapply RSCompose. apply H8. eapply RSCompose. apply H7.\n\n    clear H8. clear H7.\n\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n          ([#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: NatValue (eee varx) :: nil)\n         (eee, empty_heap)).\n    eapply H0.\n    destruct (eee varx). simpl. left. reflexivity. destruct n. simpl. right. left. reflexivity.\n    destruct n. right. right. left. reflexivity. destruct n. right. right. right. left. reflexivity.\n    simpl in H3. inversion H3.\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ (!!varx))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), (!!varx)) ==== #0] *\\/*\n          ([#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), (!!varx))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ (!!varx)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ (!!varx)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: NatValue (eee varx) :: nil)\n         (eee, empty_heap)).\n    eapply removeQuantVar. apply H. instantiate (2 := 8). simpl. reflexivity. simpl. reflexivity.\n\n    eapply expressionSubRSLR in H12. Focus 2. apply H10. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    eapply expressionSubRSLR in H12. Focus 2. apply H9. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H12.\n    eapply expressionSubGRSLR. apply H9. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    eapply expressionSubGRSLR. apply H10. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    eapply simplifyEquiv2.\n    compute. reflexivity. apply H12.\n    apply concreteComposeEmpty. split. reflexivity. reflexivity.\n    apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n\n    Transparent basicEval. simpl. Opaque basicEval. destruct (eee varx).\n    reflexivity. destruct n. reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n    destruct n. reflexivity. simpl in H3. inversion H3.*)\nQed.\n\nTheorem mergeTheorem1Aux9b : forall v v0 v1 v2 l v4 x x0 eee e x1 x2 x3,\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n        ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n         ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n         [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n         ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n        (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n        (eee, empty_heap) ->\n      (forall x1 : Value,\n       NatValue 0 = x1 \\/\n       NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(8))])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n         (eee, empty_heap)) ->\n      In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n      NatValue 0 = nth (eee varx) l NoValue ->\n      e <> 0 ->\n      NatValue e =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else @NatValue unit 1) ->\n       (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (AbsAll range(#0, #4)\n                      (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)]))))\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n       (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n          [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n          [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n          [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n         ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n       true =\n       validPredicate\n         (@absEval unit eq_unit (@basicEval unit) eee\n            (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n            (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx)))) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll TreeRecords(v(0))\n             ([~~ (!!(varx) ==== nth(find(v(0), v(6)), #3))]))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(!!(varx) ++++ #1, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           ((--( v(2), v(6) )---> (#2 ++++ v(10)) \\\\//\n             --( v(2), v(6) )---> (#6 ++++ v(10))) //\\\\\n            nth(v(4), v(10)) ==== #0), v(9)))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n  ([#1 ==== v(8) ++++ v(9)])\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           nth(v(4), v(10)) ==== #0, #1))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (((((([--( v(2), v(6) )---> (#10 ++++ !!(varx))] *\\/*\n               [--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n               [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0]) *\\/*\n              [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n             [nth(replacenth(v(4), !!(varx), !!(valuex)), !!(varx)) ==== #0]) *\\/*\n            [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ==== #0]) *\\/*\n           [!!(varx) ==== v(9)]) *\\/*\n          ([!!(varx) ==== v(9)] ** [!!(varx) ==== (!!(varx))] *\\/*\n           AbsExists TreeRecords(v(0))\n             ([!!(varx) ==== v(9)] **\n              [nth(find(v(0), v(10)), #3) ==== (!!(varx))])) *\\/*\n          AbsExists TreeRecords(v(0))\n            (AbsExists TreeRecords(find(v(0), v(10)))\n               ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                [nth(find(v(0), v(11)), #3) ==== (!!(varx))])))\n         ((v\n           :: v0\n              :: v1\n                 :: v2\n                    :: ListValue l\n                       :: v4 :: x :: x0 :: NatValue (eee varx) :: nil) ++\n          x3 :: nil) (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n   ([#0 <<<< nth(v(4), v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n          (eee, empty_heap) ->\n    In x3 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n    length l = 4 ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n  ([--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n      [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0])\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: nil) \n     (eee, empty_heap).\nProof. admit.\n    (*intros.\n\n    clear H. clear H5. clear H11. clear H12. clear H13.\n\n    inversion H14. subst. clear H14.\n    inversion H13. subst. clear H13.\n    inversion H14. subst. clear H14.\n    inversion H13. subst. clear H13.\n    inversion H14. subst. clear H14.\n    inversion H13. subst. clear H13.\n\n    eapply expressionSubRL in H14. Focus 2. rewrite H7. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H14. subst. clear H14. Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n\n    subst. clear H13.\n    eapply dumpVar in H14. Focus 2. instantiate (1 := 7). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H14.\n    eapply dumpVar in H14. Focus 2. instantiate (1 := 7). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H14.\n    eapply dumpVar in H14. Focus 2. instantiate (1 := 7). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H14.\n    apply H14.\n\n    subst. clear H14.\n    simpl in H13.\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H13.\n    eapply expressionSubRSNeg in H16. Focus 2. apply H13. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    inversion H16. subst. clear H16.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n\n    subst. clear H13.\n\n    simpl in H14. eapply removeReplaceSame in H14. Focus 2. instantiate (1 := !!(varx)).\n    instantiate (1 := v(4)). simpl. reflexivity. Focus 2. Transparent basicEval. simpl. reflexivity.\n    Opaque basicEval. Focus 2. Transparent basicEval. simpl. reflexivity.\n    Focus 2. rewrite H18. destruct (eee varx). omega. destruct n. omega. destruct n. omega.\n    destruct n. omega. inversion H4. subst. elim H3. reflexivity.\n\n    inversion H8. subst. clear H8.\n    eapply expressionSubRSLR in H14. Focus 2. apply H13. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    inversion H14. subst. clear H14.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n    subst. clear H8.\n    eapply expressionSubRSLR in H14. Focus 2. apply H13. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    inversion H14. subst. clear H14.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n\n    subst. clear H14.\n\n    remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee\n            (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n            (v(8) ==== (!!(varx))))).\n    destruct b.\n    simpl in H13.\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H13.\n    eapply expressionSubLR in H13. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    simpl in H13. eapply removeReplaceSame in H13. Focus 2. instantiate (1 := !!(varx)).\n    instantiate (1 := v(4)). simpl. reflexivity. Focus 2. Transparent basicEval. simpl. reflexivity.\n    Opaque basicEval. Focus 2. Transparent basicEval. simpl. reflexivity.\n    Focus 2. rewrite H18. destruct (eee varx). omega. destruct n. omega. destruct n. omega.\n    destruct n. omega. inversion H4. subst. elim H3. reflexivity.\n\n    inversion H8. subst. clear H8.\n    eapply expressionSubRSLR in H13. Focus 2. apply H14. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n    subst. clear H8.\n    eapply expressionSubRSLR in H13. Focus 2. apply H14. Focus 2. simpl. reflexivity. Focus 2. simpl.\n    reflexivity. Focus 2. simpl. reflexivity.\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19. elim H5. reflexivity.\n\n\n    eapply dumpVar in H13. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H13.\n    eapply removeReplace in H13. Focus 2. rewrite Heqb. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    eapply expressionSubRSLR in H15. Focus 2. apply H13. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H15. subst. clear H15. Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. elim H5. reflexivity.\n\n    subst. clear H13.\n\n    eapply dumpVar in H14. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H14.\n\n    eapply expressionSubRSRL in H15. Focus 2. apply H14. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H15. subst. clear H15. Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19; subst; clear H19. rewrite <- H2 in H. simpl in H. inversion H. subst.\n    elim H5. reflexivity.\n\n    subst. clear H14.\n\n    inversion H13; subst; clear H13.\n    inversion H14; subst; clear H14.\n\n    inversion H13; subst; clear H13.\n\n    eapply concreteComposeEmpty in H20. inversion H20; subst; clear H20.\n\n    eapply dumpVar in H11. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H11.\n\n    eapply expressionSubRSRL in H15. Focus 2. apply H11. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H15. subst. clear H15. Transparent basicEval. simpl in H20. Opaque basicEval.\n    inversion H20; subst; clear H20. rewrite <- H2 in H. simpl in H. inversion H. subst.\n    elim H5. reflexivity.\n\n    inversion H13. subst. clear H13.\n    Transparent basicEval. simpl in H12. Opaque basicEval. inversion H12. subst. clear H12.\n    inversion H20; subst; clear H20.\n    inversion H; subst; clear H.\n    inversion H12; subst; clear H12.\n    eapply concreteComposeEmpty in H22. inversion H22; subst; clear H22.\n\n    eapply dumpVar in H14. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H11.\n\n    eapply expressionSubRSRL in H15. Focus 2. apply H14. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n\n    inversion H15. subst. clear H15. Transparent basicEval. simpl in H22. Opaque basicEval.\n    inversion H22; subst; clear H22. rewrite <- H2 in H. simpl in H. inversion H. subst.\n    elim H12. reflexivity.\n\n    inversion H14; subst; clear H14. Transparent basicEval. simpl in H12. Opaque basicEval.\n    inversion H20; subst; clear H20.\n    inversion H; subst; clear H.\n    inversion H11; subst; clear H11.\n    Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H22; subst; clear H22. inversion H; subst; clear H. destruct x4; inversion H19; subst; clear H19.\n    inversion H10; subst; clear H10.\n    Transparent basicEval. simpl in H21. Opaque basicEval.\n    inversion H13; subst; clear H13.\n    eapply concreteComposeEmpty in H25. inversion H25; subst; clear H25.\n    simpl in H20. simpl in H24. simpl in H19.\n\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 6). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 6). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 6). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 6). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n    eapply dumpVar in H20. Focus 2. instantiate (1 := 6). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H20.\n\n    eapply reverse in H20.\n    eapply expressionSubRSNeg in H20. Focus 2. eapply H24.\n    rewrite H21 in H12. inversion H12; subst; clear H12.\n    eapply  subRangeSet. apply H14. apply H11. apply H5. apply H21.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity.\n\n    inversion H20. subst. clear H20. Transparent basicEval. simpl in H25. Opaque basicEval.\n    inversion H25. subst. clear H25. elim H10. reflexivity.\n\n Qed.\n\n\nTheorem mergeTheorem1Aux9 : forall v v0 v1 v2 l v4 x x0 eee e,\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n          ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n         (eee, empty_heap) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4), #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)),\n           #2)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n        (forall x1 : Value,\n        NatValue 0 = x1 \\/\n        NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n            [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n           [--( v(2), v(6) )---> (#6 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n          (eee, empty_heap)) ->\n       In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       NatValue 0 = nth (eee varx) l NoValue ->\n       e <> 0 ->\n       NatValue e =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else @NatValue unit 1) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4),\n           (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n            --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n           nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0, \n           #1)) (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n          (eee, empty_heap) ->\n        (forall x1 : Value,\n         In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n         @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (AbsAll range(#0, #4)\n                      (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)]))))\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n           x1 :: nil) (eee, empty_heap)) ->\n       (forall x1 : Value,\n        In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n         @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n           [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n           [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n           x1 :: nil) (eee, empty_heap)) ->\n        (true =\n         validPredicate\n           (@absEval unit eq_unit (@basicEval unit) eee\n              (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n              (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx))))) ->\n         (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n         (eee, empty_heap)) ->\n         @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       (AbsAll TreeRecords(v(0))\n              ([~~ (!!(varx) ==== nth(find(v(0), v(6)), #3))]))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil)\n          (eee, empty_heap) ->\n   length l = 4 ->\n   @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n     ([--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n      [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0])\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: nil) \n     (eee, empty_heap).\nProof.\n    intros.\n\n    eapply andSum8 in H6. Focus 2. apply H8. Focus 2. simpl. reflexivity. Focus 2.\n    Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n\n    simplifyHyp H6.\n\n    eapply unfoldSum in H6. Focus 2. simpl. reflexivity. Focus 2. instantiate (1 := (!!varx)). simpl. reflexivity.\n    Focus 2. Transparent basicEval. simpl. Opaque basicEval.\n    destruct (eee varx). reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n    destruct n. reflexivity. destruct n. reflexivity. inversion H5. subst. clear H5. elim H4. reflexivity.\n\n    simpl in H6. inversion H6. subst. clear H6. inversion H15. subst. clear H15.\n    inversion H6. subst. clear H6. inversion H15. subst. clear H15. inversion H6. subst. clear H6.\n    inversion H17. subst. clear H17.\n    eapply concreteComposeEmpty in H20. inversion H20. subst. clear H20.\n    eapply concreteComposeEmpty in H22. inversion H22. subst. clear H22.\n    simpl in H15. simpl in H16. simpl in H18.\n    simplifyHyp H15. simplifyHyp H16.\n    eapply foldSum in H16. Focus 2. apply H15. Focus 2. simpl. reflexivity.\n    eapply expressionSubRL in H15. Focus 2. rewrite H9. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H15.\n    eapply expressionSubRL in H16. Focus 2. rewrite H9. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H16.\n    eapply expressionSubRL in H18. Focus 2. rewrite H9. reflexivity. Focus 2. simpl. reflexivity.\n    Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simplifyHyp H18.\n    eapply expressionSubRSRL in H16. Focus 2. apply H18. Focus 2. simpl. reflexivity. Focus 2.\n    simpl. reflexivity. Focus 2. simpl. reflexivity.\n    eapply resolveSum8x10 in H16. Focus 2. intros. eapply H1. instantiate (1 := NatValue 0::NatValue 1::NatValue 2::NatValue 3::nil) in H6. simpl in H6. apply H6.\n    Focus 2. simpl. reflexivity.\n    Focus 2. simpl. intros. instantiate (1 := ((#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10))) //\\\\\n                                               (nth(v(4), v(10)) ==== #0))).\n    simplifyHyp H14. simplifyHyp H14.\n    inversion H14. subst. clear H14.\n    inversion H22. subst. clear H22.\n    eapply expressionSubGRSLR. apply H21. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity. eapply RSEmpty. unfold empty_heap. reflexivity.\n    subst. clear H22.\n    eapply expressionSubGRSOr1. apply H21. simpl. reflexivity. simpl. reflexivity.\n    instantiate (3 := (--( v(2), v(6) )---> (#6 ++++ v(10)))).\n    instantiate (1 := (nth(v(4), v(10)) ==== #0)). simpl. reflexivity.\n    simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity. eapply RSEmpty. unfold empty_heap. reflexivity.\n    subst. clear H14.\n    eapply expressionSubGRSOr2. apply H22. simpl. reflexivity. simpl. reflexivity.\n    instantiate (3 := (--( v(2), v(6) )---> (#2 ++++ v(10)))).\n    instantiate (1 := (nth(v(4), v(10)) ==== #0)). simpl. reflexivity.\n    simpl. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity. eapply RSEmpty. unfold empty_heap. reflexivity.\n    Focus 2. Transparent basicEval. simpl. reflexivity.\n\n    eapply sumDiff in H0. Focus 2.\n    eapply dumpVar in H16. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H16.\n    eapply dumpVar in H16. Focus 2. instantiate (1 := 8). simpl. reflexivity. Focus 2. simpl. reflexivity.\n    simpl in H16.\n    apply H16. Focus 2. simpl. reflexivity.\n    simplifyHyp H0.\n \n    eapply sumExists in H0.\n    inversion H0. subst. clear H0. Transparent basicEval. simpl in H19. Opaque basicEval.\n    inversion H19. subst. clear H19.\n    inversion H22. subst. clear H22. inversion H0. subst. clear H0.\n    simplifyHyp H14. inversion H14. subst. clear H14.\n    eapply concreteComposeEmpty in H23. inversion H23. subst. clear H23.\n\n    assert(\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (AbsAll range(#0, #4)\n            (((((([--( v(2), v(6) )---> (#10 ++++ (!!varx))] *\\/*\n                  [--( v(2), v(6) )---> (#2 ++++ (!!varx)) ==== #0] **\n                  [--( v(2), v(6) )---> (#6 ++++ (!!varx)) ==== #0]) *\\/*\n                 [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                [nth(replacenth(v(4), !!(varx), !!(valuex)), (!!varx)) ==== #0]) *\\/*\n               [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ==== #0]) *\\/*\n              [(!!varx) ==== v(9)]) *\\/*\n             ([(!!(varx)) ==== v(9)] ** [(!!(varx)) ==== (!!(varx))] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([(!!(varx)) ==== v(9)] **\n                 [nth(find(v(0), v(10)), #3) ==== (!!(varx))])) *\\/*\n             AbsExists TreeRecords(v(0))\n               (AbsExists TreeRecords(find(v(0), v(10)))\n                  ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                   [nth(find(v(0), v(11)), #3) ==== (!!(varx))]))))\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: NatValue (eee varx) :: nil)\n         (eee, empty_heap)\n    ).\n    eapply removeQuantVar. eapply H7.\n    destruct (eee varx). left. reflexivity. destruct n. right. left. reflexivity. destruct n.\n    right. right. left. reflexivity. destruct n. right. right. right. left. reflexivity.\n    inversion H5. subst. clear H5. elim H4. reflexivity.\n    instantiate (2 := 8). simpl. reflexivity. simpl. reflexivity.\n    inversion H0. subst. clear H0.\n    Transparent basicEval. simpl in H22. Opaque basicEval. inversion H22. subst. clear H22.\n    assert (In x3 (NatValue 0::NatValue 1::NatValue 2::NatValue 3::nil)). apply H6.\n    eapply H25 in H6. clear H25.\n\n    eapply mergeTheorem1Aux9b.\n    apply H. apply H1. apply H2. apply H3. apply H4. apply H5. apply H7. apply H8. apply H9. apply H10.\n    apply H11. apply H12. apply H15. apply H18. apply H16. apply H6. apply H20. apply H19. apply H0.\n    apply H13.*)\nQed.\n\nTheorem mergeTheorem1 : forall bbb eee hhh, length bbb=6 ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       ((AbsEmpty **\n           [#0 ==== nth(v(4), !!(varx))] **\n           AbsEmpty **\n           [!!(stack) ==== (!!(ssss))] **\n           [!!(ssss) ==== nth(v(0), #0)] **\n           AbsEmpty **\n           [!!(backtrack) ==== #0] **\n           [v(1)] **\n           AbsEmpty **\n           AbsEmpty **\n           AbsEmpty **\n           (([!!(varx) <<<< #4] ** AbsEmpty) **\n            (([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2]) ** AbsEmpty) **\n            AbsEmpty **\n            AbsAll TreeRecords(v(0))\n              ([~~ !!(varx) ==== nth(find(v(0), v(6)), #3)]) ** AbsEmpty) **\n           AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])) **\n           AbsEmpty **\n           AbsEmpty **\n           AbsAll TreeRecords(v(2))\n             (AbsExists range(#0, #4)\n                (([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n                  [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0])) **\n                 AbsAll range(#0, #4)\n                   (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                     [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n                    [--( v(2), v(6) )---> (#6 ++++ v(8))]) **\n                 AbsAll range(#0, #4)\n                   ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n                    ([#0 <<<< --( v(2), v(6) )---> (#18 ++++ v(8))] *\\/*\n                     [nth(v(5), v(8)) ==== v(6)]) *\\/*\n                    ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#18 ++++ v(8)) ==== #0]) **\n                    [~~ nth(v(5), v(8)) ==== v(6)]) **\n                 SUM(range(#0, #4),\n                 #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)), \n                 #2) **\n                 (SUM(range(#0, #4),\n                  (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n                   --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n                  nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0,\n                  #1) **\n                  AbsAll range(#0, #4)\n                    ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0] *\\/*\n                     [#0 <<<<\n                      nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n                     [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) **\n                  AbsAll range(#0, #4)\n                    (AbsAll range(#0, #4)\n                       (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                             [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                             [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                            [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                            #0]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                           #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                        ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(9)] **\n                            [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                              [nth(find(v(0), v(11)), #3) ==== v(8)])))) *\\/*\n                  AbsExists range(#0, #4)\n                    (([--( v(2), v(6) )---> (#2 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #2] *\\/*\n                      [--( v(2), v(6) )---> (#6 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #1]) **\n                     AbsAll range(#0, #4)\n                       (([#0 ====\n                          nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))] *\\/*\n                         [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n                         [#0 <<<<\n                          nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))]) *\\/*\n                        ([!!(varx) ==== v(9)] **\n                         ([#0 <<<< --( v(2), v(6) )---> (#2 ++++ !!(varx))] **\n                          [!!(valuex) ==== #2] *\\/*\n                          [#0 <<<< --( v(2), v(6) )---> (#6 ++++ !!(varx))] **\n                          [!!(valuex) ==== #1]) *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(9)] **\n                            ([#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#2 ++++ nth(find(v(0), v(10)), #3))] **\n                             [nth(find(v(0), v(10)), #4) ==== #2] *\\/*\n                             [#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#6 ++++ nth(find(v(0), v(10)), #3))] **\n                             [nth(find(v(0), v(10)), #4) ==== #1]))) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                              ([#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                               [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                               [#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                               [nth(find(v(0), v(11)), #4) ==== #1]))))) *\\/*\n                  AbsAll range(#0, #4)\n                    ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0]))))) **\n          (AbsEach range(#0, #4)\n             (AbsExistsT\n                (Path(nth(v(5), v(6)), v(2), v(7), #21, #14 ++++ v(6) :: nil) **\n                 AbsAll TreeRecords(v(7))\n                   ([--( nth(v(5), v(6)), v(8) )---> (#18 ++++ v(6)) ==== #0] **\n                    [nth(v(5), v(6)) ==== v(7)] *\\/*\n                    [--( v(7), --( v(7), v(8) )---> (#18 ++++ v(6))\n                     )---> (#14 ++++ v(6)) ==== v(8)]))) **\n           AbsAll TreeRecords(v(3))\n             ([nth(find(v(3), !!(assignments_to_do_head)), #3) ==== #0] **\n              [!!(assignments_to_do_head) ==== v(6)] *\\/*\n              [nth(find(v(3), v(6)), #3) inTree v(3)] **\n              [nth(find(v(3), nth(find(v(3), v(6)), #3)), #2) ==== v(6)]) **\n           AbsAll TreeRecords(v(0))\n             (AbsAll TreeRecords(nth(find(v(0), v(6)), #2))\n                ([~~\n                  nth(find(v(0), v(6)), #3) ====\n                  nth(find(nth(find(v(0), v(6)), #2), v(7)), #3)])) **\n           AbsAll TreeRecords(v(0))\n             ([nth(v(4), nth(find(v(0), v(6)), #3)) ====\n               nth(find(v(0), v(6)), #4)]) **\n           AbsAll TreeRecords(v(0))\n             ([nth(find(v(0), v(6)), #4) ==== #1] *\\/*\n              [nth(find(v(0), v(6)), #4) ==== #2]) **\n           AbsAll TreeRecords(v(0)) ([nth(find(v(0), v(6)), #3) <<<< #4]) **\n           ARRAY(!!(watches), #4, v(5)) **\n           TREE(!!(assignments_to_do_head), v(3), #4, #1 :: nil) **\n           TREE(!!(clauses), v(2), #21, #1 :: nil) **\n           TREE(!!(stack), v(0), #4, #1 :: nil) **\n           [#1 ==== #1] ** ARRAY(!!(assignments), #4, v(4)) ** AbsEmpty) **\n          build_equivs\n            ((!!(stack) :: !!(ssss) :: nth(v(0), #0) :: nil)\n             :: (!!(have_var) :: #1 :: nil)\n                :: (nth(v(4), !!(varx)) :: !!(backtrack) :: #0 :: nil) :: nil))\n         bbb (eee, hhh) ->\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n    (AbsAll TreeRecords(v(2))\n        (AbsExists range(#0, #4)\n           (([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n             ([nth(v(4), v(7)) ==== #2] *\\/* [nth(v(4), v(7)) ==== #0]) *\\/*\n             [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n             ([nth(v(4), v(7)) ==== #1] *\\/* [nth(v(4), v(7)) ==== #0])) **\n            AbsAll range(#0, #4)\n              (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n               [--( v(2), v(6) )---> (#6 ++++ v(8))]) **\n            AbsAll range(#0, #4)\n              ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n               ([#0 <<<< --( v(2), v(6) )---> (#18 ++++ v(8))] *\\/*\n                [nth(v(5), v(8)) ==== v(6)]) *\\/*\n               ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] **\n                [--( v(2), v(6) )---> (#18 ++++ v(8)) ==== #0]) **\n               [~~ nth(v(5), v(8)) ==== v(6)]) **\n            SUM(range(#0, #4), #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)),\n            #2) **\n            (SUM(range(#0, #4),\n             (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n              --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n             nth(v(4), v(8)) ==== #0, #1) **\n             AbsAll range(#0, #4)\n               ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n                [nth(v(4), v(8)) ==== #0] *\\/*\n                [#0 <<<< nth(v(4), v(8))] *\\/*\n                [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) **\n             AbsAll range(#0, #4)\n               (AbsAll range(#0, #4)\n                  (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                        [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                        [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                       [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                      [nth(v(4), v(8)) ==== #0]) *\\/*\n                     [nth(v(4), v(9)) ==== #0]) *\\/* \n                    [v(8) ==== v(9)]) *\\/*\n                   AbsExists TreeRecords(v(0))\n                     (AbsExists TreeRecords(find(v(0), v(10)))\n                        ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                         [nth(find(v(0), v(11)), #3) ==== v(8)])))) *\\/*\n             AbsExists range(#0, #4)\n               (([--( v(2), v(6) )---> (#2 ++++ v(8))] **\n                 [nth(v(4), v(8)) ==== #2] *\\/*\n                 [--( v(2), v(6) )---> (#6 ++++ v(8))] **\n                 [nth(v(4), v(8)) ==== #1]) **\n                AbsAll range(#0, #4)\n                  (([#0 ==== nth(v(4), v(9))] *\\/*\n                    [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n                    [#0 <<<< nth(v(4), v(9))]) *\\/*\n                   AbsExists TreeRecords(v(0))\n                     (AbsExists TreeRecords(find(v(0), v(10)))\n                        ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                         ([#0 <<<<\n                           --( v(2), v(6)\n                           )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                          [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                          [#0 <<<<\n                           --( v(2), v(6)\n                           )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                          [nth(find(v(0), v(11)), #4) ==== #1]))))) *\\/*\n             AbsAll range(#0, #4)\n               ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                [nth(v(4), v(8)) ==== #0]))))) bbb (eee,empty_heap).\nProof. admit.\n    (*intros.\n\n    assert(@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (AbsAll TreeRecords(v(2))\n             (AbsExists range(#0, #4)\n                (([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n                  [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0])) **\n                 AbsAll range(#0, #4)\n                   (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                     [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n                    [--( v(2), v(6) )---> (#6 ++++ v(8))]) **\n                 AbsAll range(#0, #4)\n                   ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n                    ([#0 <<<< --( v(2), v(6) )---> (#18 ++++ v(8))] *\\/*\n                     [nth(v(5), v(8)) ==== v(6)]) *\\/*\n                    ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#18 ++++ v(8)) ==== #0]) **\n                    [~~ nth(v(5), v(8)) ==== v(6)]) **\n                 SUM(range(#0, #4),\n                 #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8)), \n                 #2) **\n                 (SUM(range(#0, #4),\n                  (--( v(2), v(6) )---> (#2 ++++ v(8)) \\\\//\n                   --( v(2), v(6) )---> (#6 ++++ v(8))) //\\\\\n                  nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0,\n                  #1) **\n                  AbsAll range(#0, #4)\n                    ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0] *\\/*\n                     [#0 <<<<\n                      nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n                     [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) **\n                  AbsAll range(#0, #4)\n                    (AbsAll range(#0, #4)\n                       (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                             [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                             [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                            [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                            #0]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                           #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                        ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(9)] **\n                            [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                              [nth(find(v(0), v(11)), #3) ==== v(8)])))) *\\/*\n                  AbsExists range(#0, #4)\n                    (([--( v(2), v(6) )---> (#2 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #2] *\\/*\n                      [--( v(2), v(6) )---> (#6 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #1]) **\n                     AbsAll range(#0, #4)\n                       (([#0 ====\n                          nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))] *\\/*\n                         [--( v(2), v(6) )---> (#10 ++++ v(9)) ==== #0] **\n                         [#0 <<<<\n                          nth(replacenth(v(4), !!(varx), !!(valuex)), v(9))]) *\\/*\n                        ([!!(varx) ==== v(9)] **\n                         ([#0 <<<< --( v(2), v(6) )---> (#2 ++++ !!(varx))] **\n                          [!!(valuex) ==== #2] *\\/*\n                          [#0 <<<< --( v(2), v(6) )---> (#6 ++++ !!(varx))] **\n                          [!!(valuex) ==== #1]) *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(9)] **\n                            ([#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#2 ++++ nth(find(v(0), v(10)), #3))] **\n                             [nth(find(v(0), v(10)), #4) ==== #2] *\\/*\n                             [#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#6 ++++ nth(find(v(0), v(10)), #3))] **\n                             [nth(find(v(0), v(10)), #4) ==== #1]))) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                              ([#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#2 ++++ nth(find(v(0), v(11)), #3))] **\n                               [nth(find(v(0), v(11)), #4) ==== #2] *\\/*\n                               [#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#6 ++++ nth(find(v(0), v(11)), #3))] **\n                               [nth(find(v(0), v(11)), #4) ==== #1]))))) *\\/*\n                  AbsAll range(#0, #4)\n                    ([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0]))))) bbb (eee,empty_heap)).\n        solvePickTerm H0.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) ([#0 ==== nth(v(4), !!(varx))]) bbb (eee,empty_heap)). solvePickTerm H0.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) ([!!(varx) <<<< #4]) bbb (eee,empty_heap)). solvePickTerm H0.\n\n        destruct_bindings. simpl.\n\n        Transparent basicEval.\n        destructState.\n        eapply RSAll. simpl. reflexivity. simpl. rewrite H6. reflexivity.\n        Opaque basicEval.\n\n        intros. assert (In x rl). apply H. apply H9 in H1. clear H9.\n        Transparent basicEval.\n        destructState. hypSimp. destruct v3; inversion H7; subst; clear H7; hypSimp. Opaque basicEval.\n        remember (nth (eee varx) l NoValue). destruct y; inversion HeqH7; subst; clear HeqH7.\n        Transparent basicEval.\n        destruct n0; inversion H1; subst; clear H1; hypSimp. Opaque basicEval. Focus 2. elim H3. reflexivity.\n\n        eapply RSExists. simpl. reflexivity. Transparent basicEval. simpl. reflexivity. Opaque basicEval.\n        eapply ex_intro.\n        split. apply H2. simpl. simpl in H11. simpl in H19. simpl in H17.\n        simpl in H9.\n\n        Transparent basicEval.\n\n        inversion H8; subst; clear H8.\n\n        eapply RSCompose.\n\n        eapply mergeTheorem1Aux5.\n            apply H9. apply H2. apply H7. apply H1. apply Heqy.\n\n\n        Focus 2. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        eapply RSCompose. eapply RSAll. simpl. reflexivity. Transparent basicEval. reflexivity. Opaque basicEval.\n        intros. simpl in H8. apply H17 in H8. apply H8.\n\n        Focus 2. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        eapply RSCompose. eapply RSAll. simpl. reflexivity. Transparent basicEval. reflexivity. Opaque basicEval.\n        intros. simpl in H8. apply H19 in H8. apply H8.\n\n        Focus 2. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        eapply RSCompose. apply H4.\n\n        Focus 2. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        inversion H11. subst. clear H11.\n\n        Transparent basicEval. destructState.\n        hypSimp. Opaque basicEval.\n        (*remember (beq_nat 0 match (nth (10+(eee varx)) (match (@findRecord unit (match v1 with | NatValue z => z | _ => 0 end) x) with | ListValue l => l | _ => nil end) NoValue) with | NatValue x => x | _ => 1 end).*)\n        remember (validPredicate (@absEval unit eq_unit (@basicEval unit) eee (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!varx)))).\n        destruct b.\n\n        eapply RSOrComposeL.\n        eapply RSCompose.\n\n        Focus 3. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n             (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])))\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n                ([--( v(2), v(6) )--->(#2 ++++ (!!varx))====#0] **\n                 [--( v(2), v(6) )--->(#6 ++++ (!!varx))====#0])\n            (v::v0::v1::v2::ListValue l::v4::x::nil) (eee, empty_heap)). eapply mergeTheorem1Aux9.\n            apply H9. apply H4. apply H17. apply H2. apply Heqy. apply H7. apply H1. apply H12.\n            apply H22. apply H21. apply Heqb. apply H8. apply H11.\n            solvePickTerm H0.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H13. subst. clear H13.\n            eapply arrayLength. apply H14. simpl. reflexivity.\n\n        eapply mergeTheorem1Aux1. apply H12. apply H21. apply Heqb. apply H8.\n            destruct (eee varx). simpl. reflexivity.\n            destruct n. reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n            inversion H1. subst. elim H7. reflexivity.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H14. subst. clear H14.\n            eapply arrayLength. apply H15. simpl. reflexivity.\n            apply Heqy. apply H13.\n\n        eapply RSCompose.\n        Focus 3. apply concreteComposeEmpty. split. reflexivity. reflexivity.\n\n        eapply RSAll. simpl. reflexivity. Transparent basicEval. simpl. reflexivity. Opaque basicEval. intros. eapply H21 in H8.\n\n        simpl. eapply mergeTheorem1Aux2. apply Heqb. apply H8. apply Heqy.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0. apply H11.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H11. subst. clear H11.\n            eapply arrayLength. apply H13. simpl. reflexivity.\n           assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n                ([--( v(2), v(6) )--->(#2 ++++ (!!varx))====#0] **\n                 [--( v(2), v(6) )--->(#6 ++++ (!!varx))====#0])\n            (v::v0::v1::v2::ListValue l::v4::x::nil) (eee, empty_heap)). eapply mergeTheorem1Aux9.\n            apply H9. apply H4. apply H17. apply H2. apply Heqy. apply H7. apply H1. apply H12.\n            apply H22. apply H21. apply Heqb.\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n           apply H11.\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n             (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])))\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n        apply H11.\n            solvePickTerm H0.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H11. subst. clear H11.\n            eapply arrayLength. apply H13. simpl. reflexivity.\napply H11.\n\n\n        eapply RSAll. simpl. reflexivity. Transparent basicEval. simpl. reflexivity. Opaque basicEval. intros. eapply H22 in H8. clear H22.\n\n        inversion H8. subst. clear H8. Transparent basicEval. simpl in H15. inversion H15. subst. clear H15.\n        Opaque basicEval. simpl in H20.\n        eapply RSAll. simpl. reflexivity. Transparent basicEval. reflexivity. Opaque basicEval. intros. simpl in H8. eapply H20 in H8. clear H20. simpl.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n        eapply mergeTheorem1Aux3.\n            destruct (eee varx). reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n            destruct n. reflexivity. inversion H1. subst. elim H7. reflexivity.\n            apply Heqy. apply Heqb. apply H8.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H13. subst. clear H13.\n            eapply arrayLength. apply H14. simpl. reflexivity.\n            apply H11.\n\n        eapply RSOrComposeR. eapply RSOrComposeR.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n      \n        eapply mergeTheorem1Aux4.\n            apply H4.\n            simpl. apply H17.\n            apply H2.\n            destruct (eee varx). reflexivity. destruct n. reflexivity. destruct n. reflexivity.\n            destruct n. reflexivity. inversion H1. subst. clear H1. elim H7. reflexivity.\n            apply Heqy. apply H12. apply H22. apply H21. apply Heqb. apply H8.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H11. subst. clear H11.\n            eapply arrayLength. apply H13. simpl. reflexivity.\n\n        subst. clear H11.\n\n        inversion H15. subst. clear H15.\n \n        eapply RSOrComposeR.\n\n        remember (@mapSum unit eq_unit (@basicEval unit) eee (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) (NatValue 0::NatValue 1::NatValue 2::NatValue 3::nil) \n             ((--( v(2), v(6) )---> (#2 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #2) \\\\//\n              (--( v(2), v(6) )---> (#6 ++++ v(8)) //\\\\ nth(v(4), v(8)) ==== #1))).\n\n        destruct n.\n\n        eapply RSOrComposeR.\n\n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n            eapply mergeTheorem1Aux7.\n            apply H9. apply H4. apply H17. apply H2. apply Heqy. apply H7. apply H1. apply H14.\n            apply Heqn. apply H8.\n            assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n                (AbsAll TreeRecords(v(0)) ([nth(find(v(0), v(6)), #3) <<<< #4]))\n                (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n            simpl.\n            eapply dumpVar2. instantiate (2 := 6). Focus 2. simpl. reflexivity. Focus 2. simpl.\n            reflexivity. simpl.\n            eapply dumpVar2. instantiate (2 := 6). Focus 2. simpl. reflexivity. Focus 2. simpl.\n            reflexivity. simpl.\n            inversion H11. subst. clear H11.\n            Transparent basicEval. simpl in H16. Opaque basicEval.\n            eapply RSAll. Transparent basicEval. simpl. reflexivity. apply H16.\n            intros. apply H21 in H11. simpl in H11. simpl. apply H11.\n            assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n                (AbsAll TreeRecords(v(0))\n             ([nth(v(4), nth(find(v(0), v(6)), #3)) ====\n               nth(find(v(0), v(6)), #4)]))\n                (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n            simpl.\n            eapply dumpVar2. instantiate (2 := 6). Focus 2. simpl. reflexivity. Focus 2. simpl.\n            reflexivity. simpl.\n            eapply dumpVar2. instantiate (2 := 6). Focus 2. simpl. reflexivity. Focus 2. simpl.\n            reflexivity. simpl.\n            inversion H11. subst. clear H11.\n            Transparent basicEval. simpl in H16. Opaque basicEval.\n            eapply RSAll. Transparent basicEval. simpl. reflexivity. apply H16.\n            intros. apply H21 in H11. simpl in H11. simpl. apply H11.\n\n        eapply RSOrComposeL.\n      \n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n        eapply mergeTheorem1Aux8.\n            apply H9. apply H4. apply H17. apply H2. apply Heqy. apply H7. apply H1. apply H14.\n            apply Heqn. apply H8.\n\n        eapply RSOrComposeR. eapply RSOrComposeR.\n        subst. clear H15. \n        assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n            (v::v0::v1::v2::ListValue l::v4::nil) (eee, empty_heap)). solvePickTerm H0.\n\n        eapply mergeTheorem1Aux6.\n            apply H2. apply H7. apply H1. apply  Heqy. apply H14. apply H8.\n            assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(4)))  (v::v0::v1::v2::ListValue l::v4::nil) (eee, hh)).\n            solvePickData H0. inversion H11. subst. clear H11.\n            eapply arrayLength. apply H12. simpl. reflexivity.*)\nQed.\n\nTheorem SatProgramWorks :\n    exists x, {{invariant}}Program{{finalState x, Return x}}.\nProof.\n    unfold invariant. unfold Program. simpl.\n\n    eapply ex_intro.\n\n    eapply strengthenPost.\n\n    (* backtrack ::= ANum(0); *)\n    pcrunch.\n\n    (* WHILE ANum(1) DO *)\n    eapply while with (invariant := invariant). unfold invariant. apply sbasic. intros. unfold invariant.\n\n    eapply ex_intro. eapply strengthenPost.\n\n    pcrunch. admit. apply sbasic.\n\n    simp. simp. simp. simp. simp.\n    eapply unfold_pre. unfoldHeap (@AbsVar unit eq_unit (@basicEval unit) stack).\n\n    simp. simp. simp. simp.\n\n    pcrunch. pcrunch. pcrunch. pcrunch.\n    simp. simp. simp. simp. simp. simp. simp. simp. simp.\n\n    eapply store_array.\n    apply (AbsQVar 0).\n    compute. reflexivity. compute. reflexivity. simpl. reflexivity. simpl. reflexivity. simpl. reflexivity.\n    solveSPickElement.\n\n    intros. removeExistentials. simpl in H.\n    eapply pickAssertion.\n    apply H. solveSPickElement. reflexivity.  intro X. inversion X. compute. reflexivity.\n\n    compute. reflexivity.\n\n    simp. simp. simp. simp. simp.\n\n    eapply while with (invariant := invariant1). unfold invariant1. apply sbasic. intros. unfold invariant1.\n    eapply ex_intro. eapply strengthenPost.\n\n    simp. simp. simp. simp. simp.\n\n    pcrunch.\n\n    eapply load_array.\n    apply (AbsQVar 0).\n    compute. reflexivity. compute. reflexivity. compute. reflexivity. compute. reflexivity.\n    solveSPickElement.\n\n    intros. removeExistentials. simpl in H.\n\n    assert (@absEval unit eq_unit basicEval (fst ss) nil (~~ #3 <<<< !!(iiii))=NatValue 1).\n    eapply pickAssertion.\n    apply H. solveSPickElement. reflexivity.  intro X. inversion X. compute. reflexivity.\n\n    clear H. Transparent basicEval. simpl in H0. simpl.\n\n    remember (ble_nat (fst ss iiii) 3).\n    destruct b.\n\n    destruct (fst ss iiii). reflexivity.\n    destruct n. reflexivity.\n    destruct n. reflexivity.\n    destruct n. reflexivity.\n    simpl in Heqb. inversion Heqb.\n    simpl in H0. inversion H0.\n  \n    Opaque basicEval.\n\n    compute. reflexivity.\n\n    admit. apply sbasic.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n\n    startMerge.\n    doMergeStates.\n\n    eapply DMImplyPredicates1.\n    instantiate (2 := ([~~ !!(have_var)] *\\/* [nth(v(3), !!(varx)) ==== #0])). solveSPickElement.\n    simpl. reflexivity.\n\n    simpl. intros.\n\n assert (exists hh, @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (ARRAY(!!(assignments), #4, v(5))) bbb (eee,hh)).\n    solvePickData H0.\n    inversion H1. subst. clear H1.\n assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) ( [!!(varx) ==== !!(iiii)]) bbb (eee,empty_heap)).\n    solvePickTerm H0.\n assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) ( [#0 ==== nth(v(5), !!(iiii))]) bbb (eee,empty_heap)).\n    solvePickTerm H0.\n\n    Transparent basicEval.\n\n        inversion H1. subst. clear H1. simpl in H9. inversion H9. subst. clear H9.\n            remember (beq_nat (eee varx) (eee iiii)). destruct b. apply beq_nat_eq in Heqb.\n\n        inversion H3. subst. clear H3. simpl in H11.\n\n        inversion H2. subst. clear H2. simpl in H10. inversion H10. subst. clear H10.\n\n        rewrite <- H7 in H11.\n\n        inversion H11. subst. clear H11. remember (nth (eee iiii) vl NoValue). destruct y.\n            destruct n.\n\n        eapply RSOrComposeR. eapply RSR. simpl. reflexivity. rewrite Heqb. rewrite Heqy.\n        rewrite <- H7. rewrite <- Heqy. simpl. eapply BTStatePredicate. intro X. inversion X.\n\n        unfold empty_heap. reflexivity.\n\n        inversion H2. subst. clear H2. elim H3. reflexivity.\n        inversion H2. inversion H2. inversion H2. inversion H1. subst. clear H1.\n        elim H4. reflexivity.\n\n    Opaque basicEval.\n\n    eapply DMFinish. solveAllPredicates. solveAllPredicates.\n\n    intros. simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n\n    stateImplication.\n\n    intros.\n\n    eapply simplifyEquiv2. rewrite H0. compute. reflexivity.\n    eapply RSEmpty. unfold empty_heap. reflexivity.\n\n    intros. simplifyHyp H. simplifyHyp H. simplifyHyp H. unfold invariant1.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n\n    stateImplication.\n\n    intros. clear H.\n\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n            ([!!(have_var) ==== #0]) b (e,empty_heap)).\n    solvePickTerm H1.\n\n    eapply simplifyEquiv2. rewrite H0. compute. reflexivity.\n    eapply simplifyEquiv2. rewrite H0. compute. reflexivity.\n\n    Transparent basicEval.\n\n        inversion H. subst. clear H. simpl in H7. inversion H7. subst. clear H7.\n        remember (beq_nat (e have_var) 0). destruct b0. apply beq_nat_eq in Heqb0.\n\n        eapply RSOrComposeL. eapply RSR. simpl. reflexivity.\n        rewrite Heqb0. simpl. eapply BTStatePredicate.\n        intro X. inversion X. unfold empty_heap. reflexivity.\n\n        inversion H. subst. clear H. elim H2. reflexivity.\n\n    Opaque basicEval.\n\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n    eapply mergeSimplifyLeft. compute. reflexivity.\n\n    startMerge.\n    doMergeStates.\n\n    eapply DMImplyPredicates1.\n\n    instantiate (2 := (AbsAll range(#0,#4) _)). solveSPickElement. simpl. reflexivity.\n\n    simpl. intros.\n\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))]))) bbb (eee,empty_heap)).\n      solvePickTerm H0.\n    assert (@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) ([#0 ==== nth(v(4), !!(varx))]) bbb (eee,empty_heap)).\n      solvePickTerm H0.\n\n    Transparent basicEval.\n\n        inversion H2. subst. clear H2. simpl in H8.\n        remember (nth 4 bbb NoValue). destruct y.\n            inversion H8.\n            remember (nth (eee varx) l NoValue). destruct y.\n            destruct n.\n                eapply RSAll. simpl. reflexivity. reflexivity. intros.\n                inversion H1. subst. clear H1. simpl in H6. inversion H6. subst. clear H6.\n                eapply H10 in H2. inversion H2.\n                    subst. clear H2.\n                    eapply RSOrComposeL. apply H6.\n                    subst. clear H2.\n                        inversion H6. subst. clear H6.\n                            inversion H5. subst. clear H5. simpl in H7. remember (nth 6 (bbb++x::nil) NoValue). destruct y.\n                                inversion H7. subst. clear H7. remember (beq_nat (eee varx) n). destruct b.\n                                inversion H1. subst. clear H1. apply beq_nat_eq in Heqb.\n                                apply RSOrComposeL. eapply RSR. simpl. reflexivity.\n                                rewrite <- Heqy1.\n                                remember (nth 4 (bbb ++ x :: nil) NoValue). destruct y.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                simpl in Heqy. simpl in Heqy2.\n                                rewrite <- Heqy in Heqy2. inversion Heqy2.\n                                rewrite <- Heqb.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                simpl in Heqy. simpl in Heqy2. rewrite <- Heqy in Heqy2.\n                                inversion Heqy2. rewrite <- Heqy0. simpl.\n                                eapply BTStatePredicate. intro X. inversion X.\n                                unfold empty_heap. reflexivity.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                simpl in Heqy. simpl in Heqy2.\n                                rewrite <- Heqy in Heqy2. inversion Heqy2.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                destruct bbb. simpl in Heqy. inversion Heqy.\n                                simpl in Heqy. simpl in Heqy2.\n                                rewrite <- Heqy in Heqy2. inversion Heqy2.\n                            inversion H1. subst. clear H1. elim H2. reflexivity.\n                            inversion H7. inversion H7. inversion H7.\n                        subst. eapply RSOrComposeR. apply H5.\n                        inversion H8. elim H3. reflexivity.\n                        inversion H8. inversion H8. inversion H8. inversion H8. inversion H8.\n\n    Opaque basicEval.\n\n    Focus 1.\n\n    eapply DMImplyPredicates1. instantiate (2 := (AbsAll _ _)). solveSPickElement.\n    simpl. reflexivity.\n\n    intros.\n\n    eapply mergeTheorem1. apply H. apply H0.\n\n    apply DMFinish. solveAllPredicates. solveAllPredicates.\n    assert(@realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit)) (AbsAll TreeRecords(v(2))\n             (AbsExists range(#0, #4)\n                (([--( v(2), v(6) )---> (#1 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n                  [--( v(2), v(6) )---> (#5 ++++ v(7))] **\n                  ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n                   [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0])) **\n                 AbsAll range(#0, #4)\n                   ([~~ --( v(2), v(6) )---> (#9 ++++ v(8)) ==== #0] **\n                    ([~~ --( v(2), v(6) )---> (#17 ++++ v(8)) ==== #0] *\\/*\n                     [nth(v(5), v(8)) ==== v(6)]) *\\/*\n                    ([--( v(2), v(6) )---> (#9 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#17 ++++ v(8)) ==== #0]) **\n                    [~~ nth(v(5), v(8)) ==== v(6)]) **\n                 (SUM(range(#0, #4),\n                  ite(--( v(6), v(2) )---> (#9 ++++ v(8)),\n                  --( v(6), v(2) )---> (#9 ++++ v(8)), \n                  #0), #2) *\\/*\n                  AbsAll range(#0, #4)\n                    ([--( v(6), v(2) )---> (#9 ++++ v(8))])) **\n                 (SUM(range(#0, #4),\n                  (--( v(2), v(6) )---> (#1 ++++ v(8)) //\\\\\n                   (ite(nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                        #1,\n                    nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #1,\n                    #0))) ++++\n                  (--( v(2), v(6) )---> (#5 ++++ v(8)) //\\\\\n                   (ite(nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                        #2,\n                    nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #2,\n                    #0))), #4) **\n                  AbsAll range(#0, #4)\n                    ([#0 <<<< --( v(2), v(6) )---> (#9 ++++ v(8))] **\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0] *\\/*\n                     [--( v(2), v(6) )---> (#1 ++++ v(8)) ==== #0] **\n                     [--( v(2), v(6) )---> (#5 ++++ v(8)) ==== #0]) **\n                  AbsAll range(#0, #4)\n                    (AbsAll range(#0, #4)\n                       ((((([--( v(2), v(6) )---> (#9 ++++ v(8))] *\\/*\n                            [~~ --( v(2), v(6) )---> (#9 ++++ v(9))]) *\\/*\n                           [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                            #0]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                           #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                        ([!!(varx) ==== v(8)] ** [!!(varx) ==== v(9)] *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(8)] **\n                            [nth(find(v(0), v(10)), #2) ==== v(9)])) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #2) ==== v(8)] **\n                              [nth(find(find(v(0), v(10)), v(11)), #2) ====\n                               v(9)])))) *\\/*\n                  AbsExists range(#0, #4)\n                    (([--( v(2), v(6) )---> (#1 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #2] *\\/*\n                      [--( v(2), v(6) )---> (#5 ++++ v(8))] **\n                      [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                       #1]) **\n                     AbsAll range(#0, #4)\n                       ([--( v(2), v(6) )---> (#9 ++++ v(9)) ==== #0] *\\/*\n                        ([!!(varx) ==== v(9)] **\n                         ([#0 <<<< --( v(2), v(6) )---> (#1 ++++ !!(varx))] **\n\n                          [!!(valuex) ==== #2] *\\/*\n                          [#0 <<<< --( v(2), v(6) )---> (#5 ++++ !!(varx))] **\n                          [!!(valuex) ==== #1]) *\\/*\n                         AbsExists TreeRecords(v(0))\n                           ([!!(varx) ==== v(9)] **\n                            ([#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#1 ++++ nth(find(v(0), v(10)), #2))] **\n                             [nth(find(v(0), v(10)), #3) ==== #2] *\\/*\n                             [#0 <<<<\n                              --( v(2), v(6)\n                              )---> (#5 ++++ nth(find(v(0), v(10)), #2))] **\n                             [nth(find(v(0), v(10)), #3) ==== #1]))) *\\/*\n                        AbsExists TreeRecords(v(0))\n                          (AbsExists TreeRecords(find(v(0), v(10)))\n                             ([nth(find(v(0), v(10)), #2) ==== v(9)] **\n                              ([#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#1 ++++\n                                       nth(find(find(v(0), v(10)), v(11)),\n                                       #2))] **\n                               [nth(find(find(v(0), v(10)), v(11)), #3) ====\n                                #2] *\\/*\n                               [#0 <<<<\n                                --( v(2), v(6)\n                                )---> (#5 ++++\n                                       nth(find(find(v(0), v(10)), v(11)),\n                                       #2))] **\n                               [nth(find(find(v(0), v(10)), v(11)), #3) ====\n                                #1]))))) *\\/*\n                  AbsAll range(#0, #4)\n                    ([--( v(2), v(6) )---> (#9 ++++ v(8)) ==== #0] *\\/*\n                     [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                      #0]))))) bbb (eee,empty_heap)).\n        solvePickTerm H0.\n\n        inversion H1. subst. clear H1. simpl in H5.\n        eapply RSAll. simpl. reflexivity. simpl. rewrite H5. reflexivity.\n\n        intros. apply H8 in H1. clear H8. inversion H1. subst. clear H1. inversion H9. subst. clear H9.\n        inversion H1. subst. clear H1. inversion H3. subst. clear H3.\n        apply concreteComposeEmpty in H11. inversion H11. subst. clear H11.\n        inversion H8. subst. clear H8. inversion H4. subst. clear H4.\n        inversion H9. subst. clear H9.\n        apply concreteComposeEmpty in H12. inversion H12. subst. clear H12.\n        apply concreteComposeEmpty in H15. inversion H15. subst. clear H15. simpl in H10.\n        eapply RSExists. simpl. reflexivity. Transparent basicEval. simpl. Opaque basicEval. reflexivity.\n        eapply ex_intro. Transparent basicEval. simpl in H6. Opaque basicEval. inversion H6. subst. clear H6.\n        split. apply H2.\n        eapply RSCompose.\n        inversion H8. subst. clear H8. Focus 2. subst. clear H8. Focus 1.\n\n    (* End of derivation *)\n", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/SatSolver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19953807839114812}}
{"text": "Require Import RamifyCoq.lib.Ensembles_ext.\nRequire Import RamifyCoq.lib.Relation_ext.\nRequire Import RamifyCoq.lib.List_ext.\nRequire Import RamifyCoq.veric_ext.SeparationLogic.\nRequire Import RamifyCoq.floyd_ext.ramification.\nRequire Import VST.floyd.base.\nRequire Import VST.floyd.canon.\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 vars_relation_Included: forall P Q, Included P Q -> inclusion _ (vars_relation P) (vars_relation Q).\nProof.\n  intros.\n  intros ? ? ?.\n  unfold vars_relation in *.\n  split.\n  + unfold Included, Ensembles.In in H.\n    destruct H0 as [? _].\n    firstorder.\n  + exact (proj2 H0).\nQed.\n\nModule RAM_FRAME.\n\nRecord SingleFrame' l g s: Type := {\n  frame: environ -> mpred;\n  cont: statement;\n  frame_sound: g |-- l * ModBox (Ssequence s cont) frame\n}.\n\nRecord SingleFrame: Type := {\n  local_assert: environ -> mpred;\n  global_assert: environ -> mpred;\n  stats: statement;\n  real_frame: SingleFrame' local_assert global_assert stats\n}.\n\nEnd RAM_FRAME.\n\nDefinition SingleFrame' := RAM_FRAME.SingleFrame'.\nDefinition SingleFrame := RAM_FRAME.SingleFrame.\n\nArguments RAM_FRAME.Build_SingleFrame' {l} {g} {s} frame cont frame_sound.\n\nSection SEMAX.\n\nContext {Espec: OracleKind}.\nContext {cs: compspecs}.\n\nInductive add_stats (s0: statement) : list SingleFrame -> list SingleFrame -> Prop :=\n  | add_stats_nil : add_stats s0 nil nil\n  | add_stats_cons : forall l g s cont f fs fs' F F', add_stats s0 F F' ->\n      add_stats s0\n       (RAM_FRAME.Build_SingleFrame l g s (RAM_FRAME.Build_SingleFrame' f (Ssequence s0 cont) fs) :: F)\n       (RAM_FRAME.Build_SingleFrame l g (Ssequence s s0) (RAM_FRAME.Build_SingleFrame' f cont fs') :: F')\n  .\n\nDefinition SingleFrame'_inv {l g s s0} (F: SingleFrame' l g (Ssequence s s0)) : SingleFrame' l g s :=\n  match F with\n  | RAM_FRAME.Build_SingleFrame' f cont fs =>\n      RAM_FRAME.Build_SingleFrame' f (Ssequence s0 cont) fs\n  end.\n(* This use the fact that \"modifiedvars (Ssequence (Ssequence s s0) cont)\"\nand \"modifiedvars (Ssequence s (Ssequence s0 cont))\" are convertably equal. *)\n\nLemma eexists_add_stats_cons: forall s0 l g s (F0: SingleFrame' _ _ _) F F',\n  add_stats s0 F F' ->\n  add_stats s0\n   (RAM_FRAME.Build_SingleFrame l g s (SingleFrame'_inv F0) :: F)\n   (RAM_FRAME.Build_SingleFrame l g (Ssequence s s0) F0 :: F').\nProof.\n  intros.\n  destruct F0; unfold SingleFrame'_inv.\n  constructor.\n  auto.\nQed.\n\nFixpoint semax_ram (Delta: tycontext) (F: list SingleFrame) (P: environ -> mpred) (c: statement) (Q: ret_assert): Prop :=\n  match F with\n  | nil => semax Delta P c Q\n  | RAM_FRAME.Build_SingleFrame _ _ s (RAM_FRAME.Build_SingleFrame' F0 cont _) :: F_tail =>\n      semax_ram Delta F_tail (P * ModBox (Ssequence s cont) F0) c Q\n  end.\n\nLemma semax_ram_pre: forall Delta F P P' c Q,\n  P' |-- P ->\n  semax_ram Delta F P c Q ->\n  semax_ram Delta F P' c Q.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  revert P P' H0 H; induction F; intros; simpl in H0 |- *.\nTransparent LiftNatDed' LiftSepLog'.\n  + eapply semax_pre0; eauto.\n  + destruct a as [l g s [F0 cont ?]].\n    eapply IHF; eauto.\n    apply sepcon_derives; auto.\nQed.\n\nLemma semax_ram_localize: forall Delta F P c Q P',\n  (exists F0: SingleFrame' P' P Sskip,\n     semax_ram Delta (RAM_FRAME.Build_SingleFrame P' P Sskip F0 :: F) P' c Q) ->\n  semax_ram Delta F P c Q.\nProof.\n  intros.\n  destruct H as [F0 ?].\n  simpl in H.\n  destruct F0 as [F0 ? ?].  \n  eapply semax_ram_pre; eauto.\nQed.\n\nLemma semax_ram_unlocalize: forall Delta l g s F P c Q P'\n  (frame_sound: g |-- l * ModBox (Ssequence s Sskip) (P -* P')),\n  semax_ram Delta F P' c Q ->\n  semax_ram Delta\n   (RAM_FRAME.Build_SingleFrame l g s\n     (RAM_FRAME.Build_SingleFrame' (P -* P') Sskip frame_sound) :: F) P c Q.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  simpl.\nTransparent LiftNatDed' LiftSepLog'.\n  eapply semax_ram_pre; [| eauto].\n  rewrite sepcon_comm.\n  apply wand_sepcon_adjoint.\n  apply EnvironBox_T.\n  apply vars_relation_Equivalence.\nQed.\n\nLemma semax_ram_unlocalize': forall Delta l g s F P c Q P' Frame\n  (frame_sound: g |-- l * ModBox (Ssequence s Sskip) Frame),\n  Frame |-- P -* P' ->\n  semax_ram Delta F P' c Q ->\n  semax_ram Delta\n   (RAM_FRAME.Build_SingleFrame l g s\n     (RAM_FRAME.Build_SingleFrame' Frame Sskip frame_sound) :: F) P c Q.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  simpl.\nTransparent LiftNatDed' LiftSepLog'.\n  eapply semax_ram_pre; [| eauto].\n  rewrite sepcon_comm.\n  apply wand_sepcon_adjoint.\n  eapply derives_trans; [| apply H].\n  apply EnvironBox_T; apply vars_relation_Equivalence.\nQed.\n\n(*\nLemma semax_ram_unlocalize': forall Delta l g s F P0 P1 P c Q P'\n  (frame_sound: g |-- l * (P1 && (P -* P')))\n  (frame_closed: Forall (fun s => closed_wrt_modvars s (P1 && (P -* P'))) s),\n  corable P0 ->\n  corable P1 ->\n  semax_ram Delta F (P0 && P1 && P') c Q ->\n  semax_ram Delta\n   (RAM_FRAME.Build_SingleFrame l g s\n     (RAM_FRAME.Build_SingleFrame' (P1 && (P -* P')) frame_sound frame_closed) :: F) (P0 && P) c Q.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  simpl.\nTransparent LiftNatDed' LiftSepLog'.\n  eapply semax_ram_pre; [| eauto].\n  rewrite corable_andp_sepcon1 by auto.\n  rewrite andp_assoc.\n  apply andp_derives; [auto |].\n  rewrite corable_sepcon_andp1 by auto. \n  apply andp_derives; [auto |].\n  rewrite sepcon_comm.\n  apply wand_sepcon_adjoint.\n  auto.\nQed.\n\nLemma corable_PROP_LOCAL: forall P Q R, corable R -> corable (PROPx P (LOCALx Q R)).\nProof.\nOpaque LiftNatDed' LiftSepLog' LiftCorableSepLog'.\n  intros.\n  unfold PROPx, LOCALx.\n  apply corable_andp; auto.\n  unfold local, lift1.\n  apply corable_andp; auto.\n  unfold_lift.\nTransparent LiftNatDed' LiftSepLog' LiftCorableSepLog'.\n  simpl.\n  intros.\n  auto.\nQed.\n\nLemma frame_sound_aux: forall g l R P' Q1' R',\n  g |-- PROPx P' (LOCALx Q1' TT) ->\n  g |-- l * (SEPx R -* SEPx R') ->\n  g |-- l * (PROPx P' (LOCALx Q1' TT) && (SEPx R -* SEPx R')).\nProof.\n  intros.\n  rewrite corable_sepcon_andp1 by (apply corable_PROP_LOCAL; simpl; auto).\n  apply andp_right; auto.\nQed.\n\nLemma frame_closed_aux: forall s R P' Q' Q1' Q2' R',\n  split_by_closed s Q' Q1' Q2' ->\n  Forall (fun s => closed_wrt_modvars s (SEPx R -* SEPx R')) s ->\n  Forall (fun s => closed_wrt_modvars s (PROPx P' (LOCALx Q1' TT) && (SEPx R -* SEPx R'))) s.\nProof.\n  intros.\n  apply split_by_closed_spec with (P := P') in H.\n  destruct H as [? _].\n  rewrite Forall_forall in *.\n  intros x HH; specialize (H x HH); specialize (H0 x HH).\n  auto with closed.\nQed.\n\nLemma semax_ram_unlocalize_PROP_LOCAL_SEP: forall Delta l g s F P Q R c Ret P' Q' Q1' Q2' R'\n  (SPLIT: split_by_closed s Q' Q1' Q2')\n  (SEP_frame_sound: g |-- l * (SEPx R -* SEPx R'))\n  (SEP_frame_closed: Forall (fun s => closed_wrt_modvars s (SEPx R -* SEPx R')) s)\n  (PURE_frame_sound: g |-- PROPx P' (LOCALx Q1' TT)),\n  PROPx P (LOCALx Q (SEPx R)) |-- PROPx nil (LOCALx Q2' TT) ->\n  semax_ram Delta F (PROPx P' (LOCALx Q' (SEPx R'))) c Ret ->\n  semax_ram Delta\n   (RAM_FRAME.Build_SingleFrame l g s\n     (RAM_FRAME.Build_SingleFrame'\n       (PROPx P' (LOCALx Q1' TT) && (SEPx R -* SEPx R'))\n       (frame_sound_aux _ _ _ _ _ _ PURE_frame_sound SEP_frame_sound)\n       (frame_closed_aux _ _ _ _ _ _ _ SPLIT SEP_frame_closed)) :: F)\n   (PROPx P (LOCALx Q (SEPx R))) c Ret.\nProof.\n  intros.\n  eapply semax_ram_pre with (PROPx nil (LOCALx Q2' (SEPx R))).\n  1: rewrite SEPx_sepcon with (Q := Q2'); apply andp_right;\n       [eauto | rewrite SEPx_sepcon; apply andp_left2; auto].\n  rewrite SEPx_sepcon in H |- *.\n  apply semax_ram_unlocalize';\n   [ apply corable_PROP_LOCAL; simpl; auto\n   | apply corable_PROP_LOCAL; simpl; auto\n   |].\n  apply split_by_closed_spec with (P := P') in SPLIT.\n  rewrite (andp_comm (PROP  ()  (LOCALx Q2' TT))), <- (proj2 SPLIT).\n  rewrite SEPx_sepcon in H0; auto.\nQed.\n\nLemma semax_ram_abduction: forall Delta l g s F P c Q F0\n  (frame_sound: g |-- l * F0)\n  (frame_closed: Forall (fun s => closed_wrt_modvars s F0) s),\n  semax_ram Delta F (P * F0) c Q ->\n  semax_ram Delta\n    (RAM_FRAME.Build_SingleFrame l g s\n      (RAM_FRAME.Build_SingleFrame' F0 frame_sound frame_closed) :: F) P c Q.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  simpl.\nTransparent LiftNatDed' LiftSepLog'.\n  eapply semax_ram_pre; [| eauto]; auto.\nQed.\n*)\nLemma semax_ram_seq_skip:\n  forall Delta F P c Q,\n  semax_ram Delta F P c Q <-> semax_ram Delta F P (Ssequence c Sskip) Q.\nProof.\n  intros.\n  revert P Q; induction F; intros.\n  + unfold semax_ram.\n    apply semax_seq_skip.\n  + destruct a; destruct real_frame; simpl.\n    apply IHF.\nQed.\n\nLemma semax_ram_seq: forall Delta F F' P Q R c0 c1,\n  add_stats c0 F F' ->\n  semax Delta P c0 (normal_ret_assert Q) ->\n  semax_ram (update_tycon Delta c0) F' Q c1 R ->\n  semax_ram Delta F P (Ssequence c0 c1) R.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  revert P Q H0 H1; induction H; intros; simpl in H1 |- *.\nTransparent LiftNatDed' LiftSepLog'.\n  + eapply semax_seq'; eauto.\n  + eapply IHadd_stats; [| eauto].\n    rewrite <- frame_normal.\n    apply semax_frame; auto.\n    apply EnvironStable_var_relation_closed.\n    apply EnvironBox_EnvironStable_weaken; [apply vars_relation_Equivalence |].\n    apply vars_relation_Included.\n    hnf; unfold Ensembles.In, modifiedvars; simpl; intros.\n    rewrite modifiedvars'_union in H2 |- *.\n    rewrite (modifiedvars'_union _ c0).\n    rewrite (modifiedvars'_union _ cont).\n    tauto.\nQed.\n\nLemma semax_ram_seq': forall Delta F F' P Q R c,\n  add_stats c F F' ->\n  semax Delta P c (normal_ret_assert Q) ->\n  semax_ram (update_tycon Delta c) F' Q Sskip R ->\n  semax_ram Delta F P c R.\nProof.\n  intros.\n  rewrite semax_ram_seq_skip.\n  eapply semax_ram_seq;\n  eauto.\nQed.\n\nLemma ram_seq_assoc: forall Delta F P s1 s2 s3 R,\n  semax_ram Delta F P (Ssequence s1 (Ssequence s2 s3)) R <->\n  semax_ram Delta F P (Ssequence (Ssequence s1 s2) s3) R.\nProof.\n  induction F; intros.\n  + apply seq_assoc.\n  + simpl.\n    destruct a as [l g s [F0 ? ?]].\n    apply IHF; auto.\nQed.\n\nLemma ram_extract_exists_pre: forall A Delta F P c Q,\n  (forall x : A, semax_ram Delta F (P x) c Q) ->\n  semax_ram Delta F (EX  x : A, P x) c Q.\nProof.\nOpaque LiftNatDed' LiftSepLog'.\n  induction F; intros; simpl in H |- *.\nTransparent LiftNatDed' LiftSepLog'.\n  + apply extract_exists_pre; auto.\n  + destruct a as [l g s [F0 ? ?]].\n    rewrite exp_sepcon1.\n    apply IHF; auto.\nQed.\n\nLemma ram_extract_PROP: forall Delta F (PP: Prop) (P: list Prop) QR c Post,\n  (PP -> semax_ram Delta F (PROPx P QR) c Post) ->\n  semax_ram Delta F (PROPx (PP :: P) QR) c Post.\nProof.\n  intros.\nOpaque LiftNatDed' LiftSepLog'.\n  revert QR H; induction F; intros; simpl in H |- *.\nTransparent LiftNatDed' LiftSepLog'.\n  + apply semax_extract_PROP; auto.\n  + destruct a as [l g s [F0 ? ?]].\n    unfold PROPx in H |- *.\n    rewrite sepcon_andp_prop' in H |- *.\n    apply IHF.\n    auto.\nQed.\n\nLemma revert_exists_left: forall {A} (x : A) P (Q: environ -> mpred),\n  (EX  x : A, P x) |-- Q ->\n  (P x) |-- Q.\nProof.\n  intros.\n  eapply derives_trans; [| eauto].\n  apply (exp_right x); auto.\nQed.\n\nLemma revert_prop_left: forall {PureF: Prop},\n  PureF -> \n  forall P Q R Post,\n  PROPx (PureF :: P) (LOCALx Q (SEPx R)) |-- Post ->\n  PROPx P (LOCALx Q (SEPx R)) |-- Post.\nProof.\n  intros.\n  eapply derives_trans; [| eauto].\n  unfold PROPx; simpl; intros; normalize.\nQed.\n\nLemma ram_revert_exists_pre: forall {A} (x : A) Delta F P c Q,\n  semax_ram Delta F (EX  x : A, P x) c Q ->\n  semax_ram Delta F (P x) c Q.\nProof.\n  intros.\n  eapply semax_ram_pre; [| eauto].\n  apply (exp_right x); auto.\nQed.\n\nLemma ram_revert_prop_pre: forall {PureF: Prop},\n  PureF -> \n  forall Delta F P c Q,\n  semax_ram Delta F (!! PureF && P) c Q ->\n  semax_ram Delta F P c Q.\nProof.\n  intros.\n  eapply semax_ram_pre; [| eauto].\n  normalize.\nQed.\n  \nEnd SEMAX.\n\nArguments SingleFrame' {l} {g} {s}.\n\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/semax_ram_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.19943325166608242}}
{"text": "Require Import Coq.Lists.List.\nRequire Import coqutil.Z.Lia.\nImport ListNotations.\nRequire Import coqutil.Word.Properties.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import riscv.Spec.Machine.\nRequire Import Coq.ZArith.ZArith.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Platform.Run.\nRequire Import riscv.Utility.MkMachineWidth.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Utility.InstructionCoercions.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import compiler.GoFlatToRiscv.\nRequire Import compiler.SeparationLogic.\nRequire Import compiler.FlatToRiscvDef.\nRequire Export coqutil.Word.SimplWordExpr.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire Import bedrock2.ptsto_bytes.\nRequire Import coqutil.Tactics.Simp.\nImport Utility Decode.\n\nOpen Scope Z_scope.\nOpen Scope ilist_scope.\n\nDefinition x1: Z := 1.\nDefinition x2: Z := 2.\n\n(* average of register x1 and x2 put into x2 *)\nDefinition asm_prog_1: list Instruction := [[\n  Add x2 x1 x2;\n  Srai x2 x2 1\n]].\n\nDefinition input_ptr: Z := 0x400.\nDefinition output_ptr: Z := 0x500.\n\n(* a program with memory operations *)\nDefinition asm_prog_2: list Instruction := [[\n  Lw x1 Register0 input_ptr;\n  Lw x2 Register0 (input_ptr+4)\n]] ++\nasm_prog_1 ++ [[\n  Sw Register0 x2 output_ptr\n]].\n\nSection Verif.\n\n  Context {width} {BW: Bitwidth width} {word: word.word width} {word_ok: word.ok word}.\n  Context {Registers: map.map Register word}.\n  Context {Registers_ok: map.ok Registers}.\n  Context {mem: map.map word byte}.\n  Context {mem_ok: map.ok mem}.\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  Definition iset := if width =? 32 then RV32I else RV64I.\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  Ltac simulate'_step :=\n    first [ eapply go_loadWord_sep ; simpl in *; simpl_word_exprs word_ok; [sidecondition..|]\n          | eapply go_storeWord_sep; simpl in *; simpl_word_exprs word_ok; [sidecondition..|intros]\n          | simulate_step ].\n\n  Ltac simulate' := repeat simulate'_step.\n\n  Ltac run1det :=\n    eapply runsTo_det_step;\n    [ simulate';\n      match goal with\n      | |- ?mid = ?RHS =>\n        (* simpl RHS because mid will be instantiated to it and turn up again in the next step *)\n        is_evar mid; simpl; reflexivity\n      | |- _ => fail 10000 \"simulate' did not go through completely\"\n      end\n    | ].\n\n  Definition gallina_prog_1(v1 v2: word): word :=\n    word.srs (word.add v1 v2) (word.of_Z 1).\n\n  Lemma asm_prog_1_correct: forall (initial: MetricRiscvMachine) newPc R Rexec (v1 v2: word),\n      map.get initial.(getRegs) x1 = Some v1 ->\n      map.get initial.(getRegs) x2 = Some v2 ->\n      newPc = word.add initial.(getPc) (word.of_Z (4 * (Z.of_nat (List.length asm_prog_1)))) ->\n      subset (footpr (program iset initial.(getPc) asm_prog_1 * Rexec)%sep)\n             (of_list initial.(getXAddrs)) ->\n      (program iset initial.(getPc) asm_prog_1 * Rexec * R)%sep initial.(getMem) ->\n      initial.(getNextPc) = word.add initial.(getPc) (word.of_Z 4) ->\n      runsTo (mcomp_sat (run1 iset)) initial\n             (fun final =>\n                final.(getPc) = newPc /\\\n                final.(getNextPc) = add newPc (word.of_Z 4) /\\\n                subset (footpr (program iset initial.(getPc) asm_prog_1 * Rexec)%sep)\n                       (of_list final.(getXAddrs)) /\\\n                (program iset initial.(getPc) asm_prog_1 * Rexec * R)%sep final.(getMem) /\\\n                map.get final.(getRegs) x2 = Some (gallina_prog_1 v1 v2)).\n  Proof.\n    intros.\n    assert (valid_register x1). { unfold valid_register, x1. blia. }\n    assert (valid_register x2). { unfold valid_register, x2. blia. }\n    destruct_RiscvMachine initial.\n    unfold asm_prog_1 in *.\n    simpl in *. simp.\n    subst.\n    run1det.\n    run1det.\n    eapply runsToDone.\n    simpl.\n    repeat split; first [ solve_word_eq word_ok | assumption | idtac ].\n    apply map.get_put_same.\n  Qed.\n\n  Opaque asm_prog_1.\n\n  Definition gallina_prog_2(v1 v2: w32): word :=\n    gallina_prog_1 (word.of_Z (BitOps.signExtend 32 (LittleEndian.combine 4 v1)))\n                   (word.of_Z (BitOps.signExtend 32 (LittleEndian.combine 4 v2))).\n\n  Arguments LittleEndian.combine: simpl never.\n\n  Axiom fix_updated_mem_TODO: False.\n  Axiom fix_footpr_TODO: False.\n\n  Arguments Z.add: simpl never.\n  Arguments Z.mul: simpl never.\n  Arguments Z.of_nat: simpl never.\n\n  Lemma asm_prog_2_correct: forall (initial: MetricRiscvMachine) newPc\n                                  (argvars resvars: list Register) R Rexec (v1 v2 dummy: w32),\n      newPc = word.add initial.(getPc) (word.of_Z (4 * Z.of_nat (List.length asm_prog_2))) ->\n      subset (footpr (program iset initial.(getPc) asm_prog_2 * Rexec)%sep)\n             (of_list initial.(getXAddrs)) ->\n      (program iset initial.(getPc) asm_prog_2 * Rexec *\n       ptsto_bytes 4 (word.of_Z input_ptr) v1 *\n       ptsto_bytes 4 (word.of_Z (input_ptr+4)) v2 *\n       ptsto_bytes 4 (word.of_Z output_ptr) dummy * R)%sep initial.(getMem) ->\n      initial.(getNextPc) = word.add initial.(getPc) (word.of_Z 4) ->\n      runsTo (mcomp_sat (run1 iset)) initial\n             (fun final =>\n                final.(getPc) = newPc /\\\n                final.(getNextPc) = add newPc (word.of_Z 4) /\\\n                subset (footpr (program iset initial.(getPc) asm_prog_2 * Rexec)%sep)\n                       (of_list final.(getXAddrs)) /\\\n                (program iset initial.(getPc) asm_prog_2 * Rexec * R)%sep final.(getMem) /\\\n                map.get final.(getRegs) x2 = Some (gallina_prog_2 v1 v2)).\n  Proof.\n    intros.\n    assert (valid_register x1). { unfold valid_register, x1. blia. }\n    assert (valid_register x2). { unfold valid_register, x2. blia. }\n    destruct_RiscvMachine initial.\n    unfold asm_prog_2 in *.\n    simpl in *.\n    unfold program in *.\n    subst.\n    simpl.\n    run1det.\n    run1det.\n\n(* TODO integrate changes into GoFlatToRiscv *)\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                                 wcancel_assumption\n  | H: subset (footpr _) _ |- subset (footpr ?F) _ =>\n    tryif is_evar F then\n      eassumption\n    else\n      (simpl in H |- *; eapply rearrange_footpr_subset; [ exact H | solve [wwcancel] ])\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 using valid_FlatImp_var_implies_valid_register,\n                              valid_FlatImp_vars_bcond_implies_valid_registers_bcond]\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.store ?sz ?m ?addr ?val = Some ?m' => eassumption\n  | |- _ => sidecondition_hook\n  end.\n\n\n    eapply runsTo_trans. {\n      eapply asm_prog_1_correct; simpl; try sidecondition.\n      rewrite map.get_put_diff by (unfold x1, x2; blia).\n      apply map.get_put_same.\n    }\n    simpl.\n    intros middle (? & ? & ? & ? & ?).\n    destruct_RiscvMachine middle. simpl in *.\n    subst. simp.\n\n    (* TODO matching up addresses should work automatically *)\n    replace (@word.add _ word\n              (@word.add _ word\n                 (@word.add _ word initial_pc (@word.of_Z _ word 4))\n                 (@word.of_Z _ word 4))\n              (@word.of_Z _ word\n                 (@word.unsigned _ word (@word.of_Z _ word 4) *\n                  BinInt.Z.of_nat (@Datatypes.length Instruction asm_prog_1))))\n      with (@word.add _ word\n        (@word.add _ word (@word.add _ word initial_pc (@word.of_Z _ word 4))\n           (@word.of_Z _ word 4))\n        (@word.mul _ word (@word.of_Z _ word 4)\n           (@word.of_Z _ word (Z.of_nat (@Datatypes.length Instruction asm_prog_1)))))\n      in H1; cycle 1. {\n      clear -word_ok.\n      change BinInt.Z.of_nat with Z.of_nat in *.\n      f_equal.\n      apply word.unsigned_inj.\n      rewrite word.unsigned_mul.\n      rewrite word.unsigned_of_Z at 2. unfold word.wrap.\n      rewrite (word.unsigned_of_Z (4 mod 2 ^ width * Z.of_nat (Datatypes.length asm_prog_1))).\n      rewrite! word.unsigned_of_Z. unfold word.wrap.\n      apply Zmult_mod_idemp_r.\n    }\n\n    run1det.\n    eapply runsToDone.\n    simpl.\n    repeat split.\n    - solve_word_eq word_ok.\n    - solve_word_eq word_ok.\n    - (* TODO *) case fix_footpr_TODO.\n    - (* TODO *) case fix_updated_mem_TODO.\n    - assumption.\n  Qed.\n\nEnd Verif.\n\n(* Print Assumptions asm_prog_2_correct. *)\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/AssemblyVerif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1993527444655677}}
{"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 Dots.\n\nRequire Import ValidationUtil.\n\n\nHint Rewrite def_eqtp : prepare.\n\n\nLemma eqtpForm_valid : eqtpForm_obligation.\nProof.\nprepare.\nintros G a b ext1 ext0 Ha Hb.\napply tr_eqtype_formation; auto.\nQed.\n\n\nLemma eqtpEq_valid : eqtpEq_obligation.\nProof.\nprepare.\nintros G a b c d ext1 ext0 Hab Hcd.\napply tr_eqtype_formation; auto.\nQed.\n\n\nLemma eqtpFormUniv_valid : eqtpFormUniv_obligation.\nProof.\nprepare.\nintros G a b i ext1 ext0 Ha Hb.\napply tr_eqtype_formation_univ; auto.\nQed.\n\n\nLemma eqtpEqUniv_valid : eqtpEqUniv_obligation.\nProof.\nprepare.\nintros G a b c d i ext1 ext0 Hab Hcd.\napply tr_eqtype_formation_univ; auto.\nQed.\n\n\nLemma eqtpIntro_valid : eqtpIntro_obligation.\nProof.\nprepare.\nintros G a b ext0 H.\nauto.\nQed.\n\n\nLemma eqtpElim_valid : eqtpElim_obligation.\nProof.\nprepare.\nintros G a b p ext0 H.\nauto.\nQed.\n\n\nLemma eqtpExt_valid : eqtpExt_obligation.\nProof.\nunfoldtop.\nintros G a b p q ext1 ext0 Hp Hq.\nunfold Defs.dof in * |- *.\nautorewrite with prepare in Hp, Hq |- *.\nunfold Defs.triv.\napply tr_equal_intro.\napply (tr_transitivity _ _ triv).\n  {\n  apply tr_eqtype_eta; auto.\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  apply tr_symmetry.\n  apply tr_eqtype_eta; auto.\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\nQed.\n\n\nLemma eqtpLeft_valid : eqtpLeft_obligation.\nProof.\nprepare.\nintros G1 G2 a b c m H.\nunfold Defs.triv in H.\napply tr_eqtype_eta_hyp; auto.\nQed.\n\n\nLemma eqtpFunct_valid : eqtpFunct_obligation.\nProof.\nprepare.\nintros G a b m n ext1 ext0 Hb Hmn.\neapply tr_functionality; eauto.\nQed.\n\n\nLemma equivalenceOf_valid : equivalenceOf_obligation.\nProof.\nprepare.\nintros G a b m ext1 ext0 Hab Hm.\neapply tr_eqtype_convert; eauto.\nQed.\n\n\nLemma equivalenceEq_valid : equivalenceEq_obligation.\nProof.\nprepare.\nintros G a b m n ext1 ext0 Hab Hmn.\neapply tr_eqtype_convert; eauto.\nQed.\n\n\nLemma equivalence_valid : equivalence_obligation.\nProof.\nprepare.\nintros G a b ext0 m Hab Hm.\neapply tr_eqtype_convert; eauto.\nQed.\n\n\nLemma equivalenceLeft_valid : equivalenceLeft_obligation.\nProof.\nprepare.\nintros G1 G2 a b c ext0 m Hab Hm.\nreplace (deq m m c) with (substj (dot triv id) (deq (subst sh1 m) (subst sh1 m) (subst sh1 c))) by (simpsub; auto).\nset (k := length G2).\napply (tr_generalize _ (subst (sh (S k)) (eqtype a a)) triv).\n  {\n  simpsub.\n  fold (deqtype (subst (sh (S k)) a) (subst (sh (S k)) a)).\n  apply (tr_inhabitation_formation _ (var k) (var k)).\n  eapply hypothesis; eauto.\n  eapply (index_app_right _ _ _ 0).\n  apply index_0.\n  }\neapply (exchange_1_n _ G2 _ []).\n  {\n  simpsub.\n  rewrite <- compose_assoc.\n  rewrite -> compose_sh_unlift_ge; try omega.\n  replace (S k - length G2) with 1 by omega.\n  simpsub.\n  reflexivity.\n  }\nsimpsub.\nrewrite -> compose_sh_unlift_ge; try omega.\nreplace (S k - length G2) with 1 by omega.\ncbn [List.app].\nrewrite <- (compose_sh_sh _ 1 k).\nrewrite <- under_dots.\napply (exchange_1_1 _ _ _ (substctx sh1 G2)).\n  {\n  simpsub.\n  reflexivity.\n  }\nsimpsub.\nrewrite -> length_substctx.\nfold k.\nrewrite <- compose_under.\nsimpsub.\neapply tr_eqtype_convert_hyp; eauto.\ncut (tr (substctx (dot (var 0) (sh 2)) G2 ++ [hyp_tm (subst (sh 1) b)] ++ hyp_tm (eqtype a a) :: G1) (deq (subst (under k (dot (var 0) (sh 2))) m) (subst (under k (dot (var 0) (sh 2))) m) (subst (under k (dot (var 0) (sh 2))) c))).\n  {\n  intro H.\n  cbn [List.app] in H.\n  exact H.\n  }\nrewrite -> app_assoc.\napply (weakening _ [_] _).\n  {\n  cbn [length unlift].\n  simpsub.\n  rewrite -> substctx_append.\n  cbn [length].\n  simpsub.\n  reflexivity.\n  }\n\n  {\n  cbn [length unlift].\n  simpsub.\n  rewrite -> app_length.\n  rewrite length_substctx.\n  cbn [length].\n  fold k.\n  rewrite <- under_sum.\n  rewrite <- compose_under.\n  simpsub.\n  reflexivity.\n  }\ncbn [length unlift].\nrewrite -> app_length.\nrewrite -> length_substctx.\ncbn [length].\nsimpsub.\nrewrite <- under_sum.\nfold k.\nrewrite <- compose_under.\nsimpsub.\nrewrite -> substctx_append.\ncbn [length].\nsimpsub.\nrewrite <- app_assoc.\ncbn [List.app].\nrewrite -> (substctx_eqsub _#4 (eqsub_symm _#3 (eqsub_expand_id _))).\nsimpsub.\nrewrite -> !(subst_eqsub _#4 (eqsub_symm _#3 (eqsub_under _ k _ _ (eqsub_expand_id _)))).\nsimpsub.\nsimpsubin Hm.\nexact Hm.\nQed.\n\n\nLemma eqtpRefl_valid : eqtpRefl_obligation.\nProof.\nprepare.\nintros G a ext0 H.\nauto.\nQed.\n\n\nLemma eqtpSymm_valid : eqtpSymm_obligation.\nProof.\nprepare.\nintros G a b ext0 H.\napply tr_eqtype_symmetry; auto.\nQed.\n\n\nLemma eqtpTrans_valid : eqtpTrans_obligation.\nProof.\nprepare.\nintros G a b c ext1 ext0 Hab Hbc.\neapply tr_eqtype_transitivity; eauto.\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/ValidationEqtp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1993527367682031}}
{"text": "Require 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 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.\nRequire Import Behavior.\n\nRequire Import PromiseConsistent.\nRequire Import Cover.\nRequire Import MemorySplit.\nRequire Import MemoryMerge.\nRequire Import FulfillStep.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\nRequire Import LowerMemory.\nRequire Import FulfillStep.\nRequire Import ReorderStepPromise.\nRequire Import Pred.\nRequire Import Trace.\n\nRequire Import SeqLib.\nRequire Import Delayed.\n\nSet Implicit Arguments.\n\n\nSection DStep.\n  Variable lang: language.\n\n  (** delayed steps *)\n\n  Variant dstep (e: ThreadEvent.t) (e1 e4: Thread.t lang): Prop :=\n  | dstep_intro\n      e2 e3 pf\n      (PROMISES: rtc (tau (@pred_step is_promise _)) e1 e2)\n      (LOWERS: rtc (tau lower_step) e2 e3)\n      (STEP_RELEASE: Thread.step pf e e3 e4)\n      (EVENT_RELEASE: release_event e)\n  .\n\n  Variant dsteps: forall (e: MachineEvent.t) (e1 e2: Thread.t lang), Prop :=\n  | dsteps_promises\n      e1 e2 e3\n      (DSTEPS: rtc (tau dstep) e1 e2)\n      (PROMISES: rtc (tau (@pred_step is_promise _)) e2 e3):\n    dsteps MachineEvent.silent e1 e3\n  | dsteps_step\n      e te e1 e2 e3\n      (DSTEPS: rtc (tau dstep) e1 e2)\n      (DSTEP: dstep te e2 e3)\n      (EVENT: e = ThreadEvent.get_machine_event te):\n    dsteps e e1 e3\n  .\n\n  Definition delayed_consistent (e1: Thread.t lang): Prop :=\n    forall mem1 (CAP: Memory.cap e1.(Thread.memory) mem1),\n    exists e e2,\n      (<<DSTEPS: dsteps\n                   e (Thread.mk _ (Thread.state e1) (Thread.local e1) (Thread.sc e1) mem1) e2>>) /\\\n      ((<<FAILURE: e = MachineEvent.failure>>) \\/\n       (exists e3,\n           (<<SILENT: e = MachineEvent.silent>>) /\\\n           (<<STEPS: rtc (tau lower_step) e2 e3>>) /\\\n           (<<PROMISES: Local.promises (Thread.local e3) = Memory.bot>>))).\n\n  Lemma dstep_rtc_all_step\n        e e1 e2\n        (STEP: dstep e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    etrans.\n    { eapply rtc_implies; try eapply PROMISES.\n      i. inv H. inv TSTEP. econs. eauto.\n    }\n    etrans.\n    { eapply rtc_implies; try eapply LOWERS.\n      i. inv H. inv TSTEP. econs. econs. econs 2. eauto.\n    }\n    econs 2; eauto. econs. econs. eauto.\n  Qed.\n\n  Lemma dstep_rtc_tau_step\n        e e1 e2\n        (STEP: dstep e e1 e2)\n        (SILENT: ThreadEvent.get_machine_event e = MachineEvent.silent):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    etrans.\n    { eapply rtc_implies; try eapply PROMISES.\n      i. inv H. inv TSTEP. econs; eauto.\n    }\n    etrans.\n    { eapply rtc_implies; try eapply LOWERS.\n      i. inv H. inv TSTEP. econs; eauto. econs. econs 2. eauto.\n    }\n    econs 2; eauto. econs; eauto. econs. eauto.\n  Qed.\n\n  Lemma rtc_dstep_rtc_tau_step\n        e1 e2\n        (STEP: rtc (tau dstep) e1 e2):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    induction STEP; eauto. inv H.\n    exploit dstep_rtc_tau_step; eauto. i.\n    etrans; eauto.\n  Qed.\n\n  Lemma dsteps_rtc_all_step\n        e e1 e2\n        (STEP: dsteps e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      etrans.\n      + eapply rtc_implies; try eapply x0.\n        i. inv H. econs. eauto.\n      + eapply rtc_implies; try eapply PROMISES.\n        i. inv H. inv TSTEP. econs. eauto.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit dstep_rtc_all_step; eauto. i.\n      etrans; [|eauto].\n      eapply rtc_implies; try eapply x0.\n      i. inv H. econs. eauto.\n  Qed.\n\n  Lemma dsteps_rtc_tau_step\n        e e1 e2\n        (STEP: dsteps e e1 e2)\n        (SILENT: e = MachineEvent.silent):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      etrans; eauto.\n      eapply rtc_implies; try eapply PROMISES.\n      i. inv H0. inv TSTEP. econs; eauto.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit dstep_rtc_tau_step; eauto. i.\n      etrans; eauto.\n  Qed.\n\n  Lemma dsteps_plus_step\n        e e1 e3\n        (STEP: dsteps e e1 e3):\n    e = MachineEvent.silent /\\ e1 = e3 \\/\n    exists e2 pf te,\n      (<<STEPS: rtc (@Thread.tau_step lang) e1 e2>>) /\\\n      (<<STEP: Thread.step pf te e2 e3>>) /\\\n      (<<EVENT: ThreadEvent.get_machine_event te = e>>).\n  Proof.\n    inv STEP.\n    { exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit rtc_implies; try eapply PROMISES.\n      { i. instantiate (1 := @Thread.tau_step lang).\n        inv H. inv TSTEP. econs; eauto.\n      }\n      i. rewrite x1 in x0. clear e2 DSTEPS PROMISES x1.\n      exploit rtc_tail; try exact x0. i. des; eauto.\n      right. inv x2. inv TSTEP.\n      esplits; eauto.\n    }\n    { exploit rtc_dstep_rtc_tau_step; eauto. i.\n      inv DSTEP.\n      exploit rtc_implies; try eapply PROMISES; i.\n      { i. instantiate (1 := @Thread.tau_step lang).\n        inv H. inv TSTEP. econs; eauto.\n      }\n      exploit rtc_implies; try eapply LOWERS; i.\n      { i. instantiate (1 := @Thread.tau_step lang).\n        inv H. inv TSTEP. econs; eauto. econs. econs 2. eauto.\n      }\n      rewrite x2 in x1. rewrite x1 in x0.\n      clear x1 x2 DSTEPS PROMISES LOWERS.\n      right. esplits; eauto.\n    }\n  Qed.\n\n\n  (** non release steps *)\n\n  Variant nr_step (e: ThreadEvent.t) (e1 e2: Thread.t lang): Prop :=\n  | nr_step_intro\n      pf\n      (STEP: Thread.step pf e e1 e2)\n      (RELEASE: ~ release_event e)\n  .\n\n  Variant nrp_step (e: ThreadEvent.t) (e1 e3: Thread.t lang): Prop :=\n  | nrp_step_intro\n      e2 pf\n      (STEPS: rtc (tau nr_step) e1 e2)\n      (STEP: Thread.step pf e e2 e3)\n      (RELEASE: release_event e)\n  .\n\n  Variant nrp_steps: forall (e: MachineEvent.t) (e1 e2: Thread.t lang), Prop :=\n  | nrp_steps_non_release\n      e1 e2 e3\n      (STEPS: rtc (tau nrp_step) e1 e2)\n      (NSTEPS: rtc (tau nr_step) e2 e3):\n    nrp_steps MachineEvent.silent e1 e3\n  | nrp_steps_release\n      e e1 e2 e3\n      (STEPS: rtc (tau nrp_step) e1 e2)\n      (STEP: nrp_step e e2 e3):\n    nrp_steps (ThreadEvent.get_machine_event e) e1 e3\n  .\n\n  Lemma nrp_step_rtc_all_step\n        e e1 e2\n        (STEP: nrp_step e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP. etrans.\n    - eapply rtc_implies; try eapply STEPS.\n      i. inv H. inv TSTEP. econs. econs. eauto.\n    - econs 2; eauto. econs. econs. eauto.\n  Qed.\n\n  Lemma nrp_step_rtc_tau_step\n        e e1 e2\n        (STEP: nrp_step e e1 e2)\n        (SILENT: ThreadEvent.get_machine_event e = MachineEvent.silent):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    inv STEP. etrans.\n    - eapply rtc_implies; try eapply STEPS.\n      i. inv H. inv TSTEP. econs; eauto. econs. eauto.\n    - econs 2; eauto. econs; eauto. econs. eauto.\n  Qed.\n\n  Lemma rtc_nrp_step_rtc_tau_step\n        e1 e2\n        (STEP: rtc (tau nrp_step) e1 e2):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    induction STEP; eauto. inv H.\n    exploit nrp_step_rtc_tau_step; eauto. i.\n    etrans; eauto.\n  Qed.\n\n  Lemma nrp_steps_rtc_all_step\n        e e1 e2\n        (STEP: nrp_steps e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    - etrans.\n      + eapply rtc_implies; try eapply rtc_nrp_step_rtc_tau_step; eauto.\n        i. inv H. econs. eauto.\n      + eapply rtc_implies; try eapply NSTEPS.\n        i. inv H. inv TSTEP. econs. econs. eauto.\n    - etrans.\n      + eapply rtc_implies; try eapply rtc_nrp_step_rtc_tau_step; eauto.\n        i. inv H. econs. eauto.\n      + eapply nrp_step_rtc_all_step; eauto.\n  Qed.\n\n  Lemma non_release_silent\n        e\n        (RELEASE: ~ release_event e):\n    ThreadEvent.get_machine_event e = MachineEvent.silent.\n  Proof.\n    destruct e; ss.\n  Qed.\n\n  Lemma lower_event_release\n        e_src e_tgt\n        (LOWER: lower_event e_src e_tgt):\n    release_event e_src <-> release_event e_tgt.\n  Proof.\n    inv LOWER; ss.\n  Qed.\n\n  Lemma lower_event_machine_event\n        e_src e_tgt\n        (LOWER: lower_event e_src e_tgt):\n    ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt.\n  Proof.\n    inv LOWER; ss.\n  Qed.\n\n  Lemma rtc_tau_step_nrp_steps\n        e1 e2\n        (STEPS: rtc (@Thread.tau_step _) e1 e2):\n    nrp_steps MachineEvent.silent e1 e2.\n  Proof.\n    induction STEPS.\n    { econs; refl. }\n    clear - H IHSTEPS.\n    inv H. inv TSTEP.\n    destruct (classic (release_event e)).\n    { inv IHSTEPS.\n      { econs 1; try exact NSTEPS.\n        econs 2; try exact STEPS.\n        econs; try exact EVENT.\n        econs; try refl; eauto.\n      }\n      { econs 2; try exact STEP0.\n        econs 2; try exact STEPS.\n        econs; try exact EVENT.\n        econs; try refl; eauto.\n      }\n    }\n    { inv IHSTEPS.\n      { inv STEPS.\n        { econs 1; [refl|].\n          econs 2; try exact NSTEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n        { econs 1; try exact NSTEPS.\n          econs 2; try exact H1.\n          inv H0. econs; try exact EVENT0.\n          inv TSTEP. econs; try exact STEP0; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT. econs; eauto.\n        }\n      }\n      { inv STEPS.\n        { econs 2; [refl|].\n          inv STEP0. econs; try exact STEP1; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n        { econs 2; try exact STEP0.\n          econs 2; try exact H2.\n          inv H0. econs; try exact EVENT0.\n          inv TSTEP. econs; try exact STEP1; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n      }\n    }\n  Qed.\n\n  Lemma plus_step_nrp_steps\n        pf e e1 e2 e3\n        (STEPS: rtc (@Thread.tau_step _) e1 e2)\n        (STEP: Thread.step pf e e2 e3):\n    nrp_steps (ThreadEvent.get_machine_event e) e1 e3.\n  Proof.\n    induction STEPS; i.\n    { destruct (classic (release_event e)).\n      - econs 2; try refl. econs; try refl; eauto.\n      - rewrite non_release_silent; eauto.\n        econs 1; try refl. econs 2; try refl.\n        econs; try eapply non_release_silent; eauto.\n        econs; eauto.\n    }\n    exploit IHSTEPS; eauto. intros x0. clear IHSTEPS.\n    clear - H x0.\n    inv H. inv TSTEP.\n    destruct (classic (release_event e0)).\n    { inv x0.\n      { econs 1; try exact NSTEPS.\n        econs 2; try exact STEPS.\n        econs; try exact EVENT.\n        econs; try refl; eauto.\n      }\n      { econs 2; try exact STEP0.\n        econs 2; try exact STEPS.\n        econs; try exact EVENT.\n        econs; try refl; eauto.\n      }\n    }\n    { inv x0.\n      { inv STEPS.\n        { econs 1; [refl|].\n          econs 2; try exact NSTEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n        { econs 1; try exact NSTEPS.\n          econs 2; try exact H2.\n          inv H0. econs; try exact EVENT0.\n          inv TSTEP. econs; try exact STEP0; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT. econs; eauto.\n        }\n      }\n      { inv STEPS.\n        { econs 2; [refl|].\n          inv STEP0. econs; try exact STEP1; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n        { econs 2; try exact STEP0.\n          econs 2; try exact H2.\n          inv H0. econs; try exact EVENT0.\n          inv TSTEP. econs; try exact STEP1; ss.\n          econs 2; try exact STEPS.\n          econs; try exact EVENT.\n          econs; eauto.\n        }\n      }\n    }\n  Qed.\n\n\n  (** steps to delayed steps *)\n\n  Variant delayed_thread (e_src e_lower: Thread.t lang): Prop :=\n  | delayed_thread_intro\n      (SC: Thread.sc e_src = Thread.sc e_lower)\n      (MEM: Thread.memory e_src = Thread.memory e_lower)\n      (DELAYED: delayed (Thread.state e_src) (Thread.state e_lower)\n                        (Thread.local e_src) (Thread.local e_lower)\n                        (Thread.sc e_lower) (Thread.memory e_lower))\n  .\n\n  Lemma delayed_thread_refl\n        e\n        (WF: Local.wf (Thread.local e) (Thread.memory e))\n        (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n        (MEM: Memory.closed (Thread.memory e)):\n    delayed_thread e e.\n  Proof.\n    econs; eauto. eapply delayed_refl; eauto.\n  Qed.\n\n  Lemma delayed_wf_src\n        e_src e_lower\n        (DELAYED: delayed_thread e_src e_lower):\n    (<<WF: Local.wf (Thread.local e_src) (Thread.memory e_src)>>) /\\\n    (<<SC: Memory.closed_timemap (Thread.sc e_src) (Thread.memory e_src)>>) /\\\n    (<<MEM: Memory.closed (Thread.memory e_src)>>).\n  Proof.\n    inv DELAYED. unfold delayed in *. des.\n    rewrite SC, MEM in *. auto.\n  Qed.\n\n  Variant lower_delayed_thread (e_src e_tgt: Thread.t lang): Prop :=\n  | lower_delayed_thread_intro\n      e_lower\n      (LOWER: lower_thread e_lower e_tgt)\n      (DELAYED: delayed_thread e_src e_lower)\n  .\n\n  Lemma lower_delayed_thread_refl\n        e\n        (WF: Local.wf (Thread.local e) (Thread.memory e))\n        (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n        (MEM: Memory.closed (Thread.memory e)):\n    lower_delayed_thread e e.\n  Proof.\n    econs; try refl.\n    eapply delayed_thread_refl; eauto.\n  Qed.\n\n  Lemma ld_wf_src\n        e_src e_tgt\n        (LD: lower_delayed_thread e_src e_tgt):\n    (<<WF: Local.wf (Thread.local e_src) (Thread.memory e_src)>>) /\\\n    (<<SC: Memory.closed_timemap (Thread.sc e_src) (Thread.memory e_src)>>) /\\\n    (<<MEM: Memory.closed (Thread.memory e_src)>>).\n  Proof.\n    inv LD. eapply delayed_wf_src; eauto.\n  Qed.\n\n  Lemma delayed_rtc_nr_step_aux\n        (st0 st1 st2: Language.state lang) lc0 lc1 lc2\n        mem1 sc1 mem2 sc2\n        (STEP: rtc (tau nr_step) (Thread.mk _ st1 lc1 sc1 mem1) (Thread.mk _ st2 lc2 sc2 mem2))\n        (CONS: Local.promise_consistent lc2)\n        (DELAYED: delayed st0 st1 lc0 lc1 sc1 mem1)\n    :\n      exists lc0',\n        (<<PROMISES: rtc (tau (@pred_step is_promise _)) (Thread.mk _ st0 lc0 sc1 mem1) (Thread.mk _ st0 lc0' sc2 mem2)>>) /\\\n        (<<DELAYED: delayed st0 st2 lc0' lc2 sc2 mem2>>).\n  Proof.\n    remember (Thread.mk _ st1 lc1 sc1 mem1) as e1.\n    remember (Thread.mk _ st2 lc2 sc2 mem2) as e2.\n    revert lc0 st1 lc1 sc1 mem1 Heqe1 st2 lc2 sc2 mem2 Heqe2 CONS DELAYED.\n    induction STEP; i; subst.\n    { inv Heqe2. esplits; eauto. }\n    destruct y as [st lc sc mem].\n    inv H. inv TSTEP.\n    exploit delayed_step; try exact STEP0; try exact DELAYED; eauto.\n    { exploit Thread.step_future; try exact STEP0; try apply DELAYED. s. i. des.\n      hexploit rtc_all_step_promise_consistent;\n        try eapply rtc_implies; try eapply STEP; eauto; ss.\n      i. inv H. inv TSTEP. econs. econs. eauto.\n    }\n    i. des.\n    exploit IHSTEP; try exact DELAYED0; eauto. i. des.\n    esplits; [etrans; eauto|].\n    unfold delayed in *. des. splits; eauto.\n  Qed.\n\n  Lemma delayed_rtc_nr_step\n        e1_src e1_lower e2_lower\n        (DELAYED: delayed_thread e1_src e1_lower)\n        (STEP: rtc (tau nr_step) e1_lower e2_lower)\n        (CONS: Local.promise_consistent (Thread.local e2_lower)):\n      exists e2_src,\n        (<<PROMISES: rtc (tau (@pred_step is_promise _)) e1_src e2_src>>) /\\\n        (<<DELAYED: delayed_thread e2_src e2_lower>>).\n  Proof.\n    destruct e1_src as [st1_src lc1_src sc1_src mem1_src],\n             e1_lower as [st1_lower lc1_lower sc1_lower mem1_lower],\n             e2_lower as [st2_lower lc2_lower sc2_lower mem2_lower].\n    inv DELAYED. ss. subst.\n    exploit delayed_rtc_nr_step_aux; try exact DELAYED0; eauto. i. des.\n    esplits; eauto.\n    econs; ss; eauto.\n  Qed.\n\n  Lemma delayed_nrp_step\n        e1_src e1_lower e_lower e2_lower\n        (DELAYED: delayed_thread e1_src e1_lower)\n        (STEP: nrp_step e_lower e1_lower e2_lower)\n        (CONS: Local.promise_consistent (Thread.local e2_lower)):\n    exists e_src e2_src,\n      (<<STEP_SRC: dstep e_src e1_src e2_src>>) /\\\n      (<<EVENT: lower_event e_src e_lower>>) /\\\n      (<<LOWER: lower_thread e2_src e2_lower>>).\n  Proof.\n    inv DELAYED. inv STEP.\n    destruct e1_src as [st1_src lc1_src sc1_src mem1_src],\n             e1_lower as [st1_lower lc1_lower sc1_lower mem1_lower],\n             e2 as [st2_lower lc2_lower sc2_lower mem2_lower].\n    ss. subst.\n    exploit delayed_rtc_nr_step_aux; try exact DELAYED0; eauto.\n    { exploit Thread.rtc_all_step_future;\n        try eapply rtc_implies; try exact STEPS; try apply DELAYED0.\n      { i. inv H. inv TSTEP. econs. econs. eauto. }\n      s. i. des.\n      hexploit step_promise_consistent; try exact STEP0; eauto.\n    }\n    i. des.\n    unfold delayed in DELAYED. des.\n    hexploit Thread.rtc_all_step_future;\n      try eapply rtc_implies; try exact STEPS0; ss; try apply DELAYED0.\n    { i. inv H. inv TSTEP. econs. econs. econs 2; eauto. }\n    i. des.\n    destruct e2_lower as [st3_lower lc3_lower sc3_lower mem3_lower]. ss.\n    exploit lower_memory_thread_step; try exact STEP0;\n      try exact LOCAL; try exact MEM0; eauto. i. des.\n    esplits.\n    - econs; eauto. erewrite lower_event_release; eauto.\n    - ss.\n    - econs; eauto.\n  Qed.\n\n  Lemma lower_rtc_nr_step\n        e1_lower e1_tgt e2_tgt\n        (LOWER1: lower_thread e1_lower e1_tgt)\n        (WF1_LOWER: Local.wf (Thread.local e1_lower) (Thread.memory e1_lower))\n        (SC1_LOWER: Memory.closed_timemap (Thread.sc e1_lower) (Thread.memory e1_lower))\n        (CLOSED1_LOWER: Memory.closed (Thread.memory e1_lower))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: rtc (tau nr_step) e1_tgt e2_tgt):\n      exists e2_lower,\n        (<<STEP_LOWER: rtc (tau nr_step) e1_lower e2_lower>>) /\\\n        (<<LOWER2: lower_thread e2_lower e2_tgt>>).\n  Proof.\n    revert e1_lower LOWER1 WF1_LOWER SC1_LOWER CLOSED1_LOWER.\n    induction STEP_TGT; i; eauto.\n    inv H. inv TSTEP.\n    exploit lower_thread_step; try exact LD1; eauto. i. des.\n    exploit Thread.step_future; try exact STEP; eauto. i. des.\n    exploit Thread.step_future; try exact STEP0; eauto. i. des.\n    exploit IHSTEP_TGT; try exact LOWER; eauto. i. des.\n    esplits; try exact LOWER2.\n    econs 2; eauto. econs.\n    - econs; [eauto|]. erewrite lower_event_release; eauto.\n    - erewrite lower_event_machine_event; eauto.\n  Qed.\n\n  Lemma lower_nrp_step\n        e1_lower e_tgt e1_tgt e2_tgt\n        (LOWER1: lower_thread e1_lower e1_tgt)\n        (WF1_LOWER: Local.wf (Thread.local e1_lower) (Thread.memory e1_lower))\n        (SC1_LOWER: Memory.closed_timemap (Thread.sc e1_lower) (Thread.memory e1_lower))\n        (CLOSED1_LOWER: Memory.closed (Thread.memory e1_lower))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: nrp_step e_tgt e1_tgt e2_tgt):\n      exists e_src e2_lower,\n        (<<STEP_LOWER: nrp_step e_src e1_lower e2_lower>>) /\\\n        (<<EVENT: lower_event e_src e_tgt>>) /\\\n        (<<LOWER2: lower_thread e2_lower e2_tgt>>).\n  Proof.\n    inv STEP_TGT.\n    exploit lower_rtc_nr_step; try exact LOWER1; eauto. i. des.\n    exploit Thread.rtc_tau_step_future; try eapply rtc_implies; try exact STEPS; eauto.\n    { i. inv H. inv TSTEP. econs; eauto. econs. eauto. }\n    i. des.\n    exploit Thread.rtc_tau_step_future; try eapply rtc_implies; try exact STEP_LOWER; eauto.\n    { i. inv H. inv TSTEP. econs; eauto. econs. eauto. }\n    i. des.\n    exploit lower_thread_step; try exact STEP; eauto. i. des.\n    esplits; eauto. econs; eauto.\n    erewrite lower_event_release; eauto.\n  Qed.\n\n  Lemma ld_rtc_nr_step\n        e1_src e1_tgt e2_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP: rtc (tau nr_step) e1_tgt e2_tgt)\n        (CONS: Local.promise_consistent (Thread.local e2_tgt)):\n      exists e2_src,\n        (<<PROMISES: rtc (tau (@pred_step is_promise _)) e1_src e2_src>>) /\\\n        (<<LD2: lower_delayed_thread e2_src e2_tgt>>).\n  Proof.\n    inv LD1.\n    exploit lower_rtc_nr_step; try exact LOWER; try apply DELAYED; eauto. i. des.\n    hexploit lower_thread_consistent; try apply LOWER2; eauto. i.\n    exploit delayed_rtc_nr_step; try exact DELAYED; eauto. i. des.\n    esplits; eauto. econs; eauto.\n  Qed.\n\n  Lemma ld_nrp_step\n        e1_src e1_tgt e_tgt e2_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP: nrp_step e_tgt e1_tgt e2_tgt)\n        (CONS: Local.promise_consistent (Thread.local e2_tgt)):\n      exists e_src e2_src,\n        (<<PROMISES: dstep e_src e1_src e2_src>>) /\\\n        (<<EVENT: lower_event e_src e_tgt>>) /\\\n        (<<LD2: lower_delayed_thread e2_src e2_tgt>>).\n  Proof.\n    inv LD1.\n    exploit lower_nrp_step; try exact LOWER; try apply DELAYED; eauto. i. des.\n    hexploit lower_thread_consistent; try apply LOWER2; eauto. i.\n    exploit delayed_nrp_step; try exact DELAYED; eauto. i. des.\n    exploit delayed_wf_src; eauto. i. des.\n    exploit Thread.rtc_all_step_future;\n      try eapply dstep_rtc_all_step; try exact STEP_SRC; eauto. i. des.\n    esplits; eauto.\n    - etrans; eauto.\n    - econs; try apply delayed_thread_refl; eauto. etrans; eauto.\n  Qed.\n\n  Lemma ld_rtc_nrp_step\n        e1_src e1_tgt e2_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP: rtc (tau nrp_step) e1_tgt e2_tgt)\n        (CONS: Local.promise_consistent (Thread.local e2_tgt)):\n      exists e2_src,\n        (<<PROMISES: rtc (tau dstep) e1_src e2_src>>) /\\\n        (<<LD2: lower_delayed_thread e2_src e2_tgt>>).\n  Proof.\n    revert e1_src LD1.\n    induction STEP; i; eauto. inv H.\n    exploit Thread.rtc_all_step_future;\n      try eapply nrp_step_rtc_all_step; try exact TSTEP; eauto. i. des.\n    exploit ld_nrp_step; try exact LD1; eauto.\n    { eapply rtc_tau_step_promise_consistent;\n        try eapply rtc_nrp_step_rtc_tau_step; try exact STEP; eauto.\n    }\n    i. des.\n    exploit IHSTEP; eauto. i. des.\n    esplits; [|eauto].\n    econs 2; eauto. econs; eauto.\n    erewrite lower_event_machine_event; eauto.\n  Qed.\n\n  Lemma ld_nrp_steps_dsteps\n        e1_src e1_tgt e_tgt e2_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP: nrp_steps e_tgt e1_tgt e2_tgt)\n        (CONS: Local.promise_consistent (Thread.local e2_tgt)):\n    exists e_src e2_src,\n      (<<STEP_SRC: dsteps e_src e1_src e2_src>>) /\\\n      (<<EVENT: e_src = e_tgt>>) /\\\n      (<<LD2: lower_delayed_thread e2_src e2_tgt>>).\n  Proof.\n    inv STEP.\n    { exploit Thread.rtc_tau_step_future;\n        try eapply rtc_nrp_step_rtc_tau_step; try exact STEPS; eauto. i. des.\n      exploit ld_rtc_nrp_step; eauto.\n      { eapply rtc_tau_step_promise_consistent;\n          try eapply rtc_implies; try exact NSTEPS; eauto.\n        i. inv H. inv TSTEP. econs; eauto. econs. eauto.\n      }\n      i. des.\n      exploit ld_rtc_nr_step; try exact LD2; eauto. i. des.\n      esplits; eauto. econs 1; eauto.\n    }\n    { exploit Thread.rtc_tau_step_future;\n        try eapply rtc_nrp_step_rtc_tau_step; try exact STEPS; eauto. i. des.\n      exploit ld_rtc_nrp_step; eauto.\n      { eapply rtc_all_step_promise_consistent;\n          try eapply nrp_step_rtc_all_step; try exact STEP0; eauto.\n      }\n      i. des.\n      exploit ld_nrp_step; try exact LD2; eauto. i. des.\n      esplits; eauto. econs 2; eauto.\n      exploit lower_event_machine_event; eauto.\n    }\n  Qed.\n\n  Lemma ld_rtc_tau_step_dsteps\n        e1_src e1_tgt e2_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS: rtc (@Thread.tau_step _) e1_tgt e2_tgt)\n        (CONS: Local.promise_consistent (Thread.local e2_tgt)):\n    exists e2_src,\n      (<<STEP_SRC: dsteps MachineEvent.silent e1_src e2_src>>) /\\\n      (<<LD2: lower_delayed_thread e2_src e2_tgt>>).\n  Proof.\n    exploit rtc_tau_step_nrp_steps; eauto. i.\n    exploit ld_nrp_steps_dsteps; eauto. i. des. subst. eauto.\n  Qed.\n\n  Lemma ld_plus_step_dsteps\n        e1_src e1_tgt pf e_tgt e2_tgt e3_tgt\n        (LD1: lower_delayed_thread e1_src e1_tgt)\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS: rtc (@Thread.tau_step _) e1_tgt e2_tgt)\n        (STEP: Thread.step pf e_tgt e2_tgt e3_tgt)\n        (CONS: Local.promise_consistent (Thread.local e3_tgt)):\n    exists e_src e3_src,\n      (<<STEP_SRC: dsteps e_src e1_src e3_src>>) /\\\n      (<<EVENT: e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n      (<<LD2: lower_delayed_thread e3_src e3_tgt>>).\n  Proof.\n    exploit plus_step_nrp_steps; eauto. i.\n    exploit ld_nrp_steps_dsteps; eauto.\n  Qed.\n\n  Lemma ld_future\n        e_src e_tgt\n        sc_src mem_src sc_tgt mem_tgt\n        (LD: lower_delayed_thread e_src e_tgt)\n        (SC: TimeMap.le sc_src sc_tgt)\n        (MEM: lower_memory mem_src mem_tgt)\n        (MEM_FUTURE_SRC: Memory.future (Thread.memory e_src) mem_src)\n        (WF_SRC: Local.wf (Thread.local e_src) mem_src)\n        (SC_SRC: Memory.closed_timemap sc_src mem_src)\n        (MEM_SRC: Memory.closed mem_src):\n    (<<LD_FUTURE: lower_delayed_thread\n                    (Thread.mk _ (Thread.state e_src) (Thread.local e_src) sc_src mem_src)\n                    (Thread.mk _ (Thread.state e_tgt) (Thread.local e_tgt) sc_tgt mem_tgt)>>).\n  Proof.\n    inv LD. econs.\n    - instantiate (1 := (Thread.mk _ (Thread.state e_lower) (Thread.local e_lower) sc_src mem_src)).\n      inv LOWER. econs; ss.\n    - inv DELAYED. econs; ss.\n      eapply delayed_future; try exact DELAYED0; ss.\n      rewrite <- MEM0.\n      apply Memory.future_future_weak; eauto.\n  Qed.\n\n  Lemma ld_cap\n        e_src e_tgt\n        cap_src cap_tgt\n        (LD: lower_delayed_thread e_src e_tgt)\n        (MEM_TGT: Memory.closed (Thread.memory e_tgt))\n        (CAP_SRC: Memory.cap (Thread.memory e_src) cap_src)\n        (CAP_TGT: Memory.cap (Thread.memory e_tgt) cap_tgt):\n    (<<LD_CAP: lower_delayed_thread\n                 (Thread.mk _ (Thread.state e_src) (Thread.local e_src) (Thread.sc e_src) cap_src)\n                 (Thread.mk _ (Thread.state e_tgt) (Thread.local e_tgt) (Thread.sc e_tgt) cap_tgt)>>).\n  Proof.\n    inv LD.\n    destruct e_src as [st_src lc_src sc_src mem_src],\n             e_lower as [st_lower lc_lower sc_lower mem_lower],\n             e_tgt as [st_tgt lc_tgt sc_tgt mem_tgt].\n    inv LOWER. inv DELAYED. ss. subst.\n    exploit lower_memory_cap; try exact MEMORY; eauto; try apply DELAYED0. i.\n    econs.\n    - instantiate (1 := Thread.mk _ st_tgt lc_lower sc_lower cap_src).\n      econs; ss.\n    - econs; ss.\n      eapply delayed_future; eauto.\n      + eapply Local.cap_wf; eauto. apply DELAYED0.\n      + eapply Memory.cap_closed_timemap; eauto. apply DELAYED0.\n      + eapply Memory.cap_closed; eauto. apply DELAYED0.\n      + eapply Memory.cap_future_weak; eauto. apply DELAYED0.\n  Qed.\n\n  Lemma ld_consistent\n        e_src e_tgt\n        (LD: lower_delayed_thread e_src e_tgt)\n        (WF_TGT: Local.wf (Thread.local e_tgt) (Thread.memory e_tgt))\n        (SC_TGT: Memory.closed_timemap (Thread.sc e_tgt) (Thread.memory e_tgt))\n        (CLOSED_TGT: Memory.closed (Thread.memory e_tgt))\n        (CONSISTENT_TGT: Thread.consistent e_tgt):\n    (<<CONSISTENT_SRC: delayed_consistent e_src>>).\n  Proof.\n    ii. exploit Memory.cap_exists; try apply CLOSED_TGT. i. des.\n    exploit ld_cap; try exact LD; eauto. i. des.\n    exploit CONSISTENT_TGT; eauto. unfold Thread.steps_failure. i. des.\n    { exploit ld_plus_step_dsteps; try exact x0; eauto; ss.\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.cap_closed_timemap; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { inv STEP_FAILURE; inv STEP; ss. inv LOCAL; ss; inv LOCAL0; ss. }\n      i. des.\n      rewrite EVENT_FAILURE in *. subst.\n      esplits; eauto.\n    }\n    { exploit ld_rtc_tau_step_dsteps; try exact x0; eauto; ss.\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.cap_closed_timemap; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { ii. rewrite PROMISES in *. rewrite Memory.bot_get in *. ss. }\n      i. des.\n      esplits; eauto. right.\n      inv LD2. inv DELAYED.\n      unfold delayed in *. des.\n      destruct e2_src, e_lower. ss. subst.\n      esplits; eauto. ss.\n      inv LOCAL. ss. inv LOWER. ss. inv LOCAL. ss.\n      rewrite <- H in *. ss.\n    }\n  Qed.\n\n  Lemma delayed_consistent_consistent\n        e\n        (CONSISTENT: delayed_consistent e):\n    (<<CONSISTENT: Thread.consistent e>>).\n  Proof.\n    ii. exploit CONSISTENT; eauto. i. des.\n    { left.\n      exploit dsteps_plus_step; eauto. i. des; subst; ss.\n      replace pf with true in *; cycle 1.\n      { inv STEP; inv STEP0; ss. }\n      unfold Thread.steps_failure. esplits; eauto.\n    }\n    { right.\n      exploit dsteps_rtc_tau_step; eauto. i.\n      esplits; try exact PROMISES.\n      etrans; eauto.\n      eapply rtc_implies; try exact STEPS.\n      i. inv H. inv TSTEP. econs; eauto. econs. econs 2. eauto.\n    }\n  Qed.\n\n  Lemma ld_terminal\n        e_src e_tgt\n        (LD: lower_delayed_thread e_src e_tgt)\n        (TERMINAL: Language.is_terminal _ (Thread.state e_tgt)):\n    exists e1_src,\n      (<<STEP: rtc (tau lower_step) e_src e1_src>>) /\\\n      (<<TERMINAL_SRC: Language.is_terminal _ (Thread.state e1_src)>>) /\\\n      (<<PROMISES: Local.promises (Thread.local e1_src) = Local.promises (Thread.local e_tgt)>>) /\\\n      (<<SC_LOWER: TimeMap.le (Thread.sc e1_src) (Thread.sc e_tgt)>>) /\\\n      (<<MEM_LOWER: lower_memory (Thread.memory e1_src) (Thread.memory e_tgt)>>).\n  Proof.\n    inv LD.\n    destruct e_src as [st_src lc_src sc_src mem_src],\n             e_lower as [st_lower lc_lower sc_lower mem_lower],\n             e_tgt as [st_tgt lc_tgt sc_tgt mem_tgt].\n    inv LOWER. inv DELAYED. ss. subst.\n    unfold delayed in *. des.\n    esplits; try exact STEPS; ss.\n    - inv LOCAL. ss. inv LOCAL2. ss.\n    - etrans; eauto.\n  Qed.\n\n  Lemma delayed_consistent_promise_consistent (th: Thread.t lang)\n        (CONSISTENT: delayed_consistent th)\n        (MEM: Memory.closed th.(Thread.memory))\n        (LOCAL: Local.wf th.(Thread.local) th.(Thread.memory))\n        (SC: Memory.closed_timemap th.(Thread.sc) th.(Thread.memory))\n    :\n      Local.promise_consistent th.(Thread.local).\n  Proof.\n    eapply delayed_consistent_consistent in CONSISTENT.\n    eapply consistent_promise_consistent; eauto.\n  Qed.\n\n\n\nEnd DStep.\n\n\nModule DConfiguration.\n  Variant step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n  | step_intro\n      e tid c1 lang st1 lc1 st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n      (DSTEPS: dsteps e (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                      (Thread.mk _ st2 lc2 sc2 mem2))\n      (CONSISTENT: e <> MachineEvent.failure ->\n                   delayed_consistent (Thread.mk _ st2 lc2 sc2 mem2)):\n      step e tid c1\n           (Configuration.mk (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1)) sc2 mem2)\n  .\n\n  Variant terminal_step: forall (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n  | terminal_step_intro\n      tid c1 lang st1 lc1 st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n      (STEPS: rtc (tau lower_step)\n                  (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                  (Thread.mk _ st2 lc2 sc2 mem2))\n      (TERMINAL: Language.is_terminal _ st2)\n      (PROMISES: Local.promises lc2 = Memory.bot):\n      terminal_step tid c1\n                    (Configuration.mk\n                       (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1))\n                       sc2 mem2)\n  .\n\n  Inductive terminal_steps: forall (tids: list Ident.t) (c1 c2: Configuration.t), Prop :=\n  | terminal_steps_nil\n      c:\n      terminal_steps [] c c\n  | terminal_steps_cons\n      tid c1 c2 tids c3\n      (NOTIN: ~ List.In tid tids)\n      (STEP: terminal_step tid c1 c2)\n      (STEPS: terminal_steps tids c2 c3):\n      terminal_steps (tid :: tids) c1 c3\n  .\n\n  Lemma step_step\n        e tid c1 c2\n        (STEP: step e tid c1 c2):\n    Configuration.opt_step e tid c1 c2.\n  Proof.\n    inv STEP.\n    exploit dsteps_plus_step; eauto. i. des.\n    - inv x1. destruct c1 as [threads sc mem]. ss.\n      rewrite IdentMap.gsident; eauto.\n    - subst. econs 2. econs; eauto. i.\n      hexploit CONSISTENT; eauto. i.\n      eapply delayed_consistent_consistent; eauto.\n  Qed.\n\n  Lemma terminal_step_step\n        tid c1 c2\n        (STEP: terminal_step tid c1 c2):\n    Configuration.opt_step MachineEvent.silent tid c1 c2.\n  Proof.\n    inv STEP.\n    exploit rtc_tail; eauto. i. des.\n    - inv x1. inv TSTEP. destruct a2. ss.\n      rewrite <- EVENT.\n      econs 2. econs; [eauto|..].\n      + eapply rtc_implies; try eapply x0.\n        i. inv H. inv TSTEP. econs; try exact EVENT0. econs. econs 2. eauto.\n      + econs 2. eauto.\n      + ii. ss. right. esplits; eauto.\n    - inv x0. destruct c1 as [threads sc mem]. ss.\n      rewrite IdentMap.gsident; eauto.\n  Qed.\n\n  Variant ld_sl (sc_src sc_tgt: TimeMap.t) (mem_src mem_tgt: Memory.t):\n    forall (sl_src sl_tgt: {lang: language & Language.state lang} * Local.t), Prop :=\n  | ld_sl_intro\n      lang st_src lc_src st_tgt lc_tgt\n      (LD: lower_delayed_thread (Thread.mk lang st_src lc_src sc_src mem_src)\n                                (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)):\n    ld_sl sc_src sc_tgt mem_src mem_tgt\n          (existT _ lang st_src, lc_src)\n          (existT _ lang st_tgt, lc_tgt)\n  .\n\n  Variant ld_conf: forall (c_src c_tgt: Configuration.t), Prop :=\n  | ld_conf_intro\n      ths_src sc_src mem_src\n      ths_tgt sc_tgt mem_tgt\n      (THS: forall tid,\n          option_rel\n            (ld_sl sc_src sc_tgt mem_src mem_tgt)\n            (IdentMap.find tid ths_src)\n            (IdentMap.find tid ths_tgt)):\n    ld_conf (Configuration.mk ths_src sc_src mem_src)\n            (Configuration.mk ths_tgt sc_tgt mem_tgt)\n  .\n\n  Lemma ld_conf_refl\n        c\n        (WF: Configuration.wf c):\n    ld_conf c c.\n  Proof.\n    destruct c. econs. i.\n    destruct (IdentMap.find tid threads) as [[[lang st] lc]|] eqn:FIND; ss.\n    inv WF. ss.\n    inv WF0. exploit THREADS; eauto. i.\n    econs. eapply lower_delayed_thread_refl; eauto.\n  Qed.\n\n  Lemma ld_conf_step_aux\n        c1_src c1_tgt\n        e tid c2_tgt\n        (LD: ld_conf c1_src c1_tgt)\n        (WF1_SRC: Configuration.wf c1_src)\n        (WF1_TGT: Configuration.wf c1_tgt)\n        (STEP: Configuration.step e tid c1_tgt c2_tgt):\n    exists c2_src lang st2_src lc2_src st2_tgt lc2_tgt,\n      (<<STEP_SRC: step e tid c1_src c2_src>>) /\\\n      (<<FIND_SRC: IdentMap.find tid (Configuration.threads c2_src) =\n                   Some (existT _ lang st2_src, lc2_src)>>) /\\\n      (<<FIND_TGT: IdentMap.find tid (Configuration.threads c2_tgt) =\n                   Some (existT _ lang st2_tgt, lc2_tgt)>>) /\\\n      (<<LD_THREAD: lower_delayed_thread\n                      (Thread.mk _ st2_src lc2_src (Configuration.sc c2_src) (Configuration.memory c2_src))\n                      (Thread.mk _ st2_tgt lc2_tgt (Configuration.sc c2_tgt) (Configuration.memory c2_tgt))>>).\n  Proof.\n    destruct c1_src as [ths1_src sc1_src mem1_src],\n             c1_tgt as [ths1_tgt sc1_tgt mem1_tgt].\n    inv LD. inv STEP. ss.\n    specialize (THS tid). rewrite TID in THS.\n    destruct (IdentMap.find tid ths1_src) as [[[lang_src st1_src] lc1_src]|] eqn:FIND_SRC; ss.\n    inv THS. Configuration.simplify.\n    inv WF1_SRC. ss.\n    inv WF. exploit THREADS; eauto. intro WF1_SRC.\n    clear DISJOINT THREADS.\n    inv WF1_TGT. ss.\n    inv WF. exploit THREADS; eauto. intro WF1_TGT.\n    clear DISJOINT THREADS.\n    exploit ld_plus_step_dsteps; try exact LD; eauto.\n    { destruct (classic (ThreadEvent.get_machine_event e0 = MachineEvent.failure)).\n      { inv STEP0; inv STEP; ss. inv LOCAL; ss; inv LOCAL0; ss. }\n      { exploit Thread.rtc_tau_step_future; try exact STEPS; eauto. s. i. des.\n        exploit Thread.step_future; try exact STEP0; eauto. s. i. des.\n        hexploit consistent_promise_consistent; try eapply EVENT; eauto.\n      }\n    }\n    i. des. subst.\n    destruct e3_src as [st3_src lc3_src sc3_src mem3_src].\n    esplits.\n    - econs; eauto. i.\n      exploit Thread.rtc_tau_step_future; try exact STEPS; eauto. s. i. des.\n      exploit Thread.step_future; try exact STEP0; eauto. s. i. des.\n      eapply ld_consistent; eauto.\n    - ss. rewrite IdentMap.gss. eauto.\n    - rewrite IdentMap.gss. eauto.\n    - ss.\n  Qed.\n\n  Lemma ld_lower\n        lang e_src e_tgt\n        (LD: @lower_delayed_thread lang e_src e_tgt):\n    (<<SC_LOWER: TimeMap.le (Thread.sc e_src) (Thread.sc e_tgt)>>) /\\\n    (<<MEM_LOWER: lower_memory (Thread.memory e_src) (Thread.memory e_tgt)>>).\n  Proof.\n    inv LD.\n    destruct e_src, e_tgt, e_lower. ss.\n    inv LOWER. inv DELAYED. ss. subst.\n    splits; auto.\n  Qed.\n\n  Lemma ld_conf_step\n        c1_src c1_tgt\n        e tid c2_tgt\n        (LD1: ld_conf c1_src c1_tgt)\n        (WF1_SRC: Configuration.wf c1_src)\n        (WF1_TGT: Configuration.wf c1_tgt)\n        (STEP: Configuration.step e tid c1_tgt c2_tgt):\n    exists c2_src,\n      (<<STEP_SRC: step e tid c1_src c2_src>>) /\\\n      (<<LD2: ld_conf c2_src c2_tgt>>).\n  Proof.\n    exploit ld_conf_step_aux; eauto. i. des.\n    esplits; eauto.\n    exploit Configuration.opt_step_future;\n      try eapply step_step; try exact STEP_SRC; eauto. i. des.\n    inv STEP. ss. inv STEP_SRC. ss.\n    econs. i. do 2 rewrite IdentMap.gsspec.\n    condtac; ss.\n    { subst. Configuration.simplify. }\n    { clear FIND_SRC FIND_TGT.\n      clear TID STEPS STEP0 EVENT TID0 DSTEPS CONSISTENT COND.\n      clear pf st1 lc1 e2 st0 lc0.\n      destruct c1_src as [ths1_src sc1_src mem1_src],\n               c1_tgt as [ths1_tgt sc1_tgt mem1_tgt].\n      inv LD1. ss.\n      specialize (THS tid0).\n      destruct (IdentMap.find tid0 ths1_src) as [[[lang_src st_src] lc_src]|] eqn:FIND_SRC; ss.\n      destruct (IdentMap.find tid0 ths1_tgt) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:FIND_TGT; ss.\n      inv THS. Configuration.simplify. econs.\n      exploit ld_lower; try exact LD_THREAD. s. i. des.\n      hexploit ld_future; try exact LD; try exact SC_LOWER; try exact MEM_LOWER; s; eauto.\n      - inv WF2. inv WF. ss.\n        eapply THREADS.\n        rewrite IdentMap.gso; eauto.\n      - inv WF2. ss.\n      - inv WF2. ss.\n    }\n  Qed.\n\n  Lemma ld_conf_terminal\n        c_src c_tgt\n        (LD: ld_conf c_src c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (TERMINAL: Configuration.is_terminal c_tgt):\n    exists c1_src,\n      (<<STEP: terminal_steps\n                 (IdentSet.elements (Threads.tids (Configuration.threads c_src)))\n                 c_src c1_src>>) /\\\n      (<<TERMINAL: Configuration.is_terminal c1_src>>).\n  Proof.\n    destruct c_src as [ths_src sc_src mem_src],\n             c_tgt as [ths_tgt sc_tgt mem_tgt]. ss.\n    remember (Threads.tids ths_src) as tids eqn:TIDS_SRC.\n    assert (NOTIN: forall tid lang_src st_src lc_src\n                     (FIND: IdentMap.find tid ths_src = Some (existT _ lang_src st_src, lc_src))\n                     (TID: ~ List.In tid (IdentSet.elements tids)),\n               Language.is_terminal _ st_src /\\ Local.is_terminal lc_src).\n    { i. destruct (IdentSet.mem tid tids) eqn:MEM.\n      - exfalso. apply TID. rewrite IdentSet.mem_spec in MEM.\n        rewrite <- IdentSet.elements_spec1 in MEM.\n        clear - MEM. induction MEM; [econs 1|econs 2]; auto.\n      - rewrite TIDS_SRC in MEM. rewrite Threads.tids_o in MEM.\n        destruct (IdentMap.find tid ths_src) eqn:IFIND; [inv MEM|]. ss.\n    }\n    assert (IN: forall tid (TID: List.In tid (IdentSet.elements tids)),\n               exists lang st_src lc_src st_tgt lc_tgt,\n                 (<<FIND_SRC: IdentMap.find tid ths_src = Some (existT _ lang st_src, lc_src)>>) /\\\n                 (<<FIND_TGT: IdentMap.find tid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)>>) /\\\n                 (<<LD_THREAD: lower_delayed_thread\n                                 (Thread.mk _ st_src lc_src sc_src mem_src)\n                                 (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt)>>)).\n    { i. destruct (IdentSet.mem tid tids) eqn:MEM.\n      - subst. dup MEM. rewrite Threads.tids_o in MEM0.\n        inv LD. specialize (THS tid).\n        destruct (IdentMap.find tid ths_src) as [[[lang_src st_src] lc_src]|] eqn:FIND_SRC; ss.\n        destruct (IdentMap.find tid ths_tgt) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:FIND_TGT; ss.\n        inv THS. Configuration.simplify.\n        esplits; eauto.\n      - exfalso. subst.\n        assert (SetoidList.InA eq tid (IdentSet.elements (Threads.tids ths_src))).\n        { clear - TID. induction (IdentSet.elements (Threads.tids ths_src)); eauto. }\n        rewrite IdentSet.elements_spec1 in H.\n        rewrite <- IdentSet.mem_spec in H. congr.\n    }\n    assert (TIDS_MEM: forall tid, List.In tid (IdentSet.elements tids) -> IdentSet.mem tid tids = true).\n    { i. rewrite IdentSet.mem_spec.\n      rewrite <- IdentSet.elements_spec1.\n      eapply SetoidList.In_InA; auto.\n    }\n    assert (NODUP: List.NoDup (IdentSet.elements tids)).\n    { specialize (IdentSet.elements_spec2w tids). i.\n      clear - H. induction H; econs; eauto.\n    }\n    clear LD.\n    revert NOTIN IN TIDS_MEM NODUP.\n    revert ths_src sc_src mem_src WF_SRC TIDS_SRC.\n    induction (IdentSet.elements tids); i.\n    { esplits; [econs 1|]. ii. eauto. }\n    exploit (IN a); try by econs 1. i. des.\n    exploit TERMINAL; eauto. i. des. inv THREAD.\n    exploit ld_terminal; try exact LD_THREAD; eauto. s. i. des.\n    rewrite PROMISES in *.\n    destruct e1_src as [st1 lc1 sc1 mem1]. ss.\n    assert (STEP_SRC: terminal_step\n                        a\n                        (Configuration.mk ths_src sc_src mem_src)\n                        (Configuration.mk\n                           (IdentMap.add a (existT _ _ st1, lc1) ths_src) sc1 mem1)).\n    { econs; eauto. }\n    exploit Configuration.opt_step_future;\n      try eapply terminal_step_step; try eapply STEP_SRC; eauto. s. i. des.\n    exploit IHl; try exact WF2; ss; eauto; i.\n    { rewrite Threads.tids_add. rewrite IdentSet.add_mem; eauto. }\n    { rewrite IdentMap.gsspec in FIND. revert FIND. condtac; ss; i.\n      - subst. Configuration.simplify.\n      - eapply NOTIN; eauto. ii. des; ss. subst. ss.\n    }\n    { exploit IN; eauto. i. des. inv NODUP.\n      rewrite IdentMap.gso; try by (ii; subst; ss).\n      esplits; eauto.\n      exploit ld_future; try exact LD_THREAD0; [..|eauto]; ss; try apply WF2.\n      inv WF2. inv WF. ss.\n      eapply (THREADS tid).\n      rewrite IdentMap.gso; eauto. ii. subst. ss.\n    }\n    { inv NODUP. ss. }\n    des. esplits; [|eauto].\n    econs; eauto. inv NODUP. ss.\n  Qed.\n\n  Inductive delayed_behaviors:\n    forall (conf:Configuration.t) (b:list Event.t) (f: bool), Prop :=\n  | delayed_behaviors_nil\n      c1 c2\n      (STEP: terminal_steps\n               (IdentSet.elements (Threads.tids (Configuration.threads c1)))\n               c1 c2)\n      (TERMINAL: Configuration.is_terminal c2):\n      delayed_behaviors c1 nil true\n  | delayed_behaviors_syscall\n      e1 e2 tid c1 c2 beh f\n      (STEP: step (MachineEvent.syscall e2) tid c1 c2)\n      (NEXT: delayed_behaviors c2 beh f)\n      (EVENT: Event.le e1 e2):\n      delayed_behaviors c1 (e1::beh) f\n  | delayed_behaviors_failure\n      tid c1 c2 beh f\n      (STEP: step MachineEvent.failure tid c1 c2):\n      delayed_behaviors c1 beh f\n  | delayed_behaviors_tau\n      tid c1 c2 beh f\n      (STEP: step MachineEvent.silent tid c1 c2)\n      (NEXT: delayed_behaviors c2 beh f):\n      delayed_behaviors c1 beh f\n  | delayed_behaviors_partial_term\n      c:\n      delayed_behaviors c [] false\n  .\n\n  Lemma ld_conf_behavior\n        c_src c_tgt\n        (LD: ld_conf c_src c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (WF_tgt: Configuration.wf c_tgt):\n    behaviors Configuration.step c_tgt <2= delayed_behaviors c_src.\n  Proof.\n    i. revert c_src LD WF_SRC. induction PR; i.\n    - exploit ld_conf_terminal; eauto. i. des.\n      econs 1; eauto.\n    - exploit ld_conf_step; eauto. i. des.\n      exploit Configuration.opt_step_future;\n        try eapply step_step; try exact STEP_SRC; eauto. i. des.\n      exploit Configuration.step_future; try exact STEP; eauto. i. des.\n      econs 2; eauto.\n    - exploit ld_conf_step; eauto. i. des.\n      econs 3; eauto.\n    - exploit ld_conf_step; eauto. i. des.\n      exploit Configuration.opt_step_future;\n        try eapply step_step; try exact STEP_SRC; eauto. i. des.\n      exploit Configuration.step_future; try exact STEP; eauto. i. des.\n      econs 4; eauto.\n    - econs 5.\n  Qed.\n\n  Lemma delayed_refinement\n        c\n        (WF: Configuration.wf c):\n    behaviors Configuration.step c <2= delayed_behaviors c.\n  Proof.\n    exploit ld_conf_refl; eauto. i.\n    eapply ld_conf_behavior; eauto.\n  Qed.\n\n  Lemma step_future c0 c1 e tid\n        (STEP: step e tid c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<WF2: Configuration.wf c1>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c0) (Configuration.sc c1)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c0) (Configuration.memory c1)>>).\n  Proof.\n    inv WF. inv WF0. inv STEP; s.\n    exploit THREADS; ss; eauto. i.\n    eapply dsteps_rtc_all_step in DSTEPS.\n    exploit Thread.rtc_all_step_future; eauto. s. i. des.\n    splits; eauto. econs; ss. econs.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH1; eauto. i.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des. ss.\n        symmetry. auto.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH2; eauto. i. des.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n      + eapply DISJOINT; [|eauto|eauto]. auto.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      exploit THREADS; try apply TH; eauto. i.\n      exploit Thread.rtc_all_step_disjoint; eauto. i. des.\n      auto.\n  Qed.\n\n  Lemma terminal_step_future c0 c1 tid\n        (STEP: terminal_step tid c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<WF2: Configuration.wf c1>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c0) (Configuration.sc c1)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c0) (Configuration.memory c1)>>).\n  Proof.\n    inv WF. inv WF0. inv STEP; s.\n    exploit THREADS; ss; eauto. i.\n    eapply rtc_implies in STEPS.\n    2:{ instantiate (1:=@Thread.all_step _). i. inv H. inv TSTEP. econs; eauto. econs; eauto. econs 2; eauto. }\n    exploit Thread.rtc_all_step_future; eauto. s. i. des.\n    splits; eauto. econs; ss. econs.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH1; eauto. i.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des. ss.\n        symmetry. auto.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH2; eauto. i. des.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n      + eapply DISJOINT; [|eauto|eauto]. auto.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      exploit THREADS; try apply TH; eauto. i.\n      exploit Thread.rtc_all_step_disjoint; eauto. i. des.\n      auto.\n  Qed.\nEnd DConfiguration.\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/DelayedStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1993527367682031}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Memory.\nRequire Import Intermediate.Machine.\nRequire Import Lib.Monads.\n\nImport Intermediate.\n\nFrom mathcomp Require Import ssreflect ssrfun.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nRecord global_env := mkGlobalEnv {\n  genv_interface: Program.interface;\n  genv_procedures: NMap (NMap code);\n  genv_entrypoints: EntryPoint.t;\n}.\n\nDefinition executing G (pc : Pointer.t) (i : instr) : Prop :=\n  exists C_procs P_code,\n    getm (genv_procedures G) (Pointer.component pc) = Some C_procs /\\\n    getm C_procs (Pointer.block pc) = Some P_code /\\\n    (Pointer.offset pc >= 0) % Z /\\\n    nth_error P_code (Z.to_nat (Pointer.offset pc)) = Some i.\n\nDefinition prepare_global_env (p: program) : global_env :=\n  let '(_, procs, entrypoints) := prepare_procedures_initial_memory p in\n  {| genv_interface := prog_interface p;\n     genv_procedures := procs;\n     genv_entrypoints := entrypoints |}.\n\n(* global environments are computational and pure: deterministic.\n   what else do I need? some kind of per-component isolation stated\n   in a way that's easy to reuse *)\nLemma domm_genv_procedures : forall p,\n  domm (genv_procedures (prepare_global_env p)) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold genv_procedures, prepare_global_env.\n  rewrite Extra.domm_map. (* RB: Should be domm_mapm! *)\n  rewrite domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nLemma domm_genv_entrypoints : forall p,\n  domm (genv_entrypoints (prepare_global_env p)) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold genv_procedures, prepare_global_env.\n  rewrite Extra.domm_map domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nDefinition global_env_union (genv1 genv2 : global_env) : global_env := {|\n  genv_interface   := unionm (genv_interface   genv1) (genv_interface   genv2);\n  genv_procedures  := unionm (genv_procedures  genv1) (genv_procedures  genv2);\n  genv_entrypoints := unionm (genv_entrypoints genv1) (genv_entrypoints genv2)\n|}.\n\nLemma prepare_global_env_link : forall {p c},\n  well_formed_program p ->\n  well_formed_program c ->\n  linkable (prog_interface p) (prog_interface c) ->\n  linkable_mains p c ->\n  prepare_global_env (program_link p c) =\n  global_env_union (prepare_global_env p) (prepare_global_env c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  unfold prepare_global_env, prepare_procedures_initial_memory.\n  rewrite (prepare_procedures_initial_memory_aux_after_linking\n           Hwfp Hwfc Hlinkable Hmains).\n  unfold global_env_union. simpl.\n  rewrite !mapm_unionm.\n  reflexivity.\nQed.\n\n(* RB: NOTE: This kind of lemma is usually the composition of two unions, one\n   of which is generally extant. Compare with \"after_linking\" lemmas. *)\nLemma imported_procedure_recombination {p c c' Cid C P} :\n  Cid \\notin domm (prog_interface c) ->\n  imported_procedure (genv_interface (prepare_global_env (program_link p c ))) Cid C P ->\n  imported_procedure (genv_interface (prepare_global_env (program_link p c'))) Cid C P.\nProof.\n  intros Hdomm Himp.\n  rewrite (imported_procedure_unionm_left Hdomm) in Himp.\n  destruct Himp as [CI [Hcomp Himp]]. exists CI. split; [| assumption].\n  unfold Program.has_component. rewrite unionmE. now rewrite Hcomp.\nQed.\n\nLemma genv_procedures_program_link_left_notin :\n  forall {c Cid},\n    Cid \\notin domm (prog_interface c) ->\n  forall {p},\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 c Cid Hnotin p 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 (HNone : (genv_procedures (prepare_global_env c)) Cid = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  setoid_rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) Cid) eqn:Hcase;\n    by setoid_rewrite Hcase.\nQed.\n\nLemma genv_entrypoints_program_link_left :\n  forall {c C},\n    C \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n  forall {P},\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c))) =\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env p)).\nProof.\n  intros c C Hnotin p Hwfp Hwfc Hlinkable Hmains P.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n  unfold EntryPoint.get, global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_entrypoints (prepare_global_env c)) C = None)\n    by (apply /dommPn; rewrite domm_genv_entrypoints; done).\n  rewrite HNone.\n  destruct ((genv_entrypoints (prepare_global_env p)) C) eqn:Hcase;\n    by rewrite Hcase.\nQed.\n\n(* RB: NOTE: Add program well-formedness if needed. *)\nLemma genv_entrypoints_interface_some p p' C P b (* pc *) :\n  (* Pointer.component pc \\in domm (prog_interface p) -> *)\n  (* imported_procedure (genv_interface (globalenv sem')) (Pointer.component pc) C P -> *)\n  well_formed_program p ->\n  well_formed_program p' ->\n  prog_interface p = prog_interface p' ->\n  EntryPoint.get C P (genv_entrypoints (prepare_global_env p )) = Some b ->\nexists b',\n  EntryPoint.get C P (genv_entrypoints (prepare_global_env p')) = Some b'.\nProof.\n  move=> Hwf Hwf' Hiface.\n  unfold EntryPoint.get (*, prepare_global_env *) (*, genv_entrypoints *); simpl.\n  (* move=> H; exists b; rewrite -H; clear H. *)\n  unfold prepare_procedures_initial_memory_aux.\n  unfold elementsm, odflt, oapp.\n  rewrite 2!mapmE.\n  unfold omap, obind, oapp; simpl.\n  rewrite 2!mkfmapfE.\n  rewrite -Hiface.\n  destruct (C \\in domm (prog_interface p)) eqn:HC.\n  - rewrite HC.\n    intro HSome.\n    destruct ((prog_procedures p) C) as [procs |] eqn:Hcase1;\n      last discriminate.\n    assert (exists procs', (prog_procedures p') C = Some procs') as [procs' Hcase1'].\n    { apply /dommP.\n      rewrite -(wfprog_defined_procedures Hwf') -Hiface (wfprog_defined_procedures Hwf).\n      apply /dommP. now exists procs. }\n    (* JT: TODO: Clean up this step *)\n    assert (Hbufs: prog_buffers p C <> None).\n    { intros Hn.\n      have: (exists procs, prog_procedures p C = Some procs) by (now exists procs).\n      move=> /dommP[H].\n      move: Hn => /dommPn[H'].\n      move: H H'.\n      rewrite -(wfprog_defined_buffers Hwf) -(wfprog_defined_procedures Hwf) => H1 H2.\n      exfalso. move: H2 => /negP. by []. }\n    destruct ((prog_buffers p) C) as [bufs |] eqn:Hcase2;\n      last contradiction.\n    assert (exists bufs', (prog_buffers p') C = Some bufs') as [bufs' Hcase2'].\n    { apply /dommP.\n      rewrite -(wfprog_defined_buffers Hwf') -Hiface (wfprog_defined_buffers Hwf).\n      apply /dommP. now exists bufs. }\n    rewrite -> Hcase1', Hcase2'.\n    (* RB: NOTE: For now, phrase in terms of domains. *)\n    assert (P \\in domm (reserve_component_blocks p C (ComponentMemory.prealloc bufs) procs).2) as Hdomm.\n    {\n      apply /dommP. eauto. (* RB: TODO: Clean up this step. *)\n    }\n    apply /dommP.\n    (* Continue to case analyze both machines in sync. *)\n    unfold reserve_component_blocks. unfold reserve_component_blocks in Hdomm.\n    destruct (ComponentMemoryExtra.reserve_blocks (ComponentMemory.prealloc bufs) (length procs))\n      as [Cmem bs] eqn:Hblocks.\n    destruct (ComponentMemoryExtra.reserve_blocks (ComponentMemory.prealloc bufs') (length procs'))\n      as [Cmem' bs'] eqn:Hblocks'.\n    rewrite domm_mkfmap. rewrite domm_mkfmap in Hdomm.\n    rewrite <- Hiface.\n    assert (Hmain : matching_mains p p') by now apply interface_implies_matching_mains.\n    destruct (prog_main p) as [|] eqn:Hcase3;\n      destruct (prog_main p') as [|] eqn:Hcase4.\n    + match goal with\n      | |- is_true (P \\in seq.unzip1 (seq.pmap ?F ?L)) => remember F as fmap eqn:Hfmap\n      end.\n      simpl in Hfmap.\n      rewrite -domm_mkfmap. rewrite -domm_mkfmap in Hdomm.\n      remember (seq.zip (seq.unzip1 procs') bs') as l' eqn:Hl'.\n      remember (seq.zip (seq.unzip1 procs) bs) as l eqn:Hl.\n      destruct (prog_interface p C) as [iface |] eqn:Hiface_eq.\n      * assert (Hin: forall l,\n                   P \\in domm (mkfmap (seq.pmap fmap l)) <->\n                         (P \\in Component.export iface \\/ (P = 0 /\\ C = 0)) /\\ P \\in domm (mkfmap l)).\n        {\n          clear -Hfmap.\n          intros l; subst; split.\n          - intros H; induction l.\n            + move: H => /dommP [v Hv]; by [].\n            + simpl in H; unfold oapp in H.\n              destruct a as [P' b']; destruct (P' \\in Component.export iface) eqn:HP';\n                rewrite HP' in H; simpl in H.\n              * move: H; rewrite domm_set => /fsetU1P.\n                move=> [Heq | Hdomm]; subst.\n                -- split; first now left.\n                   rewrite domm_set; simpl.\n                   apply /fsetU1P; now left.\n                -- specialize (IHl Hdomm) as [IH1 IH2].\n                   split; try assumption.\n                   rewrite domm_set; apply /fsetU1P; now right.\n              * destruct C eqn:HeqC; destruct P' eqn:HeqP'; simpl in *;\n                  try (specialize (IHl H) as [IH1 IH2]; split; first assumption;\n                       rewrite domm_set in_fsetU; apply /orP; now right).\n                move: H; rewrite domm_set => /fsetU1P [Heq | Hdomm]; subst.\n                -- split; first now right.\n                   rewrite domm_set; simpl. apply /fsetU1P; now left.\n                -- specialize (IHl Hdomm) as [IH1 IH2].\n                   split; first assumption.\n                   rewrite domm_set in_fsetU. apply /orP; now right.\n          - move=> [H1 H2].\n            induction l.\n            + case: H2. by [].\n            + simpl; unfold oapp.\n              destruct a as [P' b']; destruct (P' \\in Component.export iface) eqn:HP';\n                rewrite HP'; simpl.\n              * simpl in *.\n                move: H2. rewrite domm_set in_fsetU => /orP. move => [H2 | H2].\n                move: H2 => /fset1P Heq; subst.\n                rewrite domm_set; apply /fsetU1P; now left.\n                rewrite domm_set; apply /fsetU1P; right.\n                now apply IHl.\n              * destruct C eqn:HeqC; destruct P' eqn:HeqP'; simpl in *;\n                  try (apply IHl;\n                       move: H2; rewrite domm_set in_fsetU => /orP [H2 | H2]; last assumption;\n                                                             move: H2; rewrite in_fset1; rewrite eqtype.eqE; simpl;\n                                                             intros H; assert (Heq: P = S s) by (now apply /ssrnat.eqnP); subst P;\n                                                             rewrite HP' in H1; destruct H1 as [? | [? ?]]; congruence).\n                -- rewrite domm_set in_fsetU; apply /orP.\n                   destruct P; first now left.\n                   right. apply IHl.\n                   move: H2; rewrite domm_set in_fsetU => /orP [H2 | H2]; last assumption.\n                   inversion H2.\n                -- apply IHl.\n                   destruct P. destruct H1. rewrite HP' in H. congruence.\n                   destruct H. congruence.\n                   move: H2; rewrite domm_set in_fsetU => /orP [H2 | H2]; last assumption.\n                   inversion H2.\n        }\n        apply Hin in Hdomm as [Hdomm1 Hdomm2].\n        apply Hin; split; try assumption. simpl in *.\n        (* now we are left to prove that domm (mkfmap l') \u2286 domm (mkfmap l) *)\n        subst l l'.\n        rewrite domm_map_zip_unzip_same_length_is_equal;\n          last (symmetry; apply (ComponentMemoryExtra.reserve_blocks_length _ _ _ _ Hblocks')).\n        rewrite domm_map_zip_unzip_same_length_is_equal in Hdomm2;\n          last (symmetry; apply (ComponentMemoryExtra.reserve_blocks_length _ _ _ _ Hblocks)).\n        \n        (* Now we can conclude by well-formedness of p' *)\n        clear -Hiface_eq Hdomm2 Hdomm1 Hiface Hcase1 Hcase1' Hwf Hwf'.\n        assert (Hiface_eq': prog_interface p' C = Some iface) by now rewrite -Hiface.\n        destruct Hdomm1 as [Hdomm1 | Hdomm1].\n        -- assert (His_exporting': Component.is_exporting iface P) by assumption.\n           pose proof wfprog_exported_procedures_existence Hwf' Hiface_eq' His_exporting'\n             as [procs'' [? [? ?]]].\n           assert (procs' = procs'') by congruence; subst procs''.\n           apply /dommP. exists x.\n           rewrite mkfmapE. assumption.\n        -- destruct Hdomm1; subst.\n           pose proof (wfprog_main_existence Hwf').\n           destruct H as [main_procs [H1 H2]]. apply (wfprog_main_component Hwf').\n           apply /dommP; exists iface; unfold Component.main; auto.\n           unfold Component.main in *; unfold Procedure.main in *.\n           assert (main_procs = procs') by congruence.\n           subst; auto. rewrite domm_mkfmap.\n           unfold domm in *. (* ... *)\n           rewrite in_fset in H2. assumption.\n      * assert (H: seq.pmap fmap l = []).\n        {\n          clear -Hfmap.\n          subst.\n          induction l. by [].\n          rewrite //= /oapp; now destruct a.\n        }\n        rewrite H in Hdomm; clear -Hdomm; exfalso.\n        move: Hdomm => //=. apply /negP.\n        now rewrite domm0.\n    + now rewrite -> (proj1 Hmain Hcase3) in Hcase4. (* Contra. *)\n    + now rewrite -> (proj2 Hmain Hcase4) in Hcase3. (* Contra. *)\n    + (* Finish synchronizing both runs. Refer to first case as needed. Since\n         there are no main procedures, the complications of that case are\n         avoided here. *)\n      match goal with\n      | |- is_true (P \\in seq.unzip1 (seq.pmap ?F ?L)) => remember F as fmap eqn:Hfmap\n      end.\n\n      (* First attempt *)\n      rewrite -domm_mkfmap. rewrite -domm_mkfmap in Hdomm.\n      remember (seq.zip (seq.unzip1 procs') bs') as l' eqn:Hl'.\n      remember (seq.zip (seq.unzip1 procs) bs) as l eqn:Hl.\n      destruct (prog_interface p C) as [iface |] eqn:Hiface_eq.\n      * (* this assert helps simplify the expression *)\n        assert (Hin : forall l,\n                   P \\in domm (mkfmap (seq.pmap fmap l)) <->\n                         (P \\in Component.export iface /\\ P \\in domm (mkfmap l))).\n        { clear -Hfmap.\n          intros l.\n          subst.\n          split.\n          - intros H.\n            induction l.\n            + move: H => /dommP [v Hv]; case: Hv. by [].\n            + simpl in H; unfold oapp in H.\n              destruct a as [P' b']; destruct (P' \\in Component.export iface) eqn:HP';\n                rewrite HP' in H; simpl in H.\n              * move: H; rewrite domm_set => /fsetU1P.\n                move=> [Heq | Hdomm]; subst.\n                -- split; first assumption.\n                   rewrite domm_set.\n                   simpl; apply /fsetU1P; now left.\n                -- specialize (IHl Hdomm) as [IH1 IH2].\n                   split; try assumption.\n                   rewrite domm_set; apply /fsetU1P; now right.\n              * simpl in *.\n                specialize (IHl H) as [IH1 IH2].\n                split; first assumption.\n                rewrite domm_set. rewrite in_fsetU.\n                apply /orP. now right.\n          - move=> [H1 H2].\n            induction l.\n            + case: H2. by [].\n            + simpl; unfold oapp.\n              destruct a as [P' b']; destruct (P' \\in Component.export iface) eqn:HP';\n                rewrite HP'; simpl.\n              * simpl in *.\n                move: H2. rewrite domm_set in_fsetU => /orP. move => [H2 | H2].\n                move: H2 => /fset1P Heq; subst.\n                rewrite domm_set; apply /fsetU1P; now left.\n                rewrite domm_set; apply /fsetU1P; right.\n                now apply IHl.\n              * simpl in *.\n                apply IHl.\n                move: H2. rewrite domm_set in_fsetU => /orP. move=> [H2 | H3]; last assumption.\n                move: H2; rewrite in_fset1.\n                rewrite eqtype.eqE. simpl.\n                intros H. assert (Heq: P = P') by now apply /ssrnat.eqnP.\n                rewrite Heq in H1. rewrite HP' in H1. inversion H1.\n        }\n        apply Hin in Hdomm as [Hdomm1 Hdomm2].\n        apply Hin; split; try assumption. simpl in *.\n        (* now we are left to prove that domm (mkfmap l') \u2286 domm (mkfmap l) *)\n        subst l l'.\n        rewrite domm_map_zip_unzip_same_length_is_equal;\n          last (symmetry; apply (ComponentMemoryExtra.reserve_blocks_length _ _ _ _ Hblocks')).\n        rewrite domm_map_zip_unzip_same_length_is_equal in Hdomm2;\n          last (symmetry; apply (ComponentMemoryExtra.reserve_blocks_length _ _ _ _ Hblocks)).\n\n        (* Now we can conclude by well-formedness of p' *)\n        clear -Hiface_eq Hdomm2 Hdomm1 Hiface Hcase1 Hcase1' Hwf Hwf'.\n        assert (Hiface_eq': prog_interface p' C = Some iface) by now rewrite -Hiface.\n        assert (His_exporting': Component.is_exporting iface P) by assumption.\n        pose proof wfprog_exported_procedures_existence Hwf' Hiface_eq' His_exporting'\n          as [procs'' [? [? ?]]].\n        assert (procs' = procs'') by congruence; subst procs''.\n        apply /dommP. exists x.\n        rewrite mkfmapE. assumption.\n      * assert (H: seq.pmap fmap l = []).\n        {\n          clear -Hfmap.\n          subst.\n          induction l. by [].\n          rewrite //= /oapp; now destruct a.\n        }\n        rewrite H in Hdomm; clear -Hdomm; exfalso.\n        move: Hdomm => //=. apply /negP.\n        now rewrite domm0.\n  - now rewrite HC.\nQed.\n\n(* RB: NOTE: The two EntryPoint lemmas can be phrased as a more general one\n   operating on an explicit program link, one then being the exact symmetric of\n   the other, i.e., its application after communativity of linking. There is a\n   choice of encoding of component membership in both cases. *)\n\n(* RB: TODO: Rephrase goal as simple equality? *)\n(* Search _ EntryPoint.get. *)\nLemma genv_entrypoints_recombination_left :\n  forall p c c',\n    well_formed_program p ->\n    well_formed_program c ->\n    well_formed_program c' ->\n    mergeable_interfaces (prog_interface p) (prog_interface c) ->\n    prog_interface c = prog_interface c' ->\n  forall C P b,\n    C \\in domm (prog_interface p) ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c ))) = Some b ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c'))) = Some b.\nProof.\n  intros p c c' Hwfp Hwfc Hwfc' Hmergeable_ifaces Hifacec C P b Hdomm Hentry.\n  pose proof proj1 Hmergeable_ifaces as Hlinkable.\n  eapply (domm_partition_notin _ _ (mergeable_interfaces_sym _ _ Hmergeable_ifaces)) in Hdomm.\n  rewrite genv_entrypoints_program_link_left in Hentry; try assumption;\n    [| now apply linkable_implies_linkable_mains].\n  rewrite Hifacec in Hlinkable, Hdomm.\n  rewrite genv_entrypoints_program_link_left; try assumption.\n  now apply linkable_implies_linkable_mains.\nQed.\n\nLemma genv_entrypoints_recombination_right :\n  forall p c p' c',\n    well_formed_program p ->\n    well_formed_program p' ->\n    well_formed_program c' ->\n    mergeable_interfaces (prog_interface p) (prog_interface c) ->\n    prog_interface p = prog_interface p' ->\n    prog_interface c = prog_interface c' ->\n  forall C P b,\n    C \\in domm (prog_interface c) ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p' c'))) = Some b ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p  c'))) = Some b.\nProof.\n  intros p c p' c' Hwfp Hwfp' Hwfc' Hmergeable_ifaces Hifacep Hifacec C P b Hdomm Hentry.\n  pose proof proj1 Hmergeable_ifaces as Hlinkable.\n  rewrite program_linkC in Hentry; try congruence.\n  rewrite program_linkC; try congruence.\n  eapply genv_entrypoints_recombination_left with (c := p'); try assumption; try congruence.\n  rewrite -Hifacec -Hifacep. now apply mergeable_interfaces_sym.\nQed.\n\nFixpoint find_label (c : code) (l : label) : option Z :=\n  let fix aux c o :=\n      match c with\n      | [] => None\n      | ILabel l' :: c' =>\n        if Nat.eqb l l' then\n          Some o\n        else\n          aux c' (1 + o)%Z\n      | _ :: c' =>\n        aux c' (1 + o)%Z\n      end\n  in aux c 0%Z.\n\nDefinition find_label_in_procedure G (pc : Pointer.t) (l : label) : option Pointer.t :=\n  match getm (genv_procedures G) (Pointer.component pc) with\n  | Some C_procs =>\n    match getm C_procs (Pointer.block pc) with\n    | Some P_code =>\n      match find_label P_code l with\n      | Some offset => Some (Pointer.component pc, Pointer.block pc, offset)\n      | None => None\n      end\n    | None => None\n    end\n  | None => None\n  end.\n\nFixpoint find_label_in_component_helper\n         G (procs: list (Block.id * code))\n         (pc: Pointer.t) (l: label) : option Pointer.t :=\n  match procs with\n  | [] => None\n  | (p_block,p_code) :: procs' =>\n    match find_label_in_procedure G (Pointer.component pc, p_block, 0%Z) l with\n    | None => find_label_in_component_helper G procs' pc l\n    | Some ptr => Some ptr\n    end\n  end.\n\nDefinition find_label_in_component G (pc : Pointer.t) (l : label) : option Pointer.t :=\n  match getm (genv_procedures G) (Pointer.component pc) with\n  | Some C_procs =>\n    find_label_in_component_helper G (elementsm C_procs) pc l\n  | None => None\n  end.\n\nLemma find_label_in_procedure_guarantees:\n  forall G pc pc' l,\n    find_label_in_procedure G pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc' /\\\n    Pointer.block pc = Pointer.block pc'.\nProof.\n  intros G pc pc' l Hfind.\n  unfold find_label_in_procedure in Hfind.\n  destruct (getm (genv_procedures G) (Pointer.component pc)) as [procs|];\n    try discriminate.\n  destruct (getm procs (Pointer.block pc)) as [code|];\n    try discriminate.\n  destruct (find_label code l) as [offset|];\n    try discriminate.\n  destruct pc'. destruct p.\n  inversion Hfind. subst.\n  split; reflexivity.\nQed.\n\nLemma find_label_in_procedure_1:\n  forall G pc pc' l,\n    find_label_in_procedure G pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  eapply find_label_in_procedure_guarantees.\nQed.\n\nLemma find_label_in_procedure_program_link_left:\n  forall {c pc},\n    Pointer.component pc \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n  forall {l},\n    find_label_in_procedure (prepare_global_env (program_link p c)) pc l =\n    find_label_in_procedure (prepare_global_env p) pc l.\nProof.\n  (* RB: Note the proof strategy for all these lemmas is remarkably similar.\n     It may be worthwhile to refactor it and/or its intermediate steps. *)\n  intros c pc Hnotin p Hwfp Hwfc Hlinkable Hmains l.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n  unfold find_label_in_procedure, global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env c)) (Pointer.component pc) = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) (Pointer.component pc)) eqn:Hcase;\n    by rewrite Hcase.\nQed.\n\nLemma find_label_in_component_helper_guarantees:\n  forall G procs pc pc' l,\n    find_label_in_component_helper G procs pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  intros G procs pc pc' l Hfind.\n  induction procs.\n  - discriminate.\n  - simpl in *.\n    destruct a.\n    destruct (find_label_in_procedure\n                G (Pointer.component pc, i, 0%Z) l)\n             eqn:Hfind'.\n    + apply find_label_in_procedure_1 in Hfind'.\n      simpl in *. inversion Hfind. subst. auto.\n    + apply IHprocs; auto.\nQed.\n\nLemma find_label_in_component_1:\n  forall G pc pc' l,\n    find_label_in_component G pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  intros G pc pc' l Hfind.\n  unfold find_label_in_component in Hfind.\n  destruct (getm (genv_procedures G) (Pointer.component pc)) as [procs|];\n    try discriminate.\n  eapply find_label_in_component_helper_guarantees in Hfind; auto.\nQed.\n\nLemma find_label_in_component_program_link_left:\n  forall {c pc},\n    Pointer.component pc \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n  forall {l},\n    find_label_in_component (prepare_global_env (program_link p c)) pc l =\n    find_label_in_component (prepare_global_env p) pc l.\nProof.\n  intros c pc Hnotin p Hwfp Hwfc Hlinkable Hmains l.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n  unfold find_label_in_component. unfold global_env_union at 1. simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env c)) (Pointer.component pc) = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) (Pointer.component pc))\n    as [procs |] eqn:Hcase;\n    rewrite Hcase.\n  - simpl.\n    (* Inlined is the corresponding lemma on find_label_in_component_helper. *)\n    induction (elementsm procs) as [| [p_block code] elts IHelts];\n      first reflexivity.\n    unfold find_label_in_component_helper; simpl.\n    assert (Hnotin' : Pointer.component (Pointer.component pc, p_block, 0%Z)\n                      \\notin domm (prog_interface c)).\n      by done.\n    rewrite <- (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n    rewrite (find_label_in_procedure_program_link_left Hnotin' Hwfp Hwfc Hlinkable Hmains).\n    fold find_label_in_component_helper.\n    rewrite <- IHelts.\n    rewrite <- (prepare_global_env_link Hwfp Hwfc Hlinkable Hmains).\n    reflexivity.\n  - reflexivity.\nQed.\n\n(* RB: Unified presentation of linkable + linkable_mains, to be used as needed\n   around the development? *)\nLemma execution_invariant_to_linking:\n  forall p c1 c2 pc instr,\n    linkable (prog_interface p) (prog_interface c1) ->\n    linkable (prog_interface p) (prog_interface c2) ->\n    linkable_mains p c1 ->\n    linkable_mains p c2 ->\n    well_formed_program p ->\n    well_formed_program c1 ->\n    well_formed_program c2 ->\n    Pointer.component pc \\in domm (prog_interface p) ->\n    executing (prepare_global_env (program_link p c1)) pc instr ->\n    executing (prepare_global_env (program_link p c2)) pc instr.\nProof.\n  intros p c1 c2 pc instr Hlinkable1 Hlinkable2 Hmains1 Hmains2 Hwf Hwf1 Hwf2 Hpc Hexec.\n  inversion Hexec as [procs [proc [Hgenv_procs [Hprocs_proc [Hoffset Hproc_instr]]]]].\n  exists procs, proc.\n  split; [| split; [| split]];\n    [| assumption | assumption | assumption].\n  assert (Pointer.component pc \\notin domm (prog_interface c1)) as Hcc1.\n  {\n    inversion Hlinkable1 as [_ Hdisjoint]. apply /fdisjointP. apply Hdisjoint. assumption.\n  }\n  assert (Pointer.component pc \\notin domm (prog_interface c2)) as Hcc2.\n  {\n    inversion Hlinkable2 as [_ Hdisjoint]. apply /fdisjointP. apply Hdisjoint. assumption.\n  }\n  rewrite (genv_procedures_program_link_left_notin Hcc1 Hwf Hwf1 Hlinkable1 Hmains1) in Hgenv_procs.\n  rewrite (genv_procedures_program_link_left_notin Hcc2 Hwf Hwf2 Hlinkable2 Hmains2).\n  assumption.\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/Intermediate/GlobalEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1993527367682031}}
{"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 DiSeL Require Import Rely Actions Injection Process Always HoareTriples.\nFrom DiSeL Require Import InferenceRules InductiveInv While.\nFrom DiSeL Require Import SeqLib CalculatorProtocol CalculatorInvariant.\n\nObligation Tactic := Tactics.program_simpl.\n\nSection CalculatorRecieve.\n\nVariable l : Label.\n\nVariable f : input -> option nat.\nVariable prec : input -> bool.\n\nVariable cs: seq nid.\nVariable cls : seq nid.\n(* All nodes *)\nNotation nodes := (cs ++ cls).\n(* All nodes are unique *)\nHypothesis Huniq : uniq nodes.\n\n(* Protocol and its transitions *)\n\nNotation cal := (cal_with_inv l f prec cs cls).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\n\nNotation W := (mkWorld cal).\n\n(* Variable d : dstatelet. *)\n(* Hypothesis C : coh cal d. *)\n(* Check proj2 C. *)\n(* Check cal_inv_resp _ _ _ _ _ _ _ _ _ _ _ _ (proj1 C)(proj2 C). *)\n\nVariable cl : nid.\nHypothesis  Hc : cl \\in cls.\n\nProgram Definition tryrecv_resp_act := act (@tryrecv_action_wrapper W cl\n      (fun k _ t b => (k == l) && (t == resp)) _).\nNext Obligation. by case/andP:H=>/eqP->; rewrite domPt inE/=. Qed.\n\nNotation loc i := (getLocal cl (getStatelet i l)).\nNotation st := (ptr_nat 1).\n\nExport CalculatorProtocol.\n\n(* The following spec relates outstanding requests in\n   pre/postconditions and also ensures that we've got the right\n   answer. *)\nProgram Definition tryrecv_resp :\n  {rs : reqs}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (r : option perm) m =>\n     match r with\n     | Some (from, _, ms) =>\n       let v := head 0 ms in\n       let args := behead ms in\n       exists rs' : reqs,\n       [/\\ loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = Some v]\n     | None => loc m = st :-> rs\n     end)\n  := Do tryrecv_resp_act.\nNext Obligation.\napply: ghC=>i1 rs L1 C.\napply: act_rule=>i2 R1/=; split; first by case: (rely_coh R1).\nmove=>r i3 i4[Sf]S R3/=; rewrite -(rely_loc' l R1) in L1.\ncase: Sf=>_ _ _ _ /(_ l); clear C=>C.\ncase: S=>C2[|[l'][mid][tms][from][rt][pf][][E]Hin E1 Hw/=].\n- by case=>?->Z; subst i3; rewrite (rely_loc' _ R3).\ncase/andP=>/eqP Z G; subst l'; set d := (getStatelet i2 l) in C E pf Hw *.\nmove=>Z->{r}; subst i3.\nmove: rt pf (coh_s l C2) Hin E1 Hw R3 C G.\nrewrite prEq=>rt pf cohs Hin E1 Hw R3 C G.\ncase: Hin=>/=Z; do?[subst rt|case: Z]=>//Z; subst rt.\nsimpl in E1, Hw, R3; clear G.\nrewrite /cr_wf/= in Hw.\ncase: tms E E1 R3 Hw=>t tms/= E E1 R3 Hw; subst t.\nhave A1: exists s', dsoup d = mid \\\\-> (Msg (TMsg resp tms) from cl true) \\+ s'.\n+ by move/esym/um_eta2: E=>->; exists (free (dsoup d) mid).\ncase: A1=>s' Es.\n\n(* Some auxiliary facts *)\nhave Y : tms = head 0 tms :: behead tms.\n- suff M: exists x xs, tms = x::xs by case:M=>x [xs]E'; subst tms.\n  by case/andP: Hw=>_; case: (tms)=>//x xs _; exists x, xs.\nhave Y' : from \\in cs.\n- case: (proj1 C)=>Cs _ _ _. case: Cs=>Vs/(_ mid)Cs.\n  rewrite Es in Vs Cs; move: (findPtUn Vs)=>Ez.\n  by move: (Cs _ Ez)=>/=; rewrite/cohMsg/==>H; case: H.\n\n(* Using the invariant *)\nmove: ((proj2 C) (proj1 C) cl from (head 0 tms) (behead tms) mid s' Hc Y')=>//=.\nrewrite -!Y; move/(_ Es)=>F.\nrewrite Y in Hw.\n\n(* Proving the change in permissions *)\nhave X: (cl, from, (behead tms)) \\in rs.\n- by case/andP: Hw; rewrite (getStK (proj1 cohs) L1).\nhave P1: valid (dstate d) by apply: (cohVl C).\nhave P2: valid i2 by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom i2 by rewrite -(cohD(proj2(rely_coh R1)))domPt inE/=.\nrewrite (rely_loc' _ R3)/= locE// /cr_step (getStK (proj1 cohs) L1)/=.\nclear R3 Hw P1 P2 P3; exists (remove_elem rs (cl, from, (behead tms))).\nmove: (remove_elem_in rs (cl, from, (behead tms))); rewrite X.\nby rewrite perm_sym=>H.\nQed.\n\n\nDefinition receive_loop_cond (res : option nat) := res == None .\n\nDefinition receive_loop_inv (rs : reqs) :=\n  fun r i =>\n    match r with\n     | Some v =>\n       exists (rs' : reqs) from args ,\n       [/\\ loc i = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = r]\n     | None => loc i = st :-> rs\n    end.\n\nProgram Definition receive_loop' :\n  {(rs : reqs)}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (res : option nat) m =>\n     exists (rs' : reqs) v from args ,\n       [/\\ res = Some v, loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = res]) :=\n  Do _ (@while cl W _ _ receive_loop_cond receive_loop_inv _\n        (fun r => Do _ (\n           r <-- tryrecv_resp;\n           match r with\n           | Some (_, _, msg) => ret _ _ (Some (head 0 msg))\n           | None => ret _ _ None\n           end)) None).\n\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation.\nby move:H; rewrite /receive_loop_inv (rely_loc' _ H0).\nQed.\nNext Obligation.\napply:ghC=>i1 rs[];rewrite /receive_loop_cond.\nmove/eqP=>->/=E1 C1; apply: step; apply: (gh_ex (g:=rs)).\napply: call_rule=>//={r}res i2; case: res; last first.\n- move=>E2 C; apply:ret_rule=>i3 R2.\n  by rewrite /receive_loop_inv (rely_loc' _ R2).\ncase; case=>from v msg[rs'][E2]P F C2.\napply:ret_rule=>i3 R2; rewrite /receive_loop_inv (rely_loc' _ R2).\nby exists rs', from, (behead msg).\nQed.\n\nNext Obligation.\napply: ghC=>i rs E1 C1; apply: (gh_ex (g:=rs)).\napply: call_rule=>//res m[].\nrewrite /receive_loop_cond; case: res=>//=v _.\nmove=>[rs'][from][args][E2]Hp F C2.\nby exists rs', v, from, args.\nQed.\n\n(* Blocking receive-loop that always returns a result (but may not\n   terminate) *)\nProgram Definition blocking_receive_resp :\n  {(rs : reqs)}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (res :  nat) m =>\n     exists (rs': reqs) from args ,\n       [/\\ loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = Some res]) :=\n  Do _ (r <-- receive_loop';\n        match r with\n        | Some res => ret _ _ res\n        | None => ret _ _ 0\n        end).\nNext Obligation.\napply: ghC=>i rs E1 C1; apply: step; apply: (gh_ex (g:=rs)).\napply: call_rule=>//res i2[rs'][v][from][args][Z]E2 H1 H2.\nsubst res=>C2; apply: ret_rule=>i3 R2.\nby exists rs', from, args; rewrite (rely_loc' _ R2).\nQed.\n\n(* Simple send_transition *)\n\nDefinition client_send_trans :=\n  ProtocolWithInvariant.snd_transI (s2 l f prec cs cls).\n\nProgram Definition send_request server args :=\n  act (@send_action_wrapper W cal cl l (prEq cal) client_send_trans _\n                            args server).\nNext Obligation. by rewrite InE; right; rewrite InE. Qed.\n\n\nProgram Definition compute_f (server : nid) (args: seq nat) :\n  DHT [cl, W]\n  (fun i =>\n     [/\\ loc i = st :-> ([::] : reqs),\n      prec args & server \\in cs],\n   fun (res : nat) m => loc m = st :-> ([::] : reqs) /\\\n                        f args = Some res) :=\n  Do _ (send_request server args;;\n        blocking_receive_resp).\nNext Obligation.\nmove=>i1/=[E1 H2 H3].\napply: step; apply: act_rule=>i2 R1.\ncase: (rely_coh R1)=>_ C2.\nhave C': coh cal (getStatelet i2 l) by case: C2=>_ _ _ _/(_ l);rewrite prEq.\nsplit=>//=.\n- split=>//=.\n  + by split=>//; case: C'.\n  + rewrite/Actions.can_send -(cohD C2)/=domPt inE/= eqxx.\n    by rewrite mem_cat Hc orbC.\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.\nmove=>y i3 i4[S]/=;case=>Z[b]/=[F]E3 R3; subst y.\ncase: F=>/=F; subst b i3=>/=.\nrewrite -(rely_loc' _ R1) in E1.\nrewrite (getStK _ E1) in R3.\napply: (gh_ex (g:=[:: (cl, server, args)])).\napply: call_rule=>//.\n- move=>C4; rewrite (rely_loc' _ R3) locE//; last by apply: (cohVl C').\n  + by rewrite -(cohD C2) domPt inE/=.\n  by apply: (cohS C2).\nclear R3=>v i5[rs'][from][args'][E5]P5 R C.\nsuff X: args = args' /\\ rs' = [::] by case: X=>Z X; subst args' rs'.\nsuff X': rs' = [::].\n- subst rs'; split=>//; move/perm_mem: P5=>P5.\n  move/P5: (cl, server, args).\n  by rewrite inE eqxx inE/==>/esym/eqP; case=>_->.\nby case/perm_size: P5=>/esym/size0nil.\nQed.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n5 person-hours\n\n*)\n(**************************************************)\n\n\n(* More elaborated client program, compting a list of values *)\n\nDefinition compute_list_spec server ys :=\n  forall (xs_acc : (seq input) * (seq (input * nat))),\n  DHT [cl, W]\n   (fun i =>\n     let: (xs, acc) := xs_acc in\n     [/\\ loc i = st :-> ([::] : reqs),\n      all prec xs,\n      all (fun e => f e.1 == Some e.2) acc,\n      ys = map fst acc ++ xs &\n      server \\in cs],\n   fun (res : seq (input * nat)) m =>\n     [/\\ loc m = st :-> ([::] : reqs),\n      all (fun e => f e.1 == Some e.2) res &\n      ys = map fst res]).\n\nProgram Definition compute_list_f server (xs : seq input) :\n  DHT [cl, W]\n   (fun i =>\n     [/\\ loc i = st :-> ([::] : reqs),\n      all prec xs &\n      server \\in cs],\n   fun (res : seq (input * nat)) m =>\n     [/\\ loc m = st :-> ([::] : reqs),\n      all (fun e => f e.1 == Some e.2) res &\n      xs = map fst res])\n  :=\n  Do (ffix (fun (rec : compute_list_spec server xs) xsa =>\n    Do _ (let: (xs, acc) := xsa in\n          if xs is x :: xs'\n          then r <-- compute_f server x;\n               let: acc' := rcons acc (x, r) in\n               rec (xs', acc')\n          else ret _ _ acc)) (xs, [::])).\n\nNext Obligation.\nmove=>i1/=[L1]; move:l0 l4=>zs acc H1 H2 H3 H4.\ncase: zs H1 H3=>//=[_|z zs/andP[H1]H5] H3.\n- by rewrite cats0 in H3;\n  apply: ret_rule=>i2 R1; split=>//; rewrite ?(rely_loc' _ R1)//.\napply: step; apply: call_rule=>//r i2[L2]F C2.\napply: call_rule=>//_; split=>//; first by rewrite all_rcons/= F eqxx.\nby rewrite map_rcons/= -cats1 -catA cat_cons/=.\nQed.\n\nNext Obligation.\nby move=>i1/=[L1]??; apply: call_rule=>//; rewrite cats0.\nQed.\n\nEnd CalculatorRecieve.\n", "meta": {"author": "DistributedComponents", "repo": "disel", "sha": "88dc15450394a5963f513d220001b49389c6b52f", "save_path": "github-repos/coq/DistributedComponents-disel", "path": "github-repos/coq/DistributedComponents-disel/disel-88dc15450394a5963f513d220001b49389c6b52f/theories/Examples/Calculator/CalculatorClientLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.19929669447936502}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\nRequire Import Program.\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.\n\nRequire Import Time.\nFrom PromisingLib Require Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Global.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import MemoryProps.\nRequire Import Certify.\nRequire Import CurrentCertify.\nRequire Import PFConsistent.\n\nSet Implicit Arguments.\n\nDefinition owned_future_mem_loc loc: Memory.t -> Memory.t -> Prop :=\n  fun mem0 mem1 =>\n    forall from to val released na\n           (GET: Memory.get loc to mem1 = Some (from, Message.message val released na)),\n      Memory.get loc to mem0 = Some (from, Message.message val released na)\n.\n\nGlobal Program Instance owned_future_mem_loc_PreOrder loc:\n  PreOrder (owned_future_mem_loc loc).\nNext Obligation.\nProof.\n  ii. auto.\nQed.\nNext Obligation.\nProof.\n  ii. eapply H; auto.\nQed.\n\nDefinition owned_future_global_loc loc: Global.t -> Global.t -> Prop :=\n  fun gl0 gl1 =>\n    (<<MEM: owned_future_mem_loc loc gl0.(Global.memory) gl1.(Global.memory)>>) /\\\n      (<<PROM: gl1.(Global.promises) loc = gl0.(Global.promises) loc>>)\n.\n\nGlobal Program Instance owned_future_global_loc_PreOrder loc:\n  PreOrder (owned_future_global_loc loc).\nNext Obligation.\nProof.\n  unfold owned_future_global_loc. ii. splits.\n  { refl. }\n  { auto. }\nQed.\nNext Obligation.\nProof.\n  unfold owned_future_global_loc. ii. des. splits.\n  { etrans; eauto. }\n  { etrans; eauto. }\nQed.\n\nDefinition owned_future_global_promises\n           (prom: BoolMap.t) (gl0 gl1: Global.t): Prop :=\n  forall loc (OWNED: prom loc = true), owned_future_global_loc loc gl0 gl1.\n\nGlobal Program Instance owned_future_global_promises_PreOrder prom:\n  PreOrder (owned_future_global_promises prom).\nNext Obligation.\nProof.\n  ii. refl.\nQed.\nNext Obligation.\nProof.\n  ii. etrans; eauto.\nQed.\n\nLemma owned_future_global_promises_mon\n      prom0 prom1 gl0 gl1\n      (FUTURE: owned_future_global_promises prom1 gl0 gl1)\n      (LE: BoolMap.le prom0 prom1)\n  :\n  owned_future_global_promises prom0 gl0 gl1.\nProof.\n  ii. eapply FUTURE; eauto.\nQed.\n\n\n\nLemma local_reserve_step_owned_future\n      own\n      loc from to lc0 gl0 lc1 gl1\n      (STEP: Local.reserve_step lc0 gl0 loc from to lc1 gl1):\n  owned_future_global_promises\n    own\n    gl0 gl1.\nProof.\n  inv STEP; ss. inv RESERVE. ii. rr. splits; ss.\n  ii. erewrite Memory.add_o in GET; eauto. des_ifs.\nQed.\n\nLemma local_cancel_step_owned_future\n      own\n      loc from to lc0 gl0 lc1 gl1\n      (STEP: Local.cancel_step lc0 gl0 loc from to lc1 gl1):\n  owned_future_global_promises\n    own\n    gl0 gl1.\nProof.\n  inv STEP; ss. inv CANCEL. ii. rr. splits; ss.\n  ii. erewrite Memory.remove_o in GET; eauto. des_ifs.\nQed.\n\nLemma local_program_step_owned_future\n      own\n      e lc0 gl0 lc1 gl1\n      (STEP: Local.program_step e lc0 gl0 lc1 gl1):\n  (<<FUTURE: owned_future_global_promises\n               own\n               gl0 gl1>>) \\/\n    (exists loc from to val released ord,\n        (<<ACCESS: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)>>) /\\\n          (<<RACE: own loc = true>>)).\nProof.\n  inv STEP; ss.\n  { left. r. refl. }\n  { left. r. refl. }\n  { destruct (own loc) eqn:RACE.\n    { right. esplits; eauto. }\n    { left. ii. assert (NEQ: loc0 <> loc).\n      { ii. subst. rewrite RACE in *. ss. }\n      inv LOCAL. econs; ss.\n      { ii. erewrite Memory.add_o in GET; eauto. des_ifs. ss. des; clarify. }\n      { inv FULFILL; ss. inv REMOVE. inv GREMOVE.\n        rr. erewrite ! loc_fun_add_spec. condtac; subst; ss.\n      }\n    }\n  }\n  { destruct (own loc) eqn:RACE.\n    { right. esplits; eauto. }\n    { left. ii. assert (NEQ: loc0 <> loc).\n      { ii. subst. rewrite RACE in *. ss. }\n      inv LOCAL1. inv LOCAL2. econs; ss.\n      { ii. erewrite Memory.add_o in GET0; eauto.\n        destruct (loc_ts_eq_dec (loc0, to) (loc, tsw)); ss. des; clarify.\n      }\n      { inv FULFILL; ss. inv REMOVE. inv GREMOVE.\n        rr. erewrite ! loc_fun_add_spec. condtac; subst; ss.\n      }\n    }\n  }\n  { left. inv LOCAL; ss. ii. split; ss. }\n  { left. inv LOCAL; ss. ii. split; ss. }\n  { left. r. refl. }\n  { left. r. refl. }\n  { left. r. refl. }\n  { left. r. refl. }\nQed.\n\nLemma program_step_owned_future\n      own\n      e lang (th1 th2: Thread.t lang)\n      (STEP: Thread.program_step e th1 th2):\n  (exists loc from to val released ord,\n      (<<ACCESS: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)>>) /\\\n        (<<RACE: own loc = true>>)) \\/\n    (<<FUTURE: owned_future_global_promises\n                 own\n                 (th1.(Thread.global)) (th2.(Thread.global))>>).\nProof.\n  inv STEP. hexploit local_program_step_owned_future; eauto.\n  i. des; cycle 1.\n  { left. destruct e; ss; clarify.\n    { esplits; eauto. }\n    { esplits; eauto. }\n  }\n  right. esplits; eauto.\nQed.\n\nLemma pf_step_owned_future\n      own\n      lang (th1 th2: Thread.t lang)\n      (STEP: pstep (@Thread.step lang) (ThreadEvent.is_pf /1\\ non_sc) th1 th2):\n  (exists loc from to val released ord th2' e',\n      (<<STEP: Thread.step e' th1 th2'>>) /\\\n        (<<ACCESS: ThreadEvent.is_writing e' = Some (loc, from, to, val, released, ord)>>) /\\\n        (<<RACE: own loc = true>>)) \\/\n    ((<<FUTURE: owned_future_global_promises\n                  own\n                  (th1.(Thread.global)) (th2.(Thread.global))>>)).\nProof.\n  inv STEP. des. inv STEP0; ss.\n  { right. inv LOCAL; ss.\n    eapply local_cancel_step_owned_future; eauto.\n  }\n  { hexploit program_step_owned_future.\n    { econs; eauto. }\n    i. des.\n    { left. esplits; eauto. }\n    right. esplits; eauto.\n  }\nQed.\n\nLemma pf_steps_owned_future\n      own\n      lang (th1 th2: Thread.t lang)\n      (STEPS: rtc (pstep (@Thread.step lang) (ThreadEvent.is_pf /1\\ non_sc)) th1 th2):\n  (exists th1' th2' e' loc from to val released ord,\n      (<<STEPS: rtc (pstep (@Thread.step lang) (ThreadEvent.is_pf /1\\ non_sc)) th1 th1'>>) /\\\n        (<<STEP: Thread.step e' th1' th2'>>) /\\\n        (<<ACCESS: ThreadEvent.is_writing e' = Some (loc, from, to, val, released, ord)>>) /\\\n        (<<RACE: own loc = true>>)) \\/\n    ((<<FUTURE: owned_future_global_promises\n                  own\n                  (th1.(Thread.global)) (th2.(Thread.global))>>)).\nProof.\n  induction STEPS; i.\n  { right. splits; auto. refl. }\n  hexploit pf_step_owned_future; eauto. i. des.\n  { left. esplits; eauto. }\n  { left. esplits; eauto. }\n  { left. esplits.\n    { econs 2; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n  }\n  { right. r. etrans; eauto. }\nQed.\n\nLemma promise_step_owned_future\n      own\n      lang (th1 th2: Thread.t lang) loc\n      (STEP: Thread.step (ThreadEvent.promise loc) th1 th2)\n      (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n      (GL_WF1: Global.wf (Thread.global th1))\n      (CONS: rtc_consistent th2)\n  :\n  (exists th1' th2' e',\n      (<<STEPS: rtc (pstep (@Thread.step lang) (ThreadEvent.is_pf /1\\ non_sc)) th1 th1'>>) /\\\n        (<<STEP: Thread.step e' th1' th2'>>) /\\\n        ((<<FAILURE: ThreadEvent.get_machine_event e' = MachineEvent.failure>>) \\/\n           (exists loc from to val released ord,\n               (<<ACCESS: ThreadEvent.is_writing e' = Some (loc, from, to, val, released, ord)>>) /\\\n                 (<<RACE: own loc = true>>)))) \\/\n    ((<<FUTURE: owned_future_global_promises\n                  own\n                  (th1.(Thread.global)) (th2.(Thread.global))>>) /\\\n       (<<NOWN: own loc = false>>)).\nProof.\n  destruct (own loc) eqn:RACE.\n  { left.\n    rr in CONS. des.\n    eapply CurrentCertify.rtc_step_consistent_ceritfy_racy_promise in STEP.\n    2:{ eauto. }\n    2:{ eauto. }\n    2:{ eapply rtc_implies; [|eauto]. i. inv H. econs; eauto. }\n    2:{ eauto. }\n    inv STEP.\n    { hexploit pf_steps_owned_future; eauto. i. des.\n      { esplits; eauto. right. esplits; eauto. }\n      { esplits; eauto. }\n    }\n    { esplits; eauto. right. esplits; eauto. ss. }\n  }\n  { right.\n    inv STEP; inv LOCAL; ss. inv LOCAL0; ss. esplits; eauto.\n    ii. rr. splits; ss. inv PROMISE. inv ADD. inv GADD.\n    erewrite loc_fun_add_spec. des_ifs.\n  }\nQed.\n\nLemma step_owned_future\n      own\n      lang (th1 th2: Thread.t lang) e\n      (STEP: Thread.step e th1 th2)\n      (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n      (GL_WF1: Global.wf (Thread.global th1))\n      (CONS: rtc_consistent th2)\n  :\n  (exists th1' th2' e',\n      (<<STEPS: rtc (pstep (@Thread.step lang) (ThreadEvent.is_pf /1\\ non_sc)) th1 th1'>>) /\\\n        (<<STEP: Thread.step e' th1' th2'>>) /\\\n        ((<<FAILURE: ThreadEvent.get_machine_event e' = MachineEvent.failure>>) \\/\n           (exists loc from to val released ord,\n               (<<ACCESS: ThreadEvent.is_writing e' = Some (loc, from, to, val, released, ord)>>) /\\\n                 (<<RACE: own loc = true>>)))) \\/\n    ((<<FUTURE: owned_future_global_promises\n                  own\n                  (th1.(Thread.global)) (th2.(Thread.global))>>)).\nProof.\n  inv STEP.\n  { inv LOCAL.\n    { hexploit promise_step_owned_future; eauto. i. des.\n      { left. esplits; eauto. }\n      { left. esplits; eauto. right. esplits; eauto. }\n      { right. esplits; eauto. }\n    }\n    { right. esplits; eauto. eapply local_reserve_step_owned_future; eauto. }\n    { right. esplits; eauto. eapply local_cancel_step_owned_future; eauto. }\n  }\n  { hexploit program_step_owned_future; eauto.\n    { econs; eauto. }\n    i. des; ss.\n    { left. esplits; eauto. right. esplits; eauto. }\n    { right. esplits; eauto. }\n  }\nQed.\n\nLemma local_internal_step_owned_future\n      e lc0 gl0 lc1 gl1\n      (STEP: Local.internal_step e lc0 gl0 lc1 gl1)\n  :\n  owned_future_global_promises\n    (BoolMap.minus gl0.(Global.promises) lc0.(Local.promises))\n    gl0 gl1.\nProof.\n  inv STEP.\n  { inv LOCAL. inv PROMISE. ii; ss. split; ss.\n    inv ADD. inv GADD. rewrite loc_fun_add_spec.\n    unfold BoolMap.minus, andb, negb in OWNED. des_ifs.\n  }\n  { inv LOCAL. inv RESERVE. ii. split; ss.\n    ii. erewrite Memory.add_o in GET; eauto. des_ifs.\n  }\n  { inv LOCAL. inv CANCEL. ii. split; ss.\n    ii. erewrite Memory.remove_o in GET; eauto. des_ifs.\n  }\nQed.\n\nLemma internal_step_owned_future\n      lang (th1 th2: Thread.t lang)\n      (STEP: Thread.internal_step th1 th2)\n  :\n  owned_future_global_promises\n    (BoolMap.minus th1.(Thread.global).(Global.promises) th1.(Thread.local).(Local.promises))\n    (th1.(Thread.global)) (th2.(Thread.global)).\nProof.\n  inv STEP. eapply local_internal_step_owned_future in LOCAL; ss.\nQed.\n\nLemma rtc_internal_step_owned_future\n      lang (th1 th2: Thread.t lang)\n      (STEPS: rtc (@Thread.internal_step _) th1 th2)\n  :\n  owned_future_global_promises\n    (BoolMap.minus th1.(Thread.global).(Global.promises) th1.(Thread.local).(Local.promises))\n    (th1.(Thread.global)) (th2.(Thread.global)).\nProof.\n  induction STEPS; i.\n  { refl. }\n  { hexploit internal_step_owned_future; eauto. i. etrans; eauto.\n    inv H. ss. apply Local.internal_step_promises_minus in LOCAL.\n    rewrite LOCAL. auto.\n  }\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/Owned.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.199296690589615}}
{"text": "(* This file gives two different implementations of the blockchain\nexecution layer defined in Blockchain.v. Both versions are execution\nlayers using std++'s finite maps and are thus relatively\nefficient. They differ in execution order: one uses a depth-first\nexecution order, while the other uses a breadth-first execution order. *)\n\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import BoundedN.\nFrom ConCert.Execution Require Import ChainedList.\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.Utils Require Import Automation.\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Permutation.\nFrom Coq Require Import List.\nFrom Coq Require Import Psatz.\n\nImport ListNotations.\n\nSection LocalBlockchain.\n  Local Open Scope bool.\n\n  Context {AddrSize : N}.\n  Context {DepthFirst : bool}.\n\n  Definition ContractAddrBase : N := AddrSize / 2.\n\n  Global Instance LocalChainBase : ChainBase :=\n    {| Address := BoundedN AddrSize;\n      address_eqb := BoundedN.eqb;\n      address_eqb_spec := BoundedN.eqb_spec;\n      address_is_contract a := (ContractAddrBase <=? BoundedN.to_N a)%N\n    |}.\n\n  Record LocalChain :=\n    build_local_chain {\n      lc_height : nat;\n      lc_slot : nat;\n      lc_fin_height : nat;\n      lc_account_balances : FMap Address Amount;\n      lc_contract_state : FMap Address SerializedValue;\n      lc_contracts : FMap Address WeakContract;\n    }.\n\n  MetaCoq Run (make_setters LocalChain).\n\n  Definition lc_to_env (lc : LocalChain) : Environment :=\n    {| env_chain :=\n          {| chain_height := lc_height lc;\n            current_slot := lc_slot lc;\n            finalized_height := lc_fin_height lc; |};\n      env_account_balances a := with_default 0%Z (FMap.find a (lc_account_balances lc));\n      env_contract_states a := FMap.find a (lc_contract_state lc);\n      env_contracts a := FMap.find a (lc_contracts lc); |}.\n\n  Global Coercion lc_to_env : LocalChain >-> Environment.\n\n  Section ExecuteActions.\n    Local Open Scope Z.\n\n    Definition add_balance\n                (addr : Address)\n                (amt : Amount)\n                (lc : LocalChain)\n                : LocalChain :=\n      let update opt := Some (amt + with_default 0 opt) in\n      lc<|lc_account_balances ::= FMap.partial_alter update addr|>.\n\n    Definition transfer_balance\n                (from to : Address)\n                (amount : Amount)\n                (lc : LocalChain)\n                : LocalChain :=\n      add_balance to amount (add_balance from (-amount) lc).\n\n    Definition get_new_contract_addr (lc : LocalChain) : option Address :=\n      BoundedN.of_N (ContractAddrBase + N.of_nat (FMap.size (lc_contracts lc))).\n\n    Definition add_contract\n                (addr : Address)\n                (wc : WeakContract)\n                (lc : LocalChain) : LocalChain :=\n      lc<|lc_contracts ::= FMap.add addr wc|>.\n\n    Definition set_contract_state\n                (addr : Address)\n                (state : SerializedValue)\n                (lc : LocalChain) : LocalChain :=\n      lc<|lc_contract_state ::= FMap.add addr state|>.\n\n    Definition weak_error_to_error_init\n                (r : result SerializedValue SerializedValue)\n                : result SerializedValue ActionEvaluationError :=\n      bind_error (fun err => init_failed err) r.\n\n    Definition weak_error_to_error_receive\n                (r : result (SerializedValue * list ActionBody) SerializedValue)\n                : result (SerializedValue * list ActionBody) ActionEvaluationError :=\n      bind_error (fun err => receive_failed err) r.\n\n    Definition send_or_call\n                (origin : Address)\n                (from to : Address)\n                (amount : Amount)\n                (msg : option SerializedValue)\n                (lc : LocalChain)\n                : result (list Action * LocalChain) ActionEvaluationError :=\n      do if amount <? 0 then Err (amount_negative amount) else Ok tt;\n      do if amount >? env_account_balances lc from then Err (amount_too_high amount) else Ok tt;\n      match FMap.find to lc.(lc_contracts) with\n      | None =>\n        (* Fail if sending a message to address without contract *)\n        do if address_is_contract to then Err (no_such_contract to) else Ok tt;\n        match msg with\n          | None => Ok ([], transfer_balance from to amount lc)\n          | Some msg => Err (no_such_contract to)\n        end\n      | Some wc =>\n        do state <- result_of_option (env_contract_states lc to) internal_error;\n        let lc := transfer_balance from to amount lc in\n        let ctx := build_ctx origin from to (env_account_balances lc to) amount in\n        do '(new_state, new_actions) <- weak_error_to_error_receive (wc_receive wc lc ctx state msg);\n        let lc := set_contract_state to new_state lc in\n          Ok (map (build_act origin to) new_actions, lc)\n      end.\n\n    Definition deploy_contract\n                (origin : Address)\n                (from : Address)\n                (amount : Amount)\n                (wc : WeakContract)\n                (setup : SerializedValue)\n                (lc : LocalChain)\n                : result (list Action * LocalChain) ActionEvaluationError :=\n      do if amount <? 0 then Err (amount_negative amount) else Ok tt;\n      do if amount >? env_account_balances lc from then Err (amount_too_high amount) else Ok tt;\n      do contract_addr <- result_of_option (get_new_contract_addr lc) too_many_contracts;\n      do match FMap.find contract_addr (lc_contracts lc) with\n        | Some _ => Err internal_error\n        | None => Ok tt\n        end;\n      let lc := transfer_balance from contract_addr amount lc in\n      let ctx := build_ctx origin from contract_addr amount amount in\n      do state <- weak_error_to_error_init (wc_init wc lc ctx setup);\n      let lc := add_contract contract_addr wc lc in\n      let lc := set_contract_state contract_addr state lc in\n      Ok ([], lc).\n\n    Local Open Scope nat.\n\n    Definition execute_action\n                (act : Action)\n                (lc : LocalChain)\n                : result (list Action * LocalChain) ActionEvaluationError :=\n      match act with\n      | build_act origin from (act_transfer to amount) =>\n        send_or_call origin from to amount None lc\n      | build_act origin from (act_deploy amount wc setup) =>\n        deploy_contract origin from amount wc setup lc\n      | build_act origin from (act_call to amount msg) =>\n        send_or_call origin from to amount (Some msg) lc\n      end.\n\n    Fixpoint execute_actions\n              (count : nat)\n              (acts : list Action)\n              (lc : LocalChain)\n              (depth_first : bool)\n              : result LocalChain AddBlockError :=\n      match count, acts with\n      | _, [] => Ok lc\n      | 0, _ => Err action_evaluation_depth_exceeded\n      | S count, act :: acts =>\n        match execute_action act lc with\n        | Ok (next_acts, lc) =>\n          let acts := if depth_first\n                      then next_acts ++ acts\n                      else acts ++ next_acts in\n          execute_actions count acts lc depth_first\n        | Err act_err =>\n          Err (action_evaluation_error act act_err)\n        end\n      end.\n\n    Lemma transfer_balance_equiv\n            (from to : Address)\n            (amount : Amount)\n            (lc : LocalChain)\n            (env : Environment) :\n      EnvironmentEquiv lc env ->\n      EnvironmentEquiv\n        (transfer_balance from to amount lc)\n        (Blockchain.transfer_balance from to amount env).\n    Proof.\n      intros <-.\n      apply build_env_equiv; auto.\n      cbn.\n      intros addr.\n      unfold Amount in *.\n      destruct_address_eq; subst;\n        repeat\n          (try rewrite FMap.find_partial_alter;\n          try rewrite FMap.find_partial_alter_ne by auto;\n          cbn); lia.\n    Defined.\n\n    Lemma set_contract_state_equiv addr state (lc : LocalChain) (env : Environment) :\n      EnvironmentEquiv lc env ->\n      EnvironmentEquiv\n        (set_contract_state addr state lc)\n        (Blockchain.set_contract_state addr state env).\n    Proof.\n      intros <-.\n      apply build_env_equiv; auto.\n      intros addr'.\n      cbn.\n      unfold set_chain_contract_state.\n      destruct_address_eq.\n      - subst. now rewrite FMap.find_add.\n      - rewrite FMap.find_add_ne; auto.\n    Defined.\n\n    Lemma add_contract_equiv addr wc (lc : LocalChain) (env : Environment) :\n      EnvironmentEquiv lc env ->\n      EnvironmentEquiv\n        (add_contract addr wc lc)\n        (Blockchain.add_contract addr wc env).\n    Proof.\n      intros <-.\n      apply build_env_equiv; auto.\n      intros addr'.\n      cbn.\n      destruct_address_eq.\n      - subst. now rewrite FMap.find_add.\n      - rewrite FMap.find_add_ne; auto.\n    Defined.\n\n    Local Open Scope Z.\n    Lemma gtb_le x y :\n      x >? y = false ->\n      x <= y.\n    Proof.\n      intros H.\n      rewrite Z.gtb_ltb in H.\n      apply Z.ltb_ge.\n      auto.\n    Defined.\n\n    Lemma ltb_ge x y :\n      x <? y = false ->\n      x >= y.\n    Proof.\n      intros H.\n      apply Z.ltb_ge in H.\n      lia.\n    Defined.\n\n    Local Hint Resolve gtb_le ltb_ge : core.\n\n    Lemma send_or_call_step origin from to amount msg act lc_before new_acts lc_after :\n      send_or_call origin from to amount msg lc_before = Ok (new_acts, lc_after) ->\n      act = build_act origin from (match msg with\n                                  | None => act_transfer to amount\n                                  | Some msg => act_call to amount msg\n                                  end) ->\n      ActionEvaluation lc_before act lc_after new_acts.\n    Proof.\n      intros sent act_eq.\n      unfold send_or_call in sent.\n      destruct (Z.ltb amount 0) eqn:amount_nonnegative;\n        [cbn in *; congruence|].\n      destruct (Z.gtb amount (env_account_balances lc_before from)) eqn:balance_enough;\n        [cbn in *; congruence|].\n      destruct (FMap.find to (lc_contracts lc_before)) as [wc|] eqn:to_contract.\n      - (* there is a contract at destination, so do call *)\n        destruct (env_contract_states _ _) as [prev_state|] eqn:prev_state_eq;\n          [|cbn in *; congruence].\n        cbn -[lc_to_env] in *.\n        destruct (wc_receive wc _ _ _ _) as [[new_state resp_acts]|] eqn:receive;\n          [|cbn in *; congruence].\n        apply (eval_call origin from to amount wc msg prev_state new_state resp_acts);\n          try solve [cbn in *; auto; congruence].\n        + cbn in sent.\n          inversion_clear sent.\n          rewrite <- receive.\n          auto.\n        + inversion sent; subst;\n            now apply set_contract_state_equiv, transfer_balance_equiv.\n      - (* no contract at destination, so msg should be empty *)\n        destruct (address_is_contract to) eqn:addr_format; cbn in *; try congruence.\n        destruct msg; cbn in *; try congruence.\n        assert (new_acts = []) by congruence; subst new_acts.\n        apply (eval_transfer origin from to amount); auto.\n        inversion sent; subst; now apply transfer_balance_equiv.\n    Defined.\n\n    Lemma get_new_contract_addr_is_contract_addr lc addr :\n      get_new_contract_addr lc = Some addr ->\n      address_is_contract addr = true.\n    Proof.\n      intros get.\n      unfold get_new_contract_addr in get.\n      pose proof (BoundedN.of_N_some get) as eq.\n      destruct addr as [addr prf].\n      cbn in *; rewrite eq.\n      match goal with\n      | [|- context[N.leb ?a ?b = true]] => destruct (N.leb_spec a b); auto; lia\n      end.\n    Defined.\n\n    Local Hint Resolve get_new_contract_addr_is_contract_addr : core.\n    Lemma deploy_contract_step origin from amount wc setup act lc_before new_acts lc_after :\n      deploy_contract origin from amount wc setup lc_before = Ok (new_acts, lc_after) ->\n      act = build_act origin from (act_deploy amount wc setup) ->\n      ActionEvaluation lc_before act lc_after new_acts.\n    Proof.\n      intros dep act_eq.\n      unfold deploy_contract in dep.\n      destruct (Z.ltb amount 0) eqn:amount_nonnegative;\n        [cbn in *; congruence|].\n      destruct (Z.gtb amount (env_account_balances lc_before from)) eqn:balance_enough;\n        [cbn in *; congruence|].\n      destruct (get_new_contract_addr lc_before) as [contract_addr|] eqn:new_contract_addr;\n        [|cbn in *; congruence].\n      cbn -[incoming_txs] in dep.\n      destruct (FMap.find _ _) eqn:no_contracts; [cbn in *; congruence|].\n      destruct (wc_init _ _ _ _) as [state|] eqn:recv; [|cbn in *; congruence].\n      cbn in dep.\n      assert (new_acts = []) by congruence; subst new_acts.\n      apply (eval_deploy origin from contract_addr amount wc setup state); eauto.\n      inversion dep; subst lc_after.\n      now apply set_contract_state_equiv, add_contract_equiv, transfer_balance_equiv.\n    Defined.\n\n    Local Hint Resolve send_or_call_step deploy_contract_step : core.\n    Lemma execute_action_step\n          (act : Action)\n          (new_acts : list Action)\n          (lc_before : LocalChain)\n          (lc_after : LocalChain) :\n      execute_action act lc_before = Ok (new_acts, lc_after) ->\n      ActionEvaluation lc_before act lc_after new_acts.\n    Proof.\n      intros exec.\n      unfold execute_action in exec.\n      destruct act as [orig from body].\n      destruct body as [to amount|to amount msg|amount wc setup]; eauto.\n    Defined.\n\n    Hint Constructors ChainStep : core.\n    Hint Constructors ChainedList : core.\n    Hint Unfold ChainTrace : core.\n\n    Lemma execute_actions_trace count acts (lc lc_final : LocalChain) df\n          (trace : ChainTrace empty_state (build_chain_state lc acts)) :\n      execute_actions count acts lc df = Ok lc_final ->\n      ChainTrace empty_state (build_chain_state lc_final []).\n    Proof.\n      revert acts lc lc_final trace.\n      induction count as [| count IH]; intros acts lc lc_final trace exec; cbn in *.\n      - destruct acts; congruence.\n      - destruct acts as [|x xs]; try congruence.\n        destruct (execute_action x lc) as [[new_acts lc_after]|] eqn:exec_once;\n          cbn in *; try congruence.\n        set (step := execute_action_step _ _ _ _ exec_once).\n        refine (IH _ _ _ _ exec).\n        destruct df.\n        + (* depth-first case *)\n          eauto.\n        + (* breadth-first case. Insert permute step. *)\n          assert (Permutation (new_acts ++ xs) (xs ++ new_acts)) by perm_simplify.\n          cut (ChainTrace\n                empty_state\n                (build_chain_state lc_after (new_acts ++ xs))); eauto.\n          intros.\n          econstructor; eauto.\n          constructor; eauto.\n          constructor; eauto.\n    Defined.\n  End ExecuteActions.\n\n  Definition lc_initial : LocalChain :=\n    {| lc_height := 0;\n      lc_slot := 0;\n      lc_fin_height := 0;\n      lc_account_balances := FMap.empty;\n      lc_contract_state := FMap.empty;\n      lc_contracts := FMap.empty; |}.\n\n  Record LocalChainBuilder :=\n    build_local_chain_builder {\n      lcb_lc : LocalChain;\n      lcb_trace : ChainTrace empty_state (build_chain_state lcb_lc []);\n    }.\n\n  Definition lcb_initial : LocalChainBuilder :=\n    {| lcb_lc := lc_initial; lcb_trace := clnil |}.\n\n  Definition validate_header (header : BlockHeader) (chain : Chain) : bool :=\n    (block_height header =? S (chain_height chain))\n    && (current_slot chain <? block_slot header)\n    && (finalized_height chain <=? block_finalized_height header)\n    && (block_finalized_height header <? block_height header)\n    && address_not_contract (block_creator header)\n    && (block_reward header >=? 0)%Z.\n\n  Lemma validate_header_valid header chain :\n    validate_header header chain = true ->\n    IsValidNextBlock header chain.\n  Proof.\n    intros valid.\n    unfold validate_header in valid.\n    repeat\n      (match goal with\n      | [H: context[Nat.eqb ?a ?b] |- _] => destruct (Nat.eqb_spec a b)\n      | [H: context[Nat.ltb ?a ?b] |- _] => destruct (Nat.ltb_spec a b)\n      | [H: context[Nat.leb ?a ?b] |- _] => destruct (Nat.leb_spec a b)\n      | [H: context[Z.geb ?a ?b] |- _] => destruct (Z.geb_spec a b)\n      end; [|repeat rewrite Bool.andb_false_r in valid; cbn in valid; congruence]).\n    destruct (address_not_contract (block_creator header)) eqn:to_acc;\n      [|cbn in valid; congruence].\n    apply Bool.negb_true_iff in to_acc.\n    apply build_is_valid_next_block; cbn; auto.\n    lia.\n  Defined.\n\n  Definition find_origin_neq_from (actions : list Action) : option Action :=\n    find (fun act => address_neqb (act_origin act) (act_from act)) actions.\n\n  Lemma validate_origin_neq_from_valid actions :\n    find_origin_neq_from actions = None ->\n    Forall (fun act => address_eqb (act_origin act) (act_from act) = true) actions.\n  Proof.\n    intros find_none.\n    unfold find_origin_neq_from in find_none.\n    specialize (List.find_none _ _ find_none) as all_nin.\n    cbn in *.\n    assert (all_nin0 : forall x, In x actions -> (act_origin x =? act_from x)%address = true).\n    { intros. now apply ssrbool.negbFE. }\n    now apply Forall_forall in all_nin0.\n  Defined.\n\n  Definition find_invalid_root_action (actions : list Action) : option Action :=\n    find (fun act => address_is_contract (act_from act)) actions.\n\n  Lemma validate_actions_valid actions :\n    find_invalid_root_action actions = None ->\n    Forall (fun act => act_is_from_account act) actions.\n  Proof.\n    intros find_none.\n    unfold find_invalid_root_action in find_none.\n    specialize (List.find_none _ _ find_none) as all_nin.\n    unfold act_is_from_account.\n    now apply Forall_forall in all_nin.\n  Defined.\n\n  Definition add_new_block (header : BlockHeader) (lc : LocalChain) : LocalChain :=\n    let lc := add_balance (block_creator header) (block_reward header) lc in\n    lc<|lc_height := block_height header|>\n      <|lc_slot := block_slot header|>\n      <|lc_fin_height := block_finalized_height header|>.\n\n  Lemma add_new_block_equiv header (lc : LocalChain) (env : Environment) :\n    EnvironmentEquiv lc env ->\n    EnvironmentEquiv\n      (add_new_block header lc)\n      (Blockchain.add_new_block_to_env header env).\n  Proof.\n    intros eq.\n    apply build_env_equiv; try apply eq; auto.\n    intros addr.\n    cbn.\n    unfold Blockchain.add_balance.\n    destruct_address_eq.\n    - subst. rewrite FMap.find_partial_alter.\n      cbn.\n      f_equal.\n      apply eq.\n    - rewrite FMap.find_partial_alter_ne; auto.\n      apply eq.\n  Defined.\n\n  (* The computational bits of adding a block *)\n  Definition add_block_exec\n            (depth_first : bool)\n            (lc : LocalChain)\n            (header : BlockHeader)\n            (actions : list Action) : result LocalChain AddBlockError :=\n    do (if validate_header header lc then Ok tt else Err (invalid_header header));\n    do (match find_origin_neq_from actions with\n        | Some act => Err (origin_from_mismatch act)\n        | None => Ok tt\n        end);\n    do (match find_invalid_root_action actions with\n        | Some act => Err (invalid_root_action act)\n        | None => Ok tt\n        end);\n    let lc := add_new_block header lc in\n    execute_actions 1000 actions lc depth_first.\n\n  Local Hint Resolve validate_header_valid validate_actions_valid validate_origin_neq_from_valid : core.\n\n  (* Adds a block to the chain by executing the specified chain actions.\n    Returns the new chain if the execution succeeded (for instance,\n    transactions need enough funds, contracts should not reject, etc. *)\n  Definition add_block\n            (depth_first : bool)\n            (lcb : LocalChainBuilder)\n            (header : BlockHeader)\n            (actions : list Action) : result LocalChainBuilder AddBlockError.\n  Proof.\n    set (lcopt := add_block_exec depth_first (lcb_lc lcb) header actions).\n    unfold add_block_exec in lcopt.\n    destruct lcopt as [lc|e] eqn:exec; [|exact (Err e)].\n    subst lcopt.\n    destruct (validate_header _) eqn:validate; [|cbn in exec; congruence].\n    destruct (find_origin_neq_from _) eqn:no_origin_neq_from; [cbn in exec; congruence|].\n    destruct (find_invalid_root_action _) eqn:no_invalid_root_act; [cbn in exec; congruence|].\n    destruct lcb as [prev_lc_end prev_lcb_trace].\n    refine (Ok {| lcb_lc := lc; lcb_trace := _ |}).\n    cbn -[execute_actions] in exec.\n\n    refine (execute_actions_trace _ _ _ _ _ _ exec).\n    refine (snoc prev_lcb_trace _).\n    apply (step_block _ _ header); auto.\n    apply add_new_block_equiv.\n    reflexivity.\n  Defined.\n\n  Definition LocalChainBuilderImpl : ChainBuilderType :=\n    {| builder_type := LocalChainBuilder;\n      builder_initial := lcb_initial;\n      builder_env lcb := lcb_lc lcb;\n      builder_add_block := add_block DepthFirst;\n      builder_trace := lcb_trace; |}.\n\nEnd LocalBlockchain.\n\nArguments LocalChainBase : clear implicits.\nArguments LocalChainBuilder : clear implicits.\nArguments LocalChainBuilderImpl : clear implicits.\nArguments lcb_initial : clear implicits.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/execution/test/LocalBlockchain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.199296690589615}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Constant propagation over RTL.  This is one of the optimizations\n  performed at RTL level.  It proceeds by a standard dataflow analysis\n  and the corresponding code rewriting. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import Liveness.\nRequire Import ConstpropOp.\n\n(** * Static analysis *)\n\n(** The type [approx] of compile-time approximations of values is\n  defined in the machine-dependent part [ConstpropOp]. *)\n\n(** We equip this type of approximations with a semi-lattice structure.\n  The ordering is inclusion between the sets of values denoted by\n  the approximations. *)\n\nModule Approx <: SEMILATTICE_WITH_TOP.\n  Definition t := approx.\n  Definition eq (x y: t) := (x = y).\n  Definition eq_refl: forall x, eq x x := (@refl_equal t).\n  Definition eq_sym: forall x y, eq x y -> eq y x := (@sym_equal t).\n  Definition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := (@trans_equal t).\n  Lemma eq_dec: forall (x y: t), {x=y} + {x<>y}.\n  Proof.\n    decide equality.\n    apply Int.eq_dec.\n    apply Float.eq_dec.\n    apply Int64.eq_dec.\n    apply Int.eq_dec.\n    apply ident_eq.\n    apply Int.eq_dec.\n  Defined.\n  Definition beq (x y: t) := if eq_dec x y then true else false.\n  Lemma beq_correct: forall x y, beq x y = true -> x = y.\n  Proof.\n    unfold beq; intros.  destruct (eq_dec x y). auto. congruence.\n  Qed.\n\n  Definition ge (x y: t) : Prop := x = Unknown \\/ y = Novalue \\/ x = y.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge; tauto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge; intuition congruence.\n  Qed.\n  Lemma ge_compat: forall x x' y y', eq x x' -> eq y y' -> ge x y -> ge x' y'.\n  Proof.\n    unfold eq, ge; intros; congruence.\n  Qed.\n  Definition bot := Novalue.\n  Definition top := Unknown.\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Lemma ge_top: forall x, ge top x.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Definition lub (x y: t) : t :=\n    if eq_dec x y then x else\n    match x, y with\n    | Novalue, _ => y\n    | _, Novalue => x\n    | _, _ => Unknown\n    end.\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\n  Lemma ge_lub_right: forall x y, ge (lub x y) y.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. subst. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\nEnd Approx.\n\nModule D := LPMap Approx.\n\n(** We keep track of read-only global variables (i.e. \"const\" global\n  variables in C) as a map from their names to their initialization\n  data. *)\n\nDefinition global_approx : Type := PTree.t (list init_data).\n\n(** Given some initialization data and a byte offset, compute a static\n  approximation of the result of a memory load from a memory block\n  initialized with this data. *)\n\nFixpoint eval_load_init (chunk: memory_chunk) (pos: Z) (il: list init_data): approx :=\n  match il with\n  | nil => Unknown\n  | Init_int8 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint8unsigned => I (Int.zero_ext 8 n)\n        | Mint8signed => I (Int.sign_ext 8 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 1) il'\n  | Init_int16 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint16unsigned => I (Int.zero_ext 16 n)\n        | Mint16signed => I (Int.sign_ext 16 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 2) il'\n  | Init_int32 n :: il' =>\n      if zeq pos 0\n      then match chunk with Mint32 => I n | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_int64 n :: il' =>\n      if zeq pos 0\n      then match chunk with Mint64 => L n | _ => Unknown end\n      else eval_load_init chunk (pos - 8) il'\n  | Init_float32 n :: il' =>\n      if zeq pos 0\n      then match chunk with\n           | Mfloat32 => if propagate_float_constants tt then F (Float.singleoffloat n) else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_float64 n :: il' =>\n      if zeq pos 0\n      then match chunk with\n           | Mfloat64 => if propagate_float_constants tt then F n else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 8) il'\n  | Init_addrof symb ofs :: il' =>\n      if zeq pos 0\n      then match chunk with Mint32 => G symb ofs | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_space n :: il' =>\n      eval_load_init chunk (pos - Zmax n 0) il'\n  end.\n\n(** Compute a static approximation for the result of a load at an address whose\n  approximation is known.  If the approximation points to a global variable,\n  and this global variable is read-only, we use its initialization data\n  to determine a static approximation.  Otherwise, [Unknown] is returned. *)\n\nDefinition eval_static_load (gapp: global_approx) (chunk: memory_chunk) (addr: approx) : approx :=\n  match addr with\n  | G symb ofs =>\n      match gapp!symb with\n      | None => Unknown\n      | Some il => eval_load_init chunk (Int.unsigned ofs) il\n      end\n  | _ => Unknown\n  end.\n\n(** The transfer function for the dataflow analysis is straightforward.\n  For [Iop] instructions, we set the approximation of the destination\n  register to the result of executing abstractly the operation.\n  For [Iload] instructions, we set the approximation of the destination\n  register to the result of [eval_static_load].\n  For [Icall] and [Ibuiltin], the destination register becomes [Unknown].\n  Other instructions keep the approximations unchanged, as they preserve\n  the values of all registers. *)\n\nDefinition approx_reg (app: D.t) (r: reg) :=\n  D.get r app.\n\nDefinition approx_regs (app: D.t) (rl: list reg):=\n  List.map (approx_reg app) rl.\n\nDefinition transfer (gapp: global_approx) (f: function) (pc: node) (before: D.t) :=\n  match f.(fn_code)!pc with\n  | None => before\n  | Some i =>\n      match i with\n      | Iop op args res s =>\n          let a := eval_static_operation op (approx_regs before args) in\n          D.set res a before\n      | Iload chunk addr args dst s =>\n          let a := eval_static_load gapp chunk\n                     (eval_static_addressing addr (approx_regs before args)) in\n          D.set dst a before\n      | Icall sig ros args res s =>\n          D.set res Unknown before\n      | Ibuiltin ef args res s =>\n          D.set res Unknown before\n      | _ =>\n          before\n      end\n  end.\n\n(** To reduce the size of approximations, we preventively set to [Top]\n  the approximations of registers used for the last time in the\n  current instruction. *)\n\nDefinition transfer' (gapp: global_approx) (f: function) (lastuses: PTree.t (list reg))\n                     (pc: node) (before: D.t) :=\n  let after := transfer gapp f pc before in\n  match lastuses!pc with\n  | None => after\n  | Some regs => List.fold_left (fun a r => D.set r Unknown a) regs after\n  end.\n\n(** The static analysis itself is then an instantiation of Kildall's\n  generic solver for forward dataflow inequations. [analyze f]\n  returns a mapping from program points to mappings of pseudo-registers\n  to approximations.  It can fail to reach a fixpoint in a reasonable\n  number of iterations, in which case we use the trivial mapping\n  (program point -> [D.top]) instead. *)\n\nModule DS := Dataflow_Solver(D)(NodeSetForward).\n\nDefinition analyze (gapp: global_approx) (f: RTL.function): PMap.t D.t :=\n  let lu := Liveness.last_uses f in\n  match DS.fixpoint (successors f) (transfer' gapp f lu)\n                    ((f.(fn_entrypoint), D.top) :: nil) with\n  | None => PMap.init D.top\n  | Some res => res\n  end.\n\n(** * Code transformation *)\n\n(** The code transformation proceeds instruction by instruction.\n    Operators whose arguments are all statically known are turned\n    into ``load integer constant'', ``load float constant'' or\n    ``load symbol address'' operations.  Likewise for loads whose\n    result can be statically predicted.  Operators for which some\n    but not all arguments are known are subject to strength reduction,\n    and similarly for the addressing modes of load and store instructions.\n    Conditional branches and multi-way branches are statically resolved\n    into [Inop] instructions if possible. Other instructions are unchanged.\n\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 (app: D.t) (ros: reg + ident) : reg + ident :=\n  match ros with\n  | inl r =>\n      match D.get r app with\n      | G symb ofs => if Int.eq ofs Int.zero then inr _ symb else ros\n      | _ => ros\n      end\n  | inr s => ros\n  end.\n\nParameter generate_float_constants : unit -> bool.\n\nDefinition const_for_result (a: approx) : option operation :=\n  match a with\n  | I n => Some(Ointconst n)\n  | F n => if generate_float_constants tt then Some(Ofloatconst n) else None\n  | G symb ofs => Some(Oaddrsymbol symb ofs)\n  | S ofs => Some(Oaddrstack ofs)\n  | _ => None\n  end.\n\nFixpoint successor_rec (n: nat) (f: function) (app: D.t) (pc: node) : node :=\n  match n with\n  | O => pc\n  | Datatypes.S n' =>\n      match f.(fn_code)!pc with\n      | Some (Inop s) =>\n          successor_rec n' f app s\n      | Some (Icond cond args s1 s2) =>\n          match eval_static_condition cond (approx_regs app args) with\n          | Some b => 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) (app: D.t) (pc: node) : node :=\n  successor_rec num_iter f app pc.\n\nFunction annot_strength_reduction\n     (app: D.t) (targs: list annot_arg) (args: list reg) :=\n  match targs, args with\n  | AA_arg ty :: targs', arg :: args' =>\n      let (targs'', args'') := annot_strength_reduction app targs' args' in\n      match ty, approx_reg app arg with\n      | Tint, I n => (AA_int n :: targs'', args'')\n      | Tfloat, F n => (AA_float n :: targs'', args'')\n      | _, _ => (AA_arg ty :: targs'', arg :: args'')\n      end\n  | targ :: targs', _ =>\n      let (targs'', args'') := annot_strength_reduction app targs' args in\n      (targ :: targs'', args'')\n  | _, _ =>\n      (targs, args)\n  end.\n\nFunction builtin_strength_reduction\n      (app: D.t) (ef: external_function) (args: list reg) :=\n  match ef, args with\n  | EF_vload chunk, r1 :: nil =>\n      match approx_reg app r1 with\n      | G symb n1 => (EF_vload_global chunk symb n1, nil)\n      | _ => (ef, args)\n      end\n  | EF_vstore chunk, r1 :: r2 :: nil =>\n      match approx_reg app r1 with\n      | G symb n1 => (EF_vstore_global chunk symb n1, r2 :: nil)\n      | _ => (ef, args)\n      end\n  | EF_annot text targs, args =>\n      let (targs', args') := annot_strength_reduction app targs args in\n      (EF_annot text targs', args')\n  | _, _ =>\n      (ef, args)\n  end.\n\nDefinition transf_instr (gapp: global_approx) (f: function) (apps: PMap.t D.t)\n                       (pc: node) (instr: instruction) :=\n  let app := apps!!pc in\n  match instr with\n  | Iop op args res s =>\n      let a := eval_static_operation op (approx_regs app args) in\n      let s' := successor f (D.set res a app) 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 (approx_regs app args) in\n          Iop op' args' res s'\n      end\n  | Iload chunk addr args dst s =>\n      let a := eval_static_load gapp chunk\n                  (eval_static_addressing addr (approx_regs app args)) in\n      match const_for_result a with\n      | Some cop =>\n          Iop cop nil dst s\n      | None =>\n          let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n          Iload chunk addr' args' dst s\n      end\n  | Istore chunk addr args src s =>\n      let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n      Istore chunk addr' args' src s\n  | Icall sig ros args res s =>\n      Icall sig (transf_ros app ros) args res s\n  | Itailcall sig ros args =>\n      Itailcall sig (transf_ros app ros) args\n  | Ibuiltin ef args res s =>\n      let (ef', args') := builtin_strength_reduction app ef args in\n      Ibuiltin ef' args' res s\n  | Icond cond args s1 s2 =>\n      match eval_static_condition cond (approx_regs app args) with\n      | Some b =>\n          if b then Inop s1 else Inop s2\n      | None =>\n          let (cond', args') := cond_strength_reduction cond args (approx_regs app args) in\n          Icond cond' args' s1 s2\n      end\n  | Ijumptable arg tbl =>\n      match approx_reg app arg with\n      | I n =>\n          match list_nth_z tbl (Int.unsigned n) with\n          | Some s => Inop s\n          | None => instr\n          end\n      | _ => instr\n      end\n  | _ =>\n      instr\n  end.\n\nDefinition transf_code (gapp: global_approx) (f: function) (app: PMap.t D.t) (instrs: code) : code :=\n  PTree.map (transf_instr gapp f app) instrs.\n\nDefinition transf_function (gapp: global_approx) (f: function) : function :=\n  let approxs := analyze gapp f in\n  mkfunction\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (transf_code gapp f approxs f.(fn_code))\n    f.(fn_entrypoint).\n\nDefinition transf_fundef (gapp: global_approx) (fd: fundef) : fundef :=\n  AST.transf_fundef (transf_function gapp) fd.\n\nFixpoint make_global_approx (gapp: global_approx) (gdl: list (ident * globdef fundef unit)): global_approx :=\n  match gdl with\n  | nil => gapp\n  | (id, gl) :: gdl' =>\n      let gapp1 :=\n        match gl with\n        | Gfun f => PTree.remove id gapp\n        | Gvar gv =>\n            if gv.(gvar_readonly) && negb gv.(gvar_volatile)\n            then PTree.set id gv.(gvar_init) gapp\n            else PTree.remove id gapp\n        end in\n      make_global_approx gapp1 gdl'\n  end.\n\nDefinition transf_program (p: program) : program :=\n  let gapp := make_global_approx (PTree.empty _) p.(prog_defs) in\n  transform_program (transf_fundef gapp) 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/backend/Constprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19925681226562394}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nImport Clightdefs.ClightNotations.\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\nLocal Open Scope clight_scope.\n\nModule Info.\n  Definition version := \"3.10\".\n  Definition build_number := \"\".\n  Definition build_tag := \"\".\n  Definition build_branch := \"\".\n  Definition arch := \"x86\".\n  Definition model := \"32sse2\".\n  Definition abi := \"standard\".\n  Definition bitsize := 32.\n  Definition big_endian := false.\n  Definition source_file := \"sha/hmac.c\".\n  Definition normalized := false.\nEnd Info.\n\nDefinition _HMAC : ident := 117%positive.\nDefinition _HMAC2 : ident := 119%positive.\nDefinition _HMAC_Final : ident := 113%positive.\nDefinition _HMAC_Init : ident := 110%positive.\nDefinition _HMAC_Update : ident := 111%positive.\nDefinition _HMAC_cleanup : ident := 114%positive.\nDefinition _K256 : ident := 45%positive.\nDefinition _Ki : ident := 62%positive.\nDefinition _Nh : ident := 3%positive.\nDefinition _Nl : ident := 2%positive.\nDefinition _SHA256 : ident := 79%positive.\nDefinition _SHA256_Final : ident := 78%positive.\nDefinition _SHA256_Init : ident := 65%positive.\nDefinition _SHA256_Update : ident := 74%positive.\nDefinition _SHA256_addlength : ident := 69%positive.\nDefinition _SHA256state_st : ident := 6%positive.\nDefinition _T1 : ident := 57%positive.\nDefinition _T2 : ident := 58%positive.\nDefinition _X : ident := 60%positive.\nDefinition ___builtin_annot : ident := 23%positive.\nDefinition ___builtin_annot_intval : ident := 24%positive.\nDefinition ___builtin_bswap : ident := 8%positive.\nDefinition ___builtin_bswap16 : ident := 10%positive.\nDefinition ___builtin_bswap32 : ident := 9%positive.\nDefinition ___builtin_bswap64 : ident := 7%positive.\nDefinition ___builtin_clz : ident := 11%positive.\nDefinition ___builtin_clzl : ident := 12%positive.\nDefinition ___builtin_clzll : ident := 13%positive.\nDefinition ___builtin_ctz : ident := 14%positive.\nDefinition ___builtin_ctzl : ident := 15%positive.\nDefinition ___builtin_ctzll : ident := 16%positive.\nDefinition ___builtin_debug : ident := 40%positive.\nDefinition ___builtin_expect : ident := 31%positive.\nDefinition ___builtin_fabs : ident := 17%positive.\nDefinition ___builtin_fabsf : ident := 18%positive.\nDefinition ___builtin_fmadd : ident := 34%positive.\nDefinition ___builtin_fmax : ident := 32%positive.\nDefinition ___builtin_fmin : ident := 33%positive.\nDefinition ___builtin_fmsub : ident := 35%positive.\nDefinition ___builtin_fnmadd : ident := 36%positive.\nDefinition ___builtin_fnmsub : ident := 37%positive.\nDefinition ___builtin_fsqrt : ident := 19%positive.\nDefinition ___builtin_membar : ident := 25%positive.\nDefinition ___builtin_memcpy_aligned : ident := 21%positive.\nDefinition ___builtin_read16_reversed : ident := 38%positive.\nDefinition ___builtin_read32_reversed : ident := 41%positive.\nDefinition ___builtin_sel : ident := 22%positive.\nDefinition ___builtin_sqrt : ident := 20%positive.\nDefinition ___builtin_unreachable : ident := 30%positive.\nDefinition ___builtin_va_arg : ident := 27%positive.\nDefinition ___builtin_va_copy : ident := 28%positive.\nDefinition ___builtin_va_end : ident := 29%positive.\nDefinition ___builtin_va_start : ident := 26%positive.\nDefinition ___builtin_write16_reversed : ident := 39%positive.\nDefinition ___builtin_write32_reversed : ident := 42%positive.\nDefinition ___compcert_i64_dtos : ident := 84%positive.\nDefinition ___compcert_i64_dtou : ident := 85%positive.\nDefinition ___compcert_i64_sar : ident := 96%positive.\nDefinition ___compcert_i64_sdiv : ident := 90%positive.\nDefinition ___compcert_i64_shl : ident := 94%positive.\nDefinition ___compcert_i64_shr : ident := 95%positive.\nDefinition ___compcert_i64_smod : ident := 92%positive.\nDefinition ___compcert_i64_smulh : ident := 97%positive.\nDefinition ___compcert_i64_stod : ident := 86%positive.\nDefinition ___compcert_i64_stof : ident := 88%positive.\nDefinition ___compcert_i64_udiv : ident := 91%positive.\nDefinition ___compcert_i64_umod : ident := 93%positive.\nDefinition ___compcert_i64_umulh : ident := 98%positive.\nDefinition ___compcert_i64_utod : ident := 87%positive.\nDefinition ___compcert_i64_utof : ident := 89%positive.\nDefinition ___compcert_va_composite : ident := 83%positive.\nDefinition ___compcert_va_float64 : ident := 82%positive.\nDefinition ___compcert_va_int32 : ident := 80%positive.\nDefinition ___compcert_va_int64 : ident := 81%positive.\nDefinition _a : ident := 48%positive.\nDefinition _aux : ident := 108%positive.\nDefinition _b : ident := 49%positive.\nDefinition _buf : ident := 112%positive.\nDefinition _c : ident := 50%positive.\nDefinition _cNh : ident := 68%positive.\nDefinition _cNl : ident := 67%positive.\nDefinition _ctx : ident := 46%positive.\nDefinition _ctx_key : ident := 109%positive.\nDefinition _d : ident := 51%positive.\nDefinition _data : ident := 4%positive.\nDefinition _data_ : ident := 70%positive.\nDefinition _e : ident := 52%positive.\nDefinition _f : ident := 53%positive.\nDefinition _fragment : ident := 73%positive.\nDefinition _g : ident := 54%positive.\nDefinition _h : ident := 1%positive.\nDefinition _hmac_ctx_st : ident := 103%positive.\nDefinition _i : ident := 63%positive.\nDefinition _i_ctx : ident := 101%positive.\nDefinition _in : ident := 47%positive.\nDefinition _j : ident := 105%positive.\nDefinition _key : ident := 104%positive.\nDefinition _key_len : ident := 116%positive.\nDefinition _l : ident := 61%positive.\nDefinition _len : ident := 66%positive.\nDefinition _ll : ident := 76%positive.\nDefinition _m : ident := 115%positive.\nDefinition _m__1 : ident := 118%positive.\nDefinition _main : ident := 99%positive.\nDefinition _md : ident := 75%positive.\nDefinition _md_ctx : ident := 100%positive.\nDefinition _memcpy : ident := 43%positive.\nDefinition _memset : ident := 44%positive.\nDefinition _n : ident := 72%positive.\nDefinition _num : ident := 5%positive.\nDefinition _o_ctx : ident := 102%positive.\nDefinition _p : ident := 71%positive.\nDefinition _pad : ident := 107%positive.\nDefinition _reset : ident := 106%positive.\nDefinition _s0 : ident := 55%positive.\nDefinition _s1 : ident := 56%positive.\nDefinition _sha256_block_data_order : ident := 64%positive.\nDefinition _t : ident := 59%positive.\nDefinition _xn : ident := 77%positive.\n\nDefinition f_HMAC_Init := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_ctx, (tptr (Tstruct _hmac_ctx_st noattr))) ::\n                (_key, (tptr tuchar)) :: (_len, tint) :: nil);\n  fn_vars := ((_pad, (tarray tuchar 64)) :: (_ctx_key, (tarray tuchar 64)) ::\n              nil);\n  fn_temps := ((_i, tint) :: (_j, tint) :: (_reset, tint) ::\n               (_aux, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _reset (Econst_int (Int.repr 0) tint))\n  (Ssequence\n    (Sifthenelse (Ebinop One (Etempvar _key (tptr tuchar))\n                   (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) tint)\n      (Ssequence\n        (Sset _reset (Econst_int (Int.repr 1) tint))\n        (Ssequence\n          (Sset _j (Econst_int (Int.repr 64) tint))\n          (Sifthenelse (Ebinop Olt (Etempvar _j tint) (Etempvar _len tint)\n                         tint)\n            (Ssequence\n              (Scall None\n                (Evar _SHA256_Init (Tfunction\n                                     (Tcons\n                                       (tptr (Tstruct _SHA256state_st noattr))\n                                       Tnil) tvoid cc_default))\n                ((Eaddrof\n                   (Efield\n                     (Ederef\n                       (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                       (Tstruct _hmac_ctx_st noattr)) _md_ctx\n                     (Tstruct _SHA256state_st noattr))\n                   (tptr (Tstruct _SHA256state_st noattr))) :: nil))\n              (Ssequence\n                (Scall None\n                  (Evar _SHA256_Update (Tfunction\n                                         (Tcons\n                                           (tptr (Tstruct _SHA256state_st noattr))\n                                           (Tcons (tptr tvoid)\n                                             (Tcons tuint Tnil))) tvoid\n                                         cc_default))\n                  ((Eaddrof\n                     (Efield\n                       (Ederef\n                         (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                         (Tstruct _hmac_ctx_st noattr)) _md_ctx\n                       (Tstruct _SHA256state_st noattr))\n                     (tptr (Tstruct _SHA256state_st noattr))) ::\n                   (Etempvar _key (tptr tuchar)) :: (Etempvar _len tint) ::\n                   nil))\n                (Ssequence\n                  (Scall None\n                    (Evar _SHA256_Final (Tfunction\n                                          (Tcons (tptr tuchar)\n                                            (Tcons\n                                              (tptr (Tstruct _SHA256state_st noattr))\n                                              Tnil)) tvoid cc_default))\n                    ((Evar _ctx_key (tarray tuchar 64)) ::\n                     (Eaddrof\n                       (Efield\n                         (Ederef\n                           (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                           (Tstruct _hmac_ctx_st noattr)) _md_ctx\n                         (Tstruct _SHA256state_st noattr))\n                       (tptr (Tstruct _SHA256state_st noattr))) :: nil))\n                  (Scall None\n                    (Evar _memset (Tfunction\n                                    (Tcons (tptr tvoid)\n                                      (Tcons tint (Tcons tuint Tnil)))\n                                    (tptr tvoid) cc_default))\n                    ((Ebinop Oadd (Evar _ctx_key (tarray tuchar 64))\n                       (Econst_int (Int.repr 32) tint) (tptr tuchar)) ::\n                     (Econst_int (Int.repr 0) tint) ::\n                     (Econst_int (Int.repr 32) tint) :: nil)))))\n            (Ssequence\n              (Scall None\n                (Evar _memcpy (Tfunction\n                                (Tcons (tptr tvoid)\n                                  (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                                (tptr tvoid) cc_default))\n                ((Evar _ctx_key (tarray tuchar 64)) ::\n                 (Etempvar _key (tptr tuchar)) :: (Etempvar _len tint) ::\n                 nil))\n              (Scall None\n                (Evar _memset (Tfunction\n                                (Tcons (tptr tvoid)\n                                  (Tcons tint (Tcons tuint Tnil)))\n                                (tptr tvoid) cc_default))\n                ((Ebinop Oadd (Evar _ctx_key (tarray tuchar 64))\n                   (Etempvar _len tint) (tptr tuchar)) ::\n                 (Econst_int (Int.repr 0) tint) ::\n                 (Ebinop Osub (Esizeof (tarray tuchar 64) tuint)\n                   (Etempvar _len tint) tuint) :: nil))))))\n      Sskip)\n    (Ssequence\n      (Sifthenelse (Etempvar _reset tint)\n        (Ssequence\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 64) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Sset _aux\n                    (Ecast\n                      (Ederef\n                        (Ebinop Oadd (Evar _ctx_key (tarray tuchar 64))\n                          (Etempvar _i tint) (tptr tuchar)) tuchar) tuchar))\n                  (Ssequence\n                    (Sset _aux\n                      (Ecast\n                        (Ebinop Oxor (Econst_int (Int.repr 54) tint)\n                          (Etempvar _aux tuchar) tint) tuchar))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _pad (tarray tuchar 64))\n                          (Etempvar _i tint) (tptr tuchar)) tuchar)\n                      (Etempvar _aux tuchar)))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Ssequence\n            (Scall None\n              (Evar _SHA256_Init (Tfunction\n                                   (Tcons\n                                     (tptr (Tstruct _SHA256state_st noattr))\n                                     Tnil) tvoid cc_default))\n              ((Eaddrof\n                 (Efield\n                   (Ederef\n                     (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                     (Tstruct _hmac_ctx_st noattr)) _i_ctx\n                   (Tstruct _SHA256state_st noattr))\n                 (tptr (Tstruct _SHA256state_st noattr))) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _SHA256_Update (Tfunction\n                                       (Tcons\n                                         (tptr (Tstruct _SHA256state_st noattr))\n                                         (Tcons (tptr tvoid)\n                                           (Tcons tuint Tnil))) tvoid\n                                       cc_default))\n                ((Eaddrof\n                   (Efield\n                     (Ederef\n                       (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                       (Tstruct _hmac_ctx_st noattr)) _i_ctx\n                     (Tstruct _SHA256state_st noattr))\n                   (tptr (Tstruct _SHA256state_st noattr))) ::\n                 (Evar _pad (tarray tuchar 64)) ::\n                 (Econst_int (Int.repr 64) tint) :: nil))\n              (Ssequence\n                (Ssequence\n                  (Sset _i (Econst_int (Int.repr 0) tint))\n                  (Sloop\n                    (Ssequence\n                      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                     (Econst_int (Int.repr 64) tint) tint)\n                        Sskip\n                        Sbreak)\n                      (Ssequence\n                        (Sset _aux\n                          (Ecast\n                            (Ederef\n                              (Ebinop Oadd (Evar _ctx_key (tarray tuchar 64))\n                                (Etempvar _i tint) (tptr tuchar)) tuchar)\n                            tuchar))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _pad (tarray tuchar 64))\n                              (Etempvar _i tint) (tptr tuchar)) tuchar)\n                          (Ebinop Oxor (Econst_int (Int.repr 92) tint)\n                            (Etempvar _aux tuchar) tint))))\n                    (Sset _i\n                      (Ebinop Oadd (Etempvar _i tint)\n                        (Econst_int (Int.repr 1) tint) tint))))\n                (Ssequence\n                  (Scall None\n                    (Evar _SHA256_Init (Tfunction\n                                         (Tcons\n                                           (tptr (Tstruct _SHA256state_st noattr))\n                                           Tnil) tvoid cc_default))\n                    ((Eaddrof\n                       (Efield\n                         (Ederef\n                           (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                           (Tstruct _hmac_ctx_st noattr)) _o_ctx\n                         (Tstruct _SHA256state_st noattr))\n                       (tptr (Tstruct _SHA256state_st noattr))) :: nil))\n                  (Scall None\n                    (Evar _SHA256_Update (Tfunction\n                                           (Tcons\n                                             (tptr (Tstruct _SHA256state_st noattr))\n                                             (Tcons (tptr tvoid)\n                                               (Tcons tuint Tnil))) tvoid\n                                           cc_default))\n                    ((Eaddrof\n                       (Efield\n                         (Ederef\n                           (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n                           (Tstruct _hmac_ctx_st noattr)) _o_ctx\n                         (Tstruct _SHA256state_st noattr))\n                       (tptr (Tstruct _SHA256state_st noattr))) ::\n                     (Evar _pad (tarray tuchar 64)) ::\n                     (Econst_int (Int.repr 64) tint) :: nil)))))))\n        Sskip)\n      (Scall None\n        (Evar _memcpy (Tfunction\n                        (Tcons (tptr tvoid)\n                          (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                        (tptr tvoid) cc_default))\n        ((Eaddrof\n           (Efield\n             (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n               (Tstruct _hmac_ctx_st noattr)) _md_ctx\n             (Tstruct _SHA256state_st noattr))\n           (tptr (Tstruct _SHA256state_st noattr))) ::\n         (Eaddrof\n           (Efield\n             (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n               (Tstruct _hmac_ctx_st noattr)) _i_ctx\n             (Tstruct _SHA256state_st noattr))\n           (tptr (Tstruct _SHA256state_st noattr))) ::\n         (Esizeof (Tstruct _SHA256state_st noattr) tuint) :: nil)))))\n|}.\n\nDefinition f_HMAC_Update := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_ctx, (tptr (Tstruct _hmac_ctx_st noattr))) ::\n                (_data, (tptr tvoid)) :: (_len, tuint) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None\n  (Evar _SHA256_Update (Tfunction\n                         (Tcons (tptr (Tstruct _SHA256state_st noattr))\n                           (Tcons (tptr tvoid) (Tcons tuint Tnil))) tvoid\n                         cc_default))\n  ((Eaddrof\n     (Efield\n       (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n         (Tstruct _hmac_ctx_st noattr)) _md_ctx\n       (Tstruct _SHA256state_st noattr))\n     (tptr (Tstruct _SHA256state_st noattr))) ::\n   (Etempvar _data (tptr tvoid)) :: (Etempvar _len tuint) :: nil))\n|}.\n\nDefinition f_HMAC_Final := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_ctx, (tptr (Tstruct _hmac_ctx_st noattr))) ::\n                (_md, (tptr tuchar)) :: nil);\n  fn_vars := ((_buf, (tarray tuchar 32)) :: nil);\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _SHA256_Final (Tfunction\n                          (Tcons (tptr tuchar)\n                            (Tcons (tptr (Tstruct _SHA256state_st noattr))\n                              Tnil)) tvoid cc_default))\n    ((Evar _buf (tarray tuchar 32)) ::\n     (Eaddrof\n       (Efield\n         (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n           (Tstruct _hmac_ctx_st noattr)) _md_ctx\n         (Tstruct _SHA256state_st noattr))\n       (tptr (Tstruct _SHA256state_st noattr))) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _memcpy (Tfunction\n                      (Tcons (tptr tvoid)\n                        (Tcons (tptr tvoid) (Tcons tuint Tnil))) (tptr tvoid)\n                      cc_default))\n      ((Eaddrof\n         (Efield\n           (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n             (Tstruct _hmac_ctx_st noattr)) _md_ctx\n           (Tstruct _SHA256state_st noattr))\n         (tptr (Tstruct _SHA256state_st noattr))) ::\n       (Eaddrof\n         (Efield\n           (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n             (Tstruct _hmac_ctx_st noattr)) _o_ctx\n           (Tstruct _SHA256state_st noattr))\n         (tptr (Tstruct _SHA256state_st noattr))) ::\n       (Esizeof (Tstruct _SHA256state_st noattr) tuint) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _SHA256_Update (Tfunction\n                               (Tcons (tptr (Tstruct _SHA256state_st noattr))\n                                 (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                               tvoid cc_default))\n        ((Eaddrof\n           (Efield\n             (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n               (Tstruct _hmac_ctx_st noattr)) _md_ctx\n             (Tstruct _SHA256state_st noattr))\n           (tptr (Tstruct _SHA256state_st noattr))) ::\n         (Evar _buf (tarray tuchar 32)) :: (Econst_int (Int.repr 32) tint) ::\n         nil))\n      (Scall None\n        (Evar _SHA256_Final (Tfunction\n                              (Tcons (tptr tuchar)\n                                (Tcons\n                                  (tptr (Tstruct _SHA256state_st noattr))\n                                  Tnil)) tvoid cc_default))\n        ((Etempvar _md (tptr tuchar)) ::\n         (Eaddrof\n           (Efield\n             (Ederef (Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr)))\n               (Tstruct _hmac_ctx_st noattr)) _md_ctx\n             (Tstruct _SHA256state_st noattr))\n           (tptr (Tstruct _SHA256state_st noattr))) :: nil)))))\n|}.\n\nDefinition f_HMAC_cleanup := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_ctx, (tptr (Tstruct _hmac_ctx_st noattr))) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None\n  (Evar _memset (Tfunction\n                  (Tcons (tptr tvoid) (Tcons tint (Tcons tuint Tnil)))\n                  (tptr tvoid) cc_default))\n  ((Etempvar _ctx (tptr (Tstruct _hmac_ctx_st noattr))) ::\n   (Econst_int (Int.repr 0) tint) ::\n   (Esizeof (Tstruct _hmac_ctx_st noattr) tuint) :: nil))\n|}.\n\nDefinition v_m := {|\n  gvar_info := (tarray tuchar 32);\n  gvar_init := (Init_space 32 :: nil);\n  gvar_readonly := false;\n  gvar_volatile := false\n|}.\n\nDefinition f_HMAC := {|\n  fn_return := (tptr tuchar);\n  fn_callconv := cc_default;\n  fn_params := ((_key, (tptr tuchar)) :: (_key_len, tint) ::\n                (_d, (tptr tuchar)) :: (_n, tint) :: (_md, (tptr tuchar)) ::\n                nil);\n  fn_vars := ((_c, (Tstruct _hmac_ctx_st noattr)) :: nil);\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Ebinop Oeq (Etempvar _md (tptr tuchar))\n                 (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) tint)\n    (Sset _md (Evar _m (tarray tuchar 32)))\n    Sskip)\n  (Ssequence\n    (Scall None\n      (Evar _HMAC_Init (Tfunction\n                         (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                           (Tcons (tptr tuchar) (Tcons tint Tnil))) tvoid\n                         cc_default))\n      ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n         (tptr (Tstruct _hmac_ctx_st noattr))) ::\n       (Etempvar _key (tptr tuchar)) :: (Etempvar _key_len tint) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _HMAC_Update (Tfunction\n                             (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                               (Tcons (tptr tvoid) (Tcons tuint Tnil))) tvoid\n                             cc_default))\n        ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n           (tptr (Tstruct _hmac_ctx_st noattr))) ::\n         (Etempvar _d (tptr tuchar)) :: (Etempvar _n tint) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _HMAC_Final (Tfunction\n                              (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                                (Tcons (tptr tuchar) Tnil)) tvoid cc_default))\n          ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n             (tptr (Tstruct _hmac_ctx_st noattr))) ::\n           (Etempvar _md (tptr tuchar)) :: nil))\n        (Ssequence\n          (Scall None\n            (Evar _HMAC_cleanup (Tfunction\n                                  (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                                    Tnil) tvoid cc_default))\n            ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n               (tptr (Tstruct _hmac_ctx_st noattr))) :: nil))\n          (Sreturn (Some (Etempvar _md (tptr tuchar)))))))))\n|}.\n\nDefinition v_m__1 := {|\n  gvar_info := (tarray tuchar 64);\n  gvar_init := (Init_space 64 :: nil);\n  gvar_readonly := false;\n  gvar_volatile := false\n|}.\n\nDefinition f_HMAC2 := {|\n  fn_return := (tptr tuchar);\n  fn_callconv := cc_default;\n  fn_params := ((_key, (tptr tuchar)) :: (_key_len, tint) ::\n                (_d, (tptr tuchar)) :: (_n, tint) :: (_md, (tptr tuchar)) ::\n                nil);\n  fn_vars := ((_c, (Tstruct _hmac_ctx_st noattr)) :: nil);\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Ebinop Oeq (Etempvar _md (tptr tuchar))\n                 (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) tint)\n    (Sset _md (Evar _m__1 (tarray tuchar 64)))\n    Sskip)\n  (Ssequence\n    (Scall None\n      (Evar _HMAC_Init (Tfunction\n                         (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                           (Tcons (tptr tuchar) (Tcons tint Tnil))) tvoid\n                         cc_default))\n      ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n         (tptr (Tstruct _hmac_ctx_st noattr))) ::\n       (Etempvar _key (tptr tuchar)) :: (Etempvar _key_len tint) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _HMAC_Update (Tfunction\n                             (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                               (Tcons (tptr tvoid) (Tcons tuint Tnil))) tvoid\n                             cc_default))\n        ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n           (tptr (Tstruct _hmac_ctx_st noattr))) ::\n         (Etempvar _d (tptr tuchar)) :: (Etempvar _n tint) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _HMAC_Final (Tfunction\n                              (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                                (Tcons (tptr tuchar) Tnil)) tvoid cc_default))\n          ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n             (tptr (Tstruct _hmac_ctx_st noattr))) ::\n           (Etempvar _md (tptr tuchar)) :: nil))\n        (Ssequence\n          (Scall None\n            (Evar _HMAC_Init (Tfunction\n                               (Tcons (tptr (Tstruct _hmac_ctx_st noattr))\n                                 (Tcons (tptr tuchar) (Tcons tint Tnil)))\n                               tvoid cc_default))\n            ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n               (tptr (Tstruct _hmac_ctx_st noattr))) ::\n             (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) ::\n             (Etempvar _key_len tint) :: nil))\n          (Ssequence\n            (Scall None\n              (Evar _HMAC_Update (Tfunction\n                                   (Tcons\n                                     (tptr (Tstruct _hmac_ctx_st noattr))\n                                     (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                                   tvoid cc_default))\n              ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n                 (tptr (Tstruct _hmac_ctx_st noattr))) ::\n               (Etempvar _d (tptr tuchar)) :: (Etempvar _n tint) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _HMAC_Final (Tfunction\n                                    (Tcons\n                                      (tptr (Tstruct _hmac_ctx_st noattr))\n                                      (Tcons (tptr tuchar) Tnil)) tvoid\n                                    cc_default))\n                ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n                   (tptr (Tstruct _hmac_ctx_st noattr))) ::\n                 (Ebinop Oadd (Etempvar _md (tptr tuchar))\n                   (Econst_int (Int.repr 32) tint) (tptr tuchar)) :: nil))\n              (Ssequence\n                (Scall None\n                  (Evar _HMAC_cleanup (Tfunction\n                                        (Tcons\n                                          (tptr (Tstruct _hmac_ctx_st noattr))\n                                          Tnil) tvoid cc_default))\n                  ((Eaddrof (Evar _c (Tstruct _hmac_ctx_st noattr))\n                     (tptr (Tstruct _hmac_ctx_st noattr))) :: nil))\n                (Sreturn (Some (Etempvar _md (tptr tuchar))))))))))))\n|}.\n\nDefinition composites : list composite_definition :=\n(Composite _SHA256state_st Struct\n   (Member_plain _h (tarray tuint 8) :: Member_plain _Nl tuint ::\n    Member_plain _Nh tuint :: Member_plain _data (tarray tuchar 64) ::\n    Member_plain _num tuint :: nil)\n   noattr ::\n Composite _hmac_ctx_st Struct\n   (Member_plain _md_ctx (Tstruct _SHA256state_st noattr) ::\n    Member_plain _i_ctx (Tstruct _SHA256state_st noattr) ::\n    Member_plain _o_ctx (Tstruct _SHA256state_st noattr) :: nil)\n   noattr :: nil).\n\nDefinition global_definitions : list (ident * globdef fundef type) :=\n((___compcert_va_int32,\n   Gfun(External (EF_runtime \"__compcert_va_int32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tvoid) Tnil) tuint cc_default)) ::\n (___compcert_va_int64,\n   Gfun(External (EF_runtime \"__compcert_va_int64\"\n                   (mksignature (AST.Tint :: nil) AST.Tlong cc_default))\n     (Tcons (tptr tvoid) Tnil) tulong cc_default)) ::\n (___compcert_va_float64,\n   Gfun(External (EF_runtime \"__compcert_va_float64\"\n                   (mksignature (AST.Tint :: nil) AST.Tfloat cc_default))\n     (Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::\n (___compcert_va_composite,\n   Gfun(External (EF_runtime \"__compcert_va_composite\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     (tptr tvoid) cc_default)) ::\n (___compcert_i64_dtos,\n   Gfun(External (EF_runtime \"__compcert_i64_dtos\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tlong cc_default)) ::\n (___compcert_i64_dtou,\n   Gfun(External (EF_runtime \"__compcert_i64_dtou\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tulong cc_default)) ::\n (___compcert_i64_stod,\n   Gfun(External (EF_runtime \"__compcert_i64_stod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tlong Tnil) tdouble cc_default)) ::\n (___compcert_i64_utod,\n   Gfun(External (EF_runtime \"__compcert_i64_utod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tulong Tnil) tdouble cc_default)) ::\n (___compcert_i64_stof,\n   Gfun(External (EF_runtime \"__compcert_i64_stof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tlong Tnil) tfloat cc_default)) ::\n (___compcert_i64_utof,\n   Gfun(External (EF_runtime \"__compcert_i64_utof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tulong Tnil) tfloat cc_default)) ::\n (___compcert_i64_sdiv,\n   Gfun(External (EF_runtime \"__compcert_i64_sdiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_udiv,\n   Gfun(External (EF_runtime \"__compcert_i64_udiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_smod,\n   Gfun(External (EF_runtime \"__compcert_i64_smod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umod,\n   Gfun(External (EF_runtime \"__compcert_i64_umod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_shl,\n   Gfun(External (EF_runtime \"__compcert_i64_shl\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_shr,\n   Gfun(External (EF_runtime \"__compcert_i64_shr\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_sar,\n   Gfun(External (EF_runtime \"__compcert_i64_sar\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_smulh,\n   Gfun(External (EF_runtime \"__compcert_i64_smulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umulh,\n   Gfun(External (EF_runtime \"__compcert_i64_umulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___builtin_bswap64,\n   Gfun(External (EF_builtin \"__builtin_bswap64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) tulong cc_default)) ::\n (___builtin_bswap,\n   Gfun(External (EF_builtin \"__builtin_bswap\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap32,\n   Gfun(External (EF_builtin \"__builtin_bswap32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap16,\n   Gfun(External (EF_builtin \"__builtin_bswap16\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::\n (___builtin_clz,\n   Gfun(External (EF_builtin \"__builtin_clz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzl,\n   Gfun(External (EF_builtin \"__builtin_clzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzll,\n   Gfun(External (EF_builtin \"__builtin_clzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctz,\n   Gfun(External (EF_builtin \"__builtin_ctz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzl,\n   Gfun(External (EF_builtin \"__builtin_ctzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzll,\n   Gfun(External (EF_builtin \"__builtin_ctzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_fabs,\n   Gfun(External (EF_builtin \"__builtin_fabs\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_fabsf,\n   Gfun(External (EF_builtin \"__builtin_fabsf\"\n                   (mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))\n     (Tcons tfloat Tnil) tfloat cc_default)) ::\n (___builtin_fsqrt,\n   Gfun(External (EF_builtin \"__builtin_fsqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_sqrt,\n   Gfun(External (EF_builtin \"__builtin_sqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_memcpy_aligned,\n   Gfun(External (EF_builtin \"__builtin_memcpy_aligned\"\n                   (mksignature\n                     (AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr tvoid)\n       (Tcons (tptr tvoid) (Tcons tuint (Tcons tuint Tnil)))) tvoid\n     cc_default)) ::\n (___builtin_sel,\n   Gfun(External (EF_builtin \"__builtin_sel\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tbool Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot,\n   Gfun(External (EF_builtin \"__builtin_annot\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot_intval,\n   Gfun(External (EF_builtin \"__builtin_annot_intval\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))\n     tint cc_default)) ::\n (___builtin_membar,\n   Gfun(External (EF_builtin \"__builtin_membar\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_va_start,\n   Gfun(External (EF_builtin \"__builtin_va_start\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_va_arg,\n   Gfun(External (EF_builtin \"__builtin_va_arg\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_va_copy,\n   Gfun(External (EF_builtin \"__builtin_va_copy\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::\n (___builtin_va_end,\n   Gfun(External (EF_builtin \"__builtin_va_end\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_unreachable,\n   Gfun(External (EF_builtin \"__builtin_unreachable\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_expect,\n   Gfun(External (EF_builtin \"__builtin_expect\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons tint (Tcons tint Tnil)) tint\n     cc_default)) ::\n (___builtin_fmax,\n   Gfun(External (EF_builtin \"__builtin_fmax\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmin,\n   Gfun(External (EF_builtin \"__builtin_fmin\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmadd,\n   Gfun(External (EF_builtin \"__builtin_fmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fmsub,\n   Gfun(External (EF_builtin \"__builtin_fmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmadd,\n   Gfun(External (EF_builtin \"__builtin_fnmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmsub,\n   Gfun(External (EF_builtin \"__builtin_fnmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_read16_reversed,\n   Gfun(External (EF_builtin \"__builtin_read16_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons (tptr tushort) Tnil) tushort\n     cc_default)) ::\n (___builtin_read32_reversed,\n   Gfun(External (EF_builtin \"__builtin_read32_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tuint) Tnil) tuint cc_default)) ::\n (___builtin_write16_reversed,\n   Gfun(External (EF_builtin \"__builtin_write16_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))\n     tvoid cc_default)) ::\n (___builtin_write32_reversed,\n   Gfun(External (EF_builtin \"__builtin_write32_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_debug,\n   Gfun(External (EF_external \"__builtin_debug\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tint Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (_memcpy,\n   Gfun(External (EF_external \"memcpy\"\n                   (mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tint cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n     (tptr tvoid) cc_default)) ::\n (_memset,\n   Gfun(External (EF_external \"memset\"\n                   (mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tint cc_default))\n     (Tcons (tptr tvoid) (Tcons tint (Tcons tuint Tnil))) (tptr tvoid)\n     cc_default)) ::\n (_SHA256_Init,\n   Gfun(External (EF_external \"SHA256_Init\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr (Tstruct _SHA256state_st noattr)) Tnil) tvoid cc_default)) ::\n (_SHA256_Update,\n   Gfun(External (EF_external \"SHA256_Update\"\n                   (mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr (Tstruct _SHA256state_st noattr))\n       (Tcons (tptr tvoid) (Tcons tuint Tnil))) tvoid cc_default)) ::\n (_SHA256_Final,\n   Gfun(External (EF_external \"SHA256_Final\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tuchar)\n       (Tcons (tptr (Tstruct _SHA256state_st noattr)) Tnil)) tvoid\n     cc_default)) :: (_HMAC_Init, Gfun(Internal f_HMAC_Init)) ::\n (_HMAC_Update, Gfun(Internal f_HMAC_Update)) ::\n (_HMAC_Final, Gfun(Internal f_HMAC_Final)) ::\n (_HMAC_cleanup, Gfun(Internal f_HMAC_cleanup)) :: (_m, Gvar v_m) ::\n (_HMAC, Gfun(Internal f_HMAC)) :: (_m__1, Gvar v_m__1) ::\n (_HMAC2, Gfun(Internal f_HMAC2)) :: nil).\n\nDefinition public_idents : list ident :=\n(_HMAC2 :: _HMAC :: _HMAC_cleanup :: _HMAC_Final :: _HMAC_Update ::\n _HMAC_Init :: _SHA256_Final :: _SHA256_Update :: _SHA256_Init :: _memset ::\n _memcpy :: ___builtin_debug :: ___builtin_write32_reversed ::\n ___builtin_write16_reversed :: ___builtin_read32_reversed ::\n ___builtin_read16_reversed :: ___builtin_fnmsub :: ___builtin_fnmadd ::\n ___builtin_fmsub :: ___builtin_fmadd :: ___builtin_fmin ::\n ___builtin_fmax :: ___builtin_expect :: ___builtin_unreachable ::\n ___builtin_va_end :: ___builtin_va_copy :: ___builtin_va_arg ::\n ___builtin_va_start :: ___builtin_membar :: ___builtin_annot_intval ::\n ___builtin_annot :: ___builtin_sel :: ___builtin_memcpy_aligned ::\n ___builtin_sqrt :: ___builtin_fsqrt :: ___builtin_fabsf ::\n ___builtin_fabs :: ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz ::\n ___builtin_clzll :: ___builtin_clzl :: ___builtin_clz ::\n ___builtin_bswap16 :: ___builtin_bswap32 :: ___builtin_bswap ::\n ___builtin_bswap64 :: ___compcert_i64_umulh :: ___compcert_i64_smulh ::\n ___compcert_i64_sar :: ___compcert_i64_shr :: ___compcert_i64_shl ::\n ___compcert_i64_umod :: ___compcert_i64_smod :: ___compcert_i64_udiv ::\n ___compcert_i64_sdiv :: ___compcert_i64_utof :: ___compcert_i64_stof ::\n ___compcert_i64_utod :: ___compcert_i64_stod :: ___compcert_i64_dtou ::\n ___compcert_i64_dtos :: ___compcert_va_composite ::\n ___compcert_va_float64 :: ___compcert_va_int64 :: ___compcert_va_int32 ::\n nil).\n\nDefinition prog : Clight.program := \n  mkprogram composites global_definitions public_idents _main Logic.I.\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sha/hmac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19925680465702822}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word.\nRequire Import Lib.Struct Lib.FMap Lib.StringEq Lib.Indexer.\nRequire Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Renaming Kami.Inline Kami.InlineFacts.\nRequire Import Kami.Decomposition Kami.Notations Kami.Tactics Kami.ModuleBoundEx.\nRequire Import Kami.PrimFifo.\nRequire Import Ex.MemTypes Ex.MemAsync.\nRequire Import Ex.SC Ex.ProcDec Ex.ProcThreeStage Ex.ProcThreeStDec Ex.ProcFDCorrect.\nRequire Import Eqdep.\n\nSet Implicit Arguments.\n\nSection ProcFDE.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Context {indexSize tagSize: nat}.\n  Variables (getIndex: forall ty, fullType ty (SyntaxKind (Bit addrSize)) ->\n                                  Expr ty (SyntaxKind (Bit indexSize)))\n            (getTag: forall ty, fullType ty (SyntaxKind (Bit addrSize)) ->\n                                Expr ty (SyntaxKind (Bit tagSize))).\n\n  (* Abstract f2dElt *)  \n  Variable (f2dElt: Kind).\n  Variable (f2dPack:\n              forall ty,\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind f2dElt)).\n  Variables\n    (f2dRawInst: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (f2dCurPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dNextPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dEpoch: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Hypotheses (Hf2dRawInst: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dRawInst _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr rawInst)\n             (Hf2dCurPc: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dCurPc _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr curPc)\n             (Hf2dNextPc: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dNextPc _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr nextPc)\n             (Hf2dEpoch: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dEpoch _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr epoch).\n\n  Hypothesis\n    (Hf2dpackExt:\n       forall rawInst1 curPc1 nextPc1 epoch1 rawInst2 curPc2 nextPc2 epoch2,\n         evalExpr rawInst1 = evalExpr rawInst2 ->\n         evalExpr curPc1 = evalExpr curPc2 ->\n         evalExpr nextPc1 = evalExpr nextPc2 ->\n         evalExpr epoch1 = evalExpr epoch2 ->\n         evalExpr (f2dPack rawInst1 curPc1 nextPc1 epoch1) =\n         evalExpr (f2dPack rawInst2 curPc2 nextPc2 epoch2)).\n\n  (* Abstract d2eElt *)\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  (* Abstract e2wElt *)  \n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n\n  Variable (init: ProcInit addrSize dataBytes rfIdx).\n\n  Definition fetchDecode: Modules :=\n    fetchICacheDecode\n      fetch dec d2ePack\n      f2dPack f2dRawInst f2dCurPc f2dNextPc f2dEpoch getIndex getTag\n      (pcInit init).\n\n  Definition p4st := (fetchDecode\n                        ++ regFile (rfInit init)\n                        ++ scoreBoard rfIdx\n                        ++ PrimFifo.fifo PrimFifo.primPipelineFifoName d2eFifoName d2eElt\n                        ++ PrimFifo.fifoF PrimFifo.primBypassFifoName w2dFifoName (w2dElt addrSize)\n                        ++ (executer exec d2eOpType d2eVal1 d2eVal2\n                                     d2eRawInst d2eCurPc e2wPack)\n                        ++ epoch\n                        ++ PrimFifo.fifo PrimFifo.primPipelineFifoName e2wFifoName e2wElt\n                        ++ (wb dec exec d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eRawInst\n                               d2eCurPc d2eNextPc d2eEpoch e2wDecInst e2wVal))%kami.\n\n  Definition p3st := ProcThreeStage.p3st\n                       fetch dec exec\n                       d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                       d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                       e2wPack e2wDecInst e2wVal init.\n\n  Lemma p4st_refines_p3st: p4st <<== p3st.\n  Proof. (* SKIP_PROOF_ON\n    kmodular.\n    - apply fetchICacheDecode_refines_fetchNDecode; auto.\n    - krefl.\n      END_SKIP_PROOF_ON *) apply cheat.\n  Qed.\n\nEnd ProcFDE.\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/ProcFourStDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.1992568046570282}}
{"text": "(** Axiomatisation of the host. **)\n(* (C) M. Bodin - see LICENSE.txt *)\n\nFrom mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq.\nFrom Wasm Require Import common datatypes operations typing.\nFrom ITree Require Import ITree ITreeFacts.\n\nImport Monads.\n\nSet Implicit Arguments.\n\n(** * General host definitions **)\n\n(** We provide two versions of the host.\n  One based on a relation, to be used in the operational semantics,\n  and one computable based on the [host_monad] monad, to be used in the interpreter.\n  There is no host state in the host monad: it is entirely caught by the (state) monad. **)\n\n(** ** Predicate Host **)\n\n(** We start with a host expressed as a predicate, useful for proofs. **)\n\nSection Predicate.\n\n(** We assume a set of host functions. **)\nVariable host_function : eqType.\n\nLet store_record := store_record host_function.\nLet store_extension : store_record -> store_record -> bool := @store_extension _.\n\n(** The application of a host function either:\n  - returns [Some (st', result)], returning a new Wasm store and a result (which can be [Trap]),\n  - diverges, represented as [None].\n  This can be non-deterministic. **)\n\nRecord host := {\n    host_state : eqType (** For the relation-based version, we assume some kind of host state. **) ;\n    host_application : host_state -> store_record -> function_type -> host_function -> seq value ->\n                       host_state -> option (store_record * result) -> Prop\n                       (** An application of the host function. **)\n    (* FIXME: Should the resulting [host_state] be part of the [option]?\n      (See https://github.com/rems-project/wasm_coq/issues/16#issuecomment-616402508\n       for a discussion about this.) *) ;\n\n    host_application_extension : forall s t st h vs s' st' r,\n      host_application s st t h vs s' (Some (st', r)) ->\n      store_extension st st' (** The returned store must be an extension of the original one. **) ;\n    host_application_typing : forall s t st h vs s' st' r,\n      host_application s st t h vs s' (Some (st', r)) ->\n      store_typing st ->\n      store_typing st' (** [host_application] preserves store typing. **) ;\n    host_application_respect : forall s t1s t2s st h vs s' st' r,\n      all2 types_agree t1s vs ->\n      host_application s st (Tf t1s t2s) h vs s' (Some (st', r)) ->\n      result_types_agree t2s r (** [host_application] respects types. **)\n  }.\n\nEnd Predicate.\n\nArguments host_application [_ _].\n\n(** ** Executable Host **)\n\n(** We start with a host expressed as a predicate, useful for proofs. **)\n\nSection Executable.\n\n(** We assume a set of host functions.\n  To help with the extraction, it is expressed as a [Type] and not an [eqType]. **)\nVariable host_function : Type.\n\nLet store_record := store_record host_function.\nRecord executable_host := make_executable_host {\n    host_event : Type -> Type (** The events that the host actions can yield. **) ;\n    host_monad : Monad host_event (** They form a monad. **) ;\n    host_apply : store_record -> function_type -> host_function -> seq value ->\n                 host_event (option (store_record * result))\n                 (** The application of a host function, returning a value in the monad. **)\n  }.\n\nEnd Executable.\n\nArguments host_apply [_ _].\n\n(** ** Relation between both versions **)\n\nSection Parameterised.\n\nVariable host_function : eqType.\n\nLet store_record := store_record host_function.\n\nLet host : Type := host host_function.\nLet executable_host : Type := executable_host host_function.\n\nVariable phost : host.\nVariable ehost : executable_host.\n\n(* TODO. What we really need is the property with the interactive tree interpretation.\n(** Relation between [host] and [executable_host]. **)\nDefinition host_spec :=\n  forall st t h vs st' r,\n    host_apply ehost st t h vs = Some (st', r) -> (* FIXME: under the [host_event] monad! *)\n    host_application host st t h vs st' r.\n*)\n\nEnd Parameterised.\n\n\n(** * Extractible module **)\n\n(** The definitions of the previous section are based on dependent types, which are very\n  practical to manipulate them in Coq, but do not extract very well.\n  The following is an extract-friendly adaptation using modules.\n  We also require other useful hypotheses **)\n\nModule Type Executable_Host.\n\nParameter host_function : Type.\nParameter host_function_eq_dec : forall f1 f2 : host_function, {f1 = f2} + {f1 <> f2}.\nParameter host_event : Type -> Type.\nParameter host_ret : forall t : Type, t -> host_event t.\nParameter host_bind : forall t u : Type, host_event t -> (t -> host_event u) -> host_event u.\n\nParameter host_apply : store_record host_function -> function_type -> host_function -> seq value ->\n                       host_event (option (store_record host_function * result)).\n\nEnd Executable_Host.\n\n(** Such a module can easily be converted into an [executable_host] definition. **)\n\nModule convert_to_executable_host (H : Executable_Host).\n\nExport H.\n\nDefinition host_function_eqb f1 f2 : bool := host_function_eq_dec f1 f2.\n\nDefinition host_functionP : Equality.axiom host_function_eqb :=\n  eq_dec_Equality_axiom host_function_eq_dec.\n\nCanonical Structure host_function_eqMixin := EqMixin host_functionP.\nCanonical Structure host_function :=\n  Eval hnf in EqType _ host_function_eqMixin.\n\nDefinition executable_host := executable_host H.host_function.\nDefinition store_record := store_record H.host_function.\nDefinition config_tuple := config_tuple H.host_function.\n(*Definition administrative_instruction := administrative_instruction H.host_function.*)\nDefinition function_closure := function_closure H.host_function.\nDefinition res_tuple := res_tuple H.host_function.\n\nDefinition host_monad : Monad host_event := {|\n    ret := host_ret ;\n    bind := host_bind\n  |}.\n\nDefinition executable_host_instance : executable_host :=\n  make_executable_host host_monad host_apply.\n\nDefinition host_functor := Functor_Monad (M := host_monad).\n\nEnd convert_to_executable_host.\n\n\n(** * Host instantiations **)\n\n(** ** Dummy host **)\n\nFrom ExtLib Require Import IdentityMonad.\n\n(** This host provides no function. **)\n\nModule DummyHost : Executable_Host.\n\nDefinition host_function := void.\nDefinition host_event := ident.\nDefinition host_ret := @ret _ Monad_ident.\nDefinition host_bind := @bind _ Monad_ident.\nDefinition store_record := store_record host_function.\nDefinition host_apply (_ : store_record) (_ : function_type) :=\n  of_void (seq value -> ident (option (store_record * result))).\n\nDefinition host_function_eq_dec : forall f1 f2 : host_function, {f1 = f2} + {f1 <> f2}.\nProof. decidable_equality. Defined.\n\nEnd DummyHost.\n\nModule DummyHosts.\n\nModule Exec := convert_to_executable_host DummyHost.\nExport Exec.\n\nDefinition host : Type := host host_function.\n\nDefinition host_instance : host.\nProof.\n  by refine {|\n      host_state := unit_eqType ;\n      host_application _ _ _ _ _ _ _ := False\n    |}; intros; exfalso; auto.\nDefined.\n\n(* TODO: host_spec *)\n\nEnd DummyHosts.\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/host.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19925680085273037}}
{"text": "(*===========================================================================\n    Processor state: registers, flags and memory\n  ===========================================================================*)\nRequire Import ssreflect ssrfun ssrbool finfun fintype.\nRequire Export update reg regstate flags mem bitsrep.\nRequire Import 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\n(* @TODO: update lemmas *)\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/procstate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.19923329715255295}}
{"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(** Architecture-dependent parameters for IA32 *)\n\nRequire Import ZArith.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\n\nDefinition big_endian := false.\n\nNotation align_int64 := 4%Z (only parsing).\nNotation align_float64 := 4%Z (only parsing).\n\nProgram Definition default_pl_64 : bool * nan_pl 53 :=\n  (true, nat_iter 51 xO xH).\n\nDefinition choose_binop_pl_64 (s1: bool) (pl1: nan_pl 53) (s2: bool) (pl2: nan_pl 53) :=\n  false.                        (**r always choose first NaN *)\n\nProgram Definition default_pl_32 : bool * nan_pl 24 :=\n  (true, nat_iter 22 xO xH).\n\nDefinition choose_binop_pl_32 (s1: bool) (pl1: nan_pl 24) (s2: bool) (pl2: nan_pl 24) :=\n  false.                        (**r always choose first NaN *)\n\nDefinition float_of_single_preserves_sNaN := false.\n\nGlobal Opaque big_endian\n              default_pl_64 choose_binop_pl_64\n              default_pl_32 choose_binop_pl_32\n              float_of_single_preserves_sNaN.\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/boolcirc/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.19908995257912407}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Export Maps.\nRequire Import Events.\nRequire Import Globalenvs.\n\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Stacklayout.\n\nRequire Import Mach. \nRequire Import Mach_coop. \n\nRequire Import mem_lemmas. (*for mem_forward*)\nRequire Import semantics.\nRequire Import effect_semantics.\nRequire Import BuiltinEffects.\nRequire Import load_frame.\n\nNotation \"a ## b\" := (List.map a b) (at level 1).\nNotation \"a # b <- c\" := (Regmap.set b c a) (at level 1, b at next level).\n\nSection MACH_EFFSEM.\nVariable hf : I64Helpers.helper_functions.\nVariable return_address_offset: function -> code -> int -> Prop.\n\nInductive mach_effstep (ge:genv): (block -> Z -> bool) -> \n                        Mach_core -> mem -> Mach_core -> mem -> Prop :=\n  | Mach_effexec_Mlabel:\n      forall s f sp lbl c rs m lf,\n      mach_effstep ge EmptyEffect \n        (Mach_State s f sp (Mlabel lbl :: c) rs lf) m\n        (Mach_State s f sp c rs lf) m\n  | Mach_effexec_Mgetstack:\n      forall s f sp ofs ty dst c rs m v lf,\n      load_stack m sp ty ofs = Some v ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s f sp (Mgetstack ofs ty dst :: c) rs lf) m\n        (Mach_State s f sp c (rs#dst <- v) lf) m\n  | Mach_effexec_Msetstack:\n      forall s f sp src ofs ty c rs m m' rs' lf,\n      store_stack m sp ty ofs (rs src) = Some m' ->\n      rs' = undef_regs (destroyed_by_setstack ty) rs ->\n      mach_effstep ge \n        (StoreEffect (Val.add sp (Vint ofs)) (encode_val (chunk_of_type ty) (rs src)))\n        (Mach_State s f sp (Msetstack src ofs ty :: c) rs lf) m\n        (Mach_State s f sp c rs' lf) m'\n  | Mach_effexec_Mgetparam:\n      forall s fb f sp ofs ty dst c rs m v rs' args0 tys0 sp0 retty,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m sp Tint f.(fn_link_ofs) = Some (parent_sp0 sp0 s) ->\n      load_stack m (parent_sp0 sp0 s) ty ofs = Some v ->\n      rs' = (rs # temp_for_parent_frame <- Vundef # dst <- v) ->\n      mach_effstep ge EmptyEffect \n                   (Mach_State s fb sp (Mgetparam ofs ty dst :: c) rs \n                                       (mk_load_frame sp0 args0 tys0 retty)) m\n                   (Mach_State s fb sp c rs' (mk_load_frame sp0 args0 tys0 retty)) m\n  | Mach_effexec_Mop:\n      forall s f sp op args res c rs m v rs' lf,\n      eval_operation ge sp op rs##args m = Some v ->\n      rs' = ((undef_regs (destroyed_by_op op) rs)#res <- v) ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s f sp (Mop op args res :: c) rs lf) m\n        (Mach_State s f sp c rs' lf) m\n  | Mach_effexec_Mload:\n      forall s f sp chunk addr args dst c rs m a v rs' lf,\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.loadv chunk m a = Some v ->\n      rs' = ((undef_regs (destroyed_by_load chunk addr) rs)#dst <- v) ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s f sp (Mload chunk addr args dst :: c) rs lf) m\n        (Mach_State s f sp c rs' lf) m\n  | Mach_effexec_Mstore:\n      forall s f sp chunk addr args src c rs m m' a rs' lf,\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.storev chunk m a (rs src) = Some m' ->\n      rs' = undef_regs (destroyed_by_store chunk addr) rs ->\n      mach_effstep ge (StoreEffect a (encode_val chunk (rs src)))\n        (Mach_State s f sp (Mstore chunk addr args src :: c) rs lf) m\n        (Mach_State s f sp c rs' lf) m'\n  (*NOTE [loader]*)\n  | Mach_effexec_Minitialize_call: \n      forall m args tys m1 stk m2 fb z retty,\n      args_len_rec args tys = Some z -> \n      Mem.alloc m 0 (4*z) = (m1, stk) ->\n      store_args m1 stk args tys = Some m2 -> \n      mach_effstep ge EmptyEffect \n        (Mach_CallstateIn fb args tys retty) m\n        (Mach_Callstate nil fb (Regmap.init Vundef) (mk_load_frame stk args tys retty)) m2\n  | Mach_effexec_Mcall_internal:\n      forall s fb sp sig ros c rs m f f' ra callee lf,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      return_address_offset f c ra ->\n      (*NEW: check that the block f' actually contains a function:*)\n      Genv.find_funct_ptr ge f' = Some (Internal callee) ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s fb sp (Mcall sig ros :: c) rs lf) m\n        (Mach_Callstate (Stackframe fb sp (Vptr fb ra) c :: s) f' rs lf) m\n  | Mach_effexec_Mcall_external:\n      forall s fb sp sig ros c rs m f f' ra callee args lf,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      return_address_offset f c ra ->\n      (*NEW: check that the block f' actually contains a (external) function, \n             and perform the \"extra step\":*)\n      Genv.find_funct_ptr ge f' = Some (External callee) ->\n      extcall_arguments rs m sp (ef_sig callee) args ->\n      mach_effstep ge EmptyEffect\n         (Mach_State s fb sp (Mcall sig ros :: c) rs lf) m\n         (Mach_CallstateOut (Stackframe fb sp (Vptr fb ra) c :: s) f' callee args rs lf) m\n  | Mach_effexec_Mtailcall_internal:\n      forall s fb stk soff sig ros c rs m f f' m' callee sp0 args0 tys0 retty,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp0 sp0 s) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_retaddr_ofs) = Some (parent_ra s) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      (*NEW: check that the block f' actually contains a function:*)\n      Genv.find_funct_ptr ge f' = Some (Internal callee) ->\n      mach_effstep ge (FreeEffect m 0 (f.(fn_stacksize)) stk)\n        (Mach_State s fb (Vptr stk soff) (Mtailcall sig ros :: c) rs (mk_load_frame sp0 args0 tys0 retty)) m\n        (Mach_Callstate s f' rs (mk_load_frame sp0 args0 tys0 retty)) m'\n  | Mach_effexec_Mtailcall_external:\n      forall s fb stk soff sig ros c rs m f f' m' callee args sp0 args0 tys0 retty,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp0 sp0 s) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_retaddr_ofs) = Some (parent_ra s) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      (*NEW: check that the block f' actually contains a function:*)\n       Genv.find_funct_ptr ge f' = Some (External callee) ->\n      extcall_arguments rs m' (parent_sp0 sp0 s) (ef_sig callee) args ->\n      mach_effstep ge (FreeEffect m 0 (f.(fn_stacksize)) stk)\n         (Mach_State s fb (Vptr stk soff) (Mtailcall sig ros :: c) rs (mk_load_frame sp0 args0 tys0 retty)) m\n         (Mach_CallstateOut s f' callee args rs (mk_load_frame sp0 args0 tys0 retty)) m'\n  | Mach_effexec_Mbuiltin:\n      forall s f sp rs m ef args res b t vl rs' m' lf,\n      external_call' ef ge rs##args m t vl m' ->\n      ~ observableEF hf ef ->\n      rs' = set_regs res vl (undef_regs (destroyed_by_builtin ef) rs) ->\n      mach_effstep ge (BuiltinEffect ge ef (decode_longs (sig_args (ef_sig ef)) (rs##args)) m)\n         (Mach_State s f sp (Mbuiltin ef args res :: b) rs lf) m\n         (Mach_State s f sp b rs' lf) m'\n\n(* annotations are observable, so now handled by atExternal\n  | Mach_effexec_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      mach_effstep (Mach_State s f sp (Mannot ef args :: b) rs) m\n         t (Mach_State s f sp b rs) m'*)\n\n  | Mach_effexec_Mgoto:\n      forall s fb f sp lbl c rs m c' lf,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      find_label lbl f.(fn_code) = Some c' ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s fb sp (Mgoto lbl :: c) rs lf) m\n        (Mach_State s fb sp c' rs lf) m\n  | Mach_effexec_Mcond_true:\n      forall s fb f sp cond args lbl c rs m c' rs' lf,\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      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s fb sp (Mcond cond args lbl :: c) rs lf) m\n        (Mach_State s fb sp c' rs' lf) m\n  | Mach_effexec_Mcond_false:\n      forall s f sp cond args lbl c rs m rs' lf,\n      eval_condition cond rs##args m = Some false ->\n      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s f sp (Mcond cond args lbl :: c) rs lf) m\n        (Mach_State s f sp c rs' lf) m\n  | Mach_effexec_Mjumptable:\n      forall s fb f sp arg tbl c rs m n lbl c' rs' lf,\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      rs' = undef_regs destroyed_by_jumptable rs ->\n      mach_effstep ge EmptyEffect \n        (Mach_State s fb sp (Mjumptable arg tbl :: c) rs lf) m\n        (Mach_State s fb sp c' rs' lf) m\n  | Mach_effexec_Mreturn:\n      forall s fb stk soff c rs m f m' sp0 args0 tys0 retty,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp0 sp0 s) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_retaddr_ofs) = Some (parent_ra s) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      mach_effstep ge (FreeEffect m 0 (f.(fn_stacksize)) stk)\n        (Mach_State s fb (Vptr stk soff) (Mreturn :: c) rs (mk_load_frame sp0 args0 tys0 retty)) m\n        (Mach_Returnstate s (sig_res (fn_sig f)) rs (mk_load_frame sp0 args0 tys0 retty)) m'\n  | Mach_effexec_function_internal:\n      forall s fb rs m f m1 m2 m3 stk rs' sp0 args0 tys0 retty,\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      Mem.alloc m 0 f.(fn_stacksize) = (m1, stk) ->\n      let sp := Vptr stk Int.zero in\n      store_stack m1 sp Tint f.(fn_link_ofs) (parent_sp0 sp0 s) = Some m2 ->\n      store_stack m2 sp Tint f.(fn_retaddr_ofs) (parent_ra s) = Some m3 ->\n      rs' = undef_regs destroyed_at_function_entry rs ->\n      mach_effstep ge EmptyEffect \n        (Mach_Callstate s fb rs (mk_load_frame sp0 args0 tys0 retty)) m\n        (Mach_State s fb sp f.(fn_code) rs' (mk_load_frame sp0 args0 tys0 retty)) m3\n\n  | Mach_effexec_function_external:\n      forall cs f' rs m t rs' callee args res m' lf\n      (OBS: EFisHelper hf callee),\n      Genv.find_funct_ptr ge f' = Some (External callee) ->\n      external_call' callee ge args m t res m' ->\n      rs' = set_regs (loc_result (ef_sig callee)) res rs ->\n      mach_effstep ge (BuiltinEffect ge callee args m)\n      (Mach_CallstateOut cs f' callee args rs lf) m\n      (Mach_Returnstate cs (sig_res (ef_sig callee)) rs' lf) m'\n\n  | Mach_effexec_return:\n      forall s f sp ra c retty rs m lf,\n      mach_effstep ge EmptyEffect \n        (Mach_Returnstate (Stackframe f sp ra c :: s) retty rs lf) m\n        (Mach_State s f sp c rs lf) m.\n\nLemma machstep_effax1: forall (M : block -> Z -> bool) ge c m c' m',\n      mach_effstep ge M c m c' m' ->\n      (corestep (Mach_coop_sem hf return_address_offset) ge c m c' m' /\\\n       Mem.unchanged_on (fun (b : block) (ofs : Z) => M b ofs = false) m m').\nProof. \nintros.\n  induction H.\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         unfold store_stack in H.\n         eapply StoreEffect_Storev; eassumption. \n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         eapply StoreEffect_Storev; eassumption. \n  split. econstructor; eassumption. \n    { assert (sp_fresh: ~Mem.valid_block m stk).\n      { eapply Mem.fresh_block_alloc; eauto. }\n      eapply mem_unchanged_on_sub_strong.\n      eapply unchanged_on_trans with (m2 := m1).\n      solve[eapply Mem.alloc_unchanged_on; eauto].\n      solve[eapply store_args_unch_on; eauto].\n      solve[apply alloc_forward in H0; auto].\n      simpl. intros b ofs H2 _ H3. subst. \n      solve[apply sp_fresh; auto]. } \n  split. eapply Mach_exec_Mcall_internal; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. eapply Mach_exec_Mcall_external; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. eapply Mach_exec_Mtailcall_internal; eassumption.\n         eapply FreeEffect_free; eassumption.\n  split. eapply Mach_exec_Mtailcall_external; eassumption.\n         eapply FreeEffect_free; eassumption.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         inv H.\n         eapply BuiltinEffect_unchOn; eassumption.\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. eapply Mach_exec_Mcond_true; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. eapply Mach_exec_Mcond_false; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; try eassumption.\n         apply Mem.unchanged_on_refl.\n  split. econstructor; eassumption.\n         eapply FreeEffect_free; eassumption.\n  split. econstructor; eassumption. subst sp.\n    subst. \n    unfold store_stack, Val.add in *. \n    rewrite Int.add_zero_l in *.\n    simpl in *. \n    remember (Int.unsigned (fn_link_ofs f)) as z1.\n    remember (Int.unsigned (fn_retaddr_ofs f)) as z2.\n    remember (parent_ra s) as v2. \n    clear Heqz1 H Heqz2 Heqv2.\n    split; intros.\n    { split; intros.\n        eapply Mem.perm_store_1; try eassumption.\n        eapply Mem.perm_store_1; try eassumption.\n        eapply Mem.perm_alloc_1; eassumption.\n      apply (Mem.perm_store_2 _ _ _ _ _ _ H2) in H4.\n        apply (Mem.perm_store_2 _ _ _ _ _ _ H1) in H4.\n        eapply Mem.perm_alloc_4; try eassumption.\n         intros N; subst. apply Mem.fresh_block_alloc in H0. \n         contradiction. }\n    { rewrite (Mem.store_mem_contents _ _ _ _ _ _ H2).\n        rewrite (Mem.store_mem_contents _ _ _ _ _ _ H1).\n        assert (BB: b <> stk). \n        { intros N. subst. \n          apply Mem.fresh_block_alloc in H0. \n          apply Mem.perm_valid_block in H3. contradiction. }\n        rewrite PMap.gso; trivial. \n        rewrite PMap.gso; trivial. \n        eapply EmptyEffect_alloc; eassumption. }\n  { split. unfold corestep, coopsem; simpl. econstructor; try eassumption.\n         inv H0.\n       exploit @BuiltinEffect_unchOn. \n         eapply EFhelpers; eassumption.\n         eapply H2. \n       unfold BuiltinEffect; simpl.\n         destruct callee; simpl; trivial; contradiction. }\n  split. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\nQed.\n\nLemma  machstep_effax2 ge c m c' m':\n      corestep (Mach_coop_sem hf return_address_offset) ge c m c' m' ->\n      exists M, mach_effstep ge M c m c' m'.\nProof.\n  intros. unfold corestep, coopsem in H; simpl in H.\n  inv H.\n    eexists. eapply Mach_effexec_Mlabel; eassumption.\n    eexists. eapply Mach_effexec_Mgetstack; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Msetstack; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mgetparam; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mop; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mload; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mstore; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Minitialize_call; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mcall_internal; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mcall_external; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mtailcall_internal; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mtailcall_external; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mbuiltin; try eassumption; trivial.\n(*    eexists. eapply Mach_effexec_Mannot; try eassumption; trivial.*)\n    eexists. eapply Mach_effexec_Mgoto; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mcond_true; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mcond_false; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mjumptable; try eassumption; trivial.\n    eexists. eapply Mach_effexec_Mreturn; try eassumption; trivial.\n    eexists. eapply Mach_effexec_function_internal; try eassumption; trivial.\n    eexists. eapply Mach_effexec_function_external; try eassumption; trivial.\n    eexists. eapply Mach_effexec_return; try eassumption; trivial.\nQed.\n\nLemma mach_effstep_valid: forall (M : block -> Z -> bool) ge c m c' m',\n      mach_effstep ge M c m c' m' ->\n       forall b z, M b z = true -> Mem.valid_block m b.\nProof.\nintros.\n  induction H; try (solve [inv H0]).\n\n  unfold store_stack in H.\n  apply StoreEffectD in H0. destruct H0 as [i [VADDR ARITH]]; subst.\n  destruct sp; inv H. unfold Val.add in VADDR. inv VADDR.\n  apply Mem.store_valid_access_3 in H1.\n  eapply Mem.valid_access_valid_block.\n  eapply Mem.valid_access_implies; try eassumption. constructor.\n\n  apply StoreEffectD in H0. destruct H0 as [ofs [VADDR ARITH]]; subst.\n  inv H1. apply Mem.store_valid_access_3 in H2.\n  eapply Mem.valid_access_valid_block.\n  eapply Mem.valid_access_implies; try eassumption. constructor.\n\n  eapply FreeEffect_validblock; eassumption.\n  eapply FreeEffect_validblock; eassumption.\n  eapply BuiltinEffect_valid_block; eassumption.\n  eapply FreeEffect_validblock; eassumption.\n  eapply BuiltinEffect_valid_block; eassumption.\nQed.\n\nProgram Definition Mach_eff_sem : \n  @EffectSem genv Mach_core.\nProof.\neapply Build_EffectSem with \n (sem := Mach_coop_sem hf return_address_offset).\napply machstep_effax1.\napply machstep_effax2.\napply mach_effstep_valid. \nDefined.\n\nEnd MACH_EFFSEM.", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/backend/Mach_eff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1990899359183549}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Typing rules and a type inference algorithm for RTL. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Unityping.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import Globalenvs.\nRequire Import Values.\nRequire Import Integers.\nRequire Import Memory.\nRequire Import Events.\nRequire Import RTL RTLmach.\nRequire Import Conventions.\n\n(** * The type system *)\n\n(** Like Cminor and all intermediate languages, RTL can be equipped with\n  a simple type system that statically guarantees that operations\n  and addressing modes are applied to the right number of arguments\n  and that the arguments are of the correct types.   The type algebra\n  is very simple, consisting of the four types [Tint] (for integers\n  and pointers), [Tfloat] (for double-precision floats), [Tlong]\n  (for 64-bit integers) and [Tsingle] (for single-precision floats).\n\n  Additionally, we impose that each pseudo-register has the same type\n  throughout the function.  This requirement helps with register allocation,\n  enabling each pseudo-register to be mapped to a single hardware register\n  or stack location of the correct type.\n\n  Finally, we also check that the successors of instructions\n  are valid, i.e. refer to non-empty nodes in the CFG.\n\n  The typing judgement for instructions is of the form [wt_instr f env\n  instr], where [f] is the current function (used to type-check\n  [Ireturn] instructions) and [env] is a typing environment\n  associating types to pseudo-registers.  Since pseudo-registers have\n  unique types throughout the function, the typing environment does\n  not change during type-checking of individual instructions.  One\n  point to note is that we have one polymorphic operator, [Omove],\n  which can work over both integers and floats.\n*)\n\nDefinition regenv := reg -> typ.\n\nSection WT_INSTR.\n\nVariable funct: function.\nVariable env: regenv.\n\nDefinition valid_successor (s: node) : Prop :=\n  exists i, funct.(fn_code)!s = Some i.\n\nDefinition type_of_builtin_arg (a: builtin_arg reg) : typ :=\n  match a with\n  | BA r => env r\n  | BA_int _ => Tint\n  | BA_long _ => Tlong\n  | BA_float _ => Tfloat\n  | BA_single _ => Tsingle\n  | BA_loadstack chunk ofs => type_of_chunk chunk\n  | BA_addrstack ofs => Tptr\n  | BA_loadglobal chunk id ofs => type_of_chunk chunk\n  | BA_addrglobal id ofs => Tptr\n  | BA_splitlong hi lo => Tlong\n  | BA_addptr a1 a2 => Tptr\n  end.\n\nDefinition type_of_builtin_res (r: builtin_res reg) : typ :=\n  match r with\n  | BR r => env r\n  | _    => Tint\n  end.\n\nInductive wt_instr : instruction -> Prop :=\n  | wt_Inop:\n      forall s,\n      valid_successor s ->\n      wt_instr (Inop s)\n  | wt_Iopmove:\n      forall r1 r s,\n      env r = env r1 ->\n      valid_successor s ->\n      wt_instr (Iop Omove (r1 :: nil) r s)\n  | wt_Iop:\n      forall op args res s,\n      op <> Omove ->\n      map env args = fst (type_of_operation op) ->\n      env res = snd (type_of_operation op) ->\n      valid_successor s ->\n      wt_instr (Iop op args res s)\n  | wt_Iload:\n      forall chunk addr args dst s,\n      map env args = type_of_addressing addr ->\n      env dst = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Iload chunk addr args dst s)\n  | wt_Istore:\n      forall chunk addr args src s,\n      map env args = type_of_addressing addr ->\n      env src = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Istore chunk addr args src s)\n  | wt_Icall:\n      forall sig ros args res s,\n      match ros with inl r => env r = Tptr | inr s => True end ->\n      map env args = sig.(sig_args) ->\n      env res = proj_sig_res sig ->\n      valid_successor s ->\n      wt_instr (Icall sig ros args res s)\n  | wt_Itailcall:\n      forall sig ros args,\n      match ros with inl r => env r = Tptr | inr s => True end ->\n      map env args = sig.(sig_args) ->\n      sig.(sig_res) = funct.(fn_sig).(sig_res) ->\n      tailcall_possible sig ->\n      wt_instr (Itailcall sig ros args)\n  | wt_Ibuiltin:\n      forall ef args res s,\n      match ef with\n      | EF_annot _ _ _ | EF_debug _ _ _ => True\n      | _ => map type_of_builtin_arg args = (ef_sig ef).(sig_args)\n      end ->\n      type_of_builtin_res res = proj_sig_res (ef_sig ef) ->\n      valid_successor s ->\n      wt_instr (Ibuiltin ef args res s)\n  | wt_Icond:\n      forall cond args s1 s2,\n      map env args = type_of_condition cond ->\n      valid_successor s1 ->\n      valid_successor s2 ->\n      wt_instr (Icond cond args s1 s2)\n  | wt_Ijumptable:\n      forall arg tbl,\n      env arg = Tint ->\n      (forall s, In s tbl -> valid_successor s) ->\n      list_length_z tbl * 4 <= Int.max_unsigned ->\n      wt_instr (Ijumptable arg tbl)\n  | wt_Ireturn_none:\n      funct.(fn_sig).(sig_res) = Tvoid ->\n      wt_instr (Ireturn None)\n  | wt_Ireturn_some:\n      forall arg ty,\n      funct.(fn_sig).(sig_res) <> Tvoid ->\n      env arg = proj_sig_res funct.(fn_sig) ->\n      env arg = ty ->\n      wt_instr (Ireturn (Some arg)).\n\nEnd WT_INSTR.\n\n(** A function [f] is well-typed w.r.t. a typing environment [env],\n   written [wt_function env f], if all instructions are well-typed,\n   parameters agree in types with the function signature, and\n   parameters are pairwise distinct. *)\n\nRecord wt_function (f: function) (env: regenv): Prop :=\n  mk_wt_function {\n    wt_params:\n      map env f.(fn_params) = f.(fn_sig).(sig_args);\n    wt_norepet:\n      list_norepet f.(fn_params);\n    wt_instrs:\n      forall pc instr,\n      f.(fn_code)!pc = Some instr -> wt_instr f env instr;\n    wt_entrypoint:\n      valid_successor f f.(fn_entrypoint)\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef)\n  | wt_function_internal: forall f env,\n      wt_function f env ->\n      wt_fundef (Internal f).\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, Gfun f) (prog_defs p) -> wt_fundef f.\n\n(** * Type inference *)\n\n(** Type inference reuses the generic solver for unification constraints\n  defined in module [Unityping]. *)\n\nModule RTLtypes <: TYPE_ALGEBRA.\n\nDefinition t := typ.\nDefinition eq := typ_eq.\nDefinition default := Tint.\n\nEnd RTLtypes.\n\nModule S := UniSolver(RTLtypes).\n\nSection INFERENCE.\n\nLocal Open Scope error_monad_scope.\n\nVariable f: function.\n\n(** Checking the validity of successor nodes. *)\n\nDefinition check_successor (s: node): res unit :=\n  match f.(fn_code)!s with\n  | None => Error (MSG \"bad successor \" :: POS s :: nil)\n  | Some i => OK tt\n  end.\n\nFixpoint check_successors (sl: list node): res unit :=\n  match sl with\n  | nil => OK tt\n  | s1 :: sl' => do x <- check_successor s1; check_successors sl'\n  end.\n\n(** Check structural constraints and process / record all type constraints. *)\n\nDefinition type_ros (e: S.typenv) (ros: reg + ident) : res S.typenv :=\n  match ros with\n  | inl r => S.set e r Tptr\n  | inr s => OK e\n  end.\n\nDefinition is_move (op: operation) : bool :=\n  match op with Omove => true | _ => false end.\n\nDefinition type_expect (e: S.typenv) (t1 t2: typ) : res S.typenv :=\n  if typ_eq t1 t2 then OK e else Error(msg \"unexpected type\").\n\nDefinition type_builtin_arg (e: S.typenv) (a: builtin_arg reg) (ty: typ) : res S.typenv :=\n  match a with\n  | BA r => S.set e r ty\n  | BA_int _ => type_expect e ty Tint\n  | BA_long _ => type_expect e ty Tlong\n  | BA_float _ => type_expect e ty Tfloat\n  | BA_single _ => type_expect e ty Tsingle\n  | BA_loadstack chunk ofs => type_expect e ty (type_of_chunk chunk)\n  | BA_addrstack ofs => type_expect e ty Tptr\n  | BA_loadglobal chunk id ofs => type_expect e ty (type_of_chunk chunk)\n  | BA_addrglobal id ofs => type_expect e ty Tptr\n  | BA_splitlong hi lo => type_expect e ty Tlong\n  | BA_addptr a1 a2 => type_expect e ty Tptr\n  end.\n\nFixpoint type_builtin_args (e: S.typenv) (al: list (builtin_arg reg)) (tyl: list typ) : res S.typenv :=\n  match al, tyl with\n  | nil, nil => OK e\n  | a1 :: al, ty1 :: tyl =>\n      do e1 <- type_builtin_arg e a1 ty1; type_builtin_args e1 al tyl\n  | _, _ =>\n      Error (msg \"builtin arity mismatch\")\n  end.\n\nDefinition type_builtin_res (e: S.typenv) (a: builtin_res reg) (ty: typ) : res S.typenv :=\n  match a with\n  | BR r => S.set e r ty\n  | _    => type_expect e ty Tint\n  end.\n\nDefinition type_instr (e: S.typenv) (i: instruction) : res S.typenv :=\n  match i with\n  | Inop s =>\n      do x <- check_successor s; OK e\n  | Iop op args res s =>\n      do x <- check_successor s;\n      if is_move op then\n        match args with\n        | arg :: nil => do (changed, e') <- S.move e res arg; OK e'\n        | _ => Error (msg \"ill-formed move\")\n        end\n      else\n       (let (targs, tres) := type_of_operation op in\n        do e1 <- S.set_list e args targs; S.set e1 res tres)\n  | Iload chunk addr args dst s =>\n      do x <- check_successor s;\n      do e1 <- S.set_list e args (type_of_addressing addr);\n      S.set e1 dst (type_of_chunk chunk)\n  | Istore chunk addr args src s =>\n      do x <- check_successor s;\n      do e1 <- S.set_list e args (type_of_addressing addr);\n      S.set e1 src (type_of_chunk chunk)\n  | Icall sig ros args res s =>\n      do x <- check_successor s;\n      do e1 <- type_ros e ros;\n      do e2 <- S.set_list e1 args sig.(sig_args);\n      S.set e2 res (proj_sig_res sig)\n  | Itailcall sig ros args =>\n      do e1 <- type_ros e ros;\n      do e2 <- S.set_list e1 args sig.(sig_args);\n      if rettype_eq sig.(sig_res) f.(fn_sig).(sig_res) then\n        if tailcall_is_possible sig\n        then OK e2\n        else Error(msg \"tailcall not possible\")\n      else Error(msg \"bad return type in tailcall\")\n  | Ibuiltin ef args res s =>\n      let sig := ef_sig ef in\n      do x <- check_successor s;\n      do e1 <-\n        match ef with\n        | EF_annot _ _ _ | EF_debug _ _ _ => OK e\n        | _ => type_builtin_args e args sig.(sig_args)\n        end;\n      type_builtin_res e1 res (proj_sig_res sig)\n | Icond cond args s1 s2 =>\n      do x1 <- check_successor s1;\n      do x2 <- check_successor s2;\n      S.set_list e args (type_of_condition cond)\n | Ijumptable arg tbl =>\n      do x <- check_successors tbl;\n      do e1 <- S.set e arg Tint;\n      if zle (list_length_z tbl * 4) Int.max_unsigned\n      then OK e1\n      else Error(msg \"jumptable too big\")\n  | Ireturn optres =>\n      match optres, rettype_eq f.(fn_sig).(sig_res) Tvoid with\n      | None, left _ => OK e\n      | Some r, right _ => S.set e r (proj_sig_res f.(fn_sig))\n      | _, _ => Error(msg \"bad return\")\n      end\n  end.\n\nDefinition type_code (e: S.typenv): res S.typenv :=\n  PTree.fold (fun re pc i =>\n    match re with\n    | Error _ => re\n    | OK e =>\n        match type_instr e i with\n        | Error msg => Error(MSG \"At PC \" :: POS pc :: MSG \": \" :: msg)\n        | OK e' => OK e'\n        end\n    end)\n  f.(fn_code) (OK e).\n\n(** Solve remaining constraints *)\n\nDefinition check_params_norepet (params: list reg): res unit :=\n  if list_norepet_dec Reg.eq params\n  then OK tt\n  else Error(msg \"duplicate parameters\").\n\nDefinition type_function : res regenv :=\n  do e1 <- type_code S.initial;\n  do e2 <- S.set_list e1 f.(fn_params) f.(fn_sig).(sig_args);\n  do te <- S.solve e2;\n  do x1 <- check_params_norepet f.(fn_params);\n  do x2 <- check_successor f.(fn_entrypoint);\n  OK te.\n\n(** ** Soundness proof *)\n\nRemark type_ros_incr:\n  forall e ros e' te, type_ros e ros = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold type_ros; intros. destruct ros. eauto with ty. inv H; auto with ty.\nQed.\n\nHint Resolve type_ros_incr: ty.\n\nLemma type_ros_sound:\n  forall e ros e' te, type_ros e ros = OK e' -> S.satisf te e' ->\n  match ros with inl r => te r = Tptr | inr s => True end.\nProof.\n  unfold type_ros; intros. destruct ros.\n  eapply S.set_sound; eauto.\n  auto.\nQed.\n\nLemma check_successor_sound:\n  forall s x, check_successor s = OK x -> valid_successor f s.\nProof.\n  unfold check_successor, valid_successor; intros.\n  destruct (fn_code f)!s; inv H. exists i; auto.\nQed.\n\nHint Resolve check_successor_sound: ty.\n\nLemma check_successors_sound:\n  forall sl x, check_successors sl = OK x -> forall s, In s sl -> valid_successor f s.\nProof.\n  induction sl; simpl; intros.\n  contradiction.\n  monadInv H. destruct H0. subst a; eauto with ty. eauto.\nQed.\n\nRemark type_expect_incr:\n  forall e ty1 ty2 e' te, type_expect e ty1 ty2 = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold type_expect; intros. destruct (typ_eq ty1 ty2); inv H. auto.\nQed.\n\nHint Resolve type_expect_incr: ty.\n\nLemma type_expect_sound:\n  forall e ty1 ty2 e', type_expect e ty1 ty2 = OK e' -> ty1 = ty2.\nProof.\n  unfold type_expect; intros. destruct (typ_eq ty1 ty2); inv H. auto.\nQed.\n\nLemma type_builtin_arg_incr:\n  forall e a ty e' te, type_builtin_arg e a ty = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold type_builtin_arg; intros; destruct a; eauto with ty.\nQed.\n\nLemma type_builtin_args_incr:\n  forall a ty e e' te, type_builtin_args e a ty = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  induction a; destruct ty; simpl; intros; try discriminate.\n  inv H; auto.\n  monadInv H. eapply type_builtin_arg_incr; eauto.\nQed.\n\nLemma type_builtin_res_incr:\n  forall e a ty e' te, type_builtin_res e a ty = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold type_builtin_res; intros; destruct a; inv H; eauto with ty.\nQed.\n\nHint Resolve type_builtin_args_incr type_builtin_res_incr: ty.\n\nLemma type_builtin_arg_sound:\n  forall e a ty e' te,\n  type_builtin_arg e a ty = OK e' -> S.satisf te e' -> type_of_builtin_arg te a = ty.\nProof.\n  intros. destruct a; simpl in *; try (symmetry; eapply type_expect_sound; eassumption).\n  eapply S.set_sound; eauto.\nQed.\n\nLemma type_builtin_args_sound:\n  forall al tyl e e' te,\n  type_builtin_args e al tyl = OK e' -> S.satisf te e' -> List.map (type_of_builtin_arg te) al = tyl.\nProof.\n  induction al as [|a al]; destruct tyl as [|ty tyl]; simpl; intros; try discriminate.\n- auto.\n- monadInv H. f_equal.\n  eapply type_builtin_arg_sound; eauto with ty.\n  eauto.\nQed.\n\nLemma type_builtin_res_sound:\n  forall e a ty e' te,\n  type_builtin_res e a ty = OK e' -> S.satisf te e' -> type_of_builtin_res te a = ty.\nProof.\n  intros. destruct a; simpl in *.\n  eapply S.set_sound; eauto.\n  symmetry; eapply type_expect_sound; eauto.\n  symmetry; eapply type_expect_sound; eauto.\nQed.\n\nLemma type_instr_incr:\n  forall e i e' te,\n  type_instr e i = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  intros; destruct i; try (monadInv H); eauto with ty.\n- (* op *)\n  destruct (is_move o) eqn:ISMOVE.\n  destruct l; try discriminate. destruct l; monadInv EQ0. eauto with ty.\n  destruct (type_of_operation o) as [targs tres] eqn:TYOP. monadInv EQ0. eauto with ty.\n- (* tailcall *)\n  destruct (rettype_eq (sig_res s) (sig_res (fn_sig f))); try discriminate.\n  destruct (tailcall_is_possible s) eqn:TCIP; inv EQ2.\n  eauto with ty.\n- (* builtin *)\n  destruct e0; try monadInv EQ1; eauto with ty.\n- (* jumptable *)\n  destruct (zle (list_length_z l * 4) Int.max_unsigned); inv EQ2.\n  eauto with ty.\n- (* return *)\n  simpl in H.\n  destruct o as [r|] eqn: RET; destruct (rettype_eq (sig_res (fn_sig f)) Tvoid); try discriminate.\n  eauto with ty.\n  inv H; auto with ty.\nQed.\n\nLemma type_instr_sound:\n  forall e i e' te,\n  type_instr e i = OK e' -> S.satisf te e' -> wt_instr f te i.\nProof.\n  intros; destruct i; try (monadInv H); simpl.\n- (* nop *)\n  constructor; eauto with ty.\n- (* op *)\n  destruct (is_move o) eqn:ISMOVE.\n  (* move *)\n  + assert (o = Omove) by (unfold is_move in ISMOVE; destruct o; congruence).\n    subst o.\n    destruct l; try discriminate. destruct l; monadInv EQ0.\n    constructor. eapply S.move_sound; eauto. eauto with ty.\n  + destruct (type_of_operation o) as [targs tres] eqn:TYOP. monadInv EQ0.\n    apply wt_Iop.\n    unfold is_move in ISMOVE; destruct o; congruence.\n    rewrite TYOP. eapply S.set_list_sound; eauto with ty.\n    rewrite TYOP. eapply S.set_sound; eauto with ty.\n    eauto with ty.\n- (* load *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* store *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* call *)\n  constructor.\n  eapply type_ros_sound; eauto with ty.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* tailcall *)\n  destruct (rettype_eq (sig_res s) (sig_res (fn_sig f))); try discriminate.\n  destruct (tailcall_is_possible s) eqn:TCIP; inv EQ2.\n  constructor.\n  eapply type_ros_sound; eauto with ty.\n  eapply S.set_list_sound; eauto with ty.\n  auto.\n  apply tailcall_is_possible_correct; auto.\n- (* builtin *)\n  constructor.\n  destruct e0; auto; eapply type_builtin_args_sound; eauto with ty.\n  eapply type_builtin_res_sound; eauto.\n  eauto with ty.\n- (* cond *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eauto with ty.\n  eauto with ty.\n- (* jumptable *)\n  destruct (zle (list_length_z l * 4) Int.max_unsigned); inv EQ2.\n  constructor.\n  eapply S.set_sound; eauto.\n  eapply check_successors_sound; eauto.\n  auto.\n- (* return *)\n  simpl in H.\n  destruct o as [r|] eqn: RET; destruct (rettype_eq (sig_res (fn_sig f)) Tvoid); try discriminate.\n  econstructor. auto. eapply S.set_sound; eauto with ty. eauto.\n  inv H. constructor. auto.\nQed.\n\nLemma type_code_sound:\n  forall pc i e e' te,\n  type_code e = OK e' ->\n  f.(fn_code)!pc = Some i -> S.satisf te e' -> wt_instr f te i.\nProof.\n  intros pc i e0 e1 te TCODE.\n  set (P := fun c opte =>\n         match opte with\n         | Error _ => True\n         | OK e' => c!pc = Some i -> S.satisf te e' -> wt_instr f te i\n         end).\n  change (P f.(fn_code) (OK e1)).\n  rewrite <- TCODE. unfold type_code. apply PTree_Properties.fold_rec; unfold P; intros.\n  - (* extensionality *)\n    destruct a; auto; intros. rewrite <- H in H1. eapply H0; eauto.\n  - (* base case *)\n    rewrite PTree.gempty in H; discriminate.\n  - (* inductive case *)\n    destruct a as [e|?]; auto.\n    destruct (type_instr e v) as [e'|?] eqn:TYINSTR; auto.\n    intros. rewrite PTree.gsspec in H2. destruct (peq pc k).\n    inv H2. eapply type_instr_sound; eauto.\n    eapply H1; eauto. eapply type_instr_incr; eauto.\nQed.\n\nTheorem type_function_correct:\n  forall env, type_function = OK env -> wt_function f env.\nProof.\n  unfold type_function; intros. monadInv H.\n  assert (SAT0: S.satisf env x0) by (eapply S.solve_sound; eauto).\n  assert (SAT1: S.satisf env x) by (eauto with ty).\n  constructor.\n- (* type of parameters *)\n  eapply S.set_list_sound; eauto.\n- (* parameters are unique *)\n  unfold check_params_norepet in EQ2.\n  destruct (list_norepet_dec Reg.eq (fn_params f)); inv EQ2; auto.\n- (* instructions are well typed *)\n  intros. eapply type_code_sound; eauto.\n- (* entry point is valid *)\n  eauto with ty.\nQed.\n\n(** ** Completeness proof *)\n\nLemma type_ros_complete:\n  forall te ros e,\n  S.satisf te e ->\n  match ros with inl r => te r = Tptr | inr s => True end ->\n  exists e', type_ros e ros = OK e' /\\ S.satisf te e'.\nProof.\n  intros; destruct ros; simpl.\n  eapply S.set_complete; eauto.\n  exists e; auto.\nQed.\n\nLemma check_successor_complete:\n  forall s, valid_successor f s -> check_successor s = OK tt.\nProof.\n  unfold valid_successor, check_successor; intros.\n  destruct H as [i EQ]; rewrite EQ; auto.\nQed.\n\nLemma type_expect_complete:\n  forall e ty, type_expect e ty ty = OK e.\nProof.\n  unfold type_expect; intros. rewrite dec_eq_true; auto.\nQed.\n\nLemma type_builtin_arg_complete:\n  forall te a e,\n  S.satisf te e ->\n  exists e', type_builtin_arg e a (type_of_builtin_arg te a) = OK e' /\\ S.satisf te e'.\nProof.\n  intros. destruct a; simpl; try (exists e; split; [apply type_expect_complete|assumption]).\n  apply S.set_complete; auto.\nQed.\n\nLemma type_builtin_args_complete:\n  forall te al e,\n  S.satisf te e ->\n  exists e', type_builtin_args e al (List.map (type_of_builtin_arg te) al) = OK e' /\\ S.satisf te e'.\nProof.\n  induction al; simpl; intros.\n- exists e; auto.\n- destruct (type_builtin_arg_complete te a e) as (e1 & A & B); auto.\n  destruct (IHal e1) as (e2 & C & D); auto.\n  exists e2; split; auto. rewrite A. auto.\nQed.\n\nLemma type_builtin_res_complete:\n  forall te a e,\n  S.satisf te e ->\n  exists e', type_builtin_res e a (type_of_builtin_res te a) = OK e' /\\ S.satisf te e'.\nProof.\n  intros. destruct a; simpl.\n  apply S.set_complete; auto.\n  exists e; auto.\n  exists e; auto.\nQed.\n\nLemma type_instr_complete:\n  forall te e i,\n  S.satisf te e ->\n  wt_instr f te i ->\n  exists e', type_instr e i = OK e' /\\ S.satisf te e'.\nProof.\n  induction 2; simpl.\n- (* nop *)\n  econstructor; split. rewrite check_successor_complete; simpl; eauto. auto.\n- (* move *)\n  exploit S.move_complete; eauto. intros (changed & e' & A & B).\n  exists e'; split. rewrite check_successor_complete by auto; simpl. rewrite A; auto. auto.\n- (* other op *)\n  destruct (type_of_operation op) as [targ tres]. simpl in *.\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl.\n  replace (is_move op) with false. rewrite A; simpl; rewrite C; auto.\n  destruct op; reflexivity || congruence.\n- (* load *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl.\n  rewrite A; simpl; rewrite C; auto.\n- (* store *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl.\n  rewrite A; simpl; rewrite C; auto.\n- (* call *)\n  exploit type_ros_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_list_complete. eauto. eauto. intros [e2 [C D]].\n  exploit S.set_complete. eexact D. eauto. intros [e3 [E F]].\n  exists e3; split; auto.\n  rewrite check_successor_complete by auto; simpl.\n  rewrite A; simpl; rewrite C; simpl; rewrite E; auto.\n- (* tailcall *)\n  exploit type_ros_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_list_complete. eauto. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite A; simpl; rewrite C; simpl.\n  rewrite H2; rewrite dec_eq_true.\n  replace (tailcall_is_possible sig) with true; auto.\n  symmetry. unfold tailcall_is_possible. apply forallb_forall.\n  intros. apply H3 in H4. destruct x; intuition auto.\n- (* builtin *)\n  exploit type_builtin_args_complete; eauto. instantiate (1 := args). intros [e1 [A B]].\n  exploit type_builtin_res_complete; eauto. instantiate (1 := res). intros [e2 [C D]].\n  exploit type_builtin_res_complete. eexact H. instantiate (1 := res). intros [e3 [E F]].\n  rewrite check_successor_complete by auto. simpl.\n  exists (match ef with EF_annot _ _ _ | EF_debug _ _ _ => e3 | _ => e2 end); split.\n  rewrite H1 in C, E.\n  destruct ef; try (rewrite <- H0; rewrite A); simpl; auto.\n  destruct ef; auto.\n- (* cond *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exists e1; split; auto.\n  rewrite check_successor_complete by auto; simpl.\n  rewrite check_successor_complete by auto; simpl.\n  auto.\n- (* jumptbl *)\n  exploit S.set_complete. eauto. eauto. intros [e1 [A B]].\n  exists e1; split; auto.\n  replace (check_successors tbl) with (OK tt). simpl.\n  rewrite A; simpl. apply zle_true; auto.\n  revert H1. generalize tbl. induction tbl0; simpl; intros. auto.\n  rewrite check_successor_complete by auto; simpl.\n  apply IHtbl0; intros; auto.\n- (* return none *)\n  rewrite H0, dec_eq_true. exists e; auto.\n- (* return some *)\n  rewrite dec_eq_false by auto. apply S.set_complete; auto.\nQed.\n\nLemma type_code_complete:\n  forall te e,\n  (forall pc instr, f.(fn_code)!pc = Some instr -> wt_instr f te instr) ->\n  S.satisf te e ->\n  exists e', type_code e = OK e' /\\ S.satisf te e'.\nProof.\n  intros te e0 WTC SAT0.\n  set (P := fun c res =>\n        (forall pc i, c!pc = Some i -> wt_instr f te i) ->\n        exists e', res = OK e' /\\ S.satisf te e').\n  assert (P f.(fn_code) (type_code e0)).\n  {\n    unfold type_code. apply PTree_Properties.fold_rec; unfold P; intros.\n    - apply H0. intros. apply H1 with pc. rewrite <- H; auto.\n    - exists e0; auto.\n    - destruct H1 as [e [A B]].\n      intros. apply H2 with pc. rewrite PTree.gso; auto. congruence.\n      subst a.\n      destruct (type_instr_complete te e v) as [e' [C D]].\n      auto. apply H2 with k. apply PTree.gss.\n      exists e'; split; auto. rewrite C; auto.\n  }\n  apply H; auto.\nQed.\n\nTheorem type_function_complete:\n  forall te, wt_function f te -> exists te, type_function = OK te.\nProof.\n  intros. destruct H.\n  destruct (type_code_complete te S.initial) as (e1 & A & B).\n  auto. apply S.satisf_initial.\n  destruct (S.set_list_complete te f.(fn_params) f.(fn_sig).(sig_args) e1) as (e2 & C & D); auto.\n  destruct (S.solve_complete te e2) as (te' & E); auto.\n  exists te'; unfold type_function.\n  rewrite A; simpl. rewrite C; simpl. rewrite E; simpl.\n  unfold check_params_norepet. rewrite pred_dec_true; auto. simpl.\n  rewrite check_successor_complete by auto. auto.\nQed.\n\nEnd INFERENCE.\n\n(** * Type preservation during evaluation *)\n\n(** The type system for RTL is not sound in that it does not guarantee\n  progress: well-typed instructions such as [Icall] can fail because\n  of run-time type tests (such as the equality between callee and caller's\n  signatures).  However, the type system guarantees a type preservation\n  property: if the execution does not fail because of a failed run-time\n  test, the result values and register states match the static\n  typing assumptions.  This preservation property will be useful\n  later for the proof of semantic equivalence between [Linear] and [Mach].\n  Even though we do not need it for [RTL], we show preservation for [RTL]\n  here, as a warm-up exercise and because some of the lemmas will be\n  useful later. *)\n\nDefinition wt_regset (env: regenv) (rs: regset) : Prop :=\n  forall r, Val.has_type (rs#r) (env r).\n\nLemma wt_regset_assign:\n  forall env rs v r,\n  wt_regset env rs ->\n  Val.has_type v (env r) ->\n  wt_regset env (rs#r <- v).\nProof.\n  intros; red; intros.\n  rewrite Regmap.gsspec.\n  case (peq r0 r); intro.\n  subst r0. assumption.\n  apply H.\nQed.\n\nLemma wt_regset_list:\n  forall env rs,\n  wt_regset env rs ->\n  forall rl, Val.has_type_list (rs##rl) (List.map env rl).\nProof.\n  induction rl; simpl.\n  auto.\n  split. apply H. apply IHrl.\nQed.\n\nLemma wt_regset_setres:\n  forall env rs v res,\n  wt_regset env rs ->\n  Val.has_type v (type_of_builtin_res env res) ->\n  wt_regset env (regmap_setres res v rs).\nProof.\n  intros. destruct res; simpl in *; auto. apply wt_regset_assign; auto.\nQed.\n\nLemma wt_init_regs:\n  forall env rl args,\n  Val.has_type_list args (List.map env rl) ->\n  wt_regset env (init_regs args rl).\nProof.\n  induction rl; destruct args; simpl; intuition.\n  red; intros. rewrite Regmap.gi. simpl; auto.\n  apply wt_regset_assign; auto.\nQed.\n\nLemma wt_exec_Iop:\n  forall (ge: genv) env f sp op args res s rs m v,\n  wt_instr f env (Iop op args res s) ->\n  eval_operation ge sp op rs##args m = Some v ->\n  wt_regset env rs ->\n  wt_regset env (rs#res <- v).\nProof.\n  intros. inv H.\n  simpl in H0. inv H0. apply wt_regset_assign; auto.\n  rewrite H4; auto.\n  eapply wt_regset_assign; auto.\n  rewrite H8. eapply type_of_operation_sound; eauto.\nQed.\n\nLemma wt_exec_Iload:\n  forall env f chunk addr args dst s m a v rs,\n  wt_instr f env (Iload chunk addr args dst s) ->\n  Mem.loadv chunk m a = Some v ->\n  wt_regset env rs ->\n  wt_regset env (rs#dst <- v).\nProof.\n  intros. destruct a; simpl in H0; try discriminate. inv H.\n  eapply wt_regset_assign; eauto. rewrite H8; eapply Mem.load_type; eauto.\nQed.\n\nLemma wt_exec_Ibuiltin:\n  forall env f ef (ge: genv) args res s vargs m t vres m' rs,\n  wt_instr f env (Ibuiltin ef args res s) ->\n  external_call ef ge vargs m t vres m' ->\n  wt_regset env rs ->\n  wt_regset env (regmap_setres res vres rs).\nProof.\n  intros. inv H.\n  eapply wt_regset_setres; eauto.\n  rewrite H7. eapply external_call_well_typed; eauto.\nQed.\n\nLemma wt_instr_at:\n  forall f env pc i,\n  wt_function f env -> f.(fn_code)!pc = Some i -> wt_instr f env i.\nProof.\n  intros. inv H. eauto.\nQed.\n\nInductive wt_stackframes: list stackframe -> signature -> Prop :=\n  | wt_stackframes_nil: forall sg,\n      sg.(sig_res) = Tint ->\n      wt_stackframes nil sg\n  | wt_stackframes_cons:\n      forall s res f sp pc rs env sg,\n      wt_function f env ->\n      wt_regset env rs ->\n      env res = proj_sig_res sg ->\n      wt_stackframes s (fn_sig f) ->\n      wt_stackframes (Stackframe res f sp pc rs :: s) sg.\n\nInductive wt_state: state -> Prop :=\n  | wt_state_intro:\n      forall s f sp pc rs m env\n        (WT_STK: wt_stackframes s (fn_sig f))\n        (WT_FN: wt_function f env)\n        (WT_RS: wt_regset env rs),\n      wt_state (State s f sp pc rs m)\n  | wt_state_call:\n      forall s f args m id,\n      wt_stackframes s (funsig f) ->\n      wt_fundef f ->\n      Val.has_type_list args (sig_args (funsig f)) ->\n      wt_state (Callstate s f args m id)\n  | wt_state_return:\n      forall s v m sg,\n      wt_stackframes s sg ->\n      Val.has_type v (proj_sig_res sg) ->\n      wt_state (Returnstate s v m).\n\nRemark wt_stackframes_change_sig:\n  forall s sg1 sg2,\n  sg1.(sig_res) = sg2.(sig_res) -> wt_stackframes s sg1 -> wt_stackframes s sg2.\nProof.\n  intros. inv H0.\n- constructor; congruence.\n- econstructor; eauto. rewrite H3. unfold proj_sig_res. rewrite H. auto.\nQed.\n\nSection SUBJECT_REDUCTION.\n\nVariable p: program.\n\nHypothesis wt_p: wt_program p.\n\nLet ge := Genv.globalenv p.\n\nVariable fn_stack_requirements : ident -> Z.\n\nLemma subject_reduction:\n  forall st1 t st2, step fn_stack_requirements ge st1 t st2 ->\n  forall (WT: wt_state st1), wt_state st2.\nProof.\n  induction 1; intros; inv WT;\n  try (generalize (wt_instrs _ _ WT_FN pc _ H); intros WTI).\n  (* Inop *)\n  econstructor; eauto.\n  (* Iop *)\n  econstructor; eauto. eapply wt_exec_Iop; eauto.\n  (* Iload *)\n  econstructor; eauto. eapply wt_exec_Iload; eauto.\n  (* Istore *)\n  econstructor; eauto.\n  (* Icall *)\n  try (generalize (wt_instrs _ _ WT_FN pc _ H0); intros WTI).\n  assert (wt_fundef fd).\n    destruct ros; simpl in H1.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H1.\n    caseEq (Genv.find_symbol ge i); intros; rewrite H2 in H1.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H1.\n    discriminate.\n  econstructor; eauto.\n  econstructor; eauto. inv WTI; auto.\n  inv WTI. rewrite <- H9. apply wt_regset_list. auto.\n  (* Itailcall *)\n  try (generalize (wt_instrs _ _ WT_FN pc _ H0); intros WTI).\n  assert (wt_fundef fd).\n    destruct ros; simpl in H1.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H1.\n    caseEq (Genv.find_symbol ge i); intros; rewrite H2 in H1.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H1.\n    discriminate.\n  econstructor; eauto.\n  inv WTI. apply wt_stackframes_change_sig with (fn_sig f); auto.\n  inv WTI. rewrite <- H10. apply wt_regset_list. auto.\n  (* Ibuiltin *)\n  econstructor; eauto. eapply wt_exec_Ibuiltin; eauto.\n  (* Icond *)\n  econstructor; eauto.\n  (* Ijumptable *)\n  econstructor; eauto.\n  (* Ireturn *)\n  econstructor; eauto.\n  inv WTI; simpl. auto. rewrite <- H5. auto.\n  (* internal function *)\n  simpl in *. inv H8.\n  econstructor; eauto.\n  inv H3. apply wt_init_regs; auto. rewrite wt_params0. auto.\n  (* external function *)\n  econstructor; eauto.\n  eapply external_call_well_typed; eauto.\n  (* return *)\n  inv H1. econstructor; eauto.\n  apply wt_regset_assign; auto. rewrite H10; auto.\nQed.\n\nLemma wt_initial_state:\n  forall S, initial_state p S -> wt_state S.\nProof.\n  intros. inv H. constructor. constructor. rewrite H3; auto.\n  pattern f. apply Genv.find_funct_ptr_prop with fundef unit p b.\n  exact wt_p. exact H2.\n  rewrite H3. constructor.\nQed.\n\nLemma wt_instr_inv:\n  forall s f sp pc rs m i,\n  wt_state (State s f sp pc rs m) ->\n  f.(fn_code)!pc = Some i ->\n  exists env, wt_instr f env i /\\ wt_regset env rs.\nProof.\n  intros. inv H. exists env; split; auto.\n  inv WT_FN. eauto.\nQed.\n\nEnd SUBJECT_REDUCTION.\n\n\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/RTLtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1990834329050347}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.type_induction.\n(*Require Import VST.floyd.fieldlist.*)\nRequire Import VST.floyd.compact_prod_sum.\n(*Require Import VST.floyd.aggregate_type.*)\nRequire Import VST.floyd.mapsto_memory_block.\nRequire Import VST.floyd.nested_pred_lemmas.\nRequire Import VST.floyd.jmeq_lemmas.\nRequire Import VST.floyd.sublist.\n\nRequire Export VST.floyd.fieldlist.\nRequire Export VST.floyd.aggregate_type.\n\nOpen Scope Z.\nOpen Scope logic.\n\n(******************************************\n\nDefinition and lemmas about rangespec\n\n******************************************)\n\nFixpoint rangespec (lo: Z) (n: nat) (P: Z -> val -> mpred): val -> mpred :=\n  match n with\n  | O => fun _ => emp\n  | S n' => P lo * rangespec (Z.succ 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 (Z.succ 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      apply derives_refl.\n  + erewrite H; eauto.\n      apply derives_refl.\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}{d: Inhabitant 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)) 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: Inhabitant A} lo hi P p,\n  hi = lo ->\n  array_pred 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: Inhabitant A} i P v p,\n  array_pred 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: Inhabitant A} lo mid hi P v p,\n  lo <= mid <= hi ->\n  Zlength v = hi - lo ->\n  array_pred lo hi P v p =\n  array_pred lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred 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)) 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))) p).\n      2:{\n        apply rangespec_ext; intros.\n        f_equal.\n        rewrite <- Znth_succ by omega; auto.\n      }\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: Inhabitant 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) p = P i (Znth (i-lo) v) p) ->\n  array_pred lo' hi' P' v p = array_pred lo hi P v p.\nProof.\n  intros.\n  unfold array_pred.\n  apply andp_prop_ext; [omega | intros].\n  replace (hi' - lo') with (hi - lo) by omega.\n  destruct (zlt hi lo). rewrite Z2Nat_neg by omega. reflexivity.\n  apply pred_ext; apply rangespec_shift_derives; intros.\n  rewrite H4; rewrite Z2Nat.id in H3 by omega.\n  rewrite H1; auto; omega.\n  rewrite <- H4; rewrite Z2Nat.id in H3 by omega.\n  rewrite H1; auto; omega.\nQed.\n\nLemma array_pred_ext_derives: forall {A B} (dA: Inhabitant A) (dB: Inhabitant B)\n         lo hi P0 P1 (v0: list A) v1 p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0) p |-- P1 i (Znth (i-lo) v1) p) ->\n  array_pred  lo hi P0 v0 p |-- array_pred lo hi P1 v1 p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  rewrite prop_true_andp by omega.\n  apply rangespec_ext_derives.\n  intros.\n  destruct (zlt hi lo).\n  + rewrite Z2Nat_neg  in H2 by omega.\n    change (Z.of_nat 0) with 0 in H2. omega.\n  + rewrite Z2Nat.id in H2 by omega.\n    apply H0. omega.\nQed.\n\nLemma array_pred_ext: forall {A B} (dA: Inhabitant A) (dB: Inhabitant B) lo hi P0 P1 \n        (v0: list A) (v1: list B) p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0) p = P1 i (Znth (i-lo) v1) p) ->\n  array_pred lo hi P0 v0 p = array_pred 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: Inhabitant A} lo hi P v ofs p,\n  at_offset (array_pred lo hi P v) ofs p = array_pred 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: Inhabitant A} lo hi P Q v p,\n  array_pred lo hi P v p * array_pred lo hi Q v p = array_pred 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;      apply derives_refl.\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    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    }\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; apply derives_refl.\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: Inhabitant A} lo hi P v p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred 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    {\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    }\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))) p)\n    with (rangespec (Z.succ lo) (length v)\n            (fun i : Z => P i (Znth (i - Z.succ lo) v)) p).\n    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    }\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: Inhabitant A} sh t lo hi v b ofs,\n  0 <= ofs + sizeof t * lo /\\ ofs + sizeof t * hi < Ptrofs.modulus ->\n  0 <= lo <= hi ->\n  Zlength v = hi - lo ->\n  array_pred lo hi\n    (fun i _ p => memory_block sh (sizeof t) (offset_val (sizeof t * i) p)) v\n    (Vptr b (Ptrofs.repr ofs)) =\n   memory_block sh (sizeof t * (hi - lo)) (Vptr b (Ptrofs.repr (ofs + sizeof t * lo))).\nProof.\n  intros.\n  unfold array_pred.\n  rewrite prop_true_andp by auto; clear H1.\n  f_equal.\n  remember (Z.to_nat (hi - lo)) as n eqn:HH.\n  revert lo HH H H0 v; induction n; intros.\n  + simpl.\n    pose proof arith_aux00 _ _ (proj2 H0) HH.\n    rewrite H1, Z.mul_0_r, memory_block_zero_Vptr.\n    reflexivity.\n  + simpl.\n    pose proof arith_aux01 _ _ _ HH.\n    solve_mod_modulus.\n    pose_size_mult cenv_cs t (0 :: hi - Z.succ lo :: hi - lo :: nil).\n    rewrite IHn; [| apply arith_aux02; auto | omega | omega | exact v].\n    replace (ofs + sizeof  t * Z.succ lo) with (ofs + sizeof t * lo + sizeof t) by omega.\n    rewrite <- memory_block_split by (auto; omega).\n    f_equal.\n    omega.\nQed.\n\nLemma memory_block_array_pred': forall {A}{d: Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred 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) a)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros.\n  rewrite memory_block_array_pred.\n  f_equal. f_equal. omega. f_equal. f_equal. rewrite Z.mul_0_r. omega.\n  rewrite Z.mul_0_r. split; omega. omega.\n  rewrite Z.sub_0_r. auto. rewrite Zlength_list_repeat', Z2Nat.id by omega.\n  omega.\nQed.\n\nLemma memory_block_struct_pred: forall sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (fst it) m sz - field_offset cenv_cs (fst it) m))\n     (offset_val (field_offset cenv_cs (fst it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  unfold field_offset, Ctypes.field_offset, field_offset_next.\n  intros sh m sz A v b ofs NIL_CASE NO_REPLI; intros.\n  destruct m as [| (i0, t0) m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  assert (align 0 (alignof t0) = 0) by apply align_0, alignof_pos.\n  revert H0; pattern ofs at 1 4; replace ofs with (ofs + align 0 (alignof t0)) by omega; intros.\n  revert H; pattern sz at 2 4; replace sz with (sz - align 0 (alignof t0)) by omega; intros.\n  pattern 0 at 1; rewrite <- H1.\n  clear NIL_CASE H1.\n  revert H H0; generalize 0 at 1 2 4 5 6 8 10 11; revert i0 t0 v NO_REPLI;\n  induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    reflexivity.\n  + match goal with\n    | |- struct_pred ((i0, t0) :: (i1, t1) :: m) ?P v ?p = _ =>\n           change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p) with\n             (P (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p);\n           simpl (P (i0, t0) (fst v) p)\n    end.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    erewrite struct_pred_ext.\n    - rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n      rewrite IHm with (z := align z (alignof t0) + sizeof t0);\n        [| now auto\n         | simpl in H |- *; pose_align_le; pose_sizeof_pos; omega\n         | pose_align_le; pose_sizeof_pos; omega].\n      replace (ofs + align (align z (alignof t0) + sizeof t0) (alignof t1)) with\n        (ofs + align z (alignof t0) +\n         (align (align z (alignof t0) + sizeof t0) (alignof t1) -\n          align z (alignof t0))) by omega.\n      rewrite <- memory_block_split by\n        (simpl in H; revert H; pose_align_le; pose_sizeof_pos; intros; omega).\n      f_equal; omega.\n    - rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n      auto.\n    - intros. instantiate (1 := (snd v)).\n      solve_mod_modulus.\n      unfold fst.\n      pose proof in_members_tail_no_replicate _ _ _ _ NO_REPLI H2.\n      rewrite (neq_field_offset_rec_cons cenv_cs i i0 t0) by auto.\n      rewrite (neq_field_offset_next_rec_cons cenv_cs i i0 t0) by auto.\n      reflexivity.\nQed.\n\nLemma memory_block_union_pred: forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros sh m sz A v b ofs NIL_CASE; intros.\n  destruct m as [| (i0, t0) m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  clear NIL_CASE.\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl; auto.\n  + destruct v.\n    - simpl; auto.\n    - apply IHm.\nQed.\n\nEnd MEMORY_BLOCK_AGGREGATE.\n\nModule aggregate_pred.\n\nOpen Scope Z.\nOpen Scope logic.\n\n\nDefinition array_pred: forall {A: Type}{d: Inhabitant 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: Inhabitant A} lo hi P p,\n  hi = lo ->\n  array_pred lo hi P nil p = emp\n:= @array_pred_len_0.\n\nDefinition array_pred_len_1: forall {A}{d: Inhabitant A} i P v p,\n  array_pred i (i + 1) P (v :: nil) p =  P i v p\n:= @array_pred_len_1.\n\nDefinition split_array_pred: forall  {A}{d: Inhabitant A} lo mid hi P v p,\n  lo <= mid <= hi ->\n  Zlength v = (hi-lo) ->\n  array_pred lo hi P v p =\n  array_pred lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred mid hi P (sublist (mid-lo) (hi-lo) v) p\n:= @split_array_pred.\n\nDefinition array_pred_shift: forall {A} {d: Inhabitant A} lo hi lo' hi' mv \n              P' P v p,\n  lo - lo' = mv ->\n  hi - hi' = mv ->\n  (forall i i', lo <= i < hi -> i - i' = mv ->\n           P' i' (Znth (i - lo) v) p = P i (Znth (i - lo) v) p) ->\n  array_pred lo' hi' P' v p = array_pred lo hi P v p\n:= @array_pred_shift.\n\nDefinition array_pred_ext_derives:\n  forall {A B} {dA: Inhabitant A} {dB: Inhabitant B} lo hi P0 P1 \n            (v0: list A) (v1: list B) p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n      P0 i (Znth (i-lo) v0) p |-- P1 i (Znth (i-lo) v1) p) ->\n  array_pred lo hi P0 v0 p |-- array_pred lo hi P1 v1 p\n:= @array_pred_ext_derives.\n\nDefinition array_pred_ext:\n  forall {A B} {dA: Inhabitant A} {dB: Inhabitant B} lo hi P0 P1 (v0: list A) (v1: list B)  p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n     P0 i (Znth (i - lo) v0) p = P1 i (Znth (i - lo) v1) p) ->\n  array_pred lo hi P0 v0 p = array_pred lo hi P1 v1 p\n:= @array_pred_ext.\n\nDefinition at_offset_array_pred: forall {A} {d: Inhabitant A} lo hi P v ofs p,\n  at_offset (array_pred lo hi P v) ofs p = array_pred 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: Inhabitant A} lo hi P Q v p,\n  array_pred lo hi P v p * array_pred lo hi Q v p = array_pred 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: Inhabitant A} lo hi P v p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred lo hi P v p |-- !! (Zlength v = hi - lo /\\ Forall Q v)\n:= @array_pred_local_facts.\n\nDefinition struct_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  struct_pred m P v p |-- !! struct_Prop m R v\n:= @struct_pred_local_facts.\n\nDefinition union_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  union_pred m P v p |-- !! union_Prop m R v\n:= @union_pred_local_facts.\n\nEnd aggregate_pred.\n\nRequire Import VST.floyd.reptype_lemmas.\n\n(******************************************\n\nAuxiliary predicates\n\n******************************************)\n\nSection AUXILIARY_PRED.\n\nContext {cs: compspecs}.\n\nVariable sh: share.\n\nDefinition struct_data_at_rec_aux (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| (i0, t0) m]; [exact (fun _ => emp) |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs i0 m0 + sizeof (field_type i0 m0))\n            (field_offset_next cenv_cs i0 m0 sz)\n            (at_offset (a v) (field_offset cenv_cs i0 m0))).\n  + simpl in v, P.\n    destruct (ident_eq i1 i1); [| congruence].\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs i1 m0 + sizeof (field_type i1 m0))\n            (field_offset_next cenv_cs i1 m0 sz)\n            (at_offset (a (fst v)) (field_offset cenv_cs i1 m0)) * IHm i0 t0 (snd v) b)%logic.\nDefined.\n\nDefinition union_data_at_rec_aux (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| (i0, t0) m]; [exact (fun _ => emp) |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh (sizeof (field_type i0 m0)) sz (a v)).\n  + simpl in v, P.\n    inversion P; subst.\n    destruct v as [v | v].\n    - exact (withspacer sh (sizeof (field_type i1 m0)) sz (a v)).\n    - exact (IHm i0 t0 v b).\nDefined.\n\nLemma struct_data_at_rec_aux_spec: forall m m0 sz v P,\n  struct_data_at_rec_aux m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (fst it) m0 + sizeof (field_type (fst it) m0))\n       (field_offset_next cenv_cs (fst it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (fst it) m0))) v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_data_at_rec_aux ((i1, t1) :: (i0, t0) :: m) m0 sz\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> val -> mpred)\n        P ((i1, t1) :: (i0, t0) :: m)) v) with\n     (withspacer sh\n       (field_offset cenv_cs i1 m0 + sizeof (field_type i1 m0))\n         (field_offset_next cenv_cs i1 m0 sz)\n           (at_offset (P (i1, t1) (fst v)) (field_offset cenv_cs i1 m0)) *\n      struct_data_at_rec_aux ((i0, t0) :: m) m0 sz\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> val -> mpred)\n        P ((i0, t0) :: m)) (snd v))%logic.\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\n      destruct (ident_eq i1 i1); [| congruence].\n      reflexivity.\nQed.\n\nLemma union_data_at_rec_aux_spec: forall m m0 sz v P,\n  union_data_at_rec_aux m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (fst it) m0))\n       sz\n       (P it v)) v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl. unfold union_pred. simpl. reflexivity.\n  + destruct v as [v | v].\n    - reflexivity.\n    - match goal with\n      | _ => apply IHm\n      | _ => simpl ; f_equal ; apply IHm\n      end.\nQed.\n\nDefinition struct_value_fits_aux (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)) : Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    apply (a v).\n  + simpl in v, P.\n    destruct (ident_eq i1 i1); [| congruence].\n    inversion P; subst.\n    apply (a (fst v) /\\ IHm i0 t0 (snd v) b).\nDefined.\n\nDefinition union_value_fits_aux (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)) : Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (a v).\n  + simpl in v, P.\n    inversion P; subst.\n    destruct v as [v | v].\n    - exact (a v).\n    - exact (IHm i0 t0 v b).\nDefined.\n\nLemma struct_value_fits_aux_spec: forall m m0 v P,\n  struct_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  struct_Prop m P v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_value_fits_aux ((i1, t1) :: (i0, t0) :: m) m0\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> Prop)\n        P ((i1, t1) :: (i0, t0) :: m)) v) with\n     (P (i1, t1) (fst v) /\\  struct_value_fits_aux ((i0, t0) :: m) m0\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> Prop)\n        P ((i0, t0) :: m)) (snd v)).\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\n      destruct (ident_eq i1 i1); [| congruence].\n      reflexivity.\nQed.\n\nLemma union_value_fits_aux_spec: forall m m0 v P,\n  union_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  union_Prop m P v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl. unfold union_Prop. simpl. reflexivity.\n  + destruct v as [v | v].\n    - reflexivity.\n    - match goal with\n      | _ => apply IHm\n      | _ => simpl ; f_equal ; apply IHm\n      end.\nQed.\n\nEnd AUXILIARY_PRED.\n\nModule auxiliary_pred.\n\nImport aggregate_pred.\n\nDefinition struct_data_at_rec_aux:\n   forall {cs: compspecs} (sh: share) (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)), (val -> mpred)\n:= @struct_data_at_rec_aux.\n\nDefinition union_data_at_rec_aux:\n  forall {cs: compspecs} (sh: share) (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)), (val -> mpred)\n:= @union_data_at_rec_aux.\n\nDefinition struct_data_at_rec_aux_spec: forall {cs: compspecs} (sh: share) m m0 sz v P,\n  struct_data_at_rec_aux sh m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (fst it) m0 + sizeof (field_type (fst it) m0))\n       (field_offset_next cenv_cs (fst it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (fst it) m0))) v\n:= @struct_data_at_rec_aux_spec.\n\nDefinition union_data_at_rec_aux_spec: forall {cs: compspecs} sh m m0 sz v P,\n  union_data_at_rec_aux sh m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (fst it) m0))\n       sz\n       (P it v)) v\n:= @union_data_at_rec_aux_spec.\n\nDefinition struct_value_fits_aux:\n  forall {cs: compspecs} (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)), Prop\n:= @struct_value_fits_aux.\n\nDefinition union_value_fits_aux:\n  forall {cs: compspecs} (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)), Prop\n:= @union_value_fits_aux.\n\nDefinition struct_value_fits_aux_spec: forall {cs: compspecs} m m0 v P,\n  struct_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  struct_Prop m P v\n:= @struct_value_fits_aux_spec.\n\nDefinition union_value_fits_aux_spec: forall {cs: compspecs} m m0 v P,\n  union_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  union_Prop m P v\n:= @union_value_fits_aux_spec.\n\nDefinition memory_block_array_pred:\n  forall {cs: compspecs} {A : Type} {d : Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred 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) a)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_array_pred'.\n\nDefinition memory_block_struct_pred:\n  forall {cs: compspecs} sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (fst it) m sz - field_offset cenv_cs (fst it) m))\n     (offset_val (field_offset cenv_cs (fst it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_struct_pred.\n\nDefinition memory_block_union_pred:\n  forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_union_pred.\n\nEnd auxiliary_pred.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/aggregate_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1990834329050347}}
{"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 DataSystem.\nRequire Import cNNRC.\nRequire Import cNNRCEq.\nRequire Import TcNNRC.\n\nSection TcNNRCEq.\n  (* Named Nested Relational Calculus *)\n\n  (* A different kind of equivalence for rewrites *)\n\n  Context {m:basic_model}.\n  Context {\u03c4cenv:tbindings}.\n\n  Definition tnncr_core_rewrites_to (e1 e2:nnrc) : Prop :=\n    forall (\u03c4env : tbindings) (\u03c4out:rtype),\n      nnrc_core_type \u03c4cenv \u03c4env e1 \u03c4out ->\n      (nnrc_core_type \u03c4cenv \u03c4env e2 \u03c4out)\n      /\\ (forall (cenv env:bindings),\n             bindings_type cenv \u03c4cenv ->\n             bindings_type env \u03c4env ->\n             nnrc_core_eval brand_relation_brands cenv env e1\n             = nnrc_core_eval brand_relation_brands cenv env e2).\n\n  Notation \"e1 \u21d2\u1d9c\u1d9c e2\" := (tnncr_core_rewrites_to e1 e2) (at level 80).\n\n  Open Scope nnrc_scope.\n\n  Lemma data_normalized_bindings_type_map env \u03c4env :\n    bindings_type env \u03c4env ->\n    Forall (data_normalized brand_relation_brands) (map snd env).\n  Proof.\n    rewrite Forall_map.\n    apply bindings_type_Forall_normalized.\n  Qed.\n\n  Hint Resolve data_normalized_bindings_type_map : qcert.\n  \n  Lemma nnrc_base_rewrites_typed_with_untyped (e1 e2:nnrc) :\n    e1 \u2261\u1d9c\u1d9c e2 ->\n    (forall {\u03c4env: tbindings}\n            {\u03c4out:rtype},\n        nnrc_core_type \u03c4cenv \u03c4env e1 \u03c4out\n        -> nnrc_core_type \u03c4cenv \u03c4env e2 \u03c4out)\n    -> e1 \u21d2\u1d9c\u1d9c e2.\n  Proof.\n    intros.\n    unfold tnncr_core_rewrites_to; simpl; intros.\n    split; auto 2; intros.\n    apply H; qeauto.\n  Qed.\n\n  (****************\n   * Proper stuff *\n   ****************)\n\n  Hint Constructors nnrc_core_type : qcert.\n  Hint Constructors unary_op_type : qcert.\n  Hint Constructors binary_op_type : qcert.\n\n  Global Instance  tnncr_core_rewrites_to_pre : PreOrder tnncr_core_rewrites_to.\n  Proof.\n    constructor; red; intros.\n    - unfold tnncr_core_rewrites_to; intros.\n      split; try assumption; intros.\n      reflexivity.\n    - unfold tnncr_core_rewrites_to in *; intros.\n      specialize (H \u03c4env \u03c4out H1).\n      elim H; clear H; intros.\n      specialize (H0 \u03c4env \u03c4out H).\n      elim H0; clear H0; intros.\n      split; try assumption; intros.\n      rewrite (H2 cenv env); try assumption.\n      rewrite (H3 cenv env); try assumption.\n      reflexivity.\n  Qed.\n  \n  (* NNRCVar *)\n\n  Global Instance nnrc_base_var_tproper:\n    Proper (eq ==> tnncr_core_rewrites_to) NNRCVar.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    rewrite <- H.\n    split; try assumption.\n    intros; reflexivity.\n  Qed.\n  \n  (* NNRCConst *)\n\n  Global Instance nnrc_base_const_tproper:\n    Proper (eq ==> tnncr_core_rewrites_to) NNRCConst.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    rewrite <- H.\n    split; try assumption.\n    intros; reflexivity.\n  Qed.\n\n  (* NNRCBinop *)\n\n  Global Instance nnrc_base_binop_tproper:\n    Proper (eq ==> tnncr_core_rewrites_to\n               ==> tnncr_core_rewrites_to\n               ==> tnncr_core_rewrites_to) NNRCBinop.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    rewrite H in *; clear H.\n    inversion H2; clear H2; subst.\n    econstructor; eauto.\n    specialize (H0 \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4env \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    econstructor; eauto; intros.\n    intros.\n    specialize (H0 \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4env \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    simpl.\n    rewrite (H3 cenv env H H2); rewrite (H4 cenv env H H2); reflexivity.\n  Qed.\n  \n  (* NNRCUnop *)\n\n  Global Instance nnrc_base_unop_tproper :\n    Proper (eq ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to) NNRCUnop.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    rewrite H in *; clear H.\n    inversion H1; clear H1; subst.\n    econstructor; eauto.\n    econstructor; eauto.\n    specialize (H0  \u03c4env \u03c4\u2081 H6); elim H0; clear H0 H6; intros; assumption.\n    intros.\n    specialize (H0  \u03c4env \u03c4\u2081 H6); elim H0; clear H0 H6; intros.\n    simpl. rewrite (H2 cenv env H H1); reflexivity.\n  Qed.\n\n  (* NNRCLet *)\n\n  Global Instance nnrc_base_let_tproper :\n    Proper (eq ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to) NNRCLet.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    inversion H2; clear H2; subst.\n    specialize (H0 \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 ((y, \u03c4\u2081) :: \u03c4env) \u03c4out H9); elim H1; clear H1 H9; intros.\n    econstructor; qeauto.\n    intros; simpl.\n    rewrite (H0 cenv env H3 H4).\n    case_eq (nnrc_core_eval brand_relation_brands cenv env y0); intros; try reflexivity.\n    rewrite (H2 cenv ((y, d) :: env) H3); try reflexivity.\n    unfold bindings_type.\n    apply Forall2_cons; try assumption.\n    simpl; split; try reflexivity.\n    generalize (@typed_nnrc_core_yields_typed_data _ _ \u03c4\u2081 cenv env \u03c4env y0 H3 H4 H); intros.\n    elim H6; intros.\n    rewrite H5 in H7.\n    elim H7; clear H7; intros.\n    inversion H7; assumption.\n  Qed.\n    \n  (* NNRCFor *)\n\n  Lemma dcoll_wt (l:list data) (\u03c4:rtype) (\u03c4env:tbindings) (cenv env:bindings) (e:nnrc):\n    bindings_type cenv \u03c4cenv ->\n    bindings_type env \u03c4env ->\n    nnrc_core_type \u03c4cenv \u03c4env e (Coll \u03c4) ->\n    nnrc_core_eval brand_relation_brands cenv env e = Some (dcoll l) ->\n    forall x:data, In x l -> (data_type x \u03c4).\n  Proof.\n    intros.\n    generalize (@typed_nnrc_core_yields_typed_data _ _ (Coll \u03c4) cenv env \u03c4env e H H0 H1); intros.\n    elim H4; clear H4; intros.\n    elim H4; clear H4; intros.\n    rewrite H4 in H2.\n    inversion H2; clear H2.\n    subst.\n    dependent induction H5.\n    rtype_equalizer.\n    subst.\n    rewrite Forall_forall in H2.\n    apply (H2 x0 H3).\n  Qed.\n\n  Global Instance nnrc_base_for_tproper :\n    Proper (eq ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to) NNRCFor.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    inversion H2; clear H2; subst.\n    specialize (H0 \u03c4env (Coll \u03c4\u2081) H8); elim H0; clear H0 H8; intros.\n    specialize (H1 ((y, \u03c4\u2081) :: \u03c4env) \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    econstructor; qeauto.\n    intros; simpl.\n    rewrite (H0 cenv env H3 H4).\n    case_eq (nnrc_core_eval brand_relation_brands cenv env y0); intros; try reflexivity.\n    destruct d; try reflexivity.\n    assert (forall x, In x l -> (data_type x \u03c4\u2081)) by\n        (apply (dcoll_wt l \u03c4\u2081 \u03c4env cenv env y0); assumption).\n    clear H5 H.\n    induction l; try reflexivity.\n    simpl in *.\n    assert (forall x : data, In x l -> data_type x \u03c4\u2081)\n      by (intros; apply (H6 x); right; assumption).\n    specialize (IHl H); clear H.\n    rewrite (H2 cenv ((y, a) :: env) H3).\n    destruct (nnrc_core_eval brand_relation_brands cenv ((y, a) :: env) y1); try reflexivity.\n    destruct ((lift_map (fun d1 : data => nnrc_core_eval brand_relation_brands cenv ((y, d1) :: env) x1) l)); destruct ((lift_map (fun d1 : data => nnrc_core_eval brand_relation_brands cenv ((y, d1) :: env) y1) l)); simpl in *; try congruence.\n    unfold bindings_type.\n    apply Forall2_cons; try assumption.\n    simpl; split; try reflexivity.\n    apply (H6 a); left; reflexivity.\n  Qed.\n    \n  (* NNRCIf *)\n\n  Global Instance nnrc_base_if_tproper :\n    Proper (tnncr_core_rewrites_to ==> tnncr_core_rewrites_to\n                             ==> tnncr_core_rewrites_to\n                             ==> tnncr_core_rewrites_to) NNRCIf.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    inversion H2; clear H2; subst.\n    specialize (H \u03c4env Bool H7); elim H; clear H H7; intros.\n    specialize (H0 \u03c4env \u03c4out H9); elim H0; clear H0 H9; intros.\n    specialize (H1 \u03c4env \u03c4out H10); elim H1; clear H1 H10; intros.\n    econstructor; qeauto.\n    intros; simpl.\n    rewrite (H2 cenv env H5 H6). rewrite (H3 cenv env H5 H6). rewrite (H4 cenv env H5 H6).\n    reflexivity.\n  Qed.\n\n  (* NNRCEither *)\n\n  Global Instance nnrc_base_either_tproper :\n    Proper (tnncr_core_rewrites_to ==> eq ==> tnncr_core_rewrites_to ==> eq ==> tnncr_core_rewrites_to ==> tnncr_core_rewrites_to) NNRCEither.\n  Proof.\n    unfold Proper, respectful, tnncr_core_rewrites_to; intros.\n    subst.\n    inversion H4; clear H4; subst.\n    destruct (H _ _ H10).\n    destruct (H1 _ _ H11).\n    destruct (H3 _ _ H12).\n    clear H H1 H3.\n    simpl.\n    split; [qeauto | ]; intros.\n    rewrite H2; trivial.\n    destruct (@typed_nnrc_core_yields_typed_data _ _ _ _ _ _ _ H H1 H0) as [?[??]].\n    rewrite H3.\n    apply data_type_Either_inv in H8.\n    destruct H8 as [[?[??]]|[?[??]]]; subst.\n    - apply (H5 _ _ H). constructor; simpl; intuition; eauto.\n    - eapply (H7 _ _ H). constructor; simpl; intuition; eauto.\n  Qed.\n\nEnd TcNNRCEq.\n\nNotation \"e1 \u21d2\u1d9c\u1d9c e2\" := (tnncr_core_rewrites_to e1 e2) (at level 80) : nnrc_scope.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/cNNRC/Typing/TcNNRCEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19908343290503466}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv While.\nFrom DiSeL\nRequire Import CalculatorProtocol CalculatorInvariant.\nFrom DiSeL\nRequire Import CalculatorClientLib.\nFrom DiSeL\nRequire Import SeqLib.\n\nSection CalculatorServerLib.\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\n(***********************)\n(* Server receive loop *)\n(***********************)\n\nExport CalculatorProtocol.\n\nProgram Definition tryrecv_req_act := act (@tryrecv_action_wrapper W sv\n      (fun k _ t b => (k == l) && (t == req)) _).\nNext Obligation. by case/andP:H=>/eqP->; rewrite domPt inE/=. Qed.\n\n(* Receive-transition for the calculator *)\nProgram Definition tryrecv_req :\n  {ps : reqs}, DHT [sv, W]\n  (fun i => loc i = st :-> ps,\n   fun (r : option perm) m =>\n     match r with\n     | Some (from, t, args) =>\n       [/\\ loc m = st :-> ((from, sv, args) :: ps),\n        prec args & from \\in cls]\n     | None => loc m = st :-> ps\n     end) \n  := Do tryrecv_req_act.    \nNext Obligation.\napply: ghC=>i1 ps E1 C1.\napply: act_rule=>i2 R1; split=>//=; first by apply: (proj2 (rely_coh R1)).\nmove=>r i3 i4[_]/=St R3.\ncase: St=>C2; case.\n- by move=>[]?->Z; subst i3;rewrite (rely_loc' _ R3) (rely_loc' _ R1).\ncase=>k[m][tms][from][rt][pf'][[F]]H1 H2 H3/andP[/eqP Z]H4/= Z'->; subst k i3. \nmove: rt  pf' (coh_s l C2) H1 H2 H3 H4 R3.\nrewrite prEq=>rt  pf' cohs H1 H2 H3 H4 R3.\ncase: H1 H4; last by case=>//=->. \nmove=>Z _; subst rt; move: H3; rewrite /msg_wf/=/sr_wf=>->; split=>//.\nset d := (getStatelet i2 l).\nhave P1: valid (dstate d) by apply: (cohVl cohs).\nhave P2: valid i2 by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom i2 by rewrite -(cohD(proj2(rely_coh R1)))domPt inE/=.\nrewrite -(rely_loc' _ R1) in E1.\n- by rewrite (rely_loc' _ R3)/= locE//=/sr_step Hs/= (getStK cohs E1).\ncase: (cohs)=>Cs _ _ _. move/esym: F=> F.\nby case: Cs=>_/(_ _ _ F); rewrite /cohMsg/= H2/=; case.\nQed.\n\nDefinition receive_req_loop_cond (res : option (nid * input)) := res == None.\n\nDefinition receive_req_loop_inv (ps : reqs) :=\n  fun (r : option (nid * input)) i =>\n    match r with\n     | Some (from, args) =>\n       [/\\ loc i = st :-> ((from, sv, args) :: ps),\n        prec args & from \\in cls]\n     | None => loc i = st :-> ps\n    end.\n\nProgram Definition receive_req_loop :\n  {ps : reqs}, DHT [sv, W]\n  (fun i => loc i = st :-> ps,\n   fun (r : option (nid * input)) m =>\n     exists from args,\n     [/\\ r = Some (from, args),\n      loc m = st :-> ((from, sv, args) :: ps),\n      from \\in cls &\n      prec args]) := \n  Do _ (@while sv W _ _ receive_req_loop_cond receive_req_loop_inv _\n        (fun r => Do _ (\n           r <-- tryrecv_req;\n           match r with\n           | Some (from, _, args) => ret _ _ (Some (from, args))\n           | None => ret _ _ None\n           end)) None).\n\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation.\nby move:H; rewrite /receive_req_loop_inv (rely_loc' _ H0).\nQed.\nNext Obligation.\napply:ghC=>i1 ps/=[/eqP H1]L1 C1; subst r.\napply: step; apply: (gh_ex (g:=ps)).\napply: call_rule=>//r i2/=; case: r; last first.\n- by move=>L2 C2; apply: ret_rule=>i3 R2; rewrite -(rely_loc' _ R2) in L2.\ncase=>[[from to] args]E2 C2; apply: ret_rule=>i3 R2/=.\nby rewrite (rely_loc' _ R2). \nQed.\nNext Obligation.\napply: ghC=>i ps E1 C1; apply: (gh_ex (g:=ps)).\napply: call_rule=>//res m[].\nrewrite /receive_req_loop_cond; case: res=>//=[[from args]]_ [H1 H2]C2.\nby exists from, args. \nQed.\n\nProgram Definition blocking_receive_req :\n  {ps : reqs}, DHT [sv, W]\n  (fun i => loc i = st :-> ps,\n   fun (r : nid * input) m =>\n     [/\\ loc m = st :-> ((r.1, sv, r.2) :: ps),\n      r.1 \\in cls &\n      prec r.2]) :=\n  Do _ (r <-- receive_req_loop;\n        match r with\n        | Some res => ret _ _ res\n        | None => ret _ _ (0, [::])\n        end).\nNext Obligation.\napply: ghC=>i ps E1 C1; apply: step; apply: (gh_ex (g:=ps)).\napply: call_rule=>//res i2[from][args][Z]E2 H1 H2 C2.\nby subst res; apply: ret_rule=>i3 R2/=; rewrite (rely_loc' _ R2).\nQed.\n\n\n(***************************)\n(* Server sending messages *)\n(***************************)\n\n\n(* Generic server' send that assumes a permission to respond *)\n\nProgram Definition send_ans_act to msg :=\n  act (@send_action_wrapper W cal sv l (prEq cal)\n        (server_send_trans f prec cs cls) _ msg to).\nNext Obligation. by rewrite /cal_sends /InMem/=; left. Qed.\n\nProgram Definition send_answer (to : nid) (args : seq nat) (ans : nat) :\n  {ps : reqs}, DHT [sv, W]\n  (fun i => [/\\ loc i = st :-> ps, to \\in cls,\n             (to, sv, args) \\in ps &\n             f args = Some ans],                    \n   fun (r : seq nat) m =>\n       [/\\ loc m = st :-> (remove_elem ps (to, sv, args)) &\n       r = ans :: args]) \n  := Do send_ans_act to (ans :: args).    \nNext Obligation.\napply: ghC=>i1 ps [L1]H1 H2 H3 C1.\napply: act_rule=>i2 R1.\nmove: (proj2 (rely_coh R1))=>C2.\ncase: (C2)=>_ _ _ _/(_ l); rewrite prEq=>C.\nset d := (getStatelet i2 l).\nsplit=>//[|r i3 i4[Sf]St R3].\n- split=>//; first 1 last.\n  + by rewrite/Actions.can_send mem_cat Hs/=\n       -(cohD C2)/= domPt/= inE eqxx.\n  + rewrite/Actions.filter_hooks umfilt0=>???.\n    move => F.\n    apply sym_eq in F.\n    move: F.\n    move/find_some.\n    by rewrite dom0.\n  split=>//; split=>//.\n  exists C; rewrite -(rely_loc' _ R1) in L1; rewrite (getStK C L1).\n  by apply/hasP; exists (to, sv, args)=>//=; rewrite H3 !eqxx.\nrewrite (rely_loc' _ R3)=>{R3}.\ncase: St=>->[b]/=[][]->->/=; split=>//.\nhave P1: valid (dstate (getStatelet i2 l)). by apply: (cohVl C).\nhave P2: valid i2 by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom i2 by rewrite -(cohD(proj2(rely_coh R1))) domPt inE/=. \nrewrite -(rely_loc' _ R1) in L1.\nby rewrite (pf_irr (ss_safe_coh _ ) C) locE// (getStK C L1).\nQed.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n2 person-hours\n\n*)\n(**************************************************)\n\n\nEnd CalculatorServerLib.\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/CalculatorServerLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228824, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19908342729603196}}
{"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 TableAux2.Spec.\nRequire Import TableAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_destroy_aux_spec0 (g_llt: Pointer) (g_tbl: Pointer) (ll_table: Pointer) (level: Z64) (index: Z64) (map_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_llt, g_tbl, ll_table, level, index, map_addr with\n    | (_g_llt_base, _g_llt_ofst), (_g_tbl_base, _g_tbl_ofst), (_ll_table_base, _ll_table_ofst), VZ64 _level, VZ64 _index, VZ64 _map_addr =>\n      let _ret := 0 in\n      when'' _table_base, _table_ofst, adt == granule_map_spec (_g_tbl_base, _g_tbl_ofst) 7 adt;\n      rely is_int _table_ofst;\n      when' _gcnt, adt == get_g_rtt_refcount_spec (_g_tbl_base, _g_tbl_ofst) adt;\n      rely is_int64 _gcnt;\n      if (_gcnt =? 1) then\n        let _t'6 := 1 in\n        if (_gcnt =? 1) then\n          when' _new_pgte, adt == table_delete_spec (_table_base, _table_ofst) (_g_llt_base, _g_llt_ofst) adt;\n          rely is_int64 _new_pgte;\n          rely is_int64 _index;\n          when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 0) adt;\n          rely is_int64 (Z.land _new_pgte 504403158265495552);\n          rely is_int64 ((Z.land _new_pgte 504403158265495552) / 72057594037927936);\n          if (((Z.land _new_pgte 504403158265495552) / 72057594037927936) =? 2) then\n            rely is_int64 _map_addr;\n            when adt == invalidate_pages_in_block_spec (VZ64 _map_addr) adt;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n            when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n            when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n            rely is_int _t'5_ofst;\n            when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n            when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n            when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n            when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n            Some (adt, (VZ64 _ret))\n          else\n            rely is_int64 _map_addr;\n            when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n            when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n            when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n            rely is_int _t'5_ofst;\n            when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n            when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n            when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n            when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n            Some (adt, (VZ64 _ret))\n        else\n          rely is_int64 _level;\n          when' _new_pgte, adt == table_fold_spec (_table_base, _table_ofst) (VZ64 _level) (_g_tbl_base, _g_tbl_ofst) adt;\n          rely is_int64 _new_pgte;\n          rely is_int64 _index;\n          when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 0) adt;\n          rely is_int64 (Z.land _new_pgte 504403158265495552);\n          rely is_int64 ((Z.land _new_pgte 504403158265495552) / 72057594037927936);\n          if (((Z.land _new_pgte 504403158265495552) / 72057594037927936) =? 2) then\n            rely is_int64 _map_addr;\n            when adt == invalidate_pages_in_block_spec (VZ64 _map_addr) adt;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n            when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n            when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n            rely is_int _t'5_ofst;\n            when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n            when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n            when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n            when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n            Some (adt, (VZ64 _ret))\n          else\n            rely is_int64 _map_addr;\n            when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n            when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n            when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n            rely is_int _t'5_ofst;\n            when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n            when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n            when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n            when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n            Some (adt, (VZ64 _ret))\n      else\n        rely is_int64 (512 + 1);\n        let _t'6 := (_gcnt =? (512 + 1)) in\n        if _t'6 then\n          if (_gcnt =? 1) then\n            when' _new_pgte, adt == table_delete_spec (_table_base, _table_ofst) (_g_llt_base, _g_llt_ofst) adt;\n            rely is_int64 _new_pgte;\n            rely is_int64 _index;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 0) adt;\n            rely is_int64 (Z.land _new_pgte 504403158265495552);\n            rely is_int64 ((Z.land _new_pgte 504403158265495552) / 72057594037927936);\n            if (((Z.land _new_pgte 504403158265495552) / 72057594037927936) =? 2) then\n              rely is_int64 _map_addr;\n              when adt == invalidate_pages_in_block_spec (VZ64 _map_addr) adt;\n              when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n              when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n              when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n              rely is_int _t'5_ofst;\n              when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n              when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n              when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n              when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n              Some (adt, (VZ64 _ret))\n            else\n              rely is_int64 _map_addr;\n              when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n              when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n              when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n              when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n              rely is_int _t'5_ofst;\n              when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n              when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n              when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n              when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n              Some (adt, (VZ64 _ret))\n          else\n            rely is_int64 _level;\n            when' _new_pgte, adt == table_fold_spec (_table_base, _table_ofst) (VZ64 _level) (_g_tbl_base, _g_tbl_ofst) adt;\n            rely is_int64 _new_pgte;\n            rely is_int64 _index;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 0) adt;\n            rely is_int64 (Z.land _new_pgte 504403158265495552);\n            rely is_int64 ((Z.land _new_pgte 504403158265495552) / 72057594037927936);\n            if (((Z.land _new_pgte 504403158265495552) / 72057594037927936) =? 2) then\n              rely is_int64 _map_addr;\n              when adt == invalidate_pages_in_block_spec (VZ64 _map_addr) adt;\n              when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n              when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n              when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n              rely is_int _t'5_ofst;\n              when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n              when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n              when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n              when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n              Some (adt, (VZ64 _ret))\n            else\n              rely is_int64 _map_addr;\n              when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n              when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n              when adt == granule_put_spec (_g_tbl_base, _g_tbl_ofst) adt;\n              when'' _t'5_base, _t'5_ofst == null_ptr_spec  adt;\n              rely is_int _t'5_ofst;\n              when adt == set_g_rtt_rd_spec (_g_tbl_base, _g_tbl_ofst) (_t'5_base, _t'5_ofst) adt;\n              when adt == granule_memzero_mapped_spec (_table_base, _table_ofst) adt;\n              when adt == granule_set_state_spec (_g_tbl_base, _g_tbl_ofst) 1 adt;\n              when adt == buffer_unmap_spec (_table_base, _table_ofst) adt;\n              Some (adt, (VZ64 _ret))\n        else\n          let _ret := 1 in\n          when adt == buffer_unmap_spec (_table_base, _table_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/TableAux3/LowSpecs/table_destroy_aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.1990419616100778}}
{"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_compact.\n  Context {\u03a3} `{!heapG \u03a3, !multicopyG \u03a3, !multicopy_lsmG \u03a3}.\n  Notation iProp := (iProp \u03a3).  \n  Local Notation \"m !1 i\" := (nzmap_total_lookup i m) (at level 20).\n\n  (* nodePred without node(r, n, es, Vn) *)\n  Definition nodePred_aux \u03b3_gh \u03b3_s n (Cn: gmap K (V*T)) (Vn: gmap K V) \n                      (Tn Qn: gmap K T) \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn es: iProp :=\n      own \u03b3_gh (\u25ef {[n := ghost_loc \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn]})  \n    \u2217 frac_ghost_state \u03b3_en \u03b3_cn \u03b3_qn es Tn Qn\n    \u2217 own \u03b3_s (\u25ef set_of_map Cn)\n    \u2217 contents_proj Cn Vn Tn.\n\n  (* nodeShared without outflow_constraints and \u03c6_i's *)  \n  Definition nodeShared_aux \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Tn Qn Bn H\n                \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn es In Jn : iProp :=\n      own \u03b3_gh (\u25ef {[n := ghost_loc \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn]})\n    \u2217 frac_ghost_state \u03b3_en \u03b3_cn \u03b3_qn es Tn Qn  \n    \u2217 singleton_interfaces_ghost_state \u03b3_I \u03b3_J n In Jn \n    \u2217 inFP \u03b3_f n\n    \u2217 closed \u03b3_f es\n    \u2217 \u231ccontents_in_reach Bn Tn Qn\u231d\n    \u2217 (if decide (n = r) \n       then \u231c\u2200 k, Bn !!! k = ((map_of_set H) !!! k).2\u231d \n            \u2217 \u231cinflow_zero In\u231d \n       else True)%I\n    \u2217 ([\u2217 set] k \u2208 KS, own (\u03b3_cirn !!! (k)) (\u25cf (MaxNat (Bn !!! k)))).\n\n  Lemma maxnat_set_update (\u03b3: gmap K gname) (S: gset K) (B B': gmap K nat) :\n        (\u231c\u2200 k, k \u2208 S \u2192 B !!! k \u2264 B' !!! k\u231d) -\u2217 \n          ([\u2217 set] k \u2208 S, own (\u03b3 !!! k) (\u25cf MaxNat (B !!! k))) ==\u2217\n            ([\u2217 set] k \u2208 S, own (\u03b3 !!! k) (\u25cf MaxNat (B' !!! k))).\n  Proof.\n    iIntros \"%\".\n    iInduction S as [| s S' H'] \"IHs\" using set_ind_L.\n    - iIntros \"_\"; iModIntro; try done.\n    - iIntros \"H\". \n      rewrite (big_sepS_delete _ ({[s]} \u222a S') s); last first.\n      clear; set_solver. \n      iDestruct \"H\" as \"(Hs & H')\".\n      iMod (own_update (\u03b3 !!! s) (\u25cf (MaxNat (B !!! s))) \n                    (\u25cf (MaxNat (B' !!! s))) with \"Hs\") as \"Hs\".\n      { apply (auth_update_auth _ _ (MaxNat (B' !!! s))).\n        apply max_nat_local_update. simpl. \n        apply H; try set_solver. }\n      assert (({[s]} \u222a S') \u2216 {[s]} = S') as HS.\n      { clear -H'; set_solver. } rewrite HS. \n      rewrite (big_sepS_delete _ ({[s]} \u222a S') s); last first.\n      clear; set_solver. iSplitL \"Hs\". iModIntro; iFrame \"Hs\".\n      rewrite HS. iMod (\"IHs\" with \"[] [$H']\") as \"H'\".\n      iPureIntro; intros k Hk; apply H; set_solver. \n      iModIntro; iFrame.\n  Qed.\n\n  Lemma ghost_update_contExt (\u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh \u03b3_en \u03b3_cn \u03b3_qn: gname)\n                   (\u03b3_cirn: gmap K gnameO)\n                (H0: gset KVT) (h\u03b30: gmap Node per_node_gl) \n                (I0 Im0 In0: multiset_flowint_ur KT)\n                (J0 Jm0 Jn0: multiset_flowint_ur K) \n                (r m n: Node) (Cm0 Cn: gmap K (V*T)) (Vm0 Vn: gmap K V) \n                (Tm0 Tn Bm0 Bn Qm0 Qn: gmap K T)\n                (esn esm0: esT):\n            \u231cm \u2209 domm I0\u231d\n          \u2217 \u231cCm0 = \u2205\u231d  \n          \u2217 \u231cVm0 = \u2205\u231d\n          \u2217 \u231cTm0 = \u2205\u231d\n          \u2217 \u231cesm0 = \u2205\u231d\n          \u2217 \u231cBm0 = \u2205\u231d\n          \u2217 \u231cQm0 = \u2205\u231d\n          \u2217 \u231cIm0 = int {| infR := {[m := \u2205]} ; outR := \u2205 |}\u231d\n          \u2217 \u231cJm0 = int {| infR := {[m := \u2205]} ; outR := \u2205 |}\u231d          \n          -\u2217\n            inFP \u03b3_f n\n          \u2217 nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn \n                         \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn  \n          \u2217 nodeShared' \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Tn Qn Bn H0 \n                        \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn In0 Jn0\n          \u2217 own \u03b3_s (\u25cf H0)\n          \u2217 \u231cHInit H0\u231d             \n          \u2217 global_state \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r h\u03b30 I0 J0\n          ==\u2217\n          \u2203 (h\u03b3': gmap Node per_node_gl) I0' J0' (\u03b3_em \u03b3_cm \u03b3_qm: gname)\n            (\u03b3_cirm: gmap K gnameO),\n            inFP \u03b3_f m\n          \u2217 nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn \n                         \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn\n          \u2217 nodeShared' \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Tn Qn Bn H0 \n                        \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn In0 Jn0\n          \u2217 nodePred_aux \u03b3_gh \u03b3_s m Cm0 Vm0 Tm0 Qm0 \n                         \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0\n          \u2217 nodeShared_aux \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Tm0 Qm0 Bm0 H0 \n                            \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0 Im0 Jm0\n          \u2217 own \u03b3_s (\u25cf H0)             \n          \u2217 global_state \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r h\u03b3' I0' J0'\n          \u2217 \u231cesn !!! m = \u2205\u231d\n          \u2217 \u231cout In0 m = 0%CCM\u231d\n          \u2217 \u231cout Jn0 m = 0%CCM\u231d\n          \u2217 \u231cdomm I0' = domm I0 \u222a {[m]}\u231d\n          \u2217 \u231cm \u2260 r\u231d \u2217 \u231cm \u2260 n\u231d.\n  Proof.\n    iIntros \"(%&%&%&%&%&%&%&%&%) (#FP_n & HnP_aux & HnS_n' & HH & HInit & Hglob)\".\n    rename H into m_notin_I0. rename H1 into HCm0. rename H2 into HVm0. \n    rename H3 into HTm0. rename H4 into Hesm.\n    rename H5 into HBm0. rename H6 into HQm0. rename H7 into HIm0.\n    rename H8 into HJm0. iDestruct \"HInit\" as %HInit.\n    iDestruct \"Hglob\" as \"(HI & Out_I & HR \n        & Out_J & Inf_J & Hf & H\u03b3 & FP_r & domm_IJ & domm_I\u03b3)\".   \n\n    iAssert (\u231cn \u2208 domm I0\u231d)%I as \"%\".\n    { by iPoseProof (inFP_domm _ _ _ with \"[$FP_n] [$Hf]\") as \"H'\". }\n    rename H into n_in_I0.  \n\n    iDestruct \"HnP_aux\" as \"(HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n    iDestruct \"HnS_n'\" as \n                  \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                        & HnS_cl & HnS_oc & HnS_Bn & HnS_H & HnS_star & H\u03c6)\".\n\n    iAssert (\u231cr \u2208 domm I0\u231d)%I as \"%\". \n    { by iPoseProof (inFP_domm _ _ _ with \"[$FP_r] [$Hf]\") as \"H'\". }\n    rename H into r_in_I0.\n    assert (m \u2260 r) as m_neq_r. \n    { clear -m_notin_I0 r_in_I0. set_solver. }\n    assert (m \u2260 n) as m_neq_n. \n    { clear -m_notin_I0 n_in_I0. set_solver. }\n    assert (domm Im0 = {[m]}) as Domm_Im0.\n    { subst Im0. unfold domm, dom, flowint_dom.\n      unfold inf_map. simpl. apply leibniz_equiv. \n      by rewrite dom_singleton. }\n    assert (domm Jm0 = {[m]}) as Domm_Jm0.\n    { subst Jm0. unfold domm, dom, flowint_dom.\n      unfold inf_map. simpl. apply leibniz_equiv. \n      by rewrite dom_singleton. }  \n\n    iAssert (\u231cesn !!! m = \u2205\u231d)%I as %Esn_empty.\n    { destruct (decide (esn !!! m = \u2205)); try done.\n      iAssert (\u231cesn !!! m \u2260 \u2205\u231d)%I as \"H'\".\n      by iPureIntro. \n      iPoseProof (\"HnS_cl\" with \"H'\") as \"Hfp_m\".\n      iAssert (\u231cm \u2208 domm I0\u231d)%I as \"%\". \n      { by iPoseProof (inFP_domm _ _ _ with \"[$Hfp_m] [$Hf]\") as \"H''\". }\n      iPureIntro. clear -H m_notin_I0. set_solver. }\n       \n    iPoseProof (own_valid with \"HI\") as \"%\".\n    rename H into Valid_I0.\n    rewrite auth_auth_valid in Valid_I0 *; intros Valid_I0. \n\n    iDestruct \"HnS_si\" as \"(HnI & HnR & Domm_In0 & Domm_Jn0)\".\n    iPoseProof (own_valid with \"HnI\") as \"%\".\n    rename H into Valid_In0. \n    rewrite auth_frag_valid in Valid_In0 *; intros Valid_In0.\n    iPoseProof (own_valid with \"HnR\") as \"%\".\n    rename H into Valid_Jn0. \n    rewrite auth_frag_valid in Valid_Jn0 *; intros Valid_Jn0.\n    iDestruct \"Domm_In0\" as %Domm_In0.\n    iDestruct \"Domm_Jn0\" as %Domm_Jn0.\n        \n    assert (\u2713 Im0) as Valid_Im0.\n    { unfold valid, cmra_valid, flowint_valid.\n      subst Im0. simpl. split.\n      solve_map_disjoint. \n      intros _; try done. }\n    assert (\u2713 Jm0) as Valid_Jm0.\n    { unfold valid, cmra_valid, flowint_valid.\n      subst Jm0. simpl. split.\n      solve_map_disjoint. \n      intros _; try done. }\n\n    iPoseProof ((auth_own_incl \u03b3_I I0 In0) with \"[$HI $HnI]\") as \"%\".\n    rename H into Incl_In0. destruct Incl_In0 as [Iz Incl_In0].\n    iDestruct \"Out_I\" as %Out_I.\n    assert (out In0 m = 0%CCM \u2227 out Iz m = 0%CCM) as [Out_In_m Out_Iz_m].\n    { unfold outflow_zero in Out_I.\n      rewrite Incl_In0 in Valid_I0*; intro H'.\n      rewrite Incl_In0 in m_notin_I0*; intro H''.\n      pose proof (intComp_unfold_out In0 Iz H' m H'') as Hout.\n      unfold out in Hout. unfold out.\n      rewrite <-Incl_In0 in Hout. rewrite Out_I in Hout. \n      rewrite nzmap_lookup_empty in Hout. \n      unfold ccmunit, ccm_unit in Hout. simpl in Hout.\n      unfold lift_unit in Hout. unfold ccmop, ccm_op in Hout.\n      simpl in Hout. unfold lift_op in Hout.\n      unfold ccmop, ccm_op in Hout. simpl in Hout.\n      rewrite nzmap_eq in Hout*; intros Hout.\n      unfold ccmunit, lift_unit. split; apply nzmap_eq;\n      intros k; rewrite nzmap_lookup_empty;\n      unfold ccmunit, ccm_unit; simpl;\n      unfold nat_unit; pose proof Hout k as Hout;\n      rewrite nzmap_lookup_empty in Hout;\n      unfold ccmunit, ccm_unit in Hout;\n      simpl in Hout; unfold nat_unit, nat_op in Hout;\n      rewrite nzmap_lookup_merge in Hout; clear-Hout; lia. }\n\n    assert (\u2713 (In0 \u22c5 Im0)) as Valid_Inm0.\n    { apply intValid_composable. unfold intComposable.\n      repeat split; try done.\n      * rewrite Domm_In0 Domm_Im0.\n        clear -m_notin_I0 n_in_I0.\n        set_solver.\n      * unfold map_Forall. intros n' x Hinf.\n        subst Im0. unfold out. simpl.\n        rewrite nzmap_lookup_empty.\n        rewrite ccm_left_id. rewrite ccm_pinv_unit.\n        unfold inf. by rewrite Hinf.\n      * unfold map_Forall. intros n' x Hinf.\n        destruct (decide (n' = m)).\n        ** subst n'. rewrite Out_In_m.\n           rewrite ccm_left_id. rewrite ccm_pinv_unit.\n           unfold inf. by rewrite Hinf.\n        ** subst Im0. simpl in Hinf.\n           rewrite lookup_singleton_ne in Hinf; try done. }\n\n    assert (domm (In0 \u22c5 Im0) = {[n; m]}) as Domm_Inm0.\n    { rewrite flowint_comp_fp; try done.\n      by rewrite Domm_In0 Domm_Im0. }\n    assert (domm I0 = domm In0 \u222a domm Iz) as Domm_Inz.\n    { rewrite Incl_In0. rewrite flowint_comp_fp. done.\n      by rewrite <-Incl_In0. }   \n    assert (n \u2209 domm Iz) as n_notin_Iz.\n    { rewrite Incl_In0 in Valid_I0 *; intros Valid_In0'.\n      apply intComposable_valid in Valid_In0'.\n      unfold intComposable in Valid_In0'.\n      destruct Valid_In0' as [_ [_ [H' _]]].\n      rewrite Domm_In0 in H'. clear -H'; set_solver. }\n\n    assert (m \u2209 domm Iz) as m_notin_Iz.\n    { clear -Domm_Inz m_notin_I0. set_solver. }\n          \n                \n    iMod (own_updateP (flowint_update_P (_) I0 In0 (In0 \u22c5 Im0)) \u03b3_I\n               (\u25cf I0 \u22c5 \u25ef (In0)) with \"[HI HnI]\") as (Io) \"H'\".\n    { rewrite Incl_In0. apply flowint_update. \n      split; last split.\n      - unfold contextualLeq.\n        repeat split; try done.\n        + rewrite flowint_comp_fp; try done.\n          clear; set_solver.\n        + intros n' H'.\n          assert (n' = n) as Hn.\n          { rewrite Domm_In0 in H'.\n            clear -H'; set_solver. }\n          subst n'.\n          pose proof (intComp_inf_1 In0 Im0 Valid_Inm0 n H') as H''.\n          rewrite H''. subst Im0; unfold out; simpl.\n          rewrite nzmap_lookup_empty.\n          by rewrite ccm_pinv_unit. \n        + intros n' H'.\n          pose proof (intComp_unfold_out In0 Im0 Valid_Inm0 n' H') as H''.\n          rewrite H''. unfold out at 3, out_map. subst Im0.\n          simpl. rewrite nzmap_lookup_empty.\n          by rewrite ccm_right_id.\n      - rewrite Domm_Inm0. clear -n_notin_Iz m_notin_Iz.\n        set_solver.\n      - intros n' Hn'. rewrite Domm_Inm0 Domm_In0 in Hn'.\n        assert (n' = m) as H'. clear -Hn'. set_solver.\n        subst n'. by unfold out in Out_Iz_m. }              \n\n    { rewrite own_op. iFrame. }                        \n    iPoseProof ((flowint_update_result' \u03b3_I I0 In0 (In0 \u22c5 Im0))\n                    with \"H'\") as (I0') \"(% & % & (HI & HIn))\".\n    rename H into ContLeq_I0. clear Io. \n    destruct H1 as [Io [HI0 HI0']].\n    iEval (rewrite auth_frag_op) in \"HIn\".\n    iDestruct \"HIn\" as \"(HIn & HIm)\".\n    iPoseProof (own_valid with \"HI\") as \"%\".\n    rename H into Valid_I0'.\n    rewrite auth_auth_valid in Valid_I0' *; intros Valid_I0'. \n\n    assert (domm I0' = domm I0 \u222a {[m]}) as Domm_I0'.\n    { rewrite Incl_In0 in HI0*; intros H'.\n      apply intComp_cancelable in H'. \n      rewrite HI0'. repeat rewrite flowint_comp_fp.\n      rewrite Domm_Im0 H'. clear; set_solver.\n      rewrite Incl_In0 in Valid_I0 *; intros H''.\n      done. done. apply leibniz_equiv_iff in HI0'. \n      by rewrite <-HI0'. by rewrite <-Incl_In0. }\n\n    assert (domm I0' \u2216 {[m]} = domm I0) as Domm_I0_m.\n    { clear -Domm_I0' m_notin_I0. set_solver. }  \n\n        \n    iAssert (\u231cr \u2208 domm J0\u231d)%I as \"%\". \n    { iDestruct \"domm_IJ\" as %H'. iPureIntro. by rewrite <-H'. }\n    rename H into r_in_J0.\n    iAssert (\u231cm \u2209 domm J0\u231d)%I as \"%\".\n    { iDestruct \"domm_IJ\" as %H'. iPureIntro. by rewrite <-H'. }\n    rename H into m_notin_J0.\n    iAssert (\u231cn \u2208 domm J0\u231d)%I as \"%\".\n    { iDestruct \"domm_IJ\" as %H'. iPureIntro. by rewrite <-H'. }\n    rename H into n_in_J0.        \n        \n    iPoseProof (own_valid with \"HR\") as \"%\".\n    rename H into Valid_J0.\n    rewrite auth_auth_valid in Valid_J0 *; intros Valid_J0. \n        \n    iPoseProof ((auth_own_incl \u03b3_J J0 Jn0) with \"[$HR $HnR]\") as \"%\".\n    rename H into Incl_Jn0. destruct Incl_Jn0 as [Jz Incl_Jn0].\n    iDestruct \"Out_J\" as %Out_J.\n    assert (out Jn0 m = 0%CCM \u2227 out Jz m = 0%CCM) as [Out_Jn_m Out_Jz_m].\n    { unfold outflow_zero in Out_J.\n      rewrite Incl_Jn0 in Valid_J0*; intro H'.\n      rewrite Incl_Jn0 in m_notin_J0*; intro H''.\n      pose proof (intComp_unfold_out Jn0 Jz H' m H'') as Hout.\n      unfold out in Hout. unfold out.\n      rewrite <-Incl_Jn0 in Hout. rewrite Out_J in Hout. \n      rewrite nzmap_lookup_empty in Hout. \n      unfold ccmunit, ccm_unit in Hout. simpl in Hout.\n      unfold lift_unit in Hout. unfold ccmop, ccm_op in Hout.\n      simpl in Hout. unfold lift_op in Hout.\n      unfold ccmop, ccm_op in Hout. simpl in Hout.\n      rewrite nzmap_eq in Hout*; intros Hout.\n      unfold ccmunit, lift_unit. split; apply nzmap_eq;\n      intros k; rewrite nzmap_lookup_empty;\n      unfold ccmunit, ccm_unit; simpl;\n      unfold nat_unit; pose proof Hout k as Hout;\n      rewrite nzmap_lookup_empty in Hout;\n      unfold ccmunit, ccm_unit in Hout;\n      simpl in Hout; unfold nat_unit, nat_op in Hout;\n      rewrite nzmap_lookup_merge in Hout; clear-Hout; lia. }\n\n    assert (\u2713 (Jn0 \u22c5 Jm0)) as Valid_Jnm0.\n    { apply intValid_composable. unfold intComposable.\n      repeat split; try done.\n      * rewrite Domm_Jn0 Domm_Jm0.\n        clear -m_notin_J0 n_in_J0.\n        set_solver.\n      * unfold map_Forall. intros n' x Hinf.\n        subst Jm0. unfold out. simpl.\n        rewrite nzmap_lookup_empty.\n        rewrite ccm_left_id. rewrite ccm_pinv_unit.\n        unfold inf. by rewrite Hinf.\n      * unfold map_Forall. intros n' x Hinf.\n        destruct (decide (n' = m)).\n        ** subst n'. rewrite Out_Jn_m.\n           rewrite ccm_left_id. rewrite ccm_pinv_unit.\n           unfold inf. by rewrite Hinf.\n        ** subst Jm0. simpl in Hinf.\n           rewrite lookup_singleton_ne in Hinf; try done. }\n\n    assert (domm (Jn0 \u22c5 Jm0) = {[n; m]}) as Domm_Jnm0.\n    { rewrite flowint_comp_fp; try done.\n      by rewrite Domm_Jn0 Domm_Jm0. }\n    assert (domm J0 = domm Jn0 \u222a domm Jz) as Domm_Jnz.\n    { rewrite Incl_Jn0. rewrite flowint_comp_fp. done.\n      by rewrite <-Incl_Jn0. }   \n    assert (n \u2209 domm Jz) as n_notin_Jz.\n    { rewrite Incl_Jn0 in Valid_J0 *; intros Valid_Jn0'.\n      apply intComposable_valid in Valid_Jn0'.\n      unfold intComposable in Valid_Jn0'.\n      destruct Valid_Jn0' as [_ [_ [H' _]]].\n      rewrite Domm_Jn0 in H'. clear -H'; set_solver. }\n    assert (m \u2209 domm Jz) as m_notin_Jz.\n    { clear -Domm_Jnz m_notin_J0. set_solver. }               \n\n    iMod (own_updateP (flowint_update_P (_) J0 Jn0 (Jn0 \u22c5 Jm0)) \u03b3_J\n              (\u25cf J0 \u22c5 \u25ef (Jn0)) with \"[HR HnR]\") as (Jo) \"H'\".\n    { rewrite Incl_Jn0. apply flowint_update. \n      split; last split.\n      - unfold contextualLeq.\n        repeat split; try done.\n        + rewrite flowint_comp_fp; try done.\n          clear; set_solver.\n        + intros n' H'.\n          assert (n' = n) as Hn.\n          { rewrite Domm_Jn0 in H'.\n            clear -H'; set_solver. }\n          subst n'.\n          pose proof (intComp_inf_1 Jn0 Jm0 Valid_Jnm0 n H') as H''.\n          rewrite H''. subst Jm0; unfold out; simpl.\n          rewrite nzmap_lookup_empty.\n          by rewrite ccm_pinv_unit. \n        + intros n' H'.\n          pose proof (intComp_unfold_out Jn0 Jm0 Valid_Jnm0 n' H') as H''.\n          rewrite H''. unfold out at 3, out_map. subst Jm0.\n          simpl. rewrite nzmap_lookup_empty.\n          by rewrite ccm_right_id.\n      - rewrite Domm_Jnm0. clear -n_notin_Jz m_notin_Jz.\n        set_solver.\n      - intros n' Hn'. rewrite Domm_Jnm0 Domm_Jn0 in Hn'.\n        assert (n' = m) as H'. clear -Hn'. set_solver.\n        subst n'. by unfold out in Out_Jz_m. }              \n    { rewrite own_op. iFrame. }                        \n    iPoseProof ((flowint_update_result \u03b3_J J0 Jn0 (Jn0 \u22c5 Jm0))\n                   with \"H'\") as (J0') \"(% & % & (HR & HJn))\".\n    rename H into ContLeq_J0. clear Jo. \n    destruct H1 as [Jo [HR0 HR0']].\n    iEval (rewrite auth_frag_op) in \"HJn\".\n    iDestruct \"HJn\" as \"(HJn & HJm)\".\n    iPoseProof (own_valid with \"HR\") as \"%\".\n    rename H into Valid_J0'.\n    rewrite auth_auth_valid in Valid_J0' *; intros Valid_J0'. \n\n    assert (domm J0' = domm J0 \u222a {[m]}) as Domm_J0'.\n    { rewrite Incl_Jn0 in HR0*; intros H'.\n      apply intComp_cancelable in H'. \n      rewrite HR0'. repeat rewrite flowint_comp_fp.\n      rewrite Domm_Jm0 H'. clear; set_solver.\n      rewrite Incl_Jn0 in Valid_J0 *; intros H''.\n      done. done. apply leibniz_equiv_iff in HR0'. \n      by rewrite <-HR0'. by rewrite <-Incl_Jn0. }\n    assert (domm J0' \u2216 {[m]} = domm J0) as Domm_J0_m.\n    { clear -Domm_J0' m_notin_J0. set_solver. }\n    iDestruct \"Inf_J\" as %Inf_J.  \n    iAssert (\u231cinflow_J J0' r\u231d)%I as \"Inf_J'\".\n    { iPureIntro. unfold inflow_J. intros n' k.\n      destruct (decide (n' = r)) eqn: Hn'.\n      + subst n'. pose proof Inf_J r k as Inf_J.\n        rewrite Hn' in Inf_J.\n        unfold contextualLeq in ContLeq_J0.\n        destruct ContLeq_J0 as [_ [_ [_ [H' _]]]].\n        pose proof H' r r_in_J0 as H'.\n        unfold in_inset. unfold in_inset in Inf_J.\n        by rewrite <-H'. \n      + pose proof Inf_J n' k as Inf_J.\n        rewrite Hn' in Inf_J.\n        unfold contextualLeq in ContLeq_J0.\n        destruct ContLeq_J0 as [_ [_ [_ [H' H'']]]].\n        destruct (decide (n' \u2208 domm J0)).\n        * pose proof H' n' e as H'.\n          unfold in_inset. unfold in_inset in Inf_J.\n          by rewrite <-H'.\n        * destruct (decide (n' = m)).\n          ** subst n'.\n             pose proof (intComp_inf_2 J0 Jm0) as Hinf.\n             rewrite cmra_comm in HR0' *; intros HR0'.\n             rewrite cmra_assoc in HR0' *; intros HR0'.\n             rewrite cmra_comm in HR0 *; intros HR0.\n             rewrite <-HR0 in HR0'.\n             rewrite HR0' in Valid_J0'.\n             assert (m \u2208 domm Jm0) as m_in_Jm0.\n             { rewrite Domm_Jm0. clear; set_solver. }\n             pose proof Hinf Valid_J0' m m_in_Jm0 as Hinf.\n             apply leibniz_equiv_iff in HR0'. \n             rewrite <-HR0' in Hinf.\n             unfold in_inset. rewrite Hinf.\n             unfold outflow_zero_J in Out_J.\n             unfold out. rewrite Out_J.\n             rewrite nzmap_lookup_empty.\n             subst Jm0. unfold inf. simpl.\n             rewrite lookup_singleton.\n             simpl. rewrite ccm_pinv_unit.\n             clear. unfold dom_ms, dom, nzmap_dom.\n             set_solver.\n          ** assert (n' \u2209 domm J0') as Hdom.\n             { rewrite Domm_J0'.\n               clear -n1 n2. set_solver. }\n             unfold domm, dom, flowint_dom in Hdom.\n             destruct J0' as [ [Rinf Rout] | ]; last by contradiction.\n             simpl in Hdom. rewrite not_elem_of_dom in Hdom *; intros Hdom.\n             unfold in_inset. unfold inf, inf_map.\n             simpl. rewrite Hdom. simpl.\n             unfold ccmunit, ccm_unit, lift_unit.\n             unfold dom_ms, dom, flowint_dom, nzmap_dom.\n             unfold nzmap_unit. simpl. clear; set_solver. }\n\n    iMod (own_update \u03b3_f (\u25cf domm I0) (\u25cf (domm I0 \u222a {[m]}) \u22c5 \u25ef ({[m]}))\n                     with \"[Hf]\") as \"(Hf & H')\"; try done.\n    { apply (auth_update_alloc (domm I0) (domm I0 \u222a {[m]}) ({[m]})).\n      apply local_update_discrete.\n      intros mz _ Hmz. split; try done.\n      rewrite gset_opM in Hmz. rewrite gset_opM.\n      rewrite Hmz. clear. set_solver. }\n    iEval (rewrite <-Domm_I0') in \"Hf\".\n    iAssert (inFP \u03b3_f m) with \"H'\" as \"#FP_m\".\n    iDestruct \"H'\" as \"HnS_FPm\".\n        \n    iMod (own_alloc (to_frac_agree (1) (esm0))) \n          as (\u03b3_em)\"Hesm_f\". { try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hesm_f\".      \n    iEval (rewrite (frac_agree_op (1/2) (1/2) _)) in \"Hesm_f\". \n    iDestruct \"Hesm_f\" as \"(HnS_esm & HnP_esm)\".        \n\n    iMod (own_alloc (to_frac_agree (1) (Tm0))) \n          as (\u03b3_cm)\"Hcm_f\". { try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hcm_f\".      \n    iEval (rewrite (frac_agree_op (1/2) (1/2) _)) in \"Hcm_f\". \n    iDestruct \"Hcm_f\" as \"(HnS_cm & HnP_cm)\".        \n\n    iMod (own_alloc (to_frac_agree (1) (Qm0))) \n          as (\u03b3_qm)\"Hqm_f\". { try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hqm_f\".      \n    iEval (rewrite (frac_agree_op (1/2) (1/2) _)) in \"Hqm_f\". \n    iDestruct \"Hqm_f\" as \"(HnS_qm & HnP_qm)\".\n        \n    iAssert (frac_ghost_state \u03b3_em \u03b3_cm \u03b3_qm esm0 Tm0 Qm0\n            \u2217 frac_ghost_state \u03b3_em \u03b3_cm \u03b3_qm esm0 Tm0 Qm0)%I\n            with \"[HnS_esm HnP_esm HnS_cm HnP_cm HnS_qm HnP_qm]\"\n            as \"(HnS_fracm & HnP_fracm)\".\n    { iFrame. }               \n\n    iMod (own_alloc_set KS with \"[]\") as \"HnS_starm\"; first done.\n    iDestruct \"HnS_starm\" as (\u03b3_cirm)\"HnS_starm\".\n        \n    iDestruct \"domm_IJ\" as \"#domm_IJ\".\n    iDestruct \"domm_I\u03b3\" as \"#domm_I\u03b3\".\n    iMod ((ghost_heap_update \u03b3_gh h\u03b30 m \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm) \n                with \"[] [$H\u03b3]\") as \"(H\u03b3 & #HnS_ghm)\".\n    { iDestruct \"domm_I\u03b3\" as %H'. iPureIntro.\n      rewrite <-H'. apply m_notin_I0. }            \n\n    assert (set_of_map Cm0 = \u2205) as Set_of_Cm0.\n    { unfold set_of_map. subst Cm0.\n      by rewrite map_fold_empty. }\n    iMod (own_update \u03b3_s (\u25cf H0) (\u25cf H0 \u22c5 \u25ef (set_of_map Cm0))\n             with \"[$HH]\") as \"HH\".\n    { apply (auth_update_alloc _ (H0) (set_of_map Cm0)).\n      rewrite Set_of_Cm0.\n      apply local_update_discrete. intros mz Valid_H1 H1_eq.\n      split; try done. }\n    iDestruct \"HH\" as \"(HH & HnP_Cm)\".\n        \n    iAssert (closed \u03b3_f esm0) as \"HnS_clm\".\n    { iIntros (n')\"%\". rename H into H'.\n      exfalso. rewrite Hesm in H'.\n      rewrite /(\u2205 !!! n') in H'.\n      unfold map_lookup_total in H'.\n      rewrite lookup_empty in H'.\n      simpl in H'. clear -H'; done. }\n\n    iAssert (\u231coutflow_zero I0'\u231d)%I as \"Out_I'\".\n    { iPureIntro. unfold outflow_zero.\n      apply nzmap_eq. intros n'.\n      destruct (decide (n' \u2208 domm I0')).\n      + pose proof intValid_in_dom_not_out I0' n' Valid_I0' e as H'.\n        unfold out in H'. rewrite H'.\n        by rewrite nzmap_lookup_empty.\n      + destruct ContLeq_I0 as [_ [_ [_ [H' H'']]]].\n        pose proof H'' n' n0 as H''.\n        unfold out in H''. rewrite <-H''.\n        apply leibniz_equiv in Out_I.\n        rewrite nzmap_eq in Out_I *; intros Out_I.\n        pose proof Out_I n' as Out_I.\n        by rewrite Out_I. }  \n\n    iAssert (\u231coutflow_zero_J J0'\u231d)%I as \"Out_J'\".\n    { iPureIntro. unfold outflow_zero.\n      apply nzmap_eq. intros n'.\n      destruct (decide (n' \u2208 domm J0')).\n      + pose proof intValid_in_dom_not_out J0' n' Valid_J0' e as H'.\n        unfold out in H'. rewrite H'.\n        by rewrite nzmap_lookup_empty.\n      + destruct ContLeq_J0 as [_ [_ [_ [H' H'']]]].\n        pose proof H'' n' n0 as H''.\n        unfold out in H''. rewrite <-H''.\n        apply leibniz_equiv in Out_J.\n        rewrite nzmap_eq in Out_J *; intros Out_J.\n        pose proof Out_J n' as Out_J.\n        by rewrite Out_J. }\n              \n    iAssert (contents_proj Cm0 Vm0 Tm0) as \"HnP_ctsm\".\n    { subst Cm0 Vm0 Tm0. iPureIntro. repeat split; try done.\n      - clear; set_solver.\n      - clear; set_solver.\n      - intros [H' _]; clear -H'; exfalso; try done. }\n        \n    iModIntro. iExists (<[m:=ghost_loc \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm]> h\u03b30), \n                    I0', J0', \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm. \n    iSplitR. iFrame \"FP_m\".\n    iSplitL \"HnP_gh HnP_frac HnP_C HnP_cts\". { iFrame. }\n    iSplitL \"HnS_gh HnS_frac HnS_FP HnS_cl HnS_oc HnS_Bn HnS_H HnS_star HIn HJn H\u03c6\".\n    { iFrame. by iPureIntro. }\n    iSplitL \"HnP_fracm HnP_Cm\". \n    { iFrame \"\u2217#\". }\n    iSplitL \"HnS_fracm HnS_starm HIm HJm\".\n    { iFrame \"\u2217#\". iSplitR. by iPureIntro.\n      iSplitR. iPureIntro. \n      { intros k0 t0 HKS. subst Tm0 Bm0 Qm0.\n        split; try done. }  \n      iSplitR. destruct (decide (m = r)); try done. \n      iApply (big_sepS_mono \n                (\u03bb y, own (\u03b3_cirm !!! y) (\u25cf {| max_nat_car := 0 |}) )%I\n                (\u03bb y, own (\u03b3_cirm !!! y) (\u25cf {| max_nat_car := Bm0 !!! y |}))%I\n                KS); try done.\n      { intros k HKS. iFrame. rewrite HBm0. rewrite /(\u2205 !!! k). \n        unfold map_lookup_total. rewrite lookup_empty.\n        simpl. try eauto. } }\n    iFrame \"\u2217#\". iDestruct \"domm_IJ\" as %domm_IJ.\n    iDestruct \"domm_I\u03b3\" as %domm_I\u03b3.\n    iPureIntro. repeat split; try done.\n    by rewrite Domm_I0' Domm_J0' domm_IJ.\n    apply leibniz_equiv. rewrite dom_insert.\n    rewrite Domm_I0' domm_I\u03b3. clear; set_solver.\n  Qed.\n              \n  Lemma ghost_update_interface_mod \u03b3_I \u03b3_J \u03b3_f \u03b3_gh \u03b3_s r H0  \n                m Cm0 Vm0 Tm0 esm0 Bm0 Qm0 \u03b3_em \u03b3_cm \u03b3_qm\n               \u03b3_cirm Im0 Jm0\n                n Cn Vn Tn Bn Qn \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn esn' In0 Jn0 :\n            \u231cCm0 = \u2205\u231d\n          \u2217 \u231cesm0 = \u2205\u231d\n          \u2217 \u231cBm0 = \u2205\u231d\n          \u2217 \u231cQm0 = \u2205\u231d\n          \u2217 \u231cIm0 = int {| infR := {[m := \u2205]} ; outR := \u2205 |}\u231d\n          \u2217 \u231cJm0 = int {| infR := {[m := \u2205]} ; outR := \u2205 |}\u231d\n          \u2217 \u231cesn' = <[m := (esn' !!! m)]> esn\u231d\n          \u2217 \u231cesn !!! m = \u2205\u231d\n          \u2217 \u231cout In0 m = 0%CCM\u231d\n          \u2217 \u231cout Jn0 m = 0%CCM\u231d\n          \u2217 \u231cHInit H0\u231d\n          \u2217 \u231cm \u2260 r\u231d\n          -\u2217\n            node r n esn' Vn\n          \u2217 nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn \n                         \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn  \n          \u2217 nodeShared' \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Tn Qn Bn H0 \n                        \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn In0 Jn0\n          \u2217 node r m esm0 Vm0\n          \u2217 nodePred_aux \u03b3_gh \u03b3_s m Cm0 Vm0 Tm0 Qm0 \n                          \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0\n          \u2217 nodeShared_aux \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Tm0 Qm0 Bm0 H0 \n                            \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0 Im0 Jm0     \n          ==\u2217\n          \u2203 Qn0',\n            nodePred' \u03b3_gh \u03b3_s r n Cn Vn Tn Qn0' \n                      \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn'\n          \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Qn0' H0\n          \u2217 nodePred' \u03b3_gh \u03b3_s r m Cm0 Vm0 Tm0 Qm0 \n                      \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0\n          \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Qm0 H0.\n  Proof.\n    iIntros \"(%&%&%&%&%&%&%&%&%&%&%&%) (node_n & HnP_aux & HnS_n' & \n                            node_m & HnP_auxm & HnS_auxm)\".\n    rename H into HCm0. rename H1 into Hesm. rename H2 into HBm0. \n    rename H3 into HQm0. rename H4 into HIm0. rename H5 into HJm0. \n    rename H6 into Hesn'. rename H7 into Esn_empty.\n    rename H8 into Out_In_m. rename H9 into Out_Jn_m.\n    rename H10 into HInit. rename H11 into m_neq_r.\n    \n    iDestruct \"HnP_aux\" as \"(HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n    iDestruct \"HnS_auxm\" as \"(HnS_ghm & HnS_fracm & HnS_sim & #HnS_FPm \n                                & HnS_clm & HnS_Bnm & HnS_Hm & HnS_starm)\".\n    iDestruct \"HnS_n'\" as  \n                  \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                      & HnS_cl & HnS_oc & HnS_Bn & HnS_H & HnS_star & H\u03c6)\".\n\n    iDestruct \"HnS_si\" as \"(HIn & HJn & Domm_In0 & Domm_Jn0)\".\n    iDestruct \"HnS_sim\" as \"(HIm & HJm & Domm_Im0 & Domm_Jm0)\".\n    iDestruct \"Domm_In0\" as %Domm_In0.\n    iDestruct \"Domm_Im0\" as %Domm_Im0.\n    iDestruct \"Domm_Jn0\" as %Domm_Jn0.\n    iDestruct \"Domm_Jm0\" as %Domm_Jm0.\n        \n    set (Sr := KS \u2229 (esn' !!! m \u2229 inset K Jn0 n)).\n    set (Sr_map := map_restriction Sr \u2205).\n    set (Sr_mset := map_subset Sr \u2205).\n    set (Sb := KS \u2229 (Sr \u2216 dom (gset K) Tn)).\n    set (Sb_map := map_restriction Sb \u2205). \n    set (Qn0' := gmap_insert_map Qn Sr_map).\n    set (Bn0' := gmap_insert_map Bn Sb_map).\n    set (In0' := outflow_insert_set In0 m Sr_mset).\n    set (Im0' := inflow_insert_set Im0 m Sr_mset). \n    set (Jn0' := outflow_insert_set Jn0 m Sr).\n    set (Jm0' := inflow_insert_set Jm0 m Sr).\n\n    iMod ((frac_update \u03b3_en \u03b3_cn \u03b3_qn esn Tn Qn esn' Tn Qn0') \n         with \"[$HnP_frac $HnS_frac]\") as \"(HnP_frac & HnS_frac)\".\n\n    iPoseProof ((node_es_disjoint r n) with \"[$node_n]\") as \"%\".\n    rename H into Disj_esn'.                        \n\n    iAssert (closed \u03b3_f esn')%I with \"[HnS_cl]\" as \"HnS_cl\".\n    { unfold closed. iIntros (n')\"%\". rename H into Hn'.\n      destruct (decide (n' = m)).\n      + subst n'; try done.\n      + rewrite Hesn' in Hn'.\n        rewrite lookup_total_insert_ne in Hn'; try done.\n        iApply \"HnS_cl\". by iPureIntro. }\n\n    assert (\u2200 k, k \u2208 Sr \u2192 (\u2200 n', k \u2209 esn !!! n')) as Esn_not.\n    { intros k Hk. subst Sr. \n      rewrite !elem_of_intersection in Hk*; intros Hk.\n      destruct Hk as [_ [Hk _]].\n      intros n'. destruct (decide (k \u2208 esn !!! n')); try done.\n      destruct (decide (n' = m)).\n      - subst n'. clear -e Esn_empty. set_solver.\n      - assert (k \u2208 esn' !!! n') as H'. \n        rewrite Hesn'. rewrite lookup_total_insert_ne; try done.\n        pose proof Disj_esn' n' m n0 as H''.\n        clear -H'' H' Hk. set_solver.  } \n\n    iAssert (\u231c\u03c61 esn Qn\u231d)%I as \"%\".\n    { by iDestruct \"H\u03c6\" as \"(%&_)\". }\n    rename H into H\u03c61.\n\n    iAssert (\u231c\u2200 k, k \u2208 Sb \u2192 Bn !!! k = 0\u231d)%I as %HSb.\n    { iDestruct \"HnS_Bn\" as %HBn.\n      iPureIntro. intros k Hk. subst Sb. \n      rewrite elem_of_intersection in Hk *; intros Hk.\n      destruct Hk as [_ Hk].\n      rewrite elem_of_difference in Hk *; intros Hk.\n      destruct Hk as [Hk1 Hk2].\n      rewrite not_elem_of_dom in Hk2*; intros Hk2.\n      pose proof (Esn_not k Hk1) as Hk'.\n      subst Sr.  rewrite elem_of_intersection in Hk1*; intros Hk1.\n      destruct Hk1 as [H' H'']. apply HBn in Hk2.\n      apply H\u03c61 in Hk'. rewrite lookup_total_alt.\n      rewrite Hk2 Hk'; by simpl. try done.\n      try done. try done. }\n\n    assert (dom (gset K) Sb_map = Sb) as Domm_Sbmap.\n    { subst Sb_map. by rewrite map_restriction_dom. }\n\n    iAssert (\u231c\u2200 k, Bn !!! k \u2264 Bn0' !!! k\u231d)%I as \"%\".\n    { iPureIntro. intros k.\n      destruct (decide (k \u2208 Sb)).\n      - rewrite HSb; try done. lia. \n      - subst Bn0'. rewrite !lookup_total_alt. \n        rewrite gmap_lookup_insert_map_ne. done.\n        by rewrite Domm_Sbmap.  }\n    rename H into Bn_le_Bn0'.\n\n    iPoseProof((maxnat_set_update \u03b3_cirn KS Bn Bn0') \n                    with \"[] [$HnS_star]\") as \">HnS_star\".\n    { iPureIntro; intros k Hk; apply Bn_le_Bn0'. }\n\n    assert (domm Jm0' = {[m]}) as Domm_Jm0'.\n    { pose proof (flowint_inflow_insert_set_dom Jm0 m Sr Jm0') as H'.\n      subst Jm0'. rewrite H'. clear -Domm_Jm0; set_solver.\n      done. }\n          \n    assert (domm Im0' = {[m]}) as Domm_Im0'.\n    { pose proof (flowint_inflow_insert_set_dom Im0 m Sr_mset Im0') as H'.\n      subst Im0'. rewrite H'. clear -Domm_Im0; set_solver.\n      done. }         \n\n    iAssert (own \u03b3_J (\u25ef Jn0') \u2217 own \u03b3_J (\u25ef Jm0'))%I \n            with \"[HJn HJm]\" as \"(HJn & HJm)\".\n    { iCombine \"HJn HJm\" as \"HJnm\".\n      assert (Jn0' = outflow_insert_set Jn0 m Sr) \n              as HJn0'. done.\n      assert (Jm0' = inflow_insert_set Jm0 m Sr)\n              as HJm0'. done. \n      iPoseProof (own_valid with \"[$HJnm]\") as \"%\".\n      rename H into Valid_Jnm. \n      rewrite auth_frag_valid in Valid_Jnm*; intros Valid_Jnm.\n      assert (m \u2208 domm Jm0) by (clear -Domm_Jm0; set_solver).\n      assert (domm Jn0 \u2260 \u2205) by (clear -Domm_Jn0; set_solver).\n      pose proof (flowint_insert_eq Jn0 Jn0' Jm0 Jm0' \n              m Sr H H1 HJn0' HJm0' Valid_Jnm) as HJnm0'.\n      iEval (rewrite HJnm0') in \"HJnm\".\n      iEval (rewrite auth_frag_op) in \"HJnm\".\n      iDestruct \"HJnm\" as \"(?&?)\". iFrame. }\n\n    iAssert (own \u03b3_I (\u25ef In0') \u2217 own \u03b3_I (\u25ef Im0'))%I \n            with \"[HIn HIm]\" as \"(HIn & HIm)\".\n    { iCombine \"HIn HIm\" as \"HInm\".\n      assert (In0' = outflow_insert_set In0 m Sr_mset) \n              as HIn0'. done.\n      assert (Im0' = inflow_insert_set Im0 m Sr_mset)\n              as HIm0'. done.         \n      iPoseProof (own_valid with \"[$HInm]\") as \"%\".\n      rename H into Valid_Inm. \n      rewrite auth_frag_valid in Valid_Inm*; intros Valid_Inm.\n      assert (m \u2208 domm Im0) by (clear -Domm_Im0; set_solver).\n      assert (domm In0 \u2260 \u2205) by (clear -Domm_In0; set_solver).\n      pose proof (flowint_insert_eq In0 In0' Im0 Im0' \n             m Sr_mset H H1 HIn0' HIm0' Valid_Inm) as HInm0'.\n      iEval (rewrite HInm0') in \"HInm\".\n      iEval (rewrite auth_frag_op) in \"HInm\".\n      iDestruct \"HInm\" as \"(?&?)\". iFrame. }\n\n \n    assert (dom (gset K) Sr_map = Sr) as Domm_Srmap.\n    { subst Sr_map. by rewrite map_restriction_dom. }\n\n\n    assert (\u2200 k, k \u2208 Sr \u2192 Qn0' !! k = Some 0) as Lookup_Qn0'.\n    { intros k Hk. subst Qn0'. rewrite gmap_lookup_insert_map.\n      subst Sr_map. rewrite lookup_map_restriction; try done.\n      by rewrite Domm_Srmap. }\n\n    assert (\u2200 k, k \u2209 Sr \u2192 Qn0' !! k = Qn !! k) as Lookup_Qn0'_ne.\n    { intros k Hk. subst Qn0'. \n      rewrite gmap_lookup_insert_map_ne; try done.\n      by rewrite Domm_Srmap. }\n\n    assert (\u2200 k, k \u2208 Sb \u2192 Bn0' !! k = Some 0) as Lookup_Bn0'.\n    { intros k Hk. subst Bn0'. rewrite gmap_lookup_insert_map.\n      subst Sb_map. rewrite lookup_map_restriction; try done.\n      by rewrite Domm_Sbmap. }\n\n    assert (\u2200 k, k \u2209 Sb \u2192 Bn0' !! k = Bn !! k) as Lookup_Bn0'_ne.\n    { intros k Hk. subst Bn0'. \n      rewrite gmap_lookup_insert_map_ne; try done.\n      by rewrite Domm_Sbmap. }\n        \n    assert (\u2200 k t, (k, t) \u2208 Sr_mset \u2194 k \u2208 Sr \u2227 t = 0) as HSr_mset.\n    { intros k t. subst Sr_mset. apply map_subset_member. }      \n\n        \n    iDestruct \"HnS_oc\" as \"(%&%&%)\".\n    rename H into OC1. rename H1 into OC2. rename H2 into OC3.\n\n    iAssert (outflow_constraints n In0' Jn0' esn' Qn0')%I as \"HnS_oc\".\n    { iPureIntro. split; last split; try done.\n      - intros n' k t HKS. destruct (decide (n' = m)).\n        + subst n'. assert (outset KT In0' m = Sr_mset) as Hout.\n          { assert (outset KT In0 m = \u2205).\n            { unfold outset. rewrite Out_In_m. \n              unfold ccmunit, ccm_unit. unfold lift_unit.\n              unfold nzmap_unit, dom_ms, dom, nzmap_dom.\n              simpl. apply leibniz_equiv. by rewrite dom_empty. }\n            assert (In0' = outflow_insert_set In0 m Sr_mset) as H' by done.  \n            pose proof (outflow_insert_set_outset In0 m Sr_mset In0' H').\n            rewrite H in H1. clear -H1; set_solver. }\n          rewrite Hout. split.\n          * intros H'. apply HSr_mset in H'. \n            destruct H' as [H1' H2'].\n            split. subst Sr. clear -H1'. set_solver.\n            rewrite (Lookup_Qn0' k H1').\n            by rewrite H2'.\n          * intros [Hkt1 Hkt2].\n            destruct (decide (k \u2208 Sr)).\n            ** rewrite (Lookup_Qn0' k e) in Hkt2.\n               inversion Hkt2. rewrite HSr_mset.\n               split; try done. \n            ** assert (\u2200 n', k \u2209 esn !!! n') as Hnot.\n               { intros n'. destruct (decide (n' = m)).\n                 subst n'. rewrite Esn_empty. clear; set_solver.\n                 destruct (decide (k \u2208 esn !!! n')); try done.\n                 assert (k \u2208 esn' !!! n') as H'. rewrite Hesn'. \n                 rewrite lookup_total_insert_ne; try done.\n                 pose proof Disj_esn' n' m n1 as Disj_esn'.\n                 clear -Disj_esn' Hkt1 H'. set_solver. }\n               rewrite (Lookup_Qn0'_ne k n0) in Hkt2.   \n               pose proof H\u03c61 k HKS Hnot as H'. rewrite H' in Hkt2.\n               done.\n        + rewrite Hesn'. rewrite lookup_total_insert_ne; try done.\n          assert (outset KT In0' n' = outset KT In0 n') as Hout.\n          { assert (In0' = outflow_insert_set In0 m Sr_mset) as H' by done.  \n            by pose proof (outflow_insert_set_outset_ne In0 m \n                                            Sr_mset In0' n' n0 H'). }\n            rewrite Hout. split.\n          * destruct (decide (k \u2208 Sr)).\n            ** intros H'. apply OC1 in H'.\n               destruct H' as [H' _].\n               pose proof Esn_not k e n' as H''.\n               clear -H' H''. set_solver. done.\n            ** rewrite (Lookup_Qn0'_ne k n1). apply OC1. done.   \n          * intros [Hkt1 Hkt2]. destruct (decide (k \u2208 Sr)).\n            ** pose proof Esn_not k e n' as H''.\n               clear -Hkt1 H''. set_solver.\n            ** rewrite (Lookup_Qn0'_ne k n1) in Hkt2.\n               apply OC1; try done.   \n      - intros n' k HKS. assert (inset K Jn0' n = inset K Jn0 n) as Hin.\n        { try done. } rewrite Hin. destruct (decide (n' = m)).\n        + subst n'. assert (outset K Jn0' m = Sr) as Hout.\n          { assert (outset K Jn0 m = \u2205).\n            { unfold outset. rewrite Out_Jn_m. \n              unfold ccmunit, ccm_unit. unfold lift_unit.\n              unfold nzmap_unit. unfold dom_ms, dom, nzmap_dom.\n              simpl. apply leibniz_equiv. by rewrite dom_empty. }  \n            assert (Jn0' = outflow_insert_set Jn0 m Sr) as H' by done.  \n            pose proof (outflow_insert_set_outset Jn0 m Sr Jn0' H').\n            rewrite H in H1. clear -H1; set_solver. } rewrite Hout. \n          subst Sr.  rewrite !elem_of_intersection.\n          split; try done. intros [H' [H'' H''']]; split; try done.\n        + assert (outset K Jn0' n' = outset K Jn0 n') as Hout.\n          { assert (Jn0' = outflow_insert_set Jn0 m Sr) as H' by done.  \n            by pose proof (outflow_insert_set_outset_ne Jn0 m Sr \n                      Jn0' n' n0 H'). } rewrite Hout. rewrite Hesn'. \n          rewrite lookup_total_insert_ne; try done.\n          by pose proof OC2 n' k HKS.\n      - intros n' kt. destruct (decide (n' = m)).\n        + subst n'. subst In0'.\n          destruct (decide (kt \u2208 Sr_mset)).\n          * unfold out, out_map. unfold outflow_insert_set.\n            unfold outflow_map_set. simpl.\n            rewrite nzmap_lookup_total_insert.\n            rewrite nzmap_lookup_total_map_set.\n            rewrite Out_In_m. unfold ccmunit, ccm_unit.\n            simpl. unfold lift_unit. rewrite nzmap_lookup_empty.\n            unfold ccmunit, ccm_unit. simpl. lia. done.\n          * unfold out, out_map. unfold outflow_insert_set.\n            unfold outflow_map_set. simpl.\n            rewrite nzmap_lookup_total_insert.\n            rewrite nzmap_lookup_total_map_set_ne.\n            rewrite Out_In_m. unfold ccmunit, ccm_unit.\n            simpl. unfold lift_unit. rewrite nzmap_lookup_empty.\n            unfold ccmunit, ccm_unit. simpl. unfold nat_unit. lia. done.\n        + subst In0'. unfold outflow_insert_set.\n          unfold out at 1, out_map at 1; simpl.\n          rewrite nzmap_lookup_total_insert_ne; try done.\n          pose proof OC3 n' kt as H'. by unfold out in H'.  }\n       \n    iAssert (outflow_constraints m Im0' Jm0' esm0 Qm0)%I as \"HnS_ocm\".\n    { iPureIntro. split; last split.\n      - intros n' k t HKS. split.\n        + unfold outset, dom_ms. \n          rewrite nzmap_elem_of_dom_total. unfold out, out_map. \n          subst Im0. simpl. rewrite nzmap_lookup_empty. \n          unfold ccmunit, ccm_unit. simpl.\n          unfold lift_unit.\n          rewrite nzmap_lookup_empty.\n          unfold ccmunit, ccm_unit. simpl. done.\n        + subst esm0. rewrite /(\u2205 !!! n'). \n          unfold map_lookup_total. rewrite lookup_empty.\n          simpl. clear; set_solver.\n      - unfold outflow_constraint_J. \n        intros n' k. unfold outset.\n        assert (out Jm0' n' = out Jm0 n') as Hout.\n        { assert (Jm0' = inflow_insert_set Jm0 m Sr) as H' by done.  \n          by pose proof (inflow_insert_set_out_eq Jm0 m Sr Jm0' n' H'). }\n        rewrite Hout. split.\n        + unfold in_outset, dom_ms. \n          rewrite nzmap_elem_of_dom_total. unfold out, out_map. \n          subst Jm0. simpl. rewrite nzmap_lookup_empty. \n          unfold ccmunit, ccm_unit. simpl.\n          unfold lift_unit.\n          rewrite nzmap_lookup_empty.\n          unfold ccmunit, ccm_unit. simpl. done.\n        + subst esm0. rewrite /(\u2205 !!! n'). \n          unfold map_lookup_total. rewrite lookup_empty.\n          simpl. clear; set_solver.\n      - intros n' kt. unfold out, out_map; subst Im0; simpl.\n        rewrite nzmap_lookup_empty. unfold ccmunit, ccm_unit.\n        simpl. unfold lift_unit. rewrite nzmap_lookup_empty.\n        unfold ccmunit, ccm_unit; simpl. unfold nat_unit. lia. }\n\n    iAssert (\u231ccontents_in_reach Bn0' Tn Qn0'\u231d)%I with \"[HnS_Bn]\" as \"HnS_Bn\".\n    { iDestruct \"HnS_Bn\" as %HBn. iPureIntro.\n      intros k t HKS. destruct (decide (k \u2208 Sr)).\n      + split.\n        * intros HCn.\n          assert (is_Some(Tn !! k)). by exists t; try done.\n          rewrite <-elem_of_dom in H.\n          assert (k \u2209 Sb) as Hk.\n          { destruct (decide (k \u2208 Sb)); try done.\n            subst Sb. rewrite elem_of_intersection in e0*; intros e0.\n            destruct e0 as [_ e0].\n            clear -e0 H. set_solver. }\n          rewrite (Lookup_Bn0'_ne k Hk).\n          by apply HBn.\n        * intros HCn. rewrite <-not_elem_of_dom in HCn.\n          assert (k \u2208 Sb) as Hk.\n          { subst Sb. clear -e HCn HKS. set_solver. }\n          rewrite (Lookup_Bn0' k Hk).\n          rewrite (Lookup_Qn0' k e).\n          done.\n      + assert (k \u2209 Sb) as Hk.\n        { destruct (decide (k \u2208 Sb)); try done.\n          subst Sb. rewrite elem_of_intersection in e*; intros e.\n          destruct e as [_ e]. clear -e n0. set_solver. }\n        rewrite (Lookup_Bn0'_ne k Hk).\n        rewrite (Lookup_Qn0'_ne k n0).\n        apply HBn. done. }\n\n    iAssert (\u231c\u03c61 esn' Qn0'\u231d \u2217 \u231c\u03c62 n Bn0' In0'\u231d \u2217 \u231c\u03c63 Bn0' Qn0'\u231d \n              \u2217 \u231c\u03c64 n Bn0' Jn0'\u231d \u2217 \u231c\u03c65 n Jn0'\u231d  \n              \u2217 \u231c\u03c66 n esn' Jn0' Qn0'\u231d \u2217 \u231c\u03c67 n In0'\u231d)%I \n            with \"[H\u03c6]\" as \"H\u03c6\".\n    { iDestruct \"H\u03c6\" as \"(%&%&%&%&%&%&%)\".         \n      clear H. rename H1 into H\u03c62. \n      rename H2 into H\u03c63. rename H3 into H\u03c64.\n      rename H4 into H\u03c65. rename H5 into H\u03c66.\n      rename H6 into H\u03c67.\n      iPureIntro. split; last split; last split; \n      last split; last split; last split.\n      - intros k HKS Hnot. destruct (decide (k \u2208 Sr)). \n        + subst Sr. rewrite !elem_of_intersection in e*; intros e. \n          destruct e as [_ [e _]]. pose proof Hnot m as Hnot. \n          clear -Hnot e. set_solver.  \n        + rewrite (Lookup_Qn0'_ne k n0). apply H\u03c61. done. \n          intros n'. destruct (decide (n' = m)).\n          * subst n'. rewrite Esn_empty.\n            clear; set_solver.\n          * pose proof Hnot n' as Hnot.\n            rewrite Hesn' in Hnot.\n            rewrite lookup_total_insert_ne in Hnot; try done.\n      - intros k t HKS. assert (inset KT In0' n = inset KT In0 n) as Hin. \n        { assert (In0' = outflow_insert_set In0 m Sr_mset) by done.\n          by pose proof (outflow_insert_set_inset In0 m Sr_mset In0' n H). }\n        rewrite Hin. destruct (decide (k \u2208 Sb)). \n        + intros H'. apply H\u03c62 in H'. rewrite lookup_total_alt.\n          rewrite (Lookup_Bn0' k e). simpl.\n          by rewrite (HSb k e) in H'. done.\n        + rewrite lookup_total_alt. rewrite (Lookup_Bn0'_ne k n0).\n          rewrite <-lookup_total_alt. apply H\u03c62. done.\n      - intros k. destruct (decide (k \u2208 Sb)).\n        + destruct (decide (k \u2208 Sr)).\n          * rewrite !lookup_total_alt. \n            rewrite (Lookup_Bn0' k e).\n            rewrite (Lookup_Qn0' k e0).\n            by simpl.\n          * subst Sb Sr; clear -e n0; set_solver.\n        + destruct (decide (k \u2208 Sr)).\n          * rewrite lookup_total_alt.\n            rewrite (Lookup_Qn0' k e).\n            simpl. lia.\n          * rewrite !lookup_total_alt. \n            rewrite (Lookup_Bn0'_ne k n0).\n            rewrite (Lookup_Qn0'_ne k n1).\n            rewrite <-!lookup_total_alt.\n            by apply H\u03c63.\n      - intros k HKS. assert (inset K Jn0' n = inset K Jn0 n) as Hin.\n        { assert (Jn0' = outflow_insert_set Jn0 m Sr) by done.\n          by pose proof (outflow_insert_set_inset Jn0 m Sr Jn0' n H). }\n        rewrite Hin.\n        destruct (decide (k \u2208 Sb)).\n        + right. subst Sb. subst Sr. clear -e. set_solver.\n        + rewrite (Lookup_Bn0'_ne k n0).\n          by pose proof H\u03c64 k HKS.\n      - try done.\n      - intros k HKS. intros [H' H''].\n        destruct H' as [n' H'].\n        destruct (decide (n' = m)).\n        + subst n'. rewrite elem_of_dom. \n          assert (k \u2208 Sr).\n          { subst Sr. rewrite !elem_of_intersection.\n            split; try done. }\n          rewrite (Lookup_Qn0' k H).\n          by exists 0.\n        + assert (inset K Jn0' n = inset K Jn0 n) as Hin.\n          { assert (Jn0' = outflow_insert_set Jn0 m Sr). done. \n            by pose proof (outflow_insert_set_inset Jn0 m Sr Jn0' n' H). } \n          rewrite Hesn' in H'.\n          rewrite lookup_total_insert_ne in H'; try done.\n          destruct (decide (k \u2208 Sr)).\n          * pose proof Lookup_Qn0' k e as H'''.\n            rewrite elem_of_dom. rewrite H'''.\n            by exists 0.\n          * rewrite elem_of_dom. rewrite (Lookup_Qn0'_ne k n1).\n            rewrite <-elem_of_dom. apply H\u03c66. done.\n            split; try done. by exists n'.\n      - try done. }\n          \n    iAssert (\u231c\u03c61 esm0 Qm0\u231d \u2217 \u231c\u03c62 m Bm0 Im0'\u231d \u2217 \u231c\u03c63 Bm0 Qm0\u231d \n              \u2217 \u231c\u03c64 m Bm0 Jm0'\u231d \u2217 \u231c\u03c65 m Jm0'\u231d   \n              \u2217 \u231c\u03c66 m esm0 Jm0' Qm0\u231d \u2217 \u231c\u03c67 m Im0'\u231d)%I\n                as \"H\u03c6m\".\n    { iPureIntro. subst esm0 Cm0 Bm0 Qm0.\n      repeat split; try done.\n      - unfold \u03c62.\n        assert (inset KT Im0' m = Sr_mset) as Hin.\n        { assert (inset KT Im0 m = \u2205) as Hin.\n          subst Im0. unfold inset, dom_ms, inf; simpl.\n          rewrite lookup_insert. simpl.\n          unfold dom, nzmap_dom. apply leibniz_equiv.\n          by rewrite dom_empty.\n          assert (Im0' = inflow_insert_set Im0 m Sr_mset). done.\n          pose proof (inflow_insert_set_inset Im0 m Sr_mset Im0' H).\n          rewrite H1; rewrite Hin; clear; set_solver. } \n        rewrite Hin. intros k t HKS Hkt.\n        apply HSr_mset in Hkt.\n        destruct Hkt as [_ H'].\n        rewrite lookup_total_alt; rewrite lookup_empty; by simpl.\n      - intros k HKS. rewrite /(\u2205 !!! k).\n        unfold map_lookup_total.\n        rewrite lookup_empty. by simpl.  \n      - unfold \u03c63. intros k HKS; left.\n        rewrite /(\u2205 !!! k). unfold map_lookup_total.\n        rewrite lookup_empty. by simpl.\n      - unfold \u03c65. intros k.\n        subst Jm0; unfold inf, inf_map; simpl.\n        rewrite lookup_insert. simpl.\n        unfold inf, inf_map; simpl.\n        rewrite lookup_insert. simpl.\n        destruct (decide (k \u2208 Sr)). \n        + rewrite nzmap_lookup_total_map_set.\n          rewrite nzmap_lookup_empty. \n          unfold ccmunit, ccm_unit; simpl.\n          lia. done.\n        + rewrite nzmap_lookup_total_map_set_ne.\n          rewrite nzmap_lookup_empty. \n          unfold ccmunit, ccm_unit; simpl.\n          unfold nat_unit.\n          lia. done.\n      - intros k HKS [Hkt1 Hkt2].\n        destruct Hkt1 as [n' H'].\n        clear -H'. set_solver.\n      - intros kt. subst Im0'. unfold inflow_insert_set, inflow_map_set.\n        unfold inf; simpl. rewrite !lookup_insert. simpl.\n        destruct (decide (kt \u2208 Sr_mset)).\n        + rewrite nzmap_lookup_total_map_set; try done.\n          rewrite HIm0. unfold inf_map; simpl.\n          rewrite lookup_insert. simpl.\n          rewrite nzmap_lookup_empty.\n          unfold ccmunit, ccm_unit; simpl; lia.\n        + rewrite nzmap_lookup_total_map_set_ne; try done.\n          rewrite HIm0. unfold inf_map; simpl.\n          rewrite lookup_insert. simpl.\n          rewrite nzmap_lookup_empty.\n          unfold ccmunit, ccm_unit; simpl. unfold nat_unit; lia. }\n      \n\n    iModIntro. iExists Qn0'.\n    iSplitL \"node_n HnP_gh HnP_C HnP_frac HnP_cts\". { iFrame. }\n    iSplitL \"HnS_gh HnS_FP HnS_H HnS_frac HnS_cl HnS_Bn HnS_star HJn HIn H\u03c6\".\n    { iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn', Tn, Bn0', In0'. iExists Jn0'.\n      iFrame. iFrame \"HnS_oc\". iSplitR. by iPureIntro.\n      destruct (decide (n = r)); try done.\n      - subst n. iDestruct \"HnS_H\" as \"(%&%)\".\n        rename H into Bn_eq_H0. rename H1 into Infz_In0. \n        iPureIntro. repeat split; try done.\n        intros k.\n        destruct (decide (k \u2208 Sb)).\n        + pose proof (Lookup_Bn0' k e) as H'.\n          rewrite lookup_lookup_total in H'.\n          inversion H'. clear H'. rewrite H1. clear H1.\n          pose proof Bn_eq_H0 k as H'.\n          rewrite <-H'. \n          pose proof (HSb k e) as H''.\n          by rewrite H''.\n          pose proof (Lookup_Bn0' k e) as H'.\n          rewrite H'; by exists 0. \n        + pose proof (Lookup_Bn0'_ne k n) as H'.\n          rewrite lookup_total_alt.\n          rewrite H'.\n          pose proof (Bn_eq_H0 k) as Bn_eq_H0.\n          by rewrite lookup_total_alt in Bn_eq_H0. }\n    iSplitL \"node_m HnP_auxm\". { iFrame. }\n    iExists \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm, esm0, Tm0, Bm0, Im0'. \n    iExists Jm0'.\n    iFrame \"\u2217#\". iSplitR. by iPureIntro.\n    destruct (decide (m = r)); try done.\n  Qed.          \n  \n  Lemma mergeContents_ghost_update \n               (\u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh \u03b3_en \u03b3_cn \u03b3_qn \u03b3_em \u03b3_cm \u03b3_qm: gname) \n               (r n m: Node)  (t': T) (H: gset KVT) h\u03b3 I J (K1: gset K)\n               (Cn Cm: gmap K (V*T))\n               (Vn Vn' Vm Vm': gmap K V) \n               (Tn Qn0' Tm Qm: gmap K T)\n               (esm esn' : esT) \n               \u03b3_cirn \u03b3_cirm :\n\n          \u231cm \u2260 r\u231d\n        \u2217 \u231cVn' = mergeLeft K1 Vn (esn' !!! m) Vm\u231d\n        \u2217 \u231cVm' = mergeRight K1 Vn (esn' !!! m) Vm\u231d\n        -\u2217\n          node r n esn' Vn' \u2217 nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn0' \n                                          \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn'\n        \u2217 node r m esm Vm' \u2217 nodePred_aux \u03b3_gh \u03b3_s m Cm Vm Tm Qm \n                                          \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm\n        \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Qn0' H\n        \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Qm H\n        \u2217 own \u03b3_s (\u25cf H)\n        \u2217 \u231cHClock t' H\u231d             \n        \u2217 global_state \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r h\u03b3 I J\n        ==\u2217\n          \u2203 Cn' Cm' Qn', nodePred \u03b3_gh \u03b3_s r n Cn' Qn'\n        \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Qn' H \n        \u2217 nodePred \u03b3_gh \u03b3_s r m Cm' Qm\n        \u2217 nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Qm H\n        \u2217 own \u03b3_s (\u25cf H)\n        \u2217 global_state \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r h\u03b3 I J.\n  Proof.\n    iIntros \"(%&%&%)\". rename H0 into m_neq_r.\n    rename H1 into Hvn'. rename H2 into Hvm'.\n\n    iIntros \"(node_n & HnP_aux & node_m & HnP_auxm & HnS_n & HnS_m \n                                        & HH & HClock & Hglob)\".\n    iDestruct \"HnP_aux\" as \"(#HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n    iDestruct \"HnP_auxm\" as \"(#HnP_ghm & HnP_fracm & HnP_Cm & HnP_ctsm)\".\n    iDestruct \"HnS_n\" as (\u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn' es' Tn' Bn In Jn) \"HnS_n'\".\n    iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_n']\")\n           as \"(HnP_frac & HnS_n' &%&%&_)\". subst es' Tn'.   \n    iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                          & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & H\u03c6)\".\n\n    iDestruct \"HnS_m\" as (\u03b3_em' \u03b3_cm' \u03b3_qm' \u03b3_cirm' es' Tm' Bm Im Jm) \"HnS_m'\".\n    iPoseProof (nodePred_nodeShared_eq with \"[$HnP_ghm] [$HnP_fracm] [$HnS_m']\")\n           as \"(HnP_fracm & HnS_m' &%&%&_)\". subst es' Tm'.   \n    iDestruct \"HnS_m'\" as \"(HnS_ghm & HnS_fracm & HnS_sim & HnS_FPm \n                      & HnS_clm & HnS_ocm & HnS_Bnm & HnS_Hm  & HnS_starm & H\u03c6m)\".\n    iDestruct \"HClock\" as %HClock.\n    \n    set (S := KS \u2229 K1 \u2229 (dom (gset K) Vn) \u2229 (esn' !!! m)).\n\n    set (Tn' := mergeLeft K1 Tn (esn' !!! m) Tm).\n    set (Cn' := mergeLeft K1 Cn (esn' !!! m) Cm).\n    set (Tm' := mergeRight K1 Tn (esn' !!! m) Tm).\n    set (Cm' := mergeRight K1 Cn (esn' !!! m) Cm).\n\n    set (S_map := map_restriction S Tn).\n    set (Qn_old := map_subset S Qn0').\n    set (Qn_new := map_subset S Tn).\n    set (Qn' := gmap_insert_map Qn0' S_map).\n    set (Bm' := gmap_insert_map Bm S_map).\n    set (In_temp := outflow_delete_set In m Qn_old).\n    set (In' := outflow_insert_set In_temp m Qn_new).\n    set (Im_temp := inflow_delete_set Im m Qn_old).\n    set (Im' := inflow_insert_set Im_temp m Qn_new).\n\n    iPoseProof ((node_es_disjoint r n) with \"[$node_n]\") as \"%\".\n    rename H0 into Disj_esn'.                        \n\n    iMod ((frac_update \u03b3_en \u03b3_cn \u03b3_qn esn' Tn Qn0' esn' Tn' Qn') \n         with \"[$HnP_frac $HnS_frac]\") as \"(HnP_frac & HnS_frac)\".\n\n    iMod ((frac_update \u03b3_em \u03b3_cm \u03b3_qm esm Tm Qm esm Tm' Qm) \n         with \"[$HnP_fracm $HnS_fracm]\") as \"(HnP_fracm & HnS_fracm)\".\n\n    assert (S \u2286 esn' !!! m) as S_sub_es.\n    { subst S; clear; set_solver. }\n\n    assert (\u2200 k t, (k,t) \u2208 Qn_new \u2194 k \u2208 S \u2227 t = Tn !!! k) as HQn_new.\n    { intros k t. subst Qn_new. apply map_subset_member. } \n    assert (\u2200 k t, (k,t) \u2208 Qn_old \u2194 k \u2208 S \u2227 t = Qn0' !!! k) as HQn_old.\n    { intros k t. subst Qn_old. apply map_subset_member. } \n    assert (dom (gset K) S_map = S) as Dom_Smap.\n    { subst S_map. apply map_restriction_dom. }\n    \n    iAssert (contents_proj Cn Vn Tn) with \"[$HnP_cts]\" as %HnP_cts.\n    \n    destruct HnP_cts as [dom_Cn_Vn [dom_Cn_Tn HCn]].\n    assert (dom (gset K) Vn = dom (gset K) Tn) as dom_Vn_Tn.\n    { rewrite <-dom_Cn_Vn. by rewrite dom_Cn_Tn. }\n\n    assert (\u2200 k, k \u2208 S \u2192 S_map !! k = Some(Tn !!! k)) as Lookup_Smap.\n    { intros k Hk. subst S_map. by rewrite lookup_map_restriction. }\n    assert (\u2200 k, k \u2208 S \u2192 Qn' !! k = Tn !! k) as Lookup_Qn'.\n    { intros k Hk. subst Qn'. rewrite gmap_lookup_insert_map.\n      rewrite (Lookup_Smap k Hk).\n      assert (k \u2208 dom (gset K) Tn) as H'.\n      { subst S. rewrite <-dom_Cn_Tn. rewrite dom_Cn_Vn. \n        clear -Hk. set_solver. }\n      rewrite elem_of_dom in H'*; intros H'. destruct H' as [t H'].\n      rewrite lookup_total_alt. rewrite H'; by simpl.\n      by rewrite Dom_Smap. }\n    assert (\u2200 k, k \u2209 S \u2192 Qn' !! k = Qn0' !! k) as Lookup_Qn'_ne.\n    { intros k Hk. subst Qn'. rewrite gmap_lookup_insert_map_ne.\n      done. by rewrite Dom_Smap. }\n    assert (\u2200 k t, k \u2209 S \u2192 (k,t) \u2209 Qn_old) as HQn_old_ne.\n    { intros k t Hk. destruct (decide ((k,t) \u2208 Qn_old)); try done. \n      rewrite HQn_old in e*; intros e. destruct e as [e _].\n      clear -e Hk; set_solver. }\n    assert (\u2200 k t, k \u2209 S \u2192 (k,t) \u2209 Qn_new) as HQn_new_ne.\n    { intros k t Hk. destruct (decide ((k,t) \u2208 Qn_new)); try done. \n      rewrite HQn_new in e*; intros e. destruct e as [e _].\n      clear -e Hk; set_solver. }\n        \n    assert (\u2200 k, k \u2208 S \u2192 Tn !! k = Tm' !! k) as Lookup_merge.\n    { intros k Hk.\n      subst Tm'. unfold mergeRight. rewrite !gmap_imerge_prf.\n      unfold f_mergeRight.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Tn) \u2229 esn' !!! m)); try done.\n      clear -Hk n0 dom_Vn_Tn; subst S. rewrite dom_Vn_Tn in Hk; set_solver. }\n\n    iAssert(\u231cS \u2286 KS\u231d)%I as %S_sub_KS.\n    { iPureIntro. subst S. clear; set_solver. }\n    \n    iAssert(\u231cS \u2286 dom (gset K) Tn\u231d)%I as %S_sub_Tn.\n    { iPureIntro. subst S. rewrite dom_Vn_Tn. clear; set_solver. }\n        \n\n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 k \u2208 inset K Jn n\u231d)%I as %S_sub_insetn.\n    { iDestruct \"H\u03c6\" as \"(_&_&_&%&_)\".\n      rename H0 into H\u03c64. \n      iDestruct \"HnS_Bn\" as %HBn. iPureIntro.\n      intros k Hk. \n      pose proof S_sub_KS k Hk as Hk'.\n      pose proof H\u03c64 k Hk' as H\u03c64.\n      destruct H\u03c64 as [H' | H']; try done.\n      unfold contents_in_reach in HBn.\n      apply S_sub_Tn in Hk.\n      rewrite elem_of_dom in Hk*; intros Hk.\n      destruct Hk as [t Hk].\n      pose proof HBn k t Hk' as HBn.\n      apply HBn in Hk. clear -H' Hk. \n      exfalso; rewrite H' in Hk; try done. }\n\n\n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 k \u2208 outset K Jn m\u231d)%I as %Out_Jn_m.\n    { iDestruct \"HnS_oc\" as \"(_&%&_)\". rename H0 into OC2.\n      iPureIntro; intros k Hk. apply OC2.\n      by apply S_sub_KS in Hk.         \n      split; try done. by apply S_sub_es.\n      by apply S_sub_insetn. }\n        \n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 k \u2208 inset K Jm m\u231d)%I as %S_sub_insetm.\n    { iDestruct \"HnS_si\" as \"(_&HJn&_&Domm_Jn)\".\n      iDestruct \"HnS_sim\" as \"(_&HJm&_&Domm_Jm)\".\n      iCombine \"HJn HJm\" as \"HJnm\".\n      iPoseProof (own_valid with \"[$HJnm]\") as \"%\".\n      rename H0 into Valid_Jnm. \n      rewrite auth_frag_valid in Valid_Jnm*; intros Valid_Jnm.\n      iDestruct \"Domm_Jn\" as %Domm_Jn.\n      iDestruct \"Domm_Jm\" as %Domm_Jm. \n      assert (m \u2208 domm Jm) as m_in_Jm. \n      clear -Domm_Jm; set_solver. \n      pose proof intComp_unfold_inf_2 Jn Jm Valid_Jnm m m_in_Jm as H'. \n      unfold ccmop, ccm_op in H'. simpl in H'. unfold lift_op in H'.\n      iPureIntro. rewrite nzmap_eq in H' *; intros H'.\n      intros k Hk. pose proof H' k as H'.\n      unfold inset. rewrite nzmap_elem_of_dom_total.\n      unfold ccmunit, ccm_unit. simpl.\n      unfold nat_unit.\n      rewrite nzmap_lookup_merge in H'.\n      unfold ccmop, ccm_op in H'. simpl in H'.\n      unfold nat_op in H'.\n      assert (1 \u2264 out Jn m !1 k) as Hout.\n      { pose proof Out_Jn_m k Hk as H''.\n        unfold outset in H''.\n        rewrite nzmap_elem_of_dom_total in H'' *; \n        intros H''.\n        unfold ccmunit, ccm_unit in H''.\n        simpl in H''. unfold nat_unit in H''.\n        clear - H''. lia. }\n      assert (1 \u2264 inf Jm m !1 k) as Hin.\n      { clear -H' Hout. \n        assert (\u2200 (x y z: nat), 1 \u2264 y \u2192 x = z + y \u2192 1 \u2264 x) as H''.\n        lia. by pose proof H'' _ _ _ Hout H'. }\n      clear -Hin. lia. }\n\n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 (k, Qn0' !!! k) \u2208 outset KT In m\u231d)%I \n                                            as %Out_In_m.\n    { iDestruct \"HnS_oc\" as \"(%&_)\". \n      iDestruct \"H\u03c6\" as \"(_&_&_&_&_&%&_)\". \n      rename H0 into OC1. rename H1 into H\u03c67.\n      iPureIntro; intros k Hk. apply OC1.\n      by apply S_sub_KS in Hk.\n      split; try done. by apply S_sub_es.\n      pose proof H\u03c67 k as H'.\n      assert (k \u2208 dom (gset K) Qn0') as H''.\n      apply H'. by apply S_sub_KS in Hk. split.\n      exists m; by apply S_sub_es in Hk.\n      by apply S_sub_insetn. \n      rewrite elem_of_dom in H''*; intros H''.\n      destruct H'' as [t H''].\n      rewrite lookup_total_alt; rewrite H''; by simpl. }\n\n\n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 (k, Qn0' !!! k) \u2208 inset KT Im m\u231d)%I as %Ins_Im.\n    { iDestruct \"HnS_si\" as \"(HIn&_&Domm_In&_)\".\n      iDestruct \"HnS_sim\" as \"(HIm&_&Domm_Im&_)\".\n      iCombine \"HIn HIm\" as \"HInm\".\n      iPoseProof (own_valid with \"[$HInm]\") as \"%\".\n      rename H0 into Valid_Inm. \n      rewrite auth_frag_valid in Valid_Inm*; intros Valid_Inm.\n      iDestruct \"Domm_In\" as %Domm_In.\n      iDestruct \"Domm_Im\" as %Domm_Im. \n      assert (m \u2208 domm Im) as m_in_Im. \n      clear -Domm_Im; set_solver. \n      pose proof intComp_unfold_inf_2 In Im Valid_Inm m m_in_Im as H'. \n      unfold ccmop, ccm_op in H'. simpl in H'. unfold lift_op in H'.\n      iPureIntro. rewrite nzmap_eq in H' *; intros H'.\n      intros k Hk. pose proof H' (k, Qn0' !!! k) as H'.\n      unfold inset. rewrite nzmap_elem_of_dom_total.\n      unfold ccmunit, ccm_unit. simpl.\n      unfold nat_unit.\n      rewrite nzmap_lookup_merge in H'.\n      unfold ccmop, ccm_op in H'. simpl in H'.\n      unfold nat_op in H'.\n      assert (1 \u2264 out In m !1 (k, Qn0' !!! k)) as Hout.\n      { pose proof Out_In_m k Hk as H''.\n        unfold outset in H''.\n        rewrite nzmap_elem_of_dom_total in H'' *; \n        intros H''.\n        unfold ccmunit, ccm_unit in H''.\n        simpl in H''. unfold nat_unit in H''.\n        clear - H''. lia. }\n      assert (1 \u2264 inf Im m !1 (k, Qn0' !!! k)) as Hin.\n      { clear -H' Hout. \n        assert (\u2200 (x y z: nat), 1 \u2264 y \u2192 x = z + y \u2192 1 \u2264 x) as H''.\n        lia. by pose proof H'' _ _ _ Hout H'. }\n      clear -Hin. lia. }\n\n    iAssert (\u231c\u2200 k, k \u2208 S \u2192 Bm !!! k = Qn0' !!! k\u231d)%I as %Bm_eq_Qn.\n    { iDestruct \"H\u03c6m\" as \"(_&%&_)\".\n      rename H0 into H\u03c62.\n      iPureIntro. intros k Hk.\n      pose proof Ins_Im k Hk as H'.\n      apply S_sub_KS in Hk.\n      by pose proof H\u03c62 k (Qn0' !!! k) Hk H' as H''. }\n\n    iAssert (\u231c\u2200 k, Bm !!! k \u2264 Bm' !!! k\u231d)%I as \"%\".\n    { iDestruct \"H\u03c6\" as \"(_&_&%&_)\".\n      rename H0 into H\u03c63. \n      iDestruct \"HnS_Bn\" as %HBn. iPureIntro.\n      intros k. subst Bm'.\n      destruct (decide (k \u2208 S)).\n      - pose proof Bm_eq_Qn k e as H'.\n        rewrite H'. rewrite /(gmap_insert_map Bm S_map !!! k).\n        unfold map_lookup_total.\n        rewrite gmap_lookup_insert_map.\n        rewrite (Lookup_Smap k e). simpl.\n        assert (Hk := e).\n        apply S_sub_Tn in Hk.\n        rewrite elem_of_dom in Hk*; intros [t Hk].\n        pose proof HBn k t as [Hc _]. by apply S_sub_KS in e.\n        pose proof Hc Hk as Hc.\n        rewrite lookup_total_alt.\n        rewrite Hk. apply leibniz_equiv_iff in Hc. \n        rewrite <-Hc. rewrite <-lookup_total_alt.\n        apply H\u03c63. by apply S_sub_KS in e. by rewrite Dom_Smap. \n      - rewrite !lookup_total_alt.\n        rewrite gmap_lookup_insert_map_ne.\n        done. by rewrite Dom_Smap. }\n    rename H0 into Bm_le_Bm'.\n\n    iPoseProof((maxnat_set_update \u03b3_cirm KS Bm Bm') \n                    with \"[] [$HnS_starm]\") as \">HnS_starm\".\n    { iPureIntro; intros k Hk; apply Bm_le_Bm'. }\n\n    iDestruct \"Hglob\" as \"(HI & Out_I & HR \n        & Out_J & Inf_J & Hf & H\u03b3 & FP_r & domm_IJ & domm_I\u03b3)\".\n\n    iAssert (\u231cset_of_map Cn \u2286 H\u231d)%I as %Cn_sub_H.\n    { iPoseProof ((auth_own_incl \u03b3_s H _) with \"[$HH $HnP_C]\") as \"%\".\n      rename H0 into H'. by apply gset_included in H'. }\n\n    iAssert (\u231cset_of_map Cm \u2286 H\u231d)%I as %Cm_sub_H.\n    { iPoseProof ((auth_own_incl \u03b3_s H _) with \"[$HH $HnP_Cm]\") as \"%\".\n      rename H0 into H'. by apply gset_included in H'. }\n\n    iAssert (\u231cset_of_map Cn' \u2286 set_of_map Cn\u231d)%I as %Cn'_sub_Cn.\n    { iPureIntro. intros [k [v t]] Hkvt.\n      apply set_of_map_member_rev in Hkvt.\n      apply set_of_map_member. subst Cn'.\n      unfold mergeLeft in Hkvt.\n      rewrite !gmap_imerge_prf in Hkvt.\n      unfold f_mergeLeft in Hkvt.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)); try done. }\n      \n    iAssert (\u231cset_of_map Cn' \u2286 H\u231d)%I as %Cn'_sub_H.\n    { iPureIntro. clear -Cn'_sub_Cn Cn_sub_H.  set_solver. }\n\n    iAssert (\u231cset_of_map Cm' \u2286 set_of_map Cn \u222a set_of_map Cm\u231d)%I as %Cm'_sub_Cn_Cm.\n    { iPureIntro. intros [k [v t]] Hkvt.\n      rewrite elem_of_union.\n      apply set_of_map_member_rev in Hkvt. subst Cm'.\n      unfold mergeRight in Hkvt.\n      rewrite !gmap_imerge_prf in Hkvt.\n      unfold f_mergeRight in Hkvt.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n      - left. by apply set_of_map_member.\n      - right; by apply set_of_map_member. }      \n\n    iAssert (\u231cset_of_map Cm' \u2286 H\u231d)%I as %Cm'_sub_H.\n    { iPureIntro. clear -Cm'_sub_Cn_Cm Cm_sub_H Cn_sub_H.  set_solver. }\n\n    iAssert (\u231c\u2200 k, Tn !!! k \u2264 t'\u231d)%I as %Tn_le_t'.\n    { iPureIntro. \n      intros k. destruct (Tn !! k) as [t |] eqn: Hcn.\n      - assert (is_Some(Tn !! k)) as Hcn'.\n        { rewrite Hcn; by exists t. }\n        apply elem_of_dom in Hcn'.\n        rewrite <-dom_Vn_Tn in Hcn'.\n        apply elem_of_dom in Hcn'.\n        destruct Hcn' as [v Hcn'].\n        assert (H' := conj Hcn' Hcn).\n        apply (HCn k v t) in H'.\n        apply set_of_map_member in H'.\n        apply Cn_sub_H in H'.\n        apply HClock in H'.\n        rewrite lookup_total_alt.\n        rewrite Hcn; simpl. clear -H'. lia.\n      - rewrite lookup_total_alt.\n        rewrite Hcn; simpl. lia. }\n        \n    iMod (own_update \u03b3_s (\u25cf H) \n         (\u25cf H \u22c5 \u25ef (set_of_map Cn' \u22c5 set_of_map Cm')) with \"[$HH]\") as \"HH\".\n    { apply (auth_update_alloc _ (H) (set_of_map Cn' \u22c5 set_of_map Cm')).\n      apply local_update_discrete. intros mc Valid_H1 H1_eq.\n      split; try done. rewrite /(\u03b5 \u22c5? mc) in H1_eq.\n      destruct mc. 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 Cn' \u22c5 set_of_map Cm' \u22c5? Some H).\n      rewrite !gset_op.\n      clear - Cn'_sub_H Cm'_sub_H. set_solver.\n      rewrite /(set_of_map Cn' \u22c5 set_of_map Cm' \u22c5? None).\n      rewrite gset_op.\n      clear - Cn'_sub_H Cm'_sub_H H1_eq. set_solver. }\n         \n    iClear \"HnP_C HnP_Cm\".\n    iDestruct \"HH\" as \"(HH & (HnP_C & HnP_Cm))\".\n        \n    iAssert (global_state \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r h\u03b3 I J)\n      with \"[HI Out_I HR Out_J \n        Inf_J Hf H\u03b3 FP_r domm_IJ domm_I\u03b3]\" as \"Hglob\".\n    { iFrame. }     \n      \n        \n    iDestruct \"HnS_oc\" as \"(%&%&%)\".\n    rename H0 into OC1. rename H1 into OC2. rename H2 into OC3.\n    iAssert (outflow_constraints n In' Jn esn' Qn')%I as \"HnS_oc\".\n    { iPureIntro. split; last split; try done.\n      - intros n' k t HKS. destruct (decide (n' = m)).\n        + subst n'. \n          assert (outset KT In' m = \n                      outset KT In m \u2216 Qn_old \u222a Qn_new) as Outset'.\n          { assert (In_temp = outflow_delete_set In m Qn_old) by done.\n            assert (In' = outflow_insert_set In_temp m Qn_new) by done.\n            assert (\u2200 kt, kt \u2208 Qn_old \u2192 out In m !1 kt \u2264 1).\n            { intros kt Hkt. apply OC3. } \n            pose proof (outflow_insert_set_outset In_temp m Qn_new In' H1).\n            pose proof (outflow_delete_set_outset In m Qn_old In_temp H2 H0).\n            by rewrite H4 in H3. }\n          split.\n          * intros Hout. rewrite Outset' in Hout.\n            rewrite elem_of_union in Hout*; intros Hout.\n            destruct Hout as [Hout | Hout].\n            ** rewrite elem_of_difference in Hout *; intros Hout.\n               destruct Hout as [Hout1 Hout2].\n               apply (OC1 m k t) in Hout1.\n               destruct Hout1 as [H' H''].\n               assert (Ht := H'').\n               apply lookup_total_correct in H''.\n               rewrite <-H'' in Hout2.\n               assert (k \u2209 S) as Hk.\n               { destruct (decide (k \u2208 S)); try done.\n                 assert ((k, Qn0' !!! k) \u2208 Qn_old) as HkQn.\n                 apply (HQn_old k (Qn0' !!! k)). \n                 split; try done. clear -Hout2 HkQn. done. }\n               split; try done. subst Qn'.\n               rewrite gmap_lookup_insert_map_ne.\n               done. by rewrite Dom_Smap. done.\n            ** apply HQn_new in Hout.\n               destruct Hout as [Hout1 Hout2].\n               split. clear -Hout1 S_sub_es. set_solver.\n               subst Qn'. \n               rewrite gmap_lookup_insert_map.\n               rewrite (Lookup_Smap k Hout1).\n               by rewrite Hout2. by rewrite Dom_Smap.\n          * destruct (decide (k \u2208 S)).\n            ** subst Qn'.\n               rewrite gmap_lookup_insert_map; try done.\n               rewrite (Lookup_Smap k e). simpl.\n               intros [H1' H2'].\n               assert (k \u2208 S \u2227 t = Tn !!! k) as H''.\n               split; try done. by inversion H2'.\n               apply (HQn_new k t) in H''.\n               clear -H'' Outset'. set_solver.\n               by rewrite Dom_Smap.\n            ** rewrite (Lookup_Qn'_ne k n0).\n               intros H'. apply OC1 in H'.\n               apply (HQn_old_ne k t) in n0.\n               clear -H' Outset' n0. set_solver. done.\n        + assert (outset KT In' n' = outset KT In n') as Outset'.\n          { assert (In' = outflow_insert_set In_temp m Qn_new) by done.\n            assert (In_temp = outflow_delete_set In m Qn_old) by done.\n            pose proof (outflow_insert_set_outset_ne In_temp m \n                                            Qn_new In' n' n0 H0).\n            pose proof (outflow_delete_set_outset_ne In m  \n                                            Qn_old In_temp n' n0 H1).\n            by rewrite H3 in H2. } rewrite Outset'.\n          split.\n          * intros Hout. apply OC1 in Hout.\n            destruct Hout as [Hout1 Hout2].\n            assert (k \u2209 S) as Hk.\n            { destruct (decide (k \u2208 S)); try done.\n              apply S_sub_es in e.\n              pose proof Disj_esn' n' m n0.\n              clear -H0 e Hout1. set_solver. }\n            rewrite (Lookup_Qn'_ne k Hk).\n            split; try done. done.\n          * intros Hkt.\n            assert (k \u2209 S) as Hk.\n            { destruct Hkt as [Hkt1 Hkt2].\n              destruct (decide (k \u2208 S)); try done.\n              apply S_sub_es in e.\n              pose proof Disj_esn' n' m n0.\n              clear -H0 e Hkt1. set_solver. }\n            rewrite (Lookup_Qn'_ne k Hk) in Hkt.\n            by apply OC1 in Hkt. \n      - unfold outflow_le_1. intros n' kt. \n        destruct (decide (n' = m)).\n        * subst n'. subst In'. unfold out, out_map. \n          unfold outflow_insert_set. simpl.\n          rewrite nzmap_lookup_total_insert.\n          unfold out, out_map.\n          unfold In_temp, outflow_delete_set.\n          simpl. rewrite nzmap_lookup_total_insert.\n          pose proof OC3 m kt as OC3.\n          destruct (decide (kt \u2208 Qn_new)).\n          ** rewrite nzmap_lookup_total_map_set; try done.\n             destruct (decide (kt \u2208 Qn_old)).\n             *** rewrite nzmap_lookup_total_map_set; try done.\n                 clear -OC3. lia.\n             *** rewrite nzmap_lookup_total_map_set_ne; try done.\n                 assert (\u2200 (x: nat), x \u2264 1 \u2192 x = 0 \u2228 x = 1) as Hx.\n                 { lia. } apply Hx in OC3.\n                 destruct OC3 as [OC3 | OC3].\n                 rewrite OC3. lia.\n                 assert (kt \u2208 outset KT In m) as Hkt.\n                 { unfold outset, dom_ms.\n                   rewrite nzmap_elem_of_dom_total.\n                   rewrite OC3. unfold ccmunit, ccm_unit; simpl.\n                   by unfold nat_unit. }\n                 destruct kt as [k t].\n                 apply OC1 in Hkt.\n                 destruct Hkt as [_ H'].\n                 apply lookup_total_correct in H'.\n                 rewrite <-H' in n0.\n                 assert ((k, Qn0' !!! k) \u2208 Qn_old) as H''.\n                 { apply HQn_old. apply HQn_new in e.\n                   destruct e as [e _]. split; try done. }\n                 clear -H'' n0. done. apply HQn_new in e. \n                 destruct e as [e _]. apply S_sub_KS in e. done.\n          ** rewrite nzmap_lookup_total_map_set_ne; try done.\n             destruct (decide (kt \u2208 Qn_old)).\n             *** rewrite nzmap_lookup_total_map_set; try done.\n                 clear -OC3. lia.\n             *** rewrite nzmap_lookup_total_map_set_ne; try done.\n        * subst In'. unfold out, out_map. \n          unfold outflow_insert_set. simpl.\n          rewrite nzmap_lookup_total_insert_ne; try done.\n          rewrite nzmap_lookup_total_insert_ne; try done.\n          pose proof OC3 n' kt as OC3.\n          by unfold out in OC3. }\n\n    iDestruct \"HnS_ocm\" as \"(%&%&%)\".\n    rename H0 into OC1m. rename H1 into OC2m. rename H2 into OC3m.\n\n    iAssert (outflow_constraints m Im' Jm esm Qm)%I as \"HnS_ocm\".\n    { iPureIntro. split; last split; try done. }\n\n    iAssert (\u231cdomm In = {[n]}\u231d)%I as %Domm_In.\n    { iDestruct \"HnS_si\" as \"(_&_&%&_)\". by iPureIntro. }\n\n    iAssert (\u231cdomm Im = {[m]}\u231d)%I as %Domm_Im.\n    { iDestruct \"HnS_sim\" as \"(_&_&%&_)\". by iPureIntro. }\n\n    assert (domm In' = {[n]}) as Domm_In'.\n    { try done. }\n\n    iAssert (\u231cdomm Im_temp = {[m]}\u231d)%I as %Domm_Im_temp.\n    { assert (Im_temp = inflow_delete_set Im m Qn_old) by done.\n      pose proof (flowint_inflow_delete_set_dom Im m Qn_old Im_temp H0).\n      iPureIntro; rewrite H1 Domm_Im. clear; set_solver. } \n\n    assert (domm In_temp = {[n]}) as Domm_In_temp.\n    { try done. }\n\n\n    assert (domm Im' = {[m]}) as Domm_Im'.\n    { assert (Im' = inflow_insert_set Im_temp m Qn_new) by done.\n      pose proof (flowint_inflow_insert_set_dom Im_temp m Qn_new Im' H0).\n      rewrite H1 Domm_Im_temp. clear; set_solver. }\n\n    iAssert (singleton_interfaces_ghost_state \u03b3_I \u03b3_J n In' Jn\n        \u2217 singleton_interfaces_ghost_state \u03b3_I \u03b3_J m Im' Jm)%I \n                with \"[HnS_si HnS_sim]\" as \"(HnS_si & HnS_sim)\".\n    { iDestruct \"HnS_si\" as \"(HIn & HJn & Domm_In & Domm_Jn)\".\n      iDestruct \"HnS_sim\" as \"(HIm & HJm & Domm_Im & Domm_Jm)\".\n      iCombine \"HIn HIm\" as \"HInm\".\n      assert (Im_temp = inflow_delete_set Im m Qn_old) \n          as HIm_temp. done.\n      assert (In_temp = outflow_delete_set In m Qn_old)\n          as HIn_temp. done.\n      assert (In' = outflow_insert_set In_temp m Qn_new)\n          as HIn'. done.\n      assert (Im' = inflow_insert_set Im_temp m Qn_new)\n          as HIm'. done.\n      iPoseProof (own_valid with \"[$HInm]\") as \"%\".\n      rename H0 into Valid_Inm. \n      rewrite auth_frag_valid in Valid_Inm*; intros Valid_Inm.\n      assert (m \u2208 domm Im) by (clear -Domm_Im; set_solver).\n      assert (domm In \u2260 \u2205) by (clear -Domm_In; set_solver).\n      assert (\u2200 kt, kt \u2208 Qn_old \u2192 1 \u2264 out In m !1 kt).\n      { intros [k t] Hkt. apply HQn_old in Hkt.\n        destruct Hkt as [Hkt1 Hkt2].\n        apply Out_In_m in Hkt1. subst t.\n        clear -Hkt1. unfold outset in Hkt1.\n        rewrite nzmap_elem_of_dom_total in Hkt1*; intros Hkt1.\n        unfold ccmunit, ccm_unit in Hkt1. simpl in Hkt1.\n        unfold nat_unit in Hkt1. \n        assert (\u2200 x: nat, x \u2260 0 \u2192 1 \u2264 x). lia.\n        apply H; try done. }\n      pose proof (flowint_delete_eq In In_temp Im Im_temp \n              m Qn_old H2 H0 H1 HIn_temp HIm_temp Valid_Inm) as HInm_temp.\n      rewrite HInm_temp in Valid_Inm.\n      assert (m \u2208 domm Im_temp) by (clear -Domm_Im_temp; set_solver).\n      assert (domm In_temp \u2260 \u2205) by (clear -Domm_In_temp; set_solver).\n      pose proof (flowint_insert_eq In_temp In' Im_temp Im' \n              m Qn_new H3 H4 HIn' HIm' Valid_Inm) as HInm'.\n      iEval (rewrite HInm_temp) in \"HInm\".\n      iEval (rewrite HInm') in \"HInm\".\n      iEval (rewrite auth_frag_op) in \"HInm\".\n      iDestruct \"HInm\" as \"(?&?)\". iFrame. by iPureIntro. }\n\n    iDestruct \"HnS_Bn\" as %HBn.\n    iAssert (\u231ccontents_in_reach Bn Tn' Qn'\u231d)%I as \"HnS_Bn\".\n    { iPureIntro. intros k t HKS. subst Tn'.\n      unfold mergeLeft. rewrite !gmap_imerge_prf.\n      unfold f_mergeLeft.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Tn) \u2229 esn' !!! m)).\n      - split. intros H'; inversion H'.\n        intros _. assert (k \u2208 S) as Hk. { subst S; by rewrite dom_Vn_Tn. }\n        apply Lookup_Qn' in Hk. rewrite Hk.\n        assert (k \u2208 dom (gset K) Tn) as Htn by (clear -e; set_solver).\n        apply elem_of_dom in Htn. destruct Htn as [t1 Htn].\n        pose proof HBn k t1 HKS as HBn. rewrite Htn.\n        by apply HBn in Htn.\n      - assert (k \u2209 S) as Hk.\n        { subst S. by rewrite dom_Vn_Tn. }\n        rewrite (Lookup_Qn'_ne k Hk).\n        apply HBn; try done. } \n\n    iAssert (\u231c\u03c61 esn' Qn'\u231d \u2217 \u231c\u03c62 n Bn In'\u231d \u2217 \u231c\u03c63 Bn Qn'\u231d \n              \u2217 \u231c\u03c64 n Bn Jn\u231d \u2217 \u231c\u03c65 n Jn\u231d  \n              \u2217 \u231c\u03c66 n esn' Jn Qn'\u231d \u2217 \u231c\u03c67 n In'\u231d)%I\n            with \"[H\u03c6]\" as \"H\u03c6\".\n    { iDestruct \"H\u03c6\" as \"(%&%&%&%&%&%&%)\". \n      rename H0 into H\u03c61. rename H1 into H\u03c62.\n      rename H2 into H\u03c63. rename H3 into H\u03c64.\n      rename H4 into H\u03c65. rename H5 into H\u03c66. \n      rename H6 into H\u03c67. \n      iPureIntro. split; last split; last split; \n      last split; last split; last split.\n      - unfold \u03c61. intros k HKS Hnot.\n        assert (k \u2209 S) as Hk.\n        { destruct (decide (k \u2208 S)); try done.\n          apply S_sub_es in e. pose proof Hnot m as Hnot.\n          clear -e Hnot. set_solver. }\n        rewrite (Lookup_Qn'_ne k Hk).\n        apply H\u03c61; try done.  \n      - unfold \u03c62. try done.\n      - intros k HKS. destruct (decide (k \u2208 S)).\n        + rewrite /(Qn' !!! k).\n          unfold map_lookup_total. \n          rewrite (Lookup_Qn' k e).\n          destruct (Tn !! k) as [t |] eqn: HCnk.\n          * pose proof HBn k t as H'.\n            destruct H' as [H' _]. done.\n            pose proof H' HCnk as H'.\n            rewrite lookup_total_alt.\n            by rewrite H'.\n          * by simpl; lia.\n        + rewrite /(Qn' !!! k).\n          rewrite /(Bn !!! k). \n          unfold map_lookup_total. \n          rewrite (Lookup_Qn'_ne k n0).\n          pose proof H\u03c63 k HKS as H'.    \n          rewrite /(Qn0' !!! k) in H'.\n          by rewrite /(Bn !!! k) in H'. \n      - unfold \u03c64. try done.\n      - try done.\n      - intros k. intros H'. rewrite elem_of_dom.\n        apply H\u03c66 in H'. rewrite elem_of_dom in H'*; intros H'.\n        destruct (decide (k \u2208 S)).\n        * rewrite (Lookup_Qn' k e).\n          intros _. \n          assert (k \u2208 dom (gset K) Tn) as H''.\n          { subst S. rewrite <-dom_Vn_Tn. clear -e; set_solver. }\n          by rewrite elem_of_dom in H''*; intros H''.\n        * by rewrite (Lookup_Qn'_ne k n0).\n      - try done. }\n        \n                              \n    iAssert (\u231ccontents_in_reach Bm' Tm' Qm\u231d)%I with \"[HnS_Bnm]\" as \"HnS_Bnm\".\n    { iDestruct \"HnS_Bnm\" as %HBnm. iPureIntro.\n      intros k t HKS. subst Tm'.\n      unfold mergeRight. rewrite !gmap_imerge_prf.\n      unfold f_mergeRight.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Tn) \u2229 esn' !!! m)).\n      - split; last first.\n        + intros H'. apply not_elem_of_dom in H'.\n          clear -H' e; set_solver.\n        + subst Bm'. rewrite gmap_lookup_insert_map.\n          assert (k \u2208 S) as Hk.\n          { subst S. by rewrite dom_Vn_Tn. }\n          rewrite (Lookup_Smap k Hk).\n          intros H'. rewrite lookup_total_alt.\n          rewrite H'; by simpl.\n          rewrite Dom_Smap. subst S.\n          by rewrite dom_Vn_Tn.\n      - subst Bm'. rewrite gmap_lookup_insert_map_ne.\n        apply HBnm; try done. rewrite Dom_Smap.\n        subst S; by rewrite dom_Vn_Tn. }         \n    \n    iAssert (\u231c\u03c61 esm Qm\u231d \u2217 \u231c\u03c62 m Bm' Im'\u231d \u2217 \u231c\u03c63 Bm' Qm\u231d\n              \u2217 \u231c\u03c64 m Bm' Jm\u231d \u2217 \u231c\u03c65 m Jm\u231d  \n              \u2217 \u231c\u03c66 m esm Jm Qm\u231d \u2217 \u231c\u03c67 m Im'\u231d)%I\n            with \"[H\u03c6m]\" as \"H\u03c6m\".\n    { iDestruct \"H\u03c6m\" as \"(%&%&%&%&%&%&%)\". \n      rename H0 into H\u03c61. rename H1 into H\u03c62.\n      rename H2 into H\u03c63. rename H3 into H\u03c64.\n      rename H4 into H\u03c65. rename H5 into H\u03c66. \n      rename H6 into H\u03c67. \n      iPureIntro. split; last split; last split; \n      last split; last split; last split.\n      - unfold \u03c61. try done.\n      - unfold \u03c62. intros k t HKS Hkt.\n        assert (inset KT Im' m = \n                      inset KT Im m \u2216 Qn_old \u222a Qn_new) as Hinset.\n        { assert (Im_temp = inflow_delete_set Im m Qn_old) by done.\n          assert (Im' = inflow_insert_set Im_temp m Qn_new) by done.\n          assert (\u2200 kt, kt \u2208 Qn_old \u2192 inf Im m !1 kt \u2264 1) as H'.\n          { intros kt kt_in_Qnold. apply H\u03c67. }   \n          pose proof (inflow_delete_set_inset Im m Qn_old Im_temp H' H0).\n          pose proof (inflow_insert_set_inset Im_temp m Qn_new Im' H1).\n          by rewrite H3 H2. }\n        rewrite Hinset in Hkt.\n        rewrite elem_of_union in Hkt*; intros Hkt.\n        destruct Hkt as [Hkt | Hkt].\n        * rewrite elem_of_difference in Hkt*; intros Hkt.\n          destruct Hkt as [Hkt1 Hkt2].\n          apply H\u03c62 in Hkt1; try done.\n          destruct (decide (k \u2208 S)).\n          ** pose proof Bm_eq_Qn k e as H'.\n             assert ((k,t) \u2208 Qn_old) as H''.\n             { apply HQn_old. split; try done.\n               by rewrite H' in Hkt1. }\n             clear -H'' Hkt2. set_solver.\n          ** rewrite lookup_total_alt. subst Bm'.\n             rewrite gmap_lookup_insert_map_ne.\n             by rewrite lookup_total_alt in Hkt1.\n             by rewrite Dom_Smap.\n        * apply HQn_new in Hkt.\n          destruct Hkt as [Hkt1 Hkt2].\n          rewrite lookup_total_alt.\n          subst Bm'. rewrite gmap_lookup_insert_map.\n          rewrite (Lookup_Smap k Hkt1).\n          by simpl. by rewrite Dom_Smap.\n      - intros k HKS. \n        apply (Nat.le_trans _ (Bm !!! k) _).\n        apply H\u03c63. done. apply Bm_le_Bm'.\n      - unfold \u03c64. intros k.\n        destruct (decide (k \u2208 S)).\n        + apply S_sub_insetm in e.\n          right. unfold in_inset.\n          by unfold inset in e.\n        + subst Bm'.\n          rewrite gmap_lookup_insert_map_ne.\n          apply H\u03c64. by rewrite Dom_Smap.\n      - try done.\n      - try done.\n      - intros kt. subst Im'. unfold inflow_insert_set.\n        unfold inflow_map_set. unfold inf; simpl.\n        rewrite !lookup_insert. simpl.\n        destruct (decide (kt \u2208 Qn_new)).\n        + rewrite nzmap_lookup_total_map_set; try done.\n          destruct (decide (kt \u2208 Qn_old)).\n          * rewrite nzmap_lookup_total_map_set; try done.\n            pose proof H\u03c67 kt as H'. clear -H'. lia.\n          * rewrite nzmap_lookup_total_map_set_ne; try done.\n            pose proof H\u03c67 kt as H'.\n            assert (inf Im m !1 kt = 0 \u2228 inf Im m !1 kt = 1).\n            { clear -H'; lia. }\n            destruct H0 as [H0 | H0].\n            ** rewrite H0; lia.\n            ** assert (kt \u2208 inset KT Im m).\n               { unfold inset. rewrite nzmap_elem_of_dom_total.\n                 rewrite H0. unfold ccmunit, ccm_unit; simpl.\n                 unfold nat_unit; lia. }\n               destruct kt as [k t]. apply H\u03c62 in H1.\n               apply HQn_new in e. destruct e as [e1 e2].\n               pose proof Ins_Im k e1. apply H\u03c62 in H2.\n               rewrite H2 in H1.\n               assert ((k, t) \u2208 Qn_old).\n               apply HQn_old. split; try done.\n               done. apply S_sub_KS in e1. done.\n               apply HQn_new in e. destruct e as [e _].\n               apply S_sub_KS in e. done.\n        + rewrite nzmap_lookup_total_map_set_ne; try done.\n          destruct (decide (kt \u2208 Qn_old)).\n          * rewrite nzmap_lookup_total_map_set; try done.\n            pose proof H\u03c67 kt as H'. clear -H'; lia.\n          * rewrite nzmap_lookup_total_map_set_ne; try done. }\n    \n    assert (dom (gset K) Cn' = dom (gset K) Vn') as dom_Cn'_Vn'.\n    { assert (dom (gset K) Cn' \u2286 dom (gset K) Vn') as H'.\n      { intros k. rewrite !elem_of_dom. subst Cn' Vn'.\n        rewrite !gmap_imerge_prf. unfold f_mergeLeft.\n        rewrite <-dom_Cn_Vn.\n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n        - intros [vt H']; inversion H'.\n        - intros [[v t] Hk]. apply HCn in Hk.\n          destruct Hk as [Hk _]. by exists v. }\n      assert (dom (gset K) Vn' \u2286 dom (gset K) Cn') as H''.\n      { intros k. rewrite !elem_of_dom. subst Cn' Vn'.\n        rewrite !gmap_imerge_prf. unfold f_mergeLeft.\n        rewrite dom_Cn_Vn. \n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Vn) \u2229 esn' !!! m)).\n        - intros [vt H'']; inversion H''.\n        - intros [v Hk]. \n          assert (k \u2208 dom (gset K) Tn) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite dom_Vn_Tn in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [t H''].\n          assert (H''' := conj Hk H'').\n          apply HCn in H'''. by exists (v, t). } \n      clear -H' H''. set_solver. }\n        \n    assert (dom (gset K) Cn' = dom (gset K) Tn') as dom_Cn'_Tn'.\n    { assert (dom (gset K) Cn' \u2286 dom (gset K) Tn') as H'.\n      { intros k. rewrite !elem_of_dom. subst Cn' Tn'.\n        rewrite !gmap_imerge_prf. unfold f_mergeLeft.\n        rewrite <-dom_Cn_Tn.\n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n        - intros [vt H']; inversion H'.\n        - intros [[v t] Hk]. apply HCn in Hk.\n          destruct Hk as [_ Hk]. by exists t. }\n      assert (dom (gset K) Tn' \u2286 dom (gset K) Cn') as H''.\n      { intros k. rewrite !elem_of_dom. subst Cn' Tn'.\n        rewrite !gmap_imerge_prf. unfold f_mergeLeft.\n        rewrite dom_Cn_Tn. \n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Tn) \u2229 esn' !!! m)).\n        - intros [vt H'']; inversion H''.\n        - intros [t Hk]. \n          assert (k \u2208 dom (gset K) Vn) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite <-dom_Vn_Tn in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [v H''].\n          assert (H''' := conj H'' Hk).\n          apply HCn in H'''. by exists (v, t). } \n      clear -H' H''. set_solver. }\n\n    iAssert (contents_proj Cn' Vn' Tn') with \"[HnP_cts]\" as \"HnP_cts\".\n    { iPureIntro. split; try done. split; try done.\n      intros k v t. subst Cn' Vn' Tn'. unfold mergeLeft.\n      rewrite !gmap_imerge_prf. unfold f_mergeLeft.\n      rewrite <-dom_Cn_Vn. rewrite <-dom_Cn_Tn.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n      - split. intros H'; inversion H'. intros [H' _]; inversion H'.\n      - apply HCn. }\n\n    iAssert (contents_proj Cm Vm Tm) with \"[$HnP_ctsm]\" as %HnP_ctsm. \n    \n    destruct HnP_ctsm as [dom_Cm_Vm [dom_Cm_Tm HCm]].\n    assert (dom (gset K) Vm = dom (gset K) Tm) as dom_Vm_Tm.\n    { rewrite <-dom_Cm_Vm. by rewrite dom_Cm_Tm. }\n\n    assert (dom (gset K) Cm' = dom (gset K) Vm') as dom_Cm'_Vm'.\n    { assert (dom (gset K) Cm' \u2286 dom (gset K) Vm') as H'.\n      { intros k. rewrite !elem_of_dom. subst Cm' Vm'.\n        rewrite !gmap_imerge_prf. unfold f_mergeRight.\n        rewrite <-dom_Cn_Vn.\n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n        - intros [[v t] Hk]. apply HCn in Hk.\n          destruct Hk as [Hk _]. by exists v.\n        - intros [[v t] Hk]. apply HCm in Hk. \n          destruct Hk as [Hk _]. by exists v. }\n\n      assert (dom (gset K) Vm' \u2286 dom (gset K) Cm') as H''.\n      { intros k. rewrite !elem_of_dom. subst Cm' Vm'.\n        rewrite !gmap_imerge_prf. unfold f_mergeRight.\n        rewrite dom_Cn_Vn. \n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Vn) \u2229 esn' !!! m)).\n        - intros [v Hk]. \n          assert (k \u2208 dom (gset K) Tn) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite dom_Vn_Tn in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [t H''].\n          assert (H''' := conj Hk H'').\n          apply HCn in H'''. by exists (v, t).\n        - intros [v Hk]. \n          assert (k \u2208 dom (gset K) Tm) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite dom_Vm_Tm in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [t H''].\n          assert (H''' := conj Hk H'').\n          apply HCm in H'''. by exists (v, t). }\n      clear -H' H''. set_solver. }\n        \n    assert (dom (gset K) Cm' = dom (gset K) Tm') as dom_Cm'_Tm'.\n    { assert (dom (gset K) Cm' \u2286 dom (gset K) Tm') as H'.\n      { intros k. rewrite !elem_of_dom. subst Cm' Tm'.\n        rewrite !gmap_imerge_prf. unfold f_mergeRight.\n        rewrite <-dom_Cn_Tn.\n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n        - intros [[v t] Hk]. apply HCn in Hk.\n          destruct Hk as [_ Hk]. by exists t.\n        - intros [[v t] Hk]. apply HCm in Hk. \n          destruct Hk as [_ Hk]. by exists t. }\n\n      assert (dom (gset K) Tm' \u2286 dom (gset K) Cm') as H''.\n      { intros k. rewrite !elem_of_dom. subst Cm' Tm'.\n        rewrite !gmap_imerge_prf. unfold f_mergeRight.\n        rewrite dom_Cn_Tn. \n        destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Tn) \u2229 esn' !!! m)).\n        - intros [t Hk]. \n          assert (k \u2208 dom (gset K) Vn) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite <-dom_Vn_Tn in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [v H''].\n          assert (H''' := conj H'' Hk).\n          apply HCn in H'''. by exists (v, t).\n        - intros [t Hk]. \n          assert (k \u2208 dom (gset K) Vm) as H''.\n          { apply elem_of_dom_2 in Hk. by rewrite <-dom_Vm_Tm in Hk. }\n          apply elem_of_dom in H''.\n          destruct H'' as [v H''].\n          assert (H''' := conj H'' Hk).\n          apply HCm in H'''. by exists (v, t). }\n      clear -H' H''. set_solver. }\n\n    iAssert (contents_proj Cm' Vm' Tm') with \"[HnP_ctsm]\" as \"HnP_ctsm\".\n    { iPureIntro. split; try done. split; try done.\n      intros k v t. subst Cm' Vm' Tm'. unfold mergeRight.\n      rewrite !gmap_imerge_prf. unfold f_mergeRight.\n      rewrite <-dom_Cn_Vn. rewrite <-dom_Cn_Tn.\n      destruct (decide (k \u2208 ((KS \u2229 K1) \u2229 dom (gset K) Cn) \u2229 esn' !!! m)).\n      - apply HCn. \n      - apply HCm. }\n\n    iModIntro. iExists Cn', Cm', Qn'. iFrame \"Hglob HH\".  \n    iSplitL \"node_n HnP_gh HnP_cts HnP_C HnP_frac\".\n    { iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn', Vn', Tn'. iFrame \"\u2217#\". }\n    iSplitL \"HnS_gh HnS_FP HnS_cl HnS_Bn HnS_H HnS_star HnS_frac H\u03c6 HnS_si\".\n    { iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn', Tn', Bn, In'. \n      iExists Jn. iFrame \"\u2217#\". }\n    iSplitL \"node_m HnP_ghm HnP_ctsm HnP_Cm HnP_fracm\".\n    { iExists \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm, esm, Vm', Tm'. iFrame \"\u2217#\". }\n    iExists \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm, esm, Tm', Bm', Im'.\n    iExists Jm. iFrame \"\u2217#\".\n    destruct (decide (m = r)); try done.\n  Qed.        \n      \n  Lemma compact_spec N \u03b3_te \u03b3_he \u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh \n                     r \u03b3_td \u03b3_ght (n: Node) :\n      \u22a2 inFP \u03b3_f n -\u2217 \n          <<< \u2200 M, MCS_high N \u03b3_te \u03b3_he \u03b3_s \n                      (Inv_LSM \u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r) \n                      \u03b3_td \u03b3_ght M >>> \n                compact r #n @ \u22a4 \u2216 \u2191(mcsN N)\n          <<< MCS_high N \u03b3_te \u03b3_he \u03b3_s \n                (Inv_LSM \u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r) \n                 \u03b3_td \u03b3_ght M, RET #() >>>.\n  Proof.\n    iL\u00f6b as \"IH\" forall (n).\n    iIntros \"#FP_n\". iIntros (\u03a6) \"AU\".\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 \"\u2217#\". iModIntro.    \n    wp_lam.\n    awp_apply lockNode_spec_high; try done.\n    iAaccIntro with \"\"; try eauto with iFrame.\n    iIntros (Cn Qn)\"HnP_n\". iModIntro. wp_pures. \n    iDestruct \"HnP_n\" as (\u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn Vn Tn)\"(node_n   \n                            & #HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n    iPoseProof ((node_es_disjoint r n) with \"[$node_n]\") as \"%\".\n    rename H into Disj_esn.                        \n    wp_apply (atCapacity_spec with \"node_n\").\n    iIntros (b) \"node_n\". destruct b; last first; wp_pures.\n    - awp_apply (unlockNode_spec_high with \"[] [] [-AU]\"); try done.\n      iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn, Vn, Tn. iFrame \"\u2217#\".\n      iAaccIntro with \"\"; try eauto with iFrame.\n      iIntros \"_\". iMod \"AU\" as (M)\"[MCS_high [_ Hclose]]\".\n      iMod (\"Hclose\" with \"MCS_high\") as \"H\u03a6\".\n      by iModIntro.\n    - wp_apply (chooseNext_spec with \"node_n\").\n      iIntros (m)\"(node_n & Hif)\".\n      destruct m as [m | ]; last first.\n      + wp_pures. iDestruct \"Hif\" as \"NeedsNew\".\n        wp_apply allocNode_spec; try done.\n        iIntros (m lm)\"(NodeSp_m & % & Hl_m)\".\n        subst lm. wp_pures.\n        iApply fupd_wp. iInv \"HInv\" as (T'' H'')\"(mcs_high & >Inv_LSM)\".\n        iDestruct \"Inv_LSM\" as (h\u03b3'' I'' J'')\"(Hglob & Hstar)\".\n        iAssert (\u231cm \u2209 domm I''\u231d)%I as \"%\".\n        { destruct (decide (m \u2208 domm I'')); try done.\n          rewrite (big_sepS_delete _ (domm I'') m); last by eauto.\n          iDestruct \"Hstar\" as \"(Hm & _)\".\n          iDestruct \"Hm\" as (bm Cm Qm)\"((Hl_m' & _) & _)\".\n          iDestruct (mapsto_valid_2 with \"Hl_m Hl_m'\") as \"(% & _)\".\n          exfalso. done. } rename H into m_notin_I''.\n        iAssert (inFP \u03b3_f r) as \"#FP_r\".\n        { by iDestruct \"Hglob\" as \"(HI & Out_I & HR \n            & Out_J & Inf_J & Hf & H\u03b3 & #FP_r & domm_IJ & domm_I\u03b3)\". }\n\n        iPoseProof (inFP_domm_glob with \"[$FP_r] [$Hglob]\") as \"%\".\n        rename H into r_in_I''.\n        \n        assert (m \u2260 r) as m_neq_r.\n        { clear -m_notin_I'' r_in_I''. set_solver. }  \n\n        iModIntro. iSplitL \"Hglob Hstar mcs_high\".\n        iNext. iExists T'', H''; iFrame.\n        iExists h\u03b3'', I'', J''. iFrame.\n                       \n   \n        iModIntro.\n        wp_apply (insertNode_spec with \"[$node_n $NeedsNew $NodeSp_m]\").\n        { by iPureIntro. }\n        \n        iIntros (esn' esm0 Vm0)\"(node_n & node_m & Hesn' & Hesn_m' & Hcm & Hesm)\". \n        iDestruct \"Hesn'\" as %Hesn'.\n        iDestruct \"Hesn_m'\" as %Hesn_m'.\n        iDestruct \"Hcm\" as %Hvm.\n        iDestruct \"Hesm\" as %Hesm.\n        iApply fupd_wp. iInv \"HInv\" as (T0' H0)\"(mcs_high & >Inv_LSM)\".\n        iDestruct \"Inv_LSM\" as (h\u03b30 I0 J0)\"(Hglob & Hstar)\".\n        iAssert (\u231cm \u2209 domm I0\u231d)%I as \"%\".\n        { destruct (decide (m \u2208 domm I0)); try done.\n          rewrite (big_sepS_delete _ (domm I0) m); last by eauto.\n          iDestruct \"Hstar\" as \"(Hm & _)\".\n          iDestruct \"Hm\" as (bm Cm Qm)\"((Hl_m' & _) & _)\".\n          iDestruct (mapsto_valid_2 with \"Hl_m Hl_m'\") as \"(% & _)\".\n          exfalso. done. } rename H into m_notin_I0.\n          \n        iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n        rename H into n_in_I0.  \n\n        rewrite (big_sepS_delete _ (domm I0) n); last by eauto.\n        iDestruct \"Hstar\" as \"(H_n & Hstar')\".\n        iDestruct \"H_n\" as (bn Cn' Qn')\"(Hl_n & HnS_n)\".\n        iDestruct \"HnS_n\" as (\u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn' \n                                  es' Tn' Bn In0 Jn0) \"HnS_n'\".\n        iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_n']\")\n             as \"(HnP_frac & HnS_n' &%&%&%)\". subst es' Tn' Qn'.   \n        iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & H\u03c6)\".\n\n        iAssert (nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn \n                              \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn)%I\n                   with \"[HnP_gh HnP_frac HnP_C HnP_cts]\" as \"HnP_aux\".\n        { iFrame \"\u2217#\". }\n        \n        iAssert (nodeShared' \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Tn Qn Bn H0 \n                            \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn In0 Jn0) with\n                  \"[HnS_gh HnS_frac HnS_si HnS_FP \n                        HnS_cl HnS_oc HnS_Bn HnS_H HnS_star H\u03c6]\" as \"HnS_n'\".\n        { iFrame. }                \n\n        set (Cm0 := \u2205 : gmap K (V*T)).\n        set (Tm0 := \u2205 : gmap K T).\n        set (Qm0 := \u2205 : gmap K T).  \n        set (Bm0 := \u2205 : gmap K T).  \n        set (Im0 := int {| infR := {[m := \u2205]} ; outR := \u2205|}: multiset_flowint_ur KT).\n        set (Jm0 := int {| infR := {[m := \u2205]} ; outR := \u2205|}: multiset_flowint_ur K).\n               \n        iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >% & >HClock & >HUniq & Prot)\".\n        rename H into HInit.\n\n        iMod ((ghost_update_contExt \n                 \u03b3_s \u03b3_I \u03b3_J \u03b3_f \u03b3_gh \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn \n                 H0 h\u03b30 I0 Im0 In0 J0 Jm0 Jn0 \n                 r m n Cm0 Cn Vm0 Vn Tm0 Tn \n                 Bm0 Bn Qm0 Qn esn esm0) with\n                \"[] [$FP_n $HnP_aux HnS_n' $HH $Hglob]\") \n                    as (h\u03b3' I0' R0' \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm)\"H\".\n        { iPureIntro; try done. }\n        { iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n             & HnS_cl & HnS_oc & HnS_Bn & HnS_H & HnS_star & H\u03c6)\". \n          iFrame. by iPureIntro. }\n            \n        iDestruct \"H\" as \"(#FP_m & HnP_aux & HnS_n' & HnP_auxm & HnS_auxm \n                  & HH & Hglob & Esn_empty & Out_In_m & Out_Jn_m \n                  & Domm_I0' & m_neq_r & m_neq_n)\".\n        iDestruct \"Esn_empty\" as %Esn_empty.\n        iDestruct \"Out_In_m\" as %Out_In_m.\n        iDestruct \"Out_Jn_m\" as %Out_Jn_m.\n        iDestruct \"Domm_I0'\" as %Domm_I0'.\n        iDestruct \"m_neq_n\" as %m_neq_n.                   \n        \n        iMod ((ghost_update_interface_mod) with \n                \"[] [$node_n $HnP_aux $HnS_n' $node_m $HnP_auxm $HnS_auxm]\") \n                    as \"H\".\n        { iPureIntro; try repeat split; try done. }            \n\n        iDestruct \"H\" as (Qn0')\"(HnP_n' & HnS_n & HnP_m' & HnS_m)\".\n        \n        \n        iAssert (\u231cbn = true\u231d)%I as \"%\".\n        { iDestruct \"HnP_n'\" as \"(node_n & _)\".\n          iPoseProof (nodePred_lockR_true with \"[$node_n] [$Hl_n]\")\n            as \"%\". try done. } subst bn.\n\n\n        iModIntro. iSplitR \"AU HnP_n' HnP_m'\".\n        { iNext. iExists T0', H0. iFrame.\n          iSplitR; first by iPureIntro.\n          iExists h\u03b3', I0', R0'. iFrame \"Hglob\". rewrite Domm_I0'.     \n          rewrite (big_sepS_delete _ (domm I0 \u222a {[m]}) m); \n              last first. { clear; set_solver. }\n          iSplitL \"Hl_m HnS_m\".\n          { iExists true, Cm0, Qm0. iFrame \"Hl_m\".\n            iFrame \"HnS_m\". }\n          assert ((domm I0 \u222a {[m]}) \u2216 {[m]} = domm I0) as H'.\n          { clear -m_notin_I0. set_solver. }\n          rewrite H'. rewrite (big_sepS_delete _ (domm I0) n); \n              last apply n_in_I0.\n          iFrame \"Hstar'\". iExists true, Cn, Qn0'.\n          iFrame. } \n            \n        iModIntro.\n        wp_pures.\n        iDestruct \"HnP_m'\" as \"(node_m & #HnP_ghm & HnP_fracm & HnP_Cm & HnP_ctsm)\".\n        iDestruct \"HnP_n'\" as \"(node_n & _ & HnP_frac & HnP_C & HnP_cts)\".\n        wp_apply (mergeContents_spec with \"[$node_n $node_m]\"); try done.\n        clear Cn' \u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn'.\n        iIntros (S Vn' Vm') \"(node_n & node_m & Hvn' & Hvm')\".\n        iDestruct \"Hvn'\" as %Hvn'.\n        iDestruct \"Hvm'\" as %Hvm'.          \n        wp_pures.\n        iApply fupd_wp. iInv \"HInv\" as (t' H)\"(mcs_high & >Inv_LSM)\".\n        iDestruct \"Inv_LSM\" as (h\u03b3 I J)\"(Hglob & Hstar)\".\n        \n        iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n        rename H1 into n_in_I.  \n        rewrite (big_sepS_delete _ (domm I) n); last by eauto.\n        iDestruct \"Hstar\" as \"(H_n & Hstar')\".\n        iDestruct \"H_n\" as (bn Cn' Qn'')\"(Hl_n & HnS_n)\".\n        iDestruct \"HnS_n\" as (\u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn' es' Tn'' Bn' In Jn) \"HnS_n'\".\n        iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_n']\")\n             as \"(HnP_frac & HnS_n' &%&%&%)\". subst es' Tn'' Qn''.   \n        iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & H\u03c6)\".\n\n        iPoseProof (inFP_domm_glob with \"[$FP_m] [$Hglob]\") as \"%\".\n        rename H1 into m_in_I.  \n\n        rewrite (big_sepS_delete _ (domm I \u2216 {[n]}) m); last by set_solver.\n        iDestruct \"Hstar'\" as \"(H_m & Hstar')\".\n        iDestruct \"H_m\" as (bm Cm' Qm'')\"(Hl_m & HnS_m)\".\n        iDestruct \"HnS_m\" as (\u03b3_em' \u03b3_cm' \u03b3_qm' \u03b3_cirm' es' Tm'' Bm Im Jm) \"HnS_m'\".\n        iPoseProof (nodePred_nodeShared_eq with \"[$HnP_ghm] [$HnP_fracm] [$HnS_m']\")\n             as \"(HnP_fracm & HnS_m' &%&%&%)\". subst es' Tm'' Qm''.   \n        iDestruct \"HnS_m'\" as \"(HnS_ghm & HnS_fracm & HnS_sim & HnS_FPm \n                         & HnS_clm & HnS_ocm & HnS_Bnm & HnS_Hm & HnS_starm & H\u03c6m)\".\n\n        iPoseProof (nodePred_lockR_true with \"[$node_n] [$Hl_n]\")\n            as \"%\". subst bn.    \n        iPoseProof (nodePred_lockR_true with \"[$node_m] [$Hl_m]\")\n            as \"%\". subst bm.    \n\n        iAssert (nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn0' \n                              \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn')%I\n                   with \"[HnP_gh HnP_frac HnP_C HnP_cts]\" as \"HnP_aux\".\n        { iFrame \"\u2217#\". }           \n\n        iAssert (nodePred_aux \u03b3_gh \u03b3_s m Cm0 Vm0 Tm0 Qm0 \n                              \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm0)%I\n                   with \"[HnP_ghm HnP_fracm HnP_Cm HnP_ctsm]\" as \"HnP_auxm\".\n        { iFrame \"\u2217#\". }\n        \n        iAssert (nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Qn0' H)%I\n                  with \"[HnS_gh HnS_frac HnS_si HnS_FP HnS_cl \n                    HnS_oc HnS_Bn HnS_H HnS_star H\u03c6]\" as \"HnS_n\".\n        { iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn', Tn, Bn', In. iExists Jn. \n          iFrame. }\n                              \n        iAssert (nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Qm0 H)%I\n                  with \"[HnS_ghm HnS_fracm HnS_sim HnS_FPm HnS_clm \n                    HnS_ocm HnS_Bnm HnS_Hm HnS_starm H\u03c6m]\" as \"HnS_m\".\n        { iExists \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm, esm0, Tm0, Bm, Im. iExists Jm. \n          iFrame. }\n\n        iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >HInit & >% & Prot)\".\n        rename H1 into HClock.\n        \n        iMod (mergeContents_ghost_update with \n                \"[] [$node_n $HnP_aux $node_m $HnP_auxm $HnS_n $HnS_m \n                          $HH $Hglob]\") \n                    as (Cn'' Cm'' Qn') \"(HnP_n & HnS_n & HnP_m & HnS_m \n                                  & HH & Hglob)\".\n        { iPureIntro; try done. }\n        { by iPureIntro. }\n        \n        iModIntro.\n        iSplitR \"AU HnP_n HnP_m\".\n        { iNext. iExists t', H. iFrame.\n          iSplitR; first by iPureIntro.\n          iExists h\u03b3, I, J. iFrame \"Hglob\".\n          rewrite (big_sepS_delete _ (domm I) n); last by eauto.\n          iSplitL \"Hl_n HnS_n\".\n          { iExists true, Cn'', Qn'. iFrame \"HnS_n\".\n            iApply lockR_true; try done. }\n          rewrite (big_sepS_delete _ (domm I \u2216 {[n]}) m); last first.\n          clear - m_neq_n m_in_I. set_solver. \n          iFrame \"Hstar'\". iExists true, Cm'', Qm0.\n          iFrame\"HnS_m\". iApply lockR_true; try done. }\n        iModIntro.\n        awp_apply (unlockNode_spec_high with \"[] [] \n            [$HnP_n]\"); try done.\n        iAaccIntro with \"\"; try eauto with iFrame.\n        iIntros \"_\"; iModIntro. wp_pures.\n        awp_apply (unlockNode_spec_high with \"[] [] \n            [$HnP_m]\"); try done.\n        iAaccIntro with \"\"; try eauto with iFrame.\n        iIntros \"_\"; iModIntro. wp_pures.\n        iApply \"IH\"; try done.\n    + wp_pures.\n      iDestruct \"Hif\" as %es_ne.\n    \n      iApply fupd_wp.\n      iInv \"HInv\" as (T0' H0)\"(mcs_high & >Inv_LSM)\".\n      iDestruct \"Inv_LSM\" as (h\u03b30 I0 J0)\"(Hglob & Hstar)\".\n      iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n      rename H into n_in_I0.    \n\n      rewrite (big_sepS_delete _ (domm I0) n); last by eauto.\n      iDestruct \"Hstar\" as \"(H_n & Hstar')\".\n      iDestruct \"H_n\" as (bn Cn' Qn'')\"(Hl_n & HnS_n)\".\n      iDestruct \"HnS_n\" as (\u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn' es' Tn'' Bn In0 Jn0) \"HnS_n'\".\n      iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_n']\")\n           as \"(HnP_frac & HnS_n' &%&%&%)\". subst es' Tn'' Qn''.   \n      iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & H\u03c6)\".\n      \n      iAssert (inFP \u03b3_f m)%I as \"#FP_m\".\n      { iApply \"HnS_cl\". iPureIntro; clear -es_ne; set_solver. }\n       \n      iPoseProof (inFP_domm_glob with \"[$FP_m] [$Hglob]\") as \"%\".\n      rename H into m_in_I0.  \n      \n      iAssert (\u231cm \u2260 n \u2227 m \u2260 r\u231d)%I as %H'.\n      { iPoseProof (node_es_empty with \"[$node_n]\") as \"%\".\n        destruct H as [Esn_r Esn_n]. iPureIntro. split.\n        - destruct (decide (m = n)); try done.\n          subst m. clear -es_ne Esn_n. set_solver.\n        - destruct (decide (m = r)); try done.\n          subst m. clear -es_ne Esn_r. set_solver. }\n      destruct H' as [m_neq_n m_neq_r].    \n\n      iPoseProof (nodePred_lockR_true with \"[$node_n] [$Hl_n]\")\n         as \"%\". subst bn.\n                        \n      iModIntro. iSplitR \"AU node_n HnP_frac HnP_gh HnP_C HnP_cts\".\n      { iNext. iExists T0', H0. iFrame \"mcs_high\".\n        iExists h\u03b30, I0, J0. iFrame \"Hglob\".\n        rewrite (big_sepS_delete _ (domm I0) n); last by eauto.\n        iFrame \"Hstar'\". iExists true, Cn, Qn. iFrame.\n        iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn, Tn, Bn, In0. iExists Jn0.\n        iFrame. } \n        \n      iModIntro.\n      awp_apply lockNode_spec_high; try done.\n      iAaccIntro with \"\"; try eauto with iFrame.\n      iIntros (Cm Qm)\"HnP_m\". iModIntro.\n      wp_pures.\n      iDestruct \"HnP_m\" as (\u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm Vm Tm)\"(node_m   \n                          & #HnP_ghm & HnP_fracm & HnP_Cm & HnP_ctsm)\".\n      wp_apply (mergeContents_spec with \"[$node_n $node_m]\"); try done.\n      clear Cn' \u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn'.\n      iIntros (S Vn' Vm') \"(node_n & node_m & Hvn' & Hvm')\".\n      iDestruct \"Hvn'\" as %Hvn'.\n      iDestruct \"Hvm'\" as %Hvm'.          \n      wp_pures.\n      iApply fupd_wp. iInv \"HInv\" as (t' H)\"(mcs_high & >Inv_LSM)\".\n      iDestruct \"Inv_LSM\" as (h\u03b3 I J)\"(Hglob & Hstar)\".\n      iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n      rename H1 into n_in_I.  \n      rewrite (big_sepS_delete _ (domm I) n); last by eauto.\n      iDestruct \"Hstar\" as \"(H_n & Hstar')\".\n      iDestruct \"H_n\" as (bn Cn' Qn'')\"(Hl_n & HnS_n)\".\n      iDestruct \"HnS_n\" as (\u03b3_en' \u03b3_cn' \u03b3_qn' \u03b3_cirn' es' Tn'' Bn' In Jn) \"HnS_n'\".\n      iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$HnS_n']\")\n           as \"(HnP_frac & HnS_n' &%&%&%)\". subst es' Tn'' Qn''.   \n      iDestruct \"HnS_n'\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP \n                            & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & H\u03c6)\".\n\n      iPoseProof (inFP_domm_glob with \"[$FP_m] [$Hglob]\") as \"%\".\n      rename H1 into m_in_I.\n      rewrite (big_sepS_delete _ (domm I \u2216 {[n]}) m); last by set_solver.\n      iDestruct \"Hstar'\" as \"(H_m & Hstar')\".\n      iDestruct \"H_m\" as (bm Cm' Qm'')\"(Hl_m & HnS_m)\".\n      iDestruct \"HnS_m\" as (\u03b3_em' \u03b3_cm' \u03b3_qm' \u03b3_cirm' es' Tm'' Bm Im Jm) \"HnS_m'\".\n      iPoseProof (nodePred_nodeShared_eq with \"[$HnP_ghm] [$HnP_fracm] [$HnS_m']\")\n             as \"(HnP_fracm & HnS_m' &%&%&%)\". subst es' Tm'' Qm''.   \n      iDestruct \"HnS_m'\" as \"(HnS_ghm & HnS_fracm & HnS_sim & HnS_FPm \n                       & HnS_clm & HnS_ocm & HnS_Bnm & HnS_Hm & HnS_starm & H\u03c6m)\".\n\n      iPoseProof (nodePred_lockR_true with \"[$node_n] [$Hl_n]\")\n         as \"%\". subst bn.\n\n      iPoseProof (nodePred_lockR_true with \"[$node_m] [$Hl_m]\")\n         as \"%\". subst bm.\n                \n      iAssert (nodePred_aux \u03b3_gh \u03b3_s n Cn Vn Tn Qn \n                            \u03b3_en \u03b3_cn \u03b3_qn \u03b3_cirn esn)%I\n                 with \"[HnP_gh HnP_frac HnP_C HnP_cts]\" as \"HnP_aux\".\n      { iFrame \"\u2217#\". }           \n\n      iAssert (nodePred_aux \u03b3_gh \u03b3_s m Cm Vm Tm Qm \n                            \u03b3_em \u03b3_cm \u03b3_qm \u03b3_cirm esm)%I\n                 with \"[HnP_fracm HnP_Cm HnP_ctsm]\" as \"HnP_auxm\".\n      { iFrame \"\u2217#\". }\n       \n      iAssert (nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r n Qn H)%I\n                with \"[HnS_gh HnS_frac HnS_si HnS_FP HnS_cl \n                  HnS_oc HnS_Bn HnS_H HnS_star H\u03c6]\" as \"HnS_n\".\n      { iExists \u03b3_en, \u03b3_cn, \u03b3_qn, \u03b3_cirn, esn, Tn, Bn', In. iExists Jn.\n        iFrame. }\n                              \n      iAssert (nodeShared \u03b3_I \u03b3_J \u03b3_f \u03b3_gh r m Qm H)%I\n                with \"[HnS_ghm HnS_fracm HnS_sim HnS_FPm HnS_clm \n                  HnS_ocm HnS_Bnm HnS_Hm HnS_starm H\u03c6m]\" as \"HnS_m\".\n      { iExists \u03b3_em, \u03b3_cm, \u03b3_qm, \u03b3_cirm, esm, Tm, Bm, Im. iExists Jm.\n        iFrame. }\n        \n      iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >HInit & >% & Prot)\".\n      rename H1 into HClock.\n\n      iMod (mergeContents_ghost_update with \n              \"[] [$node_n $HnP_aux $node_m $HnP_auxm \n                                     $HnS_n $HnS_m $HH $Hglob]\") \n                  as (Cn'' Cm'' Qn') \"(HnP_n & HnS_n & HnP_m & HnS_m \n                                                  & HH & Hglob)\".\n      { iPureIntro; repeat split; try done. }\n      { by iPureIntro. }\n        \n      iModIntro.\n      iSplitR \"AU HnP_n HnP_m\".\n      { iNext. iExists t', H. iFrame.\n        iSplitR; first by iPureIntro.\n        iExists h\u03b3, I, J. iFrame \"Hglob\".\n        rewrite (big_sepS_delete _ (domm I) n); last by eauto.\n        iSplitL \"Hl_n HnS_n\".\n        { iExists true, Cn'', Qn'. iFrame \"HnS_n\".\n          iApply lockR_true; try done. }\n        rewrite (big_sepS_delete _ (domm I \u2216 {[n]}) m); last first.\n        clear - m_neq_n m_in_I. set_solver. \n        iFrame \"Hstar'\". iExists true, Cm'', Qm.\n        iFrame \"HnS_m\". iApply lockR_true; try done. }\n      iModIntro.\n      awp_apply (unlockNode_spec_high with \"[] [] \n          [$HnP_n]\"); try done.\n      iAaccIntro with \"\"; try eauto with iFrame.\n      iIntros \"_\"; iModIntro. wp_pures.\n      awp_apply (unlockNode_spec_high with \"[] [] \n          [$HnP_m]\"); try done.\n      iAaccIntro with \"\"; try eauto with iFrame.\n      iIntros \"_\"; iModIntro. wp_pures.\n      iApply \"IH\"; try done.\n  Qed.\n\nEnd multicopy_lsm_compact.\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_compact.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.19897177266204405}}
{"text": "Require Import List.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FunctionalExtensionality.\nRequire Import Utils.\nRequire Import Lattices.\nRequire Import CLattices.\nRequire Import Instr.\nRequire Import AbstractCommon.\nRequire Import Rules.\nRequire Import AbstractMachine.\nRequire Import QuasiAbstractMachine.\nRequire Import Concrete.\nRequire Import ConcreteMachine.\nRequire Import ConcreteExecutions.\nRequire Import Determinism.\nRequire Import Refinement.\nRequire Import FaultRoutine.\nRequire Import Semantics.\nRequire Import Encodable.\n\nOpen Scope Z_scope.\nCoercion Z_of_nat : nat >-> Z.\n\n(** The Concrete Machine (with appropriate Fault Handler) refines the Abstract Machine. *)\n\nSet Implicit Arguments.\n\n(** * First refinement : from the abstract to the quasi-abstract machine *)\nSection AbstractQuasiAbstract.\n\nContext {T: Type}\n        {Latt: JoinSemiLattice T}.\n\nLemma abstract_step_equiv : forall s e s',\n                              step tini_quasi_abstract_machine s e s' <->\n                              step abstract_machine s e s'.\nProof.\n  intros.\n  split; intro H; inv H;\n  unfold QuasiAbstractMachine.ifc_run_tmr, apply_rule in *;\n  simpl in *;\n  repeat match goal with\n           | H : Some _ = Some _ |- _ =>\n             inv H\n           | H : (if ?b then _ else _) = _ |- _ =>\n             destruct b eqn:E; inv H\n         end;\n  unfold Vector.nth_order in *; simpl in *;\n  try [> once (econstructor; solve [compute; eauto]) ..].\n\n  econstructor; eauto.\n  unfold QuasiAbstractMachine.ifc_run_tmr, apply_rule. simpl.\n  unfold Vector.nth_order. simpl.\n  rewrite CHECK. trivial.\nQed.\n\nProgram Definition abstract_quasi_abstract_sref :=\n  @strong_refinement abstract_machine\n                     tini_quasi_abstract_machine\n                     eq eq _.\nNext Obligation.\n  exists a2. exists s22.\n  repeat split; trivial.\n  rewrite <- (abstract_step_equiv s21 a2 s22).\n  auto.\n  destruct a2; constructor; auto.\nQed.\n\nProgram Definition abstract_quasi_abstract_ref :=\n  @refinement_from_state_refinement abstract_machine tini_quasi_abstract_machine\n                                    abstract_quasi_abstract_sref eq\n                                    _.\n\nEnd AbstractQuasiAbstract.\n\n(** * Second Refinement:\n     from the quasi-abstract machine to the concrete machine *)\n\n(** Matching relation between concrete and abstract values\n    Generic in the rule table and fault handler *)\nSection MatchAbstractConcrete.\n\nContext {L: Type}\n        {Latt: JoinSemiLattice L}\n        {CLatt: ConcreteLattice L}\n        {ELatt : Encodable L}\n        {WFCLatt: WfConcreteLattice L Latt CLatt ELatt}.\n\nDefinition atom_labToZ (a:@Atom L) : (@Atom Z) :=\n  let (v,l) := a in (v,labToZ l).\n\nDefinition atom_ZToLab (a:@Atom Z) : (@Atom L) :=\n  let (v,l) := a in (v,ZToLab l).\n\nLemma atom_ZToLab_labToZ_id: forall (a:@Atom L), a = atom_ZToLab (atom_labToZ a).\nProof.\n  intros. unfold atom_labToZ, atom_ZToLab. destruct a. f_equal.\n  apply ZToLab_labToZ_id.\nQed.\n\nDefinition mem_labToZ (m: list (@Atom L)) : list (@Atom Z) :=\n  map atom_labToZ m.\n\nDefinition mem_ZToLab (m: list (@Atom Z)) : list (@Atom L) :=\n  map atom_ZToLab m.\n\nLemma mem_ZToLab_labToZ_id : forall (m: list (@Atom L)),\n   m = mem_ZToLab (mem_labToZ m).\nProof.\n  intros. unfold mem_ZToLab, mem_labToZ. rewrite map_map.\n  replace (fun x => atom_ZToLab (atom_labToZ x)) with (@id (@Atom L)).\n  rewrite map_id; auto.\n  extensionality x.\n  apply atom_ZToLab_labToZ_id.\nQed.\n\nLemma read_m_labToZ : forall m addrv xv xl,\n read_m addrv m = Some (xv, xl) ->\n read_m addrv (mem_labToZ m) = Some (xv, labToZ xl).\nProof.\n  unfold read_m in *.\n  destruct m ; intros.\n  - case (addrv <? 0) in *. inv H.\n    rewrite index_list_nil in H; inv H.\n  - destruct addrv; simpl in *.\n    + inv H. reflexivity.\n    + edestruct (Pos2Nat.is_succ p0); eauto.\n      rewrite H0 in *. simpl in *.\n      unfold mem_labToZ. erewrite index_list_map; eauto.\n      reflexivity.\n    + inv H.\nQed.\n\nLemma read_m_labToZ' :\n  forall i m xv xl,\n    read_m i (mem_labToZ m) = Some (xv, xl) ->\n    exists xl',\n      read_m i m = Some (xv, xl') /\\\n      xl = labToZ xl'.\nProof.\n  unfold index_list_Z.\n  intros.\n  destruct (i <? 0). inv H.\n  gdep m.\n  generalize (Z.to_nat i). clear i.\n  intros i.\n  induction i as [|i IH];\n  intros m H;\n  destruct m as [|[xv' xl'] m'];\n  simpl in *; inv H; intuition.\n  eexists. split; repeat f_equal.\nQed.\n\nLemma upd_m_labToZ : forall i xv xl m cm'\n                            (UP : upd_m i (xv, labToZ xl) (mem_labToZ m) = Some cm'),\n                       exists m',\n                         upd_m i (xv, xl) m = Some m' /\\\n                         cm' = mem_labToZ m'.\nProof.\n  intros i; unfold upd_m; intros.\n  destruct (i <? 0). inv UP.\n  gdep cm'. gdep m.\n  generalize (Z.to_nat i). clear i.\n  intros i.\n  induction i as [|i IH];\n  intros [| [xv' xl']] cm' UP; simpl in *; inv UP.\n  repeat eexists.\n  destruct (update_list i (xv, labToZ xl) (mem_labToZ l)) eqn:E; inv H0.\n  guess tt IH.\n  destruct IH. intuition.\n  subst. eexists. rewrite H0.\n  eauto.\nQed.\n\nInductive match_stacks : list (@StkElmt L) ->  list CStkElmt -> Prop :=\n| ms_nil : match_stacks nil nil\n| ms_cons_data: forall a ca s cs,\n                  match_stacks s cs ->\n                  ca = atom_labToZ a ->\n                  match_stacks (AData a :: s) (CData ca :: cs)\n| ms_cons_ret: forall a ca r s cs,\n                  match_stacks s cs ->\n                  ca = atom_labToZ a ->\n                  match_stacks (ARet a r:: s) (CRet ca r false:: cs).\nHint Constructors match_stacks : core.\n\nLemma match_stacks_args :\n  forall s args cs,\n    match_stacks s (args ++ cs) ->\n    exists args' s',\n      s = args' ++ s' /\\ match_stacks args' args /\\ match_stacks s' cs.\nProof.\n  intros s args. gdep s.\n  induction args; intros.\n  simpl in *. exists nil; exists s. split; auto.\n  inv H;\n    (exploit IHargs; eauto; intros [args' [cs' [Heq [Hmatch Hmatch']]]]);\n    (inv Heq; (eexists; eexists; split; eauto ; try reflexivity)).\nQed.\n\nLemma match_stacks_length : forall s cs,\n    match_stacks s cs ->\n    length cs = length s.\nProof.\n  induction 1; intros; (simpl; eauto).\nQed.\n\nLemma match_stacks_app : forall s cs s' cs',\n    match_stacks s cs ->\n    match_stacks s' cs' ->\n    match_stacks (s++s') (cs++cs').\nProof.\n  induction 1 ; intros; (simpl; eauto).\nQed.\n\nLemma match_stacks_data :\n  forall s cs,\n    match_stacks s cs ->\n    (forall a : CStkElmt, In a cs -> exists d : Atom, a = CData d) ->\n    (forall a : StkElmt, In a s -> exists d : Atom, a = AData d).\nProof.\n  induction 1;  intros.\n  - inv H0.\n  - inv H2.  eauto.\n    eapply IHmatch_stacks; eauto.\n    intros; eapply H1; eauto.\n    econstructor 2; eauto.\n  - inv H2.\n    eelim (H1 (CRet (atom_labToZ a) r false)); eauto. intros. inv H0.\n    constructor; auto.\n    eapply IHmatch_stacks; eauto.\n    intros; eapply H1; eauto.\n    econstructor 2; eauto.\nQed.\n\nLemma match_stacks_app_length : forall S CS,\n    match_stacks S CS ->\n    forall s s' cs cs',\n    S = (s++s') ->\n    CS = (cs++cs') ->\n    length s = length cs ->\n    match_stacks s cs\n    /\\ match_stacks s' cs'.\nProof.\n  induction 1 ; intros; (simpl; eauto).\n  - exploit app_eq_nil ; eauto. intros [Heq Heq']. inv Heq.\n    exploit (app_eq_nil s) ; eauto. intros [Heq Heq']. inv Heq.\n    split; eauto.\n  - destruct s0 ; simpl in *. inv H1.\n    destruct cs0 ; simpl in *. inv H2; split; eauto. congruence.\n    inv H1. destruct cs0; simpl in *. congruence.\n    inv H3.\n    inv H2.\n    exploit IHmatch_stacks; eauto.\n    intros [Hmatch Hmatch']; split; eauto.\n  - destruct s0 ; simpl in *. inv H1.\n    destruct cs0 ; simpl in *. inv H2; split; eauto. congruence.\n    inv H1. destruct cs0; simpl in *. congruence.\n    inv H3.\n    inv H2.\n    exploit IHmatch_stacks; eauto.\n    intros [Hmatch Hmatch']; split; eauto.\nQed.\n\nHint Constructors pop_to_return : core.\n\nLemma match_stacks_c_pop_to_return :\n  forall astk cstk rpc rpcl b1 b2 cstk'\n         (MATCH : match_stacks astk cstk)\n         (POP : c_pop_to_return cstk (CRet (rpc, rpcl) b1 b2 :: cstk')),\n    exists rpcl' astk',\n      pop_to_return astk (ARet (rpc, rpcl') b1 :: astk') /\\\n      rpcl = labToZ rpcl' /\\\n      match_stacks astk' cstk'.\nProof.\n  intros.\n  gdep astk.\n  match type of POP with\n    | c_pop_to_return _ ?CSTK =>\n      remember CSTK as cstk''\n  end.\n  induction POP; subst;\n  intros astk MATCH; inv MATCH; try inv Heqcstk''; eauto;\n  repeat match goal with\n           | A : Atom |- _ => destruct A; simpl in *\n           | H : (_, _) = (_, _) |- _ => inv H; simpl in *\n         end;\n  eauto.\n  guess tt IHPOP.\n  destruct IHPOP as [? [? [? [? ?]]]].\n  subst. eauto 7.\nQed.\nHint Resolve match_stacks_c_pop_to_return : core.\n\n(** Generic fault handler code *)\nVariable fetch_rule_g : forall (o: OpCode), AllowModify (labelCount o).\n\nDefinition fetch_rule_impl : fetch_rule_impl_type :=\n  fun o => existT _ (labelCount o) (fetch_rule_g o).\n\nDefinition LCL := LatticeConcreteLabels fetch_rule_impl.\n\nDefinition cache_up2date tmuc :=\n  forall opcode vls pcl,\n    cache_hit tmuc (opCodeToZ opcode) (labsToZs vls) (labToZ pcl) ->\n    match apply_rule (fetch_rule_g opcode) pcl vls with\n      | Some (rpcl,rl) => cache_hit_read tmuc (labToZ rl) (labToZ rpcl)\n      | None => False\n    end.\n\nDefinition cache_up2date_weak tmuc :=\n  forall opcode vls pcl rl rpcl,\n  forall (RULE: apply_rule (fetch_rule_g opcode) pcl vls = Some (rpcl, rl)),\n  forall (CHIT: cache_hit tmuc (opCodeToZ opcode) (labsToZs vls) (labToZ pcl)),\n         cache_hit_read tmuc (labToZ rl) (labToZ rpcl).\n\nLemma cache_up2date_success :\n  forall tmuc, cache_up2date tmuc -> cache_up2date_weak tmuc.\nProof.\n  unfold cache_up2date, cache_up2date_weak.\n  intros.\n  specialize (H opcode vls pcl CHIT).\n  rewrite RULE in H.\n  trivial.\nQed.\n\nDefinition faultHandler := @FaultRoutine.faultHandler L ELatt labelCount\n                                                      (ifc_run_tmr fetch_rule_g)\n                                                      LCL.\n\nInductive match_states : @AS L -> CS -> Prop :=\n ms: forall am cm i astk tmuc cstk apc cpc\n              (CACHE: cache_up2date tmuc)\n              (STKS: match_stacks astk cstk)\n              (MEM: cm = mem_labToZ am)\n              (PC: cpc = atom_labToZ apc),\n         match_states (AState am i astk apc)\n                      (CState tmuc cm faultHandler i cstk cpc false).\n\nLemma opCodeToZ_inj: forall o1 o2, opCodeToZ o1 = opCodeToZ o2 -> o1 = o2.\nProof.\n  intros o1 o2 Heq.\n  destruct o1, o2; inv Heq; try congruence.\nQed.\n\nLemma labsToZs_cons_hd: forall n0 a v0 b v3,\n  S n0 <= 3 ->\n  labsToZs (Vector.cons L a n0 v0) = labsToZs (Vector.cons L b n0 v3) ->\n  a = b.\nProof.\n  intros.  inv H0.\n  unfold nth_labToZ in H2. destruct (le_lt_dec (S n0) 0).  inv l.\n  unfold Vector.nth_order in H2. simpl in H2.\n  apply labToZ_inj in H2.  auto.\nQed.\n\nLemma nth_labToZ_cons:\n  forall nth n a v,\n    nth_labToZ (Vector.cons L a n v) (S nth) = nth_labToZ v nth.\nProof.\n  induction n; intros.\n  - unfold nth_labToZ.\n    case_eq (le_lt_dec (S nth) 1); case_eq (le_lt_dec nth 0); intros; auto;\n    try (zify ; lia).\n  - unfold nth_labToZ.\n    case_eq (le_lt_dec (S (S n)) (S nth)); case_eq (le_lt_dec (S n) nth); intros; auto;\n    try (zify ; lia).\n    unfold Vector.nth_order. simpl. symmetry.\n    erewrite of_nat_lt_proof_irrel ; eauto.\nQed.\n\nLemma labsToZs_cons_tail:\n  forall n0 a v0 b v3,\n    (n0 <= 2)%nat ->\n    labsToZs (Vector.cons L a n0 v0) = labsToZs (Vector.cons L b n0 v3) ->\n    labsToZs v0 = labsToZs v3.\nProof.\n  intros. inv H0.\n  unfold labsToZs.\n  repeat (rewrite nth_labToZ_cons in H3). inv H3. clear H1.\n  repeat (rewrite nth_labToZ_cons in H4). inv H4. clear H1.\n  replace (nth_labToZ v0 2) with (nth_labToZ v3 2).\n  auto.\n  unfold nth_labToZ.\n  case_eq (le_lt_dec n0 2); intros; auto.\n  zify ; lia.\nQed.\n\n\nLemma labsToZs_inj: forall n (v1 v2: Vector.t L n), n <= 3 ->\n     labsToZs v1 = labsToZs v2 -> v1 = v2.\nProof.\n  intros n v1 v2.\n  set (P:= fun n (v1 v2: Vector.t L n) => n <= 3 -> labsToZs v1 = labsToZs v2 -> v1 = v2) in *.\n  eapply Vector.rect2 with (P0:= P); eauto.\n  unfold P. auto.\n  intros.\n  unfold P in *. intros.\n  exploit labsToZs_cons_hd; eauto. intros Heq ; inv Heq.\n  eapply labsToZs_cons_tail in H1; eauto.\n  exploit H ; eauto. zify; lia.\n  intros Heq. inv Heq.\n  reflexivity. zify ; lia.\nQed.\n\nDefinition abstract_action (ce : CEvent+\u03c4) : (@Event L)+\u03c4 :=\n  match ce with\n    | E (CEInt ca) => E (EInt (atom_ZToLab ca))\n    | Silent => Silent\n  end.\n\nDefinition concretize_action (ae : (@Event L)+\u03c4) : CEvent+\u03c4 :=\n  match ae with\n    | E (EInt aa) => E (CEInt (atom_labToZ aa))\n    | Silent => Silent\n  end.\n\nDefinition match_actions a1 a2 := concretize_action a1 = a2.\n\nLemma abstract_action_concretize_action :\n  forall ae, abstract_action (concretize_action ae) = ae.\nProof.\n  intros [[[xv xl]]|]; simpl; auto.\n  rewrite <- ZToLab_labToZ_id.\n  reflexivity.\nQed.\n\n\n(** The refinement proof itself. Generic in the rule table used to generate the fault handler *)\n\nSection RefQAC.\n\n(* Reconstruct the quasi_abstract label vector *)\nLtac quasi_abstract_labels :=\n  match goal with\n    | L : Type,\n      Latt : JoinSemiLattice ?L,\n      H : context[cache_hit _ _ (dontCare, dontCare, dontCare) _] |- _ =>\n      pose (vls := Vector.nil L)\n    | H : context[cache_hit _ _ (labToZ ?l, dontCare, dontCare) _] |- _ =>\n      pose (vls := Vector.cons _ l _ (Vector.nil _))\n    | H : context[cache_hit _ _ (labToZ ?l1, labToZ ?l2, dontCare) _] |- _ =>\n      pose (vls := Vector.cons _ l1 _ (Vector.cons _ l2 _ (Vector.nil _)))\n    | H : context[cache_hit _ _ (labToZ ?l1, labToZ ?l2, labToZ ?l3) _] |- _ =>\n      pose (vls := Vector.cons _ l1 _\n                               (Vector.cons _ l2 _\n                                            (Vector.cons _ l3 _ (Vector.nil _))))\n  end.\n\n(* Relate the results of a cache read to its arguments *)\nLtac analyze_cache_hit OP vls apcl:=\n  match goal with\n    | CACHE : cache_up2date _ |- _ =>\n      let H := fresh \"H\" in\n      generalize (@CACHE OP vls apcl);\n      intros H; guess tt H;\n      try match type of H with\n        | context[ (apply_rule (fetch_rule_g ?r) ?aapcl ?vvls) ] =>\n          destruct (apply_rule (fetch_rule_g r) aapcl vvls) as [[? ?]|] eqn:Happly ;\n            [| inv H]\n      end\n  end;\n  match goal with\n    | H1 : cache_hit_read _ _ _,\n      H2 : cache_hit_read _ _ _ |- _ =>\n      let H := fresh \"H\" in\n      generalize (cache_hit_read_determ H2 H1);\n        intros H;\n        destruct H;\n        subst;\n        clear H2\n      end.\n\n(** Cache hit case *)\n\nLemma cache_hit_simulation :\n  forall s1 s2 e2 s2'\n         (Hmatch : match_states s1 s2)\n         (Hs2' : priv s2' = false)\n         (Hstep : cstep s2 e2 s2'),\n    exists a1 s1', step_rules (ifc_run_tmr fetch_rule_g) s1 a1 s1' /\\\n                   match_actions a1 e2 /\\\n                   match_states s1' s2'.\nProof.\n  intros.\n  inv Hmatch.\n  unfold match_actions.\n  destruct apc as [apc apcl].\n  inv Hstep; simpl in *; try congruence;\n\n  (* Invert some hypotheses *)\n  repeat match goal with\n           | H : ?x = ?x |- _ => clear H\n           | H : match_stacks _ (_ ::: _) |- _ => inv H\n           | H : match_stacks _ (_ ++ _) |- _ =>\n             apply match_stacks_args' in H;\n             destruct H as [? [? [? [? ?]]]];\n             subst\n           | a : _,\n             H : (_, _) = atom_labToZ ?a |- _ =>\n             destruct a; simpl in H; inv H\n         end;\n\n  (* For the Load/Store cases *)\n  try_exploit read_m_labToZ';\n\n  (* For the Ret cases *)\n  try_exploit match_stacks_c_pop_to_return;\n\n  quasi_abstract_labels;\n\n  (* Find the current opcode *)\n  match goal with\n    | H : read_m _ _ = Some ?instr |- _ =>\n      let opcode := (eval compute in (opcode_of_instr instr)) in\n      match opcode with\n        | Some ?opcode => pose (OP := opcode)\n      end\n  end;\n\n  analyze_cache_hit OP vls apcl;\n\n  subst OP vls;\n\n  (* For the Store case *)\n  try_exploit upd_m_labToZ;\n\n  (* For the BranchNZ case *)\n  try match goal with\n        | |- context[if (?z =? 0) then _ else _ ] =>\n          let H := fresh \"H\" in\n          assert (H := Z.eqb_spec z 0);\n          destruct (z =? 0);\n          inv H\n      end;\n\n  try solve [\n        eexists; eexists; split; try split;\n        try [> once (econstructor; solve [compute; eauto]) ..];\n        repeat (constructor; eauto); simpl; f_equal; intuition\n      ].\n\n  - exists Silent.\n    exploit match_stacks_args; eauto. intros [args' [s' [Hargs' [Hmatchargs' Hmatchs']]]].\n    subst. eexists. split.\n\n    + eapply (step_call (ifc_run_tmr fetch_rule_g)); try solve [compute; eauto].\n      * symmetry. eapply match_stacks_length; eauto.\n      * eapply match_stacks_data; eauto.\n\n    + repeat (constructor; eauto); simpl; f_equal; intuition.\n      eauto using match_stacks_app.\nQed.\n\n(** Cache miss case *)\n\nLemma invalid_pc_no_step :\n  forall s1 e s2\n         (STEP : cstep s1 e s2)\n         (FAIL : fst (pc s1) < 0),\n    False.\nProof.\n  intros.\n  inv STEP; simpl in *;\n  unfold read_m in *;\n  generalize (Z.ltb_spec0 pcv 0);\n  let H := fresh \"H\" in\n  intros H;\n  destruct (pcv <? 0); inv H; intuition; congruence.\nQed.\n\nLemma kernel_run_success_fail_contra :\n  forall s1 s21 s22\n         (RUN1 : runsUntilUser s1 s21)\n         (RUN2 : runsToEnd s1 s22)\n         (FAIL : fst (pc s22) < 0),\n    False.\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  try match goal with\n        | [ H : runsToEnd _ _ |- _ ] =>\n          generalize (runsToEnd_l H);\n          intros\n      end;\n  try congruence;\n  eauto using invalid_pc_no_step ; eauto.\nQed.\n\nLemma kernel_fail_determ :\n  forall s1 s21 s22\n         (RUN1 : runsToEnd s1 s21)\n         (FAIL1 : fst (pc s21) < 0)\n         (RUN2 : runsToEnd s1 s22)\n         (FAIL2 : fst (pc s22) < 0),\n    s21 = s22.\nProof.\n  intros.\n  induction RUN1; inv RUN2; trivial;\n  try solve [exfalso; eauto using invalid_pc_no_step];\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.\nQed.\n\nLemma runsToEscape_determ :\n  forall s1 s21 s22\n         (RUN1 : runsToEscape s1 s21)\n         (RUN2 : runsToEscape s1 s22),\n    s21 = s22.\nProof.\n  intros.\n  inv RUN1; inv RUN2;\n  eauto using runsUntilUser_determ,\n              kernel_fail_determ;\n  try solve [exfalso; eauto using kernel_run_success_fail_contra];\n  try match goal with\n        | [ H : runsUntilUser _ _ |- _ ] =>\n          generalize (runsUntilUser_l H);\n          intros\n      end;\n  try match goal with\n        | [ H : runsToEnd _ _ |- _ ] =>\n          generalize (runsToEnd_l H);\n          intros\n      end;\n  try congruence.\nQed.\n\nLemma configuration_at_miss :\n  forall s1 s21 e2 s22\n         (MATCH : match_states s1 s21)\n         (STEP : cstep s21 e2 s22)\n         (PRIV : priv s22 = true),\n    exists opcode (vls : Vector.t L (projT1 (fetch_rule_impl opcode))),\n      cache_hit (cache s22) (opCodeToZ opcode)\n                (labsToZs vls) (labToZ (snd (apc s1))) /\\\n      mem s22 = mem s21 /\\\n      fhdl s22 = fhdl s21 /\\\n      imem s22 = imem s21 /\\\n      stk s22 = CRet (pc s21) false false :: stk s21 /\\\n      pc s22 = (0, handlerTag).\nProof.\n  intros.\n  inv MATCH.\n  inv STEP; simpl in *; try congruence;\n\n  (* Invert some hypotheses *)\n  repeat match goal with\n           | H : true = false |- _ => inv H\n           | H : ?x = ?x |- _ => clear H\n           | H : match_stacks _ (_ ::: _) |- _ => inv H\n           | H : match_stacks _ (_ ++ _) |- _ =>\n             apply match_stacks_args' in H;\n             destruct H as [? [? [? [? ?]]]];\n             subst\n           | a : _,\n             H : (_, _) = atom_labToZ ?a |- _ =>\n             destruct a; simpl in H; inv H\n         end;\n\n    (* For the Load case *)\n  try_exploit read_m_labToZ';\n\n  (* For the Ret cases *)\n  try_exploit match_stacks_c_pop_to_return;\n\n  try quasi_abstract_labels;\n\n  match goal with\n    | H : read_m _ _ = Some ?i |- _ =>\n      let oc := eval compute in (opcode_of_instr i) in\n      match oc with\n        | Some ?oc => (exists oc)\n      end\n  end;\n\n  exists vls; repeat econstructor;\n  unfold update_cache;\n  rewrite index_list_Z_update_list_list; eauto;\n  compute; reflexivity.\nQed.\n\nLemma update_cache_spec_rvec_cache_hit :\n  forall rpcl rl cache cache' op tags pc\n         (MATCH : handler_final_mem_matches rpcl rl cache cache')\n         (HIT : cache_hit cache op tags pc),\n    cache_hit cache' op tags pc.\nProof.\n  intros.\n  inv HIT;\n  repeat match goal with\n           | H : tag_in_mem _ _ _ |- _ =>\n             inv H\n           | H : tag_in_mem' _ _ _ |- _ =>\n             inv H\n         end.\n  destruct MATCH as [RES UP].\n  destruct RES.\n  econstructor; eauto; econstructor;\n  try solve [rewrite <- UP; eauto; compute; lia];\n  repeat match goal with\n           | H : tag_in_mem _ _ _ |- _ =>\n             inv H\n           | H : tag_in_mem' _ _ _ |- _ =>\n             inv H\n         end;\n  eauto.\nQed.\n\nLemma cache_hit_unique:\n  forall c opcode opcode' labs labs' pcl pcl',\n    forall\n      (CHIT: cache_hit c opcode labs pcl)\n      (CHIT': cache_hit c opcode' labs' pcl'),\n      opcode = opcode' /\\\n      labs = labs' /\\\n      pcl = pcl'.\nProof.\n  intros. inv CHIT; inv CHIT'.\n  inv OP; inv OP0.\n  inv TAG1; inv TAG0.\n  inv TAG2; inv TAG4.\n  inv TAG3; inv TAG5.\n  inv TAGPC; inv TAGPC0.\n  repeat allinv'.\n  intuition.\nQed.\n\nLemma cache_miss_simulation :\n  forall s1 s21 e21 s22 s23\n         (MATCH : match_states s1 s21)\n         (STEP1 : cstep s21 e21 s22)\n         (RUN : runsUntilUser s22 s23),\n    match_states s1 s23.\nProof.\n  intros.\n  exploit runsUntilUser_l; eauto.\n  intros PRIV.\n  exploit configuration_at_miss; eauto.\n  intros [op [vls [HIT EQS]]].\n  destruct s22; simpl in EQS, PRIV; subst.\n  inv MATCH; simpl.\n  intuition. subst.\n  destruct (apply_rule (projT2 (fetch_rule_impl op)) (snd apc) vls)\n    as [[orl rpcl]|] eqn:E.\n  - exploit (handler_correct_succeed (CT := LCL)); eauto.\n    intros [cache' [ESCAPE1 MATCH']].\n    exploit rte_success; eauto.\n    intros ESCAPE2.\n    unfold faultHandler in *.\n    generalize (runsToEscape_determ ESCAPE1 ESCAPE2).\n    intros H. subst.\n    constructor; eauto.\n    simpl in *.\n    exploit update_cache_spec_rvec_cache_hit; eauto.\n    clear HIT. intros HIT.\n    intros op' vls' pcl' HIT'.\n    generalize (cache_hit_unique HIT HIT').\n    intros [E1 [E2 E3]].\n    apply opCodeToZ_inj in E1. subst.\n    apply labToZ_inj in E3. subst.\n    apply labsToZs_inj in E2.\n    + subst. rewrite E.\n      destruct MATCH'. trivial.\n    + destruct op'; simpl; lia.\n  - exploit (handler_correct_fail (CT := LCL)); eauto.\n    simpl in *.\n    intros [stk' ESCAPE1].\n    inv ESCAPE1.\n    + apply runsUntilUser_r in STAR. simpl in STAR. congruence.\n    + exfalso.\n      eapply kernel_run_success_fail_contra; eauto.\nQed.\n\nLemma filter_cons_inv :\n  forall A (f : A -> bool) a l1 l2,\n    a :: l1 = filter f l2 ->\n    exists l2', l1 = filter f l2'.\nProof.\n  induction l2 as [|a' l2 IH]; simpl. congruence.\n  destruct (f a'); intros H; auto.\n  inv H. eauto.\nQed.\n\nInductive ac_match_initial_data :\n  init_data abstract_machine ->\n  init_data (concrete_machine faultHandler) -> Prop :=\n| ac_mid : forall d1 p1 n1 b1,\n             ac_match_initial_data\n               (p1, d1, n1, b1)\n               (p1, mem_labToZ d1, n1, labToZ b1).\n\nLemma match_init_stacks: forall d1,\n match_stacks (map (fun a : Atom => AData a) d1)\n     (map (fun a : Atom => CData a) (mem_labToZ d1)).\nProof.\n  induction d1 ; intros;\n  (simpl ; constructor; auto).\nQed.\n\nLemma replicate_mem_labToZ :\n  forall b n,\n    replicate (0, labToZ b) n = mem_labToZ (replicate (0, b) n).\nProof.\n  induction n ; intros.\n  auto.\n  simpl. inv IHn. auto.\nQed.\n\nLemma ac_match_initial_data_match_initial_states :\n  forall ai ci,\n    ac_match_initial_data ai ci ->\n    match_states (init_state abstract_machine ai)\n                      (init_state (concrete_machine faultHandler) ci).\nProof.\n  intros ai ci H. inv H.\n  simpl in *.\n  constructor; simpl; eauto.\n  - intros op vls pcl contra.\n    inv contra.\n    destruct op;\n    destruct OP as [OP]; inv OP.\n  - apply match_init_stacks.\n  - apply replicate_mem_labToZ.\nQed.\n\n(** Notions of concrete executions for proving this refinement *)\nSection CExec.\n\n(* congruence fails if this is let-bound *)\nLocal Notation ctrace := (list CEvent).\n\nLet cons_event e t : ctrace :=\n  match e with\n    | E e => e :: t\n    | Silent => t\n  end.\n\nInductive exec_end : CS -> CS -> Prop :=\n| ee_refl : forall s, exec_end s s\n| ee_kernel_end : forall s s', runsToEnd s s' -> exec_end s s'\n| ee_final_fault : forall s s' s'',\n                     priv s = false ->\n                     cstep s Silent s' ->\n                     runsToEnd s' s'' ->\n                     exec_end s s''.\nHint Constructors exec_end : core.\n\nInductive cexec : CS -> ctrace -> CS -> Prop :=\n| ce_end : forall s s', exec_end s s' -> cexec s nil s'\n| ce_kernel_begin : forall s s' t s'',\n                      runsUntilUser s s' ->\n                      cexec s' t s'' ->\n                      cexec s t s''\n| ce_user_hit : forall s e s' t s'',\n                  priv s = false ->\n                  cstep s e s' ->\n                  priv s' = false ->\n                  cexec s' t s'' ->\n                  cexec s (cons_event e t) s''\n| ce_user_miss : forall s s' s'' t s''',\n                   priv s = false ->\n                   cstep s Silent s' ->\n                   runsUntilUser s' s'' ->\n                   cexec s'' t s''' ->\n                   cexec s t s'''.\nHint Constructors cexec : core.\n\nLemma exec_end_step : forall s e s' s''\n                             (STEP : cstep s e s')\n                             (EXEC : exec_end s' s''),\n                        cexec s (cons_event e nil) s''.\nProof.\n  intros.\n  destruct (priv s) eqn:PRIV;\n  [exploit priv_no_event_l; eauto; intros ?; subst|];\n  (destruct (priv s') eqn:PRIV';\n  [exploit priv_no_event_r; eauto; intros ?; subst|]);\n  inv EXEC; eauto.\nQed.\nHint Resolve exec_end_step : core.\n\nLemma cexec_step : forall s e s' t s''\n                          (Hstep : cstep s e s')\n                          (Hexec : cexec s' t s''),\n                          cexec s (cons_event e t) s''.\nProof.\n  intros.\n  inv Hexec; simpl; eauto;\n  (destruct (priv s) eqn:PRIV;\n   [assert (e = Silent) by (eapply priv_no_event_l; eauto); subst|]);\n  eauto.\n  - exploit priv_no_event_r; eauto.\n    intros ?. subst.\n    eauto.\n  - subst. simpl.\n    eapply ce_kernel_begin; eauto.\nQed.\n\nDefinition is_E {T} (a:T+\u03c4) : bool :=\n  match a with\n    | Silent => false\n    | E _ => true\n  end.\n\nLemma exec_cexec : forall s t s',\n                     (@TINI.exec (concrete_machine faultHandler)) s t s' ->\n                     cexec s t s'.\nProof.\n  intros s t s' Hexec.\n  induction Hexec; eauto.\n  eapply cexec_step with (e:=E e); eauto.\n  eapply cexec_step with (e:=Silent); eauto.\nQed.\n\nEnd CExec.\n\nDefinition match_events (e1:@Event L) (e2:CEvent) : Prop :=\n  match e1 with\n      EInt aa => CEInt (atom_labToZ aa) = e2\n  end.\n\nLemma quasi_abstract_concrete_sref_prop :\n  @state_refinement_statement (ifc_quasi_abstract_machine fetch_rule_g)\n                              (concrete_machine faultHandler)\n                              match_states match_events.\nProof.\n  intros s1 s2 t2 s2' MATCH EXEC. simpl.\n  apply exec_cexec in EXEC.\n  match type of EXEC with\n    | cexec _ ?T _ =>\n      remember T as t2'\n  end.\n  gdep t2. gdep s1.\n  unfold remove_none.\n  induction EXEC; intros s1 MATCH t2 Ht2; unfold remove_none.\n  - exists nil. exists s1.\n    split. constructor.\n    constructor.\n  - inv MATCH.\n    apply runsUntilUser_l in H.\n    inv H.\n  - exploit cache_hit_simulation; eauto.\n    intros [e1 [s1' [STEP [ME MS]]]].\n    unfold match_actions in *. subst.\n    exploit IHEXEC; eauto.\n    intros [t1 [? [? ?]]].\n    destruct e1; simpl.\n    + exists (e::t1). eexists.\n      split. econstructor 2; eauto.\n      simpl. destruct e; simpl; eauto.\n      constructor; auto.\n      constructor; auto.\n    + exists (t1). eexists.\n      split. econstructor; eauto.\n      auto.\n\n  - exploit cache_miss_simulation; eauto.\nQed.\n\nDefinition quasi_abstract_concrete_sref :=\n  {| sref_prop := quasi_abstract_concrete_sref_prop |}.\n\nDefinition quasi_abstract_concrete_ref :\n  refinement (ifc_quasi_abstract_machine fetch_rule_g)\n             (concrete_machine faultHandler) :=\n  @refinement_from_state_refinement _ _\n                                    quasi_abstract_concrete_sref\n                                    ac_match_initial_data\n                                    ac_match_initial_data_match_initial_states.\n\n\nEnd RefQAC.\nEnd MatchAbstractConcrete.\n\n(** * Combining the above into the final result *)\n(** This is where we instantiate the generic refinement. *)\nSection RefAC.\n\nContext {observer: Type}\n        {Latt: JoinSemiLattice observer}\n        {CLatt: ConcreteLattice observer}\n        {ELatt : Encodable observer}\n        {WFCLatt: WfConcreteLattice observer Latt CLatt ELatt}.\n\nDefinition tini_fetch_rule_withsig :=\n  (fun opcode => existT _\n                        (QuasiAbstractMachine.labelCount opcode)\n                        (QuasiAbstractMachine.fetch_rule opcode)).\nDefinition tini_faultHandler := @FaultRoutine.faultHandler observer ELatt\n                                                           labelCount\n                                                           (ifc_run_tmr fetch_rule)\n                                                           (LatticeConcreteLabels (fetch_rule_impl fetch_rule)).\nDefinition tini_match_states := match_states QuasiAbstractMachine.fetch_rule.\n\nDefinition tini_concrete_machine := concrete_machine tini_faultHandler.\n\nProgram Definition abstract_concrete_ref :\n  refinement abstract_machine tini_concrete_machine :=\n  @ref_composition _ _ _\n                   abstract_quasi_abstract_ref\n                   (quasi_abstract_concrete_ref fetch_rule)\n                   (@ac_match_initial_data _ _ _ _ _ fetch_rule)\n                   match_events\n                   _ _.\n\nNext Obligation.\n  eauto.\nQed.\n\nEnd RefAC.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/basic_machines/RefinementAC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.29746994260479465, "lm_q1q2_score": 0.19897176873508246}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import ITreeLang.\n\nRequire Import PromiseConsistent.\n\nRequire Import FulfillStep.\n\nRequire Import iPromotionDef.\nRequire Import SimCommon.\n\nSet Implicit Arguments.\n\n\nModule SimThreadOther.\n  Import SimCommon.\n  Section TYPE.\n  Variable R: Type.\n\n  Inductive sim_thread (l: Loc.t) (e_src e_tgt: Thread.t (lang R)): Prop :=\n  | sim_thread_intro\n      (LOCFREE: loc_free_itree l (Thread.state e_src))\n      (STATE: (Thread.state e_src) = (Thread.state e_tgt))\n      (LOCAL: sim_local l (Thread.local e_src) (Thread.local e_tgt))\n      (SC: sim_timemap l (Thread.sc e_src) (Thread.sc e_tgt))\n      (MEMORY: sim_memory l (Thread.memory e_src) (Thread.memory e_tgt))\n      (PROMISES: forall to, Memory.get l to (Local.promises (Thread.local e_src)) = None)\n      (FULFILLABLE: fulfillable l (Local.tview (Thread.local e_src)) (Thread.memory e_src)\n                                  (Local.promises (Thread.local e_src)))\n  .\n  Hint Constructors sim_thread: core.\n\n  Lemma sim_thread_promise_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (STEP_TGT: Thread.promise_step pf e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_promise_step e_src e1_src e2_src>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e2_src)>>.\n  Proof.\n    inversion STEP_TGT. subst.\n    destruct (Loc.eq_dec loc l).\n    { subst. inv LOCAL; ss.\n      esplits; [econs 1| |]; eauto.\n      inv SIM1. ss.\n      exploit promise_loc; try exact PROMISE; try apply LOCAL; eauto. i. des.\n      econs; ss; eauto.\n      econs; ss; eauto; try apply LOCAL.\n    }\n    exploit promise_step; try exact LOCAL; try apply SIM1;\n      try apply WF1_SRC; try apply WF1_TGT; eauto.\n    i. des.\n    destruct e1_src. ss.\n    esplits.\n    - econs 2. econs; eauto.\n    - inv SIM1. ss. econs; eauto; ss.\n      i. inv STEP_SRC.\n      erewrite Memory.promise_get_diff_promise; try exact PROMISE; eauto.\n    - i. s. inv STEP_SRC.\n      erewrite <- Memory.promise_get_diff; try exact PROMISE; eauto.\n  Qed.\n\n  Lemma sim_thread_program_step\n        l e1_src\n        e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.program_step e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_program_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e2_src)>>.\n  Proof.\n    inv STEP_TGT; ss.\n    hexploit loc_free_step_is_accessing_loc; eauto; i.\n    { inv SIM1. ss. subst. eauto. }\n    exploit program_step; try exact LOCAL; try eapply SIM1; eauto. i. des.\n    destruct e1_src. ss.\n    esplits.\n    - econs 2. econs; try exact STEP_SRC.\n      inv SIM1. inv STATE0. ss.\n      rewrite H0. rewrite EVENT2. eauto.\n    - ss.\n    - econs; eauto.\n      + s. eapply step_loc_free; eauto.\n        inv SIM1. ss. subst. ss.\n      + s. i. inv SIM1. ss.\n        erewrite <- Local.program_step_get_diff_promises; eauto.\n        erewrite ThreadEvent.eq_program_event_eq_loc; eauto.\n    - s. i.\n      eapply Local.program_step_get_diff; eauto.\n      erewrite ThreadEvent.eq_program_event_eq_loc; eauto.\n  Qed.\n\n  Lemma sim_thread_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.step pf e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e2_src)>>.\n  Proof.\n    inv STEP_TGT.\n    - exploit sim_thread_promise_step; eauto. i. des.\n      esplits.\n      + inv STEP_SRC.\n        * econs 1.\n        * econs 2. econs 1; eauto.\n      + inv STEP. ss. inv STEP_SRC; ss. inv STEP. ss.\n      + ss.\n      + ss.\n    - exploit sim_thread_program_step; eauto. i. des.\n      esplits.\n      + inv STEP_SRC.\n        * econs 1.\n        * econs 2. econs 2; eauto.\n      + ss.\n      + ss.\n      + ss.\n  Qed.\n\n  Lemma sim_thread_opt_step\n        l e1_src\n        e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.opt_step e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e2_src)>>.\n  Proof.\n    inv STEP_TGT.\n    - esplits; eauto. econs 1.\n    - exploit sim_thread_step; eauto.\n  Qed.\n\n  Lemma sim_thread_rtc_tau_step\n        l e1_src\n        e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang R)) e1_tgt e2_tgt):\n    exists e2_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e2_src)>>.\n  Proof.\n    revert e1_src SIM1 WF1_SRC SC1_SRC CLOSED1_SRC.\n    induction STEPS_TGT; i.\n    - esplits; eauto.\n    - inv H. inv TSTEP.\n      exploit sim_thread_step; eauto. i. des.\n      exploit Thread.step_future; try exact STEP; eauto. i. des.\n      exploit Thread.opt_step_future; try exact STEP_SRC; eauto. i. des.\n      exploit IHSTEPS_TGT; eauto. i. des.\n      inv STEP_SRC.\n      + esplits; eauto.\n      + esplits; [M|..]; eauto.\n        * econs; [|eauto].\n          econs; [econs; eauto|]. rewrite <- EVENT. ss.\n        * i. rewrite MEMLOC. ss.\n  Qed.\n\n  Lemma sim_thread_plus_step\n        l e1_src\n        e_tgt e1_tgt e2_tgt e3_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang R)) e1_tgt e2_tgt)\n        (STEP_TGT: Thread.opt_step e_tgt e2_tgt e3_tgt):\n    exists e_src e2_src e3_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<STEP_SRC: Thread.opt_step e_src e2_src e3_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM3: sim_thread l e3_src e3_tgt>> /\\\n      <<MEMLOC: forall to, Memory.get l to (Thread.memory e1_src) = Memory.get l to (Thread.memory e3_src)>>.\n  Proof.\n    exploit sim_thread_rtc_tau_step; eauto. i. des.\n    exploit Thread.rtc_tau_step_future; try exact STEPS_SRC; eauto. i. des.\n    exploit Thread.rtc_tau_step_future; try exact STEPS_TGT; eauto. i. des.\n    exploit sim_thread_opt_step; eauto. i. des.\n    esplits; eauto.\n    i. rewrite MEMLOC. ss.\n  Qed.\n\n\n  (* future *)\n\n  Lemma sim_thread_future\n        l\n        st_src lc_src sc1_src mem1_src sc2_src mem2_src\n        st_tgt lc_tgt sc1_tgt mem1_tgt sc2_tgt mem2_tgt\n        (SIM1: sim_thread l\n                          (Thread.mk (lang R) st_src lc_src sc1_src mem1_src)\n                          (Thread.mk (lang R) st_tgt lc_tgt sc1_tgt mem1_tgt))\n        (WF1_SRC: Local.wf lc_src mem1_src)\n        (MEM_SRC: Memory.future mem1_src mem2_src)\n        (SC: sim_timemap l sc2_src sc2_tgt)\n        (MEM: sim_memory l mem2_src mem2_tgt)\n        (PREV: Memory.prev_None mem1_src mem2_src):\n    sim_thread l\n               (Thread.mk (lang R) st_src lc_src sc2_src mem2_src)\n               (Thread.mk (lang R) st_tgt lc_tgt sc2_tgt mem2_tgt).\n  Proof.\n    inv SIM1. ss. econs; s; eauto. ii.\n    exploit FULFILLABLE; eauto. i. des. split; ss.\n    unfold prev_released_le_loc in *. des_ifs; ss.\n    - exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n      inv MSG_LE. inv RELEASED; try congr.\n      rewrite Heq in *. inv GET.\n      unnw. etrans; eauto. split; apply LE.\n    - exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n      inv MSG_LE. inv RELEASED; try congr.\n    - exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n      rewrite GET in *. inv Heq. inv MSG_LE.\n    - inv WF1_SRC. exploit PROMISES0; eauto. i.\n      exploit PREV; eauto; ss. ii. congr.\n    - inv WF1_SRC. exploit PROMISES0; eauto. i.\n      exploit PREV; eauto; ss. ii. congr.\n  Qed.\n\n\n  (* terminal *)\n\n  Lemma sim_thread_promises_bot\n        l e_src e_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (PROMISES_TGT: (Local.promises (Thread.local e_tgt)) = Memory.bot):\n    <<PROMISES_SRC: (Local.promises (Thread.local e_src)) = Memory.bot>>.\n  Proof.\n    inv SIM. inv LOCAL. apply Memory.ext. i.\n    rewrite Memory.bot_get.\n    destruct (Loc.eq_dec loc l); subst; ss.\n    symmetry in PROMISES1.\n    exploit sim_memory_get_None_src; eauto.\n    rewrite PROMISES_TGT. rewrite Memory.bot_get. ss.\n  Qed.\n\n  Lemma sim_thread_terminal\n        l e_src e_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (TERMINAL_TGT: (Language.is_terminal (lang R)) (Thread.state e_tgt)):\n    <<TERMINAL_SRC: (Language.is_terminal (lang R)) (Thread.state e_src)>>.\n  Proof.\n    inv SIM. rewrite STATE. ss.\n  Qed.\n\n\n  (* certification *)\n\n  Lemma sim_thread_cap\n        l e_src e_tgt\n        cap_src cap_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (WF_SRC: Local.wf (Thread.local e_src) (Thread.memory e_src))\n        (WF_TGT: Local.wf (Thread.local e_tgt) (Thread.memory e_tgt))\n        (CLOSED_SRC: Memory.closed (Thread.memory e_src))\n        (CLOSED_TGT: Memory.closed (Thread.memory e_tgt))\n        (CAP_SRC: Memory.cap (Thread.memory e_src) cap_src)\n        (CAP_TGT: Memory.cap (Thread.memory e_tgt) cap_tgt):\n    sim_thread l\n               (Thread.mk (lang R) (Thread.state e_src) (Thread.local e_src) (Thread.sc e_src) cap_src)\n               (Thread.mk (lang R) (Thread.state e_tgt) (Thread.local e_tgt) (Thread.sc e_tgt) cap_tgt).\n  Proof.\n    inv SIM. inv LOCAL.\n    exploit sim_memory_cap; try exact MEMORY; eauto. i. des.\n    econs; eauto.\n    s. eapply cap_fulfillable; eauto. apply WF_SRC.\n  Qed.\n\n  Lemma sim_thread_consistent\n        l e_src e_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (WF_SRC: Local.wf (Thread.local e_src) (Thread.memory e_src))\n        (WF_TGT: Local.wf (Thread.local e_tgt) (Thread.memory e_tgt))\n        (SC_SRC: Memory.closed_timemap (Thread.sc e_src) (Thread.memory e_src))\n        (SC_TGT: Memory.closed_timemap (Thread.sc e_tgt) (Thread.memory e_tgt))\n        (CLOSED_SRC: Memory.closed (Thread.memory e_src))\n        (CLOSED_TGT: Memory.closed (Thread.memory e_tgt))\n        (CONSISTENT_TGT: Thread.consistent e_tgt):\n    <<CONSISTENT_SRC: Thread.consistent e_src>>.\n  Proof.\n    exploit Memory.cap_exists; try exact CLOSED_TGT. i. des.\n    exploit Memory.cap_closed; eauto. ii.\n    exploit sim_thread_cap; try exact SIM; try exact CAP0; try exact CAP; eauto. i.\n    exploit Local.cap_wf; try exact WF_SRC; eauto. intro WF_CAP_SRC.\n    exploit Local.cap_wf; try exact WF_TGT; eauto. intro WF_CAP_TGT.\n    hexploit Memory.cap_closed_timemap; try exact SC_SRC; eauto. i.\n    hexploit Memory.cap_closed_timemap; try exact SC_TGT; eauto. i.\n    exploit Memory.cap_closed; try exact CLOSED_SRC; eauto. intro CLOSED_CAP_SRC.\n    exploit Memory.cap_closed; try exact CLOSED_TGT; eauto. intro CLOSED_CAP_TGT.\n    exploit CONSISTENT_TGT; eauto. i. des.\n    - left. unfold Thread.steps_failure in *. des.\n      exploit sim_thread_plus_step; eauto.\n      { econs 2; eauto. }\n      s. i. des.\n      inv STEP_SRC; ss; try congr.\n      destruct pf; try by (inv STEP; inv STEP0; ss; congr).\n      esplits; eauto. congr.\n    - right.\n      exploit sim_thread_rtc_tau_step; try exact STEPS; eauto. i. des.\n      esplits; eauto.\n      eapply sim_thread_promises_bot; eauto.\n  Qed.\n  End TYPE.\nEnd SimThreadOther.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/promotion/iSimThreadOther.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19886229715274964}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Function calling conventions and other conventions regarding the use of \n    machine registers and stack slots. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Events.\nRequire Import Locations.\nRequire Archi.\n\n(** * Classification of machine registers *)\n\n(** Machine registers (type [mreg] in module [Locations]) are divided in\n  the following groups:\n- Temporaries used for spilling, reloading, and parallel move operations.\n- Allocatable registers, that can be assigned to RTL pseudo-registers.\n  These are further divided into:\n-- Callee-save registers, whose value is preserved across a function call.\n-- Caller-save registers that can be modified during a function call.\n\n  We follow the ARM application binary interface (EABI) in our choice\n  of callee- and caller-save registers.\n*)\n\nDefinition int_caller_save_regs :=\n  R0 :: R1 :: R2 :: R3 :: R12 :: nil.\n\nDefinition float_caller_save_regs :=\n  F0 :: F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: nil.\n\nDefinition int_callee_save_regs :=\n  R4 :: R5 :: R6 :: R7 :: R8 :: R9 :: R10 :: R11 :: nil.\n\nDefinition float_callee_save_regs :=\n  F8 :: F9 :: F10 :: F11 :: F12 :: F13 :: F14 :: F15 :: nil.\n\nDefinition destroyed_at_call :=\n  int_caller_save_regs ++ float_caller_save_regs.\n\nDefinition dummy_int_reg := R0.     (**r Used in [Coloring]. *)\nDefinition dummy_float_reg := F0.   (**r Used in [Coloring]. *)\n\n(** The [index_int_callee_save] and [index_float_callee_save] associate\n  a unique positive integer to callee-save registers.  This integer is\n  used in [Stacking] to determine where to save these registers in\n  the activation record if they are used by the current function. *)\n\nDefinition index_int_callee_save (r: mreg) :=\n  match r with\n  | R4 => 0  | R5 => 1  | R6 => 2  | R7 => 3\n  | R8 => 4  | R9 => 5  | R10 => 6 | R11 => 7\n  | _ => -1\n  end.\n\nDefinition index_float_callee_save (r: mreg) :=\n  match r with\n  | F8 => 0  | F9 => 1  | F10 => 2  | F11 => 3\n  | F12 => 4  | F13 => 5  | F14 => 6  | F15 => 7\n  | _ => -1\n  end.\n\nLtac ElimOrEq :=\n  match goal with\n  |  |- (?x = ?y) \\/ _ -> _ =>\n       let H := fresh in\n       (intro H; elim H; clear H;\n        [intro H; rewrite <- H; clear H | ElimOrEq])\n  |  |- False -> _ =>\n       let H := fresh in (intro H; contradiction)\n  end.\n\nLtac OrEq :=\n  match goal with\n  | |- (?x = ?x) \\/ _ => left; reflexivity\n  | |- (?x = ?y) \\/ _ => right; OrEq\n  | |- False => fail\n  end.\n\nLtac NotOrEq :=\n  match goal with\n  | |- (?x = ?y) \\/ _ -> False =>\n       let H := fresh in (\n       intro H; elim H; clear H; [intro; discriminate | NotOrEq])\n  | |- False -> False =>\n       contradiction\n  end.\n\nLemma index_int_callee_save_pos:\n  forall r, In r int_callee_save_regs -> index_int_callee_save r >= 0.\nProof.\n  intro r. simpl; ElimOrEq; unfold index_int_callee_save; omega.\nQed.\n\nLemma index_float_callee_save_pos:\n  forall r, In r float_callee_save_regs -> index_float_callee_save r >= 0.\nProof.\n  intro r. simpl; ElimOrEq; unfold index_float_callee_save; omega.\nQed.\n\nLemma index_int_callee_save_pos2:\n  forall r, index_int_callee_save r >= 0 -> In r int_callee_save_regs.\nProof.\n  destruct r; simpl; intro; omegaContradiction || OrEq.\nQed.\n\nLemma index_float_callee_save_pos2:\n  forall r, index_float_callee_save r >= 0 -> In r float_callee_save_regs.\nProof.\n  destruct r; simpl; intro; omegaContradiction || OrEq.\nQed.\n\nLemma index_int_callee_save_inj:\n  forall r1 r2, \n  In r1 int_callee_save_regs ->\n  In r2 int_callee_save_regs ->\n  r1 <> r2 ->\n  index_int_callee_save r1 <> index_int_callee_save r2.\nProof.\n  intros r1 r2. \n  simpl; ElimOrEq; ElimOrEq; unfold index_int_callee_save;\n  intros; congruence.\nQed.\n\nLemma index_float_callee_save_inj:\n  forall r1 r2, \n  In r1 float_callee_save_regs ->\n  In r2 float_callee_save_regs ->\n  r1 <> r2 ->\n  index_float_callee_save r1 <> index_float_callee_save r2.\nProof.\n  intros r1 r2. \n  simpl; ElimOrEq; ElimOrEq; unfold index_float_callee_save;\n  intros; congruence.\nQed.\n\n(** The following lemmas show that\n    (temporaries, destroyed at call, integer callee-save, float callee-save)\n    is a partition of the set of machine registers. *)\n\nLemma int_float_callee_save_disjoint:\n  list_disjoint int_callee_save_regs float_callee_save_regs.\nProof.\n  red; intros r1 r2. simpl; ElimOrEq; ElimOrEq; discriminate.\nQed.\n\nLemma register_classification:\n  forall r, \n  In r destroyed_at_call \\/ In r int_callee_save_regs \\/ In r float_callee_save_regs.\nProof.\n  destruct r; \n  try (left; simpl; OrEq);\n  try (right; left; simpl; OrEq);\n  try (right; right; simpl; OrEq).\nQed.\n\n\nLemma int_callee_save_not_destroyed:\n  forall r, \n    In r destroyed_at_call -> In r int_callee_save_regs -> False.\nProof.\n  intros. revert H0 H. simpl. ElimOrEq; NotOrEq.\nQed.\n\nLemma float_callee_save_not_destroyed:\n  forall r, \n    In r destroyed_at_call -> In r float_callee_save_regs -> False.\nProof.\n  intros. revert H0 H. simpl. ElimOrEq; NotOrEq.\nQed.\n\nLemma int_callee_save_type:\n  forall r, In r int_callee_save_regs -> mreg_type r = Tany32.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLemma float_callee_save_type:\n  forall r, In r float_callee_save_regs -> mreg_type r = Tany64.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLtac NoRepet :=\n  match goal with\n  | |- list_norepet nil =>\n      apply list_norepet_nil\n  | |- list_norepet (?a :: ?b) =>\n      apply list_norepet_cons; [simpl; intuition discriminate | NoRepet]\n  end.\n\nLemma int_callee_save_norepet:\n  list_norepet int_callee_save_regs.\nProof.\n  unfold int_callee_save_regs; NoRepet.\nQed.\n\nLemma float_callee_save_norepet:\n  list_norepet float_callee_save_regs.\nProof.\n  unfold float_callee_save_regs; NoRepet.\nQed.\n\n(** * Function calling conventions *)\n\n(** The functions in this section determine the locations (machine registers\n  and stack slots) used to communicate arguments and results between the\n  caller and the callee during function calls.  These locations are functions\n  of the signature of the function and of the call instruction.  \n  Agreement between the caller and the callee on the locations to use\n  is guaranteed by our dynamic semantics for Cminor and RTL, which demand \n  that the signature of the call instruction is identical to that of the\n  called function.\n\n  Calling conventions are largely arbitrary: they must respect the properties\n  proved in this section (such as no overlapping between the locations\n  of function arguments), but this leaves much liberty in choosing actual\n  locations.  *)\n\n(** ** Location of function result *)\n\n(** The result value of a function is passed back to the caller in\n  registers [R0] or [F0] or [R0,R1], depending on the type of the\n  returned value.  We treat a function without result as a function\n  with one integer result.\n\n  For the \"softfloat\" convention, results of FP types should be passed\n  in [R0] or [R0,R1].  This doesn't fit the CompCert register model,\n  so we have code in [arm/PrintAsm.ml] that inserts additional moves\n  to/from [F0]. *)\n\nDefinition loc_result (s: signature) : list mreg :=\n  match s.(sig_res) with\n  | None => R0 :: nil\n  | Some (Tint | Tany32) => R0 :: nil\n  | Some (Tfloat | Tsingle | Tany64) => F0 :: nil\n  | Some Tlong => R1 :: R0 :: nil\n  end.\n\n(** The result registers have types compatible with that given in the signature. *)\n\nLemma loc_result_type:\n  forall sig,\n  subtype_list (proj_sig_res' sig) (map mreg_type (loc_result sig)) = true.\nProof.\n  intros. unfold proj_sig_res', loc_result. destruct (sig_res sig) as [[]|]; auto.\nQed.\n\n(** The result locations are caller-save registers *)\n\nLemma loc_result_caller_save:\n  forall (s: signature) (r: mreg), \n  In r (loc_result s) -> In r destroyed_at_call.\nProof.\n  intros.\n  assert (r = R0 \\/ r = R1 \\/ r = F0).\n    unfold loc_result in H. destruct (sig_res s); [destruct t|idtac]; simpl in H; intuition.\n  destruct H0 as [A | [A | A]]; subst r; simpl; OrEq.\nQed.\n\n(** ** Location of function arguments *)\n\n(** For the \"hardfloat\" configuration, we use the following calling conventions,\n    adapted from the ARM EABI-HF:\n- The first 4 integer arguments are passed in registers [R0] to [R3].\n- The first 2 long integer arguments are passed in an aligned pair of\n  two integer registers.\n- The first 8 single- and double-precision float arguments are passed\n  in registers [F0...F7]\n- Extra arguments are passed on the stack, in [Outgoing] slots, consecutively\n  assigned (1 word for an integer or single argument, 2 words for a float\n  or a long), starting at word offset 0.\n\nThis convention is not quite that of the ARM EABI-HF, whereas single float\narguments are passed in 32-bit float registers.  Unfortunately,\nthis does not fit the data model of CompCert.  In [PrintAsm.ml]\nwe insert additional code around function calls that moves\ndata appropriately. *)\n\nDefinition int_param_regs :=\n  R0 :: R1 :: R2 :: R3 :: nil.\n\nDefinition float_param_regs :=\n  F0 :: F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: nil.\n\nDefinition ireg_param (n: Z) : mreg :=\n  match list_nth_z int_param_regs n with Some r => r | None => R0 end.\n\nDefinition freg_param (n: Z) : mreg :=\n  match list_nth_z float_param_regs n with Some r => r | None => F0 end.\n\nFixpoint loc_arguments_hf\n     (tyl: list typ) (ir fr ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | (Tint | Tany32) as ty :: tys =>\n      if zlt ir 4\n      then R (ireg_param ir) :: loc_arguments_hf tys (ir + 1) fr ofs\n      else S Outgoing ofs ty :: loc_arguments_hf tys ir fr (ofs + 1)\n  | (Tfloat | Tany64) as ty :: tys =>\n      if zlt fr 8\n      then R (freg_param fr) :: loc_arguments_hf tys ir (fr + 1) ofs\n      else let ofs := align ofs 2 in\n           S Outgoing ofs ty :: loc_arguments_hf tys ir fr (ofs + 2)\n  | Tsingle :: tys =>\n      if zlt fr 8\n      then R (freg_param fr) :: loc_arguments_hf tys ir (fr + 1) ofs\n      else S Outgoing ofs Tsingle :: loc_arguments_hf tys ir fr (ofs + 1)\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      if zlt ir 4\n      then R (ireg_param (ir + 1)) :: R (ireg_param ir) :: loc_arguments_hf tys (ir + 2) fr ofs\n      else let ofs := align ofs 2 in\n          S Outgoing (ofs + 1) Tint :: S Outgoing ofs Tint :: loc_arguments_hf tys ir fr (ofs + 2)\n  end.\n\n(** For the \"softfloat\" configuration, as well as for variable-argument functions\n  in the \"hardfloat\" configuration, we use the default ARM EABI (not HF)\n  calling conventions:\n- The first 4 integer arguments are passed in registers [R0] to [R3].\n- The first 2 long integer arguments are passed in an aligned pair of\n  two integer registers.\n- The first 2 double-precision float arguments are passed in [F0] or [F2]\n- The first 4 single-precision float arguments are passed in [F0...F3]\n- Integer arguments and float arguments are kept in sync so that\n  they can all be mapped back to [R0...R3] in [PrintAsm.ml].\n- Extra arguments are passed on the stack, in [Outgoing] slots, consecutively\n  assigned (1 word for an integer or single argument, 2 words for a float\n  or a long), starting at word offset 0.\n\nThis convention is not quite that of the ARM EABI, whereas every float\nargument are passed in one or two integer registers.  Unfortunately,\nthis does not fit the data model of CompCert.  In [PrintAsm.ml]\nwe insert additional code around function calls and returns that moves\ndata appropriately. *)\n\nFixpoint loc_arguments_sf\n     (tyl: list typ) (ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | (Tint|Tany32) as ty :: tys =>\n      (if zlt ofs 0 then R (ireg_param (ofs + 4)) else S Outgoing ofs ty)\n      :: loc_arguments_sf tys (ofs + 1)\n  | (Tfloat|Tany64) as ty :: tys =>\n      let ofs := align ofs 2 in\n      (if zlt ofs 0 then R (freg_param (ofs + 4)) else S Outgoing ofs ty)\n      :: loc_arguments_sf tys (ofs + 2)\n  | Tsingle :: tys =>\n      (if zlt ofs 0 then R (freg_param (ofs + 4)) else S Outgoing ofs Tsingle)\n      :: loc_arguments_sf tys (ofs + 1)\n  | Tlong :: tys =>\n      let ofs := align ofs 2 in\n      (if zlt ofs 0 then R (ireg_param (ofs+1+4)) else S Outgoing (ofs+1) Tint)\n      :: (if zlt ofs 0 then R (ireg_param (ofs+4)) else S Outgoing ofs Tint)\n      :: loc_arguments_sf tys (ofs + 2)\n  end.\n\n(** [loc_arguments s] returns the list of locations where to store arguments\n  when calling a function with signature [s].  *)\n\nDefinition loc_arguments (s: signature) : list loc :=\n  match Archi.abi with\n  | Archi.Softfloat =>\n      loc_arguments_sf s.(sig_args) (-4)\n  | Archi.Hardfloat =>\n      if s.(sig_cc).(cc_vararg)\n      then loc_arguments_sf s.(sig_args) (-4)\n      else loc_arguments_hf s.(sig_args) 0 0 0\n  end.\n\n(** [size_arguments s] returns the number of [Outgoing] slots used\n  to call a function with signature [s]. *)\n\nFixpoint size_arguments_hf (tyl: list typ) (ir fr ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => ofs\n  | (Tint|Tany32) :: tys =>\n      if zlt ir 4\n      then size_arguments_hf tys (ir + 1) fr ofs\n      else size_arguments_hf tys ir fr (ofs + 1)\n  | (Tfloat|Tany64) :: tys =>\n      if zlt fr 8\n      then size_arguments_hf tys ir (fr + 1) ofs\n      else size_arguments_hf tys ir fr (align ofs 2 + 2)\n  | Tsingle :: tys =>\n      if zlt fr 8\n      then size_arguments_hf tys ir (fr + 1) ofs\n      else size_arguments_hf tys ir fr (ofs + 1)\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      if zlt ir 4\n      then size_arguments_hf tys (ir + 2) fr ofs\n      else size_arguments_hf tys ir fr (align ofs 2 + 2)\n  end.\n\nFixpoint size_arguments_sf (tyl: list typ) (ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => Zmax 0 ofs\n  | (Tint | Tsingle | Tany32) :: tys => size_arguments_sf tys (ofs + 1)\n  | (Tfloat | Tlong | Tany64) :: tys => size_arguments_sf tys (align ofs 2 + 2)\n  end.\n\nDefinition size_arguments (s: signature) : Z :=\n  match Archi.abi with\n  | Archi.Softfloat =>\n      size_arguments_sf s.(sig_args) (-4)\n  | Archi.Hardfloat =>\n      if s.(sig_cc).(cc_vararg)\n      then size_arguments_sf s.(sig_args) (-4)\n      else size_arguments_hf s.(sig_args) 0 0 0\n  end.\n\n(** Argument locations are either non-temporary registers or [Outgoing] \n  stack slots at nonnegative offsets. *)\n\nDefinition loc_argument_acceptable (l: loc) : Prop :=\n  match l with\n  | R r => In r destroyed_at_call\n  | S Outgoing ofs ty => ofs >= 0 /\\ ty <> Tlong\n  | _ => False\n  end.\n\nRemark ireg_param_in_params: forall n, In (ireg_param n) int_param_regs.\nProof.\n  unfold ireg_param; intros. \n  destruct (list_nth_z int_param_regs n) as [r|] eqn:NTH.\n  eapply list_nth_z_in; eauto. \n  simpl; auto.\nQed.\n\nRemark freg_param_in_params: forall n, In (freg_param n) float_param_regs.\nProof.\n  unfold freg_param; intros. \n  destruct (list_nth_z float_param_regs n) as [r|] eqn:NTH.\n  eapply list_nth_z_in; eauto. \n  simpl; auto.\nQed.\n\nRemark loc_arguments_hf_charact:\n  forall tyl ir fr ofs l,\n  In l (loc_arguments_hf tyl ir fr ofs) ->\n  match l with\n  | R r => In r int_param_regs \\/ In r float_param_regs\n  | S Outgoing ofs' ty => ofs' >= ofs /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\n  assert (INCR: forall l ofs1 ofs2,\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= ofs2 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end ->\n            ofs1 <= ofs2 ->\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= ofs1 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end).\n  {\n    intros. destruct l; auto. destruct sl; auto. intuition omega.\n  }\n  induction tyl; simpl loc_arguments_hf; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct (zlt ir 4); destruct H.\n  subst. left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  eapply INCR. eapply IHtyl; eauto.\n  apply Zle_trans with (align ofs 2). apply align_le; omega. omega.\n- (* long *)\n  set (ir' := align ir 2) in *.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  destruct (zlt ir' 4).\n  destruct H. subst l; left; apply ireg_param_in_params.\n  destruct H. subst l; left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  destruct H. subst l; split; [ omega | congruence ].\n  destruct H. subst l; split; [ omega | congruence ].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* single *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any32 *)\n  destruct (zlt ir 4); destruct H.\n  subst. left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any64 *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  eapply INCR. eapply IHtyl; eauto.\n  apply Zle_trans with (align ofs 2). apply align_le; omega. omega.\nQed.\n\nRemark loc_arguments_sf_charact:\n  forall tyl ofs l,\n  In l (loc_arguments_sf tyl ofs) ->\n  match l with\n  | R r => In r int_param_regs \\/ In r float_param_regs\n  | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\n  assert (INCR: forall l ofs1 ofs2,\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs2 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end ->\n            ofs1 <= ofs2 ->\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs1 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end).\n  {\n    intros. destruct l; auto. destruct sl; auto. intuition xomega.\n  }\n  induction tyl; simpl loc_arguments_sf; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct H. \n  destruct (zlt ofs 0); subst l. \n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* float *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* long *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* single *)\n  destruct H. \n  destruct (zlt ofs 0); subst l. \n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any32 *)\n  destruct H. \n  destruct (zlt ofs 0); subst l. \n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any64 *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\nQed.\n\nLemma loc_arguments_acceptable:\n  forall (s: signature) (l: loc),\n  In l (loc_arguments s) -> loc_argument_acceptable l.\nProof.\n  unfold loc_arguments; intros.\n  assert (forall r, In r int_param_regs \\/ In r float_param_regs -> In r destroyed_at_call).\n  {\n    intros. elim H0; simpl; ElimOrEq; OrEq.\n  }\n  assert (In l (loc_arguments_sf (sig_args s) (-4)) -> loc_argument_acceptable l).\n  { intros. red. exploit loc_arguments_sf_charact; eauto. destruct l; auto. }\n  assert (In l (loc_arguments_hf (sig_args s) 0 0 0) -> loc_argument_acceptable l).\n  { intros. red. exploit loc_arguments_hf_charact; eauto. destruct l; auto. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; auto.\nQed.\n\nHint Resolve loc_arguments_acceptable: locs.\n\n(** The offsets of [Outgoing] arguments are below [size_arguments s]. *)\n\nRemark size_arguments_hf_above:\n  forall tyl ir fr ofs0,\n  ofs0 <= size_arguments_hf tyl ir fr ofs0.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a.\n  destruct (zlt ir 4); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  set (ir' := align ir 2).\n  destruct (zlt ir' 4); eauto. \n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (ofs0 + 1); eauto. omega.\n  destruct (zlt ir 4); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\nQed.\n\nRemark size_arguments_sf_above:\n  forall tyl ofs0,\n  Zmax 0 ofs0 <= size_arguments_sf tyl ofs0.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a; (eapply Zle_trans; [idtac|eauto]). \n  xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\n  xomega.\n  xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\nQed.\n\nLemma size_arguments_above:\n  forall s, size_arguments s >= 0.\nProof.\n  intros; unfold size_arguments. apply Zle_ge.\n  assert (0 <= size_arguments_sf (sig_args s) (-4)).\n  { change 0 with (Zmax 0 (-4)). apply size_arguments_sf_above. }\n  assert (0 <= size_arguments_hf (sig_args s) 0 0 0).\n  { apply size_arguments_hf_above. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; auto.\nQed.\n\nLemma loc_arguments_hf_bounded:\n  forall ofs ty tyl ir fr ofs0,\n  In (S Outgoing ofs ty) (loc_arguments_hf tyl ir fr ofs0) ->\n  ofs + typesize ty <= size_arguments_hf tyl ir fr ofs0.\nProof.\n  induction tyl; simpl; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct (zlt ir 4); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above. \n  eauto.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto. \n  inv H. apply size_arguments_hf_above. \n  eauto.\n- (* long *)\n  destruct (zlt (align ir 2) 4).\n  destruct H. discriminate. destruct H. discriminate. eauto. \n  destruct H. inv H.\n  rewrite <- Zplus_assoc. simpl. apply size_arguments_hf_above.\n  destruct H. inv H.\n  eapply Zle_trans. 2: apply size_arguments_hf_above. simpl; omega.\n  eauto.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\n- (* any32 *)\n  destruct (zlt ir 4); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above. \n  eauto.\n- (* any64 *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto. \n  inv H. apply size_arguments_hf_above. \n  eauto.\nQed.\n\nLemma loc_arguments_sf_bounded:\n  forall ofs ty tyl ofs0,\n  In (S Outgoing ofs ty) (loc_arguments_sf tyl ofs0) ->\n  Zmax 0 (ofs + typesize ty) <= size_arguments_sf tyl ofs0.\nProof.\n  induction tyl; simpl; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct H. \n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above. \n  eauto.\n- (* float *)\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H. apply size_arguments_sf_above.\n  eauto.\n- (* long *)\n  destruct H. \n  destruct (zlt (align ofs0 2) 0); inv H.\n  rewrite <- Zplus_assoc. simpl. apply size_arguments_sf_above.\n  destruct H. \n  destruct (zlt (align ofs0 2) 0); inv H.\n  eapply Zle_trans. 2: apply size_arguments_sf_above. simpl; xomega.\n  eauto.\n- (* float *)\n  destruct H. \n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above. \n  eauto.\n- (* any32 *)\n  destruct H. \n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above. \n  eauto.\n- (* any64 *)\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H. apply size_arguments_sf_above.\n  eauto.\nQed.\n\nLemma loc_arguments_bounded:\n  forall (s: signature) (ofs: Z) (ty: typ),\n  In (S Outgoing ofs ty) (loc_arguments s) ->\n  ofs + typesize ty <= size_arguments s.\nProof.\n  unfold loc_arguments, size_arguments; intros.\n  assert (In (S Outgoing ofs ty) (loc_arguments_sf (sig_args s) (-4)) ->\n          ofs + typesize ty <= size_arguments_sf (sig_args s) (-4)).\n  { intros. eapply Zle_trans. 2: eapply loc_arguments_sf_bounded; eauto. xomega. }\n  assert (In (S Outgoing ofs ty) (loc_arguments_hf (sig_args s) 0 0 0) ->\n          ofs + typesize ty <= size_arguments_hf (sig_args s) 0 0 0).\n  { intros. eapply loc_arguments_hf_bounded; eauto. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; eauto.\nQed.\n\nLemma loc_arguments_main:\n  loc_arguments signature_main = nil.\nProof.\n  unfold loc_arguments. \n  destruct Archi.abi; reflexivity.\nQed.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/arm/Conventions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1988622971527496}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.OneLeaderPerTermInterface.\n\nRequire Import VerdiRaft.CandidateEntriesInterface.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.RefinementCommonTheorems.\n\nRequire Import VerdiRaft.LeaderSublogInterface.\n\nHint Extern 4 (@BaseParams) => apply base_params : typeclass_instances.\nHint Extern 4 (@MultiParams _) => apply multi_params : typeclass_instances.\nHint Extern 4 (@FailureParams _ _) => apply failure_params : typeclass_instances.\n\nSection LeaderSublogProof.\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 {cei : candidate_entries_interface}.\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n  Context {olpti : one_leader_per_term_interface}.\n\n  Ltac prove_in :=\n    match goal with\n      | [ _ : nwPackets ?net = _,\n              _ : In (?p : packet) _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n      | [ _ : nwPackets ?net = _,\n              _ : pBody ?p = _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n    end.\n\n\n  Notation is_append_entries m :=\n    (exists t n prevT prevI entries c,\n       m = AppendEntries t n prevT prevI entries c).\n\n  Lemma leader_sublog_invariant_same_state :\n    forall net net',\n      leader_sublog_host_invariant net ->\n      (forall h, log (nwState net h) = log (nwState net' h)) ->\n      (forall h, type (nwState net' h) = Leader ->\n            type (nwState net h) = Leader /\\\n            currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n      leader_sublog_host_invariant net'.\n  Proof using. \n    unfold leader_sublog_host_invariant in *. intros.\n    specialize (H leader e h).\n    forward H; [apply H1; auto|].\n    intuition.\n    rewrite H0 in *. specialize (H1 leader). intuition.\n    rewrite H7 in *; auto.\n    rewrite H0 in *. auto.\n  Qed.\n\n  Lemma leader_sublog_invariant_subset :\n    forall net net',\n      leader_sublog_invariant net ->\n      (forall p, is_append_entries (pBody p) -> In p (nwPackets net') -> In p (nwPackets net)) ->\n      (forall h, log (nwState net h) = log (nwState net' h)) ->\n      (forall h, type (nwState net' h) = Leader ->\n            type (nwState net h) = Leader /\\\n            currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n      leader_sublog_invariant net'.\n  Proof using. \n    unfold leader_sublog_invariant in *. intros; intuition.\n    - eauto using leader_sublog_invariant_same_state.\n    - unfold leader_sublog_nw_invariant in *. intros.\n      pose proof H1 leader.\n      pose proof H2 leader; concludes.\n      pose proof H3 leader. intuition.\n      symmetry in H13.\n      repeat find_rewrite.\n      eapply H11; simpl in *; repeat find_rewrite; eauto.\n      assert (is_append_entries (pBody p)) by (repeat eexists; eauto).\n      eauto.\n  Qed.\n\n  Theorem leader_sublog_do_leader :\n    raft_net_invariant_do_leader leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_do_leader.\n    intros.\n    unfold doLeader in *.\n    break_match; try solve [\n                       find_inversion; simpl in *;\n                       eapply leader_sublog_invariant_subset;\n                       eauto; intuition; simpl in *;\n                       repeat find_apply_hyp_hyp; intuition;\n                       repeat find_higher_order_rewrite; repeat break_if; subst; intuition].\n    break_if.\n    - unfold replicaMessage in *. find_inversion. simpl in *.\n      unfold leader_sublog_invariant in *; intuition.\n      + unfold leader_sublog_host_invariant in *. intros.\n        simpl in *. repeat find_higher_order_rewrite.\n        repeat break_if; simpl in *; intuition eauto.\n      + unfold leader_sublog_nw_invariant in *. intros.\n        simpl in *. repeat find_higher_order_rewrite.\n        find_apply_hyp_hyp.\n        break_if; intuition idtac; simpl in *; subst; intuition eauto;\n        simpl in *;\n        repeat do_in_map; subst; simpl in *;\n        find_inversion; eauto using findGtIndex_in.\n    - find_inversion.\n      unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n      leader_sublog_host_invariant, advanceCommitIndex in *.\n\n      intuition; find_higher_order_rewrite; repeat break_if; simpl in *; subst;\n      repeat break_if; simpl in *; eauto;\n      find_apply_hyp_hyp; intuition; eauto.\n  Qed.\n\n  Lemma leader_sublog_client_request :\n    raft_net_invariant_client_request leader_sublog_invariant.\n  Proof using olpti. \n    unfold raft_net_invariant_client_request.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleClientRequest in *. intuition idtac.\n    - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n      repeat break_if; subst; simpl in *;\n      intuition eauto;\n      simpl in *; in_crush_finish; intuition eauto. in_crush; eauto.\n      exfalso.\n      match goal with\n        | H : raft_intermediate_reachable _ |- _ =>\n          eapply one_leader_per_term_invariant in H\n      end.\n      assert (leader = h) by (eapply_prop one_leader_per_term; eauto).\n      intuition.\n    - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n      repeat break_if; find_apply_hyp_hyp; intuition eauto; subst.\n      simpl in *.\n      in_crush; eauto.\n  Qed.\n\n  Lemma leader_sublog_timeout :\n    raft_net_invariant_timeout\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_timeout. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleTimeout, tryToBecomeLeader in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; try solve_by_inversion;\n      in_crush; repeat find_inversion; discriminate.\n  Qed.\n\n  Lemma leader_sublog_append_entries :\n    raft_net_invariant_append_entries\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_append_entries. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleAppendEntries, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion;\n      do_in_app; intuition; eauto using removeAfterIndex_in.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_append_entries_reply :\n    raft_net_invariant_append_entries_reply\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_append_entries_reply. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleAppendEntriesReply, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_request_vote :\n    raft_net_invariant_request_vote\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_request_vote. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleRequestVote, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n\n  Definition CandidateEntriesLowered net e h :=\n      currentTerm (nwState net h) = eTerm e ->\n      wonElection (dedup name_eq_dec (votesReceived (nwState net h))) = true ->\n      type (nwState net h) <> Candidate.\n\n  Lemma candidate_entries_lowered' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall h h' e,\n        In e (log (snd (nwState net h'))) ->\n        CandidateEntriesLowered (deghost net) e h.\n  Proof using rri. \n    unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    apply_prop_hyp candidateEntries_host_invariant In.\n    eapply candidateEntries_wonElection; auto; repeat find_rewrite_lem deghost_spec; eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall h h' e,\n        In e (log (nwState net h')) ->\n        CandidateEntriesLowered net e h.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Definition CandidateEntriesLowered_rvr net e p :=\n    In p (nwPackets net) ->\n    pBody p = RequestVoteReply (eTerm e) true ->\n    currentTerm (nwState net (pDst p)) = eTerm e ->\n    wonElection (dedup name_eq_dec (pSrc p :: votesReceived (nwState net (pDst p)))) = true ->\n    type (nwState net (pDst p)) <> Candidate.\n\n  Lemma deghost_packet_exists :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    unfold deghost.\n    simpl.\n    intros.\n    do_in_map.\n    eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered_rvr' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p h e,\n        In e (log (snd (nwState net h))) ->\n        CandidateEntriesLowered_rvr (deghost net) e p.\n  Proof using rri. \n    unfold CandidateEntriesLowered_rvr, CandidateEntries.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n\n    apply_prop_hyp candidateEntries_host_invariant In.\n    eapply wonElection_candidateEntries_rvr; auto;\n    repeat find_rewrite_lem deghost_spec; eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered_rvr :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p h e,\n        In e (log (nwState net h)) ->\n        CandidateEntriesLowered_rvr net e p.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_rvr';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall h p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets (deghost net)) ->\n        In e es ->\n        CandidateEntriesLowered (deghost net) e h.\n  Proof using rri. \n    unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists. break_and. subst.\n\n    eapply_prop_hyp candidateEntries_nw_invariant In; eauto.\n    unfold candidateEntries in *. break_exists. break_and.\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n\n    intro.\n    assert (h = x0).\n    {\n      eapply_prop one_vote_per_term;\n      eapply_prop cronies_votes.\n      - eapply_prop votes_received_cronies; eauto.\n      - find_reverse_rewrite. auto.\n    }\n    subst.\n    concludes. contradiction.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall h p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets net) ->\n        In e es ->\n        CandidateEntriesLowered net e h.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_nw';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw_rvr' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p' p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets (deghost net)) ->\n        In e es ->\n        CandidateEntriesLowered_rvr (deghost net) e p'.\n  Proof using rri. \n    unfold CandidateEntriesLowered_rvr, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n    eapply_prop_hyp votes_nw pBody. concludes.\n    eapply_prop_hyp candidateEntries_nw_invariant pBody; auto.\n\n    find_insterU. conclude_using eauto.\n    unfold candidateEntries in *.\n    break_exists. break_and.\n\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    simpl in *.\n    break_or_hyp.\n    - apply_prop_hyp cronies_votes In.\n      assert (pDst x = x1) by (eapply_prop one_vote_per_term; eauto).\n      subst. auto.\n    - intro.\n      assert (pDst x = x1).\n      { eapply_prop one_vote_per_term;\n        eapply_prop cronies_votes.\n        - eapply_prop votes_received_cronies; eauto.\n        - repeat find_reverse_rewrite. auto.\n      }\n      subst.\n      concludes. contradiction.\n  Qed.\n\n\n  Lemma candidate_entries_lowered_nw_rvr :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p' p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets net) ->\n        In e es ->\n        CandidateEntriesLowered_rvr net e p'.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_nw_rvr';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma leader_sublog_request_vote_reply :\n    raft_net_invariant_request_vote_reply\n      leader_sublog_invariant.\n  Proof using cci vci cei rri. \n    unfold raft_net_invariant_request_vote_reply.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n           leader_sublog_host_invariant, handleRequestVoteReply, advanceCurrentTerm.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *; intuition eauto; try discriminate.\n      + exfalso. eapply candidate_entries_lowered; eauto.\n      + rewrite dedup_not_in_cons in * by auto.\n        exfalso. eapply candidate_entries_lowered_rvr; eauto.\n        do_bool.\n        find_rewrite.\n        f_equal.\n        omega.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *; intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n      + exfalso. eapply candidate_entries_lowered_nw; eauto.\n      + rewrite dedup_not_in_cons in * by auto.\n        exfalso. eapply candidate_entries_lowered_nw_rvr; eauto.\n        do_bool.\n        find_rewrite.\n        f_equal.\n        omega.\n  Qed.\n\n  Lemma leader_sublog_do_generic_server :\n    raft_net_invariant_do_generic_server\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, doGenericServer in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      use_applyEntries_spec;\n      subst; simpl in *;\n      intuition eauto;\n      try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      use_applyEntries_spec;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant in *. intuition idtac;\n      repeat find_reverse_higher_order_rewrite; intuition eauto.\n  Qed.\n\n  Lemma leader_sublog_reboot :\n    raft_net_invariant_reboot\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_reboot. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, reboot in *. intuition idtac.\n    - repeat find_higher_order_rewrite.\n      simpl in *. repeat break_match; subst; simpl in *; intuition eauto; discriminate.\n    - repeat find_higher_order_rewrite.\n      simpl in *. repeat find_rewrite.\n      repeat break_match; subst; simpl in *;\n      intuition eauto; try discriminate.\n  Qed.\n\n  Theorem leader_sublog_init :\n    raft_net_invariant_init leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_init, leader_sublog_invariant,\n    leader_sublog_host_invariant, leader_sublog_nw_invariant;\n    intuition.\n  Qed.\n\n  Theorem leader_sublog_invariant_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      leader_sublog_invariant net.\n  Proof using olpti cci vci cei rri. \n    intros.\n    eapply raft_net_invariant; eauto.\n    - apply leader_sublog_init.\n    - apply leader_sublog_client_request.\n    - apply leader_sublog_timeout.\n    - apply leader_sublog_append_entries.\n    - apply leader_sublog_append_entries_reply.\n    - apply leader_sublog_request_vote.\n    - apply leader_sublog_request_vote_reply.\n    - apply leader_sublog_do_leader.\n    - apply leader_sublog_do_generic_server.\n    - apply leader_sublog_state_same_packet_subset.\n    - apply leader_sublog_reboot.\n  Qed.\n\n  Instance lsi : leader_sublog_interface.\n  Proof.\n    split.\n    auto using leader_sublog_invariant_invariant.\n  Qed.\nEnd LeaderSublogProof.\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/LeaderSublogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.19867636248606288}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.veric.base.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.tycontext.\nRequire Import VST.veric.Clight_lemmas.\nRequire Export VST.veric.expr.\n\nLemma neutral_cast_lemma: forall t1 t2 v,\n  is_neutral_cast t1 t2 = true ->\n  tc_val t1 v -> eval_cast t1 t2 v = v.\nProof.\nintros.\nassert (- two_p (16-1) < Byte.min_signed) by (compute; congruence).\nassert (two_p (16-1) > Byte.max_signed) by (compute; congruence).\nassert (two_p 16 > Byte.max_unsigned) by (compute; congruence).\nassert (- two_p (8-1) = Byte.min_signed) by reflexivity.\nassert (two_p (8-1) - 1 = Byte.max_signed) by reflexivity.\nassert (two_p 8 - 1 = Byte.max_unsigned) by reflexivity.\n destruct t1 as [ | [ | | | ] [ | ] | | [ | ] | | | | | ],\n t2 as [ | [ | | | ] [ | ] | | [ | ] | | | | | ];\n unfold eval_cast, sem_cast, classify_cast,\n  sem_cast_pointer, sem_cast_i2bool, sem_cast_l2bool;\ntry solve [\n try match goal with |- context [Archi.ptr64] => destruct Archi.ptr64 end;\n inversion H; clear H; try reflexivity;\n destruct v; unfold tc_val, is_int in H0; try contradiction;\n simpl; f_equal;\n try (first [apply sign_ext_inrange| apply zero_ext_inrange];\n       try omega;\n    match type of H0 with _ \\/ _ =>\n       destruct H0; subst i; simpl;\n       try  rewrite Int.signed_zero;\n       try  rewrite Int.unsigned_zero;\n       try change (Int.signed Int.one) with 1;\n       try change (Int.unsigned Int.one) with 1;\n       clear; compute; split; congruence\n    end);\n try (destruct H0; subst i; try rewrite Int.eq_true; auto)].\n unfold is_neutral_cast in H.\n rewrite orb_true_iff in H.\n destruct H.\n apply eqb_type_true in H. rewrite <- H in *.\n unfold tc_val in H0.\n rewrite eqb_reflx.\n if_tac in H0; destruct v; inv H0; reflexivity.\n rewrite andb_true_iff in H. destruct H.\n destruct (eqb_type (Tpointer t1 a) int_or_ptr_type); inv H.\n destruct (eqb_type (Tpointer t2 a0) int_or_ptr_type); inv H7.\n simpl.\n unfold tc_val in H0.\n if_tac in H0; destruct v; inv H0; reflexivity.\nQed.\n\nLemma neutral_cast_subsumption: forall t1 t2 v,\n  is_neutral_cast t1 t2 = true ->\n  tc_val t1 v -> tc_val t2 v.\nProof.\nintros.\nassert (- two_p (16-1) < Byte.min_signed) by (compute; congruence).\nassert (two_p (16-1) > Byte.max_signed) by (compute; congruence).\nassert (two_p 16 > Byte.max_unsigned) by (compute; congruence).\nassert (- two_p (8-1) = Byte.min_signed) by reflexivity.\nassert (two_p (8-1) - 1 = Byte.max_signed) by reflexivity.\nassert (two_p 8 - 1 = Byte.max_unsigned) by reflexivity.\ndestruct t1 as [ | [ | | | ] [ | ] | | [ | ] | | | | | ],\n t2   as [ | [ | | | ] [ | ] | | [ | ] | | | | | ]; inv H;\n destruct v; try solve [contradiction H0]; try apply I;\n unfold tc_val, is_int in *;\n  auto;\n try omega;\n try\n    match type of H0 with _ \\/ _ =>\n       destruct H0; subst i; simpl;\n       try  rewrite Int.signed_zero;\n       try  rewrite Int.unsigned_zero;\n       try change (Int.signed Int.one) with 1;\n       try change (Int.unsigned Int.one) with 1;\n       clear; compute; try split; congruence\n    end;\n try ( if_tac in H0; contradiction H0).\n destruct (eqb_type (Tpointer t2 a0) int_or_ptr_type) eqn:?H.\n apply I.\n apply eqb_type_false in H.\n destruct (eqb_type (Tpointer t1 a) int_or_ptr_type) eqn:?H; auto.\n apply eqb_type_true in H7. inv H7. simpl in *.\n rewrite orb_false_r in H8. \n rewrite andb_true_iff in H8. destruct H8.\n destruct t2; inv H7.\n destruct a0.\n destruct attr_volatile; try solve [inv H8].\n simpl in H8.\n destruct attr_alignas; try solve [inv H8].\n destruct n as [ [ | ] | ]; try solve [inv H8].\n apply Peqb_true_eq in H8. subst p.\n contradiction H. reflexivity.\n destruct (eqb_type (Tpointer t2 a0) int_or_ptr_type) eqn:?H.\n apply I.\n apply I.\nQed.\n\n(** Denotation functions for each of the assertions that can be produced by the typechecker **)\n\nDefinition denote_tc_iszero v : mpred :=\n         match v with\n         | Vint i => prop (is_true (Int.eq i Int.zero))\n         | Vlong i => prop (is_true (Int64.eq (Int64.repr (Int64.unsigned i)) Int64.zero))\n         | _ => FF\n         end.\n\nDefinition denote_tc_nonzero v : mpred :=\n         match v with\n         | Vint i => if negb (Int.eq i Int.zero) then TT else FF\n         | Vlong i => if negb (Int64.eq i Int64.zero) then TT else FF\n         | _ => FF end.\n\nDefinition denote_tc_igt i v : mpred :=\n     match v with\n     | Vint i1 => prop (is_true (Int.ltu i1 i))\n     | _ => FF\n     end.\n\nDefinition denote_tc_lgt l v : mpred :=\n     match v with\n     | Vlong l1 => prop (is_true (Int64.ltu l1 l))\n     | _ => FF\n     end.\n\nDefinition Zoffloat (f:float): option Z := (**r conversion to Z *)\n  match f with\n    | Fappli_IEEE.B754_finite s m (Zpos e) _ =>\n       Some (Fcore_Zaux.cond_Zopp s (Zpos m) * Zpower_pos 2 e)\n    | Fappli_IEEE.B754_finite s m 0 _ => Some (Fcore_Zaux.cond_Zopp s (Zpos m))\n    | Fappli_IEEE.B754_finite s m (Zneg e) _ => Some (Fcore_Zaux.cond_Zopp s (Zpos m / Zpower_pos 2 e))\n    | Fappli_IEEE.B754_zero _ => Some 0\n    | _ => None\n  end.  (* copied from CompCert 2.3, because it's missing in CompCert 2.4 *)\n\nDefinition Zofsingle (f: float32): option Z := (**r conversion to Z *)\n  match f with\n    | Fappli_IEEE.B754_finite s m (Zpos e) _ =>\n       Some (Fcore_Zaux.cond_Zopp s (Zpos m) * Zpower_pos 2 e)\n    | Fappli_IEEE.B754_finite s m 0 _ => Some (Fcore_Zaux.cond_Zopp s (Zpos m))\n    | Fappli_IEEE.B754_finite s m (Zneg e) _ => Some (Fcore_Zaux.cond_Zopp s (Zpos m / Zpower_pos 2 e))\n    | Fappli_IEEE.B754_zero _ => Some 0\n    | _ => None\n  end.  (* copied from CompCert 2.3, because it's missing in CompCert 2.4 *)\n\n\nDefinition denote_tc_Zge z v : mpred :=\n          match v with\n                     | Vfloat f => match Zoffloat f with\n                                    | Some n => prop (is_true (Zge_bool z n))\n                                    | None => FF\n                                   end\n                     | Vsingle f => match Zofsingle f with\n                                    | Some n => prop (is_true (Zge_bool z n))\n                                    | None => FF\n                                   end\n                     | _ => FF\n                  end.\n\nDefinition denote_tc_Zle z v : mpred :=\n          match v with\n                     | Vfloat f => match Zoffloat f with\n                                    | Some n => prop (is_true (Zle_bool z n))\n                                    | None => FF\n                                   end\n                     | Vsingle f => match Zofsingle f with\n                                    | Some n => prop (is_true (Zle_bool z n))\n                                    | None => FF\n                                   end\n                     | _ => FF\n                  end.\n\nDefinition sameblock v1 v2 : bool :=\n         match v1, v2 with\n          | Vptr b1 _, Vptr b2 _ => peq b1 b2\n          | _, _ => false\n         end.\n\nDefinition denote_tc_samebase v1 v2 : mpred :=\n       prop (is_true (sameblock v1 v2)).\n\n(** Case for division of int min by -1, which would cause overflow **)\nDefinition denote_tc_nodivover v1 v2 : mpred :=\nmatch v1, v2 with\n          | Vint n1, Vint n2 => prop (is_true (negb\n                                   (Int.eq n1 (Int.repr Int.min_signed)\n                                    && Int.eq n2 Int.mone)))\n          | Vlong n1, Vlong n2 => prop (is_true (negb\n                                   (Int64.eq n1 (Int64.repr Int64.min_signed)\n                                    && Int64.eq n2 Int64.mone)))\n          | Vint n1, Vlong n2 => TT\n          | Vlong n1, Vint n2 => prop (is_true (negb\n                                   (Int64.eq n1 (Int64.repr Int64.min_signed)\n                                    && Int.eq n2 Int.mone)))\n          | _ , _ => FF\n        end.\n\nDefinition denote_tc_nosignedover (op: Z->Z->Z) v1 v2 : mpred :=\n match v1,v2 with\n | Vint n1, Vint n2 => \n   prop (Int.min_signed <= op (Int.signed n1) (Int.signed n2) <= Int.max_signed)\n | Vlong n1, Vlong n2 =>\n   prop (Int64.min_signed <= op (Int64.signed n1) (Int64.signed n2) <= Int64.max_signed)\n | Vint n1, Vlong n2 =>\n   prop (Int64.min_signed <= op (Int.signed n1) (Int64.signed n2) <= Int64.max_signed)\n | Vlong n1, Vint n2 =>\n   prop (Int64.min_signed <= op (Int64.signed n1) (Int.signed n2) <= Int64.max_signed)\n | _, _ => FF\n end.\n\nDefinition denote_tc_initialized id ty rho : mpred :=\n    prop (exists v, Map.get (te_of rho) id = Some v\n               /\\ tc_val ty v).\n\nDefinition denote_tc_isptr v : mpred :=\n  prop (isptr v).\n\nDefinition test_eq_ptrs v1 v2 : mpred :=\n  if sameblock v1 v2\n  then (andp (weak_valid_pointer v1) (weak_valid_pointer v2))\n  else (andp (valid_pointer v1) (valid_pointer v2)).\n\nDefinition test_order_ptrs v1 v2 : mpred :=\n  if sameblock v1 v2\n  then (andp (weak_valid_pointer v1) (weak_valid_pointer v2))\n  else FF.\n\nDefinition denote_tc_test_eq v1 v2 : mpred :=\n match v1, v2 with\n | Vint i, Vint j => \n     if Archi.ptr64 then FF else andp (prop (i = Int.zero)) (prop (j = Int.zero))\n | Vlong i, Vlong j => \n     if Archi.ptr64 then andp (prop (i = Int64.zero)) (prop (j = Int64.zero)) else FF\n | Vint i, Vptr _ _ =>\n      if Archi.ptr64 then FF else andp (prop (i = Int.zero)) (weak_valid_pointer v2)\n | Vlong i, Vptr _ _ =>\n      if Archi.ptr64 then andp (prop (i = Int64.zero)) (weak_valid_pointer v2) else FF\n | Vptr _ _, Vint i =>\n      if Archi.ptr64 then FF else andp (prop (i = Int.zero)) (weak_valid_pointer v1)\n | Vptr _ _, Vlong i =>\n      if Archi.ptr64 then andp (prop (i = Int64.zero)) (weak_valid_pointer v1) else FF\n | Vptr _ _, Vptr _ _ =>\n      test_eq_ptrs v1 v2\n | _, _ => FF\n end.\n\nDefinition denote_tc_test_order v1 v2 : mpred :=\n match v1, v2 with\n | Vint i, Vint j => if Archi.ptr64 then FF else andp (prop (i = Int.zero)) (prop (j = Int.zero))\n | Vlong i, Vlong j => if Archi.ptr64 then andp (prop (i = Int64.zero)) (prop (j = Int64.zero)) else FF\n | Vptr _ _, Vptr _ _ =>\n      test_order_ptrs v1 v2\n | _, _ => FF\n end.\n\nDefinition typecheck_error (e: tc_error) : Prop := False.\n\nFixpoint denote_tc_assert {CS: compspecs}(a: tc_assert) : environ -> mpred :=\n  match a with\n  | tc_FF msg => `(prop (typecheck_error msg))\n  | tc_TT => `TT\n  | tc_andp' b c => `andp (denote_tc_assert b) (denote_tc_assert c)\n  | tc_orp' b c => `orp (denote_tc_assert b) (denote_tc_assert c)\n  | tc_nonzero' e => `denote_tc_nonzero (eval_expr e)\n  | tc_isptr e => `denote_tc_isptr (eval_expr e)\n  | tc_test_eq' e1 e2 => `denote_tc_test_eq (eval_expr e1) (eval_expr e2)\n  | tc_test_order' e1 e2 => `denote_tc_test_order (eval_expr e1) (eval_expr e2)\n  | tc_ilt' e i => `(denote_tc_igt i) (eval_expr e)\n  | tc_llt' e l => `(denote_tc_lgt l) (eval_expr e)\n  | tc_Zle e z => `(denote_tc_Zge z) (eval_expr e)\n  | tc_Zge e z => `(denote_tc_Zle z) (eval_expr e)\n  | tc_samebase e1 e2 => `denote_tc_samebase (eval_expr e1) (eval_expr e2)\n  | tc_nodivover' v1 v2 => `denote_tc_nodivover (eval_expr v1) (eval_expr v2)\n  | tc_initialized id ty => denote_tc_initialized id ty\n  | tc_iszero' e => `denote_tc_iszero (eval_expr e)\n  | tc_nosignedover op e1 e2 => `(denote_tc_nosignedover op) (eval_expr e1) (eval_expr e2)\n end.\n\nLemma and_False: forall x, (x /\\ False) = False.\nProof.\nintros; apply prop_ext; intuition.\nQed.\n\nLemma and_True: forall x, (x /\\ True) = x.\nProof.\nintros; apply prop_ext; intuition.\nQed.\n\nLemma True_and: forall x, (True /\\ x) = x.\nProof.\nintros; apply prop_ext; intuition.\nQed.\n\nLemma False_and: forall x, (False /\\ x) = False.\nProof.\nintros; apply prop_ext; intuition.\nQed.\n\nLemma tc_andp_sound : forall {CS: compspecs} a1 a2 rho m,\n    denote_tc_assert  (tc_andp a1 a2) rho m <->\n    denote_tc_assert  (tc_andp' a1 a2) rho m.\nProof.\nintros.\n unfold tc_andp.\n destruct a1; simpl; unfold_lift;\n repeat first [rewrite False_and | rewrite True_and\n                    | rewrite and_False | rewrite and_True ];\n  try apply iff_refl;\n  destruct a2; simpl in *; unfold_lift;\n repeat first [rewrite False_and | rewrite True_and\n                    | rewrite and_False | rewrite and_True ];\n  try apply iff_refl.\nQed.\n\nLemma denote_tc_assert_andp:\n  forall {CS: compspecs} a b rho, denote_tc_assert (tc_andp a b) rho =\n             andp (denote_tc_assert a rho) (denote_tc_assert b rho).\nProof.\n intros.\n apply pred_ext.\n intro m. rewrite tc_andp_sound. intros [? ?]; split; auto.\n intros m [? ?]. rewrite tc_andp_sound; split; auto.\nQed.\n\nLemma neutral_isCastResultType:\n  forall {CS: compspecs} t t' v rho,\n   is_neutral_cast t' t = true ->\n   forall m, denote_tc_assert (isCastResultType t' t v) rho m.\nProof.\nintros.\n  unfold isCastResultType.\n  unfold is_neutral_cast in H; simpl classify_cast.\n  destruct t'  as [ | [ | | | ] [ | ] | | [ | ] | | | | |],\n   t  as [ | [ | | | ] [ | ] | | [ | ] | | | | |];\n   try solve [inv H; try apply I; simpl; if_tac; apply I];\n  try (rewrite denote_tc_assert_andp; split);\n  try solve [unfold eval_cast, sem_cast, classify_cast,\n     sem_cast_pointer, sem_cast_i2bool, sem_cast_l2bool;\n      destruct Archi.ptr64; simpl; try if_tac; try apply I].\n  apply orb_true_iff in H.\n  unfold classify_cast.\n  destruct (eqb (eqb_type (Tpointer t a0) int_or_ptr_type)\n         (eqb_type (Tpointer t' a) int_or_ptr_type)) eqn:J.\n  destruct (eqb_type (Tpointer t' a) (Tpointer t a0)) eqn:?H.\n  apply I.\n  destruct H. inv H.\n  apply andb_true_iff in H. destruct H.\n  rewrite eqb_true_iff in J.\n  unfold is_pointer_type.\n  rewrite <- J in *. apply eqb_type_false in H0.\n  destruct (eqb_type (Tpointer t a0) int_or_ptr_type); inv H.\n  apply I.\n  destruct H.\n  apply eqb_type_true in H. rewrite <- H in *.\n  rewrite eqb_reflx in J. inv J.\n  destruct (eqb_type (Tpointer t' a) int_or_ptr_type),\n     (eqb_type (Tpointer t a0) int_or_ptr_type); inv H; inv J.\nQed.\n\nLemma is_true_e: forall b, is_true b -> b=true.\nProof. intros. destruct b; try contradiction; auto.\nQed.\n\nLemma tc_bool_e: forall {CS: compspecs} b a rho m,\n  app_pred (denote_tc_assert (tc_bool b a) rho) m ->\n  b = true.\nProof.\nintros.\ndestruct b; simpl in H; auto.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/veric/expr2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1986763598665159}}
{"text": "Require Import Relations.\nRequire Import Permutation.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nRequire Import sflib.\nRequire Import PacoNotation.\nRequire Import HahnRelationsBasic.\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.\nRequire Import PromisingArch.promising.Promising.\nRequire Import PromisingArch.promising.CommonPromising.\nRequire Import PromisingArch.axiomatic.Axiomatic.\nRequire Import PromisingArch.equiv.SimLocal.\n\nSet Implicit Arguments.\n\n\nDefinition mem_of_ex\n           (ex:Execution.t)\n           (ob:list eidT):\n  Memory.t :=\n  filter_map\n    (fun eid =>\n       match Execution.label eid ex with\n       | Some (Label.write ex ord loc val) => Some (Msg.mk loc val (fst eid))\n       | _ => None\n       end)\n    ob.\n\nLemma mem_of_ex_app ex ob1 ob2:\n  mem_of_ex ex (ob1 ++ ob2) = mem_of_ex ex ob1 ++ mem_of_ex ex ob2.\nProof. apply filter_map_app. Qed.\n\nLemma mem_of_ex_in_length\n      ex ob eid\n      (IN: List.In eid ob)\n      (EID: ex.(Execution.label_is) Label.is_write eid):\n  length (mem_of_ex ex ob) <> 0.\nProof.\n  eapply filter_map_in_length; eauto.\n  inv EID. rewrite EID0. destruct l; ss.\nQed.\n\nInductive sim_mem (ex:Execution.t) (mem: Memory.t): Prop :=\n| sim_mem_intro\n    ob\n    (EIDS: Permutation ob (Execution.eids ex))\n    (MEM: mem = mem_of_ex ex ob)\n.\nHint Constructors sim_mem.\n\nDefinition view_of_eid (ex:Execution.t) (ob: list eidT) (eid:eidT): option Time.t :=\n  option_map\n    (fun n => length (mem_of_ex ex (List.firstn (S n) ob)))\n    (List_find_pos (fun eid' => eid' == eid) ob).\n\nLemma view_of_eid_inv\n      ex ob eid view\n      (VIEW: view_of_eid ex ob eid = Some view):\n  exists n,\n    <<N: List.nth_error ob n = Some eid>> /\\\n    <<VIEW: view = length (mem_of_ex ex (List.firstn (S n) ob))>>.\nProof.\n  unfold view_of_eid in *.\n  destruct ((List_find_pos (fun eid' : eidT => equiv_dec eid' eid) ob)) eqn:POS; inv VIEW.\n  exploit List_find_pos_inv; eauto. i. des. destruct (equiv_dec a eid); ss. inv e.\n  esplits; eauto.\nQed.\n\nLemma view_of_eid_ob_write_write\n      ex ob eid1 eid2 view\n      (VIEW1: view_of_eid ex ob eid1 = Some view)\n      (VIEW2: view_of_eid ex ob eid2 = Some view)\n      (WRITE1: Execution.label_is ex (Label.is_write) eid1)\n      (WRITE2: Execution.label_is ex (Label.is_write) eid2):\n  eid1 = eid2.\nProof.\n  exploit view_of_eid_inv; try exact VIEW1; eauto. i. des.\n  exploit view_of_eid_inv; try exact VIEW2; eauto. i. des.\n  inv WRITE1. destruct l; try done.\n  inv WRITE2. destruct l; try done.\n  destruct (Nat.compare_spec n n0).\n  - subst. congr.\n  - rewrite (@List_firstn_le (S n) (S n0)) in VIEW0; [|lia].\n    rewrite mem_of_ex_app, List.app_length in VIEW0.\n    apply plus_minus in VIEW0. rewrite Nat.sub_diag, Nat.sub_succ in VIEW0.\n    exploit List_nth_error_skipn; eauto. i.\n    exploit @List_nth_error_firstn; [eauto| |i].\n    { instantiate (1 := (n0 - n)). lia. }\n    exploit List.nth_error_In; eauto. i.\n    exfalso. eapply mem_of_ex_in_length; eauto.\n  - symmetry in VIEW0.\n    rewrite (@List_firstn_le (S n0) (S n)) in VIEW0; [|lia].\n    rewrite mem_of_ex_app, List.app_length in VIEW0.\n    apply plus_minus in VIEW0. rewrite Nat.sub_diag, Nat.sub_succ in VIEW0.\n    exploit List_nth_error_skipn; try exact N; eauto. i.\n    exploit @List_nth_error_firstn; [eauto| |i].\n    { instantiate (1 := (n - n0)). lia. }\n    exploit List.nth_error_In; eauto. i.\n    exfalso. eapply mem_of_ex_in_length; eauto.\nQed.\n\nLemma view_of_eid_ob\n      ex rel ob eid1 eid2 view1 view2\n      (LINEARIZED: linearized rel ob)\n      (OB: rel eid1 eid2)\n      (VIEW1: view_of_eid ex ob eid1 = Some view1)\n      (VIEW2: view_of_eid ex ob eid2 = Some view2):\n  le view1 view2.\nProof.\n  exploit view_of_eid_inv; try exact VIEW1; eauto. i. des.\n  exploit view_of_eid_inv; try exact VIEW2; eauto. i. des.\n  subst. exploit LINEARIZED; try exact OB; eauto. i.\n  erewrite (@List_firstn_le (S n) (S n0)); [|lia].\n  rewrite mem_of_ex_app, List.app_length. unfold le. lia.\nQed.\n\nLemma view_of_eid_ob_write\n      ex rel ob eid1 eid2 view1 view2 loc\n      (LINEARIZED: linearized rel ob)\n      (OB: rel eid1 eid2)\n      (VIEW1: view_of_eid ex ob eid1 = Some view1)\n      (VIEW2: view_of_eid ex ob eid2 = Some view2)\n      (WRITE2: Execution.label_is ex (Label.is_writing loc) eid2):\n  view1 < view2.\nProof.\n  exploit view_of_eid_inv; try exact VIEW1; eauto. i. des.\n  exploit view_of_eid_inv; try exact VIEW2; eauto. i. des.\n  subst. exploit LINEARIZED; try exact OB; eauto. i.\n  erewrite (@List_firstn_le (S n) (S n0)); [|lia].\n  rewrite mem_of_ex_app, List.app_length. apply Nat.lt_add_pos_r.\n  exploit List_nth_error_skipn; eauto. i.\n  exploit List_nth_error_firstn; [eauto| |i].\n  { instantiate (1 := (S n0 - S n)). lia. }\n  exploit List.nth_error_In; eauto. i.\n  apply neq_0_lt. ii. eapply mem_of_ex_in_length; eauto.\n  inv WRITE2. apply Label.is_writing_inv in LABEL. des. subst.\n  econs; eauto.\nQed.\n\nLemma view_of_eid_co\n      p ex ob eid1 eid2 view1 view2 loc\n      (EX: Valid.ex p ex)\n      (LINEARIZED: linearized (Execution.ob ex) ob)\n      (VIEW1: view_of_eid ex ob eid1 = Some view1)\n      (VIEW2: view_of_eid ex ob eid2 = Some view2)\n      (WRITE1: Execution.label_is ex (Label.is_writing loc) eid1)\n      (WRITE2: Execution.label_is ex (Label.is_writing loc) eid2)\n      (LT: view1 < view2):\n  Execution.co ex eid1 eid2.\nProof.\n  obtac.\n  exploit EX.(Valid.CO1).\n  { destruct l; destruct l0; ss; eqvtac.\n    esplits; [exact EID | exact EID0]; eauto.\n  }\n  i. des; ss.\n  { subst. rewrite VIEW1 in VIEW2. inv VIEW2. lia. }\n  cut (view2 < view1).\n  { i. lia. }\n  eapply view_of_eid_ob_write; eauto.\n  left. left. left. left. left. left. right. ss.\nQed.\n\nInductive sim_view (ex:Execution.t) (ob: list eidT) (eids:eidT -> Prop) (view:Time.t): Prop :=\n| sim_view_bot\n    (VIEW: view = bot)\n| sim_view_event\n    eid v\n    (EID: eids eid)\n    (VIEW_OF_EID: view_of_eid ex ob eid = Some v)\n    (VIEW: le view v)\n.\nHint Constructors sim_view.\n\nLemma sim_view_join ex ob pred v1 v2\n      (V1: sim_view ex ob pred v1)\n      (V2: sim_view ex ob pred v2):\n  sim_view ex ob pred (join v1 v2).\nProof.\n  inv V1.\n  { rewrite join_comm, bot_join; [|exact Time.order]. ss. }\n  inv V2.\n  { rewrite bot_join; [|exact Time.order]. econs 2; eauto. }\n\n  generalize (Time.max_spec_le v1 v2). i. des.\n  - unfold join, Time.join. rewrite H0. econs 2; try exact VIEW_OF_EID0; eauto.\n  - unfold join, Time.join. rewrite H0. econs 2; try exact VIEW_OF_EID; eauto.\nQed.\n\nLemma sim_view_le ex ob pred1 pred2\n      (PRED: pred1 <1= pred2):\n  sim_view ex ob pred1 <1= sim_view ex ob pred2.\nProof.\n  i. inv PR.\n  - econs 1. ss.\n  - econs 2; eauto.\nQed.\n\nLemma sim_view_le2 ex ob pred v1 v2\n      (SIM: sim_view ex ob pred v2)\n      (LE: v1 <= v2):\n  sim_view ex ob pred v1.\nProof.\n  inv SIM.\n  - inv LE. econs 1. refl.\n  - econs 2; eauto. etrans; eauto.\nQed.\n\nInductive sim_val (tid:Id.t) (ex:Execution.t) (ob: list eidT) (avala:ValA.t (A:=nat -> Prop)) (vala:ValA.t (A:=View.t (A:=unit))): Prop :=\n| sim_val_intro\n    (VAL: avala.(ValA.val) = vala.(ValA.val))\n    (VIEW: sim_view ex ob (fun eid => (fst eid) = tid /\\ avala.(ValA.annot) (snd eid)) vala.(ValA.annot).(View.ts))\n.\nHint Constructors sim_val.\n\nInductive sim_rmap (tid:Id.t) (ex:Execution.t) (ob: list eidT) (armap:RMap.t (A:=nat -> Prop)) (rmap:RMap.t (A:=View.t (A:=unit))): Prop :=\n| sim_rmap_intro\n    (RMAP: IdMap.Forall2 (fun reg => sim_val tid ex ob) armap rmap)\n.\nHint Constructors sim_rmap.\n\nInductive sim_state (tid:Id.t) (ex:Execution.t) (ob: list eidT) (astate:State.t (A:=nat -> Prop)) (state:State.t (A:=View.t (A:=unit))): Prop :=\n| sim_state_intro\n    (STMTS: astate.(State.stmts) = state.(State.stmts))\n    (RMAP: sim_rmap tid ex ob astate.(State.rmap) state.(State.rmap))\n.\nHint Constructors sim_state.\n\nLemma sim_rmap_add\n      tid ex ob armap rmap reg avala vala\n      (SIM: sim_rmap tid ex ob armap rmap)\n      (VAL: sim_val tid ex ob avala vala):\n  sim_rmap tid ex ob (RMap.add reg avala armap) (RMap.add reg vala rmap).\nProof.\n  econs. ii. unfold RMap.add. rewrite ? IdMap.add_spec.\n  inv SIM. condtac; eauto.\nQed.\n\nLemma sim_rmap_expr\n      tid ex ob armap rmap e\n      (SIM: sim_rmap tid ex ob armap rmap):\n  sim_val tid ex ob (sem_expr armap e) (sem_expr rmap e).\nProof.\n  inv SIM. induction e; s.\n  - (* const *)\n    econs; ss. econs 1; ss.\n  - (* reg *)\n    specialize (RMAP reg). unfold RMap.find. inv RMAP; ss.\n    econs; ss. econs 1; ss.\n  - (* op1 *)\n    inv IHe. econs; ss. congr.\n  - (* op2 *)\n    inv IHe1. inv IHe2. econs; ss.\n    + congr.\n    + apply sim_view_join; eapply sim_view_le; eauto.\n      * s. i. des. subst. esplits; eauto. left. ss.\n      * s. i. des. subst. esplits; eauto. right. ss.\nQed.\n\nInductive sim_local (tid:Id.t) (ex:Execution.t) (ob: list eidT) (alocal:ALocal.t) (local:Local.t (A:=unit)): Prop := mk_sim_local {\n  COH: forall loc,\n        sim_view\n          ex ob\n          (inverse (sim_local_coh ex loc) (eq (tid, List.length (alocal.(ALocal.labels)))))\n          (Memory.latest_ts loc (local.(Local.coh) loc).(View.ts) (mem_of_ex ex ob));\n  VRN: sim_view\n         ex ob\n         (inverse (sim_local_vrn ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vrn).(View.ts);\n  VWN: sim_view\n         ex ob\n         (inverse (sim_local_vwn ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vwn).(View.ts);\n  VRO: sim_view\n         ex ob\n         (inverse (sim_local_vro ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vro).(View.ts);\n  VWO: sim_view\n         ex ob\n         (inverse (sim_local_vwo ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vwo).(View.ts);\n  VCAP: sim_view\n         ex ob\n         (inverse (sim_local_vcap ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vcap).(View.ts);\n  VREL: sim_view\n          ex ob\n          (inverse (sim_local_vrel ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n          local.(Local.vrel).(View.ts);\n  FWDBANK: forall loc,\n      (exists eid,\n          <<TS_NONZERO: (local.(Local.fwdbank) loc).(FwdItem.ts) > 0>> /\\\n          <<WRITE: sim_local_fwd ex loc eid (tid, List.length (alocal.(ALocal.labels)))>> /\\\n          <<TS: view_of_eid ex ob eid = Some (local.(Local.fwdbank) loc).(FwdItem.ts)>> /\\\n          <<VIEW: sim_view\n                    ex ob\n                    (inverse (ex.(Execution.addr) \u222a ex.(Execution.data)) (eq eid))\n                    (local.(Local.fwdbank) loc).(FwdItem.view).(View.ts)>> /\\\n          <<EX: (local.(Local.fwdbank) loc).(FwdItem.ex) <-> ex.(Execution.label_is) (Label.is_ex) eid>>) \\/\n      ((local.(Local.fwdbank) loc) = FwdItem.init /\\\n       forall eid, ~ (inverse (sim_local_fwd_none ex loc) (eq (tid, List.length (alocal.(ALocal.labels)))) eid));\n  EXBANK: opt_rel\n            (fun aeb eb =>\n               ex.(Execution.label_is) (Label.is_reading eb.(Exbank.loc)) (tid, aeb) /\\\n               (forall eid v, ex.(Execution.rf) eid (tid, aeb) -> view_of_eid ex ob eid = Some v -> le v eb.(Exbank.ts)) /\\\n               sim_view\n                 ex ob\n                 (inverse ex.(Execution.rf) (eq (tid, aeb)))\n                 eb.(Exbank.ts) /\\\n               sim_view\n                 ex ob\n                 (eq (tid, aeb))\n                 eb.(Exbank.view).(View.ts))\n            alocal.(ALocal.exbank) local.(Local.exbank);\n  PROMISES: forall view,\n      Promises.lookup view local.(Local.promises) <->\n      (exists n,\n          <<N: (length alocal.(ALocal.labels)) <= n>> /\\\n          <<WRITE: ex.(Execution.label_is) Label.is_write (tid, n)>> /\\\n          <<VIEW: view_of_eid ex ob (tid, n) = Some view>>);\n  COH_CL: forall loc,\n          exists mloc_cl,\n          <<CL: Loc.cl loc mloc_cl>> /\\\n          <<COH_MAX_CL: forall loc0 (CL: Loc.cl loc0 mloc_cl),\n                         (local.(Local.coh) loc0).(View.ts) <= (local.(Local.coh) mloc_cl).(View.ts)>> /\\\n          <<COH_CL:\n              sim_view\n                ex ob\n                (inverse (sim_local_coh_cl ex loc) (eq (tid, List.length (alocal.(ALocal.labels)))))\n                (local.(Local.coh) mloc_cl).(View.ts)>>;\n  VPR: sim_view\n         ex ob\n         (inverse (sim_local_vpr ex) (eq (tid, List.length (alocal.(ALocal.labels)))))\n         local.(Local.vpr).(View.ts);\n  VPA: forall loc,\n        sim_view\n          ex ob\n          (inverse (sim_local_vpa ex loc) (eq (tid, List.length (alocal.(ALocal.labels)))))\n          (local.(Local.vpa) loc).(View.ts);\n  VPC: forall loc,\n        sim_view\n          ex ob\n          (inverse (sim_local_vpc ex loc) (eq (tid, List.length (alocal.(ALocal.labels)))))\n          (local.(Local.vpc) loc).(View.ts);\n}.\nHint Constructors sim_local.\n\nInductive sim_eu (tid:Id.t) (ex:Execution.t) (ob: list eidT) (aeu:AExecUnit.t) (eu:ExecUnit.t (A:=unit)): Prop :=\n| sim_eu_intro\n    (STATE: sim_state tid ex ob aeu.(AExecUnit.state) eu.(ExecUnit.state))\n    (LOCAL: sim_local tid ex ob aeu.(AExecUnit.local) eu.(ExecUnit.local))\n    (MEM: eu.(ExecUnit.mem) = mem_of_ex ex ob)\n.\nHint Constructors sim_eu.\n\nInductive persisted_event_view (ex:Execution.t) (ob: list eidT) (loc:Loc.t) (view: Time.t): Prop :=\n| persisted_event_view_uninit\n  (VIEW: view = bot)\n  (NPER: forall eid (PEID: Valid.persisted_event ex loc eid), False)\n| persisted_event_view_init\n  eid1 ex1 ord1 val1\n  (VIEW: view_of_eid ex ob eid1 = Some view)\n  (EID: Execution.label eid1 ex = Some (Label.write ex1 ord1 loc val1))\n  (VPC: forall eid0 (PEID: Valid.persisted_event ex loc eid0), ex.(Execution.co)^? eid0 eid1)\n.\nHint Constructors persisted_event_view.\n\nLemma label_mem_of_ex\n      l eid ex ob\n      (OB: Permutation ob (Execution.eids ex))\n      (LABEL: Execution.label eid ex = Some l):\n  exists view,\n    <<VIEW: view_of_eid ex ob eid = Some view>>.\nProof.\n  generalize (Execution.eids_spec ex). i. des. rename NODUP into NODUP0.\n  specialize (LABEL0 eid). rewrite LABEL in LABEL0.\n  inv LABEL0. clear H0. exploit H; [congr|]. clear H. intro IN0.\n  symmetry in OB. exploit Permutation_in; eauto. intro IN.\n  exploit HahnList.Permutation_nodup; eauto. intro NODUP.\n  generalize (List_in_find_pos _ ob IN). i. des.\n  unfold view_of_eid. rewrite H. s. eauto.\nQed.\n\nLemma label_write_mem_of_ex_msg\n      eid ex ob exm ord loc val\n      (OB: Permutation ob (Execution.eids ex))\n      (LABEL: Execution.label eid ex = Some (Label.write exm ord loc val)):\n  exists n,\n    <<VIEW: view_of_eid ex ob eid = Some (S n)>> /\\\n    <<MSG: List.nth_error (mem_of_ex ex ob) n = Some (Msg.mk loc val (fst eid))>>.\nProof.\n  generalize (Execution.eids_spec ex). i. des. rename NODUP into NODUP0.\n  specialize (LABEL0 eid). rewrite LABEL in LABEL0.\n  inv LABEL0. clear H0. exploit H; [congr|]. clear H. intro IN0.\n  symmetry in OB. exploit Permutation_in; eauto. intro IN.\n  exploit HahnList.Permutation_nodup; eauto. intro NODUP.\n  generalize (List_in_find_pos _ ob IN). i. des.\n  unfold view_of_eid. rewrite H.\n  exploit List_find_pos_inv; eauto. i. des.\n  destruct (equiv_dec a eid); [|done]. inversion e. subst.\n  esplits.\n  - unfold option_map. erewrite List_firstn_S; eauto.\n    rewrite mem_of_ex_app, List.app_length.\n    unfold mem_of_ex at 2. s. rewrite LABEL. s. rewrite Nat.add_1_r. ss.\n  - rewrite <- (List.firstn_skipn n ob) at 1.\n    rewrite mem_of_ex_app, List.nth_error_app2; [|lia].\n    erewrite Nat.sub_diag, List_skipn_cons; eauto. s.\n    unfold mem_of_ex. s. rewrite LABEL. ss.\nQed.\n\nLemma label_write_mem_of_ex\n      eid ex ob exm ord loc val\n      (OB: Permutation ob (Execution.eids ex))\n      (LABEL: Execution.label eid ex = Some (Label.write exm ord loc val)):\n  exists n,\n    <<VIEW: view_of_eid ex ob eid = Some (S n)>> /\\\n    <<READ: Memory.read loc (S n) (mem_of_ex ex ob) = Some val>> /\\\n    <<MSG: Memory.get_msg (S n) (mem_of_ex ex ob) = Some (Msg.mk loc val (fst eid))>>.\nProof.\n  exploit label_write_mem_of_ex_msg; eauto. i. des.\n  esplits; eauto.\n  unfold Memory.read. s. rewrite MSG. s. condtac; [|congr]. ss.\nQed.\n\nLemma in_mem_of_ex\n      ex ob view msg\n      (NODUP: List.NoDup ob)\n      (IN: List.nth_error (mem_of_ex ex ob) view = Some msg):\n  exists n ex1 ord1,\n    <<LABEL: Execution.label (msg.(Msg.tid), n) ex = Some (Label.write ex1 ord1 msg.(Msg.loc) msg.(Msg.val))>> /\\\n    <<VIEW: view_of_eid ex ob (msg.(Msg.tid), n) = Some (S view)>>.\nProof.\n  unfold mem_of_ex in IN. exploit nth_error_filter_map_inv; eauto. i. des.\n  destruct (Execution.label a ex) eqn:LABEL; ss. destruct t; inv FA. destruct a. ss.\n  esplits.\n  - eauto.\n  - unfold view_of_eid.\n    erewrite List_nth_error_find_pos; eauto. s. f_equal. ss.\nQed.\n\nLemma sim_eu_step\n      p ex ob tid aeu1 eu1 aeu2\n      (EX: Valid.ex p ex)\n      (OB: Permutation ob (Execution.eids ex))\n      (LINEARIZED: linearized (Execution.ob ex) ob)\n      (SIM: sim_eu tid ex ob aeu1 eu1)\n      (WF: ExecUnit.wf tid eu1)\n      (STEP: AExecUnit.step aeu1 aeu2)\n      (LABEL: forall n label (LABEL: List.nth_error aeu2.(AExecUnit.local).(ALocal.labels) n = Some label),\n          Execution.label (tid, n) ex = Some label)\n      (ADDR: tid_lift tid aeu2.(AExecUnit.local).(ALocal.addr) \u2286 ex.(Execution.addr))\n      (DATA: tid_lift tid aeu2.(AExecUnit.local).(ALocal.data) \u2286 ex.(Execution.data))\n      (CTRL: tid_lift tid aeu2.(AExecUnit.local).(ALocal.ctrl) \u2286 ex.(Execution.ctrl0))\n      (RMW: tid_lift tid aeu2.(AExecUnit.local).(ALocal.rmw) \u2286 ex.(Execution.rmw)):\n  exists eu2,\n    <<STEP: ExecUnit.state_step tid eu1 eu2>> /\\\n    <<SIM: sim_eu tid ex ob aeu2 eu2>>.\nProof.\n  destruct eu1 as [[stmts1 rmap1] local1].\n  destruct aeu1 as [[astmts1 armap1] alocal1].\n  destruct aeu2 as [[astmts2 armap2] alocal2].\n  inv SIM. inv STATE. ss. subst. rename LOCAL into SIM_LOCAL.\n  inv STEP. ss. inv STATE; inv LOCAL; inv EVENT; ss.\n  - (* skip *)\n    eexists (ExecUnit.mk _ _ _). esplits.\n    + econs 1. econs; ss.\n      { econs; ss. }\n      econs 1; ss.\n    + econs; ss.\n      inv SIM_LOCAL; econs; eauto.\n  - (* assign *)\n    eexists (ExecUnit.mk _ _ _). esplits.\n    + econs 1. econs; ss.\n      { econs; ss. }\n      econs 1; ss.\n    + econs; ss.\n      * econs; ss. apply sim_rmap_add; ss. apply sim_rmap_expr; ss.\n      * inv SIM_LOCAL; econs; eauto.\n  - (* read *)\n    exploit LABEL.\n    { rewrite List.nth_error_app2; [|refl]. rewrite Nat.sub_diag. ss. }\n    intro LABEL_LEN.\n    exploit sim_rmap_expr; eauto. instantiate (1 := eloc). intro X. inv X.\n    exploit label_mem_of_ex; eauto. i. des.\n\n    assert (SIM_LOC: sim_view ex ob\n                              (eq (tid, ALocal.next_eid alocal1))\n                              (ValA.annot (sem_expr rmap1 eloc)).(View.ts)).\n    { econs 2; eauto; ss.\n      inv VIEW.\n      { rewrite VIEW1. apply bot_spec. }\n      rewrite VIEW1. des. subst.\n      eapply view_of_eid_ob; eauto.\n      left. left. left. left. left. right. left. econs. splits; [|eauto]. left. apply ADDR. econs; ss. right. ss.\n    }\n\n    assert (SIM_VRN: sim_view ex ob\n                              (eq (tid, ALocal.next_eid alocal1))\n                              local1.(Local.vrn).(View.ts)).\n    { econs 2; eauto; ss.\n      generalize SIM_LOCAL.(VRN). intro VRN.\n      inv VRN.\n      { rewrite VIEW1. apply bot_spec. }\n      rewrite VIEW1. eapply view_of_eid_ob; eauto.\n      inv EID. exploit sim_local_vrn_spec; eauto.\n    }\n\n    assert (SIM_VREL: sim_view ex ob\n                               (eq (tid, ALocal.next_eid alocal1))\n                               (ifc (OrdR.ge ord OrdR.acquire) (Local.vrel local1)).(View.ts)).\n    { econs 2; eauto; ss.\n      generalize SIM_LOCAL.(VREL). intro VREL.\n      destruct (OrdR.ge ord OrdR.acquire) eqn:ORD; ss; cycle 1.\n      { apply bot_spec. }\n      inv VREL.\n      { rewrite VIEW1. apply bot_spec. }\n      rewrite VIEW1. eapply view_of_eid_ob; eauto.\n      inv EID. exploit sim_local_vrel_spec; eauto.\n    }\n\n    assert (exists n,\n               <<READ: Memory.read (ValA.val (sem_expr armap1 eloc)) n (mem_of_ex ex ob) = Some res0>> /\\\n               <<MSG: n > 0 ->\n                      exists eid2,\n                        <<RF: ex.(Execution.rf) eid2 (tid, length (ALocal.labels alocal1))>> /\\\n                        <<VIEW: view_of_eid ex ob eid2 = Some n>> /\\\n                        <<MSG: Memory.get_msg n (mem_of_ex ex ob) = Some (Msg.mk (ValA.val (sem_expr armap1 eloc)) res0 (fst eid2))>>>> /\\\n               <<FWD: n = 0 ->\n                      <<RF: ~ codom_rel ex.(Execution.rf) (tid, length (ALocal.labels alocal1))>> /\\\n                      <<FWD: Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc)) = FwdItem.init>>>> /\\\n               <<SIM_FWD: sim_view ex ob\n                                   (eq (tid, ALocal.next_eid alocal1))\n                                   (FwdItem.read_view (Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc))) n ord).(View.ts)>>).\n    { exploit EX.(Valid.RF1); eauto. i. des.\n      { (* read from uninit *)\n        subst. exists 0.\n        assert (FWD: Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc)) = FwdItem.init).\n        { generalize (SIM_LOCAL.(FWDBANK) (ValA.val (sem_expr armap1 eloc))).\n          destruct (Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc))) eqn:FWD; eauto.\n          i. des. inv WRITE. inv WRITE0. apply Label.is_writing_inv in LABEL0. des. subst.\n          exfalso. eapply EX.(Valid.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. right. econs.\n            + econs; eauto. econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n            + econs; eauto. econs; eauto.\n          - ss.\n        }\n        splits; ss.\n        { lia. }\n        rewrite FWD. econs 1. ss.\n      }\n      exploit label_write_mem_of_ex; eauto. i. des.\n      esplits; eauto.\n      { i. inv H. }\n      econs 2; try exact VIEW0; eauto; ss.\n      generalize (SIM_LOCAL.(FWDBANK) (ValA.val (sem_expr armap1 eloc))). i. des.\n      - (* fwdbank = Some *)\n        destruct (Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc))) eqn:FWD.\n        ss. unfold FwdItem.read_view. s. condtac.\n        + (* forwarded *)\n          apply Bool.andb_true_iff in X. des.\n          destruct (equiv_dec ts (S n)); ss. inv e.\n          assert (eid2 = eid).\n          { eapply view_of_eid_ob_write_write; eauto.\n            inv WRITE. inv WRITE0. apply Label.is_writing_inv in LABEL1. des. subst.\n            econs; eauto.\n          }\n          subst. inv VIEW2.\n          { rewrite VIEW3. apply bot_spec. }\n          rewrite VIEW3. eapply view_of_eid_ob; eauto.\n          inv EID. inv WRITE. inv PO. ss. subst.\n          left. left. left. left. left. right. left.\n          econs. splits; eauto. econs 2. econs; eauto.\n        + (* not forwarded *)\n          eapply view_of_eid_ob; eauto.\n          destruct eid2. destruct (t == tid); cycle 1.\n          { left. left. left. left. left. left. left. left. econs; ss. }\n          inv e.\n          exploit rfi_sim_local_fwd; eauto.\n          { econs; [|apply Label.write_is_writing]. eauto. }\n          { econs; [|apply Label.read_is_reading]. eauto. }\n          { econs; eauto. }\n          i. exploit sim_local_fwd_functional; [exact WRITE|exact x0|]. i. subst.\n          rewrite VIEW1 in TS. inv TS.\n          apply Bool.andb_false_iff in X. des.\n          { unfold Time.t in *. destruct (equiv_dec (S n) (S n)); ss. congr. }\n          apply Bool.negb_false_iff, Bool.andb_true_iff in X. des. destruct ex0; ss.\n          inv WRITE. inv WRITE0. apply Label.is_writing_inv in LABEL1. des. subst.\n          rewrite EID in LABEL0. inv LABEL0.\n          exploit EX0; eauto. clear EX0. intro Y. inv Y. rewrite EID in EID0. inv EID0.\n          exploit (Valid.write_ex_codom_rmw EX); eauto.\n          intro Y. inv Y. left. left. left. left. right. econs. splits.\n          { econs; eauto. econs; eauto. }\n          econs. splits.\n          * econs; eauto.\n          * econs; eauto. apply Bool.orb_true_iff in X0. des.\n            { destruct (equiv_dec arch riscv); ss. inv e. left. ss. }\n            right. econs; eauto.\n      - (* fwdbank = None *)\n        rewrite H. s. eapply view_of_eid_ob; eauto.\n        destruct eid2. destruct (t == tid); cycle 1.\n        { left. left. left. left. left. left. left. econs; ss. }\n        inv e. exfalso. eapply H0. econs; eauto. econs. splits.\n        + econs; eauto. econs; eauto. apply Label.write_is_writing.\n        + exploit rfi_sim_local_fwd; eauto.\n          { econs; [|apply Label.write_is_writing]. eauto. }\n          { econs; [|apply Label.read_is_reading]. eauto. }\n          { econs; eauto. }\n          intro X. apply X.\n    }\n    des.\n\n    assert (SIM_EXT1: sim_view ex ob\n                               (eq (tid, ALocal.next_eid alocal1))\n                               (joins [\n                                    (ValA.annot (sem_expr rmap1 eloc));\n                                    local1.(Local.vrn);\n                                    (ifc (OrdR.ge ord OrdR.acquire) (Local.vrel local1))\n                                ]).(View.ts)).\n    { repeat apply sim_view_join; ss. econs; ss. }\n\n    assert (SIM_EXT2: sim_view ex ob\n                               (eq (tid, ALocal.next_eid alocal1))\n                               (join\n                                  (joins [\n                                       (ValA.annot (sem_expr rmap1 eloc));\n                                       local1.(Local.vrn);\n                                       (ifc (OrdR.ge ord OrdR.acquire) (Local.vrel local1))\n                                   ])\n                                  (FwdItem.read_view (Local.fwdbank local1 (ValA.val (sem_expr armap1 eloc))) n ord)).(View.ts)).\n    { apply sim_view_join; ss. }\n\n    assert (READ_STEP: exists res1 local2, Local.read ex1 ord (sem_expr rmap1 eloc) res1 n local1 (mem_of_ex ex ob) local2).\n    { esplits. econs; eauto.\n      - (* internal *)\n        generalize (SIM_LOCAL.(COH) (ValA.val (sem_expr armap1 eloc))). intro X. inv X.\n        { eapply Memory.latest_mon1. eapply Memory.latest_ts_latest; eauto. apply bot_spec. }\n        eapply Memory.latest_mon1. eapply Memory.latest_ts_latest; eauto.\n        rewrite VIEW1. inv EID. inv REL. inv H. inv H0.\n        inv H2. apply Label.is_writing_inv in LABEL0. des. subst.\n        inv H1. des. inv H.\n        { exploit Valid.coherence_wr; try exact H0; eauto.\n          all: try by econs; eauto; eauto using Label.write_is_writing, Label.read_is_reading.\n          i. des.\n          destruct n.\n          { (* read from uninit *)\n            specialize (FWD eq_refl). des.\n            generalize (SIM_LOCAL.(FWDBANK) (ValA.val (sem_expr armap1 eloc))).\n            rewrite FWD0; ss. i. des; [by inv TS_NONZERO|].\n            exfalso. eapply H1. econs; eauto. econs; eauto.\n            econs; eauto. econs; eauto. econs; eauto. eapply Label.write_is_writing.\n          }\n          exploit MSG; [lia|]. i. des.\n          exploit EX.(Valid.RF_WF); [exact RF|exact RF0|]. i. subst.\n          inv CO.\n          - rewrite VIEW_OF_EID in VIEW2. inv VIEW2. refl.\n          - eapply view_of_eid_ob; eauto. left. left. left. left. left. left. right. eauto.\n        }\n        { inv H1.\n          exploit EX.(Valid.RF2); eauto. i. des.\n          rewrite EID in WRITE. inv WRITE.\n          exploit Valid.coherence_rr; try exact H0; eauto.\n          all: try by econs; eauto; eauto using Label.write_is_writing, Label.read_is_reading.\n          i. des.\n          destruct n.\n          { (* read from uninit *)\n            specialize (FWD eq_refl). des.\n            contradict RF0. econs; eauto.\n          }\n          exploit MSG; [lia|]. i. des.\n          exploit EX.(Valid.RF_WF); [exact RF|exact RF0|]. i. subst.\n          inv CO.\n          - rewrite VIEW_OF_EID in VIEW2. inv VIEW2. refl.\n          - eapply view_of_eid_ob; eauto. left. left. left. left. left. left. right. ss.\n        }\n      - (* external *)\n        ii.\n        exploit in_mem_of_ex; swap 1 2; eauto.\n        { eapply Permutation_NoDup; [by symmetry; eauto|].\n          eapply Execution.eids_spec; eauto.\n        }\n        i. des. destruct msg. ss. subst.\n        destruct n.\n        { (* read from uninit *)\n          specialize (FWD eq_refl). des.\n          assert (view < S ts).\n          { eapply view_of_eid_ob_write; eauto.\n            - left. left. left. left. left. left. left. right. right. econs.\n              + econs; eauto. econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n              + econs; eauto. econs ;eauto.\n            - econs; eauto. apply Label.write_is_writing.\n          }\n          inv SIM_EXT1.\n          { rewrite VIEW2 in TS2. inv TS2. }\n          unfold ALocal.next_eid in VIEW_OF_EID. rewrite VIEW_OF_EID in VIEW0. inv VIEW0.\n          unfold le in VIEW2. lia.\n        }\n        exploit MSG; [lia|]. i. des.\n        exploit EX.(Valid.RF1); eauto. i. des.\n        { contradict NORF. econs. eauto. }\n        exploit EX.(Valid.RF_WF); [exact RF|exact RF0|]. i. subst.\n        exploit EX.(Valid.CO1).\n        { rewrite LABEL0, LABEL1. esplits; eauto. }\n        i. des.\n        { subst. rewrite VIEW1 in VIEW2. inv VIEW2. lia. }\n        { cut (S ts < S n); [lia|].\n          eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. left. right. ss.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        assert (view < S ts).\n        { eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. left. left. right. left. econs; eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        inv SIM_EXT1.\n        { rewrite VIEW3 in TS2. inv TS2. }\n        unfold ALocal.next_eid in VIEW_OF_EID. rewrite VIEW_OF_EID in VIEW0. inv VIEW0.\n        unfold le in VIEW3. lia.\n    }\n\n    des. eexists (ExecUnit.mk _ _ _). esplits.\n    + econs. econs; ss.\n      { econs; ss. }\n      econs 2; eauto.\n    + generalize READ_STEP. intro X. inv X.\n      exploit sim_rmap_expr; eauto. intro Y. inv Y. clear VIEW1.\n      rewrite VAL0 in *. rewrite READ in MSG0. inv MSG0.\n      econs; ss.\n      { econs; ss. apply sim_rmap_add; ss. econs; ss.\n        eapply sim_view_le; eauto. i. subst. ss.\n      }\n      econs; ss.\n      * (* sim_local coh *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_coh_step. rewrite inverse_step.\n        rewrite inverse_union, fun_add_spec. condtac; cycle 1.\n        { eapply sim_view_le; [|exact (SIM_LOCAL.(COH) loc)]. eauto. }\n        inversion e. subst. inv WF.\n        generalize (Local.read_spec LOCAL READ_STEP). i. des. ss.\n        revert COH1. rewrite fun_add_spec. condtac; ss. i.\n        rewrite <- COH1. destruct n.\n        { econs 1. ss. }\n        exploit MSG; [lia|]. i. des.\n        exploit EX.(Valid.RF1); eauto. i. des.\n        { contradict NORF. econs. eauto. }\n        exploit EX.(Valid.RF_WF); [exact RF|exact RF0|]. i. subst.\n        destruct eid0. ss. destruct (t == tid).\n        { inversion e1. subst. exploit rfi_sim_local_fwd.\n          4: { econs; eauto. }\n          all: eauto.\n          { econs; eauto. apply Label.write_is_writing. }\n          { econs; eauto. apply Label.read_is_reading. }\n          i. inv x0. econs 2; try exact VIEW1; ss.\n          left. econs; eauto. econs. splits.\n          - econs; eauto.\n          - econs. splits; eauto.\n        }\n        { econs 2; try exact VIEW1; ss.\n          right. econs; eauto. econs. splits.\n          - econs; eauto. econs; eauto. apply Label.write_is_writing.\n          - econs 2. econs; eauto.\n        }\n      * (* sim_local vrn *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vrn_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto. }\n        destruct (OrdR.ge ord OrdR.acquire_pc) eqn:ORD; ss; eauto.\n        eapply sim_view_le; [|exact SIM_EXT2].\n        i. subst. right. right. econs; eauto. econs; eauto.\n      * (* sim_local vwn *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vwn_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto. }\n        destruct (OrdR.ge ord OrdR.acquire_pc) eqn:ORD; ss; eauto.\n        eapply sim_view_le; [|exact SIM_EXT2].\n        i. subst. right. right. econs; eauto. econs; eauto.\n      * (* sim_local vro *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vro_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join; eauto.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto. }\n        eapply sim_view_le; [|exact SIM_EXT2].\n        i. subst. right. econs; eauto. econs; eauto.\n      * (* sim_local vwo *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vwo_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto.\n      * (* sim_local vcap *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vcap_step; eauto. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join; eauto.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto. }\n        { eapply sim_view_le; [|exact VIEW]. right. right. des. subst.\n          econs; eauto. apply ADDR. econs; eauto. right. econs; eauto.\n        }\n      * (* sim_local vrel *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vrel_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto.\n      * (* sim_local fwdbank *)\n        rewrite List.app_length, Nat.add_1_r. i.\n        generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n        { left. esplits; eauto.\n          rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n          left. econs. splits; eauto. econs; eauto.\n        }\n        { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n          inv H3. destruct x0. ss. inv N. inv H1.\n          - inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n          - eapply H0. econs; eauto. econs; eauto.\n        }\n      * (* sim_local exbank *)\n        destruct ex1; cycle 1.\n        { apply SIM_LOCAL. }\n        destruct n.\n        { (* read from uninit *)\n          specialize (FWD eq_refl). des.\n          econs. splits; eauto.\n          - econs; eauto. apply Label.read_is_reading.\n          - i. contradict RF. econs. eauto.\n        }\n        exploit MSG; [lia|]. i. des.\n        exploit EX.(Valid.RF1); eauto. i. des.\n        { contradict NORF. econs. eauto. }\n        exploit EX.(Valid.RF_WF); [exact RF|exact RF0|]. i. subst.\n        econs. splits; ss.\n        { econs; eauto. apply Label.read_is_reading. }\n        { i. exploit EX.(Valid.RF_WF); [exact H|exact RF0|]. i. subst.\n          rewrite VIEW1 in H0. inv H0. refl.\n        }\n        { econs 2; eauto. refl. }\n      * (* sim_local promises *)\n        i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n        { inv N.\n          - inv WRITE. destruct l; ss. congr.\n          - esplits; cycle 1; eauto. lia.\n        }\n        { esplits; cycle 1; eauto. lia. }\n      * (* sim_local coh_cl *)\n        i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n        inv WF. generalize (Local.read_spec LOCAL READ_STEP). funtac. i. des.\n        destruct (Loc.cl (ValA.val (sem_expr rmap1 eloc)) mloc_cl) eqn:H_CL; cycle 1.\n        { exists mloc_cl. esplits; ss.\n          - i. funtac.\n            + inversion e. subst. rewrite H_CL in *. ss.\n            + inversion e. subst.\n              exploit Loc.cl_refl. rewrite H_CL. ss.\n          - funtac.\n            + inversion e. subst.\n              exploit Loc.cl_refl. rewrite H_CL. ss.\n            + rewrite List.app_length, Nat.add_1_r.\n              rewrite sim_local_coh_cl_step. rewrite inverse_step.\n              rewrite inverse_union. eapply sim_view_le; [| exact COH_CL0]. eauto.\n        }\n        destruct (lt_eq_lt_dec\n          (join (Local.coh local1 (ValA.val (sem_expr rmap1 eloc)))\n                (join\n                  (View._join (ValA.annot (sem_expr rmap1 eloc))\n                      (View._join (Local.vrn local1)\n                        (View._join\n                            (ifc (OrdR.ge ord OrdR.acquire) (Local.vrel local1))\n                            View._bot)))\n                  (FwdItem.read_view\n                      (Local.fwdbank local1 (ValA.val (sem_expr rmap1 eloc))) n ord))).(View.ts)\n          (Local.coh local1 mloc_cl).(View.ts)).\n        { (* <= *)\n          eexists mloc_cl. splits; ss.\n          - i. funtac.\n            { inv s; lia. }\n            inversion e. subst.\n            rewrite COH_MAX_CL; ss. apply join_l.\n          - rewrite List.app_length, Nat.add_1_r.\n            rewrite sim_local_coh_cl_step. rewrite inverse_step.\n            rewrite inverse_union, fun_add_spec. condtac; cycle 1.\n            { eapply sim_view_le; [|exact COH_CL0]. eauto. }\n            inversion e. subst. inv s; ss.\n            { unfold join in H. unfold Time.join in H. lia. }\n            rewrite H. eapply sim_view_le; [|exact COH_CL0]. eauto.\n        }\n        { (* > *)\n          eexists (ValA.val (sem_expr rmap1 eloc)). splits; ss.\n          - eapply Loc.cl_trans; eauto. eapply Loc.cl_sym. ss.\n          - i. funtac.\n            rewrite COH_MAX_CL; try lia. eapply Loc.cl_trans; eauto.\n          - rewrite List.app_length, Nat.add_1_r.\n            rewrite sim_local_coh_cl_step. rewrite inverse_step.\n            rewrite inverse_union. funtac.\n            apply sim_view_join.\n            + inv COH_CL0.\n              { econs; eauto. apply le_antisym; [| apply bot_spec].\n                rewrite COH_MAX_CL; ss. rewrite VIEW1. ss.\n              }\n              econs 2; try exact VIEW1; eauto. rewrite COH_MAX_CL; ss.\n            + eapply sim_view_le; [|exact SIM_EXT2].\n              i. subst. right. econs; eauto. simtac. econs; eauto. ss.\n              eapply Loc.cl_trans; eauto. eapply Loc.cl_sym. ss.\n        }\n      * (* sim_local vpr *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpr_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact SIM_LOCAL.(VPR)]. eauto.\n      * (* sim_local vpa *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpa_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n      * (* sim_local per *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpc_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPC) loc)]. eauto.\n  - (* write *)\n    exploit LABEL.\n    { rewrite List.nth_error_app2; [|refl]. rewrite Nat.sub_diag. ss. }\n    intro LABEL_LEN.\n    exploit label_write_mem_of_ex; eauto. i. des.\n    exploit sim_rmap_expr; eauto. instantiate (1 := eloc). intro X. inv X.\n    exploit sim_rmap_expr; eauto. instantiate (1 := eval). intro X. inv X.\n\n    assert (COH_LT: View.ts (Local.coh local1 (ValA.val (sem_expr rmap1 eloc))) < S n).\n    { (* internal *)\n      rewrite <- VAL.\n      eapply Memory.latest_ts_read_lt; eauto.\n      generalize (SIM_LOCAL.(COH) (ValA.val (sem_expr armap1 eloc))).\n      intro X. inv X.\n      { rewrite VIEW2. clear. unfold bot. unfold Time.bot. lia. }\n      eapply Time.le_lt_trans; eauto. inv EID. inv REL. inv H. inv H0.\n      inv H2. apply Label.is_writing_inv in LABEL0. des. subst.\n      inv H1. des. inv H.\n      { exploit Valid.coherence_ww; try exact H0; eauto.\n        all: try by econs; eauto; eauto using Label.write_is_writing, Label.read_is_reading.\n        i. eapply view_of_eid_ob_write; eauto.\n        - left. left. left. left. left. left. right. ss.\n        - econs; eauto. apply Label.write_is_writing.\n      }\n      { inv H1.\n        exploit EX.(Valid.RF2); eauto. i. des.\n        rewrite EID in WRITE. inv WRITE.\n        exploit Valid.coherence_rw; try exact H0; eauto.\n        all: try by econs; eauto; eauto using Label.write_is_writing, Label.read_is_reading.\n        i. eapply view_of_eid_ob_write; eauto.\n        - left. left. left. left. left. left. right. ss.\n        - econs; eauto. apply Label.write_is_writing.\n      }\n    }\n\n    eexists (ExecUnit.mk _ _ _). esplits.\n    + econs. econs; ss.\n      { econs; ss. }\n      econs 3; ss.\n      econs; try refl.\n      all: cycle 1.\n      { rewrite <- VAL, <- VAL0. eauto. }\n      { rewrite SIM_LOCAL.(PROMISES). esplits; eauto. }\n      econs; try refl; ss.\n      * (* external *)\n        unfold lt. apply le_n_S. s. repeat apply join_spec.\n        { inv VIEW0.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. destruct eid. ss. des. subst.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. right. left. econs. splits.\n            + instantiate (1 := (tid, _)).  left. apply ADDR. econs; eauto. right. ss.\n            + eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { inv VIEW1.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. destruct eid. ss. des. subst.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. right. left. econs. splits.\n            + instantiate (1 := (tid, _)).  right. apply DATA. econs; eauto. right. ss.\n            + eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { generalize SIM_LOCAL.(VCAP). intro X. inv X.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. inv EID.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. right. right. econs. splits; eauto.\n            econs. econs; ss. econs; eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { generalize SIM_LOCAL.(VWN). intro X. inv X.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. inv EID.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - eapply sim_local_vwn_spec; eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { destruct (OrdW.ge ord OrdW.release_pc) eqn:ORD; s; cycle 1.\n          { apply bot_spec. }\n          generalize SIM_LOCAL.(VRO). intro X. inv X.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. inv EID.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - inv REL. des. inv H.\n            left. left. left. right. left. right. econs. split.\n            { econs; try refl. inv H2. destruct l; ss. econs; eauto. }\n            econs. splits; eauto. econs; eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { destruct (OrdW.ge ord OrdW.release_pc) eqn:ORD; s; cycle 1.\n          { apply bot_spec. }\n          generalize SIM_LOCAL.(VWO). intro X. inv X.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2. inv EID.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - inv REL. des. inv H.\n            left. left. left. right. left. right. econs. splits.\n            { econs; try refl. inv H2. destruct l; ss. econs; eauto. }\n            econs. splits; eauto. econs; eauto.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { unfold ifc. condtac; cycle 1.\n          { apply bot_spec. }\n          destruct ex1; ss. exploit EX0; eauto. i. des. inv x0.\n          generalize (SIM_LOCAL.(EXBANK)). rewrite x. intro Y. inv Y. des.\n          inv REL2.\n          { rewrite VIEW2. apply bot_spec. }\n          rewrite VIEW2.\n          apply lt_n_Sm_le. eapply view_of_eid_ob_write; eauto.\n          - left. left. left. right. right. rewrite X. s. apply RMW. econs; ss. right. econs; ss.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { apply bot_spec. }\n      * (* exclusive *)\n        i. specialize (EX0 H). des. inv EX1. des.\n        destruct a; ss. destruct ex0; ss. symmetry in H1.\n        generalize (SIM_LOCAL.(EXBANK)). rewrite EX0. intro X. inv X. des.\n        inv REL. apply Label.is_reading_inv in LABEL0. des. subst.\n        esplits; eauto. i. subst.\n        exploit List.nth_error_Some. rewrite H1. intros [X _]. exploit X; ss. clear X. intro X.\n        exploit LABEL.\n        { rewrite List.nth_error_app1; eauto. }\n        intro LABEL_READ. destruct ex1; ss.\n        rewrite EID in LABEL_READ. inv LABEL_READ.\n        ii. exploit in_mem_of_ex; swap 1 2; eauto.\n        { eapply Permutation_NoDup; [by symmetry; eauto|].\n          eapply Execution.eids_spec; eauto.\n        }\n        i. des. destruct msg. ss. subst.\n\n        exploit EX.(Valid.CO1).\n        { rewrite LABEL0, LABEL_LEN. esplits; eauto. f_equal. f_equal. ss. }\n        i. des; cycle 2.\n        { cut (S n < S ts); [lia|].\n          eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. left. right. ss.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n        { inv x0. congr. }\n\n        inv REL1.\n        { (* read from uninit *)\n          exploit EX.(Valid.RF1); eauto. i. des; cycle 1.\n          { exploit label_write_mem_of_ex; eauto. i. des.\n            exploit REL0; eauto. rewrite VIEW3. i. inv x.\n          }\n\n          eapply EX.(Valid.ATOMIC). econs; cycle 1.\n          { econs. splits.\n            - econs.\n              + right. econs; cycle 1.\n                * econs; eauto. econs; eauto.\n                * econs; eauto. rewrite H0.\n                  econs; eauto using Label.read_is_accessing, Label.write_is_accessing.\n              + econs. s. congr.\n            - econs; eauto.\n          }\n          { apply RMW. econs; eauto. right. econs; eauto. }\n        }\n\n        inv EID0. exploit REL0; eauto. i.\n        replace v with b.(Exbank.ts) in * by (apply Time.le_antisymm; ss).\n\n        exploit Valid.rf_inv_write; eauto. i. des.\n        exploit EX.(Valid.CO1).\n        { rewrite LABEL0, LABEL1. esplits; eauto. f_equal. f_equal. ss. }\n        i. des.\n        { subst. rewrite VIEW_OF_EID in VIEW2. inv VIEW2. rewrite H5 in *. lia. }\n        { cut (S ts < b.(Exbank.ts)); [lia|].\n          eapply view_of_eid_ob_write; eauto.\n          - left. left. left. left. left. left. right. ss.\n          - econs; eauto. apply Label.write_is_writing.\n        }\n\n        eapply EX.(Valid.ATOMIC). econs; cycle 1.\n        { econs. splits.\n          - econs.\n            + left. econs; eauto.\n            + econs. s. congr.\n          - econs; eauto.\n        }\n        { apply RMW. econs; eauto. right. econs; eauto. }\n    + econs; ss.\n      { econs; ss. apply sim_rmap_add; ss. econs; ss.\n        unfold ifc. condtac; [|econs 1]. econs 2; eauto; ss. refl.\n      }\n      econs; ss.\n      * i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_coh_step. rewrite inverse_step.\n        rewrite inverse_union, fun_add_spec. condtac; ss.\n        { unfold Memory.get_msg in MSG. ss. rewrite MSG.\n          inversion e. subst. condtac; ss.\n          econs 2; eauto; [|refl]. right. econs; eauto.\n          econs. splits; eauto. econs; eauto. econs; eauto.\n          rewrite VAL. apply Label.write_is_writing.\n        }\n        { eapply sim_view_le; [|exact (SIM_LOCAL.(COH) loc)]. eauto. }\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vrn_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vwn_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vro_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vwo_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto. }\n        { eapply sim_view_le; [by right; eauto|]. econs 2; eauto.\n          - econs; eauto. econs; eauto.\n          - refl.\n        }\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vcap_step. rewrite inverse_step.\n        rewrite inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto. }\n        { eapply sim_view_le; [|by eauto]. s. i. des. subst.\n          right. econs; ss. right. apply ADDR. econs; eauto. right. econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vrel_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto. }\n        { destruct (OrdW.ge ord OrdW.release) eqn:ORD; [|by econs].\n          eapply sim_view_le; [by right; eauto|]. econs 2; eauto.\n          - econs; eauto. econs; eauto.\n          - refl.\n        }\n      * rewrite List.app_length, Nat.add_1_r. i.\n        rewrite fun_add_spec. condtac; s; cycle 1.\n        { generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n          - left. esplits; eauto.\n            rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n            left. econs. splits; eauto. econs; eauto. econs; eauto. s.\n            destruct (equiv_dec (ValA.val (sem_expr armap1 eloc)) loc); ss. congr.\n          - right. splits; ss. i. rewrite sim_local_fwd_none_step, inverse_step. ii. inv H1. inv REL.\n            + eapply H0; eauto.\n            + inv H1. inv H3. apply Label.is_writing_inv in LABEL0. des. subst. congr.\n        }\n        { inversion e. subst. left. esplits; eauto.\n          - lia.\n          - econs; eauto.\n            + econs; eauto. rewrite VAL. apply Label.write_is_writing.\n            + i. destruct eid. inv PO. inv PO0. ss. subst. lia.\n          - rewrite inverse_union. apply sim_view_join.\n            + eapply sim_view_le; [|by apply VIEW0].\n              i. destruct x0. ss. des. subst.\n              left. econs; eauto. apply ADDR. econs; eauto. right. ss.\n            + eapply sim_view_le; [|by apply VIEW1].\n              i. destruct x0. ss. des. subst.\n              right. econs; eauto. apply DATA. econs; eauto. right. ss.\n          - econs; i.\n            + econs; eauto.\n            + inv H. rewrite LABEL_LEN in EID. inv EID. ss.\n        }\n      * destruct ex1; ss. apply SIM_LOCAL.(EXBANK).\n      * i. rewrite Promises.unset_o. condtac.\n        { econs; ss. i. des. inversion e. subst.\n          rewrite List.app_length in *. ss.\n          assert ((tid, length (ALocal.labels alocal1)) = (tid, n0)).\n          { eapply view_of_eid_ob_write_write; eauto. }\n          inv H. lia.\n        }\n        rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n        { inv N.\n          - inv WRITE. destruct l; ss. congr.\n          - esplits; cycle 1; eauto. lia.\n        }\n        { esplits; cycle 1; eauto. lia. }\n      * (* sim_local coh_cl *)\n        i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n        destruct (Loc.cl (ValA.val (sem_expr rmap1 eloc)) mloc_cl) eqn:H_CL; cycle 1.\n        { exists mloc_cl. esplits; ss.\n          - i. funtac.\n            + inversion e. subst. rewrite H_CL in *. ss.\n            + inversion e. subst.\n              exploit Loc.cl_refl. rewrite H_CL. ss.\n          - funtac.\n            + inversion e. subst.\n              exploit Loc.cl_refl. rewrite H_CL. ss.\n            + rewrite List.app_length, Nat.add_1_r.\n              rewrite sim_local_coh_cl_step. rewrite inverse_step.\n              rewrite inverse_union. eapply sim_view_le; [| exact COH_CL0]. eauto.\n        }\n        destruct (lt_eq_lt_dec (S n) ((Local.coh local1) mloc_cl).(View.ts)).\n        { (* <= *)\n          eexists mloc_cl. splits; ss.\n          - i. funtac.\n            { inv s; lia. }\n            inversion e. subst. inv s; lia.\n          - rewrite List.app_length, Nat.add_1_r.\n            rewrite sim_local_coh_cl_step. rewrite inverse_step.\n            rewrite inverse_union, fun_add_spec. condtac; cycle 1.\n            { eapply sim_view_le; [|exact COH_CL0]. eauto. }\n            inversion e. subst. inv s; ss.\n            { unfold join in H. unfold Time.join in H. lia. }\n            rewrite H. eapply sim_view_le; [|exact COH_CL0]. eauto.\n        }\n        { (* > *)\n          eexists (ValA.val (sem_expr rmap1 eloc)). splits; ss.\n          - eapply Loc.cl_trans; eauto. eapply Loc.cl_sym. ss.\n          - i. funtac.\n            rewrite COH_MAX_CL; try lia. eapply Loc.cl_trans; eauto.\n          - rewrite List.app_length, Nat.add_1_r.\n            rewrite sim_local_coh_cl_step. rewrite inverse_step.\n            rewrite inverse_union. funtac.\n            econs 2; eauto; ss.\n            right. econs; eauto. econs; eauto. econs; eauto. s.\n            eapply Loc.cl_trans; eauto. eapply Loc.cl_sym. rewrite VAL. ss.\n        }\n      * (* sim_local vpr *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpr_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact SIM_LOCAL.(VPR)]. eauto.\n      * (* sim_local vpa *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpa_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n      * (* sim_local per *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpc_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPC) loc)]. eauto.\n  - (* write_failure *)\n    eexists (ExecUnit.mk _ _ _). esplits.\n    + econs. econs; ss.\n      { econs; ss. }\n      econs 4; ss.\n    + econs; ss.\n      * econs; ss. apply sim_rmap_add; ss. econs; ss. econs 1. ss.\n      * inv SIM_LOCAL; econs; eauto. econs.\n  - (* barrier *)\n    exploit LABEL.\n    { rewrite List.nth_error_app2; ss. rewrite Nat.sub_diag. ss. }\n    intro LABEL_LEN. destruct b0; eexists (ExecUnit.mk _ _ _).\n    + (* isb *)\n      esplits.\n      { econs. econs; ss.\n        - econs; ss.\n        - econs 5; ss.\n      }\n      econs; ss.\n      econs; ss.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        i. rewrite sim_local_coh_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply SIM_LOCAL.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrn_step. rewrite inverse_step.\n        rewrite ? inverse_union. apply sim_view_join.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto. }\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)].\n          right. left. right.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwn_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vro_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwo_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vcap_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrel_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. i.\n        generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n        { left. esplits; eauto.\n          rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n          left. econs. splits; eauto. econs; eauto.\n        }\n        { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n          destruct x, x0. inv H3. ss. inv N. inv H1.\n          - inv H3. inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n          - inv H3. ss. subst. eapply H0. econs; eauto. econs; eauto.\n        }\n      * apply SIM_LOCAL.\n      * i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n        { inv N.\n          - inv WRITE. destruct l; ss. congr.\n          - esplits; cycle 1; eauto. lia.\n        }\n        { esplits; cycle 1; eauto. lia. }\n      * i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n        exists mloc_cl. splits; ss.\n        rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_coh_cl_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply COH_CL0.\n      * (* sim_local vpr *)\n        rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpr_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VPR)]. eauto.\n      * (* sim_local vpa *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpa_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n      * (* sim_local per *)\n        i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpc_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPC) loc)]. eauto.\n    + (* dmb *)\n      esplits.\n      { econs. econs; ss.\n        - econs; ss.\n        - econs 6; ss. econs; ss.\n      }\n      econs; ss.\n      econs; ss.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        i. rewrite sim_local_coh_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply SIM_LOCAL.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrn_step. rewrite inverse_step.\n        rewrite ? inverse_union. repeat apply sim_view_join; eauto using sim_view_bot.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto. }\n        { destruct rr; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VRO)].\n          right. left. left. left. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n        { destruct wr; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VWO)].\n          right. left. left. right. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwn_step. rewrite inverse_step.\n        rewrite ? inverse_union. repeat apply sim_view_join; eauto using sim_view_bot.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto. }\n        { destruct rw; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VRO)].\n          right. left. left. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n        { destruct ww; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VWO)].\n          right. left. right. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vro_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwo_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vcap_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrel_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. i.\n        generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n        { left. esplits; eauto.\n          rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n          left. econs. splits; eauto. econs; eauto.\n        }\n        { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n          destruct x, x0. inv H3. ss. inv N. inv H1.\n          - inv H3. inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n          - inv H3. ss. subst. eapply H0. econs; eauto. econs; eauto.\n        }\n      * apply SIM_LOCAL.\n      * i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n        { inv N.\n          - inv WRITE. destruct l; ss. congr.\n          - esplits; cycle 1; eauto. lia.\n        }\n        { esplits; cycle 1; eauto. lia. }\n      * i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n        exists mloc_cl. splits; ss.\n        rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_coh_cl_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply COH_CL0.\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpr_step. rewrite inverse_step.\n        rewrite inverse_union.\n        unfold ifc. condtac; cycle 1.\n        { eapply sim_view_le; [by left; eauto|]. rewrite bot_join; [|exact Time.order]. apply SIM_LOCAL. }\n        destruct rr; destruct rw; destruct wr; destruct ww; ss. cleartriv.\n        repeat eapply sim_view_join.\n        { eapply sim_view_le; [by left; eauto|]. apply SIM_LOCAL. }\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. i.\n          right. econs; eauto.\n          inv PR. inv REL. obtac. simtac.\n        }\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. i.\n          right. econs; eauto.\n          inv PR. inv REL. obtac. simtac.\n        }\n      * i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpa_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n      * i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpc_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPC) loc)]. eauto.\n    + (* dsb *)\n      esplits.\n      { econs. econs; ss.\n        - econs; ss.\n        - econs 7; ss. econs; ss.\n      }\n      econs; ss.\n      econs; ss.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        i. rewrite sim_local_coh_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply SIM_LOCAL.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrn_step. rewrite inverse_step.\n        rewrite ? inverse_union. repeat apply sim_view_join; eauto using sim_view_bot.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto. }\n        { destruct rr; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VRO)].\n          right. left. left. left. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n        { destruct wr; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VWO)].\n          right. left. left. right. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwn_step. rewrite inverse_step.\n        rewrite ? inverse_union. repeat apply sim_view_join; eauto using sim_view_bot.\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto. }\n        { destruct rw; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VRO)].\n          right. left. left. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n        { destruct ww; eauto using sim_view_bot.\n          eapply sim_view_le; [|exact SIM_LOCAL.(VWO)].\n          right. left. right. rewrite seq_assoc.\n          inv PR. econs; eauto. econs; splits; eauto.\n          econs; eauto.\n        }\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vro_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vwo_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vcap_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_vrel_step. rewrite inverse_step.\n        rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto.\n      * rewrite List.app_length, Nat.add_1_r. i.\n        generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n        { left. esplits; eauto.\n          rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n          left. econs. splits; eauto. econs; eauto.\n        }\n        { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n          destruct x, x0. inv H3. ss. inv N. inv H1.\n          - inv H3. inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n          - inv H3. ss. subst. eapply H0. econs; eauto. econs; eauto.\n        }\n      * apply SIM_LOCAL.\n      * i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n        { inv N.\n          - inv WRITE. destruct l; ss. congr.\n          - esplits; cycle 1; eauto. lia.\n        }\n        { esplits; cycle 1; eauto. lia. }\n      * i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n        exists mloc_cl. splits; ss.\n        rewrite List.app_length, Nat.add_1_r. s.\n        rewrite sim_local_coh_cl_step. rewrite inverse_step.\n        rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n        apply COH_CL0.\n      * rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpr_step. rewrite inverse_step.\n        rewrite inverse_union.\n        unfold ifc. condtac; cycle 1.\n        { eapply sim_view_le; [by left; eauto|]. rewrite bot_join; [|exact Time.order]. apply SIM_LOCAL. }\n        destruct rr; destruct rw; destruct wr; destruct ww; ss. cleartriv.\n        repeat eapply sim_view_join.\n        { eapply sim_view_le; [by left; eauto|]. apply SIM_LOCAL. }\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. i.\n          right. econs; eauto.\n          inv PR. inv REL. obtac. simtac.\n        }\n        { eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. i.\n          right. econs; eauto.\n          inv PR. inv REL. obtac. simtac.\n        }\n      * i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpa_step. rewrite inverse_step.\n        rewrite inverse_union.\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n      * i. rewrite List.app_length, Nat.add_1_r.\n        rewrite sim_local_vpc_step. rewrite inverse_step.\n        rewrite inverse_union.\n        unfold ifc. condtac; cycle 1.\n        { eapply sim_view_le; [by left; eauto|]. apply SIM_LOCAL. }\n        destruct rr; destruct rw; destruct wr; destruct ww; ss. cleartriv.\n        ss. apply sim_view_join.\n        { eapply sim_view_le; [by left; eauto|]. apply SIM_LOCAL. }\n        eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. i.\n        right. econs; eauto.\n        inv PR. econs. econs; eauto. simtac.\n  - (* if *)\n    exploit LABEL.\n    { rewrite List.nth_error_app2; ss. rewrite Nat.sub_diag. ss. }\n    intro LABEL_LEN. eexists (ExecUnit.mk _ _ _).\n    esplits.\n    { econs. econs; ss.\n      - econs 8; ss.\n      - econs 8; ss.\n    }\n    generalize (sim_rmap_expr cond RMAP). intro X. inv X.\n    econs; ss.\n    { econs; ss. rewrite VAL. ss. }\n    econs; ss.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      i. rewrite sim_local_coh_step. rewrite inverse_step.\n      rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vrn_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRN)]. eauto.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vwn_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWN)]. eauto.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vro_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VRO)]. eauto.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vwo_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VWO)]. eauto.\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vcap_step. rewrite inverse_step.\n      rewrite ? inverse_union. apply sim_view_join.\n      { eapply sim_view_le; [|exact SIM_LOCAL.(VCAP)]. eauto. }\n      { eapply sim_view_le; [|exact VIEW]. s. i. des. subst.\n        right. left. econs; ss. apply CTRL. econs; ss. right. econs; eauto.\n      }\n    * rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vrel_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [|exact SIM_LOCAL.(VREL)]. eauto.\n    * rewrite List.app_length, Nat.add_1_r. i.\n      generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n      { left. esplits; eauto.\n        rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n        left. econs. splits; eauto. econs; eauto.\n      }\n      { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n        destruct x, x0. inv H3. ss. inv N. inv H1.\n        - inv H3. inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n        - inv H3. ss. subst. eapply H0. econs; eauto. econs; eauto.\n      }\n    * apply SIM_LOCAL.\n    * i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n      { inv N.\n        - inv WRITE. destruct l; ss. congr.\n        - esplits; cycle 1; eauto. lia.\n      }\n      { esplits; cycle 1; eauto. lia. }\n    * i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n      exists mloc_cl. splits; ss.\n      rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_coh_cl_step. rewrite inverse_step.\n      rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply COH_CL0.\n    * rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpr_step. rewrite inverse_step.\n      rewrite inverse_union.\n      eapply sim_view_le; [|exact SIM_LOCAL.(VPR)]. eauto.\n    * i. rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpa_step. rewrite inverse_step.\n      rewrite inverse_union.\n      eapply sim_view_le; [|exact (SIM_LOCAL.(VPA) loc)]. eauto.\n    * i. rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpc_step. rewrite inverse_step.\n      rewrite inverse_union.\n      eapply sim_view_le; [|exact (SIM_LOCAL.(VPC) loc)]. eauto.\n  - (* dowhile *)\n    eexists (ExecUnit.mk _ _ _). esplits.\n    + econs. econs; ss.\n      { econs; ss. }\n      * econs; ss.\n    + econs; ss.\n      inv SIM_LOCAL; econs; eauto.\n  - (* flushopt *)\n    exploit LABEL.\n    { rewrite List.nth_error_app2; ss. rewrite Nat.sub_diag. ss. }\n    intro LABEL_LEN.\n    exploit sim_rmap_expr; eauto. instantiate (1 := eloc). intro X. inv X. rewrite VAL in *.\n    generalize (SIM_LOCAL.(COH_CL)). intro H. specialize (H (ValA.val (sem_expr rmap1 eloc))). des.\n    eexists (ExecUnit.mk _ _ _). splits.\n    { econs. econs; ss.\n      - econs; ss.\n      - econs 9; ss. econs; ss. econs; [rewrite CL|]; ss.\n        i. unfold ifc. condtac; [| apply bot_spec]. rewrite COH_MAX_CL; ss.\n        eapply Loc.cl_trans; eauto. eapply Loc.cl_sym. ss.\n    }\n    econs; ss. econs; ss.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      i. rewrite sim_local_coh_step. rewrite inverse_step.\n      rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vrn_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vwn_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vro_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vwo_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vcap_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_vrel_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + rewrite List.app_length, Nat.add_1_r. i.\n      generalize (SIM_LOCAL.(FWDBANK) loc). i. des.\n      { left. esplits; eauto.\n        rewrite sim_local_fwd_step. econs. instantiate (1 := (_, _)). splits; [|econs; ss].\n        left. econs. splits; eauto. econs; eauto.\n      }\n      { right. splits; ss. ii. inv H1. inv REL. inv H1. rewrite Execution.po_po_adj in H3. inv H3. des.\n        destruct x, x0. inv H3. ss. inv N. inv H1.\n        - inv H3. inv H2. inv H3. rewrite LABEL_LEN in EID. inv EID. ss.\n        - inv H3. ss. subst. eapply H0. econs; eauto. econs; eauto.\n      }\n    + apply SIM_LOCAL.\n    + i. rewrite SIM_LOCAL.(PROMISES), List.app_length. s. econs; i; des.\n      { inv N.\n        - inv WRITE. destruct l; ss; congr.\n        - esplits; cycle 1; eauto. lia.\n      }\n      { esplits; cycle 1; eauto. lia. }\n    + i. generalize SIM_LOCAL.(COH_CL). intro X. specialize (X loc). des.\n      exists mloc_cl0. splits; ss.\n      rewrite List.app_length, Nat.add_1_r. s.\n      rewrite sim_local_coh_cl_step. rewrite inverse_step.\n      rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply COH_CL1.\n    + i. rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpr_step. rewrite inverse_step.\n      rewrite ? inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\n    + i. rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpa_step. rewrite inverse_step.\n      rewrite inverse_union. apply sim_view_join.\n      { eapply sim_view_le; [by left; eauto|]. apply SIM_LOCAL. }\n      exploit sim_rmap_expr; eauto. intro X. inv X. rewrite <- VAL in *.\n      unfold ifc. condtac; [| econs 1]; ss.\n      apply sim_view_join.\n      * hexploit label_mem_of_ex; eauto. i. des.\n        econs 2; eauto.\n        { right. econs; ss. simtac. econs; eauto. apply Loc.cl_sym. ss. }\n        inv COH_CL0.\n        { rewrite VIEW2. apply bot_spec. }\n        etrans; eauto.\n        inv EID. inv REL. obtac.\n        eapply view_of_eid_ob; eauto.\n        left. left. right. left. simtac. econs; ss. simtac.\n        destruct l; ss; econs; eauto with axm; apply Loc.cl_sym; ss.\n      * hexploit label_mem_of_ex; eauto. i. des.\n        econs 2; eauto.\n        { right. econs; ss. simtac. econs; eauto. apply Loc.cl_sym. ss. }\n        generalize (SIM_LOCAL.(VPR)). intro Z. inv Z.\n        { rewrite VIEW2. apply bot_spec. }\n        etrans; eauto. eapply view_of_eid_ob; eauto.\n        inv EID. inv REL.\n        obtac. left. left. right. right. simtac.\n    + i. rewrite List.app_length, Nat.add_1_r.\n      rewrite sim_local_vpc_step. rewrite inverse_step.\n      rewrite inverse_union. eapply sim_view_le; [by left; eauto|].\n      apply SIM_LOCAL.\nQed.\n\nLemma sim_eu_rtc_step\n      p ex ob tid aeu1 eu1 aeu2\n      (EX: Valid.ex p ex)\n      (OB: Permutation ob (Execution.eids ex))\n      (LINEARIZED: linearized (Execution.ob ex) ob)\n      (SIM: sim_eu tid ex ob aeu1 eu1)\n      (WF_EU: ExecUnit.wf tid eu1)\n      (WF_AEU: AExecUnit.wf aeu1)\n      (STEP: rtc AExecUnit.step aeu1 aeu2)\n      (LOCAL: IdMap.find tid EX.(Valid.aeus) = Some aeu2):\n  exists eu2,\n    <<SIM: sim_eu tid ex ob aeu2 eu2>> /\\\n    <<STEP: rtc (ExecUnit.state_step tid) eu1 eu2>>.\nProof.\n  revert eu1 WF_EU SIM. induction STEP.\n  { esplits; eauto. }\n  i.\n  exploit AExecUnit.step_future; eauto. i. des.\n  exploit AExecUnit.rtc_step_future; eauto. i. des.\n  exploit sim_eu_step; eauto.\n  { i. unfold Execution.label. s.\n    rewrite EX.(Valid.LABELS), IdMap.map_spec, LOCAL. s.\n    inv LE0. des. rewrite LABELS, List.nth_error_app1; ss.\n    apply List.nth_error_Some. congr.\n  }\n  { rewrite EX.(Valid.ADDR). ii. econs.\n    - rewrite IdMap.map_spec, LOCAL. ss.\n    - eapply tid_lift_incl; eauto. inv LE0; ss.\n  }\n  { rewrite EX.(Valid.DATA). ii. econs.\n    - rewrite IdMap.map_spec, LOCAL. ss.\n    - eapply tid_lift_incl; eauto. inv LE0; ss.\n  }\n  { rewrite EX.(Valid.CTRL). ii. econs.\n    - rewrite IdMap.map_spec, LOCAL. ss.\n    - eapply tid_lift_incl; eauto. inv LE0; ss.\n  }\n  { rewrite EX.(Valid.RMW). ii. econs.\n    - rewrite IdMap.map_spec, LOCAL. ss.\n    - eapply tid_lift_incl; eauto. inv LE0; ss.\n  }\n  i. des.\n  specialize (ExecUnit.state_step_wf STEP0 WF_EU). i.\n  exploit IHSTEP; try exact SIM0; eauto. i. des.\n  esplits; eauto.\nQed.\n\nTheorem axiomatic_to_promising\n      p ex smem\n      (EX: Valid.ex p ex)\n      (PMEM: Valid.persisted ex smem):\n  exists m,\n    <<STEP: Machine.exec p m>> /\\\n    <<TERMINAL: Valid.is_terminal EX -> Machine.is_terminal m>> /\\\n    <<STATE: IdMap.Forall2\n               (fun tid sl aeu => sim_state_weak (fst sl) aeu.(AExecUnit.state))\n               m.(Machine.tpool) EX.(Valid.aeus)>> /\\\n    <<MEM: sim_mem ex m.(Machine.mem)>> /\\\n    <<PMEM: Machine.persisted m smem>>.\nProof.\n  (* Linearize events and construct memory. *)\n  exploit (linearize (Execution.eids ex)).\n  { eapply EX.(Valid.EXTERNAL). }\n  i. des. rename l' into ob.\n  remember (mem_of_ex ex ob) as mem eqn:MEM.\n\n  (* Construct promise steps. *)\n  exploit (Machine.pf_init_with_promises p mem); eauto.\n  { i. subst. unfold mem_of_ex in MSG. rewrite in_filter_map_iff in MSG. des.\n    exploit Permutation_in; eauto. intro X.\n    generalize (Execution.eids_spec ex). i. des.\n    apply LABEL in X. destruct (Execution.label a ex) eqn:Y; ss.\n    destruct t; ss. inv MSG0. s. unfold Execution.label in Y.\n    rewrite EX.(Valid.LABELS), IdMap.map_spec in Y.\n    destruct (IdMap.find (fst a) (Valid.PRE EX).(Valid.aeus)) eqn:Z; ss.\n    generalize (EX.(Valid.AEUS) (fst a)). intro W. inv W; ss. congr.\n  }\n  unfold IdMap.Equal, Machine.init_with_promises. s. i. des. subst.\n  setoid_rewrite IdMap.mapi_spec in TPOOL.\n\n  (* It's sufficient to construct steps from the promised state. *)\n  cut (exists m0,\n          <<STEP: rtc (Machine.step ExecUnit.state_step) m m0>> /\\\n          <<NOPROMISE: Machine.no_promise m0>> /\\\n          <<TERMINAL: Valid.is_terminal EX -> Machine.is_terminal m0>> /\\\n          <<STATE: IdMap.Forall2\n                     (fun tid sl aeu => sim_state_weak (fst sl) aeu.(AExecUnit.state))\n                     m0.(Machine.tpool) EX.(Valid.aeus)>> /\\\n          <<MEM: sim_mem ex (Machine.mem m0)>> /\\\n          <<PMEM: Machine.persisted m0 smem>>).\n  { i. des. esplits; eauto. econs; eauto.\n    etrans.\n    - eapply rtc_mon; [|by eauto]. apply Machine.step_mon. right. ss.\n    - eapply rtc_mon; [|by eauto]. apply Machine.step_mon. left. ss.\n  }\n  clear STEP.\n\n  (* Execute threads one-by-one (induction). *)\n  assert (IN: forall tid stmts\n                (FIND1: IdMap.find tid p = Some stmts),\n             IdMap.find tid m.(Machine.tpool) =\n             Some (State.init stmts,\n                   Local.init_with_promises (Promises.promises_from_mem tid (Machine.mem m)))).\n  { i. rewrite TPOOL, FIND1, MEM0. ss. }\n  assert (OUT: forall tid st lc\n                 (FIND1: IdMap.find tid p = None)\n                 (FIND2: IdMap.find tid m.(Machine.tpool) = Some (st, lc)),\n             exists aeu,\n               <<AEU: IdMap.find tid EX.(Valid.aeus) = Some aeu>> /\\\n               <<STATE: sim_state_weak st aeu.(AExecUnit.state)>> /\\\n               <<PROMISE: lc.(Local.promises) = bot>> /\\\n               <<PMEM: forall loc view\n                              (PVIEW: persisted_event_view ex ob loc view),\n                        Memory.latest loc view (lc.(Local.vpc) loc).(View.ts) m.(Machine.mem)>>).\n  { i. rewrite TPOOL, FIND1 in FIND2. ss. }\n  assert (INVALID: forall tid\n                     (FIND1: IdMap.find tid p = None)\n                     (FIND2: IdMap.find tid m.(Machine.tpool) = None),\n             IdMap.find tid EX.(Valid.aeus) = None).\n  { i. generalize (EX.(Valid.AEUS) tid). rewrite FIND1. intro X. inv X. ss. }\n  assert (P: forall tid stmts\n               (FIND1: IdMap.find tid p = Some stmts),\n             IdMap.find tid p = Some stmts) by ss.\n\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 INVALID at 1.\n  setoid_rewrite IdMap.elements_spec in P at 1.\n  generalize (IdMap.elements_3w p). intro NODUP. revert NODUP.\n  revert IN OUT INVALID P. generalize (IdMap.elements p). intro ps.\n  revert m MEM0. induction ps; ss.\n  { i. esplits; eauto.\n    - econs. i. exploit OUT; eauto. i. des. eauto.\n    - econs. i. exploit OUT; eauto. i. des. splits; ss.\n      exploit H; eauto. intro X. inv X. inv STATE.\n      unfold State.is_terminal. congr.\n    - ii. destruct (IdMap.find id (Machine.tpool m)) as [[]|] eqn:T.\n      + exploit OUT; eauto. i. des. rewrite AEU. econs. ss.\n      + exploit INVALID; eauto. intro X. rewrite X. ss.\n    - ii. specialize (PMEM loc). inv PMEM.\n      + assert (ZERO: Memory.read loc 0 m.(Machine.mem) = Some (smem loc)).\n        { rewrite UNINIT. ss. }\n        econs; eauto.\n        intros tid [st0 lc0]. i. s. hexploit OUT; eauto. i. des.\n        eapply PMEM; eauto.\n      + exploit label_write_mem_of_ex; eauto. i. des.\n        rewrite <- MEM0 in *. econs; eauto.\n        intros tid [st0 lc0]. i. s.\n        hexploit OUT; eauto. i. des.\n        eapply PMEM; eauto.\n  }\n  i.\n\n  destruct a as [tid stmts].\n  exploit (IN tid); eauto.\n  { destruct (equiv_dec tid tid); [|congr]. ss. }\n  intro FIND.\n  cut (exists st2 lc2 aeu,\n          <<STEP: rtc (ExecUnit.state_step (A:=unit) tid)\n                      (ExecUnit.mk\n                         (State.init stmts)\n                         (Local.init_with_promises (Promises.promises_from_mem tid (Machine.mem m)))\n                         (Machine.mem m))\n                      (ExecUnit.mk st2 lc2 (Machine.mem m))>> /\\\n          <<TERMINAL: Valid.is_terminal EX -> State.is_terminal st2>> /\\\n          <<AEU: IdMap.find tid EX.(Valid.aeus) = Some aeu>> /\\\n          <<STATE: sim_state_weak st2 aeu.(AExecUnit.state)>> /\\\n          <<NOPROMISE: lc2.(Local.promises) = bot>> /\\\n          <<PMEM: forall loc view\n                         (PVIEW: persisted_event_view ex ob loc view),\n                  Memory.latest loc view (lc2.(Local.vpc) loc).(View.ts) m.(Machine.mem)>>).\n  { i. des. subst.\n    exploit Machine.rtc_eu_step_step; try exact STEP; eauto. i.\n    assert (NOTIN: SetoidList.findA (fun id' : IdMap.key => if equiv_dec tid id' then true else false) ps = None).\n    { inv NODUP. revert H1. clear. induction ps; ss.\n      destruct a. i. destruct (equiv_dec tid k); eauto.\n      inv e. contradict H1. left. ss.\n    }\n    exploit (IHps (Machine.mk\n                     (IdMap.add tid (st2, lc2) (Machine.tpool m))\n                     (Machine.mem m))); ss.\n    { i. rewrite IdMap.add_spec. condtac; ss.\n      - inversion e. subst. congr.\n      - apply IN. destruct (equiv_dec tid0 tid); ss.\n    }\n    { i. revert FIND2. rewrite IdMap.add_spec. condtac.\n      - i. inv FIND2. inversion e. subst. eauto.\n      - apply OUT. destruct (equiv_dec tid0 tid); ss.\n    }\n    { i. revert FIND2. rewrite IdMap.add_spec. condtac.\n      - i. inv FIND2.\n      - apply INVALID. destruct (equiv_dec tid0 tid); ss.\n    }\n    { i. generalize (P tid0 stmts0). destruct (equiv_dec tid0 tid); eauto.\n      inv e. congr.\n    }\n    { inv NODUP. ss. }\n    i. des. esplits; cycle 1; eauto. etrans; eauto.\n  }\n  generalize (P tid stmts). destruct (equiv_dec tid tid); [|congr].\n  intro FINDP. specialize (FINDP eq_refl).\n  rewrite MEM0 in *.\n  clear NODUP IN OUT INVALID P IHps MEM0 FIND ps e m.\n\n  (* Execute a thread `tid`. *)\n  generalize (EX.(Valid.AEUS) tid). rewrite FINDP.\n  intro X. inv X. des. rename b into aeu, H into AEU. clear FINDP.\n  exploit (@sim_eu_rtc_step p ex ob tid); eauto.\n  { instantiate (1 := ExecUnit.mk\n                        (State.init stmts)\n                        (Local.init_with_promises (Promises.promises_from_mem tid (mem_of_ex ex ob)))\n                        (mem_of_ex ex ob)).\n    econs; ss.\n    - econs; ss. econs. ii. rewrite ? IdMap.gempty. ss.\n    - econs; eauto; ss.\n      + right. splits; ss. ii. inv H. inv REL1. inv H. inv H1. ss. lia.\n      + econs; i.\n        { destruct view; ss. apply Promises.promises_from_mem_spec in H. des.\n          exploit in_mem_of_ex; swap 1 2; eauto.\n          { eapply Permutation_NoDup; [by symmetry; eauto|].\n            eapply Execution.eids_spec; eauto.\n          }\n          s. i. des. esplits; cycle 1; eauto. lia.\n        }\n        { des. inv WRITE. destruct l; ss. exploit label_write_mem_of_ex; eauto. i. des.\n          rewrite VIEW in VIEW0. inv VIEW0.\n          unfold Memory.get_msg in MSG. ss. apply Promises.promises_from_mem_spec. eauto.\n        }\n      + i. exists loc. splits; eauto. eapply Loc.cl_refl.\n  }\n  { clear. econs; ss.\n    - econs. i. unfold RMap.find, RMap.init.\n      rewrite IdMap.gempty. ss. apply bot_spec.\n    - econs; ss; i; try by apply bot_spec.\n      + econs; esplits; ss.\n      + destruct ts; ss.\n        rewrite Promises.promises_from_mem_spec in IN. des.\n        apply lt_le_S. rewrite <- List.nth_error_Some. ii. congr.\n      + destruct ts; ss.\n        unfold Memory.get_msg in MSG. ss. destruct msg. ss. subst.\n        apply Promises.promises_from_mem_lookup in MSG. auto.\n      + econs; try rewrite Loc.cl_refl; ss. i. apply bot_spec.\n  }\n  { apply AExecUnit.wf_init. }\n  i. des. destruct eu2 as [state2 local2 mem2]. inv SIM. ss. subst.\n  esplits; eauto.\n  - intro X. exploit X; eauto. i. inv STATE. congr.\n  - inv STATE. econs; ss.\n    inv RMAP. econs. ii. specialize (RMAP0 id). inv RMAP0; ss. econs.\n    inv REL1. econs. ss.\n  - apply Promises.ext. i. rewrite Promises.lookup_bot.\n    destruct (Promises.lookup i (Local.promises local2)) eqn:L; ss; cycle 1.\n    apply LOCAL.(PROMISES) in L. des.\n    exploit view_of_eid_inv; eauto. i. des. subst.\n    inv WRITE. unfold Execution.label in EID. ss.\n    rewrite EX.(Valid.LABELS), IdMap.map_spec, <- AEU in EID. ss.\n    apply List.nth_error_None in N. congr.\n  - i. generalize LOCAL.(VPC). intro SIM_VPC. specialize (SIM_VPC loc). inv SIM_VPC.\n    { rewrite VIEW. unfold bot. unfold Time.bot. ii. lia. }\n    unfold le in *. ii. exploit in_mem_of_ex; try exact MSG.\n    { generalize (Execution.eids_spec ex). i. des.\n      symmetry in PERM. eapply HahnList.Permutation_nodup; eauto.\n    }\n    i. des. destruct msg; ss. subst.\n\n    cut (exists feid fview beid,\n          <<FEID: Execution.label_is ex (fun l => Label.is_flushopting_cl loc l) feid>> /\\\n          <<FVIEW: view_of_eid ex ob feid = Some fview>> /\\\n          <<SIM2FL: v <= fview>> /\\\n          <<PO: Execution.po feid beid>> /\\\n          <<BARRIER: Execution.label_is ex (fun l => Label.is_barrier_c Barrier.is_dsb_full l) beid>>).\n    { i. des. obtac.\n      cut (Execution.fp ex feid (tid0, n)).\n      { i.\n        cut (fview < S ts).\n        { i. lia. }\n        eapply view_of_eid_ob_write; eauto with axm. right. ss.\n      }\n      destruct l0; ss. eqvtac.\n      exploit EX.(Valid.PF1); eauto with axm. i. des.\n      { right. simtac. }\n      cut (view_of_eid ex ob eid2 = Some view).\n      { i.\n        assert (Execution.co ex eid2 (tid0, n)).\n        { eapply view_of_eid_co; eauto with axm. }\n        left. econs; eauto.\n      }\n      assert (PERSISTED: Valid.persisted_event ex loc eid2).\n      { econs; eauto. obtac. econs. econs. simtac. }\n      inv PVIEW.\n      { exfalso. eapply NPER. eauto. }\n      obtac. exploit label_write_mem_of_ex_msg; try exact LABEL1; eauto. i. des.\n      destruct l0; ss. eqvtac. exploit EX.(Valid.CO1).\n      { esplits; [try exact EID2 | try exact EID3]; eauto. }\n      i. des.\n      - subst. ss.\n      - hexploit VPC0; eauto. intro Z. inv Z; ss.\n        exfalso. eapply EX.(Valid.EXTERNAL).\n        econs 2; econs; left; left; left; left; left; left; right; eauto.\n      - cut (fview < view).\n        { i. lia. }\n        eapply view_of_eid_ob_write; eauto with axm.\n        right. left. econs; eauto.\n    }\n\n    inv EID. inv REL1. obtac. inv H. obtac.\n    esplits; eauto.\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/equiv/AtoP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19867635477269666}}
{"text": "Require Import language.\nRequire Import msl.base.\nRequire Import msl.seplog.\nRequire Import msl.alg_seplog.\n\nLocal Open Scope logic.\n\nDefinition lift0 {B} (P: B) : env -> B := fun _ => P.\nDefinition lift1 {A1 B} (P: A1 -> B) (f1: env -> A1) : env -> B := fun rho => P (f1 rho).\nDefinition lift2 {A1 A2 B} (P: A1 -> A2 -> B) (f1: env -> A1) (f2: env -> A2):\n   env -> B := fun rho => P (f1 rho) (f2 rho).\n\nDefinition subst' {A} (x: var) (e: env -> adr) (P: env -> A) : env -> A := fun s => subst x (e s) P s.\n\nDefinition neq {A} (x y: A) := ~(x=y).\nDefinition local {A}{NA: NatDed A} (P: env -> Prop) : env -> A := fun s => prop (P s).\n\n\nModule Type SEMAX_LIFT.\n\n  Parameter mpred : Type.\n  Parameter Nm: NatDed mpred.  Existing Instance Nm.\n  Parameter Sm: SepLog mpred.  Existing Instance Sm.\n  Parameter Cm: ClassicalSep mpred.  Existing Instance Cm.\n  Parameter Im: Indir mpred.  Existing Instance Im.\n  Parameter Rm: RecIndir mpred.  Existing Instance Rm.\n  Parameter SIm: SepIndir mpred.  Existing Instance SIm.\n  Parameter SRm: SepRec mpred.  Existing Instance SRm.\n\n  Parameter mapsto: forall (v1 v2: adr), mpred.\n\n  Axiom mapsto_conflict:  forall a b c, mapsto a b  *  mapsto a c |-- FF.\n\n  Definition assert := env -> mpred.\n  Bind Scope logic with assert.\n\n  Definition funspec := (list var * assert)%type.\n  Definition funspecs := table adr funspec.\n\n  Definition call (P: list var * assert) (vl: list adr) : mpred :=\n     (!! (length vl = length (fst P)) && snd P (arguments (fst P) vl)).\n  Parameter cont: forall (nP: funspec)  (v: adr), mpred.\n\nDefinition funassert (G: funspecs) : mpred :=\n   (ALL  i:_, ALL P:_,  !! (table_get G i = Some P) --> cont P i)  &&\n   (ALL  i:_, ALL P:_,  cont P i --> !! exists P', table_get G i = Some P').\n\n\n  Axiom funassert_get:\n  forall G v nP,  funassert  G && cont nP v |--\n                      EX P':assert, (ALL vl:list adr, |> ! (call nP vl <=> call (fst nP,P') vl)) && !! (table_get G v = Some (fst nP,P')).\n\n  Parameter allocpool: forall (b: adr), mpred.\n  Axiom alloc: forall b, allocpool b = ((!! (b > 0) && mapsto b 0) * allocpool (S b)).\n\n  Parameter semax : varset -> funspecs -> assert -> control -> Prop.\n  Parameter semax_func: forall (G: funspecs) (p: program) (G': funspecs), Prop.\n\n  Axiom semax_func_nil: forall G, semax_func G nil nil.\n  Axiom semax_func_cons:\n   forall  fs id f vars P (G G': funspecs),\n      inlist id (map (@fst adr (list var * control)) fs) = false ->\n      list_nodups vars = true ->\n      length vars = length (fst P) ->\n(*      semax vars G (fun s => call P (map s vars)) f -> *)\n      semax vars G (lift1 (call P) (fun s => map s vars)) f ->\n      semax_func G fs G' ->\n      semax_func G ((id, (vars,f))::fs) ((id, P) :: G').\n\n  Definition program_proved (p: program) :=\n   exists G, semax_func G p G\n                            /\\ table_get G 0 = Some  (0::nil, lift1 allocpool (eval (Var 0))).\n\n  Axiom semax_sound:\n  forall p, program_proved p -> forall n, run p n <> None.\n\n  Axiom semax_go:  forall vars G (P: funspec) x ys,\n    typecheck vars (Go x ys) = true ->\n    semax vars G (lift1 (cont P) (eval x) && lift1 (call P) (eval_list ys)) (Go x ys) .\n\nAxiom semax_assign: forall x y c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c ->\n    semax vars G (|> subst' x (eval y) P) (Do x := y ; c).\n\nAxiom semax_if: forall x c1 c2 vars G (P: assert),\n    expcheck vars x = true ->\n    semax vars G (local (lift2 neq (eval x) (lift0 0)) && P) c1 ->\n    semax vars G (local (lift2 eq (eval x) (lift0 0)) && P) c2 ->\n    semax vars G P (If x Then c1 Else c2).\n\nAxiom semax_load:  forall x y z c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c ->\n    semax vars G ((lift2 mapsto (eval y) (lift0 z) * TT) && |> subst' x (lift0 z) P)\n               (Do x := Mem y ; c).\n\nAxiom semax_store: forall x y v c vars G (P: assert),\n    expcheck vars x = true ->\n    expcheck vars y = true ->\n    semax vars G (lift2 mapsto (eval x) (eval y) * P) c ->\n    semax vars G (lift2 mapsto (eval x) (lift0 v)  * P)  (Do Mem x  := y ; c).\n\nAxiom semax_pre:\n  forall P P' vars G c, (forall s, P s |-- P' s) -> semax vars G P' c -> semax vars G P c.\n\nAxiom semax_exp: forall A vars G (P: A -> assert) c,\n    typecheck vars c = true ->\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (EX v:A, (P v)) c.\n\nAxiom semax_exp': forall A (any: A) vars G (P: A -> assert) c,\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (EX v:A, (P v)) c.\n\nAxiom semax_prop:\n  forall (R: Prop) vars G P c,\n      typecheck vars c = true ->\n      (R -> semax vars G P c) ->\n      semax vars G (!!R && P) c.\n\nAxiom semax_G:\n   forall vars G P c, semax vars G (P && lift0 (funassert G)) c -> semax vars G P c.\n\nEnd SEMAX_LIFT.\n\nRequire Import seplogic.\nModule S2 (Module S2: SEMAX) : SEMAX_LIFT := S2.\n\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/examples/cont/lift_seplogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1986763547726966}}
{"text": "Require Import Events.\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import Values.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Axioms.\n\nRequire Import mem_lemmas. (*needed for definition of mem_forward etc*)\nRequire Import semantics.\nRequire Import semantics_lemmas.\nRequire Import effect_semantics.\nRequire Import structured_injections.\nRequire Import reach.\nRequire Import simulations.\n\n(** * Simulations Lemmas *)\n\n(** This file specializes [simulations] in a number of useful ways. *)\n\nSection Eff_INJ_SIMU_DIAGRAMS.\n  Context {F1 V1 C1 F2 V2 C2:Type}\n          {Sem1 : @EffectSem (Genv.t F1 V1) C1} \n          {Sem2 : @EffectSem (Genv.t F2 V2) C2}\n\n          {ge1: Genv.t F1 V1} \n          {ge2: Genv.t F2 V2}.\n\n  Let core_data := C1.\n\n  Variable match_states: core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop.\n   \n   Hypothesis genvs_dom_eq: genvs_domain_eq ge1 ge2.\n\n   Hypothesis match_sm_wd: forall d mu c1 m1 c2 m2, \n          match_states d mu c1 m1 c2 m2 ->\n          SM_wd mu.\n\n    Hypothesis match_visible: forall d mu c1 m1 c2 m2, \n          match_states d mu c1 m1 c2 m2 -> \n          REACH_closed m1 (vis mu).\n\n    Hypothesis match_restrict: forall d mu c1 m1 c2 m2 X, \n          match_states d mu c1 m1 c2 m2 -> \n          (forall b, vis mu b = true -> X b = true) ->\n          REACH_closed m1 X ->\n          match_states d (restrict_sm mu X) c1 m1 c2 m2.\n\n   Hypothesis match_validblocks: forall d mu c1 m1 c2 m2, \n          match_states d mu c1 m1 c2 m2 ->\n          sm_valid mu m1 m2.\n\n    Hypothesis match_genv: forall d mu c1 m1 c2 m2 (MC:match_states d mu c1 m1 c2 m2),\n          meminj_preserves_globals ge1 (extern_of mu) /\\\n          (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true).\n\n   Hypothesis inj_initial_cores: forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n          initial_core Sem1 ge1 v vals1 = Some c1 ->\n          Mem.inject j m1 m2 -> \n          Forall2 (val_inject j) vals1 vals2 ->\n          meminj_preserves_globals ge1 j ->\n          globalfunction_ptr_inject ge1 j -> \n\n        (*the next two conditions are required to guarantee intialSM_wd*)\n         (forall b1 b2 d, j b1 = Some (b2, d) -> \n                          DomS b1 = true /\\ DomT b2 = true) ->\n         (forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true -> DomT b = true) ->\n\n        (*the next two conditions ensure the initialSM satisfies sm_valid*)\n         (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n         (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n       exists c2, \n            initial_core Sem2 ge2 v vals2 = Some c2 /\\\n            match_states c1 (initial_SM DomS\n                                       DomT \n                                       (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b)) \n                                       (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n                           c1 m1 c2 m2.\n\n  Hypothesis inj_halted : forall cd mu c1 m1 c2 m2 v1,\n      match_states cd mu c1 m1 c2 m2 ->\n      halted Sem1 c1 = Some v1 ->\n\n      exists v2, \n             Mem.inject (as_inj mu) m1 m2 /\\\n             val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n             halted Sem2 c2 = Some v2.\n\n  Hypothesis inj_at_external : \n      forall mu c1 m1 c2 m2 e vals1 ef_sig,\n        match_states c1 mu c1 m1 c2 m2 ->\n        at_external Sem1 c1 = Some (e,ef_sig,vals1) ->\n        Mem.inject (as_inj mu) m1 m2 /\\ \n          exists vals2, \n            Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\ \n            at_external Sem2 c2 = Some (e,ef_sig,vals2)\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_states c1 nu c1 m1 c2 m2 \n       /\\ Mem.inject (shared_of nu) m1 m2.\n\nSection EFF_INJ_SIMULATION_STAR_WF.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu') \n        (GSep: globals_separate ge2 nu nu')\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n             forall \n               (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n               b ofs (Ub: U2 b ofs = true), \n             visTgt mu b = true /\\ \n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\n(* RESTRIC : clear - match_restrict. intros. destruct H; subst. eauto.*)\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores . intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H\n         H0 H1 H2 H3 H4 H5 H6 H7)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition. \nclear - inj_effcore_diagram genvs_dom_eq. \n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as \n\n    [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]]. \n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split. eapply gsep_domain_eq; eassumption.\n  split; try assumption. \n  split. split; trivial. \n  exists U2. split; assumption. \nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial. \n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros. \n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ INC GSep\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt \n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp \n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF.\n\nSection EFF_INJ_SIMULATION_STAR_WF_TYPED.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')  \n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n           forall\n             (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n             b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                U1 b1 (ofs-delta1) = true /\\\n                Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf_typed: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\n(* RESTRICT: clear - match_restrict. intros. destruct H; subst. eauto.*)\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5 H6 H7)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition. \nclear - inj_effcore_diagram genvs_dom_eq. \n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as \n    [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]]. \n  exists c2'. exists m2'. exists st1'. exists mu'. \n  split; try assumption.\n  split. eapply gsep_domain_eq; eassumption.\n  split; try assumption.\n  split. split; trivial. \n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial. \n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros. \n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ HasTy1 HasTy2 INC GSep\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt \n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp \n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF_TYPED.\n\nSection EFF_INJ_SIMULATION_STAR.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')  \n        (GSep: globals_separate ge2 nu nu')\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n  \n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall \n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true), \n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf.\n  apply  (well_founded_ltof _ measure).\n  apply inj_after_external.\n  clear - inj_effcore_diagram genvs_dom_eq.  intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0) \n    as [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'. \n  split; try assumption.\n  split; try assumption.\n  (*split. eapply globalsep_domain_eq. eassumption.*)\n  split; try assumption. \n  split; try assumption.  \n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR.\n\nSection EFF_INJ_SIMULATION_STAR_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')  \n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n  \n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall \n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n              visTgt mu b = true /\\ \n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star_typed: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf_typed.\n  apply  (well_founded_ltof _ measure).\n  intros. eapply inj_after_external with (mu := mu); eauto.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0) \n    as [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'. \n  split; try assumption. \n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_TYPED.\n\nSection EFF_INJ_SIMULATION_PLUS.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')  \n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n \n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall \n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                 b ofs (Ub: U2 b ofs = true),\n                 visTgt mu b = true /\\ \n                 (locBlocksTgt mu b = false ->\n                     exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n  \nLemma inj_simulation_plus: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS.\n\nSection EFF_INJ_SIMULATION_PLUS_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,ef_sig,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',ef_sig',vals2)) \n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)  \n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')  \n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b)) \n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n \n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\ \n                                                      pubBlocksSrc nu b = false) m1 m1') \n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram : \n      forall st1 m1 st1' m1' U1, \n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\ \n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,              \n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall \n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                  b ofs (Ub: U2 b ofs = true),\n                visTgt mu b = true /\\ \n                (locBlocksTgt mu b = false ->\n                    exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                    U1 b1 (ofs-delta1) = true /\\\n                    Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n  \nLemma inj_simulation_plus_typed: \n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star_typed with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS_TYPED.\n\nEnd Eff_INJ_SIMU_DIAGRAMS.\n\nDefinition compose_sm (mu1 mu2 : SM_Injection) : SM_Injection :=\n Build_SM_Injection \n   (locBlocksSrc mu1) (locBlocksTgt mu2)\n   (pubBlocksSrc mu1) (pubBlocksTgt mu2)\n   (compose_meminj (local_of mu1) (local_of mu2))\n   (extBlocksSrc mu1) (extBlocksTgt mu2)\n   (frgnBlocksSrc mu1) (frgnBlocksTgt mu2) \n   (compose_meminj (extern_of mu1) (extern_of mu2)).\n\nLemma compose_sm_valid: forall mu1 mu2 m1 m2 m2' m3\n          (SMV1: sm_valid mu1 m1 m2) (SMV2: sm_valid mu2 m2' m3),\n       sm_valid (compose_sm mu1 mu2) m1 m3.\nProof.  split. apply SMV1. apply SMV2. Qed.\n\nLemma compose_sm_pub: forall mu12 mu23 \n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      pub_of (compose_sm mu12 mu23) =\n      compose_meminj (pub_of mu12) (pub_of mu23).\nProof. intros. unfold compose_sm, pub_of. \n  extensionality b. \n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (pubSrc _ WD1 _ Heqd) as [b2 [d1 [LOC1 Tgt1]]]; simpl in *.\n    rewrite Heqd in LOC1. apply HypPub in Tgt1. \n    unfold compose_meminj. rewrite Heqd. rewrite LOC1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_DomSrc: forall mu12 mu23,\n  DomSrc (compose_sm mu12 mu23) = DomSrc mu12.\nProof. intros. unfold compose_sm, DomSrc; simpl. trivial. Qed. \n\nLemma compose_sm_DomTgt: forall mu12 mu23,\n  DomTgt (compose_sm mu12 mu23) = DomTgt mu23.\nProof. intros. unfold compose_sm, DomTgt; simpl. trivial. Qed. \n\nLemma compose_sm_foreign: forall mu12 mu23\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      foreign_of (compose_sm mu12 mu23) = \n      compose_meminj (foreign_of mu12) (foreign_of mu23).\nProof. intros. unfold compose_sm, foreign_of. \n  extensionality b. \n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (fSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (frgnSrc _ WD1 _ Heqd) as [b2 [d1 [EXT1 Tgt1]]]; simpl in *.\n    rewrite Heqd in EXT1. apply HypFrg in Tgt1. \n    unfold compose_meminj. rewrite Heqd. rewrite EXT1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_priv: forall mu12 mu23,\n   priv_of (compose_sm mu12 mu23) =\n   compose_meminj (priv_of mu12) (local_of mu23).\nProof. intros. unfold priv_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_unknown: forall mu12 mu23,\n   unknown_of (compose_sm mu12 mu23) = \n   compose_meminj (unknown_of mu12) (extern_of mu23).\nProof. intros. unfold unknown_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (locBSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  remember (fSrc1 b) as q; destruct q; apply eq_sym in Heqq.\n    unfold compose_meminj. rewrite Heqd. rewrite Heqq. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. rewrite Heqq. trivial.\nQed.\n\nLemma compose_sm_local: forall mu12 mu23,\n   local_of (compose_sm mu12 mu23) =\n   compose_meminj (local_of mu12) (local_of mu23).\nProof. intros. reflexivity. Qed. \n\nLemma compose_sm_extern: forall mu12 mu23,\n   extern_of (compose_sm mu12 mu23) =\n   compose_meminj (extern_of mu12) (extern_of mu23).\nProof. intros. reflexivity. Qed. \n\nLemma compose_sm_shared: forall mu12 mu23 \n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12) (WD2:SM_wd mu23),\n      shared_of (compose_sm mu12 mu23) =\n      compose_meminj (shared_of mu12) (shared_of mu23).\nProof. intros. unfold shared_of. \n  rewrite compose_sm_pub; trivial.\n  rewrite compose_sm_foreign; trivial.\n  unfold join, compose_meminj. extensionality b.\n  remember (foreign_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    destruct (foreign_DomRng _ WD1 _ _ _ Heqf) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypFrg in F.\n    destruct (frgnSrc _ WD2 _ F) as [b3 [d2 [FRG2 TGT2]]].\n    rewrite FRG2. trivial.\n  remember (pub_of mu12 b) as d; destruct d; apply eq_sym in Heqd; trivial.\n    destruct p as [b2 d1].\n    destruct (pub_locBlocks _ WD1 _ _ _ Heqd) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypPub in B.\n    destruct (pubSrc _ WD2 _ B) as [b3 [d2 [PUB2 TGT2]]].\n    rewrite PUB2.\n    apply (pubBlocksLocalSrc _ WD2) in B.\n    apply (locBlocksSrc_frgnBlocksSrc _ WD2) in B.\n    unfold foreign_of. destruct mu23. simpl in *. rewrite B. trivial.\nQed.\n\nLemma compose_sm_wd: forall mu1 mu2 (WD1: SM_wd mu1) (WD2:SM_wd mu2)\n         (HypPub: forall b, pubBlocksTgt mu1 b = true ->\n                            pubBlocksSrc mu2 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu1 b = true ->\n                            frgnBlocksSrc mu2 b = true),\n      SM_wd (compose_sm mu1 mu2).\nProof. intros.\n  destruct mu1 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu2 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\nsplit; simpl in *.\napply WD1.\napply WD2.\n(*local_DomRng*)\n  intros b1 b3 d H. \n  destruct (compose_meminjD_Some _ _ _ _ _ H) \n    as [b2 [d1 [d2 [PUB1 [PUB2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply PUB1. \n         eapply WD2. apply PUB2. \n(*extern_DomRng*)\n  intros b1 b3 d H. \n  destruct (compose_meminjD_Some _ _ _ _ _ H) \n    as [b2 [d1 [d2 [EXT1 [EXT2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply EXT1. \n         eapply WD2. apply EXT2. \n(*pubSrc*)\n  intros. \n  destruct (pubSrc _ WD1 _ H) as [b2 [d1 [Loc1 Tgt1]]]. simpl in *.\n  apply HypPub in Tgt1. \n  destruct (pubSrc _ WD2 _ Tgt1) as [b3 [d2 [Loc2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Loc1. rewrite Loc2. auto.\n(*frgnSrc*)\n  intros.\n  destruct (frgnSrc _ WD1 _ H) as [b2 [d1 [Ext1 Tgt1]]]. simpl in *.\n  apply HypFrg in Tgt1. \n  destruct (frgnSrc _ WD2 _ Tgt1) as [b3 [d2 [Ext2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Ext1. rewrite Ext2. auto.\n(*locBlocksDomTgt*)\n  apply WD2.\n(*frgnBlocksDomTgt*)\n  apply WD2.\nQed.\n\nLemma compose_sm_as_inj: forall mu12 mu23 (WD1: SM_wd mu12) (WD2: SM_wd mu23)\n   (SrcTgtLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n   (SrcTgtExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n   as_inj (compose_sm mu12 mu23) = \n   compose_meminj (as_inj mu12) (as_inj mu23).\nProof. intros.\n  unfold as_inj.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_local.\n  unfold join, compose_meminj. extensionality b.\n  remember (extern_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    remember (extern_of mu23 b2) as d; destruct d; apply eq_sym in Heqd.\n      destruct p as [b3 d2]. trivial.\n    destruct (disjoint_extern_local _ WD1 b).\n       rewrite H in Heqf. discriminate.\n    rewrite H. \n    destruct (extern_DomRng _ WD1 _ _ _ Heqf) as [A B]. \n    rewrite SrcTgtExt in B.\n    remember (local_of mu23 b2) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b3 d2].\n    destruct (local_DomRng _ WD2 _ _ _ Heqq) as [AA BB].\n    destruct (disjoint_extern_local_Src _ WD2 b2); congruence. \n  remember (local_of mu12 b) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b2 d1].\n    destruct (local_DomRng _ WD1 _ _ _ Heqq) as [AA BB].\n    remember (extern_of mu23 b2) as d; destruct d; trivial; apply eq_sym in Heqd.\n      destruct p as [b3 d2].\n      destruct (extern_DomRng _ WD2 _ _ _ Heqd) as [A B]. \n      rewrite SrcTgtLoc in BB.\n      destruct (disjoint_extern_local_Src _ WD2 b2); congruence.  \nQed.\n\nLemma compose_sm_intern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: intern_incr mu12 mu12') \n            (inc23: intern_incr mu23 mu23'),\n      intern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; simpl in *.\n    eapply compose_meminj_inject_incr.\n        apply inc12.\n        apply intern_incr_local; eassumption.\nsplit. rewrite (intern_incr_extern _ _ inc12).\n       rewrite (intern_incr_extern _ _ inc23).\n       trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma compose_sm_extern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: extern_incr mu12 mu12') \n            (inc23: extern_incr mu23 mu23')\n  (FRG': forall b1 b2 d1, foreign_of mu12' b1 = Some(b2,d1) ->\n         exists b3 d2, foreign_of mu23' b2 = Some(b3,d2))\n  (WD12': SM_wd mu12') (WD23': SM_wd mu23'),\n  extern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; intros.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_extern.\n  eapply compose_meminj_inject_incr.\n    apply inc12.\n    apply extern_incr_extern; eassumption.\nsplit; simpl.\n  rewrite (extern_incr_local _ _ inc12). \n  rewrite (extern_incr_local _ _ inc23).\n  trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma extern_incr_inject_incr: \n      forall nu12 nu23 nu' (WDnu' : SM_wd nu')\n          (EXT: extern_incr (compose_sm nu12 nu23) nu')\n          (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                      locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                      extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                      (forall b, pubBlocksTgt nu12 b = true -> \n                                 pubBlocksSrc nu23 b = true) /\\\n                      (forall b, frgnBlocksTgt nu12 b = true -> \n                                 frgnBlocksSrc nu23 b = true)),\n      inject_incr (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu').\nProof. intros.\n  intros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [Nu12 [Nu23 D]]]]]; subst; clear H.\n  unfold extern_incr in EXT. simpl in EXT.\n  destruct EXT as [EXT [LOC [extBSrc12 [extBTgt23 [locBSrc12 [locBTgt23 [pubBSrc12 [pubBTgt23 [frgnBSrc12 frgnBTgt23]]]]]]]]].\n  destruct (joinD_Some _ _ _ _ _ Nu12); clear Nu12.\n  (*extern12*)\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        apply join_incr_left. apply EXT.\n        unfold compose_meminj. rewrite H. rewrite H0. trivial.\n     (*local*)\n        destruct H0.\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLa _ _ _ H) as [? [? [? [? [? [? [? ?]]]]]]].\n        destruct (local_locBlocks _ GLb _ _ _ H1) as [? [? [? [? [? [? [? ?]]]]]]].\n        rewrite GLd in *. congruence.  \n  (*local*) \n     destruct H.\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLb _ _ _ H1) as [? [? [? [? [? ?]]]]].\n        destruct (local_locBlocks _ GLa _ _ _ H0) as [? [? [? [? [? ?]]]]].\n        rewrite GLd in *. congruence. \n     (*local*)\n        destruct H1. \n        apply join_incr_right. eapply disjoint_extern_local. apply WDnu'.\n        rewrite <- LOC. unfold compose_meminj.\n        rewrite H0, H2. trivial.\nQed.\n\nLemma compose_sm_as_injD: forall mu1 mu2 b1 b3 d\n      (I: as_inj (compose_sm mu1 mu2) b1 = Some (b3, d))\n      (WD1: SM_wd mu1) (WD2: SM_wd mu2),\n      exists b2 d1 d2, as_inj mu1 b1 = Some(b2,d1) /\\\n                       as_inj mu2 b2 = Some(b3,d2) /\\\n                       d=d1+d2.\nProof. intros.\ndestruct (joinD_Some _ _ _ _ _ I); clear I.\n(*extern*)\n  rewrite compose_sm_extern in H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n      as [b2 [d1 [d2 [EXT1 [EXT2 D]]]]]; clear H.\n  exists b2, d1, d2.\n  split. apply join_incr_left. assumption.\n  split. apply join_incr_left. assumption.\n         assumption. \n(*local*)\n  destruct H. \n  rewrite compose_sm_extern in H.\n  rewrite compose_sm_local in H0.\n  destruct (compose_meminjD_Some _ _ _ _ _ H0)\n      as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; clear H0.\n  exists b2, d1, d2.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption. \n           assumption.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption. \n           assumption.\n         assumption.\nQed.\n\nLemma compose_sm_as_injD_None:\n  forall (mu1 mu2 : SM_Injection) b1,\n       SM_wd mu1 ->\n       SM_wd mu2 ->\n    (locBlocksTgt mu1 = locBlocksSrc mu2 /\\\n         extBlocksTgt mu1 = extBlocksSrc mu2) ->\n       as_inj (compose_sm mu1 mu2) b1 = None ->\n         as_inj mu1 b1 = None  \\/\n         exists b2 d, (as_inj mu1 b1 = Some (b2, d) /\\ as_inj mu2 b2 = None).\nProof.\nintros mu1 mu2 b1 SMWD1 SMWD2 [GLUEloc GLUEext].\nunfold as_inj, join, compose_sm; simpl.\ndestruct (Values.compose_meminj (extern_of mu1) (extern_of mu2) b1) as [[b2 delta]| ] eqn:extmap.\ndiscriminate.\ndestruct (Values.compose_meminj (local_of mu1) (local_of mu2) b1) as [[b2 delta]| ] eqn:locmap.\ndiscriminate.\nintros tautology.\ndestruct (compose_meminjD_None _ _ _ extmap) as [extmap' | [b' [ofs' [extmap1 extmap2]]]];\ndestruct (compose_meminjD_None _ _ _ locmap) as [locmap' | [b'' [ofs'' [locmap1 locmap2]]]].\n- rewrite extmap'; simpl.  rewrite locmap'; auto.\n- rewrite extmap'; simpl. right.\n  exists b'', ofs''. split.  \n  + auto.\n  + destruct (extern_of mu2 b'') as [[b0 d]| ] eqn:extmap0.\n    * apply SMWD2 in extmap0. apply SMWD1 in locmap1.\n      destruct locmap1; destruct extmap0.\n      rewrite GLUEloc in *.\n      destruct SMWD2 as [disj_src _].\n      destruct (disj_src b'') as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\n    * assumption.\n- rewrite extmap1; simpl. right.\n  exists b', ofs'. split.\n  + reflexivity.\n  + rewrite extmap2; simpl.\n    destruct (local_of mu2 b') as [[b0 d]| ] eqn:locmap0.\n    * apply SMWD2 in locmap0. apply SMWD1 in extmap1.\n      destruct extmap1; destruct locmap0.\n      rewrite GLUEext in *.\n      destruct SMWD2 as [disj_src _].\n      destruct (disj_src b') as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\n    * assumption.\n- apply SMWD1 in extmap1; apply SMWD1 in locmap1.\n  destruct locmap1; destruct extmap1.\n  destruct SMWD1 as [disj_src _].\n  destruct (disj_src b1) as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\nQed.  \n\n\n\n(*\nLemma compose_sm_intern_separated:\n      forall mu12 mu12' mu23 mu23' m1 m2 m3 \n        (inc12: intern_incr mu12 mu12') \n        (inc23: intern_incr mu23 mu23')\n        (InjSep12 : sm_inject_separated mu12 mu12' m1 m2)\n        (InjSep23 : sm_inject_separated mu23 mu23' m2 m3)\n        (WD12: SM_wd mu12) (WD12': SM_wd mu12') (WD23: SM_wd mu23) (WD23': SM_wd mu23')\n        (BlocksLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n        (BlocksExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n      sm_inject_separated (compose_sm mu12 mu23)\n                          (compose_sm mu12' mu23') m1 m3.\nProof. intros.\ndestruct InjSep12 as [AsInj12 [DomTgt12 Sep12]].\ndestruct InjSep23 as [AsInj23 [DomTgt23 Sep23]].\nsplit.\n  intros b1 b3 d; intros.\n  simpl.\n  destruct (compose_sm_as_injD _ _ _ _ _ H0)\n     as [b2 [d1 [d2 [AI12' [AI23' X]]]]]; subst; trivial; clear H0.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n  assert (DomSrc (compose_sm mu12' mu23') b1 = true /\\\n          DomTgt (compose_sm mu12' mu23') b3 = true).\n    rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n    split. eapply as_inj_DomRng; eassumption.\n           eapply as_inj_DomRng; eassumption. \n  destruct H0 as [DOM1 TGT3]; simpl in *.\n  assert (TGT2: DomTgt mu12' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD12'.\n  assert (DOMB2: DomSrc mu23' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD23'.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt in *.\n  remember (as_inj mu12 b1) as q.\n  destruct q; apply eq_sym in Heqq.\n    destruct p.\n    specialize (intern_incr_as_inj _ _ inc12 WD12' _ _ _ Heqq); intros.\n    rewrite AI12' in H0. apply eq_sym in H0. inv H0.\n    destruct (joinD_Some _ _ _ _ _ Heqq); clear Heqq.\n    (*extern12Some*)\n       assert (extern_of mu12' b1 = Some (b2, d1)).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         assert (extern_of mu23 b2 = Some (b3, d2)).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_extern in H2.\n         unfold compose_meminj in H2. \n         rewrite H0 in H2. rewrite H4 in H2. inv H2.\n       (*extern23'None*)\n         destruct H.\n         rewrite compose_sm_extern in H2.\n         destruct (compose_meminjD_None _ _ _ H2); clear H2.\n            rewrite H5 in H0. discriminate.\n         destruct H5 as [bb2 [dd1 [EXT12 EXT23]]].\n         rewrite EXT12 in H0. inv H0.\n         rewrite compose_sm_local in H3.\n         remember (local_of mu23 b2) as qq.\n         destruct qq; apply eq_sym in Heqqq.\n            destruct p.\n            specialize (intern_incr_local _ _ inc23); intros.\n            specialize (H0 _ _ _ Heqqq). rewrite H0 in H4. inv H4.\n            destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [A B].\n            destruct (local_DomRng _ WD23 _ _ _ Heqqq) as [AA BB].\n            rewrite BlocksExt in B. \n            destruct (disjoint_extern_local_Src _ WD23 b2); congruence.\n         destruct (AsInj23 b2 b3 d2).\n            apply joinI_None. assumption. assumption.\n            apply join_incr_right.\n              apply disjoint_extern_local. assumption.\n              assumption.\n         destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [XX YY].\n           rewrite BlocksExt in YY. unfold DomSrc in H0.\n           rewrite YY in H0. rewrite orb_comm in H0. discriminate.\n    (*extern12None*)\n       destruct H0.\n       assert (extern_of mu12' b1 = None).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       assert (local_of mu12' b1 = Some (b2, d1)).\n          eapply (intern_incr_local _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         destruct (local_DomRng _ WD12' _ _ _ H3) as [AA BB].\n         destruct (extern_DomRng _ WD23' _ _ _ H) as [A B].\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AAA BBB].\n         rewrite BlocksLoc in BBB. \n         assert (locBlocksSrc mu23' b2 = true). apply inc23. assumption.\n         destruct (disjoint_extern_local_Src _ WD23' b2); congruence.\n       (*extern23'None*)\n         destruct H.\n         assert (extern_of mu23 b2 = None).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_local in H5.\n         unfold compose_meminj in H5. rewrite H1 in H5.\n         remember (local_of mu23 b2).\n         destruct o. destruct p. inv H5. clear H5. apply eq_sym in Heqo.\n         clear H4.\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AA BB].\n         assert (DomSrc mu23 b2 = false /\\ DomTgt mu23 b3 = false).\n            eapply AsInj23.\n              apply joinI_None; assumption.\n              apply join_incr_right; try eassumption.\n                apply disjoint_extern_local; eassumption.\n         destruct H4.  \n         destruct (local_locBlocks _ WD12 _ _ _ H1) \n           as [AAA [BBB [CCC [DDD [EEE FFF]]]]].\n         rewrite BlocksLoc in BBB. unfold DomSrc in H4.\n             rewrite BBB in H4. discriminate.\n   (*as_inj mu12 b1 = None*)\n     destruct (AsInj12 _ _ _ Heqq AI12'). split; trivial. clear H.\n     remember (as_inj mu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n       destruct p.\n       specialize (intern_incr_as_inj _ _ inc23 WD23' _ _ _ Heqd).\n       intros ZZ; rewrite AI23' in ZZ. apply eq_sym in ZZ; inv ZZ.\n       destruct (as_inj_DomRng _ _ _ _ Heqd WD23).\n       unfold DomSrc in H. unfold DomTgt in H1.\n       rewrite BlocksLoc, BlocksExt in H1. rewrite H1 in H; discriminate.\n     eapply AsInj23. eassumption. eassumption.\nsimpl.\n  split. apply DomTgt12. apply Sep23.\nQed.*)\n\n\nLemma vis_compose_sm: forall mu nu, vis (compose_sm mu nu) = vis mu.\nProof. intros. unfold vis. destruct mu; simpl. reflexivity. Qed.\n\nLemma restrict_compose: forall j k X, \n  restrict (compose_meminj j k) X = compose_meminj (restrict j X) k.\nProof. intros.\n  extensionality b.\n  unfold compose_meminj, restrict.\n  remember (X b) as d.\n  destruct d; trivial.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/core/simulations_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.19867635353556026}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\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 Syntax.\nRequire Import Semantics.\n\nRequire Import PromiseConsistent.\nRequire Import SimpleSimulation.\n\nRequire Import AMemory.\nRequire Import ALocal.\nRequire Import ATView.\nRequire Import AThread.\n\nRequire Import PFCommon.\nRequire Import PFStep.\nRequire Import PFCertify.\nRequire Import Invariant.\n\nSet Implicit Arguments.\n\n\nSection AssertInsertion.\n  Variable\n    (S:ThreadsProp)\n    (J:MemoryProp)\n    (program: Threads.syntax).\n\n  Context `{LOGIC: Logic.t S J program}.\n\n\n  (* simulation relations on threads *)\n\n  Inductive insert_assertion (tid: Ident.t): forall (stmts_src stmts_tgt: list Stmt.t), Prop :=\n  | insert_assertion_nil:\n      insert_assertion tid [] []\n  | insert_assertion_instr\n      (i: Instr.t) stmts_src stmts_tgt\n      (SIM: insert_assertion tid stmts_src stmts_tgt):\n      insert_assertion tid ((Stmt.instr i)::stmts_src) ((Stmt.instr i)::stmts_tgt)\n  | insert_assertion_ite\n      cond\n      stmts1_src stmts2_src stmts_src\n      stmts1_tgt stmts2_tgt stmts_tgt\n      (SIM1: insert_assertion tid (stmts1_src ++ stmts_src) (stmts1_tgt ++ stmts_tgt))\n      (SIM2: insert_assertion tid (stmts2_src ++ stmts_src) (stmts2_tgt ++ stmts_tgt)):\n      insert_assertion tid\n                       ((Stmt.ite cond stmts1_src stmts2_src)::stmts_src)\n                       ((Stmt.ite cond stmts1_tgt stmts2_tgt)::stmts_tgt)\n  | insert_assertion_dowhile\n      cond\n      stmts1_src stmts_src\n      stmts1_tgt stmts_tgt\n      (SIM: insert_assertion tid\n                             (stmts1_src ++ (Stmt.ite cond ((Stmt.dowhile stmts1_src cond)::nil) nil) :: stmts_src)\n                             (stmts1_tgt ++ (Stmt.ite cond ((Stmt.dowhile stmts1_tgt cond)::nil) nil) :: stmts_tgt)):\n      insert_assertion tid\n                       ((Stmt.dowhile stmts1_src cond)::stmts_src)\n                       ((Stmt.dowhile stmts1_tgt cond)::stmts_tgt)\n  | insert_assertion_assert\n      c stmts_src stmts_tgt\n      (SIM: insert_assertion tid stmts_src stmts_tgt)\n      (SUCCESS: forall rs (TH: S tid lang (State.mk rs stmts_src)),\n          RegFile.eval_expr rs c <> 0):\n      insert_assertion tid stmts_src ((Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts_tgt)\n  .\n  #[local]\n  Hint Constructors insert_assertion: core.\n\n  Inductive sim_state (tid: Ident.t) (st_src st_tgt: State.t): Prop :=\n  | sim_state_intro\n      (STMTS: insert_assertion tid (State.stmts st_src) (State.stmts st_tgt))\n      (REGS: (State.regs st_src) = (State.regs st_tgt))\n  .\n  #[local]\n  Hint Constructors sim_state: core.\n\n  Inductive sim_thread (tid: Ident.t) (e_src e_tgt: Thread.t lang): Prop :=\n  | sim_thread_intro\n      (STATE: sim_state tid (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: (Thread.memory e_src) = (Thread.memory e_tgt))\n  .\n  #[local]\n  Hint Constructors sim_thread: core.\n\n\n  Lemma sim_state_step\n        tid st1_src\n        e st1_tgt st2_tgt\n        (SIM1: sim_state tid st1_src st1_tgt)\n        (STEP: (Language.step lang) e st1_tgt st2_tgt):\n    (exists st2_src,\n        <<STEP_SRC: State.opt_step e st1_src st2_src>> /\\\n        <<SIM2: sim_state tid st2_src st2_tgt>>) \\/\n    (exists c stmts,\n        <<STMTS: (State.stmts st1_tgt) =\n                 (Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts>> /\\\n        <<SUCCESS: forall (SOUND: S tid lang st1_src),\n            RegFile.eval_expr (State.regs st1_src) c <> 0>> /\\\n        <<FAIL: RegFile.eval_expr (State.regs st1_src) c = 0>>).\n  Proof.\n    destruct st1_src, st1_tgt, st2_tgt.\n    inv SIM1. ss. subst.\n    inv STMTS.\n    - inv STEP.\n    - left.\n      exists (State.mk regs1 stmts_src).\n      inv STEP. split; eauto.\n      econs 2. econs; eauto.\n    - left.\n      inv STEP. esplits.\n      + econs 2. econs; eauto.\n      + condtac; eauto.\n    - left.\n      inv STEP. esplits.\n      + econs 2. econs; eauto.\n      + ss.\n    - inv STEP. condtac; ss.\n      + right. esplits; eauto.\n      + left. esplits; [econs 1|]. ss.\n  Qed.\n\n  Lemma sim_thread_promise_step\n        tid e1_src\n        pf e e1_tgt e2_tgt\n        (SIM1: sim_thread tid e1_src e1_tgt)\n        (STEP_TGT: Thread.promise_step pf e e1_tgt e2_tgt):\n    exists e2_src,\n      <<STEP_SRC: Thread.promise_step pf e e1_src e2_src>> /\\\n      <<SIM2: sim_thread tid e2_src e2_tgt>>.\n  Proof.\n    destruct e1_src, e1_tgt, e2_tgt. ss.\n    inv SIM1. ss. subst.\n    inv STEP_TGT; ss.\n    esplits.\n    - econs; eauto.\n    - eauto.\n  Qed.\n\n  Lemma sim_thread_program_step\n        tid e1_src\n        e e1_tgt e2_tgt\n        (SIM1: sim_thread tid e1_src e1_tgt)\n        (STEP_TGT: Thread.program_step e e1_tgt e2_tgt):\n    (exists e2_src,\n        <<STEP_SRC: Thread.opt_program_step e e1_src e2_src>> /\\\n        <<SIM2: sim_thread tid e2_src e2_tgt>>) \\/\n    (exists c stmts,\n        <<STMTS: (State.stmts (Thread.state e1_tgt)) =\n                 (Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts>> /\\\n        <<SUCCESS: forall (SOUND: S tid lang (Thread.state e1_src)),\n            RegFile.eval_expr (State.regs (Thread.state e1_src)) c <> 0>> /\\\n        <<FAIL: RegFile.eval_expr (State.regs (Thread.state e1_src)) c = 0>>).\n  Proof.\n    destruct e1_src, e1_tgt, e2_tgt. ss.\n    inv SIM1. ss. subst.\n    inv STEP_TGT; ss.\n    exploit sim_state_step; eauto. i. des; cycle 1.\n    { right. esplits; eauto. }\n    left. inv LOCAL; inv STEP_SRC; ss.\n    - esplits.\n      + econs 1.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n    - esplits.\n      + econs 2. econs; eauto.\n      + econs; eauto.\n  Qed.\n\n  Lemma sim_thread_step\n        tid e1_src\n        pf e e1_tgt e2_tgt\n        (SIM1: sim_thread tid e1_src e1_tgt)\n        (STEP_TGT: Thread.step pf e e1_tgt e2_tgt):\n    (exists e2_src,\n        <<STEP_SRC: Thread.opt_step e e1_src e2_src>> /\\\n        <<SIM2: sim_thread tid e2_src e2_tgt>>) \\/\n    (exists c stmts,\n        <<STMTS: (State.stmts (Thread.state e1_tgt)) =\n                 (Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts>> /\\\n        <<ASSERT: forall (SOUND: S tid lang (Thread.state e1_src)),\n            RegFile.eval_expr (State.regs (Thread.state e1_src)) c <> 0>> /\\\n        <<FAIL: RegFile.eval_expr (State.regs (Thread.state e1_src)) c = 0>>).\n  Proof.\n    inv STEP_TGT.\n    - left.\n      exploit sim_thread_promise_step; eauto. i. des.\n      esplits; eauto.\n      econs 2. econs 1. eauto.\n    - exploit sim_thread_program_step; eauto. i. des.\n      + left. esplits; eauto.\n        inv STEP_SRC.\n        * econs 1.\n        * econs 2. econs 2. eauto.\n      + right. esplits; eauto.\n  Qed.\n\n  Lemma sim_thread_rtc_tau_step\n        tid e1_src e1_tgt e2_tgt\n        (SIM1: sim_thread tid e1_src e1_tgt)\n        (STEPS_TGT: rtc (@Thread.tau_step lang) e1_tgt e2_tgt):\n    (exists e2_src,\n        <<STEPS_SRC: rtc (@Thread.tau_step lang) e1_src e2_src>> /\\\n        <<SIM2: sim_thread tid e2_src e2_tgt>>) \\/\n    (exists e_src e_tgt c stmts,\n        <<STEPS1_TGT: rtc (@Thread.tau_step lang) e1_tgt e_tgt>> /\\\n        <<STEPS2_TGT: rtc (@Thread.tau_step lang) e_tgt e2_tgt>> /\\\n        <<STEPS_SRC: rtc (@Thread.tau_step lang) e1_src e_src>> /\\\n        <<SIM: sim_thread tid e_src e_tgt>> /\\\n        <<STMTS: (State.stmts (Thread.state e_tgt)) =\n                 (Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts>> /\\\n        <<ASSERT: forall (SOUND: S tid lang (Thread.state e_src)),\n            RegFile.eval_expr (State.regs (Thread.state e_src)) c <> 0>> /\\\n        <<FAIL: RegFile.eval_expr (State.regs (Thread.state e_src)) c = 0>>).\n  Proof.\n    revert e1_src SIM1.\n    induction STEPS_TGT; eauto; i.\n    inv H. inv TSTEP.\n    exploit sim_thread_step; eauto. i. des.\n    - exploit IHSTEPS_TGT; eauto. i. des.\n      + left. esplits; [|eauto].\n        inv STEP_SRC; eauto.\n        econs 2; eauto.\n        econs; [econs; eauto|ss].\n      + right.\n        esplits; try exact STEPS2_TGT; try exact SIM; eauto.\n        * econs 2; eauto.\n          econs; [econs; eauto|ss].\n        * inv STEP_SRC; eauto.\n          econs 2; eauto.\n          econs; [econs; eauto|ss].\n    - right.\n      esplits; try exact SIM1; eauto.\n      econs 2; eauto.\n      econs; [econs; eauto| ss].\n  Qed.\n\n  Lemma sim_thread_rtc_program_step\n        tid e1_src e1_tgt e2_tgt\n        (SIM1: sim_thread tid e1_src e1_tgt)\n        (STEPS_TGT: rtc (tau (@Thread.program_step lang)) e1_tgt e2_tgt):\n    (exists e2_src,\n        <<STEPS_SRC: rtc (tau (@Thread.program_step lang)) e1_src e2_src>> /\\\n        <<SIM2: sim_thread tid e2_src e2_tgt>>) \\/\n    (exists e_src e_tgt c stmts,\n        <<STEPS1_TGT: rtc (tau (@Thread.program_step lang)) e1_tgt e_tgt>> /\\\n        <<STEPS2_TGT: rtc (tau (@Thread.program_step lang)) e_tgt e2_tgt>> /\\\n        <<STEPS_SRC: rtc (tau (@Thread.program_step lang)) e1_src e_src>> /\\\n        <<SIM: sim_thread tid e_src e_tgt>> /\\\n        <<STMTS: (State.stmts (Thread.state e_tgt)) =\n                 (Stmt.ite c [Stmt.instr Instr.abort] nil)::stmts>> /\\\n        <<ASSERT: forall (SOUND: S tid lang (Thread.state e_src)),\n            RegFile.eval_expr (State.regs (Thread.state e_src)) c <> 0>> /\\\n        <<FAIL: RegFile.eval_expr (State.regs (Thread.state e_src)) c = 0>>).\n  Proof.\n    revert e1_src SIM1.\n    induction STEPS_TGT; eauto; i.\n    inv H.\n    exploit sim_thread_program_step; eauto. i. des.\n    - exploit IHSTEPS_TGT; eauto. i. des.\n      + left. esplits; [|eauto].\n        inv STEP_SRC; eauto.\n      + right.\n        esplits; try exact STEPS2_TGT; try exact SIM; eauto.\n        inv STEP_SRC; eauto.\n    - right.\n      esplits; try exact SIM1; eauto.\n  Qed.\n\n\n  (* simulation relation on configurations *)\n\n  Inductive sim_conf (c_src c_tgt: Configuration.t): Prop :=\n  | sim_conf_intro\n      (SEM: sem S J c_src)\n      (TIDS: Threads.tids (Configuration.threads c_src) = Threads.tids (Configuration.threads c_tgt))\n      (FIND_SRC: forall tid l st_src lc_src\n                   (FIND: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ l st_src, lc_src)),\n          l = lang)\n      (FIND_TGT: forall tid l st_tgt lc_tgt\n                   (FIND: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ l st_tgt, lc_tgt)),\n          l = lang)\n      (THREADS: forall tid st_src lc_src st_tgt lc_tgt\n                  (FIND_SRC: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st_src, lc_src))\n                  (FIND_TGT: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st_tgt, lc_tgt)),\n          <<STATE: sim_state tid st_src st_tgt>> /\\\n          <<LOCAL: lc_src = lc_tgt>>)\n      (SC: (Configuration.sc c_src) = (Configuration.sc c_tgt))\n      (MEMORY: (Configuration.memory c_src) = (Configuration.memory c_tgt))\n  .\n  #[local]\n  Hint Constructors sim_conf: core.\n\n\n  Lemma sim_conf_find\n        c_src c_tgt tid\n        (SIM: sim_conf c_src c_tgt):\n    (exists lang_src st_src lc_src,\n        IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang_src st_src, lc_src)) <->\n    (exists lang_tgt st_tgt lc_tgt,\n        IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang_tgt st_tgt, lc_tgt)).\n  Proof.\n    inv SIM. destruct c_src, c_tgt. ss.\n    eapply Threads.tids_find; eauto.\n  Qed.\n\n  Lemma sim_conf_sim_thread\n        c_src c_tgt\n        tid st_src lc_src st_tgt lc_tgt\n        (SIM: sim_conf c_src c_tgt)\n        (FIND_SRC: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st_src, lc_src))\n        (FIND_TGT: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st_tgt, lc_tgt)):\n    sim_thread tid\n               (Thread.mk lang st_src lc_src (Configuration.sc c_src) (Configuration.memory c_src))\n               (Thread.mk lang st_tgt lc_tgt (Configuration.sc c_tgt) (Configuration.memory c_tgt)).\n  Proof.\n    inv SIM. exploit THREADS; eauto. i. des.\n    econs; eauto.\n  Qed.\n\n  Lemma sim_conf_sim\n        c_src c_tgt\n        (SIM: sim_conf c_src c_tgt):\n    sim c_src c_tgt.\n  Proof.\n    revert c_src c_tgt SIM.\n    pcofix CIH. i. pfold. econs; ii.\n    { (* terminal *)\n      esplits; eauto. ii.\n      exploit sim_conf_find; eauto. i. des.\n      exploit x0; eauto. i. des.\n      inv SIM. ss.\n      exploit FIND_SRC; eauto. i. subst.\n      exploit FIND_TGT; eauto. i. subst.\n      exploit THREADS; eauto. i. des. subst.\n      exploit TERMINAL_TGT; eauto. i. des.\n      split; auto.\n      destruct st, st_tgt; ss. inv STATE0. ss. subst.\n      inv STATE. inv STMTS. ss.\n    }\n    inv STEP_TGT.\n    { (* failure step *)\n      exploit sim_conf_find; eauto. i. des.\n      exploit x1; eauto. i. des. clear x0 x1.\n      destruct c_src as [ths1_src sc1_src mem1_src].\n      destruct c_tgt as [ths1_tgt sc1 mem1].\n      dup SIM. inv SIM0. ss. subst.\n      exploit FIND_SRC; eauto. i. subst.\n      exploit FIND_TGT; eauto. i. subst.\n      clear FIND_SRC FIND_TGT THREADS.\n      exploit sim_conf_sim_thread; eauto. s. intro SIM_TH.\n      exploit sim_thread_rtc_tau_step; eauto. i. des.\n      - exploit sim_thread_step; eauto. i. des; cycle 1.\n        { destruct e2, state. ss. subst.\n          inv STEP; inv STEP0. inv STATE. }\n        inv STEP_SRC. destruct e2_src0. ss.\n        assert (CSTEP: Configuration.step\n                         MachineEvent.failure tid\n                         (Configuration.mk ths1_src sc1 mem1)\n                         (Configuration.mk\n                            (IdentMap.add tid (existT (fun (lang: language) => (Language.state lang)) lang state, local) ths1_src)\n                            sc memory)).\n        { econs 1; eauto. }\n        esplits; [econs 2; eauto|].\n        right. apply CIH. econs; ss; try by (inv SIM0; ss).\n        + eapply configuration_step_sem; try exact CSTEP; eauto.\n        + repeat rewrite Threads.tids_add.\n          repeat rewrite IdentSet.add_mem; ss.\n          * rewrite Threads.tids_o. rewrite TID. ss.\n          * rewrite Threads.tids_o. rewrite x2. ss.\n        + i. revert FIND. rewrite IdentMap.gsspec. condtac; ss; i.\n          * inv FIND. ss.\n          * inv SIM. eapply FIND_SRC; eauto.\n        + i. revert FIND. rewrite IdentMap.gsspec. condtac; ss; i.\n          * inv FIND. ss.\n          * inv SIM. eapply FIND_TGT; eauto.\n        + i. revert FIND_SRC. rewrite IdentMap.gsspec. condtac; ss; i.\n          * subst. revert FIND_TGT. rewrite IdentMap.gsspec. condtac; ss; i.\n            Configuration.simplify2. inv SIM0. ss.\n          * revert FIND_TGT. rewrite IdentMap.gsspec. condtac; ss; i.\n            inv SIM. eauto.\n      - exfalso.\n        dup WF_TGT. inv WF_TGT0. inv WF. ss. clear DISJOINT.\n        exploit THREADS; eauto. intro WF1_TGT. clear THREADS.\n        dup WF_SRC. inv WF_SRC0. inv WF. ss. clear DISJOINT.\n        exploit THREADS; eauto. intro WF1_SRC. clear THREADS.\n        exploit Thread.rtc_tau_step_future; try exact STEPS1_TGT; eauto. s. i. des.\n        exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n        exploit PFStep.thread_rtc_tau_step; try exact SIM1; eauto.\n        { inv SIM0. rewrite LOCAL.\n          inv STEP; inv STEP0. inv LOCAL0. inv LOCAL1.\n          eapply rtc_tau_step_promise_consistent; eauto. }\n        i. des.\n        inv SEM. ss. exploit TH; eauto. i.\n        exploit rtc_tau_aprogram_step_sem; try exact STEPS_SRC0; eauto.\n        { inv SIM1. ss. rewrite STATE. eauto. }\n        { eapply vals_incl_sem_memory; eauto.\n          eapply PFStep.sim_memory_vals_incl; try eapply SIM1. }\n        { eapply PFStep.sim_memory_inhabited; try eapply SIM1; ss.\n          - apply WF1_SRC.\n          - apply MEM. }\n        i. des.\n        inv SIM2. rewrite STATE in *.\n        eapply ASSERT; eauto.\n    }\n    (* normal step *)\n    exploit sim_conf_find; eauto. i. des.\n    exploit x1; eauto. i. des. clear x0 x1.\n    destruct c_src as [ths1_src sc1_src mem1_src].\n    destruct c_tgt as [ths1_tgt sc1 mem1].\n    dup SIM. inv SIM0. ss. subst.\n    exploit FIND_SRC; eauto. i. subst.\n    exploit FIND_TGT; eauto. i. subst.\n    clear FIND_SRC FIND_TGT THREADS.\n    exploit sim_conf_sim_thread; eauto. s. intro SIM_TH.\n    dup WF_TGT. inv WF_TGT0. inv WF. ss. clear DISJOINT.\n    exploit THREADS; eauto. intro WF1_TGT. clear THREADS.\n    dup WF_SRC. inv WF_SRC0. inv WF. ss. clear DISJOINT.\n    exploit THREADS; eauto. intro WF1_SRC. clear THREADS.\n    exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n    exploit Thread.step_future; eauto. s. i. des.\n    exploit sim_thread_rtc_tau_step; eauto. i. des; cycle 1.\n    { exfalso.\n      exploit Thread.rtc_tau_step_future; try exact STEPS1_TGT; eauto. s. i. des.\n      exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n      exploit PFStep.thread_rtc_tau_step; try exact SIM1; eauto.\n      { inv SIM0. rewrite LOCAL.\n        eapply rtc_tau_step_promise_consistent; eauto.\n        eapply step_promise_consistent; eauto.\n        eapply consistent_promise_consistent; eauto. }\n      i. des.\n      inv SEM. ss. exploit TH; eauto. i.\n      exploit rtc_tau_aprogram_step_sem; try exact STEPS_SRC0; eauto.\n      { inv SIM1. ss. rewrite STATE. eauto. }\n      { eapply vals_incl_sem_memory; eauto.\n        eapply PFStep.sim_memory_vals_incl; try eapply SIM1. }\n      { eapply PFStep.sim_memory_inhabited; try eapply SIM1; ss.\n        - apply WF1_SRC.\n        - apply MEM. }\n      i. des.\n      inv SIM2. rewrite STATE in *.\n      eapply ASSERT; eauto.\n    }\n    exploit sim_thread_step; eauto. i. des; cycle 1.\n    { exfalso.\n      exploit Thread.rtc_tau_step_future; try exact STEPS1_TGT; eauto. s. i. des.\n      exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n      exploit PFStep.thread_rtc_tau_step; try exact SIM0; eauto.\n      { inv SIM2. rewrite LOCAL.\n        eapply step_promise_consistent; eauto.\n        eapply consistent_promise_consistent; eauto. }\n      i. des.\n      inv SEM. ss. exploit TH; eauto. i.\n      exploit rtc_tau_aprogram_step_sem; try exact STEPS_SRC0; eauto.\n      { inv SIM0. ss. rewrite STATE. eauto. }\n      { eapply vals_incl_sem_memory; eauto.\n        eapply PFStep.sim_memory_vals_incl; try eapply SIM0. }\n      { eapply PFStep.sim_memory_inhabited; try eapply SIM0; ss.\n        - apply WF1_SRC.\n        - apply MEM. }\n      i. des.\n      inv SIM1. rewrite STATE in *.\n      eapply ASSERT; eauto.\n    }\n    destruct e2_src0.\n    assert (CONSISTENT_SRC: Thread.consistent (Thread.mk lang state local sc memory)).\n    { exploit Memory.cap_exists; try exact CLOSED0. i. des.\n      exploit Memory.cap_closed; eauto. intro CLOSED_CAP.\n      exploit Local.cap_wf; try exact WF0; eauto. intro WF_CAP.\n      exploit Memory.max_full_timemap_exists; try apply CLOSED_CAP. i. des.\n      hexploit Memory.max_full_timemap_closed; try exact x1; eauto. intro SC_MAX.\n      dup SIM0. inv SIM1. ss. subst. ii. ss.\n      exploit Memory.cap_inj; [exact CAP|exact CAP0|..]; eauto. i. subst.\n      exploit Memory.max_full_timemap_inj; [exact x0|exact SC_MAX0|..]. i. subst.\n      exploit CONSISTENT; eauto. s. i. des.\n      - (* failure certification *)\n        left. unfold Thread.steps_failure in *. des.\n        exploit (@sim_thread_rtc_tau_step tid (Thread.mk lang state lc3 sc0 mem0));\n          try exact STEPS0; eauto.\n        i. des; cycle 1.\n        { exfalso.\n          exploit Thread.tau_opt_all; try exact STEPS_SRC; eauto. i.\n          exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n          exploit PFStep.thread_rtc_all_step; try exact x2; eauto.\n          { hexploit consistent_promise_consistent; eauto. }\n          i. des.\n          exploit PFCertify.sim_thread_exists; try exact SIM4; eauto. s. i. des.\n          exploit PFCertify.thread_rtc_tau_step; try exact STEPS_SRC0; eauto.\n          { exploit Thread.rtc_tau_step_future; try exact STEPS1_TGT; eauto. s. i. des.\n            inv SIM1. rewrite LOCAL.\n            eapply rtc_tau_step_promise_consistent; eauto.\n            inv FAILURE0; inv STEP0. inv LOCAL0. inv LOCAL1. ss. }\n          i. des.\n          inv SEM. ss. exploit TH; eauto. i.\n          exploit rtc_all_aprogram_step_sem; try exact STEPS_SRC; eauto.\n          { inv SIM3. ss. rewrite STATE0. eauto. }\n          { eapply vals_incl_sem_memory; eauto.\n            eapply PFStep.sim_memory_vals_incl; try eapply SIM3. }\n          { eapply PFStep.sim_memory_inhabited; try eapply SIM3; ss.\n            - apply WF1_SRC.\n            - apply MEM. }\n          i. des.\n          exploit rtc_pf_step_sem; try exact STEPS_SRC2; eauto; s.\n          { eapply vals_incl_sem_memory; eauto. }\n          { eapply PFCertify.sim_memory_inhabited; try eapply SIM5.\n            - apply WF0.\n            - eapply Memory.cap_closed; eauto. }\n          i. des.\n          inv SIM6. rewrite STATE0 in *.\n          eapply ASSERT; eauto.\n        }\n        exploit sim_thread_step; try exact SIM1; eauto. i. des; cycle 1.\n        { exfalso.\n          exploit Thread.tau_opt_all; try exact STEPS_SRC; eauto. i.\n          exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n          exploit PFStep.thread_rtc_all_step; try exact x2; eauto.\n          { hexploit consistent_promise_consistent; eauto. }\n          i. des.\n          exploit PFCertify.sim_thread_exists; try exact SIM4; eauto. s. i. des.\n          exploit PFCertify.thread_rtc_tau_step; try exact STEPS_SRC0; eauto.\n          { exploit Thread.rtc_tau_step_future; try exact STEPS0; eauto. s. i. des.\n            inv SIM1. rewrite LOCAL.\n            eapply rtc_tau_step_promise_consistent; eauto.\n            inv FAILURE0; inv STEP0. inv LOCAL0. inv LOCAL1. ss. }\n          i. des.\n          inv SEM. ss. exploit TH; eauto. i.\n          exploit rtc_all_aprogram_step_sem; try exact STEPS_SRC; eauto.\n          { inv SIM3. ss. rewrite STATE0. eauto. }\n          { eapply vals_incl_sem_memory; eauto.\n            eapply PFStep.sim_memory_vals_incl; try eapply SIM3. }\n          { eapply PFStep.sim_memory_inhabited; try eapply SIM3; ss.\n            - apply WF1_SRC.\n            - apply MEM. }\n          i. des.\n          exploit rtc_pf_step_sem; try exact STEPS_SRC2; eauto; s.\n          { eapply vals_incl_sem_memory; eauto. }\n          { eapply PFCertify.sim_memory_inhabited; try eapply SIM5.\n            - apply WF0.\n            - eapply Memory.cap_closed; eauto. }\n          i. des.\n          inv SIM6. rewrite STATE0 in *.\n          eapply ASSERT; eauto.\n        }\n        inv STEP_SRC0. destruct pf0; try by (inv STEP0; inv STEP1).\n        esplits; eauto.\n      - (* normal certification *)\n        right.\n        exploit (@sim_thread_rtc_tau_step tid (Thread.mk lang state lc3 sc0 mem0));\n          try exact STEPS0; eauto. i. des; cycle 1.\n        { exfalso.\n          exploit Thread.tau_opt_all; try exact STEPS_SRC; eauto. i.\n          exploit (@PFStep.sim_thread_exists lang (Thread.mk lang st_src lc_src sc1 mem1)); ss; eauto. i. des.\n          exploit PFStep.thread_rtc_all_step; try exact x2; eauto.\n          { hexploit consistent_promise_consistent; eauto. }\n          i. des.\n          exploit PFCertify.sim_thread_exists; try exact SIM4; eauto. s. i. des.\n          exploit PFCertify.thread_rtc_tau_step; try exact STEPS_SRC0; eauto.\n          { exploit Thread.rtc_tau_step_future; try exact STEPS1_TGT; eauto. s. i. des.\n            inv SIM1. rewrite LOCAL.\n            eapply rtc_tau_step_promise_consistent; eauto.\n            eapply Local.bot_promise_consistent; eauto. }\n          i. des.\n          inv SEM. ss. exploit TH; eauto. i.\n          exploit rtc_all_aprogram_step_sem; try exact STEPS_SRC; eauto.\n          { inv SIM3. ss. rewrite STATE0. eauto. }\n          { eapply vals_incl_sem_memory; eauto.\n            eapply PFStep.sim_memory_vals_incl; try eapply SIM3. }\n          { eapply PFStep.sim_memory_inhabited; try eapply SIM3; ss.\n            - apply WF1_SRC.\n            - apply MEM. }\n          i. des.\n          exploit rtc_pf_step_sem; try exact STEPS_SRC2; eauto; s.\n          { eapply vals_incl_sem_memory; eauto. }\n          { eapply PFCertify.sim_memory_inhabited; try eapply SIM5.\n            - apply WF0.\n            - eapply Memory.cap_closed; eauto. }\n          i. des.\n          inv SIM6. rewrite STATE0 in *.\n          eapply ASSERT; eauto.\n        }\n        esplits; eauto.\n        inv SIM1. rewrite LOCAL. ss.\n    }\n    assert (CSTEP: Configuration.opt_step\n                     (ThreadEvent.get_machine_event e0) tid\n                     (Configuration.mk ths1_src sc1 mem1)\n                     (Configuration.mk\n                        (IdentMap.add tid (existT (fun (lang: language) => (Language.state lang)) lang state, local) ths1_src)\n                        sc memory)).\n    { inv STEP_SRC.\n      - generalize (rtc_tail STEPS_SRC). i. des.\n        + inv H0. inv TSTEP. ss. rewrite <- EVENT0.\n          econs 2. econs; try exact x; try exact H; eauto.\n          destruct e; ss.\n        + inv H. ss.\n          replace (IdentMap.add\n                     tid\n                     (existT (fun lang:language => (Language.state lang)) lang state, local)\n                     ths1_src)\n            with ths1_src; eauto.\n          apply IdentMap.eq_leibniz. ii.\n          rewrite -> IdentMap.gsident; auto.\n      - econs 2. econs 2; try exact x; try exact H; eauto.\n    }\n    esplits; eauto.\n    right. apply CIH. econs; ss; try by (inv SIM0; ss).\n    - inv CSTEP; ss.\n      + repeat rewrite <- H. ss.\n      + eapply configuration_step_sem; try exact STEP0; eauto.\n    - repeat rewrite Threads.tids_add.\n      repeat rewrite IdentSet.add_mem; ss.\n      + rewrite Threads.tids_o. rewrite TID. ss.\n      + rewrite Threads.tids_o. rewrite x2. ss.\n    - i. revert FIND. rewrite IdentMap.gsspec. condtac; ss; i.\n      + inv FIND. ss.\n      + inv SIM. eapply FIND_SRC; eauto.\n    - i. revert FIND. rewrite IdentMap.gsspec. condtac; ss; i.\n      + inv FIND. ss.\n      + inv SIM. eapply FIND_TGT; eauto.\n    - i. revert FIND_SRC. rewrite IdentMap.gsspec. condtac; ss; i.\n      + subst. revert FIND_TGT. rewrite IdentMap.gsspec. condtac; ss; i.\n        Configuration.simplify2. inv SIM0. ss.\n      + revert FIND_TGT. rewrite IdentMap.gsspec. condtac; ss; i.\n        inv SIM. eauto.\n  Qed.\n\n\n  (* assert insertion *)\n\n  Definition syntax_tids (pgm: Threads.syntax): IdentSet.t :=\n    List.fold_right (fun p s => IdentSet.add (fst p) s) IdentSet.empty (IdentMap.elements pgm).\n\n  Lemma syntax_tids_o tid pgm:\n    IdentSet.mem tid (syntax_tids pgm) = IdentMap.find tid pgm.\n  Proof.\n    unfold syntax_tids. rewrite IdentMap.Facts.elements_o.\n    induction (IdentMap.elements pgm); ss. destruct a. s.\n    rewrite IdentSet.Facts.add_b, IHl.\n    unfold IdentSet.Facts.eqb, IdentMap.Facts.eqb.\n    repeat match goal with\n           | [|- context[if ?c then true else false]] => destruct c\n           end; ss; congr.\n  Qed.\n\n  Inductive insert_assertion_program (program_tgt: Threads.syntax): Prop :=\n  | insert_assertion_program_intro\n      (TIDS: syntax_tids program_tgt = syntax_tids program)\n      (FIND_SRC: forall tid l syn_src\n                   (FIND: IdentMap.find tid program = Some (existT _ l syn_src)),\n          l = lang)\n      (FIND_TGT: forall tid l syn_tgt\n                   (FIND: IdentMap.find tid program_tgt = Some (existT _ l syn_tgt)),\n          l = lang)\n      (THREADS: forall tid syn_src syn_tgt\n                  (FIND_SRC: IdentMap.find tid program = Some (existT _ lang syn_src))\n                  (FIND_TGT: IdentMap.find tid program_tgt = Some (existT _ lang syn_tgt)),\n          insert_assertion tid syn_src syn_tgt)\n  .\n\n  Lemma init_sim_conf\n        program_tgt\n        (INSERT: insert_assertion_program program_tgt):\n    sim_conf (Configuration.init program) (Configuration.init program_tgt).\n  Proof.\n    inv INSERT. econs; ss; i.\n    - apply init_sem; ss.\n    - apply IdentSet.ext. i.\n      repeat rewrite Threads.tids_o.\n      unfold Threads.init.\n      repeat rewrite IdentMap.Facts.map_o.\n      specialize (@syntax_tids_o i program). i.\n      specialize (@syntax_tids_o i program_tgt). i.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) i program) eqn:SRC;\n        destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                    (@sigT _ (@Language.syntax ProgramEvent.t)) i program_tgt) eqn:TGT; ss.\n      + assert (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) i program = IdentMap.find i program) by ss.\n        rewrite <- H1 in *. rewrite SRC in *. ss.\n        assert (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) i program_tgt = IdentMap.find i program_tgt) by ss.\n        rewrite <- H2 in *. rewrite TGT in *. ss.\n        rewrite TIDS in *. congr.\n      + assert (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) i program = IdentMap.find i program) by ss.\n        rewrite <- H1 in *. rewrite SRC in *. ss.\n        assert (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) i program_tgt = IdentMap.find i program_tgt) by ss.\n        rewrite <- H2 in *. rewrite TGT in *. ss.\n        rewrite TIDS in *. congr.\n    - unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid program) eqn:SRC; ss.\n      destruct s. ss. inv FIND. eapply FIND_SRC; eauto.\n    - unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid program_tgt) eqn:SRC; ss.\n      destruct s. ss. inv FIND. eapply FIND_TGT; eauto.\n    - unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid program) eqn:SRC;\n        destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                    (@sigT _ (@Language.syntax ProgramEvent.t)) tid program_tgt) eqn:TGT; ss.\n      destruct s, s0; ss.\n      inv FIND_SRC0. inv FIND_TGT0. split; ss. Configuration.simplify2.\n      unfold State.init. econs; ss.\n      eapply THREADS; eauto.\n  Qed.\n\n  Theorem insert_assertion_behavior\n          program_tgt\n          (INSERT: insert_assertion_program program_tgt):\n    behaviors Configuration.step (Configuration.init program_tgt) <1=\n    behaviors Configuration.step (Configuration.init program).\n  Proof.\n    exploit init_sim_conf; eauto. i.\n    specialize (Configuration.init_wf program). intro WF_SRC.\n    specialize (Configuration.init_wf program_tgt). intro WF_TGT.\n    hexploit sim_conf_sim; eauto. i.\n    exploit sim_adequacy; try exact H; eauto.\n  Qed.\nEnd AssertInsertion.\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/gopt/AssertInsertion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.19867635215314963}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom iris.bi Require Import fixpoint big_op.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nDefinition twp_pre `{irisG \u039b \u03a3} (s : stuckness)\n      (wp : coPset \u2192 expr \u039b \u2192 (val \u039b \u2192 iProp \u03a3) \u2192 iProp \u03a3) :\n    coPset \u2192 expr \u039b \u2192 (val \u039b \u2192 iProp \u03a3) \u2192 iProp \u03a3 := \u03bb E e1 \u03a6,\n  match to_val e1 with\n  | Some v => |={E}=> \u03a6 v\n  | None => \u2200 \u03c31,\n     state_interp \u03c31 ={E,\u2205}=\u2217 \u231cif s is NotStuck then reducible e1 \u03c31 else True\u231d \u2217\n     \u2200 e2 \u03c32 efs, \u231cprim_step e1 \u03c31 e2 \u03c32 efs\u231d ={\u2205,E}=\u2217\n       state_interp \u03c32 \u2217 wp E e2 \u03a6 \u2217\n       [\u2217 list] ef \u2208 efs, wp \u22a4 ef (\u03bb _, True)\n  end%I.\n\nLemma twp_pre_mono `{irisG \u039b \u03a3} s\n    (wp1 wp2 : coPset \u2192 expr \u039b \u2192 (val \u039b \u2192 iProp \u03a3) \u2192 iProp \u03a3) :\n  ((\u25a1 \u2200 E e \u03a6, wp1 E e \u03a6 -\u2217 wp2 E e \u03a6) \u2192\n  \u2200 E e \u03a6, twp_pre s wp1 E e \u03a6 -\u2217 twp_pre s wp2 E e \u03a6)%I.\nProof.\n  iIntros \"#H\"; iIntros (E e1 \u03a6) \"Hwp\". rewrite /twp_pre.\n  destruct (to_val e1) as [v|]; first done.\n  iIntros (\u03c31) \"H\u03c3\". iMod (\"Hwp\" with \"H\u03c3\") as \"($ & Hwp)\"; iModIntro.\n  iIntros (e2 \u03c32 efs) \"Hstep\".\n  iMod (\"Hwp\" with \"Hstep\") as \"($ & Hwp & Hfork)\"; iModIntro; iSplitL \"Hwp\".\n  - by iApply \"H\".\n  - iApply (@big_sepL_impl with \"[$Hfork]\"); iIntros \"!#\" (k e _) \"Hwp\".\n    by iApply \"H\".\nQed.\n\n(* Uncurry [twp_pre] and equip its type with an OFE structure *)\nDefinition twp_pre' `{irisG \u039b \u03a3} (s : stuckness) :\n  (prodC (prodC (leibnizC coPset) (exprC \u039b)) (val \u039b -c> iProp \u03a3) \u2192 iProp \u03a3) \u2192\n  prodC (prodC (leibnizC coPset) (exprC \u039b)) (val \u039b -c> iProp \u03a3) \u2192 iProp \u03a3 :=\n    curry3 \u2218 twp_pre s \u2218 uncurry3.\n\nLocal Instance twp_pre_mono' `{irisG \u039b \u03a3} s : BiMonoPred (twp_pre' s).\nProof.\n  constructor.\n  - iIntros (wp1 wp2) \"#H\"; iIntros ([[E e1] \u03a6]); iRevert (E e1 \u03a6).\n    iApply twp_pre_mono. iIntros \"!#\" (E e \u03a6). iApply (\"H\" $! (E,e,\u03a6)).\n  - intros wp Hwp n [[E1 e1] \u03a61] [[E2 e2] \u03a62]\n      [[?%leibniz_equiv ?%leibniz_equiv] ?]; simplify_eq/=.\n    rewrite /uncurry3 /twp_pre. do 16 (f_equiv || done). by apply Hwp, pair_ne.\nQed.\n\nDefinition twp_def `{irisG \u039b \u03a3} (s : stuckness) (E : coPset)\n    (e : expr \u039b) (\u03a6 : val \u039b \u2192 iProp \u03a3) :\n  iProp \u03a3 := bi_least_fixpoint (twp_pre' s) (E,e,\u03a6).\nDefinition twp_aux `{irisG \u039b \u03a3} : seal (@twp_def \u039b \u03a3 _). by eexists. Qed.\nInstance twp' `{irisG \u039b \u03a3} : Twp \u039b (iProp \u03a3) stuckness := twp_aux.(unseal).\nDefinition twp_eq `{irisG \u039b \u03a3} : twp = @twp_def \u039b \u03a3 _ := twp_aux.(seal_eq).\n\nSection twp.\nContext `{irisG \u039b \u03a3}.\nImplicit Types s : stuckness.\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 iProp \u03a3.\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\n\n(* Weakest pre *)\nLemma twp_unfold s E e \u03a6 : WP e @ s; E [{ \u03a6 }] \u22a3\u22a2 twp_pre s (twp s) E e \u03a6.\nProof. by rewrite twp_eq /twp_def least_fixpoint_unfold. Qed.\nLemma twp_ind s \u03a8 :\n  (\u2200 n E e, Proper (pointwise_relation _ (dist n) ==> dist n) (\u03a8 E e)) \u2192\n  (\u25a1 (\u2200 e E \u03a6, twp_pre s (\u03bb E e \u03a6, \u03a8 E e \u03a6 \u2227 WP e @ s; E [{ \u03a6 }]) E e \u03a6 -\u2217 \u03a8 E e \u03a6) \u2192\n  \u2200 e E \u03a6, WP e @ s; E [{ \u03a6 }] -\u2217 \u03a8 E e \u03a6)%I.\nProof.\n  iIntros (H\u03a8). iIntros \"#IH\" (e E \u03a6) \"H\". rewrite twp_eq.\n  set (\u03a8' := curry3 \u03a8 :\n    prodC (prodC (leibnizC coPset) (exprC \u039b)) (val \u039b -c> iProp \u03a3) \u2192 iProp \u03a3).\n  assert (NonExpansive \u03a8').\n  { intros n [[E1 e1] \u03a61] [[E2 e2] \u03a62]\n      [[?%leibniz_equiv ?%leibniz_equiv] ?]; simplify_eq/=. by apply H\u03a8. }\n  iApply (least_fixpoint_strong_ind _ \u03a8' with \"[] H\").\n  iIntros \"!#\" ([[??] ?]) \"H\". by iApply \"IH\".\nQed.\n\nGlobal Instance twp_ne s E e n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (twp (PROP:=iProp \u03a3) s E e).\nProof.\n  intros \u03a61 \u03a62 H\u03a6. rewrite !twp_eq. by apply (least_fixpoint_ne _), pair_ne, H\u03a6.\nQed.\nGlobal Instance twp_proper s E e :\n  Proper (pointwise_relation _ (\u2261) ==> (\u2261)) (twp (PROP:=iProp \u03a3) s E e).\nProof.\n  by intros \u03a6 \u03a6' ?; apply equiv_dist=>n; apply twp_ne=>v; apply equiv_dist.\nQed.\n\nLemma twp_value' s E \u03a6 v : \u03a6 v -\u2217 WP of_val v @ s; E [{ \u03a6 }].\nProof. iIntros \"H\u03a6\". rewrite twp_unfold /twp_pre to_of_val. auto. Qed.\nLemma twp_value_inv' s E \u03a6 v : WP of_val v @ s; E [{ \u03a6 }] ={E}=\u2217 \u03a6 v.\nProof. by rewrite twp_unfold /twp_pre to_of_val. Qed.\n\nLemma twp_strong_mono s1 s2 E1 E2 e \u03a6 \u03a8 :\n  s1 \u2291 s2 \u2192 E1 \u2286 E2 \u2192\n  WP e @ s1; E1 [{ \u03a6 }] -\u2217 (\u2200 v, \u03a6 v ={E2}=\u2217 \u03a8 v) -\u2217 WP e @ s2; E2 [{ \u03a8 }].\nProof.\n  iIntros (? HE) \"H H\u03a6\". iRevert (E2 \u03a8 HE) \"H\u03a6\"; iRevert (e E1 \u03a6) \"H\".\n  iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e E1 \u03a6) \"IH\"; iIntros (E2 \u03a8 HE) \"H\u03a6\".\n  rewrite !twp_unfold /twp_pre. destruct (to_val e) as [v|] eqn:?.\n  { iApply (\"H\u03a6\" with \"[> -]\"). by iApply (fupd_mask_mono E1 _). }\n  iIntros (\u03c31) \"H\u03c3\". iMod (fupd_intro_mask' E2 E1) as \"Hclose\"; first done.\n  iMod (\"IH\" with \"[$]\") as \"[% IH]\".\n  iModIntro; iSplit; [by destruct s1, s2|]. iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"IH\" with \"[//]\") as \"($ & IH & IHefs)\"; auto.\n  iMod \"Hclose\" as \"_\"; iModIntro. iSplitR \"IHefs\".\n  - iDestruct \"IH\" as \"[IH _]\". iApply (\"IH\" with \"[//] H\u03a6\").\n  - iApply (big_sepL_impl with \"[$IHefs]\"); iIntros \"!#\" (k ef _) \"[IH _]\".\n    by iApply \"IH\".\nQed.\n\nLemma fupd_twp s E e \u03a6 : (|={E}=> WP e @ s; E [{ \u03a6 }]) -\u2217 WP e @ s; E [{ \u03a6 }].\nProof.\n  rewrite twp_unfold /twp_pre. iIntros \"H\". destruct (to_val e) as [v|] eqn:?.\n  { by iMod \"H\". }\n  iIntros (\u03c31) \"H\u03c31\". iMod \"H\". by iApply \"H\".\nQed.\nLemma twp_fupd s E e \u03a6 : WP e @ s; E [{ v, |={E}=> \u03a6 v }] -\u2217 WP e @ s; E [{ \u03a6 }].\nProof. iIntros \"H\". iApply (twp_strong_mono with \"H\"); auto. Qed.\n\nLemma twp_atomic s E1 E2 e \u03a6 `{!Atomic (stuckness_to_atomicity s) e} :\n  (|={E1,E2}=> WP e @ s; E2 [{ v, |={E2,E1}=> \u03a6 v }]) -\u2217 WP e @ s; E1 [{ \u03a6 }].\nProof.\n  iIntros \"H\". rewrite !twp_unfold /twp_pre /=.\n  destruct (to_val e) as [v|] eqn:He.\n  { by iDestruct \"H\" as \">>> $\". }\n  iIntros (\u03c31) \"H\u03c3\". iMod \"H\". iMod (\"H\" $! \u03c31 with \"H\u03c3\") as \"[$ H]\".\n  iModIntro. iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"(Hphy & H & $)\". destruct s.\n  - rewrite !twp_unfold /twp_pre. destruct (to_val e2) as [v2|] eqn:He2.\n    + iDestruct \"H\" as \">> $\". by iFrame.\n    + iMod (\"H\" with \"[$]\") as \"[H _]\". iDestruct \"H\" as %(? & ? & ? & ?).\n      by edestruct (atomic _ _ _ _ Hstep).\n  - destruct (atomic _ _ _ _ Hstep) as [v <-%of_to_val].\n    iMod (twp_value_inv' with \"H\") as \">H\". iFrame \"Hphy\". by iApply twp_value'.\nQed.\n\nLemma twp_bind K `{!LanguageCtx K} s E e \u03a6 :\n  WP e @ s; E [{ v, WP K (of_val v) @ s; E [{ \u03a6 }] }] -\u2217 WP K e @ s; E [{ \u03a6 }].\nProof.\n  revert \u03a6. cut (\u2200 \u03a6', WP e @ s; E [{ \u03a6' }] -\u2217 \u2200 \u03a6,\n    (\u2200 v, \u03a6' v -\u2217 WP K (of_val v) @ s; E [{ \u03a6 }]) -\u2217 WP K e @ s; E [{ \u03a6 }]).\n  { iIntros (help \u03a6) \"H\". iApply (help with \"H\"); auto. }\n  iIntros (\u03a6') \"H\". iRevert (e E \u03a6') \"H\". iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e E1 \u03a6') \"IH\". iIntros (\u03a6) \"H\u03a6\".\n  rewrite /twp_pre. destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. iApply fupd_twp. by iApply \"H\u03a6\". }\n  rewrite twp_unfold /twp_pre fill_not_val //.\n  iIntros (\u03c31) \"H\u03c3\". iMod (\"IH\" with \"[$]\") as \"[% IH]\". iModIntro; iSplit.\n  { iPureIntro. unfold reducible in *.\n    destruct s; naive_solver eauto using fill_step. }\n  iIntros (e2 \u03c32 efs Hstep).\n  destruct (fill_step_inv e \u03c31 e2 \u03c32 efs) as (e2'&->&?); auto.\n  iMod (\"IH\" $! e2' \u03c32 efs with \"[//]\") as \"($ & IH & IHfork)\".\n  iModIntro; iSplitR \"IHfork\".\n  - iDestruct \"IH\" as \"[IH _]\". by iApply \"IH\".\n  - by setoid_rewrite and_elim_r.\nQed.\n\nLemma twp_bind_inv K `{!LanguageCtx K} s E e \u03a6 :\n  WP K e @ s; E [{ \u03a6 }] -\u2217 WP e @ s; E [{ v, WP K (of_val v) @ s; E [{ \u03a6 }] }].\nProof.\n  iIntros \"H\". remember (K e) as e' eqn:He'.\n  iRevert (e He'). iRevert (e' E \u03a6) \"H\". iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e' E1 \u03a6) \"IH\". iIntros (e ->).\n  rewrite !twp_unfold {2}/twp_pre. destruct (to_val e) as [v|] eqn:He.\n  { iModIntro. apply of_to_val in He as <-. rewrite !twp_unfold.\n    iApply (twp_pre_mono with \"[] IH\"). by iIntros \"!#\" (E e \u03a6') \"[_ ?]\". }\n  rewrite /twp_pre fill_not_val //.\n  iIntros (\u03c31) \"H\u03c3\". iMod (\"IH\" with \"[$]\") as \"[% IH]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_fill. }\n  iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"IH\" $! (K e2) \u03c32 efs with \"[]\") as \"($ & IH & IHfork)\"; eauto using fill_step.\n  iModIntro; iSplitR \"IHfork\".\n  - iDestruct \"IH\" as \"[IH _]\". by iApply \"IH\".\n  - by setoid_rewrite and_elim_r.\nQed.\n\nLemma twp_wp s E e \u03a6 : WP e @ s; E [{ \u03a6 }] -\u2217 WP e @ s; E {{ \u03a6 }}.\nProof.\n  iIntros \"H\". iL\u00f6b as \"IH\" forall (E e \u03a6).\n  rewrite wp_unfold twp_unfold /wp_pre /twp_pre. destruct (to_val e) as [v|]=>//.\n  iIntros (\u03c31) \"H\u03c3\". iMod (\"H\" with \"H\u03c3\") as \"[$ H]\". iIntros \"!>\".\n  iIntros (e2 \u03c32 efs) \"Hstep\". iMod (\"H\" with \"Hstep\") as \"($ & H & Hfork)\".\n  iApply step_fupd_intro; [set_solver+|]. iNext.\n  iSplitL \"H\". by iApply \"IH\". iApply (@big_sepL_impl with \"[$Hfork]\").\n  iIntros \"!#\" (k e' _) \"H\". by iApply \"IH\".\nQed.\n\n(** * Derived rules *)\nLemma twp_mono s E e \u03a6 \u03a8 :\n  (\u2200 v, \u03a6 v -\u2217 \u03a8 v) \u2192 WP e @ s; E [{ \u03a6 }] -\u2217 WP e @ s; E [{ \u03a8 }].\nProof.\n  iIntros (H\u03a6) \"H\"; iApply (twp_strong_mono with \"H\"); auto.\n  iIntros (v) \"?\". by iApply H\u03a6.\nQed.\nLemma twp_stuck_mono s1 s2 E e \u03a6 :\n  s1 \u2291 s2 \u2192 WP e @ s1; E [{ \u03a6 }] \u22a2 WP e @ s2; E [{ \u03a6 }].\nProof. iIntros (?) \"H\". iApply (twp_strong_mono with \"H\"); auto. Qed.\nLemma twp_stuck_weaken s E e \u03a6 :\n  WP e @ s; E [{ \u03a6 }] \u22a2 WP e @ E ?[{ \u03a6 }].\nProof. apply twp_stuck_mono. by destruct s. Qed.\nLemma twp_mask_mono s E1 E2 e \u03a6 :\n  E1 \u2286 E2 \u2192 WP e @ s; E1 [{ \u03a6 }] -\u2217 WP e @ s; E2 [{ \u03a6 }].\nProof. iIntros (?) \"H\"; iApply (twp_strong_mono with \"H\"); auto. Qed.\nGlobal Instance twp_mono' s E e :\n  Proper (pointwise_relation _ (\u22a2) ==> (\u22a2)) (twp (PROP:=iProp \u03a3) s E e).\nProof. by intros \u03a6 \u03a6' ?; apply twp_mono. Qed.\n\nLemma twp_value s E \u03a6 e v : IntoVal e v \u2192 \u03a6 v -\u2217 WP e @ s; E [{ \u03a6 }].\nProof. intros <-. by apply twp_value'. Qed.\nLemma twp_value_fupd' s E \u03a6 v : (|={E}=> \u03a6 v) -\u2217 WP of_val v @ s; E [{ \u03a6 }].\nProof. intros. by rewrite -twp_fupd -twp_value'. Qed.\nLemma twp_value_fupd s E \u03a6 e v : IntoVal e v \u2192 (|={E}=> \u03a6 v) -\u2217 WP e @ s; E [{ \u03a6 }].\nProof. intros ?. rewrite -twp_fupd -twp_value //. Qed.\nLemma twp_value_inv s E \u03a6 e v : IntoVal e v \u2192 WP e @ s; E [{ \u03a6 }] ={E}=\u2217 \u03a6 v.\nProof. intros <-. by apply twp_value_inv'. Qed.\n\nLemma twp_frame_l s E e \u03a6 R : R \u2217 WP e @ s; E [{ \u03a6 }] -\u2217 WP e @ s; E [{ v, R \u2217 \u03a6 v }].\nProof. iIntros \"[? H]\". iApply (twp_strong_mono with \"H\"); auto with iFrame. Qed.\nLemma twp_frame_r s E e \u03a6 R : WP e @ s; E [{ \u03a6 }] \u2217 R -\u2217 WP e @ s; E [{ v, \u03a6 v \u2217 R }].\nProof. iIntros \"[H ?]\". iApply (twp_strong_mono with \"H\"); auto with iFrame. Qed.\n\nLemma twp_wand s E e \u03a6 \u03a8 :\n  WP e @ s; E [{ \u03a6 }] -\u2217 (\u2200 v, \u03a6 v -\u2217 \u03a8 v) -\u2217 WP e @ s; E [{ \u03a8 }].\nProof.\n  iIntros \"H H\u03a6\". iApply (twp_strong_mono with \"H\"); auto.\n  iIntros (?) \"?\". by iApply \"H\u03a6\".\nQed.\nLemma twp_wand_l s E e \u03a6 \u03a8 :\n  (\u2200 v, \u03a6 v -\u2217 \u03a8 v) \u2217 WP e @ s; E [{ \u03a6 }] -\u2217 WP e @ s; E [{ \u03a8 }].\nProof. iIntros \"[H Hwp]\". iApply (twp_wand with \"Hwp H\"). Qed.\nLemma twp_wand_r s E e \u03a6 \u03a8 :\n  WP e @ s; E [{ \u03a6 }] \u2217 (\u2200 v, \u03a6 v -\u2217 \u03a8 v) -\u2217 WP e @ s; E [{ \u03a8 }].\nProof. iIntros \"[Hwp H]\". iApply (twp_wand with \"Hwp H\"). Qed.\nEnd twp.\n\n(** Proofmode class instances *)\nSection proofmode_classes.\n  Context `{irisG \u039b \u03a3}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03a6 : val \u039b \u2192 iProp \u03a3.\n\n  Global Instance frame_twp p s E e R \u03a6 \u03a8 :\n    (\u2200 v, Frame p R (\u03a6 v) (\u03a8 v)) \u2192\n    Frame p R (WP e @ s; E [{ \u03a6 }]) (WP e @ s; E [{ \u03a8 }]).\n  Proof. rewrite /Frame=> HR. rewrite twp_frame_l. apply twp_mono, HR. Qed.\n\n  Global Instance is_except_0_wp s E e \u03a6 : IsExcept0 (WP e @ s; E [{ \u03a6 }]).\n  Proof. by rewrite /IsExcept0 -{2}fupd_twp -except_0_fupd -fupd_intro. Qed.\n\n  Global Instance elim_modal_bupd_twp p s E e P \u03a6 :\n    ElimModal True p false (|==> P) P (WP e @ s; E [{ \u03a6 }]) (WP e @ s; E [{ \u03a6 }]).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      (bupd_fupd E) fupd_frame_r wand_elim_r fupd_twp.\n  Qed.\n\n  Global Instance elim_modal_fupd_twp p s E e P \u03a6 :\n    ElimModal True p false (|={E}=> P) P (WP e @ s; E [{ \u03a6 }]) (WP e @ s; E [{ \u03a6 }]).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r fupd_twp.\n  Qed.\n\n  Global Instance elim_modal_fupd_twp_atomic p s E1 E2 e P \u03a6 :\n    Atomic (stuckness_to_atomicity s) e \u2192\n    ElimModal True p false (|={E1,E2}=> P) P\n            (WP e @ s; E1 [{ \u03a6 }]) (WP e @ s; E2 [{ v, |={E2,E1}=> \u03a6 v }])%I.\n  Proof.\n    intros. by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r twp_atomic.\n  Qed.\n\n  Global Instance add_modal_fupd_twp s E e P \u03a6 :\n    AddModal (|={E}=> P) P (WP e @ s; E [{ \u03a6 }]).\n  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_twp. Qed.\nEnd proofmode_classes.\n", "meta": {"author": "JasonGross", "repo": "iris-coq", "sha": "f891015e2ab48926cec9618b0eadf0c0fec9ba1b", "save_path": "github-repos/coq/JasonGross-iris-coq", "path": "github-repos/coq/JasonGross-iris-coq/iris-coq-f891015e2ab48926cec9618b0eadf0c0fec9ba1b/theories/program_logic/total_weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19863872695545315}}
{"text": "(* Concurrent Compiler Correcntess *)\n\n(** Prove a simulation between the Clight concurrent semantics and \n    the x86 concurrent semantics.\n*)\n\nRequire Import VST.concurrency.compiler.HybridMachine_simulation.\n\n(*Clight Machine *)\nRequire Import VST.concurrency.common.ClightMachine.\n(*Asm Machine*)\nRequire Import VST.concurrency.common.x86_context.\n\n\nSection ConcurrentCopmpilerSpecification.\n  (*Import the Clight Hybrid Machine*)\n  Import ClightMachine.\n  Import DMS.  \n  (*Import the Asm X86 Hybrid Machine*)\n  Import X86Context.\n\n  (*Import the Asm Hybrid Machine*)\n  Context (Clight_g : Clight.genv).\n  Context (Asm_g : Clight.genv).\n  Context (Asm_program: Asm.program).\n  Context (Asm_genv_safe: Asm_core.safe_genv (@the_ge Asm_program)).\n\n  Variable opt_init_mem_source: option Memory.Mem.mem.\n  Variable opt_init_mem_target: option Memory.Mem.mem.\n  Definition ConcurrentCompilerCorrectness_specification: Type:=\n    HybridMachine_simulation (ClightConcurSem(ge:=Clight_g) opt_init_mem_source) (@AsmConcurSem Asm_program Asm_genv_safe opt_init_mem_target).\n\n\nEnd ConcurrentCopmpilerSpecification.\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/concurrent_compiler_simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19863872695545315}}
{"text": "(**\n   Version tr\u00e8s simplifi\u00e9e des id\u00e9e de: \"Java bytecode verification: algorithms\n   and formalizations\", Xavier Leroy (Journal of Automated Reasoning,\n   30(3-4):235-269, 2003).\n\n   Dont voici l'abstract:\n\n   \"Bytecode verification is a crucial security component for Java applets, on\n   the Web and on embedded devices such as smart cards. This paper reviews the\n   various bytecode verification algorithms that have been proposed, recasts\n   them in a common framework of dataflow analysis, and surveys the use of proof\n   assistants to specify bytecode verification and prove its correctness.\"\n\n *)\n\n(* Coq \u00e9crira de pr\u00e9f\u00e9rence la syntaxe [foo.(bar)] plut\u00f4t que [(bar\n   foo)], pour les champs (bar) de records (foo). *)\nSet Printing Projections.\n\n\nRequire Omega.\nRequire Import OrderedType OrderedTypeEx OrderedTypeAlt DecidableType DecidableTypeEx FunInd.\nFrom bcv Require Import LibHypsNaming heritage vmtype vmdefinition.\n\n(** * Valeurs manipul\u00e9e par la machine d\u00e9fensive,\n\n   Ce module servira \u00e0 instancier VMDefinition plus bas.\n   La d\u00e9finition des types, classes et instruction est fix\u00e9e dans [vmtype]. *)\n\nModule DefVal <: VMVal.\n\n  Inductive DVal:Set :=\n  | Vint (i:nat)\n  | Vref (clrf:class_id * heap_idx) (** nom de classe * adresse dans le tas *)\n  | Vrefnull\n  | Error\n  | NonInit.\n\n  Definition Val := DVal.\n\n  (** Calcul du type d'une valeur d\u00e9fensive. *)\n  Definition v2t (v:Val): VMType :=\n    match v with\n      | Vint i => Tint\n      | Vref (clid,_) => Tref clid\n      | Vrefnull => Trefnull\n      | Error => Top\n      | NonInit => Top\n    end.\n\n  Lemma val_eq_dec : forall v1 v2:Val, {v1=v2}+{v1<>v2}.\n  Proof.\n    intros v1 v2.\n    decide equality.\n    decide equality.\n    decide equality.\n    decide equality.\n    decide equality.\n  Qed.\n\nEnd DefVal.\n\n\n\nModule D (H:Herit).\n\n\n(** \u00c9tats d\u00e9fensifs. *)\n  Module Def := VMDefinition(DefVal)(H).\n  Import DefVal.\n  Include Def.\n  Ltac rename_dvm h th := fail.\n\n  (* Hypothesis renaming stuff from other files + current file.\n     DO NOT REDEFINE IN THIS FILE. Redefine rename_dvm instead. *)\n  Ltac rename_hyp h th ::=\n    match th with\n    | _ => (rename_dvm h th) (* redefine this tactic at will to enrich renaming*)\n    | _ => (Def.rename_vmdef h th) (* renaming from Def *)\n    | _ => (LibHypsNaming.rename_hyp_neg h th) (* basic generic renaming *)\n    end.\n\n  Definition build_flds: ClasseDef -> (Dico.t Val) :=\n    Dico.map \n      (fun t:VMType =>\n         match t with\n         | Tint => Vint 0\n         | Tref id => Vrefnull (** null = 0 *)\n         | Object => Vrefnull (** null = 0 *)\n         | Top => Vrefnull (** Should never happen *)\n         | Trefnull => Vrefnull (** Should never happen *)\n         end).\n\nFunction new (clid:class_id) (heap:Heap) : option (heap_idx * Heap) :=\n    match Dico.find clid allcl with\n    | None => None (** Classe inconnue *)\n    | Some cldef =>\n      let flds:Obj := {| objclass := clid; objfields := build_flds cldef |} in\n      let newhpidx: nat := maxkey heap in\n      Some((S newhpidx), Dico.add (S newhpidx) flds heap)\n    end.\n\n  (** test *)\n  (*\n    Definition obj1:Obj := {| objclass:=1; objfields:=Dico.empty _|}.\n    Definition heap1:Heap := Dico.empty _ .\n    Definition heap2:Heap := Dico.add 1 obj1 heap1.\n    Definition heap3:Heap := Dico.add 2 obj1 heap2.\n    Eval vm_compute in (maxkey heap3).\n    Eval vm_compute in (maxkey heap2). *)\n  (* fin test *)\n\n\n\n  (** * Fonction d'ex\u00e9cution d\u00e9fensive d'*un* bytecode.\n\n     Pas de v\u00e9rif d'overflow sur la pile d'op\u00e9randes. pas de nb\n     n\u00e9gatifs, on ne v\u00e9rifie que le typage et les underflow. *)\n  Definition exec_step (s:State): option State :=\n    let frm:Frame := s.(frame) in\n    let pc: pc_idx := frm.(pc) in\n    let instr_opt := Dico.find pc (frm.(mdef).(instrs)) in\n    match instr_opt with\n    | None => None\n    | Some instr =>\n      match instr with\n      | ret => Some s\n      | Iconst i =>\n        Some {| framestack := s.(framestack); heap := s.(heap);\n                frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                            pc:= pc + 1;\n                            stack:= (Vint i) :: s.(frame).(stack)\n                         |}\n             |}\n      | Iadd =>\n        match s.(frame).(stack) with\n        | Vint i1 :: Vint i2 :: stack' =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef); regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:= (Vint (i1 + i2)) :: stack'\n                           |}\n               |}\n         | nil | _ :: nil => None\n         | _ :: _ => None\n        end\n\n      | Iload ridx =>\n        match Dico.find ridx (s.(frame).(regs)) with\n        | Some (Vint i) =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef); regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:= Vint i :: s.(frame).(stack)\n                           |}\n               |}\n        | Some _ (** Invalid register content *)\n        | None => None (** Bad register number *)\n        end\n\n      | Rload clid ridx =>\n        match Dico.find ridx (s.(frame).(regs)) with\n        | Some (Vref r) =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:= Vref r :: s.(frame).(stack)\n                           |}\n               |}\n        | Some _ (** Invalid register content *)\n        | None => None (** Bad register number *)\n        end\n\n      | Istore ridx =>\n        match s.(frame).(stack) with\n        | Vint i :: stack' =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ;\n                              regs:= Dico.add ridx (Vint i) (s.(frame).(regs));\n                              pc:= pc + 1;\n                              stack:= stack'\n                           |}\n               |}\n        | nil\n        | _ => None (** Stack underflow *)\n        end\n\n      | Rstore clid ridx =>\n        match s.(frame).(stack) with\n        | Vref r :: stack' =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ;\n                              regs:= Dico.add ridx (Vref r) (s.(frame).(regs));\n                              pc:= pc + 1;\n                              stack:= stack'\n                           |}\n               |}\n        | nil => None (** Stack underflow *)\n        | _ => None\n        end\n\n      | Iifle jmp => (** ifeqe *)\n        match s.(frame).(stack) with\n        | (Vint 0) :: stack' => (** = 0  --> jump *)\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              pc:= jmp;\n                              stack:= stack'\n                           |}\n               |}\n        | _ :: stack' => (** <> 0  --> pc+1 *)\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              pc:= pc+1;\n                              stack:= stack'\n                           |}\n               |}\n        | nil => None (** Stack underflow *)\n        end\n\n      | Goto jmp =>\n        Some {| framestack := s.(framestack); heap := s.(heap);\n                frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                            stack:= s.(frame).(stack);\n                            pc:= jmp\n                         |}\n             |}\n\n      | Getfield cl namefld typ =>\n        match s.(frame).(stack) with\n        | (Vint hpidx) :: stack' =>\n          match Dico.find hpidx s.(heap) with\n          | None => None (** adresse inconnue *)\n          | Some {|objclass:= objcl; objfields:= flds |} =>\n            if Nat.eqb objcl cl then\n              match Dico.find namefld flds with\n              | None => None (** Champ de classe inconnu ou pas initialis\u00e9 *)\n              | Some v =>\n                Some {| framestack := s.(framestack); heap := s.(heap);\n                        frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                                    pc:= pc+1;\n                                    stack:= v :: stack'\n                                 |}\n                     |}\n              end\n            else None\n          end\n        | nil => None (** Stack underflow *)\n        | _ => None\n        end\n\n      | Putfield cl namefld typ =>\n        match s.(frame).(stack) with\n        | (Vint hpidx) :: v :: stack' =>\n          match Dico.find hpidx s.(heap) with\n          | None => None (** adresse inconnue, objet non allou\u00e9 *)\n          | Some {| objclass:= objcl; objfields:= flds |} =>\n            if Nat.eqb objcl cl then\n              let newflds := {| objclass:= cl;\n                                objfields:=Dico.add namefld v flds |} in\n              let newheap := Dico.add hpidx newflds s.(heap) in\n              Some {| framestack := s.(framestack);\n                      heap := newheap;\n                      frame := {| mdef:=s.(frame).(mdef) ;\n                                  regs:= s.(frame).(regs);\n                                  pc:= pc+1;\n                                  stack:= stack'\n                               |}\n                   |}\n            else None\n          end\n        | nil | _ :: nil => None (** Stack underflow *)\n        | _ :: _ => None\n        end\n\n      | New clid =>\n        match new clid s.(heap) with\n        | None => None (** Classe inconnue *)\n        | Some (newobj,newhp) =>\n          Some {| framestack := s.(framestack); heap := newhp;\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              stack:= (Vref (clid,newobj)) :: s.(frame).(stack);\n                              pc:= pc+1\n                           |} \n               |}\n\n        end\n      end\n    end.\n\n  Functional Scheme exec_step_ind := Induction for exec_step Sort Prop.\n\n  (** * Tests *)\n\n  Notation \"k --> i , d\" := (Dico.add k i d) (at level 55, right associativity).\n\n  Definition prog:MethodDef :=\n    {| instrs := (0 --> Iload 1 ,\n                  1 --> Istore 2 ,\n                  2 --> ret ,\n                  Dico.empty ) ;\n       argstype :=( Tint :: Tint:: nil);\n       restype := Tint |}.\n\n  Definition startstate:State :=\n    {|\n      framestack := nil;\n      heap := Dico.empty;\n      frame := {|\n                mdef:= prog ;\n                regs:= (0 --> Vint 32 , 1-->Vint 11, Dico.empty );\n                pc:= 0;\n                stack:= nil\n              |}\n    |}.\n\n  Fixpoint exec_n (s : State) (n:nat) {struct n}: option State :=\n    match n with\n    | 0 => Some s\n    | S n' =>\n      match exec_step s with\n      | None => None\n      | Some s' => exec_n s' n'\n      end\n    end.\n  (*\n    Eval simpl in exec_n startstate 1.\n    Eval simpl in exec_n startstate 2.\n    Eval simpl in exec_n startstate 5.\n   *)\n  (* Eval simpl in exec_n (fun x y => false) (Dico.empty _) startstate 2. *)\n\n\n  (** Exemple de preuve tr\u00e8s simple sur la fonction d'ex\u00e9cution: la\n  pile (hormis la m\u00e9thode en cours d'ex\u00e9cution) ne change pas au cours\n  de exec_step. *)\n\n  Lemma essai : forall s x,\n      exec_step s = Some x ->\n      x.(framestack) = s.(framestack).\n  Proof.\n    intros s.\n    functional induction exec_step s;intros ;simpl;\n      try solve [discriminate | inversion H; subst;simpl;reflexivity] .\n  Qed.\n\n\nEnd D.\n\n\n", "meta": {"author": "Fuitudestos", "repo": "ProjetSVP", "sha": "3ab4bfcb9579dafe114a27c388541e1209371c87", "save_path": "github-repos/coq/Fuitudestos-ProjetSVP", "path": "github-repos/coq/Fuitudestos-ProjetSVP/ProjetSVP-3ab4bfcb9579dafe114a27c388541e1209371c87/dvm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.19863872695545307}}
{"text": "Require Import Framework FileDiskLayer FileDiskRefinement.\nRequire Import FD_ORS FileDiskNoninterference. (* FileDiskTS. *)\n\nTheorem ss_AD_read:\n  forall n inum off u u',\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Read inum off))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Read inum off))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' None) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_read.\n    - apply read_simulation.\n    - apply read_simulation.\n    - apply abstract_oracles_exist_wrt_read.\n    - apply abstract_oracles_exist_wrt_read.\n    - apply ORS_read.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_write:\n  forall n inum off u u' v,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Write inum off v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Write inum off v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' None) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_write.\n    - apply write_simulation.\n    - apply write_simulation.\n    - apply abstract_oracles_exist_wrt_write.\n    - apply abstract_oracles_exist_wrt_write.\n    - apply ORS_write.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_extend:\n  forall n inum u u' v,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Extend inum v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Extend inum v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' None) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_extend.\n    - apply extend_simulation.\n    - apply extend_simulation.\n    - apply abstract_oracles_exist_wrt_extend.\n    - apply abstract_oracles_exist_wrt_extend.\n    - apply ORS_extend.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_change_owner:\n  forall n inum u u' v,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (ChangeOwner inum v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (ChangeOwner inum v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' (Some inum)) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_change_owner.\n    - apply change_owner_simulation.\n    - apply change_owner_simulation.\n    - apply abstract_oracles_exist_wrt_change_owner.\n    - apply abstract_oracles_exist_wrt_change_owner.\n    - apply ORS_change_owner.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_create:\n  forall n u u' v,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Create v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Create v))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' None) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_create.\n    - apply create_simulation.\n    - apply create_simulation.\n    - apply abstract_oracles_exist_wrt_create.\n    - apply abstract_oracles_exist_wrt_create.\n    - apply ORS_create.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\n\nTheorem ss_AD_delete:\n  forall n inum u u',\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Delete inum))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Delete inum))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' None) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_delete.\n    - apply delete_simulation.\n    - apply delete_simulation.\n    - apply abstract_oracles_exist_wrt_delete.\n    - apply abstract_oracles_exist_wrt_delete.\n    - apply ORS_delete.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_write_input:\n  forall n inum off u u' v1 v2,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Write inum off v1))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Write inum off v2))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' (Some inum)) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_write_input.\n    - apply write_simulation.\n    - apply write_simulation.\n    - apply abstract_oracles_exist_wrt_write.\n    - apply abstract_oracles_exist_wrt_write.\n    - apply ORS_write_input.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.\n\nTheorem ss_AD_extend_input:\n  forall n inum u u' v1 v2,\n    RDNI_Weak u \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Extend inum v1))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) (Extend inum v2))) \n    (FD.refinement.(Simulation.Definitions.compile) (FDOp.(Op) Recover)) AD_valid_state \n    (AD_related_states u' (Some inum)) (eq u') (authenticated_disk_reboot_list n).\nProof.\n    intros; eapply RDNIW_transfer.\n    - apply RDNI_to_RDNIW; apply ss_FD_extend_input.\n    - apply extend_simulation.\n    - apply extend_simulation.\n    - apply abstract_oracles_exist_wrt_extend.\n    - apply abstract_oracles_exist_wrt_extend.\n    - apply ORS_extend.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\n    - unfold exec_compiled_preserves_validity,\n    refines_valid, FD_valid_state; intros; eauto.\nQed.", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/src/Noninterference/FileDisk/TransferProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3557748866829644, "lm_q1q2_score": 0.19863872314170797}}
{"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(*                           nogreyaccnblackn.v                             *)\n(****************************************************************************)\n\nSection invariant5.\n\nRequire Export accnotfree.\nRequire Export noedgeblacktowhite.\n\nLemma nogrey_accn_imp_blackn_init :\n forall s : state, init_state s -> nogrey_accn_imp_blackn s.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s init H_col n2 acces_s_n2.\nelim init; clear init.\nintros ctls H_mark_col.\nelim H_mark_col; clear H_mark_col.\nintros mark heap; elim mark; clear mark.\nintros mksrt mark; elim acces_s_n2; auto.\nintros n m acces_s_m mksm hsmn.\nabsurd (hp s m n = false); auto.\nrewrite hsmn; discriminate.\nQed.\n\nLemma nogrey_accn_imp_blackn_addedge :\n forall s t : state,\n nogrey_accn_imp_blackn s -> add_edge s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s addedge H_col n2 acces_t_n2.\napply (add_blacks_blackt s t); auto.\napply H_s.\nintro n1; apply (add_notgreyt_notgreys s t); auto.\napply (add_accest_access s t); assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_removeedge :\n forall s t : state,\n nogrey_accn_imp_blackn s -> remove_edge s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s removeedge H_col n2 acces_t_n2.\napply (remove_blacks_blackt s t); auto.\napply H_s.\nintro n1; apply (remove_notgreyt_notgreys s t); auto.\napply (remove_accest_access s t); assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_alloc :\n forall s t : state,\n nogrey_accn_imp_blackn s -> alloc s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s alloc H_col n2 acces_t_n2.\nelim alloc; clear alloc.\nintros ctls ctlt n mksn H_fils mark add; elim mark; clear mark.\nintros mark mktn; elim (eq_dec_node n n2).\nintro neqn2; rewrite <- neqn2; assumption.\nintro ndifn2; rewrite <- (mark n2); auto.\napply H_s.\nintro n1; apply (alloc_notgreyt_notgreys s t); auto.\napply (alloc_add_free_to_rt s t) with (n := n); auto.\nunfold update_color in |- *; auto.\napply (alloc_accest_access s t n); auto.\nunfold update_color in |- *; auto.\nQed.\n\nLemma nogrey_accn_imp_blackn_gccall :\n forall s t : state,\n rt_grey_or_black s ->\n no_edge_black_to_white_bis s ->\n acc_imp_notfree s ->\n nogrey_accn_imp_blackn s -> gc_call s t -> nogrey_accn_imp_blackn t.\n\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t inv1_s inv2_s inv3_s H_s gccall H_col n2 acces_t_n2.\nelim gccall; clear gccall.\nintros ctls ctlt heap mark init; elim init; clear init.\nintros mktrt H_mark_col; absurd (mk t rt = grey); auto.\nintros ctls ctlt heap H_sons; apply (ind t); auto.\napply (rt_grey_or_black_gccall s t); auto.\napply (call_exist_grey s t); assumption.\napply (no_edge_black_to_white_gccall s t); auto.\napply (call_exist_grey s t); auto.\napply (acc_imp_notfree_gccall s t); auto.\napply (call_exist_grey s t); auto.\nintros ctls ctlt heap H_col2 m mksm mark.\napply (updatecolor_blacks_blackt s t) with (m := m); auto.\napply H_s; auto.\nrewrite heap; assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_marknode :\n forall s t : state,\n rt_grey_or_black s ->\n no_edge_black_to_white_bis s ->\n acc_imp_notfree s ->\n nogrey_accn_imp_blackn s -> mark_node s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t inv1_s inv2_s inv3_s H_s marknode H_col n2 acces_t_n2.\napply (ind t); auto.\napply (rt_grey_or_black_marknode s t); assumption.\napply (no_edge_black_to_white_marknode s t); assumption.\napply (acc_imp_notfree_marknode s t); assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_gcstop :\n forall s t : state,\n nogrey_accn_imp_blackn s -> gc_stop s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s gcstop H_col n2 acces_t_n2.\napply (gcstop_blacks_blackt s t); auto.\napply H_s.\nintro n1; apply (gcstop_notgreyt_notgreys s t); auto.\napply (gcstop_accest_access s t); auto.\nQed.\n\nLemma nogrey_accn_imp_blackn_gcfree :\n forall s t : state,\n nogrey_accn_imp_blackn s -> gc_free s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s gcfree H_col n2 acces_t_n2.\napply (gcfree_blacks_blackt s t); auto.\napply H_s.\nelim gcfree; clear gcfree.\nintros ctls ctlt H_col2 heap m mksm mark n1; auto.\napply (gcfree_accest_access s t); assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_gcfree1 :\n forall s t : state,\n sweep_no_greys s ->\n nogrey_accn_imp_blackn s -> gc_free1 s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *; unfold sweep_no_greys in |- *.\nintros s t inv4_s H_s gcfree1 H_col n2 acces_t_n2.\napply (gcfree1_blacks_blackt s t); auto.\napply H_s.\nintro n1; apply inv4_s.\nelim gcfree1; clear gcfree1; auto.\napply (gcfree1_accest_access s t); assumption.\nQed.\n\nLemma nogrey_accn_imp_blackn_gcend :\n forall s t : state,\n nogrey_accn_imp_blackn s -> gc_end s t -> nogrey_accn_imp_blackn t.\n\nunfold nogrey_accn_imp_blackn in |- *.\nintros s t H_s gcend H_col n2 acces_t_n2.\napply (gcend_blacks_blackt s t); auto.\napply H_s.\nintro n1; apply (gcend_notgreyt_notgreys s t); auto.\napply (gcend_accest_access s t); auto.\nQed.\n\nEnd invariant5.\n\nHint Immediate nogrey_accn_imp_blackn_addedge.\nHint Immediate nogrey_accn_imp_blackn_removeedge.\nHint Immediate nogrey_accn_imp_blackn_alloc.\nHint Immediate nogrey_accn_imp_blackn_gccall.\nHint Immediate nogrey_accn_imp_blackn_marknode.\nHint Immediate nogrey_accn_imp_blackn_gcstop.\nHint Immediate nogrey_accn_imp_blackn_gcfree.\nHint Immediate nogrey_accn_imp_blackn_gcfree1.\nHint Immediate nogrey_accn_imp_blackn_gcend.\nHint Immediate imp1.\n\n\n\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/nogreyaccnblackn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19863871932796276}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, Coll\u00e8ge 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\nRequire Import Coqlib Maps Errors.\nRequire Import AST Integers Floats Values Memory Globalenvs Events Smallstep.\nRequire Import Cminor.\nRequire Import Unityping.\nRequire Import sflib.\n\nLocal Open Scope string_scope.\nLocal Open Scope error_monad_scope.\n\n(** * Type inference algorithm *)\n\nDefinition type_constant (c: constant) : typ :=\n  match c with\n  | Ointconst _ => Tint\n  | Ofloatconst _ => Tfloat\n  | Osingleconst _ => Tsingle\n  | Olongconst _ => Tlong\n  | Oaddrsymbol _ _ => Tptr\n  | Oaddrstack _ => Tptr\n  end.\n\nDefinition type_unop (op: unary_operation) : typ * typ :=\n  match op with\n  | Ocast8unsigned | Ocast8signed | Ocast16unsigned | Ocast16signed\n  | Onegint | Onotint => (Tint, Tint)\n  | Onegf | Oabsf => (Tfloat, Tfloat)\n  | Onegfs | Oabsfs => (Tsingle, Tsingle)\n  | Osingleoffloat => (Tfloat, Tsingle)\n  | Ofloatofsingle => (Tsingle, Tfloat)\n  | Ointoffloat | Ointuoffloat => (Tfloat, Tint)\n  | Ofloatofint | Ofloatofintu => (Tint, Tfloat)\n  | Ointofsingle | Ointuofsingle => (Tsingle, Tint)\n  | Osingleofint | Osingleofintu => (Tint, Tsingle)\n  | Onegl | Onotl => (Tlong, Tlong)\n  | Ointoflong => (Tlong, Tint)\n  | Olongofint | Olongofintu => (Tint, Tlong)\n  | Olongoffloat | Olonguoffloat => (Tfloat, Tlong)\n  | Ofloatoflong | Ofloatoflongu => (Tlong, Tfloat)\n  | Olongofsingle | Olonguofsingle => (Tsingle, Tlong)\n  | Osingleoflong | Osingleoflongu => (Tlong, Tsingle)\n  end.\n\nDefinition type_binop (op: binary_operation) : typ * typ * typ :=\n  match op with\n  | Oadd  | Osub  | Omul  | Odiv  | Odivu  | Omod  | Omodu\n  | Oand  | Oor   | Oxor  | Oshl  | Oshr   | Oshru => (Tint, Tint, Tint)\n  | Oaddf | Osubf | Omulf | Odivf  => (Tfloat, Tfloat, Tfloat)\n  | Oaddfs| Osubfs| Omulfs| Odivfs => (Tsingle, Tsingle, Tsingle)\n  | Oaddl | Osubl | Omull | Odivl | Odivlu | Omodl | Omodlu\n  | Oandl | Oorl  | Oxorl => (Tlong, Tlong, Tlong)\n  | Oshll | Oshrl | Oshrlu => (Tlong, Tint, Tlong)\n  | Ocmp _ | Ocmpu _ => (Tint, Tint, Tint)\n  | Ocmpf _ => (Tfloat, Tfloat, Tint)\n  | Ocmpfs _ => (Tsingle, Tsingle, Tint)\n  | Ocmpl _ | Ocmplu _ => (Tlong, Tlong, Tint)\n  end.\n\nModule RTLtypes <: TYPE_ALGEBRA.\n\nDefinition t := typ.\nDefinition eq := typ_eq.\nDefinition default := Tint.\n\nEnd RTLtypes.\n\nModule S := UniSolver(RTLtypes).\n\nDefinition expect (e: S.typenv) (t1 t2: typ) : res S.typenv :=\n  if typ_eq t1 t2 then OK e else Error (msg \"type mismatch\").\n\nFixpoint type_expr (e: S.typenv) (a: expr) (t: typ) : res S.typenv :=\n  match a with\n  | Evar id => S.set e id t\n  | Econst c => expect e (type_constant c) t\n  | Eunop op a1 =>\n      let '(targ1, tres) := type_unop op in\n      do e1 <- type_expr e a1 targ1;\n      expect e1 tres t\n  | Ebinop op a1 a2 =>\n      let '(targ1, targ2, tres) := type_binop op in\n      do e1 <- type_expr e a1 targ1;\n      do e2 <- type_expr e1 a2 targ2;\n      expect e2 tres t\n  | Eload chunk a1 =>\n      do e1 <- type_expr e a1 Tptr;\n      expect e1 (type_of_chunk chunk) t\n  end.\n\nFixpoint type_exprlist (e: S.typenv) (al: list expr) (tl: list typ) : res S.typenv :=\n  match al, tl with\n  | nil, nil => OK e\n  | a :: al, t :: tl => do e1 <- type_expr e a t; type_exprlist e1 al tl\n  | _, _ => Error (msg \"arity mismatch\")\n  end.\n\nDefinition type_assign (e: S.typenv) (id: ident) (a: expr) : res S.typenv :=\n  match a with\n  | Evar id' =>\n      do (changed, e1) <- S.move e id id'; OK e1\n  | Econst c =>\n      S.set e id (type_constant c)\n  | Eunop op a1 =>\n      let '(targ1, tres) := type_unop op in\n      do e1 <- type_expr e a1 targ1;\n      S.set e1 id tres\n  | Ebinop op a1 a2 =>\n      let '(targ1, targ2, tres) := type_binop op in\n      do e1 <- type_expr e a1 targ1;\n      do e2 <- type_expr e1 a2 targ2;\n      S.set e2 id tres\n  | Eload chunk a1 =>\n      do e1 <- type_expr e a1 Tptr;\n      S.set e1 id (type_of_chunk chunk)\n  end.\n\nDefinition opt_set (e: S.typenv) (optid: option ident) (ty: typ) : res S.typenv :=\n  match optid with\n  | None => OK e\n  | Some id => S.set e id ty\n  end.\n\nFixpoint type_stmt (tret: option typ) (e: S.typenv) (s: stmt) : res S.typenv :=\n  match s with\n  | Sskip => OK e\n  | Sassign id a => type_assign e id a\n  | Sstore chunk a1 a2 =>\n      do e1 <- type_expr e a1 Tptr; type_expr e1 a2 (type_of_chunk chunk)\n  | Scall optid sg fn args =>\n      do e1 <- type_expr e fn Tptr;\n      do e2 <- type_exprlist e1 args sg.(sig_args);\n      opt_set e2 optid (proj_sig_res sg)\n  | Stailcall sg fn args =>\n      assertion (opt_typ_eq sg.(sig_res) tret);\n      do e1 <- type_expr e fn Tptr;\n      type_exprlist e1 args sg.(sig_args)\n  | Sbuiltin optid ef args =>\n      let sg := ef_sig ef in\n      do e1 <- type_exprlist e args sg.(sig_args);\n      opt_set e1 optid (proj_sig_res sg)\n  | Sseq s1 s2 =>\n      do e1 <- type_stmt tret e s1; type_stmt tret e1 s2\n  | Sifthenelse a s1 s2 =>\n      do e1 <- type_expr e a Tint;\n      do e2 <- type_stmt tret e1 s1;\n      type_stmt tret e2 s2\n  | Sloop s1 =>\n      type_stmt tret e s1\n  | Sblock s1 =>\n      type_stmt tret e s1\n  | Sexit n =>\n      OK e\n  | Sswitch sz a tbl dfl =>\n      type_expr e a (if sz then Tlong else Tint)\n  | Sreturn opta =>\n      match opta, tret with\n      | None, _ => OK e\n      | Some a, Some t => type_expr e a t\n      | _, _ => Error (msg \"inconsistent return\")\n      end\n  | Slabel lbl s1 =>\n      type_stmt tret e s1\n  | Sgoto lbl =>\n      OK e\n  end.\n\nDefinition typenv := ident -> typ.\n\nDefinition type_function (f: function) : res typenv :=\n  do e1 <- S.set_list S.initial f.(fn_params) f.(fn_sig).(sig_args);\n  do e2 <- type_stmt f.(fn_sig).(sig_res) e1 f.(fn_body);\n  S.solve e2.\n\n(** * Relational specification of the type system *)\n\nSection SPEC.\n\nVariable env: ident -> typ.\nVariable tret: option typ.\n\nInductive wt_expr: expr -> typ -> Prop :=\n  | wt_Evar: forall id,\n      wt_expr (Evar id) (env id)\n  | wt_Econst: forall c,\n      wt_expr (Econst c) (type_constant c)\n  | wt_Eunop: forall op a1 targ1 tres,\n      type_unop op = (targ1, tres) ->\n      wt_expr a1 targ1 ->\n      wt_expr (Eunop op a1) tres\n  | wt_Ebinop: forall op a1 a2 targ1 targ2 tres,\n      type_binop op = (targ1, targ2, tres) ->\n      wt_expr a1 targ1 -> wt_expr a2 targ2 ->\n      wt_expr (Ebinop op a1 a2) tres\n  | wt_Eload: forall chunk a1,\n      wt_expr a1 Tptr ->\n      wt_expr (Eload chunk a1) (type_of_chunk chunk).\n\nDefinition wt_opt_assign (optid: option ident) (optty: option typ) : Prop :=\n  match optid with\n  | Some id => match optty with Some ty => ty | None => Tint end = env id\n  | _ => True\n  end.\n\nInductive wt_stmt: stmt -> Prop :=\n  | wt_Sskip:\n      wt_stmt Sskip\n  | wt_Sassign: forall id a,\n      wt_expr a (env id) ->\n      wt_stmt (Sassign id a)\n  | wt_Sstore: forall chunk a1 a2,\n      wt_expr a1 Tptr -> wt_expr a2 (type_of_chunk chunk) ->\n      wt_stmt (Sstore chunk a1 a2)\n  | wt_Scall: forall optid sg a1 al,\n      wt_expr a1 Tptr -> list_forall2 wt_expr al sg.(sig_args) ->\n      wt_opt_assign optid sg.(sig_res) ->\n      wt_stmt (Scall optid sg a1 al)\n  | wt_Stailcall: forall sg a1 al,\n      wt_expr a1 Tptr -> list_forall2 wt_expr al sg.(sig_args) ->\n      sg.(sig_res) = tret ->\n      wt_stmt (Stailcall sg a1 al)\n  | wt_Sbuiltin: forall optid ef al,\n      list_forall2 wt_expr al (ef_sig ef).(sig_args) ->\n      wt_opt_assign optid (ef_sig ef).(sig_res) ->\n      wt_stmt (Sbuiltin optid ef al)\n  | wt_Sseq: forall s1 s2,\n      wt_stmt s1 -> wt_stmt s2 ->\n      wt_stmt (Sseq s1 s2)\n  | wt_Sifthenelse: forall a s1 s2,\n      wt_expr a Tint -> wt_stmt s1 -> wt_stmt s2 ->\n      wt_stmt (Sifthenelse a s1 s2)\n  | wt_Sloop: forall s1,\n      wt_stmt s1 ->\n      wt_stmt (Sloop s1)\n  | wt_Sblock: forall s1,\n      wt_stmt s1 ->\n      wt_stmt (Sblock s1)\n  | wt_Sexit: forall n,\n      wt_stmt (Sexit n)\n  | wt_Sswitch: forall (sz: bool) a tbl dfl,\n      wt_expr a (if sz then Tlong else Tint) ->\n      wt_stmt (Sswitch sz a tbl dfl)\n  | wt_Sreturn_none:\n      wt_stmt (Sreturn None)\n  | wt_Sreturn_some: forall a t,\n      tret = Some t -> wt_expr a t ->\n      wt_stmt (Sreturn (Some a))\n  | wt_Slabel: forall lbl s1,\n      wt_stmt s1 ->\n      wt_stmt (Slabel lbl s1)\n  | wt_Sgoto: forall lbl,\n      wt_stmt (Sgoto lbl).\n\nEnd SPEC.\n\nInductive wt_function (env: typenv) (f: function) : Prop :=\n  wt_function_intro:\n    type_function f = OK env ->     (**r to ensure uniqueness of [env] *)\n    List.map env f.(fn_params) = f.(fn_sig).(sig_args) ->\n    wt_stmt env f.(fn_sig).(sig_res) f.(fn_body) ->\n    wt_function env f.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_internal: forall env f,\n      wt_function env f ->\n      wt_fundef (Internal f)\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef).\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, Gfun f) (prog_defs p) -> wt_fundef f.\n\n(** * Soundness of type inference *)\n\nLemma expect_incr: forall te e t1 t2 e',\n  expect e t1 t2 = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold expect; intros. destruct (typ_eq t1 t2); inv H; auto.\nQed.\nHint Resolve expect_incr: ty.\n\nLemma expect_sound: forall e t1 t2 e',\n  expect e t1 t2 = OK e' -> t1 = t2.\nProof.\n  unfold expect; intros. destruct (typ_eq t1 t2); inv H; auto.\nQed.\n\nLemma type_expr_incr: forall te a t e e',\n  type_expr e a t = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  induction a; simpl; intros until e'; intros T SAT; try (monadInv T); eauto with ty.\n- destruct (type_unop u) as [targ1 tres]; monadInv T; eauto with ty.\n- destruct (type_binop b) as [[targ1 targ2] tres]; monadInv T; eauto with ty.\nQed.\nHint Resolve type_expr_incr: ty.\n\nLemma type_expr_sound: forall te a t e e',\n    type_expr e a t = OK e' -> S.satisf te e' -> wt_expr te a t.\nProof.\n  induction a; simpl; intros until e'; intros T SAT; try (monadInv T).\n- erewrite <- S.set_sound by eauto. constructor.\n- erewrite <- expect_sound by eauto. constructor.\n- destruct (type_unop u) as [targ1 tres] eqn:TU; monadInv T.\n  erewrite <- expect_sound by eauto. econstructor; eauto with ty.\n- destruct (type_binop b) as [[targ1 targ2] tres] eqn:TB; monadInv T.\n  erewrite <- expect_sound by eauto. econstructor; eauto with ty.\n- erewrite <- expect_sound by eauto. econstructor; eauto with ty.\nQed.\n\nLemma type_exprlist_incr: forall te al tl e e',\n  type_exprlist e al tl = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  induction al; destruct tl; simpl; intros until e'; intros T SAT; monadInv T; eauto with ty.\nQed.\nHint Resolve type_exprlist_incr: ty.\n\nLemma type_exprlist_sound: forall te al tl e e',\n    type_exprlist e al tl = OK e' -> S.satisf te e' -> list_forall2 (wt_expr te) al tl.\nProof.\n  induction al; destruct tl; simpl; intros until e'; intros T SAT; monadInv T.\n- constructor.\n- constructor; eauto using type_expr_sound with ty.\nQed.\n\nLemma type_assign_incr: forall te id a e e',\n    type_assign e id a = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  induction a; simpl; intros until e'; intros T SAT; try (monadInv T); eauto with ty.\n- destruct (type_unop u) as [targ1 tres]; monadInv T; eauto with ty.\n- destruct (type_binop b) as [[targ1 targ2] tres]; monadInv T; eauto with ty.\nQed.\nHint Resolve type_assign_incr: ty.\n\nLemma type_assign_sound: forall te id a e e',\n    type_assign e id a = OK e' -> S.satisf te e' -> wt_expr te a (te id).\nProof.\n  induction a; simpl; intros until e'; intros T SAT; try (monadInv T).\n- erewrite S.move_sound by eauto. constructor.\n- erewrite S.set_sound by eauto. constructor.\n- destruct (type_unop u) as [targ1 tres] eqn:TU; monadInv T.\n  erewrite S.set_sound by eauto. econstructor; eauto using type_expr_sound with ty.\n- destruct (type_binop b) as [[targ1 targ2] tres] eqn:TB; monadInv T.\n  erewrite S.set_sound by eauto. econstructor; eauto using type_expr_sound with ty.\n- erewrite S.set_sound by eauto. econstructor; eauto using type_expr_sound with ty.\nQed.\n\nLemma opt_set_incr: forall te optid optty e e',\n    opt_set e optid optty = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold opt_set; intros. destruct optid, optty; try (monadInv H); eauto with ty.\nQed.\nHint Resolve opt_set_incr: ty.\n\nLemma opt_set_sound: forall te optid sg e e',\n    opt_set e optid (proj_sig_res sg) = OK e' -> S.satisf te e' ->\n    wt_opt_assign te optid sg.(sig_res).\nProof.\n  unfold opt_set; intros; red. destruct optid.\n- erewrite S.set_sound by eauto. auto.\n- inv H. auto.\nQed.\n\nLemma type_stmt_incr: forall te tret s e e',\n    type_stmt tret e s = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  induction s; simpl; intros e1 e2 T SAT; try (monadInv T); eauto with ty.\n- destruct tret, o; try (monadInv T); eauto with ty.\nQed.\nHint Resolve type_stmt_incr: ty.\n\nLemma type_stmt_sound: forall te tret s e e',\n    type_stmt tret e s = OK e' -> S.satisf te e' -> wt_stmt te tret s.\nProof.\n  induction s; simpl; intros e1 e2 T SAT; try (monadInv T).\n- constructor.\n- constructor; eauto using type_assign_sound.\n- constructor; eauto using type_expr_sound with ty.\n- constructor; eauto using type_expr_sound, type_exprlist_sound, opt_set_sound with ty.\n- constructor; eauto using type_expr_sound, type_exprlist_sound with ty.\n- constructor; eauto using type_exprlist_sound, opt_set_sound with ty.\n- constructor; eauto with ty.\n- constructor; eauto using type_expr_sound with ty.\n- constructor; eauto.\n- constructor; eauto.\n- constructor.\n- constructor; eauto using type_expr_sound with ty.\n- destruct tret, o; try (monadInv T); econstructor; eauto using type_expr_sound with ty.\n- constructor; eauto.\n- constructor.\nQed.\n\nTheorem type_function_sound: forall f env,\n  type_function f = OK env -> wt_function env f.\nProof.\n  intros. generalize H; unfold type_function; intros T; monadInv T.\n  assert (S.satisf env x0) by (apply S.solve_sound; auto).\n  constructor; eauto using S.set_list_sound, type_stmt_sound with ty.\nQed.\n\n(** * Semantic soundness of the type system *)\n\nDefinition wt_env (env: typenv) (e: Cminor.env) : Prop :=\n  forall id v, e!id = Some v -> Val.has_type v (env id).\n\nDefinition def_env (f: function) (e: Cminor.env) : Prop :=\n  forall id, In id f.(fn_params) \\/ In id f.(fn_vars) -> exists v, e!id = Some v.\n\nInductive wt_cont_call: cont -> option typ -> Prop :=\n  | wt_cont_Kstop: forall ty,\n      wt_cont_call Kstop ty\n  | wt_cont_Kcall: forall optid f sp e k tret env\n        (WT_FN: wt_function env f)\n        (WT_CONT: wt_cont env f.(fn_sig).(sig_res) k)\n        (WT_ENV: wt_env env e)\n        (DEF_ENV: def_env f e)\n        (WT_DEST: wt_opt_assign env optid tret),\n      wt_cont_call (Kcall optid f sp e k) tret\n\nwith wt_cont: typenv -> option typ -> cont -> Prop :=\n  | wt_cont_Kseq: forall env tret s k,\n      wt_stmt env tret s ->\n      wt_cont env tret k ->\n      wt_cont env tret (Kseq s k)\n  | wt_cont_Kblock: forall env tret k,\n      wt_cont env tret k ->\n      wt_cont env tret (Kblock k)\n  | wt_cont_other: forall env tret k,\n      wt_cont_call k tret ->\n      wt_cont env tret k.\n\nInductive wt_state: state -> Prop :=\n  | wt_normal_state: forall f s k sp e m env\n        (WT_FN: wt_function env f)\n        (WT_STMT: wt_stmt env f.(fn_sig).(sig_res) s)\n        (WT_CONT: wt_cont env f.(fn_sig).(sig_res) k)\n        (WT_ENV: wt_env env e)\n        (DEF_ENV: def_env f e),\n      wt_state (State f s k sp e m)\n  | wt_call_state: forall fptr sg args k m\n        (* (WT_FD: wt_fundef f) *)\n        (WT_ARGS: Val.has_type_list args sg.(sig_args))\n        (WT_CONT: wt_cont_call k sg.(sig_res)),\n      wt_state (Callstate fptr sg args k m)\n  | wt_return_state: forall v k m tret\n        (WT_RES: Val.has_type v (match tret with None => Tint | Some t => t end))\n        (WT_CONT: wt_cont_call k tret),\n      wt_state (Returnstate v k m).\n\nLemma wt_is_call_cont:\n  forall env tret k, wt_cont env tret k -> is_call_cont k -> wt_cont_call k tret.\nProof.\n  destruct 1; intros ICC; contradiction || auto.\nQed.\n\nLemma call_cont_wt:\n  forall env tret k, wt_cont env tret k -> wt_cont_call (call_cont k) tret.\nProof.\n  induction 1; simpl; auto. inversion H; subst; auto.\nQed.\n\nLemma wt_env_assign: forall env id e v,\n  wt_env env e -> Val.has_type v (env id) -> wt_env env (PTree.set id v e).\nProof.\n  intros; red; intros. rewrite PTree.gsspec in H1; destruct (peq id0 id).\n- congruence.\n- auto.\nQed.\n\nLemma def_env_assign: forall f e id v,\n  def_env f e -> def_env f (PTree.set id v e).\nProof.\n  intros; red; intros i IN. rewrite PTree.gsspec. destruct (peq i id).\n  exists v; auto.\n  auto.\nQed.\n\nLemma wt_env_set_params: forall env il vl,\n  Val.has_type_list vl (map env il) -> wt_env env (set_params vl il).\nProof.\n  induction il as [ | i il]; destruct vl as [ | vl]; simpl; intros; try contradiction.\n- red; intros. rewrite PTree.gempty in H0; discriminate.\n- destruct H. apply wt_env_assign; auto.\nQed.\n\nLemma def_set_params: forall id il vl,\n  In id il -> exists v, PTree.get id (set_params vl il) = Some v.\nProof.\n  induction il as [ | i il]; simpl; intros.\n- contradiction.\n- destruct vl as [ | v vl]; rewrite PTree.gsspec; destruct (peq id i).\n  econstructor; eauto.\n  apply IHil; intuition congruence.\n  econstructor; eauto.\n  apply IHil; intuition congruence.\nQed.\n\nLemma wt_env_set_locals: forall env il e,\n  wt_env env e -> wt_env env (set_locals il e).\nProof.\n  induction il as [ | i il]; simpl; intros.\n- auto.\n- apply wt_env_assign; auto. exact I.\nQed.\n\nLemma def_set_locals: forall id il e,\n  (exists v, PTree.get id e = Some v) \\/ In id il ->\n  exists v, PTree.get id (set_locals il e) = Some v.\nProof.\n  induction il as [ | i il]; simpl; intros.\n- tauto.\n- rewrite PTree.gsspec; destruct (peq id i).\n  econstructor; eauto.\n  apply IHil; intuition congruence.\nQed.\n\nLemma wt_find_label: forall env tret lbl s k,\n  wt_stmt env tret s -> wt_cont env tret k ->\n  match find_label lbl s k with\n  | Some (s', k') => wt_stmt env tret s' /\\ wt_cont env tret k'\n  | None => True\n  end.\nProof.\n  induction s; intros k WS WK; simpl; auto.\n- inv WS. assert (wt_cont env tret (Kseq s2 k)) by (constructor; auto).\n  specialize (IHs1 _ H1 H). destruct (find_label lbl s1 (Kseq s2 k)).\n  auto. apply IHs2; auto.\n- inv WS. specialize (IHs1 _ H3 WK). destruct (find_label lbl s1 k).\n  auto. apply IHs2; auto.\n- inversion WS; subst. apply IHs; auto. constructor; auto.\n- inv WS. apply IHs; auto. constructor; auto.\n- inv WS. destruct (ident_eq lbl l). auto. apply IHs; auto.\nQed.\n\nSection SUBJECT_REDUCTION.\n\nVariable p: program.\n\nHypothesis wt_p: wt_program p.\n\nVariable se: Senv.t.\nVariable ge: genv.\n\nHypothesis CONTAINED: forall fptr f\n    (FINDF: Genv.find_funct ge fptr = Some f),\n    exists i, In (i, Gfun f) (prog_defs p).\n\nLtac VHT :=\n  match goal with\n  | [ |- Val.has_type (if Archi.ptr64 then _ else _) _] => unfold Val.has_type; destruct Archi.ptr64 eqn:?; VHT\n  | [ |- Val.has_type (match ?v with _ => _ end) _] => destruct v; VHT\n  | [ |- Val.has_type (Vptr _ _) Tptr ] => apply Val.Vptr_has_type\n  | [ |- Val.has_type _ _ ] => exact I\n  | [ |- Val.has_type (?f _ _ _ _ _) _ ] => unfold f; VHT\n  | [ |- Val.has_type (?f _ _ _ _) _ ] => unfold f; VHT\n  | [ |- Val.has_type (?f _ _) _ ] => unfold f; VHT\n  | [ |- Val.has_type (?f _ _ _) _ ] => unfold f; VHT\n  | [ |- Val.has_type (?f _) _ ] => unfold f; VHT\n  | [ |- True ] => exact I\n  | [ |- ?x = ?x ] => reflexivity\n  | _ => idtac\n  end.\n\nLtac VHT' :=\n  match goal with\n  | [ H: None = Some _ |- _ ] => discriminate\n  | [ H: Some _ = Some _ |- _ ] => inv H; VHT\n  | [ H: match ?x with _ => _ end = Some _ |- _ ] => destruct x; VHT'\n  | [ H: ?f _ _ _ _ = Some _ |- _ ] => unfold f in H; VHT'\n  | [ H: ?f _ _ _ = Some _ |- _ ] => unfold f in H; VHT'\n  | [ H: ?f _ _ = Some _ |- _ ] => unfold f in H; VHT'\n  | [ H: ?f _ = Some _ |- _ ] => unfold f in H; VHT'\n  | _ => idtac\n  end.\n\nLemma type_constant_sound: forall sp cst v,\n  eval_constant ge sp cst = Some v ->\n  Val.has_type v (type_constant cst).\nProof.\n  intros until v; intros EV. destruct cst; simpl in *; inv EV; VHT.\nQed.\n\nLemma type_unop_sound: forall op v1 v,\n  eval_unop op v1 = Some v -> Val.has_type v (snd (type_unop op)).\nProof.\n  unfold eval_unop; intros op v1 v EV; destruct op; simpl; VHT'.\nQed.\n\nLemma type_binop_sound: forall op v1 v2 m v,\n  eval_binop op v1 v2 m = Some v -> Val.has_type v (snd (type_binop op)).\nProof.\n  unfold eval_binop; intros op v1 v2 m v EV; destruct op; simpl; VHT';\n  destruct (eq_block b b0); VHT.\nQed.\n\nLemma wt_eval_expr: forall env sp e m a v,\n  eval_expr ge sp e m a v ->\n  forall t,\n  wt_expr env a t ->\n  wt_env env e ->\n  Val.has_type v t.\nProof.\n  induction 1; intros t WT ENV.\n- inv WT. apply ENV; auto.\n- inv WT. eapply type_constant_sound; eauto.\n- inv WT. replace t with (snd (type_unop op)) by (rewrite H3; auto). eapply type_unop_sound; eauto.\n- inv WT. replace t with (snd (type_binop op)) by (rewrite H5; auto). eapply type_binop_sound; eauto.\n- inv WT. destruct vaddr; try discriminate. eapply Mem.load_type; eauto.\nQed.\n\nLemma wt_eval_exprlist: forall env sp e m al vl,\n  eval_exprlist ge sp e m al vl ->\n  forall tl,\n  list_forall2 (wt_expr env) al tl ->\n  wt_env env e ->\n  Val.has_type_list vl tl.\nProof.\n  induction 1; intros tl WT ENV; inv WT; simpl.\n- auto.\n- split. eapply wt_eval_expr; eauto. eauto.\nQed.\n\nLemma wt_find_funct: forall v fd,\n  Genv.find_funct ge v = Some fd -> wt_fundef fd.\nProof.\n  intros. exploit CONTAINED; eauto. i; des. eapply wt_p; eauto.\nQed.\n\nLemma subject_reduction:\n  forall st1 t st2, step se ge st1 t st2 ->\n  forall (WT: wt_state st1), wt_state st2.\nProof.\n  destruct 1; intros; inv WT.\n- inv WT_CONT. econstructor; eauto. inv H.\n- inv WT_CONT. econstructor; eauto. inv H.\n- econstructor; eauto using wt_is_call_cont. exact I.\n- inv WT_STMT. econstructor; eauto using wt_Sskip.\n  apply wt_env_assign; auto. eapply wt_eval_expr; eauto.\n  apply def_env_assign; auto.\n- econstructor; eauto using wt_Sskip.\n- inv WT_STMT. econstructor; eauto.\n  (* eapply wt_find_funct; eauto. *)\n  eapply wt_eval_exprlist; eauto.\n  econstructor; eauto.\n- inv WT_STMT. econstructor; eauto.\n  (* eapply wt_find_funct; eauto. *)\n  eapply wt_eval_exprlist; eauto.\n  rewrite H9; eapply call_cont_wt; eauto.\n- inv WT_STMT. exploit external_call_well_typed; eauto. intros TRES.\n  econstructor; eauto using wt_Sskip.\n  unfold proj_sig_res in TRES; red in H5.\n  destruct optid. rewrite H5 in TRES. apply wt_env_assign; auto. assumption.\n  destruct optid. apply def_env_assign; auto. assumption.\n- inv WT_STMT. econstructor; eauto. econstructor; eauto.\n- inv WT_STMT. destruct b; econstructor; eauto.\n- inv WT_STMT. econstructor; eauto. econstructor; eauto. constructor; auto.\n- inv WT_STMT. econstructor; eauto. econstructor; eauto.\n- inv WT_CONT. econstructor; eauto. inv H.\n- inv WT_CONT. econstructor; eauto using wt_Sskip. inv H.\n- inv WT_CONT. econstructor; eauto using wt_Sexit. inv H.\n- econstructor; eauto using wt_Sexit.\n- inv WT_STMT. econstructor; eauto using call_cont_wt. exact I.\n- inv WT_STMT. econstructor; eauto using call_cont_wt.\n  rewrite H2. eapply wt_eval_expr; eauto.\n- inv WT_STMT. econstructor; eauto.\n- inversion WT_FN; subst.\n  assert (WT_CK: wt_cont env (sig_res (fn_sig f)) (call_cont k)).\n  { constructor. eapply call_cont_wt; eauto. }\n  generalize (wt_find_label _ _ lbl _ _ H2 WT_CK).\n  rewrite H. intros [WT_STMT' WT_CONT']. econstructor; eauto.\n- exploit wt_find_funct; eauto. intro WT_FD.\n  inv WT_FD. inversion H1; subst. econstructor; eauto.\n  constructor; auto.\n  apply wt_env_set_locals. apply wt_env_set_params. rewrite H2; auto.\n  red; intros. apply def_set_locals. destruct H4; auto. left; apply def_set_params; auto.\n- exploit external_call_well_typed; eauto. unfold proj_sig_res. simpl in *. intros.\n  econstructor; eauto.\n- inv WT_CONT. econstructor; eauto using wt_Sskip.\n  red in WT_DEST.\n  destruct optid. rewrite WT_DEST in WT_RES. apply wt_env_assign; auto. assumption.\n  destruct optid. apply def_env_assign; auto. assumption.\nQed.\n\nLemma subject_reduction_star:\n  forall st1 t st2, star step se ge st1 t st2 ->\n  forall (WT: wt_state st1), wt_state st2.\nProof.\n  induction 1; eauto using subject_reduction.\nQed.\n\nLemma wt_initial_state:\n  forall S, initial_state p S -> wt_state S.\nProof.\n  intros. inv H. constructor. ss. ss. econs; eauto.\nQed.\n\nEnd SUBJECT_REDUCTION.\n\n(** * Safe expressions *)\n\n(** Function parameters and declared local variables are always defined\n  throughout the execution of a function.  The following [known_idents]\n  data structure represents the set of those variables, with efficient membership. *)\n\nDefinition known_idents := PTree.t unit.\n\nDefinition is_known (ki: known_idents) (id: ident) :=\n  match ki!id with Some _ => true | None => false end.\n\nDefinition known_id (f: function) : known_idents :=\n  let add (ki: known_idents) (id: ident) := PTree.set id tt ki in\n  List.fold_left add f.(fn_vars)\n      (List.fold_left add f.(fn_params) (PTree.empty unit)).\n\n(** A Cminor expression is safe if it always evaluates to a value,\n    never causing a run-time error. *)\n\nDefinition safe_unop (op: unary_operation) : bool :=\n  match op with\n  | Ointoffloat | Ointuoffloat | Ofloatofint | Ofloatofintu => false\n  | Ointofsingle | Ointuofsingle | Osingleofint | Osingleofintu => false\n  | Olongoffloat | Olonguoffloat | Ofloatoflong | Ofloatoflongu => false\n  | Olongofsingle | Olonguofsingle | Osingleoflong | Osingleoflongu => false\n  | _ => true\n  end.\n\nDefinition safe_binop (op: binary_operation) : bool :=\n  match op with\n  | Odiv | Odivu | Omod | Omodu => false\n  | Odivl | Odivlu | Omodl | Omodlu => false\n  | Ocmpl _ | Ocmplu _ => false\n  | _ => true\n  end.\n\nFixpoint safe_expr (ki: known_idents) (a: expr) : bool :=\n  match a with\n  | Evar v => is_known ki v\n  | Econst c => true\n  | Eunop op e1 => safe_unop op && safe_expr ki e1\n  | Ebinop op e1 e2 => safe_binop op && safe_expr ki e1 && safe_expr ki e2\n  | Eload chunk e => false\n  end.\n\n(** Soundness of [known_id]. *)\n\nLemma known_id_sound_1:\n  forall f id x, (known_id f)!id = Some x -> In id f.(fn_params) \\/ In id f.(fn_vars).\nProof.\n  unfold known_id.\n  set (add := fun (ki: known_idents) (id: ident) => PTree.set id tt ki).\n  intros.\n  assert (REC: forall l ki, (fold_left add l ki)!id = Some x -> In id l \\/ ki!id = Some x).\n  { induction l as [ | i l ]; simpl; intros.\n    - auto.\n    - apply IHl in H0. destruct H0; auto. unfold add in H0; rewrite PTree.gsspec in H0.\n      destruct (peq id i); auto. }\n  apply REC in H. destruct H; auto. apply REC in H. destruct H; auto.\n  rewrite PTree.gempty in H; discriminate.\nQed.\n\nLemma known_id_sound_2:\n  forall f id, is_known (known_id f) id = true -> In id f.(fn_params) \\/ In id f.(fn_vars).\nProof.\n  unfold is_known; intros. destruct (known_id f)!id eqn:E; try discriminate.\n  eapply known_id_sound_1; eauto.\nQed.\n\n(** Expressions that satisfy [safe_expr] always evaluate to a value. *)\n\nLemma eval_safe_expr:\n  forall ge f sp e m a,\n  def_env f e ->\n  safe_expr (known_id f) a = true ->\n  exists v, eval_expr ge sp e m a v.\nProof.\n  induction a; simpl; intros.\n  - apply known_id_sound_2 in H0.\n    destruct (H i H0) as [v E].\n    exists v; constructor; auto.\n  - destruct (eval_constant ge sp c) as [v|] eqn:E.\n    exists v; constructor; auto.\n    destruct c; try discriminate.\n  - InvBooleans. destruct IHa as [v1 E1]; auto.\n    destruct (eval_unop u v1) as [v|] eqn:E.\n    exists v; econstructor; eauto.\n    destruct u; discriminate.\n  - InvBooleans.\n    destruct IHa1 as [v1 E1]; auto.\n    destruct IHa2 as [v2 E2]; auto.\n    destruct (eval_binop b v1 v2 m) as [v|] eqn:E.\n    exists v; econstructor; eauto.\n    destruct b; discriminate.\n  - discriminate.\nQed.\n\n\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/backend/Cminortyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1986387193279627}}
{"text": "(** Definitions of various kinds of Lemmas about _fibrations_, leading up to a theorem characterizing their composites. *)\n\nRequire Import UniMath.Foundations.Sets.\nRequire Import UniMath.MoreFoundations.PartA.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Univalence. (* only coercions *)\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.categories.HSET.Core.\nRequire Import UniMath.CategoryTheory.categories.HSET.MonoEpiIso.\nRequire Import UniMath.CategoryTheory.categories.HSET.Univalence.\nRequire Import UniMath.CategoryTheory.limits.pullbacks.\nRequire Import UniMath.CategoryTheory.Adjunctions.Core.\nRequire Import UniMath.CategoryTheory.Equivalences.Core.\nRequire Import UniMath.CategoryTheory.FunctorCategory.\nRequire Import UniMath.CategoryTheory.opp_precat.\nRequire Import UniMath.CategoryTheory.Presheaf.\nLocal Open Scope cat.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Fibrations.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Fiber.\n\nRequire Import UniMath.Foundations.All.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.MoreFibrations.Prefibrations.\nRequire Import UniMath.CategoryTheory.DisplayedCats.MoreFibrations.CartesiannessOfComposites.\n\nLocal Open Scope type_scope.\nLocal Open Scope mor_disp_scope.\n\nDefinition precleaving_comp_is_precart\n    {C : category} {D : disp_cat C} (lift : precleaving D)\n  := forall (c c' c'' : C) (f' : c'' --> c') (f : c' --> c) (d : D c),\n    is_precartesian ((lift _ _ f' (object_of_precartesian_lift (lift _ _ f d))) ;; (lift _ _ f d)).\n\nDefinition precleaving_is_cleaving\n    {C : category} {D : disp_cat C} (lift : precleaving D)\n:= forall (c c' : C) (f: c' --> c) (d : D c), is_cartesian (lift _ _ f d).\n\nLemma transportf_cancel\n      {X : UU} (P : X \u2192 UU) {x x' : X} (e : x = x') (y0 y1 : P x):\n      transportf P e y0 = transportf P e y1 -> y0 = y1.\nProof.\n  induction e.\n  apply idfun.\nDefined.\n\nDefinition assoc_eq {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 ff' : xx -->[f] yy) (gg gg' : yy -->[g] zz) (hh hh' : zz -->[h] ww)\n  : ff ;; (gg ;; hh) = ff' ;; (gg' ;; hh') -> (ff ;; gg) ;; hh = (ff' ;; gg') ;; hh'.\nProof.\n  intro H.\n  eapply pathscomp0.\n  - apply assoc_disp_var.\n  - eapply pathscomp0.\n    + apply maponpaths.\n      exact H.\n    + apply pathsinv0.\n      apply assoc_disp_var.\nQed.\n\nDefinition assoc_eq_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 ff' : xx -->[f] yy) (gg gg' : yy -->[g] zz) (hh hh' : zz -->[h] ww)\n  : (ff ;; gg) ;; hh = (ff' ;; gg') ;; hh' -> ff ;; (gg ;; hh) = ff' ;; (gg' ;; hh').\nProof.\n  intro H.\n  eapply pathscomp0.\n  - apply assoc_disp.\n  - eapply pathscomp0.\n    + apply maponpaths.\n      exact H.\n    + apply pathsinv0.\n      apply assoc_disp.\nQed.\n\n\nDefinition prefibration_w_precart_closed_implies_fibration\n    {C : category} {D : disp_cat C} (lift : precleaving D)\n  : precleaving_comp_is_precart lift -> precleaving_is_cleaving lift.\nProof.\n  unfold precleaving_comp_is_precart, precleaving_is_cleaving.\n  intros liftclosed c c' f d.\n  unfold is_cartesian.\n  intros c'' g d'' hh.\n  apply iscontraprop1.\n  - apply invproofirrelevance.\n    unfold isProofIrrelevant.\n    intros [gg0 comm0] [gg1 comm1].\n    apply subtypePairEquality.\n    + intro gg.\n      apply homsets_disp.\n    + eapply transportf_cancel.\n      eapply pathscomp0.\n      * apply pathsinv0.\n        use precartesian_factorisation_commutes.\n        3: { use precartesian_lift_is_precartesian. apply lift. }\n      * eapply pathscomp0.\n        2: { use precartesian_factorisation_commutes.\n          3: { use precartesian_lift_is_precartesian. apply lift. } }\n        -- apply maponpaths_2.\n           eapply precartesian_factorisation_unique.\n           ++ apply liftclosed.\n           ++ apply assoc_eq_var.\n              eapply pathscomp0.\n              ** apply maponpaths_2.\n                 apply precartesian_factorisation_commutes.\n              ** eapply pathscomp0.\n                 --- eapply pathscomp0.\n                     +++ apply mor_disp_transportf_postwhisker.\n                     +++ eapply pathscomp0.\n                         *** apply maponpaths.\n                             exact (comm0 @ ! comm1).\n                         *** apply pathsinv0.\n                             apply mor_disp_transportf_postwhisker.\n                 --- apply pathsinv0.\n                     apply maponpaths_2.\n                     apply precartesian_factorisation_commutes.\n  - use tpair.\n    + apply (transportf _ (id_left _)).\n      eapply comp_disp.\n      2: { apply lift. }\n      eapply precartesian_factorisation.\n      * apply liftclosed.\n      * exact hh.\n    + simpl.\n      eapply pathscomp0.\n      * eapply pathscomp0.\n        -- apply mor_disp_transportf_postwhisker.\n        -- eapply pathscomp0.\n          ++ apply maponpaths.\n             apply assoc_disp_var.\n          ++ eapply pathscomp0.\n             ** apply transport_f_f.\n             ** apply maponpaths_2.\n                apply homset_property.\n      * apply transportf_transpose_left.\n        apply precartesian_factorisation_commutes.\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/DisplayedCats/MoreFibrations/FibrationsCharacterisation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1986063470836285}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Proof generation *)\n\nSet Implicit Arguments.\n\nRequire Import hpattern vgtac.\nRequire Import Global.\nRequire DomCon SemCon SemSen SemSenLocal SemInsenLocal.\nRequire GamSen DenSenLocal DenInsenLocal.\nRequire ExtSenLocal ExtInsenLocal ExtFin.\nRequire CorSen CorSenLocal CorInsenLocal CorFin.\nRequire Import UserProofType.\n\nModule Make (Import PInput : PINPUT).\n\nModule Sen := SemSen.Make PInput.\nModule GSen := GamSen.Make PInput.\nModule ESenLocal := ExtSenLocal.Make PInput.\nModule EInsenLocal := ExtInsenLocal.Make PInput.\nModule EFin := ExtFin.Make PInput.\nModule CSen := CorSen.Make PInput.\nModule CSenLocal := CorSenLocal.Make PInput.\nModule CInsenLocal := CorInsenLocal.Make PInput.\nModule CFin := CorFin.Make PInput.\n\nDefinition extends (g : G.t) (amap : access_map)\n           (s : Table.t Mem.t) (sen_s : Sen.state_t) : Prop :=\n  exists senl_s,\n    exists insenl_s,\n      EFin.extends g s insenl_s\n      /\\ EInsenLocal.extends g amap insenl_s senl_s\n      /\\ ESenLocal.extends g amap senl_s sen_s.\n\nTheorem correctness :\n  forall (g : G.t) (Hg : G.wf g)\n         (locs : PowLoc.t) (fis_mem : Mem.t) (amap : access_map)\n         (orig_inputof inputof outputof : Table.t Mem.t)\n         (Hvalid :\n            valid g amap orig_inputof inputof outputof = true),\n  exists s', (forall s (Hsem : SemCon.Sem g s), GSen.State_g s s')\n             /\\ extends g amap orig_inputof s'.\nProof.\ni.\nexploit CFin.correctness; eauto\n; destruct 1 as [insen_s [Hinsen_post [Hinsen_amap Hinsen_ext]]].\nexploit CInsenLocal.correctness; eauto\n; destruct 1 as [senl_s [Hsenl_post [Hsenl_amap Hsenl_ext]]].\nexploit CSenLocal.correctness; eauto\n; destruct 1 as [sen_s [Hsen_post Hsen_ext]].\nexists sen_s; split.\n- apply CSen.correctness.\n  eauto.\n- exists senl_s; exists insen_s; repeat split; by auto.\nQed.\n\nEnd Make.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Proof/GenProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19860634153415052}}
{"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import gmap fin_maps list countable.\nFrom cap_machine Require Export addr_reg.\n\n(* Definitions: capabilities, machine words, machine instructions *)\n\nInductive Perm: Type :=\n| O\n| RO\n| RW\n| RWL\n| RX\n| E\n| RWX\n| RWLX\n| URW\n| URWL\n| URWX\n| URWLX.\n\nInductive Locality: Type :=\n| Global\n| Local\n| Directed.\n\nDefinition Cap: Type :=\n  (Perm * Locality) * Addr * Addr * Addr.\n\nDefinition Word := (Z + Cap)%type.\n\nInductive instr: Type :=\n| Jmp (r: RegName)\n| Jnz (r1 r2: RegName)\n| Mov (dst: RegName) (src: Z + RegName)\n| Load (dst src: RegName)\n| Store (dst: RegName) (src: Z + RegName)\n| Lt (dst: RegName) (r1 r2: Z + RegName)\n| Add (dst: RegName) (r1 r2: Z + RegName)\n| Sub (dst: RegName) (r1 r2: Z + RegName)\n| Lea (dst: RegName) (r: Z + RegName)\n| Restrict (dst: RegName) (r: Z + RegName)\n| Subseg (dst: RegName) (r1 r2: Z + RegName)\n| IsPtr (dst r: RegName)\n| GetL (dst r: RegName)\n| GetP (dst r: RegName)\n| GetB (dst r: RegName)\n| GetE (dst r: RegName)\n| GetA (dst r: RegName)\n| Fail\n| Halt\n(* Load value at src + offs into dst *)\n| LoadU (dst src: RegName) (offs: Z + RegName)\n(* Load value in src to dst + offs *)\n| StoreU (dst: RegName) (offs src: Z + RegName)\n(* Promote the uninitialized capability in dst *)\n| PromoteU (dst: RegName).\n\n(* Registers and memory: maps from register names/addresses to words *)\n\nNotation Reg := (gmap RegName Word).\nNotation Mem := (gmap Addr Word).\n\n(* Auxiliary definitions for localities *)\n\nDefinition isLocal (l: Locality): bool :=\n  match l with\n  | Local | Directed => true\n  | _ => false\n  end.\n\nDefinition isLocalWord (w : Word): bool :=\n  match w with\n  | inl _ => false\n  | inr ((_,l),_,_,_) => isLocal l\n  end.\n\nLemma isLocalWord_cap_isLocal (c0:Cap):\n  isLocalWord (inr c0) = true \u2192\n  \u2203 p g b e a, c0 = (p,g,b,e,a) \u2227 isLocal g = true.\nProof.\n  intros. destruct c0, p, p, p.\n  cbv in H. destruct l; try congruence.\n  eexists _, _, _, _, _. split; eauto.\n  eexists _, _, _, _, _. split; eauto.\nQed.\n\nDefinition isGlobal (l: Locality): bool :=\n  match l with\n  | Global => true\n  | _ => false\n  end.\n\nDefinition isGlobalWord (w : Word): bool :=\n  match w with\n  | inl _ => false\n  | inr ((_,l),_,_,_) => isGlobal l\n  end.\n\nLemma isGlobalWord_cap_isGlobal (w0:Word):\n  isGlobalWord w0 = true \u2192\n  \u2203 p g b e a, w0 = inr (p,g,b,e,a) \u2227 isGlobal g = true.\nProof.\n  intros. destruct w0;[done|].\n  destruct c, p, p, p.\n  cbv in H. destruct l; try done.\n  eexists _, _, _, _, _. split; eauto.\nQed.\n\n(* EqDecision instances *)\n\nInstance perm_eq_dec : EqDecision Perm.\nProof. solve_decision. Defined.\nInstance local_eq_dec : EqDecision Locality.\nProof. solve_decision. Defined.\nInstance cap_eq_dec : EqDecision Cap.\nProof. solve_decision. Defined.\nInstance word_eq_dec : EqDecision Word.\nProof. solve_decision. Defined.\nInstance instr_eq_dec : EqDecision instr.\nProof. solve_decision. Defined.\n\n(* Auxiliary definitions to work on permissions *)\n\nDefinition isU (p: Perm) :=\n  match p with\n  | URW | URWL | URWX | URWLX => true\n  | _ => false\n  end.\n\nDefinition pwl p : bool :=\n  match p with\n  | RWLX | RWL => true\n  | _ => false\n  end.\n\nDefinition pwlU p : bool :=\n  match p with\n  | RWLX | RWL | URWLX | URWL => true\n  | _ => false\n  end.\n\nDefinition executeAllowed (p: Perm): bool :=\n  match p with\n  | RWX | RWLX | RX | E => true\n  | _ => false\n  end.\n\n(* Uninitialized capabilities are neither read nor write allowed *)\nDefinition readAllowed (p: Perm): bool :=\n  match p with\n  | RWX | RWLX | RX | RW | RWL | RO => true\n  | _ => false\n  end.\n\nDefinition writeAllowed (p: Perm): bool :=\n  match p with\n  | RWX | RWLX | RW | RWL => true\n  | _ => false\n  end.\n\nDefinition promote_perm (p: Perm): Perm :=\n  match p with\n  | URW => RW\n  | URWL => RWL\n  | URWX => RWX\n  | URWLX => RWLX\n  | _ => p\n  end.\n\nLemma writeA_implies_readA p :\n  writeAllowed p = true \u2192 readAllowed p = true.\nProof. destruct p; auto. Qed.\n\nLemma pwl_implies_RWL_RWLX p :\n  pwl p = true \u2192 p = RWL \u2228 p = RWLX.\nProof.\n  intros. destruct p; try by exfalso.\n  by left. by right.\nQed.\n\nDefinition canReadUpTo (w: Word): Addr :=\n  match w with\n  | inl _ => za\n  | inr ((p, g), b, e, a) => match p with\n                            | O => za\n                            | RO | RW | RWL | RX | RWX | RWLX | E => e\n                            | URW | URWL | URWX | URWLX => a\n                            end\n  end.\n\nDefinition canStore (p: Perm) (a: Addr) (w: Word): bool :=\n  match w with\n  | inl _ => true\n  | inr ((_, g), _, _, _) => match g with\n                            | Global => true\n                            | Local => pwl p\n                            | Directed => pwl p && leb_addr (canReadUpTo w) a\n                            end\n  end.\n\nDefinition canStoreU (p: Perm) (a: Addr) (w: Word): bool :=\n  match w with\n  | inl _ => true\n  | inr ((_, g), _, _, _) => match g with\n                            | Global => true\n                            | Local => pwlU p\n                            | Directed => pwlU p && leb_addr (canReadUpTo w) a\n                            end\n  end.\n\nDefinition isPerm p p' := @bool_decide _ (perm_eq_dec p p').\n\nLemma isPerm_refl p : isPerm p p = true.\nProof. destruct p; auto. Qed.\nLemma isPerm_ne p p' : p \u2260 p' \u2192 isPerm p p' = false.\nProof. intros Hne. destruct p,p'; auto; congruence. Qed.\n\nDefinition isPermWord (w : Word) (p : Perm): bool :=\n  match w with\n  | inl _ => false\n  | inr ((p',_),_,_,_) => isPerm p p'\n  end.\n\nLemma isPermWord_cap_isPerm (w0:Word) p:\n  isPermWord w0 p = true \u2192\n  \u2203 p' g b e a, w0 = inr (p',g,b,e,a) \u2227 isPerm p p' = true.\nProof.\n  intros. destruct w0;[done|].\n  destruct c,p0,p0,p0.\n  cbv in H. destruct p; try done;\n  eexists _, _, _, _, _; split; eauto.\nQed.\n\n(* perm-flows-to: the locality and permission lattice.\n   \"x flows to y\" if x is lower than y in the lattice.\n  *)\n\nDefinition LocalityFlowsTo (l1 l2: Locality): bool :=\n  match l1 with\n  | Directed => true\n  | Local => match l2 with\n            | Directed => false\n            | _ => true\n            end\n  | Global => match l2 with\n             | Global => true\n             | _ => false\n             end\n  end.\n\n(* Sanity check *)\nLemma LocalityFlowsToTransitive:\n  transitive _ LocalityFlowsTo.\nProof.\n  red; intros; destruct x; destruct y; destruct z; try congruence; auto.\nQed.\n\n(* Sanity check 2 *)\nLemma LocalityFlowsToReflexive:\n  forall g, LocalityFlowsTo g g.\nProof.\n  intros; destruct g; auto.\nQed.\n\nDefinition PermFlowsTo (p1 p2: Perm): bool :=\n  match p1 with\n  | O => true\n  | E => match p2 with\n        | E | RX | RWX | RWLX => true\n        | _ => false\n        end\n  | RX => match p2 with\n         | RX | RWX | RWLX => true\n         | _ => false\n         end\n  | RWX => match p2 with\n          | RWX | RWLX => true\n          | _ => false\n          end\n  | RWLX => match p2 with\n           | RWLX => true\n           | _ => false\n           end\n  | RO => match p2 with\n         | E | O | URW | URWL | URWX | URWLX => false\n         | _ => true\n         end\n  | RW => match p2 with\n         | RW | RWX | RWL | RWLX => true\n         | _ => false\n         end\n  | RWL => match p2 with\n          | RWL | RWLX => true\n          | _ => false\n          end\n  | URW => match p2 with\n          | URW | URWL | URWX | URWLX | RW | RWX | RWL | RWLX => true\n          | _ => false\n          end\n  | URWL => match p2 with\n           | URWL | RWL | RWLX | URWLX => true\n           | _ => false\n           end\n  | URWX => match p2 with\n           | URWX | RWX | RWLX | URWLX => true\n           | _ => false\n           end\n  | URWLX => match p2 with\n            | URWLX | RWLX => true\n            | _ => false\n            end\n  end.\n\n(* Sanity check *)\nLemma PermFlowsToTransitive:\n  transitive _ PermFlowsTo.\nProof.\n  red; intros; destruct x; destruct y; destruct z; try congruence; auto.\nQed.\n\n(* Sanity check 2 *)\nLemma PermFlowsToReflexive:\n  forall p, PermFlowsTo p p.\nProof.\n  intros; destruct p; auto.\nQed.\n\nDefinition PermPairFlowsTo (pg1 pg2: Perm * Locality): bool :=\n  PermFlowsTo (fst pg1) (fst pg2) && LocalityFlowsTo (snd pg1) (snd pg2).\n\n(* perm-flows-to as a predicate *)\nDefinition PermFlows : Perm \u2192 Perm \u2192 Prop :=\n  \u03bb p1 p2, PermFlowsTo p1 p2 = true.\n\nLemma PermFlows_refl : \u2200 p, PermFlows p p.\nProof.\n  rewrite /PermFlows /PermFlowsTo.\n  destruct p; auto.\nQed.\n\nLemma PermFlows_trans P1 P2 P3 :\n  PermFlows P1 P2 \u2192 PermFlows P2 P3 \u2192 PermFlows P1 P3.\nProof.\n  intros Hp1 Hp2. rewrite /PermFlows /PermFlowsTo.\n  destruct P1,P3,P2; simpl; auto; contradiction.\nQed.\n\nLemma readAllowed_nonO p p' :\n  PermFlows p p' \u2192 readAllowed p = true \u2192 p' \u2260 O.\nProof.\n  intros Hfl' Hra. destruct p'; auto. destruct p; inversion Hfl'. inversion Hra.\nQed.\n\nLemma writeAllowed_nonO p p' :\n  PermFlows p p' \u2192 writeAllowed p = true \u2192 p' \u2260 O.\nProof.\n  intros Hfl' Hra. apply writeA_implies_readA in Hra. by apply (readAllowed_nonO p p').\nQed.\n\nLemma PCPerm_nonO p p' :\n  PermFlows p p' \u2192 p = RX \u2228 p = RWX \u2228 p = RWLX \u2192 p' \u2260 O.\nProof.\n  intros Hfl Hvpc. destruct p'; auto. destruct p; inversion Hfl.\n  destruct Hvpc as [Hcontr | [Hcontr | Hcontr]]; inversion Hcontr.\nQed.\n\n(* Helper definitions for capabilities *)\n\n(* Turn E into RX into PC after a jump *)\nDefinition updatePcPerm (w: Word): Word :=\n  match w with\n  | inr ((E, g), b, e, a) => inr ((RX, g), b, e, a)\n  | _ => w\n  end.\n\nLemma updatePcPerm_cap_non_E p g b e a :\n  p \u2260 E \u2192\n  updatePcPerm (inr (p, g, b, e, a)) = inr (p, g, b, e, a).\nProof.\n  intros HnE. cbn. destruct p; auto. contradiction.\nQed.\n\nDefinition nonZero (w: Word): bool :=\n  match w with\n  | inr _ => true\n  | inl n => Zneq_bool n 0\n  end.\n\nDefinition cap_size (w : Word) : Z :=\n  match w with\n  | inr (_,_,b,e,_) => (e - b)%Z\n  | _ => 0%Z\n  end.\n\nDefinition is_cap (w: Word): bool :=\n  match w with\n  | inr _ => true\n  | inl _ => false\n  end.\n\n(* Bound checking *)\n\nDefinition withinBounds (c: Cap): bool :=\n  match c with\n  | (_, b, e, a) => (b <=? a)%a && (a <? e)%a\n  end.\n\nLemma withinBounds_true_iff p g b e a :\n  withinBounds (p, g, b, e, a) = true \u2194 (b <= a)%a \u2227 (a < e)%a.\nProof.\n  unfold withinBounds.\n  rewrite /le_addr /lt_addr /leb_addr /ltb_addr.\n  rewrite andb_true_iff Z.leb_le Z.ltb_lt. auto.\nQed.\n\nLemma withinBounds_le_addr p l b e a:\n  withinBounds (p, l, b, e, a) = true \u2192\n  (b <= a)%a \u2227 (a < e)%a.\nProof. rewrite withinBounds_true_iff //. Qed.\n\nLemma isWithinBounds_bounds_alt p g b e (a0 a1 a2 : Addr) :\n  withinBounds (p,g,b,e,a0) = true \u2192\n  withinBounds (p,g,b,e,a2) = true \u2192\n  (a0 \u2264 a1)%Z \u2227 (a1 \u2264 a2)%Z \u2192\n  withinBounds (p,g,b,e,a1) = true.\nProof. rewrite !withinBounds_true_iff. solve_addr. Qed.\n\nLemma isWithinBounds_bounds_alt' p g b e (a0 a1 a2 : Addr) :\n  withinBounds (p,g,b,e,a0) = true \u2192\n  withinBounds (p,g,b,e,a2) = true \u2192\n  (a0 \u2264 a1)%Z \u2227 (a1 < a2)%Z \u2192\n  withinBounds (p,g,b,e,a1) = true.\nProof. rewrite !withinBounds_true_iff. solve_addr. Qed.\n\nLemma le_addr_withinBounds p l b e a:\n  (b <= a)%a \u2192 (a < e)%a \u2192\n  withinBounds (p, l, b, e, a) = true .\nProof. rewrite withinBounds_true_iff //. Qed.\n\n\n(* isCorrectPC: valid capabilities for PC *)\n\nInductive isCorrectPC: Word \u2192 Prop :=\n| isCorrectPC_intro:\n    forall p g (b e a : Addr),\n      (b <= a < e)%a \u2192\n      p = RX \\/ p = RWX \\/ p = RWLX \u2192\n      isCorrectPC (inr ((p, g), b, e, a)).\n\nLemma isCorrectPC_dec:\n  forall w, { isCorrectPC w } + { not (isCorrectPC w) }.\nProof.\n  destruct w.\n  - right. red; intros H. inversion H.\n  - destruct c as ((((p & g) & b) & e) & a).\n    case_eq (match p with RX | RWX | RWLX => true | _ => false end); intros.\n    + destruct (Addr_le_dec b a).\n      * destruct (Addr_lt_dec a e).\n        { left. econstructor; simpl; eauto. by auto.\n          destruct p; naive_solver. }\n        { right. red; intro HH. inversion HH; subst. solve_addr. }\n      * right. red; intros HH; inversion HH; subst. solve_addr.\n    + right. red; intros HH; inversion HH; subst. naive_solver.\nQed.\n\nDefinition isCorrectPCb (w: Word): bool :=\n  match w with\n  | inl _ => false\n  | inr (p, g, b, e, a) =>\n    (b <=? a)%a && (a <? e)%a &&\n    (isPerm p RX || isPerm p RWX || isPerm p RWLX)\n  end.\n\nLemma isCorrectPCb_isCorrectPC w :\n  isCorrectPCb w = true \u2194 isCorrectPC w.\nProof.\n  rewrite /isCorrectPCb. destruct w.\n  { split; try congruence. inversion 1. }\n  { destruct c as [[[[? ?] ?] ?] ?]. rewrite /leb_addr /ltb_addr.\n    rewrite !andb_true_iff !orb_true_iff !Z.leb_le !Z.ltb_lt.\n    rewrite /isPerm !bool_decide_eq_true.\n    split.\n    { intros [? ?]. constructor. solve_addr. naive_solver. }\n    { inversion 1; subst. split. solve_addr. naive_solver. } }\nQed.\n\nLemma isCorrectPCb_nisCorrectPC w :\n  isCorrectPCb w = false \u2194 \u00ac isCorrectPC w.\nProof.\n  destruct (isCorrectPCb w) eqn:HH.\n  { apply isCorrectPCb_isCorrectPC in HH. split; congruence. }\n  { split; auto. intros _. intros ?%isCorrectPCb_isCorrectPC. congruence. }\nQed.\n\nLemma isCorrectPC_ra_wb pc_p pc_g pc_b pc_e pc_a :\n  isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) \u2192\n  readAllowed pc_p && ((pc_b <=? pc_a)%a && (pc_a <? pc_e)%a).\nProof.\n  intros. inversion H; subst.\n  - destruct H2. apply andb_prop_intro. split.\n    + destruct H6,pc_p; inversion H1; try inversion H2; auto; try congruence.\n    + apply andb_prop_intro.\n      split; apply Is_true_eq_left; [apply Z.leb_le | apply Z.ltb_lt]; lia.\nQed.\n\nLemma not_isCorrectPC_perm p g b e a :\n  p \u2260 RX \u2227 p \u2260 RWX \u2227 p \u2260 RWLX \u2192 \u00ac isCorrectPC (inr ((p,g),b,e,a)).\nProof.\n  intros (Hrx & Hrwx & Hrwlx).\n  intros Hvpc. inversion Hvpc;\n    destruct H5 as [Hrx' | [Hrwx' | Hrwlx']]; contradiction.\nQed.\n\nLemma not_isCorrectPC_bounds p g b e a :\n \u00ac (b <= a < e)%a \u2192 \u00ac isCorrectPC (inr ((p,g),b,e,a)).\nProof.\n  intros Hbounds.\n  intros Hvpc. inversion Hvpc.\n  by exfalso.\nQed.\n\nLemma isCorrectPC_bounds p g b e (a0 a1 a2 : Addr) :\n  isCorrectPC (inr (p, g, b, e, a0)) \u2192\n  isCorrectPC (inr (p, g, b, e, a2)) \u2192\n  (a0 \u2264 a1 < a2)%Z \u2192 isCorrectPC (inr (p, g, b, e, a1)).\nProof.\n  intros Hvpc0 Hvpc2 [Hle Hlt].\n  inversion Hvpc0.\n  - subst; econstructor; auto.\n    inversion Hvpc2; subst.\n    + destruct H1 as [Hb He]. destruct H2 as [Hb2 He2]. split.\n      { apply Z.le_trans with a0; auto. }\n      { apply Z.lt_trans with a2; auto. }\nQed.\n\nLemma isCorrectPC_bounds_alt p g b e (a0 a1 a2 : Addr) :\n  isCorrectPC (inr (p, g, b, e, a0))\n  \u2192 isCorrectPC (inr (p, g, b, e, a2))\n  \u2192 (a0 \u2264 a1)%Z \u2227 (a1 \u2264 a2)%Z\n  \u2192 isCorrectPC (inr (p, g, b, e, a1)).\nProof.\n  intros Hvpc0 Hvpc2 [Hle0 Hle2].\n  apply Z.lt_eq_cases in Hle2 as [Hlt2 | Heq2].\n  - apply isCorrectPC_bounds with a0 a2; auto.\n  - apply z_of_eq in Heq2. rewrite Heq2. auto.\nQed.\n\nLemma isCorrectPC_withinBounds p g p' g' b e a :\n  isCorrectPC (inr (p, g, b, e, a)) \u2192\n  withinBounds (p', g', b, e, a) = true.\nProof.\n  intros HH. inversion HH; subst.\n  rewrite /withinBounds !andb_true_iff Z.leb_le Z.ltb_lt. auto.\nQed.\n\nLemma correctPC_nonO p p' g b e a :\n  PermFlows p p' \u2192 isCorrectPC (inr (p,g,b,e,a)) \u2192 p' \u2260 O.\nProof.\n  intros Hfl HcPC. inversion HcPC. by apply (PCPerm_nonO p p').\nQed.\n\nLemma in_range_is_correctPC p l b e a b' e' :\n  isCorrectPC (inr ((p,l),b,e,a)) \u2192\n  (b' <= b)%a \u2227 (e <= e')%a \u2192\n  (b' <= a)%a \u2227 (a < e')%a.\nProof.\n  intros Hvpc [Hb He].\n  inversion Hvpc; simplify_eq. solve_addr.\nQed.\n\n(* Helper tactics *)\n\nLtac destruct_pair_l c n :=\n  match eval compute in n with\n  | 0 => idtac\n  | _ => let sndn := fresh c in\n        destruct c as (c,sndn); destruct_pair_l c (pred n)\n  end.\n\nLtac destruct_cap c :=\n  destruct_pair_l c 4.\n\n(* Useful instances *)\n\nInstance perm_countable : Countable Perm.\nProof.\n  set encode := fun p => match p with\n    | O => 1\n    | RO => 2\n    | RW => 3\n    | RWL => 4\n    | RX => 5\n    | E => 6\n    | RWX => 7\n    | RWLX => 8\n    | URW => 9\n    | URWL => 10\n    | URWX => 11\n    | URWLX => 12\n    end%positive.\n  set decode := fun n => match n with\n    | 1 => Some O\n    | 2 => Some RO\n    | 3 => Some RW\n    | 4 => Some RWL\n    | 5 => Some RX\n    | 6 => Some E\n    | 7 => Some RWX\n    | 8 => Some RWLX\n    | 9 => Some URW\n    | 10 => Some URWL\n    | 11 => Some URWX\n    | 12 => Some URWLX\n    | _ => None\n    end%positive.\n  eapply (Build_Countable _ _ encode decode).\n  intro p. destruct p; reflexivity.\nDefined.\n\nInstance locality_countable : Countable Locality.\nProof.\n  set encode := fun l => match l with\n    | Local => 1\n    | Global => 2\n    | Directed => 3\n    end%positive.\n  set decode := fun n => match n with\n    | 1 => Some Local\n    | 2 => Some Global\n    | 3 => Some Directed\n    | _ => None\n    end%positive.\n  eapply (Build_Countable _ _ encode decode).\n  intro l. destruct l; reflexivity.\nDefined.\n\nInstance cap_countable : Countable Cap.\nProof.\n  (* NB: this relies on the fact that cap_eq_dec has been Defined, because the\n  eq decision we have for Cap has to match the one used in the conclusion of the\n  lemma... *)\n  apply prod_countable.\nDefined.\n\nInstance word_countable : Countable Word.\nProof. apply sum_countable. Defined.\n\nInstance instr_countable : Countable instr.\nProof.\n  set (enc := fun e =>\n      match e with\n      | Jmp r => GenNode 0 [GenLeaf (inl r)]\n      | Jnz r1 r2 => GenNode 1 [GenLeaf (inl r1); GenLeaf (inl r2)]\n      | Mov dst src => GenNode 2 [GenLeaf (inl dst); GenLeaf (inr src)]\n      | Load dst src => GenNode 3 [GenLeaf (inl dst); GenLeaf (inl src)]\n      | Store dst src => GenNode 4 [GenLeaf (inl dst); GenLeaf (inr src)]\n      | Lt dst r1 r2 => GenNode 5 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)]\n      | Add dst r1 r2 => GenNode 6 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)]\n      | Sub dst r1 r2 => GenNode 7 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)]\n      | Lea dst r => GenNode 8 [GenLeaf (inl dst); GenLeaf (inr r)]\n      | Restrict dst r => GenNode 9 [GenLeaf (inl dst); GenLeaf (inr r)]\n      | Subseg dst r1 r2 => GenNode 10 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)]\n      | IsPtr dst r => GenNode 11 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | GetL dst r => GenNode 12 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | GetP dst r => GenNode 13 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | GetB dst r => GenNode 14 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | GetE dst r => GenNode 15 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | GetA dst r => GenNode 16 [GenLeaf (inl dst); GenLeaf (inl r)]\n      | Fail => GenNode 17 []\n      | Halt => GenNode 18 []\n      | LoadU dst src offs => GenNode 19 [GenLeaf (inl dst); GenLeaf (inl src); GenLeaf (inr offs)]\n      | StoreU dst offs src => GenNode 20 [GenLeaf (inl dst); GenLeaf (inr offs); GenLeaf (inr src)]\n      | PromoteU dst => GenNode 21 [GenLeaf (inl dst)]\n      end).\n  set (dec := fun e =>\n      match e with\n      | GenNode 0 [GenLeaf (inl r)] => Jmp r\n      | GenNode 1 [GenLeaf (inl r1); GenLeaf (inl r2)] => Jnz r1 r2\n      | GenNode 2 [GenLeaf (inl dst); GenLeaf (inr src)] => Mov dst src\n      | GenNode 3 [GenLeaf (inl dst); GenLeaf (inl src)] => Load dst src\n      | GenNode 4 [GenLeaf (inl dst); GenLeaf (inr src)] => Store dst src\n      | GenNode 5 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)] => Lt dst r1 r2\n      | GenNode 6 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)] => Add dst r1 r2\n      | GenNode 7 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)] => Sub dst r1 r2\n      | GenNode 8 [GenLeaf (inl dst); GenLeaf (inr r)] => Lea dst r\n      | GenNode 9 [GenLeaf (inl dst); GenLeaf (inr r)] => Restrict dst r\n      | GenNode 10 [GenLeaf (inl dst); GenLeaf (inr r1); GenLeaf (inr r2)] => Subseg dst r1 r2\n      | GenNode 11 [GenLeaf (inl dst); GenLeaf (inl r)] => IsPtr dst r\n      | GenNode 12 [GenLeaf (inl dst); GenLeaf (inl r)] => GetL dst r\n      | GenNode 13 [GenLeaf (inl dst); GenLeaf (inl r)] => GetP dst r\n      | GenNode 14 [GenLeaf (inl dst); GenLeaf (inl r)] => GetB dst r\n      | GenNode 15 [GenLeaf (inl dst); GenLeaf (inl r)] => GetE dst r\n      | GenNode 16 [GenLeaf (inl dst); GenLeaf (inl r)] => GetA dst r\n      | GenNode 17 [] => Fail\n      | GenNode 18 [] => Halt\n      | GenNode 19 [GenLeaf (inl dst); GenLeaf (inl src); GenLeaf (inr offs)] => LoadU dst src offs\n      | GenNode 20 [GenLeaf (inl dst); GenLeaf (inr offs); GenLeaf (inr src)] => StoreU dst offs src\n      | GenNode 21 [GenLeaf (inl dst)] => PromoteU dst\n      | _ => Fail (* dummy *)\n      end).\n  refine (inj_countable' enc dec _).\n  intros i. destruct i; simpl; done.\nDefined.\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/machine_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19860634153415052}}
{"text": "Set Implicit Arguments.\n\nRequire Import ADT.\nRequire Import RepInv.\n\nModule Make (Import E : ADT) (Import M : RepInv E).\n\n  Require Import PostOk.\n  Module Import PostOkMake := Make E M.\n  Require Import VerifCondOk.\n  Module Import VerifCondOkMake := Make E M.\n  Import CompileStmtSpecMake.\n  Import InvMake.\n  Import Semantics.\n  Import SemanticsMake.\n  Import InvMake2.\n\n  Section TopSection.\n\n    Require Import AutoSep.\n\n    Variable vars : list string.\n\n    Variable temp_size : nat.\n\n    Variable imports : LabelMap.t assert.\n\n    Variable imports_global : importsGlobal imports.\n\n    Variable modName : string.\n\n    Require Import Syntax.\n\n    Variable rv_postcond : W -> vals -> Prop.\n\n    Notation do_compile := (CompileStmtImplMake.compile vars temp_size rv_postcond imports_global modName).\n\n    Variable s k : Stmt.\n\n    Require Import Wrap.\n    Definition compile : cmd imports modName.\n      refine (\n          Wrap imports imports_global modName \n               (do_compile s k) \n               (fun _ => postcond vars temp_size k rv_postcond) \n               (verifCond vars temp_size s k rv_postcond) \n               _ _).\n      eapply post_ok.\n      eapply verifCond_ok.\n    Defined.\n\n  End TopSection.\n\nEnd Make.", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/CompileStmt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.19860633782816517}}
{"text": "(* \n * \u00a9 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     Automation\n     Maps\n     Keys\n     Messages\n     Tactics\n     Simulation\n     RealWorld\n     SafetyAutomation\n\n     Theory.CipherTheory\n     Theory.KeysTheory\n     Theory.MessagesTheory\n     Theory.InvariantsTheory\n.\n\nSet Implicit Arguments.\nImport RealWorld RealWorldNotations.\n\nImport SafetyAutomation.\n\nInductive ty : Set :=\n| TyDontCare\n| TyHonestKey\n| TyMyCphr (uid : user_id) (k_id : key_identifier)\n| TyRecvMsg\n| TyRecvCphr\n| TySent\n.\n\nRecord safe_typ :=\n  { cmd_type : user_cmd_type ;\n    cmd_val  : << cmd_type >> ;\n    safetyTy : ty\n  }.\n\nRequire Import Coq.Program.Equality Coq.Logic.JMeq.\n\nLemma safe_typ_eq :\n  forall t1 t2 tv1 tv2 styp1 styp2,\n    {| cmd_type := t1 ; cmd_val := tv1 ; safetyTy := styp1 |} =\n    {| cmd_type := t2 ; cmd_val := tv2 ; safetyTy := styp2 |}\n    -> t1 = t2\n    /\\ styp1 = styp2\n    /\\ JMeq tv1 tv2\n.\nProof.\n  intros.\n  dependent induction H; eauto.\nQed.\n\nInductive HonestKey (context : list safe_typ) : key_identifier -> Prop :=\n| HonestPermission : forall k tf,\n    List.In {| cmd_type := Base Access ; cmd_val := (k,tf) ; safetyTy := TyHonestKey |} context\n    -> HonestKey context k\n| HonestFromMsg : forall t (msg : RealWorld.message.message t) k kp,\n    List.In {| cmd_type := RealWorld.Message t ; cmd_val := msg ; safetyTy := TyRecvMsg |} context\n    -> findKeysMessage msg $? k = Some kp\n    -> HonestKey context k\n| HonestKeyFromMsgVerify : forall t (v : bool * message t) k kp,\n    List.In {| cmd_type := UPair (Base Bool) (Message t) ;\n               cmd_val := v ;\n               safetyTy := TyRecvMsg |}\n            context\n    -> findKeysMessage (snd v) $? k = Some kp\n    -> HonestKey context k\n(* | HonestKeyFromMsgVerify : forall (v : bool * message Access), *)\n(*     List.In {| cmd_type := UPair (Base Bool) (Message Access) ; *)\n(*                cmd_val := v ; *)\n(*                safetyTy := TyRecvMsg |} *)\n(*             context *)\n(* | HonestFromMsg : forall k kp t (msg : RealWorld.message.message t), *)\n(*     findKeysMessage msg $? k = Some kp *)\n(*     -> HonestKey context k. *)\n(* | HonestKeyFromMsgVerify : forall (v : bool * message Access), *)\n(*     List.In {| cmd_type := UPair (Base Bool) (Message Access) ; *)\n(*                cmd_val := v ; *)\n(*                safetyTy := TyRecvMsg |} *)\n(*             context *)\n(*     -> HonestKey context (fst (extractPermission (snd v))) *)\n.\n\nFixpoint init_context (ks : list key_permission) : list safe_typ :=\n  match ks with\n  | []         => []\n  | (kp :: kps) =>\n    {| cmd_type := Base Access ; cmd_val := kp ; safetyTy := TyHonestKey |} :: init_context kps\n  end.\n\nInductive syntactically_safe (u_id : user_id) (uids : list user_id) :\n  list safe_typ -> forall t, user_cmd t -> ty -> Prop :=\n\n| SafeBind : forall {t t'} context (cmd1 : user_cmd t') t1,\n    syntactically_safe u_id uids context cmd1 t1\n    -> forall (cmd2 : <<t'>> -> user_cmd t) t2,\n      (forall a, syntactically_safe u_id uids ({| cmd_type := t' ; cmd_val := a ; safetyTy := t1 |} :: context) (cmd2 a) t2)\n      -> syntactically_safe u_id uids context (Bind cmd1 cmd2) t2\n\n| SafeEncrypt : forall context {t} (msg : message t) k__sign k__enc msg_to,\n    HonestKey context k__enc\n    -> HonestKey context k__sign\n    -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> HonestKey context k_id)\n    -> msg_to <> u_id\n    -> List.In msg_to uids\n    -> syntactically_safe u_id uids context (SignEncrypt k__sign k__enc msg_to msg) (TyMyCphr msg_to k__sign)\n\n| SafeSign : forall context {t} (msg : message t) k msg_to,\n    HonestKey context k\n    -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> HonestKey context k_id /\\ kp = false)\n    -> msg_to <> u_id\n    -> List.In msg_to uids\n    -> syntactically_safe u_id uids context (Sign k msg_to msg) (TyMyCphr msg_to k)\n\n| SafeRecvSigned : forall context t k,\n    HonestKey context k\n    -> syntactically_safe u_id uids context (@Recv t (Signed k true)) TyRecvCphr\n\n| SafeRecvEncrypted : forall context t k__sign k__enc,\n    HonestKey context k__sign\n    -> syntactically_safe u_id uids context (@Recv t (SignedEncrypted k__sign k__enc true)) TyRecvCphr\n\n| SafeSend : forall context t (msg : crypto t) msg_to k,\n    (* ~ List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := TySent |} context *)\n    List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := (TyMyCphr msg_to k) |} context\n    -> syntactically_safe u_id uids context (Send msg_to msg) TyDontCare\n\n| SafeReturn : forall {A} context (a : << A >>) sty,\n    List.In {| cmd_type := A ; cmd_val := a ; safetyTy := sty |} context\n    -> syntactically_safe u_id uids context (Return a) sty\n\n| SafeReturnUntyped : forall {A} context (a : << A >>),\n    syntactically_safe u_id uids context (Return a) TyDontCare\n\n| SafeGen : forall context,\n    syntactically_safe u_id uids context Gen TyDontCare\n\n| SafeDecrypt : forall context t (msg : crypto t),\n    List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := TyRecvCphr |} context\n    -> syntactically_safe u_id uids context (Decrypt msg) TyRecvMsg\n| SafeVerify : forall context t k msg,\n    List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := TyRecvCphr |} context\n    -> syntactically_safe u_id uids context (@Verify t k msg) TyRecvMsg\n\n| SafeGenerateKey : forall context kt usage,\n    syntactically_safe u_id uids context (GenerateKey kt usage) TyHonestKey\n\n(* | SafeGenerateSymKey : forall context usage, *)\n(*     syntactically_safe u_id uids context (GenerateSymKey usage) TyHonestKey *)\n(* | SafeGenerateAsymKey : forall context usage, *)\n(*     syntactically_safe u_id uids context (GenerateAsymKey usage) TyHonestKey *)\n.\n\nDefinition compute_ids' {V} (m : NatMap.t V) :=\n  List.map (fun '(k,_) => k) (elements m).\n\nDefinition compute_ids {V} (m : NatMap.t V) :=\n  List.map (fun '(k,_) => k) (elements (mapi (fun k v => k) m)).\n(* fold (fun k _ l => k :: l) m []. *)\n\nLemma list_setoidlist_iff :\n  forall {V} (l : list (nat * V)) k v,\n    List.In (k,v) l <-> SetoidList.InA (@eq_key_elt V) (k,v) l.\nProof.\n  induction l; split; intros;\n    repeat match goal with\n           | [ H : eq_key_elt _ _ |- _ ] => invert H; simpl in *; subst\n           | [ H : (_,_) = (_,_) |- _ ] => invert H\n           | [ H : List.In _ [] |- _ ] => invert H\n           | [ H : SetoidList.InA _ _ [] |- _ ] => invert H\n           | [ H : List.In _ (?a :: _) |- _ ] => destruct a; simpl in H; split_ors\n           | [ H : SetoidList.InA _ _ (?a :: _) |- _ ] => destruct a; invert H\n           end; eauto 3.\n  - econstructor; red; eauto using Raw.PX.eqke_refl.\n  - eapply IHl in H; eauto.\n  - eapply IHl in H1; eauto.\nQed.\n\nLemma in_ids_in_m :\n  forall V (m : NatMap.t V) k,\n    List.In k (compute_ids m)\n    -> exists v,\n      m $? k = Some v.\nProof.\n  unfold compute_ids; intros *.\n  induction m using map_induction_bis; intros; Equal_eq; eauto.\n  contradiction.\n\n  destruct (k ==n x); subst.\n  - eexists; clean_map_lookups; eauto.\n  - assert (List.In k (List.map (fun '(k, _) => k) (elements (elt:=Map.key) (mapi (fun (k : Map.key) (_ : V) => k) m)))).\n\n    rewrite in_map_iff in H0 |- *; split_ex.\n    destruct x0; subst.\n    exists (k,k1); split; eauto.\n    rewrite list_setoidlist_iff in *.\n    rewrite <- elements_mapsto_iff in *.\n    rewrite mapi_mapsto_iff in *; eauto.\n    split_ex; subst.\n    eexists; rewrite find_mapsto_iff in *; clean_map_lookups; eauto.\n\n    clean_map_lookups; eauto.\nQed.\n\n\nLemma readd_user_in :\n  forall V (m : NatMap.t V) k v v',\n    m $? k = Some v\n    -> List.map (fun '(k,_) => k) (elements (mapi (fun k _ => k) (m $+ (k,v'))))\n      = List.map (fun '(k,_) => k) (elements (mapi (fun k _ => k) m)).\nProof.\n  intros.\n\n  assert ( mapi (fun k _ => k) (m $+ (k,v')) = mapi (fun k _ => k) m ).\n  apply map_eq_Equal; unfold Equal; intros.\n  cases (m $? y);\n    destruct (y ==n k); subst; clean_map_lookups; eauto;\n      rewrite !mapi_o; eauto;\n        clean_map_lookups; eauto.\n\n  rewrite <- H0; trivial.\nQed.\n\nLemma compute_userids_readd_idempotent :\n  forall A (usrs : honest_users A) uid u u',\n    usrs $? uid = Some u\n    -> compute_ids (usrs $+ (uid,u')) = compute_ids usrs.\nProof.\n  unfold compute_ids; intros; eauto using readd_user_in.\nQed.\n\nLemma user_step_nochange_uids :\n  forall {A B C} cs cs' lbl u_id (usrs usrs' : honest_users A) (adv adv' : user_data B)\n    gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n    step_user lbl u_id bd bd'\n    -> forall (cmd : user_cmd C),\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> forall cmd',\n        bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> compute_ids usrs' = compute_ids usrs.\nProof.\n  induction 1; inversion 1; inversion 1; intros; subst; eauto;\n    repeat match goal with\n           | [ H : ?us $? ?uid = Some _ |- ?us $? ?uid <> None ] => solve [ rewrite H; intro C; invert C ]\n           end.\n\n  clean_context.\n  erewrite compute_userids_readd_idempotent by eauto.\n  trivial.\nQed.\n\nDefinition U_syntactically_safe {A B} (U : RealWorld.universe A B) :=\n  forall u_id u uids,\n    U.(users) $? u_id = Some u\n    -> uids = compute_ids U.(users)\n    -> forall ctx,\n      ctx = init_context (elements u.(key_heap))\n      -> exists t,\n        syntactically_safe u_id uids ctx u.(protocol) t.\n\n#[export] Hint Constructors\n     HonestKey\n     syntactically_safe\n  : core.\n\nLemma HonestKey_split :\n  forall t (tv : <<t>>) styp k context key_rec,\n    key_rec = {| cmd_type := t ; cmd_val := tv ; safetyTy := styp |}\n    -> HonestKey (key_rec :: context) k\n    -> (exists tf, key_rec = {| cmd_type := Base Access ; cmd_val := (k,tf) ; safetyTy := TyHonestKey |})\n    \\/ (exists t msg kp, key_rec = {| cmd_type := (Message t) ;\n                                cmd_val  := msg ;\n                                safetyTy := TyRecvMsg |}\n                   /\\ findKeysMessage msg $? k = Some kp)\n    \\/ (exists t bool_msg kp, key_rec  = {| cmd_type := UPair (Base Bool) (Message t) ;\n                                      cmd_val := bool_msg ;\n                                      safetyTy := TyRecvMsg |}\n                        /\\ findKeysMessage (snd bool_msg) $? k = Some kp)\n    (* \\/ (exists v, key_rec  = {| cmd_type := (Message Access) ; *)\n    (*                       cmd_val  := v ; *)\n    (*                       safetyTy := TyRecvMsg |} *)\n    (*         /\\ k = fst (extractPermission v)) *)\n    (* \\/ (exists v, key_rec  = {| cmd_type := UPair (Base Bool) (Message Access) ; *)\n    (*                       cmd_val := v ; *)\n    (*                       safetyTy := TyRecvMsg |} *)\n    (*         /\\ k = fst (extractPermission (snd v))) *)\n    \\/ HonestKey context k\n.\nProof.\n  intros; subst.\n  invert H0; simpl in *; split_ors; eauto 15.\nQed.\n\nLemma HonestKey_split_drop :\n  forall t (tv : <<t>>) k context sty,\n    sty <> TyHonestKey\n    -> sty <> TyRecvMsg\n    -> HonestKey ({| cmd_type := t ; cmd_val := tv ; safetyTy := sty |} :: context) k\n    -> HonestKey context k\n.\nProof.\n  intros; subst.\n  eapply HonestKey_split in H1; split_ors; eauto.\n  all: eapply safe_typ_eq in H1; split_ands; subst; contradiction.\nQed.\n\n#[export] Hint Resolve HonestKey_split_drop : core.\n\nLemma HonestKey_skip :\n  forall t (tv : <<t>>) styp k context key_rec,\n    HonestKey context k\n    -> key_rec = {| cmd_type := t ; cmd_val := tv ; safetyTy := styp |}\n    -> HonestKey (key_rec :: context) k\n.\nProof.\n  intros; subst.\n  invert H; eauto.\nQed.\n\nLemma HonestKey_augment_context :\n  forall k ctx ctx',\n    HonestKey ctx k\n    -> Forall (fun styp => List.In styp ctx') ctx\n    -> HonestKey ctx' k.\n  intros * H FOR; invert H; rewrite Forall_forall in FOR; intros; eauto.\nQed.\n\n#[export] Hint Resolve\n     HonestKey_skip HonestKey_split\n     HonestKey_augment_context\n  : core.\n\nLemma Forall_In_refl :\n  forall a (l : list a),\n    Forall (fun e => List.In e l) l.\nProof.\n  intros; rewrite Forall_forall; intros; eauto.\nQed.\n\nLemma Forall_In_add :\n  forall a (l : list a) elem,\n    Forall (fun e => List.In e (elem :: l)) l.\nProof.\n  intros; rewrite Forall_forall; intros; eauto.\nQed.\n\n#[export] Hint Resolve\n     Forall_In_refl\n     Forall_In_add\n  : core.\n\nLemma syntactically_safe_add_ctx :\n  forall ctx u_id uids A (cmd : user_cmd A) sty,\n    syntactically_safe u_id uids ctx cmd sty\n    -> forall ctx',\n      List.Forall (fun styp => List.In styp ctx') ctx\n      -> syntactically_safe u_id uids ctx' cmd sty.\nProof.\n  induction 1; intros;\n    eauto;\n    try solve [ rewrite Forall_forall in *; eauto 8 ].\n\n  - econstructor; eauto.\n    intros.\n    eapply H1; eauto.\n    econstructor; eauto.\n    rewrite Forall_forall in *; intros; eauto.\n    \n  - econstructor; intros; eauto.\n  - econstructor; intros; eauto.\n    apply H0 in H4; split_ex; subst; eauto.\nQed.\n\nDefinition typingcontext_sound (ctx : list safe_typ)\n           (* (honestk : key_perms) *)\n           {A} (usrs : honest_users A)\n           (* (honestk : key_perms) *)\n           (cs : ciphers)\n           (* (ks : key_perms) *)\n           (u_id : user_id) :=\n  (forall kid, HonestKey ctx kid -> (findUserKeys usrs) $? kid = Some true)\n(* /\\ (forall kid, ks $? kid = Some true -> HonestKey ctx kid) *)\n/\\ (forall t msg msg_to k,\n      List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := (TyMyCphr msg_to k) |} ctx\n      -> exists c_id c,\n        msg = SignedCiphertext c_id\n        /\\ cs $? c_id = Some c\n        /\\ cipher_to_user c = msg_to\n        /\\ cipher_signing_key c = k\n        /\\ fst (cipher_nonce c) = Some u_id\n        /\\ HonestKey ctx k\n        (* clauses to ensure sends aren't stuck *)\n        /\\ u_id <> msg_to\n        /\\ (exists rec_u, usrs $? msg_to = Some rec_u)\n        /\\ (exists me, usrs $? u_id = Some me\n               /\\ incl [c_id] me.(c_heap)\n               /\\ keys_mine me.(key_heap) (findKeysCrypto cs msg))\n  )\n(* /\\ (forall t msg, *)\n(*       List.In {| cmd_type := Crypto t ; cmd_val := msg ; safetyTy := TyRecvCphr |} ctx *)\n(*       -> forall kid kp, *)\n(*         findKeysCrypto cs msg $? kid = Some kp -> HonestKey ctx kid) *)\n.\n\n(* Lemma in_userids_in_usrs : *)\n(*   forall V (m : NatMap.t V) k, *)\n(*     List.In k (List.map (fun '(k,_) => k) (elements m)) *)\n(*     -> exists v, *)\n(*       m $? k = Some v. *)\n(* Proof. *)\n(* Admitted. *)\n\nLtac process_ctx1 :=\n  match goal with\n  | [ H : ?x = ?x |- _ ] => clear H\n  | [ H : Crypto _ = Crypto _ |- _ ] => invert H\n  | [ H : TyMyCphr _ _  = _ |- _ ] => invert H\n  | [ H : UPair _ _ = UPair _ _ |- _ ] => invert H\n  | [ H : (_,_) = (_,_) |- _ ] => invert H\n  | [ H : {| cmd_type := _ |} = {| cmd_type := _ |} |- _ ] => eapply safe_typ_eq in H; split_ex; subst; try discriminate\n  | [ H : _ ~= _ |- _ ] => invert H\n  | [ H : syntactically_safe _ _ _ (Return _) _ |- _ ] => invert H\n  | [ H : syntactically_safe _ _ _ _ (TyMyCphr _ _) |- _ ] => invert H\n  | [ H1 : ?m $? ?k = _ , H2 : ?m $? ?k = _ |- _ ] => clean_map_lookups\n  | [ H : List.In _ (compute_ids _) |- _] =>\n    apply in_ids_in_m in H; split_ex\n  (* | [ H : (forall _ _ _ _, List.In _ ?ctx -> exists _ _, _), ARG : List.In _ ?ctx |- _ ] => *)\n  (*   specialize (H _ _ _ _ ARG); split_ex; subst *)\n  (* | [ H : (forall _ _, List.In _ ?ctx -> exists _ _, _), ARG : List.In _ ?ctx |- _ ] => *)\n  (*   specialize (H _ _ ARG) *)\n  | [ H : (forall _ _ _ _, List.In _ ?ctx -> exists _ _, _), ARG : List.In _ ?ctx |- _ ] =>\n    eapply H in ARG; split_ex; subst\n  | [ H : (forall _ _, List.In _ ?ctx -> exists _ _, _), ARG : List.In _ ?ctx |- _ ] =>\n    eapply H in ARG; split_ex\n    (* specialize (H _ _ ARG) *)\n  | [ H : HonestKey ({| cmd_type := ?cty |} :: _) ?kid |- context [ ?kid ] ] =>\n    eapply (@HonestKey_split cty _ _ _ _ _ eq_refl) in H; split_ors\n  | [ |- incl _ (c_heap _) ] => progress simpl\n  | [ H : incl _ (c_heap _) |- _ ] => progress ( simpl in H )\n  | [ |- keys_mine (key_heap _) _ ] => progress ( simpl )\n  | [ H : keys_mine (key_heap _) _ |- _ ] => progress ( simpl in * )\n  | [ H : List.In _ (_ :: _) |- _ ] => simpl in H; split_ors\n  | [ HK : HonestKey ?ctx ?k, H : (forall _, HonestKey ?ctx _  -> _) |- _ ] =>\n    match goal with\n    | [ H : findUserKeys _ $? k = Some true |- _ ] => fail 1\n    | _ => idtac\n    end;\n    generalize (H _ HK); intros\n  (* (forall kid, HonestKey ctx kid -> (findUserKeys usrs) $? kid = Some true) *)\n  (* | [ HK : HonestKey ?ctx _, H : (forall _, HonestKey ?ctx _  -> _) |- _ ] => *)\n  (*   generalize (H _ HK); intros; clear HK *)\n  | [ H : Some _ <> None -> ?non = (Some ?uid, ?curn) |- _ ] =>\n    assert (non = (Some uid,curn)) by (eapply H; congruence); subst; clear H\n                                                                \n  | [ |- incl [?x] (?x :: _) ] =>\n    let LIN := fresh \"LIN\"\n    in  unfold incl; intros * LIN; simpl in LIN; split_ors; try contradiction; subst\n  | [ |- keys_mine _ (match _ $+ (?k1,_) $? ?k2 with _ => _ end) ] =>\n    (progress clean_map_lookups)\n    || (destruct (k1 ==n k2); subst; clean_map_lookups)\n  | [ |- keys_mine _ (match _ $+ (?k1,_) $? ?k2 with _ => _ end) ] =>\n    (progress clean_map_lookups)\n    || (destruct (k1 ==n k2); subst; clean_map_lookups)\n  | [ |- _ $k++ _ $? _ = Some true ] => solve_perm_merges\n  | [ |- exists _ _, _ ] => (do 2 eexists); repeat simple apply conj\n  | [ |- exists _, _ ] => eexists; repeat simple apply conj\n  end.\n\nLtac process_ctx := repeat process_ctx1.\n\n#[export] Hint Constructors\n     RealWorld.msg_accepted_by_pattern \n     RealWorld.msg_pattern_safe\n  : core.\n#[export] Hint Extern 1 (List.In _ _) => progress simpl : core.\n#[export] Hint Extern 1 (_ $+ (_,_) $? _ = _) => progress clean_map_lookups : core.\n#[export] Hint Extern 1 (_ $+ (?k1,_) $? ?k2 = _) =>\n  solve [ destruct (k1 ==n k2); subst; clean_map_lookups; trivial ] : core.\n\nLemma keys_mine_addln_keys :\n  forall ks1 ks2 ks3,\n    keys_mine ks1 ks3\n    -> keys_mine (ks1 $k++ ks2) ks3.\nProof.\n  unfold keys_mine; intros.\n  apply H in H0; split_ors; split_ex; subst.\n  - cases (ks2 $? k_id); destruct kp;\n      try solve [ left; solve_perm_merges ].\n    destruct b; solve_perm_merges; eauto.\n\n  - right; split; eauto.\n    solve_perm_merges.\nQed.\n\nLemma keys_mine_new_honestk :\n  forall kid ks1 ks2,\n    keys_mine ks1 ks2\n    -> keys_mine (add_key_perm kid true ks1) ks2.\nProof.\n  unfold keys_mine, add_key_perm; intros.\n  apply H in H0.\n  destruct (kid ==n k_id); subst;\n    split_ors; clean_map_lookups;\n      solve_perm_merges; eauto.\n\n  destruct kp; eauto.\nQed.\n\n#[export] Hint Resolve keys_mine_addln_keys keys_mine_new_honestk : core.\n#[export] Hint Resolve incl_appr incl_tl : core.\n\nLemma syntactically_safe_honest_keys_preservation' :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' ctx sty,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n\n      -> forall honestk cmdc cmdc' u_id usrs'' uids,\n          suid = Some u_id\n          -> uids = compute_ids usrs\n          -> syntactically_safe u_id uids ctx cmd sty\n          -> usrs $? u_id = Some {| key_heap := ks;\n                                   protocol := cmdc;\n                                   msg_heap := qmsgs;\n                                   c_heap   := mycs;\n                                   from_nons := froms;\n                                   sent_nons := sents;\n                                   cur_nonce := cur_n |}\n          -> typingcontext_sound ctx usrs cs u_id\n          -> honestk  = findUserKeys usrs\n          -> message_queue_ok honestk cs qmsgs gks\n          -> encrypted_ciphers_ok honestk cs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> honest_users_only_honest_keys usrs\n          -> usrs'' = usrs' $+ (u_id, {| key_heap := ks';\n                                        protocol := cmdc';\n                                        msg_heap := qmsgs';\n                                        c_heap   := mycs';\n                                        from_nons := froms';\n                                        sent_nons := sents';\n                                        cur_nonce := cur_n' |})\n\n          -> exists ctx',\n              List.Forall (fun styp => List.In styp ctx') ctx\n              /\\ typingcontext_sound ctx' usrs'' cs' u_id\n              /\\ syntactically_safe u_id uids ctx' cmd' sty\n.\nProof.\n  induction 1; inversion 1; inversion 1;\n    invert 3;\n    unfold typingcontext_sound;\n    intros; subst;\n      autorewrite with find_user_keys;\n      try solve [\n            split_ands; eexists; process_ctx; repeat simple apply conj; swap 1 4; intros; eauto;\n            repeat (progress (process_ctx; eauto))\n          ].\n\n  - clean_context.\n    eapply IHstep_user in H33; eauto.\n    clear IHstep_user.\n    split_ex.\n    unfold typingcontext_sound in H1; split_ands.\n    eexists; repeat simple apply conj; eauto.\n    econstructor; eauto.\n    intros.\n    eapply syntactically_safe_add_ctx; eauto.\n    econstructor; eauto.\n    rewrite Forall_forall in *; eauto.\n\n  - split_ex; clean_context.\n    (* invert H; split_ands; clean_context. *)\n    eapply H5 in H39; split_ex; subst.\n    progress clean_map_lookups.\n    eexists; process_ctx.\n    repeat simple apply conj; swap 1 4; eauto.\n    intros.\n    destruct (msg_to ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n    \n  - split_ex; eexists; process_ctx; repeat simple apply conj; swap 1 4; intros; eauto;\n      repeat (progress (process_ctx; eauto))\n      ; invert H8\n      ; clean_map_lookups.\n\n    user_cipher_queues_prop; encrypted_ciphers_prop.\n    apply H25 in H9; clean_map_lookups; eauto.\n\n    user_cipher_queues_prop; encrypted_ciphers_prop.\n    apply H25 in H9; clean_map_lookups; eauto.\n\n  - split_ex; eexists; process_ctx; repeat simple apply conj; swap 1 4; intros; eauto;\n      repeat (progress (process_ctx; eauto))\n      ; clean_map_lookups\n      ; simpl in *.\n\n    user_cipher_queues_prop; encrypted_ciphers_prop.\n    apply H20 in H4; clean_map_lookups; eauto.\nQed.\n\nLemma syntactically_safe_honest_keys_preservation :\n  forall {A B} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        cmd cmd' ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' ctx sty,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n\n      -> forall honestk u_id uids usrs'',\n          suid = Some u_id\n          -> uids = compute_ids usrs\n          -> usrs $? u_id = Some {| key_heap := ks;\n                                   protocol := cmd;\n                                   msg_heap := qmsgs;\n                                   c_heap   := mycs;\n                                   from_nons := froms;\n                                   sent_nons := sents;\n                                   cur_nonce := cur_n |}\n          -> syntactically_safe u_id uids ctx cmd sty\n          -> typingcontext_sound ctx usrs cs u_id\n          -> honestk  = findUserKeys usrs\n          -> message_queue_ok honestk cs qmsgs gks\n          -> encrypted_ciphers_ok honestk cs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> honest_users_only_honest_keys usrs\n          -> usrs'' = usrs' $+ (u_id, {| key_heap := ks';\n                                        protocol := cmd';\n                                        msg_heap := qmsgs';\n                                        c_heap   := mycs';\n                                        from_nons := froms';\n                                        sent_nons := sents';\n                                        cur_nonce := cur_n' |})\n\n          -> exists ctx',\n              List.Forall (fun styp => List.In styp ctx') ctx\n              /\\ typingcontext_sound ctx' usrs'' cs' u_id\n              /\\ syntactically_safe u_id uids ctx' cmd' sty\n.\nProof.\n  intros; subst; eapply syntactically_safe_honest_keys_preservation'; eauto.\nQed.\n\n  Lemma syntactically_safe_adv_step_preservation :\n  forall {A B C} lbl bd bd',\n\n    step_user lbl None bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' ctx sty,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n\n      -> forall u_id uids u u' cmda,\n          uids = compute_ids usrs\n          -> usrs $? u_id = Some u\n          -> usrs' $? u_id = Some u'\n          -> syntactically_safe u_id uids ctx u.(protocol) sty\n          -> typingcontext_sound ctx usrs cs u_id\n          -> adv = mkUserData ks cmda qmsgs mycs froms sents cur_n\n          -> exists ctx',\n              List.Forall (fun styp => List.In styp ctx') ctx\n              /\\ typingcontext_sound ctx' usrs' cs' u_id\n              /\\ syntactically_safe u_id uids ctx' u'.(protocol) sty\n.\nProof.\n  induction 1; inversion 1; inversion 1;\n    intros;\n    subst;\n    clean_map_lookups;\n    simpl in *;\n    eauto.\n\n  - destruct (rec_u_id ==n u_id); subst; clean_map_lookups; simpl.\n    \n    + eexists; repeat simple apply conj; swap 1 3; eauto.\n      unfold typingcontext_sound in *; split_ex; repeat simple apply conj; process_ctx; eauto; intros.\n      autorewrite with find_user_keys; process_ctx; eauto.\n      destruct (u_id ==n msg_to);\n        subst; clean_map_lookups; process_ctx; eauto.\n\n    +  eexists; repeat simple apply conj; swap 1 3; eauto.\n       unfold typingcontext_sound in *; split_ex; repeat simple apply conj; process_ctx; eauto; intros.\n       autorewrite with find_user_keys; process_ctx; eauto.\n       destruct (rec_u_id ==n msg_to);\n         subst; clean_map_lookups; process_ctx; eauto.\n\n  - eexists; repeat simple apply conj; swap 1 3; eauto.\n    unfold typingcontext_sound in *; split_ex; repeat simple apply conj; process_ctx; eauto; intros.\n    process_ctx; eauto.\n\n  - eexists; repeat simple apply conj; swap 1 3; eauto.\n    unfold typingcontext_sound in *; split_ex; repeat simple apply conj; process_ctx; eauto; intros.\n    process_ctx; eauto.\n\nQed.\n\nDefinition syntactically_safe_U {A B} (U : universe A B) :=\n  forall uid u uids,\n    U.(users) $? uid = Some u\n    -> uids = compute_ids U.(users)\n    -> exists sty ctx,\n      syntactically_safe uid uids ctx u.(protocol) sty\n      /\\ typingcontext_sound ctx U.(users) U.(all_ciphers) uid.\n\nLemma syntactically_safe_na :\n  forall A uid uids ctx (p : user_cmd A) sty,\n    syntactically_safe uid uids ctx p sty\n    -> forall B (p__n : user_cmd B),\n      nextAction p p__n\n      -> exists sty', syntactically_safe uid uids ctx p__n sty'.\nProof.\n  induction 1; try solve [ invert 1; eauto ]; intros.\nQed.\n\nLemma typingcontext_sound_ok_nochange_usrs_ks_mycs :\n  forall A (usrs : honest_users A) uid uid' cs ks cmd qmsgs mycs froms sents n ctx,\n    usrs $? uid = Some (mkUserData ks cmd qmsgs mycs froms sents n)\n    -> typingcontext_sound ctx usrs cs uid'\n    -> forall cmd' qmsgs' froms' sents' n',\n        typingcontext_sound ctx\n                            (usrs $+ (uid, mkUserData ks cmd' qmsgs' mycs froms' sents' n'))\n                            cs uid'.\nProof.\n  unfold typingcontext_sound; intros; eauto.\n  destruct (uid ==n uid'); subst; clean_map_lookups;\n    autorewrite with find_user_keys; split_ands; repeat simple apply conj; eauto.\n  \n  intros * LIN;\n    eapply H1 in LIN; split_ex; subst;\n      process_ctx; eauto.\n\n  intros * LIN;\n    eapply H1 in LIN; split_ex; subst; eauto.\n\n  destruct (uid ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n    process_ctx; eauto.\nQed.\n\n#[export] Hint Resolve typingcontext_sound_ok_nochange_usrs_ks_mycs : core.\n\nLemma typingcontext_sound_other_user_step :\n  forall {A B C} suid lbl bd bd',\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n',\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> message_queues_ok cs usrs gks\n      -> encrypted_ciphers_ok (findUserKeys usrs) cs gks\n      -> user_cipher_queues_ok cs (findUserKeys usrs) usrs\n      -> forall cmdc cmdc' u_id1 u_id2 ctx ctx__step sty, \n          suid = Some u_id1\n          -> u_id1 <> u_id2\n          -> usrs $? u_id1 = Some {| key_heap := ks;\n                                    protocol := cmdc;\n                                    msg_heap := qmsgs;\n                                    c_heap   := mycs;\n                                    from_nons := froms;\n                                    sent_nons := sents;\n                                    cur_nonce := cur_n |}\n          -> syntactically_safe u_id1 (compute_ids usrs) ctx__step cmd sty\n          -> typingcontext_sound ctx__step usrs cs u_id1\n          -> typingcontext_sound ctx usrs cs u_id2\n          -> typingcontext_sound ctx (usrs' $+ (u_id1,\n                                               mkUserData ks' cmdc' qmsgs' mycs' froms' sents' cur_n')) cs' u_id2.\nProof.\n  induction 1; inversion 1; inversion 1;\n    intros; subst; autorewrite with find_user_keys; eauto.\n\n  - invert H30; eauto.\n  - msg_queue_prop.\n    unfold typingcontext_sound in *; repeat simple apply conj; intros; split_ands; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n    \n    assert (msg_pattern_safe (findUserKeys usrs') pat) by (invert H38; eauto).\n    assert (msg_honestly_signed (findUserKeys usrs') cs' msg = true) by eauto.\n    unfold msg_honestly_signed in H13.\n    destruct (msg_signing_key cs' msg); try discriminate.\n    rewrite <- honest_key_honest_keyb in H13.\n    specialize (H2 _ eq_refl); split_ands.\n    specialize (H14 H13); split_ands.\n    eapply H5 in H3; split_ex; subst.\n    destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups;\n      process_ctx; eauto.\n\n  - destruct (rec_u_id ==n u_id1); subst; clean_map_lookups; eauto.\n\n    unfold typingcontext_sound in *; split_ands; split; intros; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n\n    eapply H4 in H9; split_ex; subst.\n\n    destruct (rec_u_id ==n u_id2);\n    destruct (rec_u_id ==n cipher_to_user x0);\n      destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n\n  - unfold typingcontext_sound in *; split_ands; split; intros; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n    eapply H7 in H12; split_ex; subst.\n    destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n\n  - user_cipher_queues_prop.\n    encrypted_ciphers_prop.\n\n    unfold typingcontext_sound in *; repeat simple apply conj; intros; split_ands; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n\n    eapply H10 in H4; split_ex; subst.\n    destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n\n  - unfold typingcontext_sound in *; split_ands; split; intros; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n    apply H5 in H10; eauto; split_ex; subst.\n    destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n    \n  - unfold typingcontext_sound in *; split_ands; split; intros; eauto.\n    autorewrite with find_user_keys; process_ctx; eauto.\n    eapply H1 in H6; split_ex; subst.\n    destruct (u_id1 ==n cipher_to_user x0); subst; clean_map_lookups; eauto;\n      process_ctx; eauto.\n\nQed.\n\nSection PredicatePreservation.\n  Import RealWorld.\n\n  Hint Resolve\n       encrypted_cipher_ok_addnl_cipher\n       encrypted_cipher_ok_addnl_key\n       encrypted_cipher_ok_addnl_honest_key\n       encrypted_ciphers_ok_new_honest_key_adv_univ\n       users_permission_heaps_good_merged_permission_heaps_good\n       : core.\n\n  Lemma silent_user_step_encrypted_ciphers_ok :\n    forall {A B C} cs cs' u_id suid lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> forall (cmd : user_cmd C) honestk ctx styp uids,\n          bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> honestk = findUserKeys usrs\n          -> uids = compute_ids usrs\n          -> encrypted_ciphers_ok (findUserKeys usrs) cs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> keys_and_permissions_good gks usrs adv.(key_heap)\n          -> syntactically_safe u_id uids ctx cmd styp\n          -> typingcontext_sound ctx usrs cs u_id\n          -> lbl = Silent\n          -> forall cmd' usrs'',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> forall cmdc cmdc' honestk',\n                usrs $? u_id = Some {| key_heap := ks ; msg_heap := qmsgs ; protocol := cmdc\n                                       ; c_heap := mycs ; from_nons := froms ; sent_nons := sents ; cur_nonce := cur_n |}\n                -> usrs'' = usrs' $+ (u_id, {| key_heap := ks'; protocol := cmdc'; msg_heap := qmsgs'\n                                              ; c_heap := mycs' ; from_nons := froms' ; sent_nons := sents' ; cur_nonce := cur_n' |})\n                -> honestk' = findUserKeys usrs''\n                -> encrypted_ciphers_ok honestk' cs' gks'.\n  Proof.\n    induction 1; inversion 2; invert 6; inversion 3; intros; subst;\n      try discriminate;\n      eauto 2;\n      autorewrite with find_user_keys in *;\n      try keys_and_permissions_prop;\n      clean_context;\n      eauto.\n\n    - unfold typingcontext_sound in *; split_ex.\n      econstructor; eauto.\n      eapply SigEncCipherHonestSignedEncKeyHonestOk; eauto.\n      unfold encrypted_ciphers_ok in *; rewrite Forall_natmap_forall in *; intros; eauto.\n      \n    - user_cipher_queues_prop; encrypted_ciphers_prop.\n      rewrite merge_keys_addnl_honest; eauto.\n    - unfold typingcontext_sound in *; split_ex.\n      econstructor; eauto.\n      econstructor; eauto.\n      intros * FKM.\n      eapply H33 in FKM; split_ex; eauto.\n      unfold encrypted_ciphers_ok in *; rewrite Forall_natmap_forall in *; intros; eauto.\n\n    - eapply encrypted_ciphers_ok_new_honest_key_adv_univ with (honestk := (findUserKeys usrs'));\n        simpl; eauto; simpl; eauto.\n  Qed.\n\n  Hint Resolve\n       honest_users_only_honest_keys_nochange_keys\n       honest_users_only_honest_keys_gen_key\n    : core.\n\n  Lemma honest_users_only_honest_keys_honest_steps :\n    forall {A B C} u_id suid cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> forall (cmd : user_cmd C) honestk uids,\n          honestk = findUserKeys usrs\n          -> uids = compute_ids usrs\n          -> bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> honest_users_only_honest_keys usrs\n          -> forall ctx styp, syntactically_safe u_id uids ctx cmd styp\n          -> typingcontext_sound ctx usrs cs u_id\n          (* -> next_cmd_safe (findUserKeys usrs) cs u_id froms sents cmd *)\n          -> encrypted_ciphers_ok honestk cs gks\n          -> user_cipher_queues_ok  cs honestk usrs\n          -> forall cmd',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> forall cmdc cmdc' usrs'',\n                usrs $? u_id = Some {| key_heap := ks\n                                       ; msg_heap := qmsgs\n                                       ; protocol := cmdc\n                                       ; c_heap := mycs\n                                       ; from_nons := froms\n                                       ; sent_nons := sents\n                                       ; cur_nonce := cur_n |}\n                -> usrs'' = usrs' $+ (u_id, {| key_heap := ks'\n                                              ; msg_heap := qmsgs'\n                                              ; protocol := cmdc'\n                                              ; c_heap := mycs'\n                                              ; from_nons := froms'\n                                              ; sent_nons := sents'\n                                              ; cur_nonce := cur_n' |})\n                -> honest_users_only_honest_keys usrs''.\n  Proof.\n    induction 1; inversion 4; inversion 6; intros;\n      subst;\n      autorewrite with find_user_keys.\n\n    invert H16.\n    eapply IHstep_user in H8; eauto.\n\n    all : eauto; clean_context.\n\n    - unfold honest_users_only_honest_keys in *; intros.\n      destruct (u_id ==n u_id0); subst; clean_map_lookups; eauto;\n        simpl in *;\n        rewrite findUserKeys_readd_user_addnl_keys; eauto.\n\n      specialize (H12 _ _ H29); simpl in *.\n\n      assert (msg_pattern_safe (findUserKeys usrs') pat) by\n          (unfold typingcontext_sound in *; split_ex; invert H24; eauto).\n      \n      solve_perm_merges;\n        try\n          match goal with\n          | [ H : (forall _ _, ?ks $? _ = Some _ -> _), ARG : ?ks $? _ = Some _ |- _ ] => specialize (H _ _ ARG)\n          end; clean_map_lookups; eauto;\n          assert (msg_honestly_signed (findUserKeys usrs') cs' msg = true) as MHS by eauto.\n\n      + generalize (msg_honestly_signed_has_signing_key_cipher_id _ _ _ MHS); intros; split_ands; split_ex.\n        eapply msg_honestly_signed_signing_key_honest in MHS; eauto.\n        unfold msg_cipher_id in H2; destruct msg; try discriminate;\n          clean_context; simpl in *.\n        cases (cs' $? c_id); try discriminate.\n        clean_context; invert MHS.\n        destruct c; simpl in *; clean_map_lookups; eauto.\n        encrypted_ciphers_prop; eauto.\n        specialize (H14 _ _ H1); split_ands; subst; clean_map_lookups; eauto.\n\n      + generalize (msg_honestly_signed_has_signing_key_cipher_id _ _ _ MHS); intros; split_ands; split_ex.\n        eapply msg_honestly_signed_signing_key_honest in MHS; eauto.\n        unfold msg_cipher_id in H2; destruct msg; try discriminate;\n          clean_context; simpl in *.\n        cases (cs' $? c_id); try discriminate.\n        clean_context; invert MHS.\n        destruct c; simpl in *; clean_map_lookups; eauto.\n        encrypted_ciphers_prop; eauto.\n        specialize (H14 _ _ H1); split_ands; subst; clean_map_lookups; eauto.\n\n      + eapply H12 in H0; eauto.\n        solve_perm_merges; eauto.\n\n    - unfold honest_users_only_honest_keys in *; intros.\n      assert (rec_u_id <> u_id) by (unfold not; intros; subst; contradiction).\n      destruct (u_id ==n u_id0); destruct (u_id ==n rec_u_id);\n        subst;\n        try contradiction;\n        clean_map_lookups;\n        simpl in *;\n        eauto.\n\n      + generalize H28; intros; eapply H11 in H28; eauto.\n        autorewrite with find_user_keys; eauto.\n\n      + destruct (u_id0 ==n rec_u_id); subst;\n          clean_map_lookups;\n          autorewrite with find_user_keys;\n          eauto 2.\n\n    - unfold typingcontext_sound in *; split_ex.\n      user_cipher_queues_prop.\n      encrypted_ciphers_prop; clean_map_lookups.\n      unfold honest_users_only_honest_keys in *; intros.\n      autorewrite with find_user_keys.\n      destruct (u_id ==n u_id0);\n        subst;\n        try contradiction;\n        clean_map_lookups;\n        simpl in *;\n        eauto.\n\n      specialize (H12 _ _ H29); simpl in *.\n      apply merge_perms_split in H9; split_ors;\n        match goal with\n        | [ ARG : findKeysMessage _ $? _ = Some _, H : (forall _ _, findKeysMessage _ $? _ = Some _ -> _) |- _ ] =>\n          specialize (H _ _ ARG)\n        | [ H : (forall _ _, ?ks $? _ = Some _ -> _), ARG : ?ks $? _ = Some _ |- _ ] => specialize (H _ _ ARG)\n        end; solve_perm_merges; eauto.\n      \n      eapply H12 in H6; eauto; solve_perm_merges; eauto.\n  Qed.\n\n  Lemma honest_labeled_step_encrypted_ciphers_ok :\n    forall {A B C} cs cs' u_id suid lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd' a,\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> message_queues_ok cs usrs gks\n      -> encrypted_ciphers_ok (findUserKeys usrs) cs gks\n      -> forall (cmd : user_cmd C),\n          bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> forall ctx styp uids, syntactically_safe u_id uids ctx cmd styp\n          -> typingcontext_sound ctx usrs cs u_id\n          -> uids = compute_ids usrs\n          -> lbl = Action a\n          -> forall cmd',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> forall cmdc cmdc' usrs'' ud',\n                usrs $? u_id = Some {| key_heap := ks ; msg_heap := qmsgs ; protocol := cmdc ; c_heap := mycs ; from_nons := froms ; sent_nons := sents ; cur_nonce := cur_n |}\n                -> ud' = {| key_heap := ks'; protocol := cmdc'; msg_heap := qmsgs' ; c_heap := mycs' ; from_nons := froms' ; sent_nons := sents' ; cur_nonce := cur_n' |}\n                -> usrs'' = usrs' $+ (u_id, ud')\n                -> encrypted_ciphers_ok (findUserKeys usrs'') cs' gks'.\n  Proof.\n    induction 1; inversion 4; inversion 5; intros; subst; try discriminate;\n      eauto 2; autorewrite with find_user_keys;\n        clean_context; eauto.\n\n    invert H4.\n    eapply IHstep_user in H9; eauto.\n\n    unfold typingcontext_sound in *; split_ex.\n    assert (msg_pattern_safe (findUserKeys usrs') pat) by\n        (unfold typingcontext_sound in *; split_ex; invert H12; eauto).\n    msg_queue_prop; eapply encrypted_ciphers_ok_addnl_pubk; auto.\n    specialize_msg_ok; eauto.\n  Qed.\n\n  Lemma honest_labeled_step_user_cipher_queues_ok_ss :\n    forall {A B C} u_id cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd' a suid,\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> forall (cmd : user_cmd C) honestk,\n          bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> honestk = findUserKeys usrs\n          -> message_queues_ok cs usrs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> forall cmd' honestk',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> lbl = Action a\n              -> forall ctx styp uids, syntactically_safe u_id uids ctx cmd styp\n              -> typingcontext_sound ctx usrs cs u_id\n              -> uids = compute_ids usrs\n              -> forall cmdc cmdc' usrs'',\n                  usrs $? u_id = Some {| key_heap := ks ; msg_heap := qmsgs ; protocol := cmdc ; c_heap := mycs ; from_nons := froms ; sent_nons := sents ; cur_nonce := cur_n |}\n                  -> usrs'' = usrs' $+ (u_id, {| key_heap := ks' ; msg_heap := qmsgs' ; protocol := cmdc' ; c_heap := mycs' ; from_nons := froms' ; sent_nons := sents' ; cur_nonce := cur_n' |})\n                  -> honestk' = findUserKeys usrs''\n                  -> user_cipher_queues_ok cs' honestk' usrs''.\n  Proof.\n    induction 1; inversion 2; inversion 4; intros; subst; try discriminate; eauto;\n      autorewrite with find_user_keys; clean_context.\n\n    - invert H29.\n      eapply IHstep_user in H6; eauto.\n\n    - assert (msg_pattern_safe (findUserKeys usrs') pat) by\n          (unfold typingcontext_sound in *; split_ex; invert H37; eauto).\n\n      msg_queue_prop; eauto.\n      specialize_msg_ok.\n      eapply user_cipher_queues_ok_add_user; autorewrite with find_user_keys; eauto.\n\n    - remember ((usrs $+ (rec_u_id,\n                          {| key_heap := key_heap rec_u;\n                             protocol := protocol rec_u;\n                             msg_heap := msg_heap rec_u ++ [existT crypto t0 msg];\n                             c_heap := c_heap rec_u |}))) as usrs'.\n\n      assert (findUserKeys usrs = findUserKeys usrs') as RW\n          by (subst; autorewrite with find_user_keys; eauto).\n\n      rewrite RW; clear RW.\n      destruct rec_u; simpl in *.\n      eapply user_cipher_queues_ok_readd_user; subst; clean_map_lookups; eauto.\n      autorewrite with find_user_keys.\n      eapply user_cipher_queues_ok_readd_user; subst; clean_map_lookups; eauto.\n  Qed.\n\n  Lemma honest_labeled_step_message_queues_ok_ss :\n    forall {A B C} u_id suid cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd' a,\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> forall (cmd : user_cmd C) honestk,\n          bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> honestk = findUserKeys usrs\n          -> message_queues_ok cs usrs gks\n          -> keys_and_permissions_good gks usrs adv.(key_heap)\n          -> encrypted_ciphers_ok honestk cs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> forall cmd' honestk',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> lbl = Action a\n              -> forall ctx styp uids, syntactically_safe u_id uids ctx cmd styp\n              -> typingcontext_sound ctx usrs cs u_id\n              -> uids = compute_ids usrs\n              -> forall cmdc cmdc' usrs'',\n                  usrs $? u_id = Some {| key_heap := ks ; msg_heap := qmsgs ; protocol := cmdc\n                                         ; c_heap := mycs ; from_nons := froms ; sent_nons := sents ; cur_nonce := cur_n |}\n                  -> usrs'' = usrs' $+ (u_id, {| key_heap := ks' ; msg_heap := qmsgs' ; protocol := cmdc'\n                                                ; c_heap := mycs' ; from_nons := froms' ; sent_nons := sents' ; cur_nonce := cur_n' |})\n                  -> honestk' = findUserKeys usrs''\n                  -> message_queues_ok cs' usrs'' gks'.\n  Proof.\n    induction 1; inversion 2; inversion 6; intros; subst; try discriminate;\n      eauto 2; autorewrite with find_user_keys; eauto;\n        clean_context; msg_queue_prop; specialize_msg_ok; eauto.\n\n    - invert H31.\n      eapply IHstep_user in H7; eauto.\n\n    - assert (msg_pattern_safe (findUserKeys usrs') pat) by\n          (unfold typingcontext_sound in *; split_ex; invert H39; eauto).\n\n      unfold message_queues_ok in *; rewrite Forall_natmap_forall in *; intros;\n        autorewrite with find_user_keys in *.\n\n      assert (msg_honestly_signed (findUserKeys usrs') cs' msg = true) by eauto.\n      eapply message_honestly_signed_msg_signing_key_honest in H5; split_ex.\n      specialize_simply.\n      rewrite honestk_merge_new_msgs_keys_same; eauto.\n      destruct (u_id ==n k); subst; clean_map_lookups; eauto.\n\n    - unfold message_queues_ok in *; rewrite Forall_natmap_forall in *; intros;\n        autorewrite with find_user_keys in *.\n      assert (rec_u_id <> u_id) by (unfold not; intros; subst; contradiction).\n\n      unfold typingcontext_sound in *; split_ex.\n      invert H38.\n\n      destruct (rec_u_id ==n k);\n        destruct (u_id ==n k);\n        subst;\n        clean_map_lookups;\n        simpl;\n        eauto.\n\n      eapply H7 in H13; split_ex; subst.\n      eapply H21 in H2; unfold message_queue_ok in H2.\n      eapply Forall_app; simpl; econstructor; eauto.\n\n      eapply H6 in H12.\n      keys_and_permissions_prop.\n\n      encrypted_ciphers_prop;\n        repeat simple apply conj;\n        intros;\n        simpl in *;\n        context_map_rewrites;\n        clean_map_lookups;\n        eauto.\n\n      + eapply H27 in H20; split_ex; subst.\n        eapply H18 in H15; split_ex; clean_map_lookups.\n\n      + simpl in *; context_map_rewrites.\n        repeat simple apply conj; intros; eauto.\n        discriminate.\n        unfold message_no_adv_private; simpl.\n        context_map_rewrites.\n        split; intros; eauto.\n        apply H27 in H20; split_ex; auto.\n\n      + simpl in *; context_map_rewrites.\n        repeat simple apply conj; intros; eauto.\n        discriminate.\n        unfold message_no_adv_private; simpl.\n        context_map_rewrites.\n        split; intros\n        ; clean_map_lookups.\n  Qed.\n\n  Definition adv_goodness {A} (usrs : honest_users A)\n             (cs : ciphers) (gks : keys) (msgs : queued_messages) (mycs : my_ciphers) :=\n    Forall (fun sigm => match sigm with\n                     | (existT _ _ m) =>\n                       (* (forall cid, msg_cipher_id m = Some cid -> cs $? cid <> None) *)\n                       (forall k kp,\n                           findKeysCrypto cs m $? k = Some kp\n                           -> gks $? k <> None /\\ (kp = true -> (findUserKeys usrs) $? k <> Some true))\n                     (* /\\ (forall k, *)\n                     (*       msg_signing_key cs m = Some k *)\n                     (*       -> gks $? k <> None) *)\n                     /\\ (forall c_id, List.In c_id (findCiphers m) -> exists c, cs $? c_id = Some c)\n                     end) msgs\n  /\\ Forall (fun cid => exists c, cs $? cid = Some c) mycs.\n\n  Lemma adv_step_adv_no_honest_keys_ss :\n    forall {A B C} cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n      step_user lbl None bd bd'\n      -> forall (cmd : user_cmd C) honestk,\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> honestk = findUserKeys usrs\n        -> ks = adv.(key_heap)\n        -> mycs = adv.(c_heap)\n        -> encrypted_ciphers_ok honestk cs gks\n        -> adv_no_honest_keys honestk ks\n        -> keys_and_permissions_good gks usrs ks\n        -> adv_goodness usrs cs gks qmsgs mycs\n        -> forall cmd' honestk',\n            bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n            -> honestk' = findUserKeys usrs'\n            -> adv_no_honest_keys honestk' ks'.\n  Proof.\n    induction 1; inversion 1; inversion 8; intros; subst;\n      eauto 2; autorewrite with find_user_keys; eauto;\n        try rewrite add_key_perm_add_private_key; clean_context;\n          match goal with\n          | [ H : keys_and_permissions_good _ _ _ |- _ ] => unfold keys_and_permissions_good in H; split_ands\n          end.\n\n    - invert H26; split_ex.\n      eapply break_msg_queue_prop in H2; split_ex.\n      unfold adv_no_honest_keys in *; intros.\n      specialize (H24 k_id); intuition idtac.\n      right; right; intuition eauto.\n      eapply merge_perms_split in H9; split_ors; auto.\n      eapply H2 in H9; split_ex; eauto.\n      \n    - assert (adv_no_honest_keys (findUserKeys usrs') (key_heap adv')) as ADV by assumption.\n      specialize (ADV k__encid); split_ors; split_ands; try contradiction;\n        encrypted_ciphers_prop; clean_map_lookups; intuition idtac;\n          unfold adv_no_honest_keys; intros;\n            specialize (H24 k_id); clean_map_lookups; intuition idtac;\n              right; right; split; eauto; intros;\n                eapply merge_perms_split in H10; split_ors;\n                  try contradiction;\n                  specialize (H19 _ _ H10); split_ex; split_ands; eauto.\n\n    - eapply adv_no_honest_keys_after_new_adv_key; eauto.\n\n  Qed.\n\n  Lemma honest_labeled_step_adv_no_honest_keys_ss :\n    forall {A B C} u_id suid cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd' a,\n      step_user lbl suid bd bd'\n      -> suid = Some u_id\n      -> forall (cmd : user_cmd C) honestk,\n          bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n          -> honestk = findUserKeys usrs\n          -> message_queues_ok cs usrs gks\n          -> encrypted_ciphers_ok honestk cs gks\n          -> user_cipher_queues_ok cs honestk usrs\n          -> adv_no_honest_keys honestk adv.(key_heap)\n          -> forall cmd' honestk',\n              bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n              -> lbl = Action a\n              -> forall ctx styp uids, syntactically_safe u_id uids ctx cmd styp\n              -> typingcontext_sound ctx usrs cs u_id\n              -> uids = compute_ids usrs\n              -> forall cmdc cmdc' usrs'',\n                  usrs $? u_id = Some (mkUserData ks cmdc qmsgs mycs froms sents cur_n)\n                  -> usrs'' = usrs' $+ (u_id, mkUserData ks' cmdc' qmsgs' mycs' froms' sents' cur_n')\n                  -> honestk' = findUserKeys usrs''\n                  -> adv_no_honest_keys honestk' adv'.(key_heap).\n  Proof.\n    induction 1; inversion 2; inversion 6; intros; subst;\n      try discriminate;\n      autorewrite with find_user_keys;\n      clean_context.\n\n    - invert H31.\n      eapply IHstep_user in H6; eauto.\n\n    - assert (msg_pattern_safe (findUserKeys usrs') pat) by (unfold typingcontext_sound in *; split_ex; invert H39; eauto).\n      msg_queue_prop; specialize_msg_ok;\n        unfold adv_no_honest_keys, message_no_adv_private in *;\n        simpl in *;\n        repeat\n          match goal with\n          | [ RW : honest_keyb ?honk ?kid = _ , H : if honest_keyb ?honk ?kid then _ else _ |- _] => rewrite RW in H\n          | [ H : (forall k_id, findUserKeys _ $? k_id = None \\/ _) |- (forall k_id, _) ] => intro KID; specialize (H KID)\n          | [ |- context [ _ $k++ $0 ] ] => rewrite merge_keys_right_identity\n          | [ FK : findKeysCrypto _ ?msg $? ?kid = Some _, H : (forall k p, findKeysCrypto _ ?msg $? k = Some p -> _)\n              |- context [ _ $k++ findKeysCrypto _ ?msg $? ?kid] ] => specialize (H _ _ FK); split_ands; try solve_perm_merges\n          | [ FK : findKeysCrypto _ ?msg $? ?kid = None |- context [ ?uks $k++ findKeysCrypto _ ?msg $? ?kid] ] =>\n            split_ors; split_ands; solve_perm_merges\n          | [ H : (forall k p, findKeysCrypto _ ?msg $? k = Some p -> _)  |- context [ _ $k++ findKeysCrypto ?cs ?msg $? ?kid] ] =>\n            match goal with\n            | [ H : findKeysCrypto cs msg $? kid = _ |- _ ] => fail 1\n            | _ => cases (findKeysCrypto cs msg $? kid)\n            end\n          end; eauto.\n\n      split_ors; split_ands; contra_map_lookup; eauto.\n\n    - unfold typingcontext_sound in *; split_ex; invert H38; process_ctx.\n      unfold adv_no_honest_keys in *; intros.\n      specialize (H24 k_id).\n      split_ex; subst; simpl in *.\n      assert (List.In x mycs') by eauto.\n      user_cipher_queues_prop.\n      rewrite CipherTheory.cipher_honestly_signed_honest_keyb_iff in H12.\n      encrypted_ciphers_prop; eauto.\n      intuition idtac.\n      right; right; split; eauto; intros.\n      solve_perm_merges;\n        specialize (H17 _ _ H13); split_ex; discriminate.\n  Qed.\n\n  Hint Resolve\n       permission_heap_good_addnl_key\n       permission_heap_good_new_key_perm\n    : core.\n\n  Lemma adv_step_keys_good_ss :\n    forall {A B C} cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n      step_user lbl None bd bd'\n      -> forall (cmd : user_cmd C),\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> ks = adv.(key_heap)\n        -> mycs = adv.(c_heap)\n        -> adv_goodness usrs cs gks qmsgs mycs\n        -> encrypted_ciphers_ok (findUserKeys usrs) cs gks\n        -> keys_and_permissions_good gks usrs ks\n        -> forall cmd',\n            bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n            -> keys_and_permissions_good gks' usrs' ks'.\n  Proof.\n    induction 1; inversion 1; inversion 6; intros; subst; try discriminate;\n      eauto; clean_context.\n\n    - unfold keys_and_permissions_good in *; intuition eauto.\n      unfold permission_heap_good in *; intros.\n      cases (key_heap adv' $? k_id); eauto.\n      hnf in H22; split_ex.\n      eapply break_msg_queue_prop in H3; split_ex.\n      cases (findKeysCrypto cs' msg $? k_id); solve_perm_merges.\n      specialize (H3 _ _ H9); split_ex; subst.\n      cases (gks' $? k_id); try contradiction; eauto.\n    - destruct rec_u; simpl in *.\n      eapply keys_and_permissions_good_readd_user_same_perms; eauto.\n    - unfold keys_and_permissions_good in *; intuition eauto.\n      unfold permission_heap_good in *; intros.\n      eapply merge_perms_split in H5; split_ors; eauto.\n      encrypted_ciphers_prop; clean_map_lookups; eauto.\n      + specialize_msg_ok; split_ex; intuition eauto.\n      + assert (permission_heap_good gks' (findUserKeys usrs')) by eauto.\n        specialize_msg_ok; subst.\n        specialize (H9 _ _ H20); eauto.\n\n    - unfold keys_and_permissions_good in *; intuition eauto.\n      destruct (k_id ==n k_id0); subst; clean_map_lookups; eauto.\n      rewrite Forall_natmap_forall in *; intros; eauto.\n  Qed.\n\n  Hint Resolve\n       message_queues_ok_addnl_cipher\n       message_queues_ok_addnl_adv_key\n       message_queues_ok_addnl_honest_key\n    : core.\n\n  Lemma adv_step_message_queues_ok_ss :\n    forall {A B C} cs cs' lbl (usrs usrs' : honest_users A) (adv adv' : user_data B)\n      gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' bd bd',\n      step_user lbl None bd bd'\n      -> forall (cmd : user_cmd C) honestk,\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> honestk = findUserKeys usrs\n        -> ks = adv.(key_heap)\n        -> qmsgs = adv.(msg_heap)\n        -> mycs = adv.(c_heap)\n        -> encrypted_ciphers_ok honestk cs gks\n        -> message_queues_ok cs usrs gks\n        -> permission_heap_good gks honestk\n        -> permission_heap_good gks ks\n        -> adv_goodness usrs cs gks qmsgs mycs\n        -> forall cmd' honestk',\n            bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n            -> honestk' = findUserKeys usrs'\n            -> message_queues_ok cs' usrs' gks'.\n  Proof.\n    induction 1; inversion 1; inversion 10; intros; subst;\n      eauto 2; try discriminate; eauto;\n        clean_context.\n    \n    unfold message_queues_ok in *;\n      rewrite Forall_natmap_forall in *;\n      intros.\n\n    destruct (rec_u_id ==n k); subst; clean_map_lookups;\n      eauto;\n      autorewrite with find_user_keys;\n      simpl; eauto.\n\n    unfold message_queue_ok; eapply Forall_app.\n    unfold message_queue_ok in *; econstructor; eauto.\n\n    repeat (apply conj); intros; eauto.\n    - specialize (H0 _ _ H); split_ors; split_ands; subst; eauto.\n      specialize (H26 _ _ H0); unfold not; intros; split_ex; contra_map_lookup.\n      specialize (H26 _ _ H0); unfold not; intros; split_ex; contra_map_lookup.\n    - unfold not; intros.\n      unfold keys_mine in *.\n      destruct msg; simpl in *; try discriminate; clean_context.\n\n      unfold adv_goodness in *; split_ex.\n      rewrite Forall_forall in H5.\n\n      assert (List.In cid (c_heap adv)) as LIN by eauto.\n      specialize (H5 _ LIN); split_ex; split_ands; contra_map_lookup.\n    - unfold msg_signing_key in *; destruct msg; try discriminate;\n        cases (cs' $? c_id); try discriminate;\n          clean_context.\n      simpl in *; context_map_rewrites.\n\n      encrypted_ciphers_prop; simpl in *; eauto;\n        clean_context; intuition clean_map_lookups; eauto;\n          unfold message_no_adv_private; intros; simpl in *; context_map_rewrites;\n            repeat\n              match goal with\n              | [ ARG : findKeysMessage ?msg $? _ = Some ?b |- _ ] => is_var b; destruct b\n              | [ H : (forall k, findKeysMessage ?msg $? k = Some ?b -> _), ARG : findKeysMessage ?msg $? _ = Some ?b |- _ ] =>\n                specialize (H _ ARG)\n              | [ H : honest_key ?honk ?k, H2 : ?honk $? ?k = Some true -> False |- _ ] => invert H; contradiction\n              end; try contradiction; clean_map_lookups; eauto.\n  Qed.\n\n  Lemma honest_step_adv_goodness :\n    forall {A B C} suid lbl bd bd',\n      step_user lbl suid bd bd'\n\n      -> forall u_id cs cs' (usrs usrs' : honest_users A) (adv adv' : user_data B) (cmd cmd' : user_cmd C)\n          gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n',\n\n        suid = Some u_id\n        -> bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> message_queues_ok cs usrs gks\n        -> encrypted_ciphers_ok (findUserKeys usrs) cs gks\n        -> user_cipher_queues_ok cs (findUserKeys usrs) usrs\n        -> keys_and_permissions_good gks usrs adv.(key_heap)\n        -> adv_goodness usrs cs gks adv.(msg_heap) adv.(c_heap)\n        -> forall ctx styp uids, syntactically_safe u_id uids ctx cmd styp\n        -> typingcontext_sound ctx usrs cs u_id\n        -> uids = compute_ids usrs\n        -> forall cmdc cmdc' usrs'',\n            usrs $? u_id = Some (mkUserData ks cmdc qmsgs mycs froms sents cur_n)\n            -> usrs'' = usrs' $+ (u_id, mkUserData ks' cmdc' qmsgs' mycs' froms' sents' cur_n')\n            -> adv_goodness usrs'' cs' gks' adv'.(msg_heap) adv'.(c_heap).\n\n  Proof.\n    induction 1; inversion 2; inversion 1; intros; subst;\n      eauto;\n      unfold adv_goodness in *;\n      autorewrite with find_user_keys; eauto;\n        clean_context.\n\n    - invert H30.\n      eapply IHstep_user in H6; eauto.\n\n    - assert (msg_pattern_safe (findUserKeys usrs') pat)\n        by (unfold typingcontext_sound in *; invert H38; split_ex; eauto).\n      assert (msg_honestly_signed (findUserKeys usrs') cs' msg = true) by eauto.\n      split_ex; split; eauto.\n      generalize H0; intros; eapply msg_honestly_signed_has_signing_key_cipher_id in H0; split_ex.\n      msg_queue_prop.\n      specialize_msg_ok.\n      rewrite honestk_merge_new_msgs_keys_same; eauto.\n\n    - simpl; autorewrite with find_user_keys.\n      unfold typingcontext_sound in *; invert H37; split_ex.\n      process_ctx.\n\n      split_ex; split; eauto.\n      rewrite Forall_app; econstructor; eauto.\n      split; intros; eauto.\n\n      + encrypted_ciphers_prop; simpl in *; clean_map_lookups.\n        eapply H18 in H9; split_ex; subst; eauto.\n        keys_and_permissions_prop.\n        specialize (H20 _ _ H9); split_ex.\n        unfold not; split; intros; clean_map_lookups.\n\n      + simpl in *; split_ors; subst; try contradiction; eauto.\n\n    - rewrite !Forall_forall in *; split_ex; split; intros; eauto.\n\n      + destruct x; intros; eauto.\n        eapply H5 in H8; eauto.\n        unfold typingcontext_sound in *; invert H40; process_ctx; eauto.\n        split_ex; split; intros; eauto.\n        * unfold findKeysCrypto in *; context_map_rewrites; destruct c; eauto.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n        * destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n\n      + destruct (c_id ==n x); subst; clean_map_lookups; eauto.\n\n    - unfold typingcontext_sound in *; invert H38; split_ex; process_ctx.\n      split; eauto.\n      user_cipher_queues_prop.\n      encrypted_ciphers_prop.\n      rewrite honestk_merge_new_msgs_keys_dec_same; eauto.\n\n    - rewrite !Forall_forall in *; split_ex; split; intros; eauto.\n\n      + destruct x; intros; eauto; simpl in *.\n        eapply H3 in H6; eauto; split_ex.\n        unfold typingcontext_sound in *; invert H38; process_ctx; eauto.\n        split_ex; split; intros; eauto.\n        * unfold findKeysCrypto in *; context_map_rewrites; destruct c; eauto.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n          eapply H14 in H4; split_ex; subst.\n          eapply H9 in H4.\n          keys_and_permissions_prop.\n          eapply H18 in H4; split_ex; split; intros; clean_map_lookups.\n          \n        * destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n\n      + destruct (c_id ==n x); subst; clean_map_lookups; eauto.\n\n    - split_ex; split; eauto.\n      \n      rewrite !Forall_forall in *; split_ex; intros; eauto.\n      destruct x; intros.\n      eapply H0 in H2; split_ex; split; intros; eauto.\n      eapply H2 in H4; split_ex; split; intros; eauto.\n\n      destruct (k_id ==n k); subst; clean_map_lookups.\n      destruct (k_id ==n k); subst; clean_map_lookups; eauto.\n\n  Qed.\n\n  Lemma adv_step_adv_goodness :\n    forall {A B C} lbl bd bd',\n      step_user lbl None bd bd'\n\n      -> forall cs cs' (usrs usrs' : honest_users A) (adv adv' : user_data B) (cmd cmd' : user_cmd C)\n          gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n',\n\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> qmsgs = adv.(msg_heap)\n        -> mycs = adv.(c_heap)\n        -> keys_and_permissions_good gks usrs ks\n        -> adv_no_honest_keys (findUserKeys usrs) ks\n        -> adv_goodness usrs cs gks qmsgs mycs\n        -> adv_goodness usrs' cs' gks' qmsgs' mycs'.\n  Proof.\n    induction 1; inversion 1; inversion 1; intros; subst;\n      eauto;\n      unfold adv_goodness in *;\n      autorewrite with find_user_keys;\n      simpl;\n      eauto;\n      clean_context. \n\n    - split_ex.\n      eapply break_msg_queue_prop in H; split_ex; split; eauto.\n      clear H1; rewrite Forall_forall in *; intros.\n      rewrite in_app_iff in H1; split_ors; eauto.\n\n    (* Recv Drop rule *)\n    (* - split_ex. *)\n    (*   invert H; split; eauto. *)\n\n    - split_ex; split;\n        rewrite Forall_forall in *; intros.\n\n      + destruct x; intros; eauto.\n        eapply H5 in H8; split_ex; split; intros; eauto.\n\n        * destruct c; simpl in *; eauto.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n        * destruct c; simpl in *; try contradiction.\n          specialize (H9 _ H10); split_ex.\n          split_ors; subst; try contradiction.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n        \n      + simpl in *; split_ors; subst; eauto.\n        eapply H7 in H8; split_ex.\n        destruct (c_id ==n x); subst; clean_map_lookups; eauto.\n\n    - split_ex; split;\n        rewrite Forall_forall in *; intros.\n\n      + destruct x; intros; eauto.\n        eapply H3 in H6; split_ex; split; intros; eauto.\n\n        * destruct c; simpl in *; eauto.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n          split.\n          ** unfold keys_and_permissions_good in H34; split_ex.\n             specialize (H2 _ _ H8).\n             unfold permission_heap_good in H11; split_ors; eauto; unfold not; intros;\n               eapply H11 in H2; split_ex; clean_map_lookups.\n\n          ** specialize (H35 k); intros; subst; unfold not; intros.\n             specialize (H2 _ _ H8).\n             split_ors; clean_map_lookups; eauto.\n          \n        * destruct c; simpl in *; try contradiction.\n          specialize (H7 _ H8); split_ex.\n          split_ors; subst; try contradiction.\n          destruct (c_id ==n c_id0); subst; clean_map_lookups; eauto.\n        \n      + simpl in *; split_ors; subst; eauto.\n        eapply H5 in H6; split_ex.\n        destruct (c_id ==n x); subst; clean_map_lookups; eauto.\n        \n    - split_ex; split; eauto.\n      rewrite Forall_forall in *; eauto; intros.\n      destruct x; intros.\n      eapply H0 in H2; eauto.\n      split_ex; split; intros; eauto.\n      eapply H2 in H4; eauto; split_ex; split; eauto.\n      destruct (k ==n k_id); subst; clean_map_lookups; eauto.\n\n  Qed.\n\n  Definition goodness_predicates {A B} (U : universe A B) : Prop :=\n    let honestk := findUserKeys U.(users)\n    in  encrypted_ciphers_ok honestk U.(all_ciphers) U.(all_keys)\n      /\\ keys_and_permissions_good U.(all_keys) U.(users) U.(adversary).(key_heap)\n      /\\ user_cipher_queues_ok U.(all_ciphers) honestk U.(users)\n      /\\ message_queues_ok U.(all_ciphers) U.(users) U.(all_keys)\n      /\\ honest_users_only_honest_keys U.(users)\n      /\\ adv_goodness U.(users) U.(all_ciphers) U.(all_keys) U.(adversary).(msg_heap) U.(adversary).(c_heap)\n      /\\ adv_no_honest_keys honestk U.(adversary).(key_heap).\n      (* /\\ adv_cipher_queue_ok U.(all_ciphers) U.(users) U.(adversary).(c_heap) *)\n      (* /\\ adv_message_queue_ok U.(users) U.(all_ciphers) U.(all_keys) U.(adversary).(msg_heap). *)\n\n  Lemma goodness_preservation_stepU :\n    forall {A B} (U U' : universe A B) suid lbl,\n      step_universe suid U lbl U'\n      -> syntactically_safe_U U\n      -> goodness_predicates U\n      -> goodness_predicates U'.\n  Proof.\n    intros.\n\n    invert H.\n\n    - unfold goodness_predicates, syntactically_safe_U in *; simpl in *.\n      destruct lbl0, U, userData;\n        unfold build_data_step in *; simpl in *;\n          specialize (H0 _ _ _ H2 eq_refl); split_ex; simpl in *.\n    \n      + autorewrite with find_user_keys; repeat simple apply conj; eauto.\n\n        eapply silent_user_step_encrypted_ciphers_ok; eauto.\n        eapply honest_silent_step_keys_good; eauto.\n        eapply honest_silent_step_user_cipher_queues_ok; eauto.\n        eapply honest_silent_step_message_queues_ok; eauto; keys_and_permissions_prop; eauto.\n        eapply honest_users_only_honest_keys_honest_steps; eauto.\n        eapply honest_step_adv_goodness; eauto.\n        eapply honest_silent_step_adv_no_honest_keys; eauto.\n\n      + repeat simple apply conj.\n        eapply honest_labeled_step_encrypted_ciphers_ok; eauto.\n        eapply honest_labeled_step_keys_and_permissions_good; eauto.\n        eapply honest_labeled_step_user_cipher_queues_ok_ss; eauto.\n        eapply honest_labeled_step_message_queues_ok_ss; eauto.\n        eapply honest_users_only_honest_keys_honest_steps; eauto.\n        eapply honest_step_adv_goodness; eauto.\n        eapply honest_labeled_step_adv_no_honest_keys_ss; eauto.\n\n    - simpl.\n      unfold goodness_predicates, build_data_step in *;\n        destruct U, adversary;\n        split_ex; simpl in *.\n\n      repeat simple apply conj.\n\n      eapply adv_step_encrypted_ciphers_ok; eauto.\n      eapply adv_step_keys_good_ss; eauto.\n      eapply adv_step_user_cipher_queues_ok; eauto.\n\n      unfold keys_and_permissions_good in *; split_ex.\n      eapply adv_step_message_queues_ok_ss; eauto.\n\n      eapply honest_users_only_honest_keys_adv_steps; eauto.\n      eapply adv_step_adv_goodness; eauto.\n      eapply adv_step_adv_no_honest_keys_ss; eauto.\n  Qed.\n\n  Lemma step_user_nochange_that_user_in_honest_users :\n    forall {A B C} suid lbl bd bd',\n      step_user lbl suid bd bd'\n      -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n          (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n          froms froms' sents sents' cur_n cur_n',\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> forall u_id1 ud1,\n            suid = Some u_id1\n            -> usrs $? u_id1 = Some ud1\n            -> usrs' $? u_id1 = Some ud1.\n  Proof.\n    induction 1; inversion 1; inversion 1;\n      intros; subst; eauto.\n  Qed.\n\n  Lemma step_back_into_other_user :\n    forall {A B C} suid lbl bd bd',\n      step_user lbl suid bd bd'\n      -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n          (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n          froms froms' sents sents' cur_n cur_n',\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> forall cmdc u_id1 u_id2 ks2 cmdc2 qmsgs2 mycs2 froms2 sents2 cur_n2,\n            suid = Some u_id1\n            -> u_id1 <> u_id2\n            -> usrs $? u_id1 = Some {| key_heap := ks;\n                                      protocol := cmdc;\n                                      msg_heap := qmsgs;\n                                      c_heap   := mycs;\n                                      from_nons := froms;\n                                      sent_nons := sents;\n                                      cur_nonce := cur_n |}\n            -> usrs' $? u_id2 = Some {| key_heap := ks2;\n                                       protocol := cmdc2;\n                                       msg_heap := qmsgs2;\n                                       c_heap   := mycs2;\n                                       from_nons := froms2;\n                                       sent_nons := sents2;\n                                       cur_nonce := cur_n2 |}\n            -> usrs $? u_id2 = Some {| key_heap := ks2;\n                                      protocol := cmdc2;\n                                      msg_heap := qmsgs2;\n                                      c_heap   := mycs2;\n                                      from_nons := froms2;\n                                      sent_nons := sents2;\n                                      cur_nonce := cur_n2 |}\n              \\/ exists m qmsgs2',\n                qmsgs2 = qmsgs2' ++ [m]\n                /\\ usrs $? u_id2 = Some {| key_heap := ks2;\n                                          protocol := cmdc2;\n                                          msg_heap := qmsgs2';\n                                          c_heap   := mycs2;\n                                          from_nons := froms2;\n                                          sent_nons := sents2;\n                                          cur_nonce := cur_n2 |}.\n  Proof.\n    induction 1; inversion 1; inversion 1;\n      intros; subst; eauto.\n\n    destruct (rec_u_id ==n u_id2); subst; clean_map_lookups; eauto.\n    destruct rec_u; eauto.\n  Qed.\n\n  Lemma impact_from_other_user_step :\n    forall {A B C} lbl suid1 bd bd',\n      step_user lbl suid1 bd bd'\n                \n      -> forall (usrs usrs' : honest_users A) (adv adv' : user_data B) cs cs' gks gks'\n          u_id1 u_id2 ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' (cmd cmd' : user_cmd C),\n        \n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> suid1 = Some u_id1\n        -> u_id1 <> u_id2\n        -> forall ks2 qmsgs2 mycs2 froms2 sents2 cur_n2 cmd2,\n            usrs $? u_id2 = Some (mkUserData ks2 cmd2 qmsgs2 mycs2 froms2 sents2 cur_n2)\n            -> exists m,\n              usrs' $? u_id2 = Some (mkUserData ks2 cmd2 (qmsgs2 ++ m) mycs2 froms2 sents2 cur_n2).\n  Proof.\n    induct 1; inversion 1; inversion 2; intros; subst;\n      clean_context;\n      match goal with\n      | [ H : (_,_,_,_,_,_,_,_,_,_,_) = (_,_,_,_,_,_,_,_,_,_,_) |- _ ] => invert H\n      end;\n      clean_map_lookups;\n      try solve [ exists []; rewrite app_nil_r; trivial ];\n      eauto.\n\n    destruct (rec_u_id ==n u_id2); subst; clean_map_lookups;\n      repeat simple apply conj; trivial; eauto.\n    exists []; rewrite app_nil_r; trivial.\n  Qed.\n\n  Lemma impact_from_adv_step :\n    forall {A B C} lbl bd bd',\n      step_user lbl None bd bd'\n                \n      -> forall (usrs usrs' : honest_users A) (adv adv' : user_data B) cs cs' gks gks'\n          u_id ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' cur_n cur_n' (cmd cmd' : user_cmd C),\n        \n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n        -> forall cmda, adv = mkUserData ks cmda qmsgs mycs froms sents cur_n\n        -> forall ks2 qmsgs2 mycs2 froms2 sents2 cur_n2 cmd2,\n            usrs' $? u_id = Some (mkUserData ks2 cmd2 qmsgs2 mycs2 froms2 sents2 cur_n2)\n            -> exists qmsgs2' m,\n                qmsgs2' ++ m = qmsgs2\n             /\\  usrs $? u_id = Some (mkUserData ks2 cmd2 qmsgs2' mycs2 froms2 sents2 cur_n2).\n  Proof.\n    induction 1; inversion 1; inversion 1; intros; subst;\n      eauto;\n      try solve [ exists qmsgs2; exists []; rewrite app_nil_r; eauto ].\n\n    simpl in *; clean_context.\n    destruct (rec_u_id ==n u_id); subst; clean_map_lookups.\n\n    exists rec_u.(msg_heap); exists [existT crypto t0 msg]; split; eauto; destruct rec_u; simpl in *; eauto.\n    exists qmsgs2; exists[]; rewrite app_nil_r; eauto.\n  Qed.\n\n  Lemma syntactically_safe_U_preservation_stepU :\n    forall A B (U U' : universe A B) suid lbl,\n      step_universe suid U lbl U'\n      -> goodness_predicates U\n      -> syntactically_safe_U U\n      -> syntactically_safe_U U'.\n  Proof.\n    intros * STEP GOOD SS.\n    invert STEP.\n\n    unfold syntactically_safe_U, build_data_step in *; destruct U; destruct userData;\n      simpl in *; intros.\n    unfold goodness_predicates in *; split_ex; simpl in *.\n    msg_queue_prop; subst.\n\n    pose proof (step_user_nochange_that_user_in_honest_users H0 eq_refl eq_refl eq_refl H).\n    erewrite compute_userids_readd_idempotent by eauto.\n    erewrite user_step_nochange_uids by eauto.\n\n    destruct (u_id ==n uid); subst; clean_map_lookups; simpl.\n    - specialize (SS _ _ _ H eq_refl); split_ex; simpl in *.\n      eapply syntactically_safe_honest_keys_preservation in H0; eauto.\n      split_ex; eauto.\n\n    - generalize H0; intros STEP.\n      destruct u; generalize STEP; intros STEP'.\n      eapply step_back_into_other_user in STEP; simpl; eauto.\n      \n      split_ors; split_ex; subst.\n      + subst.\n        generalize (SS _ _ _ H eq_refl); intros; split_ex.\n        specialize (SS _ _ _ H11 eq_refl); split_ex; simpl in *.\n        (do 2 eexists); split; eauto.\n        eapply typingcontext_sound_other_user_step; eauto.\n      + subst.\n        generalize (SS _ _ _ H eq_refl); intros; split_ex.\n        specialize (SS _ _ _ H12 eq_refl); split_ex; simpl in *.\n        (do 2 eexists); split; eauto.\n        eapply typingcontext_sound_other_user_step; eauto.\n\n    - unfold buildUniverseAdv; simpl.\n      unfold syntactically_safe_U in *; intros; simpl in *.\n      destruct U, adversary; unfold build_data_step in *; simpl in *.\n      destruct u; simpl in *.\n      subst; erewrite user_step_nochange_uids by eauto.\n      pose proof (impact_from_adv_step H _ eq_refl eq_refl eq_refl H0); split_ex.\n      generalize (SS _ _ _ H2 eq_refl); simpl; intros; split_ex; eauto.\n      eapply syntactically_safe_adv_step_preservation in H; eauto; simpl in *; split_ex; eauto.\n  Qed.\n\nEnd PredicatePreservation.\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/SyntacticallySafe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.19856296547066205}}
{"text": "From cap_machine Require Export logrel.\nFrom cap_machine.rules Require Export rules_AddSubLt.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Import machine_base.\nFrom cap_machine.rules Require Import rules_base.\n\nSection fundamental.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3} {sealsg: sealStoreG \u03a3}\n          {nainv: logrel_na_invs \u03a3}\n          `{MachineParameters}.\n\n  Notation D := ((leibnizO Word) -n> iPropO \u03a3).\n  Notation R := ((leibnizO Reg) -n> iPropO \u03a3).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma add_sub_lt_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst : RegName) (r1 r2: Z + RegName) (P : D):\n    p = RX \u2228 p = RWX\n    \u2192 (\u2200 x : RegName, is_Some (r !! x))\n    \u2192 isCorrectPC (WCap p b e a)\n    \u2192 (b <= a)%a \u2227 (a < e)%a\n    \u2192 (decodeInstrW w = Add dst r1 r2 \\/\n       decodeInstrW w = Sub dst r1 r2 \\/\n       decodeInstrW w = Lt dst r1 r2)\n    -> \u25a1 \u25b7 (\u2200 a0 a1 a2 a3 a4,\n             full_map a0\n          -\u2217 (\u2200 (r1 : RegName) v, \u231cr1 \u2260 PC\u231d \u2192 \u231ca0 !! r1 = Some v\u231d \u2192 (fixpoint interp1) v)\n          -\u2217 registers_mapsto (<[PC:=WCap a1 a2 a3 a4]> a0)\n          -\u2217 na_own logrel_nais \u22a4\n          -\u2217 \u25a1 (fixpoint interp1) (WCap a1 a2 a3 a4) -\u2217 interp_conf)\n    -\u2217 (fixpoint interp1) (WCap p b e a)\n    -\u2217 inv (logN.@a) (\u2203 w0 : leibnizO Word, a \u21a6\u2090 w0 \u2217 P w0)\n    -\u2217 (\u2200 (r1 : RegName) v, \u231cr1 \u2260 PC\u231d \u2192 \u231cr !! r1 = Some v\u231d \u2192 (fixpoint interp1) v)\n    -\u2217 \u25b7 \u25a1 (\u2200 w : Word, P w -\u2217 (fixpoint interp1) w)\n            \u2217 (if decide (writeAllowed_in_r_a (<[PC:=WCap p b e a]> r) a) then \u25b7 \u25a1 (\u2200 w : Word, (fixpoint interp1) w -\u2217 P w) else emp)\n    -\u2217 na_own logrel_nais \u22a4\n    -\u2217 a \u21a6\u2090 w\n    -\u2217 \u25b7 P w\n    -\u2217 (\u25b7 (\u2203 w0 : leibnizO Word, a \u21a6\u2090 w0 \u2217 P w0) ={\u22a4 \u2216 \u2191logN.@a,\u22a4}=\u2217 emp)\n    -\u2217 PC \u21a6\u1d63 WCap p b e a\n    -\u2217 ([\u2217 map] k\u21a6y \u2208 delete PC (<[PC:=WCap p b e a]> r), k \u21a6\u1d63 y)\n    -\u2217\n        WP Instr Executable\n        @ \u22a4 \u2216 \u2191logN.@a {{ v, |={\u22a4 \u2216 \u2191logN.@a,\u22a4}=> WP Seq (of_val v)\n                                                    {{ v0, \u231cv0 = HaltedV\u231d\n                                                           \u2192 \u2203 r1 : Reg, full_map r1 \u2227 registers_mapsto r1\n                                                                                                        \u2217 na_own logrel_nais \u22a4 }} }}.\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_AddSubLt with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec; cycle 1.\n    { iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext; iIntros \"_\".\n      iApply wp_value; auto. iIntros; discriminate. }\n    { incrementPC_inv; simplify_map_eq.\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro]. iNext;iIntros \"_\".\n      assert (dst <> PC) as HdstPC by (intros ->; simplify_map_eq).\n      simplify_map_eq.\n      iApply (\"IH\" $! (<[dst:=_]> (<[PC:=_]> r)) with \"[%] [] [Hmap] [$Hown]\");\n        try iClear \"IH\"; eauto.\n      { intro. cbn. by repeat (rewrite lookup_insert_is_Some'; right). }\n      iIntros (ri v Hri Hsv). rewrite insert_commute // lookup_insert_ne // in Hsv; [].\n      destruct (decide (ri = dst)); simplify_map_eq.\n      { repeat rewrite fixpoint_interp1_eq; auto. }\n      { by iApply \"Hreg\". }\n      { iModIntro. rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->];iFrame \"Hinv\". }\n    }\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/AddSubLt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19856295767811002}}
{"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(** I64 builtins layer *)\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Floats.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcertx.backend.I64helpers.\nRequire Import compcert.backend.SelectLong.\nRequire Import compcertx.backend.SelectLongproofX.\nRequire Import liblayers.compat.CompatPrimSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatExternalCalls.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import liblayers.compcertx.Observation.\n\n(** Missing lemma from [PseudoJoin] *)\n\nSection WITHPSEUDOJOIN.\n  Context `{PseudoJoin}.\n\n  Lemma split_le_left:\n    forall a b c,\n      (a \u2295 b) \u2264 c ->\n      a \u2264 c.\n  Proof.\n    intros. etransitivity. eapply left_upper_bound. eassumption.\n  Qed.\n\n  Lemma split_le_right:\n    forall a b c,\n      (a \u2295 b) \u2264 c ->\n      b \u2264 c.\n  Proof.\n    intros until c.\n    rewrite commutativity.\n    eapply split_le_left.\n  Qed.\nEnd WITHPSEUDOJOIN.\n\nLtac split_le :=\n  match goal with\n    | [ H: ?a \u2295 ?b \u2264 ?c |- _ ] =>\n      let Hl := fresh H \"l\" in\n      let Hr := fresh H \"r\" in\n      generalize (split_le_left _ _ _ H);\n        generalize (split_le_right _ _ _ H);\n        clear H;\n        intros Hr Hl\n  end.   \n\nSection WITHSTENCIL.\nContext `{Hobs: Observation}.\nContext `{Hstencil: Stencil}.\n\nContext `{Hmem: Mem.MemoryModel}.\nContext `{Hmwd: UseMemWithData mem}.\n\nContext {D: compatdata}.\n\n  Definition csem_info step args res: sextcall_info (mem := mwd D) :=\n    {|\n      sextcall_step := step;\n      sextcall_csig := mkcsig args res;\n      sextcall_valid := const (B := stencil) true\n    |}.\n\n  Definition csem_full (sem: sextcall_info (mem := mwd D)) :=\n    fun `{!ExtcallProperties sem} `{!ExtcallInvariants sem} =>\n      {|\n        sextcall_primsem_step := sem;\n        sextcall_props := OK _;\n        sextcall_invs := OK _\n      |}.\n\n  (** longoffloat *)\n\n  Inductive sextcall_longoffloat_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_longoffloat_step_intro\n      x z\n      (Hxz: Val.longoffloat x = Some z)\n      m :\n      sextcall_longoffloat_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_longoffloat_info :=\n    csem_info\n      sextcall_longoffloat_step\n      (Tcons (Tfloat F64 noattr) Tnil)\n      (Tlong Signed noattr).\n\n  Instance sextcall_longoffloat_properties:\n    ExtcallProperties sextcall_longoffloat_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longoffloat f); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longoffloat f); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longoffloat f0); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_longoffloat_invariants:\n    ExtcallInvariants sextcall_longoffloat_info.\n  Proof.\n    constructor; inversion 1; try congruence; try reflexivity.\n    * (* inject neutral *)\n      subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longoffloat f); try discriminate.\n      inv Hxz. constructor.\n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longoffloat f); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_longoffloat_primsem: sextcall_primsem D :=\n    csem_full sextcall_longoffloat_info.\n\n  Definition sextcall_longoffloat_compatsem: compatsem D :=\n    inl sextcall_longoffloat_primsem.\n\n  (** longuoffloat *)\n\n  Inductive sextcall_longuoffloat_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_longuoffloat_step_intro\n      x z\n      (Hxz: Val.longuoffloat x = Some z)\n      m :\n      sextcall_longuoffloat_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_longuoffloat_info :=\n    csem_info\n      sextcall_longuoffloat_step\n      (Tcons (Tfloat F64 noattr) Tnil)\n      (Tlong Unsigned noattr).\n\n  Instance sextcall_longuoffloat_properties:\n    ExtcallProperties sextcall_longuoffloat_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longuoffloat f); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longuoffloat f); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longuoffloat f0); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_longuoffloat_invariants:\n    ExtcallInvariants sextcall_longuoffloat_info.\n  Proof.\n    constructor; inversion 1; try congruence; try reflexivity.\n    * (* inject neutral *)\n      subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longuoffloat f); try discriminate.\n      inv Hxz. constructor.\n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct (Float.longuoffloat f); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n\n  Definition sextcall_longuoffloat_primsem: sextcall_primsem D :=\n    csem_full sextcall_longuoffloat_info.\n\n  Definition sextcall_longuoffloat_compatsem: compatsem D :=\n    inl sextcall_longuoffloat_primsem.\n\n  (** floatoflong *)\n\n  Inductive sextcall_floatoflong_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_floatoflong_step_intro\n      x z\n      (Hxz: Val.floatoflong x = Some z)\n      m :\n      sextcall_floatoflong_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_floatoflong_info :=\n    csem_info\n      sextcall_floatoflong_step\n      (Tcons (Tlong Signed noattr) Tnil)\n      (Tfloat F64 noattr).\n\n  Instance sextcall_floatoflong_properties:\n    ExtcallProperties sextcall_floatoflong_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_floatoflong_invariants:\n    ExtcallInvariants sextcall_floatoflong_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_floatoflong_primsem: sextcall_primsem D :=\n    csem_full sextcall_floatoflong_info.\n\n  Definition sextcall_floatoflong_compatsem: compatsem D :=\n    inl sextcall_floatoflong_primsem.\n\n  (** floatoflongu *)\n  \n  Inductive sextcall_floatoflongu_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_floatoflongu_step_intro\n      x z\n      (Hxz: Val.floatoflongu x = Some z)\n      m :\n      sextcall_floatoflongu_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_floatoflongu_info :=\n    csem_info\n      sextcall_floatoflongu_step\n      (Tcons (Tlong Unsigned noattr) Tnil)\n      (Tfloat F64 noattr).\n\n  Instance sextcall_floatoflongu_properties:\n    ExtcallProperties sextcall_floatoflongu_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_floatoflongu_invariants:\n    ExtcallInvariants sextcall_floatoflongu_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_floatoflongu_primsem: sextcall_primsem D :=\n    csem_full sextcall_floatoflongu_info.\n\n  Definition sextcall_floatoflongu_compatsem: compatsem D :=\n    inl sextcall_floatoflongu_primsem.\n  \n  (** singleoflong *)\n\n  Inductive sextcall_singleoflong_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_singleoflong_step_intro\n      x z\n      (Hxz: Val.singleoflong x = Some z)\n      m :\n      sextcall_singleoflong_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_singleoflong_info :=\n    csem_info\n      sextcall_singleoflong_step\n      (Tcons (Tlong Signed noattr) Tnil)\n      (Tfloat F32 noattr).\n\n  Instance sextcall_singleoflong_properties:\n    ExtcallProperties sextcall_singleoflong_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      simpl. rewrite <- Float.singleoflong_idem. apply Float.singleoffloat_is_single.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_singleoflong_invariants:\n    ExtcallInvariants sextcall_singleoflong_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      simpl. rewrite <- Float.singleoflong_idem. apply Float.singleoffloat_is_single.\n  Qed.\n\n  Definition sextcall_singleoflong_primsem: sextcall_primsem D :=\n    csem_full sextcall_singleoflong_info.\n\n  Definition sextcall_singleoflong_compatsem: compatsem D :=\n    inl sextcall_singleoflong_primsem.\n\n  (** singleoflongu *)\n  \n  Inductive sextcall_singleoflongu_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_singleoflongu_step_intro\n      x z\n      (Hxz: Val.singleoflongu x = Some z)\n      m :\n      sextcall_singleoflongu_step s WB (x :: nil) m z m\n  .\n\n  Definition sextcall_singleoflongu_info :=\n    csem_info\n      sextcall_singleoflongu_step\n      (Tcons (Tlong Unsigned noattr) Tnil)\n      (Tfloat F32 noattr).\n\n  Instance sextcall_singleoflongu_properties:\n    ExtcallProperties sextcall_singleoflongu_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      simpl.\n      unfold Float.singleoflongu.\n      esplit. reflexivity.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_singleoflongu_invariants:\n    ExtcallInvariants sextcall_singleoflongu_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      inv Hxz.\n      simpl.\n      unfold Float.singleoflongu.\n      esplit. reflexivity.\n  Qed.\n\n  Definition sextcall_singleoflongu_primsem: sextcall_primsem D :=\n    csem_full sextcall_singleoflongu_info.\n\n  Definition sextcall_singleoflongu_compatsem: compatsem D :=\n    inl sextcall_singleoflongu_primsem.\n\n  (** divls *)\n\n  Inductive sextcall_divls_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_divls_step_intro\n      x y z\n      (Hxz: Val.divls x y = Some z)\n      m :\n      sextcall_divls_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_divls_info :=\n    csem_info\n      sextcall_divls_step\n      (Tcons (Tlong Signed noattr) (Tcons (Tlong Signed noattr) Tnil))\n      (Tlong Signed noattr).\n\n  Instance sextcall_divls_properties:\n    ExtcallProperties sextcall_divls_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4. inv H5. inv H8.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      inv H5. inv H8.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_divls_invariants:\n    ExtcallInvariants sextcall_divls_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct y; try discriminate.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_divls_primsem: sextcall_primsem D :=\n    csem_full sextcall_divls_info.\n\n  Definition sextcall_divls_compatsem: compatsem D :=\n    inl sextcall_divls_primsem.\n\n  (** divlu *)\n\n  Inductive sextcall_divlu_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_divlu_step_intro\n      x y z\n      (Hxz: Val.divlu x y = Some z)\n      m :\n      sextcall_divlu_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_divlu_info :=\n    csem_info\n      sextcall_divlu_step\n      (Tcons (Tlong Unsigned noattr) (Tcons (Tlong Unsigned noattr) Tnil))\n      (Tlong Unsigned noattr).\n\n  Instance sextcall_divlu_properties:\n    ExtcallProperties sextcall_divlu_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4. inv H5. inv H8.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      inv H5. inv H8.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_divlu_invariants:\n    ExtcallInvariants sextcall_divlu_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct y; try discriminate.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_divlu_primsem: sextcall_primsem D :=\n    csem_full sextcall_divlu_info.\n\n  Definition sextcall_divlu_compatsem: compatsem D :=\n    inl sextcall_divlu_primsem.\n\n  (** modls *)\n\n  Inductive sextcall_modls_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_modls_step_intro\n      x y z\n      (Hxz: Val.modls x y = Some z)\n      m :\n      sextcall_modls_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_modls_info :=\n    csem_info\n      sextcall_modls_step\n      (Tcons (Tlong Signed noattr) (Tcons (Tlong Signed noattr) Tnil))\n      (Tlong Signed noattr).\n\n  Instance sextcall_modls_properties:\n    ExtcallProperties sextcall_modls_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4. inv H5. inv H8.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      inv H5. inv H8.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_modls_invariants:\n    ExtcallInvariants sextcall_modls_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct y; try discriminate.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (\n          Int64.eq i0 Int64.zero\n            || Int64.eq i (Int64.repr Int64.min_signed) &&\n               Int64.eq i0 Int64.mone\n        ); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_modls_primsem: sextcall_primsem D :=\n    csem_full sextcall_modls_info.\n\n  Definition sextcall_modls_compatsem: compatsem D :=\n    inl sextcall_modls_primsem.\n\n  (** modlu *)\n\n  Inductive sextcall_modlu_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_modlu_step_intro\n      x y z\n      (Hxz: Val.modlu x y = Some z)\n      m :\n      sextcall_modlu_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_modlu_info :=\n    csem_info\n      sextcall_modlu_step\n      (Tcons (Tlong Unsigned noattr) (Tcons (Tlong Unsigned noattr) Tnil))\n      (Tlong Unsigned noattr).\n\n  Instance sextcall_modlu_properties:\n    ExtcallProperties sextcall_modlu_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      constructor.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      inversion 2; subst. inv H6.\n      inv H4. inv H5. inv H8.\n      esplit. esplit. split.\n      econstructor; eauto.\n      split; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      generalize Hxz.\n      intro Hy.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      inversion 2; subst.\n      inv H5. inv H7.\n      inv H5. inv H8.\n      intros.\n      esplit. esplit. esplit. split.\n      econstructor; eauto.\n      split. econstructor.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_modlu_invariants:\n    ExtcallInvariants sextcall_modlu_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; try discriminate.\n      simpl in Hxz.\n      destruct y; try discriminate.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz. constructor.  \n    * (* type *)\n      subst.\n      destruct x; try discriminate.\n      destruct y; try discriminate.\n      simpl in Hxz.\n      destruct (Int64.eq i0 Int64.zero); try discriminate.\n      inv Hxz.\n      constructor.\n  Qed.\n\n  Definition sextcall_modlu_primsem: sextcall_primsem D :=\n    csem_full sextcall_modlu_info.\n\n  Definition sextcall_modlu_compatsem: compatsem D :=\n    inl sextcall_modlu_primsem.\n\n  (** shll *)\n\n  Inductive sextcall_shll_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_shll_step_intro\n      x y z\n      (Hxz: Val.shll x y = z)\n      m :\n      sextcall_shll_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_shll_info :=\n    csem_info\n      sextcall_shll_step\n      (Tcons (Tlong Signed noattr) (Tcons (Tint I32 Unsigned noattr) Tnil))\n      (Tlong Signed noattr).\n    \n  Instance sextcall_shll_properties:\n    ExtcallProperties sextcall_shll_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      inversion 2; subst. inv H6. inv H8.\n      esplit. esplit. split.\n      econstructor. reflexivity.\n      split. \n      inv H4; simpl; auto.\n      destruct v2; simpl; auto.\n      inv H5; simpl; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      inversion 2; subst.\n      inv H7. inv H9.\n      esplit. esplit. esplit.\n      split. econstructor. reflexivity.\n      instantiate (1 := f).\n      split.\n       inv H5; simpl; auto.\n       inv H6; simpl; auto.\n       destruct (Int.ltu i0 Int64.iwordsize'); auto.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_shll_invariants:\n    ExtcallInvariants sextcall_shll_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; simpl; try (constructor; fail).\n      destruct y; simpl; try (constructor; fail).\n      destruct (Int.ltu i0 Int64.iwordsize'); constructor.\n    * (* type *)\n      subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n  Qed.\n\n  Definition sextcall_shll_primsem: sextcall_primsem D :=\n    csem_full sextcall_shll_info.\n\n  Definition sextcall_shll_compatsem: compatsem D :=\n    inl sextcall_shll_primsem.\n  \n  (** shrlu *)\n\n  Inductive sextcall_shrlu_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_shrlu_step_intro\n      x y z\n      (Hxz: Val.shrlu x y = z)\n      m :\n      sextcall_shrlu_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_shrlu_info :=\n    csem_info\n      sextcall_shrlu_step\n      (Tcons (Tlong Unsigned noattr) (Tcons (Tint I32 Unsigned noattr) Tnil))\n      (Tlong Signed noattr).\n    \n  Instance sextcall_shrlu_properties:\n    ExtcallProperties sextcall_shrlu_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      inversion 2; subst. inv H6. inv H8.\n      esplit. esplit. split.\n      econstructor. reflexivity.\n      split. \n      inv H4; simpl; auto.\n      destruct v2; simpl; auto.\n      inv H5; simpl; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      inversion 2; subst.\n      inv H7. inv H9.\n      esplit. esplit. esplit.\n      split. econstructor. reflexivity.\n      instantiate (1 := f).\n      split.\n       inv H5; simpl; auto.\n       inv H6; simpl; auto.\n       destruct (Int.ltu i0 Int64.iwordsize'); auto.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_shrlu_invariants:\n    ExtcallInvariants sextcall_shrlu_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; simpl; try (constructor; fail).\n      destruct y; simpl; try (constructor; fail).\n      destruct (Int.ltu i0 Int64.iwordsize'); constructor.\n    * (* type *)\n      subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n  Qed.\n\n  Definition sextcall_shrlu_primsem: sextcall_primsem D :=\n    csem_full sextcall_shrlu_info.\n\n  Definition sextcall_shrlu_compatsem: compatsem D :=\n    inl sextcall_shrlu_primsem.\n\n  (** shrl *)\n\n  Inductive sextcall_shrl_step (s: stencil) (WB: block -> Prop):\n    list val -> mwd D -> val -> mwd D -> Prop :=\n  | sextcall_shrl_step_intro\n      x y z\n      (Hxz: Val.shrl x y = z)\n      m :\n      sextcall_shrl_step s WB (x :: y :: nil) m z m\n  .\n\n  Definition sextcall_shrl_info :=\n    csem_info\n      sextcall_shrl_step\n      (Tcons (Tlong Signed noattr) (Tcons (Tint I32 Unsigned noattr) Tnil))\n      (Tlong Signed noattr).\n    \n  Instance sextcall_shrl_properties:\n    ExtcallProperties sextcall_shrl_info.\n  Proof.\n    constructor; try (inversion 1; congruence).\n    * (* type *)\n      inversion 1; subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n    * (* unchanged_on loc_not_writable *)\n      inversion 1; subst. apply Mem.unchanged_on_refl.\n    * (* extends *)\n      inversion 1; subst.\n      inversion 2; subst. inv H6. inv H8.\n      esplit. esplit. split.\n      econstructor. reflexivity.\n      split. \n      inv H4; simpl; auto.\n      destruct v2; simpl; auto.\n      inv H5; simpl; auto.\n      split; auto.\n      apply Mem.unchanged_on_refl.\n    * (* injects *)\n      inversion 2; subst.\n      inversion 2; subst.\n      inv H7. inv H9.\n      esplit. esplit. esplit.\n      split. econstructor. reflexivity.\n      instantiate (1 := f).\n      split.\n       inv H5; simpl; auto.\n       inv H6; simpl; auto.\n       destruct (Int.ltu i0 Int64.iwordsize'); auto.\n      split. eassumption.\n      split. apply Mem.unchanged_on_refl.\n      split. apply Mem.unchanged_on_refl.\n      split. apply inject_incr_refl.\n      intro. congruence.\n    * (* determ *)\n      inversion 1; inversion 1; split; congruence.\n    * (* WB weak *)\n      inversion 2; subst; econstructor; eauto.\n  Qed.\n\n  Instance sextcall_shrl_invariants:\n    ExtcallInvariants sextcall_shrl_info.\n  Proof.\n    constructor; inversion 1; try congruence; try xomega.\n    * (* inject neutral *)\n      inversion 1; subst.\n      split; auto.\n      destruct x; simpl; try (constructor; fail).\n      destruct y; simpl; try (constructor; fail).\n      destruct (Int.ltu i0 Int64.iwordsize'); constructor.\n    * (* type *)\n      subst.\n      destruct x; simpl; auto.\n      destruct y; simpl; auto.\n      destruct (Int.ltu i0 Int64.iwordsize'); simpl; auto.\n  Qed.\n\n  Definition sextcall_shrl_primsem: sextcall_primsem D :=\n    csem_full sextcall_shrl_info.\n\n  Definition sextcall_shrl_compatsem: compatsem D :=\n    inl sextcall_shrl_primsem.\n\n  (** Pack everything in a single layer *)\n\n  Definition L64: compatlayer D :=\n    ((i64_dtos hf) \u21a6 sextcall_longoffloat_compatsem)\n      \u2295 ((i64_dtou hf) \u21a6 sextcall_longuoffloat_compatsem)\n      \u2295 ((i64_stod hf) \u21a6 sextcall_floatoflong_compatsem)\n      \u2295 ((i64_utod hf) \u21a6 sextcall_floatoflongu_compatsem)\n      \u2295 ((i64_stof hf) \u21a6 sextcall_singleoflong_compatsem)\n      \u2295 ((i64_utof hf) \u21a6 sextcall_singleoflongu_compatsem)\n      \u2295 ((i64_sdiv hf) \u21a6 sextcall_divls_compatsem)\n      \u2295 ((i64_udiv hf) \u21a6 sextcall_divlu_compatsem)\n      \u2295 ((i64_smod hf) \u21a6 sextcall_modls_compatsem)\n      \u2295 ((i64_umod hf) \u21a6 sextcall_modlu_compatsem)\n      \u2295 ((i64_shl hf) \u21a6 sextcall_shll_compatsem)\n      \u2295 ((i64_shr hf) \u21a6 sextcall_shrlu_compatsem)\n      \u2295 ((i64_sar hf) \u21a6 sextcall_shrl_compatsem).\n\n  (** Prove that any layer [L \u2265 L64] *which has no \"magic\"* yields a\n  correct [ExternalCallI64helpers].*)\n\n(** We guarantee that I64 helpers have a well-defined (and correct)\nsemantics only if the global environment matches some stencil. To this\nend, we specified the [GenvValidOps] and [GenvValid] classes, which we\nnow need to instantiate accordingly. *)\n\n  Definition stencil_valid {D} (s: stencil) (p: compatsem D): Prop :=\n    match p with\n      | inl p' => sextcall_valid p' s = true\n      | _ => True\n    end.\n\n  Global Instance stencil_matches_genv_valid_ops {D} (L: _ D): GenvValidOps :=\n    {\n      genv_valid F V ge :=\n        exists s, stencil_matches s ge /\\\n                  forall (i: ident) p, get_layer_primitive i L = OK (Some p) ->\n                                       stencil_valid s p\n\n    }.\n  \n  Global Instance stencil_matches_genv_valid {D} (L: _ D): GenvValid (genv_valid_ops := stencil_matches_genv_valid_ops L).\n  Proof.\n    constructor.\n    intros.\n    destruct VALID as (s & ? & ?).\n    exists s.\n    split; eauto; eapply stencil_matches_preserves_symbols; try eassumption; eauto.\n  Qed.\n\n  Theorem L64_correct:\n    forall L, L64 \u2264 L ->\n              LayerOK L ->\n              ExternalCallI64Helpers (genv_valid_ops := stencil_matches_genv_valid_ops L) (CompCertBuiltins.external_functions_sem (ExternalCallsOpsX := compatlayer_extcall_ops_x L)) hf.\n  Proof.\n    Opaque hf get_layer_primitive.\n    unfold L64.\n    intros.\n    repeat split_le.\n    constructor; simpl; intros; intro; intros;\n    destruct VALID as (s & Hs & PRIMVALID);\n    unfold stencil_valid in PRIMVALID;\n    match goal with\n      | [ H: ?i \u21a6 ?\u03c3 \u2264 L |- context [ get_layer_primitive ?i L ] ] =>\n        destruct (get_layer_primitive_mapsto_le_ok L i \u03c3 H) as (\u03c3' & H\u03c3'eq & H\u03c3'le);\n          rewrite H\u03c3'eq\n    end;\n    esplit; split; eauto;\n    eapply compatsem_extcall_le; eauto;\n    repeat (econstructor; eauto);\n    try (intros s' Hmatch'; replace s' with s in * by (eapply stencil_matches_unique; eauto);\n    eapply PRIMVALID; eauto; fail);\n    econstructor; eauto.\n  Qed.\n\nEnd WITHSTENCIL.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/liblayers/compat/I64Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.19856294988555823}}
{"text": "From Perennial.program_proof.mvcc Require Import\n     txn_prelude txnmgr_repr txn_repr\n     wrbuf_proof.\n\nSection program.\nContext `{!heapGS \u03a3, !mvcc_ghostG \u03a3}.\n\n(*****************************************************************)\n(* func (txnMgr *TxnMgr) New() *Txn                              *)\n(*****************************************************************)\nTheorem wp_txnMgr__New txnmgr \u03b3 :\n  is_txnmgr txnmgr \u03b3 -\u2217\n  {{{ True }}}\n    TxnMgr__New #txnmgr\n  {{{ (txn : loc), RET #txn; own_txn_uninit txn \u03b3 }}}.\nProof.\n  iIntros \"#Htxnmgr\" (\u03a6) \"!> _ H\u03a6\".\n  iPoseProof \"Htxnmgr\" as \"Htxnmgr'\".\n  iNamed \"Htxnmgr\".\n  wp_call.\n  \n  (***********************************************************)\n  (* txnMgr.latch.Lock()                                     *)\n  (***********************************************************)\n  wp_loadField.\n  wp_apply (acquire_spec with \"Hlock\").\n  iIntros \"[Hlocked HtxnmgrOwn]\".\n  iNamed \"HtxnmgrOwn\".\n  wp_pures.\n  \n  (***********************************************************)\n  (* txn := new(Txn)                                         *)\n  (***********************************************************)\n  wp_apply (wp_allocStruct); first auto 10.\n  iIntros (txn) \"Htxn\".\n  iDestruct (struct_fields_split with \"Htxn\") as \"Htxn\".\n  iNamed \"Htxn\".\n  simpl.\n  wp_pures.\n  \n  (***********************************************************)\n  (* txn.wrbuf = wrbuf.MkWrBuf                               *)\n  (***********************************************************)\n  wp_apply (wp_MkWrBuf).\n  iIntros (wrbuf) \"HwrbufRP\".\n  wp_storeField.\n          \n  (***********************************************************)\n  (* sid := txnMgr.sidCur                                    *)\n  (* txn.sid = sid                                           *)\n  (***********************************************************)\n  wp_loadField.\n  wp_pures.\n  wp_storeField.\n  \n  (***********************************************************)\n  (* txn.idx = txnMgr.idx                                    *)\n  (* txn.txnMgr = txnMgr                                     *)\n  (***********************************************************)\n  wp_loadField.\n  do 2 wp_storeField.\n  \n  (***********************************************************)\n  (* txnMgr.sidCur = sid + 1                                 *)\n  (* if txnMgr.sidCur == config.N_TXN_SITES {                *)\n  (*     txnMgr.sidCur = 0                                   *)\n  (* }                                                       *)\n  (***********************************************************)\n  wp_storeField.\n  wp_loadField.\n  wp_apply (wp_If_join_evar with \"[Hsidcur]\").\n  { iIntros (b') \"%Eb'\".\n    case_bool_decide.\n    { wp_if_true.\n      wp_storeField.\n      iSplit; first done.\n      replace (U64 0) with (if b' then (U64 0) else (word.add sidcur (U64 1))) by by rewrite Eb'.\n      iNamedAccu.\n    }\n    { wp_if_false.\n      iModIntro.\n      subst.\n      by iFrame \"\u2217\".\n    }\n  }\n  iIntros \"H\".\n  iNamed \"H\".\n  wp_pures.\n    \n  (***********************************************************)\n  (* txnMgr.latch.Unlock()                                   *)\n  (* return txn                                              *)\n  (***********************************************************)\n  wp_loadField.\n  wp_apply (release_spec with \"[Hlocked Hsidcur]\").\n  { iFrame \"Hlock Hlocked\".\n    iNext.\n    unfold own_txnmgr.\n    iExists _.\n    iFrame.\n    iSplit; last done.\n    iPureIntro.\n    case_bool_decide; first done.\n    unfold N_TXN_SITES in *.\n    apply Znot_le_gt in H.\n    by apply Z.gt_lt.\n  }\n  wp_pures.\n  iApply \"H\u03a6\".\n  iMod (readonly_alloc_1 with \"idx\") as \"#Hidx_txn\".\n  iMod (readonly_alloc_1 with \"txnMgr\") as \"#Htxnmgr_txn\".\n  replace (int.nat 0) with 0%nat by word.\n  simpl.\n  eauto 20 with iFrame.\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_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.19846836749957103}}
{"text": "(* Require Import StlcFix.SpecScoping. *)\n(* Require Import StlcFix.LemmasScoping. *)\n(* Require Import StlcFix.DecideEval. *)\nRequire Import LogRelFE.PseudoType.\nRequire Import LogRelFE.LemmasPseudoType.\nRequire Import LogRelFE.LR.\nRequire Import LogRelFE.LemmasLR.\nRequire Import LogRelFE.LemmasIntro.\nRequire Import Lia.\nRequire Import Db.Lemmas.\n\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.SpecEquivalent.\nRequire Import StlcFix.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.Fix.\nRequire Import StlcEqui.SpecEquivalent.\nRequire Import StlcEqui.Size.\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.\nEnd F.\n\nModule E.\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.Fix.\n  Include StlcEqui.Size.\nEnd E.\n\nFixpoint compfe_ty (\u03c4 : F.Ty) : E.Ty :=\n  match \u03c4 with\n    | F.tunit => E.tunit\n    | F.tbool => E.tbool\n    | F.tprod \u03c41 \u03c42 => E.tprod (compfe_ty \u03c41) (compfe_ty \u03c42)\n    | F.tarr \u03c41 \u03c42 => E.tarr (compfe_ty \u03c41) (compfe_ty \u03c42)\n    | F.tsum \u03c41 \u03c42 => E.tsum (compfe_ty \u03c41) (compfe_ty \u03c42)\n  end.\n\nLemma validTy_compfe_ty {\u03c4} : ValidTy (compfe_ty \u03c4).\nProof.\n  induction \u03c4; cbn; crushValidTy.\nQed.\n\nFixpoint compfe_env (\u0393 : F.Env) : E.Env :=\n  match \u0393 with\n    | F.empty => E.empty\n    | F.evar \u0393 \u03c4 => E.evar (compfe_env \u0393) (compfe_ty \u03c4)\n  end.\n\nFixpoint compfe (t : F.Tm) : E.Tm :=\n  match t with\n    | F.var x => E.var x\n    | F.abs \u03c4 t => E.abs (compfe_ty \u03c4) (compfe t)\n    | F.app t1 t2 => E.app (compfe t1) (compfe t2)\n    | F.unit => E.unit\n    | F.true => E.true\n    | F.false => E.false\n    | F.ite t1 t2 t3 => E.ite (compfe t1) (compfe t2) (compfe t3)\n    | F.pair t1 t2 => E.pair (compfe t1) (compfe t2)\n    | F.proj\u2081 t => E.proj\u2081 (compfe t)\n    | F.proj\u2082 t => E.proj\u2082 (compfe t)\n    | F.inl t => E.inl (compfe t)\n    | F.inr t => E.inr (compfe t)\n    | F.caseof t1 t2 t3 => E.caseof (compfe t1) (compfe t2) (compfe t3)\n    | F.seq t1 t2 => E.seq (compfe t1) (compfe t2)\n    | F.fixt \u03c41 \u03c42 t => E.app (E.ufix (compfe_ty \u03c41) (compfe_ty \u03c42)) (compfe t)\n  end.\n\nFixpoint compfe_annot (t : F.TmA) : E.TmA :=\n  match t with\n    | F.a_var x => E.ea_var x\n    | F.a_abs \u03c4\u2081 \u03c4\u2082 t => E.ea_abs (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t)\n    | F.a_app \u03c4\u2081 \u03c4\u2082 t1 t2 => E.ea_app (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t1) (compfe_annot t2)\n    | F.a_unit => E.ea_unit\n    | F.a_true => E.ea_true\n    | F.a_false => E.ea_false\n    | F.a_ite \u03c4 t1 t2 t3 => E.ea_ite (compfe_ty \u03c4) (compfe_annot t1) (compfe_annot t2) (compfe_annot t3)\n    | F.a_pair \u03c4\u2081 \u03c4\u2082 t1 t2 => E.ea_pair (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t1) (compfe_annot t2)\n    | F.a_proj\u2081 \u03c4\u2081 \u03c4\u2082 t => E.ea_proj\u2081 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t)\n    | F.a_proj\u2082 \u03c4\u2081 \u03c4\u2082 t => E.ea_proj\u2082 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t)\n    | F.a_inl \u03c4\u2081 \u03c4\u2082 t => E.ea_inl (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t)\n    | F.a_inr \u03c4\u2081 \u03c4\u2082 t => E.ea_inr (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t)\n    | F.a_caseof \u03c4\u2081 \u03c4\u2082 \u03c4 t1 t2 t3 => E.ea_caseof (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_ty \u03c4) (compfe_annot t1) (compfe_annot t2) (compfe_annot t3)\n    | F.a_seq \u03c4 t\u2081 t\u2082 => E.ea_seq (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_annot t\u2082)\n    | F.a_fixt \u03c41 \u03c42 t => E.ea_app (tarr (tarr (compfe_ty \u03c41) (compfe_ty \u03c42)) (tarr (compfe_ty \u03c41) (compfe_ty \u03c42))) (tarr (compfe_ty \u03c41) (compfe_ty \u03c42)) (E.ufix_annot (compfe_ty \u03c41) (compfe_ty \u03c42)) (compfe_annot t)\n  end.\n\n(* The two compiler definitions are the same modulo type annotations. *)\nLemma compfe_compfe_annot {t} :\n  compfe (F.eraseAnnot t) = E.eraseAnnot (compfe_annot t).\nProof.\n  induction t; cbn; f_equal; try assumption; try reflexivity.\nQed.\n\nFixpoint compfe_pctx_annot (C : F.PCtxA) : E.PCtxA :=\n  match C with\n  | F.a_phole => E.ea_phole\n  | F.a_pabs \u03c4\u2081 \u03c4\u2082 C => E.ea_pabs (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C)\n  | F.a_papp\u2081 \u03c4\u2081 \u03c4\u2082 C t => E.ea_papp\u2081 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C) (compfe_annot t)\n  | F.a_papp\u2082 \u03c4\u2081 \u03c4\u2082 t C => E.ea_papp\u2082 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t) (compfe_pctx_annot C)\n  | F.a_pite\u2081 \u03c4 C t\u2082 t\u2083 => E.ea_pite\u2081 (compfe_ty \u03c4) (compfe_pctx_annot C) (compfe_annot t\u2082) (compfe_annot t\u2083)\n  | F.a_pite\u2082 \u03c4 t\u2081 C t\u2083 => E.ea_pite\u2082 (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_pctx_annot C) (compfe_annot t\u2083)\n  | F.a_pite\u2083 \u03c4 t\u2081 t\u2082 C => E.ea_pite\u2083 (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_annot t\u2082) (compfe_pctx_annot C)\n  | F.a_ppair\u2081 \u03c4\u2081 \u03c4\u2082 C t => E.ea_ppair\u2081 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C) (compfe_annot t)\n  | F.a_ppair\u2082 \u03c4\u2081 \u03c4\u2082 t C => E.ea_ppair\u2082 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_annot t) (compfe_pctx_annot C)\n  | F.a_pproj\u2081 \u03c4\u2081 \u03c4\u2082 C => E.ea_pproj\u2081 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C)\n  | F.a_pproj\u2082 \u03c4\u2081 \u03c4\u2082 C => E.ea_pproj\u2082 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C)\n  | F.a_pinl \u03c4\u2081 \u03c4\u2082 C => E.ea_pinl (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C)\n  | F.a_pinr \u03c4\u2081 \u03c4\u2082 C => E.ea_pinr (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_pctx_annot C)\n  | F.a_pcaseof\u2081 \u03c4\u2081 \u03c4\u2082 \u03c4 C t\u2082 t\u2083 => E.ea_pcaseof\u2081 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_ty \u03c4) (compfe_pctx_annot C) (compfe_annot t\u2082) (compfe_annot t\u2083)\n  | F.a_pcaseof\u2082 \u03c4\u2081 \u03c4\u2082 \u03c4 t\u2081 C t\u2083 => E.ea_pcaseof\u2082 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_pctx_annot C) (compfe_annot t\u2083)\n  | F.a_pcaseof\u2083 \u03c4\u2081 \u03c4\u2082 \u03c4 t\u2081 t\u2082 C => E.ea_pcaseof\u2083 (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082) (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_annot t\u2082) (compfe_pctx_annot C)\n  | F.a_pseq\u2081 \u03c4 C t\u2082 => E.ea_pseq\u2081 (compfe_ty \u03c4) (compfe_pctx_annot C) (compfe_annot t\u2082)\n  | F.a_pseq\u2082 \u03c4 t\u2081 C => E.ea_pseq\u2082 (compfe_ty \u03c4) (compfe_annot t\u2081) (compfe_pctx_annot C)\n  | F.a_pfixt \u03c4\u2081 \u03c4\u2082 C => E.ea_papp\u2082 (tarr (tarr (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082)) (tarr (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082)))\n                                   (tarr (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082))\n                                   (E.ufix_annot (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082))\n                                   (compfe_pctx_annot C)\n  end.\n\nLemma smoke_test_compiler :\n  (compfe_annot F.a_unit) = E.ea_unit.\nProof.\n  simpl. reflexivity.\nQed.\n\nLemma compfe_getevar_works {i \u03c4 \u0393} :\n  \u27ea i : \u03c4 \u2208 \u0393 \u27eb \u2192\n  \u27ea i : compfe_ty \u03c4 r\u2208 compfe_env \u0393 \u27eb.\nProof.\n  induction 1; constructor; assumption.\nQed.\n\nLemma compfe_typing_works {\u0393 t \u03c4} :\n  \u27ea \u0393 \u22a2 t : \u03c4 \u27eb \u2192\n  \u27ea compfe_env \u0393 e\u22a2 compfe t : compfe_ty \u03c4 \u27eb.\nProof.\n  induction 1; F.crushTyping; E.crushTyping; eauto using E.AnnotTyping, compfe_getevar_works, E.ufix_typing, validTy_compfe_ty.\nQed.\n\nLemma compfe_annot_typing_works {\u0393 t \u03c4} :\n  \u27ea \u0393 a\u22a2 t : \u03c4 \u27eb \u2192\n  \u27ea compfe_env \u0393 ea\u22a2 compfe_annot t : compfe_ty \u03c4 \u27eb.\nProof.\n  induction 1; F.crushTyping; E.crushTyping; eauto using E.AnnotTyping, compfe_getevar_works, E.ufix_annot_typing, validTy_compfe_ty.\nQed.\n\nLemma compfe_pctx_annot_typing_works {C \u0393 \u0393' \u03c4 \u03c4'} :\n  \u27ea a\u22a2 C : \u0393, \u03c4 \u2192 \u0393', \u03c4' \u27eb \u2192\n  \u27ea ea\u22a2 compfe_pctx_annot C : compfe_env \u0393, compfe_ty \u03c4 \u2192\n  compfe_env \u0393', compfe_ty \u03c4' \u27eb.\nProof.\n  induction 1; eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty.\n  - eapply compfe_annot_typing_works in H0.\n    eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty with tyvalid.\n  - eapply compfe_annot_typing_works in H.\n    eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty with tyvalid.\n  - eapply compfe_annot_typing_works in H0, H1.\n    eauto using PCtxTypingAnnot, compfe_typing_works.\n  - eapply compfe_annot_typing_works in H, H1.\n    eauto using PCtxTypingAnnot, compfe_typing_works.\n  - eapply compfe_annot_typing_works in H, H0.\n    eauto using PCtxTypingAnnot, compfe_typing_works.\n  - eapply compfe_annot_typing_works in H0.\n    eauto using PCtxTypingAnnot, compfe_typing_works.\n  - eapply compfe_annot_typing_works in H.\n    eauto using PCtxTypingAnnot, compfe_typing_works.\n  - eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty with tyvalid.\n  - eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty with tyvalid.\n  - eapply compfe_annot_typing_works in H0, H1.\n    eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty.\n  - eapply compfe_annot_typing_works in H, H1.\n    eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty.\n  - eapply compfe_annot_typing_works in H, H0.\n    eauto using PCtxTypingAnnot, compfe_typing_works, validTy_compfe_ty.\n  - eapply compfe_annot_typing_works in H0.\n    eauto using PCtxTypingAnnot, compfe_typing_works, E.ufix_annot_typing.\n  - eapply compfe_annot_typing_works in H.\n    eauto using PCtxTypingAnnot, compfe_typing_works, E.ufix_annot_typing.\n  - eauto using PCtxTypingAnnot, compfe_typing_works, E.ufix_annot_typing, validTy_compfe_ty with tyvalid2.\n    cbn.\n    constructor; eauto using ufix_annot_typing, validTy_compfe_ty with tyvalid.\nQed.\n\nLemma compileCtx_works {\u0393 i \u03c4} :\n  F.GetEvar \u0393 i \u03c4 \u2192\n  \u27ea i : embed \u03c4 p\u2208 embedCtx \u0393 \u27eb.\nProof.\n  induction 1; eauto using GetEvarP.\nQed.\n\nLocal Ltac crush :=\n  cbn in * |- ;\n  repeat\n    (cbn;\n     repeat crushLRMatch;\n     crushOfType;\n     F.crushTyping;\n     E.crushTyping;\n     repeat crushRepEmulEmbed;\n     repeat crushRecTypesMatchH;\n     repeat F.crushStlcSyntaxMatchH;\n     repeat E.crushStlcSyntaxMatchH;\n     subst;\n     trivial\n    ); try lia; eauto.\n\nLemma compiler_is_fxToIs_embed :\n  \u2200 \u03c4 : F.Ty, compfe_ty \u03c4 = fxToIs (embed \u03c4).\nProof.\n  induction \u03c4; simpl;\n    try rewrite IH\u03c41; try rewrite IH\u03c42;\n      reflexivity.\nQed.\n\nLemma compiler_is_fxToIs_embed_env :\n  \u2200 \u0393 : F.Env, compfe_env \u0393 = fxToIsCtx (embedCtx \u0393).\nProof.\n  induction \u0393; crush; apply compiler_is_fxToIs_embed.\nQed.\n\nSection CompatibilityLemmas.\n\n  Lemma compat_lambda {\u0393 \u03c4' ts d n tu \u03c4} :\n    ValidPTy \u03c4 -> ValidPTy \u03c4' -> ValidPEnv \u0393 ->\n    \u27ea \u0393 p\u25bb \u03c4' \u22a9 ts \u27e6 d , n \u27e7 tu : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 (F.abs (repEmul \u03c4') ts) \u27e6 d , n \u27e7 (E.abs (fxToIs \u03c4') tu) : ptarr \u03c4' \u03c4 \u27eb.\n  Proof.\n    crush.\n    - eauto using E.wtSub_up, envrel_implies_WtSub_equi, validTy_fxToIs.\n    - eauto using validTy_fxToIs.\n    - eauto using E.wtSub_up, envrel_implies_WtSub_equi, validTy_fxToIs.\n    - eauto using validTy_fxToIs.\n    - eauto using F.wtSub_up, envrel_implies_WtSub, validTy_fxToIs.\n    - repeat eexists; try reflexivity.\n      intros w' fw vs vu szvu vr.\n      rewrite -> ?ap_comp.\n      apply H4; [lia|].\n      eauto using extend_envrel, envrel_mono.\n  Qed.\n\n  Lemma compat_lambda_embed {\u0393 \u03c4' ts d n tu \u03c4} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4 ->\n    \u27ea \u0393 p\u25bb embed \u03c4' \u22a9 ts \u27e6 d , n \u27e7 tu : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 (F.abs \u03c4' ts) \u27e6 d , n \u27e7 (E.abs (fxToIs (embed \u03c4')) tu) : ptarr (embed \u03c4') \u03c4 \u27eb.\n  Proof.\n    intros v\u0393 v\u03c4.\n    rewrite <- (repEmul_embed_leftinv \u03c4') at 2.\n    apply compat_lambda; eauto using validPTy_embed.\n  Qed.\n\n  Lemma compat_lambda_embed' {\u0393 \u03c4' ts d n tu \u03c4} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4 ->\n    \u27ea \u0393 p\u25bb embed \u03c4' \u22a9 ts \u27e6 d , n \u27e7 tu : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 (F.abs \u03c4' ts) \u27e6 d , n \u27e7 (E.abs (compfe_ty \u03c4') tu) : ptarr (embed \u03c4') \u03c4 \u27eb.\n  Proof.\n    rewrite (compiler_is_fxToIs_embed \u03c4').\n    apply compat_lambda_embed.\n  Qed.\n\n  Lemma compat_unit {\u0393 d n} :\n    \u27ea \u0393 \u22a9 F.unit \u27e6 d , n \u27e7 E.unit : ptunit \u27eb.\n  Proof.\n    crush.\n  Qed.\n\n  Lemma compat_true {\u0393 d n} :\n    \u27ea \u0393 \u22a9 F.true \u27e6 d , n \u27e7 E.true : ptbool \u27eb.\n  Proof.\n    crush.\n  Qed.\n\n  Lemma compat_false {\u0393 d n} :\n    \u27ea \u0393 \u22a9 F.false \u27e6 d , n \u27e7 E.false : ptbool \u27eb.\n  Proof.\n    crush.\n  Qed.\n\n  Lemma compat_pair {\u0393 d n ts\u2081 tu\u2081 \u03c4\u2081 ts\u2082 tu\u2082 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts\u2081 \u27e6 d , n \u27e7 tu\u2081 : \u03c4\u2081 \u27eb \u2192\n    \u27ea \u0393 \u22a9 ts\u2082 \u27e6 d , n \u27e7 tu\u2082 : \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.pair ts\u2081 ts\u2082 \u27e6 d , n \u27e7 E.pair tu\u2081 tu\u2082 : ptprod \u03c4\u2081 \u03c4\u2082 \u27eb.\n  Proof.\n    crush.\n    apply termrel_pair; crush.\n    refine (H5 w' _ _ _ _); unfold lev in *; try lia.\n    eauto using envrel_mono.\n  Qed.\n\n  Lemma compat_app {\u0393 d n ts\u2081 tu\u2081 \u03c4\u2081 ts\u2082 tu\u2082 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts\u2081 \u27e6 d , n \u27e7 tu\u2081 : ptarr \u03c4\u2081 \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 ts\u2082 \u27e6 d , n \u27e7 tu\u2082 : \u03c4\u2081 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.app ts\u2081 ts\u2082 \u27e6 d , n \u27e7 E.app tu\u2081 tu\u2082 : \u03c4\u2082 \u27eb.\n  Proof.\n    intros v\u0393 v\u03c4\u2081 v\u03c4\u2082.\n    crush.\n    refine (termrel_app v\u03c4\u2081 _ _ _); crush.\n    refine (H2 w' _ _ _ _); unfold lev in *; try lia.\n    eauto using envrel_mono.\n  Qed.\n\n  Lemma compat_inl {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : \u03c4\u2081 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.inl ts \u27e6 d , n \u27e7 E.inl tu : ptsum \u03c4\u2081 \u03c4\u2082 \u27eb.\n  Proof.\n    crush; eauto using validTy_fxToIs.\n    refine (termrel_inl _ _ _); crush.\n  Qed.\n\n  Lemma compat_inr {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.inr ts \u27e6 d , n \u27e7 E.inr tu : ptsum \u03c4\u2081 \u03c4\u2082 \u27eb.\n  Proof.\n    crush; eauto using validTy_fxToIs.\n    refine (termrel_inr _ _ _); crush.\n  Qed.\n\n  Lemma compat_seq {\u0393 d n ts\u2081 tu\u2081 ts\u2082 tu\u2082 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts\u2081 \u27e6 d , n \u27e7 tu\u2081 : ptunit \u27eb \u2192\n    \u27ea \u0393 \u22a9 ts\u2082 \u27e6 d , n \u27e7 tu\u2082 : \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.seq ts\u2081 ts\u2082 \u27e6 d , n \u27e7 E.seq tu\u2081 tu\u2082 : \u03c4\u2082 \u27eb.\n  Proof.\n    crush.\n    apply termrel_seq; crush.\n    refine (H4 w' _ _ _ _); crush.\n    eauto using envrel_mono.\n  Qed.\n\n  Lemma compat_proj\u2082 {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : ptprod \u03c4\u2081 \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.proj\u2082 ts \u27e6 d , n \u27e7 E.proj\u2082 tu : \u03c4\u2082 \u27eb.\n  Proof.\n    intros v\u0393 v\u03c4\u2081 v\u03c4\u2082.\n    crush.\n    refine (termrel_proj\u2082 v\u03c4\u2081 _ _); crush.\n  Qed.\n\n  Lemma compat_proj\u2081 {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : ptprod \u03c4\u2081 \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.proj\u2081 ts \u27e6 d , n \u27e7 E.proj\u2081 tu : \u03c4\u2081 \u27eb.\n  Proof.\n    intros v\u0393 v\u03c4\u2081 v\u03c4\u2082.\n    crush.\n    refine (termrel_proj\u2081 v\u03c4\u2081 v\u03c4\u2082 _); crush.\n  Qed.\n\n  Lemma compat_ite {\u0393 d n ts\u2081 tu\u2081 ts\u2082 tu\u2082 ts\u2083 tu\u2083 \u03c4} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4 ->\n    \u27ea \u0393 \u22a9 ts\u2081 \u27e6 d , n \u27e7 tu\u2081 : ptbool \u27eb \u2192\n    \u27ea \u0393 \u22a9 ts\u2082 \u27e6 d , n \u27e7 tu\u2082 : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 ts\u2083 \u27e6 d , n \u27e7 tu\u2083 : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.ite ts\u2081 ts\u2082 ts\u2083 \u27e6 d , n \u27e7 E.ite tu\u2081 tu\u2082 tu\u2083 : \u03c4 \u27eb.\n  Proof.\n    crush.\n    apply termrel_ite; crush.\n    - refine (H7 w' _ _ _ _); crush.\n      eauto using envrel_mono.\n    - refine (H5 w' _ _ _ _); crush.\n      eauto using envrel_mono.\n  Qed.\n\n  Lemma compat_caseof {\u0393 d n ts\u2081 tu\u2081 ts\u2082 tu\u2082 ts\u2083 tu\u2083 \u03c4\u2081 \u03c4\u2082 \u03c4} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts\u2081 \u27e6 d , n \u27e7 tu\u2081 : ptsum \u03c4\u2081 \u03c4\u2082 \u27eb \u2192\n    \u27ea \u0393 p\u25bb \u03c4\u2081 \u22a9 ts\u2082 \u27e6 d , n \u27e7 tu\u2082 : \u03c4 \u27eb \u2192\n    \u27ea \u0393 p\u25bb \u03c4\u2082 \u22a9 ts\u2083 \u27e6 d , n \u27e7 tu\u2083 : \u03c4 \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.caseof ts\u2081 ts\u2082 ts\u2083 \u27e6 d , n \u27e7 E.caseof tu\u2081 tu\u2082 tu\u2083 : \u03c4 \u27eb.\n  Proof.\n    intros v\u0393 v\u03c4\u2081 v\u03c4\u2082.\n    crush; eauto using validTy_fxToIs.\n    refine (termrel_caseof v\u03c4\u2081 v\u03c4\u2082 _ _ _); crush;\n    rewrite -> ?ap_comp.\n    - refine (H5 w' _ _ _ _); [lia|].\n      eauto using extend_envrel, envrel_mono.\n    - refine (H3 w' _ _ _ _); [lia|].\n      eauto using extend_envrel, envrel_mono.\n  Qed.\n\n  Lemma compat_fix {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPEnv \u0393 -> ValidPTy \u03c4\u2081 -> ValidPTy \u03c4\u2082 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : ptarr (ptarr \u03c4\u2081 \u03c4\u2082) (ptarr \u03c4\u2081 \u03c4\u2082) \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.fixt (repEmul \u03c4\u2081) (repEmul \u03c4\u2082) ts \u27e6 d , n \u27e7 E.app (E.ufix (fxToIs \u03c4\u2081) (fxToIs \u03c4\u2082)) tu : ptarr \u03c4\u2081 \u03c4\u2082 \u27eb.\n  Proof.\n    crush.\n    - eauto using E.ufix_typing, validTy_fxToIs.\n    - refine (termrel_fix _ _ _); crush.\n  Qed.\n\n  Lemma compat_fix' {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPEnv \u0393 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : embed (F.tarr (F.tarr \u03c4\u2081 \u03c4\u2082) (F.tarr \u03c4\u2081 \u03c4\u2082)) \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.fixt \u03c4\u2081 \u03c4\u2082 ts \u27e6 d , n \u27e7 E.app (E.ufix (compfe_ty \u03c4\u2081) (compfe_ty \u03c4\u2082)) tu : ptarr (embed \u03c4\u2081) (embed \u03c4\u2082) \u27eb.\n  Proof.\n    intros v\u0393 tr.\n    rewrite <- (repEmul_embed_leftinv \u03c4\u2081) at 1.\n    rewrite <- (repEmul_embed_leftinv \u03c4\u2082) at 1.\n    rewrite (compiler_is_fxToIs_embed \u03c4\u2081) at 1.\n    rewrite (compiler_is_fxToIs_embed \u03c4\u2082) at 1.\n    apply compat_fix; eauto using validPTy_embed.\n  Qed.\n\n  Lemma compat_fix'' {\u0393 d n ts tu \u03c4\u2081 \u03c4\u2082} :\n    ValidPEnv \u0393 ->\n    \u27ea \u0393 \u22a9 ts \u27e6 d , n \u27e7 tu : embed (F.tarr (F.tarr \u03c4\u2081 \u03c4\u2082) (F.tarr \u03c4\u2081 \u03c4\u2082)) \u27eb \u2192\n    \u27ea \u0393 \u22a9 F.fixt \u03c4\u2081 \u03c4\u2082 ts \u27e6 d , n \u27e7 E.app (E.ufix (fxToIs (embed \u03c4\u2081)) (fxToIs (embed \u03c4\u2082))) tu : ptarr (embed \u03c4\u2081) (embed \u03c4\u2082) \u27eb.\n  Proof.\n    rewrite <- (compiler_is_fxToIs_embed \u03c4\u2081) at 1.\n    rewrite <- (compiler_is_fxToIs_embed \u03c4\u2082) at 1.\n    exact compat_fix'.\n  Qed.\n\n  Lemma compfe_correct {\u0393 d n ts \u03c4} :\n    \u27ea \u0393 \u22a2 ts : \u03c4 \u27eb \u2192\n    \u27ea embedCtx \u0393 \u22a9 ts \u27e6 d , n \u27e7 compfe ts : embed \u03c4 \u27eb.\n  Proof.\n    induction 1;\n      cbn -[E.ufix_annot E.ufix\u2081_annot];\n      rewrite ?compiler_is_fxToIs_embed, ?eraseAnnot_ufix;\n      eauto using compat_inl\n      , compat_inr\n      , compat_pair\n      , compat_lambda_embed\n      , compat_app\n      , compat_false, compat_true\n      , compat_var\n      , compat_unit\n      , embedCtx_works\n      , compat_seq\n      , compat_ite, compat_proj\u2081, compat_proj\u2082\n      , compat_caseof\n      , compat_fix''\n      , validPTy_embed\n      , validPEnv_embedCtx.\n  Qed.\n\n  Lemma compfe_correct' {\u0393 d n ts \u03c4 \u03c4'} :\n    \u27ea \u0393 \u22a2 ts : \u03c4 \u27eb \u2192\n    \u03c4' = embed \u03c4 ->\n    \u27ea embedCtx \u0393 \u22a9 ts \u27e6 d , n \u27e7 compfe ts : \u03c4' \u27eb.\n  Proof.\n    intros; subst; now eapply compfe_correct.\n  Qed.\n\n  Lemma compfe_annot_correct {\u0393 d n ts \u03c4} :\n    \u27ea \u0393 a\u22a2 ts : \u03c4 \u27eb \u2192\n    \u27ea embedCtx \u0393 \u22a9 F.eraseAnnot ts \u27e6 d , n \u27e7 E.eraseAnnot (compfe_annot ts) : embed \u03c4 \u27eb.\n  Proof.\n    induction 1;\n      cbn -[E.ufix_annot E.ufix\u2081_annot];\n      rewrite ?compiler_is_fxToIs_embed, ?eraseAnnot_ufix;\n      eauto using compat_inl\n      , compat_inr\n      , compat_pair\n      , compat_lambda_embed\n      , compat_app\n      , compat_false, compat_true\n      , compat_var\n      , compat_unit\n      , embedCtx_works\n      , compat_seq\n      , compat_ite, compat_proj\u2081, compat_proj\u2082\n      , compat_caseof\n      , compat_fix''\n      , validPTy_embed\n      , validPEnv_embedCtx.\n  Qed.\n\n  Lemma compfe_ctx_correct {\u0393 \u0393' d n C \u03c4 \u03c4'} :\n    \u27ea a\u22a2 C : \u0393 , \u03c4 \u2192 \u0393' , \u03c4'\u27eb \u2192\n    \u27ea \u22a9 F.eraseAnnot_pctx C \u27e6 d , n \u27e7 eraseAnnot_pctx (compfe_pctx_annot C) : embedCtx \u0393 , embed \u03c4 \u2192 embedCtx \u0393' , embed \u03c4' \u27eb.\n  Proof.\n    intros ty; unfold OpenLRCtxN; split; [|split];\n      rewrite <-?compiler_is_fxToIs_embed in *;\n      rewrite <-?compiler_is_fxToIs_embed_env in *;\n      rewrite ?repEmul_embed_leftinv in *;\n      rewrite ?repEmulCtx_embedCtx_leftinv in *;\n      eauto using F.eraseAnnot_pctxT, E.eraseAnnot_pctxT, compfe_pctx_annot_typing_works, F.pctxtyping_app, F.eraseAnnot_pctxT, E.pctxtyping_app, E.eraseAnnot_pctxT.\n\n    induction ty; simpl;\n    intros ts tu lr;\n      try assumption; (* deal with phole *)\n      specialize (IHty ts tu lr);\n      rewrite <-?compfe_compfe_annot;\n      repeat (try match goal with\n             | [ |- \u27ea_\u22a9 F.abs _ _ \u27e6d,n\u27e7 E.abs _ _ : _ \u27eb ] => eapply compat_lambda_embed'\n             | [ |- \u27ea_\u22a9 F.app _ _ \u27e6d,n\u27e7 E.app _ _ : _ \u27eb ] => eapply compat_app\n             | [ |- \u27ea_\u22a9 F.ite _ _ _ \u27e6d,n\u27e7 E.ite _ _ _ : _ \u27eb ] => eapply compat_ite\n             | [ |- \u27ea_\u22a9 F.pair _ _ \u27e6d,n\u27e7 E.pair _ _ : _ \u27eb ] => eapply compat_pair\n             | [ |- \u27ea_\u22a9 F.inl _ \u27e6d,n\u27e7 E.inl _ : _ \u27eb ] => eapply compat_inl\n             | [ |- \u27ea_\u22a9 F.inr _ \u27e6d,n\u27e7 E.inr _ : _ \u27eb ] => eapply compat_inr\n             | [ |- \u27ea_\u22a9 F.proj\u2081 _ \u27e6d,n\u27e7 E.proj\u2081 _ : _ \u27eb ] => eapply compat_proj\u2081\n             | [ |- \u27ea_\u22a9 F.proj\u2082 _ \u27e6d,n\u27e7 E.proj\u2082 _ : _ \u27eb ] => eapply compat_proj\u2082\n             | [ |- \u27ea_\u22a9 F.fixt _ _ _ \u27e6d,n\u27e7 _ : _ \u27eb ] => eapply compat_fix'\n             | [ |- \u27ea_\u22a9 F.caseof _ _ _ \u27e6d,n\u27e7 E.caseof _ _ _ : _ \u27eb ] => eapply compat_caseof\n             | [ |- \u27ea_\u22a9 F.seq _ _ \u27e6d,n\u27e7 E.seq _ _ : _ \u27eb ] => eapply compat_seq\n             (* | [ |- context[ ptarr (embed ?\u03c41) (embed ?\u03c42) ]] => *)\n             (*   change (ptarr (embed \u03c41) (embed \u03c42)) with (embed (F.tarr \u03c41 \u03c42)) *)\n             | [ |- \u27ea_\u22a9 _ \u27e6d,n\u27e7 compfe _ : _ \u27eb ] => eapply compfe_correct'\n             | [ |- \u27ea _ \u22a2 F.eraseAnnot _ : _ \u27eb ] => eapply F.eraseAnnotT\n             | [ |- \u27ea _ \u22a2 E.eraseAnnot _ : _ \u27eb ] => eapply E.eraseAnnotT\n              end;\n              eauto using validPTy_embed, validPEnv_embedCtx;\n              try eassumption;\n              fold embed;\n              try reflexivity;\n              change (embedCtx ?\u0393 p\u25bb embed ?\u03c4) with (embedCtx (\u0393 \u25bb \u03c4))).\n  Qed.\n\nEnd CompatibilityLemmas.\n\nLemma equivalenceReflection {\u0393 t\u2081 t\u2082 \u03c4} :\n  \u27ea \u0393 \u22a2 t\u2081 : \u03c4 \u27eb \u2192\n  \u27ea \u0393 \u22a2 t\u2082 : \u03c4 \u27eb \u2192\n  \u27ea compfe_env \u0393 e\u22a2 compfe t\u2081 \u2243 compfe t\u2082 : compfe_ty \u03c4 \u27eb \u2192\n  \u27ea \u0393 \u22a2 t\u2081 \u2243 t\u2082 : \u03c4 \u27eb.\nProof.\n  revert t\u2081 t\u2082 \u03c4.\n  enough (\u2200 {t\u2081 t\u2082} \u03c4,\n            \u27ea \u0393 \u22a2 t\u2081 : \u03c4 \u27eb \u2192\n            \u27ea \u0393 \u22a2 t\u2082 : \u03c4 \u27eb \u2192\n            \u27ea compfe_env \u0393 e\u22a2 compfe t\u2081 \u2243 compfe t\u2082 : compfe_ty \u03c4 \u27eb \u2192\n            \u2200 C \u03c4',\n              \u27ea a\u22a2 C : \u0393 , \u03c4 \u2192 F.empty, \u03c4' \u27eb \u2192\n                    F.Terminating (F.pctx_app t\u2081 (F.eraseAnnot_pctx C)) \u2192 F.Terminating (F.pctx_app t\u2082 (F.eraseAnnot_pctx C))) as Hltor\n  by (intros t\u2081 t\u2082 \u03c4 ty1 ty2 eq C \u03c4';\n      assert (\u27ea compfe_env \u0393 e\u22a2 compfe t\u2082 \u2243 compfe t\u2081 : compfe_ty \u03c4 \u27eb)\n        by (apply E.pctx_equiv_symm; assumption);\n  split;\n  refine (Hltor _ _ \u03c4 _ _ _ C \u03c4' _); assumption).\n\n  intros t\u2081 t\u2082 \u03c4 ty1 ty2 eq C \u03c4' tyC term.\n\n  destruct (F.Terminating_TermHor term) as [n termN]; clear term.\n\n  assert (\u27ea embedCtx \u0393 \u22a9 t\u2081 \u27e6 dir_lt , S n \u27e7 compfe t\u2081 : embed \u03c4 \u27eb) as lrt\u2081 by exact (compfe_correct ty1).\n\n  assert (\u27ea \u22a9 (F.eraseAnnot_pctx C) \u27e6 dir_lt , S n \u27e7 E.eraseAnnot_pctx (compfe_pctx_annot C) : embedCtx \u0393 , embed \u03c4 \u2192 pempty , embed \u03c4' \u27eb) as lrC_lt\n      by apply (compfe_ctx_correct tyC).\n\n  apply lrC_lt in lrt\u2081.\n\n  assert (E.Terminating (E.pctx_app (compfe t\u2081) (E.eraseAnnot_pctx (compfe_pctx_annot C))))\n    as termu\u2081 by (apply (adequacy_lt lrt\u2081 termN); lia).\n\n  assert (E.Terminating (E.pctx_app (compfe t\u2082) (E.eraseAnnot_pctx (compfe_pctx_annot C)))).\n  eapply eq; try assumption; eauto using compfe_pctx_annot_typing_works, validTy_compfe_ty.\n  apply (compfe_pctx_annot_typing_works tyC).\n\n  destruct (E.Terminating_TermHor H) as [n' termN']; clear H.\n\n  assert (\u27ea \u22a9 F.eraseAnnot_pctx C \u27e6 dir_gt , S n' \u27e7 E.eraseAnnot_pctx (compfe_pctx_annot C) : embedCtx \u0393 , embed \u03c4 \u2192 pempty , embed \u03c4' \u27eb) as lrC_gt\n    by (apply (compfe_ctx_correct tyC)).\n\n  assert (\u27ea embedCtx \u0393 \u22a9 t\u2082 \u27e6 dir_gt , S n' \u27e7 compfe t\u2082 : embed \u03c4 \u27eb) as lrt\u2082 by exact (compfe_correct ty2).\n\n  apply lrC_gt in lrt\u2082.\n\n  apply (adequacy_gt lrt\u2082 termN'); lia.\nQed.\n\nLemma equivalenceReflectionEmpty {t\u2081 t\u2082 \u03c4} :\n  \u27ea F.empty \u22a2 t\u2081 : \u03c4 \u27eb \u2192\n  \u27ea F.empty \u22a2 t\u2082 : \u03c4 \u27eb \u2192\n  \u27ea E.empty e\u22a2 compfe t\u2081 \u2243 compfe t\u2082 : compfe_ty \u03c4 \u27eb \u2192\n  \u27ea F.empty \u22a2 t\u2081 \u2243 t\u2082 : \u03c4 \u27eb.\nProof.\n  apply @equivalenceReflection.\nQed.\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/CompilerFE/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19846836749957103}}
{"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 Lia.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import OQL.\nRequire Import NRAEnvRuntime.\n\nSection OQLtoNRAEnv.\n  Context {fruntime:foreign_runtime}.\n\n  Section query_var.\n    Context (deflist:list string).\n\n  (*****************************\n   * OQL to NRAEnv translation *\n   *****************************)\n\n  Definition lookup_table (table_name:string) : nraenv\n    := if in_dec string_eqdec table_name deflist\n       then NRAEnvUnop (OpDot table_name) NRAEnvEnv\n       else NRAEnvGetConstant table_name.\n\n  Fixpoint oql_to_nraenv_expr (e:oql_expr) : nraenv :=\n    match e with\n    | OConst d => NRAEnvConst d\n    | OVar v => NRAEnvUnop (OpDot v) NRAEnvID\n    | OTable t => lookup_table t\n    | OBinop b e1 e2 => NRAEnvBinop b (oql_to_nraenv_expr e1) (oql_to_nraenv_expr e2)\n    | OUnop u e1 => NRAEnvUnop u (oql_to_nraenv_expr e1)\n    | OSFW select_clause from_clause where_clause order_clause =>\n      let nraenv_of_from (opacc:nraenv) (from_in_expr : oql_in_expr) :=\n          match from_in_expr with\n            | OIn in_v from_expr =>\n              NRAEnvMapProduct (NRAEnvMap (NRAEnvUnop (OpRec in_v) NRAEnvID) (oql_to_nraenv_expr from_expr)) opacc\n            | OInCast in_v brand_name from_expr =>\n              NRAEnvMapProduct (NRAEnvMap (NRAEnvUnop (OpRec in_v) NRAEnvID)\n                                 (NRAEnvUnop OpFlatten\n                                         (NRAEnvMap\n                                            (NRAEnvEither (NRAEnvUnop OpBag NRAEnvID)\n                                                      (NRAEnvConst (dcoll nil)))\n                                            (NRAEnvMap (NRAEnvUnop (OpCast (brand_name::nil)) NRAEnvID)\n                                                   (oql_to_nraenv_expr from_expr))\n                                         )))\n                          opacc\n          end\n      in\n      let nraenv_of_from_clause :=\n          fold_left nraenv_of_from from_clause (NRAEnvUnop OpBag NRAEnvID)\n      in\n      let nraenv_of_where_clause :=\n          match where_clause with\n          | OTrue => nraenv_of_from_clause\n          | OWhere where_expr =>\n            NRAEnvSelect (oql_to_nraenv_expr where_expr) nraenv_of_from_clause\n          end\n      in\n      let nraenv_of_order_clause :=\n          match order_clause with\n          | ONoOrder => nraenv_of_where_clause\n          | OOrderBy e sc => nraenv_of_where_clause\n          end\n      in\n      match select_clause with\n      | OSelect select_expr =>\n        NRAEnvMap (oql_to_nraenv_expr select_expr) nraenv_of_order_clause\n      | OSelectDistinct select_expr =>\n        NRAEnvUnop OpDistinct (NRAEnvMap (oql_to_nraenv_expr select_expr) nraenv_of_order_clause)\n      end\n    end.\n\n  End query_var.\n\n  Fixpoint oql_to_nraenv_query_program\n               (defllist:list string) (oq:oql_query_program) : nraenv\n    := match oq with\n       | ODefineQuery s e rest =>\n         NRAEnvAppEnv \n              (oql_to_nraenv_query_program (s::defllist) rest)\n              (NRAEnvBinop OpRecConcat\n                      NRAEnvEnv\n                      (NRAEnvUnop (OpRec s)\n                                  (oql_to_nraenv_expr defllist e)))\n       | OUndefineQuery s rest =>\n         NRAEnvAppEnv\n           (oql_to_nraenv_query_program (remove_all s defllist) rest)\n           (NRAEnvUnop (OpRecRemove s) NRAEnvEnv)\n       | OQuery q => \n         oql_to_nraenv_expr defllist q\n       end.\n\n  Definition oql_to_nraenv (q:oql) : nraenv\n    := NRAEnvAppEnv \n         (NRAEnvApp (oql_to_nraenv_query_program nil q)\n                    (NRAEnvConst (drec nil)))\n         (NRAEnvConst (drec nil)).\n\n\n  (***************************\n   * Translation correctness *\n   ***************************)\n  \n  (* Some useful lemmas *)\n\n  Lemma lift_map_rec_concat_map_is_map_rec_concat_map a s l1 :\n    lift_map\n      (fun x : data =>\n         match x with\n         | dunit => None\n         | dnat _ => None\n         | dfloat _ => None\n         | dbool _ => None\n         | dstring _ => None\n         | dcoll _ => None\n         | drec r1 => Some (drec (rec_concat_sort a r1))\n         | dleft _ => None\n         | dright _ => None\n         | dbrand _ _ => None\n         | dforeign _ => None\n         end) (map (fun d : data => drec ((s, d) :: nil)) l1) =\n    Some (map (fun x : list (string * data) => drec (rec_concat_sort a x))\n              (map (fun x : data => (s, x) :: nil) l1)).\n  Proof.\n    induction l1; [reflexivity| ]; simpl.\n    rewrite IHl1; simpl.\n    reflexivity.\n  Qed.\n                                                        \n  Lemma flatten_either_is_lift_map_either h bn l0:\n    (olift oflatten\n           (olift\n              (lift_map\n                 (fun x : data =>\n                    match x with\n                    | dunit => None\n                    | dnat _ => None\n                    | dfloat _ => None\n                    | dbool _ => None\n                    | dstring _ => None\n                    | dcoll _ => None\n                    | drec _ => None\n                    | dleft dl => Some (dcoll (dl :: nil))\n                    | dright _ => Some (dcoll nil)\n                    | dbrand _ _ => None\n                    | dforeign _ => None\n                    end))\n              (lift_map\n                 (fun x : data =>\n                    match x with\n                    | dunit => None\n                    | dnat _ => None\n                    | dfloat _ => None\n                    | dbool _ => None\n                    | dstring _ => None\n                    | dcoll _ => None\n                    | drec _ => None\n                    | dleft _ => None\n                    | dright _ => None\n                    | dbrand b' _ =>\n                      if sub_brands_dec h b' (bn :: nil)\n                      then Some (dsome x)\n                      else Some dnone\n                    | dforeign _ => None\n                    end) l0))) =\n    lift_flat_map\n      (fun x : data =>\n         match x with\n         | dunit => None\n         | dnat _ => None\n         | dfloat _ => None\n         | dbool _ => None\n         | dstring _ => None\n         | dcoll _ => None\n         | drec _ => None\n         | dleft _ => None\n         | dright _ => None\n         | dbrand b' _ =>\n           if sub_brands_dec h b' (bn :: nil)\n           then Some (x :: nil)\n           else Some nil\n         | dforeign _ => None\n         end) l0.\n  Proof.\n    induction l0; [reflexivity| ]; simpl.\n    destruct a; try reflexivity.\n    destruct (sub_brands_dec h b (bn :: nil)); simpl;\n    rewrite <- IHl0;\n      destruct ((lift_map\n             (fun x : data =>\n              match x with\n              | dunit => None\n              | dnat _ => None\n              | dfloat _ => None\n              | dbool _ => None\n              | dstring _ => None\n              | dcoll _ => None\n              | drec _ => None\n              | dleft _ => None\n              | dright _ => None\n              | dbrand b' _ =>\n                  if sub_brands_dec h b' (bn :: nil)\n                  then Some (dsome x)\n                  else Some dnone\n              | dforeign _ => None\n              end) l0)); simpl; try reflexivity;\n      destruct (lift_map\n          (fun x : data =>\n           match x with\n           | dunit => None\n           | dnat _ => None\n           | dfloat _ => None\n           | dbool _ => None\n           | dstring _ => None\n           | dcoll _ => None\n           | drec _ => None\n           | dleft dl => Some (dcoll (dl :: nil))\n           | dright _ => Some (dcoll nil)\n           | dbrand _ _ => None\n           | dforeign _ => None\n           end) l); reflexivity.\n  Qed.\n  \n  Lemma map_map_drec_works s a l1 l2:\n    dcoll\n      (map (fun x : list (string * data) => drec (rec_concat_sort a x))\n           (map (fun x : data => (s, x) :: nil) l1) ++ \n           map drec l2) =\n    (dcoll\n       (map drec\n            (map (fun x : list (string * data) => rec_concat_sort a x)\n                 (map (fun x : data => (s, x) :: nil) l1) ++ l2))).\n  Proof.\n    rewrite map_map.\n    rewrite map_map.\n    rewrite map_app.\n    rewrite map_map.\n    reflexivity.\n  Qed.\n\n  Lemma push_lift_coll_in_lift_map l f :\n    olift (fun x0 : list oql_env => lift dcoll (lift_map f x0)) l =\n    lift dcoll (olift (fun x0 : list oql_env => (lift_map f x0)) l).\n  Proof.\n    destruct l; reflexivity.\n  Qed.\n\n  Lemma olift_rondcoll_over_dcoll l f :\n    (olift (fun d : data => rondcoll f d) (lift dcoll l)) =\n    (lift (fun x : list data => dcoll (f x)) l).\n  Proof.\n    destruct l; reflexivity.\n  Qed.\n\n  Lemma map_env_with_drec (s:string) (l:list data) :\n    (map (fun d : data => drec ((s, d) :: nil)) l) =\n    (map drec (map (fun x : data => (s, x) :: nil) l)).\n  Proof.\n    induction l; try reflexivity; simpl in *.\n    rewrite IHl; reflexivity.\n  Qed.\n\n  Lemma pull_drec_from_map_concat (s:string) env l :\n    Some (map drec\n              (env_map_concat_single env (map (fun x : data => (s, x) :: nil) l))) =\n    omap_concat (drec env) (map drec (map (fun x : data => (s, x) :: nil) l)).\n  Proof.\n    induction l; try reflexivity; simpl in *.\n    unfold omap_concat in *; simpl in *.\n    unfold env_map_concat_single in *; simpl in *.\n    rewrite <- IHl; simpl.\n    reflexivity.\n  Qed.\n\n  Lemma oql_nra_dual_map_concat (s:string) env l:\n    Some\n      (dcoll\n         (map drec\n              (env_map_concat_single env\n                                     (map (fun x : data => (s, x) :: nil) l)))) =\n    lift dcoll\n         match\n           omap_concat (drec env)\n                       (map (fun d : data => drec ((s, d) :: nil)) l)\n         with\n         | Some x' => Some (x' ++ nil)\n         | None => None\n         end.\n  Proof.\n    rewrite map_env_with_drec.\n    idtac.\n    rewrite <- pull_drec_from_map_concat; simpl.\n    rewrite app_nil_r.\n    reflexivity.\n  Qed.\n\n  Lemma lift_map_orecconcat_lift_map_drec s a l0 :\n    lift_map (fun x : data => orecconcat (drec a) x)\n         (map (fun d : data => drec ((s, d) :: nil)) l0) =\n    Some (map (fun d : data => drec (rec_concat_sort a ((s,d)::nil))) l0).\n  Proof.\n    induction l0; try reflexivity; simpl in *.\n    rewrite IHl0; reflexivity.\n  Qed.\n\n  Lemma map_drec_app s a l0 l1:\n    map (fun d : data => drec (rec_concat_sort a ((s, d) :: nil))) l0 ++\n        map drec l1 =\n    map drec\n        (map (fun x : list (string * data) => rec_concat_sort a x)\n             (map (fun x : data => (s, x) :: nil) l0) ++ l1).\n  Proof.\n    rewrite map_app.\n    repeat rewrite map_map.\n    trivial.\n  Qed.\n\n\n  (*****************************\n   * Select clause correctness *\n   *****************************)\n\n  Section correct.\n    Context (h:brand_relation_t).\n    Context (constant_env:list (string*data)).\n\n    Lemma nraenv_of_select_expr_correct defls\n          (o:oql_expr) xenv (env0 : option (list oql_env)) :\n      (forall xenv (env : oql_env),\n          oql_expr_interp h (rec_concat_sort constant_env defls) o env =\n          (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 (drec env) \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv) ->\n      olift (fun x0 : list oql_env => lift dcoll (lift_map (oql_expr_interp h (rec_concat_sort constant_env defls) o) x0)) env0 =\n    olift\n      (fun d : data =>\n         lift_oncoll\n           (fun c1 : list data =>\n              lift dcoll\n                   (lift_map\n                      (nraenv_eval h constant_env (oql_to_nraenv_expr (domain defls) o) (drec (rec_concat_sort xenv defls)))\n                      c1)) d) (lift (fun x => dcoll (map drec x)) env0).\n    Proof.\n      intros.\n      destruct env0; [|reflexivity]; simpl.\n      induction l; simpl; try reflexivity.\n      rewrite (H xenv).\n      destruct (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 (drec a) \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv; simpl;\n        [|reflexivity].\n      destruct (lift_map (oql_expr_interp h (rec_concat_sort constant_env defls) o) l);\n        destruct (lift_map (nraenv_eval h constant_env (oql_to_nraenv_expr (domain defls) o) (drec (rec_concat_sort xenv defls)))\n                       (map drec l)); simpl in *; congruence.\n    Qed.\n\n    (***************************\n     * From clause correctness *\n     ***************************)\n\n    (* first off, prove the one-step used in the fold correctly adds one\n     variable and does cartesian product (i.e., MapProduct) *)\n    Lemma one_from_fold_step_is_map_concat defls s o op xenv envs envs0:\n      (h \u22a2 op @\u2093 envs \u22a3 constant_env ; (drec (rec_concat_sort xenv defls)))%nraenv =\n      lift (fun x : list (list (string * data)) => dcoll (map drec x)) envs0 ->\n      (forall xenv0 (env : oql_env),\n          oql_expr_interp h (rec_concat_sort constant_env defls) o env =\n          (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 drec env \u22a3 constant_env; (drec (rec_concat_sort xenv0 defls)))%nraenv) ->\n      ((h \u22a2 (NRAEnvMapProduct (NRAEnvMap (NRAEnvUnop (OpRec s) NRAEnvID) (oql_to_nraenv_expr (domain defls) o)) op) @\u2093 envs \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv =\n       lift (fun x : list (list (string * data)) => dcoll (map drec x))\n            (match envs0 with\n             | Some envl' =>\n               env_map_concat s (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n             | None => None\n             end)).\n    Proof.\n      intros; simpl.\n      unfold nraenv_eval in *; simpl.\n      rewrite H; simpl; clear H.\n      destruct envs0; [|reflexivity]; simpl.\n      induction l; try reflexivity; simpl.\n      unfold env_map_concat in *; simpl.\n      unfold omap_product in *; simpl.\n      unfold oncoll_map_concat in *; simpl.\n      unfold oenv_map_concat_single in *; simpl.\n      rewrite (H0 xenv).\n      destruct (cNRAEnv.nraenv_core_eval h constant_env\n                                         (nraenv_to_nraenv_core (oql_to_nraenv_expr (domain defls) o))\n                                         (drec (rec_concat_sort xenv defls))\n                                         (drec a))%nraenv;\n        try reflexivity; simpl.\n      destruct d; try reflexivity; simpl.\n      autorewrite with alg; simpl.\n      unfold omap_concat in *.\n      rewrite lift_map_orecconcat_lift_map_drec.\n      destruct ((lift_flat_map\n                   (fun a0 : oql_env =>\n                      match oql_expr_interp h (rec_concat_sort constant_env defls) o a0 with\n                      | Some (dcoll y) =>\n                        Some\n                          (env_map_concat_single a0\n                                                 (map (fun x : data => (s, x) :: nil) y))\n                      | Some _ => None\n                      | None => None\n                      end) l));\n        destruct (lift_flat_map\n                    (fun a0 : data =>\n                       match\n                         olift\n                           (fun d : data =>\n                              lift_oncoll\n                                (fun c1 : list data =>\n                                   lift dcoll\n                                        (lift_map\n                                           (fun x : data => Some (drec ((s, x) :: nil)))\n                                           c1)) d)\n                           (cNRAEnv.nraenv_core_eval h constant_env\n                                                     (nraenv_to_nraenv_core (oql_to_nraenv_expr (domain defls) o)) (drec (rec_concat_sort xenv defls)) a0)%nraenv\n                       with\n                       | Some (dcoll y) => lift_map (fun x : data => orecconcat a0 x) y\n                       | Some _ => None\n                       | None => None\n                       end) (map drec l)); simpl in *; try congruence; simpl in *.\n      inversion IHl. subst; simpl.\n      unfold env_map_concat_single; simpl.\n      rewrite map_drec_app.\n      reflexivity.\n    Qed.\n\n    (* re-first off, prove the one-step used in the fold for from-cast\n       correctly adds one variable and does cartesian product (i.e.,\n       MapProduct) as well *)\n\n    Lemma one_from_cast_fold_step_is_map_concat_cast defls s bn o op xenv envs envs0:\n      (h \u22a2 op @\u2093 envs \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv =\n      lift (fun x : list (list (string * data)) => dcoll (map drec x)) envs0 ->\n      (forall xenv0 (env : oql_env),\n          oql_expr_interp h (rec_concat_sort constant_env defls) o env =\n          (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 drec env \u22a3 constant_env; (drec (rec_concat_sort xenv0 defls)))%nraenv) ->\n      ((h \u22a2 (NRAEnvMapProduct\n               (NRAEnvMap\n                  (NRAEnvUnop (OpRec s) NRAEnvID)\n                  (NRAEnvUnop OpFlatten(\n                                NRAEnvMap (NRAEnvEither (NRAEnvUnop OpBag NRAEnvID)\n                                                        (NRAEnvConst (dcoll nil)))\n                                          (NRAEnvMap (NRAEnvUnop (OpCast (bn :: nil)) NRAEnvID)\n                                                     (oql_to_nraenv_expr (domain defls) o))))) op) @\u2093 envs\n          \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv\n       =\n       lift (fun x : list (list (string * data)) => dcoll (map drec x))\n            match envs0 with\n            | Some envl' =>\n              env_map_concat_cast h s bn (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n            | None => None\n            end).\n    Proof.\n      intros; simpl.\n      unfold nraenv_eval in *; simpl.\n      rewrite H; simpl; clear H.\n      destruct envs0; [|reflexivity]; simpl.\n      induction l; try reflexivity; simpl.\n      unfold env_map_concat_cast in *; simpl.\n      unfold omap_product in *; simpl.\n      unfold oncoll_map_concat in *; simpl.\n      unfold oenv_map_concat_single_with_cast in *; simpl.\n      rewrite (H0 xenv).\n      destruct (cNRAEnv.nraenv_core_eval h constant_env\n                                         (nraenv_to_nraenv_core (oql_to_nraenv_expr (domain defls) o)) (drec (rec_concat_sort xenv defls))\n                                         (drec a))%nraenv;\n        try reflexivity; simpl.\n      destruct d; try reflexivity; simpl.\n      unfold filter_cast in *; simpl in *.\n      autorewrite with alg; simpl.\n      rewrite flatten_either_is_lift_map_either; simpl.\n      assert (@lift_flat_map (@data (@foreign_runtime_data fruntime))\n                         (@data (@foreign_runtime_data fruntime))\n                         (fun x : @data (@foreign_runtime_data fruntime) =>\n                            match\n                              x\n                              return\n                              (option (list (@data (@foreign_runtime_data fruntime))))\n                            with\n                            | dbrand b' _ =>\n                              match\n                                sub_brands_dec h b' (@cons string bn (@nil string))\n                                return\n                                (option\n                                   (list (@data (@foreign_runtime_data fruntime))))\n                              with\n                              | left _ =>\n                                @Some\n                                  (list (@data (@foreign_runtime_data fruntime)))\n                                  (@cons (@data (@foreign_runtime_data fruntime)) x\n                                         (@nil (@data (@foreign_runtime_data fruntime))))\n                              | right _ =>\n                                @Some\n                                  (list (@data (@foreign_runtime_data fruntime)))\n                                  (@nil (@data (@foreign_runtime_data fruntime)))\n                              end\n                            | _ =>\n                              None\n                            end) l0 =\n              (@lift_flat_map (@data (@foreign_runtime_data fruntime))\n                          (@data (@foreign_runtime_data fruntime))\n                          (fun x : @data (@foreign_runtime_data fruntime) =>\n                             match\n                               x\n                               return\n                               (option\n                                  (list (@data (@foreign_runtime_data fruntime))))\n                             with\n                             | dbrand b' _ =>\n                               match\n                                 sub_brands_dec h b'\n                                                (@cons brand bn (@nil brand))\n                                 return\n                                 (option\n                                    (list\n                                       (@data (@foreign_runtime_data fruntime))))\n                               with\n                               | left _ =>\n                                 @Some\n                                   (list\n                                      (@data (@foreign_runtime_data fruntime)))\n                                   (@cons\n                                      (@data (@foreign_runtime_data fruntime))\n                                      x\n                                      (@nil\n                                         (@data\n                                            (@foreign_runtime_data fruntime))))\n                               | right _ =>\n                                 @Some\n                                   (list\n                                      (@data (@foreign_runtime_data fruntime)))\n                                   (@nil\n                                      (@data (@foreign_runtime_data fruntime)))\n                               end\n                             | _ => None\n                             end) l0)) by reflexivity.\n      rewrite H; clear H.\n      destruct (lift_flat_map\n                  (fun x : data =>\n                     match x with\n                     | dbrand b' _ =>\n                       if sub_brands_dec h b' (bn :: nil)\n                       then Some (x :: nil)\n                       else Some nil\n                     | _ => None\n                     end) l0); simpl; try reflexivity.\n      autorewrite with alg; simpl.\n      unfold env_map_concat_single in *.\n      unfold omap_concat in *.\n      autorewrite with alg; simpl.\n      rewrite lift_map_rec_concat_map_is_map_rec_concat_map; simpl.\n      match type of IHl with\n      | lift _ ?x = lift _ ?y  => destruct y; destruct x; simpl in *\n      end; simpl in *; try discriminate.\n      - invcs IHl.\n        rewrite map_map_drec_works.\n        reflexivity.\n      - congruence.\n    Qed.\n\n    (* Second, show that 'x in expr' translation is correct *)\n  \n    Lemma nraenv_of_from_in_correct defls env o s xenv :\n      (forall xenv0 (env0 : oql_env),\n          oql_expr_interp h (rec_concat_sort constant_env defls) o env0 =\n          (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 drec env0 \u22a3 constant_env; (drec (rec_concat_sort xenv0 defls)))%nraenv) ->\n      (lift (fun x : list (list (string * data)) => dcoll (map drec x))\n            (env_map_concat s (oql_expr_interp h (rec_concat_sort constant_env defls) o) (env :: nil))) =\n      (nraenv_eval h constant_env (NRAEnvMapProduct (NRAEnvMap (NRAEnvUnop (OpRec s) NRAEnvID) (oql_to_nraenv_expr (domain defls) o)) (NRAEnvUnop OpBag NRAEnvID)) (drec (rec_concat_sort xenv defls)) (drec env)).\n    Proof.\n      intros; simpl.\n      unfold nraenv_eval; simpl.\n      unfold omap_product; simpl.\n      unfold env_map_concat; simpl.\n      unfold oncoll_map_concat; simpl.\n      unfold oenv_map_concat_single; simpl.\n      rewrite (H xenv); clear H.\n      unfold nraenv_eval; simpl.\n      destruct (cNRAEnv.nraenv_core_eval h constant_env\n                                         (nraenv_to_nraenv_core (oql_to_nraenv_expr (domain defls) o)) (drec (rec_concat_sort xenv defls))\n                                         (drec env))%nraenv;\n        try reflexivity; simpl.\n      destruct d; simpl; try reflexivity.\n      autorewrite with alg; simpl.\n      rewrite app_nil_r.\n      apply oql_nra_dual_map_concat.\n    Qed.\n\n    (* Finally, the main fold_left for a whole from clause is correct *)\n  \n    Lemma nraenv_of_from_clause_correct defls op envs envs0 el xenv :\n      Forall\n        (fun ab : oql_in_expr =>\n           forall xenv (env : oql_env),\n             oql_expr_interp h (rec_concat_sort constant_env defls) (oin_expr ab) env =\n             (h \u22a2 oql_to_nraenv_expr (domain defls) (oin_expr ab) @\u2093 drec env \u22a3 constant_env;\n                (drec (rec_concat_sort xenv defls)))%nraenv) el ->\n      (h \u22a2 op @\u2093 envs \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv =\n      (lift (fun x : list (list (string * data)) => dcoll (map drec x)) envs0) ->\n      (lift (fun x : list (list (string * data)) => dcoll (map drec x))\n            (fold_left\n               (fun (envl : option (list oql_env))\n                    (from_in_expr : oql_in_expr) =>\n                  match from_in_expr with\n                  | OIn in_v from_expr =>\n                    match envl with\n                    | None => None\n                    | Some envl' =>\n                      env_map_concat in_v (oql_expr_interp h (rec_concat_sort constant_env defls) from_expr) envl'\n                    end\n                  | OInCast in_v brand_name from_expr =>\n                    match envl with\n                    | None => None\n                    | Some envl' =>\n                      env_map_concat_cast h in_v brand_name (oql_expr_interp h (rec_concat_sort constant_env defls) from_expr) envl'\n                    end\n                  end\n               ) el envs0)) =\n      (h\n         \u22a2 fold_left\n         (fun (opacc : nraenv) (from_in_expr : oql_in_expr) =>\n            match from_in_expr with\n            | OIn in_v from_expr =>\n              NRAEnvMapProduct\n                (NRAEnvMap (NRAEnvUnop (OpRec in_v) NRAEnvID) (oql_to_nraenv_expr (domain defls) from_expr))\n                opacc\n            | OInCast in_v brand_name from_expr =>\n              NRAEnvMapProduct\n                (NRAEnvMap\n                   (NRAEnvUnop (OpRec in_v) NRAEnvID)\n                   (NRAEnvUnop OpFlatten\n                               (NRAEnvMap (NRAEnvEither (NRAEnvUnop OpBag NRAEnvID)\n                                                        (NRAEnvConst (dcoll nil)))\n                                          (NRAEnvMap (NRAEnvUnop (OpCast (brand_name::nil))\n                                                                 NRAEnvID)\n                                                     (oql_to_nraenv_expr (domain defls) from_expr)))))\n                opacc\n            end\n         )\n         el op @\u2093 envs \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv.\n    Proof.\n      intros.\n      revert op xenv envs0 envs H0.\n      induction el; simpl in *; intros; try (rewrite H0; reflexivity).\n      destruct a; simpl in *.\n      (* OIn case *)\n      - inversion H; subst; simpl in *.\n        specialize (IHel H4); clear H H4.\n        specialize (IHel (NRAEnvMapProduct\n                            (NRAEnvMap (NRAEnvUnop (OpRec s) NRAEnvID)\n                                       (oql_to_nraenv_expr (domain defls) o)) op)%nraenv).\n        assert ((h \u22a2 (NRAEnvMapProduct\n                        (NRAEnvMap (NRAEnvUnop (OpRec s) NRAEnvID)\n                                   (oql_to_nraenv_expr (domain defls) o)) op)%nraenv\n                   @\u2093 envs \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv =\n                lift (fun x : list (list (string * data)) => dcoll (map drec x))\n                     (match envs0 with\n                      | Some envl' =>\n                        env_map_concat s (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n                      | None => None\n                      end))\n          by (apply one_from_fold_step_is_map_concat; assumption).\n        apply (IHel xenv (match envs0 with\n                          | Some envl' =>\n                            env_map_concat s (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n                          | None => None\n                          end) envs H).\n      (* OInCast case *)\n      - inversion H; subst; simpl in *.\n        specialize (IHel H4); clear H H4.\n        specialize\n          (IHel (NRAEnvMapProduct\n                   (NRAEnvMap\n                      (NRAEnvUnop (OpRec s) NRAEnvID)\n                      (NRAEnvUnop OpFlatten\n                                  (NRAEnvMap\n                                     (NRAEnvEither (NRAEnvUnop OpBag NRAEnvID)\n                                                   (NRAEnvConst (dcoll nil)))\n                                     (NRAEnvMap (NRAEnvUnop (OpCast (s0 :: nil)) NRAEnvID)\n                                                (oql_to_nraenv_expr (domain defls) o))))) (op))%nraenv).\n        assert ((h \u22a2 (NRAEnvMapProduct\n                        (NRAEnvMap\n                           (NRAEnvUnop (OpRec s) NRAEnvID)\n                           (NRAEnvUnop OpFlatten\n                                       (NRAEnvMap\n                                          (NRAEnvEither (NRAEnvUnop OpBag NRAEnvID)\n                                                        (NRAEnvConst (dcoll nil)))\n                                          (NRAEnvMap (NRAEnvUnop (OpCast (s0 :: nil)) NRAEnvID)\n                                                     (oql_to_nraenv_expr (domain defls) o))))) (op)) @\u2093 envs\n                   \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv\n                =\n                lift (fun x : list (list (string * data)) => dcoll (map drec x))\n                     match envs0 with\n                     | Some envl' =>\n                       env_map_concat_cast h s s0 (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n                     | None => None\n                     end)\n          by (apply one_from_cast_fold_step_is_map_concat_cast; assumption).\n        apply (IHel xenv (match envs0 with\n                          | Some envl' =>\n                            env_map_concat_cast h s s0 (oql_expr_interp h (rec_concat_sort constant_env defls) o) envl'\n                          | None => None\n                          end) envs H).\n    Qed.\n\n    (****************************\n     * Where clause correctness *\n     ****************************)\n  \n    Lemma nraenv_of_where_clause_correct defls\n          (o:oql_expr) xenv (ol : option (list oql_env)):\n      (forall xenv (env : oql_env),\n          oql_expr_interp h (rec_concat_sort constant_env defls) o env =\n          (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 drec env \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv) ->\n      lift (fun x : list (list (string * data)) => dcoll (map drec x))\n           (olift\n              (lift_filter\n                 (fun x' : oql_env =>\n                    match oql_expr_interp h (rec_concat_sort constant_env defls) o x' with\n                    | Some (dbool b) => Some b\n                    | Some _ => None\n                    | None => None\n                    end)) ol) =\n      olift\n        (fun d : data =>\n           lift_oncoll\n             (fun c1 : list data =>\n                lift dcoll\n                     (lift_filter\n                        (fun x' : data =>\n                           match\n                             (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 x' \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv\n                           with\n                           | Some (dbool b) => Some b\n                           | Some _ => None\n                           | None => None\n                           end) c1)) d)\n        (lift (fun x : list (list (string * data)) => dcoll (map drec x)) ol).\n    Proof.\n      intros.\n      destruct ol; [|reflexivity]; simpl.\n      induction l; [reflexivity|idtac]; simpl.\n      rewrite (H xenv a); simpl in *.\n      destruct (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 drec a \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv; try reflexivity; simpl.\n      destruct d; try reflexivity; simpl.\n      destruct (lift_filter\n                  (fun x' : data =>\n                     match\n                       (h \u22a2 oql_to_nraenv_expr (domain defls) o @\u2093 x' \u22a3 constant_env; (drec (rec_concat_sort xenv defls)))%nraenv\n                     with\n                     | Some (dbool b0) => Some b0\n                     | Some _ => None\n                     | None => None\n                     end) (map drec l));\n        destruct ((lift_filter\n                     (fun x' : oql_env =>\n                        match oql_expr_interp h (rec_concat_sort constant_env defls) o x' with\n                        | Some (dbool b) => Some b\n                        | Some _ => None\n                        | None => None\n                        end) l)); simpl in *; try congruence.\n      inversion IHl; subst.\n      destruct b; reflexivity.\n    Qed.\n\n    (* OQL expr to NRAEnv translation is correct *)\n\n    (* delete env section *)\n    Theorem oql_to_nraenv_expr_correct (e:oql_expr) :\n      forall xenv, forall defls, forall env,\n            oql_expr_interp h (rec_concat_sort constant_env defls) e env =\n            (nraenv_eval h constant_env (oql_to_nraenv_expr (domain defls) e)\n                         (drec (rec_concat_sort xenv defls)) (drec env))%nraenv.\n    Proof.\n      intros. revert xenv env.\n      induction e; simpl; intros.\n      (* OConst *)\n      - reflexivity.\n      (* OVar *)\n      - reflexivity.\n      (* OTable *)\n      - unfold lookup_table; unfold nraenv_eval.\n        match_destr; simpl.\n        + unfold edot.\n          unfold rec_concat_sort.\n          repeat rewrite assoc_lookupr_drec_sort.\n          rewrite (assoc_lookupr_app constant_env defls).\n          rewrite (assoc_lookupr_app xenv defls).\n          match_case; intros nin.\n          apply assoc_lookupr_none_nin in nin.\n          congruence.\n        + unfold edot.\n          unfold rec_concat_sort.\n          rewrite assoc_lookupr_drec_sort.\n          rewrite (assoc_lookupr_app constant_env defls).\n          match_case; intros ? inn.\n          apply assoc_lookupr_in in inn.\n          apply in_dom in inn.\n          congruence.\n      (* OBinop *)\n      - rewrite (IHe1 xenv env); rewrite (IHe2 xenv env).\n        reflexivity.\n      (* OUnop *)\n      - rewrite (IHe xenv env).\n        reflexivity.\n      (* OSFW *)\n      - destruct e1.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil)))\n          ; [idtac|assumption|reflexivity].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          reflexivity.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          rewrite push_lift_coll_in_lift_map; simpl.\n          rewrite olift_rondcoll_over_dcoll.\n          reflexivity.\n      - destruct e1.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_where_clause_correct; intros Hwhere.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hwhere; [|assumption].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          reflexivity.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_where_clause_correct; intros Hwhere.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hwhere; [|assumption].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          rewrite push_lift_coll_in_lift_map; simpl.\n          rewrite olift_rondcoll_over_dcoll.\n          reflexivity.\n      - destruct e1.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          reflexivity.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          rewrite push_lift_coll_in_lift_map; simpl.\n          rewrite olift_rondcoll_over_dcoll.\n          reflexivity.\n      - destruct e1.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_where_clause_correct; intros Hwhere.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hwhere; [|assumption].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          reflexivity.\n        + simpl in *.\n          generalize (nraenv_of_from_clause_correct defls); intros Hfrom.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- (Hfrom _ _ (Some (env :: nil))) ; [idtac|assumption|reflexivity]. \n          generalize nraenv_of_where_clause_correct; intros Hwhere.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hwhere; [|assumption].\n          generalize nraenv_of_select_expr_correct; intros Hselect.\n          unfold nraenv_eval in *; simpl.\n          rewrite <- Hselect; [|assumption].\n          rewrite push_lift_coll_in_lift_map; simpl.\n          rewrite olift_rondcoll_over_dcoll.\n          reflexivity.\n    Qed.\n\n    Global Instance lookup_table_proper :\n      Proper (equivlist ==> eq ==> eq) lookup_table.\n    Proof.\n      red; intros l1 l2 eql s1 s2 eqs; subst s2.\n      unfold lookup_table.\n      match_destr; match_destr.\n      - rewrite eql in i; congruence.\n      - rewrite <- eql in i; congruence.\n    Qed.\n\n    Global Instance oql_to_nraenv_expr_proper :\n      Proper (equivlist ==> eq ==> eq) oql_to_nraenv_expr.\n    Proof.\n      Ltac fold_left_local_solver \n        := match goal with\n             [H:Forall _ ?el |- fold_left ?f1 ?e1 ?n1 = fold_left ?f2 ?e2 ?n2 ]\n             => cut (forall n, fold_left f1 e1 n = fold_left f2 e2 n); [solve[auto] | ]\n                ; intros n; revert H n\n                ; let IHel := (fresh \"IHel\") in\n                  (induction el as [| ? ? IHel]; intros FH n; simpl in *; trivial\n                   ; invcs FH; rewrite IHel; trivial\n                   ; match_destr; simpl in *; congruence)\n           end.\n      red; intros l1 l2 eql q1 q2 eqq; subst q2.\n      induction q1; simpl in *; trivial.\n      - rewrite eql; trivial.\n      - rewrite IHq1_1, IHq1_2; trivial.\n      - rewrite IHq1; trivial.\n      - destruct e1; simpl in *; rewrite IHq1; clear IHq1.\n        + do 1 f_equal; fold_left_local_solver.\n        + do 2 f_equal; fold_left_local_solver.\n      - destruct e1; simpl in *; rewrite IHq0, IHq1; clear IHq0 IHq1.\n        + do 2 f_equal; fold_left_local_solver.\n        + do 3 f_equal; fold_left_local_solver.\n      - destruct e1; simpl in *; rewrite IHq1; clear IHq1.\n        + do 1 f_equal; fold_left_local_solver.\n        + do 2 f_equal; fold_left_local_solver.\n      - destruct e1; simpl in *; rewrite IHq1_1, IHq1_2; clear IHq1_1 IHq1_2 IHq1_3.\n        + do 2 f_equal; fold_left_local_solver.\n        + do 3 f_equal; fold_left_local_solver.\n    Qed.\n  \n    Global Instance oql_to_nraenv_query_program_proper :\n      Proper (equivlist ==> eq ==> eq) oql_to_nraenv_query_program.\n    Proof.\n      red; intros l1 l2 eql q1 q2 eqq; subst q2.\n      revert l1 l2 eql.\n      induction q1; intros l1 l2 eql; simpl.\n      - f_equal.\n        + apply IHq1.\n          apply equivlist_cons; trivial.\n        + do 2 f_equal. apply oql_to_nraenv_expr_proper; trivial.\n      - f_equal.\n        apply IHq1.\n        apply equivlist_remove_all; trivial.\n      - apply oql_to_nraenv_expr_proper; trivial.\n    Qed.\n\n    Lemma rec_concat_sort_domain_app_commutatuve_equiv {K} {odt:ODT} {B} l1 l2 :\n      (equivlist (domain (rec_concat_sort l1 l2)) (domain l2 ++ @domain K B l1)).\n    Proof.\n      unfold rec_concat_sort.\n      rewrite drec_sort_equiv_domain.\n      rewrite domain_app.\n      rewrite app_commutative_equivlist.\n      simpl.\n      reflexivity.\n    Qed.\n\n    Lemma oql_to_nraenv_query_program_correct (defllist:list string) (oq:oql_query_program) :\n      forall (defls:oql_env) xenv env,\n        (forall x, In x ((domain defls)++(oql_query_program_defls oq)) -> ~In x (domain xenv)) ->\n        oql_query_program_interp h constant_env defls oq env =\n        nraenv_eval h constant_env (oql_to_nraenv_query_program (domain defls) oq) (drec (rec_concat_sort xenv defls)) (drec env).\n    Proof.\n      intros. revert defls xenv env H.\n      induction oq; simpl; intros.\n      - rewrite (oql_to_nraenv_expr_correct _ xenv).\n        unfold nraenv_eval; simpl.\n        match goal with\n          [|- olift _ ?x = _ ] => destruct x\n        end; simpl; trivial.\n        rewrite (IHoq _ xenv).\n        + unfold nraenv_eval; simpl.\n          assert (equivlist (domain (rec_concat_sort defls ((s, d) :: nil))) (s::domain defls))\n            by (rewrite rec_concat_sort_domain_app_commutatuve_equiv; simpl; reflexivity).\n          rewrite (oql_to_nraenv_query_program_proper _ _ H0 _ _ (eq_refl _ )).\n          unfold rec_concat_sort.\n          rewrite rec_sort_rec_sort_app1.\n          rewrite app_ass.\n          rewrite rec_sort_rec_sort_app2.\n          trivial.\n        + intros.\n          apply H.\n          rewrite in_app_iff in H0.\n          unfold rec_concat_sort in H0.\n          rewrite in_dom_rec_sort in H0.\n          rewrite domain_app in H0.\n          simpl in H0.\n          rewrite in_app_iff in H0.\n          rewrite in_app_iff; simpl in *.\n          tauto.\n      - unfold nraenv_eval; simpl.\n        rewrite (IHoq _ xenv).\n        + unfold nraenv_eval.\n          f_equal.\n          * rewrite domain_rremove; trivial.\n          * unfold rec_concat_sort.\n            rewrite rremove_rec_sort_commute.\n            rewrite rremove_app.\n            rewrite (nin_rremove xenv); trivial.\n            apply H.\n            rewrite in_app_iff; simpl.\n            tauto.\n        + intros.\n          apply H.\n          rewrite in_app_iff; simpl.\n          rewrite domain_rremove in H0.\n          rewrite in_app_iff in H0.\n          rewrite remove_all_filter in H0.\n          rewrite filter_In in H0.\n          tauto.\n      - apply oql_to_nraenv_expr_correct.\n    Qed.\n    \n    Theorem oql_to_nraenv_correct (q:oql) :\n      forall xenv xdata,\n        oql_interp h constant_env q =\n        nraenv_eval h constant_env (oql_to_nraenv q) xenv xdata.\n    Proof.\n      intros xenv.\n      unfold oql_to_nraenv, oql_interp.\n      rewrite (oql_to_nraenv_query_program_correct nil q nil nil); simpl; [| tauto].\n      reflexivity.\n    Qed.\n  End correct.\n\n  Section Top.\n    Context (h:brand_relation_t).\n\n    (* Top-level translation call *)\n    Definition oql_to_nraenv_top (q:oql) : nraenv :=\n      oql_to_nraenv q.\n\n    Theorem oql_to_nraenv_top_correct (q:oql) (cenv:bindings) : \n        oql_eval_top h q cenv =\n        nraenv_eval_top h (oql_to_nraenv_top q) cenv.\n    Proof.\n      apply oql_to_nraenv_correct.\n    Qed.\n  End Top.\n\nEnd OQLtoNRAEnv.\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/Lang/OQLtoNRAEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "(* Sequentialisation - A terminal ax vertex is sequentializing *)\n(* From a Proof Net, return a LL proof of the same sequent *)\n\nFrom Coq Require Import Bool.\nFrom OLlibs Require Import dectype.\nSet Warnings \"-notation-overridden\". (* to ignore warnings due to the import of ssreflect *)\nFrom mathcomp Require Import all_ssreflect.\nSet Warnings \"notation-overridden\".\nFrom GraphTheory Require Import preliminaries mgraph setoid_bigop structures bij.\n\nFrom Yalla Require Export mll_prelim mll_def mll_basic mll_seq_to_pn mll_pn_to_seq_def.\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\u00e9cup\u00e9rer les notations *)\nNotation formula := (@formula atom).\nNotation base_graph := (graph (flat rule) (flat (formula * bool))).\nNotation graph_data := (@graph_data atom).\nNotation proof_structure := (@proof_structure atom).\nNotation proof_net := (@proof_net atom).\nNotation switching := (@switching atom).\nNotation switching_left := (@switching_left atom).\n\n\nSection Sequentializing_ax.\nContext {G : proof_net} {v : G}.\nHypothesis (V : vlabel v = ax) (T : terminal v).\n\nLemma sequentializing_ax_step0 :\n  {'(e, e') | flabel e = flabel e'^ /\\ source e = v /\\ source e' = v /\\ vlabel (target e) = c /\\\n  vlabel (target e') = c}.\nProof.\n  destruct (p_ax_type V) as [[e e'] [E [E' F]]]. subst v.\n  exists (e, e'); splitb; by apply (terminal_source T).\nQed.\nLocal Notation e := (fst (proj1_sig sequentializing_ax_step0)).\nLocal Notation e' := (snd (proj1_sig sequentializing_ax_step0)).\n\nLemma sequentializing_ax_step1 (u : G) : u = source e \\/ u = target e \\/ u = target e'.\nProof.\n  destruct sequentializing_ax_step0 as [[e e'] [F [E [E' [Te Te']]]]];\n  simpl; subst v.\n  assert (C := p_correct G).\n  apply correct_to_weak in C.\n  destruct C as [_ C]. elim: (C (source e) u) => [[p /andP[/andP[W U] N]] _].\n  destruct p as [ | (a, b) p]; first by (revert W => /= /eqP-->; caseb).\n  revert W => /= /andP[/eqP-Hf W].\n  destruct b; last by (contradict Hf; by apply no_target_ax).\n  enough (A : a = e \\/ a = e').\n  { destruct A; [set ae := e | set ae := e']; subst a.\n    all: destruct p as [ | (a, b) p]; first by (revert W => /= /eqP-->; caseb).\n    all: revert W => /= /andP[/eqP-Hf2 _].\n    all: destruct b; first by (contradict Hf2; by apply no_source_c).\n    all: contradict U; apply /negP.\n    all: assert (a = ae) by (by apply one_target_c); subst a.\n    all: rewrite /= in_cons; caseb. }\n  assert (C2 : #|edges_at_out (source e)| == 2) by by apply /eqP; rewrite p_deg_out V.\n  revert C2 => /cards2P[f [f' [/eqP-Fneq FF]]].\n  assert (a \\in edges_at_out (source e) /\\ e \\in edges_at_out (source e) /\\\n    e' \\in edges_at_out (source e)) as [Ina [Ine Ine']]\n    by by splitb; rewrite !in_set; apply /eqP.\n  revert Ina Ine Ine'. rewrite !FF !in_set. introb; subst; caseb.\n  all: contradict F; apply nesym, no_selfdual.\nQed.\n\nLemma sequentializing_ax_step2 (a : edge G) : (a == e) || (a == e').\nProof.\n  destruct (sequentializing_ax_step1 (target a)) as [A | A];\n  destruct sequentializing_ax_step0 as [[e e'] [F [E [E' [Te Te']]]]];\n  simpl; simpl in A; subst v.\n  - contradict A. by apply no_target_ax.\n  - destruct A as [A | A]; apply one_target_c in A; rewrite // A; caseb.\nQed.\n\nLemma sequentializing_ax_step3 :\n  e' <> e /\\ target e' <> source e /\\ target e <> source e /\\ target e' <> target e.\nProof.\n  destruct sequentializing_ax_step0 as [[e e'] [F [E [E' [Te Te']]]]];\n  simpl; subst v.\n  assert (En : e' <> e).\n  { intros ?. subst e'. contradict F. apply nesym, no_selfdual. }\n  splitb.\n  - rewrite -E'. apply nesym, no_selfloop.\n  - by apply nesym, no_selfloop.\n  - intros ?. contradict En. by by apply one_target_c.\nQed.\n\nDefinition terminal_ax_v_bij_fwd (u : G) : ax_graph (flabel e) :=\n  if u == source e then ord0\n  else if u == target e then ord2\n  else ord1.\n\nDefinition terminal_ax_v_bij_bwd (u : ax_graph (flabel e)) : G :=\n  match val u with\n  | 0 => source e\n  | 1 => target e'\n  | _ => target e\n  end.\n\nLemma terminal_ax_v_bijK : cancel terminal_ax_v_bij_fwd terminal_ax_v_bij_bwd.\nProof.\n  intro u.\n  unfold terminal_ax_v_bij_bwd, terminal_ax_v_bij_fwd. case_if.\n  by destruct (sequentializing_ax_step1 u) as [? | [? | ?]].\nQed.\n\nLemma terminal_ax_v_bijK' : cancel terminal_ax_v_bij_bwd terminal_ax_v_bij_fwd.\nProof.\n  destruct sequentializing_ax_step3 as [En [T'S [TS T'T]]].\n  intro u.\n  unfold terminal_ax_v_bij_bwd, terminal_ax_v_bij_fwd.\n  destruct_I u; case_if; cbnb.\nQed.\n\nDefinition terminal_ax_iso_v := {|\n  bijK:= terminal_ax_v_bijK;\n  bijK':= terminal_ax_v_bijK';\n  |}.\n\nDefinition terminal_ax_e_bij_fwd (a : edge G) : edge (ax_graph (flabel e)) :=\n  if a == e then ord1 else ord0.\n\nDefinition terminal_ax_e_bij_bwd (a : edge (ax_graph (flabel e))) : edge G :=\n  match val a with\n  | 0 => e'\n  | _ => e\n  end.\n\nLemma terminal_ax_e_bijK : cancel terminal_ax_e_bij_fwd terminal_ax_e_bij_bwd.\nProof.\n  intro a.\n  unfold terminal_ax_e_bij_bwd, terminal_ax_e_bij_fwd. case_if.\n  by elim: (orb_sum (sequentializing_ax_step2 a)) => /eqP-?.\nQed.\n\nLemma terminal_ax_e_bijK' : cancel terminal_ax_e_bij_bwd terminal_ax_e_bij_fwd.\nProof.\n  destruct sequentializing_ax_step3 as [En _].\n  intro a.\n  unfold terminal_ax_e_bij_bwd, terminal_ax_e_bij_fwd.\n  destruct_I a; case_if; cbnb.\nQed.\n\nDefinition terminal_ax_iso_e := {|\n  bijK:= terminal_ax_e_bijK;\n  bijK':= terminal_ax_e_bijK';\n  |}.\n\nLemma terminal_ax_iso_ihom : is_ihom terminal_ax_iso_v terminal_ax_iso_e pred0.\nProof.\n  rewrite /= /terminal_ax_v_bij_fwd /terminal_ax_e_bij_fwd.\n  assert (Cu := sequentializing_ax_step1).\n  assert (Ca := sequentializing_ax_step2).\n  destruct sequentializing_ax_step3 as [En [T'S [TS T'T]]].\n  destruct sequentializing_ax_step0 as [[e e'] [F [E [E' [Te Te']]]]];\n  simpl in *; subst v.\n  split.\n  - intros a []; elim: (orb_sum (Ca a)) => /eqP-?; subst a; simpl.\n    all: unfold terminal_ax_e_bij_fwd, terminal_ax_v_bij_fwd; case_if.\n    enough (source e' <> target e) by by [].\n    rewrite E'. by apply nesym.\n  - intros u; destruct (Cu u) as [? | [? | ?]]; subst u; case_if.\n  - intros a; elim: (orb_sum (Ca a)) => /eqP-?; subst a; case_if.\n    + destruct (elabel e) as [Fe Le] eqn:LL.\n      apply /eqP. revert LL => /eqP. cbn => /andP[? /eqP-L]. splitb.\n      rewrite -L. apply p_noleft. caseb.\n    + destruct (elabel e') as [Fe Le] eqn:LL.\n      apply /eqP. revert LL => /eqP. cbn => /andP[/eqP-F' /eqP-L]. subst Fe Le. splitb.\n      * rewrite F bidual. cbnb.\n      * apply p_noleft. auto.\nQed.\n\nDefinition sequentializing_ax_iso : G \u2243 ax_graph (flabel e) :=\n  {| iso_ihom := terminal_ax_iso_ihom |}.\n\nLemma terminal_ax_is_sequentializing : sequentializing v.\nProof.\n  rewrite /sequentializing V.\n  exists (flabel e). exact sequentializing_ax_iso.\nQed.\n\nEnd Sequentializing_ax.\n\nEnd Atoms.", "meta": {"author": "RemiDiG", "repo": "proofnet_mll", "sha": "03e12bce95709fe92f628f2d16aa69cf82d81ff4", "save_path": "github-repos/coq/RemiDiG-proofnet_mll", "path": "github-repos/coq/RemiDiG-proofnet_mll/proofnet_mll-03e12bce95709fe92f628f2d16aa69cf82d81ff4/yalla/mll_pn_to_seq_ax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"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 ssrnat seq.\nRequire Import ZArith_ext ssrnat_ext.\nRequire Import integral_type bipl seplog.\nRequire Import topsy_hm topsy_hmAlloc_prg.\n\nRequire Import expr_b_dp.\nImport seplog_Z_m.assert_m.expr_m.\nImport seplog_Z_m.assert_m.\nImport seplog_Z_m.\n\nLocal Close Scope positive_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope seplog_expr_scope.\nLocal Open Scope seplog_assert_scope.\nLocal Open Scope seplog_cmd_scope.\nLocal Open Scope seplog_hoare_scope.\n\n(** this file contains:\n - 1. the verification of list traversal (findFree)\n - 2. the verification of compaction (compact, original version and optimization)\n - 3. the verification of splitting (split)\n - 4. the verification of the allocation function (hmAlloc)\n*)\n\nLocal Close Scope Z_scope.\n\nDefinition findFree_specif := forall adr x sizex size,\n  size > 0 -> adr > 0 ->\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n     In_hl l (x, sizex, alloc) adr /\\\n     [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s }}\n  findFree size entry fnd sz stts\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n     In_hl l (x, sizex, alloc) adr /\\\n     [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n     ((exists y size'', size'' >= size /\\\n      In_hl l (y, size'', topsy_hm.free) adr /\\\n      [ var_e entry \\= nat_e y \\&& nat_e y \\> null ]b_s)\n      \\/\n      [ var_e entry \\= null ]b_s) }}.\n\nLemma findFree_verif : findFree_specif.\nProof.\nrewrite /findFree_specif => adr x sizex size H H0.\nrewrite /findFree.\n\n(**  entry <- var_e hmStart; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\ [ var_e entry \\= nat_e adr ]b_s ).\n\nmove: H1 => [l [Hl [Hl' Hb]]].\nexists l.\nby Resolve_topsy.\n\n(**  stts <-* (entry -.> status); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\ [ var_e entry \\= nat_e adr ]b_s /\\\n  [ var_e stts \\= Allocated \\|| var_e stts \\= Free ]b_s).\n\nmove: H1 => [x0 [H1 [H4 [H2 [H6 H5]]]]].\ndestruct x0 as [|p x0]; first by rewrite //= in H4.\ndestruct p.\nexists (hlstat_bool2expr b).\napply mapsto_strictly_exact; split.\n- case: H1 => h1 [h2 [H1 [H7 [H3 H9]]]].\n  inversion_clear H3.\n  + subst b nxt.\n    case_sepcon H13.\n    rewrite /= in H13_h31; case_sepcon H13_h31.\n    Compose_sepcon h311 (h312 \\U h32 \\U h4 \\U h2); last by done.\n    rewrite /status; by Mapsto.\n  + subst b nxt.\n    rewrite /= in H13; case_sepcon H13.\n    Compose_sepcon h31 (h32 \\U h4 \\U h2); last by done.\n    rewrite /status; by Mapsto.\n- exists ((n, b) :: x0).\n  Resolve_topsy.\n  destruct b; rewrite eval_b_upd_subst; by omegab.\n\n(**  fnd <- cst_e 0%Z; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\ [ var_e entry \\= nat_e adr ]b_s /\\\n  [ var_e stts \\= Allocated \\|| var_e stts \\= Free ]b_s /\\\n  [ var_e fnd \\= nat_e 0 ]b_s).\n\ncase: H1 => x0 [H1 [H4 [H2 [H7 [H6 H5]]]]].\nexists x0.\nby Resolve_topsy.\n\n(**  while ((var_e entry \\!= null) \\&& (var_e fnd \\!= cst_e 1%Z)) ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\\n  (exists bloc_adr,\n    [ var_e entry \\= nat_e bloc_adr ]b_s /\\\n    ((bloc_adr = 0 /\\ [ var_e fnd \\= nat_e 0 ]b_s) \\/\n      (bloc_adr = get_endl l adr  /\\\n        [ var_e fnd \\= nat_e 0 ]b_s /\\\n        bloc_adr > 0) \\/\n      (exists bloc_size bloc_status,\n        bloc_adr > 0 /\\\n        In_hl l (bloc_adr, bloc_size, bloc_status) adr /\\\n        [ var_e fnd \\= nat_e 0 ]b_s) \\/\n      exists bloc_size, bloc_size >= size /\\\n        In_hl l (bloc_adr, bloc_size, topsy_hm.free) adr /\\\n        [ var_e fnd \\= nat_e 1 ]b_s /\\\n        bloc_adr > 0))).\n\nrewrite /while.entails => s h [l [H1 [H4 [H2 [H8 [H7 [H6 H5]]]]]]].\nexists l; Resolve_topsy.\ncase : l H1 H4 => [|[n b] tl] H1 H4; first by done.\nexists adr; Resolve_topsy.\nright; right; left; exists n, b; Resolve_topsy.\nby rewrite /= !eqxx.\n\nrewrite /while.entails => s h [[x0 [H2 [H3 [H4 [H5 [x1 [H6 H8]]]]]]] H1].\nexists x0; Resolve_topsy.\ncase: H8.\n- case => ? H7; subst x1.\n  right; by omegab.\n- case.\n  + case => H7 [H8 H11].\n    move: (get_endl_gt x0 adr) => H9.\n    have H10 : [ var_e entry \\!= null \\&& var_e fnd \\!= cst_e 1%Z ]b_s by omegab.\n    rewrite /hoare_m.eval_b in H1.\n    by rewrite H10 in H1.\n  + case.\n    * case => x2 [x3 [H8 [H9 H10]]].\n      move: (get_endl_gt x0 adr) => H7.\n      have H11 : [ var_e entry \\!= null \\&& var_e fnd \\!= cst_e 1%Z ]b_s by omegab.\n      rewrite /hoare_m.eval_b in H1.\n      by rewrite H11 in H1.\n    * move => [x2 [H7 [H10 [H11 H12]]]].\n      left; exists x1, x2; by Resolve_topsy.\n\n(**    stts <-* (entry -.> status); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\\n  (exists bloc_adr, [ var_e entry \\= nat_e bloc_adr ]b_s /\\\n    ((bloc_adr = get_endl l adr /\\\n      [ var_e fnd \\= nat_e O ]b_s /\\\n      [ var_e stts \\= Allocated ]b_s /\\\n      bloc_adr > O) \\/\n    exists bloc_size bloc_status,\n      In_hl l (bloc_adr, bloc_size, bloc_status) adr /\\\n      [ var_e fnd \\= nat_e O ]b_s /\\\n      [ var_e stts \\= hlstat_bool2expr bloc_status ]b_s /\\\n      bloc_adr > O))).\n\nmove: H1 => [[x0 [H2 [H5 [H3 [H6 [x1 [H4 H8]]]]]]] H9].\ncase: H8.\n- case => H1 H7; subst x1.\n  suff : False by done. omegab.\n- case.\n  + case => H1 [H7 H12].\n    subst x1.\n    exists Allocated.\n    apply mapsto_strictly_exact; split.\n    * move/hl_getstat_last : H2 => H2; case_sepcon H2.\n      Compose_sepcon h1 h2; [rewrite /status; by Mapsto | done].\n    * rewrite /wp_assign; exists x0.\n      split; first by Heap_List_equiv.\n      split; first by assumption.\n      Resolve_topsy.\n      exists (get_endl x0 adr).\n      Resolve_topsy.\n      left; by Resolve_topsy.\n  + case.\n    * case => x2 [x3 [H8 [H11 H1]]].\n      case/In_hl_destruct : (H11) => [x4 [x5 [Hx0 H13]]].\n      exists (hlstat_bool2expr x3).\n      apply mapsto_strictly_exact; split.\n      rewrite Hx0 in H2; move/hl_getstatus : H2 => H10; case_sepcon H10.\n      Compose_sepcon h1 h2; [rewrite /status; by Mapsto | done].\n      rewrite /wp_assign; exists x0.\n      split; first by Heap_List_equiv.\n      Resolve_topsy.\n      exists (get_endl x4 adr); Resolve_topsy.\n      right; exists x2, x3; Resolve_topsy.\n      by rewrite H13.\n      destruct x3; rewrite eval_b_upd_subst; omegab.\n      by rewrite H13.\n   * case => x2 [H1 [H11 [H13 H8]]].\n     case/In_hl_destruct : (H11) => [x3 [x4 [H12 H14]]].\n     exists Free.\n     apply mapsto_strictly_exact; split.\n     rewrite H12 in H2; move/hl_getstatus : H2 => H2; case_sepcon H2.\n     Compose_sepcon h1 h2; [by Mapsto | done].\n     rewrite /wp_assign; exists x0.\n     split; first by Heap_List_equiv.\n     split; first by assumption.\n     Resolve_topsy.\n     exists (get_endl x3 adr); Resolve_topsy.\n     right; exists x2, topsy_hm.free; Resolve_topsy.\n     by rewrite H14.\n     by rewrite H14.\n\n(**    ENTRYSIZE entry sz; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\\n  (exists bloc_adr,\n    [ var_e entry \\= nat_e bloc_adr ]b_s /\\\n    ((bloc_adr = get_endl l adr /\\\n        [ var_e fnd \\= nat_e 0 ]b_s /\\\n        [ var_e stts \\= Allocated ]b_s /\\\n        bloc_adr > 0 /\\\n        [ var_e sz \\= nat_e 0 ]b_s) \\/\n      exists bloc_size bloc_status,\n        In_hl l (bloc_adr, bloc_size, bloc_status) adr /\\\n        [ var_e fnd \\= nat_e 0 ]b_s /\\\n        [ var_e stts \\= hlstat_bool2expr bloc_status ]b_s /\\\n        bloc_adr > 0 /\\\n        [ var_e sz \\= nat_e bloc_size ]b_s))).\n\nrewrite /ENTRYSIZE.\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s /\\\n  (exists bloc_adr, [ var_e entry \\= nat_e bloc_adr ]b_s /\\\n    ((bloc_adr = get_endl l adr /\\\n      [ var_e fnd \\= nat_e 0 ]b_s /\\\n      [ var_e stts \\= Allocated ]b_s /\\\n      bloc_adr > 0 /\\\n      [ var_e sz \\= nat_e 0 ]b_s ) \\/\n    (exists bloc_size bloc_status,\n      In_hl l (bloc_adr, bloc_size, bloc_status) adr /\\\n      [ var_e fnd \\= nat_e 0 ]b_s /\\\n      [ var_e stts \\= hlstat_bool2expr bloc_status ]b_s /\\\n      bloc_adr > 0 /\\\n      [ var_e sz \\= nat_e (bloc_adr + 2 + bloc_size) ]b_s)))).\n\nmove: H1 => [x0 [H1 [H4 [H2 [H5 [x1 [H7 H9]]]]]]].\ncase: H9.\n- case => [H11 [H3 [H8 H10]]].\n  exists null.\n  apply mapsto_strictly_exact; split.\n  move/hl_getnext_last : H1 => H1; case_sepcon H1.\n  Compose_sepcon h1 h2; [rewrite /next; by Mapsto | done].\n  rewrite /wp_assign; exists x0; Resolve_topsy.\n  exists x1; Resolve_topsy.\n  left; by Resolve_topsy.\n- move => [x2 [x3 [H10 [H11 [H3 H8]]]]].\n  move/In_hl_destruct : (H10) => [x4 [x5 [H9 H12]]].\n  exists (nat_e (x1 + 2 + x2)).\n  apply mapsto_strictly_exact; split.\n  rewrite H9 in H1; move/hl_getnext : H1 => H6.\n  case_sepcon H6.\n  Compose_sepcon h1 h2; last by done.\n  rewrite /next; by Mapsto.\n  rewrite /wp_assign; exists x0; Resolve_topsy.\n  exists (get_endl x4 adr); Resolve_topsy.\n  right; exists x2, x3; split.\n  by rewrite H12.\n  Resolve_topsy.\n  destruct x3; rewrite eval_b_upd_subst; by omegab.\n  by rewrite H12.\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\ [ var_e hmStart \\= nat_e adr ]b_s /\\\n  [ var_e result \\= null ]b_s  /\\\n  (exists bloc_adr, [ var_e entry \\= nat_e bloc_adr ]b_s /\\\n    ((bloc_adr = get_endl l adr /\\\n      [ var_e fnd \\= nat_e 0 ]b_s /\\\n      [ var_e stts \\= Allocated ]b_s /\\\n      bloc_adr > 0 /\\\n      [ var_e sz \\= nat_e 0 \\- nat_e bloc_adr \\- nat_e 2 ]b_s) \\/\n    exists bloc_size bloc_status,\n      In_hl l (bloc_adr, bloc_size, bloc_status) adr /\\\n      [ var_e fnd \\= nat_e 0 ]b_s /\\\n      [ var_e stts \\= hlstat_bool2expr bloc_status ]b_s /\\\n      bloc_adr > 0 /\\\n      [ var_e sz \\= nat_e bloc_size ]b_s))).\n\nmove: H1 => [x0 [H1 [H4 [H2 [H5 [x1 [H7 H3]]]]]]].\ncase: H3.\n- move => [H10 [H3 [H11 [H8 H9]]]].\n  exists x0; Resolve_topsy.\n  exists (get_endl x0 adr); Resolve_topsy.\n  left; Resolve_topsy.\n  by omegab.\n- move => [x2 [x3 [H9 [H10 [H3 [H11 H8]]]]]].\n  exists x0; Resolve_topsy.\n  exists x1; Resolve_topsy.\n  right; exists x2, x3; Resolve_topsy.\n  rewrite eval_b_upd_subst; by destruct x3; omegab.\n\n(**    ifte ((var_e stts \\= Free) \\&& (var_e sz \\>= nat_e size)) thendo *)\n\nStep TT.\n\nStep TT.\n\nmove => s h [[x0 [H1 [H2 [H5 [H3 [x1 [H6 H8]]]]]]] H4].\ncase: H8.\n- move => [H8 [H12 [H7 [H13 H10]]]].\n  exists x0; Resolve_topsy.\n  exists x1; Resolve_topsy.\n  left; by Resolve_topsy.\n- move => [x2 [x3 [H8 [H11 [H7 [H12 H9]]]]]].\n  exists x0; Resolve_topsy.\n  exists x1; Resolve_topsy.\n  right; exists x2, x3; by Resolve_topsy.\n\nStep TT.\n\nrewrite /while.entails => s h [[x0 [H3 [H2 [H5 [H1 [x1 [H6 H8]]]]]]] H4].\nexists x0; Resolve_topsy.\ncase: H8 => H7.\n- move: H7 => [H12 [H7 [H13 [H10 H11]]]].\n  have H8 : [ nat_e 0 \\> var_e sz ]b_s by omegab.\n  by rewrite H8 in H4.\n- exists x1; by Resolve_topsy.\n\nStep TT.\n\n(*      (fnd <- cst_e 1%Z) *)\n\nStep TT.\n\nmove => s h [[x0 [H2 [H5 [H3 [H6 [x1 [H8 H7]]]]]]] H9].\nexists x0; split.\nby apply Heap_List_inde_store with s.\nResolve_topsy.\nexists x1; Resolve_topsy.\ncase: H7.\n- move => [H4 [H12 [H1 [H13 H10]]]].\n  suff : False by done. omegab.\n- move => [x2 [[] [H11 [H1 [H12 [H10 H13]]]]]].\n  + simpl hlstat_bool2expr in H12.\n    right; right; right; exists x2.\n    split; first by omegab.\n    split; first by assumption.\n    rewrite eval_b_upd_subst; by intuition.\n  + suff : False by done. omegab.\n\n(**    elsedo\n         (entry <-* (entry -.> next))). *)\n\nStep TT.\n\nrewrite /while.entails => s h [[x0 [H2 [H5 [H1 [H6 [x1 [H8 H4]]]]]]] H3].\ncase: H4.\n- move => [H11 [H7 [H12 [H9 H14]]]].\n  exists (nat_e 0).\n  apply mapsto_strictly_exact; split.\n  move/hl_getnext_last : H2 => H2; case_sepcon H2.\n  Compose_sepcon h1 h2; [rewrite /next; by Mapsto | done].\n  rewrite /wp_assign.\n  exists x0; split.\n  by apply Heap_List_inde_store with s.\n  Resolve_topsy.\n  exists 0; Resolve_topsy.\n  left; by Resolve_topsy.\n- case => [x2 [x3 [H11 [H7 [H12 [H9 H13]]]]]].\n  exists (nat_e (x1 + 2 +x2)).\n  apply mapsto_strictly_exact; split.\n  move/In_hl_destruct : H11 => [x4 [x5 [H15 H14]]].\n  rewrite H15 in H2.\n  move/hl_getnext : H2 => [h1 [h2 [H4 [H16 [H10 H17]]]]].\n  Compose_sepcon h1 h2; last by done.\n  rewrite /next; by Mapsto.\n  rewrite /wp_assign.\n  exists x0; split.\n  by apply Heap_List_inde_store with s.\n  Resolve_topsy.\n  exists (x1 + 2 + x2); Resolve_topsy.\n  move/In_hl_destruct : H11 => [x4 [x5 [H15 H14]]].\n  case: x5 H15 => [|[n b] x5] H15.\n  + right; left; split.\n    by rewrite H15 get_endl_app H14.\n    split.\n    rewrite eval_b_upd_subst; by omegab.\n    ssromega.\n  + right; right; left; exists n, b.\n    split; first by ssromega.\n    split.\n    rewrite H15; apply In_hl_or_app; right => /=.\n    case: ifP => // _.\n    by rewrite H14 /= !eqxx.\n  by rewrite eval_b_upd_subst; omegab.\nQed.\n\nDefinition brk := 10.\nDefinition tmp := 11.\nDefinition cstts := 12.\nDefinition nstts := 13.\n\nDefinition compact'_specif:= forall adr size x sizex,\n size > 0 -> adr > 0 ->\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n     In_hl l (x, sizex, alloc) adr /\\\n     [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null \\&& var_e cptr \\= nat_e adr ]b_s }}\n  compact' cptr nptr brk tmp cstts nstts\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n     In_hl l (x, sizex, alloc) adr /\\\n     [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s }}.\n\nLemma compact'_verif: compact'_specif.\nProof.\nrewrite /compact'_specif /compact' => adr size x sizex H H0.\n\n(**  while (var_e cptr \\!= null) ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s  /\\\n  (exists cptr_value, [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    (cptr_value = 0 \\/\n      cptr_value = get_endl l adr \\/\n      exists cptr_size cptr_status, In_hl l (cptr_value, cptr_size, cptr_status) adr))).\n\nrewrite /while.entails => s h [x0 [H2 [H5 H6]]].\nexists x0.\nsplit; first by assumption.\nsplit; first by assumption.\nsplit; first by omegab.\nexists adr.\nsplit; first by omegab.\ncase: x0 H2 H5 => [| [n b] x0] H2 H5.\n- by rewrite /= in H5.\n- right; right; exists n, b => /=.\n  by rewrite !eqxx.\n\nrewrite /while.entails => s h [[x0 [H2 [H3 [H4 H5]]]] H6].\nexists x0; by Resolve_topsy.\n\n(**    nptr <-* (cptr -.> next); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n      (exists cptr_value nptr_value,\n        [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n        [ var_e nptr \\= nat_e nptr_value ]b_s /\\\n           ((cptr_value = get_endl l adr /\\\n             nptr_value = 0) \\/\n            exists cptr_size cptr_status,\n               In_hl l (cptr_value, cptr_size, cptr_status) adr /\\\n               nptr_value = cptr_value + 2 + cptr_size))).\n\nmove: H1 => [[l [Hl [Hl' [Hs [cptr [Hs' [Hcptr' | [Hcptr' | [cptr_size [cptr_status Hl'']]]]]]]]]] Hcptr].\n- subst cptr; by omegab.\n- exists (nat_e 0).\n  apply mapsto_strictly_exact; split.\n  + move/hl_getnext_last : Hl => Hl; case_sepcon Hl.\n    Compose_sepcon h1 h2; [rewrite /next; by Mapsto | done].\n  + exists l; Resolve_topsy.\n    exists cptr, 0; by Resolve_topsy.\n- exists (nat_e (cptr + 2 + cptr_size)).\n  apply mapsto_strictly_exact; split.\n  move/In_hl_destruct : Hl'' => [x0 [x1 [H5 H6]]].\n  rewrite H5 in Hl.\n  move/hl_getnext : Hl => H4'.\n  case_sepcon H4'.\n  Compose_sepcon h1 h2; [rewrite /next; by Mapsto | done].\n  exists l; Resolve_topsy.\n  exists cptr, (cptr + 2 + cptr_size); Resolve_topsy.\n  right; by exists cptr_size, cptr_status.\n\n(*:    brk <- nat_e 1 ; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null \\&& var_e brk \\= nat_e 1 ]b_s /\\\n  (exists cptr_value nptr_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e nptr_value ]b_s /\\\n    ((cptr_value = get_endl l adr /\\\n      nptr_value = 0) \\/\n    exists cptr_size cptr_status,\n      In_hl l (cptr_value,cptr_size,cptr_status) adr /\\\n      nptr_value = cptr_value + 2 + cptr_size))).\n\ncase: H1 => l [Hl [Hl' [Hb [cptr_value [nptr_value [Hcptr [Hnptr Htmp]]]]]]].\nrewrite /wp_assign.\nexists l; Resolve_topsy.\nexists cptr_value, nptr_value; by Resolve_topsy.\n\n(*:    cstts <-* (cptr -.> status); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null \\&& var_e brk \\= nat_e 1 ]b_s /\\\n  (exists cptr_value nptr_value cstts_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e nptr_value ]b_s /\\\n        [ var_e cstts \\= cstts_value ]b_s /\\\n        ((cptr_value = get_endl l adr /\\\n          nptr_value = 0 /\\\n          cstts_value = Allocated) \\/\n        exists cptr_size cptr_status,\n          In_hl l (cptr_value,cptr_size,cptr_status) adr /\\\n          nptr_value = cptr_value + 2 + cptr_size /\\\n          cstts_value = (hlstat_bool2expr cptr_status)))).\n\ncase: H1 => l [Hl [Hl' [Hb [cptr_value [nptr_value [Hcptr [Hnptr []]]]]]]].\n- case=> Hcptr_value Hnptr_value.\n  exists Allocated.\n  apply mapsto_strictly_exact; split.\n  move/hl_getstat_last : Hl => Hl; case_sepcon Hl.\n  Compose_sepcon h1 h2; [rewrite /status; by Mapsto | done].\n  exists l; Resolve_topsy.\n  exists cptr_value, nptr_value, Allocated; by Resolve_topsy.\n- case=> cptr_size [cptr_status [Hl'' Hnptr_value]].\n  exists (hlstat_bool2expr cptr_status).\n  apply mapsto_strictly_exact; split.\n  move/In_hl_destruct : Hl'' => [l1 [l2 [Hl1l2 Hcptr_value]]].\n  rewrite Hl1l2 in Hl; move/hl_getstatus : Hl => Hl; case_sepcon Hl.\n  Compose_sepcon h1 h2; [rewrite /status; by Mapsto | done].\n  exists l; Resolve_topsy.\n  exists cptr_value, nptr_value, (hlstat_bool2expr cptr_status); Resolve_topsy.\n  by destruct cptr_status; Resolve_topsy.\n  right; exists cptr_size, cptr_status; by Resolve_topsy.\n\n(**    while ((var_e cstts \\= Free) \\&& (var_e nptr \\!= null) \\&& (var_e brk \\= nat_e 1)) ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  ((exists cptr_value cptr_size brk_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e (cptr_value + 2 + cptr_size) ]b_s /\\\n    [ var_e cstts \\= Free ]b_s /\\\n    [ var_e brk \\= nat_e brk_value ]b_s /\\\n    In_hl l (cptr_value,cptr_size,topsy_hm.free) adr /\\\n    ((cptr_value + 2 + cptr_size = get_endl l adr /\\ (brk_value = 0 \\/ brk_value = 1)) \\/\n      (exists  nptr_size nptr_status,\n        In_hl l (cptr_value + 2 + cptr_size,nptr_size,nptr_status) adr /\\\n        ((nptr_status = true /\\ brk_value = 1) \\/\n          (nptr_status = false /\\ (brk_value = 1 \\/ brk_value = 0)))))) \\/\n  (exists cptr_value nptr_value cstts_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e nptr_value ]b_s /\\\n    [ var_e cstts \\= Allocated ]b_s /\\\n    [ var_e brk \\= nat_e 1 ]b_s /\\\n    ((cptr_value = get_endl l adr /\\\n      nptr_value = 0 /\\\n      cstts_value = Allocated) \\/\n    (exists cptr_size cptr_status,\n      In_hl l (cptr_value,cptr_size,cptr_status) adr /\\\n      nptr_value = cptr_value + 2 + cptr_size))))).\n\ncase : H1 => x0 [H2 [H5 [H7 [x1 [x2 [x3 [H13 [H11 [H12 H10]]]]]]]]].\nexists x0; Resolve_topsy.\ncase: H10.\n- case => H4 [H13' Hx3]; subst x3.\n  right; exists x1, x2, Allocated; by Resolve_topsy.\n- case => x4 [[] [H4 [Hx2 Hx3]]]; subst x2 x3.\n  + left; exists x1, x4, 1; Resolve_topsy.\n    move/In_hl_destruct : H4 => [x2 [x3 [Hx0 Hx1]]].\n    case : x3 Hx0 => [| [n b] x3] Hx0.\n    * left; rewrite Hx0 get_endl_app /=; ssromega.\n    * right; exists n, b.\n      split; last by destruct b; Resolve_topsy.\n      rewrite Hx0; apply In_hl_or_app; right => /=.\n      have : get_endl x2 adr != x1 + 2 + x4 by apply/eqP; ssromega.\n      move/negbTE => -> /=.\n      by rewrite Hx1 !eqxx.\n  + right; exists x1, (x1 + 2 + x4), Allocated; Resolve_topsy.\n    right; by exists x4, false.\n\n(**       nstts <-* (nptr -.> status); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  (exists cptr_value cptr_size brk_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e (cptr_value + 2 + cptr_size) ]b_s /\\\n    [ var_e cstts \\= Free ]b_s /\\\n    [ var_e brk \\= nat_e brk_value ]b_s /\\\n    In_hl l (cptr_value,cptr_size,topsy_hm.free) adr /\\\n    ((cptr_value + 2 + cptr_size = get_endl l adr /\\ (brk_value = 0 \\/ brk_value = 1) /\\\n        [ var_e nstts \\= Allocated ]b_s) \\/\n      exists  nptr_size nptr_status,\n        In_hl l (cptr_value + 2 + cptr_size,nptr_size,nptr_status) adr /\\\n        ((nptr_status = true /\\ brk_value = 1) \\/\n          (nptr_status = false /\\ (brk_value = 1 \\/ brk_value = 0))) /\\\n        [ var_e nstts \\= hlstat_bool2expr nptr_status ]b_s))).\n\ncase : H1 => [[x0 [H3 [H6 [H7 H8]]]] H2].\ncase : H8.\n- case => cptr_val [cptr_sz [brk_val [H12 [H13 [H14 [H15 [H17 H16]]]]]]].\n  case: H16.\n  + case => H15' H16.\n    exists Allocated.\n    rewrite /status.\n    apply mapsto_strictly_exact; split.\n    * move/hl_getstat_last : H3 => H3; case_sepcon H3.\n      Compose_sepcon h1 h2; [by Mapsto | done].\n    * rewrite /wp_assign; exists x0.\n      Resolve_topsy.\n      exists cptr_val, cptr_sz, brk_val; Resolve_topsy.\n      left; by Resolve_topsy.\n  + case => x4 [x5 [H15' H16]].\n    exists (hlstat_bool2expr x5).\n    rewrite /status.\n    apply mapsto_strictly_exact; split.\n    * case/In_hl_destruct : H15' => x6 [x7 [H17' H18]].\n      rewrite H17' in H3; move/hl_getstatus : H3 => H3; case_sepcon H3.\n      Compose_sepcon h1 h2; [rewrite H18 in H3_h1; by Mapsto | done].\n    * rewrite /wp_assign; exists x0.\n      Resolve_topsy.\n      exists cptr_val, cptr_sz, brk_val; Resolve_topsy.\n      right; exists x4, x5; by destruct x5; Resolve_topsy.\n- case => cptr_val [nptr_val [cstts_val [H12 [H13 [H14 [H15 H16]]]]]].\n  suff : False by done. omegab.\n\n(**       ifte (var_e nstts \\!= Free) thendo ( *)\n\nStep TT.\n\n(**          brk <- nat_e 0 *)\n\nStep TT.\nmove=> s h H2.\ncase : H2 => [[x0 [H3 [H6 [H7 [x1 [x2 [x3 [H8 [H9 [H10 [H11 [H12 H13]]]]]]]]]]]] H4].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nleft.\ncase: H13.\n- case => H13 [H15 H16].\n  exists x1, x2, 0; by Resolve_topsy.\n- case => x4 [x5 [H13 [H15 H16]]].\n  exists x1; exists x2, 0; Resolve_topsy.\n  right; exists x4, x5; Resolve_topsy.\n  destruct x5; omegab.\n\n(**       ) elsedo (\n\t tmp <-* nptr -.> next; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  (exists cptr_value cptr_size brk_value,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e nptr \\= nat_e (cptr_value + 2 + cptr_size) ]b_s /\\\n    [ var_e cstts \\= Free ]b_s /\\\n    [ var_e brk \\= nat_e brk_value ]b_s /\\\n    In_hl l (cptr_value, cptr_size, topsy_hm.free) adr /\\\n    exists nptr_size nptr_status,\n      In_hl l (cptr_value + 2 + cptr_size, nptr_size, nptr_status) adr /\\\n      (nptr_status = true /\\ brk_value = 1) /\\\n      [ var_e tmp \\= nat_e (cptr_value + 2 + cptr_size + 2 + nptr_size) ]b_s)).\n\ncase : H1 => [[x0 [H3 [H6 [H7 [x1 [x2 [x3 [H8 [H9 [H10 [H11 [H12 H13]]]]]]]]]]]] H4].\ncase : H13.\n- case => H13 [H15 H16].\n  suff : False by done. omegab.\n- case => x4 [x5 [H13 [H15 H16]]].\n  destruct x5.\n  + exists (nat_e (x1 + 2 + x2 + 2 + x4)).\n    rewrite /next.\n    apply mapsto_strictly_exact; split.\n    * case/In_hl_destruct : H13 => x5 [x6 [H5 H17]].\n      rewrite H5 in H3.\n      move/hl_getnext : H3 => H14.\n      case_sepcon H14.\n      Compose_sepcon h1 h2; last by done.\n      rewrite H17 in H14_h1; by Mapsto.\n    * exists x0; Resolve_topsy.\n      exists x1, x2, 1.\n      case: H15 => [ [_ H14] | [] // ].\n      subst x3;  Resolve_topsy.\n      exists x4, true; by Resolve_topsy.\n  + case: H15 => H5.\n    * by case: H5.\n    * suff : False by done. omegab.\n\n(**         cptr -.> next *<- var_e tmp ; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  (exists cptr_value cptr_size,\n    [ var_e cptr \\= nat_e cptr_value ]b_s /\\\n    [ var_e cstts \\= Free ]b_s /\\\n    [ var_e brk \\= nat_e 1 ]b_s /\\\n    In_hl l (cptr_value, cptr_size, topsy_hm.free) adr /\\\n    [ var_e tmp \\= nat_e (cptr_value + 2 + cptr_size) ]b_s)).\n\ncase : H1 => x0 [H2 [H5 [H6 [x1 [x2 [x3 [H10 [H11 [H12 [H13 [H14 [x4 [x5 [H15 [[H16 H18] H17]]]]]]]]]]]]]]].\n\ncase: (In_hl_next _ _ _ _ _ _ _ H14 H15) => x6 [x7 [H4 Hx1]].\nsubst x5 x3.\nrewrite H4 /topsy_hm.free in H2.\ncase: (Heap_List_compaction x6 x7 x2 x4 _ s h H2) => x3 mem_s_h.\nexists x3.\ncase_sepcon mem_s_h; Compose_sepcon h1 h2.\nby rewrite /next; Mapsto.\nmove: mem_s_h_h2; apply monotony_imp => h' Hh'.\nrewrite /next in Hh'; by Mapsto.\nexists (x6 ++ (x2 + x4 + 2, topsy_hm.free) :: x7).\nsplit; first by assumption.\nsplit.\n- rewrite H4 in H5.\n  case/In_hl_app_or : H5 => H18.\n  + by apply In_hl_or_app; left.\n  + apply In_hl_or_app; right.\n    move: H18.\n    rewrite /= /alloc /topsy_hm.free /= -andbA andbC /= -andbA andbC /=.\n    rewrite (_ : get_endl x6 adr + 2 + (x2 + x4 + 2) = get_endl x6 adr + 2 + x2 + 2 + x4) //; ssromega.\n- Resolve_topsy.\n  exists x1, (x2 + 2 + x4); Resolve_topsy.\n  apply In_hl_or_app; right => /=.\n  rewrite Hx1 (_ : x2 + x4 + 2 = x2 + 2 + x4) //; last by ssromega.\n  by rewrite !eqxx.\n\n(**         nptr <- (var_e tmp) *)\n\nStep TT.\nmove=> s h H2.\nrewrite /wp_assign.\ncase : H2 => x0 [H2 [H5 [H3 [x1 [x2 [H9 [H11 [H7 [H8 H6]]]]]]]]].\nexists x0; Resolve_topsy.\nleft; exists x1, x2, 1; Resolve_topsy.\ncase/In_hl_destruct : H8 => x3 [x4 [Hx0 H13]].\ncase : x4 Hx0 => [|[n b] x4] Hx0.\n- left; rewrite Hx0 get_endl_app /= H13; tauto.\n- right; exists n, b; split.\n  rewrite Hx0; apply In_hl_or_app; right => /=.\n  case: ifP => // _.\n  by rewrite H13 !eqxx.\ndestruct b; tauto.\n\n(**       )\n    );\n    cptr <-* (cptr -.> next)\n  ). *)\n\nStep TT.\nrewrite /while.entails; move=> s h [[x0 [H3 [H6 [H7 H8]]]] H4].\ncase : H8.\n- case => x1 [x2 [x3 [H12 [H5 [H11 [H9 [H10 H14]]]]]]].\n  case : H14.\n  + case => H13 H14.\n    rewrite /next.\n    exists (nat_e (x1 + 2 + x2)).\n    apply mapsto_strictly_exact; split.\n    case/In_hl_destruct : H10 => x4 [x5 [H8 H16]].\n    rewrite H8 in H3; move/hl_getnext : H3 => H2'.\n    case_sepcon H2'; Compose_sepcon h1 h2; [by Mapsto | done].\n    rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists (x1 + 2 + x2); by Resolve_topsy.\n  + case => x4 [x5 [H13 H14]].\n    rewrite /next.\n    exists (nat_e (x1 + 2 + x2)).\n    apply mapsto_strictly_exact; split.\n    case/In_hl_destruct : H10 => x6 [x7 [H8 H16]].\n    rewrite H8 in H3; move/hl_getnext : H3  => H2'.\n    case_sepcon H2'; Compose_sepcon h1 h2; [by Mapsto | done].\n    rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists (x1 + 2 + x2); Resolve_topsy.\n    right; right; by exists x4, x5.\n- case => x1 [x2 [x3 [H5 [H11 [H9 [H10 H13]]]]]].\n  case: H13.\n  + case => H12 [H14 H15].\n    unfold next.\n    exists (nat_e 0).\n    apply mapsto_strictly_exact; split.\n    move/hl_getnext_last : H3 => H3; case_sepcon H3.\n    subst x1 x2 x3.\n    Compose_sepcon h1 h2; [by Mapsto | done].\n    rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists 0; by Resolve_topsy.\n  + case => x4 [x5 [H12 H13]].\n    exists (nat_e (x1 + 2 + x4)).\n    unfold next.\n    apply mapsto_strictly_exact; split.\n    case/In_hl_destruct : H12 => x6 [x7 [H8 H15]].\n    rewrite H8 in H3; move/hl_getnext : H3 => H2'.\n    case_sepcon H2'; Compose_sepcon h1 h2; [by Mapsto | done].\n    rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists (x1 + 2 + x4); Resolve_topsy.\n    right.\n    case/In_hl_destruct : H12 => x6 [x7 [H8 H15]].\n    case: x7 H8 => [|[n b] x7] H8.\n    * left; by rewrite H8 get_endl_app /= H15.\n    * right; exists n, b.\n      rewrite H8; apply In_hl_or_app; right => /=.\n      have : get_endl x6 adr <> x1 + 2 + x4 by ssromega.\n      move/eqP/negbTE => -> /=.\n      rewrite (_ : get_endl x6 adr + 2 + x4 = x1 + 2 + x4); last by congruence.\n      by rewrite !eqxx.\nQed.\n\nDefinition compact_specif := forall adr size sizex x,\n  size > 0 -> adr > 0 ->\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null \\&& var_e cptr \\= nat_e adr ]b_s }}\n  compact cptr nptr stts\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s }}.\n\nLemma compact_verif : compact_specif.\nProof.\nunfold compact_specif.\nintros.\nunfold compact.\n\n(**  while (var_e cptr \\!= null) ( *)\n\nStep (fun s h => exists l,\n  Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    (cur_adr = 0 \\/\n      (cur_adr = get_endl l adr /\\\n        cur_adr > 0) \\/\n      (exists cur_size cur_status, In_hl l (cur_adr, cur_size, cur_status) adr /\\\n        cur_adr > 0))).\n\nrewrite /while.entails => s h [x0 [H1 [H4 H3]]].\nexists x0; Resolve_topsy.\nexists adr.\nsplit; first by omegab.\ncase: x0 H1 H4 => [| [n b] x0] H1 H4.\n- by rewrite /= in H4.\n- right; right; exists n, b; split; last by done.\n  by rewrite /= !eqxx.\n\nrewrite /while.entails => s h [[x0 [H2 [H3 [H4 H5]]]] H1].\nexists x0; by Resolve_topsy.\n\n(**    stts <-* (cptr -.> status); *)\n\nStep (fun s h => exists l,\n  Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    ((cur_adr = get_endl l adr /\\\n      cur_adr > 0 /\\\n      [ var_e stts \\= Allocated ]b_s) \\/\n    (exists cur_size cur_status, In_hl l (cur_adr, cur_size, cur_status) adr /\\\n      [ var_e stts \\= hlstat_bool2expr cur_status ]b_s /\\\n      cur_adr > 0))).\n\ncase : H1 => [[x0 [H2 [H4 [H5 [x1 [H8 H7]]]]]] H3].\ncase: H7 => [?|].\n- subst x1; by omegab.\n- case.\n  + case => Hx1 H9.\n    exists (nat_e 0).\n    rewrite /status.\n    apply mapsto_strictly_exact; split.\n    move/hl_getstat_last : H2 => H2; case_sepcon H2.\n    Compose_sepcon h1 h2; [by Mapsto | done].\n    rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists x1; Resolve_topsy.\n    left; by Resolve_topsy.\n  + case => x2 [x3 [In_hl_x0 H9]].\n    case/In_hl_destruct : (In_hl_x0) => x4 [x5 [H10 H11]].\n    rewrite /status.\n    exists (hlstat_bool2expr x3).\n    apply mapsto_strictly_exact; split.\n    * rewrite H10 in H2; move/hl_getstatus : H2 => H2; case_sepcon H2.\n      Compose_sepcon h1 h2; [by Mapsto | done].\n    * rewrite /wp_assign.\n      exists x0; Resolve_topsy.\n      exists x1; Resolve_topsy.\n      right; exists x2, x3; Resolve_topsy.\n      by destruct x3; Resolve_topsy.\n\n(**    ifte (var_e stts \\=  Free) thendo ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    ((cur_adr = get_endl l adr /\\ cur_adr > 0 ) \\/\n    (exists cur_size cur_status, In_hl l (cur_adr, cur_size, cur_status) adr /\\\n      cur_adr > 0))).\n\n(**      nptr <-* (cptr -.> next);  *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    (exists cur_size, In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      [ var_e nptr \\= nat_e (cur_adr + 2 + cur_size) ]b_s /\\\n      cur_adr > 0)).\n\ncase : H1 => [[x0 [H2 [H4 [H5 [x1 [H6 H7]]]]]] H3].\ncase : H7.\n- case => H7 [H10 H11].\n  suff : False by done. omegab.\n- case => x2 [[] [H7 [H11 H10]]].\n  + exists (nat_e (x1 + 2 + x2)).\n    unfold next.\n    apply mapsto_strictly_exact; split.\n    * case/In_hl_destruct : H7 => x3 [x4 [Hx0 H9]].\n      rewrite Hx0 in H2; move/hl_getnext : H2 => H12.\n      case_sepcon H12; Compose_sepcon h1 h2; [by Mapsto | done].\n    * rewrite /wp_assign.\n      exists x0; Resolve_topsy.\n      exists x1; Resolve_topsy.\n      exists x2; by Resolve_topsy.\n  + suff : False by done. omegab.\n\n(**      stts <-* (nptr -.> status); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    (exists cur_size, In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      [ var_e nptr \\= nat_e (cur_adr + 2 + cur_size) ]b_s /\\\n      cur_adr > 0 /\\ (\n        (exists next_size next_status,\n          In_hl l ((cur_adr + 2 + cur_size), next_size, next_status) adr /\\\n          [ var_e stts \\= hlstat_bool2expr next_status ]b_s) \\/\n        (cur_adr + 2 + cur_size = get_endl l adr /\\\n          [ var_e stts \\= Allocated ]b_s)))).\n\ncase : H1 => x0 [H1 [H4 [H7 [x1 [H5 [x2 [H6 [H8 H9]]]]]]]].\ncase/In_hl_destruct : (H6) => x3 [x4 [H10 Hx1]].\ncase: x4 H10 => [|[n b] x4] H10.\n- exists Allocated.\n  rewrite /status.\n  apply mapsto_strictly_exact; split.\n  + rewrite H10 in H1; move/hl_getstat_last : H1 => H1; case_sepcon H1.\n    Compose_sepcon h1 h2; last by done.\n    rewrite get_endl_app in H1_h1; by Mapsto.\n  + rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists x1; Resolve_topsy.\n    exists x2; Resolve_topsy.\n    right; Resolve_topsy.\n    by rewrite -Hx1 H10 get_endl_app.\n- exists (hlstat_bool2expr b).\n  rewrite /status.\n  apply mapsto_strictly_exact; split.\n  + rewrite H10 in H1; Hl_getstatus H1 n H2; last by done.\n    rewrite get_endl_app [get_endl _]/= in H2_h1; by Mapsto.\n  + exists x0; Resolve_topsy.\n    exists x1; Resolve_topsy.\n    exists x2; Resolve_topsy.\n    left; exists n, b; split.\n    * rewrite H10; apply In_hl_or_app; right => /=.\n      have : get_endl x3 adr <> x1 + 2 + x2 by ssromega.\n      move/eqP/negbTE => -> /=.\n      by rewrite Hx1 !eqxx.\n    * by destruct b; Resolve_topsy.\n\n(*:      while (var_e stts \\= Free) ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    exists cur_size, In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      [ var_e nptr \\= nat_e (cur_adr + 2 + cur_size) ]b_s /\\\n      cur_adr > 0 /\\ (\n        (exists next_size next_status,\n          In_hl l (cur_adr + 2 + cur_size, next_size, next_status) adr /\\\n          [ var_e stts \\= hlstat_bool2expr next_status ]b_s) \\/\n        (cur_adr + 2 + cur_size = get_endl l adr /\\\n          [ var_e stts \\= Allocated ]b_s))).\n\ndone.\n\n(**        stts <-* (nptr -.> next); *)\n\nrewrite /while.entails => s h [[x0 [H2 [H3 [H4 [x1 [H5 [x2 [H6 [H7 [H8 H9]]]]]]]]]] H1].\nexists x0; Resolve_topsy.\nexists x1; Resolve_topsy.\nright; by exists x2, topsy_hm.free.\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    exists cur_size,  In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      [ var_e nptr \\= nat_e (cur_adr + 2 + cur_size) ]b_s /\\\n      cur_adr > 0 /\\\n      exists next_size,\n        In_hl l (cur_adr + 2 + cur_size, next_size, topsy_hm.free) adr /\\\n        [ var_e stts \\= nat_e (cur_adr + 2 + cur_size + 2 + next_size) ]b_s).\n\ncase : H1 => [[x0 [H2 [H4 [H5 [x1 [H6 [x2 [H7 [H8 [H9 H11]]]]]]]]]] H3].\ncase: H11.\n- case => x3 [x4 [H11 H12]].\n  destruct x4.\n  + case/In_hl_destruct : (H11) => x4 [x5 [Hx0 H14]].\n    exists (nat_e (x1 + 2 + x2 + 2 +x3)).\n    rewrite /next.\n    apply mapsto_strictly_exact; split.\n    * rewrite Hx0 in H2; move/hl_getnext : H2 => H2.\n      case_sepcon H2; Compose_sepcon h1 h2; [by Mapsto | done].\n    * rewrite /wp_assign.\n      exists x0; Resolve_topsy.\n      exists x1; Resolve_topsy.\n      exists x2; Resolve_topsy.\n      exists x3; Resolve_topsy.\n  + suff : False by done. omegab.\n- case => H11 H12.\n  suff : False by done. omegab.\n\n(**        (cptr -.> next) *<- var_e stts; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    exists cur_size,\n      In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      cur_adr > 0 /\\\n      [ var_e stts \\= nat_e (cur_adr + 2 + cur_size) ]b_s).\n\ncase : H1 => x0 [H1 [H4 [H5 [x1 [H6 [x2 [H7 [H8 [H9 [x3 [H10 H11]]]]]]]]]]].\ncase: (In_hl_next _ _ _ _ _ _ _ H7 H10) => x4 [x7 [H12 H13]].\nrewrite /next.\nrewrite H12 in H1; case/Heap_List_compaction : H1 => x5 H14.\ncase_sepcon H14.\nexists x5.\nCompose_sepcon h1 h2.\n- by Mapsto.\n- move: H14_h2; apply monotony_imp => h' Hh'; first by Mapsto.\n  exists (x4 ++ (x2 + x3 + 2, topsy_hm.free) :: x7).\n  split; first by done.\n  split.\n  * rewrite H12 in H4; case/In_hl_app_or : H4 => H4.\n    - apply In_hl_or_app; by left.\n    - apply In_hl_or_app; right.\n      move: H4.\n      rewrite /= /alloc /topsy_hm.free /= -andbA andbC /= -andbA andbC /=.\n      rewrite (_ : get_endl _ adr + 2 + (x2 + x3 + 2) = get_endl x4 adr + 2 + x2 + 2 + x3) //; ssromega.\n  * Resolve_topsy.\n    exists x1; Resolve_topsy.\n    exists (x2 + x3 + 2); split.\n    - apply In_hl_or_app; right => /=.\n      by rewrite -H13 !eqxx.\n    - split; [assumption | omegab].\n\n(*:        nptr <- var_e stts; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists cur_adr, [ var_e cptr \\= nat_e cur_adr ]b_s /\\\n    exists cur_size,\n      In_hl l (cur_adr, cur_size, topsy_hm.free) adr /\\\n      cur_adr > 0 /\\\n      [ var_e nptr \\= nat_e (cur_adr + 2 + cur_size) ]b_s).\n\ncase : H1 => x0 [H1 [H4 [H5 [x1 [H6 [x2 [H8 [H9 H2]]]]]]]].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nexists x1; Resolve_topsy.\nexists x2; by Resolve_topsy.\n\n(*:        stts <-* (nptr -.> status))) *)\n\nStep TT.\n\nrewrite /while.entails => s h [x0 [H1 [H4 [H5 [x1 [H6 [x2 [H8 [H9 H2]]]]]]]]].\ncase/In_hl_destruct : (H8) => x3 [x4 [H10 H11]].\ncase : x4 H10 => [|[n b] x4] H10.\n- exists Allocated.\n  rewrite /status.\n  apply mapsto_strictly_exact; split.\n  + move/hl_getstat_last : H1 => H1; case_sepcon H1.\n    rewrite H10 get_endl_app /= H11 in H1_h1.\n    Compose_sepcon h1 h2; [by Mapsto | done].\n  + rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists x1; Resolve_topsy.\n    exists x2; Resolve_topsy.\n    right; Resolve_topsy.\n    by rewrite H10 get_endl_app H11.\n- exists (hlstat_bool2expr b).\n  rewrite /status.\n  apply mapsto_strictly_exact; split.\n  + rewrite H10 in H1; Hl_getstatus H1 n H3; last by done.\n    rewrite get_endl_app [get_endl _]/= in H3_h1; by Mapsto.\n  + rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists x1; Resolve_topsy.\n    exists x2; Resolve_topsy.\n    left; exists n, b; split.\n    * rewrite H10; apply In_hl_or_app; right => /=.\n      have : get_endl x3 adr <> x1 + 2 + x2 by ssromega.\n      move/eqP/negbTE => -> /=.\n      by rewrite H11 !eqxx.\n    * by destruct b; Resolve_topsy.\n\n(**    elsedo\n      skip; *)\n\nStep TT.\nrewrite /while.entails => s h [[x0 [H2 [H5 [H7 [x1 [H6 H8]]]]]] H3].\nexists x0; Resolve_topsy.\nexists x1; Resolve_topsy.\ncase: H8.\n- left; tauto.\n- case => x2 [x3 [H11 [H10 H12]]].\n  right; exists x2, x3; by Resolve_topsy.\n\n(**      cptr <-* (cptr -.> next)). *)\n\nStep TT.\nrewrite /while.entails => s h [x0 [H1 [H4 [H2 [x1 [H5 H6]]]]]].\nrewrite /next.\ncase: H6.\n- case => H6 H8.\n  exists (nat_e 0).\n  apply mapsto_strictly_exact; split.\n  move/hl_getnext_last : H1 => H3; case_sepcon H3.\n  Compose_sepcon h1 h2; [by Mapsto | done].\n  rewrite /wp_assign.\n  exists x0; Resolve_topsy.\n  exists 0; by Resolve_topsy.\n- case => x2 [x3 [H6 H8]].\n  case/In_hl_destruct : H6 => x4 [x5 [H9 Hx1]].\n  exists (nat_e (x1 + 2 + x2)).\n  apply mapsto_strictly_exact; split.\n  + rewrite H9 in H1; move/hl_getnext : H1 => H3.\n    case_sepcon H3; Compose_sepcon h1 h2; [by Mapsto | done].\n  + rewrite /wp_assign.\n    exists x0; Resolve_topsy.\n    exists (x1 + 2 + x2); Resolve_topsy.\n    case : x5 H9 => [|[n b] x5] H9.\n    * right; left.\n      rewrite H9 get_endl_app Hx1 /=; ssromega.\n    * right; right; exists n, b.\n      split; last by ssromega.\n      rewrite H9; apply In_hl_or_app; right => /=.\n      have : get_endl x4 adr <> x1 + 2 + x2 by ssromega.\n      move/eqP/negbTE => -> /=.\n      by rewrite Hx1 !eqxx.\nQed.\n\nDefinition split_specif := forall adr size sizex x,\n  size > 0 -> adr > 0 ->\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n     In_hl l (x, sizex, alloc) adr /\\\n     [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n     exists y size'', size'' >= size /\\\n       In_hl l (y, size'', topsy_hm.free) adr /\\\n       [ var_e entry \\= nat_e y ]b_s /\\\n       y > 0 /\\ y <> x }}\n  split entry size cptr sz\n  {{ fun s h => exists l, In_hl l (x, sizex, alloc) adr /\\\n     exists y, y > 0 /\\ [ var_e entry \\= nat_e y ]b_s /\\\n       exists size'', size'' >= size /\\\n         (Heap_List l adr ** Array (y + 2) size'') s h /\\\n         In_hl l (y, size'', alloc) adr /\\ y <> x }}.\n\nLemma split_verif : split_specif.\nProof.\nrewrite /split_specif.\nintros.\nrewrite /split.\n\n(**  ENTRYSIZE entry sz; *)\n\nrewrite /ENTRYSIZE /LEFTOVER.\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists y size'', size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ var_e entry \\= nat_e y ]b_s /\\\n    y > 0 /\\ y <> x /\\\n    [ var_e sz \\= nat_e size'' ]b_s).\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n    exists y size'', size'' >= size /\\\n     In_hl l (y, size'', topsy_hm.free) adr /\\\n     [ var_e entry \\= nat_e y ]b_s /\\\n     y > 0 /\\ y <> x /\\\n     [ var_e sz \\= nat_e (y + 2 + size'') ]b_s).\n\ncase : H1 => x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H10 [H6 H5]]]]]]]]].\nexists (nat_e (x1 + 2 + x2)).\nrewrite /next.\napply mapsto_strictly_exact; split.\ncase/In_hl_destruct : H8 => x3 [x4 [H11 H12]].\nrewrite H11 in H1; move/hl_getnext : H1 => H2'.\ncase_sepcon H2'; Compose_sepcon h1 h2; [by Mapsto | done].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nexists x1, x2; by Resolve_topsy.\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists y size'', size'' >= size /\\\n     In_hl l (y, size'', topsy_hm.free) adr /\\\n     [ var_e entry \\= nat_e y ]b_s /\\\n     y > 0 /\\ y <> x /\\\n     [ var_e sz \\= nat_e size'' ]b_s).\n\ncase : H1 => x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H10 [H6 [H5 H9]]]]]]]]]].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nexists x1, x2; by Resolve_topsy.\n\nStep TT.\n\nStep TT.\n\nmove=> s h [[x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H10 [H6 [H5 H9]]]]]]]]]]] H1'].\nsuff : False by done. omegab.\n\nStep TT.\n\nrewrite /while.entails => *; tauto.\n\n(**  ifte (var_e sz \\>= (nat_e size \\+ nat_e LEFTOVER \\+ nat_e 2)) thendo ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists y size'', size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ var_e entry \\= nat_e y ]b_s /\\\n    y > 0 /\\ y <> x).\n\n(**    cptr <- var_e entry \\+ nat_e 2 \\+ nat_e size; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists y size'', size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ var_e entry \\= nat_e y ]b_s /\\\n    y > 0 /\\ y <> x /\\\n    [ var_e sz \\= nat_e size'' ]b_s /\\\n    size'' >= size + LEFTOVER + 2 /\\\n    [ var_e cptr \\= nat_e (y + 2 + size) ]b_s).\n\nunfold LEFTOVER.\ncase : H1 => [[x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H10 [H6 [H5 H9]]]]]]]]]]] H1'].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nexists x1, x2; Resolve_topsy; by omegab.\n\n(*:    sz <-* (entry -.> next); *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  exists y size'', size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ var_e entry \\= nat_e y ]b_s /\\\n    y > 0 /\\ y <> x /\\\n    [ var_e sz \\= nat_e (y + 2 + size'') ]b_s /\\\n    size'' >= size + LEFTOVER + 2 /\\\n    [ var_e cptr \\= nat_e (y + 2 + size) ]b_s).\n\ncase : H1 => x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H9 [H11 [H12 [H13 [H14 H15]]]]]]]]]]]].\nexists (nat_e (x1 + 2 + x2)).\nrewrite /next.\napply mapsto_strictly_exact; split.\ncase/In_hl_destruct : H8 => x3 [x4 [Hx0 Hx1]].\nrewrite Hx0 in H1; move/hl_getnext : H1 => H2'.\ncase_sepcon H2'; Compose_sepcon h1 h2; [by Mapsto | done].\nrewrite /wp_assign.\nexists x0; Resolve_topsy.\nby exists x1, x2; Resolve_topsy.\n\n(**    (cptr -.> next) *<- var_e sz; *)\n\nStep (fun s h => exists e'',\n  (cptr -.> status |~> e'' **\n    (cptr -.> status |~> Free -*\n      (fun s0 h0 => exists e''0,\n        (entry -.> next |~> e''0 **\n          (entry -.> next |~> var_e cptr -*\n            (fun s1 h1 => exists l, Heap_List l adr s h1 /\\\n              In_hl l (x, sizex, alloc) adr /\\\n              [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s1 /\\\n              exists y size'',\n                size'' >= size /\\\n                In_hl l (y, size'', topsy_hm.free) adr /\\\n                [ var_e entry \\= nat_e y ]b_s1 /\\\n                y > 0 /\\ y <> x))) s0 h0))) s h).\n\ncase : H1 => x0 [H1 [H2 [H3 [x1 [x2 [H4 [H5 [H6 [H7 [H8 [H9 [H10 H11]]]]]]]]]]]].\nrewrite (_ : x2 = size + 2 + (x2 - 2 - size)) in H5; last by ssromega.\ncase/In_hl_destruct : H5 => x3 [x4 [H3' H15]].\nrewrite H3' in H1; case/Heap_List_splitting : H1 => x5 H16.\nexists x5.\ncase_sepcon H16.\nrewrite /next.\nCompose_sepcon h1 h2.\n  rewrite H15 in H16_h1; by Mapsto.\nrewrite /status.\nmove: H16_h2; apply assert_m.monotony_imp.\n  move=> h' Hh'; by Mapsto.\nmove=> h' Hh'.\ncase: Hh' => x6 H18.\nexists x6.\ncase_sepcon H18.\nCompose_sepcon h'1 h'2; first by Mapsto.\nmove: H18_h'2; apply monotony_imp.\n  move=> h'' Hh''; by Mapsto.\nmove=> h'' Hh''.\ncase: Hh'' => x7 H21.\nexists x7.\ncase_sepcon H21.\nCompose_sepcon h''1 h''2; first by Mapsto.\nmove: H21_h''2; apply monotony_imp.\n  move=> h''' Hh'''; by Mapsto.\nmove=> h''' Hh'''.\nexists (x3 ++ (size, true) :: (x2 - 2 - size, true) :: x4).\nsplit; first by assumption.\nResolve_topsy.\n- rewrite H3' in H2; case/In_hl_app_or : H2 => H2.\n  - apply In_hl_or_app; by left.\n  - apply In_hl_or_app; right.\n    move: H2.\n    do 2 rewrite /= /alloc /topsy_hm.free /= -andbA andbC /=.\n    by rewrite !addnA.\nexists x1, size; Resolve_topsy.\napply In_hl_or_app; right => /=.\nby rewrite H15 !eqxx.\n\n(*:    (cptr -.> status) *<- Free; *)\n\nStep (fun s0 h0 => exists e'',\n  (entry -.> next |~> e'' **\n    (entry -.> next |~> var_e cptr -*\n      (fun s h => exists l,\n        Heap_List l adr s h /\\\n        In_hl l (x, sizex, alloc) adr /\\\n        [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n        exists y size'', size'' >= size /\\\n          In_hl l (y, size'', topsy_hm.free) adr /\\\n          [ var_e entry \\= nat_e y ]b_s /\\\n          y > 0 /\\ y <> x))) s0 h0).\n\nassumption.\n\n(**    (entry -.> next) *<- var_e cptr) *)\n\nStep TT.\nby apply hoare_prop_m.entails_id.\n\n(**   elsedo\n     skip *)\n\nStep TT.\nrewrite /while.entails => s h [[x0 [H1 [H4 [H2 [x1 [x2 [H7 [H8 [H10 [H6 [H5 H9]]]]]]]]]]] H1'].\nexists x0; Resolve_topsy.\nexists x1, x2; by Resolve_topsy.\n\n(**  (entry -.> status) *<- Allocated. *)\n\nStep TT.\nrewrite /while.entails => s h [x0 [H1 [H2 [H3 [x1 [x2 [H4 [H5 [H6 [H7 H8]]]]]]]]]].\ncase/In_hl_destruct : H5 => x3 [x4 [H11 H12]].\nrewrite H11 in H1; case/hl_free2alloc : H1 => x5 H1.\ncase_sepcon H1.\nexists x5.\nrewrite /status.\nCompose_sepcon h1 h2; first by Mapsto.\nmove: H1_h2; apply monotony_imp => h' Hh'; first by Mapsto.\ncase_sepcon Hh'.\nexists (x3 ++ (x2,false) :: x4).\nResolve_topsy.\n- rewrite H11 in H2; case/In_hl_app_or : H2 => H2.\n  - apply In_hl_or_app; by left.\n  - rewrite /= /alloc /topsy_hm.free /= -andbA andbC /= in H2.\n    apply In_hl_or_app; right => /=.\n    have : get_endl x3 adr <> x by lia.\n    by move/eqP/negbTE => ->.\n- exists x1; Resolve_topsy.\n  exists x2; Resolve_topsy.\n  Compose_sepcon h'1 h'2; [done | by Array_equiv].\n  apply In_hl_or_app; right.\n  by rewrite /= H12 !eqxx.\nQed.\n\nDefinition hmAlloc_specif := forall adr x sizex size, adr > 0 -> size > 0 ->\n  {{ fun s h => exists l, Heap_List l adr s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    [ var_e hmStart \\= nat_e adr ]b_s }}\n  hmAlloc result size entry cptr fnd stts nptr sz\n  {{ fun s h =>\n    (exists l y, y > 0 /\\ [ var_e result \\= nat_e (y + 2) ]b_s /\\\n      exists size'', size'' >= size /\\\n        (Heap_List l adr ** Array (y + 2) size'') s h /\\\n        In_hl l (x, sizex, alloc) adr /\\ In_hl l (y, size'', alloc) adr /\\\n        x <> y)\n    \\/\n    (exists l, [ var_e result \\= nat_e 0 ]b_s /\\\n      Heap_List l adr s h /\\ In_hl l (x, sizex, alloc) adr) }}.\n\nLemma hmAlloc_verif: hmAlloc_specif.\nProof.\nrewrite /hmAlloc_specif /hmAlloc => adr x sizex size H H0.\n\n(**  result <- null; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s).\n\ncase : H1 => x0 [H1 [H4 H5]].\nrewrite /wp_assign.\nexists x0; by Resolve_topsy.\n\n(**  findFree size entry fnd sz stts; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  ((exists y size'',\n    size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ (var_e entry \\= nat_e y) ]b_s /\\\n    y > 0) \\/\n  [ var_e entry \\= null ]b_s)).\n\nmove: (findFree_verif adr x sizex size H0 H) => H1.\n\nStep TT. (* apply hoare_conseq (?) *)\n- rewrite /while.entails => s h [x0 [H2 [H4 [H3 H6]]]] {H1}.\n  exists x0; Resolve_topsy.\n  case : H6 => H1.\n  + case : H1 => x1 [x2 [H5 [H7 H1]]].\n    left; exists x1, x2; Resolve_topsy.\n    omegab.\n  + by right.\n- by apply hoare_prop_m.entails_id.\n\n(**  ifte (var_e entry \\= null) thendo ( *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s /\\\n  ((exists y size'', size'' >= size /\\\n    In_hl l (y, size'', topsy_hm.free) adr /\\\n    [ var_e entry \\= nat_e y ]b_s /\\\n    y > 0) \\/ [ var_e entry \\= null ]b_s)).\n\n(**    cptr <- var_e hmStart; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr ]b_s /\\ [ var_e result \\= null ]b_s /\\\n  [ var_e entry \\= null ]b_s /\\ [ var_e cptr \\= var_e hmStart ]b_s).\n\ncase : H1 => [[x0 [H2 [H5 [H4 H7]]]] H6].\ncase : H7.\n- case => x1 [x2 [H7 [H9 [H11 H8]]]].\n  suff : False by done. omegab.\n- exists x0; by Resolve_topsy.\n\n(**    compact cptr nptr stts; *)\n\nStep (fun s h => exists l, Heap_List l adr s h /\\\n  In_hl l (x, sizex, alloc) adr /\\\n  [ var_e hmStart \\= nat_e adr \\&& var_e result \\= null ]b_s).\n\nmove: (compact_verif adr size sizex x H0 H) => H1.\nStep TT.\n- rewrite /while.entails => {H1} s h [x0 [H1 [H4 H2]]].\n  exists x0; by Resolve_topsy.\n- rewrite /while.entails => s h [x0 [H2 [H5 [H9 [H7 [H6 H4]]]]]].\n  exists x0; by Resolve_topsy.\n\nmove: (findFree_verif adr x sizex size H0 H) => H1.\n\n(**    findFree size entry fnd sz stts *)\n\nStep TT. (* apply hoare_conseq (?) *)\n- rewrite /while.entails => s h [x0 [H2 [H5 [H7 H3]]]].\n  exists x0; Resolve_topsy.\n  case : H3 => H4.\n  + case : H4 => x1 [x2 [H3 [H8 H4]]].\n    left; exists x1, x2; Resolve_topsy.\n    by omegab.\n  + by right.\n- done.\n\n(**  ) elsedo\n       skip *)\n\nStep TT.\nrewrite /while.entails; intros; tauto.\n\n(**  ifte (var_e entry \\= null) thendo ( *)\n\nStep TT.\n\n(**    result <- HM_ALLOCFAILED *)\n\nStep TT.\nmove=> s h H1.\nrewrite /wp_assign.\ncase : H1 => [[x0 [H2 [H5 [H3 H7]]]] H4].\ncase : H7 => H1.\n- case : H1 => x1 [x2 [H7 [H9 [H11 H8]]]].\n  suff : False by done. omegab.\n- right; exists x0; by Resolve_topsy.\n\n(**  ) elsedo (\n    split entry size cptr sz; *)\n\nStep (fun s h => exists l y, y > 0 /\\\n  [ var_e entry \\= nat_e y ]b_s /\\\n  exists size', size' >= size /\\\n    (Heap_List l adr ** Array (y + 2) size') s h /\\\n    In_hl l (x, sizex, alloc) adr /\\\n    In_hl l (y, size', alloc) adr /\\ x <> y).\n\nmove: (split_verif adr size sizex x H0 H) => H1.\n\nStep TT. (* apply hoare_conseq (?) *)\n- rewrite /while.entails => {H1} s h [x0 [H1 [x1 [H2 [H3 [x2 [H4 [H5 [H6 H7]]]]]]]]].\n  exists x0, x1; Resolve_topsy.\n  exists x2; by Resolve_topsy.\n- rewrite /while.entails => {H1} s h [[x0 [H2 [H5 [H7 H1]]]] H3].\n  case : H1 => H4.\n  + case: H4 => x1 [x2 [H8 [H9 H11]]].\n    exists x0; Resolve_topsy.\n    exists x1, x2; Resolve_topsy.\n    tauto.\n    omegab.\n    by apply (In_hl_dif _ _ _ _ _ _ H5 H9).\n  + by omegab.\n\n(**    result <- var_e entry \\+ nat_e 2\n     ). *)\n\nStep TT.\nrewrite /wp_assign => s h [x0 [x1 [H2 [H3 [x2 [H4 [H5 [H6 [H7 H8]]]]]]]]].\nleft; exists x0, x1; Resolve_topsy.\nexists x2; Resolve_topsy.\ncase_sepcon H5.\nCompose_sepcon h1 h2.\nby Resolve_topsy.\nby Array_equiv.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/seplog/topsy_hmAlloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export 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\n(* !! MOVE to lsubst_hyps *)\nLemma wf_hyps_proof_irrelevance {o} :\n  forall (hs : @barehypotheses o)\n         (p1 p2 : wf_hyps hs),\n    p1 = p2.\nProof.\n  introv.\n  allunfold @wf_hyps.\n  allunfold @wf_hyp.\n  apply functional_extensionality_dep; introv.\n  apply functional_extensionality_dep; introv.\n  apply wf_term_proof_irrelevance.\nQed.\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                   (wf_hyps_app_left H J (wf_sequent_2hyps (H ++ J) ||- (mk_concl C t) wg))\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                   (wf_hyps_app_right H J (wf_sequent_2hyps (H ++ J) ||- (mk_concl C t) wg))\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                   (wf_concl_ext_2typ C t (wf_sequent_2concl (H ++ J) ||- (mk_concl C t) wg))\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                   (wf_concl_ext_2ext C t (wf_sequent_2concl (H ++ J) ||- (mk_concl C t) wg))\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    remember (wf_hyps_app_left H J (wf_sequent_2hyps (H ++ J) ||- (mk_concl C t) wg)) as wH.\n    remember (wf_concl_ext_2typ C t (wf_sequent_2concl (H ++ J) ||- (mk_concl C t) wg)) as wC.\n    remember (wf_concl_ext_2ext C t (wf_sequent_2concl (H ++ J) ||- (mk_concl C t) wg)) as wt.\n\n    rw <- (replace_utokens_bhyps_eq H wH wH _ _ e1).\n    rw <- (replace_utokens_t_eq C wC wC _ _ e2).\n    rw <- (replace_utokens_t_eq t wt wt _ _ e3).\n\n    remember (wf_sequent_2hyps (H) ||- (mk_concl C t) wfs) as wH'.\n    remember (wf_concl_ext_2typ C t (wf_sequent_2concl (H) ||- (mk_concl C t) wfs)) as wC'.\n    remember (wf_concl_ext_2ext C t (wf_sequent_2concl (H) ||- (mk_concl C t) wfs)) as wt'.\n    allsimpl.\n\n    pose proof (wf_term_proof_irrelevance C wC wC') as e; rw e; clear e.\n    pose proof (wf_term_proof_irrelevance t wt wt') as e; rw e; clear e.\n    pose proof (wf_hyps_proof_irrelevance H wH wH') as e; rw e; clear e.\n\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\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\" \"../cequiv/\" \"../per/\" \"../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/rules/rules_atom_struct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.198468367499571}}
{"text": "Require Import Omega.\n\nRequire Import Coq.Classes.Morphisms.\nRequire Import Relation_Definitions.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\n\nRequire Import VST.concurrency.lib.setoid_help.\nRequire Import VST.concurrency.common.permissions. Import permissions.\nRequire Import VST.concurrency.common.Clight_bounds.\nRequire Import VST.concurrency.common.permissions.\n(* Require Import VST.concurrency.lib.Coqlib3. *)\n\nImport FunctionalExtensionality.\nImport Logic.\nImport Basics.\nImport BinInt.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n\n(** *Extension to rewrite library:*)\n(*    We add partially reflexive relations:\n    https://coq.inria.fr/refman/addendum/generalized-rewriting.html#rewriting-and-non-reflexive-relations\n *)\n\n\nClass PartReflexive {A:Type} (P: A -> Prop) R:=\n  { PReflex: forall x : A, P x -> R x x }.\nLemma part_reflexive_proper_proxy {A P} {R: relation A}\n      `(PartReflexive A P R) (x : A) : P x -> ProperProxy R x.\n  intros. eapply H; auto.\nQed.\n(* This ensures that when ProperProxy is ebing resolved,\n   partial reflexivity is considered\n *)\nHint Extern 3 (ProperProxy ?R _) => \nnot_evar R; class_apply @part_reflexive_proper_proxy;\n  try typeclasses eauto; eauto\n                         : typeclass_instances.\n\n\n(* We present two more relations that help take advantage of the above.*)\nInductive trieq {A : Type} (x : A) : A -> A -> Prop :=\n| triew_refl: trieq x x x.\nHint Resolve (triew_refl).\nInstance trieq_PartReflexive: forall A (x:A), PartReflexive (eq x) (trieq x).\nProof. constructor; intros; subst; constructor. Qed.\nGlobal Instance Symmetric_trieq:\n  forall {A} (x:A), Symmetric (trieq x).\nProof.\n  intros. intros ???H; inversion H; constructor. Qed.\nGlobal Instance Transitive_trieq:\n  forall {A} (x:A), Transitive (trieq x).\nProof.\n  intros. intros ??? H1 H2.\n  inversion H1; inversion H2. constructor.\nQed. \n\nDefinition eq_P {A : Type} (P:A -> Prop) (x y: A) : Prop := \n  (x = y) /\\ P x.\nInstance eq_P_PartReflexive: forall {A P}, PartReflexive P (@eq_P A P).\nProof. constructor; intros; subst; constructor; auto. Qed.\nGlobal Instance Symmetric_eq_P:\n  forall {A P}, Symmetric (@eq_P A P).\nProof.\n  intros. intros ???H; inversion H; subst; constructor; auto. Qed.\nGlobal Instance Transitive_eq_P:\n  forall {A P}, Transitive (@eq_P A P).\nProof.\n  intros. intros ??? H1 H2.\n  inversion H1; inversion H2; subst. constructor; auto.\nQed. \n\n(* End rewrite extension*)\n\n\n\n\nLtac rewrite_getPerm_goal:=\n  match goal with\n  | [|- context[(?f ?m) !! ?b ?ofs ?k] ] =>\n    replace ((f m) !! b ofs k) with (permission_at m b ofs k)\n      by reflexivity;\n    match k with\n    | Cur => rewrite <- getCurPerm_correct\n    | Max => rewrite <- getMaxPerm_correct\n    end\n  end.\nLtac rewrite_getPerm_hyp:=\n  match goal with\n  | [H: context[(?f ?m) !! ?b ?ofs ?k]|- _ ] =>\n    replace ((f m) !! b ofs k) with (permission_at m b ofs k) in H\n      by reflexivity;\n    match k with\n    | Cur => rewrite <- getCurPerm_correct in H\n    | Max => rewrite <- getMaxPerm_correct in H\n    end\n  end.\nLtac rewrite_getPerm := first [rewrite_getPerm_goal|rewrite_getPerm_hyp].\n\n\n\nDefinition access_map_equiv (a1 a2: access_map): Prop :=\n  forall b, a1 !! b =  a2 !! b.\nInstance access_map_equiv_Equivalence: Equivalence access_map_equiv.\nProof.\n  constructor; try constructor; intros ?; intros.\n  - unfold access_map_equiv in *; auto.\n  - unfold access_map_equiv in *; etransitivity; auto.\nQed.\n\n\nLtac destruct_address_range b ofs b0 ofs0 n:=\n  let Hrange:= fresh \"Hrange\" in\n  let Hneq:= fresh \"Hneq\" in\n  destruct (Coqlib.peq b b0) as [Hneq | Hneq];\n  [subst b0;\n   destruct (Intv.In_dec ofs0\n                         (ofs, ofs + BinInt.Z.of_nat(n))%Z )\n     as [Hrange | Hrange]\n  | ].\n\n\nInstance setPermBlock_access_map_equiv:\n  Proper (eq ==> eq ==> eq ==>\n             access_map_equiv ==> eq_P (lt 0) ==>  access_map_equiv)\n         (setPermBlock ).\nProof.\n  proper_intros; inversion H3; subst.\n  intros b; extensionality ofs.\n  destruct_address_range y0 y1 b ofs y3.\n  - unfold Intv.In in *; simpl in *.\n    repeat rewrite setPermBlock_same; auto.\n  - eapply Intv.range_notin in Hrange; simpl; try omega.\n    repeat rewrite setPermBlock_other_1; auto.\n    rewrite H2; auto.\n  - subst.\n    repeat rewrite setPermBlock_other_2; auto.\n    rewrite H2; auto.\nQed.\n\nDefinition Max_equiv (m1 m2: mem): Prop :=\n  access_map_equiv (getMaxPerm m1) (getMaxPerm m2).\n\nGlobal Instance Equivalenc_Max_equiv:\n  Equivalence Max_equiv.\nProof.\n  econstructor.\n  - intros??; reflexivity.\n  - intros ????. symmetry; auto.\n  - intros ??????. etransitivity; eauto.\nQed.\nDefinition Cur_equiv (m1 m2: mem): Prop :=\n  access_map_equiv (getCurPerm m1) (getCurPerm m2).\nGlobal Instance Equivalenc_Cur_equiv:\n  Equivalence Cur_equiv.\nProof.\n  econstructor.\n  - intros??; reflexivity.\n  - intros ????. symmetry; auto.\n  - intros ??????. etransitivity; eauto.\nQed.\n\nLemma restr_Max_equiv:\n  forall {p m}\n         (Hlt: permMapLt p (getMaxPerm m)),\n    Max_equiv (restrPermMap Hlt) m.\nProof. intros ????.\n       extensionality ofs.\n       rewrite getMaxPerm_correct.\n       apply restrPermMap_Max.\nQed.\n\nDefinition content_equiv (m1 m2: mem):=\n  forall b ofs,\n    ZMap.get ofs (Mem.mem_contents m1) !! b =\n    ZMap.get ofs (Mem.mem_contents m2) !! b.\nGlobal Instance Equivalenc_content_equiv:\n  Equivalence content_equiv.\nProof.\n  econstructor.\n  - intros??; reflexivity.\n  - intros ????. symmetry; auto.\n  - intros ??????. etransitivity; eauto.\nQed.\nLemma restr_content_equiv:\n  forall {p m} Hlt,\n    content_equiv (@restrPermMap p m Hlt) m.\nProof. intros ?????; reflexivity. Qed.\n\nRecord mem_equiv (m1 m2: mem): Prop :=\n  { cur_eqv:> Cur_equiv m1 m2;\n    max_eqv:> Max_equiv m1 m2;\n    content_eqv:>\n               content_equiv m1 m2 ;\n    nextblock_eqv:> Mem.nextblock m1 = Mem.nextblock m2 }.\n\nGlobal Instance Equivalence_mem_equiv:\n  Equivalence mem_equiv.\nProof.\n  econstructor.\n  - intros ?; econstructor; reflexivity.\n  - intros ?? H; inversion H; econstructor; symmetry; auto.\n  - intros ??? H1 H2. inversion H1; inversion H2.\n    econstructor; etransitivity; eauto.\nQed.\n\nInstance Proper_perm_max:\n  Proper (Max_equiv ==> eq ==> eq ==> (trieq Max) ==> eq ==> iff) Mem.perm.\nProof.\n  proper_iff; proper_intros; subst.\n  inversion H2; subst.\n  unfold Max_equiv in *.\n  unfold Mem.perm in *;\n    repeat rewrite_getPerm.\n  rewrite <- H; auto.\nQed.\nInstance Proper_perm_cur:\n  Proper (Cur_equiv ==> eq ==> eq ==> (trieq Cur) ==> eq ==> iff) Mem.perm.\nProof.\n  proper_iff; proper_intros; subst.\n  inversion H2; subst.\n  unfold Cur_equiv in *.\n  unfold Mem.perm in *;\n    repeat rewrite_getPerm.\n  - rewrite <- H; auto.\nQed.\n\nInstance Proper_perm:\n  Proper (mem_equiv ==> eq ==> eq ==> eq ==> eq ==> iff) Mem.perm.\nProof.\n  proper_iff; proper_intros; subst.\n  destruct y2; [rewrite <- (max_eqv _ _ H)| erewrite <- (cur_eqv _ _ H)];\n    assumption.\nQed.\nInstance Proper_perm_Max:\n  Proper (Max_equiv ==> eq ==> eq ==> trieq Max ==> eq ==> iff) Mem.perm.\nProof.\n  proper_iff; unfold Mem.perm; proper_intros; subst.\n  inversion H2; subst.\n  repeat rewrite_getPerm; auto. \n  rewrite <- H; assumption.\nQed.\n\nInstance range_perm_mem_equiv:\n  Proper (mem_equiv ==> eq ==>  eq ==>  eq ==>  eq ==>  eq ==> iff) Mem.range_perm.\nProof.\n  proper_iff; proper_intros; subst.\n  unfold Mem.range_perm in *; intros.\n  rewrite <- H. eapply H5; auto.\nQed.\nInstance range_perm_mem_equiv_Max:\n  Proper (Max_equiv ==> eq ==>  eq ==>  eq ==>  trieq Max  ==>  eq ==> iff) Mem.range_perm.\nProof.\n  proper_iff; proper_intros; subst.\n  inversion H3; subst.\n  unfold Mem.range_perm in *; intros.\n  rewrite <- H. eapply H5; auto.\nQed.\nInstance range_perm_mem_equiv_Cur:\n  Proper (Cur_equiv ==> eq ==>  eq ==>  eq ==>  trieq Cur  ==>  eq ==> iff) Mem.range_perm.\nProof.\n  proper_iff; proper_intros; subst.\n  inversion H3; subst.\n  unfold Mem.range_perm in *; intros.\n  rewrite <- H. eapply H5; auto.\nQed.\n\nInstance mem_inj_equiv:\n  Proper ( eq ==> mem_equiv ==> mem_equiv ==> iff) Mem.mem_inj.\nProof.\n  proper_iff. proper_intros; subst.\n  econstructor; intros.\n  - rewrite <- H1.\n    rewrite <- H0 in H3.\n    eapply H2; eauto.\n  - eapply H2; eauto.\n    rewrite H0; eauto.\n  - rewrite <- H0 in H3.\n    destruct H0; destruct H1.\n    unfold content_equiv in *.\n    rewrite <- content_eqv0.\n    rewrite <- content_eqv1.\n    eapply H2; eauto.\nQed.\n\nInstance Proper_nextblock:\n  Proper (mem_equiv ==> Logic.eq) Mem.nextblock.\nProof. intros ???. erewrite nextblock_eqv; auto. Qed.\n\nInstance Proper_valid_block:\n  Proper (mem_equiv ==> Logic.eq ==> Logic.eq) Mem.valid_block.\nProof.\n  intros ??????.\n  subst; unfold Mem.valid_block.\n  rewrite H; reflexivity.\nQed.\n\n\nInstance Proper_no_overlap_max_equiv:\n  Proper (Logic.eq ==> Max_equiv ==> iff)\n         Mem.meminj_no_overlap.\nProof.\n  unfold Mem.meminj_no_overlap.\n  proper_iff. proper_intros; subst.\n  eapply H1; unfold  Mem.perm in *; eauto.\n  - repeat rewrite_getPerm.\n    rewrite H0; auto.\n  - repeat rewrite_getPerm.\n    rewrite H0; auto.\nQed.\n\n\nInstance Proper_no_overlap_mem_equiv:\n  Proper (eq ==> mem_equiv ==> iff) Mem.meminj_no_overlap.\nProof.\n  proper_iff. proper_intros; subst.\n  eapply Proper_no_overlap_max_equiv; eauto.\n  symmetry; apply H0.\nQed.\n\nInstance mem_inject_equiv:\n  Proper  ( eq ==> mem_equiv ==> mem_equiv ==> iff) Mem.inject.\nProof.\n  proper_iff.\n  intros ?????  Heqv1 ?? Heqv2 Hinj; subst.\n  symmetry in Heqv1, Heqv2.\n  econstructor.\n  - rewrite Heqv1, Heqv2. eapply Hinj.\n  - intros ?.\n    rewrite Heqv1. eapply Hinj.\n  - intros ???.\n    rewrite Heqv2. eapply Hinj.\n  - rewrite Heqv1. apply Hinj.\n  - intros. eapply Hinj; eauto.\n    rewrite <- Heqv1; auto.\n  - intros ???????.\n    rewrite Heqv2, Heqv1.\n    apply Hinj; auto.\nQed.\n\nInstance permMapLt_equiv:\n  Proper (access_map_equiv ==> access_map_equiv ==> iff)\n         permMapLt.\nProof. proper_iff. intros ?????? HH ??; rewrite <- H, <- H0; auto. Qed.\n\nLemma getCur_restr:\n  forall perm m (Hlt: permMapLt perm (getMaxPerm m)),\n    access_map_equiv\n      (getCurPerm (restrPermMap Hlt))  perm.\nProof.\n  unfold getCurPerm, access_map_equiv.\n  intros; simpl.\n  rewrite PMap.gmap.\n  Import FunctionalExtensionality.\n  extensionality ofs; simpl.\n  unfold PMap.get; simpl.\n  rewrite PTree.gmap.\n  destruct ((snd (Mem.mem_access m)) ! b) eqn:HH.\n  - reflexivity.\n  - simpl.\n    specialize (Hlt b ofs).\n    rewrite getMaxPerm_correct in Hlt;\n      unfold permission_at in Hlt.\n    unfold PMap.get in Hlt.\n    rewrite HH in Hlt.\n    rewrite Clight_bounds.Mem_canonical_useful in Hlt.\n    simpl in Hlt.\n    destruct ( (snd perm) ! b).\n    + destruct (o ofs); first [contradiction | auto].\n    + destruct (fst perm ofs); first [contradiction | auto].\nQed.\nLemma getMax_restr:\n  forall perm m (Hlt: permMapLt perm (getMaxPerm m)),\n    access_map_equiv\n      (getMaxPerm (restrPermMap Hlt))  (getMaxPerm m) .\nProof. intros; intros ?; eapply getMax_restr. Qed.\n\n\nLemma restrPermMap_equiv:\n  forall perm1 perm2 m1 m2\n         Hlt1 Hlt2,\n    mem_equiv m1 m2 ->\n    access_map_equiv perm1 perm2 ->\n    mem_equiv (@restrPermMap perm1 m1 Hlt1)\n              (@restrPermMap perm2 m2 Hlt2).\nProof.\n  intros. inversion H.\n  econstructor.\n  - unfold Cur_equiv; do 2 rewrite getCur_restr; auto.\n  - unfold Max_equiv; intros ?.\n    do 2 rewrite getMax_restr; auto.\n  - simpl; eauto.\n  - simpl. auto.\nQed.\nLemma restrPermMap_idempotent:\n  forall perm0 perm1 m1 Hlt0 Hlt1 Hlt2, \n    mem_equiv (@restrPermMap perm1 m1 Hlt1)\n              (@restrPermMap perm1 (@restrPermMap perm0 m1 Hlt0) Hlt2).\nProof.\n  intros; econstructor.\n  - unfold Cur_equiv; do 2 rewrite getCur_restr; reflexivity.\n  - unfold Max_equiv; intros ?.\n    do 3 rewrite getMax_restr; auto.\n  - simpl; eauto.\n    etransitivity; try eapply restr_content_equiv.\n    etransitivity; try eapply (restr_content_equiv Hlt2).\n  - simpl; eapply nextblock_eqv; reflexivity.\nQed.\nArguments restrPermMap_idempotent {_ _ _} _ _.\n\nLemma useful_permMapLt_trans:\n  forall {perm m perm0} Hlt0,\n    permMapLt perm (getMaxPerm m) ->\n    permMapLt perm (getMaxPerm (@restrPermMap perm0 m Hlt0)).\n\nProof. unfold permMapLt; intros. rewrite getMax_restr; eauto. Qed.\n\nLemma restrPermMap_idempotent':\n  forall perm0 perm1 m1 Hlt0 Hlt1 , \n    mem_equiv (@restrPermMap perm1 m1 Hlt1)\n              (@restrPermMap perm1 (@restrPermMap perm0 m1 Hlt0)\n                             (useful_permMapLt_trans Hlt0 Hlt1)).\nProof. intros; eapply restrPermMap_idempotent. Qed.\n\nLemma restr_proof_irr_equiv:\n  forall m perm Hlt Hlt',\n    mem_equiv (@restrPermMap m perm Hlt) (@restrPermMap m perm Hlt').\n  intros. replace Hlt with Hlt'.\n  - reflexivity. \n  - apply Axioms.proof_irr.\nQed.\n\n\nInstance valid_access_Proper:\n  Proper (mem_equiv  ==> Logic.eq ==> Logic.eq  ==>\n                     Logic.eq ==> Logic.eq ==> iff) Mem.valid_access.\nProof.\n  unfold Mem.valid_access.\n  setoid_help.proper_iff; setoid_help.proper_intros; subst.\n  rewrite <- H; auto.\nQed.\nInstance load_Proper:\n  Proper (Logic.eq ==> mem_equiv ==> Logic.eq ==> Logic.eq  ==> Logic.eq) Mem.load.\nProof.\n  setoid_help.proper_intros; subst.\n  Transparent Mem.load.\n  unfold Mem.load.\n  destruct (Mem.valid_access_dec x0 y y1 y2 Readable) as [v|v];\n    rewrite H0 in v;\n    destruct (Mem.valid_access_dec y0 y y1 y2 Readable);\n    (* solve the impossible ones*)\n    try solve[contradict v; auto].\n  - destruct  H0. do 2 f_equal.\n    clear - content_eqv0 y1 y2.\n    revert y2 y1.\n    induction (size_chunk_nat y); auto; intros.\n    simpl.  f_equal; eauto.\n  - reflexivity.\nQed.\n\nInstance loadv_Proper:\n  Proper (Logic.eq ==> mem_equiv ==> Logic.eq  ==> Logic.eq) Mem.loadv.\nProof. intros ??? ??? ???; subst.\n       destruct y1; auto.\n       eapply load_Proper; auto.\nQed.\n\n\nLemma cur_equiv_restr_mem_equiv:\n  forall (m:mem) p\n    (Hlt: permMapLt p (getMaxPerm m)),\n    access_map_equiv p (getCurPerm m) ->\n    mem_equiv (restrPermMap Hlt) m.\nProof.\n  intros. constructor; eauto.\n  - unfold Cur_equiv. etransitivity; eauto.\n    eapply getCur_restr.\n  - eapply getMax_restr.\n  - eapply restr_content_equiv.\nQed.\nLemma mem_access_max_equiv:\n  forall m1 m2, Mem.mem_access m1 =  Mem.mem_access m2 ->\n           Max_equiv m1 m2.\nProof. intros ** ?; unfold getMaxPerm; simpl.\n       rewrite H; reflexivity.\nQed.\nLemma mem_access_cur_equiv:\n  forall m1 m2, Mem.mem_access m1 = Mem.mem_access m2 ->\n           Cur_equiv m1 m2.\nProof. intros ** ?; unfold getCurPerm; simpl.\n       rewrite H; reflexivity.\nQed.\n\nLemma Cur_equiv_restr:\n  forall p1 p2 m1 m2 Hlt1 Hlt2,\n    access_map_equiv p1 p2 ->\n    Cur_equiv (@restrPermMap p1 m1 Hlt1)\n              (@restrPermMap p2 m2 Hlt2).\nProof. unfold Cur_equiv; intros.\n       do 2 rewrite getCur_restr; assumption. Qed.\nLemma Max_equiv_restr:\n  forall p1 p2 m1 m2 Hlt1 Hlt2,\n    Max_equiv m1 m2 ->\n    Max_equiv (@restrPermMap p1 m1 Hlt1)\n              (@restrPermMap p2 m2 Hlt2).\nProof. unfold Max_equiv; intros.\n       do 2 rewrite getMax_restr; assumption. Qed.\n\nLemma store_max_eq:\n  forall cnk  m b ofs v m',\n    Mem.store cnk  m b ofs v = Some m' ->\n    getMaxPerm m = getMaxPerm m'.\nProof.\n  intros.\n  Transparent Mem.store.\n  unfold Mem.store in H; simpl in *.\n  destruct (Mem.valid_access_dec m cnk b ofs Writable); try discriminate.\n  inversion H. reflexivity.\nQed.\nLemma store_max_equiv:\n  forall sz m b ofs v m',\n    Mem.store sz m b ofs v = Some m' ->\n    Max_equiv m m'.\nProof.\n  intros. intros ?.\n  erewrite store_max_eq; eauto.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/compiler/mem_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.19846836749957097}}
{"text": "(* In this file we introduce a reentrancy problem in the Congress\ncontract described in Congress.v. We then use one of our blockchain\nimplementations (the depth first local blockchain) to prove that this\nversion can send out too many transactions. This is done by\nconstructing a contract that actually exploits this version of the\nCongress and then just asking Coq to compute. *)\n\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Psatz.\nFrom Coq Require Import List.\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.\nFrom ConCert.Execution.Test Require LocalBlockchain.\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Utils Require Import RecordUpdate.\n\nImport ListNotations.\n\n\nSection CongressBuggy.\n  Context {BaseTypes : ChainBase}.\n\n  Local Open Scope Z.\n  Set Primitive Projections.\n  Set Nonrecursive Elimination Schemes.\n\n  Definition ProposalId := nat.\n\n  Inductive CongressAction :=\n  | cact_transfer (to : Address) (amount : Amount)\n  | cact_call (to : Address) (amount : Amount) (msg : SerializedValue).\n\n  Record Proposal :=\n    build_proposal {\n      actions : list CongressAction;\n      votes : FMap Address Z;\n      vote_result : Z;\n      proposed_in : nat;\n    }.\n\n  MetaCoq Run (make_setters Proposal).\n\n  Record Rules :=\n    build_rules {\n      min_vote_count_permille : Z;\n      margin_needed_permille : Z;\n      debating_period_in_blocks : nat;\n    }.\n\n  Record Setup :=\n    build_setup {\n      setup_rules : Rules;\n    }.\n\n  Definition Error : Type := nat.\n  Definition default_error : Error := 1%nat.\n\n  Inductive Msg :=\n  | transfer_ownership : Address -> Msg\n  | change_rules : Rules -> Msg\n  | add_member : Address -> Msg\n  | remove_member : Address -> Msg\n  | create_proposal : list CongressAction -> Msg\n  | vote_for_proposal : ProposalId -> Msg\n  | vote_against_proposal : ProposalId -> Msg\n  | retract_vote : ProposalId -> Msg\n  | finish_proposal : ProposalId -> Msg\n  | finish_proposal_remove : ProposalId -> Msg.\n\n  Record State :=\n    build_state {\n      owner : Address;\n      state_rules : Rules;\n      proposals : FMap nat Proposal;\n      next_proposal_id : ProposalId;\n      members : FMap Address unit;\n    }.\n\n  (* begin hide *)\n  MetaCoq Run (make_setters State).\n  (* end hide *)\n\n  Section Serialization.\n\n    Global Instance rules_serializable : Serializable Rules :=\n      Derive Serializable Rules_rect <build_rules>.\n\n    Global Instance setup_serializable : Serializable Setup :=\n      Derive Serializable Setup_rect <build_setup>.\n\n    Global Instance congress_action_serializable : Serializable CongressAction :=\n      Derive Serializable CongressAction_rect <cact_transfer, cact_call>.\n\n    Global Instance proposal_serializable : Serializable Proposal :=\n      Derive Serializable Proposal_rect <build_proposal>.\n\n    Global Instance msg_serializable : Serializable Msg :=\n      Derive Serializable Msg_rect <transfer_ownership, change_rules, add_member, remove_member,\n                                    create_proposal, vote_for_proposal, vote_against_proposal,\n                                    retract_vote, finish_proposal, finish_proposal_remove>.\n\n    Global Instance state_serializable : Serializable State :=\n      Derive Serializable State_rect <build_state>.\n\n  End Serialization.\n\n  Definition validate_rules (rules : Rules) : bool :=\n    (rules.(min_vote_count_permille) >=? 0)\n    && (rules.(min_vote_count_permille) <=? 1000)\n    && (rules.(margin_needed_permille) >=? 0)\n    && (rules.(margin_needed_permille) <=? 1000)\n    && (0 <=? rules.(debating_period_in_blocks))%nat.\n\n  Definition init (chain : Chain)\n                  (ctx : ContractCallContext)\n                  (setup : Setup)\n                  : result State Error :=\n    if validate_rules setup.(setup_rules) then\n      Ok {|\n        owner := ctx.(ctx_from);\n        state_rules := setup.(setup_rules);\n        proposals := FMap.empty;\n        next_proposal_id := 1%nat;\n        members := FMap.empty\n      |}\n    else\n      Err default_error.\n\n  Definition add_proposal (actions : list CongressAction)\n                          (chain : Chain)\n                          (state : State)\n                          : State :=\n    let id := state.(next_proposal_id) in\n    let slot_num := chain.(current_slot) in\n    let proposal := {| actions := actions;\n                      votes := FMap.empty;\n                      vote_result := 0;\n                      proposed_in := slot_num |} in\n    state<|proposals ::= FMap.add id proposal|>\n        <|next_proposal_id ::= S|>.\n\n  Definition vote_on_proposal (voter : Address)\n                              (pid : ProposalId)\n                              (vote : Z)\n                              (state : State)\n                              : result State Error :=\n    do proposal <- result_of_option (FMap.find pid state.(proposals)) default_error;\n    let old_vote := match FMap.find voter proposal.(votes) with\n                  | Some old => old\n                  | None => 0\n                  end in\n    let new_votes := FMap.add voter vote proposal.(votes) in\n    let new_vote_result := proposal.(vote_result) - old_vote + vote in\n    let new_proposal :=\n        proposal<|votes := new_votes|>\n                <|vote_result := new_vote_result|> in\n    Ok (state<|proposals ::= FMap.add pid new_proposal|>).\n\n  Definition do_retract_vote (voter : Address)\n                             (pid : ProposalId)\n                             (state : State)\n                             : result State Error :=\n    do proposal <- result_of_option (FMap.find pid state.(proposals)) default_error;\n    do old_vote <- result_of_option (FMap.find voter proposal.(votes)) default_error;\n    let new_votes := FMap.remove voter proposal.(votes) in\n    let new_vote_result := proposal.(vote_result) - old_vote in\n    let new_proposal :=\n        proposal<|votes := new_votes|>\n                <|vote_result := new_vote_result|> in\n    Ok (state<|proposals ::= FMap.add pid new_proposal|>).\n\n  Definition congress_action_to_chain_action (act : CongressAction) : ActionBody :=\n    match act with\n    | cact_transfer to amt => act_transfer to amt\n    | cact_call to amt msg => act_call to amt msg\n    end.\n\n  Definition proposal_passed (proposal : Proposal)\n                             (state : State)\n                             : bool :=\n    let rules := state.(state_rules) in\n    let total_votes_for_proposal := Z.of_nat (FMap.size proposal.(votes)) in\n    let total_members := Z.of_nat (FMap.size state.(members)) in\n    let aye_votes := (proposal.(vote_result) + total_votes_for_proposal) / 2 in\n    let vote_count_permille := total_votes_for_proposal * 1000 / total_members in\n    let aye_permille := aye_votes * 1000 / total_votes_for_proposal in\n    let enough_voters := vote_count_permille >=? rules.(min_vote_count_permille) in\n    let enough_ayes := aye_permille >=? rules.(margin_needed_permille) in\n    enough_voters && enough_ayes.\n\n  Definition do_finish_proposal (ctx : ContractCallContext)\n                                (pid : ProposalId)\n                                (state : State)\n                                (chain : Chain)\n                                : result (State * list ActionBody) Error :=\n    do proposal <- result_of_option (FMap.find pid state.(proposals)) default_error;\n    let rules := state.(state_rules) in\n    let debate_end := (proposal.(proposed_in) + rules.(debating_period_in_blocks))%nat in\n    let cur_slot := chain.(current_slot) in\n    if (cur_slot <? debate_end)%nat then\n      Err default_error\n    else\n      let response_acts :=\n          if proposal_passed proposal state\n          then proposal.(actions)\n          else [] in\n      let response_chain_acts := map congress_action_to_chain_action response_acts in\n      let self_call_msg := serialize (finish_proposal_remove pid) in\n      let self_call := act_call (ctx_contract_address ctx) 0 self_call_msg in\n        Ok (state, response_chain_acts ++ [self_call]).\n\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 is_from_owner := (sender =? state.(owner))%address in\n    let is_from_member := FMap.mem sender state.(members) in\n    match maybe_msg, is_from_owner, is_from_member with\n    | Some (transfer_ownership new_owner), true, _ =>\n      Ok (state<|owner := new_owner|>, [])\n\n    | Some (change_rules new_rules), true, _ =>\n      if validate_rules new_rules then\n        Ok (state<|state_rules := new_rules|>, [])\n      else\n        Err default_error\n\n    | Some (add_member new_member), true, _ =>\n      Ok (state<|members ::= FMap.add new_member tt|>, [])\n\n    | Some (remove_member old_member), true, _ =>\n      Ok (state<|members ::= FMap.remove old_member|>, [])\n\n    | Some (create_proposal actions), _, true =>\n      Ok (add_proposal actions chain state, [])\n\n    | Some (vote_for_proposal pid), _, true =>\n      without_actions (vote_on_proposal sender pid 1 state)\n\n    | Some (vote_against_proposal pid), _, true =>\n      without_actions (vote_on_proposal sender pid (-1) state)\n\n    | Some (retract_vote pid), _, true =>\n      without_actions (do_retract_vote sender pid state)\n\n    | Some (finish_proposal pid), _, _ =>\n      do_finish_proposal ctx pid state chain\n\n    | Some (finish_proposal_remove pid), _, _ =>\n      if (sender =? ctx_contract_address ctx)%address then\n        Ok (state<|proposals ::= FMap.remove pid|>, [])\n      else\n        Err default_error\n\n    | _, _, _ =>\n          Err default_error\n    end.\n\n  Definition contract : Contract Setup Msg State Error :=\n    build_contract init receive.\n\nEnd CongressBuggy.\n(* We will show that this contract is buggy and does not satisfy the\n   property we proved for the other version of the Congress. We do\n   this with a counterexample, where we exploit reentrancy similar to\n   the DAO hack. We first define a contract that does this\n   exploitation. *)\n\nSection ExploitContract.\n  Context {Base : ChainBase}.\n\n  Definition ExploitSetup := unit.\n  Definition ExploitState := nat. (* how many times have we called ourselves *)\n  Definition ExploitMsg := unit.\n  Definition ExploitError := nat.\n  Definition exploit_init (chain : Chain)\n                          (ctx : ContractCallContext)\n                          (setup : ExploitSetup)\n                          : result ExploitState ExploitError :=\n    Ok 0.\n\n  Definition exploit_receive\n              (chain : Chain)\n              (ctx : ContractCallContext)\n              (state : ExploitState)\n              (msg : option ExploitMsg)\n              : result (ExploitState * list ActionBody) ExploitError :=\n    if 25 <? state then\n      Ok (state, [])\n    else\n      let again := finish_proposal 1 in\n      Ok (S state, [act_call (ctx_from ctx) 0 (serialize again)]).\n\n  Definition exploit_contract : Contract ExploitSetup ExploitMsg ExploitState ExploitError :=\n    build_contract exploit_init exploit_receive.\n\nEnd ExploitContract.\n\n(* With this defined we can give the counterexample with relative ease. We use a\nconcrete implementation of a blockchain for this. *)\nSection Theories.\n  Import LocalBlockchain.\n\n  Let AddrSize := (2^128)%N.\n  Instance Base : ChainBase := LocalChainBase AddrSize.\n  Instance Builder : ChainBuilderType := LocalChainBuilderImpl AddrSize true.\n\n  Open Scope nat.\n  Definition exploit_example : option (Address * Builder) :=\n    let chain := builder_initial in\n    let creator := BoundedN.of_Z_const AddrSize 10 in\n    let add_block (chain : Builder) act_bodies :=\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        let acts := map (build_act creator creator) act_bodies in\n        option_of_result (builder_add_block chain next_header acts) in\n    (* Get some money on the creator *)\n    do chain <- add_block chain [];\n    (* Deploy congress and exploit contracts *)\n    let rules :=\n        {| min_vote_count_permille := 200;\n           margin_needed_permille := 501;\n           debating_period_in_blocks := 0; |} in\n    let dep_congress := create_deployment 50 contract {| setup_rules := rules |} in\n    let dep_exploit := create_deployment 0 exploit_contract tt in\n    do chain <- add_block chain [dep_congress; dep_exploit];\n    let contracts := map fst (FMap.elements (lc_contracts (lcb_lc chain))) in\n    let exploit := nth 0 contracts creator in\n    let congress := nth 1 contracts creator in\n    (* Add creator to congress, create a proposal to transfer *)\n    (* some money to exploit contract, vote for the proposal, and execute the proposal *)\n    let add_creator := add_member creator in\n    let create_proposal := create_proposal [cact_transfer exploit 1] in\n    let vote_proposal := vote_for_proposal 1 in\n    let exec_proposal := finish_proposal 1 in\n    let act_bodies :=\n        map (fun m => act_call congress 0 (serialize m))\n            [add_creator; create_proposal; vote_proposal; exec_proposal] in\n    do chain <- add_block chain act_bodies;\n    Some (congress, chain).\n\n  Definition unpacked_exploit_example : Address * Builder :=\n    unpack_option exploit_example.\n\n  Definition num_acts_created_in_proposals (calls : list (ContractCallInfo Msg)) :=\n    let count call :=\n        match call_msg call with\n        | Some (create_proposal acts) => length acts\n        | _ => 0\n        end in\n    sumnat count calls.\n\n  (* Now we prove that this version of the contract is buggy, i.e. it does not satisfy the\n     property we proved for the other version of the Congress. We filter out transactions\n     from the congress to the congress as we have those now (due to self calls). *)\n  Theorem congress_buggy :\n    exists bstate caddr (trace : ChainTrace empty_state bstate)\n           (inc_calls : list (ContractCallInfo Msg)),\n      env_contracts bstate caddr = Some (contract : WeakContract) /\\\n      incoming_calls Msg trace caddr = Some inc_calls /\\\n      length (filter (fun tx => negb (tx_to tx =? caddr)%address)\n                     (outgoing_txs trace caddr)) >\n      num_acts_created_in_proposals inc_calls.\n  Proof.\n    exists (build_chain_state (snd unpacked_exploit_example) []).\n    exists (fst unpacked_exploit_example).\n    exists (builder_trace (snd unpacked_exploit_example)).\n    set (inc_calls := unpack_option\n                        (incoming_calls Msg\n                                        (builder_trace (snd unpacked_exploit_example))\n                                        (fst unpacked_exploit_example))).\n    vm_compute in inc_calls.\n    exists inc_calls.\n    split; [|split].\n    - reflexivity.\n    - reflexivity.\n    - vm_compute.\n      clear inc_calls.\n      lia.\n  Qed.\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/congress/Congress_Buggy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.1984491126531188}}
{"text": "Require Import compcert.common.Memory.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values. (*for val*)\nRequire Import concurrency.permissions.\nRequire Import Coq.ZArith.ZArith.\nRequire Import compcert.lib.Coqlib.\n\n(** ** Various results about CompCert's memory model*)\nModule MemoryLemmas.\n\n  Global Notation \"a # b\" := (Maps.PMap.get b a) (at level 1).\n  Transparent Mem.store.\n  (*TODO: see if we can reuse that for gsoMem_obs_eq.*)\n  (*TODO: maybe we don't need to open up the interface here*)\n  Lemma store_contents_other:\n    forall m m' b b' ofs ofs' v chunk\n      (Hstore: Mem.store chunk m b ofs v = Some m')\n      (Hstable: ~ Mem.perm m b' ofs' Cur Writable),\n      Maps.ZMap.get ofs' (Mem.mem_contents m') # b' =\n      Maps.ZMap.get ofs' (Mem.mem_contents m) # b'.\n  Proof.\n    intros.\n    erewrite Mem.store_mem_contents; eauto.\n    simpl.\n    destruct (Pos.eq_dec b b') as [Heq | Hneq];\n      [| by erewrite Maps.PMap.gso by auto].\n    subst b'.\n    rewrite Maps.PMap.gss.\n    destruct (Z_lt_le_dec ofs' ofs) as [Hlt | Hge].\n    erewrite Mem.setN_outside by (left; auto);\n      by reflexivity.\n    destruct (Z_lt_ge_dec\n                ofs' (ofs + (size_chunk chunk)))\n      as [Hlt | Hge'].\n    (* case the two addresses coincide - contradiction*)\n    apply Mem.store_valid_access_3 in Hstore.\n    unfold Mem.valid_access in Hstore. simpl in Hstore.\n    destruct Hstore as [Hcontra _].\n    unfold Mem.range_perm in Hcontra.\n    specialize (Hcontra ofs' (conj Hge Hlt));\n      by exfalso.\n    erewrite Mem.setN_outside by (right; rewrite size_chunk_conv in Hge';\n                                    by rewrite encode_val_length);\n      by auto.\n  Qed.\n\n  Transparent Mem.alloc.\n\n  Lemma val_at_alloc_1:\n    forall m m' sz nb b ofs\n      (Halloc: Mem.alloc m 0 sz = (m', nb))\n      (Hvalid: Mem.valid_block m b),\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m)) =\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m')).\n  Proof.\n    intros.\n    unfold Mem.alloc in Halloc.\n    inv Halloc.\n    simpl.\n    rewrite Maps.PMap.gso; auto.\n    intro; subst. unfold Mem.valid_block in *.\n    eapply Plt_strict; eauto.\n  Qed.\n\n  Lemma val_at_alloc_2:\n    forall m m' sz nb ofs\n      (Halloc: Mem.alloc m 0 sz = (m', nb)),\n      Maps.ZMap.get ofs (Maps.PMap.get nb (Mem.mem_contents m')) = Undef.\n  Proof.\n    intros.\n    unfold Mem.alloc in Halloc.\n    inv Halloc.\n    simpl.\n    rewrite PMap.gss, ZMap.gi.\n    reflexivity.\n  Qed.\n\n  (*stronger version of val_at_alloc_1*)\n  Lemma val_at_alloc_3:\n    forall m m' sz nb b ofs\n      (Halloc: Mem.alloc m 0 sz = (m', nb))\n      (Hvalid: b <> nb),\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m)) =\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m')).\n  Proof.\n    intros.\n    unfold Mem.alloc in Halloc.\n    inv Halloc.\n    simpl.\n    rewrite Maps.PMap.gso; auto.\n  Qed.\n\n  Lemma permission_at_alloc_1:\n    forall m m' lo hi nb b ofs\n      (Halloc: Mem.alloc m lo hi = (m', nb))\n      (Hvalid: Mem.valid_block m b),\n    forall k, permissions.permission_at m b ofs k =\n         permissions.permission_at m' b ofs k.\n  Proof.\n    intros.\n    unfold Mem.alloc in Halloc.\n    inv Halloc.\n    unfold permissions.permission_at. simpl.\n    rewrite Maps.PMap.gso; auto.\n    intro; subst. unfold Mem.valid_block in *.\n    eapply Plt_strict; eauto.\n  Qed.\n\n  Lemma permission_at_alloc_2:\n    forall m m' lo sz nb ofs\n      (Halloc: Mem.alloc m lo sz = (m', nb))\n      (Hofs: (lo <= ofs < sz)%Z),\n      forall k, permissions.permission_at m' nb ofs k = Some Freeable.\n  Proof.\n    intros.\n    eapply Memory.alloc_access_same in Halloc; eauto.\n  Qed.\n\n  Lemma permission_at_alloc_3:\n    forall m m' lo sz nb ofs\n      (Halloc: Mem.alloc m lo sz = (m', nb))\n      (Hofs: (ofs < lo \\/ ofs >= sz)%Z),\n      forall k, permissions.permission_at m' nb ofs k = None.\n  Proof.\n    intros.\n    pose proof (Mem.fresh_block_alloc _ _ _ _ _ Halloc) as Hinvalid.\n    apply Mem.nextblock_noaccess with (ofs := ofs) (k := k) in Hinvalid.\n    unfold permission_at.\n    eapply Memory.alloc_access_other with (b' := nb) (k := k) in Halloc;\n      unfold Memory.access_at, permission_at in *; simpl in *; eauto.\n    rewrite <- Halloc;\n      now auto.\n  Qed.\n\n  Lemma permission_at_alloc_4:\n    forall m m' lo hi nb b ofs\n      (Halloc: Mem.alloc m lo hi = (m', nb))\n      (Hb: b <> nb),\n    forall k, permissions.permission_at m b ofs k =\n         permissions.permission_at m' b ofs k.\n  Proof.\n    intros.\n    unfold Mem.alloc in Halloc.\n    inv Halloc.\n    unfold permissions.permission_at. simpl.\n    rewrite Maps.PMap.gso; auto.\n  Qed.\n\n  Lemma permission_at_free_1 :\n    forall m m' (lo hi : Z) b b' ofs'\n      (Hfree: Mem.free m b lo hi = Some m')\n      (Hnon_freeable: ~ Mem.perm m b' ofs' Cur Freeable),\n    forall k : perm_kind,\n      permission_at m b' ofs' k = permission_at m' b' ofs' k.\n  Proof.\n    intros.\n    pose proof (Mem.free_result _ _ _ _ _ Hfree) as Hfree'.\n    subst.\n    unfold Mem.unchecked_free. unfold permission_at. simpl.\n    destruct (Pos.eq_dec b' b); subst.\n    - destruct (zle lo ofs' && zlt ofs' hi) eqn:Hintv.\n      + exfalso.\n        apply andb_true_iff in Hintv.\n        destruct Hintv as [Hle Hlt].\n        destruct (zle lo ofs'); simpl in *; auto.\n        destruct (zlt ofs' hi); simpl in *; auto.\n        apply Mem.free_range_perm in Hfree.\n        unfold Mem.range_perm in Hfree.\n        specialize (Hfree ofs' (conj l l0)).\n        auto.\n      + rewrite Maps.PMap.gss.\n        rewrite Hintv.\n        reflexivity.\n    - rewrite Maps.PMap.gso;\n      auto.\n  Qed.\n\n  Lemma permission_at_free_2 :\n    forall m m' (lo hi : Z) b b' ofs'\n      (Hfree: Mem.free m b lo hi = Some m')\n      (Hb: b <> b'),\n    forall k : perm_kind,\n      permission_at m b' ofs' k = permission_at m' b' ofs' k.\n  Proof.\n    intros.\n    pose proof (Mem.free_result _ _ _ _ _ Hfree) as Hfree'.\n    subst.\n    unfold Mem.unchecked_free. unfold permission_at. simpl.\n    destruct (Pos.eq_dec b' b); subst.\n    - exfalso; now auto.\n    - rewrite Maps.PMap.gso;\n        auto.\n  Qed.\n\n  Lemma permission_at_free_list_1:\n    forall m m' l b ofs\n      (Hfree: Mem.free_list m l = Some m')\n      (Hnon_freeable: ~ Mem.perm m b ofs Cur Freeable),\n    forall k : perm_kind,\n      permission_at m b ofs k = permission_at m' b ofs k.\n  Proof.\n    intros m m' l.\n    generalize dependent m.\n    induction l; intros.\n    - simpl in Hfree; inv Hfree; reflexivity.\n    - simpl in Hfree. destruct a, p.\n      destruct (Mem.free m b0 z0 z) eqn:Hfree'; try discriminate.\n      pose proof Hfree' as Hfree''.\n      eapply permission_at_free_1 with (k := k) in Hfree'; eauto.\n      eapply permission_at_free_1 with (k := Cur) in Hfree''; eauto.\n      rewrite Hfree'. eapply IHl; eauto.\n      unfold Mem.perm in *. unfold permission_at in *.\n      rewrite <- Hfree''. assumption.\n  Qed.\n\n  Lemma mem_free_contents:\n    forall m m2 sz b\n      (Hfree: Mem.free m b 0 sz = Some m2),\n    forall b' ofs,\n      Maps.ZMap.get ofs (Maps.PMap.get b' (Mem.mem_contents m)) =\n      Maps.ZMap.get ofs (Maps.PMap.get b' (Mem.mem_contents m2)).\n  Proof.\n    intros.\n    apply Mem.free_result in Hfree.\n    subst; unfold Mem.unchecked_free.\n    reflexivity.\n  Qed.\n\n  Lemma mem_store_max:\n    forall chunk b ofs v m m',\n      Mem.store chunk m b ofs v = Some m' ->\n      forall b' ofs',\n        (getMaxPerm m) # b' ofs' = (getMaxPerm m') # b' ofs'.\n  Proof.\n    intros.\n    unfold Mem.store in *.\n    destruct (Mem.valid_access_dec m chunk b ofs Writable); try discriminate.\n    inversion H; subst.\n    do 2 rewrite getMaxPerm_correct.\n    reflexivity.\n  Qed.\n\n  Lemma mem_storebytes_cur :\n    forall b (ofs : Z) bytes (m m' : mem),\n      Mem.storebytes m b ofs bytes = Some m' ->\n      forall (b' : positive) (ofs' : Z),\n        (getCurPerm m) !! b' ofs' = (getCurPerm m') !! b' ofs'.\n  Proof.\n    intros.\n    Transparent Mem.storebytes.\n    unfold Mem.storebytes in *.\n    destruct (Mem.range_perm_dec m b ofs (ofs + Z.of_nat (length bytes)) Cur\n                                 Writable); try discriminate.\n    inversion H; subst.\n    do 2 rewrite getCurPerm_correct.\n    reflexivity.\n  Qed.\n\n  Lemma mem_store_cur:\n    forall chunk b ofs v m m',\n      Mem.store chunk m b ofs v = Some m' ->\n      forall b' ofs',\n        (getCurPerm m) # b' ofs' = (getCurPerm m') # b' ofs'.\n  Proof.\n    intros.\n    apply Mem.store_storebytes in H.\n    eapply mem_storebytes_cur; eauto.\n  Qed.\n\n  Lemma mem_storev_store:\n    forall chunk ptr v m m',\n      Mem.storev chunk m ptr v = Some m' ->\n      exists b ofs, ptr = Vptr b ofs /\\\n               Mem.store chunk m b (Integers.Int.intval ofs) v = Some m'.\n  Proof.\n    intros.\n    destruct ptr; try discriminate.\n    simpl in H.\n    do 2 eexists; split; eauto.\n  Qed.\n\n  Lemma load_valid_block:\n    forall (m : mem) b ofs chunk v,\n      Mem.load chunk m b ofs = Some v ->\n      Mem.valid_block m b.\n  Proof.\n    intros m b ofs chunk v Hload.\n    apply Mem.load_valid_access in Hload.\n    apply Mem.valid_access_valid_block with (chunk:=chunk) (ofs:= ofs).\n    eapply Mem.valid_access_implies; eauto.\n    constructor.\n  Qed.\n\n  Definition max_inv mf := forall b ofs, Mem.valid_block mf b ->\n                                    permission_at mf b ofs Max = Some Freeable.\n\n  Lemma max_inv_store:\n    forall m m' chunk b ofs v pmap\n      (Hlt: permMapLt pmap (getMaxPerm m))\n      (Hmax: max_inv m)\n      (Hstore: Mem.store chunk (restrPermMap Hlt) b ofs v = Some m'),\n      max_inv m'.\n  Proof.\n    intros.\n    intros b0 ofs0 Hvalid0.\n    unfold permission_at.\n    erewrite Mem.store_access; eauto.\n    assert (H := restrPermMap_Max Hlt b0 ofs0).\n    eapply Mem.store_valid_block_2 in Hvalid0; eauto.\n    erewrite restrPermMap_valid in Hvalid0.\n    specialize (Hmax b0 ofs0 Hvalid0).\n    unfold permission_at in H.\n    rewrite H.\n    rewrite getMaxPerm_correct;\n      by assumption.\n  Qed.\n\n   Lemma sim_valid_access:\n    forall (mf m1f : mem)\n      (b1 b2 : block) (ofs : Z)\n      (Hm1f: m1f = makeCurMax mf)\n      (HmaxF: max_inv mf)\n      (Hvalidb2: Mem.valid_block mf b2)\n      (Halign: (4 | ofs)%Z),\n      Mem.valid_access m1f Mint32 b2 ofs Freeable.\n  Proof.\n    unfold Mem.valid_access. simpl. split; try assumption.\n    unfold Mem.range_perm. intros ofs0 Hbounds. subst m1f.\n    specialize (HmaxF _ ofs0 Hvalidb2).\n    unfold Mem.perm.\n    assert (Hperm := makeCurMax_correct mf b2 ofs0 Cur).\n    rewrite HmaxF in Hperm.\n    unfold permission_at in Hperm.\n    unfold Mem.perm.\n    rewrite <- Hperm.\n    simpl;\n      by constructor.\n  Qed.\n\n  Lemma setPermBlock_lt:\n    forall pmap m b ofs sz p\n      (Hinv: max_inv m)\n      (Hvalid: Mem.valid_block m b)\n      (Hlt: permMapLt pmap (getMaxPerm m)),\n      permMapLt (setPermBlock p b ofs pmap sz) (getMaxPerm m).\n  Proof.\n    intros.\n    intros b' ofs'.\n    specialize (Hlt b' ofs').\n    destruct (Pos.eq_dec b b').\n    - subst.\n      destruct (Intv.In_dec ofs' (ofs, ofs + Z.of_nat sz)%Z).\n      + erewrite setPermBlock_same by eauto.\n        specialize (Hinv _ ofs' Hvalid).\n        erewrite getMaxPerm_correct in *.\n        erewrite Hinv in *.\n        simpl; destruct p; eauto using perm_order.\n      + destruct sz. simpl.\n        assumption.\n        erewrite setPermBlock_other_1.\n        assumption.\n        eapply Intv.range_notin in n; eauto.\n        simpl. zify; omega.\n    - erewrite setPermBlock_other_2 by eauto.\n      assumption.\n  Qed.\n\n  Lemma setN_inside: forall (vl : list memval) (c : ZMap.t memval) (ofs0 ofs: Z),\n      Intv.In ofs0 (ofs, (ofs + Z.of_nat (length vl))%Z) ->\n      ZMap.get ofs0 (Mem.setN vl ofs c) = List.nth (Z.to_nat (ofs0 - ofs)%Z) vl Undef.\n  Proof.\n    intros vl.\n    induction vl using rev_ind; intros.\n    - unfold Intv.In in H.\n      simpl in H. exfalso.\n      now omega.\n    - simpl in *.\n      unfold Intv.In in H. simpl in H.\n      rewrite Mem.setN_concat.\n      simpl.\n      rewrite ZMap.gsspec.\n      destruct (ZIndexed.eq ofs0 (ofs + Z.of_nat (length vl))). subst.\n      + assert ((Z.to_nat (ofs + Z.of_nat (length vl) - ofs)) = length vl)\n          by (rewrite <- Z.add_sub_assoc;\n              rewrite Zplus_minus, Nat2Z.id; reflexivity).\n        rewrite H0.\n        rewrite List.app_nth2.\n        rewrite NPeano.Nat.sub_diag. reflexivity.\n        omega.\n      + rewrite List.app_length in H.\n        simpl in H.\n        rewrite NPeano.Nat.add_1_r in H.\n        simpl in H.\n        rewrite Zpos_P_of_succ_nat in H.\n        apply threads_lemmas.lt_succ_neq in H; eauto.\n        rewrite List.app_nth1.\n        eapply IHvl. auto.\n        destruct H.\n        clear - H0 H.\n        zify.\n        erewrite Z2Nat.id in * by omega.\n        omega.\n  Qed.\n\nEnd MemoryLemmas.", "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/memory_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.19844911265311876}}
{"text": "Require Import Bedrock.Platform.AutoSep Bedrock.Platform.Malloc Bedrock.Platform.tests.Abort Bedrock.Platform.Bootstrap.\n\n\nModule Type S.\n  Parameter heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [Abort.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Goto \"test\"!\"main\"\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link Abort.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link Abort.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "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/AbortDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.19844910888556297}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.spec_salsa.\nRequire Import sha.general_lemmas.\nRequire Import tweetnacl20140427.tweetNaclBase.\n\n(*from verif_ld_st*)\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 vn_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_vn vn_spec.\nProof.\nstart_function.\nforward.\nassert_PROP (n = Zlength (map Vint (map Int.repr (map Byte.unsigned xcont))) /\\ \n             n = Zlength (map Vint (map Int.repr (map Byte.unsigned ycont)))) as LEN by entailer!.\ndestruct LEN as [LenX LenY].\nassert (ZWS: Int.zwordsize = 32) by reflexivity. \nassert (BWS: Byte.zwordsize = 8) by reflexivity. \nforward_for_simple_bound n\n(EX i:Z, EX d:_,\n  (PROP  (Byte.eq d Byte.zero = if list_eq_dec Byte.eq_dec (sublist 0 i xcont) (sublist 0 i ycont) then true else false)\n   LOCAL (temp _d (Vint (Int.repr (Byte.unsigned d)));\n          temp _x x; temp _y y; temp _n (Vint (Int.repr n)))\n   SEP (data_at xsh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n   data_at ysh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y))).\n{ Exists Byte.zero. entailer!.  }\n{ Intros. rename H0 into I. rename H1 into B. rename x0 into b.\n  rewrite 3 Zlength_map in LenX, LenY. \n  forward.\n  { entailer!. \n    rewrite Znth_map with (d':=Byte.zero); trivial. \n    rewrite Int.unsigned_repr. apply Byte.unsigned_range_2. apply Byte_unsigned_range_32. }\n  rewrite Znth_map with (d':=Byte.zero) by omega. \n  forward.\n  { entailer!.\n    rewrite Znth_map with (d':=Byte.zero) by omega. \n    rewrite Int.unsigned_repr. apply Byte.unsigned_range_2. apply Byte_unsigned_range_32. }\n  rewrite Znth_map with (d':=Byte.zero) by omega. \n  forward. entailer!. clear H3 H6 H4 H7.\n  rewrite <- (sublist_rejoin 0 i (i+1) xcont), sublist_len_1 with (d:=Byte.zero); try omega.\n  rewrite <- (sublist_rejoin 0 i (i+1) ycont), sublist_len_1 with (d:=Byte.zero); try omega.\n  rewrite list_eq_dec_app. 2: rewrite 2 Zlength_sublist; trivial; omega. 2: rewrite 2 Zlength_cons, Zlength_nil; trivial.\n  rewrite <- B. unfold Int.xor. \n  remember (list_eq_dec Byte.eq_dec [Znth i xcont Byte.zero] [Znth i ycont Byte.zero]).  simpl.\n  rewrite or_repr. clear H0 H1 H2 (*H4*) H5 (*H7*) SH SH0 PNx PNy Heqs.\n(*  rewrite 2 zero_ext_inrange by \n      (rewrite Int.unsigned_repr; [ apply Byte.unsigned_range_2 | apply byte_unsigned_range_int_unsigned_max]).*)\n  rewrite 2 Int.unsigned_repr by apply byte_unsigned_range_int_unsigned_max. \n  destruct (list_eq_dec Byte.eq_dec (sublist 0 i xcont) (sublist 0 i ycont)).\n  + specialize (Byte.eq_spec b Byte.zero); rewrite B; intros; subst b; clear B.\n    simpl. destruct s.\n    - inv e0. rewrite H1, Z.lxor_nilpotent, Z.lor_0_r.\n      Exists Byte.zero. entailer.\n    - destruct (Z_lxor_byte_neq (Znth i xcont Byte.zero) (Znth i ycont Byte.zero)) as [bb [BB HBB]].\n      * intros N. apply n; rewrite N; trivial.\n      * Exists bb; entailer!. split. apply Byte.eq_false; trivial. \n        rewrite BB, Zlor_Byteor, Byte.or_zero_l; trivial.\n  + destruct s.\n    - inv e. rewrite H1, Z.lxor_nilpotent, Z.lor_0_r, andb_true_r.\n      Exists b. entailer!.\n    - destruct (Z_lxor_byte_neq (Znth i xcont Byte.zero) (Znth i ycont Byte.zero)) as [bb [BB HBB]].\n      * intros N. apply n0; rewrite N; trivial.\n      * rewrite BB, Zlor_Byteor, andb_false_r. \n        Exists (Byte.or b bb). entailer!. apply Byte.eq_false. intros N.\n        destruct (ByteOr_zero _ _ N). contradiction. }\napply extract_exists_pre; intros b.\nforward. apply prop_right.\n  rewrite ! Zlength_map in *. rewrite 2 sublist_same in H0; trivial. \n  clear H1 H4 H6 H3 H2 H5 SH SH0 PNx PNy.\n  destruct (list_eq_dec Byte.eq_dec xcont ycont).\n  + specialize (Byte.eq_spec b Byte.zero). rewrite H0; intros; subst. reflexivity.\n  + specialize (Byte.eq_spec b Byte.zero). rewrite H0; intros. clear - ZWS BWS H1.\n    f_equal. unfold Int.sub. \n    assert (Int.shru (Int.repr (Byte.unsigned b - 1)) (Int.repr 8) = Int.zero).\n    - apply Int.same_bits_eq. rewrite ZWS; intros. rewrite Int.bits_zero, Int.bits_shru; try omega.\n      rewrite (Int.unsigned_repr 8), ZWS. 2: rewrite int_max_unsigned_eq; omega.\n      if_tac; trivial. rewrite Int.testbit_repr by omega. apply isbyteZ_testbit. 2: omega.\n      destruct (Byte.unsigned_range b). replace Byte.modulus with 256 in H3 by reflexivity. split; try omega.\n      destruct (zle 0 (Byte.unsigned b - 1)); trivial. elim H1; clear H1.\n      assert (ZZ: Byte.unsigned b =0) by omega.\n      apply initialize.zero_ext_inj. rewrite ZZ; reflexivity.\n    - rewrite H, Int.and_zero; reflexivity.\nQed.\n\nLemma verify16_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_crypto_verify_16_tweet verify16_spec.\nProof.\nstart_function.\nforward_call (x,y,16,xsh,ysh,xcont,ycont).\nforward.\nQed.\n\nLemma verify32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_crypto_verify_32_tweet verify32_spec.\nProof.\nstart_function.\nforward_call (x,y,32,xsh,ysh,xcont,ycont).\nforward.\nQed.", "meta": {"author": "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_verify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.19844910511800717}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma pure1 (sz1l1 : nat) (sz2l1 : nat) (sz2 : nat) : (0) <= (sz1l1) -> (0) <= (((1) + (sz1l1)) + (sz2l1)) -> (0) <= (sz2) -> (0) <= (sz2l1) -> ((sz1l1) + (((1) + (sz2l1)) + (sz2))) = ((((1) + (sz1l1)) + (sz2l1)) + (sz2)). intros; hammer. Qed.\nHint Resolve pure1: ssl_pure.\nLemma pure2 (sz2l1 : nat) (sz2 : nat) (sz1l1 : nat) : (0) <= (sz1l1) -> (0) <= (((1) + (sz1l1)) + (sz2l1)) -> (0) <= (sz2) -> (0) <= (sz2l1) -> (0) <= (((1) + (sz2l1)) + (sz2)). intros; hammer. Qed.\nHint Resolve pure2: ssl_pure.\nLemma pure3 (hi2l1 : nat) (hi1l1 : nat) (lo2 : nat) (v1 : nat) (lo2l1 : nat) (vl11 : nat) : ((if (hi2l1) <= (vl11) then vl11 else hi2l1)) <= (v1) -> (vl11) <= (lo2l1) -> (0) <= (vl11) -> (v1) <= (lo2) -> (0) <= (v1) -> (vl11) <= (7) -> (hi1l1) <= (vl11) -> (v1) <= (7) -> (hi2l1) <= (v1).\n  (* intros; hammer. *)\n  intros.\n  intros.\n  destruct (hi2l1 <= vl11) eqn:H7; last by done.\n  exact (leq_trans H7 H).\nQed.\nHint Resolve pure3: ssl_pure.\nLemma pure4 (hi2l1 : nat) (hi1l1 : nat) (lo2 : nat) (v1 : nat) (lo2l1 : nat) (vl11 : nat) : ((if (hi2l1) <= (vl11) then vl11 else hi2l1)) <= (v1) -> (vl11) <= (lo2l1) -> (0) <= (vl11) -> (v1) <= (lo2) -> (0) <= (v1) -> (vl11) <= (7) -> (hi1l1) <= (vl11) -> (v1) <= (7) -> (vl11) <= ((if (v1) <= (lo2l1) then v1 else lo2l1)).\n  (* intros; hammer. *)\n  intros.\n  destruct (v1 <= lo2l1) eqn:H7; last by done.\n  destruct (hi2l1 <= vl11) eqn:H8; first by done.\n  apply negbT in H8.\n  rewrite -ltnNge in H8.\n  apply ltnW in H8.\n  exact (leq_trans H8 H).\nQed.\nHint Resolve pure4: ssl_pure.\n\nDefinition bst_right_rotate_type :=\n  forall (vprogs : ptr * ptr),\n  {(vghosts : nat * nat * nat * nat * ptr * nat * nat * ptr * nat * ptr)},\n  STsep (\n    fun h =>\n      let: (x, retv) := vprogs in\n      let: (sz1, sz2, v, hi1, l, lo2, lo1, r, hi2, unused) := vghosts in\n      exists h_bst_lsz1lo1hi1_a h_bst_rsz2lo2hi2_b,\n      (0) <= (sz1) /\\ (0) <= (sz2) /\\ (0) <= (v) /\\ (hi1) <= (v) /\\ ~~ ((l) == (null)) /\\ (v) <= (7) /\\ (v) <= (lo2) /\\ h = retv :-> (unused) \\+ x :-> (v) \\+ x .+ 1 :-> (l) \\+ x .+ 2 :-> (r) \\+ h_bst_lsz1lo1hi1_a \\+ h_bst_rsz2lo2hi2_b /\\ bst l sz1 lo1 hi1 h_bst_lsz1lo1hi1_a /\\ bst r sz2 lo2 hi2 h_bst_rsz2lo2hi2_b,\n    [vfun (_: unit) h =>\n      let: (x, retv) := vprogs in\n      let: (sz1, sz2, v, hi1, l, lo2, lo1, r, hi2, unused) := vghosts in\n      exists sz3 sz4 v3 hi3 lo4 l3 lo3 hi4 y,\n      exists h_bst_l3sz3lo3hi3_2 h_bst_xsz4lo4hi4_3,\n      (0) <= (sz3) /\\ (0) <= (sz4) /\\ (0) <= (v3) /\\ (hi3) <= (v3) /\\ ((sz3) + (sz4)) == ((sz1) + (sz2)) /\\ (v3) <= (7) /\\ (v3) <= (lo4) /\\ h = retv :-> (y) \\+ y :-> (v3) \\+ y .+ 1 :-> (l3) \\+ y .+ 2 :-> (x) \\+ h_bst_l3sz3lo3hi3_2 \\+ h_bst_xsz4lo4hi4_3 /\\ bst l3 sz3 lo3 hi3 h_bst_l3sz3lo3hi3_2 /\\ bst x sz4 lo4 hi4 h_bst_xsz4lo4hi4_3\n    ]).\n\nProgram Definition bst_right_rotate : bst_right_rotate_type :=\n  Fix (fun (bst_right_rotate : bst_right_rotate_type) vprogs =>\n    let: (x, retv) := vprogs in\n    Do (\n      unused1 <-- @read ptr retv;\n      v1 <-- @read nat x;\n      l1 <-- @read ptr (x .+ 1);\n      r1 <-- @read ptr (x .+ 2);\n      if (l1) == (null)\n      then\n        ret tt\n      else\n        vl11 <-- @read nat l1;\n        ll11 <-- @read ptr (l1 .+ 1);\n        rl11 <-- @read ptr (l1 .+ 2);\n        (l1 .+ 2) ::= x;;\n        (x .+ 1) ::= rl11;;\n        retv ::= l1;;\n        ret tt\n    )).\nObligation Tactic := intro; move=>[x retv]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>[[[[[[[[[sz1 sz2] v] hi1] l] lo2] lo1] r] hi2] unused].\nex_elim h_bst_lsz1lo1hi1_a h_bst_rsz2lo2hi2_b.\nmove=>[phi_self0] [phi_self1] [phi_self2] [phi_self3] [phi_self4] [phi_self5] [phi_self6].\nmove=>[sigma_self].\nsubst h_self.\nmove=>[H_bst_lsz1lo1hi1_a H_bst_rsz2lo2hi2_b].\nssl_ghostelim_post.\nssl_read retv.\ntry rename unused into unused1.\nssl_read x.\ntry rename v into v1.\nssl_read (x .+ 1).\ntry rename l into l1.\ntry rename h_bst_lsz1lo1hi1_a into h_bst_l1sz1lo1hi1_a.\ntry rename H_bst_lsz1lo1hi1_a into H_bst_l1sz1lo1hi1_a.\nssl_read (x .+ 2).\ntry rename r into r1.\ntry rename h_bst_rsz2lo2hi2_b into h_bst_r1sz2lo2hi2_b.\ntry rename H_bst_rsz2lo2hi2_b into H_bst_r1sz2lo2hi2_b.\nssl_open ((l1) == (null)) H_bst_l1sz1lo1hi1_a.\nmove=>[phi_bst_l1sz1lo1hi1_a0] [phi_bst_l1sz1lo1hi1_a1] [phi_bst_l1sz1lo1hi1_a2].\nmove=>[sigma_bst_l1sz1lo1hi1_a].\nsubst h_bst_l1sz1lo1hi1_a.\nssl_inconsistency.\nex_elim sz1l1 sz2l1 vl1 hi2l1 hi1l1.\nex_elim lo1l1 lo2l1 ll1 rl1.\nex_elim h_bst_ll1sz1l1lo1l1hi1l1_0l1 h_bst_rl1sz2l1lo2l1hi2l1_1l1.\nmove=>[phi_bst_l1sz1lo1hi1_a0] [phi_bst_l1sz1lo1hi1_a1] [phi_bst_l1sz1lo1hi1_a2] [phi_bst_l1sz1lo1hi1_a3] [phi_bst_l1sz1lo1hi1_a4] [phi_bst_l1sz1lo1hi1_a5] [phi_bst_l1sz1lo1hi1_a6] [phi_bst_l1sz1lo1hi1_a7] [phi_bst_l1sz1lo1hi1_a8].\nmove=>[sigma_bst_l1sz1lo1hi1_a].\nsubst h_bst_l1sz1lo1hi1_a.\nmove=>[H_bst_ll1sz1l1lo1l1hi1l1_0l1 H_bst_rl1sz2l1lo2l1hi2l1_1l1].\ntry rename h_bst_l1sz1lo1hi1_a into h_bst_l1sz1lo1hi2l1vl1vl1hi2l1_a.\ntry rename H_bst_l1sz1lo1hi1_a into H_bst_l1sz1lo1hi2l1vl1vl1hi2l1_a.\ntry rename h_bst_l1sz1lo1hi2l1vl1vl1hi2l1_a into h_bst_l1sz1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a.\ntry rename H_bst_l1sz1lo1hi2l1vl1vl1hi2l1_a into H_bst_l1sz1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a.\ntry rename h_bst_l1sz1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a into h_bst_l1sz1l1sz2l1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a.\ntry rename H_bst_l1sz1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a into H_bst_l1sz1l1sz2l1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a.\nssl_read l1.\ntry rename vl1 into vl11.\ntry rename h_bst_l1sz1l1sz2l1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a into h_bst_l1sz1l1sz2l1vl11lo1l1vl11lo1l1hi2l1vl11vl11hi2l1_a.\ntry rename H_bst_l1sz1l1sz2l1vl1lo1l1vl1lo1l1hi2l1vl1vl1hi2l1_a into H_bst_l1sz1l1sz2l1vl11lo1l1vl11lo1l1hi2l1vl11vl11hi2l1_a.\nssl_read (l1 .+ 1).\ntry rename ll1 into ll11.\ntry rename h_bst_ll1sz1l1lo1l1hi1l1_0l1 into h_bst_ll11sz1l1lo1l1hi1l1_0l1.\ntry rename H_bst_ll1sz1l1lo1l1hi1l1_0l1 into H_bst_ll11sz1l1lo1l1hi1l1_0l1.\nssl_read (l1 .+ 2).\ntry rename rl1 into rl11.\ntry rename h_bst_rl1sz2l1lo2l1hi2l1_1l1 into h_bst_rl11sz2l1lo2l1hi2l1_1l1.\ntry rename H_bst_rl1sz2l1lo2l1hi2l1_1l1 into H_bst_rl11sz2l1lo2l1hi2l1_1l1.\ntry rename h_bst_xsz4lo4hi4_3 into h_bst_xsz4lo4hi21xv2xv2xhi21x_3.\ntry rename H_bst_xsz4lo4hi4_3 into H_bst_xsz4lo4hi21xv2xv2xhi21x_3.\ntry rename h_bst_xsz4lo4hi21xv2xv2xhi21x_3 into h_bst_xsz4v2xlo11xv2xlo11xhi21xv2xv2xhi21x_3.\ntry rename H_bst_xsz4lo4hi21xv2xv2xhi21x_3 into H_bst_xsz4v2xlo11xv2xlo11xhi21xv2xv2xhi21x_3.\ntry rename h_bst_xsz4v2xlo11xv2xlo11xhi21xv2xv2xhi21x_3 into h_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_3.\ntry rename H_bst_xsz4v2xlo11xv2xlo11xhi21xv2xv2xhi21x_3 into H_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_3.\ntry rename h_bst_l3sz3lo3hi3_2 into h_bst_ll11sz1l1lo1l1hi1l1_0l1.\ntry rename H_bst_l3sz3lo3hi3_2 into H_bst_ll11sz1l1lo1l1hi1l1_0l1.\ntry rename h_bst_l2xsz11xlo11xhi11x_0x into h_bst_rl11sz2l1lo2l1hi2l1_1l1.\ntry rename H_bst_l2xsz11xlo11xhi11x_0x into H_bst_rl11sz2l1lo2l1hi2l1_1l1.\ntry rename h_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_3 into h_bst_xsz11xsz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3.\ntry rename H_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_3 into H_bst_xsz11xsz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3.\ntry rename h_bst_xsz11xsz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3 into h_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3.\ntry rename H_bst_xsz11xsz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3 into H_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3.\ntry rename h_bst_r2xsz21xlo21xhi21x_1x into h_bst_r1sz2lo2hi2_b.\ntry rename H_bst_r2xsz21xlo21xhi21x_1x into H_bst_r1sz2lo2hi2_b.\ntry rename h_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3 into h_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi2v2xv2xhi2_3.\ntry rename H_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi21xv2xv2xhi21x_3 into H_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi2v2xv2xhi2_3.\ntry rename h_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi2v2xv2xhi2_3 into h_bst_xsz2l1sz2v2xlo2l1v2xlo2l1hi2v2xv2xhi2_3.\ntry rename H_bst_xsz2l1sz21xv2xlo2l1v2xlo2l1hi2v2xv2xhi2_3 into H_bst_xsz2l1sz2v2xlo2l1v2xlo2l1hi2v2xv2xhi2_3.\nssl_write (l1 .+ 2).\nssl_write_post (l1 .+ 2).\nssl_write (x .+ 1).\nssl_write_post (x .+ 1).\nssl_write retv.\nssl_write_post retv.\ntry rename h_bst_xsz2l1sz2v2xlo2l1v2xlo2l1hi2v2xv2xhi2_3 into h_bst_xsz2l1sz2v1lo2l1v1lo2l1hi2v1v1hi2_3.\ntry rename H_bst_xsz2l1sz2v2xlo2l1v2xlo2l1hi2v2xv2xhi2_3 into H_bst_xsz2l1sz2v1lo2l1v1lo2l1hi2v1v1hi2_3.\nssl_emp;\nexists (sz1l1), (((1) + (sz2l1)) + (sz2)), (vl11), (hi1l1), ((if (v1) <= (lo2l1) then v1 else lo2l1)), (ll11), (lo1l1), ((if (hi2) <= (v1) then v1 else hi2)), (l1);\nexists (h_bst_ll11sz1l1lo1l1hi1l1_0l1);\nexists (x :-> (v1) \\+ x .+ 1 :-> (rl11) \\+ x .+ 2 :-> (r1) \\+ h_bst_rl11sz2l1lo2l1hi2l1_1l1 \\+ h_bst_r1sz2lo2hi2_b);\nsslauto.\nshelve.\nssl_close 2;\nexists (sz2l1), (sz2), (v1), (hi2), (hi2l1), (lo2l1), (lo2), (rl11), (r1), (h_bst_rl11sz2l1lo2l1hi2l1_1l1), (h_bst_r1sz2lo2hi2_b);\nsslauto.\nshelve.\nshelve.\nUnshelve.\nssl_frame_unfold.\nssl_frame_unfold.\nssl_frame_unfold.\nQed.\n", "meta": {"author": "TyGuS", "repo": "ssl-htt", "sha": "3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d", "save_path": "github-repos/coq/TyGuS-ssl-htt", "path": "github-repos/coq/TyGuS-ssl-htt/ssl-htt-3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d/benchmarks/advanced/bst/bst_right_rotate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3242354120407358, "lm_q1q2_score": 0.19823168602530722}}
{"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base pagetable mem trans.\nFrom HypVeri.rules Require Import rules_base mult.\nFrom HypVeri.logrel Require Import logrel logrel_extra.\nFrom HypVeri Require Import proofmode.\nImport uPred.\n\nSection ftlr_mult.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{hypparams:!HypervisorParameters}.\n  Context `{vmG: !gen_VMG \u03a3}.\n\nLemma ftlr_mult {i mem_acc_tx ai regs rxs ps_acc p_tx p_rx instr trans op1 op2} P:\n  base_extra.is_total_gmap regs ->\n  base_extra.is_total_gmap rxs ->\n  {[p_tx; p_rx]} \u2286 ps_acc ->\n  currently_accessible_in_trans_memory_pages i trans \u2286 ps_acc \u2216 {[p_tx; p_rx]} ->\n  p_rx \u2209 ps_acc \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i trans ->\n  p_tx \u2209 ps_acc \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i trans ->\n  regs !! PC = Some ai ->\n  tpa ai \u2208 ps_acc ->\n  tpa ai \u2260 p_tx ->\n  dom mem_acc_tx = set_of_addr (ps_acc \u2216 {[p_tx]}) ->\n  tpa ai \u2208 ps_acc \u2216 {[p_tx]} ->\n  mem_acc_tx !! ai = Some instr ->\n  decode_instruction instr = Some (Mult op1 op2) ->\n  \u22a2 \u25b7 (\u2200 (a : gmap reg_name Word) (a0 : gset PID) (a1 : gmap Word transaction) (a2 : gmap VMID (option (Word * VMID))),\n              \u231cbase_extra.is_total_gmap a2\u231d -\u2217\n              \u231cbase_extra.is_total_gmap a\u231d -\u2217\n              \u231c{[p_tx; p_rx]} \u2286 a0\u231d -\u2217\n              \u231ccurrently_accessible_in_trans_memory_pages i a1 \u2286 a0 \u2216 {[p_tx; p_rx]}\u231d -\u2217\n              \u231cp_rx \u2209 a0 \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i a1\u231d -\u2217\n              \u231cp_tx \u2209 a0 \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i a1\u231d -\u2217\n              ([\u2217 map] r\u21a6w \u2208 a, r @@ i ->r w) -\u2217\n              TX@i:=p_tx -\u2217\n              p_tx -@O> - \u2217 p_tx -@E> true -\u2217\n              mailbox.rx_page i p_rx -\u2217\n              i -@A> a0 -\u2217\n              pagetable_entries_excl_owned i (a0 \u2216 {[p_rx; p_tx]} \u2216 currently_accessible_in_trans_memory_pages i a1) -\u2217\n              transaction_hpool_global_transferred a1 -\u2217\n              transaction_pagetable_entries_transferred i a1 -\u2217\n              retrievable_transaction_transferred i a1 -\u2217\n              rx_state_get i a2 -\u2217\n              rx_states_global (delete i a2) -\u2217\n              transaction_pagetable_entries_owned i a1 -\u2217\n              retrieved_transaction_owned i a1 -\u2217\n              (\u2203 mem : lang.mem, memory_pages (a0 \u222a (accessible_in_trans_memory_pages i a1)) mem) -\u2217\n              (P a1 a2) -\u2217\n              WP ExecI @ i {{ _, True }}) -\u2217\n   ([\u2217 map] r\u21a6w \u2208 regs, r @@ i ->r w) -\u2217\n   TX@i:=p_tx -\u2217\n   p_tx -@O> - \u2217 p_tx -@E> true -\u2217\n   i -@A> ps_acc -\u2217\n   pagetable_entries_excl_owned i (ps_acc \u2216 {[p_rx; p_tx]} \u2216 (currently_accessible_in_trans_memory_pages i trans)) -\u2217\n   transaction_hpool_global_transferred trans -\u2217\n   transaction_pagetable_entries_transferred i trans -\u2217\n   retrievable_transaction_transferred i trans -\u2217\n   rx_state_get i rxs -\u2217\n   mailbox.rx_page i p_rx -\u2217\n   rx_states_global (delete i rxs) -\u2217\n   transaction_pagetable_entries_owned i trans -\u2217\n   retrieved_transaction_owned i trans -\u2217\n   (\u2203 mem1 : mem, memory_pages ((ps_acc \u222a (accessible_in_trans_memory_pages i trans)) \u2216 ps_acc) mem1) -\u2217\n   ([\u2217 map] k\u21a6v \u2208 mem_acc_tx, k ->a v) -\u2217\n   (\u2203 mem2 : mem, memory_page p_tx mem2) -\u2217\n   (P trans rxs) -\u2217\n   SSWP ExecI @ i {{ bm, (if bm.1 then VMProp_holds i (1 / 2) else True) -\u2217 WP bm.2 @ i {{ _, True }} }}.\n  Proof.\n    iIntros (Htotal_regs Htotal_rxs Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx Hlookup_PC Hin_ps_acc Hneq_ptx Hdom_mem_acc_tx Hin_ps_acc_tx Hlookup_mem_ai Heqn).\n    iIntros \"IH regs tx pgt_tx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state rx other_rx tran_pgt_owned\n                 retri_owned mem_rest mem_acc_tx mem_tx P\".\n    destruct op1 as [| | n nle].\n    {\n      apply decode_instruction_valid in Heqn.\n      inversion Heqn.\n      unfold reg_valid_cond in *.\n      exfalso.\n      naive_solver.\n    }\n    {\n      apply decode_instruction_valid in Heqn.\n      inversion Heqn.\n      unfold reg_valid_cond in *.\n      exfalso.\n      naive_solver.\n    }\n    pose proof (Htotal_regs (R n nle)) as [a_arg1 Hlookup_arg1].\n    (* getting registers *)\n    iDestruct ((reg_big_sepM_split_upd2 i Hlookup_PC Hlookup_arg1)\n                with \"[$regs]\") as \"(PC & r_arg1 & Hacc_regs)\"; [done | done |].\n    (* getting mem *)\n    iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with \"[$mem_acc_tx]\")\n      as \"[mem_instr Hacc_mem_acc_tx]\".\n    iApply (mult_word _ op2 (R n nle) with \"[PC tx pgt_acc mem_instr r_arg1]\"); iFrameAutoSolve.\n    iNext. iIntros \"(PC & mem_instr & pgt_acc & r_arg1 & tx) _\".\n    iDestruct (\"Hacc_regs\" with \"[$PC $r_arg1]\") as (regs') \"[%Htotal_regs' regs]\";iFrame.\n    iDestruct (\"Hacc_mem_acc_tx\" with \"mem_instr\") as \"mem_acc_tx\".\n    iApply (\"IH\" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with \"regs tx pgt_tx rx pgt_acc pgt_owned\n                       trans_hpool_global tran_pgt_transferred retri rx_state other_rx\n                           tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P\").\n    {\n      iDestruct (memory_pages_split_singleton' p_tx ps_acc with \"[mem_acc_tx $mem_tx]\") as \"mem_acc\". set_solver + Hsubset_mb.\n      iExists mem_acc_tx;by iFrame \"mem_acc_tx\".\n      iApply (memory_pages_split_diff' _ ps_acc with \"[$mem_rest $mem_acc]\").\n      set_solver +.\n    }\n  Qed.\n\nEnd ftlr_mult.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/logrel/ftlr_mult.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.19823166546454776}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\n(*                                                                          *)\n(* Licensed under the Apache License, Version 2.0 (the \"License\")           *)\n(* you may not use this file except in compliance with the License.         *)\n(* You may obtain a copy of the License at                                  *)\n(*                                                                          *)\n(*     http://www.apache.org/licenses/LICENSE-2.0                           *)\n(*                                                                          *)\n(* Unless required by applicable law or agreed to in writing, software      *)\n(* distributed under the License is distributed on an \"AS IS\" BASIS,        *)\n(* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *)\n(* See the License for the specific language governing permissions and      *)\n(* limitations under the License.                                           *)\n(****************************************************************************)\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Vectors.Vector.\nRequire Import Cava.Arrow.Classes.Category Cava.Arrow.Classes.Arrow.\nRequire Import Cava.Arrow.Primitives.\n\nImport ListNotations.\nImport VectorNotations.\nImport CategoryNotations.\n\nLocal Open Scope category_scope.\nLocal Open Scope arrow_scope.\n\n(* Class CircuitLaws `(A: Arrow, ! ArrowCopy A, ! ArrowSwap A, ! ArrowDrop A) := {\n  cancelr_unit_uncancelr {x}: @cancelr x >>> uncancelr =M= id;\n  cancell_unit_uncancell {x}: @cancell _ _ A x >>> uncancell =M= id;\n  uncancelr_cancelr {x}:      @uncancelr _ _ A x >>> cancelr =M= id;\n  uncancell_cancell {x}:      @uncancell _ _ A x >>> cancell =M= id;\n\n  drop_annhilates {x y} (f: x~>y): f >>> drop =M= drop;\n\n  cancelr_unit_is_drop : @cancelr A unit =M= drop;\n  cancell_unit_is_drop : @cancell A unit =M= drop;\n\n  first_first   {x y z w} (f: x~>y) (g:y~>z): @first A x y w f >>> first g  =M= first (f >>> g);\n  second_second {x y z w} (f: x~>y) (g:y~>z): @second A x y w f >>> second g  =M= second (f >>> g);\n\n  swap_swap {x y}: @swap A _ x y >>> swap =M= id;\n\n  first_id  {x w}: @first A x x w id  =M= id;\n  second_id {x w}: @second A x x w id  =M= id;\n\n  first_f  {x y w} (f: x~>y) (g:x~>y): f =M= g -> @first A x y w f =M= first g;\n  second_f {x y w} (f: x~>y) (g:x~>y): f =M= g -> @second A x y w f =M= second g;\n}. *)\n\nNotation arrow_input x := (arrow_input (object:=Kind) (unit:=Unit) (product:=Tuple) x).\nNotation arrow_output x := (arrow_output (object:=Kind) (unit:=Unit) (product:=Tuple) x).\n\n(* Single clock circuit *)\nInductive Circuit: Kind -> Kind -> Type :=\n  | Structural: forall (x: ArrowStructure), Circuit (arrow_input x) (arrow_output x)\n  | Primitive: forall (x: CircuitPrimitive), Circuit (primitive_input x) (primitive_output x)\n\n  (* contains subcircuits *)\n  | Composition: forall x y z, Circuit x y -> Circuit y z -> Circuit x z\n  | First: forall x y z, Circuit x y -> Circuit (Tuple x z) (Tuple y z)\n  | Second: forall x y z, Circuit x y -> Circuit (Tuple z x) (Tuple z y)\n  | Loopr: forall x y z, Circuit (Tuple x z) (Tuple y z) -> Circuit x y\n  | Loopl: forall x y z, Circuit (Tuple z x) (Tuple z y) -> Circuit x y\n\n  | Delay: forall x, Circuit x x\n\n  | RewriteTy: forall x y, Circuit x y\n  .\n\nInstance CircuitCat : Category Kind := {\n  morphism X Y := Circuit X Y;\n  id X := Structural (Id X);\n  compose X Y Z f g := Composition X Y Z g f;\n}.\n\nInstance CircuitArrow : Arrow Kind CircuitCat Unit Tuple := {\n  first  f := First f;\n  second f := Second f;\n  assoc   x y z := Structural (Assoc x y z);\n  unassoc x y z := Structural (Unassoc x y z);\n  cancelr  x := Structural (Cancelr x);\n  cancell  x := Structural (Cancell x);\n  uncancell x := Structural (Uncancell x);\n  uncancelr x := Structural (Uncancelr x);\n}.\n\nInstance CircuitArrowDrop : ArrowDrop CircuitArrow := { drop _ := Structural (Drop _); }.\nInstance CircuitArrowSwap : ArrowSwap CircuitArrow := { swap _ _ := Structural (Swap _ _); }.\nInstance CircuitArrowCopy : ArrowCopy CircuitArrow := { copy _ := Structural (Copy _); }.\nInstance CircuitArrowLoop : ArrowLoop CircuitArrow := { loopl := Loopl; loopr := Loopr; }.\nInstance CircuitArrowSTKC : ArrowSTKC CircuitArrow := { }.\n\nLtac match_primitive X :=\n  match X with\n  | (Circuit _ _ _) => idtac\n  end.\n\nLtac match_compose X :=\n  match X with\n  | (Composition _ _ ?Y ?Z) => idtac\n  end.\n\nDefinition high : Unit ~> Bit := Primitive (P0 (Constant Bit true)).\nDefinition low : Unit ~> Bit := Primitive (P0 (Constant Bit false)).\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/CircuitArrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19810702581556874}}
{"text": "Require Import Coq.Strings.Ascii.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import ByteData.\nRequire Import DiskSubset.\nRequire Import Fetch.\nRequire Import File.\nRequire Import FileData.\n\nLocal Open Scope bool.\nLocal Open Scope char.\nLocal Open Scope N.\n\nDefinition isJpeg (file: File) (disk: Disk) :=\n     file @[  0 | disk ] = Found \"255\"\n  /\\ file @[  1 | disk ] = Found \"216\"\n  /\\ file @[- 2 | disk ] = Found \"255\"\n  /\\ file @[- 1 | disk ] = Found \"217\".\n\nDefinition isJpeg_compute (file: File) (disk: Disk) :=\n     Byte.feqb (file @[  0 | disk ]) (Found \"255\")\n  && Byte.feqb (file @[  1 | disk ]) (Found \"216\")\n  && Byte.feqb (file @[- 2 | disk ]) (Found \"255\")\n  && Byte.feqb (file @[- 1 | disk ]) (Found \"217\").\n\nLemma isJpeg_reflection (file: File) (disk: Disk) :\n  isJpeg_compute file disk = true -> isJpeg file disk.\nProof.\n  intros. unfold isJpeg_compute in H. unfold isJpeg.\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  split. apply Byte.feqb_reflection. auto.\n  split. apply Byte.feqb_reflection. auto.\n  split. apply Byte.feqb_reflection. auto.\n  apply Byte.feqb_reflection. auto.\nQed.\n\nDefinition isJpeg_subset:\n  forall (sub super: Disk) (file: File),\n    sub \u2286 super ->\n      isJpeg file sub -> isJpeg file super.\nProof.\n  intros sub super file subset.\n  unfold isJpeg.\n  intros H. destruct H as [H0 [H1 [Hn2 Hn1]]].\n  split. apply fetchByte_subset with (1:=subset). auto.\n  split. apply fetchByte_subset with (1:=subset). auto.\n  split. apply fetchByte_subset_neg with (1:=subset). auto.\n         apply fetchByte_subset_neg with (1:=subset). auto.\nQed.\n\nDefinition isGzip (file: File) (disk: Disk) :=\n     file @[ 0 | disk ] = Found \"031\"\n  /\\ file @[ 1 | disk ] = Found \"139\" \n  /\\ file @[ 2 | disk ] = Found \"008\".\n\nDefinition isGzip_compute (file: File) (disk: Disk) :=\n     Byte.feqb (file @[ 0 | disk ]) (Found \"031\")\n  && Byte.feqb (file @[ 1 | disk ]) (Found \"139\")\n  && Byte.feqb (file @[ 2 | disk ]) (Found \"008\").\n\nLemma isGzip_reflection (file: File) (disk: Disk) :\n  isGzip_compute file disk = true -> isGzip file disk.\nProof.\n  intros. unfold isGzip_compute in H. unfold isGzip.\n  apply Bool.andb_true_iff in H. destruct H.\n  apply Bool.andb_true_iff in H. destruct H.\n\n  split. apply Byte.feqb_reflection. auto.\n  split. apply Byte.feqb_reflection. auto.\n  apply Byte.feqb_reflection. auto.\nQed.\n\nDefinition isGzip_subset:\n  forall (sub super: Disk) (file: File),\n    sub \u2286 super ->\n      isGzip file sub -> isGzip file super.\nProof.\n  intros sub super file subset.\n  unfold isGzip.\n  intros H. destruct H as [H0 [H1 H2]].\n  split. apply fetchByte_subset with (1:=subset). auto.\n  split. apply fetchByte_subset with (1:=subset). auto.\n         apply fetchByte_subset with (1:=subset). auto.\nQed.\n\nDefinition isElf (file: File) (disk: Disk) :=\n     file @[ 0 | disk ] = Found \"127\"\n  /\\ file @[ 1 | disk ] = Found \"E\"\n  /\\ file @[ 2 | disk ] = Found \"L\"\n  /\\ file @[ 3 | disk ] = Found \"F\".\n\nDefinition isElf_compute (file: File) (disk: Disk) :=\n     Byte.feqb (file @[ 0 | disk ]) (Found \"127\")\n  && Byte.feqb (file @[ 1 | disk ]) (Found \"E\")\n  && Byte.feqb (file @[ 2 | disk ]) (Found \"L\")\n  && Byte.feqb (file @[ 3 | disk ]) (Found \"F\").\n\nLemma isElf_reflection (file: File) (disk: Disk) :\n  isElf_compute file disk = true -> isElf file disk.\nProof.\n  intros. unfold isElf_compute in H. unfold isElf.\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  split. apply Byte.feqb_reflection. auto.\n  split. apply Byte.feqb_reflection. auto.\n  split. apply Byte.feqb_reflection. auto.\n  apply Byte.feqb_reflection. auto.\nQed.\n\nDefinition isElf_subset:\n  forall (sub super: Disk) (file: File),\n    sub \u2286 super ->\n      isElf file sub -> isElf file super.\nProof.\n  intros sub super file subset.\n  unfold isElf.\n  intros H. destruct H as [H0 [H1 [H2 H3]]].\n  split. apply fetchByte_subset with (1:=subset). auto.\n  split. apply fetchByte_subset with (1:=subset). auto.\n  split. apply fetchByte_subset with (1:=subset). auto.\n         apply fetchByte_subset with (1:=subset). auto.\nQed.\n\n\nLemma jpeg_is_not_gzip : forall (file: File) (disk: Disk),\n  (isJpeg file disk) -> ~ (isGzip file disk).\nProof.\n  unfold isGzip, isJpeg.\n  intros file disk jpeg_asmpt.\n  destruct jpeg_asmpt as [byte0_is_255]. rewrite byte0_is_255.\n  unfold not. intros contra. destruct contra as [not_equal].\n  discriminate not_equal.\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/FileTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19805169301539852}}
{"text": "Require Import Charge.Open.Subst.\nRequire Import Charge.Open.Open.\nRequire Import Charge.Open.Stack.\nRequire Import Charge.Logics.BILogic.\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 ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.String.\nRequire Import ExtLib.Data.Sum.\nRequire Import ExtLib.Tactics.Consider.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.Lemma.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.syms.SymEnv.\nRequire Import MirrorCore.syms.SymSum.\nRequire Import MirrorCore.Subst.FMapSubst.\n\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Language.Lang.\nRequire Import Java.Language.Program.\nRequire Import Java.Semantics.OperationalSemantics.\nRequire Import Java.Func.JavaType.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Bool.Bool.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n\tInductive java_func :=\n\n\t| pMethodSpec\n\t| pProgEq\n\t| pTriple\n\t| pTypeOf\n\t| pFieldLookup\n\t| pMethodLookup\n\t\n\t| pPointsto\n\t| pNull\n\t\n\t| pMethodBody\n\t| pMethodArgs\n\t| pMethodRet\n\t\n\t\n\t| pPlus\n\t| pMinus\n\t| pTimes\n\t| pAnd\n\t| pOr\n\t| pNot\n\t| pLt\n\t| pValEq.\n\n\tFixpoint beq_list {A} (f : A -> A -> bool) (xs ys : list A) :=\n\t\tmatch xs, ys with\n\t\t\t| nil, nil => true\n\t\t\t| x::xs, y :: ys => andb (f x y) (beq_list f xs ys)\n\t\t\t| _, _ => false\n\t\tend.\n\n\tDefinition typeof_java_func bf :=\n\t\tmatch bf with\n\t\t    | pMethodSpec => Some (tyArr tyString (tyArr tyString (tyArr tyVarList\n\t\t    \t (tyArr tyString (tyArr tySasn (tyArr tySasn tySpec))))))\n\t\t    | pProgEq => Some (tyArr tyProg tySpec)\n\t\t    | pTriple => Some (tyArr tySasn (tyArr tySasn (tyArr tyCmd tySpec)))\n\t\t    \n\t\t    | pTypeOf => Some (tyArr tyString (tyArr tyVal tyProp))\n\t\t    \n\t\t    | pFieldLookup => Some (tyArr tyProg (tyArr tyString (tyArr tyFields tyProp)))\n\t\t    | pMethodLookup => Some (tyArr tyProg (tyArr tyString (tyArr tyString (tyArr tyMethod tyProp))))\n\t\t    \n\t\t    | pPointsto => Some (tyArr tyVal (tyArr tyString (tyArr tyVal tyAsn)))\n\t\t    | pNull => Some tyVal\n\t\t    \n\t\t    | pMethodBody => Some (tyArr tyMethod tyCmd)\n\t\t    | pMethodArgs => Some (tyArr tyMethod (tyList tyString))\n\t\t    | pMethodRet => Some (tyArr tyMethod tyDExpr)\n\t\t    \n\t\t    | pPlus => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pMinus => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pTimes => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pAnd => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pOr => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pNot => Some (tyArr tyVal tyVal)\n\t\t    | pLt => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pValEq => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\tend.\n\n\tDefinition java_func_eq (a b : java_func) : option bool :=\n\t  match a , b with\n\t    | pMethodSpec, pMethodSpec => Some true\n\t    | pProgEq, pProgEq => Some true\n\t\t| pTriple, pTriple => Some true\n\t\n\t    | pTypeOf, pTypeOf => Some true\n\t\n\t    | pPointsto, pPointsto => Some true\n\t    | pFieldLookup, pFieldLookup => Some true\n\t    | pMethodLookup, pMethodLookup => Some true\n\t    \n\t    | pMethodBody, pMethodBody => Some true\n\t    | pMethodArgs, pMethodArgs => Some true\n\t    | pMethodRet, pMethodRet => Some true\n\t\n\t    | pNull, pNull => Some true\n\t    | pPlus, pPlus => Some true\n\t    | pMinus, pMinus => Some true\n\t    | pTimes, pTimes => Some true\n\t    | pAnd, pAnd => Some true\n\t    | pOr, pOr => Some true\n\t    | pNot, pNot => Some true\n\t    | pLt, pLt => Some true\n\t    | pValEq, pValEq => Some true\n\t    | _, _ => None\n\t  end.\n\n    Global Instance RelDec_java_func : RelDec (@eq java_func) := {\n      rel_dec a b := match java_func_eq a b with \n    \t  \t\t       | Some b => b \n    \t\t \t       | None => false \n    \t\t\t     end\n    }.\n\n    Global Instance RelDec_Correct_java_func : RelDec_Correct RelDec_java_func.\n    Proof.\n      constructor.\n      destruct x; destruct y; simpl;\n      try solve [ try rewrite Bool.andb_true_iff ;\n                  repeat rewrite rel_dec_correct; intuition congruence ].                  \t\n    Qed.\n\nDefinition set_fold_fun (x : String.string) (f : field) (P : sasn) :=\n\t(`pointsto) (x/V) `f `null ** P.\n\n  \t Definition java_func_symD bf :=\n\t\tmatch bf as bf return match typeof_java_func bf with\n\t\t\t\t\t\t\t\t| Some t => typD t\n\t\t\t\t\t\t\t\t| None => unit\n\t\t\t\t\t\t\t  end with\n              | pMethodSpec => method_spec\n              | pProgEq => prog_eq\n              | pTriple => triple\n              \n              | pTypeOf => typeof\n                            \n              | pFieldLookup => field_lookup\n              | pMethodLookup => method_lookup\n              \n              | pPointsto => pointsto\n              \n              | pNull => null\n              \n              | pMethodBody => m_body\n              | pMethodArgs => m_params\n              | pMethodRet => m_ret\n              \n              | pPlus => eplus\n              | pMinus => eminus\n              | pTimes => etimes\n              | pAnd => eand\n              | pOr => eor\n              | pNot => enot\n              | pLt => elt\n              | pValEq => eeq\n\tend.\n\n\tGlobal Instance RSym_JavaFunc : SymI.RSym java_func := {\n\t  typeof_sym := typeof_java_func;\n\t  symD := java_func_symD;\n\t  sym_eqb := java_func_eq\n\t}.\n\n\tGlobal Instance RSymOk_JavaFunc : SymI.RSymOk RSym_JavaFunc.\n\tProof.\n\t\tsplit; intros.\n\t\tdestruct a, b; simpl; try apply I; try reflexivity.\n\tQed.\t\t\n\n\nDefinition func := (SymEnv.func + @ilfunc typ + @bilfunc typ + \n                    @base_func typ RType_typ + @list_func typ + @open_func typ _ _ + \n                    @embed_func typ + @later_func typ + java_func)%type.\n\n\nNotation pProg P := (Inj (inl (inl (inl (inl (inl (inr (pConst tyProg P)))))))).\nNotation pMethod M := (Inj (inl (inl (inl (inl (inl (inr (pConst tyMethod M)))))))).\n\nSection MakeJavaFunc.\n\n\tDefinition mkVal v : expr typ func := Inj (inl (inl (inl (inl (inl (inr (pConst tyVal v))))))).\n\tDefinition mkProg P : expr typ func := pProg P.\n\tDefinition mkMethod M : expr typ func := pMethod M.\n\tDefinition mkCmd c : expr typ func := Inj (inl (inl (inl (inl (inl (inr (pConst tyCmd c))))))).\n\tDefinition mkDExpr e : expr typ func := Inj (inl (inl (inl (inl (inl (inr (pConst tyDExpr e))))))).\n\tDefinition mkFields fs : expr typ func := Inj (inl (inl (inl (inl (inl (inr (pConst (tyList tyString) fs))))))).\n\n\tDefinition fMethodSpec : expr typ func := Inj (inr pMethodSpec).\n\tDefinition fProgEq : expr typ func := Inj (inr pProgEq).\n\tDefinition fTriple : expr typ func := Inj (inr pTriple).\n\tDefinition fTypeOf : expr typ func := Inj (inr pTypeOf).\n\tDefinition fFieldLookup : expr typ func := Inj (inr pFieldLookup).\n\tDefinition fMethodLookup : expr typ func := Inj (inr pMethodLookup).\n\tDefinition fPointsto : expr typ func := Inj (inr pPointsto).\n\tDefinition mkNull : expr typ func := Inj (inr pNull).\n\n\tDefinition fMethodBody : expr typ func := Inj (inr pMethodBody).\n\tDefinition fMethodArgs : expr typ func := Inj (inr pMethodArgs).\n\tDefinition fMethodRet : expr typ func := Inj (inr pMethodRet).\t\n\t\n\tDefinition fPlus : expr typ func := Inj (inr pPlus).\n\tDefinition fMinus : expr typ func := Inj (inr pMinus).\n\tDefinition fTimes : expr typ func := Inj (inr pTimes).\n\tDefinition fAnd : expr typ func := Inj (inr pAnd).\n\tDefinition fOr : expr typ func := Inj (inr pOr).\n\tDefinition fNot : expr typ func := Inj (inr pNot).\n\tDefinition fLt : expr typ func := Inj (inr pLt).\n\tDefinition fValEq : expr typ func := Inj (inr pValEq).\n\n\tDefinition mkTriple P c Q : expr typ func := App (App (App fTriple P) Q) c.\n\tDefinition mkFieldLookup P C f : expr typ func := App (App (App fFieldLookup P) C) f.\n\tDefinition mkTypeOf C x : expr typ func := App (App fTypeOf C) x.\n\tDefinition mkProgEq P := App fProgEq P.\n\t\n\tDefinition mkMethodBody (M : Method) : expr typ func := App fMethodBody (mkMethod M).\n\tDefinition mkMethodArgs (M : Method) : expr typ func := App fMethodArgs (mkMethod M).\n\tDefinition mkMethodRet (M : Method) : expr typ func := App fMethodRet (mkMethod M).\n\t\n\tDefinition mkExprList es :=\n\t\t(fold_right (fun (e : dexpr) (acc : expr typ func) => \n\t\t\tmkCons tyExpr (mkDExpr e) acc) (mkNil tyExpr) es).\n\t\n\tFixpoint evalDExpr (e : dexpr) : expr typ func :=\n\t\tmatch e with\n\t\t\t| E_val v => mkConst tyVal (mkVal v)\n\t\t\t| E_var x => App (fStackGet (func := expr typ func)) (mkString (func := func) x)\n\t\t\t| E_plus e1 e2 => mkAps fPlus ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_minus e1 e2 => mkAps fMinus ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_times e1 e2 => mkAps fTimes ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_and e1 e2 => mkAps fAnd ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_or e1 e2 => mkAps fOr ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_not e => mkAps fNot ((evalDExpr e, tyVal)::nil) tyVal\n\t\t\t| E_lt e1 e2 => mkAps fLt ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_eq e1 e2 => mkAps fValEq ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\tend.\n\n\nEnd MakeJavaFunc.\n\nRequire Import Java.Examples.ListModel.\n\n\nClass Environment := { java_env :> @SymEnv.functions typ _}.\n\nSection JavaFunc.\n\n  Context {fs : Environment}.\n\n(* This needs to be parametric. It shouldn't be here \nDefinition fs : @SymEnv.functions typ _ :=\n  SymEnv.from_list\n  \t(@SymEnv.F typ _ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) List::\n  \t @SymEnv.F typ _ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) NodeList::nil). \n\n*)\nCheck RSym.\n\n  Global Instance RSym_ilfunc : RSym (@ilfunc typ) := \n\t  RSym_ilfunc ilops.\n  Global Instance RSym_bilfunc : RSym (@bilfunc typ) := \n\t  RSym_bilfunc _ bilops.\n  Global Instance RSym_embed_func : RSym (@embed_func typ) :=\n\t  RSym_embed_func _ eops.\n  Global Instance RSym_later_func : RSym (@later_func typ) :=\n\t  RSym_later_func _ lops.\n(*\n  Global Instance RelDec_func : RelDec (@eq func).\n  repeat apply RelDec_eq_pair; try apply _.\n  apply _.\n*)\n  Global Instance RSym_open_func : RSym (@open_func typ _ _) :=\n\t  @RSym_OpenFunc _ _ _ RType_typ _ _ _ _ _ _ _ _.\n\n  Global Existing Instance RSym_sum.\n  Global Existing Instance RSymOk_sum.\n\n  Global Instance RSym_func : RSym func.\n    repeat (apply RSym_sum; [|apply _]).\n    apply RSym_sum; [|apply (RSym_BaseFunc (edt := edt))].\n    repeat (apply RSym_sum; [|apply _]).\n    apply (RSym_func java_env).\n  Defined.\n  \n  Global Instance RSymOk_func : RSymOk RSym_func.\n  Proof.\n    repeat (apply RSymOk_sum); try apply _.\n    apply (RSymOk_BaseFunc (edtOk := edtOk)).\n  Qed.\n\n  Global Instance Expr_expr : ExprI.Expr _ (expr typ func) := @Expr_expr typ func _ _ _.\n  Global Instance Expr_ok : @ExprI.ExprOk typ RType_typ (expr typ func) Expr_expr := ExprOk_expr.\n\n  Require Import MirrorCore.VariablesI.\n  Require Import MirrorCore.Lambda.ExprVariables.\n\n  Global Instance ExprVar_expr : ExprVar (expr typ func) := _.\n  Global Instance ExprVarOk_expr : ExprVarOk ExprVar_expr := _.\n\n  Global Instance ExprUVar_expr : ExprUVar (expr typ func) := _.\n  Global Instance ExprUVarOk_expr : ExprUVarOk ExprUVar_expr := _.\n\n  Definition subst : Type :=\n    FMapSubst.SUBST.raw (expr typ func).\n  Global Instance SS : SubstI.Subst subst (expr typ func) :=\n    @FMapSubst.SUBST.Subst_subst _.\n  Global Instance SU : SubstI.SubstUpdate subst (expr typ func) :=\n    @FMapSubst.SUBST.SubstUpdate_subst _ _. \n  Global Instance SO : SubstI.SubstOk SS := \n    @FMapSubst.SUBST.SubstOk_subst typ RType_typ (expr typ func) _ _.\n  Global Instance SUO :SubstI.SubstUpdateOk SU SO :=  @FMapSubst.SUBST.SubstUpdateOk_subst typ RType_typ (expr typ func) _ _ _.\n\n  Global Instance MA : MentionsAny (expr typ func) := {\n    mentionsAny := ExprCore.mentionsAny\n  }.\n\n  Global Instance MAOk : MentionsAnyOk MA _ _.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma evalDexpr_wt (e : dexpr) : \n\t  typeof_expr nil nil (evalDExpr e) = Some tyExpr.\n  Proof.\n    induction e.\n    + simpl; reflexivity.\n    + simpl; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n  Qed.\n\n  Definition is_pure (e : expr typ func) : bool :=\n\tmatch e with\n\t  | App f P => match embedS f with\n\t\t\t\t     | Some (eilf_embed tyPure tySasn) => true\n\t\t\t\t\t | Some (eilf_embed tyProp tySasn) => true\n\t\t\t\t\t | _ => false\n\t\t\t\t   end\n\t\t\t\n \t  | e =>\n \t\tmatch ilogicS e with\n \t\t  | Some (ilf_true _) => true\n \t\t  | Some (ilf_false _) => true\n \t\t  | _ => false\n \t\tend\n   end.\n\n  Definition mkPointstoVar x f e : 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                      (App fStackGet (mkString x)))\n                (mkConst tyString (mkString f)))\n          e.\n\n  Definition test_lemma :=\n    @lemmaD typ (expr typ func) RType_typ Expr_expr (expr typ func)\n            (fun tus tvs e => exprD' tus tvs tyProp e)\n            _\n            nil nil.\nEnd JavaFunc.", "meta": {"author": "jesper-bengtson", "repo": "Java", "sha": "bc889ae914e1ba39b2f4d0edcb63371ffd52a5dd", "save_path": "github-repos/coq/jesper-bengtson-Java", "path": "github-repos/coq/jesper-bengtson-Java/Java-bc889ae914e1ba39b2f4d0edcb63371ffd52a5dd/Java/src/Java/Func/JavaFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1980516930153985}}
{"text": "From mathcomp.ssreflect Require Import ssreflect ssrnat seq eqtype ssrbool ssrfun. \nFrom mathcomp.algebra Require Import ssrint ssralg.\nFrom Coq.Strings Require Import Ascii String.\nRequire Import Program.Basics.\nRequire Import UtilString.\nImport intZmod.       \nRequire Import Syntax Common Types Memory.\n\n\n       \nInductive get_query := Get t:  nat-> ptr t-> int -> ptr t -> nat -> get_query .\nInductive put_query := Put t: value -> ptr t -> nat -> put_query .\n\n    Theorem put_query_eq_dec: eq_dec put_query.\n      rewrite /eq_dec.\n      move=> x y; case x; case y.\n      move=> t v p n t0 v0 p0 n0.\n      move: (ctype_eq_dec t0 t)=> [Heqt|Heqt].\n        move: (value_eq_dec v0 v) => [Heqv|Heqv];\n        move: (nat_eq_dec n0 n) => [Heqn|Heqn]; subst; try\n      move: (ptr_eq_dec _ p0 p) => [Heqp|Heqp]; try by [right;case].\n      subst; by left.\n      right.\n      case.\n      move=> H.\n        by depcomp H.\n      move: (nat_eq_dec n0 n) => [Hn|Hn]; by [right; case | done].      \n    Defined.\n    \n    Definition put_query_eqP := reflect_from_dec put_query_eq_dec.\n    \n    Canonical put_query_eqMixin := EqMixin put_query_eqP.\n    Canonical put_query_eqType := EqType put_query put_query_eqMixin.\n\n  \n\nInductive push_query := Push: anyptr -> nat -> push_query.\nInductive pop_query := Pop: anyptr -> pop_query.\n\n\nRecord proc_state := mk_proc_state {\n                         proc_id : nat;\n                         proc_symbols : seq (seq var_descr);\n                         proc_queue_get: seq get_query;\n                         proc_queue_put: seq ( seq put_query );\n                         proc_queue_pop_reg: seq pop_query;\n                         proc_queue_push_reg: seq push_query;\n                         proc_memory: seq block;\n                         proc_conts: seq statement;\n                         proc_registered_locs: seq ( anyptr * nat )                         \n                       }.\nDefinition ps_mod_f\n           mod_syms    \n           mod_queue_get \n           mod_queue_put \n           mod_queue_pop \n           mod_queue_push\n           mod_memory    \n           mod_conts     \n           mod_reg_locs  \n           (ps: proc_state) : proc_state :=\n  mk_proc_state\n    (proc_id ps)\n    (mod_syms ps)\n    (mod_queue_get ps)\n    (mod_queue_put ps)\n    (mod_queue_pop ps)\n    (mod_queue_push ps)\n    (mod_memory ps)\n    (mod_conts ps)\n    (mod_reg_locs ps)\n.\n\nDefinition ps_mod\n           mod_syms    \n           mod_queue_get \n           mod_queue_put \n           mod_queue_pop \n           mod_queue_push\n           mod_memory  \n           mod_conts   \n           mod_reg_locs : proc_state -> proc_state :=\n  ps_mod_f\n    (mod_syms \\o proc_symbols)\n    (mod_queue_get \\o proc_queue_get)\n    (mod_queue_put \\o proc_queue_put)\n    (mod_queue_pop \\o proc_queue_pop_reg)\n    (mod_queue_push \\o proc_queue_push_reg)\n    (mod_memory \\o proc_memory)\n    (mod_conts \\o proc_conts)\n    (mod_reg_locs \\o proc_registered_locs).\n\nDefinition ps_mod_syms       f := ps_mod f  id id id id id id id.\nDefinition ps_mod_queue_get  f := ps_mod id f  id id id id id id.\nDefinition ps_mod_queue_put  f := ps_mod id id f  id id id id id.\nDefinition ps_mod_queue_pop  f := ps_mod id id id f  id id id id.\nDefinition ps_mod_queue_push f := ps_mod id id id id f  id id id.\nDefinition ps_mod_mem        f := ps_mod id id id id id f  id id.\nDefinition ps_mod_cont       f := ps_mod id id id id id id f  id.\nDefinition ps_mod_reg_loc    f := ps_mod id id id id id id id f .\n\n\nInductive error_code := | OK | BadPointer | ModNonExistingBlock | PointerOutsideBlock| BadWriteLocation | TypeMismatch | WritingGarbage | NonExistingSymbol | GenericError | InvalidPopReg | InvalidPushReg | InvalidGet | InvalidPut.\nScheme Equality for error_code.\nCanonical error_code_eqMixin := EqMixin (reflect_from_dec error_code_eq_dec).\nCanonical error_code_eqType := EqType error_code error_code_eqMixin.\n\n\n\nInductive machine_state :=\n| MGood: seq proc_state -> seq function -> machine_state\n| MBad:  seq ((error_code * option statement) * proc_state) -> seq function -> machine_state\n| MNeedSync: seq( seq (seq put_query) )-> seq proc_state -> seq function -> machine_state.\n\nDefinition ms_source s := match s with | MGood _ f | MBad  _  f | MNeedSync _ _ f => f end.\nDefinition ms_procs s := match s with | MGood p _ | MNeedSync _ p _ => p | MBad  p _ => map snd p end.\n\nDefinition proc_state_empty:= @nil (seq var_descr).\n\n\nDefinition get_var (ps:proc_state) (name:string) : option var_descr :=\n  option_find (fun p: var_descr => var_name p == name) (flatten (proc_symbols ps)).\n\nDefinition get_fun (s:machine_state) (name:string) : option function :=\n         option_find (fun p: function => fun_name p == name) $ ms_source s.\n\n\nDefinition add_var (vd: var_descr) := ps_mod_syms\n                                        (fun s=> match s with\n                                                   | nil => cons [::vd] nil\n                                                   | cons x xs => cons (cons vd x) xs\n                                                 end).\n\n\n\n\nDefinition ms_mod_proc_all (f:proc_state->proc_state) (ms:machine_state) :=\n  match ms with\n    | MNeedSync q ps fs => MNeedSync q (map f ps) fs \n    | MGood ps fs  => MGood (map f ps) fs\n    | MBad _ _ =>  ms\n  end.\n\nDefinition ms_mod_proc_all_or_fail (f:proc_state->proc_state ?) (ms:machine_state) :=\n\n  match ms with\n    | MNeedSync q ps fs =>   let newprocs := seq_unsome (map f ps) in\n                             option_map (fun p => MNeedSync q p fs) newprocs\n    | MGood ps fs  =>   let newprocs := seq_unsome (map f ps) in\n                              option_map (fun p => MGood p fs) newprocs\n                              | MBad _ _ =>  None\n  end.\n\n\nDefinition ms_for_proc {T} (ms:machine_state) (pid:nat) (f: proc_state -> T) : T? :=\n  option_map f $  option_nth (ms_procs ms) pid.\n\n  \nDefinition ms_mod_proc (pid:nat) (f:proc_state->proc_state) : machine_state->machine_state :=\n  ms_mod_proc_all (fun p=> if proc_id p == pid then f p else p).\n\n\nDefinition can_write (b:block) (i:nat) (v:value) : error_code :=\n  match option_nth (contents b) i, v with\n    | Some Garbage, val => if el_type b == type_of_val val then OK else TypeMismatch\n    | Some Deallocated, _ => BadWriteLocation\n    | Some _, Deallocated => WritingGarbage\n    | Some _, Error => GenericError\n    | Some _, Garbage => WritingGarbage\n    | Some Error, _ => GenericError\n    | None, _ => BadWriteLocation\n    | Some vx, vy  => if (el_type b == type_of_val vy) && (el_type b == type_of_val vx) then OK else TypeMismatch\n  end.\nDefinition ErrorBlock := mk_block Data 0 0 ErrorType [::].\n\n\nDefinition mem_write  (bid:nat) (pos: nat) (val:value) (ps: proc_state): (error_code * proc_state) :=\n  let m := proc_memory ps in\n  let oldblock := option_nth m bid in\n  match oldblock with\n    | Some oldblock =>\n      let err_code_write := can_write oldblock pos val in\n      if err_code_write == OK then\n        let newblockcnt := set_nth val (contents oldblock) pos val in\n        let newblock := block_mod_cont (const newblockcnt) oldblock in\n        let newmem := set_nth ErrorBlock m bid newblock in\n        (OK, ps_mod_mem (const newmem) ps)\n      else (err_code_write , ps)\n    | None => (ModNonExistingBlock, ps)\n  end.\n\nDefinition mem_mod_block (bid:nat) (f:block->block) (ps:proc_state) : proc_state :=\n  ps_mod_mem (mod_at ErrorBlock bid f) ps.\n\nDefinition mem_fill_block (bid:nat) (val:value) (ps: proc_state): proc_state :=\n  let block_trans := block_mod id id id match val with\n                         | Garbage \n                         | Deallocated \n                         | Error => id\n                         | x =>  const $ type_of_val x \n                       end (map (const val))\n  in\n  mem_mod_block bid block_trans ps.\n\n(*** Tests ***)\nModule Tests.\n  Require Import TestUtils.\n  Definition sample_block s := mk_block Data 0 s Int64 $ fill (ValueI64 0) s.\n  Definition ps s :proc_state := mk_proc_state 0 nil nil nil nil nil [:: sample_block s ] nil nil .\n  Check assert_eq _:  mem_fill_block 0 (ValueI32 11) ( ps 2 )= {|\n       proc_id := 0;\n       proc_symbols := [::];\n       proc_queue_get := [::];\n       proc_queue_put := [::];\n       proc_queue_pop_reg := [::];\n       proc_queue_push_reg := [::];\n       proc_memory := [:: {|\n                          region := Data;\n                          block_id := 0;\n                          block_size := 2;\n                          el_type := Int S32;\n                          contents := [:: ValueI32 11; ValueI32 11] |}];\n       proc_conts := [::];\n       proc_registered_locs := [::] |}.\n\n  Check assert_eq _ : mem_fill_block 0 (ValueI32 11) (ps 2) = {|\n       proc_id := 0;\n       proc_symbols := [::];\n       proc_queue_get := [::];\n       proc_queue_put := [::];\n       proc_queue_pop_reg := [::];\n       proc_queue_push_reg := [::];\n       proc_memory := [:: {|\n                          region := Data;\n                          block_id := 0;\n                          block_size := 2;\n                          el_type := Int S32;\n                          contents := [:: ValueI32 11; ValueI32 11] |}];\n       proc_conts := [::];\n       proc_registered_locs := [::] |}.\n\n  \nEnd Tests.\n\n\n\n\n(* TODO: handle byte sizes instead of elements' counts *)", "meta": {"author": "sayon", "repo": "mini-c", "sha": "802cd66231053b9835ad83794ebd364224839432", "save_path": "github-repos/coq/sayon-mini-c", "path": "github-repos/coq/sayon-mini-c/mini-c-802cd66231053b9835ad83794ebd364224839432/bsp/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.19801616467613642}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\n\n(* Borrow from CompCert *)\nRequire Import Coqlib.\nRequire Import Bitvectors.\n\nRequire Import AST.\nRequire Import Semantics.\nRequire Import Utils.\nRequire Import Builtins.\nRequire Import BuiltinSem.\nRequire Import Values.        \n\nRequire Import EvalTac.\nRequire Import SplitTest.\n\nLemma eval_c :\n  eval_expr ge empty c (bits (v 3)).\nProof.\n  g.\n  e. e. e. e. e. g.\n  e. e. e. e. e. e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. repeat e. e.\n  repeat e.\n  e. e. e. e. g.\n  e. e. e. repeat e. e.\n  repeat e. \n  e. e. e. e.\n  e. e. e. e. e. e.\n  e. e. e. e. g.\n  e. e. e. e. e. e. e. e.\n  e. e. repeat e. e.\n  eapply select_split. e. reflexivity.\n  simpl. reflexivity.\n  e. e. e. g.\n  e. e. e. e. e. e. e. e.\n  e.\n  e. repeat e.\n  e. eapply select_slice.\n  repeat e. reflexivity.\n  simpl. repeat e.\n  Unshelve.\n  all: try exact nz; simpl; unfold Pos.to_nat; simpl; try congruence.\nQed.  \n  ", "meta": {"author": "GaloisInc", "repo": "cryptol-semantics", "sha": "b4d8b55ec9b3b796427eb9e270e73e1857c597bf", "save_path": "github-repos/coq/GaloisInc-cryptol-semantics", "path": "github-repos/coq/GaloisInc-cryptol-semantics/cryptol-semantics-b4d8b55ec9b3b796427eb9e270e73e1857c597bf/.old/SplitTestC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19799956543742508}}
{"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 SeqLiftStep.\nRequire Import SeqLiftCertification.\nRequire Import SeqLiftInterference.\nRequire Import DelayedSimulation.\nRequire Import SequentialRefinement.\nRequire Import Sequential.\n\nRequire Import Pred.\n\nRequire Import SimAux.\nRequire Import FlagAux.\nRequire Import SeqAux.\nRequire Import NoMix.\n\nVariant initial_finalized: Messages.t :=\n  | initial_finalized_intro\n      loc\n    :\n    initial_finalized loc Time.bot Time.bot Message.elt\n.\n\nLemma configuration_initial_finalized s\n  :\n  finalized (Configuration.init s) = initial_finalized.\nProof.\n  extensionality loc.\n  extensionality from.\n  extensionality to.\n  extensionality msg.\n  apply Coq.Logic.PropExtensionality.propositional_extensionality.\n  split; i.\n  { inv H. ss. unfold Memory.init, Memory.get in GET.\n    rewrite Cell.init_get in GET. des_ifs. }\n  { inv H. econs; eauto. i. ss. unfold Threads.init in *.\n    rewrite IdentMap.Facts.map_o in TID. unfold option_map in *. des_ifs.\n  }\nQed.\n\nDefinition initial_mapping: Mapping.t :=\n  Mapping.mk\n    (fun v ts =>\n       if PeanoNat.Nat.eq_dec v 0 then\n         if (Time.eq_dec ts Time.bot) then Some (Time.bot)\n         else None\n       else None)\n    0\n    (fun v ts => v = 0 /\\ ts = Time.bot)\n.\n\nDefinition initial_mappings: Mapping.ts :=\n  fun _ => initial_mapping.\n\nLemma initial_mapping_wf:\n  Mapping.wf initial_mapping.\nProof.\n  econs.\n  { i. ss. exists ([(Time.bot, Time.bot)]).\n    i. des_ifs. ss. auto.\n  }\n  { i. ss. des_ifs. }\n  { i. ss. des_ifs.\n    { esplits; eauto. refl. }\n    { exfalso. lia. }\n  }\n  { i. ss. des_ifs. exfalso. lia. }\n  { ss. }\n  { i. ss. exists [Time.bot]. i. des; subst. ss. auto. }\n  { i. ss. des; subst. splits; auto. lia. }\n  { ss. ii. des. lia. }\n  { ss. }\nQed.\n\nLemma initial_mappings_wf:\n  Mapping.wfs initial_mappings.\nProof.\n  ii. eapply initial_mapping_wf.\nQed.\n\nDefinition initial_ver: version := fun _ => 0.\n\nDefinition initial_vers: versions :=\n  fun loc ts =>\n    if (Time.eq_dec ts Time.bot) then Some initial_ver else None.\n\nLemma initial_version_wf\n  :\n  version_wf initial_mappings initial_ver.\nProof.\n  ii. ss.\nQed.\n\nLemma initial_versions_wf:\n  versions_wf initial_mappings initial_vers.\nProof.\n  ii. unfold initial_vers. des_ifs.\n  ss. eapply initial_version_wf.\nQed.\n\nLemma initial_sim_timestamp_exact\n  :\n  sim_timestamp_exact initial_mapping 0 Time.bot Time.bot.\nProof.\n  ss.\nQed.\n\nLemma initial_time_closed\n  :\n  Mapping.closed initial_mapping 0 Time.bot.\nProof.\n  ss.\nQed.\n\nLemma initial_sim_timestamp\n  :\n  sim_timestamp initial_mapping 0 Time.bot Time.bot.\nProof.\n  red. esplits.\n  { refl. }\n  { refl. }\n  { eapply initial_sim_timestamp_exact. }\n  { eapply initial_time_closed. }\nQed.\n\nLemma initial_sim_timemap L:\n  sim_timemap L initial_mappings initial_ver TimeMap.bot TimeMap.bot.\nProof.\n  ii. eapply initial_sim_timestamp.\nQed.\n\nLemma initial_sim_view L:\n  sim_view L initial_mappings initial_ver View.bot View.bot.\nProof.\n  econs.\n  { eapply initial_sim_timemap. }\n  { eapply initial_sim_timemap. }\nQed.\n\nLemma initial_sim_tview:\n  sim_tview initial_mappings (fun _ => false) (fun _ => initial_ver) TView.bot TView.bot.\nProof.\n  econs.\n  { i. eapply initial_sim_view. }\n  { i. eapply initial_sim_view. }\n  { i. eapply initial_sim_view. }\n  { i. eapply initial_version_wf. }\nQed.\n\nLemma initial_sim_promises:\n  sim_promises TimeMap.bot (fun _ => false) (fun _ => false) initial_mappings initial_vers Memory.bot Memory.bot.\nProof.\n  econs.\n  { i. rewrite Memory.bot_get in GET. ss. }\n  { i. rewrite Memory.bot_get in GET. ss. }\n  { i. ss. }\nQed.\n\nLemma initial_sim_local\n  :\n  sim_local initial_mappings initial_vers TimeMap.bot (fun _ => false) (fun _ => false) Local.init Local.init.\nProof.\n  econs.\n  { eapply initial_sim_tview. }\n  { eapply initial_sim_promises. }\n  { econs. i. rewrite Memory.bot_get in GET. ss. }\n  { i. ss. }\n  { i. ss. }\nQed.\n\nLemma initial_sim_message loc\n  :\n  sim_message false loc initial_mappings (Some initial_ver) Message.elt Message.elt.\nProof.\n  econs; ss. econs.\nQed.\n\nLemma initial_sim_memory\n  :\n  sim_memory_interference initial_mappings initial_vers Memory.init Memory.init.\nProof.\n  econs.\n  { i. eapply memory_init_get_if in GET. des; clarify. esplits.\n    { ss. }\n    { ss. }\n    { eapply initial_sim_message. }\n    { i. eapply initial_time_closed. }\n  }\n  { i. eapply memory_init_get_if in GET. des; clarify. esplits.\n    { refl. }\n    { refl. }\n    { left. splits; eauto. }\n    { eapply initial_sim_timestamp_exact. }\n    { i. inv ITV. ss. timetac. }\n  }\nQed.\n\nLemma initial_versioned_memory\n  :\n  versioned_memory initial_vers Memory.init.\nProof.\n  econs.\n  { i. eapply memory_init_get_if in GET. des; clarify. }\n  { i. unfold initial_vers in VER. des_ifs. esplits.\n    { eapply memory_init_get. }\n    { ss. }\n  }\nQed.\n\nLemma initial_sim_closed_memory\n  :\n  sim_closed_memory initial_mappings Memory.init.\nProof.\n  ii. ss. des; subst. esplits. eapply memory_init_get.\nQed.\n\nLemma initial_max_readable loc\n  :\n  max_readable Memory.init Memory.bot loc Time.bot Const.undef None.\nProof.\n  econs.\n  { eapply memory_init_get. }\n  { rewrite Memory.bot_get. auto. }\n  { i. eapply memory_init_get_if in GET. des; clarify. timetac. }\nQed.\n\nLemma initial_sim_thread\n  :\n  SeqLiftStep.sim_thread\n    initial_mappings initial_vers\n    (fun _ => false) (fun _ => false)\n    (fun _ => Some Const.undef) (fun _ => Some Const.undef)\n    Memory.init Memory.init Local.init Local.init TimeMap.bot TimeMap.bot.\nProof.\n  econs.\n  { eapply initial_sim_timemap. }\n  { eapply sim_memory_interference_sim_memory; ss. eapply initial_sim_memory. }\n  { eapply initial_sim_local. }\n  { ii. econs.\n    { i. clarify. esplits. eapply initial_max_readable. }\n    { i. ss. }\n  }\n  { ii. econs.\n    i. clarify. esplits. eapply initial_max_readable.\n  }\n  { ss. }\n  { exists []. splits. i. split; i; des; ss. }\n  { eapply initial_versioned_memory. }\n  { eapply initial_sim_closed_memory. }\n  { i. ss. }\n  { ii. ss. }\n  { ii. ss. erewrite Memory.bot_get in GETSRC. ss. }\nQed.\n\nRequire Import Program.\n\nModule CertOracle.\n  Definition t := Loc.t -> Const.t.\n\n  Definition output (e: ProgramEvent.t): Oracle.output :=\n    Oracle.mk_output\n      (if is_accessing e then Some Perm.high else None)\n      (if is_acquire e then Some (fun _ => Perm.low, fun _ => Const.undef) else None)\n      (if is_release e then Some (fun _ => Perm.high) else None)\n  .\n\n  Variant step (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (vs: t): t -> Prop :=\n    | step_read\n        loc ord\n        (EVENT: e = ProgramEvent.read loc (vs loc) ord)\n        (INPUT: Oracle.wf_input e i)\n        (OUTPUT: o = output e)\n      :\n      step e i o vs vs\n    | step_write\n        loc val ord\n        (EVENT: e = ProgramEvent.write loc val ord)\n        (INPUT: Oracle.wf_input e i)\n        (OUTPUT: o = output e)\n      :\n      step e i o vs (fun loc0 => if Loc.eq_dec loc0 loc then val else vs loc0)\n    | step_update\n        loc valw ordr ordw\n        (EVENT: e = ProgramEvent.update loc (vs loc) valw ordr ordw)\n        (INPUT: Oracle.wf_input e i)\n        (OUTPUT: o = output e)\n      :\n      step e i o vs (fun loc0 => if Loc.eq_dec loc0 loc then valw else vs loc0)\n    | step_fence\n        ordr ordw\n        (EVENT: e = ProgramEvent.fence ordr ordw)\n        (INPUT: Oracle.wf_input e i)\n        (OUTPUT: o = output e)\n      :\n      step e i o vs vs\n    | step_syscall\n        ev\n        (EVENT: e = ProgramEvent.syscall ev)\n        (INPUT: Oracle.wf_input e i)\n        (OUTPUT: o = output e)\n      :\n      step e i o vs vs\n  .\n\n  Definition to_oracle (vs: t): Oracle.t := @Oracle.mk t step vs.\n\n  Lemma to_oracle_wf vs: Oracle.wf (to_oracle vs).\n  Proof.\n    revert vs. pcofix CIH. i. pfold. econs.\n    { i. dependent destruction STEP. inv STEP.\n      { splits; auto. red. splits; ss; des_ifs. }\n      { splits; auto. red. splits; ss; des_ifs. }\n      { splits; auto. red. splits; ss; des_ifs. }\n      { splits; auto. red. splits; ss; des_ifs. }\n      { splits; auto. red. splits; ss; des_ifs. }\n    }\n    { i. exists (vs loc). splits.\n      { econs. esplits.\n        { econs. eapply step_read; eauto. }\n        { red. splits; ss; des_ifs. }\n      }\n      { i. econs. esplits.\n        { econs. eapply step_update; eauto. }\n        { red. splits; ss; des_ifs. }\n      }\n    }\n    { i. econs. esplits.\n      { econs. eapply step_write; eauto. }\n      { red. splits; ss; des_ifs. }\n    }\n    { i. econs. esplits.\n      { econs. eapply step_fence; eauto. }\n      { red. splits; ss; des_ifs. }\n    }\n    { i. econs. esplits.\n      { econs. eapply step_syscall; eauto. }\n      { red. splits; ss; des_ifs. }\n    }\n  Qed.\nEnd CertOracle.\n\n\nSection LIFT.\n  Variable loc_na: Loc.t -> Prop.\n  Variable loc_at: Loc.t -> Prop.\n  Hypothesis LOCDISJOINT: forall loc (NA: loc_na loc) (AT: loc_at loc), False.\n\n  Definition sim_seq_interference lang_src lang_tgt sim_terminal p0 D st_src st_tgt :=\n    forall p1 (PERM: Perms.le p1 p0),\n      @sim_seq lang_src lang_tgt sim_terminal p1 D st_src st_tgt.\n\n  Lemma sim_seq_interference_mon lang_src lang_tgt sim_terminal p0 D st_src st_tgt\n        (SIM: @sim_seq_interference _ _ sim_terminal p0 D st_src st_tgt)\n        p1 (PERM: Perms.le p1 p0)\n    :\n    @sim_seq_interference lang_src lang_tgt sim_terminal p1 D st_src st_tgt.\n  Proof.\n    ii. eapply SIM. etrans; eauto.\n  Qed.\n\n  Lemma sim_seq_interference_sim_seq lang_src lang_tgt sim_terminal p D st_src st_tgt\n        (SIM: @sim_seq_interference _ _ sim_terminal p D st_src st_tgt)\n    :\n    @sim_seq lang_src lang_tgt sim_terminal p D st_src st_tgt.\n  Proof.\n    eapply SIM. refl.\n  Qed.\n\n  Lemma perm_antisym p0 p1\n        (LE0: Perm.le p0 p1)\n        (LE1: Perm.le p1 p0)\n    :\n    p0 = p1.\n  Proof.\n    destruct p0, p1; ss.\n  Qed.\n\n  Lemma perms_antisym p0 p1\n        (LE0: Perms.le p0 p1)\n        (LE1: Perms.le p1 p0)\n    :\n    p0 = p1.\n  Proof.\n    extensionality loc. eapply perm_antisym; eauto.\n  Qed.\n\n  Definition perms_top: Perms.t := fun _ => Perm.high.\n\n  Definition seq_memory_init: SeqMemory.t := (SeqMemory.mk (fun _ => Const.undef) Flags.bot).\n\n  Lemma sim_seq_init lang_src lang_tgt sim_terminal st_src st_tgt\n        (SIM: @sim_seq_all lang_src lang_tgt sim_terminal st_src st_tgt)\n    :\n    sim_seq_interference\n      _ _ sim_terminal\n      perms_top Flags.bot\n      (SeqState.mk _ st_src seq_memory_init)\n      (SeqState.mk _ st_tgt seq_memory_init).\n  Proof.\n    ii. eapply SIM.\n  Qed.\n\n  Definition world := (Mapping.ts * versions * Memory.t)%type.\n\n  Definition world_bot: world := (fun _ => initial_mapping, initial_vers, Memory.init).\n\n  Definition sim_seq_cond (c: bool)\n             lang_src lang_tgt sim_terminal p D st_src st_tgt :=\n    if c\n    then @sim_seq lang_src lang_tgt sim_terminal p D st_src st_tgt\n    else @sim_seq_interference lang_src lang_tgt sim_terminal p D st_src st_tgt.\n\n  Definition world_messages_le (msgs_src msgs_tgt: Messages.t) (w0: world) (w1: world): Prop :=\n        match w0, w1 with\n        | (f0, vers0, mem_src0), (f1, vers1, mem_src1) =>\n            forall (WF: Mapping.wfs f0),\n              (<<MAPLE: Mapping.les f0 f1>>) /\\ (<<VERLE: versions_le vers0 vers1>>) /\\\n                (<<MEMSRC: Memory.future_weak mem_src0 mem_src1>>) /\\\n                (<<FUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n                (<<WF: Mapping.wfs f1>>) /\\\n                (<<SPACE: space_future_memory msgs_tgt f0 mem_src0 f1 mem_src1>>)\n        end\n  .\n\n  Global Program Instance world_messages_le_PreOrder msgs_src msgs_tgt: PreOrder (world_messages_le msgs_src msgs_tgt).\n  Next Obligation.\n    unfold world_messages_le. ii. des_ifs. splits.\n    { refl. }\n    { refl. }\n    { refl. }\n    { eapply map_future_memory_refl. }\n    { auto. }\n    { eapply space_future_memory_refl; eauto. refl. }\n  Qed.\n  Next Obligation.\n    unfold world_messages_le. ii. des_ifs. i.\n    hexploit H; eauto. i. des.\n    hexploit H0; eauto. i. des.\n    splits.\n    { etrans; eauto. }\n    { etrans; eauto. }\n    { etrans; eauto. }\n    { eapply map_future_memory_trans; eauto. }\n    { eauto. }\n    { eapply space_future_memory_trans; eauto. }\n  Qed.\n\n  Definition initial_world: world := (initial_mappings, initial_vers, Memory.init).\n\n  Lemma world_messages_le_mon:\n    forall msgs_src0 msgs_tgt0 msgs_src1 msgs_tgt1 w0 w1\n           (LE: world_messages_le msgs_src1 msgs_tgt1 w0 w1)\n           (MSGSRC: msgs_src0 <4= msgs_src1)\n           (MSGTGT: msgs_tgt0 <4= msgs_tgt1),\n      world_messages_le msgs_src0 msgs_tgt0 w0 w1.\n  Proof.\n    unfold world_messages_le. i. des_ifs. i.\n    hexploit LE; eauto. i. des. splits; auto.\n    eapply space_future_memory_mon_msgs; eauto.\n  Qed.\n\n  Definition sim_memory_lift: forall (w: world) (mem_src mem_tgt:Memory.t), Prop :=\n    fun w mem_src mem_tgt =>\n      match w with\n      | (f, vers, mem_src') =>\n          (<<MEMSRC: mem_src = mem_src'>>) /\\\n            (<<SIM: sim_memory_interference f vers mem_src mem_tgt>>) /\\\n            (<<VERSIONED: versioned_memory vers mem_tgt>>) /\\\n            (<<SIMCLOSED: sim_closed_memory f mem_src>>) /\\\n            (<<VERSWF: versions_wf f vers>>)\n      end.\n\n  Lemma initial_sim_memory_lift:\n    sim_memory_lift initial_world Memory.init Memory.init.\n  Proof.\n    ss. splits; auto.\n    { eapply initial_sim_memory. }\n    { eapply initial_versioned_memory. }\n    { eapply initial_sim_closed_memory. }\n    { eapply initial_versions_wf. }\n  Qed.\n\n  Definition sim_timemap_lift: forall (w: world) (tm_src: TimeMap.t) (tm_tgt: TimeMap.t), Prop :=\n    fun w tm_src tm_tgt =>\n      match w with\n      | (f, vers, _) =>\n          (<<SIM: sim_timemap (fun _ => True) f (Mapping.vers f) tm_src tm_tgt>>)\n      end.\n\n  Lemma initial_sim_timemap_lift:\n    sim_timemap_lift initial_world TimeMap.bot TimeMap.bot.\n  Proof.\n    ss. splits; auto.\n    eapply initial_sim_timemap.\n  Qed.\n\n  Variant sim_val_lift: forall\n      (p: Perm.t)\n      (sv_src: Const.t) (sv_tgt: Const.t)\n      (v_src: option Const.t) (v_tgt: option Const.t), Prop :=\n    | sim_val_lift_low\n        sv_src sv_tgt\n      :\n      sim_val_lift Perm.low sv_src sv_tgt None None\n    | sim_val_lift_high\n        sv_src sv_tgt v_src v_tgt\n        (VALSRC: Const.le sv_src v_src)\n        (VALTGT: Const.le v_tgt sv_tgt)\n      :\n      sim_val_lift Perm.high sv_src sv_tgt (Some v_src) (Some v_tgt)\n  .\n\n  Definition sim_vals_lift\n             (p: Perms.t) (svs_src: ValueMap.t) (svs_tgt: ValueMap.t)\n             (vs_src: Loc.t -> option Const.t) (vs_tgt: Loc.t -> option Const.t): Prop :=\n    forall loc (NA: loc_na loc), sim_val_lift (p loc) (svs_src loc) (svs_tgt loc) (vs_src loc) (vs_tgt loc).\n\n  Variant sim_flag_lift\n          (d: Flag.t) (sflag_src: Flag.t) (sflag_tgt: Flag.t)\n          (flag_src: bool) (flag_tgt: bool): Prop :=\n    | sim_flag_lift_intro\n        (TGT: Flag.le flag_tgt (Flag.join flag_src (Flag.join d sflag_tgt)))\n        (SRC: sflag_src = flag_src)\n  .\n\n  Definition sim_flags_lift\n             (d: Flags.t) (sflag_src: Flags.t) (sflag_tgt: Flags.t)\n             (flag_src: Loc.t -> bool) (flag_tgt: Loc.t -> bool): Prop :=\n    forall loc, sim_flag_lift (d loc) (sflag_src loc) (sflag_tgt loc) (flag_src loc) (flag_tgt loc).\n\n  Variant sim_state_lift c:\n    forall (w: world)\n           (smem_src: SeqMemory.t) (smem_tgt: SeqMemory.t)\n           (p: Perms.t)\n           (D: Flags.t)\n           (mem_src: Memory.t)\n           (mem_tgt: Memory.t)\n           (lc_src: Local.t)\n           (lc_tgt: Local.t)\n           (sc_src: TimeMap.t)\n           (sc_tgt: TimeMap.t), Prop :=\n    | sim_state_lift_intro\n        svs_src sflag_src svs_tgt sflag_tgt\n        p D f vers flag_src flag_tgt vs_src vs_tgt\n        mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n        (SIM: SeqLiftStep.sim_thread f vers flag_src flag_tgt vs_src vs_tgt mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n        (VALS: sim_vals_lift p svs_src svs_tgt vs_src vs_tgt)\n        (FLAGS: sim_flags_lift D sflag_src sflag_tgt flag_src flag_tgt)\n        (ATLOCS: forall loc (NNA: ~ loc_na loc),\n            (<<FLAGSRC: flag_src loc = false>>) /\\\n              (<<FLAGTGT: flag_tgt loc = false>>) /\\\n              (<<VAL: option_rel Const.le (vs_tgt loc) (vs_src loc)>>))\n        (INTERFERENCE: c = false -> flag_src = fun _ => false)\n        (MAPWF: Mapping.wfs f)\n        (VERSWF: versions_wf f vers)\n      :\n      sim_state_lift\n        c\n        (f, vers, mem_src)\n        (SeqMemory.mk svs_src sflag_src) (SeqMemory.mk svs_tgt sflag_tgt)\n        p D\n        mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n  .\n\n  Lemma sim_state_lift_cond_mon c0 c1\n        w smem_src smem_tgt p D mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n        (SIM: sim_state_lift c0 w smem_src smem_tgt p D mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n        (COND: c1 = false -> c0 = false)\n    :\n    sim_state_lift c1 w smem_src smem_tgt p D mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt.\n  Proof.\n    inv SIM. econs; eauto.\n  Qed.\n\n  Lemma rtc_steps_thread_failure lang th0 th1\n        (STEPS: rtc (@Thread.tau_step lang) th0 th1)\n        (FAILURE: Thread.steps_failure th1)\n    :\n    Thread.steps_failure th0.\n  Proof.\n    unfold Thread.steps_failure in *. des. esplits.\n    { etrans; eauto. }\n    { eauto. }\n    { eauto. }\n  Qed.\n\n  Lemma sim_thread_lift_init\n    :\n    sim_state_lift\n      false initial_world seq_memory_init seq_memory_init perms_top Flags.bot\n      Memory.init Memory.init Local.init Local.init TimeMap.bot TimeMap.bot.\n  Proof.\n    econs.\n    { eapply initial_sim_thread. }\n    { ii. econs; auto. }\n    { ii. econs; auto. }\n    { i. splits; ss. }\n    { ss. }\n    { eapply initial_mappings_wf. }\n    { eapply initial_versions_wf. }\n  Qed.\n\n  Lemma sim_lift_tgt_na_write_step:\n    forall\n      c w0 p D smem_src smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      mem_tgt1 lc_tgt1 sc_tgt1\n      loc from to val msgs kinds kind\n      (LIFT: sim_state_lift c w0 smem_src smem_tgt0 p D mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Local.write_na_step lc_tgt0 sc_tgt0 mem_tgt0 loc from to val Ordering.na lc_tgt1 sc_tgt1 mem_tgt1 msgs kinds kind)\n      (NALOCS: loc_na loc)\n      (LOWER: mem_tgt1 = mem_tgt0)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt0)\n      lang_src st_src,\n    exists lc_src1 mem_src1 sc_src1 me smem_tgt1,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: SeqState.na_local_step p me (ProgramEvent.write loc val Ordering.na) smem_tgt0 smem_tgt1>>) /\\\n        (<<LIFTAUX: forall (FAILURE: me = MachineEvent.failure),\n            exists w1,\n              (<<LIFT: sim_state_lift true w1 smem_src smem_tgt0 p D mem_src1 mem_tgt0 lc_src1 lc_tgt0 sc_src1 sc_tgt0>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>)>>) /\\\n        (<<LIFT: forall (NORMAL: me <> MachineEvent.failure),\n          exists w1,\n            (<<LIFT: sim_state_lift true w1 smem_src smem_tgt1 p D mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>)>>).\n  Proof.\n    i. inv LIFT. destruct (vs_tgt loc) eqn:VAL.\n    { hexploit sim_thread_tgt_write_na; eauto. i. des. esplits.\n      { eauto. }\n      { econs 3; eauto. }\n      { i. hexploit (VALS loc); auto. i.\n        rewrite VAL in H. inv H.\n        rewrite <- H1 in *. ss.\n      }\n      { i. subst. esplits; eauto.\n        { econs; eauto.\n          { ii. unfold ValueMap.write. des_ifs; ss.\n            { des_ifs. hexploit (VALS loc); auto. i.\n              rewrite VAL in *. rewrite Heq0 in *.\n              inv H. econs; eauto. refl.\n            }\n            { eapply VALS; eauto. }\n          }\n          { ss. unfold Flags.update. ii. des_ifs.\n            { econs; ss; auto.\n              { i. destruct (flag_src loc), (D loc); ss. }\n              { eapply FLAGS; auto. }\n            }\n          }\n          { i. ss. des_ifs. eapply ATLOCS; eauto. }\n          { ss. }\n        }\n        { ss. splits; auto.\n          { refl. }\n          { refl. }\n          { eapply Thread.rtc_tau_step_future in STEPS; eauto.\n            i. des; ss. eapply Memory.future_future_weak; auto.\n          }\n          { eapply map_future_memory_refl. }\n        }\n      }\n    }\n    { esplits.\n      { refl. }\n      { econs 3; ss. }\n      { i. esplits.\n        { econs; eauto. ss. }\n        { refl. }\n      }\n      { i. hexploit (VALS loc); auto. i.\n        rewrite VAL in H. inv H.\n        rewrite <- H1 in *. ss.\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_tgt_na_local_step:\n    forall\n      c w0 p D smem_src smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      e pe mem_tgt1 lc_tgt1 sc_tgt1\n      (LIFT: sim_state_lift c w0 smem_src smem_tgt0 p D mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Local.program_step e lc_tgt0 sc_tgt0 mem_tgt0 lc_tgt1 sc_tgt1 mem_tgt1)\n      (EVENT: ThreadEvent.get_program_event e = pe)\n      (NA: ~ is_atomic_event pe)\n      (NALOCS: forall loc val (ACCESS: is_accessing pe = Some (loc, val)), loc_na loc)\n      (LOWER: is_na_write e -> mem_tgt1 = mem_tgt0)\n\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt0)\n      lang_src st_src,\n    exists lc_src1 mem_src1 sc_src1 me smem_tgt1,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: SeqState.na_local_step p me pe smem_tgt0 smem_tgt1>>) /\\\n        (<<LIFTAUX: forall (FAILURE: me = MachineEvent.failure),\n            exists w1,\n              (<<LIFT: sim_state_lift true w1 smem_src smem_tgt0 p D mem_src1 mem_tgt0 lc_src1 lc_tgt0 sc_src1 sc_tgt0>>) /\\\n                (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>)>>) /\\\n        (<<LIFT: forall (NORMAL: me <> MachineEvent.failure),\n            exists w1,\n              (<<LIFT: sim_state_lift true w1 smem_src smem_tgt1 p D mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n                (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>) /\\\n                (<<NFAILURE: ThreadEvent.get_machine_event e = MachineEvent.silent>>)>>)\n  .\n  Proof.\n    i. inv STEP; ss.\n    { esplits.\n      { refl. }\n      { econs 1. }\n      { ss. }\n      { i. esplits; eauto.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n    }\n    { inv LIFT. destruct ord; ss. hexploit sim_thread_tgt_read_na; eauto.\n      i. des. esplits.\n      { refl. }\n      { econs 2; eauto. i. ss. hexploit (VALS loc); eauto. i. inv H0.\n        { des_ifs. }\n        hexploit VAL; eauto. i. etrans; eauto.\n      }\n      { ss. }\n      { i. esplits.\n        { econs; eauto. ss. }\n        { ss. i. splits; auto; try refl.\n          { eapply map_future_memory_refl. }\n          { eapply space_future_memory_refl; eauto. refl. }\n        }\n        { ss. }\n      }\n    }\n    { destruct ord; ss. eapply local_write_step_write_na_step in LOCAL.\n      hexploit sim_lift_tgt_na_write_step; eauto. i. des. esplits; eauto.\n      i. hexploit LIFT0; eauto. i. des. esplits; eauto.\n    }\n    { esplits.\n      { refl. }\n      { econs 5. red. destruct ordr, ordw; ss; auto. }\n      { i. esplits; eauto.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n      { ss. }\n    }\n    { esplits.\n      { refl. }\n      { econs 4. }\n      { i. esplits; eauto.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n      { ss. }\n    }\n    { destruct ord; ss. hexploit sim_lift_tgt_na_write_step; eauto.\n      i. des. esplits; eauto. i. hexploit LIFT0; eauto. i. des. esplits; eauto.\n    }\n    { inv LIFT. destruct ord; ss. hexploit sim_thread_tgt_read_na_racy; eauto.\n      i. esplits.\n      { refl. }\n      { econs 2; eauto. i. hexploit (VALS loc); eauto. i.\n        rewrite H in H1. inv H1.\n        rewrite <- H3 in *. ss.\n      }\n      { ss. }\n      { i. esplits.\n        { econs; eauto. ss. }\n        { ss. i. splits; auto; try refl.\n          { eapply map_future_memory_refl. }\n          { eapply space_future_memory_refl; eauto. refl. }\n        }\n        { ss. }\n      }\n    }\n    { inv LIFT. destruct ord; ss. hexploit sim_thread_tgt_write_na_racy; eauto.\n      i. esplits.\n      { refl. }\n      { econs 3; eauto. }\n      { i. esplits.\n        { econs; eauto. ss. }\n        { ss. i. splits; auto; try refl.\n          { eapply map_future_memory_refl. }\n          { eapply space_future_memory_refl; eauto. refl. }\n        }\n      }\n      { i. hexploit (VALS loc); eauto. i. rewrite H in H0. inv H0.\n        rewrite <- H2 in *. ss.\n      }\n    }\n    { esplits.\n      { refl. }\n      { econs 5. red. destruct ordr, ordw; ss; auto. }\n      { i. esplits.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n      { ss. }\n    }\n  Qed.\n\n  Lemma sim_lift_src_na_local_step:\n    forall\n      c w0 p D smem_src0 smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      pe me smem_src1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (STEP: SeqState.na_local_step p me pe smem_src0 smem_src1)\n      (NA: ~ is_atomic_event pe)\n      (NALOCS: forall loc val (ACCESS: is_accessing pe = Some (loc, val)), loc_na loc)\n\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt)\n      lang_src st_src,\n    exists lc_src1 mem_src1 sc_src1 lc_src2 mem_src2 sc_src2 e,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: Local.program_step e lc_src1 sc_src1 mem_src1 lc_src2 sc_src2 mem_src2>>) /\\\n        (<<MACHINE: ThreadEvent.get_machine_event e = me>>) /\\\n        (<<EVENT: ThreadEvent.get_program_event e = pe>>) /\\\n        (<<LIFT: forall (NORMAL: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n          exists w1,\n            (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt p D mem_src2 mem_tgt lc_src2 lc_tgt sc_src2 sc_tgt>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt lc_tgt.(Local.promises)) w0 w1>>)>>).\n  Proof.\n    i. inv STEP.\n    { esplits.\n      { refl. }\n      { eapply Local.step_silent. }\n      { ss. }\n      { ss. }\n      { i. esplits; eauto.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n    }\n    { inv LIFT. ss. hexploit (VALS loc); eauto. i. inv H.\n      { hexploit sim_thread_src_read_na_racy; eauto. i. des.\n        esplits.\n        { refl. }\n        { eapply Local.step_racy_read; eauto. }\n        { ss. }\n        { ss. destruct ord; ss. }\n        { i. esplits; eauto.\n          { econs; eauto. ss. }\n          { ss. i. splits; auto; try refl.\n            { eapply map_future_memory_refl. }\n            { eapply space_future_memory_refl; eauto. refl. }\n          }\n        }\n      }\n      { hexploit sim_thread_src_read_na.\n        { eauto. }\n        { eauto. }\n        { instantiate (1:=val). etrans; eauto.\n          ss. rewrite <- H1 in *. auto.\n        }\n        { auto. }\n        i. des.\n        esplits.\n        { refl. }\n        { eapply Local.step_read; eauto. }\n        { ss. }\n        { ss. destruct ord; ss. }\n        { i. esplits.\n          { econs; eauto. ss. }\n          { ss. i. splits; auto; try refl.\n            { eapply map_future_memory_refl. }\n            { eapply space_future_memory_refl; eauto. refl. }\n          }\n        }\n      }\n    }\n    { inv LIFT. ss. hexploit (VALS loc); eauto. i. inv H.\n      { hexploit sim_thread_src_write_na_racy; eauto.\n        i. des. esplits.\n        { refl. }\n        { eapply Local.step_racy_write; eauto. }\n        { ss. }\n        { ss. destruct ord; ss. }\n        { ss. }\n      }\n      { hexploit sim_thread_src_write_na; eauto.\n        i. des. esplits.\n        { eauto. }\n        { eapply Local.step_write_na; eauto. }\n        { ss. }\n        { ss. destruct ord; ss. }\n        { i. esplits.\n          { econs; eauto.\n            { ss. unfold ValueMap.write. ii. des_ifs.\n              { rewrite <- H1. rewrite <- H5. econs; eauto. refl. }\n              { eapply VALS; auto. }\n            }\n            { ss. unfold Flags.update. ii. des_ifs.\n            }\n            { i. ss. des_ifs.\n              { exfalso. eapply NNA; eauto. }\n              { eapply ATLOCS; eauto. }\n            }\n            { ss. }\n          }\n          { ss. i. splits; auto; try refl.\n            { eapply Thread.rtc_tau_step_future in STEPS; eauto.\n              des; ss.\n              hexploit Local.write_na_step_future; eauto.\n              i. des; ss.\n              eapply Memory.future_future_weak; eauto. etrans; eauto.\n            }\n            { eapply map_future_memory_refl. }\n          }\n        }\n      }\n    }\n    { inv LIFT. esplits.\n      { refl. }\n      { eapply Local.step_failure. econs.\n        inv SIM. eapply sim_local_consistent; eauto.\n      }\n      { ss. }\n      { ss. }\n      { ss. }\n    }\n    { inv LIFT. esplits.\n      { refl. }\n      { instantiate (4:=ThreadEvent.racy_update loc Time.bot valr valw ordr ordw).\n        inv SIM. eapply sim_local_consistent in CONSISTENT; eauto.\n        eapply Local.step_racy_update. red in ORD. des.\n        { econs 1; eauto. }\n        { econs 2; eauto. }\n      }\n      { ss. }\n      { ss. }\n      { ss. }\n    }\n  Qed.\n\n  Lemma sim_lift_src_na_step:\n    forall\n      c w0 p D smem_src0 smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      me smem_src1\n      lang_src st_src0 st_src1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (STEP: SeqState.na_step p me (SeqState.mk _ st_src0 smem_src0) (SeqState.mk _ st_src1 smem_src1))\n      (NOMIX: nomix loc_na loc_at _ st_src0)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt),\n    exists lc_src1 mem_src1 sc_src1 lc_src2 mem_src2 sc_src2 e pf,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src0 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: Thread.step pf e (Thread.mk _ st_src0 lc_src1 sc_src1 mem_src1) (Thread.mk _ st_src1 lc_src2 sc_src2 mem_src2)>>) /\\\n        (<<MACHINE: ThreadEvent.get_machine_event e = me>>) /\\\n        (<<LIFT: forall (NORMAL: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n          exists w1,\n            (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt p D mem_src2 mem_tgt lc_src2 lc_tgt sc_src2 sc_tgt>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt lc_tgt.(Local.promises)) w0 w1>>)>>) /\\\n        (<<NOMIX: nomix loc_na loc_at _ st_src1>>)\n  .\n  Proof.\n    i. inv STEP.\n    punfold NOMIX. exploit NOMIX; eauto. i. des.\n    hexploit sim_lift_src_na_local_step; eauto.\n    { inv LOCAL; ss.\n      { destruct ord; ss. }\n      { destruct ord; ss. }\n      { red in ORD. des; destruct ordr, ordw; ss. }\n    }\n    { i. eapply NA; eauto. inv LOCAL; ss.\n      { destruct ord; ss. }\n      { destruct ord; ss. }\n      { red in ORD. destruct ordr, ordw; des; ss. }\n    }\n    i. des. subst. esplits; eauto.\n    { econs 2; eauto. econs; eauto. }\n    pclearbot. auto.\n  Qed.\n\n  Lemma sim_lift_src_na_opt_step:\n    forall\n      c w0 p D smem_src0 smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      me smem_src1\n      lang_src st_src0 st_src1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (STEP: SeqState.na_opt_step p me (SeqState.mk _ st_src0 smem_src0) (SeqState.mk _ st_src1 smem_src1))\n      (NOMIX: nomix loc_na loc_at _ st_src0)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt),\n    exists lc_src1 mem_src1 sc_src1 lc_src2 mem_src2 sc_src2 e,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src0 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: Thread.opt_step e (Thread.mk _ st_src0 lc_src1 sc_src1 mem_src1) (Thread.mk _ st_src1 lc_src2 sc_src2 mem_src2)>>) /\\\n        (<<MACHINE: ThreadEvent.get_machine_event e = me>>) /\\\n        (<<LIFT: forall (NORMAL: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n          exists w1,\n            (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt p D mem_src2 mem_tgt lc_src2 lc_tgt sc_src2 sc_tgt>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt lc_tgt.(Local.promises)) w0 w1>>)>>) /\\\n        (<<NOMIX: nomix loc_na loc_at _ st_src1>>)\n  .\n  Proof.\n    i. inv STEP.\n    { hexploit sim_lift_src_na_step; eauto.\n      i. des. esplits; eauto. econs 2; eauto.\n    }\n    { esplits; eauto.\n      { econs 1. }\n      { ss. }\n      { esplits; eauto.\n        { eapply sim_state_lift_cond_mon; eauto. ss. }\n        { refl. }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_src_na_steps:\n    forall\n      c lang_src st_src0 st_src1\n      p smem_src0 smem_src1\n      (STEPS: rtc (SeqState.na_step p MachineEvent.silent) (SeqState.mk _ st_src0 smem_src0) (SeqState.mk _ st_src1 smem_src1))\n      w0 D smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (NOMIX: nomix loc_na loc_at _ st_src0)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt),\n    exists lc_src1 mem_src1 sc_src1,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<LIFT: exists w1,\n            (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt p D mem_src1 mem_tgt lc_src1 lc_tgt sc_src1 sc_tgt>>) /\\\n              (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt lc_tgt.(Local.promises)) w0 w1>>)>>) /\\\n        (<<NOMIX: nomix loc_na loc_at _ st_src1>>)\n  .\n  Proof.\n    intros c lang_src st_src0 st_src1 p smem_src0 smem_src1 STEPS.\n    remember (SeqState.mk _ st_src0 smem_src0) as th_src0.\n    remember (SeqState.mk _ st_src1 smem_src1) as th_src1.\n    revert c st_src0 st_src1 smem_src0 smem_src1 Heqth_src0 Heqth_src1.\n    induction STEPS; i; clarify.\n    { esplits.\n      { refl. }\n      { eapply sim_state_lift_cond_mon; eauto. ss. }\n      { refl. }\n      { auto. }\n    }\n    destruct y. hexploit sim_lift_src_na_step; eauto. i. des.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    hexploit Thread.step_future; eauto. i. des; ss.\n    hexploit LIFT0; eauto.\n    { rewrite MACHINE. ss. }\n    i. des. hexploit IHSTEPS; eauto. i. des. esplits.\n    { etrans; [eauto|]. econs.\n      { econs; eauto. econs; eauto. }\n      { eauto. }\n    }\n    { eauto. }\n    { etrans; eauto. }\n    { eauto. }\n  Qed.\n\n  Variant sim_val_sol_lift: forall (p: Perm.t) (P: bool) (sv: Const.t) (v: Const.t), Prop :=\n    | sim_val_sol_lift_high\n        sv v\n        (VAL: Const.le sv v)\n      :\n      sim_val_sol_lift Perm.high true sv v\n    | sim_val_sol_lift_low\n        sv v\n      :\n      sim_val_sol_lift Perm.low false sv v\n  .\n\n  Definition sim_vals_sol_lift (p: Perms.t) (P: Loc.t -> bool) (svs: ValueMap.t) (vs: Loc.t -> Const.t) :=\n    forall loc (NA: loc_na loc), sim_val_sol_lift (p loc) (P loc) (svs loc) (vs loc).\n\n  Variant sim_flag_sol_lift (D: Flag.t) (d: bool) (W: Flag.t) (flag: Flag.t): Prop :=\n    | sim_flag_sol_lift_intro\n        (DEBT: d -> D)\n        (WRITTEN: Flag.join W flag -> ~ d)\n  .\n\n  Definition sim_flags_sol_lift (D: Flags.t) (d: Loc.t -> bool) (W: Flags.t) (flag: Flags.t): Prop :=\n    forall loc, sim_flag_sol_lift (D loc) (d loc) (W loc) (flag loc).\n\n  Variant sim_state_sol_lift (c: bool):\n    forall (smem: SeqMemory.t) (p: Perms.t) (D: Flags.t) (W: Flags.t)\n           (mem: Memory.t) (lc: Local.t) (sc: TimeMap.t) (o: Oracle.t), Prop :=\n    | sim_state_sol_lift_intro\n        svs flag\n        p P W d D vs ovs\n        mem lc sc\n        (SIM: sim_thread_sol c vs P d mem lc)\n        (VAL: sim_vals_sol_lift p P svs vs)\n        (FLAG: sim_flags_sol_lift D d W flag)\n        (OVALS: forall loc (NA: loc_at loc), Const.le (ovs loc) (vs loc))\n      :\n      sim_state_sol_lift\n        c\n        (SeqMemory.mk svs flag)\n        p D W\n        mem lc sc (CertOracle.to_oracle ovs)\n  .\n\n  Lemma sim_lift_sim_lift_sol c:\n    forall\n      c1 w p D smem_src smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      lang_src st_src\n      (LIFT: sim_state_lift c1 w smem_src smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CERTIFIED: c = true -> lc_tgt.(Local.promises) = Memory.bot),\n    exists lc_src1 mem_src1 sc_src1 o,\n      (<<STEPS: rtc (@Thread.tau_step lang_src) (Thread.mk _ st_src lc_src0 sc_src0 mem_src0) (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<LIFT: sim_state_sol_lift\n                   c smem_src p (Flags.join D smem_tgt.(SeqMemory.flags)) smem_src.(SeqMemory.flags) mem_src1 lc_src1 sc_src1 o>>) /\\\n        (<<ORACLE: Oracle.wf o>>)\n  .\n  Proof.\n    i. inv LIFT.\n    hexploit (@sim_thread_sim_thread_sol c (fun loc => Flag.minus (flag_tgt loc) (flag_src loc))); eauto.\n    { i. destruct (flag_src loc), (flag_tgt loc); ss. }\n    i. des. esplits; eauto.\n    econs; eauto.\n    { ii. hexploit (VALS loc); eauto. i. inv H.\n      { econs; eauto. }\n      { hexploit VALS0; eauto. i. rewrite H. econs; eauto. }\n    }\n    { ii. ss. hexploit (FLAGS loc); eauto. i. inv H. econs.\n      { unfold Flags.minus, Flags.join.\n        destruct (D loc), (sflag_tgt loc), (sflag_src loc), (flag_tgt loc), (flag_src loc); auto.\n      }\n      { unfold Flags.minus, Flags.join. ii.\n        destruct (D loc), (sflag_tgt loc), (sflag_src loc), (flag_tgt loc), (flag_src loc); ss.\n      }\n    }\n    { i. refl. }\n    { eapply CertOracle.to_oracle_wf. }\n  Qed.\n\n  Lemma sim_lift_sol_na_local_step c:\n    forall\n      p D W smem0 mem0 lc0 sc0 o\n      smem1 me pe\n      (LIFT: sim_state_sol_lift c smem0 p D W mem0 lc0 sc0 o)\n      (STEP: SeqState.na_local_step p me pe smem0 smem1)\n      (NALOCS: forall loc val (ACCESS: is_accessing pe = Some (loc, val)), loc_na loc)\n      (WF_SRC: Local.wf lc0 mem0)\n      (SC_SRC: Memory.closed_timemap sc0 mem0)\n      (MEM_SRC: Memory.closed mem0)\n      lang st,\n    exists lc1 mem1 sc1 lc2 mem2 sc2 e,\n      (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk _ st lc0 sc0 mem0) (Thread.mk _ st lc1 sc1 mem1)>>) /\\\n        (<<STEP: Local.program_step e lc1 sc1 mem1 lc2 sc2 mem2>>) /\\\n        (<<MACHINE: ThreadEvent.get_machine_event e = me \\/ ThreadEvent.get_machine_event e = MachineEvent.failure>>) /\\\n        (<<EVENT: ThreadEvent.get_program_event e = pe>>) /\\\n        (<<LIFT: forall (NORMAL: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n            sim_state_sol_lift c smem1 p D W mem2 lc2 sc2 o>>).\n  Proof.\n    i. inv STEP.\n    { esplits.\n      { refl. }\n      { eapply Local.step_silent. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n    }\n    { inv LIFT. destruct ord; ss.\n      hexploit (VAL0 loc); eauto. i. inv H.\n      { rewrite <- H1 in *.\n        hexploit sim_thread_sol_read_na.\n        { eauto. }\n        { eauto. }\n        { etrans; [eapply VAL; auto|eapply VAL1]. }\n        i. des. esplits.\n        { refl. }\n        { eapply Local.step_read; eauto. }\n        { eauto. }\n        { ss. }\n        { i. econs; eauto. }\n      }\n      { rewrite <- H1 in *.\n        hexploit sim_thread_sol_read_na_racy; eauto.\n        { rewrite <- H2. ss. }\n        i. des. esplits.\n        { refl. }\n        { eapply Local.step_racy_read; eauto. }\n        { eauto. }\n        { ss. }\n        { i. econs; eauto. }\n      }\n    }\n    { inv LIFT. destruct ord; ss.\n      hexploit (VAL loc); eauto. i. inv H.\n      { hexploit sim_thread_sol_write_na; eauto. i. des.\n        { esplits.\n          { refl. }\n          { eapply Local.step_racy_write; eauto. }\n          { eauto. }\n          { ss. }\n          { ss. }\n        }\n        { esplits.\n          { eauto. }\n          { eapply Local.step_write_na; eauto. }\n          { eauto. }\n          { ss. }\n          { i. econs; eauto.\n            { ii. unfold ValueMap.write. ss. des_ifs.\n              { rewrite <- H1. econs. refl. }\n              { eapply VAL; auto. }\n            }\n            { ii. unfold Flags.update. ss. des_ifs.\n            }\n            { i. ss. des_ifs.\n              { exfalso. eapply LOCDISJOINT; eauto. }\n              { eapply OVALS; eauto. }\n            }\n          }\n        }\n      }\n      { hexploit sim_thread_sol_write_na_racy; eauto.\n        { rewrite <- H2. ss. }\n        i. des. esplits.\n        { refl. }\n        { eapply Local.step_racy_write; eauto. }\n        { eauto. }\n        { ss. }\n        { ss. }\n      }\n    }\n    { inv LIFT. hexploit sim_thread_sol_failure; eauto. i.\n      esplits.\n      { refl. }\n      { eapply Local.step_failure; eauto. }\n      { eauto. }\n      { ss. }\n      { ss. }\n    }\n    { inv LIFT. esplits.\n      { refl. }\n      { eapply Local.step_racy_update.\n        instantiate (1:=ordw). instantiate (1:=ordr).\n        red in ORD. des.\n        { econs 1; eauto. inv SIM. auto. }\n        { econs 2; eauto. inv SIM. auto. }\n      }\n      { auto. }\n      { ss. }\n      { ss. }\n    }\n  Qed.\n\n  Lemma perm_meet_high_r p\n    :\n    Perm.meet p Perm.high = p.\n  Proof.\n    destruct p; ss.\n  Qed.\n\n  Lemma sim_lift_sol_at_step c:\n    forall\n      D W smem0 mem0 lc0 sc0\n      smem1 pe i o\n      lang st0 st1 p0 p1 o0 o1\n      (LIFT: sim_state_sol_lift c smem0 p0 D W mem0 lc0 sc0 o0)\n      (STEP: SeqThread.at_step pe i o (SeqThread.mk (SeqState.mk _ st0 smem0) p0 o0) (SeqThread.mk (SeqState.mk _ st1 smem1) p1 o1))\n      (ATLOCS: forall loc val (ACCESS: is_accessing pe = Some (loc, val)), loc_at loc)\n      (NUPDATE: ~ is_updating pe)\n      (NACQUIRE: ~ is_acquire pe)\n      (WF_SRC: Local.wf lc0 mem0)\n      (SC_SRC: Memory.closed_timemap sc0 mem0)\n      (MEM_SRC: Memory.closed mem0),\n    exists lc1 mem1 e sc1 pf,\n      (<<STEP: Thread.step pf e (Thread.mk lang st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1)>>) /\\\n        (<<EVENT: ThreadEvent.get_program_event e = pe>>) /\\\n        (<<LIFT: forall (NORMAL: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n            sim_state_sol_lift c smem1 p1 D (Flags.join W (SeqEvent.written i)) mem1 lc1 sc1 o1>>).\n  Proof.\n    i. inv LIFT. inv STEP. inv MEM.\n    assert (exists ovs1,\n               (<<ORACLE: o1 = (CertOracle.to_oracle ovs1)>>) /\\\n                 (<<OSTEP: CertOracle.step e0 i0 o ovs ovs1>>)).\n    { dependent destruction ORACLE. esplits; eauto. }\n    clear ORACLE. des; clarify.\n    red in INPUT0. des. inv ACQ.\n    2:{ rewrite <- H0 in *. hexploit ACQUIRE; eauto. i. ss. }\n    inv OSTEP; ss; clarify.\n    { des_ifs; ss. hexploit OVALS; eauto. i.\n      hexploit sim_thread_sol_read; eauto.\n      i. des. esplits.\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_read; eauto. }\n        { eauto. }\n      }\n      { ss. }\n      { i. inv REL. inv UPD.\n        specialize (UPDATE loc0 v_new). des.\n        hexploit UPDATE; eauto. i. inv H2.\n        inv MEM. ss. econs; eauto.\n        { ii. unfold Perms.update, ValueMap.write.\n          destruct (LocSet.Facts.eq_dec loc0 loc), (LocSet.Facts.eq_dec loc loc0); subst; ss; auto.\n          econs. auto.\n        }\n        { ii. unfold SeqEvent.written. rewrite <- H4. rewrite <- H3. ss.\n          unfold Flags.add, Flags.join, Flags.update, Flags.bot.\n          hexploit (FLAG loc); eauto. i. inv H2.\n          destruct (flag loc0) eqn:EQ0, (LocSet.Facts.eq_dec loc loc0); subst; ss.\n          { rewrite EQ0 in *. econs; auto. }\n          { rewrite flag_join_bot_r. auto. }\n          { rewrite EQ0 in *. rewrite flag_join_bot_r. auto. econs; auto. }\n          { rewrite flag_join_bot_r. auto. }\n        }\n      }\n    }\n    { destruct pe; ss. des. clarify.\n      inv UPD. inv MEM. ss. red in INPUT. des. ss.\n      rewrite <- H2 in *. ss.\n      destruct (Oracle.in_access i0) as [[[loc1 val1] flag1]|] eqn:ACCESS0; ss.\n      des; subst. hexploit (UPDATE loc v_new); eauto. i. des.\n      hexploit H1; eauto. i. inv H4.\n      hexploit sim_thread_sol_write; eauto.\n      i. des. esplits.\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_write; eauto. }\n        { eauto. }\n      }\n      { ss. }\n      i. inv REL.\n      { ss. econs; eauto.\n        { unfold Perms.update, ValueMap.write. ii.\n          repeat des_if; subst; ss.\n          { econs. refl. }\n          { eapply VAL; eauto. }\n        }\n        { unfold SeqEvent.written. rewrite <- H2. rewrite <- H5.\n          ss. rewrite flags_join_bot_r.\n          unfold Flags.add, Flags.update, Flags.join, Flags.bot. ii.\n          hexploit (FLAG loc0); eauto. i. inv H4. econs; auto.\n          destruct (flag loc) eqn:EQ0, (LocSet.Facts.eq_dec loc0 loc); subst.\n          { subst. rewrite flag_join_bot_r. rewrite EQ0 in *. auto. }\n          { rewrite flag_join_bot_r. auto. }\n          { subst. rewrite flag_join_bot_r. rewrite EQ0 in *. auto. }\n          { rewrite flag_join_bot_r. auto. }\n        }\n        { i. ss. condtac; subst; auto. }\n      }\n      { inv MEM. ss.\n        destruct (Ordering.le Ordering.strong_relaxed ord0); ss. inv H6.\n        econs; eauto.\n        { unfold Perms.meet, Perms.update, ValueMap.write. ii.\n          repeat condtac; subst; ss.\n          { econs. refl. }\n          { rewrite perm_meet_high_r. eapply VAL; eauto. }\n        }\n        { unfold SeqEvent.written. rewrite <- H2. rewrite <- H5. ss.\n          unfold Flags.add, Flags.update, Flags.join, Flags.bot. ii.\n          hexploit (FLAG loc0); eauto. i. inv H4. econs; auto.\n          destruct (flag loc) eqn:EQ0, (LocSet.Facts.eq_dec loc0 loc); subst.\n          { subst. rewrite flag_join_bot_r. rewrite EQ0 in *. auto. }\n          { rewrite flag_join_bot_r. auto. }\n          { subst. rewrite flag_join_bot_r. rewrite EQ0 in *. auto. }\n          { rewrite flag_join_bot_r. auto. }\n        }\n        { i. ss. condtac; subst; auto. }\n      }\n    }\n    { destruct pe; ss. }\n    { hexploit sim_thread_sol_fence; eauto.\n      { instantiate (1:=ordr). destruct ordr, ordw; ss. }\n      { instantiate (1:=ordw). destruct ordr, ordw; ss. }\n      i. des. esplits.\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_fence; eauto. }\n        { eauto. }\n      }\n      { ss. }\n      i. inv UPD. inv REL.\n      { econs; eauto. unfold SeqEvent.written.\n        rewrite <- H2. rewrite <- H3. ss.\n        rewrite flags_join_bot_r. auto.\n      }\n      { destruct (Ordering.le Ordering.strong_relaxed ordw); ss. clarify.\n        inv MEM. ss. econs; eauto.\n        { unfold Perms.meet. ii. rewrite perm_meet_high_r. auto. }\n        { unfold SeqEvent.written. rewrite <- H2. rewrite <- H3.\n          ss. rewrite flags_join_bot_l. unfold Flags.join, Flags.bot. ii.\n          hexploit (FLAG loc); eauto. i. inv H1. econs; auto.\n          rewrite flag_join_bot_r. auto.\n        }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_sol_steps c\n        tr\n        lang st0 st1 smem0 smem1 p0 p1 o0 o1\n        (STEPS: SeqThread.steps (@SeqState.na_step _) tr (SeqThread.mk (SeqState.mk _ st0 smem0) p0 o0) (SeqThread.mk (SeqState.mk _ st1 smem1) p1 o1))\n    :\n    forall mem0 lc0 sc0 w D W\n           (LIFT: sim_state_sol_lift c smem0 p0 D W mem0 lc0 sc0 o0)\n           (NOMIX: nomix loc_na loc_at _ st0)\n           (TRACE: SeqThread.writing_trace tr w)\n           (WF_SRC: Local.wf lc0 mem0)\n           (SC_SRC: Memory.closed_timemap sc0 mem0)\n           (MEM_SRC: Memory.closed mem0),\n      (<<FAILURE: Thread.steps_failure (Thread.mk _ st0 lc0 sc0 mem0)>>) \\/\n        exists lc1 mem1 sc1,\n          (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk _ st0 lc0 sc0 mem0) (Thread.mk _ st1 lc1 sc1 mem1)>>) /\\\n            (<<LIFT: sim_state_sol_lift c smem1 p1 D (Flags.join w W) mem1 lc1 sc1 o1>>) /\\\n            (<<NOMIX: nomix loc_na loc_at _ st1>>)\n  .\n  Proof.\n    remember (SeqThread.mk (SeqState.mk _ st0 smem0) p0 o0) as th0.\n    remember (SeqThread.mk (SeqState.mk _ st1 smem1) p1 o1) as th1.\n    revert st0 st1 smem0 smem1 p0 p1 o0 o1 Heqth0 Heqth1. induction STEPS; i; clarify.\n    { inv TRACE. right. esplits.\n      { refl. }\n      { rewrite flags_join_bot_l. auto. }\n      { auto. }\n    }\n    { inv STEP. inv STEP0. hexploit sim_lift_sol_na_local_step; eauto.\n      { punfold NOMIX. exploit NOMIX; eauto. i. des.\n        eapply NA in ACCESS; auto. inv LOCAL; ss.\n        { destruct ord; ss. }\n        { destruct ord; ss. }\n      }\n      i. ss. des; subst.\n      { assert (STEPS1: rtc (@Thread.tau_step _) (Thread.mk _ st0 lc0 sc0 mem0) (Thread.mk _ st4 lc2 sc2 mem2)).\n        { etrans; [eauto|]. econs; [|refl]. econs; eauto.\n          econs. econs 2; eauto. econs; eauto.\n        }\n        clear STEPS0 STEP.\n        hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n        hexploit LIFT0.\n        { rewrite MACHINE. ss. }\n        i. hexploit IHSTEPS; eauto.\n        { punfold NOMIX. exploit NOMIX; eauto. i. des. pclearbot. auto. }\n        i. des.\n        { left. eapply rtc_steps_thread_failure; eauto. }\n        { right. esplits.\n          { etrans; eauto. }\n          { eauto. }\n          { auto. }\n        }\n      }\n      { left. splits. red. esplits; eauto. econs 2; eauto. econs; eauto. }\n    }\n    { destruct th1. destruct state0. inv TRACE.\n      hexploit sim_lift_sol_at_step; eauto.\n      { inv STEP. punfold NOMIX. exploit NOMIX; eauto. i. des.\n        eapply AT in ACCESS; auto.\n      }\n      i. ss. des; subst.\n      { destruct (ThreadEvent.get_machine_event e0) eqn:EVENT.\n        { assert (STEP1: rtc (@Thread.tau_step _) (Thread.mk _ st0 lc0 sc0 mem0) (Thread.mk _ state0 lc1 sc1 mem1)).\n          { econs; [|refl]. econs; eauto. econs; eauto. }\n          hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n          hexploit LIFT0; ss.\n          i. hexploit IHSTEPS; eauto.\n          { punfold NOMIX. inv STEP. exploit NOMIX; eauto. i. des. pclearbot. auto. }\n          i. des.\n          { left. eapply rtc_steps_thread_failure; eauto. }\n          { right. esplits.\n            { etrans; eauto. }\n            { replace (Flags.join (Flags.join (SeqEvent.written i) w0) W) with\n                (Flags.join w0 (Flags.join W (SeqEvent.written i))); auto.\n              unfold Flags.join. extensionality loc.\n              destruct (w0 loc), (W loc), (SeqEvent.written i loc); auto.\n            }\n            { auto. }\n          }\n        }\n        { destruct e0; ss. }\n        { left. splits. red. esplits; [refl| |eauto].\n          replace pf with true in STEP0; eauto.\n          inv STEP0; ss. inv STEP1; ss.\n        }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_failure_case:\n    forall\n      c w p D smem_src smem_tgt mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      lang st\n      (LIFT: sim_state_lift c w smem_src smem_tgt p D mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt)\n      (FAILURE: sim_seq_failure_case p (SeqState.mk _ st smem_src))\n      (NOMIX: nomix loc_na loc_at _ st)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt),\n      (<<FAILURE: Thread.steps_failure (Thread.mk lang st lc_src sc_src mem_src)>>).\n  Proof.\n    i. hexploit sim_lift_sim_lift_sol; eauto.\n    { instantiate (1:=false). ss. }\n    i. des.\n    eapply rtc_steps_thread_failure; eauto.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    exploit FAILURE; eauto. i. des.\n    destruct th. destruct state0.\n    hexploit sim_lift_sol_steps; eauto. i. des; eauto.\n    inv FAILURE0. des. inv H. inv STEP.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    hexploit sim_lift_sol_na_local_step; eauto.\n    { punfold NOMIX0. exploit NOMIX0; eauto. i. des. eapply NA; eauto.\n      inv LOCAL; ss.\n      { destruct ord; ss. }\n      { red in ORD. destruct ordr, ordw; des; ss. }\n    }\n    i. des.\n    { eapply rtc_steps_thread_failure; eauto.\n      red. esplits; eauto. econs 2. econs; eauto.\n      rewrite EVENT. eauto.\n    }\n    { eapply rtc_steps_thread_failure; eauto.\n      red. esplits; eauto. econs 2. econs; eauto.\n      rewrite EVENT. eauto.\n    }\n  Qed.\n\n  Lemma sim_lift_partial_case c:\n    forall\n      w p D smem_src smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      lang_src lang_tgt\n      (st_src0: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n      (LIFT: sim_state_lift c w smem_src smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (PARTIAL: sim_seq_partial_case p D (SeqState.mk _ st_src0 smem_src) (SeqState.mk _ st_tgt smem_tgt))\n      (BOT: lc_tgt.(Local.promises) = Memory.bot)\n      (NOMIX: nomix loc_na loc_at _ st_src0)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt),\n    exists st_src1 lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step lang_src)\n                    (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) \\/\n           (<<BOT: lc_src1.(Local.promises) = Memory.bot>>)).\n  Proof.\n    i. hexploit sim_lift_sim_lift_sol; eauto.\n    i. des.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    exploit PARTIAL; eauto. intros x.\n    destruct x as [?th [?tr [?w [STEPS0 [WRITING FINAL]]]]].\n    guardH FINAL. destruct th. destruct state0. des.\n    hexploit sim_lift_sol_steps; eauto. i. des; eauto.\n    { esplits; eauto. } esplits.\n    { etrans; eauto. }\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    red in FINAL. des.\n    { right. inv LIFT1. eapply sim_thread_none; eauto.\n      i. hexploit (FLAG loc). i. inv H.\n      specialize (FLAGS loc). unfold Flags.join in *.\n      destruct (d loc); auto. exfalso. eapply WRITTEN; auto.\n      ss. rewrite DEBT in FLAGS; auto.\n      destruct (w0 loc), (flag loc), (SeqMemory.flags smem_src loc); ss.\n    }\n    { left. inv FAILURE. des. inv H. inv STEP.\n      hexploit sim_lift_sol_na_local_step; eauto.\n      { punfold NOMIX0. exploit NOMIX0; eauto. i. des. eapply NA; eauto.\n        inv LOCAL; ss.\n        { destruct ord; ss. }\n        { red in ORD. destruct ordr, ordw; des; ss. }\n      }\n      i. des.\n      { eapply rtc_steps_thread_failure; eauto.\n        red. esplits; eauto. econs 2. econs; eauto.\n        rewrite EVENT. eauto.\n      }\n      { eapply rtc_steps_thread_failure; eauto.\n        red. esplits; eauto. econs 2. econs; eauto.\n        rewrite EVENT. eauto.\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_terminal_case c:\n    forall\n      w0 p D smem_src smem_tgt mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt\n      lang_src lang_tgt sim_terminal\n      (st_src0: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n      (LIFT: sim_state_lift c w0 smem_src smem_tgt p D mem_src0 mem_tgt lc_src0 lc_tgt sc_src0 sc_tgt)\n      (SIM: sim_seq_terminal_case sim_terminal p D (SeqState.mk _ st_src0 smem_src) (SeqState.mk _ st_tgt smem_tgt))\n      (TERMINAL: lang_tgt.(Language.is_terminal) st_tgt)\n      (BOT: lc_tgt.(Local.promises) = Memory.bot)\n      (NOMIX: nomix loc_na loc_at _ st_src0)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC: Local.wf lc_src0 mem_src0)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src0)\n      (MEM_TGT: Memory.closed mem_tgt),\n    exists st_src1 lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) \\/\n           exists w1,\n             (<<TERMINAL_SRC: (Language.is_terminal lang_src) st_src1>>) /\\\n               (<<BOT: lc_src1.(Local.promises) = Memory.bot>>) /\\\n               (<<SC: sim_timemap_lift w1 sc_src1 sc_tgt>>) /\\\n               (<<MEMORY: sim_memory_lift w1 mem_src1 mem_tgt>>) /\\\n               (<<WORLD: world_messages_le (unchangable mem_src1 lc_src1.(Local.promises)) (unchangable mem_tgt lc_tgt.(Local.promises)) w0 w1>>)).\n  Proof.\n    i. exploit SIM; eauto. i. des.\n    destruct st_src1. hexploit sim_lift_src_na_steps; eauto.\n    i. des. ss.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    inv LIFT1. ss. hexploit sim_thread_deflag_all; eauto.\n    { instantiate (1:=fun _ => False).\n      i. right. specialize (FLAGS loc). specialize (FLAG loc).\n      inv FLAGS. splits.\n      { i. rewrite H in *. ss. rewrite SRC in *.\n        unfold Flags.join in FLAG.\n        destruct (flag_tgt loc), (Flag.join (D loc) (sflag_tgt loc)); ss.\n      }\n      { specialize (VALUE loc). specialize (VALS loc). i.\n        left. destruct (classic (loc_na loc)).\n        { hexploit VALS; auto. i. inv H0; ss.\n          etrans; eauto. etrans; eauto.\n        }\n        { eapply ATLOCS; eauto. }\n      }\n    }\n    i. des. eapply rtc_implies in STEPS1; cycle 1.\n    { instantiate (1:=@Thread.tau_step _). i. inv H.\n      inv TSTEP. econs; eauto.\n    }\n    esplits.\n    { etrans; eauto. }\n    right. eexists (f1,  vers, mem_src2). esplits; eauto.\n    { inv SIM1. inv LOCAL.\n      eapply sim_promises_bot in PROMISES; eauto.\n      i. specialize (FLAG0 loc). des; ss.\n    }\n    { ss. inv SIM1. eapply sim_timemap_mon_locs; eauto; ss. }\n    { ss. inv SIM1. splits; auto.\n      { eapply sim_memory_sim_memory_interference; eauto. }\n      { eapply versions_wf_mapping_mon; eauto. }\n    }\n    { etrans; eauto. ss. i. splits; auto.\n      { refl. }\n      { eapply Thread.rtc_tau_step_future in STEPS1; eauto. des; ss.\n        eapply Memory.future_future_weak; eauto.\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_interference_future:\n    forall\n      w0 p0 D smem_src smem_tgt mem_src0 mem_tgt0 lc_src0 lc_tgt sc_src0 sc_tgt0\n      w1 mem_src1 mem_tgt1 sc_src1 sc_tgt1\n      lang_src lang_tgt sim_terminal st_src st_tgt\n      (LIFT: sim_state_lift false w0 smem_src smem_tgt p0 D mem_src0 mem_tgt0 lc_src0 lc_tgt sc_src0 sc_tgt0)\n      (SIM: sim_seq_interference _ _ sim_terminal p0 D (SeqState.mk lang_src st_src smem_src) (SeqState.mk lang_tgt st_tgt smem_tgt))\n      (NOMIX: nomix loc_na loc_at _ st_src)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0)\n      (CONS: Thread.consistent (Thread.mk lang_src st_src lc_src0 sc_src0 mem_src0))\n      (WF_SRC1: Local.wf lc_src0 mem_src1)\n      (WF_TGT1: Local.wf lc_tgt mem_tgt1)\n      (SC_SRC1: Memory.closed_timemap sc_src1 mem_src1)\n      (SC_TGT1: Memory.closed_timemap sc_tgt1 mem_tgt1)\n      (MEM_SRC1: Memory.closed mem_src1)\n      (MEM_TGT1: Memory.closed mem_tgt1)\n      (MEMSRC: Memory.future_weak mem_src0 mem_src1)\n      (MEMTGT: Memory.future_weak mem_tgt0 mem_tgt1)\n      (CLOSEDFUTURE: closed_future_tview loc_na lc_tgt.(Local.tview) mem_tgt0 mem_tgt1)\n      (SCSRC: TimeMap.le sc_src0 sc_src1)\n      (SCTGT: TimeMap.le sc_tgt0 sc_tgt1)\n      (WORLD: world_messages_le (Messages.of_memory lc_src0.(Local.promises)) (Messages.of_memory lc_tgt.(Local.promises)) w0 w1)\n      (MEM: sim_memory_lift w1 mem_src1 mem_tgt1)\n      (SC: sim_timemap_lift w1 sc_src1 sc_tgt1)\n    ,\n    exists lc_src2 sc_src2 mem_src2,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src lc_src0 sc_src1 mem_src1)\n                    (Thread.mk _ st_src lc_src2 sc_src2 mem_src2)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src lc_src2 sc_src2 mem_src2)>>) \\/\n           (exists w2 p1,\n               (<<LIFT: sim_state_lift false w2 smem_src smem_tgt p1 D mem_src2 mem_tgt1 lc_src2 lc_tgt sc_src2 sc_tgt1>>) /\\\n                 (<<SIM: sim_seq_interference _ _ sim_terminal p1 D (SeqState.mk lang_src st_src smem_src) (SeqState.mk lang_tgt st_tgt smem_tgt)>>) /\\\n                 (<<SC: sim_timemap_lift w2 sc_src2 sc_tgt1>>) /\\\n                 (<<MEM: sim_memory_lift w2 mem_src2 mem_tgt1>>) /\\\n                 (<<WORLD: world_messages_le (unchangable mem_src1 lc_src0.(Local.promises)) (unchangable mem_tgt1 lc_tgt.(Local.promises)) w1 w2>>))).\n  Proof.\n    i. inv LIFT. destruct w1 as [[f1 vers1] mem_src1'].\n    red in WORLD. red in MEM. red in SC.\n    hexploit WORLD; eauto. i. des. subst.\n    hexploit INTERFERENCE; eauto. i. subst.\n    hexploit SeqLiftInterference.sim_thread_future; eauto.\n    { i. eapply ATLOCS; auto. }\n    i. des.\n    { esplits; eauto. }\n    esplits; eauto. right.\n    hexploit (choice (fun loc p =>\n                        (<<NA: loc_na loc -> p = if (vs_src1 loc) then Perm.high else Perm.low>>) /\\\n                          (<<AT: ~ loc_na loc -> p = p0 loc>>))).\n    { intros loc. destruct (classic (loc_na loc)).\n      { esplits; [eauto|]. ss. }\n      { esplits; [|eauto]. ss. }\n    }\n    intros [p1 PERM1].\n    esplits.\n    { econs; eauto.\n      { instantiate (1:=p1). ii.\n        specialize (PERM1 loc). des. rewrite NA0; auto.\n        hexploit (VALS loc); auto. i. des_ifs.\n        { inv SIM2. specialize (PERM loc).\n          rewrite Heq in PERM. destruct (vs_tgt1 loc) eqn:VAL; ss.\n          hexploit VALTGT; eauto. i.\n          hexploit VALSRC; eauto. i. des.\n          rewrite VS in H. rewrite H0 in H. inv H.\n          econs.\n          { etrans; eauto. }\n          { auto. }\n        }\n        { inv SIM2. specialize (PERM loc).\n          rewrite Heq in PERM. destruct (vs_tgt1 loc) eqn:VAL; ss.\n          econs.\n        }\n      }\n      { ii. ss. hexploit ATLOCS; eauto. i. des. splits; auto.\n        inv SIM2. specialize (PERM loc).\n        destruct (vs_src1 loc) eqn:VSRC, (vs_tgt1 loc) eqn:VTGT; ss.\n        hexploit no_flag_max_value_same; eauto.\n        { rewrite <- VSRC. eauto. }\n        i. des. inv MAX. hexploit (MAXTGT loc); eauto. i. inv H.\n        hexploit MAX; eauto. i. des. hexploit MAX0; eauto. i. des.\n        eapply max_readable_inj in MAX1; eauto. des. subst. auto.\n      }\n      { eapply versions_wf_mapping_mon; eauto. eapply Mapping.les_strong_les; eauto. }\n    }\n    { eapply sim_seq_interference_mon; eauto.\n      ii. specialize (PERM1 loc). des.\n      destruct (classic (loc_na loc)).\n      { rewrite NA; auto. des_ifs. hexploit VALSRC; eauto. i. des.\n        hexploit (VALS loc); auto. i. rewrite VS in H0. inv H0. refl.\n      }\n      { rewrite AT; auto. refl. }\n    }\n    { inv SIM2. ss. }\n    { inv SIM2. ss. splits; auto.\n      { eapply sim_memory_sim_memory_interference; eauto. }\n      { eapply versions_wf_mapping_mon; eauto. eapply Mapping.les_strong_les; eauto. }\n    }\n    { ss. i. splits; auto; try refl.\n      { eapply Mapping.les_strong_les; eauto. }\n      { hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n        eapply Memory.future_future_weak; eauto.\n      }\n      { eapply map_future_memory_les_strong; eauto. }\n    }\n  Qed.\n\n  Lemma sim_lift_interference_promise:\n    forall\n      w0 p D smem_src smem_tgt mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src st_tgt\n      lc_tgt1 mem_tgt1 loc from_tgt to_tgt msg_tgt kind_tgt\n      (LIFT: sim_state_lift false w0 smem_src smem_tgt p D mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (SIM: sim_seq_interference _ _ sim_terminal p D (SeqState.mk lang_src st_src smem_src) (SeqState.mk lang_tgt st_tgt smem_tgt))\n      (NOMIX: nomix loc_na loc_at _ st_src)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0)\n      (PROMISE: Local.promise_step lc_tgt0 mem_tgt0 loc from_tgt to_tgt msg_tgt lc_tgt1 mem_tgt1 kind_tgt),\n    exists lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src lc_src1 sc_src1 mem_src1)>>) \\/\n           (exists w1,\n               (<<LIFT: sim_state_lift false w1 smem_src smem_tgt p D mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt0>>) /\\\n                 (<<SC: sim_timemap_lift w1 sc_src1 sc_tgt0>>) /\\\n                 (<<MEM: sim_memory_lift w1 mem_src1 mem_tgt1>>) /\\\n                 (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>))).\n  Proof.\n    i. inv LIFT.\n    hexploit INTERFERENCE; eauto. i. subst.\n    hexploit sim_thread_promise_step; eauto.\n    i. des. esplits.\n    { econs 2; [|refl]. econs.\n      { econs. econs 1. econs; eauto. }\n      { ss. }\n    }\n    right. esplits.\n    { econs; eauto. }\n    { inv SIM1. ss. }\n    { inv SIM1. ss. splits; auto. eapply sim_memory_sim_memory_interference; eauto. }\n    { ss. i. splits; auto.\n      { eapply Mapping.les_strong_les; eauto. }\n      { hexploit Local.promise_step_future; eauto. i. des; ss.\n        eapply Memory.future_future_weak; eauto.\n      }\n      { eapply map_future_memory_les_strong; eauto. }\n    }\n  Qed.\n\n  Lemma sim_lift_interference_cap:\n    forall\n      w0 p D smem_src smem_tgt mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src st_tgt\n      cap_src cap_tgt\n      (LIFT: sim_state_lift false w0 smem_src smem_tgt p D mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (SIM: sim_seq_interference _ _ sim_terminal p D (SeqState.mk lang_src st_src smem_src) (SeqState.mk lang_tgt st_tgt smem_tgt))\n      (NOMIX: nomix loc_na loc_at _ st_src)\n      (CONSISTENT: Local.promise_consistent lc_tgt0)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0)\n      (CAPSRC: Memory.cap mem_src0 cap_src)\n      (CAPTGT: Memory.cap mem_tgt0 cap_tgt),\n      (exists w1,\n          (<<LIFT: sim_state_lift false w1 smem_src smem_tgt p D cap_src cap_tgt lc_src0 lc_tgt0 sc_src0 sc_tgt0>>) /\\\n            (<<SC: sim_timemap_lift w1 sc_src0 sc_tgt0>>) /\\\n            (<<MEM: sim_memory_lift w1 cap_src cap_tgt>>)).\n  Proof.\n    i. inv LIFT.\n    hexploit INTERFERENCE; eauto. i. subst.\n    hexploit sim_thread_cap; eauto.\n    i. des. esplits.\n    { econs; eauto. }\n    { inv SIM1. ss. }\n    { inv SIM1. ss. splits; auto. eapply sim_memory_sim_memory_interference; eauto. }\n  Qed.\n\n  Lemma wf_oracle_output_exists e\n    :\n    exists o, (<<WFOUT: Oracle.wf_output e o>>).\n  Proof.\n    exists (Oracle.mk_output\n              (if is_accessing e then (Some Perm.high) else None)\n              (if is_acquire e then (Some (perms_top, fun _ => Const.undef)) else None)\n              (if is_release e then (Some perms_top) else None)).\n    splits. red. ss. des_ifs.\n  Qed.\n\n  Lemma flag_join_false_r f0\n    :\n      Flag.join f0 false = f0.\n  Proof.\n    destruct f0; ss.\n  Qed.\n\n  Lemma sim_seq_atomic_step lang_src lang_tgt sim_terminal\n        p0 d0 st_src0 st_tgt0\n        (SIM: sim_seq_at_step_case (@sim_seq lang_src lang_tgt sim_terminal) p0 d0 st_src0 st_tgt0)\n    :\n    forall st_tgt1 e_tgt\n           (STEP_TGT: lang_tgt.(Language.step) e_tgt st_tgt0.(SeqState.state) st_tgt1)\n           (ATOMIC: is_atomic_event e_tgt),\n    exists st_src1 st_src2 e_src,\n      (<<STEPS: rtc (SeqState.na_step p0 MachineEvent.silent) st_src0 st_src1>>) /\\\n        (<<STEP: lang_src.(Language.step) e_src st_src1.(SeqState.state) st_src2>>) /\\\n        (<<EVENT: ProgramEvent.le e_tgt e_src>>) /\\\n        (<<ACQ: forall (ACQUIRE: is_acquire e_tgt),\n            Flags.le (Flags.join st_tgt0.(SeqState.memory).(SeqMemory.flags) d0) (st_src1.(SeqState.memory).(SeqMemory.flags))>>) /\\\n        (<<SIM: forall i_tgt o p1 mem_tgt\n                       (INPUT: SeqEvent.wf_input e_tgt i_tgt)\n                       (OUTPUT: Oracle.wf_output e_tgt o)\n                       (STEP_TGT: SeqEvent.step i_tgt o p0 st_tgt0.(SeqState.memory) p1 mem_tgt),\n          exists i_src mem_src d1,\n            (<<STEP_SRC: SeqEvent.step i_src o p0 st_src1.(SeqState.memory) p1 mem_src>>) /\\\n              (<<MATCH: SeqEvent.input_match d0 d1 i_src i_tgt>>) /\\\n              (<<INPUT: SeqEvent.wf_input e_src i_src>>) /\\\n              (<<SIM: sim_seq_cond\n                        (negb (is_release e_tgt))\n                        _ _ sim_terminal\n                        p1 d1\n                        (SeqState.mk _ st_src2 mem_src)\n                        (SeqState.mk _ st_tgt1 mem_tgt)>>)>>).\n  Proof.\n    i. exploit SIM; eauto. i. des. esplits; eauto.\n    { i. hexploit wf_oracle_output_exists. i. des.\n      hexploit event_step_exists; eauto. i. des.\n      hexploit SIM0; eauto. i. des.\n      red in WF. des. inv MATCH. inv STEP0; ss. inv ACQUIRE2.\n      { hexploit ACQUIRE1; eauto. rewrite <- H3. ss. }\n      inv STEP_SRC. rewrite <- H2 in *. rewrite <- H3 in *.\n      inv ACQ. inv ACQ0. inv MEM. inv MEM0. ss.\n      inv ACCESS.\n      { inv UPD.\n        2:{ rewrite <- H1 in *. ss. }\n        inv UPD0.\n        2:{ rewrite <- H8 in *. ss. }\n        etrans; eauto. eapply Flags.join_mon_r; auto.\n      }\n      { inv UPD.\n        { rewrite <- H1 in *. ss. }\n        inv UPD0.\n        { rewrite <- H8 in *. ss. }\n        inv MEM. inv MEM0. ss.\n        rewrite <- H7 in H1. rewrite <- H6 in H8. inv H8. inv H1.\n        move FLAG0 at bottom. move FLAG at bottom.\n        ii. specialize (FLAG loc). clear - FLAG0 FLAG DEFERRED.\n        unfold Flags.update, Flags.join in FLAG. unfold Flags.join. des_ifs.\n        etrans; eauto. eapply Flag.join_mon_r; auto.\n      }\n    }\n    i. hexploit SIM0; eauto. i. des.\n    hexploit min_input_match_exists; eauto. i. des. inv MIN.\n    destruct (is_release e_tgt) eqn:RELEASE; ss; eauto.\n    inv STEP_TGT0. inv REL.\n    { red in OUTPUT. des. hexploit RELEASE1; eauto.\n      i. rewrite <- H in *. ss.\n    }\n    esplits; eauto. ii.\n    hexploit (SIM0 i_tgt (Oracle.mk_output o.(Oracle.out_access) o.(Oracle.out_acquire) (Some p1))); eauto.\n    { red in OUTPUT. des. red. splits; auto. }\n    { econs.\n      { eauto. }\n      { eauto. }\n      { ss. rewrite <- H0. econs 2; eauto. }\n    }\n    i. des. inv STEP_SRC0. inv STEP_SRC. ss.\n    hexploit SeqEvent.step_update_inj.\n    { eapply UPD0. }\n    { eapply UPD1. }\n    { i. red in INPUT1. red in INPUT0. des; ss.\n      hexploit UPDATE0; eauto. i. des.\n      hexploit UPDATE; eauto. i. des.\n      hexploit H3.\n      { esplits. eapply IN1. }\n      i.\n      hexploit H1.\n      { esplits. eapply IN2. }\n      i. clarify.\n    }\n    { auto. }\n    i. des; clarify.\n    hexploit SeqEvent.step_acquire_inj.\n    { eapply ACQ0. }\n    { eapply ACQ1. }\n    { auto. }\n    i. des; clarify. inv REL0.\n    { rewrite <- H in H5. ss. }\n    inv REL. inv MEM0. inv MEM1.\n    assert (PERMEQ: Perms.meet p4 p1 = p1).\n    { clear - PERM. eapply perms_antisym.\n      { eapply Perms.meet_le_r. }\n      { eapply Perms.meet_spec.\n        { etrans; eauto. eapply Perms.meet_le_l. }\n        { reflexivity . }\n      }\n    }\n    rewrite PERMEQ in SIM2. ginit.\n    guclo deferred_le_sf_ctx_spec. econs.\n    2:{ gfinal. right. eapply SIM2. }\n    ss. rewrite flags_join_bot_r.\n    eapply MIN0; eauto.\n    destruct i_src, i_src0; ss. clarify.\n  Qed.\n\n  Definition lift_out_access (e: ProgramEvent.t): option Perm.t :=\n    (if (is_accessing e) then Some Perm.low else None).\n\n  Definition lift_out_acquire (e: ProgramEvent.t) (vs: Loc.t -> option Const.t):\n    option (Perms.t * ValueMap.t) :=\n    if (is_acquire e)\n    then\n      Some ((fun loc => if vs loc then Perm.high else Perm.low),\n            (fun loc => match vs loc with | Some v => v | _ => Const.undef end))\n    else\n      None.\n\n  Definition lift_out_release (e: ProgramEvent.t): option (Perms.t) :=\n    if (is_release e) then Some (fun _ => Perm.high) else None.\n\n  Definition lift_output (e: ProgramEvent.t) (vs: Loc.t -> option Const.t): Oracle.output :=\n    Oracle.mk_output (lift_out_access e) (lift_out_acquire e vs) (lift_out_release e).\n\n  Lemma lift_out_access_wf e:\n    lift_out_access e <-> is_accessing e.\n  Proof.\n    ss. unfold lift_out_access. des_ifs.\n  Qed.\n\n  Lemma lift_out_acquire_wf e vs:\n    lift_out_acquire e vs <-> is_acquire e.\n  Proof.\n    ss. unfold lift_out_acquire. des_ifs.\n  Qed.\n\n  Lemma lift_out_release_wf e:\n    lift_out_release e <-> is_release e.\n  Proof.\n    ss. unfold lift_out_release. des_ifs.\n  Qed.\n\n  Lemma lift_output_wf e vs\n    :\n      Oracle.wf_output e (lift_output e vs).\n  Proof.\n    red. splits.\n    { eapply lift_out_access_wf. }\n    { eapply lift_out_acquire_wf. }\n    { eapply lift_out_release_wf. }\n  Qed.\n\n  Definition seqevent_wf_in_access\n             (e: ProgramEvent.t) (i: option (Loc.t * Const.t * Flag.t * Const.t)): Prop :=\n    forall loc v_new,\n      (exists v_old f_old,\n          i = Some (loc, v_old, f_old, v_new)) <->\n      is_accessing e = Some (loc, v_new).\n\n  Definition seqevent_wf_in_acquire\n             (e: ProgramEvent.t) (i: option Flags.t): Prop :=\n    i <-> is_acquire e.\n\n  Definition seqevent_wf_in_release\n             (e: ProgramEvent.t) (i: option (ValueMap.t * Flags.t)): Prop :=\n    i <-> is_release e.\n\n  Lemma seqevent_wf_cons e i\n        (ACCESS: seqevent_wf_in_access e i.(SeqEvent.in_access))\n        (ACQUIRE: seqevent_wf_in_acquire e i.(SeqEvent.in_acquire))\n        (RELEASE: seqevent_wf_in_release e i.(SeqEvent.in_release))\n    :\n      SeqEvent.wf_input e i.\n  Proof.\n    red. splits; auto.\n  Qed.\n\n  Lemma seqevent_wf_destruct e i\n        (WF: SeqEvent.wf_input e i)\n    :\n      (<<ACCESS: seqevent_wf_in_access e i.(SeqEvent.in_access)>>) /\\\n      (<<ACQUIRE: seqevent_wf_in_acquire e i.(SeqEvent.in_acquire)>>) /\\\n      (<<RELEASE: seqevent_wf_in_release e i.(SeqEvent.in_release)>>).\n  Proof.\n    auto.\n  Qed.\n\n  Lemma sim_lift_event_step_access:\n    forall\n      vs_src0 vs_tgt0 vs_src1 vs_tgt1\n      flag_src0 flag_tgt0\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0 D0 sflag_src0 sflag_tgt0\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (ATLOCS: forall loc (NNA: ~ loc_na loc),\n          (<<FLAGSRC: flag_src0 loc = false>>) /\\\n            (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n      (AT: forall loc val (ACC: is_accessing e_tgt = Some (loc, val)), loc_at loc)\n      (VAL: forall loc (NA: loc_na loc),\n          (<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)),\n    forall i_src svs_src1 sflag_src1 D1 i_tgt svs_tgt1 sflag_tgt1 p1 p'\n           (INPUT_SRC: seqevent_wf_in_access e_src i_src)\n           (INPUT_TGT: seqevent_wf_in_access e_tgt i_tgt)\n           (MATCH: SeqEvent.in_access_match D0 D1 i_src i_tgt)\n           (STEP_SRC: SeqEvent.step_update\n                        i_src (lift_out_access e_tgt)\n                        p0 (SeqMemory.mk svs_src0 sflag_src0)\n                        p1 (SeqMemory.mk svs_src1 sflag_src1))\n           (STEP_TGT: SeqEvent.step_update\n                        i_tgt (lift_out_access e_tgt)\n                        p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                        p' (SeqMemory.mk svs_tgt1 sflag_tgt1)),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src1 vs_tgt1>>) /\\\n        (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 flag_src0 flag_tgt0>>).\n  Proof.\n    i. inv MATCH.\n    { inv STEP_TGT. inv STEP_SRC. splits; auto.\n      { ii. hexploit (VAL loc); auto. i. des.\n        rewrite SRC. rewrite TGT. auto.\n      }\n      { ii. specialize (FLAGS loc). inv FLAGS. econs; auto.\n        etrans; eauto. eapply Flag.join_mon_r. eapply Flag.join_mon_l. auto.\n      }\n    }\n    { inv STEP_TGT. inv STEP_SRC. inv MEM. inv MEM0. ss.\n      exploit INPUT_TGT. intros x. des. exploit x; eauto. i. rewrite x2 in *.\n      splits.\n      { rewrite <- H in H5. inv H5. auto. }\n      { ii. unfold ValueMap.write, Perms.update. condtac; subst.\n        { exfalso. eapply LOCDISJOINT; eauto. }\n        condtac; subst; ss.\n        hexploit (VAL loc); auto. i. des.\n        rewrite SRC. rewrite TGT. auto.\n      }\n      { ii. unfold Flags.update. specialize (FLAGS loc). inv FLAGS. condtac; subst.\n        { econs.\n          { rewrite SRC in FLAG. rewrite flag_join_false_r.\n            etrans; eauto. etrans; [|eapply Flag.join_ge_l].\n            eapply Flag.join_spec; [refl|]. rewrite flag_join_comm. auto.\n          }\n          { hexploit ATLOCS; eauto. i. des. rewrite FLAGSRC. ss. }\n        }\n        { econs; auto. etrans; eauto.\n          eapply Flag.join_mon_r. eapply Flag.join_mon_l. eapply DEFERRED; auto.\n        }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_event_step_acquire:\n    forall\n      vs_src0 vs_tgt0 vs_src1 vs_tgt1\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0\n      D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (ATLOCS: forall loc (NNA: ~ loc_na loc),\n          (<<FLAGSRC: flag_src0 loc = false>>) /\\\n          (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n          (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n      (VAL: forall loc (NA: loc_na loc),\n          ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n          (exists val_src val_tgt,\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              (<<ACQ: is_acquire e_tgt>>)))\n      (ACQFLAG: forall loc\n                       (SRC: flag_src0 loc = false) (TGT: flag_tgt0 loc = true),\n          ~ is_acquire e_tgt),\n    forall i_src svs_src1 sflag_src1 D1\n           i_tgt svs_tgt1 sflag_tgt1 p1 p'\n           (INPUT_SRC: seqevent_wf_in_acquire e_src i_src)\n           (INPUT_TGT: seqevent_wf_in_acquire e_tgt i_tgt)\n           (MATCH: SeqEvent.in_acquire_match D0 D1 i_src i_tgt)\n           (STEP_SRC: SeqEvent.step_acquire\n                        i_src (lift_out_acquire e_tgt vs_src1)\n                        p0 (SeqMemory.mk svs_src0 sflag_src0)\n                        p1 (SeqMemory.mk svs_src1 sflag_src1))\n           (STEP_TGT: SeqEvent.step_acquire\n                        i_tgt (lift_out_acquire e_tgt vs_src1)\n                        p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                        p' (SeqMemory.mk svs_tgt1 sflag_tgt1)),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src1 vs_tgt1>>) /\\\n        (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 flag_src0 flag_tgt0>>).\n  Proof.\n    i. inv MATCH.\n    { inv STEP_TGT. inv STEP_SRC.\n      splits; auto.\n      { ii. hexploit (VAL loc); auto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { red in INPUT_TGT. rewrite ACQ in INPUT_TGT. des. hexploit INPUT_TGT0; ss.\n        }\n      }\n      { ii. specialize (FLAGS loc). inv FLAGS. econs; auto.\n        etrans; eauto. eapply Flag.join_mon_r. eapply Flag.join_mon_l. auto.\n      }\n    }\n    { inv STEP_TGT. inv STEP_SRC. inv MEM. inv MEM0.\n      unfold lift_out_acquire in *. des_ifs. ss. splits.\n      { auto. }\n      { ii. hexploit (VALS loc); eauto. i.\n        unfold lift_out_acquire in *. des_ifs.\n        unfold ValueMap.acquire, Perms.acquired, Perms.join.\n        hexploit VAL; eauto. i. des.\n        { rewrite SRC. rewrite TGT. inv H; ss.\n          { econs. }\n          { econs; eauto. }\n        }\n        { rewrite VALSRC. rewrite VALTGT.\n          rewrite NONESRC in *. rewrite NONETGT in *. inv H; ss.\n          econs; eauto. refl.\n        }\n      }\n      { ii. hexploit (FLAGS loc); eauto. i.\n        specialize (FLAGS loc). inv FLAGS. econs; auto.\n        etrans; [|eapply Flag.join_ge_l].\n        destruct (flag_tgt0 loc) eqn:FLAGSRC, (flag_src0 loc) eqn:FLATGT; ss.\n        hexploit ACQFLAG; eauto. ss.\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_event_step_release_normal:\n    forall\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0\n      D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (NORMAL: ~ is_release e_tgt),\n    forall i_src svs_src1 sflag_src1 D1 i_tgt svs_tgt1 sflag_tgt1 p1 p'\n           (INPUT_SRC: seqevent_wf_in_release e_src i_src)\n           (INPUT_TGT: seqevent_wf_in_release e_tgt i_tgt)\n           (MATCH: SeqEvent.in_release_match D0 D1 i_src i_tgt)\n           (STEP_SRC: SeqEvent.step_release\n                        i_src (lift_out_release e_tgt)\n                        p0 (SeqMemory.mk svs_src0 sflag_src0)\n                        p1 (SeqMemory.mk svs_src1 sflag_src1))\n           (STEP_TGT: SeqEvent.step_release\n                        i_tgt (lift_out_release e_tgt)\n                        p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                        p' (SeqMemory.mk svs_tgt1 sflag_tgt1)),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src0 vs_tgt0>>) /\\\n        (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 flag_src0 flag_tgt0>>).\n  Proof.\n    i. inv MATCH.\n    { inv STEP_TGT. inv STEP_SRC.\n      splits; auto.\n      { ii. specialize (FLAGS loc). inv FLAGS. econs; auto.\n        etrans; eauto. eapply Flag.join_mon_r. eapply Flag.join_mon_l. auto.\n      }\n    }\n    { exfalso. eapply NORMAL. eapply INPUT_TGT. ss. }\n  Qed.\n\n  Lemma sim_lift_event_step_release_release:\n    forall\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0\n      D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0 flag_tgt1\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (NORMAL: is_release e_tgt)\n      (ATLOCS: forall loc (NNA: ~ loc_na loc),\n          (<<FLAGSRC: flag_src0 loc = false>>) /\\\n          (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n          (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n      (DEBT: forall loc\n                    (FLAG: flag_src0 loc = false -> flag_tgt0 loc = false)\n                    (VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)),\n          flag_tgt1 loc = false),\n    forall i_src svs_src1 sflag_src1 D1 i_tgt svs_tgt1 sflag_tgt1 p1 p'\n           (INPUT_SRC: seqevent_wf_in_release e_src i_src)\n           (INPUT_TGT: seqevent_wf_in_release e_tgt i_tgt)\n           (MATCH: SeqEvent.in_release_match D0 D1 i_src i_tgt)\n           (STEP_SRC: SeqEvent.step_release\n                        i_src (lift_out_release e_tgt)\n                        p0 (SeqMemory.mk svs_src0 sflag_src0)\n                        p1 (SeqMemory.mk svs_src1 sflag_src1))\n           (STEP_TGT: SeqEvent.step_release\n                        i_tgt (lift_out_release e_tgt)\n                        p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                        p' (SeqMemory.mk svs_tgt1 sflag_tgt1)),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src0 vs_tgt0>>) /\\\n      (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 (fun _ => false) flag_tgt1>>).\n  Proof.\n    i. inv MATCH.\n    { exfalso. red in INPUT_TGT. rewrite NORMAL in INPUT_TGT.\n      des. hexploit INPUT_TGT0; ss.\n    }\n    inv STEP_TGT. inv STEP_SRC. inv MEM. inv MEM0. ss.\n    unfold lift_out_release in *. rewrite NORMAL in *. clarify. splits; auto.\n    { ii. unfold Perms.meet. rewrite perm_meet_high_r. auto. }\n    { ii. specialize (FLAGS loc). inv FLAGS.\n      econs; ss. unfold Flags.bot. rewrite flag_join_false_r.\n      specialize (DEBT loc). specialize (VAL loc).\n      specialize (DEFERRED loc). unfold Flags.join in DEFERRED.\n      destruct (flag_tgt1 loc), (D1 loc); ss. hexploit DEBT; ss.\n      { i. rewrite H in *. ss. rewrite flag_join_false_r in *.\n        rewrite SRC in *. rewrite flag_join_comm in TGT.\n        destruct (flag_tgt0 loc); ss. rewrite TGT in *. ss.\n      }\n      { destruct (classic (loc_na loc)).\n        { hexploit (VALS loc); eauto. i. inv H0; ss. etrans; eauto. etrans; eauto. }\n        { hexploit ATLOCS; eauto. i. des. auto. }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_event_step_normal:\n    forall\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0\n      D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0\n      vs_src1 vs_tgt1\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (ATLOCS: forall loc (NNA: ~ loc_na loc),\n          (<<FLAGSRC: flag_src0 loc = false>>) /\\\n            (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n      (NORMAL: ~ is_release e_tgt)\n      (AT: forall loc val (ACC: is_accessing e_tgt = Some (loc, val)), loc_at loc)\n      (VAL: forall loc (NA: loc_na loc),\n          ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n            (exists val_src val_tgt,\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                  (<<ACQ: is_acquire e_tgt>>)))\n      (ACQFLAG: forall loc\n                       (SRC: flag_src0 loc = false) (TGT: flag_tgt0 loc = true),\n          ~ is_acquire e_tgt),\n    forall i_src svs_src1 sflag_src1 D1 i_tgt svs_tgt1 sflag_tgt1 p1 p'\n           (INPUT_SRC: SeqEvent.wf_input e_src i_src)\n           (INPUT_TGT: SeqEvent.wf_input e_tgt i_tgt)\n           (MATCH: SeqEvent.input_match D0 D1 i_src i_tgt)\n           (STEP_SRC: SeqEvent.step\n                        i_src (lift_output e_tgt vs_src1)\n                        p0 (SeqMemory.mk svs_src0 sflag_src0)\n                        p1 (SeqMemory.mk svs_src1 sflag_src1))\n           (STEP_TGT: SeqEvent.step\n                        i_tgt (lift_output e_tgt vs_src1)\n                        p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                        p' (SeqMemory.mk svs_tgt1 sflag_tgt1)),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src1 vs_tgt1>>) /\\\n        (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 flag_src0 flag_tgt0>>).\n  Proof.\n    i. inv MATCH. inv STEP_SRC. inv STEP_TGT.\n    eapply seqevent_wf_destruct in INPUT_SRC.\n    eapply seqevent_wf_destruct in INPUT_TGT. des.\n    destruct m1, m2, m3, m4. ss.\n    hexploit sim_lift_event_step_access; eauto. i. des; subst.\n    hexploit sim_lift_event_step_acquire; eauto. i. des; subst.\n    hexploit sim_lift_event_step_release_normal; eauto.\n  Qed.\n\n  Lemma sim_lift_event_step_release:\n    forall\n      e_tgt e_src\n      p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0\n      D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0 flag_tgt1\n      vs_src1 vs_tgt1 i_src svs_src1 sflag_src1 D1 i_tgt svs_tgt1 sflag_tgt1 p1 p'\n      (STEP_SRC: SeqEvent.step\n                   i_src (lift_output e_tgt vs_src1)\n                   p0 (SeqMemory.mk svs_src0 sflag_src0)\n                   p1 (SeqMemory.mk svs_src1 sflag_src1))\n      (STEP_TGT: SeqEvent.step\n                   i_tgt (lift_output e_tgt vs_src1)\n                   p0 (SeqMemory.mk svs_tgt0 sflag_tgt0)\n                   p' (SeqMemory.mk svs_tgt1 sflag_tgt1))\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (VALS: sim_vals_lift p0 svs_src0 svs_tgt0 vs_src0 vs_tgt0)\n      (FLAGS: sim_flags_lift D0 sflag_src0 sflag_tgt0 flag_src0 flag_tgt0)\n      (ATLOCS: forall loc (NNA: ~ loc_na loc),\n          (<<FLAGSRC: flag_src0 loc = false>>) /\\\n          (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n          (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n      (RELEASE: is_release e_tgt)\n      (AT: forall loc val (ACC: is_accessing e_tgt = Some (loc, val)), loc_at loc)\n      (VAL: forall loc,\n          ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n          (exists val_src val_tgt,\n              ((<<NNA: ~ loc_na loc>>) \\/ ((<<NONESRC: vs_src0 loc = None>>) /\\ (<<NONETGT: vs_tgt0 loc = None>>) /\\ (<<ACQ: is_acquire e_tgt>>))) /\\\n              (<<VALSRC: vs_src1 loc = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc = Some val_tgt>>) /\\\n              (<<VALLE: Const.le val_tgt val_src>>)))\n      (ACQFLAG: forall loc\n                       (SRC: flag_src0 loc = false) (TGT: flag_tgt0 loc = true),\n          ~ is_acquire e_tgt)\n      (DEBT: forall loc\n                    (FLAG: flag_src0 loc = false -> flag_tgt0 loc = false)\n                    (VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)),\n          flag_tgt1 loc = false)\n      (INPUT_SRC: SeqEvent.wf_input e_src i_src)\n      (INPUT_TGT: SeqEvent.wf_input e_tgt i_tgt)\n      (MATCH: SeqEvent.input_match D0 D1 i_src i_tgt),\n      (<<PERMEQ: p' = p1>>) /\\\n      (<<VALS: sim_vals_lift p1 svs_src1 svs_tgt1 vs_src1 vs_tgt1>>) /\\\n      (<<FLAGS: sim_flags_lift D1 sflag_src1 sflag_tgt1 (fun _ => false) flag_tgt1>>).\n  Proof.\n    i. inv MATCH. inv STEP_SRC. inv STEP_TGT.\n    eapply seqevent_wf_destruct in INPUT_SRC.\n    eapply seqevent_wf_destruct in INPUT_TGT. des.\n    destruct m1, m2, m3, m4. ss.\n    hexploit sim_lift_event_step_access; eauto. i. des; subst.\n    assert (VAL0: forall loc (NA: loc_na loc),\n               ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n               (exists val_src val_tgt,\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                   (<<ACQ: is_acquire e_tgt>>))).\n    { i. hexploit VAL; eauto. i. des.\n      { left. splits; eauto. }\n      { ss. }\n      { right. esplits; eauto. }\n    }\n    hexploit sim_lift_event_step_acquire; eauto. i. des; subst.\n    hexploit sim_lift_event_step_release_release; eauto.\n    { i. hexploit ATLOCS; eauto. i. des. splits; auto.\n      hexploit (VAL loc); eauto. i. des.\n      { rewrite SRC. rewrite TGT. auto. }\n      { rewrite VALSRC. rewrite VALTGT. auto. }\n      { rewrite VALSRC. rewrite VALTGT. auto. }\n    }\n    { i. eapply DEBT; auto. destruct (classic (loc_na loc)).\n      { hexploit VAL0; eauto. i. des.\n        { rewrite SRC in VAL1. rewrite TGT in VAL1. ss. }\n        { rewrite NONESRC. rewrite NONETGT. ss. }\n      }\n      { hexploit ATLOCS; eauto. i. des. auto. }\n    }\n  Qed.\n\n  Lemma sim_thread_local_program_step_normal\n        f0 vers0 flag_src0 flag_tgt0 vs_src0 vs_tgt0\n        mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n        pe_tgt pe_src\n        e_tgt lc_tgt1 mem_tgt1 sc_tgt1\n        lang st0 st1\n        (SIM: SeqLiftStep.sim_thread\n                f0 vers0 flag_src0 flag_tgt0 vs_src0 vs_tgt0\n                mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n        (STEP: Local.program_step e_tgt lc_tgt0 sc_tgt0 mem_tgt0 lc_tgt1 sc_tgt1 mem_tgt1)\n        (EVENTTGT: ThreadEvent.get_program_event e_tgt = pe_tgt)\n        (EVENTLE: ProgramEvent.le pe_tgt pe_src)\n        (LANGSTEP: lang.(Language.step) pe_src st0 st1)\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        (ATOMIC: is_atomic_event pe_tgt)\n        (NORMAL: ~ is_release pe_tgt)\n        (ATLOCS: forall loc (NNA: ~ loc_na loc),\n            (<<FLAGSRC: flag_src0 loc = false>>) /\\\n              (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n              (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n        (AT: forall loc val (ACC: is_accessing pe_tgt = Some (loc, val)), loc_at loc)\n        (ACQFLAG: forall loc\n                         (SRC: flag_src0 loc = false) (TGT: flag_tgt0 loc = true),\n            ~ is_acquire pe_tgt)\n    :\n    (<<FAILURE: Thread.steps_failure (Thread.mk lang st0 lc_src0 sc_src0 mem_src0)>>) \\/\n    exists lc_src1 mem_src1 sc_src1 f1 vers1 vs_src1 vs_tgt1,\n      (<<STEPS: rtc (@Thread.tau_step _) (Thread.mk lang st0 lc_src0 sc_src0 mem_src0) (Thread.mk lang st1 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<SIM: SeqLiftStep.sim_thread\n                  f1 vers1 flag_src0 flag_tgt0 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 f0 f1>>) /\\\n        (<<VERSLE: versions_le vers0 vers1>>) /\\\n        (<<VERSWF: versions_wf f1 vers1>>) /\\\n        (<<MAPFUTURE: map_future_memory f0 f1 mem_src1>>) /\\\n        (<<ATLOCS: forall loc (NNA: ~ loc_na loc), option_rel Const.le (vs_tgt1 loc) (vs_src1 loc)>>) /\\\n        (<<VAL: forall loc (NA: loc_na loc),\n            ((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>)) \\/\n              (exists val_src val_tgt,\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                    (<<ACQ: is_acquire pe_tgt>>))>>) /\\\n          (<<NFAILURE: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent>>) /\\\n        (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src1>>)\n  .\n  Proof.\n    inv STEP; ss; clarify.\n    (* read *)\n    { hexploit (ATLOCS loc); eauto. i. des.\n      hexploit sim_thread_read; eauto.\n      i. des. right. esplits.\n      { econs 2; [|refl]. econs.\n        { econs. econs 2. econs; cycle 1.\n          { eapply Local.step_read. eapply READ.\n            instantiate (1:=val). etrans; eauto.\n          }\n          { ss. }\n        }\n        { ss. }\n      }\n      { eauto. }\n      { eauto. }\n      { refl. }\n      { refl. }\n      { eauto. }\n      { eapply map_future_memory_refl. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc0); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT0. ss. }\n        { rewrite VALSRC. rewrite VALTGT0. ss. }\n      }\n      { i. hexploit (VALS loc0); eauto. i. des.\n        { left. auto. }\n        { right. esplits; eauto. }\n        { subst. exfalso. eapply LOCDISJOINT; eauto. }\n      }\n      { ss. }\n      { eapply space_future_memory_refl; eauto. refl. }\n    }\n    (* write *)\n    { hexploit (ATLOCS loc); eauto. i. des_ifs. des. subst.\n      hexploit sim_thread_write_step_normal; eauto.\n      i. des. right. esplits.\n      { econs 2; [|refl]. econs.\n        { econs. econs 2. econs; cycle 1.\n          { eapply Local.step_write; eauto. }\n          { ss. }\n        }\n        { ss. }\n      }\n      { eauto. }\n      { eauto. }\n      { eapply Mapping.les_strong_les; eauto. }\n      { eauto. }\n      { eauto. }\n      { eapply map_future_memory_les_strong; eauto. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n        { rewrite VALSRC1. rewrite VALTGT1. ss. }\n      }\n      { i. hexploit (VALS loc); eauto. i. des.\n        { left. auto. }\n        { subst. exfalso. eapply LOCDISJOINT; eauto. }\n        { left. rewrite VALSRC0. rewrite VALTGT0. auto. }\n      }\n      { ss. }\n      { auto. }\n    }\n    (* update *)\n    { hexploit (ATLOCS loc); eauto. i. des_ifs. des. subst.\n      hexploit sim_thread_update_step_normal; eauto.\n      i. des. right. esplits.\n      { econs 2; [|refl]. econs.\n        { econs. econs 2. econs; cycle 1.\n          { eapply Local.step_update.\n            { eapply READ. instantiate (1:=valr0). etrans; eauto. }\n            { eauto. }\n          }\n          { ss. }\n        }\n        { ss. }\n      }\n      { eauto. }\n      { eauto. }\n      { eapply Mapping.les_strong_les; eauto. }\n      { eauto. }\n      { eauto. }\n      { eapply map_future_memory_les_strong; eauto. }\n      { i. hexploit ATLOCS; eauto. i. des. destruct (Loc.eq_dec loc0 loc).\n        { red in UPDATED. des; subst.\n          { rewrite TGT. rewrite SRC. ss. }\n          { rewrite TGTNONE1. rewrite SRCNONE1. ss. }\n        }\n        { hexploit VALS; eauto. i. des.\n          { rewrite SRC. rewrite TGT. auto. }\n          { rewrite VALSRC. rewrite VALTGT0. ss. }\n        }\n      }\n      { i. hexploit (VALS loc); eauto.\n        { ii. subst. eapply LOCDISJOINT; eauto. }\n      }\n      { ss. }\n      { auto. }\n    }\n    (* fence *)\n    { hexploit sim_thread_fence_step_normal; eauto.\n      { ii. hexploit ACQFLAG; eauto. rewrite H. destruct ordw; ss. }\n      { destruct ordw; ss. }\n      i. des. right. esplits.\n      { econs 2; [|refl]. econs.\n        { econs. econs 2. econs; cycle 1.\n          { eapply Local.step_fence; eauto. }\n          { ss. }\n        }\n        { ss. }\n      }\n      { eauto. }\n      { eauto. }\n      { refl. }\n      { refl. }\n      { eauto. }\n      { eapply map_future_memory_refl. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n      }\n      { i. hexploit (VALS loc); eauto. i. des.\n        { left. auto. }\n        { right. esplits; eauto. rewrite ORD. destruct ordw; ss. }\n        { right. esplits; eauto. rewrite ORD. ss. }\n      }\n      { ss. }\n      { eapply space_future_memory_refl; eauto. refl. }\n    }\n    (* na write *)\n    { inv LOCAL; ss. destruct ord; ss. }\n    (* racy read *)\n    { hexploit (ATLOCS loc); eauto. i. des.\n      hexploit sim_thread_racy_read_step; eauto.\n      i. des. right. esplits.\n      { econs 2; [|refl]. econs.\n        { econs. econs 2. econs; cycle 1.\n          { eapply Local.step_racy_read; eauto. }\n          { ss. eauto. }\n        }\n        { ss. }\n      }\n      { eauto. }\n      { eauto. }\n      { refl. }\n      { refl. }\n      { eauto. }\n      { eapply map_future_memory_refl. }\n      { i. hexploit ATLOCS; eauto. i. des. auto. }\n      { i. left. auto. }\n      { ss. }\n      { eapply space_future_memory_refl; eauto. refl. }\n    }\n    (* racy write *)\n    { des_ifs. hexploit (ATLOCS loc); eauto. i. des. subst.\n      hexploit sim_thread_racy_write_step; eauto.\n      i. des. left. esplits. red. esplits.\n      { refl. }\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_racy_write; eauto. }\n        { ss. eauto. }\n      }\n      { ss. }\n    }\n    (* racy update *)\n    { des_ifs. hexploit (ATLOCS loc); eauto. i. des. subst.\n      hexploit sim_thread_racy_update_step; eauto.\n      i. des. left. esplits. red. esplits.\n      { refl. }\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_racy_update; eauto. }\n        { ss. eauto. }\n      }\n      { ss. }\n    }\n  Qed.\n\n  Lemma sim_thread_local_program_step_release\n        f0 vers0 flag_src0 flag_tgt0 vs_src0 vs_tgt0\n        mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n        pe_tgt pe_src\n        e_tgt lc_tgt1 mem_tgt1 sc_tgt1\n        lang st0 st1\n        (SIM: SeqLiftStep.sim_thread\n                f0 vers0 flag_src0 flag_tgt0 vs_src0 vs_tgt0\n                mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n        (STEP: Local.program_step e_tgt lc_tgt0 sc_tgt0 mem_tgt0 lc_tgt1 sc_tgt1 mem_tgt1)\n        (EVENTTGT: ThreadEvent.get_program_event e_tgt = pe_tgt)\n        (EVENTLE: ProgramEvent.le pe_tgt pe_src)\n        (LANGSTEP: lang.(Language.step) pe_src st0 st1)\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        (ATOMIC: is_atomic_event pe_tgt)\n        (NORMAL: is_release pe_tgt)\n        (ATLOCS: forall loc (NNA: ~ loc_na loc),\n            (<<FLAGSRC: flag_src0 loc = false>>) /\\\n            (<<FLAGTGT: flag_tgt0 loc = false>>) /\\\n            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)>>))\n        (AT: forall loc val (ACC: is_accessing pe_tgt = Some (loc, val)), loc_at loc)\n        (ACQFLAG: forall loc\n                         (SRC: flag_src0 loc = false) (TGT: flag_tgt0 loc = true),\n            ~ is_acquire pe_tgt)\n    :\n      (<<FAILURE: Thread.steps_failure (Thread.mk lang st0 lc_src0 sc_src0 mem_src0)>>) \\/\n      exists lc_src1 mem_src1 sc_src1 lc_src2 mem_src2 sc_src2 lc_src3 mem_src3 sc_src3 f1 vers1 vs_src1 vs_tgt1 flag_tgt1 e_src,\n        (<<STEPS0: rtc (@Thread.tau_step _) (Thread.mk lang st0 lc_src0 sc_src0 mem_src0) (Thread.mk lang st0 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEP: Thread.opt_step e_src (Thread.mk lang st0 lc_src1 sc_src1 mem_src1) (Thread.mk lang st1 lc_src2 sc_src2 mem_src2)>>) /\\\n        (<<STEPS1: rtc (@Thread.tau_step _) (Thread.mk lang st1 lc_src2 sc_src2 mem_src2) (Thread.mk lang st1 lc_src3 sc_src3 mem_src3)>>) /\\\n        (<<SIM: SeqLiftStep.sim_thread\n                  f1 vers1 (fun _ => false) flag_tgt1 vs_src1 vs_tgt1\n                  mem_src3 mem_tgt1 lc_src3 lc_tgt1 sc_src3 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        (<<MAPFUTURE: map_future_memory f0 f1 mem_src3>>) /\\\n        (<<SPACE: space_future_memory (unchangable mem_tgt0 lc_tgt0.(Local.promises)) f0 mem_src0 f1 mem_src3>>) /\\\n        (<<ATLOCS: forall loc (NNA: ~ loc_na loc), option_rel Const.le (vs_tgt1 loc) (vs_src1 loc)>>) /\\\n        (<<VAL: forall loc,\n            (((<<SRC: vs_src1 loc = vs_src0 loc>>) /\\ (<<TGT: vs_tgt1 loc = vs_tgt0 loc>>))) \\/\n            (exists val_src val_tgt,\n                ((<<NNA: ~ loc_na loc>>) \\/ ((<<NONESRC: vs_src0 loc = None>>) /\\ (<<NONETGT: vs_tgt0 loc = None>>) /\\ (<<ACQ: is_acquire pe_tgt>>))) /\\\n                (<<VALSRC: vs_src1 loc = Some val_src>>) /\\ (<<VALTGT: vs_tgt1 loc = Some val_tgt>>) /\\\n                (<<VALLE: Const.le val_tgt val_src>>))>>) /\\\n        (<<DEBT: forall loc\n                        (FLAG: flag_src0 loc = false -> flag_tgt0 loc = false)\n                        (VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)),\n            flag_tgt1 loc = false>>) /\\\n        (<<EVENT: machine_event_le (ThreadEvent.get_machine_event e_tgt) (ThreadEvent.get_machine_event e_src)>>)\n  .\n  Proof.\n    assert (exists (D: Loc.t -> Prop),\n               (<<MIN: forall loc\n                              (FLAG: flag_src0 loc = false -> flag_tgt0 loc = false)\n                              (VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc)),\n                   ~ D loc>>) /\\\n               (<<DEBT: forall loc, (<<DEBT: D loc>>) \\/\n                                    ((<<FLAG: flag_src0 loc = false -> flag_tgt0 loc = false>>) /\\\n                                     (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc) \\/ flag_src0 loc = false>>))>>)).\n    { exists (fun loc => ~ ((<<FLAG: flag_src0 loc = false -> flag_tgt0 loc = false>>) /\\\n                            (<<VAL: option_rel Const.le (vs_tgt0 loc) (vs_src0 loc) \\/ flag_src0 loc = false>>))).\n      splits.\n      { i. ii. eapply H. auto. }\n      { ii. eapply or_comm. eapply classic. }\n    }\n    des. inv STEP; ss; clarify.\n    (* write *)\n    { hexploit (ATLOCS loc); eauto. i. des_ifs. des. subst.\n      hexploit sim_thread_write_step_release; eauto.\n      i. des. right. esplits.\n      { eapply rtc_implies; [|eapply STEPS]. i.\n        inv H. econs; eauto. inv TSTEP. auto.\n      }\n      { econs. econs 2. econs; cycle 1.\n        { eapply Local.step_write; eauto. }\n        { ss. }\n      }\n      { refl. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n        { rewrite VALSRC1. rewrite VALTGT1. ss. }\n      }\n      { i. hexploit (VALS loc); eauto. i. des.\n        { left. auto. }\n        { subst. right. esplits; eauto. }\n        { left. rewrite VALSRC0. rewrite VALTGT0. auto. }\n      }\n      { i. specialize (FLAG loc). des; ss. exfalso. eapply MIN; eauto. }\n      { ss. econs. }\n    }\n    (* update *)\n    { hexploit (ATLOCS loc); eauto. i. des_ifs. des. subst.\n      hexploit sim_thread_update_step_release; eauto.\n      i. des. right. esplits.\n      { eapply rtc_implies; [|eapply STEPS]. i.\n        inv H0. econs; eauto. inv TSTEP. auto.\n      }\n      { econs. econs 2. econs; cycle 1.\n        { eapply Local.step_update.\n          { eapply READ. instantiate (1:=valr0). etrans; eauto. }\n          { eauto. }\n        }\n        { ss. }\n      }\n      { refl. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { i. hexploit ATLOCS; eauto. i. des. destruct (Loc.eq_dec loc0 loc).\n        { red in UPDATED. des; subst.\n          { rewrite TGT. rewrite SRC. ss. }\n          { rewrite TGTNONE1. rewrite SRCNONE1. ss. }\n        }\n        { hexploit VALS; eauto. i. des.\n          { rewrite SRC. rewrite TGT. auto. }\n          { rewrite VALSRC. rewrite VALTGT0. ss. }\n        }\n      }\n      { i. destruct (Loc.eq_dec loc loc0).\n        { subst. red in UPDATED. des.\n          { right. esplits; eauto. }\n          { left. rewrite SRCNONE0. rewrite TGTNONE0. splits; auto. }\n        }\n        { hexploit (VALS loc); eauto. i. des; auto.\n          right. esplits; eauto.\n        }\n      }\n      { i. specialize (FLAG loc). des; ss. exfalso. eapply MIN; eauto. }\n      { ss. econs. }\n    }\n    (* fence *)\n    { hexploit sim_thread_fence_step_release; eauto.\n      { ii. eapply ACQFLAG; eauto. rewrite H. destruct ordw; ss. }\n      { ii. eapply ACQFLAG; eauto. rewrite H. destruct ordr; ss. }\n      i. des. right. esplits.\n      { refl. }\n      { econs. econs 2. econs; cycle 1.\n        { eapply Local.step_fence; eauto. }\n        { ss. }\n      }\n      { eapply rtc_implies; [|eapply STEPS]. i.\n        inv H. econs; eauto. inv TSTEP. auto.\n      }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { refl. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n      }\n      { i. hexploit (VALS loc); eauto. i. des.\n        { left. auto. }\n        { right. esplits; eauto. right. rewrite ORD. destruct ordw; ss. }\n        { right. esplits; eauto. right. rewrite ORD. ss. }\n      }\n      { i. specialize (FLAG loc). des; ss. exfalso. eapply MIN; eauto. }\n      { ss. econs. }\n    }\n    (* syscall *)\n    { des_ifs. hexploit sim_thread_fence_step_release; eauto.\n      i. des. right. esplits.\n      { refl. }\n      { econs. econs 2. econs; cycle 1.\n        { eapply Local.step_syscall; eauto. }\n        { eauto. }\n      }\n      { eapply rtc_implies; [|eapply STEPS]. i.\n        inv H. econs; eauto. inv TSTEP. auto.\n      }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { refl. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { i. hexploit ATLOCS; eauto. i. des.\n        hexploit (VALS loc); eauto. i. des.\n        { rewrite SRC. rewrite TGT. auto. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n        { rewrite VALSRC. rewrite VALTGT. ss. }\n      }\n      { i. hexploit (VALS loc); eauto. i. des.\n        { left. auto. }\n        { right. esplits; eauto. }\n        { right. esplits; eauto. }\n      }\n      { i. specialize (FLAG loc). des; ss. exfalso. eapply MIN; eauto. }\n      { ss. econs. auto. }\n    }\n    (* na write *)\n    { exfalso. inv LOCAL. destruct ord; ss. }\n    (* racy write *)\n    { left. des_ifs. hexploit (ATLOCS loc); eauto. i. des. subst.\n      hexploit sim_thread_racy_write_step; eauto.\n      i. des. esplits. red. esplits.\n      { refl. }\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_racy_write; eauto. }\n        { ss. eauto. }\n      }\n      { ss. }\n    }\n    (* racy update *)\n    { left. des_ifs. hexploit (ATLOCS loc); eauto. i. des. subst.\n      hexploit sim_thread_racy_update_step; eauto.\n      i. des. esplits. red. esplits.\n      { refl. }\n      { econs 2. econs; cycle 1.\n        { eapply Local.step_racy_update; eauto. }\n        { ss. eauto. }\n      }\n      { ss. }\n    }\n  Qed.\n\n  Lemma sim_lift_at_step_normal c:\n    forall\n      w0 p0 D0 smem_src0 smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src0 st_tgt0\n      e st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt0 p0 D0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Thread.program_step e (Thread.mk lang_tgt st_tgt0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (SIM: sim_seq_at_step_case (@sim_seq lang_src lang_tgt sim_terminal) p0 D0 (SeqState.mk lang_src st_src0 smem_src0) (SeqState.mk lang_tgt st_tgt0 smem_tgt0))\n      (ATOMIC: is_atomic_event (ThreadEvent.get_program_event e))\n      (RELEASE: is_release (ThreadEvent.get_program_event e) = false)\n      (NOMIXSRC: nomix loc_na loc_at _ st_src0)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt0)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0),\n    exists st_src1 lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) \\/\n           (exists w1 p1 D1 smem_src1 smem_tgt1,\n               (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt1 p1 D1 mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n                 (<<SIM: @sim_seq _ _ sim_terminal p1 D1 (SeqState.mk lang_src st_src1 smem_src1) (SeqState.mk lang_tgt st_tgt1 smem_tgt1)>>) /\\\n                 (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>) /\\\n                 (<<NOMIXSRC: nomix loc_na loc_at _ st_src1>>) /\\\n                 (<<NOMIXTGT: nomix loc_na loc_at _ st_tgt1>>) /\\\n                 (<<NFAILURE: ThreadEvent.get_machine_event e = MachineEvent.silent>>))).\n  Proof.\n    i. hexploit PromiseConsistent.step_promise_consistent.\n    { econs 2; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    intros CONSTGT0. ss.\n    inv STEP.\n    hexploit sim_seq_atomic_step; eauto. i. des.\n    destruct st_src1 as [st_src1 smem_src1].\n    hexploit sim_lift_src_na_steps; eauto. i. des.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    punfold NOMIXTGT. exploit NOMIXTGT; eauto. i. des.\n    punfold NOMIX. exploit NOMIX; eauto. i. des. pclearbot.\n    inv LIFT1.\n    assert (ACQFLAG: forall loc\n                            (NONE: flag_src loc = false)\n                            (SOME: flag_tgt loc = true),\n               ~ is_acquire (ThreadEvent.get_program_event e)).\n    { ii. hexploit ACQ; eauto. i. ss.\n      hexploit (FLAGS loc); eauto. i. inv H1.\n      rewrite NONE in *. rewrite SOME in *. ss.\n      hexploit TGT; auto. rewrite flag_join_comm. i.\n      specialize (H0 loc). unfold Flags.join in H0.\n      rewrite H1 in H0. rewrite SRC in H0. ss.\n    }\n    hexploit sim_thread_local_program_step_normal; eauto.\n    { ii. clarify. }\n    i. des.\n    { esplits.\n      { eauto. }\n      { left. eauto. }\n    }\n    hexploit event_step_exists.\n    { eapply (@lift_output_wf (ThreadEvent.get_program_event e) vs_src1). }\n    i. des. hexploit SIM0; eauto.\n    { eapply lift_output_wf. }\n    i. des. destruct mem_src, m2.\n    hexploit sim_lift_event_step_normal; eauto.\n    { ii. clarify. }\n    i. des. ss. esplits.\n    { etrans; eassumption. }\n    right. eexists (_, _, _). esplits; auto.\n    { econs; eauto. i. hexploit (ATLOCS loc); eauto. i. des. splits; auto. }\n    { ss. rewrite RELEASE in *. auto. }\n    { etrans; eauto. ss. splits; auto.\n      eapply Thread.rtc_tau_step_future in STEPS1; eauto. ss. des.\n      eapply Memory.future_future_weak; eauto.\n    }\n  Qed.\n\n  Lemma sim_lift_at_step_release c:\n    forall\n      w0 p0 D0 smem_src0 smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src0 st_tgt0\n      e_tgt st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt0 p0 D0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Thread.program_step e_tgt (Thread.mk lang_tgt st_tgt0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (SIM: sim_seq_at_step_case (@sim_seq lang_src lang_tgt sim_terminal) p0 D0 (SeqState.mk lang_src st_src0 smem_src0) (SeqState.mk lang_tgt st_tgt0 smem_tgt0))\n      (ATOMIC: is_atomic_event (ThreadEvent.get_program_event e_tgt))\n      (RELEASE: is_release (ThreadEvent.get_program_event e_tgt) = true)\n      (NOMIXSRC: nomix loc_na loc_at _ st_src0)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt0)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0),\n      (<<FAILURE: Thread.steps_failure (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)>>) \\/\n      exists st_src1 st_src2 lc_src1 sc_src1 mem_src1 lc_src2 sc_src2 mem_src2 lc_src3 sc_src3 mem_src3 w1 p1 D1 smem_src1 smem_tgt1 e_src,\n        (<<STEPS0: rtc (@Thread.tau_step _)\n                       (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                       (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        (<<STEPS: Thread.opt_step\n                    e_src\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)\n                    (Thread.mk _ st_src2 lc_src2 sc_src2 mem_src2)>>) /\\\n        (<<STEPS1: rtc (@Thread.tau_step _)\n                       (Thread.mk _ st_src2 lc_src2 sc_src2 mem_src2)\n                       (Thread.mk _ st_src2 lc_src3 sc_src3 mem_src3)>>) /\\\n        (<<LIFT: sim_state_lift false w1 smem_src1 smem_tgt1 p1 D1 mem_src3 mem_tgt1 lc_src3 lc_tgt1 sc_src3 sc_tgt1>>) /\\\n        (<<SIM: @sim_seq_interference _ _ sim_terminal p1 D1 (SeqState.mk lang_src st_src2 smem_src1) (SeqState.mk lang_tgt st_tgt1 smem_tgt1)>>) /\\\n        (<<SC: sim_timemap_lift w1 sc_src3 sc_tgt1>>) /\\\n        (<<MEM: sim_memory_lift w1 mem_src3 mem_tgt1>>) /\\\n        (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>) /\\\n        (<<NOMIXSRC: nomix loc_na loc_at _ st_src2>>) /\\\n        (<<NOMIXTGT: nomix loc_na loc_at _ st_tgt1>>) /\\\n        (<<EVENT: machine_event_le (ThreadEvent.get_machine_event e_tgt) (ThreadEvent.get_machine_event e_src)>>)\n  .\n  Proof.\n    i. hexploit PromiseConsistent.step_promise_consistent.\n    { econs 2; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    intros CONSTGT0. ss.\n    inv STEP. hexploit sim_seq_atomic_step; eauto. i. des.\n    destruct st_src1 as [st_src1 smem_src1].\n    hexploit sim_lift_src_na_steps; eauto. i. des.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    punfold NOMIXTGT. exploit NOMIXTGT; eauto. i. des.\n    punfold NOMIX. exploit NOMIX; eauto. i. des. pclearbot.\n    inv LIFT1.\n    assert (ACQFLAG: forall loc\n                            (NONE: flag_src loc = false)\n                            (SOME: flag_tgt loc = true),\n               ~ is_acquire (ThreadEvent.get_program_event e_tgt)).\n    { ii. hexploit ACQ; eauto. i. ss.\n      hexploit (FLAGS loc); eauto. i. inv H1.\n      rewrite NONE in *. rewrite SOME in *. ss.\n      hexploit TGT; auto. rewrite flag_join_comm. i.\n      specialize (H0 loc). unfold Flags.join in H0.\n      rewrite H1 in H0. rewrite SRC in H0. ss.\n    }\n    hexploit sim_thread_local_program_step_release; eauto. i. des.\n    { left. eapply rtc_steps_thread_failure; eauto. }\n    hexploit event_step_exists.\n    { eapply (@lift_output_wf (ThreadEvent.get_program_event e_tgt) vs_src1). }\n    i. des. hexploit SIM0; eauto.\n    { eapply lift_output_wf. }\n    i. des. destruct mem_src, m2.\n    hexploit sim_lift_event_step_release; [eapply STEP_SRC|eapply STEP1|..]; eauto.\n    i. des. esplits. right. esplits.\n    { etrans; eauto. }\n    { eauto. }\n    { eapply STEPS2. }\n    { econs; eauto. i. ss. hexploit (ATLOCS loc); eauto. i. des.\n      hexploit DEBT; eauto. i. splits; auto.\n    }\n    { rewrite RELEASE in SIM3. ss. }\n    { inv SIM2. ss. }\n    { inv SIM2. ss. splits; auto. eapply sim_memory_sim_memory_interference; eauto. }\n    { etrans; eauto. ss. i. splits; eauto.\n      eapply Thread.rtc_tau_step_future in STEPS1; eauto. ss. des.\n      eapply Thread.opt_step_future in STEP0; eauto. ss. des.\n      eapply Thread.rtc_tau_step_future in STEPS2; eauto. ss. des.\n      eapply Memory.future_future_weak; eauto. etrans; eauto. etrans; eauto.\n    }\n    { auto. }\n    { auto. }\n    { auto. }\n  Qed.\n\n  Definition racy_update_event (e: ThreadEvent.t): Prop :=\n    match e with\n    | ThreadEvent.update _ _ _ _ _ _ _ ordr ordw =>\n      orb (Ordering.le ordw Ordering.na) (Ordering.le ordr Ordering.na)\n    | _ => False\n    end.\n\n  Lemma program_step_unchangable e lc0 sc0 mem0 lc1 sc1 mem1\n        (STEP: Local.program_step e lc0 sc0 mem0 lc1 sc1 mem1)\n    :\n    unchangable mem0 lc0.(Local.promises) <4= unchangable mem1 lc1.(Local.promises).\n  Proof.\n    i. inv STEP; ss; try inv LOCAL; ss.\n    - eapply unchangable_write; eauto.\n    - inv LOCAL1. inv LOCAL2. ss. inv WRITE.\n      eapply unchangable_write; eauto.\n    - eapply unchangable_write_na; eauto.\n  Qed.\n\n  Lemma sim_lift_na_step_aux c:\n    forall\n      w0 p0 D0 smem_src0 smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src0 st_tgt0\n      e st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt0 p0 D0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Thread.program_step e (Thread.mk lang_tgt st_tgt0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (SIM: sim_seq_na_step_case (@sim_seq lang_src lang_tgt sim_terminal) p0 D0 (SeqState.mk lang_src st_src0 smem_src0) (SeqState.mk lang_tgt st_tgt0 smem_tgt0))\n      (ATOMIC: is_atomic_event (ThreadEvent.get_program_event e) = false)\n      (LOWER: is_na_write e -> mem_tgt1 = mem_tgt0)\n      (NOMIXSRC: nomix loc_na loc_at _ st_src0)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt0)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0),\n    exists st_src1 lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) \\/\n           (exists w1 p1 D1 smem_src1 smem_tgt1,\n               (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt1 p1 D1 mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n                 (<<SIM: @sim_seq _ _ sim_terminal p1 D1 (SeqState.mk lang_src st_src1 smem_src1) (SeqState.mk lang_tgt st_tgt1 smem_tgt1)>>) /\\\n                 (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>) /\\\n                 (<<NOMIXSRC: nomix loc_na loc_at _ st_src1>>) /\\\n                 (<<NOMIXTGT: nomix loc_na loc_at _ st_tgt1>>) /\\\n                 (<<FAILURE: ThreadEvent.get_machine_event e = MachineEvent.silent>>))).\n  Proof.\n    i. hexploit PromiseConsistent.step_promise_consistent.\n    { econs 2; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    intros CONSTGT0. ss.\n    hexploit Thread.program_step_future; eauto. i. des; ss.\n    inv STEP. punfold NOMIXTGT. exploit NOMIXTGT; eauto. i. des. pclearbot.\n    hexploit sim_lift_tgt_na_local_step; eauto.\n    { ii. clarify. }\n    i. des.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n    exploit SIM; eauto.\n    { econs; eauto. }\n    i. des. destruct (classic (me = MachineEvent.failure)).\n    { subst. inv STEP0. hexploit LIFTAUX; eauto. i. des. destruct st_src1.\n      hexploit sim_lift_src_na_steps; eauto. i. des; ss. destruct st_src2.\n      hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n      hexploit sim_lift_src_na_step; eauto. i. des; ss.\n      esplits; [refl|]. left. red. esplits.\n      { etrans; [eauto|]. etrans; eauto. }\n      { replace pf with true in *; [eauto|].\n        inv STEP0; ss. inv STEP2; ss.\n      }\n      { eauto. }\n    }\n    { hexploit LIFT0; eauto. i. des. destruct st_src1.\n      hexploit sim_lift_src_na_steps; eauto. i. des; ss. destruct st_src2.\n      hexploit Thread.rtc_tau_step_future; eauto. i. des; ss.\n      hexploit sim_lift_src_na_opt_step; eauto. i. des; ss. subst.\n      esplits.\n      { etrans; [eauto|]. etrans; [eauto|]. eapply Thread.tau_opt_tau; eauto.\n        inv STEP; ss.\n        { rewrite PERM in *. destruct (p0 loc); ss. }\n        { rewrite <- H1 in *. ss. }\n        { rewrite <- H1 in *. ss. }\n      }\n      { right. hexploit LIFT2; eauto. i. des. esplits; eauto.\n        etrans; eauto. eapply world_messages_le_mon.\n        { etrans; eauto. }\n        { i. eapply unchangable_rtc_tau_step_increase in STEPS; eauto. }\n        { i. eapply program_step_unchangable; eauto. }\n      }\n    }\n  Qed.\n\n  Lemma sim_lift_na_step c:\n    forall\n      w0 p0 D0 smem_src0 smem_tgt0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0\n      lang_src lang_tgt sim_terminal st_src0 st_tgt0\n      e st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1\n      (LIFT: sim_state_lift c w0 smem_src0 smem_tgt0 p0 D0 mem_src0 mem_tgt0 lc_src0 lc_tgt0 sc_src0 sc_tgt0)\n      (STEP: Thread.program_step e (Thread.mk lang_tgt st_tgt0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st_tgt1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (SIM: sim_seq_na_step_case (@sim_seq lang_src lang_tgt sim_terminal) p0 D0 (SeqState.mk lang_src st_src0 smem_src0) (SeqState.mk lang_tgt st_tgt0 smem_tgt0))\n      (ATOMIC: is_atomic_event (ThreadEvent.get_program_event e) = false)\n      (LOWER: is_na_write e -> mem_tgt1 = mem_tgt0)\n      (NOMIXSRC: nomix loc_na loc_at _ st_src0)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt0)\n      (CONSISTENT: Local.promise_consistent lc_tgt1)\n      (WF_SRC0: Local.wf lc_src0 mem_src0)\n      (WF_TGT0: Local.wf lc_tgt0 mem_tgt0)\n      (SC_SRC0: Memory.closed_timemap sc_src0 mem_src0)\n      (SC_TGT0: Memory.closed_timemap sc_tgt0 mem_tgt0)\n      (MEM_SRC0: Memory.closed mem_src0)\n      (MEM_TGT0: Memory.closed mem_tgt0),\n    exists st_src1 lc_src1 sc_src1 mem_src1,\n      (<<STEPS: rtc (@Thread.tau_step _)\n                    (Thread.mk _ st_src0 lc_src0 sc_src0 mem_src0)\n                    (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) /\\\n        ((<<FAILURE: Thread.steps_failure (Thread.mk _ st_src1 lc_src1 sc_src1 mem_src1)>>) \\/\n           (exists w1 p1 D1 smem_src1 smem_tgt1,\n               (<<LIFT: sim_state_lift true w1 smem_src1 smem_tgt1 p1 D1 mem_src1 mem_tgt1 lc_src1 lc_tgt1 sc_src1 sc_tgt1>>) /\\\n                 (<<SIM: @sim_seq _ _ sim_terminal p1 D1 (SeqState.mk lang_src st_src1 smem_src1) (SeqState.mk lang_tgt st_tgt1 smem_tgt1)>>) /\\\n                 (<<WORLD: world_messages_le (unchangable mem_src0 lc_src0.(Local.promises)) (unchangable mem_tgt0 lc_tgt0.(Local.promises)) w0 w1>>) /\\\n                 (<<NOMIXSRC: nomix loc_na loc_at _ st_src1>>) /\\\n                 (<<NOMIXTGT: nomix loc_na loc_at _ st_tgt1>>) /\\\n                 (<<FAILURE: ThreadEvent.get_machine_event e = MachineEvent.silent>>) /\\\n                 (<<UPDATE: ~ racy_update_event e>>))).\n  Proof.\n    i. hexploit PromiseConsistent.step_promise_consistent.\n    { econs 2; eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    i. ss. destruct (classic (racy_update_event e)).\n    { destruct e; ss.\n      assert (RACE: Thread.program_step (ThreadEvent.racy_update loc Time.bot valr valw ordr ordw) (Thread.mk lang_tgt st_tgt0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk lang_tgt st_tgt1 lc_tgt0 sc_tgt0 mem_tgt0)).\n      { inv STEP; ss. econs; ss. econs.\n        destruct (Ordering.le ordw Ordering.na) eqn:ORDR; ss.\n        { econs 2; eauto. }\n        { econs 1; eauto. }\n      }\n      hexploit sim_lift_na_step_aux; eauto. i. des; ss. esplits; eauto.\n    }\n    { hexploit sim_lift_na_step_aux; eauto. i. des.\n      { esplits; eauto. }\n      { esplits; eauto. right. esplits; eauto. }\n    }\n  Qed.\n\n  Lemma sim_seq_cond_sim_seq\n        c lang_src lang_tgt sim_terminal p D st_src st_tgt\n        (SIM: @sim_seq_cond c lang_src lang_tgt sim_terminal p D st_src st_tgt)\n    :\n      @sim_seq lang_src lang_tgt sim_terminal p D st_src st_tgt.\n  Proof.\n    destruct c; ss. eapply sim_seq_interference_sim_seq; auto.\n  Qed.\n\n  Lemma sim_lift lang_src lang_tgt sim_terminal:\n    forall\n      c (st_src: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n      w p D smem_src smem_tgt mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt\n      (SIM: @sim_seq_cond c _ _ sim_terminal p D (SeqState.mk _ st_src smem_src) (SeqState.mk _ st_tgt smem_tgt))\n      (NOMIXSRC: nomix loc_na loc_at _ st_src)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt)\n      (LIFT: sim_state_lift c w smem_src smem_tgt p D mem_src mem_tgt lc_src lc_tgt sc_src sc_tgt),\n      @sim_thread\n        world world_messages_le sim_memory_lift sim_timemap_lift loc_na\n        lang_src lang_tgt c w st_src lc_src sc_src mem_src st_tgt lc_tgt sc_tgt mem_tgt.\n  Proof.\n    assert (UPACO: upaco7 _sim_seq bot7 = sim_seq).\n    { repeat (let x := fresh \"x\" in extensionality x).\n      apply Coq.Logic.PropExtensionality.propositional_extensionality.\n      split; auto. i. pclearbot. auto.\n    }\n    pcofix CIH. i. pfold. ii.\n    destruct (classic (sim_seq_failure_case p (SeqState.mk _ st_src smem_src))).\n    { right. splits. red. esplits; [refl|].\n      eapply sim_lift_failure_case; eauto.\n    }\n    left. splits.\n    { ii. eapply sim_seq_cond_sim_seq in SIM. punfold SIM. inv SIM; ss.\n      rewrite UPACO in *. inv STEP_TGT.\n      { inv STEP; ss. }\n      destruct (is_atomic_event (ThreadEvent.get_program_event e_tgt)) eqn:NA.\n      { destruct (is_release (ThreadEvent.get_program_event e_tgt)) eqn:ISRELEASE.\n        { hexploit sim_lift_at_step_release; eauto. i. des.\n          { esplits; eauto. }\n          { esplits; eauto. right. esplits; eauto. }\n        }\n        { hexploit sim_lift_at_step_normal; eauto. i. des.\n          { esplits; eauto. }\n          { exfalso. destruct e_tgt eqn:EVENT; ss.\n            { destruct ord; ss. }\n            { rewrite RELEASE in *. ss. }\n            { destruct ordw; ss. }\n          }\n        }\n      }\n      { hexploit sim_lift_na_step; eauto.\n        { ii. destruct e_tgt eqn:EQ; ss. destruct ord; ss. }\n        i. des.\n        { esplits; eauto. }\n        { exfalso. destruct e_tgt eqn:EVENT; ss.\n          { destruct ord; ss. }\n          { exfalso. eapply UPDATE. destruct ordr, ordw; ss. }\n        }\n      }\n    }\n    { ii. eapply sim_seq_cond_sim_seq in SIM. punfold SIM. inv SIM; ss.\n      hexploit sim_lift_partial_case; eauto.\n    }\n    { ii. eapply sim_seq_cond_sim_seq in SIM. punfold SIM. inv SIM; ss.\n      rewrite UPACO in *. inv STEP_TGT. ss.\n      destruct (is_atomic_event (ThreadEvent.get_program_event e_tgt)) eqn:NA.\n      { destruct (is_release (ThreadEvent.get_program_event e_tgt)) eqn:ISRELEASE.\n        { hexploit sim_lift_at_step_release; eauto. i. des.\n          { esplits; eauto. }\n          { exfalso. destruct e_tgt eqn:EQ; ss.\n            inv STEP. inv LOCAL. inv LOCAL0. destruct ord; ss.\n          }\n        }\n        { hexploit sim_lift_at_step_normal; eauto. i. des.\n          { esplits; eauto. }\n          {  esplits; eauto. right. esplits; eauto. }\n        }\n      }\n      { hexploit sim_lift_na_step; eauto. i. des.\n        { esplits; eauto. }\n        { esplits; eauto. right. esplits; eauto. }\n      }\n    }\n    { ii. eapply sim_seq_cond_sim_seq in SIM. punfold SIM. inv SIM; ss.\n      hexploit sim_lift_terminal_case; eauto.\n    }\n    { ii. subst. inv STEP_TGT.\n      2:{ inv STEP. inv LOCAL; ss. }\n      inv STEP. hexploit sim_lift_interference_promise; eauto. i. des.\n      { esplits; eauto. }\n      { esplits; eauto. right. esplits; eauto. }\n    }\n    { ii. subst. hexploit sim_lift_interference_cap; eauto. i. des.\n      esplits; eauto.\n    }\n    { ii. subst. hexploit sim_lift_interference_future; try eassumption. i. des.\n      { esplits; eauto. }\n      { esplits; eauto. right. esplits; eauto. }\n    }\n  Qed.\n\n  Lemma sim_lift_init lang_src lang_tgt sim_terminal:\n    forall\n      (st_src: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n      (SIM: @sim_seq_all lang_src lang_tgt sim_terminal st_src st_tgt)\n      (NOMIXSRC: nomix loc_na loc_at _ st_src)\n      (NOMIXTGT: nomix loc_na loc_at _ st_tgt),\n      @sim_thread\n        world world_messages_le sim_memory_lift sim_timemap_lift loc_na\n        lang_src lang_tgt false initial_world\n        st_src Local.init TimeMap.bot Memory.init\n        st_tgt Local.init TimeMap.bot Memory.init.\n  Proof.\n    i. eapply sim_lift; eauto.\n    { simpl. eapply sim_seq_init. eauto. }\n    { econs; eauto.\n      { eapply initial_sim_thread. }\n      { ii. econs; refl. }\n      { ii. econs; ss. }\n      { i. splits; ss. }\n      { i. ss. }\n      { eapply initial_mappings_wf. }\n      { eapply initial_versions_wf. }\n    }\n  Qed.\nEnd LIFT.\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/SeqLiftSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1979995526252503}}
{"text": "Require Import SynthesisPlugin.\n\nTheorem fiff_2 : (2 + 2 = 5) -> (2 + 2 = 3) -> (2 + 2 = 7) <-> False.\nProof.\n  (* RunProverbotOnFile (IDENT \"~/Downloads/coq-synthesis/theories/Test.v\"). *)\n  (* StringInput abc. *)\n  (* split.  *)\n  (* - PredictTactic. *)\n  RunProverbot.\nAdmitted.\n\n(* Decompile fiff_2. *)", "meta": {"author": "agrarpan", "repo": "coq-synthesis", "sha": "1f7df84289fbe5b68c4f83cd3a21253b0487fd84", "save_path": "github-repos/coq/agrarpan-coq-synthesis", "path": "github-repos/coq/agrarpan-coq-synthesis/coq-synthesis-1f7df84289fbe5b68c4f83cd3a21253b0487fd84/theories/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1979218897797599}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import Decs.\nRequire Import Hints.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire Import TODOProof.\nRequire Import OpsemAux.\nRequire Import SimulationLocal.\nRequire Import Simulation.\nRequire Import Inject.\nRequire AssnMem.\nRequire AssnState.\nRequire Import ValidAux.\nRequire Import SoundBase.\nRequire Import SoundImplies.\nRequire Import SoundPostcondCmd.\nRequire Import SoundPostcondCall.\nRequire Import SoundPostcondPhinodes.\nRequire Import SoundInfrules.\nRequire Import SoundReduceMaydiff.\nRequire Import opsem_wf.\n\nSet Implicit Arguments.\n\nInductive valid_state_sim\n          (conf_src conf_tgt:Config)\n          (stack0_src stack0_tgt:ECStack)\n          (assnmem:AssnMem.Rel.t)\n          (idx:nat)\n          (st_src st_tgt:State): Prop :=\n| valid_state_sim_intro\n    m_src m_tgt\n    fdef_hint cmds_hint\n    inv\n    invst\n    (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n    (ECS_SRC: st_src.(ECS) = stack0_src)\n    (ECS_TGT: st_tgt.(ECS) = stack0_tgt)\n    (FDEF: valid_fdef m_src m_tgt st_src.(EC).(CurFunction) st_tgt.(EC).(CurFunction) fdef_hint)\n    (LABEL: st_src.(EC).(CurBB).(fst) = st_tgt.(EC).(CurBB).(fst))\n    inv_term\n    (CMDS: valid_cmds m_src m_tgt st_src.(EC).(CurCmds) st_tgt.(EC).(CurCmds) cmds_hint inv = Some inv_term)\n    (TERM: exists infrules,\n        valid_terminator fdef_hint (Infrules.apply_infrules m_src m_tgt infrules inv_term) m_src m_tgt\n                         (st_src.(EC).(CurFunction).(get_blocks))\n                         (st_tgt.(EC).(CurFunction).(get_blocks))\n                         (st_src.(EC).(CurBB).(fst))\n                         (st_src.(EC).(Terminator))\n                         (st_tgt.(EC).(Terminator)))\n    (STATE: AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst assnmem inv)\n    (MEM: AssnMem.Rel.sem conf_src conf_tgt st_src.(Mem) st_tgt.(Mem) assnmem)\n    (WF_SRC: wf_ConfigI conf_src /\\ wf_StateI conf_src st_src)\n    (WF_TGT: wf_ConfigI conf_tgt /\\ wf_StateI conf_tgt st_tgt)\n.\n\nLemma decide_nonzero_inject\n      TD conds_src conds_tgt decision meminj\n      (NONZERO: decide_nonzero TD conds_src decision)\n      (INJECT: genericvalues_inject.gv_inject meminj conds_src conds_tgt)\n  :\n    <<NONZERO: decide_nonzero TD conds_tgt decision>>\n.\nProof.\n  inv NONZERO.\n  red. econs; eauto.\n  eapply genericvalues_inject.simulation__GV2int; eauto.\nQed.\n\nLemma valid_sim_term\n      conf_src conf_tgt inv0 idx0\n      CurFunction0 CurBB0 Terminator0 Locals0 Allocas0\n      ECS0 Mem0 CurFunction1 CurBB1 Terminator1 Locals1 Allocas1 ECS1 Mem1\n      (ERROR_SRC : ~ error_state conf_src\n                     (mkState (mkEC CurFunction0 CurBB0 [] Terminator0 Locals0 Allocas0) ECS0 Mem0))\n      (m_src m_tgt : module)\n      fdef_hint inv_term invst\n      (CONF : AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (FDEF : valid_fdef m_src m_tgt CurFunction0 CurFunction1 fdef_hint)\n      (LABEL : fst CurBB0 = fst CurBB1)\n      (TERM: exists infrules,\n          valid_terminator fdef_hint (Infrules.apply_infrules m_src m_tgt infrules inv_term)\n                           m_src m_tgt (get_blocks CurFunction0)\n                           (get_blocks CurFunction1) (fst CurBB0) Terminator0 Terminator1)\n      (MEM : AssnMem.Rel.sem conf_src conf_tgt Mem0 Mem1 inv0)\n      (STATE : AssnState.Rel.sem conf_src conf_tgt\n                                (mkState (mkEC CurFunction0 CurBB0 [] Terminator0 Locals0 Allocas0) ECS0 Mem0)\n                                (mkState (mkEC CurFunction1 CurBB1 [] Terminator1 Locals1 Allocas1) ECS1 Mem1)\n                                invst inv0 inv_term)\n      (WF_SRC: wf_ConfigI conf_src /\\\n               wf_StateI conf_src (mkState (mkEC CurFunction0 CurBB0 [] Terminator0 Locals0 Allocas0)\n                                           ECS0 Mem0))\n      (WF_TGT: wf_ConfigI conf_tgt /\\\n               wf_StateI conf_tgt (mkState (mkEC CurFunction1 CurBB1 [] Terminator1 Locals1 Allocas1)\n                                           ECS1 Mem1))\n  :\n    <<SIM_TERM: _sim_local conf_src conf_tgt\n                           (valid_state_sim conf_src conf_tgt)\n                           ECS0 ECS1 inv0 idx0\n                           (mkState (mkEC CurFunction0 CurBB0 [] Terminator0 Locals0 Allocas0) ECS0 Mem0)\n                           (mkState (mkEC CurFunction1 CurBB1 [] Terminator1 Locals1 Allocas1) ECS1 Mem1)\n                           >>\n.\nProof.\n  des.\n  unfold valid_terminator in TERM.\n  expl apply_infrules_sound. cbn in *.\n  simtac;\n    (try by exfalso; eapply has_false_False; eauto).\n  destruct Terminator0, Terminator1; simtac.\n  + (* return *)\n    move inv0 at bottom.\n    move assnmem1 at bottom.\n    eapply _sim_local_return; eauto; ss.\n    { apply STATE0. }\n    { eapply Forall_harder; [apply STATE0|].\n      s. i.\n      rpapply H. symmetry. apply MEM0. }\n    { eapply Forall_harder; [apply STATE0|].\n      s. i.\n      rpapply H. symmetry. apply MEM0. }\n    { apply STATE0. }\n    { apply STATE0. }\n    i.\n    exploit AssnState.Rel.inject_value_spec; try exact COND0; eauto.\n    { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n    i. des. rewrite AssnState.Unary.sem_valueT_physical in VAL_TGT. ss.\n    esplits; eauto.\n    econs; eauto.\n    * eapply get_operand_valid_ptr; eauto; try apply STATE0; try apply MEM0.\n    * eapply get_operand_valid_ptr; eauto; try apply STATE0; try apply MEM0.\n  + (* return_void *)\n    eapply _sim_local_return_void; eauto; ss.\n    { apply STATE. }\n    { eapply Forall_harder; [apply STATE|].\n      s. i.\n      rpapply H. symmetry. apply MEM. }\n    { eapply Forall_harder; [apply STATE|].\n      s. i.\n      rpapply H. symmetry. apply MEM. }\n    { apply STATE. }\n    { apply STATE. }\n  + (* br *)\n    clears invst.\n    rename STATE0 into STATE1.\n    exploit nerror_nfinal_nstuck; eauto. i. des. inv x0.\n    rewrite <- (ite_spec decision l0 l3) in *. simtac.\n    exploit AssnState.Rel.inject_value_spec; eauto.\n    { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n    rewrite AssnState.Unary.sem_valueT_physical. s. i. des.\n    eapply _sim_local_step; swap 2 4. (* move 2 to the end *)\n    {\n      expl progress.\n      - ss.\n      - unfold OpsemPP.undefined_state in *.\n        des_ifs_safe; ss.\n        des; ss.\n        { des_ifs; ss. }\n        des_ifs.\n        exfalso.\n        inv H13.\n        inv CONF. inv INJECT0. ss. clarify.\n        clear - Heq0 INT INJECT.\n        unfold GV2int in *.\n        des_ifs_safe.\n        inv INJECT. inv H4. inv H3.\n        des_ifs.\n      - ii. ss.\n    }\n    { splits; ss. }\n    { splits; ss. }\n    i.\n    expl preservation (try exact WF_TGT0; eauto). rename preservation into WF_TGT_NEXT.\n    clear ERROR_SRC.\n    inv STEP. unfold valid_phinodes in *.\n    do 12 simtac0. rewrite <- (ite_spec decision0 l0 l3) in *.\n    {\n      inv CONF. inv INJECT0. ss. clarify.\n      expl decide_nonzero_inject_aux. clarify.\n      expl valid_fdef_valid_stmts (try exact COND3; eauto).\n      expl valid_fdef_valid_stmts (try exact COND7; eauto).\n      move COND1 at bottom.\n      move COND2 at bottom.\n      rename s0 into __s0__.\n      rename s into __s__.\n\n      Ltac abstr_gen_infrules HYP NAME :=\n        match goal with\n        | [H: context[(gen_infrules_next_inv false ?x ?y)] |- _ ] =>\n          check_equal H HYP;\n          abstr (gen_infrules_next_inv false x y) NAME\n        end.\n      Ltac abstr_gen_infrules_first HYP NAME :=\n        match goal with\n        | [H: context[(gen_infrules_next_inv true ?x ?y) ++ ?z] |- _ ] =>\n          check_equal H HYP;\n          abstr ((gen_infrules_next_inv true x y) ++ z) NAME\n        end.\n\n      abstr_gen_infrules COND1 infrulesA0.\n      abstr_gen_infrules COND2 infrulesB0.\n      unfold l in *.\n\n      abstr_gen_infrules_first COND1 infrulesA2.\n      abstr (ValidationHint.assertion_after_phinodes __s0__) inv_afterA.\n      assert(exists infrulesA1,\n                (Assertion.implies\n                  (Postcond.reduce_maydiff\n                     (Infrules.apply_infrules m_src m_tgt infrulesA1\n                        (Postcond.reduce_maydiff\n                           (Infrules.apply_infrules m_src m_tgt infrulesA2 t0)))) inv_afterA)).\n      { des_ifsH COND1; des_bool.\n        - esplits; ss. eassumption.\n        - exists nil. ss. etransitivity; eauto.\n          eapply implies_reduce_maydiff; eauto. }\n      clear COND1.\n\n      abstr_gen_infrules_first COND2 infrulesB2.\n      abstr (ValidationHint.assertion_after_phinodes __s__) inv_afterB.\n      abstr (ValidationHint.cmds __s__) cmdsB.\n      assert(exists infrulesB1,\n                (Assertion.implies\n                  (Postcond.reduce_maydiff\n                     (Infrules.apply_infrules m_src m_tgt infrulesB1\n                        (Postcond.reduce_maydiff\n                           (Infrules.apply_infrules m_src m_tgt infrulesB2 t)))) inv_afterB)).\n      { des_ifsH COND2; des_bool.\n        - esplits; ss. eassumption.\n        - exists nil. ss. etransitivity; eauto.\n          eapply implies_reduce_maydiff; eauto. }\n      clear COND2.\n\n      des. clarify.\n      (* expl add_terminator_cond_br. *)\n      rewrite lookupBlockViaLabelFromFdef_spec in *.\n      (* expl (lookupAL_ite fdef_hint decision0 l0 l3). *) (* TODO: Fix expl to pass thi *)\n      exploit (lookupAL_ite fdef_hint decision0 l0 l3); eauto. clear COND7 COND3. i.\n      exploit (lookupAL_ite CurFunction0.(get_blocks) decision0 l0 l3); eauto. clear COND8 COND4. i.\n      exploit (lookupAL_ite CurFunction1.(get_blocks) decision0 l0 l3); eauto. clear COND9 COND5. i.\n      (* TODO: apply & clear ? *)\n      rewrite x1 in *. clarify.\n      rewrite x2 in *. clarify.\n\n\n      expl add_terminator_cond_br.\n      destruct decision0; ss; clarify.\n      -\n        exploit postcond_phinodes_sound;\n          try exact add_terminator_cond_br; try exact COND10; try eassumption; eauto; ss; []; intro STATE2.\n        destruct STATE2 as [invst2 STATE2].\n        clears add_terminator_cond_br invst1.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE3.\n        destruct STATE3 as [invst3 [assnmem3 [STATE3 [MEM3 MEMLE3]]]]; des.\n        clears invst2.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE4.\n        destruct STATE4 as [invst4 STATE4]; des.\n        clears invst3.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE5.\n        destruct STATE5 as [invst5 [assnmem5 [STATE5 [MEM5 MEMLE5]]]]; des.\n        clears invst4.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE6.\n        destruct STATE6 as [invst6 STATE6]; des.\n        clears invst5.\n\n        assert(AssnMem.Rel.le inv0 assnmem5).\n        { etransitivity; eauto. etransitivity; eauto. }\n\n\n        esplits; eauto.\n        { econs 1. econs; eauto. rewrite lookupBlockViaLabelFromFdef_spec. ss. }\n        {\n          econs; eauto; ss.\n          - eapply implies_sound; eauto.\n            { ss. }\n          - split; ss.\n            eapply preservation; eauto.\n            rpapply sBranch; eauto. ss.\n            rewrite lookupBlockViaLabelFromFdef_spec. ss.\n            (* Are we lucky? Will there be no siuation that forces us to get wf_src before esplits? *)\n            (* Will we always be able to (easy to) re-construct sInsn like this? *)\n        }\n      -\n        exploit postcond_phinodes_sound;\n          try exact add_terminator_cond_br; try exact COND6; try eassumption; eauto; ss; []; intro STATE2.\n        destruct STATE2 as [invst2 STATE2].\n        clears add_terminator_cond_br invst1.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE3.\n        destruct STATE3 as [invst3 [assnmem3 [STATE3 [MEM3 MEMLE3]]]]; des.\n        clears invst2.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE4.\n        destruct STATE4 as [invst4 STATE4]; des.\n        clears invst3.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE5.\n        destruct STATE5 as [invst5 [assnmem5 [STATE5 [MEM5 MEMLE5]]]]; des.\n        clears invst4.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE6.\n        destruct STATE6 as [invst6 STATE6]; des.\n        clears invst5.\n\n        assert(AssnMem.Rel.le inv0 assnmem5).\n        { etransitivity; eauto. etransitivity; eauto. }\n        esplits; eauto.\n        { econs 1. econs; eauto. rewrite lookupBlockViaLabelFromFdef_spec. ss. }\n        {\n          econs; eauto; ss.\n          (* - eapply inject_allocas_inj_incr; eauto. *)\n          - eapply implies_sound; eauto.\n            { ss. }\n          - split; ss.\n            eapply preservation; eauto.\n            rpapply sBranch; eauto. ss.\n            rewrite lookupBlockViaLabelFromFdef_spec. ss.\n        }\n    }\n  + (* br_uncond *)\n    clears invst.\n    rename STATE0 into STATE1.\n    exploit nerror_nfinal_nstuck; eauto. i. des. inv x0.\n    eapply _sim_local_step; swap 2 4. (* move 2 to the end *)\n    {\n      expl progress.\n      - ss.\n      - unfold OpsemPP.undefined_state in *.\n        des_ifs; des; ss.\n      - ii. ss.\n    }\n    { split; ss. }\n    { split; ss. }\n    i.\n    expl preservation. rename preservation into WF_TGT_NEXT.\n    clear ERROR_SRC.\n    inv STEP. unfold valid_phinodes in *.\n    {\n      inv CONF. inv INJECT. ss. clarify.\n      repeat (simtac0; []).\n      expl valid_fdef_valid_stmts.\n      hide_goal.\n      abstr_gen_infrules COND0 infrulesA0.\n      unfold l in *.\n\n      abstr_gen_infrules_first COND0 infrulesA2.\n      abstr (ValidationHint.assertion_after_phinodes s) inv_afterA.\n      assert(exists infrulesA1,\n                (Assertion.implies\n                  (Postcond.reduce_maydiff\n                     (Infrules.apply_infrules m_src m_tgt infrulesA1\n                        (Postcond.reduce_maydiff\n                           (Infrules.apply_infrules m_src m_tgt infrulesA2 t)))) inv_afterA)).\n      { des_ifsH COND0; des_bool.\n        - esplits; ss. eassumption.\n        - exists nil. ss. etransitivity; eauto.\n          eapply implies_reduce_maydiff; eauto. }\n      clear COND0.\n\n      des. clarify.\n      rewrite lookupBlockViaLabelFromFdef_spec in *.\n      rewrite COND2 in *. rewrite COND3 in *. clarify.\n      rewrite add_terminator_cond_br_uncond in *.\n\n      -\n        exploit postcond_phinodes_sound;\n          try eassumption; eauto; ss; []; intro STATE2.\n        destruct STATE2 as [invst2 STATE2].\n        clears invst1.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE3.\n        destruct STATE3 as [invst3 [assnmem3 [STATE3 [MEM3 MEMLE3]]]]; des.\n        clears invst2.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE4.\n        destruct STATE4 as [invst4 STATE4]; des.\n        clears invst3.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE5.\n        destruct STATE5 as [invst5 [assnmem5 [STATE5 [MEM5 MEMLE5]]]]; des.\n        clears invst4.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE6.\n        destruct STATE6 as [invst6 STATE6]; des.\n        clears invst5.\n\n        assert(AssnMem.Rel.le inv0 assnmem5).\n        { etransitivity; eauto. etransitivity; eauto. }\n        unfold HIDDEN_GOAL.\n        esplits; eauto.\n        { econs 1. econs; eauto. rewrite lookupBlockViaLabelFromFdef_spec. ss. }\n        {\n          econs; eauto; ss.\n          (* - eapply inject_allocas_inj_incr; eauto. *)\n          - eapply implies_sound; eauto.\n            { ss. }\n          - split; ss.\n            eapply preservation; eauto.\n            econs; eauto.\n            rewrite lookupBlockViaLabelFromFdef_spec. ss.\n        }\n    }\n  + (* switch *)\n    clears invst.\n    rename STATE0 into STATE1.\n    exploit nerror_nfinal_nstuck; eauto. i. des. inv x0.\n    eapply _sim_local_step; swap 2 4. (* move 2 to the end *)\n    {\n      expl progress.\n      - ss.\n      - unfold OpsemPP.undefined_state in *.\n        des_ifs_safe; ss.\n        des; ss.\n        { des_ifs. }\n        des_ifs.\n        exfalso.\n        inv CONF. inv INJECT. ss. clarify.\n        exploit AssnState.Rel.inject_value_spec; eauto.\n        { ss. }\n        { rewrite AssnState.Unary.sem_valueT_physical. ss. eauto. }\n        i; des. rewrite AssnState.Unary.sem_valueT_physical in *. ss. clarify.\n        clear - INJECT Heq1 Heq0.\n        unfold GV2int in *.\n        des_ifs_safe.\n        inv INJECT. inv H4. inv H3.\n        des_ifs.\n      - ii. ss.\n    }\n    { split; ss. }\n    { split; ss. }\n    i.\n    expl preservation. rename preservation into WF_TGT_NEXT.\n    clear ERROR_SRC.\n    inv STEP. unfold valid_phinodes in *.\n    {\n      inv CONF. inv INJECT. ss. clarify.\n      des_sumbool. subst. (* list_const_l_dec *)\n      rename l_0 into dflt.\n      rename l1 into cases.\n      rename COND3 into COND_DFLT.\n      rename COND2 into COND_CASES.\n      repeat (simtac0; []).\n      rename COND4 into PCOND_DFLT.\n      hexploit AssnState.Rel.inject_value_spec; try exact STATE1; ss; eauto.\n      { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n      i; des.\n      rewrite AssnState.Unary.sem_valueT_physical in *. ss. clarify.\n      expl get_switch_branch_inject. clarify.\n      hide_goal.\n\n      expl add_terminator_cond_switch.\n\n      expl get_switch_branch_in_successors.\n      unfold successors_terminator in *.\n      apply nodup_In in get_switch_branch_in_successors0. ss. des.\n      { (* default *)\n        expl valid_fdef_valid_stmts.\n        clear COND_CASES.\n        subst dflt.\n        rewrite lookupBlockViaLabelFromFdef_spec in *.\n\n        move H19 at bottom.\n        move COND3 at bottom.\n        move get_switch_branch_inject at bottom.\n\n        eq_closure_tac. clarify.\n\n        abstr_gen_infrules COND_DFLT infrulesA0.\n        unfold l in *.\n\n\n        abstr_gen_infrules_first COND_DFLT infrulesA2.\n        abstr (ValidationHint.assertion_after_phinodes s) inv_afterA.\n        assert(exists infrulesA1,\n                  (Assertion.implies\n                     (Postcond.reduce_maydiff\n                        (Infrules.apply_infrules\n                           m_src m_tgt infrulesA1\n                           (Postcond.reduce_maydiff\n                              (Infrules.apply_infrules m_src m_tgt infrulesA2 t)))) inv_afterA)).\n        { des_ifsH COND_DFLT; des_bool.\n          - esplits; ss. eassumption.\n          - exists nil. ss. etransitivity; eauto.\n            eapply implies_reduce_maydiff; eauto. }\n        clear COND_DFLT.\n        des.\n\n\n\n        exploit postcond_phinodes_sound; try exact PCOND_DFLT; try exact add_terminator_cond_switch;\n          ss; eauto; []; intro STATE2. destruct STATE2 as [invst2 STATE2].\n        clears invst1.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE3.\n        destruct STATE3 as [invst3 [assnmem3 [STATE3 [MEM3 MEMLE3]]]]; des.\n        clears invst2.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE4.\n        destruct STATE4 as [invst4 STATE4]; des.\n        clears invst3.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE5.\n        destruct STATE5 as [invst5 [assnmem5 [STATE5 [MEM5 MEMLE5]]]]; des.\n        clears invst4.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE6.\n        destruct STATE6 as [invst6 STATE6]; des.\n        clears invst5.\n\n\n        assert(AssnMem.Rel.le inv0 assnmem5).\n        { etransitivity; eauto. etransitivity; eauto. }\n        unfold HIDDEN_GOAL.\n        esplits; eauto.\n        { econs 1. econs; eauto. rewrite lookupBlockViaLabelFromFdef_spec. ss. }\n        {\n          econs; eauto; ss.\n          - eapply implies_sound; eauto.\n            { ss. }\n          - split; ss.\n            eapply preservation; eauto.\n            econs; eauto.\n            rewrite lookupBlockViaLabelFromFdef_spec. ss.\n        }\n      }\n      { (* cases *)\n        (* clears dflt. *)\n        clear COND_DFLT PCOND_DFLT COND1 COND2 COND3.\n        apply list_prj2_inv in get_switch_branch_in_successors0. des.\n        rewrite forallb_forall in COND_CASES.\n        specialize (COND_CASES (x, tgt0) get_switch_branch_in_successors0).\n        clear get_switch_branch_in_successors0.\n        des_bool. des_ifs_safe. des_bool.\n        clear_tac. rename Heq into COND_CASES. rename Heq3 into PCOND_CASES.\n        rewrite lookupBlockViaLabelFromFdef_spec in *.\n        ss. eq_closure_tac. clarify.\n        expl valid_fdef_valid_stmts. ss.\n\n        abstr_gen_infrules COND_CASES infrulesA0.\n        unfold l in *.\n\n\n        abstr_gen_infrules_first COND_CASES infrulesA2.\n        abstr (ValidationHint.assertion_after_phinodes s0) inv_afterA.\n        assert(exists infrulesA1,\n                  (Assertion.implies\n                     (Postcond.reduce_maydiff\n                        (Infrules.apply_infrules\n                           m_src m_tgt infrulesA1\n                           (Postcond.reduce_maydiff\n                              (Infrules.apply_infrules m_src m_tgt infrulesA2 t0)))) inv_afterA)).\n        { des_ifsH COND_CASES; des_bool.\n          - esplits; ss. eassumption.\n          - exists nil. ss. etransitivity; eauto.\n            eapply implies_reduce_maydiff; eauto. }\n        clear COND_CASES.\n        des.\n\n\n        exploit postcond_phinodes_sound; try exact PCOND_CASES; try exact add_terminator_cond_switch;\n          ss; eauto; []; intro STATE2. destruct STATE2 as [invst2 STATE2].\n        clears invst1.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE3.\n        destruct STATE3 as [invst3 [assnmem3 [STATE3 [MEM3 MEMLE3]]]]; des.\n        clears invst2.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE4.\n        destruct STATE4 as [invst4 STATE4]; des.\n        clears invst3.\n\n        exploit apply_infrules_sound; eauto; ss; []; intro STATE5.\n        destruct STATE5 as [invst5 [assnmem5 [STATE5 [MEM5 MEMLE5]]]]; des.\n        clears invst4.\n\n        exploit reduce_maydiff_sound; eauto; ss; []; intro STATE6.\n        destruct STATE6 as [invst6 STATE6]; des.\n        clears invst5.\n\n\n        assert(AssnMem.Rel.le inv0 assnmem5).\n        { etransitivity; eauto. etransitivity; eauto. }\n        unfold HIDDEN_GOAL.\n        esplits; eauto.\n        { econs 1. econs; eauto. rewrite lookupBlockViaLabelFromFdef_spec. ss. }\n        {\n          econs; eauto; ss.\n          (* - eapply inject_allocas_inj_incr; eauto. *)\n          - eapply implies_sound; eauto.\n            { ss. }\n          - split; ss.\n            eapply preservation; eauto.\n            econs; eauto.\n            rewrite lookupBlockViaLabelFromFdef_spec. ss.\n        }\n      }\n    }\n  + (* unreachable *)\n    exploit nerror_nfinal_nstuck; eauto. i. des. inv x0.\nUnshelve.\nall: try destruct CONF; subst; ss.\nQed.\n(* TODO: Pull out same pattern as lemma or tac *)\n\n(* TODO: move to postcond.v? SoundBase? Maybe this is proper position.. *)\nLemma postcond_cmd_implies_inject_event\n      c0 c1 inv t\n      (POSTCOND: Postcond.postcond_cmd c0 c1 inv = Some t)\n  :\n    <<INJECT_EVENT: Postcond.postcond_cmd_inject_event\n                      c0 c1\n                      (if Instruction.isCallInst c0\n                       then\n                         Postcond.ForgetStackCall.t (AtomSetImpl_from_list (Postcond.Cmd.get_def c0))\n                                                    (AtomSetImpl_from_list (Postcond.Cmd.get_def c1))\n                                                    (Postcond.ForgetMemoryCall.t inv)\n                       else\n                         Postcond.ForgetStack.t\n                           (AtomSetImpl_from_list (Postcond.Cmd.get_def c0))\n                           (AtomSetImpl_from_list (Postcond.Cmd.get_def c1))\n                           (AtomSetImpl_from_list (Postcond.Cmd.get_leaked_ids c0))\n                           (AtomSetImpl_from_list (Postcond.Cmd.get_leaked_ids c1))\n                           (Postcond.ForgetMemory.t (Postcond.Cmd.get_def_memory c0)\n                                                    (Postcond.Cmd.get_def_memory c1)\n                                                    (Postcond.Cmd.get_leaked_ids_to_memory c0)\n                                                    (Postcond.Cmd.get_leaked_ids_to_memory c1) inv))\n                    = true>>\n.\nProof.\n  unfold Postcond.postcond_cmd in *.\n  unfold Postcond.postcond_cmd_check in *.\n  des_ifs; ss; des_bool; ss.\nQed.\n\nLemma valid_progress\n      conf_src conf_tgt stack0_src stack0_tgt inv0 idx0 st_src st_tgt\n      (VALID: valid_state_sim conf_src conf_tgt stack0_src stack0_tgt inv0 idx0 st_src st_tgt)\n      (ERROR_SRC: ~ error_state conf_src st_src)\n      c_src cs_src\n      (CMDSRC: st_src.(EC).(CurCmds) = c_src :: cs_src)\n      (NOTCALL: Instruction.isCallInst c_src = false)\n      c_tgt cs_tgt\n      (CMDTGT: st_tgt.(EC).(CurCmds) = c_tgt :: cs_tgt)\n      (NOTFINAL: s_isFinalState conf_tgt st_tgt = None)\n  :\n    <<PROGRESS: ~stuck_state conf_tgt st_tgt>>\n.\nProof.\n  inv VALID.\n  des.\n  expl progress; ss. clear WF_TGT WF_TGT0.\n  destruct st_src, st_tgt; ss.\n  destruct EC0, EC1; ss.\n  destruct CurCmds0, CurCmds1; ss. clarify; clear_tac.\n  des_ifs_safe.\n  unfold OpsemPP.undefined_state in *.\n  des_ifs_safe.\n  des; ss.\n  - des_ifs; ss.\n  - des_ifsH IS_UNDEFINED; ss.\n    unfold Debug.debug_print_auto in *.\n    unfold Debug.failwith_None in *.\n    des_ifs_safe.\nAbort.\n\n\nHint Unfold Debug.debug_print_auto. (* TODO: Put all debugs into this *)\nHint Unfold Debug.debug_print_validation_process.\n\nLemma apply_is_true\n      x\n  :\n    is_true x <-> x = true (* using << >> here will unable rewrite *)\n.\nProof. ss. Qed.\n\nLemma valid_sim\n      conf_src conf_tgt\n  :\n  (valid_state_sim conf_src conf_tgt) <6= (sim_local conf_src conf_tgt).\nProof.\n  pcofix CIH.\n  intros stack0_src stack0_tgt inv0 idx0 st_src st_tgt SIM. pfold.\n  apply _sim_local_src_error; try apply SIM; []. i.\n  destruct st_src, st_tgt. destruct EC0, EC1.\n  inv SIM. ss.\n  destruct CurCmds0.\n  - (* term *)\n    des.\n    simtac.\n    expl valid_sim_term.\n    eapply _sim_local_mon; eauto.\n  - (* cmd *)\n    ss. des_ifs_safe. Fail progress repeat (simtac0; []).\n    destruct (Assertion.has_false inv) eqn:T.\n    { exfalso; eapply has_false_False; eauto. }\n    autounfold in *. ss.\n    destruct (match Postcond.postcond_cmd c c0 inv with\n              | Some inv1 => Some inv1\n              | None =>\n                Postcond.postcond_cmd\n                  c c0\n                  (Infrules.apply_infrules m_src m_tgt\n                                           (gen_infrules_from_insns (insn_cmd c) (insn_cmd c0) inv) inv)\n              end) eqn: PCND; try by ss.\n\n    abstr (gen_infrules_next_inv true t0 inv ++ l1) l2.\n    clear l1. rename l2 into l1. (* to minimize proof break *)\n\n    rename t into __t__.\n    assert(PCND0: exists infrulesA,\n              Postcond.postcond_cmd\n                c c0\n                (Infrules.apply_infrules m_src m_tgt infrulesA inv) = Some t0).\n    { clear CMDS.\n      des_ifs.\n      - exists nil. esplits; ss.\n      - esplits; eassumption.\n    } clear PCND. des.\n    des_ifs_safe ss.\n\n    assert(IMPLIES: exists infrulesB,\n            Assertion.implies\n              (Postcond.reduce_maydiff\n                 (Infrules.apply_infrules\n                    m_src m_tgt infrulesB\n                    (Postcond.reduce_maydiff\n                       (Infrules.apply_infrules m_src m_tgt l1 t0)))) __t__ = true).\n    { des_ifs.\n      - exists nil. ss.\n        rewrite <- apply_is_true.\n        rewrite <- apply_is_true in Heq0.\n        etransitivity; eauto.\n        eapply implies_reduce_maydiff.\n      - esplits; eassumption.\n    } clear Heq. des.\n\n    exploit apply_infrules_sound; try apply STATE; eauto; []; intro PCND;\n      destruct PCND as [invst_pcnd [assnmem_pcnd [STATE_PCND [MEM_PCND MEMLE_PCND]]]]. des.\n    clears invst.\n\n\n    (* clears inv0. *)\n    (* MEMLE should survive. *)\n    (* TODO: if we can make a lemma, sim_local inv0 && inv0 <= inv1 => sim_local inv1, we can *)\n    (* do \"clears inv0\". *)\n    (* The lemma is not true for now, (AssnMem.Rel.le not relaxed in all cases) but it seems ok *)\n    clear MEM.\n    instantiate (1:= infrulesA) in STATE_PCND.\n    abstr (Infrules.apply_infrules m_src m_tgt infrulesA inv) inv_pcnd.\n    clears inv.\n\n    rename MEM_PCND into MEM1.\n    rename MEMLE_PCND into MEMLE1.\n    rename STATE_PCND into STATE1.\n    rename invst_pcnd into invst1.\n    rename assnmem_pcnd into assnmem1.\n    rename inv_pcnd into inv1.\n\n\n    destruct (Instruction.isCallInst c) eqn:CALL; cycle 1.\n    + ss.\n      simtac. des.\n      eapply _sim_local_step; swap 2 4. (* move 2 to the end *)\n      {\n\n        expl progress.\n        - ss.\n        - move ERROR_SRC at bottom.\n          apply error_state_neg in ERROR_SRC. des; ss. apply NNPP in ERROR_SRC. des.\n          rename ERROR_SRC into SRC_STEP.\n          rename PCND0 into POSTCOND.\n          (* rename inv into inv0. *)\n          move POSTCOND at bottom.\n          destruct conf_src; ss.\n          inv CONF. inv INJECT. ss. clarify.\n          eapply postcond_cmd_implies_inject_event in POSTCOND; des. rewrite CALL in *.\n\n          unfold OpsemPP.undefined_state in *.\n          des_ifs_safe. des; ss; des_ifs_safe; ss.\n          + des_ifs; ss.\n          + exfalso.\n            destruct c; des_ifs. ss. repeat (des_bool; des; des_sumbool). clarify.\n            inv SRC_STEP.\n            unfold alloca in *. des_ifs.\n            assert(INJECT : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem1) gn g).\n            {\n              eapply AssnState.Subset.inject_value_Subset in POSTCOND1; cycle 1.\n              { instantiate (1:= inv1).\n                etransitivity; eauto.\n                { eapply SoundForgetStack.forget_stack_Subset; eauto. }\n                etransitivity; eauto.\n                { eapply SoundForgetMemory.forget_memory_Subset; eauto. }\n                reflexivity.\n              }\n              exploit AssnState.Rel.inject_value_spec; try exact POSTCOND1; eauto.\n              { ss. }\n              { rewrite AssnState.Unary.sem_valueT_physical. ss. eauto. }\n              i; des.\n              rewrite AssnState.Unary.sem_valueT_physical in *. ss. rewrite Heq in *. clarify.\n            }\n            expl genericvalues_inject.simulation__GV2int. rewrite simulation__GV2int in *. ss.\n          + exfalso.\n            destruct c; des_ifs. ss. des_bool; des. des_sumbool. clarify.\n            inv SRC_STEP.\n            assert(INJECT : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem1) mptr0 g).\n            {\n              eapply AssnState.Subset.inject_value_Subset in POSTCOND0; cycle 1.\n              { instantiate (1:= inv1).\n                etransitivity; eauto.\n                { eapply SoundForgetStack.forget_stack_Subset; eauto. }\n                etransitivity; eauto.\n                { eapply SoundForgetMemory.forget_memory_Subset; eauto. }\n                reflexivity.\n              }\n              exploit AssnState.Rel.inject_value_spec; try exact POSTCOND0; eauto.\n              { ss. }\n              { rewrite AssnState.Unary.sem_valueT_physical. ss. rewrite <- H17. ss. }\n              i; des.\n              rewrite AssnState.Unary.sem_valueT_physical in *. ss. rewrite Heq in *. clarify.\n            }\n            {\n              (* free inject. easy *)\n              unfold free in *. des_ifs_safe.\n              unfold GV2ptr in *. des_ifs_safe.\n              repeat all_with_term ltac:(fun H => inv H) genericvalues_inject.gv_inject.\n              repeat all_with_term ltac:(fun H => inv H) memory_sim.MoreMem.val_inject.\n              exploit genericvalues_inject.mem_inj__free; eauto; try apply MEM1; i; des.\n              assert(delta = 0).\n              { inv MEM1. ss. inv WF. expl mi_bounds. }\n              clarify.\n              repeat rewrite Z.add_0_r in *.\n              rewrite <- int_add_0 in *. clarify.\n\n              des_ifs.\n              exploit genericvalues_inject.mi_bounds.\n              { apply MEM1. }\n              { eauto. }\n              i; des.\n\n              eq_closure_tac.\n              clarify.\n            }\n          +\n            destruct c; des_ifs; ss; repeat (des_bool; des; des_sumbool; clarify).\n(*             * (* nop case *) *)\n(*               exfalso. *)\n(*               rewrite SoundSnapshot.ExprPairSet_exists_filter in POSTCOND. *)\n(*               apply Exprs.ExprPairSetFacts.exists_iff in POSTCOND; [|solve_compat_bool]. *)\n(*               unfold Exprs.ExprPairSet.Exists in *. des. *)\n(*               des_ifs. des_bool. des. unfold compose in *. des_bool. *)\n(*               apply Exprs.ExprPairSetFacts.mem_iff in POSTCOND. *)\n(*               { *)\n(*                 des. des_sumbool. clarify. *)\n(*                 assert(NOT_IN_MD: Assertion.not_in_maydiff inv1 *)\n(*                                                            (Exprs.ValueT.lift Exprs.Tag.physical value1)). *)\n(*                 { *)\n(*                   expl SoundForgetStack.forget_stack_Subset. *)\n(*                   eapply AssnState.Subset.not_in_maydiff_Subset; eauto. *)\n(*                 } clear POSTCOND0. *)\n\n\n(*                 assert(DEFINED: exists val, const2GV CurTargetData0 Globals0 (const_undef typ5) = *)\n(*                                             Some val). *)\n(*                 { AD-MIT \" *)\n(* Issue on encoding definedness with undef. *)\n(* More explanation on: https://github.com/snu-sf/crellvm/issues/426\". } *)\n(*                 des. *)\n(*                 exploit AssnState.Rel.lessdef_expr_spec; eauto. *)\n(*                 { apply STATE1. } *)\n(*                 { unfold AssnState.Unary.sem_expr. ss. eauto. } *)\n(*                 i; des. ss. rewrite AssnState.Unary.sem_valueT_physical in *. ss. des_ifs. *)\n\n(*                 exploit AssnState.Rel.not_in_maydiff_value_spec; try apply STATE1; eauto. *)\n(*                 { ss.  } *)\n(*                 { rewrite AssnState.Unary.sem_valueT_physical. ss. eauto. } *)\n(*                 i; des. *)\n(*                 rewrite AssnState.Unary.sem_valueT_physical in *. ss. *)\n\n(*                 { *)\n(*                   (* load inject. easy *) *)\n(*                   unfold mload in *. des_ifs_safe. *)\n(*                   unfold GV2ptr in *. des_ifs_safe. *)\n(*                   rename g into __g__. *)\n(*                   repeat all_with_term ltac:(fun H => inv H) genericvalues_inject.gv_inject. *)\n(*                   repeat all_with_term ltac:(fun H => inv H) memory_sim.MoreMem.val_inject. *)\n(*                   exploit genericvalues_inject.simulation_mload_aux; eauto; try apply MEM1; i; des. *)\n(*                   assert(delta = 0). *)\n(*                   { inv MEM1. ss. inv WF. expl mi_bounds. } *)\n(*                   clarify. *)\n(*                   rewrite Z.add_0_r in *. *)\n(*                   rewrite <- int_add_0 in *. clarify. *)\n(*                 } *)\n(*               } *)\n            * exfalso.\n              inv SRC_STEP.\n              assert(INJECT : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem1) mp g).\n              {\n                eapply AssnState.Subset.inject_value_Subset in POSTCOND0; cycle 1.\n                { instantiate (1:= inv1).\n                  etransitivity; eauto.\n                  { eapply SoundForgetStack.forget_stack_Subset; eauto. }\n                  etransitivity; eauto.\n                  { eapply SoundForgetMemory.forget_memory_Subset; eauto. }\n                  reflexivity.\n                }\n                exploit AssnState.Rel.inject_value_spec; try exact POSTCOND0; eauto.\n                { ss. }\n                { rewrite AssnState.Unary.sem_valueT_physical. ss. rewrite <- H18. ss. }\n                i; des.\n                rewrite AssnState.Unary.sem_valueT_physical in *. ss. rewrite Heq in *. clarify.\n              }\n              {\n                (* load inject. easy *)\n                unfold mload in *. des_ifs_safe.\n                unfold GV2ptr in *. des_ifs_safe.\n                repeat all_with_term ltac:(fun H => inv H) genericvalues_inject.gv_inject.\n                repeat all_with_term ltac:(fun H => inv H) memory_sim.MoreMem.val_inject.\n                exploit genericvalues_inject.simulation_mload_aux; eauto; try apply MEM1; i; des.\n                assert(delta = 0).\n                { inv MEM1. ss. inv WF. expl mi_bounds. }\n                clarify.\n                rewrite Z.add_0_r in *.\n                rewrite <- int_add_0 in *. clarify.\n              }\n          + exfalso.\n            destruct c; des_ifs; ss; repeat (des_bool; des; des_sumbool; clarify).\n            inv SRC_STEP.\n            assert(INJECT1 : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem1) gv1 g).\n            {\n              eapply AssnState.Subset.inject_value_Subset in POSTCOND1; cycle 1.\n              { instantiate (1:= inv1).\n                etransitivity; eauto.\n                { eapply SoundForgetStack.forget_stack_Subset; eauto. }\n                etransitivity; eauto.\n                { eapply SoundForgetMemory.forget_memory_Subset; eauto. }\n                reflexivity.\n              }\n              exploit AssnState.Rel.inject_value_spec; try exact POSTCOND1; eauto.\n              { ss. }\n              { rewrite AssnState.Unary.sem_valueT_physical. ss. rewrite <- H19. ss. }\n              i; des.\n              rewrite AssnState.Unary.sem_valueT_physical in *. ss. rewrite Heq in *. clarify.\n            }\n            assert(INJECT2 : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem1) mp2 g0).\n            {\n              eapply AssnState.Subset.inject_value_Subset in POSTCOND0; cycle 1.\n              { instantiate (1:= inv1).\n                etransitivity; eauto.\n                { eapply SoundForgetStack.forget_stack_Subset; eauto. }\n                etransitivity; eauto.\n                { eapply SoundForgetMemory.forget_memory_Subset; eauto. }\n                reflexivity.\n              }\n              exploit AssnState.Rel.inject_value_spec; try exact POSTCOND0; eauto.\n              { ss. }\n              { rewrite AssnState.Unary.sem_valueT_physical. ss. rewrite <- H20. ss. }\n              i; des.\n              rewrite AssnState.Unary.sem_valueT_physical in *. ss. rewrite Heq0 in *. clarify.\n            }\n            {\n              (* mstore inject. easy *)\n              unfold mstore in *. des_ifs_safe.\n              unfold GV2ptr in *. des_ifs_safe.\n              inv INJECT2. inv H4.\n              repeat all_with_term ltac:(fun H => inv H) memory_sim.MoreMem.val_inject.\n              exploit genericvalues_inject.mem_inj_mstore_aux; eauto; try apply MEM1; i; des.\n              assert(delta = 0).\n              { inv MEM1. ss. inv WF. expl mi_bounds. }\n              clarify.\n              rewrite Z.add_0_r in *.\n              rewrite <- int_add_0 in *. clarify.\n            }\n          + destruct c; ss.\n        - i; ss.\n      }\n\n      { split; ss. }\n      { split; ss. }\n      i.\n      expl preservation. rename preservation into WF_TGT_NEXT.\n      exploit postcond_cmd_is_call; eauto. i. rewrite CALL in x0.\n      exploit sInsn_non_call; eauto; try congruence. i. des. subst. ss.\n      exploit postcond_cmd_sound; [apply WF_SRC | apply WF_TGT | apply WF_SRC0 | apply WF_TGT0|..]; eauto;\n        ss; try congruence. i. des.\n      exploit sInsn_non_call; eauto; try congruence. i. des. subst. ss.\n\n\n      (* Want to get AssnState.Rel.sem of __t__ *)\n      exploit apply_infrules_sound; try apply STATE; eauto; []; intro STATE2;\n        destruct STATE2 as [invst2 [assnmem2 [STATE2 [MEM2 MEMLE2]]]]. des. ss.\n      clears invst1.\n      instantiate (1:= l1) in STATE2.\n\n      exploit reduce_maydiff_sound; try apply STATE2; eauto; ss; []; intro STATE3.\n      destruct STATE3 as [invst3 STATE3]; des.\n      clears invst2.\n\n      exploit apply_infrules_sound; try apply STATE3; eauto; []; intro STATE4;\n        destruct STATE4 as [invst4 [assnmem4 [STATE4 [MEM4 MEMLE4]]]]. des. ss.\n      clears invst3.\n      instantiate (1:= infrulesB) in STATE4.\n\n      exploit reduce_maydiff_sound; try apply STATE4; eauto; ss; []; intro STATE5.\n      destruct STATE5 as [invst5 STATE5]; des.\n      clears invst4.\n\n      {\n        assert(AssnMem.Rel.le inv0 assnmem4).\n        { etransitivity; eauto. etransitivity; eauto. etransitivity; eauto. }\n        esplits; eauto.\n        { econs 1; eauto. }\n        { right. apply CIH. econs; eauto.\n          - eapply implies_sound; eauto.\n          - split; ss. eapply preservation; eauto.\n        }\n      }\n    + (* call *)\n      exploit postcond_cmd_is_call; eauto. i.\n      destruct c; ss. destruct c0; ss.\n      clear_tac.\n      rename t0 into __t0__.\n      hexploit postcond_call_sound; try exact PCND0; eauto;\n        (try instantiate (2 := (mkState (mkEC _ _ _ _ _ _) _ _))); ss; eauto; ss.\n      { inv WF_SRC0; ss. }\n      { inv WF_TGT0; ss. }\n      i. des. subst. des.\n\n      eapply _sim_local_call with\n          (inv2 := assnmem1)\n          (uniqs_src:= (memory_blocks_of conf_src Locals0 (Assertion.unique (Assertion.src inv1))))\n          (uniqs_tgt:= (memory_blocks_of conf_tgt Locals1 (Assertion.unique (Assertion.tgt inv1))))\n          (privs_src:= (memory_blocks_of_t conf_src _ _ (Assertion.private (Assertion.src inv1))))\n          (privs_tgt:= (memory_blocks_of_t conf_tgt _ _ (Assertion.private (Assertion.tgt inv1))));\n        ss; eauto; ss.\n      { inv STATE1. inv SRC.\n        unfold memory_blocks_of. ii.\n        des.\n        match goal with [ H: In _ (flat_map _ _) |- _ ] => eapply in_flat_map in H; eauto end.\n        des.\n        des_ifs.\n        exploit UNIQUE.\n        { apply AtomSetFacts.elements_iff, InA_iff_In; eauto. }\n        intro UNIQUE_A. inv UNIQUE_A. ss. clarify.\n        (* TODO: name clash on \"MEM\". Chnage sem_unqiue? smarter way? *)\n        exploit MEM; eauto.\n      }\n      { inv STATE1. inv SRC.\n        unfold memory_blocks_of. ii.\n        des.\n        match goal with [ H: In _ (flat_map _ _) |- _ ] => eapply in_flat_map in H; eauto end.\n        des.\n        des_ifs.\n        exploit UNIQUE.\n        { apply AtomSetFacts.elements_iff, InA_iff_In; eauto. }\n        intro UNIQUE_A. inv UNIQUE_A. ss. clarify.\n        exploit GLOBALS; eauto.\n        (* NEED TO STRENGTHEN GLOBALS *)\n      }\n\n      { inv STATE1. inv TGT.\n        unfold memory_blocks_of. ii.\n        des.\n        match goal with [ H: In _ (flat_map _ _) |- _ ] => eapply in_flat_map in H; eauto end.\n        des.\n        des_ifs.\n        exploit UNIQUE.\n        { apply AtomSetFacts.elements_iff, InA_iff_In; eauto. }\n        intro UNIQUE_A. inv UNIQUE_A. ss. clarify.\n        exploit MEM; eauto.\n      }\n      {\n        inv STATE1. inv TGT. ss.\n        unfold memory_blocks_of.\n        replace (AtomSetImpl.elements (Assertion.unique (Assertion.tgt inv1))) with ([]: list atom); cycle 1.\n        { symmetry. apply AtomSetProperties.elements_Empty; ss. }\n        ss.\n      }\n      {\n        inv STATE1. inv TGT. ss.\n        unfold memory_blocks_of.\n        replace (AtomSetImpl.elements (Assertion.unique (Assertion.tgt inv1))) with ([]: list atom); cycle 1.\n        { symmetry. apply AtomSetProperties.elements_Empty; ss. }\n        ss.\n      }\n      { inv STATE1. inv SRC. ss.\n        i. unfold memory_blocks_of_t in IN.\n        des.\n        match goal with [ H: In _ (flat_map _ _) |- _ ] => eapply in_flat_map in H; eauto end.\n        des.\n        des_ifs.\n        exploit PRIVATE; eauto.\n        { apply Exprs.IdTSetFacts.elements_iff.\n          (* apply In_InA; eauto. *)\n          apply InA_iff_In; eauto.\n          split.\n          - apply Exprs.IdT.compare_leibniz.\n          - i. subst. apply Exprs.IdTFacts.compare_refl.\n        }\n        ss. i. des. clarify.\n      }\n      { inv STATE1. inv TGT. ss.\n        i. unfold memory_blocks_of_t in IN.\n        des.\n        match goal with [ H: In _ (flat_map _ _) |- _ ] => eapply in_flat_map in H; eauto end.\n        des.\n        des_ifs.\n        exploit PRIVATE; eauto.\n        { apply Exprs.IdTSetFacts.elements_iff.\n          (* apply In_InA; eauto. *)\n          apply InA_iff_In; eauto.\n          split.\n          - apply Exprs.IdT.compare_leibniz.\n          - i. subst. apply Exprs.IdTFacts.compare_refl.\n        }\n        ss. i. des. clarify.\n      }\n\n      i.\n      exploit RETURN; eauto. intro STATE'. des.\n      hide_goal.\n      rename STATE into STATE'0.\n      rename MEM0 into MEM'0.\n      rename assnmem2 into assnmem'0.\n      rename invst2 into invst'0.\n\n      (* Want to get AssnState.Rel.sem of __t__ *)\n      (* This part is common with non-call case... can we remove redundancy? *)\n\n      exploit apply_infrules_sound; try apply STATE'0; eauto; []; intro STATE'1;\n        destruct STATE'1 as [invst'1 [assnmem'1 [STATE'1 [MEM'1 MEMLE'1]]]]. des. ss.\n      clears invst'0.\n      instantiate (1:= l1) in STATE'1.\n\n      exploit reduce_maydiff_sound; try apply STATE'1; eauto; ss; []; intro STATE'2.\n      destruct STATE'2 as [invst'2 STATE'2]; des.\n      clears invst'1.\n\n      exploit apply_infrules_sound; try apply STATE'2; eauto; []; intro STATE'3;\n        destruct STATE'3 as [invst'3 [assnmem'3 [STATE'3 [MEM'3 MEMLE'3]]]]. des. ss.\n      clears invst'2.\n      instantiate (1:= infrulesB) in STATE'3.\n\n      exploit reduce_maydiff_sound; try apply STATE'3; eauto; ss; []; intro STATE'4.\n      destruct STATE'4 as [invst'4 STATE'4]; des.\n      clears invst'3.\n\n      {\n       unfold HIDDEN_GOAL.\n        exists locals2_tgt, 0%nat, assnmem'3. splits; ss.\n        - etransitivity; eauto. etransitivity; eauto.\n        - esplits; eauto.\n          { right. apply CIH. econs; eauto.\n            - eapply implies_sound; eauto.\n          }\n      }\nUnshelve.\nall: try ss.\nQed.\n\n\n(* TODO: move to better position? with init_invvmem in SimModule *)\n(* I think the laziest point (here) may make sense in this case .. *)\nDefinition init_invst: AssnState.Rel.t :=\n  (AssnState.Rel.mk (AssnState.Unary.mk [] []) (AssnState.Unary.mk [] [])).\n\nLemma initLocals_type_spec\n      TD args argvs lc\n      a ty\n      (IN:In a (getArgsIDs args))\n      (ARGTY: lookupTypViaIDFromArgs args a = Some ty)\n      (INIT:initLocals TD args argvs = Some lc)\n  : exists gv : GenericValue,\n    ((exists gv0, fit_gv TD ty gv0 = Some gv) \\/ gundef TD ty = Some gv) /\\\n    lookupAL GenericValue lc a = Some gv.\nProof.\n  revert lc argvs IN ARGTY INIT.\n  induction args; ss.\n  i. unfold initLocals in INIT. ss.\n  des_ifs; try (by esplits; eauto using lookupAL_updateAddAL_eq);\n    by rewrite <- lookupAL_updateAddAL_neq; eauto;\n      exploit IHargs; eauto; ss; des; congruence.\nQed.\n\nLemma function_entry_args_sound\n      conf st a args ty argvs lc invst\n      (INARG: In a (getArgsIDs args))\n      (ARGTY: lookupTypViaIDFromArgs args a = Some ty)\n      (INITLOCALS_SRC : initLocals (CurTargetData conf) args argvs = Some lc)\n      (LOCALS: st.(EC).(Locals) = lc)\n  : AssnState.Unary.sem_lessdef conf st invst\n                               (Exprs.Expr.value (Exprs.ValueT.const (const_undef ty)),\n                                Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, a))).\nProof.\n  ii. ss.\n  exploit opsem_props.OpsemProps.initLocals_spec; eauto. i. des.\n  esplits.\n  - unfold AssnState.Unary.sem_idT. ss. subst. eauto.\n  - exploit initLocals_type_spec; eauto. i. des.\n    + clarify. eapply fit_gv_undef; eauto.\n    + clarify. unfold const2GV, _const2GV in *.\n      des_ifs. unfold cgv2gv. apply GVs.lessdef_refl.\nQed.\n\nLemma function_entry_args_aux\n      e1 e2 args\n      (IN : Exprs.ExprPairSet.In (e1, e2) (Assertion.add_Args_IDs args))\n  : exists a ty, In a (getArgsIDs args) /\\\n                 lookupTypViaIDFromArgs args a = Some ty /\\\n                 e1 = Exprs.Expr.value (Exprs.ValueT.const (const_undef ty)) /\\\n                 e2 = Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, a)).\nProof.\n  unfold Assertion.add_Args_IDs in *.\n  induction (getArgsIDs args) as [|a al]; simpl in *.\n  - apply Exprs.ExprPairSetFacts.empty_iff in IN. contradiction.\n  - destruct (lookupTypViaIDFromArgs args a) eqn:ARGTY.\n    + apply Exprs.ExprPairSetFacts.add_iff in IN. des.\n      * inv IN.\n        exploit Exprs.ExprPair.compare_leibniz; eauto. inversion 1.\n        esplits; eauto.\n      * apply IHal in IN. des. esplits; eauto.\n    + apply IHal in IN. des. esplits; eauto.\nQed.\n\nLemma function_entry_gids_aux\n      e1 e2 prods\n      (IN : Exprs.ExprPairSet.In (e1, e2) (Assertion.add_Gvar_IDs prods))\n  : exists gv id ty, In (product_gvar gv) prods /\\\n                     (id = getGvarID gv) /\\\n                     (lookupTypViaGIDFromProducts prods id = Some (typ_pointer ty)) /\\\n                     e1 = Exprs.Expr.value (Exprs.ValueT.const (const_undef (typ_pointer ty))) /\\\n                     e2 = Exprs.Expr.value (Exprs.ValueT.const (const_gid ty id)).\nProof.\n  unfold Assertion.add_Gvar_IDs in *.\n  remember (Assertion.getGvarIDs prods) as gvars eqn:HGVARS.\n  assert (GVARS_SPEC: forall x, In x gvars -> exists gv, In (product_gvar gv) prods /\\ getGvarID gv = x).\n  { i. unfold Assertion.getGvarIDs in HGVARS. exploit filter_map_inv.\n    - subst; eauto.\n    - i. des. des_ifs. esplits; eauto. }\n  clear HGVARS.\n  induction gvars as [|g gl]; simpl in *.\n  - apply Exprs.ExprPairSetFacts.empty_iff in IN. contradiction.\n  - destruct (lookupTypViaGIDFromProducts prods g) as [ty|] eqn:ARGTY.\n    + destruct ty; try by apply IHgl; eauto; i; apply GVARS_SPEC; intuition.\n      apply Exprs.ExprPairSetFacts.add_iff in IN. des.\n      * exploit Exprs.ExprPair.compare_leibniz; eauto. inversion 1.\n        exploit (GVARS_SPEC g); eauto.\n        i. des. clarify. esplits; eauto.\n      * apply IHgl; eauto.\n    + apply IHgl; eauto.\nQed.\n\nLemma function_entry_gids_sound\n      conf lo ndt\n      st ty invst prods gv x\n      (SYSTEM: conf.(CurSystem) = [module_intro lo ndt prods])\n      (WF: OpsemPP.wf_Config conf)\n      (IN_PROD: In (product_gvar gv) prods)\n      (ID: getGvarID gv = x)\n      (GID_TY: lookupTypViaGIDFromProducts prods x = Some (typ_pointer ty))\n  : AssnState.Unary.sem_lessdef conf st invst\n                               ((Exprs.Expr.value\n                                   (Exprs.ValueT.const (const_undef (typ_pointer ty)))),\n                                (Exprs.Expr.value (Exprs.ValueT.const (const_gid ty x)))).\nProof.\n  subst. ii. ss.\n  unfold OpsemPP.wf_Config in WF.\n  destruct conf as [sys TD curprods gl ft]. ss. destruct TD as [los nts].\n  destruct WF as [WF_NAMEDT [WF_GLOBAL [WF_SYSTEM WF_MIN]]].\n  exploit (WF_GLOBAL (getGvarID gv) (typ_pointer ty)).\n  { clarify. inv WF_SYSTEM. ss. des. des_ifs. }\n  intros (gv_wf & sz_wf & LOOKUP_GL & TYSIZE & ZDIV & CHUNK).\n  i. des.\n  esplits; eauto.\n  { unfold const2GV. ss. des_ifs. }\n  unfold cgv2gv.\n  unfold gv_chunks_match_typ in *. ss.\n  unfold const2GV, cgv2gv in *. ss. clarify.\n  destruct gv_wf as [|[v ch] gv_wf].\n  { inversion CHUNK. }\n  destruct gv_wf; [|inv CHUNK; match goal with [H:Forall2 _ _ _ |- _] => inv H end].\n  inv CHUNK. match goal with [H:vm_matches_typ _ _ |- _] => inv H end.\n  ss. clarify.\n\n  econs; eauto; [|econs].\n  ss. splits; ss. i. destruct v; ss.\n  des.\n  destruct (Nat.eq_dec wz 31); ss. clarify.\n  destruct (zle _ _); ss.\n  destruct (zlt _ _); ss.\nQed.\n\nLemma function_entry_inv_sound\n      conf_src lo_src ndt_src prods_src\n      conf_tgt lo_tgt ndt_tgt prods_tgt\n      (CONF: inject_conf conf_src conf_tgt)\n      (WF_CONF_SRC: wf_ConfigI conf_src)\n      (WF_CONF_TGT: wf_ConfigI conf_tgt)\n      (SYSTEM_SRC: conf_src.(CurSystem) = [module_intro lo_src ndt_src prods_src])\n      (SYSTEM_TGT: conf_tgt.(CurSystem) = [module_intro lo_tgt ndt_tgt prods_tgt])\n      assnmem\n      st_src st_tgt\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st_src.(Mem) st_tgt.(Mem) assnmem)\n      (INITST: st_src.(EC).(Allocas) = [] /\\ st_tgt.(EC).(Allocas) = [])\n      args args_src args_tgt\n      (INJECT_ARGS: list_forall2 (genericvalues_inject.gv_inject\n                                    (AssnMem.Rel.inject assnmem)) args_src args_tgt)\n      (VALID_SRC: List.Forall (memory_props.MemProps.valid_ptrs (Memory.Mem.nextblock st_src.(Mem))) args_src)\n      (VALID_TGT: List.Forall (memory_props.MemProps.valid_ptrs (Memory.Mem.nextblock st_tgt.(Mem))) args_tgt)\n      (INITLOCALS_SRC: initLocals (CurTargetData conf_src) args args_src =\n                       Some st_src.(EC).(Locals))\n      (INITLOCALS_TGT: initLocals (CurTargetData conf_tgt) args args_tgt =\n                       Some st_tgt.(EC).(Locals))\n      (INJECT_LOCALS: fully_inject_locals assnmem.(AssnMem.Rel.inject) st_src.(EC).(Locals) st_tgt.(EC).(Locals))\n      (WF_SRC: wf_EC st_src.(EC) /\\ wf_fdef conf_src.(CurSystem) conf_src st_src.(EC).(CurFunction))\n      (WF_TGT: wf_EC st_tgt.(EC) /\\ wf_fdef conf_tgt.(CurSystem) conf_tgt st_tgt.(EC).(CurFunction))\n      (* TODO: conf_src.(CurSystem) != [(module_of_conf conf_src)] *)\n      (* WF condition for this? which is conceptually right? *)\n      (* Anyway, let's do this lazy.. *)\n  :\n  <<SEM: AssnState.Rel.sem conf_src conf_tgt\n                          st_src st_tgt init_invst assnmem\n                          (Assertion.function_entry_inv args args prods_src prods_tgt)>>\n.\nProof.\n  (* inject_locals is reduced from below *)\n  (* proof.Inject.locals_init *)\n  destruct st_src, st_tgt; ss.\n  destruct EC0, EC1; ss.\n  des; clarify.\n  econs; ss; eauto.\n  - econs; ss; eauto.\n    + intros [e1 e2] IN. apply Exprs.ExprPairSetFacts.union_iff in IN. des.\n      * (* ARGS *)\n        exploit function_entry_args_aux; eauto.\n        i. des. subst. eapply function_entry_args_sound; eauto.\n      * (* GID *)\n        exploit function_entry_gids_aux; eauto.\n        i. des; subst. eapply function_entry_gids_sound; eauto.\n        eapply wf_ConfigI_spec in WF_CONF_SRC; eauto.\n    + ii. exfalso. eapply AtomSetFacts.empty_iff; eauto.\n    + ii. exfalso. eapply Exprs.IdTSetFacts.empty_iff; eauto.\n    + (* wf_lc *)\n      inv MEM.\n      clear SRC TGT INJECT FUNTABLE.\n      inv WF.\n      clear Hno_overlap Hmap1 Hmap2\n            (* mi_freeblocks *)\n            mi_mappedblocks mi_range_block mi_bounds mi_globals.\n      clear_tac. unfold initLocals in *.\n      (* REMARK: Originally, we proved this by using wasabi, injection implies valid *)\n      (* However, this logic no longer holds in tgt, so validitiy condition of args became needed *)\n      (* This is current proof, same logic as tgt *)\n      eapply initLocals_preserves_valid_ptrs; eauto.\n    + (* diffblock unique parent *)\n      inv MEM. clear TGT INJECT FUNTABLE.\n      inv SRC.\n      clear MEM_PARENT UNIQUE_PARENT_MEM UNIQUE_PARENT_GLOBALS NEXTBLOCK NEXTBLOCK_PARENT.\n      ii.\n      eapply sublist_In in UNIQUE_PRIVATE_PARENT; eauto.\n      expl PRIVATE_PARENT.\n      expl fully_inject_locals_spec.\n      rewrite PTR in *. unfold lift2_option in *.\n      des_ifs.\n      unfold AssnMem.private_block in *. des.\n      clear - PRIVATE_PARENT0 ING fully_inject_locals_spec.\n      ginduction fully_inject_locals_spec; ii; ss.\n      rewrite GV2blocks_cons in ING.\n      apply in_app in ING. des.\n      { destruct v1; ss. des; ss. clarify.\n        apply PRIVATE_PARENT0; eauto.\n        ii. inv H; clarify.\n      }\n      eauto.\n  - (* tgt. same with src *)\n    (* exactly copied from above *)\n    econs; ss; eauto.\n    + intros [e1 e2] IN. apply Exprs.ExprPairSetFacts.union_iff in IN. des.\n      * (* ARGS *)\n        exploit function_entry_args_aux; eauto.\n        i. des. subst. eapply function_entry_args_sound; eauto.\n      * (* GID *)\n        exploit function_entry_gids_aux; eauto.\n        i. des; subst. eapply function_entry_gids_sound; eauto.\n        eapply wf_ConfigI_spec in WF_CONF_TGT; eauto.\n    + ii. exfalso. eapply AtomSetFacts.empty_iff; eauto.\n    + ii. exfalso. eapply Exprs.IdTSetFacts.empty_iff; eauto.\n    + (* wf_lc *)\n      inv MEM.\n      clear SRC TGT INJECT FUNTABLE.\n      inv WF.\n      clear Hno_overlap Hmap1 Hmap2\n            (* mi_freeblocks *)\n            mi_freeblocks mi_range_block mi_bounds mi_globals.\n      clear_tac. unfold initLocals in *.\n      eapply initLocals_preserves_valid_ptrs; eauto.\n    + (* diffblock unique parent *)\n      inv MEM. clear SRC INJECT FUNTABLE.\n      inv TGT.\n      clear MEM_PARENT UNIQUE_PARENT_MEM UNIQUE_PARENT_GLOBALS NEXTBLOCK NEXTBLOCK_PARENT.\n      rewrite TGT_NOUNIQ. ii; ss.\n  - ii. clear NOTIN.\n    destruct id0; ss.\n    destruct t; ss.\n    unfold AssnState.Unary.sem_idT in *. ss.\n    eapply fully_inject_locals_inject_locals; eauto.\n  - econs; eauto.\nQed.\n\nLemma init_fdef_wf_EC\n      conf fdef args ec\n      (INIT: init_fdef conf fdef args ec)\n  :\n    <<WF: wf_EC ec>>\n.\nProof.\n  inv INIT; ss.\n  des_ifs.\n  econs; ss; eauto.\n  - apply orb_true_iff. left. unfold blockEqB. unfold sumbool2bool. des_ifs.\n  - unfold get_cmds_from_block. ss. apply sublist_refl.\n  - unfold terminatorEqB. unfold sumbool2bool. des_ifs.\nQed.\n\nLemma valid_init\n      m_src m_tgt\n      conf_src conf_tgt\n      stack0_src stack0_tgt\n      fdef_src fdef_tgt\n      fdef_hint\n      args_src args_tgt\n      mem_src mem_tgt\n      inv idx\n      ec_src\n      (WF_SRC: wf_ConfigI conf_src)\n      (WF_TGT: wf_ConfigI conf_tgt)\n      (SYSTEM_SRC: conf_src.(CurSystem) = [m_src])\n      (SYSTEM_TGT: conf_tgt.(CurSystem) = [m_tgt])\n      (FDEF: valid_fdef m_src m_tgt fdef_src fdef_tgt fdef_hint)\n      (ARGS: list_forall2 (genericvalues_inject.gv_inject inv.(AssnMem.Rel.inject)) args_src args_tgt)\n      (VALID_SRC: List.Forall (memory_props.MemProps.valid_ptrs (Memory.Mem.nextblock mem_src)) args_src)\n      (VALID_TGT: List.Forall (memory_props.MemProps.valid_ptrs (Memory.Mem.nextblock mem_tgt)) args_tgt)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt mem_src mem_tgt inv)\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (INIT_SRC: init_fdef conf_src fdef_src args_src ec_src)\n  :\n  exists ec_tgt,\n    (<<INIT_TGT: init_fdef conf_tgt fdef_tgt args_tgt ec_tgt>>) /\\\n    (forall (WF_SRC: wf_ConfigI conf_src /\\ wf_StateI conf_src (mkState ec_src stack0_src mem_src))\n            (WF_TGT: wf_ConfigI conf_tgt /\\ wf_StateI conf_tgt (mkState ec_tgt stack0_tgt mem_tgt))\n            (WF_FDEF_SRC: wf_fdef conf_src.(CurSystem) conf_src ec_src.(CurFunction))\n            (WF_FDEF_TGT: wf_fdef conf_tgt.(CurSystem) conf_tgt ec_tgt.(CurFunction))\n      ,\n        <<SIM:\n          valid_state_sim\n            conf_src conf_tgt\n            stack0_src stack0_tgt\n            inv idx\n            (mkState ec_src stack0_src mem_src)\n            (mkState ec_tgt stack0_tgt mem_tgt)>>).\nProof.\n  expl init_fdef_wf_EC. rename init_fdef_wf_EC0 into WF_EC_SRC. (* TODO: make \"expl into\" *)\n  inv INIT_SRC. unfold valid_fdef in FDEF. simtac.\n  exploit locals_init; eauto; [by apply CONF|apply MEM|]. i. des.\n  generalize FDEF. i.\n  unfold forallb2AL in FDEF0. ss. apply andb_true_iff in FDEF0. des.\n  do 10 simtac0.\n  unfold proj_sumbool in *. des_ifs_safe ss. clarify.\n  assert(VALID_TERM_INFRULES: exists infrules,\n            valid_terminator fdef_hint\n                             (Infrules.apply_infrules\n                                (module_intro layouts5 namedts5 products5)\n                                (module_intro layouts0 namedts0 products0)\n                                infrules t)\n                             (module_intro layouts5 namedts5 products5)\n                             (module_intro layouts0 namedts0 products0)\n                             ((l0, stmts_intro ps' cs' tmn') :: b0)\n                             ((l0, stmts_intro phinodes5 cmds5 terminator5) :: b1)\n                             l0 tmn' terminator5).\n  { simtac.\n    - exists nil. assumption.\n    - eexists; eassumption.\n  }\n  clear COND4. des.\n\n  i. des.\n\n  eexists.\n  apply dependent_split.\n  - econs; eauto; ss.\n  - intros INIT_TGT ? ? ? ? . des.\n    expl init_fdef_wf_EC. rename init_fdef_wf_EC0 into WF_EC_TGT. clear INIT_TGT.\n    econs; eauto.\n    { ss.\n      repeat\n        (try match goal with\n             | [|- is_true (if ?c then _ else _)] =>\n               let COND := fresh \"COND\" in\n               destruct c eqn:COND\n             end;\n         simtac).\n      { match goal with\n        | [H: proj_sumbool (fheader_dec ?a ?a) = false |- _] => destruct (fheader_dec a a); ss\n        end.\n      }\n      apply andb_true_iff. splits; [|by eauto].\n      repeat\n        (try match goal with\n             | [|- (if ?c then _ else _) = true] =>\n               let COND := fresh \"COND\" in\n               destruct c eqn:COND\n             end;\n         simtac).\n      { match goal with\n        | [H: proj_sumbool (id_dec ?a ?a) = false |- _] => destruct (id_dec a a); ss\n        end.\n      }\n      des_ifs_safe ss. clarify.\n    }\n    {\n      eapply implies_sound; eauto.\n      clear FDEF FDEF1. clear_tac.\n      clear COND VALID_TERM_INFRULES. clear_tac.\n      inv CONF. unfold is_empty in *. des_ifs.\n      clear COND0 COND3. clear_tac.\n      eapply function_entry_inv_sound; eauto.\n    }\nQed.\n\nLemma valid_sim_fdef\n      m_src m_tgt\n      conf_src conf_tgt\n      fdef_src fdef_tgt\n      fdef_hint\n      (SYSTEM_SRC: conf_src.(CurSystem) = [m_src])\n      (SYSTEM_TGT: conf_tgt.(CurSystem) = [m_tgt])\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (FDEF: valid_fdef m_src m_tgt fdef_src fdef_tgt fdef_hint)\n      (WF_SRC: wf_ConfigI conf_src)\n      (WF_TGT: wf_ConfigI conf_tgt)\n      (WF_FDEF_SRC: wf_fdef conf_src.(CurSystem) conf_src fdef_src)\n      (WF_FDEF_TGT: wf_fdef conf_tgt.(CurSystem) conf_tgt fdef_tgt)\n  :\n  sim_fdef conf_src conf_tgt fdef_src fdef_tgt.\nProof.\n  ii.\n  assert(WF: wf_EC ec0_src).\n  { inv SRC. ss.\n    des_ifs.\n    econs; ss; eauto.\n    - apply orb_true_iff. left. unfold blockEqB. unfold sumbool2bool. des_ifs.\n    - unfold get_cmds_from_block. ss. apply sublist_refl.\n    - unfold terminatorEqB. unfold sumbool2bool. des_ifs.\n  }\n  exploit valid_init; try exact CONF; eauto.\n  intro VALID_INIT. des.\n  esplits; eauto. i.\n  specialize (VALID_INIT0 WF_SRC0).\n  specialize (VALID_INIT0 WF_TGT0).\n  exploit VALID_INIT0.\n  { rpapply WF_FDEF_SRC. inv SRC. ss. }\n  { rpapply WF_FDEF_TGT. inv INIT_TGT. ss. }\n  intro VALID_INIT; des.\n  apply valid_sim; eauto.\nGrab Existential Variables.\n  { exact 0%nat. }\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SimulationValid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19786855279001267}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Classes.Morphisms.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcertx.common.MemoryX.\nRequire Import liblayers.lib.Functor.\nRequire Import liblayers.lib.Monad.\nRequire Import liblayers.lib.Lens.\nRequire Export liblayers.lib.Lift.\nRequire Export liblayers.compcertx.LiftMem.\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\nSection LIFTMEM.\n  Context mem bmem `{Hmem: LiftMemoryModel mem bmem}.\n\n  Local Arguments fmap : simpl never.\n\n  Global Instance liftmemx_spec:\n    Mem.MemoryModelX bmem -> Mem.MemoryModelX mem.\n  Proof.\n    intros Hbmem; split.\n    typeclasses eauto.\n    lift \u03c0 Mem.extends_extends_compose.\n    lift \u03c0 Mem.inject_extends_compose.\n    lift \u03c0 Mem.inject_compose.\n    lift \u03c0 Mem.extends_inject_compose.\n    lift \u03c0 Mem.inject_neutral_incr.\n    lift \u03c0 Mem.free_inject_neutral.\n    lift \u03c0 Mem.drop_perm_right_extends.\n    lift \u03c0 Mem.drop_perm_parallel_extends.\n    lift \u03c0 Mem.storebytes_inject_neutral.\n    {\n      lift_partial \u03c0 Mem.free_range.\n      destruct Hf; try tauto.      \n      right; eauto using lens_same_context_eq, eq_sym.\n    }\n    {\n      lift_partial \u03c0 Mem.storebytes_empty.\n      eauto using lens_same_context_eq, eq_sym.\n    }      \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/LiftMemX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19786854523442743}}
{"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 Term.\nSet Implicit Arguments.\n\nInductive VarSym : Set :=  tmVSym | tyVSym.\nInductive TNonTerminal : Set := term | type .\nDefinition vSubstType (vc : VarSym) : TNonTerminal :=\nmatch vc with  \n  tmVSym => term  | tyVSym => type \nend.\n\nInductive Terminal :Set := .\nInductive PNonTerminal : Set := | lasgn | asgn | asgnRhs.\n\n\nInductive PatProd : Set :=  | aNil | aCons | asgnP.\n\nInductive EmbedProd : Set := | asgnRhsE.\n\nDefinition EmbedLhsRhs  (_: EmbedProd)\n: (PNonTerminal * TNonTerminal) := (asgnRhs, term).\n\nNotation inrr := (fun x => inr (inr x)).\nNotation inlr := (fun x => inl (inr x)).\nNotation inll := (fun x => inl (inl x)).\n\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.\n\nInductive TermProd : Set := | app | lam | letr.\n\nDefinition tpLhsRhs (p:TermProd) :\n (TNonTerminal * \n    list ((PNonTerminal + VarSym) + (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 => []\n|lam => [(0,1)]\n|letr  => [(0,0),(0,1)]\nend.\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 NVarSpec.\n  - intro. intro. destruct x. destruct y. auto.\n  - exact vSubstType.\n  - intro H. contradiction.\n  - exact ppLhsRhs.\n  - exact EmbedLhsRhs.\n  - admit.\n  - intro. intro. destruct x. destruct y. auto.\n  - intro H. contradiction.\n  - intro. intro. destruct x. destruct y. auto.\n  - intro. intro. destruct x; destruct y; \n    try (left; cpx; fail); (try right; introv Hc; inverts Hc ; cpx).\n  - intro. intro. destruct x; destruct y; \n    try (left; cpx; fail); (try right; introv Hc; inverts Hc ; cpx).\n  - intro. intro. destruct x; destruct y; \n    try (left; cpx; fail); (try right; introv Hc; inverts Hc ; cpx).\n  - intro. intro. destruct x; destruct y; \n    try (left; cpx; fail); (try right; introv Hc; inverts Hc ; cpx).\nDefined.\n\nDefinition letrxxx : @Term letrecCFGV (@gsymTN letrecCFGV term).\nProof.\n  apply (@tnode letrecCFGV letr). apply (mpcons).\n  - simpl. apply (@pnode letrecCFGV aCons); simpl.\n    apply (mpcons); simpl.\n    + apply (@pnode letrecCFGV aNil). simpl. apply mnil.\n    + apply (mpcons); [| apply mnil].\n      apply (@pnode letrecCFGV asgnP). simpl.\n      apply (mpcons).\n      * apply pvleaf. simpl. exact nvarx.\n      * apply (mpcons);[| apply mnil].\n        apply (@embed letrecCFGV asgnRhsE). simpl.\n        apply (@vleaf letrecCFGV vsym).\n        exact nvarx.\n  - simpl. apply (mtcons);[| apply mnil].\n    apply (@vleaf letrecCFGV vsym).\n    exact nvarx.\nDefined.\n*)\n", "meta": {"author": "coq-contribs", "repo": "cfgv", "sha": "d9f4d58ddf571639217f0ba1706e1141921a693a", "save_path": "github-repos/coq/coq-contribs-cfgv", "path": "github-repos/coq/coq-contribs-cfgv/cfgv-d9f4d58ddf571639217f0ba1706e1141921a693a/LetrecFEx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.19786854145663488}}
{"text": "Require Import VST.progs.prod.\nRequire Import VST.floyd.proofauto.\n\nDefinition bound_int (v : val) (b : Z) :=\n  match v with\n  | Vint i => -b < (Int.signed i) < b\n  | _ => False\n  end.\n\nDefinition product a b := map (fun vp => Val.mul (fst vp) (snd vp)) (combine a b).\n\nDefinition product_spec :=\n  DECLARE _product\n  WITH b0 : val, sh : share, orig_a : list val, orig_b : list val, out0 : val, a0 : val\n  PRE [_out OF (tptr tlong), _a OF (tptr tint), _b OF (tptr tint)]\n    PROP (writable_share sh;\n          length orig_a = 10%nat;\n          length orig_b = 10%nat;\n          forall i, 0 <= i < 10 -> is_long (Znth i orig_a Vundef);\n          forall i, 0 <= i < 10 -> is_long (Znth i orig_b Vundef);\n          forall i, 0 <= i < 10 -> bound_int (Znth i orig_a Vundef) 134217728;\n          forall i, 0 <= i < 10 -> bound_int (Znth i orig_b Vundef) 134217728)\n    LOCAL (temp _out out0;\n           temp _a a0;\n           temp _b b0;\n           `isptr (eval_id _out);\n           `isptr (eval_id _a);\n           `isptr (eval_id _b))\n    SEP (`(data_at sh (tarray tlong 10) orig_a a0);\n         `(data_at sh (tarray tlong 10) orig_b b0);\n         `(data_at_ sh (tarray tlong 10) out0))\n  POST [ tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (`(data_at sh (tarray tlong 10) orig_a a0);\n         `(data_at sh (tarray tlong 10) orig_b b0);\n         `(data_at sh (tarray tlong 10) (product orig_a orig_b) out0)).\n\nLocal Open Scope logic.\n\nDefinition Vprog : varspecs := nil.\nDefinition Gprog : funspecs :=   ltac:(with_library prog [product_spec]).\n\nLemma cast_l2i : forall (x : val), is_long x -> is_int I32 Signed (force_val (sem_cast_l2i I32 Signed x)).\nProof.\nintros.\nunfold force_val, sem_cast_l2i.\ninduction x.\nauto.\nauto.\nFocus 2.\nauto.\nFocus 2.\nauto.\nauto.\ninversion H.\nQed.\n\nLemma product_sumarray : semax_body Vprog Gprog f_product product_spec.\nProof.\nstart_function.\nforward.\n  entailer!.\n  apply cast_l2i.\n  apply H2.\n  lia.\nforward.\n  entailer!.\n  apply cast_l2i.\n  apply H3.\n  lia.\nforward.\nforward.\nforward.\nAbort.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_prod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.1978685414566348}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Constant propagation over RTL.  This is one of the optimizations\n  performed at RTL level.  It proceeds by a standard dataflow analysis\n  and the corresponding code rewriting. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import ConstpropOp.\n\n(** * Static analysis *)\n\n(** The type [approx] of compile-time approximations of values is\n  defined in the machine-dependent part [ConstpropOp]. *)\n\n(** We equip this type of approximations with a semi-lattice structure.\n  The ordering is inclusion between the sets of values denoted by\n  the approximations. *)\n\nModule Approx <: SEMILATTICE_WITH_TOP.\n  Definition t := approx.\n  Definition eq (x y: t) := (x = y).\n  Definition eq_refl: forall x, eq x x := (@refl_equal t).\n  Definition eq_sym: forall x y, eq x y -> eq y x := (@sym_equal t).\n  Definition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := (@trans_equal t).\n  Lemma eq_dec: forall (x y: t), {x=y} + {x<>y}.\n  Proof.\n    decide equality.\n    apply Int.eq_dec.\n    apply Float.eq_dec.\n    apply Int.eq_dec.\n    apply ident_eq.\n    apply Int.eq_dec.\n  Defined.\n  Definition beq (x y: t) := if eq_dec x y then true else false.\n  Lemma beq_correct: forall x y, beq x y = true -> x = y.\n  Proof.\n    unfold beq; intros.  destruct (eq_dec x y). auto. congruence.\n  Qed.\n\n  Definition ge (x y: t) : Prop := x = Unknown \\/ y = Novalue \\/ x = y.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge; tauto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge; intuition congruence.\n  Qed.\n  Lemma ge_compat: forall x x' y y', eq x x' -> eq y y' -> ge x y -> ge x' y'.\n  Proof.\n    unfold eq, ge; intros; congruence.\n  Qed.\n  Definition bot := Novalue.\n  Definition top := Unknown.\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Lemma ge_top: forall x, ge top x.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Definition lub (x y: t) : t :=\n    if eq_dec x y then x else\n    match x, y with\n    | Novalue, _ => y\n    | _, Novalue => x\n    | _, _ => Unknown\n    end.\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\n  Lemma ge_lub_right: forall x y, ge (lub x y) y.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. subst. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\nEnd Approx.\n\nModule D := LPMap Approx.\n\n(** We keep track of read-only global variables (i.e. \"const\" global\n  variables in C) as a map from their names to their initialization\n  data. *)\n\nDefinition global_approx : Type := PTree.t (list init_data).\n\n(** Given some initialization data and a byte offset, compute a static\n  approximation of the result of a memory load from a memory block\n  initialized with this data. *)\n\nFixpoint eval_load_init (chunk: memory_chunk) (pos: Z) (il: list init_data): approx :=\n  match il with\n  | nil => Unknown\n  | Init_int8 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint8unsigned => I (Int.zero_ext 8 n)\n        | Mint8signed => I (Int.sign_ext 8 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 1) il'\n  | Init_int16 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint16unsigned => I (Int.zero_ext 16 n)\n        | Mint16signed => I (Int.sign_ext 16 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 2) il'\n  | Init_int32 n :: il' =>\n      if zeq pos 0 \n      then match chunk with Mint32 => I n | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_float32 n :: il' =>\n      if zeq pos 0\n      then match chunk with \n           | Mfloat32 => if propagate_float_constants tt then F (Float.singleoffloat n) else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_float64 n :: il' =>\n      if zeq pos 0 \n      then match chunk with\n           | Mfloat64 => if propagate_float_constants tt then F n else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 8) il'\n  | Init_addrof symb ofs :: il' =>\n      if zeq pos 0\n      then match chunk with Mint32 => G symb ofs | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_space n :: il' =>\n      eval_load_init chunk (pos - Zmax n 0) il'\n  end.\n\n(** Compute a static approximation for the result of a load at an address whose\n  approximation is known.  If the approximation points to a global variable,\n  and this global variable is read-only, we use its initialization data\n  to determine a static approximation.  Otherwise, [Unknown] is returned. *)\n\nDefinition eval_static_load (gapp: global_approx) (chunk: memory_chunk) (addr: approx) : approx :=\n  match addr with\n  | G symb ofs =>\n      match gapp!symb with\n      | None => Unknown\n      | Some il => eval_load_init chunk (Int.unsigned ofs) il\n      end\n  | _ => Unknown\n  end.\n\n(** The transfer function for the dataflow analysis is straightforward.\n  For [Iop] instructions, we set the approximation of the destination\n  register to the result of executing abstractly the operation.\n  For [Iload] instructions, we set the approximation of the destination\n  register to the result of [eval_static_load].\n  For [Icall] and [Ibuiltin], the destination register becomes [Unknown].\n  Other instructions keep the approximations unchanged, as they preserve\n  the values of all registers. *)\n\nDefinition approx_reg (app: D.t) (r: reg) := \n  D.get r app.\n\nDefinition approx_regs (app: D.t) (rl: list reg):=\n  List.map (approx_reg app) rl.\n\nDefinition transfer (gapp: global_approx) (f: function) (pc: node) (before: D.t) :=\n  match f.(fn_code)!pc with\n  | None => before\n  | Some i =>\n      match i with\n      | Iop op args res s =>\n          let a := eval_static_operation op (approx_regs before args) in\n          D.set res a before\n      | Iload chunk addr args dst s =>\n          let a := eval_static_load gapp chunk\n                     (eval_static_addressing addr (approx_regs before args)) in\n          D.set dst a before\n      | Icall sig ros args res s =>\n          D.set res Unknown before\n      | Ibuiltin ef args res s =>\n          D.set res Unknown before\n      | _ =>\n          before\n      end\n  end.\n\n(** The static analysis itself is then an instantiation of Kildall's\n  generic solver for forward dataflow inequations. [analyze f]\n  returns a mapping from program points to mappings of pseudo-registers\n  to approximations.  It can fail to reach a fixpoint in a reasonable\n  number of iterations, in which case we use the trivial mapping\n  (program point -> [D.top]) instead. *)\n\nModule DS := Dataflow_Solver(D)(NodeSetForward).\n\nDefinition analyze (gapp: global_approx) (f: RTL.function): PMap.t D.t :=\n  match DS.fixpoint (successors f) (transfer gapp f) \n                    ((f.(fn_entrypoint), D.top) :: nil) with\n  | None => PMap.init D.top\n  | Some res => res\n  end.\n\n(** * Code transformation *)\n\n(** The code transformation proceeds instruction by instruction.\n    Operators whose arguments are all statically known are turned\n    into ``load integer constant'', ``load float constant'' or\n    ``load symbol address'' operations.  Likewise for loads whose\n    result can be statically predicted.  Operators for which some\n    but not all arguments are known are subject to strength reduction,\n    and similarly for the addressing modes of load and store instructions.\n    Conditional branches and multi-way branches are statically resolved\n    into [Inop] instructions if possible. Other instructions are unchanged.\n\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 (app: D.t) (ros: reg + ident) : reg + ident :=\n  match ros with\n  | inl r =>\n      match D.get r app with\n      | G symb ofs => if Int.eq ofs Int.zero then inr _ symb else ros\n      | _ => ros\n      end\n  | inr s => ros\n  end.\n\nParameter generate_float_constants : unit -> bool.\n\nDefinition const_for_result (a: approx) : option operation :=\n  match a with\n  | I n => Some(Ointconst n)\n  | F n => if generate_float_constants tt then Some(Ofloatconst n) else None\n  | G symb ofs => Some(Oaddrsymbol symb ofs)\n  | S ofs => Some(Oaddrstack ofs)\n  | _ => None\n  end.\n\nFixpoint successor_rec (n: nat) (f: function) (app: D.t) (pc: node) : node :=\n  match n with\n  | O => pc\n  | Datatypes.S n' =>\n      match f.(fn_code)!pc with\n      | Some (Inop s) =>\n          successor_rec n' f app s\n      | Some (Icond cond args s1 s2) =>\n          match eval_static_condition cond (approx_regs app args) with\n          | Some b => 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) (app: D.t) (pc: node) : node :=\n  successor_rec num_iter f app pc.\n\nFunction annot_strength_reduction\n     (app: D.t) (targs: list annot_arg) (args: list reg) :=\n  match targs, args with\n  | AA_arg ty :: targs', arg :: args' =>\n      let (targs'', args'') := annot_strength_reduction app targs' args' in\n      match ty, approx_reg app arg with\n      | Tint, I n => (AA_int n :: targs'', args'')\n      | Tfloat, F n => (AA_float n :: targs'', args'')\n      | _, _ => (AA_arg ty :: targs'', arg :: args'')\n      end\n  | targ :: targs', _ =>\n      let (targs'', args'') := annot_strength_reduction app targs' args in\n      (targ :: targs'', args'')\n  | _, _ =>\n      (targs, args)\n  end.\n\nFunction builtin_strength_reduction\n      (app: D.t) (ef: external_function) (args: list reg) :=\n  match ef, args with\n  | EF_vload chunk, r1 :: nil =>\n      match approx_reg app r1 with\n      | G symb n1 => (EF_vload_global chunk symb n1, nil)\n      | _ => (ef, args)\n      end\n  | EF_vstore chunk, r1 :: r2 :: nil =>\n      match approx_reg app r1 with\n      | G symb n1 => (EF_vstore_global chunk symb n1, r2 :: nil)\n      | _ => (ef, args)\n      end\n  | EF_annot text targs, args =>\n      let (targs', args') := annot_strength_reduction app targs args in\n      (EF_annot text targs', args')\n  | _, _ =>\n      (ef, args)\n  end.\n\nDefinition transf_instr (gapp: global_approx) (f: function) (apps: PMap.t D.t)\n                       (pc: node) (instr: instruction) :=\n  let app := apps!!pc in\n  match instr with\n  | Iop op args res s =>\n      let a := eval_static_operation op (approx_regs app args) in\n      let s' := successor f (D.set res a app) 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 (approx_regs app args) in\n          Iop op' args' res s'\n      end\n  | Iload chunk addr args dst s =>\n      let a := eval_static_load gapp chunk\n                  (eval_static_addressing addr (approx_regs app args)) in\n      match const_for_result a with\n      | Some cop =>\n          Iop cop nil dst s\n      | None =>\n          let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n          Iload chunk addr' args' dst s      \n      end\n  | Istore chunk addr args src s =>\n      let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n      Istore chunk addr' args' src s      \n  | Icall sig ros args res s =>\n      Icall sig (transf_ros app ros) args res s\n  | Itailcall sig ros args =>\n      Itailcall sig (transf_ros app ros) args\n  | Ibuiltin ef args res s =>\n      let (ef', args') := builtin_strength_reduction app ef args in\n      Ibuiltin ef' args' res s\n  | Icond cond args s1 s2 =>\n      match eval_static_condition cond (approx_regs app args) with\n      | Some b =>\n          if b then Inop s1 else Inop s2\n      | None =>\n          let (cond', args') := cond_strength_reduction cond args (approx_regs app args) in\n          Icond cond' args' s1 s2\n      end\n  | Ijumptable arg tbl =>\n      match approx_reg app arg with\n      | I n =>\n          match list_nth_z tbl (Int.unsigned n) with\n          | Some s => Inop s\n          | None => instr\n          end\n      | _ => instr\n      end\n  | _ =>\n      instr\n  end.\n\nDefinition transf_code (gapp: global_approx) (f: function) (app: PMap.t D.t) (instrs: code) : code :=\n  PTree.map (transf_instr gapp f app) instrs.\n\nDefinition transf_function (gapp: global_approx) (f: function) : function :=\n  let approxs := analyze gapp f in\n  mkfunction\n    f.(fn_id)\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (transf_code gapp f approxs f.(fn_code))\n    f.(fn_entrypoint).\n\nDefinition transf_fundef (gapp: global_approx) (fd: fundef) : fundef :=\n  AST.transf_fundef (transf_function gapp) fd.\n\nFixpoint make_global_approx (gapp: global_approx) (gdl: list (ident * globdef fundef unit)): global_approx :=\n  match gdl with\n  | nil => gapp\n  | (id, gl) :: gdl' =>\n      let gapp1 :=\n        match gl with\n        | Gfun f => PTree.remove id gapp\n        | Gvar gv =>\n            if gv.(gvar_readonly) && negb gv.(gvar_volatile)\n            then PTree.set id gv.(gvar_init) gapp\n            else PTree.remove id gapp\n        end in\n      make_global_approx gapp1 gdl'\n  end.\n\nDefinition transf_program (p: program) : program :=\n  let gapp := make_global_approx (PTree.empty _) p.(prog_defs) in\n  transform_program (transf_fundef gapp) p.\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/Constprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19786853993434267}}
{"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.\nRequire Import v1.Expr.\n\nRequire Import v1.EpicsTypes.\n\nRequire v1.EpicsRecordsBase.\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\nDefinition set_calc_A_to_L  (r : calc_abs ) x0' : calc_abs  :=\n    let '(CalcAbs  x0 x1) := r in\n    CalcAbs  x0' x1.\n\nDefinition set_calc_VAL  (r : calc_abs ) x1' : calc_abs  :=\n    let '(CalcAbs  x0 x1) := r in\n    CalcAbs  x0 x1'.\n\nDefinition set_calc_out_A_to_L  (r : calc_out_abs ) x0' : calc_out_abs  :=\n    let '(CalcOutAbs  x0 x1 x2 x3 x4) := r in\n    CalcOutAbs  x0' x1 x2 x3 x4.\n\nDefinition set_calc_out_VAL  (r : calc_out_abs ) x1' : calc_out_abs  :=\n    let '(CalcOutAbs  x0 x1 x2 x3 x4) := r in\n    CalcOutAbs  x0 x1' x2 x3 x4.\n\nDefinition set_calc_out_PVAL  (r : calc_out_abs ) x2' : calc_out_abs  :=\n    let '(CalcOutAbs  x0 x1 x2 x3 x4) := r in\n    CalcOutAbs  x0 x1 x2' x3 x4.\n\nDefinition set_calc_out_OVAL  (r : calc_out_abs ) x3' : calc_out_abs  :=\n    let '(CalcOutAbs  x0 x1 x2 x3 x4) := r in\n    CalcOutAbs  x0 x1 x2 x3' x4.\n\nDefinition set_calc_out_tmp0  (r : calc_out_abs ) x4' : calc_out_abs  :=\n    let '(CalcOutAbs  x0 x1 x2 x3 x4) := r in\n    CalcOutAbs  x0 x1 x2 x3 x4'.\n\nDefinition set_str_calc_out_A_to_L  (r : str_calc_out_abs ) x0' : str_calc_out_abs  :=\n    let '(StrCalcOutAbs  x0 x1 x2 x3 x4) := r in\n    StrCalcOutAbs  x0' x1 x2 x3 x4.\n\nDefinition set_str_calc_out_VAL  (r : str_calc_out_abs ) x1' : str_calc_out_abs  :=\n    let '(StrCalcOutAbs  x0 x1 x2 x3 x4) := r in\n    StrCalcOutAbs  x0 x1' x2 x3 x4.\n\nDefinition set_str_calc_out_PVAL  (r : str_calc_out_abs ) x2' : str_calc_out_abs  :=\n    let '(StrCalcOutAbs  x0 x1 x2 x3 x4) := r in\n    StrCalcOutAbs  x0 x1 x2' x3 x4.\n\nDefinition set_str_calc_out_OVAL  (r : str_calc_out_abs ) x3' : str_calc_out_abs  :=\n    let '(StrCalcOutAbs  x0 x1 x2 x3 x4) := r in\n    StrCalcOutAbs  x0 x1 x2 x3' x4.\n\nDefinition set_str_calc_out_tmp0  (r : str_calc_out_abs ) x4' : str_calc_out_abs  :=\n    let '(StrCalcOutAbs  x0 x1 x2 x3 x4) := r in\n    StrCalcOutAbs  x0 x1 x2 x3 x4'.\n\nDefinition set_array_calc_out_A_to_L {n} (r : array_calc_out_abs n) x0' : array_calc_out_abs n :=\n    let '(ArrayCalcOutAbs _ x0 x1 x2 x3 x4) := r in\n    ArrayCalcOutAbs _ x0' x1 x2 x3 x4.\n\nDefinition set_array_calc_out_VAL {n} (r : array_calc_out_abs n) x1' : array_calc_out_abs n :=\n    let '(ArrayCalcOutAbs _ x0 x1 x2 x3 x4) := r in\n    ArrayCalcOutAbs _ x0 x1' x2 x3 x4.\n\nDefinition set_array_calc_out_PVAL {n} (r : array_calc_out_abs n) x2' : array_calc_out_abs n :=\n    let '(ArrayCalcOutAbs _ x0 x1 x2 x3 x4) := r in\n    ArrayCalcOutAbs _ x0 x1 x2' x3 x4.\n\nDefinition set_array_calc_out_OVAL {n} (r : array_calc_out_abs n) x3' : array_calc_out_abs n :=\n    let '(ArrayCalcOutAbs _ x0 x1 x2 x3 x4) := r in\n    ArrayCalcOutAbs _ x0 x1 x2 x3' x4.\n\nDefinition set_array_calc_out_tmp0 {n} (r : array_calc_out_abs n) x4' : array_calc_out_abs n :=\n    let '(ArrayCalcOutAbs _ x0 x1 x2 x3 x4) := r in\n    ArrayCalcOutAbs _ x0 x1 x2 x3 x4'.\n\nDefinition set_analog_in_VAL  (r : analog_in_abs ) x0' : analog_in_abs  :=\n    let '(AnalogInAbs  x0) := r in\n    AnalogInAbs  x0'.\n\nDefinition set_analog_out_VAL  (r : analog_out_abs ) x0' : analog_out_abs  :=\n    let '(AnalogOutAbs  x0 x1) := r in\n    AnalogOutAbs  x0' x1.\n\nDefinition set_analog_out_PVAL  (r : analog_out_abs ) x1' : analog_out_abs  :=\n    let '(AnalogOutAbs  x0 x1) := r in\n    AnalogOutAbs  x0 x1'.\n\nDefinition set_binary_in_VAL  (r : binary_in_abs ) x0' : binary_in_abs  :=\n    let '(BinaryInAbs  x0) := r in\n    BinaryInAbs  x0'.\n\nDefinition set_binary_out_VAL  (r : binary_out_abs ) x0' : binary_out_abs  :=\n    let '(BinaryOutAbs  x0) := r in\n    BinaryOutAbs  x0'.\n\nDefinition set_mbbo_VAL  (r : mbbo_abs ) x0' : mbbo_abs  :=\n    let '(MBBOAbs  x0) := r in\n    MBBOAbs  x0'.\n\nDefinition set_long_in_VAL  (r : long_in_abs ) x0' : long_in_abs  :=\n    let '(LongInAbs  x0) := r in\n    LongInAbs  x0'.\n\nDefinition set_long_out_VAL  (r : long_out_abs ) x0' : long_out_abs  :=\n    let '(LongOutAbs  x0) := r in\n    LongOutAbs  x0'.\n\nDefinition set_dfanout_VAL  (r : dfanout_abs ) x0' : dfanout_abs  :=\n    let '(DFanoutAbs  x0) := r in\n    DFanoutAbs  x0'.\n\nDefinition set_seq_DO1_to_DOA  (r : seq_abs ) x0' : seq_abs  :=\n    let '(SeqAbs  x0) := r in\n    SeqAbs  x0'.\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/FloatAbsBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101154203231, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.19780931554987743}}
{"text": "Require Import Examples.AutoSep Examples.Malloc.\n\n\n(* Two definitions based on hiding functions inside a new datatype, to avoid confusing our reification tactics *)\nInductive fn := Fn (f : W -> W).\nDefinition app (f : fn) (x : W) := let (f) := f in f x.\n\n(* What does it mean for a program counter to implement a mathematical function? *)\nDefinition goodMemo (f : fn) (pc : W) : HProp := fun s m =>\n  (ExX : settings * state, Cptr pc #0\n    /\\ ExX : settings * smem, #0 (s, m)\n    /\\ Al st : settings * state, AlX : settings * smem, AlX : settings * state,\n    (Ex vs, Cptr st#Rp #0\n      /\\ ![ ^[locals (\"rp\" :: \"x\" :: nil) vs 0 st#Sp] * #1 * #2 ] st\n      /\\ Al st' : state,\n      ([| Regs st' Sp = st#Sp /\\ Regs st' Rv = app f (sel vs \"x\") |]\n        /\\ Ex vs', ![ ^[locals (\"rp\" :: \"x\" :: nil) vs' 0 st#Sp] * #1 * #2 ] (fst st, st'))\n      ---> #0 (fst st, st'))\n    ---> #3 st)%PropX.\n\nModule Type MEMO.\n  Parameter memo : fn -> W -> HProp.\n  (* Arguments: mathematical function that is implemented, and pointer to private data *)\n\n  Axiom memo_fwd : forall f p,\n    memo f p ===> Ex pc, Ex lastIn, Ex lastOut, (p ==*> pc, lastIn, lastOut) * [| lastOut = app f lastIn |] * goodMemo f pc.\n\n  Axiom memo_bwd : forall f p,\n    (Ex pc, Ex lastIn, Ex lastOut, (p ==*> pc, lastIn, lastOut) * [| lastOut = app f lastIn|] * goodMemo f pc) ===> memo f p.\nEnd MEMO.\n\nModule Memo : MEMO.\n  Definition memo (f : fn) (p : W) : HProp :=\n    (Ex pc, Ex lastIn, Ex lastOut, (p ==*> pc, lastIn, lastOut) * [| lastOut = app f lastIn |] * goodMemo f pc)%Sep.\n\n  Theorem memo_fwd : forall (f : fn) p,\n    memo f p ===> Ex pc, Ex lastIn, Ex lastOut, (p ==*> pc, lastIn, lastOut) * [| lastOut = app f lastIn |] * goodMemo f pc.\n    unfold memo; sepLemma.\n  Qed.\n\n  Theorem memo_bwd : forall f p,\n    (Ex pc, Ex lastIn, Ex lastOut, (p ==*> pc, lastIn, lastOut) * [| lastOut = app f lastIn|] * goodMemo f pc) ===> memo f p.\n    unfold memo; sepLemma.\n  Qed.\nEnd Memo.\n\nImport Memo.\nExport Memo.\n\nDefinition hints : TacPackage.\n  prepare memo_fwd memo_bwd.\nDefined.\n\nDefinition initS : spec := SPEC(\"f\", \"in\", \"out\") reserving 7\n  Al f,\n  PRE[V] goodMemo f (V \"f\") * [| V \"out\" = app f (V \"in\") |] * mallocHeap\n  POST[R] memo f R * mallocHeap.\n\nDefinition callS : spec := SPEC(\"m\", \"x\") reserving 4\n  Al f,\n  PRE[V] memo f (V \"m\")\n  POST[R] [| R = app f (V \"x\") |] * memo f (V \"m\").\n\nDefinition memoizeM := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"memoize\" {{\n  bfunction \"init\"(\"f\", \"in\", \"out\", \"r\") [initS]\n    \"r\" <-- Call \"malloc\"!\"malloc\"(1)\n    [PRE[V, R] R =?> 3\n     POST[R'] [| R' = R |] * R ==*> V \"f\", V \"in\", V \"out\" ];;\n    \"r\" *<- \"f\";;\n    \"r\" <- \"r\" + 4;;\n    \"r\" *<- \"in\";;\n    \"r\" <- \"r\" + 4;;\n    \"r\" *<- \"out\";;\n    Return \"r\" - 8\n  end with bfunction \"call\"(\"m\", \"x\", \"tmp\", \"tmp2\") [callS]\n    \"tmp\" <-* \"m\" + 4;;\n    If (\"x\" = \"tmp\") {\n      (* We're in luck!  This call is cached. *)\n\n      \"tmp\" <-* \"m\" + 8;;\n      Return \"tmp\"\n    } else {\n      (* This is a different argument from last time.  Call the function again. *)\n\n      \"tmp\" <-* \"m\";;\n      \"tmp\" <-- ICall \"tmp\"(\"x\")\n      [Al f,\n        PRE[V, R] [| R = app f (V \"x\") |] * memo f (V \"m\")\n        POST[R'] [| R' = R |] * memo f (V \"m\") ];;\n\n      \"tmp2\" <- \"m\" + 4;;\n      \"tmp2\" *<- \"x\";;\n      \"tmp2\" <- \"m\" + 8;;\n      \"tmp2\" *<- \"tmp\";;\n\n      Return \"tmp\"\n    }\n  end\n}}.\n\nHint Extern 1 (@eq W _ _) =>\n  match goal with\n    | [ |- context[app] ] => fail 1\n    | _ => words\n  end.\n\nHint Extern 1 (interp ?specs (?U ?x ?y)) =>\n  match goal with\n    | [ H : interp ?specs (?f (?x, ?y)) |- _ ] =>\n      equate U (fun x y => f (x, y)); exact H\n  end.\n\nLemma goodMemo_elim : forall specs f pc P st,\n  interp specs (![ goodMemo f pc * P ] st)\n  -> exists pre, specs pc = Some pre\n    /\\ exists inv, interp specs (![ inv * P ] st)\n      /\\ forall st fr rpre,\n        interp specs ((Ex vs, Cptr st#Rp (fun x => rpre x)\n          /\\ ![ ^[locals (\"rp\" :: \"x\" :: nil) vs 0 st#Sp] * fr * inv ] st\n          /\\ Al st' : state,\n          ([| Regs st' Sp = st#Sp /\\ Regs st' Rv = app f (sel vs \"x\") |]\n            /\\ Ex vs', ![ ^[locals (\"rp\" :: \"x\" :: nil) vs' 0 st#Sp] * fr * inv ] (fst st, st'))\n          ---> rpre (fst st, st'))\n        ---> pre st)%PropX.\n  Local Opaque locals.\n  rewrite sepFormula_eq; repeat (propxFo; repeat (eauto; esplit)).\n  specialize (H4 (a, b) (fun a_b => fr (fst a_b) (snd a_b)) rpre).\n  Local Transparent locals lift.\n  repeat rewrite sepFormula_eq in *.\n  assumption.\n  Local Opaque locals lift.\nQed.\n\nLemma goodMemo_intro : forall specs pre inv f pc,\n  specs pc = Some pre\n  -> (forall (st : ST.settings * state) (fr : hpropB nil)\n    (rpre : settings * state -> propX W (settings * state) nil),\n    interp specs\n    ((Ex vs : vals,\n      Cptr (st) # (Rp) (fun x : settings * state => rpre x) /\\\n      ![^[locals (\"rp\" :: \"x\" :: nil) vs 0 (st) # (Sp)] * fr * inv] st /\\\n      (Al st' : state,\n        [| Regs st' Sp = (st) # (Sp) /\\\n          Regs st' Rv = app f (sel vs \"x\")|] /\\\n        (Ex vs' : vals,\n          ![^[locals (\"rp\" :: \"x\" :: nil) vs' 0 (st) # (Sp)] * fr * inv]\n          (fst st, st')) ---> rpre (fst st, st')))%PropX ---> pre st))\n  -> himp specs inv (goodMemo f pc).\n  intros.\n  unfold goodMemo, himp; propxFo.\n  imply_simp unf.\n  imply_simp unf.\n  imply_simp unf.\n  eauto.\n  imply_simp unf.\n  imply_simp unf.\n  instantiate (1 := fun p => inv (fst p) (snd p)); apply Imply_refl.\n  apply Imply_I; apply interp_weaken.\n  propxFo.\n  eapply Imply_trans; [ | apply H0 ].\n  rewrite sepFormula_eq.\n  instantiate (1 := a1).\n  instantiate (1 := fun a b => a0 (a, b)).\n  apply Imply_refl.\nQed.\n\nLemma switchUp : forall specs P Q R,\n  himp specs P R\n  -> himp specs (P * Q)%Sep (Q * R)%Sep.\n  intros; etransitivity; [ apply himp_star_comm | ]; apply himp_star_frame; auto; reflexivity.\nQed.\n\nHint Extern 1 (himp _ _ _) =>\n  apply switchUp; eapply goodMemo_intro; eassumption.\n\n(* Alternate VC post-processor that understands indirect function calls *)\nLtac post :=\n  PreAutoSep.post;\n  try ((* This appears to be an indirect function call.\n        * Put the appropriate marker predicate in [H], to trigger use of a lemma about the\n        * point-of-view shift from caller to callee. *)\n    icall (\"x\" :: nil);\n\n    (* Trigger symbolic execution early. *)\n    evaluate hints;\n\n    (* Move [goodMemo] to the front of its hypothesis and eliminate it. *)\n    match goal with\n      | [ H : interp _ _ |- _ ] =>\n        toFront ltac:(fun P => match P with goodMemo _ _ => idtac end) H;\n        apply goodMemo_elim in H; sep_firstorder\n    end;\n\n    (* Find and apply the hypothesis explaining the spec of the function pointer. *)\n    match goal with\n      | [ H : forall x : ST.settings * state, _ |- _ ] =>\n        eapply Imply_sound; [ apply H | ]\n    end).\n\n(* Main tactic *)\nLtac sep := post; PreAutoSep.sep hints; auto.\n\nTheorem memoizeMOk : moduleOk memoizeM.\n  vcgen; abstract sep.\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/examples/Memoize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "Require StlcIso.SpecSyntax.\nRequire StlcEqui.SpecSyntax.\nRequire Import StlcIso.SpecTyping.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcIso.Size.\nRequire Import StlcIso.SpecAnnot.\nRequire Import StlcIso.Fix.\nRequire Import StlcEqui.SpecEvaluation.\nRequire Import StlcIso.SpecEvaluation.\nRequire Import StlcIso.CanForm.\nRequire Import StlcEqui.LemmasEvaluation.\nRequire Import StlcEqui.TypeSafety.\nRequire Import StlcEqui.SpecTyping.\nRequire Import StlcIso.LemmasEvaluation.\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 LogRelIE.LemmasInversion.\nRequire Import Lia.\nRequire Import Db.Lemmas.\n\nRequire Import LogRelIE.LR.\n(* Require Import CompilerIE.ProtectConfine. *)\nRequire Import CompilerIE.Compiler.\n\nRequire Import BacktransIE.UValHelpers.\nRequire Import BacktransIE.UValHelpers2.\n\nRequire Import UValIE.UVal.\n\nLocal Ltac crush :=\n  cbn in * |-;\n  repeat\n    (repeat I.crushStlcSyntaxMatchH;\n     repeat E.crushStlcSyntaxMatchH;\n     repeat crushDbSyntaxMatchH;\n     repeat crushRepEmulEmbed;\n     repeat I.crushStlcEval;\n     repeat E.crushStlcEval;\n     I.crushTyping;\n     E.crushTyping;\n     crushOfType;\n     try split;\n     trivial;\n     subst*);\n  try discriminate; try lia;\n  eauto with eval;\n  repeat I.crushStlcSyntaxMatchH; (* remove apTm's again *)\n  repeat E.crushStlcSyntaxMatchH. (* remove apTm's again *)\n\nLemma Terminating_inl {t} : t \u21d3 -> (inl t) \u21d3.\nProof.\n  intros (v & vv & vreds).\n  exists (inl v).\n  split; eauto with eval.\n  now eapply (evalstar_ctx (pinl phole)).\nQed.\n\nFixpoint removeTRec (\u03c4 : Ty) : Ty :=\n  match \u03c4 with\n  | trec \u03c4' => \u03c4'\n  | _ => tunit\n  end.\n\nFixpoint ia_unfolds (n : nat) (\u03c4 : Ty) (t : TmA) : TmA :=\n  match n with\n  | 0 => t\n  | S n => ia_unfolds n (unfoldOnce \u03c4) (ia_unfold_ (removeTRec \u03c4) t)\n  end.\n\nLemma ia_unfolds_T {n \u03c4 t \u0393} :\n  n <= LMC \u03c4 -> ValidTy \u03c4 ->\n  \u27ea \u0393 ia\u22a2 t : \u03c4 \u27eb ->\n  \u27ea \u0393 ia\u22a2 ia_unfolds n \u03c4 t : unfoldn n \u03c4 \u27eb.\nProof.\n  revert t \u03c4.\n  induction n; intros t \u03c4 ineq v\u03c4 tyt; [easy|].\n  cbn.\n  destruct \u03c4; cbn in ineq;\n    try match goal with\n    | [ _ : S n <= 0 |- _ ] => exfalso; lia\n    end.\n  eapply IHn.\n  rewrite (LMC_unfoldOnce (trec \u03c4)); cbn; crushValidTy.\n  eauto with tyvalid.\n  constructor; crushValidTy; cbn.\nQed.\n\nFixpoint unfolds (n : nat) (t : Tm) : Tm :=\n  match n with\n  | 0 => t\n  | S n => unfolds n (unfold_ t)\n  end.\n\nLemma unfolds_T {n \u03c4 t \u0393} :\n  n <= LMC \u03c4 -> ValidTy \u03c4 ->\n  \u27ea \u0393 i\u22a2 t : \u03c4 \u27eb ->\n  \u27ea \u0393 i\u22a2 unfolds n t : unfoldn n \u03c4 \u27eb.\nProof.\n  revert t \u03c4.\n  induction n; intros t \u03c4 ineq v\u03c4 tyt; [easy|].\n  cbn.\n  destruct \u03c4; cbn in ineq;\n    try match goal with\n    | [ _ : S n <= 0 |- _ ] => exfalso; lia\n    end.\n  eapply IHn.\n  rewrite (LMC_unfoldOnce (trec \u03c4)); cbn; crushValidTy.\n  eauto with tyvalid.\n  constructor; crushValidTy; cbn.\nQed.\n\nLemma unfolds_sub {n \u03b3} : forall t, (unfolds n t) [ \u03b3 ] = unfolds n (t [ \u03b3 ]).\nProof.\n  induction n; intros; cbn; [easy|].\n  now rewrite IHn.\nQed.\n\nFixpoint unfolds_ctx (n : nat) : PCtx :=\n  match n with\n  | 0 => phole\n  | S n => pctx_cat (punfold phole) (unfolds_ctx n)\n  end.\n\nLemma unfolds_unfolds_ctx {n} : forall t, unfolds n t = pctx_app t (unfolds_ctx n).\nProof.\n  induction n; [easy|].\n  intros t; simpl.\n  now rewrite IHn, pctx_cat_app.\nQed.\n\nLemma unfolds_ectx {n} : ECtx (unfolds_ctx n).\nProof.\n  induction n; cbn; [easy|].\n  now eapply ectx_cat.\nQed.\n\nLemma unfolds_terminate {\u03c4} : forall vs,\n  ValidTy \u03c4 ->\n  \u27ea empty i\u22a2 vs : \u03c4 \u27eb ->\n  Value vs ->\n  (unfolds (LMC \u03c4) vs) \u21d3.\nProof.\n  remember (LMC \u03c4) as n.\n  revert \u03c4 Heqn.\n  induction n; intros.\n  destruct \u03c4; cbn; intros;\n   now eapply values_terminate.\n  destruct \u03c4; inversion Heqn.\n  stlcCanForm1.\n  destruct_conjs; subst.\n  cbn in *.\n  eapply I.termination_closed_under_antireduction.\n  eapply eval_from_eval\u2080.\n  eapply (eval_fold_unfold _ H1).\n  rewrite unfolds_unfolds_ctx; reflexivity.\n  reflexivity.\n  now eapply unfolds_ectx.\n  rewrite <- unfolds_unfolds_ctx.\n  eapply (IHn (unfoldOnce (trec \u03c4)));\n  crushValidTy.\n  rewrite LMC_unfoldOnce; crushValidTy.\n  cbn; lia.\nQed.\n\nLemma ia_unfolds_eraseAnnot {n \u03c4 t} :\n  eraseAnnot (ia_unfolds n \u03c4 t) = unfolds n (eraseAnnot t).\nProof.\n  revert \u03c4 t.\n  induction n; [easy|].\n  intros \u03c4 t.\n  cbn. now rewrite IHn.\nQed.\n\nFixpoint ia_folds (n : nat) (\u03c4 : Ty) (t : TmA) : TmA :=\n  match n with\n  | 0 => t\n  | S n => ia_fold_ (removeTRec \u03c4) (ia_folds n (unfoldOnce \u03c4) t)\n  end.\n\nLemma ia_folds_T {n \u03c4 t \u0393} :\n  n <= LMC \u03c4 -> ValidTy \u03c4 ->\n  \u27ea \u0393 ia\u22a2 t : unfoldn n \u03c4 \u27eb ->\n  \u27ea \u0393 ia\u22a2 ia_folds n \u03c4 t : \u03c4 \u27eb.\nProof.\n  revert t \u03c4.\n  induction n; intros t \u03c4 ineq v\u03c4 tyt; [easy|].\n  cbn.\n  destruct \u03c4; cbn in ineq;\n    try match goal with\n    | [ _ : S n <= 0 |- _ ] => exfalso; lia\n    end.\n  I.crushTypingIA.\n  eapply IHn; try easy.\n  change (LMC _) with (LMC (unfoldOnce (trec \u03c4))).\n  rewrite (LMC_unfoldOnce (trec \u03c4)); cbn; crushValidTy.\n  crushValidTy.\nQed.\n\nFixpoint folds (n : nat) (t : Tm) : Tm :=\n  match n with\n  | 0 => t\n  | S n => fold_ (folds n t)\n  end.\n\nLemma folds_T {n \u03c4 t \u0393} :\n  n <= LMC \u03c4 -> ValidTy \u03c4 ->\n  \u27ea \u0393 i\u22a2 t : unfoldn n \u03c4 \u27eb ->\n  \u27ea \u0393 i\u22a2 folds n t : \u03c4 \u27eb.\nProof.\n  revert t \u03c4.\n  induction n; intros t \u03c4 ineq v\u03c4 tyt; [easy|].\n  cbn.\n  destruct \u03c4; cbn in ineq;\n    try match goal with\n    | [ _ : S n <= 0 |- _ ] => exfalso; lia\n    end.\n  constructor; try assumption.\n  eapply IHn.\n  change (n <= LMC (unfoldOnce (trec \u03c4))).\n  rewrite (LMC_unfoldOnce (trec \u03c4)); cbn; crushValidTy.\n  crushValidTy.\n  exact tyt.\nQed.\n\nLemma ia_folds_eraseAnnot {n \u03c4 t} :\n  eraseAnnot (ia_folds n \u03c4 t) = folds n (eraseAnnot t).\nProof.\n  revert \u03c4 t.\n  induction n; [easy|].\n  intros \u03c4 t.\n  cbn. now rewrite IHn.\nQed.\n\nLemma folds_Value {n vs} :\n  Value (folds n vs) <-> Value vs.\nProof.\n  induction n; intuition.\nQed.\n\nLemma folds_sub {n \u03b3} : forall t, (folds n t) [ \u03b3 ] = folds n (t [ \u03b3 ]).\nProof.\n  induction n; intros; simpl; [easy|].\n  now rewrite <-IHn.\nQed.\n\nFixpoint folds_ctx (n : nat) : PCtx :=\n  match n with\n  | 0 => phole\n  | S n => pctx_cat (folds_ctx n) (pfold phole)\n  end.\n\nLemma folds_folds_ctx {n} : forall t, folds n t = pctx_app t (folds_ctx n).\nProof.\n  induction n; [easy|].\n  intros t; simpl.\n  now rewrite <-IHn.\nQed.\n\nLemma folds_ectx {n} : ECtx (folds_ctx n).\nProof.\n  induction n; now cbn.\nQed.\n\nLemma unfolds_folds_evalStar {n vs} :\n  Value vs ->\n  unfolds n (folds n vs) -->* vs.\nProof.\n  revert vs.\n  induction n; [eauto with eval|].\n  intros vs vvs.\n  cbn.\n  eapply evalStepStar.\n  rewrite unfolds_unfolds_ctx.\n  eapply eval_ctx\u2080.\n  now eapply eval_fold_unfold, folds_Value.\n  now eapply unfolds_ectx.\n  rewrite <-unfolds_unfolds_ctx.\n  now eapply IHn.\nQed.\n\nFixpoint injectA (n : nat) (\u03c4 : I.Ty) {struct n} : I.TmA :=\n       I.ia_abs \u03c4 (UValIE n \u03c4)\n         (* TODO: argument of type \u03c4 needs to be unfolded (LMC \u03c4) times before use! *)\n             (match n with\n              | O => I.ia_unit\n              | S n => (match (unfoldn (LMC \u03c4) \u03c4) with\n                       | I.tarr \u03c4\u2081 \u03c4\u2082 => I.ia_inl (I.tarr (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)) I.tunit\n                                          (I.ia_abs (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)\n                                              (I.ia_app \u03c4\u2082 (UValIE n \u03c4\u2082)\n                                                       (injectA n \u03c4\u2082)\n                                                       (I.ia_app \u03c4\u2081 \u03c4\u2082 (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 1))\n                                                                (I.ia_app (UValIE n \u03c4\u2081) \u03c4\u2081\n                                                                         (extractA n \u03c4\u2081)\n                                                                         (I.ia_var 0)))))\n                       | I.tunit => I.ia_inl I.tunit I.tunit (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 0))\n                       | I.tbool => I.ia_inl I.tbool I.tunit (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 0))\n                       | I.tprod \u03c4\u2081 \u03c4\u2082 => I.ia_inl (I.tprod (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)) I.tunit\n                                                 (I.ia_pair (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)\n                                                           (I.ia_app \u03c4\u2081 (UValIE n \u03c4\u2081) (injectA n \u03c4\u2081)\n                                                                    (I.ia_proj\u2081 \u03c4\u2081 \u03c4\u2082 (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 0))))\n                                                           (I.ia_app \u03c4\u2082 (UValIE n \u03c4\u2082) (injectA n \u03c4\u2082)\n                                                                    (I.ia_proj\u2082 \u03c4\u2081 \u03c4\u2082 (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 0)))))\n                       | I.tsum \u03c4\u2081 \u03c4\u2082 => I.ia_inl (I.tsum (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)) I.tunit (I.ia_caseof \u03c4\u2081 \u03c4\u2082 (I.tsum (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)) (ia_unfolds (LMC \u03c4) \u03c4 (I.ia_var 0))\n                                                 (I.ia_inl (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)\n                                                          (I.ia_app \u03c4\u2081 (UValIE n \u03c4\u2081) (injectA n \u03c4\u2081)\n                                                                 (I.ia_var 0)))\n                                                 (I.ia_inr (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)\n                                                          (I.ia_app \u03c4\u2082 (UValIE n \u03c4\u2082) (injectA n \u03c4\u2082)\n                                                               (I.ia_var 0))))\n                       | I.trec _ => I.ia_unit\n                       | I.tvar _ => I.ia_unit\n                       end)\n                end)\n  with extractA (n : nat) (\u03c4 : I.Ty) {struct n} : I.TmA :=\n         let case\u03c4 : I.Tm \u2192 I.Tm := caseUVal (UValIE n \u03c4) in\n         I.ia_abs (UValIE n \u03c4) \u03c4\n               (match n with\n                   | O => OmA \u03c4\n                   | S n => match (unfoldn (LMC \u03c4) \u03c4) with\n                           | I.tarr \u03c4\u2081 \u03c4\u2082 => ia_folds (LMC \u03c4) \u03c4 (I.ia_abs \u03c4\u2081 \u03c4\u2082 (I.ia_app (UValIE n \u03c4\u2082) \u03c4\u2082\n                                                                (extractA n \u03c4\u2082)\n                                                                (I.ia_app (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082)\n                                                                         (caseArrA n (I.ia_var 1)\n                                                                                   \u03c4\u2081\n                                                                                   \u03c4\u2082)\n                                                                         (I.ia_app \u03c4\u2081 (UValIE n \u03c4\u2081) (injectA n \u03c4\u2081)\n                                                                                  (I.ia_var 0)))))\n                           | I.tunit => ia_folds (LMC \u03c4) \u03c4 (caseUnitA n (I.ia_var 0))\n                           | I.tbool => ia_folds (LMC \u03c4) \u03c4 (caseBoolA n (I.ia_var 0))\n                           | I.tprod \u03c4\u2081 \u03c4\u2082 => ia_folds (LMC \u03c4) \u03c4 (I.ia_pair \u03c4\u2081 \u03c4\u2082\n                                                      (I.ia_app (UValIE n \u03c4\u2081) \u03c4\u2081 (extractA n \u03c4\u2081)\n                                                               (I.ia_proj\u2081 (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082) (caseProdA n (I.ia_var 0) \u03c4\u2081 \u03c4\u2082)))\n                                                      (I.ia_app (UValIE n \u03c4\u2082) \u03c4\u2082 (extractA n \u03c4\u2082)\n                                                               (I.ia_proj\u2082 (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082) (caseProdA n (I.ia_var 0) \u03c4\u2081 \u03c4\u2082))))\n                           | I.tsum \u03c4\u2081 \u03c4\u2082 => ia_folds (LMC \u03c4) \u03c4 (I.ia_caseof (UValIE n \u03c4\u2081) (UValIE n \u03c4\u2082) (I.tsum \u03c4\u2081 \u03c4\u2082)\n                                                       (caseSumA n (I.ia_var 0) \u03c4\u2081 \u03c4\u2082)\n                                                       (I.ia_inl \u03c4\u2081 \u03c4\u2082 (I.ia_app (UValIE n \u03c4\u2081) \u03c4\u2081 (extractA n \u03c4\u2081) (I.ia_var 0)))\n                                                       (I.ia_inr \u03c4\u2081 \u03c4\u2082 (I.ia_app (UValIE n \u03c4\u2082) \u03c4\u2082 (extractA n \u03c4\u2082) (I.ia_var 0))))\n                           | I.trec _ => I.ia_unit\n                           | I.tvar _ => I.ia_unit\n                           end\n               end).\nDefinition inject n \u03c4 := eraseAnnot (injectA n \u03c4).\nDefinition extract n \u03c4 := eraseAnnot (extractA n \u03c4).\n\nArguments injectA !n \u03c4.\nArguments extractA !n \u03c4.\nArguments inject !n \u03c4.\nArguments extract !n \u03c4.\n\nLemma inject_value {n \u03c4} : I.Value (inject n \u03c4).\nProof.\n  (* exact E. *)\n  (* Should be doable without the induction, but I don't see how *)\n  destruct n; destruct \u03c4; simpl; eauto with eval.\nQed.\n\nArguments UValIE !n \u03c4.\nLemma injectAT {n \u03c4 \u0393} : ValidTy \u03c4 -> \u27ea \u0393 ia\u22a2 injectA n \u03c4 : I.tarr \u03c4 (UValIE n \u03c4) \u27eb\nwith extractAT {n \u03c4 \u0393} : ValidTy \u03c4 -> \u27ea \u0393 ia\u22a2 extractA n \u03c4 : I.tarr (UValIE n \u03c4) \u03c4 \u27eb.\nProof.\n  - intros v\u03c4. destruct n.\n    + simpl.\n      eauto with typing uval_typing.\n    + simpl [UValIE UValIE'].\n      assert (vu\u03c4 : ValidTy (unfoldn (LMC \u03c4) \u03c4)) by eauto using ValidTy_unfoldn.\n      assert (lu\u03c4z : LMC (unfoldn (LMC \u03c4) \u03c4) = 0) by (eapply unfoldn_LMC; crushValidTy).\n      remember (unfoldn (LMC \u03c4) \u03c4) as \u03c4'.\n      destruct \u03c4'; try inversion lu\u03c4z; I.crushTypingIA; crushValidTy_with_UVal;\n      rewrite Heq\u03c4';\n      eapply ia_unfolds_T; I.crushTypingIA.\n  - intros v\u03c4. destruct n.\n    + simpl.\n      eauto with typing uval_typing tyvalid.\n    + simpl [UValIE UValIE'].\n      assert (vu\u03c4 : ValidTy (unfoldn (LMC \u03c4) \u03c4)) by eauto using ValidTy_unfoldn.\n      assert (lu\u03c4z : LMC (unfoldn (LMC \u03c4) \u03c4) = 0) by (eapply unfoldn_LMC; crushValidTy).\n      remember (unfoldn (LMC \u03c4) \u03c4) as \u03c4'.\n      destruct \u03c4'; try inversion lu\u03c4z; I.crushTypingIA; crushValidTy_with_UVal;\n      eapply ia_folds_T; I.crushTypingIA;\n      rewrite <-Heq\u03c4'; I.crushTypingIA;\n      eauto using wtOmA_tau with typing uval_typing; crushValidTy_with_UVal;\n      eapply wtOmA_tau; crushValidTy_with_UVal.\nQed.\n\nLemma injectT {n \u03c4 \u0393} : ValidTy \u03c4 -> \u27ea \u0393 i\u22a2 inject n \u03c4 : I.tarr \u03c4 (UValIE n \u03c4) \u27eb.\nProof.\n  eauto using eraseAnnotT, injectAT.\nQed.\nLemma extractT {n \u03c4 \u0393} : ValidTy \u03c4 -> \u27ea \u0393 i\u22a2 extract n \u03c4 : I.tarr (UValIE n \u03c4) \u03c4 \u27eb.\nProof.\n  eauto using eraseAnnotT, extractAT.\nQed.\n\n#[export]\nHint Resolve injectT : uval_typing.\n#[export]\nHint Resolve extractT : uval_typing.\n#[export]\nHint Resolve injectAT : uval_typing.\n#[export]\nHint Resolve extractAT : uval_typing.\n\nLemma inject_closed {n \u03c4} :\n  ValidTy \u03c4 ->\n  \u27e8 0 \u22a2 inject n \u03c4 \u27e9.\nProof.\n  intros v\u03c4.\n  eapply (wt_implies_ws (\u0393 := I.empty)).\n  now eapply injectT.\nQed.\n\nLemma extract_value {n \u03c4} : I.Value (extract n \u03c4).\nProof.\n  (* exact E. *)\n  (* Should be doable without the induction, but I don't see how *)\n  destruct n; destruct \u03c4; simpl; eauto with eval.\nQed.\n\nLemma extract_closed {n \u03c4} :\n  ValidTy \u03c4 ->\n  \u27e8 0 \u22a2 extract n \u03c4 \u27e9.\nProof.\n  intros v\u03c4.\n  eapply (wt_implies_ws (\u0393 := I.empty)).\n  now eapply extractT.\nQed.\n\nLemma inject_sub {n \u03c4 \u03b3} : ValidTy \u03c4 -> (inject n \u03c4)[\u03b3] = inject n \u03c4.\nProof.\n  intros v\u03c4.\n  apply wsClosed_invariant.\n  now eapply inject_closed.\nQed.\n\nLemma extract_sub {n \u03c4 \u03b3} : ValidTy \u03c4 -> (extract n \u03c4)[\u03b3] = extract n \u03c4.\nProof.\n  intros v\u03c4.\n  apply wsClosed_invariant.\n  now eapply extract_closed.\nQed.\n\nFixpoint inject_terminates n {\u03c4 vs}:\n  ValidTy \u03c4 ->\n  OfTypeStlcIso (embed \u03c4) vs ->\n  Terminating (I.app (inject n \u03c4) vs).\nProof.\n  intros v\u03c4 [vvs vty].\n  assert (vu\u03c4 : ValidTy (unfoldn (LMC \u03c4) \u03c4)) by eauto using ValidTy_unfoldn.\n  assert (lu\u03c4z : LMC (unfoldn (LMC \u03c4) \u03c4) = 0) by (eapply unfoldn_LMC; crushValidTy).\n  destruct n.\n  - eapply I.termination_closed_under_antireduction.\n    now eapply eval_eval\u2080, eval_beta.\n    now eapply values_terminate.\n  - unfold inject.\n    cbn [injectA eraseAnnot].\n    remember (unfoldn (LMC \u03c4) \u03c4) as \u03c4'.\n    rewrite repEmul_embed_leftinv in vty.\n    destruct \u03c4';\n     (eapply I.termination_closed_under_antireduction;\n      [now eapply eval_eval\u2080, eval_beta|]);\n      simpl;\n      I.crushTyping;\n      rewrite ?ia_unfolds_eraseAnnot;\n      rewrite ?unfolds_sub;\n      simpl.\n    + eapply values_terminate.\n      now cbn.\n    + crushTyping.\n      eapply Terminating_inl.\n      now eapply unfolds_terminate.\n    + assert ((unfolds (LMC \u03c4) vs) \u21d3) as (v & vv & vreds).\n      { eapply unfolds_terminate; crush; I.crushTyping. }\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' vreds); inferContext.\n        cbn; eauto using inject_value.\n      }\n      cbn.\n      eapply values_terminate; now cbn.\n    + change (app _) with (app (inject n \u03c4'1)[beta1 vs]) at 1.\n      change (app _) with (app (inject n \u03c4'2)[beta1 vs]) at 2.\n      rewrite ?inject_sub; crushValidTy.\n      rewrite ?unfolds_sub; cbn.\n      assert ((unfolds (LMC \u03c4) vs) \u21d3) as (v & vv & vreds).\n      { eapply unfolds_terminate; crush; I.crushTyping. }\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' vreds); inferContext.\n        cbn; eauto using inject_value.\n      }\n      cbn.\n      assert \u27ea empty i\u22a2 v : \u03c4'1 r\u00d7 \u03c4'2 \u27eb.\n      { eapply (I.preservation_star vreds); I.crushTyping.\n        rewrite Heq\u03c4'.\n        eapply unfolds_T; crush.\n      }\n      I.stlcCanForm1.\n      destruct vv as (vx & vx0).\n      eapply I.termination_closed_under_antireduction.\n      { eapply (eval_from_eval\u2080 (eval_proj\u2081 vx vx0)); I.inferContext; cbn; eauto using inject_value with eval. }\n      cbn.\n      assert (OfTypeStlcIso (embed \u03c4'1) x) as otx.\n      { split; crush. }\n      destruct (inject_terminates n \u03c4'1 x H otx) as (vs' & vvs' & es).\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' es); I.inferContext; now cbn. }\n      cbn.\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' vreds); inferContext.\n        cbn; eauto using inject_value.\n      }\n      cbn.\n      eapply I.termination_closed_under_antireduction.\n      { eapply (eval_from_eval\u2080 (eval_proj\u2082 vx vx0)); I.inferContext; cbn; eauto using inject_value with eval. }\n      cbn.\n      assert (OfTypeStlcIso (embed \u03c4'2) x0) as otx0.\n      { split; crush. }\n      destruct (inject_terminates n \u03c4'2 x0 H0 otx0) as (vs2' & vvs2' & es2).\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' es2); I.inferContext; now cbn. }\n      cbn.\n      eapply values_terminate; now cbn.\n    + change (app _) with (app (inject n \u03c4'1) [(beta1 vs)\u2191]) at 1.\n      change (app _) with (app (inject n \u03c4'2) [(beta1 vs)\u2191]) at 2.\n      rewrite ?inject_sub; crushValidTy.\n      assert ((unfolds (LMC \u03c4) vs) \u21d3) as (v & vv & vreds).\n      { eapply unfolds_terminate; crush; I.crushTyping. }\n      eapply I.termination_closed_under_antireductionStar.\n      { eapply (evalstar_ctx' vreds); I.inferContext; now cbn. }\n      cbn.\n      assert \u27ea empty i\u22a2 v : \u03c4'1 r\u228e \u03c4'2 \u27eb.\n      { eapply (I.preservation_star vreds); I.crushTyping.\n        rewrite Heq\u03c4'.\n        eapply unfolds_T; crush.\n      }\n      I.stlcCanForm1.\n      * eapply I.termination_closed_under_antireduction.\n        { eapply (eval_from_eval\u2080 (eval_case_inl vv)); I.inferContext; now cbn. }\n        crushTyping.\n        rewrite inject_sub; crushValidTy.\n        assert (OfTypeStlcIso (embed \u03c4'1) x) as otx.\n        { split; crush. }\n        destruct (inject_terminates n \u03c4'1 x H otx) as (v' & vv' & es).\n        eapply I.termination_closed_under_antireductionStar.\n        { eapply (evalstar_ctx' es); I.inferContext; now cbn. }\n        cbn.\n        eapply values_terminate; now cbn.\n      * eapply I.termination_closed_under_antireduction.\n        { eapply (eval_from_eval\u2080 (eval_case_inr vv)); I.inferContext; now cbn. }\n        crushTyping.\n        rewrite inject_sub; crushValidTy.\n        assert (OfTypeStlcIso (embed \u03c4'2) x) as otx.\n        { split; crush. }\n        destruct (inject_terminates n \u03c4'2 x H0 otx) as (v' & vv' & es).\n        eapply I.termination_closed_under_antireductionStar.\n        { eapply (evalstar_ctx' es); I.inferContext; now cbn. }\n        cbn.\n        eapply values_terminate; now cbn.\n    + eapply values_terminate; now cbn.\n    + eapply values_terminate; now cbn.\nQed.\n\nDefinition inject_works_prop (n : nat) (w : World) (d : Direction) (p : Prec) (vs : I.Tm) (vu : E.Tm) (\u03c4 : I.Ty) : Prop :=\n  dir_world_prec n w d p \u2192\n  valrel d w (embed \u03c4) vs vu \u2192\n  termrelnd\u2080 d w (pEmulDV n p \u03c4) (I.app (inject n \u03c4) vs) vu.\n  (* ECtx Cs \u2192 E.ECtx Cu \u2192 *)\n  (* contrel d w (embed \u03c4) Cs Cu \u2192 *)\n  (* (exists vs', I.pctx_app (I.app (inject n \u03c4) vs) Cs -->* I.pctx_app vs' Cs *)\n  (*        \u2227 valrel d w (pEmulDV n p \u03c4) vs' vu) *)\n  (* \u2228 Obs d w (I.pctx_app (I.app (inject n \u03c4) vs) Cs) (E.pctx_app vu Cu). *)\n\nDefinition extract_works_prop (n : nat) (w : World) (d : Direction) (p : Prec) (vs : I.Tm) (vu : E.Tm) (\u03c4 : I.Ty) : Prop :=\n  dir_world_prec n w d p \u2192\n  (d = dir_gt -> E.size vu <= w) ->\n  valrel d w (pEmulDV n p \u03c4) vs vu \u2192\n  termrelnd\u2080 d w (embed \u03c4) (I.app (extract n \u03c4) vs) vu.\n  (* ECtx Cs \u2192 E.ECtx Cu \u2192 *)\n  (* contrel d w (embed \u03c4) Cs Cu \u2192 *)\n  (* (exists vs', I.pctx_app (I.app (extract n \u03c4) vs) Cs -->* I.pctx_app vs' Cs *)\n  (*        \u2227 valrel d w (embed \u03c4) vs' vu) *)\n  (* \u2228 Obs d w (I.pctx_app (I.app (extract n \u03c4) vs) Cs) (E.pctx_app vu Cu). *)\n\nLemma inject_zero_works {w d p vs vu \u03c4} :\n  inject_works_prop 0 w d p vs vu \u03c4.\nProof.\n  intros dwp vr.\n  destruct (dwp_zero dwp); subst.\n  destruct (valrel_implies_OfType vr) as [[vvs ovs] [vvu ovu]].\n  eapply termrelnd\u2080_antired.\n  - eapply evalToStar, eval\u2080_to_eval, eval_beta.\n    assumption.\n  - eapply rt1n_refl.\n  - eapply valrel_termrelnd\u2080.\n    crush.\n    now rewrite isToEq_embed_leftinv in ovu.\nQed.\n\nLemma extract_zero_works {w d p vs vu \u03c4} :\n  extract_works_prop 0 w d p vs vu \u03c4.\nProof.\n  intros dwp _ vr.\n  destruct (dwp_zero dwp); subst.\n  intros vs0 vvs0 es.\n  exfalso.\n  cbn in es.\n  eapply Om_div.\n  exists vs0; split; [assumption|].\n  refine (I.determinacyStar1 _ es _).\n  - eapply eval_eval\u2080.\n    destruct (valrel_implies_Value vr).\n    eenough (Om _ = ?[t']) as ->.\n    eapply eval_beta; crush.\n    now cbn.\n  - eauto using values_are_normal.\nQed.\n\nLemma has_n_folds_eq {n ts1 ts2}:\n  has_n_folds n ts1 ts2 <->\n  ts1 = folds n ts2.\nProof.\n  revert ts1 ts2.\n  induction n; cbn; [easy|].\n  split.\n  - intros (ts1' & -> & eq).\n    specialize (proj1 (IHn _ _) eq).\n    intros; now f_equal.\n  - intros ->.\n    exists (folds n ts2).\n    split; [reflexivity|].\n    now eapply (proj2 (IHn _ _)).\nQed.\n\nLemma invert_folds_Value {n vs} :\n  Value (folds n vs) -> Value vs.\nProof.\n  induction n; eauto.\nQed.\n\nLemma LMC_pty_embed {\u03c4} :\n  LMC_pty (embed \u03c4) = LMC \u03c4.\nProof.\n  induction \u03c4; crush.\nQed.\n\nLemma pUnfoldOnce_embed {\u03c4} :\n  pUnfoldOnce (embed \u03c4) = embed (unfoldOnce \u03c4).\nProof.\n  destruct \u03c4; cbn; intuition.\n  rewrite embed_sub.\n  f_equal.\n  extensionality i.\n  destruct i; now cbn.\nQed.\n\nLemma pUnfoldn_embed {n \u03c4} :\n  pUnfoldn n (embed \u03c4) = embed (unfoldn n \u03c4).\nProof.\n  revert \u03c4.\n  induction n; cbn; intuition.\n  rewrite pUnfoldOnce_embed.\n  now rewrite IHn.\nQed.\n\nLemma folds_T_inversion {n \u03c4 t \u0393} :\n  \u27ea \u0393 i\u22a2 folds n t : \u03c4 \u27eb ->\n  \u27ea \u0393 i\u22a2 t : unfoldn n \u03c4 \u27eb.\nProof.\n  revert \u03c4 t \u0393.\n  induction n; cbn; [easy|].\n  intros \u03c4 t \u0393 ty\u03c4.\n  inversion ty\u03c4; subst.\n  eapply IHn in H0; crushValidTy.\nQed.\n\nLemma unfolds_works {d w \u03c4 vs vu}:\n  ValidTy \u03c4 ->\n  valrel d w (embed \u03c4) vs vu ->\n  exists vs',\n    Value vs' /\\\n    unfolds (LMC \u03c4) vs -->* vs' /\\\n    valrel d w (embed (unfoldn (LMC \u03c4) \u03c4)) vs' vu.\nProof.\n  intros v\u03c4 vr.\n  rewrite valrel_fixp in vr.\n  unfold valrel' in vr.\n  destruct vr as (ot & vs' & hnf & vvs & vr).\n  rewrite has_n_folds_eq in hnf.\n  rewrite hnf in *.\n  exists vs'.\n  split.\n  - eauto using invert_folds_Value.\n  - rewrite LMC_pty_embed in *.\n    split.\n    + eapply unfolds_folds_evalStar.\n      now rewrite folds_Value in vvs.\n    + rewrite pUnfoldn_embed in vr.\n      rewrite valrel_fixp.\n      destruct ot as ((? & ?) & (? & ?)).\n      split.\n      split; split; crushOfType;\n      eauto using folds_Value.\n      now rewrite folds_Value in vvs.\n      rewrite repEmul_embed_leftinv in *.\n      eapply folds_T_inversion; crush.\n      rewrite isToEq_embed_leftinv in *.\n      eapply WtEq.\n      eapply tyeq_symm.\n      eapply E.ty_eq_unfoldn; crush.\n      now destruct v\u03c4 as (? & ?).\n      crushValidTy.\n      eapply E.ValidTy_unfoldn; crushValidTy.\n      crush.\n      exists vs'.\n      rewrite ?LMC_pty_embed.\n      rewrite ?unfoldn_LMC; cbn.\n      crush.\n      now rewrite folds_Value in vvs.\n      now destruct v\u03c4 as (? & ?).\nQed.\n\nLemma folds_works {d w \u03c4 vs vu}:\n  ValidTy \u03c4 ->\n  valrel d w (embed (unfoldn (LMC \u03c4) \u03c4)) vs vu ->\n  valrel d w (embed \u03c4) (folds (LMC \u03c4) vs) vu.\nProof.\n  intros v\u03c4.\n  rewrite ?valrel_fixp.\n  unfold valrel'.\n  rewrite ?LMC_pty_embed.\n  rewrite ?pUnfoldn_embed.\n  rewrite unfoldn_LMC.\n  intros (ot & ts2 & hnf & vvs' & vr).\n  cbn in vr.\n  split.\n  - destruct ot as ((? & ?) & ? & ?).\n    split; split; crush.\n    now eapply folds_Value.\n    eapply folds_T; crush.\n    now rewrite repEmul_embed_leftinv in *.\n    rewrite isToEq_embed_leftinv in *.\n    refine (WtEq _ _ _ _ H2).\n    eapply ty_eq_unfoldn; crushValidTy.\n    eapply ValidTy_unfoldn; crushValidTy.\n    crushValidTy.\n  - exists vs.\n    rewrite has_n_folds_eq.\n    split; [reflexivity|].\n    split; [now eapply folds_Value|].\n    destruct hnf.\n    exact vr.\n  - crushValidTy.\nQed.\n\nLemma inject_unit_works {n w d p vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tunit ->\n  inject_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq dwp vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  eapply unfolds_works in vr; crushValidTy.\n  destruct vr as (vs' & vvs' & vpreds & vr).\n  eapply termrelnd\u2080_antired.\n  - eapply evalStepStar.\n    refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n    rewrite eq, ia_unfolds_eraseAnnot.\n    cbn.\n    I.crushStlcSyntaxMatchH.\n    rewrite unfolds_sub.\n    now eapply (evalstar_ctx' vpreds); I.inferContext.\n  - eapply rt1n_refl.\n  - cbn.\n    eapply valrel_termrelnd\u2080.\n    eapply valrel_pEmulDV_unfoldn; crushValidTy.\n    rewrite eq in *.\n    eapply valrel_ptunit_inversion in vr.\n    apply valrel_inUnit; intuition.\nQed.\n\nLemma extract_unit_works {n w d p vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tunit ->\n  extract_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq dwp sz vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  cbn -[UValIE] in tyvs, tyvu.\n\n  eapply valrel_pEmulDV_unfoldn in vr; crushValidTy.\n  rewrite eq in vr.\n\n  destruct (invert_valrel_pEmulDV_unit vr) as [(? & ?) | (vs' & ? & ?)];\n    unfold unkUVal in H;\n    subst.\n\n  - apply dwp_invert_imprecise in dwp; subst.\n    intros vs vvs' es.\n    exfalso.\n    refine (divergence_closed_under_evalstar _ _ (ex_intro _ vs (conj vvs' es))).\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n\n      eapply evalStepStar.\n      rewrite folds_folds_ctx.\n      eapply (eval_from_eval\u2080 (eval_case_inr (t := I.unit) I)); I.inferContext; eauto using folds_ectx.\n      eapply rt1n_refl.\n    + eapply divergence_closed_under_evalcontext; eauto using folds_ectx.\n      exact (Om_div (\u03c4 := tunit)).\n  - eapply termrelnd\u2080_antired.\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n      unfold caseUnitA, caseUnit_pctxA, caseUVal_pctxA.\n      eapply evalStepStar.\n      * rewrite folds_folds_ctx.\n        cbn in vvs.\n        eapply (eval_from_eval\u2080 (eval_case_inl vvs)); I.inferContext;\n         eauto using folds_ectx.\n      * eapply rt1n_refl.\n    + eapply rt1n_refl.\n    + eapply valrel_termrelnd\u2080.\n      cbn.\n      rewrite <-folds_folds_ctx.\n      eapply folds_works; crushValidTy.\n      now rewrite eq.\nQed.\n\nLemma inject_bool_works {n w d p vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tbool ->\n  inject_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq dwp vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  eapply unfolds_works in vr; crushValidTy.\n  destruct vr as (vs' & vvs' & vpreds & vr).\n  eapply termrelnd\u2080_antired.\n  - eapply evalStepStar.\n    refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n    rewrite eq, ia_unfolds_eraseAnnot.\n    cbn.\n    I.crushStlcSyntaxMatchH.\n    rewrite unfolds_sub.\n    now eapply (evalstar_ctx' vpreds); I.inferContext.\n  - eapply rt1n_refl.\n  - cbn.\n    eapply valrel_termrelnd\u2080.\n    eapply valrel_pEmulDV_unfoldn; crushValidTy.\n    rewrite eq in *.\n    eapply valrel_ptbool_inversion in vr.\n    apply valrel_inBool; intuition.\nQed.\n\nLemma extract_bool_works {n w d p vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tbool ->\n  extract_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq dwp sz vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  cbn -[UValIE] in tyvs, tyvu.\n\n  eapply valrel_pEmulDV_unfoldn in vr; crushValidTy.\n  rewrite eq in vr.\n\n  destruct (invert_valrel_pEmulDV_bool vr) as [(? & ?) | (vs' & ? & ?)];\n    unfold unkUVal in H;\n    subst.\n\n  - apply dwp_invert_imprecise in dwp; subst.\n    intros vs vvs' es.\n    exfalso.\n    refine (divergence_closed_under_evalstar _ _ (ex_intro _ vs (conj vvs' es))).\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n\n      eapply evalStepStar.\n      rewrite folds_folds_ctx.\n      eapply (eval_from_eval\u2080 (eval_case_inr (t := I.unit) I)); I.inferContext; eauto using folds_ectx.\n      eapply rt1n_refl.\n    + eapply divergence_closed_under_evalcontext; eauto using folds_ectx.\n      exact (Om_div (\u03c4 := tbool)).\n  - eapply termrelnd\u2080_antired.\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n      unfold caseUnitA, caseUnit_pctxA, caseUVal_pctxA.\n      eapply evalStepStar.\n      * rewrite folds_folds_ctx.\n        cbn in vvs.\n        eapply (eval_from_eval\u2080 (eval_case_inl vvs)); I.inferContext;\n         eauto using folds_ectx.\n      * eapply rt1n_refl.\n    + eapply rt1n_refl.\n    + eapply valrel_termrelnd\u2080.\n      cbn.\n      rewrite <-folds_folds_ctx.\n      eapply folds_works; crushValidTy.\n      now rewrite eq.\nQed.\n\nLemma fizzbuzz {n p \u03c4} : isToEq (pEmulDV n p \u03c4) = isToEq (embed \u03c4).\nProof.\n  now rewrite isToEq_embed_leftinv.\nQed.\n\nLemma value_sub t (v: I.Value t) :\n  \u2200 (\u03b6: Sub I.Tm), Value t[\u03b6].\nProof.\n  induction t; crush; cbn; apply IHt;\n  assumption.\nQed.\n(* #[export] *)\n(* Hint Resolve value_sub. *)\n\nLemma inject_tarr_works {n w d p vs vu \u03c41 \u03c42 \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tarr \u03c41 \u03c42 ->\n  ValidTy \u03c41 -> ValidTy \u03c42 ->\n  (forall w' vs1 vu1, inject_works_prop n w' d p vs1 vu1 \u03c42) \u2192\n  (forall w' vs1 vu1, extract_works_prop n w' d p vs1 vu1 \u03c41) \u2192\n  inject_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c41 v\u03c42 IHinj IHext dwp vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  destruct (unfolds_works v\u03c4' vr) as (vs' & vvs' & vspreds & vr').\n  eapply termrelnd\u2080_antired.\n  - eapply evalToStar.\n    unfold inject, injectA; cbn.\n    eapply (I.eval_ctx\u2080 I.phole); simpl;\n      eauto using I.eval_beta.\n  - apply rt1n_refl.\n  - rewrite eq.\n    crushTyping.\n    change (eraseAnnot _) with (inject n \u03c42) at 1.\n    rewrite ia_unfolds_eraseAnnot.\n    change (eraseAnnot _) with (extract n \u03c41) at 2.\n    rewrite inject_sub, extract_sub, unfolds_sub; crushValidTy.\n    cbn.\n    assert (ve\u03c41 : ValidPTy (embed \u03c41)) by eauto using ValidTy_implies_ValidPTy_embed.\n    assert (ve\u03c42 : ValidPTy (embed \u03c42)) by eauto using ValidTy_implies_ValidPTy_embed.\n\n    rewrite eq in vr'.\n    destruct (valrel_ptarr_inversion ve\u03c41 ve\u03c42 vr') as (tsb & tub & \u03c4\u2081' & -> & -> & v\u03c4\u2081' & tyeq & tytsb & tytub & trtsub).\n    eapply valrel_termrelnd\u2080.\n\n    eapply valrel_pEmulDV_unfoldn; crushValidTy.\n    rewrite eq.\n    eapply valrel_inArr.\n    change (UValIE n \u03c41) with (repEmul (pEmulDV n p \u03c41)).\n    rewrite isToEq_embed_leftinv in tyeq.\n    refine (valrel_lambda _ _ _ _ _ _); cbn;\n      eauto using ValidTy_implies_ValidPTy_embed, ValidTy_implies_ValidPTy_pEmulDV with tyvalid;\n      crushOfType.\n    now eapply tyeq_refl.\n    cbn.\n    erewrite <-?(fizzbuzz (n := n) (p := p)) in tytub; cbn in tytub.\n    I.crushTyping;\n    rewrite ?repEmul_embed_leftinv.\n    eapply injectT; crushValidTy.\n    erewrite <- eq.\n    eapply unfolds_T; crush.\n    now rewrite repEmul_embed_leftinv in tyvs.\n    eapply extractT; crushValidTy.\n    now eapply UValIE_valid.\n    cbn.\n    E.crushTyping.\n    now rewrite ?isToEq_embed_leftinv in tytub.\n\n    intros w' vs' vu' fw' szvu vr''.\n    destruct (valrel_implies_Value vr'') as (vvs'' & vvu').\n    cbn.\n    crush.\n    rewrite inject_sub, extract_sub; crushValidTy.\n\n    rewrite unfolds_sub.\n    rewrite <-ap_liftSub, liftSub_wkm, apply_wkm_beta1_cancel.\n    assert (dir_world_prec n w' d p) as dwp' by apply (dwp_invert_S' dwp _ fw').\n    destruct d.\n    + (* eapply termrel_size_left. *)\n      (* intros sz. *)\n      (* cbn in sz. *)\n      (* assert (szvs' : (size vs') <= w') by lia. *)\n      assert (nsz : forall A, dir_lt = dir_gt -> A) by (intros _ [=]).\n      pose proof (IHext _ _ _ dwp' (nsz _) vr'') as extr_tr.\n      refine (termrel_antired_star_left _ _).\n      eapply (evalstar_ctx' vspreds);\n        I.inferContext; cbn; eauto using inject_value.\n      cbn.\n      (* clear sz szvs'. *)\n      refine (termrelnd\u2080_ectx_sub (I.papp\u2082 (inject n \u03c42) (I.papp\u2082 _ I.phole)) _ extr_tr _);\n        cbn; eauto using inject_value.\n      intros vs2 vr2.\n      destruct (valrel_implies_Value vr2) as (vvs2 & _).\n      clear extr_tr IHext.\n      cbn.\n      refine (termrel_antired_star_left _ _).\n      {eapply evalToStar.\n       refine (eval_ctx\u2080 (I.papp\u2082 (inject n \u03c42) I.phole) (I.eval_beta _) _); cbn; eauto using inject_value.\n      }\n      rewrite valrel_fixp in vr'.\n      destruct vr' as [_ vr'].\n      destruct vr' as (tsb' & eq1 & _ & tsb2 & tub' & ? & ? & -> & eq2 & vr').\n      inversion eq1; inversion eq2; subst.\n      specialize (vr' w' fw' vs2 vu' (nsz _) vr2).\n      cbn.\n      eapply (termrel_ectx' vr'); I.inferContext; E.inferContext;\n        cbn; eauto using inject_value.\n      intros w3 fw3 vs3 vu3 vr3.\n      eapply termrelnd\u2080_termrel.\n      refine (IHinj w3 vs3 vu3 _ vr3); eauto using dwp_mono.\n    + destruct (dwp_invert_gt dwp) as (-> & ineq).\n      pose proof (IHext _ _ _ dwp' (fun _ => szvu eq_refl) vr'') as extr_tr.\n      refine (termrel_antired_star_left _ _).\n      eapply (evalstar_ctx' vspreds);\n        I.inferContext; cbn; eauto using inject_value.\n      cbn.\n      refine (termrelnd\u2080_ectx_sub (I.papp\u2082 (inject n \u03c42) (I.papp\u2082 _ I.phole)) _ extr_tr _);\n        cbn; eauto using inject_value.\n      intros vs2 vr2.\n      destruct (valrel_implies_Value vr2) as (vvs2 & _).\n      clear extr_tr IHext.\n      cbn.\n      refine (termrel_antired_star_left _ _).\n      eapply evalToStar.\n      refine (eval_ctx\u2080 (I.papp\u2082 (inject n \u03c42) I.phole) (I.eval_beta _) _); cbn; eauto using inject_value.\n\n      rewrite valrel_fixp in vr'.\n      destruct vr' as [_ vr'].\n      destruct vr' as (tsb' & eq1 & _ & tsb2 & tub' & ? & ? & -> & eq2 & vr').\n      inversion eq1; inversion eq2; subst.\n      specialize (vr' w' fw' vs2 vu' (fun _ => szvu eq_refl) vr2).\n      eapply (termrel_ectx' vr'); I.inferContext; E.inferContext;\n        cbn; eauto using inject_value.\n      intros w3 fw3 vs3 vu3 vr3.\n      eapply termrelnd\u2080_termrel.\n      refine (IHinj w3 vs3 vu3 _ vr3); eauto using dwp_mono.\nQed.\n\nLemma inject_tprod_works {n w d p \u03c4\u2081 \u03c4\u2082 vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tprod \u03c4\u2081 \u03c4\u2082 ->\n  ValidTy \u03c4\u2081 -> ValidTy \u03c4\u2082 ->\n  (forall w' vs1 vu1, inject_works_prop n w' d p vs1 vu1 \u03c4\u2081) \u2192\n  (forall w' vs1 vu1, inject_works_prop n w' d p vs1 vu1 \u03c4\u2082) \u2192\n  inject_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c4\u2081 v\u03c4\u2082 inj\u2081 inj\u2082 dwp vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tvs] [vvu tvu]].\n  destruct (unfolds_works v\u03c4' vr) as (vs' & vvs' & vspreds & vr').\n  rewrite eq in vr'.\n\n  assert (ve\u03c4\u2081 : ValidPTy (embed \u03c4\u2081)) by eauto using ValidTy_implies_ValidPTy_embed.\n  assert (ve\u03c4\u2082 : ValidPTy (embed \u03c4\u2082)) by eauto using ValidTy_implies_ValidPTy_embed.\n  destruct (valrel_ptprod_inversion ve\u03c4\u2081 ve\u03c4\u2082 vr') as (vs1 & vs2 & vu1 & vu2 & -> & -> & ot1 & ot2 & vr2).\n  destruct ot1 as [[vvs1 tvs1] tvu1].\n  destruct ot2 as [[vvs2 tvs2] tvu2].\n  eapply termrelnd\u2080_antired_left.\n  { (* beta-reduce *)\n    eapply evalStepStar.\n    apply eval\u2080_to_eval.\n    unfold inject, injectA; cbn.\n    eapply eval_beta; now cbn.\n    rewrite eq.\n    cbn.\n    crushTyping.\n    change (eraseAnnot _) with (inject n \u03c4\u2081) at 1.\n    rewrite ia_unfolds_eraseAnnot.\n    change (eraseAnnot _) with (inject n \u03c4\u2082) at 2.\n    rewrite ?inject_sub, unfolds_sub; crushValidTy.\n    cbn.\n\n    eapply evalStepTrans.\n    eapply (evalstar_ctx' vspreds); I.inferContext; cbn; eauto using inject_value.\n    cbn.\n\n    eapply evalStepStar.\n    eapply (I.eval_from_eval\u2080 (eval_proj\u2081 vvs1 vvs2)); I.inferContext; cbn; eauto using inject_value.\n    eapply rt1n_refl.\n  }\n  cbn.\n\n  destruct w.\n  - destruct (inject_terminates n v\u03c4\u2081 (conj vvs1 tvs1)) as (vs1' & vvs1' & es1).\n    destruct (inject_terminates n v\u03c4\u2082 (conj vvs2 tvs2)) as (vs2' & vvs2' & es2).\n    eapply termrelnd\u2080_antired_left.\n    { crushTyping.\n      rewrite ?inject_sub; crushValidTy.\n      eapply evalStepTrans.\n      { eapply (evalstar_ctx' es1); I.inferContext; cbn; eauto using inject_value. }\n      eapply evalStepTrans.\n      { eapply (evalstar_ctx' vspreds); I.inferContext; cbn; eauto using inject_value. }\n      eapply evalStepStar.\n      { eapply (eval_from_eval\u2080 (eval_proj\u2082 vvs1 vvs2)); I.inferContext; cbn; eauto using inject_value. }\n      eapply evalStepTrans.\n      { eapply (evalstar_ctx' es2); I.inferContext; cbn; eauto using inject_value. }\n      eapply rt1n_refl.\n    }\n    cbn.\n    eapply valrel_termrelnd\u2080.\n    destruct tvu1 as (vvu1 & tvu1).\n    destruct tvu2 as (vvu2 & tvu2).\n    rewrite isToEq_embed_leftinv in *.\n    rewrite repEmul_embed_leftinv in *.\n\n    eapply valrel_pEmulDV_unfoldn; crushValidTy.\n    rewrite eq in *.\n\n    eapply valrel_inProd''; crushValidTy.\n    rewrite valrel_fixp; unfold valrel'; cbn.\n    split.\n    split; split; cbn; crushTyping; eauto.\n    + eapply (I.preservation_star es1).\n      crushTyping.\n      crushTyping.\n\n      eauto using injectT with typing uval_typing tyvalid.\n    + eapply (I.preservation_star es2).\n      crushTyping.\n      eauto with typing uval_typing.\n    + E.crushTyping.\n    + eexists _; intuition.\n      split; intros; exfalso; lia.\n  -  assert (fw : w < S w) by lia.\n     destruct (vr2 w fw) as (vr3 & vr4).\n     fold embed in *.\n     eapply dwp_invert_S in dwp.\n     specialize (inj\u2081 w vs1 vu1 dwp vr3).\n     specialize (inj\u2082 w vs2 vu2 dwp vr4).\n     unfold inject, injectA; cbn.\n     change (eraseAnnot _) with (inject n \u03c4\u2081) at 1.\n     change (eraseAnnot _) with (inject n \u03c4\u2082).\n     eapply (termrelnd\u2080_ectx' inj\u2081); I.inferContext; E.inferContext; [|now cbn].\n     intros vs5 vu5 vr5.\n     destruct (valrel_implies_Value vr5) as (vvs5 & vvu5).\n     cbn.\n     eapply termrelnd\u2080_antired_left.\n     { (* beta-reduce *)\n       eapply evalStepTrans.\n       { eapply (evalstar_ctx' vspreds); I.inferContext; cbn; eauto using inject_value. }\n       eapply evalStepStar.\n       { eapply (eval_from_eval\u2080 (eval_proj\u2082 vvs1 vvs2)); I.inferContext; cbn; eauto using inject_value. }\n       cbn.\n       eapply rt1n_refl.\n     }\n     eapply (termrelnd\u2080_ectx' inj\u2082); I.inferContext; E.inferContext; cbn; eauto.\n     intros vs6 vu6 vr6.\n     eapply valrel_termrelnd\u2080.\n\n    eapply valrel_pEmulDV_unfoldn; crushValidTy.\n    rewrite eq in *.\n\n     eapply valrel_inProd'', valrel_pair';\n       try crushValidPTyMatch; crushValidTy.\nQed.\n\nLemma inject_tsum_works {n w d p \u03c4\u2081 \u03c4\u2082 vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tsum \u03c4\u2081 \u03c4\u2082 ->\n  ValidTy \u03c4\u2081 -> ValidTy \u03c4\u2082 ->\n  (forall w' vs1 vu1, inject_works_prop n w' d p vs1 vu1 \u03c4\u2081) \u2192\n  (forall w' vs1 vu1, inject_works_prop n w' d p vs1 vu1 \u03c4\u2082) \u2192\n  inject_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c4\u2081 v\u03c4\u2082 inj\u2081 inj\u2082 dwp vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tvs] [vvu tvu]].\n\n  destruct (unfolds_works v\u03c4' vr) as (vs' & vvs' & vspreds & vr').\n  rewrite eq in vr'.\n\n  (* assert (w < S w) as fw by lia. *)\n  (* assert (dir_world_prec n w d p) as dwp' by eauto using dwp_invert_S. *)\n\n  cbn in vr'.\n  assert (ve\u03c4\u2081 : ValidPTy (embed \u03c4\u2081)) by eauto using ValidTy_implies_ValidPTy_embed.\n  assert (ve\u03c4\u2082 : ValidPTy (embed \u03c4\u2082)) by eauto using ValidTy_implies_ValidPTy_embed.\n\n  destruct (valrel_ptsum_inversion ve\u03c4\u2081 ve\u03c4\u2082 vr') as (vs''' & vu' & [(? & ? & ot' & vrs)|(? & ? & ot' & vrs) ]);\n    (* specialize (vrs w fw); *)\n    subst; cbn in vvs.\n  - eapply termrelnd\u2080_antired_left.\n    { (* beta-reduce *)\n      eapply evalStepStar.\n      apply eval\u2080_to_eval.\n      unfold inject, injectA; cbn.\n      eauto with eval.\n      rewrite eq.\n      cbn.\n      rewrite ia_unfolds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (inject n \u03c4\u2081) at 1.\n      change (eraseAnnot _) with (inject n \u03c4\u2082).\n      crushTyping.\n      rewrite unfolds_sub.\n      cbn.\n      rewrite ?inject_sub; crushValidTy.\n      eapply evalStepTrans.\n      eapply (evalstar_ctx' vspreds); I.inferContext; cbn; try easy.\n      eapply evalToStar.\n      refine (eval_ctx\u2080 (I.pinl I.phole) _ I).\n      crush.\n    }\n    cbn.\n    repeat change (apTm ?\u03be ?t) with t[\u03be].\n    rewrite ?inject_sub; crushValidTy.\n\n    destruct w.\n    + rewrite isToEq_embed_leftinv in *.\n      assert (\u27ea empty i\u22a2 I.inl vs''' : unfoldn (LMC \u03c4') \u03c4' \u27eb) as tvs'.\n      eapply (I.preservation_star vspreds); crush.\n      { rewrite repEmul_embed_leftinv in *; eauto using unfolds_T. }\n      rewrite eq in tvs'.\n      inversion tvs'; subst.\n\n      eapply (WtEq _ (U := unfoldn (LMC \u03c4') \u03c4')) in tvu; crushValidTy_with_UVal; eauto using ValidTy_unfoldn.\n      2: { eapply tyeq_symm, ty_eq_unfoldn; crushValidTy. }\n      rewrite eq in tvu.\n\n      eapply E.invert_ty_inl in tvu; eauto with tyvalid.\n      destruct tvu as (\u03c4\u2081' & \u03c4\u2082' & v\u03c4\u2081\u2082 & v\u03c4\u2082' & tyvu' & (tyeq\u2081 & tyeq\u2082)%tyeq_invert_tsum).\n\n      cbn in vvs'.\n      rewrite <-repEmul_embed_leftinv in H2.\n      destruct (inject_terminates n v\u03c4\u2081 (conj vvs' H2)) as (vs2 & vvs2 & es2).\n      eapply termrelnd\u2080_antired_left.\n      {eapply (evalstar_ctx' es2); I.inferContext; now cbn. }\n      cbn.\n      eapply valrel_termrelnd\u2080.\n\n      eapply valrel_pEmulDV_unfoldn; crushValidTy.\n      rewrite eq in *.\n\n      eapply valrel_inSum''; crushValidTy.\n      eapply valrel_inl''; try crushValidPTyMatch; crushValidTy.\n      assert (tyvs2 : \u27ea empty i\u22a2 vs2 : repEmul (pEmulDV n p \u03c4\u2081) \u27eb).\n      * eapply (I.preservation_star es2); eauto using ValidEnv_nil.\n        I.crushTyping.\n        cbn.\n        rewrite repEmul_embed_leftinv.\n        eapply injectT; crushValidTy.\n      * repeat split; try assumption.\n        cbn.\n        refine (WtEq _ tyeq\u2081 _ _ tyvu'); try E.try_typed_terms_are_valid; eauto with tyvalid.\n    + assert (fw : w < S w) by lia.\n      specialize (vrs w fw).\n      eapply dwp_invert_S in dwp.\n      specialize (inj\u2081 w vs''' vu' dwp vrs).\n      change (inl (inl ?t)) with (pctx_app t (pinl (pinl phole))).\n      change (E.inl ?t) with (E.pctx_app t (E.pinl E.phole)).\n      eapply termrelnd\u2080_ectx; cbn; eauto.\n      intros vs2 vu2 vr2.\n      cbn.\n      eapply valrel_termrelnd\u2080.\n\n      eapply valrel_pEmulDV_unfoldn; crushValidTy.\n      rewrite eq in *.\n\n      eapply valrel_inSum''; eauto using valrel_inSum'', valrel_inl'.\n      eapply valrel_inl'; cbn; eauto using valrel_inSum'', valrel_inl', ValidTy_implies_ValidPTy_pEmulDV.\n  - eapply termrelnd\u2080_antired_left.\n    { (* beta-reduce *)\n      eapply evalStepStar.\n      apply eval\u2080_to_eval.\n      unfold inject, injectA; cbn.\n      eauto with eval.\n      rewrite eq.\n      cbn.\n      rewrite ia_unfolds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (inject n \u03c4\u2081) at 1.\n      change (eraseAnnot _) with (inject n \u03c4\u2082).\n      crushTyping.\n      rewrite unfolds_sub.\n      cbn.\n      rewrite ?inject_sub; crushValidTy.\n      eapply evalStepTrans.\n      eapply (evalstar_ctx' vspreds); I.inferContext; cbn; try easy.\n      eapply evalToStar.\n      refine (eval_ctx\u2080 (I.pinl I.phole) _ I).\n      crush.\n    }\n    cbn.\n    repeat change (apTm ?\u03be ?t) with t[\u03be].\n    rewrite ?inject_sub; crushValidTy.\n\n    destruct w.\n    + rewrite isToEq_embed_leftinv in *.\n      assert (\u27ea empty i\u22a2 I.inr vs''' : unfoldn (LMC \u03c4') \u03c4' \u27eb) as tvs'.\n      eapply (I.preservation_star vspreds); crush.\n      { rewrite repEmul_embed_leftinv in *; eauto using unfolds_T. }\n      rewrite eq in tvs'.\n      inversion tvs'; subst.\n\n      eapply (WtEq _ (U := unfoldn (LMC \u03c4') \u03c4')) in tvu; crushValidTy_with_UVal; eauto using ValidTy_unfoldn.\n      2: { eapply tyeq_symm, ty_eq_unfoldn; crushValidTy. }\n      rewrite eq in tvu.\n\n      eapply E.invert_ty_inr in tvu; eauto with tyvalid.\n      destruct tvu as (\u03c4\u2081' & \u03c4\u2082' & v\u03c4\u2081\u2082 & v\u03c4\u2082' & tyvu' & (tyeq\u2081 & tyeq\u2082)%tyeq_invert_tsum).\n\n      cbn in vvs'.\n      rewrite <-repEmul_embed_leftinv in H2.\n      destruct (inject_terminates n v\u03c4\u2082 (conj vvs' H2)) as (vs2 & vvs2 & es2).\n      eapply termrelnd\u2080_antired_left.\n      {eapply (evalstar_ctx' es2); I.inferContext; now cbn. }\n      cbn.\n      eapply valrel_termrelnd\u2080.\n\n      eapply valrel_pEmulDV_unfoldn; crushValidTy.\n      rewrite eq in *.\n\n      eapply valrel_inSum''; crushValidTy.\n      eapply valrel_inr''; try crushValidPTyMatch; crushValidTy.\n      assert (tyvs2 : \u27ea empty i\u22a2 vs2 : repEmul (pEmulDV n p \u03c4\u2082) \u27eb).\n      * eapply (I.preservation_star es2); eauto using ValidEnv_nil.\n        I.crushTyping.\n        cbn.\n        rewrite repEmul_embed_leftinv.\n        eapply injectT; crushValidTy.\n      * repeat split; try assumption.\n        cbn.\n        refine (WtEq _ tyeq\u2082 _ _ tyvu'); try E.try_typed_terms_are_valid; eauto with tyvalid.\n    + assert (fw : w < S w) by lia.\n      specialize (vrs w fw).\n      eapply dwp_invert_S in dwp.\n      specialize (inj\u2082 w vs''' vu' dwp vrs).\n      change (inl (inr ?t)) with (pctx_app t (pinl (pinr phole))).\n      change (E.inr ?t) with (E.pctx_app t (E.pinr E.phole)).\n      eapply termrelnd\u2080_ectx; cbn; eauto.\n      intros vs2 vu2 vr2.\n      cbn.\n      eapply valrel_termrelnd\u2080.\n\n      eapply valrel_pEmulDV_unfoldn; crushValidTy.\n      rewrite eq in *.\n\n      eapply valrel_inSum''; eauto using valrel_inSum'', valrel_inl'.\n      eapply valrel_inr'; cbn; eauto using valrel_inSum'', valrel_inl', ValidTy_implies_ValidPTy_pEmulDV.\nQed.\n\n\nLemma extract_tarr_works {n w d p \u03c4\u2081 \u03c4\u2082 vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tarr \u03c4\u2081 \u03c4\u2082 ->\n  ValidTy \u03c4\u2081 -> ValidTy \u03c4\u2082 ->\n  (forall w' vs' vu', w' < w \u2192 inject_works_prop n w' d p vs' vu' \u03c4\u2081) \u2192\n  (forall w' vs' vu', w' < w \u2192 extract_works_prop n w' d p vs' vu' \u03c4\u2082) \u2192\n  extract_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c4\u2081 v\u03c4\u2082 inj\u2081 extr\u2082 dwp sz vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  cbn -[UValIE] in tyvs, tyvu.\n\n  eapply valrel_pEmulDV_unfoldn in vr; crushValidTy.\n  rewrite eq in vr.\n\n  destruct (invert_valrel_pEmulDV_for_caseUValArr v\u03c4\u2081 v\u03c4\u2082 vr) as [(vs2 & -> & es2 & vr2) | (-> & div)].\n\n  - eapply termrelnd\u2080_antired.\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 1.\n      change (eraseAnnot _) with (inject n \u03c4\u2081) at 2.\n      change (eraseAnnot _) with (caseArr n (I.var 1) \u03c4\u2081 \u03c4\u2082) at 1.\n      crushTyping.\n      rewrite extract_sub, inject_sub, caseArr_sub; crushValidTy.\n      cbn.\n      eapply rt1n_refl.\n    + eapply rt1n_refl.\n    + eapply valrel_termrelnd\u2080.\n      eapply folds_works; crushValidTy.\n      rewrite eq.\n      unshelve eapply valrel_ptarr_inversion in vr2; try crushValidPTyMatch; crushValidTy.\n      destruct vr2 as (tsb & tub & \u03c4'' & -> & [=] & v\u03c4'' & tyeq & ttsb & ttub & trb); subst.\n      cbn.\n      rewrite <-(repEmul_embed_leftinv \u03c4\u2081) at 2.\n      refine (valrel_lambda _ _ _ _ _ _);\n        crushOfType;\n        repeat crushValidPTyMatch; I.crushTyping; E.crushTyping;\n        rewrite ?isToEq_embed_leftinv, ?repEmul_embed_leftinv;\n        try match goal with\n          | [ |- \u27ea _ i\u22a2 inject _ _ : _ \u27eb ] => eapply injectT\n          | [ |- \u27ea _ i\u22a2 extract _ _ : _ \u27eb ] => eapply extractT\n          | [ |- \u27ea _ i\u22a2 caseArr _ _ _ _ : _ \u27eb ] => eapply caseArr_T\n          end; try assumption.\n      I.crushTyping; eauto using UValIE_valid.\n      destruct (valrel_implies_Value H1) as (vvs & vvu).\n      rewrite extract_sub, inject_sub, caseArr_sub; crushValidTy.\n      cbn; crushTyping.\n      rewrite <-ap_liftSub, <-up_liftSub, liftSub_wkm, apply_wkm_beta1_up_cancel.\n      eapply termrel_antired_star.\n      { eapply (evalstar_ctx' es2); I.inferContext; cbn; eauto using extract_value. }\n      { eapply rt1n_refl. }\n      cbn.\n\n      pose proof (dwp3 := dwp_invert_S' dwp w' H).\n      specialize (inj\u2081 w' vs vu H dwp3 H1).\n\n      refine (termrelnd\u2080_ectx_sub (I.papp\u2082 _ (I.papp\u2082 _ I.phole)) _ inj\u2081 _);\n        cbn; eauto using extract_value.\n\n      intros vs2 vr2.\n      destruct (valrel_implies_Value vr2) as (vvs2 & _).\n      eapply termrel_antired_star_left.\n      { eapply evalStepStar.\n        eapply (eval_from_eval\u2080 (eval_beta vvs2)); I.inferContext; cbn; eauto using extract_value.\n        eapply rt1n_refl.\n      }\n      cbn.\n\n      specialize (trb w' vs2 vu H H0 vr2).\n      eapply (termrel_ectx' trb); I.inferContext; E.inferContext; cbn; eauto using extract_value.\n\n      intros w2 fw2 vs3 vu3 vr3.\n      eapply termrel_size_right'.\n      intros ineq.\n      eapply termrelnd\u2080_termrel.\n      eapply extr\u2082; crush.\n      eauto using dwp_mono.\n      specialize (ineq eq_refl).\n      lia.\n  - apply dwp_invert_imprecise in dwp; subst.\n    eapply termrelnd\u2080_antired_left.\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      rewrite folds_sub.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 1.\n      change (eraseAnnot _) with (inject n \u03c4\u2081) at 2.\n      change (eraseAnnot _) with (caseArr n (I.var 1) \u03c4\u2081 \u03c4\u2082) at 1.\n      crushTyping.\n      rewrite inject_sub, extract_sub, caseArr_sub; crushValidTy.\n      cbn.\n      eapply rt1n_refl.\n    + eapply valrel_termrelnd\u2080.\n      eapply folds_works; crushValidTy.\n      rewrite eq; cbn.\n\n      eapply (WtEq _ (U := unfoldn (LMC \u03c4') \u03c4')) in tyvu;\n        eauto using ty_eq_unfoldn, ValidTy_unfoldn.\n      2: eapply tyeq_symm, ty_eq_unfoldn; crushValidTy.\n\n      rewrite eq in tyvu.\n      E.stlcCanForm; crushValidTy; eauto using tyeq_refl.\n      destruct H as (\u03c4u2 & tyeq2 & v\u03c4u2 & -> & tyx).\n\n      rewrite <-(repEmul_embed_leftinv \u03c4\u2081) at 2.\n      refine (valrel_lambda _ _ _ _ _ _);\n        crushOfType;\n        I.crushTyping;\n        E.crushTyping;\n        rewrite ?isToEq_embed_leftinv, ?repEmul_embed_leftinv in *;\n        try match goal with\n          | [ |- \u27ea _ i\u22a2 inject _ _ : _ \u27eb ] => eapply injectT\n          | [ |- \u27ea _ i\u22a2 extract _ _ : _ \u27eb ] => eapply extractT\n          | [ |- \u27ea _ i\u22a2 caseArr _ _ _ _ : _ \u27eb ] => eapply caseArr_T\n          end;\n        eauto using ValidTy_implies_ValidPTy_embed with tyeq tyvalid.\n      rewrite eq in tyvs.\n      refine (typing_ren tyvs (empty r\u25bb _) wkm (I.wtRen_wkm _ _)).\n      eapply termrel_div_lt.\n      rewrite extract_sub, inject_sub, caseArr_sub; crushValidTy.\n      rewrite <-ap_liftSub, liftSub_wkm, apply_wkm_beta1_cancel.\n      eapply (divergence_closed_under_evalcontext' div); I.inferContext; cbn; eauto using extract_value.\nQed.\n\nLemma fold_eval_inv {t1 t2} :\n  fold_ t1 --> t2 -> exists t2', t2 = fold_ t2' /\\ t1 --> t2'.\nProof.\n  intros e.\n  remember (fold_ t1) as t1o.\n  destruct e as [C t1' t2' eval\u2080 eC].\n  destruct C; inversion Heqt1o.\n  - cbn in Heqt1o; subst.\n    inversion eval\u2080.\n  - exists (pctx_app t2' C).\n    split; eauto with eval.\nQed.\n\nLemma folds_eval_inv {t1 t2 n} :\n  folds n t1 --> t2 -> exists t2', t2 = folds n t2' /\\ t1 --> t2'.\nProof.\n  revert t2.\n  induction n.\n  - intros t2 e.\n    exists t2; eauto.\n  - cbn.\n    intros t2 e.\n    destruct (fold_eval_inv e) as (t2' & -> & e').\n    destruct (IHn _ e') as (t2'' & -> & e'').\n    exists t2''; eauto.\nQed.\n\nLemma folds_evalStar_inv {t1 t2 n} :\n  folds n t1 -->* t2 -> exists t2', t2 = folds n t2' /\\ t1 -->* t2'.\nProof.\n  intros es.\n  remember (folds n t1) as t1'.\n  revert t1 Heqt1'.\n  induction es.\n  - intros t1 ->.\n    exists t1; eauto with eval.\n  - intros t1 ->.\n    destruct (folds_eval_inv H) as (t3' & -> & es').\n    destruct (IHes t3' eq_refl) as (t2' & -> & es'').\n    exists t2'; eauto with eval.\nQed.\n\nLemma folds_evalStar_inv_value {t1 t2 n} :\n  folds n t1 -->* t2 -> Value t1 -> t2 = folds n t1.\nProof.\n  intros es vt1.\n  destruct (folds_evalStar_inv es) as (t2' & -> & es').\n  f_equal.\n  symmetry.\n  now eapply value_evalStar.\nQed.\n\nLemma fold_evalStar {t1 t2} :\n  fold_ t1 --> t2 -> exists t2', t2 = fold_ t2' /\\ t1 --> t2'.\nProof.\n  intros e.\n  remember (fold_ t1) as t1o.\n  destruct e as [C t1' t2' eval\u2080 eC].\n  destruct C; inversion Heqt1o.\n  - cbn in Heqt1o; subst.\n    inversion eval\u2080.\n  - exists (pctx_app t2' C).\n    split; eauto with eval.\nQed.\n\n\nLemma extract_tprod_works {n w d p \u03c4\u2081 \u03c4\u2082 vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tprod \u03c4\u2081 \u03c4\u2082 ->\n  ValidTy \u03c4\u2081 -> ValidTy \u03c4\u2082 ->\n  (forall w' vs1 vu1, extract_works_prop n w' d p vs1 vu1 \u03c4\u2081) \u2192\n  (forall w' vs1 vu1, extract_works_prop n w' d p vs1 vu1 \u03c4\u2082) \u2192\n  extract_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c4\u2081 v\u03c4\u2082 extr\u2081 extr\u2082 dwp sz vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  cbn -[UValIE] in tyvs, tyvu.\n\n  eapply valrel_pEmulDV_unfoldn in vr; crushValidTy.\n  rewrite eq in vr.\n\n  eapply invert_valrel_pEmulDV_for_caseUValProd in vr; crushValidTy.\n  destruct vr as [(vs1 & -> & es1 & vr1)|(-> & div)].\n\n  - eapply termrelnd\u2080_antired.\n    { eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2081) at 1.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 1.\n      rewrite folds_sub.\n      cbn. crushTyping.\n      rewrite ?extract_sub; crushValidTy.\n      eapply evalStepStar.\n      { rewrite folds_folds_ctx.\n        cbn in vvs.\n        eapply (eval_from_eval\u2080 (eval_case_inl vvs)); I.inferContext.\n        eapply ectx_cat; crush; eauto using folds_ectx, extract_value.\n      }\n      { eapply rt1n_refl. }\n    }\n    { eapply rt1n_refl. }\n    rewrite ?pctx_cat_app.\n    cbn.\n    eapply valrel_ptprod_inversion  in vr1; try crushValidPTyMatch; crushValidTy.\n    destruct vr1 as (vs11 & vs12 & vu11 & vu12 & -> & -> & ot11 & ot12 & vr1').\n    destruct (OfType_implies_Value ot11) as (vvs11 & _).\n    destruct (OfType_implies_Value ot12) as (vvs12 & _).\n\n    eapply termrelnd\u2080_antired_left.\n    { eapply evalToStar.\n      eapply (I.eval_from_eval\u2080 (I.eval_proj\u2081 vvs11 vvs12)); I.inferContext; cbn; eauto using extract_value.\n      repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\n    }\n    rewrite ?pctx_cat_app, <-folds_folds_ctx.\n    cbn.\n\n    destruct d.\n    + clear sz.\n      intros vs2 vvs2 es2.\n\n      rewrite folds_folds_ctx in es2.\n      destruct (evalStar_ectx_inv (folds_ctx (LMC \u03c4')) _ folds_ectx _ es2 vvs2) as (vs3 & vvs3 & es3 & es3').\n      rewrite <-folds_folds_ctx in es3'.\n      eapply folds_evalStar_inv_value in es3'; eauto; subst.\n\n      destruct (evalStar_ectx_inv (I.ppair\u2081 I.phole _) _ I _ es3 (proj1 folds_Value vvs2)) as (vs11' & vvs11' & es11' & es4).\n      cbn in es4.\n      destruct (evalStar_ectx_inv (I.ppair\u2082 vs11' I.phole) _ (conj vvs11' I) _ es4 vvs3) as (vs12' & vvs12' & es12' & es5).\n      cbn in es5.\n      assert (vs3 = pair vs11' vs12') as ->.\n      { remember (pair vs11' vs12').\n        destruct es5; try reflexivity.\n        subst.\n        destruct (values_are_normal (t := pair vs11' vs12') (conj vvs11' vvs12') _ H).\n      }\n      clear es2 es3 es4 es5.\n      assert (app (extract n \u03c4\u2082)\n            (proj\u2082 (caseof (inl (I.pair vs11 vs12)) (var 0) (Om (UValIE n \u03c4\u2081 r\u00d7 UValIE n \u03c4\u2082)))) -->*\n            app (extract n \u03c4\u2082) vs12) as es12''.\n      { eapply evalStepStar.\n        eapply (eval_from_eval\u2080 (eval_case_inl (t := I.pair vs11 vs12) vvs)); I.inferContext; cbn; eauto using extract_value.\n        eapply evalStepStar.\n        eapply (eval_from_eval\u2080 (eval_proj\u2082 vvs11 vvs12)); I.inferContext; cbn; eauto using extract_value.\n        eapply rt1n_refl.\n      }\n      pose proof (es13 := determinacyStar es12'' es12' (values_are_normal vvs12')).\n      clear es12' es12''.\n\n      exists (E.pair vu11 vu12).\n      split; [|split]; eauto with eval.\n\n      eapply folds_works; crushValidTy.\n      rewrite eq.\n\n      eapply valrel_pair''; fold embed; try crushValidPTyMatch; crushValidTy.\n      destruct vvu.\n      split; split; rewrite ?repEmul_embed_leftinv, ?isToEq_embed_leftinv; crushOfType.\n      { eapply (I.preservation_star es11'); eauto using ValidEnv_nil.\n        I.crushTyping; eauto using extractT; crushValidTy.\n      }\n      { intuition. }\n      split; split; rewrite ?repEmul_embed_leftinv, ?isToEq_embed_leftinv; crushOfType.\n      { eapply (I.preservation_star es13); eauto using ValidEnv_nil.\n        I.crushTyping; eauto using extractT; crushValidTy.\n      }\n      { intuition. }\n      { intuition. }\n      { intros w' fw.\n        destruct (vr1' w' fw) as (vr11 & vr12).\n        pose proof (dwp_invert_S' dwp w' fw) as dwp2.\n        assert (forall A, dir_lt = dir_gt -> A) as nsz2 by (intros A eq3; inversion eq3).\n        destruct (extr\u2081 w' vs11 vu11 dwp2 (nsz2 _) vr11 _ vvs11' es11') as (vu1' & vvu1' & es11'' & vr11').\n        destruct vvu as (vvu11 & vvu12).\n        pose proof (E.value_evalStar vvu11 es11''); now subst.\n      }\n      { intros w' fw.\n        destruct (vr1' w' fw) as (vr11 & vr12).\n        pose proof (dwp_invert_S' dwp w' fw) as dwp2.\n        assert (forall A, dir_lt = dir_gt -> A) as nsz2 by (intros A eq3; inversion eq3).\n        destruct (extr\u2082 w' vs12 vu12 dwp2 (nsz2 _) vr12 _ vvs12' es13) as (vu2' & vvu2' & es12'' & vr12').\n        destruct vvu as (vvu11 & vvu12).\n        pose proof (E.value_evalStar vvu12 es12''); now subst.\n      }\n    + specialize (sz eq_refl).\n      cbn in sz.\n      assert (nlen : n <= n) by lia.\n      destruct w; [exfalso; lia|].\n      eapply dwp_invert_S in dwp.\n      assert (sz1 : E.size vu11 <= w) by lia.\n      assert (sz2 : E.size vu12 <= w) by lia.\n      assert (fw : w < S w) by lia.\n      destruct (vr1' w fw) as (vr11 & vr12).\n      specialize (extr\u2081 w _ _ dwp (fun _ => sz1) vr11).\n      specialize (extr\u2082 w _ _ dwp (fun _ => sz2) vr12).\n      rewrite folds_folds_ctx.\n      eapply (termrelnd\u2080_ectx' extr\u2081); I.inferContext; E.inferContext; try now cbn.\n      2: { eapply ectx_cat; cbn; eauto using folds_ectx. }\n      intros vs21 vu21 vr21.\n      destruct (valrel_implies_Value vr21) as [vvs21 vvu21].\n      refine (termrelnd\u2080_antired_left (d := dir_gt)_ _).\n      { cbn.\n        rewrite pctx_cat_app.\n        eapply evalStepStar.\n        eapply (eval_from_eval\u2080 (eval_case_inl (conj vvs11 vvs12 : Value (I.pair vs11 vs12)))); I.inferContext; cbn; eauto using extract_value.\n        eapply ectx_cat; crush; eauto using extract_value, folds_ectx.\n        rewrite pctx_cat_app.\n        cbn.\n        eapply evalToStar.\n        eapply (eval_from_eval\u2080 (eval_proj\u2082 vvs11 vvs12)); I.inferContext; cbn; eauto using extract_value.\n        repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\n      }\n      rewrite ?pctx_cat_app.\n      cbn -[termrelnd\u2080].\n\n      eapply (termrelnd\u2080_ectx' extr\u2082); I.inferContext; E.inferContext; eauto.\n      2: { eapply ectx_cat; cbn; eauto using folds_ectx. }\n      2: { now cbn. }\n\n      intros vs31 vu31 vr31.\n      eapply (valrel_termrelnd\u2080 (d := dir_gt)).\n      rewrite pctx_cat_app.\n      cbn.\n      rewrite <-folds_folds_ctx.\n      eapply folds_works; crushValidTy.\n      rewrite eq.\n      eapply valrel_pair';\n      eauto using ValidTy_implies_ValidPTy_embed.\n  - apply dwp_invert_imprecise in dwp; subst.\n    unfold caseProd, caseProd_pctx, caseUVal_pctx in div.\n    cbn in div.\n    intros vs' vvs' es.\n    exfalso.\n    refine (I.divergence_closed_under_evalstar _ _ (ex_intro _ vs' (conj vvs' es))).\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2081) at 1.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 1.\n      rewrite folds_sub.\n      cbn.\n      crushTyping.\n      repeat change (apTy ?\u03be ?\u03c4) with \u03c4[\u03be].\n      rewrite ?extract_sub; crushValidTy.\n      eapply rt1n_refl.\n    + rewrite folds_folds_ctx.\n      change (pair ?t1 ?t2) with (pctx_app t1 (ppair\u2081 phole t2)).\n      change (app ?t1 ?t2) with (pctx_app t2 (papp\u2082 t1 phole)).\n      change (proj\u2081 ?t) with (pctx_app t (pproj\u2081 phole)).\n      rewrite <-?pctx_cat_app.\n      eapply (divergence_closed_under_evalcontext _ div).\n      repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\nQed.\n\nLemma extract_tsum_works {n w d p \u03c4\u2081 \u03c4\u2082 vs vu \u03c4'} :\n  ValidTy \u03c4' ->\n  unfoldn (LMC \u03c4') \u03c4' = I.tsum \u03c4\u2081 \u03c4\u2082 ->\n  ValidTy \u03c4\u2081 -> ValidTy \u03c4\u2082 ->\n  (forall w' vs1 vu1, extract_works_prop n w' d p vs1 vu1 \u03c4\u2081) \u2192\n  (forall w' vs2 vu2, extract_works_prop n w' d p vs2 vu2 \u03c4\u2082) \u2192\n  extract_works_prop (S n) w d p vs vu \u03c4'.\nProof.\n  intros v\u03c4' eq v\u03c4\u2081 v\u03c4\u2082 extr\u2081 extr\u2082 dwp sz vr.\n  destruct (valrel_implies_OfType vr) as [[vvs tyvs] [vvu tyvu]].\n  cbn -[UValIE] in tyvs, tyvu.\n\n  eapply valrel_pEmulDV_unfoldn in vr; crushValidTy.\n  rewrite eq in vr.\n\n  eapply invert_valrel_pEmulDV_for_caseUValSum in vr; crushValidTy.\n  destruct vr as [(vs1 & -> & es1 & vr1)|(-> & div)].\n\n  - eapply termrelnd\u2080_antired.\n    { eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2081) at 2.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 2.\n      rewrite eraseAnnot_caseSumA.\n      rewrite folds_sub.\n      cbn. crushTyping.\n      rewrite ?extract_sub; crushValidTy.\n      rewrite caseSum_sub; cbn.\n      rewrite folds_folds_ctx.\n      eapply (evalstar_ctx' es1); I.inferContext; cbn.\n      eapply ectx_cat; crush; eauto using folds_ectx.\n    }\n    { eapply rt1n_refl. }\n    rewrite ?pctx_cat_app.\n    cbn.\n    eapply valrel_ptsum_inversion  in vr1; try crushValidPTyMatch; crushValidTy.\n    destruct vr1 as (vs11 & vu11 & [(-> & -> & ot11 & vr11)|(-> & -> & ot11 & vr11)]).\n    + destruct (OfType_implies_Value ot11) as (vvs11 & _).\n\n      eapply termrelnd\u2080_antired_left.\n      { eapply evalToStar.\n        eapply (I.eval_from_eval\u2080 (I.eval_case_inl vvs11)); I.inferContext; cbn; eauto using extract_value.\n        repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\n      }\n      rewrite ?pctx_cat_app, <-folds_folds_ctx.\n      cbn.\n      crushTyping.\n      rewrite extract_sub; crushValidTy.\n\n      destruct d.\n      * clear sz.\n        intros vs2 vvs2 es2.\n\n        rewrite folds_folds_ctx in es2.\n        destruct (evalStar_ectx_inv (folds_ctx (LMC \u03c4')) _ folds_ectx _ es2 vvs2) as (vs3 & vvs3 & es3 & es3').\n        rewrite <-folds_folds_ctx in es3'.\n        eapply folds_evalStar_inv_value in es3'; eauto; subst.\n\n        destruct (evalStar_ectx_inv (I.pinl I.phole) _ I _ es3 vvs3) as (vs11' & vvs11' & es11' & es4).\n        cbn in es4.\n        assert (vs3 = inl vs11') as ->.\n        { remember (inl vs11').\n          destruct es4; try reflexivity.\n          subst.\n          destruct (values_are_normal (t := inl vs11') vvs11' _ H).\n        }\n        clear es2 es3 es4.\n        exists (E.inl vu11).\n        split; [|split]; eauto with eval.\n\n        eapply folds_works; crushValidTy.\n        rewrite eq.\n\n        eapply valrel_inl''; fold embed; try crushValidPTyMatch; crushValidTy.\n        split; split; rewrite ?repEmul_embed_leftinv, ?isToEq_embed_leftinv; crushOfType.\n        { eapply (I.preservation_star es11'); eauto using ValidEnv_nil.\n          I.crushTyping; eauto using extractT; crushValidTy.\n        }\n        { intuition. }\n        { intros w' fw.\n          specialize (vr11 w' fw).\n          pose proof (dwp_invert_S' dwp w' fw) as dwp2.\n          assert (forall A, dir_lt = dir_gt -> A) as nsz2 by (intros A eq3; inversion eq3).\n          destruct (extr\u2081 w' vs11 vu11 dwp2 (nsz2 _) vr11 _ vvs11' es11') as (vu1' & vvu1' & es11'' & vr11').\n          pose proof (E.value_evalStar vvu es11''); now subst.\n        }\n      * specialize (sz eq_refl).\n        cbn in sz.\n        assert (nlen : n <= n) by lia.\n        destruct w; [exfalso; lia|].\n        eapply dwp_invert_S in dwp.\n        assert (sz1 : E.size vu11 <= w) by lia.\n        assert (fw : w < S w) by lia.\n        specialize (vr11 w fw).\n        specialize (extr\u2081 w _ _ dwp (fun _ => sz1) vr11).\n        rewrite folds_folds_ctx.\n        eapply (termrelnd\u2080_ectx' extr\u2081); I.inferContext; E.inferContext; try now cbn.\n        2: { eapply ectx_cat; cbn; eauto using folds_ectx. }\n        intros vs21 vu21 vr21.\n        eapply (valrel_termrelnd\u2080 (d := dir_gt)).\n        rewrite pctx_cat_app; cbn.\n        rewrite <-folds_folds_ctx.\n        eapply folds_works; crushValidTy.\n        rewrite eq.\n        destruct (valrel_implies_Value vr21).\n        eapply valrel_inl'; fold embed; try crushValidPTyMatch; crushValidTy.\n    + destruct (OfType_implies_Value ot11) as (vvs11 & _).\n\n      eapply termrelnd\u2080_antired_left.\n      { eapply evalToStar.\n        eapply (I.eval_from_eval\u2080 (I.eval_case_inr vvs11)); I.inferContext; cbn; eauto using extract_value.\n        repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\n      }\n      rewrite ?pctx_cat_app, <-folds_folds_ctx.\n      cbn.\n      crushTyping.\n      rewrite extract_sub; crushValidTy.\n\n      destruct d.\n      * clear sz.\n        intros vs2 vvs2 es2.\n\n        rewrite folds_folds_ctx in es2.\n        destruct (evalStar_ectx_inv (folds_ctx (LMC \u03c4')) _ folds_ectx _ es2 vvs2) as (vs3 & vvs3 & es3 & es3').\n        rewrite <-folds_folds_ctx in es3'.\n        eapply folds_evalStar_inv_value in es3'; eauto; subst.\n\n        destruct (evalStar_ectx_inv (I.pinr I.phole) _ I _ es3 vvs3) as (vs11' & vvs11' & es11' & es4).\n        cbn in es4.\n        assert (vs3 = inr vs11') as ->.\n        { remember (inr vs11').\n          destruct es4; try reflexivity.\n          subst.\n          destruct (values_are_normal (t := inr vs11') vvs11' _ H).\n        }\n        clear es2 es3 es4.\n        exists (E.inr vu11).\n        split; [|split]; eauto with eval.\n\n        eapply folds_works; crushValidTy.\n        rewrite eq.\n\n        eapply valrel_inr''; fold embed; try crushValidPTyMatch; crushValidTy.\n        split; split; rewrite ?repEmul_embed_leftinv, ?isToEq_embed_leftinv; crushOfType.\n        { eapply (I.preservation_star es11'); eauto using ValidEnv_nil.\n          I.crushTyping; eauto using extractT; crushValidTy.\n        }\n        { intuition. }\n        { intros w' fw.\n          specialize (vr11 w' fw).\n          pose proof (dwp_invert_S' dwp w' fw) as dwp2.\n          assert (forall A, dir_lt = dir_gt -> A) as nsz2 by (intros A eq3; inversion eq3).\n          destruct (extr\u2082 w' vs11 vu11 dwp2 (nsz2 _) vr11 _ vvs11' es11') as (vu1' & vvu1' & es11'' & vr11').\n          pose proof (E.value_evalStar vvu es11''); now subst.\n        }\n      * specialize (sz eq_refl).\n        cbn in sz.\n        assert (nlen : n <= n) by lia.\n        destruct w; [exfalso; lia|].\n        eapply dwp_invert_S in dwp.\n        assert (sz1 : E.size vu11 <= w) by lia.\n        assert (fw : w < S w) by lia.\n        specialize (vr11 w fw).\n        specialize (extr\u2082 w _ _ dwp (fun _ => sz1) vr11).\n        rewrite folds_folds_ctx.\n        eapply (termrelnd\u2080_ectx' extr\u2082); I.inferContext; E.inferContext; try now cbn.\n        2: { eapply ectx_cat; cbn; eauto using folds_ectx. }\n        intros vs21 vu21 vr21.\n        eapply (valrel_termrelnd\u2080 (d := dir_gt)).\n        rewrite pctx_cat_app; cbn.\n        rewrite <-folds_folds_ctx.\n        eapply folds_works; crushValidTy.\n        rewrite eq.\n        destruct (valrel_implies_Value vr21).\n        eapply valrel_inr'; fold embed; try crushValidPTyMatch; crushValidTy.\n  - apply dwp_invert_imprecise in dwp; subst.\n    unfold caseProd, caseProd_pctx, caseUVal_pctx in div.\n    cbn in div.\n    intros vs' vvs' es.\n    exfalso.\n    refine (I.divergence_closed_under_evalstar _ _ (ex_intro _ vs' (conj vvs' es))).\n    + eapply evalStepStar.\n      refine (eval_ctx\u2080 phole (eval_beta _) I); eauto.\n      rewrite eq.\n      rewrite ia_folds_eraseAnnot.\n      cbn.\n      change (eraseAnnot _) with (extract n \u03c4\u2081) at 2.\n      change (eraseAnnot _) with (extract n \u03c4\u2082) at 2.\n      rewrite eraseAnnot_caseSumA.\n      cbn.\n      rewrite folds_sub.\n      cbn.\n      crushTyping.\n      repeat change (apTy ?\u03be ?\u03c4) with \u03c4[\u03be].\n      rewrite ?extract_sub; crushValidTy.\n      eapply rt1n_refl.\n    + rewrite folds_folds_ctx.\n      rewrite caseSum_sub.\n      cbn.\n      change (caseof ?t1 ?t2 ?t3) with (pctx_app t1 (pcaseof\u2081 phole t2 t3)).\n      change (app ?t1 ?t2) with (pctx_app t2 (papp\u2082 t1 phole)).\n      rewrite <-?pctx_cat_app.\n      eapply (divergence_closed_under_evalcontext _ div).\n      repeat eapply ectx_cat; cbn; eauto using extract_value, folds_ectx.\nQed.\n\nLemma inject_works {n w d p \u03c4 vs vu} :\n  ValidTy \u03c4 ->\n  inject_works_prop n w d p vs vu \u03c4\nwith extract_works {n w d p \u03c4 vs vu} :\n  ValidTy \u03c4 ->\n  extract_works_prop n w d p vs vu \u03c4.\nProof.\n  - intros v\u03c4.\n    revert n w vs vu.\n    destruct n.\n    + unfold inject_works_prop, inject, injectA.\n      intros w vs vu dwp vr.\n      refine (inject_zero_works dwp vr).\n    + assert (ValidTy (unfoldn (LMC \u03c4) \u03c4)) as v\u03c4' by eauto using ValidTy_unfoldn.\n      remember (unfoldn (LMC \u03c4) \u03c4) as \u03c4'.\n      destruct \u03c4';\n      intros w vs vu dwp vr.\n      * (* \u03c4\u2081' \u21d2 \u03c4\u2082' *)\n        eapply (inject_tarr_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * (* tunit *)\n        eapply (inject_unit_works v\u03c4 (eq_sym Heq\u03c4')); now assumption.\n      * (* tbool *)\n        eapply (inject_bool_works v\u03c4 (eq_sym Heq\u03c4')); now assumption.\n      * (* \u03c4\u2081 r\u00d7 \u03c4\u2082 *)\n        eapply (inject_tprod_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * (* \u03c4\u2081 \u228e \u03c4\u2082 *)\n        eapply (inject_tsum_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * assert (LMC (unfoldn (LMC \u03c4) \u03c4) = 0) by (eapply unfoldn_LMC; crushValidTy).\n        rewrite <-Heq\u03c4' in H; cbn in H; exfalso; lia.\n      * destruct v\u03c4' as (c\u03c4' & _).\n        exfalso.\n        eauto using I.closed_implies_not_var.\n  - (* extract *)\n    intros v\u03c4.\n    revert n w vs vu.\n    destruct n.\n    + unfold extract_works_prop, extract, extractA.\n      intros w vs vu dwp vr.\n      refine (extract_zero_works dwp vr).\n    + assert (ValidTy (unfoldn (LMC \u03c4) \u03c4)) as v\u03c4' by eauto using ValidTy_unfoldn.\n      remember (unfoldn (LMC \u03c4) \u03c4) as \u03c4'.\n      destruct \u03c4';\n      intros w vs vu dwp vr.\n      * (* \u03c4\u2081' \u21d2 \u03c4\u2082' *)\n        eapply (extract_tarr_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * (* tunit *)\n        eapply (extract_unit_works v\u03c4 (eq_sym Heq\u03c4')); now assumption.\n      * (* tbool *)\n        eapply (extract_bool_works v\u03c4 (eq_sym Heq\u03c4')); now assumption.\n      * (* \u03c4\u2081 r\u00d7 \u03c4\u2082 *)\n        eapply (extract_tprod_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * (* \u03c4\u2081 \u228e \u03c4\u2082 *)\n        eapply (extract_tsum_works v\u03c4 (eq_sym Heq\u03c4')); intuition.\n      * assert (LMC (unfoldn (LMC \u03c4) \u03c4) = 0) by (eapply unfoldn_LMC; crushValidTy).\n        rewrite <-Heq\u03c4' in H; cbn in H; exfalso; lia.\n      * destruct v\u03c4' as (c\u03c4' & _).\n        exfalso.\n        eauto using I.closed_implies_not_var.\nQed.\n\nLemma inject_works_open {d n m \u03c4 ts tu \u0393 p} :\n  ValidTy \u03c4 ->\n  dir_world_prec n m d p \u2192\n  \u27ea \u0393 \u22a9 ts \u27e6 d , m \u27e7 tu : embed \u03c4 \u27eb \u2192\n  \u27ea \u0393 \u22a9 I.app (inject n \u03c4) ts \u27e6 d , m \u27e7 tu : pEmulDV n p \u03c4 \u27eb.\nProof.\n  intros v\u03c4 dwp lr.\n  destruct lr as (? & ? & lr).\n  unfold OpenLRCtxN; split; [|split].\n  - crushTyping.\n    rewrite repEmul_embed_leftinv.\n    eauto using injectT.\n  - cbn.\n    rewrite isToEq_embed_leftinv in H0.\n    assumption.\n  - intros w wm \u03b3s \u03b3u envrel.\n    specialize (lr w wm \u03b3s \u03b3u envrel).\n\n    cbn; crushTyping.\n    rewrite inject_sub.\n\n    eapply (termrel_ectx' lr); I.inferContext; E.inferContext;\n      crush; eauto using inject_value.\n\n    cbn.\n    eapply termrel_size_right'.\n    intros sz.\n    eapply termrelnd\u2080_termrel.\n    eapply inject_works; eauto using dwp_mono.\n    crushValidTy.\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/BacktransIE/InjectExtract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.19770094964702578}}
{"text": "From stdpp Require Import fin_maps gmap.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.prelude Require Import collect.\nFrom aneris.aneris_lang Require Import aneris_lang network resources.\nFrom aneris.aneris_lang.state_interp Require Import state_interp_def.\nFrom RecordUpdate Require Import RecordSet.\nFrom aneris.algebra Require Import disj_gsets.\nFrom iris.algebra Require Import auth.\nSet Default Proof Using \"Type\".\n\nImport uPred.\nImport RecordSetNotations.\n\nSection state_interpretation.\n  Context `{!anerisG Mdl \u03a3}.\n\n  Lemma messages_resource_coh_init B :\n    own (A:=authUR socket_address_groupUR) aneris_socket_address_group_name\n        (\u25ef (DGSets B)) -\u2217\n    messages_resource_coh (gset_to_gmap (\u2205, \u2205) B).\n  Proof.\n    rewrite /messages_resource_coh messages_sent_init.\n    iIntros \"Hown\".\n    iSplitL; [ |].\n    { by rewrite dom_gset_to_gmap. }\n    iExists _.\n    iSplit; [done|].\n    iSplit; by iApply big_sepS_empty.\n  Qed.\n\n  (* TODO: Repeated lemma - Why is anerisG needed over anerisPreG? *)\n  Lemma socket_address_group_own_subseteq\n        \u03b3 (sags sags' : gset socket_address_group) :\n    sags' \u2286 sags \u2192\n    own (A:=(authR socket_address_groupUR)) \u03b3\n        (\u25ef (DGSets sags)) -\u2217\n    own (A:=(authR socket_address_groupUR)) \u03b3\n        (\u25ef (DGSets sags')).\n  Proof.\n    iIntros (Hle) \"Hsags\".\n    apply subseteq_disjoint_union_L in Hle.\n    destruct Hle as [Z [-> Hdisj]].\n    setoid_rewrite <-disj_gsets_op_union.\n    iDestruct \"Hsags\" as \"[H1 H2]\".\n    iFrame.\n  Qed.\n\n  Lemma messages_resource_coh_socket_address_group_own\n        (sag : socket_address_group) mh :\n    sag \u2208 dom mh \u2192\n    messages_resource_coh mh -\u2217\n    messages_resource_coh mh \u2217\n    socket_address_group_own sag.\n  Proof.\n    iIntros (Hin) \"[#H Hrest]\".\n    rewrite /socket_address_group_own.\n    iPoseProof (socket_address_group_own_subseteq _ _ {[sag]} with \"H\") as \"$\";\n      [set_solver|].\n    rewrite /messages_resource_coh. iFrame \"H\".\n    done.\n  Qed.\n\n  Lemma messages_resource_coh_send mh sagT sagR R T msg msg' \u03d5 :\n    mh !! sagT = Some (R, T) \u2192\n    m_sender msg \u2208 sagT \u2192\n    messages_addresses_coh mh \u2192\n    msg \u2261g{sagT, sagR} msg' \u2192\n    m_destination msg \u2208g sagR -\u2217\n    sagR \u2907* \u03d5 -\u2217\n    messages_resource_coh mh -\u2217\n    \u03d5 msg' -\u2217\n    messages_resource_coh (<[sagT:=(R, {[msg]} \u222a T)]> mh).\n  Proof.\n    rewrite /messages_resource_coh /=.\n    iIntros (Hmh HsagT Hmcoh Hmeq) \"[%HsagR _] #H\u03a6 [#Hown Hcoh] Hm\".\n    iAssert (socket_address_group_own sagT) as \"HownT\".\n    {\n      rewrite -(insert_id mh sagT (R,T)); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    destruct Hmcoh as (Halldisj & Hne & Hmcoh).\n    iDestruct \"Hcoh\" as (ms Hle) \"[#HcohT Hcoh]\".\n    iDestruct (socket_interp_own with \"H\u03a6\") as \"#Hown'\".\n    iSplitR.\n    {\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iApply own_op.\n      iFrame \"Hown HownT\".\n    }\n    iExists ({[msg]} \u222a ms).\n    iSplitR.\n    {\n      iPureIntro.\n      rewrite messages_sent_insert.\n      rewrite -union_assoc_L.\n      rewrite -(messages_sent_split sagT R T mh Hmh).\n      set_solver.\n    }\n    iSplitR.\n    {\n      rewrite messages_sent_insert.\n      rewrite -union_assoc_L.\n      rewrite -(messages_sent_split sagT R T mh Hmh).\n      rewrite !big_sepS_forall.\n      iIntros (m' Hin).\n      setoid_rewrite elem_of_union in Hin.\n      destruct Hin as [Hin|Hin].\n      {\n        assert (m' = msg) as <- by set_solver.\n        iExists sagT, sagR, m'.\n        iSplit; [iSplit; [|iPureIntro; set_solver] |].\n        { iPureIntro. apply message_group_equiv_refl.\n          - by destruct Hmeq as (Hmin & _).\n          - done. }\n        iFrame \"HownT Hown'\".\n      }\n      iDestruct (\"HcohT\" $!(m') (Hin))\n        as (sagT' sagR' m'' [Hmeq' Hmin]) \"[HcohT' HcohT'']\".\n      iExists sagT', sagR', m''.\n      apply (elem_of_union_r m'' {[msg]} ms) in Hmin.\n      iFrame \"#\".\n      iSplit; [done|]. iPureIntro.  done.\n    }\n    destruct (decide (msg \u2208 ms)).\n    {\n      assert ({[msg]} \u222a ms = ms) as -> by set_solver. iClear \"Hm\".\n      assert (ms \u2286 {[msg]} \u222a messages_sent mh) by set_solver.\n      rewrite /message_received.\n      rewrite !messages_received_insert.\n      iApply (big_sepS_mono with \"Hcoh\").\n      iIntros (x Hin') \"Hcoh\".\n      iDestruct \"Hcoh\" as (sagT' sagR' \u03a6 Hin'') \"[#H\u03a6' [HownT' Hcoh]]\".\n      subst.\n      iExists _, _, _.\n      iFrame \"H\u03a6'\".\n      iSplit.\n      { iPureIntro. set_solver. }\n      iFrame \"HownT'\".\n      iDestruct \"Hcoh\" as \"[Hcoh | Hcoh]\".\n      { by iLeft. }\n      iRight.\n      iDestruct \"Hcoh\" as %(m' & Heq & Hrecv).\n      iExists m'. iSplit; [done|].\n      iPureIntro.\n      rewrite -(insert_id mh sagT (R,T) Hmh) in Hrecv.\n      apply message_received_insert in Hrecv.\n      set_solver.\n    }\n    rewrite big_sepS_union; [|set_solver].\n    rewrite big_sepS_singleton.\n    iSplitL \"Hm\".\n    + iExists _,_, _. iFrame \"H\u03a6\".\n      iFrame \"HownT\".\n      iSplit.\n      { iPureIntro. set_solver. }\n      iLeft. iExists _.\n      iSplitR \"Hm\"; [done | iApply \"Hm\"].\n    + iApply (big_sepS_mono with \"Hcoh\").\n      iIntros (x Hin') \"Hcoh\".\n      iDestruct \"Hcoh\" as (sagT' sagR' \u03a6 Hin'') \"[#H\u03a6' [HownT Hcoh]]\".\n      subst.\n      iExists _,_, _.\n      iFrame \"H\u03a6'\". iFrame \"HownT\".\n      iSplit.\n      { iPureIntro. set_solver. }\n      iDestruct \"Hcoh\" as \"[Hcoh | Hcoh]\".\n      { by iLeft. }\n      iRight.\n      iDestruct \"Hcoh\" as %(m' & Heq & Hrecv).\n      iExists m'. iSplit; [done|].\n      iPureIntro.\n      rewrite -(insert_id mh sagT (R,T) Hmh) in Hrecv.\n      rewrite message_received_insert.\n      by apply message_received_insert in Hrecv.\n  Qed.\n\n  Lemma messages_resource_coh_send_duplicate mh sagT sagR R T msg :\n    mh !! sagT = Some (R, T) \u2192\n    m_sender msg \u2208 sagT \u2192\n    messages_addresses_coh mh \u2192\n    set_Exists (\u03bb m, m \u2261g{sagT, sagR} msg) T \u2192\n    m_destination msg \u2208g sagR -\u2217\n    messages_resource_coh mh -\u2217\n    messages_resource_coh (<[sagT:=(R, {[msg]} \u222a T)]> mh).\n  Proof.\n    rewrite /messages_resource_coh /=.\n    iIntros (Hmh HsagT Hmcoh Hexists) \"[%HsagR #Hown'] [#Hown Hcoh]\".\n    iAssert (socket_address_group_own sagT) as \"HownT\".\n    {\n      rewrite -(insert_id mh sagT (R,T)); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    destruct Hmcoh as (Halldisj & Hne & Hmcoh).\n    iDestruct \"Hcoh\" as (ms Hle) \"[#HcohT Hcoh]\".\n    iSplitR.\n    {\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iApply own_op.\n      iFrame \"Hown HownT\".\n    }\n    iExists ms.\n    rewrite -{3}(insert_id mh sagT (R, T)); [|set_solver].\n    rewrite /message_received.\n    rewrite !messages_received_insert.\n    iFrame.\n    iSplitR.\n    {\n      iPureIntro.\n      rewrite messages_sent_insert.\n      rewrite -union_assoc_L.\n      rewrite -(messages_sent_split sagT R T mh Hmh); set_solver.\n    }\n    rewrite messages_sent_insert.\n    rewrite -union_assoc_L.\n    rewrite -(messages_sent_split sagT R T mh Hmh).\n    destruct (decide (msg \u2208 messages_sent mh)) as [Hin|Hnin].\n    { assert ({[msg]} \u222a messages_sent mh = messages_sent mh) as Heq by set_solver.\n      rewrite Heq. done. }\n    rewrite big_sepS_union; [|set_solver].\n    iFrame \"HcohT\".\n    rewrite big_sepS_singleton.\n    destruct Hexists as [m' [Hin Hmeq]].\n    assert (m_destination m' \u2208 sagR).\n    { by destruct Hmeq as (_ & _ & H' & _). }\n    rewrite -{2}(insert_id mh sagT (R,T)); [|set_solver].\n    rewrite messages_sent_insert.\n    iDestruct (big_sepS_elem_of_acc _ _ m' with \"HcohT\") as \"[Hmsg _]\";\n      [set_solver|].\n    iDestruct \"Hmsg\" as (sagT' sagR' m'' [Hmeq' Hmin]) \"[HownT' HownR']\".\n    iExists sagT', sagR', m''. iFrame \"HownT' HownR'\". iSplit;[|done].\n    iAssert (socket_address_groups_own\n               ({[sagT]} \u222a {[sagR]} \u222a {[sagT']} \u222a {[sagR']})) as \"H\".\n    {\n      iApply socket_address_groups_own_union. iFrame \"HownR'\".\n      iApply socket_address_groups_own_union. iFrame \"HownT'\".\n      iApply socket_address_groups_own_union. iFrame \"Hown' HownT\".\n    }\n    iDestruct (own_valid with \"H\") as %Hvalid.\n    setoid_rewrite auth_frag_valid in Hvalid.\n    setoid_rewrite disj_gsets_valid in Hvalid.\n    iPureIntro.\n    pose proof (message_group_equiv_trans _ sagT sagT' sagR sagR' msg m' m'' Hvalid) as (<- & <- & Hmeq'');\n      [set_solver..| | | ].\n    - apply message_group_equiv_symmetry; try done.\n      by destruct Hmeq as (H' & _).\n    - apply Hmeq'.\n    - done.\n  Qed.\n\n  Lemma message_received_delete m mh sag1 sag2 :\n    messages_addresses_coh mh \u2192\n    m_destination m \u2208 sag1 \u2192\n    sag1 \u2208 dom mh \u2192\n    sag2 \u2208 dom mh \u2192\n    sag1 \u2260 sag2 \u2192\n    message_received m mh \u2192\n    message_received m (delete sag2 mh).\n  Proof.\n    rewrite /message_received.\n    rewrite !elem_of_messages_received.\n    intros (Hdisj & Hne & Hcoh) Hdest Hsag1 Hsag2 Hrecv\n           [sag [[R T] [Hlookup Hin]]].\n    assert (sag = sag1) as ->.\n    {\n      eapply elem_of_all_disjoint_eq; eauto.\n      apply elem_of_dom. eexists _. set_solver.\n      eapply Hcoh. eauto. eauto.\n    }\n    eexists sag1, (R,T).\n    rewrite lookup_delete_ne; last done.\n    auto.\n  Qed.\n\n  (* TODO: Clean up these lemmas and proofs *)\n  Lemma messages_resource_coh_receive_in sagR sagT R T R' T' m mh :\n    mh !! sagR = Some (R, T) \u2192\n    mh !! sagT = Some (R',T') \u2192\n    set_Forall (\u03bb m', \u00ac (m \u2261g{sagT,sagR} m')) R \u2192\n    m \u2208 T' \u2192\n    messages_addresses_coh mh \u2192\n    m_destination m \u2208g sagR -\u2217\n    m_sender m \u2208g sagT -\u2217\n    messages_resource_coh mh -\u2217\n    messages_resource_coh (<[sagR:=({[m]} \u222a R, T)]> mh) \u2217\n    \u2203 \u03c6 m', \u231cm \u2261g{sagT,sagR} m'\u231d \u2217 sagR \u2907* \u03c6 \u2217 \u25b7 \u03c6 m'.\n  Proof.\n    iIntros (Hmha Hmhb HmR HmT' (Hdisj & Hne & Hmacoh)).\n    iIntros \"[%Hmdest _] [%Hmsend _]\". \n    iDestruct 1 as \"[#Hown Hrcoh]\". rewrite /messages_resource_coh.\n    iDestruct \"Hrcoh\" as (ms Hle) \"[#HrcohT Hrcoh]\".\n    iAssert (\u231c\u2203 m', m \u2261g{sagT,sagR} m' \u2227 m' \u2208 ms\u231d%I) as %(m' & Hmeq & Hmin).\n    {\n      assert (messages_sent mh = messages_sent (<[sagT:=(R', T')]>mh)) as Heq.\n      { apply insert_id in Hmhb as Heq. by rewrite {1} Heq. }\n      rewrite Heq messages_sent_insert.\n      assert (T' = {[m]} \u222a T') as HTeq by set_solver.\n      rewrite HTeq.\n      iDestruct (big_sepS_elem_of_acc _ _ m with \"HrcohT\")\n        as \"[Hm _]\"; [set_solver|].\n      iDestruct \"Hm\" as (sagT' sagR' m' [Hmeq Hmin]) \"[HownT' HownR']\".\n      assert (sagR \u2208 dom mh).\n      { apply elem_of_dom. eexists _. set_solver. }\n\n      iAssert (socket_address_group_own sagT) as \"HownT\".\n      {\n        rewrite -(insert_id mh sagT (R',T')); [|set_solver].\n        rewrite dom_insert_L.\n        rewrite -disj_gsets_op_union.\n        rewrite auth_frag_op.\n        iDestruct \"Hown\" as \"[$ Hown]\".\n      }\n      iAssert (socket_address_group_own sagR) as \"HownR\".\n      {\n        rewrite -(insert_id mh sagR (R,T)); [|set_solver].\n        rewrite dom_insert_L.\n        rewrite -disj_gsets_op_union.\n        rewrite auth_frag_op.\n        iDestruct \"Hown\" as \"[$ Hown]\".\n      }\n      iAssert (socket_address_groups_own\n                 ({[sagT]} \u222a {[sagR]} \u222a {[sagT']} \u222a {[sagR']})) as \"Hown'\".\n      {\n        iApply socket_address_groups_own_union. iFrame \"HownR'\".\n        iApply socket_address_groups_own_union. iFrame \"HownT'\".\n        iApply socket_address_groups_own_union. iFrame \"HownR HownT\".\n      }\n      iDestruct (own_valid with \"Hown'\") as %Hvalid.\n      setoid_rewrite auth_frag_valid in Hvalid.\n      setoid_rewrite disj_gsets_valid in Hvalid.\n      assert (sagT = sagT') as <-.\n      { eapply (message_group_equiv_dest_eq _\n                  sagT sagT' sagR sagR' m m' Hvalid); try set_solver. }\n      assert (sagR = sagR') as <-.\n      { eapply (message_group_equiv_dest_eq _\n                  sagT sagT sagR sagR' m m' Hvalid); try set_solver. }\n      iPureIntro.\n      eexists m'.\n      done.\n    }\n    assert (ms = {[m']} \u222a (ms \u2216 {[m']})) as Hms.\n    { rewrite -union_difference_L. eauto. set_solver. }\n    rewrite Hms.\n    rewrite big_sepS_union; [|set_solver]. rewrite big_sepS_singleton.\n    iDestruct \"Hrcoh\" as \"[Hm' Hrcoh]\".\n    iDestruct \"Hm'\" as (sagT' sagR' \u03a6 Hdest) \"[#H\u03a6 [#HownT' Hm]]\".\n    assert (sagR \u2208 dom mh) as HsagR.\n    { rewrite elem_of_dom. eexists _. set_solver. }\n    iDestruct \"Hm\" as \"[Hm | Hm]\"; last first.\n    {\n      iDestruct \"Hm\" as %(m'' & Hmeq' & Hrecv).\n      iAssert (socket_address_group_own sagT) as \"HownT\".\n      {\n        rewrite -(insert_id mh sagT (R',T')); [|set_solver].\n        rewrite dom_insert_L.\n        rewrite -disj_gsets_op_union.\n        rewrite auth_frag_op.\n        iDestruct \"Hown\" as \"[$ Hown]\".\n      }\n      iAssert (socket_address_group_own sagR) as \"HownR\".\n      {\n        rewrite -(insert_id mh sagR (R,T)); [|set_solver].\n        rewrite dom_insert_L.\n        rewrite -disj_gsets_op_union.\n        rewrite auth_frag_op.\n        iDestruct \"Hown\" as \"[$ Hown]\".\n      }\n      iDestruct (socket_interp_own with \"H\u03a6\") as \"HownR'\".\n      iAssert (socket_address_groups_own\n                 ({[sagT]} \u222a {[sagT']} \u222a {[sagR]} \u222a {[sagR']})) as \"Hown'\".\n      {\n        iApply socket_address_groups_own_union. iFrame \"HownR'\".\n        iApply socket_address_groups_own_union. iFrame \"HownR\".\n        iApply socket_address_groups_own_union. iFrame \"HownT' HownT\".\n      }\n      iDestruct (own_valid with \"Hown'\") as %Hvalid.\n      setoid_rewrite auth_frag_valid in Hvalid.\n      setoid_rewrite disj_gsets_valid in Hvalid.\n      assert (m \u2261g{sagT, sagR} m'') as Hmeq''.\n      {  eapply (message_group_equiv_trans _ sagT sagT' sagR sagR' m m' m''); eauto.\n         set_solver. set_solver. set_solver. set_solver. }\n      assert (m_destination m'' \u2208 sagR).\n      { by eapply message_group_equiv_dest. }\n      assert (m'' \u2208 R).\n      { eapply messages_received_in; eauto.\n        by rewrite /messages_addresses_coh. }\n      assert (\u00ac m \u2261g{sagT,sagR} m'').\n      { by apply HmR. }\n      done.\n    }\n    iDestruct \"Hm\" as (m'' Hmeq') \"Hm'\".\n    iAssert (socket_address_group_own sagT) as \"HownT\".\n    {\n      rewrite -(insert_id mh sagT (R',T')); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    iAssert (socket_address_group_own sagR) as \"HownR\".\n    {\n      rewrite -(insert_id mh sagR (R,T)); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    iDestruct (socket_interp_own with \"H\u03a6\") as \"HownR'\".\n    iAssert (socket_address_groups_own\n               ({[sagT]} \u222a {[sagR]} \u222a {[sagT']} \u222a {[sagR']})) as \"Hown'''\".\n    {\n      iApply socket_address_groups_own_union. iFrame \"HownR'\".\n      iApply socket_address_groups_own_union. iFrame \"HownT'\".\n      iApply socket_address_groups_own_union. iFrame \"HownT HownR\".\n    }\n    iDestruct (own_valid with \"Hown'''\") as %Hvalid.\n    setoid_rewrite auth_frag_valid in Hvalid.\n    setoid_rewrite disj_gsets_valid in Hvalid.\n    assert (sagR' = sagR) as ->.\n    {\n      symmetry.\n      eapply (message_group_equiv_trans _ sagT sagT' sagR sagR' m m' m'' Hvalid);\n        set_solver. }\n    iSplitR \"Hm'\"; last first.\n    {\n      iExists \u03a6, m''. iFrame \"H\u03a6 Hm'\". iPureIntro.\n      eapply message_group_equiv_trans; eauto.\n      set_solver. set_solver. set_solver. set_solver.\n    }\n    iSplitR.\n    {\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite !auth_frag_op. iSplit.\n      iApply \"HownR\".\n      iFrame \"Hown\".\n    }\n    iExists ms.\n    iSplitR.\n    {\n      iPureIntro.\n      rewrite -(insert_id mh sagR (R,T) Hmha) in Hle.\n      rewrite messages_sent_insert.\n      rewrite messages_sent_insert in Hle.\n      done.\n    }\n    iSplitR.\n    {\n      rewrite -{2}(insert_id mh sagR (R,T) Hmha).\n      rewrite !messages_sent_insert.\n      rewrite -Hms.\n      iApply \"HrcohT\".\n    }\n    rewrite {3} Hms.\n    rewrite big_sepS_union; last set_solver.\n    rewrite big_sepS_singleton.\n    iSplitR.\n    { iExists sagT, sagR, \u03a6.\n      iSplit; [iPureIntro; set_solver | ].\n      iFrame \"H\u03a6\".\n      iFrame \"HownT\".\n      iRight.\n      iExists m.\n      iPureIntro.\n      split; [by apply message_group_equiv_symmetry | ].\n      rewrite message_received_insert.\n      set_solver.\n    }\n    iApply (big_sepS_impl with \"Hrcoh\").\n    iIntros \"!>\" (m''' Hmin') \"Hrcoh\".\n    iDestruct \"Hrcoh\" as (sagT'' sagR' \u03a6' Hmin'') \"[#H\u03a6' [#HownT'' H]]\".\n    iExists sagT'', sagR', \u03a6'.\n    iFrame \"#\".\n    iSplit; [done|].\n    iDestruct \"H\" as \"[H|H]\"; [ by iFrame | iRight ].\n    iDestruct \"H\" as %(m'''' & Hmeq''' & Hrecv).\n    assert (m_destination m'''' \u2208 sagR').\n    { eapply message_group_equiv_dest; eauto. }\n    pose proof Hrecv as Hrecv'.\n    rewrite /message_received in Hrecv'.\n    setoid_rewrite elem_of_messages_received in Hrecv'.\n    destruct Hrecv' as (sag & [R'' T''] & Hlookup & Hin).\n    simpl in *.\n    iAssert (socket_address_group_own sag) as \"Hown''''\".\n    {\n      rewrite -(insert_id mh sag (R'',T'')); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    iDestruct (socket_interp_own with \"H\u03a6'\") as \"Hown'''''\".\n    iDestruct (own_op with \"[Hown'''' Hown''''']\") as \"Hown''''''\".\n    { iSplit; [ iApply \"Hown''''\" | iApply \"Hown'''''\" ]. }\n    rewrite -auth_frag_op.\n    iDestruct (own_valid with \"Hown''''''\") as %Hvalid'.\n    setoid_rewrite auth_frag_valid in Hvalid'.\n    setoid_rewrite disj_gsets_valid in Hvalid'.\n    iPureIntro. exists m''''.\n    split; [done|].\n    rewrite message_received_insert.\n    destruct (decide (sagR' = sagR)) as [->|Hneq]; [left|right].\n    { apply elem_of_union_r. by eapply messages_received_in. }\n    rewrite /message_received.\n    rewrite !elem_of_messages_received.\n    assert (sag = sagR') as ->.\n    {\n      eapply (elem_of_all_disjoint_eq sag sagR' (m_destination m'''')); eauto.\n      set_solver. set_solver.\n      eapply Hmacoh. eauto. eauto.\n    }\n    eexists _, _.\n    rewrite lookup_delete_ne; last done.\n    split; [done|done].\n  Qed.\n\n  Lemma messages_resource_coh_receive_nin sagR sagT R T R' T' m mh :\n    mh !! sagR = Some (R, T) \u2192\n    mh !! sagT = Some (R',T') \u2192\n    m \u2208 T' \u2192\n    messages_addresses_coh mh \u2192\n    m_destination m \u2208g sagR -\u2217\n    m_sender m \u2208g sagT -\u2217\n    messages_resource_coh mh -\u2217\n    messages_resource_coh (<[sagR:=({[m]} \u222a R, T)]> mh).\n  Proof.\n    iIntros (Hmha Hmhb HmT' (Hdisj & Hne & Hmacoh)).\n    iIntros \"[%Hmdest _] [%Hmsend _] Hrcoh\".\n    iDestruct \"Hrcoh\" as \"[#Hown Hrcoh]\".\n    iDestruct \"Hrcoh\" as (ms Hle) \"[HrcohT Hrcoh]\".\n    rewrite /messages_resource_coh.\n    rewrite dom_insert_L.\n    iAssert (socket_address_group_own sagR) as \"HownR\".\n    {\n      rewrite -(insert_id mh sagR (R,T)); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    iSplitR.\n    {\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iSplit. iApply \"HownR\". iApply \"Hown\".\n    }\n    iExists ms.\n    iSplit.\n    { rewrite messages_sent_insert.\n      rewrite <- (insert_id _ sagR (R,T)) in Hle; auto.\n      rewrite messages_sent_insert in Hle.\n      iPureIntro.\n      set_solver. }\n    iSplitR \"Hrcoh\".\n    {\n      rewrite messages_sent_insert.\n      rewrite -(messages_sent_split sagR R T mh Hmha).\n      done.\n    }\n    iApply (big_sepS_impl with \"Hrcoh\").\n    iIntros \"!>\" (m'' Hmin') \"H\".\n    iDestruct \"H\" as (sagT' sagR' \u03a6 Hdest) \"(#Hsag' & HsagT & [H | H])\".\n    {\n      iDestruct \"H\" as (m''' Hmeq') \"H\u03a6\".\n      iExists sagT', sagR', \u03a6.\n      iSplit; [done|].\n      iSplit; [done|].\n      iSplit; [done|].\n      iLeft. eauto.\n    }\n    iDestruct \"H\" as %(m''' & Hmeq' & Hrecv).\n    iExists sagT', sagR', \u03a6.\n    iSplit; [done|].\n    iSplit; [done|].\n    iSplit; [done|].\n    iRight.\n    assert (m_destination m''' \u2208 sagR').\n    { eapply message_group_equiv_dest; eauto. }\n    pose proof Hrecv as Hrecv'.\n    rewrite /message_received in Hrecv'.\n    setoid_rewrite elem_of_messages_received in Hrecv'.\n    destruct Hrecv' as (sag & [R'' T''] & Hlookup & Hin).\n    simpl in *.\n    iAssert (socket_address_group_own sag) as \"Hown'\".\n    {\n      rewrite -(insert_id mh sag (R'',T'')); [|set_solver].\n      rewrite dom_insert_L.\n      rewrite -disj_gsets_op_union.\n      rewrite auth_frag_op.\n      iDestruct \"Hown\" as \"[$ Hown]\".\n    }\n    iDestruct (socket_interp_own with \"Hsag'\") as \"Hown''\".\n    iDestruct (own_op with \"[Hown' Hown'']\") as \"Hown'''\".\n    { iSplit; [ iApply \"Hown'\" | iApply \"Hown''\" ]. }\n    rewrite -auth_frag_op.\n    iDestruct (own_valid with \"Hown'''\") as %Hvalid'.\n    setoid_rewrite auth_frag_valid in Hvalid'.\n    setoid_rewrite disj_gsets_valid in Hvalid'.\n    iPureIntro. exists m'''.\n    split; [done|].\n    rewrite message_received_insert.\n    destruct (decide (sagR' = sagR)) as [->|Hneq]; [left|right].\n    { apply elem_of_union_r. by eapply messages_received_in. }\n    assert (sag = sagR') as ->.\n    {\n      eapply (elem_of_all_disjoint_eq sag sagR' (m_destination m''')); eauto.\n      set_solver. set_solver.\n      eapply Hmacoh. eauto. eauto.\n    }\n    rewrite /message_received.\n    rewrite !elem_of_messages_received.\n    eexists _, _.\n    rewrite lookup_delete_ne; last done.\n    split; [done|done].\n  Qed.\n\n  Lemma messages_resource_coh_receive sagR sagT R T R' T' m mh :\n    mh !! sagR = Some (R, T) \u2192\n    mh !! sagT = Some (R',T') \u2192\n    m \u2208 T' \u2192\n    messages_addresses_coh mh \u2192\n    m_destination m \u2208g sagR -\u2217\n    m_sender m \u2208g sagT -\u2217\n    messages_resource_coh mh -\u2217\n    messages_resource_coh (<[sagR:=({[m]} \u222a R, T)]> mh) \u2217\n    (\u231cset_Forall (\u03bb m', \u00ac (m \u2261g{sagT,sagR} m')) R\u231d -\u2217\n     \u2203 \u03c6 m', \u231cm \u2261g{sagT,sagR} m'\u231d \u2217 sagR \u2907* \u03c6 \u2217 \u25b7 \u03c6 m').\n  Proof.\n    iIntros (Hmha Hmhb HmT' Hcoh).\n    iIntros \"HsagR HsagT Hcoh\".\n    destruct (decide (set_Forall (\u03bb m', \u00ac (m \u2261g{sagT,sagR} m')) R)).\n    - iDestruct (messages_resource_coh_receive_in with \"HsagR HsagT Hcoh\")\n        as \"[Hcoh H\u03c6]\"; [ by eauto.. |].\n      by iFrame.\n    - iDestruct (messages_resource_coh_receive_nin with \"HsagR HsagT Hcoh\")\n        as \"[Hcoh H\u03c6]\"; [ by eauto.. |].\n      iFrame. by iIntros (H).\n  Qed.\n\nEnd state_interpretation.\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/state_interp/state_interp_messages_resource_coh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19761246859997844}}
{"text": "(* Standard library imports *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.omega.Omega.\nImport ListNotations.\n(* Project related imports *)\nRequire Import LiftMatch.\nRequire Import DtorizeI.\nRequire Import DtorizeII.\nRequire Import DtorizeIII.\nRequire Import BodyTypeDefs.\nRequire Import ProgramDef.\nRequire Import Typechecker.\nRequire Import UtilsTypechecker.\nRequire Import AST.\nRequire Import Names.\nRequire Import GenericLemmas.\nRequire Import OptionMonad.\nRequire Import Skeleton.\nRequire Import UtilsSkeleton.\nRequire Import Subterm.\nRequire Import SwitchIndices.\n\n(**************************************************************************************************)\n(** * Constructorization Part IV:                                                                *)\n(**                                                                                               *)\n(** Chains match lifting and (core) destructorization                                           *)\n(**************************************************************************************************)\n\n(* Bridges the two definitions as used in LiftMatch and DtorizeIV *)\nLemma no_matches_bridge : forall tn e,\n  contains_no_matches tn e -> no_matches tn e.\nProof with try discriminate; eauto.\nintros. unfold no_matches. intros. unfold contains_no_matches in H.\ninduction e using expr_strong_ind.\n- inversion H0; subst... inversion H2.\n- rewrite Forall_forall in H1. inversion H0; subst... inversion H3; subst.\n  apply H1 with (x:=e2)... clear - H H6. cbn in H. generalize dependent ls.\n  induction ls; intros; [inversion H6|]. cbn in H. rewrite filter_app in H.\n  destruct H6; subst.\n  + match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H0 in H...\n  + apply IHls... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H1 in H. exfalso. symmetry in H. apply app_cons_not_nil in H...\n- rewrite Forall_forall in H1. inversion H0; subst... inversion H3; subst.\n  + apply IHe... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    cbn in H. rewrite filter_app in H. unfold QName in *. rewrite H4 in H...\n  + apply H1 with (x:=e2)... clear - H H6. cbn in H. generalize dependent ls.\n    induction ls; intros; [inversion H6|]. cbn in H. rewrite filter_app in H.\n    destruct H6; subst.\n    * match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n      unfold QName in *. rewrite filter_app in H. rewrite H0 in H.\n      exfalso. symmetry in H. apply app_cons_not_nil in H...\n    * apply IHls... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n      unfold QName in *. rewrite filter_app in H.\n      case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n        (collect_match_names a)); intros.\n      -- rewrite H2 in H. simpl in H. rewrite <- filter_app in H. rewrite H1 in H...\n      -- rewrite H2 in H. exfalso. symmetry in H. rewrite <- app_comm_cons in H.\n         apply app_cons_not_nil in H...\n- rewrite Forall_forall in H1. inversion H0; subst... inversion H3; subst.\n  apply H1 with (x:=e2)... clear - H H6. cbn in H. generalize dependent ls.\n  induction ls; intros; [inversion H6|]. cbn in H. rewrite filter_app in H.\n  destruct H6; subst.\n  + match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H0 in H...\n  + apply IHls... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H1 in H. exfalso. symmetry in H. apply app_cons_not_nil in H...\n- rewrite Forall_forall in H1. inversion H0; subst... inversion H3; subst.\n  + apply IHe... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    cbn in H. rewrite filter_app in H. unfold QName in *. rewrite H4 in H...\n  + apply H1 with (x:=e2)... clear - H H6. cbn in H. generalize dependent ls.\n    induction ls; intros; [inversion H6|]. cbn in H. rewrite filter_app in H.\n    destruct H6; subst.\n    * match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n      unfold QName in *. rewrite filter_app in H. rewrite H0 in H.\n      exfalso. symmetry in H. apply app_cons_not_nil in H...\n    * apply IHls... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n      unfold QName in *. rewrite filter_app in H.\n      case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n        (collect_match_names a)); intros.\n      -- rewrite H2 in H. simpl in H. rewrite <- filter_app in H. rewrite H1 in H...\n      -- rewrite H2 in H. exfalso. symmetry in H. rewrite <- app_comm_cons in H.\n         apply app_cons_not_nil in H...\n- rewrite Forall_forall in H1. inversion H0; subst... inversion H3; subst.\n  apply H1 with (x:=e2)... clear - H H6. cbn in H. generalize dependent ls.\n  induction ls; intros; [inversion H6|]. cbn in H. rewrite filter_app in H.\n  destruct H6; subst.\n  + match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H0 in H...\n  + apply IHls... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n    unfold QName in *. rewrite H1 in H. exfalso. symmetry in H. apply app_cons_not_nil in H...\n- rewrite Forall_forall in H1. rewrite Forall_forall in H2.\n  inversion H0; subst.\n  + clear - H. cbn in H. case_eq (eq_TypeName tn (fst n0)); intros; rewrite H0 in H...\n    destruct n0. simpl in *. unfold not. intros. inversion H1; subst. rewrite eq_TypeName_refl in H0...\n  + inversion H4; subst.\n    * apply IHe... match goal with [|- ?lhs = _] => case_eq lhs; intros end...\n      cbn in H. rewrite filter_app in H. destruct (eq_TypeName tn (fst n0))...\n      unfold QName in *. rewrite H5 in H...\n    * eapply H2... cbn in H. case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n        (collect_match_names e2)); intros... apply in_split in H7. destruct H7. destruct H6.\n      rewrite <- map_map in H. rewrite H6 in H. rewrite map_app in H. cbn in H.\n      repeat (rewrite concat_app in H). cbn in H. repeat (rewrite filter_app in H).\n      unfold QName in *. rewrite H5 in H. rewrite <- app_assoc in H.\n      destruct (eq_TypeName tn (fst n0))...\n      match goal with [_ : ?a ++ ?b ++  (_ ++ ?c) ++ ?d = _ |- _] =>\n        case_eq a; [intros aEq | intros a0 a' aEq]; rewrite aEq in H; try discriminate;\n        case_eq b; [intros bEq | intros b0 b' bEq]; rewrite bEq in H; try discriminate\n      end.\n    * eapply H1... cbn in H. case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n        (collect_match_names e2)); intros... apply in_split in H7. destruct H7. destruct H6.\n      rewrite <- map_map with (f:=snd) in H. rewrite H6 in H. rewrite map_app in H. cbn in H.\n      repeat (rewrite concat_app in H). cbn in H. repeat (rewrite filter_app in H).\n      unfold QName in *. rewrite H5 in H. destruct (eq_TypeName tn (fst n0))...\n      rewrite <- app_comm_cons in H.\n      match goal with [_ : ?a ++ ?b ++ ?c ++ _ :: _ = _ |- _] =>\n        case_eq a; [intros aEq | intros a0 a' aEq]; rewrite aEq in H; try discriminate;\n        case_eq b; [intros bEq | intros b0 b' bEq]; rewrite bEq in H; try discriminate;\n        case_eq c; [intros cEq | intros c0 c' cEq]; rewrite cEq in H; try discriminate\n      end.\n- rewrite Forall_forall in H1. rewrite Forall_forall in H2.\n  inversion H0; subst... inversion H4; subst.\n  + eapply H2... cbn in H. case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n     (collect_match_names e2)); intros... apply in_split in H7. destruct H7. destruct H6.\n    rewrite <- map_map in H. rewrite H6 in H. rewrite map_app in H. cbn in H.\n    repeat (rewrite concat_app in H). cbn in H. repeat (rewrite filter_app in H).\n    unfold QName in *. rewrite H5 in H. rewrite <- app_assoc in H.\n    match goal with [_ : ?a ++  (_ ++ _) ++ _ = _ |- _] =>\n      case_eq a; [intros aEq | intros a0 a' aEq]; rewrite aEq in H; try discriminate\n    end.\n  + eapply H1... cbn in H. case_eq (filter (fun x : TypeName * Name => eq_TypeName tn (fst x))\n      (collect_match_names e2)); intros... apply in_split in H7. destruct H7. destruct H6.\n    rewrite <- map_map with (f:=snd) in H. rewrite H6 in H. rewrite map_app in H. cbn in H.\n    repeat (rewrite concat_app in H). cbn in H. repeat (rewrite filter_app in H).\n    unfold QName in *. rewrite H5 in H.\n    rewrite <- app_comm_cons in H.\n    match goal with [_ : ?a ++ ?b ++ _ :: _ = _ |- _] =>\n      case_eq a; [intros aEq | intros a0 a' aEq]; rewrite aEq in H; try discriminate;\n      case_eq b; [intros bEq | intros b0 b' bEq]; rewrite bEq in H; try discriminate\n    end.\n- inversion H0; subst... inversion H2; subst.\n  + apply IHe1... cbn in H. rewrite filter_app in H. apply app_eq_nil in H. destruct H...\n  + apply IHe2... cbn in H. rewrite filter_app in H. apply app_eq_nil in H. destruct H...\nQed.\n\nLemma funs_no_matches : forall p tn\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\nForall (no_matches tn) (map snd (program_fun_bods (lift_match_to_program p tn))).\nProof with eauto.\nintros. rewrite Forall_forall. intros. apply no_matches_bridge.\nunfold lift_match_to_program in H.\ndestruct (Nat.eq_dec (length (skeleton_cfun_sigs_l (program_skeleton p))) 0).\n- destruct (Nat.eq_dec  (length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n    (new_cfun_sigs_names_unique p tn e)))) 0).\n  + simpl in *. rewrite in_map_iff in H. do 2 destruct H. destruct x0. simpl in *. subst.\n    rewrite in_map_iff in H0. destruct H0. destruct H. inversion H; subst.\n    apply replace_matches_by_cfun_calls_removes_all_matches.\n  + exfalso. apply n. apply eq.\n- exfalso. apply n. apply eq2.\nQed.\n\nLemma cg_funs_no_matches : forall p tn bods\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\n((bods = program_cfun_bods_g \\/ bods = program_cfun_bods_l) \\/\n (bods = program_gfun_bods_g \\/ bods = program_gfun_bods_l)) ->\nForall (no_matches tn) (map snd (flat_map snd (bods (lift_match_to_program p tn)))).\nProof with eauto.\nintros p tn bods eq2 eq Choice. rewrite Forall_forall. intros. apply no_matches_bridge.\nunfold lift_match_to_program in H.\ndestruct (Nat.eq_dec (length (skeleton_cfun_sigs_l (program_skeleton p))) 0).\n- destruct (Nat.eq_dec  (length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n    (new_cfun_sigs_names_unique p tn e)))) 0).\n  + simpl in *. rewrite in_map_iff in H. do 2 destruct H.\n    rewrite in_flat_map in H0. do 2 destruct H0.\n    destruct Choice as [Choice | Choice]; destruct Choice; subst;\n      simpl in H0; [ | shelve | | exfalso]; eauto;\n    rewrite in_map_iff in H0; destruct H0; destruct H; inversion H; subst; simpl in *;\n    rewrite in_map_iff in H1; destruct H1; destruct H; destruct x0; inversion H; subst;\n    apply replace_matches_by_cfun_calls_removes_all_matches.\n    Unshelve. unfold LiftMatch.new_cfun_bods_l in H0.\n    pose proof generate_cfuns_from_expr_contains_no_matches.\n    apply in_app_or in H0. destruct H0; [| apply in_app_or in H0; destruct H0];\n      rewrite in_map_iff in H0; do 2 destruct H0; subst;\n      rewrite in_flat_map in H2; destruct H2; destruct H0;\n      specialize H with (e:=x1)(tn:=tn); rewrite Forall_forall in H;\n      apply H in H2; rewrite Forall_forall in H2; apply H2...\n  + exfalso. apply n. apply eq.\n- exfalso. apply n. apply eq2.\nQed.\n\nCorollary cfuns_g_no_matches : forall p tn\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\nForall (no_matches tn) (map snd (flat_map snd (program_cfun_bods_g (lift_match_to_program p tn)))).\nProof with eauto. intros. eapply cg_funs_no_matches... Qed.\n\nCorollary cfuns_l_no_matches : forall p tn\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\nForall (no_matches tn) (map snd (flat_map snd (program_cfun_bods_l (lift_match_to_program p tn)))).\nProof with eauto. intros. eapply cg_funs_no_matches... Qed.\n\nCorollary gfuns_g_no_matches : forall p tn\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\nForall (no_matches tn) (map snd (flat_map snd (program_gfun_bods_g (lift_match_to_program p tn)))).\nProof with eauto. intros. eapply cg_funs_no_matches... Qed.\n\nCorollary gfuns_l_no_matches : forall p tn\n(eq2 : length (skeleton_cfun_sigs_l (program_skeleton p)) = O)\n(eq : length (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn\n        (new_cfun_sigs_names_unique p tn eq2))) = O),\nForall (no_matches tn) (map snd (flat_map snd (program_gfun_bods_l (lift_match_to_program p tn)))).\nProof with eauto. intros. eapply cg_funs_no_matches... Qed.\n\nLemma no_local_gfuns_after_lift : forall p tn Uniq,\nlength (skeleton_gfun_sigs_l (program_skeleton p)) = O ->\nlength (skeleton_gfun_sigs_l (lift_match_to_skeleton p tn Uniq)) = O.\nProof with eauto. intros. unfold lift_match_to_skeleton... Qed.\n\n\n(* Note this assumes that the input program contains no functions annotated as local.\n   (If there are local consumer or generator functions, this just returns the original program.)\n *)\nDefinition destructorize_program_with_lift (p : program) (tn : TypeName) :=\nmatch Nat.eq_dec (length (skeleton_cfun_sigs_l (program_skeleton p))) O with\n| left eq2 =>\nlet Uniq := new_cfun_sigs_names_unique p tn eq2 in\nmatch Nat.eq_dec (length (skeleton_gfun_sigs_l (program_skeleton p))) O with\n| left eq =>\nlet lifted_prog := lift_match_to_program p tn in\nlet no_local_gfuns := no_local_gfuns_after_lift p tn Uniq eq in\nlet NoMFun := funs_no_matches p tn eq2 eq in\nlet NoMCFunG := cfuns_g_no_matches p tn eq2 eq in\nlet NoMCFunL := cfuns_l_no_matches p tn eq2 eq in\nlet NoMGFunG := gfuns_g_no_matches p tn eq2 eq in\nlet NoMGFunL := gfuns_l_no_matches p tn eq2 eq in\ndestructorize_program lifted_prog tn NoMFun NoMCFunG NoMCFunL NoMGFunG NoMGFunL\n| _ => p\nend\n| _ => p\nend.\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/DtorizeIV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19761246859997844}}
{"text": "Require Import\n        Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.IndexSearchTerms\n        Fiat.QueryStructure.Automation.IndexSelection\n        Fiat.QueryStructure.Automation.Common\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.CountingListBags\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsOfTuples.\n\n(* Instances for building indexes with make simple indexes. *)\n(* Every Kind of index is keyed on an inductive type with a single constructor*)\nDefinition FindPrefixIndex : string := \"FindPrefixIndex\".\n\nLtac BuildLastFindPrefixIndex\n     heading indices kind index k k_fail :=\n  let is_equality := eval compute in (string_dec kind FindPrefixIndex) in\n      match is_equality with\n      | left _ => k\n                    (fun (search_term : prod (option (Domain heading index)) (@RawTuple heading -> bool))\n                         (tup : @RawTuple heading)=>\n                       andb match fst search_term with\n                            | Some indexSearchTerm =>\n                              if IsPrefix_dec (GetAttributeRaw tup index) indexSearchTerm then\n                                true\n                              else false\n                            | None => true\n                            end (snd search_term tup))\n      | right _ => k_fail heading indices kind index k\n      end.\n\nLtac BuildEarlyFindPrefixIndex\n     heading indices kind index matcher k k_fail :=\n  let is_equality := eval compute in (string_dec kind FindPrefixIndex) in\n      match is_equality with\n      | left _ => k\n                    (fun (search_term : prod (option (Domain heading index)) _)\n                         (tup : @RawTuple heading)=>\n                       andb match fst search_term with\n                            | Some indexSearchTerm =>\n                              if IsPrefix_dec (GetAttributeRaw tup index) indexSearchTerm then\n                                true\n                              else false\n                            | None => true\n                            end (matcher (snd search_term) tup))\n      | right _ => k_fail heading indices kind index matcher k\n      end.\n\n\nInstance ExpressionAttributeCounterIsPrefixL {A }\n         {qsSchema : RawQueryStructureSchema}\n         {a a' : list A}\n         (RidxL : Fin.t _)\n         (BAidxL : @Attributes (Vector.nth _ RidxL))\n         (ExpCountL : @TermAttributeCounter _ qsSchema a RidxL BAidxL)\n  : @ExpressionAttributeCounter _ qsSchema (IsPrefix a a')\n                                (@InsertOccurenceOfAny _ _ RidxL (\"FindPrefixIndex\", BAidxL)\n                                                       (InitOccurences _)) | 0 := { }.\n\nLtac IsPrefixExpressionAttributeCounter k :=\n  psearch_combine\n    ltac:(eapply @ExpressionAttributeCounterIsPrefixL; intros) k.\n\nLtac PrefixIndexUse SC F indexed_attrs f k k_fail :=\n  match type of f with\n  (* FindPrefix Search Terms *)\n  | forall a, {IsPrefix (GetAttributeRaw _ ?fd) ?X} + {_} =>\n    let H := fresh in\n    assert (List.In (@Build_KindIndex SC FindPrefixIndex fd) indexed_attrs) as H\n        by (clear; simpl; intuition eauto); clear H;\n    k ((@Build_KindIndex SC FindPrefixIndex fd), X) (fun _ : @RawTuple SC => true)\n  | _ => k_fail SC F indexed_attrs f k\n  end.\n\n(* FindPrefix Search Terms *)\nLtac PrefixIndexUse_dep SC F indexed_attrs visited_attrs f T k k_fail :=\n  match type of f with\n  | forall a b, {IsPrefix (GetAttributeRaw _ ?fd) (@?X a)} + {_} =>\n    let H := fresh in\n    assert (List.In (@Build_KindIndex SC FindPrefixIndex fd) indexed_attrs) as H\n        by (clear; simpl; intuition eauto); clear H;\n    match eval simpl in\n          (in_dec fin_eq_dec fd visited_attrs) with\n    | right _ => k (fd :: visited_attrs)\n                   ((@Build_KindIndex SC FindPrefixIndex fd), X)\n                   (fun (a : T) (_ : @RawTuple SC) => true)\n    | left _ => k visited_attrs tt F\n    end\n  | _ => k_fail SC F indexed_attrs visited_attrs f T k\n  end.\n\nLtac createLastPrefixTerm f fds tail fs kind s k k_fail :=\n  let is_equality := eval compute in (string_dec kind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        (findMatchingTerm\n           fds kind s\n           ltac:(fun X => k (Some X, tail)))\n          || k (@None (Domain f s), tail)\n      | _ => k_fail f fds tail fs kind s k\n      end.\n\nLtac createLastPrefixTerm_dep dom f fds tail fs kind s k k_fail :=\n  let is_equality := eval compute in (string_dec kind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        (findMatchingTerm\n           fds kind s\n           ltac:(fun X => k (fun x : dom => (Some (X x), tail x)))\n                  || k (fun x : dom => (fun x : dom => (@None (Domain f s ), tail x))))\n      | _ => k_fail dom f fds tail fs kind s k\n      end.\n\nLtac createEarlyPrefixTerm f fds tail fs kind EarlyIndex LastIndex rest s k k_fail :=\n  let is_equality := eval compute in (string_dec kind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        (findMatchingTerm\n           fds kind s\n           ltac:(fun X => k (Some X, rest)))\n          || k (@None (Domain f s), rest)\n      | _ => k_fail f fds tail fs kind EarlyIndex LastIndex rest s k\n      end.\n\nLtac createEarlyPrefixTerm_dep dom f fds tail fs kind EarlyIndex LastIndex rest s k k_fail :=\n  let is_equality := eval compute in (string_dec kind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        (findMatchingTerm\n           fds kind s\n           ltac:(fun X => k (fun x : dom => (Some (X x), rest x))))\n          || k (fun x : dom => (@None (Domain f s), rest x))\n      | _ => k_fail dom f fds tail fs kind EarlyIndex LastIndex rest s k\n      end.\n\nRequire Import\n        Coq.FSets.FMapInterface\n        Coq.FSets.FMapFacts\n        Coq.FSets.FMapAVL\n        Coq.Structures.OrderedTypeEx\n        Fiat.Common.String_as_OT\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.TrieBags.\n\nModule NatTrieBag := TrieBag Nat_as_OT.\nModule ZTrieBag := TrieBag Z_as_OT.\nModule NTrieBag := TrieBag N_as_OT.\nModule StringTrieBag := TrieBag String_as_OT.\n\nLtac BuildLastTrieBag heading AttrList AttrKind AttrIndex k k_fail :=\n  let is_equality := eval compute in (string_dec AttrKind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        let AttrType := eval compute in (Domain heading AttrIndex) in\n            match AttrType with\n            | list nat =>\n              k (@NatTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 (@CountingListAsCorrectBag\n                                                    (@RawTuple heading)\n                                                    (IndexedTreeUpdateTermType heading)\n                                                    (IndexedTreebupdate_transform heading))\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n            | list N =>\n              k (@NTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 (@CountingListAsCorrectBag\n                                                    (@RawTuple heading)\n                                                    (IndexedTreeUpdateTermType heading)\n                                                    (IndexedTreebupdate_transform heading))\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n\n            | list Z =>\n              k (@ZTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 (@CountingListAsCorrectBag\n                                                    (@RawTuple heading)\n                                                    (IndexedTreeUpdateTermType heading)\n                                                    (IndexedTreebupdate_transform heading))\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n            | list string =>\n              k (@StringTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 (@CountingListAsCorrectBag\n                                                    (@RawTuple heading)\n                                                    (IndexedTreeUpdateTermType heading)\n                                                    (IndexedTreebupdate_transform heading))\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n            end\n      | right _ => k_fail heading AttrList AttrKind AttrIndex k\n      end.\n\nLtac BuildEarlyTrieBag heading AttrList AttrKind AttrIndex subtree k k_fail :=\n  let is_equality := eval compute in (string_dec AttrKind \"FindPrefixIndex\") in\n      match is_equality with\n      | left _ =>\n        let AttrType := eval compute in (Domain heading AttrIndex) in\n            match AttrType with\n            | list nat =>\n              k (@NatTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 subtree\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n\n            | list N =>\n              k (@NTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 subtree\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n\n            | list Z =>\n              k (@ZTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 subtree\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n\n            | list string =>\n              k (@StringTrieBag.TrieBagAsCorrectBag _ _ _ _ _ _ _\n                                                 subtree\n                                                 (fun x => GetAttributeRaw (heading := heading) x AttrIndex))\n            end\n      | right _ => k_fail heading AttrList AttrKind AttrIndex subtree k\n      end.\n\nLtac PrefixIndexTactics f :=\n  PackageIndexTactics\n    IsPrefixExpressionAttributeCounter\n    BuildEarlyFindPrefixIndex BuildLastFindPrefixIndex\n    PrefixIndexUse createEarlyPrefixTerm createLastPrefixTerm\n    PrefixIndexUse_dep createEarlyPrefixTerm_dep createLastPrefixTerm_dep\n    BuildEarlyTrieBag BuildLastTrieBag f.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/QueryStructure/Automation/SearchTerms/FindPrefixSearchTerms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.1976124685999784}}
{"text": "From RecoveryRefinement Require Import Lib.\nRequire Export Maybe.\nRequire Export Disk.\nRequire Import TwoDiskAPI.\n\nImport RelationNotations.\nImport TwoDisk.\nImport Helpers.RelationAlgebra.\nImport RelationNotations.\n\nSection specs.\n\n  (** Simple wrapper specs that just capture the exact semantics of the operations.\n     We use these exclusively in this file to prove higher level specs below. *)\n  Lemma read_op_ok :\n    forall i a,\n      proc_hspec TDBaseDynamics (td.read i a) (op_spec TDBaseDynamics (op_read i a)).\n  Proof. intros. eapply op_spec_sound. Qed.\n\n  Lemma write_op_ok :\n    forall i a b,\n      proc_hspec TDBaseDynamics (td.write i a b) (op_spec TDBaseDynamics (op_write i a b)).\n  Proof. intros. eapply op_spec_sound. Qed.\n\n  Lemma size_op_ok :\n    forall i,\n      proc_hspec TDBaseDynamics (td.size i) (op_spec TDBaseDynamics (op_size i)).\n  Proof. intros. eapply op_spec_sound. Qed.\n\n  Hint Resolve read_op_ok : core.\n  Hint Resolve write_op_ok : core.\n  Hint Resolve size_op_ok : core.\n\n\n  (** We now define easier-to-use specifications written in terms of\n  [maybe_holds] (the ?|= notation) for the TwoDisk layer.  The fact that at least\n  one disk is always functioning is encoded in the inductive type\n  [TwoDiskBaseAPI.State] itself; it has only three cases, for both disks, only\n  disk 0, and only disk 1.  *)\n\n\n  Definition other (i : diskId) :=\n    match i with\n    | d0 => d1\n    | d1 => d0\n    end.\n\n  Definition read_spec (i : diskId) (a : addr) : _ -> Specification _ (unit) State :=\n    fun '(d, F) state => {|\n      pre :=\n        get_disk i         state ?|= eq d /\\\n        get_disk (other i) state ?|= F;\n      post := fun state' r =>\n        match r with\n        | Working v =>\n          get_disk i         state' ?|= eq d /\\\n          get_disk (other i) state' ?|= F /\\\n          index d a ?|= eq v\n        | Failed =>\n          get_disk i         state' ?|= missing /\\\n          get_disk (other i) state' ?|= F\n        end;\n      alternate := fun state' r =>\n        get_disk i         state' ?|= eq d /\\\n        get_disk (other i) state' ?|= F;\n    |}.\n\n  Definition write_spec (i : diskId) (a : addr) (b : block)\n    : _ -> Specification (DiskResult unit) unit _ :=\n    fun '(d, F) state => {|\n      pre :=\n        get_disk i         state ?|= eq d /\\\n        get_disk (other i) state ?|= F;\n      post := fun state' r =>\n        match r with\n        | Working _ =>\n          get_disk i         state' ?|= eq (assign d a b) /\\\n          get_disk (other i) state' ?|= F\n        | Failed =>\n          get_disk i         state' ?|= missing /\\\n          get_disk (other i) state' ?|= F\n        end;\n      alternate := fun state' _ =>\n        (get_disk i state' ?|= eq d \\/\n         get_disk i state' ?|= eq (assign d a b) /\\ a < length d) /\\\n        get_disk (other i) state' ?|= F;\n    |}.\n\n  Definition size_spec (i : diskId) : _ -> Specification _ unit _ :=\n    fun '(d, F) state => {|\n      pre :=\n        get_disk i         state ?|= eq d /\\\n        get_disk (other i) state ?|= F;\n      post := fun state' r =>\n        match r with\n        | Working n =>\n          get_disk i         state' ?|= eq d /\\\n          get_disk (other i) state' ?|= F /\\\n          n = length d\n        | Failed =>\n          get_disk i         state' ?|= missing /\\\n          get_disk (other i) state' ?|= F\n        end;\n      alternate := fun state' _ =>\n        get_disk i         state' ?|= eq d /\\\n        get_disk (other i) state' ?|= F;\n    |}.\n\n    Ltac inv_step :=\n    match goal with\n    | [ H: op_step _ _ _ _ |- _ ] =>\n      inversion H; subst; clear H;\n      repeat sigT_eq;\n      safe_intuition\n    end.\n\n  Ltac inv_bg :=\n    match goal with\n    | [ H: bg_failure _ _ _ |- _ ] =>\n      inversion H; subst; clear H\n    end.\n\n  Theorem maybe_holds_stable : forall state state' F0 F1 i,\n    get_disk (other i) state ?|= F0 ->\n    get_disk i state ?|= F1 ->\n    bg_failure state state' tt ->\n    get_disk (other i) state' ?|= F0 /\\\n    get_disk i state' ?|= F1.\n  Proof.\n    intros.\n    destruct i; inv_bg; simpl in *; eauto.\n  Qed.\n\n  Lemma identity_unfold S (s s': S) T (v: T) :\n      identity s s' v ->\n      s' = s.\n  Proof.\n    unfold identity; auto.\n  Qed.\n\n  Ltac cleanup :=\n    repeat match goal with\n           | [ |- forall _, _ ] => intros\n           | |- _ /\\ _ => split; [ solve [ eauto || congruence ] | ]\n           | |- _ /\\ _ => split; [ | solve [ eauto || congruence ] ]\n           | [ H: identity _ _ _ |- _ ] => apply identity_unfold in H\n           | [ H: Working _ = Working _ |- _ ] => inversion H; subst; clear H\n           | [ H: bg_failure _ _ _ |- _ ] =>\n             eapply maybe_holds_stable in H;\n             [ | solve [ eauto ] | solve [ eauto ] ]; destruct_ands\n           | [ H: _ ?|= eq _, H': _ = Some _ |- _ ] =>\n                    pose proof (holds_some_inv_eq _ H' H); clear H\n           | [ H: ?A * ?B |- _ ] => destruct H\n           | [ H: DiskResult _ |- _ ] => destruct H\n           | _ => deex\n           | _ => destruct_tuple\n           | _ => progress autounfold in *\n           | _ => progress simpl in *\n           | _ => progress subst\n           | _ => progress safe_intuition\n           | _ => solve [ eauto ]\n           | _ => congruence\n           | _ => inv_step\n           | H: context[match ?expr with _ => _ end] |- _ =>\n             destruct expr eqn:?; [ | solve [ repeat cleanup ] ]\n           | H: context[match ?expr with _ => _ end] |- _ =>\n             destruct expr eqn:?; [ solve [ repeat cleanup ] | ]\n           end.\n\n  Ltac prim :=\n    intros;\n    eapply proc_hspec_impl; [ unfold spec_impl | eauto ]; eexists;\n    intuition eauto; cleanup;\n    intuition eauto; cleanup.\n\n  Hint Resolve holds_in_some_eq : core.\n  Hint Resolve holds_in_none_eq : core.\n  Hint Resolve pred_missing : core.\n\n  Hint Resolve tt : core.\n\n\n  Theorem read_ok : forall i a dF, proc_hspec TDBaseDynamics (td.read i a) (read_spec i a dF).\n  Proof.\n    unshelve prim; eauto.\n  Qed.\n\n  Ltac destruct_all :=\n    repeat match goal with\n           | _ => solve [ auto ]\n           | [ i: diskId |- _ ] => destruct i\n           | [ |- context[match ?s with\n                         | BothDisks _ _ => _\n                         | OnlyDisk0 _ => _\n                         | OnlyDisk1 _ => _\n                         end] ] => destruct s\n           | _ => simpl in *\n           end.\n\n\n  Theorem write_ok : forall i a v dF, proc_hspec TDBaseDynamics (td.write i a v) (write_spec i a v dF).\n  Proof.\n    unshelve prim; eauto;\n      try solve [ destruct_all ].\n    match goal with\n    | |- context[S a <= length ?d] => destruct (le_dec (S a) (length d))\n    end.\n    - destruct_all.\n    - autorewrite with array.\n      destruct_all.\n  Qed.\n\n  Theorem size_ok : forall i dF, proc_hspec TDBaseDynamics (td.size i) (size_spec i dF).\n  Proof.\n    unshelve prim.\n  Qed.\nEnd specs.\n\nGlobal Hint Resolve write_ok size_ok read_ok : core.\n", "meta": {"author": "mit-pdos", "repo": "argosy", "sha": "a6a5aa0d3868efd4ada0b40927b5748e5d8967d3", "save_path": "github-repos/coq/mit-pdos-argosy", "path": "github-repos/coq/mit-pdos-argosy/argosy-a6a5aa0d3868efd4ada0b40927b5748e5d8967d3/src/Examples/ReplicatedDisk/TwoDiskTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19761246859997839}}
{"text": "From Undecidability Require Import L.Util.L_facts.\n\nFrom Undecidability.Shared.Libs.PSL Require Import FinTypes Vectors.\nRequire Import List.\n\nRequire Import Undecidability.TM.Util.TM_facts.\n\nFrom Undecidability Require Import ProgrammingTools LM_heap_def WriteValue CaseList Copy ListTM Hoare.\nFrom Undecidability.TM.L Require Import JumpTargetTM Alphabets M_LHeapInterpreter.\nFrom Undecidability Require Import L.AbstractMachines.FlatPro.LM_heap_correct.\n\nRequire Import List.\n\nImport Vector.VectorNotations.\nImport ListNotations ResourceMeasures.\n\n\nFrom Undecidability.TM.L Require Import UnfoldClos.\n\nRequire Import Equations.Prop.DepElim.\n\nImport CasePair Code.CaseList.\n\nSet Default Proof Using \"Type\".\n\n\nModule EvalL.\nSection Fix.\n\n  Variable \u03a3 : finType.\n\n  Definition \u03a3intern :Type := sigStep + sigList (sigPair sigHClos sigNat).\n\n\n  Context (retr_eval : Retract \u03a3intern \u03a3) (retr_pro : Retract sigPro \u03a3).\n\n\n  Definition retr_unfolder : Retract (sigList (sigPair sigHClos sigNat)) \u03a3 := ComposeRetract retr_eval _.\n  Definition retr_interpreter : Retract sigStep \u03a3 := ComposeRetract retr_eval _.\n\n  Local Instance retr_closs_intrp : Retract (sigList (sigHClos)) \u03a3 := ComposeRetract retr_interpreter _.\n  Local Instance retr_clos_intrp : Retract sigHClos \u03a3 := ComposeRetract retr_closs_intrp _.\n  Local Instance retr_pro_intrp : Retract sigPro \u03a3 := ComposeRetract retr_clos_intrp _.\n  \n  Local Instance retr_nat_clos_ad' : Retract sigNat sigHClos := Retract_sigPair_X _ (Retract_id _).\n  Local Instance retr_nat_clos_ad : Retract sigNat \u03a3 := ComposeRetract _ retr_nat_clos_ad'.\n  Local Instance retr_heap : Retract sigHeap \u03a3 := ComposeRetract retr_interpreter _.\n\n\n  (*\n    auxiliary tapes:\n\n    0    : T\n    1    : V\n    2    : H\n    3-4  : aux for init\n    5-12 : aux for loop\n    13   : t\n   *)\n   \n  Definition M : pTM (\u03a3^+) unit 11 :=\n    Translate retr_pro retr_pro_intrp @ [|Fin0|];;\n    CopyValue _ @ [|Fin0;Fin1|];;\n    Reset _ @[|Fin0|];;\n    WriteValue 0 \u21d1 retr_nat_clos_ad @ [| Fin0|];;\n    Constr_pair _ _ \u21d1 retr_clos_intrp @ [|Fin0;Fin1|];;\n    Reset _ @ [|Fin0|];;\n    WriteValue ( []%list) \u21d1 retr_closs_intrp @ [| Fin0|];;\n    Constr_cons _ \u21d1 retr_closs_intrp @ [|Fin0;Fin1|];;\n    Reset _ @ [|Fin1|];;\n    WriteValue ( []%list) \u21d1 retr_closs_intrp @ [| Fin1|];;\n    WriteValue ( []%list ) \u21d1 retr_heap @ [| Fin2|];;\n    M_LHeapInterpreter.Loop \u21d1 retr_interpreter;;\n    Reset _ @ [|Fin0|];;\n    CaseList _ \u21d1 retr_closs_intrp @ [| Fin1;Fin0 |];;\n    Reset _ @ [|Fin1|];;\n    UnfoldClos.M retr_unfolder retr_heap retr_clos_intrp @ [| Fin0;Fin2;Fin1;Fin3;Fin4;Fin5;Fin6;Fin7;Fin8;Fin9|];;\n    Reset _ @ [|Fin2|];;\n    Translate (UnfoldClos.retr_pro _) retr_pro @ [|Fin0|].\n\n  \n  Arguments \"+\" : simpl never.\n  Arguments \"*\" : simpl never.\n\n  Definition steps (s : term) (k:nat) (t:term) Hcl (HR:evalIn k s t):=\n    1 + Translate_steps (compile s) +\n    (1 + CopyValue_steps (compile s) +\n    (1 + Reset_steps (compile s) +\n      (1 + WriteValue_steps (size 0) +\n      (1 + Constr_pair_steps 0 +\n        (1 + Reset_steps 0 +\n        (1 + WriteValue_steps (size []%list) +\n          (1 + Constr_cons_steps (0, compile s) +\n          (1 + Reset_steps (0, compile s) +\n            (1 + WriteValue_steps (size []%list) +\n            (1 + WriteValue_steps (size []%list) +\n              (1 + Loop_steps [(0, compile s)] [] []%list (3 * k + 1) +\n              (1 + Reset_steps []%list +\n                let (g,tmp) := completenessTimeInformative (proj2 (timeBS_evalIn _ _ _) HR) Hcl in\n                let (H,_):= tmp in\n                (1 + CaseList_steps [g] +\n                (1 + Reset_steps []%list +\n                  (1 + UnfoldClos.steps H g t +\n                  (1 + Reset_steps H + Translate_steps (compile t))))))))))))))))).\n  Arguments steps : clear implicits.\n\n  Lemma SpecT s k t (Hcl: closed s) (HR:evalIn k s t):\n    TripleT \u2243\u2243([],[|Contains retr_pro (compile s)|] ++ Vector.const Void _)\n      (steps s k t Hcl HR) M\n      (fun _ => \u2243\u2243([],[|Contains retr_pro (compile t)|] ++ Vector.const Void _)).\n  Proof.\n    unfold steps. destruct completenessTimeInformative as (g&H&?&?). clear HR.\n    eapply ConsequenceT_pre. 2:reflexivity.\n    unfold M.\n    do 11 (hstep_seq;[]). cbn.\n    hstep_seq;[| | ] .\n    { refine (TripleT_RemoveSpace _). intros. eapply Interpreter_SpecT. eassumption. inversion 1. }\n    now cbn; tspec_ext.\n    do 2 (hstep_seq;[]).\n    hintros _ _.\n    hstep_seq;[].\n    hstep_seq;[|].\n    { eapply UnfoldClos.SpecT. eassumption. }\n    cbn.\n    do 2 (hstep_seq;[]). reflexivity.\n    unfold steps. reflexivity.\n  Qed.\n\n  \n  Lemma Spec s :\n   closed s -> \n    Triple \u2243\u2243([],[|Contains retr_pro (compile s)|] ++ Vector.const Void _)\n      M\n      (fun _ t => exists s', t \u2243\u2243 ([s \u21d3 s']%list,[|Contains retr_pro (compile s')|] ++ Vector.const Void _)).\n  Proof.\n    intros cls.\n    unfold M.\n    do 11 (hstep_seq;[]). cbn.\n    hstep.\n    {\n      eapply Consequence with (Q1:= fun y => _) (Q2:= fun y => _).\n      eapply ChangeAlphabet_Spec_ex with (Q:= fun y x => _) (Q':= fun y x => _) (Ctx:= fun x (H:Prop) => (steps_k (snd x) _ (fst x) /\\ halt_state (fst x)) /\\\n        (fst (fst (fst x)) = []%list ->\n        H)).\n      now refine (Interpreter_Spec [(0,compile s)] [] [])%list. now unfold \"==>\",Proper,Basics.impl. now cbn; tspec_ext. cbn;intros _. apply reflexivity.\n    }\n    cbn. intros _.\n    eapply Triple_exists_pre. intros [[[T' V'] H'] k'];cbn.\n    eapply Triple_and_pre. intros [HR Hhalt].\n    unfold steps_k in*.\n    edestruct soundness with (1:=cls) as (?&?&?&Heq&?&?). {split. now eapply pow_star. eassumption. }\n    injection Heq as [= -> -> ->].\n    eapply Triple_forall_pre. exists eq_refl.\n    do 2 (hstep_seq;[]).\n    hintros ? _.\n    do 2 hstep_seq;[|].\n    { refine (TripleT_Triple _). refine (UnfoldClos.SpecT _ _ _ _). eassumption. }\n    cbn.\n    hstep_seq.\n    eapply Triple_exists_con. eexists _.\n    change (fun x => ?h x) with h.\n    eapply Consequence_post.\n    now hsteps_cbn.\n    cbn. intros _. tspec_ext. easy.\n  Qed.\n\nEnd Fix.\nEnd EvalL.", "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/Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.1975857242136561}}
{"text": "Require Export Arith.EqNat.\nRequire Export Arith.Le.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Lists.List.\nRequire Import Psatz. (* for lia *)\nImport ListNotations.\n\n(* Type soundness for lambda calculus with mutable references, recursive functions \u03bbf(x).t, and subtyping, quick and dirty.\n\n   - Variables in locally nameless, deBruijn _levels_ for free vars.\n   - Implements substitution in terms of opening.\n\n   Nice to have: automation, automation, automation!\n *)\n\n(* ### Syntax ### *)\n\nDefinition id := nat.\nDefinition loc := nat. (* store locations *)\n\n\n(* locally nameless for binders in terms *)\nInductive var : Type :=\n| varF : id -> var (* free var (deBruijn level) *)\n| varB : id -> var (* locally-bound variable (deBruijn index) *)\n.\n\nNotation \"# i\" := (varB i) (at level 0).\nNotation \"$ i\" := (varF i) (at level 0).\n\nInductive ty : Type :=\n| TUnit : ty\n| TFun  : ty -> ty -> ty\n| TRef  : 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.\n\nNotation \"& l\" := (tloc l) (at level 0).\nNotation \"! t\" := (tderef t) (at level 0).\nCoercion tvar : var >-> tm. (*lightens the notation of term variables*)\n\n(* ### Representation of Bindings ### *)\n\n(* An environment is a list of values, indexed by decrementing ids. *)\n\n(* Look up a free variable (deBruijn level) in env   *)\nFixpoint indexr {X : Type} (n : id) (l : list X) : option X :=\n  match l with\n    | [] => None\n    | a :: l' =>\n      if (beq_nat n (length l')) then Some a else indexr n l'\n  end.\n\nLemma indexr_head : forall {A} {x : A} {xs}, indexr (length xs) (x :: xs) = Some x.\n  intros. simpl. destruct (Nat.eqb (length xs) (length xs)) eqn:Heq. auto.\n  apply beq_nat_false in Heq. contradiction.\nQed.\n\nLemma indexr_length : forall {A B} {xs : list A} {ys : list B}, length xs = length ys -> forall {x}, indexr x xs = None <-> indexr x ys = None.\nProof.\n  intros A B xs.\n  induction xs; intros; destruct ys; split; simpl in *; intros; eauto; try lia.\n  - inversion H. destruct (PeanoNat.Nat.eqb x (length xs)). discriminate.\n    specialize (IHxs _ H2 x). destruct IHxs. auto.\n  - inversion H. rewrite <- H2 in H0. destruct (PeanoNat.Nat.eqb x (length xs)). discriminate.\n    specialize (IHxs _ H2 x). destruct IHxs. auto.\nQed.\n\nLemma indexr_skip : forall {A} {x : A} {xs : list A} {i}, i <> length xs -> indexr i (x :: xs) = indexr i xs.\nProof.\n  intros.\n  rewrite <- PeanoNat.Nat.eqb_neq in H. auto.\n  simpl. rewrite H. reflexivity.\nQed.\n\nLemma indexr_skips : forall {A} {xs' xs : list A} {i}, i < length xs -> indexr i (xs' ++ xs) = indexr i xs.\n  induction xs'; intros; intuition.\n  replace ((a :: xs') ++ xs) with (a :: (xs' ++ xs)).\n  rewrite indexr_skip. eauto. rewrite app_length. lia. auto.\nQed.\n\nLemma indexr_var_some :  forall {A} {xs : list A} {i}, (exists x, indexr i xs = Some x) <-> i < length xs.\nProof.\n  induction xs; intros; split; intros. inversion H. inversion H0.\n  inversion H. inversion H. simpl in H0. destruct (PeanoNat.Nat.eqb i (length xs)) eqn:Heq.\n  apply beq_nat_true in Heq. rewrite Heq. auto. inversion H.\n  simpl in H. rewrite Heq in H. apply IHxs in H. simpl. lia.\n  simpl. destruct (PeanoNat.Nat.eqb i (length xs)) eqn:Heq.\n  exists a. reflexivity. apply beq_nat_false in Heq. simpl in H.\n  apply IHxs. lia.\nQed.\n\n(* easier to use for assumptions without existential quantifier *)\nLemma indexr_var_some' :  forall {A} {xs : list A} {i x}, indexr i xs = Some x -> i < length xs.\nProof.\n  intros. apply indexr_var_some. exists x. auto.\nQed.\n\nLemma indexr_var_none :  forall {A} {xs : list A} {i}, indexr i xs = None <-> i >= length xs.\nProof.\n  induction xs; intros; split; intros.\n  simpl in *. lia. auto.\n  simpl in H.\n  destruct (PeanoNat.Nat.eqb i (length xs)) eqn:Heq.\n  discriminate. apply IHxs in H. apply beq_nat_false in Heq. simpl. lia.\n  assert (Hleq: i >= length xs). {\n    simpl in H. lia.\n  }\n  apply IHxs in Hleq. rewrite <- Hleq.\n  apply indexr_skip. simpl in H. lia.\nQed.\n\nLemma indexr_insert_ge : forall {A} {xs xs' : list A} {x} {y}, x >= (length xs') -> indexr x (xs ++ xs') = indexr (S x) (xs ++ y :: xs').\n  induction xs; intros.\n  - repeat rewrite app_nil_l. pose (H' := H).\n    rewrite <- indexr_var_none in H'.\n    rewrite H'. symmetry. apply indexr_var_none. simpl. lia.\n  - replace ((a :: xs) ++ xs') with (a :: (xs ++ xs')); auto.\n    replace ((a :: xs) ++ y :: xs') with (a :: (xs ++ y :: xs')); auto.\n    simpl. replace (length (xs ++ y :: xs')) with (S (length (xs ++ xs'))).\n    destruct (Nat.eqb x (length (xs ++ xs'))) eqn:Heq; auto.\n    repeat rewrite app_length. simpl. lia.\nQed.\n\nLemma indexr_insert_lt : forall {A} {xs xs' : list A} {x} {y}, x < (length xs') -> indexr x (xs ++ xs') = indexr x (xs ++ y :: xs').\n  intros.\n  rewrite indexr_skips; auto.\n  erewrite indexr_skips.\n  erewrite indexr_skip. auto.\n  lia. simpl. lia.\nQed.\n\nLemma indexr_insert:  forall {A} {xs xs' : list A} {y}, indexr (length xs') (xs ++ y :: xs') = Some y.\n  intros. induction xs.\n  - replace ([] ++ y :: xs') with (y :: xs'); auto. apply indexr_head.\n  - simpl. rewrite IHxs. rewrite app_length. simpl.\n    destruct (PeanoNat.Nat.eqb (length xs') (length xs + S (length xs'))) eqn:Heq; auto.\n    apply beq_nat_true in Heq. lia.\nQed.\n\nDefinition tenv := list ty. (* \u0393 environment: static *)\nDefinition senv := list ty. (* Sigma store typing *)\n\nDefinition extends {A} (l1 l2 : list A): Prop := exists l', l1 = l' ++ l2.\nNotation \"x \u2287 y\" := (extends x y) (at level 0).\n\nLemma extends_refl : forall {A}, forall{l : list A}, extends l l.\n  intros. unfold extends. exists []. auto.\nQed.\n\nLemma extends_cons : forall {A}, forall{l : list A}, forall{a:A}, extends (a :: l) l.\n  intros. unfold extends. exists [a]. auto.\nQed.\n\nLemma extends_length : forall {A}, forall{l1 l2 : list A}, extends l1 l2 -> length l1 >= length l2.\n  intros. unfold extends in H. destruct H as [l' Heq]. subst. rewrite app_length. lia.\nQed.\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 beq_nat 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(*simultaneous opening with self-ref and argument: *)\nDefinition open_tm (u u' : tm) t := open_rec_tm 1 u' (open_rec_tm 0 u t).\nDefinition open_tm' {A : Type} (env : list A) t :=\n  open_rec_tm 1 (varF (S (length env))) (open_rec_tm 0 (varF (length env)) t).\n\nLemma open_rec_tm_commute : forall t i j x y, i <> j -> open_rec_tm i (varF x) (open_rec_tm j (varF y) t) = open_rec_tm j (varF y) (open_rec_tm i (varF 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 beq_nat_true in Hii0. apply beq_nat_true in Hji0. subst. contradiction.\nQed.\n\n(* measure for induction over terms *)\nFixpoint tm_size (t : tm) : nat :=\n  match t with\n  | tunit          => 0\n  | tvar    _     => 0\n  | tabs    t     => S (tm_size t)\n  | tapp    t1 t2 => S (tm_size t1 + tm_size t2)\n  | tloc    _     => 0\n  | tref    t     => S (tm_size t)\n  | tderef  t     => S (tm_size t)\n  | tassign t1 t2 => S (tm_size t1 + tm_size t2)\n  end.\n\nLemma open_preserves_size: forall t x j, tm_size t = tm_size (open_rec_tm j (tvar x) t).\n  induction t; intros; simpl; eauto.\n  destruct v. auto. destruct (Nat.eqb j i); auto.\nQed.\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 (tvar (varB x))\n| cl_tvarf: forall b f l x,\n    x < f ->\n    closed_tm b f l (tvar (varF 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 (tloc 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.\nHint Constructors closed_tm : dsub.\n\nInductive stp : tenv -> senv -> ty -> ty -> Prop :=\n| s_base : forall \u0393 \u03a3,\n    stp \u0393 \u03a3 TUnit TUnit\n| s_ref : forall \u0393 \u03a3 T, (* TODO: generalize to equivalence*)\n    stp \u0393 \u03a3 (TRef T) (TRef T)\n| s_fun : forall \u0393 \u03a3 T1 T3 T2 T4,  (*TODO: this becomes less trivial with the qualifiers *)\n    stp \u0393 \u03a3 T3 T1 ->\n    stp \u0393 \u03a3 T2 T4 ->\n    stp \u0393 \u03a3 (TFun T1 T2) (TFun T3 T4)\n.\n\nInductive has_type : tenv -> senv -> tm -> ty -> Prop :=\n| t_base : forall \u0393 \u03a3,\n    has_type \u0393 \u03a3 tunit TUnit\n\n| t_var : forall \u0393 \u03a3 x T,\n    indexr x \u0393 = Some T ->\n    has_type \u0393 \u03a3 (tvar (varF x)) T\n\n| t_abs: forall \u0393 \u03a3 T1 T2 t,\n    closed_tm 2 (length \u0393) (length \u03a3) t ->\n    has_type (T1 :: (TFun T1 T2) :: \u0393) \u03a3 (open_tm' \u0393 t) T2 ->\n    has_type \u0393 \u03a3 (tabs t) (TFun T1 T2)\n\n| t_app : forall \u0393 \u03a3 t1 t2 T1 T2,\n    has_type \u0393 \u03a3 t1 (TFun T1 T2) ->\n    has_type \u0393 \u03a3 t2 T1 ->\n    has_type \u0393 \u03a3 (tapp t1 t2) T2\n\n| t_loc : forall \u0393 \u03a3 l T,\n    indexr l \u03a3 = Some T ->\n    has_type \u0393 \u03a3 (tloc l) (TRef T)\n\n| t_ref: forall \u0393 \u03a3 T t,\n    has_type \u0393 \u03a3 t T ->\n    has_type \u0393 \u03a3 (tref t) (TRef T)\n\n| t_deref: forall \u0393 \u03a3 T t,\n    has_type \u0393 \u03a3 t (TRef T) ->\n    has_type \u0393 \u03a3 (tderef t) T\n\n| t_assign: forall \u0393 \u03a3 T t1 t2,\n    has_type \u0393 \u03a3 t1 (TRef T) ->\n    has_type \u0393 \u03a3 t2 T ->\n    has_type \u0393 \u03a3 (tassign t1 t2) TUnit\n\n| t_sub: forall \u0393 \u03a3 e T1 T2,\n    has_type \u0393 \u03a3 e T1 ->\n    stp \u0393 \u03a3 T1 T2 ->\n    has_type \u0393 \u03a3 e T2\n.\n\nHint Constructors has_type : dsub.\nHint Constructors stp : dsub.\n\nLemma bound_vars_untypable : forall {\u0393 \u03a3 T i}, has_type \u0393 \u03a3 #i T -> False.\n  intros \u0393 \u03a3 T i HT. remember (tvar #i) as t. induction HT; try discriminate.\n  intuition.\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_tm_open_id : forall {t b f l}, closed_tm b f l t -> forall {n}, b <= n -> forall {x}, (open_rec_tm 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 beq_nat_true in Heq. lia.\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 (open_rec_tm b (varF 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 beq_nat_false in Heq. constructor. lia. auto. auto.\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 (open_rec_tm 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 beq_nat_false in Heq. constructor. lia. auto. auto.\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 (open_rec_tm b (varF 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 beq_nat_false in Heq. inversion H. subst.\n  constructor. lia. lia. auto.\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 (open_rec_tm j (varF 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 beq_nat_false in Heq. inversion H. subst. intuition. lia. auto.\nQed.\n\nLemma open_rec_tm_commute' : forall t i j x t' f l, i <> j -> closed_tm 0 f l t' -> open_rec_tm i (varF x) (open_rec_tm j t' t) = open_rec_tm j t' (open_rec_tm i (varF 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 beq_nat_true in Hii0. apply beq_nat_true in Hji0. subst. contradiction.\n    eapply closed_tm_open_id; eauto. lia.\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'' -> open_rec_tm i t'' (open_rec_tm j t' t) = open_rec_tm j t' (open_rec_tm 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 beq_nat_true in Hii0. apply beq_nat_true in Hji0. subst. contradiction.\n    symmetry. eapply closed_tm_open_id; eauto. lia. eapply closed_tm_open_id; eauto. lia.\nQed.\n\nLemma has_type_var_length : forall {\u0393 \u03a3 x T}, has_type \u0393 \u03a3 (tvar (varF x)) T -> x < length \u0393.\n  intros. dependent induction H; eauto.\n  apply indexr_var_some' in H. auto.\nQed.\n\nFixpoint has_type_closed  {\u0393 \u03a3 t T} (ht  : has_type \u0393 \u03a3 t T) : closed_tm 0 (length \u0393) (length \u03a3) t.\n\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.\n  + apply indexr_var_some' in H. intuition.\n  + apply indexr_var_some' in H. intuition.\nQed.\n\nRequire Import Coq.Arith.Compare_dec.\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\nLemma splice_id : forall {T b f l}, closed_tm b f l T -> (splice f T ) = 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_open : forall {T j n m}, splice n (open_rec_tm j (varF (m + n)) T) = open_rec_tm j (varF (S (m + n))) (splice n T).\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_open' :  forall {T} {A} {D : A} {\u03c1 \u03c1'}, splice (length \u03c1') (open_tm' (\u03c1 ++ \u03c1') T) = open_tm' (\u03c1 ++ D :: \u03c1') (splice (length \u03c1') T).\n  intros. unfold open_tm'.\n  replace (length (\u03c1 ++ \u03c1')) with ((length \u03c1) + (length \u03c1')).\n  replace (S (length (\u03c1 ++ D :: \u03c1'))) with (S (S (length \u03c1) + (length \u03c1'))).\n  replace (length (\u03c1 ++ D :: \u03c1')) with (S ((length \u03c1) + (length \u03c1'))).\n  rewrite <- splice_open.\n  rewrite <- splice_open.\n  reflexivity.\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 (splice m T).\n  induction T; simpl; intros; inversion H; subst; intuition.\n  destruct (le_lt_dec m x) eqn:Heq; intuition.\nQed.\n\nLemma splice_closed' : forall {T b l} {A} {D : A} {\u03c1 \u03c1'},\n    closed_tm b (length (\u03c1 ++ \u03c1')) l T ->  closed_tm b (length (\u03c1 ++ D :: \u03c1')) l (splice (length \u03c1') T).\n  intros. rewrite app_length in H.\n  replace (length (\u03c1 ++ D :: \u03c1')) with (S (length \u03c1) + (length \u03c1')).\n  apply splice_closed. auto. simpl. rewrite app_length. simpl. lia.\nQed.\n\nLemma splice_open_succ : forall {T b n l j}, closed_tm b n l T -> splice n (open_rec_tm j (varF n) T) = open_rec_tm j (varF (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\nInductive value : tm -> Prop :=\n| value_abs : forall t, value (tabs t)\n| value_cst : value tunit\n| value_loc : forall l, value (tloc l)\n.\n\nDefinition store := list tm.\n\nFixpoint update (\u03c3 : store) (l : loc) (v : tm) : store :=\n  match \u03c3 with\n  | [] => \u03c3\n  | a :: \u03c3' =>\n      if (beq_nat l (length \u03c3')) then (v :: \u03c3') else (a :: (update \u03c3' l v ))\n  end.\n\nLemma update_length : forall {\u03c3 l v}, length \u03c3 = length (update \u03c3 l v).\n  induction \u03c3; simpl; intuition.\n  destruct (Nat.eqb l (length \u03c3)) eqn:Heq; intuition.\n  simpl. congruence.\nQed.\n\nLemma update_indexr_miss : forall {\u03c3 l v l'}, l <> l' ->  indexr l' (update \u03c3 l v) = indexr l' \u03c3.\n  induction \u03c3; simpl; intuition.\n  destruct (Nat.eqb l (length \u03c3)) eqn:Hls; destruct (Nat.eqb l' (length \u03c3)) eqn:Hl's.\n  apply beq_nat_true in Hls. apply beq_nat_true in Hl's. rewrite <- Hl's in Hls. contradiction.\n  simpl. rewrite Hl's. auto.\n  simpl. rewrite <- update_length. rewrite Hl's. auto.\n  simpl. rewrite <- update_length. rewrite Hl's. apply IH\u03c3. auto.\nQed.\n\nLemma update_indexr_hit : forall {\u03c3 l v}, l < length \u03c3 -> indexr l (update \u03c3 l v) = Some v.\n  induction \u03c3; simpl; intuition.\n  destruct (Nat.eqb l (length \u03c3)) eqn:Hls.\n  apply beq_nat_true in Hls. rewrite Hls. apply indexr_head.\n  simpl. rewrite <- update_length. rewrite Hls. apply beq_nat_false in Hls.\n  apply IH\u03c3. lia.\nQed.\n\nInductive step : tm -> store -> tm -> store -> Prop :=\n(*contraction rules*)\n| step_beta : forall t v \u03c3,\n    value v ->\n    step (tapp (tabs t) v) \u03c3 (open_tm (tabs t) v t) \u03c3\n| step_ref : forall v \u03c3,\n    value v ->\n    step (tref v) \u03c3 (tloc (length \u03c3)) (v :: \u03c3)\n| step_deref : forall \u03c3 l v,\n    indexr l \u03c3 = Some v ->\n    value v ->\n    step (tderef (tloc l)) \u03c3 v \u03c3\n| step_assign : forall \u03c3 l v,\n    l < (length \u03c3) ->\n    value v ->\n    step (tassign (tloc l) v) \u03c3 tunit (update \u03c3 l v)\n(*congruence rules*)\n| step_c_ref : forall t t' \u03c3 \u03c3',\n    step t \u03c3 t' \u03c3' ->\n    step (tref t) \u03c3 (tref t') \u03c3'\n| step_c_deref : forall t t' \u03c3 \u03c3',\n    step t \u03c3 t' \u03c3' ->\n    step (tderef t) \u03c3 (tderef t') \u03c3'\n| step_c_app_l : forall t1 t1' t2 \u03c3 \u03c3',\n    step t1 \u03c3 t1' \u03c3' ->\n    step (tapp t1 t2) \u03c3 (tapp t1' t2) \u03c3'\n| step_c_app_r : forall v t2 t2' \u03c3 \u03c3',\n    value v ->\n    step t2 \u03c3 t2' \u03c3' ->\n    step (tapp v t2) \u03c3 (tapp v t2') \u03c3'\n| step_c_assign_l : forall t1 t1' t2 \u03c3 \u03c3',\n    step t1 \u03c3 t1' \u03c3' ->\n    step (tassign t1 t2) \u03c3 (tassign t1' t2) \u03c3'\n| step_c_assign_r : forall v t2 t2' \u03c3 \u03c3',\n    value v ->\n    step t2 \u03c3 t2' \u03c3' ->\n    step (tassign v t2) \u03c3 (tassign v t2') \u03c3'\n.\n\nLemma values_stuck : forall {v}, value v -> forall {t \u03c3 \u03c3'}, step v \u03c3 t \u03c3' -> False.\n  intros. inversion H0; subst; inversion H.\nQed.\n\nLemma stp_refl : forall {T \u0393 \u03a3}, stp \u0393 \u03a3 T T.\n  induction T; intros; intuition.\nQed.\n\nLemma stp_trans : forall {T2 T1 T3 \u0393 \u03a3}, stp \u0393 \u03a3 T1 T2 -> stp \u0393 \u03a3 T2 T3 -> stp \u0393 \u03a3 T1 T3.\n  induction T2; intros; try inversion H0; try inversion H; intuition.\nQed.\n\n(* Inversion lemmas abstracting over subsumption steps *)\nLemma typ_inv_unit : forall {\u0393 \u03a3 T}, has_type \u0393 \u03a3 tunit T -> T = TUnit.\n  intros \u0393 \u03a3 T HT. remember tunit as t. induction HT; try solve [discriminate].\n  auto. intuition. subst. inversion H. subst. auto.\nQed.\n\nLemma typ_inv_varf : forall {\u0393 \u03a3 i T}, has_type \u0393 \u03a3 $i T -> exists U, indexr i \u0393 = Some U /\\ stp \u0393 \u03a3 U T.\n  intros \u0393 \u03a3 i T HT. remember (tvar $i) as v. induction HT; inversion Heqv; subst.\n  - exists T. intuition. apply stp_refl.\n  - intuition. destruct H1 as [U [Hlookup UsubT1]].\n    exists U. intuition. eapply stp_trans; eauto.\nQed.\n\nLemma typ_inv_loc : forall {\u0393 \u03a3 l T}, has_type \u0393 \u03a3 &l T -> exists U, indexr l \u03a3 = Some U /\\ stp \u0393 \u03a3 (TRef U) T.\n  intros \u0393 \u03a3 l T HT. remember &l as v. induction HT; inversion Heqv; subst.\n  - exists T. intuition.\n  - intuition. destruct H1 as [U [Hlookup UsubT1]].\n    exists U. intuition. eapply stp_trans; eauto.\nQed.\n\nLemma typ_inv_ref : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 (tref t) T -> exists U, T = TRef U /\\ has_type \u0393 \u03a3 t U.\n  intros \u0393 \u03a3 t T HT. remember (tref t) as ref. induction HT; inversion Heqref; subst.\n  - exists T. intuition.\n  - intuition. destruct H1 as [U [HRef Ht]]. subst.\n    inversion H. subst. exists U. intuition.\nQed.\n\nLemma typ_inv_deref : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 !t T -> exists U, has_type \u0393 \u03a3 t (TRef U) /\\ stp \u0393 \u03a3 U T.\n  intros \u0393 \u03a3 t T HT. remember !t as ref. induction HT; inversion Heqref; subst.\n  - exists T. intuition. apply stp_refl.\n  - intuition. destruct H1 as [U [Ht Hstp]].\n    exists U. intuition. eapply stp_trans; eauto.\nQed.\n\nLemma typ_inv_abs : forall {\u0393 \u03a3 t T},\n    has_type \u0393 \u03a3 (tabs t) T ->\n    exists T1 T2, closed_tm 2 (length \u0393) (length \u03a3) t /\\ has_type (T1 :: (TFun T1 T2) :: \u0393) \u03a3 (open_tm' \u0393 t) T2 /\\ stp \u0393 \u03a3 (TFun T1 T2) T.\n  intros \u0393 \u03a3 t T HT. remember (tabs t) as abs. induction HT; inversion Heqabs; subst.\n  - exists T1. exists T2. intuition. apply stp_refl.\n  - intuition. destruct H1 as [T1' [T2' [Hc [Ht Hstp]]]]. exists T1'. exists T2'.\n    intuition. inversion Hstp. subst. inversion H. subst. eapply stp_trans; eauto.\nQed.\n\nLemma typ_inv_app : forall {\u0393 \u03a3 t1 t2 T},\n    has_type \u0393 \u03a3 (tapp t1 t2) T ->\n    exists T1, has_type \u0393 \u03a3 t1 (TFun T1 T) /\\ has_type \u0393 \u03a3 t2 T1.\n  intros \u0393 \u03a3 t1 t2 T HT. remember (tapp t1 t2) as app. induction HT; inversion Heqapp; subst.\n  - exists T1. intuition.\n  - intuition. destruct H1 as [T' [Ht1 Ht2]].\n    exists T'. split. eapply t_sub. eauto. constructor. apply stp_refl. auto.\n    auto.\nQed.\n\nLemma typ_inv_assign : forall {\u0393 \u03a3 t1 t2 T},\n    has_type \u0393 \u03a3 (tassign t1 t2) T -> T = TUnit /\\ exists U, has_type \u0393 \u03a3 t1 (TRef U) /\\ has_type \u0393 \u03a3 t2 U.\n  intros \u0393 \u03a3 t1 t2 T HT. remember (tassign t1 t2) as ass. induction HT; inversion Heqass; subst.\n  - intuition. exists T. intuition.\n  - intuition. subst. inversion H. subst. auto.\nQed.\n\nLemma weaken_stp_gen : forall {\u03931 \u03932 \u03a3 T1 T2},\n    stp (\u03931 ++ \u03932) \u03a3 T1 T2 ->\n    forall T', stp (\u03931 ++ T' :: \u03932) \u03a3 T1 T2.\n  intros \u03931 \u03932 \u03a3 T1 T2 Hstp. induction Hstp; intuition.\nQed.\n\nLemma weaken_stp : forall {\u0393 \u03a3 T1 T2}, stp \u0393 \u03a3 T1 T2 -> forall T', stp (T' :: \u0393) \u03a3 T1 T2.\n  intros. specialize (@weaken_stp_gen [] \u0393 \u03a3 T1 T2) as Hsp.\n  simpl in *. intuition.\nQed.\n\nLemma weaken_stp' : forall {\u0393 \u03a3 T1 T2}, stp \u0393 \u03a3 T1 T2 -> forall \u0393', stp (\u0393' ++ \u0393) \u03a3 T1 T2.\n  intros. induction \u0393'.\n  - simpl. auto.\n  - replace ((a :: \u0393') ++ \u0393) with (a :: (\u0393' ++ \u0393)).\n    apply weaken_stp. auto. simpl. auto.\nQed.\n\nLemma weaken_gen : forall {n t \u03931 \u03932 \u03a3 T}, tm_size t < n ->\n    closed_tm 0 (length (\u03931 ++ \u03932)) (length \u03a3) t ->\n    has_type (\u03931 ++ \u03932) \u03a3 t T ->\n    forall T', has_type (\u03931 ++ T' :: \u03932) \u03a3 (splice (length \u03932) t) T.\n  induction n; try lia; intros; destruct t; simpl.\n  - apply typ_inv_unit in H1. subst. constructor.\n  - destruct v; inversion H0; subst; try lia.\n    apply typ_inv_varf in H1. destruct H1 as [U [Hlookup Hstp]].\n    destruct (le_lt_dec (length \u03932) i) eqn:Heq.\n    rewrite (@indexr_insert_ge _ \u03931 \u03932 i T' l) in Hlookup.\n    2 : rewrite (@indexr_insert_lt _ \u03931 \u03932 i T' l) in Hlookup.\n    all: eapply t_sub.\n    1,3: constructor; apply Hlookup.\n    all: apply weaken_stp_gen; auto.\n  - (*tabs*) simpl in H. inversion H0; subst.\n    apply typ_inv_abs in H1. destruct H1 as [T1 [T2 [Hc [Ht Hstp]]]].\n    inversion Hstp. subst. eapply t_sub. apply t_abs.\n    3: apply weaken_stp_gen; eapply Hstp.\n    apply splice_closed'. auto.\n    rewrite <- splice_open'.\n    replace (T1 :: TFun T1 T2 :: \u03931 ++ T' :: \u03932) with ((T1 :: TFun T1 T2 :: \u03931) ++ T' :: \u03932).\n    eapply IHn; eauto. unfold open_tm'. rewrite <- open_preserves_size. rewrite <- open_preserves_size. lia.\n    simpl. eapply closed_tm_monotone. eapply has_type_closed; eauto. lia. simpl. lia. auto.\n    intuition.\n  - simpl in H. inversion H0; subst. apply typ_inv_app in H1.\n    destruct H1 as [U [Ht1 Ht2]]. eapply t_app.\n    eapply IHn; eauto. lia. eapply IHn; eauto. lia.\n  - apply typ_inv_loc in H1. destruct H1 as [U [Hlookup Hstp]].\n    eapply t_sub. apply t_loc. eauto. apply weaken_stp_gen. auto.\n  - simpl in H. apply typ_inv_ref in H1. destruct H1 as [U [Heq Ht]].\n    subst. inversion H0. subst. apply t_ref. eapply IHn; eauto. lia.\n  - simpl in H. inversion H0; subst. apply typ_inv_deref in H1.\n    destruct H1 as [U [Ht Hstp]]. eapply t_sub. apply t_deref. eapply IHn; eauto. lia.\n    apply weaken_stp_gen. auto.\n  - simpl in H. inversion H0; subst. apply typ_inv_assign in H1.\n    destruct H1 as [Heq [U [Ht1 Ht2]]]. subst.\n    eapply t_assign. eapply IHn; eauto; lia. eapply IHn; eauto; lia.\nQed.\n\nLemma weaken : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 t T -> forall {T'}, has_type (T' :: \u0393) \u03a3 t T.\n  intros \u0393 \u03a3 t T HT. specialize (@weaken_gen (S (tm_size t)) t [] \u0393 \u03a3 T) as Hsp. simpl in *.\n  replace (splice (length \u0393) t) with t in Hsp.\n  apply Hsp; auto. eapply has_type_closed; eauto.\n  symmetry. eapply splice_id. eapply has_type_closed; eauto.\nQed.\n\nLemma weaken' : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 t T -> forall {\u0393'}, has_type (\u0393' ++ \u0393) \u03a3 t T.\n  intros. induction \u0393'.\n  - simpl. auto.\n  - replace ((a :: \u0393') ++ \u0393) with (a :: (\u0393' ++ \u0393)).\n    apply weaken. auto. simpl. auto.\nQed.\n\nLemma weaken_stp_store : forall {\u0393 \u03a3 T1 T2}, stp \u0393 \u03a3 T1 T2 -> forall {\u03a3'}, \u03a3' \u2287 \u03a3 -> stp \u0393 \u03a3' T1 T2.\n  intros \u0393 \u03a3 T1 T2 HST. induction HST; intuition.\nQed.\n\nLemma weaken_store : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 t T -> forall {\u03a3'}, \u03a3' \u2287 \u03a3 -> has_type \u0393 \u03a3' t T.\n  intros \u0393 \u03a3 t T HT. induction HT; intros; intuition.\n  - apply t_abs. eapply closed_tm_monotone; eauto. apply extends_length. auto.\n    apply IHHT. auto.\n  - eapply t_app. eapply IHHT1; auto. eapply IHHT2; auto.\n  - eapply t_loc. unfold extends in H0. destruct H0. rewrite H0.\n    rewrite indexr_skips. auto. eapply indexr_var_some'. eauto.\n  - eapply t_assign. eapply IHHT1; auto. eapply IHHT2; auto.\n  - eapply t_sub; eauto. eapply weaken_stp_store; eauto.\nQed.\n\n(* canonical forms *)\nLemma canonical_unit : forall {\u03a3 t}, has_type [] \u03a3 t TUnit -> value t -> t = tunit.\n  intros. remember [] as \u0393. remember TUnit as T. induction H; intuition; try discriminate;\n                                                   inversion H0; subst; auto.\n  all: inversion H1; subst; intuition.\nQed.\n\nLemma canonical_fun : forall {\u03a3 t T1 T2}, has_type [] \u03a3 t (TFun T1 T2) -> value t -> exists t', t = (tabs t').\n  intros. remember [] as \u0393. remember (TFun T1 T2) as T. induction H; intuition; try discriminate;\n                                                          inversion H0; subst.\n  - exists t. auto.\n  - exists t. auto.\n  - apply typ_inv_unit in H. subst. inversion H1.\n  - apply typ_inv_loc in H. repeat destruct H. inversion H3. subst. inversion H1.\nQed.\n\nLemma canonical_ref : forall {\u03a3 t T}, has_type [] \u03a3 t (TRef T) -> value t -> exists l, t = &l.\n  intros. remember [] as \u0393. remember (TRef T) as R. induction H; intuition; try discriminate;\n                                                          inversion H0; subst.\n  - exists l. auto.\n  - apply typ_inv_abs in H. destruct H as [T2 [T3 [Hc [Ht Hstp]]]].\n    inversion Hstp. subst. inversion H1.\n  - apply typ_inv_unit in H. subst. inversion H1.\n  - exists l. auto.\nQed.\n\nLemma narrowing_stp_gen : forall{\u03931 U \u03932 \u03a3 T1 T2}, stp (\u03931 ++ U :: \u03932) \u03a3 T1 T2 -> forall {V}, stp \u03932 \u03a3 V U -> stp (\u03931 ++ V :: \u03932) \u03a3 T1 T2.\n  intros \u03931 U \u03932 \u03a3 T1 T2 HST. remember (\u03931 ++ U :: \u03932) as \u0393. generalize dependent \u03931; induction HST; intros; subst; intuition.\nQed.\n\nLemma narrowing_stp : forall{\u0393 U \u03a3 T1 T2}, stp (U :: \u0393) \u03a3 T1 T2 -> forall {V}, stp \u0393 \u03a3 V U -> stp (V :: \u0393) \u03a3 T1 T2.\n  intros. specialize (@narrowing_stp_gen [] U \u0393 \u03a3 T1 T2) as narrow. simpl in *. eapply narrow; eauto.\nQed.\n\nLemma narrowing_gen : forall{\u03931 U \u03932 \u03a3 t T}, has_type (\u03931 ++ U :: \u03932) \u03a3 t T -> forall {V}, stp \u03932 \u03a3 V U -> has_type (\u03931 ++ V :: \u03932) \u03a3 t T.\n  intros \u03931 U \u03932 \u03a3 t T HT. remember (\u03931 ++ U :: \u03932) as \u0393. generalize dependent \u03931; induction HT; intros; subst; intuition.\n  - destruct (PeanoNat.Nat.lt_trichotomy x (length \u03932)) as [Hlen | [Hlen | Hlen] ].\n    + apply t_var. rewrite <- (indexr_insert_lt Hlen). rewrite <- (indexr_insert_lt Hlen) in H. auto.\n    + rewrite Hlen in *. rewrite indexr_insert in H. inversion H. subst.\n      apply (t_sub _ _ $(length \u03932) V T). apply t_var. rewrite indexr_insert. auto. eapply weaken_stp_gen.\n      apply weaken_stp'. auto.\n    + inversion Hlen. apply t_var. rewrite <- indexr_insert_ge; eauto. rewrite <- H1 in H.\n      rewrite <- indexr_insert_ge in H; eauto. rewrite <- H2 in H.\n      apply t_var. rewrite <- indexr_insert_ge; eauto. rewrite <- indexr_insert_ge in H; eauto. lia. lia.\n  - apply t_abs. replace (length (\u03931 ++ V :: \u03932)) with (length (\u03931 ++ U :: \u03932)). auto.\n    repeat rewrite app_length. simpl. auto.\n    replace (T1 :: TFun T1 T2 :: \u03931 ++ V :: \u03932) with ((T1 :: TFun T1 T2 :: \u03931) ++ V :: \u03932); intuition.\n    replace (open_tm' (\u03931 ++ V :: \u03932) t) with (open_tm' (\u03931 ++ U :: \u03932) t); eauto.\n    unfold open_tm'. repeat rewrite app_length. simpl. auto.\n  - eapply t_app. eapply IHHT1; eauto. eapply IHHT2; eauto.\n  - eapply t_assign. eapply IHHT1; eauto. eapply IHHT2; eauto.\n  - eapply t_sub; eauto. eapply narrowing_stp_gen; eauto.\nQed.\n\nLemma narrowing : forall{\u0393 U \u03a3 t T}, has_type (U :: \u0393) \u03a3 t T -> forall {V}, stp \u0393 \u03a3 V U -> has_type (V :: \u0393) \u03a3 t T.\n  intros. specialize (@narrowing_gen [] U \u0393 \u03a3 t T) as narrow. simpl in *. eapply narrow; eauto.\nQed.\n\nLemma strengthen_stp : forall {\u03931 T1 \u03932 \u03a3 T2 T3}, stp (\u03931 ++ T1 :: \u03932) \u03a3 T2 T3 -> stp (\u03931 ++ \u03932) \u03a3 T2 T3.\n  intros \u03931 T1 \u03932 \u03a3 T2 T3 HST. induction HST; intuition.\nQed.\n\n(* This pops up in the general substitution lemma when we deal with lambdas. *)\nLemma substitution_closed :  forall {k t b m n l i j}, tm_size t < k -> i <> j ->\n    closed_tm (S (S b)) (m + S (S n)) l (open_rec_tm (S (S j)) $(S n) (open_rec_tm (S (S i)) $n (splice (S n) (splice n t)))) ->\n    forall {tx tf}, closed_tm 0 n l tx -> closed_tm 0 n l tf ->\n               closed_tm (S (S b)) (m + n) l (open_rec_tm (S (S j)) tx (open_rec_tm (S (S i)) tf t)).\n  induction k; try lia; destruct t; intros; simpl in *; try solve [inversion H1; subst; constructor; auto; eapply IHk; eauto; lia].\n  destruct v. simpl in *. constructor. destruct (le_lt_dec n i0) eqn:Hlt.\n  replace (splice (S n) $(S i0)) with (tvar $(S (S i0))) in H1.\n  simpl in *. inversion H1. subst. lia. unfold splice. destruct (le_lt_dec (S n) (S i0)). auto. lia. lia.\n  simpl in *. destruct i0 eqn:Hi0. simpl in *. inversion H1. subst. intuition.\n  destruct i1 eqn:Hi1. simpl. inversion H1. subst. intuition.\n  destruct (PeanoNat.Nat.eqb i n0) eqn:Hin0. simpl in *. erewrite closed_tm_open_id; eauto.\n  eapply closed_tm_monotone; eauto; lia. lia. simpl in *.\n  destruct (PeanoNat.Nat.eqb j n0) eqn:Hjn0. eapply closed_tm_monotone; eauto. lia.\n  inversion H1. subst. intuition. inversion H1. subst. intuition.\nQed.\n\nLemma substitution_gen : forall{n t}, tm_size t < n ->\n    forall {\u0393' Tf Tx \u0393 \u03a3 T i j}, has_type (\u0393' ++ Tx :: Tf :: \u0393) \u03a3 (open_rec_tm j $(S (length \u0393)) (open_rec_tm i $(length \u0393) (splice (S (length \u0393)) (splice (length \u0393) t)))) T -> i <> j ->\n                        forall {tf}, has_type \u0393 \u03a3 tf Tf ->\n                        forall {tx}, has_type \u0393 \u03a3 tx Tx ->\n                                has_type (\u0393' ++ \u0393) \u03a3 (open_rec_tm j tx (open_rec_tm i tf t)) T.\n  induction n; try lia; destruct t; intros; simpl in *.\n  - apply typ_inv_unit in H0. subst. intuition.\n  - destruct v.\n    + destruct (le_lt_dec (length \u0393) i0) eqn:Hle.\n      * replace (splice (S (length \u0393)) (tvar $(S i0))) with (tvar $(S (S i0))) in H0.\n        simpl in *. apply typ_inv_varf in H0. destruct H0 as [U [Hl Hstp]]. apply (t_sub _ _ _ U T).\n        apply t_var. erewrite indexr_insert_ge; eauto. erewrite indexr_insert_ge; eauto. simpl. lia.\n        eapply strengthen_stp; eauto. eapply strengthen_stp; eauto.\n        unfold splice. destruct (le_lt_dec (S (length \u0393)) (S i0)) eqn:Heq. auto. lia.\n      * erewrite splice_id in H0; intuition. simpl in *.\n        apply typ_inv_varf in H0. destruct H0 as [U [Hl Hstp]]. apply (t_sub _ _ _ U T).\n        apply t_var. erewrite indexr_insert_lt; eauto. erewrite indexr_insert_lt; eauto. simpl. lia.\n        eapply strengthen_stp; eauto. eapply strengthen_stp; eauto.\n        Unshelve. auto. auto.\n    + simpl in *. destruct (Nat.eqb i i0) eqn:Heq; simpl in *.\n      * apply typ_inv_varf in H0. destruct H0 as [U [Hl Hstp]].\n        replace (\u0393' ++ Tx :: Tf :: \u0393) with ((\u0393' ++ [Tx]) ++ Tf :: \u0393) in Hl.\n        rewrite indexr_insert in Hl. inversion Hl. subst. pose (Hc := H2). apply has_type_closed in Hc.\n        erewrite closed_tm_open_id; eauto. apply (t_sub _ _ _ U T).\n        eapply weaken'; eauto. eapply strengthen_stp; eauto. eapply strengthen_stp; eauto. lia.\n        rewrite <- app_assoc. auto.\n      * destruct (Nat.eqb j i0) eqn:Heqj. apply typ_inv_varf in H0. destruct H0 as [U [Hl Hstp]].\n        replace (S (length \u0393)) with (length (Tf :: \u0393)) in Hl; eauto.\n        rewrite indexr_insert in Hl. inversion Hl. subst. pose (Hc := H3). apply has_type_closed in Hc.\n        apply (t_sub _ _ _ U T). eapply weaken'; eauto. eapply strengthen_stp; eauto. eapply strengthen_stp; eauto.\n        apply bound_vars_untypable in H0. contradiction.\n  - specialize (has_type_closed H2) as Hcltf. specialize (has_type_closed H3) as Hcltx.\n    apply typ_inv_abs in H0. destruct H0 as [T3 [T4 [Hc [HTt Hstp]]]]. inversion Hstp. subst.\n    apply (t_sub _ _ _ (TFun T3 T4) (TFun T0 T5)). apply t_abs.\n    rewrite app_length in *. simpl in *.\n    eapply substitution_closed; eauto.\n    (* We must swap the openings in the subject so that the IHn on the body t becomes applicable. *)\n    unfold open_tm' in *.\n    erewrite open_rec_tm_commute' with (t':=tx); eauto. erewrite open_rec_tm_commute' with (t':=tx); eauto.\n    erewrite open_rec_tm_commute' with (t':=tf); eauto. erewrite open_rec_tm_commute' with (t':=tf); eauto.\n    replace (T3 :: TFun T3 T4 :: \u0393' ++ \u0393) with ((T3 :: TFun T3 T4 :: \u0393') ++ \u0393); eauto.\n    replace (T3 :: TFun T3 T4 :: \u0393' ++ Tx :: Tf :: \u0393) with ((T3 :: TFun T3 T4 :: \u0393') ++ Tx :: Tf :: \u0393) in HTt; eauto.\n    eapply IHn; eauto. rewrite <- open_preserves_size. rewrite <- open_preserves_size. lia.\n    (* Then, shuffle around the openings/splicings so that they match HTt:*)\n    rewrite app_length in *. simpl in *.\n    replace (S (length \u0393' + length \u0393)) with ((S (length \u0393')) + length \u0393); eauto.\n    rewrite splice_open. rewrite splice_open.\n    replace (S (S (length \u0393') + length \u0393)) with (S (length \u0393') + (S (length \u0393))); eauto.\n    rewrite splice_open.\n    replace (S (length \u0393' + length \u0393)) with ((length \u0393') + (S (length \u0393))); eauto.\n    rewrite splice_open.\n    erewrite <- open_rec_tm_commute' with (t':=$(length \u0393)); intuition.\n    erewrite <- open_rec_tm_commute' with (t':=$(length \u0393)); intuition.\n    erewrite <- open_rec_tm_commute' with (t':=$(S (length \u0393))); intuition.\n    erewrite <- open_rec_tm_commute' with (t':=$(S (length \u0393))); intuition.\n    replace (S (S (length \u0393') + S (length \u0393))) with (S (length \u0393' + S (S (length \u0393)))); eauto.\n    replace (S (length \u0393' + S (length \u0393))) with (length \u0393' + S (S (length \u0393))).\n    apply HTt. auto. lia. eapply strengthen_stp. eapply strengthen_stp; eauto. Unshelve.\n    all: auto.\n  - apply typ_inv_app in H0. destruct H0 as [T3 [Hfun Harg]].\n    apply (t_app _ _ _ _ T3 T). eapply IHn; eauto. lia. eapply IHn; eauto. lia.\n  - apply typ_inv_loc in H0. destruct H0 as [U [Hl Hstp]]. inversion Hstp. subst.\n    apply t_loc. auto.\n  - apply typ_inv_ref in H0. destruct H0 as [U [Heq HTU]]. subst. apply t_ref.\n    eapply IHn; eauto. lia.\n  - apply typ_inv_deref in H0. destruct H0 as [U [HTU Hstp]].\n    apply (t_sub _ _ _ U T). apply t_deref. eapply IHn; eauto. lia.\n    eapply strengthen_stp; eauto. eapply strengthen_stp; eauto.\n  - apply typ_inv_assign in H0. destruct H0 as [Heq [U [HTlhs HTrhs]]]. subst.\n    apply t_assign with (T:=U); eapply IHn; eauto; lia.\nQed.\n\nLemma substitution : forall{\u0393 Tf Tx T \u03a3 t},\n    closed_tm 2 (length \u0393) (length \u03a3) t ->\n    has_type (Tx :: Tf :: \u0393) \u03a3 (open_tm' \u0393 t) T ->\n    forall {tf}, has_type \u0393 \u03a3 tf Tf -> forall {tx}, has_type \u0393 \u03a3 tx Tx -> has_type \u0393 \u03a3 (open_tm tf tx t) T.\n  intros. unfold open_tm' in *. unfold open_tm in *. replace \u0393 with ([] ++ \u0393); eauto.\n  eapply substitution_gen; eauto. erewrite (@splice_id t); eauto. erewrite splice_id; eauto.\n  eapply closed_tm_monotone; eauto; lia.\nQed.\n\nDefinition CtxOK (\u0393 : tenv) (\u03a3 : senv) (\u03c3 : store) : Prop :=\n  length \u03a3 = length \u03c3 /\\ forall l v T, indexr l \u03a3 = Some T -> indexr l \u03c3 = Some v -> value v /\\ has_type \u0393 \u03a3 v T.\n\nLemma CtxOK_ext : forall {\u0393 \u03a3 \u03c3}, CtxOK \u0393 \u03a3 \u03c3 -> forall {v T}, has_type \u0393 \u03a3 v T -> value v -> CtxOK \u0393 (T :: \u03a3) (v :: \u03c3).\n  intros. unfold CtxOK in *. split. simpl. lia.\n  intros. destruct H as [Hlen Hprev]. destruct (beq_nat l (length \u03c3)) 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. apply extends_cons.\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. apply extends_cons.\nQed.\n\nLemma CtxOK_update : forall {\u0393 \u03a3 \u03c3}, CtxOK \u0393 \u03a3 \u03c3 -> forall {l T}, l < length \u03c3 -> indexr l \u03a3 = Some T -> forall {v}, has_type \u0393 \u03a3 v T -> value v -> CtxOK \u0393 \u03a3 (update \u03c3 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 beq_nat_true in Heq. subst.\n    apply (@update_indexr_hit \u03c3 l0 v) in H0. rewrite H1 in H. inversion H. subst.\n    rewrite H4 in H0. inversion H0. subst. intuition.\n  - apply beq_nat_false in Heq. apply (@update_indexr_miss \u03c3 l v l0) in Heq.\n    rewrite Heq in H4. eapply Hprev; eauto.\nQed.\n\nLemma progress : forall {\u03a3 t T}, has_type [] \u03a3 t T -> value t \\/ forall {\u03c3}, CtxOK [] \u03a3 \u03c3 -> exists t' \u03c3', step t \u03c3 t' \u03c3'.\n  intros \u03a3 t T HT. remember [] as \u0393; induction HT; subst; try solve [left; constructor].\n  - inversion H.\n  - (*tapp*) right; intuition.\n    + specialize (canonical_fun HT1 H1) as Hlam. destruct Hlam as [t' Heq]. subst.\n      exists (open_tm (tabs t') t2 t'). exists \u03c3. constructor. auto.\n    + apply H1 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tapp t' t2). exists \u03c3'. constructor. auto.\n    + apply H0 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tapp t1 t'). exists \u03c3'. constructor; auto.\n    + apply H1 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tapp t' t2). exists \u03c3'. constructor. auto.\n  - (*tref*) right; intuition.\n    + exists &(length \u03c3). exists (t :: \u03c3). constructor. auto.\n    + apply H0 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tref t'). exists \u03c3'. constructor. auto.\n  - (*tderef*) right; intuition.\n    + specialize (canonical_ref HT H0) as Hc. destruct Hc as [l Heq]. subst.\n      apply typ_inv_loc in HT. destruct HT as [U [Hlookup Hstp]].\n      pose (Hl:=Hlookup).\n      unfold CtxOK in H. intuition. apply indexr_var_some' in Hl.\n      rewrite H1 in Hl. rewrite <- indexr_var_some in Hl.\n      destruct Hl as [v Hl]. exists v. exists \u03c3. constructor. auto.\n      specialize (H2 l v U Hlookup Hl). intuition.\n    + apply H0 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tderef t'). exists \u03c3'. constructor. auto.\n  - (*tassign*) right; intuition.\n    + specialize (canonical_ref HT1 H1) as Href. destruct Href as [l Heq]. subst.\n      exists tunit. exists (update \u03c3 l t2). constructor. apply typ_inv_loc in HT1.\n      destruct HT1 as [U [Hl Hstp]]. unfold CtxOK in H. intuition. rewrite <- H2.\n      eapply indexr_var_some'. eauto. auto.\n    + apply H1 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tassign t' t2). exists \u03c3'. constructor. auto.\n    + apply H0 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tassign t1 t'). exists \u03c3'. constructor; auto.\n    + apply H1 in H. destruct H as [t' [\u03c3' Hstep]]. exists (tassign t' t2). exists \u03c3'. constructor. auto.\n  - (*tsub*) intuition.\nQed.\n\nLemma preservation : forall {\u0393 \u03a3 t T}, has_type \u0393 \u03a3 t T -> forall{\u03c3}, CtxOK \u0393 \u03a3 \u03c3 -> forall {t' \u03c3'}, step t \u03c3 t' \u03c3' -> exists \u03a3', \u03a3' \u2287 \u03a3 /\\ CtxOK \u0393 \u03a3' \u03c3' /\\ has_type \u0393 \u03a3' t' T .\n  intros \u0393 \u03a3 t T HT. induction HT; intros; try solve [inversion H0]; try solve [inversion H1].\n  - (*tapp*) inversion H0; subst.\n    + (*beta*) inversion H0; subst. pose (Ht2c := HT2). apply has_type_closed in Ht2c.\n      * exists \u03a3. intuition. apply extends_refl.\n        apply typ_inv_abs in HT1. destruct HT1 as [T3 [T4 [Hc [HTt Hstp]]]].\n        inversion Hstp. subst.\n        apply weaken_stp with (T' := TFun T3 T4) in H9.\n        specialize (narrowing HTt H9) as HTt'.\n        apply (t_sub _ _ _ T4 T2); eauto.\n        eapply substitution; eauto.\n        apply t_abs; eauto.\n      * inversion H7.\n      * specialize (values_stuck H6 H8) as Hsp. contradiction.\n    + apply (IHHT1 \u03c3 H t1' \u03c3') in H6. destruct H6 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition. eapply t_app; eauto. eapply weaken_store; eauto.\n    + apply (IHHT2 \u03c3 H t2' \u03c3') in H7. destruct H7 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition. eapply t_app; eauto. eapply weaken_store; eauto.\n  - (* tref *) inversion H0; subst.\n    + exists (T :: \u03a3). intuition. apply extends_cons. apply CtxOK_ext; auto.\n      apply t_loc. unfold CtxOK in H. intuition. rewrite <- H1. apply indexr_head.\n    + apply (IHHT \u03c3 H t'0 \u03c3') in H2. destruct H2 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition.\n  - (* tderef *) inversion H0; subst.\n    + exists \u03a3. intuition. apply extends_refl. apply typ_inv_loc in HT. destruct HT as [U [Hlook Hstp]].\n      unfold CtxOK in H. intuition. specialize (H4 _ _ _ Hlook H2). intuition.\n      eapply t_sub. eauto. inversion Hstp. subst. apply stp_refl.\n    + apply (IHHT \u03c3 H t'0 \u03c3') in H2. destruct H2 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition.\n  - (* tassign *) inversion H0; subst.\n    + exists \u03a3. intuition. apply extends_refl. eapply CtxOK_update; eauto.\n      apply typ_inv_loc in HT1. destruct HT1 as [U [Hl Hstp]].\n      inversion Hstp. subst. auto.\n    + apply (IHHT1 \u03c3 H t1' \u03c3') in H6. destruct H6 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition. eapply t_assign; eauto. eapply weaken_store; eauto.\n    + apply (IHHT2 \u03c3 H t2' \u03c3') in H7. destruct H7 as [\u03a3' [Hext [HOK Ht']]].\n      exists \u03a3'. intuition. eapply t_assign; eauto. eapply weaken_store; eauto.\n  - (* tsub *) apply (IHHT \u03c3 H0 t' \u03c3') in H1. destruct H1 as [\u03a3' [Hext [HOK Ht']]].\n    exists \u03a3'. intuition. eapply t_sub; eauto. eapply weaken_stp_store; eauto.\nQed.\n", "meta": {"author": "bracevac", "repo": "coqatrice", "sha": "e9263a0625b9edd45f2520d83c3c69722d01a920", "save_path": "github-repos/coq/bracevac-coqatrice", "path": "github-repos/coq/bracevac-coqatrice/coqatrice-e9263a0625b9edd45f2520d83c3c69722d01a920/stlc_ref_sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.19758571675396658}}
{"text": "\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Ordinal.\nRequire Import Relation.\nRequire Import Ofe.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Hygiene.\nRequire Import Uniform.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Dynamic.\nRequire Import Equivalence.\nRequire Import Equivalences.\nRequire Import Candidate.\nRequire Import Model.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import Standard.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import System.\nRequire Import Page.\nRequire Export PreSpacify.\nRequire Import Spaces.\nRequire Import SemanticsKnot.\nRequire Import ProperClosed.\nRequire Import ProperEquiv.\nRequire Import ProperFun.\nRequire Import ProperDownward.\nRequire Import ProperLevel.\nRequire Import Constructor.\nRequire Import Semantics.\nRequire Import SemanticsUniv.\nRequire Import SemanticsPi.\nRequire Import SemanticsFut.\nRequire Import SemanticsSimple.\nRequire Import SemanticsProperty.\nRequire Import SemanticsSigma.\n\n\nLemma interp_kext_kext :\n  forall pg i K,\n    level K <<= cin pg\n    -> interp_kext pg i (kext stop K) (approx i K).\nProof.\nintros pg i K Hlev.\nso (le_ord_succ _ _ (le_ord_trans _#3 Hlev (cin_top pg))) as fit.\nexists (expair K (space_inhabitant _)), fit.\ndo2 3 split; auto using kext_hygiene.\nunfold kext.\nunfold stop.\nrewrite -> (lt_ord_dec_is _ _ fit).\napply star_refl.\nQed.\n\n\nLemma interp_uext_uext :\n  forall pg i w (R : wurel w),\n    w <<= cin pg\n    -> interp_uext pg i (uext stop R) (ceiling (S i) (extend_urel w (cin pg) R)).\nProof.\nintros pg i w R Hlev.\nso (le_ord_succ _ _ (le_ord_trans _#3 Hlev (cin_top pg))) as fit.\nexists w, (iubase R), fit.\ndo2 3 split; auto using uext_hygiene.\nunfold uext.\nunfold stop.\nrewrite -> (lt_ord_dec_is _ _ fit).\napply star_refl.\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, fromsp_hygiene, tosp_hygiene, kext_hygiene, uext_hygiene, pagelit_closed;\n  try (apply hygiene_var; cbn; auto; done).\n\n\nLemma cty_formation :\n  forall pg i j a b,\n    rel (univ_urel the_system i pg) j a b\n    -> rel (con_urel pg (qtype (cin pg))) j (cty a) (cty b).\nProof.\nintros pg i j a b Hab.\ndestruct Hab as (Hj & R & Ha & Hb).\nrewrite -> sint_unroll in Ha, Hb.\ncbn.\nso (interp_level_internal _#5 (cin_stop pg) Ha) as (R' & ->).\nunfold con_action.\ncbn [approx].\nexists R'.\nsplit.\n  {\n  apply cinterp_eval_refl.\n  apply interp_cty; auto.\n  }\n\n  {\n  apply cinterp_eval_refl.\n  apply interp_cty; auto.\n  }\nQed.\n\n\nLemma con_formation :\n  forall pg i lv lv' j a b,\n    j <= i\n    -> pginterp lv pg\n    -> pginterp lv' pg\n    -> rel (con_urel pg (qtype (cin pg))) j a b\n    -> rel (univ_urel the_system i pg) j (con lv a) (con lv' b).\nProof.\nintros pg i lv lv' j a b Hj Hlv Hlv' Hab.\ndestruct Hab as (R & Ha & Hb).\ncbn [approx] in R, Ha, Hb.\nsplit; auto.\nunfold spcar in R; cbn [space] in R.\nexists (extend_iurel (cin_stop pg) R).\nrewrite -> sint_unroll.\nsplit.\n  {\n  apply interp_eval_refl.\n  apply interp_con; auto using le_page_refl.\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_con; auto using le_page_refl.\n  }\nQed.\n\n\nDefinition spacification pg i K A :=\n  K = approx i K\n  /\\\n  (forall j u v,\n     j <= i\n     -> j <= u\n     -> j <= v\n     -> rel (arrow_urel stop i (den A) (con_urel pg K)) j\n          (tosp stop pg (approx u K)) (tosp stop pg (approx v K)))\n  /\\\n  (forall j u v,\n     j <= i\n     -> j <= u\n     -> j <= v\n     -> rel (arrow_urel stop i (con_urel pg K) (den A)) j\n          (fromsp stop pg (approx u K)) (fromsp stop pg (approx v K)))\n  /\\\n  (forall j m p,\n     j <= i\n     -> rel (den A) j m p\n     -> rel (den A) j (app (fromsp stop pg K) (app (tosp stop pg K) m)) p)\n  /\\\n  (forall j a b,\n     j <= i\n     -> rel (con_urel pg K) j a b\n     -> rel (con_urel pg K) j (app (tosp stop pg K) (app (fromsp stop pg K) a)) b).\n\n\nLemma spacify_main :\n  forall pg s i k K,\n    kinterp pg s i k K\n    -> exists A, interp toppg s i k A /\\ spacification pg i K A.\nProof.\nexploit\n  (semantics_ind the_system\n     (fun pg s i k K =>\n        exists A,\n          interpv toppg s i k A\n          /\\\n          (forall j u v,\n             j <= i\n             -> j <= u\n             -> j <= v\n             -> rel (arrow_urel stop i (den A) (con_urel pg K)) j\n                  (tosp stop pg (approx u K)) (tosp stop pg (approx v K)))\n          /\\\n          (forall j u v,\n             j <= i\n             -> j <= u\n             -> j <= v\n             -> rel (arrow_urel stop i (con_urel pg K) (den A)) j\n                  (fromsp stop pg (approx u K)) (fromsp stop pg (approx v K)))\n          /\\\n          (forall j m p,\n             j <= i\n             -> rel (den A) j m p\n             -> rel (den A) j (app (fromsp stop pg K) (app (tosp stop pg K) m)) p)\n          /\\\n          (forall j a b,\n             j <= i\n             -> rel (con_urel pg K) j a b\n             -> rel (con_urel pg K) j (app (tosp stop pg K) (app (fromsp stop pg K) a)) b))\n     (fun _ _ _ _ _ => True)\n     (fun _ _ _ _ _ => True)\n     (fun pg s i k K =>\n        exists A,\n          interp toppg s i k A\n          /\\\n          (forall j u v,\n             j <= i\n             -> j <= u\n             -> j <= v\n             -> rel (arrow_urel stop i (den A) (con_urel pg K)) j\n                  (tosp stop pg (approx u K)) (tosp stop pg (approx v K)))\n          /\\\n          (forall j u v,\n             j <= i\n             -> j <= u\n             -> j <= v\n             -> rel (arrow_urel stop i (con_urel pg K) (den A)) j\n                  (fromsp stop pg (approx u K)) (fromsp stop pg (approx v K)))\n          /\\\n          (forall j m p,\n             j <= i\n             -> rel (den A) j m p\n             -> rel (den A) j (app (fromsp stop pg K) (app (tosp stop pg K) m)) p)\n          /\\\n          (forall j a b,\n             j <= i\n             -> rel (con_urel pg K) j a b\n             -> rel (con_urel pg K) j (app (tosp stop pg K) (app (fromsp stop pg K) a)) b))\n     (fun _ _ _ _ _ => True)\n     (fun _ _ _ _ _ => True)\n     (fun _ _ _ _ _ _ => True)) as Hind; auto.\n\n(* unit *)\n{\nintros ps s i.\neexists.\ndo2 4 split.\n  {\n  apply interp_unit.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; auto; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  exists tt.\n  split; apply cinterp_eval_refl; apply interp_cunit.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; auto; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  apply property_action_triv; auto.\n  omega.\n  }\n\n  {\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  cbn in Hmp.\n  destruct Hmp as (_ & _ & _ & _ & _ & Hp).\n  cbn.\n  do2 5 split; auto using star_refl.\n  prove_hygiene.\n  }\n\n  {\n  intros j a b Hj Hab.\n  cbn [fromsp tosp].\n  so (urel_closed _#5 Hab) as (Hcla & Hclb).\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv.\n    {\n    prove_hygiene.\n    }\n  destruct Hab as (R & Ha & Hb).\n  cbn [approx] in R, Ha, Hb.\n  exists R.\n  split; auto.\n  cbn in R.\n  destruct R.\n  apply cinterp_eval_refl.\n  apply interp_cunit.\n  }\n}\n\n(* type *)\n{\nintros pg s i lv Hintpg.\nso (pginterp_str_top _ _ Hintpg) as Hstr.\nso (pginterp_cex_top _ _ Hintpg) as Hcex.\nso (pginterp_impl_pagelit _ _ Hintpg) as Hpg.\neexists.\ndo2 4 split.\n  {\n  apply interp_univ; eauto.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  cbn [tosp approx].\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  eapply (cty_formation _ i); auto.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  cbn [fromsp approx].\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  apply con_formation; simpsub; auto.\n  omega.\n  }\n\n  {\n  intros j m p Hj Hmp.\n  cbn [fromsp tosp].\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_con; [apply equiv_refl |].\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  cbn in Hmp.\n  destruct Hmp as (_ & R & Hm & Hp).\n  cbn.\n  split; auto.\n  exists R.\n  split; auto.\n  rewrite -> sint_unroll in Hm |- *.\n  so (interp_level_internal _#5 (cin_stop pg) Hm) as (R' & ->).\n  apply interp_eval_refl.\n  apply interp_con; auto using le_page_refl.\n  apply cinterp_eval_refl.\n  apply interp_cty; auto.\n  }\n\n  {\n  intros j a b Hj Hab.\n  cbn [fromsp tosp].\n  so (urel_closed _#5 Hab) as (Hcla & Hclb).\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_cty.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv.\n    {\n    prove_hygiene.\n    }\n  destruct Hab as (R & Ha & Hb).\n  cbn [approx] in R, Ha, Hb.\n  exists R.\n  split; auto.\n  apply cinterp_eval_refl.\n  apply interp_cty.\n  apply interp_eval_refl.\n  apply interp_con; auto using le_page_refl.\n  }\n}\n\n(* karrow *)\n{\nintros pg s i k l K L Hk IH1 Hl IH2.\ndestruct IH1 as (A & HintA & IH1a & IH1b & IH1c & IH1d).\ndestruct IH2 as (B & HintB & IH2a & IH2b & IH2c & IH2d).\nso (kinterp_level_bound _#5 Hk) as HlevK.\nso (kinterp_level_bound _#5 Hl) as HlevL.\neexists.\ndo2 4 split.\n  {\n  apply interp_karrow_type; eauto.\n  }\n\n  (* karrow tosp *)\n  {\n  clear IH1a IH1c IH1d IH2b IH2c IH2d.\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; try prove_hygiene.\n  intros j p q Hj Hpq.\n  simpsub.\n  so (urel_closed _#5 Hpq) as (Hclp & Hclq).\n  apply con_urel_raise.\n  cbn [approx].\n  apply clam_formation; auto using interp_kext_kext.\n    {\n    symmetry.\n    apply approx_idem.\n    }\n\n    {\n    relquest.\n      {\n      apply interp_kext_kext.\n      eapply le_ord_trans; eauto using approx_level.\n      }\n    rewrite -> approx_combine_le; auto.\n    omega.\n    }\n\n    {\n    relquest.\n      {\n      apply interp_kext_kext.\n      eapply le_ord_trans; eauto using approx_level.\n      }\n    rewrite -> approx_combine_le; auto.\n    omega.\n    }\n  intros j' c d Hj' Hcd.\n  simpsub.\n  assert (j' <= u) as Hj'_u by omega.\n  apply con_urel_raise.\n  rewrite -> approx_combine_le; auto.\n  apply con_urel_lower.\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_u (IH2a u v w Hu Hv Hw)) _).\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj' Hpq) _).\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_u (IH1b u v w Hu Hv Hw)) _).\n  apply con_urel_raise.\n  so (con_urel_lower _#5 Hcd) as H.\n  rewrite -> approx_combine_le in H; auto.\n  }\n\n  (* karrow fromsp *)\n  {\n  clear IH1b IH1c IH1d IH2a IH2c IH2d.\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m n Hj Hmn.\n  simpsub.\n  so (urel_closed _#5 Hmn) as (Hclm & Hcln).\n  apply arrow_action_lam; try prove_hygiene.\n    {\n    omega.\n    }\n  intros j' p q Hj' Hpq.\n  simpsub.\n  assert (j' <= u) as Hj'_u by omega.\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_u (IH2b u v w Hu Hv Hw)) _).\n  apply (capp_formation _ K).\n    {\n    apply (urel_downward_leq _#3 j); auto.\n    }\n  exact (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_u (IH1a u v w Hu Hv Hw)) Hpq).\n  }\n\n  (* karrow beta *)\n  {\n  clear IH1d IH2d.\n  so (IH1a i i i (le_refl _) (le_refl _) (le_refl _)) as IH1ai.\n  so (IH1b i i i (le_refl _) (le_refl _) (le_refl _)) as IH1bi.\n  so (IH2a i i i (le_refl _) (le_refl _) (le_refl _)) as IH2ai.\n  so (IH2b i i i (le_refl _) (le_refl _) (le_refl _)) as IH2bi.\n  rewrite <- (kbasic_impl_approx _#6 Hk) in IH1ai, IH1bi.\n  rewrite <- (kbasic_impl_approx _#6 Hl) in IH2ai, IH2bi.\n  clear IH1a IH1b IH2a IH2b.\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  cbn [fromsp tosp].\n  rewrite -> den_iuarrow.\n  match goal with\n  | |- rel _ _ ?X _ =>\n      eassert (equiv X _) as Hequiv\n  end.\n    {\n    eapply equiv_trans.\n      {\n      apply steps_equiv.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    eapply equiv_trans.\n      {\n      apply equiv_lam.\n      apply equiv_app; [apply equiv_refl |].\n      apply equiv_capp; [| apply equiv_refl].\n      apply steps_equiv.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    replace (1 + 1) with 2 by omega.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ (equiv_symm _#3 Hequiv) _).\n    {\n    prove_hygiene.\n    }\n  clear Hequiv.\n  refine (arrow_action_lam1 _#8 _ Hmp _).\n    {\n    prove_hygiene.\n    }\n  intros j' n q Hj' Hnq.\n  simpsub.\n  so (le_trans _#3 Hj' Hj) as Hj'_i.\n  so (IH1c j' n q Hj'_i Hnq) as Hetan_q.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj' Hmp) Hetan_q) as Hmetan_pq.\n  so (IH2c j' _ _ Hj'_i Hmetan_pq) as Hetametan_pq.\n  exploit (capp_clam_beta_double pg (approx j' K) (approx j' L) j' (kext stop K)\n             (app (tosp stop pg L) (app (subst sh1 m) (app (fromsp stop pg K) (var 0))))\n             (app (tosp stop pg L) (app (subst sh1 p) (app (fromsp stop pg K) (var 0))))\n             (app (tosp stop pg K) n)\n             (app (tosp stop pg K) q)) as H.\n    {\n    symmetry.\n    apply approx_idem.\n    }\n\n    {\n    apply interp_kext_kext; auto.\n    }\n\n    {\n    intros j'' c d Hj'' Hcd.\n    simpsub.\n    so (le_trans _#3 Hj'' Hj'_i) as Hj''_i.\n    apply con_urel_raise.\n    rewrite -> approx_combine_le; auto.\n    apply con_urel_lower.\n    refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj''_i IH2ai) _).\n    refine (arrow_action_app _#9 (urel_downward_leq _#6 (le_trans _#3 Hj'' Hj') Hmp) _).\n    refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj''_i IH1bi) _).\n    so (con_urel_lower _#5 Hcd) as H.\n    rewrite -> approx_combine_le in H; auto.\n    apply con_urel_raise; auto.\n    }\n\n    {\n    apply con_urel_lower.\n    exact (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_i IH1ai) Hnq).\n    }\n  simpsubin H.\n  so (con_urel_raise _#5 (H andel)) as Hredex.\n  so (con_urel_raise _#5 (H ander)) as Hcontractum.\n  clear H.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_i IH2bi) Hredex) as Hfromredex.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_i IH2bi) Hcontractum) as Hfromcontractum.\n  exact (urel_zigzag _#7 Hfromredex Hfromcontractum Hetametan_pq).\n  }\n\n  (* karrow eta *)\n  {\n  clear IH1a IH1b IH1c IH2a IH2b IH2c.\n  intros j a b Hj Hab.\n  so (urel_closed _#5 Hab) as (Hcla & Hclb).\n  cbn [tosp fromsp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    apply equiv_clam; [apply equiv_refl |].\n    apply equiv_app; [apply equiv_refl |].\n    eapply equiv_trans.\n      {\n      apply equiv_app; [| apply equiv_refl].\n      eapply equiv_trans.\n        {\n        apply steps_equiv.\n        apply star_one.\n        apply step_app2.\n        }\n      simpsub.\n      replace (1 + 1) with 2 by omega.\n      apply equiv_refl.\n      }\n    eapply equiv_trans.\n      {\n      apply steps_equiv.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  clear Hequiv.\n  so (con_urel_lower _#5 Hab) as H.\n  cbn in H.\n  so (clam_capp_eta _#7 (eqsymm (approx_idem _ _)) (interp_kext_kext pg j K HlevK) H) as H12; clear H.\n  exploit (clam_formation pg (approx j K) (approx j L) j (kext stop K) (kext stop K) (capp (subst sh1 a) (var 0)) (capp (subst sh1 b) (var 0))) as H13; auto using interp_kext_kext.\n    {\n    symmetry.\n    apply approx_idem.\n    }\n\n    {\n    intros j' c d Hj' Hcd.\n    simpsub.\n    apply con_urel_lower'; auto.\n    apply (capp_formation _ K).\n      {\n      eapply urel_downward_leq; eauto.\n      }\n    \n      {\n      apply (con_urel_raise' _#6 Hj'); auto.\n      }\n    }\n  exploit (clam_formation pg (approx j K) (approx j L) j (kext stop K) (kext stop K) (app (tosp stop pg L) (app (fromsp stop pg L) (capp (subst sh1 a) (app (tosp stop pg K) (app (fromsp stop pg K) (var 0)))))) (capp (subst sh1 b) (var 0))) as H43; auto using interp_kext_kext.\n    {\n    symmetry.\n    apply approx_idem.\n    }\n\n    {\n    intros j' c d Hj' Hcd.\n    simpsub.\n    apply con_urel_lower'; auto.\n    apply IH2d; [omega |].\n    apply (capp_formation _ K); eauto using urel_downward_leq.\n    apply IH1d; [omega |].\n    apply (con_urel_raise' _#3 j); auto.\n    }\n  so (urel_zigzag _#7 H43 H13 H12) as H.\n  apply con_urel_raise.\n  exact H.\n  }\n}\n\n(* ktarrow *)\n{\nintros pg s i a k A K Ha _ Hk IH.\ndestruct IH as (B & HintB & IHa & IHb & IHc & IHd).\nso (kinterp_level_bound _#5 Hk) as HlevK.\nset (l := cin pg) in *.\nset (fit := cin_stop pg) in *.\nso (le_ord_succ _ _ (le_ord_trans _#3 HlevK (cin_top pg))) as kfit.\nchange (level K << stop) in kfit.\neexists.\ndo2 4 split.\n  {\n  apply interp_arrow; eauto.\n  exact (interp_increase _#6 (toppg_max pg) Ha).\n  }\n\n  (* ktarrow tosp *)\n  {\n  clear IHb IHc IHd.\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  apply con_urel_raise.\n  cbn [approx].\n  rewrite <- den_iutruncate.\n  assert (interp_uext pg j (uext stop (den A)) (den (iutruncate (S j) A))) as Huext.\n    {\n    so (interp_uext_uext pg j l (den A) (le_ord_refl _)) as H.\n    rewrite -> extend_urel_id in H.\n    rewrite -> den_iutruncate.\n    exact H.\n    }\n  apply ctlam_formation; auto using interp_kext_kext; try prove_hygiene.\n    {\n    relquest.\n      {\n      apply interp_uext_uext.\n      apply le_ord_refl.\n      }\n    rewrite -> den_iutruncate.\n    rewrite -> extend_urel_id.\n    rewrite -> ceiling_combine_le; auto.\n    omega.\n    }\n\n    {\n    relquest.\n      {\n      apply interp_uext_uext.\n      apply le_ord_refl.\n      }\n    rewrite -> den_iutruncate.\n    rewrite -> extend_urel_id.\n    rewrite -> ceiling_combine_le; auto.\n    omega.\n    }\n\n    {\n    relquest.\n      {\n      apply interp_kext_kext.\n      eapply le_ord_trans; eauto using approx_level.\n      }\n    rewrite -> approx_combine_le; auto.\n    omega.\n    }\n\n    {\n    relquest.\n      {\n      apply interp_kext_kext.\n      eapply le_ord_trans; eauto using approx_level.\n      }\n    rewrite -> approx_combine_le; auto.\n    omega.\n    }\n  intros j' n q Hnq.\n  simpsub.\n  rewrite -> den_iutruncate in Hnq.\n  destruct Hnq as (H & Hnq).\n  assert (j' <= j) as Hj' by omega; clear H.\n  apply con_urel_lower'; auto.\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 (le_trans _#3 Hj' Hj) (IHa u v w Hu Hv Hw)) _).\n  apply (arrow_action_app stop i (extend_urel _ _ (den A))); auto.\n  exact (urel_downward_leq _#6 Hj' Hmp).\n  }\n\n  (* ktarrow fromsp *)\n  {\n  clear IHa IHc IHd.\n  intros u v w Hu Hv Hw.\n  cbn [fromsp approx].\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  rewrite -> den_iuarrow.\n  apply arrow_action_lam; try prove_hygiene.\n    {\n    omega.\n    }\n  intros j' n q Hj' Hnq.\n  simpsub.\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 (le_trans _#3 Hj' Hj) (IHb u v w Hu Hv Hw)) _).\n  apply (ctapp_formation _ (den A)).\n    {\n    exact (urel_downward_leq _#6 Hj' Hmp).\n    }\n\n    {\n    exact Hnq.\n    }\n  }\n\n  (* ktarrow beta *)\n  {\n  so (IHa i i i (le_refl _) (le_refl _) (le_refl _)) as IHai.\n  so (IHb i i i (le_refl _) (le_refl _) (le_refl _)) as IHbi.\n  rewrite <- (kbasic_impl_approx _#6 Hk) in IHai, IHbi.\n  clear IHa IHb IHd.\n  intros j m p Hj Hmp.\n  rewrite -> den_iuarrow in Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  rewrite -> den_iuarrow.\n  rewrite -> den_extend_iurel.\n  cbn [fromsp tosp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_lam.\n    apply equiv_app; [apply equiv_refl |].\n    apply equiv_ctapp; [| apply equiv_refl].\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    replace (1 + 1) with 2 by omega.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv.\n    {\n    prove_hygiene.\n    }\n  apply (arrow_action_lam1 _#6 m); auto.\n    {\n    prove_hygiene.\n    }\n  intros j' n q Hj' Hnq.\n  simpsub.\n  exploit (ctapp_ctlam_beta_double pg (ceiling (S j') (den A)) (approx j' K) j' (uext stop (den A)) \n             (app (tosp stop pg K) (app (subst sh1 m) (var 0)))\n             (app (tosp stop pg K) (app (subst sh1 p) (var 0)))\n             (kext stop K)\n             n q); auto using interp_kext_kext; try prove_hygiene.\n    {\n    so (interp_uext_uext pg j' l (den A) (le_ord_refl _)) as H.\n    rewrite -> extend_urel_id in H.\n    exact H.\n    }\n\n    {\n    intros j'' r t Hrt.\n    simpsub.\n    destruct Hrt as (H & Hrt).\n    assert (j'' <= j') as Hj'' by omega; clear H.\n    assert (j'' <= i) as Hj''_i by omega.\n    apply con_urel_lower'; auto.\n    refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj''_i IHai) _).\n    exact (arrow_action_app _#9 (urel_downward_leq _#6 (le_trans _#3 Hj'' Hj') Hmp) Hrt).\n    }\n\n    {\n    split; auto.\n    }\n  simpsubin H.\n  destruct H as (H1 & H2).\n  so (con_urel_raise _#5 H1) as Hredex.\n  so (con_urel_raise _#5 H2) as Hcontractum.\n  clear H1 H2.\n  assert (j' <= i) as Hj'_i by omega.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_i IHbi) Hredex) as H.\n  renameover H into Hredex.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj'_i IHbi) Hcontractum) as H.\n  renameover H into Hcontractum.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj' Hmp) Hnq) as Hmn_pq.\n  so (IHc _#3 Hj'_i Hmn_pq) as H.\n  exact (urel_zigzag _#7 Hredex Hcontractum H).\n  }\n\n  (* ktarrow eta *)\n  {\n  clear IHa IHb IHc.\n  intros j b c Hj Hbc.\n  so (urel_closed _#5 Hbc) as (Hb & Hc).\n  cbn [tosp fromsp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_ctlam; [apply equiv_refl | | apply equiv_refl].\n    apply equiv_app; [apply equiv_refl |].\n    eapply equiv_trans.\n      {\n      apply equiv_app; [| apply equiv_refl].\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv.\n    {\n    prove_hygiene.\n    }\n  so (interp_uext_uext pg j l (den A) (le_ord_refl _)) as Huext.\n  rewrite -> extend_urel_id in Huext.\n  so (con_urel_lower _#5 Hbc) as H.\n  cbn [approx] in H.\n  so (ctlam_ctapp_eta _#8 (interp_kext_kext pg j K HlevK) Huext H) as Heta; clear H.\n  change (rel (con_urel pg (approx j (qtarrow (cin pg) (den A) K))) j (ctlam (uext stop (den A)) (ctapp (subst sh1 b) (var 0)) (kext stop K)) c) in Heta.\n  so (con_urel_raise _#5 Heta) as H; renameover H into Heta.\n  refine (urel_zigzag _#4 (ctlam (uext stop (den A)) (ctapp (subst sh1 c) (var 0)) (kext stop K)) _ _ _ _ Heta).\n    {\n    apply con_urel_raise.\n    cbn [approx].\n    apply ctlam_formation; auto using interp_kext_kext; try prove_hygiene.\n    intros j' m p Hmp.\n    simpsub.\n    so Hmp as (H & _).\n    assert (j' <= j) as Hj' by omega; clear H.\n    apply con_urel_lower'; auto.\n    apply IHd.\n      {\n      omega.\n      }\n    apply (ctapp_formation _ (den A)).\n      {\n      eapply urel_downward_leq; eauto.\n      }\n\n      {\n      exact (Hmp ander).\n      }\n    }\n\n    {\n    apply con_urel_raise.\n    cbn [approx].\n    apply ctlam_formation; auto using interp_kext_kext; try prove_hygiene.\n    intros j' m p Hmp.\n    simpsub.\n    so Hmp as (H & _).\n    assert (j' <= j) as Hj' by omega; clear H.\n    apply con_urel_lower'; auto.\n    apply (ctapp_formation _ (den A)).\n      {\n      eapply urel_downward_leq; eauto.\n      }\n\n      {\n      exact (Hmp ander).\n      }\n    }\n  }\n}\n\n(* kprod *)\n{\nintros pg s i k l K L Hk IH1 Hl IH2.\ndestruct IH1 as (A & HintA & IH1a & IH1b & IH1c & IH1d).\ndestruct IH2 as (B & HintB & IH2a & IH2b & IH2c & IH2d).\nso (kinterp_level_bound _#5 Hk) as HlevK.\nso (kinterp_level_bound _#5 Hl) as HlevL.\neexists.\ndo2 4 split.\n  {\n  apply interp_prod; eauto.\n  }\n\n\n\n\n\n  (* kprod tosp *)\n  {\n  clear IH1b IH1c IH1d IH2b IH2c IH2d.\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; try prove_hygiene.\n  intros j p q Hj Hpq.\n  simpsub.\n  so (urel_closed _#5 Hpq) as (Hclp & Hclq).\n  apply cpair_formation.\n    {\n    eapply arrow_action_app.\n      {\n      apply IH1a; omega.\n      }\n\n      {\n      eapply prod_action_ppi1.\n      exact Hpq.\n      }\n    }\n\n    {\n    eapply arrow_action_app.\n      {\n      apply IH2a; omega.\n      }\n\n      {\n      eapply prod_action_ppi2.\n      exact Hpq.\n      }\n    }\n  }\n\n  (* kprod fromsp *)\n  {\n  clear IH1a IH1c IH1d IH2a IH2c IH2d.\n  intros u v w Hu Hv Hw.\n  cbn.\n  apply arrow_action_lam; try prove_hygiene.\n  intros j p q Hj Hpq.\n  simpsub.\n  so (urel_closed _#5 Hpq) as (Hclp & Hclq).\n  apply prod_action_ppair.\n    {\n    eapply arrow_action_app.\n      {\n      apply IH1b; omega.\n      }\n    eapply cpi1_formation; eauto.\n    }\n\n    {\n    eapply arrow_action_app.\n      {\n      apply IH2b; omega.\n      }\n    eapply cpi2_formation; eauto.\n    }\n  }\n\n  (* kprod beta *)\n  {\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  clear IH1d IH2d.\n  so (IH1a i i i (le_refl _) (le_refl _) (le_refl _)) as IH1ai.\n  so (IH1b i i i (le_refl _) (le_refl _) (le_refl _)) as IH1bi.\n  so (IH2a i i i (le_refl _) (le_refl _) (le_refl _)) as IH2ai.\n  so (IH2b i i i (le_refl _) (le_refl _) (le_refl _)) as IH2bi.\n  rewrite <- (kbasic_impl_approx _#6 Hk) in IH1ai, IH1bi.\n  rewrite <- (kbasic_impl_approx _#6 Hl) in IH2ai, IH2bi.\n  cbn [fromsp tosp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n       eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_ppair.\n      {\n      apply equiv_app; [apply equiv_refl |].\n      eapply equiv_trans.\n        {\n        apply equiv_cpi1.\n        apply steps_equiv; apply star_one; apply step_app2.\n        }\n      simpsub.\n      apply equiv_refl.\n      }\n\n      {\n      apply equiv_app; [apply equiv_refl |].\n      eapply equiv_trans.\n        {\n        apply equiv_cpi2.\n        apply steps_equiv; apply star_one; apply step_app2.\n        }\n      simpsub.\n      apply equiv_refl.\n      }\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv; try prove_hygiene.\n  so (prod_action_ppi1 _#6 Hmp) as Hmp1.\n  so (prod_action_ppi2 _#6 Hmp) as Hmp2.\n  refine (prod_action_ppair1 _#8 _ Hmp _ _); try prove_hygiene.\n    {\n    apply (urel_zigzag _#4 (app (fromsp stop pg K) (app (tosp stop pg K) (ppi1 p))) (app (fromsp stop pg K) (app (tosp stop pg K) (ppi1 m)))); auto.\n      {\n      eapply arrow_action_app.\n        {\n        exact (urel_downward_leq _#6 Hj IH1bi).\n        }\n      eapply cpi1_cpair_beta; eauto.\n        {\n        eapply arrow_action_app; eauto.\n        exact (urel_downward_leq _#6 Hj IH1ai).\n        }\n      eapply arrow_action_app; eauto.\n      exact (urel_downward_leq _#6 Hj IH2ai).\n      }\n\n      {\n      eapply arrow_action_app.\n        {\n        exact (urel_downward_leq _#6 Hj IH1bi).\n        }\n      eapply arrow_action_app; eauto.\n      exact (urel_downward_leq _#6 Hj IH1ai).\n      }\n    }\n\n    {\n    apply (urel_zigzag _#4 (app (fromsp stop pg L) (app (tosp stop pg L) (ppi2 p))) (app (fromsp stop pg L) (app (tosp stop pg L) (ppi2 m)))); auto.\n      {\n      eapply arrow_action_app.\n        {\n        exact (urel_downward_leq _#6 Hj IH2bi).\n        }\n      eapply cpi2_cpair_beta; eauto.\n        {\n        eapply arrow_action_app; eauto.\n        exact (urel_downward_leq _#6 Hj IH1ai).\n        }\n      eapply arrow_action_app; eauto.\n      exact (urel_downward_leq _#6 Hj IH2ai).\n      }\n\n      {\n      eapply arrow_action_app.\n        {\n        exact (urel_downward_leq _#6 Hj IH2bi).\n        }\n      eapply arrow_action_app; eauto.\n      exact (urel_downward_leq _#6 Hj IH2ai).\n      }\n    }\n  }\n\n  (* kprod eta *)\n  {\n  clear IH1a IH1b IH1c IH2a IH2b IH2c.\n  intros j a b Hj Hab.\n  so (urel_closed _#5 Hab) as (Hcla & Hclb).\n  cbn [fromsp tosp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n       eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_cpair.\n      {\n      apply equiv_app; [apply equiv_refl |].\n      eapply equiv_trans.\n        {\n        apply equiv_ppi1.\n        apply steps_equiv; apply star_one; apply step_app2.\n        }\n      simpsub.\n      apply steps_equiv; apply star_one; apply step_ppi12.\n      }\n\n      {\n      apply equiv_app; [apply equiv_refl |].\n      eapply equiv_trans.\n        {\n        apply equiv_ppi2.\n        apply steps_equiv; apply star_one; apply step_app2.\n        }\n      simpsub.\n      apply steps_equiv; apply star_one; apply step_ppi22.\n      }\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); clear Hequiv; try prove_hygiene.\n  apply (urel_zigzag _#4 (cpair (cpi1 b) (cpi2 b)) (cpair (cpi1 a) (cpi2 a))).\n    {\n    apply cpair_formation.\n      {\n      exact (IH1d j _ _ Hj (cpi1_formation _#6 Hab)).\n      }\n\n      {\n      exact (IH2d j _ _ Hj (cpi2_formation _#6 Hab)).\n      }\n    }\n\n    {\n    apply cpair_formation; eauto using cpi1_formation, cpi2_formation.\n    }\n\n    {\n    apply cpair_cpi_eta; auto.\n    }\n  }\n}\n\n(* kfut zero *)\n{\nintros pg s k Hclk.\neexists.\ndo2 4 split.\n  {\n  apply interp_fut_zero; auto.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  replace (approx v (qfut qone)) with (qfut qone).\n  2:{\n    destruct v; auto.\n    }\n  replace (approx w (qfut qone)) with (qfut qone).\n  2:{\n    destruct w; auto.\n    }\n  cbn [tosp approx].\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  assert (j = 0) by omega; subst j.\n  apply cnext_formation_zero; prove_hygiene.\n  }\n\n  {\n  intros u v w Hu Hv Hw.\n  replace (approx v (qfut qone)) with (qfut qone).\n  2:{\n    destruct v; auto.\n    }\n  replace (approx w (qfut qone)) with (qfut qone).\n  2:{\n    destruct w; auto.\n    }\n  cbn [fromsp approx].\n  apply arrow_action_lam; try prove_hygiene.\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  assert (j = 0) by omega; subst j.\n  cbn.\n  apply fut_action_next_zero; try prove_hygiene.\n  }\n\n  {\n  cbn [fromsp tosp].\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  assert (j = 0) by omega; subst j.\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  cbn in Hmp.\n  decompose Hmp.\n  intros _ q _ _ _ _ Hsteps _.\n  do 2 eexists.\n  do2 5 split; auto.\n    {\n    prove_hygiene.\n    }\n\n    {\n    apply star_refl.\n    }\n\n    {\n    exact Hsteps.\n    }\n\n    {\n    intro H; omega.\n    }\n  }\n\n  {\n  cbn [fromsp tosp].\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  assert (j = 0) by omega; subst j.\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  exists tt.\n  split.\n    {\n    apply cinterp_eval_refl.\n    apply interp_cnext_zero.\n    prove_hygiene.\n    }\n\n    {\n    destruct Hmp as (x & _ & Hp).\n    cbn in x.\n    destruct x.\n    exact Hp.\n    }\n  }\n}\n\n(* kfut *)\n{\nintros pg s i k K Hk IH.\ndestruct IH as (A & HA & IHa & IHb & IHc & IHd).\neexists.\ndo2 4 split.\n  {\n  apply interp_fut; eauto.\n  }\n\n  {\n  clear IHb IHc IHd.\n  assert (forall u,\n            exists m,\n              hygiene (permit clo) m\n              /\\ tosp stop pg (approx u (qfut K)) = lam (cnext m)) as Hform.\n    {\n    intros u.\n    destruct u as [| u].\n      {\n      cbn.\n      eexists.\n      split.\n      2:{\n        reflexivity.\n        }\n      prove_hygiene.\n      }\n  \n      {\n      cbn.\n      eexists.\n      split.\n      2:{\n        reflexivity.\n        }\n      prove_hygiene.\n      }\n    }\n  intros u v w Hu Hv Hw.\n  destruct u as [| u].\n    {\n    so (Hform v) as (a & Hcla & Heqa).\n    so (Hform w) as (b & Hclb & Heqb).\n    rewrite -> Heqa, -> Heqb; clear Heqa Heqb.\n    apply arrow_action_lam; try prove_hygiene.\n    intros j m p Hj Hmp.\n    so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n    assert (j = 0) by omega; subst j.\n    simpsub.\n    apply cnext_formation_zero; auto using hygiene_subst1.\n    }\n  assert (u <= i) as H by omega; renameover H into Hu.\n  destruct v as [| v].\n    {\n    omega.\n    }\n  assert (u <= v) as H by omega; renameover H into Hv.\n  destruct w as [| w].\n    {\n    omega.\n    }\n  assert (u <= w) as H by omega; renameover H into Hw.\n  cbn [tosp approx].\n  apply arrow_action_lam; try prove_hygiene.\n    {\n    cbn; omega.\n    }\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  destruct j as [| j].\n    {\n    apply cnext_formation_zero; prove_hygiene.\n    }\n  assert (j <= u) as H by omega; renameover H into Hj.\n  apply cnext_formation.\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj (IHa u v w Hu Hv Hw)) _).\n  eapply fut_action_prev; eauto.\n  exact Hmp.\n  }\n\n  {\n  clear IHa IHc IHd.\n  assert (forall u,\n            exists m,\n              hygiene (permit clo) m\n              /\\ fromsp stop pg (approx u (qfut K)) = lam (next m)) as Hform.\n    {\n    intros u.\n    destruct u as [| u].\n      {\n      cbn.\n      eexists.\n      split.\n      2:{\n        reflexivity.\n        }\n      prove_hygiene.\n      }\n  \n      {\n      cbn.\n      eexists.\n      split.\n      2:{\n        reflexivity.\n        }\n      prove_hygiene.\n      }\n    }\n  intros u v w Hu Hv Hw.\n  destruct u as [| u].\n    {\n    so (Hform v) as (a & Hcla & Heqa).\n    so (Hform w) as (b & Hclb & Heqb).\n    rewrite -> Heqa, -> Heqb; clear Heqa Heqb.\n    apply arrow_action_lam; try prove_hygiene.\n    intros j m p Hj Hmp.\n    so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n    assert (j = 0) by omega; subst j.\n    simpsub.\n    cbn.\n    apply fut_action_next_zero; try prove_hygiene; auto using hygiene_subst1.\n    }\n  assert (u <= i) as H by omega; renameover H into Hu.\n  destruct v as [| v].\n    {\n    omega.\n    }\n  assert (u <= v) as H by omega; renameover H into Hv.\n  destruct w as [| w].\n    {\n    omega.\n    }\n  assert (u <= w) as H by omega; renameover H into Hw.\n  cbn [fromsp approx].\n  apply arrow_action_lam; try prove_hygiene.\n    {\n    cbn; omega.\n    }\n  intros j m p Hj Hmp.\n  simpsub.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  rewrite -> den_iufut.\n  destruct j as [| j].\n    {\n    apply fut_action_next_zero; try prove_hygiene.\n    }\n  assert (j <= u) as H by omega; renameover H into Hj.\n  apply fut_action_next.\n    {\n    cbn; omega.\n    }\n  refine (arrow_action_app _#9 (urel_downward_leq _#6 Hj (IHb u v w Hu Hv Hw)) _).\n  apply cprev_formation; auto.\n  }\n\n  {\n  so (IHa i i i (le_refl _) (le_refl _) (le_refl _)) as IHai.\n  so (IHb i i i (le_refl _) (le_refl _) (le_refl _)) as IHbi.\n  rewrite <- (kbasic_impl_approx _#6 Hk) in IHai, IHbi.\n  clear IHa IHb IHd.\n  intros j m p Hj Hmp.\n  so (urel_closed _#5 Hmp) as (Hclm & Hclp).\n  cbn [fromsp tosp].\n  rewrite -> den_iufut in Hmp |- *.\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_next.\n    apply equiv_app; [apply equiv_refl |].\n    apply equiv_cprev.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_refl.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _).\n    {\n    prove_hygiene.\n    }\n  so Hmp as (_ & p' & _ & _ & _ & _ & Hp' & _).  \n  destruct j as [| j].\n    {\n    so (hygiene_invert_auto _#5 (steps_hygiene _#4 Hp' Hclp)) as H; cbn in H.\n    destruct H as (Hclp' & _).\n    refine (urel_equiv_2 _#6 Hclp (equiv_symm _#3 (steps_equiv _#3 Hp')) _).\n    apply fut_action_next_zero; try prove_hygiene.\n    }\n  assert (j <= i) as H by omega; renameover H into Hj.\n  so (fut_action_prev _#6 Hmp) as Hpm_pp.\n  so (IHc _ _ _ Hj Hpm_pp) as Hftpm_pp.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj IHai) Hpm_pp) as Htpm_tpp.\n  so (cprev_cnext_beta _#5 Htpm_tpp) as Hpntpm_tpp.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj IHbi) Htpm_tpp) as Hftpm_ftpp.\n  so (arrow_action_app _#9 (urel_downward_leq _#6 Hj IHbi) Hpntpm_tpp) as Hfpntpm_ftpp.\n  so (urel_zigzag _#7 Hfpntpm_ftpp Hftpm_ftpp Hftpm_pp) as Hfpntpm_pp.\n  eassert _ as H; [refine (fut_action_next _ (S i) _#4 _ Hfpntpm_pp) |].\n    {\n    cbn; omega.\n    }\n  refine (urel_equiv_2 _ (fut_urel stop (S i) (den A)) _#4 Hclp _ H); clear H.\n  apply (equiv_trans _ _ (next p')).\n  2:{\n    apply equiv_symm.\n    apply steps_equiv; auto.\n    }\n  apply equiv_next.\n  eapply equiv_trans.\n    {\n    apply equiv_prev.\n    apply steps_equiv; eauto.\n    }\n  apply steps_equiv; apply star_one.\n  apply step_prev2.\n  }\n\n  {\n  clear IHa IHb IHc.\n  intros j a b Hj Hab.\n  so (urel_closed _#5 Hab) as (Hcla & Hclb).\n  cbn [fromsp tosp].\n  match goal with\n  | |- rel _ _ ?X _ =>\n     eassert (equiv _ X) as Hequiv\n  end.\n    {\n    apply equiv_symm.\n    eapply equiv_trans.\n      {\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply equiv_cnext.\n    apply equiv_app; [apply equiv_refl |].\n    eapply equiv_trans.\n      {\n      apply equiv_prev.\n      apply steps_equiv; apply star_one; apply step_app2.\n      }\n    simpsub.\n    apply steps_equiv; apply star_one.\n    apply step_prev2.\n    }\n  refine (urel_equiv_1 _#6 _ Hequiv _); try prove_hygiene; clear Hequiv.\n  destruct j as [| j].\n    {\n    destruct Hab as (x & Ha & Hb).\n    exists x.\n    split; auto.\n    apply cinterp_eval_refl.\n    cbn in x.\n    destruct x.\n    cbn.\n    apply interp_cnext_zero.\n    prove_hygiene.\n    }\n  assert (j <= i) as H by omega; renameover H into Hj.\n  so (cnext_formation _#5 (IHd _ _ _ Hj (cprev_formation _#5 Hab))) as Hntfpa_npb.\n  so (cnext_cprev_eta _#5 Hab) as Hnpa_b.\n  so (cnext_formation _#5 (cprev_formation _#5 Hab)) as Hnpa_npb.\n  exact (urel_zigzag _#7 Hntfpa_npb Hnpa_npb Hnpa_b).\n  }\n}\n\n(* krec *)\n{\nintros pg s i k K _ IH.\ndestruct IH as (A & HA & H).\nexists A.\nsplit.\n  {\n  apply interp_rec; auto.\n  }\nexact H.\n}\n\n(* kinterp *)\n{\nintros pg s i k l K Hcl Hstepsl HintK IH.\ndestruct IH as (A & HA & H).\nexists A.\nsplit.\n  {\n  eapply interp_eval; eauto.\n  }\nexact H.\n}\n\n(* wrapup *)\n{\nintros pg s i k K HK.\ndestruct Hind as (H & _).\nso (H _#5 HK) as (A & HA & Hspace).\nexists A.\ndo2 2 split; auto.\neapply kbasic_impl_approx; eauto.\n}\nQed.\n\n\nLemma spacify :\n  forall pg s i k K A,\n    kinterp pg s i k K\n    -> interp toppg s i k A\n    -> spacification pg i K A.\nProof.\nintros pg s i k K A HK HA.\nso (spacify_main _#5 HK) as (A' & HA' & H).\nso (basic_fun _#7 HA HA'); subst A'.\nexact H.\nQed.\n\n\nLemma spacification_tosp :\n  forall pg i K A,\n    spacification pg i K A\n    -> rel (arrow_urel stop i (den A) (con_urel pg K)) i\n         (tosp stop pg K) (tosp stop pg K).\nProof.\nintros pg i K A Hspace.\ndestruct Hspace as (HeqK & Htosp & _).\nso (Htosp i i i (le_refl _) (le_refl _) (le_refl _)) as H.\nrewrite <- HeqK in H.\nexact H.\nQed.\n\n\nLemma spacification_fromsp :\n  forall pg i K A,\n    spacification pg i K A\n    -> rel (arrow_urel stop i (con_urel pg K) (den A)) i\n          (fromsp stop pg K) (fromsp stop pg K).\nProof.\nintros pg i K A Hspace.\ndestruct Hspace as (HeqK & _ & Hfromsp & _).\nso (Hfromsp i i i (le_refl _) (le_refl _) (le_refl _)) as H.\nrewrite <- HeqK in H.\nexact H.\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/Spacify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.19758494098360693}}
{"text": "(* En este archivo se demuestra la correcci\u00f3n de la acci\u00f3n stop *)\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 Stop.\n\nLemma stopCorrect : forall (s:System) (ic:iCmp) (sValid: validstate s),\n    (pre (stop ic) s) -> post_stop ic s (stop_post ic s).\nProof.\n    intros.\n    unfold post_stop.\n    split. simpl; auto.\n    simpl in H.\n    unfold pre_stop in H;simpl in H.\n    destruct H.\n    unfold stop_post.\n    unfold insNotInState.\n    simpl.\n    split;intros.\n    rewrite valueDropValue in H0.\n    destruct H0.\n    auto.\n    split;intros.\n    elim (classic (ic=ic'));intros.\n    right;auto.\n    left.\n    apply valueDropValue.\n    auto.\n    split.\n    apply dropPreservesCorrectness.\n    apply runningCorrect;auto.\n    split;intros.\n    apply valueDropNotValue.\n    unfold removeTPerms.\n    split;intros.\n    rewrite valueDropThenValue in H0.\n    destruct H0.\n    auto.\n    split;intros.\n    elim (classic (ic'=ic));intros.\n    right;auto.\n    left.\n    apply valueDropThenValue.\n    split;auto.\n    unfold not;intros.\n    apply H1.\n    rewrite filter_In in H2.\n    destruct H2.\n    simpl in H3.\n    destruct iCmp_eq in H3.\n    auto.\n    discriminate H3.\n    split;intros.\n    elim (classic (In (ic,cp,u) (filter (fun tuple : iCmp * CProvider * uri => if iCmp_eq ic (fst (fst tuple)) then true else false) (map_getKeys (delTPerms (state s))))));intros.\n    apply valueDropAllNotValue.\n    auto.\n    assert (map_apply deltpermsdomeq (dropAll (iCmp * CProvider * uri) PType deltpermsdomeq (filter (fun tuple : iCmp * CProvider * uri => if iCmp_eq ic (fst (fst tuple)) then true else false) (map_getKeys (delTPerms (state s)))) (delTPerms (state s))) (ic, cp, u) = map_apply deltpermsdomeq (delTPerms (state s)) (ic,cp,u)).\n    apply dropNotIn;auto.\n    rewrite H1.\n    unfold not;intros.\n    apply H0.\n    rewrite filter_In.\n    simpl.\n    split.\n    unfold map_getKeys.\n    rewrite in_map_iff.\n    unfold is_Value in H2.\n    case_eq (map_apply deltpermsdomeq (delTPerms (state s)) (ic, cp, u));intros.\n    rewrite valueIffExists in H3.\n    exists {| item_index := (ic, cp, u); item_info := p |}.\n    simpl.\n    auto.\n    apply (delTPermsCorrect);auto.\n    rewrite H3 in H2.\n    inversion H2.\n    destruct iCmp_eq;auto.\n    \n    \n    \n    \n    \n    repeat (split;auto).\n    apply dropAllPreservesCorrectness.\n    apply delTPermsCorrect;auto.\nQed.\n\nLemma notPreStopThenError : forall (s:System) (ic:iCmp), ~(pre (stop ic) s) -> validstate s -> exists ec : ErrorCode, response (step s (stop ic)) = error ec /\\ ErrorMsg s (stop ic) ec /\\ s = system (step s (stop ic)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_stop in H.\n    unfold stop_safe.\n    unfold stop_pre.\n    case_eq(is_ValueBool (map_apply iCmp_eq (running (state s)) ic));intros.\n    destruct H.\n    unfold is_ValueBool in H1.\n    case_eq ((map_apply iCmp_eq (running (state s)) ic));intros;rewrite H in H1;simpl in H1.\n    exists c;auto.\n    discriminate H1.\n    exists instance_not_running.\n    split;auto.\n    split;auto.\n    invertBool H1.\n    intro;apply H1.\n    unfold is_ValueBool.\n    unfold is_Value in H2.\n    case_eq ((map_apply iCmp_eq (running (state s)) ic));intros;rewrite H3 in H2;simpl in H2;auto.\nQed.\n\nLemma stopIsSound : forall (s:System) (ic:iCmp) (sValid: validstate s),\n        exec s (stop ic) (system (step s (stop ic))) (response (step s (stop ic))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (stop ic) s));intro.\n    left.\n    simpl.\n    assert(stop_pre ic s = None).\n    unfold stop_pre.\n    destruct H.\n    unfold is_ValueBool.\n    rewrite H.\n    auto.\n    \n    unfold stop_safe;simpl.\n    rewrite H0;simpl.\n    split;auto.\n    split;auto.\n    apply stopCorrect;auto.\n    right.\n    apply notPreStopThenError;auto.\n    \nQed.\nEnd Stop.\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/StopIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.19749077940989107}}
{"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 TableAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition table_unmap_spec0 (g_rd: Pointer) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr, level with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr, VZ64 _level =>\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'7 == is_null_spec (_g_llt_base, _g_llt_ofst) adt;\n      rely is_int _t'7;\n      if (_t'7 =? 1) then\n        let _ret := 1 in\n        Some (adt, (VZ64 _ret))\n      else\n        when'' _ll_table_base, _ll_table_ofst, adt == granule_map_spec (_g_llt_base, _g_llt_ofst) 5 adt;\n        rely is_int _ll_table_ofst;\n        when' _llt_pgte == pgte_read_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) adt;\n        rely is_int64 _llt_pgte;\n        if (_level <? 3) then\n          when _t'6 == entry_is_table_spec (VZ64 _llt_pgte) adt;\n          rely is_int _t'6;\n          let _t'5 := (_t'6 =? 1) in\n          if _t'5 then\n            let _ret := 1 in\n            when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n            when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n            Some (adt, (VZ64 _ret))\n          else\n            rely is_int64 (Z.land _llt_pgte 281474976706560);\n            let _data_addr := (Z.land _llt_pgte 281474976706560) in\n            rely is_int64 (Z.land _llt_pgte 504403158265495552);\n            rely is_int64 ((Z.land _llt_pgte 504403158265495552) / 72057594037927936);\n            let _ipa_state := ((Z.land _llt_pgte 504403158265495552) / 72057594037927936) in\n            if (_ipa_state =? 2) then\n              rely is_int64 (1 * 72057594037927936);\n              rely is_int64 (Z.lor (1 * 72057594037927936) _data_addr);\n              let _new_pgte := (Z.lor (1 * 72057594037927936) _data_addr) in\n              rely is_int64 _new_pgte;\n              when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n              if (_level =? 3) then\n                when adt == invalidate_page_spec (VZ64 _map_addr) adt;\n                let _ret := 0 in\n                when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n                when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n                Some (adt, (VZ64 _ret))\n              else\n                when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n                let _ret := 0 in\n                when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n                when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n                Some (adt, (VZ64 _ret))\n            else\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          let _t'5 := 0 in\n          rely is_int64 (Z.land _llt_pgte 281474976706560);\n          let _data_addr := (Z.land _llt_pgte 281474976706560) in\n          rely is_int64 (Z.land _llt_pgte 504403158265495552);\n          rely is_int64 ((Z.land _llt_pgte 504403158265495552) / 72057594037927936);\n          let _ipa_state := ((Z.land _llt_pgte 504403158265495552) / 72057594037927936) in\n          if (_ipa_state =? 2) then\n            rely is_int64 (1 * 72057594037927936);\n            rely is_int64 (Z.lor (1 * 72057594037927936) _data_addr);\n            let _new_pgte := (Z.lor (1 * 72057594037927936) _data_addr) in\n            rely is_int64 _new_pgte;\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _new_pgte) adt;\n            if (_level =? 3) then\n              when adt == invalidate_page_spec (VZ64 _map_addr) adt;\n              let _ret := 0 in\n              when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n              when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n              Some (adt, (VZ64 _ret))\n            else\n              when adt == invalidate_block_spec (VZ64 _map_addr) adt;\n              let _ret := 0 in\n              when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n              when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n              Some (adt, (VZ64 _ret))\n          else\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     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_unmap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.2689414096510109, "lm_q1q2_score": 0.19743514041686844}}
{"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 `{external_calls_prf: ExternalCalls}.\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\nDefinition get_pair (p: rpair mreg) (m: regset): val :=\n  match p with\n    | One l => m l\n    | Twolong l1 l2 => Val.longofwords (m l1) (m l2)\n  end.\n\nInductive final_state (lm: regset) (sg: signature): state -> (val * mem) -> Prop :=\n| final_state_intro\n    rs\n    v\n    (Hv: v = get_pair (loc_result sg) rs)\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 -> ptrofs -> Prop)\n           (lm: regset) (init_sp init_ra: val)\n           (p: Mach.program) (i: ident) (sg: signature) (args: list val) (m: mem) :=\n  Semantics\n    (Mach.step init_sp init_ra return_address_offset)\n    (initial_state lm init_sp p i sg args m)\n    (final_state lm sg)\n    (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/MachX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.TermSanityInterface.\nRequire Import VerdiRaft.CroniesTermInterface.\n\nRequire Import VerdiRaft.RefinementCommonTheorems.\n\nRequire Import VerdiRaft.SpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.CandidateEntriesInterface.\n\nSection CandidateEntriesProof.\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 {cti : cronies_term_interface}.\n  Context {tsi : term_sanity_interface}.\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Lemma handleClientRequest_spec :\n    forall h d client id c out d' l,\n      handleClientRequest h d client id c = (out, d', l) ->\n      currentTerm d' = currentTerm d /\\\n      type d' = type d /\\\n      l = [] /\\\n      (forall e, In e (log d') ->\n            (In e (log d) \\/ (e = (mkEntry\n                                     h\n                                     client\n                                     id\n                                     (S (maxIndex (log d)))\n                                     (currentTerm d)\n                                     c) /\\ log d' = e :: log d /\\ type d' = Leader))).\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; intuition.\n    simpl in *. intuition. subst. auto.\n  Qed.\n\n  Lemma candidate_entries_client_request :\n    refined_raft_net_invariant_client_request CandidateEntries.\n  Proof using cci. \n    unfold refined_raft_net_invariant_client_request, CandidateEntries.\n    intros. subst.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros; simpl in *.\n      eapply candidateEntries_ext; try eassumption.\n      repeat find_higher_order_rewrite.\n      unfold update_elections_data_client_request in *. repeat break_let. simpl in *.\n      destruct (name_eq_dec h0 h); subst.\n      + rewrite_update.\n        unfold update_elections_data_client_request in *. repeat break_let. simpl in *.\n        simpl in *. find_inversion.\n        find_apply_lem_hyp handleClientRequest_spec; intuition eauto.\n        find_apply_hyp_hyp.\n        intuition.\n        * rewrite_update.\n          eapply candidateEntries_same; eauto; intuition;\n          destruct (name_eq_dec h0 h); subst; rewrite_update; auto.\n          repeat break_match; simpl; auto.\n        * find_apply_lem_hyp cronies_correct_invariant.\n          unfold candidateEntries. exists h.\n          intuition; rewrite_update; simpl in *; try congruence.\n          repeat find_rewrite. simpl in *.\n          repeat break_match; simpl; pose won_election_cronies; eauto.\n      + rewrite_update.\n        find_apply_lem_hyp handleClientRequest_spec.\n        eapply candidateEntries_same; eauto; intuition;\n        destruct (name_eq_dec h1 h); subst; rewrite_update; auto;\n        tuple_inversion; repeat find_rewrite;\n        repeat break_match; simpl; auto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; try eassumption.\n      find_apply_lem_hyp handleClientRequest_spec.\n      intuition.\n      subst. simpl in *.\n\n      eapply_prop_hyp candidateEntries AppendEntries; eauto.\n      + eapply candidateEntries_same; eauto; intuition;\n        destruct (name_eq_dec h h0); subst; rewrite_update; auto.\n        unfold update_elections_data_client_request; repeat break_match; simpl; auto.\n      + find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma update_elections_data_timeout_leader_cronies_same :\n    forall sigma h,\n      type (snd (sigma h)) = Leader ->\n      cronies (update_elections_data_timeout h (sigma h)) =\n      cronies (fst (sigma h)).\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; subst; simpl in *; auto.\n    unfold handleTimeout, tryToBecomeLeader in *.\n    repeat break_match; try congruence; repeat find_inversion; simpl in *;\n    unfold raft_data in *;\n    congruence.\n  Qed.\n\n  Lemma handleTimeout_only_sends_RequestVotes :\n    forall h d out d' l p,\n      handleTimeout h d = (out, d', l) ->\n      In p l ->\n      exists t h' maxi maxt,\n        snd p = RequestVote t h' maxi maxt.\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition;\n    do_in_map; subst; simpl; eauto.\n  Qed.\n\n  Lemma handleTimeout_not_leader_inc_term :\n    forall h d out d' l,\n      handleTimeout h d = (out, d', l) ->\n      type d <> Leader ->\n      currentTerm d' = S (currentTerm d).\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader.\n    intros. simpl in *.\n    repeat break_match; try congruence; repeat find_inversion; auto.\n  Qed.\n\n  Lemma update_elections_data_timeout_cronies :\n    forall h d out d' l t,\n      handleTimeout h (snd d) = (out, d', l) ->\n      cronies (update_elections_data_timeout h d) t = cronies (fst d) t \\/\n      (t = currentTerm d' /\\\n       cronies (update_elections_data_timeout h d) t = votesReceived d').\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto.\n    break_match; auto.\n  Qed.\n\n  Lemma handleTimeout_preserves_candidateEntries :\n    forall net h e out d l,\n      refined_raft_intermediate_reachable net ->\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h (update_elections_data_timeout h (nwState net h), d)).\n  Proof using cti. \n    intros.\n    destruct (serverType_eq_dec (type (snd (A:=electionsData) (B:=raft_data) (nwState net h))) Leader).\n      + (* Leader case *)\n        unfold handleTimeout, tryToBecomeLeader in *. simpl in *.\n        find_rewrite. find_inversion.\n\n        eapply candidateEntries_same; eauto;\n        intros;\n        repeat (rewrite update_fun_comm; simpl in * );\n        update_destruct; subst; rewrite_update;\n        auto using update_elections_data_timeout_leader_cronies_same.\n      + (* non-Leader case *)\n\n        unfold candidateEntries in *.\n        break_exists. break_and.\n        exists x.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm with (f := type); simpl.\n        update_destruct; subst; rewrite_update; auto.\n        split.\n        * match goal with\n          | [ H : handleTimeout _ _ = _ |- _ ] =>\n            pose proof H;\n              apply update_elections_data_timeout_cronies with (t := eTerm e) in H\n          end.\n          intuition; find_rewrite; auto.\n          find_apply_lem_hyp wonElection_exists_voter.\n          break_exists.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_copy_apply_lem_hyp cronies_term_invariant; auto.\n          find_copy_apply_lem_hyp handleTimeout_not_leader_inc_term; auto.\n          simpl in *.\n          lia.\n        * intros.\n          find_apply_lem_hyp wonElection_exists_voter.\n          break_exists.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_copy_apply_lem_hyp cronies_term_invariant; auto.\n          find_copy_apply_lem_hyp handleTimeout_not_leader_inc_term; auto.\n          simpl in *.\n          lia.\n  Qed.\n\n  Lemma candidate_entries_timeout :\n    refined_raft_net_invariant_timeout CandidateEntries.\n  Proof using cti. \n    unfold refined_raft_net_invariant_timeout, CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; try eassumption.\n      repeat find_higher_order_rewrite.\n\n        find_rewrite_lem update_fun_comm. simpl in *.\n        find_rewrite_lem update_fun_comm. simpl in *.\n        find_erewrite_lem handleTimeout_log_same.\n\n        find_rewrite_lem_by update_nop_ext' auto.\n        find_apply_hyp_hyp.\n        eauto using handleTimeout_preserves_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      break_or_hyp.\n      + eapply_prop_hyp pBody pBody; eauto.\n        eauto using handleTimeout_preserves_candidateEntries.\n      + do_in_map. subst. simpl in *.\n        eapply handleTimeout_only_sends_RequestVotes in H8; eauto.\n        break_exists. congruence.\n  Qed.\n\n  Lemma update_elections_data_appendEntries_cronies_same :\n    forall h d t n pli plt es ci,\n      cronies (update_elections_data_appendEntries h d t n pli plt es ci) =\n      cronies (fst d).\n  Proof using. \n    unfold update_elections_data_appendEntries.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma handleAppendEntries_spec :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      (currentTerm st <= currentTerm st' /\\\n       (forall e,\n          In e (log st') ->\n          In e (log st) \\/\n          In e es /\\ currentTerm st' = t) /\\\n       ~ is_append_entries m).\n  Proof 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\n  Lemma handleAppendEntries_term_same_or_type_follower :\n    forall h t n pli plt es ci d m st,\n      handleAppendEntries h st t n pli plt es ci = (d, m) ->\n      (currentTerm d = currentTerm st /\\ type d = type st) \\/ type d = Follower.\n  Proof using. \n    unfold handleAppendEntries in *.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma handleAppendEntries_preserves_candidate_entries :\n    forall net h t n pli plt es ci d m e,\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h\n                                 (update_elections_data_appendEntries\n                                    h\n                                    (nwState net h) t n pli plt es ci, d)).\n  Proof using. \n    unfold candidateEntries.\n    intros. break_exists. break_and.\n    exists x.\n    split.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      rewrite update_elections_data_appendEntries_cronies_same.\n      destruct (name_eq_dec x h); subst; rewrite_update; auto.\n    - intros.\n      rewrite update_fun_comm. simpl.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      destruct (name_eq_dec x h); subst; rewrite_update; auto.\n      find_apply_lem_hyp handleAppendEntries_term_same_or_type_follower.\n      intro; intuition;\n      repeat find_rewrite; auto; discriminate.\n  Qed.\n\n\n  Lemma is_append_entries_intro :\n    forall t n plt pli es ci,\n      is_append_entries (AppendEntries t n pli plt es ci).\n  Proof using. \n    eauto 20.\n  Qed.\n\n  Lemma candidate_entries_append_entries :\n    refined_raft_net_invariant_append_entries CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct; subst; rewrite_update;\n      eapply handleAppendEntries_preserves_candidate_entries; eauto.\n      find_copy_apply_lem_hyp handleAppendEntries_spec. break_and.\n      find_apply_hyp_hyp. intuition eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntries_preserves_candidate_entries; eauto.\n      + subst. simpl in *. find_apply_lem_hyp handleAppendEntries_spec.\n        break_and.\n        subst.\n        exfalso.\n        eauto using is_append_entries_intro.\n  Qed.\n\n  Lemma handleAppendEntriesReply_spec :\n    forall h st h' t es r st' ms,\n      handleAppendEntriesReply h st h' t es r = (st', ms) ->\n      log st' = log st /\\\n      ((currentTerm st' = currentTerm st /\\ type st' = type st)\n       \\/ type st' = Follower) /\\\n      (forall m, In m ms -> ~ is_append_entries (snd m)).\n  Proof using. \n    intros.\n    unfold handleAppendEntriesReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition;\n    do_bool; intuition.\n  Qed.\n\n\n  Lemma handleAppendEntriesReply_preserves_candidate_entries :\n    forall net h h' t es r st' ms e,\n      handleAppendEntriesReply h (snd (nwState net h)) h' t es r = (st', ms) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h (fst (nwState net h), st')).\n  Proof using. \n    unfold candidateEntries.\n    intros. break_exists. break_and.\n    exists x.\n    split.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      update_destruct; subst; rewrite_update; auto.\n    - intros. update_destruct; subst; rewrite_update; auto.\n      simpl in *.\n      find_apply_lem_hyp handleAppendEntriesReply_spec.\n      intuition; repeat find_rewrite; intuition.\n      congruence.\n  Qed.\n\n\n  Ltac prove_in :=\n    match goal with\n      | [ _ : nwPackets ?net = _,\n              _ : In ?p _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n      | [ _ : nwPackets ?net = _,\n              _ : pBody ?p = _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n    end.\n\n  Lemma candidate_entries_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries. intros. intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct.\n      + subst. rewrite_update.\n        unfold candidateEntries in *.\n        find_apply_lem_hyp handleAppendEntriesReply_spec. break_and.\n        repeat find_rewrite.\n        find_apply_hyp_hyp.\n        break_exists; exists x; eauto.\n        update_destruct; intuition; subst; rewrite_update; simpl in *; auto;\n        repeat find_rewrite; intuition; congruence.\n      + rewrite_update. find_apply_hyp_hyp.\n        eauto using handleAppendEntriesReply_preserves_candidate_entries.\n    - unfold candidateEntries_nw_invariant in *. intros. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      + (* packet already in nw *)\n        prove_in.\n        eapply candidateEntries_ext; eauto.\n        find_eapply_lem_hyp handleAppendEntriesReply_preserves_candidate_entries; eauto.\n        subst. auto.\n      + exfalso.\n        do_in_map.\n        find_eapply_lem_hyp handleAppendEntriesReply_spec; eauto.\n        subst. simpl in *. find_rewrite.\n        match goal with\n          | H : ~ is_append_entries _ |- _ => apply H\n        end.\n        repeat eexists; eauto.\n  Qed.\n\n  Lemma update_elections_data_requestVote_cronies_same :\n    forall h h' t lli llt st,\n      cronies (update_elections_data_requestVote h h' t h' lli llt st) =\n      cronies (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma advanceCurrentTerm_same_or_type_follower :\n    forall st t,\n      advanceCurrentTerm st t = st \\/\n      type (advanceCurrentTerm st t) = Follower.\n  Proof using. \n    unfold advanceCurrentTerm.\n    intros. repeat break_match; auto.\n  Qed.\n\n  Lemma handleRV_advanceCurrentTerm_preserves_candidateEntries :\n    forall net h h' t lli llt e,\n      candidateEntries e (nwState net) ->\n      candidateEntries e\n                       (update name_eq_dec (nwState net) h\n                               (update_elections_data_requestVote h h' t h' lli llt (nwState net h),\n                                advanceCurrentTerm (snd (nwState net h)) t)).\n  Proof using. \n    intros.\n    unfold candidateEntries in *.\n    break_exists.  break_and.\n    exists x.\n    split; update_destruct; subst; rewrite_update; auto; simpl.\n    + rewrite update_elections_data_requestVote_cronies_same. auto.\n    + intros.\n      match goal with\n      | [ |- context [advanceCurrentTerm ?st ?t] ] =>\n        pose proof advanceCurrentTerm_same_or_type_follower st t\n      end.\n      intuition; try congruence.\n      repeat find_rewrite. auto.\n  Qed.\n\n  Lemma handleRequestVote_preserves_candidateEntries :\n    forall net h h' t lli llt d e m,\n      handleRequestVote h (snd (nwState net h)) t h' lli llt = (d, m) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h\n                                 (update_elections_data_requestVote\n                                    h h' t h' lli llt (nwState net h), d)).\n  Proof using. \n    unfold handleRequestVote.\n    intros.\n    repeat break_match; repeat find_inversion;\n    auto using handleRV_advanceCurrentTerm_preserves_candidateEntries.\n    - eapply candidateEntries_same; eauto;\n        intros;\n        repeat (rewrite update_fun_comm; simpl in * );\n        update_destruct; subst; rewrite_update;\n        auto using update_elections_data_requestVote_cronies_same.\n    - do_bool. intuition. congruence.\n    - unfold candidateEntries in *. break_exists. break_and. exists x.\n      simpl.\n      split.\n      + rewrite update_fun_comm with (f := fst). simpl.\n        rewrite update_fun_comm with (f := cronies). simpl.\n        rewrite update_elections_data_requestVote_cronies_same.\n        update_destruct; subst; rewrite_update; auto.\n      + rewrite update_fun_comm with (f := snd). simpl.\n        rewrite update_fun_comm with (f := currentTerm). simpl.\n        rewrite update_fun_comm with (f := type). simpl.\n        update_destruct; subst; rewrite_update; auto.\n        match goal with\n        | [ |- context [advanceCurrentTerm ?st ?t] ] =>\n          pose proof advanceCurrentTerm_same_or_type_follower st t\n        end.\n        intuition; try congruence.\n        repeat find_rewrite. auto.\n  Qed.\n\n  Lemma handleRequestVote_only_sends_RVR :\n    forall d h h' t lli llt d' m,\n      handleRequestVote h d t h' lli llt = (d', m) ->\n      is_request_vote_reply m.\n  Proof using. \n    unfold handleRequestVote.\n    intros.\n    repeat break_match; repeat find_inversion; eauto.\n  Qed.\n\n  Lemma candidate_entries_request_vote :\n    refined_raft_net_invariant_request_vote CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct; subst; rewrite_update; simpl in *;\n      try find_erewrite_lem handleRequestVote_same_log;\n      eapply handleRequestVote_preserves_candidateEntries; eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp. intuition.\n      + eauto using handleRequestVote_preserves_candidateEntries.\n      + subst. simpl in *.\n        find_apply_lem_hyp handleRequestVote_only_sends_RVR.\n        subst. break_exists. discriminate.\n  Qed.\n\n  Lemma candidate_entries_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply CandidateEntries.\n  Proof using cci. \n    red. unfold CandidateEntries. intros. intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct.\n      + subst. rewrite_update.\n        match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n        end.\n        find_copy_apply_lem_hyp handleRequestVoteReply_spec. break_and.\n        match goal with\n          | H : log _ = log _ |- _ => rewrite H in *\n        end.\n        find_apply_hyp_hyp.\n        eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n      + rewrite_update.\n        eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n  Qed.\n\n  Lemma doLeader_in_entries :\n    forall (h : name) d h os d' ms m t li pli plt es ci e,\n      doLeader d h = (os, d', ms) ->\n      snd m = AppendEntries t li pli plt es ci ->\n      In m ms ->\n      In e es ->\n      In e (log d).\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n\n    unfold replicaMessage in *. simpl in *. subst. simpl in *.\n    find_inversion.\n    eauto using findGtIndex_in.\n  Qed.\n\n  Lemma candidate_entries_do_leader :\n    refined_raft_net_invariant_do_leader CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      update_destruct; subst; rewrite_update.\n      + simpl in *.\n        find_erewrite_lem doLeader_same_log.\n        repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        pose doLeader_preserves_candidateEntries; eauto.\n      + pose doLeader_preserves_candidateEntries; eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + pose doLeader_preserves_candidateEntries; eauto.\n      + do_in_map. subst. simpl in *.\n        eapply doLeader_preserves_candidateEntries; eauto.\n        eapply_prop candidateEntries_host_invariant.\n        match goal with\n        | [ H : _ |- _ ] => rewrite H\n        end.\n        simpl.\n        eauto using doLeader_in_entries.\n  Qed.\n\n  Lemma doGenericServer_same_type :\n    forall h d os d' ms,\n      doGenericServer h d = (os, d', ms) ->\n      type d' = type d.\n  Proof using. \n    unfold doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion;\n    use_applyEntries_spec; subst; simpl in *;\n    auto.\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 doGenericServer_preserves_candidateEntries :\n    forall net gd d h os d' ms e,\n      nwState net h = (gd, d) ->\n      doGenericServer h d = (os, d', ms) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h (gd, d')).\n  Proof using. \n    intros.\n    eapply candidateEntries_same; eauto;\n    intros;\n    repeat (rewrite update_fun_comm; simpl in * );\n    update_destruct; subst; rewrite_update; auto;\n    repeat find_rewrite; simpl; auto.\n    - find_copy_apply_lem_hyp doGenericServer_spec. break_and. auto.\n    - eauto using doGenericServer_same_type.\n  Qed.\n\n  Lemma candidate_entries_do_generic_server :\n    refined_raft_net_invariant_do_generic_server CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      update_destruct; subst; rewrite_update.\n      + simpl in *.\n        find_copy_apply_lem_hyp doGenericServer_spec. break_and.\n        find_rewrite.\n        repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        eauto using doGenericServer_preserves_candidateEntries.\n      + eauto using doGenericServer_preserves_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto using doGenericServer_preserves_candidateEntries.\n      + do_in_map.\n        find_copy_apply_lem_hyp doGenericServer_spec. break_and.\n        subst. simpl in *.\n        find_apply_hyp_hyp.\n        exfalso.\n        find_rewrite. eauto 20.\n  Qed.\n\n  Lemma candidate_entries_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      repeat find_reverse_higher_order_rewrite.\n      apply candidateEntries_ext with (sigma := nwState net); eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      find_apply_hyp_hyp.\n      eapply_prop_hyp In In; eauto.\n      apply candidateEntries_ext with (sigma := nwState net); eauto.\n  Qed.\n\n  Lemma reboot_log_same :\n    forall d,\n      log (reboot d) = log d.\n  Proof using. \n    unfold reboot.\n    auto.\n  Qed.\n\n  Lemma reboot_preservers_candidateEntries :\n    forall net h d gd e,\n      nwState net h = (gd, d) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update name_eq_dec (nwState net) h (gd, reboot d)).\n  Proof using. \n    unfold reboot, candidateEntries.\n    intros.\n    break_exists.\n    exists x.\n    break_and.\n    rewrite update_fun_comm. simpl in *.\n    update_destruct; subst; rewrite_update; auto.\n    repeat find_rewrite. simpl in *. intuition. discriminate.\n  Qed.\n\n  Lemma candidate_entries_reboot :\n    refined_raft_net_invariant_reboot CandidateEntries.\n  Proof using. \n    red. unfold CandidateEntries.\n    intros.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      repeat find_higher_order_rewrite.\n      eapply candidateEntries_ext; eauto.\n      subst.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct; subst; rewrite_update.\n      + repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        find_apply_hyp_hyp.\n        eauto using reboot_preservers_candidateEntries.\n      + eauto using reboot_preservers_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      repeat find_reverse_rewrite.\n      eapply_prop_hyp In In; eauto.\n      eapply candidateEntries_ext; eauto.\n      eauto using reboot_preservers_candidateEntries.\n  Qed.\n\n  Lemma candidate_entries_init :\n    refined_raft_net_invariant_init CandidateEntries.\n  Proof using. \n    red.\n    unfold CandidateEntries.\n    unfold candidateEntries_host_invariant, candidateEntries_nw_invariant.\n    intuition;\n     repeat match goal with\n            | [ H : In _ _ |- _ ] => compute in H\n            end;\n    intuition.\n  Qed.\n\n  Theorem candidate_entries_invariant :\n    forall (net : network),\n      refined_raft_intermediate_reachable net ->\n      CandidateEntries net.\n  Proof using cci cti rri. \n    intros.\n    eapply refined_raft_net_invariant; eauto.\n    - apply candidate_entries_init.\n    - apply candidate_entries_client_request.\n    - apply candidate_entries_timeout.\n    - apply candidate_entries_append_entries.\n    - apply candidate_entries_append_entries_reply.\n    - apply candidate_entries_request_vote.\n    - apply candidate_entries_request_vote_reply.\n    - apply candidate_entries_do_leader.\n    - apply candidate_entries_do_generic_server.\n    - apply candidate_entries_state_same_packet_subset.\n    - apply candidate_entries_reboot.\n  Qed.\n\n  Instance cei : candidate_entries_interface.\n  Proof.\n    split.\n    auto using candidate_entries_invariant.\n  Qed.\nEnd CandidateEntriesProof.\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/CandidateEntriesProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"text": "Require Import UFO.Rel.Definitions.\nRequire Import UFO.Rel.BasicFacts.\nRequire Import UFO.Rel.Monotone.\nRequire Import UFO.Rel.Compat_weaken_X.\nRequire Import UFO.Util.Subset.\nRequire Import UFO.Util.Postfix.\nRequire Import UFO.Lang.BindingsFacts.\nRequire Import UFO.Lang.Static.\nSet Implicit Arguments.\n\nLocal Hint Rewrite in_singleton in_union in_inter dom_single.\nLocal Hint Resolve subset_union_r subset_empty_l.\nLocal Hint Resolve \ud835\udce5_monotone \ud835\udcd7_monotone.\nLocal Hint Constructors wf_XEnv.\nLocal Hint Constructors postfix.\n\nLocal Fact fsetfact3 (A : Type) (E : fset A) a :\na \u2209 E \u2192 disjoint E \\{a}.\nProof.\nintro H ; apply fset_extens ; [ intros_all ; crush | auto ].\nQed.\n\nLocal Hint Resolve fsetfact3.\n\nSection section_ccompat_tm_down.\nContext (EV LV : Set).\nContext (\u039e : XEnv EV LV).\nContext (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig).\nContext (\u03c1\u2081 \u03c1\u2082 : LV \u2192 lbl0) (\u03c1 : LV \u2192 IRel \ud835\udce3_Sig).\nContext (X : var).\nContext (T : ty \u2205 EV LV \u2205) (E : eff \u2205 EV LV \u2205).\n\nLemma ccompat_tm_down_aux n\n(FrX :\n  n \u22a8 \u2200\u1d62 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 L\u2081 L\u2082,\n      \ud835\udce4\u27e6 \u039e & (X ~ (T,E)) \u22a2 E \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 L\u2081 L\u2082 \u21d2 (X \u2209 L\u2081 \u2227 X \u2209 L\u2082)\u1d62\n) :\nn \u22a8 \u2200\u1d62 \u03b6\u2081 \u03b6\u2082 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082,\n    \ud835\udce3\u27e6 \u039e & (X ~ (T,E)) \u22a2 T # (ef_lbl (lbl_id (lid_f X))) :: E \u27e7\n      \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n      (\u03b6\u2081 ++ X :: \u03be\u2081) (\u03b6\u2082 ++ X :: \u03be\u2082) t\u2081 t\u2082 \u21d2\n    \ud835\udce3\u27e6 \u039e & (X ~ (T,E)) \u22a2 T # E \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n      (\u03b6\u2081 ++ X :: \u03be\u2081) (\u03b6\u2082 ++ X :: \u03be\u2082)\n      (ktx_plug (ktx_down ktx_hole X) t\u2081)\n      (ktx_plug (ktx_down ktx_hole X) t\u2082).\nProof.\nloeb_induction L\u00f6bIH.\niintro \u03b6\u2081 ; iintro \u03b6\u2082 ; iintro \u03be\u2081 ; iintro \u03be\u2082 ; iintro t\u2081 ; iintro t\u2082 ; iintro Ht.\napply plug1 with\n  (\u03b5 := ef_lbl (lbl_id (lid_f X))) (Ta := T) (\u03be\u2081 := \u03b6\u2081 ++ X :: \u03be\u2081) (\u03be\u2082 := \u03b6\u2082 ++ X :: \u03be\u2082).\n+ exact FrX.\n+ iintro \u03be\u2081' ; iintro \u03be\u2082' ; iintro H\u03be\u2081' ; iintro H\u03be\u2082' ;\n  iintro v\u2081 ; iintro v\u2082 ; iintro Hv.\n  eapply \ud835\udce3_step_r.\n  { simpl ; apply step_down_val ; eauto. }\n  eapply \ud835\udce3_step_l.\n  { simpl ; apply step_down_val ; eauto. }\n  iintro_later.\n  apply \ud835\udce5_in_\ud835\udce3 ; apply Hv.\n+ clear - L\u00f6bIH.\n  iintro \u03be\u2081' ; iintro \u03be\u2082' ; iintro H\u03be\u2081' ; iintro H\u03be\u2082'.\n  iintro K\u2081 ; iintro K\u2082 ;\n  iintro s\u2081 ; iintro s\u2082 ; iintro \u03c8 ; iintro Xs\u2081 ; iintro Xs\u2082.\n  iintro H.\n  iintro Xs_K\u2081K\u2082.\n  iintro Hw.\n  ielim_prop Xs_K\u2081K\u2082.\n\n  simpl in H.\n  idestruct H as X\u2081 H ; idestruct H as X\u2082 H ;\n  idestruct H as r\u2081 H ; idestruct H as r\u2082 H ;\n  idestruct H as HX\u2081X\u2082 H ; idestruct H as HXs\u2081Xs\u2082 H ;\n  idestruct H as Hs\u2081s\u2082 H ; idestruct H as HX Hr.\n\n  ielim_prop HX\u2081X\u2082 ; destruct HX\u2081X\u2082 as [HX\u2081 HX\u2082].\n  ielim_prop Hs\u2081s\u2082 ; destruct Hs\u2081s\u2082 as [Hs\u2081 Hs\u2082].\n  ielim_prop HXs\u2081Xs\u2082 ; destruct HXs\u2081Xs\u2082 as [HXs\u2081 HXs\u2082].\n  simpl in HX\u2081, HX\u2082 ; inversion HX\u2081 ; inversion HX\u2082 ; clear HX\u2081 HX\u2082.\n  subst s\u2081 s\u2082 Xs\u2081 Xs\u2082 X\u2081 X\u2082.\n\n  rewrite get_concat in Hr.\n  rewrite binds_single_eq in Hr.\n\n  simpl.\n  specialize (Xs_K\u2081K\u2082 X).\n  assert (tunnels X K\u2081) ; [ crush | ].\n  assert (tunnels X K\u2082) ; [ crush | ].\n  eapply \ud835\udce3_step_r.\n  { apply step_down_up ; eauto. }\n  eapply \ud835\udce3_step_l.\n  { apply step_down_up ; eauto. }\n\n  unfold \ud835\udcd7_Fun in Hr.\n  apply I_later_forall_down in Hr ; iespecialize Hr.\n  apply I_later_forall_down in Hr ; iespecialize Hr.\n  apply I_later_forall_down in Hr ; eapply I_forall_elim in Hr ; [ | apply postfix_refl ].\n  apply I_later_forall_down in Hr ; eapply I_forall_elim in Hr ; [ | apply postfix_refl ].\n  repeat (apply I_later_forall_down in Hr ; iespecialize Hr).\n  apply I_later_arrow_down in Hr.\n  erewrite I_iff_elim_M ; [ |\n      eapply I_later_iff_down ; iintro_later ; apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3\n  ].\n  iapply Hr.\n\n  clear - L\u00f6bIH Hw H\u03be\u2081' H\u03be\u2082'.\n  apply I_later_forall_up ; iintro \u03be\u2081''.\n  apply I_later_forall_up ; iintro \u03be\u2082''.\n  apply I_later_forall_up ; iintro H\u03be\u2081''.\n  apply I_later_forall_up ; iintro H\u03be\u2082''.\n  apply I_later_forall_up ; iintro t\u2081.\n  apply I_later_forall_up ; iintro t\u2082.\n  apply I_later_arrow_up ; iintro Ht.\n  ielim_vars Hw ; [ | apply H\u03be\u2082'' | apply H\u03be\u2081'' ].\n  iespecialize Hw.\n  ispecialize Hw ; [ apply Ht | ].\n\n  later_shift.\n  erewrite <- I_iff_elim_M ; [ | apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3 ].\n\n  simpl ktx_plug in L\u00f6bIH.\n  apply postfix_inv_app in H\u03be\u2081'' ; destruct H\u03be\u2081'' as [ \u03b6\u2081'' H\u03be\u2081'' ].\n  apply postfix_inv_app in H\u03be\u2082'' ; destruct H\u03be\u2082'' as [ \u03b6\u2082'' H\u03be\u2082'' ].\n  apply postfix_inv_app in H\u03be\u2081' ; destruct H\u03be\u2081' as [ \u03b6\u2081' H\u03be\u2081' ].\n  apply postfix_inv_app in H\u03be\u2082' ; destruct H\u03be\u2082' as [ \u03b6\u2082' H\u03be\u2082' ].\n  ispecialize L\u00f6bIH (\u03b6\u2081'' ++ \u03b6\u2081' ++ \u03b6\u2081) ;\n  ispecialize L\u00f6bIH (\u03b6\u2082'' ++ \u03b6\u2082' ++ \u03b6\u2082) ;\n  ispecialize L\u00f6bIH \u03be\u2081 ;\n  ispecialize L\u00f6bIH \u03be\u2082.\n  repeat rewrite <- app_assoc in L\u00f6bIH.\n  rewrite <- H\u03be\u2081', <- H\u03be\u2082', <- H\u03be\u2081'', <- H\u03be\u2082'' in L\u00f6bIH.\n  iespecialize L\u00f6bIH.\n  ispecialize L\u00f6bIH ; [ apply Hw | ].\n  apply L\u00f6bIH.\n+ apply postfix_refl.\n+ apply postfix_refl.\n+ assumption.\nQed.\n\nContext (FrX_\u039e : X # \u039e).\nContext (Wf_\u039e : wf_XEnv \u039e).\nContext (Wf_T : wf_ty \u039e T).\nContext (Wf_E : wf_eff \u039e E).\n\nLemma ccompat_tm_down n \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 :\nn \u22a8 ( \u2200\u1d62 \u03be\u2081' \u03be\u2082' t\u2081' t\u2082' \u03c8 Xs\u2081 Xs\u2082,\n      \ud835\udce4\u27e6 (\u039e & X ~ (T, E)) \u22a2 E \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081' \u03be\u2082' t\u2081' t\u2082' \u03c8 Xs\u2081 Xs\u2082 \u21d2\n      (X \u2209 Xs\u2081 \u2227 X \u2209 Xs\u2082)\u1d62\n    ) \u2192\nX \u2209 from_list \u03be\u2081 \u2192 X \u2209 from_list \u03be\u2082 \u2192\nn \u22a8 \ud835\udce3\u27e6 (\u039e & (X ~ (T, E))) \u22a2 T # (ef_lbl (lbl_id (lid_f X))) :: E \u27e7\n    \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    (X :: \u03be\u2081) (X :: \u03be\u2082)\n    (L_subst_tm (lid_f X) t\u2081) (L_subst_tm (lid_f X) t\u2082) \u2192\nn \u22a8 \ud835\udce3\u27e6 \u039e \u22a2 T # E \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 (\u2b07 t\u2081) (\u2b07 t\u2082).\nProof.\nintros FrX_E FrX_\u03be\u2081 FrX_\u03be\u2082 Ht.\nspecialize (ccompat_tm_down_aux FrX_E) as H.\nispecialize H ([] : list var).\nispecialize H ([] : list var).\niespecialize H.\nrepeat rewrite app_nil_l in H.\nsimpl ktx_plug in H.\n\neapply \ud835\udce3_step_r.\n{ apply step_Down with (X := X) ; assumption. }\neapply \ud835\udce3_step_l.\n{ apply step_Down with (X := X) ; assumption. }\n\niintro_later.\niespecialize H ; ispecialize H ; [ apply Ht | ].\nerewrite I_iff_elim_M ; [ apply H | apply X_weaken_\ud835\udce3 ] ; crush.\nQed.\n\nEnd section_ccompat_tm_down.\n\n\nSection section_compat_tm_down.\nContext (n : nat).\nContext (EV LV V : Set).\nContext (\u039e : XEnv EV LV).\nContext (\u0393 : V \u2192 ty \u2205 EV LV \u2205).\nContext (Wf_\u0393 : wf_\u0393 \u039e \u0393).\nContext (t\u2081 t\u2082 : tm EV LV V (inc \u2205)).\nContext (T : ty \u2205 EV LV \u2205) (E : eff \u2205 EV LV \u2205).\nContext (Wf_\u039e : wf_XEnv \u039e).\nContext (Wf_T : wf_ty \u039e T).\nContext (Wf_E : wf_eff \u039e E).\n\nLemma compat_tm_down (B : vars) :\n( \u2200 X, X \\notin B \u2192\n  n \u22a8 \u27e6 (\u039e & (X ~ (T, E))) \u0393 \u22a2\n        (L_subst_tm (lid_f X) t\u2081) \u227c\u02e1\u1d52\u1d4d (L_subst_tm (lid_f X) t\u2082) :\n        T # (ef_lbl (lbl_id (lid_f X))) :: E \u27e7\n) \u2192\nn \u22a8 \u27e6 \u039e \u0393 \u22a2 (\u2b07 t\u2081) \u227c\u02e1\u1d52\u1d4d (\u2b07 t\u2082) : T # E \u27e7.\nProof.\nintro Ht.\niintro \u03be\u2081 ; iintro \u03be\u2082 ; iintro \u03b4\u2081 ; iintro \u03b4\u2082 ; iintro \u03b4 ;\niintro \u03c1\u2081 ; iintro \u03c1\u2082 ; iintro \u03c1 ; iintro \u03b3\u2081 ; iintro \u03b3\u2082.\npick_fresh_gen (from_list \u03be\u2081 \\u from_list \u03be\u2082 \\u B) X.\nassert (X \u2209 B) as FrB ; [ crush | ].\nspecialize (Ht X FrB).\niintro H\u03be ; iintro cl_\u03b4 ; iintro cl_\u03c1\u2081\u03c1\u2082 ; iintro H\u03b3.\nielim_prop H\u03be ; specialize H\u03be as H\u03be_copy ; destruct H\u03be_copy as [H\u03be\u2081 H\u03be\u2082].\nielim_prop cl_\u03c1\u2081\u03c1\u2082.\n\nassert (X \u2209 from_list \u03be\u2081) as Fr\u03be\u2081 ; [ crush | ].\nassert (X \u2209 from_list \u03be\u2082) as Fr\u03be\u2082 ; [ crush | ].\nassert (X \u2209 dom \u039e) as Fr\u039e ; [ intro ; crush | ].\n\nispecialize Ht (X :: \u03be\u2081) ; ispecialize Ht (X :: \u03be\u2082).\nispecialize Ht \u03b4\u2081 ; ispecialize Ht \u03b4\u2082 ; ispecialize Ht \u03b4.\nispecialize Ht \u03c1\u2081 ; ispecialize Ht \u03c1\u2082 ; ispecialize Ht \u03c1.\nispecialize Ht \u03b3\u2081 ; ispecialize Ht \u03b3\u2082.\nispecialize Ht.\n{ iintro_prop ; split ; [ clear - H\u03be\u2081 | clear - H\u03be\u2082 ] ;\n  rewrite dom_concat, from_list_cons, dom_single, union_comm ;\n  apply subset_union_2 ; crush.\n}\nispecialize Ht.\n{ repeat iintro ; iespecialize cl_\u03b4 ; ispecialize cl_\u03b4 ; [ eassumption | ].\n  repeat rewrite from_list_cons ; ielim_prop cl_\u03b4 ; crush.\n}\nispecialize Ht.\n{ iintro_prop ; intros \u03b1 Y ; specialize (cl_\u03c1\u2081\u03c1\u2082 \u03b1 Y) ;\n  clear - cl_\u03c1\u2081\u03c1\u2082 ; repeat rewrite from_list_cons ; crush.\n}\nispecialize Ht.\n{ iintro x ; ispecialize H\u03b3 x ; clear - Wf_\u039e Wf_\u0393 Wf_T Wf_E Fr\u039e H\u03b3.\n  erewrite <- I_iff_elim_M ; [ | apply X_weaken_\ud835\udce5 ; crush ].\n  eauto.\n}\n\nsimpl.\napply ccompat_tm_down with (X := X) ; try assumption.\n+ iintro \u03be\u2081' ; iintro \u03be\u2082' ;\n  iintro s\u2081 ; iintro s\u2082 ; iintro \u03c8 ; iintro Xs\u2081 ; iintro Xs\u2082 ; iintro Hs.\n  erewrite <- I_iff_elim_M in Hs ; [ | apply X_weaken_\ud835\udce4 ; crush ].\n  iintro_prop.\n  assert (Xs\u2081 \\c from_list \u03be\u2081 \u2227 Xs\u2082 \\c from_list \u03be\u2082) as HXs\u2081Xs\u2082.\n  { eapply \ud835\udce4_is_closed ; eassumption. }\n  clear - HXs\u2081Xs\u2082 Fr\u03be\u2081 Fr\u03be\u2082.\n  destruct HXs\u2081Xs\u2082.\n  split ; intro ; auto.\n+ clear - Ht.\n  repeat erewrite <- V_L_bind_tm, <- EV_L_bind_tm, <- LV_L_bind_tm.\n  { apply Ht. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_lbl, L_bind_lbl_id, L_map_lbl_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_eff, L_bind_eff_id, L_map_eff_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_val, L_bind_val_id, L_map_val_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_lbl, L_bind_lbl_id, L_map_lbl_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_eff, L_bind_eff_id, L_map_eff_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_val, L_bind_val_id, L_map_val_id ; crush. }\nQed.\n\nEnd section_compat_tm_down.\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_down.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19734484463400281}}
{"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 PSCIAux2.Specs.psci_cpu_on_target.\nRequire Import PSCIAux2.LowSpecs.psci_cpu_on_target.\nRequire Import PSCIAux2.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_runnable_spec\n       buffer_unmap_spec\n       granule_unlock_spec\n       set_psci_result_x0_spec\n       psci_reset_rec_spec\n       set_rec_pc_spec\n       set_rec_runnable_spec\n       set_psci_result_forward_psci_call_spec\n       set_psci_result_forward_x1_spec\n    .\n\n  Lemma psci_cpu_on_target_spec_exists:\n    forall habd habd'  labd g_target_rec target_rec rec entry_point_address target_cpu\n           (Hspec: psci_cpu_on_target_spec g_target_rec target_rec rec entry_point_address target_cpu habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', psci_cpu_on_target_spec0 g_target_rec target_rec rec entry_point_address target_cpu labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel. destruct g_target_rec, target_rec, rec.\n    unfold psci_cpu_on_target_spec, psci_cpu_on_target_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    unfold ref_accessible in *; simpl.\n    repeat (simpl_htarget; srewrite; simpl in * ).\n    eexists; split. reflexivity. constructor; simpl.\n    repeat simpl_update_reg.\n    repeat (repeat simpl_field; repeat swap_fields).\n    rewrite <- C12. reflexivity.\n    eexists; split. reflexivity. constructor. rewrite <- C12. 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/PSCIAux2/RefProof/psci_cpu_on_target.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsIntro.Layer.\nRequire Import TableDataOpsRef1.Code.table_unmap1.\n\nRequire Import TableDataOpsRef1.LowSpecs.table_unmap1.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _table_unmap \u21a6 gensem table_unmap_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_table_unmap: block.\n    Hypothesis h_table_unmap_s : Genv.find_symbol ge _table_unmap = Some b_table_unmap.\n    Hypothesis h_table_unmap_p : Genv.find_funct_ptr ge b_table_unmap\n                                 = Some (External (EF_external _table_unmap\n                                                  (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))\n                                        (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).\n    Local Opaque table_unmap_spec.\n\n    Lemma table_unmap1_body_correct:\n      forall m d d' env le g_rd_base g_rd_offset map_addr level res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))\n             (HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))\n             (HPTlevel: PTree.get _level le = Some (Vlong level))\n             (Hspec: table_unmap1_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned map_addr)) (VZ64 (Int64.unsigned level)) d = Some (d', VZ64 (Int64.unsigned res))),\n           exists le', (exec_stmt ge env le ((m, d): mem) table_unmap1_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).\n    Proof.\n      solve_code_proof Hspec table_unmap1_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef1/CodeProof/table_unmap1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.1973448446340028}}
{"text": "\nFrom Undecidability.FOL Require Import Syntax.Facts Syntax.Asimpl Deduction.FragmentNDFacts Deduction.FragmentNDConsistency Syntax.Theories Semantics.Kripke.FragmentCore\n                                       Semantics.Kripke.FragmentSoundness \n                                       Semantics.Kripke.FragmentToTarski Deduction.FragmentSequent Deduction.FragmentSequentFacts.\nFrom Undecidability.Synthetic Require Import Definitions DecidabilityFacts MPFacts 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.\nFrom Undecidability.FOL.Completeness Require Export TarskiCompleteness.\n(* From Undecidability.FOLC Require Export Gentzen. *)\n\n(* ** Universal Models *)\n\nSection KripkeCompleteness.\n  Context {\u03a3f : funcs_signature} {\u03a3p : preds_signature}. (*\n  Variable eF : nat -> option \u03a3f.\n  Context {HeF : enumerator__T eF \u03a3f}.\n  Variable eP : nat -> option \u03a3p.\n  Context {HeP : enumerator__T eP \u03a3p}. *)\n\n(*  Hint Constructors sprv. *)\n  Instance model_bot : interp term :=\n    {| i_func := func; i_atom := fun P v => False|}.\n  Lemma universal_interp_eval rho t :\n    eval rho t = t`[rho].\n  Proof.\n    now induction t; cbn.\n  Qed.\n\n  Section Contexts.\n\n    Program Instance K_ctx {ff:falsity_flag} : kmodel term :=\n      {|\n        nodes := list form ;\n        reachable := @incl form ;\n        k_interp := model_bot ;\n        k_P := fun A P v => sprv A None (atom P v) ;\n      |}.\n    Next Obligation.\n      abstract (eauto using seq_Weak).\n    Qed.\n\n    Definition F_P {ff} : list (@form _ _ _ ff) -> Prop := match ff with falsity_on => fun n => sprv n None \u22a5 | _ => fun _ => False end.\n    Lemma mon_F {ff:falsity_flag} (u v : @nodes _ _ _ K_ctx) : reachable u v -> F_P u -> F_P v.\n    Proof.\n      cbn. unfold F_P. destruct ff; try easy. intros H H1. eapply seq_Weak; [ exact H1| exact H].\n    Qed.\n\n    Notation \"rho '\u22a9\u22a5(' u , M ')' phi\" :=  (@ksat_bot _ _ _ M _ F_P mon_F u rho phi) (at level 20).\n\n    Lemma K_ctx_correct_exp {ff:falsity_flag} (A : list form) rho phi :\n      (rho \u22a9\u22a5(A, K_ctx ) phi-> A \u22a2S phi[rho]) /\\\n      ((forall B psi, A <<= B -> B ;; phi[rho] \u22a2s psi -> B \u22a2S psi) -> rho \u22a9\u22a5(A, K_ctx) phi).\n    Proof.\n      revert A rho; enough ((forall A rho, rho \u22a9\u22a5( A, K_ctx) phi -> A \u22a2S phi[rho]) /\\\n                          (forall A rho, (forall B psi, A <<= B -> B;; phi[rho] \u22a2s psi -> B \u22a2S psi)\n                                  -> rho \u22a9\u22a5( A, K_ctx) phi)) by intuition.\n      induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi]; cbn; split; intros A rho.\n      - tauto.\n      - eauto.\n      - erewrite Vector.map_ext. 1: eauto. apply universal_interp_eval.\n      - intros H. erewrite Vector.map_ext. 1: now apply H. apply universal_interp_eval.\n      - intros Hsat. apply IR, IHpsi. apply Hsat, IHphi. 1: intuition. eauto.\n      - intros H B HB Hphi % IHphi. apply IHpsi. intros C xi HC Hxi. apply H.\n        1: now transitivity B. eauto using seq_Weak.\n      - intros Hsat. apply AllR.\n        pose (phi' := phi[up rho]).\n        destruct (find_bounded_L (phi' :: A)).\n        eapply seq_nameless_equiv_all' with (n := x) (phi := phi').\n        + intros xi Hxi. apply b. now right.\n        + eapply bounded_up. 1: apply b; now left. lia.\n        + unfold phi'. asimpl. apply IHphi, Hsat.\n      - intros H t. apply IHphi. intros B psi HB Hpsi. apply H. assumption.\n        apply AllL with (t := t). now asimpl.\n    Qed.\n\n    Corollary K_ctx_sprv_exp {ff:falsity_flag} A rho phi :\n      rho \u22a9\u22a5(A, K_ctx) phi -> A \u22a2S phi[rho].\n    Proof.\n      now destruct (K_ctx_correct_exp A rho phi).\n    Qed.\n\n    Lemma K_ctx_subst_exp {ff:falsity_flag} A phi rho :\n      rho \u22a9\u22a5( A, K_ctx) phi <-> var \u22a9\u22a5( A, K_ctx) phi[rho].\n    Proof.\n      unfold ksat_bot, falsity_to_pred.\n      rewrite <- atom_subst_comp. 2:easy.\n      assert (forall {ff:falsity_flag} rho, (atom (\u03a3_preds := \u03a3_preds_bot) (inl tt) (Vector.nil _)) = (atom (\u03a3_preds := \u03a3_preds_bot) (inl tt) (Vector.nil _))[rho]) as Heq by easy.\n      erewrite Heq.\n      rewrite <- subst_falsity_comm. cbn.\n      rewrite (ksat_comp A var rho).\n      apply ksat_ext. intros x. unfold funcomp. induction (rho x); cbn; try easy.\n      erewrite <- map_ext_forall. 2: apply Forall_in, IH. \n      now rewrite Vector.map_id.\n    Qed.\n\n    Lemma K_ctx_constraint_exp {ff:falsity_flag} A rho psi:\n      rho \u22a9\u22a5(A, K_ctx) (\u22a5 \u2192 psi).\n    Proof.\n      destruct ff eqn : Hff; try now intros.\n      intros v B HB. cbn in HB. apply K_ctx_correct_exp.\n      intros B' psi' HB' Hprv. subst. eauto using seq_Weak.\n    Qed.\n\n    Corollary K_ctx_ksat_exp {ff:falsity_flag} A rho phi :\n      (forall B psi, A <<= B -> B ;; phi[rho] \u22a2s psi -> B \u22a2S psi) -> rho \u22a9\u22a5(A, K_ctx) phi.\n    Proof.\n      now destruct (K_ctx_correct_exp A rho phi).\n    Qed.\n \n    #[local] Existing Instance falsity_off.\n\n    Lemma K_ctx_correct (A : list form) rho phi :\n      (rho \u22a9(A, K_ctx ) phi-> A \u22a2S phi[rho]) /\\\n      ((forall B psi, A <<= B -> B ;; phi[rho] \u22a2s psi -> B \u22a2S psi) -> rho \u22a9(A, K_ctx) phi).\n    Proof.\n      revert phi. remember falsity_off as ff eqn:Heqff. intros phi.\n      revert A rho; enough ((forall A rho, rho \u22a9( A, K_ctx) phi -> A \u22a2S phi[rho]) /\\\n                          (forall A rho, (forall B psi, A <<= B -> B;; phi[rho] \u22a2s psi -> B \u22a2S psi)\n                                  -> rho \u22a9( A, K_ctx) phi)) by intuition.\n      induction phi as [|t1 t2|ff [] phi IHphi psi IHpsi|ff [] phi IHphi]; cbn; split; intros A rho.\n      - tauto.\n      - congruence.\n      - erewrite Vector.map_ext. 1: eauto. apply universal_interp_eval.\n      - intros H. erewrite Vector.map_ext. 1: now apply H. apply universal_interp_eval.\n      - intros Hsat. apply IR, IHpsi. 1:easy. apply Hsat, IHphi. 1: intuition. 1:easy. eauto.\n      - intros H B HB Hphi % IHphi. 2:easy. apply IHpsi. 1:easy. intros C xi HC Hxi. apply H.\n        1: now transitivity B. eauto using seq_Weak.\n      - intros Hsat. apply AllR.\n        pose (phi' := phi[up rho]).\n        destruct (find_bounded_L (phi' :: A)).\n        eapply seq_nameless_equiv_all' with (n := x) (phi := phi').\n        + intros xi Hxi. apply b. now right.\n        + eapply bounded_up. 1: apply b; now left. lia.\n        + unfold phi'. asimpl. apply IHphi, Hsat. easy.\n      - intros H t. apply IHphi. 1:easy. intros B psi HB Hpsi. apply H. assumption.\n        apply AllL with (t := t). now asimpl.\n    Qed.\n\n    Corollary K_ctx_sprv A rho phi :\n      rho \u22a9(A, K_ctx) phi -> A \u22a2S phi[rho].\n    Proof.\n      now destruct (K_ctx_correct A rho phi).\n    Qed.\n\n    Lemma K_ctx_subst A phi rho :\n      rho \u22a9( A, K_ctx) phi <-> var \u22a9( A, K_ctx) phi[rho].\n    Proof.\n      rewrite (ksat_comp A var rho).\n      apply ksat_ext. intros x. unfold funcomp. induction (rho x); cbn; try easy.\n      erewrite <- map_ext_forall. 2: apply Forall_in, IH. \n      now rewrite Vector.map_id.\n    Qed.\n\n    Corollary K_ctx_ksat A rho phi :\n      (forall B psi, A <<= B -> B ;; phi[rho] \u22a2s psi -> B \u22a2S psi) -> rho \u22a9(A, K_ctx) phi.\n    Proof.\n      now destruct (K_ctx_correct A rho phi).\n    Qed.\n  End Contexts.\n\n  Section ExplodingCompleteness.\n\n    Lemma K_ctx_exploding {ff:falsity_flag}:\n      kexploding mon_F.\n    Proof.\n      unfold kexploding.\n      apply K_ctx_constraint_exp.\n    Qed.\n\n    Lemma K_exp_completeness A phi :\n      kvalid_exploding_ctx A phi -> A \u22a2SE phi.\n    Proof.\n      intros Hsat. erewrite <-subst_id. 1: apply K_ctx_sprv_exp with (rho := var). 2: reflexivity.\n      apply Hsat. 1: apply K_ctx_exploding. intros psi Hpsi. apply K_ctx_ksat_exp. intros B xi HB Hxi.\n      rewrite subst_id in Hxi. 2:reflexivity. eauto.\n    Qed.\n\n    Ltac clean_ksoundness :=\n      match goal with\n      | [ H : ?x = ?x -> _ |- _ ] => specialize (H eq_refl)\n      | [ H : (?A -> ?B), H2 : (?A -> ?B) -> _ |- _] => specialize (H2 H)\n      end.\n    Lemma K_exp_ksoundness {ff:falsity_flag} A phi :\n      A \u22a2I phi -> kvalid_exploding_ctx A phi.\n    Proof.\n      intros Hprv. cbn in Hprv. intros D M F_P mon_F u rho Hexpl. revert u rho.\n      remember intu as s in Hprv. induction Hprv; subst; cbn; intros u rho HA.\n      all: repeat (clean_ksoundness + discriminate). all: (eauto || cbn ; eauto).\n      - intros v Hr Hpi. eapply IHHprv. intros ? []; subst; eauto using ksat_mon. eapply ksat_mon. 2: now apply HA. easy.\n      - eapply IHHprv1. 3: eapply IHHprv2. all: eauto. apply M.\n      - intros d. apply IHHprv. intros psi [psi' [<- Hp]] % in_map_iff. cbn.\n        unfold ksat_bot. rewrite falsity_to_pred_subst.\n        rewrite ksat_comp. apply HA, Hp.\n      - unfold ksat_bot. rewrite falsity_to_pred_subst.\n        rewrite ksat_comp. eapply ksat_ext. 2: eapply (IHHprv u rho HA (eval rho t)). \n        unfold funcomp. now intros [].\n      - apply (Hexpl u rho phi u (ltac:(apply M))).\n        specialize (IHHprv u rho HA). cbn in IHHprv. apply IHHprv.\n    Qed.\n\n    Lemma K_exp_seq_ksoundness {ff:falsity_flag} A phi :\n      A \u22a2SE phi -> kvalid_exploding_ctx A phi.\n    Proof.\n      intros H%seq_ND. now apply K_exp_ksoundness.\n    Qed.\n\n    Fact SE_cut A phi psi :\n      A \u22a2SE phi -> A;;phi \u22a2sE psi -> A \u22a2SE psi.\n    Proof.\n      intros H1 % seq_ND H2 % seq_ND; cbn in *.\n      apply H2 in H1. apply K_exp_completeness.\n      apply K_exp_ksoundness. firstorder.\n    Qed.\n    \n  End ExplodingCompleteness.\n\n  Section BottomlessCompleteness.\n    #[local] Existing Instance falsity_off.\n\n    Lemma K_bottomless_completeness A phi :\n      kvalid_ctx A phi -> A \u22a2S phi.\n    Proof.\n      intros Hsat. erewrite <- subst_id. apply K_ctx_sprv with (rho := var). 2: reflexivity.\n      apply Hsat. intros psi Hpsi. apply K_ctx_ksat. intros B xi HB Hxi.\n      rewrite subst_id in Hxi. 2:easy. eauto.\n    Qed.\n  End BottomlessCompleteness.\n\n(* *** Standard Models *)\n\n  Section StandardCompleteness.\n    #[local] Existing Instance falsity_on.\n\n    Definition cons A := ~ A \u22a2SE \u22a5.\n    Definition cons_ctx := { A | cons A }.\n    Definition ctx_incl (A B : cons_ctx) := incl (proj1_sig A) (proj1_sig B).\n\n    #[local] Hint Unfold cons cons_ctx ctx_incl : core.\n\n    Notation \"A <<=C B\" := (ctx_incl A B) (at level 20).\n    Notation \"A \u22a2SC phi\" := ((proj1_sig A) \u22a2SE phi) (at level 20).\n    Notation \"A ;; psi \u22a2sC phi\" := ((proj1_sig A) ;; psi \u22a2sE phi) (at level 20).\n\n    Ltac dest_con_ctx :=\n      match goal with\n      | [ |- forall u : cons_ctx, _] => let Hu := fresh \"H\" u in intros [u Hu]\n      | [ A : cons_ctx |- _] => let HA := fresh \"H\" A in destruct A as [A HA]\n      end.\n\n    Ltac cctx := repeat (progress dest_con_ctx; unfold ctx_incl); cbn.\n\n    Hint Extern 1 => cctx : core.\n\n    Program Instance K_std : kmodel term :=\n      {|\n        reachable := ctx_incl ;\n        k_interp := model_bot ;\n        k_P := fun A P v => ~ ~ A \u22a2SC (@atom _ _ _ _ P v) \n      |}.\n    Next Obligation.\n      abstract (apply H0; intros K; apply H1; eapply seq_Weak; eauto).\n    Qed.\n\n    Lemma K_std_correct (A : cons_ctx) rho phi :\n      (rho \u22a9(A, K_std) phi -> ~ ~ A \u22a2SC phi[rho]) /\\\n      ((forall B psi, A <<=C B -> B ;; phi[rho] \u22a2sC psi -> ~ ~ B \u22a2SC psi) -> rho \u22a9(A, K_std) phi).\n    Proof.\n      revert A rho; enough ((forall A rho, rho \u22a9( A, K_std) phi -> ~ ~ A \u22a2SC phi[rho])\n                          /\\ (forall A rho, (forall B psi, A <<=C B -> B;; phi[rho] \u22a2sC psi -> ~ ~ B \u22a2SC psi)\n                                    -> rho \u22a9( A, K_std) phi)) by firstorder.\n      induction phi as [| t1 t2 | [ ] phi [IHphi1 IHphi2] psi [IHpsi1 IHpsi2] | [ ] phi [IHphi1 IHphi2] ] using form_ind_falsity.\n      all: cbn; split; intros A rho.\n      - tauto.\n      - intros H. exfalso. apply (H A \u22a5); auto.\n      - now rewrite (Vector.map_ext _ _ _ _ (universal_interp_eval rho)).\n      - rewrite <- (Vector.map_ext _ _ _ _ (universal_interp_eval rho)). intros H H'.\n        eapply H. 3: { intros H1. apply H', H1. } all: auto.\n      - intros Hsat H.\n        assert (HA : ~ ~ ((phi[rho] :: proj1_sig A) \u22a2SE \u22a5 \\/ ~ (phi[rho] :: proj1_sig A) \u22a2SE \u22a5)) by tauto.\n        apply HA. clear HA. intros [HA|HA].\n        + apply H. apply IR. apply Absurd. assumption.\n        + pose (A' := exist cons (phi[rho] :: proj1_sig A) HA). apply (IHpsi1 A' rho).\n          * apply Hsat. 1: now apply incl_tl. apply IHphi2. intros B theta HB HT.\n            intros H'. apply H'. eauto.\n          * intros H'. apply H. apply IR, H'.\n      - intros H B HB Hphi % IHphi1. apply IHpsi2. intros C xi HC Hxi.\n        intros HX. apply Hphi. intros Hphi'. apply (H C xi); trivial.\n        + cctx. now transitivity B.\n        + apply IL; trivial. eapply seq_Weak; eauto.\n      - pose (phi' := subst_form ($0 .: (rho >> subst_term (S >> var))) phi).\n        intros Hsat. intros H. cctx. destruct (find_bounded_L (phi' :: A)) as [x b].\n        apply (IHphi1 (exist cons A HA) ($x.:rho)).\n        rewrite ksat_ext. 2: reflexivity. now apply Hsat.\n        intros H'. apply H, AllR. cbn.\n        eapply seq_nameless_equiv_all' with (n := x) (phi := phi').\n        + intros xi Hxi. apply b. now right.\n        + eapply bounded_up. 1: apply b; now left. lia.\n        + unfold phi'. cbn in H'. now asimpl.\n      - intros H t. apply IHphi2. intros B psi HB Hpsi. apply H. assumption.\n        apply AllL with (t := t). now asimpl.\n    Qed.\n\n    Corollary K_std_sprv A rho phi :\n      rho \u22a9(A, K_std) phi -> ~ ~ A \u22a2SC phi[rho].\n    Proof.\n      now destruct (K_std_correct A rho phi).\n    Qed.\n\n    Corollary K_std_sprv' A rho phi :\n       ~ ~ A \u22a2SC phi[rho] -> rho \u22a9(A, K_std) phi.\n    Proof.\n      intros H. apply (K_std_correct A rho phi).\n      intros B psi H1 H2 H3. apply H. intros H'.\n      apply H3. eapply SE_cut; try eassumption.\n      now apply (seq_Weak H').\n    Qed.\n\n    Corollary K_std_ksat A rho phi :\n      (forall B psi, A <<=C B -> B ;; phi[rho] \u22a2sC psi -> ~ ~ B \u22a2SC psi) -> rho \u22a9(A, K_std) phi.\n    Proof.\n      now destruct (K_std_correct A rho phi).\n    Qed.\n\n    Lemma K_std_completeness A phi :\n      kvalid_ctx A phi -> ~ ~ A \u22a2SE phi.\n    Proof.\n      intros Hsat H.\n      assert (HA : ~ ~ (A \u22a2SE \u22a5 \\/ ~ A \u22a2SE \u22a5)) by tauto.\n      apply HA. clear HA. intros [HA|HA].\n      - apply H. apply Absurd. assumption.\n      - specialize (Hsat _ K_std (exist cons A HA) var).\n        apply K_std_sprv in Hsat.\n        + apply Hsat. intros Hsat'. apply H.\n          erewrite <- subst_id; trivial. apply Hsat'.\n        + intros psi Hpsi. apply K_std_ksat.\n          intros B xi HB Hxi. asimpl in Hxi. eauto.\n    Qed.\n\n    Lemma K_std_seq_ksoundness A phi :\n      A \u22a2SE phi -> kvalid_ctx A phi.\n    Proof.\n      intros H % seq_ND. apply ksoundness, H.\n    Qed.\n  End StandardCompleteness.\n\n\n  Section Stability.\n    Existing Instance falsity_on.\n    Context (T_kind : theory -> Prop).\n    Definition K_completeness := forall T phi, T_kind T -> closed_T T -> closed phi -> \n                  kvalid_theo T phi -> T \u22a9SE phi.\n    Lemma kcompleteness_implies_stability T phi : K_completeness ->\n      T_kind (tmap negative_translation T) ->\n      closed_T T -> closed phi ->\n      ~ ~ T \u22a2TC phi -> T \u22a2TC phi.\n    Proof.\n      intros Hcomp kindT clT clphi HTDN.\n      apply DN_T. apply nt_correct_theory. cbn. apply seq_ND_T.\n      apply Hcomp.\n      - easy.\n      - apply tmap_closed. 1: apply nt_bounded. easy.\n      - unfold closed. solve_bounds. apply nt_bounded. apply clphi.\n      - intros D M u rho HT.\n        intros v Huv Hphiv. cbn. apply HTDN.\n        intros (A & HTA & HTphi). eapply nt_Cprv_to_Iprv in HTphi.\n        eapply DN_into in HTphi.\n        apply ksoundness in HTphi.\n        unshelve eapply (@HTphi D M u rho _ v Huv Hphiv).\n        intros ? (psi & <- & HApsi) %in_map_iff. apply HT.\n        exists psi. split; try easy. now apply HTA.\n    Qed.\n  End Stability.\n\n  Section MP_Equivalence.\n    Definition kcompleteness_enumerable := K_completeness enumerable.\n\n    Lemma bot_deriv_stable_enum_k (T : @theory _ _ _ falsity_on) : kcompleteness_enumerable -> closed_T T -> enumerable T ->\n      stable (@FragmentND.tprv _ _ _ class T \u22a5).\n    Proof.\n      intros Hcomp Hclosed Henum HC.\n      apply (kcompleteness_implies_stability Hcomp); try easy. 2: econstructor.\n      now apply enum_tmap.\n    Qed.\n\n(*\n    Lemma MP_implies_kcompleteness_enum : MP -> kcompleteness_enumerable.\n    Proof.\n      intros Hmp T phi HT Hphi Henum Hvalid.\n      apply completeness_classical_stability; eauto. unfold stable.\n      eapply mp_tprv_stability; try tauto. now eapply enumerable_list_enumerable.\n    Qed.\n*)\n    Lemma kcompleteness_enum_implies_MP : kcompleteness_enumerable -> MP.\n    Proof.\n      intros HC f Hf.\n      pose (fun x : form => exists n, x = \u22a5 /\\ f n = true) as T.\n      assert (closed_T T) as Hclosed by (now intros k [n [-> Hn]]; econstructor).\n      assert (enumerable T) as Henum.\n      { exists (fun n => if f n then Some (\u22a5) else None). intros phi; split; intros H.\n        + destruct H as (n & Heq & Hfn). exists n. rewrite Hfn. now rewrite Heq.\n        + destruct H as (n & Hn). unfold T. exists n. destruct (f n); try congruence.\n          split; try easy. congruence.\n       }\n      pose proof (@bot_deriv_stable_enum_k T HC Hclosed Henum).\n      enough (T \u22a2TC \u22a5) as [[|lx lr] [HL HL']].\n      - exfalso. eapply consistent_ND. apply HL'.\n      - destruct (HL lx) as (n & Heq & Hfn). 1:now left. now exists n.\n      - apply H. intros Hc. apply Hf. intros [n Hn]. apply Hc. exists [\u22a5]. split.\n        + intros ? [<- | []]. unfold T. exists n. split; try easy.\n        + apply Ctx; now left.\n    Qed.\n\n  End MP_Equivalence.\n\n  Section LEM_Equivalence.\n    Definition kcompleteness_arbitrary := K_completeness (fun x => True).\n    Definition LEM := forall (P:Prop), P \\/ ~ P.\n\n    Lemma bot_valid_stable (T : @theory _ _ _ falsity_on) : closed_T T -> stable (valid_theory_C (classical (ff := falsity_on)) T \u22a5).\n    Proof.\n      intros Hclosed HH D I rho Hclass H.\n      apply HH. intros Hc. apply (Hc D I rho Hclass H).\n    Qed.\n    Lemma bot_deriv_stable_k (T : @theory _ _ _ falsity_on) : kcompleteness_arbitrary -> \n      closed_T T -> stable (@FragmentND.tprv _ _ _ class T \u22a5).\n    Proof.\n      intros Hcomp Hclosed HC.\n      apply (kcompleteness_implies_stability Hcomp); try easy. econstructor.\n    Qed.\n    Existing Instance falsity_on.\n    Lemma kcompleteness_implies_LEM : kcompleteness_arbitrary -> LEM.\n    Proof.\n      intros HC P.\n      pose (fun x : form => closed x /\\ (P \\/ ~P)) as T.\n      assert (closed_T T) as Hclosed by (intros k; cbv; tauto).\n      pose proof (@bot_deriv_stable_k T HC Hclosed).\n      enough (T \u22a2TC \u22a5) as [[|lx lr] [HL HL']].\n      - exfalso. eapply consistent_ND. apply HL'.\n      - eapply HL. now left.\n      - enough (~~ (P \\/ ~P)).\n        + apply H. intros Hc. apply H0. intros Hc2. apply Hc. exists [\u22a5]. split; try (apply Ctx; now left).\n          intros ? [<- | []]. cbv. split; try apply Hc2. econstructor.\n        + tauto.\n    Qed.\n(*\n    Lemma LEM_implies_kcompleteness : LEM -> kcompleteness_arbitrary.\n    Proof.\n      intros Hlem T phi HT Hphi Hvalid Htheo.\n      destruct (Hlem (T \u22a9SE phi)); try easy. exfalso.\n      apply K_std_completeness.\n      intros H. destruct (Hlem (T \u22a2TC phi)); tauto.\n    Qed.\n*)\n  End LEM_Equivalence.\n\nEnd KripkeCompleteness.\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/KripkeCompleteness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.1973396011434979}}
{"text": "\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution.Test Require Import QCTest.\nFrom ConCert.Examples.Dexter Require Import Dexter.\nFrom ConCert.Examples.Dexter Require Export DexterPrinters.\nFrom ConCert.Examples.Dexter Require Import DexterGens.\nFrom ConCert.Examples.EIP20 Require Import EIP20Token.\nFrom Coq Require Import ZArith_base.\nFrom Coq Require Import List. Import ListNotations.\n\n\nDefinition token_pool_size : N := 100.\n\nDefinition token_setup : EIP20Token.Setup := {|\n  EIP20Token.owner := creator;\n  EIP20Token.init_amount := token_pool_size;\n|}.\n\nDefinition token_caddr : Address := addr_of_Z 128.\nDefinition dexter_caddr : Address := addr_of_Z 129.\n\n(* Dexter will have 60 tokens in reverse initially *)\nDefinition dexter_setup : Dexter.Setup := {|\n  token_caddr_ := token_caddr;\n  token_pool_ := (token_pool_size - 40);\n|}.\n\nDefinition add_as_operator_act owner operator tokens :=\n  build_call owner token_caddr 0 (EIP20Token.approve operator tokens).\n\nDefinition exchange_tokens_to_money_act owner amount :=\n  build_call owner dexter_caddr 0 (Dexter.tokens_to_asset {|\n    exchange_owner := owner;\n    tokens_sold := amount;\n  |}).\n\n(* Set up a chain with token contract, and dexter contract deployed.\n   Also adds some tokens to person_1 and dexter contract, and adds some operators on the fa2 contract *)\nDefinition chain : ChainBuilder :=\n  unpack_result (TraceGens.add_block builder_initial\n  [ (* Give 10 to person 1 *)\n    build_transfer creator person_1 10 ;\n    (* Deploy contracts *)\n    build_deploy creator 0 EIP20Token.contract token_setup ;\n    build_deploy creator 30 Dexter.contract dexter_setup ;\n    (* Tranfer tokens to exchange contract and person1 *)\n    build_call creator token_caddr 0 (EIP20Token.transfer person_1 40%N) ;\n    build_call creator token_caddr 0 (EIP20Token.transfer dexter_caddr (token_pool_size - 40)%N) ;\n    (* Let dexter transfer tokens on behalf of person_1 and person_2 *)\n    add_as_operator_act person_1 dexter_caddr token_pool_size ;\n    add_as_operator_act person_2 dexter_caddr token_pool_size\n  ]).\n\nDefinition add_block_with_acts (c : ChainBuilder) acts :=\n  (TraceGens.add_block c acts).\n\nDefinition dexter_state env := get_contract_state Dexter.State env dexter_caddr.\nDefinition token_state env := get_contract_state EIP20Token.State env token_caddr.\n\nModule TestInfo <: DexterTestsInfo.\n  Definition token_caddr := token_caddr.\n  Definition dexter_contract_addr := dexter_caddr.\n  Definition test_accounts := [person_1].\nEnd TestInfo.\nModule MG := DexterGens.DexterGens TestInfo. Import MG.\n\n(* Sample (gDexterAction chain1). *)\n\n(* Sample ((liftM (fun a => add_block_with_acts chain1 [a]) (gDexterAction chain1))). *)\n(* Sample (gDexterChain 2 chain1 1). *)\n\nDefinition person_1_initial_balance : Amount := env_account_balances chain person_1.\n\nDefinition dexter_liquidity chain : Amount := env_account_balances chain dexter_caddr.\n\nDefinition account_tokens (env : Environment) (account : Address) : N :=\n  with_default 0%N (\n    do token_state <- token_state env ;\n    FMap.find account token_state.(EIP20Token.balances)\n    ).\n\nDefinition dexter_token_pool (env : Environment) : N :=\n  with_default 0%N (\n    do s <- dexter_state env ;\n    Some s.(token_pool)\n    ).\n\nOpen Scope Z_scope.\nCoercion Z.of_N : N >-> Z.\n\n(* Asserts that exchanges are priced correctly *)\nDefinition tokens_to_asset_correct_P_opt (old_env new_env : Environment) : option Checker :=\n  do state_dexter <- dexter_state new_env;\n  let person_1_balance := env_account_balances new_env person_1 in\n  let dexter_balance := env_account_balances new_env dexter_caddr in\n  let dexter_initial_balance := env_account_balances old_env dexter_caddr in\n  let dexter_initial_token_reserve := account_tokens old_env dexter_caddr in\n  let dexter_current_token_reserve := account_tokens new_env dexter_caddr in\n  (* We assume only the given account has made exchanges in this time period.\n     This assumption holds for these tests. *)\n  let tokens_received := dexter_current_token_reserve - dexter_initial_token_reserve in\n  (* Calculate token exchange price if only a single exchange was made *)\n  let expected_currency_sold := getInputPrice tokens_received dexter_initial_token_reserve dexter_initial_balance in\n  let expected_dexter_balance := dexter_initial_balance - expected_currency_sold in\n  Some (\n    whenFail (\n      \"dexter balance was \" ++ show dexter_balance ++\n      \" while it was expected to be at least \" ++ show expected_dexter_balance ++ nl ++\n      \"person_1 balance: \" ++ show person_1_balance ++ nl ++\n      \"person_1 tokens: \" ++ show (account_tokens new_env person_1) ++ nl ++\n      \"dexter balance: \" ++ show dexter_balance ++ nl ++\n      \"dexter tokens: \" ++ show dexter_current_token_reserve ++ nl ++\n      \"history: \" ++ show (state_dexter.(price_history))\n    )\n    (checker (expected_dexter_balance <=? dexter_balance))\n  ).\n\nDefinition tokens_to_asset_correct_P old_env env :=\n  match tokens_to_asset_correct_P_opt old_env env with\n  | Some p => p\n  | None => checker true\n  end.\n\nDefinition tokens_to_asset_correct :=\n  forAllChainStatePairs 1 chain (gDexterChain 2) tokens_to_asset_correct_P.\n\n(* We first test the Dexter contract with breadth-first execution model *)\n(* QuickChick (tokens_to_asset_correct). *)\n(* +++ Passed 10000 tests (0 discards) *)\n(* We see that the property holds with breadth-first execution model *)\n\n(* However, the Dexter contract was designed for Tezos which used\n   breadth-first execution model.\n   Thus, we next test the property with that model *)\n(* Extract Constant DepthFirst => \"false\".\nQuickChick (tokens_to_asset_correct). *)\n(*\nChain{|\nBlock 1 [\nAction{act_from: 10%256, act_body: (act_deploy 0, DexterSetup{token_caddr_: 10%256, token_pool_: 100})};\nAction{act_from: 10%256, act_body: (act_deploy 30, DexterSetup{token_caddr_: 128%256, token_pool_: 60})};\nAction{act_from: 10%256, act_body: (act_call 128%256, 0, DexterSetup{token_caddr_: 11%256, token_pool_: 40})};\nAction{act_from: 10%256, act_body: (act_call 128%256, 0, DexterSetup{token_caddr_: 129%256, token_pool_: 60})};\nAction{act_from: 11%256, act_body: (act_call 128%256, 0, approve 129%256 100)}];\nBlock 2 [\nAction{act_from: 11%256, act_body: (act_call 129%256, 0, token_to_asset exchange{exchange_owner: 11%256, tokens_sold: 20})};\nAction{act_from: 11%256, act_body: (act_call 129%256, 0, token_to_asset exchange{exchange_owner: 11%256, tokens_sold: 14})}]; |}\n\ndexter balance was 19 while it was expected to be at least 20\nperson_1 balance: 11\nperson_1 tokens: 6\ndexter balance: 19\ndexter tokens: 94\nhistory: [7; 4]\n*** Failed after 23 tests and 2 shrinks. (0 discards)\n*)\n\n(* We can see that the property fails in breadth-first model when two trades are made\n   in the same block. Below we simulate what goes wrong in this example.\n   The starting configuration is\n   person_1 balance: 10\n   person_1 tokens: 40\n   dexter balance: 30\n   dexter tokens: 60\n*)\n(* Compute (env_account_balances chain person_1). *)\n(* = 10 : N *)\n(* Compute (account_tokens chain person_1). *)\n(* = 40 : N *)\n(* Compute (env_account_balances chain dexter_caddr). *)\n(* = 30 : N *)\n(* Compute (account_tokens chain dexter_caddr). *)\n(* = 60 : N *)\n\n(* If both trades were merged person_1 would get 10 tez for his 34 tokens *)\n(* Compute (getInputPrice 34 60 30). *)\n(* = 10 : Z *)\n\n(* However, this is not what happens, in total person_1 gains 7+4=11 tez from\n   trading 34 tokens (20 in the first trade, 14 in the second) *)\n(* In the first trade person_1 trades 20 tokens for 7 tez *)\n(* Compute (getInputPrice 20 60 30). *)\n(* = 7 : Z *)\n(* In the second trade we would expect person_1 to get 3 tez for his 14 tokens *)\n(* Compute (getInputPrice 14 80 23). *)\n(* = 3 : Z *)\n(* However, this is not the calculation that is being done.\n   Instead the contract computes the yield of the second trade as follows *)\n(* Compute (getInputPrice 14 80 30). *)\n(* = 4 : Z *)\n(* This is because in breadth first execution model both trades gets started before tokens and tez\n   from previous trades have been transferred. Thus trades uses wrong values.\n   Dexter manually tracks and decrements the number of tokens in the reserve because of this.\n   However, the contract doesn't manually track tez the same way, thus the tez amount used is wrong. *)\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/dexter/DexterTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.19726230638345907}}
{"text": "From Coq Require Import\n  String\n  Lists.List\n  .\nFrom PlutusCert Require Import\n  Util\n  Util.List\n  Transform.Congruence\n  Analysis.FreeVars\n  AFI\n  .\nFrom PlutusCert Require\n  Language.PlutusIR\n  .\n\nImport PlutusIR (term(..), tvdecl(..), vdecl(..), ty(..), dtdecl(..), binding(..), constr(..), Recursivity(..)).\nImport PlutusIR.NamedTerm.\nImport ListNotations.\nImport AFI.\n\n(* Rename context*)\nDefinition ctx := list (string * string).\n\n\n(* Binding variable x does not capture free variables in (the pre-term) t if they were renamed\n   according to \u0393 *)\nDefinition no_capture x (\u0393 : ctx) t :=\n  forall y, In (y, x) \u0393 -> ~ AFI.Term.appears_free_in y t.\n\nDefinition no_captureA \u03b1 (\u0394 : ctx) t :=\n  forall \u03b2, In (\u03b2, \u03b1) \u0394 -> ~ AFI.Annotation.appears_free_in \u03b2 t.\n\nDefinition no_ty_capture \u03b1 (\u0394 : ctx) \u03c4 :=\n  forall \u03b2, In (\u03b2, \u03b1) \u0394 -> ~ AFI.Ty.appears_free_in \u03b2 \u03c4.\n\n\nInductive rename_tvs (\u0394 : ctx) (cs : list constructor) : list TVDecl -> list TVDecl -> ctx -> Type :=\n\n  | rn_tvs_nil :\n      rename_tvs \u0394 cs [] [] []\n\n  | rn_tvs_cons : forall \u03b1 tvs k \u03b2 tvs' \u0394_tvs,\n      (* check that the bound tyvar does not capture other renamed vars in the\n         type signatures of the constructors *)\n      Forall (fun '(Constructor (VarDecl _ cty) _) => no_ty_capture \u03b2 \u0394 cty) cs ->\n      rename_tvs ((\u03b1, \u03b2) :: \u0394) cs tvs tvs' \u0394_tvs ->\n      rename_tvs \u0394 cs (TyVarDecl \u03b1 k :: tvs) (TyVarDecl \u03b2 k :: tvs') ((\u03b1, \u03b2) :: \u0394_tvs)\n.\n\nInductive rename_ty (\u0394 : ctx) : Ty -> Ty -> Type :=\n\n   | rn_Ty_Var : forall \u03b1 \u03b1',\n      lookup \u03b1 \u0394 = Some \u03b1' ->\n      rename_ty \u0394 (Ty_Var \u03b1) (Ty_Var \u03b1')\n\n   | rn_Ty_Fun : forall \u03c3 \u03c4 \u03c3' \u03c4',\n      rename_ty \u0394 \u03c3 \u03c3' ->\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename_ty \u0394 (Ty_Fun \u03c3 \u03c4) (Ty_Fun \u03c3' \u03c4')\n\n   | rn_Ty_IFix : forall \u03c3 \u03c4 \u03c3' \u03c4',\n      rename_ty \u0394 \u03c3 \u03c3' ->\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename_ty \u0394 (Ty_IFix \u03c3 \u03c4) (Ty_IFix \u03c3' \u03c4')\n\n   | rn_Ty_Forall : forall \u03b1 \u03b1' k \u03c4 \u03c4',\n      rename_ty ((\u03b1, \u03b1') :: \u0394) \u03c4 \u03c4' ->\n      no_ty_capture \u03b1 \u0394 \u03c4 ->\n      rename_ty \u0394 (Ty_Forall \u03b1 k \u03c4) (Ty_Forall \u03b1' k \u03c4')\n\n   | rn_Ty_Builtin : forall t,\n      rename_ty \u0394 (Ty_Builtin t) (Ty_Builtin t)\n\n   | rn_Ty_Lam : forall \u03b1 \u03b1' k \u03c4 \u03c4',\n      rename_ty ((\u03b1, \u03b1') :: \u0394) \u03c4 \u03c4' ->\n      no_ty_capture \u03b1 \u0394 \u03c4 ->\n      rename_ty \u0394 (Ty_Lam \u03b1 k \u03c4) (Ty_Lam \u03b1' k \u03c4')\n\n   | Ty_App : forall \u03c3 \u03c4 \u03c3' \u03c4',\n      rename_ty \u0394 \u03c3 \u03c3' ->\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename_ty \u0394 (Ty_App \u03c3 \u03c4) (Ty_App \u03c3' \u03c4')\n.\n\nInductive rename (\u0393 \u0394 : ctx) : Term -> Term -> Type :=\n  | rn_Var : forall x y,\n      lookup x \u0393 = Some y ->\n      rename \u0393 \u0394  (Var x) (Var y)\n\n  | rn_Let_Rec : forall bs bs' t t',\n      forall \u0393_bs \u0394_bs,\n      rename_Bindings_Rec (\u0393_bs ++ \u0393) (\u0394_bs ++ \u0394) \u0393_bs \u0394_bs bs bs' ->\n      rename (\u0393_bs ++ \u0393) (\u0394_bs ++ \u0394) t t' ->\n\n      (* All bound type- and term variables in the bindings should not capture _in the body_.\n\n         Alternatively, this could have been implemented by adding `Let NonRec bs t` as \n         an index in rename_binding and putting a simple no_capture at the actual binding *)\n      Forall (fun '(_, x') => no_capture x' \u0393 t) \u0393_bs ->\n      Forall (fun '(_, \u03b1') => no_captureA \u03b1' \u0394 t) \u0394_bs ->\n\n      (* All bound (type) variables have to be unique in the binding group *)\n      NoDup (bvbs bs') ->\n      NoDup (btvbs bs') ->\n\n      rename \u0393 \u0394 (Let Rec bs t) (Let Rec bs' t')\n\n  (* If the decision procedure becomes problematic because of not structurally smaller terms,\n     these two rules should be refactored into a relation similar to rename_Bindings_Rec *)\n  | rn_Let_NonRec_nil : forall t t',\n      rename \u0393 \u0394 t t' ->\n      rename \u0393 \u0394 (Let NonRec [] t) (Let NonRec [] t')\n\n  | rn_Let_NonRec_cons : forall \u0393_b \u0394_b b b' bs bs' t t',\n      rename_binding \u0393 \u0394 \u0393_b \u0394_b b b' ->\n      rename (\u0393_b ++ \u0393) (\u0394_b ++ \u0394) (Let NonRec bs t) (Let NonRec bs' t') ->\n\n      (* All bound (type) variables in the let should not capture.\n\n         Alternatively, add `Let NonRec bs t` as index in rename_binding \n         and put a simple no_capture at the actual binding *)\n      Forall (fun '(_, x') => no_capture x' \u0393 (Let NonRec bs t)) \u0393_b ->\n      Forall (fun '(_, \u03b1') => no_captureA \u03b1' \u0394 (Let NonRec bs t)) \u0394_b ->\n\n      rename \u0393 \u0394 (Let NonRec (b :: bs) t) (Let NonRec (b' :: bs') t')\n\n  | rn_TyAbs : forall \u03b1 \u03b1' k t t',\n      rename ((\u03b1, \u03b1') :: \u0393) \u0394 t t' ->\n      no_captureA \u03b1' \u0394 t ->\n      rename \u0393 \u0394 (TyAbs \u03b1 k t) (TyAbs \u03b1' k t')\n\n  | rn_LamAbs : forall x x' \u03c4 \u03c4' t t',\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename ((x, x') :: \u0393) \u0394 t t' ->\n      no_capture x' \u0394 t ->\n      rename \u0393 \u0394 (LamAbs x \u03c4 t) (LamAbs x' \u03c4' t')\n\n  | rn_Apply : forall s t s' t',\n      rename \u0393 \u0394 s s' ->\n      rename \u0393 \u0394 t t' ->\n      rename \u0393 \u0394 (Apply s t) (Apply s' t')\n\n  | rn_Constant : forall c,\n      rename \u0393 \u0394 (Constant c) (Constant c)\n\n  | rn_Builtin : forall b,\n      rename \u0393 \u0394 (Builtin b) (Builtin b)\n\n  | rn_TyInst : forall t t' \u03c4 \u03c4',\n      rename \u0393 \u0394 t t' ->\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename \u0393 \u0394 (TyInst t \u03c4) (TyInst t' \u03c4')\n\n  | rn_Error : forall \u03c4 \u03c4',\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename \u0393 \u0394 (Error \u03c4) (Error \u03c4')\n\n  | rn_IWrap \u03c3 \u03c4 \u03c3' \u03c4' t t':\n      rename_ty \u0394 \u03c3 \u03c3' ->\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename \u0393 \u0394 t t' ->\n      rename \u0393 \u0394 (IWrap \u03c3 \u03c4 t) (IWrap \u03c3' \u03c4' t')\n\n  | rn_Unwrap : forall t t',\n      rename \u0393 \u0394 t t' ->\n      rename \u0393 \u0394 (Unwrap t) (Unwrap t')\n\nwith rename_binding (\u0393 \u0394 : ctx) : ctx -> ctx -> Binding -> Binding -> Type :=\n\n  | rn_TermBind : forall s x x' \u03c4 \u03c4' t t',\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename \u0393 \u0394 t t' ->\n      rename_binding \u0393 \u0394 [(x, x')] [] (TermBind s (VarDecl x \u03c4) t) (TermBind s (VarDecl x' \u03c4') t')\n\n  | rn_TypeBind : forall \u03b1 \u03b1' k \u03c4 \u03c4',\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename_binding \u0393 \u0394 [] [(\u03b1, \u03b1')] (TypeBind (TyVarDecl \u03b1 k) \u03c4) (TypeBind (TyVarDecl \u03b1' k) \u03c4')\n\n  | rn_DatatypeBind : forall \u03b1 \u03b1' k tvs tvs' elim elim' cs cs',\n      forall \u0394_tvs \u0393_cs \u0393_b \u0394_b,\n\n      (* Renamings of bound ty-vars, which may be used in constructor types *)\n      rename_tvs \u0394 cs' tvs tvs' \u0394_tvs ->\n      (* Constructor types are renamed and return any renamed constructor names *)\n      rename_constrs ((\u03b1, \u03b1') :: \u0394_tvs ++ \u0394) \u0393 cs cs' \u0393_cs ->\n\n      (* Renamings for the rest of the program *)\n      \u0393_b = (elim, elim') :: \u0393_cs ->\n      \u0394_b = [(\u03b1, \u03b1')] ->\n\n\n      rename_binding \u0393 \u0394 \u0393_b \u0394_b\n        (DatatypeBind (Datatype (TyVarDecl \u03b1 k) tvs elim cs))\n        (DatatypeBind (Datatype (TyVarDecl \u03b1' k) tvs' elim' cs'))\n\n(*\n  rename_Bindings_Rec is also indexed over contexts \u0393_bs, \u0394_bs, which are respectively\n  the bound term and type variables of the recursive bindings.\n*)\nwith rename_Bindings_Rec (\u0393 \u0394 : ctx) : ctx -> ctx -> list Binding -> list Binding -> Type :=\n\n  | rn_Bindings_Rec_nil :\n      rename_Bindings_Rec \u0393 \u0394 [] [] [] []\n\n  | rn_Bindings_Rec_cons : forall b b' bs bs',\n      forall \u0393_b \u0393_bs \u0394_b \u0394_bs,\n      rename_binding \u0393 \u0394 \u0393_b \u0394_b b b' ->\n      rename_Bindings_Rec \u0393 \u0394 \u0393_bs \u0394_bs bs bs' ->\n      rename_Bindings_Rec \u0393 \u0394 (\u0393_b ++ \u0393_bs) (\u0394_b ++ \u0394_bs) (b :: bs) (b' :: bs')\n\n(*\n  rename_constrs is also indexed over context \u0393_cs, which are\n  the renamings of the constructors\n*)\nwith rename_constrs (\u0393 \u0394 : ctx) : list constructor -> list constructor -> ctx -> Type :=\n\n  | rn_constrs_nil :\n      rename_constrs \u0393 \u0394 [] [] []\n\n  | rn_constrs_cons : forall x x' \u03c4 \u03c4' n cs cs' \u0393_cs,\n      rename_ty \u0394 \u03c4 \u03c4' ->\n      rename_constrs \u0393 \u0394 cs cs' \u0393_cs ->\n      rename_constrs \u0393 \u0394\n        (Constructor (VarDecl x \u03c4) n :: cs)\n        (Constructor (VarDecl x' \u03c4') n :: cs')\n        ((x, x') :: \u0393_cs)\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/Rename.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.19715089168199268}}
{"text": "(*\n * \u00a9 2020 XXX.\n * \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     ModelCheck\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n     ModelCheck.SilentStepElimination\n.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require Import Sets.\n\nModule Foo <: EMPTY.\nEnd Foo.\nModule Import SN := SetNotations(Foo).\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nModule MyProtocol.\n\n  (* Start with two users, as that is the minimum for any interesting protocol *)\n  Notation USR1 := 0.\n  Notation USR2 := 1.\n\n  Section IW.\n    Import IdealWorld.\n\n    (* Set up initial communication channels so each user can talk directly to the other *)\n    Notation pCH12 := 0.\n    Notation pCH21 := 1.\n    Notation CH12  := (# pCH12).\n    Notation CH21  := (# pCH21).\n\n    (* This is the initial channel vector, each channel should be represented and start with \n     * no messages.\n     *)\n    Notation empty_chs := (#0 #+ (CH12, []) #+ (CH21, [])).\n\n    Notation PERMS1 := ($0 $+ (pCH12, owner) $+ (pCH21, reader)).\n    Notation PERMS2 := ($0 $+ (pCH12, reader) $+ (pCH21, owner)).\n\n    (* Fill in the users' protocol specifications here, adding additional users as needed.\n     * Note that all users must return an element of the same type, and that type needs to \n     * be one of: ...\n     *)\n    Notation ideal_users :=\n      [\n        (* User 1 Specification *)\n        mkiUsr USR1 PERMS1\n                (\n                  ret 1\n                )\n        ;\n\n      (* User 2 Specification *)\n      mkiUsr USR2 PERMS2\n              (\n                ret 1\n              )\n      ].\n\n    (* This is where the entire specification universe gets assembled.  It is unlikely anything\n     * will need to change here.\n     *)\n    Definition ideal_univ_start :=\n      mkiU empty_chs ideal_users.\n\n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    (* Key management needs to be bootstrapped.  Since all honest users must only send signed\n     * messages, we need some way of initially distributing signing keys in order to be able\n     * to begin secure communication.  This is analagous in the real world where we need to \n     * have some sort of trust relationship in order to distribute trusted keys.\n     * \n     * Here, each user has a public asymmetric signing key.\n     *)\n    Notation KID1 := 0.\n    Notation KID2 := 1.\n\n    Notation KEYS := [ skey KID1 ; skey KID2 ].\n\n    Notation KEYS1 := ($0 $+ (KID1, true) $+ (KID2, false)).\n    Notation KEYS2 := ($0 $+ (KID1, false) $+ (KID2, true)).\n\n    Notation real_users :=\n      [\n        (* User 1 implementation *)\n        MkRUserSpec USR1 KEYS1\n                    (\n                      ret 1\n                    )\n        ; \n\n      (* User 2 implementation *)\n      MkRUserSpec USR2 KEYS2\n                  (\n                    ret 1\n                  ) \n      ].\n\n    (* Here is where we put the implementation universe together.  Like above, it is \n     * unlikely anything will need to change here.\n     *)\n    Definition real_univ_start :=\n      mkrU (mkKeys KEYS) real_users.\n  End RW.\n\n  (* These are here to help the proof automation.  Don't change. *)\n  #[export] Hint Unfold\n       real_univ_start\n       ideal_univ_start\n    : user_build.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with user_build; simpl).\n  \nEnd MyProtocol.\n\nModule MyProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import MyProtocol.\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 SetLemmas.\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 safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (fun st => safety st /\\ alignment st /\\ returns_align st).\n  Proof.\n    eapply invariant_weaken.\n\n    - eapply multiStepClosure_ok; simpl.\n      autounfold in *.\n      (* Calls to gen1 will need to be addded here until the model checking terminates. *)\n      gen1.\n      gen1.\n      \n    (* The remaining parts of the proof script shouldn't need to change. *)\n    - intros.\n      unfold iu0, ideal_univ_start, mkiU in *\n      ; simpl in *.\n\n\n      sets_invert; split_ex\n      ; simpl in *; autounfold with core\n      ; subst; simpl\n      ; unfold safety, alignment, returns_align\n      ; ( repeat simple apply conj\n          ; [ solve_honest_actions_safe; clean_map_lookups; eauto 8\n            | trivial\n            | unfold labels_align; intros; rstep; subst; solve_labels_align\n            | try solve [ intros; find_step_or_solve ] \n        ]).\n\n      Unshelve.\n      all: exact 0 || auto.\n\n  Qed.\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    - solve_perm_merges; eauto.\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_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\n\nEnd MyProtocolSecure.\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/protocols/ProtocolTemplate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19704265996780912}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.AppendEntriesRequestLeaderLogsInterface.\nRequire Import VerdiRaft.OneLeaderLogPerTermInterface.\nRequire Import VerdiRaft.LeaderLogsSortedInterface.\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\nRequire Import VerdiRaft.AppendEntriesRequestsCameFromLeadersInterface.\nRequire Import VerdiRaft.AllEntriesLogInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsStrongInterface.\n\nRequire Import VerdiRaft.AllEntriesLeaderLogsInterface.\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  Context {rri : raft_refinement_interface}.\n  Context {aerlli : append_entries_leaderLogs_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n  Context {llsi : leaderLogs_sorted_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {aercfli : append_entries_came_from_leaders_interface}.\n  Context {aeli : allEntries_log_interface}.\n  Context {lsi : leader_sublog_interface}.\n  Context {lhsi : leaders_have_leaderLogs_strong_interface}.\n\n  Lemma leader_without_missing_entry_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leader_without_missing_entry net.\n  Proof using aeli. \n    intros. unfold leader_without_missing_entry.\n    find_apply_lem_hyp allEntries_log_invariant.\n    unfold allEntries_log in *.\n    intros. copy_eapply_prop_hyp allEntries allEntries.\n    intuition. right. break_exists; intuition; repeat eexists; eauto.\n  Qed.\n\n  Lemma appendEntriesRequest_exists_leaderLog_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      appendEntriesRequest_exists_leaderLog net.\n  Proof using aercfli. \n    intros. unfold appendEntriesRequest_exists_leaderLog.\n    apply append_entries_came_from_leaders_invariant; auto.\n  Qed.\n\n  Lemma appendEntriesRequest_leaderLog_not_in_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      appendEntriesRequest_leaderLog_not_in net.\n  Proof using rlmli llsi ollpti aerlli. \n    unfold appendEntriesRequest_leaderLog_not_in.\n    intros.\n    find_copy_apply_lem_hyp append_entries_leaderLogs_invariant.\n    unfold append_entries_leaderLogs in *.\n    pose proof entries_sorted_nw_invariant net ltac:(auto) p _ _ _ _ _ _ ltac:(auto) ltac:(eauto).\n    match goal with\n    | [ H : In _ (nwPackets _), H' : forall _, _ |- _ ] =>\n      copy_eapply H' H\n    end; eauto.\n    break_exists. break_and.\n    pose proof one_leaderLog_per_term_invariant _ ltac:(eauto) (pSrc p) x _ _  _ ltac:(eauto) ltac:(eauto).\n    break_and. subst.\n    intro.\n    match goal with\n    | [ H : ~ In _ _ |- _ ] => apply H\n    end.\n    apply in_or_app. right.\n    find_copy_apply_lem_hyp leaderLogs_sorted_invariant; auto.\n    find_copy_eapply_lem_hyp maxIndex_is_max; eauto.\n    intuition.\n    - break_and. subst. lia.\n    - break_exists. intuition. subst.\n      unfold Prefix_sane in *. intuition.\n      + eapply prefix_contiguous; eauto.\n        pose proof entries_contiguous_nw_invariant _ ltac:(eauto) p _ _ _ _ _ _ ltac:(auto) ltac:(eauto).\n        eapply contiguous_app ; eauto.\n      + lia.\n    - subst. auto.\n  Qed.\n\n \n  Lemma leaderLogs_leader_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leaderLogs_leader net.\n  Proof using lhsi. \n    unfold leaderLogs_leader. intros.\n    find_apply_lem_hyp leaders_have_leaderLogs_strong_invariant; auto.\n    break_exists_exists. intuition.\n  Qed.\n\n  Instance aelli :  all_entries_leader_logs_interface.\n  Proof.\n    split.\n    intros.\n    red.\n    intuition.\n    - auto using leader_without_missing_entry_invariant.\n    - auto using appendEntriesRequest_exists_leaderLog_invariant.\n    - auto using appendEntriesRequest_leaderLog_not_in_invariant.\n    - auto using leaderLogs_leader_invariant.\n  Qed.\nEnd AllEntriesLeaderLogs.\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/AllEntriesLeaderLogsProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.1969659356847176}}
{"text": "Require Import SimMem SimMemLift.\nRequire Import Simulation.\nRequire Import AST.\nFrom Paco Require Import paco.\nRequire Import sflib.\nRequire Import Basics.\nRequire Import CoqlibC.\nRequire Import Values Integers.\nRequire Import Globalenvs.\nRequire Import Program.\nRequire Import MemoryC.\n\nRequire Import Skeleton SimSymb Ord.\nRequire Import ModSem.\nRequire Import Sound Preservation.\nImport ModSem.\nRequire Import ModSemProps.\nRequire Import Events.\nRequire Import SmallstepC.\nRequire Import SimModSem.\n\n\nSet Implicit Arguments.\n\n\nSection SIMMODSEM.\n\n  Variables ms_src ms_tgt: ModSem.t.\n  Context {SM: SimMem.class}.\n  Context {SS: SimSymb.class SM}.\n  Context {SMLIFT: SimMemLift.class SM}.\n  Variable sound_states: ms_src.(state) -> Prop.\n\n  Variable has_footprint: forall\n      (st_init_src: ms_src.(ModSem.state)) (st_init_tgt: ms_tgt.(ModSem.state)) (sm0: SimMem.t),\n      Prop.\n\n  Variable mle_excl: forall\n      (st_init_src: ms_src.(ModSem.state)) (st_init_tgt: ms_tgt.(ModSem.state)) (sm0: SimMem.t) (sm1: SimMem.t),\n      Prop.\n\n  Inductive fsim_step (fsim: idx -> state ms_src -> state ms_tgt -> SimMem.t -> Prop)\n            (i0: idx) (st_src0: ms_src.(state)) (st_tgt0: ms_tgt.(state)) (sm0: SimMem.t): Prop :=\n  | fsim_step_step\n      (SAFESRC: ~ ms_src.(ModSem.is_call) st_src0 /\\ ~ ms_src.(ModSem.is_return) st_src0)\n      (STEP: forall st_src1 tr\n          (STEPSRC: Step ms_src st_src0 tr st_src1),\n          exists i1 st_tgt1 sm1,\n            (<<PLUS: DPlus ms_tgt st_tgt0 tr st_tgt1>> \\/ <<STAR: DStar ms_tgt st_tgt0 tr st_tgt1 /\\ ord i1 i0>>)\n            /\\ <<MLE: SimMem.le sm0 sm1>>\n(* Note: We require le for mle_preserves_sim_ge, but we cannot require SimMem.wf, beacuse of DCEproof *)\n            /\\ <<FSIM: fsim i1 st_src1 st_tgt1 sm1>>)\n      (RECEP: receptive_at ms_src st_src0)\n  | fsim_step_stutter\n      i1 st_tgt1 sm1\n      (PLUS: DPlus ms_tgt st_tgt0 nil st_tgt1 /\\ ord i1 i0)\n      (MLE: SimMem.le sm0 sm1)\n      (BSIM: fsim i1 st_src0 st_tgt1 sm1).\n\n  Inductive bsim_step (bsim: idx -> state ms_src -> state ms_tgt -> SimMem.t -> Prop)\n            (i0: idx) (st_src0: ms_src.(state)) (st_tgt0: ms_tgt.(state)) (sm0: SimMem.t): Prop :=\n  | bsim_step_step\n      (STEP: forall st_tgt1 tr\n          (STEPTGT: Step ms_tgt st_tgt0 tr st_tgt1),\n          exists i1 st_src1 sm1,\n            (<<PLUS: Plus ms_src st_src0 tr st_src1>> \\/ <<STAR: Star ms_src st_src0 tr st_src1 /\\ ord i1 i0>>)\n            /\\ <<MLE: SimMem.le sm0 sm1>>\n            /\\ <<BSIM: bsim i1 st_src1 st_tgt1 sm1>>)\n      (PROGRESS: <<STEPTGT: exists tr st_tgt1, Step ms_tgt st_tgt0 tr st_tgt1>>)\n  | bsim_step_stutter\n      i1 st_src1 sm1\n      (STAR: Star ms_src st_src0 nil st_src1 /\\ ord i1 i0)\n      (MLE: SimMem.le sm0 sm1)\n      (BSIM: bsim i1 st_src1 st_tgt0 sm1).\n\n  Inductive _lxsim_pre (lxsim: idx -> state ms_src -> state ms_tgt -> SimMem.t -> Prop)\n            (i0: idx) (st_src0: ms_src.(state)) (st_tgt0: ms_tgt.(state)) (sm0: SimMem.t): Prop :=\n  | lxsim_step_forward\n      (SU: forall (SU: DUMMY_PROP),\n      <<FSTEP: fsim_step lxsim i0 st_src0 st_tgt0 sm0>>\n      (* Note: We used coercion on determinate_at. See final_state, which is bot2. *)\n      (* sd_determ_at_final becomes nothing, but it is OK. *)\n      (* In composed semantics, when it stepped, it must not be final *))\n\n  | lxsim_step_backward\n      (SU: forall (SU: DUMMY_PROP),\n      (<<BSTEP:\n         forall (SAFESRC: safe_modsem ms_src st_src0) ,\n         (<<BSTEP: bsim_step lxsim i0 st_src0 st_tgt0 sm0>>)>>))\n\n  | lxsim_at_external\n      (* (MCOMPAT: mem_compat st_src0 st_tgt0 sm0) *)\n      (MWF: SimMem.wf sm0)\n      (* (CALLPROGRESS: forall *)\n      (*     rs_arg_src m_arg_src *)\n      (*     (ATSRC: ms_src.(at_external) st_src0 rs_arg_src m_arg_src) *)\n      (*   , *)\n      (*     exists rs_arg_tgt m_arg_tgt, <<ATTGT: ms_tgt.(at_external) st_tgt0 rs_arg_tgt m_arg_tgt>>) *)\n      (* (SAFESRC: exists rs_arg_src m_arg_src, <<ATSRC: ms_src.(at_external) st_src0 rs_arg_src m_arg_src>>) *)\n      (* (SAFESRC: ms_tgt.(is_call) st_tgt0) *)\n      (SAFESRC: ms_src.(is_call) st_src0)\n      (* (PROGSRC: ms_src.(is_call) st_src0) *)\n      (SU: forall (SU: DUMMY_PROP),\n      <<CALLFSIM: forall args_src\n          (ATSRC: ms_src.(at_external) st_src0 args_src),\n          exists args_tgt sm_arg,\n            (<<SIMARGS: SimMem.sim_args args_src args_tgt sm_arg>>\n            /\\ (<<MWF: SimMem.wf sm_arg>>)\n            /\\ (<<MLE: SimMem.le sm0 sm_arg>>)\n            /\\ (<<FOOT: has_footprint st_src0 st_tgt0 sm0>>)\n            /\\ (<<ATTGT: ms_tgt.(at_external) st_tgt0 args_tgt>>)\n            /\\ (<<K: forall sm_ret retv_src retv_tgt st_src1\n                (MLE: SimMem.le (SimMemLift.lift sm_arg) sm_ret)\n                (MWF: SimMem.wf sm_ret)\n                (SIMRETV: SimMem.sim_retv retv_src retv_tgt sm_ret)\n                (AFTERSRC: ms_src.(after_external) st_src0 retv_src st_src1),\n                exists st_tgt1 sm_after i1,\n                  (<<AFTERTGT: ms_tgt.(after_external) st_tgt0 retv_tgt st_tgt1>>) /\\\n                  (* (<<MLE: SimMem.le sm0 sm_after>>) /\\ *)\n                  (<<MLE: mle_excl st_src0 st_tgt0 (SimMemLift.unlift sm_arg sm_ret) sm_after>>) /\\\n                  (<<LXSIM: lxsim i1 st_src1 st_tgt1 sm_after>>)>>))>>)\n\n  | lxsim_final\n      sm_ret retv_src retv_tgt\n      (MLE: SimMem.le sm0 sm_ret)\n      (MWF: SimMem.wf sm_ret)\n      (* (PROGRESS: ms_tgt.(is_return) rs_init_tgt st_tgt0) *)\n      (* (RETBSIM: forall           *)\n      (*     rs_ret_tgt m_ret_tgt *)\n      (*     (FINALTGT: ms_tgt.(final_frame) rs_init_tgt st_tgt0 rs_ret_tgt m_ret_tgt) *)\n      (*   , *)\n      (*     exists rs_ret_src m_ret_src, *)\n      (*       (<<RSREL: sm0.(SimMem.sim_regset) rs_ret_src rs_ret_tgt>>) *)\n      (*       /\\ (<<FINALSRC: ms_src.(final_frame) rs_init_src st_src0 rs_ret_src m_ret_src>>)) *)\n      (FINALSRC: ms_src.(final_frame) st_src0 retv_src)\n      (FINALTGT: ms_tgt.(final_frame) st_tgt0 retv_tgt)\n      (SIMRETV: SimMem.sim_retv retv_src retv_tgt sm_ret).\n\n      (* Note: Actually, final_frame can be defined as a function. *)\n\n      (* (FINALSRC: ms_src.(final_frame) rs_init_src st_src0 rs_ret_src m_ret_src) *)\n      (* (FINALTGT: ms_tgt.(final_frame) rs_init_tgt st_tgt0 rs_ret_tgt m_ret_tgt) *)\n\n\n  Definition _lxsim (lxsim: idx -> state ms_src -> state ms_tgt -> SimMem.t -> Prop)\n             (i0: idx) (st_src0: ms_src.(state)) (st_tgt0: ms_tgt.(state)) (sm0: SimMem.t): Prop :=\n    (forall (SUSTAR: forall st_src1 tr (STAR: Star ms_src st_src0 tr st_src1), sound_states st_src1),\n        <<LXSIM: _lxsim_pre lxsim i0 st_src0 st_tgt0 sm0>>).\n\n  Definition lxsimL: _ -> _ -> _ -> _ -> Prop := paco4 _lxsim bot4.\n\n  Lemma lxsim_mon: monotone4 _lxsim.\n  Proof.\n    repeat intro. rr in IN. hexploit1 IN; eauto. inv IN; eauto.\n    - econs 1; ss. ii. spc SU. des. esplits; eauto. inv SU.\n      + econs 1; eauto. i; des_safe. exploit STEP; eauto. i; des_safe. esplits; eauto.\n      + econs 2; eauto.\n    - econs 2; ss. ii. exploit SU; eauto. i; des. inv H.\n      + econs 1; eauto. i; des_safe. exploit STEP; eauto. i; des_safe. esplits; eauto.\n      + econs 2; eauto.\n    - econs 3; eauto. ii; ss. exploit SU; eauto. i; des.\n      esplits; eauto. ii. exploit K; eauto. i; des. esplits; eauto.\n    - econs 4; eauto.\n  Qed.\n\nEnd SIMMODSEM.\n\nHint Unfold lxsimL.\nHint Resolve lxsim_mon: paco.\n\n\nModule ModSemPair.\nInclude SimModSem.ModSemPair.\nSection MODSEMPAIR.\nContext {SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\nContext {SMLIFT: SimMemLift.class SM}.\n\n  Inductive simL (msp: ModSemPair.t): Prop :=\n  | simL_intro\n      (* (SIMSKENV: sim_skenv msp msp.(sm)) *)\n      sidx sound_states sound_state_ex\n      (PRSV: local_preservation msp.(ModSemPair.src) sound_state_ex)\n      (PRSVNOGR: forall (si: sidx), local_preservation_noguarantee msp.(ModSemPair.src) (sound_states si))\n\n      (has_footprint: msp.(ModSemPair.src).(ModSem.state) -> msp.(ModSemPair.tgt).(ModSem.state) -> SimMem.t -> Prop)\n      (mle_excl: msp.(ModSemPair.src).(ModSem.state) -> msp.(ModSemPair.tgt).(ModSem.state) -> SimMem.t -> SimMem.t -> Prop)\n      (FOOTEXCL: forall st_at_src st_at_tgt sm0 sm1 sm2\n          (MWF: SimMem.wf sm0)\n          (FOOT: has_footprint st_at_src st_at_tgt sm0)\n          (MLEEXCL: (mle_excl st_at_src st_at_tgt) sm1 sm2)\n          (MLE: SimMem.le sm0 sm1),\n          <<MLE: SimMem.le sm0 sm2>>)\n      (EXCLPRIV: forall st_init_src st_init_tgt sm0 sm1 (MWF: SimMem.wf sm0),\n          mle_excl st_init_src st_init_tgt sm0 sm1 -> SimMem.lepriv sm0 sm1)\n      (SIM: forall\n          sm_arg args_src args_tgt\n          sg_init_src sg_init_tgt\n          (FINDFSRC: (Genv.find_funct msp.(ModSemPair.src).(ModSem.skenv)) (Args.get_fptr args_src) =\n                     Some (Internal sg_init_src))\n          (FINDFTGT: (Genv.find_funct msp.(ModSemPair.tgt).(ModSem.skenv)) (Args.get_fptr args_tgt) =\n                     Some (Internal sg_init_tgt))\n          (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg)\n          (SIMSKENV: ModSemPair.sim_skenv msp sm_arg)\n          (MFUTURE: SimMem.future msp.(ModSemPair.sm) sm_arg)\n          (MWF: SimMem.wf sm_arg),\n          (<<INITBSIM: forall st_init_tgt\n              (INITTGT: msp.(ModSemPair.tgt).(initial_frame) args_tgt st_init_tgt)\n              (SAFESRC: exists _st_init_src, msp.(ModSemPair.src).(initial_frame) args_src _st_init_src),\n              exists st_init_src sm_init idx_init,\n                (<<MLE: SimMem.le sm_arg sm_init>>) /\\\n                (<<INITSRC: msp.(ModSemPair.src).(initial_frame) args_src st_init_src>>) /\\\n                (<<SIM: lxsimL msp.(ModSemPair.src) msp.(ModSemPair.tgt)\n                          (fun st => forall si, exists su m_init, sound_states si su m_init st)\n                          has_footprint mle_excl idx_init st_init_src st_init_tgt sm_init>>)>>) /\\\n          (<<INITPROGRESS: forall\n              (SAFESRC: exists st_init_src, msp.(ModSemPair.src).(initial_frame) args_src st_init_src),\n              exists st_init_tgt, (<<INITTGT: msp.(ModSemPair.tgt).(initial_frame) args_tgt st_init_tgt>>)>>)).\n\nEnd MODSEMPAIR.\nEnd ModSemPair.\n\nHint Constructors ModSemPair.sim_skenv.\n\n\n\n\n\nSection IMPLIES.\n\n  Context {SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n  Context {SMLIFT: SimMemLift.class SM}.\n\n  Lemma lxsim_lxsim\n        ms_src ms_tgt sound_state idx_init st_init_src st_init_tgt sm_init\n        (has_footprint: ms_src.(ModSem.state) -> ms_tgt.(ModSem.state) -> SimMem.t -> Prop)\n        (mle_excl: ms_src.(ModSem.state) -> ms_tgt.(ModSem.state) -> SimMem.t -> SimMem.t -> Prop)\n        (FOOTEXCL: forall st_at_src st_at_tgt sm0 sm1 sm2\n            (MWF: SimMem.wf sm0)\n            (FOOT: has_footprint st_at_src st_at_tgt sm0)\n            (MLEEXCL: (mle_excl st_at_src st_at_tgt) sm1 sm2)\n            (MLE: SimMem.le sm0 sm1),\n            <<MLE: SimMem.le sm0 sm2>>)\n        (EXCLPRIV: forall st_init_src st_init_tgt sm0 sm1 (MWF: SimMem.wf sm0),\n            mle_excl st_init_src st_init_tgt sm0 sm1 -> SimMem.lepriv sm0 sm1)\n        (SIM: lxsimL ms_src ms_tgt sound_state has_footprint mle_excl idx_init st_init_src st_init_tgt sm_init):\n      <<SIM: SimModSem.lxsim ms_src ms_tgt sound_state idx_init st_init_src st_init_tgt sm_init>>.\n  Proof.\n    move has_footprint at top. move mle_excl at top. move FOOTEXCL at top.\n    revert_until sound_state. pcofix CIH. i. pfold.\n    punfold SIM. rr in SIM. ii. exploit SIM; eauto. intro T. inv T.\n    - econs 1; eauto. i. hexploit1 SU0; ss. inv SU0.\n      + econs 1; eauto. i. exploit STEP; eauto. i; des_safe. esplits; et. right. pclearbot. eapply CIH; et.\n      + pclearbot. econs 2; eauto.\n    - econs 2; eauto. i. hexploit1 SU0; ss. des. esplits; eauto. i. hexploit SU0; ss. intro T. inv T.\n      + econs 1; eauto. i. exploit STEP; eauto. i; des_safe. esplits; et. right. pclearbot. eapply CIH; et.\n      + pclearbot. econs 2; eauto.\n    - econs 3; et.\n      ii. exploit SU0; et. i; des.\n      eexists. exists (SimMemLift.lift sm_arg).\n      esplits; eauto.\n      { eapply SimMemLift.lift_args; et. }\n      { eapply SimMemLift.lift_wf; et. }\n      { eapply SimMemLift.le_lift_lepriv; et. }\n      i; des.\n      exploit K; eauto. i; des. pclearbot.\n      eexists _, sm_after.\n      esplits; eauto.\n      { eapply FOOTEXCL; et. etrans; et. eapply SimMemLift.lift_spec; et. }\n      { etrans.\n        - eapply SimMemLift.unlift_priv with (sm_at := sm_arg); eauto.\n          eapply SimMemLift.lift_priv; eauto.\n        - eapply EXCLPRIV; eauto. eapply SimMemLift.unlift_wf; eauto.\n      }\n    - econs 4; et.\n  Qed.\n\n  Theorem sim_mod_sem_implies\n          msp\n          (SIMMS: ModSemPair.simL msp):\n      <<SIMMS: SimModSem.ModSemPair.sim msp>>.\n  Proof.\n    inv SIMMS. econs; eauto.\n    i. exploit SIM; eauto. i; des. esplits; eauto.\n    i. exploit INITBSIM; eauto. i; des.\n    esplits; eauto. eapply lxsim_lxsim; et.\n  Qed.\n\nEnd IMPLIES.\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/SimModSemLift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.19690456602945403}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Specific.X86.Core.\nRequire Import Crypto.BoundedArithmetic.Interface.\n\nLocal Coercion Z.of_nat : nat >-> Z.\n\nSection x86.\n  Local Notation n := 64%nat.\n  Context (ops : x86.instructions n).\n  Definition barrett_reduce64'1 :=\n    fun x : (x86.W * x86.W * (x86.W * x86.W) * (x86.W * x86.W * (x86.W * x86.W)))%type =>\n      let y :=\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 6346243789798364141,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 1503914060200516822,\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 1152921504606846976)) in\nlet y0 :=\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 11508512988225646668,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 12431087832907484326,\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 18446744073709551615,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 4611686018427387903)) in\nlet y1 :=\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n  @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0)) in\nlet y2 :=\n  let y2 :=\n    let (_, y2) :=\n      let (xs, x0) := let (x0, _) := x in x0 in\n      let (ys, y2) :=\n        let (x1, _) :=\n          let y2 :=\n            let (_, y2) :=\n              let y2 :=\n                let y2 := x in\n                let (high1, high2) := let (_, y3) := y2 in y3 in\n                let (_, low2) := let (x1, _) := y2 in x1 in\n                (let (high3, high4) := high1 in\n                 let (_, low4) := low2 in\n                 (let (_, y3) :=\n                    @shrdf (@x86.W (Z.of_nat 64) ops) (@x86.shrdf (Z.of_nat 64) ops) high3 low4\n                      58 in\n                  y3,\n                 let (_, y3) :=\n                   @shrdf (@x86.W (Z.of_nat 64) ops) (@x86.shrdf (Z.of_nat 64) ops) high4 high3\n                     58 in\n                 y3),\n                let (high3, high4) := high2 in\n                let (_, low4) := high1 in\n                (let (_, y3) :=\n                   @shrdf (@x86.W (Z.of_nat 64) ops) (@x86.shrdf (Z.of_nat 64) ops) high3 low4 58 in\n                 y3,\n                let (_, y3) :=\n                  @shrdf (@x86.W (Z.of_nat 64) ops) (@x86.shrdf (Z.of_nat 64) ops) high4 high3 58 in\n                y3)) in\n              let y3 := y0 in\n              let y4 :=\n                (let y4 := let (x1, _) := y2 in x1 in\n                 let y5 := let (x1, _) := y3 in x1 in\n                 let y6 :=\n                   (let (_, y6) :=\n                      @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                        (let (x1, _) := y4 in x1) (let (x1, _) := y5 in x1) in\n                    y6,\n                   let (_, y6) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (_, y6) := y4 in y6) (let (_, y6) := y5 in y6) in\n                   y6) in\n                 let y7 :=\n                   let (_, y7) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (_, y7) := y4 in y7) (let (x1, _) := y5 in x1) in\n                   y7 in\n                 let (_, out) :=\n                   let (xs0, x1) := y6 in\n                   let (carry, zs) :=\n                     let (xs1, x2) := xs0 in\n                     let (ys, y8) :=\n                       let (r1, _) := y7 in\n                       (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                       let (_, y8) :=\n                         @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                       y8) in\n                     let (carry, zs) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                     let (carry0, z) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry in\n                     (carry0, (zs, z)) in\n                   let (carry0, z) :=\n                     let (xs1, x2) := x1 in\n                     let (ys, y8) :=\n                       let (_, r2) := y7 in\n                       (let (_, y8) :=\n                          @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                        y8, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                     let (carry0, zs0) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                     let (carry1, z) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry0 in\n                     (carry1, (zs0, z)) in\n                   (carry0, (zs, z)) in\n                 let y8 :=\n                   let (_, y8) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (_, y8) := y5 in y8) (let (x1, _) := y4 in x1) in\n                   y8 in\n                 let (_, out0) :=\n                   let (xs0, x1) := out in\n                   let (carry, zs) :=\n                     let (xs1, x2) := xs0 in\n                     let (ys, y9) :=\n                       let (r1, _) := y8 in\n                       (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                       let (_, y9) :=\n                         @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                       y9) in\n                     let (carry, zs) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                     let (carry0, z) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                     (carry0, (zs, z)) in\n                   let (carry0, z) :=\n                     let (xs1, x2) := x1 in\n                     let (ys, y9) :=\n                       let (_, r2) := y8 in\n                       (let (_, y9) :=\n                          @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                        y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                     let (carry0, zs0) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                     let (carry1, z) :=\n                       @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                     (carry1, (zs0, z)) in\n                   (carry0, (zs, z)) in\n                 out0,\n                let y4 := let (_, y4) := y2 in y4 in\n                let y5 := let (_, y5) := y3 in y5 in\n                let y6 :=\n                  (let (_, y6) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (x1, _) := y4 in x1) (let (x1, _) := y5 in x1) in\n                   y6,\n                  let (_, y6) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y6) := y4 in y6) (let (_, y6) := y5 in y6) in\n                  y6) in\n                let y7 :=\n                  let (_, y7) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y7) := y4 in y7) (let (x1, _) := y5 in x1) in\n                  y7 in\n                let (_, out) :=\n                  let (xs0, x1) := y6 in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y8) :=\n                      let (r1, _) := y7 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y8) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y8) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y8) :=\n                      let (_, r2) := y7 in\n                      (let (_, y8) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y8, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                let y8 :=\n                  let (_, y8) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y8) := y5 in y8) (let (x1, _) := y4 in x1) in\n                  y8 in\n                let (_, out0) :=\n                  let (xs0, x1) := out in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y9) :=\n                      let (r1, _) := y8 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y9) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y9) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y9) :=\n                      let (_, r2) := y8 in\n                      (let (_, y9) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                out0) in\n              let y5 :=\n                let y5 := let (_, y5) := y2 in y5 in\n                let y6 := let (x1, _) := y3 in x1 in\n                let y7 :=\n                  (let (_, y7) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (x1, _) := y5 in x1) (let (x1, _) := y6 in x1) in\n                   y7,\n                  let (_, y7) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y7) := y5 in y7) (let (_, y7) := y6 in y7) in\n                  y7) in\n                let y8 :=\n                  let (_, y8) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y8) := y5 in y8) (let (x1, _) := y6 in x1) in\n                  y8 in\n                let (_, out) :=\n                  let (xs0, x1) := y7 in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y9) :=\n                      let (r1, _) := y8 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y9) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y9) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y9) :=\n                      let (_, r2) := y8 in\n                      (let (_, y9) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                let y9 :=\n                  let (_, y9) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y9) := y6 in y9) (let (x1, _) := y5 in x1) in\n                  y9 in\n                let (_, out0) :=\n                  let (xs0, x1) := out in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y10) :=\n                      let (r1, _) := y9 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y10) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y10) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y10) :=\n                      let (_, r2) := y9 in\n                      (let (_, y10) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y10, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                out0 in\n              let (_, out) :=\n                let (xs0, x1) := y4 in\n                let (carry, zs) :=\n                  let (xs1, x2) := xs0 in\n                  let (ys, y6) :=\n                    let (r1, _) := y5 in\n                    (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    let (r3, r4) := r1 in (r3, r4)) in\n                  let (carry, zs) :=\n                    let (xs2, x3) := xs1 in\n                    let (ys0, y7) := ys in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs2, x3) := x2 in\n                    let (ys0, y7) := y6 in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                let (carry0, z) :=\n                  let (xs1, x2) := x1 in\n                  let (ys, y6) :=\n                    let (_, r2) := y5 in\n                    (let (r3, r4) := r2 in (r3, r4),\n                    (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0)) in\n                  let (carry0, zs0) :=\n                    let (xs2, x3) := xs1 in\n                    let (ys0, y7) := ys in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry0 in\n                    (carry1, (zs0, z)) in\n                  let (carry1, z) :=\n                    let (xs2, x3) := x2 in\n                    let (ys0, y7) := y6 in\n                    let (carry1, zs1) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry0 in\n                    let (carry2, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry1 in\n                    (carry2, (zs1, z)) in\n                  (carry1, (zs0, z)) in\n                (carry0, (zs, z)) in\n              let y6 :=\n                let y6 := let (_, y6) := y3 in y6 in\n                let y7 := let (x1, _) := y2 in x1 in\n                let y8 :=\n                  (let (_, y8) :=\n                     @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                       (let (x1, _) := y6 in x1) (let (x1, _) := y7 in x1) in\n                   y8,\n                  let (_, y8) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y8) := y6 in y8) (let (_, y8) := y7 in y8) in\n                  y8) in\n                let y9 :=\n                  let (_, y9) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y9) := y6 in y9) (let (x1, _) := y7 in x1) in\n                  y9 in\n                let (_, out0) :=\n                  let (xs0, x1) := y8 in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y10) :=\n                      let (r1, _) := y9 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y10) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y10) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y10) :=\n                      let (_, r2) := y9 in\n                      (let (_, y10) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y10, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                let y10 :=\n                  let (_, y10) :=\n                    @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                      (let (_, y10) := y7 in y10) (let (x1, _) := y6 in x1) in\n                  y10 in\n                let (_, out1) :=\n                  let (xs0, x1) := out0 in\n                  let (carry, zs) :=\n                    let (xs1, x2) := xs0 in\n                    let (ys, y11) :=\n                      let (r1, _) := y10 in\n                      (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                      let (_, y11) :=\n                        @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                      y11) in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y11 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs1, x2) := x1 in\n                    let (ys, y11) :=\n                      let (_, r2) := y10 in\n                      (let (_, y11) :=\n                         @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                       y11, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y11 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                out1 in\n              let (_, out0) :=\n                let (xs0, x1) := out in\n                let (carry, zs) :=\n                  let (xs1, x2) := xs0 in\n                  let (ys, y7) :=\n                    let (r1, _) := y6 in\n                    (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    let (r3, r4) := r1 in (r3, r4)) in\n                  let (carry, zs) :=\n                    let (xs2, x3) := xs1 in\n                    let (ys0, y8) := ys in\n                    let (carry, zs) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 false in\n                    let (carry0, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry in\n                    (carry0, (zs, z)) in\n                  let (carry0, z) :=\n                    let (xs2, x3) := x2 in\n                    let (ys0, y8) := y7 in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry0 in\n                    (carry1, (zs0, z)) in\n                  (carry0, (zs, z)) in\n                let (carry0, z) :=\n                  let (xs1, x2) := x1 in\n                  let (ys, y7) :=\n                    let (_, r2) := y6 in\n                    (let (r3, r4) := r2 in (r3, r4),\n                    (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                    @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0)) in\n                  let (carry0, zs0) :=\n                    let (xs2, x3) := xs1 in\n                    let (ys0, y8) := ys in\n                    let (carry0, zs0) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                    let (carry1, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry0 in\n                    (carry1, (zs0, z)) in\n                  let (carry1, z) :=\n                    let (xs2, x3) := x2 in\n                    let (ys0, y8) := y7 in\n                    let (carry1, zs1) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry0 in\n                    let (carry2, z) :=\n                      @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry1 in\n                    (carry2, (zs1, z)) in\n                  (carry1, (zs0, z)) in\n                (carry0, (zs, z)) in\n              out0 in\n            y2 in\n          let y3 := y in\n          let y4 :=\n            (let y4 := let (x1, _) := y2 in x1 in\n             let y5 := let (x1, _) := y3 in x1 in\n             let y6 :=\n               (let (_, y6) :=\n                  @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                    (let (x1, _) := y4 in x1) (let (x1, _) := y5 in x1) in\n                y6,\n               let (_, y6) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (_, y6) := y4 in y6) (let (_, y6) := y5 in y6) in\n               y6) in\n             let y7 :=\n               let (_, y7) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (_, y7) := y4 in y7) (let (x1, _) := y5 in x1) in\n               y7 in\n             let (_, out) :=\n               let (xs0, x1) := y6 in\n               let (carry, zs) :=\n                 let (xs1, x2) := xs0 in\n                 let (ys, y8) :=\n                   let (r1, _) := y7 in\n                   (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                   let (_, y8) :=\n                     @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                   y8) in\n                 let (carry, zs) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                 let (carry0, z) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry in\n                 (carry0, (zs, z)) in\n               let (carry0, z) :=\n                 let (xs1, x2) := x1 in\n                 let (ys, y8) :=\n                   let (_, r2) := y7 in\n                   (let (_, y8) :=\n                      @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                    y8, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                 let (carry0, zs0) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                 let (carry1, z) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry0 in\n                 (carry1, (zs0, z)) in\n               (carry0, (zs, z)) in\n             let y8 :=\n               let (_, y8) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (_, y8) := y5 in y8) (let (x1, _) := y4 in x1) in\n               y8 in\n             let (_, out0) :=\n               let (xs0, x1) := out in\n               let (carry, zs) :=\n                 let (xs1, x2) := xs0 in\n                 let (ys, y9) :=\n                   let (r1, _) := y8 in\n                   (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                   let (_, y9) :=\n                     @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                   y9) in\n                 let (carry, zs) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                 let (carry0, z) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                 (carry0, (zs, z)) in\n               let (carry0, z) :=\n                 let (xs1, x2) := x1 in\n                 let (ys, y9) :=\n                   let (_, r2) := y8 in\n                   (let (_, y9) :=\n                      @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                    y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                 let (carry0, zs0) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                 let (carry1, z) :=\n                   @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                 (carry1, (zs0, z)) in\n               (carry0, (zs, z)) in\n             out0,\n            let y4 := let (_, y4) := y2 in y4 in\n            let y5 := let (_, y5) := y3 in y5 in\n            let y6 :=\n              (let (_, y6) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (x1, _) := y4 in x1) (let (x1, _) := y5 in x1) in\n               y6,\n              let (_, y6) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y6) := y4 in y6) (let (_, y6) := y5 in y6) in\n              y6) in\n            let y7 :=\n              let (_, y7) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y7) := y4 in y7) (let (x1, _) := y5 in x1) in\n              y7 in\n            let (_, out) :=\n              let (xs0, x1) := y6 in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y8) :=\n                  let (r1, _) := y7 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y8) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y8) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y8) :=\n                  let (_, r2) := y7 in\n                  (let (_, y8) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y8, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y8 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            let y8 :=\n              let (_, y8) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y8) := y5 in y8) (let (x1, _) := y4 in x1) in\n              y8 in\n            let (_, out0) :=\n              let (xs0, x1) := out in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y9) :=\n                  let (r1, _) := y8 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y9) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y9) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y9) :=\n                  let (_, r2) := y8 in\n                  (let (_, y9) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            out0) in\n          let y5 :=\n            let y5 := let (_, y5) := y2 in y5 in\n            let y6 := let (x1, _) := y3 in x1 in\n            let y7 :=\n              (let (_, y7) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (x1, _) := y5 in x1) (let (x1, _) := y6 in x1) in\n               y7,\n              let (_, y7) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y7) := y5 in y7) (let (_, y7) := y6 in y7) in\n              y7) in\n            let y8 :=\n              let (_, y8) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y8) := y5 in y8) (let (x1, _) := y6 in x1) in\n              y8 in\n            let (_, out) :=\n              let (xs0, x1) := y7 in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y9) :=\n                  let (r1, _) := y8 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y9) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y9) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y9) :=\n                  let (_, r2) := y8 in\n                  (let (_, y9) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y9, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y9 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            let y9 :=\n              let (_, y9) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y9) := y6 in y9) (let (x1, _) := y5 in x1) in\n              y9 in\n            let (_, out0) :=\n              let (xs0, x1) := out in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y10) :=\n                  let (r1, _) := y9 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y10) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y10) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y10) :=\n                  let (_, r2) := y9 in\n                  (let (_, y10) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y10, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            out0 in\n          let (_, out) :=\n            let (xs0, x1) := y4 in\n            let (carry, zs) :=\n              let (xs1, x2) := xs0 in\n              let (ys, y6) :=\n                let (r1, _) := y5 in\n                (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                let (r3, r4) := r1 in (r3, r4)) in\n              let (carry, zs) :=\n                let (xs2, x3) := xs1 in\n                let (ys0, y7) := ys in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs2, x3) := x2 in\n                let (ys0, y7) := y6 in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            let (carry0, z) :=\n              let (xs1, x2) := x1 in\n              let (ys, y6) :=\n                let (_, r2) := y5 in\n                (let (r3, r4) := r2 in (r3, r4),\n                (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0)) in\n              let (carry0, zs0) :=\n                let (xs2, x3) := xs1 in\n                let (ys0, y7) := ys in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry0 in\n                (carry1, (zs0, z)) in\n              let (carry1, z) :=\n                let (xs2, x3) := x2 in\n                let (ys0, y7) := y6 in\n                let (carry1, zs1) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry0 in\n                let (carry2, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y7 carry1 in\n                (carry2, (zs1, z)) in\n              (carry1, (zs0, z)) in\n            (carry0, (zs, z)) in\n          let y6 :=\n            let y6 := let (_, y6) := y3 in y6 in\n            let y7 := let (x1, _) := y2 in x1 in\n            let y8 :=\n              (let (_, y8) :=\n                 @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                   (let (x1, _) := y6 in x1) (let (x1, _) := y7 in x1) in\n               y8,\n              let (_, y8) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y8) := y6 in y8) (let (_, y8) := y7 in y8) in\n              y8) in\n            let y9 :=\n              let (_, y9) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y9) := y6 in y9) (let (x1, _) := y7 in x1) in\n              y9 in\n            let (_, out0) :=\n              let (xs0, x1) := y8 in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y10) :=\n                  let (r1, _) := y9 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y10) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y10) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y10) :=\n                  let (_, r2) := y9 in\n                  (let (_, y10) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y10, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y10 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            let y10 :=\n              let (_, y10) :=\n                @muldwf (@x86.W (Z.of_nat 64) ops) (@x86.muldwf (Z.of_nat 64) ops)\n                  (let (_, y10) := y7 in y10) (let (x1, _) := y6 in x1) in\n              y10 in\n            let (_, out1) :=\n              let (xs0, x1) := out0 in\n              let (carry, zs) :=\n                let (xs1, x2) := xs0 in\n                let (ys, y11) :=\n                  let (r1, _) := y10 in\n                  (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                  let (_, y11) :=\n                    @shlf (@x86.W (Z.of_nat 64) ops) (@x86.shlf (Z.of_nat 64) ops) r1 0 in\n                  y11) in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y11 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs1, x2) := x1 in\n                let (ys, y11) :=\n                  let (_, r2) := y10 in\n                  (let (_, y11) :=\n                     @shrf (@x86.W (Z.of_nat 64) ops) (@x86.shrf (Z.of_nat 64) ops) r2 0 in\n                   y11, @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0) in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs1 ys carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x2 y11 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            out1 in\n          let (_, out0) :=\n            let (xs0, x1) := out in\n            let (carry, zs) :=\n              let (xs1, x2) := xs0 in\n              let (ys, y7) :=\n                let (r1, _) := y6 in\n                (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                let (r3, r4) := r1 in (r3, r4)) in\n              let (carry, zs) :=\n                let (xs2, x3) := xs1 in\n                let (ys0, y8) := ys in\n                let (carry, zs) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 false in\n                let (carry0, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry in\n                (carry0, (zs, z)) in\n              let (carry0, z) :=\n                let (xs2, x3) := x2 in\n                let (ys0, y8) := y7 in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry0 in\n                (carry1, (zs0, z)) in\n              (carry0, (zs, z)) in\n            let (carry0, z) :=\n              let (xs1, x2) := x1 in\n              let (ys, y7) :=\n                let (_, r2) := y6 in\n                (let (r3, r4) := r2 in (r3, r4),\n                (@ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0,\n                @ldi (@x86.W (Z.of_nat 64) ops) (@x86.ldi (Z.of_nat 64) ops) 0)) in\n              let (carry0, zs0) :=\n                let (xs2, x3) := xs1 in\n                let (ys0, y8) := ys in\n                let (carry0, zs0) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry in\n                let (carry1, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry0 in\n                (carry1, (zs0, z)) in\n              let (carry1, z) :=\n                let (xs2, x3) := x2 in\n                let (ys0, y8) := y7 in\n                let (carry1, zs1) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) xs2 ys0 carry0 in\n                let (carry2, z) :=\n                  @adc (@x86.W (Z.of_nat 64) ops) (@x86.adc (Z.of_nat 64) ops) x3 y8 carry1 in\n                (carry2, (zs1, z)) in\n              (carry1, (zs0, z)) in\n            (carry0, (zs, z)) in\n          out0 in\n        x1 in\n      let (carry, zs) :=\n        let (xs0, x1) := xs in\n        let (ys0, y3) := ys in\n        let (carry, zs) :=\n          @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 false in\n        let (carry0, z) :=\n          @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y3 carry in\n        (carry0, (zs, z)) in\n      let (carry0, z) :=\n        let (xs0, x1) := x0 in\n        let (ys0, y3) := y2 in\n        let (carry0, zs0) :=\n          @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 carry in\n        let (carry1, z) :=\n          @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y3 carry0 in\n        (carry1, (zs0, z)) in\n      (carry0, (zs, z)) in\n    y2 in\n  let (CF, _) :=\n    let (xs, x0) := y2 in\n    let (ys, y3) := y in\n    let (carry, zs) :=\n      let (xs0, x1) := xs in\n      let (ys0, y4) := ys in\n      let (carry, zs) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 false in\n      let (carry0, z) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry in\n      (carry0, (zs, z)) in\n    let (carry0, z) :=\n      let (xs0, x1) := x0 in\n      let (ys0, y4) := y3 in\n      let (carry0, zs0) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 carry in\n      let (carry1, z) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry0 in\n      (carry1, (zs0, z)) in\n    (carry0, (zs, z)) in\n  let (_, y3) :=\n    let (xs, x0) := y2 in\n    let (ys, y3) :=\n      let (x1, x2) := y1 in\n      let (y3, y4) := y in\n      (let (x3, x4) := x1 in\n       let (y5, y6) := y3 in\n       (@selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x3 y5,\n       @selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x4 y6),\n      let (x3, x4) := x2 in\n      let (y5, y6) := y4 in\n      (@selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x3 y5,\n      @selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x4 y6)) in\n    let (carry, zs) :=\n      let (xs0, x1) := xs in\n      let (ys0, y4) := ys in\n      let (carry, zs) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 false in\n      let (carry0, z) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry in\n      (carry0, (zs, z)) in\n    let (carry0, z) :=\n      let (xs0, x1) := x0 in\n      let (ys0, y4) := y3 in\n      let (carry0, zs0) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 carry in\n      let (carry1, z) :=\n        @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry0 in\n      (carry1, (zs0, z)) in\n    (carry0, (zs, z)) in\n  y3 in\nlet (CF, _) :=\n  let (xs, x0) := y2 in\n  let (ys, y3) := y in\n  let (carry, zs) :=\n    let (xs0, x1) := xs in\n    let (ys0, y4) := ys in\n    let (carry, zs) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 false in\n    let (carry0, z) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry in\n    (carry0, (zs, z)) in\n  let (carry0, z) :=\n    let (xs0, x1) := x0 in\n    let (ys0, y4) := y3 in\n    let (carry0, zs0) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 carry in\n    let (carry1, z) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry0 in\n    (carry1, (zs0, z)) in\n  (carry0, (zs, z)) in\nlet (_, y3) :=\n  let (xs, x0) := y2 in\n  let (ys, y3) :=\n    let (x1, x2) := y1 in\n    let (y3, y4) := y in\n    (let (x3, x4) := x1 in\n     let (y5, y6) := y3 in\n     (@selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x3 y5,\n     @selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x4 y6),\n    let (x3, x4) := x2 in\n    let (y5, y6) := y4 in\n    (@selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x3 y5,\n    @selc (@x86.W (Z.of_nat 64) ops) (@x86.selc (Z.of_nat 64) ops) CF x4 y6)) in\n  let (carry, zs) :=\n    let (xs0, x1) := xs in\n    let (ys0, y4) := ys in\n    let (carry, zs) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 false in\n    let (carry0, z) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry in\n    (carry0, (zs, z)) in\n  let (carry0, z) :=\n    let (xs0, x1) := x0 in\n    let (ys0, y4) := y3 in\n    let (carry0, zs0) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) xs0 ys0 carry in\n    let (carry1, z) :=\n      @subc (@x86.W (Z.of_nat 64) ops) (@x86.subc (Z.of_nat 64) ops) x1 y4 carry0 in\n    (carry1, (zs0, z)) in\n  (carry0, (zs, z)) in\ny3.\n  Definition rexpression : Syntax.Expr base_type (interp_base_type _) op (Arrow TW (Arrow TW (Arrow TW (Arrow TW (Arrow TW (Arrow TW (Arrow TW (Arrow TW (Tbase TW))))))))).\n  Proof.\n    Typeclasses eauto := debug.\n    Time try let v := (eval cbv beta delta [barrett_reduce64'1] in (fun a b c d e f g h => barrett_reduce64'1 (((a, b), (c, d)), ((e, f), (g, h))))) in\n             let v := Reify v in\n             exact v.\n  Defined.\nEnd x86.\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_reify/src/Specific/X86/Exponent25519.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1967970071523716}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.base_logic.lib Require Import na_invariants.\nFrom self.logrel Require Import model.\nFrom self.prob_lang Require Import adequacy primitive_laws lang.\n\nClass prelogrelGpreS \u03a3 := PrelogrelGPreS {\n  prelogrelGpreS_preloc :> prelocGpreS \u03a3;\n  prelorelGpreS_na_inv  :> na_invG \u03a3;\n}.\n\nDefinition prelogrel\u03a3 : gFunctors := #[preloc\u03a3; na_inv\u03a3].\nGlobal Instance subG_prelogrelGPreS {\u03a3} : subG prelogrel\u03a3 \u03a3 \u2192 prelogrelGpreS \u03a3.\nProof. solve_inG. Qed.\n\nTheorem refines_coupling \u03a3 `{prelogrelGpreS \u03a3}\n  (A : \u2200 `{prelogrelGS \u03a3}, lrel \u03a3) (\u03c6 : val \u2192 val \u2192 Prop) e e' \u03c3 \u03c3' n :\n  (\u2200 `{prelogrelGS \u03a3}, \u2200 v v', A v v' -\u2217 \u231c\u03c6 v v'\u231d) \u2192\n  (\u2200 `{prelogrelGS \u03a3}, \u22a2 REL e << e' : A) \u2192\n  refRcoupl (exec_val n (e, \u03c3)) (lim_exec_val (e', \u03c3')) \u03c6.\nProof.\n  intros HA Hlog.\n  apply (wp_refRcoupl \u03a3).\n  intros ?.\n  iIntros \"#Hctx He'\".\n  iMod na_alloc as \"[%\u03b3 Htok]\".\n  set (Hprelogrel := PrelogrelGS \u03a3 _ _ \u03b3).\n  iPoseProof (Hlog _) as \"Hlog\".\n  rewrite refines_eq /refines_def.\n  iSpecialize (\"Hlog\" $! []  with \"[$Hctx $He'] Htok\").\n  iApply (wp_mono with \"Hlog\").\n  iIntros (?) \"H /=\".\n  iDestruct \"H\" as (?) \"([? ? ] & ? & ?) /=\".\n  iExists _. iFrame. by iApply HA.\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/logrel/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.19665915246851604}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import RVIC.Layer.\nRequire Import RVIC2.Code.rvic_target_is_valid.\n\nRequire Import RVIC2.LowSpecs.rvic_target_is_valid.\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    \u2205.\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    Lemma rvic_target_is_valid_body_correct:\n      forall m d env le target res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTtarget: PTree.get _target le = Some (Vlong target))\n             (Hspec: rvic_target_is_valid_spec0 (VZ64 (Int64.unsigned target)) d = Some (Int.unsigned res)),\n           exists le', (exec_stmt ge env le ((m, d): mem) rvic_target_is_valid_body E0 le' (m, d) (Out_return (Some (Vint res, tuint)))).\n    Proof.\n      solve_code_proof Hspec rvic_target_is_valid_body; eexists; solve_proof_low.\n      simpl in C1. solve_proof_low. simpl in C1. omega.\n      solve_proof_low. solve_proof_low. simpl in *. solve_proof_low.\n      solve_proof_low. 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/RVIC2/CodeProof/rvic_target_is_valid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664376754715787}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef.\nRequire Import IntroHeader.\nImport Sep.\n\nSet Implicit Arguments.\n\n\n\nSection PROOF.\n\n  Context `{\u03a3: GRA.t}.\n  Context `{@GRA.inG IRA.t \u03a3}.\n\n  Definition Gsbtb: list (string * fspecbody) := [(\"g\", mk_specbody g_spec (fun _ => trigger (Choose _)))].\n\n  Definition GSem: SModSem.t := {|\n    SModSem.fnsems := Gsbtb;\n    SModSem.mn := \"G\";\n    SModSem.initial_mr := GRA.embed (IRA.module true: IRA.t);\n    SModSem.initial_st := tt\u2191;\n  |}\n  .\n\n  Definition G: Mod.t := (SMod.to_tgt (fun _ => GlobalStb)) {|\n    SMod.get_modsem := fun _ => GSem;\n    SMod.sk := [(\"g\", 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/intro/IntroGSep1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664376237036088}}
{"text": "(*********************************************************************************************************************************)\n(* HaskSkolemizer:                                                                                                               *)\n(*                                                                                                                               *)\n(*   Skolemizes the portion of a proof which uses judgments at level >0                                                          *)\n(*                                                                                                                               *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import NaturalDeduction.\nRequire Import NaturalDeductionContext.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Import HaskKinds.\nRequire Import HaskCoreTypes.\nRequire Import HaskCoreVars.\nRequire Import HaskWeakTypes.\nRequire Import HaskWeakVars.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskStrongTypes.\nRequire Import HaskProof.\nRequire Import NaturalDeduction.\n\nRequire Import HaskStrongTypes.\nRequire Import HaskStrong.\nRequire Import HaskProof.\nRequire Import HaskStrongToProof.\nRequire Import HaskProofToStrong.\nRequire Import HaskWeakToStrong.\n\nOpen Scope nd_scope.\nSet Printing Width 130.\n\nSection HaskSkolemizer.\n\n(*\n  Fixpoint debruijn2phoas {\u03ba} (exp: RawHaskType (fun _ => nat) \u03ba) : HaskType TV \u03ba :=\n     match exp with\n    | TVar    _  x          => x\n    | TAll     _ y          => TAll   _  (fun v => debruijn2phoas  (y (TVar v)))\n    | TApp   _ _ x y        => TApp      (debruijn2phoas  x) (debruijn2phoas  y)\n    | TCon       tc         => TCon      tc\n    | TCoerc _ t1 t2 t      => TCoerc    (debruijn2phoas  t1) (debruijn2phoas  t2)   (debruijn2phoas  t)\n    | TArrow                => TArrow\n    | TCode      v e        => TCode     (debruijn2phoas  v) (debruijn2phoas  e)\n    | TyFunApp  tfc kl k lt => TyFunApp tfc kl k (debruijn2phoasyFunApp _ lt)\n    end\n    with debruijn2phoasyFunApp (lk:list Kind)(exp:@RawHaskTypeList (fun _ => nat) lk) : @HaskTypeList TV lk :=\n    match exp in @RawHaskTypeList _ LK return @RawHaskTypeList TV LK with\n    | TyFunApp_nil               => TyFunApp_nil\n    | TyFunApp_cons  \u03ba kl t rest => TyFunApp_cons _ _ (debruijn2phoas  t) (debruijn2phoasyFunApp _ rest)\n    end.\n*)\n  Definition isNotBrakOrEsc {h}{c} (r:Rule h c) : Prop :=\n    match r with\n      | RBrak _ _ _ _ _ _ => False\n      | REsc  _ _ _ _ _ _ => False\n      | _                 => True\n    end.\n\n  Fixpoint mkArrows {\u0393}(lt:list (HaskType \u0393 \u2605))(t:HaskType \u0393 \u2605) : HaskType \u0393 \u2605 :=\n    match lt with\n      | nil => t\n      | a::b => mkArrows b (a ---> t)\n    end.\n\n(*\n  Fixpoint unleaves_ {\u0393}(t:Tree ??(LeveledHaskType \u0393 \u2605))(l:list (HaskType \u0393 \u2605)) lev : Tree ??(LeveledHaskType \u0393 \u2605) :=\n    match l with\n      | nil  => t\n      | a::b => unleaves_ (t,,[a @@ lev]) b lev\n    end.\n*)\n  (* weak inverse of \"leaves\" *)\n  Fixpoint unleaves_ {A:Type}(l:list A) : Tree (option A) :=\n    match l with\n      | nil      => []\n      | (a::nil) => [a]\n      | (a::b)   => [a],,(unleaves_ b)\n    end.\n\n  (* rules of skolemized proofs *)\n  Definition get\u0393 (j:Judg) := match j with \u0393 > _ > _ |- _ @ _ => \u0393 end.\n\n  Fixpoint take_trustme {\u0393}\n    (n:nat)\n    (l:forall TV, InstantiatedTypeEnv TV \u0393 -> list (RawHaskType TV \u2605))\n    : list (HaskType \u0393 \u2605) :=\n\n    match n with\n      | 0    => nil\n      | S n' => (fun TV ite => match l TV ite with\n                | nil  => Prelude_error \"impossible\"\n                | a::b => a\n                end)\n                ::\n                take_trustme n' (fun TV ite => match l TV ite with\n                | nil  => Prelude_error \"impossible\"\n                | a::b => b\n                end)\n    end.\n                  \n  Axiom phoas_extensionality : forall \u0393 Q (f g:forall TV, InstantiatedTypeEnv TV \u0393 -> Q TV),\n    (forall tv ite, f tv ite = g tv ite) -> f=g.\n\n  Definition take_arg_types_as_tree {\u0393}(ht:HaskType \u0393 \u2605) : Tree ??(HaskType \u0393 \u2605 ) :=\n    unleaves_\n    (take_trustme\n      (count_arg_types (ht _ (ite_unit _)))\n      (fun TV ite => take_arg_types (ht TV ite))).\n\n  Definition drop_arg_types_as_tree {\u0393} (ht:HaskType \u0393 \u2605) : HaskType \u0393 \u2605 :=\n    fun TV ite => drop_arg_types (ht TV ite).\n\n  Implicit Arguments take_arg_types_as_tree [[\u0393]].\n  Implicit Arguments drop_arg_types_as_tree [[\u0393]].\n\n  Definition take_arrange : forall {\u0393} (tx te:HaskType \u0393 \u2605) lev,\n    Arrange ([tx @@ lev],,take_arg_types_as_tree te @@@ lev)\n      (take_arg_types_as_tree (tx ---> te) @@@ lev).\n    intros.\n    destruct (eqd_dec ([tx],,take_arg_types_as_tree te) (take_arg_types_as_tree (tx ---> te))).\n      rewrite <- e.\n      simpl.\n      apply AId.\n    unfold take_arg_types_as_tree.\n      Opaque take_arg_types_as_tree.\n      simpl.\n      destruct (count_arg_types (te (fun _ : Kind => unit) (ite_unit \u0393))).\n      simpl.\n      replace (tx) with (fun (TV : Kind \u2192 Type) (ite : InstantiatedTypeEnv TV \u0393) => tx TV ite).\n      apply ACanR.\n        apply phoas_extensionality.\n        reflexivity.\n    apply (Prelude_error \"should not be possible\").\n    Defined.\n    Transparent take_arg_types_as_tree.\n\n  Definition take_unarrange : forall {\u0393} (tx te:HaskType \u0393 \u2605) lev,\n    Arrange (take_arg_types_as_tree (tx ---> te) @@@ lev)\n      ([tx @@ lev],,take_arg_types_as_tree te @@@ lev).\n    intros.\n    destruct (eqd_dec ([tx],,take_arg_types_as_tree te) (take_arg_types_as_tree (tx ---> te))).\n      rewrite <- e.\n      simpl.\n      apply AId.\n    unfold take_arg_types_as_tree.\n      Opaque take_arg_types_as_tree.\n      simpl.\n      destruct (count_arg_types (te (fun _ : Kind => unit) (ite_unit \u0393))).\n      simpl.\n      replace (tx) with (fun (TV : Kind \u2192 Type) (ite : InstantiatedTypeEnv TV \u0393) => tx TV ite).\n      apply AuCanR.\n        apply phoas_extensionality.\n        reflexivity.\n    apply (Prelude_error \"should not be possible\").\n    Defined.\n    Transparent take_arg_types_as_tree.\n\n  Lemma drop_works : forall {\u0393}(t1 t2:HaskType \u0393 \u2605),\n    drop_arg_types_as_tree (t1 ---> t2) = (drop_arg_types_as_tree t2).\n    intros.\n    unfold drop_arg_types_as_tree.\n    simpl.\n    reflexivity.\n    Qed.\n\n  Inductive SRule : Tree ??Judg -> Tree ??Judg -> Type :=\n(*  | SFlat  : forall h c (r:Rule h c), isNotBrakOrEsc r -> SRule h c*)\n  | SFlat  : forall h c, Rule h c -> SRule h c\n  | SBrak  : forall \u0393 \u0394 t ec \u03a3 l,\n    SRule\n    [\u0393 > \u0394 > \u03a3,,(take_arg_types_as_tree t @@@ (ec::l)) |- [ drop_arg_types_as_tree t        ] @ (ec::l)]\n    [\u0393 > \u0394 > \u03a3                                  |- [<[ec |- t]>                ] @l]\n\n  | SEsc   : forall \u0393 \u0394 t ec \u03a3 l,\n    SRule\n    [\u0393 > \u0394 > \u03a3                                  |- [<[ec |- t]>                ] @l]\n    [\u0393 > \u0394 > \u03a3,,(take_arg_types_as_tree t @@@ (ec::l)) |- [ drop_arg_types_as_tree t         ] @ (ec::l)]\n    .\n\n  Definition take_arg_types_as_tree' {\u0393}(lt:LeveledHaskType \u0393 \u2605) :=\n    match lt with t @@ l => take_arg_types_as_tree t @@@ l end.\n\n  Definition drop_arg_types_as_tree' {\u0393}(lt:LeveledHaskType \u0393 \u2605) :=\n    match lt with t @@ l => drop_arg_types_as_tree t @@ l end.\n\n  Definition skolemize_judgment (j:Judg) : Judg :=\n    match j with\n      | \u0393 > \u0394 > \u03a3\u2081 |- \u03a3\u2082 @ nil       => j\n        | \u0393 > \u0394 > \u03a3\u2081 |- \u03a3\u2082 @ lev => \n          \u0393 > \u0394 > \u03a3\u2081,,(mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3\u2082 @@@ lev) |- mapOptionTree drop_arg_types_as_tree \u03a3\u2082 @ lev\n    end.\n\n  Definition check_hof : forall {\u0393}(t:HaskType \u0393 \u2605),\n    sumbool\n    True\n    (take_arg_types_as_tree t = [] /\\ drop_arg_types_as_tree t = t).\n    intros.\n    destruct (eqd_dec (take_arg_types_as_tree t) []);\n    destruct (eqd_dec (drop_arg_types_as_tree t) t).\n    right; auto.\n    left; auto.\n    left; auto.\n    left; auto.\n    Defined.\n\n  Opaque take_arg_types_as_tree.\n  Definition skolemize_proof :\n    forall  {h}{c},\n      ND Rule  h c ->\n      ND SRule (mapOptionTree skolemize_judgment h) (mapOptionTree skolemize_judgment c).\n    intros.\n    eapply nd_map'; [ idtac | apply X ].\n    clear h c X.\n    intros.\n\n    refine (match X as R in Rule H C with\n      | RArrange \u0393 \u0394 a b x l d         => let case_RArrange := tt      in _\n      | RNote    \u0393 \u0394 \u03a3 \u03c4 l n           => let case_RNote := tt         in _\n      | RLit     \u0393 \u0394 l     _           => let case_RLit := tt          in _\n      | RVar     \u0393 \u0394 \u03c3           lev   => let case_RVar := tt          in _\n      | RGlobal  \u0393 \u0394 \u03c3 l wev           => let case_RGlobal := tt       in _\n      | RLam     \u0393 \u0394 \u03a3 tx te     lev   => let case_RLam := tt          in _\n      | RCast    \u0393 \u0394 \u03a3 \u03c3 \u03c4 lev \u03b3       => let case_RCast := tt         in _\n      | RAbsT    \u0393 \u0394 \u03a3 \u03ba \u03c3 lev n       => let case_RAbsT := tt         in _\n      | RAppT    \u0393 \u0394 \u03a3 \u03ba \u03c3 \u03c4     lev   => let case_RAppT := tt         in _\n      | RAppCo   \u0393 \u0394 \u03a3 \u03ba \u03c3\u2081 \u03c3\u2082 \u03b3 \u03c3 lev => let case_RAppCo := tt        in _\n      | RAbsCo   \u0393 \u0394 \u03a3 \u03ba \u03c3  \u03c3\u2081 \u03c3\u2082  lev => let case_RAbsCo := tt        in _\n      | RApp     \u0393 \u0394 \u03a3\u2081 \u03a3\u2082 tx te lev   => let case_RApp := tt          in _\n      | RCut     \u0393 \u0394 \u03a3 \u03a3\u2081 \u03a3\u2081\u2082 \u03a3\u2082 \u03a3\u2083 l  => let case_RCut := tt          in _\n      | RLeft    \u0393 \u0394 \u03a3\u2081 \u03a3\u2082  \u03a3     l    => let case_RLeft := tt in _\n      | RRight   \u0393 \u0394 \u03a3\u2081 \u03a3\u2082  \u03a3     l    => let case_RRight := tt in _\n      | RVoid    _ _           l       => let case_RVoid := tt   in _\n      | RBrak    \u0393 \u0394 t ec succ lev     => let case_RBrak := tt         in _\n      | REsc     \u0393 \u0394 t ec succ lev     => let case_REsc := tt          in _\n      | RCase    \u0393 \u0394 lev tc \u03a3 avars tbranches alts => let case_RCase := tt         in _\n      | RLetRec  \u0393 \u0394 lri x y t         => let case_RLetRec := tt       in _\n      end); clear X h c.\n\n      destruct case_RArrange.\n        simpl.\n        destruct l. \n        apply nd_rule.\n        apply SFlat.\n        apply RArrange.\n        apply d.\n        apply nd_rule.\n        apply SFlat.\n        apply RArrange.\n        apply ARight.\n        apply d.\n\n      destruct case_RBrak.\n        simpl.\n        destruct lev; [ idtac | apply (Prelude_error \"Brak with nesting depth >1\") ].\n        apply nd_rule.\n        apply SBrak.\n\n      destruct case_REsc.\n        simpl.\n        destruct lev; [ idtac | apply (Prelude_error \"Esc with nesting depth >1\") ].\n        apply nd_rule.\n        apply SEsc.\n\n      destruct case_RNote.\n        apply nd_rule.\n        apply SFlat.\n        simpl.\n        destruct l.\n        apply RNote.\n        apply n.\n        apply RNote.\n        apply n.\n\n      destruct case_RLit.\n        simpl.\n        destruct l0.\n        apply nd_rule.\n        apply SFlat.\n        apply RLit.\n        set (check_hof (@literalType l \u0393)) as hof.\n        destruct hof; [ apply (Prelude_error \"attempt to use a literal with higher-order type at depth>0\") | idtac ].\n        destruct a.\n        rewrite H.\n        rewrite H0.\n        simpl.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; apply AuCanL ].\n        apply nd_rule.\n        apply SFlat.\n        apply RLit.\n\n      destruct case_RVar.\n        simpl.\n        destruct lev.\n        apply nd_rule; apply SFlat; apply RVar.\n        set (check_hof \u03c3) as hof.\n        destruct hof; [ apply (Prelude_error \"attempt to use a variable with higher-order type at depth>0\") | idtac ].\n        destruct a.\n        rewrite H.\n        rewrite H0.\n        simpl.\n        eapply nd_comp; [ idtac | eapply nd_rule; apply SFlat; eapply RArrange; apply AuCanR ].\n        apply nd_rule.\n        apply SFlat.\n        apply RVar.\n\n      destruct case_RGlobal.\n        simpl.\n        destruct \u03c3.\n        apply nd_rule; apply SFlat; apply RGlobal.\n        set (check_hof (l wev)) as hof.\n        destruct hof; [ apply (Prelude_error \"attempt to use a global with higher-order type at depth>0\") | idtac ].\n        destruct a.\n        rewrite H.\n        rewrite H0.\n        simpl.\n        eapply nd_comp; [ idtac | eapply nd_rule; apply SFlat; eapply RArrange; apply AuCanR ].\n        apply nd_rule.\n        apply SFlat.\n        apply RGlobal.\n\n      destruct case_RLam.\n        destruct lev.\n          apply nd_rule.\n          apply SFlat.\n          simpl.\n          apply RLam.\n        simpl.\n        rewrite drop_works.\n        apply nd_rule.\n          apply SFlat.\n          apply RArrange.\n          eapply AComp.\n          eapply AuAssoc.\n          eapply ALeft.\n          apply take_arrange.\n\n      destruct case_RCast.\n        simpl.\n        destruct lev.\n        apply nd_rule.\n        apply SFlat.\n        apply RCast.\n        apply \u03b3.\n        apply (Prelude_error \"found RCast at level >0\").\n\n      destruct case_RApp.\n        simpl.\n        destruct lev.\n        apply nd_rule.\n        apply SFlat.\n        apply RApp.\n        rewrite drop_works.\n        set (check_hof tx) as hof_tx.\n        destruct hof_tx; [ apply (Prelude_error \"attempt tp apply a higher-order function at depth>0\") | idtac ].\n        destruct a.\n        rewrite H.\n        rewrite H0.\n        simpl.\n        eapply nd_comp.\n        eapply nd_prod; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ACanR ].\n        eapply nd_rule.\n        eapply SFlat.\n        eapply RArrange.\n        eapply ALeft.\n        eapply take_unarrange.\n\n        eapply nd_comp; [ idtac | eapply nd_rule; apply SFlat; eapply RArrange; apply AAssoc ].\n        eapply nd_comp; [ apply nd_exch | idtac ].\n        eapply nd_rule; eapply SFlat; eapply RCut.\n\n      destruct case_RCut.\n        simpl; destruct l; [ apply nd_rule; apply SFlat; apply RCut | idtac ].\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3\u2083) as \u03a3\u2083''.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3\u2083) as \u03a3\u2083'''.\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3\u2081\u2082) as \u03a3\u2081\u2082''.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3\u2081\u2082) as \u03a3\u2081\u2082'''.\n        destruct (decide_tree_empty (\u03a3\u2081\u2082'' @@@ (h::l)));\n          [ idtac | apply (Prelude_error \"used RCut on a variable with function type\") ].\n        destruct (eqd_dec \u03a3\u2081\u2082 \u03a3\u2081\u2082'''); [ idtac | apply (Prelude_error \"used RCut on a variable with function type\") ].\n        rewrite <- e.\n        clear e.\n        destruct s.\n        eapply nd_comp.\n          eapply nd_prod.\n          eapply nd_rule.\n          eapply SFlat.\n          eapply RArrange.\n          eapply AComp.\n          eapply ALeft.\n          eapply arrangeCancelEmptyTree with (q:=x).\n          apply e.\n          apply ACanR.\n          apply nd_id.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply AAssoc ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply AAssoc ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RCut ].\n        apply nd_prod.\n        apply nd_id.\n        eapply nd_rule.\n          eapply SFlat.\n          eapply RArrange.\n          eapply AComp.\n          eapply AuAssoc.\n          eapply ALeft.\n          eapply AComp.\n          eapply AuAssoc.\n          eapply ALeft.\n          eapply AId.\n\n      destruct case_RLeft.\n        simpl; destruct l; [ apply nd_rule; apply SFlat; apply RLeft | idtac ].\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3\u2082) as \u03a3\u2082'.\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3) as \u03a3'.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3\u2082) as \u03a3\u2082''.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3) as \u03a3''.\n        destruct (decide_tree_empty (\u03a3' @@@ (h::l)));\n          [ idtac | apply (Prelude_error \"used RLeft on a variable with function type\") ].\n        destruct (eqd_dec \u03a3 \u03a3''); [ idtac | apply (Prelude_error \"used RLeft on a variable with function type\") ].\n        rewrite <- e.\n        clear \u03a3'' e.\n        destruct s.\n        set (arrangeUnCancelEmptyTree _ _ e) as q.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply ARight; eapply q ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply AuCanL; eapply q ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply AAssoc ].\n        apply nd_rule.\n        eapply SFlat.\n        eapply RLeft.\n        \n      destruct case_RRight.\n        simpl; destruct l; [ apply nd_rule; apply SFlat; apply RRight | idtac ].\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3\u2082) as \u03a3\u2082'.\n        set (mapOptionTreeAndFlatten take_arg_types_as_tree \u03a3) as \u03a3'.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3\u2082) as \u03a3\u2082''.\n        set (mapOptionTree drop_arg_types_as_tree \u03a3) as \u03a3''.\n        destruct (decide_tree_empty (\u03a3' @@@ (h::l)));\n          [ idtac | apply (Prelude_error \"used RRight on a variable with function type\") ].\n        destruct (eqd_dec \u03a3 \u03a3''); [ idtac | apply (Prelude_error \"used RRight on a variable with function type\") ].\n        rewrite <- e.\n        clear \u03a3'' e.\n        destruct s.\n        set (arrangeUnCancelEmptyTree _ _ e) as q.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply ALeft; eapply q ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply AuCanR ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply AAssoc ].\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply ALeft; eapply AExch ].  (* yuck *)\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply AuAssoc ].\n        eapply nd_rule.\n        eapply SFlat.\n        apply RRight.\n\n      destruct case_RVoid.\n        simpl.\n        destruct l.\n        apply nd_rule.\n        apply SFlat.\n        apply RVoid.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply SFlat; eapply RArrange; eapply AuCanL ].\n        apply nd_rule.\n        apply SFlat.\n        apply RVoid.\n\n      destruct case_RAppT.\n        simpl.\n        destruct lev; [ apply nd_rule; apply SFlat; apply RAppT | idtac ].\n        apply (Prelude_error \"RAppT at depth>0\").\n\n      destruct case_RAbsT.\n        simpl.\n        destruct lev; simpl.\n          apply nd_rule.\n          apply SFlat.\n          apply (@RAbsT \u0393 \u0394 \u03a3 \u03ba \u03c3 nil n).\n        apply (Prelude_error \"RAbsT at depth>0\").\n\n      destruct case_RAppCo.\n        simpl.\n        destruct lev; [ apply nd_rule; apply SFlat; apply RAppCo | idtac ].\n        apply \u03b3.\n        apply (Prelude_error \"RAppCo at depth>0\").\n\n      destruct case_RAbsCo.\n        simpl.\n        destruct lev; [ apply nd_rule; apply SFlat; apply RAbsCo | idtac ].\n        apply (Prelude_error \"RAbsCo at depth>0\").\n\n      destruct case_RLetRec.\n        simpl.\n        destruct t.\n        apply nd_rule.\n        apply SFlat.\n        apply (@RLetRec \u0393 \u0394 lri x y nil).\n        destruct (decide_tree_empty (mapOptionTreeAndFlatten take_arg_types_as_tree y @@@ (h :: t)));\n          [ idtac | apply (Prelude_error \"used LetRec on a set of bindings involving a function type\") ].\n        destruct (eqd_dec y (mapOptionTree drop_arg_types_as_tree y));\n          [ idtac | apply (Prelude_error \"used LetRec on a set of bindings involving a function type\") ].\n        rewrite <- e.\n        clear e.\n        eapply nd_comp.\n          eapply nd_rule.\n          eapply SFlat.\n          eapply RArrange.\n          eapply ALeft.\n          eapply AComp.\n          eapply ARight.\n          destruct s.\n          apply (arrangeCancelEmptyTree _ _ e).\n          apply ACanL.\n        eapply nd_comp.\n          eapply nd_rule.\n          eapply SFlat.\n          eapply RArrange.\n          eapply AuAssoc.\n        eapply nd_rule.\n          eapply SFlat.\n          eapply RLetRec.\n\n      destruct case_RCase.\n        destruct lev; [ idtac | apply (Prelude_error \"case at depth >0\") ]; simpl.\n        apply nd_rule.\n        apply SFlat.\n        rewrite <- mapOptionTree_compose.\n        assert\n          ((mapOptionTree (fun x => skolemize_judgment (@pcb_judg tc \u0393 \u0394 nil tbranches avars (fst x) (snd x))) alts) =\n           (mapOptionTree (fun x => (@pcb_judg tc \u0393 \u0394 nil tbranches avars (fst x) (snd x))) alts)).\n           admit.\n           rewrite H.\n        set (@RCase \u0393 \u0394 nil tc \u03a3 avars tbranches alts) as q.\n        apply q.\n        Defined.\n\n  Transparent take_arg_types_as_tree.\n\nEnd HaskSkolemizer.\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/HaskSkolemizer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19664375719356386}}
{"text": "(**\n       preservation\n       also includes lemmas about Typing\n*)\nRequire Import LibTactics.\nRequire Import Coq.Program.Equality.\nRequire Import List. Import ListNotations.\nRequire Import Arith Lia.\nRequire Export Progress.\n\n(**************************** Typing ******************************************)\n\nLemma prevalue_subst : forall P Z u A,\n    prevalue u ->\n    pType u A ->\n    lc_typ P ->\n    prevalue (typsubst_exp P Z u) /\\ pType (typsubst_exp P Z u) [Z ~~> P] A.\nProof with simpls; eauto using typsubst_exp_lc_exp, typsubst_typ_lc_typ.\n  intros. gen A. inductions H; intros.\n  - inverts H0...\n  - inverts H0...  \n  - inverts H2. splits...\n  - inverts H2. splits; forwards~ (?&?): IHprevalue1; forwards~ (?&?): IHprevalue2...\nQed.\n\nLemma consistent_subst : forall U Z u1 u2,\n    consistent u1 u2 ->\n    TWell nil U ->\n    consistent (typsubst_exp U Z u1) (typsubst_exp U Z u2).\nProof.\n  intros. inductions H; simpls; eauto.\n  - applys C_anno; eauto 4 with lngen.\n  - forwards: TWell_lc_typ H4.\n    applys C_disjoint.\n    forwards*: prevalue_subst H2 H.\n    forwards*: prevalue_subst H3 H0.\n    forwards(?&?): disjoint_regular H1.\n    forwards~: TW_not_in Z H6.\n    forwards~: TW_not_in Z H7.\n    rewrites~ typsubst_typ_fresh_eq.\n    rewrites~ typsubst_typ_fresh_eq.\n    applys* prevalue_subst.\n    applys* prevalue_subst.\nQed.\n\n\nLemma Typing_subst_1 : forall E F D e dir T S U Z,\n    Typing (E ++ Z ~ S ++ F) D e dir T ->\n    TWell [] U ->\n    disjoint F U S ->\n    TCWell (map (typsubst_typ U Z) E ++ F) ->\n    Typing (map (typsubst_typ U Z) E ++ F) (map (typsubst_typ U Z) D) (typsubst_exp U Z e) dir (typsubst_typ U Z T).\nProof with eauto 3 using Typing_regular_3, TWell_lc_typ, Typing_TCWell, TWell_weakening.\n  introv Typ.\n  remember (E ++ Z ~ S ++ F) as E'. gen E.\n  inductions Typ; intros E Eq TW TD TCW; subst; simpl;\n  try solve [ constructor; eauto;\n              applys CWell_subst; eauto;\n              rewrite_env ([] ++ F ++ []);\n              applys TWell_weakening; eauto ].\n  - pick fresh x and apply Typ_abs.\n    (* forwards: appDist_subst Z U H. *)\n    (* eauto. simpl in H3. apply H3. *)\n    applys algo_sub_subst...\n    forwards~: H1 x.\n    (* forwards~: H2 x. *)\n    rewrites typsubst_exp_open_exp_wrt_exp in H2...\n  - forwards: IHTyp2...\n    applys Typ_app...\n    forwards: appDist_subst Z U.\n    applys H.\n    forwards~: TWell_lc_typ TW.\n    simpls...\n  - pick fresh X and apply Typ_tabs.\n    applys CWell_subst...\n    instantiate_cofinites.\n    forwards~: H1 ((X, A) :: E).\n    simpl_env.\n    constructor~.\n    applys TWell_subst_1...\n    rewrites typsubst_typ_open_typ_wrt_typ_var...\n    rewrites typsubst_exp_open_exp_wrt_typ_var...\n  - rewrites typsubst_typ_open_typ_wrt_typ...\n    forwards~: IHTyp.\n    applys Typ_tapp...\n    forwards~: appDist_subst Z U H.\n    forwards~: TWell_lc_typ TW.\n    simpl in H2. applys H2.\n    applys disjoint_subst...\n  - applys Typ_proj...\n    forwards~: appDist_subst Z U H...\n  - applys Typ_merge...\n    forwards: disjoint_subst H...\n  - pick fresh x and apply Typ_fix.\n    forwards*: H0 x.\n    simpls.\n    rewrites typsubst_exp_open_exp_wrt_exp_var...\n  - applys Typ_mergev...\n    applys CWell_subst...\n    forwards: Typing_regular_0 Typ1.\n    assert(Z `notin` {}). auto.\n    forwards: TW_not_in H3 H4.\n    forwards: TY_not_in Typ1. apply H4.\n    assert([Z ~~> U] (A) = A).\n    apply typsubst_typ_fresh_eq. auto.\n    assert((typsubst_exp U Z u1) = u1).\n    apply typsubst_exp_fresh_eq. auto.\n    rewrite H7. rewrite H8. auto.\n    forwards: Typing_regular_0 Typ2.\n    assert(Z `notin` {}). auto.\n    forwards: TW_not_in H3 H4.\n    forwards: TY_not_in Typ2. apply H4.\n    assert([Z ~~> U] (B) = B).\n    apply typsubst_typ_fresh_eq. auto.\n    assert((typsubst_exp U Z u2) = u2).\n    apply typsubst_exp_fresh_eq. auto.\n    rewrite H7. rewrite H8. auto.\n    applys consistent_subst...\n  - applys Typ_sub...\n    forwards~: Typing_regular_3 Typ.\n    applys algo_sub_subst...\nQed.\n\nLemma TWell_subsub_1: forall D A B,\n    TWell D A -> subsub A B -> TWell D B.\nProof.\n  intros. inductions H0; eauto.\n    inverts H.\n    forwards~: IHsubsub1.\n    forwards~: IHsubsub2.\nQed.\n\nLemma TWell_subsub_2: forall D A B,\n    TWell D B -> subsub A B -> TWell D A.\nProof.\n  intros. inductions H0; eauto.\nQed.    \n\n(* its form can be simplified, like preservation *)\n\nLemma Typing_subst_2_inf_subsub : forall D (E F : ctx) e u S S' dir T (z : atom),\n    Typing D (F ++ [(z,S)] ++ E) e dir T ->\n    Typing D E u Inf S' -> subsub S' S ->\n    ( dir = Inf ->\n      exists T', Typing D (F ++ E) ([z ~> u] e) Inf T' /\\ subsub T' T )\n    /\\\n    ( dir = Chk -> Typing D (F ++ E) ([z ~> u] e) Chk T ).\nProof.\n  introv Typ Typv Subsub.\n  remember (F ++ [(z,S)] ++ E) as E'.\n  generalize dependent F.\n  inductions Typ;\n    intros F Eq; subst; simpl;\n      lets Lc  : Typing_regular_1 Typv;\n      lets Uni : Typing_regular_2 Typv.\n  all: split; intro Heq; try solve [inverts Heq].\n  - (* top *)\n    exists; split*; constructor*.\n    forwards* HH: CWell_app_2 H0.\n    destruct* HH as [HH1 HH2].\n    forwards*: CWell_app_2 HH1.\n    destruct* H2 as [HH3 _].\n    forwards*: CWell_app_1 HH3 HH2.\n  - (* lit *)\n    exists; split*; constructor*.\n    forwards* HH: CWell_app_2 H0.\n    destruct* HH as [HH1 HH2].\n    forwards*: CWell_app_2 HH1.\n    destruct* H2 as [HH3 _].\n    forwards*: CWell_app_1 HH3 HH2.\n  - (* var *)\n    case_if. substs. assert (A = S).\n    eapply binds_mid_eq; eauto.\n    + substs.\n      exists. split.\n      apply~ Typing_weakening_3. eauto.\n      forwards*: CWell_app_2 H0.\n      solve_uniq.\n      auto.\n    + exists A.\n      split.\n      constructor*.\n      forwards* HH: CWell_app_2 H0.\n      destruct* HH as [HH1 HH2].\n      forwards*: CWell_app_2 HH1.\n      destruct* H3 as [HH3 _].\n      forwards*: CWell_app_1 HH3 HH2.\n      constructor*.\n  - (* abs *)\n    pick fresh x and apply Typ_abs. now auto.\n    forwards~ (HF&HT1): H1 x.\n    rewrite_env (([(x, A)] ++ F) ++ [(z, S)] ++ E). now reflexivity.\n    forwards~ HT1': HT1. clear HT1 HF.\n    rewrites subst_exp_open_exp_wrt_exp_var. eassumption.\n    eauto. eauto.\n  - (* app *)\n    forwards* (HT1&HF): IHTyp1. forwards~ (?&HT1'&HS): HT1. clear HF.\n    forwards* (HF&HT2): IHTyp2. forwards~ HT2': HT2. clear HF.\n    forwards* (B'&T'&?&?&?): appDist_arr_subsub D HS.\n    exists T'. split*. econstructor; try eassumption.\n    (* duplicated Type *)\n    forwards: Typing_chk_dup; try eassumption.\n  - (* tabs *)\n    pick fresh x and apply Typ_tabs.\n    forwards* HH: CWell_app_2 H. destruct* HH as [HH1 HH2].\n    forwards* HHH: CWell_app_2 HH1. destruct* HHH as [HH3 _].\n    forwards*: CWell_app_1 HH3 HH2.\n    forwards*: H0 x.\n    forwards~ (HF&HT1): H1 x.\n    { applys* (Typing_weakening_1 [] D x A E u Inf S'). solve_notin. }\n    forwards~ HT1': HT1. clear HT1 HF.\n    rewrite subst_exp_open_exp_wrt_typ in HT1'.\n    applys HT1'. eauto.\n  - (* tapp *)\n    forwards* (HT1&HF): IHTyp. forwards~ (?&HT1'&HS): HT1. clear HT1 HF.\n    forwards~ (?&?&?&?&?): appDist_forall_subsub_disjoint D H HS.\n    exists (x1 ^-^ A). split.\n    applys* Typ_tapp HT1'.\n    apply disjoint_covariance with C1. auto. auto. auto.\n  - (* proj *)\n    forwards* (HT1&HF): IHTyp. forwards~ (?&HT1'&HS): HT1. clear HT1 HF.\n    forwards* (?&?&?): appDist_rcd_subsub D HS.\n  - (* rcd *)\n    forwards* (HT1&HF): IHTyp.\n  - (* merge *)\n    forwards* (HT1&HF): IHTyp1. forwards~ (?&HT1'&HS): HT1. clear HT1 HF.\n    forwards* (HT2&HF): IHTyp2. forwards~ (?&HT2'&HS'): HT2. clear HT2 HF.\n    exists (t_and x x0). split. constructor~.\n    apply subsub2sub with D x A in HS; auto. destruct HS.\n    apply subsub2sub with D x0 B in HS'; auto. destruct HS'.\n    apply disjoint_covariance with B.\n    apply disjoint_symm.\n    apply disjoint_covariance with A.\n    auto. auto. auto. econstructor; eauto.\n  - (* inter *)\n    forwards* (HF&HT1): IHTyp1. forwards~ HT1': HT1. clear HT1 HF.\n    forwards* (HF&HT2): IHTyp2.\n  - (* anno *)\n    forwards* (HT1&HF): IHTyp.\n  - (* fix *)\n    exists A. split*.\n    pick fresh x and apply Typ_fix.\n    forwards* (HF&HT): H0 x.\n    rewrite_env (((x, A) :: F) ++ [(z, S)] ++ E). reflexivity.\n    forwards~ HT': HT. clear HT HF.\n    rewrites subst_exp_open_exp_wrt_exp_var; eauto.\n    econstructor; eauto.\n    instantiate_cofinites. now eauto.\n  - (* mergev *)\n    lets Eq1: ((subst_value _ _ _ _ z u) Typ1).\n    lets Eq2: ((subst_value _ _ _ _ z u) Typ2).\n    rewrite Eq1.\n    rewrite Eq2.\n    exists (t_and A B).\n    split~.\n    applys* (Typ_mergev D (F ++ E) u1 u2 A B).\n    forwards* HH: CWell_app_2 H0.\n    destruct* HH as [HH1 HH2].\n    forwards*: CWell_app_2 HH1.\n    destruct* H3.\n    forwards*: CWell_app_1 H3 HH2.\n    (* assert(subsub (t_and A B) (t_and A B)).\n    eauto.\n    rewrite_env(nil ++ D ++ nil).\n    apply subsub_weakening. auto.\n    apply subsub_well_tctx in Subsub.\n    assert(nil ++ D ++ nil = D). simpl. eauto.\n    rewrite H4. auto. *)\n  - (* subsumption *)\n    forwards* (HT1&HF): IHTyp. forwards~ (?&HT1'&HS): HT1. clear HT1 HF.\n    apply subsub2sub with D x A in HS; auto. destruct HS.\n    assert (algo_sub D x B) by auto_sub.\n    applys* Typ_sub.\nQed.\n\n(****************************** reduction-related *****************************)\n\n(****************************** casting *****************************)\n\nLemma casting_value_2: forall v A v',\n    value v ->\n    casting v A v' ->\n    value v' /\\ exists A', pType v' A' /\\ subsub A' A.\nProof with eauto 3 with lngen.\n  intros v A v' Val Red.\n  induction Red...\n  all: splits...\n  all: try solve [exists; split*].\n  1: now inverts~ Val.\n  1,2: forwards~: IHRed1; forwards~: IHRed2; destruct_conj; eauto.\nQed.\n\nLemma consistent_keep: forall v v1 v2 A C,\n    value v -> pType v1 C -> TWell nil C -> consistent v v1 ->\n    casting v A v2 -> consistent v2 v1.\nProof with eauto.\n  introv Val PT TW Con TR. gen v2 A C.\n  inductions Con; intros v2 A' TR C PT TW.\n  - inductions TR.\n    2-5: try solve [applys* C_disjoint].\n    all: eauto.\n  - inductions TR.\n    1-4: try solve [applys* C_disjoint].\n    all: eauto.\n  - forwards: casting_sub TR...\n    forwards~ (?&?&?&?): casting_value_2 TR.\n    forwards (_&?): algo_sub_regular H4.\n    forwards: TWell_subsub_2 H8 H7.\n    applys C_disjoint H0...\n    forwards~ (?&?): subsub2sub H7; auto.\n    applys disjoint_symm.\n    apply disjoint_symm in H1.\n    applys* disjoint_covariance H1.\n  - inductions TR.\n    1-4: try solve [applys* C_disjoint].\n    all: eauto.\n  - inverts PT. forwards: IHCon1...\nQed.\n\n\nLemma casting_consistent : forall v A B C v1 v2,\n    value v -> \n    Typing nil nil v Inf C -> \n    casting v A v1 -> \n    casting v B v2 ->\n    consistent v1 v2.\nProof with try eassumption.\n  intros. gen B C v2.\n  dependent induction H1;intros.\n  - (* lit *)\n    dependent induction H2; intros; eauto.\n  - (* top *)\n    forwards* (?&?&?&SS): casting_value_2 H2.\n    forwards~: typ_value_ptype H1.\n    forwards~: casting_sub H2 H5.\n    forwards (_&?): algo_sub_regular H6.\n    forwards*: TWell_subsub_1.\n  - (* topabs *)\n    forwards~ (?&?&?&SS): casting_value_2 H4.\n    forwards~: typ_value_ptype H3.\n    forwards~: casting_sub H4 H7.\n    forwards (_&?): algo_sub_regular H8.\n    forwards*: TWell_subsub_1.\n  - (* toptabs *)\n    forwards~ (?&?&?&?): casting_value_2 H4.\n    forwards~: typ_value_ptype H3.\n    forwards~: casting_sub H4 H8.\n    forwards (_&?): algo_sub_regular H9.\n    forwards*: TWell_subsub_1.\n  - (* toprcd *)\n    forwards~ (?&?&?&?): casting_value_2 H4.\n    forwards~: typ_value_ptype H3.\n    forwards~: casting_sub H4 H8.\n    forwards (_&?): algo_sub_regular H9.\n    forwards*: TWell_subsub_1.\n  - (* anno *)\n    dependent induction H5; intros.\n    1-4: applys* C_disjoint.\n    + (* C-anno *) eauto.\n    + (* merge *) eauto.\n  - (* mergel *)\n    inverts H.\n    inverts H3.\n    {\n      inductions H4.\n      1-4: forwards~ (?&?&?&?): casting_value_2 H2; applys* C_disjoint;\n            forwards~ PT: typ_value_ptype H6;\n            forwards~ Sub: casting_sub H2 PT;\n            forwards (_&?): algo_sub_regular Sub;\n            forwards*: TWell_subsub_1.\n      all: forwards~ (?&?&?&SS): casting_value_2 H2;\n            forwards~ PT: typ_value_ptype H6;\n            forwards~ Sub: casting_sub H2 PT;\n            forwards (_&TW): algo_sub_regular Sub;\n            try forwards~: TWell_subsub_1 TW SS;\n            try forwards~: TWell_subsub_2 TW SS.\n      + (* same branch *)\n        inverts~ H3; applys* IHcasting.\n      + (* diff branch *)\n        forwards~(?&?): subsub2sub SS; auto.\n        forwards~ (?&?&?&SS'): casting_value_2 H4;\n          forwards~ PT': typ_value_ptype H11;\n          forwards~ Sub': casting_sub H4 PT';\n          forwards (_&TW'): algo_sub_regular Sub';\n          try forwards~: TWell_subsub_1 TW' SS';\n          try forwards~: TWell_subsub_2 TW' SS'.\n        forwards(?&?): subsub2sub SS'; auto; auto.\n        forwards PV1': cast_prevalue H2.\n        forwards PV2': cast_prevalue H4.\n        forwards~ PV1: value_inf_prevalue H6.\n        forwards~ PV2: value_inf_prevalue H11.\n        applys~ C_disjoint x x0.\n        apply disjoint_covariance with B0.\n        apply disjoint_symm.\n        apply disjoint_covariance with A0.\n        apply disjoint_symm. auto.\n        eauto. eauto.\n        + (* spl *)\n          assert (consistent v1' v3). eauto.\n          assert (consistent v1' v0). eauto. auto.\n    }\n    {\n      inductions H4.\n      1-4: forwards~ (?&?&?&?): casting_value_2 H2; applys* C_disjoint;\n            forwards~ PT: typ_value_ptype H11;\n            forwards~ Sub: casting_sub H2 PT;\n            forwards (_&?): algo_sub_regular Sub;\n            forwards*: TWell_subsub_1.\n      all: forwards~ (?&?&?&SS): casting_value_2 H2;\n            forwards~ PT: typ_value_ptype H11;\n            forwards~ Sub: casting_sub H2 PT;\n            forwards (_&TW): algo_sub_regular Sub;\n            try forwards~: TWell_subsub_1 TW SS;\n            try forwards~: TWell_subsub_2 TW SS.\n      + (* same branch *)\n        inverts~ H3; applys* IHcasting.\n      + (* diff branch *)\n        forwards~(?&?): subsub2sub SS; auto.\n        forwards~ (?&?&?&SS'): casting_value_2 H4;\n          forwards~ PT': typ_value_ptype H14;\n          forwards~ Sub': casting_sub H4 PT';\n          forwards (_&TW'): algo_sub_regular Sub';\n          try forwards~: TWell_subsub_1 TW' SS';\n          try forwards~: TWell_subsub_2 TW' SS'.\n        forwards(?&?): subsub2sub SS'; auto; auto.\n        forwards~ PV1: value_inf_prevalue v1. eassumption.\n        forwards~ PV2: value_inf_prevalue v2. eassumption.\n        applys consistent_keep H2...\n        applys consistent_symm.\n        apply consistent_symm in H15.\n        applys* consistent_keep H15.\n      + (* spl *)\n        assert (consistent v1' v3). eauto.\n        assert (consistent v1' v0). eauto. auto.\n    }\n  - (* merger *)\n  inverts H.\n  inverts H3.\n  {\n    inductions H4.\n    1-4: forwards~ (?&?&?&?): casting_value_2 H2; applys* C_disjoint;\n          forwards~ PT: typ_value_ptype H11;\n          forwards~ Sub: casting_sub H2 PT;\n          forwards (_&?): algo_sub_regular Sub;\n          forwards*: TWell_subsub_1.\n    all: forwards~ (?&?&?&SS): casting_value_2 H2;\n          forwards~ PT: typ_value_ptype H11;\n          forwards~ Sub: casting_sub H2 PT;\n          forwards (_&TW): algo_sub_regular Sub;\n          try forwards~: TWell_subsub_1 TW SS;\n          try forwards~: TWell_subsub_2 TW SS.\n    + (* diff branch *)\n      forwards~(?&?): subsub2sub SS; auto.\n      forwards~ (?&?&?&SS'): casting_value_2 H4;\n        forwards~ PT': typ_value_ptype H6;\n        forwards~ Sub': casting_sub H4 PT';\n        forwards (_&TW'): algo_sub_regular Sub';\n        try forwards~: TWell_subsub_1 TW' SS';\n        try forwards~: TWell_subsub_2 TW' SS'.\n      forwards(?&?): subsub2sub SS'; auto; auto.\n      forwards PV1': cast_prevalue H2.\n      forwards PV2': cast_prevalue H4.\n      forwards~ PV1: value_inf_prevalue H6.\n      forwards~ PV2: value_inf_prevalue H11.\n      applys~ C_disjoint x x0.\n      apply disjoint_covariance with A0.\n      apply disjoint_symm.\n      apply disjoint_covariance with B0.\n      apply disjoint_symm. auto.\n      eauto. eauto.\n    + (* same branch *)\n      inverts~ H3; applys* IHcasting.\n    + (* spl *)\n      assert (consistent v2' v3). eauto.\n      assert (consistent v2' v0). eauto. auto.\n  }\n  {\n    inductions H4.\n    1-4: forwards~ (?&?&?&?): casting_value_2 H2; applys* C_disjoint;\n          forwards~ PT: typ_value_ptype H14;\n          forwards~ Sub: casting_sub H2 PT;\n          forwards (_&?): algo_sub_regular Sub;\n          forwards*: TWell_subsub_1.\n    all: forwards~ (?&?&?&SS): casting_value_2 H2;\n          forwards~ PT: typ_value_ptype H14;\n          forwards~ Sub: casting_sub H2 PT;\n          forwards (_&TW): algo_sub_regular Sub;\n          try forwards~: TWell_subsub_1 TW SS;\n          try forwards~: TWell_subsub_2 TW SS.\n    + (* diff branch *)\n      forwards~(?&?): subsub2sub SS; auto.\n      forwards~ (?&?&?&SS'): casting_value_2 H4;\n        forwards~ PT': typ_value_ptype H11;\n        forwards~ Sub': casting_sub H4 PT';\n        forwards (_&TW'): algo_sub_regular Sub';\n        try forwards~: TWell_subsub_1 TW' SS';\n        try forwards~: TWell_subsub_2 TW' SS'.\n      forwards(?&?): subsub2sub SS'; auto; auto.\n      forwards~ PV1: value_inf_prevalue v1. eassumption.\n      forwards~ PV2: value_inf_prevalue v2. eassumption.\n      applys consistent_keep H2...\n      applys consistent_symm.\n      applys* consistent_keep H15.\n    + (* same branch *)\n      inverts~ H3; applys* IHcasting.\n    + (* spl *)\n      assert (consistent v2' v3). eauto.\n      assert (consistent v2' v0). eauto. auto.\n  }\n   - (* spl *)\n     assert(consistent v1 v0). eauto.\n     assert(consistent v2 v0). eauto. auto.\nQed.\n\n\nLemma casting_preservation: forall v v' A B,\n    value v ->\n    casting v A v'->\n    Typing nil nil v Inf B ->\n    exists C, pType v' C /\\ Typing nil nil v' Inf C /\\ subsub C A.\nProof with eauto.\n  introv Val Red Typ. (* '. forwards* (B&Typ&Sub): Typing_chk2inf Typ'. *)\n  gen B. lets Red': Red.\n  induction Red; intros.\n  - (* lit *)\n    exists. splits*.\n  - (* top *)\n    exists. splits*.\n  - (* topAbs *)\n    inverts H1. exists. splits*. repeat econstructor; eauto.\n  - (* topTabs *)\n    inverts H0. inverts H1. exists. splits*.\n    econstructor. pick fresh x and apply Typ_tabs. now eauto.\n    instantiate_cofinites_with x. eauto.\n  - (* topRcd *)\n    inverts H0. inverts H1. exists. splits*.\n  - (* anno *)\n    inverts Typ. forwards: Typing_chk_sub_2; try eassumption.\n    exists*.\n  - (* mergel *)\n    inverts Val. inverts Typ; forwards*: IHRed.\n  - (* merger *)\n    inverts Val. inverts Typ; forwards*: IHRed.\n  - (* merge_and *)\n    forwards* (?&?): TWell_spl H.\n    forwards (?&?&?&?): IHRed1 Val Red1 Typ...\n    forwards (?&?&?&?): IHRed2 Val Red2 Typ...\n    exists (t_and x x0). split. auto.\n    forwards: casting_consistent Val Typ Red1 Red2.\n    split. applys~ Typ_mergev. eauto.\nQed.\n\n(*************************** wrapping *****************************)\n\nLemma wrapping_consistent : forall e A B C u1 u2,\n    Typing nil nil e Chk C ->\n    TWell nil A ->\n    TWell nil B ->\n    wrapping e A u1 ->\n    wrapping e B u2 ->\n    consistent u1 u2.\nProof with eauto 4.\n  introv Typ TW1 TW2 cast1 cast2.\n  forwards~ (PV1&B1&PT1&?): wrapping_prevalue cast1.\n  forwards~ (PV2&B2&PT2&?): wrapping_prevalue cast2.\n  inductions cast1.\n  - applys C_disjoint t_top...\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inductions cast2.\n    + applys C_disjoint B1 t_top...\n    + applys C_disjoint B1 (t_arrow A1 A2)...\n    + applys C_disjoint B1 (t_forall A1 A2)...\n    + applys C_disjoint B1 (t_rcd l A0)...\n    + applys C_anno...\n    + forwards: prevalue_merge_l_inv PV2.\n      forwards: prevalue_merge_r_inv PV2.\n      inverts PT2.\n      forwards~: IHcast2_1 H9.\n      forwards~: IHcast2_2 H11.\n  - forwards: prevalue_merge_l_inv PV1.\n    forwards: prevalue_merge_r_inv PV1.\n    inverts PT1.\n    forwards*: IHcast1_1.\nQed.\n\n\nLemma wrapping_preservation: forall e u A B,\n    wrapping e A u ->\n    Typing nil nil e Chk B -> nil ||- B <: A ->\n    prevalue u /\\ exists C, pType u C /\\ Typing nil nil u Inf C /\\ subsub C A.\nProof.\n  intros. gen e u. indTypSize (size_typ A).\n  inverts* H. all: try (split; [now eauto | ]).\n  - exists. splits*.\n    applys Typ_anno.\n    pick fresh x and apply Typ_abs; eauto.\n    inverts H4.\n    unfolds open_exp_wrt_exp; simpls*.\n  - exists. splits*.\n    applys Typ_anno.\n    inverts H4.\n    pick fresh X and apply Typ_tabs; eauto.\n    instantiate_cofinites.\n    unfolds open_exp_wrt_typ; simpls*.\n  - exists. splits*.\n    applys Typ_anno.\n    applys Typ_rcd.\n    inverts H4.\n    unfolds open_exp_wrt_exp; simpls*.\n  - forwards*: Typing_chk_sub_2 H0 H1.\n  - forwards*: IH H3. elia.\n    forwards~: IH C B H4. elia.\n    forwards*: split_sub H2.\n    destruct H as (C'&?).\n    destruct H5 as (C''&?).\n    destruct_conj.\n    split. { applys* PV_merge. }\n    exists; splits; eauto 3.\n    forwards: Typing_regular_0 H6.\n    forwards: Typing_regular_0 H8.\n    forwards*: wrapping_consistent H0 H3 H4.\n    forwards~: TWell_subsub_1 H10 H7.\nQed.\n\n(******************************** papp ********************************)\n\n\nLemma papp_consistent : forall v1 v2 e e1 e2 A B C,\n    value v1 -> value v2 ->\n    Typing nil nil v1 Inf A -> Typing nil nil v2 Inf B -> Typing nil nil e Chk C ->\n    papp v1 (arg_exp e) e1 -> papp v2 (arg_exp e) e2 -> consistent v1 v2 -> consistent e1 e2.\nProof with (eauto using lc_body_exp_wrt_exp; solve_false).\n  introv Val1 Val2 Typ1 Typ2 Typ3 P1 P2 Cons.\n  gen A B C. lets P1': P1. lets P2': P2.\n  inductions P1; inductions P2; intros.\n  - inverts* Cons.\n    + forwards*: wrapping_unique H1 H4; substs.\n      applys C_anno...\n    + inverts H5. inverts H6.\n      forwards*: appDist_arr_disjoint H7.\n      applys C_disjoint...\n  - lets (?&?): consistent_merger Cons. eauto. eauto.\n    inverts Typ2; eauto 4.\n  - lets (?&?): consistent_mergel Cons. eauto. eauto. inverts* Typ1.\n  - (* merge ~ merge *)\n    inverts Val1. lets~ (?&?): consistent_mergel Cons. inverts* Typ1.\nQed.\n\n\nLemma papp_consistent2 : forall v1 v2 l e1 e2 A B,\n    value v1 -> value v2 ->\n    Typing nil nil v1 Inf A -> Typing nil nil v2 Inf B ->\n    papp v1 (arg_la l) e1 -> papp v2 (arg_la l) e2 -> consistent v1 v2 -> consistent e1 e2.\nProof with (try eassumption; eauto 2).\n  introv Val1 Val2 Typ1 Typ2 P1 P2 Cons.\n  gen A B. lets P1': P1. lets P2': P2.\n  inductions P1; inductions P2; intros.\n  - inverts~ Cons.\n    inverts H3. inverts H4. typing_unify.\n    forwards: appDist_rcd_disjoint H5...\n    applys C_disjoint...\n  - lets (?&?): consistent_merger Cons. now eauto. now eauto.\n    inverts Typ2; applys C_merger.\n    all: try applys IHP2_1... all: try applys IHP2_2...\n  - lets (?&?): consistent_mergel Cons. now eauto. now eauto.\n    inverts Typ1; applys C_mergel.\n    all: try applys IHP2_1... all: try applys IHP2_2...\n  - (* merge ~ merge *)\n    inverts Val1. lets~ (?&?): consistent_mergel Cons. inverts* Typ1.\nQed.\n\n\nLemma papp_consistent3 : forall v1 v2 T e1 e2 A B A1 A2 B1 B2,\n    value v1 -> value v2 ->\n    Typing nil nil v1 Inf A -> Typing nil nil v2 Inf B ->\n    appDist A (t_forall A1 A2) -> appDist B (t_forall B1 B2) ->\n    disjoint [] T (t_and A1 B1) ->\n    papp v1 (arg_typ T) e1 -> papp v2 (arg_typ T) e2 ->\n    consistent v1 v2 ->\n    consistent e1 e2.\nProof with (try eassumption; eauto 2 with lngen).\n  introv Val1 Val2 Typ1 Typ2 AD1 AD2 HD P1 P2.\n  introv Cons.\n  gen A B A1 A2 B1 B2. lets P1': P1. lets P2': P2.\n  inductions P1; inductions P2; intros.\n  - inverts~ Cons; auto_unify.\n    + constructor; eauto 3 with lngen.\n    + (* disjoint case *)\n      applys C_disjoint.\n      1-2: econstructor; eauto with lngen.\n      applys disjoint_appDist_forall_inv H1 H2...\n      all: applys PV_anno; eauto with lngen.\n  - lets (?&?): consistent_merger Cons; auto_unify.\n    forwards (?&HD2): disjoint_andr_inv HD...\n    applys C_merger; inverts Typ2; appdist_unify;\n      forwards (?&?): disjoint_andr_inv HD2...\n    all: try applys IHP2_1 T; try applys IHP2_2 T; try assumption.\n    all: match goal with\n         | |- disjoint _ _ _ => idtac\n         | _ => try eassumption; eauto\n         end.\n    all: eauto.\n  - lets (?&?): consistent_mergel Cons; auto_unify.\n    forwards (HD2&?): disjoint_andr_inv HD...\n    applys C_mergel; inverts Typ1; appdist_unify;\n      forwards (?&?): disjoint_andr_inv HD2...\n    all: try applys IHP1_1; try applys IHP1_2; try assumption.\n    all: match goal with\n         | |- disjoint _ _ _ => idtac\n         | _ => try eassumption; eauto\n         end.\n    all: applys* D_andr.\n  - (* merge ~ merge *)\n    inverts Val1. lets~ (?&?): consistent_mergel Cons.\n    applys C_mergel; inverts Typ1; appdist_unify.\n    all: try applys IHP1_1; try applys IHP1_2; try reflexivity; try eassumption.\n    all: forwards (HD2&?): disjoint_andr_inv HD; now eauto.\nQed.\n\n\nLemma papp_preservation : forall v e e' A,\n    value v ->\n    Typing nil nil (e_app v e) Inf A ->\n    papp v (arg_exp e) e' ->\n    exists A', Typing nil nil e' Inf A' /\\ subsub A' A.\nProof with try eassumption.\n  intros v e e' A Val Typ P. gen A.\n  inductions P; intros; inverts Typ as Typ1 Typ2 Typ3; auto_unify.\n  - (* abs *)\n    exists A0. split.\n    2: { econstructor; eauto. }\n         (* eapply TWell_appDist in H0. inverts H0. eassumption. eauto. } *)\n    forwards* Typ': Typing_chk_appDist H5.\n    inverts Typ' as ? HT; solve_false.\n    econstructor.\n\n    forwards: wrapping_preservation H1... destruct_conj.\n\n    pick fresh y. forwards~ HT': HT y.\n    rewrite_env ([]++[(y,A)]++[]) in HT'.\n    forwards (HL&HR): Typing_subst_2_inf_subsub HT'...\n    clear HL. forwards~ HR': HR.\n    rewrite (@subst_exp_intro y). all: eauto.\n  - (* merge *)\n    inverts Val as Val1 Val2.\n    inverts Typ1; appdist_unify;\n      forwards (?&?): Typing_chk_inter_inv Typ3.\n    + forwards~: IHP1 e. applys Typ_app...\n      forwards~: IHP2 e. applys Typ_app... destruct_conj.\n      exists. split.\n      { applys Typ_merge...\n        forwards: appDist_arr_disjoint H3 H7...\n        forwards (_&?): disjoint_regular H10.\n        forwards~ (?&?): subsub2sub H8; auto.\n        forwards~ (?&?): subsub2sub H9; auto.\n        applys disjoint_covariance...\n        applys disjoint_symm.\n        apply disjoint_symm in H10.\n        applys disjoint_covariance... }\n      { applys IS_and... eauto. }\n    + forwards~: IHP1 e. applys Typ_app...\n      forwards~: IHP2 e. applys Typ_app... destruct_conj.\n      exists. split.\n      { applys Typ_mergev...\n        applys papp_consistent P1 P2... }\n      econstructor; eauto.\nQed.\n\n\nLemma papp_preservation2 : forall v l e A,\n    value v ->\n    Typing nil nil (e_proj v l) Inf A ->\n    papp v (arg_la l) e ->\n    exists A', Typing nil nil e Inf A' /\\ subsub A' A.\nProof with try eassumption.\n  introv Val Typ P. gen A.\n  inductions P; intros; inverts Typ as Typ1 Typ2 Typ3; auto_unify.\n  - (* rcd *)\n    exists A0. split.\n    2: { econstructor; eauto. }\n         (* eapply TWell_appDist in H0. inverts H0. eassumption. eauto. } *)\n    forwards* Typ': Typing_chk_appDist H0.\n    inverts Typ'; solve_false.\n    econstructor...\n  - (* merge *)\n    inverts Val as Val1 Val2.\n    inverts Typ1; appdist_unify.\n    + forwards~: IHP1 l. applys Typ_proj...\n      forwards~: IHP2 l. applys Typ_proj... destruct_conj.\n      exists. split.\n      { applys Typ_merge...\n        forwards: appDist_rcd_disjoint H3 H7...\n        forwards (_&?): disjoint_regular H8.\n        forwards~ (?&?): subsub2sub H2; auto.\n        forwards~ (?&?): subsub2sub H6; auto.\n        applys disjoint_covariance...\n        applys disjoint_symm.\n        apply disjoint_symm in H8.\n        applys disjoint_covariance... }\n      { applys IS_and... eauto. }\n    + forwards~: IHP1 l. applys Typ_proj...\n      forwards~: IHP2 l. applys Typ_proj... destruct_conj.\n      exists. split.\n      { applys Typ_mergev...\n        applys papp_consistent2 P1 P2... }\n      econstructor; eauto.\nQed.\n\n\nLemma papp_preservation3 : forall v T e A,\n    value v ->\n    Typing nil nil (e_tapp v T) Inf A ->\n    papp v (arg_typ T) e ->\n    TWell [] T ->\n    exists A', Typing nil nil e Inf A' /\\ subsub A' A.\nProof with try eassumption.\n  introv Val Typ P TW. gen A.\n  inductions P; intros; inverts Typ as Typ1 Typ2 Typ3; auto_unify.\n  - (* tabs *)\n    exists (C2 ^-^ T). split.\n    2: { econstructor; eauto.\n         eapply TWell_appDist in H1. 2: now eauto. inverts H1.\n         instantiate_cofinites.\n         rewrite_env (nil ++ x ~ C1 ++ nil) in H7.\n         forwards: TWell_subst TW H7.\n         simpls.\n         rewrites~ (@typsubst_typ_intro x). }\n    forwards* Typ': Typing_chk_appDist H5.\n    inverts Typ' as ? HT; solve_false.\n    econstructor.\n    instantiate_cofinites.\n    rewrite_env ([]++[(x,C1)]++[]) in HT.\n    forwards*: Typing_subst_1 HT.\n    simpls.\n    rewrites~ (@typsubst_typ_intro x).\n    rewrites* (@typsubst_exp_intro x).\n  - (* merge *)\n    inverts Val as Val1 Val2.\n    inverts Typ1. appdist_unify.\n      (* forwards (?&?): Typing_chk_inter_inv Typ3. *)\n    + forwards~: IHP1. applys Typ_tapp...\n      applys~ disjoint_covariance Typ3.\n      forwards~: IHP2. applys Typ_tapp...\n      applys~ disjoint_covariance Typ3.\n      destruct_conj.\n      exists. split.\n      { applys Typ_merge...\n        forwards: disjoint_appDist_forall_inv H3 H7...\n        forwards (_&?): disjoint_regular H8.\n        forwards (_&?): subsub2sub H6; auto; auto 1.\n        forwards (_&?): subsub2sub H2; auto; auto 1.\n        applys disjoint_covariance...\n        applys disjoint_symm.\n        apply disjoint_symm in H8.\n        applys disjoint_covariance... }\n      { applys IS_and... eauto. }\n    + appdist_unify.\n      forwards~: IHP1. applys Typ_tapp...\n      applys disjoint_covariance...\n      auto_sub.\n      forwards~: IHP2. applys Typ_tapp...\n      applys disjoint_covariance...\n      auto_sub.\n      destruct_conj.\n      exists. split.\n      { applys Typ_mergev...\n        applys~ (papp_consistent3 v1 v2 T e1 e2 A B0 B1 C0 B2 C3). }\n      econstructor; eauto.\nQed.\n\n\nInductive step_or_v : exp -> exp -> Prop :=\n| ST_v : forall v, value v -> step_or_v v v\n| ST_s : forall e1 e2, step e1 e2 -> step_or_v e1 e2.\n\n#[export]\nHint Constructors step_or_v : core.\n\n(* to prove the consistent merge case in preservation_subsub *)\n\nLemma consistent_steps: forall e1 e2 e1' e2' A B,\n    Typing [] [] e1 Inf A -> Typing [] [] e2 Inf B ->\n    step_or_v e1 e1' -> step_or_v e2 e2' -> consistent e1 e2 ->\n    ( forall (e e' : exp) (A : typ),\n        size_exp e < (size_exp e1 + size_exp e2) -> \n        Typing [] [] e Inf A -> step e e' -> \n        exists C, Typing [] [] e' Inf C /\\ subsub C A ) ->\n    consistent e1' e2'.\nProof with (simpl; elia).\n  introv Typ1 Typ2 ST1 ST2 Cons IH. gen e1' e2' A B.\n  induction Cons; intros; try solve [inverts ST1; inverts ST2; solve_false; eauto].\n  + inverts ST1 as ST1'; inverts ST2 as ST2'.\n    * constructor*.\n    * inverts ST1'; inverts ST2'; solve_false.\n    * inverts ST1'; inverts ST2'; solve_false.\n    * inverts ST1'; inverts ST2'; solve_false.\n      - inverts Typ1.\n        forwards~ (?&?&_): Typing_chk2inf H11.\n        applys* casting_consistent H6 H2.\n      - inverts Typ1. clear IH.\n        inductions H9; solve_false.\n          forwards~: IHTyping1.\n          forwards~: IHTyping2.\n          inverts~ H2; inverts~ H3.\n          ptype_unify.\n          applys* C_disjoint.\n        forwards: step_unique H6 H8. applys~ H9.\n        substs~.\n  + (* disjoint *)\n    inverts ST1 as ST1'; [unify_pType e1' | unify_pType u1];\n    inverts ST2 as ST2'.\n    - forwards: principal_type_checks H Typ1.\n      forwards: principal_type_checks H0 Typ2.\n      substs. applys* C_disjoint H H0.\n    - forwards* (C&?&?): IH u2.\n      forwards: size_exp_min e1'...\n      forwards: principal_type_checks H0 Typ2; substs.\n      forwards: Typing_regular_0 Typ2.\n      forwards~ (_&?): subsub2sub H6; auto.\n      forwards~: step_prv_prevalue ST2'.\n      applys* C_disjoint.\n      forwards: principal_type_checks H4 Typ1; substs.\n      forwards: principal_type_checks H Typ1; substs.\n      applys* disjoint_covariance.\n    - forwards* (C&?&?): IH u1.\n      forwards: size_exp_min e2'...\n      forwards: principal_type_checks H Typ1; substs.\n      forwards: Typing_regular_0 Typ1.\n      forwards~ (_&?): subsub2sub H6; auto.\n      forwards~: step_prv_prevalue ST1'.\n      applys* C_disjoint.\n      apply disjoint_symm in H1.\n      applys disjoint_symm.\n      applys* disjoint_covariance.\n    - forwards* (C&?&?): IH u2.\n      forwards: size_exp_min u1...\n      forwards: principal_type_checks H0 Typ2; substs.\n      forwards: Typing_regular_0 Typ2.\n      forwards~ (_&?): subsub2sub H6; auto.\n      forwards~: step_prv_prevalue ST2'.\n\n      forwards* (C'&?&?): IH u1.\n      forwards: size_exp_min u2...\n      forwards: principal_type_checks H Typ1; substs.\n      forwards: Typing_regular_0 Typ1.\n      forwards~ (_&?): subsub2sub H11; auto.\n      forwards~: step_prv_prevalue ST1'.\n      applys* C_disjoint.\n\n      assert (disjoint nil A0 C) by applys* disjoint_covariance.\n      apply disjoint_symm in H15.\n      applys disjoint_symm.\n      applys* disjoint_covariance.\n  + inverts ST1 as ST1'; [ | inverts ST1' as ST1_1 ST1_2 ]; inverts Typ1;\n    try solve [\n      forwards*: IHCons1; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia);\n      forwards*: IHCons2; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia)].\n  + inverts ST2 as ST2'; [ | inverts ST2' as ST2_1 ST2_2 ]; inverts Typ2;\n    try solve [\n      forwards*: IHCons1; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia);\n      forwards*: IHCons2; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia)]. \n  Unshelve. all: try apply nil; pick fresh x; apply x.\nQed.\n\nLtac indExpDirSize s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : dirflag |- _ ] => (gen h) end;\n  repeat match goal with | [ h : exp |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n      intros; match goal with | [ H : _ < 0 |- _ ] => inverts H end\n    | intros ].\n\nDefinition size_dir dir :=\n  match dir with\n  | Inf => 0\n  | Chk => 1\n  end.\n\nTheorem preservation_subsub : forall e e' dir A,\n    Typing nil nil e dir A ->\n    step e e' ->\n    exists C, Typing nil nil e' dir C /\\ subsub C A.\nProof with simpl; elia; eauto.\n  introv.\n  assert (Siz: exists n1 n2 n3, size_exp e < n1 /\\ size_dir dir < n2 /\\ size_typ A < n3).\n  { exists. splits*. }\n  destruct Siz as (n1 & n2 & n3 & Siz1 & Siz2 & Siz3).\n  gen n2 n3 e' e dir A.\n  induction n1; induction n2; induction n3; introv Siz1 Siz2 Siz3 Typ J; destruct_conj.\n  all: try match goal with\n           | H : _ < 0 |- _ => exfalso; inverts H\n           end.\n\n  inverts keep Typ as Ht1 Ht2 Ht3 Ht4 Ht5 Ht6;\n    try solve [inverts J]; repeat simpl in SizeInd.\n  - (* typing_app *)\n    inverts J as J1 J2 J3.\n    + forwards*: papp_preservation J2.\n    + forwards (?&?&S2): IHn1 Ht1 J2...\n      forwards: Typing_regular_0 H.\n      lets* ( ?&? & Harr & Hsubsub & Hsub ): appDist_arr_subsub Ht2.\n      exists x1. split~.\n      forwards*: Typing_chk_dup Ht3 Hsub.\n  - (* typing_tapp *)\n    inverts J as J1 J2 J3.\n    + forwards*: papp_preservation3 J2.\n    + forwards* (B' & HT & HS) : IHn1 Ht1 J2...\n      forwards: Typing_regular_0 HT.\n      forwards* (C1' & C2' & HAD & HSS  & HAS): appDist_forall_subsub_disjoint Ht2 HS.\n      exists (C2' ^-^ A0). splits~.\n      applys Typ_tapp. apply HT. apply HAD.\n      apply disjoint_covariance with C1. auto. auto.\n  - (* typing_proj *)\n    inverts J as J1 J2 J3.\n    + forwards*: papp_preservation2 J2.\n    + forwards* (?&?&S2): IHn1 Ht1 J1...\n      forwards: Typing_regular_0 H.\n      lets* ( ? & Harr & Hsub ): appDist_rcd_subsub Ht2 S2.\n  - (* typing_merge *)\n    (* disjoint *)\n    inverts J as J1 J2 J3.\n    + forwards (?&?&?): IHn1 Ht1 J1...\n      forwards (?&?&?): IHn1 Ht2 J2...\n      exists. splits. applys Typ_merge H H1.\n      forwards: Typing_regular_0 H.\n      forwards: Typing_regular_0 H1.\n      forwards~ (?&?): subsub2sub H0; auto.\n      forwards~ (?&?): subsub2sub H2; auto.\n      apply disjoint_covariance with B.\n      apply disjoint_symm.\n      apply disjoint_covariance with A0.\n      apply disjoint_symm. auto. auto. auto.\n      eauto.\n    + forwards (?&?&?): IHn1 Ht1 J2...\n      exists. splits. applys Typ_merge H Ht2.\n      forwards: Typing_regular_0 Ht1.\n      apply disjoint_symm.\n      apply disjoint_covariance with A0.\n      apply disjoint_symm. auto.\n      forwards~(?&?): subsub2sub H0. auto. eauto.\n    + forwards (?&?&?): IHn1 Ht2 J2...\n      exists. splits. applys Typ_merge Ht1 H.\n      forwards: Typing_regular_0 H.\n      apply disjoint_covariance with B.\n      auto.\n      forwards~(?&?): subsub2sub H0. auto. eauto.\n  - (* typing_inter *)\n    forwards (T1 &?&?): IHn3 Ht1...\n    forwards (T2 &?&?): IHn3 Ht2...\n    exists (T1&T2). split*.\n     - (* typing_anno *)\n    inverts J.\n    + forwards~ (?&?&?): Typing_chk2inf Ht1.\n      lets* (?&?): casting_preservation H.\n    + forwards* (?&?&?): IHn1 Ht1 H3...\n      exists A. split*.\n      forwards: Typing_regular_0 H.\n      forwards*: Typing_chk_subsub H H0.\n      (* check subsub or refine the lemma *)\n  - (* typing_fix *)\n    inverts J as Lc. pick_fresh x.\n    rewrite* (@subst_exp_intro x).\n    forwards~ Typ_chk: Ht1.\n    rewrite_env(nil++[(x,A)]++nil) in Typ_chk.\n    lets~ (HF&HT): Typing_subst_2_inf_subsub Typ_chk Typ.\n    clear HF. forwards~ : HT.\n    exists A. split*.\n  - (* typing_mergev *) (* consistent merge *)\n    inverts J as J1 J2 J3;\n    forwards: consistent_steps Ht4 Ht5; eauto;\n      try introv p1 p2 p3; try forwards~: IHn1 p2 p3...\n    1: forwards (?&?&?): IHn1 Ht4 J1...\n    1: forwards (?&?&?): IHn1 Ht5 J2; elia; auto.\n    2: forwards (?&?&?): IHn1 Ht4 J2; elia; auto.\n    3: forwards (?&?&?): IHn1 Ht5 J2; elia; auto.\n    all: exists; splits; [applys* Typ_mergev H | ]; eauto.\n  - (* subsumption *)\n    forwards* (?&?& HS): IHn2 Ht1...\n    forwards: Typing_regular_0 H.\n    forwards~ (?&?): subsub2sub HS; auto.\n    assert (algo_sub nil x A) by auto_sub.\n    exists* A.\nQed.\n\n\nTheorem preservation : forall e e' dir A,\n    Typing nil nil e dir A ->\n    step e e' ->\n    Typing nil nil e' Chk A.\nProof.\n  intros e e' dir A H H0.\n  lets* (?&?&?): preservation_subsub H H0.\n  destruct dir.\n  forwards: Typing_regular_0 H1.\n  - forwards~: subsub2sub H2; auto.\n    sapply* Typ_sub.\n  - sapply* Typing_chk_subsub.\nQed.\n\n(* Type Safety *)\n\nTheorem preservation_multi_step : forall e e' dir A,\n    Typing nil nil e dir A ->\n    e ->* e' ->\n    exists C, Typing nil nil e' dir C /\\ subsub C A.\nProof.\n  introv Typ Red.\n  gen A. inductions Red; intros.\n  - exists. splits; eauto using Typing_lc_typ.\n  - lets* (?&?&?): preservation_subsub Typ H.\n    forwards* (?&?&?): IHRed H0.\n    exists x0. split*.\n    forwards*: subsub_trans H3 H1.\nQed.\n\n\nTheorem type_safety : forall e e' A,\n    Typing nil nil e Inf A ->\n    e ->* e' ->\n    value e' \\/ exists e'', step e' e''.\nProof.\n  introv Typ Red. gen A.\n  induction Red; intros.\n  lets*: progress Typ.\n  lets* (?&?&?): preservation_subsub Typ H.\nQed.\n", "meta": {"author": "andongfan", "repo": "CP-Foundations", "sha": "d3ee6c916fccd7312d0f571f7d2be66ed9336ccc", "save_path": "github-repos/coq/andongfan-CP-Foundations", "path": "github-repos/coq/andongfan-CP-Foundations/CP-Foundations-d3ee6c916fccd7312d0f571f7d2be66ed9336ccc/fiplus/coq/TypeSafety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19656440062496058}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import Verdi.NameOverlay.\nRequire Import Verdi.TotalMapSimulations.\nRequire Import Verdi.PartialMapSimulations.\nRequire Import Verdi.PartialExtendedMapSimulations.\n\nRequire Import AggregationDefinitions.\nRequire Import AggregationAux.\nRequire Import AggregationDynamicCorrect.\nRequire Import TreeAux.\nRequire Import TreeDynamicCorrect.\nRequire Import TreeAggregationDynamic.\n\nRequire Import Sumbool.\nRequire Import Orders.\nRequire Import MSetFacts.\nRequire Import MSetProperties.\n\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.fintype.\nRequire Import mathcomp.ssreflect.finset.\nRequire Import mathcomp.fingroup.fingroup.\n\nRequire Import AAC_tactics.AAC.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nModule TreeAggregationCorrect (Import NT : NameType)  \n (NOT : NameOrderedType NT) (NSet : MSetInterface.S with Module E := NOT) \n (NOTC : NameOrderedTypeCompat NT) (NMap : FMapInterface.S with Module E := NOTC) \n (Import RNT : RootNameType NT) \n (Import CFG : CommutativeFinGroup) \n (Import ANT : AdjacentNameType NT) \n (Import TA : TAux NT NOT NSet NOTC NMap)\n (Import AD : ADefs NT NOT NSet NOTC NMap CFG).\n\nModule AGC := AggregationCorrect NT NOT NSet NOTC NMap CFG ANT AD.\nModule AG := AGC.AG.\n\nModule TRC := TreeCorrect NT NOT NSet NOTC NMap RNT ANT TA.\nModule TR := TRC.TR.\n\nModule AX := AAux NT NOT NSet NOTC NMap CFG ANT AD.\nImport AX.\n\nModule TG := TreeAggregation NT NOT NSet NOTC NMap RNT CFG ANT TA AD.\nImport TG.\n\nImport GroupScope.\n\nModule ADCFGAACInstances := CFGAACInstances CFG.\nImport ADCFGAACInstances.\n\nModule NSetFacts := Facts NSet.\nModule NSetProps := Properties NSet.\nModule NSetOrdProps := OrdProperties NSet.\n\nRequire Import FMapFacts.\nModule NMapFacts := Facts NMap.\n\nInstance TreeAggregation_Aggregation_name_tot_map : MultiParamsNameTotalMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    tot_map_name := id ;\n    tot_map_name_inv := id ;\n  }.\n\nInstance TreeAggregation_Aggregation_name_tot_map_bijective : MultiParamsNameTotalMapBijective TreeAggregation_Aggregation_name_tot_map :=\n  {\n    tot_map_name_inv_inverse := fun _ => Logic.eq_refl ;\n    tot_map_name_inverse_inv := fun _ => Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Aggregation_params_pt_msg_map : MultiParamsMsgPartialMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    pt_map_msg := fun m =>\n      match m with\n      | Aggregate m' => Some (AG.Aggregate m')\n      | Fail => Some AG.Fail\n      | New  => Some AG.New\n      | Level _ => None\n      end    \n  }.\n\nInstance TreeAggregation_Aggregation_params_pt_ext_map : MultiParamsPartialExtendedMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    pt_ext_map_data := fun d _ =>\n      AG.mkData d.(local) d.(aggregate) d.(adjacent) d.(balance) ;\n    pt_ext_map_input := fun i n d =>\n      match i with\n      | Local m => Some (AG.Local m)\n      | SendAggregate =>\n        if root_dec n then None else\n          match parent d.(adjacent) d.(levels) with\n          | Some p => Some (AG.SendAggregate p)\n          | None => None\n          end\n      | AggregateRequest client_id => Some (AG.AggregateRequest client_id)\n      | _ => None\n      end\n  }.\n\nLemma pt_ext_map_name_msgs_level_adjacent_empty :\n  forall fs lvo,\n  filterMap pt_map_name_msg (level_adjacent lvo fs) = [].\nProof.\nmove => fs lvo.\nrewrite /level_adjacent NSet.fold_spec.\nelim: NSet.elements => //=.\nmove => n ns IH.\nrewrite {2}/level_fold /=.\nrewrite (@fold_left_level_fold_eq TreeAggregation_TreeMsg) /=.\nby rewrite filterMap_app /= -app_nil_end IH.\nQed.\n\nInstance TreeAggregation_Aggregation_multi_params_pt_ext_map_congruency : MultiParamsPartialExtendedMapCongruency TreeAggregation_Aggregation_name_tot_map TreeAggregation_Aggregation_params_pt_msg_map TreeAggregation_Aggregation_params_pt_ext_map :=\n  {\n    pt_ext_init_handlers_eq := _ ;\n    pt_ext_net_handlers_some := _ ;\n    pt_ext_net_handlers_none := _ ;\n    pt_ext_input_handlers_some := _ ;\n    pt_ext_input_handlers_none := _\n  }.\nProof.\n- by move => n; rewrite /= /InitData /=.\n- move => me src mg st mg' out st' ps H_eq H_eq'.\n  rewrite /pt_ext_mapped_net_handlers.\n  repeat break_let.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  rewrite /= /runGenHandler_ignore /= in Heqp.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, u0.\n  unfold id in *.\n  destruct st'.\n  by net_handler_cases; AG.net_handler_cases; simpl in *; congruence.\n- move => me src mg st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u.\n  destruct st'.\n  by net_handler_cases; simpl in *; congruence.\n- move => me inp st inp' out st' ps H_eq H_eq'.\n  rewrite /pt_ext_mapped_input_handlers.\n  repeat break_let.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  rewrite /= /runGenHandler_ignore /= in Heqp.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, u0.\n  unfold id in *.\n  have H_eq_inp: inp = SendAggregate \\/ inp <> SendAggregate by destruct inp; (try by right); left.\n  case: H_eq_inp => H_eq_inp.\n    subst_max.\n    rewrite /= in H_eq.\n    move: H_eq.\n    case H_p: (parent st.(adjacent) st.(levels)) => [dst|].\n      have H_p' := H_p.\n      rewrite /parent in H_p'.\n      break_match_hyp => //.\n      destruct s.\n      simpl in *.\n      find_injection.\n      inversion m0.\n      inversion H.\n      destruct st'.\n      io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; unfold id in *; try congruence.\n      move: Heqb.\n      by case root_dec.\n    by io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; congruence.\n  destruct st'.\n  simpl in *.\n  by io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; congruence.\n- move => me inp st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u.\n  destruct st'.\n  io_handler_cases; simpl in *; unfold is_left in *; repeat break_if; try break_match; try congruence.\n  by rewrite pt_ext_map_name_msgs_level_adjacent_empty.\nQed.\n\nInstance TreeAggregation_Aggregation_fail_msg_params_pt_ext_map_congruency : FailMsgParamsPartialMapCongruency TreeAggregation_FailMsgParams AG.Aggregation_FailMsgParams TreeAggregation_Aggregation_params_pt_msg_map := \n  {\n    pt_fail_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Aggregation_new_msg_params_pt_ext_map_congruency : NewMsgParamsPartialMapCongruency TreeAggregation_NewMsgParams AG.Aggregation_NewMsgParams TreeAggregation_Aggregation_params_pt_msg_map := \n  {\n    pt_new_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Aggregation_name_overlay_params_tot_map_congruency : NameOverlayParamsTotalMapCongruency TreeAggregation_NameOverlayParams AG.Aggregation_NameOverlayParams TreeAggregation_Aggregation_name_tot_map := \n  {\n    tot_adjacent_to_fst_snd := fun _ _ => conj (fun H => H) (fun H => H)\n  }.\n\nTheorem TreeAggregation_Aggregation_pt_ext_mapped_simulation_star_1 :\nforall net failed tr,\n    @step_ordered_dynamic_failure_star _ _ TreeAggregation_NameOverlayParams TreeAggregation_NewMsgParams TreeAggregation_FailMsgParams step_ordered_dynamic_failure_init (failed, net) tr ->\n    exists tr', @step_ordered_dynamic_failure_star _ _ AG.Aggregation_NameOverlayParams AG.Aggregation_NewMsgParams AG.Aggregation_FailMsgParams step_ordered_dynamic_failure_init (failed, pt_ext_map_odnet net) tr'.\nProof.\nmove => net failed tr H_st.\napply step_ordered_dynamic_failure_pt_ext_mapped_simulation_star_1 in H_st.\nmove: H_st => [tr' H_st].\nrewrite map_id in H_st.\nby exists tr'.\nQed.\n\nInstance AggregationData_Data : AggregationData Data :=\n  {\n    aggr_local := local ;\n    aggr_aggregate := aggregate ;\n    aggr_adjacent := adjacent ;\n    aggr_balance := balance\n  }.\n\nInstance AggregationMsg_TreeAggregation : AggregationMsg :=\n  {\n    aggr_msg := msg ;\n    aggr_msg_eq_dec := msg_eq_dec ;\n    aggr_fail := Fail ;\n    aggr_of := fun mg => match mg with | Aggregate m' => m' | _ => 1 end\n  }.\n\nInstance AggregationMsgMap_Aggregation_TreeAggregation : AggregationMsgMap AggregationMsg_TreeAggregation AGC.AggregationMsg_Aggregation :=\n  {\n    map_msgs := filterMap pt_map_msg ;\n    sum_aggregate_msg_map_msgs_eq := _ ;\n    aggr_fail_in_in := _;\n  }.\nProof.\n- elim => //=.\n  case => [m'||olv|] ms IH /=.\n  * by rewrite /aggregate_sum_fold /= IH.\n  * by rewrite /aggregate_sum_fold /= IH.\n  * by rewrite /aggregate_sum_fold /= IH; gsimpl.\n  * by rewrite /aggregate_sum_fold /= IH.\n- elim => //=.\n  case => [m'||olv|] ms IH /=.\n  * by split => H_in; case: H_in => H_in //; right; apply IH.\n  * by split => H_in; left.\n  * split => H_in; last by right; apply IH.\n    case: H_in => H_in //.\n    by apply IH.\n  * by split => H_in; case: H_in => H_in //; right; apply IH.\nDefined.\n\nLemma TreeAggregation_conserves_network_mass :\n  forall net failed tr,\n  step_ordered_dynamic_failure_star step_ordered_dynamic_failure_init (failed, net) tr ->\n  conserves_network_mass_opt (remove_all name_eq_dec failed net.(odnwNodes)) net.(odnwNodes) net.(odnwPackets) net.(odnwState).\nProof.\nmove => net failed tr H_st.\nhave [tr' H_st'] := TreeAggregation_Aggregation_pt_ext_mapped_simulation_star_1 H_st.\nhave H_inv := AGC.Aggregation_conserves_network_mass H_st'.\nrewrite /= /id /= /conserves_network_mass_opt in H_inv.\nrewrite /conserves_network_mass_opt.\nmove: H_inv.\nrewrite (sum_local_opt_aggr_local_eq _ (odnwState net)) map_id /=.\n- move => H_inv.\n  rewrite H_inv {H_inv}.\n  rewrite (sum_aggregate_opt_aggr_aggregate_eq _ (odnwState net)) /=.\n  * rewrite sum_aggregate_msg_incoming_active_map_msgs_eq /map_msgs /=.\n    set state := fun n : name => match _ with _ => _ end.\n    rewrite (sum_fail_balance_incoming_active_opt_map_msgs_eq _ state) // /state.\n    + by move => n H_in; break_match.\n    + move => n H_in d.\n      break_match => //= H_eq d1 H_eq'.\n      by repeat find_injection.\n    + move => n H_in d.\n      break_match => //= H_eq d1 H_eq'.\n      by repeat find_injection.\n  * by move => n H_in; break_match.\n  * move => n H_in d.\n    break_match => //= H_eq d1 H_eq'.\n    by repeat find_injection.\n- by move => n H_in; break_match.\n- move => n H_in d.\n  break_match => //= H_eq d1 H_eq'.\n  by repeat find_injection.\nQed.\n\nInstance TreeAggregation_Tree_base_params_pt_map : BaseParamsPartialMap TreeAggregation_BaseParams TR.Tree_BaseParams :=\n  {\n    pt_map_data := fun d => TR.mkData d.(adjacent) d.(broadcast) d.(levels) ;\n    pt_map_input := fun i =>\n                   match i with\n                   | LevelRequest client_id => Some (TR.LevelRequest client_id)\n                   | Broadcast => Some TR.Broadcast\n                   | _ => None\n                   end ;\n    pt_map_output := fun o =>\n                    match o with\n                    | LevelResponse client_id olv => Some (TR.LevelResponse client_id olv)\n                    | _ => None\n                    end\n  }.\n\nInstance TreeAggregation_Tree_name_tot_map : MultiParamsNameTotalMap TreeAggregation_MultiParams TR.Tree_MultiParams :=\n  {\n    tot_map_name := id ;\n    tot_map_name_inv := id ;\n  }.\n\nInstance TreeAggregation_Tree_name_tot_map_bijective : MultiParamsNameTotalMapBijective TreeAggregation_Tree_name_tot_map :=\n  {\n    tot_map_name_inv_inverse := fun _ => Logic.eq_refl ;\n    tot_map_name_inverse_inv := fun _ => Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Tree_multi_params_pt_map : MultiParamsMsgPartialMap TreeAggregation_MultiParams TR.Tree_MultiParams :=\n  {\n    pt_map_msg := fun m => match m with\n                        | Fail => Some TR.Fail\n                        | New => Some TR.New\n                        | Level lvo => Some (TR.Level lvo)\n                        | _ => None\n                        end ;\n  }.\n\nInstance TreeAggregation_Tree_multi_params_pt_map_congruency : MultiParamsPartialMapCongruency TreeAggregation_Tree_base_params_pt_map TreeAggregation_Tree_name_tot_map TreeAggregation_Tree_multi_params_pt_map :=\n  {\n    pt_init_handlers_eq := fun  _ => Logic.eq_refl ;\n    pt_net_handlers_some := _ ;\n    pt_net_handlers_none := _ ;\n    pt_input_handlers_some := _ ;\n    pt_input_handlers_none := _\n  }.\nProof.\n- move => me src mg st mg' H_eq.\n  rewrite /pt_mapped_net_handlers.\n  repeat break_let.\n  case H_n: net_handlers => [[out st'] ps].\n  rewrite /= /runGenHandler_ignore /= in Heqp H_n.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, u0.\n  destruct st'.\n  by net_handler_cases; TR.net_handler_cases; simpl in *; unfold id in *; congruence.\n- move => me src mg st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, st'.\n  by net_handler_cases; simpl in *; congruence.\n- move => me inp st inp' H_eq.\n  rewrite /pt_mapped_input_handlers.\n  repeat break_let.\n  case H_i: input_handlers => [[out st'] ps].\n  rewrite /= /runGenHandler_ignore /= in Heqp H_i.\n  repeat break_let.\n  repeat tuple_inversion.\n  unfold id in *.\n  destruct u, u0, st, st'.\n  io_handler_cases; TR.io_handler_cases; simpl in *; try congruence.\n  set ptl := filterMap _ _.\n  set ptl' := level_adjacent _ _.\n  suff H_suff: ptl = ptl' by repeat find_rewrite.\n  rewrite /ptl /ptl' /level_adjacent 2!NSet.fold_spec.\n  elim: NSet.elements => //=.\n  move => n ns IH.\n  rewrite (@fold_left_level_fold_eq TreeAggregation_TreeMsg) filterMap_app /= /id /=.\n  by rewrite (@fold_left_level_fold_eq TR.Tree_TreeMsg) /= IH.\n- move => me inp st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, st'.\n  by io_handler_cases; simpl in *; congruence.\nQed.\n\nInstance TreeAggregation_Tree_fail_msg_params_pt_map_congruency : FailMsgParamsPartialMapCongruency TreeAggregation_FailMsgParams TR.Tree_FailMsgParams TreeAggregation_Tree_multi_params_pt_map := \n  {\n    pt_fail_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Tree_new_msg_params_pt_map_congruency : NewMsgParamsPartialMapCongruency TreeAggregation_NewMsgParams TR.Tree_NewMsgParams TreeAggregation_Tree_multi_params_pt_map := \n  {\n    pt_new_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Tree_name_overlay_params_tot_map_congruency : NameOverlayParamsTotalMapCongruency TreeAggregation_NameOverlayParams TR.Tree_NameOverlayParams TreeAggregation_Tree_name_tot_map := \n  {\n    tot_adjacent_to_fst_snd := fun _ _ => conj (fun H => H) (fun H => H)\n  }.\n\nTheorem TreeAggregation_Tree_pt_mapped_simulation_star_1 :\nforall net failed tr,\n    @step_ordered_dynamic_failure_star _ _ TreeAggregation_NameOverlayParams TreeAggregation_NewMsgParams TreeAggregation_FailMsgParams step_ordered_dynamic_failure_init (failed, net) tr ->\n    @step_ordered_dynamic_failure_star _ _ TR.Tree_NameOverlayParams TR.Tree_NewMsgParams TR.Tree_FailMsgParams step_ordered_dynamic_failure_init (failed, pt_map_odnet net) (filterMap pt_map_trace_ev tr).\nProof.\nmove => net failed tr H_st.\napply step_ordered_dynamic_failure_pt_mapped_simulation_star_1 in H_st.\nby rewrite map_id in H_st.\nQed.\n\nEnd TreeAggregationCorrect.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/systems/TreeAggregationDynamicCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19652527326771715}}
{"text": "Require Import DirCache.\nRequire Import Balloc.\nRequire Import Prog ProgMonad.\nRequire Import BasicProg.\nRequire Import Bool.\nRequire Import Word.\nRequire Import BFile Bytes Rec Inode.\nRequire Import String.\nRequire Import FSLayout.\nRequire Import Pred.\nRequire Import Arith.\nRequire Import GenSepN.\nRequire Import List ListUtils.\nRequire Import Hoare.\nRequire Import Log.\nRequire Import SepAuto.\nRequire Import Array.\nRequire Import FunctionalExtensionality.\nRequire Import AsyncDisk.\nRequire Import DiskSet.\nRequire Import GenSepAuto.\nRequire Import Lock.\nRequire Import Errno.\nImport ListNotations.\nRequire Import DirTreePath.\nRequire Import DirTreeDef.\nRequire Import DirTreePred.\nRequire Import DirTreeRep.\nRequire Import DirTreeSafe.\nRequire Import DirTreeNames.\nRequire Import DirTreeInodes.\n\nSet Implicit Arguments.\n\nModule SDIR := CacheOneDir.\n\nModule DIRTREE.\n\n\n  (* Programs *)\n\n  Notation MSLL := BFILE.MSLL.\n  Notation MSAlloc := BFILE.MSAlloc.\n  Notation MSAllocC := BFILE.MSAllocC.\n  Notation MSIAllocC := BFILE.MSIAllocC.\n  Notation MSICache := BFILE.MSICache.\n  Notation MSCache := BFILE.MSCache.\n  Notation MSDBlocks := BFILE.MSDBlocks.\n\n\n  Definition namei fsxp dnum (fnlist : list string) mscs :=\n    let '(lxp, bxp, ibxp, ixp) := ((FSXPLog fsxp), (FSXPBlockAlloc fsxp),\n                                   fsxp, (FSXPInode fsxp)) in\n    let^ (mscs, inum, isdir, valid) <- ForEach fn fnrest fnlist\n      Hashmap hm\n      Ghost [ mbase m sm F Fm IFs Ftop treetop freeinodes freeinode_pred ilist freeblocks mscs0 ]\n      Loopvar [ mscs inum isdir valid ]\n      Invariant\n        LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n        exists tree bflist fndone,\n        [[ fndone ++ fnrest = fnlist ]] *\n        [[ valid = OK tt ->\n           (Ftop * tree_pred_except ibxp fndone treetop * tree_pred ibxp tree * freeinode_pred)%pred (list2nmem bflist) ]] *\n        [[ isError valid ->\n           (Ftop * tree_pred ibxp treetop * freeinode_pred)%pred (list2nmem bflist) ]] *\n        [[ (Fm * BFILE.rep bxp IFs ixp bflist ilist freeblocks (MSAllocC mscs) (MSCache mscs) (MSICache mscs) (MSDBlocks mscs) *\n            IAlloc.rep BFILE.freepred ibxp freeinodes freeinode_pred (IAlloc.mk_memstate (MSLL mscs) (MSIAllocC mscs)))%pred\n           (list2nmem m) ]] *\n        [[ dnum = dirtree_inum treetop ]] *\n        [[ valid = OK tt -> inum = dirtree_inum tree ]] *\n        [[ valid = OK tt -> isdir = dirtree_isdir tree ]] *\n        [[ valid = OK tt -> find_subtree fnlist treetop = find_subtree fnrest tree ]] *\n        [[ valid = OK tt -> find_subtree fndone treetop = Some tree ]] *\n        [[ isError valid -> find_subtree fnlist treetop = None ]] *\n        [[ MSAlloc mscs = MSAlloc mscs0 ]] *\n        [[ MSAllocC mscs = MSAllocC mscs0 ]] *\n        [[ MSDBlocks mscs = MSDBlocks mscs0 ]]\n      OnCrash\n        LOG.intact fsxp.(FSXPLog) F mbase sm hm\n      Begin\n        match valid with\n        | Err e =>\n          Ret ^(mscs, inum, isdir, Err e)\n        | OK _ =>\n          If (bool_dec isdir true) {\n            let^ (mscs, r) <- SDIR.lookup lxp ixp inum fn mscs;\n            match r with\n            | Some (inum, isdir) => Ret ^(mscs, inum, isdir, OK tt)\n            | None => Ret ^(mscs, inum, isdir, Err ENOENT)\n            end\n          } else {\n            Ret ^(mscs, inum, isdir, Err ENOTDIR)\n          }\n        end\n    Rof ^(mscs, dnum, true, OK tt);\n    match valid with\n    | OK _ =>\n      Ret ^(mscs, OK (inum, isdir))\n    | Err e =>\n      Ret ^(mscs, Err e)\n    end.\n\n  Definition mkfile fsxp dnum name fms :=\n    let '(lxp, bxp, ibxp, ixp) := ((FSXPLog fsxp), (FSXPBlockAlloc fsxp),\n                                   fsxp, (FSXPInode fsxp)) in\n    let '(al, alc, ialc, ms, icache, cache, dbcache) := (MSAlloc fms, MSAllocC fms, MSIAllocC fms, MSLL fms, MSICache fms, MSCache fms, MSDBlocks fms) in\n    let^ (ms, oi) <- IAlloc.alloc lxp ibxp (IAlloc.mk_memstate ms ialc);\n    let fms := BFILE.mk_memstate al (IAlloc.MSLog ms) alc (IAlloc.MSCache ms) icache cache dbcache in\n    match oi with\n    | None => Ret ^(fms, Err ENOSPCINODE)\n    | Some inum =>\n      let^ (fms, ok) <- SDIR.link lxp bxp ixp dnum name inum false fms;\n      match ok with\n      | OK _ =>\n        Ret ^(fms, OK (inum : addr))\n      | Err e =>\n        Ret ^(fms, Err e)\n      end\n    end.\n\n\n  Definition mkdir fsxp dnum name fms :=\n    let '(lxp, bxp, ibxp, ixp) := ((FSXPLog fsxp), (FSXPBlockAlloc fsxp),\n                                   fsxp, (FSXPInode fsxp)) in\n    let '(al, alc, ialc, ms, icache, cache, dbcache) := (MSAlloc fms, MSAllocC fms, MSIAllocC fms, MSLL fms, MSICache fms, MSCache fms, MSDBlocks fms) in\n    let^ (ms, oi) <- IAlloc.alloc lxp ibxp (IAlloc.mk_memstate ms ialc);\n    let fms := BFILE.mk_memstate al (IAlloc.MSLog ms) alc (IAlloc.MSCache ms) icache cache dbcache in\n    match oi with\n    | None => Ret ^(fms, Err ENOSPCINODE)\n    | Some inum =>\n      let^ (fms, ok) <- SDIR.link lxp bxp ixp dnum name inum true fms;\n      match ok with\n      | OK _ =>\n        Ret ^(fms, OK (inum : addr))\n      | Err e =>\n        Ret ^(fms, Err e)\n      end\n    end.\n\n\n  Definition delete fsxp dnum name mscs :=\n    let '(lxp, bxp, ibxp, ixp) := ((FSXPLog fsxp), (FSXPBlockAlloc fsxp),\n                                   fsxp, (FSXPInode fsxp)) in\n    let^ (mscs, oi) <- SDIR.lookup lxp ixp dnum name mscs;\n    match oi with\n    | None => Ret ^(mscs, Err ENOENT)\n    | Some (inum, isdir) =>\n      let^ (mscs, ok) <- If (bool_dec isdir false) {\n        Ret ^(mscs, true)\n      } else {\n        let^ (mscs, l) <- SDIR.readdir lxp ixp inum mscs;\n        match l with\n        | nil => Ret ^(mscs, true)\n        | _ => Ret ^(mscs, false)\n        end\n      };\n      If (bool_dec ok false) {\n        Ret ^(mscs, Err ENOTEMPTY)\n      } else {\n        let^ (mscs, ok) <- SDIR.unlink lxp ixp dnum name mscs;\n        match ok with\n        | OK _ =>\n          mscs <- BFILE.reset lxp bxp ixp inum mscs;\n          mscs' <- IAlloc.free lxp ibxp inum (IAlloc.mk_memstate (MSLL mscs) (MSIAllocC mscs));\n          Ret ^(BFILE.mk_memstate (MSAlloc mscs) (IAlloc.MSLog mscs') (MSAllocC mscs) (IAlloc.MSCache mscs') (MSICache mscs) (MSCache mscs) (MSDBlocks mscs), OK tt)\n        | Err e =>\n          Ret ^(mscs, Err e)\n        end\n     }\n    end.\n\n  Definition rename fsxp dnum srcpath srcname dstpath dstname mscs :=\n    let '(lxp, bxp, ibxp, ixp) := ((FSXPLog fsxp), (FSXPBlockAlloc fsxp),\n                                   fsxp, (FSXPInode fsxp)) in\n    let^ (mscs, osrcdir) <- namei fsxp dnum srcpath mscs;\n    match osrcdir with\n    | Err _ => Ret ^(mscs, Err ENOENT)\n    | OK (_, false) => Ret ^(mscs, Err ENOTDIR)\n    | OK (dsrc, true) =>\n      let^ (mscs, osrc) <- SDIR.lookup lxp ixp dsrc srcname mscs;\n      match osrc with\n      | None => Ret ^(mscs, Err ENOENT)\n      | Some (inum, inum_isdir) =>\n        let^ (mscs, _) <- SDIR.unlink lxp ixp dsrc srcname mscs;\n        let^ (mscs, odstdir) <- namei fsxp dnum dstpath mscs;\n        match odstdir with\n        | Err _ => Ret ^(mscs, Err ENOENT)\n        | OK (_, false) => Ret ^(mscs, Err ENOTDIR)\n        | OK (ddst, true) =>\n          let^ (mscs, odst) <- SDIR.lookup lxp ixp ddst dstname mscs;\n          match odst with\n          | None =>\n            let^ (mscs, ok) <- SDIR.link lxp bxp ixp ddst dstname inum inum_isdir mscs;\n            Ret ^(mscs, ok)\n          | Some _ =>\n            let^ (mscs, ok) <- delete fsxp ddst dstname mscs;\n            match ok with\n            | OK _ =>\n              let^ (mscs, ok) <- SDIR.link lxp bxp ixp ddst dstname inum inum_isdir mscs;\n              Ret ^(mscs, ok)\n            | Err e =>\n              Ret ^(mscs, Err e)\n            end\n          end\n        end\n      end\n    end.\n\n  Definition read fsxp inum off mscs :=\n    let^ (mscs, v) <- BFILE.read (FSXPLog fsxp) (FSXPInode fsxp) inum off mscs;\n    Ret ^(mscs, v).\n\n  Definition write fsxp inum off v mscs :=\n    mscs <- BFILE.write (FSXPLog fsxp) (FSXPInode fsxp) inum off v mscs;\n    Ret mscs.\n\n  Definition dwrite fsxp inum off v mscs :=\n    mscs <- BFILE.dwrite (FSXPLog fsxp) (FSXPInode fsxp) inum off v mscs;\n    Ret mscs.\n\n  Definition datasync fsxp inum mscs :=\n    mscs <- BFILE.datasync (FSXPLog fsxp) (FSXPInode fsxp) inum mscs;\n    Ret mscs.\n\n  Definition sync fsxp mscs :=\n    mscs <- BFILE.sync (FSXPLog fsxp) (FSXPInode fsxp) mscs;\n    Ret mscs.\n\n  Definition sync_noop fsxp mscs :=\n    mscs <- BFILE.sync_noop (FSXPLog fsxp) (FSXPInode fsxp) mscs;\n    Ret mscs.\n\n  Definition truncate fsxp inum nblocks mscs :=\n    let^ (mscs, ok) <- BFILE.truncate (FSXPLog fsxp) (FSXPBlockAlloc fsxp) (FSXPInode fsxp)\n                                     inum nblocks mscs;\n    Ret ^(mscs, ok).\n\n  Definition getlen fsxp inum mscs :=\n    let^ (mscs, len) <- BFILE.getlen (FSXPLog fsxp) (FSXPInode fsxp) inum mscs;\n    Ret ^(mscs, len).\n\n  Definition getattr fsxp inum mscs :=\n    let^ (mscs, attr) <- BFILE.getattrs (FSXPLog fsxp) (FSXPInode fsxp) inum mscs;\n    Ret ^(mscs, attr).\n\n  Definition setattr fsxp inum attr mscs :=\n    mscs <- BFILE.setattrs (FSXPLog fsxp) (FSXPInode fsxp) inum attr mscs;\n    Ret mscs.\n\n  Definition updattr fsxp inum kv mscs :=\n    mscs <- BFILE.updattr (FSXPLog fsxp) (FSXPInode fsxp) inum kv mscs;\n    Ret mscs.\n\n  (* Specs and proofs *)\n\n  Local Hint Unfold SDIR.rep_macro rep : hoare_unfold.\n\n  Theorem namei_ok : forall fsxp dnum fnlist mscs,\n    {< F mbase m sm Fm Ftop tree ilist freeblocks,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist freeblocks mscs sm)%pred (list2nmem m) ]] *\n           [[ dnum = dirtree_inum tree ]] *\n           [[ dirtree_isdir tree = true ]]\n    POST:hm' RET:^(mscs',r)\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs') sm hm' *\n           [[ (Fm * rep fsxp Ftop tree ilist freeblocks mscs' sm)%pred (list2nmem m) ]] *\n           [[ (isError r /\\ None = find_name fnlist tree) \\/\n              (exists v, (r = OK v /\\ Some v = find_name fnlist tree))%type ]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]]\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} namei fsxp dnum fnlist mscs.\n  Proof.\n    unfold namei.\n    step.\n\n    (* Prove loop entry: fndone = nil *)\n    rewrite app_nil_l; eauto.\n    pred_apply; cancel.\n    reflexivity.\n\n    assert (tree_names_distinct tree).\n    eapply rep_tree_names_distinct with (m := list2nmem m).\n    pred_apply. unfold rep. cancel.\n\n    (* Lock up the initial memory description, because our memory stays the\n     * same, and without this lock-up, we end up with several distinct facts\n     * about the same memory.\n     *)\n\n    all: denote! (_ (list2nmem m)) as Hm0; rewrite <- locked_eq in Hm0.\n\n    destruct_branch.\n    step.\n\n    (* isdir = true *)\n    destruct tree0; simpl in *; subst; intuition.\n    step.\n    denote (tree_dir_names_pred) as Hx.\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    safestep; eauto.\n\n    (* Lock up another copy of a predicate about our running memory. *)\n    denote! (_ (list2nmem m)) as Hm1; rewrite <- locked_eq in Hm1.\n    denote (dirlist_pred) as Hx; assert (Horig := Hx).\n    destruct_branch.\n\n    (* dslookup = Some _: extract subtree before [cancel] *)\n    prestep.\n    norml; unfold stars; simpl; inv_option_eq; msalloc_eq.\n    destruct a2.\n\n    (* subtree is a directory *)\n    rewrite tree_dir_extract_subdir in Hx by eauto; destruct_lift Hx.\n    norm. cancel. intuition simpl.\n    rewrite cons_app. rewrite app_assoc. reflexivity.\n\n    3: pred_apply; cancel.\n    pred_apply; cancel.\n    eapply pimpl_trans; [ eapply pimpl_trans | ].\n    2: eapply subtree_absorb with\n          (xp := fsxp) (fnlist := fndone) (tree := tree)\n          (subtree := TreeDir n l0) (subtree' := TreeDir n l0); eauto.\n    simpl; unfold tree_dir_names_pred; cancel; eauto.\n\n    rewrite update_subtree_same; eauto.\n\n    eapply pimpl_trans.\n    eapply subtree_extract with\n          (xp := fsxp) (fnlist := fndone ++ [elem])\n          (subtree := TreeDir a1 dummy5).\n\n    erewrite find_subtree_app by eauto.\n    eauto.\n    reflexivity.\n\n    pred_apply; cancel.\n\n    auto. auto.\n    rewrite cons_app. rewrite app_assoc.\n    erewrite find_subtree_app. reflexivity.\n    erewrite find_subtree_app by eauto. eauto.\n    erewrite find_subtree_app by eauto. eauto.\n    eauto.\n\n    (* subtree is a file *)\n    rewrite tree_dir_extract_file in Hx by eauto. destruct_lift Hx.\n    norm; unfold stars; simpl. cancel.\n    intuition idtac.\n    rewrite cons_app. rewrite app_assoc. reflexivity.\n    3: pred_apply; cancel.\n    pred_apply; cancel.\n    eassign (TreeFile a1 dummy5).\n    3: auto. 3: auto.\n\n    eapply pimpl_trans; [ eapply pimpl_trans | ].\n    2: eapply subtree_absorb with\n          (xp := fsxp) (fnlist := fndone) (tree := tree)\n          (subtree := TreeDir n l0) (subtree' := TreeDir n l0); eauto.\n    simpl; unfold tree_dir_names_pred; cancel; eauto.\n\n    rewrite update_subtree_same; eauto.\n\n    eapply pimpl_trans.\n    eapply subtree_extract with\n          (xp := fsxp) (fnlist := fndone ++ [elem])\n          (subtree := TreeFile a1 dummy5).\n\n    erewrite find_subtree_app by eauto.\n    eauto.\n    reflexivity.\n\n    pred_apply; cancel.\n\n    rewrite cons_app. rewrite app_assoc.\n    erewrite find_subtree_app. reflexivity.\n\n    erewrite find_subtree_app by eauto. eauto.\n    erewrite find_subtree_app by eauto. eauto.\n    eauto.\n\n    (* dslookup = None *)\n    prestep. norm; msalloc_eq. cancel. intuition idtac.\n    all: try solve [ exfalso; congruence ].\n    rewrite cons_app. rewrite app_assoc. reflexivity.\n    2: pred_apply; cancel.\n    pred_apply; cancel.\n\n    eapply pimpl_trans; [ | eapply pimpl_trans ].\n    2: eapply subtree_absorb with (xp := fsxp) (fnlist := fndone) (tree := tree) (subtree' := TreeDir n l0).\n    cancel. unfold tree_dir_names_pred. cancel; eauto.\n    eauto. eauto. eauto.\n\n    rewrite update_subtree_same by eauto. cancel.\n    erewrite <- find_subtree_none; eauto.\n    eauto.\n    cancel.\n\n    prestep. norm; msalloc_eq. cancel. intuition idtac.\n    rewrite cons_app. rewrite app_assoc. reflexivity.\n    all: try solve [ exfalso; congruence ].\n    2: pred_apply; cancel.\n    pred_apply; cancel.\n\n    eapply pimpl_trans; [ | eapply pimpl_trans ].\n    2: eapply subtree_absorb with (xp := fsxp) (fnlist := fndone) (tree := tree) (subtree' := tree0).\n    cancel. eauto. eauto. eauto.\n    rewrite update_subtree_same by eauto. cancel.\n    denote (find_subtree) as Hx; rewrite Hx.\n    destruct tree0; intuition.\n    eauto.\n\n    step.\n    rewrite cons_app. rewrite app_assoc. reflexivity.\n\n    (* Ret : OK *)\n    assert (tree_names_distinct tree).\n    eapply rep_tree_names_distinct with (m := locked (list2nmem m)).\n    pred_apply. unfold rep. cancel.\n\n    step; msalloc_eq.\n\n    rewrite subtree_absorb.\n    rewrite update_subtree_same.\n    cancel.\n    all: eauto.\n\n    right; eexists; intuition.\n    denote! (find_subtree (fndone ++ _) _ = _) as Hx.\n    unfold find_name; rewrite Hx.\n    destruct tree0; reflexivity.\n\n    left; intuition.\n    denote (find_subtree (fndone ++ _) _ = _) as Hx.\n    unfold find_name; rewrite Hx; eauto.\n\n    Grab Existential Variables.\n    all: try exact unit.\n    all: try exact None.\n    all: intros; try exact tt.\n    all: try congruence.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (namei _ _ _ _) _) => apply namei_ok : prog.\n\n  Theorem mkdir_ok' : forall fsxp dnum name mscs,\n    {< F mbase m sm Fm Ftop tree tree_elem ilist freeblocks,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist freeblocks mscs sm)%pred (list2nmem m) ]] *\n           [[ tree = TreeDir dnum tree_elem ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            exists inum ilist' freeblocks',\n            let tree' := TreeDir dnum ((name, TreeDir inum nil) :: tree_elem) in\n            [[ r = OK inum ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' freeblocks' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc freeblocks  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc freeblocks' (MSAlloc mscs')) tree' ]] )\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} mkdir fsxp dnum name mscs.\n  Proof.\n    unfold mkdir, rep.\n    step.\n    subst; simpl in *.\n    denote tree_dir_names_pred as Hx;\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    unfold IAlloc.MSLog in *.\n    step.\n    eapply IAlloc.ino_valid_goodSize; eauto.\n    destruct_branch; [ | step ].\n    prestep; norml; inv_option_eq; msalloc_eq.\n\n    cancel.\n    match goal with a: IAlloc.Alloc.memstate |- _\n      => destruct a; cbn in *; subst\n    end.\n    or_r; cancel.\n\n    unfold tree_dir_names_pred at 1. cancel; eauto.\n    denote (dummy1 =p=> _) as Hx. rewrite Hx.\n    unfold tree_dir_names_pred; cancel.\n    denote (BFILE.freepred _) as Hy. unfold BFILE.freepred in Hy. subst.\n    apply SDIR.bfile0_empty.\n    apply emp_empty_mem.\n    apply sep_star_comm. apply ptsto_upd_disjoint. auto. auto.\n\n    msalloc_eq.\n    eapply dirlist_safe_mkdir; auto.\n\n    Unshelve.\n    all: try eauto; exact emp; try exact nil; try exact empty_mem; try exact BFILE.bfile0.\n  Qed.\n\n\n  Theorem mkdir_ok : forall fsxp dnum name mscs,\n    {< F mbase sm m pathname Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeDir dnum tree_elem) ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            exists inum tree' ilist' frees', [[ r = OK inum ]] *\n            [[ tree' = update_subtree pathname (TreeDir dnum\n                      ((name, TreeDir inum nil) :: tree_elem)) tree ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] )\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} mkdir fsxp dnum name mscs.\n  Proof.\n    intros; eapply pimpl_ok2. apply mkdir_ok'.\n    unfold rep; cancel.\n    rewrite subtree_extract; eauto. simpl. instantiate (tree_elem0 := tree_elem). cancel.\n    step.\n    apply pimpl_or_r; right. cancel.\n    rewrite <- subtree_absorb; eauto.\n    cancel.\n    eapply dirlist_safe_subtree; eauto.\n  Qed.\n\n\n  Theorem mkfile_ok' : forall fsxp dnum name mscs,\n    {< F mbase sm m pathname Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeDir dnum tree_elem) ]]\n    POST:hm' RET:^(mscs',r) exists m',\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            exists inum ilist' tree' frees',\n            [[ r = OK inum ]] * [[ ~ In name (map fst tree_elem) ]] *\n            [[ tree' = update_subtree pathname (TreeDir dnum\n                        (tree_elem ++ [(name, (TreeFile inum dirfile0))] )) tree ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]])\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} mkfile fsxp dnum name mscs.\n  Proof.\n    unfold mkfile, rep.\n    step.\n    subst; simpl in *.\n\n    denote tree_pred as Ht;\n    rewrite subtree_extract in Ht; eauto.\n    assert (tree_names_distinct (TreeDir dnum tree_elem)).\n    eapply rep_tree_names_distinct with (m := list2nmem m).\n    pred_apply; unfold rep; cancel.\n\n    simpl in *.\n    denote tree_dir_names_pred as Hx;\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    unfold IAlloc.MSLog in *.\n    step.\n    unfold SDIR.rep_macro.\n    eapply IAlloc.ino_valid_goodSize; eauto.\n\n    destruct_branch; [ | step ].\n    prestep; norml; inv_option_eq.\n\n    cancel.\n    match goal with a: IAlloc.Alloc.memstate |- _\n      => destruct a; cbn in *; subst\n    end.\n    msalloc_eq.\n    or_r; cancel.\n    eapply dirname_not_in; eauto.\n\n    rewrite <- subtree_absorb; eauto.\n    cancel.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n    denote (dummy1 =p=> _) as Hx; rewrite Hx.\n    unfold BFILE.freepred.\n    rewrite dirlist_pred_split; simpl; cancel.\n    apply tree_dir_names_pred'_app; simpl.\n    apply sep_star_assoc; apply emp_star_r.\n    apply ptsto_upd_disjoint; auto.\n\n    eapply dirlist_safe_subtree; eauto.\n    msalloc_eq.\n    eapply dirlist_safe_mkfile; eauto.\n\n    pred_apply.\n    denote (dummy1 =p=> _) as Hx; rewrite Hx; unfold BFILE.freepred.\n    cancel.\n\n    eapply dirname_not_in; eauto.\n\n    Unshelve.\n    all: eauto.\n  Qed.\n\n  Hint Extern 0 (okToUnify (rep _ _ _ _ _ _ _) (rep _ _ _ _ _ _ _)) => constructor : okToUnify.\n\n\n  (* same as previous one, but use tree_graft *)\n  Theorem mkfile_ok : forall fsxp dnum name mscs,\n    {< F mbase sm m pathname Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeDir dnum tree_elem) ]]\n    POST:hm' RET:^(mscs',r) exists m',\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            exists inum ilist' tree' frees',\n            [[ r = OK inum ]] *\n            [[ tree' = tree_graft dnum tree_elem pathname name (TreeFile inum dirfile0) tree ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]])\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} mkfile fsxp dnum name mscs.\n  Proof.\n    unfold mkfile; intros.\n    eapply pimpl_ok2. apply mkfile_ok'.\n    cancel.\n    eauto.\n    step.\n\n    or_r; cancel.\n    rewrite tree_graft_not_in_dirents; auto.\n    rewrite <- tree_graft_not_in_dirents; auto.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (mkdir _ _ _ _) _) => apply mkdir_ok : prog.\n  Hint Extern 1 ({{_}} Bind (mkfile _ _ _ _) _) => apply mkfile_ok : prog.\n\n  Lemma false_False_true : forall x,\n    (x = false -> False) -> x = true.\n  Proof.\n    destruct x; tauto.\n  Qed.\n\n  Lemma true_False_false : forall x,\n    (x = true -> False) -> x = false.\n  Proof.\n    destruct x; tauto.\n  Qed.\n\n  Ltac subst_bool :=\n    repeat match goal with\n    | [ H : ?x = true |- _ ] => is_var x; subst x\n    | [ H : ?x = false |- _ ] => is_var x; subst x\n    | [ H : ?x = false -> False  |- _ ] => is_var x; apply false_False_true in H; subst x\n    | [ H : ?x = true -> False   |- _ ] => is_var x; apply true_False_false in H; subst x\n    end.\n\n\n  Hint Extern 0 (okToUnify (tree_dir_names_pred _ _ _) (tree_dir_names_pred _ _ _)) => constructor : okToUnify.\n\n  Theorem delete_ok' : forall fsxp dnum name mscs,\n    {< F mbase sm m Fm Ftop tree tree_elem frees ilist,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ tree = TreeDir dnum tree_elem ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            [[ r = OK tt ]] * exists frees' ilist',\n            let tree' := delete_from_dir name tree in\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] *\n            [[ forall inum def', inum <> dnum ->\n                 (In inum (tree_inodes tree') \\/ (~ In inum (tree_inodes tree))) ->\n                 selN ilist inum def' = selN ilist' inum def' ]])\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} delete fsxp dnum name mscs.\n  Proof.\n    unfold delete, rep.\n\n    (* extract some basic facts from rep *)\n    intros; eapply pimpl_ok2; monad_simpl; eauto with prog; intros; norm'l.\n    assert (tree_inodes_distinct (TreeDir dnum tree_elem)) as HiID.\n    eapply rep_tree_inodes_distinct with (m := list2nmem m).\n    pred_apply; unfold rep; cancel.\n    assert (tree_names_distinct (TreeDir dnum tree_elem)) as HdID.\n    eapply rep_tree_names_distinct with (m := list2nmem m).\n    pred_apply; unfold rep; cancel.\n\n    (* lookup *)\n    subst; simpl in *.\n    denote tree_dir_names_pred as Hx;\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    safecancel. 2: eauto.\n    unfold SDIR.rep_macro.\n    cancel; eauto.\n\n    denote! (_ (list2nmem m)) as Hm0; rewrite <- locked_eq in Hm0.\n    step.\n    step.\n    step.\n\n    (* unlink *)\n    step.\n\n    (* is_file: prepare for reset *)\n    prestep. norml.\n    denote dirlist_pred as Hx.\n    erewrite dirlist_extract with (inum := a0) in Hx; eauto.\n    destruct_lift Hx.\n    destruct dummy4; simpl in *; try congruence; subst.\n    denote dirlist_pred_except as Hx; destruct_lift Hx; auto.\n    cancel.\n\n    (* is_file: prepare for free *)\n    prestep. norml; msalloc_eq.\n    denote dirlist_pred as Hx.\n    erewrite dirlist_extract with (inum := n) in Hx; eauto.\n    destruct_lift Hx.\n    denote dirlist_pred_except as Hx; destruct_lift Hx; auto.\n    unfold IAlloc.MSLog in *; cancel.\n    match goal with H: (_ * ptsto ?a _)%pred ?m |- context [ptsto ?a]\n      => exists m; solve [pred_apply; cancel]\n    end.\n\n    (* post conditions *)\n    step.\n    or_r; safecancel.\n    denote (pimpl _ freepred') as Hx; rewrite <- Hx.\n    rewrite dir_names_delete with (dnum := dnum); eauto.\n    rewrite dirlist_pred_except_delete; eauto.\n    cancel.\n    eauto.\n    apply dirlist_safe_delete; auto.\n\n    (* inum inside the new modified tree *)\n    denote! (tree_dir_names_pred' _ _) as Hy.\n    eapply find_dirlist_exists in Hy as Hy'.\n    deex.\n    denote dirlist_combine as Hx.\n    eapply tree_inodes_distinct_delete in Hx as Hx'; eauto.\n    eassumption.\n\n    (* inum outside the original tree *)\n    denote! (forall _ _, (_ = _ -> False) -> _ = _) as Hz.\n    eapply Hz.\n    intro; subst.\n    denote! (In _ _ -> False) as Hq.\n    eapply Hq.\n    denote ((name |-> (_, false))%pred) as Hy.\n    eapply find_dirlist_exists in Hy as Hy'; eauto.\n    deex.\n    denote (dirtree_inum _ = dirtree_inum _ ) as Hd.\n    rewrite Hd.\n    eapply find_dirlist_tree_inodes; eauto.\n\n    cancel.\n    cancel.\n\n    unfold IAlloc.MSLog in *; cancel.\n    or_l. cancel.\n\n    (* case 2: is_dir: check empty *)\n    prestep.\n    intros; norm'l.\n    denote dirlist_pred as Hx; subst_bool.\n    rewrite dirlist_extract_subdir in Hx; eauto; simpl in Hx.\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    cancel. eauto.\n\n    step.\n    step.\n    step.\n    step.\n    step. msalloc_eq.\n    cancel.\n    exists (list2nmem flist'). eexists.\n    pred_apply. cancel.\n    unfold IAlloc.MSLog in *.\n    step.\n\n    (* post conditions *)\n    or_r; cancel.\n    denote (pimpl _ freepred') as Hx; rewrite <- Hx.\n    denote (tree_dir_names_pred' _ _) as Hz.\n    erewrite (@dlist_is_nil _ _ _ _ _ Hz); eauto.\n    rewrite dirlist_pred_except_delete; eauto.\n    rewrite dir_names_delete with (dnum := dnum).\n    cancel. eauto. eauto. eauto.\n    reflexivity.\n    apply dirlist_safe_delete; auto.\n\n    (* inum inside the new modified tree *)\n    eapply find_dirlist_exists in H9 as H9'.\n    deex.\n    denote dirlist_combine as Hx.\n    eapply tree_inodes_distinct_delete in Hx as Hx'; eauto.\n    eassumption.\n\n    (* inum outside the original tree *)\n    denote (selN _ _ _ = selN _ _ _) as Hs.\n    denote (In _ (dirlist_combine _ _)) as Hi.\n    denote (tree_dir_names_pred' tree_elem) as Ht.\n    apply Hs.\n    intro; subst.\n    eapply Hi.\n    eapply find_dirlist_exists with (inum := a0) in Ht as Ht'.\n    deex.\n    eapply find_dirlist_tree_inodes; eauto.\n    eassumption.\n\n    step.\n    step.\n    cancel; auto.\n    cancel; auto.\n\n    Unshelve.\n    all: try match goal with | [ |- DirTreePred.SDIR.rep _ _ ] => eauto end.\n    all: try exact unit.\n    all: try solve [repeat constructor].\n    all: eauto.\n    all: try exact string_dec.\n  Qed.\n\n\n\n  Theorem read_ok : forall fsxp inum off mscs,\n    {< F mbase sm m pathname Fm Ftop tree f B v ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]] *\n           [[ (B * off |-> v)%pred (list2nmem (DFData f)) ]]\n    POST:hm' RET:^(mscs',r)\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs') sm hm' *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs' sm)%pred (list2nmem m) ]] *\n           [[ r = fst v /\\ MSAlloc mscs' = MSAlloc mscs ]]\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} read fsxp inum off mscs.\n  Proof.\n    unfold read, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n\n    eapply list2nmem_inbound; eauto.\n    step; msalloc_eq.\n    cancel.\n\n    rewrite <- subtree_fold by eauto.\n    pred_apply. cancel.\n\n    cancel; eauto.\n  Qed.\n\n  Theorem dwrite_ok : forall fsxp inum off v mscs,\n    {< F ds sm pathname Fm Ftop tree f Fd vs ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds ds!!) (MSLL mscs) sm hm *\n           [[[ ds!! ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]] *\n           [[[ (DFData f) ::: (Fd * off |-> vs) ]]] *\n           [[ PredCrash.sync_invariant F ]]\n    POST:hm' RET:mscs'\n           exists ds' tree' f' sm' bn,\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds' ds'!!) (MSLL mscs') sm' hm' *\n           [[ ds' = dsupd ds bn (v, vsmerge vs) ]] *\n           [[ BFILE.block_belong_to_file ilist bn inum off ]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAllocC mscs' = MSAllocC mscs ]] *\n           [[ MSIAllocC mscs' = MSIAllocC mscs ]] *\n           (* spec about files on the latest diskset *)\n           [[[ ds'!! ::: (Fm  * rep fsxp Ftop tree' ilist frees mscs' sm') ]]] *\n           [[ tree' = update_subtree pathname (TreeFile inum f') tree ]] *\n           [[[ (DFData f') ::: (Fd * off |-> (v, vsmerge vs)) ]]] *\n           [[ f' = mk_dirfile (updN (DFData f) off (v, vsmerge vs)) (DFAttr f) ]] *\n           [[ dirtree_safe ilist (BFILE.pick_balloc frees (MSAlloc mscs')) tree\n                           ilist (BFILE.pick_balloc frees (MSAlloc mscs')) tree' ]]\n    XCRASH:hm'\n           LOG.recover_any fsxp.(FSXPLog) F ds hm' \\/\n           exists bn, [[ BFILE.block_belong_to_file ilist bn inum off ]] *\n           LOG.recover_any fsxp.(FSXPLog) F (dsupd ds bn (v, vsmerge vs)) hm'\n    >} dwrite fsxp inum off v mscs.\n  Proof.\n    unfold dwrite, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    eapply list2nmem_inbound; eauto.\n    prestep. norm. cancel.\n    intuition auto; msalloc_eq.\n    pred_apply; cancel.\n\n    rewrite <- subtree_absorb by eauto.\n    cancel.\n    auto.\n\n    eapply dirlist_safe_subtree; eauto.\n    apply dirtree_safe_file.\n  Qed.\n\n Theorem datasync_ok : forall fsxp inum mscs,\n    {< F ds sm pathname Fm Ftop tree f ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds ds!!) (MSLL mscs) sm hm *\n           [[[ ds!! ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]] *\n           [[ PredCrash.sync_invariant F ]]\n    POST:hm' RET:mscs'\n           exists ds' sm' tree' al,\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds' ds'!!) (MSLL mscs') sm' hm' *\n           [[ tree' = update_subtree pathname (TreeFile inum (synced_dirfile f)) tree ]] *\n           [[ ds' = dssync_vecs ds al ]] *\n           [[[ ds'!! ::: (Fm * rep fsxp Ftop tree' ilist frees mscs' sm') ]]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAllocC mscs' = MSAllocC mscs ]] *\n           [[ MSIAllocC mscs' = MSIAllocC mscs ]] *\n           [[ length al = length (DFData f) /\\ forall i, i < length al ->\n              BFILE.block_belong_to_file ilist (selN al i 0) inum i ]] *\n           [[ dirtree_safe ilist (BFILE.pick_balloc frees (MSAlloc mscs')) tree\n                           ilist (BFILE.pick_balloc frees (MSAlloc mscs')) tree' ]]\n    CRASH:hm'\n           LOG.recover_any fsxp.(FSXPLog) F ds hm'\n    >} datasync fsxp inum mscs.\n  Proof.\n    unfold datasync, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    step; msalloc_eq.\n    cancel.\n\n    rewrite <- subtree_absorb by eauto.\n    pred_apply. cancel.\n\n    eapply dirlist_safe_subtree; eauto.\n    apply dirtree_safe_file.\n  Qed.\n\n\n  Theorem sync_ok : forall fsxp mscs,\n    {< F ds sm Fm Ftop tree ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.NoTxn ds) (MSLL mscs) sm hm *\n           [[[ ds!! ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ PredCrash.sync_invariant F ]]\n    POST:hm' RET:mscs'\n           LOG.rep fsxp.(FSXPLog) F (LOG.NoTxn (ds!!, nil)) (MSLL mscs') sm hm' *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAlloc mscs' = negb (MSAlloc mscs) ]] *\n           [[ MSIAllocC mscs' = MSIAllocC mscs ]] *\n           [[ MSAllocC mscs' = MSAllocC mscs ]] *\n           [[ MSICache mscs' = MSICache mscs ]] *\n           [[ MSDBlocks mscs' = MSDBlocks mscs ]]\n    XCRASH:hm'\n           LOG.recover_any fsxp.(FSXPLog) F ds hm'\n     >} sync fsxp mscs.\n  Proof.\n    unfold sync, rep.\n    hoare.\n  Qed.\n\n  Theorem sync_noop_ok : forall fsxp mscs,\n    {< F ds sm Fm Ftop tree ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.NoTxn ds) (MSLL mscs) sm hm *\n           [[[ ds!! ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ PredCrash.sync_invariant F ]]\n    POST:hm' RET:mscs'\n           LOG.rep fsxp.(FSXPLog) F (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAlloc mscs' = negb (MSAlloc mscs) ]]\n    XCRASH:hm'\n           LOG.recover_any fsxp.(FSXPLog) F ds hm'\n     >} sync_noop fsxp mscs.\n  Proof.\n    unfold sync_noop, rep.\n    hoare.\n  Qed.\n\n  Theorem truncate_ok : forall fsxp inum nblocks mscs,\n    {< F ds sm d pathname Fm Ftop tree f frees ilist,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds d) (MSLL mscs) sm hm *\n           [[[ d ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]]\n    POST:hm' RET:^(mscs', ok)\n           exists d',\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds d') (MSLL mscs') sm hm' *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n          ([[ isError ok ]] \\/\n           [[ ok = OK tt ]] *\n           exists tree' f' ilist' frees',\n           [[[ d' ::: Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm ]]] *\n           [[ tree' = update_subtree pathname (TreeFile inum f') tree ]] *\n           [[ f' = mk_dirfile (setlen (DFData f) nblocks ($0, nil)) (DFAttr f) ]] *\n           [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                           ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] *\n           [[ nblocks >= Datatypes.length (DFData f) -> BFILE.treeseq_ilist_safe inum ilist ilist' ]])\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F ds sm hm'\n    >} truncate fsxp inum nblocks mscs.\n  Proof.\n    unfold truncate, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    step; msalloc_eq.\n    or_r.\n    cancel.\n    rewrite <- subtree_absorb by eauto. cancel.\n\n    eapply dirlist_safe_subtree; eauto.\n    apply dirtree_safe_file_trans; auto.\n  Qed.\n\n\n  Theorem getlen_ok : forall fsxp inum mscs,\n    {< F mbase sm m pathname Fm Ftop tree f frees ilist,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]]\n    POST:hm' RET:^(mscs',r)\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs') sm hm' *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs' sm)%pred (list2nmem m) ]] *\n           [[ r = length (DFData f) ]] *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]]\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} getlen fsxp inum mscs.\n  Proof.\n    unfold getlen, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    step; msalloc_eq.\n    cancel.\n    rewrite <- subtree_fold by eauto. pred_apply; cancel.\n    cancel; eauto.\n  Qed.\n\n  Theorem getattr_ok : forall fsxp inum mscs,\n    {< F ds sm d pathname Fm Ftop tree f ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds d) (MSLL mscs) sm hm *\n           [[[ d ::: Fm * rep fsxp Ftop tree ilist frees mscs sm ]]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]]\n    POST:hm' RET:^(mscs',r)\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn ds d) (MSLL mscs') sm hm' *\n           [[[ d ::: Fm * rep fsxp Ftop tree ilist frees mscs' sm ]]] *\n           [[ MSCache mscs' = MSCache mscs ]] *\n           [[ r = DFAttr f /\\ MSAlloc mscs' = MSAlloc mscs ]]\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F ds sm hm'\n    >} getattr fsxp inum mscs.\n  Proof.\n    unfold getattr, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    step; msalloc_eq.\n    cancel.\n    rewrite <- subtree_fold by eauto. pred_apply; cancel.\n    cancel; eauto.\n  Qed.\n\n  Theorem setattr_ok : forall fsxp inum attr mscs,\n    {< F mbase sm m pathname Fm Ftop tree f ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeFile inum f) ]] \n    POST:hm' RET:mscs'\n           exists m' tree' f' ilist',\n           LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ (Fm * rep fsxp Ftop tree' ilist' frees mscs' sm)%pred (list2nmem m') ]] *\n           [[ tree' = update_subtree pathname (TreeFile inum f') tree ]] *\n           [[ f' = mk_dirfile (DFData f) attr ]] *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                           ilist' (BFILE.pick_balloc frees  (MSAlloc mscs')) tree' ]] *\n           [[ BFILE.treeseq_ilist_safe inum ilist ilist' ]]\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} setattr fsxp inum attr mscs.\n  Proof.\n    unfold setattr, rep.\n    intros. prestep. norml.\n    rewrite subtree_extract in * by eauto.\n    cbn [tree_pred] in *. destruct_lifts.\n    cancel.\n    step; msalloc_eq.\n    cancel.\n    rewrite <- subtree_absorb by eauto.\n    pred_apply; cancel.\n    eapply dirlist_safe_subtree; eauto.\n    apply dirtree_safe_file_trans; auto.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (read _ _ _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (dwrite _ _ _ _ _) _) => apply dwrite_ok : prog.\n  Hint Extern 1 ({{_}} Bind (datasync _ _ _) _) => apply datasync_ok : prog.\n  Hint Extern 1 ({{_}} Bind (sync _ _) _) => apply sync_ok : prog.\n  Hint Extern 1 ({{_}} Bind (sync_noop _ _) _) => apply sync_noop_ok : prog.\n  Hint Extern 1 ({{_}} Bind (truncate _ _ _ _) _) => apply truncate_ok : prog.\n  Hint Extern 1 ({{_}} Bind (getlen _ _ _) _) => apply getlen_ok : prog.\n  Hint Extern 1 ({{_}} Bind (getattr _ _ _) _) => apply getattr_ok : prog.\n  Hint Extern 1 ({{_}} Bind (setattr _ _ _ _) _) => apply setattr_ok : prog.\n\n \n  Theorem delete_ok : forall fsxp dnum name mscs,\n    {< F mbase sm m pathname Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeDir dnum tree_elem) ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            [[ r = OK tt ]] * exists tree' ilist' frees',\n            [[ tree' = update_subtree pathname\n                      (delete_from_dir name (TreeDir dnum tree_elem)) tree ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] *\n            [[ forall inum def', inum <> dnum ->\n                 (In inum (tree_inodes tree') \\/ (~ In inum (tree_inodes tree))) ->\n                selN ilist inum def' = selN ilist' inum def' ]])\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} delete fsxp dnum name mscs.\n  Proof.\n    intros; eapply pimpl_ok2. apply delete_ok'.\n\n    intros; norml; unfold stars; simpl.\n    rewrite rep_tree_distinct_impl in *.\n    unfold rep in *; cancel.\n\n    rewrite subtree_extract; eauto. simpl. instantiate (tree_elem0:=tree_elem). cancel.\n    step.\n    apply pimpl_or_r; right. cancel.\n    rewrite <- subtree_absorb; eauto.\n    cancel.\n    eapply dirlist_safe_subtree; eauto.\n    denote (dirlist_combine tree_inodes _) as Hx.\n    specialize (Hx inum def' H4).\n    intuition; try congruence.\n\n    destruct_lift H0.\n    edestruct tree_inodes_pathname_exists. 3: eauto.\n    eapply tree_names_distinct_update_subtree; eauto.\n    eapply tree_names_distinct_delete_from_list.\n    eapply tree_names_distinct_subtree; eauto.\n\n    eapply tree_inodes_distinct_update_subtree; eauto.\n    eapply tree_inodes_distinct_delete_from_list.\n    eapply tree_inodes_distinct_subtree; eauto.\n    simpl. eapply incl_cons2.\n    eapply tree_inodes_incl_delete_from_list.\n\n    (* case A: inum inside tree' *)\n\n    repeat deex.\n    destruct (pathname_decide_prefix pathname x); repeat deex.\n\n    (* case 1: in the directory *)\n    erewrite find_subtree_app in *; eauto.\n    eapply H11.\n\n    eapply find_subtree_inum_present in H16; simpl in *.\n    intuition. exfalso; eauto.\n\n    (* case 2: outside the directory *)\n    eapply H9.\n    intro.\n    edestruct tree_inodes_pathname_exists with (tree := TreeDir dnum tree_elem) (inum := dirtree_inum subtree).\n    3: eassumption.\n\n    eapply tree_names_distinct_subtree; eauto.\n    eapply tree_inodes_distinct_subtree; eauto.\n\n    destruct H20.\n    destruct H20.\n\n    eapply H6.\n    exists x0.\n\n    edestruct find_subtree_before_prune_general; eauto.\n\n    eapply find_subtree_inode_pathname_unique.\n    eauto. eauto.\n    intuition eauto.\n    erewrite find_subtree_app; eauto.\n    intuition congruence.\n\n    (* case B: outside original tree *)\n    eapply H11; eauto.\n    right.\n    contradict H7; intuition eauto. exfalso; eauto.\n    eapply tree_inodes_find_subtree_incl; eauto.\n    simpl; intuition.\n  Unshelve.\n    all: eauto.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (delete _ _ _ _) _) => apply delete_ok : prog.\n\n\n  Theorem rename_cwd_ok : forall fsxp dnum srcpath srcname dstpath dstname mscs,\n    {< F mbase m sm Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ tree = TreeDir dnum tree_elem ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            [[ r = OK tt ]] * exists snum sents dnum dents subtree pruned tree' ilist' frees',\n            [[ find_subtree srcpath tree = Some (TreeDir snum sents) ]] *\n            [[ find_dirlist srcname sents = Some subtree ]] *\n            [[ pruned = tree_prune snum sents srcpath srcname tree ]] *\n            [[ find_subtree dstpath pruned = Some (TreeDir dnum dents) ]] *\n            [[ tree' = tree_graft dnum dents dstpath dstname subtree pruned ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] *\n            [[ forall inum' def', inum' <> snum -> inum' <> dnum ->\n               (In inum' (tree_inodes tree') \\/ (~ In inum' (tree_inodes tree))) ->\n               selN ilist inum' def' = selN ilist' inum' def' ]] )\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} rename fsxp dnum srcpath srcname dstpath dstname mscs.\n  Proof.\n    unfold rename, rep.\n\n    (* extract some basic facts *)\n    prestep; norm'l.\n    assert (tree_inodes_distinct (TreeDir dnum tree_elem)) as HnID.\n    eapply rep_tree_inodes_distinct with (m := list2nmem m).\n    pred_apply; unfold rep; cancel.\n    assert (tree_names_distinct (TreeDir dnum tree_elem)) as HiID.\n    eapply rep_tree_names_distinct with (m := list2nmem m).\n    pred_apply; unfold rep; cancel.\n\n    (* namei srcpath, isolate root tree file before cancel *)\n    subst; simpl in *.\n    denote tree_dir_names_pred as Hx; assert (Horig := Hx).\n    unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n    cancel.\n\n    (* BFILE.rep in post condition of namei doesn't unify with  BFILE.rep in context, \n       because namei may change cache content and promises a new BFILE.rep in its post\n       condition, which we should use from now on. Should we clear the old BFILE.rep? *)\n    denote! (_ (list2nmem m)) as Hm0; rewrite <- locked_eq in Hm0.\n\n    instantiate (tree := TreeDir dnum tree_elem).\n    unfold rep; simpl.\n    unfold tree_dir_names_pred; cancel.\n    all: eauto.\n\n    (* lookup srcname, isolate src directory before cancel *)\n    destruct_branch; [ | step ].\n    destruct_branch; destruct_branch; [ | step ].\n\n    prestep; norm'l.\n\n    (* lock the old BFILE.rep again, but not the new one. *)\n    denote! ( (Fm * BFILE.rep _ _ _ _ _ _ _ (MSCache mscs) _ _ * _)%pred (list2nmem m)) as Hm0; rewrite <- locked_eq in Hm0.\n\n    intuition; inv_option_eq; repeat deex; destruct_pairs.\n    denote find_name as Htree.\n    apply eq_sym in Htree.\n    apply find_name_exists in Htree.\n    destruct Htree. intuition.\n\n    denote find_subtree as Htree; assert (Hx := Htree).\n    apply subtree_extract with (xp := fsxp) in Hx.\n    denote tree_dir_names_pred as Hy; assert (Hsub := Hy).\n    eapply pimpl_trans in Hsub; [ | | eapply pimpl_sep_star; [ apply pimpl_refl | apply Hx ] ];\n      [ | cancel ]. clear Hx.\n    destruct x; simpl in *; subst; try congruence.\n    unfold tree_dir_names_pred in Hsub.\n    destruct_lift Hsub.\n    denote (_ |-> _)%pred as Hsub.\n\n    safecancel.\n    cancel. 2: eauto.\n\n    (* unlink src *)\n    step.\n\n    (* lock an old BFILE.rep *)\n    denote! ( ((Fm * BFILE.rep _ _ _ _ _ _ _ (MSCache a) _ _) * _)%pred (list2nmem m)) as Hm1; rewrite <- locked_eq in Hm1.\n\n    (* namei for dstpath, find out pruning subtree before step *)\n    denote (tree_dir_names_pred' l0 _) as Hx1.\n    denote (_ |-> (_, _))%pred as Hx2.\n    pose proof (ptsto_subtree_exists _ Hx1 Hx2) as Hx.\n    destruct Hx; intuition.\n\n    step; msalloc_eq.\n    cancel.\n    {\n      cancel.\n      match goal with |- context [(?inum_ |-> _)%pred] =>\n        eapply pimpl_trans; [ eapply pimpl_trans; [ |\n        eapply subtree_prune_absorb with (inum := inum_) (ri := dnum) (re := tree_elem) (xp := fsxp) (path := srcpath)\n        ] | ]\n      end.\n      all: eauto using dir_names_pred_delete'.\n      cancel.\n    }\n    rewrite tree_prune_preserve_inum; auto.\n    rewrite tree_prune_preserve_isdir; auto.\n\n    (* fold back predicate for the pruned tree in hypothesis as well  *)\n    denote (list2nmem flist0) as Hinterm.\n    apply helper_reorder_sep_star_2 in Hinterm.\n    erewrite subtree_prune_absorb in Hinterm; eauto.\n    2: apply dir_names_pred_delete'; auto.\n    apply helper_reorder_sep_star_2 in Hinterm.\n    rename x into mvtree.\n\n    (* lookup dstname *)\n    destruct_branch; [ | step ].\n    destruct_branch; destruct_branch; [ | step ].\n\n    (* lock an old BFILE.rep; we have a new one from namei *)\n    denote! ( (_* BFILE.rep _ _ _ _ _ _ _ (MSCache a0) _ _)%pred (list2nmem m)) as Hm2; rewrite <- locked_eq in Hm2.\n\n    prestep; norm'l.\n    intuition; inv_option_eq; repeat deex; destruct_pairs.\n\n    denote find_name as Hpruned.\n    apply eq_sym in Hpruned.\n    apply find_name_exists in Hpruned.\n    destruct Hpruned. intuition.\n\n    denote (list2nmem dummy9) as Hinterm1.\n    denote find_subtree as Hpruned; assert (Hx := Hpruned).\n    apply subtree_extract with (xp := fsxp) in Hx.\n    assert (Hdst := Hinterm1); rewrite Hx in Hdst; clear Hx.\n    destruct x; simpl in *; subst; try congruence; inv_option_eq.\n    unfold tree_dir_names_pred in Hdst.\n    destruct_lift Hdst.\n\n    safecancel. eauto.\n\n    denote! ( (Fm * _ * BFILE.rep _ _ _ _ _ _ _ (MSCache a4) _ _)%pred (list2nmem m')) as Hm3; rewrite <- locked_eq in Hm3.\n\n    (* grafting back *)\n    destruct_branch.\n\n    (* case 1: dst exists, try delete *)\n    prestep.\n    norml; msalloc_eq.\n    unfold stars; simpl; inv_option_eq.\n    denote (tree_dir_names_pred' _ _) as Hx3.\n    denote (_ |-> (_, _))%pred as Hx4.\n    pose proof (ptsto_subtree_exists _ Hx3 Hx4) as Hx.\n    destruct Hx; intuition.\n\n    denote! ( ((Fm * BFILE.rep _ _ _ _ _ _ (MSAllocC a1) _ _ _) * _)%pred (list2nmem m')) as Hm4; rewrite <- locked_eq in Hm4.\n\n    (* must unify [find_subtree] in [delete]'s precondition with\n       the root tree node.  have to do this manually *)\n    unfold rep; norm. cancel. intuition.\n    pred_apply; norm. cancel. intuition.\n    eassign (tree_prune v_1 l0 srcpath srcname (TreeDir dnum tree_elem)).\n    (* it would have been nice if we could have used Hinterm, as the old\n       proof did, but flist has changed because of caching, and we need to\n       use the latest flist and fold things back together again. *)\n    2: eauto.\n    pred_apply.\n    cancel.\n    rewrite helper_reorder_sep_star_3.\n    rewrite fold_back_dir_pred; eauto.\n    rewrite helper_reorder_sep_star_4.\n    rewrite subtree_fold; eauto. \n    cancel.\n\n    (* now, get ready for link *)\n    destruct_branch; [ | step ].\n    prestep; norml; inv_option_eq; msalloc_eq.\n    denote mvtree as Hx. assert (Hdel := Hx).\n    setoid_rewrite subtree_extract in Hx at 2.\n    2: subst; eapply find_update_subtree; eauto.\n    simpl in Hx; unfold tree_dir_names_pred in Hx; destruct_lift Hx.\n\n    denote! ( _ (list2nmem m')) as Hm5; rewrite <- locked_eq in Hm5.\n    cancel.\n    eauto.\n\n    eapply tree_pred_ino_goodSize; eauto.\n\n    pred_apply' Hdel; cancel.\n\n    safestep; msalloc_eq.\n    or_l; cancel.\n    or_r; cancel; eauto.\n    eapply subtree_graft_absorb_delete; eauto.\n    msalloc_eq.\n    eapply dirtree_safe_rename_dest_exists; eauto.\n\n    (* case 1: in the new tree *)\n    denote BFILE.treeseq_ilist_safe as Hsafe.\n    unfold BFILE.treeseq_ilist_safe in Hsafe; destruct Hsafe as [Hsafe0 Hsafe1].\n    rewrite <- Hsafe1 by auto.\n\n    denote (selN ilist _ _ = selN ilist' _ _) as Hi.\n    eapply Hi; eauto.\n\n    eapply prune_graft_preserves_inodes; eauto.\n\n    (* case 2: out of the original tree *)\n    denote BFILE.treeseq_ilist_safe as Hsafe.\n    unfold BFILE.treeseq_ilist_safe in Hsafe; destruct Hsafe as [Hsafe0 Hsafe1].\n    rewrite <- Hsafe1 by auto.\n\n    denote (selN ilist _ _ = selN ilist' _ _) as Hi.\n    eapply Hi; eauto.\n    right. intros HH.\n    eapply tree_inodes_incl_delete_from_dir in HH; eauto.\n    unfold tree_prune in *.\n    cbn in *; intuition.\n\n    cancel.\n\n    (* dst is None *)\n    safestep.\n    safestep.\n    eapply tree_pred_ino_goodSize; eauto.\n    denote (_ (list2nmem flist1)) as H'.\n    pred_apply' H'; cancel.   (* Hinterm as above *)\n\n    safestep; msalloc_eq.\n    or_l; cancel.\n    or_r; cancel; eauto.\n\n    rewrite helper_reorder_sep_star_5.\n    eapply subtree_graft_absorb; eauto.\n    msalloc_eq.\n    eapply dirtree_safe_rename_dest_none; eauto.\n    eapply notindomain_not_in_dirents; eauto.\n\n    denote BFILE.treeseq_ilist_safe as Hsafe.\n    unfold BFILE.treeseq_ilist_safe in Hsafe; destruct Hsafe as [Hsafe0 Hsafe1].\n    apply Hsafe1; auto.\n\n    denote BFILE.treeseq_ilist_safe as Hsafe.\n    unfold BFILE.treeseq_ilist_safe in Hsafe; destruct Hsafe as [Hsafe0 Hsafe1].\n    apply Hsafe1; auto.\n\n    cancel.\n    cancel; auto.\n\n    cancel.\n    Unshelve.\n    all: try exact unit.\n    all: try solve [repeat econstructor].\n    all: try eauto.\n    all: cbv [Mem.EqDec]; decide equality.\n  Qed.\n\n  Theorem rename_ok : forall fsxp dnum srcpath srcname dstpath dstname mscs,\n    {< F mbase sm m pathname Fm Ftop tree tree_elem ilist frees,\n    PRE:hm LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m) (MSLL mscs) sm hm *\n           [[ (Fm * rep fsxp Ftop tree ilist frees mscs sm)%pred (list2nmem m) ]] *\n           [[ find_subtree pathname tree = Some (TreeDir dnum tree_elem) ]]\n    POST:hm' RET:^(mscs',r)\n           exists m', LOG.rep fsxp.(FSXPLog) F (LOG.ActiveTxn mbase m') (MSLL mscs') sm hm' *\n           [[ MSAlloc mscs' = MSAlloc mscs ]] *\n           ([[ isError r ]] \\/\n            [[ r = OK tt ]] *\n            exists srcnum srcents dstnum dstents subtree pruned renamed tree' ilist' frees',\n            [[ find_subtree srcpath (TreeDir dnum tree_elem) = Some (TreeDir srcnum srcents) ]] *\n            [[ find_dirlist srcname srcents = Some subtree ]] *\n            [[ pruned = tree_prune srcnum srcents srcpath srcname (TreeDir dnum tree_elem) ]] *\n            [[ find_subtree dstpath pruned = Some (TreeDir dstnum dstents) ]] *\n            [[ renamed = tree_graft dstnum dstents dstpath dstname subtree pruned ]] *\n            [[ tree' = update_subtree pathname renamed tree ]] *\n            [[ (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)%pred (list2nmem m') ]] *\n            [[ dirtree_safe ilist  (BFILE.pick_balloc frees  (MSAlloc mscs')) tree\n                            ilist' (BFILE.pick_balloc frees' (MSAlloc mscs')) tree' ]] *\n            [[ forall inum' def', inum' <> srcnum -> inum' <> dstnum ->\n               In inum' (tree_inodes tree') ->\n               selN ilist inum' def' = selN ilist' inum' def' ]] )\n    CRASH:hm'\n           LOG.intact fsxp.(FSXPLog) F mbase sm hm'\n    >} rename fsxp dnum srcpath srcname dstpath dstname mscs.\n  Proof.\n    intros; eapply pimpl_ok2. apply rename_cwd_ok.\n\n    intros; norml; unfold stars; simpl.\n    rewrite rep_tree_distinct_impl in *.\n    unfold rep in *; cancel.\n    rewrite subtree_extract; eauto. simpl. instantiate (tree_elem0:=tree_elem). cancel.\n    step.\n    apply pimpl_or_r; right. cancel; eauto.\n    rewrite <- subtree_absorb; eauto.\n    cancel.\n    rewrite tree_graft_preserve_inum; auto.\n    rewrite tree_prune_preserve_inum; auto.\n    rewrite tree_graft_preserve_isdir; auto.\n    rewrite tree_prune_preserve_isdir; auto.\n    eapply dirlist_safe_subtree; eauto.\n\n    denote! (((Fm * BFILE.rep _ _ _ _ _ _ _ _ _ _) * IAlloc.rep _ _ _ _ _)%pred _) as Hm'.\n    eapply pimpl_apply in Hm'.\n    eapply rep_tree_names_distinct in Hm' as Hnames.\n    eapply rep_tree_inodes_distinct in Hm' as Hinodes.\n    2: unfold rep; cancel.\n    2: rewrite <- subtree_absorb.\n    2: cancel. 2: apply pimpl_refl. 2: eauto.\n    2: rewrite tree_graft_preserve_inum; auto.\n    2: rewrite tree_prune_preserve_inum; auto.\n    2: rewrite tree_graft_preserve_isdir; auto.\n    2: rewrite tree_prune_preserve_isdir; auto.\n\n    edestruct tree_inodes_pathname_exists. 3: eauto. all: eauto.\n    repeat deex.\n    destruct (pathname_decide_prefix pathname x); repeat deex.\n\n    (* case 1: inum inside tree' *)\n    erewrite find_subtree_app in *; eauto.\n\n    (* case 2: inum outside tree' *)\n    denote (selN ilist _ _ = selN ilist' _ _) as Hilisteq.\n    eapply Hilisteq; eauto.\n    right. intros.\n\n    denote ([[ tree_names_distinct _ ]]%pred) as Hlift. destruct_lift Hlift.\n    edestruct find_subtree_update_subtree_oob_general; eauto.\n    edestruct tree_inodes_pathname_exists with (tree := TreeDir dnum tree_elem) (inum := dirtree_inum subtree0) as [pn_conflict ?].\n    eapply tree_names_distinct_subtree; [ | eauto ]; eauto.\n    eapply tree_inodes_distinct_subtree; [ | | eauto ]; eauto.\n    simpl; intuition.\n\n    denote! (exists _, find_subtree _ _ = _ /\\ dirtree_inum _ = dirtree_inum _) as Hx.\n    destruct Hx.\n\n    denote! (~ (exists _, _ = _ ++ _)) as Hsuffix.\n    eapply Hsuffix.\n    exists pn_conflict.\n\n    eapply find_subtree_inode_pathname_unique with (tree := tree).\n    eauto. eauto.\n\n    intuition eauto.\n    erewrite find_subtree_app by eauto; intuition eauto.\n    intuition congruence.\n\n  Grab Existential Variables.\n    all: try exact unit.\n    all: intros; eauto using BFILE.MSIAlloc.\n    all: try solve [do 5 econstructor].\n    all: try (cbv [Mem.EqDec]; decide equality).\n    all: try exact emp.\n    all: intros; try exact True.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (rename _ _ _ _ _ _ _) _) => apply rename_ok : prog.\n\nEnd DIRTREE.\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/DirTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19652527326771713}}
{"text": "From hahn Require Import Hahn.\nRequire Import Exec.\nRequire Import Events.\n\nSection RfFunc.\n\nLemma init_dec exec E : {init exec E} + {~(init exec E)}.\nProof.\n  destruct (IW exec) as [iw|] eqn:eqinit.\n  - destruct (mev_eq_dec iw E).\n    + subst. left. unfold init. rewrite eqinit. reflexivity.\n    + right. intro. apply n. unfold init in H.\n      rewrite eqinit in H. auto.\n  - right. intro H. unfold init in H. rewrite eqinit in H.\n    contradiction.\nQed.\n\nDefinition rf_func exec :=\n  functional (rf exec)\u207b\u00b9.\n\nNotation \"a \u00b2\" := (a \u00d7 a) (at level 1, format \"a \u00b2\").\n\nDefinition aligned_and_no_overlap exec :=\n  (EV exec)\\\u2081(init exec) \u2286\u2081 aligned /\\ overlap \u2229 (EV exec \\\u2081 init exec)\u00b2 \u2286 same_loc.\n\nDefinition strong_tearfree e :=\n  functional ((rf e) \u2229 (((tearfree e)\u00b2 \u2229 same_loc) \u222a (init e \u00d7 tearfree e)))\u207b\u00b9.\n\nDefinition unisized exec := aligned_and_no_overlap exec /\\ strong_tearfree exec.\n\nLemma uni__tf exec :\n  consistent exec ->\n  unisized exec ->\n  forall E, EV exec E -> tearfree exec E.\nProof.\n  intros cst [[aligned nover] _] E EVE.\n  destruct (init_dec exec E).\n  - right. assumption.\n  - left. split.\n    + apply aligned.\n      split; assumption.\n    + assumption.\nQed.\n\nLemma uni__sameloc exec :\n  well_formed exec ->\n  unisized exec ->\n  \u2997EV exec \\\u2081 init exec\u2998 \u2a3e rf exec \u2286 same_loc.\nProof.\n  intros wf alnoov X Y H.\n  destruct (alnoov) as [[_ noov] _].\n  unfolder in H.\n  destruct H as [[EVX ninitX] rfXY].\n  apply noov.\n  split.\n  - apply rf__overlap with exec; assumption.\n  - destruct rfXY as [b [_ rfbXY]].\n    destruct (wf_rfb_wr exec wf b) as [H _].\n    apply H in rfbXY.\n    unfolder in rfbXY.\n    destruct rfbXY as [_ [_ WY]].\n    destruct (WY).\n    split; split; try assumption.\n    intro initY.\n    apply wf_iww in initY; try assumption.\n    destruct initY.\n    contradiction.\nQed.\n\nTheorem rf_is_func exec :\n  well_formed exec -> consistent exec ->\n  unisized exec -> rf_func exec.\nProof.\n  intros wf cst uni R.\n  assert (forall W, rf exec W R ->\n      ((tearfree exec)\u00b2 \u2229 same_loc \u222a init exec \u00d7 tearfree exec) W R)\n    as lemma.\n  {\n    intros W rfWR.\n    assert (tearfree exec R). {\n      apply uni__tf; try assumption.\n      apply rf__ev in rfWR; try assumption.\n      destruct rfWR.\n      assumption.\n    }\n    assert (EV exec W). {\n      apply rf__ev in rfWR; try assumption.\n      destruct rfWR.\n      assumption.\n    }\n    destruct (init_dec exec W) as [IW | nIW].\n    + right. split; assumption.\n    + left. split.\n      * split; try assumption.\n        apply uni__tf; assumption.\n      * apply uni__sameloc with exec; try assumption.\n        exists W.\n        repeat (split; auto).\n  }\n  intros W1 W2.\n  unfold transp.\n  intros rf1 rf2.\n  destruct (uni) as [[align noov] tf].\n  apply tf with R;\n  split;\n  try assumption;\n  apply lemma;\n  assumption.\nQed.\n\nEnd RfFunc.", "meta": {"author": "Biebar", "repo": "jsrelaxedmemorymodel_coq", "sha": "b0e5d5e470d7fcc579121f9013bf1df4ad5afe69", "save_path": "github-repos/coq/Biebar-jsrelaxedmemorymodel_coq", "path": "github-repos/coq/Biebar-jsrelaxedmemorymodel_coq/jsrelaxedmemorymodel_coq-b0e5d5e470d7fcc579121f9013bf1df4ad5afe69/RfFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19652527326771713}}
{"text": "Require Import Lia Setoid Program.Basics.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic Language.\nFrom imm Require Import Events Prog Execution ProgToExecution.\nRequire Import AuxDef.\nRequire Import AuxRel.\nRequire Import EventStructure.\nRequire Import LblStep.\nRequire Import ProgLoc.\nRequire Import Consistency.\nRequire Import EventToAction.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nDefinition thread_lts (t : thread_id) : Language.t (list label) :=\n  @Language.mk (list label)\n    (list Instr.t) state\n    init\n    is_terminal\n    (ilbl_step t).\n\nDefinition prog_init_threads (prog : Prog.t) :\n  IdentMap.t {lang : Language.t (list label) & Language.state lang} :=\n  IdentMap.mapi\n    (fun tid (linstr : list Instr.t) =>\n       existT _ (thread_lts tid) (ProgToExecution.init linstr))\n    prog.\n\nDefinition stable_prog_type := IdentMap.t { linstr & stable_lprog linstr }.\nDefinition stable_prog_to_prog (prog : stable_prog_type) : Prog.t :=\n  (IdentMap.map (fun x => projT1 x) prog).\n\nLemma stable_prog_to_prog_in prog thread :\n  IdentMap.In thread (stable_prog_to_prog prog) <-> IdentMap.In thread prog.\nProof.\n  unfold stable_prog_to_prog.\n  eapply RegMap.Facts.map_in_iff.\nQed.\n\nLemma stable_prog_to_prog_no_init prog\n      (PROG_NINIT : ~ IdentMap.In tid_init prog) :\n  ~ IdentMap.In tid_init (stable_prog_to_prog prog).\nProof. by rewrite stable_prog_to_prog_in. Qed.\n\nDefinition prog_init_K\n           (prog : stable_prog_type) :\n  list (cont_label * {lang : Language.t (list label) & Language.state lang}) :=\n  map\n    (fun tidc =>\n       let tid    := fst tidc in\n       let linstr := projT1 (snd tidc) in\n       let STBL   := projT2 (snd tidc) in\n       let st'    := proj1_sig (get_stable\n                                  tid (init linstr) STBL\n                                  (rt_refl _ _ (init linstr))) in\n       (CInit tid, existT _ (thread_lts tid) st'))\n    (RegMap.elements prog).\n\nDefinition prog_l_es_init (prog : stable_prog_type) (locs : list location) :=\n  ES.init (undup locs) (prog_init_K prog).\n\nDefinition prog_es_init (prog : stable_prog_type) :=\n  prog_l_es_init prog (prog_locs (stable_prog_to_prog prog)).\n\n\nLemma prog_es_init_alt (prog : stable_prog_type) :\n  prog_es_init prog = ES.init\n                        (prog_locs (stable_prog_to_prog prog))\n                        (prog_init_K prog).\nProof.\n  unfold prog_es_init, prog_l_es_init, prog_locs.\n  rewrite undup_nodup; eauto.\n  apply NoDup_nodup.\nQed.\n\nDefinition g_locs (G : execution) :=\n  undup (flatten (map (fun e =>\n                         match e with\n                         | InitEvent l => [l]\n                         | _ => []\n                         end)\n                      (acts G))).\n\nDefinition prog_g_es_init prog (G : execution) :=\n  prog_l_es_init prog (g_locs G).\n\nLemma prog_g_es_init_alt prog (G : execution) :\n  prog_g_es_init prog G = ES.init (g_locs G) (prog_init_K prog).\nProof.\n  unfold prog_g_es_init, prog_l_es_init, g_locs.\n  rewrite undup_nodup; auto.\nQed.\n\nLemma prog_l_es_init_ninit locs prog :\n  ES.acts_ninit_set (prog_l_es_init prog locs) \u2261\u2081 \u2205.\nProof.\n  split; [|basic_solver].\n  red. unfold prog_l_es_init, ES.init. intros x HH.\n  apply HH. red. split; auto.\n  apply HH.\nQed.\n\nLemma prog_g_es_init_ninit G prog :\n  ES.acts_ninit_set (prog_g_es_init prog G) \u2261\u2081 \u2205.\nProof. apply prog_l_es_init_ninit. Qed.\n\nLemma prog_l_es_init_sb locs prog :\n  ES.sb (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold prog_l_es_init, ES.init. simpls.\nQed.\n\nLemma prog_g_es_init_sb G prog :\n  ES.sb (prog_g_es_init prog G) \u2261 \u2205\u2082.\nProof. apply prog_l_es_init_sb. Qed.\n\nLemma prog_l_es_init_jf locs prog :\n  ES.jf (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold prog_l_es_init, ES.init. simpls.\nQed.\n\nLemma prog_g_es_init_jf G prog :\n  ES.jf (prog_g_es_init prog G) \u2261 \u2205\u2082.\nProof. apply prog_l_es_init_jf. Qed.\n\nLemma prog_l_es_init_sw locs prog :\n  sw (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold sw. rewrite prog_l_es_init_jf. basic_solver.\nQed.\n\nLemma prog_g_es_init_sw G prog :\n  sw (prog_g_es_init prog G) \u2261 \u2205\u2082.\nProof. apply prog_l_es_init_sw. Qed.\n\nLemma prog_l_es_init_hb locs prog :\n  hb (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold hb.\n  rewrite prog_l_es_init_sw, prog_l_es_init_sb.\n  rewrite ct_no_step; basic_solver.\nQed.\n\nLemma prog_g_es_init_hb G prog :\n  hb (prog_g_es_init prog G) \u2261 \u2205\u2082.\nProof. apply prog_l_es_init_hb. Qed.\n\nLemma prog_l_es_init_cf locs prog :\n  ES.cf (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold ES.cf. rewrite prog_l_es_init_ninit. basic_solver.\nQed.\n\nLemma prog_g_es_init_cf G prog :\n  ES.cf (prog_g_es_init prog G) \u2261 \u2205\u2082.\nProof. apply prog_l_es_init_cf. Qed.\n\nLemma prog_l_es_init_psc_f locs prog :\n  psc_f (prog_l_es_init prog locs) Weakestmo \u2261 \u2205\u2082.\nProof.\n  unfold psc_f.\n  rewrite prog_l_es_init_hb.\n  basic_solver.\nQed.\n\nLemma prog_l_es_init_scb locs prog :\n  scb (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  unfold scb.\n  unfold ES.fr, ES.rf.\n  rewrite prog_l_es_init_sb.\n  rewrite prog_l_es_init_hb.\n  rewrite prog_l_es_init_jf.\n  basic_solver.\nQed.\n\nLemma prog_l_es_init_psc_base locs prog :\n  psc_base (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  unfold psc_base.\n  rewrite prog_l_es_init_scb.\n  basic_solver.\nQed.\n\nLemma prog_l_es_init_rmw locs prog :\n  ES.rmw (prog_l_es_init prog locs) \u2261 \u2205\u2082.\nProof.\n  split; [|basic_solver].\n  unfold prog_l_es_init, ES.init. simpls.\nQed.\n\nHint Rewrite prog_g_es_init_ninit\n     prog_g_es_init_sb\n     prog_g_es_init_jf\n     prog_g_es_init_sw\n     prog_g_es_init_hb\n     prog_g_es_init_cf\n  : prog_g_es_init_db.\n\nHint Rewrite prog_l_es_init_ninit\n     prog_l_es_init_sb\n     prog_l_es_init_jf\n     prog_l_es_init_sw\n     prog_l_es_init_hb\n     prog_l_es_init_cf\n     prog_l_es_init_psc_f\n     prog_l_es_init_psc_base\n     prog_l_es_init_rmw\n  : prog_l_es_init_db.\n\nLemma prog_l_es_init_consistent locs prog :\n  @es_consistent (prog_l_es_init prog locs) Weakestmo.\nProof.\n  constructor; unfold ecf, ES.jfe, ES.icf.\n  all: autorewrite with prog_l_es_init_db; auto.\n  (* 7: apply acyclic_disj. *)\n  all: basic_solver.\nQed.\n\nLemma prog_g_es_init_consistent G prog :\n  @es_consistent (prog_g_es_init prog G) Weakestmo.\nProof. apply prog_l_es_init_consistent. Qed.\n\nLemma prog_es_init_consistent prog :\n  @es_consistent (prog_es_init prog) Weakestmo.\nProof. apply prog_l_es_init_consistent. Qed.\n\nLemma prog_l_es_init_act_in prog locs\n      e (ACT : ES.acts_set (prog_l_es_init prog locs) e) :\n  exists l,\n    In (e, init_write l)\n       (indexed_list\n          (map init_write (undup locs))).\nProof.\n  ins.\n  assert\n    (exists b,\n        In (e, b) (indexed_list\n                     (map init_write (undup locs))))\n    as [b IN].\n  { apply indexed_list_range. desf. }\n\n  assert (In b (map init_write (undup locs)))\n    as BIN.\n  { clear -IN.\n    apply In_map_snd in IN.\n    rewrite <- indexed_list_map_snd; eauto. }\n\n  apply in_map_iff in BIN. destruct BIN as [l [LB INL]].\n  rewrite <- LB in *. simpls. desf.\n  eauto.\nQed.\n\nLemma prog_g_es_init_act_in prog G\n      e (ACT : ES.acts_set (prog_g_es_init prog G) e) :\n  exists l,\n    In (e, init_write l)\n       (indexed_list\n          (map init_write (g_locs G))).\nProof.\n  apply prog_l_es_init_act_in in ACT.\n  unfold g_locs in *.\n  rewrite undup_nodup in ACT; auto.\nQed.\n\nLemma prog_l_es_init_act_lab prog locs\n      e (ACT : ES.acts_set (prog_l_es_init prog locs) e) :\n  exists l, ES.lab (prog_l_es_init prog locs) e = Astore Xpln Opln l 0.\nProof.\n  apply prog_l_es_init_act_in in ACT. destruct ACT as [l LL].\n  exists l. unfold ES.lab, prog_g_es_init, ES.init.\n  apply l2f_in; desf.\n  apply indexed_list_fst_nodup.\nQed.\n\nLemma prog_g_es_init_act_lab prog G\n      e (ACT : ES.acts_set (prog_g_es_init prog G) e) :\n  exists l, ES.lab (prog_g_es_init prog G) e = Astore Xpln Opln l 0.\nProof. by apply prog_l_es_init_act_lab. Qed.\n\nLemma prog_l_es_init_w locs prog :\n  ES.acts_set (prog_l_es_init prog locs) \u2261\u2081\n  ES.acts_set (prog_l_es_init prog locs) \u2229\u2081\n  (fun a => is_true (is_w (ES.lab (prog_l_es_init prog locs)) a)).\nProof.\n  split; [|basic_solver].\n  unfolder. intros. split; auto.\n  unfold is_w.\n  apply prog_l_es_init_act_lab in H. desf.\nQed.\n\nLemma prog_g_es_init_w G prog :\n  ES.acts_set (prog_g_es_init prog G) \u2261\u2081\n  ES.acts_set (prog_g_es_init prog G) \u2229\u2081\n  (fun a => is_true (is_w (ES.lab (prog_g_es_init prog G)) a)).\nProof. apply prog_l_es_init_w. Qed.\n\nLemma prog_l_es_seqn locs prog x : ES.seqn (prog_l_es_init prog locs) x = 0.\nProof.\n  unfold ES.seqn. autorewrite with prog_l_es_init_db; eauto.\n  relsf.\n  apply countNatP_empty.\nQed.\n\nLemma prog_g_es_seqn G prog x : ES.seqn (prog_g_es_init prog G) x = 0.\nProof. apply prog_l_es_seqn. Qed.\n\nLemma prog_l_es_init_init locs prog :\n  ES.acts_set (prog_l_es_init prog locs) \u2261\u2081\n  ES.acts_init_set (prog_l_es_init prog locs).\nProof. unfold ES.acts_init_set. simpls. basic_solver. Qed.\n\nLemma prog_es_init_init prog :\n  ES.acts_set (prog_es_init prog) \u2261\u2081\n  ES.acts_init_set (prog_es_init prog).\nProof. apply prog_l_es_init_init. Qed.\n\nLemma prog_g_es_init_init G prog :\n  ES.acts_set (prog_g_es_init prog G) \u2261\u2081\n  ES.acts_init_set (prog_g_es_init prog G).\nProof. apply prog_l_es_init_init. Qed.\n\nLemma length_nempty {A : Type} (l : list A) (nEmpty : l <> []) :\n  0 < length l.\nProof.\n  unfold length.\n  destruct l.\n  { intuition. }\n  apply Nat.lt_0_succ.\nQed.\n\nLemma prog_l_es_init_nempty locs prog\n      (nInitProg : ~ IdentMap.In tid_init prog)\n      (nLocsEmpty : locs <> []) :\n  ~ ES.acts_init_set (prog_l_es_init prog locs) \u2261\u2081 \u2205.\nProof.\n  intros HH. eapply HH.\n  apply prog_l_es_init_init.\n  unfold ES.acts_set.\n  unfold prog_l_es_init, ES.init.\n  simpls.\n  erewrite map_length.\n  eapply length_nempty.\n  by apply undup_nonnil.\nQed.\n\nLemma prog_g_es_init_nempty G prog\n      (nInitProg : ~ IdentMap.In tid_init prog)\n      (nLocsEmpty : g_locs G <> []) :\n  ~ ES.acts_init_set (prog_g_es_init prog G) \u2261\u2081 \u2205.\nProof. by apply prog_l_es_init_nempty. Qed.\n\nLemma prog_l_es_init_wf locs prog\n      (nInitProg : ~ IdentMap.In tid_init prog)\n      (nLocsEmpty : locs <> []) :\n  ES.Wf (prog_l_es_init prog locs).\nProof.\n  assert\n    (NoDup (map init_write (undup locs)))\n    as NNDD.\n  { apply nodup_map.\n    2: { ins. intros HH. inv HH. }\n    unfold g_locs. apply nodup_undup. }\n  constructor.\n  all: autorewrite with prog_l_es_init_db; auto.\n  all: simpls.\n  all: try basic_solver.\n  { ins. red. exists b.\n    splits; auto.\n    red. split; auto. }\n  { intros e [AA BB].\n    eapply prog_l_es_init_act_lab; eauto. }\n  { red. ins.\n    destruct SX as [SX _]. apply prog_l_es_init_act_in in SX.\n    destruct SY as [SY _]. apply prog_l_es_init_act_in in SY.\n    desf.\n    assert (l0 = l); subst.\n    { unfold loc, init_write in *.\n      erewrite l2f_in in EQ; eauto.\n      2: by apply indexed_list_fst_nodup.\n      erewrite l2f_in in EQ; eauto.\n      2: by apply indexed_list_fst_nodup.\n      desf. }\n    eapply indexed_list_snd_nodup; eauto. }\n  { apply prog_l_es_init_nempty; eauto. }\n  { red. basic_solver. }\n  { unfolder. ins. eexists.\n    splits; eauto.\n    2: by red.\n    apply prog_l_es_seqn. }\n  { rewrite prog_l_es_init_w. type_solver. }\n  { intros ol a b [[EA _] WA] [[EB _] WB].\n    set (CA := EA). apply prog_l_es_init_act_in in CA. desf.\n    set (CB := EB). apply prog_l_es_init_act_in in CB. desf.\n    assert (l0 = l); subst.\n    { unfold loc, init_write in *.\n      erewrite l2f_in in WB; eauto.\n      2: by apply indexed_list_fst_nodup.\n      erewrite l2f_in in WB; eauto.\n      2: by apply indexed_list_fst_nodup.\n      desf. }\n    unfolder. ins. exfalso. apply nEW. splits; auto.\n    clear -CA CB NNDD.\n    eapply indexed_list_snd_nodup; eauto. }\n  { split; [|basic_solver].\n    unfolder. ins. desf. splits; auto.\n    all: eapply prog_l_es_init_w; eauto.\n    Unshelve. all: auto. }\n  { intros HH. desf.\n    unfold prog_l_es_init, ES.init, ES.cont_thread, ES.cont_set in *.\n    simpls.\n    unfold prog_init_K in KK.\n    apply in_map_iff in KK.\n    desf. destruct x as [tid k]; simpls; desf.\n    apply RegMap.elements_complete in KK0.\n    apply nInitProg.\n    apply RegMap.Facts.in_find_iff.\n    rewrite KK0. desf. }\n  { intros HH. desf. inv RMW. }\n  { unfold prog_l_es_init, ES.init, ES.cont_thread, ES.cont_set in *.\n    simpls.\n    unfold prog_init_K in *.\n    ins.\n    apply in_map_iff in CK. apply in_map_iff in CK'.\n    desf.\n    destruct x. destruct x0.\n    apply RegMap.elements_complete in CK0.\n    apply RegMap.elements_complete in CK'0.\n    simpls; desf. }\n  { ins. by apply prog_l_es_init_ninit in EE. }\n  { ins. exfalso.\n    red in inK.\n    unfold prog_g_es_init, ES.init in *. simpls.\n    unfold prog_init_K in *.\n    apply in_map_iff in inK. desf. }\n  ins. exfalso.\n  unfold ES.cont_adjacent\n    in ADJ.\n  desc.\n  unfold ES.cont_set,\n         ES.cont,\n         prog_g_es_init,\n         prog_init_K\n    in KK'.\n  simpl in KK'.\n  apply in_map_iff in KK'.\n  destruct KK' as [HA [HB HC]].\n  inversion HB. congruence.\nQed.\n\nLemma prog_g_es_init_wf G prog\n      (nInitProg : ~ IdentMap.In tid_init prog)\n      (nLocsEmpty : g_locs G <> []) :\n  ES.Wf (prog_g_es_init prog G).\nProof. by apply prog_l_es_init_wf. Qed.\n\nLemma prog_es_init_wf prog\n      (nInitProg : ~ IdentMap.In tid_init prog)\n      (nLocsEmpty : prog_locs (stable_prog_to_prog prog) <> []) :\n  ES.Wf (prog_es_init prog).\nProof. by apply prog_l_es_init_wf. Qed.\n\nLemma prog_g_es_init_same_lab prog G (WF : Wf G) :\n  eq_dom (ES.acts_set (prog_g_es_init prog G))\n         (ES.lab (prog_g_es_init prog G))\n         (Execution.lab G \u2218 e2a (prog_g_es_init prog G)).\nProof.\n  red. ins.\n  arewrite (undup (g_locs G) = g_locs G).\n  { unfold g_locs. rewrite undup_nodup; auto. }\n  unfold compose.\n\n  apply prog_g_es_init_act_in in DX. desf.\n  rewrite prog_g_es_init_alt.\n  unfold e2a, ES.init, ES.acts_set in *; simpls; desf.\n  unfold Events.loc.\n  erewrite l2f_in; [|by apply indexed_list_fst_nodup|by eauto].\n  simpls. rewrite wf_init_lab; auto.\nQed.\n\nLemma prog_l_es_init_K prog locs k state\n      (INK : ES.cont_set\n               (prog_l_es_init prog locs)\n               (k, existT _\n                     (thread_lts (ES.cont_thread (prog_l_es_init prog locs)\n                                                 k))\n                     state)) :\n  exists thread,\n    \u27ea KTID  : k = CInit thread \u27eb /\\\n    \u27ea STEPS : (istep thread [])\uff0a (init (instrs state)) state \u27eb /\\\n    \u27ea STBL  : stable_state state \u27eb.\nProof.\n  assert (forall A B (c : A) (a b : B)\n                 (OO : (c, a) = (c, b)), a = b) as OO.\n  { ins. inv OO. }\n  ins. red in INK.\n  unfold prog_l_es_init, ES.init, prog_init_K, ES.cont_thread in *.\n  simpls.\n  apply in_map_iff in INK. desc. inv INK.\n  destruct x. simpls. desf.\n  apply OO in INK.\n  inv INK.\n  destruct s; simpls.\n  eexists; splits; eauto.\n  all: pose (AA :=\n               @proj2_sig\n                 _ _\n                 (get_stable t (init x) s\n                             (rt_refl state (step t) (init x)))).\n  arewrite\n    (instrs\n       (proj1_sig\n          (get_stable t (init x) s (rt_refl state (step t) (init x)))) =\n     instrs (init x)).\n  all: red in AA; desf.\n  eapply steps_same_instrs; eauto.\n  apply eps_steps_in_steps. eauto.\nQed.\n\nLemma prog_g_es_init_K prog G k state\n      (INK : ES.cont_set\n               (prog_g_es_init prog G)\n               (k, existT _\n                     (thread_lts (ES.cont_thread (prog_g_es_init prog G)\n                                                 k))\n                     state)) :\n  exists thread,\n    \u27ea KTID  : k = CInit thread \u27eb /\\\n    \u27ea STEPS : (istep thread [])\uff0a (init (instrs state)) state \u27eb /\\\n    \u27ea STBL  : stable_state state \u27eb.\nProof. by apply prog_l_es_init_K. Qed.\n\nLemma prog_l_es_init_lab prog locs e :\n  << ELAB : ES.lab (prog_l_es_init prog locs) e = Afence Orlx >> \\/\n  exists l,\n  << ELAB : ES.lab (prog_l_es_init prog locs) e = init_write l >>.\nProof.\n  unfold prog_l_es_init, ES.init. simpls.\n  unnw.\n  edestruct @l2f_v with (A:=nat)\n                        (l:=indexed_list (map init_write (undup locs)))\n                        (a:=e)\n                        (DEC:=Nat.eq_dec).\n  { apply indexed_list_fst_nodup. }\n\n  2: { desf. left. eauto. }\n  desf. right.\n  generalize dependent e.\n  unfold indexed_list in *.\n  remember 0 as n. clear Heqn.\n  generalize dependent n.\n  induction (undup locs); simpls.\n  ins. desf; eauto.\nQed.\n\nLemma prog_g_es_init_lab prog G e :\n  << ELAB : ES.lab (prog_g_es_init prog G) e = Afence Orlx >> \\/\n  exists l,\n  << ELAB : ES.lab (prog_g_es_init prog G) e = init_write l >>.\nProof. apply prog_l_es_init_lab. Qed.\n\nLemma traverse_map_indexed_list {A B} (f : A -> B) l :\n  indexed_list (map f l) =\n  map (fun p : nat * A => let (a, b) := p in (a, f b))\n      (indexed_list l).\nProof.\n  unfold indexed_list in *.\n  remember 0 as n. clear Heqn.\n  generalize dependent n.\n  induction l; simpls.\n  congruence.\nQed.\n\nLemma prog_l_es_init_init_loc prog locs :\n  (fun l => In l locs) \u2261\u2081 ES.init_loc (prog_l_es_init prog locs).\nProof.\n  split.\n  { intros l L_IN.\n    apply in_undup_iff in L_IN.\n    specialize (indexed_list_in_exists l (undup locs) L_IN) as [e Foo].\n    exists e. splits.\n    { apply prog_l_es_init_init.\n      unfold prog_l_es_init, ES.init.\n      unfold ES.acts_set, ES.next_act. rewrite length_map.\n      apply indexed_list_range. eauto. }\n    unfold prog_l_es_init, ES.init. simpl.\n    unfold Events.loc.\n    arewrite ((list_to_fun\n                 Nat.eq_dec\n                 (Afence Orlx)\n                 (indexed_list (map init_write (undup locs)))) e =\n              init_write l); [|done].\n    apply l2f_in.\n    { apply indexed_list_fst_nodup. }\n    rewrite traverse_map_indexed_list.\n    eapply in_map with\n        (f := (fun p : nat * location => let (a, b) := p in (a, init_write b))) in Foo.\n    auto. }\n  intros l [a HH]. desf.\n  unfold prog_l_es_init, ES.init, ES.lab in LOCA.\n  specialize (l2f_codom (indexed_list (map init_write (undup locs)))\n                        a\n                        (Afence Orlx) Nat.eq_dec) as RR.\n  desf; unfold loc in LOCA; desf.\n  all: rewrite traverse_map_indexed_list in RR;\n    apply in_map_iff in RR; desf.\n  apply In_map_snd in RR0.\n  rewrite indexed_list_map_snd in RR0.\n  by apply in_undup_iff.\nQed.\n\nLemma prog_g_init_init_loc prog G :\n  (fun l => In l (g_locs G)) \u2261\u2081 ES.init_loc (prog_g_es_init prog G).\nProof. by apply prog_l_es_init_init_loc. Qed.\n\nLemma prog_es_init_init_loc prog :\n  (fun l => In l (prog_locs (stable_prog_to_prog prog))) \u2261\u2081 ES.init_loc (prog_es_init prog).\nProof. by apply prog_l_es_init_init_loc. Qed.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/construction/ProgES.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.19647809611685552}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\n\nRequire Import SplitAcqCommon.\n\nSet Implicit Arguments.\n\n\nDefinition local_acqrel (lc:Local.t) :=\n  (Local.mk (TView.write_fence_tview\n               (TView.read_fence_tview (Local.tview lc) Ordering.acqrel)\n               TimeMap.bot\n               Ordering.acqrel)\n            (Local.promises lc)).\n\nLemma sim_local_promise_acqrel\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acqrel lc1_tgt))\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise_bot; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_fulfill_acqrel\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.acqrel)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { unfold TView.write_released, TView.write_tview. ss. viewtac.\n    repeat (condtac; aggrtac;\n            try match goal with\n                | [|- View.opt_le _ _] => econs\n                end);\n      try apply WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove_bot; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  i. des. esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n  - econs; eauto. s.\n    unfold TView.write_tview, TView.write_fence_tview, TView.read_fence_tview. ss.\n    econs; ss; repeat (condtac; aggrtac).\n    all: try by destruct ord_src, ord_tgt.\n    all: try by apply WF1_TGT.\n    + etrans; [apply LOCAL1|]. repeat (try condtac; aggrtac).\n    + etrans; [apply LOCAL1|]. aggrtac.\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. repeat (try condtac; aggrtac).\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. ss. condtac; aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n  - ss.\nQed.\n\nLemma sim_local_write_acqrel\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.acqrel)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise_acquired; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  hexploit sim_local_fulfill_acqrel; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { inv STEP_SRC. inv STEP1. ss. }\n  i. des.\n  exploit promise_fulfill_write_sim_memory; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    i. des. splits; auto. eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto. etrans; eauto.\nQed.\n", "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/SplitAcqRelCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19647809236561004}}
{"text": "Require Import AutoSep Malloc Bootstrap CountUnique.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Require ExampleImpl.\n\n  Definition m0 := link ExampleImpl.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link ExampleImpl.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($(size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/examples/CountUniqueDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19647808861436467}}
{"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.\nFrom iris Require Import options.\n\nDefinition assert : val :=\n  \u03bb: \"v\", if: \"v\" #() then #() else #0 #0. (* #0 #0 is unsafe *)\n(* just below ;; *)\nNotation \"'assert:' e\" := (assert (\u03bb: <>, e)%E) (at level 99) : expr_scope.\nNotation \"'assert:' e\" := (assert (\u03bb: <>, e)%V) (at level 99) : val_scope.\n\nLemma twp_assert `{!heapG \u03a3} E (\u03a6 : val \u2192 iProp \u03a3) e :\n  WP e @ E [{ v, \u231cv = #true\u231d \u2227 \u03a6 #() }] -\u2217\n  WP (assert: e)%V @ E [{ \u03a6 }].\nProof.\n  iIntros \"H\u03a6\". wp_lam.\n  wp_apply (twp_wand with \"H\u03a6\"). iIntros (v) \"[% ?]\"; subst. by wp_if.\nQed.\n\nLemma wp_assert `{!heapG \u03a3} E (\u03a6 : val \u2192 iProp \u03a3) e :\n  WP e @ E {{ v, \u231cv = #true\u231d \u2227 \u25b7 \u03a6 #() }} -\u2217\n  WP (assert: e)%V @ E {{ \u03a6 }}.\nProof.\n  iIntros \"H\u03a6\". wp_lam.\n  wp_apply (wp_wand with \"H\u03a6\"). iIntros (v) \"[% ?]\"; subst. by wp_if.\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/heap_lang/lib/assert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.1964780886143646}}
{"text": "Require Import RGref.DSL.DSL.\nRequire Import Coq.Arith.Arith.\n\nSection MemoTable.\n\n  (* Apparently the instances below stick around after the section ends... *)\n  Variable B : nat -> Set.\n  Variable f : forall (x:nat), B x.\n  Parameter safe_f : Safe f.\n  Existing Instance safe_f.\n  Parameter safe_B : Safe B.\n  Existing Instance safe_B.\n\n  Definition prefernat {P:nat->Set}(g:forall x:nat, P x)(a:nat) : forall x:nat, P x.\n    refine(let v := g a in\n             (fun x => if eq_nat_dec x a then _ else g x)).\n    subst. exact v.\n  Defined.\n  Print prefernat.\n\n  Definition obs_equiv {A:Set}{P:A->Set}(f g:forall x, P x)(_ _:heap) :=\n    forall x, f x = g x.\n  Lemma obs_eq_refl : forall A P, hreflexive (@obs_equiv A P).\n  Proof. intros; red. compute. eauto. Qed.\n  Hint Resolve obs_eq_refl.\n  Lemma precise_obs_equiv : precise_rel (@obs_equiv nat (fun _ => nat)).\n  Proof. compute. intuition. Qed.\n  Hint Resolve precise_obs_equiv.\n\n  Instance safe_prefernat : Safe (@prefernat).\n(*  Instance prior_safe (r:ref{forall x:nat,B x|any}[obs_equiv,obs_equiv]) (n:nat)\n    : Safe (@prefernat B (@deref _ _ _ _ _ _ (obs_eq_refl _ _) eq_refl r) n). *)\n  Instance prior_safe (r:ref{forall x:nat,B x|any}[obs_equiv,obs_equiv]) (n:nat)\n                              : ESafe 0 (@prefernat B f n).\n    repeat solve_applications.\n  Defined.\n    \n  Program Definition prioritize {\u0393} (r:ref{forall x:nat,B x|any}[obs_equiv,obs_equiv]) (n:nat) : rgref \u0393 unit \u0393 :=\n    [r]:= prefernat (!r) n.\n  Next Obligation.\n    repeat solve_applications.\n  Qed.\n  Next Obligation.\n    red. unfold prefernat. intros. induction (eq_nat_dec x n); intuition; eauto.\n    subst. compute. eauto.\n  Qed.\n(* Doesn't (and shouldn't!) typecheck *)\n  Program Example should_not_typecheck {\u0393} (r:ref{nat|any}[havoc,havoc]) : rgref \u0393 (ref{nat->nat|any}[havoc,havoc]) \u0393 :=\n    Alloc (fun x => !r). (*;\n    prioritize _ r 0.\n  (*Print should_not_typecheck.*)\n*)\n  Next Obligation. compute; eauto. Defined.\n  Next Obligation.\n    (* Cannot typecheck because (\u03bb x:N. !r) is in fact not safe! *)\n  Admitted.\n\nEnd MemoTable.", "meta": {"author": "csgordon", "repo": "rgref", "sha": "9f66be539d584b0a1ca18f67a13c07dc6b4d310a", "save_path": "github-repos/coq/csgordon-rgref", "path": "github-repos/coq/csgordon-rgref/rgref-9f66be539d584b0a1ca18f67a13c07dc6b4d310a/MemoTable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19616157901501396}}
{"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\nRequire Import Pred.\n\nRequire Import SeqLiftStep.\n\n\nVariant sim_thread_sol\n        (c: bool)\n        (vs: Loc.t -> Const.t)\n        (P: Loc.t -> bool)\n        (D: Loc.t -> bool)\n        mem lc: Prop :=\n  | sim_thread_intro\n      (CONS: Local.promise_consistent lc)\n      (DEBT: forall loc to from msg\n                    (GET: Memory.get loc to lc.(Local.promises) = Some (from, msg)),\n          (<<MSG: msg <> Message.reserve>>) /\\ (<<DEBT: c = true -> D loc>>))\n      (NSYNC: forall loc, Memory.nonsynch_loc loc lc.(Local.promises))\n      (VALS: forall loc,\n        exists from released,\n          (<<GET: Memory.get loc (lc.(Local.tview).(TView.cur).(View.rlx) loc) mem = Some (from, Message.concrete (vs loc) released)>>))\n      (PERM: forall loc val released (MAX: max_readable mem lc.(Local.promises) loc (lc.(Local.tview).(TView.cur).(View.pln) loc) val released),\n          P loc)\n.\n\nDefinition lowered_content (b: bool) (cnt0 cnt1: option (Time.t * Message.t)): Prop :=\n  (cnt0 = cnt1 /\\ b = false) \\/\n    cnt1 = match cnt0 with\n           | Some (_, Message.reserve) | None => None\n           | Some (from, Message.undef) => Some (from, Message.undef)\n           | Some (from, Message.concrete val released) => Some (from, Message.concrete val None)\n           end.\n\nLemma lowered_content_trans b0 b1 b2 cnt0 cnt1 cnt2\n      (LOWER0: lowered_content b0 cnt0 cnt1)\n      (LOWER1: lowered_content b1 cnt1 cnt2)\n      (BOOL: b0 = false -> b1 = false -> b2 =false)\n  :\n  lowered_content b2 cnt0 cnt2.\nProof.\n  unfold lowered_content in *. des; subst; auto.\n  right. des_ifs.\nQed.\n\nDefinition lowered_memory mem0 mem1: Prop :=\n  forall loc to, lowered_content false (Memory.get loc to mem0) (Memory.get loc to mem1).\n\nGlobal Program Instance lowered_memory_PreOrder: PreOrder lowered_memory.\nNext Obligation.\nProof.\n  ii. left. auto.\nQed.\nNext Obligation.\nProof.\n  ii. specialize (H loc to). specialize (H0 loc to).\n  eapply lowered_content_trans; eauto.\nQed.\n\nLemma lower_none_lowered_memory mem0 loc from to val released mem1\n      (LOWER: Memory.lower mem0 loc from to (Message.concrete val released) (Message.concrete val None) mem1)\n  :\n  lowered_memory mem0 mem1.\nProof.\n  ii. erewrite (@Memory.lower_o mem1); eauto. des_ifs.\n  { ss. des; clarify. right.\n    eapply Memory.lower_get0 in LOWER. des. rewrite GET. ss.\n  }\n  { left. auto. }\nQed.\n\nLemma cancel_lowered_memory mem0 loc from to  mem1\n      (CANCEL: Memory.remove mem0 loc from to Message.reserve mem1)\n  :\n  lowered_memory mem0 mem1.\nProof.\n  ii. erewrite (@Memory.remove_o mem1); eauto. des_ifs.\n  { ss. des; clarify. right.\n    eapply Memory.remove_get0 in CANCEL. des. rewrite GET. ss.\n  }\n  { left. auto. }\nQed.\n\nLemma nonsynch_all\n      lang st\n      tvw prom0 mem0 sc\n      (LOCAL: Local.wf (Local.mk tvw prom0) mem0)\n  :\n  exists prom1 mem1,\n    (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk _ st (Local.mk tvw prom0) sc mem0) (Thread.mk _ st (Local.mk tvw prom1) sc mem1)>>) /\\\n      (<<NONE: forall loc to,\n          Memory.get loc to prom1 = match Memory.get loc to prom0 with\n                                    | Some (_, Message.reserve) | None => None\n                                    | Some (from, Message.undef) => Some (from, Message.undef)\n                                    | Some (from, Message.concrete val released) => Some (from, Message.concrete val None)\n                                    end>>) /\\\n      (<<MAX: forall loc val released,\n          max_readable mem0 prom0 loc (tvw.(TView.cur).(View.pln) loc) val released\n          <->\n            max_readable mem1 prom1 loc (tvw.(TView.cur).(View.pln) loc) val released>>) /\\\n      (<<PRESERVE: forall loc to val released from\n                          (GET: Memory.get loc to mem0 = Some (from, Message.concrete val released)),\n        exists released', (<<GET: Memory.get loc to mem1 = Some (from, Message.concrete val released')>>)>>)\n.\nProof.\n  inv LOCAL. clear TVIEW_WF TVIEW_CLOSED. rename PROMISES into MLE.\n  red in FINITE. des.\n  cut (exists prom1 mem1,\n             (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk _ st (Local.mk tvw prom0) sc mem0) (Thread.mk _ st (Local.mk tvw prom1) sc mem1)>>) /\\\n               (<<NONE: forall loc to (IN: List.In (loc, to) dom),\n                   lowered_content true (Memory.get loc to prom0) (Memory.get loc to prom1)>>) /\\\n               (<<MAX: forall loc val released,\n                   max_readable mem0 prom0 loc (tvw.(TView.cur).(View.pln) loc) val released\n                   <->\n                     max_readable mem1 prom1 loc (tvw.(TView.cur).(View.pln) loc) val released>>) /\\\n               (<<LOWERPROM: lowered_memory prom0 prom1>>) /\\\n               (<<LOWERMEM: lowered_memory mem0 mem1>>)).\n  { i. des. esplits; eauto.\n    { i. specialize (NONE loc to). unfold lowered_content in *.\n      destruct (Memory.get loc to prom0) as [[from msg]|] eqn:PROM.\n      { hexploit NONE; eauto. i; des; ss. }\n      { specialize (LOWERPROM loc to). rewrite PROM in LOWERPROM.\n        red in LOWERPROM. des; auto.\n      }\n    }\n    { i. specialize (LOWERMEM loc to). rewrite GET in LOWERMEM. des; eauto.\n      red in LOWERMEM. des; eauto.\n    }\n  }\n  clear FINITE. revert prom0 mem0 MLE BOT. induction dom.\n  { i. esplits.\n    { refl. }\n    { i. ss. }\n    { auto. }\n    { refl. }\n    { refl. }\n  }\n  i. destruct a as [loc to].\n  destruct (Memory.get loc to prom0) as [[from msg]|] eqn:GET.\n  { destruct msg.\n    { hexploit Memory.lower_exists.\n      { eapply GET. }\n      { hexploit memory_get_ts_strong; eauto. i. des; clarify.\n        rewrite BOT in GET. ss.\n      }\n      { instantiate (1:=Message.concrete val None). econs; ss. }\n      { econs; ss. refl. }\n      i. des.\n      hexploit Memory.lower_exists_le; eauto. i. des.\n      assert (PROMISE: Memory.promise prom0 mem0 loc from to (Message.concrete val None) mem2 mem1 (Memory.op_kind_lower (Message.concrete val released))).\n      { econs; eauto; ss. econs. eapply Time.bot_spec. }\n      hexploit (IHdom mem2 mem1); eauto.\n      { eapply promise_memory_le; eauto. }\n      { eapply Memory.promise_bot_none; eauto. }\n      i. des. esplits.\n      { econs 2.\n        { econs.\n          { econs. econs 1. econs; eauto. }\n          { ss. }\n        }\n        { eauto. }\n      }\n      { i. ss. des; clarify.\n        { eapply lowered_content_trans.\n          2:{ eapply LOWERPROM. }\n          2:{ instantiate (1:=true). ss. }\n          des; clarify.\n          { rewrite GET. erewrite (@Memory.lower_o mem2); eauto.\n            des_ifs; ss; des; clarify. right. auto.\n          }\n        }\n        { eapply lowered_content_trans.\n          2:{ eapply NONE; eauto. }\n          2:{ instantiate (1:=false). ss. }\n          eapply lower_none_lowered_memory; eauto.\n        }\n      }\n      { i. etrans; [|eapply MAX]. destruct (Loc.eq_dec loc0 loc); subst.\n        { eapply promise_max_readable; eauto. }\n        { eapply promise_unchanged_loc in PROMISE; eauto. des.\n          eapply unchanged_loc_max_readable; eauto.\n        }\n      }\n      { etrans; eauto. eapply lower_none_lowered_memory; eauto. }\n      { etrans; eauto. eapply lower_none_lowered_memory; eauto. }\n    }\n    { hexploit (IHdom prom0 mem0); eauto. i. des. esplits; eauto.\n      i. ss. des; clarify.\n      { eapply lowered_content_trans.\n        2:{ eapply LOWERPROM. }\n        2:{ instantiate (1:=true). ss. }\n        rewrite GET. right. auto.\n      }\n      { eapply NONE; auto. }\n    }\n    { hexploit Memory.remove_exists.\n      { eapply GET. }\n      i. des.\n      hexploit Memory.remove_exists_le; eauto. i. des.\n      assert (PROMISE: Memory.promise prom0 mem0 loc from to Message.reserve mem2 mem1 (Memory.op_kind_cancel)).\n      { econs; eauto; ss. }\n      hexploit (IHdom mem2 mem1); eauto.\n      { eapply promise_memory_le; eauto. }\n      { eapply Memory.promise_bot_none; eauto. }\n      i. des. esplits.\n      { econs 2.\n        { econs.\n          { econs. econs 1. econs; eauto. }\n          { ss. }\n        }\n        { eauto. }\n      }\n      { i. ss. des; clarify.\n        { eapply lowered_content_trans.\n          2:{ eapply LOWERPROM. }\n          2:{ instantiate (1:=true). ss. }\n          des; clarify.\n          { rewrite GET. erewrite (@Memory.remove_o mem2); eauto.\n            des_ifs; ss; des; clarify. right. auto.\n          }\n        }\n        { eapply lowered_content_trans.\n          2:{ eapply NONE; eauto. }\n          2:{ instantiate (1:=false). ss. }\n          eapply cancel_lowered_memory; eauto.\n        }\n      }\n      { i. etrans; [|eapply MAX]. destruct (Loc.eq_dec loc0 loc); subst.\n        { eapply promise_max_readable; eauto. }\n        { eapply promise_unchanged_loc in PROMISE; eauto. des.\n          eapply unchanged_loc_max_readable; eauto.\n        }\n      }\n      { etrans; eauto. eapply cancel_lowered_memory; eauto. }\n      { etrans; eauto. eapply cancel_lowered_memory; eauto. }\n    }\n  }\n  { hexploit (IHdom prom0 mem0); eauto. i. des. esplits; eauto.\n    i. ss. des; clarify.\n    { eapply lowered_content_trans.\n      2:{ eapply LOWERPROM. }\n      2:{ instantiate (1:=true). ss. }\n      rewrite GET. right. auto.\n    }\n    { eapply NONE; auto. }\n  }\nQed.\n\nLemma sim_thread_sim_thread_sol\n      c D f vers flag_src flag_tgt vs_src vs_tgt\n      mem_src0 mem_tgt lc_src0 lc_tgt sc_src sc_tgt\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      (BOT: c = true -> lc_tgt.(Local.promises) = Memory.bot)\n      (CONSTGT: Local.promise_consistent lc_tgt)\n      (DEBT: forall loc (TGT: flag_src loc = false) (DEBT: D loc = false), flag_tgt loc = false)\n      (WF: Mapping.wfs f)\n      (LOCAL: Local.wf lc_src0 mem_src0)\n      lang st\n  :\n  exists mem_src1 lc_src1 vs,\n    (<<STEPS: rtc (@Thread.tau_step lang) (Thread.mk _ st lc_src0 sc_src mem_src0) (Thread.mk _ st lc_src1 sc_src mem_src1)>>) /\\\n      (<<SIM: sim_thread_sol c vs (fun loc => vs_src loc) D mem_src1 lc_src1>>) /\\\n      (<<VALS: forall loc val (VAL: vs_src loc = Some val), vs loc = val>>)\n.\nProof.\n  hexploit (choice (fun loc val =>\n                      exists from released,\n                        (<<GET: Memory.get loc (lc_src0.(Local.tview).(TView.cur).(View.rlx) loc) mem_src0 = Some (from, Message.concrete val released)>>))).\n  { inv LOCAL. inv TVIEW_CLOSED. inv CUR.\n    intros loc. hexploit (RLX loc). i. des. eauto.\n  }\n  intros [vs VALS]. inv SIM.\n  assert (CONSSRC: Local.promise_consistent lc_src0).\n  { eapply sim_local_consistent; eauto. }\n  destruct lc_src0 as [tvw_src prom_src0].\n  hexploit nonsynch_all; eauto. i. des.\n  exists mem1, (Local.mk tvw_src prom1), vs. splits.\n  { eauto. }\n  { econs; eauto.\n    { ii. ss. rewrite NONE in PROMISE. des_ifs.\n      { eapply CONSSRC; eauto; ss. }\n      { eapply CONSSRC; eauto; ss. }\n    }\n    { inv LOCAL0. i. ss.\n      assert (exists msg', Memory.get loc to prom_src0 = Some (from, msg') /\\ msg <> Message.reserve).\n      { rewrite NONE in GET. des_ifs.\n        { esplits; eauto; ss. }\n        { esplits; eauto; ss. }\n      }\n      des. splits; auto. i. subst.\n      hexploit sim_promises_get_if; eauto. i. des.\n      { rewrite BOT in GET0; auto. rewrite Memory.bot_get in GET0. ss. }\n      { destruct (flag_src loc) eqn:EQ.\n        { erewrite sim_promises_none in H; eauto. ss. }\n        { destruct (D loc) eqn:DEBT0; eauto. hexploit DEBT; eauto. i. des; clarify. }\n      }\n    }\n    { ii. ss. rewrite NONE in GET. des_ifs. }\n    { i. ss. specialize (VALS loc). des. hexploit PRESERVE; eauto. }\n    { i. ss. ss. hexploit (MAXSRC loc). i. inv H.\n      destruct (vs_src loc) eqn:VAL; ss.\n      exfalso. eapply NONMAX; eauto. eapply MAX; eauto.\n    }\n  }\n  { i. hexploit (MAXSRC loc). i. inv H.\n    hexploit (VALS loc). i.\n    hexploit MAX0; eauto. i. des. ss. inv MAX1.\n    assert (TS: View.pln (TView.cur tvw_src) loc = View.rlx (TView.cur tvw_src) loc).\n    { eapply TimeFacts.antisym.\n      { eapply LOCAL. }\n      destruct (Time.le_lt_dec (View.rlx (TView.cur tvw_src) loc) (View.pln (TView.cur tvw_src) loc)); auto.\n      exfalso. eapply MAX2 in l; eauto; ss.\n      exploit CONSSRC; eauto; ss. i. timetac.\n    }\n    rewrite TS in *. clarify.\n  }\nQed.\n\nLemma sim_thread_none\n      vs P D mem lc\n      (SIM: sim_thread_sol true vs P D mem lc)\n      (DEBT: forall loc, D loc = false)\n  :\n  lc.(Local.promises) = Memory.bot.\nProof.\n  eapply Memory.ext. i. rewrite Memory.bot_get.\n  inv SIM. destruct (Memory.get loc ts lc.(Local.promises)) eqn:GET; auto.\n  destruct p. exploit DEBT0; eauto. i. des.\n  exfalso. hexploit DEBT1; eauto. rewrite DEBT. ss.\nQed.\n\nLemma sim_thread_sol_failure\n      c vs P D mem lc\n      (SIM: sim_thread_sol c vs P D mem lc)\n  :\n  Local.failure_step lc.\nProof.\n  inv SIM. econs. eauto.\nQed.\n\nLemma sim_thread_sol_fence\n      c vs P D mem lc0 sc ordr ordw\n      (SIM: sim_thread_sol c vs P D mem lc0)\n      (ORDR: ~ Ordering.le Ordering.acqrel ordr)\n      (ORDW: ~ Ordering.le Ordering.seqcst ordw)\n  :\n  exists lc1,\n    (<<FENCE: Local.fence_step lc0 sc ordr ordw lc1 sc>>) /\\\n    (<<SIM: sim_thread_sol c vs P D mem lc1>>)\n.\nProof.\n  inv SIM. esplits.\n  { econs; eauto.\n    { destruct ordw; ss. }\n    { i. destruct ordw; ss. }\n  }\n  econs; eauto; ss.\n  { ii. ss. des_ifs. eapply CONS; eauto. }\n  { ii. des_ifs. }\n  { ii. des_ifs. eapply PERM; eauto. }\nQed.\n\nLemma sim_thread_sol_racy\n      c vs P D mem lc loc\n      (SIM: sim_thread_sol c vs P D mem lc)\n      (LOCAL: Local.wf lc mem)\n      (ORD: ~ P loc)\n  :\n  exists to, Local.is_racy lc mem loc to Ordering.na.\nProof.\n  inv SIM. destruct lc.\n  hexploit non_max_readable_race; eauto.\nQed.\n\nLemma sim_thread_sol_read_na_racy\n      c vs P D mem lc loc\n      (SIM: sim_thread_sol c vs P D mem lc)\n      (LOCAL: Local.wf lc mem)\n      (ORD: ~ P loc)\n      val\n  :\n  exists to, Local.racy_read_step lc mem loc to val Ordering.na.\nProof.\n  exploit sim_thread_sol_racy; eauto. i. des.\n  esplits. eauto.\nQed.\n\nLemma sim_thread_sol_write_na_racy\n      c vs P D mem lc loc\n      (SIM: sim_thread_sol c vs P D mem lc)\n      (LOCAL: Local.wf lc mem)\n      (ORD: ~ P loc)\n  :\n  exists to, Local.racy_write_step lc mem loc to Ordering.na.\nProof.\n  exploit sim_thread_sol_racy; eauto. i. des.\n  esplits. econs; eauto.\n  inv SIM. auto.\nQed.\n\nLemma sim_thread_sol_read_na\n      c vs P D mem lc loc val\n      (SIM: sim_thread_sol c vs P D mem lc)\n      (LOCAL: Local.wf lc mem)\n      (VAL: Const.le val (vs loc))\n  :\n  exists ts released,\n    (<<READ: Local.read_step lc mem loc ts val released Ordering.na lc>>)\n.\nProof.\n  inv SIM. hexploit (VALS loc); eauto. i. des.\n  esplits. econs; eauto.\n  { econs; ss. eapply LOCAL. }\n  destruct lc. f_equal. ss. unfold TView.read_tview. des_ifs.\n  ss. rewrite ! View.join_bot_r. rewrite ! View.le_join_l.\n  { destruct tview; auto. }\n  { eapply View.singleton_rw_spec.\n    { eapply LOCAL. }\n    { eapply LOCAL. }\n  }\n  { eapply View.singleton_rw_spec.\n    { eapply LOCAL. }\n    { refl. }\n  }\nQed.\n\nLemma sim_thread_sol_read\n      c vs P D mem lc0 loc ord val\n      (SIM: sim_thread_sol c vs P D mem lc0)\n      (LOCAL: Local.wf lc0 mem)\n      (ORD: ~ Ordering.le Ordering.acqrel ord)\n      (VAL: Const.le val (vs loc))\n  :\n  exists ts released lc1,\n    (<<READ: Local.read_step lc0 mem loc ts val released ord lc1>>) /\\\n    (<<SIM: sim_thread_sol c vs (fun loc0 => if (Loc.eq_dec loc0 loc) then true else P loc0) D mem lc1>>)\n.\nProof.\n  inv SIM. hexploit (VALS loc); eauto. i. des.\n  esplits. econs; eauto.\n  { econs; ss.\n    { eapply LOCAL. }\n    { i. refl. }\n  }\n  destruct lc0 as [tvw0 prom]. ss.\n  set (tvw1 := (TView.read_tview\n                  tvw0 loc\n                  (View.rlx (TView.cur tvw0) loc) released ord)).\n  assert (OTHERPLN: forall loc0 (NEQ: loc0 <> loc),\n             tvw1.(TView.cur).(View.pln) loc0 = tvw0.(TView.cur).(View.pln) loc0).\n  { i. ss. des_ifs. ss. rewrite timemap_bot_join_r.\n    unfold TimeMap.join. eapply TimeFacts.le_join_l.\n    unfold View.singleton_ur_if. des_ifs; ss.\n    { rewrite timemap_singleton_neq; auto. eapply Time.bot_spec. }\n    { eapply Time.bot_spec. }\n  }\n  assert (RLX: forall loc0, tvw1.(TView.cur).(View.rlx) loc0 = tvw0.(TView.cur).(View.rlx) loc0).\n  { i. ss. des_ifs. ss. rewrite timemap_bot_join_r.\n    unfold TimeMap.join. eapply TimeFacts.le_join_l.\n    unfold View.singleton_ur_if. des_ifs; ss.\n    { eapply TimeMap.singleton_spec. refl. }\n    { eapply TimeMap.singleton_spec. refl. }\n  }\n  remember tvw1. clear tvw1 Heqt.\n  econs; eauto; ss.\n  { ii. ss. rewrite RLX. eapply CONS; eauto. }\n  { i. rewrite RLX. eauto. }\n  { i. destruct (Loc.eq_dec loc0 loc); auto.\n    rewrite OTHERPLN in MAX; eauto.\n  }\nQed.\n\nLemma sim_thread_sol_write_na\n      c vs P D mem0 lc0 sc loc val\n      (SIM: sim_thread_sol c vs P D mem0 lc0)\n      (LOCAL: Local.wf lc0 mem0)\n      (MEM: Memory.closed mem0)\n      lang st\n  :\n  (exists to, Local.racy_write_step lc0 mem0 loc to Ordering.na)\n  \\/\n  exists lc1 mem1 lc2 mem2 from to msgs kinds kind,\n    (<<STEPS: rtc (@Thread.tau_step _)\n                  (Thread.mk lang st lc0 sc mem0)\n                  (Thread.mk _ st lc1 sc mem1)>>) /\\\n    (<<WRITE: Local.write_na_step lc1 sc mem1 loc from to val Ordering.na lc2 sc mem2 msgs kinds kind>>) /\\\n    (<<SIM: sim_thread_sol c (fun loc0 => if Loc.eq_dec loc0 loc then val else vs loc0) (fun loc0 => if (Loc.eq_dec loc0 loc) then true else P loc0) (fun loc0 => if (Loc.eq_dec loc0 loc) then false else D loc0) mem2 lc2>>)\n.\nProof.\n  destruct lc0 as [tvw0 prom0].\n  destruct (classic (exists val released, <<MAX: max_readable mem0 prom0 loc (tvw0.(TView.cur).(View.pln) loc) val released>>)).\n  2:{ left. inv SIM.\n      exploit non_max_readable_race; eauto. i. des. eauto. }\n  right. des.\n  inv SIM. hexploit max_readable_na_write_step; eauto.\n  { i. exploit NSYNC; eauto. }\n  { refl. }\n  { eapply Time.incr_spec. }\n  { eapply Time.incr_spec. }\n  i. des. esplits.\n  { eapply reserve_future_steps. eapply cancel_future_reserve_future; eauto. }\n  { eauto. }\n  assert (OTHERPLN: forall loc0 (NEQ: loc0 <> loc),\n             tvw1.(TView.cur).(View.pln) loc0 = tvw0.(TView.cur).(View.pln) loc0).\n  { inv WRITE. i. ss. des_ifs. ss.\n    unfold TimeMap.join. eapply TimeFacts.le_join_l.\n    rewrite timemap_singleton_neq; auto. eapply Time.bot_spec.\n  }\n  assert (OTHERRLX: forall loc0 (NEQ: loc0 <> loc),\n             tvw1.(TView.cur).(View.rlx) loc0 = tvw0.(TView.cur).(View.rlx) loc0).\n  { inv WRITE. i. ss. des_ifs. ss.\n    unfold TimeMap.join. eapply TimeFacts.le_join_l.\n    rewrite timemap_singleton_neq; auto. eapply Time.bot_spec.\n  }\n  assert (SAMERLX: tvw1.(TView.cur).(View.rlx) loc = tvw1.(TView.cur).(View.pln) loc).\n  { rewrite VIEW. inv WRITE. clarify. ss.\n    unfold TimeMap.join. rewrite timemap_singleton_eq.\n    eapply TimeFacts.le_join_r.\n    hexploit (VALS loc). i. des.\n    eapply Memory.max_ts_spec in GET. des. etrans; eauto.\n    left. etrans; eapply Time.incr_spec.\n  }\n  econs.\n  { ii. ss. rewrite PROMISES in PROMISE. des_ifs.\n    rewrite OTHERRLX; eauto.\n  }\n  { ii. ss. rewrite PROMISES in GET. des_ifs. eauto. }\n  { ii. ss. rewrite PROMISES in GET. des_ifs. eapply NSYNC in GET; eauto. }\n  { ii. ss. des_ifs.\n    { rewrite SAMERLX. rewrite VIEW. inv MAX0. eauto. }\n    { erewrite Memory.add_o; eauto.\n      erewrite Memory.add_o; eauto. des_ifs.\n      { ss. des; clarify. }\n      { ss. des; clarify. }\n      clear o. rewrite OTHERRLX; auto.\n      inv LOWER. rewrite OTHER; auto.\n    }\n  }\n  { i. ss. des_ifs.\n    inv WRITE. clarify. eapply na_write_unchanged_loc in WRITE0; eauto.\n    eapply cancel_future_unchanged_loc in RESERVE; eauto. des.\n    rewrite OTHERPLN in MAX1; auto.\n    des. eapply PERM. eapply unchanged_loc_max_readable; [..|eauto].\n    { etrans; eauto. }\n    { etrans; eauto. }\n  }\nQed.\n\nLemma write_tview_other_rlx\n      tvw sc loc ts ord loc0\n      (NEQ: loc0 <> loc)\n  :\n  (TView.write_tview tvw sc loc ts ord).(TView.cur).(View.rlx) loc0 = tvw.(TView.cur).(View.rlx) loc0.\nProof.\n  ss. des_ifs. ss.\n  unfold TimeMap.join. eapply TimeFacts.le_join_l.\n  rewrite timemap_singleton_neq; auto. eapply Time.bot_spec.\nQed.\n\nLemma write_tview_other_pln\n      tvw sc loc ts ord loc0\n      (NEQ: loc0 <> loc)\n  :\n  (TView.write_tview tvw sc loc ts ord).(TView.cur).(View.pln) loc0 = tvw.(TView.cur).(View.pln) loc0.\nProof.\n  ss. des_ifs. ss.\n  unfold TimeMap.join. eapply TimeFacts.le_join_l.\n  rewrite timemap_singleton_neq; auto. eapply Time.bot_spec.\nQed.\n\nLemma write_tview_same_pln\n      tvw sc loc ts ord\n      (WRITABLE: TView.writable tvw.(TView.cur) sc loc ts ord)\n      (TVIEW: TView.wf tvw)\n  :\n  (TView.write_tview tvw sc loc ts ord).(TView.cur).(View.pln) loc = ts.\nProof.\n  ss. unfold TimeMap.join.\n  rewrite timemap_singleton_eq; auto. eapply TimeFacts.le_join_r.\n  transitivity (View.rlx (TView.cur tvw) loc).\n  { eapply TVIEW. }\n  { left. eapply WRITABLE. }\nQed.\n\nLemma write_tview_same_rlx\n      tvw sc loc ts ord\n      (WRITABLE: TView.writable tvw.(TView.cur) sc loc ts ord)\n  :\n  (TView.write_tview tvw sc loc ts ord).(TView.cur).(View.rlx) loc = ts.\nProof.\n  ss. unfold TimeMap.join.\n  rewrite timemap_singleton_eq; auto. eapply TimeFacts.le_join_r.\n  left. eapply WRITABLE.\nQed.\n\nLemma sim_thread_sol_write\n      c vs P D mem0 lc0 sc loc ord val\n      (SIM: sim_thread_sol c vs P D mem0 lc0)\n      (LOCAL: Local.wf lc0 mem0)\n      (MEM: Memory.closed mem0)\n  :\n  exists lc1 mem1 from to released kind,\n    (<<WRITE: Local.write_step lc0 sc mem0 loc from to val None released ord lc1 sc mem1 kind>>) /\\\n    (<<SIM: sim_thread_sol c (fun loc0 => if Loc.eq_dec loc0 loc then val else vs loc0) (fun loc0 => if (Loc.eq_dec loc0 loc) then true else P loc0) D mem1 lc1>>)\n.\nProof.\n  Local Opaque TView.write_tview.\n  destruct lc0 as [tvw0 prom0].\n  assert (exists lc1 mem1 from to released kind,\n             (<<WRITE: Local.write_step (Local.mk tvw0 prom0) sc mem0 loc from to val None released ord lc1 sc mem1 kind>>) /\\\n             (<<CONS: Local.promise_consistent lc1>>) /\\\n             (<<NSYNC: forall loc, Memory.nonsynch_loc loc lc1.(Local.promises)>>) /\\\n             (<<GET: forall from0 to0 msg0 (GET: Memory.get loc to0 lc1.(Local.promises) = Some (from0, msg0)),\n               exists from1, Memory.get loc to0 prom0 = Some (from1, msg0)>>)).\n  { set (msg := fun ts => Message.concrete val (TView.write_released tvw0 sc loc ts None ord)).\n    assert (MSGWF: forall ts, Message.wf (msg ts)).\n    { i. unfold msg. econs.\n      eapply TViewFacts.write_future0; eauto. eapply LOCAL.\n    }\n    assert (MSGTO: forall ts (WRITABLE: TView.writable tvw0.(TView.cur) sc loc ts ord), Memory.message_to (msg ts) loc ts).\n    { i. econs. eapply writable_message_to; eauto.\n      { eapply LOCAL. }\n      { eapply WRITABLE. }\n      { eapply Time.bot_spec. }\n    }\n    hexploit (cell_elements_least (prom0 loc) (fun _ => True)).\n    i. des.\n    { assert (TS: Time.lt from to).\n      { hexploit memory_get_ts_strong; eauto. i. des; clarify.\n        inv LOCAL. ss. specialize (BOT loc). setoid_rewrite GET in BOT. ss.\n      }\n      set (ts := Time.middle from to).\n      hexploit (Time.middle_spec TS). i. des.\n      assert (WRITABLE: TView.writable tvw0.(TView.cur) sc loc ts ord).\n      { econs. eapply TimeFacts.le_lt_lt; [|eauto].\n        inv SIM. hexploit (VALS loc). i. des.\n        eapply memory_get_from_mon; eauto.\n        { eapply LOCAL. eauto. }\n        exploit CONS; eauto. eapply DEBT; eauto.\n      }\n      hexploit (@Memory.split_exists prom0 loc from ts to (msg ts) msg0); eauto.\n      i. des.\n      hexploit Memory.split_exists_le.\n      { eapply LOCAL. }\n      { eauto. }\n      i. des.\n      hexploit Memory.remove_exists.\n      { eapply Memory.split_get0 in H1. des. eapply GET2. }\n      i. des.\n      assert (WRITE: Memory.write prom0 mem0 loc from ts (msg ts) mem3 mem1 (Memory.op_kind_split to msg0)).\n      { econs; eauto.\n        { econs 2; eauto.\n          { ss. }\n          { inv SIM. eapply DEBT; eauto. }\n        }\n      }\n      esplits.\n      { econs; eauto. inv SIM. eauto. }\n      { ii. ss. destruct (Loc.eq_dec loc0 loc).\n        { subst. rewrite write_tview_same_rlx; auto.\n          erewrite Memory.remove_o in PROMISE; eauto.\n          erewrite Memory.split_o in PROMISE; eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. eapply LEAST in PROMISE; eauto.\n            eapply TimeFacts.lt_le_lt; eauto.\n          }\n        }\n        { rewrite write_tview_other_rlx; auto. inv SIM. eapply CONS; eauto.\n          ss. erewrite <- Memory.write_get_diff_promise; eauto.\n        }\n      }\n      { ii. ss. inv SIM. erewrite Memory.remove_o in GET0; eauto.\n        erewrite Memory.split_o in GET0; eauto. des_ifs.\n        { ss. des; clarify. eapply NSYNC in GET; eauto. }\n        { eapply NSYNC in GET0; eauto. }\n      }\n      { i. ss. erewrite Memory.remove_o in GET0; eauto.\n        erewrite Memory.split_o in GET0; eauto. des_ifs.\n        { ss. des; clarify. esplits. eauto. }\n        { eauto. }\n      }\n    }\n    { assert (WRITABLE: TView.writable tvw0.(TView.cur) sc loc (Time.incr (Memory.max_ts loc mem0)) ord).\n      { econs. inv SIM. hexploit (VALS loc). i. des.\n        eapply Memory.max_ts_spec in GET. des.\n        eapply TimeFacts.le_lt_lt.\n        { eapply MAX. }\n        { eapply Time.incr_spec. }\n      }\n      hexploit (@Memory.add_exists mem0 loc (Memory.max_ts loc mem0) (Time.incr (Memory.max_ts loc mem0))); eauto.\n      { i. eapply Memory.max_ts_spec in GET2. des.\n        symmetry. eapply interval_le_disjoint. auto.\n      }\n      { eapply Time.incr_spec. }\n      i. des.\n      hexploit Memory.add_exists_le.\n      { eapply LOCAL. }\n      { eauto. }\n      i. des. esplits.\n      { econs; eauto.\n        { econs; eauto.\n          { econs; eauto. i. ss.\n            hexploit Memory.max_ts_spec; eauto. i. des.\n            eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply Time.incr_spec. }\n            etrans.\n            { eapply memory_get_ts_le. eauto. }\n            { eauto. }\n          }\n          { hexploit Memory.remove_exists.\n            { eapply Memory.add_get0. eapply H0. }\n            i. des. eapply MemoryMerge.add_remove in H0; eauto.\n            subst. eauto.\n          }\n        }\n        { inv SIM. eauto. }\n      }\n      { ii. ss. destruct (Loc.eq_dec loc0 loc).\n        { subst. eapply EMPTY in PROMISE. ss. }\n        { rewrite write_tview_other_rlx; auto. inv SIM. eapply CONS; eauto. }\n      }\n      { inv SIM. eauto. }\n      { eauto. }\n    }\n  }\n  des. esplits; eauto. inv SIM. inv WRITE. ss. econs; eauto; ss.\n  { i. destruct (Loc.eq_dec loc0 loc).\n    { subst. eapply GET in GET0. des. eauto. }\n    { erewrite Memory.write_get_diff_promise in GET0; eauto. }\n  }\n  { i. des_ifs.\n    { rewrite write_tview_same_rlx; auto.\n      esplits. eapply Memory.write_get2; eauto.\n    }\n    { rewrite write_tview_other_rlx; auto.\n      erewrite Memory.write_get_diff; eauto.\n    }\n  }\n  { i. des_ifs.\n    rewrite write_tview_other_pln in MAX; auto.\n    eapply write_unchanged_loc in WRITE0; eauto. des.\n    eapply PERM; eauto. eapply unchanged_loc_max_readable; eauto.\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/SeqLiftCertification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1961443514593887}}
{"text": "Require Import Raft.\nRequire Import CommonTheorems.\nRequire Import SpecLemmas.\nRequire Import RaftRefinementInterface.\nRequire Import CroniesTermInterface.\n\nRequire Import CroniesCorrectInterface.\nRequire Import CandidateEntriesInterface.\n\nRequire Import RefinementSpecLemmas.\nRequire Import RefinementCommonTheorems.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import PrevLogCandidateEntriesTermInterface.\n\nSection PrevLogCandidateEntriesTerm.\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 {cei : candidate_entries_interface}.\n  Context {cti : cronies_term_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Lemma prevLog_candidateEntriesTerm_init :\n    refined_raft_net_invariant_init prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_init, prevLog_candidateEntriesTerm.\n    simpl. intuition.\n  Qed.\n\n  Lemma candidateEntriesTerm_ext : forall t sigma sigma',\n      (forall h, sigma' h = sigma h) ->\n      candidateEntriesTerm t sigma ->\n      candidateEntriesTerm t sigma'.\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    repeat find_higher_order_rewrite. intuition.\n  Qed.\n\n  Lemma candidateEntriesTerm_same : forall st st' t,\n       candidateEntriesTerm t st ->\n       (forall h, cronies (fst (st' h)) = cronies (fst (st h))) ->\n       (forall h, currentTerm (snd (st' h)) = currentTerm (snd (st h))) ->\n       (forall h, type (snd (st' h)) = type (snd (st h))) ->\n       candidateEntriesTerm t st'.\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    repeat find_higher_order_rewrite.\n    intuition.\n  Qed.\n\n  Ltac update_destruct :=\n    match goal with\n      | [ H : context [ update _ ?x _ ?y ] |- _ ] =>\n        destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n      | [  |- context [ update _ ?x _ ?y ] ] =>\n        destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n    end.\n\n  Lemma prevLog_candidateEntriesTerm_client_request :\n    refined_raft_net_invariant_client_request prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply candidateEntriesTerm_same; eauto; intros;\n      update_destruct; auto.\n      + now erewrite update_elections_data_client_request_cronies by eauto.\n      + find_apply_lem_hyp handleClientRequest_type. intuition.\n      + find_apply_lem_hyp handleClientRequest_type. intuition.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and. subst. simpl in *.\n      exfalso. eapply handleClientRequest_no_append_entries; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma update_elections_data_timeout_cronies :\n    forall h d out d' l t,\n      handleTimeout h (snd d) = (out, d', l) ->\n      cronies (update_elections_data_timeout h d) t = cronies (fst d) t \\/\n      (t = currentTerm d' /\\ type d' = Candidate /\\\n       cronies (update_elections_data_timeout h d) t = votesReceived d').\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto.\n    break_match; auto.\n  Qed.\n\n  Lemma handleClientRequest_preserves_candidateEntriesTerm:\n    forall net h d t out l,\n      refined_raft_intermediate_reachable net ->\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      candidateEntriesTerm t (nwState net) ->\n      candidateEntriesTerm t\n                           (update (nwState net) h\n                                   (update_elections_data_timeout h (nwState net h), d)).\n  Proof using cti. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists. break_and.\n    match goal with\n    | [ H : handleTimeout _ _ = _ |- _ ] =>\n      pose proof H;\n        eapply update_elections_data_timeout_cronies with (t := t) in H\n    end. break_or_hyp.\n    - update_destruct; auto.\n      find_copy_apply_lem_hyp handleTimeout_type_strong.\n      intuition; repeat find_rewrite; auto.\n      find_apply_lem_hyp wonElection_exists_voter.\n      break_exists.\n      find_apply_lem_hyp in_dedup_was_in.\n      find_copy_apply_lem_hyp cronies_term_invariant; auto.\n      simpl in *.\n      omega.\n    - update_destruct; auto.\n      find_copy_apply_lem_hyp handleTimeout_type_strong.\n      find_apply_lem_hyp wonElection_exists_voter.\n      break_exists.\n      find_apply_lem_hyp in_dedup_was_in.\n      find_copy_apply_lem_hyp cronies_term_invariant; auto.\n      intuition; subst; repeat find_rewrite; auto;\n      simpl in *; omega.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_timeout :\n    refined_raft_net_invariant_timeout prevLog_candidateEntriesTerm.\n  Proof using cti. \n    unfold refined_raft_net_invariant_timeout, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply handleClientRequest_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      exfalso. eapply handleTimeout_not_is_append_entries; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntries_preserves_candidateEntriesTerm :\n    forall net h t n pli plt es ci d m t',\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update (nwState net) h\n                                 (update_elections_data_appendEntries\n                                    h\n                                    (nwState net h) t n pli plt es ci, d)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists. break_and.\n    update_destruct.\n    - rewrite update_elections_data_appendEntries_cronies.\n      find_apply_lem_hyp handleAppendEntries_type.\n      intuition; subst; repeat find_rewrite; auto.\n      discriminate.\n    - intuition.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_append_entries :\n    refined_raft_net_invariant_append_entries prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply handleAppendEntries_preserves_candidateEntriesTerm; eauto.\n    - exfalso. eapply handleAppendEntries_not_append_entries; eauto.\n      simpl in *. subst. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntriesReply_preserves_candidateEntriesTerm :\n  forall net h h' t es r st' ms t',\n    handleAppendEntriesReply h (snd (nwState net h)) h' t es r = (st', ms) ->\n    refined_raft_intermediate_reachable net ->\n    candidateEntriesTerm t' (nwState net) ->\n    candidateEntriesTerm t' (update (nwState net) h (fst (nwState net h), st')).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    find_apply_lem_hyp handleAppendEntriesReply_type.\n    update_destruct.\n    - intuition; repeat find_rewrite; auto. discriminate.\n    - auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eauto using handleAppendEntriesReply_preserves_candidateEntriesTerm.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      find_apply_lem_hyp handleAppendEntriesReply_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma update_elections_data_requestVote_cronies_same :\n    forall h h' t lli llt st,\n      cronies (update_elections_data_requestVote h h' t h' lli llt st) =\n      cronies (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma advanceCurrentTerm_same_or_type_follower :\n    forall st t,\n      advanceCurrentTerm st t = st \\/\n      type (advanceCurrentTerm st t) = Follower.\n  Proof using. \n    unfold advanceCurrentTerm.\n    intros. repeat break_match; auto.\n  Qed.\n\n  Lemma handleRV_advanceCurrentTerm_preserves_candidateEntriesTerm :\n    forall net h h' t lli llt t',\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t'\n                       (update (nwState net) h\n                               (update_elections_data_requestVote h h' t h' lli llt (nwState net h),\n                                advanceCurrentTerm (snd (nwState net h)) t)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct; intuition.\n    - now rewrite update_elections_data_requestVote_cronies_same.\n    - intros.\n      match goal with\n      | [ H : context [advanceCurrentTerm ?st ?t] |- _ ] =>\n        pose proof advanceCurrentTerm_same_or_type_follower st t\n      end.\n      intuition.\n      + repeat find_rewrite. auto.\n      + congruence.\n  Qed.\n\n  Lemma handleRequestVote_preserves_candidateEntriesTerm :\n    forall net h h' t lli llt d t' m,\n      handleRequestVote h (snd (nwState net h)) t h' lli llt = (d, m) ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update (nwState net) h\n                                 (update_elections_data_requestVote\n                                    h h' t h' lli llt (nwState net h), d)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct; intuition.\n    - now rewrite update_elections_data_requestVote_cronies_same.\n    - unfold handleRequestVote, advanceCurrentTerm in *.\n      repeat break_match; do_bool; repeat find_inversion; simpl in *; break_and; try discriminate; auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_request_vote :\n    refined_raft_net_invariant_request_vote prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply handleRequestVote_preserves_candidateEntriesTerm; eauto.\n    - exfalso. eapply handleRequestVote_no_append_entries; eauto.\n      simpl in *. subst. eauto 10.\n  Qed.\n\n  Lemma handleRequestVoteReply_preserves_candidateEntriesTerm :\n    forall net h h' t r st' t',\n      handleRequestVoteReply h (snd (nwState net h)) h' t r = st' ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update (nwState net) h\n                                 (update_elections_data_requestVoteReply h h' t r (nwState net h),\n                                  st')).\n  Proof using cci. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct; auto.\n    break_and.\n    unfold raft_data in *. simpl in *.\n    unfold update_elections_data_requestVoteReply.\n    match goal with\n    | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n      remember (handleRequestVoteReply h st h' t r) as new_state\n    end; find_copy_apply_lem_hyp handleRequestVoteReply_spec.\n    repeat (break_match); intuition; repeat find_rewrite; intuition;\n    simpl; break_if; auto.\n    - find_apply_lem_hyp cronies_correct_invariant.\n      unfold cronies_correct in *. intuition.\n      unfold votes_received_leaders in *.\n      match goal with\n      | H :  Leader = _ |- _ =>\n        symmetry in H\n      end. find_apply_hyp_hyp.\n      eapply wonElection_no_dup_in;\n        eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n    - destruct (serverType_eq_dec (type (snd (nwState net x))) Leader); intuition.\n      find_apply_lem_hyp cronies_correct_invariant; auto.\n      eapply wonElection_no_dup_in;\n        eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply prevLog_candidateEntriesTerm.\n  Proof using cci. \n    unfold refined_raft_net_invariant_request_vote_reply, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp.\n    find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n    eapply candidateEntriesTerm_ext; eauto.\n    subst.\n    eapply handleRequestVoteReply_preserves_candidateEntriesTerm; eauto.\n  Qed.\n\n  Lemma doLeader_preserves_candidateEntriesTerm :\n    forall net gd d h os d' ms t',\n      nwState net h = (gd, d) ->\n      doLeader d h = (os, d', ms) ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update (nwState net) h (gd, d')).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    break_and.\n    update_destruct; auto.\n    split.\n    - match goal with\n      | [ H : nwState ?net ?h = (?x, _) |- _ ] =>\n        replace (x) with (fst (nwState net h)) in * by (rewrite H; auto)\n      end.\n      intuition.\n    - match goal with\n      | [ H : nwState ?net ?h = (_, ?x) |- _ ] =>\n        replace (x) with (snd (nwState net h)) in * by (rewrite H; auto); clear H\n      end.\n      find_apply_lem_hyp doLeader_type.\n      intuition. subst. repeat find_rewrite.\n      auto.\n  Qed.\n\n  Lemma getNextIndex_ext :\n    forall st st' h,\n      nextIndex st' = nextIndex st ->\n      log st' = log st ->\n      getNextIndex st' h = getNextIndex st h.\n  Proof using. \n    unfold getNextIndex.\n    intros.\n    repeat find_rewrite.\n    auto.\n  Qed.\n\n  Lemma replicaMessage_ext :\n    forall st st' h h',\n      nextIndex st' = nextIndex st ->\n      log st' = log st ->\n      currentTerm st' = currentTerm st ->\n      commitIndex st' = commitIndex st ->\n      replicaMessage st' h h' = replicaMessage st h h'.\n  Proof using. \n    unfold replicaMessage.\n    intros.\n    repeat break_match; repeat tuple_inversion; repeat find_rewrite;\n    erewrite getNextIndex_ext in * by eauto; congruence.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_do_leader :\n    refined_raft_net_invariant_do_leader prevLog_candidateEntriesTerm.\n  Proof using cei. \n    unfold refined_raft_net_invariant_do_leader, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_apply_hyp_hyp.\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply doLeader_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      find_copy_eapply_lem_hyp doLeader_messages; eauto.\n      break_and. intuition.\n      + omega.\n      + break_exists. break_and.\n        red.\n        find_apply_lem_hyp candidate_entries_invariant.\n        unfold CandidateEntries, candidateEntries_host_invariant in *.\n        find_apply_lem_hyp findAtIndex_elim. break_and.\n        match goal with\n        | [ H : nwState ?net ?h = (?y, ?x) |- _ ] =>\n          replace (x) with (snd (nwState net h)) in * by (rewrite H; auto);\n          replace (y) with (fst (nwState net h)) in * by (rewrite H; auto)\n        end.\n\n        eapply_prop_hyp In In.\n        subst.\n        find_eapply_lem_hyp (doLeader_preserves_candidateEntries); eauto.\n\n        match goal with\n        | [ H : nwState ?net ?h = (?y, ?x) |- _ ] => clear H\n        end.\n\n        unfold candidateEntries in *. break_exists_exists.\n        find_higher_order_rewrite.\n        update_destruct; auto.\n  Qed.\n\n  Lemma doGenericServer_preserves_candidateEntriesTerm :\n    forall net gd d h os d' ms t,\n      nwState net h = (gd, d) ->\n      doGenericServer h d = (os, d', ms) ->\n      candidateEntriesTerm t (nwState net) ->\n      candidateEntriesTerm t (update (nwState net) h (gd, d')).\n  Proof using. \n    intros.\n    find_apply_lem_hyp doGenericServer_type. break_and.\n    eapply candidateEntriesTerm_same; eauto.\n    - intros. update_destruct; auto.\n      find_rewrite. simpl. auto.\n    - intros. update_destruct; auto.\n      repeat find_rewrite.  auto.\n    - intros. update_destruct; auto.\n      repeat find_rewrite.  auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_do_generic_server :\n    refined_raft_net_invariant_do_generic_server prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply doGenericServer_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      find_apply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp.\n    eapply candidateEntriesTerm_ext with (sigma := (nwState net)).\n    - auto.\n    - eauto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_reboot :\n    refined_raft_net_invariant_reboot prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, prevLog_candidateEntriesTerm, reboot.\n    simpl. intros.\n    eapply candidateEntriesTerm_ext; eauto.\n    repeat find_rewrite.\n    find_apply_hyp_hyp.\n    unfold candidateEntriesTerm in *.\n    break_exists_exists.\n    update_destruct; auto.\n    repeat find_rewrite.\n    simpl in *. intuition.\n    discriminate.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      prevLog_candidateEntriesTerm net.\n  Proof using cci cti cei rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply prevLog_candidateEntriesTerm_init.\n    - apply prevLog_candidateEntriesTerm_client_request.\n    - apply prevLog_candidateEntriesTerm_timeout.\n    - apply prevLog_candidateEntriesTerm_append_entries.\n    - apply prevLog_candidateEntriesTerm_append_entries_reply.\n    - apply prevLog_candidateEntriesTerm_request_vote.\n    - apply prevLog_candidateEntriesTerm_request_vote_reply.\n    - apply prevLog_candidateEntriesTerm_do_leader.\n    - apply prevLog_candidateEntriesTerm_do_generic_server.\n    - apply prevLog_candidateEntriesTerm_state_same_packet_subset.\n    - apply prevLog_candidateEntriesTerm_reboot.\n  Qed.\n\n  Instance plceti : prevLog_candidateEntriesTerm_interface.\n  Proof.\n    constructor.\n    apply prevLog_candidateEntriesTerm_invariant.\n  Qed.\nEnd PrevLogCandidateEntriesTerm.", "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/PrevLogCandidateEntriesTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19614043296190864}}
{"text": "Require Import Ensembles.\nRequire Import AST.\nRequire Import Floats.\nRequire Import Metatheory.\nRequire Import alist.\nRequire Import monad.\nRequire Import targetdata.\nRequire Import genericvalues.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import syntax.\nRequire Import typings.\nRequire Import static.\nRequire Import opsem.\nRequire Import opsem_props.\nRequire Import opsem_wf.\nRequire Import vellvm_tactics.\n\nImport LLVMsyntax.\nImport LLVMgv.\nImport LLVMtd.\nImport LLVMtypings.\n\n(* This file defines the non-deterministic instance of Vellvm's operational \n   semantics. *)\n\n(* NDGVs implements the signature of GenericValues. *)\nModule MNDGVs.\n\nLemma singleton_inhabited : forall U (x:U), Inhabited U (Singleton U x).\nProof.\n  intros. apply Inhabited_intro with (x:=x); auto using In_singleton.\nQed.\n\nLemma full_set_inhabited : forall U,\n  (exists x:U, True) -> Inhabited U (Full_set U).\nProof.\n  intros. inversion H.\n  apply Inhabited_intro with (x:=x); auto using Full_intro.\nQed.\n\nDefinition t := Ensemble GenericValue.\nDefinition instantiate_gvs (gv : GenericValue) (gvs : t) : Prop :=\n  Ensembles.In _ gvs gv.\nDefinition inhabited (gvs : t) : Prop := Ensembles.Inhabited _ gvs.\nHint Unfold instantiate_gvs inhabited.\nDefinition cundef_gvs gv ty : t :=\nmatch ty with\n| typ_int sz => fun gv => exists z, gv = (Vint (sz-1) z, Mint (sz - 1))::nil\n| typ_floatpoint fp_float => \n    fun gv => exists f, gv = (Val.singleoffloat (Vfloat f), Mfloat32)::nil\n| typ_floatpoint fp_double => fun gv => exists f, gv = (Vfloat f, Mfloat64)::nil\n| typ_pointer _ =>\n    fun gv => exists b, exists ofs, gv = (Vptr b ofs, AST.Mint 31)::nil\n| _ => Singleton GenericValue gv\nend.\n\nDefinition undef_gvs gv ty : t :=\nmatch ty with\n| typ_int sz =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists z, gv = (Vint (sz-1) z, Mint (sz-1))::nil)\n| typ_floatpoint fp_float =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists f, gv = (Val.singleoffloat (Vfloat f), Mfloat32)::nil)\n| typ_floatpoint fp_double =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists f, gv = (Vfloat f, Mfloat64)::nil)\n| typ_pointer _ =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists b, exists ofs, gv = (Vptr b ofs, AST.Mint 31)::nil)\n| _ => Singleton GenericValue gv\nend.\n\nDefinition cgv2gvs (gv:GenericValue) ty : t :=\nmatch gv with\n| (Vundef, _)::nil => cundef_gvs gv ty\n| _ => Singleton _ gv\nend.\n\nDefinition gv2gvs (gv:GenericValue) (ty:typ) : t :=\nmatch gv with\n| (Vundef, _)::nil => undef_gvs gv ty\n| _ => Singleton GenericValue gv\nend.\n\nNotation \"gv @ gvs\" :=\n  (instantiate_gvs gv gvs) (at level 43, right associativity).\nNotation \"$ gv # t $\" := (gv2gvs gv t) (at level 41).\n\nLemma cundef_gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cundef_gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct_typ t; simpl in *;\n    try solve [inv Heq1; inv Hin; erewrite int_typsize; eauto |\n               inv Heq1; inv Hin; eauto].\n    destruct f; try solve [inv Heq1; inv Hin; eauto].\n    inv Heq1. inv Hin. inv H. simpl. auto.\nQed.\n\nLemma cundef_gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv' @ (cundef_gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct_typ t; simpl in *; uniq_result;\n    try solve [inv Heq1; inv Hin; auto].\n\n    inv Heq1; inv Hin. \n    constructor; auto.\n    split; auto. simpl. split; auto. apply Int.unsigned_range.\n\n    destruct f; uniq_result; inv Heq1; inv Hin; eauto.\n      constructor; auto.\n      split; auto. simpl. rewrite Float.singleoffloat_idem. auto.\n\n      constructor; auto.\n      split; auto. simpl. auto.\n\n    inv Heq1. inv Hin. inv H. \n    constructor; auto.\n    split; auto. simpl. auto.\nQed.\n\nLemma cundef_gvs__inhabited : forall gv ty, inhabited (cundef_gvs gv ty).\nProof.\n  destruct_typ ty; simpl; \n    try solve [eapply Ensembles.Inhabited_intro; constructor].\n    eapply Ensembles.Inhabited_intro.\n      exists (Int.zero (s0-1)). auto.\n\n    destruct f; try solve [\n      eapply Ensembles.Inhabited_intro; exists Float.zero; auto |\n      eapply Ensembles.Inhabited_intro; constructor].\n\n    eapply Ensembles.Inhabited_intro.\n      exists Mem.nullptr. exists (Int.repr 31 0). auto.\nQed.\n\nLemma undef_gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (undef_gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct_typ t; simpl in *;\n    try solve [inv Heq1; inv Hin; erewrite int_typsize; eauto |\n               inv Heq1; inv Hin; eauto].\n\n    inv Heq1; inv Hin; inv H; unfold Size.to_nat;\n      try solve [eauto | erewrite int_typsize; eauto].\n\n    destruct f; try solve [inv Heq1; inv Hin; eauto |\n                           inv Heq1; inv Hin; inv H; auto].\n\n    inv Heq1; inv Hin; inv H; auto.\n      inv H0. auto.\nQed.\n\nLemma undef_gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv' @ (undef_gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct_typ t; simpl in *; uniq_result; try solve [\n    inv Heq1; inv Hin; eauto\n  ].\n\n    inv Heq1; inv Hin; inv H.\n    constructor; auto. \n    constructor; auto.\n      split; auto. split; auto. apply Int.unsigned_range.\n\n    destruct f; uniq_result; try solve [\n      inv Heq1; inv Hin; eauto\n    ].\n\n      inv Heq1; inv Hin; inv H.\n      constructor; auto.\n      constructor; auto.\n        split; auto. simpl. rewrite Float.singleoffloat_idem. auto.\n\n      inv Heq1; inv Hin; inv H.\n      constructor; auto.\n      constructor; auto.\n        split; auto. simpl. auto.\n\n    inv Heq1; inv Hin; inv H; try solve [congruence | auto].\n      match goal with\n      | H1: exists _:_, _ |- _ => inv H1;\n         constructor; try solve [auto | split; simpl; auto]\n      end.\nQed.\n\nLemma undef_gvs__inhabited : forall gv ty, inhabited (undef_gvs gv ty).\nProof.\n  destruct_typ ty; simpl; try solve [\n    eapply Ensembles.Inhabited_intro; apply Union_introl; constructor |\n    eapply Ensembles.Inhabited_intro; constructor].\n\n    destruct f; try solve [\n      eapply Ensembles.Inhabited_intro; apply Union_introl; constructor |\n      eapply Ensembles.Inhabited_intro; constructor].\nQed.\n\nLemma cgv2gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cgv2gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct gv; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct p.\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply cundef_gvs__getTypeSizeInBits in Hin; eauto.\nQed.\n\nLemma cgv2gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  instantiate_gvs gv' (cgv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct gv as [|[]]; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply cundef_gvs__matches_chunks in Hin; \n        unfold gv_chunks_match_typ, vm_matches_typ in *; simpl in *; eauto.\n        rewrite <- HeqR in Hin. auto.\n        rewrite <- HeqR. auto.\nQed.\n\nLemma cgv2gvs__inhabited : forall gv t, inhabited (cgv2gvs gv t).\nProof.\n  intros gv t.\n  destruct gv; simpl.\n    apply Ensembles.Inhabited_intro with (x:=nil).\n    apply Ensembles.In_singleton.\n\n    destruct p.\n    destruct v; auto using singleton_inhabited, cundef_gvs__inhabited.\n    destruct gv; auto using singleton_inhabited, cundef_gvs__inhabited.\nQed.\n\nLemma gv2gvs__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  sizeGenericValue gv' = Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros S los nts gv t sz al Hwft Heq1 Heq2 gv' Hin.\n  destruct gv; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct p.\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply undef_gvs__getTypeSizeInBits in Hin; eauto.\nQed.\n\nLemma gv2gvs__matches_chunks : forall S los nts gv t,\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t Hwft Heq1 gv' Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct gv as [|[]]; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply undef_gvs__matches_chunks in Hin; \n        unfold gv_chunks_match_typ, vm_matches_typ in *; simpl in *; eauto.\n        rewrite <- HeqR in Hin. auto.\n        rewrite <- HeqR. auto.\nQed.\n\nLemma gv2gvs__inhabited : forall gv t, inhabited ($ gv # t $).\nProof.\n  intros gv t.\n  destruct gv; simpl.\n    apply Ensembles.Inhabited_intro with (x:=nil).\n    apply Ensembles.In_singleton.\n\n    destruct p.\n    destruct v; auto using singleton_inhabited, undef_gvs__inhabited.\n    destruct gv; auto using singleton_inhabited, undef_gvs__inhabited.\nQed.\n\nDefinition lift_op1 (f: GenericValue -> option GenericValue) gvs1 ty : option t\n  :=\n  Some (fun gv2 => exists gv1, exists gv2',\n    gv1 @ gvs1 /\\ f gv1 = Some gv2' /\\ (gv2 @ $ gv2' # ty $)).\n\nDefinition lift_op2 (f: GenericValue -> GenericValue -> option GenericValue)\n  gvs1 gvs2 ty : option t :=\n  Some (fun gv3 => exists gv1, exists gv2, exists gv3',\n    gv1 @ gvs1 /\\ gv2 @ gvs2 /\\ f gv1 gv2 = Some gv3' /\\ (gv3 @ $ gv3' # ty $)).\n\nLemma lift_op1__inhabited : forall f gvs1 ty gvs2\n  (H:forall x, exists z, f x = Some z),\n  inhabited gvs1 ->\n  lift_op1 f gvs1 ty = Some gvs2 ->\n  inhabited gvs2.\nProof.\n  intros. inv H1. inv H0.\n  destruct (@H x) as [z J].\n  destruct (@gv2gvs__inhabited z ty).\n  exists x0. unfold Ensembles.In. exists x. exists z.\n  rewrite J.\n  repeat (split; auto).\nQed.\n\nLemma lift_op2__inhabited : forall f gvs1 gvs2 ty gv3\n  (H:forall x y, exists z, f x y = Some z),\n  inhabited gvs1 -> inhabited gvs2 ->\n  lift_op2 f gvs1 gvs2 ty = Some gv3 ->\n  inhabited gv3.\nProof.\n  intros. inv H0. inv H1. inv H2.\n  destruct (@H x x0) as [z J].\n  destruct (@gv2gvs__inhabited z ty).\n  exists x1. unfold Ensembles.In. exists x. exists x0. exists z.\n  rewrite J.\n  repeat (split; auto).\nQed.\n\nLemma lift_op1__isnt_stuck : forall f gvs1 ty\n  (H:forall x, exists z, f x = Some z),\n  exists gvs2, lift_op1 f gvs1 ty = Some gvs2.\nProof.\n  intros. unfold lift_op1. eauto.\nQed.\n\nLemma lift_op2__isnt_stuck : forall f gvs1 gvs2 ty\n  (H:forall x y, exists z, f x y = Some z),\n  exists gv3, lift_op2 f gvs1 gvs2 ty = Some gv3.\nProof.\n  intros. unfold lift_op2. eauto.\nQed.\n\nLemma lift_op1__getTypeSizeInBits : forall S los nts f g t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y, x @ g -> f x = Some y ->\n   sizeGenericValue y = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros. inv H2.\n  destruct H3 as [x [y [J1 [J2 J3]]]].\n  apply H1 in J2; auto.\n  eapply gv2gvs__getTypeSizeInBits; eauto.\nQed.\n\nLemma lift_op1__matches_chunks : forall S los nts f g t gvs\n  (Hwft: wf_typ S (los,nts) t),\n  (forall x y, x @ g -> f x = Some y ->\n   gv_chunks_match_typ (los, nts) y t) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof.\n  intros. inv H0.\n  destruct H1 as [x [y [J1 [J2 J3]]]].\n  apply H in J2; auto.\n  eapply gv2gvs__matches_chunks; eauto.\nQed.\n\nLemma lift_op2__getTypeSizeInBits : forall S los nts f g1 g2 t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y z, x @ g1 -> y @ g2 -> f x y = Some z ->\n   sizeGenericValue z = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros. inv H2.\n  destruct H3 as [x [y [z [J1 [J2 [J3 J4]]]]]].\n  apply H1 in J3; auto.\n  eapply gv2gvs__getTypeSizeInBits; eauto.\nQed.\n\nLemma lift_op2__matches_chunks : forall S los nts f g1 g2 t gvs\n  (Hwft: wf_typ S (los,nts) t),\n  (forall x y z, x @ g1 -> y @ g2 -> f x y = Some z ->\n   gv_chunks_match_typ (los, nts) z t) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof.\n  intros. inv H0.\n  destruct H1 as [x [y [z [J1 [J2 [J3 J4]]]]]].\n  apply H in J3; auto.\n  eapply gv2gvs__matches_chunks; eauto.\nQed.\n\nLemma inhabited_inv : forall gvs, inhabited gvs -> exists gv, gv @ gvs.\nProof.\n  intros. inv H; eauto.\nQed.\n\nLemma instantiate_undef__undef_gvs : forall gv t, gv @ (undef_gvs gv t).\nProof.\n  intros. unfold undef_gvs.\n  destruct_typ t0; try solve [apply Union_introl; constructor | constructor].\n  destruct f; \n    try solve [apply Union_introl; constructor | constructor].\nQed.\n\nLemma instantiate_gv__gv2gvs : forall gv t, gv @ ($ gv # t $).\nProof.\n  intros.\n  destruct gv; simpl; try constructor.\n  destruct p; simpl; try constructor.\n  destruct v; simpl; try constructor.\n  destruct gv; simpl;\n    try solve [constructor | auto using instantiate_undef__undef_gvs].\nQed.\n\nLemma none_undef2gvs_inv : forall gv gv' t,\n  gv @ $ gv' # t $ -> (forall mc, (Vundef, mc)::nil <> gv') -> gv = gv'.\nProof.\n  intros.\n  destruct gv'; try solve [inv H; auto].\n  destruct p.\n  destruct v; try solve [inv H; auto].\n  destruct gv'; try solve [inv H; auto].\n  assert (J:=@H0 m). congruence.\nQed.\n\nEnd MNDGVs.\n\nDefinition NDGVs : GenericValues := mkGVs\nMNDGVs.t\nMNDGVs.instantiate_gvs\nMNDGVs.inhabited\nMNDGVs.cgv2gvs\nMNDGVs.gv2gvs\nMNDGVs.lift_op1\nMNDGVs.lift_op2\nMNDGVs.cgv2gvs__getTypeSizeInBits\nMNDGVs.cgv2gvs__matches_chunks\nMNDGVs.cgv2gvs__inhabited\nMNDGVs.gv2gvs__getTypeSizeInBits\nMNDGVs.gv2gvs__matches_chunks\nMNDGVs.gv2gvs__inhabited\nMNDGVs.lift_op1__inhabited\nMNDGVs.lift_op2__inhabited\nMNDGVs.lift_op1__isnt_stuck\nMNDGVs.lift_op2__isnt_stuck\nMNDGVs.lift_op1__getTypeSizeInBits\nMNDGVs.lift_op2__getTypeSizeInBits\nMNDGVs.lift_op1__matches_chunks\nMNDGVs.lift_op2__matches_chunks\nMNDGVs.inhabited_inv\nMNDGVs.instantiate_gv__gv2gvs\nMNDGVs.none_undef2gvs_inv.\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/ndopsem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1959585081365919}}
{"text": "Require Import GhostSimulations.\nRequire Import Raft.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import RaftRefinementInterface.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import AllEntriesVotesWithLogInterface.\nRequire Import AllEntriesLogInterface.\nRequire Import VotesWithLogTermSanityInterface.\nRequire Import VotesCorrectInterface.\nRequire Import VotesVotesWithLogCorrespondInterface.\n\nSection AllEntriesVotesWithLog.\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 {aeli : allEntries_log_interface}.\n  Context {vwltsi : votesWithLog_term_sanity_interface}.\n  Context {vvwlci : votes_votesWithLog_correspond_interface}.\n  Context {vci : votes_correct_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  Lemma update_elections_data_appendEntries_allEntries' :\n    forall h st t h' pli plt es ci t' e,\n      In (t', e) (allEntries (update_elections_data_appendEntries h st t h' pli plt es ci)) ->\n      In (t', e) (allEntries (fst st)) \\/ currentTerm (snd st) <= t'.\n  Proof using. \n    intros. unfold update_elections_data_appendEntries in *.\n    repeat break_match; auto. simpl in *.\n    do_in_app. intuition. do_in_map. find_inversion.\n    right.\n    unfold handleAppendEntries in *.\n    repeat break_match; find_inversion; simpl in *; do_bool; auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_votesWithLog.\n  Proof using vwltsi. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *.\n    - find_eapply_lem_hyp votesWithLog_update_elections_data_append_entries; eauto.\n      find_copy_apply_lem_hyp votesWithLog_term_sanity_invariant; eauto.\n      find_eapply_lem_hyp update_elections_data_appendEntries_allEntries'; eauto.\n      intuition; do 2 (unfold raft_data, ghost_data in *; simpl in *); try omega.\n      eapply_prop_hyp votesWithLog votesWithLog; eauto. intuition.\n      right. break_exists_exists. intuition.\n      find_higher_order_rewrite. destruct_update; simpl in *; auto.\n      rewrite update_elections_data_appendEntries_leaderLogs. auto.\n    - eapply_prop_hyp votesWithLog votesWithLog; eauto. intuition.\n      right. break_exists_exists. intuition.\n      find_higher_order_rewrite. destruct_update; simpl in *; auto.\n      rewrite update_elections_data_appendEntries_leaderLogs. auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n    right; break_exists_exists; intuition;\n    find_higher_order_rewrite; destruct_update; simpl in *; auto.\n  Qed.\n\n  Definition currentTerm_votedFor_votesWithLog net :=\n    forall h t n,\n      (currentTerm (snd (nwState net h)) = t /\\\n       votedFor (snd (nwState net h)) = Some n) ->\n      exists l,\n        In (t, n, l) (votesWithLog (fst (nwState net h))).\n  \n  Lemma currentTerm_votedFor_votesWithLog_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      currentTerm_votedFor_votesWithLog net.\n  Proof using vci vvwlci. \n    unfold currentTerm_votedFor_votesWithLog. intros.\n    eapply votes_votesWithLog_correspond_invariant; eauto.\n    break_and.\n    eapply votes_correct_invariant; eauto.\n  Qed.\n\n  Lemma handleRequestVote_currentTerm_leaderId' :\n    forall h st t c li lt st' m,\n      handleRequestVote h st t c li lt = (st', m) ->\n      votedFor st' <> votedFor st ->\n      currentTerm st < currentTerm st' \\/\n      leaderId st = None.\n  Proof using. \n    intros. unfold handleRequestVote, advanceCurrentTerm in *.\n    repeat (break_match; try find_inversion; simpl in *; auto);\n    do_bool; auto; congruence.\n  Qed.\n  \n  Lemma handleRequestVote_currentTerm :\n    forall h st t src lli llt st' m,\n      handleRequestVote h st t src lli llt = (st', m) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleRequestVote, advanceCurrentTerm in *.\n    repeat break_match; find_inversion; simpl in *; do_bool; auto.\n  Qed.\n    \n  Lemma votesWithLog_update_elections_data_request_vote :\n    forall net h t src lli llt st' m t' h' l',\n      refined_raft_intermediate_reachable net ->\n      handleRequestVote h (snd (nwState net h)) t src lli llt = (st', m) ->\n      In (t', h', l') (votesWithLog (update_elections_data_requestVote h src t src lli llt (nwState net h))) ->\n      In (t', h', l') (votesWithLog (fst (nwState net h))) \\/\n      (t' = currentTerm st' /\\\n       l' = log st' /\\\n       (leaderId (snd (nwState net h)) = None \\/\n        currentTerm (snd (nwState net h)) < currentTerm st')).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; repeat tuple_inversion; intuition;\n    simpl in *; intuition;\n    tuple_inversion; intuition; repeat (do_bool; intuition);\n    try congruence;\n    unfold raft_data, ghost_data in *; simpl in *;\n    repeat find_rewrite; repeat find_inversion;\n    find_copy_apply_lem_hyp handleRequestVote_currentTerm_leaderId;\n    intuition;\n    find_apply_lem_hyp handleRequestVote_currentTerm_leaderId'; repeat find_rewrite; try congruence; intuition.\n  Qed.\n\n  Lemma allEntries_votesWithLog_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_votesWithLog.\n  Proof using aeli. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *.\n    - find_rewrite_lem update_elections_data_requestVote_allEntries.\n      find_copy_apply_lem_hyp handleRequestVote_currentTerm.\n      find_copy_eapply_lem_hyp votesWithLog_update_elections_data_request_vote; eauto.\n      intuition.\n      + eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n        right; break_exists_exists; intuition;\n        find_higher_order_rewrite; destruct_update; simpl in *; auto.\n        rewrite leaderLogs_update_elections_data_requestVote. auto.\n      + subst.\n        find_apply_lem_hyp handleRequestVote_log. repeat find_rewrite.\n        find_copy_eapply_lem_hyp allEntries_log_invariant; eauto.\n        intuition.\n        right. break_exists_exists. repeat find_higher_order_rewrite.\n        simpl in *.\n        destruct_update; simpl in *; intuition; \n        try rewrite leaderLogs_update_elections_data_requestVote; eauto.\n      +  subst.\n        find_apply_lem_hyp handleRequestVote_log. repeat find_rewrite.\n        find_copy_eapply_lem_hyp allEntries_log_invariant; eauto.\n        intuition.\n        right. break_exists_exists. repeat find_higher_order_rewrite.\n        simpl in *.\n        destruct_update; simpl in *; intuition; \n        try rewrite leaderLogs_update_elections_data_requestVote; eauto.\n    - eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n      right; break_exists_exists; intuition;\n      find_higher_order_rewrite; destruct_update; simpl in *; auto.\n      rewrite leaderLogs_update_elections_data_requestVote. auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *.\n    - find_rewrite_lem update_elections_data_requestVoteReply_allEntries.\n      find_eapply_lem_hyp votesWithLog_update_elections_data_request_vote_reply; eauto.\n      eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n      right; break_exists_exists; intuition;\n      find_higher_order_rewrite; destruct_update; simpl in *; auto.\n      eauto using update_elections_data_requestVoteReply_old.\n    - eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n      right; break_exists_exists; intuition;\n      find_higher_order_rewrite; destruct_update; simpl in *; auto.\n      eauto using update_elections_data_requestVoteReply_old.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries_in_or_term :\n    forall h st client id c out st' ms t e,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      In (t, e) (allEntries (update_elections_data_client_request h st client id c)) ->\n      In (t, e) (allEntries (fst st)) \\/\n      t = currentTerm (snd st).\n  Proof using. \n    intros.\n    intros.\n    unfold update_elections_data_client_request in *.\n    repeat break_match; repeat find_inversion; auto.\n    simpl in *. intuition.\n    find_inversion. repeat find_rewrite. intuition.\n    unfold handleClientRequest in *.\n    break_match; find_inversion; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_client_request :\n    refined_raft_net_invariant_client_request allEntries_votesWithLog.\n  Proof using vwltsi. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *.\n    - find_copy_eapply_lem_hyp update_elections_data_client_request_allEntries_in_or_term; eauto. intuition.\n      + repeat find_rewrite.\n        find_eapply_lem_hyp votesWithLog_update_elections_data_client_request; eauto.\n        eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n        right; break_exists_exists; intuition;\n        find_higher_order_rewrite; destruct_update; simpl in *; auto.\n        rewrite update_elections_data_client_request_leaderLogs. auto.\n      + subst.\n        find_eapply_lem_hyp votesWithLog_update_elections_data_client_request; eauto.\n        find_eapply_lem_hyp votesWithLog_term_sanity_invariant; eauto.\n        repeat (unfold raft_data, ghost_data in *; simpl in *). omega.\n    - eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n        right; break_exists_exists; intuition;\n        find_higher_order_rewrite; destruct_update; simpl in *; auto.\n      rewrite update_elections_data_client_request_leaderLogs. auto.\n  Qed.\n\n  Lemma votesWithLog_update_elections_data_timeout' :\n    forall net h out st' ps t' h' l',\n      refined_raft_intermediate_reachable net ->\n      handleTimeout h (snd (nwState net h)) = (out, st', ps) ->\n      In (t', h', l') (votesWithLog (update_elections_data_timeout h (nwState net h))) ->\n      In (t', h', l') (votesWithLog (fst (nwState net h))) \\/\n      (t' = currentTerm st' /\\ l' = log st' /\\ currentTerm (snd (nwState net h)) < currentTerm st').\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros. repeat break_match; simpl in *; intuition; repeat tuple_inversion; intuition.\n    - unfold handleTimeout, tryToBecomeLeader in *.\n      repeat break_match; repeat find_inversion; simpl in *; intuition.\n    - unfold handleTimeout, tryToBecomeLeader in *.\n      repeat break_match;  repeat find_inversion; simpl in *; congruence.\n  Qed.\n  \n  Lemma allEntries_votesWithLog_timeout :\n    refined_raft_net_invariant_timeout allEntries_votesWithLog.\n  Proof using aeli. \n    red. unfold allEntries_votesWithLog. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *.\n    - find_rewrite_lem update_elections_data_timeout_allEntries.\n      find_eapply_lem_hyp votesWithLog_update_elections_data_timeout'; eauto.\n      intuition.\n      + eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n        right; break_exists_exists; intuition;\n        find_higher_order_rewrite; destruct_update; simpl in *; auto.\n        rewrite update_elections_data_timeout_leaderLogs. auto.\n      + subst.\n        find_copy_apply_lem_hyp handleTimeout_log_same. repeat find_rewrite.\n        find_apply_lem_hyp allEntries_log_invariant; eauto. intuition.\n        right.\n        break_exists_exists; intuition;\n        find_higher_order_rewrite; destruct_update; simpl in *; auto;\n        rewrite update_elections_data_timeout_leaderLogs; auto.\n    - eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n      right; break_exists_exists; intuition;\n      find_higher_order_rewrite; destruct_update; simpl in *; auto.\n      rewrite update_elections_data_timeout_leaderLogs; auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_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    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n    right; break_exists_exists; intuition;\n    find_higher_order_rewrite; destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_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    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    eapply_prop_hyp votesWithLog votesWithLog; eauto; intuition;\n    right; break_exists_exists; intuition;\n    find_higher_order_rewrite; destruct_update; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_votesWithLog_init :\n    refined_raft_net_invariant_init allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_votesWithLog. intros. simpl in *. intuition.\n  Qed.\n\n  Lemma allEntries_votesWithLog_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_votesWithLog in *. intros.\n    repeat find_reverse_higher_order_rewrite.\n    copy_eapply_prop_hyp votesWithLog votesWithLog; eauto. intuition. right.\n    break_exists_exists. repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma allEntries_votesWithLog_reboot :\n    refined_raft_net_invariant_reboot allEntries_votesWithLog.\n  Proof using. \n    red. unfold allEntries_votesWithLog in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    subst. unfold reboot in *.\n    destruct_update; simpl in *; eauto; copy_eapply_prop_hyp votesWithLog votesWithLog; eauto;\n    repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Theorem allEntries_votesWithLog_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      allEntries_votesWithLog net.\n  Proof using vwltsi aeli rri. \n    intros.\n    eapply refined_raft_net_invariant; eauto.\n    - exact allEntries_votesWithLog_init.\n    - exact allEntries_votesWithLog_client_request.\n    - exact allEntries_votesWithLog_timeout.\n    - exact allEntries_votesWithLog_append_entries.\n    - exact allEntries_votesWithLog_append_entries_reply.\n    - exact allEntries_votesWithLog_request_vote.\n    - exact allEntries_votesWithLog_request_vote_reply.\n    - exact allEntries_votesWithLog_do_leader.\n    - exact allEntries_votesWithLog_do_generic_server.\n    - exact allEntries_votesWithLog_state_same_packet_subset.\n    - exact allEntries_votesWithLog_reboot.\n  Qed.\n\n  Instance aevwli : allEntries_votesWithLog_interface.\n  split. eauto using allEntries_votesWithLog_invariant.\n  Defined.\nEnd AllEntriesVotesWithLog.", "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/AllEntriesVotesWithLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.19595850429142148}}
{"text": "(* If the following hold,\n\tAll executable code resides in low memory\n\tAll exported symbols target low memory areas\n\tNo disassembled instructions spans a chunk boundary\n\tstatic branches target low memory chunk boundaries\n\tall computed jumps that do not reference the IAT are \n\t\timmediately preceded by and-masking \n\t\tinstruction from Table 1 in the same chunk \n\tComputed jumps that read the IAT access a properly \n\t\taligned IAT entry, and are preceded by an \n\t\tand-mask of the return address (call \n\t\tinstructions must end on a chunk boundary \n\t\trather than requiring a mask, since they push\n\t\ttheir own return address \n\tThere are no trap instructions; int or syscall \nTHEN:\n\tThese properties ensure that any unaligned instruction sequences\nconcealed within untrusted, executable sections are not reachable\nat runtime.\n*)\n\n\n(* Actual algorithm that tests an imaginary binary - image this in \nthe light of FastVerifier *)\n\n\n(*------------------------ COPIED AND PASTED FROM FastVerifier ----------------- *)\n\n(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n\nRequire Import Coqlib.\nRequire Import Parser.\nRequire Import List.\nRequire Import Bits.\nRequire Import Decode.\nRequire Import X86Syntax.\nRequire Import Int32.\nRequire Import ReinsVerifierDFA.\nRequire Import PEFormat.\nRequire Import PETraversal.\n\nImport X86_PARSER_ARG.\nImport X86_PARSER.\nImport X86_BASE_PARSER.\n\nRequire Coq.MSets.MSetAVL.\nRequire Coq.Structures.OrdersAlt.\nRequire Coq.MSets.MSetFacts.\nModule New_Int32_OT := (Coq.Structures.OrdersAlt.Update_OT Int32_OT).\nModule Int32Set := Coq.MSets.MSetAVL.Make New_Int32_OT.\n\nDefinition n_shift_add (b: bool) (x: nat) :=\n  (if b then 2 * x + 1 else 2 * x)%nat.\n\nOpen Scope Z_scope.\n\nFixpoint n_of_bits (n: nat) (f: Z -> bool) {struct n}: nat :=\n  match n with\n  | O => O\n  | S m => n_shift_add (f 0) (n_of_bits m (fun i => f (i + 1)))\n  end.\n\n(* Maybe tokens as nats isn't best... *)\nDefinition byte2token (b: int8) : token_id := Zabs_nat (Word.unsigned b).\nDefinition token2byte (t: token_id) : int8 := Word.repr (Z_of_nat t).\n\nSection BUILT_DFAS.\n\n  (* In this section we will just assume the DFAs are all built;\n     that is, non_cflow_dfa should be the result of \"make_dfa non_cflow_parser\" and\n     similarly for dir_cflow_dfa and nacljmp_dfa *)\n  Variable non_cflow_dfa : DFA.\n  Variable dir_cflow_dfa : DFA.\n  Variable reinsjmp_nonIAT_dfa : DFA.\n  Variable reinsjmp_IAT_or_RET_dfa : DFA.\n  Variable reinsjmp_IAT_CALL_dfa : DFA.\n  Variable reinsjmp_nonIAT_mask : parser (pair_t instruction_t instruction_t).\n  Variable reinsjmp_IAT_or_RET_mask : parser (pair_t instruction_t instruction_t).\n  Variable reinsjmp_IAT_CALL_p : parser instruction_t.\n\n  (* G.T.: may be a good idea to parametrize the DFA w.r.t. the ChunkSize;\n     Google's verifier allows it either to be 16 or 32.\n   Parameters logChunkSize:nat.\n   Hypothesis logChunkSize_range : (0 < logChunkSize <= Word.wordsize 31)%nat.\n  *)\n\n  Fixpoint parseloop (ps:X86_PARSER.instParserState) (bytes:list int8) : \n    option ((prefix * instr) * list int8) := \n    match bytes with \n      | nil => None\n      | b::bs => match X86_PARSER.parse_byte ps b with \n                   | (ps',nil) => parseloop ps' bs\n                   | (_, v::_) => Some (v,bs)\n                 end\n    end.\n\n  Inductive jumptype : Set :=\n  | JMP_t : jumptype\n  | JCC_t : jumptype\n  | CALL_t: jumptype.\n\n  Definition extract_disp_and_type bytes : option (int32 * jumptype) := \n    match (parseloop Decode.X86_PARSER.initial_parser_state bytes) with\n      | Some ((_, JMP true false (Imm_op disp) None), _) => Some (disp, JMP_t)\n      | Some ((_, Jcc ct disp), _) => Some (disp, JCC_t)\n      | Some ((_, CALL true false (Imm_op disp) None), _) => Some (disp, CALL_t)\n      | _ => None\n    end.\n\n  (* parseloop, X86_PARSER.parse_byte, and X86_PARSER.instParserState all have a\n     too-restrictive type, expecting the underlying parser to parse a prefix and\n     an instruction. For our reinsjmp parsers, we are parsing pairs of instructions,\n     so we redefine these three functions with that in mind *)\n\n  Record instParserState' := mkPS' {\n      inst_ctxt' : ctxt_t;\n      inst_regexp' : regexp (pair_t instruction_t instruction_t);\n      inst_regexp_wf' : wf_regexp inst_ctxt' inst_regexp'\n  }.\n\n  Definition parse_byte' (ps:instParserState') (b:int8) : \n    instParserState' * list (instr * instr) := \n    let cs := byte_explode b in \n    let r' := deriv_parse' (inst_regexp' ps) cs in\n    let wf' := wf_derivs (inst_ctxt' ps) cs (inst_regexp' ps) (inst_regexp_wf' ps) in\n      (mkPS' (inst_ctxt' ps) r' wf', apply_null (inst_ctxt' ps) r' wf').\n\n  Fixpoint parseloop' (ps:instParserState') (bytes:list int8) : \n    option ((instr * instr) * list int8) := \n    match bytes with \n      | nil => None\n      | b::bs => match parse_byte' ps b with \n                   | (ps',nil) => parseloop' ps' bs\n                   | (_, v::_) => Some (v,bs)\n                 end\n    end.\n\n\n  Definition extract_IAT_jmp_dest bytes : option (option address) :=\n    let regexp_pair := parser2regexp reinsjmp_IAT_or_RET_mask in\n    let ips := mkPS' (snd regexp_pair) (fst regexp_pair) (p2r_wf reinsjmp_IAT_or_RET_mask _) in\n    match (parseloop' ips bytes) with\n    | Some ((_, JMP true true (Address_op addr) None), _) => Some (Some addr)\n    | Some ((_, RET _ _), _) => Some None\n    | _ => None\n    end.\n\n  (* parseloop, X86_PARSER.parse_byte, and X86_PARSER.instParserState all have a\n     too-restrictive type, expecting the underlying parser to parse a prefix and\n     an instruction. For our IAT call extraction, we want a single instruction. *)\n\n  Record instParserState'' := mkPS'' {\n      inst_ctxt'' : ctxt_t;\n      inst_regexp'' : regexp instruction_t;\n      inst_regexp_wf'' : wf_regexp inst_ctxt'' inst_regexp''\n  }.\n\n  Definition parse_byte'' (ps:instParserState'') (b:int8) : \n    instParserState'' * list instr := \n    let cs := byte_explode b in \n    let r' := deriv_parse' (inst_regexp'' ps) cs in\n    let wf' := wf_derivs (inst_ctxt'' ps) cs (inst_regexp'' ps) (inst_regexp_wf'' ps) in\n      (mkPS'' (inst_ctxt'' ps) r' wf', apply_null (inst_ctxt'' ps) r' wf').\n\n  Fixpoint parseloop'' (ps:instParserState'') (bytes:list int8) : \n    option (instr * list int8) := \n    match bytes with \n      | nil => None\n      | b::bs => match parse_byte'' ps b with \n                   | (ps',nil) => parseloop'' ps' bs\n                   | (_, v::_) => Some (v,bs)\n                 end\n    end.\n\n  Definition extract_IAT_call_dest bytes : option address :=\n    let regexp_pair := parser2regexp (reinsjmp_IAT_CALL_p) in\n    let ips := mkPS'' (snd regexp_pair) (fst regexp_pair) (p2r_wf (reinsjmp_IAT_CALL_p) _) in\n    match (parseloop'' ips bytes) with\n    | Some (CALL true true (Address_op addr) None, _) => Some addr\n    | _ => None\n    end.\n\n  Definition is_nonIAT_call bytes : bool :=\n    let regexp_pair := parser2regexp (reinsjmp_nonIAT_mask) in\n    let ips := mkPS' (snd regexp_pair) (fst regexp_pair) (p2r_wf (reinsjmp_nonIAT_mask) _) in\n    match (parseloop' ips bytes) with\n    | Some ((_, CALL _ _ _ _), _) => true\n    | _ => false\n    end.\n\n\n  (* Note: it's important to specify the type of tokens as \"list token_id\", not\n     \"list nat\", even though token_id is defined to be nat. If a proof environment\n     has one value of type \"list token_id\" and the other of type \"list nat\", \n     proof scripts such as rewrite or omega may fail since token_id needs to\n     be unfolded. *)\n\n  Fixpoint process_buffer_aux (loc: int32) (n: nat) (tokens:list (list token_id))\n    (curr_res: Int32Set.t * Int32Set.t * Int32Set.t * Int32Set.t) :=\n    match n with\n    | O => None \n    | S m =>\n      match curr_res with\n      | (start_instrs, check_list, iat_check_list, call_check_list) =>\n        match tokens with\n        | nil => Some curr_res\n        | chunk::rest => (* There are left over bytes in the buffer *)\n          match chunk with\n          | nil => process_buffer_aux loc m rest curr_res\n          | _ =>\n            match\n             (dfa_recognize 256 non_cflow_dfa              chunk,\n              dfa_recognize 256 dir_cflow_dfa              chunk,\n              dfa_recognize 256 reinsjmp_nonIAT_dfa        chunk,\n              dfa_recognize 256 reinsjmp_IAT_or_RET_dfa    chunk,\n              dfa_recognize 256 reinsjmp_IAT_CALL_dfa      chunk) with\n\n            (* Non-Control-Flow Only *)\n            | (Some (len, remaining), None, None, None, None) => \n              process_buffer_aux (loc +32_n len) m (remaining::rest)\n              (Int32Set.add loc start_instrs, check_list, iat_check_list, call_check_list)\n\n            (* Direct Control-Flow (Only) *)\n            | (None, Some (len, remaining), None, None, None) => \n              match extract_disp_and_type (List.map token2byte (firstn len chunk)) with\n                | Some (disp, JMP_t)\n                | Some (disp, JCC_t) => \n                  process_buffer_aux (loc +32_n len) m (remaining::rest)\n                  (Int32Set.add loc start_instrs,\n                   Int32Set.add (loc +32_n len +32 disp) check_list,\n                   iat_check_list,\n                   call_check_list)\n                | Some (disp, CALL_t) =>\n                  process_buffer_aux (loc +32_n len) m (remaining::rest)\n                  (Int32Set.add loc start_instrs,\n                   Int32Set.add (loc +32_n len +32 disp) check_list,\n                   iat_check_list,\n                   Int32Set.add (loc +32_n len) call_check_list)\n                | _ => None\n              end\n\n            (* Non-IAT Indirect Control Flow (with Non-Control-Flow mask) *)\n            | (Some res0, None, Some (len, remaining), None, None) => \n              process_buffer_aux (loc +32_n len) m (remaining::rest)\n              (if is_nonIAT_call (List.map token2byte (firstn len chunk)) then\n                  (Int32Set.add loc start_instrs, check_list, iat_check_list,\n                   Int32Set.add (loc +32_n len) call_check_list)\n              else\n                  (Int32Set.add loc start_instrs, check_list, iat_check_list, call_check_list))\n\n            (* IAT Indirect Jump or Retrun (with Non-Control-Flow mask) *)\n            | (Some res0, None, None, Some (len, remaining), None) =>\n              match extract_IAT_jmp_dest (List.map token2byte (firstn len chunk)) with\n              (* Not an actual IAT jmp or RET (shouldn't happen) *)\n              | None => None\n              (* IAT jmp *)\n              | Some (Some indir) =>\n                process_buffer_aux (loc +32_n len) m (remaining::rest)\n                (Int32Set.add loc start_instrs, check_list,\n                 Int32Set.add (addrDisp indir) iat_check_list,\n                 call_check_list)\n              (* RET *)\n              | Some None =>\n                process_buffer_aux (loc +32_n len) m (remaining::rest)\n                (Int32Set.add loc start_instrs, check_list, iat_check_list, call_check_list)\n              end\n\n            (* IAT Call Only (No Mask necessary) *)\n            | (None, None, None, None, Some (len, remaining)) =>\n              match extract_IAT_call_dest (List.map token2byte (firstn len chunk)) with\n              (* Not actually an IAT call (shouldn't happen) *)\n              | None => None\n              (* IAT Call *)\n              | Some indir =>\n                process_buffer_aux (loc +32_n len) m (remaining::rest)\n                (Int32Set.add loc start_instrs, check_list,\n                Int32Set.add (addrDisp indir) iat_check_list,\n                Int32Set.add (loc +32_n len) call_check_list)\n              end\n\n            (* None of the DFAs matched or too many DFAs matched *)\n            | _ => None\n            end\n          end\n        end\n      end\n    end.\n\n  (* The idea here is, given a list of int8s representing the code,\n     we call process_buffer_aux with n := length of the (flattened)\n     list plus one for each sub-list; since each sub-list incurs one\n     recursive call, and each instruction is at least one byte long,\n     this should be enough calls to process_buffer_aux to process\n     everything in the buffer, without us having to worry about\n     termination proofs\n     Note: one way to avoid the n is would be to show each dfa consumes\n     at least one byte.\n     *)\n  Definition process_buffer (buffer: list (list int8)) :=\n    process_buffer_aux\n      (Word.repr 0)\n      ((List.fold_left (fun a b => a + b)%nat (List.map (fun l => length l + 1)%nat buffer) 0%nat) + 1)\n      (List.map (List.map byte2token) buffer) \n      (Int32Set.empty, Int32Set.empty, Int32Set.empty, Int32Set.empty).\n\n  Definition aligned_bool (a:int32):bool := \n    Zeq_bool (Zmod (unsigned a) chunkSize) 0.\n  Definition aligned (a:int32) := aligned_bool a = true.\n\n  Require Import Recdef.\n  Function checkAligned_aux (p: Int32Set.t * Z * nat) {measure snd p}\n    : bool :=\n  match p with\n    | (_, 0%nat) => true\n    | ((startAddrs, next), len) =>\n      (Int32Set.mem (repr next) startAddrs &&\n       checkAligned_aux (startAddrs, (next + chunkSize), \n                            (len - Zabs_nat chunkSize)%nat))\n  end.\n  intros. simpl. omega.\n  Defined.                          \n\n  (* checking that all aligned addresses between 0 and len is in startAddrs *)\n  Definition checkAligned (startAddrs:Int32Set.t) (len: nat) :bool :=\n    checkAligned_aux (startAddrs, 0, len).\n\n  (* checking all jump targets are either in startAddrs or are aligned addresses *)\n  Definition checkJmpTargets (jmpTargets: Int32Set.t) := \n    Int32Set.for_all aligned_bool jmpTargets.\n      \n  Definition checkIATAddresses (iat : IATBounds) (iatAddresses : Int32Set.t) : bool :=\n    match iat with\n    | iatbounds (start, size) =>\n        let checkAddress addr :=\n\t     andb\n                (andb (lequ start addr) (lequ addr (start +32 size)))\n                (eq (modu (addr -32 start) (repr (Z_of_nat (wordsize 31)))) (repr 0)) in\n          Int32Set.for_all checkAddress iatAddresses\n    end.\n\n  Definition checkCallAlignment (callAddrs : Int32Set.t) : bool :=\n    Int32Set.for_all aligned_bool callAddrs.\n\n  (* A section is in low memory if its end (start + length) is <= lowMemCutoff,\n     and the addition doesn't overflow *)\n  Definition checkExecSectionLowMemory (start : int32) (length : int32) : bool :=\n    andb (int32_lequ_bool (start +32 length) (@repr 31 lowMemCutoff)) (checkNoOverflow start length).\n\n\n  (* Given an executable section, represented as a list of bytes,\n  *  check that the section obeys policy *)\n  Definition checkExecSection (iat : IATBounds) (section: int32 * int32 * list (list int8)) : (bool * Int32Set.t) :=\n    match section with\n    | (start,len,buffer) =>\n        if checkExecSectionLowMemory start len then\n          match process_buffer buffer with\n          | None => (false, Int32Set.empty)\n          | Some (start_addrs, check_addrs, iat_check_addrs, call_check_addrs) => \n              (andb (andb (andb (checkAligned start_addrs (length buffer))\n                (checkJmpTargets check_addrs)) (checkIATAddresses iat iat_check_addrs))\n                (checkCallAlignment call_check_addrs),\n              start_addrs)\n          end\n        else\n          (false,Int32Set.empty)\n    end.\n\n  (* Given a PE file, check the following properties for each executable section:\n   * - All executable sections reside in low memory\n   * - All exported symbols target low memory chunk boundaries (checkExports)\n   * - No disassembled instruction spans a chunk boundary (checkAligned)\n   * - Static branches target low memory chunk boundaries (checkJmpTargets)\n   * - Non-IAT computed jumps are masked (reinsjmp_nonIAT_mask)\n   * - IAT computed jumps have return addr masked and actually target the iat\n   *     (reinsjmp_IAT_or_RET_mask + checkIATAddresses)\n   * - Call instructions end on a chunk bounary\n   * - No trap instructions (will not parse)\n   *)\n  Definition checkProgram (data : list (list int8)) : (bool * Int32Set.t) :=\n    let exec := getExecutableSections data in\n    let iat := getIATBounds data in\n    if checkExports data safeMask then\n      let exec_check := List.map (checkExecSection iat) exec in\n      let pass := List.fold_left andb (List.map (@fst _ _) exec_check) true in\n      let addrs :=\n        if pass then\n          List.fold_left Int32Set.union (List.map (@snd _ _) exec_check) Int32Set.empty\n        else\n          Int32Set.empty\n      in\n        (pass,addrs)\n    else\n      (false,Int32Set.empty).\n\n\nEnd BUILT_DFAS.\n\nRequire Import CompiledDFAs.\n\nDefinition checkProgram' (data : list (list int8)) : (bool * Int32Set.t) :=\n    checkProgram\n      non_cflow_dfa\n      dir_cflow_dfa\n      reinsjmp_nonIAT_dfa\n      reinsjmp_IAT_JMP_or_RET_dfa\n      reinsjmp_IAT_CALL_dfa\n      reinsjmp_nonIAT_mask\n      reinsjmp_IAT_JMP_or_RET_mask\n      reinsjmp_IAT_CALL_p\n      data.\n\nExtraction \"reinsverif.ml\" checkProgram'.\n", "meta": {"author": "mpettersson", "repo": "reins-verifier-proof", "sha": "44d0b8e0c29b07eb71b1d6d44b020648783409fb", "save_path": "github-repos/coq/mpettersson-reins-verifier-proof", "path": "github-repos/coq/mpettersson-reins-verifier-proof/reins-verifier-proof-44d0b8e0c29b07eb71b1d6d44b020648783409fb/REINS/ReinsVerifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1959585004462511}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.ZArith.ZArith\n        Coq.Strings.String\n        Coq.Arith.Mult\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Common.DecideableEnsembles\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Formats.IPChecksum\n        Fiat.Narcissus.Common.ComposeCheckSum.\n\nRequire Import\n        Bedrock.Word.\n\nSection AlignedDecoders.\n\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n\n  Lemma AlignedFormatThenC\n    : forall ce (c1 : _ -> Comp _) (c2 : _ -> Comp _)\n             (v1 : _ -> {n : nat & t (word 8) n})\n             (v2 : _ -> {n : nat & t (word 8) n})\n             (ce2 : _ -> CacheFormat)\n             (ce1 : _ -> CacheFormat),\n      refine (c1 ce) (ret (build_aligned_ByteString (projT2 (v1 ce)), (ce1 ce)))\n      -> (forall v ce',\n             computes_to (c1 ce) (v, ce')\n             -> refine (c2 ce') (ret (build_aligned_ByteString (projT2 (v2 ce')), (ce2 ce'))))\n      -> refine ((c1 ThenC c2) ce)\n                (ret (build_aligned_ByteString\n                        (Vector.append (projT2 (v1 ce)) (projT2 (v2 (ce1 ce)))),\n                      (ce2 (ce1 ce)))).\n  Proof.\n    unfold compose; intros.\n    unfold Bind2.\n    etransitivity.\n    apply refine_under_bind_both; eauto.\n    intros [? ?] ?.\n    rewrite H0; try eassumption.\n    simplify with monad laws.\n    simpl.\n    instantiate (1 := fun bc => ret (ByteString_enqueue_ByteString (fst bc) (build_aligned_ByteString (projT2 (v2 (snd bc)))), ce2 (snd bc))); simpl.\n    reflexivity.\n    simplify with monad laws.\n    simpl.\n    rewrite <- build_aligned_ByteString_append.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedFormatDoneC\n    : forall ce (c1 : _ -> Comp _)\n             (v1 : _ -> {n : nat & t (word 8) n})\n             (ce1 : _ -> CacheFormat),\n      refine (c1 ce) (ret (build_aligned_ByteString (projT2 (v1 ce)), (ce1 ce)))\n      -> refine ((c1 DoneC) ce)\n                (ret (build_aligned_ByteString (projT2 (v1 ce)), (ce1 ce))).\n  Proof.\n    unfold compose; intros.\n    unfold Bind2.\n    rewrite H.\n    simplify with monad laws.\n    simpl.\n    f_equiv.\n  Qed.\n\n  Variable addE_addE_plus :\n    forall (ce : CacheFormat) (n m : nat), addE (addE ce n) m = addE ce (n + m).\n  Variable addE_0 : forall ce, addE ce 0 = ce.\n  Variable addD_0 : forall cd, addD cd 0 = cd.\n\n  Lemma AlignedFormat2Char' {numBytes}\n    : forall (w : word 16) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 16)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_word (monoidUnit := ByteString_QueueMonoidOpt) w)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons\n                                                  _ (split1' 8 8 w) _\n                                                  (Vector.cons _ (split2' 8 8 w) _ v)), ce')).\n  Proof.\n    unfold compose, Bind2; intros.\n    intros; setoid_rewrite (@format_words' _ _ 8 8 addE_addE_plus w).\n    rewrite (@AlignedFormatChar _ _ 1) by apply aligned_format_char_eq.\n    simplify with monad laws.\n    unfold snd.\n    rewrite addE_addE_plus.\n    rewrite H.\n    simplify with monad laws.\n    unfold fst.\n    rewrite <- build_aligned_ByteString_append.\n    unfold append.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedFormat2Char {numBytes}\n    : forall (w : word 16) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 16)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_word (monoidUnit := ByteString_QueueMonoidOpt) w)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons\n                                                  _ (split2 8 8 w) _\n                                                  (Vector.cons _ (split1 8 8 w) _ v)), ce')).\n  Proof.\n    unfold compose, Bind2; intros.\n    intros; setoid_rewrite (@format_words _ _ 8 8 addE_addE_plus w).\n    rewrite (@AlignedFormatChar _ _ 1) by apply aligned_format_char_eq.\n    simplify with monad laws.\n    unfold snd.\n    rewrite addE_addE_plus.\n    rewrite H.\n    simplify with monad laws.\n    unfold fst.\n    rewrite <- build_aligned_ByteString_append.\n    unfold append.\n    f_equiv.\n  Qed.\n\n  Local Arguments split1 : simpl never.\n  Local Arguments split2 : simpl never.\n\n  Lemma CorrectAlignedEncoderForFormat2Char\n    : CorrectAlignedEncoder\n        (format_word (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun n => @SetCurrentBytes _ _ n 16).\n  Proof.\n    eapply CorrectAlignedEncoderForFormatNChar; eauto.\n  Qed.\n\n  Corollary AlignedDecode2Nat {C}\n            {numBytes}\n    : forall (v : Vector.t (word 8) (S (S numBytes)))\n             (t : _ -> Hopefully C)\n             cd,\n      HBind (decode_nat (monoidUnit := ByteString_QueueMonoidOpt) 16 (build_aligned_ByteString v) cd) as w\n                                                                                                           With t w\n                                                                                                         =\n                                                                                                         Let n := wordToNat (Core.append_word (Vector.nth v (Fin.FS Fin.F1)) (Vector.nth v Fin.F1)) in\n        t (n, build_aligned_ByteString (snd (Vector_split 2 _ v)), addD cd 16).\n  Proof.\n    unfold CacheDecode.\n    unfold decode_nat, DecodeBindOpt2; intros.\n    unfold BindOpt at 1.\n    rewrite AlignedDecode2Char.\n    reflexivity.\n  Qed.\n\n  Local Open Scope AlignedDecodeM_scope.\n\n  Lemma AlignedDecodeNatM {C : Set}\n        (t : nat -> DecodeM (C * _) ByteString)\n        (t' : nat -> forall {numBytes}, AlignedDecodeM C numBytes)\n    : (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_nat (monoidUnit := ByteString_QueueMonoidOpt) 8 v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- GetCurrentByte;\n                              n <- return (wordToNat b);\n                                            t' n).\n  Proof.\n    replace\n      (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                   decode_nat 8 v cd;\n                                                  t a b0 cd') with\n        (fun (v : ByteString) (cd : CacheDecode) =>\n           `(w, b, cd') <- decode_word (sz := 8) v cd;\n           t (wordToNat w) b cd'); intros.\n    eapply AlignedDecodeBindCharM; intros.\n    replace (fun numBytes : nat => n <- return (wordToNat b);\n                                               t' n numBytes) with\n        (fun numBytes : nat => t'  (wordToNat b) numBytes).\n    eapply H.\n    unfold BindAlignedDecodeM, ReturnAlignedDecodeM; simpl.\n    repeat (apply functional_extensionality_dep; intros); reflexivity.\n    repeat (apply functional_extensionality_dep; intros).\n    unfold decode_nat, DecodeBindOpt2; intros.\n    rewrite BindOpt_assoc; f_equal.\n    repeat (apply functional_extensionality_dep; intros).\n    unfold BindOpt.\n    destruct x1; destruct p; simpl.\n    reflexivity.\n  Qed.\n\n\n  Corollary AlignedFormat2Nat'\n            {numBytes}\n    : forall (n : nat) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 16)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_nat 16 (monoidUnit := ByteString_QueueMonoidOpt) n)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons\n                                                  _ (split1' 8 8 (natToWord 16 n)) _\n                                                  (Vector.cons _ (split2' 8 8 (natToWord 16 n)) _ v)), ce')).\n  Proof.\n    unfold format_nat; cbv beta; intros.\n    rewrite <- AlignedFormat2Char'; eauto.\n    reflexivity.\n  Qed.\n\n  Corollary AlignedFormat2Nat\n            {numBytes}\n    : forall (n : nat) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 16)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_nat 16 (monoidUnit := ByteString_QueueMonoidOpt) n)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons\n                                                  _ (split2 8 8 (natToWord 16 n)) _\n                                                  (Vector.cons _ (split1 8 8 (natToWord 16 n)) _ v)), ce')).\n  Proof.\n    unfold format_nat; cbv beta; intros.\n    rewrite <- AlignedFormat2Char; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatNat\n    : CorrectAlignedEncoder\n        (format_nat 8 (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun sz v idx n => @SetCurrentByte _ _ sz v idx (natToWord 8 n)).\n  Proof.\n    eapply refine_CorrectAlignedEncoder.\n    2: eapply CorrectAlignedEncoderForFormatChar_f.\n    unfold format_nat; intros.\n    split.\n    - intros ? ?.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format in H.\n      rewrite unfold_computes in H.\n      destruct_ex; intuition; subst; eauto.\n    - intros; intro.\n      eapply H.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format.\n      rewrite unfold_computes.\n      eexists; intuition; subst; eauto.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormat2Nat\n    : CorrectAlignedEncoder\n        (format_nat 16 (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun sz v idx n => SetCurrentBytes (sz := 2) v idx (natToWord 16 n)).\n  Proof.\n    eapply refine_CorrectAlignedEncoder.\n    2: eapply CorrectAlignedEncoderForFormatMChar_f; eauto.\n    unfold format_nat; intros; split.\n    - intros ? ?.\n      eapply FMapFormat.EquivFormat_Projection_Format; eauto.\n    - intros ? ?; intro.\n      eapply H.\n      eapply FMapFormat.EquivFormat_Projection_Format; eauto.\n  Qed.\n\n  Fixpoint AlignedEncodeVector' n n' {sz} {S}\n           (S_format_align : forall numBytes, AlignedEncodeM (S := S) numBytes)\n           (numBytes : nat)\n           v\n           idx\n           (Ss : Vector.t S sz)\n           env :=\n    match n with\n    | 0 => if Coq.Init.Nat.ltb idx (1 + numBytes)\n           then @ReturnAlignedEncodeM _ (Vector.t S 0) _ v idx (Vector.nil _) env\n           else Error (InfoError \"Encoding vector\" EndOfBuffer)\n    | S n'' =>  Ifopt (Vector_nth_opt Ss n') as s Then (HBind (S_format_align numBytes v idx s env)\n        as a'\n             With\n             AlignedEncodeVector' n'' (1 + n') S_format_align numBytes (fst (fst a'))\n             (snd (fst a'))\n             Ss (snd a'))\n                                                  Else (Error (InfoError \"Encoding vector (S n)\" EndOfBuffer))\n    end.\n\n  Definition AlignedEncodeVector {sz} {S}\n             (S_format_align : forall numBytes, AlignedEncodeM (S := S) numBytes)\n    : forall numBytes, AlignedEncodeM (S := Vector.t S sz) numBytes :=\n    AlignedEncodeVector' sz 0 S_format_align .\n\n  Lemma Vector_nth_opt_append S\n    : forall n (t2 : Vector.t S n) m (t1 : Vector.t S m) k,\n      Vector_nth_opt (Vector.append t1 t2) (k + m) =\n      Vector_nth_opt t2 k.\n  Proof.\n    induction t1; simpl; intros; eauto.\n    rewrite plus_comm; simpl; eauto.\n    rewrite (plus_comm n0 k); eauto.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatVector {sz}\n        {S}\n    : forall (format_S : FormatM S ByteString)\n             (encode_S : forall numBytes : nat, AlignedEncodeM numBytes)\n             (encode_S_OK : CorrectAlignedEncoder format_S encode_S)\n             (encode_A_OK' :\n                forall (s : S) sz (l : Vector.t S sz)\n                       (env : CacheFormat) (tenv' tenv'' : ByteString * CacheFormat),\n                  format_S s env \u220b tenv' ->\n                  Vector.format_Vector format_S l (snd tenv') \u220b tenv'' ->\n                  exists tenv3 tenv4 : _ * CacheFormat,\n                    projT1 encode_S_OK s env = Ok tenv3\n                    /\\ Vector.format_Vector format_S l (snd tenv3) \u220b tenv4),\n      CorrectAlignedEncoder (Vector.format_Vector format_S)\n                            (AlignedEncodeVector encode_S (sz := sz)).\n  Proof.\n    (*\n    intros; induction sz.\n    - eapply refine_CorrectAlignedEncoder with (format' := fun s env => ret (mempty, env)).\n      intros.\n      pattern s; eapply Vector.case0; split.\n      + reflexivity.\n      + intros; intro.\n        eapply H; eauto.\n      + unfold AlignedEncodeVector; simpl.\n        eapply CorrectAlignedEncoderForDoneC.\n    - eapply refine_CorrectAlignedEncoder with (format' :=\n                                                  SequenceFormat.sequence_Format\n                                                    (FMapFormat.Projection_Format format_S Vector.hd)\n                                                    (FMapFormat.Projection_Format (Vector.format_Vector format_S) Vector.tl)).\n      + intros; pattern sz, s; eapply Vector.caseS; intros; simpl; split.\n        * unfold SequenceFormat.sequence_Format; simpl.\n          unfold compose, Bind2.\n          f_equiv; [ apply FMapFormat.EquivFormat_Projection_Format | intro].\n          f_equiv; apply FMapFormat.EquivFormat_Projection_Format.\n        * unfold SequenceFormat.sequence_Format; simpl;\n            unfold compose, Bind2; intros; intro.\n          computes_to_inv.\n          eapply H.\n          computes_to_econstructor.\n          eapply (proj1 (FMapFormat.EquivFormat_Projection_Format _ _ _ _)).\n          simpl; eauto.\n          computes_to_econstructor.\n          eapply (proj1 (FMapFormat.EquivFormat_Projection_Format _ _ _ _)).\n          simpl; eauto.\n          eauto.\n      + unfold AlignedEncodeVector.\n        eapply CorrectAlignedEncoder_morphism.\n        apply EquivFormat_reflexive.\n        2: eapply CorrectAlignedEncoderForThenC.\n        2: eapply CorrectAlignedEncoderProjection; eauto.\n        (* 2: eapply CorrectAlignedEncoderProjection; eauto. *)\n        intros.\n        pattern sz, w; apply Vector.caseS; intros.\n        unfold AppendAlignedEncodeM, Projection_AlignedEncodeM,\n        AlignedEncodeVector; simpl.\n        destruct (encode_S sz0 v idx h c) as [ [ [? ?] ?] | ] eqn: ?; simpl; eauto.\n        assert (forall n' m (t1 : Vector.t S m) n (t2 : Vector.t S n) sz0 t0 k idx cf,\n                   AlignedEncodeVector' n' (k + m) encode_S sz0 t0 idx (Vector.append t1 t2) cf =\n                   AlignedEncodeVector' n' k encode_S sz0 t0 idx t2 cf).\n        { clear; induction n'; simpl; intros; eauto.\n          rewrite Vector_nth_opt_append; simpl.\n          destruct (Vector_nth_opt t2 k); simpl; eauto.\n          destruct (encode_S sz0 t0 idx s cf) as [ [ [? ?] ?] | ] eqn: ?; simpl; eauto.\n          erewrite <- IHn' with (k := 1 + k); simpl; reflexivity.\n        }\n        instantiate (1 := fun sz v idx v' c => encode_S sz v idx (Vector.hd v') c).\n        simpl; rewrite Heqo; simpl.\n        erewrite <- H with (k := 0) (m := 1)\n                           (t1 := Vector.cons _ h _ (Vector.nil _)).\n        reflexivity.\n        simpl; rewrite Heqo; reflexivity.\n        instantiate (1 := CorrectAlignedEncoderProjection _ _ _ encode_S_OK).\n        intros.\n        match goal with\n          |- exists _ _, (projT1 ?H) ?s ?env = _ /\\ _ =>\n          destruct (projT1 H s env) eqn: ? ;\n            generalize (proj1 (projT2 H) s env); intros\n        end.\n        * apply proj1 in H1.\n          destruct p.\n          eapply H1 in Heqh.\n          eapply (proj2 (FMapFormat.EquivFormat_Projection_Format _ _ _ _)) in H.\n          eapply (proj2 (FMapFormat.EquivFormat_Projection_Format _ _ _ _)) in H0.\n          specialize (encode_A_OK' _ _ _ _ _ _ H H0).\n          destruct_ex; intuition; subst.\n          destruct encode_S_OK.\n          destruct a.\n          destruct a0.\n          unfold CorrectAlignedEncoderProjection; simpl in *.\n          eexists _, _; split.\n          unfold Basics.compose; eauto.\n          eapply FMapFormat.EquivFormat_Projection_Format.\n          eauto.\n        * apply proj2 in H1.\n          eapply isError, H1 in Heqh.\n          eapply Heqh in H; intuition.\n  Qed.\n     *)\n  Admitted.\n  Lemma CorrectAlignedEncoderForFormatNEnum\n        m\n        {len}\n        (codes : t (word (m * 8)) (S len))\n    : CorrectAlignedEncoder\n        (format_enum codes (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun sz v idx n => SetCurrentBytes (sz := m) v idx (Vector.nth codes n)).\n  Proof.\n    eapply refine_CorrectAlignedEncoder.\n    2: eapply CorrectAlignedEncoderForFormatMChar_f; eauto.\n    unfold format_enum; intros; split.\n    - intros ? ?.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format in H.\n      rewrite unfold_computes in H.\n      destruct_ex; intuition; subst; eauto.\n    - intros; intro.\n      eapply H.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format.\n      rewrite unfold_computes.\n      eexists _; intuition; subst; eauto.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatEnum\n        {len}\n        (codes : t (word 8) (S len))\n    : CorrectAlignedEncoder\n        (format_enum codes (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun sz v idx n => @SetCurrentByte _ _ sz v idx (Vector.nth codes n)).\n  Proof.\n    eapply refine_CorrectAlignedEncoder.\n    2: eapply CorrectAlignedEncoderForFormatChar_f; eauto.\n    unfold format_enum; intros; split.\n    - intros ? ?.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format in H.\n      rewrite unfold_computes in H.\n      destruct_ex; intuition; subst; eauto.\n    - intros; intro.\n      eapply H.\n      unfold FMapFormat.Projection_Format, FMapFormat.Compose_Format.\n      rewrite unfold_computes.\n      eexists _; intuition; subst; eauto.\n  Qed.\n\n  Definition aligned_option_encode {S}\n             (encode_Some : forall sz : nat, @AlignedEncodeM _ S sz)\n             (encode_None : forall sz : nat, @AlignedEncodeM _ () sz)\n             (sz : nat)\n    : @AlignedEncodeM _ (option S) sz :=\n    fun v idx s_opt => Ifopt s_opt as s Then encode_Some _ v idx s\n                                         Else encode_None _ v idx ().\n\n    Lemma CorrectAlignedEncoderForFormatOption {S}\n        (Some_format : FormatM S _)\n        (None_format : FormatM () _)\n        (encode_Some : forall sz : nat, @AlignedEncodeM _ S sz)\n        (encode_None : forall sz : nat, @AlignedEncodeM _ () sz)\n        (encode_Some_OK : CorrectAlignedEncoder Some_format encode_Some)\n        (encode_None_OK : CorrectAlignedEncoder None_format encode_None)\n    : CorrectAlignedEncoder\n        (Option.format_option Some_format None_format)\n        (aligned_option_encode encode_Some encode_None).\n  Proof.\n    exists (Option.option_encode (projT1 encode_Some_OK) (projT1 encode_None_OK));\n      simpl; intuition.\n    - destruct s; simpl in *.\n      eapply (proj1 (projT2 encode_Some_OK) s); eauto.\n      eapply (proj1 (projT2 encode_None_OK)); eauto.\n    - destruct s; simpl in *.\n      eapply (proj1 (projT2 encode_Some_OK) s); eauto.\n      eapply (proj1 (projT2 encode_None_OK)); eauto.\n    - destruct s; simpl in *.\n      eapply (proj1 (proj2 (projT2 encode_Some_OK))); eauto.\n      eapply (proj1 (proj2 (projT2 encode_None_OK))); eauto.\n    - intros ? ?.\n      destruct s.\n      eapply (proj2 (proj2 (projT2 encode_Some_OK)) _ s); eauto.\n      eapply (proj2 (proj2 (projT2 encode_None_OK)) _ ()); eauto.\n  Qed.\n\n  Lemma optimize_under_if_opt {A ResultT}\n    : forall (a_opt : option A) (t t' : A -> ResultT) (e e' : ResultT),\n      (forall a, t a = t' a) -> e = e' ->\n      Ifopt a_opt as a Then t a Else e = Ifopt a_opt as a Then t' a Else e'.\n  Proof.\n    intros; subst; eauto.\n    destruct a_opt; eauto.\n  Qed.\n\n  Lemma rewrite_under_LetIn\n        {A B}\n    : forall (a : A) (k k' : A -> B),\n      (forall a, k a = k' a) -> LetIn a k = LetIn a k'.\n  Proof.\n    intros; unfold LetIn; eauto.\n  Qed.\n\n  Fixpoint Guarded_Vector_split\n           (sz n : nat)\n           {struct sz}\n    : Vector.t (word 8) n\n      -> Vector.t (word 8) (sz + (n - sz)) :=\n    match sz, n return\n          Vector.t _ n\n          -> Vector.t (word 8) (sz + (n - sz))\n    with\n    | 0, _ => fun v => (eq_rect _ (Vector.t _) v _ (minus_n_O n))\n    | S n', 0 =>\n      fun v =>\n        Vector.cons _ (wzero _) _ (Guarded_Vector_split n' _ v)\n    | S n', S sz' =>\n      fun v =>\n        Vector.cons _ (Vector.hd v) _ (Guarded_Vector_split n' _ (Vector.tl v))\n    end .\n\n  Lemma le_B_Guarded_Vector_split\n        {n}\n        (b : Vector.t _ n)\n        (m : nat)\n    : {b' : ByteString | le_B b' (build_aligned_ByteString b)}.\n    eexists (build_aligned_ByteString\n               (snd (Vector_split _ _ (Guarded_Vector_split m n b)))).\n    abstract (unfold build_aligned_ByteString, le_B; simpl;\n              unfold length_ByteString; simpl; Lia.lia).\n  Defined.\n\n  Lemma build_aligned_ByteString_eq_split\n    : forall m n b H0,\n      (m <= n)%nat\n      -> build_aligned_ByteString b =\n         (build_aligned_ByteString (eq_rect (m + (n - m)) (t (word 8)) (Guarded_Vector_split m n b) n H0)).\n  Proof.\n    intros.\n    intros; eapply ByteString_f_equal; simpl.\n    instantiate (1 := eq_refl _); reflexivity.\n    instantiate (1 := eq_refl _).\n    simpl.\n    revert n b H0 H; induction m; simpl.\n    intros ? ?; generalize (minus_n_O n).\n    intros; rewrite <- Equality.transport_pp.\n    apply Eqdep_dec.eq_rect_eq_dec; auto with arith.\n    intros.\n    inversion H; subst.\n    - revert b H0 IHm; clear.\n      intro; pattern m, b; apply Vector.caseS; simpl; intros.\n      assert ((n + (n - n)) = n) by Lia.lia.\n      rewrite eq_rect_Vector_cons with (H' := H).\n      f_equal.\n      erewrite <- IHm; eauto.\n    - revert b H0 IHm H1; clear.\n      intro; pattern m0, b; apply Vector.caseS; simpl; intros.\n      assert ((m + (n - m)) = n) by Lia.lia.\n      erewrite eq_rect_Vector_cons with (H' := H).\n      f_equal.\n      erewrite <- IHm; eauto.\n      Lia.lia.\n  Qed.\n\n  Lemma ByteAlign_Decode_w_Measure_le {A}\n    : forall (dec_a : ByteString -> CacheDecode -> Hopefully (A * ByteString * CacheDecode))\n             (n m : nat)\n             (dec_a' : Vector.t (word 8) (m + (n - m)) -> A)\n             (cd : CacheDecode)\n             (f : CacheDecode -> CacheDecode)\n             (b : Vector.t (word 8) n)\n             decode_a_le\n             (dec_fail : ~ (m <= n)%nat\n                         -> forall b cd, is_error (dec_a (build_aligned_ByteString (numBytes := n) b) cd)),\n      (forall b cd, dec_a (build_aligned_ByteString b) cd =\n                    Ok (dec_a' b, build_aligned_ByteString (snd (Vector_split m (n - m) b)), f cd))\n      -> forall e, Decode_w_Measure_le dec_a (build_aligned_ByteString b) cd decode_a_le ~=\n         match Compare_dec.le_dec m n with\n         | left e => (Let a := dec_a' (Guarded_Vector_split m n b) in\n                          Ok (a, le_B_Guarded_Vector_split b m, f cd))\n         | right _ => Error e \n         end.\n  Proof.\n    intros.\n    destruct (Compare_dec.le_dec m n).\n    - assert (m + (n - m) = n) by Lia.lia.\n      assert (forall b, Decode_w_Measure_le dec_a (build_aligned_ByteString b) cd decode_a_le\n                        = Decode_w_Measure_le dec_a (build_aligned_ByteString ( eq_rect _ _ (Guarded_Vector_split m n b) _ H0)) cd decode_a_le).\n      { revert l; clear; intros.\n        destruct (Decode_w_Measure_le dec_a (build_aligned_ByteString b) cd decode_a_le)\n          as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_le_eq' in Heqh.\n        simpl in Heqh.\n        destruct (Decode_w_Measure_le dec_a\n                                      _ cd decode_a_le) as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_le_eq' in Heqh0.\n        simpl in *.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0 by eauto.\n        rewrite Heqh0 in Heqh.\n        injection Heqh; intros.\n        rewrite H, H2;\n          repeat f_equal.\n        revert l0 l1. rewrite H1; intros; f_equal.\n        f_equal; apply Core.le_uniqueness_proof.\n        apply ByteString_id.\n        eapply isError, Decode_w_Measure_le_eq'' in Heqh0.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0 by eauto.\n        rewrite Heqh in Heqh0; inversion Heqh0.\n        apply ByteString_id.\n        erewrite build_aligned_ByteString_eq_split in Heqh by eauto.\n        rewrite Heqh; reflexivity.\n      }\n      rewrite H1.\n      match goal with\n        |- ?a ~= _ => destruct a as [ [ [? ?] ? ] | ] eqn: ?\n      end.\n      + constructor; left.\n        eapply Decode_w_Measure_le_eq' in Heqh.\n        assert (dec_a (build_aligned_ByteString (Guarded_Vector_split m n b)) cd\n                = Ok (a, proj1_sig s, c)).\n        { destruct s; simpl in *.\n          rewrite <- Heqh.\n          unfold build_aligned_ByteString; repeat f_equal; simpl.\n          eapply ByteString_f_equal; simpl.\n          instantiate (1 := eq_refl _); reflexivity.\n          instantiate (1 := sym_eq H0).\n          clear H1.\n          destruct H0; reflexivity.\n        }\n        rewrite H in H2; injection H2; intros.\n        rewrite H3, H5; unfold LetIn; simpl.\n        repeat f_equal.\n        destruct s; simpl in *.\n        unfold le_B_Guarded_Vector_split; simpl.\n        clear H1; revert l0.\n        rewrite <- H4; intros.\n        f_equal; apply Core.le_uniqueness_proof.\n        apply ByteString_id.\n      + apply isError, Decode_w_Measure_le_eq'' in Heqh.\n        pose proof (H (Guarded_Vector_split m n b) cd).\n        match goal with\n        | [H : is_error ?x |- _ ] => destruct x eqn:?Heqh; try solve[inversion H]\n        end.\n        \n        assert (Ok (dec_a' (Guarded_Vector_split m n b),\n                     build_aligned_ByteString (snd (Vector_split m (n - m) (Guarded_Vector_split m n b))),\n                     f cd) = Error c0).\n        { \n          rewrite <- Heqh0.\n          rewrite <- H.\n          repeat f_equal.\n          eapply ByteString_f_equal; simpl.\n          instantiate (1 := eq_refl _); reflexivity.\n          instantiate (1 := sym_eq H0).\n          clear H1.\n          destruct H0; reflexivity.\n        }\n        discriminate.\n    - eapply dec_fail in n0; simpl.\n      eapply Specs.Decode_w_Measure_le_eq' in n0.\n      match goal with\n      | [H : is_error ?x |- _ ] => destruct x eqn:?Heqh; try solve[inversion H]\n      end. rewrite Heqh.\n      apply Error_eq.\n  Qed.\n\n  Lemma lt_B_Guarded_Vector_split\n        {n}\n        (b : Vector.t _ n)\n        (m : nat)\n        (m_OK : lt 0 m)\n        (_ : ~ lt n m)\n    : {b' : ByteString | lt_B b' (build_aligned_ByteString b)}.\n    eexists (build_aligned_ByteString\n               (snd (Vector_split _ _ (Guarded_Vector_split m n b)))).\n    abstract (unfold build_aligned_ByteString, lt_B; simpl;\n              unfold length_ByteString; simpl; Lia.lia).\n  Defined.\n\n  Fixpoint BytesToString {sz}\n           (b : ByteBuffer.t sz)\n    : string :=\n    match b with\n    | Vector.nil => EmptyString\n    | Vector.cons a _ b' => String (Ascii.ascii_of_N (wordToN a)) (BytesToString b')\n    end.\n\n  Fixpoint StringToBytes\n           (s : string)\n    : ByteBuffer.t (String.length s) :=\n    match s return ByteBuffer.t (String.length s) with\n    | EmptyString => Vector.nil _\n    | String a s' => Vector.cons _ (NToWord 8 (Ascii.N_of_ascii a)) _ (StringToBytes s')\n    end.\n\n  Lemma ByteAlign_Decode_w_Measure_lt {A}\n    : forall (dec_a : nat -> ByteString -> CacheDecode -> Hopefully (A * ByteString * CacheDecode))\n             (n m : nat)\n             (dec_a' : forall m n, Vector.t (word 8) (m + n) -> A)\n             (cd : CacheDecode)\n             (f : nat -> CacheDecode -> CacheDecode)\n             (b : Vector.t (word 8) n)\n             (m_OK : lt 0 m)\n             decode_a_le\n             (dec_fail : (lt n m)%nat\n                         -> forall b cd, is_error (dec_a m (build_aligned_ByteString (numBytes := n) b) cd)),\n      (forall n m b cd, dec_a m (build_aligned_ByteString b) cd =\n                          Ok (dec_a' _ _ b, build_aligned_ByteString (snd (Vector_split m n b)), f m cd))\n      -> forall e, Decode_w_Measure_lt (dec_a m) (build_aligned_ByteString b) cd decode_a_le ~=\n           match Compare_dec.lt_dec n m with\n           | left _ => Error e\n           | right n' => (Let a := dec_a' _ _ (Guarded_Vector_split m n b) in\n                            Ok (a, lt_B_Guarded_Vector_split b m m_OK n' , f m cd))\n           end.\n  Proof.\n    intros.\n    destruct (Compare_dec.lt_dec m n);\n      destruct (Compare_dec.lt_dec n m); try Lia.lia.\n    - assert (m + (n - m) = n) by Lia.lia.\n      assert (forall b, Decode_w_Measure_lt (dec_a m) (build_aligned_ByteString b) cd decode_a_le\n                        = Decode_w_Measure_lt (dec_a m)(build_aligned_ByteString ( eq_rect _ _ (Guarded_Vector_split m n b) _ H0)) cd decode_a_le).\n      { revert l; clear; intros.\n        destruct (Decode_w_Measure_lt (dec_a m) (build_aligned_ByteString b) cd decode_a_le)\n          as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_lt_eq' in Heqh.\n        simpl in Heqh.\n        destruct (Decode_w_Measure_lt (dec_a m)\n                                      _ cd decode_a_le) as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_lt_eq' in Heqh0.\n        unfold proj1_sig in Heqh0.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0.\n        rewrite Heqh0 in Heqh.\n        injection Heqh; intros.\n        rewrite H, H2;\n          repeat f_equal.\n        revert l1 l0. rewrite H1; intros; f_equal.\n        f_equal; apply Core.le_uniqueness_proof.\n        Lia.lia.\n        apply ByteString_id.\n        eapply isError, Decode_w_Measure_lt_eq'' in Heqh0.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0 by Lia.lia.\n        rewrite Heqh in Heqh0.\n        inversion Heqh0.\n        apply ByteString_id.\n        erewrite (build_aligned_ByteString_eq_split m n) in Heqh by Lia.lia.\n        rewrite Heqh; reflexivity.\n      }\n      rewrite H1.\n      match goal with\n        |- ?a ~= _ => destruct a as [ [ [? ?] ? ] | ] eqn: ?\n      end.\n      + constructor; left.\n        eapply Decode_w_Measure_lt_eq' in Heqh.\n        assert (dec_a m (build_aligned_ByteString (Guarded_Vector_split m n b)) cd\n                = Ok (a, proj1_sig s, c)).\n        { destruct s; simpl in *.\n          rewrite <- Heqh.\n          unfold build_aligned_ByteString; repeat f_equal; simpl.\n          eapply ByteString_f_equal; simpl.\n          instantiate (1 := eq_refl _); reflexivity.\n          instantiate (1 := sym_eq H0).\n          clear H1.\n          destruct H0; reflexivity.\n        }\n        rewrite H in H2; injection H2; intros.\n        rewrite H3, H5; unfold LetIn; simpl.\n        repeat f_equal.\n        destruct s; simpl in *.\n        unfold lt_B_Guarded_Vector_split; simpl.\n        clear H1; revert l0.\n        rewrite <- H4; intros.\n        f_equal. apply Core.le_uniqueness_proof.\n        apply ByteString_id.\n      + apply isError, Decode_w_Measure_lt_eq'' in Heqh.\n        pose proof (H _ _ (Guarded_Vector_split m n b) cd).\n        match goal with\n        | [H : is_error ?x |- _ ] => destruct x eqn:?Heqh; try solve[inversion H]\n        end.\n        assert (Ok (dec_a' _ _ (Guarded_Vector_split m n b),\n                       build_aligned_ByteString (snd (Vector_split m (n - m) (Guarded_Vector_split m n b))),\n                       f m cd) = Error c0).\n        { rewrite <- Heqh0.\n          rewrite <- H.\n          repeat f_equal.\n          eapply ByteString_f_equal; simpl.\n          instantiate (1 := eq_refl _); reflexivity.\n          instantiate (1 := sym_eq H0).\n          clear H1.\n          destruct H0; reflexivity.\n        }\n        discriminate.\n    - eapply dec_fail in l; simpl.\n      eapply Specs.Decode_w_Measure_lt_eq' in l.\n      constructor; right; constructor; simpl; eauto. \n    - assert (m = n) by Lia.lia; subst.\n      assert (n + (n - n) = n) by Lia.lia.\n      assert (forall b, Decode_w_Measure_lt (dec_a n) (build_aligned_ByteString b) cd decode_a_le\n                        = Decode_w_Measure_lt (dec_a n)(build_aligned_ByteString ( eq_rect _ _ (Guarded_Vector_split n n b) _ H0)) cd decode_a_le).\n      { clear; intros.\n        destruct (Decode_w_Measure_lt (dec_a n) (build_aligned_ByteString b) cd decode_a_le)\n          as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_lt_eq' in Heqh.\n        simpl in Heqh.\n        destruct (Decode_w_Measure_lt (dec_a n)\n                                      _ cd decode_a_le) as [ [ [? [? ?] ] ?] | ] eqn: ?.\n        apply Decode_w_Measure_lt_eq' in Heqh0.\n        unfold proj1_sig in Heqh0.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0.\n        rewrite Heqh0 in Heqh.\n        injection Heqh; intros.\n        rewrite H, H2;\n          repeat f_equal.\n        revert l l0. rewrite H1; intros; f_equal.\n        f_equal; apply Core.le_uniqueness_proof.\n        Lia.lia.\n        apply ByteString_id.\n        eapply isError, Decode_w_Measure_lt_eq'' in Heqh0.\n        rewrite <- build_aligned_ByteString_eq_split in Heqh0 by Lia.lia.\n        rewrite Heqh in Heqh0.\n        inversion Heqh0.\n        apply ByteString_id.\n        erewrite (build_aligned_ByteString_eq_split n n) in Heqh by Lia.lia.\n        rewrite Heqh; reflexivity.\n      }\n      rewrite H1.\n      match goal with\n        |- ?a ~= _ => destruct a as [ [ [? ?] ? ] | ] eqn: ?\n      end.\n      constructor; left.\n      eapply Decode_w_Measure_lt_eq' in Heqh.\n      assert (dec_a n (build_aligned_ByteString (Guarded_Vector_split n n b)) cd\n              = Ok (a, proj1_sig s, c)).\n      { destruct s; simpl in *.\n        rewrite <- Heqh.\n        unfold build_aligned_ByteString; repeat f_equal; simpl.\n        eapply ByteString_f_equal; simpl.\n        instantiate (1 := eq_refl _); reflexivity.\n        instantiate (1 := sym_eq H0).\n        clear H1.\n        destruct H0; reflexivity.\n      }\n      rewrite H in H2; injection H2; intros.\n      rewrite H3, H5; unfold LetIn; simpl.\n      repeat f_equal.\n      destruct s; simpl in *.\n      unfold lt_B_Guarded_Vector_split; simpl.\n      clear H1; revert l.\n      rewrite <- H4; intros.\n      f_equal. apply Core.le_uniqueness_proof.\n      apply ByteString_id.\n      apply isError, Decode_w_Measure_lt_eq'' in Heqh.\n      pose proof (H _ _ (Guarded_Vector_split n n b) cd).\n      match goal with\n        | [H : is_error ?x |- _ ] => destruct x eqn:?Heqh; try solve[inversion H]\n      end.\n      assert (Ok (dec_a' _ _ (Guarded_Vector_split n n b),\n                    build_aligned_ByteString (snd (Vector_split n (n - n) (Guarded_Vector_split n n b))),\n                    f n cd) = Error c0).\n      { rewrite <- Heqh0.\n        rewrite <- H.\n        repeat f_equal.\n        eapply ByteString_f_equal; simpl.\n        instantiate (1 := eq_refl _); reflexivity.\n        instantiate (1 := sym_eq H0).\n        clear H1.\n        destruct H0; reflexivity.\n      }\n      discriminate.\n  Qed.\n\n  Lemma optimize_under_match {A B} {P}\n    : forall (a a' : A) (f : {P a a'} + {~P a a'}) (t t' : _ -> B)\n             (e e' : _ -> B),\n      (forall (a a' : A) (a_eq : _), t a_eq = t' a_eq)\n      -> (forall (a a' : A) (a_neq : _), e a_neq = e' a_neq)\n      -> match f with\n         | left e => t e\n         | right n => e n\n         end =\n         match f with\n         | left e => t' e\n         | right n => e' n\n         end.\n  Proof.\n    destruct f; simpl; intros; eauto.\n  Qed.\n\n  Lemma optimize_Fix {A}\n    : forall\n      (body : forall x : ByteString,\n          (forall y : ByteString,\n              lt_B y x -> (fun _ : ByteString => CacheDecode -> option (A * ByteString * CacheDecode)) y) ->\n          (fun _ : ByteString => CacheDecode -> option (A * ByteString * CacheDecode)) x)\n      (body' : forall x : nat,\n          (forall y : nat,\n              (lt y x)%nat ->\n              (fun m : nat =>\n                 t (word 8) m -> CacheDecode ->\n                 option (A * {n : _ & Vector.t _ n} * CacheDecode)) y) ->\n          t (word 8) x -> CacheDecode -> option (A * {n : _ & Vector.t _ n} * CacheDecode) )\n      n (b : Vector.t _ n) (cd : CacheDecode)\n      (body_Proper :\n         forall (x0 : ByteString)\n                (f g : forall y : ByteString, lt_B y x0 -> CacheDecode -> option (A * ByteString * CacheDecode)),\n           (forall (y : ByteString) (p : lt_B y x0), f y p = g y p) -> body x0 f = body x0 g)\n      (body'_Proper :\n         forall (x0 : nat)\n                (f\n                   g : forall y : nat,\n                    (lt y x0)%nat -> t (word 8) y -> CacheDecode -> option (A * {n0 : nat & t Core.char n0} * CacheDecode)),\n           (forall (y : nat) (p : (lt y x0)%nat), f y p = g y p) -> body' x0 f = body' x0 g)\n    ,\n      (forall n (b : Vector.t (word 8) n)\n              (rec : forall x : ByteString,\n                  lt_B x (build_aligned_ByteString b) -> CacheDecode -> option (A * ByteString * CacheDecode))\n              (rec' : forall x : nat,\n                  (lt x n)%nat -> t Core.char x -> CacheDecode ->\n                  option (A * {n : _ & Vector.t _ n} * CacheDecode))\n              cd,\n          (forall m cd b a b' cd' b_lt b_lt' ,\n              rec' m b_lt' b cd = Some (a, b', cd')\n              -> rec (build_aligned_ByteString b) b_lt cd = Some (a, build_aligned_ByteString (projT2 b'), cd'))\n          -> (forall m cd b b_lt b_lt' ,\n                 rec' m b_lt' b cd = None\n                 -> rec (build_aligned_ByteString b) b_lt cd = None)\n          -> body (build_aligned_ByteString b) rec cd\n             = match (body' n rec' b cd) with\n               | Some (a, b', cd') => Some (a, build_aligned_ByteString (projT2 b'), cd')\n               | None => None\n               end)\n      -> Fix well_founded_lt_b (fun _ : ByteString => CacheDecode -> option (A * ByteString * CacheDecode)) body (build_aligned_ByteString b) cd =\n         match Fix Wf_nat.lt_wf (fun m : nat => Vector.t (word 8) m -> CacheDecode -> option (A * { n : _ & Vector.t _ n} * CacheDecode)) body' n b cd with\n         | Some (a, b', cd') => Some (a, build_aligned_ByteString (projT2 b'), cd')\n         | None => None\n         end.\n  Proof.\n    intros.\n    revert cd b; pattern n.\n    eapply (well_founded_ind Wf_nat.lt_wf); intros.\n    rewrite Init.Wf.Fix_eq, Init.Wf.Fix_eq.\n    apply H; intros.\n    erewrite H0, H1; eauto.\n    rewrite H0, H1; eauto.\n    eauto.\n    eauto.\n  Qed.\n\n  Lemma lift_match_if_ByteAlign\n        {T1}\n        {T2 T3 T4 A : T1 -> Type}\n        {B B' C}\n    : forall (b : bool)\n             (t1 : T1)\n             (t e : option (A t1 * B * C))\n             (b' : forall t1, T2 t1 -> T3 t1 -> T4 t1 -> bool)\n             (t' e' : forall t1, T2 t1 -> T3 t1 -> T4 t1 -> option (A t1 * B' * C))\n             (f : B' -> B)\n             (t2 : T2 t1)\n             (t3 : T3 t1)\n             (t4 : T4 t1),\n      (b = b' t1 t2 t3 t4)\n      -> (t = match t' t1 t2 t3 t4 with\n              | Some (a, b', c) => Some (a, f b', c)\n              | None => None\n              end)\n      -> (e = match e' t1 t2 t3 t4 with\n              | Some (a, b', c) => Some (a, f b', c)\n              | None => None\n              end)\n      -> (if b then t else e) =\n         match (fun t1 t2 t3 t4 => if b' t1 t2 t3 t4 then t' t1 t2 t3 t4 else e' t1 t2 t3 t4) t1 t2 t3 t4 with\n         | Some (a, b', c) => Some (a, f b', c)\n         | None => None\n         end.\n  Proof.\n    intros; destruct b; eauto; rewrite <- H; simpl; eauto.\n  Qed.\n\n  Lemma lift_match_if_sumbool_ByteAlign\n        {T1}\n        {T3 : T1 -> Type}\n        {P : forall t1 (t3 : T3 t1), Prop}\n        {T2 T4 A : T1 -> Type}\n        {B B' C}\n    : forall (t1 : T1)\n             (t3 : T3 t1)\n             (b : forall t1 t3, {P t1 t3} + {~P t1 t3})\n             (t : _ -> option (A t1 * B * C))\n             (e : _ -> option (A t1 * B * C))\n             (b' : forall t1 t3, T2 t1 -> T4 t1 -> {P t1 t3} + {~P t1 t3})\n             (t' : forall t1 t3, T2 t1 -> T4 t1 -> _ -> option (A t1 * B' * C))\n             (e' : forall t1 t3, T2 t1 -> T4 t1 -> _ -> option (A t1 * B' * C))\n             (f : B' -> B)\n             (t2 : T2 t1)\n             (t4 : T4 t1),\n      (b t1 t3 = b' t1 t3 t2 t4)\n      -> (forall e'',\n             t e'' = match t' t1 t3 t2 t4 e'' with\n                     | Some (a, b', c) => Some (a, f b', c)\n                     | None => None\n                     end)\n      -> (forall e'',\n             e e'' = match e' t1 t3 t2 t4 e'' with\n                     | Some (a, b', c) => Some (a, f b', c)\n                     | None => None\n                     end)\n      -> (match b t1 t3 with\n            left e'' => t e''\n          | right e'' => e e''\n          end) =\n         match (fun t1 t2 t3 t4 =>\n                  match b' t1 t3 t2 t4 with\n                  | left e'' => t' t1 t3 t2 t4 e''\n                  | right e'' => e' t1 t3 t2 t4 e''\n                  end) t1 t2 t3 t4 with\n         | Some (a, b', c) => Some (a, f b', c)\n         | None => None\n         end.\n  Proof.\n    intros; destruct b; eauto; rewrite <- H; simpl; eauto.\n  Qed.\n\n  Lemma build_aligned_ByteString_eq_split'\n    : forall n sz v,\n      (n <= sz)%nat\n      ->\n      build_aligned_ByteString v\n      = build_aligned_ByteString (Guarded_Vector_split n sz v).\n  Proof.\n    intros; eapply ByteString_f_equal; simpl.\n    instantiate (1 := eq_refl _); reflexivity.\n    instantiate (1 := (le_plus_minus_r _ _ H)).\n    generalize (le_plus_minus_r n sz H); clear.\n    revert sz v; induction n; simpl; intros.\n    unfold Guarded_Vector_split.\n    rewrite <- Equality.transport_pp.\n    generalize (eq_trans (minus_n_O sz) e); clear;\n      intro.\n    apply Eqdep_dec.eq_rect_eq_dec; auto with arith.\n    destruct v; simpl in *.\n    Lia.lia.\n    unfold Guarded_Vector_split; fold Guarded_Vector_split;\n      simpl.\n    unfold ByteBuffer.t; erewrite eq_rect_Vector_cons; eauto.\n    f_equal.\n    apply IHn.\n    Unshelve.\n    Lia.lia.\n  Qed.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> option C)\n             (a_opt' : ByteString -> option C) v,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = None)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If Coq.Init.Nat.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else None.\n  Proof.\n    intros; destruct (Coq.Init.Nat.leb n sz) eqn: ?.\n    - apply Nat.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- Nat.leb_le in H1; congruence.\n  Qed.\n\n  Lemma AlignedDecode4Char {C}\n        {numBytes}\n    : forall (v : Vector.t (word 8) (S (S (S (S numBytes)))))\n             (t : _ -> Hopefully C)\n             cd,\n      HBind (decode_word\n               (monoidUnit := ByteString_QueueMonoidOpt) (sz := 32) (build_aligned_ByteString v) cd) as w\n      With t w  ~=\n      Let n := Core.append_word (Vector.nth v (Fin.FS (Fin.FS (Fin.FS Fin.F1))))\n                                (Core.append_word (Vector.nth v (Fin.FS (Fin.FS Fin.F1)))\n                                                  (Core.append_word (Vector.nth v (Fin.FS Fin.F1)) (Vector.nth v Fin.F1))) in\n      t (n, build_aligned_ByteString (snd (Vector_split 4 _ v)), addD cd 32).\n  Proof.\n    unfold LetIn; intros.\n    unfold decode_word, WordOpt.decode_word.\n    match goal with\n      |- context[HBind ?Z as _ With _] => replace Z with\n        (let (v', v'') := Vector_split 4 numBytes v in Ok (VectorByteToWord v', build_aligned_ByteString v'')) by (symmetry; apply (@aligned_decode_char_eq' _ 3 v))\n    end.\n    Local Transparent Vector_split.\n    unfold Vector_split, If_Opt_Then_Else, If_Opt_Then_Else, hbind.\n    f_equal.\n    rewrite !Vector_nth_tl, !Vector_nth_hd.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    f_equal.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    Unshelve.\n    Lia.lia.\n    Lia.lia.\n    Lia.lia.\n    Lia.lia.\n  Qed.\n\n  Lemma split2_split2\n    : forall n m o (w : word (n + (m + o))),\n      split2' m o (split2' n (m + o) w) =\n      split2' (n + m) o (eq_rect _ _ w _ (plus_assoc _ _ _)).\n  Proof.\n    induction n; simpl; intros.\n    - rewrite <- Eqdep_dec.eq_rect_eq_dec; auto with arith.\n    - rewrite IHn.\n      f_equal.\n      pose proof (shatter_word_S w); destruct_ex; subst.\n      clear.\n      rewrite <- WS_eq_rect_eq with (H := plus_assoc n m o).\n      revert m o x0 x; induction n; simpl; intros.\n      + rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n      + erewrite <- WS_eq_rect_eq; fold plus; pose proof (shatter_word_S x0);\n          destruct_ex; subst; f_equal.\n        rewrite IHn; f_equal.\n        erewrite <- WS_eq_rect_eq; reflexivity.\n  Qed.\n\n  Lemma AlignedFormat32Char' {numBytes}\n    : forall (w : word 32) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 32)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_word (monoidUnit := ByteString_QueueMonoidOpt) w)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString\n                        (Vector.cons\n                           _ (split1' 8 24 w) _\n                           (Vector.cons\n                              _\n                              (split1' 8 16 (split2' 8 24 w)) _\n                              (Vector.cons\n                                 _\n                                 (split1' 8 8 (split2' 16 16 w)) _\n                                 (Vector.cons\n                                    _\n                                    (split2' 24 8 w) _ v)))), ce')).\n  Proof.\n    unfold compose, Bind2; intros.\n    intros; setoid_rewrite (@format_words' _ _ 8 24 addE_addE_plus w).\n    rewrite (@AlignedFormatChar _ _ 3).\n    simplify with monad laws.\n    unfold snd.\n    rewrite H.\n    simplify with monad laws.\n    unfold fst.\n    unfold mappend.\n    unfold ByteStringQueueMonoid.\n    rewrite <- build_aligned_ByteString_append.\n    instantiate (1 := Vector.cons _ _ _ (Vector.cons _ _ _ (Vector.cons _ _ _ (Vector.nil _)))).\n    unfold append.\n    reflexivity.\n    setoid_rewrite (@format_words' _ _ 8 16 addE_addE_plus _).\n    rewrite (@AlignedFormatChar _ _ 2).\n    reflexivity.\n    setoid_rewrite (@format_words' _ _ 8 8 addE_addE_plus ).\n    rewrite (@AlignedFormatChar _ _ 1) by apply aligned_format_char_eq.\n    rewrite !addE_addE_plus; simpl plus.\n    rewrite !split2_split2.\n    simpl plus.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; auto with arith.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedFormat32Char {numBytes}\n    : forall (w : word 32) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 32)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_word (monoidUnit := ByteString_QueueMonoidOpt) w)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString\n                        (Vector.cons\n                           _ (split2 24 8 w) _\n                           (Vector.cons\n                              _\n                              (split2 16 8 (split1 24 8 w)) _\n                              (Vector.cons\n                                 _\n                                 (split2 8 8 (split1 16 16 w)) _\n                                 (Vector.cons\n                                    _\n                                    (split1 8 24 w) _ v)))), ce')).\n  Proof.\n    unfold compose, Bind2; intros.\n    intros; setoid_rewrite (@format_words _ _ 8 24 addE_addE_plus w).\n    rewrite (@AlignedFormatChar _ _ 3).\n    simplify with monad laws.\n    unfold snd.\n    rewrite H.\n    simplify with monad laws.\n    unfold fst.\n    unfold mappend.\n    unfold ByteStringQueueMonoid.\n    rewrite <- build_aligned_ByteString_append.\n    instantiate (1 := Vector.cons _ _ _ (Vector.cons _ _ _ (Vector.cons _ _ _ (Vector.nil _)))).\n    unfold append.\n    reflexivity.\n    setoid_rewrite (@format_words _ _ 8 16 addE_addE_plus  _).\n    rewrite (@AlignedFormatChar _ _ 2).\n    reflexivity.\n    setoid_rewrite (@format_words _ _ 8 8).\n    rewrite (@AlignedFormatChar _ _ 1) by apply aligned_format_char_eq.\n    rewrite !addE_addE_plus; simpl plus.\n    f_equiv.\n    eauto.\n  Qed.\n\n  Fixpoint align_decode_list {A}\n           (A_decode_align : forall n,\n               ByteBuffer.t n\n               -> CacheDecode\n               -> Hopefully (A * {n : _ & Vector.t _ n}\n                          * CacheDecode))\n           (n : nat)\n           {sz}\n           (v : ByteBuffer.t sz)\n           (cd : CacheDecode)\n    : Hopefully (list A *  {n : _ & Vector.t _ n} * CacheDecode) :=\n    match n with\n    | 0 => Ok (@nil _, existT _ _ v, cd)\n    | S s' => `(x, b1, e1) <- A_decode_align sz v cd;\n                `(xs, b2, e2) <- align_decode_list A_decode_align s' (projT2 b1) e1;\n                Ok ((x :: xs)%list, b2, e2)\n    end.\n\n  Lemma optimize_align_decode_list\n        {A}\n        (A_decode :\n           ByteString\n           -> CacheDecode\n           -> Hopefully (A * ByteString * CacheDecode))\n        (A_decode_align : forall n,\n            ByteBuffer.t n\n            -> CacheDecode\n            -> Hopefully (A * {n : _ & Vector.t _ n}\n                       * CacheDecode))\n        (A_decode_OK :\n           forall n (v : Vector.t _ n) cd,\n             A_decode (build_aligned_ByteString v) cd =\n             HBind A_decode_align n v cd as a With\n                                              Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a))\n    : forall (n : nat)\n             {sz}\n             (v : ByteBuffer.t sz)\n             (cd : CacheDecode),\n      decode_list A_decode n (build_aligned_ByteString v) cd =\n      HBind align_decode_list A_decode_align n v cd as a With\n                                                         Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a)\n                                                         .\n  Proof.\n    induction n; simpl; intros; eauto.\n    rewrite A_decode_OK.\n    rewrite (HBind_DecodeBindOpt).\n    destruct (A_decode_align sz v cd) as [ [ [? [? ?] ] ?]  | ]; simpl; eauto.\n    rewrite IHn.\n    rewrite (HBind_DecodeBindOpt).\n    destruct (align_decode_list A_decode_align n t c)\n      as [ [ [? [? ?] ] ?]  | ]; simpl; eauto.\n  Qed.\n\n  Lemma LetIn_If_Opt_Then_Else {A B C}\n    : forall (a : A)\n             (k : A -> option B)\n             (t : B -> C)\n             (e : C),\n      (Ifopt LetIn a k as b Then t b Else e)\n      = LetIn a (fun a => Ifopt k a as b Then t b Else e).\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma decode_unused_word_aligned_ByteString_overflow\n    : forall {sz'}\n             (b : t (word 8) sz')\n             {sz}\n             (cd : CacheDecode),\n      lt sz' sz\n      -> is_error (decode_unused_word (sz := 8 * sz) (build_aligned_ByteString b) cd).\n  Proof.\n    induction b; intros.\n    - unfold build_aligned_ByteString; simpl.\n      inversion H; subst; reflexivity.\n    - destruct sz; try Lia.lia.\n      apply lt_S_n in H.\n      pose proof (IHb _ cd H).\n      unfold decode_unused_word, WordOpt.decode_word, FMapFormat.Compose_Decode in *.\n      rewrite <- mult_n_Sm, plus_comm.\n      rewrite decode_word_plus'.\n      rewrite aligned_decode_char_eq; simpl.\n      destruct (decode_word' (8 * sz) (build_aligned_ByteString b)) as [ [? ?] | ];\n        simpl in *; eauto.\n  Qed.\n\n  Lemma AlignedDecodeUnusedChar {C}\n        {numBytes}\n    : forall (v : ByteBuffer.t (S numBytes))\n             (t : (() * ByteString * CacheDecode) -> Hopefully C)\n             cd,\n      HBind (decode_unused_word\n               (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8) (build_aligned_ByteString v) cd)\n      as w With t w\n         =\n         (t ((), build_aligned_ByteString (snd (Vector_split 1 _ v)), addD cd 8)).\n  Proof.\n    unfold LetIn; intros.\n    unfold decode_unused_word, WordOpt.decode_word, FMapFormat.Compose_Decode in *.\n    pattern numBytes, v; apply Vector.caseS; simpl; intros.\n    rewrite aligned_decode_char_eq.\n    simpl; reflexivity.\n  Qed.\n\n  Variable addD_addD_plus :\n    forall cd n m, addD (addD cd n) m = addD cd (n + m).\n\n  Lemma AlignedDecodeUnusedChars {C}\n        {numBytes numBytes'}\n    : forall (v : ByteBuffer.t (numBytes' + numBytes))\n             (k : _ -> Hopefully C)\n             cd,\n      BindOpt (decode_unused_word\n                 (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8 * numBytes') (build_aligned_ByteString v) cd) k =\n      k ((), build_aligned_ByteString (snd (Vector_split numBytes' _ v)), addD cd (8 * numBytes')).\n  Proof.\n    induction numBytes'.\n    - Local Transparent Vector_split.\n      simpl; intros; unfold Vector_split; simpl.\n      reflexivity.\n    - simpl.\n      replace (8 * S numBytes') with (8 + 8 * numBytes') by Lia.lia.\n      unfold decode_unused_word, WordOpt.decode_word, FMapFormat.Compose_Decode in *.\n      unfold decode_unused_word; intros.\n      rewrite decode_word_plus'.\n      rewrite (@aligned_decode_char_eq ).\n      simpl BindOpt.\n      pose proof (IHnumBytes' (Vector.tl v) k (addD cd 8)).\n      unfold Core.char.\n      destruct (decode_word' (8 * numBytes') _) as [ [? ?] | ] eqn: ?; simpl in *;\n        try discriminate.\n      rewrite addD_addD_plus in H; simpl in H; rewrite H.\n      fold plus.\n      destruct ((Vector_split numBytes' numBytes _)) eqn: ?; simpl.\n      reflexivity.\n      rewrite addD_addD_plus in H; simpl in H; rewrite H.\n      fold plus; destruct ((Vector_split numBytes' numBytes _)); simpl.\n      reflexivity.\n  Qed.\n\n  Lemma aligned_format_unused_char_eq {S}\n    : forall (s : S) cd,\n      refine (format_unused_word (monoidUnit := ByteString_QueueMonoidOpt) 8 s cd)\n             (ret (build_aligned_ByteString (Vector.cons _ (wzero 8) _ (Vector.nil _)), addE cd 8)).\n  Proof.\n    unfold format_unused_word, FMapFormat.Compose_Format; simpl; intros.\n    intros ? ?.\n    computes_to_inv; subst.\n    apply unfold_computes; eexists; split; auto.\n    apply aligned_format_char_eq; computes_to_econstructor.\n    apply unfold_computes. eauto.\n  Qed.\n\n  Lemma AlignedFormatUnusedChar {S} {numBytes}\n    : forall (s : S) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 8)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_unused_word (monoidUnit := ByteString_QueueMonoidOpt) 8 s)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons _ (wzero 8) _ v), ce')).\n  Proof.\n    unfold compose, Bind2; simpl; intros.\n    rewrite aligned_format_unused_char_eq.\n    simplify with monad laws.\n    simpl snd; rewrite H; simplify with monad laws.\n    simpl.\n    rewrite <- build_aligned_ByteString_append.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedFormat2UnusedChar {S} {numBytes}\n    : forall (s : S) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 16)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_unused_word (monoidUnit := ByteString_QueueMonoidOpt) 16 s)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons _ (wzero 8) _ (Vector.cons _ (wzero 8) _ v)), ce')).\n  Proof.\n    unfold compose, Bind2; intros.\n    rewrite <- (AlignedFormat2Char (wzero 16)); eauto.\n    intros ? ?.\n    unfold compose, Bind2 in H0; computes_to_inv; subst.\n    unfold format_unused_word, FMapFormat.Compose_Format; computes_to_econstructor.\n    apply unfold_computes; eexists; split; eauto.\n    apply unfold_computes; eauto.\n    computes_to_econstructor; eauto.\n  Qed.\n\n  Definition align_decode_sumtype\n             {m : nat}\n             {types : t Type m}\n             (decoders :\n                ilist (B := fun T =>\n                              forall n,\n                                ByteBuffer.t n\n                                -> CacheDecode\n                                -> Hopefully (T * {n : _ & ByteBuffer.t n} * CacheDecode)) types)\n             (idx : Fin.t m)\n             {n : nat}\n             (v : ByteBuffer.t n)\n             (cd : CacheDecode)\n    := `(a, b', cd') <- ith (decoders) idx n v cd;\n         Ok (inj_SumType types idx a, b', cd').\n\n  Lemma align_decode_sumtype_OK'\n        {m : nat}\n        {types : t Type m}\n        (align_decoders :\n           ilist (B := fun T =>\n                         forall n,\n                           ByteBuffer.t n\n                           -> CacheDecode\n                           -> Hopefully (T * {n : _ & ByteBuffer.t n} * CacheDecode)) types)\n\n        (decoders : ilist (B := fun T => ByteString -> CacheDecode -> Hopefully (T * ByteString * CacheDecode)) types)\n        (decoders_OK : forall n v cd idx',\n            ith decoders idx' (build_aligned_ByteString v) cd\n            = HBind ith align_decoders idx' n v cd as a With\n                                                        Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a)\n                                                        )\n    : forall\n      (idx : Fin.t m)\n      {n : nat}\n      (v : ByteBuffer.t n)\n      (cd : CacheDecode),\n      decode_SumType types decoders idx (build_aligned_ByteString v) cd\n      =\n      HBind align_decode_sumtype align_decoders idx\n            v cd as a With\n                      Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a)\n                      .\n  Proof.\n    intros.\n    unfold decode_SumType, align_decode_sumtype.\n    rewrite decoders_OK.\n    destruct (ith align_decoders idx n v cd) as [ [ [? ?] ?] | ];\n      reflexivity.\n  Qed.\n\n  Corollary align_decode_sumtype_OK\n            {m : nat}\n            {types : t Type m}\n            (align_decoders :\n               ilist (B := fun T =>\n                             forall n,\n                               ByteBuffer.t n\n                               -> CacheDecode\n                               -> Hopefully (T * {n : _ & ByteBuffer.t n} * CacheDecode)) types)\n\n            (decoders : ilist (B := fun T => ByteString -> CacheDecode -> Hopefully (T * ByteString * CacheDecode)) types)\n            (decoders_OK : forall n v cd,\n                Iterate_Ensemble_BoundedIndex\n                  (fun idx' => ith decoders idx' (build_aligned_ByteString v) cd\n                               = HBind ith align_decoders idx' n v cd as a With\n                                                                           Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a)\n                                                                           ))\n    : forall\n      (idx : Fin.t m)\n      {n : nat}\n      (v : ByteBuffer.t n)\n      (cd : CacheDecode),\n      decode_SumType types decoders idx (build_aligned_ByteString v) cd\n      =\n      HBind align_decode_sumtype align_decoders idx\n            v cd as a With Ok (fst (fst a), build_aligned_ByteString (projT2 (snd (fst a))), snd a)\n                      .\n  Proof.\n    intros; eapply align_decode_sumtype_OK'; intros.\n    pose proof (decoders_OK n0 v0 cd0).\n    eapply Iterate_Ensemble_BoundedIndex_equiv in H.\n    apply H.\n  Qed.\n\n  Lemma nth_Vector_split {A}\n    : forall {sz} n v idx,\n      Vector.nth (snd (Vector_split (A := A) n sz v)) idx\n      = Vector.nth v (Fin.R n idx).\n  Proof.\n    induction n; simpl; intros; eauto.\n    assert (forall A n b, exists a b', b = Vector.cons A a n b')\n      by (clear; intros; pattern n, b; apply caseS; eauto).\n    pose proof (H _ _ v); destruct_ex; subst.\n    simpl.\n    destruct (Vector_split n sz x0) as [? ?] eqn: ?.\n    rewrite <- IHn.\n    rewrite Heqp; reflexivity.\n  Qed.\n\n  Lemma eq_rect_Vector_tl {A}\n    : forall n (v : Vector.t A (S n)) m H H',\n      Vector.tl (eq_rect (S n) (t A) v (S m) H)\n      = eq_rect _ (Vector.t A) (Vector.tl v) _ H'.\n  Proof.\n    intros n v; pattern n, v; apply Vector.caseS; simpl; intros.\n    erewrite eq_rect_Vector_cons; simpl; eauto.\n  Qed.\n\n  Lemma Vector_split_merge {A}\n    : forall sz m n (v : Vector.t A _),\n      snd (Vector_split m _ (snd (Vector_split n (m + sz) v))) =\n      snd (Vector_split (n + m) _ (eq_rect _ _ v _ (plus_assoc _ _ _))).\n  Proof.\n    induction m; intros; simpl.\n    - induction n; simpl.\n      + simpl in *.\n        apply Eqdep_dec.eq_rect_eq_dec; auto with arith.\n      + simpl in v.\n        assert (forall A n b, exists a b', b = Vector.cons A a n b')\n          by (clear; intros; pattern n, b; apply caseS; eauto).\n        pose proof (H _ _ v); destruct_ex; subst.\n        simpl.\n        pose proof (IHn x0).\n        destruct (Vector_split n sz x0) eqn: ?.\n        simpl in *.\n        rewrite H0.\n        erewrite eq_rect_Vector_cons with (H' := (plus_assoc n 0 sz)); eauto; simpl.\n        destruct (Vector_split (n + 0) sz (eq_rect (n + sz) (Vector.t A) x0 (n + 0 + sz) (plus_assoc n 0 sz))); reflexivity.\n    - assert (n + (S m + sz) = S n + (m + sz)) by Lia.lia.\n      fold plus in *; unfold Core.char in *.\n      replace (Vector.tl (snd (Vector_split n (S (m + sz)) v)))\n        with ((snd (Vector_split n (m + sz) (Vector.tl  (eq_rect _ _ v _ H))))).\n      + pose proof (IHm n ((Vector.tl (eq_rect (n + (S m + sz)) (t A) v (S n + (m + sz)) H)))).\n        destruct (Vector_split m sz (snd (Vector_split n (m + sz) (Vector.tl (eq_rect (n + (S m + sz)) (t A) v (S n + (m + sz)) H))))) eqn: ?; simpl in *.\n        fold plus in *; rewrite Heqp.\n        simpl; rewrite H0.\n        clear.\n        assert ( S (n + (m + sz)) = S (n + m + sz)) by Lia.lia.\n        rewrite <- eq_rect_Vector_tl with (H1 := H0).\n        rewrite <- Equality.transport_pp; simpl; clear.\n        generalize (eq_trans H H0);\n          generalize (NPeano.Nat.add_assoc n (S m) sz); clear H H0.\n        revert sz m v; induction n; simpl.\n        * intros.\n          rewrite <- !Eqdep_dec.eq_rect_eq_dec; auto with arith.\n          destruct (Vector_split m sz (Vector.tl v)) eqn: ?.\n          simpl in *; fold plus in *; rewrite Heqp; reflexivity.\n        * intros.\n          assert (n + S (m + sz) = S (n + m + sz)) by Lia.lia.\n          assert (n + S (m + sz) = n + S m + sz) by Lia.lia.\n          (* Again, 8.4 compatibility problems. *)\n          erewrite eq_rect_Vector_tl with (H' := H0).\n          erewrite eq_rect_Vector_tl with (H' := H).\n          pose proof (IHn _ _ (Vector.tl v) H0 H).\n          destruct ((Vector_split (n + m) sz (Vector.tl (eq_rect (n + S (m + sz)) (t A) (Vector.tl v) (S (n + m + sz)) H)))) eqn: ?.\n          simpl in *; fold plus in *; rewrite Heqp, H1; simpl.\n          destruct (Vector_split (n + S m) sz (eq_rect (n + S (m + sz)) (Vector.t A) (Vector.tl v) (n + S m + sz) H0)) eqn: ?.\n          replace (plus_assoc n (S m) sz) with H0; simpl; eauto.\n          eapply Eqdep_dec.eq_proofs_unicity; intros; Lia.lia.\n      + clear.\n        revert H v.\n        assert (forall q (v : t A (n + (S q))) H,\n                   snd (Vector_split n q (Vector.tl (eq_rect (n + (S q)) (t A) v (S n + (q)) H))) =\n                   Vector.tl (snd (Vector_split n (S (q)) v))).\n        { induction n; simpl; intros.\n          rewrite <- Eqdep_dec.eq_rect_eq_dec; auto with arith.\n          assert (n + S q = S (n + q)) by Lia.lia.\n          rewrite eq_rect_Vector_tl with (H' := H0).\n          pose proof (IHn q (Vector.tl v) H0).\n          destruct ((Vector_split n q (Vector.tl (eq_rect (n + S q) (t A) (Vector.tl v) (S n + q) H0))))\n                   eqn: ?.\n          fold plus in *; simpl in *; rewrite Heqp; simpl.\n          rewrite H1.\n          destruct (Vector_split n (S q) (Vector.tl v)); reflexivity.\n        }\n        intros; rewrite H; reflexivity.\n  Qed.\n\n  Lemma zeta_to_fst {A B C}\n    : forall (ab : A * B) (k : A -> B -> C),\n      (let (a, b) := ab in (k a b)) =\n      k (fst ab) (snd ab).\n  Proof.\n    destruct ab; reflexivity.\n  Qed.\n\n  Lemma zeta_inside_ret {A B C}\n    : forall (ab : A * B) (k : A -> B -> C),\n      refine (let (a, b) := ab in ret (k a b))\n             (ret (let (a, b) := ab in k a b)).\n  Proof.\n    destruct ab; reflexivity.\n  Qed.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n                                                  Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Corollary AlignedDecodeNat {C}\n            {numBytes}\n    : forall (v : ByteBuffer.t (S numBytes))\n             (t : _ -> Hopefully C)\n             cd,\n      HBind (decode_nat (monoidUnit := ByteString_QueueMonoidOpt) 8 (build_aligned_ByteString v) cd) as w\n                                                                                                          With t w\n                                                                                                        =\n                                                                                                        Let n := wordToNat (Vector.nth v Fin.F1) in\n        t (n, build_aligned_ByteString (snd (Vector_split 1 _ v)), addD cd 8).\n  Proof.\n    unfold CacheDecode.\n    unfold decode_nat, DecodeBindOpt2; intros.\n    unfold BindOpt at 1.\n    rewrite AlignedDecodeChar.\n    reflexivity.\n  Qed.\n\n  Lemma optimize_Guarded_Decode' {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If Coq.Init.Nat.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (Coq.Init.Nat.leb n sz) eqn: ?.\n    - apply Nat.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- Nat.leb_le in H1; congruence.\n  Qed.\n\n  Lemma AlignedDecode_shift_if_bool {A B C : Type}\n        (decode_A : DecodeM (A * _) ByteString)\n        (decode_B : A -> DecodeM (B * _) ByteString)\n        (decode_C : A -> B -> DecodeM (C * _) ByteString)\n        (cond : A -> bool)\n        (aligned_decoder : forall numBytes : nat, AlignedDecodeM C numBytes)\n        e\n    : DecodeMEquivAlignedDecodeM\n        (fun bs cd => `(a, bs', cd') <- decode_A bs cd;\n                        `(b, bs', cd') <- decode_B a bs' cd';\n                        if cond a\n                        then decode_C a b bs' cd'\n                        else Error e)\n        aligned_decoder\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => `(a, bs', cd') <- decode_A bs cd;\n                           if cond a\n                           then `(b, bs', cd') <- decode_B a bs' cd'; decode_C a b bs' cd'\n                           else Error e)\n           aligned_decoder.\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans; eauto;\n      intros; simpl; try reflexivity.\n    simpl; destruct (decode_A b cd) as [ [ [? ?] ?] | ]; simpl; try reflexivity.\n    find_if_inside; try reflexivity.\n    destruct (decode_B a b0 c) as [ [ [? ?] ?] | ]; simpl; apply Error_eq.\n  Qed.\n\n  Lemma AlignedDecode_shift_if_Sumb {A B C : Type}\n        (decode_A : DecodeM (A * _) ByteString)\n        (decode_B : A -> DecodeM (B * _) ByteString)\n        (decode_C : A -> B -> DecodeM (C * _) ByteString)\n        (P : A -> Prop)\n        (cond : forall a, {P a} + {~P a})\n        (aligned_decoder : forall numBytes : nat, AlignedDecodeM C numBytes)\n        e\n    : DecodeMEquivAlignedDecodeM\n        (fun bs cd => `(a, bs', cd') <- decode_A bs cd;\n                        `(b, bs', cd') <- decode_B a bs' cd';\n                        if cond a\n                        then decode_C a b bs' cd'\n                        else Error e)\n        aligned_decoder\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => `(a, bs', cd') <- decode_A bs cd;\n                           if cond a\n                           then `(b, bs', cd') <- decode_B a bs' cd'; decode_C a b bs' cd'\n                           else Error e)\n           aligned_decoder.\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans; eauto;\n      intros; simpl; try reflexivity.\n   simpl; destruct (decode_A b cd) as [ [ [? ?] ?] | ]; simpl; try reflexivity.\n    find_if_inside; try reflexivity.\n    destruct (decode_B a b0 c) as [ [ [? ?] ?] | ]; simpl; try reflexivity.\n    apply Error_eq.\n  Qed.\n\n  Lemma AlignedDecode_if_Sumb_dep {A : Type}\n        {P : ByteString -> Prop}\n        (decode_T decode_E : DecodeM (A * ByteString) ByteString)\n        (cond : forall bs, {P bs} + {~ P bs})\n        (cond' : forall sz, ByteBuffer.t sz -> nat -> bool)\n        (aligned_decoder_T aligned_decoder_E : forall numBytes : nat, AlignedDecodeM A numBytes)\n        (cond'OK : forall sz (v : Vector.t _ sz),\n            (if cond (build_aligned_ByteString v) then true else false) = cond' _ v 0)\n        (cond'OK2 : forall sz v idx, cond' (S sz) v (S idx) = cond' _ (Vector.tl v) idx )\n    : DecodeMEquivAlignedDecodeM decode_T aligned_decoder_T\n      -> DecodeMEquivAlignedDecodeM decode_E aligned_decoder_E\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => if cond bs\n                         then decode_T bs cd\n                         else decode_E bs cd)\n           (fun sz v idx => if cond' sz v idx\n                            then aligned_decoder_T sz v idx\n                            else aligned_decoder_E sz v idx).\n  Proof.\n    split.\n    intros.\n    rewrite cond'OK2.\n    destruct (cond' numBytes_hd (Vector.tl v)) eqn: ? ;\n      try eapply H; try eapply H0; try reflexivity.\n    split; intros.\n    destruct (cond b).\n    eapply H; eauto.\n    eapply H0; eauto.\n    specialize (cond'OK _ v).\n    simpl; destruct (cond' n v); simpl; split; intros.\n    find_if_inside; try discriminate.\n    eapply H; eauto.\n    eapply H; eauto.\n    find_if_inside; eauto.\n    discriminate.\n    find_if_inside; try discriminate.\n    eapply H0; eauto.\n    eapply H0; eauto.\n    find_if_inside; eauto.\n    discriminate.\n  Qed.\n\n  Lemma AlignedDecode_CollapseWord\n    : forall (ResultT : Type) (sz sz' : nat)\n             aligned_decoder\n             (k : word sz -> word sz' -> _ -> CacheDecode -> Hopefully (ResultT * _ * CacheDecode)),\n      DecodeMEquivAlignedDecodeM\n        (fun bs cd => `(w, b', cd') <- decode_word bs cd;\n                        k (split1' sz sz' w) (split2' sz sz' w) b' cd')\n        aligned_decoder\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => `(w, b', cd') <- decode_word bs cd;\n                           `(w', b'0, cd'0) <- decode_word b' cd';\n                           k w w' b'0 cd'0)\n           aligned_decoder.\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans; eauto;\n      intros; simpl; try reflexivity.\n    rewrite CollapseWord; eauto. \n  Qed.\n\n  Lemma AlignedDecode_CollapseEnumWord\n    : forall (ResultT : Type) (sz sz' n : nat)\n             (tb : Vector.t _ (S n))\n             aligned_decoder\n             (k : _ -> word sz' -> _ -> CacheDecode -> Hopefully (ResultT * _ * CacheDecode)),\n      DecodeMEquivAlignedDecodeM\n        (fun bs cd => `(w, b', cd') <- decode_word bs cd;\n                        HBind (word_indexed (split2 sz' sz w) tb) as idx With\n                                                          k idx\n                                                          (split1 sz' sz w) b' cd')\n        aligned_decoder\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => `(w, b', cd') <- decode_enum tb bs cd;\n                           `(w', b'0, cd'0) <- decode_word b' cd';\n                           k w w' b'0 cd'0)\n           aligned_decoder.\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans; eauto;\n      intros; simpl; try reflexivity.\n    symmetry.\n    eapply CollapseEnumWord. eauto.\n  Qed.\n\n\n  Lemma AlignedDecodeBind3CharM:\n      (forall (cd : CacheDecode) (n m : nat), addD (addD cd n) m = addD cd (n + m)) ->\n      forall (C : Type) (t : word 24 -> DecodeM (C * _) ByteString)\n             (t' : word 24 -> forall numBytes : nat, AlignedDecodeM C numBytes),\n        (forall b : word 24, DecodeMEquivAlignedDecodeM (t b) (t' b)) ->\n        DecodeMEquivAlignedDecodeM\n          (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                       decode_word v cd;\n                                                        t a b0 cd')\n          (fun numBytes : nat =>\n             (b1 <- GetCurrentByte;\n                b2 <- GetCurrentByte;\n                b3 <- GetCurrentByte;\n                w <- return (Core.append_word b3 (Core.append_word b2 b1));\n                              t' w numBytes)%AlignedDecodeM).\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans.\n    - eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply H0.\n    - simpl; intros.\n      unfold decode_word; rewrite (decode_word_plus' 8 16).\n      unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n      destruct (decode_word' 8 b) as [ [? ?] | ]; try reflexivity.\n      unfold decode_word; rewrite (decode_word_plus' 8 8).\n      unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n      destruct (decode_word' 8 b0) as [ [? ?] | ]; try reflexivity.\n      destruct (decode_word' 8 b1) as [ [? ?] | ]; eauto.\n      rewrite !addD_addD_plus; simpl plus.\n      higher_order_reflexivity.\n      - intros; reflexivity.\n  Qed.\n\n  Lemma AlignedDecodeBind4CharM:\n      (forall (cd : CacheDecode) (n m : nat), addD (addD cd n) m = addD cd (n + m)) ->\n      forall (C : Type) (t : word 32 -> DecodeM (C * _) ByteString)\n             (t' : word 32 -> forall numBytes : nat, AlignedDecodeM C numBytes),\n        (forall b : word 32, DecodeMEquivAlignedDecodeM (t b) (t' b)) ->\n        DecodeMEquivAlignedDecodeM\n          (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                       decode_word v cd;\n                                                        t a b0 cd')\n          (fun numBytes : nat =>\n             (b1 <- GetCurrentByte;\n                b2 <- GetCurrentByte;\n                b3 <- GetCurrentByte;\n                b4 <- GetCurrentByte;\n                w <- return (Core.append_word b4 (Core.append_word b3 (Core.append_word b2 b1)));\n                              t' w numBytes)%AlignedDecodeM).\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans.\n    - eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply H0.\n      - simpl; intros.\n        unfold decode_word; rewrite (decode_word_plus' 8 24).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 16).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b0) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 8).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b1) as [ [? ?] | ]; eauto.\n        destruct (decode_word' 8 b2) as [ [? ?] | ]; eauto.\n        rewrite !addD_addD_plus; simpl plus.\n        higher_order_reflexivity.\n        all: reflexivity.\n      - intros; reflexivity.\n  Qed.\n\n  Lemma AlignedDecodeBind8CharM:\n      (forall (cd : CacheDecode) (n m : nat), addD (addD cd n) m = addD cd (n + m)) ->\n      forall (C : Type) (t : word 64 -> DecodeM (C * _) ByteString)\n             (t' : word 64 -> forall numBytes : nat, AlignedDecodeM C numBytes),\n        (forall b : word 64, DecodeMEquivAlignedDecodeM (t b) (t' b)) ->\n        DecodeMEquivAlignedDecodeM\n          (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                       decode_word v cd;\n                                                        t a b0 cd')\n          (fun numBytes : nat =>\n             (b1 <- GetCurrentByte;\n             b2 <- GetCurrentByte;\n             b3 <- GetCurrentByte;\n             b4 <- GetCurrentByte;\n             b5 <- GetCurrentByte;\n             b6 <- GetCurrentByte;\n             b7 <- GetCurrentByte;\n             b8 <- GetCurrentByte;\n                w <- return (Core.append_word b8 (Core.append_word b7 (Core.append_word b6 (Core.append_word b5 (Core.append_word b4 (Core.append_word b3 (Core.append_word b2 b1)))))));\n                              t' w numBytes)%AlignedDecodeM).\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans.\n    - eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply AlignedDecodeBindCharM; intros.\n      eapply H0.\n    - constructor; left.\n      simpl; intros.\n        unfold decode_word; rewrite (decode_word_plus' 8 56).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 48).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b0) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 40).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b1) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 32).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b2) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 24).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b3) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 16).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b4) as [ [? ?] | ]; eauto.\n        rewrite (decode_word_plus' 8 8).\n        unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n        destruct (decode_word' 8 b5) as [ [? ?] | ]; eauto.\n        destruct (decode_word' 8 b6) as [ [? ?] | ]; eauto.\n        rewrite !addD_addD_plus; simpl plus.\n        higher_order_reflexivity.\n      - intros; reflexivity.\n  Qed.\n\n  Lemma AlignedDecode_ifb_dep {A : Type}\n        (decode_T decode_E : DecodeM (A * ByteString) ByteString)\n        (cond : ByteString -> bool)\n        (cond' : forall sz, ByteBuffer.t sz -> nat -> bool)\n        (aligned_decoder_T aligned_decoder_E : forall numBytes : nat, AlignedDecodeM A numBytes)\n        (cond'OK : forall sz (v : Vector.t _ sz), cond (build_aligned_ByteString v) = cond' _ v 0)\n        (cond'OK2 : forall sz v idx, cond' (S sz) v (S idx) = cond' _ (Vector.tl v) idx )\n    : DecodeMEquivAlignedDecodeM decode_T aligned_decoder_T\n      -> DecodeMEquivAlignedDecodeM decode_E aligned_decoder_E\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => if cond bs\n                         then decode_T bs cd\n                         else decode_E bs cd)\n           (fun sz v idx => if cond' sz v idx\n                            then aligned_decoder_T sz v idx\n                            else aligned_decoder_E sz v idx).\n  Proof.\n    split.\n    intros.\n    rewrite cond'OK2.\n    destruct (cond' numBytes_hd (Vector.tl v)) eqn: ? ;\n      try eapply H; try eapply H0; try reflexivity.\n    split; intros.\n    destruct (cond b).\n    eapply H; eauto.\n    eapply H0; eauto.\n    rewrite cond'OK.\n    simpl; destruct (cond' n v); simpl; split; intros.\n    eapply H; eauto.\n    eapply H; eauto.\n    eapply H0; eauto.\n    eapply H0; eauto.\n  Qed.\n\n\n  Lemma AlignedDecode_CollapseWord' {A B}\n    : forall (ResultT : Type) (sz sz' : nat)\n             aligned_decoder\n             (decode_A : DecodeM (A * _) ByteString)\n             (decode_B : DecodeM (B * _) ByteString)\n             (f : word sz -> A)\n             (f' : word sz' -> B)\n             (k : A -> B -> _ -> CacheDecode -> Hopefully (ResultT * _ * CacheDecode)),\n      DecodeMEquivAlignedDecodeM\n        (fun bs cd => `(w, b', cd') <- decode_word bs cd;\n                        k (f (split1' sz sz' w)) (f' (split2' sz sz' w)) b' cd')\n        aligned_decoder\n      -> (forall bs cd, HBind (decode_word (sz := sz) bs cd) as a With Ok (f (fst (fst a)), (snd (fst a)), snd a)  = decode_A bs cd)\n      -> (forall bs cd, HBind (decode_word (sz := sz') bs cd) as a With Ok (f' (fst (fst a)), (snd (fst a)), snd a)  = decode_B bs cd)\n      -> DecodeMEquivAlignedDecodeM\n           (fun bs cd => `(a, b', cd') <- decode_A bs cd;\n                           `(b, b'0, cd'0) <- decode_B b' cd';\n                           k a b b'0 cd'0)\n           aligned_decoder.\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans; eauto;\n      intros; simpl; try reflexivity.\n    setoid_rewrite <- H0.\n    rewrite <- (fun H => CollapseWord H sz sz' b cd (fun w w' => k (f w) (f' w'))) by eauto.\n    destruct (decode_word b cd) as [ [ [? ?] ?] | ]; simpl; try reflexivity.\n    rewrite <- H1.\n    destruct (decode_word b0 c) as [ [ [? ?] ?] | ]; simpl; try reflexivity.\n  Qed.\n\n  Definition forget_word {n} := fun (w : word n) => tt.\n  Lemma decode_word_eq_decode_unused_word {n}\n    : forall (bs : ByteString) (cd : CacheDecode),\n      (HBind decode_word (sz := n) bs cd as a With Ok (forget_word (fst (fst a)), snd (fst a), snd a)) = decode_unused_word (sz := n) bs cd.\n  Proof.\n    intros; pose proof monoid_dequeue_word_eq_decode_word'; simpl in H.\n    unfold decode_unused_word, decode_unused_word', FMapFormat.Compose_Decode.\n    destruct (decode_word bs cd) as [ [? ?] | ]; simpl; reflexivity.\n  Qed.\n\n  Lemma decode_word_eq_decode_bool\n    : forall (bs : ByteString) (cd : CacheDecode),\n      (HBind decode_word bs cd as a With Ok (@whd 0 (fst (fst a)), snd (fst a), snd a)) = Bool.decode_bool bs cd.\n  Proof.\n    intros; pose proof monoid_dequeue_word_eq_decode_word'; simpl in H.\n    unfold decode_word; rewrite <- H.\n    unfold decode_word, Bool.decode_bool; simpl.\n    destruct (ByteString_dequeue bs) as [ [? ?] | ]; reflexivity.\n  Qed.\n\n  Lemma decode_word_eq_decode_word {n}\n    : forall (bs : ByteString) (cd : CacheDecode),\n      (HBind decode_word (sz := n) bs cd as a With Ok (id (fst (fst a)), snd (fst a), snd a)) = decode_word bs cd.\n  Proof.\n    intros; destruct (decode_word bs cd) as [ [ [? ?] ?] | ]; try reflexivity.\n  Qed.\n\n  Lemma decode_word_eq_decode_nat {n}\n    : forall (bs : ByteString) (cd : CacheDecode),\n      (HBind decode_word (sz := n) bs cd as a With Ok (wordToNat (fst (fst a)), snd (fst a), snd a)) = decode_nat n bs cd.\n  Proof.\n    intros; pose proof monoid_dequeue_word_eq_decode_word'; simpl in H.\n    unfold decode_nat, decode_unused_word', FMapFormat.Compose_Decode.\n    destruct (decode_word bs cd) as [ [ [? ?] ?] | ]; simpl; reflexivity.\n  Qed.\n\n  Definition Aligned_decode_enum\n             {len : nat}\n             {cache : Cache}\n             {cacheAddNat : CacheAdd cache nat}\n             (tb : t (word 8) (S len)) :=\n    (fun n => (w <- GetCurrentByte ;\n               Ifopt (hope2option (word_indexed w tb))\n                 as idx Then ReturnAlignedDecodeM idx Else ThrowAlignedDecodeM (n := n))%AlignedDecodeM).\n\n  Lemma AlignedDecodeBindEnum {A}\n        {len}\n    : forall (t : Fin.t (S len) -> DecodeM (A * _) ByteString)\n             (t' : Fin.t (S len) -> forall numBytes : nat, AlignedDecodeM A numBytes)\n             (tb : ByteBuffer.t (S len)),\n      (forall b2 : Fin.t (S len), DecodeMEquivAlignedDecodeM (t b2) (t' b2)) ->\n      DecodeMEquivAlignedDecodeM\n        (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                     decode_enum tb v cd;\n                                                      t a b0 cd')\n        (fun numBytes : nat => (b <- Aligned_decode_enum tb numBytes;\n                                  t' b numBytes)%AlignedDecodeM).\n  Proof.\n    unfold decode_enum, Aligned_decode_enum.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans.\n    eapply AlignedDecodeBindCharM; intros.\n    2: {\n      simpl; intros.\n      constructor; left.\n      unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else, hbind.\n      destruct (decode_word b cd) as [ [ [? ?] ] | ]; eauto.\n      higher_order_reflexivity.\n    }\n    2: {\n      unfold AlignedDecodeMEquiv; simpl; intros.\n      unfold BindAlignedDecodeM.\n      destruct (GetCurrentByte v idx c) as [ [ [? ?] ] | ]; simpl; eauto.\n      higher_order_reflexivity.\n    }\n    simpl.\n    destruct (word_indexed b tb); simpl; eauto.\n    eapply AlignedDecode_Throw.\n  Qed.\n\n  Definition Aligned_decode_enumN\n             sz\n             {len : nat}\n             {cache : Cache}\n             {cacheAddNat : CacheAdd cache nat}\n             (tb : t (word (sz * 8)) (S len)) :=\n    (fun n => (w <- GetCurrentBytes sz ;\n                 Ifopt (hope2option (word_indexed w tb)) as idx Then ReturnAlignedDecodeM idx Else ThrowAlignedDecodeM (n := n))%AlignedDecodeM).\n\n  Lemma AlignedDecodeBindEnumM sz {A}\n        {len}\n    : forall (t : Fin.t (S len) -> DecodeM (A * _) ByteString)\n             (t' : Fin.t (S len) -> forall numBytes : nat, AlignedDecodeM A numBytes)\n             (tb : Vector.t (word (sz * 8))%nat (S len)),\n      (forall b2 : Fin.t (S len), DecodeMEquivAlignedDecodeM (t b2) (t' b2)) ->\n      DecodeMEquivAlignedDecodeM\n        (fun (v : ByteString) (cd : CacheDecode) => `(a, b0, cd') <-\n                                                     decode_enum tb v cd;\n                                                      t a b0 cd')\n        (fun numBytes : nat => (b <- Aligned_decode_enumN sz tb numBytes;\n                                  t' b numBytes)%AlignedDecodeM).\n  Proof.\n    unfold decode_enum, Aligned_decode_enum.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans.\n    eapply Bind_DecodeMEquivAlignedDecodeM;\n      [ eapply AlignedDecodeNCharM with (m := sz); intros; eauto | ].\n    2: {\n      simpl; intros.\n      constructor; left.\n         unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else.\n         destruct (decode_word b cd) as [ [ [? ?] ] | ]; eauto.\n         higher_order_reflexivity.\n    }\n    2: {\n      unfold AlignedDecodeMEquiv; simpl; intros.\n         unfold Aligned_decode_enumN; simpl.\n         unfold BindAlignedDecodeM.\n         destruct (GetCurrentBytes sz v idx c) as [ [ [? ?] ] | ]; simpl; eauto.\n         higher_order_reflexivity.\n    }\n    simpl.\n    intros; destruct (word_indexed a tb); simpl; eauto.\n    eapply AlignedDecode_Throw.\n  Qed.\n\n  Lemma AlignedDecodeBindUnused2CharM {C : Type}\n        (t : unit -> DecodeM (C * _) ByteString)\n        (t' : unit -> forall {numBytes}, AlignedDecodeM C numBytes)\n    : (DecodeMEquivAlignedDecodeM (t ()) (@t' ()))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_unused_word (monoidUnit := ByteString_QueueMonoidOpt) (sz := 16) v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- SkipCurrentByte; b <- SkipCurrentByte; @t' b numBytes)%AlignedDecodeM.\n  Proof.\n    intro.\n    eapply DecodeMEquivAlignedDecodeM_trans.\n    eapply Bind_DecodeMEquivAlignedDecodeM.\n    eapply AlignedDecodeNUnusedCharM with (m := 2); eauto.\n    intros [ ]; eassumption.\n    reflexivity.\n    intros; simpl.\n    unfold AlignedDecodeMEquiv, BindAlignedDecodeM; simpl; intros.\n    destruct (SkipCurrentByte v idx c) as [ [ [? ?] ] | ]; simpl; eauto.\n    destruct (SkipCurrentByte v n0 c0) as [ [ [? ?] ] | ]; simpl; eauto.\n    destruct u0; reflexivity.\n  Qed.\n\n  Definition aligned_option_decode {S}\n             (decode_Some : forall {numBytes}, AlignedDecodeM S numBytes)\n             (decode_None : forall {numBytes}, AlignedDecodeM () numBytes)\n             (b' : bool)\n    : forall {numBytes}, AlignedDecodeM (option S) numBytes :=\n    (fun sz v idx (env : CacheDecode) =>\n       If b' Then\n          match decode_Some v idx env with\n          | Ok (a, b, c) => Ok ((Some a, b), c)\n          | Error e => Error e\n          end\n          Else\n          match decode_None v idx env with\n          | Ok (a, b, c) => Ok ((None , b), c)\n          | Error e => Error e\n          end).\n  \n  Lemma AlignedDecodeBindOption {S S' : Type}\n        (decode_Some : DecodeM (S * _) ByteString)\n        (decode_None : DecodeM (() * _) ByteString)\n        (aligned_decode_Some : forall numBytes, AlignedDecodeM S numBytes)\n        (aligned_decode_None : forall numBytes, AlignedDecodeM () numBytes)\n        (t : option S -> DecodeM (S' * _) ByteString)\n        (t' : option S -> forall {numBytes}, AlignedDecodeM S' numBytes)\n        b'\n    : (DecodeMEquivAlignedDecodeM decode_Some aligned_decode_Some)\n      -> (DecodeMEquivAlignedDecodeM decode_None aligned_decode_None)\n      -> (forall s_opt, DecodeMEquivAlignedDecodeM (t s_opt) (@t' s_opt))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- Option.option_decode _ decode_Some decode_None b' v cd ;\n                          t a b0 cd')\n           (fun numBytes => a <- aligned_option_decode aligned_decode_Some aligned_decode_None b';\n                              t' a)%AlignedDecodeM.\n  Proof.\n    (*\n    intros.\n    destruct b'; simpl; eapply Bind_DecodeMEquivAlignedDecodeM; eauto.\n    - unfold DecodeMEquivAlignedDecodeM; split; intros.\n      { unfold aligned_option_decode; simpl.\n        destruct H.\n        move H at bottom.\n        rewrite H.\n        destruct (aligned_decode_Some numBytes_hd (Vector.tl v) n cd)\n        as [ [ [? ?] ] | ]; simpl; eauto. }\n      split; intros.\n      { destruct (decode_Some b cd) as [ [ [? ?] ?] | ] eqn: ? ;\n          try discriminate.\n        injections.\n        eapply H; eauto. }\n      split; intros.\n      unfold aligned_option_decode; simpl.\n      split; intros.\n      { destruct (decode_Some (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        inversion H2.\n        eapply isError, H in Heqh.\n        break_match; eauto. }\n      { destruct (aligned_decode_Some n v 0 cd)\n        as [ [ [? ?] ] | ] eqn: ?; simpl; try inversion H2.\n        eapply isError, H in Heqh. break_match; eauto. }\n      split.\n      { destruct (decode_Some (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        eapply H in Heqh; destruct Heqh. rewrite H3.\n        injections; reflexivity. }\n      { destruct (decode_Some (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        eapply H in Heqh; destruct Heqh. destruct H4.\n        injections; eauto. }\n    - unfold DecodeMEquivAlignedDecodeM; split; intros.\n      { unfold aligned_option_decode; simpl.\n        destruct H0; rewrite H0.\n        destruct (aligned_decode_None numBytes_hd (Vector.tl v) n cd)\n        as [ [ [? ?] ] | ]; simpl; eauto. }\n      split; intros.\n      { destruct (decode_None b cd) as [ [ [? ?] ?] | ] eqn: ? ;\n          try discriminate.\n        injections.\n        eapply H0; eauto. }\n      split; intros.\n      unfold aligned_option_decode; simpl.\n      split; intros.\n      { destruct (decode_None (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        inversion H2.\n        eapply isError, H0 in Heqh.\n        break_match; eauto. }\n      { destruct (aligned_decode_None n v 0 cd)\n        as [ [ [? ?] ] | ] eqn: ?; simpl; try inversion H2.\n        eapply isError, H0 in Heqh. break_match; eauto. }\n      split.\n      { destruct (decode_None (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        eapply H0 in Heqh; destruct Heqh. rewrite H3.\n        injections; reflexivity. }\n      { destruct (decode_None (build_aligned_ByteString v) cd)\n          as [ [ [? ?] ] | ] eqn: ?; simpl; try discriminate.\n        eapply H0 in Heqh; destruct Heqh. destruct H4.\n        injections; eauto. }\n  Qed.\n     *)\n  Admitted.\nEnd AlignedDecoders.\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/AlignedDecoders.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.19595849931196946}}
{"text": "Require Import List.\nRequire Export Util Val.\n\nSet Implicit Arguments.\n\nDefinition external := positive.\n\nInductive extern :=\n  ExternI {\n      extern_fnc : external;\n      extern_args : list val;\n      extern_res  : val\n    }.\n\nInductive event :=\n  | EvtExtern (call:extern)\n(*  | EvtTerminate   (res:val) *)\n  | EvtTau.\n\n(** ** [filter_tau] *)\n\nDefinition filter_tau (o:event) (L:list event) : list event :=\n  match o with\n      | EvtTau => L\n      | e => e :: L\n  end.\n\nLemma filter_tau_nil evt B\n : (filter_tau evt nil ++ B)%list = filter_tau evt B.\nProof.\n  destruct evt; simpl; eauto.\nQed.\n\nLemma filter_tau_app evt A B\n :  (filter_tau evt A ++ B)%list = filter_tau evt (A ++ B).\nProof.\n  destruct evt; eauto.\nQed.\n\nLemma filter_tau_nil_eq\n  : nil = filter_tau EvtTau nil.\nProof.\n  reflexivity.\nQed.\n\nHint Extern 5 (nil = filter_tau _ nil) => apply filter_tau_nil_eq.\n\nInductive extevent :=\n  | EEvtExtern (evt:event)\n  | EEvtTerminate (res:option val).\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/Events.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.19589228961029959}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export DistributedReferenceCounting.machine3.machine.\nRequire Export DistributedReferenceCounting.machine3.cardinal.\nRequire Export DistributedReferenceCounting.machine3.comm.\nRequire Export DistributedReferenceCounting.machine3.still_to_prove.\n\nUnset Standard Proposition Elimination Names.\n\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.\n\n\n  (* optim 1 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_weight_change_queue with (s3 := s2).\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  omega.\n  auto.\n    \n\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/machine3/invariant1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19589226931909068}}
{"text": "(* -*- coding: utf-8 -*- *)\n(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2015     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n(*                                                                      *)\n(* Micromega: A reflexive tactic using the Positivstellensatz           *)\n(*                                                                      *)\n(*  Fr\u00e9d\u00e9ric Besson (Irisa/Inria) 2006-2008                             *)\n(*                                                                      *)\n(************************************************************************)\n\nRequire Import ZArith.\nRequire Import Coq.Arith.Max.\nRequire Import List.\nSet Implicit Arguments.\n\n(* \n * This adds a Leaf constructor to the varmap data structure (plugins/quote/Quote.v)\n * --- it is harmless and spares a lot of Empty.\n * It also means smaller proof-terms.\n * As a side note, by dropping the polymorphism, one gets small, yet noticeable, speed-up.\n *)\n\nSection MakeVarMap.\n  \n  Variable A : Type.\n  Variable default : A.\n\n  Inductive t  : Type :=\n  | Empty : t\n  | Leaf : A -> t\n  | Node : t  -> A -> t  -> t .\n\n  Fixpoint find (vm : t) (p:positive) {struct vm} : A :=\n    match vm with\n      | Empty => default\n      | Leaf i => i\n      | Node l e r => match p with\n                        | xH => e\n                        | xO p => find l p\n                        | xI p => find r p\n                      end\n    end.\n\n\n  Fixpoint singleton (x:positive) (v : A) : t :=\n    match x with\n    | xH => Leaf v\n    | xO p => Node (singleton p v) default Empty\n    | xI p => Node Empty default (singleton p v)\n    end.\n  \n  Fixpoint vm_add (x: positive) (v : A) (m : t) {struct m} : t :=\n    match m with\n    | Empty   => singleton x v\n    | Leaf vl =>\n      match x with\n      | xH => Leaf v\n      | xO p => Node (singleton p v) vl Empty\n      | xI p => Node Empty vl (singleton p v)\n      end\n    | Node l o r => \n      match x with\n      | xH => Node l v r\n      | xI p => Node l o (vm_add p v r)\n      | xO p => Node (vm_add p v l) o r\n      end\n    end.\n\n  \nEnd MakeVarMap.  \n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/plugins/micromega/VarMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"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 Sorting.\nRequire Import Eqdep_dec.\nRequire Import Bool.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import BrandRelation.\nRequire Import ForeignType.\nRequire Import RType.\n\nSection RTypeNorm.\n  (** Syntax of types. Note that there is no guarantee yet that records are well formed. i.e., having distinct fields. *)\n\n  Context {ftype:foreign_type}.\n  Context {br:brand_relation}.\n\n  Fixpoint normalize_rtype\u2080 (r:rtype\u2080) : rtype\u2080 :=\n    match r with\n    | Bottom\u2080 => Bottom\u2080\n    | Top\u2080 => Top\u2080\n    | Unit\u2080 => Unit\u2080\n    | Nat\u2080 => Nat\u2080\n    | Float\u2080 => Float\u2080\n    | Bool\u2080 => Bool\u2080\n    | String\u2080 => String\u2080\n    | Coll\u2080 r' => Coll\u2080 (normalize_rtype\u2080 r')\n    | Rec\u2080 k srl => Rec\u2080 k (rec_sort (map (fun sr => ((fst sr), (normalize_rtype\u2080 (snd sr)))) srl))\n    | Either\u2080 tl tr => Either\u2080 (normalize_rtype\u2080 tl) (normalize_rtype\u2080 tr)\n    | Arrow\u2080 tin tout => Arrow\u2080 (normalize_rtype\u2080 tin) (normalize_rtype\u2080 tout)\n    | Brand\u2080 bl => Brand\u2080 (canon_brands brand_relation_brands bl)\n    | Foreign\u2080 ft => Foreign\u2080 ft\n    end.\n\n  Lemma exists_normalized_in_rec_sort x r:\n    In x\n       (rec_sort\n          (map\n             (fun sr : string * rtype\u2080 =>\n                (fst sr, normalize_rtype\u2080 (snd sr))) r)) ->\n    exists y,\n      (In y r /\\\n       snd x = (normalize_rtype\u2080 (snd y))).\n  Proof.\n    intros.\n    induction r.\n    - contradiction.\n    - simpl in *.\n      destruct a; simpl in *.\n      assert (x = (s, normalize_rtype\u2080 r0) \\/ In x (rec_sort\n              (map\n                 (fun sr : string * rtype\u2080 =>\n                    (fst sr, normalize_rtype\u2080 (snd sr))) r))) by\n          (apply in_rec_sort_insert; assumption).\n      elim H0; clear H0; intros.\n      + exists (s, r0).\n        split; [left;reflexivity|].\n        rewrite H0; reflexivity.\n      + elim (IHr H0); intros.\n        elim H1; clear H1; intros.\n        exists x0.\n        split; [right;assumption|assumption].\n  Qed.\n    \n  Lemma normalize_rtype\u2080_wf (r:rtype\u2080) :\n    wf_rtype\u2080 (normalize_rtype\u2080 r) = true.\n  Proof.\n    induction r; try reflexivity; simpl; try assumption.\n    - apply andb_true_intro; split.\n      + apply (@rec_sort_pf string ODT_string).\n      + rewrite Forall_forall in H.\n        rewrite forallb_forall; intros.\n        elim (exists_normalized_in_rec_sort x r H0); intros.\n        elim H1; clear H1; intros.\n        rewrite H2.\n        apply (H x0 H1).\n    - apply andb_true_intro; split; assumption.\n    - apply andb_true_intro; split; assumption.\n    - destruct (is_canon_brands_dec brand_relation_brands\n                                    (canon_brands brand_relation_brands b)).\n      + reflexivity.\n      + generalize (canon_brands_is_canon_brands brand_relation_brands b); intros.\n        congruence.\n  Qed.  \n\n  Program Definition normalize_rtype\u2080_to_rtype (r\u2080:rtype\u2080) : rtype :=\n    exist _ (normalize_rtype\u2080 r\u2080) _.\n  Next Obligation.\n    apply normalize_rtype\u2080_wf.\n  Defined.\n  \nEnd RTypeNorm.\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/RTypeNorm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.19582702163591229}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Cito.ADT.\nRequire Import Bedrock.Platform.Cito.RepInv.\n\nModule Make (Import E : ADT) (Import M : RepInv E).\n\n  Require Import Bedrock.Platform.Cito.Inv.\n  Module Import InvMake := Make E.\n  Module Import InvMake2 := Make M.\n\n  Require Import Bedrock.Platform.Cito.SyntaxFunc.\n  Require Import Coq.Strings.String.\n  Require Import Bedrock.Platform.Malloc.\n\n  Section TopSection.\n\n    Variable func : FuncCore.\n\n    Definition spec_without_funcs_ok fs : assert :=\n      st ~> ExX, internal_spec _ fs func st.\n\n    Definition spec : assert :=\n      st ~> Ex fs,\n      let stn := fst st in\n      funcs_ok stn fs /\\\n      spec_without_funcs_ok fs st.\n\n    Definition imply (pre new_pre: assert) := forall specs x, interp specs (pre x) -> interp specs (new_pre x).\n\n    Definition verifCond pre := imply pre spec :: nil.\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/CompileFuncSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.19582702163591223}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Spaces.\nRequire Import Uniform.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Model.\nRequire Import Truncate.\nRequire Import Standard.\nRequire Import System.\nRequire Import Semantics.\nRequire Import Extend.\nRequire Import SemanticsEqual.\nRequire Import Ceiling.\nRequire Import MapTerm.\nRequire Import Hygiene.\nRequire Import ExtendTruncate.\nRequire Import Equivalence.\nRequire Import SemanticsMu.\nRequire Import SemanticsPositive.\n\n(* These two are needed for raise_robust.  The later could be dispensed with,\n   with some work, by basing robust on step instead of reduce.\n*)\nRequire Import ProperClosed.\nRequire Import ProperEquiv.\n\n\nSection semantics.\n\n\nVariable system : System.\n\n\nLemma interp_kext_fun :\n  forall pg i m K K',\n    interp_kext pg i m K\n    -> interp_kext pg i m K'\n    -> K = K'.\nProof.\nintros pg i m K K' Hint Hint'.\ndestruct Hint as (Q & h & _ & Hsteps & _ & Heq).\ndestruct Hint' as (Q' & h' & _ & Hsteps' & _ & Heq').\nso (determinism_eval _#4 (conj Hsteps value_ext) (conj Hsteps' value_ext)) as H.\ninjectionc H.\nintro H.\ninjection (objin_inj _ _ _ H); clear H.\nintros <-.\nexact (eqtrans (eqsymm Heq) Heq').\nQed.\n\n\nLemma interp_uext_fun :\n  forall pg i m R R',\n    interp_uext pg i m R\n    -> interp_uext pg i m R'\n    -> R = R'.\nProof.\nintros pg i m R R' Hint Hint'.\ndestruct Hint as (w & A & h & _ & Hsteps & _ & Heq).\ndestruct Hint' as (w' & A' & h' & _ & Hsteps' & _ & Heq').\nso (determinism_eval _#4 (conj Hsteps value_ext) (conj Hsteps' value_ext)) as H.\ninjectionc H.\nintro H.\ninjection (objin_inj _ _ _ H); clear H.\nintros H <-.\ninjectionT H.\nintros <-.\nexact (eqtrans (eqsymm Heq) Heq').\nQed.\n\n\nLemma eval_bite_invert :\n  forall object (m n p q : term object),\n    eval (bite m n p) q\n    -> (star step m btrue /\\ star step n q)\n       \\/ (star step m bfalse /\\ star step p q).\nProof.\nintros object m n p q Heval.\ndestruct Heval as (Hsteps & Hval).\nremember (bite m n p) as r eqn:Heq.\nrevert m Heq Hval.\ninduct Hsteps.\n\n(* refl *)\n{\nintros q m -> Hval.\ninvert Hval.\nintro H.\ninvert H.\n}\n\n(* step *)\n{\nintros x s q Hstep Hsteps IH m -> Hval.\ninvert Hstep.\n  {\n  intros m' Hstepm <-.\n  so (IH m' (eq_refl _) Hval) as [(Hstepsm & Hstepsq) | (Hstepsm & Hstepsq)].\n    {\n    left.\n    split; auto.\n    eapply star_step; eauto.\n    }\n\n    {\n    right.\n    split; auto.\n    eapply star_step; eauto.\n    }\n  }\n\n  {\n  intros <- <-.\n  left.\n  split; auto using star_refl.\n  }\n\n  {\n  intros <- <-.\n  right.\n  split; auto using star_refl.\n  }\n}\nQed.\n\n\nDefinition exttin w X h := \n  @extt (obj stop) (objin (objsome (expair (qtype w) (iubase X)) h)).\n\n\nLemma subst_exttin :\n  forall s w X h, subst s (exttin w X h) = exttin w X h.\nProof.\nintros s w X h.\nunfold exttin.\nsimpsub.\nreflexivity.\nQed.\n\n\nHint Rewrite subst_exttin : subst.\n\n\nLemma subst_under_extt_hygiene :\n  forall object a k (x y : object) s,\n    hygiene clo (subst (compose (under k (dot (extt x) id)) s) a)\n    -> hygiene clo (subst (compose (under k (dot (extt y) id)) s) a).\nProof.\nintros object a k x y s Hcla.\nso (hygiene_subst_invert _#4 Hcla) as H.\neapply hygiene_subst; eauto; clear H.\nintros i Hi.\ncbn in Hi.\nrewrite -> project_compose in Hi |- *.\nso (Nat.lt_trichotomy i k) as [Hik | [H | Hki]].\n  {\n  rewrite -> project_under_lt in Hi |- *; auto.\n  }\n\n  {\n  subst i.\n  rewrite -> project_under_eq.\n  simpsub.\n  apply hygiene_auto; cbn; auto.\n  }\n\n  {\n  rewrite -> project_under_geq in Hi |- *; try omega.\n  replace (i - k) with (S (i - k - 1)) in Hi |- * by omega.\n  simpsub.\n  simpsubin Hi.\n  auto.\n  }\nQed.\n\n\nLemma raise_robust_functional_ih :\n  forall pg z i j A s b v w X Y (hv : v << stop) (hw : w << stop) F,\n    v <<= cin pg\n    -> w <<= cin pg\n    -> extend_urel v stop X = extend_urel w stop Y\n    -> (forall i s B,\n          basic system pg z i (subst (compose (under (S j) (dot (exttin v X hv) id)) s) b) B\n          -> basic system pg z i (subst (compose (under (S j) (dot (exttin w Y hw) id)) s) b) B)\n    -> functional system pg z i A (subst (dot (var 0) (compose (under j (dot (exttin v X hv) id)) (compose s sh1))) b) F\n    -> functional system pg z i A (subst (dot (var 0) (compose (under j (dot (exttin w Y hw) id)) (compose s sh1))) b) F.\nProof.\nintros pg z i k A s b v w X Y hv hw F Hvpg Hwpg Heq IH Hfunct.\ninvert Hfunct.\nintros Hhyg Hceil Hact.\napply functional_i; auto.\n  {\n  so (hygiene_subst_invert _#4 Hhyg) as Hhygi.\n  eapply hygiene_subst; eauto.\n  cbn.\n  intros x Hx.\n  destruct x as [| x].\n    {\n    simpsub.\n    apply hygiene_var.\n    split.\n    }\n  simpsub.\n  simpsubin Hx.\n  so (Nat.lt_trichotomy x k) as [Hxk | [H | Hkx]].\n    {\n    rewrite -> project_under_lt in Hx |- *; auto.\n    }\n\n    {\n    subst x.\n    rewrite -> project_under_eq.\n    simpsub.\n    apply hygiene_auto; cbn; auto.\n    }\n\n    {\n    rewrite -> project_under_geq in Hx |- *; try omega.\n    replace (x - k) with (S (x - k - 1)) in Hx |- * by omega.\n    simpsub.\n    simpsubin Hx.\n    auto.\n    }\n  }\nintros j m p Hj Hmp.\nsimpsub.\nso (Hact _#3 Hj Hmp) as Hint.\nsimpsubin Hint.\nrewrite -> split_dot.\nchange (varx (obj stop) 0) with (@var (obj stop) 0).\nexploit (IH j (dot (if z then m else p) s) (pi1 F (urelspinj A j m p Hmp))) as H.\n  {\n  simpsub.\n  auto.\n  }\nsimpsubin H.\nsimpsub.\nauto.\nQed.\n\n\nLemma raise_robust :\n  forall pg s i a v w X Y (hv : v << stop) (hw : w << stop) A,\n    v <<= cin pg\n    -> w <<= cin pg\n    -> extend_urel v stop X = extend_urel w stop Y\n    -> robust 0 a\n    -> basic system pg s i (subst1 (exttin v X hv) a) A\n    -> basic system pg s i (subst1 (exttin w Y hw) a) A.\nProof.\nintros pg z i a v w X Y hv hw A Hv Hw HeqXY Hrobust Hint.\nassert (basic system pg z i (subst (compose (under 0 (dot (exttin v X hv) id)) id) a) A) as Hint'.\n  {\n  simpsub.\n  exact Hint.\n  }\nrenameover Hint' into Hint.\ncut (basic system pg z i (subst (compose (under 0 (dot (exttin w Y hw) id)) id) a) A).\n  {\n  intro H; simpsubin H.\n  exact H.\n  }\nset (j := 0) in Hrobust, Hint |- *.\nset (s := id) in Hint at 2 |- * at 2.\nclearbody j s.\nrevert i s A Hint.\ninduct Hrobust.\n\n(* var *)\n{\nintros k i s A Hint.\nsimpsub.\nsimpsubin Hint.\nrewrite -> project_under_eq in Hint |- *.\nsimpsub.\nsimpsubin Hint.\ninvert (basic_value_inv _#6 value_extt Hint).\nintros u R hu Hu Heq <-.\nso (objin_inj _ _ _ Heq) as Heq'.\nclear Heq.\ninjectionc Heq'.\nintros Heq ->.\ninjectionT Heq.\nintros ->.\nso (proof_irrelevance _ hv hu); subst hu.\nclear Hint.\nso (interp_extt system pg z i w (iubase Y) hw Hw) as H.\nrewrite -> iutruncate_iubase in H |- *.\nrewrite -> extend_iubase in H |- *.\nrewrite <- ceiling_extend_urel in H |- *.\nrewrite -> HeqXY.\napply interp_eval_refl.\nexact H.\n}\n\n(* const *)\n{\nintros k a i s A Hint.\nrewrite <- subst_compose in Hint |- *.\nrewrite <- compose_assoc in Hint |- *.\nrewrite <- compose_under in Hint |- *.\nsimpsub.\nsimpsubin Hint.\nexact Hint.\n}\n\n(* prod *)\n{\nintros k a b _ IH1 _ IH2 i s R Hint.\nsimpsub.\nsimpsubin Hint.\ninvert (basic_value_inv _#6 value_prod Hint).\nintros A B Ha Hb <-.\napply interp_eval_refl.\napply interp_prod; eauto.\n}\n\n(* pi *)\n{\nintros j a b _ IH1 _ IH2 i s R Hint.\nsimpsub.\nsimpsubin Hint.\ninvert (basic_value_inv _#6 value_pi Hint).\nintros A B Ha Hb <-.\napply interp_eval_refl.\napply interp_pi; eauto.\nexact (raise_robust_functional_ih _#14 Hv Hw HeqXY IH2 Hb).\n}\n\n(* sigma *)\n{\nintros j a b _ IH1 _ IH2 i s R Hint.\nsimpsub.\nsimpsubin Hint.\ninvert (basic_value_inv _#6 value_sigma Hint).\nintros A B Ha Hb <-.\napply interp_eval_refl.\napply interp_sigma; eauto.\nexact (raise_robust_functional_ih _#14 Hv Hw HeqXY IH2 Hb).\n}\n\n(* mu *)\n{\nintros j a _ IH i s R Hint.\nsimpsub.\nsimpsubin Hint.\ninvert (basic_value_inv _#6 value_mu Hint).\nintros u F Hu Hact Hne Hmono Hrobust <-.\napply interp_eval_refl.\neapply interp_mu; eauto.\n  {\n  intros Z h.\n  so (Hact Z h) as HintZ.\n  exploit (IH i (dot (exttin u Z h) s) (extend_iurel (lt_ord_impl_le_ord u stop h) (F Z))) as H.\n    {\n    simpsub.\n    simpsubin HintZ.\n    auto.\n    }\n  simpsub.\n  simpsubin H.\n  auto.\n  }\n\n  {\n  set (o1 := (objin (objsome (expair (qtype v) (iubase X)) hv))).\n  set (o2 := (objin (objsome (expair (qtype w) (iubase Y)) hw))).\n  set (f := fun x => match x with | Some y => y | None => o1 end).\n  set (g := fun x => match x with | Some y => y | None => o2 end).\n  replace\n    (subst (dot (var 0) (compose (under j (dot (exttin v X hv) id)) (compose s sh1))) a)\n    with\n    (map_term f\n       (subst\n          (dot (var 0) (compose \n                          (under j (dot (extt None) id))\n                          (compose (map_sub Some s) sh1)))\n          (map_term Some a))) in Hrobust.\n  2:{\n    simpmap.\n    rewrite -> map_sub_compose.\n    rewrite -> map_term_compose.\n    subst f.\n    cbn.\n    rewrite -> map_sub_id.\n    rewrite -> map_term_id.\n    auto.\n    }\n  so (map_robust_conv _#5 Hrobust) as Hrobust'.\n  so (map_robust _#3 g _ Hrobust') as H.\n  simpmapin H.\n  rewrite -> map_sub_compose in H.\n  rewrite -> map_term_compose in H.\n  subst g.\n  cbn.\n  rewrite -> map_sub_id in H.\n  rewrite -> map_term_id in H.\n  auto.\n  }\n}\n\n(* bite *)\n{\nintros k m a b _ IH1 _ IH2 i s R Hint.\nsimpsub.\nsimpsubin Hint.\ninvertc Hint.\nintros c Hhyg Hsteps Hint.\nso (basicv_value _#6 Hint) as Hval.\nso (hygiene_invert_auto _#5 Hhyg) as H; cbn in H.\ndestruct H as (Hclm & Hcla & Hclb & _).\nassert (hygiene clo (subst (compose (under k (dot (exttin w Y hw) id)) s) a)) as Hcla'.\n  {\n  eapply subst_under_extt_hygiene; eauto.\n  }\nassert (hygiene clo (subst (compose (under k (dot (exttin w Y hw) id)) s) b)) as Hclb'.\n  {\n  eapply subst_under_extt_hygiene; eauto.\n  }\nso (eval_bite_invert _#5 (conj Hsteps Hval)) as [(Hstepm & Hstepsa) | (Hstepm & Hstepsb)].\n  {\n  assert (basic system pg z i (subst (compose (under k (dot (exttin v X hv) id)) s) a) R) as Hintv.\n    {\n    eapply interp_eval; eauto.\n    }\n  so (IH1 _#3 Hintv) as Hintw.\n  refine (basic_unstep _#7 _ _ Hintw).\n    {\n    apply hygiene_auto; cbn.\n    do2 3 split; auto.\n    rewrite <- compose_assoc in Hclm |- *.\n    rewrite <- compose_under in Hclm |- *.\n    simpsub.\n    simpsubin Hclm.\n    exact Hclm.\n    }\n\n    {\n    rewrite <- compose_assoc in Hstepm |- *.\n    rewrite <- compose_under in Hstepm |- *.\n    simpsub.\n    simpsubin Hstepm.\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun Z => bite Z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite2.\n    }\n  }\n\n  {\n  assert (basic system pg z i (subst (compose (under k (dot (exttin v X hv) id)) s) b) R) as Hintv.\n    {\n    eapply interp_eval; eauto.\n    }\n  so (IH2 _#3 Hintv) as Hintw.\n  refine (basic_unstep _#7 _ _ Hintw).\n    {\n    apply hygiene_auto; cbn.\n    do2 3 split; auto.\n    rewrite <- compose_assoc in Hclm |- *.\n    rewrite <- compose_under in Hclm |- *.\n    simpsub.\n    simpsubin Hclm.\n    exact Hclm.\n    }\n\n    {\n    rewrite <- compose_assoc in Hstepm |- *.\n    rewrite <- compose_under in Hstepm |- *.\n    simpsub.\n    simpsubin Hstepm.\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun Z => bite Z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite3.\n    }\n  }\n}\n\n(* weaken *)\n{\nintros k a _ IH i s A Hint.\nsimpsub.\nsimpsubin Hint.\nrewrite <- compose_assoc in Hint |- *.\nrewrite -> compose_sh_under_eq in Hint |- *.\nsimpsub.\nsimpsubin Hint.\nexploit (IH i (compose (sh k) s) A) as H.\n  {\n  simpsub; auto.\n  }\nsimpsubin H.\nauto.\n}\n\n(* reduce *)\n{\nintros k a b Hab _ IH i s R Hint.\nso (basic_closed _#6 Hint) as Hclas.\nso (reduce_hygiene _#4 (reduce_subst _#4 Hab) Hclas) as Hclbs.\nexploit (IH i s R) as H.\n  {\n  eapply basic_equiv; eauto.\n  apply equiv_subst.\n  apply reduce_equiv; auto.\n  }\nrefine (basic_equiv _#7 _ _ H).\n  {\n  eapply subst_under_extt_hygiene; eauto.\n  }\n\n  {\n  apply equiv_subst.\n  apply equiv_symm.\n  apply reduce_equiv; auto.\n  }\n}\nQed.\n\n\nLemma semantics_fun :\n  (forall pg s i a X X',\n     kbasic system pg s i a X\n     -> kbasic system pg s i a X'\n     -> X = X')\n  /\\\n  (forall pg s i a X X',\n     cbasic system pg s i a X\n     -> cbasic system pg s i a X'\n     -> X = X')\n  /\\\n  (forall pg s i a X X',\n     basic system pg s i a X\n     -> basic system pg s i a X'\n     -> X = X')\n  /\\\n  (forall pg s i A a X X',\n     functional system pg s i A a X\n     -> functional system pg s i A a X'\n     -> X = X').\nProof.\nexploit\n  (semantics_ind system\n     (fun pg s i a X => forall X', kbasicv system pg s i a X' -> X = X')\n     (fun pg s i a X => forall X', cbasicv system pg s i a X' -> X = X')\n     (fun pg s i a X => forall X', basicv system pg s i a X' -> X = X')\n     (fun pg s i a X => forall X', kbasic system pg s i a X' -> X = X')\n     (fun pg s i a X => forall X', cbasic system pg s i a X' -> X = X')\n     (fun pg s i a X => forall X', basic system pg s i a X' -> X = X')\n     (fun pg s i A a X => forall X', functional system pg s i A a X' -> X = X')) as Hind;\ntry (intros;\n     match goal with\n     | H : kbasicv _ _ _ _ _ _ |- _ => invert H\n     | H : cbasicv _ _ _ _ _ _ |- _ => invert H\n     | H : basicv _ _ _ _ _ _ |- _ => invert H\n     end;\n     intros; subst; f_equal; eauto;\n     done).\n\n(* ktarrow *)\n{\nintros pg s i a k A K HA IH1 _ IH2 X HX.\ninvertc HX.\nintros A' K' Ha Hk <-.\nso (IH1 _ Ha) as Heq.\nso (extend_iurel_inj _#5 Heq); subst A'.\nso (IH2 _ Hk); subst K'.\nreflexivity.\n}\n\n(* ext *)\n{\nintros pg s i Q h _ X HX.\ninvert HX.\nintros Q' h' _ Heq <-.\nso (f_equal objout Heq) as Heq'.\nrewrite -> !objout_objin in Heq'.\ninjection Heq'.\nintros ->.\nreflexivity.\n}\n\n(* clam *)\n{\nintros pg s i k a K L A h HeqL Hk _ IH X HX.\ninvertc HX.\nintros K' L' A' h' HeqL' Hk' Ha <-.\nso (interp_kext_fun _#5 Hk Hk'); subst K'.\nso (proof_irrelevance _ h h'); subst h'.\nso (space_inhabitant (approx i K)) as x.\ninjection (IH i (le_refl _) _ _ (Ha i (le_refl _) x)).\nintros _ HeqLs.\nclear x.\nso (eqtrans HeqL (eq_trans HeqLs (eqsymm HeqL'))); subst L'.\nunfold stdc.\ncbn.\nf_equal.\nrewrite -> std_arrow_is.\ncbn.\napply nearrow_extensionality.\nintro x.\ncbn.\nfold (std (S i) L).\nfold (std (S i) K).\ninjection (IH i (le_refl _) _ _ (Ha i (le_refl _) (proj i K (std (S i) K x)))).\nintros H.\ninjectionT H.\nintros Heq.\nsetoid_rewrite <- std_idem at 1 2.\nso (proj_eq_dist _#4 Heq) as Heq'.\nsetoid_rewrite -> proj_std in Heq'; auto.\nsetoid_rewrite -> embed_std in Heq'; auto.\nrewrite -> std_idem in Heq'.\nsetoid_rewrite <- embed_std in Heq'; auto.\nrewrite <- proj_std in Heq'; auto.\napply std_collapse.\neapply dist_trans.\n  {\n  apply std_nonexpansive.\n  apply (pi2 A).\n  apply dist_symm.\n  apply embed_proj.\n  }\neapply dist_trans.\n  {\n  exact Heq'.\n  }\napply std_nonexpansive.\napply (pi2 A').\napply embed_proj.\n}\n\n(* capp *)\n{\nintros pg s i a b K L A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros K' L' A' B' Ha Hb <-.\nso (IH1 _ Ha) as Heq1.\ninjection Heq1.\nintros <- <-.\nso (expair_injection_2 _#5 Heq1).\nsubst A'.\nso (expair_injection_2 _#5 (IH2 _ Hb)).\nsubst B'.\nreflexivity.\n}\n\n(* ctlam *)\n{\nintros pg s i a b k K A f B _ Ha Hk _ IH Hf X HX.\ninvertc HX.\nintros K' A' f' B' _ Ha' Hk' Hb Hf' <-.\nso (interp_uext_fun _#5 Ha Ha'); subst A'.\nso (interp_kext_fun _#5 Hk Hk'); subst K'.\nf_equal.\napply nearrow_extensionality.\nintros C.\nso (urelsp_eta _ _ C) as (j & m & p & Hmp & ->).\nso (cin_stop pg) as Hlstop.\nset (l := cin pg) in Hlstop.\nassert (rel (extend_urel l stop A) j (map_term (extend l stop) m) (map_term (extend l stop) p)) as Hmp'.\n  {\n  cbn.\n  rewrite -> !extend_term_cancel; auto.\n  }\nso (Hf _ _ _ Hmp') as H.\nrewrite -> (urelspinj_equal _#4 m _ p _ Hmp) in H.\n2:{\n  rewrite -> extend_term_cancel; auto.\n  }\nrewrite -> H; clear H.\nso (Hf' _ _ _ Hmp') as H.\nrewrite -> (urelspinj_equal _#4 m _ p _ Hmp) in H.\n2:{\n  rewrite -> extend_term_cancel; auto.\n  }\nrewrite -> H; clear H.\nf_equal.\nso (IH _#3 Hmp' _ (Hb _#3 Hmp')) as Heq'.\neapply expair_injection_2; eauto.\n}\n\n(* ctapp *)\n{\nintros pg s i b m l A K B n p Hnp Hm _ IH X HX.\ninvertc HX.\nintros l' A' K' B' n' p' Hnp' Hm' Hb <-.\nso (IH _ Hb) as Heq.\ninjection Heq.\nintros <- H <-.\ninjectionT H.\nintros <-.\ninjectionT Heq.\nintros <-.\nrewrite -> Hm' in Hm.\nf_equal.\nf_equal.\napply urelspinj_equal.\ndestruct s; subst; eapply urel_zigzag; eauto.\n}\n\n(* cpair *)\n{\nintros pg s i a b K L x y _ IH1 _ IH2 X HX.\ninvertc HX.\nintros K' L' x' y' Ha Hb <-.\ninjection (IH1 _ Ha).\nintros H <-.\ninjectionT H.\nintros <-.\ninjection (IH2 _ Hb).\nintros H <-.\ninjectionT H.\nintros <-.\nreflexivity.\n}\n\n(* cpi1 *)\n{\nintros pg s i a K L x _ IH X HX.\ninvertc HX.\nintros K' L' x' Ha <-.\ninjection (IH _ Ha).\nintros H <- <-.\ninjectionT H.\nintros <-.\nreflexivity.\n}\n\n(* cpi2 *)\n{\nintros pg s i a K L x _ IH X HX.\ninvertc HX.\nintros K' L' x' Ha <-.\ninjection (IH _ Ha).\nintros H <- <-.\ninjectionT H.\nintros <-.\nreflexivity.\n}\n\n(* cnext *)\n{\nintros pg s i a K x _ IH X HX.\ninvertc HX.\nintros K' x' Ha <-.\nso (IH _ Ha) as Heq.\ninjectionc Heq.\nintros H <-.\ninjectionT H.\nintros <-.\nreflexivity.\n}\n\n(* cprev *)\n{\nintros pg s i a K x _ IH X HX.\ninvertc HX.\nintros K' x' Ha <-.\nso (IH _ Ha) as Heq.\ninjectionc Heq.\nintros H <-.\ninjectionT H.\nintros <-.\nreflexivity.\n}\n\n(* cty *)\n{\nintros pg s i a R _ IH X HX.\ninvertc HX.\nintros R' Ha <-.\nso (IH _ Ha) as Heq.\nso (extend_iurel_inj _#5 Heq); subst R'.\nreflexivity.\n}\n\n(* con *)\n{\nintros pg s i lv a gpg R Hlv _ _ IH X HX.\ninvertc HX.\nintros gpg' R' Hlv' _ Ha <-.\nso (pginterp_fun _#3 Hlv Hlv'); subst gpg'.\nso (IH _ Ha) as Heq.\ninjectionT Heq.\nintros <-.\nreflexivity.\n}\n\n(* pi *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nreflexivity.\n}\n\n(* intersect *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nreflexivity.\n}\n\n(* sigma *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nreflexivity.\n}\n\n(* set *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nreflexivity.\n}\n\n(* quotient *)\n{\nintros pg s i a b A B hs ht _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' hs' ht' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nso (proof_irrelevance _ hs hs'); subst hs'.\nso (proof_irrelevance _ ht ht'); subst ht'.\nreflexivity.\n}\n\n(* guard *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha).\nsubst A'.\nf_equal.\napply IH2; auto.\n}\n\n(* wt *)\n{\nintros pg s i a b A B _ IH1 _ IH2 X HX.\ninvertc HX.\nintros A' B' Ha Hb <-.\nso (IH1 _ Ha); subst A'.\nso (IH2 _ Hb); subst B'.\nreflexivity.\n}\n\n(* equal *)\n{\nintros pg s i a m n p q A Hmp Hnq _ IH X HX.\ninvertc HX.\nintros p' q' A' Hmp' Hnq' Ha' <-.\nso (IH _ Ha'); subst A'.\napply iuequal_equal; auto.\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 _ _ IH2 X HX.\ninvertc HX.\nintros gpg' K' A' h' Hlv' Hk _ Ha <-.\nso (pginterp_fun _#3 Hlv Hlv'); subst gpg'.\nso (IH1 _ Hk); subst K'.\nso (proof_irrelevance _ h h'); subst h'.\nf_equal.\nrewrite -> std_arrow_is; cbn.\napply nearrow_extensionality.\nintro x.\ncbn.\nchange (std (S i) (qtype stop) (pi1 A (std (S i) K x))\n        =\n        std (S i) (qtype stop) (pi1 A' (std (S i) K x))).\nrewrite -> std_type_is.\nso (IH2 i (le_refl _) (proj i K x) _ (Ha i (le_refl _) (proj i K x))) as Heq.\netransitivity.\n  {\n  etransitivity.\n  2:{ exact Heq. }\n  symmetry.\n  f_equal.\n  f_equal.\n  apply std_collapse.\n  apply embed_proj.\n  }\n\n  {\n  f_equal.\n  f_equal.\n  apply std_collapse.\n  apply embed_proj.\n  }\n}\n\n(* alltp *)\n{\nintros pg s i a A _ IH X HX.\ninvertc HX.\nintros A' Ha <-.\nf_equal.\napply nearrow_extensionality.\nintro X.\nexact (IH i (le_refl _) X _ (Ha i (le_refl _) X)).\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 _ _ IH2 X HX.\ninvertc HX.\nintros gpg' K' A' h' Hlv' Hk _ Ha <-.\nso (pginterp_fun _#3 Hlv Hlv'); subst gpg'.\nso (IH1 _ Hk); subst K'.\nso (proof_irrelevance _ h h'); subst h'.\nf_equal.\nrewrite -> std_arrow_is; cbn.\napply nearrow_extensionality.\nintro x.\ncbn.\nchange (std (S i) (qtype stop) (pi1 A (std (S i) K x))\n        =\n        std (S i) (qtype stop) (pi1 A' (std (S i) K x))).\nrewrite -> std_type_is.\nso (IH2 i (le_refl _) (proj i K x) _ (Ha i (le_refl _) (proj i K x))) as Heq.\netransitivity.\n  {\n  etransitivity.\n  2:{ exact Heq. }\n  symmetry.\n  f_equal.\n  f_equal.\n  apply std_collapse.\n  apply embed_proj.\n  }\n\n  {\n  f_equal.\n  f_equal.\n  apply std_collapse.\n  apply embed_proj.\n  }\n}\n\n(* extt *)\n{\nintros pg s i w R h Hw X HX.\ninvertc HX.\nintros w' R' h' Hw' Heq <-.\nso (objin_inj _ _ _ Heq) as Heq'.\ninjectionc Heq'; clear Heq.\nintros Heq ->.\ninjectionT Heq.\nintros ->.\nso (proof_irrelevance _ h h'); subst h'.\nreflexivity.\n}\n\n(* mu *)\n{\nintros pg v s i a F Hv _ IH Hne HmonoF Hrobust X HX.\ninvertc HX.\nintros w G Hw Hact _ HmonoG _ <-.\nassert (v << stop) as hv.\n  {\n  eapply le_lt_ord_trans; eauto.\n  apply (le_lt_ord_trans _ top); auto using cin_top.\n  apply succ_increase.\n  }\nassert (w << stop) as hw.\n  {\n  eapply le_lt_ord_trans; eauto.\n  apply (le_lt_ord_trans _ top); auto using cin_top.\n  apply succ_increase.\n  }\nso (le_lt_ord_dec v w) as [Hvw | Hlt].\n  {\n  assert (forall X,\n            extend_urel v w (den (F X))\n            =\n            den (G (extend_urel v w X))) as Heq.\n    {\n    intro X.\n    rewrite <- (den_extend_iurel _ _ Hvw).\n    f_equal.\n    so (Hact (extend_urel v w X) hw) as Hint.\n    fold (exttin w (extend_urel v w X) hw) in Hint.\n    exploit (IH X hv (extend_iurel (lt_ord_impl_le_ord _ _ hw) (G (extend_urel v w X)))) as Heq.\n      {\n      fold (exttin v X hv).\n      eapply raise_robust; eauto.\n      rewrite <- extend_urel_compose_up; eauto.\n      }\n    replace (lt_ord_impl_le_ord _ _ hv) with (le_ord_trans _#3 Hvw (lt_ord_impl_le_ord _ _ hw)) in Heq.\n    2:{\n      apply proof_irrelevance.\n      }\n    rewrite -> extend_iurel_compose in Heq.\n    exact (extend_iurel_inj _#5 Heq).\n    }\n  rewrite -> (extend_urel_compose_up v w stop); auto.\n  do 2 f_equal.\n  rewrite -> extend_mu; auto.\n  transitivity (mu_urel w (fun X => den (G (blur v w X)))).\n    {\n    f_equal.\n    fextensionality 1.\n    intro X.\n    apply Heq.\n    }\n  apply (blur_vanish _ _ (fun X => den (G X))); auto.\n  intro X.\n  unfold blur.\n  rewrite <- !Heq.\n  rewrite <- (extend_urel_compose_up v w); auto.\n  rewrite -> extend_urel_id; auto.\n  }\n\n  {\n  rename v into u; rename w into v; rename u into w.\n  rename Hv into Hu; rename Hw into Hv; rename Hu into Hw.\n  rename hv into hu; rename hw into hv; rename hu into hw.\n  rename F into H; rename G into F; rename H into G.\n  rename HmonoF into HmonoH; rename HmonoG into HmonoF; rename HmonoH into HmonoG.\n  so (lt_ord_impl_le_ord _ _ Hlt) as Hvw; clear Hlt.\n  assert (forall X,\n            extend_urel v w (den (F (extend_urel w v X)))\n            =\n            den (G (blur v w X))) as Heq.\n    {\n    intro X.\n    rewrite <- (den_extend_iurel _ _ Hvw).\n    f_equal.\n    so (Hact (extend_urel w v X) hv) as Hint.\n    fold (exttin v (extend_urel w v X) hv) in Hint.\n    exploit (IH (blur v w X) hw (extend_iurel (lt_ord_impl_le_ord _ _ hv) (F (extend_urel w v X)))) as Heq.\n      {\n      fold (exttin w (blur v w X) hw).\n      eapply raise_robust; eauto.\n      rewrite -> (extend_urel_compose_up v w stop); auto.\n      }\n    replace (lt_ord_impl_le_ord _ _ hv) with (le_ord_trans _#3 Hvw (lt_ord_impl_le_ord _ _ hw)) in Heq.\n    2:{\n      apply proof_irrelevance.\n      }\n    rewrite -> extend_iurel_compose in Heq.\n    symmetry.\n    exact (extend_iurel_inj _#5 Heq).\n    }\n  rewrite -> (extend_urel_compose_up v w stop); auto.\n  do 2 f_equal.\n  rewrite -> extend_mu; auto.\n  symmetry.\n  transitivity (mu_urel w (fun X => den (G (blur v w X)))).\n    {\n    f_equal.\n    fextensionality 1.\n    auto.\n    }\n  apply (blur_vanish _ _ (fun X => den (G X))); auto.\n  intro X.\n  rewrite <- !Heq.\n  unfold blur.\n  rewrite <- (extend_urel_compose_up v w); auto.\n  rewrite -> extend_urel_id; auto.\n  }\n}\n\n(* univ *)\n{\nintros pg s i m gpg Hm _ _ X HX.\ninvertc HX.\nintros gpg' Hm' _ _ <-.\nso (pginterp_fun _#3 Hm Hm'); subst gpg'.\nreflexivity.\n}\n\n(* kuniv *)\n{\nintros pg s i m gpg h Hm _ X HX.\ninvertc HX.\nintros gpg' h' Hm' _ <-.\nso (pginterp_fun _#3 Hm Hm'); subst gpg'.\nso (proof_irrelevance _ h h'); subst h'.\nreflexivity.\n}\n\n(* kbasic *)\n{\nintros pg s i k l K _ Hsteps Hl IH X HX.\ninvertc HX.\nintros l' _ Hsteps' Hl'.\nso (determinism_eval _#4 (conj Hsteps (kbasicv_value _#6 Hl)) (conj Hsteps' (kbasicv_value _#6 Hl'))).\nsubst l'.\napply IH; auto.\n}\n\n(* cbasic *)\n{\nintros pg s i c d Q _ Hsteps Hd IH Q' H.\ninvertc H.\nintros d' _ Hsteps' Hd'.\nso (determinism_eval _#4 (conj Hsteps (cbasicv_value _#6 Hd)) (conj Hsteps' (cbasicv_value _#6 Hd'))).\nsubst d'.\napply IH; auto.\n}\n\n(* basic *)\n{\nintros pg s i c d R _ Hsteps Hd IH R' H.\ninvertc H.\nintros d' _ Hsteps' Hd'.\nso (determinism_eval _#4 (conj Hsteps (basicv_value _#6 Hd)) (conj Hsteps' (basicv_value _#6 Hd'))).\nsubst d'.\neapply IH; eauto.\n}\n\n(* functional *)\n{\nintros pg s i A b B _ Hcoarse Hb IH B' H.\nrevert B Hcoarse Hb IH.\ncases H.\nintros pg s i A b B' _ _ Hb' B Hcoarse Hb IH.\napply nearrow_extensionality.\nintros C.\nso (urelsp_eta _ A C) as (j & m & p & Hmp & ->).\ndestruct (transport Hcoarse (fun R => rel R j m p) Hmp) as (Hj & _).\napply IH; auto.\n  {\n  omega.\n  }\napply Hb'.\nomega.\n}\n\n(* wrapup *)\n{\ndo 6 (destruct Hind as (? & Hind)).\ndo2 3 split; intros; eauto.\n}\nQed.\n\n\nLemma kbasic_fun :\n  forall pg s i k K K',\n    kbasic system pg s i k K\n    -> kbasic system pg s i k K'\n    -> K = K'.\nProof.\nexact (semantics_fun andel).\nQed.\n\n\nLemma cbasic_fun :\n  forall pg s i a Q Q',\n    cbasic system pg s i a Q\n    -> cbasic system pg s i a Q'\n    -> Q = Q'.\nProof.\nexact (semantics_fun anderl).\nQed.\n\n\nLemma basic_fun :\n  forall pg s i a R R',\n    basic system pg s i a R\n    -> basic system pg s i a R'\n    -> R = R'.\nProof.\nexact (semantics_fun anderrl).\nQed.\n\n\nLemma functional_fun :\n  forall pg s i A b B B',\n    functional system pg s i A b B\n    -> functional system pg s i A b B'\n    -> B = B'.\nProof.\nexact (semantics_fun anderrr).\nQed.\n\n\nEnd semantics.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ProperFun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.19579652167359407}}
{"text": "(* \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     ChMaps\n     Messages\n     MessageEq\n     Keys\n     AdversaryUniverse\n.\n\nFrom SPICY Require\n     IdealWorld\n     RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       .\n\nSet Implicit Arguments.\n\n\nSection IdealDefiniions.\n\n  Import IdealWorld.\n\n  Definition istepSilent {A} (U1 U2 : universe A) :=\n    lstep_universe U1 Silent U2.\n\n  Inductive indexedIdealStep {A} (uid : user_id) (lbl : label) (U1 U2 : universe A) : Prop :=\n  | IndexedIdealStep : forall u proto chans prms,\n      U1.(users) $? uid = Some u\n      -> lstep_user uid lbl (U1.(channel_vector), u.(protocol), u.(perms)) (chans, proto, prms)\n      -> U2 = construct_universe\n               chans\n               (U1.(users) $+ (uid, {| protocol := proto ; perms := prms |}))\n      -> indexedIdealStep uid lbl U1 U2.\n\n  Lemma indexedIdealStep_ideal_step :\n    forall A uid lbl U1 U2,\n      @indexedIdealStep A uid lbl U1 U2\n      -> lstep_universe U1 lbl U2.\n  Proof. intros * IND; invert IND; econstructor; eauto. Qed.\n\nEnd IdealDefiniions.\n\nSection RealDefinitions.\n  Import RealWorld.\n\n  Inductive indexedRealStep {A B} (uid : user_id) (lbl : label) (U1 U2 : universe A B) : Prop :=\n  | IndexedRealStep : forall userData usrs adv cs gks ks qmsgs mycs froms sents cur_n (cmd : user_cmd (Base A)),\n      U1.(users) $? uid = Some userData\n      -> step_user lbl (Some uid)\n                  (build_data_step U1 userData)\n                  (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> U2 = 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      -> indexedRealStep uid lbl U1 U2.\n\n  Lemma indexedRealStep_real_step :\n    forall A B uid lbl U1 U2,\n      @indexedRealStep A B uid lbl U1 U2\n      -> step_universe (Some uid) U1 (mkULbl lbl uid) U2.\n  Proof. intros * IND; invert IND; econstructor; eauto. Qed.\n\nEnd RealDefinitions.\n\nInductive chan_key : Set :=\n| Public (ch_id : IdealWorld.channel_id)\n| Auth (ch_id : IdealWorld.channel_id): forall k,\n    k.(keyUsage) = Signing -> chan_key\n| Enc  (ch_id : IdealWorld.channel_id) : forall k,\n    k.(keyUsage) = Encryption -> chan_key\n| AuthEnc (ch_id : IdealWorld.channel_id) : forall k1 k2,\n      k1.(keyUsage) = Signing\n    -> k2.(keyUsage) = Encryption\n    -> chan_key\n.\n\nInductive action_matches (cs : RealWorld.ciphers) (gks : keys) :\n  RealWorld.uaction -> IdealWorld.action -> Prop :=\n\n| InpSig : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid uid seq froms p cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigCipher kid uid seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (uid, RealWorld.Input m__rw p froms) (IdealWorld.Input m__iw uid ch_id chans ps)\n| InpEnc : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid1 kid2 uid seq froms p cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigEncCipher kid1 kid2 uid seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (uid, RealWorld.Input m__rw p froms) (IdealWorld.Input m__iw uid ch_id chans ps)\n| OutSig : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid seq to from sents cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigCipher kid to seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (from, RealWorld.Output m__rw (Some from) (Some to) sents) (IdealWorld.Output m__iw from ch_id chans ps)\n| OutEnc : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid1 kid2 seq to from sents cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigEncCipher kid1 kid2 to seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (from, RealWorld.Output m__rw (Some from) (Some to) sents) (IdealWorld.Output m__iw from ch_id chans ps)\n.\n\nSection RealWorldUniverseProperties.\n  Import RealWorld.\n\n  Variable honestk : key_perms.\n  \n  Definition permission_heap_honest (perms : key_perms) :=\n    forall k_id p,\n     perms $? k_id = Some p\n      -> honestk $? k_id = Some true.\n\n  Definition permission_heap_good (ks : keys) (perms : key_perms) :=\n    forall k_id p,\n      perms $? k_id = Some p\n      -> exists k, ks $? k_id = Some k.\n\n  (* Syntactic Predicates *)\n  Definition keys_and_permissions_good {A} (ks : keys) (usrs : honest_users A) (adv_heap : key_perms): Prop :=\n    (forall k_id k,\n          ks $? k_id = Some k\n        -> keyId k = k_id)\n    /\\ Forall_natmap (fun u => permission_heap_good ks u.(key_heap)) usrs\n    /\\ permission_heap_good ks adv_heap.\n\n  Definition user_cipher_queue_ok (cs : ciphers) (honestk : key_perms) :=\n    Forall (fun cid => exists c, cs $? cid = Some c\n                       /\\ cipher_honestly_signed honestk c = true).\n\n  Definition user_cipher_queues_ok {A} (cs : ciphers) (honestk : key_perms) (usrs : honest_users A) :=\n    Forall_natmap\n      (fun u => user_cipher_queue_ok cs honestk u.(c_heap)) usrs.\n\n  Definition adv_cipher_queue_ok {A} (cs : ciphers) (usrs : honest_users A) :=\n    Forall (fun cid => exists new_cipher,\n                cs $? cid = Some new_cipher\n                /\\ ( cipher_honestly_signed (findUserKeys usrs) new_cipher = false\n                  \\/ ( cipher_honestly_signed (findUserKeys usrs) new_cipher = true\n                    /\\ exists u_id u rec_u,\n                      fst (cipher_nonce new_cipher) = Some u_id\n                      /\\ usrs $? u_id = Some u\n                      /\\ u_id <> cipher_to_user new_cipher\n                      /\\ List.In (cipher_nonce new_cipher) u.(sent_nons)\n                      /\\ usrs $? cipher_to_user new_cipher = Some rec_u\n                      /\\ ( List.In (cipher_nonce new_cipher) rec_u.(from_nons)\n                        \\/ Exists (fun sigM => match sigM with\n                                           | existT _ _ m =>\n                                             msg_signed_addressed (findUserKeys usrs) cs (Some (cipher_to_user new_cipher)) m = true\n                                           /\\ msg_nonce_same new_cipher cs m\n                                           end) rec_u.(msg_heap))))\n           ).\n\n  Inductive encrypted_cipher_ok (cs : ciphers) (gks : keys): cipher -> Prop :=\n  | SigCipherHonestOk : forall {t} (msg : message t) msg_to nonce k kt,\n      honestk $? k = Some true\n      -> gks $? k = Some {| keyId := k; keyUsage := Signing; keyType := kt |}\n      (* only send honest public keys *)\n      -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true /\\ kp = false)\n      -> encrypted_cipher_ok cs gks (SigCipher k msg_to nonce msg)\n  | SigCipherNotHonestOk : forall {t} (msg : message t) msg_to nonce k kt,\n      honestk $? k <> Some true\n      -> gks $? k = Some {| keyId := k; keyUsage := Signing; keyType := kt |}\n      -> encrypted_cipher_ok cs gks (SigCipher k msg_to nonce msg)\n  | SigEncCipherAdvSignedOk :  forall {t} (msg : message t) msg_to nonce k__s k__e kt__s kt__e,\n      honestk $? k__s <> Some true\n      -> gks $? k__s = Some {| keyId := k__s; keyUsage := Signing; keyType := kt__s |}\n      -> gks $? k__e = Some {| keyId := k__e; keyUsage := Encryption; keyType := kt__e |}\n      -> (forall k kp, findKeysMessage msg $? k = Some kp\n                 -> exists v, gks $? k = Some v\n                      /\\ (kp = true -> honestk $? k <> Some true))\n      -> encrypted_cipher_ok cs gks (SigEncCipher k__s k__e msg_to nonce msg)\n  | SigEncCipherHonestSignedEncKeyHonestOk : forall {t} (msg : message t) msg_to nonce k__s k__e kt__s kt__e,\n      honestk $? k__s = Some true\n      -> honestk $? k__e = Some true\n      -> gks $? k__s = Some {| keyId := k__s; keyUsage := Signing; keyType := kt__s |}\n      -> gks $? k__e = Some {| keyId := k__e; keyUsage := Encryption; keyType := kt__e |}\n      (* only send honest keys *)\n      -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true)\n      -> encrypted_cipher_ok cs gks (SigEncCipher k__s k__e msg_to nonce msg).\n\n  Definition encrypted_ciphers_ok (cs : ciphers) (gks : keys) :=\n    Forall_natmap (encrypted_cipher_ok cs gks) cs.\n\n  Definition message_no_adv_private {t} (cs : ciphers) (msg : crypto t) :=\n    forall k p, findKeysCrypto cs msg $? k = Some p -> honestk $? k = Some true /\\ p = false.\n\n  Definition adv_message_queue_ok {A} (usrs : honest_users A)\n             (cs : ciphers) (gks : keys) (msgs : queued_messages) :=\n    Forall (fun sigm => match sigm with\n                     | (existT _ _ m) =>\n                       (forall cid, msg_cipher_id m = Some cid -> cs $? cid <> None)\n                     /\\ (forall k kp,\n                           findKeysCrypto cs m $? k = Some kp\n                           -> gks $? k <> None /\\ (kp = true -> (findUserKeys usrs) $? k <> Some true))\n                     /\\ (forall k,\n                           msg_signing_key cs m = Some k\n                           -> gks $? k <> None)\n                     /\\ (forall c_id, List.In c_id (findCiphers m)\n                                -> exists c, cs $? c_id = Some c\n                                     /\\ ( cipher_honestly_signed (findUserKeys usrs) c = false\n                                       \\/ ( cipher_honestly_signed (findUserKeys usrs) c = true\n                                         /\\ exists uid u rec_u,\n                                           fst (cipher_nonce c) = Some uid\n                                           /\\ usrs $? uid = Some u\n                                           /\\ uid <> cipher_to_user c\n                                           /\\ List.In (cipher_nonce c) u.(sent_nons)\n                                           /\\ usrs $? cipher_to_user c = Some rec_u\n                                           /\\ ( List.In (cipher_nonce c) rec_u.(from_nons)\n                                             \\/ Exists (fun sigM =>\n                                                         match sigM with\n                                                         | existT _ _ m =>\n                                                           msg_signed_addressed (findUserKeys usrs) cs (Some (cipher_to_user c)) m = true\n                                                           /\\ msg_nonce_same c cs m\n                                                         end) rec_u.(msg_heap)))))\n                     end\n           ) msgs.\n\n  Definition message_queue_ok (cs : ciphers) (msgs : queued_messages) (gks : keys) :=\n    Forall (fun sigm => match sigm with\n                     | (existT _ _ m) =>\n                       (forall k kp, findKeysCrypto cs m $? k = Some kp -> gks $? k <> None)\n                     /\\ (forall cid,\n                           msg_cipher_id m = Some cid\n                           -> cs $? cid <> None)\n                     /\\ (forall k,\n                           msg_signing_key cs m = Some k\n                           -> gks $? k <> None\n                           /\\ ( honest_key honestk k\n                             -> message_no_adv_private cs m)\n                       )\n                     end) msgs.\n\n  Definition adv_no_honest_keys (advk : key_perms) : Prop :=\n    forall k_id,\n      (  honestk $? k_id = None\n      \\/  honestk $? k_id = Some false\n      \\/ (honestk $? k_id = Some true /\\ advk $? k_id <> Some true)\n      ).\n\n  Definition honest_users_only_honest_keys {A} (usrs : honest_users A) :=\n    forall u_id u,\n      usrs $? u_id = Some u\n      -> forall k_id kp,\n        u.(key_heap) $? k_id = Some kp\n        -> findUserKeys usrs $? k_id = Some true.\n\n  Definition honest_nonce_tracking_ok (cs : ciphers) (honestk : key_perms)\n             (me : option user_id) (my_sents : sent_nonces) (my_cur_n : nat)\n             (to_usr : user_id) (to_froms : recv_nonces) (to_msgs : queued_messages) :=\n\n      (* Forall (fun non => snd non < my_cur_n) my_sents *)\n      Forall (fun non => fst non = me -> snd non < my_cur_n) to_froms\n    /\\ Forall (fun '(existT _ _ msg) => \n                forall c_id c,\n                  msg = SignedCiphertext c_id\n                  -> cs $? c_id = Some c\n                  -> honestk $? (cipher_signing_key c) = Some true\n                  -> cipher_to_user c = to_usr\n                  -> fst (cipher_nonce c) = me\n                  -> snd (cipher_nonce c) < my_cur_n\n             ) to_msgs\n    /\\ forall c_id c,\n        cs $? c_id = Some c\n      -> honestk $? (cipher_signing_key c) = Some true\n      -> fst (cipher_nonce c) = me (* if cipher created by me *) \n      (* -> snd (cipher_nonce c) < my_cur_n *)\n      -> cipher_to_user c = to_usr\n      -> ~ List.In (cipher_nonce c) my_sents (* and hasn't yet been sent *)\n      -> ~ List.In (cipher_nonce c) to_froms (* then it hasn't been read by destination user *)\n        /\\ Forall (fun '(existT _ _ msg) => (* and isn't in destination user's message queue *)\n                    msg_honestly_signed  honestk cs msg = true\n                    -> msg_to_this_user cs (Some to_usr) msg = false\n                      \\/ msg_nonce_not_same c cs msg) to_msgs.\n\n  Definition honest_user_nonces_ok (cs : ciphers) (honestk : key_perms)\n             (me : option user_id) (my_sents : sent_nonces) (my_cur_n : nat) :=\n    (forall c_id c,\n      cs $? c_id = Some c\n      -> honestk $? (cipher_signing_key c) = Some true\n      -> fst (cipher_nonce c) = me (* if cipher created by me *) \n      -> snd (cipher_nonce c) < my_cur_n)\n  /\\ Forall (fun non => snd non < my_cur_n) my_sents\n  .\n\n  Definition honest_nonces_unique (cs : ciphers) (honestk : key_perms) :=\n    (forall cid1 cid2 c1 c2,\n        cid1 <> cid2\n        -> cs $? cid1 = Some c1\n        -> cs $? cid2 = Some c2\n        -> honestk $? (cipher_signing_key c1) = Some true\n        -> honestk $? (cipher_signing_key c2) = Some true\n        -> cipher_nonce c1 <> cipher_nonce c2).\n  \n  Definition action_adversary_safe (honestk : key_perms) (cs : ciphers) (a : action) : Prop :=\n    match a with\n    | Input  msg pat froms    => msg_pattern_safe honestk pat\n                              /\\ exists c_id c, msg = SignedCiphertext c_id\n                                        /\\ cs $? c_id = Some c\n                                        /\\ ~ List.In (cipher_nonce c) froms\n    | Output msg msg_from msg_to sents => msg_honestly_signed honestk cs msg = true\n                                       /\\ msg_to_this_user cs msg_to msg = true\n                                       /\\ exists c_id c, msg = SignedCiphertext c_id\n                                                 /\\ cs $? c_id = Some c\n                                                 /\\ fst (cipher_nonce c) = msg_from  (* only send my messages *)\n                                                 /\\ ~ List.In (cipher_nonce c) sents\n    end.\n\nEnd RealWorldUniverseProperties.\n\nSection SafeActions.\n  Import RealWorld.\n  \n  Inductive nextAction : forall {A B}, user_cmd A -> user_cmd B -> Prop :=\n  | NaReturn : forall A (a : << A >>),\n      nextAction (Return a) (Return a)\n  | NaGen :\n      nextAction Gen Gen\n  | NaSend : forall t uid (msg : crypto t),\n      nextAction (Send uid msg) (Send uid msg)\n  | NaRecv : forall t pat,\n      nextAction (@Recv t pat) (@Recv t pat)\n  | NaSignEncrypt : forall t k__s k__e u_id (msg : message t),\n      nextAction (SignEncrypt k__s k__e u_id msg) (SignEncrypt k__s k__e u_id msg)\n  | NaDecrypt : forall t (msg : crypto t),\n      nextAction (Decrypt msg) (Decrypt msg)\n  | NaSign : forall t k u_id (msg : message t),\n      nextAction (Sign k u_id msg) (Sign k u_id msg)\n  | NaVerify : forall t k (msg : crypto t),\n      nextAction (Verify k msg) (Verify k msg)\n  | NaGenKey : forall kt usg,\n      nextAction (GenerateKey kt usg) (GenerateKey kt usg)\n  | NaBind : forall A B r (c : user_cmd B) (c1 : user_cmd r) (c2 : << r >> -> user_cmd A),\n      nextAction c1 c\n      -> nextAction (Bind c1 c2) c\n  .\n\n  Lemma nextAction_couldBe :\n    forall {A B} (c1 : user_cmd A) (c2 : user_cmd B),\n      nextAction c1 c2\n      -> match c2 with\n        | Return _ => True\n        | Gen => True\n        | Send _ _ => True\n        | Recv _ => True\n        | SignEncrypt _ _ _ _ => True\n        | Decrypt _ => True\n        | Sign _ _ _ => True\n        | Verify _ _ => True\n        | GenerateKey _ _ => True\n        (* | GenerateAsymKey _ => True *)\n        (* | GenerateSymKey _ => True *)\n        | Bind _ _ => False\n        end.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Definition next_cmd_safe (honestk : key_perms) (cs : ciphers) (u_id : user_id)\n             (froms : recv_nonces) (sents : sent_nonces) {A} (cmd : user_cmd A) :=\n    forall B (cmd__n : user_cmd B),\n      nextAction cmd cmd__n\n      -> match cmd__n with\n        | Return _ => True\n        | Gen => True\n        | Send msg_to msg =>\n          msg_honestly_signed honestk cs msg = true\n          /\\ msg_to_this_user cs (Some msg_to) msg = true\n          /\\ (exists c_id c, msg = SignedCiphertext c_id\n                       /\\ cs $? c_id = Some c\n                       /\\ fst (cipher_nonce c) = (Some u_id)  (* only send my messages *)\n                       /\\ ~ List.In (cipher_nonce c) sents)\n        | Recv pat =>\n          msg_pattern_safe honestk pat\n        | SignEncrypt k__sign k__enc msg_to msg =>\n          honestk $? k__enc = Some true\n          /\\ (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true)\n        | Decrypt _ => True\n        | Sign _ _ msg =>\n          (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true /\\ kp = false)\n        | Verify _ _ => True\n        | GenerateKey _ _ => True\n        | Bind _ _ => False\n        end.\n\n  Definition honest_cmds_safe {A B} (U : universe A B) : Prop :=\n    forall u_id u honestk,\n      honestk = findUserKeys U.(users)\n      -> U.(users) $? u_id = Some u\n      (* -> forall lbl bd, step_user lbl (Some u_id) (build_data_step U u) bd *)\n      -> next_cmd_safe (findUserKeys U.(users)) U.(all_ciphers) u_id u.(from_nons) u.(sent_nons) u.(protocol).\n\n  Definition label_safe (honestk : key_perms) (cs : ciphers) (lbl : label) : Prop :=\n    match lbl with\n    | Silent   => True\n    | Action a => action_adversary_safe honestk cs a\n    end.\n\nEnd SafeActions.\n\nSection FinalValue.\n\n    Inductive final_value : Set :=\n    | FAccess\n    | FBool (b : bool)\n    | FNat (n : nat)\n    | FUnit\n    | FPair (fv1 fv2 : final_value).\n\n    Section IdealFV.\n      Import IdealWorld.\n      Import IdealWorld.IdealNotations.\n\n      Fixpoint Iret_val_to_val { t : type } :\n        forall (rv : << Base t >>), final_value :=\n        match t with\n        | Nat => (fun n => FNat n)\n        | Bool => (fun b => FBool b)\n        | Unit => (fun _ => FUnit)\n        | Access => (fun _ => FAccess)\n        | TPair t1 t2 => (fun '(f, s) => FPair (Iret_val_to_val f) (Iret_val_to_val s))\n        end.\n      \n    End IdealFV.\n\n    Section RealFV.\n      Import RealWorld.\n      Import RealWorld.RealWorldNotations.\n\n      Fixpoint Rret_val_to_val { t : type } :\n        forall (rv : << Base t >>), final_value :=\n        match t with\n        | Nat => (fun n => FNat n)\n        | Bool => (fun b => FBool b)\n        | Unit => (fun _ => FUnit)\n        | Access => (fun _ => FAccess)\n        | TPair t1 t2 => (fun '(f, s) => FPair (Rret_val_to_val f) (Rret_val_to_val s))\n        end.\n      \n    End RealFV.\n    \nEnd FinalValue.\n\nDefinition message_queues_ok {A} (cs : RealWorld.ciphers) (usrs : RealWorld.honest_users A) (gks : keys) :=\n  Forall_natmap (fun u => message_queue_ok (RealWorld.findUserKeys usrs) cs u.(RealWorld.msg_heap) gks) usrs.\n\nDefinition honest_nonces_ok {A} (cs : RealWorld.ciphers) (usrs : RealWorld.honest_users A) :=\n    honest_nonces_unique cs (RealWorld.findUserKeys usrs)\n  /\\ ( forall uid u,\n        usrs $? uid = Some u\n        -> honest_user_nonces_ok cs (RealWorld.findUserKeys usrs) (Some uid)\n                                u.(RealWorld.sent_nons)\n                                u.(RealWorld.cur_nonce) )\n  /\\ (forall u_id u rec_u_id rec_u,\n        u_id <> rec_u_id\n        -> usrs $? u_id = Some u\n        -> usrs $? rec_u_id = Some rec_u\n        -> honest_nonce_tracking_ok cs (RealWorld.findUserKeys usrs)\n                                   (Some u_id)\n                                   u.(RealWorld.sent_nons)\n                                   u.(RealWorld.cur_nonce)\n                                   rec_u_id rec_u.(RealWorld.from_nons)\n                                   rec_u.(RealWorld.msg_heap)).\n\nDefinition universe_ok {A B} (U : RealWorld.universe A B) : Prop :=\n  let honestk := RealWorld.findUserKeys U.(RealWorld.users)\n  in  encrypted_ciphers_ok honestk U.(RealWorld.all_ciphers) U.(RealWorld.all_keys)\n    /\\ keys_and_permissions_good U.(RealWorld.all_keys) U.(RealWorld.users) U.(RealWorld.adversary).(RealWorld.key_heap)\n    /\\ user_cipher_queues_ok U.(RealWorld.all_ciphers) honestk U.(RealWorld.users)\n    /\\ message_queues_ok U.(RealWorld.all_ciphers) U.(RealWorld.users) U.(RealWorld.all_keys)\n    /\\ adv_cipher_queue_ok U.(RealWorld.all_ciphers) U.(RealWorld.users) U.(RealWorld.adversary).(RealWorld.c_heap)\n    /\\ adv_message_queue_ok U.(RealWorld.users) U.(RealWorld.all_ciphers) U.(RealWorld.all_keys) U.(RealWorld.adversary).(RealWorld.msg_heap)\n    /\\ adv_no_honest_keys honestk U.(RealWorld.adversary).(RealWorld.key_heap)\n    /\\ honest_nonces_ok U.(RealWorld.all_ciphers) U.(RealWorld.users)\n    /\\ honest_users_only_honest_keys U.(RealWorld.users).\n\nSection Simulation.\n  Variable A B : type.\n  Variable advP : RealWorld.user_data B -> Prop.\n  Variable R : RealWorld.simpl_universe A -> IdealWorld.universe A -> Prop.\n\n  Definition simulates_silent_step :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n    -> universe_ok U__r\n    -> advP U__r.(RealWorld.adversary)\n    -> forall suid U__r',\n        RealWorld.step_universe suid U__r Silent U__r'\n        -> exists U__i',\n          istepSilent ^* U__i U__i'\n        /\\ R (RealWorld.peel_adv U__r') U__i'.\n\n  Definition simulates_labeled_step :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n    -> universe_ok U__r\n    -> advP U__r.(RealWorld.adversary)\n    -> forall uid U__r' ra,\n        indexedRealStep uid (Action ra) U__r U__r'\n        -> exists ia U__i' U__i'',\n            (indexedIdealStep uid Silent) ^* U__i U__i'\n            /\\ indexedIdealStep uid (Action ia) U__i' U__i''\n            /\\ action_matches U__r.(RealWorld.all_ciphers) U__r.(RealWorld.all_keys) (uid,ra) ia\n            /\\ R (RealWorld.peel_adv U__r') U__i''.\n\n  Definition honest_actions_safe :=\n    forall (U__r : RealWorld.universe A B) U__i,\n        R (RealWorld.peel_adv U__r) U__i\n      -> universe_ok U__r\n      -> honest_cmds_safe U__r.\n\n  Definition ri_final_actions_align :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n      -> universe_ok U__r\n      -> (forall uid lbl U__r', RealWorld.step_universe (Some uid) U__r lbl U__r' -> False)\n      -> forall uid ud__r r__r,\n          U__r.(RealWorld.users) $? uid = Some ud__r\n          -> ud__r.(RealWorld.protocol) = RealWorld.Return r__r\n          -> exists (U__i' : IdealWorld.universe A) ud__i r__i,\n              istepSilent ^* U__i U__i'\n              /\\ U__i'.(IdealWorld.users) $? uid = Some ud__i\n              /\\ ud__i.(IdealWorld.protocol) = IdealWorld.Return r__i\n              /\\ Rret_val_to_val r__r = Iret_val_to_val r__i.\n\n  Definition simulates (U__r : RealWorld.universe A B) (U__i : IdealWorld.universe A) :=\n\n    (* conditions for simulation steps *)\n    simulates_silent_step\n  /\\ simulates_labeled_step\n  /\\ honest_actions_safe\n  /\\ ri_final_actions_align\n\n  (* conditions for start *)\n  /\\ R (RealWorld.peel_adv U__r) U__i\n  /\\ universe_ok U__r\n  .\n\nEnd Simulation.\n\nSection IISimulation.\n  Import IdealWorld.\n  \n  Variable A : type.\n  Variable R : universe A -> universe A -> Prop.\n\n  Definition ii_final_labels_align (U__i U__is : universe A) :=\n    (forall lbl U__i', ~ lstep_universe U__i lbl U__i')\n    -> exists (U__is' U__is'' : universe A),\n      trc3 lstep_universe (fun _ => True) U__is U__is'\n      /\\ (forall lbl U__is'', ~ lstep_universe U__is' lbl U__is'')\n      /\\ forall uid ud__i r,\n          U__i.(users) $? uid = Some ud__i\n          -> ud__i.(protocol) = Return r\n          -> exists ud__is,\n            U__is'.(users) $? uid = Some ud__is\n          /\\ ud__is.(protocol) = Return r.\n\n  Definition ii_step :=\n    forall (U__i : universe A) U__is,\n      R U__i U__is\n      -> forall lbl U__i',\n        lstep_universe U__i lbl U__i'\n        -> exists U__is',\n          trc3 lstep_universe (fun _ => True) U__is U__is'\n          /\\ ii_final_labels_align U__i' U__is'\n          /\\ R U__i' U__is'.\n\n  Definition ii_simulates (U__i U__is : universe A) :=\n    ii_step\n    /\\ R U__i U__is.\n\nEnd IISimulation.\n\nDefinition refines {A B} (advP : RealWorld.user_data B -> Prop) (U1 : RealWorld.universe A B) (U2 : IdealWorld.universe A) :=\n  exists R, simulates advP R U1 U2.\n\nNotation \"u1 <| u2 \\ p \" := (refines p u1 u2) (no associativity, at level 70).\n\nDefinition lameAdv {B} (b : RealWorld.denote (RealWorld.Base B)) :=\n  fun adv => adv.(RealWorld.protocol) = @RealWorld.Return (RealWorld.Base B) b.\n\nDefinition awesomeAdv : forall B, RealWorld.user_data B -> Prop :=\n  fun _ _ => True.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/src/Simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.19576868086728358}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\nRequire Import Crypto.CLI.\nRequire Export Crypto.StandaloneHaskellMain.\nRequire Import Crypto.Bedrock.Field.Stringification.Stringification.\nImport ListNotations.\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\n\n(** N.B. We put bedrock2 first so that the default for these binaries\n    is bedrock2 *)\nLocal Instance bedrock2_supported_languages : ForExtraction.supported_languagesT\n  := [(\"bedrock2\", OutputBedrock2API)]\n       ++ ForExtraction.default_supported_languages.\n\nModule UnsaturatedSolinas.\n  Definition main : IO_unit\n    := main_gen ForExtraction.UnsaturatedSolinas.PipelineMain.\nEnd UnsaturatedSolinas.\n\nModule WordByWordMontgomery.\n  Definition main : IO_unit\n    := main_gen ForExtraction.WordByWordMontgomery.PipelineMain.\nEnd WordByWordMontgomery.\n\nModule SaturatedSolinas.\n  Definition main : IO_unit\n    := main_gen ForExtraction.SaturatedSolinas.PipelineMain.\nEnd SaturatedSolinas.\n\nModule BaseConversion.\n  Definition main : IO_unit\n    := main_gen ForExtraction.BaseConversion.PipelineMain.\nEnd BaseConversion.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Bedrock/Standalone/StandaloneHaskellMain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.37387582974820255, "lm_q1q2_score": 0.19569421726566186}}
{"text": "Require Import Nat.\nRequire Import String.\nRequire Import List.\nRequire Import Coq.Init.Datatypes PArray.\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom LF Require Export lang_declassify.\n\nSet Implicit Arguments.\n\n(********************************************************)\n\n(* Syntax of language *)\n\n(********************************************************)\n\n(* Example 1 *)\n(* fn (length) {\n   if (inbound(length) { //attacker can pass any value of length which might not be in bound\n      x := a[length] ; //speculatively processor goes her...lead to access to unbound index (secret memory)\n      a[y] := x;  // loads data from secret memory \n      for (i = 0 ; i <= length; i++) { //based on conditional\n          a[i] := 0; // writes in secret memory\n      }\n   }\n*)\n(* During sequential execution, this is not a problem but it might be a problem in speculative execution *)\n(* One solution is to put fence after line 2 but the drawback of fence is they stop speculation of \n   all instructions, not only the instructions that might leak *)\n(* Another solution: protect ==> it only stops speculation along certain path, memory load is guarded by protect *)\n\n(* Example 2 *)\n(* x := a[i1]\n   y := a[i2]\n   z := x + y\n   w := b[z] *)\n\n(* Example 3: Use of protect : Protects all the public loads so that attacker doesn't use it to get the secret data *)\n(* x := a[i] // where a is public and i is always public \n   a[j] := x // storing the value x in the memory *)\n(* x := a[i]  x: Transient\n   x := protect(x) RHS: x: Transient LHS: x: Public\n   a[j] := x *)\n\n(* Instructions *)\nInductive instr : Type :=\n| Iempty : instr\n| Iassgn : var -> declassify -> expr -> instr (* assignemnt x := d e *)\n| Iload : var -> declassify -> arr_access -> instr (* x := d a[e] *)\n| Istore : arr_access -> declassify -> expr -> instr  (* a[e] := d e *) \n| Iif : bexpr -> seq instr -> seq instr -> instr (* conditional if b i i *)\n| Iprotect : var -> var -> instr (* we will protect the var which gets value from public load *).\n\nDefinition cmd := seq instr.\n\n(* State *)\nRecord state := State {\n  scmd : cmd;\n  rmap : regmap;\n  mmap  : mem;\n  ms : bool\n}.\n\n(* Semantic of expressions *)\nFixpoint sem_expr_spec (s:state) (e:expr) : value :=\n  match e with \n  | Evar x => (rmap s) x\n  | Ebop o e e' => eval_bop o (sem_expr_spec s e) (sem_expr_spec s e')\n  end.\n\n(* Directives *)\nInductive directive : Type :=\n| Dstep : directive \n| Dforce : bool -> directive\n| Dload : varr -> nat -> directive \n| Dstore : varr -> nat -> directive.\n\n(* Semantics of instructions with speculation *) \nInductive sem_instr_spec : state -> directive -> seq leakage -> state -> Prop :=\n| Iempty_sem_spec : forall s c,\n  s.(scmd) = Iempty :: c ->\n  sem_instr_spec s \n  Dstep \n  [::]\n  {| scmd := c; rmap := rmap s; mmap := mmap s; ms := ms s |}\n| Iassgn_sem_spec : forall s x d e c,\n  s.(scmd) = Iassgn x d e :: c ->  \n  sem_instr_spec s \n  Dstep \n  (if d then [:: Ldeclassify (Some (sem_expr_spec s e))] else [:: Lempty])\n  {| scmd := c; \n     rmap := update_rmap s.(rmap) x (sem_expr_spec s e);\n     mmap := s.(mmap); \n     ms := s.(ms) |}\n| Iif_sem_spec : forall s bop e1 e2 bf i1 i2 v1 v2 b' c,\n  s.(scmd) = Iif (Ebool bop e1 e2) i1 i2 :: c ->\n  sem_expr_spec s e1 = v1 ->\n  sem_expr_spec s e2 = v2 -> \n  eval_bool_op bop v1 v2 = b' ->\n  sem_instr_spec s \n  (Dforce bf) \n  [::(Lbool b')] \n  {| scmd := (if bf then i1 else i2) ++ c; \n     rmap := s.(rmap);\n     mmap := s.(mmap); \n     ms := if b' == bf then s.(ms) else true (*s.ms || b' != bf*)|}\n| Iload_sem_spec : forall s x d a e c,\n  s.(scmd) = Iload x d (AA a e) :: c ->\n  sem_instr_spec s \n  (Dload a (sem_expr_spec s e)) \n  (if d then [:: Lindex (sem_expr_spec s e);\n                 Ldeclassify (Some (Array.get (mmap s a) (sem_expr_spec s e)))]\n        else [:: Lindex (sem_expr_spec s e)])\n  {| scmd := c; \n     rmap := update_rmap s.(rmap) x (Array.get (s.(mmap) a) (sem_expr_spec s e));\n     mmap := s.(mmap);\n     ms := s.(ms) |}\n| Istore_sem_spec : forall s a e d e' c,\n  s.(scmd) = Istore (AA a e) d e' :: c ->\n  sem_instr_spec s (Dstore a (sem_expr_spec s e))\n  (if d then [:: Lindex (sem_expr_spec s e); Ldeclassify (Some (sem_expr_spec s e'))]\n        else [:: Lindex (sem_expr_spec s e)])\n  {| scmd := c; \n     rmap := s.(rmap);\n     mmap := update_mem s.(mmap) a (sem_expr_spec s e) (sem_expr_spec s e');\n     ms := s.(ms) |}\n| Iprotect_sem_spec : forall s x y c,\n  s.(scmd) = Iprotect x y :: c ->\n  sem_instr_spec s \n  Dstep \n  [:: Lempty] \n  {| scmd := c; \n     rmap := if s.(ms) then update_rmap s.(rmap) x 0 else update_rmap s.(rmap) x (s.(rmap) y);\n     mmap := s.(mmap);\n     ms := s.(ms) |}.\n\n\n(* Multi step for instructions with spec *)\nInductive multi_step_spec : state -> seq directive -> seq (seq leakage) -> nat -> state -> Prop :=\n| sem_empty_spec : forall s, multi_step_spec s nil nil 0 s\n| sem_seq_spec : forall s d l s' d' l' s'' n,\n  sem_instr_spec s d l s' ->\n  multi_step_spec s' d' l' n s'' ->\n  multi_step_spec s (d :: d') (l :: l') (n + 1) s''.\n\nDefinition final_state_spec (s:state) : bool :=\nmatch s.(scmd) with \n| [::] => true\n| _ => false\nend.\n\n\nDefinition safe_state (s:state) :=\nfinal_state_spec s = true \\/ exists d l s', sem_instr_spec s d l s'.\n\n", "meta": {"author": "swarnpriya", "repo": "simple_lang_sslh", "sha": "6d7172d1d61fe579d9045a9158d7aa1d46bbc1f8", "save_path": "github-repos/coq/swarnpriya-simple_lang_sslh", "path": "github-repos/coq/swarnpriya-simple_lang_sslh/simple_lang_sslh-6d7172d1d61fe579d9045a9158d7aa1d46bbc1f8/lang_spec_declassify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.19569421552133187}}
{"text": "Require Import DirName.\nRequire Import Balloc.\nRequire Import Prog.\nRequire Import BasicProg.\nRequire Import Bool.\nRequire Import Word.\nRequire Import BFile Bytes Rec Inode.\nRequire Import String.\nRequire Import FSLayout.\nRequire Import Pred PredCrash.\nRequire Import Arith.\nRequire Import GenSepN.\nRequire Import List ListUtils.\nRequire Import Hoare.\nRequire Import Log.\nRequire Import SepAuto.\nRequire Import Array.\nRequire Import FunctionalExtensionality.\nRequire Import AsyncDisk.\nRequire Import DiskSet.\nRequire Import SyncedMem.\nRequire Import GenSepAuto.\nRequire Import BFileCrash.\nRequire Import Omega.\nRequire Import DirTreeDef.\nRequire Import DirTreeRep.\nRequire Import DirTreePred.\nRequire Import DirTreeNames.\nRequire Import DirTreeInodes.\n\nImport ListNotations.\n\nModule SDIR := DirCache.CacheOneDir.\n\nSet Implicit Arguments.\n\nModule DTCrash.\n\n  Definition file_crash (f f' : dirfile) : Prop :=\n    exists c c',\n    BFILE.file_crash (BFILE.mk_bfile (DFData f) (DFAttr f) c)\n                     (BFILE.mk_bfile (DFData f') (DFAttr f') c').\n\n  Inductive tree_crash : dirtree -> dirtree -> Prop :=\n    | TCFile : forall inum f f',\n               file_crash f f' ->\n               tree_crash (TreeFile inum f) (TreeFile inum f')\n    | TCDir  : forall inum st st',\n               map fst st = map fst st' ->\n               Forall2 tree_crash (map snd st) (map snd st') ->\n               tree_crash (TreeDir inum st) (TreeDir inum st').\n\n  Theorem tree_crash_trans : forall t1 t2 t3,\n    tree_crash t1 t2 ->\n    tree_crash t2 t3 ->\n    tree_crash t1 t3.\n  Proof.\n    induction t1 using dirtree_ind2; simpl; intros.\n    inversion H; subst. inversion H0; subst. econstructor.\n      unfold file_crash in *. repeat deex. do 2 eexists. eapply file_crash_trans; eauto.\n    inversion H0; subst. inversion H1; subst. constructor. congruence.\n    generalize dependent st'. generalize dependent st'0.\n    induction tree_ents; simpl; intros.\n    - destruct st'; simpl in *; try congruence.\n    - destruct st'; destruct st'0; simpl in *; try congruence.\n      inversion H6. inversion H8. inversion H. inversion H4. inversion H5. subst; simpl in *.\n      constructor; eauto.\n      eapply IHtree_ents. eauto.\n      all: try match goal with | [ |- Forall2 _ _ _ ] => eauto end.\n      all: eauto.\n      constructor; eauto.\n      constructor; eauto.\n  Qed.\n\n  Lemma flist_crash_xform_dirlist_pred : forall tree_ents p,\n    Forall\n      (fun t => flist_crash_xform (p t) =p=> exists t', [[ tree_crash t t' ]] * p t')\n      (map snd tree_ents) ->\n    flist_crash_xform (dirlist_pred p tree_ents) =p=>\n      exists tree_ents',\n      [[ Forall2 tree_crash (map snd tree_ents) (map snd tree_ents') ]] *\n      [[ map fst tree_ents = map fst tree_ents' ]] *\n      dirlist_pred p tree_ents'.\n  Proof.\n    induction tree_ents; simpl; intros.\n    - rewrite flist_crash_xform_emp. cancel.\n      eassign (@nil (string * dirtree)); cancel.\n      constructor.\n      constructor.\n    - destruct a. rewrite flist_crash_xform_sep_star.\n      inversion H; subst.\n      rewrite H2.\n      rewrite IHtree_ents by eauto.\n      cancel.\n      eassign ((s, t') :: tree_ents').\n      cancel.\n      constructor; eauto.\n      simpl; congruence.\n  Qed.\n\n  Lemma tree_dir_names_pred'_unchanged : forall tree_ents tree_ents',\n    map fst tree_ents = map fst tree_ents' ->\n    map (fun e => dirtree_inum e) (map snd tree_ents) = map (fun e => dirtree_inum e) (map snd tree_ents') ->\n    map (fun e => dirtree_isdir e) (map snd tree_ents) = map (fun e => dirtree_isdir e) (map snd tree_ents') ->\n    tree_dir_names_pred' tree_ents =p=> tree_dir_names_pred' tree_ents'.\n  Proof.\n    induction tree_ents; intros; destruct tree_ents'; simpl in *; try congruence.\n    destruct a; destruct p; simpl in *.\n    inversion H; clear H.\n    inversion H0; clear H0.\n    inversion H1; clear H1.\n    subst.\n    rewrite IHtree_ents; eauto.\n  Qed.\n\n  Lemma flist_crash_xform_tree_dir_names_pred : forall tree_ents tree_ents' xp inum,\n    map fst tree_ents = map fst tree_ents' ->\n    map (fun e => dirtree_inum e) (map snd tree_ents) = map (fun e => dirtree_inum e) (map snd tree_ents') ->\n    map (fun e => dirtree_isdir e) (map snd tree_ents) = map (fun e => dirtree_isdir e) (map snd tree_ents') ->\n    flist_crash_xform (tree_dir_names_pred xp inum tree_ents) =p=>\n      tree_dir_names_pred xp inum tree_ents'.\n  Proof.\n    unfold tree_dir_names_pred; intros.\n    rewrite flist_crash_xform_exists. norml; unfold stars; simpl.\n    rewrite flist_crash_xform_exists. norml; unfold stars; simpl.\n    repeat rewrite flist_crash_xform_sep_star.\n    repeat rewrite flist_crash_xform_lift_empty.\n    rewrite flist_crash_xform_ptsto.\n    cancel.\n    eapply SDIR.crash_rep; eauto.\n    pred_apply.\n    apply tree_dir_names_pred'_unchanged; eauto.\n  Qed.\n\n  Lemma tree_crash_preserves_dirtree_inum : forall t t',\n    tree_crash t t' ->\n    dirtree_inum t = dirtree_inum t'.\n  Proof.\n    inversion 1; auto.\n  Qed.\n\n  Lemma tree_crash_preserves_dirtree_isdir : forall t t',\n    tree_crash t t' ->\n    dirtree_isdir t = dirtree_isdir t'.\n  Proof.\n    inversion 1; auto.\n  Qed.\n\n  Lemma flist_crash_xform_tree_pred : forall xp t,\n    flist_crash_xform (tree_pred xp t) =p=> exists t', [[ tree_crash t t' ]] * tree_pred xp t'.\n  Proof.\n    induction t using dirtree_ind2; simpl; intros.\n    - rewrite flist_crash_xform_exists.\n      setoid_rewrite flist_crash_xform_sep_star.\n      setoid_rewrite flist_crash_xform_ptsto.\n      setoid_rewrite flist_crash_xform_lift_empty.\n      norml. destruct f'. cancel.\n      instantiate (t' := TreeFile inum (mk_dirfile _ _)). cbn. cancel.\n      econstructor; eauto.\n      unfold file_crash. do 2 eexists. eauto.\n    - rewrite flist_crash_xform_sep_star.\n      rewrite flist_crash_xform_dirlist_pred by eauto.\n      cancel.\n      eassign (TreeDir inum tree_ents').\n      cancel.\n      apply flist_crash_xform_tree_dir_names_pred; eauto.\n      eapply Forall2_to_map_eq. apply tree_crash_preserves_dirtree_inum. eauto.\n      eapply Forall2_to_map_eq. apply tree_crash_preserves_dirtree_isdir. eauto.\n      constructor; eauto.\n  Qed.\n\n  Lemma flist_crash_xform_freelist : forall (FP : BFILE.bfile -> Prop) xp frees freepred ms,\n    (forall f f', BFILE.file_crash f f' -> FP f -> FP f') ->\n    IAlloc.Alloc.rep FP xp frees freepred ms =p=>\n      IAlloc.Alloc.rep FP xp frees freepred ms *\n      [[ flist_crash_xform freepred =p=> freepred ]].\n  Proof.\n    unfold IAlloc.Alloc.rep, IAlloc.Alloc.Alloc.rep; intros.\n    cancel.\n    match goal with H: _ <=p=> _ |- _ => rewrite H end.\n    repeat match goal with\n      Hb: context [BFILE.file_crash],\n      Hother: _ |- _ => clear Hother\n    end.\n    induction frees; simpl.\n    rewrite flist_crash_xform_emp; auto.\n    rewrite flist_crash_xform_sep_star. rewrite flist_crash_xform_exists.\n    rewrite IHfrees.\n    norml; unfold stars; simpl.\n    rewrite flist_crash_xform_sep_star.\n    rewrite flist_crash_xform_lift_empty.\n    rewrite flist_crash_xform_ptsto. cancel. eauto.\n  Qed.\n\n  Lemma xform_tree_rep : forall xp F t ilist frees ms msll' sm,\n     crash_xform (rep xp F t ilist frees ms sm) =p=>\n     exists t',\n      [[ tree_crash t t' ]] * \n      rep xp (flist_crash_xform F) t' ilist frees (BFILE.ms_empty msll') sm_synced.\n  Proof.\n    unfold rep; intros.\n    xform_norm.\n    rewrite BFILE.xform_rep.\n    rewrite IAlloc.xform_rep.\n    rewrite flist_crash_xform_freelist.\n    norml; unfold stars; simpl.\n    eapply flist_crash_flist_crash_xform in H0; eauto.\n    apply flist_crash_xform_sep_star in H0. rewrite flist_crash_xform_sep_star in H0.\n    rewrite flist_crash_xform_tree_pred in H0.\n    destruct_lift H0.\n    unfold IAlloc.rep; cancel.\n    rewrite <- BFILE.rep_clear_freelist.\n    rewrite <- BFILE.rep_clear_icache.\n    rewrite <- IAlloc.rep_clear_cache.\n    cancel.\n    eauto.\n    pred_apply.\n    cancel; auto.\n    intros; eapply BFILE.freepred_file_crash; eauto.\n  Grab Existential Variables.\n    all: exact (LOG.mk_memstate0 (Cache.BUFCACHE.cache0 1)).\n  Qed.\n\n  Theorem tree_crash_find_name :\n    forall fnlist t t' subtree,\n    tree_crash t t' ->\n    find_subtree fnlist t = Some subtree ->\n    exists subtree',\n    find_subtree fnlist t' = Some subtree' /\\\n    tree_crash subtree subtree'.\n  Proof.\n    induction fnlist.\n    - simpl; intros.\n      eexists; intuition eauto.\n      inversion H0; subst; auto.\n    - intros.\n      inversion H0.\n      destruct t; try congruence.\n      inversion H; subst.\n      generalize dependent st'.\n      induction l; intros.\n      + simpl in *. congruence.\n      + destruct st'; try solve [ simpl in *; congruence ].\n        destruct p.\n        unfold find_subtree_helper in H2 at 1.\n        destruct a0.\n        simpl in H2.\n        destruct (string_dec s0 a).\n        * subst.\n          edestruct IHfnlist.\n          2: apply H2.\n          inversion H6; eauto.\n          eexists.\n          intuition eauto.\n          inversion H4; subst.\n          simpl; destruct (string_dec s s); try congruence.\n        * edestruct IHl.\n\n          eauto.\n          eauto.\n          all: try solve [ inversion H4; exact H5 ].\n          all: try solve [ inversion H6; eauto ].\n\n          constructor. inversion H4; eauto.\n          inversion H. inversion H8; eauto.\n\n          exists x. intuition.\n          simpl.\n          inversion H4; subst. destruct (string_dec s a); try congruence.\n          apply H3.\n  Qed.\n\n  Theorem tree_crash_find_none :\n    forall fnlist t t',\n    tree_crash t t' ->\n    find_subtree fnlist t = None ->\n    find_subtree fnlist t' = None.\n  Proof.\n    induction fnlist.\n    - simpl; intros.\n      congruence.\n    - intros.\n      inversion H0. rewrite H2.\n      destruct t; inversion H; subst.\n      eauto.\n\n      generalize dependent st'.\n      induction l; intros.\n      + destruct st'; simpl in *; try congruence.\n      + destruct st'; try solve [ simpl in *; congruence ].\n        destruct p.\n        unfold find_subtree_helper in H2 at 1.\n        destruct a0.\n        simpl in H2.\n        destruct (string_dec s0 a).\n        * subst.\n          edestruct IHfnlist.\n          2: apply H2.\n          inversion H6; eauto.\n          inversion H4; subst.\n          simpl; destruct (string_dec s s); try congruence.\n        * edestruct IHl.\n\n          eauto.\n          eauto.\n          all: try solve [ inversion H4; exact H5 ].\n          all: try solve [ inversion H6; eauto ].\n\n          constructor. inversion H4; eauto.\n          inversion H. inversion H8; eauto.\n\n          simpl.\n          inversion H4; subst. destruct (string_dec s a); try congruence.\n  Qed.\n\n  Lemma tree_crash_find_subtree_root: forall t t' inum,\n    tree_crash t t' ->\n    (exists elem, find_subtree [] t = Some (TreeDir inum elem)) ->\n    (exists elem', find_subtree [] t' = Some (TreeDir inum elem')).\n  Proof.\n    intros.\n    destruct t.\n    - destruct H0.\n      inversion H0.\n    - destruct H0.\n      unfold find_subtree in *. simpl in *.\n      destruct t'.\n      inversion H0.\n      inversion H0.\n      subst; simpl.\n      exfalso.\n      inversion H.\n      inversion H0.\n      subst; simpl.\n      inversion H.\n      subst; simpl; eauto.\n  Qed.\n\n  Lemma tree_crash_find_name_root: forall t t' inum,\n    tree_crash t t' ->\n    find_name [] t = Some (inum, true) ->\n    find_name [] t' = Some (inum, true).\n  Proof.\n    intros.\n    destruct t.\n    - unfold find_name in H0; subst; simpl.\n      unfold find_subtree in H0.\n      inversion H0.\n    - destruct t'.\n      unfold find_name in H0.\n      destruct (find_subtree [] (TreeDir n l)).\n      destruct d.\n      inversion H0.\n      inversion H0.\n      subst; simpl.\n      exfalso.\n      inversion H.\n      congruence.\n      inversion H.\n      subst; simpl; eauto.\n  Qed.\n\n  Theorem file_crash_exists : forall file, exists file',\n    BFILE.file_crash file file'.\n  Proof.\n    unfold BFILE.file_crash; intros.\n    eexists.\n    exists (map fst (BFILE.BFData file)).\n    intuition.\n    split; intros.\n    rewrite map_length; eauto.\n    unfold vsmerge. constructor.\n    erewrite selN_map; eauto.\n  Qed.\n\n  Theorem tree_crash_exists : forall tree, exists tree',\n    tree_crash tree tree'.\n  Proof.\n    induction tree using dirtree_ind2; intros.\n    edestruct file_crash_exists as [ [] H].\n    eexists (TreeFile _ (mk_dirfile _ _)).\n    econstructor; cbn. unfold file_crash. do 2 eexists. eauto.\n    induction tree_ents.\n    eexists; constructor; eauto. constructor.\n    destruct a; simpl in *.\n    inversion H.\n    edestruct IHtree_ents; eauto.\n    inversion H4.\n    repeat deex.\n    exists (TreeDir inum ((s, tree') :: st')).\n    constructor. simpl; f_equal; auto.\n    constructor; auto.\n  Unshelve.\n    exact None.\n  Qed.\n\n  Theorem tree_crash_update_subtree' :\n    forall pn tree subtree tree' subtree',\n    tree_crash tree tree' ->\n    tree_crash subtree subtree' ->\n    tree_crash (update_subtree pn subtree tree) (update_subtree pn subtree' tree').\n  Proof.\n    induction pn; simpl; intros; eauto.\n    destruct tree; simpl in *.\n    - inversion H; subst. eauto.\n    - inversion H; subst. constructor; eauto.\n      + generalize dependent st'.\n        induction l; simpl; intros; destruct st'; simpl in *; try congruence.\n        inversion H; subst.\n        inversion H6; subst.\n        inversion H7; subst.\n        f_equal.\n        destruct a0; destruct p; simpl in *. rewrite H2 in *; clear H2.\n        destruct (string_dec s0 a); subst; simpl in *; auto.\n        apply IHl; try eassumption. constructor; eauto.\n      + generalize dependent st'.\n        induction l; simpl; intros; destruct st'; simpl in *; try congruence.\n        inversion H; subst.\n        inversion H6; subst.\n        inversion H7; subst.\n        constructor.\n        destruct a0; destruct p; simpl in *. rewrite H2 in *; clear H2.\n        destruct (string_dec s0 a); subst; simpl in *; auto.\n        eapply IHl; try eassumption. constructor; eauto.\n  Qed.\n\n  Theorem tree_crash_tree_names_distinct : forall t t',\n    tree_crash t t' ->\n    tree_names_distinct t ->\n    tree_names_distinct t'.\n  Proof.\n    induction t using dirtree_ind2; simpl in *; intros.\n    inversion H; constructor.\n    inversion H0; subst.\n    inversion H1; subst.\n    constructor; try congruence.\n    eapply forall_forall2_l in H; try ( eapply forall2_length; eauto ).\n    eapply forall_forall2_l in H5; try ( eapply forall2_length; eauto ).\n    eapply forall2_forall_r; try ( eapply forall2_length; eauto ).\n    eapply forall2_impl. apply H.\n    eapply forall2_impl. apply H5.\n    eapply forall2_impl. apply H6.\n    apply forall2_lift; try ( eapply forall2_length; eauto ).\n    intros; eauto.\n  Qed.\n\n  Theorem tree_crash_tree_inodes_permutation : forall t t',\n    tree_crash t t' ->\n    permutation addr_eq_dec (tree_inodes t) (tree_inodes t').\n  Proof.\n    induction t using dirtree_ind2; simpl; intros.\n    - inversion H; subst. constructor.\n    - inversion H0; subst.\n      generalize dependent st'.\n      induction tree_ents; intros; destruct st'; simpl in *; try congruence.\n      destruct a. destruct p.\n      inversion H5; subst.\n      inversion H; subst.\n      repeat rewrite cons_app with (l := app _ _).\n      eapply permutation_trans. apply permutation_app_comm. rewrite <- app_assoc.\n      eapply permutation_trans. 2: apply permutation_app_comm. rewrite <- app_assoc.\n      eapply permutation_app_split. eauto.\n      eapply permutation_trans. apply permutation_app_comm.\n      eapply permutation_trans. 2: apply permutation_app_comm.\n      eapply IHtree_ents; eauto.\n      constructor; eauto.\n      inversion H0; subst. inversion H10; subst. eauto.\n      inversion H0; subst. inversion H10; subst. eauto.\n  Qed.\n\n  Theorem tree_crash_tree_inodes_distinct : forall t t',\n    tree_crash t t' ->\n    tree_inodes_distinct t ->\n    tree_inodes_distinct t'.\n  Proof.\n    unfold tree_inodes_distinct; intros.\n    eapply NoDup_incl_count; eauto.\n    eapply permutation_incl_count.\n    apply permutation_comm.\n    eapply tree_crash_tree_inodes_permutation; eauto.\n  Qed.\n\n  Theorem tree_crash_update_subtree :\n    forall pn tree subtree updated_tree_crashed,\n    tree_names_distinct tree ->\n    tree_crash (update_subtree pn subtree tree) updated_tree_crashed ->\n    exists tree_crashed subtree_crashed,\n    tree_crash tree tree_crashed /\\\n    tree_crash subtree subtree_crashed /\\\n    updated_tree_crashed = update_subtree pn subtree_crashed tree_crashed.\n  Proof.\n    induction pn; simpl; intros.\n    {\n      edestruct (tree_crash_exists tree). do 2 eexists; intuition eauto.\n    }\n    destruct tree; simpl in *.\n    {\n      inversion H0; subst.\n      edestruct (tree_crash_exists subtree). do 2 eexists; intuition eauto.\n    }\n    inversion H0; clear H0; subst.\n    generalize dependent st'.\n    induction l; simpl; intros; destruct st'; simpl in *; try congruence.\n    {\n      edestruct (tree_crash_exists subtree). do 2 eexists; intuition eauto.\n      constructor; eauto. auto.\n    }\n    destruct a0; destruct p; simpl in *.\n    inversion H3; clear H3; subst.\n    inversion H5; clear H5; subst.\n    destruct (string_dec s a); subst; simpl in *.\n    {\n      clear IHl.\n      edestruct IHpn. 2: eauto. eauto. deex.\n      exists (TreeDir n ((a, x) :: st')). simpl. destruct (string_dec a a); try congruence. eexists.\n      inversion H. inversion H8. subst.\n      rewrite update_subtree_notfound with (l := l) in *; eauto.\n      intuition eauto.\n      constructor; simpl. f_equal; eauto. eauto.\n\n      rewrite update_subtree_notfound; eauto.\n      eapply tree_crash_tree_names_distinct in H.\n      2: eapply TCDir with (st' := (a, x) :: st').\n      inversion H. inversion H10; eauto.\n      simpl. f_equal. eauto.\n      constructor. eauto. eauto.\n    }\n    {\n      clear IHpn.\n      edestruct IHl; clear IHl; eauto. deex.\n      destruct x; simpl in *; try congruence.\n      exists (TreeDir n ((s, d0) :: l0)). eexists.\n      inversion H1; subst.\n      intuition eauto. constructor; simpl. f_equal. auto. constructor; eauto.\n      simpl. destruct (string_dec s a); try congruence.\n    }\n  Qed.\n\n  Lemma file_crash_data_length : forall f f',\n    file_crash f f' -> length (DFData f) = length (DFData f').\n  Proof.\n    unfold file_crash; intros.\n    repeat deex.\n    eapply BFILE.file_crash_data_length in H; simpl in *.\n    eauto.\n  Qed.\n\n  Lemma file_crash_synced : forall f f',\n    file_crash (synced_dirfile f) f' ->\n    f' = synced_dirfile f.\n  Proof.\n    unfold file_crash, synced_dirfile; intros.\n    repeat deex.\n    edestruct BFILE.file_crash_synced; eauto.\n    pose proof (BFILE.fsynced_synced_file (BFILE.mk_bfile (DFData f) (DFAttr f) c)).\n    unfold BFILE.synced_file in H0; simpl in *.\n    eauto.\n\n    destruct f'; simpl in *.\n    subst; eauto.\n  Qed.\n\n  Lemma dirfile_crash_exists : forall f, exists f',\n    file_crash f f'.\n  Proof.\n    unfold file_crash; intros.\n    edestruct (file_crash_exists (BFILE.mk_bfile (DFData f) (DFAttr f) None)).\n    destruct x.\n    exists (mk_dirfile BFData BFAttr).\n    do 2 eexists.\n    simpl; eauto.\n  Qed.\n\nEnd DTCrash.\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/TreeCrash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1956942136140167}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import MemRegion State Monad.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom dx.Type Require Import Bool.\nFrom dx Require Import IR.\nFrom Coq Require Import List ZArith.\nFrom compcert Require Import Integers Values Clight Memory AST.\nFrom compcert Require Import Coqlib.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import clight_exec Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nCheck get_block_perm.\n\nget_block_perm\n     : memory_region -> DxMonad.M permission\n*)\n\nSection Get_block_perm.\n  Context {S: special_blocks}.\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(memory_region:Type)].\n  Definition res : Type := (permission:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_block_perm.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_block_perm.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (statefull (match_region st_blk mrs_blk ins_blk))\n       (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := stateless perm_correct.\n\n  Instance correct_function_get_block_perm : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _mr.\n\n    unfold match_region in c0.\n    destruct c0 as (o & Hptr & Hmatch).\n    unfold match_region_at_ofs in Hmatch.\n    destruct Hmatch as (_ & _ & (vperm & Hperm_load & Hinj) & _).\n    subst.\n\n    (**according to the type:\n         static unsigned long long getMemRegion_start_addr(struct memory_region *mr1)\n       1. return value should be  `Vlong vaddr`\n       2. the memory is same\n      *)\n    exists (Vint vperm), m, Events.E0.\n\n    split_and; unfold step2.\n    -\n      repeat forward_star.\n      unfold align, Ctypes.alignof; simpl. change (64 / 8)%Z with 8%Z.\n      unfold Mem.loadv in Hperm_load.\n      rewrite Hperm_load; reflexivity.\n\n      reflexivity.\n    - unfold eval_inv,match_res. simpl. unfold correct_perm in Hinj. unfold perm_correct.\n      destruct (block_perm c); rewrite Hinj; reflexivity.\n    - constructor. reflexivity.\n    - auto.\n    - apply unmodifies_effect_refl.\n  Qed.\n\nEnd Get_block_perm.\n\nExisting Instance correct_function_get_block_perm.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_block_perm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.19569421170670126}}
{"text": "Require Import Relations.\nRequire Import Permutation.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nRequire Import sflib.\nRequire Import PacoNotation.\nRequire Import HahnRelationsBasic.\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.\nRequire Import PromisingArch.promising.Promising.\nRequire Import PromisingArch.promising.CommonPromising.\nRequire Import PromisingArch.promising.StateExecFacts.\nRequire Import PromisingArch.axiomatic.Axiomatic.\nRequire Import PromisingArch.equiv.SimLocal.\n\nSet Implicit Arguments.\n\n\nInductive sim_trace (p: program) (mem: Memory.t) (tid: Id.t):\n  forall (tr: list (ExecUnit.t (A:=unit))) (atr: list AExecUnit.t)\n     (wl: list (nat -> option (Loc.t * Time.t))) (rl: list (nat -> option (Loc.t * Time.t))) (fl: list (nat -> option (Loc.t * Time.t)))\n     (cov: list (nat -> Time.t)) (vext: list (nat -> Time.t)), Prop :=\n| sim_trace_init\n    st lc stmts\n    (FIND: IdMap.find tid (Machine.init_with_promises p mem).(Machine.tpool) = Some (st, lc))\n    (STMT: IdMap.find tid p = Some stmts):\n    sim_trace p mem tid [ExecUnit.mk st lc mem] [AExecUnit.mk (State.init stmts) ALocal.init]\n              [fun _ => None] [fun _ => None] [fun _ => None] [fun _ => Time.bot] [fun _ => Time.bot]\n| sim_trace_step\n    e ae tr eu1 eu2 atr aeu1 aeu2 rl r1 r2 wl w1 w2 fl f1 f2 covl cov1 cov2 vextl vext1 vext2\n    (STEP: ExecUnit.state_step0 tid e e eu1 eu2)\n    (ASTATE_STEP: State.step ae aeu1.(AExecUnit.state) aeu2.(AExecUnit.state))\n    (ALOCAL_STEP: ALocal.step ae aeu1.(AExecUnit.local) aeu2.(AExecUnit.local))\n    (EVENT: sim_event e ae)\n    (STATE: sim_state_weak eu2.(ExecUnit.state) aeu2.(AExecUnit.state))\n    (LOCAL: sim_local_weak eu2.(ExecUnit.local) aeu2.(AExecUnit.local))\n    (W: w2 = match e with\n             | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n               (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                          then Some (vloc.(ValA.val),\n                                     Memory.latest_ts\n                                       vloc.(ValA.val)\n                                       (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n                                       mem)\n                         else w1 eid)\n             | _ => w1\n             end)\n    (R: r2 = match e with\n               | Event.read _ _ _ vloc _ =>\n                 (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                            then Some (vloc.(ValA.val),\n                                       Memory.latest_ts\n                                         vloc.(ValA.val)\n                                         (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n                                         mem)\n                            else r1 eid)\n               | _ => r1\n               end)\n    (F: f2 = match e with\n               | Event.flushopt vloc =>\n                 (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                            then Some (vloc.(ValA.val),\n                                       (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts))\n                            else f1 eid)\n               | _ => f1\n               end)\n    (COV: cov2 = match e with\n                 | Event.read _ _ _ vloc _\n                 | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n                   (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                              then Memory.latest_ts\n                                     vloc.(ValA.val)\n                                     (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n                                     mem\n                              else cov1 eid)\n                 | Event.flushopt vloc =>\n                   (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                               then (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts)\n                               else cov1 eid)\n                 | _ => cov1\n                 end)\n    (VEXT: vext2 = match e with\n                   | Event.read _ _ _ _ res =>\n                     (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                                then res.(ValA.annot).(View.ts)\n                                else vext1 eid)\n                   | Event.write _ _ vloc _ (ValA.mk _ 0 _) =>\n                     (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                                then (eu2.(ExecUnit.local).(Local.coh) vloc.(ValA.val)).(View.ts)\n                                else vext1 eid)\n                   | Event.flushopt vloc =>\n                     (fun eid => if Nat.eqb eid (ALocal.next_eid aeu1.(AExecUnit.local))\n                                 then (eu2.(ExecUnit.local).(Local.vpa) vloc.(ValA.val)).(View.ts)\n                                 else vext1 eid)\n                   | _ => vext1\n                   end)\n    (TRACE: sim_trace p mem tid (eu1::tr) (aeu1::atr) (w1::wl) (r1::rl) (f1::fl) (cov1::covl) (vext1::vextl)):\n    sim_trace p mem tid (eu2::eu1::tr) (aeu2::aeu1::atr) (w2::w1::wl) (r2::r1::rl) (f2::f1::fl) (cov2::cov1::covl) (vext2::vext1::vextl)\n.\n\nDefinition sim_traces\n           (p: program) (mem: Memory.t)\n           (trs: IdMap.t (list (ExecUnit.t (A:=unit))))\n           (atrs: IdMap.t (list AExecUnit.t))\n           (ws: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n           (rs: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n            (fs: IdMap.t (list (nat -> option (Loc.t * Time.t))))\n           (covs: IdMap.t (list (nat -> Time.t)))\n           (vexts: IdMap.t (list (nat -> Time.t)))\n  : Prop :=\n  IdMap.Forall7 (sim_trace p mem) trs atrs ws rs fs covs vexts.\n\nLemma sim_trace_last\n      p mem tid tr atr wl rl fl covl vextl\n      (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n  exists eu tr' aeu atr' w wl' r rl' f fl' cov covl' vext vextl',\n    <<HDTR: tr = eu :: tr'>> /\\\n    <<HDATR: atr = aeu :: atr'>> /\\\n    <<HDWL: wl = w :: wl'>> /\\\n    <<HDRL: rl = r :: rl'>> /\\\n    <<HDFL: fl = f :: fl'>> /\\\n    <<HDCOVL: covl = cov :: covl'>> /\\\n    <<HDVEXTL: vextl = vext :: vextl'>>.\nProof.\n  inv SIM; esplits; eauto.\nQed.\n\nLemma sim_trace_length\n      p mem tid tr atr wl rl fl covl vextl\n      (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl):\n  <<LENGTH_ATR: List.length atr = List.length tr>> /\\\n  <<LENGTH_WL: List.length wl = List.length tr>> /\\\n  <<LENGTH_RL: List.length rl = List.length tr>> /\\\n  <<LENGTH_FL: List.length fl = List.length tr>> /\\\n  <<LENGTH_COVL: List.length covl = List.length tr>> /\\\n  <<LENGTH_VEXTL: List.length vextl = List.length tr>>.\nProof.\n  induction SIM; ss. des. splits; congr.\nQed.\n\nLemma sim_trace_memory\n      p mem tid tr atr rl wl fl covl vextl\n      eu tr'\n      (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n      (EU: tr = eu :: tr'):\n  mem = eu.(ExecUnit.mem).\nProof.\n  revert eu tr' EU.\n  induction SIM.\n  - ii. inv EU. ss.\n  - ii. inv EU. exploit IHSIM; try refl. i.\n    inv STEP. ss.\nQed.\n\nLemma sim_traces_memory\n      p trs atrs rs ws fs covs vexts\n      m\n      ts loc val tid\n      (STEP: Machine.pf_exec p m)\n      (SIM: sim_traces p m.(Machine.mem) trs atrs ws rs fs covs vexts)\n      (TR: IdMap.Forall2\n             (fun tid tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n             trs m.(Machine.tpool))\n      (GET: Memory.get_msg ts m.(Machine.mem) = Some (Msg.mk loc val tid)):\n  exists eu, IdMap.find tid trs = Some eu.\nProof.\n  generalize (SIM tid). intro X. inv X; eauto.\n  generalize (TR tid). rewrite <- H0. intro X. inv X.\n  inv STEP. hexploit state_exec_rtc_state_step; [by eauto|]. i. des.\n  exploit Machine.step_get_msg_tpool.\n  - etrans.\n    + eapply Machine.rtc_step_mon; [|by eauto]. right. ss.\n    + eapply Machine.rtc_step_mon; [|by eauto]. left. ss.\n  - inv EQUIV. rewrite <- MEM. eauto.\n  - s. i. des. inv EQUIV. generalize (TPOOL tid). congr.\nQed.\n\nLtac simplify :=\n  repeat\n    (try match goal with\n         | [H1: _ = IdMap.find ?id ?m, H2: _ = IdMap.find ?id ?m |- _] =>\n           rewrite <- H1 in H2; inv H2\n         | [H1: IdMap.find ?id ?m = _, H2: IdMap.find ?id ?m = _ |- _] =>\n           rewrite H1 in H2; inv H2\n         | [H1: IdMap.find ?id ?m = _, H2: _ = IdMap.find ?id ?m |- _] =>\n           rewrite H1 in H2; inv H2\n         | [H: Some _ = Some _ |- _] => inv H\n         | [H: _::_ = _::_ |- _] => inv H\n         end).\n\nLemma promising_pf_sim_step\n      tid e (eu1 eu2:ExecUnit.t (A:=unit)) aeu1\n      (STATE1: sim_state_weak eu1.(ExecUnit.state) aeu1.(AExecUnit.state))\n      (LOCAL1: sim_local_weak eu1.(ExecUnit.local) aeu1.(AExecUnit.local))\n      (STEP: ExecUnit.state_step0 tid e e eu1 eu2):\n  exists ae aeu2,\n    <<ASTATE_STEP: State.step ae aeu1.(AExecUnit.state) aeu2.(AExecUnit.state)>> /\\\n    <<ALOCAL_STEP: ALocal.step ae aeu1.(AExecUnit.local) aeu2.(AExecUnit.local)>> /\\\n    <<EVENT: sim_event e ae>> /\\\n    <<STATE2: sim_state_weak eu2.(ExecUnit.state) aeu2.(AExecUnit.state)>> /\\\n    <<LOCAL2: sim_local_weak eu2.(ExecUnit.local) aeu2.(AExecUnit.local)>>.\nProof.\n  destruct eu1 as [st1 lc1 mem1].\n  destruct eu2 as [st2 lc2 mem2].\n  destruct aeu1 as [[astmt1 armap1] alc1].\n  inv STATE1. inv STEP. ss. subst. inv STATE; inv LOCAL; inv EVENT; ss.\n  - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 1.\n    + econs; ss.\n    + ss.\n    + ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto.\n  - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 2. ss.\n    + econs; ss.\n    + econs; ss.\n    + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + inv LOCAL1; [econs 1|econs 2]; eauto.\n  - inv STEP. ss.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 3; ss.\n    + econs 2; ss.\n    + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + destruct ex0.\n      * econs 2; ss.\n        rewrite List.nth_error_app2, minus_diag; ss.\n        specialize (@sim_rmap_weak_expr rmap armap1 eloc RMAP). i.\n        inv H. rewrite VAL. refl.\n      * inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n        rewrite List.nth_error_app1; eauto.\n        eapply List.nth_error_Some. ii. congr.\n  - inv STEP. ss.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 4; ss.\n    + econs 3; ss. inv WRITABLE. i. specialize (EX H). des.\n      inv LOCAL1; try congr.\n      rewrite TSX in LOCAL_EX. inv LOCAL_EX.\n      esplits; eauto. rewrite LABEL_EX; eauto.\n    + econs; ss.\n      * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n      * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + destruct ex0; eauto.\n      inv LOCAL1; [econs 1|econs 2]; ss.\n      { eauto. }\n      { eauto. }\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\n  - inv STEP. destruct ex0; ss.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 4; ss.\n    + econs 4; ss.\n    + econs; ss.\n      * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n      * eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + econs; ss. eauto using sim_rmap_weak_add, sim_rmap_weak_expr.\n    + eauto.\n  - inv STEP.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 7; ss.\n    + econs 5; ss.\n    + econs; ss.\n    + econs; ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\n  - inv STEP.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 7; ss.\n    + econs 5; ss.\n    + econs; ss.\n    + econs; ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\n  - inv STEP.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 7; ss.\n    + econs 5; ss.\n    + econs; ss.\n    + econs; ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\n  - inv LC.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 8; ss.\n    + econs 6; ss.\n    + econs; ss.\n      exploit sim_rmap_weak_expr; eauto. intro X. inv X.\n      inv VAL. rewrite <- H0. ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\n  - eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 9. ss.\n    + econs; ss.\n    + ss.\n    + ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto.\n  - inv STEP.\n    eexists _, (AExecUnit.mk (State.mk _ _) _). splits; ss.\n    + econs 10; ss.\n    + econs 7; ss.\n    + econs; ss.\n      eauto using sim_rmap_weak_expr.\n    + econs; ss.\n    + inv LOCAL1; [econs 1|econs 2]; eauto; ss.\n      rewrite List.nth_error_app1; eauto.\n      eapply List.nth_error_Some. ii. congr.\nQed.\n\nLemma promising_pf_sim_traces\n      p m\n      (STEP: Machine.pf_exec p m):\n  exists trs atrs ws rs fs covs vexts ex (PRE: Valid.pre_ex p ex),\n    <<SIM: sim_traces p m.(Machine.mem) trs atrs ws rs fs covs vexts>> /\\\n    <<TR: IdMap.Forall2\n            (fun tid tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) m.(Machine.mem)) :: l)\n            trs m.(Machine.tpool)>> /\\\n    <<ATR: IdMap.Forall2\n             (fun tid atr aeu => exists l, atr = aeu :: l)\n             atrs PRE.(Valid.aeus)>>.\nProof.\n  inv STEP. exploit state_exec_rtc_state_step; eauto. i. des.\n  eapply Machine.equiv_no_promise in NOPROMISE; eauto. revert NOPROMISE.\n  cut (exists trs atrs ws rs fs covs vexts ex (PRE: Valid.pre_ex p ex),\n    <<SIM: sim_traces p (Machine.mem m2') trs atrs ws rs fs covs vexts>> /\\\n    <<TR: forall tid, opt_rel\n            (fun tr sl => exists l, tr = (ExecUnit.mk (fst sl) (snd sl) (Machine.mem m2')) :: l)\n            (IdMap.find tid trs)\n            (IdMap.find tid (Machine.tpool m2'))>> /\\\n    <<ATR: IdMap.Forall2\n             (fun tid atr aeu => exists l, atr = aeu :: l)\n             atrs PRE.(Valid.aeus)>>).\n  { inv EQUIV. rewrite MEM. i. des. esplits; eauto. ii. rewrite TPOOL. ss. }\n  clear m STEP2 EQUIV.\n  apply clos_rt_rt1n_iff, clos_rt_rtn1_iff in EXEC. induction EXEC.\n  { eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n    eexists (IdMap.map (fun x => [x]) (IdMap.mapi (fun _ _ => _) p)).\n    eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n    eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n    eexists (IdMap.mapi (fun _ _ => [fun _ => None]) p).\n    eexists (IdMap.mapi (fun _ _ => [bot]) p).\n    eexists (IdMap.mapi (fun _ _ => [bot]) p).\n    eexists (Execution.mk (IdMap.mapi (fun _ _ => _) p) bot bot bot bot bot bot bot).\n    eexists (@Valid.mk_pre_ex _ _ (IdMap.mapi (fun tid stmts => AExecUnit.mk (State.init stmts) ALocal.init) p)  _ _ _ _ _ _).\n    hexploit Machine.rtc_promise_step_spec; eauto. s. intro X.\n    s. splits; cycle 1.\n    - i. specialize (X tid). rewrite ? IdMap.map_spec, ? IdMap.mapi_spec in *.\n      rewrite X. destruct (IdMap.find tid p); ss. econs. eauto.\n    - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p); ss. eauto.\n    - ii. rewrite ? IdMap.map_spec, ? IdMap.mapi_spec. destruct (IdMap.find id p) eqn:STMTS; ss. econs.\n      econs 1; ss. rewrite IdMap.mapi_spec, STMTS. s. ss.\n  }\n  des.\n  destruct y as [tpool1 mem1].\n  destruct z as [tpool2 mem2].\n  ss. inv H. ss. subst. inv STEP. inv STEP0. ss. subst.\n  generalize (TR tid). rewrite FIND. intro Y. inv Y. des. subst. rename H0 into TRS. symmetry in TRS.\n  generalize (SIM tid). intro Y. inv Y; [congr|]. rewrite TRS in H0. inv H0.\n  hexploit sim_trace_last; eauto. i. des. subst. simplify.\n  exploit promising_pf_sim_step; eauto.\n  { inv REL7; eauto. s.\n    unfold Machine.init_with_promises in FIND0. ss.\n    rewrite IdMap.mapi_spec, STMT in *. inv FIND0.\n    apply sim_state_weak_init.\n  }\n  { inv REL7; eauto. s.\n    unfold Machine.init_with_promises in FIND0. ss.\n    rewrite IdMap.mapi_spec, STMT in *. inv FIND0.\n    auto.\n  }\n  { instantiate (1 := ExecUnit.mk _ _ _). econs; ss; eauto. }\n  i. des.\n\n  eexists (IdMap.add tid _ trs).\n  eexists (IdMap.add tid _ atrs).\n  eexists (IdMap.add tid _ ws).\n  eexists (IdMap.add tid _ rs).\n  eexists (IdMap.add tid _ fs).\n  eexists (IdMap.add tid _ covs).\n  eexists (IdMap.add tid _ vexts).\n  eexists (Execution.mk _ _ _ _ _ _ _ _).\n  eexists (@Valid.mk_pre_ex _ _ (IdMap.add tid _ PRE.(Valid.aeus))  _ _ _ _ _ _).\n  s. splits; cycle 1.\n  - i. rewrite ? IdMap.add_spec. condtac; eauto.\n  - ii. rewrite ? IdMap.add_spec. condtac; eauto.\n  - s. ii. rewrite ? IdMap.add_spec. condtac; eauto. inversion e0. subst. clear e0 X. econs.\n    econs 2; eauto. econs; eauto.\nGrab Existential Variables.\nall: ss.\n1: { ii. generalize (PRE.(Valid.AEUS) id). intro X.\n     rewrite IdMap.add_spec. condtac; ss. inversion e0. subst. clear e0 X0.\n     generalize (ATR tid). rewrite <- H. intro Y. inv Y. des. inv REL.\n     rewrite <- H7 in X. inv X. econs. etrans; eauto.\n}\n4: { funext. i. funext. i. propext. econs; ss. i. inv H.\n     rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n     inv RELS. inv REL. ss.\n}\n4: { funext. i. funext. i. propext. econs; ss. i. inv H.\n     rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n     inv RELS. inv REL. ss.\n}\n4: { funext. i. funext. i. propext. econs; ss. i. inv H.\n     rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n     inv RELS. inv REL. ss.\n}\n4: { funext. i. funext. i. propext. econs; ss. i. inv H.\n     rewrite IdMap.map_spec, IdMap.mapi_spec in RELS. destruct (IdMap.find tid p); ss.\n     inv RELS. inv REL. ss.\n}\n5: { ii. rewrite IdMap.mapi_spec. destruct (IdMap.find id p); ss. econs. refl. }\n4: { unfold IdMap.map. rewrite IdMap.mapi_mapi. f_equal. }\n1: { apply bot. (* it's ex's co. *) }\n1: { apply bot. (* it's ex's rf. *) }\n1: { apply bot. (* it's ex's pf. *) }\nQed.\n\nInductive sim_th\n          (p:program) (mem:Memory.t) (tid:Id.t)\n          (eu:ExecUnit.t (A:=unit))\n          (aeu:AExecUnit.t)\n          (w: nat -> option (Loc.t * Time.t))\n          (r: nat -> option (Loc.t * Time.t))\n          (f: nat -> option (Loc.t * Time.t))\n          (cov: nat -> Time.t)\n          (vext: nat -> Time.t): Prop := mk {\n  WPROP1:\n    forall ts loc val\n      (GET: Memory.get_msg ts mem = Some (Msg.mk loc val tid)),\n      ((Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = true /\\\n        forall eid, w eid <> Some (loc, ts)) \\/\n       (Promises.lookup ts eu.(ExecUnit.local).(Local.promises) = false /\\\n        exists eid ex ord,\n          w eid = Some (loc, ts) /\\\n          List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val)));\n  WPROP2:\n    forall eid ex ord loc val\n      (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val)),\n    exists ts,\n      w eid = Some (loc, ts) /\\\n      Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n  WPROP3:\n    forall eid loc ts (GET: w eid = Some (loc, ts)),\n      Time.lt Time.bot ts /\\\n      cov eid = ts /\\\n      vext eid = ts /\\\n      le ts (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n      exists ex ord val,\n        List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.write ex ord loc val) /\\\n        Memory.get_msg ts mem = Some (Msg.mk loc val tid);\n  WPROP4:\n    forall eid1 loc1 eid2 loc2 ts (W1: w eid1 = Some (loc1, ts)) (W2: w eid2 = Some (loc2, ts)),\n      eid1 = eid2;\n  RPROP1:\n    forall eid ex ord loc val\n      (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.read ex ord loc val)),\n    exists ts tid',\n      r eid = Some (loc, ts) /\\\n      __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n                 Memory.get_msg ts mem = Some (Msg.mk loc val tid'));\n  RPROP2:\n    forall eid loc ts (GET: r eid = Some (loc, ts)),\n    cov eid = ts /\\\n    le ts (eu.(ExecUnit.local).(Local.coh) loc).(View.ts) /\\\n    exists ex ord val tid',\n      List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.read ex ord loc val) /\\\n      __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n                 Memory.get_msg ts mem = Some (Msg.mk loc val tid'));\n  FPROP1:\n    forall eid loc1\n      (GET: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.flushopt loc1)),\n    exists perv,\n      <<FEID: f eid = Some (loc1, perv)>> /\\\n      <<CL_REL:\n        forall loc2 (CL: Loc.cl loc1 loc2),\n          exists ts tid' val,\n          ts = Memory.latest_ts loc2 perv mem /\\\n          <<FLUSH_TS_SPEC:\n              __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n              Memory.get_msg ts mem = Some (Msg.mk loc2 val tid'))>>>>;\n  FPROP2:\n    forall eid loc1 perv\n           (GET: f eid = Some (loc1, perv)),\n    <<COV_EQ: cov eid = perv>> /\\\n    <<VEXT_EQ: vext eid = perv>> /\\\n    List.nth_error aeu.(AExecUnit.local).(ALocal.labels) eid = Some (Label.flushopt loc1) /\\\n    <<CL_REL:\n        forall loc2 (CL: Loc.cl loc1 loc2),\n          exists ts tid' val,\n          ts = Memory.latest_ts loc2 perv mem /\\\n          <<FLUSH_TS_SPEC:\n              __guard__ ((ts = Time.bot /\\ val = Val.default) \\/\n              Memory.get_msg ts mem = Some (Msg.mk loc2 val tid'))>>>>;\n  COVPROP:\n    forall eid (COV: cov eid > 0),\n      AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access_persist eid;\n  VEXTPROP:\n    forall eid (VEXT: vext eid > 0),\n      AExecUnit.label_is aeu.(AExecUnit.local).(ALocal.labels) Label.is_access_persist eid;\n\n  PO: forall iid1 iid2 label1 label2\n     (PO: iid1 < iid2)\n     (LABEL1: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid1 = Some label1)\n     (LABEL2: List.nth_error aeu.(AExecUnit.local).(ALocal.labels) iid2 = Some label2)\n     (REL: Execution.label_loc label1 label2),\n      <<PO_LOC_WRITE:\n        Label.is_write label2 ->\n        Time.lt (cov iid1) (cov iid2)>> /\\\n      <<PO_LOC_READ:\n        Label.is_read label2 ->\n        Time.le (cov iid1) (cov iid2)>>;\n  EU_WF: ExecUnit.wf tid eu;\n  AEU_WF: AExecUnit.wf aeu;\n  MEM: eu.(ExecUnit.mem) = mem;\n}.\n\nLemma sim_trace_sim_state_weak\n      p mem tid\n      tr eu tr'\n      atr aeu atr'\n      wl w wl'\n      rl r rl'\n      fl f fl'\n      covl cov covl'\n      vextl vext vextl'\n      (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n      (EU: tr = eu :: tr')\n      (AEU: atr = aeu :: atr')\n      (RL: rl = r :: rl')\n      (WL: wl = w :: wl')\n      (FL: fl = f :: fl')\n      (COV: covl = cov :: covl')\n      (VEXT: vextl = vext :: vextl'):\n  sim_state_weak eu.(ExecUnit.state) aeu.(AExecUnit.state).\nProof.\n  subst. inv SIM; ss.\n  rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n  eapply sim_state_weak_init.\nQed.\n\nLemma sim_trace_sim_th\n      p mem tid\n      tr eu tr'\n      atr aeu atr'\n      wl w wl'\n      rl r rl'\n      fl f fl'\n      covl cov covl'\n      vextl vext vextl'\n      (SIM: sim_trace p mem tid tr atr wl rl fl covl vextl)\n      (EU: tr = eu :: tr')\n      (AEU: atr = aeu :: atr')\n      (RL: rl = r :: rl')\n      (WL: wl = w :: wl')\n      (FL: fl = f :: fl')\n      (COV: covl = cov :: covl')\n      (VEXT: vextl = vext :: vextl'):\n  sim_th p mem tid eu aeu w r f cov vext.\nProof.\n  revert f fl' r rl' w wl' eu tr' aeu atr' cov covl' vext vextl' FL RL WL EU AEU COV VEXT. induction SIM.\n  { i. simplify. ss. econs; ss.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n      left. splits; ss. destruct ts; ss.\n      eapply Promises.promises_from_mem_lookup. eauto.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n      destruct eid; ss.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n      destruct eid; ss.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND. s. i.\n      destruct eid; ss.\n    - unfold Time.bot. i. lia.\n    - unfold Time.bot. i. lia.\n    - i. destruct iid1; ss.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n      econs; ss.\n      + econs. i. unfold RMap.find. rewrite IdMap.gempty. ss. apply bot_spec.\n      + econs; ss; i; try by apply bot_spec.\n        * econs; esplits; ss.\n        * destruct ts; ss.\n          rewrite Promises.promises_from_mem_spec in IN. des.\n          apply lt_le_S. rewrite <- List.nth_error_Some. ii. congr.\n        * destruct ts; ss.\n          unfold Memory.get_msg in *. ss. destruct msg.\n          exploit Promises.promises_from_mem_lookup; eauto. ss. subst. ss.\n        * econs; try rewrite Loc.cl_refl; ss. i. apply bot_spec.\n    - rewrite IdMap.mapi_spec, STMT in FIND. inv FIND.\n      econs; ss.\n      + ii. unfold RMap.init in N. unfold RMap.find in N.\n        rewrite IdMap.gempty in N. ss.\n      + ii. apply List.nth_error_In in LABEL. inv LABEL.\n  }\n  clear LOCAL.\n  i. simplify.\n  destruct eu1 as [st1 lc1 mem1].\n  destruct eu as [st2 lc2 mem2].\n  destruct aeu1 as [ast1 alc1].\n  destruct aeu as [ast2 alc2].\n  assert (mem1 = mem); subst.\n  { exploit sim_trace_memory; eauto. }\n  ss. exploit IHSIM; eauto.\n  i. rename x into IH.\n  assert (EU_WF2: ExecUnit.wf tid (ExecUnit.mk st2 lc2 mem2)).\n  { destruct IH.\n    eapply ExecUnit.state_step_wf; eauto. econs; eauto. }\n  assert (AEU_WF2: AExecUnit.wf (AExecUnit.mk ast2 alc2)).\n  { destruct IH.\n    eapply AExecUnit.step_future; eauto. }\n  inv STEP. inv ALOCAL_STEP; inv EVENT; ss; eauto.\n  { (* internal *)\n    inv LOCAL; ss. inv EVENT. econs; ss; try by apply IH.\n  }\n  { (* read *)\n    inv LOCAL; ss. generalize IH.(EU_WF). i. inv H.\n    specialize (Local.read_spec LOCAL STEP). intro READ_SPEC. guardH READ_SPEC.\n    inv STEP. inv STATE0; cycle 1.\n    { i. unfold ALocal.next_eid in *. s. i. des_ifs. }\n    inv ASTATE_STEP. ss. inv EVENT.\n    exploit sim_trace_sim_state_weak; eauto. s. intro Y. inv Y. ss. inv STMTS.\n    exploit sim_rmap_weak_expr; eauto. intro Y. inv Y.\n\n    econs; ss; clear EU_WF2 AEU_WF2.\n    - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - i. exploit IH.(WPROP2); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n      { exfalso. apply Nat.eqb_eq in Heq. subst.\n        unfold ALocal.next_eid in *.\n        assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n        apply List.nth_error_Some in H. lia.\n      }\n      esplits; eauto.\n      + rewrite fun_add_spec. des_ifs; eauto. inv e.\n        ss. etrans; eauto. apply join_l.\n      + eapply nth_error_app_mon. eauto.\n    - eapply IH.(WPROP4).\n    - i. apply nth_error_snoc_inv in GET. des.\n      + exploit IH.(RPROP1); eauto. i. des. esplits; eauto.\n        des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n      + des_ifs; cycle 1.\n        { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n        rewrite fun_add_spec in *. condtac; [|congr].\n        inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n        move READ_SPEC at bottom. desH READ_SPEC. rewrite <- COH0.\n        exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n    - i. des_ifs.\n      + apply Nat.eqb_eq in Heq. subst.\n        rewrite fun_add_spec in *. des_ifs; [|congr].\n        inv VLOC. inv VAL. ss. subst. rewrite VAL1 in *.\n        move READ_SPEC at bottom. desH READ_SPEC. rewrite <- COH0.\n        exploit Memory.read_get_msg; eauto. i. des; esplits; eauto.\n        all: try by rewrite COH0 at 1; eapply Memory.latest_ts_spec.\n        all: try by rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss.\n      + exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n        * rewrite fun_add_spec. des_ifs; eauto.\n          inv e. etrans; eauto. ss. apply join_l.\n        * eapply nth_error_app_mon. eauto.\n    - i. des. exploit IH.(FPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; ss.\n    - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n      { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n      exfalso. apply Nat.eqb_eq in Heq. subst.\n      unfold ALocal.next_eid in *.\n      assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n      apply List.nth_error_Some in H. lia.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n    - i. unfold ALocal.next_eid in *.\n      apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n      + repeat condtac.\n        all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n        all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n        eapply IH.(PO); eauto.\n      + lia.\n      + subst. repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n        all: try apply Nat.eqb_neq in X0; ss; try lia.\n        splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n        inv REL. destruct label1; ss.\n        * destruct (equiv_dec loc0 loc); ss. inv e0.\n          destruct (equiv_dec (ValA.val (sem_expr rmap0 eloc0)) loc); ss. inv e0.\n          exploit IH.(RPROP1); eauto. i. des.\n          exploit IH.(RPROP2); eauto. s. i. des. subst.\n          exploit sim_rmap_weak_expr; eauto. i. inv x2. rewrite VAL1 in *.\n          desH x5.\n          { rewrite x5. apply bot_spec. }\n          exploit Memory.latest_ts_read_le; try eapply Memory.get_msg_read; eauto. i.\n          rewrite x2. apply Memory.latest_ts_mon. apply join_l.\n        * destruct (equiv_dec loc0 loc); ss. inv e0.\n          destruct (equiv_dec (ValA.val (sem_expr rmap0 eloc0)) loc); ss. inv e0.\n          exploit IH.(WPROP2); eauto. i. des.\n          exploit IH.(WPROP3); eauto. s. i. des. subst.\n          exploit sim_rmap_weak_expr; eauto. i. inv x3. rewrite VAL1 in *.\n          exploit Memory.latest_ts_read_le; try eapply Memory.get_msg_read; eauto. i.\n          rewrite x3. apply Memory.latest_ts_mon. apply join_l.\n      + subst. repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; try lia.\n  }\n  { (* write *)\n    inv LOCAL; ss; inv EVENT; inv RES; inv STEP; ss. inv STATE. ss.\n    destruct IH.(EU_WF).\n    econs; ss; clear EU_WF2 AEU_WF2.\n    - i. exploit IH.(WPROP1); eauto. s. i. rewrite Promises.unset_o. des_ifs.\n      { inv e. right. rewrite MSG in GET. inv GET. esplits; ss.\n        - instantiate (1 := ALocal.next_eid alc1). des_ifs; cycle 1.\n          { apply Nat.eqb_neq in Heq. congr. }\n          rewrite fun_add_spec. des_ifs; ss; try congr.\n          repeat f_equal. destruct ts; ss.\n          unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n        - rewrite List.nth_error_app2, Nat.sub_diag; ss.\n          inv VLOC. inv VVAL. rewrite VAL0, VAL1. eauto.\n      }\n      des; [left|right]; splits; ss.\n      + i. des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. ii. inv H.\n        rewrite fun_add_spec in *. des_ifs; [|congr]. ss. apply c.\n        specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n        destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n      + esplits; eauto.\n        * des_ifs; eauto. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *.\n          assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n          apply List.nth_error_Some in H. lia.\n        * eapply nth_error_app_mon. eauto.\n    - i. unfold ALocal.next_eid in *. apply nth_error_snoc_inv in GET. des.\n      + des_ifs.\n        { apply Nat.eqb_eq in Heq. subst. lia. }\n        eapply IH.(WPROP2); eauto.\n      + des_ifs; cycle 1.\n        { apply Nat.eqb_neq in Heq. lia. }\n        esplits; eauto.\n        * inv VLOC. rewrite VAL0. eauto.\n        * rewrite fun_add_spec in *. des_ifs; [|congr]. ss.\n          inv VLOC. inv VVAL. rewrite <- VAL0, <- VAL1.\n          specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n          destruct ts; ss. unfold Memory.get_msg in MSG. ss.\n          rewrite MSG. ss. des_ifs.\n    - i. unfold ALocal.next_eid in *. des_ifs.\n      + apply Nat.eqb_eq in Heq. subst. rewrite fun_add_spec. des_ifs; [|congr]. inv e.\n        destruct ts; ss. esplits; eauto.\n        * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n          unfold Time.lt, Time.bot. lia.\n        * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n        * unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n        * rewrite List.nth_error_app2, Nat.sub_diag; ss.\n          inv VLOC. rewrite VAL0. eauto.\n        * generalize MSG. intro X. inv VVAL. rewrite <- VAL0.\n          unfold Memory.get_msg in X. ss. rewrite X. des_ifs.\n      + exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n        * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n          inv WRITABLE. apply Nat.lt_le_incl. ss.\n        * eapply nth_error_app_mon. eauto.\n    - i. unfold ALocal.next_eid in *.\n      specialize (Memory.latest_ts_spec (ValA.val vloc0) ts mem). i. des.\n      exploit Memory.latest_ts_read_le; [|refl|i; exploit le_antisym; try eapply LE; eauto; i].\n      { eapply Memory.get_msg_read; eauto. }\n      des_ifs.\n      + apply Nat.eqb_eq in Heq. apply Nat.eqb_eq in Heq0. subst. ss.\n      + clear Heq0. rewrite fun_add_spec in *. des_ifs; [|congr].\n        exploit IH.(WPROP3); eauto. s. i. des.\n        exploit IH.(WPROP1); eauto. s. rewrite x1 in *.\n        rewrite PROMISE. i. des; ss.\n        rewrite MSG in x7. inv x7. clear - WRITABLE x5. unfold le in x5. inv WRITABLE. lia.\n      + rewrite fun_add_spec in *. des_ifs; [|congr].\n        exploit IH.(WPROP3); eauto. s. i. des.\n        exploit IH.(WPROP1); eauto. s. rewrite x1 in *.\n        rewrite PROMISE. i. des; ss.\n        rewrite MSG in x7. inv x7. clear -WRITABLE x5. unfold le in x5. inv WRITABLE. lia.\n      + eapply IH.(WPROP4); eauto.\n    - i. exploit IH.(RPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n      * des_ifs.\n        exfalso. apply Nat.eqb_eq in Heq. subst.\n        unfold ALocal.next_eid in *.\n        assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n        apply List.nth_error_Some in H. lia.\n      * rewrite fun_add_spec. des_ifs; eauto. inv e. etrans; eauto.\n        inv WRITABLE. apply Nat.lt_le_incl. ss.\n      * eapply nth_error_app_mon. eauto.\n    - i. des. exploit IH.(FPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; ss.\n    - i. exploit IH.(FPROP2); eauto. s. i. des. des_ifs; cycle 1.\n      { esplits; eauto. eapply nth_error_app_mon in x0. eauto. }\n      exfalso. apply Nat.eqb_eq in Heq. subst.\n      unfold ALocal.next_eid in *.\n      assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n      apply List.nth_error_Some in H. lia.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n    - inv ASTATE_STEP; ss; eauto. subst.\n      inv VLOC. inv VVAL. rewrite VAL0, VAL1 in *. unfold ALocal.next_eid in *.\n      i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n      + repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n        all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n        eapply IH.(PO); eauto.\n      + lia.\n      + subst. repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n        all: try apply Nat.eqb_neq in X0; ss; try lia.\n        splits; ss. rewrite fun_add_spec. des_ifs; [|congr].\n        inv REL. destruct label1; ss.\n        * destruct (equiv_dec loc0 loc); ss. inv e0.\n          destruct (equiv_dec (ValA.val (sem_expr rmap eloc)) loc); ss. inv e0.\n          exploit IH.(RPROP1); eauto. i. des.\n          exploit IH.(RPROP2); eauto. s. i. des. subst.\n          destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n          eapply Nat.le_lt_trans; eauto. inv WRITABLE. rewrite VAL0 in *. ss.\n        * destruct (equiv_dec loc0 loc); ss. inv e0.\n          destruct (equiv_dec (ValA.val (sem_expr rmap eloc)) loc); ss. inv e0.\n          exploit IH.(WPROP2); eauto. i. des.\n          exploit IH.(WPROP3); eauto. s. i. des. subst.\n          destruct ts; ss. unfold Memory.get_msg in MSG. ss. rewrite MSG. des_ifs.\n          eapply Nat.le_lt_trans; eauto. inv WRITABLE. rewrite VAL0 in *. ss.\n      + subst. repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; try lia.\n  }\n  { (* write failure *)\n    inv RES. destruct res1. ss. subst.\n    inv LOCAL; ss; inv STEP; ss. inv EVENT. econs; ss; try by apply IH.\n  }\n  { (* barrier *)\n    inv LOCAL; ss.\n    { (* isb *)\n      inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n      - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(WPROP2); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(WPROP3); eauto. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - eapply IH.(WPROP4).\n      - i. exploit IH.(RPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(FPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(FPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n      - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n        { subst. inv REL. inv X. }\n        apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n        { subst. inv REL. inv Y. }\n        eapply IH.(PO); eauto.\n    }\n    { (* dmb *)\n      inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n      - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(WPROP2); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - eapply IH.(WPROP4).\n      - i. exploit IH.(RPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(FPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(FPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n      - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n        { subst. inv REL. inv X. }\n        apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n        { subst. inv REL. inv Y. }\n        eapply IH.(PO); eauto.\n    }\n    { (* dsb *)\n      inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n      - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(WPROP2); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(WPROP3); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - eapply IH.(WPROP4).\n      - i. exploit IH.(RPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. exploit IH.(FPROP1); eauto.\n        apply nth_error_snoc_inv in GET. des; eauto. congr.\n      - i. exploit IH.(FPROP2); eauto. s. i. des. esplits; eauto.\n        eapply nth_error_app_mon. eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n      - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n      - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n        { subst. inv REL. inv X. }\n        apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n        { subst. inv REL. inv Y. }\n        eapply IH.(PO); eauto.\n    }\n  }\n  { (* control *)\n    inv LOCAL; ss. inv LC. inv STATE0. inv ASTATE_STEP. ss. inv EVENT.\n    econs; ss.\n    - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - i. exploit IH.(WPROP2); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(WPROP3); eauto. i. des. esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - eapply IH.(WPROP4).\n    - i. exploit IH.(RPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - i. exploit IH.(FPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(FPROP2); eauto. s. i. des. esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - i. apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n    - i. apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n    - i. apply nth_error_snoc_inv in LABEL1. des; cycle 1.\n      { subst. inv REL. inv X. }\n      apply nth_error_snoc_inv in LABEL2. des; cycle 1.\n      { subst. inv REL. inv Y. }\n      eapply IH.(PO); eauto.\n  }\n  { (* flushopt *)\n    inv LOCAL; ss.\n    inv STEP. inv ASTATE_STEP. ss. inv EVENT. econs; ss.\n    - i. exploit IH.(WPROP1); eauto. s. i. des; [left|right]; esplits; eauto.\n      eapply nth_error_app_mon. eauto.\n    - i. exploit IH.(WPROP2); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(WPROP3); eauto. s. i. des. des_ifs.\n      { exfalso. apply Nat.eqb_eq in Heq. subst.\n        unfold ALocal.next_eid in *.\n        assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n        apply List.nth_error_Some in H. lia.\n      }\n      esplits; eauto. eapply nth_error_app_mon. eauto.\n    - eapply IH.(WPROP4).\n    - i. exploit IH.(RPROP1); eauto.\n      apply nth_error_snoc_inv in GET. des; eauto. congr.\n    - i. exploit IH.(RPROP2); eauto. s. i. des. esplits; eauto.\n      + des_ifs.\n        exfalso. apply Nat.eqb_eq in Heq. subst.\n        unfold ALocal.next_eid in *.\n        assert (H: List.nth_error (ALocal.labels alc1) (length (ALocal.labels alc1)) <> None) by (ii; congr).\n        apply List.nth_error_Some in H. lia.\n      + eapply nth_error_app_mon. eauto.\n    - i. des. apply nth_error_snoc_inv in GET. des.\n      + exploit IH.(FPROP1); eauto. i. des. esplits; eauto.\n        des_ifs. apply Nat.eqb_eq in Heq. subst. unfold ALocal.next_eid in *. lia.\n      + des_ifs; cycle 1.\n        { apply Nat.eqb_neq in Heq. unfold ALocal.next_eid in *. congr. }\n        ss. eqvtac. inv VLOC. inv VAL.\n        esplits; eauto. i.\n        exploit Memory.latest_ts_spec. i. des.\n        exploit Memory.read_get_msg; eauto. i. des; esplits; eauto; [left|right]; eauto.\n    - i. des_ifs.\n      + split; ss.\n        apply Nat.eqb_eq in Heq. subst.\n        inv VLOC. inv VAL. ss.\n        esplits; cycle 1.\n        { rewrite List.nth_error_app2, Nat.sub_diag; [|refl]; ss; eauto with axm. }\n        all: eauto with axm.\n        i.\n        exploit Memory.latest_ts_spec. i. des.\n        exploit Memory.read_get_msg; eauto. i. des; esplits; ss; [left | right]; eauto.\n      + exploit IH.(FPROP2); eauto. s. i. des; esplits; eauto with axm.\n        eapply nth_error_app_mon; eauto.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(COVPROP); eauto.\n    - unfold ALocal.next_eid in *. s. i. des_ifs.\n      { apply Nat.eqb_eq in Heq. subst. econs; eauto.\n        - rewrite List.nth_error_app2, Nat.sub_diag; [|refl]. ss.\n        - econs; ss.\n      }\n      apply AExecUnit.label_is_mon. eapply IH.(VEXTPROP); eauto.\n    - unfold ALocal.next_eid in *.\n      i. apply nth_error_snoc_inv in LABEL1. apply nth_error_snoc_inv in LABEL2. des.\n      + repeat condtac; ss.\n        all: try apply Nat.eqb_eq in X; ss; subst; try lia.\n        all: try apply Nat.eqb_eq in X0; ss; subst; try lia.\n        eapply IH.(PO); eauto.\n      + lia.\n      + subst. repeat condtac; ss.\n      + subst. repeat condtac; ss.\n  }\n  Grab Existential Variables.\n  all: auto. (* tid *)\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/equiv/PFtoA1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.19548369260193152}}
{"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  Record relate_RData (hadt: RData) (ladt: RData) :=\n      mkrelate_RData {\n          id_priv: priv ladt = priv hadt;\n          id_share: share ladt = share hadt;\n          hrepl: repl hadt = replay 2;\n          lrepl: repl ladt = replay 1;\n          valid_ho: ValidOracle 2 (oracle hadt);\n          valid_lo: ValidOracle 1 (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              st = st' -> repl ladt lo st = repl hadt lh st'\n        }.\n\nEnd RefineRel.\n\nLtac rewrite_oracle_rel R H :=\n  match type of H with\n  | repl ?habd (oracle ?habd ?l) ?st = _ =>\n    match goal with\n    | [ |- context[repl ?labd (oracle ?labd ?l') st]] =>\n      rewrite (R st st l l'); [rewrite H|reflexivity]\n    end\n  end.\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/RefRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.1954629536740928}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import State Monad.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom Coq Require Import List Lia.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\nRequire Import ZArith.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nunsigned int get_addr_ofs(unsigned long long x, int ofs)\n{\n  return (unsigned int) (x + (unsigned long long) ofs);\n}\n\nPrint get_addr_ofs.\nget_addr_ofs = \nfun (x : val64_t) (ofs : sint32_t) =>\nreturnM (val_intuoflongu (Val.addl x (Val.longofintu (sint32_to_vint ofs))))\n     : val64_t -> sint32_t -> M valu32_t\n\n*)\n\nSection Get_addr_ofs.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(val:Type); (int:Type)].\n  Definition res : Type := (val:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_addr_ofs.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_addr_ofs.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (stateless val64_correct)\n       (dcons (stateless sint32_correct)\n                    (DList.DNil _))).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := stateless val32_correct.\n\n  Instance correct_function_get_addr_ofs : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _x.\n    get_invariant _ofs.\n\n    unfold stateless, eval_inv, val64_correct in c1.\n    unfold stateless, eval_inv, sint32_correct in c2.\n    destruct c1 as (Hc_eq & (vi & Hvi_eq)).\n    destruct c2 as (c2 & c2_range).\n    subst c v v0.\n\n    (**according to the type of eval_pc:\nunsigned int get_addr_ofs(unsigned long long x, int ofs)\n{\n  return (unsigned int) (x + (unsigned long long) ofs);\n}\n       1. return value should be  x+y\n       2. the memory is same\n      *)\n    eexists. exists m, Events.E0.\n\n    split_and; unfold step2;auto.\n    -\n      repeat forward_star.\n    - simpl. unfold val32_correct. eauto.\n    - simpl.\n      constructor.\n      reflexivity.\n    - apply unmodifies_effect_refl.\n  Qed.\n\nEnd Get_addr_ofs.\n\nExisting Instance correct_function_get_addr_ofs.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_addr_ofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19546295367409278}}
{"text": "Require Export CertiGraph.msl_ext.seplog.\nRequire Export CertiGraph.msl_ext.log_normalize.\nRequire Export CertiGraph.msl_ext.alg_seplog.\nRequire Export CertiGraph.msl_ext.iter_sepcon.\nRequire Export CertiGraph.msl_ext.ramification_lemmas.\nRequire Export CertiGraph.veric_ext.seplog.\nRequire Export VST.veric.address_conflict.\nRequire Import VST.veric.SeparationLogic.\n\nInstance PSLveric: PreciseSepLog mpred := algPreciseSepLog compcert_rmaps.RML.R.rmap.\nInstance OSLveric: OverlapSepLog mpred := algOverlapSepLog compcert_rmaps.RML.R.rmap.\nInstance DSLveric: DisjointedSepLog mpred := algDisjointedSepLog compcert_rmaps.RML.R.rmap.\nInstance COSLveric: CorableOverlapSepLog mpred := algCorableOverlapSepLog compcert_rmaps.RML.R.rmap.\n\nInstance LiftPreciseSepLog' T {ND: NatDed T}{SL: SepLog T}{PSL: PreciseSepLog T} :\n           PreciseSepLog (LiftEnviron T) := LiftPreciseSepLog _ _.\nInstance LiftOverlapSepLog' T {ND: NatDed T}{SL: SepLog T}{PSL: PreciseSepLog T}{OSL: OverlapSepLog T} :\n           OverlapSepLog (LiftEnviron T) := LiftOverlapSepLog _ _.\nInstance LiftDisjointedSepLog' T {ND: NatDed T}{SL: SepLog T}{PSL: PreciseSepLog T}{OSL: OverlapSepLog T}{DSL: DisjointedSepLog T} :\n           DisjointedSepLog (LiftEnviron T) := LiftDisjointedSepLog _ _.\n\nGlobal Opaque PSLveric OSLveric DSLveric COSLveric.\n\nLocal Open Scope logic.\n\nLemma exp_mapsto_precise: forall sh t p, precise (EX v: val, mapsto sh t p v).\nProof. exact exp_mapsto_precise. Qed.\n\nLemma disj_mapsto_: forall {cs: composite_env} sh t1 t2 p1 p2,\n  ~ pointer_range_overlap p1 (sizeof t1) p2 (sizeof t2) ->\n  disjointed (EX v1: val, mapsto sh t1 p1 v1) (EX v2: val, mapsto sh t2 p2 v2).\nProof. exact @disj_mapsto_. Qed.\n\nLemma memory_block_precise: forall sh p n, precise (memory_block sh n p).\nProof. exact memory_block_precise. Qed.\n\nLemma disj_memory_block: forall sh p1 n1 p2 n2, ~ pointer_range_overlap p1 n1 p2 n2 -> disjointed (memory_block sh n1 p1) (memory_block sh n2 p2).\nProof. exact disj_memory_block. Qed.\n\n\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/veric_ext/SeparationLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.19543222775791283}}
{"text": "Require Import VST.msl.Coqlib2.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.shares.\nRequire Import VST.msl.pshares.\nRequire Import VST.veric.coqlib4.\nRequire Import VST.veric.shares.\nRequire Import VST.veric.juicy_mem.\nRequire Import VST.veric.juicy_mem_ops.\nRequire Import VST.concurrency.permjoin_def.\nImport Memtype.\n\n  Lemma perm_of_glb_not_Freeable: forall sh,\n      ~ perm_of_sh (Share.glb Share.Rsh sh) = Some Freeable.\n  Proof.\n   intros.\n   unfold perm_of_sh.\n   if_tac.\n   rewrite if_false by apply glb_Rsh_not_top.\n   congruence.\n   if_tac. congruence.\n   if_tac. congruence. congruence.\n  Qed.\n\nLemma join_bot_bot_eq sh :\n  sepalg.join Share.bot Share.bot sh ->\n  sh = Share.bot.\nProof.\n  intros j.\n  apply (join_eq j  (z' := Share.bot) (join_bot_eq Share.bot)).\nQed.\n\nLemma join_to_bot_l {sh1 sh2} :\n  sepalg.join sh1 sh2 Share.bot ->\n  sh1 = Share.bot.\nProof.\n  intros [H H'].\n  apply shares.lub_bot_e in H'.\n  apply H'.\nQed.\n\nLemma join_to_bot_r {sh1 sh2} :\n  sepalg.join sh1 sh2 Share.bot ->\n  sh2 = Share.bot.\nProof.\n  intros [H H'].\n  apply shares.lub_bot_e in H'.\n  apply H'.\nQed.\n\nLemma join_top_l {sh2 sh3} :\n  sepalg.join Share.top sh2 sh3 ->\n  sh2 = Share.bot.\nProof.\n  intros [H H'].\n  rewrite Share.glb_commute in H.\n  rewrite Share.glb_top in H.\n  auto.\nQed.\n\nLemma join_top {sh2 sh3} :\n  sepalg.join Share.top sh2 sh3 ->\n  sh3 = Share.top.\nProof.\n  intros [H H'].\n  rewrite Share.lub_commute in H'.\n  rewrite Share.lub_top in H'.\n  auto.\nQed.\n\nLemma join_pfullshare {sh2 sh3 : pshare} : ~sepalg.join pfullshare sh2 sh3.\nProof.\n  intros [H H'].\n  unfold pfullshare in *.\n  unfold fullshare in *.\n  simpl in *.\n  rewrite Share.glb_commute in H.\n  rewrite Share.glb_top in H.\n  destruct sh2.\n  simpl in *.\n  subst.\n  destruct (shares.not_nonunit_bot Share.bot).\n  tauto.\nQed.\n\nLemma join_with_bot_r sh1 sh2 : join sh1 Share.bot sh2 -> sh1 = sh2.\nProof.\n  intros [H H'].\n  rewrite Share.lub_bot in H'.\n  auto.\nQed.\n\nLemma join_with_bot_l sh1 sh2 : join Share.bot sh1 sh2 -> sh1 = sh2.\n  intros [H H'].\n  rewrite Share.lub_commute in H'.\n  rewrite Share.lub_bot in H'.\n  auto.\nQed.\n\nLemma join_top_r sh1 sh3 : join sh1 Share.top sh3 -> sh1 = Share.bot.\nProof.\n  intros [H H'].\n  rewrite Share.glb_top in H.\n  auto.\nQed.\n\nLemma join_pshare_top_l (p1 p2 p3 : pshare) :\n  @join pshare _ p1 p2 p3 ->\n  pshare_sh p1 <> Share.top.\nProof.\n  destruct p1; simpl in *.\n  intros [H H'] ->.\n  simpl in *.\n  destruct p2 as [x n0]; simpl in *.\n  rewrite Share.glb_commute in H.\n  rewrite Share.glb_top in H.\n  subst x.\n  simpl in *.\n  subst.\n  destruct (shares.not_nonunit_bot Share.bot).\n  tauto.\nQed.\n\nLemma join_pshare_top_r (p1 p2 p3 : pshare) :\n  @join pshare _ p1 p2 p3 ->\n  pshare_sh p2 <> Share.top.\nProof.\n  intros j.\n  apply join_comm in j.\n  apply join_pshare_top_l in j; auto.\nQed.\n\n(*Got this ltac from permission.v maybe should factor*)\nLtac if_simpl:=\n  repeat match goal with\n         | [ H: ?X = true |- context[if ?X then _ else _] ] => rewrite H; simpl \n         | [ H: ?X = false |- context[if ?X then _ else _] ] => rewrite H; simpl \n         | [ H: ?X = left _ |- context[match ?X with left _ => _ | right _ => _ end] ]=>\n           rewrite H; simpl \n         | [ H: ?X = right _ |- context[match ?X with left _ => _ | right _ => _ end] ]=>\n           rewrite H; simpl \n         end.\nLemma top_aint_bot:\n  eq_dec Share.top Share.bot = right Share.nontrivial.\n  destruct (eq_dec Share.top Share.bot).\n  - exfalso; apply Share.nontrivial; auto.\n  - f_equal. apply proof_irr.\nQed.\n\n  \nLtac common_contradictions:=\n  match goal with\n  | [H: Share.glb _ _ = Share.top |- _ ] =>\n    exfalso;\n    eapply shares.glb_Rsh_not_top; eassumption\n    | [ H: Share.bot = Share.top |- _ ] => exfalso; apply Share.nontrivial; symmetry; assumption\n    | [ H: Share.top = Share.bot |- _ ] => exfalso; apply Share.nontrivial; assumption\n    | [ H: ~ shares.readable_share Share.top |- _ ] => pose proof shares.readable_share_top; contradiction\n    | [ H: ~ shares.writable_share Share.top |- _ ] => pose proof shares.writable_share_top; contradiction\n    | [ H: shares.readable_share Share.bot |- _ ] => pose proof shares.bot_unreadable; contradiction        \n    | [ H: shares.writable_share Share.bot |- _ ] => apply shares.writable_readable in H; pose proof shares.bot_unreadable; contradiction\n    | [ H: shares.writable_share ?sh, H0: ~ shares.readable_share ?sh   |- _ ] =>\n      exfalso; apply H0; eapply shares.writable_readable; assumption\n    | _ => contradiction \n    end.\n  \n  Ltac join_share_contradictions_oneside:=\n    match goal with\n    | [ H: @join Share.t _ Share.top _ _ |- _ ] =>\n      pose proof (join_top_l H); first [common_contradictions | subst]\n    | [ H: @join Share.t _ Share.bot _ _ |- _ ] =>\n      pose proof (join_with_bot_l _ _ H); first [common_contradictions | subst]\n    | [ H: @join Share.t _ _ _ Share.bot |- _ ] =>\n      pose proof (join_to_bot_l H); pose proof (join_to_bot_r H);\n      first [common_contradictions | subst]\n    | [ H1: ~ shares.readable_share ?sh1,\n        H2: ~ shares.readable_share ?sh2,\n            H: join ?sh1 ?sh2 _ |- _ ] =>\n      pose proof (shares.join_unreadable_shares H H1 H2);\n      first [common_contradictions | subst]\n    | [ H1: ~ shares.writable_share ?sh1,\n        H2: ~ shares.readable_share ?sh2,\n            H: join ?sh1 ?sh2 _ |- _ ] =>\n      pose proof (join_readable_unreadable _ _ _ H H1 H2);\n      first [common_contradictions | subst]\n    | [ H1: shares.writable_share ?sh1,\n        H2: shares.writable_share ?sh2,\n            H: join ?sh1 ?sh2 _ |- _ ] =>\n      exfalso; eapply shares.join_writable_readable;\n      try eapply shares.writable_readable; eassumption\n    | [ H1: shares.writable_share ?sh1,\n            H: join ?sh1 _ _ |- _ ] =>\n      pose proof (shares.join_writable1 H H1);\n      first [common_contradictions | subst]\n    | [ H1: shares.readable_share ?sh1,\n            H: join ?sh1 ?sh2 _ |- _ ] =>\n      pose proof (shares.join_readable1 H H1);\n      common_contradictions\n    end.\n  Ltac join_share_contradictions:=\n    try join_share_contradictions_oneside;\n    match goal with\n    | [ H: @join Share.t _ _ _ _ |- _ ] =>\n      apply join_comm in H; join_share_contradictions_oneside\n    end; try contradiction.\n\nLemma join_permjoin r1 r2 r3 :\n  join r1 r2 r3 ->\n  permjoin (perm_of_res r1) (perm_of_res r2) (perm_of_res r3).\nProof.\n  intros.\n  inversion H; subst;\n    try (destruct k);\n    try constructor;\n  functional induction (perm_of_sh sh1) using perm_of_sh_ind;\n    simpl; if_simpl;\n    repeat match goal with\n           | [  |- context [eq_dec Share.top Share.bot] ] => rewrite top_aint_bot \n           end;\n  functional induction (perm_of_sh sh2) using perm_of_sh_ind;\n    simpl; if_simpl;\n    repeat match goal with\n           | [  |- context [eq_dec Share.top Share.bot] ] => rewrite top_aint_bot \n           end;\n  functional induction (perm_of_sh sh3) using perm_of_sh_ind;\n  simpl; if_simpl;\n    repeat match goal with\n           | [  |- context [eq_dec Share.top Share.bot] ] => rewrite top_aint_bot \n           end;\n    try (do 2 join_share_contradictions);\n    unfold perm_of_sh; if_simpl; \n    try econstructor.\n    contradiction (join_readable_unreadable RJ _x _x2); apply writable_share_top.\n    contradiction (join_readable_unreadable RJ _x _x2).\n    contradiction (join_readable_unreadable (join_comm RJ) _x2 _x0); apply writable_share_top.\n    contradiction (join_readable_unreadable (join_comm RJ) _x2 _x0).\nQed.\n\nLemma join_permjoin_lock\n  : forall r1 r2 r3 ,\n    sepalg.join r1 r2 r3 ->\n    permjoin_def.permjoin\n      (perm_of_res_lock r1)\n      (perm_of_res_lock r2)\n      (perm_of_res_lock r3).\nProof.\n intros.\n inversion H; clear H; subst; simpl; try constructor;\n repeat match goal with\n | [ H: join ?sh _ _ , H1: shares.readable_share ?sh  |- _ ] =>\n   apply readable_glb in H1\n | [ H: join ?sh _ _ , H1: ~ shares.readable_share ?sh  |- _ ] =>\n   apply unreadable_glb in H1\n | [ H: join _ ?sh _ , H1: shares.readable_share ?sh  |- _ ] =>\n   apply readable_glb in H1\n | [ H: join _ ?sh _ , H1: ~ shares.readable_share ?sh  |- _ ] =>\n   apply unreadable_glb in H1\n | [ H: join _ _ ?sh , H1: shares.readable_share ?sh  |- _ ] =>\n   apply readable_glb in H1\n | [ H: join _ _ ?sh , H1: ~ shares.readable_share ?sh  |- _ ] =>\n   apply unreadable_glb in H1\n end;\n match goal with\n   | [ H: join _ _ _ |- _ ] => eapply compcert_rmaps.join_glb_Rsh in H \n end;\n   try (destruct k);\n    try constructor;\n  functional induction (perm_of_sh  (Share.glb Share.Rsh sh1)) using perm_of_sh_ind;\n    simpl; if_simpl;\n  functional induction (perm_of_sh  (Share.glb Share.Rsh sh2)) using perm_of_sh_ind;\n    simpl; if_simpl;\n  functional induction (perm_of_sh  (Share.glb Share.Rsh sh3)) using perm_of_sh_ind;\n  simpl; if_simpl;\n    repeat match goal with\n           | [  |- context [eq_dec Share.top Share.bot] ] => rewrite top_aint_bot \n           end;\n    try (unfold perm_of_sh; if_simpl; econstructor);\n    try (do 2 join_share_contradictions);\n  try eapply permjoin_None_l;\n  try eapply permjoin_None_r;\n  forget (Share.glb Share.Rsh sh1) as s1;\n  forget (Share.glb Share.Rsh sh2) as s2;\n  forget (Share.glb Share.Rsh sh3) as s3;\n  clear e e0 e1 e2 e3 e4 e5; subst;\n  try contradiction (join_readable_unreadable RJ _x _x2).\n  apply join_unit1_e in RJ; auto; subst; contradiction.\n  contradiction (join_readable_unreadable (join_comm RJ) _x2 _x0).\n  apply join_unit1_e in RJ; auto; subst; contradiction.\n  contradiction (join_readable_unreadable (join_comm RJ) _x2 _x0).\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/concurrency/permjoin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.19533598758092335}}
{"text": "Require Import Algebra.Utils Algebra.Monad SetoidUtils Algebra.SetoidCat.ListUtils Algebra.SetoidCat Algebra.Monad.StoreHeap Algebra.Monad.ContT Algebra.NearSemiRing Algebra.Monoid Tactics Algebra.FoldableFunctor Algebra.SetoidCat.PairUtils Algebra.Functor Algebra.Alternative Algebra.SetoidCat.MaybeUtils Algebra.Monad.Maybe Algebra.Applicative Algebra.SetoidCat.BoolUtils Algebra.SetoidCat.UnitUtils Algebra.Monoid.BoolUtils Algebra.Monoid.Alternative Algebra.Alternative.List Algebra.Functor.List Algebra.FoldableFunctor.List Algebra.Monad.Utils QAL.Command QAL.Definitions QAL.AbstractHeap QAL.AbstractStore.\n\nRequire Import Coq.Lists.List PeanoNat RelationClasses Relation_Definitions Morphisms Coq.Program.Basics SetoidClass.\n\nSection Aggregator.\n\n  Inductive qalAggregator :=\n  | cExists : qalAggregator\n  | cNot : qalAggregator\n  | cReturn : list var -> qalAggregator\n  .\n\n  Program Instance qalAggregatorS : Setoid qalAggregator.\n\nEnd Aggregator.\n\nModule QALAggregator (PT : PredType) (VT : ValType)\n       (S : AbstractStore VT) (H : AbstractHeap PT VT) : Aggregator PT VT S H.\n  Open Scope type_scope.\n  Module TS := Types PT VT S H.\n  Module CA := CommandAux PT VT S H.\n  Import VT S H TS CA.\n\n  Definition aggregator := qalAggregator.\n  Instance aggregatorS : Setoid aggregator := qalAggregatorS.\n      \n  Fixpoint _freeVarsAggregator (agg : aggregator) (fv : FVarSet.t) :=\n    match agg with\n      | cNot  => fv\n      | cExists  => fv\n      | cReturn _ => fv \n    end\n  .\n\n  Instance _freeVarsAggregator_Proper : Proper (equiv ==> equiv ==> equiv) _freeVarsAggregator.\n  Proof.\n    unfold Proper, respectful. intros. simpl in H. rewrite H. destruct y.\n    * simpl. auto.  \n    * simpl. auto. \n    * simpl. auto.\n  Qed.\n\n  Definition freeVarsAggregator := injF2 _freeVarsAggregator _.\n\n  \n\n  Section NegationGeneric.\n    Context\n      (a : H.l S.t _).\n    Definition negationGeneric : state unit := stopNotNull @ a.\n  End NegationGeneric.\n  Instance negationGeneric_Proper : Proper (equiv ==> equiv) negationGeneric.\n  Proof.\n    solve_properS negationGeneric.\n  Qed.\n  \n  Section ExistentialQuantificationGeneric.\n    Context\n      (a : H.l S.t _).\n    Definition existentialQuantificationGeneric : state unit :=\n      stopNull @ a.\n  End ExistentialQuantificationGeneric.\n  Instance existentialQuantificationGeneric_Proper : Proper (equiv ==> equiv) existentialQuantificationGeneric.\n  Proof.\n    solve_properS existentialQuantificationGeneric.\n  Qed.\n\n  Section ReturnGeneric.\n    Context\n      (vl : list var)\n      (a : H.l S.t _).\n    Definition _narrowStore (vl : list var) (s : S.t) : S.t :=\n      fold_right (fun v s2 => match s [ v ]s with\n                               | None => s2\n                               | Some val => S.update @ v @ val @ s2\n                            end) S.empty vl.\n\n    Instance _narrowStore_Proper : Proper (equiv ==> equiv ==> equiv) _narrowStore.\n    Proof.\n      unfold Proper, respectful. intros. generalize H  x0 y0 H0 . clear H x0 y0 H0.\n      apply list_ind_2 with (l1:=x) (l2:=y).\n      - intros. simpl. reflexivity.\n      - intros. inversion H0.\n      - intros. inversion H0.\n      - intros. inversion H0.\n        simpl. matchequiv. evalproper. simpl in H8. rewritesr. apply H.  auto.  auto. apply H. auto. auto.\n    Qed.\n\n    Definition narrowStore := injF2 _narrowStore _.\n\n    Definition returnGeneric : state unit :=\n      branchStore @ (narrowStore @ vl <$> a).\n  End ReturnGeneric.\n  Instance returnGeneric_Proper : Proper (equiv ==> equiv ==> equiv) returnGeneric.\n  Proof.\n    solve_properS returnGeneric.\n  Qed.\n \n\n  Fixpoint _interpretAggregator (agg : aggregator) (a : H.l S.t _)  : state unit :=\n    match agg with\n      | cNot =>\n        negationGeneric a\n      | cExists =>\n        existentialQuantificationGeneric a\n      | cReturn vl => returnGeneric vl a\n    end\n  .\n\n  Instance _interpretAggregator_Proper : Proper (equiv ==> equiv ==> equiv) _interpretAggregator.\n  Proof.\n    unfold Proper, respectful. intros. simpl in H. rewrite H. destruct y.\n    * simpl. arrequiv. \n    * simpl. arrequiv.\n    * simpl. arrequiv.\n  Qed.\n\n  Definition interpretAggregator := injF2 _interpretAggregator _.\n\nEnd QALAggregator.\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/QAL/Concrete/Aggregator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.19533597738395045}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend   Require Csem.\n\nFrom trancert.invariants  Require EnvsDisjoint.\nFrom trancert.analysis    Require ContinuationQuant.\nFrom trancert.properties  Require Env.\nFrom trancert.axioms      Require NoFreeLocals.\n\nImport\n  Csyntax\n  Csem\n  EnvsDisjoint\n  lib.All\n  Coqlib\n  properties.Env\n  properties.State\n  Memory.Mem\n  Maps.PTree\n  StateQuant\n  ContinuationQuant\n  invariants.Common\n  Estate\n  CsemAugmented\n  NoFreeLocals.\n\nSection Instance.\n\n  Variable p: program.\n\n  Open Scope positive.\n\n  (** All addresses corresponding to local variables have [Freeable]\npremissions. This is a universal invariant.\n\n  Remark: this applies only to the live variables, whose host functions are\n  being executed. Once the function returns and is removed from continuation and\n  program state, its local variables are deallocated; such variables are outside\n  of the scope of this invariant. Deallocation in CompCert does not remove\n  blocks from memory but only marks them as such (by lowering their permissions\n  below [Freeable]).\n *)\n\n  Record state_env_freeable (s:estate) : Prop :=\n    {\n      (* requires this invariant, proven separately *)\n      sef_disjoint: envs_disjoint s ;\n      sef_freeable:\n        forall m, estate_mem s m ->\n             forall_envs_in_estate (fun _ _ => env_freeable (Csem.globalenv p) m) s;\n    }.\n\n  (** This hypothesis is required because the proof relies on\n  [ec_other_envs_freeable] and [ec_env_freeable] properties. See\n  [remove_local.Extcall].\n\n  Informally, the need for these hypothesis is the following. In CompCert, all\n  blocks are alike, whether they were allocated by a C function [malloc] or\n  automatically as local variables. Block deallocation is performed by either\n  calling [free] explicitly on dynamic memory, or implicitly by performing one\n  of \"return from function\" transitions like [step_return_1].\n  There is no constraint that prohibits an external function from freeing a\n  local variable, even though in real world such programs are impossible to\n  craft without relying on compiling and runtime details.\n\n  A constraint [ec_other_envs_freeable] guarantees that the locals of the current\n  functions are not freed by an external call; another constraint [ec_env_freeable]\n  guarantees that the locals of all other functions (whose local environments\n  are stored in the continuation) will not be freed by an external call.\n   *)\n  Hypothesis Hlocals_free: locals_stay_free_axiom.\n\n\n  Theorem correct: invariant (semantics p) state_env_freeable.\n  Proof.\n    econstructor.\n    - constructor; intros.\n      + edestruct EnvsDisjoint.correct; eauto.\n      + inv H.\n        constructor; intros; estate_components.\n        constructor.\n    - econstructor; inv H.\n      + edestruct EnvsDisjoint.correct. by eapply inv_stability; eauto.\n      +\n        pose s1 := x1.\n        pose s2 := x2.\n\n        destruct H0 as [Hestep|Hsstep].\n        * intros m H; estate_components; inv Hestep.\n          ** inv H3; constructor; intros; estate_components; eapply sef_freeable0; constructor.\n          ** inv H3; constructor; intros; estate_components; try by (eapply sef_freeable0; constructor).\n             *** inv sef_disjoint0.\n                 intros i b0 t1 H1 x H2.\n                 eapply Assign.assign_loc_perm; eauto.\n                 eapply sef_freeable0; eauto; constructor.\n             *** inv sef_disjoint0.\n                 exploit sef_freeable0; try by constructor.\n                 inversion 1.\n                 exploit aeis_cont; try by constructor.\n                 move => ?; eapply econt_cond_impl; eauto.\n                 repeat constructor; simpl => _ ? ? Henv ? ? ? ? ? ?.\n                 intros.\n                 eapply Assign.assign_loc_perm; eauto.\n                 eapply Henv; eauto.\n             *** exploit sef_freeable0; try by constructor.  \n                 edestruct (Hlocals_free ef); eauto; first by\n                 (left; eapply step_rred; eauto; eapply red_builtin; eauto).\n                 **** econstructor.\n                 **** econstructor.\n                 **** eapply sef_disjoint0.\n                 **** eapply sef_freeable0; constructor.\n                 **** intro Hfreeable.\n                      inv Hfreeable.\n                      eapply aeis_current; constructor.\n             *** exploit sef_freeable0; try by constructor. \n                 edestruct (Hlocals_free ef); eauto; first by\n                 (left; eapply step_rred; eauto; eapply red_builtin; eauto).\n                 **** econstructor.\n                 **** econstructor.\n                 **** eapply sef_disjoint0.\n                 **** eapply sef_freeable0; constructor.\n                 **** intro Hfreeable.\n                      inv Hfreeable.\n                      eapply aeis_cont; constructor.\n          ** inv H3.\n             exploit sef_freeable0; try by constructor.\n             intros [].\n             constructor; intros; estate_components.\n             *** econstructor; simpl in *; eauto; try by constructor.\n                 **** eapply aeis_cont; econstructor.\n                 **** eapply aeis_current; econstructor.\n             *** econstructor; simpl in *; eauto; try by constructor.\n                 **** eapply aeis_cont; econstructor.\n                 **** eapply aeis_current; econstructor.\n        * (* sstep *)\n          intros m H; estate_components; inv Hsstep;\n            exploit sef_freeable0; try solve [econstructor]; intros [];\n              constructor; intros; estate_components;\n              try solve [\n                    by eapply aeis_current; constructor|\n                    by exploit aeis_cont; constructor|\n                      by exploit aeis_cont; solve [by constructor| by inversion 1 | by inversion 1; constructor] \n                  ].\n          ** by eapply aeis_cont; constructor.\n          ** exploit aeis_cont; try by constructor.\n             intros.\n             apply econt_cond_call_econt in H.\n             eapply find_label_econt_cond_rec in H2; eauto.\n             *** by decomp.\n             *** apply env_only_always_local.\n             *** constructor.\n          ** eapply BindParameters.bind_parameters_env_freeable_any; eauto.\n             eapply Alloc.alloc_variables_freeable_after; eauto.\n             unfold env_freeable. intros ? ? ?.  by rewrite gempty.\n          ** exploit aeis_cont; try constructor.\n             intros; eapply econt_cond_impl; eauto.\n             repeat constructor.\n             intros f e0 i H0.\n             eapply BindParameters.bind_parameters_env_freeable_any; eauto.\n             by eapply Alloc.alloc_variables_freeable_any; eauto.\n          ** econstructor.\n             *** eapply aeis_cont; constructor.\n             *** clear. induction sl; by constructor.\n          ** eapply econt_cond_call_econt_f; eauto.\n             *** inv sef_disjoint0.\n                 inv ed_envs_disjoint.\n                 eapply Free.free_list_env_freeable; eauto.\n                 by eapply aeis_cont; constructor.\n          ** eapply econt_cond_call_econt_f; eauto.\n             *** inv sef_disjoint0.\n                 inv ed_envs_disjoint.\n                 inv H0.\n                 eapply Free.free_list_env_freeable; eauto.\n                 exploit aeis_cont; try by constructor.\n                 inversion 1. eassumption.\n          ** exploit aeis_cont; try by constructor.\n             intros.\n             eapply econt_cond_kcall_f_indep; eauto.\n             eapply Free .free_list_env_freeable; eauto.\n             inv sef_disjoint0.\n             by inv ed_envs_disjoint.\n          **\n             exploit (Hlocals_free ef m0 m (Csem.globalenv p) t0 ).\n             *** right; constructor; eassumption.\n             *** econstructor.\n             *** econstructor.\n             *** eapply sef_disjoint0.\n             *** eassumption.\n             *** econstructor; intros; estate_components.\n                 eapply aeis_cont; constructor.\n             *** inversion 1. eapply aeis_cont0; constructor.\n  Qed.\n\nEnd Instance.\n\nHint Resolve correct : invariants.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/invariants/EnvsFreeable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.1953359761435814}}
{"text": "(******************************************************************************)\n(** Generic Semantics                                                         *)\n(******************************************************************************)\n\nFrom Coq Require Import ssreflect.\nFrom Coq Require Import List.\nImport ListNotations.\n\nFrom Bits Require Import bits.\nFrom mathcomp Require Import eqtype tuple.\n\nFrom BIRD Require Import Bits Util.\nFrom BIRD Require Import GenericSyntax.\n\nDeclare Scope bird_scope.\nDelimit Scope bird_scope with bird.\n\n(******************************************************************************)\n(*** STATE PART                                                               *)\n(******************************************************************************)\n\nSection STATEPART.\n\n  Variable (Cell : Type).\n  Variable (Annot : Type).\n\n  Local Notation the_src := (source Cell Annot).\n  Local Notation the_dst := (destination Cell Annot).\n\n  Definition source_word_size `{IsCell Cell Annot} (src : the_src) : word_size :=\n    match src with\n    | src_imm  _   => QWORD\n    | src_addr a   => fst a\n    | src_expr e   => QWORD\n    | src_cell c a => cell_word_size c a\n    | src_rip      => QWORD\n    end.\n\n  Definition destination_word_size `{IsCell Cell Annot} (dst : the_dst) : word_size :=\n    match dst with\n    | dst_addr a   => fst a\n    | dst_cell c a => cell_word_size c a\n    end.\n\n  Definition source_word_type      `{IsCell Cell Annot} (src : the_src)\n    := word_type (source_word_size src).\n  Definition destination_word_type `{IsCell Cell Annot} (dst : the_dst)\n    := word_type (destination_word_size dst).\n\nEnd STATEPART.\n\n(******************************************************************************)\n(*** STATE                                                                    *)\n(******************************************************************************)\n\nSection STATE.\n\n  Local Open Scope bird.\n\n  Variable (Cell Annot Label : Type).\n  Context `{IsLabel Label}.\n\n  Definition memory := abs_addr -> byte.\n  Definition flags  := flag -> bit.\n  Definition cells  := Cell -> qword.\n  Definition rip    := Label.\n\n  Class IsCellState `{IsCell Cell Annot} :=\n      { cells_read        : cells -> forall c a, cell_word_type c a\n      ; cells_write       : cells -> forall c a, cell_word_type c a -> cells\n      ; cells_read_qword  : cells -> Cell -> qword\n      ; cells_write_qword : cells -> Cell -> qword -> cells\n      }.\n\n  Record state := mk_state\n    { state_mem   : memory\n    ; state_flags : flags\n    ; state_cells : cells\n    ; state_rip   : rip\n    }.\n\n  Definition _0 : qword := (#0, #0, #0, #0, #0, #0, #0, #0).\n  Definition _1 : qword := (#0, #0, #0, #0, #0, #0, #0, #1).\n  Definition _2 : qword := (#0, #0, #0, #0, #0, #0, #0, #2).\n  Definition _3 : qword := (#0, #0, #0, #0, #0, #0, #0, #3).\n  Definition _4 : qword := (#0, #0, #0, #0, #0, #0, #0, #4).\n  Definition _5 : qword := (#0, #0, #0, #0, #0, #0, #0, #5).\n  Definition _6 : qword := (#0, #0, #0, #0, #0, #0, #0, #6).\n  Definition _7 : qword := (#0, #0, #0, #0, #0, #0, #0, #7).\n  Definition _8 : qword := (#0, #0, #0, #0, #0, #0, #0, #8).\n\n  Definition memory_read (m : memory) (a : addr Cell) (f : Cell -> qword) : addr_word_type a :=\n    let '(s, e) := a in\n    let b (offset : abs_addr) := m ((addr_expr_eval e f) + offset) in\n    match s as s' return addr_word_type (s', e) with\n    | BYTE  =>                                            b _0\n    | WORD  =>                                     (b _1, b _0)\n    | DWORD =>                         (b _3, b _2, b _1, b _0)\n    | QWORD => (b _7, b _6, b _5, b _4, b _3, b _2, b _1, b _0)\n    end.\n\n  Definition memory_write (m : memory) (a : addr Cell) (f : Cell -> qword) (v : addr_word_type a) : memory.\n    destruct a as [s e].\n    set e_val := addr_expr_eval e f.\n    set w := fun (m : memory) (b : byte) (offset : abs_addr) a' => if a' == e_val + offset then b else m a'.\n    case s eqn:?.\n    - exact (w m v _0).\n    - destruct v as [v0 v1].\n      exact (w (w m v0 _0) v1 _1).\n    - destruct v as (((v0&v1)&v2)&v3).\n      exact (w (w (w (w m v0 _0) v1 _1) v2 _2) v3 _3).\n    - destruct v as (((((((v0&v1)&v2)&v3)&v4)&v5)&v6)&v7).\n      exact (w (w (w (w (w (w (w (w m v0 _0) v1 _1) v2 _2) v3 _3) v4 _4) v5 _5) v6 _6) v7 _7).\n  Defined.\n\n  Definition flags_read  (F : flags) (f : flag) : bit := F f.\n  Definition flags_write (F : flags) (f : flag) (v : bit) : flags := fun g => if flag_eqb f g then v else F g.\n\n  Definition state_read `{IsCellState} `{IsLabel Label}\n    (s : state) (src : source Cell Annot) : source_word_type _ _ src :=\n    match src as src' return source_word_type _ _ src' with\n    | src_imm  i   => i\n    | src_addr a   => memory_read (state_mem s) a (cells_read_qword (state_cells s))\n    | src_expr e   => addr_expr_eval e (cells_read_qword (state_cells s))\n    | src_cell c a => cells_read (state_cells s) c a\n    | src_rip      => label_value (state_rip s)\n    end.\n\n  Definition state_read_qword `{IsCellState} `{IsLabel Label}\n    (s : state) (src : source Cell Annot) : qword.\n  Proof.\n    set v := state_read s src.\n    unfold source_word_type in v.\n    unfold source_word_size in v.\n    case src eqn:? ; cbn in *.\n    - exact v.\n    - destruct a. case w eqn:? ; cbn in v.\n        + exact (insert _0 low8 v).\n        + exact (insert _0 low16 v).\n        + exact (insert _0 low32 v).\n        + exact (insert _0 full64 v).\n    - exact v.\n    - exact (insert _0 (cell_word_pattern c a) v).\n    - exact v.\n  Defined.\n\n  Definition state_write `{IsCellState}\n    (s : state) (dst : destination Cell Annot) (v : destination_word_type _ _ dst) : state :=\n    let M := state_mem s in\n    let F := state_flags s in\n    let C := state_cells s in\n    let R := state_rip s in\n    match dst as dst' return dst = dst' -> destination_word_type _ _ dst' -> state with\n    | dst_addr a => fun _ v' =>\n                      let mem' := memory_write (state_mem s) a (cells_read_qword (state_cells s)) v' in\n                      {| state_mem := mem' ; state_flags := F ; state_cells := C ; state_rip := R |}\n    | dst_cell c a => fun _ v' =>\n                        let cells' := cells_write (state_cells s) c a v' in\n                        {| state_cells := cells' ; state_flags := F ; state_mem := M ; state_rip := R |}\n    end Logic.eq_refl v.\n\n  Definition state_write_qword `{IsCellState} `{IsLabel Label}\n    (s : state) (dst : destination Cell Annot) (v : qword) : state.\n  Proof.\n    set t := (destination_word_type _ _ dst).\n    unfold destination_word_type in t.\n    case (destination_word_size _ _ dst) eqn:F.\n    - set v' := extract v low8. cbn in v'.\n      have T: (byte = destination_word_type _ _ dst) by unfold destination_word_type ; rewrite F.\n      exact s.\n    - set v' := extract v low16. cbn in v'.\n      have T: (word = destination_word_type _ _ dst) by unfold destination_word_type ; rewrite F.\n      exact s.\n    - set v' := extract v low32. cbn in v'.\n      have T: (dword = destination_word_type _ _ dst) by unfold destination_word_type ; rewrite F.\n      exact s.\n    - set v' := extract v full64. cbn in v'.\n      have T: (qword = destination_word_type _ _ dst) by unfold destination_word_type ; rewrite F.\n      exact s.\n  Defined.\n\n\n  Definition state_write_rip (s : state) (r : rip) : state :=\n    let M := state_mem s in\n    let F := state_flags s in\n    let C := state_cells s in\n    mk_state M F C r.\n\n  Definition state_inc_rip {p : program Cell Annot Label} (s : state) (i : instruction Cell Annot Label (prog_nodes _ _ _ p)) : state :=\n    let rip := label_value (state_rip s) in state_write_rip s (label_unvalue (qword_add rip _8)).\n\nEnd STATE.\n\nSection DENOTATION.\n\n  Variables (Cell Label Annot : Type).\n\n  Local Notation the_dst := (destination Cell Annot).\n  Local Notation the_src := (source Cell Annot).\n  Local Notation the_state := (state Cell Annot).\n\n  (* Few implementations for presentation purposes, other follow *)\n  (* when this is integrated into the rest of the decompiler *)\n\n  Definition computation_1_1 (opcode : opcode_1_1) : option (qword -> qword) :=\n    match opcode with\n    | op_inc => Some (fun a => qword_add a _1)\n    | _ => None\n    end.\n\n  Definition computation_2_1 (opcode : opcode_2_1) : option (qword -> qword -> qword) :=\n    match opcode with\n    | op_add => Some qword_add\n    | _ => None\n    end.\n\n  Definition computation_2_2 (opcode : opcode_2_2) : option (qword -> qword -> (qword * qword)%type) :=\n    match opcode with\n    | op_xchg => Some (fun a b => (b, a))\n    | _ => None\n    end.\n\n  Definition effect_1_1 (opcode : opcode_1_1) : option (qword -> flags -> flags) :=\n    match opcode with\n    | op_inc => Some (fun a s => let '(c, a') := qword_addc a _1 in\n                                 let s' := flags_write s zero_flag (a' == _0)%bool in\n                                 flags_write s' carry_flag c\n                  )\n    | _ => None\n    end.\n\n  Definition effect_2_0 (opcode : opcode_2_0) : option (qword -> qword -> flags -> flags) :=\n    match opcode with\n    | op_cmp => Some (fun a b s => let '(b, z) := qword_subb a b in\n                                   flags_write s zero_flag (negb b && (z == _0))%bool)\n    | _ => None\n    end.\n\n  Definition effect_2_1 (opcode : opcode_2_1) : option (qword -> qword -> flags -> flags) :=\n    match opcode with\n    | op_add => Some (fun a b s => let '(c, r) := qword_addc a b in\n                                  let s' := flags_write s zero_flag (r == _0)%bool in\n                                 flags_write s' carry_flag c)\n    | _ => None\n    end.\n\n  Definition effect_2_2 (opcode : opcode_2_2) : option (qword -> qword -> flags -> flags) :=\n    match opcode with\n    | op_xchg => Some (fun a b s => s)\n    | _ => None\n    end.\n\n  Definition condition (op : opcode_cond) : option (flags -> bool) :=\n    match op with\n    | op_jnz => Some (fun fs => negb (flags_read fs zero_flag))\n    | op_jz => Some (fun fs => (flags_read fs zero_flag))\n    | _ => None\n    end.\n\n  Definition run_effect_1 (s : the_state) (e : qword -> flags -> flags) (v : qword) :=\n    let M := state_mem _ _ s in\n    let F := e v (state_flags _ _ s) in\n    let C := state_cells _ _ s in\n    let R := state_rip _ _ s in\n    mk_state _ _ M F C R.\n\n  Definition run_effect_2 (s : the_state) (e : qword -> qword -> flags -> flags) (v1 : qword) (v2 : qword) :=\n    let M := state_mem _ _ s in\n    let F := e v1 v2 (state_flags _ _ s) in\n    let C := state_cells _ _ s in\n    let R := state_rip _ _ s in\n    mk_state _ _ M F C R.\n\nEnd DENOTATION.\n\nSection SEMANTICS.\n\n  Variables (Cell Annot Label : Type).\n\n  Local Notation the_prog  := (program Cell Annot Label).\n  Local Notation the_instr := (instruction Cell Annot Label).\n  Local Notation the_node  := (node Cell Annot Label).\n  Local Notation the_state := (state Cell Label).\n  Local Notation the_phis  := (phi_block Cell).\n  Local Notation the_phi   := (phi_instruction Cell).\n  Local Notation the_src   := (source Cell Annot).\n  Local Notation the_dst   := (destination Cell Annot).\n\n  Definition run_phi `{IsCellState Cell Annot} (n : nat) (p : the_phi) (\u03c3 : the_state) : the_state :=\n    if List.nth_error (phi_srcs _ p) n is Some s\n    then\n      let \u03b8  := state_mem _ _ \u03c3 in\n      let \u03be  := state_flags _ _ \u03c3 in\n      let \u03b3  := state_cells _ _ \u03c3 in\n      let \u03c1  := state_rip _ _ \u03c3 in\n      let v  := cells_read_qword _ _ \u03b3 s in\n      let \u03b3' := cells_write_qword _ _ \u03b3 (phi_dst _ p) v in\n      mk_state _ _ \u03b8 \u03be \u03b3' \u03c1\n    else \u03c3.\n\n  Fixpoint run_phis `{IsCellState Cell Annot} (n : nat) (ps : the_phis) (\u03c3 : the_state) : the_state :=\n    match ps with\n    | []     => \u03c3\n    | p::ps' => run_phis n ps' (run_phi n p \u03c3)\n    end.\n\n  Inductive phi_step `{EqDec Label} `{IsCellState Cell Annot} (p : the_prog) :\n    the_node p -> the_state -> the_node p -> the_state -> Prop :=\n  | phi_step_block (k\u2081 k\u2082 : the_node p) (\u03c3\u2081 \u03c3\u2082 : the_state) n :\n    is_nth_pred _ _ _ k\u2081 k\u2082 n ->\n    \u03c3\u2082 = run_phis n (phi _ _ _ k\u2082) \u03c3\u2081 ->\n    phi_step p k\u2081 \u03c3\u2081 k\u2082 \u03c3\u2082.\n\n  Inductive instr_step `{EqDec Label} `{IsCellState Cell Annot} `{IsLabel Label} (p : the_prog) :\n    the_node p -> the_state -> option (the_node p) -> the_state -> Prop :=\n\n  | step_nop k1 k2 s1 s2 :\n    instr _ _ _ k1 = instr_nop _ _ _ _ k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    instr_step p k1 s1 (Some k2) s2\n\n  | step_hlt k s :\n    instr _ _ _ k = instr_hlt _ _ _ _ ->\n    instr_step p k s None s\n\n  | step_1_1 op dst src k1 k2 s1 s2 s3 s4 d f v :\n    instr _ _ _ k1 = instr_1_1 _ _ _ _ op dst src k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    Some d = computation_1_1 op ->\n    Some f = effect_1_1 op ->\n    v = state_read_qword _ _ _ s1 src ->\n    s3 = state_write_qword _ _ _ s2 dst (d v) ->\n    s4 = run_effect_1 _ _ s3 f v ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_2_0 op src1 src2 k1 k2 s1 s2 s4 f v1 v2 :\n    instr _ _ _ k1 = instr_2_0 _ _ _ _ op src1 src2 k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    Some f = effect_2_0 op ->\n    v1 = state_read_qword _ _ _ s1 src1 ->\n    v2 = state_read_qword _ _ _ s1 src2 ->\n    s4 = run_effect_2 _ _ s2 f v1 v2 ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_2_1 op dst src1 src2 k1 k2 s1 s2 s3 s4 d f v1 v2 :\n    instr _ _ _ k1 = instr_2_1 _ _ _ _ op dst src1 src2 k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    Some d = computation_2_1 op ->\n    Some f = effect_2_1 op ->\n    v1 = state_read_qword _ _ _ s1 src1 ->\n    v2 = state_read_qword _ _ _ s1 src2 ->\n    s3 = state_write_qword _ _ _ s2 dst (d v1 v2) ->\n    s4 = run_effect_2 _ _ s3 f v1 v2 ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_2_2 op dst1 dst2 src1 src2 k1 k2 s1 s2 s3 s4 s5 d f v1 v2 v1' v2' :\n    instr _ _ _ k1 = instr_2_2 _ _ _ _ op dst1 dst2 src1 src2 k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    Some d = computation_2_2 op ->\n    Some f = effect_2_2 op ->\n    v1 = state_read_qword _ _ _ s1 src1 ->\n    v2 = state_read_qword _ _ _ s1 src2 ->\n    v1' = fst (d v1 v2) ->\n    v2' = snd (d v1 v2) ->\n    s3 = state_write_qword _ _ _ s2 dst1 v1' ->\n    s4 = state_write_qword _ _ _ s2 dst2 v2' ->\n    s5 = run_effect_2 _ _ s5 f v1 v2 ->\n    instr_step p k1 s1 (Some k2) s5\n\n  | step_push (sp_s sp_d : Cell) src k1 k2 s1 s2 s3 s4 v sz :\n    instr _ _ _ k1 = instr_push _ _ _ _ sp_s sp_d src k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    v = state_read_qword _ _ _ s1 src ->\n    s3 = state_write_qword _ _ _ s2 (dst_addr _ _ (sz, mk_addr_expr _ (Some sp_s) None scale1 _0)) v ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_pop (sp_s sp_d : Cell) dst k1 k2 s1 s2 s3 s4 v sz :\n    instr _ _ _ k1 = instr_pop _ _ _ _ dst sp_s sp_d k2 ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    v = state_read_qword _ _ _ s1 (src_addr _ _ (sz, mk_addr_expr _ (Some sp_s) None scale1 _0)) ->\n    s3 = state_write_qword _ _ _ s2 dst v ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_jmp src k1 k2 k_t s1 s2 :\n    instr _ _ _ k1 = instr_jmp _ _ _ _ src k_t ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    In k2 k_t ->\n    instr_step p k1 s1 (Some k2) s2\n\n  | step_cjmp cond src k1 k2 k_t k_f s1 s2 c :\n    instr _ _ _ k1 = instr_cjmp _ _ _ _ cond src k_t k_f ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    Some c = condition cond ->\n    (c (state_flags _ _ s1) = true  -> In k2 k_t) ->\n    (c (state_flags _ _ s1) = false -> k2 = k_f) ->\n    instr_step p k1 s1 (Some k2) s2\n\n  | step_call (sp_s sp_d : Cell) src k1 k2 kc kr s1 s2 s3 s4 v :\n    instr _ _ _ k1 = instr_call _ _ _ _ sp_s sp_d src kc kr ->\n    s2 = state_write_rip _ _ s1 (proj1_sig kr) ->\n    v = state_read_qword _ _ _ s1 src ->\n    label_value (proj1_sig k2) = v ->\n    In k2 kc ->\n    s3 = state_write_qword _ _ _ s2 (dst_addr _ _ (QWORD, mk_addr_expr _ (Some sp_s) None scale1 _0)) (label_value (proj1_sig kr)) ->\n    instr_step p k1 s1 (Some k2) s4\n\n  | step_ret (sp_s sp_d : Cell) k1 k2 s1 s2 v kr :\n    instr _ _ _ k1 = instr_ret _ _ _ _ sp_s sp_d kr ->\n    s2 = state_write_rip _ _ s1 (proj1_sig k2) ->\n    In k2 kr ->\n    v = state_read_qword _ _ _ s1 (src_addr _ _ (QWORD, mk_addr_expr _ (Some sp_s) None scale1 _0)) ->\n    label_value (proj1_sig k2) = v ->\n    instr_step p k1 s1 (Some k2) s2\n    .\n\n    Inductive step_star `{EqDec Label} `{IsCellState Cell Annot} `{IsLabel Label} (p : the_prog) :\n      the_node p -> the_state -> option (the_node p) -> the_state -> Prop  :=\n\n    | step_terminal s1 s2 k :\n      instr_step p k s1 None s2 ->\n      step_star  p k s1 None s2\n\n    | step_nonterminal s1 s2 s3 s4 k1 k2 k3 k4 :\n      instr_step p k1 s1 (Some k2) s2 ->\n      phi_step   p k2 s2 k3 s3 ->\n      step_star  p k3 s3 k4 s4 ->\n      step_star  p k1 s1 k4 s4\n\n      .\n\nEnd SEMANTICS.\n", "meta": {"author": "proof-by-sledgehammer", "repo": "BIRD", "sha": "50ba5eee27301cee326f6c57bbd511cada2c80a8", "save_path": "github-repos/coq/proof-by-sledgehammer-BIRD", "path": "github-repos/coq/proof-by-sledgehammer-BIRD/BIRD-50ba5eee27301cee326f6c57bbd511cada2c80a8/GenericSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.19528548962214484}}
{"text": "Require Import RelationClasses.\n\nFrom sflib Require Import sflib.\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 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.\n\nSet Implicit Arguments.\n\n\nModule ThreadEvent.\n  Variant t :=\n  | promise (loc: Loc.t)\n  | reserve (loc: Loc.t) (from to: Time.t)\n  | cancel (loc: Loc.t) (from to: Time.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)\n           (releasedr releasedw: option View.t) (ordr ordw: Ordering.t)\n  | fence (ordr ordw: Ordering.t)\n  | syscall (e: Event.t)\n  | failure\n  | racy_read (loc: Loc.t) (to: option Time.t) (val: Const.t) (ord: Ordering.t)\n  | racy_write (loc: Loc.t) (to: option Time.t) (val: Const.t) (ord: Ordering.t)\n  | racy_update (loc: Loc.t) (to: option Time.t) (valr valw: Const.t) (ordr ordw: Ordering.t)\n  .\n  #[global] Hint Constructors t: core.\n\n  Definition get_event (e: t): option Event.t :=\n    match e with\n    | syscall e => Some e\n    | _ => None\n    end.\n\n  Definition get_program_event (e: t): ProgramEvent.t :=\n    match e with\n    | read loc _ val _ ord => ProgramEvent.read loc val ord\n    | write loc _ _ val _ ord => ProgramEvent.write loc val ord\n    | update loc _ _ valr valw _ _ ordr ordw => ProgramEvent.update loc valr valw ordr ordw\n    | fence ordr ordw => ProgramEvent.fence ordr ordw\n    | syscall ev => ProgramEvent.syscall ev\n    | failure => ProgramEvent.failure\n    | racy_read loc _ val ord => ProgramEvent.read loc val ord\n    | racy_write loc _ val ord => ProgramEvent.write loc val ord\n    | racy_update loc _ valr valw ordr ordw => ProgramEvent.update loc valr valw ordr ordw\n    | _ => ProgramEvent.silent\n    end.\n\n  Definition get_machine_event (e: t): MachineEvent.t :=\n    match e with\n    | syscall e => MachineEvent.syscall e\n    | failure\n    | racy_write _ _ _ _\n    | racy_update _ _ _ _ _ _ => MachineEvent.failure\n    | _ => MachineEvent.silent\n    end.\n\n  Definition get_machine_event_pf (e: t): MachineEvent.t :=\n    match e with\n    | syscall e => MachineEvent.syscall e\n    | failure\n    | racy_read _ _ _ _\n    | racy_write _ _ _ _\n    | racy_update _ _ _ _ _ _ => MachineEvent.failure\n    | _ => MachineEvent.silent\n    end.\n\n  Definition is_reading (e:t): option (Loc.t * Time.t * Const.t * option View.t * Ordering.t) :=\n    match e with\n    | read loc ts val released ord => Some (loc, ts, val, released, ord)\n    | update loc tsr _ valr _ releasedr _ ordr _ => Some (loc, tsr, valr, releasedr, ordr)\n    | _ => None\n    end.\n\n  Definition is_writing (e:t): option (Loc.t * Time.t * Time.t * Const.t * option View.t * Ordering.t) :=\n    match e with\n    | write loc from to val released ord => Some (loc, from, to, val, released, ord)\n    | update loc tsr tsw _ valw _ releasedw _ ordw => Some (loc, tsr, tsw, valw, releasedw, ordw)\n    | _ => None\n    end.\n\n  Definition is_accessing (e:t): option (Loc.t * Time.t) :=\n    match e with\n    | read loc ts _ _ _ => Some (loc, ts)\n    | write loc _ ts _ _ _ => Some (loc, ts)\n    | update loc _ ts _ _ _ _ _ _ => Some (loc, ts)\n    | _ => None\n    end.\n\n  Definition is_accessing_loc (l: Loc.t) (e: t): Prop :=\n    match e with\n    | read loc _ _ _ _\n    | write loc _ _ _ _ _\n    | update loc _ _ _ _ _ _ _ _\n    | racy_read loc _ _ _\n    | racy_write loc _ _ _\n    | racy_update loc _ _ _ _ _ => loc = l\n    | _ => False\n    end.\n\n  Definition is_racy (e: t): Prop :=\n    match e with\n    | racy_read _ _ _ _\n    | racy_write _ _ _ _\n    | racy_update _ _ _ _ _ _ => True\n    | _ => False\n    end.\n\n  Definition is_racy_promise (e: t): Prop :=\n    match e with\n    | racy_read _ None _ _\n    | racy_write _ None _ _ => True\n    | racy_update _ None _ _ ordr ordw =>\n        Ordering.le Ordering.plain ordr /\\\n        Ordering.le Ordering.plain ordw\n    | _ => False\n    end.\n\n  Definition is_sc (e: t): Prop :=\n    match e with\n    | fence _ ordw => Ordering.le Ordering.seqcst ordw\n    | syscall _ => True\n    | _ => False\n    end.\n\n  Definition is_pf (e: t): Prop :=\n    match e with\n    | promise _\n    | reserve _ _ _ => False\n    | _ => True\n    end.\n\n  Definition is_internal (e: t): Prop :=\n    match e with\n    | promise _\n    | reserve _ _ _\n    | cancel _ _ _ => True\n    | _ => False\n    end.\n\n  Definition is_program (e: t): Prop :=\n    match e with\n    | promise _\n    | reserve _ _ _\n    | cancel _ _ _ => False\n    | _ => True\n    end.\n\n  Definition is_silent (e: t): Prop :=\n    get_machine_event e = MachineEvent.silent.\n\n  Lemma eq_program_event_eq_loc\n        e1 e2 loc\n        (EVENT: get_program_event e1 = get_program_event e2):\n    is_accessing_loc loc e1 <-> is_accessing_loc loc e2.\n  Proof.\n    unfold is_accessing_loc.\n    destruct e1, e2; ss; inv EVENT; ss.\n  Qed.\nEnd ThreadEvent.\n\n\nModule Local.\n  Structure t := mk {\n    tview: TView.t;\n    promises: BoolMap.t;\n    reserves: Memory.t;\n  }.\n\n  Definition init := mk TView.bot BoolMap.bot Memory.bot.\n\n  Variant is_terminal (lc:t): Prop :=\n  | is_terminal_intro\n      (PROMISES: promises lc = BoolMap.bot)\n  .\n  #[global] Hint Constructors is_terminal: core.\n\n  Variant wf (lc: t) (gl: Global.t): Prop :=\n  | wf_intro\n      (TVIEW_WF: TView.wf (tview lc))\n      (TVIEW_CLOSED: TView.closed (tview lc) (Global.memory gl))\n      (PROMISES: BoolMap.le (promises lc) (Global.promises gl))\n      (PROMISES_FINITE: BoolMap.finite (promises lc))\n      (RESERVES: Memory.le (reserves lc) (Global.memory gl))\n      (RESERVES_ONLY: Memory.reserve_only (reserves lc))\n      (RESERVES_FINITE: Memory.finite (reserves lc))\n  .\n  #[global] Hint Constructors wf: core.\n\n  Lemma init_wf: wf init Global.init.\n  Proof.\n    econs; ss.\n    - apply TView.bot_wf.\n    - apply TView.bot_closed.\n    - apply BoolMap.bot_finite.\n    - apply Memory.bot_le.\n    - apply Memory.bot_reserve_only.\n    - apply Memory.bot_finite.\n  Qed.\n\n  Lemma cap_wf\n        lc gl\n        (WF: wf lc gl):\n    wf lc (Global.cap_of gl).\n  Proof.\n    inv WF. econs; ss.\n    - eapply TView.cap_closed; eauto.\n      apply Memory.cap_of_cap.\n    - etrans; eauto. apply Memory.cap_le.\n      apply Memory.cap_of_cap.\n  Qed.\n\n  Variant disjoint (lc1 lc2:t): Prop :=\n  | disjoint_intro\n      (PROMISES_DISJOINT: BoolMap.disjoint (promises lc1) (promises lc2))\n      (RESERVES_DISJOINT: Memory.disjoint (reserves lc1) (reserves lc2))\n  .\n  #[global] Hint Constructors disjoint: core.\n\n  Global Program Instance disjoint_Symmetric: Symmetric disjoint.\n  Next Obligation.\n    econs; symmetry; apply H.\n  Qed.\n\n\n  Variant promise_step (lc1: t) (gl1: Global.t) (loc: Loc.t) (lc2: t) (gl2: Global.t): Prop :=\n  | promise_step_intro\n      prm2 gprm2\n      (PROMISE: Promises.promise (promises lc1) (Global.promises gl1) loc prm2 gprm2)\n      (LC2: lc2 = mk (tview lc1) prm2 (reserves lc1))\n      (GL2: gl2 = Global.mk (Global.sc gl1) gprm2 (Global.memory gl1))\n  .\n  #[global] Hint Constructors promise_step: core.\n\n  Variant reserve_step (lc1: t) (gl1: Global.t) (loc: Loc.t) (from to: Time.t) (lc2: t) (gl2: Global.t): Prop :=\n  | reserve_step_intro\n      rsv2 mem2\n      (RESERVE: Memory.reserve (reserves lc1) (Global.memory gl1) loc from to rsv2 mem2)\n      (LC2: lc2 = mk (tview lc1) (promises lc1) rsv2)\n      (GL2: gl2 = Global.mk (Global.sc gl1) (Global.promises gl1) mem2)\n  .\n  #[global] Hint Constructors reserve_step: core.\n\n  Variant cancel_step (lc1: t) (gl1: Global.t) (loc: Loc.t) (from to: Time.t) (lc2: t) (gl2: Global.t): Prop :=\n  | cancel_step_intro\n      rsv2 mem2\n      (CANCEL: Memory.cancel (reserves lc1) (Global.memory gl1) loc from to rsv2 mem2)\n      (LC2: lc2 = mk (tview lc1) (promises lc1) rsv2)\n      (GL2: gl2 = Global.mk (Global.sc gl1) (Global.promises gl1) mem2)\n  .\n  #[global] Hint Constructors cancel_step: core.\n\n  Variant read_step\n          (lc1: t) (gl1: Global.t)\n          (loc: Loc.t) (to: Time.t) (val: Const.t) (released: option View.t) (ord: Ordering.t)\n          (lc2: t): Prop :=\n  | read_step_intro\n      from val' na\n      tview2\n      (GET: Memory.get loc to (Global.memory gl1) = Some (from, Message.message val' released na))\n      (VAL: Const.le val val')\n      (READABLE: TView.readable (TView.cur (tview lc1)) loc to ord)\n      (TVIEW: TView.read_tview (tview lc1) loc to released ord = tview2)\n      (LC2: lc2 = mk tview2 (promises lc1) (reserves lc1)):\n      read_step lc1 gl1 loc to val released ord lc2\n  .\n  #[global] Hint Constructors read_step: core.\n\n  Variant write_step\n          (lc1: 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: t) (gl2: Global.t): Prop :=\n  | write_step_intro\n      prm2 gprm2 mem2\n      (RELEASED: released = TView.write_released (tview lc1) loc to releasedm ord)\n      (WRITABLE: TView.writable (TView.cur (tview lc1)) loc to ord)\n      (FULFILL: Promises.fulfill (promises lc1) (Global.promises gl1) loc ord prm2 gprm2)\n      (WRITE: Memory.add (Global.memory gl1) loc from to\n                         (Message.message val released (Ordering.le ord Ordering.na)) mem2)\n      (LC2: lc2 = mk (TView.write_tview (tview lc1) loc to ord) prm2 (reserves lc1))\n      (GL2: gl2 = Global.mk (Global.sc gl1) gprm2 mem2):\n      write_step lc1 gl1 loc from to val releasedm released ord lc2 gl2\n  .\n  #[global] Hint Constructors write_step: core.\n\n  Variant fence_step (lc1: t) (gl1: Global.t) (ordr ordw: Ordering.t) (lc2: t) (gl2: Global.t): Prop :=\n  | fence_step_intro\n      tview2\n      (READ: TView.read_fence_tview (tview lc1) ordr = tview2)\n      (LC2: lc2 = mk (TView.write_fence_tview tview2 (Global.sc gl1) ordw)\n                     (promises lc1) (reserves lc1))\n      (GL2: gl2 = Global.mk (TView.write_fence_sc tview2 (Global.sc gl1) ordw)\n                            (Global.promises gl1) (Global.memory gl1))\n      (PROMISES: Ordering.le Ordering.seqcst ordw -> promises lc1 = BoolMap.bot):\n      fence_step lc1 gl1 ordr ordw lc2 gl2\n  .\n  #[global] Hint Constructors fence_step: core.\n\n  Variant failure_step (lc1:t): Prop :=\n  | failure_step_intro\n  .\n  #[global] Hint Constructors failure_step: core.\n\n  Variant is_racy (lc1: t) (gl1: Global.t) (loc: Loc.t): forall (to: option Time.t) (ord: Ordering.t), Prop :=\n  | is_racy_promise\n      ord\n      (GET: (Global.promises gl1) loc = true)\n      (GETP: (promises lc1) loc = false):\n    is_racy lc1 gl1 loc None ord\n  | is_racy_message\n      to from val released na ord\n      (GET: Memory.get loc to (Global.memory gl1) = Some (from, Message.message val released na))\n      (RACE: TView.racy_view (TView.cur (tview lc1)) loc to)\n      (MSG: Ordering.le Ordering.plain ord -> na = true):\n    is_racy lc1 gl1 loc (Some to) ord\n  .\n  #[global] Hint Constructors is_racy: core.\n\n  Variant racy_read_step (lc1: t) (gl1: Global.t) (loc: Loc.t) (to: option Time.t) (val:Const.t) (ord:Ordering.t): Prop :=\n  | racy_read_step_intro\n      (RACE: is_racy lc1 gl1 loc to ord)\n  .\n  #[global] Hint Constructors racy_read_step: core.\n\n  Variant racy_write_step (lc1: t) (gl1: Global.t) (loc: Loc.t) (to: option Time.t) (ord: Ordering.t): Prop :=\n  | racy_write_step_intro\n      (RACE: is_racy lc1 gl1 loc to ord)\n  .\n  #[global] Hint Constructors racy_write_step: core.\n\n  Variant racy_update_step (lc1: t) (gl1: Global.t) (loc: Loc.t):\n    forall (to: option Time.t) (ordr ordw: Ordering.t), Prop :=\n  | racy_update_step_ordr\n      ordr ordw\n      (ORDR: Ordering.le ordr Ordering.na):\n    racy_update_step lc1 gl1 loc None ordr ordw\n  | racy_update_step_ordw\n      ordr ordw\n      (ORDW: Ordering.le ordw Ordering.na):\n    racy_update_step lc1 gl1 loc None ordr ordw\n  | racy_update_step_race\n      to ordr ordw\n      (RACE: is_racy lc1 gl1 loc to ordr):\n    racy_update_step lc1 gl1 loc to ordr ordw\n  .\n  #[global] Hint Constructors racy_update_step: core.\n\n\n  Variant internal_step:\n    forall (e: ThreadEvent.t) (lc1: t) (gl1: Global.t) (lc2: t) (gl2: Global.t), Prop :=\n  | internal_step_promise\n      lc1 gl1\n      loc lc2 gl2\n      (LOCAL: promise_step lc1 gl1 loc lc2 gl2):\n    internal_step (ThreadEvent.promise loc) lc1 gl1 lc2 gl2\n  | internal_step_reserve\n      lc1 gl1\n      loc from to lc2 gl2\n      (LOCAL: reserve_step lc1 gl1 loc from to lc2 gl2):\n    internal_step (ThreadEvent.reserve loc from to) lc1 gl1 lc2 gl2\n  | internal_step_cancel\n      lc1 gl1\n      loc from to lc2 gl2\n      (LOCAL: cancel_step lc1 gl1 loc from to lc2 gl2):\n    internal_step (ThreadEvent.cancel loc from to) lc1 gl1 lc2 gl2\n  .\n  #[global] Hint Constructors internal_step: core.\n\n  Variant program_step:\n    forall (e: ThreadEvent.t) (lc1: t) (gl1: Global.t) (lc2: 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: 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: 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: 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: 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: 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: 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  #[global] Hint Constructors program_step: core.\n\n\n  (* step_future *)\n\n  Lemma promise_step_future\n        lc1 gl1 loc lc2 gl2\n        (STEP: promise_step lc1 gl1 loc lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    hexploit Promises.promise_le; eauto. i.\n    hexploit Promises.promise_finite; eauto. i.\n    splits; ss; try refl. econs; refl.\n  Qed.\n\n  Lemma reserve_step_future\n        lc1 gl1 loc from to lc2 gl2\n        (STEP: reserve_step lc1 gl1 loc from to lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    hexploit Memory.reserve_future; eauto. i. des.\n    splits; try refl.\n    - econs; ss. eapply TView.future_closed; eauto.\n    - econs; ss. eapply Memory.future_closed_timemap; eauto.\n    - econs; ss. refl.\n  Qed.\n\n  Lemma cancel_step_future\n        lc1 gl1 loc from to lc2 gl2\n        (STEP: cancel_step lc1 gl1 loc from to lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    hexploit Memory.cancel_future; eauto. i. des.\n    splits; try refl.\n    - econs; ss. eauto using TView.future_closed.\n    - econs; ss. eauto using Memory.future_closed_timemap.\n    - econs; ss. refl.\n  Qed.\n\n  Lemma read_step_future\n        lc1 gl1 loc ts val released ord lc2\n        (STEP: read_step lc1 gl1 loc ts val released ord lc2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl1>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released (Global.memory gl1)>> /\\\n    <<REL_TS: Time.le (View.rlx (View.unwrap released) loc) ts>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    dup MEM_CLOSED. inv MEM_CLOSED0. exploit CLOSED; eauto. i. des.\n    inv MSG_WF. inv MSG_CLOSED. inv MSG_TS.\n    exploit TViewFacts.read_future; try exact GET; eauto.\n    i. des. splits; auto.\n    - econs; eauto.\n    - apply TViewFacts.read_tview_incr.\n  Qed.\n\n  Lemma write_step_future\n        lc1 gl1 loc from to val releasedm released ord lc2 gl2\n        (STEP: write_step lc1 gl1 loc from to val releasedm released ord lc2 gl2)\n        (REL_WF: View.opt_wf releasedm)\n        (REL_CLOSED: Memory.closed_opt_view releasedm (Global.memory gl1))\n        (REL_TS: Time.le (View.rlx (View.unwrap releasedm) loc) to)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_TS: Time.le ((View.rlx (View.unwrap released)) loc) to>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released (Global.memory gl2)>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    hexploit Promises.fulfill_le; try exact FULFILL; eauto. i.\n    hexploit Promises.fulfill_finite; try exact FULFILL; eauto. i.\n    exploit TViewFacts.write_future; eauto. s. i. des.\n    exploit Memory.add_future; try apply WRITE; eauto.\n    { econs. eapply TViewFacts.write_released_ts; eauto. }\n    i. des.\n    exploit Memory.add_get0; try apply WRITE; eauto. i. des.\n    splits; eauto.\n    - econs; eauto. ss.\n      eapply Memory.future_closed_timemap; eauto.\n    - apply TViewFacts.write_tview_incr. auto.\n    - econs; ss. refl.\n    - eapply TViewFacts.write_released_ts; eauto.\n  Qed.\n\n  Lemma update_step_future\n        lc1 gl1 loc ts val1 released1 ordr lc2\n        to val2 released2 ordw lc3 gl3\n        (READ: read_step lc1 gl1 loc ts val1 released1 ordr lc2)\n        (WRITE: write_step lc2 gl1 loc ts to val2 released1 released2 ordw lc3 gl3)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc3 gl3>> /\\\n    <<GL_WF2: Global.wf gl3>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl3>> /\\\n    <<REL_WF: View.opt_wf released2>> /\\\n    <<REL_TS: Time.le ((View.rlx (View.unwrap released2)) loc) to>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released2 (Global.memory gl3)>>.\n  Proof.\n    exploit read_step_future; eauto. i. des.\n    exploit write_step_future; eauto.\n    { etrans; eauto. econs.\n      inv WRITE. eapply Memory.add_ts; eauto.\n    }\n    i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma fence_step_future\n        lc1 gl1 ordr ordw lc2 gl2\n        (STEP: fence_step lc1 gl1 ordr ordw lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv LC_WF1. inv GL_WF1. inv STEP. ss.\n    exploit TViewFacts.read_fence_future; eauto. i. des.\n    exploit TViewFacts.write_fence_future; eauto. i. des.\n    splits; eauto.\n    - etrans.\n      + apply TViewFacts.write_fence_tview_incr. auto.\n      + apply TViewFacts.write_fence_tview_mon; eauto; try refl.\n        apply TViewFacts.read_fence_tview_incr. auto.\n    - econs; try refl.\n      apply TViewFacts.write_fence_sc_incr.\n  Qed.\n\n  Lemma internal_step_future\n        e lc1 gl1 lc2 gl2\n        (STEP: internal_step e lc1 gl1 lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv STEP.\n    - eapply promise_step_future; eauto.\n    - eapply reserve_step_future; eauto.\n    - eapply cancel_step_future; eauto.\n  Qed.\n\n  Lemma program_step_future\n        e lc1 gl1 lc2 gl2\n        (STEP: program_step e lc1 gl1 lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.future gl1 gl2>>.\n  Proof.\n    inv STEP; try by (splits; eauto; try refl).\n    - exploit read_step_future; eauto. i. des.\n      esplits; eauto; try refl.\n    - exploit write_step_future; eauto;\n        (try by econs); try apply Time.bot_spec. i. des.\n      esplits; eauto; try refl.\n    - exploit read_step_future; eauto. i. des.\n      exploit write_step_future; eauto; try by econs.\n      { etrans; eauto. inv LOCAL2.\n        econs. eauto using Memory.add_ts.\n      }\n      i. des.\n      esplits; eauto. etrans; eauto.\n    - exploit fence_step_future; eauto.\n    - exploit fence_step_future; eauto.\n  Qed.\n\n\n  (* step_strong_le *)\n\n  Lemma promise_step_strong_le\n        lc1 gl1 loc lc2 gl2\n        (STEP: promise_step lc1 gl1 loc lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>>.\n  Proof.\n    hexploit promise_step_future; eauto. i. des. esplits; eauto. econs.\n    { eapply Global.future_le; eauto. }\n    { econs. i. left. inv STEP. ss. inv PROMISE. inv GADD.\n      change (LocFun.add loc true (Global.promises gl1) loc0) with\n        (LocFun.find loc0 (LocFun.add loc true (Global.promises gl1))).\n      rewrite LocFun.add_spec. des_ifs. rewrite Bool.implb_same. auto.\n    }\n  Qed.\n\n  Lemma reserve_step_strong_le\n        lc1 gl1 loc from to lc2 gl2\n        (STEP: reserve_step lc1 gl1 loc from to lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>>.\n  Proof.\n    hexploit reserve_step_future; eauto. i. des. esplits; eauto. econs.\n    { eapply Global.future_le; eauto. }\n    { econs. i. left. inv STEP. rewrite Bool.implb_same. auto. }\n  Qed.\n\n  Lemma cancel_step_strong_le\n        lc1 gl1 loc from to lc2 gl2\n        (STEP: cancel_step lc1 gl1 loc from to lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>>.\n  Proof.\n    hexploit cancel_step_future; eauto. i. des. esplits; eauto. econs.\n    { eapply Global.future_le; eauto. }\n    { econs. i. left. inv STEP. rewrite Bool.implb_same. auto. }\n  Qed.\n\n  Lemma write_step_strong_le\n        lc1 gl1 loc from to val releasedm released ord lc2 gl2\n        (STEP: write_step lc1 gl1 loc from to val releasedm released ord lc2 gl2)\n        (REL_WF: View.opt_wf releasedm)\n        (REL_CLOSED: Memory.closed_opt_view releasedm (Global.memory gl1))\n        (REL_TS: Time.le (View.rlx (View.unwrap releasedm) loc) to)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_TS: Time.le ((View.rlx (View.unwrap released)) loc) to>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released (Global.memory gl2)>>\n    \\/\n    exists ts, <<NA: Ordering.le ord Ordering.na>> /\\ <<RACE: is_racy lc1 gl1 loc ts ord>>\n  .\n  Proof.\n    destruct (classic (exists ts, Ordering.le ord Ordering.na /\\ is_racy lc1 gl1 loc ts ord)) as [RACE|SAFE]; auto.\n    left. hexploit write_step_future; eauto. i. des.\n    esplits; eauto. econs.\n    { eapply Global.future_le; eauto. }\n    { econs. i. inv STEP. ss. inv FULFILL; ss.\n      { left. rewrite Bool.implb_same. auto. }\n      inv GREMOVE.\n      change (LocFun.add loc false (Global.promises gl1) loc0) with\n        (LocFun.find loc0 (LocFun.add loc false (Global.promises gl1))).\n      rewrite LocFun.add_spec. condtac.\n      { subst. right. repeat red. esplits.\n        { inv ORD. rewrite H0 in *. eapply Memory.add_get0; eauto. }\n        i. destruct (Time.le_lt_dec to ts1); auto. exfalso.\n        eapply SAFE. esplits.\n        { destruct ord; ss. }\n        econs 2.\n        { eauto. }\n        { unfold TView.racy_view.\n          eapply TimeFacts.lt_le_lt; eauto.\n          inv WRITABLE. eapply TimeFacts.le_lt_lt; eauto. eapply LC_WF1.\n        }\n        { destruct ord; ss. }\n      }\n      { rewrite Bool.implb_same. auto. }\n    }\n  Qed.\n\n  Lemma fence_step_strong_le\n        lc1 gl1 ordr ordw lc2 gl2\n        (STEP: fence_step lc1 gl1 ordr ordw lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>>.\n  Proof.\n    hexploit fence_step_future; eauto. i. des. esplits; eauto. econs.\n    { eapply Global.future_le; eauto. }\n    { econs. i. left. inv STEP. rewrite Bool.implb_same. auto. }\n  Qed.\n\n  Lemma internal_step_strong_le\n        e lc1 gl1 lc2 gl2\n        (STEP: internal_step e lc1 gl1 lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>>.\n  Proof.\n    inv STEP.\n    - eapply promise_step_strong_le; eauto.\n    - eapply reserve_step_strong_le; eauto.\n    - eapply cancel_step_strong_le; eauto.\n  Qed.\n\n  Lemma program_step_strong_le\n        e lc1 gl1 lc2 gl2\n        (STEP: program_step e lc1 gl1 lc2 gl2)\n        (LC_WF1: wf lc1 gl1)\n        (GL_WF1: Global.wf gl1):\n    <<LC_WF2: wf lc2 gl2>> /\\\n    <<GL_WF2: Global.wf gl2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<GL_FUTURE: Global.strong_le gl1 gl2>> \\/\n    exists e_race,\n      <<STEP: program_step e_race lc1 gl1 lc1 gl1>> /\\\n      <<EVENT: ThreadEvent.get_program_event e_race = ThreadEvent.get_program_event e>> /\\\n      <<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>\n  .\n  Proof.\n    inv STEP; try by (left; splits; eauto; try refl).\n    - left. exploit read_step_future; eauto. i. des. esplits; eauto. refl.\n    - exploit write_step_strong_le; eauto;\n        (try by econs); try apply Time.bot_spec. i. des.\n      { left. esplits; eauto; try refl. }\n      { right. esplits.\n        { eapply program_step_racy_write. econs; eauto. }\n        { ss. }\n        { ss. }\n      }\n    - exploit read_step_future; eauto. i. des.\n      exploit write_step_strong_le; eauto; try by econs.\n      { etrans; eauto. inv LOCAL2.\n        econs. eauto using Memory.add_ts.\n      }\n      i. des.\n      { left. esplits; eauto. etrans; eauto. }\n      { right. esplits.\n        { eapply program_step_racy_update; eauto. }\n        { ss. }\n        { ss. }\n      }\n    - left. exploit fence_step_strong_le; eauto.\n    - left. exploit fence_step_strong_le; eauto.\n  Qed.\n\n\n\n  (* step_inhabited *)\n\n  Lemma internal_step_inhabited\n        e lc1 gl1 lc2 gl2\n        (STEP: internal_step e lc1 gl1 lc2 gl2)\n        (INHABITED1: Memory.inhabited (Global.memory gl1)):\n    <<INHABITED2: Memory.inhabited (Global.memory gl2)>>.\n  Proof.\n    inv STEP; try inv LOCAL; ss.\n    - eapply Memory.reserve_inhabited; eauto.\n    - eapply Memory.cancel_inhabited; eauto.\n  Qed.\n\n  Lemma program_step_inhabited\n        e lc1 gl1 lc2 gl2\n        (STEP: program_step e lc1 gl1 lc2 gl2)\n        (INHABITED1: Memory.inhabited (Global.memory gl1)):\n    <<INHABITED2: Memory.inhabited (Global.memory gl2)>>.\n  Proof.\n    inv STEP; try inv LOCAL; ss.\n    - eapply Memory.add_inhabited; eauto.\n    - inv LOCAL2. eapply Memory.add_inhabited; eauto.\n  Qed.\n\n\n  (* step_disjoint *)\n\n  Lemma promise_step_disjoint\n        lc1 gl1 loc lc2 gl2 lc\n        (STEP: promise_step lc1 gl1 loc lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv DISJOINT1. inv LC_WF. inv STEP.\n    exploit Promises.promise_disjoint; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma reserve_step_disjoint\n        lc1 gl1 loc from to lc2 gl2 lc\n        (STEP: reserve_step lc1 gl1 loc from to lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv DISJOINT1. inv LC_WF. inv STEP.\n    hexploit Memory.reserve_messages_le; eauto. i.\n    exploit Memory.reserve_disjoint; eauto. i. des.\n    esplits; eauto. econs; ss.\n    eapply TView.le_closed; eauto.\n  Qed.\n\n  Lemma cancel_step_disjoint\n        lc1 gl1 loc from to lc2 gl2 lc\n        (STEP: cancel_step lc1 gl1 loc from to lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv DISJOINT1. inv LC_WF. inv STEP.\n    hexploit Memory.cancel_messages_le; eauto. i.\n    exploit Memory.cancel_disjoint; eauto. i. des.\n    esplits; eauto. econs; ss.\n    eapply TView.le_closed; eauto.\n  Qed.\n\n  Lemma read_step_disjoint\n        lc1 gl1 loc ts val released ord lc2 lc\n        (STEP: read_step lc1 gl1 loc ts val released ord lc2)\n        (DISJOINT1: disjoint lc1 lc):\n    disjoint lc2 lc.\n  Proof.\n    inv DISJOINT1. inv STEP. ss.\n  Qed.\n\n  Lemma write_step_disjoint\n        lc1 gl1 loc from to val releasedm released ord lc2 gl2 lc\n        (STEP: write_step lc1 gl1 loc from to val releasedm released ord lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv DISJOINT1. inv LC_WF. inv STEP.\n    hexploit Memory.add_messages_le; eauto. i.\n    exploit Promises.fulfill_disjoint; try exact FULFILL; eauto. i. des.\n    esplits; eauto. econs; ss.\n    - eapply TView.le_closed; eauto.\n    - etrans; eauto. eapply Memory.add_le; eauto.\n  Qed.\n\n  Lemma fence_step_disjoint\n        lc1 gl1 ordr ordw lc2 gl2 lc\n        (STEP: fence_step lc1 gl1 ordr ordw lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv DISJOINT1. inv LC_WF. inv STEP. splits; ss.\n  Qed.\n\n  Lemma read_step_promises\n        lc1 gl1 loc to val released ord lc2\n        (READ: read_step lc1 gl1 loc to val released ord lc2):\n    (promises lc1) = (promises lc2).\n  Proof.\n    inv READ. auto.\n  Qed.\n\n  Lemma internal_step_disjoint\n        e lc1 gl1 lc2 gl2 lc\n        (STEP: internal_step e lc1 gl1 lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv STEP.\n    - eapply promise_step_disjoint; eauto.\n    - eapply reserve_step_disjoint; eauto.\n    - eapply cancel_step_disjoint; eauto.\n  Qed.\n\n  Lemma program_step_disjoint\n        e lc1 gl1 lc2 gl2 lc\n        (STEP: program_step e lc1 gl1 lc2 gl2)\n        (DISJOINT1: disjoint lc1 lc)\n        (LC_WF: wf lc gl1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<LC_WF: wf lc gl2>>.\n  Proof.\n    inv STEP; try by (splits; eauto).\n    - exploit read_step_disjoint; eauto.\n    - exploit write_step_disjoint; eauto.\n    - exploit read_step_disjoint; eauto. i.\n      exploit write_step_disjoint; eauto.\n    - exploit fence_step_disjoint; eauto.\n    - exploit fence_step_disjoint; 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 (promises lc2) (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 FULFILL; ss.\n      split; eauto using BoolMap.remove_le.\n    - inv LOCAL1. inv LOCAL2. inv FULFILL; ss.\n      split; eauto using BoolMap.remove_le.\n  Qed.\n\n  Lemma program_step_reserves\n        e lc1 gl1 lc2 gl2\n        (STEP: program_step e lc1 gl1 lc2 gl2):\n    reserves lc1 = reserves lc2.\n  Proof.\n    inv STEP; ss; try by (inv LOCAL; ss).\n    inv LOCAL1. inv LOCAL2. ss.\n  Qed.\n\n  Lemma internal_step_promises_minus\n        e lc1 gl1 lc2 gl2\n        (STEP: internal_step e lc1 gl1 lc2 gl2):\n    BoolMap.minus (Global.promises gl1) (promises lc1) =\n    BoolMap.minus (Global.promises gl2) (promises lc2).\n  Proof.\n    inv STEP; inv LOCAL; ss.\n    eapply Promises.promise_minus; eauto.\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) (promises lc1) =\n    BoolMap.minus (Global.promises gl2) (promises lc2).\n  Proof.\n    inv STEP; ss; try by (inv LOCAL; ss).\n    - inv LOCAL. ss.\n      eapply Promises.fulfill_minus; eauto.\n    - inv LOCAL1. inv LOCAL2. ss.\n      eapply Promises.fulfill_minus; eauto.\n  Qed.\n\n  Lemma write_max_exists\n        lc1 gl1\n        loc val releasedm ord\n        (LC_WF: Local.wf lc1 gl1)\n        (RELEASEDM_WF: View.opt_wf releasedm):\n    exists from to released lc2 gl2,\n      (<<WRITE: write_step lc1 gl1 loc from to val releasedm released ord lc2 gl2>>) /\\\n      (<<FROM: Time.lt (Memory.max_ts loc (Global.memory gl1)) from>>).\n  Proof.\n    exploit Memory.add_exists_max; try eapply Time.incr_spec; cycle 1.\n    { i. des. esplits; try exact FROM.\n      econs; try exact ADD; eauto. econs.\n      eapply TimeFacts.le_lt_lt; [|apply Time.incr_spec].\n      inv LC_WF. inv TVIEW_CLOSED. inv CUR. specialize (RLX loc). des.\n      eapply Memory.max_ts_spec. eauto.\n    }\n    econs. unfold TView.write_released. condtac; econs.\n    repeat (try condtac; aggrtac; try apply LC_WF).\n  Qed.\n\n  Lemma fence_step_non_sc\n        lc1 gl1 or ow lc2 gl2\n        (STEP: fence_step lc1 gl1 or ow lc2 gl2)\n        (SC: Ordering.le ow Ordering.acqrel):\n    gl2 = gl1.\n  Proof.\n    destruct gl1. inv STEP. ss. f_equal.\n    apply TViewFacts.write_fence_sc_acqrel. ss.\n  Qed.\nEnd Local.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/model/Local.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.19523797997483272}}
{"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 Effects.\nRequire Import Environment.\nRequire Import TypeSystem.\nRequire Import Determinism.\nRequire Import Definitions2.\nRequire Import CorrectnessLemmas.\n\nImport TypeSoundness.\nImport EffectSoundness.\n\nDefinition Correctness_1 (ea : Expr) (ee : Expr) :\n  forall (h h' h'' : Heap) (env : Env) (rho : Rho) (p p' : Phi) (v : Val) (eff : Theta),\n    (h, env, rho, ea) \u21d3 (h', v, p) -> \n    ReadOnlyPhi p' ->\n    (h, env, rho, ee) \u21d3 (h'', Eff eff, p') -> \n    forall stty ctxt rgns ty static,\n      TcEnv (stty, rho, env, ctxt) -> \n      TcExp (stty, ctxt, rgns, ea, ty, static) ->    \n      TcHeap (h, stty) ->\n      TcRho (rho, rgns) ->\n      BackTriangle (stty, ctxt, rgns, ea, ee) -> p \u2291 eff.\nProof.\n  intros h h' h'' env rho p p' v eff Exprs.\n  generalize dependent eff.\n  generalize dependent p'.\n  generalize dependent ee.\n  dependent induction Exprs;\n  intros edesc p' eff HReadOnly Specs stty ctxt rgns ty static Henv Hexp Hheap HRho Back;\n  inversion Specs; subst; inversion Back; inversion Hexp; subst; try (solve [apply PTS_Nil | apply PhiInThetaTop]).\n  (*- assert (facts \u2291 Some empty_set) by (eapply IHExprs1  with (ee:=\u2205); eauto; constructor).\n    apply EmptyIsNil in H. rewrite H. rewrite Phi_Seq_Nil_L.\n    assert (aacts \u2291 Some empty_set).\n    eapply IHExprs2 with (ee:=\u2205) (p':=Phi_Nil); eauto.\n    + assert (h''=fheap) by (eapply ReadOnlyTracePreservesHeap_2; eauto).\n      subst; constructor.\n    + assert (h''=fheap) by (eapply ReadOnlyTracePreservesHeap_2; eauto).\n      subst; assumption.\n    + inversion H1; subst.  rewrite Phi_Seq_Nil_L.\n\n      assert (clsTcVal : exists stty',  \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t') \n               /\\ TcHeap (fheap, stty')\n               /\\ TcVal (stty', Cls (env', rho', Mu f x ec' ee'), subst_rho rho (Ty2_Arrow tya effc1 ty effe1 Ty2_Effect))) \n        by (eapply ty_sound; eauto).\n      destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n\n      assert (argTcVal : exists stty',\n             (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n               /\\ TcHeap (aheap, stty')\n               /\\ TcVal (stty', v0, subst_rho rho tya))\n        by (eapply ty_sound; eauto using update_env, ext_stores__env, ext_stores__exp).\n      destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n\n      \n      inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcEnv_env' TcExp_abs | | ]; subst. \n      inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | |  | | | | | | | | | | |  ]; subst.\n      rewrite <- H12 in TcVal_cls.\n      do 2 rewrite subst_rho_arrow in H12. inversion H12. \n      rewrite <- H2 in TcVal_v'.\n       \n      eapply IHExprs3 with (ee:=ee') (stty := sttya); eauto.\n      * admit.\n      * apply update_env; simpl.\n        eapply ext_stores__env; eauto.\n        { apply update_env; eauto. }\n        { eassumption. }\n      * eapply ext_stores__exp; eauto.\n      * eapply ext_stores__bt; eauto.\n      * { inversion H2; subst.\n          - admit.\n          - admit.\n          - admit.\n          - admit.\n          - admit.\n          - admit.\n          - admit. }\n      * apply PTS_Seq.\n        { apply PTS_Seq; apply EmptyInAnyTheta; assumption. }\n        { assert (clsTcVal : exists stty',  \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n               /\\ TcHeap (fheap, stty')\n               /\\ TcVal (stty', Cls (env', rho', Mu f x ec' ee'), subst_rho rho (Ty2_Arrow tya effc1 ty effe1 Ty2_Effect))) \n            by (eapply ty_sound; eauto).\n          destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n\n          assert (argTcVal : exists stty',\n                               (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n                               /\\ TcHeap (aheap, stty')\n                               /\\ TcVal (stty', v0, subst_rho rho tya))\n            by (eapply ty_sound; eauto using update_env, ext_stores__env, ext_stores__exp).\n          destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n\n          \n          inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcEnv_env' TcExp_abs | | ]; subst. \n          inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | |  | | | | | | | | | | |  ]; subst.\n          rewrite <- H14 in TcVal_cls.\n          do 2 rewrite subst_rho_arrow in H14. inversion H14. \n          rewrite <- H4 in TcVal_v'.\n\n          eapply IHExprs3 with (ee:=ee') (stty := sttya); eauto.\n          - admit.\n          - apply update_env; simpl.\n            eapply ext_stores__env; eauto.\n            { apply update_env; eauto. }\n            { eassumption. }\n          - eapply ext_stores__exp; eauto.\n          - eapply ext_stores__bt; eauto. }\n      * admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit. *)\n  - inversion HReadOnly; subst.\n    assert (facts \u2291 effa) by (eapply IHExprs1 with (p':=phia); eauto).\n    apply PTS_Seq. \n    + apply PTS_Seq.\n      * apply Theta_introl. assumption.\n      * inversion H7; subst.\n        assert (aacts \u2291 effa2)\n          by (eapply IHExprs2 with (p':=phia0); eauto;\n              inversion HReadOnly; inversion H13; auto;\n              assert (h'' = fheap) by (eapply ReadOnlyTracePreservesHeap_2; eauto); subst; assumption).\n        apply Theta_intror. apply Theta_introl. assumption.\n    + assert (clsTcVal : exists stty',  \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n               /\\ TcHeap (fheap, stty')\n               /\\ TcVal (stty', Cls (env', rho', Mu f x ec' ee'), subst_rho rho (Ty2_Arrow tya effc ty effe Ty2_Effect))) \n        by (eapply ty_sound; eauto).\n      destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n\n      assert (argTcVal : exists stty',\n             (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n               /\\ TcHeap (aheap, stty')\n               /\\ TcVal (stty', v0, subst_rho rho tya))\n        by (eapply ty_sound; eauto using update_env, ext_stores__env, ext_stores__exp).\n      destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n\n      \n      inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcEnv_env' TcExp_abs | | ]; subst. \n      inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | |  | | | | | | | | | | |  ]; subst.\n      rewrite <- H14 in TcVal_cls.\n      do 2 rewrite subst_rho_arrow in H14. inversion H14. \n      rewrite <- H4 in TcVal_v'.\n      inversion H7; subst.\n      eapply IHExprs3 with (stty := sttya) (ee:=ee') (p' := phib0); eauto;\n      inversion H3; subst; auto.\n      * admit.\n      * apply update_env; simpl.\n        eapply ext_stores__env; eauto.\n        { apply update_env; eauto. }\n        { eassumption. }\n      * eapply ext_stores__exp; eauto.\n      * eapply ext_stores__bt; eauto.\n  - admit.\nAdmitted.        \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/Correctness2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.19523797718870106}}
{"text": "Require Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Core.\nRequire Import ProD3.core.Tofino.\nRequire Import ProD3.examples.sbf.p4ast.\nRequire Import ProD3.examples.sbf.ConFilter.\nRequire Import ProD3.examples.sbf.common.\nRequire Import ProD3.examples.sbf.FilterRepr.\nRequire Import ProD3.examples.sbf.verif_Win1.\nRequire Import ProD3.examples.sbf.verif_Win2.\nRequire Import ProD3.examples.sbf.verif_Win3.\nRequire Import ProD3.examples.sbf.verif_Win4.\nRequire Import ProD3.examples.sbf.verif_Filter.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_index_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_window_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_4_body) : func_specs.\n\nDefinition P4_bf2_win_md_t_query (f cf if' : Z) (new_clear_index : Sval) (is : list Sval) :=\n  if f=? cf then\n    P4_bf2_win_md_t (P4Bit 8 CLEAR) (Zrepeat new_clear_index 3)\n  else\n    P4_bf2_win_md_t (P4Bit 8 QUERY) is.\n\nDefinition tbl_set_win_query_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_1\"; \"api_4\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_2\"; \"api_2\"];\n               [\"act_set_clear_win_2\"; \"api_3\"];\n               [\"act_set_clear_win_2\"; \"api_4\"];\n               [\"act_set_clear_win_3\"; \"api_1\"];\n               [\"act_set_clear_win_3\"; \"api_2\"];\n               [\"act_set_clear_win_3\"; \"api_3\"];\n               [\"act_set_clear_win_3\"; \"api_4\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_2\"];\n               [\"act_set_clear_win_4\"; \"api_3\"];\n               [\"act_set_clear_win_4\"; \"api_4\"]]) []\n    WITH (timer : Z * bool) (clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval)\n      (H_timer : 0 <= fst timer < frame_tick_tocks * num_frames),\n      PRE\n        (ARG []\n        (MEM [([\"api\"], P4Bit 8 QUERY);\n              ([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (let cf := get_clear_frame timer in\n        let if' := get_insert_frame cf in\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_query 0 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_2\", P4_bf2_win_md_t_query 1 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_3\", P4_bf2_win_md_t_query 2 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_4\", P4_bf2_win_md_t_query 3 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3])])]\n        (EXT [])))))%arg_ret_assr.\n\nLemma tbl_set_win_query_body :\n  func_sound ge tbl_set_win_fd nil tbl_set_win_query_spec.\nProof.\n  start_function; elim_trivial_cases.\n  - replace (get_clear_frame timer) with 0. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_1_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 1. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_2_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 2. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_3_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 3. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_4_body.\n    { entailer. }\n    { entailer. }\n  - lia.\nQed.\n\nDefinition act_merge_wins_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_merge_wins\"] ge).\n\nDefinition act_merge_wins_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"query_res\"]]) []\n    WITH,\n      PRE\n        (ARG []\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"query_res\"], (P4Bit 8 1))]\n        (EXT []))).\n\nLemma act_merge_wins_body :\n  func_sound ge act_merge_wins_fd nil act_merge_wins_spec.\nProof.\n  start_function.\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition act_merge_default_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_merge_default\"] ge).\n\nDefinition act_merge_default_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"query_res\"]]) []\n    WITH,\n      PRE\n        (ARG []\n        (MEM []\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"query_res\"], (P4Bit 8 0))]\n        (EXT []))).\n\nLemma act_merge_default_body :\n  func_sound ge act_merge_default_fd nil act_merge_default_spec.\nProof.\n  start_function.\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition tbl_merge_wins_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_merge_wins\"; \"apply\"] ge).\n\nDefinition P4_bf2_win_md_t_rw rw1 rw2 rw3 :=\n  ValBaseStruct\n    [(\"api\", P4Bit_ 8);\n     (\"index_1\", P4Bit_ index_w);\n     (\"index_2\", P4Bit_ index_w);\n     (\"index_3\", P4Bit_ index_w);\n     (\"rw_1\", P4Bit 8 (Z.b2z rw1));\n     (\"rw_2\", P4Bit 8 (Z.b2z rw2));\n     (\"rw_3\", P4Bit 8 (Z.b2z rw3))].\n\n(* Because this function doesn't modify ds_md, so we can describe it in this way.\nBut if it does modify ds_md, we don't have a really good way to isolate the unchanged part.\nBut on the other hand, the get/update system doesn't work very well, either. *)\nDefinition tbl_merge_wins_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"query_res\"]]) []\n    WITH rw11 rw12 rw13 rw21 rw22 rw23 rw31 rw32 rw33 rw41 rw42 rw43,\n      PRE\n        (ARG []\n        (MEM [([\"api\"], P4Bit 8 QUERY);\n              ([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit_ 16);\n                  (\"clear_index_1\", P4Bit_ index_w);\n                  (\"hash_index_1\", P4Bit_ index_w);\n                  (\"hash_index_2\", P4Bit_ index_w);\n                  (\"hash_index_3\", P4Bit_ index_w);\n                  (\"win_1\", P4_bf2_win_md_t_rw rw11 rw12 rw13);\n                  (\"win_2\", P4_bf2_win_md_t_rw rw21 rw22 rw23);\n                  (\"win_3\", P4_bf2_win_md_t_rw rw31 rw32 rw33);\n                  (\"win_4\", P4_bf2_win_md_t_rw rw41 rw42 rw43)])]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"query_res\"], (P4Bit 8 (Z.b2z (\n          fold_orb (map fold_andb\n            [[rw11; rw12; rw13];\n             [rw21; rw22; rw23];\n             [rw31; rw32; rw33];\n             [rw41; rw42; rw43]])))))]\n        (EXT []))))%arg_ret_assr.\n\nLemma b2z_one : forall b,\n  Z.b2z b =? 1 = b.\nProof.\n  destruct b; auto.\nQed.\n\nLemma tbl_merge_wins_body :\n  func_sound ge tbl_merge_wins_fd nil tbl_merge_wins_spec.\nProof.\n  unfold tbl_merge_wins_spec, P4_bf2_win_md_t_rw.\n  start_function;\n    repeat rewrite b2z_one in *;\n    repeat lazymatch goal with\n    | H : is_true (_ && _) |- _ =>\n        apply Reflect.andE in H;\n        destruct H\n    end;\n    repeat match goal with\n    | H : is_true ?b |- _ =>\n        is_var b;\n        unfold is_true in H;\n        subst b\n    end.\n  - table_action act_merge_wins_body.\n    { entailer. }\n    { entailer. }\n\n#[export] Hint Rewrite Bool.orb_true_l Bool.orb_true_r Bool.orb_false_l Bool.orb_false_r : simpl_orb.\n\n  - table_action act_merge_wins_body.\n    { entailer. }\n    { entailer.\n      unfold map, fold_andb, fold_orb, fold_left.\n      autorewrite with simpl_andb simpl_orb.\n      apply sval_refine_refl.\n    }\n  - table_action act_merge_wins_body.\n    { entailer. }\n    { entailer.\n      unfold map, fold_andb, fold_orb, fold_left.\n      autorewrite with simpl_andb simpl_orb.\n      apply sval_refine_refl.\n    }\n  - table_action act_merge_wins_body.\n    { entailer. }\n    { entailer.\n      unfold map, fold_andb, fold_orb, fold_left.\n      autorewrite with simpl_andb simpl_orb.\n      apply sval_refine_refl.\n    }\n  - table_action act_merge_default_body.\n    { entailer. }\n    { entailer.\n      unfold map, fold_andb, fold_orb, fold_left.\n      autorewrite with simpl_andb simpl_orb.\n      replace (rw11 && rw12 && rw13) with false by (destruct (rw11 && rw12 && rw13); auto).\n      replace (rw21 && rw22 && rw23) with false by (destruct (rw21 && rw22 && rw23); auto).\n      replace (rw31 && rw32 && rw33) with false by (destruct (rw31 && rw32 && rw33); auto).\n      replace (rw41 && rw42 && rw43) with false by (destruct (rw41 && rw42 && rw43); auto).\n      apply sval_refine_refl.\n    }\n  - elim_trivial_cases.\n  - elim_trivial_cases.\nQed.\n\nDefinition filter_query := @filter_query num_frames num_rows num_slots H_num_frames H_num_rows H_num_slots\n  frame_tick_tocks.\n\nDefinition Filter_query_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (key : Val) (tstamp : Z) (cf : filter num_frames num_rows num_slots),\n      PRE\n        (ARG [eval_val_to_sval key; P4Bit 8 QUERY; P4Bit 48 tstamp; P4Bit_ 8]\n        (MEM []\n        (EXT [filter_repr p index_w panes rows cf])))\n      POST\n        (ARG_RET [P4Bit 8 (Z.b2z (snd (filter_query cf (Z.odd (tstamp/2097152)) (hashes key))))] ValBaseNull\n        (MEM []\n        (EXT [filter_repr p index_w panes rows (fst (filter_query cf (Z.odd (tstamp/2097152)) (hashes key)))]))).\n\nLtac destruct_listn l :=\n  destruct l as [l ?H];\n  destruct_list l.\n\nLemma Filter_query_body :\n  func_sound ge Filter_fd nil Filter_query_spec.\nProof.\n  start_function.\n  destruct cf as [[ps ?H] ? ?].\n  unfold filter_repr.\n  cbn [proj1_sig] in *.\n  destruct_list ps.\n  normalize_EXT.\n  step.\n  step_call tbl_hash_index_1_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_2_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_3_body.\n  { entailer. }\n  Intros _.\n  set (is := (exist _ [hash1 key; hash2 key; hash3 key] eq_refl : listn Z 3)).\n  set (clear_is := (exist _ (Zrepeat fil_clear_index 3) eq_refl : listn Z 3)).\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`is)). {\n    repeat first [apply Forall_cons | apply Forall_nil].\n    all : unfold hash1, hash2, hash3;\n      apply Z.mod_pos_bound; lia.\n  }\n  P4assert (0 <= fil_clear_index < num_slots). {\n    unfold fil_clear_index_repr.\n    Intros i'.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    subst.\n    apply Z.mod_pos_bound.\n    lia.\n  }\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`clear_is)). {\n    repeat first [\n      assumption\n    | constructor\n    ].\n  }\n  step_call tbl_clear_index_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_clear_window_body.\n  { entailer. }\n  Intros _.\n  set (new_timer := update_timer fil_timer (Z.odd (tstamp / 2097152))).\n  P4assert (0 <= fst new_timer < num_frames * frame_tick_tocks).\n  { unfold timer_repr.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    auto.\n  }\n  step_call tbl_set_win_query_body.\n  { entailer. }\n  { auto. }\n  Intros _.\n  (* unfold and fold in the post condition *)\n  unfold filter_query, ConFilter.filter_query.\n  (* cbn [proj1_sig fst snd]. *)\n  unfold proj1_sig. unfold fst. unfold snd.\n  fold new_timer.\n  replace (exist (fun i : list Z => Zlength i = num_rows) (Zrepeat fil_clear_index num_rows) _) with clear_is. 2 : {\n    apply subset_eq_compat. auto.\n  }\n  assert (0 <= get_clear_frame new_timer < num_frames). {\n    unfold ConFilter.get_clear_frame.\n    split.\n    - apply Z.div_le_lower_bound; lia.\n    - apply Z.div_lt_upper_bound; lia.\n  }\n  destruct (get_clear_frame new_timer =? 0) eqn:?.\n  { replace (get_clear_frame new_timer) with 0 by lia.\n    step_call verif_Win1.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_body.\n    { unfold P4_bf2_win_md_t_rw.\n      entailer.\n      replace (P4Bit 8 0) with (P4Bit 8 (Z.b2z false)) by auto.\n      repeat first [\n        apply sval_refine_refl\n      | constructor\n      ].\n    }\n    Intros _.\n    step.\n    entailer.\n    destruct_listn x.\n    destruct_listn x0.\n    destruct_listn x1.\n    destruct_listn x2.\n    apply sval_refine_refl.\n  }\n  destruct (get_clear_frame new_timer =? 1) eqn:?.\n  { replace (get_clear_frame new_timer) with 1 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_body.\n    { unfold P4_bf2_win_md_t_rw.\n      entailer.\n      replace (P4Bit 8 0) with (P4Bit 8 (Z.b2z false)) by auto.\n      repeat first [\n        apply sval_refine_refl\n      | constructor\n      ].\n    }\n    Intros _.\n    step.\n    entailer.\n    destruct_listn x.\n    destruct_listn x0.\n    destruct_listn x1.\n    destruct_listn x2.\n    apply sval_refine_refl.\n  }\n  destruct (get_clear_frame new_timer =? 2) eqn:?.\n  { replace (get_clear_frame new_timer) with 2 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_body.\n    { unfold P4_bf2_win_md_t_rw.\n      entailer.\n      replace (P4Bit 8 0) with (P4Bit 8 (Z.b2z false)) by auto.\n      repeat first [\n        apply sval_refine_refl\n      | constructor\n      ].\n    }\n    Intros _.\n    step.\n    entailer.\n    destruct_listn x.\n    destruct_listn x0.\n    destruct_listn x1.\n    destruct_listn x2.\n    apply sval_refine_refl.\n  }\n  destruct (get_clear_frame new_timer =? 3) eqn:?.\n  { replace (get_clear_frame new_timer) with 3 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_body.\n    { unfold P4_bf2_win_md_t_rw.\n      entailer.\n      replace (P4Bit 8 0) with (P4Bit 8 (Z.b2z false)) by auto.\n      repeat first [\n        apply sval_refine_refl\n      | constructor\n      ].\n    }\n    Intros _.\n    step.\n    entailer.\n    destruct_listn x.\n    destruct_listn x0.\n    destruct_listn x1.\n    destruct_listn x2.\n    apply sval_refine_refl.\n  }\n  lia.\n(* This is slow. I can understand it but I don't know the direct reason. *)\nTime Qed.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/sbf/verif_Filter_query.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.19523797612340468}}
{"text": "Require Import Program SepAlg SepAlgInsts AssertionLogic SpecLogic SepAlgMap.\nRequire Import MapInterface MapFacts.\n\nRequire Import Charge.Logics.ILInsts.\nRequire Import Charge.Logics.ILogic.\nRequire Import Charge.Logics.ILEmbed.\nRequire Import Charge.Logics.BILogic.\nRequire Import Charge.Open.OpenILogic. \nRequire Import Charge.Open.Open.\nRequire Import Charge.Open.Subst.\nRequire Import Charge.Open.Stack.\nRequire Import Charge.Tactics.ILEmbedTac. \nRequire Import Charge.Tactics.ILQuantTac. \n\nRequire Import Java.Language.Lang.\nRequire Import Java.Semantics.SemCmd.\nRequire Import Java.Semantics.SemCmdRules.\nRequire Import Java.Logic.HeapArr.\n\nImport SepAlgNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSection Commands.\n\n  Inductive assign_sem (x : Lang.var) (e : dexpr) : semCmdType :=\n  | assign_ok : forall P s h v\n                       (He: eval e s = v),\n      assign_sem x e P 1 s h (Some (stack_add x v s, h)).\n  Program Definition assign_cmd x e := Build_semCmd (assign_sem x e) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation with eauto using assign_sem.\n    unfold frame_property; intros.\n    inversion HSem; subst; clear HSem; exists h...\n  Qed.\n\n  Inductive read_sem (x y : Lang.var) (f : field) : semCmdType :=\n  | read_ok : forall ref v P (s : stack) (h : heap)\n      (Rref  : s y = vptr ref)\n      (Rmaps : MapsTo (ref,f) v (fst h)),\n      read_sem x y f P 1 s h (Some (stack_add x v s, h))\n  | read_fail : forall ref P s (h : heap_ptr) (h' : heap_arr)\n      (Sref   : s y = vptr ref)\n      (Snotin : ~ In (ref,f) h),\n      read_sem x y f P 1 s (h, h') None.\n  Program Definition read_cmd x y f := Build_semCmd (read_sem x y f) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation with eauto using read_sem.\n    unfold frame_property; intros.\n    inversion HSem; subst n s0 h0 s' big'; clear HSem; exists h; intuition.\n    apply read_ok with ref; [assumption |]; specialize (HSafe _ (le_n _)).\n    destruct h, big, frame; simpl in *; subst.\n    apply sa_mul_split in HFrame.\n    destruct HFrame as [HFrame _].\n    destruct (sa_mul_mapstoR HFrame Rmaps) as [[H1 H2] | [H1 H2]]; [assumption|].\n    contradiction HSafe; apply read_fail with ref; assumption.\n  Qed.\n\nRequire Import Compare_dec.\n\n  Lemma in_list_fresh (lst : list nat) :\n    exists n, ~ List.In n lst.\n  Proof.\n    assert (exists n, forall x, List.In x lst -> n > x). {\n      induction lst. \n      + exists 0; intros x H. destruct H.\n      + destruct IHlst as [n IHlst].\n        destruct (gt_dec n a).\n        * exists n; intros. simpl in H.\n          destruct H. subst. assumption.\n          apply IHlst. apply H.\n        * assert (n <= a) by omega; clear n0.          \n          exists (S a); intros. simpl in H0.\n          destruct H0. subst. omega.\n          specialize (IHlst x H0). omega.\n    }\n    destruct H as [n H].                                                         \n    exists n. intros Hn. \n    specialize (H n Hn). omega.\n  Qed.\n\n  Lemma heap_arr_exists_fresh (h : heap_arr) :\n    exists k, forall i, ~ In (k, i) h.\n  Proof.\n    assert (forall lst, exists k, forall i, ~ In (k, i) h /\\ ~List.In k lst).\n    generalize dependent h.\n    apply (@map_induction (arrptr * nat) _ _ _ val \n                          (fun (h : heap_arr) => forall lst, exists k : arrptr, \n                                                   forall i : nat, ~ In (k, i) h /\\ \n                                                                   ~ List.In k lst)).\n    + intros.\n      destruct (in_list_fresh lst) as [x H1].\n      exists x; intros. split; [|assumption].\n      intros H2.\n      rewrite elements_Empty in H.\n      rewrite elements_in_iff in H2.\n      destruct H2 as [e H2]; rewrite H in H2.\n      inversion H2.\n    + intros. destruct x; simpl in *.\n      specialize (H (a::lst)).\n      destruct H as [k H].\n      exists k; intros.\n      specialize (H i). destruct H as [H2 H3].\n      simpl in H3.\n      assert (a <> k /\\ ~ List.In k lst). {\n        split. intros H4. apply H3. left. assumption.\n        intros H. apply H3. right. apply H.\n      }\n      destruct H as [H4 H5].\n      split; [|assumption].\n      unfold Add in H1.\n      specialize (H1 (k, i)).\n      rewrite add_neq_o in H1.\n      intros H. apply H2.\n      rewrite in_find_iff; rewrite in_find_iff in H.\n      intros H6.\n      apply H. rewrite H1. apply H6.\n      unfold Equivalence.equiv, complement; simpl.\n      intros. inversion H; subst. apply H4. reflexivity.\n    + destruct (H nil) as [k H1]; clear H.\n      exists k; intros. destruct (H1 i) as [H _].\n      apply H.\n  Qed.\n\n\n(*\n  Require Import ZArith.\n  Definition valid_path (vpath : list val) := \n    List.Forall (fun v => exists a, v = vint a /\\ (a >= 0)%Z) vpath.\n*)\n  Inductive read_arr_sem (x y : Lang.var) (path : list dexpr) : semCmdType :=\n  | read_arr_ok P arr s hp ha v vpath\n                (Sref : s y = varr arr)\n                (Smap : List.map (fun e => eval e s) path = vpath)\n(*                (Sarr : valid_path vpath)*)\n                (Sfind : find_heap_arr arr (List.map val_to_nat vpath) ha = Some v) :\n      read_arr_sem x y path P 1 s (hp, ha) (Some (stack_add x v s, (hp, ha)))\n  | read_arr_fail P arr s h vpath\n                  (Sref : s y = varr arr)\n                  (Smap : List.map (fun e => eval e s) path = vpath)\n                  (Sarr : ~ in_heap_arr arr (List.map val_to_nat vpath) (snd h)) :\n      read_arr_sem x y path P 1 s h None.\n  Program Definition read_arr_cmd x y path := Build_semCmd (read_arr_sem x y path) _ _.\n  Next Obligation.\n    intros H. inversion H.\n  Qed.\n  Next Obligation.\n    unfold frame_property; intros; exists h.\n    inversion HSem; subst; specialize (HSafe _ (le_n _)). \n    split; [assumption|].\n    destruct h as [hp' ha'].\n    apply read_arr_ok with (arr := arr) (vpath := (List.map (fun e : dexpr => eval e s)) path);\n      try assumption; try reflexivity.\n    destruct frame.\n    apply sa_mul_split in HFrame as [_ HFrame].\n\n    assert (in_heap_arr arr (List.map val_to_nat (List.map (fun e : dexpr => eval e s) path)) ha').\n    apply dec_double_neg; [apply in_heap_arr_dec | intro H].\n    apply HSafe.\n    eapply read_arr_fail; try eassumption; try reflexivity.\n    eapply find_heap_arr_frame; eauto.\n  Qed.    \n\n  Inductive write_arr_sem (x : Lang.var) (path : list dexpr) (e : dexpr) : semCmdType :=\n  | write_arr_ok P arr s hp ha ha' vpath\n                 (Sref : s x = varr arr)\n                 (Smap : List.map (fun e' => eval e' s) path = vpath)\n                 (Sin  : in_heap_arr arr (List.map val_to_nat vpath) ha)\n                 (Sha  : add_heap_arr arr (List.map val_to_nat vpath) ha (eval e s) = Some ha') :\n      write_arr_sem x path e P 1 s (hp, ha) (Some (s, (hp, ha')))\n  | write_arr_fail P arr s h vpath\n                   (Sref : s x = varr arr)\n                   (Smap : List.map (fun e' => eval e' s) path = vpath)\n                   (Sin  : ~ in_heap_arr arr (List.map val_to_nat vpath) (snd h)) :\n      write_arr_sem x path e P 1 s h None.\n  Program Definition write_arr_cmd x path e := Build_semCmd (write_arr_sem x path e) _ _.\n  Next Obligation.\n    intros H. inversion H.\n  Qed.\n  Next Obligation.\n    unfold frame_property; intros; inversion HSem; subst; clear HSem.\n    destruct h, frame.\n    apply sa_mul_split in HFrame as [Hhp Hha].\n    specialize (HSafe _ (le_n _)).\n    assert (in_heap_arr arr\n          (List.map val_to_nat (List.map (fun e' : dexpr => eval e' s') path))\n          h0). {\n      apply dec_double_neg; [apply in_heap_arr_dec | intro H].\n      apply HSafe; eapply write_arr_fail; try eassumption; reflexivity.\n    }\n\n    destruct (add_heap_arr_frame _ _ _ _ _ _ _ Hha Sha H) as [ha'' [H1 H2]].\n    exists (h, ha'').\n    split.\n    split; simpl. apply Hhp. apply H1.\n    eapply write_arr_ok; try eassumption; reflexivity.\n  Qed.\n\n  Inductive alloc_arr_sem (x : Lang.var) (e : dexpr) : semCmdType :=\n  | alloc_arr_ok (P : Program) (s s' : stack) (hp : heap_ptr) (ha ha' : heap_arr) (n : nat)\n                 (Sfresh_ha : forall i, ~ In (n, i) ha) \n                 (Sha : alloc_heap_arr n (val_to_nat (eval e s)) ha === ha') \n                 (Ss : s' = stack_add x (varr n) s) :\n      alloc_arr_sem x e P 1 s (hp, ha) (Some (s', (hp, ha'))).\n  Program Definition alloc_arr_cmd x e := Build_semCmd (alloc_arr_sem x e) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation.\n    unfold frame_property; intros; inversion HSem; subst P n s s' big big'.\n    destruct h, frame.\n    apply sa_mul_split in HFrame as [Hhp Hha].\n    specialize (HSafe _ (le_n _)).\n    Lemma alloc_heap_arr_frame (n m : nat) (h frame h' h'' : heap_arr)\n          (Hfresh : forall i, ~ In (n, i) frame)\n          (Hh : alloc_heap_arr n m h === h')\n          (HFrame : sa_mul h'' frame h) :\n      exists h''', alloc_heap_arr n m h'' === h''' /\\ sa_mul h''' frame h'.\n    Proof.\n      admit.\n      (*\n      generalize dependent h'; induction m; simpl in *; intros.\n      + setoid_rewrite <- Hh.\n        exists (add (n, 0) null h''); split; [reflexivity|].\n        apply sa_mul_add; [assumption | apply Hfresh]. \n      + assert (alloc_heap_arr n m h === alloc_heap_arr n m h) by reflexivity.\n        destruct (IHm _ H) as [h'''' [H1 H2]].\n        exists (add (n, m) null h'''').\n        split.\n        rewrite H1. reflexivity.\n        rewrite <- Hh.\n        apply sa_mul_add. assumption.\n        apply Hfresh.\n*)\n    Qed.\n    \n    assert (forall i : nat, ~ In (n0, i) h2) as Sfresh_frame. {\n      intros i H; apply Sfresh_ha with i.\n      apply sa_mulC in Hha; destruct (sa_mul_inL Hha H); assumption.\n    }\n    destruct (alloc_heap_arr_frame Sfresh_frame Sha Hha) as [ha'' [H1 H2]].\n    exists (h, ha''). split. split; simpl; assumption.\n    apply alloc_arr_ok with n0; try assumption.\n    intros i H.\n    specialize (Sfresh_ha i). apply Sfresh_ha.\n    destruct (sa_mul_inL Hha H). apply H3.\n  Qed.\n\n  Inductive alloc_sem (x : Lang.var) (C : class) : semCmdType :=\n  | alloc_ok : forall (P : Program) (s s0 : stack) (h h0 : heap_ptr) (h' : heap_arr) n fields\n      (Snotnull : (n, C) <> pnull)\n      (Sfresh_h : forall f, ~ In ((n, C), f) h)\n      (Sfields  : field_lookup P C fields)\n      (Sh0      : sa_mul h\n        (fold_right (fun f h' => add ((n, C), f) (pnull : val) h') heap_ptr_unit fields) h0)\n      (Ss0      : s0 = stack_add x (vptr (n, C)) s),\n      alloc_sem x C P 1 s (h, h') (Some (s0, (h0, h'))).\n  Program Definition alloc_cmd x C := Build_semCmd (alloc_sem x C) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation.\n    unfold frame_property; intros.\n    inversion HSem; subst; clear HSem.\n    destruct h, frame; simpl in *.\n    apply sa_mul_split in HFrame. destruct HFrame as [HFrame HFrameArr].\n    destruct (sa_mulA HFrame Sh0) as [h5 [H1 H2]].\n    apply sa_mulC in H2; destruct (sa_mulA H1 H2) as [h6 [H3 H5]].\n    exists (h6, h2).\n    split; [split; simpl; [apply sa_mulC|]; assumption|].\n    eapply alloc_ok; [eassumption | | eassumption | apply sa_mulC; assumption | reflexivity].\n    intros f H6; apply (Sfresh_h f).\n    apply sa_mulC in H2.\n    destruct (sa_mul_inL H2 H6) as [H8 H9].    \n    destruct (sa_mul_inR Sh0 H9) as [[H10 H11] | [H10 H11]]; [assumption|].\n    apply sa_mulC in H1; destruct (sa_mul_inL H1 H10); intuition.\n  Qed.\n\n  Inductive write_sem (x:Lang.var) (f:field) (e:dexpr) : semCmdType := \n  | write_ok : forall P (s: stack) (h h' : heap_ptr) (h'' : heap_arr) ref v\n      (Sref: s x = vptr ref)\n      (Sin:  In (ref,f) h )\n      (Heval : eval e s = v)\n      (Sadd: h' = add (ref,f) v h ),\n      write_sem x f e P 1 s (h, h'') (Some (s, (h', h'')))\n  | write_fail : forall P (s: stack) h h'' ref\n      (Sref:   s x = vptr ref)\n      (Sin : ~ In (ref, f) h),\n      write_sem x f e P 1 s (h, h'') None.\n  Program Definition write_cmd x f e := Build_semCmd (write_sem x f e) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation.\n    unfold frame_property; intros.\n    inversion HSem. subst; clear HSem.\n    destruct h, frame; simpl in *.\n    apply sa_mul_split in HFrame as [HFrame HFramePtr].\n    assert (~ In (ref, f) h2).\n    intros H. \n    apply (HSafe 1); [omega |].\n    eapply write_fail; [eassumption|].\n    destruct (sa_mul_inR HFrame Sin); intuition.\n    exists ((add (ref, f) (eval e s') h, h1)). split.\n    split.\n    apply sa_mul_add; assumption. simpl. assumption.\n    eapply write_ok; try eassumption; try reflexivity.\n    destruct (sa_mul_inR HFrame Sin); intuition.\n  Qed.\n\n  Fixpoint create_stack (ps : list Lang.var) (vs : list val) : stack :=\n    match ps, vs with\n      | nil, nil => stack_empty Lang.var val\n      | p :: ps, v :: vs =>\n        stack_add p v (create_stack ps vs)\n      | _, _ => stack_empty Lang.var val\n    end.\n        \n  Inductive call_sem (rvar : Lang.var) (C : open class) m es (c : cmd) (sc : semCmd)\n    : semCmdType :=\n  | call_failS : forall (P : Program) s h\n      (HLFail  : forall mrec, ~ method_lookup P (C s) m mrec),\n      call_sem rvar C m es c sc P 1 s h None\n  | call_failC : forall (P : Program) ps rexpr (s : stack) h n\n      (HLookup : method_lookup P (C s) m (Build_Method ps c rexpr))\n      (HLen    : length ps = length es)\n      (HFail   : sc P n (create_stack ps (eval_exprs s es)) h None),\n      call_sem rvar C m es c sc P (S n) s h None\n  | call_failL : forall (P : Program) ps rexpr s h\n      (HLookup : method_lookup P (C s) m (Build_Method ps c rexpr))\n      (HLen    : length ps <> length es),\n      call_sem rvar C m es c sc P 1 s h None\n  | call_ok    : forall (P : Program) ps rexpr (s sr : stack) h hr n\n      (HLookup : method_lookup P (C s) m (Build_Method ps c rexpr))\n      (HLen    : length ps = length es)\n      (HSem    : sc P n (create_stack ps (eval_exprs s es)) h (Some (sr, hr))),\n      call_sem rvar C m es c sc P (S n) s h\n        (Some (stack_add rvar (eval rexpr sr) s, hr)).\n  Program Definition call_cmd rvar C m es c sc := Build_semCmd (call_sem rvar C m es c sc) _ _.\n  Next Obligation.\n    intros H; inversion H.\n  Qed.\n  Next Obligation with eauto using call_sem.\n    unfold frame_property; intros.\n    inversion HSem; subst; clear HSem.\n    edestruct (@cmd_frame sc) as [h1 [HFrame1 HSem1]]...\n    intros k HLe HFail; apply HSafe with (S k); [omega |]...\n  Qed.\n\n  Inductive semantics : cmd -> semCmd -> Prop :=\n  | semassign : forall x e,\n      semantics (cassign x e) (assign_cmd x e)\n  | semread   : forall x y f,\n      semantics (cread x y f) (read_cmd x y f)\n  | semalloc  : forall x C,\n      semantics (calloc x C) (alloc_cmd x C)\n  | semwrite  : forall x f e,\n      semantics (cwrite x f e) (write_cmd x f e)\n  | semarrread : forall x y es,\n                   semantics (carrread x y es) (read_arr_cmd x y es)\n  | semarrwrite : forall x es e,\n                   semantics (carrwrite x es e) (write_arr_cmd x es e)\n  | semarralloc : forall x (e : dexpr),\n                    semantics (carralloc x e) (alloc_arr_cmd x e)\n  | semskip   : semantics cskip skip_cmd\n  | semseq    : forall c1 c2 sc1 sc2\n      (HL : semantics c1 sc1)\n      (HR : semantics c2 sc2),\n      semantics (cseq c1 c2) (seq_cmd sc1 sc2)\n  | semif     : forall e cl cr scl scr\n      (HL : semantics cl scl)\n      (HR : semantics cr scr),\n      semantics (cif e cl cr) (nondet_cmd\n        (seq_cmd (assume_cmd (vlogic_eval e)) scl)\n        (seq_cmd (assume_cmd (vlogic_eval (E_not e))) scr))\n  | semwhile  : forall e c sc\n      (HS : semantics c sc),\n      semantics (cwhile e c) (seq_cmd (kleene_cmd\n        (seq_cmd (assume_cmd (vlogic_eval e)) sc)) (assume_cmd (vlogic_eval (E_not e))))\n  | semdcall  : forall (x y : Lang.var) m es c sc \n      (HSem     : semantics c sc),\n      semantics (cdcall x y m es) (call_cmd x ((liftn val_class) (var_expr y)) m ((E_var y) :: es) c sc)\n  | semscall  : forall (x : Lang.var) (C : class) m es c sc\n      (HSem     : semantics c sc),\n      semantics (cscall x C m es) (call_cmd x (open_const C) m es c sc)\n  | semassert : forall e,\n      semantics (cassert e) (assert_cmd (vlogic_eval e)).\n\n  Definition c_not_modifies c x :=\n    forall sc, semantics c sc -> not_modifies sc x.\n\n  Lemma modifies_syn_sem c x :\n     ~ List.In x (modifies c) -> c_not_modifies c x.\n  Proof.\n    induction c; simpl in *; intros HNM; intros sc HSem; inversion_clear HSem.\n    + intros P s s0 h h0 n HAsgn;\n      simpl in *; inversion HAsgn; subst.\n      rewrite stack_lookup_add2; trivial.\n      intuition congruence.\n    + intros P s s0 h h0 n HSkip; simpl in *; inversion HSkip; subst; trivial.\n    + intros P s s0 h h0 n HSeq; simpl in *; inversion HSeq; subst.\n      transitivity (s2 x).\n      * eapply IHc1; [| eassumption | eassumption]; intros HIn; apply HNM;\n        rewrite in_app_iff; auto.\n      * eapply IHc2; [| eassumption | eassumption]; intros HIn; apply HNM;\n        rewrite in_app_iff; auto.\n    + intros P s s0 h h0 n HND; simpl in *; inversion HND; subst; clear HND.\n      * inversion H4; subst.\n        apply assume_inv in H6; destruct H6; subst.\n        eapply IHc1; [| eassumption | eassumption]; intros HIn; apply HNM;\n          rewrite in_app_iff; auto.\n      * inversion H4; subst.\n        apply assume_inv in H6; destruct H6; subst.\n        eapply IHc2; [| eassumption | eassumption]; intros HIn; apply HNM;\n        rewrite in_app_iff; auto.\n    + intros P s s0 h h0 n HKl; simpl in *; inversion HKl; subst; clear HKl.\n      apply assume_inv in H6; destruct H6; subst; simpl in *.\n      remember (Some (s0, h0)); induction H5; subst;\n        [inversion Heqo; trivial | discriminate | discriminate |].\n      transitivity (s1 x); simpl in *.\n      * inversion H; subst; clear H.\n        apply assume_inv in H7; destruct H7; subst.\n        eapply IHc; eassumption.\n      * apply IHkleene_sem; assumption.\n    + intros P s s0 h h0 n HWr; simpl in *; inversion HWr; subst; reflexivity.\n    + intros P s s0 h h0 n HRd; simpl in *;\n      inversion HRd; subst; rewrite stack_lookup_add2; trivial;\n      intuition congruence.\n    + intros P s s0 h h0 n Hrd; simpl in *.\n      inversion Hrd; subst. rewrite stack_lookup_add2; [reflexivity | intuition congruence ].\n    + intros P s s0 h h0 n Hrd; simpl in *; inversion Hrd; reflexivity.\n    + intros P s s0 h h0 n Hrd; simpl in *.\n      inversion Hrd; subst. rewrite stack_lookup_add2; [reflexivity | intuition congruence].\n    + intros P s s0 h h0 n HCl; simpl in *;\n      inversion HCl; subst; rewrite stack_lookup_add2; trivial;\n      intuition congruence.\n    + intros P s s0 h h0 n HCl; simpl in *;\n      inversion HCl; subst; rewrite stack_lookup_add2; trivial;\n      intuition congruence.\n    + intros P s s0 h h0 n HCl; simpl in *;\n      inversion HCl; subst; rewrite stack_lookup_add2; trivial;\n      intuition congruence.\n    + intros P s s0 h h0 n HAs; inversion HAs; subst; reflexivity.\n  Qed.\n\n  (* A reasonable alternative definition would be\n   * [ [E] sc, [pure] semantics c sc [/\\] triple _ P Q sc ]\n   *\n   * The two definitions should really be equivalent, but proving that to be\n   * the case requires proving that [semantics] is a total and functional\n   * relation. This might not be straightforward since it requires induction\n   * over some number of steps, either by indexing [semantics] with [nat] or by\n   * somehow using the number that's in the semCmd parameter.\n   *\n   * The definition chosen here allows us to lift all the proof rules about\n   * triples that we care about into c_triple. The proof rules that cannot be\n   * lifted here but could be lifted with the other definition seem to be more\n   * obscure. For example, {true} c {true} |= [E]s,[E]h, safe c s h. Here, the\n   * witness for the existential depends on the triple, but the triple cannot\n   * be taken apart without guessing a semantic command.\n   *)\n\nEnd Commands.\n\n  Local Transparent ILPre_Ops.\n  Local Transparent ILFun_Ops.\n\n  Definition triple (P Q : sasn) (c : cmd) :=\n    Forall sc : semCmd, (semantics c sc) ->> {{P}} sc {{Q}}.\n\n  Notation \" '{[' P ']}' c '{[' Q ']}' \" := (triple P Q c) (at level 89,\n    format \" {[ P ]} '/' c '/' {[ Q ]} \").\n\n  Add Parametric Morphism : triple with signature\n    lentails --> lentails ++> eq ==> lentails\n    as triple_entails_m.\n  Proof.\n    intros p p' Hp q q' Hq c.\n    unfold triple. \n    setoid_rewrite Hq; setoid_rewrite <- Hp. reflexivity.\n  Qed.\n\nOpen Scope open_scope.\n\n  Definition method_spec C m (ps : list Lang.var) (rn : Lang.var) (P Q : sasn) := (\n    NoDup (rn :: ps) /\\\\\n    Exists ps' : (list Lang.var), Exists c : cmd, Exists re : dexpr,\n      [prog] (fun X : Program => method_lookup X C m (Build_Method ps' c re)\n        /\\ length ps = length ps' /\\\n        (forall x, List.In x ps' -> ~ List.In x (modifies c)))\n      //\\\\ {[ P //! zip ps (List.map var_expr ps') ]}\n         c {[ Q //! zip (rn :: ps) (eval re :: (List.map var_expr ps'))]}\n    ).\n\n  Notation \" C ':.:' m |-> ps {{ P }}-{{ r , Q }} \" :=\n    (method_spec C m ps r P Q) (at level 60).\n\n  Add Parametric Morphism : method_spec with signature\n    eq ==> eq ==> eq ==> eq ==>\n      lentails --> lentails ++> lentails\n    as method_spec_entails_m.\n  Proof.\n    intros C m ps rn P P' HP Q Q' HQ. unfold method_spec.\n    (* Unravel the two almost identical sides of the entailment first because\n        setoid_rewrite doesn't seem to go under these binders. *)\n    apply lpropandL; intro H. apply lpropandR; [assumption|].\n    lexistsL ps' c re. lexistsR ps' c re.\n    apply landR; [apply landL1; reflexivity | apply landL2].\n    admit.\n(*    setoid_rewrite HP. setoid_rewrite HQ. reflexivity.*)\n  Qed.\n\n  Add Parametric Morphism : method_spec with signature\n    eq ==> eq ==> eq ==> eq ==>\n      lequiv ==> lequiv ==> lequiv\n    as method_spec_bientails_m.\n  Proof.\n    split; apply method_spec_entails_m; try rewrite ?H, ?H0; reflexivity.\n  Qed.\n\n\n  Lemma c_triple_zero P (p q : sasn) (c : cmd) :\n    ({[ p ]} c {[ q ]}) P 0.\n  Proof.\n    intros sc n Hn Q HPQ sem R k m s h HQR Hk Hv Hp.\n    assert (m = 0) by omega.\n    assert (k = 0) by omega.\n    subst. split.\n    + apply safe_zero.\n    + intros h' s'' Hc. apply cmd_zero in Hc. contradiction.\n  Qed.\n\n(* Arguments swapped to please the type classes *)\n\n  Definition typeof (C : class) (v : val) : Prop := exists p, v = vptr p /\\ snd p = C.\n(*\n  Notation \" x ':::' C \" := \n    (@coerce _ _ (@lift2_C _ _ _ _) typeof (@coerce _ _ (@lift0_C _ _) C) (var_expr x)) (at level 60).\n\n  (* TODO: should P,Q be allowed to reference stack vars from the outside? *)\n  Definition expr_spec x m (ps: list var) (r: var) (P Q: hasn) : hasn :=\n    (<E> C, <pure> x:::C </\\> lift0 (FunI (C:.:m |-> ps {{P}}-{{r,Q}})))\n    %asn.\n\n  Arguments Scope expr_spec [_ _ _ _ asn_scope asn_scope].\n\n  Notation \" x ':..:' m |-> ps {{ P }}-{{ r , Q }} \" :=\n    (expr_spec x m ps r P Q) (at level 60).\n*)\n\nSection StructuralRules.\n\n  Lemma triple_false (G : spec) (Q : sasn) c :\n    G |-- {[lfalse]} c {[Q]}.\n  Proof.\n    intros n; simpl in *; intros; destruct H4.\n  Qed.\n\n  Lemma roc (P P' Q Q' : sasn) c (G : spec)\n    (HPre  : P  |-- P')\n    (HPost : Q' |-- Q)\n    (Hc    : G  |-- {[P']} c {[Q']}) :\n    G |-- {[P]} c {[Q]}.\n  Proof.  \n    rewrite Hc.\n    unfold triple. lforallR sc. apply lpropimplR; intros Hsc.\n    lforallL sc. apply lpropimplL; [assumption|]. apply rule_of_consequence; assumption.\n  Qed.\n\n  Lemma roc_pre (P P' Q : sasn) c G\n    (HPre : P |-- P')\n    (Hc   : G |-- {[P']} c {[Q]}) :\n    G |-- {[P]} c {[Q]}.\n  Proof.\n  \teapply roc; eassumption || reflexivity.\n  Qed.\n\n  Lemma roc_post (P Q Q' : sasn) c G\n    (Hc : G  |-- {[P]} c {[Q']})\n    (HPost : Q' |-- Q) :\n    G |-- {[P]} c {[Q]}.\n  Proof.\n    eapply roc; eassumption || reflexivity.\n  Qed.\n  \n  Lemma rule_frame_ax_list P Q R c (xs: list Lang.var)\n    (HMod : forall x, ~ List.In x xs -> c_not_modifies c x) :\n    {[ P ]} c {[ Q ]} |--\n    {[ P ** R ]} c {[ Q ** Exists vs, apply_subst R (subst_fresh vs xs) ]}.\n  Proof.\n    unfold triple. lforallR sc; apply lpropimplR; intro Hsc. lforallL sc. \n    apply lpropimplL; [assumption|].\n    apply frame_rule. unfold c_not_modifies in HMod. intros. apply HMod; auto.\n  Qed.\n\n  Definition subst_mod_asn (R: sasn) (c: cmd) : sasn :=\n    Exists vs, apply_subst R (subst_fresh vs (modifies c)).\n\n  Lemma rule_frame_ax P Q R c : \n    {[ P ]} c {[ Q ]} |--\n    {[ P ** R ]} c {[ Q ** subst_mod_asn R c ]}.\n  Proof.\n    apply rule_frame_ax_list. intros x HnotIn. apply modifies_syn_sem.\n    assumption.\n  Qed.\n\n  Lemma rule_frame P Q R c G \n    (HPre : G |-- {[P]} c {[Q]}) :\n    G |-- {[ P ** R ]} c {[ Q ** subst_mod_asn R c ]}.\n  Proof.\n    intros; rewrite <- rule_frame_ax; assumption.\n  Qed.\n  Implicit Arguments rule_frame [[P] [Q] [R] [c] [G]].\n\n  Lemma exists_into_precond2 {A} (P: A -> sasn) c q :\n    (Forall x, {[P x]} c {[q]}) -|- {[Exists x, P x]} c {[q]}.\n  Proof.\n    unfold triple; setoid_rewrite <- exists_into_precond; split.\n    + lforallR sc. apply lpropimplR; intro Hsc; lforallR x.\n      lforallL x sc. apply lpropimplL; [assumption | reflexivity].\n    + lforallR x sc. apply lpropimplR; intro Hsc.\n      lforallL sc. apply lpropimplL; [assumption | lforallL x; reflexivity].\n  Qed.\n  \n  Lemma existentialise_triple (x : Lang.var) (P Q : sasn) c (G : spec) \n\t(H : forall (v : val), G |-- {[@lembedand vlogic sasn _ _ (open_eq (x/V) (`v)) P]} c {[Q]}) :\n    G |-- {[P]} c {[Q]}.\n  Proof.\n    eapply roc_pre; [apply existentialise_var with (x0 := x)|].\n    rewrite <- exists_into_precond2. lforallR y. apply H.\n  Qed.\n\nEnd StructuralRules.", "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/Semantics/OperationalSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.19523796842054864}}
{"text": "From iris.base_logic.lib Require Export fancy_updates wsat.\nFrom iris.proofmode Require Import base tactics classes.\nFrom mwp Require Import mwp mwp_adequacy mwp_lifting.\nFrom mwp.mwp_modalities.ni_logrel Require Import mwp_right.\nFrom iris.program_logic Require Export ectxi_language ectx_language language.\n\nSection mwp_left.\n  Context {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n  Typeclasses Transparent mwpC_state_interp mwpC_modality.\n\n  Definition mwpd_left : mwpData \u039b \u03a3 :=\n    {| mwpD_state_interp := mwpD_SI;\n       mwpD_Extra := [Prod val \u039b; nat];\n       mwpD_modality_index := [Prod expr \u039b];\n       mwpD_modality_bind_condition e1 e2 f g :=\n         \u2203 K (_: LanguageCtx K),\n           e1 = K e2 \u2227 g = (\u03bb x y, (y.1, x.2 + y.2)) \u2227\n           \u2200 v k, f (v, k) = K (of_val v);\n      mwpD_modality idx E n \u03a6 :=\n        MWP@{mwpd_right mwpD_SI', n} idx @ E {{ w; k, \u03a6 (w, k) }}%I;\n    |}.\n\n  Global Instance mwpC_left : mwpC mwpd_left.\n  Proof.\n    split.\n    - intros idx E m n ? ? ?; simpl. apply mwp_ne.\n      intros ? ? ?; auto.\n    - intros idx E1 E2 n \u03a6 \u03a8 HE; simpl.\n      iIntros \"HP Hic\".\n      iApply (mwp_strong_mono_wand _ _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      by iIntros (? ? ?) \"?\"; iApply \"HP\".\n    - iIntros (idx E n \u03a6) \"H\";simpl.\n      iApply mwp_right_intro; last eauto. simpl; lia.\n    - intros e e' f g E n m \u03a6 (K & HK & He & Hg & Hf); simplify_eq.\n      iIntros \"H\"; simpl.\n      iApply (mwp_right_bind _ _ _ _ _ _ n m); simpl; first done.\n      iApply (mwp_strong_mono_wand _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      iIntros (v l _); rewrite Hf /=.\n      iIntros \"H\".\n      iApply (mwp_strong_mono_wand _ _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      by iIntros (? j _) \"?\".\n  Qed.\n\n  Global Instance mwpC_left_is_outer_fupd idx :\n    mwpMIsOuterModal mwpd_left idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_left_is_outer_bupd idx :\n    mwpMIsOuterModal mwpd_left idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_left_is_outer_except_0 idx :\n    mwpMIsOuterModal mwpd_left idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_left_is_inner_fupd idx :\n    mwpMIsInnerModal mwpd_left idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_fupd _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  Global Instance mwpC_left_is_inner_bupd idx :\n    mwpMIsInnerModal mwpd_left idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_bupd _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  Global Instance mwpC_left_is_inner_except_0 idx :\n    mwpMIsInnerModal mwpd_left idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_except_0 _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  (* Global Instance mwpC_left_SupportsAtomicShift idx : *)\n  (*   mwpMSupportsAtomicShift mwpd_left idx. *)\n  (* Proof. *)\n  (*   rewrite /mwpMSupportsAtomicShift /mwpC_modality /mwpD_modality /=. *)\n  (*   iIntros (n E1 E2 \u03a6 Hn) \"H\". *)\n  (*   iApply (mwp_shift (mwpd_indexed_step_fupd mwpD_SI')); *)\n  (*     eauto using mwp_indexed_step_fupd_AlwaysSupportsShift. *)\n  (* Qed. *)\n\n  Global Program Instance mwpC_left_SplitForStep idx :\n    mwpMSplitForStep mwpd_left idx :=\n    {|\n      mwpM_split_for_step_M1 E P := |={E, \u2205}=> \u25b7 P;\n      mwpM_split_for_step_M2 E P := |={\u2205, E}=> P;\n    |}%I.\n  Next Obligation.\n  Proof.\n    iIntros (e n E P) \"HP /=\".\n    rewrite /mwpC_modality /mwpD_modality /=.\n    by iApply (mwp_indexed_step_fupd_index_step_fupd _ _ 1).\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    by iMod \"HP\"; iModIntro; iApply \"HPQ\".\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    iMod \"HP\"; iModIntro. by iApply \"HPQ\".\n  Qed.\n\n  Lemma mwp_left_strong_bind\n        K `{!LanguageCtx K} K' `{!LanguageCtx K'} E e e' \u03a6 :\n    MWP@{mwpd_left, e'} e @ E {{ v; m | w ; k,\n      MWP@{mwpd_left, K' (of_val w)}\n        K (of_val v) @ E {{ w; n | u ; y, \u03a6 w (m + n) (u, (k + y)) }} }}\n    \u22a2 MWP@{mwpd_left, K' e'} K e @ E {{ \u03a6 }}.\n  Proof.\n    iIntros \"H\".\n    iApply (@mwp_bind _ _ _ mwpC_left K _ _ e'\n                     (\u03bb '(v, k), K' (of_val v))\n                     (\u03bb x y, (y.1, x.2 + y.2))).\n    { rewrite /mwpC_modality_bind_condition /=; eauto. }\n    iApply mwp_mono; last eauto.\n    intros ? ? []; auto.\n  Qed.\n\nLemma mwp_left_change_of_index e1' e2' f E e \u03a6 :\n  (\u2200 \u03a8 n,\n      MWP@{mwpd_right mwpD_SI', n}\n        e1' @ E {{ v; n | [_], \u03a8 (f (v, n)) }} -\u2217\n        MWP@{mwpd_right mwpD_SI', n}\n        e2' @ E {{ v; n | [_], \u03a8 (v, n) }})\n  -\u2217 MWP@{mwpd_left, e1'} e @ E {{ \u03bb v n x, \u03a6 v n (f x) }}\n  -\u2217 MWP@{mwpd_left, e2'} e @ E {{ \u03a6 }}.\nProof.\n  iIntros \"Hm H\".\n  iApply (mwp_change_of_index mwpd_left with \"[Hm] H\").\n  iIntros (\u03a8 n) \"H\".\n  by iApply \"Hm\".\nQed.\n\nLemma mwp_left_pure_step_index `{!Inhabited (state \u039b)}  e1' e2' E e \u03a6 \u03c6 n :\n  PureExec \u03c6 n e2' e1' \u2192\n  \u03c6 \u2192\n  MWP@{mwpd_left, e1'} e @ E {{ v;k | w;m, \u03a6 v k (w, n + m) }}\n  \u22a2 MWP@{mwpd_left, e2'} e @ E {{ v;m | [x], \u03a6 v m x }}.\nProof.\n  iIntros (Hexec H\u03c6) \"Hic\".\n  iApply (mwp_left_change_of_index _ _ (\u03bb '(v, m), (v, n + m))).\n  - iIntros (??) \"H\".\n    iApply mwp_right_pure_step; first done.\n    iNext. iApply \"H\".\n  - iApply mwp_wand_r; iSplitL; first iApply \"Hic\".\n    by iIntros (??[]) \"Hic\".\nQed.\n\nEnd mwp_left.\n\nSection lifting.\n\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI': state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_fupd_lift_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n    (\u2200 \u03c31, mwpD_SI \u03c31 -\u2217\n      |={E, \u2205}=>\n     \u25b7 \u2200 e2 \u03c32,\n         \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n            (mwpD_SI \u03c32 \u2217 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n                    e2 @ E {{ v; n| [x], \u03a6 v (S n) x }}))\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (?) \"?\".\n  iApply (mwp_lift_step (mwpd_left mwpD_SI mwpD_SI') idx E); simpl; auto.\nQed.\n\nLemma mwp_left_lift_pure_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2 \u03c32, prim_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n      \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e2 @ E\n        {{ v; n | [x], \u03a6 v (S n) x }})\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_step\n            (mwpd_left mwpD_SI mwpD_SI') idx E);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_left_lift_atomic_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 \u2200 v2 \u03c32,\n            \u231cprim_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d\n             ={\u2205, E}=\u2217 (mwpD_SI \u03c32 \u2217\n                        MWP@{mwpd_right mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (??).\n  by iApply (mwp_lift_atomic_step\n               (mwpd_left mwpD_SI mwpD_SI') idx E).\nQed.\n\nLemma mwp_left_lift_atomic_det_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n  (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     \u25b7 (\u2203 v2 \u03c32,\n         \u231c\u2200 e2' \u03c32', prim_step e1 \u03c31 [] e2' \u03c32' [] \u2192\n                     \u03c32 = \u03c32' \u2227 to_val e2' = Some v2\u231d \u2227\n                     |={\u2205, E}=> mwpD_SI \u03c32 \u2217\n                          MWP@{mwpd_right mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by iIntros (??);\n    iApply (mwp_lift_atomic_det_step\n              (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_left_lift_pure_det_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2' \u03c32, prim_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  \u25b7 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_det_step\n            (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_left_pure_step `{!Inhabited (state \u039b)} idx E e1 e2 \u03c6 n \u03a6 :\n  PureExec \u03c6 n e1 e2 \u2192\n  \u03c6 \u2192\n  \u25b7^n MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v ; m | [x], \u03a6 v (n + m) x }}\n  \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (Hexec H\u03c6) \"Hic\".\n  iApply (mwp_pure_step (mwpd_left mwpD_SI mwpD_SI') idx); eauto.\n  clear Hexec.\n  iInduction n as [] \"IH\" forall (\u03a6); simpl; auto.\n  iApply step_fupd_intro; first set_solver.\n  iApply (\"IH\" $! (\u03bb w k, \u03a6 w (S k)) with \"Hic\").\nQed.\n\nEnd lifting.\n\nSection mwp_ectx_lifting.\n\nContext {\u039b : ectxLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_left_lift_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 \u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n                          e2 @ E {{ w; n | [x], \u03a6 w (S n) x }}))\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by intros;\n    iApply (mwp_lift_head_step\n              (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_left_lift_pure_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n      \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n        e2 @ E {{ w; n| [x], \u03a6 w (S n) x }})\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_head_step\n            (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_left_lift_atomic_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     \u25b7 \u2200 v2 \u03c32,\n       \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n          (mwpD_SI \u03c32 \u2217 MWP@{mwpd_right mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n     \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by intros;\n    iApply (mwp_lift_atomic_head_step\n              (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_left_lift_pure_det_head_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  \u25b7 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_det_head_step\n            (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nEnd mwp_ectx_lifting.\n\nSection mwp_ectxi_lifting.\n\nContext {\u039b : ectxiLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : (val \u039b) \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\nImplicit Types v : (val \u039b).\nImplicit Types e : (expr \u039b).\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_left_lift_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 (\u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n                            e2 @ E {{ w; n | [x], \u03a6 w (S n) x }})))\n     \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by iIntros (??);\n    iApply (mwp_lift_head_step'\n              (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_left_lift_pure_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n       \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n       MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n         e2 @ E {{ w; n | [x], \u03a6 w (S n) x }})\n     \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_head_step'\n            (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1); eauto.\n   by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_left_lift_atomic_head_step' idx E \u03a6 e1:\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n      \u25b7 (\u2200 v2 \u03c32,\n          \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n           (mwpD_SI \u03c32 \u2217 MWP@{mwpd_right mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }})))\n    \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???).\n  by iApply (mwp_lift_atomic_head_step'\n               (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_left_lift_pure_det_head_step' idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2') \u2192\n  \u25b7 MWP@{mwpd_left mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_det_head_step'\n            (mwpd_left mwpD_SI mwpD_SI') idx E \u03a6 e1); eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nEnd mwp_ectxi_lifting.\n\nSection basmwp_soundness.\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nLemma mwp_left_adequacy_basic idx E e \u03c3 \u03a6 :\n  mwpD_SI \u03c3 \u2217 MWP@{mwpd_left mwpD_SI mwpD_SI', idx} e @ E {{ \u03bb v n x, \u03a6 v n x.1 x.2 }} -\u2217\n    \u2200 (rd : Reds e \u03c3),\n      MWP@{mwpd_right mwpD_SI', nstps rd}\n                          idx @ E {{ v; n, mwpD_SI (end_state rd) \u2217\n                                          \u03a6 (end_val rd) (nstps rd) v n }}.\nProof.\n  iApply (mwp_adequacy_basic\n            (mwpd_left mwpD_SI mwpD_SI') idx E e \u03c3 (\u03bb v n x, \u03a6 v n x.1 x.2)).\nQed.\n\nEnd basmwp_soundness.\n\nSection soundness.\nContext {\u039b \u03a3} `{!invPreG \u03a3}\n        {SI_data : Type} (mwpD_SI : SI_data \u2192 state \u039b \u2192 iProp \u03a3)\n          {SI_data' : Type} (mwpD_SI' : SI_data' \u2192 state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nProgram Instance left_Initialization\n        SSI SSI' `{!InitData SSI} `{!InitData SSI'} e' \u03c3' :\n  Initialization\n    (val \u039b * nat)\n    (\u03bb x : invG_pack \u03a3 (SI_data * SI_data'),\n           mwpd_left (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2))\n    (\u03bb x, @mwpC_left \u039b \u03a3 _ (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2))\n    (\u03bb _, e') :=\n{|\n  initialization_modality Hi P := |={\u22a4}=> P;\n  initialization_seed_for_modality _ := wsat \u2217 ownE \u22a4;\n  initialization_seed_for_state_interp x := SSI (PIG_cnt x).1 \u2217 SSI' (PIG_cnt x).2;\n  initialization_residue _ := \u25b7 wsat \u2217 \u25b7 ownE \u22a4;\n  initialization_elim_laters := 1;\n  initialization_mwpCM_soundness_arg := Reds e' \u03c3';\n  initialization_mwpCM_soundness_laters n rd' := S ((nstps rd') + S n);\n  initialization_modality_initializer x _ := mwpD_SI' (PIG_cnt x).2 \u03c3';\n  initialization_mwpCM_soundness_fun rd := (end_val rd, nstps rd);\n  initialization_Ex_conv _ x := x;\n|}%I.\nNext Obligation.\nProof.\n  intros; simpl.\n  iApply init_data.\n  apply (init_invGpack (\u03bb x, SSI x.1 \u2217 SSI' x.2))%I.\nQed.\nNext Obligation.\nProof.\n  iIntros (???? e' \u03c3' P Hi) \"[Hs HE] HP\".\n  rewrite uPred_fupd_eq /uPred_fupd_def.\n  iMod (\"HP\" with \"[$]\") as \"(Hs & HE & HP)\".\n  iModIntro. rewrite -!bi.later_sep.\n  iMod \"Hs\"; iMod \"HE\"; iMod \"HP\". iNext.\n  iFrame.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  iIntros (???? e' \u03c3' Hi P E n rd) \"[[Hs HE] [H\u03c3' HP]]\".\n  iNext.\n  rewrite /mwpC_modality /mwpD_modality /=.\n  iDestruct (mwp_right_adequacy_basic with \"[H\u03c3' $HP]\")\n    as \"HP\"; eauto.\n  iSpecialize (\"HP\" $! rd).\n  rewrite uPred_fupd_eq /uPred_fupd_def /=.\n  replace \u22a4 with ((\u22a4 \u2216 E) \u222a E) by by rewrite difference_union_L; set_solver.\n  iDestruct (ownE_op with \"HE\") as \"[_ HE]\"; first set_solver.\n  rewrite (plus_comm _ (S n))  -Nat.add_1_r -plus_assoc (plus_comm 1)\n          plus_assoc bi.laterN_plus (plus_comm n) /=.\n  iInduction (nstps rd + n) as [] \"IH\".\n  { iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & ? & HP)\".\n    by iMod \"HP\". }\n  simpl.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iNext.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  rewrite -bi.laterN_later /=.\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iApply (\"IH\" with \"Hs HP HE\").\nQed.\n\nLemma mwp_left_adequacy SSI SSI' `{!InitData SSI} `{!InitData SSI'}\n      E e \u03c3 (e' : expr \u039b) \u03c3' (\u03a8 : val \u039b \u2192 nat \u2192 val \u039b \u2192 nat \u2192 Prop) :\n  (\u2200 (x : invG_pack \u03a3 (SI_data * SI_data')),\n      SSI (PIG_cnt x).1 \u2217 SSI' (PIG_cnt x).2\n          \u22a2 |={\u22a4}=> (mwpD_SI (PIG_cnt x).1 \u03c3 \u2217 mwpD_SI' (PIG_cnt x).2 \u03c3' \u2217\n                  MWP@{mwpd_left (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2), e'}\n                    e @ E {{ v ; n| w; k,  \u231c\u03a8 v n w k\u231d }}))\n  \u2192 \u2200 (rd : Reds e \u03c3) (rd' : Reds e' \u03c3'),\n    \u03a8 (end_val rd) (@nstps \u039b _ _ rd) (end_val rd') (@nstps \u039b _ _ rd').\nProof.\n  intros Hic rd rd'.\n  by apply (mwp_adequacy\n              _ _ _ _ (left_Initialization SSI SSI' e' \u03c3') E e \u03c3\n              (\u03bb v n x, \u03a8 v n x.1 x.2) rd').\nQed.\n\nEnd soundness.\n", "meta": {"author": "logsem", "repo": "modal-weakestpre", "sha": "9d9034f868a94e195a8a22f53af06a14e1529f3f", "save_path": "github-repos/coq/logsem-modal-weakestpre", "path": "github-repos/coq/logsem-modal-weakestpre/modal-weakestpre-9d9034f868a94e195a8a22f53af06a14e1529f3f/theories/mwp_modalities/ni_logrel/mwp_left.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.1952379645691206}}
{"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.StandardResults.\nRequire Import ComhCoq.ComhBasics.\n(*\nRequire Import ComhCoq.LanguageFoundations.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.ProtAuxDefs.\nRequire Import ComhCoq.InterfaceLanguage.\nRequire Import ComhCoq.ModeStateLanguage.\nRequire Import ComhCoq.EntityLanguage.*)\nRequire Import ComhCoq.NetworkLanguage.\n(*Require Import ComhCoq.EntAux.*)\nRequire Import ComhCoq.NetAuxBasics.\nRequire Import ComhCoq.NetAuxDefs.\n\n\n(*If an entity is pending then it cannot delay.*)\nTheorem pending_urgent (n n' : Network) (d : Delay) (i : nat) (p : reachableNet n) :\n  pending i n p -> ~ n -ND- d -ND> n'. Admitted. (*1*)\n(**Proof: *SPAWN SEPARATE URGENCY RESULTS FOR THIS DONE*\nInduction on pending. We have 2 cases. Case 1 is that we are\novWaitStateNet m t x 0 i n- the y parameter can be shown to be 0 (separate proof?).\nIn this case, the input on pos is enabled and so the process can't delay by\nprogress [salvaged?]. Case 2 is the ovReadyStateNet m t l i n', which is ready to\noutput on io. Again by progress this means a delay is not possible.*)\n\n(* If an entity is pending, and the same entity is in the state\novWaitState m u x y, then we can show that u is equal to tw(m0, m) + period m, for some m0.*)\nTheorem pending_time1 (n : Network) (m : Mode) (i : nat)\n  (u x y : Time) (p : reachableNet n) :\n  pending i n p -> ovWaitStateNet m u x y i n -> exists m0 q,\n  u = addTime (waitTime m0 m q) (period m). Admitted. (*1*)\n(**Proof: COMMON TACTICS FOR THE ADDTIME SHIT? THERE ARE MORE THEOREMS OF A SIMILAR NATURE.\nBy induction on pending. In the base case, we have that the previous state was\ninit m and so by backtracking (...) we can show that y = 0 and u = tw(m0, m) + period m.\nIn the first inductive case, we can show that u does not change from one state to the next.\nThe other two inductive cases fail because they involve ovReadyState, which is not\novWaitState.*)\n\n(* If an entity is pending, and the same entity is in the state ovReadyState m u l,\nthen we can show that u is equal to tw(m0, m) + period m, for some m0.*)\nTheorem pending_time2 (n : Network) (m : Mode) (i : nat)\n  (u : Time) (l : Position) (p : reachableNet n) :\n  pending i n p -> ovReadyStateNet m u l i n ->\n  exists m0 q, u = addTime (waitTime m0 m q) (period m).\n  Admitted. (*1*)\n(**Proof: Induction on pending. BaseType case fails because it only applies to ovWait.\nDiscrete inductive case can be shown by (backtracking + automation) to follow from\novWaitState m u t' i n. But then by (pending_time1), we have that u = tw(m0, m) + period m.\nAnd since the u is the same across the transition, it holds now. The delay inductive case\nfails because delay can be shown to be impossible when a state is pending (pending_urgent).*)\n\n(*If an entity is nextSince m t, and the same entity is in the state ovReadyState m u l,\nthen t + u is constant, equal to the sum of the wait time to m from some mode, tw(m0, m)\nand the period of broadcast for m, period m. This is the combination of two results*)\nTheorem nextSince_ovWait_ovReady_time (n : Network) (m : Mode) (i : nat)\n  (t u x y : Time) (l : Position) (p : reachableNet n) :\n  (nextSince m t i n p -> ovWaitStateNet m u x y i n ->\n  exists m0 q, addTime t x = waitTime m0 m q\n  /\\ addTime u y = addTime x (period m)) /\\ (*Half theorem*)\n  (nextSince m t i n p -> ovReadyStateNet m u l i n ->\n  exists m0 q,\n  addTime t u = addTime (waitTime m0 m q) (period m)). Admitted. (*1*)\n(**Proof: Mutual induction on nextSince. We don't have to actually use mutual induction,\njust effectively we will be by proving these two results together as a conjunction and\nthe splitting by case analysis later.\n!Four applications of ovWait_prev?! could be tidied up! For ovWait: In the base case,\nwe have that the entity in the previous state was pending, and the previous state was\novReadySate m u0 l for some u0, l. Well then, by (pending_time2), we have that\nu0 = tw(m0, m) + period m, for some m. But we also have by (...ovWait_prev...)\nthat x = u = u0 - period m, after eliminating the initState possibility because\nit causes a contradiction. So substituting for u0 and tidying up we have x = tw(m0, m).\nAnd since this is the base case, t = 0. So t + x = tw(m0, m) as required. Also from\n(...ovWait_prev...) we have that on entering the state u = x and y = period m.\nSo u = x - y + period m holds. In the delay inductive case, t increases and u decreases\nproportionately. By the I.H. t + u = tw(m0, m), and so for a delay of d, the new sum\nbecomes (t + d) + (u - d) = t + u = tw(m0, m), and our constant sum is preserved.\nAlso, x and y decrease by this d. So we want to show u = x - d - (y - d) + period m.\nBut this is clearly u = x - y + period m, which is our I.H. In the discrete case,\neither the previous state was ovReady, and our result follows by the I.H. or the previous\nstate was not ovReady. In the latter case, we can use (...ovWait_prev...) and our inductive\nhypothesis of nextSince (to eliminate initState) to show that the previous state must have\nbeen ovReadyState m u0 l i n, with u = u0 - period m, and u = x. We then separately show\n(the other half of this mutually inductive proof) that this combination of nextSince m t\nand ovReadyState m u0 l implies that t + u0 = tw(m0, m) + period m, for some m0. Hence we\nget t + u = tw(m0, m), and u = x from before, so t + x = tw(m0, m). Also, by\n(...ovWait_prev...), we have much as in the base case, that on entering the state u = x\nand y = period m. So u = x - y + period m holds. For ovReady: The base case fails to match,\nthe delay inductive case fails also because ovReady can't delay by progress [salvaged?],\nand we can't go from ovWait to ovReady by a delay. So we're left with the discrete inductive\ncase, where the parameter t for next since is the same across both states. By\n(...ovReady_prev...) then we show that the previous state was ovWaitState m u x 0.\nNote the parameter y must be 0 so that the transition is enabled. But we also have by our\nmutually inductive I.H. that u = x - y + period m, in this case y = 0, so we have\nu = x + period m. So t + u = t + x + period m. But we know again by our mutual I.H.\nthat t + x = tw(m0, m). And so t + u = tw(m0, m) + period m as required.*)\n\n(* If an entity is nextSince m t, and the same entity is in the state\nswitchBcState m, then we can show that mL + max AN trans < t.*)\nTheorem nextSince_switchBc_lower (n : Network) (m : Mode) (i : nat)\n  (t : Time) (p : reachableNet n) :\n  nextSince m t i n p -> switchBcStateNet m i n ->\n  msgLatency + Rmax adaptNotif transMax < t. Admitted. (*1*)\n(**Proof: Induction on nextSince. BaseType case fails. Delay follows by monotonicity of t with\nnextSince, as does the discrete case where the previous state is still switchBCState. So\nthe only case of any complexity is the discrete inductive case where the previous state was\nnot a switchBcState m. In which case we can show that it must be ovWaitState m u 0 y for\nsome u and y (...switchBc_prev...). We then have by (nextSince_ovWait_time), with x = 0,\nthat t + 0 = tw(m0, m), which simplifies to t = tw(m0, m). We can then expand tw to max\n(mL + max(AN, trans) + Dw) (ts m1 m2) which, due to a strictly positive Dw, is greater\nthan mL + max AN trans as required.*)\n\n(* If an entity is nextSince m t, and the same entity is in the state switchCurrState m,\nthen we can show that mL + max AN trans < t.*)\nTheorem nextSince_switchCurr_lower (n : Network) (m : Mode) (i : nat)\n  (t : Time) (p : reachableNet n) :\n  nextSince m t i n p -> switchCurrStateNet i n ->\n  msgLatency + Rmax adaptNotif transMax < t. Admitted. (*1*)\n(**Proof: SIMILAR TO ANALOGOUS PROOF FOR SWITCHBC- SHARED TACTICS?\nInduction on nextSince and case analysis on switchCurrState. The base case fails.\nFor the inductive case, we case analyse the previous state for the predicate switchCurrState.\n If this was true, then by the I.H. the t parameter in that state exceeds the lower bound, \nand so, by monotonicity of nextSince in both delay & discrete cases, so will the t' in this \nstate. Otherwise, the previous state is not switchCurrState m. In which case we can show \nthat it must be switchBcState m (...switchCurr_prev...). We then prove a similar result for \nthis (nextSince_switchBc_lower) & since the t parameter is the same from the last state to \nthis one because our transition is discrete, that result carries forward.*)", "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/NAROvlpTime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.19508560342075307}}
{"text": "(* -*- company-coq-local-symbols: ((\"|=\" . ?\u22a8) (\"=|\" . ?\u2ae4) (\"->>\" . ?\u21a0) (\"=~\" . ?\u2248) (\"<|\" . ?\u27e8) (\"|>\" . ?\u27e9) ); -*- *)\nSet Warnings \"-notation-overridden\".\n\nRequire Import Prelude.Prelude.\nRequire Import Defs.Defs.\n\nRequire Import Wf.Wf.\n\n(*** Umi_split *)\nLemma umi_split_head_helper : forall (denv__in : DEnv) (dsub__in dsub : DSub) (exA exA1 exA2 : exvar) (a1 : A) (da : DA),\n    {denv__in, dsub__in}a |= exA2 :: exA1 :: a1 ~> {da, dsub}\n  -> exists dt1 dt2 dsub',\n      dsub = (exA2, dt2) :: (exA1, dt1) :: dsub'\n    /\\ {denv__in, dsub__in}a |= exA :: a1 ~> {da, (exA, DT_Fun dt1 dt2) :: dsub'}.\nProof.\n  introv INST. inv_AInst. do 3 eexists. split. auto.\n  rep_app_assoc. constructor; try assumption.\n  constructor; rewr; eauto.\nQed.\n\nLemma umi_split_head: forall (exA exA1 exA2 : exvar) (env1 : Env) (a1 a2 : A) (denv : DEnv) (dsub : DSub),\n    {\u25aa, []}|= env1 ::a (a2 ++ exA2 :: exA1 :: a1) ~> {denv, dsub}\n  -> exists (dt1 dt2 : DTy) (dsub1 dsub2 : DSub),\n      dsub = dsub2 ++ (exA2, dt2) :: (exA1, dt1) :: dsub1\n    /\\ Env_exvars (env1 ::a a1) [=] DSub_dom dsub1\n    /\\ {\u25aa, []}|= env1 ::a (a2 ++ exA :: a1) ~> {denv, dsub2 ++ (exA, DT_Fun dt1 dt2) :: dsub1}.\n  Proof.\n    introv INST. inverts INST.\n    AInst_split_destr. eassumption.\n    forwards [dt1 [dt2 [dsub' [?EQ__dsub INSTA']]]]: umi_split_head_helper exA. eassumption.\n    rewr*.\n    forwards INST'': EInstA. eassumption. apply AInst_merge. rewr. apply INSTA'. eapply AInst_swap_subinit. rewr. eassumption.\n    inverts INSTA'.\n    forwards: EInst_props__base1 (env1 ::a a1). econstructor. eassumption. rewr. eassumption.\n    subst. rewr*.\n    do 4 eexists. splits. 3:{ apply INST''. } reflexivity. auto. rewr. fsetdec.\nQed.\n\nLemma umi_split_tail : forall (dsub__mid dsub__mid' : DSub) (denv__init : DEnv) (env : Env) (denv : DEnv) (dsub1 dsub2 dsub3 : DSub) (ty : Ty) (exA : exvar),\n    {denv__init, dsub2 ++ dsub__mid ++ dsub1}|= subst_exvar_Env ty exA env ~> {denv, dsub3}\n  -> (forall sch, SchSI.In sch (Env_Obj_Schs env)\n            -> DSub_app (subst_exvar_Sch ty exA sch) (dsub__mid  ++ dsub1)\n            = DSub_app sch (dsub__mid' ++ dsub1))\n  -> {denv__init, dsub2 ++ dsub__mid' ++ dsub1}|= env ~> {denv, dsub3}.\nProof.\n  introv INST EQ__sub. gen denv dsub3. dependent induction env; intros.\n  - inverts INST. auto.\n  - inverts INST.\n  - inverts INST. econstructor; rewr; eauto using AInst_swap_subinit. eapply IHenv.\n    intros. apply EQ__sub. rewr. assumption. assumption.\n  - inverts INST. econstructor.\n    eapply IHenv. intros. eapply EQ__sub. rewr. fsetdec'. assumption.\n    forwards: EQ__sub Sch5. rewr. fsetdec.\n    subdist*. crush.\n  - inverts INST. destruct Obj5. simpl in H3. inverts H3.\n    econstructor.\n    eapply IHenv. intros. eapply EQ__sub. rewr. fsetdec'. eauto. eauto using AInst_swap_subinit.\n    forwards: EQ__sub Sch0. rewr. fsetdec.\n    subdist*. crush.\nQed.\n\nLemma umi_split_substr : forall (exA exA1 exA2 : exvar) (dsub : DSub) (dt1 dt2 : DTy) (sch : Sch),\n    exA1 \\notin free_exvars_Sch sch\n  -> exA2 \\notin free_exvars_Sch sch\n  -> exA1 <> exA2\n  -> exA \\notin DSub_dom dsub\n  -> exA1 \\notin DSub_dom dsub\n  -> exA2 \\notin DSub_dom dsub\n  -> DSub_app (subst_exvar_Sch (T_Fun (T_ExVar exA1) (T_ExVar exA2)) exA sch) (([(exA2, dt2)] ++ [(exA1, dt1)]) ++ dsub)\n  = DSub_app sch ([(exA, DT_Fun dt1 dt2)] ++ dsub).\n  Proof.\n    intros.\n    subdist. Sch_Ty_ind sch; rewr; auto.\n    - simpl. DSub_exA_decide.\n      + ifdec.\n        * rewr.\n          do_DSub_exA_decide dsub exA1. 2:{ assert (exA1 \\in DSub_dom dsub). eauto. fsetdec. }\n          do_DSub_exA_decide dsub exA2. 2:{ assert (exA2 \\in DSub_dom dsub). eauto. fsetdec. }\n          crush. ifdec; crush. if_taut.\n        * rewrite INV. simpl.\n          destruct (exA0 == exA). crush.\n          destruct (exA0 == exA1). crush. simpl.\n          destruct (exA0 == exA2). crush. reflexivity.\n      + ifdec. subst.\n        assert (exA \\in DSub_dom dsub). eauto. fsetdec. crush.\n    - crush.\n    - crush.\nQed.\n\n(** split main *)\nTheorem umi_split : forall (denv : DEnv) (exA exA1 exA2 : exvar) (env1 : Env) (a1 a2 : A) (env2 : Env),\n    FullEInst (subst_exvar_Env (T_Fun (T_ExVar exA1) (T_ExVar exA2)) exA (env1 ::a (a2 ++ (exA2 :: exA1 :: a1)) +++ env2)) denv\n  -> wf(subst_exvar_Env (T_Fun (T_ExVar exA1) (T_ExVar exA2)) exA (env1 ::a (a2 ++ (exA2 :: exA1 :: a1)) +++ env2))\n  -> wf(env1 ::a (a2 ++ [exA] ++ a1) +++ env2)\n  -> FrA [exA2; exA1] (env1 ::a (a2 ++ [exA] ++ a1) +++ env2)\n  -> FullEInst (                                                           env1 ::a (a2 ++ (exA  ::        a1)) +++ env2 ) denv.\nProof.\n  introv INST WF1 WF2 FR. destr. rewr*.\n  assert (exA `notin` Env_Obj_exvars env1).\n  { forwards DISJ: wf_Env_exvar_disj env1. norm in WF2. rep_Env_app_assoc in WF2. apply WF2.\n    eapply in_disjoint_impl_notin1. eassumption. rewr. fsetdec. }\n  rewrite subst_exvar_Env_notin_Env_idempotent in *. 2,3,4,5: eauto.\n  (**)\n  EInst_split_destr. eassumption.\n  (**)\n  forwards [dt1 [dt2 [dsub1' [dsub2 [? [DOMSUB ?INST]]]]]]: umi_split_head. eassumption.\n  (**)\n  subst. rewr*. exists. apply EInst_merge. eassumption.\n  applys_eq (umi_split_tail ([(exA2, dt2)] ++ [(exA1, dt1)]) ([(exA, DT_Fun dt1 dt2)])).\n  2:{ rewr. norm in INST1. eassumption. } rewr. reflexivity.\n  (**)\n  intros sch IN.\n  forwards SUB: fv_sch_in_wfenv_subset sch (env1 ::a (a2 ++ [exA] ++ a1) +++ env2). rewr. fsetdec'. auto.\n  inv_AInst.\n  (* forwards DOMSUB: EInst_props1. apply EInstA. apply INST1. rewr. eassumption. *)\n  apply umi_split_substr.\n  - unfold not. rewrite SUB. intros.\n    assert (FR': FrA [exA1] (env1 +++ <a2 ++ [exA] ++ a1>a +++ env2)). simpl in FR. eauto.\n    inverts FR'. crush.\n  - unfold not. rewrite SUB. intros.\n    inverts FR. crush.\n  - assert (UNI: NoDup' [exA2; exA1]). apply FrA_props in FR. jauto.\n    destruct (exA1 == exA2). subst. inverts UNI. crush. assumption.\n  - unfold not. rewrite <- DOMSUB. intro IN'.\n    assert (NI: exA \\notin Env_Obj_exvars (env1 ::a a1)). eauto.\n    apply NI. rewr. indestr in IN'. destr. fsetdec. auto.\n  - unfold not. rewrite <- DOMSUB. intro IN'.\n    assert (wf(env1 ::a (exA1 :: a1))). eauto.\n    assert (FR': FrA (exA1 :: a1) env1). eauto.\n    inverts FR'. apply FR0. indestr in IN'. destr; rewr; eauto.\n  - unfold not. rewrite <- DOMSUB. intro IN'.\n    inverts FR. apply FR0. indestr in IN'. destr; rewr. eauto. fsetdec.\nQed.\n\n(** split drop *)\nTheorem umi_split__drop: forall (n : nat) (denv : DEnv) (exA exA1 exA2 : exvar) (env1 : Env) (a1 a2 : A) (env2 : Env),\n    FullEInst (Env_drop n (subst_exvar_Env (T_Fun (T_ExVar exA1) (T_ExVar exA2)) exA (env1 ::a (a2 ++ (exA2 :: exA1 :: a1)) +++ env2))) denv\n  -> wf(Env_drop n (subst_exvar_Env (T_Fun (T_ExVar exA1) (T_ExVar exA2)) exA (env1 ::a (a2 ++ (exA2 :: exA1 :: a1)) +++ env2)))\n  -> wf(env1 ::a (a2 ++ [exA] ++ a1) +++ env2)\n  -> FrA [exA2; exA1] (env1 ::a (a2 ++ [exA] ++ a1) +++ env2)\n  -> FullEInst (Env_drop n (                                                           env1 ::a (a2 ++ (exA  ::        a1)) +++ env2 )) denv.\nProof.\n  introv [dsub INST] WF1 WF2 WFTY. rewrite Env_drop_subst_exvar_Env_comm in *.\n  dropdistr*. destruct (le_lt_dec n (Env_length env2)).\n  - forwards NIL: nat_minus_greater. eassumption. rewrite NIL in *. rewr*.\n    eapply umi_split. rewr. eauto. rewr. eassumption.\n    rewrite Env_drop_distr'. eauto using wf_Env_drop.\n    rewrite Env_drop_distr'. eauto using FrA_drop.\n  - rewrite (Env_drop_greater n) in *. 2,3,4: crush.\n    rewr*.\n    assert (exA `notin` Env_Obj_exvars env1).\n    { forwards DISJ: wf_Env_exvar_disj env1. norm in WF2. rep_Env_app_assoc in WF2. apply WF2.\n      eapply in_disjoint_impl_notin1. eassumption. rewr. fsetdec. }\n    destruct (n - Env_length env2).\n    + simpl in *.\n      rewrite subst_exvar_Env_notin_Env_idempotent in INST. 3:{ eauto. } 2:assumption.\n      forwards [dty [dsub1 [dsub2 [? [? [? ?]]]]]]: umi_split_head exA. eassumption.\n      exists. eassumption.\n    + simpl in *. exists.\n      rewrite subst_exvar_Env_notin_Env_idempotent in INST. eassumption.\n      rewrite Env_drop_Env_exvars_Obj. assumption.\n      eauto using wf_Env_drop.\nQed.\n\n(*** Umi_subst *)\nLemma umi_subst_head_helper : forall (exA : exvar) (dty : DTy) (a : A) (da : DA) (dsub : DSub) (denv__init : DEnv) (dsub__init : DSub),\n    {denv__init, dsub__init}a|= a ~> {da, dsub}\n  -> denv__init :::a da |=dty DS_Mono dty\n  -> {denv__init, dsub__init}a|= exA :: a ~> {da, (exA, dty) :: dsub}.\nProof. introv INST WFDTY. rewrite <- (app_nil_l da). econstructor; crush. Qed.\n\nLemma umi_subst_head: forall (exA : exvar) (ty : Ty) (env1 : Env) (a1 a2 : A) (denv0 : DEnv) (dsub : DSub),\n    {\u25aa, []}|= env1 ::a (a2 ++ a1) ~> {denv0, dsub}\n  -> (env1 ::a a1) |=ty S_Mono ty\n  -> wf(env1 ::a (exA :: a1))\n  -> exists (dty : DTy) (dsub1 dsub2 : DSub),\n          dsub = dsub2 ++ dsub1\n        /\\ DSub_app_t ty dsub1 = emb_Ty dty\n        /\\ DSub_unique ((exA, dty) :: dsub1)\n        /\\ {\u25aa, []}|= env1 ::a (a2 ++ exA :: a1) ~> {denv0, dsub2 ++ (exA, dty) :: dsub1}.\nProof.\n  introv INST WFTY WF. inverts INST.\n  (**)\n  AInst_split_destr. eassumption.\n  (**)\n  forwards dsch EMB WFDTY: EInst_WfTy_impl_emb. 2:{ eassumption. } econstructor. eassumption. eassumption.\n  emb_auto. rewr*.\n  (**)\n  forwards INSTA': umi_subst_head_helper exA a1. eassumption. eassumption. rewr in INSTA'.\n  forwards INSTA'': EInstA. eassumption. eapply AInst_merge. rewr. apply INSTA'. eapply AInst_swap_subinit. rewr. eassumption.\n  exists dty (dsub ++ DSub1) dsub0. splits.\n  - reflexivity.\n  - auto.\n  - forwards WFSUB: EInst_props__wf (env1 ::a (exA :: a1)). econstructor. eassumption. rewr.\n    econstructor. 2:eassumption. instantiate (2 := nil). rewr. eassumption. assumption.\n    auto. crush. rewr in WFSUB. eauto.\n  - rewr*. eassumption.\nQed.\n\nLemma umi_subst_sub : forall (exA : exvar) (ty : Ty) (dty : DTy) (dsub : DSub) (sch : Sch),\n    DSub_unique ((exA, dty) :: dsub)\n  -> DSub_app_t ty dsub = emb_Ty dty\n  -> DSub_app (subst_exvar_Sch ty exA sch) dsub = subst_exvar_Sch (emb_Ty dty) exA (DSub_app sch dsub).\nProof.\n  introv UNI EMB.\n  subdist. Sch_Ty_ind sch. 1,2,4,6: crush. all:simpl.\n  - ifdec'.\n    + DSub_exA_decide; rewrite EMB. rewrite INV. simpl. if_taut.\n      rewrite EMB0. rewrite subst_exvar_Ty_embed_idempotent.\n      forwards: UNI dty dty0. rewr. fsetdec. rewr. fsetdec'. crush.\n    + DSub_exA_decide. rewrite INV. simpl. if_taut.\n      rewrite EMB0. rewrite subst_exvar_Ty_embed_idempotent. crush.\n  - rewr. crush.\nQed.\n\nLemma umi_subst_tail : forall (dty : DTy) (exA : exvar) (ty : Ty) (dsub1 dsub2 : DSub) (env : Env) (denv : DEnv) (dsub : DSub) (denv__init : DEnv),\n    {denv__init, dsub2 ++ dsub1}|= subst_exvar_Env ty exA env ~> {denv, dsub}\n  -> DSub_app_t ty dsub1 = emb_Ty dty\n  -> DSub_unique ((exA, dty) :: dsub1)\n  -> {denv__init, dsub2 ++ (exA, dty) :: dsub1}|= env ~> {denv, dsub}.\nProof.\n  introv INST EMB UNI.\n  EInst_genind' INST env.\n  - auto.\n  - econstructor. eauto. eauto using AInst_swap_subinit.\n  - econstructor. eauto. subdist*.\n    erewrite <- umi_subst_sub; eassumption.\n  - destruct Obj5; inverts H3.\n    econstructor. eauto. eauto using AInst_swap_subinit. subdist*.\n    erewrite <- umi_subst_sub; eassumption.\nQed.\n\n(** subst main *)\nTheorem umi_subst : forall (exA : exvar) (ty : Ty) (env1 env2 : Env) (a1 a2 : A) (denv : DEnv),\n    FullEInst (subst_exvar_Env ty exA (env1 ::a (a2 ++ a1) +++ env2)) denv\n  -> wf(env1 ::a (a2 ++ exA :: a1) +++ env2)\n  -> env1 ::a a1 |=ty (S_Mono ty)\n  -> FullEInst (env1 ::a (a2 ++ exA :: a1) +++ env2) denv.\nProof.\n  introv INST WF2 WFTY. destr. rewr*.\n  assert (exA `notin` Env_Obj_exvars env1).\n  { forwards DISJ: wf_Env_exvar_disj env1. norm in WF2. rep_Env_app_assoc in WF2. apply WF2.\n    eapply in_disjoint_impl_notin1. eassumption. rewr. fsetdec. }\n  rewrite subst_exvar_Env_notin_Env_idempotent in *. 2,3: eauto.\n  (**)\n  EInst_split_destr. eassumption.\n  (**)\n  forwards [dty [dsub1' [dsub2 [? [? [? ?]]]]]]: umi_subst_head exA a1. eassumption. eassumption. constructor. eauto.\n  constructor. eauto.\n  assert (FrA (exA :: a1) env1). eauto. inv_FrA. eassumption.\n  subst.\n  (**)\n  eexists. rewr*. apply EInst_merge.\n  - eassumption.\n  - rewr. eapply umi_subst_tail. eassumption. eassumption. eassumption.\nQed.\n\n(** subst drop *)\nTheorem umi_subst__drop : forall (n : nat) (exA : exvar) (ty : Ty) (env1 env2 : Env) (a1 a2 : A) (denv : DEnv),\n    FullEInst (Env_drop n (subst_exvar_Env ty exA (env1 ::a (a2 ++ a1) +++ env2))) denv\n  -> wf(Env_drop n (subst_exvar_Env ty exA (env1 ::a (a2 ++ a1) +++ env2)))\n  -> wf(env1 ::a (a2 ++ exA :: a1) +++ env2)\n  -> env1 ::a a1 |=ty (S_Mono ty)\n  -> FullEInst (Env_drop n (env1 ::a (a2 ++ exA :: a1) +++ env2)) denv.\nProof.\n  introv [dsub INST] WF1 WF2 WFTY. rewrite Env_drop_subst_exvar_Env_comm in *.\n  dropdistr*. destruct (le_lt_dec n (Env_length env2)).\n  - forwards NIL: nat_minus_greater. eassumption. rewrite NIL in *. rewr*.\n    eapply umi_subst. rewr. eauto. rewrite Env_drop_distr'. eauto using wf_Env_drop.\n    eassumption.\n  - rewrite (Env_drop_greater n) in *. 2,3,4: crush.\n    rewr*.\n    assert (exA `notin` Env_Obj_exvars env1).\n    { forwards DISJ: wf_Env_exvar_disj env1. norm in WF2. rep_Env_app_assoc in WF2. apply WF2.\n      eapply in_disjoint_impl_notin1. eassumption. rewr. fsetdec. }\n    destruct (n - Env_length env2).\n    + simpl in *.\n      rewrite subst_exvar_Env_notin_Env_idempotent in INST. 3:{ eauto. } 2:assumption.\n      forwards [dty [dsub1 [dsub2 [? [? [? ?]]]]]]: umi_subst_head exA. eassumption. eassumption. constructor. eauto.\n      constructor. eauto.\n      assert (FrA (exA :: a1) env1). eauto. inv_FrA. eassumption.\n      exists. eassumption.\n    + simpl in *. exists.\n      rewrite subst_exvar_Env_notin_Env_idempotent in INST. eassumption.\n      rewrite Env_drop_Env_exvars_Obj. assumption.\n      eauto using wf_Env_drop.\nQed.\n\n(*** Main theorems *)\nTheorem unification_maintains_instantiation : forall (env__in env__out : Env) (eqs : Eqs) (denv : DEnv),\n    U env__in eqs env__out\n  -> FullEInst env__out denv\n  -> wf( env__in )\n  -> FullEInst env__in denv.\nProof.\n  introv UNI [Sub INST] WF1. inverts UNI.\n  induction Us. eauto.\n  forwards WF2: Uss_Wf. eassumption. auto.\n  forwards [Sub__IH INST__IH]: IHUs. eassumption. assumption.\n  destruct UNI; simpl in WF2; simpl in  INST__IH; eauto using umi_split, umi_subst.\nQed.\n\nTheorem unification_maintains_instantiation__drop : forall (n : nat) (env__in env__out : Env) (eqs : Eqs) (denv : DEnv),\n    U env__in eqs env__out\n  -> FullEInst (Env_drop n env__out) denv\n  -> wf(env__in)\n  -> FullEInst (Env_drop n env__in) denv.\nProof.\n  introv UNI [Sub INST] WF1. inverts UNI.\n  induction Us. eauto.\n  forwards WF2: Uss_Wf. eassumption. auto.\n  forwards [Sub__IH INST__IH]: IHUs. eassumption. assumption.\n  destruct UNI; simpl in WF2; simpl in  INST__IH; eauto using umi_split__drop, umi_subst__drop.\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/Sound/Umi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19508559756236413}}
{"text": "Require Import Coq.Bool.Bool.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\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.structured_injections.\nRequire Import sepcomp.reach.\nRequire Import sepcomp.mem_wd.\n\nRequire Import sepcomp.effect_semantics. (*for specialization below*)\n\nModule Wholeprog_sim. Section Wholeprog_sim.\n\nContext {G1 C1 M1 G2 C2 M2 : Type}\n\n(Sem1 : @CoreSemantics G1 C1 M1)\n(Sem2 : @CoreSemantics G2 C2 M2)\n\n(ge1 : G1)\n(ge2 : G2)\n\n(main : val).\n\nVariable ge_inv : G1 -> G2 -> Prop.\n\nVariable init_inv : meminj -> G1 -> list val -> M1 -> G2 -> list val -> M2 -> Prop.\n\nVariable halt_inv : (*SM_Injection*)meminj -> G1 -> val -> M1 -> G2 -> val -> M2 -> Prop.\n\nRecord Wholeprog_sim :=\n{ core_data : Type\n; match_state : core_data -> (*SM_Injection*)meminj -> C1 -> M1 -> C2 -> M2 -> Prop\n; core_ord : core_data -> core_data -> Prop\n; core_ord_wf : well_founded core_ord\n; genv_inv : ge_inv ge1 ge2\n; core_initial :\n    forall j c1 vals1 m1 vals2 m2,\n    initial_core Sem1 ge1 main vals1 = Some c1 ->\n    init_inv j ge1 vals1 m1 ge2 vals2 m2 ->\n    exists (*mu*) cd c2,\n      (*as_inj mu = j*\n      /\\*) initial_core Sem2 ge2 main vals2 = Some c2\n      /\\ match_state cd (*mu*)j c1 m1 c2 m2\n; core_diagram :\n    forall st1 m1 st1' m1',\n    corestep Sem1 ge1 st1 m1 st1' m1' ->\n    forall cd st2 mu m2,\n    match_state cd mu st1 m1 st2 m2 ->\n    exists st2', exists m2', exists cd', exists mu',\n    match_state cd' mu' st1' m1' st2' m2'\n    /\\ (corestep_plus Sem2 ge2 st2 m2 st2' m2'\n        \\/ (corestep_star Sem2 ge2 st2 m2 st2' m2' /\\ core_ord cd' cd))\n; core_halted :\n    forall cd mu c1 m1 c2 m2 v1,\n    match_state cd mu c1 m1 c2 m2 ->\n    halted Sem1 c1 = Some v1 ->\n    exists j v2,\n       halt_inv j ge1 v1 m1 ge2 v2 m2\n    /\\ halted Sem2 c2 = Some v2 }.\n\nEnd Wholeprog_sim.\n\nEnd Wholeprog_sim.\n\n\nSection CompCert_wholeprog_sim.\n\nContext {F1 V1 C1 F2 V2 C2 : Type}\n\n(Sem1 : @EffectSem (Genv.t F1 V1) C1)\n(Sem2 : @EffectSem (Genv.t F2 V2) C2)\n\n(ge1 : Genv.t F1 V1)\n(ge2 : Genv.t F2 V2)\n\n(main : val).\n\nDefinition cc_init_inv j (ge1 : Genv.t F1 V1) vals1 m1 (ge2 : Genv.t F2 V2) vals2 m2 :=\n  Mem.inject j m1 m2 /\\ Forall2 (val_inject j) vals1 vals2\n  /\\ meminj_preserves_globals ge1 j /\\ globalfunction_ptr_inject ge1 j\n  /\\ mem_wd m2 /\\ valid_genv ge2 m2 /\\ Forall (fun v2 => val_valid v2 m2) vals2\n  /\\ mem_respects_readonly ge1 m1 /\\ mem_respects_readonly ge2 m2.\n\nDefinition cc_halt_inv j (ge1 : Genv.t F1 V1) v1 m1 (ge2 : Genv.t F2 V2) v2 m2 :=\n  meminj_preserves_globals ge1 j\n  /\\ val_inject j v1 v2\n  /\\ Mem.inject j m1 m2.\n\nDefinition CompCert_wholeprog_sim :=\n  @Wholeprog_sim.Wholeprog_sim _ _ _ _ _ _\n    Sem1 Sem2\n    ge1 ge2\n    main\n    genvs_domain_eq\n    cc_init_inv\n    cc_halt_inv.\n\nEnd CompCert_wholeprog_sim.\n\nRequire Import sepcomp.internal_diagram_trans.\nRequire Import Relations.\nLemma well_founded_sem_compose_ord_eq_eq: forall {D12 D23:Type}\n  (ord12: D12 -> D12 -> Prop) (ord23: D23 -> D23 -> Prop)  (C2:Type)\n  (WF12: well_founded ord12) (WF23: well_founded ord23),\n  well_founded (sem_compose_ord_eq_eq ord12 ord23 C2).\nProof.\n  intros. intro. destruct a as [[d12 c2] d23].\n  revert d12.\n  destruct c2.\n  2: constructor; intros. 2: inv H.\n  revert c.\n  induction d23 using (well_founded_induction WF23).\n  intros.\n  induction d12 using (well_founded_induction WF12).\n  constructor; intros. inv H1.\n  generalize (H0 d0). simpl. intros.\n  apply H1. auto.\n  generalize (H d1).\n  intros.\n  specialize H1. auto.\nQed.\n\nRequire Import sepcomp.simulations.\n\nSection WholeSimTrans.\nContext {F1 V1 C1 F2 V2 C2 F3 V3 C3:Type}\n        (Sem1 : @EffectSem (Genv.t F1 V1) C1)\n        (Sem2 : @EffectSem (Genv.t F2 V2) C2)\n        (Sem3 : @EffectSem (Genv.t F3 V3) C3)\n        (g1 : Genv.t F1 V1)\n        (g2 : Genv.t F2 V2)\n        (g3 : Genv.t F3 V3).\n\nVariable Main :val.\nVariable GeInv12: (Genv.t F1 V1) -> (Genv.t F2 V2) -> Prop.\nVariable InitInv12 : meminj -> (Genv.t F1 V1) -> list val -> mem -> (Genv.t F2 V2) -> list val -> mem -> Prop.\nVariable HaltInv12 : (*SM_Injection*)meminj -> (Genv.t F1 V1) -> val -> mem -> (Genv.t F2 V2) -> val -> mem -> Prop.\n\nVariable GeInv23: (Genv.t F2 V2) -> (Genv.t F3 V3) -> Prop.\nVariable InitInv23 : meminj -> (Genv.t F2 V2) -> list val -> mem -> (Genv.t F3 V3) -> list val -> mem -> Prop.\nVariable HaltInv23: (*SM_Injection*)meminj -> (Genv.t F2 V2) -> val -> mem -> (Genv.t F3 V3) -> val -> mem -> Prop.\n\nVariable SIM12: Wholeprog_sim.Wholeprog_sim Sem1 Sem2 g1 g2 Main GeInv12 InitInv12 HaltInv12.\nVariable SIM23: Wholeprog_sim.Wholeprog_sim Sem2 Sem3 g2 g3 Main GeInv23 InitInv23 HaltInv23.\n\nDefinition CoreData12:= Wholeprog_sim.core_data _ _ _ _ _ _ _ _  SIM12.\nDefinition CoreData23:= Wholeprog_sim.core_data _ _ _ _ _ _ _ _  SIM23.\nDefinition CoreOrd12:= Wholeprog_sim.core_ord _ _ _ _ _ _ _ _  SIM12.\nDefinition CoreOrd23:= Wholeprog_sim.core_ord  _ _ _ _ _ _ _ _ SIM23.\nDefinition MatchState12:= Wholeprog_sim.match_state _ _ _ _ _ _ _ _ SIM12.\nDefinition MatchState23:= Wholeprog_sim.match_state _ _ _ _ _ _ _ _ SIM23.\nDefinition genv_inv12 := Wholeprog_sim.genv_inv _ _ _ _ _ _ _ _ SIM12.\nDefinition genv_inv23 := Wholeprog_sim.genv_inv _ _ _ _ _ _ _ _ SIM23.\n\nDefinition CoreDiag12 := Wholeprog_sim.core_diagram _ _ _ _ _ _ _ _ SIM12.\nDefinition CoreDiag23 := Wholeprog_sim.core_diagram _ _ _ _ _ _ _ _ SIM23.\nDefinition Halted12:= Wholeprog_sim.core_halted _ _ _ _ _ _ _ _ SIM12.\nDefinition Halted23:= Wholeprog_sim.core_halted _ _ _ _ _ _ _ _ SIM23.\nDefinition Init12:= Wholeprog_sim.core_initial _ _ _ _ _ _ _ _ SIM12.\nDefinition Init23:= Wholeprog_sim.core_initial _ _ _ _ _ _ _ _ SIM23.\n\nDefinition GeInv13 (ge1:Genv.t F1 V1) (ge3: Genv.t F3 V3): Prop := exists ge2, GeInv12 ge1 ge2 /\\ GeInv23 ge2 ge3.\n\nDefinition InitInv13 ge2 (j13:meminj) (ge1: Genv.t F1 V1) (vals1:list val) (m1:mem) (ge3:Genv.t F3 V3) (vals3:list val) (m3: mem): Prop :=\n  exists j12 j23 vals2 m2, InitInv12 j12 ge1 vals1 m1 ge2 vals2 m2 /\\\n                           InitInv23 j23 ge2 vals2 m2 ge3 vals3 m3 /\\\n                           j13 = compose_meminj j12 j23.\nDefinition HaltInv13 ge2 (j13:(*SM_Injection*)meminj) (ge1: Genv.t F1 V1) (v1: val) (m1: mem)\n                                                  (ge3: Genv.t F3 V3) (v3: val) (m3: mem): Prop :=\n  exists j12 j23 v2 m2, HaltInv12 j12 ge1 v1 m1 ge2 v2 m2 /\\\n                        HaltInv23 j23 ge2 v2 m2 ge3 v3 m3 /\\\n                        j13 = compose_meminj j12 j23.\n\nDefinition CoreOrd:= clos_trans _ (sem_compose_ord_eq_eq CoreOrd12 CoreOrd23 C2).\nDefinition MatchState := fun d mu c1 m1 c3 m3 =>\n      match d with (d1,X,d2) =>\n        exists c2, exists m2, exists mu1, exists mu2,\n          X=Some c2 /\\ mu = compose_meminj mu1 mu2 /\\\n          MatchState12 d1 mu1 c1 m1 c2 m2 /\\ MatchState23 d2 mu2 c2 m2 c3 m3\n      end.\n\nLemma WP_corestep_trans: forall (st1 : C1) (m1 : mem) (st1' : C1) (m1' : mem)\n      (CS1: corestep Sem1 g1 st1 m1 st1' m1'),\n      forall cd (st3 : C3) (j : meminj) (m3 : mem), MatchState cd j st1 m1 st3 m3 ->\n      exists (st3' : C3) (m3' : mem) cd' (j' : meminj),\n          MatchState cd' j' st1' m1' st3' m3' /\\\n         (corestep_plus Sem3 g3 st3 m3 st3' m3' \\/\n          corestep_star Sem3 g3 st3 m3 st3' m3' /\\ CoreOrd cd' cd).\nProof.  intros.\ndestruct cd as [[cd12 X] cd23].\ndestruct H as [c2 [m2 [j12 [j23 [HX [Hj [MS12 MS23]]]]]]]. subst X.\ndestruct (CoreDiag12 _ _ _ _ CS1 _ _ _ _ MS12) as [c2' [m2' [cd12' [j12' [MS12' Step2]]]]].\nassert (ZZ: corestep_plus Sem2 g2 c2 m2 c2' m2' \\/\n    (c2,m2) = (c2',m2') /\\ CoreOrd12 cd12' cd12).\n{ destruct Step2. auto.\n  destruct H.\n  destruct H. destruct x.\n  right. split; auto.\n  left. exists x; auto.\n}\nclear Step2. destruct ZZ as [CS2 | [CS2 ord12']].\n+ (*case1*)\n  destruct CS2.\n  clear CS1.\n  cut (exists st3' : C3,  exists m3' : mem, exists cd23', exists j23' : meminj,\n    MatchState23 cd23' j23' c2' m2' st3' m3' /\\\n    (corestep_plus Sem3 g3 st3 m3 st3' m3' \\/\n      (corestep_star Sem3 g3 st3 m3 st3' m3' /\\\n        clos_trans (CoreData12 * option C2 * CoreData23)\n        (sem_compose_ord_eq_eq CoreOrd12 CoreOrd23 C2) (cd12', Some c2', cd23')\n        (cd12, Some c2, cd23)))).\n  intros XX; destruct XX as [c3' [m3' [cd23' [j23' [MC23' ZZ]]]]].\n  exists c3'. exists m3'. exists (cd12', Some c2', cd23'). exists (compose_meminj j12' j23').\n  split. subst. red. exists c2', m2', j12', j23'. eauto.\n    apply ZZ.\n  clear MS12 MS12' Hj.\n  revert j23 cd23 c2 m2 st3 m3 H MS23.\n  induction x; intros.\n  - (*base case*)\n    destruct H as [c22 [m2'' [? ?]]].\n    inv H0.\n    destruct (CoreDiag23 _ _ _ _ H _ _ _ _ MS23)\n      as [c3' [m3' [cd23' [j23' [MS23' Step3]]]]].\n    exists c3', m3', cd23', j23'.\n    split; trivial.\n    destruct Step3. left; assumption.\n    destruct H0. right. split; trivial.\n    apply t_step. constructor 2. trivial.\n  - (*inductive case*)\n    remember (S x) as x'.\n    destruct H as [st2'' [m2'' [Step2 StepN2]]]. subst x'.\n    destruct (CoreDiag23 _ _ _ _ Step2 _ _ _ _ MS23)\n      as [c3' [m3' [cd23' [j23' [MS23' Step3]]]]].\n    specialize (IHx j23' cd23' _ _ c3' m3' StepN2 MS23'). clear Step2 StepN2 MS23'.\n    destruct IHx as [c3'' [m3'' [cd23'' [j23'' [MC' XX]]]]].\n    exists c3'', m3'', cd23'', j23''.\n    split. apply MC'.\n    destruct Step3; destruct XX.\n           (*1/4*)\n              left. destruct H as [n1 ?]. destruct H0 as [n2 ?].\n                      exists (n1 + S n2)%nat.\n                      change (S (n1 + S n2)) with (S n1 + S n2)%nat.\n                      rewrite corestepN_add. eauto.\n           (*2/4*)\n               destruct H0.\n               left. destruct H as [n1 ?]. destruct H0 as [n2 ?].\n                       exists (n1 + n2)%nat.\n                       change (S (n1 + n2)) with (S n1 + n2)%nat.\n                       rewrite corestepN_add. eauto.\n           (*3/4*)\n               left. destruct H.\n                       destruct H as [n1 ?]. destruct H0 as [n2 ?].\n                       exists (n1 + n2)%nat.\n                       replace (S (n1 + n2)) with (n1 + S n2)%nat by omega.\n                       rewrite corestepN_add. eauto.\n           (*3/4*)\n               right. destruct H. destruct H0.\n               split. destruct H as [n1 ?]. destruct H0 as [n2 ?].\n                         exists (n1 + n2)%nat.\n                         rewrite corestepN_add. eauto.\n              eapply t_trans; eauto.\n          (*4/4*)\n              apply t_step.\n              constructor 2. assumption.\n+ (*case 2*)\n   inv CS2.\n   exists st3, m3, (cd12',Some c2', cd23), (compose_meminj j12' j23).\n   split. exists c2', m2', j12', j23; auto.\n   right. split. exists O. simpl; auto.\n   apply t_step. constructor 1; auto.\nQed.\n\nDefinition WP_trans:\n        Wholeprog_sim.Wholeprog_sim Sem1 Sem3 g1 g3 Main GeInv13 (InitInv13 g2) (HaltInv13 g2).\neapply Wholeprog_sim.Build_Wholeprog_sim with\n  (core_ord:=CoreOrd)(match_state:=MatchState).\n{ (*well_founded*)\n  eapply Transitive_Closure.wf_clos_trans.\n  eapply well_founded_sem_compose_ord_eq_eq. apply SIM12. apply SIM23. }\n{ exists g2; split. apply genv_inv12. apply genv_inv23. }\n{ (*Init*)\n  intros j13 c1 vals1 m1 vals3 m3 Init1 IInv13.\n  destruct IInv13 as [j12 [j23 [vals2 [m2 [Initial12 [Initial23 Hj]]]]]].\n  destruct (Init12 _ _ _ _ _ _ Init1 Initial12) as [cd12 [c2 [Init2 MS12]]].\n  destruct (Init23 _ _ _ _ _ _ Init2 Initial23) as [cd23 [c3 [Init3 MS23]]].\n  exists ((cd12, Some c2), cd23), c3. split; trivial.\n  exists c2, m2, j12, j23; auto. }\n{ apply WP_corestep_trans. }\n{ (*Halted*)\n  intros [[c12 X] c23] j c1 m1 c3 m3 v1 MS HALT1.\n  destruct MS as [c2 [m2 [j12 [j23 [HX [Hj [MS12 MS23]]]]]]].\n  destruct (Halted12 _ _ _ _ _ _ _ MS12 HALT1) as [j12' [v2 [MI12 HALT2]]].\n  destruct (Halted23 _ _ _ _ _ _ _ MS23 HALT2) as [j23' [v3 [MI23 HALT3]]].\n  exists (compose_meminj j12' j23'), v3; split; trivial.\n  exists j12', j23', v2, m2; auto. }\nQed.\nEnd WholeSimTrans.\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_simulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.19508559597143432}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom compcert Require Import Coqlib.\nFrom compcert Require Import Zbits.\nFrom compcert Require Archi.\nFrom compcert Require Import AST.\nFrom compcert Require Import Integers.\nFrom compcert Require Import Floats.\nFrom compcert Require Import Values.\n\n\n\n\n\nDefinition size_chunk (chunk: memory_chunk) : Z :=\nmatch chunk with\n| Mint8signed => 1\n| Mint8unsigned => 1\n| Mint16signed => 2\n| Mint16unsigned => 2\n| Mint32 => 4\n| Mint64 => 8\n| Mfloat32 => 4\n| Mfloat64 => 8\n| Many32 => 4\n| Many64 => 8\nend.\n\nLemma size_chunk_pos:\nforall chunk, size_chunk chunk > 0.\nProof. hammer_hook \"Memdata\" \"Memdata.size_chunk_pos\".\nintros. destruct chunk; simpl; omega.\nQed.\n\nDefinition size_chunk_nat (chunk: memory_chunk) : nat :=\nZ.to_nat(size_chunk chunk).\n\nLemma size_chunk_conv:\nforall chunk, size_chunk chunk = Z.of_nat (size_chunk_nat chunk).\nProof. hammer_hook \"Memdata\" \"Memdata.size_chunk_conv\".\nintros. destruct chunk; reflexivity.\nQed.\n\nLemma size_chunk_nat_pos:\nforall chunk, exists n, size_chunk_nat chunk = S n.\nProof. hammer_hook \"Memdata\" \"Memdata.size_chunk_nat_pos\".\nintros.\ngeneralize (size_chunk_pos chunk). rewrite size_chunk_conv.\ndestruct (size_chunk_nat chunk).\nsimpl; intros; omegaContradiction.\nintros; exists n; auto.\nQed.\n\nLemma size_chunk_Mptr: size_chunk Mptr = if Archi.ptr64 then 8 else 4.\nProof. hammer_hook \"Memdata\" \"Memdata.size_chunk_Mptr\".\nunfold Mptr; destruct Archi.ptr64; auto.\nQed.\n\n\n\nDefinition align_chunk (chunk: memory_chunk) : Z :=\nmatch chunk with\n| Mint8signed => 1\n| Mint8unsigned => 1\n| Mint16signed => 2\n| Mint16unsigned => 2\n| Mint32 => 4\n| Mint64 => 8\n| Mfloat32 => 4\n| Mfloat64 => 4\n| Many32 => 4\n| Many64 => 4\nend.\n\nLemma align_chunk_pos:\nforall chunk, align_chunk chunk > 0.\nProof. hammer_hook \"Memdata\" \"Memdata.align_chunk_pos\".\nintro. destruct chunk; simpl; omega.\nQed.\n\nLemma align_chunk_Mptr: align_chunk Mptr = if Archi.ptr64 then 8 else 4.\nProof. hammer_hook \"Memdata\" \"Memdata.align_chunk_Mptr\".\nunfold Mptr; destruct Archi.ptr64; auto.\nQed.\n\nLemma align_size_chunk_divides:\nforall chunk, (align_chunk chunk | size_chunk chunk).\nProof. hammer_hook \"Memdata\" \"Memdata.align_size_chunk_divides\".\nintros. destruct chunk; simpl; try apply Z.divide_refl; exists 2; auto.\nQed.\n\nLemma align_le_divides:\nforall chunk1 chunk2,\nalign_chunk chunk1 <= align_chunk chunk2 -> (align_chunk chunk1 | align_chunk chunk2).\nProof. hammer_hook \"Memdata\" \"Memdata.align_le_divides\".\nintros. destruct chunk1; destruct chunk2; simpl in *;\nsolve [ omegaContradiction\n| apply Z.divide_refl\n| exists 2; reflexivity\n| exists 4; reflexivity\n| exists 8; reflexivity ].\nQed.\n\nInductive quantity : Type := Q32 | Q64.\n\nDefinition quantity_eq (q1 q2: quantity) : {q1 = q2} + {q1 <> q2}.\nProof. hammer_hook \"Memdata\" \"Memdata.quantity_eq\". decide equality. Defined.\nGlobal Opaque quantity_eq.\n\nDefinition size_quantity_nat (q: quantity) :=\nmatch q with Q32 => 4%nat | Q64 => 8%nat end.\n\nLemma size_quantity_nat_pos:\nforall q, exists n, size_quantity_nat q = S n.\nProof. hammer_hook \"Memdata\" \"Memdata.size_quantity_nat_pos\".\nintros. destruct q; [exists 3%nat | exists 7%nat]; auto.\nQed.\n\n\n\n\n\n\n\nInductive memval: Type :=\n| Undef: memval\n| Byte: byte -> memval\n| Fragment: val -> quantity -> nat -> memval.\n\n\n\n\n\nFixpoint bytes_of_int (n: nat) (x: Z) {struct n}: list byte :=\nmatch n with\n| O => nil\n| S m => Byte.repr x :: bytes_of_int m (x / 256)\nend.\n\nFixpoint int_of_bytes (l: list byte): Z :=\nmatch l with\n| nil => 0\n| b :: l' => Byte.unsigned b + int_of_bytes l' * 256\nend.\n\nDefinition rev_if_be (l: list byte) : list byte :=\nif Archi.big_endian then List.rev l else l.\n\nDefinition encode_int (sz: nat) (x: Z) : list byte :=\nrev_if_be (bytes_of_int sz x).\n\nDefinition decode_int (b: list byte) : Z :=\nint_of_bytes (rev_if_be b).\n\n\n\nLemma length_bytes_of_int:\nforall n x, length (bytes_of_int n x) = n.\nProof. hammer_hook \"Memdata\" \"Memdata.length_bytes_of_int\".\ninduction n; simpl; intros. auto. decEq. auto.\nQed.\n\nLemma rev_if_be_length:\nforall l, length (rev_if_be l) = length l.\nProof. hammer_hook \"Memdata\" \"Memdata.rev_if_be_length\".\nintros; unfold rev_if_be; destruct Archi.big_endian.\napply List.rev_length.\nauto.\nQed.\n\nLemma encode_int_length:\nforall sz x, length(encode_int sz x) = sz.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_int_length\".\nintros. unfold encode_int. rewrite rev_if_be_length. apply length_bytes_of_int.\nQed.\n\n\n\nLemma int_of_bytes_of_int:\nforall n x,\nint_of_bytes (bytes_of_int n x) = x mod (two_p (Z.of_nat n * 8)).\nProof. hammer_hook \"Memdata\" \"Memdata.int_of_bytes_of_int\".\ninduction n; intros.\nsimpl. rewrite Zmod_1_r. auto.\nOpaque Byte.wordsize.\nrewrite Nat2Z.inj_succ. simpl.\nreplace (Z.succ (Z.of_nat n) * 8) with (Z.of_nat n * 8 + 8) by omega.\nrewrite two_p_is_exp; try omega.\nrewrite Zmod_recombine. rewrite IHn. rewrite Z.add_comm.\nchange (Byte.unsigned (Byte.repr x)) with (Byte.Z_mod_modulus x).\nrewrite Byte.Z_mod_modulus_eq. reflexivity.\napply two_p_gt_ZERO. omega. apply two_p_gt_ZERO. omega.\nQed.\n\nLemma rev_if_be_involutive:\nforall l, rev_if_be (rev_if_be l) = l.\nProof. hammer_hook \"Memdata\" \"Memdata.rev_if_be_involutive\".\nintros; unfold rev_if_be; destruct Archi.big_endian.\napply List.rev_involutive.\nauto.\nQed.\n\nLemma decode_encode_int:\nforall n x, decode_int (encode_int n x) = x mod (two_p (Z.of_nat n * 8)).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_int\".\nunfold decode_int, encode_int; intros. rewrite rev_if_be_involutive.\napply int_of_bytes_of_int.\nQed.\n\nLemma decode_encode_int_1:\nforall x, Int.repr (decode_int (encode_int 1 (Int.unsigned x))) = Int.zero_ext 8 x.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_int_1\".\nintros. rewrite decode_encode_int.\nrewrite <- (Int.repr_unsigned (Int.zero_ext 8 x)).\ndecEq. symmetry. apply Int.zero_ext_mod. compute. intuition congruence.\nQed.\n\nLemma decode_encode_int_2:\nforall x, Int.repr (decode_int (encode_int 2 (Int.unsigned x))) = Int.zero_ext 16 x.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_int_2\".\nintros. rewrite decode_encode_int.\nrewrite <- (Int.repr_unsigned (Int.zero_ext 16 x)).\ndecEq. symmetry. apply Int.zero_ext_mod. compute; intuition congruence.\nQed.\n\nLemma decode_encode_int_4:\nforall x, Int.repr (decode_int (encode_int 4 (Int.unsigned x))) = x.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_int_4\".\nintros. rewrite decode_encode_int. transitivity (Int.repr (Int.unsigned x)).\ndecEq. apply Z.mod_small. apply Int.unsigned_range. apply Int.repr_unsigned.\nQed.\n\nLemma decode_encode_int_8:\nforall x, Int64.repr (decode_int (encode_int 8 (Int64.unsigned x))) = x.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_int_8\".\nintros. rewrite decode_encode_int. transitivity (Int64.repr (Int64.unsigned x)).\ndecEq. apply Z.mod_small. apply Int64.unsigned_range. apply Int64.repr_unsigned.\nQed.\n\n\n\nLemma bytes_of_int_mod:\nforall n x y,\neqmod (two_p (Z.of_nat n * 8)) x y ->\nbytes_of_int n x = bytes_of_int n y.\nProof. hammer_hook \"Memdata\" \"Memdata.bytes_of_int_mod\".\ninduction n.\nintros; simpl; auto.\nintros until y.\nrewrite Nat2Z.inj_succ.\nreplace (Z.succ (Z.of_nat n) * 8) with (Z.of_nat n * 8 + 8) by omega.\nrewrite two_p_is_exp; try omega.\nintro EQM.\nsimpl; decEq.\napply Byte.eqm_samerepr. red.\neapply eqmod_divides; eauto. apply Z.divide_factor_r.\napply IHn.\ndestruct EQM as [k EQ]. exists k. rewrite EQ.\nrewrite <- Z_div_plus_full_l. decEq. change (two_p 8) with 256. ring. omega.\nQed.\n\nLemma encode_int_8_mod:\nforall x y,\neqmod (two_p 8) x y ->\nencode_int 1%nat x = encode_int 1%nat y.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_int_8_mod\".\nintros. unfold encode_int. decEq. apply bytes_of_int_mod. auto.\nQed.\n\nLemma encode_int_16_mod:\nforall x y,\neqmod (two_p 16) x y ->\nencode_int 2%nat x = encode_int 2%nat y.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_int_16_mod\".\nintros. unfold encode_int. decEq. apply bytes_of_int_mod. auto.\nQed.\n\n\n\nDefinition inj_bytes (bl: list byte) : list memval :=\nList.map Byte bl.\n\nFixpoint proj_bytes (vl: list memval) : option (list byte) :=\nmatch vl with\n| nil => Some nil\n| Byte b :: vl' =>\nmatch proj_bytes vl' with None => None | Some bl => Some(b :: bl) end\n| _ => None\nend.\n\nRemark length_inj_bytes:\nforall bl, length (inj_bytes bl) = length bl.\nProof. hammer_hook \"Memdata\" \"Memdata.length_inj_bytes\".\nintros. apply List.map_length.\nQed.\n\nRemark proj_inj_bytes:\nforall bl, proj_bytes (inj_bytes bl) = Some bl.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_inj_bytes\".\ninduction bl; simpl. auto. rewrite IHbl. auto.\nQed.\n\nLemma inj_proj_bytes:\nforall cl bl, proj_bytes cl = Some bl -> cl = inj_bytes bl.\nProof. hammer_hook \"Memdata\" \"Memdata.inj_proj_bytes\".\ninduction cl; simpl; intros.\ninv H; auto.\ndestruct a; try congruence. destruct (proj_bytes cl); inv H.\nsimpl. decEq. auto.\nQed.\n\nFixpoint inj_value_rec (n: nat) (v: val) (q: quantity) {struct n}: list memval :=\nmatch n with\n| O => nil\n| S m => Fragment v q m :: inj_value_rec m v q\nend.\n\nDefinition inj_value (q: quantity) (v: val): list memval :=\ninj_value_rec (size_quantity_nat q) v q.\n\nFixpoint check_value (n: nat) (v: val) (q: quantity) (vl: list memval)\n{struct n} : bool :=\nmatch n, vl with\n| O, nil => true\n| S m, Fragment v' q' m' :: vl' =>\nVal.eq v v' && quantity_eq q q' && Nat.eqb m m' && check_value m v q vl'\n| _, _ => false\nend.\n\nDefinition proj_value (q: quantity) (vl: list memval) : val :=\nmatch vl with\n| Fragment v q' n :: vl' =>\nif check_value (size_quantity_nat q) v q vl then v else Vundef\n| _ => Vundef\nend.\n\nDefinition encode_val (chunk: memory_chunk) (v: val) : list memval :=\nmatch v, chunk with\n| Vint n, (Mint8signed | Mint8unsigned) => inj_bytes (encode_int 1%nat (Int.unsigned n))\n| Vint n, (Mint16signed | Mint16unsigned) => inj_bytes (encode_int 2%nat (Int.unsigned n))\n| Vint n, Mint32 => inj_bytes (encode_int 4%nat (Int.unsigned n))\n| Vptr b ofs, Mint32 => if Archi.ptr64 then list_repeat 4%nat Undef else inj_value Q32 v\n| Vlong n, Mint64 => inj_bytes (encode_int 8%nat (Int64.unsigned n))\n| Vptr b ofs, Mint64 => if Archi.ptr64 then inj_value Q64 v else list_repeat 8%nat Undef\n| Vsingle n, Mfloat32 => inj_bytes (encode_int 4%nat (Int.unsigned (Float32.to_bits n)))\n| Vfloat n, Mfloat64 => inj_bytes (encode_int 8%nat (Int64.unsigned (Float.to_bits n)))\n| _, Many32 => inj_value Q32 v\n| _, Many64 => inj_value Q64 v\n| _, _ => list_repeat (size_chunk_nat chunk) Undef\nend.\n\nDefinition decode_val (chunk: memory_chunk) (vl: list memval) : val :=\nmatch proj_bytes vl with\n| Some bl =>\nmatch chunk with\n| Mint8signed => Vint(Int.sign_ext 8 (Int.repr (decode_int bl)))\n| Mint8unsigned => Vint(Int.zero_ext 8 (Int.repr (decode_int bl)))\n| Mint16signed => Vint(Int.sign_ext 16 (Int.repr (decode_int bl)))\n| Mint16unsigned => Vint(Int.zero_ext 16 (Int.repr (decode_int bl)))\n| Mint32 => Vint(Int.repr(decode_int bl))\n| Mint64 => Vlong(Int64.repr(decode_int bl))\n| Mfloat32 => Vsingle(Float32.of_bits (Int.repr (decode_int bl)))\n| Mfloat64 => Vfloat(Float.of_bits (Int64.repr (decode_int bl)))\n| Many32 => Vundef\n| Many64 => Vundef\nend\n| None =>\nmatch chunk with\n| Mint32 => if Archi.ptr64 then Vundef else Val.load_result chunk (proj_value Q32 vl)\n| Many32 => Val.load_result chunk (proj_value Q32 vl)\n| Mint64 => if Archi.ptr64 then Val.load_result chunk (proj_value Q64 vl) else Vundef\n| Many64 => Val.load_result chunk (proj_value Q64 vl)\n| _ => Vundef\nend\nend.\n\nLtac solve_encode_val_length :=\nmatch goal with\n| [ |- length (inj_bytes _) = _ ] => rewrite length_inj_bytes; solve_encode_val_length\n| [ |- length (encode_int _ _) = _ ] => apply encode_int_length\n| [ |- length (if ?x then _ else _) = _ ] => destruct x eqn:?; solve_encode_val_length\n| _ => reflexivity\nend.\n\nLemma encode_val_length:\nforall chunk v, length(encode_val chunk v) = size_chunk_nat chunk.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_length\".\nintros. destruct v; simpl; destruct chunk; solve_encode_val_length.\nQed.\n\nLemma check_inj_value:\nforall v q n, check_value n v q (inj_value_rec n v q) = true.\nProof. hammer_hook \"Memdata\" \"Memdata.check_inj_value\".\ninduction n; simpl. auto.\nunfold proj_sumbool. rewrite dec_eq_true. rewrite dec_eq_true.\nrewrite <- beq_nat_refl. simpl; auto.\nQed.\n\nLemma proj_inj_value:\nforall q v, proj_value q (inj_value q v) = v.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_inj_value\".\nintros. unfold proj_value, inj_value. destruct (size_quantity_nat_pos q) as [n EQ].\nrewrite EQ at 1. simpl. rewrite check_inj_value. auto.\nQed.\n\nRemark in_inj_value:\nforall mv v q, In mv (inj_value q v) -> exists n, mv = Fragment v q n.\nProof. hammer_hook \"Memdata\" \"Memdata.in_inj_value\".\nLocal Transparent inj_value.\nunfold inj_value; intros until q. generalize (size_quantity_nat q). induction n; simpl; intros.\ncontradiction.\ndestruct H. exists n; auto. eauto.\nQed.\n\nLemma proj_inj_value_mismatch:\nforall q1 q2 v, q1 <> q2 -> proj_value q1 (inj_value q2 v) = Vundef.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_inj_value_mismatch\".\nintros. unfold proj_value. destruct (inj_value q2 v) eqn:V. auto. destruct m; auto.\ndestruct (in_inj_value (Fragment v0 q n) v q2) as [n' EQ].\nrewrite V; auto with coqlib. inv EQ.\ndestruct (size_quantity_nat_pos q1) as [p EQ1]; rewrite EQ1; simpl.\nunfold proj_sumbool. rewrite dec_eq_true. rewrite dec_eq_false by congruence. auto.\nQed.\n\nDefinition decode_encode_val (v1: val) (chunk1 chunk2: memory_chunk) (v2: val) : Prop :=\nmatch v1, chunk1, chunk2 with\n| Vundef, _, _ => v2 = Vundef\n| Vint n, Mint8signed, Mint8signed => v2 = Vint(Int.sign_ext 8 n)\n| Vint n, Mint8unsigned, Mint8signed => v2 = Vint(Int.sign_ext 8 n)\n| Vint n, Mint8signed, Mint8unsigned => v2 = Vint(Int.zero_ext 8 n)\n| Vint n, Mint8unsigned, Mint8unsigned => v2 = Vint(Int.zero_ext 8 n)\n| Vint n, Mint16signed, Mint16signed => v2 = Vint(Int.sign_ext 16 n)\n| Vint n, Mint16unsigned, Mint16signed => v2 = Vint(Int.sign_ext 16 n)\n| Vint n, Mint16signed, Mint16unsigned => v2 = Vint(Int.zero_ext 16 n)\n| Vint n, Mint16unsigned, Mint16unsigned => v2 = Vint(Int.zero_ext 16 n)\n| Vint n, Mint32, Mint32 => v2 = Vint n\n| Vint n, Many32, Many32 => v2 = Vint n\n| Vint n, Mint32, Mfloat32 => v2 = Vsingle(Float32.of_bits n)\n| Vint n, Many64, Many64 => v2 = Vint n\n| Vint n, (Mint64 | Mfloat32 | Mfloat64 | Many64), _ => v2 = Vundef\n| Vint n, _, _ => True\n| Vptr b ofs, (Mint32 | Many32), (Mint32 | Many32) => v2 = if Archi.ptr64 then Vundef else Vptr b ofs\n| Vptr b ofs, Mint64, (Mint64 | Many64) => v2 = if Archi.ptr64 then Vptr b ofs else Vundef\n| Vptr b ofs, Many64, Many64 => v2 = Vptr b ofs\n| Vptr b ofs, Many64, Mint64 => v2 = if Archi.ptr64 then Vptr b ofs else Vundef\n| Vptr b ofs, _, _ => v2 = Vundef\n| Vlong n, Mint64, Mint64 => v2 = Vlong n\n| Vlong n, Mint64, Mfloat64 => v2 = Vfloat(Float.of_bits n)\n| Vlong n, Many64, Many64 => v2 = Vlong n\n| Vlong n, (Mint8signed|Mint8unsigned|Mint16signed|Mint16unsigned|Mint32|Mfloat32|Mfloat64|Many32), _ => v2 = Vundef\n| Vlong n, _, _ => True\n| Vfloat f, Mfloat64, Mfloat64 => v2 = Vfloat f\n| Vfloat f, Mfloat64, Mint64 => v2 = Vlong(Float.to_bits f)\n| Vfloat f, Many64, Many64 => v2 = Vfloat f\n| Vfloat f, (Mint8signed|Mint8unsigned|Mint16signed|Mint16unsigned|Mint32|Mfloat32|Mint64|Many32), _ => v2 = Vundef\n| Vfloat f, _, _ => True\n| Vsingle f, Mfloat32, Mfloat32 => v2 = Vsingle f\n| Vsingle f, Mfloat32, Mint32 => v2 = Vint(Float32.to_bits f)\n| Vsingle f, Many32, Many32 => v2 = Vsingle f\n| Vsingle f, Many64, Many64 => v2 = Vsingle f\n| Vsingle f, (Mint8signed|Mint8unsigned|Mint16signed|Mint16unsigned|Mint32|Mint64|Mfloat64|Many64), _ => v2 = Vundef\n| Vsingle f, _, _ => True\nend.\n\nRemark decode_val_undef:\nforall bl chunk, decode_val chunk (Undef :: bl) = Vundef.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_undef\".\nintros. unfold decode_val. simpl. destruct chunk, Archi.ptr64; auto.\nQed.\n\nRemark proj_bytes_inj_value:\nforall q v, proj_bytes (inj_value q v) = None.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_bytes_inj_value\".\nintros. destruct q; reflexivity.\nQed.\n\nLtac solve_decode_encode_val_general :=\nexact I || reflexivity ||\nmatch goal with\n| |- context [ if Archi.ptr64 then _ else _ ] => destruct Archi.ptr64 eqn:?\n| |- context [ proj_bytes (inj_bytes _) ] => rewrite proj_inj_bytes\n| |- context [ proj_bytes (inj_value _ _) ] => rewrite proj_bytes_inj_value\n| |- context [ proj_value _ (inj_value _ _) ] => rewrite ?proj_inj_value, ?proj_inj_value_mismatch by congruence\n| |- context [ Int.repr(decode_int (encode_int 1 (Int.unsigned _))) ] => rewrite decode_encode_int_1\n| |- context [ Int.repr(decode_int (encode_int 2 (Int.unsigned _))) ] => rewrite decode_encode_int_2\n| |- context [ Int.repr(decode_int (encode_int 4 (Int.unsigned _))) ] => rewrite decode_encode_int_4\n| |- context [ Int64.repr(decode_int (encode_int 8 (Int64.unsigned _))) ] => rewrite decode_encode_int_8\n| |- Vint (Int.sign_ext _ (Int.sign_ext _ _)) = Vint _ => f_equal; apply Int.sign_ext_idem; omega\n| |- Vint (Int.zero_ext _ (Int.zero_ext _ _)) = Vint _ => f_equal; apply Int.zero_ext_idem; omega\n| |- Vint (Int.sign_ext _ (Int.zero_ext _ _)) = Vint _ => f_equal; apply Int.sign_ext_zero_ext; omega\nend.\n\nLemma decode_encode_val_general:\nforall v chunk1 chunk2,\ndecode_encode_val v chunk1 chunk2 (decode_val chunk2 (encode_val chunk1 v)).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_val_general\".\nOpaque inj_value.\nintros.\ndestruct v; destruct chunk1 eqn:C1; try (apply decode_val_undef);\ndestruct chunk2 eqn:C2; unfold decode_encode_val, decode_val, encode_val, Val.load_result;\nrepeat solve_decode_encode_val_general.\n- rewrite Float.of_to_bits; auto.\n- rewrite Float32.of_to_bits; auto.\nQed.\n\nLemma decode_encode_val_similar:\nforall v1 chunk1 chunk2 v2,\ntype_of_chunk chunk1 = type_of_chunk chunk2 ->\nsize_chunk chunk1 = size_chunk chunk2 ->\ndecode_encode_val v1 chunk1 chunk2 v2 ->\nv2 = Val.load_result chunk2 v1.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_encode_val_similar\".\nintros until v2; intros TY SZ DE.\ndestruct chunk1; destruct chunk2; simpl in TY; try discriminate; simpl in SZ; try omegaContradiction;\ndestruct v1; auto.\nQed.\n\nLemma decode_val_type:\nforall chunk cl,\nVal.has_type (decode_val chunk cl) (type_of_chunk chunk).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_type\".\nintros. unfold decode_val.\ndestruct (proj_bytes cl).\ndestruct chunk; simpl; auto.\nLocal Opaque Val.load_result.\ndestruct chunk; simpl;\n(exact I || apply Val.load_result_type || destruct Archi.ptr64; (exact I || apply Val.load_result_type)).\nQed.\n\nLemma encode_val_int8_signed_unsigned:\nforall v, encode_val Mint8signed v = encode_val Mint8unsigned v.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int8_signed_unsigned\".\nintros. destruct v; simpl; auto.\nQed.\n\nLemma encode_val_int16_signed_unsigned:\nforall v, encode_val Mint16signed v = encode_val Mint16unsigned v.\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int16_signed_unsigned\".\nintros. destruct v; simpl; auto.\nQed.\n\nLemma encode_val_int8_zero_ext:\nforall n, encode_val Mint8unsigned (Vint (Int.zero_ext 8 n)) = encode_val Mint8unsigned (Vint n).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int8_zero_ext\".\nintros; unfold encode_val. decEq. apply encode_int_8_mod. apply Int.eqmod_zero_ext.\ncompute; intuition congruence.\nQed.\n\nLemma encode_val_int8_sign_ext:\nforall n, encode_val Mint8signed (Vint (Int.sign_ext 8 n)) = encode_val Mint8signed (Vint n).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int8_sign_ext\".\nintros; unfold encode_val. decEq. apply encode_int_8_mod. apply Int.eqmod_sign_ext'. compute; auto.\nQed.\n\nLemma encode_val_int16_zero_ext:\nforall n, encode_val Mint16unsigned (Vint (Int.zero_ext 16 n)) = encode_val Mint16unsigned (Vint n).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int16_zero_ext\".\nintros; unfold encode_val. decEq. apply encode_int_16_mod. apply Int.eqmod_zero_ext. compute; intuition congruence.\nQed.\n\nLemma encode_val_int16_sign_ext:\nforall n, encode_val Mint16signed (Vint (Int.sign_ext 16 n)) = encode_val Mint16signed (Vint n).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int16_sign_ext\".\nintros; unfold encode_val. decEq. apply encode_int_16_mod. apply Int.eqmod_sign_ext'. compute; auto.\nQed.\n\nLemma decode_val_cast:\nforall chunk l,\nlet v := decode_val chunk l in\nmatch 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\nend.\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_cast\".\nunfold decode_val; intros; destruct chunk; auto; destruct (proj_bytes l); auto.\nunfold Val.sign_ext. rewrite Int.sign_ext_idem; auto. omega.\nunfold Val.zero_ext. rewrite Int.zero_ext_idem; auto. omega.\nunfold Val.sign_ext. rewrite Int.sign_ext_idem; auto. omega.\nunfold Val.zero_ext. rewrite Int.zero_ext_idem; auto. omega.\nQed.\n\n\n\nDefinition quantity_chunk (chunk: memory_chunk) :=\nmatch chunk with\n| Mint64 | Mfloat64 | Many64 => Q64\n| _ => Q32\nend.\n\nInductive shape_encoding (chunk: memory_chunk) (v: val): list memval -> Prop :=\n| shape_encoding_f: forall q i mvl,\n(chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Mint64 \\/ chunk = Many64) ->\nq = quantity_chunk chunk ->\nS i = size_quantity_nat q ->\n(forall mv, In mv mvl -> exists j, mv = Fragment v q j /\\ S j <> size_quantity_nat q) ->\nshape_encoding chunk v (Fragment v q i :: mvl)\n| shape_encoding_b: forall b mvl,\nmatch v with Vint _ => True | Vlong _ => True | Vfloat _ => True | Vsingle _ => True | _ => False end ->\n(forall mv, In mv mvl -> exists b', mv = Byte b') ->\nshape_encoding chunk v (Byte b :: mvl)\n| shape_encoding_u: forall mvl,\n(forall mv, In mv mvl -> mv = Undef) ->\nshape_encoding chunk v (Undef :: mvl).\n\nLemma encode_val_shape: forall chunk v, shape_encoding chunk v (encode_val chunk v).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_shape\".\nintros.\ndestruct (size_chunk_nat_pos chunk) as [sz EQ].\nassert (A: forall mv q n,\n(n < size_quantity_nat q)%nat ->\nIn mv (inj_value_rec n v q) ->\nexists j, mv = Fragment v q j /\\ S j <> size_quantity_nat q).\n{\ninduction n; simpl; intros. contradiction. destruct H0.\nexists n; split; auto. omega. apply IHn; auto. omega.\n}\nassert (B: forall q,\nq = quantity_chunk chunk ->\n(chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Mint64 \\/ chunk = Many64) ->\nshape_encoding chunk v (inj_value q v)).\n{\nLocal Transparent inj_value.\nintros. unfold inj_value. destruct (size_quantity_nat_pos q) as [sz' EQ'].\nrewrite EQ'. simpl. constructor; auto.\nintros; eapply A; eauto. omega.\n}\nassert (C: forall bl,\nmatch v with Vint _ => True | Vlong _ => True | Vfloat _ => True | Vsingle _ => True | _ => False end ->\nlength (inj_bytes bl) = size_chunk_nat chunk ->\nshape_encoding chunk v (inj_bytes bl)).\n{\nintros. destruct bl as [|b1 bl]. simpl in H0; congruence. simpl.\nconstructor; auto. unfold inj_bytes; intros. exploit list_in_map_inv; eauto.\nintros (b & P & Q); exists b; auto.\n}\nassert (D: shape_encoding chunk v (list_repeat (size_chunk_nat chunk) Undef)).\n{\nintros. rewrite EQ; simpl; constructor; auto.\nintros. eapply in_list_repeat; eauto.\n}\ngeneralize (encode_val_length chunk v). intros LEN.\nunfold encode_val; unfold encode_val in LEN;\ndestruct v; destruct chunk;\n(apply B || apply C || apply D || (destruct Archi.ptr64; (apply B || apply D)));\nauto.\nQed.\n\nInductive shape_decoding (chunk: memory_chunk): list memval -> val -> Prop :=\n| shape_decoding_f: forall v q i mvl,\n(chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Mint64 \\/ chunk = Many64) ->\nq = quantity_chunk chunk ->\nS i = size_quantity_nat q ->\n(forall mv, In mv mvl -> exists j, mv = Fragment v q j /\\ S j <> size_quantity_nat q) ->\nshape_decoding chunk (Fragment v q i :: mvl) (Val.load_result chunk v)\n| shape_decoding_b: forall b mvl v,\nmatch v with Vint _ => True | Vlong _ => True | Vfloat _ => True | Vsingle _ => True |  _ => False end ->\n(forall mv, In mv mvl -> exists b', mv = Byte b') ->\nshape_decoding chunk (Byte b :: mvl) v\n| shape_decoding_u: forall mvl,\nshape_decoding chunk mvl Vundef.\n\nLemma decode_val_shape: forall chunk mv1 mvl,\nshape_decoding chunk (mv1 :: mvl) (decode_val chunk (mv1 :: mvl)).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_shape\".\nintros.\nassert (A: forall mv mvs bs, proj_bytes mvs = Some bs -> In mv mvs ->\nexists b, mv = Byte b).\n{\ninduction mvs; simpl; intros.\ncontradiction.\ndestruct a; try discriminate. destruct H0. exists i; auto.\ndestruct (proj_bytes mvs); try discriminate. eauto.\n}\nassert (B: forall v q mv n mvs,\ncheck_value n v q mvs = true -> In mv mvs -> (n < size_quantity_nat q)%nat ->\nexists j, mv = Fragment v q j /\\ S j <> size_quantity_nat q).\n{\ninduction n; destruct mvs; simpl; intros; try discriminate.\ncontradiction.\ndestruct m; try discriminate. InvBooleans. apply beq_nat_true in H4. subst.\ndestruct H0. subst mv. exists n0; split; auto. omega.\neapply IHn; eauto. omega.\n}\nassert (U: forall mvs, shape_decoding chunk mvs (Val.load_result chunk Vundef)).\n{\nintros. replace (Val.load_result chunk Vundef) with Vundef. constructor.\ndestruct chunk; auto.\n}\nassert (C: forall q, size_quantity_nat q = size_chunk_nat chunk ->\n(chunk = Mint32 \\/ chunk = Many32 \\/ chunk = Mint64 \\/ chunk = Many64) ->\nshape_decoding chunk (mv1 :: mvl) (Val.load_result chunk (proj_value q (mv1 :: mvl)))).\n{\nintros. unfold proj_value. destruct mv1; auto.\ndestruct (size_quantity_nat_pos q) as [sz EQ]. rewrite EQ.\nsimpl. unfold proj_sumbool. rewrite dec_eq_true.\ndestruct (quantity_eq q q0); auto.\ndestruct (Nat.eqb sz n) eqn:EQN; auto.\ndestruct (check_value sz v q mvl) eqn:CHECK; auto.\nsimpl. apply beq_nat_true in EQN. subst n q0. constructor. auto.\ndestruct H0 as [E|[E|[E|E]]]; subst chunk; destruct q; auto || discriminate.\ncongruence.\nintros. eapply B; eauto. omega.\n}\nunfold decode_val.\ndestruct (proj_bytes (mv1 :: mvl)) as [bl|] eqn:PB.\nexploit (A mv1); eauto with coqlib. intros [b1 EQ1]; subst mv1.\ndestruct chunk; (apply shape_decoding_u || apply shape_decoding_b); eauto with coqlib.\ndestruct chunk, Archi.ptr64; (apply shape_decoding_u || apply C); auto.\nQed.\n\n\n\n\n\nInductive memval_inject (f: meminj): memval -> memval -> Prop :=\n| memval_inject_byte:\nforall n, memval_inject f (Byte n) (Byte n)\n| memval_inject_frag:\nforall v1 v2 q n,\nVal.inject f v1 v2 ->\nmemval_inject f (Fragment v1 q n) (Fragment v2 q n)\n| memval_inject_undef:\nforall mv, memval_inject f Undef mv.\n\nLemma memval_inject_incr:\nforall f f' v1 v2, memval_inject f v1 v2 -> inject_incr f f' -> memval_inject f' v1 v2.\nProof. hammer_hook \"Memdata\" \"Memdata.memval_inject_incr\".\nintros. inv H; econstructor. eapply val_inject_incr; eauto.\nQed.\n\n\n\nLemma proj_bytes_inject:\nforall f vl vl',\nlist_forall2 (memval_inject f) vl vl' ->\nforall bl,\nproj_bytes vl = Some bl ->\nproj_bytes vl' = Some bl.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_bytes_inject\".\ninduction 1; simpl. congruence.\ninv H; try congruence.\ndestruct (proj_bytes al); intros.\ninv H. rewrite (IHlist_forall2 l); auto.\ncongruence.\nQed.\n\nLemma check_value_inject:\nforall f vl vl',\nlist_forall2 (memval_inject f) vl vl' ->\nforall v v' q n,\ncheck_value n v q vl = true ->\nVal.inject f v v' -> v <> Vundef ->\ncheck_value n v' q vl' = true.\nProof. hammer_hook \"Memdata\" \"Memdata.check_value_inject\".\ninduction 1; intros; destruct n; simpl in *; auto.\ninv H; auto.\nInvBooleans. assert (n = n0) by (apply beq_nat_true; auto). subst v1 q0 n0.\nreplace v2 with v'.\nunfold proj_sumbool; rewrite ! dec_eq_true. rewrite <- beq_nat_refl. simpl; eauto.\ninv H2; try discriminate; inv H4; congruence.\ndiscriminate.\nQed.\n\nLemma proj_value_inject:\nforall f q vl1 vl2,\nlist_forall2 (memval_inject f) vl1 vl2 ->\nVal.inject f (proj_value q vl1) (proj_value q vl2).\nProof. hammer_hook \"Memdata\" \"Memdata.proj_value_inject\".\nintros. unfold proj_value.\ninversion H; subst. auto. inversion H0; subst; auto.\ndestruct (check_value (size_quantity_nat q) v1 q (Fragment v1 q0 n :: al)) eqn:B; auto.\ndestruct (Val.eq v1 Vundef). subst; auto.\nerewrite check_value_inject by eauto. auto.\nQed.\n\nLemma proj_bytes_not_inject:\nforall f vl vl',\nlist_forall2 (memval_inject f) vl vl' ->\nproj_bytes vl = None -> proj_bytes vl' <> None -> In Undef vl.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_bytes_not_inject\".\ninduction 1; simpl; intros.\ncongruence.\ninv H; try congruence.\nright. apply IHlist_forall2.\ndestruct (proj_bytes al); congruence.\ndestruct (proj_bytes bl); congruence.\nauto.\nQed.\n\nLemma check_value_undef:\nforall n q v vl,\nIn Undef vl -> check_value n v q vl = false.\nProof. hammer_hook \"Memdata\" \"Memdata.check_value_undef\".\ninduction n; intros; simpl.\ndestruct vl. elim H. auto.\ndestruct vl. auto.\ndestruct m; auto. simpl in H; destruct H. congruence.\nrewrite IHn; auto. apply andb_false_r.\nQed.\n\nLemma proj_value_undef:\nforall q vl, In Undef vl -> proj_value q vl = Vundef.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_value_undef\".\nintros; unfold proj_value.\ndestruct vl; auto. destruct m; auto.\nrewrite check_value_undef. auto. auto.\nQed.\n\nTheorem decode_val_inject:\nforall f vl1 vl2 chunk,\nlist_forall2 (memval_inject f) vl1 vl2 ->\nVal.inject f (decode_val chunk vl1) (decode_val chunk vl2).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_inject\".\nintros. unfold decode_val.\ndestruct (proj_bytes vl1) as [bl1|] eqn:PB1.\nexploit proj_bytes_inject; eauto. intros PB2. rewrite PB2.\ndestruct chunk; constructor.\nassert (A: forall q fn,\nVal.inject f (Val.load_result chunk (proj_value q vl1))\n(match proj_bytes vl2 with\n| Some bl => fn bl\n| None => Val.load_result chunk (proj_value q vl2)\nend)).\n{ intros. destruct (proj_bytes vl2) as [bl2|] eqn:PB2.\nrewrite proj_value_undef. destruct chunk; auto. eapply proj_bytes_not_inject; eauto. congruence.\napply Val.load_result_inject. apply proj_value_inject; auto.\n}\ndestruct chunk; destruct Archi.ptr64; auto.\nQed.\n\n\n\nLemma inj_bytes_inject:\nforall f bl, list_forall2 (memval_inject f) (inj_bytes bl) (inj_bytes bl).\nProof. hammer_hook \"Memdata\" \"Memdata.inj_bytes_inject\".\ninduction bl; constructor; auto. constructor.\nQed.\n\nLemma repeat_Undef_inject_any:\nforall f vl,\nlist_forall2 (memval_inject f) (list_repeat (length vl) Undef) vl.\nProof. hammer_hook \"Memdata\" \"Memdata.repeat_Undef_inject_any\".\ninduction vl; simpl; constructor; auto. constructor.\nQed.\n\nLemma repeat_Undef_inject_encode_val:\nforall f chunk v,\nlist_forall2 (memval_inject f) (list_repeat (size_chunk_nat chunk) Undef) (encode_val chunk v).\nProof. hammer_hook \"Memdata\" \"Memdata.repeat_Undef_inject_encode_val\".\nintros. rewrite <- (encode_val_length chunk v). apply repeat_Undef_inject_any.\nQed.\n\nLemma repeat_Undef_inject_self:\nforall f n,\nlist_forall2 (memval_inject f) (list_repeat n Undef) (list_repeat n Undef).\nProof. hammer_hook \"Memdata\" \"Memdata.repeat_Undef_inject_self\".\ninduction n; simpl; constructor; auto. constructor.\nQed.\n\nLemma inj_value_inject:\nforall f v1 v2 q, Val.inject f v1 v2 -> list_forall2 (memval_inject f) (inj_value q v1) (inj_value q v2).\nProof. hammer_hook \"Memdata\" \"Memdata.inj_value_inject\".\nintros.\nLocal Transparent inj_value.\nunfold inj_value. generalize (size_quantity_nat q). induction n; simpl; constructor; auto.\nconstructor; auto.\nQed.\n\nTheorem encode_val_inject:\nforall f v1 v2 chunk,\nVal.inject f v1 v2 ->\nlist_forall2 (memval_inject f) (encode_val chunk v1) (encode_val chunk v2).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_inject\".\nLocal Opaque list_repeat.\nintros. inversion H; subst; simpl; destruct chunk;\nauto using inj_bytes_inject, inj_value_inject, repeat_Undef_inject_self, repeat_Undef_inject_encode_val.\n- destruct Archi.ptr64; auto using inj_value_inject, repeat_Undef_inject_self.\n- destruct Archi.ptr64; auto using inj_value_inject, repeat_Undef_inject_self.\n- unfold encode_val. destruct v2; apply inj_value_inject; auto.\n- unfold encode_val. destruct v2; apply inj_value_inject; auto.\nQed.\n\nDefinition memval_lessdef: memval -> memval -> Prop := memval_inject inject_id.\n\nLemma memval_lessdef_refl:\nforall mv, memval_lessdef mv mv.\nProof. hammer_hook \"Memdata\" \"Memdata.memval_lessdef_refl\".\nred. destruct mv; econstructor. apply val_inject_id. auto.\nQed.\n\n\n\nLemma memval_inject_compose:\nforall f f' v1 v2 v3,\nmemval_inject f v1 v2 -> memval_inject f' v2 v3 ->\nmemval_inject (compose_meminj f f') v1 v3.\nProof. hammer_hook \"Memdata\" \"Memdata.memval_inject_compose\".\nintros. inv H.\ninv H0. constructor.\ninv H0. econstructor.\neapply val_inject_compose; eauto.\nconstructor.\nQed.\n\n\n\nLemma int_of_bytes_append:\nforall l2 l1,\nint_of_bytes (l1 ++ l2) = int_of_bytes l1 + int_of_bytes l2 * two_p (Z.of_nat (length l1) * 8).\nProof. hammer_hook \"Memdata\" \"Memdata.int_of_bytes_append\".\ninduction l1; simpl int_of_bytes; intros.\nsimpl. ring.\nsimpl length. rewrite Nat2Z.inj_succ.\nreplace (Z.succ (Z.of_nat (length l1)) * 8) with (Z.of_nat (length l1) * 8 + 8) by omega.\nrewrite two_p_is_exp. change (two_p 8) with 256. rewrite IHl1. ring.\nomega. omega.\nQed.\n\nLemma int_of_bytes_range:\nforall l, 0 <= int_of_bytes l < two_p (Z.of_nat (length l) * 8).\nProof. hammer_hook \"Memdata\" \"Memdata.int_of_bytes_range\".\ninduction l; intros.\nsimpl. omega.\nsimpl length. rewrite Nat2Z.inj_succ.\nreplace (Z.succ (Z.of_nat (length l)) * 8) with (Z.of_nat (length l) * 8 + 8) by omega.\nrewrite two_p_is_exp. change (two_p 8) with 256.\nsimpl int_of_bytes. generalize (Byte.unsigned_range a).\nchange Byte.modulus with 256. omega.\nomega. omega.\nQed.\n\nLemma length_proj_bytes:\nforall l b, proj_bytes l = Some b -> length b = length l.\nProof. hammer_hook \"Memdata\" \"Memdata.length_proj_bytes\".\ninduction l; simpl; intros.\ninv H; auto.\ndestruct a; try discriminate.\ndestruct (proj_bytes l) eqn:E; inv H.\nsimpl. f_equal. auto.\nQed.\n\nLemma proj_bytes_append:\nforall l2 l1,\nproj_bytes (l1 ++ l2) =\nmatch proj_bytes l1, proj_bytes l2 with\n| Some b1, Some b2 => Some (b1 ++ b2)\n| _, _ => None\nend.\nProof. hammer_hook \"Memdata\" \"Memdata.proj_bytes_append\".\ninduction l1; simpl.\ndestruct (proj_bytes l2); auto.\ndestruct a; auto. rewrite IHl1.\ndestruct (proj_bytes l1); auto. destruct (proj_bytes l2); auto.\nQed.\n\nLemma decode_val_int64:\nforall l1 l2,\nlength l1 = 4%nat -> length l2 = 4%nat -> Archi.ptr64 = false ->\nVal.lessdef\n(decode_val Mint64 (l1 ++ l2))\n(Val.longofwords (decode_val Mint32 (if Archi.big_endian then l1 else l2))\n(decode_val Mint32 (if Archi.big_endian then l2 else l1))).\nProof. hammer_hook \"Memdata\" \"Memdata.decode_val_int64\".\nintros. unfold decode_val. rewrite H1.\nrewrite proj_bytes_append.\ndestruct (proj_bytes l1) as [b1|] eqn:B1; destruct (proj_bytes l2) as [b2|] eqn:B2; auto.\nexploit length_proj_bytes. eexact B1. rewrite H; intro L1.\nexploit length_proj_bytes. eexact B2. rewrite H0; intro L2.\nassert (UR: forall l, length l = 4%nat -> Int.unsigned (Int.repr (int_of_bytes l)) = int_of_bytes l).\nintros. apply Int.unsigned_repr.\ngeneralize (int_of_bytes_range l). rewrite H2.\nchange (two_p (Z.of_nat 4 * 8)) with (Int.max_unsigned + 1).\nomega.\napply Val.lessdef_same.\nunfold decode_int, rev_if_be. destruct Archi.big_endian; rewrite B1; rewrite B2.\n+ rewrite <- (rev_length b1) in L1.\nrewrite <- (rev_length b2) in L2.\nrewrite rev_app_distr.\nset (b1' := rev b1) in *; set (b2' := rev b2) in *.\nunfold Val.longofwords. f_equal. rewrite Int64.ofwords_add. f_equal.\nrewrite !UR by auto. rewrite int_of_bytes_append.\nrewrite L2. change (Z.of_nat 4 * 8) with 32. ring.\n+ unfold Val.longofwords. f_equal. rewrite Int64.ofwords_add. f_equal.\nrewrite !UR by auto. rewrite int_of_bytes_append.\nrewrite L1. change (Z.of_nat 4 * 8) with 32. ring.\nQed.\n\nLemma bytes_of_int_append:\nforall n2 x2 n1 x1,\n0 <= x1 < two_p (Z.of_nat n1 * 8) ->\nbytes_of_int (n1 + n2) (x1 + x2 * two_p (Z.of_nat n1 * 8)) =\nbytes_of_int n1 x1 ++ bytes_of_int n2 x2.\nProof. hammer_hook \"Memdata\" \"Memdata.bytes_of_int_append\".\ninduction n1; intros.\n- simpl in *. f_equal. omega.\n- assert (E: two_p (Z.of_nat (S n1) * 8) = two_p (Z.of_nat n1 * 8) * 256).\n{\nrewrite Nat2Z.inj_succ. change 256 with (two_p 8). rewrite <- two_p_is_exp.\nf_equal. omega. omega. omega.\n}\nrewrite E in *. simpl. f_equal.\napply Byte.eqm_samerepr. exists (x2 * two_p (Z.of_nat n1 * 8)).\nchange Byte.modulus with 256. ring.\nrewrite Z.mul_assoc. rewrite Z_div_plus. apply IHn1.\napply Zdiv_interval_1. omega. apply two_p_gt_ZERO; omega. omega.\nassumption. omega.\nQed.\n\nLemma bytes_of_int64:\nforall i,\nbytes_of_int 8 (Int64.unsigned i) =\nbytes_of_int 4 (Int.unsigned (Int64.loword i)) ++ bytes_of_int 4 (Int.unsigned (Int64.hiword i)).\nProof. hammer_hook \"Memdata\" \"Memdata.bytes_of_int64\".\nintros. transitivity (bytes_of_int (4 + 4) (Int64.unsigned (Int64.ofwords (Int64.hiword i) (Int64.loword i)))).\nf_equal. f_equal. rewrite Int64.ofwords_recompose. auto.\nrewrite Int64.ofwords_add'.\nchange 32 with (Z.of_nat 4 * 8).\nrewrite Z.add_comm. apply bytes_of_int_append. apply Int.unsigned_range.\nQed.\n\nLemma encode_val_int64:\nforall v,\nArchi.ptr64 = false ->\nencode_val Mint64 v =\nencode_val Mint32 (if Archi.big_endian then Val.hiword v else Val.loword v)\n++ encode_val Mint32 (if Archi.big_endian then Val.loword v else Val.hiword v).\nProof. hammer_hook \"Memdata\" \"Memdata.encode_val_int64\".\nintros. unfold encode_val. rewrite H.\ndestruct v; destruct Archi.big_endian eqn:BI; try reflexivity;\nunfold Val.loword, Val.hiword, encode_val.\nunfold inj_bytes. rewrite <- map_app. f_equal.\nunfold encode_int, rev_if_be. rewrite BI. rewrite <- rev_app_distr. f_equal.\napply bytes_of_int64.\nunfold inj_bytes. rewrite <- map_app. f_equal.\nunfold encode_int, rev_if_be. rewrite BI.\napply bytes_of_int64.\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/compcert/Memdata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638776888653}}
{"text": "From refinedc.typing Require Import typing.\nFrom refinedc.project.learning.src.circuit Require Import generated_code.\nFrom refinedc.project.learning.src.circuit Require Import generated_spec.\nSet Default Proof Using \"Type\".\n\n(* Generated from [src/circuit.c]. *)\nSection proof_set_two.\n  Context `{!typeG \u03a3} `{!globalG \u03a3}.\n\n  (* Typing proof for [set_two]. *)\n  Lemma type_set_two :\n    \u22a2 typed_function impl_set_two type_of_set_two.\n  Proof.\n    Open Scope printing_sugar.\n    start_function \"set_two\" ([[[a b] x] p]) => arg_c arg_v.\n    prepare_parameters (a b x p).\n    split_blocks ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)) ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)).\n    - repeat liRStep; liShow.\n      all: print_typesystem_goal \"set_two\" \"#0\".\n    Unshelve. all: li_unshelve_sidecond; sidecond_hook; prepare_sideconditions; normalize_and_simpl_goal; try solve_goal; unsolved_sidecond_hook.\n    all: tauto.\n    all: print_sidecondition_goal \"set_two\".\n    Unshelve. all: try done; try apply: inhabitant; print_remaining_shelved_goal \"set_two\".\n  Qed.\nEnd proof_set_two.\n", "meta": {"author": "afifit", "repo": "circuit_verif", "sha": "5427a1223c5ea7e4a52f909489c45f8e51c4be54", "save_path": "github-repos/coq/afifit-circuit_verif", "path": "github-repos/coq/afifit-circuit_verif/circuit_verif-5427a1223c5ea7e4a52f909489c45f8e51c4be54/src/proofs/circuit/generated_proof_set_two.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.19507638568881358}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import List.\nRequire Import FJ_tactics.\nRequire Import Functors.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import PNames.\nRequire Import EffPure.\nRequire Import EffExcept.\nRequire Import EffReader.\n\nSection ESoundER.\n\n  Variable D : Set -> Set.\n  Context {Fun_D : Functor D}.\n\n  Variable E : Set -> Set -> Set.\n  Context {Fun_F : forall A, Functor (E A)}.\n\n  Variable V : Set -> Set.\n  Context {Fun_V : Functor V}.\n  Context {Sub_StuckValue_V : StuckValue :<: V}.\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  Variable MT : Set -> Set.\n  Context {Fun_MT : Functor MT}.\n  Context {Mon_MT : Monad MT}.\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). (* Evaluation Monad. *)\n  Context {Fun_ME : Functor ME}.\n  Context {Mon_ME : Monad ME}.\n  Context {Environment_ME : Environment ME (list (Names.Value V))}.\n  Context {Exception_ME : Exception ME Datatypes.unit}.\n  Context {Fail_ME : FailMonad ME}.\n  Context {Reasonable_ME : Reasonable_Monad ME}.\n\n  Context {Typeof_E : forall T, FAlgebra TypeofName T (typeofR D MT) (E (DType D))}.\n  Context {WF_MAlg_typeof : WF_MAlgebra Typeof_E}.\n\n  Context {evalM_E : FAlgebra EvalName (Names.Exp (E nat)) (evalMR V ME) (E nat)}.\n\n  Variable EQV_E : forall A B, (eqv_i E A B -> Prop) -> eqv_i E A B -> Prop.\n  Context {funEQV_E : forall A B, iFunctor (EQV_E A B)}.\n\n  Variable TypContext : Set.\n  Context {TypContextCE : ConsExtensionC TypContext}.\n  Context {GammaTypContext : GammaTypContextC D TypContext}.\n  Context {TypContext_GCE : GammaConsExtensionC _ TypContext _ _}.\n\n  Variable WFV : (WFValue_i D V TypContext -> Prop) -> WFValue_i D V TypContext -> Prop.\n  Context {funWFV : iFunctor WFV}.\n\n  Context {WFV_Weaken_WFV : iPAlgebra WFValue_Weaken_Name (WFValue_Weaken_P D V _ WFV) 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  Context {Sub_WFVM_Base_WFVM : Sub_iFunctor (WFValueM_base D V MT ME _ WFV) WFVM}.\n  Context {Sub_WFVM_Except_WFVM : Sub_iFunctor (WFValueM_Except D V MT ME _) WFVM}.\n  Context {Sub_WFVM_Environment_WFVM : Sub_iFunctor (WFValueM_Environment D MT V ME _ WFV) WFVM}.\n  Context {Sub_WFVM_Bot_WFVM : Sub_iFunctor (WFValueM_Bot D V MT ME _) WFVM}.\n\n  Context {EQV_proj1_EQV_E :\n    forall A B, iPAlgebra EQV_proj1_Name (EQV_proj1_P E EQV_E A B) (EQV_E _ _)}.\n  Context {WFV_proj1_b_WFV : iPAlgebra WFV_proj1_b_Name (WFV_proj1_b_P D V _ WFV) WFV}.\n\n  Variable WFV' : (WFValue_i D V (list (Names.DType D)) -> Prop) -> WFValue_i D V (list (Names.DType D)) -> Prop.\n  Context {funWFV' : iFunctor WFV'}.\n  Variable WFVM' : (WFValueM_i D V MT ME (list (Names.DType D)) -> Prop) ->\n    WFValueM_i D V MT ME (list (Names.DType D)) -> Prop.\n  Variable funWFVM' : iFunctor WFVM'.\n\n  Definition Except_Sound_X_P (i : WFValueM_i D V MT ME _) :=\n    forall T gamma''\n      (WF_gamma'' : WF_Environment _ _ _ WFV' (wfvm_S _ _ _ _ _ i) gamma'' (wfvm_S _ _ _ _ _ i)),\n      wfvm_T _ _ _ _ _ i = return_ T ->\n      (local (fun _ => gamma'') (wfvm_v _ _ _ _ _ i) = fail) \\/\n      (exists t, local (fun _ => gamma'') (wfvm_v _ _ _ _ _ i) = throw t) \\/\n      exists v : Value V,\n        local (fun _ => gamma'') (wfvm_v _ _ _ _ _ i) = return_ (M := ME) v /\\\n        WFValueC _ _ _ WFV' (wfvm_S _ _ _ _ _ i) v T.\n\n  Context {WFV_proj1_b_WFV' : iPAlgebra WFV_proj1_b_Name (WFV_proj1_b_P D V _ WFV') WFV'}.\n\n  Inductive Except_Sound_X_Name := except_sound_X_name.\n\n  Global Instance Except_Sound_WFVM_base' :\n    iPAlgebra Except_Sound_X_Name Except_Sound_X_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 := _) (Monad_ME := _);\n      try assumption; unfold Except_Sound_X_P; intros; repeat right.\n    (* WFVM_Return' *)\n    simpl; rewrite local_return; exists v; repeat split; simpl in *; auto.\n    destruct H1 as [mt' mt'_eq]; subst.\n    destruct (MT_eq_dec _ mt') as [[s s_eq] | s_eq]; subst.\n    rewrite fmap_return in H2.\n    apply inj_return in H2; subst.\n    simpl in *; subst; auto.\n    destruct s as [T0 T0_UP']; simpl in *.\n    destruct T0; apply (WFV_proj1_b D V _ WFV' _ _ H0); simpl; auto.\n    failmonaddisc.\n      (* WFVM_Untyped' *)\n    simpl in H0; apply sym_eq in H0.\n    elimtype False; eapply FailMonad_Disc with (M := MT) (a := T) (mb := mt); auto.\n  Qed.\n\n  Context {WFV_Weaken'_WFV : iPAlgebra WFValue_Weaken'_Name (WFValue_Weaken'_P _ _ _ WFV') WFV'}.\n\n  Global Instance Except_Sound_X_WFVM_Environment :\n    iPAlgebra Except_Sound_X_Name Except_Sound_X_P\n    (WFValueM_Environment (TypContextCE := GammaTypContextCE D) D MT V ME _ WFV').\n  Proof.\n    econstructor.\n    unfold iAlgebra; intros; apply ind_alg_WFVM_Environment with (MT := MT)\n      (Fun_MT := Fun_MT) (Mon_MT := Mon_MT) (WFV := WFV')\n      (TypContextCE := GammaTypContextCE D)\n      (GammaTypContext := PNames.GammaTypContext D)\n      (Environment_ME := Environment_ME); try eassumption;\n        unfold Except_Sound_X_P; simpl; intros.\n      (* WFVM_Local *)\n    destruct (H0 gamma'' WF_gamma'' _ _ WF_gamma'' H1) as\n      [eval_fail | [eval_throw | [v [eval_k WF_v_T0]]]].\n    left; generalize ask_query; unfold wbind; intro ask_query'.\n    rewrite local_bind, local_ask, ask_query', <- left_unit; auto.\n    right; left; generalize ask_query; unfold wbind; intro ask_query'.\n    rewrite local_bind, local_ask, ask_query', <- left_unit; auto.\n    right; right; exists v; repeat split; auto.\n    generalize ask_query; unfold wbind; intro ask_query'.\n    rewrite local_bind, local_ask, ask_query', <- left_unit.\n    apply eval_k; auto.\n      (* WFVM_Ask *)\n    rewrite local_bind, local_local; unfold Basics.compose.\n    destruct (H1 _ _ (H0 _ WF_gamma'') (refl_equal _)) as\n      [eval_fail | [[t eval_throw] | [v [eval_m WF_v_T0]]]].\n    left; unfold DType, Value in *|-*; unfold wbind, Env in *|-*;\n      rewrite eval_fail, bind_fail; auto.\n    right; left; exists t; unfold DType, Value in *|-*; unfold wbind, Env in *|-*;\n      rewrite eval_throw, bind_throw; auto.\n    unfold DType, Value in *|-*; unfold wbind, Env in *|-*;\n      rewrite eval_m, <- left_unit; destruct (H2 _ _ (refl_equal _)\n        (WFV_Weaken' _ _ _ WFV' _ WF_v_T0 Sigma) _ _\n        WF_gamma'' H3)\n      as [eval_fail | [[t eval_throw] | [v' [eval_k WF_v'_T0]]]].\n    auto.\n    right; left; eexists _; eauto.\n    repeat right; exists v'; repeat split; auto.\n  Qed.\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, local (fun _ => env) mte = return_ (Monad := Mon_ME) a) \\/\n    (local (fun _ => env) mte = fail) \\/\n    (local (fun _ => env) mte = throw tt)}.\n\n  Variable local_throw : forall (A : Set) f t,\n    local f (throw t) = throw t (A := A).\n  Variable local_catch : forall (A : Set) e h f,\n    local f (catch (A := A) e h) = catch (local f e) (fun t => local f (h t)).\n  Variable catch_fail : forall (A : Set) h,\n    catch (A := A) fail h = fail.\n  Variable throw_neq_fail : forall (A : Set) t,\n    throw t <> fail (A := A).\n\n  Global Instance Except_Sound_X_WFVM_Except :\n    iPAlgebra Except_Sound_X_Name Except_Sound_X_P\n    (WFValueM_Except (TypContextCE := GammaTypContextCE D) D V MT ME _).\n  Proof.\n    econstructor.\n    unfold iAlgebra; intros; apply ind_alg_WFVM_Except with (Fail_MT := Fail_MT)\n      (TypContextCE := GammaTypContextCE D)\n      (Exception_ME := Exception_ME) (eq_DType_DT := eq_DType_DT);\n      try assumption; unfold Except_Sound_X_P; simpl; intros.\n      (* throw case *)\n    simpl; right; left; exists tt; apply local_throw.\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 H2.\n    caseEq (eq_DType _ (proj1_sig T') T''); rewrite H3 in H2.\n    destruct (H0 _ _ WF_gamma'' H2) as\n      [eval_fail | [[t eval_throw] | [v [eval_k WF_v_T0]]]].\n    rewrite local_bind, local_catch.\n    destruct (ME_eq_dec' _ e' gamma'') as [[v'' e'_eq] | [e'_eq | e'_eq]];\n      unfold Env in *|-*; rewrite e'_eq in *|-*.\n    left; rewrite catch_return, <- left_unit;\n      rewrite local_bind, e'_eq, <- left_unit in eval_fail; auto.\n    rewrite catch_fail, bind_fail; auto.\n    rewrite local_bind, e'_eq, bind_throw in eval_fail;\n      elimtype False; eapply throw_neq_fail; eauto.\n    rewrite local_bind, local_catch.\n    destruct (ME_eq_dec' _ e' gamma'') as [[v'' e'_eq] | [e'_eq | e'_eq]];\n      unfold Env in *|-*; rewrite e'_eq in *|-*.\n    right; left; rewrite catch_return, <- left_unit;\n      rewrite local_bind, e'_eq, <- left_unit in eval_throw; eauto.\n    rewrite local_bind, e'_eq, bind_fail in eval_throw;\n      elimtype False; eapply throw_neq_fail; eauto.\n    rewrite catch_throw', <- local_bind.\n    destruct (MT_eq_dec _ kT') as [[c kT'_eq] | kT'_eq]; subst.\n    repeat rewrite <- left_unit in H1, H2.\n    destruct (MT_eq_dec _ (kT c T'')) as [[d kTcT''_eq] | kTcT''_eq].\n    destruct (H1 tt _ (refl_equal _) _ _ WF_gamma'' kTcT''_eq) as\n      [eval_fail | [[t' eval_throw'] | [v [eval_k WF_v_T0]]]];\n      eauto.\n    repeat right; exists v; repeat split; eauto.\n    destruct T; apply (WFV_proj1_b D V _ WFV' _ _ WF_v_T0); simpl; auto.\n    generalize (kt_eq _ _ (eq_DType_eq _ _ _ H3)).\n      repeat rewrite <- left_unit;\n      rewrite H2, kTcT''_eq; simpl;\n      repeat rewrite fmap_return;\n      intros x_eq; apply inj_return in x_eq; auto.\n    elimtype False; generalize (kt_eq _ _ (eq_DType_eq _ _ _ H3));\n      repeat rewrite <- left_unit; rewrite H2, kTcT''_eq; simpl;\n      rewrite fmap_return; rewrite fmap_fail; intros x_eq.\n    failmonaddisc.\n    failmonaddisc.\n    rewrite local_bind, local_catch.\n    destruct (ME_eq_dec' _ e' gamma'') as [[v'' e'_eq] | [e'_eq | e'_eq]];\n      unfold Env in *|-*; rewrite e'_eq in *|-*.\n    repeat right; rewrite catch_return, <- left_unit;\n      rewrite local_bind, e'_eq, <- left_unit in eval_k; eauto.\n    rewrite catch_fail, bind_fail; auto.\n    rewrite local_bind, e'_eq, bind_throw in eval_k.\n    elimtype False; eapply Exception_Disc with (M := ME) (a := v) (mb := return_ tt);\n    eauto; unfold wbind; rewrite <- left_unit; eauto.\n    destruct (MT_eq_dec _ kT') as [[c kT'_eq] | kT'_eq]; subst; failmonaddisc.\n    destruct (MT_eq_dec _ kT') as [[c kT'_eq] | kT'_eq]; subst; failmonaddisc.\n    destruct (MT_eq_dec _ kT') as [[c kT'_eq] | kT'_eq]; subst; failmonaddisc.\n  Qed.\n\n  Context {FailEnvM : FailEnvironmentMonad (Env (Value V)) ME}.\n\n  Global Instance Except_Sound_X_WFVM_Bot :\n    iPAlgebra Except_Sound_X_Name Except_Sound_X_P (WFValueM_Bot D V MT ME _).\n  Proof.\n    econstructor.\n    unfold iAlgebra; intros; eapply ind_alg_WFVM_Bot;\n      try eassumption; unfold Except_Sound_X_P; simpl; intros.\n    (* WFVM_fail *)\n    left; rewrite local_fail; auto.\n  Qed.\n\n  Context {soundness_X'_alg :\n    forall eval_rec,\n      iPAlgebra soundness_X'_Name\n      (soundness_X'_P D V E MT ME _ EQV_E WFVM' (fun e => typeof _ _ MT (proj1_sig e)) eval_rec\n        (f_algebra (FAlgebra := Typeof_E _))\n        (f_algebra (FAlgebra := evalM_E))) (EQV_E _ _)}.\n  Context {Except_Sound_X_WFVM : iPAlgebra Except_Sound_X_Name Except_Sound_X_P WFVM'}.\n\n  Context {Sub_WFVM_Bot_WFVM' : Sub_iFunctor (WFValueM_Bot _ _ _ _ (list (DType D))) WFVM'}.\n\n  Theorem Except_Sound_X :\n    forall (n : nat) Sigma gamma gamma' gamma'' e' e'',\n      E_eqvC E 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_gamma'' : WF_Environment _ _ _ WFV' Sigma gamma'' gamma)\n      (WF_gamma2 : List.length gamma = List.length gamma')\n      (WF_gamma' : forall n b, lookup gamma' n = Some b -> b = n)\n      (WF_Sigma : Gamma D Sigma = gamma) (T : DType D),\n      typeof D (E (DType D)) MT (Typeof_E := Typeof_E) (proj1_sig e') = return_ T ->\n      (local (M := ME) (fun _ => gamma'') (bevalM V E ME n e'') = fail) \\/\n      (exists t, local (M := ME) (fun _ => gamma'') (bevalM V E ME n e'') = throw t) \\/\n        exists v : Value V,\n          local (M := ME) (fun _ => gamma'') (bevalM V E ME n e'') =\n          return_ (M := ME) v /\\ WFValueC _ _ _ WFV' Sigma v T.\n  Proof.\n    intros.\n    intros; eapply (ifold_ WFVM' _ (ip_algebra (iPAlgebra := Except_Sound_X_WFVM))\n      _ (eval_soundness_X' D V E MT ME _ EQV_E WFVM' n _ _ _ _ H Sigma WF_gamma WF_gamma2 WF_gamma' WF_Sigma));\n    simpl in *|-*; unfold DType in *|-*; eauto;\n    simpl in H0; eauto.\n    unfold id in *|-*; subst; eauto.\n  Qed.\n\nEnd ESoundER.\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/ESoundER.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "Require Import SimrelDefinition.\nRequire Import SimrelCategory.\nRequire Import AbstractDataType.\nRequire SimrelInvariant.\n\n(** This module originated as a variant of [SimrelInvariant] to account for the\n  fact that primitives should preserve the kernel mode flag of the abstract\n  data. *)\n\n(** ** Invariants *)\n\nSection KERNELMODE.\n  Context `{Hmem: BaseMemoryModel}.\n\n  (** *** Definition *)\n\n  Definition km_world :=\n    unit.\n    (* sig (fun x => forall b, block_is_global b -> Pos.lt b x). *)\n\n  Definition kernel_mode (D: certikosdata) (d: D) :=\n    ikern d = true /\\ ihost d = true.\n  \n  Program Definition km_ops (D: certikosdata): simrel_components D D :=\n    {|\n      simrel_world := km_world;\n      simrel_acc := {| le := fun _ _ => True |};\n      simrel_new_glbl := nil;\n      simrel_undef_matches_values_bool := false;\n      simrel_undef_matches_block p b := False;\n      match_mem w m m' := m = m' /\\ kernel_mode D (snd m);\n      simrel_meminj w := inject_id\n    |}.\n\n  (** *** Properties *)\n\n  Global Instance match_mem_corefl D p:\n    Coreflexive (match_mem (km_ops D) p).\n  Proof.\n    intros m m' H.\n    destruct H. \n    assumption.\n  Qed.\n\n  Global Instance match_val_km_refl D p:\n    Reflexive (match_val (km_ops D) p).\n  Proof.\n    red. intro v; subst.\n    destruct v; try constructor.\n    replace i with (Ptrofs.add i Ptrofs.zero) at 2 by apply Ptrofs.add_zero.\n    econstructor; eauto.\n  Qed.\n\n  Global Instance match_val_km_corefl D p:\n    Coreflexive (match_val (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv; try constructor; try now (discriminate H || destruct H).\n    inv H. simpl in H1. unfold inject_id in H1.\n    inv H1. rewrite Ptrofs.add_zero. reflexivity.\n  Qed.\n\n  Global Instance match_ptr_km_corefl D p:\n    Coreflexive (match_ptr (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv; try constructor; try now (discriminate H || destruct H).\n    inv H. rewrite Z.add_0_r. reflexivity.\n  Qed.\n\n  Global Instance match_ptrbits_km_corefl D p:\n    Coreflexive (match_ptrbits (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv. simpl in H.\n    unfold inject_id in H. inv H.\n    rewrite Ptrofs.add_zero. reflexivity.\n  Qed.\n\n\n  Global Instance match_ptrrange_km_corefl D p:\n    Coreflexive (match_ptrrange (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv.\n    apply coreflexivity in H. inv H. reflexivity. \n  Qed.\n\n  Global Instance match_block_km_corefl D p:\n    Coreflexive (match_block (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv. simpl in H.\n    unfold inject_id in H. inv H.\n    reflexivity.\n  Qed.\n\n\n  Global Instance match_vals_km_corefl D p:\n    Coreflexive (list_rel (match_val (km_ops D) p)).\n  Proof.\n    intros vs1 vs2 Hvs.\n    induction Hvs; try constructor.\n    f_equal; eauto.\n    eapply match_val_km_corefl; eauto.\n  Qed.\n\n  Global Instance match_memval_km_corefl D p:\n    Coreflexive (match_memval (km_ops D) p).\n  Proof.\n    intros v1 v2 Hv.\n    destruct Hv; try constructor; try now (discriminate H || destruct H).\n    f_equal; rauto.\n  Qed.\n\n  Global Instance match_memval_km_refl D p:\n    Reflexive (match_memval (km_ops D) p).\n  Proof.\n    red. intro v; subst.\n    destruct v; try constructor.\n    reflexivity.\n  Qed.\n\n  Global Instance match_memvals_km_refl D p:\n    Reflexive (list_rel (match_memval (km_ops D) p)).\n  Proof.\n    red.\n    induction x; simpl; intros; constructor; reflexivity.\n  Qed.\n\n  Global Instance match_memvals_km_corefl D p:\n    Coreflexive (list_rel (match_memval (km_ops D) p)).\n  Proof.\n    intros vs1 vs2 Hvs.\n    induction Hvs; try constructor.\n    f_equal; eauto.\n    eapply match_memval_km_corefl; eauto.\n  Qed.\n\n  Lemma km_inject_neutral_match_val D p v :\n    Val.inject inject_id v v <->\n    match_val (km_ops D) p v v.\n  Proof.\n    split; intros Hv;\n    inversion Hv; clear Hv; try constructor.\n    {\n      pattern ofs1 at 2.\n      rewrite H3.\n      constructor.\n      assumption.\n    }\n    subst.\n    inversion H1.\n    rewrite H4 at 1.\n    econstructor; eauto.\n  Qed.\n\n  Lemma km_inject_neutral_match_vals D p l:\n    Val.inject_list inject_id l l <->\n    list_rel (match_val (km_ops D) p) l l .\n  Proof.\n    split; intros Hl; induction l; inversion Hl; subst; constructor; auto.\n    + rewrite <- km_inject_neutral_match_val. simpl. assumption.\n    + rewrite <- km_inject_neutral_match_val in *. simpl in *. assumption.\n  Qed.\n\n  Lemma km_inject_neutral_match_memval D p v:\n    memval_inject inject_id v v <->\n    match_memval (km_ops D) p v v.\n  Proof.\n    split; intros Hv;\n    inversion Hv; clear Hv; try constructor.\n    - apply km_inject_neutral_match_val.\n      assumption.\n    - apply km_inject_neutral_match_val in H1.\n      assumption.\n  Qed.\n\n  Lemma km_inject_neutral_match_memvals D p vs:\n    list_forall2 (memval_inject inject_id) vs vs <->\n    list_rel (match_memval (km_ops D) p) vs vs.\n  Proof.\n    generalize (eq_refl vs).\n    generalize vs at 2 4 6.\n    revert vs.\n    intros vs1 vs2 Hvseq.\n    split.\n    {\n      intro Hvs.\n      revert Hvseq.\n      induction Hvs.\n      - constructor.\n      - intros Heq.\n        constructor.\n        + inversion Heq.\n          eapply km_inject_neutral_match_memval.\n          congruence.\n        + eapply IHHvs.\n          congruence.\n    }\n    intro Hvs.\n    revert Hvseq.\n    induction Hvs.\n    - constructor.\n    - intros Heq.\n      constructor.\n      + inversion Heq.\n        rewrite km_inject_neutral_match_memval with (D := D) (p:=p).\n        congruence.\n      + eapply IHHvs.\n        congruence.\n  Qed.\n\n  Lemma km_match_val_inject_neutral D p v1 v2:\n    match_val (km_ops D) p v1 v2 ->\n    Val.inject inject_id v1 v2.\n  Proof.\n    intros Hv.\n    inversion Hv; subst; try now constructor.\n    inversion H; subst.\n    econstructor; eauto.\n  Qed.\n\n  Lemma km_match_memval_inject_neutral D p v1 v2:\n    match_memval (km_ops D) p v1 v2 ->\n    memval_inject inject_id v1 v2.\n  Proof.\n    intros Hv.\n    inversion Hv; subst; constructor.\n    eapply km_match_val_inject_neutral; eauto.\n  Qed.\n\n  Lemma km_match_memvals_inject_neutral D p v1 v2:\n    list_rel (match_memval (km_ops D) p) v1 v2 ->\n    list_forall2 (memval_inject inject_id) v1 v2.\n  Proof.\n    intros Hv.\n    induction Hv; constructor; eauto.\n    eapply km_match_memval_inject_neutral; eauto.\n  Qed.\n\n  (** *** Initial states *)\n\n  (** To prove that initial memories satisfy the invariant, we first\n    characterize the construction of initial memories with abstract\n    data. *)\n\n(*  Section WITHDATA.\n    Context {D: layerdata}.\n\n    Lemma store_zeros_with_data:\n      forall m b o n (d: D),\n        store_zeros (m, d) b o n =\n        match store_zeros m b o n with\n          | Some m' => Some (m', d)\n          | None => None\n        end.\n    Proof.\n      intros.\n      functional induction (store_zeros m b o n); intros.\n      * rewrite store_zeros_equation.\n        rewrite e.\n        reflexivity.\n      * rewrite <- IHo0; clear IHo0.\n        rewrite store_zeros_equation.\n        rewrite e.\n        lift_unfold.\n        rewrite e0.\n        reflexivity.\n      * rewrite store_zeros_equation.\n        rewrite e.\n        lift_unfold.\n        rewrite e0.\n        reflexivity.\n    Qed.\n\n    Lemma store_init_data_with_data:\n      forall {F V: Type} (ge: _ F V) m b p a (d: D),\n        Genv.store_init_data ge (m, d) b p a =\n        match Genv.store_init_data ge m b p a with\n          | Some m' => Some (m', d)\n          | None => None\n        end.\n    Proof.\n      intros.\n      destruct a; simpl; try reflexivity.\n      destruct (Genv.find_symbol ge i); reflexivity.\n    Qed.\n\n    Lemma store_init_data_list_with_data:\n      forall {F V: Type} (ge: _ F V) l m b p (d: D),\n        Genv.store_init_data_list ge (m, d) b p l =\n        match Genv.store_init_data_list ge m b p l with\n          | Some m' => Some (m', d)\n          | None => None\n        end.\n    Proof.\n      induction l; simpl; try reflexivity.\n      intros.\n      rewrite store_init_data_with_data.\n      destruct (Genv.store_init_data ge m b p a); try reflexivity.\n      eauto.\n    Qed.\n\n    Lemma alloc_global_with_data:\n      forall {F V} (ge: _ F V),\n        forall m ig (d: D),\n          Genv.alloc_global ge (m, d) ig =\n          match Genv.alloc_global ge m ig with\n            | Some m' => Some (m', d)\n            | None => None\n          end.\n    Proof.\n      unfold Genv.alloc_global. intros.\n      destruct ig as [? [ [ | ] | ]].\n      * (* function *)\n        lift_unfold.\n        destruct (Mem.alloc m 0 1).\n        reflexivity.\n      * (* variable *)\n        lift_unfold.\n        destruct (Mem.alloc m 0 (init_data_list_size (gvar_init v))).\n        unfold set; simpl.\n        rewrite store_zeros_with_data.\n        destruct (store_zeros m0 b 0 (init_data_list_size (gvar_init v))); try reflexivity.\n        rewrite store_init_data_list_with_data.\n        destruct (Genv.store_init_data_list ge m1 b 0 (gvar_init v)); reflexivity.\n      * (* none *)\n        lift_unfold.\n        destruct (Mem.alloc m 0 0); reflexivity.\n    Qed.\n\n    Lemma alloc_globals_with_data:\n      forall {F V} (ge: _ F V),\n        forall l m (d: D),\n          Genv.alloc_globals ge (m, d) l =\n          match Genv.alloc_globals ge m l with\n            | Some m' => Some (m', d)\n            | None => None\n          end.\n    Proof.\n      induction l; simpl; try reflexivity.\n      intros.\n      rewrite alloc_global_with_data.\n      destruct (Genv.alloc_global ge m a); try reflexivity.\n      eauto.\n    Qed.\n\n    Theorem init_mem_with_data:\n      forall {F V} (p: _ F V),\n        Genv.init_mem (mem := mwd D) p =\n        match Genv.init_mem (mem := mem) p with\n          | Some m' => Some (m', init_data)\n          | None => None\n        end.\n    Proof.\n      intros.\n      unfold Genv.init_mem.\n      simpl.\n      apply alloc_globals_with_data.\n    Qed.\n  End WITHDATA.\n *)\n  \n(** XXX: mettre au bon endroit. *)\nInstance:\n  Related Pos.lt Pos.le subrel.\nProof.\n  intros x y Hxy.\n  apply Pos.le_lteq.\n  eauto.\nQed.\n\n\nLtac coreflexivity H :=\n  let Heq := fresh in\n  pose proof (coreflexivity _ _ H) as Heq; inv Heq.\n\n\n  Global Instance km_prf D:\n    SimulationRelation (km_ops D).\n  Proof.\n    split.\n    - (* carrier preorder *)\n      split; simpl; eauto.\n    - (* simrel_undef_matches_block increases with carrier *)\n      simpl. solve_monotonic.\n    - (* match_block increases with carrier *)\n      simpl; unfold RelCompFun.\n      intros p1 p2 Hp.\n      red.\n      intro b.\n      unfold inject_id. repeat constructor.\n    - (* undef_matches_values implies undef_matches_block *)\n      discriminate.\n    - (* undef_matches_block implies undef_matches_values *)\n      simpl; tauto.\n    - (* undef_match_block for non-injective match_block *)\n      simpl.\n      intros.\n      coreflexivity H0.\n      coreflexivity H1.\n      congruence.\n    - (* undef_match_block for non weakly valid pointers *)\n      intros.\n      coreflexivity H1.\n      coreflexivity H.\n      revert H0 H2; simpl. \n      unfold Mem.weak_valid_pointer; simpl.\n      lift_unfold.\n      congruence.\n    - (* undef_match_block for invalid pointers *)\n      intros.\n      coreflexivity H1.\n      coreflexivity H.\n      revert H0 H2; simpl. \n      unfold Mem.weak_valid_pointer; simpl.\n      lift_unfold.\n      congruence.\n\n    - (* global blocks related to themselves *)\n      intros p b Hb.\n      destruct p as [thr Hthr].\n      red. \n      unfold match_block_sameofs.\n      simpl.\n      unfold inject_id.\n      auto.\n\n    - (* global blocks related to themselves, reciprocal *)\n      intros p b1 b2 Hb2 [delta Hinj].\n      simpl in Hinj.\n      unfold inject_id in Hinj.\n      congruence.\n\n    - (* [Genv.init_mem] *)\n      intros.\n      intros p1 p2 Hp.\n      assert\n        ((option_le ((rexists w, match_mem (simrel_id (D:=D)) w) /\\\n                     (req glob_threshold @@ Mem.nextblock)))\n           (Genv.init_mem p1)\n           (Genv.init_mem p2)) as Hm.\n      {\n        eapply genv_init_mem_simrel_withnextblock; eauto.\n        + apply SimrelCategory.simrel_id_init_mem.\n        + intros x y [H _].\n          exists tt.\n          assumption.\n      }\n      pose proof (@SimrelInvariant.init_mem_with_data _ D F1 V p1).\n      destruct (Genv.init_mem (mem:=mwd D) p1) as [m1|] eqn:Hinit_mem; [|constructor].\n      destruct (Genv.init_mem (mem:=mem) p1) as [m|] eqn:Hm1'; try discriminate.\n      inversion Hm as [ | xm1 xm2 Hmeq]; clear Hm; subst.\n      constructor.\n      destruct Hmeq as [[[] Hmeq] Hmnb].\n      simpl in Hmeq; subst.\n      inversion H; clear H; subst.\n      assert (Hw: forall b, block_is_global b -> (b < Mem.nextblock m)%positive).\n      {\n        intros b Hb.\n        red in Hmnb.\n        lift_unfold.\n        destruct Hmnb.\n        exact Hb.\n      }\n      exists tt.\n      split; auto.\n      simpl.\n      red; split; reflexivity.\n\n    - (* [Mem.alloc] *)\n      intros p m m1 Hm ofs sz.\n      coreflexivity Hm.\n      exists tt; split; auto. \n      + simpl; auto.\n      + split; [ constructor | ] ; simpl.\n        * lift_unfold.\n          destruct Hm; subst.\n          f_equal.\n        * lift_unfold. destruct Hm; subst.\n          destruct @Mem.alloc. simpl. auto.\n        * lift_unfold.\n          destruct Hm; subst.\n          destruct @Mem.alloc. simpl. auto.\n          unfold match_block_sameofs.\n          simpl.\n          unfold inject_id.\n          congruence.\n\n    - (* [Mem.free] *)\n      intros p m1 m2 Hm [[b1 lo1] hi1] [[b2 lo2] hi2] Hb.\n      coreflexivity Hm.\n      coreflexivity Hb.\n      simpl in *.\n      lift_unfold.\n      destruct (Mem.free _ _ _ _) as [m'|] eqn:Hm'; constructor.\n      exists tt.\n      split; auto.\n      split; auto.\n      lift_simpl. intuition.\n      \n    - (* [Mem.load] *)\n      intros p chunk m1 m2 Hm [b1 ofs1] [b2 ofs2] Hb.\n      coreflexivity Hm.\n      coreflexivity Hb.\n      simpl in *.\n      lift_unfold.\n      destruct (@Mem.load) as [v|] eqn:Hv; constructor.\n      reflexivity.\n\n    - (* [Mem.store] *)\n      intros p chunk m1 m2 Hm [b1 ofs1] [b2 ofs2] Hb v1 v2 Hv.\n      coreflexivity Hb.\n      coreflexivity Hv.\n      coreflexivity Hm.\n      destruct (uncurry _ _ _) eqn:?; constructor.\n      exists tt; simpl; split; auto.\n      split; auto.\n      simpl in Hm; intuition.\n      unfold uncurry in Heqy.\n      lift_unfold. intuition congruence.\n\n    - (* [Mem.loadbytes] *)\n      intros p m1 m2 Hm [b1 ofs1] [b2 ofs2] Hb len.\n      coreflexivity Hm.\n      coreflexivity Hb. \n      simpl in *.\n      lift_unfold.\n      destruct (Mem.loadbytes _ _ _ _) as [v|] eqn:Hv; constructor.\n      reflexivity.\n\n    - (* [Mem.storebytes] *)\n      intros p m1 m2 Hm [b1 ofs1] [b2 ofs2] Hb vs1 vs2 Hvs.\n      coreflexivity Hm.\n      coreflexivity Hb.\n      coreflexivity Hvs. \n      simpl in *.\n      lift_unfold.\n      destruct (Mem.storebytes _ _ _ _) as [m'|] eqn:Hm'; constructor.\n      split; split; split; eauto.\n      lift_simpl. intuition.\n\n    - (* [Mem.perm] *)\n      intros p m1 m2 Hm [b1 ofs1] [b2 ofs2] Hb k perm.\n      coreflexivity Hm.\n      coreflexivity Hb.\n      reflexivity.\n\n    - (* [Mem.valid_block] *)\n      intros p m1 m2 Hm b1 b2 Hb.\n      coreflexivity Hm.\n      coreflexivity Hb. \n      simpl in *.\n      unfold Mem.valid_block. simpl. lift_unfold.\n      tauto.\n\n    - (* [Mem.different_pointers_inject] *)\n      intros p m m' b1 ofs1 b2 ofs2 b1' delta1 b2' delta2 H H0 H1 H2 H3 H4.\n      simpl in H3, H4.\n      unfold inject_id in H3, H4.\n      inv H3. inv H4.\n      tauto.\n\n    - (* [Mem.weak_valid_pointer_inject_val] *)\n      intros.\n      coreflexivity H.\n      coreflexivity H1.\n      assumption.\n\n    - (* weak_valid_pointer_address_inject_weak *)\n      intros p m1 m2 b1 b2 delta H H0.\n      coreflexivity H. \n      simpl in H0.\n      unfold inject_id in H0.\n      inv H0.\n      exists 0.\n      intros ofs1 WVP.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    - (* [Mem.address_inject] *)\n      intros p m1 m2 b1 ofs1 b2 delta pe H H0 H1.\n      simpl in H1.\n      unfold inject_id in H1.\n      inv H1.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    - (* [Mem.aligned_area_inject] *)\n      intros p m m' b ofs al sz b' delta H H0 H1 H2 H3 H4 H5.\n      simpl in H5.\n      unfold inject_id in H5.\n      inv H5.\n      rewrite Z.add_0_r.\n      assumption.\n\n    - (* [Mem.disjoint_or_equal_inject] *)\n      intros p m m' b1 b1' delta1 b2 b2' delta2 ofs1 ofs2 sz H H0 H1 H2 H3 H4 H5.\n      simpl in H0, H1.\n      unfold inject_id in H0, H1.\n      inv H0; inv H1.\n      intuition omega.\n  Qed.\n\n  Definition km {D: certikosdata}: simrel D D :=\n    {|\n      simrel_ops := km_ops D\n    |}.\nEnd KERNELMODE.\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/SimrelKernelMode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.19507638209139166}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\n\nInductive insn :=\n| Block (code : list insn)\n| Arg\n| Self\n| Deref (off : nat)\n| Call\n| MkConstr (tag : nat) (nargs : nat)\n| Switch (cases : list (list insn))\n| MkClose (f : function_name) (nfree : nat)\n| OpaqueOp (op : opaque_oper_name) (nargs : nat)\n.\n\nDefinition env := list (list insn).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    stack : list value\n}.\n\nDefinition push f v :=\n    Frame (arg f) (self f) (v :: stack f).\n\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| Ktail (code : list insn) (stk : list value) (k : 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| SBlock : forall code is f k,\n        sstep E (Run (Block code :: is) f k)\n                (Run code (Frame (arg f) (self f) []) (Ktail is (stack f) k))\n\n| SArg : forall f k,\n        stack f = [] ->\n        sstep E (Run [Arg] f k)\n                (Run [] (push f (arg f)) k)\n| SSelf : forall f k,\n        stack f = [] ->\n        sstep E (Run [Self] f k)\n                (Run [] (push f (self f)) k)\n\n| SDerefinateConstr : forall off f k  tag args v,\n        stack f = [Constr tag args] ->\n        nth_error args off = Some v ->\n        sstep E (Run [Deref off] f k)\n                (Run [] (pop_push f 1 v) k)\n| SDerefinateClose : forall off f k  fname free v,\n        stack f = [Close fname free] ->\n        nth_error free off = Some v ->\n        sstep E (Run [Deref off] f k)\n                (Run [] (pop_push f 1 v) k)\n\n| SConstrDone : forall tag nargs f k,\n        length (stack f) = nargs ->\n        sstep E (Run [MkConstr tag nargs] f k)\n                (Run [] (pop_push f nargs (Constr tag (rev (stack f)))) k)\n| SCloseDone : forall fname nfree f k,\n        length (stack f) = nfree ->\n        sstep E (Run [MkClose fname nfree] f k)\n                (Run [] (pop_push f nfree (Close fname (rev (stack f)))) k)\n| SOpaqueOpDone : forall op nargs f k v,\n        length (stack f) = nargs ->\n        opaque_oper_denote_higher op (rev (stack f)) = Some v ->\n        sstep E (Run [OpaqueOp op nargs] f k)\n                (Run [] (pop_push f nargs v) k)\n\n| SMakeCall : forall f k  fname free body argv,\n        stack f = [argv; Close fname free] ->\n        nth_error E fname = Some body ->\n        sstep E (Run [Call] f k)\n                (Run body (Frame argv (Close fname free) [])\n                    (Kret [] (pop f 2) k))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall cases f k  tag args case,\n        stack f = [] ->\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run [Switch cases] f k)\n                (Run case f (Kswitch [] (stack f) k))\n\n| SContTail : forall code f stk k v,\n        stack f = [v] ->\n        sstep E (Run [] f (Ktail code stk k))\n                (Run code (Frame (arg f) (self f) (v :: stk)) k)\n| SContRet : forall code f f' k v,\n        stack f = [v] ->\n        sstep E (Run [] f (Kret code f' k))\n                (Run code (push f' v) 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 v,\n        stack f = [v] ->\n        sstep E (Run [] f Kstop)\n                (Stop v)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\n\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 * Mutual recursion/induction schemes for expr\n *)\n\nDefinition insn_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HBlock :   forall code, Pl code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Pll cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (i : insn) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        let fix go_list_list iss :=\n            match iss as iss_ return Pll iss_ with\n            | [] => Hnil2\n            | is :: iss => Hcons2 is iss (go_list is) (go_list_list iss)\n            end in\n        match i as i_ return P i_ with\n        | Block code => HBlock code (go_list code)\n        | Arg => HArg\n        | Self => HSelf\n        | Deref off => HDeref off\n        | Call => HCall\n        | MkConstr tag nargs => HConstr tag nargs\n        | Switch cases => HSwitch cases (go_list_list cases)\n        | MkClose fname nfree => HClose fname nfree\n        | OpaqueOp op nargs => HOpaqueOp op nargs\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition insn_ind' (P : insn -> Prop)\n    (HBlock :   forall code, Forall P code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Forall (Forall P) cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (i : insn) : P i :=\n    ltac:(refine (@insn_rect_mut P (Forall P) (Forall (Forall P))\n        HBlock HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp _ _ _ _ i); eauto).\n\nDefinition insn_list_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HBlock :   forall code, Pl code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Pll cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (is : list insn) : Pl is :=\n    let go := insn_rect_mut P Pl Pll\n            HBlock HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp\n            Hnil Hcons Hnil2 Hcons2 in\n    let fix go_list is :=\n        match is as is_ return Pl is_ with\n        | [] => Hnil\n        | i :: is => Hcons i is (go i) (go_list is)\n        end in go_list is.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/StackCont3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}}
{"text": "(** CompCert transform_program* and LayerLib make_program. *)\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.AST.\nRequire Export liblayers.logic.Structures.\nRequire Export liblayers.logic.OptionOrders.\nRequire Export liblayers.lib.OptionMonad.\nRequire Export liblayers.compcertx.ErrorMonad.\nRequire Import Coq.Classes.RelationPairs.\nRequire Export liblayers.compcertx.CompcertStructures.\nRequire Import liblayers.compcertx.MakeProgramSpec.\nRequire Import liblayers.logic.GlobalVars.\n\nArguments mkglobvar {_} _ _ _ _.\n\nInductive globvar_rel\n          {V_prog_from V_prog_to: Type} (R: rel V_prog_from V_prog_to):\n  rel (globvar V_prog_from) (globvar V_prog_to)\n  :=\n    globvar_rel_intro:\n      Monotonic\n        mkglobvar\n        (R ++> eq ++> eq ++> eq ++> globvar_rel R).\n\n(* transform_program and program_rel *)\n\nSection TRANSFORM_PROGRAM.\n\n  Local Existing Instance globvar_rel_intro.\n\n  Context {F_prog_from V_prog_from F_prog_to V_prog_to: Type}.\n\n  Variables transf_F_prog: F_prog_from -> res F_prog_to.\n  Variables transf_V_prog: V_prog_from -> res V_prog_to.\n\n  Let RF_prog := fun _: ident => option_rel (fun f_from f_to => transf_F_prog f_from = OK f_to).\n  Let RV_prog := fun _: ident => option_rel (globvar_rel (fun v_from v_to => transf_V_prog v_from = OK v_to)).\n\n  Section GLOBDEFS_REL.\n\n  Let globdefs_rel := list_rel ((eq (A := ident)) * rforall i, globdef_rel (RF_prog) (RV_prog) i)%rel.\n\n  Lemma transf_globdefs_rel_recip l_from l_to:\n      globdefs_rel l_from l_to ->\n      transf_globdefs (fun _ => transf_F_prog) (fun _ => transf_V_prog) l_from = OK l_to.\n  Proof.\n    induction 1; simpl; auto.\n    inversion_clear H; subst.\n    destruct x; destruct y; simpl in * |- * ; subst.\n    specialize (H2 i0).\n    inversion_clear H2; subst.\n    rewrite IHlist_rel; clear IHlist_rel; simpl.\n    unfold Monad.bind in *;\n    destruct o; destruct o0; simpl in * |- * ; auto.\n    {\n      destruct g; destruct g0; (try now inversion H); (try now inversion H1);\n      unfold fun_of_globdef, var_of_globdef in *;\n      simpl in *.\n      {\n        inversion_clear H; subst.\n        rewrite H2.\n        reflexivity.\n      }\n      inversion_clear H1; subst.\n      inversion_clear H2; subst.\n      unfold transf_globvar; simpl.\n      unfold bind; simpl.\n      rewrite H1.\n      reflexivity.\n    }\n    {\n      destruct g; (try now inversion H); (try now inversion H1).\n    }\n    destruct g; (try now inversion H); (try now inversion H1).\n  Qed.    \n\n  Lemma globdefs_rel_flip_impl:\n    forall j,\n      subrel\n        (CompcertStructures.globdefs_rel (fun i => flip (RF_prog i)) (fun i => flip (RV_prog i)) j)\n        (flip globdefs_rel).\n  Proof.\n    unfold flip, globdefs_rel.\n    red.\n    induction 1.\n    { constructor. }\n    apply app_rel; auto.\n    constructor.\n    {\n      constructor; auto.\n      red.\n      intros c.\n      inversion H0.\n      constructor; auto.\n    }\n    constructor.\n  Qed.\n\n  End GLOBDEFS_REL.\n\n  Lemma transform_partial_program2_recip_flip p:\n    forall pto,\n      program_rel (fun j => flip (RF_prog j)) (fun j => flip (RV_prog j)) pto p ->\n      transform_partial_program2 (fun _ => transf_F_prog) (fun _ => transf_V_prog) p = OK pto.\n  Proof.\n    intros pto H.    \n    inversion H; subst.\n    inversion program_rel_upto_glob_threshold; subst.    \n    unfold transform_partial_program2.\n    simpl.\n    apply globdefs_rel_flip_impl in H0.\n    apply transf_globdefs_rel_recip in H0.\n    rewrite H0.\n    reflexivity.\n  Qed.\n\n  Context\n    {ld_from Fm_from Vm_from module_from : Type}\n    {primsem_from layer_from : ld_from -> Type}\n    {gvar_from_ops: GlobalVarsOps (globvar Vm_from)}\n    {module_from_ops : ModuleOps ident Fm_from (globvar Vm_from) module_from}\n    {primsem_from_ops : PrimitiveOps primsem_from}\n    {layer_from_ops : LayerOps ident primsem_from (globvar Vm_from) layer_from}\n    {program_format_ops_from: ProgramFormatOps Fm_from Vm_from F_prog_from V_prog_from}\n    {D_from: ld_from}\n  .\n\n  Context\n    {ld_to Fm_to Vm_to module_to : Type}\n    {primsem_to layer_to : ld_to -> Type}\n    {gvar_to_ops: GlobalVarsOps (globvar Vm_to)}\n    {module_to_ops : ModuleOps ident Fm_to (globvar Vm_to) module_to}\n    {primsem_to_ops : PrimitiveOps primsem_to}\n    {layer_to_ops : LayerOps ident primsem_to (globvar Vm_to) layer_to}\n    {program_format_ops_to: ProgramFormatOps Fm_to Vm_to F_prog_to V_prog_to}\n    {D_to: ld_to}\n  .\n\n  Variables\n    (convert_primsem: ident -> primsem_from D_from -> primsem_to D_to)\n    (convert_globalvar: Vm_from -> Vm_to)\n  .\n\n  (* Source to compiled. *)\n\n  Let RF_module: funrel D_from D_to :=\n    fun i =>\n    option_rel\n      ((fun (f_from: Fm_from) f_to =>\n         exists fp_from,\n           make_internal f_from = OK fp_from /\\\n           exists fp_to,\n             transf_F_prog fp_from = OK fp_to /\\\n             make_internal f_to = OK fp_to) + (fun p_from p_to => convert_primsem i p_from = p_to)).\n\n  Let RV_module: varrel (Vm1 := Vm_from) (Vm2 := Vm_to) :=\n    fun _ =>\n      option_rel (globvar_rel (fun v_from v_to => convert_globalvar v_from = v_to)).\n\n  Hypothesis convert_primitive_to_program:\n    forall i f f_,\n      make_external D_from i f = OK f_ -> \n      forall fto_,\n        make_external D_to i (convert_primsem i f) = OK fto_ ->\n        transf_F_prog f_ = OK fto_.\n\n  Variables (make_varinfo_from: Vm_from -> V_prog_from).\n  Variables (make_varinfo_to: Vm_to -> V_prog_to).\n\n  Hypothesis make_varinfo_from_map:\n    forall v v',\n    make_varinfo v = OK v' ->\n    v' = globvar_map make_varinfo_from v.\n\n  Hypothesis make_varinfo_to_map:\n    forall v v',\n    make_varinfo v = OK v' ->\n    v' = globvar_map make_varinfo_to v.\n\n  Hypothesis transf_V_module_to_program:\n    forall v,\n      transf_V_prog (make_varinfo_from v) = OK (make_varinfo_to (convert_globalvar v)).\n\n  Local Instance make_program_relations:\n    MakeProgramRelations D_from D_to RF_module RV_module RF_prog RV_prog.\n  Proof.\n    split.\n    * intros i.\n      red.\n      unfold RF_module.\n      inversion 1; subst; congruence.\n    * intros i.\n      red.\n      unfold RV_module.\n      inversion 1; subst; congruence.\n    * repeat red.\n      unfold RF_module.\n      intros i x y H x0 y0 H0 H1.\n      inversion H; clear H; subst.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        inversion H3; clear H3; subst.\n        {\n          inversion H1; clear H1; subst.\n          inversion H2; clear H2; subst.\n          destruct H as (fp_from & make_from & fp_to & transf & make_to).\n          constructor.\n          congruence.\n        }\n        inversion H2; clear H2; subst.\n        inversion H1; clear H1; subst.\n        constructor.\n        eauto.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        constructor.\n    * repeat red.\n      unfold RV_module.\n      intros i x y H x0 y0 H0 H1.\n      inversion H; clear H; subst.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        inversion H3; clear H3; subst.\n        inversion H1; clear H1; subst.\n        inversion H2; clear H2; subst.        \n        apply make_varinfo_to_map in H0.\n        unfold globvar_map in H0.\n        simpl in H0.\n        subst.\n        apply make_varinfo_from_map in H1.\n        unfold globvar_map in H1.\n        simpl in H1.\n        subst.\n        constructor.\n        constructor; auto.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        constructor.\n    * intros i f1 f2 Hf.\n      inversion Hf; clear Hf; subst.\n      destruct H1 as [f_from f_to Hf | p_from p_to Hp].\n      + destruct Hf as (fp_from & Hfp_from & fp_to & Hfp & Hfp_to).\n        simpl.\n        rewrite Hfp_from, Hfp_to.\n        intros [err H].\n        discriminate.\n      + simpl.        \n        inversion 1.\n        revert H.\n        admit. (* need properties on convert_primsem vs. make_external *)\n    * intros i v1 v2 Hv.\n      inversion Hv; clear Hv; subst.\n      destruct H1 as [v1 v2 Hv init _ [] ro _ [] vol _ []].\n      admit. (* need properties on convert_globvar vs. make_varinfo *)\n  Admitted.\n\n  Local Instance make_program_relations_flip:\n    MakeProgramRelations D_to D_from (fun i => flip (RF_module i)) (fun i => flip (RV_module i)) (fun i => flip (RF_prog i)) (fun i => flip (RV_prog i)).\n  Proof.\n    split.\n    * intros i.\n      red.\n      unfold flip, RF_module.\n      inversion 1; subst; congruence.\n    * intros i.\n      red.\n      unfold flip, RV_module.\n      inversion 1; subst; congruence.\n    * repeat red.\n      unfold flip, RF_module.\n      intros i x y H x0 y0 H0 H1.\n      inversion H; clear H; subst.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        inversion H4; clear H4; subst.\n        {\n          inversion H1; clear H1; subst.\n          inversion H2; clear H2; subst.\n          destruct H as (fp_from & make_from & fp_to & transf & make_to).\n          constructor.\n          congruence.\n        }\n        inversion H2; clear H2; subst.\n        inversion H1; clear H1; subst.\n        constructor.\n        eauto.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        constructor.\n    * repeat red.\n      unfold flip, RV_module.\n      intros i x y H x0 y0 H0 H1.\n      inversion H; clear H; subst.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        inversion H4; clear H4; subst.\n        inversion H1; clear H1; subst.\n        inversion H2; clear H2; subst.\n        apply make_varinfo_from_map in H0.\n        unfold globvar_map in H0.\n        simpl in H0.\n        subst.\n        apply make_varinfo_to_map in H1.\n        unfold globvar_map in H1.\n        simpl in H1.\n        subst.\n        constructor.\n        constructor; auto.\n      + inversion H1; clear H1; subst.\n        inversion H0; clear H0; subst.\n        constructor.\n    * intros i f1 f2 Hf.\n      inversion Hf; clear Hf; subst.\n      destruct H1 as [f_from f_to Hf | p_from p_to Hp].\n      + destruct Hf as (fp_from & Hfp_from & fp_to & Hfp & Hfp_to).\n        simpl.\n        rewrite Hfp_from, Hfp_to.\n        intros [err H].\n        discriminate.\n      + simpl.        \n        inversion 1.\n        revert H.\n        admit. (* need properties on convert_primsem vs. make_external *)\n    * intros i v1 v2 Hv.\n      inversion Hv; clear Hv; subst.\n      destruct H1 as [v1 v2 Hv init _ [] ro _ [] vol _ []].\n      admit. (* need properties on convert_globvar vs. make_varinfo *)\n  Admitted.\n\n  (* For a correctly compiled module. *)\n\n  Variables (Mfrom: module_from) (Mto: module_to).\n  Variables (Lfrom: layer_from D_from) (Lto: layer_to D_to).\n\n  Hypothesis get_module_function_some:\n    forall i ffrom,\n      get_module_function i Mfrom = OK (Some ffrom) ->\n      exists fto,\n        get_module_function i Mto = OK (Some fto) /\\\n        exists fp_from,\n          make_internal ffrom = OK fp_from /\\\n          exists fp_to,\n            transf_F_prog fp_from = OK fp_to /\\\n            make_internal fto = OK fp_to.\n\n  Hypothesis get_module_function_none:\n    forall i,\n      get_module_function i Mfrom = OK None ->\n      get_module_function i Mto = OK None.\n\n  Hypothesis get_module_variable_eq:\n    forall i ffrom,\n      get_module_variable i Mfrom = OK ffrom ->\n      get_module_variable i Mto = OK (option_map (globvar_map convert_globalvar) ffrom).\n\n  Hypothesis get_layer_primitive_eq:\n    forall i ffrom,\n      get_layer_primitive i Lfrom = OK ffrom ->\n      get_layer_primitive i Lto = OK (option_map (convert_primsem i) ffrom).\n\n  Hypothesis get_layer_globalvar_eq:\n    forall i ffrom,\n      get_layer_globalvar i Lfrom = OK ffrom ->\n      get_layer_globalvar i Lto = OK (option_map (globvar_map convert_globalvar) ffrom).\n    \n  Lemma module_layer_rel_flip_intro:      \n    module_layer_rel D_to D_from (fun i : ident => flip (RF_module i))\n                     (fun i : ident => flip (RV_module i)) (Mto, Lto) (Mfrom, Lfrom).\n  Proof.\n    unfold module_layer_rel.\n    simpl.\n    intros i.\n    split.\n    {\n      unfold get_module_layer_function; simpl.\n      destruct (get_module_function i Mfrom) eqn:H.\n      {\n        destruct (get_layer_primitive i Lfrom) eqn:H0.\n        {\n          apply get_layer_primitive_eq in H0.\n          rewrite H0.\n          destruct o.\n          {\n            apply get_module_function_some in H.\n            destruct H as (? & H & TRANSF).\n            rewrite H.\n            simpl.\n            destruct o0; simpl; constructor; auto.\n            constructor.\n            constructor.\n            assumption.\n          }\n          apply get_module_function_none in H.\n          rewrite H.\n          simpl.\n          destruct o0; simpl; constructor; auto; repeat constructor.\n        }\n        simpl.\n        destruct o; constructor.\n      }\n      simpl.\n      constructor.\n    }\n    unfold get_module_layer_variable; simpl.\n    destruct (get_module_variable i Mfrom) as [ o | ] eqn:H; simpl.\n    {\n      apply get_module_variable_eq in H.\n      rewrite H; clear H.\n      destruct (get_layer_globalvar i Lfrom) as [ o0 | ] eqn:H0; simpl.\n      {\n        apply get_layer_globalvar_eq in H0.\n        rewrite H0; clear H0.\n        destruct o as [ g | ].\n        {\n          destruct o0 as [ g0 | ].\n          {\n            destruct (Decision.decide (g = g0)).\n            {\n              subst.\n              autorewrite with res_option_globalvar.\n              simpl.\n              repeat constructor.\n              destruct g0; repeat constructor.\n            }\n            rewrite (GlobalVars.res_option_globalvar_oplus_diff g g0) by assumption.\n            constructor.\n          }\n          autorewrite with res_option_globalvar.\n          simpl.\n          repeat constructor.\n          destruct g; repeat constructor.\n        }\n        autorewrite with res_option_globalvar.\n        simpl.\n        repeat constructor.\n        destruct o0 as [ g0 | ]; repeat constructor.\n        destruct g0; repeat constructor.\n      }\n      GlobalVars.res_option_globalvar_red.\n      constructor.\n    }\n    GlobalVars.res_option_globalvar_red.\n    constructor.\n  Qed.\n  \n  Context `{make_program_prf: MakeProgram}.\n\n  Lemma make_program_transform_partial_program2 pfrom pto:\n    make_program _ (Mfrom, Lfrom) = OK pfrom ->\n    make_program _ (Mto, Lto) = OK pto ->\n    transform_partial_program2 (fun _ => transf_F_prog) (fun _ => transf_V_prog) pfrom = OK pto.\n  Proof.\n    intros H H0.\n    generalize (make_program_rel make_program_relations_flip _ _ module_layer_rel_flip_intro).\n    rewrite H.\n    rewrite H0.\n    inversion 1; subst.\n    eapply transform_partial_program2_recip_flip; eauto.\n  Qed.\n\n  Lemma make_program_from_to_exists pfrom:\n    make_program _ (Mfrom, Lfrom) = OK pfrom ->\n    exists pto, make_program _ (Mto, Lto) = OK pto.\n  Proof.\n    intros H.\n    generalize (make_program_rel make_program_relations_flip _ _ module_layer_rel_flip_intro).\n    rewrite H.\n    inversion 1; subst.\n    eauto.\n  Qed.\n\n  Hypothesis Mfrom_OK_function:\n    forall i,\n      isError (get_module_function i Mfrom) ->\n      isError (get_module_function i Mto).\n\n  Hypothesis Mfrom_OK_variable:\n    forall i,\n      isError (get_module_variable i Mfrom) ->\n      isError (get_module_variable i Mto).\n\n  Hypothesis Lfrom_OK_primitive:\n    forall i,\n      isError (get_layer_primitive i Lfrom) ->\n      isError (get_layer_primitive i Lto).\n\n  Hypothesis Lfrom_OK_globalvar:\n    forall i,\n      isError (get_layer_globalvar i Lfrom) ->\n      isError (get_layer_globalvar i Lto).\n\n  (** The following condition is required to ensure that Mfrom, Lfrom\n      do not have different global variables at the same\n      symbol. Indeed, if we were to have some, and if those two global\n      variables were converted to the same one, then we would have to\n      prove [res_le (option_le _) (Error _) (OK _)], which obviously\n      does not hold.\n\n      The alternative is to require that [convert_globalvar] be\n      injective, which is not realistic unless we use the same type for\n      source and target global variables for modules and layers, and\n      convert them only when translating their corresponding programs.\n   *)\n  Hypothesis DISJ: module_layer_disjoint Mfrom Lfrom.\n\n  Lemma module_layer_rel_intro:\n    module_layer_rel D_from D_to RF_module RV_module (Mfrom, Lfrom) (Mto, Lto).\n  Proof.\n    unfold module_layer_rel.\n    simpl.\n    intros i.\n    split.\n    {\n      unfold get_module_layer_function; simpl.\n      destruct (get_module_function i Mfrom) eqn:H.\n      {\n        destruct (get_layer_primitive i Lfrom) eqn:H0.\n        {\n          apply get_layer_primitive_eq in H0.\n          rewrite H0.\n          destruct o.\n          {\n            apply get_module_function_some in H.\n            destruct H as (? & H & TRANSF).\n            rewrite H.\n            simpl.\n            destruct o0; simpl; constructor; auto.\n            constructor.\n            constructor.\n            assumption.\n          }\n          apply get_module_function_none in H.\n          rewrite H.\n          simpl.\n          destruct o0; simpl; constructor; auto; repeat constructor.\n        }\n        destruct (Lfrom_OK_primitive i) as [? H1].\n        { rewrite H0. econstructor. reflexivity. }\n        rewrite H1.\n        destruct (get_module_function i Mto).\n        {\n          destruct o0; constructor.\n        }\n        constructor.\n      }\n      destruct (Mfrom_OK_function i) as [? H1].\n      { rewrite H. econstructor. reflexivity. }\n      rewrite H1.\n      constructor.\n    }\n    unfold get_module_layer_variable; simpl.\n    destruct (get_module_variable i Mfrom) as [ o | ] eqn:H.\n    {\n      generalize H. intro H_.\n      apply get_module_variable_eq in H.\n      rewrite H; clear H.\n      destruct (get_layer_globalvar i Lfrom) as [ o0 | ] eqn:H0.\n      {\n        generalize H0. intro H0_.\n        apply get_layer_globalvar_eq in H0.\n        rewrite H0; clear H0.\n        destruct o as [ g | ].\n        {\n          destruct o0 as [ g0 | ].\n          {\n            assert (g = g0).\n            {\n              specialize (DISJ i).\n              rewrite H_ in DISJ.\n              rewrite H0_ in DISJ.\n              inversion DISJ; congruence.\n            }\n            subst.\n            autorewrite with res_option_globalvar.\n            destruct g0; repeat constructor.\n          }\n          simpl.\n          autorewrite with res_option_globalvar.\n          destruct g; repeat constructor.\n        }\n        simpl.\n        autorewrite with res_option_globalvar.\n        destruct o0 as [ [ ] | ] ; repeat constructor.\n      }\n      edestruct Lfrom_OK_globalvar as [ ? EQ ]; unfold isError; eauto.\n      rewrite EQ.\n      res_option_globalvar_red.\n      constructor.\n    }\n    edestruct Mfrom_OK_variable as [ ? EQ ]; unfold isError; eauto.\n    rewrite EQ.\n    res_option_globalvar_red.\n    constructor.\n  Qed.\n\n  Lemma make_program_to_from_exists pto:\n    make_program _ (Mto, Lto) = OK pto ->\n    exists pfrom, make_program _ (Mfrom, Lfrom) = OK pfrom.\n  Proof.\n    intros H.\n    generalize (make_program_rel make_program_relations _ _ module_layer_rel_intro).\n    rewrite H.\n    inversion 1; subst.\n    eauto.\n  Qed.\n\nEnd TRANSFORM_PROGRAM.\n", "meta": {"author": "VeriGu", "repo": "E6998-Formal-Verification", "sha": "83c0bdd12b723f81c08886be1dedca0ca8aff0eb", "save_path": "github-repos/coq/VeriGu-E6998-Formal-Verification", "path": "github-repos/coq/VeriGu-E6998-Formal-Verification/E6998-Formal-Verification-83c0bdd12b723f81c08886be1dedca0ca8aff0eb/certikos/liblayers/compcertx/TransformProgram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.19507638209139164}}
{"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 & Mark Bickford\n\n*)\n\n\nRequire Export computation7.\n\n\n\nLemma computes_steps_prinargs_comp2 {p} :\n  forall lib a ntp1 ntp2 lbt k1 k2 ntpc1 ntpc2,\n    compute_at_most_k_steps lib k1 ntp1 = csuccess ntpc1\n    -> iswfpk a ntpc1\n    -> compute_at_most_k_steps lib k2 ntp2 = @csuccess p ntpc2\n    -> {j : nat $ compute_at_most_k_steps lib j (oterm (NCan (NCompOp a))\n                        ((bterm [] ntp1)::((bterm [] ntp2)::lbt)))\n            = csuccess (oterm (NCan (NCompOp a))\n                              ((bterm [] ntpc1)::((bterm [] ntpc2)::lbt)))\n                       # j<= (k1+k2)}.\nProof.\n  induction k2 as [| k2 Hind];  introv H1c H1v H2c.\n  - inverts H2c.\n    match goal with\n    | [ |- {_ : nat $ compute_at_most_k_steps _ _\n          (oterm (NCan ?no) (?h :: ?tl)) = _ # _ }] =>\n     apply @computes_atmost_ksteps_prinarg with (lbt:= tl)\n      (op:=no) in H1c\n    end.\n    exrepnd. exists j. dands; spc. omega.\n  - rename H2c into Hck. rename k2 into k.\n    destruct ntp2 as [|f|ntp2o ntp2lbt];\n      [rw @compute_at_most_steps_var in Hck; spc; fail| |].\n\n    { rw @compute_at_most_k_steps_isvalue_like in Hck; eauto 3 with slow; ginv.\n      pose proof (Hind ntpc1 (sterm f)) as h; clear Hind.\n      repeat (autodimp h hyp).\n      { rw @compute_at_most_k_steps_isvalue_like; eauto 3 with slow; ginv. }\n      exrepnd.\n      eexists; dands; eauto; try omega. }\n\n    allsimpl.\n    remember (compute_at_most_k_steps lib k (oterm ntp2o ntp2lbt)) as ck.\n    destruct ck as [csk | cf]; spc;[].\n    pose proof (Hind _ csk H1c H1v eq_refl) as XX. exrepnd.\n    destruct csk as [sckv|f| csko csklbt]; [inverts Hck; fail| |].\n\n    { csunf Hck; allsimpl; ginv.\n      pose proof (Hind ntpc1 (sterm f)) as h; clear Hind.\n      repeat (autodimp h hyp).\n      exrepnd.\n      eexists; dands; eauto; try omega. }\n\n    dopid csko as [cskoc| cskon | cskexc | cskabs] Case.\n    + Case \"Can\".\n      simpl in Hck. inverts Hck. exists j; sp. omega.\n    + Case \"NCan\".\n      exists (S j). dands;[|omega].\n      allsimpl.\n      rw XX1.\n      unfold iswfpk in H1v; destruct a.\n      * unfold isinteger in H1v; exrepnd; subst.\n        csunf; simpl.\n        rw Hck;sp.\n      * unfold ispk in H1v; exrepnd; subst.\n        csunf; simpl; allrw @pk2term_eq; dcwf h; allsimpl;\n        try (rw Hck;sp);[].\n        unfold co_wf in Heqh; allrw @get_param_from_cop_pk2can; ginv.\n    + Case \"Exc\".\n      rw @compute_step_exception in Hck; sp; inversion Hck; subst; GC.\n      exists j; sp; omega.\n    + Case \"Abs\".\n      exists (S j). dands;[|omega].\n      simpl.\n      rw XX1.\n      unfold iswfpk in H1v; destruct a.\n      * unfold isinteger in H1v; exrepnd; subst.\n        csunf; simpl.\n        rw Hck;sp.\n      * unfold ispk in H1v; exrepnd; subst.\n        csunf; simpl; allrw @pk2term_eq; dcwf h; allsimpl;\n        try (rw Hck;sp);[].\n        unfold co_wf in Heqh; allrw @get_param_from_cop_pk2can; ginv.\nQed.\n\nLemma reduce_to_prinargs_comp2 {p} :\n  forall lib a (ntp1 ntp2 : @NTerm p) lbt ntpv1 ntpc2,\n    reduces_to lib ntp1 ntpv1\n    -> iswfpk a ntpv1\n    -> reduces_to lib ntp2 ntpc2\n    -> reduces_to lib (oterm (NCan (NCompOp a))\n                             ((bterm [] ntp1)::((bterm [] ntp2)::lbt)))\n                  (oterm (NCan (NCompOp a))\n                         ((bterm [] ntpv1)::((bterm [] ntpc2)::lbt))).\nProof.\n  introv H1c isc H2c.\n  repnud H2c.\n  repnud H1c.\n  exrepnd.\n  eapply @computes_steps_prinargs_comp2\n  with (lbt:=lbt)\n         (a:=a)\n         (ntpc1:= ntpv1)\n         (ntpc2:= ntpc2) in H1c0;\n    exrepnd; eauto.\n  unfolds_base; exists j; eauto.\nQed.\n\nLemma computes_steps_prinargs_arith2 {p} :\n  forall lib a ntp1 ntp2 lbt k1 k2 ntpc1 ntpc2,\n    compute_at_most_k_steps lib k1 ntp1 = csuccess ntpc1\n    -> isinteger ntpc1\n    -> compute_at_most_k_steps lib k2 ntp2 = @csuccess p ntpc2\n    -> {j : nat $ compute_at_most_k_steps lib j (oterm (NCan (NArithOp a))\n                        ((bterm [] ntp1)::((bterm [] ntp2)::lbt)))\n            = csuccess (oterm (NCan (NArithOp a))\n                              ((bterm [] ntpc1)::((bterm [] ntpc2)::lbt)))\n                       # j<= (k1+k2)}.\nProof.\n  induction k2 as [| k2 Hind];  introv H1c H1v H2c.\n  - inverts H2c.\n    match goal with\n    | [ |- {_ : nat $ compute_at_most_k_steps _ _\n          (oterm (NCan ?no) (?h :: ?tl)) = _ # _ }] =>\n     apply @computes_atmost_ksteps_prinarg with (lbt:= tl)\n      (op:=no) in H1c\n    end.\n    exrepnd. exists j. dands; spc. omega.\n  - rename H2c into Hck. rename k2 into k.\n    destruct ntp2 as [|f|ntp2o ntp2lbt];\n      [rw @compute_at_most_steps_var in Hck; spc; fail| |].\n\n    { rw @compute_at_most_k_steps_isvalue_like in Hck; eauto 3 with slow; ginv.\n      pose proof (Hind ntpc1 (sterm f)) as h; clear Hind.\n      repeat (autodimp h hyp).\n      { rw @compute_at_most_k_steps_isvalue_like; eauto 3 with slow; ginv. }\n      exrepnd.\n      eexists; dands; eauto; try omega. }\n\n    allsimpl.\n    remember (compute_at_most_k_steps lib k (oterm ntp2o ntp2lbt)) as ck.\n    destruct ck as [csk | cf]; spc;[].\n    pose proof (Hind _ csk H1c H1v eq_refl) as XX. exrepnd.\n    unfold isinteger in H1v; exrepnd; subst.\n    destruct csk as [sckv|f|csko csklbt]; [inverts Hck; fail| |].\n\n    { csunf Hck; allsimpl; ginv.\n      pose proof (Hind (mk_integer z) (sterm f)) as h; clear Hind.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      exrepnd.\n      eexists; dands; eauto; try omega. }\n\n    dopid csko as [cskoc| cskon | cskexc | cskabs] Case.\n    + Case \"Can\".\n      simpl in Hck. inverts Hck. exists j; sp. omega.\n    + Case \"NCan\".\n      exists (S j). dands;[|omega].\n      simpl.\n      rw XX1.\n      csunf; simpl.\n      rw Hck;sp.\n    + Case \"Exc\".\n      rw @compute_step_exception in Hck; sp; inversion Hck; subst; GC.\n      exists j; sp; omega.\n    + Case \"Abs\".\n      exists (S j). dands;[|omega].\n      simpl.\n      rw XX1.\n      csunf; simpl.\n      rw Hck;sp.\nQed.\n\nLemma reduce_to_prinargs_arith2 {p} :\n  forall lib a (ntp1 ntp2 : @NTerm p) lbt ntpv1 ntpc2,\n    reduces_to lib ntp1 ntpv1\n    -> isinteger ntpv1\n    -> reduces_to lib ntp2 ntpc2\n    -> reduces_to lib (oterm (NCan (NArithOp a))\n                             ((bterm [] ntp1)::((bterm [] ntp2)::lbt)))\n                  (oterm (NCan (NArithOp a))\n                         ((bterm [] ntpv1)::((bterm [] ntpc2)::lbt))).\nProof.\n  introv H1c isc H2c.\n  repnud H2c.\n  repnud H1c.\n  exrepnd.\n  eapply @computes_steps_prinargs_arith2\n  with (lbt:=lbt)\n         (a:=a)\n         (ntpc1:= ntpv1)\n         (ntpc2:= ntpc2) in H1c0;\n    exrepnd; eauto.\n  unfolds_base; exists j; eauto.\nQed.\n\nLemma reduces_to_fresh2 {o} :\n  forall (lib : library) (t u : @NTerm o) (v : NVar) a,\n  wf_term t\n  -> !LIn a (get_utokens t)\n  -> reduces_to lib (subst t v (mk_utoken a)) u\n  -> {z : NTerm\n      $ reduces_to lib (mk_fresh v t) (mk_fresh v z)\n      # alpha_eq z (subst_utokens u [(a, mk_var v)])}.\nProof.\n  introv w ni r.\n\n  pose proof (reduces_to_change_utok_sub\n                lib t u\n                [(v,mk_utoken a)]\n                [(v,mk_utoken (get_fresh_atom t))]) as r'.\n  allrw @get_utokens_sub_cons; allrw @get_utokens_sub_nil; allsimpl.\n  allrw disjoint_singleton_l.\n  repeat (autodimp r' hyp); eauto 3 with slow.\n  { apply nr_ut_sub_cons; eauto with slow.\n    intro i; apply get_fresh_atom_prop. }\n  { apply get_fresh_atom_prop. }\n  exrepnd.\n\n  allrw disjoint_singleton_l.\n  allrw @fold_subst.\n\n  pose proof (reduces_to_fresh lib t s v) as h; simpl in h.\n  repeat (autodimp h hyp); exrepnd.\n  exists z; dands; auto.\n\n  remember (get_fresh_atom t) as a'.\n\n  pose proof (alpha_eq_subst_utokens\n                s (subst w0 v (mk_utoken a'))\n                [(a', mk_var v)]\n                [(a', mk_var v)]) as aeqs1.\n  repeat (autodimp aeqs1 hyp); eauto 3 with slow.\n  pose proof (simple_alphaeq_subst_utokens_subst w0 v a') as aeqs2.\n  autodimp aeqs2 hyp.\n  { subst; intro i; apply r'4 in i; apply get_fresh_atom_prop in i; sp. }\n  eapply alpha_eq_trans in aeqs2;[|exact aeqs1]; clear aeqs1.\n  eapply alpha_eq_trans in aeqs2;[|exact h0].\n  eapply alpha_eq_trans;[exact aeqs2|].\n\n  pose proof (alpha_eq_subst_utokens\n                u (subst w0 v (mk_utoken a))\n                [(a, mk_var v)]\n                [(a, mk_var v)]) as aeqs1.\n  repeat (autodimp aeqs1 hyp); eauto 3 with slow.\n  pose proof (simple_alphaeq_subst_utokens_subst w0 v a) as aeqs3.\n  autodimp aeqs3 hyp.\n  eapply alpha_eq_trans in aeqs3;[|exact aeqs1]; eauto with slow.\nQed.\n\nLemma alpha_eq_subst_utokens_same {o} :\n  forall (t1 t2 : @NTerm o) (s : utok_sub),\n    alpha_eq t1 t2\n    -> alpha_eq (subst_utokens t1 s) (subst_utokens t2 s).\nProof.\n  introv aeq.\n  apply alpha_eq_subst_utokens; eauto with slow.\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\")\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/computation/computation8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19507638209139164}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sha.SHA256.\nRequire Import sha.spec_sha.\nRequire Import sha.sha.\nRequire Export sha.pure_lemmas.\nRequire Export sha.general_lemmas.\nExport ListNotations.\n\nLocal Open Scope logic.\n\nGlobal Opaque K256.\n\nTransparent peq.\n\nLemma mapsto_tc_val:\n  forall sh t p v,\n  readable_share sh ->\n  v <> Vundef ->\n  mapsto sh t p v = !! tc_val t v && mapsto sh t p v .\nProof.\nintros.\napply pred_ext; [ | normalize].\napply andp_right; auto.\nunfold mapsto; simpl.\ndestruct (access_mode t); try apply FF_left.\ndestruct (attr_volatile (attr_of_type t)); try apply FF_left.\ndestruct p; try apply FF_left.\nif_tac; try contradiction. apply orp_left.\nnormalize.\nnormalize.\nQed.\n\nFixpoint loops (s: statement) : list statement :=\n match s with\n  | Ssequence a b => loops a ++ loops b\n  | Sloop _ _ => [s]\n  | Sifthenelse _ a b => loops a ++ loops b\n  | _ => nil\n  end.\n\nLemma nth_big_endian_integer:\n  forall i bl w,\n   nth_error bl i = Some w ->\n    w = big_endian_integer\n                   (sublist (Z.of_nat i * WORD)\n                        (Z.succ (Z.of_nat i) * WORD)\n                   (map Int.repr (intlist_to_Zlist bl))).\nProof.\ninduction i; destruct bl; intros; inv H.\n*\n unfold sublist; simpl.\n rewrite big_endian_integer4.\n repeat rewrite Int.repr_unsigned.\n assert (Int.zwordsize=32)%Z by reflexivity.\n unfold Z_to_Int, Shr; simpl.\n change 255%Z with (Z.ones 8).\n apply Int.same_bits_eq; intros;\n autorewrite with testbit.\n if_tac; simpl.\n if_tac; simpl.\n if_tac; simpl; autorewrite with testbit. auto. f_equal; omega.\n rewrite if_false by omega. autorewrite with testbit. f_equal; omega.\n rewrite if_false by omega. rewrite if_false by omega.\n autorewrite with testbit. f_equal; omega.\n*\nspecialize (IHi _ _ H1); clear H1.\nsimpl map.\nrewrite IHi.\nunfold sublist.\nreplace (Z.to_nat (Z.of_nat (S i) * WORD)) with (4 + Z.to_nat (Z.of_nat i * WORD))%nat\n  by (rewrite plus_comm, inj_S; unfold Z.succ; rewrite Z.mul_add_distr_r;\n        rewrite Z2Nat.inj_add by (change WORD with 4; omega); reflexivity).\nrewrite <- skipn_skipn.\nsimpl skipn.\nf_equal. f_equal. f_equal. rewrite inj_S.  unfold Z.succ.\nrewrite !Z.mul_add_distr_r; omega.\nQed.\n\nLemma Znth_big_endian_integer:\n  forall i bl,\n   0 <= i < Zlength bl ->\n   Znth i bl Int.zero =\n     big_endian_integer\n                   (sublist (i * WORD) (Z.succ i * WORD)\n                   (map Int.repr (intlist_to_Zlist bl))).\nProof.\nintros.\nunfold Znth.\n rewrite if_false by omega.\npose proof (nth_error_nth _ Int.zero (Z.to_nat i) bl).\nrewrite <- (Z2Nat.id i) at 2 3 by omega.\napply nth_big_endian_integer.\napply H0.\napply Nat2Z.inj_lt.\nrewrite Z2Nat.id by omega.\nrewrite <- Zlength_correct; omega.\nQed.\n\nFixpoint sequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence c (sequence cs' s)\n end.\n\nFixpoint rsequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence (rsequence cs' s) c\n end.\n\nLemma sequence_rsequence:\n forall Espec CS Delta P cs s0 s R,\n    @semax CS Espec Delta P (Ssequence s0 (sequence cs s)) R  <->\n  @semax CS Espec Delta P (Ssequence (rsequence (rev cs) s0) s) R.\nProof.\nintros.\nrevert Delta P R s0 s; induction cs; intros.\nsimpl. apply iff_refl.\nsimpl.\nrewrite seq_assoc.\nrewrite IHcs; clear IHcs.\nreplace (rsequence (rev cs ++ [a]) s0) with\n    (rsequence (rev cs) (Ssequence s0 a)); [apply iff_refl | ].\nrevert s0 a; induction (rev cs); simpl; intros; auto.\nrewrite IHl. auto.\nQed.\n\nLemma seq_assocN:\n  forall {Espec: OracleKind} CS,\n   forall Q Delta P cs s R,\n        @semax CS Espec Delta P (sequence cs Sskip) (normal_ret_assert Q) ->\n         @semax CS Espec\n       (update_tycon Delta (sequence cs Sskip)) Q s R ->\n        @semax CS Espec Delta P (sequence cs s) R.\nProof.\nintros.\nrewrite semax_skip_seq.\nrewrite sequence_rsequence.\nrewrite semax_skip_seq in H.\nrewrite sequence_rsequence in H.\nrewrite <- semax_seq_skip in H.\neapply semax_seq'; [apply H | ].\neapply semax_extensionality_Delta; try apply H0.\nclear.\nrevert Delta; induction cs; simpl; intros.\napply tycontext_sub_refl.\neapply tycontext_sub_trans; [apply IHcs | ].\nclear.\nrevert Delta; induction (rev cs); simpl; intros.\napply tycontext_sub_refl.\napply update_tycon_sub.\napply IHl.\nQed.\n\nFixpoint sequenceN (n: nat) (s: statement) : list statement :=\n match n, s with\n | S n', Ssequence a s' => a::sequenceN n' s'\n | _, _ => nil\n end.\n\nLemma data_block_local_facts:\n forall {cs: compspecs} sh f data,\n  data_block sh f data |--\n   prop (field_compatible (tarray tuchar (Zlength f)) [] data\n           /\\ Forall isbyteZ f).\nProof.\nintros. unfold data_block, array_at.\nsimpl.\nentailer.\nQed.\nHint Resolve @data_block_local_facts : saturate_local.\n\nRequire Import JMeq.\n\nLemma reptype_tarray {cs: compspecs}:\n   forall t len, reptype (tarray t len) = list (reptype t).\nProof.\nintros.\nrewrite reptype_eq. simpl. reflexivity.\nQed.\n\nLocal Open Scope nat.\n\n(*** Application of Omega stuff ***)\n\nLemma CBLOCKz_eq : CBLOCKz = 64%Z.\nProof. reflexivity. Qed.\nLemma LBLOCKz_eq : LBLOCKz = 16%Z.\nProof. reflexivity. Qed.\n\nLtac helper2 :=\n match goal with\n   | |- context [CBLOCK] => add_nonredundant (CBLOCK_eq)\n   | |- context [LBLOCK] => add_nonredundant (LBLOCK_eq)\n   | |- context [CBLOCKz] => add_nonredundant (CBLOCKz_eq)\n   | |- context [LBLOCKz] => add_nonredundant (LBLOCKz_eq)\n   | H: context [CBLOCK] |- _ => add_nonredundant (CBLOCK_eq)\n   | H: context [LBLOCK] |- _ => add_nonredundant (LBLOCK_eq)\n   | H: context [CBLOCKz] |- _ => add_nonredundant (CBLOCKz_eq)\n   | H: context [LBLOCKz] |- _ => add_nonredundant (LBLOCKz_eq)\n  end.\n\nLtac Omega1 := Omega (helper1 || helper2).\n\nLtac MyOmega :=\n  rewrite ?length_list_repeat, ?skipn_length, ?map_length,\n   ?Zlength_map, ?Zlength_nil;\n  pose proof CBLOCK_eq;\n  pose proof CBLOCKz_eq;\n  pose proof LBLOCK_eq;\n  pose proof LBLOCKz_eq;\n  Omega1.\n(*** End Omega stuff ***)\n\nLocal Open Scope Z.\n\nLocal Open Scope logic.\n\nLemma data_block_valid_pointer {cs: compspecs} sh l p: sepalg.nonidentity sh -> Zlength l > 0 ->\n      data_block sh l p |-- valid_pointer p.\nProof. unfold data_block. simpl; intros.\n  apply andp_valid_pointer2. apply data_at_valid_ptr; auto; simpl.\n  rewrite Z.max_r, Z.mul_1_l; omega.\nQed.\n\nLemma data_block_isbyteZ {cs: compspecs}:\n forall sh data v, data_block sh data v = !! Forall isbyteZ data && data_block sh data v.\nProof.\nunfold data_block; intros.\nsimpl.\nnormalize.\nf_equal. f_equal. apply prop_ext. intuition.\nQed.\n\nLemma sizeof_tarray_tuchar:\n forall (n:Z), (n>=0)%Z -> (sizeof (tarray tuchar n) =  n)%Z.\nProof. intros.\n unfold sizeof,tarray; cbv beta iota.\n  rewrite Z.max_r by omega.\n  unfold alignof, tuchar; cbv beta iota.\n  rewrite Z.mul_1_l. auto.\nQed.\n\nLemma isbyte_value_fits_tuchar:\n  forall x, isbyteZ x -> value_fits tuchar (Vint (Int.repr x)).\nProof.\nintros. hnf in H|-*; intros.\nsimpl. rewrite Int.unsigned_repr by rep_omega.\n  change Byte.max_unsigned with 255%Z. omega.\nQed.\n\nLemma Zlength_Zlist_to_intlist:\n  forall (n:Z) (l: list Z),\n   (Zlength l = WORD*n)%Z -> Zlength (Zlist_to_intlist l) = n.\nProof.\nintros.\nrewrite Zlength_correct in *.\nassert (0 <= n)%Z by ( change WORD with 4%Z in H; omega).\nrewrite (length_Zlist_to_intlist (Z.to_nat n)).\napply Z2Nat.id; auto.\napply Nat2Z.inj. rewrite H.\nrewrite Nat2Z.inj_mul.\nf_equal. rewrite Z2Nat.id; omega.\nQed.\n\nLemma nth_intlist_to_Zlist_eq:\n forall d (n i j k: nat) al, (i < n)%nat -> (i < j*4)%nat -> (i < k*4)%nat ->\n    nth i (intlist_to_Zlist (firstn j al)) d = nth i (intlist_to_Zlist (firstn k al)) d.\nProof.\n induction n; destruct i,al,j,k; simpl; intros; auto; try omega.\n destruct i; auto. destruct i; auto. destruct i; auto.\n apply IHn; omega.\nQed.\n\n\nHint Resolve isbyteZ_sublist.\n\n\nLemma split2_data_block:\n  forall  {cs: compspecs}  n sh data d,\n  (0 <= n <= Zlength data)%Z ->\n  data_block sh data d =\n  (data_block sh (sublist 0 n data) d *\n   data_block sh (sublist n (Zlength data) data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc n] d))%logic.\nProof.\n  intros.\n  unfold data_block. simpl. normalize.\n  f_equal. f_equal.\n  apply prop_ext.\n  split; intro. split; apply Forall_sublist; auto.\n  erewrite <- (sublist_same 0 (Zlength data)); auto.\n  rewrite (sublist_split 0 n) by omega.\n  apply Forall_app; auto.\n  rewrite <- !sublist_map.\n  unfold tarray.\n  rewrite split2_data_at_Tarray_tuchar with (n1:=n) by (autorewrite with sublist; auto).\n  autorewrite with sublist.\n  reflexivity.\nQed.\n\nLemma split3_data_block:\n  forall  {cs: compspecs} lo hi sh data d,\n  0 <= lo <= hi ->\n  hi <= Zlength data  ->\n  data_block sh data d =\n  (data_block sh (sublist 0 lo data) d *\n   data_block sh (sublist lo hi data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc lo] d) *\n   data_block sh (sublist hi (Zlength data) data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc hi] d))%logic.\nProof.\n  intros.\n  unfold data_block. simpl. normalize.\n  f_equal. f_equal.\n  apply prop_ext.\n  split; intro. split3; apply Forall_sublist; auto.\n  erewrite <- (sublist_same 0 (Zlength data)); auto.\n  rewrite (sublist_split 0 lo (Zlength data)) by omega.\n  rewrite (sublist_split lo hi (Zlength data)) by omega.\n  destruct H1 as [? [? ?]].\n  repeat (apply Forall_app; split);  auto.\n  rewrite <- !sublist_map.\n  unfold tarray.\n  rewrite split3_data_at_Tarray_tuchar with (n1:=lo)(n2:=hi) by (autorewrite with sublist; auto).\n  autorewrite with sublist.\n  reflexivity.\nQed.\n\nGlobal Opaque WORD.\n\nLemma S256abs_data:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_data (S256abs hashed data) = data.\nProof.\nintros. unfold S256abs, s256a_data.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\ndestruct H as [n ?].\nrewrite H.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\npose proof (Zlength_nonneg data).\nrewrite sublist_app2; rewrite Zlength_intlist_to_Zlist; rewrite H;\n rewrite <- Z.mul_assoc; change (LBLOCKz * 4)%Z with CBLOCKz.\napply sublist_same.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega. omega.\nomega.\nrewrite Z.div_add_l by  omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.\nsplit; [ | omega].\napply Z.mul_nonneg_nonneg.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\ndestruct H0; auto.\npose proof (Zlength_nonneg hashed).\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nomega.\nomega.\nQed.\n\nLemma S256abs_hashed:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_hashed (S256abs hashed data) = hashed.\nProof.\nintros;  unfold S256abs, s256a_hashed.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\ndestruct H as [n ?].\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\npose proof (Zlength_nonneg data).\nrewrite sublist_app1; rewrite ?Zlength_intlist_to_Zlist;\n  rewrite H.\nrewrite sublist_same; try omega.\napply intlist_to_Zlist_to_intlist.\nrewrite Zlength_intlist_to_Zlist.\n  rewrite H.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nsplit; [omega | ].\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\nsimpl.\ndestruct H0.\npose proof (Zlength_nonneg hashed).\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nomega.\nrewrite Z.add_0_r.\napply Z.mul_nonneg_nonneg; auto.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nQed.\n\nLemma s256a_hashed_divides:\n  forall a, (LBLOCKz | Zlength (s256a_hashed a)).\nProof.\nintros. unfold s256a_hashed.\nexists (Zlength a / CBLOCKz)%Z.\nerewrite Zlength_Zlist_to_intlist; [reflexivity |].\nrewrite Zlength_sublist.\nrewrite (Z.mul_comm WORD).\nrewrite <- Z.mul_assoc.\nchange (LBLOCKz * WORD)%Z with CBLOCKz.\nomega.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nQed.\n\nLemma s256a_data_len:\n  forall a: s256abs,\n  Zlength (s256a_data a) = Zlength a mod CBLOCKz.\nProof.\nintros.\nunfold s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nrewrite H0.\nrewrite Zlength_sublist; try omega.\nsplit; try omega.\napply Z.mul_nonneg_nonneg.\napply Z.div_pos.\napply Zlength_nonneg.\nomega. omega.\nQed.\n\nLemma s256a_data_Zlength_less:\n  forall a, Zlength (s256a_data a) < CBLOCKz.\nProof.\nintros.\nrewrite s256a_data_len.\napply Z_mod_lt.\nrewrite CBLOCKz_eq; omega.\nQed.\n\nLemma hashed_data_recombine:\n  forall a,\n     Forall isbyteZ a ->\n    intlist_to_Zlist (s256a_hashed a) ++ s256a_data a = a.\nProof.\nintros. rename H into BYTES.\nunfold s256a_hashed, s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\nrewrite Zlist_to_intlist_to_Zlist.\nrewrite sublist_rejoin.\nautorewrite with sublist. auto.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nrewrite Zlength_sublist.\nrewrite Z.sub_0_r.\napply Z.divide_mul_r.\nexists LBLOCKz. reflexivity.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nomega.\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\napply Forall_sublist.\nauto.\nQed.\n\nDefinition bitlength (hashed: list int) (data: list Z) : Z :=\n   ((Zlength hashed * WORD + Zlength data) * 8)%Z.\n\nLemma bitlength_eq:\n  forall hashed data,\n  bitlength hashed data = s256a_len (S256abs hashed data).\nProof.\nintros.\nunfold bitlength, s256a_len, S256abs.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\nreflexivity.\nQed.\n\nLemma S256abs_recombine:\n forall a, Forall isbyteZ a ->\n    S256abs (s256a_hashed a) (s256a_data a) = a.\nProof.\nintros.\napply hashed_data_recombine; auto.\nQed.\n\nLemma Zlist_to_intlist_app:\n  forall a b,\n  (WORD | Zlength a) ->\n   Zlist_to_intlist (a++b) = Zlist_to_intlist a ++ Zlist_to_intlist b.\nProof.\nintros.\ndestruct H as [na H].\nrewrite <- (Z2Nat.id na) in H.\nFocus 2.\ndestruct (zlt na 0); try omega.\nassert (na * WORD < 0); [apply Z.mul_neg_pos; auto | ].\npose proof (Zlength_nonneg a); omega.\nrevert a H; induction (Z.to_nat na); intros.\nsimpl in H. destruct a. simpl. auto. rewrite Zlength_cons in H.\npose proof (Zlength_nonneg a); omega.\nrewrite inj_S in H.\nunfold Z.succ in H. rewrite Z.mul_add_distr_r in H.\nchange (1*WORD)%Z with 4 in H.\nassert (Zlength a >= 4).\nassert (0 <= Z.of_nat n * WORD); [ | omega].\napply Z.mul_nonneg_nonneg; try omega.\nchange WORD with 4%Z; omega.\ndo 4 (destruct a; [rewrite Zlength_nil in H0; omega | rewrite Zlength_cons in H,H0  ]).\nsimpl.\ndo 4 f_equal. apply IHn.\nomega.\nQed.\n\nLemma round_range:\n forall {A} (a: list A) (N:Z),\n  N > 0 ->\n   0 <= Zlength a / N * N <= Zlength a.\nProof.\nintros.\nsplit.\napply Z.mul_nonneg_nonneg; auto; try omega.\napply Z.div_pos; try omega.\napply Zlength_nonneg.\npose proof (Zmod_eq (Zlength a) N H).\npose proof (Z_mod_lt (Zlength a) N H).\nomega.\nQed.\n\nLemma CBLOCKz_gt: CBLOCKz > 0.\nProof. rewrite CBLOCKz_eq; omega.\nQed.\n\nLemma Zlist_to_intlist_inj:\n  forall a b,\n   (WORD | Zlength a) ->\n   (WORD | Zlength b) ->\n   Forall isbyteZ a ->\n   Forall isbyteZ b ->\n   Zlist_to_intlist a = Zlist_to_intlist b ->\n   a=b.\nProof.\nintros.\nrewrite <- (Zlist_to_intlist_to_Zlist a) by auto.\nrewrite H3.\napply Zlist_to_intlist_to_Zlist; auto.\nQed.\n\nDefinition update_abs (incr: list Z) (a: list Z) (a': list Z) :=\n    a' = a ++ incr.\n\nLemma update_abs_eq:\n  forall msg a a',\n Forall isbyteZ (a++msg) ->\n Forall isbyteZ a' ->\n (update_abs msg a a' <->\n  exists blocks,\n    s256a_hashed a' = s256a_hashed a ++ blocks /\\\n    s256a_data a ++ msg = intlist_to_Zlist blocks ++ s256a_data a').\nProof.\nintros. rename H0 into H'.\nunfold update_abs.\nassert (0 <= 0 <= Zlength a / CBLOCKz * CBLOCKz). {\n split; [omega | ].\n apply Z.mul_nonneg_nonneg.\n apply Z.div_pos.\n apply Zlength_nonneg.\n rewrite CBLOCKz_eq; omega.\n rewrite CBLOCKz_eq; omega.\n}\npose proof (round_range a _ CBLOCKz_gt).\npose proof (round_range (a++msg) _ CBLOCKz_gt).\nsplit; intro.\n*\nsubst a'.\nunfold s256a_hashed.\nexists (Zlist_to_intlist\n            (sublist (Zlength a / CBLOCKz * CBLOCKz) (Zlength (a++msg) / CBLOCKz * CBLOCKz)\n                  (a++msg))).\nsplit.\n +\n rewrite (sublist_split 0 (Zlength a / CBLOCKz * CBLOCKz)); auto.\n rewrite Zlist_to_intlist_app.\n f_equal.\n rewrite sublist_app1; auto. omega.\n rewrite Zlength_sublist; auto.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n rewrite Zlength_app.\n pose proof (Zlength_nonneg msg); omega.\n split; [ | apply round_range; apply CBLOCKz_gt].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n +\n rewrite Zlist_to_intlist_to_Zlist.\n Focus 2. rewrite Zlength_sublist. rewrite <- Z.mul_sub_distr_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [Omega1 | ].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n apply round_range. apply CBLOCKz_gt.\n 2: apply Forall_sublist; auto.\n unfold s256a_data.\n destruct (zlt   (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) (Zlength a) ).\n  -\n   rewrite sublist_app1; try omega.\n   rewrite (sublist_split (Zlength (a ++ msg) / CBLOCKz * CBLOCKz)\n               (Zlength a) (Zlength (a ++ msg))); try omega.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2 by omega.\n   autorewrite with sublist.\n   rewrite (sublist_same 0) by omega.\n   rewrite <- app_ass. f_equal.\n   rewrite sublist_rejoin; try omega. auto.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  Omega1.\n  rewrite Zlength_app in l; omega.\n  rewrite Zlength_app; Omega1.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  rewrite Zlength_app; Omega1.\n -\n   rewrite (sublist_split (Zlength a / CBLOCKz * CBLOCKz) (Zlength a)\n                  (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) ); auto.\n   rewrite app_ass.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2; try omega.\n   rewrite Z.sub_diag.\n   f_equal.\n   rewrite sublist_app2; try omega.\n   rewrite sublist_rejoin.\n   autorewrite with sublist. auto.\n   omega.\n  split; try omega. rewrite Zlength_app; Omega1.\n   omega.\n*\ndestruct H3 as [blocks [? ?]].\nmatch type of H3 with ?A = ?B =>\n  assert (Zlength A * WORD = Zlength B * WORD)%Z by congruence\nend.\nmatch type of H4 with ?A = ?B =>\n  assert (sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ A =\n              sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ B) by congruence\nend.\nunfold s256a_hashed, s256a_data in *.\nrewrite <- app_ass in H6.\nrewrite sublist_rejoin in H6 by omega.\nrewrite sublist_same in H6 by omega.\nrewrite H6.\nclear H6 H4.\nrewrite <- (sublist_same 0 (Zlength a') a') at 1; auto.\nrewrite <- app_ass.\nrewrite (sublist_split 0 (Zlength a' / CBLOCKz * CBLOCKz) (Zlength a')); try omega.\nf_equal.\napply Zlist_to_intlist_inj.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n rewrite Zlength_app.\n apply Z.divide_add_r.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n exists (Zlength blocks).\n apply Zlength_intlist_to_Zlist.\n apply Forall_sublist; auto.\n apply Forall_app; split.\n apply Forall_app in H; destruct H;\n apply Forall_sublist; auto.\n apply isbyte_intlist_to_Zlist.\n rewrite H3.\n rewrite Zlist_to_intlist_app. f_equal.\n symmetry; apply intlist_to_Zlist_to_intlist.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n auto.\n omega.\n split; [clear; omega |].\n apply round_range; apply CBLOCKz_gt.\n split; [ | clear; omega].\n apply round_range; apply CBLOCKz_gt.\nQed.\n\nLemma array_at_memory_block:\n forall {cs: compspecs} sh t gfs lo hi v p n,\n  sizeof (nested_field_array_type t gfs lo hi) = n ->\n  lo <= hi ->\n  array_at sh t gfs lo hi v p |--\n  memory_block sh n (field_address0 t (ArraySubsc lo :: gfs) p).\nProof.\nintros.\nrewrite  array_at_data_at by auto.\nnormalize.\nunfold at_offset.\nrewrite field_address0_offset by auto.\nsubst n.\napply data_at_memory_block.\nQed.\n\nHint Extern 2 (array_at _ _ _ _ _ _ _ |-- memory_block _ _ _) =>\n   (apply array_at_memory_block; try reflexivity; try omega) : cancel.\n\n", "meta": {"author": "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/sha/sha_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1950763820913916}}
{"text": "From iris.proofmode Require Import tactics.\nFrom mwp.mwp_modalities Require Import mwp_step_fupd.\nFrom mwp.mwp_modalities.ni_logrel Require Import mwp_left mwp_right ni_logrel_lemmas.\nFrom logrel_ifc.lambda_sec Require Export lattice fundamental_binary notation.\n\n(* OBS: high observer *)\nLocal Instance tpSecurityLatticeH : SecurityLattice tplabel := { \u03b6 := H }.\n\n(* This examples shows that it does not matter if we write H information to a L\n     location if the observer is H---it is all the same for the observer. *)\n\n(* low := !high *)\nDefinition prog_explicit_flow :=\n  ($0 <- !$1)%E.\n\n(* ... and the same is the case for implicit flows; the observer can see the\n     secret, so both conditionals will always go into the same branch. *)\n\n(* if !high then low := true else low := false *)\nDefinition prg_implicit_flow :=\n  (if: !$1 then $0 <- true else $0 <- false)%E.\n\nSection related.\n  Context `{!secG \u03a3}.\n\n  Lemma prg_high_to_low_bi_related :\n    [TRef (TBool @ (LLabel L)) @ (LLabel L); TRef (TBool @ (LLabel H)) @ (LLabel L)] \u22a8\n     prog_explicit_flow \u2264\u2097 prog_explicit_flow : TUnit @ (LLabel L).\n  Proof.\n    iIntros (\u03b8 \u03c1 vvs Hpers) \"[#Hcoh Henv]\".\n    iDestruct (interp_env_length with \"Henv\") as %?.\n    do 2 (destruct vvs; [done|]).\n    iDestruct (interp_env_cons with \"Henv\") as \"[Hlow Henv']\".\n    iDestruct (interp_env_cons with \"Henv'\") as \"[Hhigh _]\".\n    rewrite !interp_sec_def.\n    rewrite !bool_decide_eq_true_2 // !interp_ref_def.\n    iDestruct \"Hlow\" as ([l1 l2]) \"[-> #Hlow] /=\".\n    iDestruct \"Hhigh\" as ([l1' l2']) \"[-> #Hhigh] /=\".\n    rewrite /interp_ref_inv /= !loc_to_val.\n    iApply (mwp_left_strong_bind _ _ (fill [StoreRCtx _]) (fill [StoreRCtx _])); cbn.\n    iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n    iInv (nroot.@(l1',l2')) as \"Hl\" \"HcloseI\".\n    iDestruct \"Hl\" as (v1 v2) \"(Hl1 & Hl2 & #H\u03c4) /=\".\n    iModIntro.\n    iApply ((@mwp_step_fupd_load _ secG_un_left) with \"[//]\").\n    iFrame. iIntros \"!> Hl1\".\n    iApply ((@mwp_fupd_load _ secG_un_right) with \"[//]\").\n    iFrame. iIntros \"Hl2\". ubools.\n    rewrite bool_decide_eq_true_2 //=.\n    iDestruct \"H\u03c4\" as (? b) \"(-> & -> & ->)\".\n    iMod (\"HcloseI\" with \"[Hl1 Hl2]\") as \"_\".\n    { iNext. iExists _,_. iFrame. ubools.\n      rewrite bool_decide_eq_true_2 //. eauto. }\n    iModIntro.\n    iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n    iInv (nroot.@(l1,l2)) as \"Hl\" \"HcloseI\".\n    iDestruct \"Hl\" as (v1 v2) \"(Hl1 & Hl2 & #H\u03c4) /=\".\n    iModIntro.\n    rewrite !bool_to_val.\n    iApply (@mwp_step_fupd_store _ secG_un_left); [done|].\n    iFrame. iIntros \"!> Hl1\".\n    iApply (@mwp_fupd_store _ secG_un_right); [done|].\n    iFrame. iIntros \"Hl2\".\n    rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=.\n    iDestruct \"H\u03c4\" as (? b') \"(-> & -> & ->)\".\n    iMod (\"HcloseI\" with \"[Hl1 Hl2]\") as \"_\".\n    { iNext. iExists _,_. iFrame. ubools.\n      rewrite bool_decide_eq_true_2 //. eauto. }\n    rewrite interp_sec_def interp_unit_def bool_decide_eq_true_2 //.\n  Qed.\n\n  Lemma prg_high_ctx_to_low :\n    [TRef (TBool @ (LLabel L)) @ (LLabel L); TRef (TBool @ (LLabel H)) @ (LLabel L)] \u22a8\n    prg_implicit_flow \u2264\u2097 prg_implicit_flow : TUnit @ (LLabel L).\n  Proof.\n    iIntros (\u03b8 \u03c1 vvs Hpers) \"[#Hcoh Henv]\".\n    iDestruct (interp_env_length with \"Henv\") as %?.\n    do 2 (destruct vvs; [done|]).\n    iDestruct (interp_env_cons with \"Henv\") as \"[Hlow Henv']\".\n    iDestruct (interp_env_cons with \"Henv'\") as \"[Hhigh _]\".\n    rewrite !interp_sec_def.\n    rewrite !bool_decide_eq_true_2 // !interp_ref_def.\n    iDestruct \"Hlow\" as ([l1 l2]) \"[-> #Hlow] /=\".\n    iDestruct \"Hhigh\" as ([l1' l2']) \"[-> #Hhigh] /=\".\n    rewrite /interp_ref_inv /= !loc_to_val !bool_to_val.\n    iApply (mwp_left_strong_bind _ _ (fill [IfCtx _ _]) (fill [IfCtx _ _])).\n    iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n    iInv (nroot.@(l1',l2')) as \"Hl\" \"HcloseI\".\n    iDestruct \"Hl\" as (v1 v2) \"(Hl1 & Hl2 & #H\u03c4) /=\".\n    iModIntro.\n    iApply ((@mwp_step_fupd_load _ secG_un_left) with \"[//]\").\n    iFrame. iIntros \"!> Hl1\".\n    iApply ((@mwp_fupd_load _ secG_un_right) with \"[//]\").\n    iFrame. iIntros \"Hl2\".\n    rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=.\n    iDestruct \"H\u03c4\" as (? b) \"(-> & -> & ->)\".\n    iMod (\"HcloseI\" with \"[Hl1 Hl2]\") as \"_\".\n    { iNext. iExists _,_. iFrame. ubools.\n      rewrite bool_decide_eq_true_2 //=. eauto. }\n    iModIntro.\n    destruct b.\n    - iApply mwp_left_pure_step; [done|].\n      iApply mwp_left_pure_step_index; [done|].\n      iNext.\n      iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n      iInv (nroot.@(l1,l2)) as \"Hl\" \"HcloseI\".\n      iDestruct \"Hl\" as (v1 v2) \"(Hl1 & Hl2 & #H\u03c4) /=\".\n      iModIntro. rewrite !bool_to_val.\n      iApply (@mwp_step_fupd_store _ secG_un_left); [done|].\n      iFrame. iIntros \"!> Hl1\".\n      iApply (@mwp_fupd_store _ secG_un_right); [done|].\n      iFrame. iIntros \"Hl2\".\n      rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=.\n      iDestruct \"H\u03c4\" as (? b') \"(-> & -> & ->)\".\n      iMod (\"HcloseI\" with \"[Hl1 Hl2]\") as \"_\".\n      { iNext. iExists _,_. iFrame. ubools.\n        rewrite bool_decide_eq_true_2 //. eauto. }\n      rewrite interp_sec_def interp_unit_def bool_decide_eq_true_2 //.\n    - iApply mwp_left_pure_step; [done|].\n      iApply mwp_left_pure_step_index; [done|].\n      iNext.\n      iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n      iInv (nroot.@(l1,l2)) as \"Hl\" \"HcloseI\".\n      iDestruct \"Hl\" as (v1 v2) \"(Hl1 & Hl2 & #H\u03c4) /=\".\n      iModIntro. rewrite !bool_to_val.\n      iApply (@mwp_step_fupd_store _ secG_un_left); [done|].\n      iFrame. iIntros \"!> Hl1\".\n      iApply (@mwp_fupd_store _ secG_un_right); [done|].\n      iFrame. iIntros \"Hl2\".\n      rewrite interp_sec_def interp_bool_def bool_decide_eq_true_2 //=.\n      iDestruct \"H\u03c4\" as (? b') \"(-> & -> & ->)\".\n      iMod (\"HcloseI\" with \"[Hl1 Hl2]\") as \"_\".\n      { iNext. iExists _,_. iFrame. ubools.\n        rewrite bool_decide_eq_true_2 //. eauto. }\n      rewrite interp_sec_def interp_unit_def bool_decide_eq_true_2 //.\n  Qed.\n\nEnd related.\n", "meta": {"author": "logsem", "repo": "iris-tini", "sha": "1f3440dc1a992329635a25b1fd81703cd058c817", "save_path": "github-repos/coq/logsem-iris-tini", "path": "github-repos/coq/logsem-iris-tini/iris-tini-1f3440dc1a992329635a25b1fd81703cd058c817/theories/examples/high_observer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3812195592260441, "lm_q1q2_score": 0.19507637849396978}}
{"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(** Architecture-dependent parameters for PowerPC *)\n\nRequire Import ZArith.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\n\nDefinition big_endian := true.\n\nNotation align_int64 := 8%Z (only parsing).\nNotation align_float64 := 8%Z (only parsing).\n\nProgram Definition default_pl_64 : bool * nan_pl 53 :=\n  (false, iter_nat 51 _ xO xH).\n\nDefinition choose_binop_pl_64 (s1: bool) (pl1: nan_pl 53) (s2: bool) (pl2: nan_pl 53) :=\n  false.                        (**r always choose first NaN *)\n\nProgram Definition default_pl_32 : bool * nan_pl 24 :=\n  (false, iter_nat 22 _ xO xH).\n\nDefinition choose_binop_pl_32 (s1: bool) (pl1: nan_pl 24) (s2: bool) (pl2: nan_pl 24) :=\n  false.                        (**r always choose first NaN *)\n\nDefinition float_of_single_preserves_sNaN := true.\n\nGlobal Opaque big_endian\n              default_pl_64 choose_binop_pl_64\n              default_pl_32 choose_binop_pl_32\n              float_of_single_preserves_sNaN.\n\n(** Can we use the 64-bit extensions to the PowerPC architecture? *)\nParameter ppc64: bool.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/compcert/powerpc/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.19499282342423352}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef3.Specs.table_destroy3.\nRequire Import TableDataOpsRef3.LowSpecs.table_destroy3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_destroy_spec\n       table_destroy2_spec\n    .\n\n  Lemma table_destroy3_spec_exists:\n    forall habd habd'  labd g_rd map_addr rtt_addr level res\n      (Hspec: table_destroy3_spec g_rd map_addr rtt_addr level habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', table_destroy3_spec0 g_rd map_addr rtt_addr level labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq granule_fill_table.fill_table.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rd.\n    unfold table_destroy3_spec, table_destroy3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table, table_destroy.destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. unfold query_oracle. autounfold. simpl.\n      destruct Hrel. grewrite. destruct valid_lo0. erewrite Hright_log_nil. simpl.\n      repeat (grewrite; try simpl_htarget; simpl). rewrite <- H1, <- H0. simpl.\n      (eexists; split; [reflexivity| constructor; simpl; try assumption; try reflexivity]).\n      eapply RightLogMover.\n      apply walk_right. omega. omega. apply RightLogOracle.\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table, table_destroy.destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. unfold query_oracle. autounfold. simpl.\n      destruct Hrel. grewrite. destruct valid_lo0. erewrite Hright_log_nil. simpl.\n      repeat (grewrite; try simpl_htarget; simpl). rewrite <- H1, <- H0. simpl.\n      (eexists; split; [reflexivity| constructor; simpl; try assumption; try reflexivity]).\n      eapply RightLogMover.\n      apply walk_right. omega. omega. apply RightLogOracle.\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table, table_destroy.destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. unfold query_oracle. autounfold. simpl.\n      destruct Hrel. grewrite. destruct valid_lo0. erewrite Hright_log_nil. simpl.\n      repeat (grewrite; try simpl_htarget; simpl). rewrite <- H1, <- H0. simpl.\n      (eexists; split; [reflexivity| constructor; simpl; try assumption; try reflexivity]).\n      eapply RightLogMover.\n      apply walk_right. omega. omega. apply RightLogOracle.\n      autounfold. unfold query_oracle. autounfold. simpl.\n      destruct Hrel. grewrite. destruct valid_lo0. erewrite Hright_log_nil. simpl.\n      repeat (grewrite; try simpl_htarget; simpl). rewrite <- H1, <- H0. simpl.\n      (eexists; split; [reflexivity| constructor; simpl; try assumption; try reflexivity]).\n      eapply RightLogMover.\n      apply walk_right. omega. omega. apply RightLogOracle.\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/table_destroy3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.1947359095582749}}
{"text": "(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\nRequire Import securite.\n\nLemma POinvprel5 :\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 rel5\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 inv1, invP, rel5 in |- *. intros Inv0 know_Kas_Kbs know_Kab and1.\nelim know_Kas_Kbs; intros know_Kas know_Kbs.\nelim and1; intros eq_l0 t1.\nclear Inv0 know_Kas_Kbs and1 t1.\nrewrite eq_l0.\nunfold triple in |- *.\napply D2.\nsimpl in |- *.\nrepeat apply C3 || apply C4.\nelim (D_dec d0 d1).\n\n(* (d0, d1) = (Aid, Bid) *)\nintros eq_d0_d1; elim eq_d0_d1; intros eq_d0 eq_d1.\nrewrite eq_d0.\nrewrite eq_d1.\napply C1. apply C1. \napply D1.\napply EP1 with rngDDKKeyAB.\napply equivnknown1 with (B2C (K2B (KeyX Bid))) (l ++ rngDDKKeyAB).\napply equivS4 with (l ++ rngDDKKeyABminusKab ++ rngDDKKeyAB).\nelim l; simpl in |- *; auto with otway_rees.\nexact rngs.\nrewrite (app_ass l rngDDKKeyABminusKab rngDDKKeyAB).\nelim l; elim rngDDKKeyABminusKab; elim rngDDKKeyAB; simpl in |- *;\n auto with otway_rees.\nauto with otway_rees.\nassumption.\ndiscriminate.\ndiscriminate.\n\n(* (d0, d1) <> (Aid, Bid) *)\nintros not_eq_d0_d1.\nrepeat apply C2 || apply C3 || apply C4.\napply\n equivncomp\n  with\n    (Encrypt (Pair (B2C (D2B d3)) (B2C (K2B (KeyAB d0 d1)))) (KeyX d1)\n     :: B2C (K2B (KeyAB d0 d1)) :: l ++ rngDDKKeyABminusKab).\napply equivS2.\nrepeat apply C2 || apply C3 || apply C4.\napply equivncomp with (B2C (K2B (KeyAB d0 d1)) :: l ++ rngDDKKeyABminusKab).\napply AlreadyIn1; unfold In in |- *; left; auto with otway_rees.\napply equivncomp with (l ++ rngDDKKeyABminusKab).\napply AlreadyIn1; apply in_or_app; right. \napply rngDDKKeyABminusKab1; apply KeyAB1.\ntauto.\napply D1; assumption.\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/invprel5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.19473589676484807}}
{"text": "Require Import Program Equality Ring Lia Omega.\nFrom Coq Require Import ssreflect ssrfun ssrbool.\nFrom mathcomp Require Import seq eqtype ssrnat.\nFrom istari Require Import lemmas0\n     source subst_src rules_src basic_types0 basic_types\n     help subst_help0 subst_help trans derived_rules embedded_lemmas proofs.\nFrom istari Require Import Sigma Tactics\n     Syntax Subst SimpSub Promote Hygiene\n     ContextHygiene Equivalence Equivalences.\nFrom istari Require Import Rules Defined DefsEquiv.\n\nTheorem total G E A: of_m G E A ->\n                exists ebar, trans G E A ebar.\n  intros He. induction He.\n  {exists (lam (lam (gamma_nth (var 0) i))). constructor. assumption.\n  }\n  { exists (lam (lam nzero)). constructor. \n  }\n  {\n    destruct IHHe as [mbar Hm].\n    exists (lam (lam (nsucc (app (app (subst (sh 2) mbar) (var 1)) (var 0))))).\n    constructor. assumption.\n  }\n  { destruct IHHe as [Et Hm].\n    exists \n      (lam (lam (lam (lam (lam\n                             (app (app (shift 5 Et) (var 2))\n                                        (ppair (var 0) (move_gamma G (var 4) (var 2)\n                                                                   (var 1) (var 3)))\n\n            )))))). constructor. assumption.\n  }\n  { destruct IHHe1 as [Et1 Het1]. destruct IHHe2 as [Et2 Het2].\n    exists ( lam (lam \n                   (let Et1 := shift 2 Et1 in\n                   let Et2 := shift 2 Et2 in\n                   let l := (var 1) in\n                   let g := (var 0) in\n                   let arg := (app (app Et2 l) g) in\n                   (app (app (app (app (app Et1 l) g) l) (make_subseq_refl l)) arg)\n                ))). eapply t_ap. apply Het1. assumption.\n  }\n  { destruct IHHe as [Et Het].\n    exists \n          (lam (lam (lam (lam (lam \n                                 (let l1 := var 4 in\n                                  let g := var 3 in\n                                  let l := var 2 in\n                            let m := var 1 in\n                            let s := var 0 in\n                            let e := move_app A l1 l m (app (app (shift 5 Et) l1) g) in\n                            inl (\n                                (ppair\n                                   l\n                                   (ppair (ppair (make_subseq_refl l) s) e))\n                            )\n\n          )))))). apply t_ret. assumption.\n  }\n  { destruct IHHe1 as [Et1 Het1]. destruct IHHe2 as [Et2 Het2].\nexists ( lam (lam ( lam ( (*l1 : = 2, g: Gamma_at G = 1 l :=0 *) lam ( (*l1 := 3, l := 1, m := 0*)\n                           lam ( (*l1 := 4, l := 2, m := 1, s := 0*)\n                               let l1 := (var 4) in\n                               let g := (var 3) in\n                               let l := (var 2) in\n                               let m := (var 1) in\n                               let s := (var 0) in\nlet btarg := app (app (app (app (app (shift 5 Et1) l1) g) l) m) s in\nmake_bind btarg ( lam (*l1 := 5, l := 3, m := 2, s := 1, z1 := 0*)\n              (\n                               let z1 := (var 0) in (*basically added 6 vars to my context*)\n                               let lv := (picomp1 z1) in\n                               let mv := (picomp2 z1) in\n                               let sv := (picomp3 z1) in\n                               let x' := (picomp4 z1) in\n                               let l := (shift 1 l) in (*l = 3*)\n                                                                        (*\nin the context (A :: G) Et2 is a function which wants a length\nin the context G, Et2 has var 0 free. In context G, (lam Et2) is a function which wants an\nx, then a length\nmake the lambda first before you introduce other variables and it's still the first var\nthat. you want to bind \n                                                                         *)\n                               (*x' lam, floating around in the context as var 0*)\n(*et2's var 0 is the x.\n maybe plan is bring the subst outside the lamda so that you type check the lamda in the\n weakened context*)                                                      \n\n                               let btarg :=\n                                   (*Et2 Gamma@V lv*)\n                                   app (app (shift 6 Et2)\n                                           lv \n                                            )\n                                            (*5: Gamma_at G w\n                                              move 5: Gamma_at G v\n                                          <x, 5> : Gamma_at A::G v*)\n                       (ppair x' (move_gamma G\n                                             (var 5) lv\n                       (make_subseq_trans (var 5) (var 3) lv (var 2) mv)\n                       (var 4)))                                                 in\n                               let e2bar' := app (app (app btarg lv) (make_subseq_refl lv) )\n                                                 (*v, z1 <= v, z1*)\n                                                 sv in\n                               make_bind e2bar' (lam ( (*l = var 4*)\n                                                    let z2 := (var 0) in\n                                                    ret_a (ppair (picomp1 z2)\n                                                                 (ppair (ppair\n             (make_subseq_trans (shift 1 l) (shift 1 lv) (picomp1 z2) (picomp2 (shift 1 z1)) (picomp2 z2))\n                                                                           (*z2 \\circ z1*)\n                                                      (picomp3 z2)) (picomp4 z2))                         \n                                                        )\n                                               ))\n              )\n\n          )\n\n    ))\n  )))). eapply t_bind. apply Het1. assumption.\n}\n  {\n    destruct IHHe as [Et Het].\n    exists (lam (lam (lam (lam ( lam ( (*l1, g, l, m, s*)\n         let l := var 2 in                                                        \n         let m1 := (make_consb_subseq l) in (*u <= u1, consb subseq*)\n         let p1 := (ppair m1\n                         (lam (lam ( lam ( (*making a value of type store U1, lambdas go l2, m2, i*)\n                                         let l1 := var 7 in\n                                         let g := var 6 in\n                                         let l := var 5 in\n                                         let m := var 4 in\n                                         let s := var 3 in\n                                         let l2 := var 2 in\n                                         let m2 := var 1 in\n                                         let i := var 0 in\n                                         let x := app (app (shift 8 Et) l1) g in\n                                         let m12 := (make_subseq_trans l (nsucc l)\n                                                                      l2 (subst (sh 3) m1) m2) (*U <=  U1 <= U2*)\n                                         in \n                                         let m02 := make_subseq_trans l1 l l2 m m12 in (*W <= U + U <= U2 = W <= U2*)\n                                         \n                                         (*m12 o m : W <= U2*)\n                                         bite (ltb_app i l)\n                                              (app (app (app s l2) m12) i) (*move value in s:store(U) to U2*)\n                                              (next (move_app A\n                                                              l1 l2\n                                                              m02 x)) (*move x to be : |> A @ U2*)\n                                               ))\n                         ))\n         ) in\n             ret_a (ppair (nsucc l) (*length of new world*)\n                          (ppair p1 (*new word is accessible from current world, *)\n                                 (ppair l (ppair (app leq_refl_fn (nsucc l)) (lam triv)) (*ref A @ new world*)\n                                 ) \n                          )\n                   ))))))). constructor. assumption.\n\n  }\n  { destruct IHHe1 as [Et Het1]. destruct IHHe2 as [Rt Het2].\n    exists \n            (lam (lam (lam (lam ( lam ( (*l = 4, g = 3, l1 = 2, m = 1, s1 = 0*)\n                                      let l := var 4 in\n                                      let m := var 1 in\n                                      let l1 := var 2 in\n                                      let g := var 3 in\n                                      let s1 := var 0 in \n                                      let ref := move_app (reftp_m T)\n                                                          (var 4) (var 2)\n                                                          m (app (app (shift 5 Rt) l) g) in\n                                      let i := ppi1 ref in\n                                      let p := ppi2 ref in\n                                      let store_u1  := lam (lam (lam (*l2 = 2, m1 = 1,j = 0*)\n                                                                  (\n                                                                    let j := (var 0) in\n                                                                    let l2 := var 2 in\n                                                                    let m1 := var 1 in\n                                                                    let i := shift 3 i in\n                                                                    let l := shift 3 l in\n                                                                    let l1 := shift 3 l1 in\n                                                                    let g := shift 3 g in\n                                                                    let m := shift 3 m in\n                                                                    bite\n                                                                      (app (eq_b j) i)\n                                                                      (next (move_app T\n                                                                                      l\n                                                                                      l2\n   (make_subseq_trans l l1 l2 m m1)\n                                                                    (app (app (shift 8 Et) l) g)))\n                                                                      (app (app (app (shift 3 s1) l2) m1) j)\n                                                                 ))) in\n                                      ret_a (ppair l1\n                                                   (ppair\n                                                      (ppair (make_subseq_refl l1) (*refl u1*)\n                                                             store_u1)\n                                                      triv))\n            )))))).\n    constructor. assumption. assumption. }\n  { destruct IHHe as [Rt Het]. \n    exists (lam (lam (lam (lam ( lam (                                       let l := var 4 in\n                                      let g := var 3 in\n                                      let l1 := var 2 in\n                                      let m := var 1 in\n                                      let s := var 0 in\n                                      let ref := move_app (reftp_m T) l l1\n                                                          m (app (app (shift 5 Rt) l) g) in\n                                      let i := ppi1 ref in\n                                      let e := prev (app (app (app s l1)\n                                                (make_subseq_refl l1)) i) in\n                                     (inr (next (inl (ppair\n                                                                            l1\n                                                                            (ppair (\n                                                                                 ppair (make_subseq_refl l1)\n                                                                                       s)\n                                                                                   e)\n                                                                               )\n                                    ))))\n            ))))). constructor. assumption.\n  }\n  { exists (lam (lam triv)). constructor. } Qed.\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/proofs_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.1946674914389354}}
{"text": "(** This file implements an interface to [expr] that\n ** makes star, emp, and pure assertions apparent.\n **)\n(* Require Import ExtLib.Data.Positive. *)\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Tactics.\nRequire Import BILogic Pure.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCore.Lambda.TypedFoldApp.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** NOTE: This could work on arbitrary expr's **)\nSection seplog_fold.\n  Variable typ : Type.\n  Variable RType_typ : RType typ.\n  Variable Typ2_Fun : Typ2 _ Fun.\n  Variable sym : Type.\n  Variable RSym_sym : RSym sym.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n\n  Let Expr_expr := @Expr_expr typ sym _ _ _.\n  Local Existing Instance Expr_expr.\n\n  Variable T : Type.\n  Variable SL : typ.\n\n  Record SepLogArgs : Type :=\n  { do_other : expr typ sym -> list (expr typ sym * T) -> T\n  ; do_pure : expr typ sym -> T\n  ; do_emp : T\n  ; do_star : T -> T -> T\n  }.\n\n  Record SepLogSpec : Type :=\n  { is_pure : expr typ sym -> bool\n  ; is_emp : expr typ sym -> bool\n  ; is_star : expr typ sym -> bool\n  }.\n\n  Variable sla : SepLogArgs.\n  Variable sls : SepLogSpec.\n\n  Record SepLogSpecOk (sls : SepLogSpec)\n         (OPS : ILogic.ILogicOps (typD SL))\n         (BI : BILOperators (typD SL)) : Type :=\n  { _PureOp : @PureOp (typD SL)\n  ; _Pure : @Pure _ OPS BI _PureOp\n  ; His_pure : forall e,\n                 sls.(is_pure) e = true ->\n                 forall us vs val,\n                   exprD us vs e SL = Some val ->\n                   pure val\n  ; His_emp : forall e,\n                sls.(is_emp) e = true ->\n                forall us vs,\n                  exprD us vs e SL = Some empSP\n  ; His_star : forall e,\n                 sls.(is_star) e = true ->\n                 forall us vs,\n                   exprD us vs e (tyArr SL (tyArr SL SL)) =\n                   Some match eq_sym (typ2_cast SL (tyArr SL SL)) in _ = t\n                              return t\n                        with\n                          | eq_refl =>\n                            match eq_sym (typ2_cast SL SL) in _ = t\n                                  return _ -> t\n                            with\n                              | eq_refl => sepSP\n                            end\n                        end\n  }.\n\n  Record SepLogArgsOk (R_t : expr typ sym -> T -> tenv typ -> tenv typ -> Prop) :=\n  { otherOk\n    : forall e es tus tvs,\n        @typeof_apps typ sym _ _ _ tus tvs e (List.map fst es) = Some SL ->\n        (forall x y,\n           In (x,y) es ->\n           typeof_expr tus tvs x = Some SL ->\n           R_t x y tus tvs) ->\n        R_t (apps e (List.map fst es)) (sla.(do_other) e es) tus tvs\n  ; pureOk\n    : forall e tus tvs,\n        typeof_expr tus tvs e = Some SL ->\n        sls.(is_pure) e = true ->\n        R_t e (sla.(do_pure) e) tus tvs\n  ; empOk\n    : forall e tus tvs,\n        typeof_sym e = Some SL ->\n        sls.(is_emp) (Inj e) = true ->\n        R_t (Inj e) sla.(do_emp) tus tvs\n  ; starOk\n    : forall e l r l_res r_res tus tvs,\n        typeof_sym e = Some (tyArr SL (tyArr SL SL)) ->\n        typeof_expr tus tvs l = Some SL ->\n        typeof_expr tus tvs r = Some SL ->\n        sls.(is_star) (Inj e) = true ->\n        R_t l l_res tus tvs ->\n        R_t r r_res tus tvs ->\n        R_t (apps (Inj e) (l :: r :: nil)) (sla.(do_star) l_res r_res) tus tvs\n  }.\n\n  Require Import ExtLib.Structures.Applicative.\n  Instance Applicative_Lazy : Applicative Lazy :=\n  { ap := fun _ _ f x z =>\n            match f z , x z with\n              | Some f , Some x => Some (f x)\n              | _ , _ => None\n            end\n  ; pure := fun _ x => fun _ => Some x }.\n\n  (** NOTE: This does not need to be typed! **)\n  Definition AppFullFoldArgs_SepLogArgs\n  : AppFullFoldArgs typ sym T.\n  refine\n    match sla , sls with\n      | {| do_other := do_other\n         ; do_pure := do_pure\n         ; do_star := do_star\n         ; do_emp := do_emp |}\n      , {| is_pure := is_pure\n         ; is_star := is_star\n         ; is_emp := is_emp |} =>\n        @Build_AppFullFoldArgs\n          typ sym T\n          (fun v _ _ =>\n             if is_pure (Var v) then\n               Some (do_pure (Var v))\n             else\n               if is_emp (Var v) then\n                 Some do_emp\n               else\n                 Some (do_other (Var v) nil))\n          (fun u _ _ =>\n             if is_pure (UVar u) then\n               Some (do_pure (UVar u))\n             else\n               if is_emp (UVar u) then\n                 Some do_emp\n               else\n                 Some (do_other (UVar u) nil))\n          (fun i _ _ =>\n             if is_emp (Inj i) then\n               Some do_emp\n             else\n               if is_pure (Inj i) then\n                 Some (do_pure (Inj i))\n               else\n                 Some (do_other (Inj i) nil))\n          (fun tus tvs t f fres args z =>\n             if is_star f then\n               match args with\n                 | (_,_,l) :: (_,_,r) :: nil =>\n                   match l z , r z with\n                     | Some l , Some r =>\n                       Some (do_star l r)\n                     | _ , _ => None\n                   end\n                 | _ => Some do_emp\n               end\n             else\n               let original := apps f (map (fun x => snd (fst x)) args) in\n               if is_pure original then\n                 Some (do_pure original)\n               else\n                 ap (pure (do_other f))\n                    (mapT (fun tev => let '(t,e,v) := tev in\n                                      match v tt with\n                                        | None => None\n                                        | Some v => Some (e,v)\n                                      end) args))\n          (fun tus tvs t _ e eres _ =>\n             if is_pure (Abs t e) then\n               Some (do_pure (Abs t e))\n             else\n               if is_emp (Abs t e) then\n                 Some do_emp\n               else\n                 Some (do_other (Abs t e) nil))\n    end.\n  Defined.\n\n(* TODO(gmalecha): Port the proof!\n  Section sound.\n    Hypothesis BILOps : BILOperators (typD nil SL).\n    Context R_t `{slaok : SepLogArgsOk R_t}.\n\n    Lemma atomic_ok\n    : forall ts (tus tvs : tenv typ) e (t : typ),\n        typeof_expr ts tus tvs e = Some t ->\n        t = SL ->\n        R_t e (sla.(do_other) e nil) tus tvs.\n    Proof.\n      destruct slaok. simpl; intros. subst.\n      change e with (apps e nil) at 1.\n      eapply (otherOk0 ts e nil tus tvs); simpl.\n      { unfold typeof_apps. simpl. rewrite H. reflexivity. }\n      { intuition. }\n    Qed.\n\n    Hypothesis is_starOk\n    : forall i,\n        sls.(is_star) (Inj i) = true ->\n        typeof_sym i = Some (tyArr SL (tyArr SL SL)).\n\n    Lemma lem_other\n    : forall ts0 t rs tus tvs l_res do_atomic_app0,\n        Forall2\n          (fun (t0 : typ) (x : expr sym * (tenv typ -> tenv typ -> T)) =>\n             typeof_expr tus tvs (fst x) = Some t0 /\\\n             (t0 = SL -> R_t (fst x) (snd x tus tvs) tus tvs)) ts0 rs ->\n        forall e : expr sym,\n          typeof_expr tus tvs (apps e (map fst rs)) = Some t ->\n          (fold_right tyArr t ts0 = SL -> R_t e (l_res tus tvs) tus tvs) ->\n          typeof_apps RSym_sym tus tvs e (map fst rs) = Some SL ->\n          (forall (e0 : expr sym) (es : list (expr sym * T)) (tus0 tvs0 : tenv typ),\n             typeof_apps RSym_sym tus0 tvs0 e0 (map fst es) = Some SL ->\n             (forall (x : expr sym) (y : T),\n                In (x, y) es -> typeof_expr tus0 tvs0 x = Some SL -> R_t x y tus0 tvs0) ->\n             R_t (apps e0 (map fst es)) (do_atomic_app0 e0 es) tus0 tvs0) ->\n          R_t (apps e (map fst rs))\n              (do_atomic_app0 e\n                              (map\n                                 (fun x : expr sym * (tenv typ -> tenv typ -> T) =>\n                                    (fst x, snd x tus tvs)) rs)) tus tvs.\n    Proof.\n      intros.\n      specialize (H3 e (map\n                          (fun x : expr sym * (tenv typ -> tenv typ -> T) =>\n                             (fst x, snd x tus tvs)) rs) tus tvs).\n      rewrite map_map in *. simpl in *.\n      eapply H3; eauto.\n      clear - H. induction H; simpl; intuition.\n      inv_all. subst. rewrite H1 in *. inv_all; subst.\n      eauto.\n    Qed.\n\n    Definition AppFullFoldArgsOk_SepLogsOk\n    : AppFullFoldArgsOk _ (AppFullFoldArgs_SepLogArgs sla)\n                        (fun t e res tus tvs =>\n                           t = SL ->\n                           R_t e res tus tvs).\n    Proof.\n      remember sla as s; destruct s; simpl; remember sls as s; destruct s.\n      constructor.\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { simpl; intros.\n        consider (is_emp0 v); intros.\n        { replace do_emp0 with (sla.(do_emp)).\n          eapply (@empOk _ slaok); eauto.\n          Cases.rewrite_all_goal. auto.\n          rewrite <- Heqs0. simpl. auto.\n          rewrite <- Heqs. reflexivity. }\n        { replace do_other0 with (sla.(do_other)).\n          eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. } }\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { intros. subst ft. simpl.\n        assert (typeof_apps RSym_sym tus tvs l (map fst rs) = Some SL).\n        { rewrite <- typeof_expr_apps. congruence. }\n        generalize (otherOk slaok). rewrite <- Heqs. simpl.\n        destruct l; eauto using lem_other.\n        consider (is_star0 s); eauto using lem_other; intros.\n        { generalize H4. eapply is_starOk in H4.\n          unfold typeof_apps in H3.\n          simpl in H3. rewrite H4 in *.\n          inversion H1; clear H1; try subst.\n          { subst rs ts0; intros.\n            simpl in *. clear - H3. inv_all.\n            symmetry in H3. eapply tyArr_circ_L in H3. intuition. }\n          { subst rs ts0. inversion H7; clear H7.\n            { subst l l'; intros; simpl in *.\n              rewrite H4 in *. forward.\n              intuition. inv_all. subst y t0.\n              clear - H8. symmetry in H8.\n              eapply tyArr_circ_L in H8. intuition. }\n            { subst l l'. inversion H8; clear H8.\n              { subst l0 l'0. intuition. subst t.\n                destruct y, y0; simpl in *.\n                rewrite H8 in *. rewrite H6 in *. rewrite H4 in *.\n                unfold type_of_apply in *. forward.\n                inv_all.\n                subst x0 x t1 t2 t3 p0 p.\n                replace do_star0 with (sla.(do_star));\n                  [ | rewrite <- Heqs; reflexivity ].\n                eapply (starOk slaok); eauto.\n                rewrite <- Heqs0. auto. }\n              { exfalso. clear Heqs Heqs0. subst.\n                simpl in H3. intuition.\n                rewrite H2 in *. rewrite H6 in *. rewrite H1 in *.\n                forward. inv_all; try subst.\n                clear H15 H13. subst x x0 x1.\n                clear - H14.\n                eapply type_of_applys_circle_False in H14. auto. } } } } }\n    Qed.\n\n    Definition seplog_fold (sla : SepLogArgs) : expr sym -> tenv typ -> tenv typ -> T :=\n      app_fold_args (AppFullFoldArgs_SepLogArgs sla).\n\n    Theorem seplog_fold_sound\n    : forall e tus tvs result,\n        seplog_fold sla e tus tvs = result ->\n        typeof_expr tus tvs e = Some SL ->\n        R_t e result tus tvs.\n    Proof.\n      intros.\n      eapply (app_fold_args_sound AppFullFoldArgsOk_SepLogsOk) in H; eauto.\n    Qed.\n  End sound.\n*)\n\n\n(*\n  Variable OPS : ILogic.ILogicOps (typD ts nil SL).\n  Variable BI : BILOperators (typD ts nil SL).\n  Variable slsok : SepLogSpecOk sls OPS BI.\n\n  Require Import Relations.\n  Require Import ExtLib.Data.HList.\n\n  Record SepLogArgsSemOk\n         (TD : T -> forall tus tvs, tenv typ -> tenv typ -> option (typD ts nil SL))\n         (R : forall tus tvs,\n                relation (hlist (typD ts nil) tus ->\n                          hlist (typD ts nil) tvs ->\n                          typD ts nil SL)) :=\n  { atomic_appOk\n    : forall e es tus tvs val,\n        exprD' tus tvs (apps e es) SL = Some val ->\n        R tus tvs val (TD (sla.(do_other) e es))\n  ; pureOk\n    : forall e tus tvs,\n        typeof_expr tus tvs e = Some SL ->\n        sls.(is_pure) e = true ->\n        R_t e (sla.(do_pure) e) tus tvs\n  ; empOk\n    : forall e tus tvs,\n        typeof_sym e = Some SL ->\n        sls.(is_emp) e = true ->\n        R_t (Inj e) sla.(do_emp) tus tvs\n  ; starOk\n    : forall e l r l_res r_res tus tvs,\n        typeof_sym e = Some (tyArr SL (tyArr SL SL)) ->\n        typeof_expr tus tvs l = Some SL ->\n        typeof_expr tus tvs r = Some SL ->\n        sls.(is_star) e = true ->\n        R_t l l_res tus tvs ->\n        R_t r r_res tus tvs ->\n        R_t (apps (Inj e) (l :: r :: nil)) (sla.(do_star) l_res r_res) tus tvs\n  }.\n*)\n\nEnd seplog_fold.", "meta": {"author": "jesper-bengtson", "repo": "Charge", "sha": "e58efc35e9f68a50cec6fcb40e83562133a84a21", "save_path": "github-repos/coq/jesper-bengtson-Charge", "path": "github-repos/coq/jesper-bengtson-Charge/Charge-e58efc35e9f68a50cec6fcb40e83562133a84a21/Charge!/src/Charge/Tactics/SepLogFold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.19466747498495754}}
{"text": "Require Import logic.\nFrom iris.base_logic Require Import soundness gen_heap.\nFrom iris.base_logic Require Export big_op.\nFrom iris.algebra Require Import dra gmap agree auth frac.\nFrom iris.base_logic.lib Require Import wsat fancy_updates.\nFrom iris.base_logic.lib Require Export namespaces invariants.\nFrom iris.proofmode Require Import tactics.\nFrom iris_c.clang.lib Require Export spec refine.\nFrom iris_c.lib Require Import pair refine_ra.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nSection sound.\n  Context `{refineG \u03a3, clangG \u03a3} {N: namespace}.\n\n  Inductive simulate: expr \u2192 spec.spec_code \u2192 Prop :=\n  | SimVal: \u2200 v, simulate (Evalue v) (SCdone (Some v))\n  | SimStep:\n      \u2200 \u03c3 \u03c3' l l' (\u03a3 \u03a3': spec.spec_state) e c e' c' efs,\n        cstep e l \u03c3 e' \u03c3' l' efs \u2192\n        spec_step_star c \u03a3 c' \u03a3 \u2192\n        simulate e c.\n\n  Local Hint Constructors simulate.\n\n  From iris_c.program_logic Require Import language adequacy.\n\n  Notation world \u03c3 := (wsat \u2217 ownE \u22a4 \u2217 state_interp \u03c3)%I.\n  Notation wptp t := ([\u2217 list] ef \u2208 t, WP ef {{ _, True }})%I.\n\nLemma wp_step R e1 l1 \u03c31 e2 l2 \u03c32 efs \u03a6 :\n  (R \u22a2 |==> \u25b7 R) \u2192\n  prim_step e1 l1 \u03c31 e2 l2 \u03c32 efs \u2192\n  world \u03c31 \u2217 R \u2217 WP (e1, l1) {{ \u03a6 }} ==\u2217 \u25b7 |==> \u25c7 (world \u03c32 \u2217 R \u2217 WP (e2, l2) {{ \u03a6 }} \u2217 wptp (map (,([], semp)) efs)).\nProof.\n  rewrite {1}wp_unfold /wp_pre.\n  iIntros (HR Hstep) \"[(Hw & HE & H\u03c3) [HR [H|[_ H]]]]\".\n  { iDestruct \"H\" as (v) \"[% _]\". apply val_stuck in Hstep.\n    simpl in *. simplify_eq. }\n  rewrite fupd_eq /fupd_def.\n  iMod (\"H\" $! \u03c31 with \"H\u03c3 [$Hw $HE]\") as \">(Hw & HE & _ & H)\".\n  iModIntro; iNext. simpl.\n  iMod (\"H\" $! (e2, l2) \u03c32 efs with \"[%] [$Hw $HE]\") as \">($ & $ & $ & $ & ?)\"=>//.\n  iFrame.\n  iDestruct (@big_sepL_fmap _ (expr clang_lang) (expr clang_lang * local_state clang_lang)\n                            (,([], semp)) (fun _ x => (WP x {{ _, True }})%I) efs with \"~\") as \"?\".\n  auto.\nQed.\n\n  Lemma wptp_step' R e1 t1 t2 \u03c31 \u03c32 \u03a6 :\n    (R \u22a2 |==> \u25b7 R) \u2192\n    step (e1 :: t1,\u03c31) (t2, \u03c32) \u2192\n    world \u03c31 \u2217 R \u2217 WP e1 {{ \u03a6 }} \u2217 wptp t1\n    ==\u2217 \u2203 e2 t2', \u231ct2 = e2 :: t2'\u231d \u2217 \u25b7 |==> \u25c7 (world \u03c32 \u2217 R \u2217 WP e2 {{ \u03a6 }} \u2217 wptp t2').\n  Proof.\n    iIntros (HR Hstep) \"(HW & HR & He & Ht)\".\n    destruct Hstep as [e1' l1' \u03c31' e2' l2' \u03c32' efs [|? t1'] t2' ?? Hstep]; simplify_eq/=.\n    - iExists (e2', l2'), (t2' ++ map (,([], semp)) efs); iSplitR; first eauto.\n      rewrite big_sepL_app. iFrame \"Ht\". iApply wp_step; try iFrame; eauto.\n    - iExists p, (t1' ++ (e2', l2') :: t2' ++ map (,([], semp)) efs); iSplitR; first eauto.\n      rewrite !big_sepL_app !big_sepL_cons big_sepL_app.\n      iDestruct \"Ht\" as \"($ & He' & $)\"; iFrame \"He\".\n      iApply wp_step; try iFrame; eauto.\n  Qed.\n\n  Lemma wptp_steps' R n e1 t1 t2 \u03c31 \u03c32 \u03a6 :\n    (R \u22a2 |==> \u25b7 R) \u2192\n    nsteps (@step clang_lang) n (e1 :: t1, \u03c31) (t2, \u03c32) \u2192\n    world \u03c31 \u2217 R \u2217 WP e1 {{ \u03a6 }} \u2217 wptp t1 \u22a2\n    Nat.iter (S n) (\u03bb P, |==> \u25b7 P) (\u2203 e2 t2',\n    \u231ct2 = e2 :: t2'\u231d \u2217 world \u03c32 \u2217 R \u2217 WP e2 {{ \u03a6 }} \u2217 wptp t2').\n  Proof.\n    revert e1 t1 t2 \u03c31 \u03c32; simpl; induction n as [|n IH]=> e1 t1 t2 \u03c31 \u03c32 /=.\n    { intros HR. inversion_clear 1. iIntros \"?\". eauto 10. }\n    iIntros (HR Hsteps) \"H\". inversion_clear Hsteps as [|?? [t1' \u03c31']].\n    iMod (wptp_step' with \"H\") as (e1' t1'') \"[% H]\";\n      first eauto; simplify_eq. apply H1.\n    iModIntro; iNext; iMod \"H\" as \">?\". iApply IH=>//.\n    subst. done.\n  Qed.\n\n  Lemma bar' ss sc:\n    (inv N spec_inv \u2217 own_sstate ss \u2217 own_scode sc)\n    \u22a2 |==> \u25b7 (inv N spec_inv \u2217 own_sstate ss \u2217 own_scode sc).\n  Proof. iIntros \"?\". iModIntro. by iNext. Qed.\n\n  Lemma soudness n e1 l2 t1 \u03c31 t2 \u03c32 c1 \u03a31 \u03a32 v2:\n    nsteps step n (e1 :: t1, \u03c31) ((of_val v2, l2) :: t2, \u03c32) \u2192\n    world \u03c31 \u2217 (inv N spec_inv \u2217 own_sstate \u03a31 \u2217 own_scode c1) \u2217\n    WP e1 {{ v, own_sstate \u03a32 \u2217 own_scode (SCdone (Some v)) }} \u2217 wptp t1 \u22a2\n    Nat.iter (S (S n)) (\u03bb P, |==> \u25b7 P) \u231csimulate (Evalue v2) c1\u231d.\n  Proof.\n    intros. rewrite wptp_steps' //; last by apply bar'.\n    rewrite (Nat_iter_S_r (S n)). apply bupd_iter_mono.\n    iDestruct 1 as (e2 t2') \"(% & (Hw & HE & _) & (?&?&?) & [H _])\"; simplify_eq.\n    iDestruct (wp_value_inv with \"H\") as \"H\". rewrite fupd_eq /fupd_def.\n    iMod (\"H\" with \"[Hw HE]\") as \">(_ & _ & (?&?))\"; first iFrame.\n    iModIntro. iNext.\n    iDestruct (@own_pair_agree spec_state with \"[~2 ~1]\") as \"%\"; first iFrame.\n    iDestruct (@own_pair_agree spec_code with \"[~3 ~4]\") as \"%\"; first iFrame.\n    iPureIntro. by simplify_eq.\n  Qed.\n\nEnd sound.\n", "meta": {"author": "izgzhen", "repo": "iris-c-coq", "sha": "ca4bbc8fd86d8c53406a371eb30d0dda64a0920e", "save_path": "github-repos/coq/izgzhen-iris-c-coq", "path": "github-repos/coq/izgzhen-iris-c-coq/iris-c-coq-ca4bbc8fd86d8c53406a371eb30d0dda64a0920e/theories/clang/lib/refine_sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.19465798915481067}}
{"text": "From stdpp Require Import strings.\nFrom iris.si_logic Require Import bi.\nUnset Mangle Names.\n\nCheck \"unseal_test\".\nLemma unseal_test (P Q : siProp) (\u03a6 : nat \u2192 siProp) :\n  P \u2227 \u25b7 Q \u2227 (\u2203 x, \u03a6 x) \u22a3\u22a2 \u2203 x, P \u2217 \u25b7 Q \u2227 emp \u2228 \u03a6 x.\nProof.\n  siProp.unseal.\n  Show.\nAbort.\n\n(** Make sure that [siProp]s are parsed in [bi_scope]. *)\nDefinition test : siProp := \u25b7 True.\nDefinition testI : siPropI := \u25b7 True.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/tests/siprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.19465798672197276}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Csyntax.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr id ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 Mem.empty with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nDefinition lookup_composite (ce: composite_env) (id: ident) : res composite :=\n  match ce!id with\n  | Some co => OK co\n  | None => Error (MSG \"Undefined struct or union \" :: CTX id :: nil)\n  end.\n\nFixpoint constval (ce: composite_env) (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ | Vsingle _ | Vlong _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval ce l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval ce l\n  | Eunop op r1 ty =>\n      do v1 <- constval ce r1;\n      match sem_unary_operation op v1 (typeof r1) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match sem_binary_operation ce op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval ce r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ce ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ce ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some true => do_cast v2 (typeof r2) type_bool\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some false => do_cast v2 (typeof r2) type_bool\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      do v3 <- constval ce r3;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval ce r1; constval ce r2\n  | Evar x ty =>\n      OK(Vptr x Int.zero)\n  | Ederef r ty =>\n      constval ce r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id _ =>\n          do co <- lookup_composite ce id;\n          do delta <- field_offset ce f (co_members co);\n          do v <- constval ce l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id _ =>\n          constval ce l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r tycast ty =>\n      do v <- constval ce r; do_cast v (typeof r) tycast\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_array (il: initializer_list)\n  | Init_struct (il: initializer_list)\n  | Init_union (f: ident) (i: initializer)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ce: composite_env) (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval ce a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint (I8|IBool) sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vlong n, Tlong _ _ => OK(Init_int64 n)\n  | Vsingle f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr id ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr id ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  [transl_init ce ty i] returns the appropriate list of initialization data.\n  The intermediate functions [transl_init_rec], [transl_init_array]\n  and [transl_init_struct] append initialization data to the given\n  list [k], and build the list of initialization data in reverse order,\n  so as to remain tail-recursive. *)\n\nDefinition padding (frm to: Z) (k: list init_data) : list init_data :=\n  if zlt frm to then Init_space (to - frm) :: k else k.\n\nFixpoint transl_init_rec (ce: composite_env) (ty: type) (i: initializer)\n                         (k: list init_data) {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ce ty a; OK (d :: k)\n  | Init_array il, Tarray tyelt nelt _ =>\n      transl_init_array ce tyelt il (Zmax 0 nelt) k\n  | Init_struct il, Tstruct id _ =>\n      do co <- lookup_composite ce id;\n      match co_su co with\n      | Struct => transl_init_struct ce ty (co_members co) il 0 k\n      | Union  => Error (MSG \"struct/union mismatch on \" :: CTX id :: nil)\n      end\n  | Init_union f i1, Tunion id _ =>\n      do co <- lookup_composite ce id;\n      match co_su co with\n      | Struct => Error (MSG \"union/struct mismatch on \" :: CTX id :: nil)\n      | Union =>\n          do ty1 <- field_type f (co_members co);\n          do k1  <- transl_init_rec ce ty1 i1 k;\n          OK (padding (sizeof ce ty1) (sizeof ce ty) k1)\n      end\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ce: composite_env) (ty: type) (il: initializer_list) (sz: Z)\n                       (k: list init_data) {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0 then OK k\n      else if zle 0 sz then OK (Init_space (sz * sizeof ce ty) :: k)\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do k1 <- transl_init_rec ce ty i1 k;\n      transl_init_array ce ty il' (sz - 1) k1\n  end\n\nwith transl_init_struct (ce: composite_env) (ty: type)\n                        (fl: members) (il: initializer_list) (pos: Z)\n                        (k: list init_data)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, nil =>\n      OK (padding pos (sizeof ce ty) k)\n  | Init_cons i1 il', (_, ty1) :: fl' =>\n      let pos1 := align pos (alignof ce ty1) in\n      do k1 <- transl_init_rec ce ty1 i1 (padding pos pos1 k);\n      transl_init_struct ce ty fl' il' (pos1 + sizeof ce ty1) k1\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end.\n\nDefinition transl_init (ce: composite_env) (ty: type) (i: initializer)\n                       : res (list init_data) :=\n  do k <- transl_init_rec ce ty i nil; OK (List.rev' k).\n", "meta": {"author": "scuellar", "repo": "CompCertMod", "sha": "c39722ce4e26014391aedb32051e3bc233c2b348", "save_path": "github-repos/coq/scuellar-CompCertMod", "path": "github-repos/coq/scuellar-CompCertMod/CompCertMod-c39722ce4e26014391aedb32051e3bc233c2b348/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.19465168916207215}}
{"text": "Set Primitive Projections.\nSet Implicit Arguments.\nRecord prod A B := pair { fst : A; snd : B}.\n\nGoal fst (@pair Type Type Type Type).\nSet Printing All.\nmatch goal with |- ?f ?x => set (foo := f x) end.\nAbort.\n\nGoal forall x : prod Set Set, x = @pair _ _ (fst x) (snd x).\nProof.\n  intro x.\n  lazymatch goal with\n    | [ |- ?x = @pair _ _ (?f ?x) (?g ?x) ] => pose f\n  end.\n(* Toplevel input, characters 7-44:\nError: No matching clauses for match. *)\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/3377.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.19451570033299367}}
{"text": "(** * Push-Button Synthesis of Unsaturated Solinas *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Coq.Lists.List.\nRequire Import Coq.QArith.QArith_base Coq.QArith.Qround.\nRequire Import Coq.derive.Derive.\nRequire Crypto.TAPSort.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.FoldBool.\nRequire Import Crypto.Util.Strings.Decimal.\nRequire Import Crypto.Util.ZRange.\nRequire Crypto.Util.Option.\nRequire Import Crypto.Util.Strings.Show.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.HasBody.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.SpecializeUnderBindersBy.\nRequire Import Rewriter.Language.Wf.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.Arithmetic.Freeze.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.UnsaturatedSolinasHeuristics.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.PushButtonSynthesis.Primitives.\nRequire Import Crypto.PushButtonSynthesis.UnsaturatedSolinasReificationCache.\nRequire Import Crypto.Assembly.Equivalence.\nImport Option.Notations.\nImport ListNotations.\nLocal Open Scope string_scope. Local Open Scope bool_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\nImport\n  Language.Wf.Compilers\n  Language.Compilers\n  AbstractInterpretation.Compilers\n  Stringification.Language.Compilers\n  Rewriter.All.Compilers.RewriteRules.\nImport Compilers.API.\n\nImport COperationSpecifications.Primitives.\nImport COperationSpecifications.Solinas.\n\nImport Associational Positional.\n\nLocal Coercion Z.of_nat : nat >-> Z.\nLocal Coercion QArith_base.inject_Z : Z >-> Q.\nLocal Coercion Z.pos : positive >-> Z.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\n(* needed for making [autorewrite] not take a very long time *)\nLocal Opaque\n      reified_carry_mul_gen\n      reified_carry_square_gen\n      reified_carry_scmul_gen\n      reified_carry_gen\n      reified_add_gen\n      reified_sub_gen\n      reified_opp_gen\n      reified_carry_add_gen\n      reified_carry_sub_gen\n      reified_carry_opp_gen\n      reified_id_gen\n      reified_to_bytes_gen\n      reified_from_bytes_gen\n      reified_encode_gen\n      reified_encode_gen\n      reified_zero_gen\n      reified_one_gen\n      reified_eval_gen\n      reified_bytes_eval_gen\n      reified_prime_gen\n      expr.Interp.\n\nSection __.\n  Context {output_language_api : ToString.OutputLanguageAPI}\n          {pipeline_opts : PipelineOptions}\n          {pipeline_to_string_opts : PipelineToStringOptions}\n          {synthesis_opts : SynthesisOptions}\n          {tight_upperbound_fraction : tight_upperbound_fraction_opt}\n          (n : nat)\n          (s : Z)\n          (c : list (Z * Z))\n          (machine_wordsize : machine_wordsize_opt).\n\n  Local Notation limbwidth := (limbwidth n s c).\n  Definition idxs : list nat := carry_chains n s c.\n  Definition n_bytes := bytes_n s.\n  Local Notation prime_upperbound_list := (prime_upperbound_list n s c) (only parsing).\n  Definition prime_bytes_upperbound_list : list Z\n    := Partition.partition (weight 8 1) n_bytes (s-1).\n  Local Notation tight_upperbounds := (tight_upperbounds n s c) (only parsing).\n  Local Notation loose_upperbounds := (loose_upperbounds n s c) (only parsing).\n  Local Notation tight_bounds := (tight_bounds n s c) (only parsing).\n  Local Notation loose_bounds := (loose_bounds n s c) (only parsing).\n  Global Instance tight_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some tight_bounds)\n    := { name := \"tight_field_element\"\n         ; description name := (text_before_type_name ++ name ++ \" is a field element with tight bounds.\")%string }.\n  Global Instance loose_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some loose_bounds)\n    := { name := \"loose_field_element\"\n         ; description name := (text_before_type_name ++ name ++ \" is a field element with loose bounds.\")%string }.\n  Definition prime_bound : ZRange.type.interp base.type.Z\n    := r[0~>(s - Associational.eval c - 1)]%zrange.\n  Definition prime_bounds : list (ZRange.type.option.interp (base.type.Z))\n    := List.map (fun v => Some r[0 ~> v]%zrange) prime_upperbound_list.\n  Definition prime_bytes_bounds : list (ZRange.type.option.interp base.type.Z)\n    := List.map (fun v => Some r[0 ~> v]%zrange) prime_bytes_upperbound_list.\n  Local Notation word_bound := (word_bound machine_wordsize).\n  Local Notation saturated_bounds := (saturated_bounds n machine_wordsize).\n  Local Notation balance := (balance n s c).\n\n  Definition m : Z := s - Associational.eval c.\n  (* m_enc needs to be such that, if x is bounded by tight bounds:\n\n     -2*fw[i] <= x[i] - m_enc[i] <= fw[i]\n\n     ...so as to obey the bounds for the sub-with-borrow in\n     freeze. fw[i] here is shorthand for (weight (S i) / weight i). To\n     obey the upper bound, we need to redistribute m_enc such that:\n\n     tight_upperbounds[i] - fw[i] <= m_enc[i]\n\n     Additionally, we cannot have the minimum be uniformly 0, or else\n     we'll encode 0; if this happens, we bump the highest limb to be\n     at least 1 *)\n  Definition m_enc_min : list Z :=\n    let wt := weight (Qnum limbwidth) (Qden limbwidth) in\n    let fw := List.map (fun i => wt (S i) / wt i) (seq 0 n) in\n    let m_enc_min := map2 Z.sub tight_upperbounds fw in\n    if List.forallb (Z.eqb 0) m_enc_min\n    then set_nth (n-1) 1 m_enc_min\n    else m_enc_min.\n\n  Definition m_enc : list Z :=\n    let M := encode (weight (Qnum limbwidth) (Qden limbwidth)) n s c m in\n    distribute_balance n s c m_enc_min M.\n\n  Local Notation possible_values := (possible_values_of_machine_wordsize machine_wordsize).\n  Local Notation possible_values_with_bytes := (possible_values_of_machine_wordsize_with_bytes machine_wordsize).\n\n  Local Existing Instance default_translate_to_fancy.\n  Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.\n  Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.\n  Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.\n\n  Local Notation weightf := (weight (Qnum limbwidth) (QDen limbwidth)).\n  Local Notation evalf := (eval weightf n).\n\n  Lemma length_prime_bytes_upperbound_list : List.length prime_bytes_upperbound_list = n_bytes.\n  Proof using Type. cbv [prime_bytes_upperbound_list]; now autorewrite with distr_length. Qed.\n  Hint Rewrite length_prime_bytes_upperbound_list : distr_length.\n  Lemma length_saturated_bounds : List.length saturated_bounds = n.\n  Proof using Type. cbv [saturated_bounds]; now autorewrite with distr_length. Qed.\n  Hint Rewrite length_saturated_bounds : distr_length.\n  Lemma length_m_enc : List.length m_enc = n.\n  Proof using Type. cbv [m_enc]; repeat distr_length. Qed.\n  Hint Rewrite length_m_enc : distr_length.\n  Lemma eval_list_Z_bounded_by_tight_bounds\n        (Hwt : 0 < QDen limbwidth <= Qnum limbwidth)\n        x\n        (Hx : list_Z_bounded_by tight_bounds x)\n    : 0 <= evalf x <= evalf tight_upperbounds.\n  Proof using Type.\n    Local Opaque UnsaturatedSolinasHeuristics.tight_upperbounds.\n    cbv [tight_bounds] in *.\n    intros.\n    lazymatch goal with\n    | [ H1 : list_Z_bounded_by (List.map (fun y => Some (@?f y)) ?b) ?x\n        |- context[eval ?wt ?n ?x] ]\n      => unshelve epose proof (eval_list_Z_bounded_by wt n (List.map (fun x => Some (f x)) b) (List.map f b) x H1 _ _ (fun A B => Z.lt_le_incl _ _ (weight_positive _ _))); clear H1\n    end.\n    all: repeat first [ reflexivity\n                      | apply wprops\n                      | progress rewrite ?map_map in *\n                      | progress rewrite ?map_id in *\n                      | progress cbn [upper lower] in *\n                      | assumption\n                      | progress autorewrite with distr_length\n                      | lia\n                      | match goal with\n                        | [ H : context[List.map (fun _ => 0) _] |- _ ] => erewrite <- zeros_ext_map, ?eval_zeros in H by reflexivity; autorewrite with distr_length push_eval in H\n                        end ].\n    Local Transparent UnsaturatedSolinasHeuristics.tight_upperbounds.\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    := check_args_of_list\n         ((List.map\n             (fun v => (true, v))\n             (* first, all the ones that should always hold *)\n             [((Qle_bool 1 limbwidth)%Q, Pipeline.Value_not_leQ \"limbwidth < 1\" 1%Q limbwidth)\n              ; (n <=? Z.log2_up (s - Associational.eval c), Pipeline.Value_not_leZ \"Z.log2_up (s - Associational.eval c) < n\" n (Z.log2_up (s - Associational.eval c)))\n              ; (Associational.eval c <? s, Pipeline.Value_not_ltZ \"s \u2264 Associational.eval c\" (Associational.eval c) s)\n              ; (0 <? s, Pipeline.Value_not_ltZ \"s \u2264 0\" 0 s)\n              ; (negb (n =? 0)%nat, Pipeline.Values_not_provably_distinctZ \"n = 0\" n 0%nat)\n              ; (0 <? machine_wordsize, Pipeline.Value_not_ltZ \"machine_wordsize \u2264 0\" 0 machine_wordsize)\n              ; (let v1 := s - Associational.eval c in\n                 let v2 := weight (Qnum limbwidth) (QDen limbwidth) n in\n                 (v1 <=? v2, Pipeline.Value_not_leZ \"weight n < s - Associational.eval c\" v1 v2))\n\n                  (** For bedrock2 *)\n              ; (let v1 := List.fold_right Z.max 0 prime_bytes_upperbound_list in\n                 let v2 := 2^machine_wordsize-1 in\n                 (v1 <=? v2,\n                  Pipeline.Value_not_leZ \"max(prime_bytes_upperbounds) > 2^machine_wordsize-1\" v1 v2))\n              ; (let v1 := List.fold_right Z.max 0 tight_upperbounds in\n                 let v2 := 2^machine_wordsize-1 in\n                 (v1 <=? v2,\n                  Pipeline.Value_not_leZ \"max(tight_upperbounds) > 2^machine_wordsize-1\" v1 v2))\n              ; (let v1 := List.fold_right Z.max 0 loose_upperbounds in\n                 let v2 := 2^machine_wordsize-1 in\n                 (v1 <=? v2,\n                  Pipeline.Value_not_leZ \"max(loose_upperbounds) > 2^machine_wordsize-1\" v1 v2))\n          ])\n            (* the littany of to_bytes ones *)\n            ++ (List.map\n                  (fun v => (request_present requests \"to_bytes\", v))\n                  [(0 <? Associational.eval c, Pipeline.Value_not_ltZ \"Associational.eval c \u2264 0 (needed for to_bytes)\" 0 (Associational.eval c))\n                   ; (let v1 := s in\n                      let v2 := weight (Qnum limbwidth) (QDen limbwidth) n in\n                      (v1 =? v2, Pipeline.Values_not_provably_equalZ \"s \u2260 weight n (needed for to_bytes)\" v1 v2))\n                   ; (let v1 := (List.map (Z.land (Z.ones machine_wordsize)) m_enc) in\n                      let v2 := m_enc in\n                      (list_beq _ Z.eqb v1 v2, Pipeline.Values_not_provably_equal_listZ \"map mask m_enc \u2260 m_enc (needed for to_bytes)\" v1 v2))\n                   ; (let v1 := eval (weight (Qnum limbwidth) (QDen limbwidth)) n m_enc in\n                      let v2 := s - Associational.eval c in\n                      (v1 =? v2, Pipeline.Values_not_provably_equalZ \"eval m_enc \u2260 s - Associational.eval c (needed for to_bytes)\" v1 v2))\n                   ; (let v1 := eval (weight (Qnum limbwidth) (QDen limbwidth)) n tight_upperbounds in\n                      let v2 := 2 * eval (weight (Qnum limbwidth) (QDen limbwidth)) n m_enc in\n                      (v1 <? v2, Pipeline.Value_not_ltZ \"2 * eval m_enc \u2264 eval tight_upperbounds (needed for to_bytes)\" v1 v2))\n               ])\n            ++ [(request_present requests \"from_bytes\",\n                 (1 <? s, Pipeline.Value_not_ltZ \"s \u2264 1 (need for from_bytes)\" 1 s))\n         ])\n         res.\n\n  Local Ltac use_curve_good_t :=\n    repeat first [ use_requests_to_prove_curve_good_t_step\n                 | assumption\n                 | lia\n                 | progress autorewrite with distr_length\n                 | progress distr_length\n                 | progress autorewrite with zsimplify_fast in * ].\n\n  Context (requests : list string)\n          (curve_good : check_args requests (Success tt) = Success tt).\n\n  Lemma use_curve_good\n    : let eval := eval (weight (Qnum limbwidth) (QDen limbwidth)) n in\n      0 < Qden limbwidth <= Qnum limbwidth\n      /\\ n <= Z.log2_up (s - Associational.eval c)\n      /\\ 0 < s - Associational.eval c\n      /\\ 0 < s - Associational.eval c <= weight (Qnum limbwidth) (QDen limbwidth) n\n      /\\ s - Associational.eval c <> 0\n      /\\ s <> 0\n      /\\ 0 < machine_wordsize\n      /\\ n <> 0%nat\n      /\\ List.fold_right Z.max 0 prime_bytes_upperbound_list <= 2^machine_wordsize-1\n      /\\ List.fold_right Z.max 0 tight_upperbounds <= 2^machine_wordsize-1\n      /\\ List.fold_right Z.max 0 loose_upperbounds <= 2^machine_wordsize-1\n      /\\ (request_present requests \"from_bytes\" = true -> 1 < s)\n      /\\ (request_present requests \"to_bytes\" = true -> 1 < s)\n      /\\ (request_present requests \"to_bytes\" = true -> 0 < Associational.eval c < s)\n      /\\ (request_present requests \"to_bytes\" = true -> s = weight (Qnum limbwidth) (QDen limbwidth) n)\n      /\\ (request_present requests \"to_bytes\" = true -> List.map (Z.land (Z.ones machine_wordsize)) m_enc = m_enc)\n      /\\ (request_present requests \"to_bytes\" = true -> eval m_enc = s - Associational.eval c)\n      /\\ (request_present requests \"to_bytes\" = true -> eval tight_upperbounds < 2 * eval m_enc)\n      /\\ List.length tight_bounds = n\n      /\\ List.length loose_bounds = n\n      /\\ List.length prime_bytes_upperbound_list = n_bytes\n      /\\ List.length saturated_bounds = n\n      /\\ Datatypes.length m_enc = n.\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    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n  Qed.\n\n  Lemma use_curve_good_extra\n    : (request_present requests \"to_bytes\" = true -> forall x, list_Z_bounded_by tight_bounds x -> 0 <= evalf x < 2 * (s - Associational.eval c)).\n  Proof using curve_good.\n    pose proof use_curve_good; cbv beta zeta in *; destruct_head'_and.\n    pose proof eval_list_Z_bounded_by_tight_bounds.\n    repeat match goal with |- _ /\\ _ => split end.\n    { intros.\n      specialize_by auto.\n      specialize_all_ways_under_binders_by eassumption.\n      lia. }\n  Qed.\n\n  Local Notation notations_for_docstring\n    := (CorrectnessStringification.dyn_context.cons\n          m \"m\"\n          (CorrectnessStringification.dyn_context.cons\n             weightf \"weight\"\n             (CorrectnessStringification.dyn_context.cons\n                evalf \"eval\"\n                CorrectnessStringification.dyn_context.nil)))%string.\n  Local Notation \"'docstring_with_summary_from_lemma!' summary correctness\"\n    := (docstring_with_summary_from_lemma_with_ctx!\n          notations_for_docstring\n          summary\n          correctness)\n         (only parsing, at level 10, summary at next level, correctness at next level).\n\n  Definition carry_mul\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_carry_mul_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs)\n         (Some loose_bounds, (Some loose_bounds, tt))\n         (Some tight_bounds).\n\n  Definition scarry_mul (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry_mul\" carry_mul\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" multiplies two field elements and reduces the result.\"]%string)\n             (carry_mul_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition carry_square\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_carry_square_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs)\n         (Some loose_bounds, tt)\n         (Some tight_bounds).\n\n  Definition scarry_square (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry_square\" carry_square\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" squares a field element and reduces the result.\"]%string)\n             (carry_square_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition carry_scmul_const (x : Z)\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_carry_scmul_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs @ GallinaReify.Reify x)\n         (Some loose_bounds, tt)\n         (Some tight_bounds).\n\n  Definition scarry_scmul_const (prefix : string) (x : Z)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix (\"carry_scmul_\" ++ Decimal.Z.to_string x)%string (carry_scmul_const x)\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" multiplies a field element by \" ++ Decimal.Z.to_string x ++ \" and reduces the result.\"]%string)\n             (carry_scmul_const_correct weightf n m tight_bounds loose_bounds x)).\n\n  Definition carry\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_carry_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs)\n         (Some loose_bounds, tt)\n         (Some tight_bounds).\n\n  Definition scarry (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry\" carry\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" reduces a field element.\"]%string)\n             (carry_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition add\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_add_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify n)\n         (Some tight_bounds, (Some tight_bounds, tt))\n         (Some loose_bounds).\n\n  Definition sadd (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"add\" add\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" adds two field elements.\"]%string)\n             (add_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition sub\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_sub_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify n @ GallinaReify.Reify balance)\n         (Some tight_bounds, (Some tight_bounds, tt))\n         (Some loose_bounds).\n\n  Definition ssub (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"sub\" sub\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" subtracts two field elements.\"]%string)\n             (sub_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition opp\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_opp_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify n @ GallinaReify.Reify balance)\n         (Some tight_bounds, tt)\n         (Some loose_bounds).\n\n  Definition sopp (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"opp\" opp\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" negates a field element.\"]%string)\n             (opp_correct weightf n m tight_bounds loose_bounds)).\n\n  Definition carry_add\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_carry_add_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs)\n         (Some tight_bounds, (Some tight_bounds, tt))\n         (Some tight_bounds).\n\n  Definition scarry_add (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry_add\" carry_add\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" adds two field elements.\"]%string)\n             (carry_add_correct weightf n m tight_bounds)).\n\n  Definition carry_sub\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_carry_sub_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs @ GallinaReify.Reify balance)\n         (Some tight_bounds, (Some tight_bounds, tt))\n         (Some tight_bounds).\n\n  Definition scarry_sub (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry_sub\" carry_sub\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" subtracts two field elements.\"]%string)\n             (carry_sub_correct weightf n m tight_bounds)).\n\n  Definition carry_opp\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_carry_opp_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n @ GallinaReify.Reify idxs @ GallinaReify.Reify balance)\n         (Some tight_bounds, tt)\n         (Some tight_bounds).\n\n  Definition scarry_opp (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"carry_opp\" carry_opp\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" negates a field element.\"]%string)\n             (carry_opp_correct weightf n m tight_bounds)).\n\n  Definition relax\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         reified_id_gen\n         (Some tight_bounds, tt)\n         (Some loose_bounds).\n\n  Definition srelax (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"relax\" relax\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" is the identity function converting from tight field elements to loose field elements.\"]%string)\n             (relax_correct tight_bounds loose_bounds)).\n\n  Definition to_bytes\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values_with_bytes\n         (reified_to_bytes_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify n @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify m_enc)\n         (Some tight_bounds, tt)\n         (Some prime_bytes_bounds).\n\n  Definition sto_bytes (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"to_bytes\" to_bytes\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" serializes a field element to bytes in little-endian order.\"]%string)\n             (to_bytes_correct weightf n n_bytes m tight_bounds)).\n\n  Definition from_bytes\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values_with_bytes\n         (reified_from_bytes_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify n)\n         (Some prime_bytes_bounds, tt)\n         (Some tight_bounds).\n\n  Definition sfrom_bytes (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"from_bytes\" from_bytes\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" deserializes a field element from bytes in little-endian order.\"]%string)\n             (from_bytes_correct weightf n n_bytes m s tight_bounds)).\n\n  Definition encode\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_encode_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n)\n         (Some prime_bound, tt)\n         (Some tight_bounds).\n\n  Definition sencode (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"encode\" encode\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" encodes an integer as a field element.\"]%string)\n             (encode_correct weightf n m tight_bounds)).\n\n  Definition encode_word\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_encode_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n)\n         (Some word_bound, tt)\n         (Some tight_bounds).\n\n  Definition sencode_word (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"encode_word\" encode_word\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" encodes an integer as a field element.\"]%string)\n             (encode_word_correct machine_wordsize weightf n m tight_bounds)).\n\n  Definition zero\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_zero_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n)\n         tt\n         (Some tight_bounds).\n\n  Definition szero (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"zero\" zero\n          (docstring_with_summary_from_lemma!\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the field element zero.\"]%string)\n             (zero_correct weightf n m tight_bounds)).\n\n  Definition one\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_one_gen\n            @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify n)\n         tt\n         (Some tight_bounds).\n\n  Definition sone (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"one\" one\n          (docstring_with_summary_from_lemma!\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the field element one.\"]%string)\n             (one_correct weightf n m tight_bounds)).\n\n  Definition reval (* r for reified *)\n    := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects\n         n\n         (Pipeline.PreBoundsPipeline\n            true (* subst01 *)\n            false (* let_bind_return *)\n            (reified_eval_gen\n               @ GallinaReify.Reify (Qnum limbwidth) @ GallinaReify.Reify (Z.pos (Qden limbwidth)) @ GallinaReify.Reify n)\n            (Some loose_bounds, tt)).\n\n  Definition seval (arg_name : string) (* s for string *)\n    := show (invert_expr.smart_App_curried (reval _) (arg_name, tt)).\n\n  Definition rbytes_eval (* r for reified *)\n    := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects\n         n_bytes\n         (Pipeline.PreBoundsPipeline\n            true (* subst01 *)\n            false (* let_bind_return *)\n            (reified_bytes_eval_gen\n               @ GallinaReify.Reify s)\n            (Some prime_bytes_bounds, tt)).\n\n  Definition sbytes_eval (arg_name : string) (* s for string *)\n    := show (invert_expr.smart_App_curried (rbytes_eval _) (arg_name, tt)).\n\n  Definition selectznz : Pipeline.ErrorT _ := Primitives.selectznz n machine_wordsize.\n  Definition sselectznz (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Primitives.sselectznz n machine_wordsize prefix.\n\n  Definition copy : Pipeline.ErrorT _ := Primitives.copy n machine_wordsize.\n  Definition scopy (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Primitives.scopy n machine_wordsize prefix.\n\n  Local Ltac solve_extra_bounds_side_conditions :=\n    cbn [lower upper fst snd] in *; Bool.split_andb; Z.ltb_to_lt; lia.\n\n  Hint Rewrite\n       eval_carry_mulmod\n       eval_carry_squaremod\n       eval_carry_scmulmod\n       eval_addmod\n       eval_submod\n       eval_oppmod\n       eval_carry_addmod\n       eval_carry_submod\n       eval_carry_oppmod\n       eval_carrymod\n       freeze_to_bytesmod_partitions\n       eval_to_bytesmod\n       eval_from_bytesmod\n       eval_encodemod\n       using solve [ auto using eval_balance, length_balance | congruence | solve_extra_bounds_side_conditions ] : push_eval.\n  Hint Unfold zeromod onemod : push_eval.\n\n  Local Ltac solve_prove_correctness_side_conditions _ :=\n    solve [ auto | congruence | now autorewrite with distr_length | solve_extra_bounds_side_conditions ].\n  Local Ltac prove_correctness _ :=\n    Primitives.prove_correctness (conj use_curve_good use_curve_good_extra);\n    try solve_prove_correctness_side_conditions ().\n\n  (** Work around COQBUG(https://github.com/coq/coq/issues/9286) *)\n  Local Opaque\n        carry_mulmod\n        carry_squaremod\n        carry_scmulmod\n        carrymod\n        addmod\n        submod\n        oppmod\n        carry_addmod\n        carry_submod\n        carry_oppmod\n        from_bytesmod\n        to_bytesmod\n        (* Set Printing Width 100000. Print Rewrite HintDb push_eval. | sed s'/^.*->//g' | grep -o ' eval \\(([^)]\\+)\\|[^ ]*\\) \\(([^)]\\+)\\|[^ ]*\\) [^ )]*' | grep -o '[A-Za-z0-9_\\.][A-Za-z0-9_\\.]\\+$' | sort | uniq *)\n        addmod\n        BaseConversion.convert_bases\n        BaseConversion.convert_basesmod\n        carrymod\n        carry_mulmod\n        carry_scmulmod\n        carry_squaremod\n        encodemod\n        extend_to_length\n        Freeze.from_bytes\n        Freeze.to_bytes\n        freeze_to_bytesmod\n        from_bytesmod\n        oppmod\n        Partition.partition\n        select\n        submod\n        to_bytesmod\n        zeros\n        zselect\n  .\n\n  Lemma carry_mul_correct res\n        (Hres : carry_mul = Success res)\n    : carry_mul_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_mul res (Hres : carry_mul = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_square_correct res\n        (Hres : carry_square = Success res)\n    : carry_square_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_square res (Hres : carry_square = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_scmul_const_correct a res\n        (Hres : carry_scmul_const a = Success res)\n    : carry_scmul_const_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds a (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_scmul_const a res (Hres : carry_scmul_const a = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_correct res\n        (Hres : carry = Success res)\n    : carry_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry res (Hres : carry = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma add_correct res\n        (Hres : add = Success res)\n    : add_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_add res (Hres : add = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma sub_correct res\n        (Hres : sub = Success res)\n    : sub_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_sub res (Hres : sub = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma opp_correct res\n        (Hres : opp = Success res)\n    : opp_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_opp res (Hres : opp = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_add_correct res\n        (Hres : carry_add = Success res)\n    : carry_add_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_add res (Hres : carry_add = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_sub_correct res\n        (Hres : carry_sub = Success res)\n    : carry_sub_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_sub res (Hres : carry_sub = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma carry_opp_correct res\n        (Hres : carry_opp = Success res)\n    : carry_opp_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_carry_opp res (Hres : carry_opp = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma relax_correct res\n        (Hres : relax = Success res)\n    : relax_correct tight_bounds loose_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_relax res (Hres : relax = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma from_bytes_correct res\n        (Hres : from_bytes = Success res)\n        (Hrequests : request_present requests \"from_bytes\" = true)\n    : from_bytes_correct (weight (Qnum limbwidth) (QDen limbwidth)) n n_bytes m s tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_from_bytes res (Hres : from_bytes = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma relax_valid\n    : forall x, list_Z_bounded_by tight_bounds x -> list_Z_bounded_by loose_bounds x.\n  Proof using Type. apply relax_list_Z_bounded_by, tight_bounds_tighter. Qed.\n\n  Lemma to_bytes_correct res\n        (Hres : to_bytes = Success res)\n        (Hrequests : request_present requests \"to_bytes\" = true)\n    : to_bytes_correct (weight (Qnum limbwidth) (QDen limbwidth)) n n_bytes m tight_bounds (Interp res).\n  Proof using curve_good.\n    prove_correctness (); [].\n    erewrite freeze_to_bytesmod_partitions; [ reflexivity | .. ].\n    all: try solve_prove_correctness_side_conditions ().\n  Qed.\n\n  Lemma Wf_to_bytes res (Hres : to_bytes = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [encode]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma encode_correct res\n        (Hres : encode = Success res)\n    : encode_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_encode res (Hres : encode = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [encode_word]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma encode_word_correct res\n        (Hres : encode_word = Success res)\n    : encode_word_correct machine_wordsize (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_encode_word res (Hres : encode_word = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [zero]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma zero_correct res\n        (Hres : zero = Success res)\n    : zero_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_zero res (Hres : zero = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [one]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma one_correct res\n        (Hres : one = Success res)\n    : one_correct (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_one res (Hres : one = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma copy_correct res\n        (Hres : copy = Success res)\n    : copy_correct saturated_bounds (Interp res).\n  Proof using curve_good. apply Primitives.copy_correct; assumption. Qed.\n\n  Lemma Wf_copy res (Hres : copy = Success res) : Wf res.\n  Proof using Type. revert Hres; cbv [copy]; apply Wf_copy. Qed.\n\n  Lemma selectznz_correct res\n        (Hres : selectznz = Success res)\n    : selectznz_correct saturated_bounds (Interp res).\n  Proof using curve_good. apply Primitives.selectznz_correct, Hres. Qed.\n\n  Lemma Wf_selectznz res (Hres : selectznz = Success res) : Wf res.\n  Proof using Type. revert Hres; cbv [selectznz]; apply Wf_selectznz. Qed.\n\n  Section ring.\n    Context carry_mul_res (Hcarry_mul : carry_mul = Success carry_mul_res)\n            add_res       (Hadd       : add       = Success add_res)\n            sub_res       (Hsub       : sub       = Success sub_res)\n            opp_res       (Hopp       : opp       = Success opp_res)\n            carry_res     (Hcarry     : carry     = Success carry_res)\n            encode_res    (Hencode    : encode    = Success encode_res)\n            zero_res      (Hzero      : zero      = Success zero_res)\n            one_res       (Hone       : one       = Success one_res).\n\n    Definition GoodT : Prop\n      := GoodT\n           (weight (Qnum limbwidth) (QDen limbwidth)) n m tight_bounds\n           (Interp carry_mul_res)\n           (Interp add_res)\n           (Interp sub_res)\n           (Interp opp_res)\n           (Interp carry_res)\n           (Interp encode_res)\n           (Interp zero_res)\n           (Interp one_res).\n\n    Theorem Good : GoodT.\n    Proof using curve_good Hcarry_mul Hadd Hsub Hopp Hcarry Hencode Hzero Hone.\n      pose proof use_curve_good; cbv zeta in *; destruct_head'_and.\n      eapply Good.\n      all: repeat first [ assumption\n                        | apply carry_mul_correct\n                        | apply add_correct\n                        | apply sub_correct\n                        | apply opp_correct\n                        | apply carry_correct\n                        | apply encode_correct\n                        | apply zero_correct\n                        | apply one_correct\n                        | apply relax_valid ].\n    Qed.\n  End ring.\n\n  Section for_stringification.\n    Local Open Scope string_scope.\n    Local Open Scope list_scope.\n\n    Definition known_functions\n      := [(\"carry_mul\", wrap_s scarry_mul);\n            (\"carry_square\", wrap_s scarry_square);\n            (\"carry\", wrap_s scarry);\n            (\"add\", wrap_s sadd);\n            (\"sub\", wrap_s ssub);\n            (\"opp\", wrap_s sopp);\n            (\"carry_add\", wrap_s scarry_add);\n            (\"carry_sub\", wrap_s scarry_sub);\n            (\"carry_opp\", wrap_s scarry_opp);\n            (\"relax\", wrap_s srelax);\n            (\"selectznz\", wrap_s sselectznz);\n            (\"to_bytes\", wrap_s sto_bytes);\n            (\"from_bytes\", wrap_s sfrom_bytes)].\n\n    Definition valid_names : string\n      := Eval compute in String.concat \", \" (List.map (@fst _ _) known_functions) ++ \", or 'carry_scmul' followed by a decimal literal\".\n\n    Definition extra_special_synthesis (function_name_prefix : string) (name : string)\n      : list (option { t : _ & string * Pipeline.M (Pipeline.ExtendedSynthesisResult t) }%type)\n      := [if prefix \"carry_scmul\" name\n          then let sc := substring (String.length \"carry_scmul\") (String.length name) name in\n               (scZ <- Decimal.Z.of_string sc;\n               if (sc =? Decimal.Z.to_string scZ)%string\n               then Some (wrap_s (fun _ => scarry_scmul_const function_name_prefix scZ) tt)\n               else None)%option\n          else None].\n\n    (** Note: If you change the name or type signature of this\n          function, you will need to update the code in CLI.v *)\n    Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)\n      : list (synthesis_output_kind * string * Pipeline.M (list string))\n      := Primitives.Synthesize\n           machine_wordsize valid_names known_functions (extra_special_synthesis function_name_prefix) all_typedefs!\n           check_args\n           (ToString.comment_file_header_block\n              (comment_header\n                 ++ [\"\"\n                     ; \"Computed values:\"]\n                 ++ (List.map\n                       (fun s => \"  \" ++ s)%string\n                       ((ToString.prefix_and_indent \"carry_chain = \" [show idxs])\n                          ++ (ToString.prefix_and_indent \"eval z = \" [seval \"z\"])\n                          ++ (ToString.prefix_and_indent \"bytes_eval z = \" [sbytes_eval \"z\"])\n                          ++ (ToString.prefix_and_indent \"balance = \" [let show_lvl_Z := Hex.show_lvl_Z in show balance])))))\n           function_name_prefix requests.\n  End for_stringification.\nEnd __.\n\nModule Export Hints.\n#[global]\n  Hint Opaque\n       carry_mul\n       carry_square\n       carry_scmul_const\n       carry\n       add\n       sub\n       opp\n       carry_add\n       carry_sub\n       carry_opp\n       relax\n       from_bytes\n       to_bytes\n       encode\n       encode_word\n       zero\n       one\n       copy\n       selectznz\n  : wf_op_cache.\n#[global]\n  Hint Immediate\n       Wf_carry_mul\n       Wf_carry_square\n       Wf_carry_scmul_const\n       Wf_carry\n       Wf_add\n       Wf_sub\n       Wf_opp\n       Wf_carry_add\n       Wf_carry_sub\n       Wf_carry_opp\n       Wf_relax\n       Wf_from_bytes\n       Wf_to_bytes\n       Wf_encode\n       Wf_encode_word\n       Wf_zero\n       Wf_one\n       Wf_copy\n       Wf_selectznz\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/UnsaturatedSolinas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.1943283403927874}}
{"text": "Require Import Coq.QArith.QArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.HexString.\nRequire Crypto.Util.Strings.String.\nRequire Import Crypto.Assembly.Syntax.\nRequire Import Crypto.Assembly.Parse.\nRequire Import Crypto.Assembly.Equivalence.\nRequire Import Crypto.Util.Strings.Decimal.\nRequire Import Crypto.Util.Strings.ParseArithmetic.\nRequire Import Crypto.Util.Strings.ParseArithmeticToTaps.\nRequire Import Crypto.Util.Strings.Parse.Common.\nRequire Import Crypto.Util.Strings.NamingConventions.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.OptionList.\nRequire Import Crypto.Util.Strings.Show.\nRequire Crypto.PushButtonSynthesis.SaturatedSolinas.\nRequire Crypto.PushButtonSynthesis.UnsaturatedSolinas.\nRequire Crypto.PushButtonSynthesis.WordByWordMontgomery.\nRequire Crypto.PushButtonSynthesis.BaseConversion.\nRequire Import Crypto.UnsaturatedSolinasHeuristics.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Stringification.C.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.Stringification.Rust.\nRequire Import Crypto.Stringification.Go.\nRequire Import Crypto.Stringification.Java.\nRequire Import Crypto.Stringification.JSON.\nRequire Import Crypto.Stringification.Zig.\nRequire Crypto.Util.Arg.\nImport ListNotations. Local Open Scope Z_scope. Local Open Scope string_scope.\n\nImport\n  Stringification.Language.Compilers\n  Stringification.C.Compilers.\n\nModule ForExtraction.\n  Definition parse_string_and {T} (parse_T : string -> option T) (s : string) : option (string * T)\n    := option_map (@pair _ _ s) (parse_T s).\n  Definition parse_Z (s : string) : option Z := parseZ_arith_strict s.\n  Definition parse_N (s : string) : option N := parseN_arith_strict s.\n  Definition parse_nat (s : string) : option nat := parsenat_arith_strict s.\n  Definition parse_Q (s : string) : option Q := parseQ_arith_strict s.\n  Definition parse_bool (s : string) : option bool\n    := if string_dec s \"true\"\n       then Some true\n       else if string_dec s \"false\"\n            then Some false\n            else None.\n  Definition parse_list_Z (s : string) : option (list Z)\n    := (ls <- finalize (parse_list ParseArithmetic.parse_Qexpr) s;\n          ls <-- List.map ParseArithmetic.eval_Qexpr_strict ls;\n          ls <-- List.map ParseArithmetic.Q_to_Z_strict ls;\n          Some ls).\n\n  Definition parse_list_REG (s : string) : option (list REG)\n    := finalize (parse_comma_list parse_REG) s.\n\n  (* Workaround for lack of notation in 8.8 *)\n  Local Notation \"x =? y\" := (if string_dec x y then true else false) : string_scope.\n\n  Definition parse_n (n : string) : option MaybeLimbCount\n    := match parse_nat n with\n       | Some n => Some (NumLimbs n)\n       | None\n         => let idx1 := String.length \"(auto\" in\n            let autov := substring 0 idx1 n in\n            let numv := substring idx1 (String.length n) n in\n            let numv := substring 0 (String.length numv - 1) numv in\n            let lastch := substring (String.length n - 1) 1 n in\n            if ((lastch =? \")\") && (autov =? \"(auto\"))%string%bool\n            then let numv := if (numv =? \"\")%string\n                             then Some 0%nat\n                             else parse_nat numv in\n                 option_map Auto numv\n            else None\n       end.\n\n  Definition parse_sc (s : string) : option (Z * list (Z * Z))\n    := parseZ_arith_to_taps s.\n\n  Definition parse_machine_wordsize (s : string) : option Z\n    := parse_Z s.\n  Definition parse_m (s : string) : option Z\n    := parse_Z s.\n\n  Definition parse_case_convention (s : string) : option capitalization_data\n    := parse_capitalization_data_strict s.\n  Definition valid_case_conventions : string\n    := Eval compute in\n        String.concat\n          \", \"\n          (List.flat_map\n             (fun '(_, ls)\n              => match ls with\n                 | [] => []\n                 | [n] => [n]\n                 | n :: ns\n                   => [n ++ \" (alternatively: \" ++ String.concat \", \" ns ++ \")\"]\n                 end%string)\n             parse_capitalization_data_pre_list).\n\n  Definition parse_src_n : string -> option nat := parse_nat.\n  Definition parse_limbwidth : string -> option Q := parse_Q.\n  Definition parse_max (s : string) : option (option Z)\n    := option_map (@Some _) (parse_Z s).\n  Definition parse_bounds_multiplier (s : option string) : string * option (option Q)\n    := let s := Option.value s \"\" in\n       (s,\n        if string_dec s \"\"\n        then Some None\n        else option_map (@Some _) (parse_Q s)).\n  Definition parse_dirbounds_multiplier (dir : string) (s : option string + list string) : string * (option Q + list string)\n    := match s with\n       | inl s\n         => let '(s, q) := parse_bounds_multiplier s in\n            (s,\n             match q with\n             | Some q => inl q\n             | None => inr [\"Could not parse '\" ++ s ++ \"' as a \u211a for --\" ++ dir ++ \"bounds-multiplier\"]%string\n             end)\n       | inr opts\n         => (\"\", inr [\"Argument --\" ++ dir ++ \"bounds-multiplier can only be passed once; passed multiple times with values: \" ++ String.concat \", \" opts])\n       end.\n\n  Definition parse_bounds_list (s : option string) : string * option (option (list Z))\n    := match s with\n       | None => (\"\", Some None)\n       | Some s\n         => (s,\n             option_map (@Some _) (parse_list_Z s))\n       end.\n\n  Definition parse_dirbounds (dir : string) (s : option string + list string) (use_bitwidth : bool) : string * (BaseConversion.bounds + list string)\n    := match s with\n       | inl s\n         => let '(s, ls) := parse_bounds_list s in\n            (s,\n             match ls, use_bitwidth with\n             | Some (Some ls), false => inl (BaseConversion.exactly ls)\n             | Some None, false => inl BaseConversion.use_prime\n             | Some None, true => inl BaseConversion.use_bitwidth\n             | _, _\n               => let err1 := match ls, use_bitwidth with\n                              | Some _, true => [\"Cannot pass both --use-bitwidth-\" ++ dir ++ \" and --\" ++ dir ++ \"bounds=\" ++ s]%string\n                              | _, _ => []\n                              end in\n                  let err2 := match ls with\n                              | None => [\"Could not parse \" ++ dir ++ \"bounds (\" ++ s ++ \")\"]%string\n                              | _ => []\n                              end in\n                  inr (err1 ++ err2)%list\n             end)\n       | inr opts\n         => (\"\",\n             inr (([\"Argument --\" ++ dir ++ \"bounds can only be passed once; passed multiple times with values: \" ++ String.concat \", \" opts]%string)\n                    ++ if use_bitwidth\n                       then [\"Cannot pass both --use-bitwidth-\" ++ dir ++ \" and --\" ++ dir ++ \"bounds\"]%string\n                       else [])%list)\n       end.\n\n  Definition show_c : Show (list (Z * Z))\n    := @show_list _ (@show_prod _ _ PowersOfTwo.show_Z Decimal.show_Z).\n\n  Local Open Scope string_scope.\n\n  (** TODO: Write a better quoter and maybe move this elsewhere *)\n  (** https://mywiki.wooledge.org/BashGuide/SpecialCharacters *)\n  (** We also quote the \"/\" character so that we don't change quoting behavior based on Windows vs Linux paths *)\n  Definition quote (s : string) : string\n    := if List.existsb (fun ch => List.existsb (fun badch => badch =? ch)%char\n                                               [\" \"; \"$\"; \"'\"; \"\"\"\"; \"\\\"; \"#\"; \"=\"; \"!\"; \">\"; \"<\"; \"|\"; \";\"; \"{\"; \"}\"; \"(\"; \")\"; \"[\"; \"]\"; \"*\"; \"?\"; \"~\"; \"&\"; \"`\"; \"/\"]%char)\n                       (String.list_ascii_of_string s)\n          || (String.length s =? 0)%nat\n       then \"'\" ++ String.replace \"'\" \"'\"\"'\"\"'\" s ++ \"'\"\n       else s.\n\n  Definition CollectErrors\n             {machine_wordsize : machine_wordsize_opt}\n             {output_language_api : ToString.OutputLanguageAPI}\n             (res : list (synthesis_output_kind * string * Pipeline.ErrorT (list string)) + list string)\n    : ((* normal *) list (list string) * (* asm output *) list (list string)) + (* error *) list (list string)\n    := match res with\n       | inl res\n         => let header := hd \"\" (List.map (@snd _ _) (List.map (@fst _ _) res)) in\n            let res :=\n                List.fold_right\n                  (fun '(kind, name, res) rest\n                   => match kind, res, rest with\n                      | _, ErrorT.Error err, rest\n                        => let in_name := (\"In \" ++ name ++ \":\") in\n                           let cur :=\n                               match show_lines false err with\n                               | [serr] => [in_name ++ \" \" ++ serr]\n                               | serr => in_name::serr\n                               end in\n                           let rest := match rest with inl _ => nil | inr rest => rest end in\n                           inr (cur :: rest)\n                      | _, ErrorT.Success v, inr ls => inr ls\n                      | normal_output, ErrorT.Success v_normal, inl (ls_normal, ls_asm)\n                        => inl (v_normal :: ls_normal, ls_asm)\n                      | assembly_output, ErrorT.Success v_asm, inl (ls_normal, ls_asm)\n                        => inl (ls_normal, v_asm :: ls_asm)\n                      end)\n                  (inl (nil, nil))\n                  res in\n            match res with\n            | inl ls => inl ls\n            | inr err => inr ([header]::err)\n            end\n       | inr res\n         => inr [res]\n       end.\n\n  Class supported_languagesT := supported_languages : list (string * ToString.OutputLanguageAPI).\n\n  (** N.B. The order matters, as the first element of the supported\n      languages list is used as the default. *)\n  Definition default_supported_languages : supported_languagesT\n    := [(\"C\", ToString.OutputCAPI)\n        ; (\"Rust\", Rust.OutputRustAPI)\n        ; (\"Go\", Go.OutputGoAPI)\n        ; (\"Java\", Java.OutputJavaAPI)\n        ; (\"JSON\", JSON.OutputJSONAPI)\n        ; (\"Zig\", Zig.OutputZigAPI)].\n\n  Local Notation anon_argT := (string * Arg.spec * Arg.doc)%type (only parsing).\n  Local Notation named_argT := (list Arg.key * Arg.spec * Arg.doc)%type (only parsing).\n\n  Definition curve_description_spec : anon_argT\n    := (\"curve_description\",\n        Arg.String,\n        [\"A string which will be prefixed to every function name generated\"]).\n  Definition lang_default {supported_languages : supported_languagesT}\n    := List.hd (\"C\", ToString.OutputCAPI) supported_languages.\n  Definition lang_spec {supported_languages : supported_languagesT} : named_argT\n    := let supported_language_names := List.map (@fst _ _) supported_languages in\n       ([Arg.long_key \"lang\"],\n        Arg.CustomSymbol supported_languages,\n        [\"The output language code should be emitted in.  Defaults to \" ++ List.hd \"C\" supported_language_names ++ \" if no language is given.  Case-sensitive.\"]).\n  Definition no_prefix_fiat_spec : named_argT\n    := ([Arg.long_key \"no-prefix-fiat\"], Arg.Unit, [\"Don't prefix functions with fiat_\"]).\n  Definition package_name_spec : named_argT\n    := ([Arg.long_key \"package-name\"], Arg.String, [\"The name of the package, for languages that support it.\"]).\n  Definition class_name_spec : named_argT\n    := ([Arg.long_key \"class-name\"], Arg.String, [\"The name of the class, for languages that support it.\"]).\n  Definition private_function_case_spec : named_argT\n    := ([Arg.long_key \"private-function-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for non-exported function names.  Default is to not adjust case, resulting in, roughly, snake_case.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition public_function_case_spec : named_argT\n    := ([Arg.long_key \"public-function-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for exported function names.  Default is to not adjust case, resulting in, roughly, snake_case.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition private_type_case_spec : named_argT\n    := ([Arg.long_key \"private-type-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for non-exported type names.  Default is to not adjust case, resulting in, roughly, snake_case.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition public_type_case_spec : named_argT\n    := ([Arg.long_key \"public-type-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for exported type names.  Default is to not adjust case, resulting in, roughly, snake_case.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition class_case_spec : named_argT\n    := ([Arg.long_key \"class-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for the default class name.  Only meaningful when the class name is inferred from curve_description, rather than given explicitly with --class-name.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition package_case_spec : named_argT\n    := ([Arg.long_key \"package-case\"],\n        Arg.Custom (parse_string_and parse_case_convention) \"CONVENTION\",\n        [\"The case convention for the default package name.  Only meaningful when the package name is inferred from curve_description, rather than given explicitly with --package-name.\"\n         ; \"Valid options are: \" ++ valid_case_conventions ++ \".\"]).\n  Definition static_spec : named_argT\n    := ([Arg.long_key \"static\"], Arg.Unit, [\"Declare the functions as static, i.e., local to the file.\"]).\n  Definition internal_static_spec : named_argT\n    := ([Arg.long_key \"internal-static\"], Arg.Unit, [\"Declare internal functions as static, i.e., local to the file.\"]).\n  Definition only_signed_spec : named_argT\n    := ([Arg.long_key \"only-signed\"], Arg.Unit, [\"Only allow signed integer types.\"]).\n  Definition no_select_spec : named_argT\n    := ([Arg.long_key \"no-select\"], Arg.Unit, [\"Use expressions that don't require cmov.\"]).\n  Definition no_wide_int_spec : named_argT\n    := ([Arg.long_key \"no-wide-int\"], Arg.Unit, [\"Don't use integers wider than the bitwidth.\"]).\n  Definition widen_carry_to_bytes_spec : named_argT\n    := ([Arg.long_key \"widen-carry-to-bytes\"], Arg.Unit, [\"Always widen carry bit integer types the byte type, or to the full bitwidth if --widen-bytes is also passed.\"]).\n  Definition widen_carry_spec : named_argT\n    := ([Arg.long_key \"widen-carry\"], Arg.Unit, [\"Widen carry bit integer types to either the byte type, or to the full bitwidth if --widen-bytes is also passed.\"]).\n  Definition widen_bytes_spec : named_argT\n    := ([Arg.long_key \"widen-bytes\"], Arg.Unit, [\"Widen byte types to the full bitwidth.\"]).\n  Definition split_multiret_spec : named_argT\n    := ([Arg.long_key \"split-multiret\"], Arg.Unit, [\"Don't allow instructions to return two results. This should always be set for bedrock2.\"]).\n  Definition value_barrier_spec : named_argT\n    := ([Arg.long_key \"use-value-barrier\"], Arg.Unit, [\"Guard some expressions with an assembly barrier to prevent compilers from generating non-constant-time code for cmovznz.\"]).\n  Definition no_primitives_spec : named_argT\n    := ([Arg.long_key \"no-primitives\"], Arg.Unit, [\"Suppress the generation of the bodies of primitive operations such as addcarryx, subborrowx, cmovznz, mulx, etc.\"]).\n  Definition cmovznz_by_mul_spec : named_argT\n    := ([Arg.long_key \"cmovznz-by-mul\"], Arg.Unit, [\"Use an alternative implementation of cmovznz using multiplication rather than bitwise-and with -1.\"]).\n  Definition tight_bounds_multiplier_default := default_tight_upperbound_fraction.\n  Definition tight_bounds_multiplier_spec : named_argT\n    := ([Arg.long_key \"tight-bounds-mul-by\"],\n        Arg.Custom (parse_string_and parse_Q) \"\u211a\",\n        [\"The (improper) fraction by which the (tight) bounds of each limb are scaled\"]).\n  Definition n_spec : anon_argT\n    := (\"n\",\n        Arg.Custom (parse_string_and parse_n) \"an \u2115 or the literal '(auto)' or '(autoN)' for a non-negative number N\",\n        [\"The number of limbs, or the literal '(auto)' or '(autoN)' for a non-negative number N, to automatically guess the number of limbs\"]).\n  Definition sc_spec : anon_argT\n    := (\"s-c\",\n        Arg.Custom (parse_string_and parse_sc) \"an integer expression\",\n        [\"The prime, which must be expressed as a difference of a power of two and a small field element (e.g., '2^255 - 19', '2^448 - 2^224 - 1')\"]).\n  Definition m_spec : anon_argT\n    := (\"m\",\n        Arg.Custom (parse_string_and parse_m) \"an integer expression\",\n        [\"The prime (e.g., '2^434 - (2^216*3^137 - 1)')\"]).\n  Definition machine_wordsize_spec : anon_argT\n    := (\"machine_wordsize\",\n        Arg.Custom (parse_string_and parse_machine_wordsize) \"an integer\",\n        [\"The machine bitwidth (e.g., 32 or 64)\"]).\n  Definition src_n_spec : anon_argT\n    := (\"src_n\",\n        Arg.Custom (parse_string_and parse_src_n) \"\u2115\",\n        [\"The number of limbs in the input\"]).\n  Definition src_limbwidth_spec : anon_argT\n    := (\"src_limbwidth\",\n        Arg.Custom (parse_string_and parse_limbwidth) \"\u2115\",\n        [\"The limbwidth of the input field element\"]).\n  Definition dst_limbwidth_spec : anon_argT\n    := (\"dst_limbwidth\",\n        Arg.Custom (parse_string_and parse_limbwidth) \"\u2115\",\n        [\"The limbwidth of the field element to be returned\"]).\n  Definition use_bitwidth_in_spec : named_argT\n    := ([Arg.long_key \"use-bitwidth-in\"],\n        Arg.Unit,\n        [\"Instead of using an upper bound of s-1 on the input, use the maximum number that can be properly represented with the given base\"]).\n  Definition use_bitwidth_out_spec : named_argT\n    := ([Arg.long_key \"use-bitwidth-out\"],\n        Arg.Unit,\n        [\"Instead of using an upper bound of s-1 on the output, use the maximum number that can be properly represented with the given base\"]).\n  Definition default_inbounds_multiplier := 1.\n  Definition inbounds_multiplier_spec : named_argT\n    := ([Arg.long_key \"inbounds-multiplier\"],\n        Arg.String,\n        [\"The (improper) fraction by which the bounds of each input limb are scaled (default: \" ++ show false default_inbounds_multiplier ++ \")\"]).\n  Definition default_outbounds_multiplier := 1.\n  Definition outbounds_multiplier_spec : named_argT\n    := ([Arg.long_key \"outbounds-multiplier\"],\n        Arg.String,\n        [\"The (improper) fraction by which the bounds of each output limb are scaled (default: \" ++ show false default_outbounds_multiplier ++ \")\"]).\n  Definition inbounds_spec : named_argT\n    := ([Arg.long_key \"inbounds\"],\n        Arg.String,\n        [\"A semicolon-separated, square-bracked-surrounded list of integer expressions describing the input bounds.  Incompatible with --use-bitwidth-in.\"]).\n  Definition outbounds_spec : named_argT\n    := ([Arg.long_key \"outbounds\"],\n        Arg.String,\n        [\"A semicolon-separated, square-bracked-surrounded list of integer expressions describing the output bounds.  Incompatible with --use-bitwidth-out.\"]).\n  Definition function_to_synthesize_spec (valid_names : string) : anon_argT\n    := (\"function_to_synthesize\",\n        Arg.String,\n        [\"A space-separated list of functions that should be synthesized.  If no functions are given, all functions are synthesized.\"\n         ; \"Valid options are \" ++ valid_names ++ \".\"]).\n  Definition hint_file_spec : named_argT\n    := ([Arg.long_key \"hints-file\"],\n        Arg.String,\n        [\"An assembly file to be read for hinting the synthesis process.  Use - for stdin.\"]).\n  Definition output_file_spec : named_argT\n    := ([Arg.long_key \"output\"; Arg.short_key \"o\"],\n        Arg.String,\n        [\"The name of the file to write output to.  Use - for stdout.  (default: -)\"]).\n  Definition asm_output_spec : named_argT\n    := ([Arg.long_key \"output-asm\"],\n        Arg.String,\n        [\"The name of the file to write generated assembly to.  Use - for stdout.  (default: -)\"]).\n  Definition asm_reg_spec : named_argT\n    := ([Arg.long_key \"asm-reg\"],\n        Arg.Custom (parse_string_and parse_list_REG) \"REG\",\n        [\"A comma-separated list of registers to use for calling conventions.  Only relevant when --hints-file is specified.\"\n         ; \"Defaults to the System V AMD64 ABI of \" ++ String.concat \",\" (List.map (show false) default_assembly_calling_registers) ++ \".  Note that registers are first used for outputs and then inputs.\"]).\n  Definition asm_stack_size_spec : named_argT\n    := ([Arg.long_key \"asm-stack-size\"],\n        Arg.Custom (parse_string_and parse_N) \"\u2115\",\n        [\"The number of bytes of stack.  Only relevant when --hints-file is specified.  Default: \" ++ show false (default_assembly_stack_size:N) ++ \".\"]).\n  Definition no_error_on_unused_asm_functions_spec : named_argT\n    := ([Arg.long_key \"no-error-on-unused-asm-functions\"],\n        Arg.Unit,\n        [\"Don't error if there are global labels in the hints-file which are not requested functions.\"]).\n  Definition asm_input_first_spec : named_argT\n    := ([Arg.long_key \"asm-input-first\"],\n        Arg.Unit,\n        [\"By default, output pointers are assumed to come before input arguments in the C code the assembly hints are based on.  This flag reverses that convention.\"]).\n  Definition asm_reg_rtl_spec : named_argT\n    := ([Arg.long_key \"asm-reg-rtl\"],\n        Arg.Unit,\n        [\"By default, registers are assumed to be assigned to function arguments from left to right in the hints file.  This flag reverses that convention to be right-to-left.  Note that this flag interacts with --asm-input-first, which determines whether the output pointers are to the left or to the right of the input arguments.\"]).\n\n  Definition collapse_list_default {A} (default : A) (ls : list A)\n    := List.hd default (List.rev ls).\n\n  Definition join_errors {A B} (x : A + list string) (y : B + list string) : (A * B) + list string\n    := match x, y with\n       | inr errs1, inr errs2 => inr (errs1 ++ errs2)%list\n       | inr err, inl _ | inl _, inr err => inr err\n       | inl x, inl y => inl (x, y)\n       end.\n\n  (** We define a class for holding the various options we might pass to [Synthesize] *)\n  (** We split up the ones we can directly parse and the ones we have to process *)\n  Class ParsedSynthesizeOptions :=\n    {\n      (** Is the code static / inlined *)\n      static :> static_opt\n      (** Is the internal code static / inlined *)\n      ; internal_static :> internal_static_opt\n      (** Should we only use signed integers *)\n      ; only_signed :> only_signed_opt\n      (** Should we emit expressions requiring cmov *)\n      ; no_select :> no_select_opt\n      (** Should we emit primitive operations *)\n      ; emit_primitives :> emit_primitives_opt\n      (** Should we use the alternate implementation of cmovznz *)\n      ; use_mul_for_cmovznz :> use_mul_for_cmovznz_opt\n      (** Should we split apart oversized operations? *)\n      ; should_split_mul :> should_split_mul_opt\n      (** Should we split apart multi-return operations? *)\n      ; should_split_multiret :> should_split_multiret_opt\n      (** Should we remove use of value_barrier? *)\n      ; unfold_value_barrier :> unfold_value_barrier_opt\n      (** Should we widen the carry to the full bitwidth? *)\n      ; widen_carry :> widen_carry_opt\n      (** Should we widen the byte type to the full bitwidth? *)\n      ; widen_bytes :> widen_bytes_opt\n      (** What method should we use for rewriting? *)\n      ; low_level_rewriter_method :> low_level_rewriter_method_opt\n        := default_low_level_rewriter_method\n      (** What's the bitwidth? *)\n      ; machine_wordsize :> machine_wordsize_opt\n      (** What's the package name *)\n      ; internal_package_name :> package_name_opt\n      (** What's the class name *)\n      ; internal_class_name :> class_name_opt\n      (** What's are the naming conventions to use? *)\n      ; language_naming_conventions :> language_naming_conventions_opt\n      (** list of registers for calling assembly functions *)\n      ; assembly_calling_registers :> assembly_calling_registers_opt\n      (** size of the stack in bytes *)\n      ; assembly_stack_size :> assembly_stack_size_opt\n      (** error if there are un-requested assembly functions *)\n      ; error_on_unused_assembly_functions :> error_on_unused_assembly_functions_opt\n      (** Are output arrays considered to come before input arrays, or after them? *)\n      ; assembly_output_first :> assembly_output_first_opt\n      (** Should we assign registers to the arguments in left-to-right or right-to-left order? *)\n      ; assembly_argument_registers_left_to_right :> assembly_argument_registers_left_to_right_opt\n      (** don't prepend fiat to prefix *)\n      ; no_prefix_fiat : bool\n    }.\n  Class SynthesizeOptions :=\n    {\n      parsed_synthesize_options :> ParsedSynthesizeOptions\n      (** Lines of assembly hints *)\n      ; assembly_hints_lines :> assembly_hints_lines_opt\n    }.\n\n  (** We define a class for holding the various options about file interaction that we don't pass to [Synthesize] *)\n  Class IODriverOptions :=\n    {\n      (** The name of the file holding assembly hints *)\n      hint_file_names : list string\n      (** The name of the file to output to *)\n      ; output_file_name : string\n      (** The name of the file to output assembly to *)\n      ; asm_output_file_name : string\n    }.\n\n  Fixpoint with_read_concat_asm_files_cps\n           {A}\n           (with_read_file : string (* fname *) -> (list string -> A) -> A)\n           (hint_file_names : list string)\n    : (assembly_hints_lines_opt -> A) -> A\n    := match hint_file_names with\n       | nil => fun k => k None\n       | fname :: fnames\n         => fun k\n            => with_read_file\n                 fname\n                 (fun lines\n                  => with_read_concat_asm_files_cps\n                       with_read_file\n                       fnames\n                       (fun rest_lines => k (Some (lines ++ Option.value rest_lines nil)%list)))\n       end.\n\n  Definition common_optional_options {supported_languages : supported_languagesT}\n    := [lang_spec\n        ; package_name_spec\n        ; class_name_spec\n        ; package_case_spec\n        ; class_case_spec\n        ; private_function_case_spec\n        ; public_function_case_spec\n        ; private_type_case_spec\n        ; public_type_case_spec\n        ; no_prefix_fiat_spec\n        ; static_spec\n        ; internal_static_spec\n        ; no_wide_int_spec\n        ; widen_carry_spec\n        ; widen_bytes_spec\n        ; no_select_spec\n        ; split_multiret_spec\n        ; value_barrier_spec\n        ; no_primitives_spec\n        ; cmovznz_by_mul_spec\n        ; only_signed_spec\n        ; hint_file_spec\n        ; output_file_spec\n        ; asm_output_spec\n        ; asm_reg_spec\n        ; asm_stack_size_spec\n        ; no_error_on_unused_asm_functions_spec\n        ; asm_input_first_spec\n        ; asm_reg_rtl_spec\n       ].\n\n  Definition parse_common_optional_options\n             {supported_languages : supported_languagesT}\n             {machine_wordsizev : machine_wordsize_opt}\n             (data : Arg.keyed_spec_list_data common_optional_options)\n    : (IODriverOptions * ParsedSynthesizeOptions * ToString.OutputLanguageAPI) + list string\n    := let '(langv\n             , package_namev\n             , class_namev\n             , package_casev\n             , class_casev\n             , private_function_casev\n             , public_function_casev\n             , private_type_casev\n             , public_type_casev\n             , no_prefix_fiatv\n             , staticv\n             , internal_staticv\n             , no_wide_intv\n             , widen_carryv\n             , widen_bytesv\n             , no_selectv\n             , split_multiretv\n             , value_barrierv\n             , no_primitivesv\n             , cmovznz_by_mulv\n             , only_signedv\n             , hint_file_namesv\n             , output_file_namev\n             , asm_output_file_namev\n             , asm_regv\n             , asm_stack_sizev\n             , no_error_on_unused_asm_functionsv\n             , asm_input_firstv\n             , asm_reg_rtlv\n            ) := data in\n       let to_bool ls := (0 <? List.length ls)%nat in\n       let to_string_list ls := List.map (@snd _ _) ls in\n       let to_N_list ls := List.map (@snd _ _) (List.map (@snd _ _) ls) in\n       let to_reg_list ls := match List.map (@snd _ _) (List.map (@snd _ _) ls) with\n                             | nil => None\n                             | ls => Some (List.concat ls)\n                             end in\n       let to_N_opt ls := List.nth_error (to_N_list ls) 0 in\n       let to_N_default ls default := Option.value (to_N_opt ls) default in\n       let to_string_opt ls := List.nth_error (to_string_list ls) 0 in\n       let to_string_default ls default := Option.value (to_string_opt ls) default in\n       let to_capitalization_data_opt ls := List.nth_error (List.map (fun '(_, (_, v)) => v) ls) 0 in\n       let to_capitalization_convention_opt ls\n           := option_map (fun d => {| capitalization_convention_data := d ; only_lower_first_letters := true |})\n                         (to_capitalization_data_opt ls) in\n       let res\n           := ({|\n                  hint_file_names := to_string_list hint_file_namesv\n                  ; output_file_name := to_string_default output_file_namev \"-\"\n                  ; asm_output_file_name := to_string_default asm_output_file_namev \"-\"\n                |},\n               {| static := to_bool staticv\n                  ; internal_class_name := to_string_opt class_namev\n                  ; internal_package_name := to_string_opt package_namev\n                  ; language_naming_conventions\n                    := {| public_function_naming_convention := to_capitalization_convention_opt public_function_casev\n                          ; private_function_naming_convention := to_capitalization_convention_opt private_function_casev\n                          ; public_type_naming_convention := to_capitalization_convention_opt public_type_casev\n                          ; private_type_naming_convention := to_capitalization_convention_opt private_type_casev\n                          ; variable_naming_convention := None\n                          ; package_naming_convention := to_capitalization_convention_opt package_casev\n                          ; class_naming_convention := to_capitalization_convention_opt class_casev\n                       |}\n                  ; no_prefix_fiat := to_bool no_prefix_fiatv\n                  ; internal_static := to_bool internal_staticv\n                  ; widen_carry := to_bool widen_carryv\n                  ; widen_bytes := to_bool widen_bytesv\n                  ; no_select := to_bool no_selectv\n                  ; only_signed := to_bool only_signedv\n                  ; should_split_mul := to_bool no_wide_intv\n                  ; should_split_multiret := to_bool split_multiretv\n                  ; unfold_value_barrier := negb (to_bool value_barrierv)\n                  ; use_mul_for_cmovznz := to_bool cmovznz_by_mulv\n                  ; emit_primitives := negb (to_bool no_primitivesv)\n                  ; assembly_calling_registers := to_reg_list asm_regv\n                  ; assembly_stack_size := to_N_opt asm_stack_sizev\n                  ; error_on_unused_assembly_functions := negb (to_bool no_error_on_unused_asm_functionsv)\n                  ; assembly_output_first := negb (to_bool asm_input_firstv)\n                  ; assembly_argument_registers_left_to_right := negb (to_bool asm_reg_rtlv)\n               |},\n               snd (List.hd lang_default langv)) in\n       match langv with\n       | [] | [_] => inl res\n       | opts => inr [\"Only one language specification with --lang is allowed; multiple languages were requested: \" ++ String.concat \", \" (List.map (@fst _ _) opts)]\n       end.\n\n  (** We define a class for the various operations that are specific to a pipeline *)\n  Class PipelineAPI :=\n    {\n      (** The spec of curve-specific command line arguments *)\n      spec : Arg.arg_spec;\n      (** Type of arguments parsed from the command line *)\n      ParsedArgsT : Type;\n      (** Type of (unparsed) arguments remembered from the command line *)\n      StringArgsT : Type;\n      ArgsT := (StringArgsT * ParsedArgsT)%type;\n\n      (** Takes in args parsed via the spec and post-parses\n          curve-specific arguments, returning either [inl value] or\n          [inr errors] *)\n      parse_args : forall {synthesize_opts : SynthesizeOptions}, Arg.arg_spec_results spec -> ArgsT + list string;\n\n      (** Renders a header at the top displaying the command line\n          arguments.  Will be wrapped in a comment block *)\n      show_lines_args : ArgsT -> list string;\n\n      (** The Synthesize function from the pipeline *)\n      (** N.B. [comment_header] will be passed in *without* wrapping\n          it in a comment block first *)\n      Synthesize : forall\n          {output_language_api : ToString.OutputLanguageAPI}\n          {synthesize_opts : SynthesizeOptions}\n          (args : ParsedArgsT) (comment_header : list string) (function_name_prefix : string),\n          list (synthesis_output_kind * string * Pipeline.ErrorT (list string))\n    }.\n\n  (** API for performing IO *)\n  Class IODriverAPI {A} :=\n    {\n      error : list string -> A\n      ; ret : unit -> A\n      ; with_read_stdin : (list string -> A) -> A\n      ; write_stdout_then : list string (* lines, to be joined with \"\" *) -> (unit -> A) -> A\n      ; with_read_file : string (* fname *) -> (list string -> A) -> A\n      ; write_file_then : string (* fname *) -> list string (* lines, to be joined with \"\" *) -> (unit -> A) -> A\n    }.\n  Global Arguments IODriverAPI : clear implicits.\n\n  Module Export Notations.\n    Bind Scope list_scope with supported_languagesT.\n  End Notations.\n\n  Module Parameterized.\n    Section __.\n      Context {api : PipelineAPI}.\n\n      Definition PipelineLines\n                 {output_language_api : ToString.OutputLanguageAPI}\n                 {synthesize_opts : SynthesizeOptions}\n                 (invocation : string)\n                 (curve_description : string)\n                 (str_machine_wordsize : string)\n                 (args : ArgsT)\n        : list (synthesis_output_kind * string * Pipeline.ErrorT (list string)) + list string\n        := let prefix := ((if no_prefix_fiat then \"\" else \"fiat_\")\n                            ++ (if (curve_description =? \"\") then \"\" else (curve_description ++ \"_\")))%string in\n           let header :=\n               (([\"Autogenerated: \" ++ invocation\n                  ; match (curve_description =? \"\"), internal_package_name, internal_class_name with\n                    | false, _, _\n                    | _, (None | Some \"\"), (None | Some \"\")\n                      => \"curve description: \" ++ curve_description\n                    | _, Some pkg, _\n                      => \"curve description (via package name): \" ++ pkg\n                    | _, _, Some cls\n                      => \"curve description (via class name): \" ++ cls\n                    end\n                  ; \"machine_wordsize = \" ++ show false (machine_wordsize:Z) ++ \" (from \"\"\" ++ str_machine_wordsize ++ \"\"\")\"]%string)\n                  ++ show_lines_args args)%list in\n           inl (Synthesize (snd args) header prefix).\n\n      Definition strip_trailing_spaces (s : string) : string\n        := String.concat String.NewLine (List.map String.rtrim (String.split String.NewLine s)).\n\n      Definition ProcessedLines\n                 {output_language_api : ToString.OutputLanguageAPI}\n                 {synthesize_opts : SynthesizeOptions}\n                 (invocation : string)\n                 (curve_description : string)\n                 (str_machine_wordsize : string)\n                 (args : ArgsT)\n        : ((* normal *) list string * (* asm *) list string) + list string\n        := match CollectErrors (PipelineLines invocation curve_description str_machine_wordsize args) with\n           | inl (ls_normal, ls_asm)\n             => let postprocess_lines\n                    := List.flat_map (fun s => ((List.map (fun s => s ++ String.NewLine) (List.map strip_trailing_spaces s))%string)\n                                                 ++ [String.NewLine])%list in\n                inl (postprocess_lines ls_normal, postprocess_lines ls_asm)\n           | inr nil => inr nil\n           | inr (l :: ls)\n             => inr (l ++ (List.flat_map\n                             (fun e => String.NewLine :: e)\n                             ls))%list\n           end.\n\n      Definition Pipeline\n                 {A}\n                 {output_language_api : ToString.OutputLanguageAPI}\n                 {synthesize_opts : SynthesizeOptions}\n                 (invocation : string)\n                 (curve_description : string)\n                 (str_machine_wordsize : string)\n                 (args : ArgsT)\n                 (success : list string * list string -> A)\n                 (error : list string -> A)\n        : A\n        := match ProcessedLines invocation curve_description str_machine_wordsize args with\n           | inl s => success s\n           | inr s => error s\n           end.\n\n      Definition PipelineMain\n                 {supported_languages : supported_languagesT}\n                 {A}\n                 {io_driver : IODriverAPI A}\n                 (argv : list string)\n        : A\n        := let with_read_file fname\n               := if (fname =? \"-\")%string then with_read_stdin else with_read_file fname in\n           let write_file_then fname\n               := if (fname =? \"-\")%string then write_stdout_then else write_file_then fname in\n           let invocation := String.concat \" \" (List.map quote argv) in\n           let full_spec\n               := {| Arg.named_args := common_optional_options ++ spec.(Arg.named_args)\n                     ; Arg.anon_args := curve_description_spec :: machine_wordsize_spec :: spec.(Arg.anon_args)\n                     ; Arg.anon_opt_args := spec.(Arg.anon_opt_args)\n                     ; Arg.anon_opt_repeated_arg := spec.(Arg.anon_opt_repeated_arg) |} in\n           match Arg.parse_argv argv full_spec with\n           | ErrorT.Success (named_data, anon_data, anon_opt_data, anon_opt_repeated_data)\n             => let '(common_named_data, named_data) := Arg.split_type_of_list' (ls1:=List.map _ common_optional_options) named_data in\n                let '((curve_description, (str_machine_wordsize, machine_wordsize)), anon_data) := Arg.split_type_of_list' (ls1:=[_;_]) anon_data in\n                let machine_wordsize : machine_wordsize_opt := machine_wordsize in\n                match parse_common_optional_options common_named_data with\n                | inl (io_driver_opts, opts, output_language_api)\n                  => with_read_concat_asm_files_cps\n                       with_read_file\n                       hint_file_names\n                       (fun assembly_hints_linesv\n                        => let success :=\n                               fun '(normal_lines, asm_lines)\n                               => write_file_then\n                                    output_file_name\n                                    normal_lines\n                                    (fun 'tt\n                                     => match asm_lines, assembly_hints_linesv with\n                                        | nil, None => ret tt\n                                        | _, _ => write_file_then\n                                                    asm_output_file_name\n                                                    asm_lines\n                                                    ret\n                                        end) in\n                           let opts := {|\n                                 parsed_synthesize_options := opts\n                                 ; assembly_hints_lines := assembly_hints_linesv\n                               |} in\n                           match parse_args (named_data, anon_data, anon_opt_data, anon_opt_repeated_data) with\n                           | inl args\n                             => Pipeline invocation curve_description str_machine_wordsize args success error\n                           | inr errs => error errs\n                           end)\n                | inr errs => error errs\n                end\n           | ErrorT.Error err => error (Arg.show_list_parse_error full_spec err)\n           end.\n    End __.\n  End Parameterized.\n\n  Module UnsaturatedSolinas.\n    Local Instance api : PipelineAPI\n      := {\n          spec :=\n            {| Arg.named_args := [tight_bounds_multiplier_spec]\n               ; Arg.anon_args := [n_spec; sc_spec]\n               ; Arg.anon_opt_args := []\n               ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec UnsaturatedSolinas.valid_names) |};\n\n          parse_args opts args\n          := let '(tight_bounds_multiplier, ((str_n, n), (str_sc, (s, c))), tt, requests) := args in\n             let show_requests := match requests with nil => \"(all)\" | _ => String.concat \", \" requests end in\n             let '(str_tight_bounds_multiplier, tight_bounds_multiplier) := collapse_list_default (\"\", tight_bounds_multiplier_default) (List.map (@snd _ _) tight_bounds_multiplier) in\n             let tight_bounds_multiplier : tight_upperbound_fraction_opt := tight_bounds_multiplier in\n             match get_num_limbs s c machine_wordsize n, n with\n             | None, NumLimbs n => inr [\"Internal error: get_num_limbs (on (\" ++ PowersOfTwo.show_Z false s ++ \", \" ++ show_c false c ++ \", \" ++ show false (machine_wordsize:Z) ++ \", \" ++ show false n ++ \")) returned None even though the argument was NumLimbs\"]\n             | None, Auto idx => inr [\"Invalid index \" ++ show false idx ++ \" when guessing the number of limbs for s-c = \" ++ PowersOfTwo.show_Z false s ++ \" - \" ++ show_c false c ++ \"; valid indices must index into the list \" ++ show false (get_possible_limbs s c machine_wordsize) ++ \".\"]\n             | Some n, _\n               => inl\n                    ((str_n, str_sc, str_tight_bounds_multiplier, show_requests),\n                     (n, s, c, tight_bounds_multiplier, requests))\n             end;\n\n          show_lines_args :=\n            fun '((str_n, str_sc, str_tight_bounds_multiplier, show_requests),\n                  (n, s, c, tight_bounds_multiplier, requests))\n            => [\"requested operations: \" ++ show_requests;\n               \"n = \" ++ show false n ++ \" (from \"\"\" ++ str_n ++ \"\"\")\";\n               \"s-c = \" ++ PowersOfTwo.show_Z false s ++ \" - \" ++ show_c false c ++ \" (from \"\"\" ++ str_sc ++ \"\"\")\";\n               \"tight_bounds_multiplier = \" ++ show false (tight_bounds_multiplier:Q) ++ \" (from \"\"\" ++ str_tight_bounds_multiplier ++ \"\"\")\"]%string;\n\n          Synthesize\n          := fun _ opts '(n, s, c, tight_bounds_multiplier, requests) comment_header prefix\n             => UnsaturatedSolinas.Synthesize n s c machine_wordsize comment_header prefix requests;\n        }.\n\n    Definition PipelineMain\n               {supported_languages : supported_languagesT}\n               {A}\n               {io_driver : IODriverAPI A}\n               (argv : list string)\n      : A\n      := Parameterized.PipelineMain argv.\n  End UnsaturatedSolinas.\n\n  Module WordByWordMontgomery.\n    Local Instance api : PipelineAPI\n      := {\n          spec :=\n            {| Arg.named_args := []\n               ; Arg.anon_args := [m_spec]\n               ; Arg.anon_opt_args := []\n               ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec WordByWordMontgomery.valid_names) |};\n\n          parse_args opts args\n          := let '(tt, (str_m, m), tt, requests) := args in\n             let show_requests := match requests with nil => \"(all)\" | _ => String.concat \", \" requests end in\n             inl ((str_m, show_requests),\n                  (m, requests));\n\n          show_lines_args :=\n            fun '((str_m, show_requests),\n                  (m, requests))\n            => [\"requested operations: \" ++ show_requests;\n               \"m = \" ++ Hex.show_Z false m ++ \" (from \"\"\" ++ str_m ++ \"\"\")\";\n               \"                                                                  \";\n               \"NOTE: In addition to the bounds specified above each function, all\";\n               \"  functions synthesized for this Montgomery arithmetic require the\";\n               \"  input to be strictly less than the prime modulus (m), and also  \";\n               \"  require the input to be in the unique saturated representation. \";\n               \"  All functions also ensure that these two properties are true of \";\n               \"  return values.                                                  \"];\n\n          Synthesize\n          := fun _ opts '(m, requests) comment_header prefix\n             => WordByWordMontgomery.Synthesize m machine_wordsize comment_header prefix requests\n        }.\n\n    Definition PipelineMain\n               {supported_languages : supported_languagesT}\n               {A}\n               {io_driver : IODriverAPI A}\n               (argv : list string)\n      : A\n      := Parameterized.PipelineMain argv.\n  End WordByWordMontgomery.\n\n  Module SaturatedSolinas.\n    Local Instance api : PipelineAPI\n      := {\n          spec :=\n            {| Arg.named_args := []\n               ; Arg.anon_args := [sc_spec]\n               ; Arg.anon_opt_args := []\n               ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec SaturatedSolinas.valid_names) |};\n\n          parse_args opts args\n          := let '(tt, (str_sc, (s, c)), tt, requests) := args in\n             let show_requests := match requests with nil => \"(all)\" | _ => String.concat \", \" requests end in\n             inl ((str_sc, show_requests),\n                  (s, c, requests));\n\n          show_lines_args :=\n            fun '((str_sc, show_requests),\n                  (s, c, requests))\n            => [\"requested operations: \" ++ show_requests;\n               \"s-c = \" ++ PowersOfTwo.show_Z false s ++ \" - \" ++ show_c false c ++ \" (from \"\"\" ++ str_sc ++ \"\"\")\"];\n\n          Synthesize\n          := fun _ opts '(s, c, requests) comment_header prefix\n             => SaturatedSolinas.Synthesize s c machine_wordsize comment_header prefix requests\n        }.\n\n    Definition PipelineMain\n               {supported_languages : supported_languagesT}\n               {A}\n               {io_driver : IODriverAPI A}\n               (argv : list string)\n      : A\n      := Parameterized.PipelineMain argv.\n  End SaturatedSolinas.\n\n  Module BaseConversion.\n    Local Instance api : PipelineAPI\n      := {\n          spec :=\n            {| Arg.named_args := [inbounds_multiplier_spec; outbounds_multiplier_spec; inbounds_spec; outbounds_spec; use_bitwidth_in_spec; use_bitwidth_out_spec]\n               ; Arg.anon_args := [src_n_spec; sc_spec; src_limbwidth_spec; dst_limbwidth_spec]\n               ; Arg.anon_opt_args := []\n               ; Arg.anon_opt_repeated_arg := Some (function_to_synthesize_spec BaseConversion.valid_names) |};\n\n          parse_args opts args\n          := let '((inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, use_bitwidth_in, use_bitwidth_out),\n                   ((str_src_n, src_n), (str_sc, (s, c)), (str_src_limbwidth, src_limbwidth), (str_dst_limbwidth, dst_limbwidth)),\n                   tt,\n                   requests) := args in\n             let show_requests := match requests with nil => \"(all)\" | _ => String.concat \", \" requests end in\n             let to_bool ls := (0 <? List.length ls)%nat in\n             let to_string_opt ls := List.nth_error (List.map (@snd _ _) ls) 0 in\n             let inbounds_multiplier := to_string_opt inbounds_multiplier in\n             let outbounds_multiplier := to_string_opt outbounds_multiplier in\n             let inbounds := to_string_opt inbounds in\n             let outbounds := to_string_opt outbounds in\n             let use_bitwidth_in := to_bool use_bitwidth_in in\n             let use_bitwidth_out := to_bool use_bitwidth_out in\n             let '(str_inbounds_multiplier, inbounds_multiplier) := parse_dirbounds_multiplier \"in\" (inl inbounds_multiplier) in\n             let '(str_outbounds_multiplier, outbounds_multiplier) := parse_dirbounds_multiplier \"out\" (inl outbounds_multiplier) in\n             let '(str_inbounds, inbounds) := parse_dirbounds \"in\" (inl inbounds) use_bitwidth_in in\n             let '(str_outbounds, outbounds) := parse_dirbounds \"out\" (inl outbounds) use_bitwidth_out in\n             match join_errors\n                     (join_errors\n                        inbounds_multiplier\n                        outbounds_multiplier)\n                     (join_errors\n                        inbounds\n                        outbounds)\n             with\n             | inr errs => inr errs\n             | inl ((inbounds_multiplier, outbounds_multiplier), (inbounds, outbounds))\n               => inl ((str_src_n, str_sc, str_src_limbwidth, str_dst_limbwidth, str_inbounds_multiplier, str_outbounds_multiplier, use_bitwidth_in, use_bitwidth_out, str_inbounds, str_outbounds, show_requests),\n                       (src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests))\n             end;\n\n          show_lines_args :=\n            fun '((str_src_n, str_sc, str_src_limbwidth, str_dst_limbwidth, str_inbounds_multiplier, str_outbounds_multiplier, use_bitwidth_in, use_bitwidth_out, str_inbounds, str_outbounds, show_requests),\n                  (src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests))\n            => [\"requested operations: \" ++ show_requests;\n               \"src_n = \" ++ show false src_n ++ \" (from \"\"\" ++ str_src_n ++ \"\"\")\";\n               \"s-c = \" ++ PowersOfTwo.show_Z false s ++ \" - \" ++ show_c false c ++ \" (from \"\"\" ++ str_sc ++ \"\"\")\";\n               \"src_limbwidth = \" ++ show false src_limbwidth ++ \" (from \"\"\" ++ str_src_limbwidth ++ \"\"\")\";\n               \"dst_limbwidth = \" ++ show false dst_limbwidth ++ \" (from \"\"\" ++ str_dst_limbwidth ++ \"\"\")\";\n               \"inbounds_multiplier = \" ++ show false inbounds_multiplier ++ \" (from \"\"\" ++ str_inbounds_multiplier ++ \"\"\")\";\n               \"outbounds_multiplier = \" ++ show false outbounds_multiplier ++ \" (from \"\"\" ++ str_outbounds_multiplier ++ \"\"\")\";\n               \"inbounds = \" ++ show false inbounds ++ \" (from \"\"\" ++ str_inbounds ++ \"\"\" and use_bithwidth_in = \" ++ show false use_bitwidth_in ++ \")\";\n               \"outbounds = \" ++ show false outbounds ++ \" (from \"\"\" ++ str_outbounds ++ \"\"\" and use_bithwidth_out = \" ++ show false use_bitwidth_out ++ \")\"];\n\n          Synthesize\n          := fun _ opts '(src_n, s, c, src_limbwidth, dst_limbwidth, inbounds_multiplier, outbounds_multiplier, inbounds, outbounds, requests) comment_header prefix\n             => BaseConversion.Synthesize s c src_n src_limbwidth dst_limbwidth machine_wordsize inbounds_multiplier outbounds_multiplier inbounds outbounds comment_header prefix requests\n        }.\n\n    Definition PipelineMain\n               {supported_languages : supported_languagesT}\n               {A}\n               {io_driver : IODriverAPI A}\n               (argv : list string)\n      : A\n      := Parameterized.PipelineMain argv.\n  End BaseConversion.\nEnd ForExtraction.\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/CLI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19423646169227823}}
{"text": "(**\n----\n_This file is part of_\n\n----\n*** A Formal Definition of JML in Coq #<br/># and its Application to Runtime Assertion Checking\nPh.D. Thesis by Hermann Lehner\n----\nOnline available at #<a href=\"http://jmlcoq.info/\">jmlcoq.info</a>#\n\nAuthors:\n  - Hermann Lehner\n  - David Pichardie (Bicolano)\n  - Andreas Kaegi (Syntax Rewritings, Implementation of ADTs)\n\nCopyright 2011 Hermann Lehner\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*)\n\nFrom JML Require Export JMLRac2.\nFrom Coq Require Import List.\nFrom JML Require Import Stack.\nFrom Coq Require Import ListSet.\nFrom Coq Require Import Bool.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Relation_Operators.\nFrom JML Require Import ListHelpers.\nFrom Coq Require Import Classical.\nFrom Coq Require Import DecidableType.\nFrom Coq Require Import FSetInterface.\nFrom Coq Require Import FSetProperties.\nFrom Coq Require Import FSetEqProperties.\nFrom Coq Require Import FSetFacts.\nFrom Coq Require Import Sumbool.\nFrom Coq Require Import Lia.\n\nImport Dom.\nImport Prog.\nImport JmlNotations.\nImport METHODSPEC.\nImport TYPESPEC.\n\nModule LocSetProp := Properties LocSet.\nImport LocSetProp.\nModule LocSetPropEq := EqProperties LocSet.\nImport LocSetPropEq.\nModule LocSetFacts := Facts LocSet.\nImport LocSetFacts.\n\nOpen Scope jml_scope.\n\n(** * The JML Runtime Assertion Checker Rac3\nThis module describes the runtime assertions checks for suported JML-Level 0 constructs *)\n\nModule Rac3 <: JML.\n\n(** ** Implementation of the JML Frame for Rac3 *)\n\n  Declare Module LocDict: DICT \n    with Definition Key := (* pivot *) Location\n    with Definition Val := (* dg *) LocSet.t.\n\n\n  Declare Module Backlinks : DICT \n    with Definition Key := (* field *) Location\n    with Definition Val := LocDict.t.\n\n\n\nDefinition StaticDGs (p : Program) (f : Location) : list Location :=\n  match f with\n  | Heap.InstanceField obj fsig =>\n    match findField p fsig with\n    | Some f =>\n      let dgs := FIELD.dataGroups f in\n      let dgs_static := filter (fun dg => negb (DATA_GROUP.isDynamic dg)) dgs in\n      let dgfsig := flat_map DATA_GROUP.dataGroups dgs_static in\n      map (Heap.InstanceField obj) dgfsig\n    | _ => []\n    end\n  | _ => []\n  end.\n\nLemma StaticDGs_Correct:\nforall p field_am dg_am,\nIn dg_am (StaticDGs p field_am) <-> direct_FieldInDg_static p field_am dg_am.\nProof.\nintuition.\n unfold StaticDGs in H.\n case_eq field_am; intros; subst; try inversion H.\n case_eq (findField p f); intros; rewrite H0 in H; try inversion H.\n apply in_map_iff in H.\n destruct H as [dg_fsig H].\n destruct H.\n apply in_flat_map in H1.\n destruct H1 as [dg H1].\n destruct H1.\n apply filter_In in H1.\n destruct H1.\n split with o dg_fsig o f f0 dg; auto.\n case_eq (DATA_GROUP.isDynamic dg); intros.\n  rewrite H4 in H3; inversion H3.\n  \n  trivial.\n  \n destruct H.\n unfold StaticDGs.\n rewrite H0.\n rewrite H2.\n apply in_map_iff.\n exists dg_fsig.\n rewrite <- H1.\n split; auto.\n apply in_flat_map.\n exists dg.\n rewrite filter_In.\n split.\n  split.\n   trivial.\n   \n   rewrite H4.\n   simpl; trivial.\n   \n  trivial.\nQed.\n\n\nFixpoint option_list2list {A : Type} (l: list (option A)) : list A :=\nmatch l with\n| nil => nil\n| (h::t) =>\n    match h with\n    | Some a => (a :: option_list2list t)\n    | _ => option_list2list t\n    end\n end.\n\nLemma some_list_list:\nforall {A : Type} (l : list (option A)) x,\nIn (Some x) l <-> In x (option_list2list l).\nProof.\ninduction l.\n simpl.\n tauto.\n \n intros.\n simpl.\n split; intro.\n  destruct H.\n   rewrite H.\n   auto with *.\n   \n   rewrite IHl in H.\n   destruct a.\n    auto with *.\n    \n    trivial.\n    \n  case_eq a.\n   intros.\n   rewrite H0 in H.\n   simpl in H.\n   destruct H.\n    rewrite H.\n    tauto.\n    \n    right.\n    rewrite IHl; trivial.\n    \n   intros.\n   right.\n   rewrite IHl.\n   rewrite H0 in H.\n   trivial.\nQed.\n\nDeclare Module FsigDec : DecidableType with Definition t := FieldSignature\n\t                                with Definition eq := eq (A := FieldSignature).\n\nDefinition DynamicDGs (p : Program) (f_fsig : FieldSignature) (pivot : Location) : list Location :=\n  match pivot with\n  | Heap.InstanceField pivot_obj pivot_fsig =>\n    match findField p pivot_fsig with\n    | Some pivot_f =>\n      let dgs_dyn := filter (fun dg => DATA_GROUP.isDynamic dg) (FIELD.dataGroups pivot_f) in\n                let dgs_f_target := filter (fun dg => \n                  match DATA_GROUP.pivotTarget dg with\n                  | Some (FieldDg fsig) => if FsigDec.eq_dec fsig f_fsig then true else false\n                  | _ => false\n                  end        \n                  ) dgs_dyn in\n                let dg_fsig := flat_map DATA_GROUP.dataGroups dgs_f_target in\n                map (Heap.InstanceField pivot_obj) dg_fsig\n      | _ => []\n    end\n  | _ => []\n  end.\n\nLemma DynamicDGs_Correct:\nforall p h f_obj f_fsig pivot dg,\nHeap.get h pivot = Some (Ref f_obj) ->\n(In dg (DynamicDGs p f_fsig pivot) <-> direct_FieldInDg_dynamic p h (Heap.InstanceField f_obj f_fsig) dg pivot).\nProof.\nintuition.\n unfold DynamicDGs in H0.\n case_eq pivot; intros; rewrite H1 in H0; try inversion H0.\n rename o into pivot_obj.\n rename f into pivot_fsig.\n case_eq (findField p pivot_fsig); intros; rewrite H2 in H0; try inversion H0.\n rename f into pivot_f.\n  apply in_map_iff in H0.\n  destruct H0 as (dg_fsig, H0).\n  destruct H0.\n  apply in_flat_map in H3.\n  destruct H3 as (dgt, H3).\n  destruct H3.\n  apply filter_In in H3.\n  destruct H3.\n  apply filter_In in H3.\n  destruct H3.\n  case_eq (DATA_GROUP.pivotTarget dgt); intros; rewrite H7 in H5.\n   case_eq d; intros.\n   rewrite H8 in H5.\n   rewrite H8 in H7.\n   clear d H8.\n   case_eq (FsigDec.eq_dec fsig f_fsig); intros.\n    unfold FsigDec.eq in e.\n    rewrite e in H7.\n    clear H5 H8.\n    clear fsig e.\n    split\n     with pivot_obj dg_fsig f_obj f_fsig pivot_obj pivot_fsig pivot_f dgt;\n     trivial.\n     auto.\n     \n     rewrite <- H1; trivial.\n     \n    rewrite H8 in H5; inversion H5.\n    \n   inversion H5.\n   \n inversion H0.\n unfold DynamicDGs.\n rewrite H3.\n rewrite H5.\n inversion H2.\n rewrite <- H16.\n  \n   apply in_map_iff.\n   exists dg_fsig.\n   split.\n    rewrite <- H10; auto.\n    \n    apply in_flat_map.\n    exists dg0.\n    rewrite filter_In.\n    split.\n     split.\n      rewrite filter_In.\n      split.\n       trivial.\n       \n       trivial.\n       \n      rewrite H8.\n    destruct FsigDec.eq_dec.\n     trivial.\n     \n     elim n.\n     auto.\n     \n   trivial.\nQed.\n\nDefinition PivotTargets (p : Program) (pivot : Location) : list FieldSignature :=\n  match pivot with \n  | Heap.InstanceField pivot_obj pivot_fsig =>\n    match findField p pivot_fsig with\n    | Some pivot_f =>\n      let dgs_dyn := filter (fun dg => DATA_GROUP.isDynamic dg) (FIELD.dataGroups pivot_f) in\n      let fsigs_option := (map (fun dg => match (DATA_GROUP.pivotTarget dg) with \n                                                            | Some (FieldDg fsig) => Some fsig\n                                                            | _ => None end) dgs_dyn) in\n       option_list2list fsigs_option\n    | _ => []\n    end\n  | _ => []\n  end.\n\nLemma PivotTargets_Correct:\nforall p h f_fsig f_obj pivot,\nHeap.get h pivot = Some (Ref f_obj) ->\n(In f_fsig (PivotTargets p pivot) <-> exists dg, direct_FieldInDg_dynamic p h (Heap.InstanceField f_obj f_fsig) dg pivot).\nProof.\nintuition.\n unfold PivotTargets in H0.\n case_eq pivot; intros; rewrite H1 in H0; try inversion H0.\n rename o into pivot_obj.\n rename f into pivot_fsig.\n case_eq (findField p pivot_fsig); intros; rewrite H2 in H0; try inversion H0.\n apply some_list_list in H0.\n apply in_map_iff in H0.\n destruct H0 as (dg, H0).\n destruct H0.\n case_eq (DATA_GROUP.pivotTarget dg); intros; rewrite H4 in H0.\n  case_eq d; intros; rewrite H5 in H0.\n  apply filter_In in H3.\n  destruct H3.\n  generalize DATA_GROUP.dataGroups_not_nil.\n  intro.\n  specialize H7 with dg.\n  case_eq (DATA_GROUP.dataGroups dg); intros.\n   elim H7; trivial.\n   \n   exists (Heap.InstanceField pivot_obj f0).\n   split with pivot_obj f0 f_obj f_fsig pivot_obj pivot_fsig f dg; trivial.\n    rewrite <- H1; trivial.\n    \n    inversion H0.\n    rewrite H10 in H5.\n    rewrite <- H5.\n    trivial.\n    \n    rewrite H8.\n    auto with *.\n    \n     inversion H0.\n   \n destruct H0 as (dg, H0).\n inversion H0.\n unfold PivotTargets.\n rewrite H3.\n rewrite H5.\n  \n  apply some_list_list.\n   apply in_map_iff.\n   exists dg0.\n   rewrite H8.\n   inversion H2.\n   split;auto.\n   apply filter_In.\n   split.\n   trivial.\n   trivial.\nQed.\n\nLemma PivotTargets_not_nil:\nforall p pivot,\nPivotField p pivot ->\nexists fsig , In fsig (PivotTargets p pivot).\nProof.\nintros.\ninversion H.\nunfold PivotTargets.\nrewrite H0.\nrewrite H1.\ncase_eq (DATA_GROUP.pivotTarget dg);intros.\n destruct d.\n exists fsig0.\n apply some_list_list.\n apply in_map_iff.\n exists dg.\n rewrite H4.\n split; trivial.\n apply filter_In.\n tauto.\nunfold DATA_GROUP.isDynamic in H3.\nrewrite H4 in H3.\ninversion H3.\nQed.\n\n\n  Definition set_backlink (bl :Backlinks.t) (f : Location) (pivot : Location) (dgs: LocSet.t) : Backlinks.t :=\n    match Backlinks.get bl f with\n    | None => \n      Backlinks.update bl f (LocDict.singleton pivot dgs)\n    | Some amdict => \n      let amdict' := LocDict.update amdict pivot dgs in \n      Backlinks.update bl f amdict'\n    end.\n\n  Definition remove_backlink (bl : Backlinks.t) (f : Location) (pivot: Location) : Backlinks.t :=\n    match Backlinks.get bl f with\n    | None => bl\n    | Some amdict =>\n      let amdict' := LocDict.remove amdict pivot in\n      Backlinks.update bl f amdict'\n    end.\n\n  Definition get_backlinks (bl : Backlinks.t) (f: Location) : LocDict.t :=\n  match Backlinks.get bl f with\n  | None => LocDict.empty\n  | Some am => am\n  end.\n\nModule Adds <: ADDS.\n\n  Record t_rec : Type := make {\n    backlinks: Backlinks.t\n  }.\n\n  Definition t := t_rec.\n\nEnd Adds.\n\nModule FrameAdds := Rac2.FrameAdds.\n\nModule Frame := Rac2.Frame.\nDeclare Module State : STATE \n  with Module Frame := Frame \n  with Module Adds := Adds.\n\nModule Notations.\n\n  Declare Scope rac3_scope.\n  Delimit Scope rac3_scope with rac3.\n\n  Open Scope rac3_scope.\n\n  Notation \"st '@h'\" := (State.h st) (at level 1, left associativity): rac3_scope.\n  Notation \"st '@fr'\" := (State.fr st) (at level 1, left associativity) : rac3_scope.\n  Notation \"st '@adds'\" := (State.adds st) (at level 1, left associativity) : rac3_scope.\n  Notation \"st '@bl'\" := (Adds.backlinks st@adds) (at level 1, left associativity) : rac3_scope.\n\n  Notation \"st '[h' ':=' h ']'\" := (State.set_h st h) (at level 1, left associativity): rac3_scope.\n  Notation \"st '[fr' ':=' fr ']'\" := (State.set_fr st fr) (at level 1, left associativity) : rac3_scope.\n  Notation \"st '[adds' ':=' adds ']'\" := (State.set_adds st adds) (at level 1, left associativity) : rac3_scope.\n  Notation \"st '[bl' ':=' bl ']'\" := (st[adds := Adds.make bl]) (at level 1, left associativity) : rac3_scope.\n  Notation \"[ h , fr , adds ]\" := (State.build h fr adds) : rac3_scope.\n\nEnd Notations.\n\n\nImport Sem.Notations.\nImport Rac1.Notations.\nImport Rac2.Notations.\nImport Notations.\n\nOpen Scope nat_scope.\n\n(** A new JML Frame is initialized with the assignable locations from the caller *)\nDefinition NewFrame (m : Method) (p : ParamDict.t) (st : State.t) : Frame.t :=\n  let adds := FrameAdds.make ((LocSet.empty,LocSetAll)::st@fr@assignables) (ObjSet.empty::st@fr@fresh) (st@h , p) VarDict.empty in\n  Frame.build m p adds.\n\nInductive DGTree :=  DGNode (am : Location) (dgs: list DGTree).\n\nSection correct_dgtree_ind.\nVariables (P : DGTree ->  Prop) (Q : list DGTree ->  Prop).\nHypotheses\n   (H : forall (a : Location) (l : list DGTree), Q l ->  P (DGNode a l))\n   (H0 : Q nil)\n   (H1 : forall (t : DGTree),\n         P t -> forall (l : list DGTree ), Q l ->  Q (cons t l)).\n\nFixpoint DGTree_ind2 (t : DGTree) : P t :=\n match t as x return P x with\n    DGNode a l =>\n      H a l ((fix l_ind (l' : list DGTree) : Q l' :=\n                     match l' as x return Q x with\n                     | nil => H0\n                     | cons t1 tl => H1 t1 (DGTree_ind2 t1) tl (l_ind tl)\n                     end) l)\n end.\nEnd correct_dgtree_ind.\n\nInductive InDG (dg : Location) (tree : DGTree) : Prop :=\n| InDG_base: \n  forall kids,\n  tree = (DGNode dg kids) ->\n  InDG dg tree\n| InDG_step:\n  forall kids f tree',\n  tree = (DGNode f kids) ->\n  dg <> f ->\n  In tree' kids ->\n  InDG dg tree' ->\n  InDG dg tree.\n\nFixpoint InDGTree (dg : Location) (tree : DGTree) : bool :=\nmatch tree with\n| DGNode f kids =>\n  if LocDec.eq_dec dg f then true\n  else fold_right (fun tree' => (orb (InDGTree dg tree'))) false kids\nend.\n\nDefinition DGSubTree (t1 t2: DGTree) : Prop :=\nforall a,\nInDG a t1 -> InDG a t2.\n\nLemma fold_right_andb:\nforall (A : Type) (l : list A) f,\nfold_right (fun elem b => (f elem) && b) true l = true <-> (forall elem, In elem l -> f elem = true).\nProof.\nsplit; intros.\n induction l.\n  inversion H0.\n  \n  simpl in H0.\n  simpl in H.\n  rewrite andb_true_iff in H.\n  destruct H.\n  destruct H0.\n   rewrite <- H0; trivial.\n   \n   apply IHl; trivial.\n   \n induction l.\n  simpl; trivial.\n  \n  simpl.\n  rewrite andb_true_iff.\n  split.\n   apply H.\n   auto with *.\n   \n   apply IHl.\n   intros.\n   apply H.\n   auto with *.\nQed.\n\nLemma fold_right_orb:\nforall (A : Type) (l : list A) f,\nfold_right (fun elem b => (f elem) || b) false l = true <-> (exists elem, In elem l /\\ f elem = true).\nProof.\nsplit;intros.\ninduction l.\n simpl in H.\n discriminate H.\n \n simpl in H.\n apply orb_prop in H.\n destruct H.\n  exists a.\n  auto with *.\n  \n  apply IHl in H.\n  destruct H.\n  exists x.\n  intuition auto with datatypes.\n\n destruct H as (elem, H).\n destruct H.\n induction l.\n  inversion H.\n  \n  simpl.\n  apply orb_true_intro.\n  destruct H.\n   left.\n   rewrite H.\n   trivial.\n   \n   right.\n   apply IHl.\n   trivial.\nQed.\n\nLemma LocSet_fold_orb:\nforall f s,  LocSet.fold (fun e b => (f e) || b) s false = true <-> exists e, LocSet.In e s /\\ f e = true.\nProof.\nintros.\nrewrite LocSet.fold_1.\nrewrite <- fold_left_rev_right.\nrewrite fold_right_orb.\nsplit; intros.\n destruct H as (e, H).\n rewrite <- in_rev in H.\n exists e.\n destruct H.\n split.\n  apply LocSet.elements_2.\n  unfold LocSet.E.eq.\n  clear H0.\n  induction (LocSet.elements s).\n   inversion H.\n   \n   simpl in H.\n   destruct H.\n    apply InA_cons_hd.\n    auto.\n    \n    apply InA_cons_tl.\n    apply IHl; trivial.\n    \n  trivial.\n  \n destruct H as (e, H).\n exists e.\n split.\n  destruct H.\n  rewrite <- in_rev.\n  apply LocSet.elements_1 in H.\n  unfold LocSet.E.eq in H.\n  induction H.\n   left; auto.\n   \n   right.\n   trivial.\n   \n  tauto.\nQed.\n\nLemma fold_right_union:\nforall e l,\nLocSet.In e (fold_right LocSet.union LocSet.empty l) \n<->\nexists s, In s l /\\ LocSet.In e s.\nProof.\ninduction l.\n intuition.\n  simpl in H.\n  apply LocSet.empty_1 in H.\n  tauto.\n  \n  destruct H.\n  tauto.\n  \n simpl.\n intuition.\n  apply LocSet.union_1 in H1.\n  destruct H1.\n   exists a.\n   split; tauto.\n   \n   apply H in H1.\n   destruct H1.\n   exists x.\n   split; tauto.\n   \n  destruct H1.\n  destruct H1.\n  destruct H1.\n   apply LocSet.union_2.\n   rewrite H1.\n   trivial.\n   \n   apply LocSet.union_3.\n   apply H0.\n   exists x.\n   tauto.\nQed.\n\nLemma In_InA: \nforall x l,\nInA LocSet.E.eq x l <-> In x l.\nProof.\nintros.\ninduction l.\nsimpl.\nintuition.\ninversion H.\nsimpl.\nintuition.\ninversion H1.\nsubst.\nleft.\nauto.\nsubst.\nright.\napply H;trivial.\nQed.\n\nLemma InDGTree_Correct:\nforall tree dg,\nInDG dg tree <-> InDGTree dg tree = true.\nProof.\nsplit;intros.\ninduction H.\n subst.\n simpl.\n case_eq (LocDec.eq_dec dg dg); intro; trivial.\n elim n; trivial.\n \n unfold InDGTree.\n rewrite H.\n destruct LocDec.eq_dec; trivial.\nfold InDGTree.\n apply fold_right_orb.\n exists tree'.\n tauto.\n\ngeneralize dg H.\nclear dg H.\nelim tree using\n DGTree_ind2\n  with\n    (Q := fun kids =>\n          forall dg tree',\n          In tree' kids -> InDGTree dg tree' = true -> InDG dg tree').\n intros.\n unfold InDGTree in H0.\n case_eq (LocDec.eq_dec dg a).\n  intros.\n  apply InDG_base with l.\n  unfold LocDec.eq in e.\n  rewrite e.\n  trivial.\n  \n  intros.\n  unfold LocDec.eq in n.\n  rewrite H1 in H0.\n  apply fold_right_orb in H0.\n  destruct H0 as (tree', H0).\n  destruct H0.\n  apply InDG_step with l a tree'; trivial.\n  apply H; trivial.\n  \n intros.\n inversion H.\n \n intros.\n simpl in H1.\n destruct H1.\n  rewrite <- H1.\n  rewrite <- H1 in H2.\n  apply H; trivial.\n  \n  apply H0; trivial.\nQed.\n\n\nDefinition FieldOfNode (n : DGTree) : LocSet.elt :=\nmatch n with\n| DGNode f _ => f\nend.\n\nInductive ValidDGTree (p : Program) (bl : Backlinks.t) (ep : LocSet.t) \n                 (f : Location) (m : LocSet.t) : DGTree -> Prop :=\n| ValidDGTree_def:\n  forall  dg dgs ad f'list f'list',\n  dg = DGNode f dgs ->\n  get_backlinks bl f = ad ->\n  (LocSet.elements (fold_right (LocSet.union) \n        LocSet.empty \n        (LocDict.filter ad (fun f'' => ~ LocSet.In f'' ep))))  \n        +++ (StaticDGs p f) = f'list' ->\n  filter (fun f'' => LocSet.mem f'' m) f'list' = f'list ->\n  length dgs = length f'list ->\n  (forall n f'' f' dgs', \n    n < length dgs ->\n    nth n  f'list f'' = f' ->\n    nth n dgs (DGNode f'' []) = dgs' ->\n    ValidDGTree p bl ep f' (LocSet.remove f' m) dgs') ->\n  ValidDGTree p bl ep f m dg.\n\nLemma ValidDGTree_func: forall p bl ep tree f m,\nValidDGTree p bl ep f m tree ->\nforall tree',\nValidDGTree p bl ep f m tree' -> \ntree = tree'.\nProof.\nintros p bl ep tree.\nelim tree using\n DGTree_ind2\n  with\n    (Q := fun kids =>\n          forall k f m,\n          In k kids ->\n          ValidDGTree p bl ep f (LocSet.remove f m) k ->\n          forall k', ValidDGTree p bl ep f (LocSet.remove f m) k' -> eq k k').\n intros.\n inversion H0.\n inversion H1.\n rewrite H9.\n inversion H2.\n rewrite H18 in H.\n assert (eq dgs dgs0).\n  rewrite H3 in H10.\n  rewrite <- H10 in H11.\n  rewrite H4 in H11.\n  rewrite <- H11 in H12.\n  rewrite H5 in H12.\n  rewrite <- H12 in H13.\n  rewrite <- H12 in H14.\n  rewrite <- H6 in H13.\n  clear a l H0 tree' H1 dg ad f'list' H2 H3 H4 H5 H8 dg0 ad0 f'list0 f'list'0\n   H9 H10 H11 H12 H15 H17 H18.\n  assert\n   (forall n f'',\n    (nth n dgs (DGNode f'' nil)) = (nth n dgs0 (DGNode f'' nil))).\n   intros.\n   case_eq (Nat.compare n (length dgs)); intros.\n    assert (le (length dgs) n).\n     rewrite nat_compare_Eq in H0.\n     lia.\n     \n     generalize H1; intro.\n     apply nth_overflow with (d := DGNode f'' nil) in H1.\n     rewrite <- H13 in H2.\n     apply nth_overflow with (d := DGNode f'' nil) in H2.\n     rewrite H1; rewrite H2; trivial.\n     \n    rewrite <- nat_compare_lt in H0.\n    apply H with (nth n f'list f'') m.\n     apply nth_In; trivial.\n     \n     apply H7 with n f''; trivial.\n     \n     apply H14 with n f''; trivial.\n     rewrite H13; trivial.\n     \n    assert (le (length dgs) n).\n     rewrite <- nat_compare_gt in H0.\n     lia.\n     \n     generalize H1; intro.\n     apply nth_overflow with (d := DGNode f'' nil) in H1.\n     rewrite <- H13 in H2.\n     apply nth_overflow with (d := DGNode f'' nil) in H2.\n     rewrite H1; rewrite H2; trivial.\n     \n   clear p bl ep tree H f m f'list H6 H7 H14.\n   symmetry  in H13.\n   generalize dgs0, H13, H0.\n   clear dgs0 H13 H0.\n   induction dgs.\n    intros.\n    destruct dgs0; trivial.\n    inversion H13.\n    \n    intros.\n    destruct dgs0.\n     inversion H13.\n     \n     assert (eq a d).\n      destruct a.\n      specialize H0 with O am.\n      simpl in H0; trivial.\n      \n      assert (eq dgs dgs0).\n       apply IHdgs.\n        auto.\n        \n        intros.\n        specialize H0 with (S n) f''.\n        simpl in H0; trivial.\n        \n       rewrite H; rewrite H1; trivial.\n       \n  rewrite H16; trivial.\n  \n intros.\n inversion H.\n \n intros.\n simpl in H1.\n destruct H1.\n  rewrite <- H1.\n  rewrite <- H1 in H2.\n  apply H with f (LocSet.remove f m); trivial.\n  \n  apply H0 with f m; trivial.\nQed.\n\nLemma ValidDGTree_exists: forall p bl ep m,\nforall f, exists dg, ValidDGTree p bl ep f m dg.\nProof.\nintros p bl ep m.\nassert (exists n , n = LocSet.cardinal m).\nexists (LocSet.cardinal m);trivial.\ndestruct H as [n H].\ngeneralize n m H.\nclear m n H.\ninduction n.\n\n intros.\n set (ad := get_backlinks bl f).\n set\n  (f'list' :=\n    (LocSet.elements (fold_right (LocSet.union) LocSet.empty (LocDict.filter ad (fun f'' => ~ LocSet.In f'' ep))))  +++ (StaticDGs p f)).\n exists (DGNode f nil).\n apply\n  ValidDGTree_def\n   with (dgs := nil) (ad := ad) (f'list' := f'list') (f'list := nil); \n  trivial.\n  induction f'list'.\n   simpl; trivial.\n   \n   simpl.\n   symmetry  in H.\n   rewrite <- LocSetProp.cardinal_Empty in H.\n   replace (LocSet.mem a m) with false .\n    trivial.\n    \n    case_eq (LocSet.mem a m); intro; trivial.\n    apply LocSet.mem_2 in H0.\n    unfold LocSet.Empty in H.\n    destruct H with a; trivial.\n    \n  intros.\n  simpl in H0.\n  inversion H0.\n  \n intros.\n set (ad := get_backlinks bl f).\n set\n  (f'list' :=\n    (LocSet.elements (fold_right (LocSet.union) LocSet.empty (LocDict.filter ad (fun f'' => ~ LocSet.In f'' ep))))  +++ (StaticDGs p f)).\n set (f'list := filter (fun f'' => LocSet.mem f'' m) f'list').\n set (dgsEx := (exists dgs, length dgs = length f'list /\\ forall n f'' f' dgs', n < length dgs ->\n    nth n  f'list f'' = f' ->\n    nth n dgs (DGNode f'' []) = dgs' ->\n    ValidDGTree p bl ep f' (LocSet.remove f' m) dgs')).\nunfold ad in f'list'.\n\n elim classic with dgsEx; intros.\n  destruct H0 as (dgs, H0).\n  clear dgsEx.\n  destruct H0.\n  exists (DGNode f dgs).\n  apply\n   ValidDGTree_def\n    with (dgs := dgs) (ad := ad) (f'list' := f'list') (f'list := f'list);\n   trivial.\n  \n  elim H0.\nunfold dgsEx.\n  apply not_all_not_ex.\n  intro.\n  clear H0 dgsEx.\n  induction f'list'.\n   specialize H1 with (nil (A:=DGTree)).\n   destruct H1.\n   split.\n    trivial.\n    \n    intros.\n    inversion H0.\n    \n   apply IHf'list'.\n   clear IHf'list'.\n   intro.\n   intro.\n   case_eq (LocSet.mem a m); intro.\n    specialize IHn with (m := LocSet.remove a m).\n    destruct IHn with a.\n     apply eq_add_S.\n     rewrite H.\n     symmetry .\n     apply LocSetProp.remove_cardinal_1.\n     apply LocSet.mem_2; trivial.\n     apply H1 with (cons x n0).\n     split.\n      unfold f'list.\n      simpl.\n      rewrite H2.\n      simpl.\n      lia.\n      \n      destruct H0.\n      intros.\n      unfold f'list in H6.\n      simpl in H6.\n      rewrite H2 in H6.\n      case_eq n1; intros.\n       simpl in H7.\n       rewrite H8 in H7.\n       simpl in H6.\n       rewrite H8 in H6.\n       rewrite <- H6.\n       rewrite <- H7.\n       trivial.\n       \n       simpl in H7.\n       apply H4 with n2 f''.\n        rewrite H8 in H5.\n        simpl in H5.\n        auto with *.\n        \n        rewrite H8 in H6.\n        simpl in H6.\n        trivial.\n        \n        rewrite H8 in H7.\n        trivial.\n\n    apply H1 with n0.\n    unfold f'list.\n    simpl.\n    rewrite H2.\n    trivial.\nQed.\n\nLemma ValidDGTree_1:\nforall p bl ep f m dg,\nValidDGTree p bl ep f m dg ->\nexists dgs, dg = DGNode f dgs.\nProof.\nintros.\ninversion H.\nexists dgs.\ntrivial.\nQed.\n\nLemma ValidDGTree_EqualSets:\nforall p bl ep n f tree  s1 s2 ,\ns1 [=] s2 ->\nn = LocSet.cardinal s1 ->\nValidDGTree p bl ep f s1 tree ->\nValidDGTree p bl ep f s2 tree.\nProof.\nintros p bl ep.\ninduction n.\n intros.\n inversion H1.\n symmetry  in H0.\n apply LocSetProp.cardinal_Empty in H0.\n assert (f'list = []).\n  clear H4 H7 H6.\n  generalize f'list, H5.\n  clear f'list H5.\n  induction f'list'.\n   intros.\n   simpl in H5.\n   auto.\n   \n   intros.\n   simpl in H5.\n   assert (LocSet.mem a s1 = false).\n    unfold LocSet.Empty in H0.\n    specialize H0 with a.\n    apply LocSetPropEq.mem_3; trivial.\n    \n    rewrite H4 in H5.\n    intros.\n    apply IHf'list'.\n    trivial.\n    \n  rewrite H9 in H5.\n  rewrite H9 in H7.\n  apply ValidDGTree_def with dgs ad [] f'list'; trivial.\n   assert (LocSet.Empty s2).\n    unfold LocSet.Empty.\n    intros.\n    unfold LocSet.Empty in H0.\n    unfold LocSet.Equal in H.\n    intro.\n    apply H in H10.\n    elim H0 with a; trivial.\n    \n    clear H4 H5 H6 H7 H9.\n    induction f'list'.\n     simpl; trivial.\n     \n     assert (LocSet.mem a s2 = false).\n      apply LocSetPropEq.mem_3; trivial.\n      \n      simpl.\n      rewrite H4.\n      trivial.\n      \n   rewrite H6.\n   rewrite H9.\n   trivial.\n   \n   intros.\n   rewrite H6 in H10.\n   rewrite H9 in H10.\n   simpl in H10; inversion H10.\n   \n intros.\n inversion H1.\n apply ValidDGTree_def with dgs ad f'list f'list'; trivial.\n  generalize f'list, H5.\n  clear f'list H4 H5 H6 H7.\n  induction f'list'.\n   simpl.\n   trivial.\n   \n   simpl.\n   intros.\n   case_eq (LocSet.mem a s1); intros.\n    rewrite H4 in H5.\n    rewrite H in H4.\n    rewrite H4.\n    destruct f'list.\n     inversion H5.\n     \n     specialize IHf'list' with f'list.\n     rewrite IHf'list'.\n      inversion H5.\n      trivial.\n      \n      inversion H5; trivial.\n      \n    rewrite H4 in H5.\n    rewrite H in H4.\n    rewrite H4.\n    rewrite IHf'list' with f'list; trivial.\n    \n  intros.\n  specialize IHn with f' dgs' (LocSet.remove f' s1) (LocSet.remove f' s2).\n  case_eq (LocSet.mem f' s1); intros.\n   apply IHn.\n    apply LocSetProp.Equal_remove; trivial.\n    \n    apply eq_add_S.\n    rewrite H0.\n    symmetry .\n    apply LocSetPropEq.remove_cardinal_1; trivial.\n    \n    apply H7 with n0 f''; trivial.\n    \n   assert (LocSet.mem f' s1 = true).\n    generalize nth_In.\n    intros.\n    assert (In f' f'list).\n     rewrite <- H10.\n     apply H13.\n     rewrite <- H6.\n     trivial.\n     \n     rewrite <- H5 in H14.\n     clear H4.\n     generalize f'list, H5.\n     clear f'list H5 H10 H6 H7.\n     induction f'list'.\n      intros.\n      simpl in *.\n      inversion H14.\n      \n      intros.\n      simpl in H5.\n      case_eq (LocSet.mem a s1); intros.\n       rewrite H4 in H5.\n       simpl in H14.\n       rewrite H4 in H14.\n       case_eq (LocDec.eq_dec a f').\n        intros.\n        unfold LocDec.eq in e.\n        rewrite <- e.\n        trivial.\n        \n        intros.\n        simpl in H14.\n        destruct H14.\n         elim n1.\n         unfold LocDec.eq.\n         trivial.\n         \n         destruct f'list.\n          inversion H5.\n          \n          apply IHf'list' with f'list in H7; trivial.\n          inversion H5.\n          trivial.\n          \n       rewrite H4 in H5.\n       simpl in H14.\n       rewrite H4 in H14.\n       apply IHf'list' with f'list in H14; trivial.\n       \n    rewrite H12 in H13.\n    inversion H13.\nQed.\n\nParameter BuildDGTree: Program -> Backlinks.t -> (* excluded pivots *) LocSet.t -> (* field *) Location -> LocSet.t -> DGTree.\nAxiom BuildDGTree_def: forall p bl ep f tree m,\nValidDGTree p bl ep f m tree <-> BuildDGTree p bl ep f m  = tree.\n\nDefinition FieldInDg_rac3 (p : Program) (bl : Backlinks.t) \n      ((* excluded pivots *) ep : LocSet.t) (f : Location) \n      (dg : Location) : bool :=\n  InDGTree dg (BuildDGTree p bl ep f (LocSetAll \\ (LocSet.singleton f))).\n\n\nDefinition CorrectBacklink (p : Program) (st : State.t) (f dg pivot : Location) : Prop :=\ndirect_FieldInDg_dynamic p st@h f dg pivot\n<->\nexists ams,  LocDict.get (get_backlinks st@bl f) pivot = Some ams /\\ LocSet.In dg ams.\n\nDefinition CorrectBacklinks (p : Program) (st : State.t) : Prop :=\nforall f dg pivot , CorrectBacklink p st f dg pivot.\n\nLemma LocDict_get_some:\nforall bl f pivot ams,\nLocDict.get (get_backlinks bl f) pivot = Some ams ->\nexists ad, Backlinks.get bl f = Some ad.\nProof.\nintros.\nunfold get_backlinks in H.\ncase_eq (Backlinks.get bl f);intros.\nexists v;trivial.\nrewrite H0 in H.\nrewrite LocDict.get_empty in H.\ninversion H.\nQed.\n\nInductive EqualAssignables (a1 a2: list (LocSet.t * LocSet.t)) :=\nEqualAssignables_def:\nlength a1 = length a2 ->\n(forall n a,\n  fst (nth n  a1 a) [=] fst (nth n  a2 a) /\\\n  snd (nth n  a1 a) [=] snd (nth n  a2 a)) ->\nEqualAssignables a1 a2.\n\nInductive EqualFresh (f1 f2: stack ObjSet.t) :=\nEqualFresh_def:\nlength f1 = length f2 ->\n(forall n d,\n  (nth n  f1 d) [[=]] (nth n  f2 d)) ->\nEqualFresh f1 f2.\n\nInductive CorrespondingFrame : Rac2.Frame.t -> Frame.t -> Prop :=\n| CorrespondingFrame_def:\n  forall fr_rac2 fr_rac3,\n  fr_rac2@params         = fr_rac3@params ->\n  fr_rac2@vars           = fr_rac3@vars ->\n  fr_rac2@pc             = fr_rac3@pc ->\n  fr_rac2@ret            = fr_rac3@ret ->\n  fr_rac2@pre            = fr_rac3@pre ->\n  fr_rac2@quants         = fr_rac3@quants ->\n  EqualFresh fr_rac2@fresh fr_rac3@fresh ->\n  EqualAssignables fr_rac2@assignables fr_rac3@assignables -> \n  CorrespondingFrame fr_rac2 fr_rac3.\n\nInductive CorrespondingState (p : Program): Rac2.State.t -> State.t -> Prop :=\n| CorrespondingState_def:\n  forall st_rac2 st_rac3,\n  CorrespondingFrame st_rac2@fr%rac2 st_rac3@fr ->\n  st_rac2@h%rac2 = st_rac3@h ->\n  CorrectBacklinks p st_rac3 ->\n  CorrespondingState p st_rac2 st_rac3.\n\nLemma nil_length:\nforall A (l : list A),\n0 = length l -> l = nil.\nProof.\nintuition.\nunfold length in H.\ndestruct l;trivial.\ninversion H.\nQed.\n\nLemma FieldInDg_rac_EqualSets:\nforall p h s1 f dg,\nRac2.FieldInDg_rac p h s1 f dg ->\nforall s2,\ns1 [=] s2 ->\nRac2.FieldInDg_rac p h s2 f dg.\nProof.\nintros p h s1 f dg H.\ninduction H; intros.\n apply Rac2.FieldInDg_rac_step with dg'.\n  apply IHFieldInDg_rac1; trivial.\n  \n  apply IHFieldInDg_rac2; trivial.\n  \n apply Rac2.FieldInDg_rac_static; trivial.\n \n apply Rac2.FieldInDg_rac_dynamic with pivot; trivial.\n intro.\n elim H0.\n apply H1; trivial.\n \n apply Rac2.FieldInDg_rac_same; trivial.\nQed.\n\n(* field in rac as in second refinement, but terminating *)\nInductive FieldInDg_rac2 (p : Program) (h : Heap.t) (ep : LocSet.t) (s : LocSet.t): (* field *) Location -> (* dg *) Location -> Prop :=\n  | FieldInDg_rac2_static : forall f dg dg',\n    direct_FieldInDg_static p f dg' ->\n    ~ LocSet.In dg' s ->\n    FieldInDg_rac2 p h ep (LocSet.add dg' s) dg' dg ->\n    FieldInDg_rac2 p h ep s f dg\n  | FieldInDg_rac2_dynamic : forall f dg pivot dg',\n    direct_FieldInDg_dynamic p h f dg' pivot ->\n    ~ LocSet.In pivot ep ->\n    ~ LocSet.In dg' s ->\n    FieldInDg_rac2 p h ep (LocSet.add dg' s) dg' dg ->\n    FieldInDg_rac2 p h ep s f dg\n  | FieldInDg_rac2_base : forall f dg, \n    f = dg ->\n    FieldInDg_rac2 p h ep s f dg.\n\nLemma FieldInDg_rac2_Correct:\nforall p h ep1 ep2 f dg,\nep1 [=] ep2 ->\n(Rac2.FieldInDg_rac p h ep1 f dg \n<->\nFieldInDg_rac2 p h ep2 (LocSet.singleton f) f dg).\nAdmitted. (* Pen and paper proof *)\n\nLemma FieldInDg_rac2_EqualSet:\nforall p h ep s1 f dg,\nFieldInDg_rac2 p h ep s1 f dg -> \nforall s2, s1 [=] s2 ->\nFieldInDg_rac2 p h ep s2 f dg.\nProof.\nintros p h ep s1 f dg H.\ninduction H.\n intros.\n apply FieldInDg_rac2_static with dg'; trivial.\n  intro; elim H0.\n  apply H2.\n  trivial.\n  \n  apply IHFieldInDg_rac2.\n  auto with *.\n  \n intros.\n apply FieldInDg_rac2_dynamic with pivot dg'; trivial.\n  intro; elim H1.\n  apply H3.\n  trivial.\n  \n  apply IHFieldInDg_rac2.\n  auto with *.\n  \n intros.\n apply FieldInDg_rac2_base; trivial.\nQed.\n\nLemma LocSet_remove_diff_remove_add:\nforall x y e,\nLocSet.In e x ->\nx \\ (y \\ {e})  [=] LocSet.add e (x \\ y).\nProof.\nsplit; intros.\n case_eq (MP.FM.eq_dec e a); intros.\n  apply LocSet.add_1; trivial.\n  \n  apply LocSet.add_2.\n  apply LocSet.diff_3.\n   apply LocSet.diff_1 in H0; trivial.\n   \n   apply LocSet.diff_2 in H0.\n   intro; elim H0.\n   apply LocSet.remove_2; trivial.\n   \n case_eq (MP.FM.eq_dec e a); intros.\n  unfold LocDec.eq in e0; subst.\n  apply LocSet.diff_3; trivial.\n  apply LocSet.remove_1; trivial.\n  \n  apply LocSet.add_3 in H0; trivial.\n  apply LocSet.diff_3.\n   apply LocSet.diff_1 in H0; trivial.\n   \n   apply LocSet.diff_2 in H0.\n   intro; elim H0.\n   apply LocSet.remove_3 in H2; trivial.\nQed.\n\nLemma LocSet_diff_remove_diff_add:\nforall x y e,\n(x \\ y) \\ {e} [=] x \\ (LocSet.add e y).\nProof.\nsplit; intros.\n apply LocSet.diff_3.\n  apply LocSet.remove_3 in H.\n  apply LocSet.diff_1 in H.\n  trivial.\n  \n  intro.\n  apply LocSet.add_3 in H0.\n   apply LocSet.remove_3 in H.\n   apply LocSet.diff_2 in H.\n   elim H; trivial.\n   \n   intro.\n   unfold LocSet.E.eq in H1.\n   rewrite H1 in H.\n   apply LocSet.remove_1 in H.\n    elim H.\n    \n    trivial.\n    \n apply LocSet.remove_2.\n  intro.\n  unfold LocSet.E.eq in H0.\n  rewrite H0 in H.\n  apply LocSet.diff_2 in H.\n  elim H.\n  apply LocSet.add_1.\n  trivial.\n  \n  apply LocSet.diff_3.\n   apply LocSet.diff_1 in H.\n   trivial.\n   \n   apply LocSet.diff_2 in H.\n   intro; elim H.\n   apply LocSet.add_2.\n   trivial.\nQed.\n\nLemma FieldInDg_rac3_Correct:\nforall p ep st f dg ,\nCorrectBacklinks p st ->\n(FieldInDg_rac2 p st@h ep (LocSet.singleton f) f dg \n<->\nFieldInDg_rac3 p st@bl ep f dg = true).\nProof.\nsplit;intros.\n unfold FieldInDg_rac3 in *.\n apply InDGTree_Correct.\n induction H0.\n  elim\n   ValidDGTree_exists\n    with p st@bl ep (LocSetAll \\ s) f; \n   trivial.\n  intro tree.\n  intro.\n  replace (BuildDGTree p st@bl ep f (LocSetAll \\ s)) with tree .\n   destruct tree.\n   inversion H3.\n   assert (In dg' f'list').\n    rewrite <- H6.\n    apply in_or_app.\n    right.\n    apply StaticDGs_Correct; trivial.\n    \n    assert (In dg' f'list).\n     clear H6.\n     generalize f'list, H7, H11.\n     clear f'list H7 H11 H8 H9.\n     assert (LocSet.mem dg' (LocSetAll \\ s) = true).\n      rewrite LocSetPropEq.diff_mem.\n      apply andb_true_iff.\n      split.\n       apply LocSet.mem_1.\n       apply LocSetAll_def.\n       \n       apply negb_true_iff.\n       apply LocSetPropEq.mem_3; trivial.\n       \n      induction f'list'.\n       intros.\n       inversion H11.\n       \n       intros.\n       simpl in H11.\n       destruct H11.\n        subst.\n        simpl.\n        rewrite H6.\n        simpl; left; trivial.\n        \n        simpl in H7.\n        case_eq (LocSet.mem a (LocSetAll \\ s)); intros; rewrite H9 in H7.\n         destruct f'list.\n          inversion H7.\n          \n          specialize IHf'list' with f'list.\n          inversion H7.\n          rewrite H13.\n          apply IHf'list' in H13.\n           auto with *.\n           \n           trivial.\n           \n         apply IHf'list'.\n          trivial.\n          \n          trivial.\n     \n     apply in_nth with (d:=f) in H12.\n      destruct H12 as [n H12].\n      destruct H12.\n      inversion H4.\n      set (tree' := nth n dgs0 (DGNode f [])).\n      specialize H9 with n f dg' tree'.\n      case_eq (LocDec.eq_dec dg f); intros.\n       unfold LocDec.eq in e.\n       apply InDG_base with dgs0.\n       rewrite e; trivial.\n       \n       apply InDG_step with dgs0 f tree'; trivial.\n        unfold tree'.\n        apply nth_In.\n        rewrite H8; trivial.\n        \n        assert (BuildDGTree p st@bl ep dg' (LocSetAll \\ (LocSet.add dg' s)) = tree').\n         rewrite <- BuildDGTree_def.\n         apply\n          ValidDGTree_EqualSets\n           with\n             (n := LocSet.cardinal ((LocSetAll \\ s) \\ {dg'}))\n             (s1 := (LocSetAll \\ s) \\ {dg'}); trivial.\n             \n             apply LocSet_diff_remove_diff_add.\n             \n          apply H9; trivial.\n          rewrite H8; trivial.\n          \n         rewrite <- H17.\n         trivial.\n\n   symmetry .\n   apply BuildDGTree_def; trivial.\n\n  elim\n   ValidDGTree_exists\n    with p st@bl ep (LocSetAll \\ s) f; \n   trivial.\n  intro tree.\n  intro.\n  replace (BuildDGTree p st@bl ep f (LocSetAll \\ s)) with tree .\n  destruct tree.\n   inversion H4.\n   assert (In dg' f'list').\n    rewrite <- H7.\n    apply in_or_app.\n    left.\n    unfold CorrectBacklinks in H.\n    unfold CorrectBacklink in H.\n    unfold get_backlinks in H6.\n    rewrite H in H0.\n    destruct H0 as [amd H0].\n    destruct H0.\n    rewrite <- In_InA.\n    apply LocSet.elements_1.\n    apply fold_right_union.\n    elim LocDict_get_some with st@bl f pivot amd;trivial.\n    intros.\n    rewrite H13 in H6.\n    rewrite <- H6.\n    exists amd.\n    split;trivial.\n    apply LocDict.filter_1.\n    exists pivot.\n    unfold get_backlinks in H0.\n    rewrite H13 in H0.\n    tauto.\n\n    assert (In dg' f'list).\n     clear H7.\n     generalize f'list, H8, H12.\n     clear f'list H8 H12 H9 H10.\n     assert (LocSet.mem dg' (LocSetAll \\ s) = true).\n      rewrite LocSetPropEq.diff_mem.\n      apply andb_true_iff.\n      split.\n       apply LocSet.mem_1.\n       apply LocSetAll_def.\n       \n       apply negb_true_iff.\n       apply LocSetPropEq.mem_3; trivial.\n       \n      induction f'list'.\n       intros.\n       inversion H12.\n       \n       intros.\n       simpl in H12.\n       destruct H12.\n        subst.\n        simpl.\n        rewrite H7.\n        simpl; left; trivial.\n        \n        simpl in H8.\n        case_eq (LocSet.mem a (LocSetAll \\ s)); intros; rewrite H10 in H8.\n         destruct f'list.\n          inversion H8.\n          \n          specialize IHf'list' with f'list.\n          inversion H8.\n          rewrite H14.\n          apply IHf'list' in H14.\n           auto with *.\n           \n           trivial.\n           \n         apply IHf'list'.\n          trivial.\n          \n          trivial.\n          \n     apply in_nth with (d := f) in H13.\n      destruct H13 as [n H13].\n      destruct H13.\n      inversion H4.\n      set (tree' := nth n dgs0 (DGNode f [])).\n      specialize H10 with n f dg' tree'.\n      case_eq (LocDec.eq_dec dg f); intros.\n       unfold LocDec.eq in e.\n       apply InDG_base with dgs0.\n       rewrite e; trivial.\n       \n       apply InDG_step with dgs0 f tree'; trivial.\n        unfold tree'.\n        apply nth_In.\n        rewrite H9; trivial.\n        \n        assert (BuildDGTree p st@bl ep dg' (LocSetAll \\ (LocSet.add dg' s)) = tree').\n         rewrite <- BuildDGTree_def.\n         apply\n          ValidDGTree_EqualSets\n           with\n             (n := LocSet.cardinal ((LocSetAll \\ s) \\ {dg'}))\n             (s1 := (LocSetAll \\ s) \\ {dg'}); trivial.\n             \n             apply LocSet_diff_remove_diff_add.\n             \n          apply H10; trivial.\n          rewrite H9; trivial.\n          \n         rewrite <- H23.\n         trivial.\n      \n   symmetry .\n   apply BuildDGTree_def; trivial.\n\n  assert(exists tree, BuildDGTree p st@bl ep f (LocSetAll \\s) = tree).\n  exists (BuildDGTree p st@bl ep f (LocSetAll \\s)).\n  trivial.\n  destruct H1 as [tree H1].\n  apply BuildDGTree_def in H1.\n  replace (BuildDGTree p st@bl ep f (LocSetAll \\s)) with tree.\n  inversion H1.\n  apply InDG_base with dgs.\n  rewrite <- H0.\n  trivial.\n  symmetry.\n  apply BuildDGTree_def;trivial.\n\napply FieldInDg_rac2_EqualSet with (LocSetAll \\ (LocSetAll \\ (LocSet.singleton f))).\nunfold FieldInDg_rac3 in *.\napply InDGTree_Correct in H0.\nassert\n (exists tree, BuildDGTree p st@bl ep f (LocSetAll \\ LocSet.singleton f) = tree).\n exists (BuildDGTree p st@bl ep f (LocSetAll \\ LocSet.singleton f)).\n trivial.\n \n destruct H1 as (tree, H1).\n rewrite H1 in H0.\n apply BuildDGTree_def in H1.\n induction H1.\n destruct H0.\n  rewrite H0 in H1.\n  inversion H1.\n  apply FieldInDg_rac2_base.\n  trivial.\n  \n  rewrite H0 in H1.\n  inversion H1.\n  apply in_nth with (d := DGNode f []) in H9.\n  destruct H9 as (n, H9).\n  destruct H9.\n  set (f' := nth n f'list f).\n  assert (In f' f'list).\n   apply nth_In.\n   rewrite <- H5.\n   rewrite <- H13; trivial.\n   assert (LocSet.In f' m).\n    clear H3.\n    generalize f'list, H4, f', H14.\n    clear f'list H4 f' H14 H5 H6 H7.\n    induction f'list'.\n     intros.\n     simpl in H4.\n     rewrite <- H4 in H14.\n     inversion H14.\n     \n     intros.\n     simpl in H4.\n     case_eq (LocSet.mem a m); intros; rewrite H3 in H4.\n      destruct f'list.\n       inversion H4.\n       \n       simpl in H14.\n       destruct H14.\n        rewrite <- H5.\n        inversion H4.\n        rewrite <- H7.\n        apply LocSet.mem_2; trivial.\n        \n        apply IHf'list' with f'list.\n         inversion H4; trivial.\n         \n         trivial.\n         \n      apply IHf'list' with f'list; trivial.\n      \n    specialize H6 with n f f' tree'.\n    specialize H7 with n f f' tree'.\n    assert (In f' f'list').\n     rewrite <- H4 in H14.\n     rewrite filter_In in H14.\n     destruct H14; trivial.\n     \n     rewrite <- H3 in H16.\n     apply in_app_or in H16.\n     destruct H16.\n      unfold CorrectBacklinks in H.\n      unfold CorrectBacklink in H.\n      apply In_InA in H16.\n      apply LocSet.elements_2 in H16.\n      apply fold_right_union in H16.\n      destruct H16 as (ams, H16).\n      rewrite LocDict.filter_1 in H16.\n      destruct H16.\n      destruct H16 as (pivot, H16).\n      destruct H16.\n      apply FieldInDg_rac2_dynamic with pivot f'; trivial.\n       rewrite H.\n       exists ams.\n       split;trivial.\n         rewrite H2;trivial.\n\n       intro.\n       apply LocSet.diff_2 in H19.\n       elim H19;trivial.\n\n       apply FieldInDg_rac2_EqualSet with (LocSetAll \\ (m \\ {f'})).\n        rewrite <- H13 in H7.\n        apply H7; trivial.\n        \n        apply LocSet_remove_diff_remove_add.\n        apply LocSetAll_def.\n        \n      apply StaticDGs_Correct in H16.\n      apply FieldInDg_rac2_static with f'; trivial.\n       intro.\n       apply LocSet.diff_2 in H17.\n       elim H17; trivial.\n       \n       apply FieldInDg_rac2_EqualSet with (LocSetAll \\ (m \\ {f'})).\n        rewrite <- H13 in H7.\n        apply H7; trivial.\n        \n        apply LocSet_remove_diff_remove_add.\n        apply LocSetAll_def.\n\n  split; intros.\n   apply LocSet.diff_2 in H1.\n   assert (LocSet.In a LocSetAll).\n    apply LocSetAll_def.\n    \n    assert (~ LocSet.In a (LocSetAll \\ {f})).\n     intro; elim H1.\n     apply remove_diff_singleton; trivial.\n     \n     apply LocSet.singleton_2.\n     unfold LocSet.E.eq.\n     case_eq (MP.FM.eq_dec f a); intros.\n      auto.\n      \n      elim H3.\n      apply LocSet.remove_2.\n       trivial.\n       \n       trivial.\n       \n   apply LocSet.diff_3.\n    apply LocSetAll_def.\n    \n    intro.\n    apply LocSet.diff_2 in H2.\n    elim H2; trivial.\nQed.\n\n\nDefinition St3to2 (st: State.t) : Rac2.State.t :=\nRac2.State.build st@h st@fr Rac2.Adds.singleton.\n\n(** Postpone this ... *)\nDeclare Module AnnotationTable : ANNOTATION_TABLE State.\n\nModule Assignables <: ASSIGNABLES State.\t\n\n  Lemma NewFrame_Correct: forall p m param st_rac2 st_rac3 fr'_rac2 fr'_rac3,\n  CorrespondingState p st_rac2 st_rac3 ->\n  fr'_rac2 = Rac2.NewFrame m param st_rac2 ->\n  fr'_rac3 = NewFrame m param st_rac3 ->\n  CorrespondingState p st_rac2[fr:=fr'_rac2]%rac2 st_rac3[fr:=fr'_rac3].\n  Proof.\nintuition.\ndestruct H.\nsplit.\n rewrite H0.\n rewrite H1.\n unfold NewFrame.\n unfold Rac2.NewFrame.\n destruct H.\n split; trivial.\n  simpl.\n  rewrite H2.\n  trivial.\n  \n  simpl.\n  split.\n   destruct H9.\n   simpl.\n   rewrite e.\n   trivial.\n   \n   destruct H9.\n   simpl.\n   destruct n.\n    intros.\n    apply ObjSet.eq_refl.\n    \n    trivial.\n    \n  simpl.\n  split.\n   destruct H10.\n   simpl.\n   rewrite e.\n   trivial.\n   \n   destruct H10.\n   simpl.\n   destruct n.\n    intros.\n    split; simpl; apply LocSet.eq_refl.\n    \n    specialize a with (n := n).\n    trivial.\n    \n simpl; trivial.\n \n unfold CorrectBacklinks.\n intros.\n split; intros.\n  unfold CorrectBacklinks in H3.\n  simpl.\n  apply H3.\n  rewrite H1 in H4.\n  unfold NewFrame in H4.\n  simpl in H4; trivial.\n  \n  unfold CorrectBacklinks in H3.\n  simpl in H4.\n  apply H3 in H4.\n  rewrite H1.\n  unfold NewFrame.\n  simpl.\n  trivial.\nQed.\n\n  Definition Assignable (p : Program) (bl : Backlinks.t) (f : Location) (a : LocSet.t * LocSet.t) : bool :=\n      LocSet.fold\n         (fun dg b => (FieldInDg_rac3 p bl (fst a) f dg) || b)\n         (snd a)\n         false.\n\n  Definition FieldUpdateCheck (p : Program) (loc : Location) (st : State.t): Prop :=\n  forall n,\n  (n < length st@fr@assignables)%nat ->\n       (exists m, \n        (m <= n /\\ m < length st@fr@fresh)%nat /\\ LocSet.In loc (ObjSet2LocSet (nth m st@fr@fresh ObjSet.empty)))\n    \\/\n        Assignable p st@bl loc (nth n st@fr@assignables (LocSet.empty,LocSet.empty)) = true.\n\n  Lemma FieldUpdateCheck_Correct:\n    forall am p st_rac2 st_rac3,\n    CorrespondingState p st_rac2 st_rac3 ->\n    ( Rac2.Assignables.FieldUpdateCheck p am st_rac2 <-> FieldUpdateCheck p am st_rac3).\nProof.\nintros.\ndestruct H.\nrename H1 into Hcorr.\ninversion H.\nclear H H1 H2 H3 H4 H5 H6.\nsubst.\nrename H8 into H6.\nrename H7 into H5.\nrename H0 into H7.\nunfold FieldUpdateCheck.\nunfold Rac2.Assignables.FieldUpdateCheck.\nintuition.\n  destruct (H n).  \n  inversion H6.\n  rewrite H1.\n  trivial.\n  left.\n  destruct H1 as (m0, H1).\n  destruct H1.\n \n   exists m0.\n   split.\n   inversion H5.\n   rewrite <- H3.\n   trivial.\n   rewrite ObjSet2LocSet_def in H2 |- * .\n   unfold LocInObjSet in H2 |- *.\n   destruct am; trivial.\n   inversion H5.\n   unfold ObjSet.Equal in H4.\n   apply ObjSet.mem_1.\n   apply ObjSet.mem_2 in H2.\n   apply H4.\n   trivial.\n   inversion H5.\n   unfold ObjSet.Equal in H4.\n   apply ObjSet.mem_1.\n   apply ObjSet.mem_2 in H2.\n   apply H4.\n   trivial.\n\n  right.\n  unfold Assignable.\n  apply LocSet_fold_orb.\n  destruct H1.\n  destruct H1.\n  inversion H6.  \n  specialize H4 with n (LocSet.empty, LocSet.empty).\n  unfold LocSet.Equal in H4.\n  destruct H4.  \n  exists x.\n  split; [apply H8; trivial|].\n  rewrite <- FieldInDg_rac3_Correct; trivial.\n  rewrite <- FieldInDg_rac2_Correct with (ep1 := fst (nth n st_rac2 @fr%rac2 @assignables (LocSet.empty, LocSet.empty) )); trivial.\n  rewrite <- H7;trivial.\n    \n destruct H with n.\n\n  inversion H6.\n  rewrite <- H1.\n  trivial.\n  \n  left.\n  destruct H1 as (m0, H1).\n  destruct H1.\n \n   exists m0.\n   split.\n   inversion H5.\n   rewrite H3.\n   trivial.\n   rewrite ObjSet2LocSet_def in H2 |- * .\n   unfold LocInObjSet in H2 |- *.\n   destruct am; trivial.\n   inversion H5.\n   unfold ObjSet.Equal in H4.\n   apply ObjSet.mem_1.\n   apply ObjSet.mem_2 in H2.\n   rewrite H4.\n   trivial.\n   inversion H5.\n   unfold ObjSet.Equal in H4.\n   apply ObjSet.mem_1.\n   apply ObjSet.mem_2 in H2.\n   rewrite H4.\n   trivial.\n\n  right.\n  unfold Assignable in H1.\n  apply LocSet_fold_orb in H1.\n\n  inversion H6.\n  specialize H3 with n (LocSet.empty, LocSet.empty).\n  unfold LocSet.Equal in H3.\n  destruct H3.\n  destruct H1.\n  exists x.\n  destruct H1.\n  split; [apply H4; trivial|].\n  rewrite  FieldInDg_rac2_Correct with (ep2 := fst (nth n st_rac3 @fr@assignables (LocSet.empty, LocSet.empty) )); trivial.\n  rewrite H7;trivial.    \n  rewrite  FieldInDg_rac3_Correct; trivial.\nQed.\n\n  Definition AssignablePivotTargets ( p : Program) (bl : Backlinks.t) (pivot : Location) (a : LocSet.t * LocSet.t) : LocSet.t :=\n    list2LocSet (\n      filter\n        (fun f => \n\t   match LocDict.get (get_backlinks bl f) pivot with\n\t   | Some dgs => if LocSet.fold (fun dg b => (Assignable p bl dg a) || b) dgs false  then true else false\n\t   | None => false\n           end)\n        (Backlinks.keys bl)).\n\n  Lemma AssignablePivotTargets_Correct:\n    forall p  st  a1 a2 pivot,\n    CorrectBacklinks p st ->\n    (fst a1) [=] (fst a2) ->\n    (snd a1) [=] (snd a2) ->\n    Rac2.AssignablePivotTargets p st@h pivot a1   [=]\n    AssignablePivotTargets p st@bl pivot a2.\n  Proof.\nintros.\nunfold CorrectBacklinks in H.\nsplit; intros.\n destruct a1.\n destruct a2.\n simpl in *.\n rewrite Rac2.AssignablePivotTargets_def in H2.\n destruct H2 as (dg', H2).\n destruct H2.\n destruct H3 as (dg, H3).\n destruct H3.\n unfold AssignablePivotTargets.\n apply list2LocSet_1.\n apply filter_In.\n apply H in H2.\n destruct H2 as (dgs, H2).\n destruct H2.\n split.\n  apply Backlinks.keys_1.\n  intro.\n  apply LocDict_get_some in H2.\n  destruct H2.\n  rewrite H2 in H6.\n  inversion H6.\n  \n  rewrite H2.\n  case_eq\n   (LocSet.fold\n      (fun (elem : LocSet.elt) (b : bool) =>\n       Assignable p st @bl elem (t1, t2) || b) dgs false); \n   intro.\n   trivial.\n   \n   rewrite <- not_true_iff_false in H6.\n   rewrite LocSet_fold_orb in H6.\n   elim H6.\n   clear H6.\n   exists dg'.\n   split; trivial.\n   unfold Assignable.\n   simpl.\n   rewrite LocSet_fold_orb.\n   exists dg.\n   split; trivial.\n    rewrite <- H1; trivial.\n    \n    rewrite <- FieldInDg_rac3_Correct.\n     rewrite <- FieldInDg_rac2_Correct with (ep1 := t); trivial.\n     \n     auto with *.\n     \n destruct a1.\n destruct a2.\n simpl in *.\n rewrite Rac2.AssignablePivotTargets_def.\n unfold AssignablePivotTargets in H2.\n apply list2LocSet_1 in H2.\n apply filter_In in H2.\n destruct H2 as (H', H2).\n case_eq (LocDict.get (get_backlinks st @bl a) pivot); intros.\n  rewrite H3 in H2.\n  case_eq\n   (LocSet.fold\n      (fun (dg : LocSet.elt) (b : bool) =>\n       Assignable p st @bl dg (t1, t2) || b) v false); \n   intros.\n   apply LocSet_fold_orb in H4.\n   destruct H4.\n   destruct H4.\n   exists x.\n   split.\n    apply H.\n    exists v.\n    auto.\n    \n    unfold Assignable in H5.\n    apply LocSet_fold_orb in H5.\n    simpl in H5.\n    destruct H5 as (dg, H5).\n    exists dg.\n    rewrite H1.\n    rewrite FieldInDg_rac2_Correct with (ep2 := t1); trivial.\n    rewrite FieldInDg_rac3_Correct; trivial.\n    destruct H5.\n    auto.\n    \n   rewrite H4 in H2.\n   inversion H2.\n   \n  rewrite H3 in H2.\n  inversion H2.\nQed.\n\n  Definition SavePreState (p : Program) \n                          (bl : Backlinks.t) \n                          (pivot : Location)\n                          (assignable: LocSet.t * LocSet.t) : (LocSet.t * LocSet.t) :=\n  if LocSet.mem pivot (fst assignable) then\n    assignable\n  else\n    let fields := AssignablePivotTargets p bl pivot assignable in\n    (LocSet.add pivot (fst assignable), LocSet.union fields (snd assignable)).\n\n  Lemma SavePreState_same:\n  forall p st pivot a3 a2,\n  CorrectBacklinks p st ->\n  (fst a2) [=] (fst a3) ->\n  (snd a2) [=] (snd a3) ->\n  (fst (Rac2.SavePreState p st@h pivot a2) [=] fst (SavePreState p st@bl pivot a3) /\\\n  snd (Rac2.SavePreState p st@h pivot a2) [=] snd (SavePreState p st@bl pivot a3)).\n  Proof.\nintros.\nunfold SavePreState.\nunfold Rac2.SavePreState.\ncase_eq (LocSet.mem pivot (fst a2 )); case_eq (LocSet.mem pivot (fst a3 )); intros;\n try rewrite <- not_true_iff_false in H2;\n try rewrite <- not_true_iff_false in H3; try apply LocSet.mem_2 in H2;\n try apply LocSet.mem_2 in H3.\n tauto.\n \n elim H2.\n apply LocSet.mem_1.\n rewrite <- H0.\n trivial.\n \n elim H3.\n apply LocSet.mem_1.\n rewrite H0.\n trivial.\n \n split; split; simpl.\n  intros.\n  apply add_iff in H4.\n  destruct H4.\n   apply LocSet.add_1.\n   trivial.\n   \n   apply LocSet.add_2.\n   rewrite <- H0; trivial.\n   \n  intros.\n  apply add_iff in H4.\n  destruct H4.\n   apply LocSet.add_1.\n   trivial.\n   \n   apply LocSet.add_2.\n   rewrite H0; trivial.\n   \n  intros.\n  rewrite <- AssignablePivotTargets_Correct with (a1 := a2); auto with *.\n  apply LocSet.union_1 in H4.\n  destruct H4.\n   apply LocSet.union_2; trivial.\n   \n   apply LocSet.union_3.\n   rewrite <- H1; trivial.\n   \n  intros.\n  rewrite AssignablePivotTargets_Correct with (a2 := a3); auto with *.\n  apply LocSet.union_1 in H4.\n  destruct H4.\n   apply LocSet.union_2; trivial.\n   \n   apply LocSet.union_3.\n   rewrite H1; trivial.\nQed.\n\n  (* Don't bother for now, just assume that this function yields the same assignable locations than in the semantics.*)\n  Parameter EvalAssignableClause : Program -> Class -> Method -> State.t -> LocSet.t.\n  Parameter EvalAssignableClause_def : \n    forall p c m st_rac2 st_rac3,\n    CorrespondingState p st_rac2 st_rac3 ->\n    (EvalAssignableClause p c m st_rac3 [=] Rac2.Assignables.EvalAssignableClause p c m st_rac2).\n\n  Definition MethodCallAction (p : Program) (c : Class) (m : Method) (st : State.t) : State.t :=\n  let ams := EvalAssignableClause p c m st in\n  st[fr:=st@fr[assignables :+ (LocSet.empty, ams)]].\n\n  Lemma MethodCallAction_Correct:\n    forall p c m st_rac2 st_rac2' st_rac3 st_rac3',\n    CorrespondingState p st_rac2 st_rac3 ->\n    Rac2.Assignables.MethodCallAction p c m st_rac2 = st_rac2' ->\n    MethodCallAction p c m st_rac3 = st_rac3' ->\n    CorrespondingState p st_rac2' st_rac3'.\nProof.\nintuition.\ninversion H.\nsubst.\nunfold MethodCallAction.\nunfold Rac2.Assignables.MethodCallAction.\nsplit; simpl.\n destruct H2.\n split; simpl; trivial.\n split.\n  destruct H9.\n  unfold replace_top.\n  destruct fr_rac2@assignables; destruct fr_rac3@assignables;trivial.\n  \n  destruct H9.\n  intros.\n  unfold replace_top.\n  destruct fr_rac2@assignables; destruct fr_rac3@assignables;trivial.\n  inversion e.\n  inversion e.\n  destruct n.\n  simpl.\n  split.\n  apply LocSet.eq_refl.\n  rewrite EvalAssignableClause_def with (st_rac2 := st_rac2);trivial.\n  apply LocSet.eq_refl.\n    simpl.\n    specialize a with (S n) a0.\n    simpl in a.\n    trivial.\n    \n trivial.\n \n unfold CorrectBacklinks.\n simpl.\n trivial.\nQed.\n\n(** Add all fields of a newly created object to the list of fresh locations, as well\nto the assignable list *)\n\n  Definition NewObjectAction (p : Program) (obj : Object) (st : State.t) : State.t :=\n    st[fr:=st@fr[fresh :+ obj]].\n\n\n  Lemma NewObjectAction_Correct:\n    forall p l st_rac2 st_rac2' st_rac3 st_rac3',\n    CorrespondingState p st_rac2 st_rac3 ->\n    NewObjectAction p l st_rac3 = st_rac3' ->\n    Rac2.Assignables.NewObjectAction p l st_rac2 = st_rac2' ->\n    CorrespondingState p st_rac2' st_rac3'.\n  Proof.\nintuition.\nsubst.\ninversion H.\nsplit; trivial.\nsubst.\nsimpl in *.\ndestruct H0.\nsplit; simpl; trivial.\nsubst.\nunfold apply_top.\ndestruct H8.\ndestruct fr_rac2 @fresh; destruct fr_rac3 @fresh.\n split.\n  trivial.\n  \n  trivial.\n  \n inversion e.\n \n inversion e.\n \n split; simpl.\n  trivial.\n  \n  intros.\n  destruct n.\n   specialize e0 with 0 d.\n   simpl in e0.\n   unfold ObjSet.Equal in * |- *.\nsplit;intros.\ncase_eq(ObjDec.eq_dec l a);intros.\napply ObjSet.add_1;trivial.\napply ObjSet.add_2;trivial.\napply ObjSet.add_3 in H8;trivial.\nrewrite <- e0;trivial.\ncase_eq(ObjDec.eq_dec l a);intros.\napply ObjSet.add_1;trivial.\napply ObjSet.add_2;trivial.\napply ObjSet.add_3 in H8;trivial.\nrewrite e0;trivial.\n   \n   specialize e0 with (S n) d.\n   simpl in e0.\n   trivial.\nQed.\n\n(** Upon method return, add all freshly created locations to the list of fresh locations from the caller *)\n\n  Definition MethodReturnAction (p : Program) (st_c : State.t) (st : State.t) : State.t :=\n    st_c[fr:=st@fr[fresh :\\/ (peekd st_c@fr@fresh ObjSet.empty)][assignables := pop st_c@fr@assignables]].\n    \n\n  Lemma MethodReturnAction_Correct:\n    forall p st_rac2 st_rac2_c st_rac2_c' st_rac3 st_rac3_c st_rac3_c',\n    CorrespondingState p st_rac2_c st_rac3_c ->\n    CorrespondingState p st_rac2 st_rac3 ->\n    Rac2.Assignables.MethodReturnAction p st_rac2_c st_rac2 = st_rac2_c' ->\n    MethodReturnAction p st_rac3_c st_rac3 = st_rac3_c' ->\n    CorrespondingState p st_rac2_c' st_rac3_c'.\n  Proof.\nintuition.\nsubst.\nunfold MethodReturnAction.\nunfold Rac2.Assignables.MethodReturnAction.\ninversion H.\ninversion H1.\ninversion H0.\ninversion H16.\nsplit; trivial.\nsplit; simpl; trivial.\n\n  unfold apply_top.\n  destruct H27.\n  destruct st_rac2 @fr%rac2 @fresh ; destruct  st_rac3 @fr @fresh;trivial.\n      split;simpl;trivial.\n    inversion e.\ninversion e.\n    split;simpl.\n    trivial.\n    intros.\n    destruct n.\nspecialize e0 with O d.\nsimpl in e0.\n destruct H12.\n unfold peekd.\n destruct st_rac2_c @fr@fresh%rac2; destruct  st_rac3_c @fr @fresh ; simpl;trivial.\n apply UnionEqual.\n apply ObjSet.eq_refl.\n trivial.\n inversion e1.\ninversion e1.\nspecialize e2 with O d.\nsimpl in e2.\napply  UnionEqual;trivial.\nspecialize e0 with (S n) d.\nsimpl in e0.\ntrivial.\n destruct H13.\n split.\n  unfold pop.\n  destruct st_rac2_c @fr%rac2 @assignables;\n   destruct st_rac3_c @fr @assignables; trivial.\n   inversion e.\n   \n   inversion e.\n   \n   simpl in e.\n   auto.\n   \n  intros.\n  unfold pop.\n  destruct st_rac2_c @fr%rac2 @assignables;\n   destruct st_rac3_c @fr @assignables; trivial.\n   inversion e.\n   \n   inversion e.\n   \n   specialize a with (S n) a0.\n   simpl in a.\n   trivial.\nQed.\n\nDefinition RemoveBacklinks (p : Program) (pivot : Location) (st : State.t) : Backlinks.t :=\n  match Heap.get st@h pivot with\n  | Some (Ref obj) => \n    fold_right (fun f bl => remove_backlink bl (Heap.InstanceField obj f) pivot) st@bl (PivotTargets p pivot)\n  | _ => st@bl\n  end.\n\nDefinition SetBacklinks (p : Program) (pivot : Location) (v : Value) (bl : Backlinks.t) : Backlinks.t :=\nmatch v with\n| Ref obj => \n    fold_right (fun f bl' => set_backlink bl' (Heap.InstanceField obj f) pivot (list2LocSet (DynamicDGs p f pivot))) bl (PivotTargets p pivot)\n| _ => bl\nend.\n\nLemma get_remove_old_f_uncompat:\nforall f p pivot st, \n(forall f_obj f_fsig , f <> Heap.InstanceField f_obj f_fsig) ->\nget_backlinks st@bl f = get_backlinks (RemoveBacklinks p pivot st) f.\nProof.\nintros.\ndestruct f.\n unfold RemoveBacklinks.\n destruct (Heap.get st @h pivot); trivial.\n destruct v; trivial.\n induction (PivotTargets p pivot); trivial.\n simpl.\n unfold remove_backlink at 1.\n destruct Backlinks.get.\n  simpl.\n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n  \n  trivial.\n  \n elim H with o f.\n trivial.\n \n unfold RemoveBacklinks.\n destruct (Heap.get st @h pivot); trivial.\n destruct v; trivial.\n induction (PivotTargets p pivot); trivial.\n simpl.\n unfold remove_backlink at 1.\n destruct Backlinks.get.\n  simpl.\n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n  \n  trivial.\nQed.\n\nLemma get_set_old_f_uncompat:\nforall f p pivot bl v, \n(forall f_obj f_fsig , f <> Heap.InstanceField f_obj f_fsig) ->\nget_backlinks bl f = get_backlinks (SetBacklinks p pivot v bl) f.\nProof.\nintros.\ndestruct f.\n unfold SetBacklinks.\n destruct v; trivial.\n induction (PivotTargets p pivot); trivial.\n simpl.\n unfold set_backlink at 1.\n destruct Backlinks.get.\n  simpl.\n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n  \n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n  \n elim H with o f.\n trivial.\n \n unfold SetBacklinks.\n destruct v; trivial.\n induction (PivotTargets p pivot); trivial.\n simpl.\n unfold set_backlink at 1.\n destruct Backlinks.get.\n  simpl.\n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n  \n  unfold get_backlinks.\n  rewrite Backlinks.get_update_old; trivial.\n  intuition.\n  inversion H0; trivial.\n Qed.\n\n\nLemma get_remove_old:\nforall p loc pivot st x f,\npivot <> loc ->\n(LocDict.get (get_backlinks st@bl f) pivot = Some x <->\nLocDict.get (get_backlinks  (RemoveBacklinks p loc st) f) pivot = Some x).\nProof.\nsplit;intros.\nunfold RemoveBacklinks.\ncase_eq (Heap.get st @h loc); intros; trivial.\ndestruct v; trivial.\ninduction (PivotTargets p loc).\n simpl; trivial.\n \n simpl.\n unfold remove_backlink at 1.\n case_eq\n  (Backlinks.get\n     (fold_right\n        (fun (f0 : FieldSignature) (bl : Backlinks.t) =>\n         remove_backlink bl (Heap.InstanceField o f0) loc) \n        st @bl l) (Heap.InstanceField o a)); intros.\n  simpl.\n  unfold get_backlinks.\n  case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n   rewrite <- e.\n   rewrite Backlinks.get_update_same.\n   unfold get_backlinks in IHl.\n   rewrite e in H2.\n   rewrite H2 in IHl.\n   rewrite LocDict.get_remove_old; auto.\n   \n   rewrite Backlinks.get_update_old; trivial.\n   \n  case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n   rewrite e in H2.\n   unfold get_backlinks in IHl.\n   rewrite H2 in IHl.\n   rewrite LocDict.get_empty in IHl.\n   inversion IHl.\n   \n   trivial.\n\nunfold RemoveBacklinks in H0.\ncase_eq (Heap.get st @h loc); intros; trivial.\nrewrite H1 in H0.\ndestruct v; trivial.\ninduction (PivotTargets p loc).\n simpl; trivial.\n \n simpl in H0.\n unfold remove_backlink at 1 in H0.\n case_eq\n  (Backlinks.get\n     (fold_right\n        (fun (f0 : FieldSignature) (bl : Backlinks.t) =>\n         remove_backlink bl (Heap.InstanceField o f0) loc) \n        st @bl l) (Heap.InstanceField o a)); intros.\n  rewrite H2 in H0.\n  simpl in * |- *.\n  unfold get_backlinks in H0.\n  case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n   rewrite <- e in H0.\n   rewrite Backlinks.get_update_same in H0.\n   unfold get_backlinks in IHl.\n   rewrite e in H2.\n   rewrite H2 in IHl.\n   rewrite LocDict.get_remove_old in H0; auto.\n   \n   rewrite Backlinks.get_update_old in H0; trivial.\n   \n   apply IHl.\n   trivial.\n   apply IHl.\n   rewrite H2 in H0.\n   trivial.\n   rewrite H1 in H0.\n   trivial.\nQed.\n\nLemma get_set_old:\nforall p loc pivot bl x f v,\npivot <> loc ->\n(LocDict.get (get_backlinks bl f) pivot = Some x <->\nLocDict.get (get_backlinks  (SetBacklinks p loc v bl) f)\n  pivot = Some x).\nProof.\nsplit; intros.\n unfold SetBacklinks.\n destruct v; trivial.\n induction (PivotTargets p loc).\n  simpl; trivial.\n  \n  simpl.\n  unfold set_backlink at 1.\n  case_eq\n   (Backlinks.get\n      (fold_right\n         (fun (f0 : FieldSignature) (bl' : Backlinks.t) =>\n          set_backlink bl' (Heap.InstanceField o f0) loc\n            (list2LocSet (DynamicDGs p f0 loc))) bl l) \n      (Heap.InstanceField o a)); intros.\n   simpl.\n   unfold get_backlinks.\n   case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n    rewrite <- e.\n    rewrite Backlinks.get_update_same.\n    unfold get_backlinks in IHl.\n    rewrite e in H1.\n    rewrite H1 in IHl.\n    rewrite LocDict.get_update_old; auto.\n    \n    rewrite Backlinks.get_update_old; trivial.\n    \n   case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n    rewrite e in H1.\n    unfold get_backlinks in IHl.\n    rewrite H1 in IHl.\n    rewrite LocDict.get_empty in IHl.\n    inversion IHl.\n    \n    unfold LocDict.singleton.\n    unfold get_backlinks.\n    rewrite Backlinks.get_update_old; trivial.\n    \n unfold SetBacklinks in H0.\n destruct v; trivial.\n induction (PivotTargets p loc).\n  simpl; trivial.\n  \n  simpl in H0.\n  unfold set_backlink at 1 in H0.\n  case_eq\n   (Backlinks.get\n      (fold_right\n         (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n          set_backlink bl' (Heap.InstanceField o f) loc\n            (list2LocSet (DynamicDGs p f loc))) bl l) \n      (Heap.InstanceField o a)); intros.\n   rewrite H1 in H0.\n   simpl in H0.\n   unfold get_backlinks in H0.\n   case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n    rewrite <- e in H0.\n    rewrite Backlinks.get_update_same in H0.\n    unfold get_backlinks in IHl.\n    rewrite e in H1.\n    rewrite H1 in IHl.\n    rewrite LocDict.get_update_old in H0; auto.\n    \n    rewrite Backlinks.get_update_old in H0; trivial.\n    apply IHl.\n    trivial.\n    \n   rewrite H1 in H0.\n   unfold get_backlinks in H0.\n   case_eq (eq_dec (Heap.InstanceField o a) f); intros.\n    rewrite e in H0.\n    rewrite Backlinks.get_update_same in H0.\n    unfold LocDict.singleton in H0.\n    rewrite LocDict.get_update_old in H0.\n     rewrite LocDict.get_empty in H0.\n     inversion H0.\n     \n     auto.\n     \n    rewrite Backlinks.get_update_old in H0.\n     apply IHl.\n     trivial.\n     \n     trivial.\nQed.\n\nLemma get_remove_none:\nforall p st obj f pivot dg,\nCorrectBacklink p st (Heap.InstanceField obj f) dg pivot ->\nPivotField p pivot ->\n   ~ (exists locs,  LocDict.get\n       (get_backlinks (RemoveBacklinks p pivot st) (Heap.InstanceField obj f))\n       pivot = Some locs /\\ (LocSet.In dg locs)).\nProof.\nunfold CorrectBacklink.\nintros.\nunfold RemoveBacklinks.\ncase_eq (Heap.get st@h pivot);intros.\ndestruct v.\nintro.\nrewrite <- H in H2.\ninversion H2.\nrewrite H6 in H1.\ninversion H1.\nintro.\nrewrite <- H in H2.\ninversion H2.\nrewrite H6 in H1.\ninversion H1.\ncase_eq (ObjDec.eq_dec o obj).\n intros.\n rewrite e.\n rewrite e in H1.\n clear o e H2.\n elim\n  classic\n   with\n     (exists dg,\n      direct_FieldInDg_dynamic p st @h (Heap.InstanceField obj f) dg pivot).\n  intros.\n  generalize H2; intro.\n  rewrite <- PivotTargets_Correct in H3; trivial.\n  induction (PivotTargets p pivot).\n   inversion H3.\n   \n   simpl in H3.\n   destruct H3.\n    clear IHl.\n    rewrite H3.\n    clear a H3.\n    simpl.\n    unfold get_backlinks.\n    unfold remove_backlink at 1.\n    case_eq\n     (Backlinks.get\n        (fold_right\n           (fun (f0 : FieldSignature) (bl : Backlinks.t) =>\n            remove_backlink bl (Heap.InstanceField obj f0) pivot) \n           st @bl l) (Heap.InstanceField obj f)).\n     intros.\n     simpl.\n     rewrite Backlinks.get_update_same.\n     rewrite LocDict.get_remove_none.\n     intro.\n     destruct H4.\n     destruct H4.\n     inversion H4.\n     \n     intros.\n     rewrite H3.\n     intro.\n     rewrite LocDict.get_empty in H4.\n     destruct H4.\n     destruct H4.\n     inversion H4.\n     \n    simpl.\n    case_eq (FsigDec.eq_dec a f).\n     intros.\n     rewrite e.\n     unfold get_backlinks.\n     unfold remove_backlink at 1.\n     case_eq\n      (Backlinks.get\n         (fold_right\n            (fun (f0 : FieldSignature) (bl : Backlinks.t) =>\n             remove_backlink bl (Heap.InstanceField obj f0) pivot) \n            st @bl l) (Heap.InstanceField obj f)).\n      simpl.\n      intros.\n      rewrite Backlinks.get_update_same.\n      rewrite LocDict.get_remove_none.\n      intro.\n      destruct H6.\n      destruct H6.\n      inversion H6.\n      \n      intro.\n      rewrite H5.\n      intro.\n      rewrite LocDict.get_empty in H6.\n      destruct H6.\n      destruct H6.\n      inversion H6.\n      \n     intros.\n     unfold get_backlinks.\n     unfold remove_backlink at 1.\n     case_eq\n      (Backlinks.get\n         (fold_right\n            (fun (f0 : FieldSignature) (bl : Backlinks.t) =>\n             remove_backlink bl (Heap.InstanceField obj f0) pivot) \n            st @bl l) (Heap.InstanceField obj a)).\n      intros.\n      simpl.\n      rewrite Backlinks.get_update_old.\n       apply IHl.\n       trivial.\n       \n       intro.\n       elim n.\n       inversion H6; trivial.\n       \n      intro.\n      apply IHl.\n      trivial.\n      \n  intros.\n  intro.\n  elim H2.\n  exists dg.\n  apply H.\n  rewrite <- PivotTargets_Correct in H2.\n   induction (PivotTargets p pivot).\n    simpl.\n    intros.\n    destruct H3 as [ams H3].\n    exists ams.\n    trivial.\n    \n    intros.\n    simpl in H3.\n    unfold remove_backlink at 1 in H3.\n    case_eq\n     (Backlinks.get\n        (fold_right\n           (fun (f : FieldSignature) (bl : Backlinks.t) =>\n            remove_backlink bl (Heap.InstanceField obj f) pivot) \n           st @bl l) (Heap.InstanceField obj a)); intros; \n     rewrite H4 in H3.\n     simpl in H3.\n     simpl in H2.\n     assert (a <> f).\n      intro.\n      elim H2.\n      left; trivial.\n      \n      unfold get_backlinks in H3.\n      rewrite Backlinks.get_update_old in H3.\n       apply IHl.\n        intro.\n        elim H2.\n        right.\n        trivial.\n        \n        trivial.\n        \n       intro.\n       elim H5.\n       inversion H6.\n       trivial.\n       \n     apply IHl.\n      intro.\n      elim H2.\n      right; trivial.\n      \n      trivial.\n      \n   trivial.\n   \n intros.\n assert (~ direct_FieldInDg_dynamic p st @h (Heap.InstanceField obj f) dg pivot).\n  intro.\n  inversion H3.\n  inversion H5.\n  rewrite H7 in H1.\n  inversion H1.\n  rewrite <- H18 in H20.\n  elim n.\n  symmetry.\n  trivial.\n  \n  rewrite H in H3.\n  intro.\n  elim H3.\n  induction (PivotTargets p pivot).\n   simpl in H4.\n   trivial.\n   \n   apply IHl.\n   clear IHl.\n   simpl in H4.\n   unfold remove_backlink at 1 in H4.\n   case_eq\n    (Backlinks.get\n       (fold_right\n          (fun (f : FieldSignature) (bl : Backlinks.t) =>\n           remove_backlink bl (Heap.InstanceField o f) pivot) \n          st @bl l) (Heap.InstanceField o a)); intros; \n    rewrite H5 in H4.\n    simpl.\n    unfold get_backlinks in H4.\n    rewrite Backlinks.get_update_old in H4.\n     trivial.\n     \n     intro.\n     elim n.\n     inversion H6; trivial.\n     \n    trivial.\n    intro.\nrewrite <- H in H2.\ninversion H2.\nrewrite H6 in H1.\ninversion H1.\nintro.\nrewrite <- H in H2.\ninversion H2.\nrewrite H6 in H1.\ninversion H1.\nQed.\n\n\nLemma SetRemoveBacklinks_Correct:\nforall p loc st st' f dg pivot v cn um loc_obj loc_fsig,\nPivotField p loc ->\nloc = Heap.InstanceField loc_obj loc_fsig ->\nHeap.typeof st@h loc_obj = Some (Heap.ObjectObject cn um) ->\ndefined_field p cn loc_fsig ->\nassign_compatible p st@h v (FIELDSIGNATURE.type (snd loc_fsig)) ->\nst' = st[h := (Heap.update st@h loc v)]\n              [bl := (SetBacklinks p loc v (RemoveBacklinks p loc st))] ->\nCorrectBacklink p st f dg pivot ->\nCorrectBacklink p st' f dg pivot.\nProof.\nunfold CorrectBacklink.\nintros.\nrewrite H4.\nsimpl.\nclear H4.\nrename H5 into H4.\nsplit; intros.\n inversion H5.\n case_eq (LocSet.E.eq_dec pivot_loc loc); intros.\n  intros.\n  rewrite e in H18.\n  rewrite H18 in H5.\n  rewrite H18 in H9.\n  set (h' := Heap.update (State.h st) pivot v).\n  assert (Heap.Compat (State.h st) pivot).\n   rewrite H18 in H0.\n   rewrite H0.\n   apply Heap.CompatObject with cn um; trivial.\n   \n   generalize H9; intros.\n   rewrite Heap.get_update_same in H21; trivial.\n   inversion H21.\n   fold h' in H5.\n   fold h' in H9.\n   rewrite H18.\n   exists (list2LocSet (DynamicDGs p field_fsig pivot)).\n   generalize H9; intro.\n   apply PivotTargets_Correct with (p := p) (f_fsig := field_fsig) in H9.\n   destruct H9.\n   rewrite <- H7 in H24.\n   assert (ex (fun dg => direct_FieldInDg_dynamic p h' f dg pivot)).\n    exists dg; trivial.\n    unfold SetBacklinks.\n    apply H24 in H25.\n    clear H9 H24.\n    rewrite H7.\n    induction (PivotTargets p pivot).\n     inversion H25.\n     \n     split.\n      case_eq (FsigDec.eq_dec a field_fsig); intros.\n       simpl in H25.\n       destruct H25.\n        clear IHl.\n        rewrite H24.\n        simpl.\n        unfold set_backlink at 1.\n        simpl.\n        destruct Backlinks.get.\n         unfold get_backlinks.\n         rewrite Backlinks.get_update_same.\n         rewrite LocDict.get_update_same.\n         trivial.\n         \n         unfold get_backlinks.\n         rewrite Backlinks.get_update_same.\n         unfold LocDict.singleton.\n         rewrite LocDict.get_update_same.\n         trivial.\n         \n        rewrite e0.\n        simpl.\n        unfold set_backlink at 1.\n        simpl.\n        destruct Backlinks.get.\n         unfold get_backlinks.\n         rewrite Backlinks.get_update_same.\n         rewrite LocDict.get_update_same.\n         trivial.\n         \n         unfold get_backlinks.\n         rewrite Backlinks.get_update_same.\n         unfold LocDict.singleton.\n         rewrite LocDict.get_update_same.\n         trivial.\n         \n       simpl in H25.\n       destruct H25.\n        elim n; trivial.\n        \n        simpl.\n        unfold set_backlink at 1.\n        destruct Backlinks.get.\n         unfold get_backlinks.\n         rewrite Backlinks.get_update_old.\n          apply IHl.\n          trivial.\n          \n          intro.\n          inversion H25.\n          elim n; trivial.\n          \n         unfold get_backlinks.\n         rewrite Backlinks.get_update_old.\n          apply IHl.\n          trivial.\n          \n          intro.\n          inversion H25.\n          elim n; trivial.\n          \n      apply list2LocSet_1.\n      rewrite DynamicDGs_Correct with (h := h') (f_obj := field_obj); trivial.\n      rewrite <- H7; trivial.\n      \n  rewrite Heap.get_update_old in H9.\n   destruct H4.\n   elim H4.\n    intros.\n    exists x.\n    split; trivial.\n     clear H4 H20.\n     destruct H21.\n     apply get_remove_old with (p := p) (loc := loc) in H4.\n      apply get_set_old with (p := p) (loc := loc) (v := v) in H4; trivial.\n      rewrite <- H18; trivial.\n      \n      rewrite <- H18; trivial.\n      \n     tauto.\n     \n    split\n     with\n       dg_obj\n       dg_fsig\n       field_obj\n       field_fsig\n       pivot_obj\n       pivot_fsig\n       pivot_f\n       dg0; trivial.\n    \n   rewrite <- H18; auto.\n   \n case_eq (LocSet.E.eq_dec pivot loc); intros.\n  rewrite <- e in H5.\n  rewrite <- e.\n  rewrite <- e in H0.\n  rewrite <- e in H.\n  clear loc e H6.\n  destruct f.\n   rewrite <- get_set_old_f_uncompat in H5.\n    rewrite <- get_remove_old_f_uncompat in H5.\n     apply H4 in H5.\n     inversion H5.\n     inversion H7.\n     \n     intros; intro; inversion H6.\n     \n    intros; intro; inversion H6.\n   unfold SetBacklinks in H5.\n   inversion H3.\n    rewrite <- H6 in H5.\n    elim get_remove_none with p st o f pivot dg; trivial.\n    \n    rewrite <- H8 in H5.\n    case_eq (ObjDec.eq_dec o obj).\n     intros.\n     rewrite e.\n     rewrite e in H5.\n     repeat rewrite e in H4.\n     clear o e H10.\n     elim classic with (In f (PivotTargets p pivot)).\n      intros.\n      induction (PivotTargets p pivot).\n       inversion H10.\n       \n       simpl in H10.\n       destruct H10.\n        clear IHl.\n        rewrite H10 in H5.\n        simpl in H5.\n        unfold set_backlink at 1 in H5.\n        case_eq\n         (Backlinks.get\n            (fold_right\n               (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                set_backlink bl' (Heap.InstanceField obj f) pivot\n                  (list2LocSet (DynamicDGs p f pivot)))\n               (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj f));\n         intros; rewrite H11 in H5.\n         simpl.\n         unfold get_backlinks in H5.\n         rewrite Backlinks.get_update_same in H5.\n         rewrite LocDict.get_update_same in H5.\n         destruct H5.\n         destruct H5.\n         inversion H5.\n         rewrite <- H14 in H12.\n         apply list2LocSet_1 in H12.\n         rewrite\n          DynamicDGs_Correct\n           with\n             (h := Heap.update (State.h st) pivot (Ref obj))\n             (f_obj := obj) in H12.\n          trivial.\n          \n          apply Heap.get_update_same.\n          rewrite H0.\n          apply Heap.CompatObject with cn um; trivial.\n          \n         unfold LocDict.singleton in H5.\n         unfold get_backlinks in H5.\n         rewrite Backlinks.get_update_same in H5.\n         rewrite LocDict.get_update_same in H5.\n         destruct H5.\n         destruct H5.\n         inversion H5.\n         rewrite <- H14 in H12.\n         apply list2LocSet_1 in H12.\n         rewrite\n          DynamicDGs_Correct\n           with\n             (h := Heap.update (State.h st) pivot (Ref obj))\n             (f_obj := obj) in H12.\n          trivial.\n          \n          apply Heap.get_update_same.\n          rewrite H0.\n          apply Heap.CompatObject with cn um; trivial.\n          \n        case_eq (FsigDec.eq_dec a f).\n         intros.\n         rewrite e in H5.\n         clear IHl.\n         clear a e H11.\n         simpl in H5.\n         unfold set_backlink at 1 in H5.\n         case_eq\n          (Backlinks.get\n             (fold_right\n                (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                 set_backlink bl' (Heap.InstanceField obj f) pivot\n                   (list2LocSet (DynamicDGs p f pivot)))\n                (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj f));\n          intros; rewrite H11 in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_same in H5.\n          rewrite LocDict.get_update_same in H5.\n          destruct H5.\n          destruct H5.\n          inversion H5.\n          rewrite <- H14 in H12.\n          apply list2LocSet_1 in H12.\n          rewrite\n           DynamicDGs_Correct\n            with\n              (h := Heap.update (State.h st) pivot (Ref obj))\n              (f_obj := obj) in H12.\n           trivial.\n           \n           apply Heap.get_update_same.\n           rewrite H0.\n           apply Heap.CompatObject with cn um; trivial.\n           \n          unfold LocDict.singleton in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_same in H5.\n          rewrite LocDict.get_update_same in H5.\n          destruct H5.\n          destruct H5.\n          inversion H5.\n          rewrite <- H14 in H12.\n          apply list2LocSet_1 in H12.\n          rewrite\n           DynamicDGs_Correct\n            with\n              (h := Heap.update (State.h st) pivot (Ref obj))\n              (f_obj := obj) in H12.\n           trivial.\n           \n           apply Heap.get_update_same.\n           rewrite H0.\n           apply Heap.CompatObject with cn um; trivial.\n           \n         intros.\n         simpl in H5.\n         unfold set_backlink at 1 in H5.\n         case_eq\n          (Backlinks.get\n             (fold_right\n                (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                 set_backlink bl' (Heap.InstanceField obj f) pivot\n                   (list2LocSet (DynamicDGs p f pivot)))\n                (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n          intros; rewrite H12 in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_old in H5.\n           apply IHl; trivial.\n           \n           intro.\n           inversion H13.\n           elim n; trivial.\n           \n          unfold LocDict.singleton in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_old in H5.\n           apply IHl; trivial.\n           \n           intro.\n           inversion H13.\n           elim n; trivial.\n           \n      intros.\n      induction (PivotTargets p pivot).\n       simpl in H5.\n       intros.\n       elim get_remove_none with p st obj f pivot dg; trivial.\n       \n       simpl in H5.\n       unfold set_backlink at 1 in H5.\n       case_eq\n        (Backlinks.get\n           (fold_right\n              (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n               set_backlink bl' (Heap.InstanceField obj f) pivot\n                 (list2LocSet (DynamicDGs p f pivot)))\n              (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n        intros; rewrite H11 in H5.\n        simpl in H5.\n        unfold get_backlinks in H5.\n        rewrite Backlinks.get_update_old in H5.\n         apply IHl; trivial.\n         intro; elim H10; auto with *.\n         \n         intro; elim H10.\n         inversion H12.\n         auto with *.\n         \n        unfold get_backlinks in H5.\n        rewrite Backlinks.get_update_old in H5.\n         apply IHl; trivial.\n         intro; elim H10; auto with *.\n         \n         intro; elim H10.\n         inversion H12.\n         auto with *.\n         \n     intros.\n     induction (PivotTargets p pivot).\n      simpl in H5.\n      elim get_remove_none with p st o f pivot dg; trivial.\n      \n      simpl in H5.\n      unfold set_backlink at 1 in H5.\n      case_eq\n       (Backlinks.get\n          (fold_right\n             (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n              set_backlink bl' (Heap.InstanceField obj f) pivot\n                (list2LocSet (DynamicDGs p f pivot)))\n             (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n       intros; rewrite H11 in H5.\n       simpl in H5.\n       unfold get_backlinks in H5.\n       rewrite Backlinks.get_update_old in H5.\n        apply IHl; trivial.\n        \n        intro; elim n.\n        inversion H12; trivial.\n        \n       unfold get_backlinks in H5.\n       rewrite Backlinks.get_update_old in H5.\n        apply IHl; trivial.\n        \n        intro; elim n.\n        inversion H12; trivial.\n        \n    rewrite <- H8 in H5.\n    case_eq (ObjDec.eq_dec o obj).\n     intros.\n     rewrite e.\n     rewrite e in H5.\n     repeat rewrite e in H4.\n     clear o e H10.\n     elim classic with (In f (PivotTargets p pivot)).\n      intros.\n      induction (PivotTargets p pivot).\n       inversion H10.\n       \n       simpl in H10.\n       destruct H10.\n        clear IHl.\n        rewrite H10 in H5.\n        simpl in H5.\n        unfold set_backlink at 1 in H5.\n        case_eq\n         (Backlinks.get\n            (fold_right\n               (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                set_backlink bl' (Heap.InstanceField obj f) pivot\n                  (list2LocSet (DynamicDGs p f pivot)))\n               (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj f));\n         intros; rewrite H11 in H5.\n         simpl.\n         unfold get_backlinks in H5.\n         rewrite Backlinks.get_update_same in H5.\n         rewrite LocDict.get_update_same in H5.\n         destruct H5.\n         destruct H5.\n         inversion H5.\n         rewrite <- H14 in H12.\n         apply list2LocSet_1 in H12.\n         rewrite\n          DynamicDGs_Correct\n           with\n             (h := Heap.update (State.h st) pivot (Ref obj))\n             (f_obj := obj) in H12.\n          trivial.\n          \n          apply Heap.get_update_same.\n          rewrite H0.\n          apply Heap.CompatObject with cn um; trivial.\n          \n         unfold LocDict.singleton in H5.\n         unfold get_backlinks in H5.\n         rewrite Backlinks.get_update_same in H5.\n         rewrite LocDict.get_update_same in H5.\n         destruct H5.\n         destruct H5.\n         inversion H5.\n         rewrite <- H14 in H12.\n         apply list2LocSet_1 in H12.\n         rewrite\n          DynamicDGs_Correct\n           with\n             (h := Heap.update (State.h st) pivot (Ref obj))\n             (f_obj := obj) in H12.\n          trivial.\n          \n          apply Heap.get_update_same.\n          rewrite H0.\n          apply Heap.CompatObject with cn um; trivial.\n          \n        case_eq (FsigDec.eq_dec a f).\n         intros.\n         rewrite e in H5.\n         clear IHl.\n         clear a e H11.\n         simpl in H5.\n         unfold set_backlink at 1 in H5.\n         case_eq\n          (Backlinks.get\n             (fold_right\n                (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                 set_backlink bl' (Heap.InstanceField obj f) pivot\n                   (list2LocSet (DynamicDGs p f pivot)))\n                (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj f));\n          intros; rewrite H11 in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_same in H5.\n          rewrite LocDict.get_update_same in H5.\n          destruct H5.\n          destruct H5.\n          inversion H5.\n          rewrite <- H14 in H12.\n          apply list2LocSet_1 in H12.\n          rewrite\n           DynamicDGs_Correct\n            with\n              (h := Heap.update (State.h st) pivot (Ref obj))\n              (f_obj := obj) in H12.\n           trivial.\n           \n           apply Heap.get_update_same.\n           rewrite H0.\n           apply Heap.CompatObject with cn um; trivial.\n           \n          unfold LocDict.singleton in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_same in H5.\n          rewrite LocDict.get_update_same in H5.\n          destruct H5.\n          destruct H5.\n          inversion H5.\n          rewrite <- H14 in H12.\n          apply list2LocSet_1 in H12.\n          rewrite\n           DynamicDGs_Correct\n            with\n              (h := Heap.update (State.h st) pivot (Ref obj))\n              (f_obj := obj) in H12.\n           trivial.\n           \n           apply Heap.get_update_same.\n           rewrite H0.\n           apply Heap.CompatObject with cn um; trivial.\n           \n         intros.\n         simpl in H5.\n         unfold set_backlink at 1 in H5.\n         case_eq\n          (Backlinks.get\n             (fold_right\n                (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n                 set_backlink bl' (Heap.InstanceField obj f) pivot\n                   (list2LocSet (DynamicDGs p f pivot)))\n                (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n          intros; rewrite H12 in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_old in H5.\n           apply IHl; trivial.\n           \n           intro.\n           inversion H13.\n           elim n; trivial.\n           \n          unfold LocDict.singleton in H5.\n          unfold get_backlinks in H5.\n          rewrite Backlinks.get_update_old in H5.\n           apply IHl; trivial.\n           \n           intro.\n           inversion H13.\n           elim n; trivial.\n           \n      intros.\n      induction (PivotTargets p pivot).\n       simpl in H5.\n       intros.\n       elim get_remove_none with p st obj f pivot dg; trivial.\n       \n       simpl in H5.\n       unfold set_backlink at 1 in H5.\n       case_eq\n        (Backlinks.get\n           (fold_right\n              (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n               set_backlink bl' (Heap.InstanceField obj f) pivot\n                 (list2LocSet (DynamicDGs p f pivot)))\n              (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n        intros; rewrite H11 in H5.\n        simpl in H5.\n        unfold get_backlinks in H5.\n        rewrite Backlinks.get_update_old in H5.\n         apply IHl; trivial.\n         intro; elim H10; auto with *.\n         \n         intro; elim H10.\n         inversion H12.\n         auto with *.\n         \n        unfold get_backlinks in H5.\n        rewrite Backlinks.get_update_old in H5.\n         apply IHl; trivial.\n         intro; elim H10; auto with *.\n         \n         intro; elim H10.\n         inversion H12.\n         auto with *.\n         \n     intros.\n     induction (PivotTargets p pivot).\n      simpl in H5.\n      elim get_remove_none with p st o f pivot dg; trivial.\n      \n      simpl in H5.\n      unfold set_backlink at 1 in H5.\n      case_eq\n       (Backlinks.get\n          (fold_right\n             (fun (f : FieldSignature) (bl' : Backlinks.t) =>\n              set_backlink bl' (Heap.InstanceField obj f) pivot\n                (list2LocSet (DynamicDGs p f pivot)))\n             (RemoveBacklinks p pivot st) l) (Heap.InstanceField obj a));\n       intros; rewrite H11 in H5.\n       simpl in H5.\n       unfold get_backlinks in H5.\n       rewrite Backlinks.get_update_old in H5.\n        apply IHl; trivial.\n        \n        intro; elim n.\n        inversion H12; trivial.\n        \n       unfold get_backlinks in H5.\n       rewrite Backlinks.get_update_old in H5.\n        apply IHl; trivial.\n        \n        intro; elim n.\n        inversion H12; trivial.\n        \n    rewrite <- H7 in H5.\n    elim get_remove_none with p st o f pivot dg; trivial.\n    \n   rewrite <- get_set_old_f_uncompat in H5.\n    rewrite <- get_remove_old_f_uncompat in H5.\n     apply H4 in H5.\n     inversion H5.\n     inversion H7.\n     \n     intros; intro; inversion H6.\n     \n    intros; intro; inversion H6.\n    \n  destruct H5.\n  destruct H5.\n  apply get_set_old in H5.\n   apply get_remove_old in H5.\n    destruct H4.\n    assert\n     (ex\n        (fun ams  =>\n         and\n           (eq\n              (LocDict.get (get_backlinks (Adds.backlinks (State.adds st)) f)\n                 pivot) (Some ams)) (LocSet.In dg ams))).\n     exists x; auto.\n     \n     apply H8 in H9.\n     inversion H9.\n     split\n      with\n        dg_obj\n        dg_fsig\n        field_obj\n        field_fsig\n        pivot_obj\n        pivot_fsig\n        pivot_f\n        dg0; trivial.\n     rewrite Heap.get_update_old.\n      trivial.\n      \n      auto.\n      \n    trivial.\n    \n   trivial.\nQed.\n\n\nDefinition FieldUpdateAction (p : Program) (pivot : Location) (v : Value) (st : State.t) : State.t :=\n    if (isPivot p pivot) then\n       let bl1 := RemoveBacklinks p pivot st in\n       let bl' := SetBacklinks p pivot v bl1 in\n        st[fr := st@fr[assignables := map (SavePreState p st@bl pivot) st@fr@assignables]][bl := bl']\n    else\n      st.\n\n\nLemma not_isPivot_direct_FieldInDg:\nforall p h f dg pivot loc v,\nisPivot p loc = false ->\n(direct_FieldInDg_dynamic p h f dg pivot <->\ndirect_FieldInDg_dynamic p (Heap.update h loc v) f dg pivot).\nProof.\nintros.\napply not_true_iff_false in H.\nrewrite isPivot_PivotField in H.\nsplit; intro.\n destruct H0.\n split\n  with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg;\n  trivial.\n case_eq (eq_dec loc pivot_loc); intros.\n  rewrite e in H.\n  elim H.\n  split with pivot_fsig pivot_obj pivot_f dg; trivial.\n  \n  rewrite Heap.get_update_old; trivial.\n  \n destruct H0.\n split\n  with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg;\n  trivial.\n case_eq (eq_dec loc pivot_loc); intros.\n  rewrite e in H.\n  elim H.\n  split with pivot_fsig pivot_obj pivot_f dg; trivial.\n  \n  rewrite Heap.get_update_old in H3; trivial.\nQed.\n\n  Lemma FieldUpdateAction_Correct:\n    forall p loc st_rac2 v st_rac2' st_rac3 st_rac3' cn um loc_obj loc_fsig,\n    loc = Heap.InstanceField loc_obj loc_fsig ->\n    Heap.typeof st_rac3@h loc_obj = Some (Heap.ObjectObject cn um) ->\n    defined_field p cn loc_fsig ->\n    assign_compatible p st_rac3@h v (FIELDSIGNATURE.type (snd loc_fsig)) ->\n    CorrespondingState p st_rac2 st_rac3 ->\n    FieldUpdateAction p loc v st_rac3 = st_rac3' ->\n    Rac2.Assignables.FieldUpdateAction p loc v st_rac2 = st_rac2' ->\n    CorrespondingState p \n      st_rac2'[h:=Heap.update st_rac2@h loc v]%rac2\n      st_rac3'[h:=Heap.update st_rac3@h loc v].\nProof.\nintuition.\nunfold FieldUpdateAction in H4.\nunfold Rac2.Assignables.FieldUpdateAction in H5.\ncase_eq (isPivot p loc); intros; rewrite H6 in H5;rewrite H6 in H4.\n inversion H3.\n subst.\n split; simpl.\n\n  inversion H7.\n  subst.\n  split; simpl; trivial.\n  destruct H14.\n  split.\n   repeat rewrite map_length.\n   trivial.\n   \n   intros.\n   case_eq (Nat.compare n (length st_rac3 @fr @assignables )).\n    intros.\n    rewrite nat_compare_Eq in H14.\n    repeat rewrite nth_overflow.\n     auto with *.\n     \n     rewrite map_length.\n     lia.\n     \n     rewrite map_length.\n     lia.\n     \n    intros.\n    apply nat_compare_lt in H14.\n    generalize H14; intros.\n    rewrite <- e in H15.\n    repeat\n     rewrite\n      (nth_indep\n         (map (Rac2.SavePreState p st_rac2 @h%rac2 (Heap.InstanceField loc_obj loc_fsig))\n            st_rac2 @fr%rac2 @assignables) a0\n         (Rac2.SavePreState p st_rac2 @h%rac2 (Heap.InstanceField loc_obj loc_fsig) a0)).\n     repeat\n      rewrite\n       (nth_indep\n          (map (SavePreState p st_rac3 @bl (Heap.InstanceField loc_obj loc_fsig)) st_rac3 @fr @assignables) a0\n          (SavePreState p st_rac3 @bl (Heap.InstanceField loc_obj loc_fsig) a0)).\n      rewrite map_nth.\n      rewrite map_nth.\n      destruct a with n a0.\n      repeat rewrite H8.\n\n      apply SavePreState_same; trivial.\n      \n      rewrite map_length; trivial.\n      \n     rewrite map_length; trivial.\n     \n    intros.\n    rewrite <- nat_compare_gt in H14.\n    repeat rewrite nth_overflow.\n     auto with *.\n     \n     rewrite map_length.\n     lia.\n     \n     rewrite map_length.\n     lia.\n     \n  rewrite H8.\n  trivial.\n  \n  unfold CorrectBacklinks in H9 |- *.\n  unfold CorrectBacklink in H9 |- *.\n  intros.\n  simpl.\n  set (st' := st_rac3[h :=(Heap.update st_rac3 @h (Heap.InstanceField loc_obj loc_fsig) v)]\n[bl := (SetBacklinks p (Heap.InstanceField loc_obj loc_fsig) v\n           (RemoveBacklinks p (Heap.InstanceField loc_obj loc_fsig) st_rac3))]).\n  replace (Heap.update st_rac3 @h (Heap.InstanceField loc_obj loc_fsig) v) with st'@h.\n  replace ((SetBacklinks p (Heap.InstanceField loc_obj loc_fsig) v\n           (RemoveBacklinks p (Heap.InstanceField loc_obj loc_fsig) st_rac3))) with st'@bl.\n  apply SetRemoveBacklinks_Correct with (Heap.InstanceField loc_obj loc_fsig) st_rac3 v cn um loc_obj loc_fsig ;trivial.\n  apply isPivot_PivotField;trivial.\n  unfold CorrectBacklink.\n  trivial.\ntrivial.\ntrivial.\n split; simpl.\n  destruct H.\n  subst; trivial.\n  \n  destruct H3.\n  trivial.\n\n  destruct H3.\n  rewrite H7.\n  trivial.\n  \n  destruct H3.\n  destruct H3.\n  unfold CorrectBacklinks in H8 |- *.\n  unfold CorrectBacklink in H8 |- *.\n  simpl.\n  rewrite <- H4.\n  intros.\n  rewrite <- not_isPivot_direct_FieldInDg.\n   trivial.\n   \n   trivial.\nQed.\n\nLemma CorrectBacklinks_new:\nforall st p cn um obj h' ,\nHeap.new st@h p (Heap.ObjectObject cn um) = Some (obj, h') ->\n(CorrectBacklinks p st <-> CorrectBacklinks p st [h := h']).\nProof.\nintuition.\n intros.\n unfold CorrectBacklinks.\n unfold CorrectBacklink.\n intros.\n destruct H0 with f dg pivot.\n simpl in *.\n intuition.\n  apply H1.\n  clear H1 H2.\n  inversion H3.\n  split\n   with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg0;\n   trivial.\n  assert (pivot_obj <> obj).\n   intro.\n   rewrite H15 in H4.\n   apply\n    Rac2.new_object_field_not_ref\n     with (fsig := pivot_fsig) (loc := pivot) (r := field_obj) \n    in H; trivial.\n   elim H; trivial.\n   \n   rewrite <- H5.\n   symmetry .\n   apply Heap.new_object_no_change with p cn um obj; trivial.\n   intros.\n   rewrite H4.\n   intro.\n   inversion H16.\n   elim H15; trivial.\n   \n  clear H3 H2.\n  inversion H4.\n  split\n   with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg0;\n   trivial.\n  assert (pivot_obj <> obj).\n   intro.\n   rewrite H15 in H3.\n   apply Heap.new_fresh_location in H.\n   assert (~Heap.Compat st @h pivot).\n    intro.\n    destruct H16.\n     inversion H3.\n     \n     inversion H3.\n     rewrite H18 in H16.\n     rewrite H in H16.\n     inversion H16.\n     \n     inversion H3.\n     \n    apply Heap.get_uncompat in H16.\n    rewrite H5 in H16.\n    inversion H16.\n    \n   rewrite <- H5.\n   apply Heap.new_object_no_change with p cn um obj; trivial.\n   intros.\n   rewrite H3.\n   intro.\n   inversion H16.\n   elim H15; trivial.\n   \n unfold CorrectBacklinks.\n unfold CorrectBacklink.\n intros.\n destruct H0 with f dg pivot.\n simpl in *.\n intuition.\n  apply H1.\n  clear H1 H2.\n  inversion H3.\n  split\n   with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg0;\n   trivial.\n  assert (pivot_obj <> obj).\n   intro.\n   rewrite H15 in H4.\n   apply Heap.new_fresh_location in H.\n   assert (~Heap.Compat st @h pivot).\n    intro.\n    destruct H16.\n     inversion H4.\n     \n     inversion H4.\n     rewrite H18 in H16.\n     rewrite H in H16.\n     inversion H16.\n     \n     inversion H4.\n     \n    apply Heap.get_uncompat in H16.\n    rewrite H5 in H16.\n    inversion H16.\n    \n   rewrite <- H5.\n   apply Heap.new_object_no_change with p cn um obj; trivial.\n   intros.\n   rewrite H4.\n   intro.\n   inversion H16.\n   elim H15; trivial.\n   \n  clear H3 H2.\n  inversion H4.\n  split\n   with dg_obj dg_fsig field_obj field_fsig pivot_obj pivot_fsig pivot_f dg0;\n   trivial.\n  assert (pivot_obj <> obj).\n   intro.\n   rewrite H15 in H3.\n   apply\n    Rac2.new_object_field_not_ref\n     with (fsig := pivot_fsig) (loc := pivot) (r := field_obj) \n    in H; trivial.\n   elim H; trivial.\n   \n   rewrite <- H5.\n   symmetry .\n   apply Heap.new_object_no_change with p cn um obj; trivial.\n   intros.\n   rewrite H3.\n   intro.\n   inversion H16.\n   elim H15; trivial.\nQed.\n\nEnd Assignables.\n\nEnd Rac3.\n", "meta": {"author": "coq-community", "repo": "jmlcoq", "sha": "f9a99b380992d7b6302673ac6d313c34afa43daf", "save_path": "github-repos/coq/coq-community-jmlcoq", "path": "github-repos/coq/coq-community-jmlcoq/jmlcoq-f9a99b380992d7b6302673ac6d313c34afa43daf/theories/JMLRac3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.19422425320806055}}
{"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.Vectors.Vector.\nRequire Import Cava.Cava.\nRequire Import Cava.CavaProperties.\nOpen Scope monad_scope.\n\nSection WithCava.\n  Context `{semantics: Cava}.\n\n  Definition half_adder (input : signal Bit * signal Bit)\n  : cava (signal Bit * signal Bit) :=\n    sum <- xor2 input ;;\n    carry <- and2 input ;;\n    ret (sum, carry).\n\n  Definition half_subtractor (input : signal Bit * signal Bit)\n    : cava (signal Bit * signal Bit) :=\n    let '(x,y) := input in\n    diff <- xor2 (x,y) ;;\n    notx <- inv x ;;\n    borrow <- and2 (notx, y) ;;\n    ret (diff, borrow).\n\n  (* increment a 4-bit vector *)\n  Definition incr4 (input : signal (Vec Bit 4))\n    : cava (signal (Vec Bit 4)) :=\n    i0 <- indexConst input 0 ;;\n    i1 <- indexConst input 1 ;;\n    i2 <- indexConst input 2 ;;\n    i3 <- indexConst input 3 ;;\n    '(sum0, carry) <- half_adder (one, i0) ;;\n    '(sum1, carry) <- half_adder (carry, i1) ;;\n    '(sum2, carry) <- half_adder (carry, i2) ;;\n    '(sum3, carry) <- half_adder (carry, i3) ;;\n    packV [sum0;sum1;sum2;sum3]%vector.\n\n  (* decrement a 4-bit vector *)\n  Definition decr4 (input : signal (Vec Bit 4))\n    : cava (signal (Vec Bit 4)) :=\n    i0 <- indexConst input 0 ;;\n    i1 <- indexConst input 1 ;;\n    i2 <- indexConst input 2 ;;\n    i3 <- indexConst input 3 ;;\n    '(diff0, borrow) <- half_subtractor (i0, one) ;;\n    '(diff1, borrow) <- half_subtractor (i1, borrow) ;;\n    '(diff2, borrow) <- half_subtractor (i2, borrow) ;;\n    '(diff3, borrow) <- half_subtractor (i3, borrow) ;;\n    packV [diff0;diff1;diff2;diff3]%vector.\n\n  Fixpoint incr' {sz} (carry : signal Bit)\n    : signal (Vec Bit sz) -> cava (signal (Vec Bit sz)) :=\n    match sz as sz0 return\n          signal (Vec Bit sz0) -> cava (signal (Vec Bit sz0)) with\n    | 0 => fun input => ret input\n    | S sz' => fun input : signal (Vec Bit (S sz')) =>\n                i0 <- Vec.hd input ;;\n                rem <- Vec.tl input ;;\n                '(sum0, carry) <- half_adder (carry, i0) ;;\n                sum <- incr' carry rem ;;\n                Vec.cons sum0 sum\n    end.\n\n  (* increments a bit vector of any length *)\n  Definition incr {sz} (input : signal (Vec Bit sz)) : cava (signal (Vec Bit sz)) :=\n    incr' one input.\n\n  Fixpoint decr' {sz} (borrow : signal Bit)\n    : signal (Vec Bit sz) -> cava (signal (Vec Bit sz)) :=\n    match sz as sz0 return\n          signal (Vec Bit sz0) -> cava (signal (Vec Bit sz0)) with\n    | 0 => fun input => ret input\n    | S sz' => fun input : signal (Vec Bit (S sz')) =>\n                i0 <- Vec.hd input ;;\n                rem <- Vec.tl input ;;\n                '(diff0, borrow) <- half_subtractor (i0, borrow) ;;\n                diff <- decr' borrow rem ;;\n                Vec.cons diff0 diff\n    end.\n\n  (* decrements a bit vector of any length *)\n  Definition decr {sz} (input : signal (Vec Bit sz)) : cava (signal (Vec Bit sz)) :=\n    decr' one input.\nEnd WithCava.\n\nSection Proofs.\n  Existing Instance CombinationalSemantics.\n\n  Lemma half_adder_correct (x y : combType Bit) :\n    half_adder (x,y) = (xorb x y, andb x y).\n  Proof.\n    cbv [half_adder and2 xor2 CombinationalSemantics].\n    simpl_ident. reflexivity.\n  Qed.\n  Hint Rewrite half_adder_correct using solve [eauto] : simpl_ident.\n\n  Lemma incr4_correct (input : combType (Vec Bit 4)) :\n    incr4 input = N2Bv_sized 4 (Bv2N input + 1).\n  Proof.\n    cbv [incr4]. simpl_ident. boolsimpl.\n    cbn [packV indexConst CombinationalSemantics].\n    cbn [combType] in input. constant_bitvec_cases input.\n    all:reflexivity.\n  Qed.\n\n  Lemma half_subtractor_correct (x y : combType Bit) :\n    half_subtractor (x,y) = (xorb x y, andb (negb x) y).\n  Proof.\n    cbv [half_subtractor and2 xor2 CombinationalSemantics].\n    simpl_ident; reflexivity.\n  Qed.\n  Hint Rewrite half_subtractor_correct using solve [eauto] : simpl_ident.\n\n  Lemma decr4_correct (input : combType (Vec Bit 4)) :\n    decr4 input = N2Bv_sized 4 (if (Bv2N input =? 0)%N then 15\n                                          else Bv2N input - 1).\n  Proof.\n    cbv [decr4]. simpl_ident. boolsimpl.\n    cbn [combType] in input. constant_bitvec_cases input.\n    all:reflexivity.\n  Qed.\n\n  Lemma incr'_correct {sz} carry (input : combType (Vec Bit sz)) :\n    incr' carry input\n    = N2Bv_sized _ (Bv2N input + if carry then 1 else 0)%N.\n  Proof.\n    revert carry input; induction sz; intros; [ cbn; f_equal; solve [apply nil_eq] | ].\n    cbn [incr']. simpl_ident.\n    rewrite (Vector.eta input). autorewrite with vsimpl.\n    rewrite IHsz. rewrite Bv2N_cons.\n    destruct carry, (Vector.hd input); boolsimpl;\n      rewrite ?N.add_0_r, ?N.double_succ_double, ?N.succ_double_succ;\n      rewrite ?N2Bv_sized_double, ?N2Bv_sized_succ_double;\n      reflexivity.\n  Qed.\n\n  Lemma incr_correct {sz} (input : combType (Vec Bit sz)) :\n    incr input = N2Bv_sized _ (Bv2N input + 1).\n  Proof. cbv [incr]. simpl_ident. apply incr'_correct. Qed.\n\n  Lemma decr'_correct {sz} borrow (input : combType (Vec Bit sz)) :\n    decr' borrow input\n    = N2Bv_sized _ (if borrow\n                    then if (Bv2N input =? 0)%N\n                         then N.ones (N.of_nat sz)\n                         else N.pred (Bv2N input)\n                    else Bv2N input).\n  Proof.\n    revert borrow input; induction sz; intros; [ cbn; f_equal; solve [apply nil_eq] | ].\n    cbn [decr']. simpl_ident.\n    rewrite (eta input). autorewrite with vsimpl. repeat destruct_pair_let.\n    rewrite IHsz. rewrite Bv2N_cons.\n    destruct borrow, (Vector.hd input); boolsimpl;\n      autorewrite with push_Bv2N push_N2Bv_sized;\n      rewrite ?N.sub_0_r, ?N2Bv_sized_Bv2N;\n      try reflexivity; [ | ].\n    (* solve the majority of cases *)\n    all:repeat match goal with\n               | H : (?n = 0)%N |- _ => rewrite H\n               | H : (N.succ_double ?n = 0)%N |- _ =>\n                 rewrite N.succ_double_spec in H; lia\n               | H : (N.double 0 <> 0)%N |- _ =>\n                 cbn [N.double] in H; congruence\n               | H1 : (?n <> 0)%N, H2 : (N.double ?n = 0)%N |- _ =>\n                 rewrite N.double_spec in H2; lia\n               | _ => first [ progress autorewrite with push_N2Bv_sized\n                           | rewrite N2Bv_sized_Bv2N\n                           | rewrite N.pred_sub, N.succ_double_double\n                           | destruct_one_match\n                           | reflexivity ]\n               end.\n    (* should only have one case left *)\n    {  f_equal; rewrite <-N2Bv_sized_succ_double.\n       rewrite !N.double_spec, !N.succ_double_spec, !N.pred_sub.\n       f_equal; lia. }\n  Qed.\n\n  Lemma decr_correct {sz} (input : combType (Vec Bit sz)) :\n    decr input\n    = N2Bv_sized _ ( if (Bv2N input =? 0)%N\n                     then 2 ^ (N.of_nat sz) - 1\n                     else Bv2N input - 1)%N.\n  Proof.\n    cbv [decr]. rewrite decr'_correct.\n    rewrite N.ones_equiv, !N.pred_sub. reflexivity.\n  Qed.\nEnd Proofs.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/examples/IncrDecr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.1942242515133966}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.msl.cjoins.\nRequire Import VST.msl.Coqlib2.\nRequire Import VST.msl.sepalg_list.\nRequire Import VST.veric.shares.\nRequire Import VST.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' 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' 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  repeat intro.\n  apply rmap_ext.\n  { apply join_level in H0; tauto. }\n  intro l; specialize (H l).\n  apply (resource_at_join _ _ _ l), H in H0; auto.\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.\napply identity_unit' 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; inv H0.\n  econstructor; proof_irr; eauto.\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; inv H0.\n  eauto.\nQed.\n\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' 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\n(*Lemma Cross_resource: Cross_alg resource.\nProof.\nintro; intros.\ndestruct a as [ra | ra sa ka pa | ka pa | ma].\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   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.\ndestruct b as [| | | mb]; try solve [elimtype False; inv H].\ndestruct z as [| | | mz]; try solve [elimtype False; inv H].\ndestruct c as [| | | mc]; try solve [elimtype False; inv H0].\ndestruct d as [| | | md]; try solve [elimtype False; inv H0].\n(* relies on cross-split for ghost state *)\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\n(*Definition fixup_trace (retain: AV.address -> Share.t)\n                 (trace: AV.address -> option (rshare * AV.kind)) (gtrace: AV.address -> option M)\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 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 +\ninv H; simpl.\nadmit. (* What should fixup_trace do with a ghost? *)\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.\n*\ninv H.\nadmit.\nAdmitted.\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.\n   + apply identity_unit' in H. inv H; auto. apply identity_unit_equiv; auto.\n   + repeat intro.\n     inv H0.\n     * apply H in RJ; subst.\n       f_equal; apply proof_irr.\n     * apply H in RJ; subst.\n       f_equal; apply proof_irr.\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 replace (core w @ i) with (core (core w @ i)).\n pose proof (core_unit (w @ i)) as H1.\n pose proof (core_unit w) as H2.\n apply (resource_at_join _ _ _ i) in H2.\n unfold unit_for in *.\n rewrite <- core_idem.\n destruct (join_assoc (join_comm H1) (join_comm H2)) as [? [? ?]].\n eapply join_core2; eauto.\n symmetry; apply identity_core, resource_at_core_identity.\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\nLemma core_not_YES: forall {w loc rsh sh k pp},\n   core w @ loc = YES rsh sh k pp -> False.\nProof.\nintros.\npose proof (core_duplicable w) as Hj.\napply (resource_at_join _ _ _ loc) in Hj; rewrite H in Hj.\ninv Hj.\neapply readable_nonidentity; eauto.\neapply unit_identity; eauto.\nQed.\n\nLemma resource_at_empty2:\n forall phi: rmap, (forall l, identity (phi @ l)) -> identity phi.\nProof.\nrepeat intro.\napply rmap_ext.\n{ eapply join_level; eauto. }\nintro l.\napply (resource_at_join _ _ _ l), H in H0; auto.\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": "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/rmaps_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19422425151339656}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\n(** This file describes a subset of the C type system. This subset includes\npointer, array, struct, and union types, but omits qualifiers as volatile and\nconst. Also variable length arrays are omitted from the formalization. *)\nFrom stdpp Require Import fin_maps stringmap mapset.\nFrom Coq Require Import String.\nRequire Import prelude stringmap.\nRequire Export type_classes integer_coding.\n\n(** * Tags *)\n(** We consider an (unordered) environment to maps tags (struct and union\nnames) to lists of types corresponding to the fields of structs and unions.\nWe use the same namespace for structs and unions. *)\nDefinition tag := string.\nDefinition tagmap := stringmap.\nNotation tagset := (mapset tagmap).\n\n#[global] Instance tag_eq_dec: EqDecision tag. \nProof. solve_decision. Defined.\n#[global] Instance tagmap_dec `{EqDecision A}: EqDecision (tagmap A).\nProof. solve_decision. Defined.\n#[global] Instance tagmap_empty {A} : Empty (tagmap A) := @empty (stringmap A) _.\n#[global] Instance tagmap_lookup {A} : Lookup tag A (tagmap A) :=\n  @lookup _ _ (stringmap A) _.\n#[global] Instance tagmap_partial_alter {A} : PartialAlter tag A (tagmap A) :=\n  @partial_alter _ _ (stringmap A) _.\n#[global] Instance tagmap_to_list {A} : FinMapToList tag A (tagmap A) :=\n  @map_to_list _ _ (tagmap A) _.\n#[global] Instance tagmap_omap: OMap tagmap := @omap stringmap _.\n#[global] Instance tagmap_merge : Merge tagmap := @merge stringmap _.\n#[global] Instance tagmap_fmap: FMap tagmap := @fmap stringmap _.\n#[global] Instance: FinMap tag tagmap := _.\n#[global] Instance tagmap_dom {A} : Dom (tagmap A) tagset := mapset_dom.\n#[global] Instance: FinMapDom tag tagmap tagset := mapset_dom_spec.\n\nTypeclasses Opaque tag tagmap.\n\n(** * Function names *)\n(** Function names have a separate namespace from structs/unions. *)\nDefinition funname := string.\nDefinition funmap := stringmap.\nNotation funset := (mapset funmap).\n\n#[global] Instance funname_eq_dec: EqDecision funname.\nProof. solve_decision. Defined.\n#[global] Instance funmap_dec {A} `{EqDecision A}: EqDecision (funmap A).\nProof. solve_decision. Defined.\n#[global] Instance funmap_empty {A} : Empty (funmap A) := @empty (stringmap A) _.\n#[global] Instance funmap_lookup {A} : Lookup funname A (funmap A) :=\n  @lookup _ _ (stringmap A) _.\n#[global] Instance funmap_partial_alter {A} : PartialAlter funname A (funmap A) :=\n  @partial_alter _ _ (stringmap A) _.\n#[global] Instance funmap_to_list {A} : FinMapToList funname A (funmap A) :=\n  @map_to_list _ _ (funmap A) _.\n#[global] Instance funmap_omap: OMap funmap := @omap stringmap _.\n#[global] Instance funmap_merge : Merge funmap := @merge stringmap _.\n#[global] Instance funmap_fmap: FMap funmap := @fmap stringmap _.\n#[global] Instance: FinMap funname funmap := _.\n#[global] Instance funmap_dom {A} : Dom (funmap A) funset := mapset_dom.\n#[global] Instance: FinMapDom funname funmap funset := mapset_dom_spec.\n\nTypeclasses Opaque funname funmap.\n\n(** * Types *)\n(** Types are defined mutually inductively. The type [type] represents the\ntypes of full C types (arrays, structs, unions), and [base_type] describes the\ntypes of values that can occur at the leafs of a full value (integers,\npointers). Structs and unions include a name that refers to their fields in the\nenvironment. *)\nInductive compound_kind := Struct_kind | Union_kind.\n\nInductive type (K : iType) : iType :=\n  | TBase :> base_type K \u2192 type K\n  | TArray : type K \u2192 nat \u2192 type K\n  | TCompound : compound_kind \u2192 tag \u2192 type K\nwith ptr_type (K : iType) : iType :=\n  | TType : type K \u2192 ptr_type K\n  | TAny : ptr_type K\n  | TFun : list (type K) \u2192 type K \u2192 ptr_type K\nwith base_type (K : iType) : iType :=\n  | TVoid : base_type K\n  | TInt : int_type K \u2192 base_type K\n  | TPtr : ptr_type K \u2192 base_type K.\n\nDeclare Scope ctype_scope.\nDeclare Scope cptr_type_scope.\nDeclare Scope cbase_type_scope.\nDelimit Scope ctype_scope with T.\nDelimit Scope cptr_type_scope with PT.\nDelimit Scope cbase_type_scope with BT.\nBind Scope ctype_scope with type.\nBind Scope cptr_type_scope with ptr_type.\nBind Scope cbase_type_scope with base_type.\nLocal Open Scope ctype_scope.\n\nArguments TBase {_} _%BT.\nArguments TArray {_} _ _.\nArguments TCompound {_} _ _%string.\nArguments TType {_} _%T.\nArguments TAny {_}.\nArguments TFun {_} _%T _%T.\nArguments TVoid {_}.\nArguments TInt {_} _%IT.\nArguments TPtr {_} _%PT.\n\nNotation \"'baseT' \u03c4\" := (TBase \u03c4) (at level 10) : ctype_scope.\nNotation \"'baseT' \u03c4\" := (TType (TBase \u03c4)) (at level 10) : cptr_type_scope.\nNotation \"\u03c4 .[ n ]\" := (TArray \u03c4 n)\n  (at level 25, left associativity, format \"\u03c4 .[ n ]\") : ctype_scope.\nNotation \"\u03c4 .[ n ]\" := (TType (TArray \u03c4 n))\n  (at level 25, left associativity, format \"\u03c4 .[ n ]\") : cptr_type_scope.\nNotation \"'compoundT{' c } s\" := (TCompound c s)\n  (at level 10, format \"'compoundT{' c }  s\") : ctype_scope.\nNotation \"'compoundT{' c } s\" := (TType (TCompound c s))\n  (at level 10, format \"'compoundT{' c }  s\") : cptr_type_scope.\nNotation \"'structT' s\" := (TCompound Struct_kind s) (at level 10) : ctype_scope.\nNotation \"'structT' s\" := (TType (TCompound Struct_kind s))\n  (at level 10) : cptr_type_scope.\nNotation \"'unionT' s\" := (TCompound Union_kind s) (at level 10) : ctype_scope.\nNotation \"'unionT' s\" := (TType (TCompound Union_kind s))\n  (at level 10) : cptr_type_scope.\nNotation \"'voidT'\" := TVoid : cbase_type_scope.\nNotation \"'voidT'\" := (TBase TVoid) : ctype_scope.\nNotation \"'intT' \u03c4\" := (TInt \u03c4) (at level 10) : cbase_type_scope.\nNotation \"'intT' \u03c4\" := (TBase (TInt \u03c4)) (at level 10) : ctype_scope.\nNotation \"'intT' \u03c4\" := (TType (TBase (TInt \u03c4))) (at level 10) : cptr_type_scope.\nNotation \"'charT{' K }\" := (TInt (charT{K})) : cbase_type_scope.\nNotation \"'charT'\" := (TInt charT) : cbase_type_scope.\nNotation \"'charT{' K }\" := (TBase (charT{K})) : ctype_scope.\nNotation \"'charT'\" := (TBase charT) : ctype_scope.\nNotation \"'charT{' K }\" := (TType (charT{K})) : cptr_type_scope.\nNotation \"'charT'\" := (TType charT) : cptr_type_scope.\nNotation \"'ucharT'\" := (TInt ucharT) : cbase_type_scope.\nNotation \"'ucharT'\" := (TBase ucharT) : ctype_scope.\nNotation \"'ucharT'\" := (TType (TBase ucharT)) : cptr_type_scope.\nNotation \"'scharT'\" := (TInt scharT) : cbase_type_scope.\nNotation \"'scharT'\" := (TBase scharT) : ctype_scope.\nNotation \"'scharT'\" := (TType (TBase scharT)) : cptr_type_scope.\nNotation \"'uintT'\" := (TInt uintT) : cbase_type_scope.\nNotation \"'uintT'\" := (TBase uintT) : ctype_scope.\nNotation \"'uintT'\" := (TType (TBase uintT)) : cptr_type_scope.\nNotation \"'sintT'\" := (TInt sintT) : cbase_type_scope.\nNotation \"'sintT'\" := (TBase sintT) : ctype_scope.\nNotation \"'sintT'\" := (TType (TBase sintT)) : cptr_type_scope.\nNotation \"'uptrT'\" := (TInt uptrT) : cbase_type_scope.\nNotation \"'uptrT'\" := (TBase uptrT) : ctype_scope.\nNotation \"'uptrT'\" := (TType (TBase uptrT)) : cptr_type_scope.\nNotation \"'sptrT'\" := (TInt sptrT) : cbase_type_scope.\nNotation \"'sptrT'\" := (TBase sptrT) : ctype_scope.\nNotation \"'sptrT'\" := (TType (TBase sptrT)) : cptr_type_scope.\nNotation \"\u03c4p .*\" := (TPtr \u03c4p) (at level 25, format \"\u03c4p .*\") : cbase_type_scope.\nNotation \"\u03c4p .*\" := (TBase (\u03c4p.*)) (at level 25, format \"\u03c4p .*\") : ctype_scope.\nNotation \"\u03c4p .*\" := (TType (TBase (\u03c4p.*)))\n  (at level 25, format \"\u03c4p .*\") : cptr_type_scope.\nNotation \"\u03c4s ~> \u03c4\" := (TFun \u03c4s \u03c4) (at level 40) : ctype_scope.\n\n#[global] Instance compound_kind_eq_dec: EqDecision compound_kind.\nProof. solve_decision. Defined.\nSection dec.\nContext `{EqDecision K}.\nFixpoint type_eq_dec' (\u03c41 \u03c42 : type K) : Decision (\u03c41 = \u03c42)\nwith ptr_type_eq_dec' (\u03c4p1 \u03c4p2 : ptr_type K) : Decision (\u03c4p1 = \u03c4p2)\nwith base_type_eq_dec' (\u03c4b1 \u03c4b2 : base_type K) : Decision (\u03c4b1 = \u03c4b2).\nProof.\n refine\n  match \u03c41, \u03c42 with\n  | baseT \u03c4b1, baseT \u03c4b2 => cast_if (decide (\u03c4b1 = \u03c4b2))\n  | \u03c41.[n1], \u03c42.[n2] =>\n     cast_if_and (decide (n1 = n2)) (decide (\u03c41 = \u03c42))\n  | compoundT{c1} s1, compoundT{c2} s2 =>\n     cast_if_and (decide (c1 = c2)) (decide (s1 = s2))\n  | _, _ => right _\n  end; try solve_decision; abstract congruence.\n refine\n  match \u03c4p1, \u03c4p2 with\n  | TType \u03c41, TType \u03c42 => cast_if (decide (\u03c41 = \u03c42))\n  | TAny, TAny => left _\n  | \u03c4s1 ~> \u03c41, \u03c4s2 ~> \u03c42 =>\n     cast_if_and (decide (\u03c41 = \u03c42)) (decide (\u03c4s1 = \u03c4s2))\n  | _, _ => right _\n  end; try solve_decision; abstract congruence.\n refine\n  match \u03c4b1, \u03c4b2 with\n  | voidT, voidT => left _\n  | intT \u03c4i1, intT \u03c4i2 => cast_if (decide (\u03c4i1 = \u03c4i2))\n  | \u03c4p1.*, \u03c4p2.* => cast_if (decide (\u03c4p1 = \u03c4p2))\n  | _, _ => right _\n  end%BT; try solve_decision; abstract congruence.\nDefined.\n#[global] Instance type_eq_dec: EqDecision (type K) := type_eq_dec'.\n#[global] Instance ptr_type_eq_dec: EqDecision (ptr_type K) := ptr_type_eq_dec'.\n#[global] Instance base_type_eq_dec: EqDecision (base_type K) := base_type_eq_dec'.\nEnd dec.\n\n#[global] Instance maybe_TInt {K} : Maybe (@TInt K) := \u03bb \u03c4b,\n  match \u03c4b with intT \u03c4i => Some \u03c4i | _ => None end%BT.\n#[global] Instance maybe_TPtr {K} : Maybe (@TPtr K) := \u03bb \u03c4b,\n  match \u03c4b with \u03c4p.* => Some \u03c4p | _ => None end%BT.\n#[global] Instance maybe_TBase {K} : Maybe (@TBase K) := \u03bb \u03c4,\n  match \u03c4 with baseT \u03c4b => Some \u03c4b | _ => None end.\n#[global] Instance maybe_TArray {K} : Maybe2 (@TArray K) := \u03bb \u03c4,\n  match \u03c4 with \u03c4.[n] => Some (\u03c4,n) | _ => None end.\n#[global] Instance maybe_TCompound {K} : Maybe2 (@TCompound K) := \u03bb \u03c4,\n  match \u03c4 with compoundT{c} t => Some (c,t) | _ => None end.\n#[global] Instance maybe_TType {K} : Maybe (@TType K) := \u03bb \u03c4,\n  match \u03c4 with TType \u03c4 => Some \u03c4 | _ => None end.\n#[global] Instance maybe_TFun {K} : Maybe2 (@TFun K) := \u03bb \u03c4,\n  match \u03c4 with \u03c4s ~> \u03c4 => Some (\u03c4s,\u03c4) | _ => None end.\n\n(** * Environments *)\nRecord env (K : iType) : iType := mk_env {\n  env_t : tagmap (list (type K));\n  env_f : funmap (list (type K) * type K)\n}.\nAdd Printing Constructor env.\nArguments mk_env {_} _ _.\nArguments env_t {_} _.\nArguments env_f {_} _.\n\n#[global] Instance env_subseteq {K} : SubsetEq (env K) := \u03bb \u03931 \u03932,\n  env_t \u03931 \u2286 env_t \u03932 \u2227 env_f \u03931 \u2286 env_f \u03932.\n#[global] Instance env_empty {K} : Empty (env K) := mk_env \u2205 \u2205.\n#[global] Instance env_lookup_compound {K} :\n  Lookup tag (list (type K)) (env K) := \u03bb t \u0393, env_t \u0393 !! t.\n#[global] Instance env_lookup_fun {K} :\n  Lookup funname (list (type K) * type K) (env K) := \u03bb f \u0393, env_f \u0393 !! f.\n#[global] Instance env_insert_compound {K} :\n    Insert tag (list (type K)) (env K) := \u03bb t \u03c4s \u0393,\n  mk_env (<[t:=\u03c4s]>(env_t \u0393)) (env_f \u0393).\n#[global] Instance env_insert_fun {K} :\n    Insert funname (list (type K) * type K) (env K) := \u03bb f \u03c4s\u03c4 \u0393,\n  mk_env (env_t \u0393) (<[f:=\u03c4s\u03c4]>(env_f \u0393)).\n#[global] Instance env_delete_compound {K} :\n  Delete tag (env K) := \u03bb t \u0393, mk_env (delete t (env_t \u0393)) (env_f \u0393).\n#[global] Instance env_delete_fun {K} :\n  Delete funname (env K) := \u03bb f \u0393, mk_env (env_t \u0393) (delete f (env_f \u0393)).\n\n(** * Well-formed types *)\n(** Not all pseudo-types are valid C types; in particular circular unions and\nstructs (like [struct t { struct t x; }]) are not excluded. The predicate\n[type_valid \u0393] describes that a type is valid with respect to [\u0393]. That means,\nrecursive occurrences of unions and structs are always guarded by a pointer.\nThe predicate [env_valid] describes that an environment is valid. *)\nSection types.\n  Context {K : iType} `{EqDecision K}.\n  Implicit Types \u0393 \u03a3 : env K.\n  Implicit Types \u03c4 : type K.\n  Implicit Types \u03c4p : ptr_type K.\n  Implicit Types \u03c4s : list (type K).\n  Implicit Types \u03c4ps : list (ptr_type K).\n  Implicit Types \u03c4b : base_type K.\n  Implicit Types \u03c4i : int_type K.\n  Implicit Types t : tag.\n  Implicit Types f : funname.\n\n  Inductive type_valid' \u0393 : type K \u2192 Prop :=\n    | TBase_valid' \u03c4b : base_type_valid' \u0393 \u03c4b \u2192 type_valid' \u0393 (baseT \u03c4b)\n    | TArray_valid' \u03c4 n : type_valid' \u0393 \u03c4 \u2192 n \u2260 0 \u2192 type_valid' \u0393 (\u03c4.[n])\n    | TCompound_valid' c t : is_Some (\u0393 !! t) \u2192 type_valid' \u0393 (compoundT{c} t)\n  with ptr_type_valid' \u0393 : ptr_type K \u2192 Prop :=\n    | TAny_ptr_valid' : ptr_type_valid' \u0393 TAny\n    | TBase_ptr_valid' \u03c4b :\n       base_type_valid' \u0393 \u03c4b \u2192 ptr_type_valid' \u0393 (baseT \u03c4b)\n    | TArray_ptr_valid' \u03c4 n :\n       type_valid' \u0393 \u03c4 \u2192 n \u2260 0 \u2192 ptr_type_valid' \u0393 (\u03c4.[n])\n    | TCompound_ptr_valid' c t : ptr_type_valid' \u0393 (compoundT{c} t)\n    | TFun_ptr_valid' \u03c4s \u03c4 :\n       Forall (ptr_type_valid' \u0393) (TType <$> \u03c4s) \u2192 ptr_type_valid' \u0393 (TType \u03c4) \u2192\n       ptr_type_valid' \u0393 (\u03c4s ~> \u03c4)\n  with base_type_valid' \u0393 : base_type K \u2192 Prop :=\n    | TVoid_valid' : base_type_valid' \u0393 voidT\n    | TInt_valid' \u03c4i : base_type_valid' \u0393 (intT \u03c4i)\n    | TPtr_valid' \u03c4p : ptr_type_valid' \u0393 \u03c4p \u2192 base_type_valid' \u0393 (\u03c4p.*).\n  Global Instance type_valid : Valid (env K) (type K) := type_valid'.\n  Global Instance ptr_type_valid :\n    Valid (env K) (ptr_type K) := ptr_type_valid'.\n  Global Instance base_type_valid :\n    Valid (env K) (base_type K) := base_type_valid'.\n\n  Lemma TBase_valid \u0393 \u03c4b : \u2713{\u0393} \u03c4b \u2192 \u2713{\u0393} (baseT \u03c4b).\n  Proof. by constructor. Qed.\n  Lemma TArray_valid \u0393 \u03c4 n : \u2713{\u0393} \u03c4 \u2192 n \u2260 0 \u2192 \u2713{\u0393} (\u03c4.[n]).\n  Proof. by constructor. Qed.\n  Lemma TCompound_valid \u0393 c t : is_Some (\u0393 !! t) \u2192 \u2713{\u0393} (compoundT{c} t).\n  Proof. by constructor. Qed.\n\n  Lemma TAny_ptr_valid \u0393 : \u2713{\u0393} TAny.\n  Proof. constructor. Qed.\n  Lemma TBase_ptr_valid \u0393 \u03c4b : \u2713{\u0393} \u03c4b \u2192 \u2713{\u0393} (baseT \u03c4b)%PT.\n  Proof. by constructor. Qed.\n  Lemma TArray_ptr_valid \u0393 \u03c4 n : \u2713{\u0393} \u03c4 \u2192 n \u2260 0 \u2192 \u2713{\u0393} (\u03c4.[n])%PT.\n  Proof. by constructor. Qed.\n  Lemma TCompound_ptr_valid \u0393 c t : \u2713{\u0393} (compoundT{c} t)%PT.\n  Proof. by constructor. Qed.\n  Lemma TFun_ptr_valid \u0393 \u03c4s \u03c4 :\n    \u2713{\u0393}* (TType <$> \u03c4s) \u2192 \u2713{\u0393} (TType \u03c4) \u2192 \u2713{\u0393} (\u03c4s ~> \u03c4).\n  Proof. by constructor. Qed.\n\n  Lemma TVoid_valid \u0393 : \u2713{\u0393} voidT%BT.\n  Proof. by constructor. Qed.\n  Lemma TInt_valid \u0393 \u03c4i : \u2713{\u0393} (intT \u03c4i)%BT.\n  Proof. by constructor. Qed.\n  Lemma TPtr_valid \u0393 \u03c4p : \u2713{\u0393} \u03c4p \u2192 \u2713{\u0393} (\u03c4p.*)%BT.\n  Proof. by constructor. Qed.\n\n  Lemma TBase_valid_inv \u0393 \u03c4b : \u2713{\u0393} (baseT \u03c4b) \u2192 \u2713{\u0393} \u03c4b.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TArray_valid_inv \u0393 \u03c4 n : \u2713{\u0393} (\u03c4.[n]) \u2192 \u2713{\u0393} \u03c4 \u2227 n \u2260 0.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TArray_valid_inv_type \u0393 \u03c4 n : \u2713{\u0393} (\u03c4.[n]) \u2192 \u2713{\u0393} \u03c4.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TArray_valid_inv_size \u0393 \u03c4 n : \u2713{\u0393} (\u03c4.[n]) \u2192 n \u2260 0.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TArray_ptr_valid_inv_size \u0393 \u03c4 n : \u2713{\u0393} (TType (\u03c4.[n])) \u2192 n \u2260 0.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TCompound_valid_inv \u0393 c t : \u2713{\u0393} (compoundT{c} t) \u2192 is_Some (\u0393 !! t).\n  Proof. by inversion_clear 1. Qed.\n  Lemma TBase_ptr_valid_inv \u0393 \u03c4b : \u2713{\u0393} (baseT \u03c4b)%PT \u2192 \u2713{\u0393} \u03c4b.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TArray_ptr_valid_inv_type \u0393 \u03c4 n : \u2713{\u0393} (\u03c4.[n])%PT \u2192 \u2713{\u0393} \u03c4.\n  Proof. by inversion_clear 1. Qed.\n  Lemma TFun_valid_inv \u0393 \u03c4s \u03c4 :\n    \u2713{\u0393} (\u03c4s ~> \u03c4) \u2192 \u2713{\u0393}* (TType <$> \u03c4s) \u2227 \u2713{\u0393} (TType \u03c4).\n  Proof. by inversion 1. Qed.\n  Lemma TFun_valid_inv_args \u0393 \u03c4s \u03c4 : \u2713{\u0393} (\u03c4s ~> \u03c4) \u2192 \u2713{\u0393}* (TType <$> \u03c4s).\n  Proof. by inversion 1. Qed.\n  Lemma TFun_valid_inv_ret \u0393 \u03c4s \u03c4 : \u2713{\u0393} (\u03c4s ~> \u03c4) \u2192 \u2713{\u0393} (TType \u03c4).\n  Proof. by inversion 1. Qed.\n  Lemma TPtr_valid_inv \u0393 \u03c4p : \u2713{\u0393} (\u03c4p.*)%BT \u2192 \u2713{\u0393} \u03c4p.\n  Proof. by inversion_clear 1. Qed.\n\n  Fixpoint type_valid_dec \u0393 \u03c4 : Decision (\u2713{\u0393} \u03c4)\n  with ptr_type_valid_dec \u0393 \u03c4p : Decision (\u2713{\u0393} \u03c4p)\n  with ptr_type_valid_dec_aux \u0393 \u03c4 : Decision (\u2713{\u0393} (TType \u03c4))\n  with base_type_valid_dec \u0393 \u03c4b : Decision (\u2713{\u0393} \u03c4b).\n  Proof.\n   refine\n    match \u03c4 with\n    | baseT \u03c4b => cast_if (decide (\u2713{\u0393} \u03c4b))\n    | \u03c4.[n] => cast_if_and (decide (n \u2260 0)) (decide (\u2713{\u0393} \u03c4))\n    | compoundT{c} t => cast_if (decide (is_Some (\u0393 !! t)))\n    end; clear type_valid_dec ptr_type_valid_dec ptr_type_valid_dec_aux\n      base_type_valid_dec; abstract first [by constructor | by inversion 1].\n   refine\n    match \u03c4p with\n    | TAny => left _\n    | TType \u03c4 => cast_if (decide (\u2713{\u0393} (TType \u03c4)))\n    | \u03c4s ~> \u03c4 => cast_if_and\n       (decide (Forall (ptr_type_valid \u0393 \u2218 TType) \u03c4s)) (decide (\u2713{\u0393} (TType \u03c4)))\n    end; clear type_valid_dec ptr_type_valid_dec base_type_valid_dec\n      ptr_type_valid_dec_aux; abstract (repeat match goal with\n        | H : _ |- _ => rewrite <-Forall_fmap in H\n        end; first [done|by constructor | by inversion 1]).\n   refine\n    match \u03c4 with\n    | baseT \u03c4b => cast_if (decide (\u2713{\u0393} \u03c4b))\n    | \u03c4.[n] => cast_if_and (decide (n \u2260 0)) (decide (\u2713{\u0393} \u03c4))\n    | compoundT{_} _ => left _\n    end; clear type_valid_dec ptr_type_valid_dec base_type_valid_dec\n      ptr_type_valid_dec_aux; abstract first [by constructor | by inversion 1].\n   refine\n    match \u03c4b with\n    | \u03c4p.* => cast_if (decide (\u2713{\u0393} \u03c4p)) | _ => left _\n    end%BT; clear type_valid_dec ptr_type_valid_dec base_type_valid_dec\n      ptr_type_valid_dec_aux; abstract first [by repeat constructor | by inversion 1].\n  Defined.\n  #[global] Existing Instance type_valid_dec.\n  #[global] Existing Instance base_type_valid_dec.\n  #[global] Existing Instance ptr_type_valid_dec.\n\n  Lemma type_valid_inv \u0393 (P : Prop) \u03c4 :\n    \u2713{\u0393} \u03c4 \u2192\n    match \u03c4 with\n    | baseT \u03c4 => (\u2713{\u0393} \u03c4 \u2192 P) \u2192 P\n    | \u03c4.[n] => (\u2713{\u0393} \u03c4 \u2192 n \u2260 0 \u2192 P) \u2192 P\n    | compoundT{c} t => (is_Some (\u0393 !! t) \u2192 P) \u2192 P\n    end.\n  Proof. destruct 1; eauto. Qed.\n  Lemma type_valid_ptr_type_valid \u0393 \u03c4 : \u2713{\u0393} \u03c4 \u2192 \u2713{\u0393} (TType \u03c4).\n  Proof. by destruct 1; constructor. Qed.\n  Lemma types_valid_ptr_types_valid \u0393 \u03c4s : \u2713{\u0393}* \u03c4s \u2192 \u2713{\u0393}* (TType <$> \u03c4s).\n  Proof. induction 1; csimpl; eauto using type_valid_ptr_type_valid. Qed.\n\n  Inductive type_complete (\u0393 : env K) : type K \u2192 Prop :=\n    | TBase_complete \u03c4b : type_complete \u0393 (baseT \u03c4b)\n    | TArray_complete \u03c4 n : type_complete \u0393 (\u03c4.[n])\n    | TCompound_complete c t :\n       is_Some (\u0393 !! t) \u2192 type_complete \u0393 (compoundT{c} t).\n  Global Instance type_complete_dec \u0393 \u03c4 : Decision (type_complete \u0393 \u03c4).\n  Proof.\n   refine\n    match \u03c4 with\n    | compoundT{_} t => cast_if (decide (is_Some (\u0393 !! t))) | _ => left _\n    end; abstract first [by constructor|by inversion 1].\n  Defined.\n  Lemma type_valid_complete \u0393 \u03c4 : \u2713{\u0393} \u03c4 \u2192 type_complete \u0393 \u03c4.\n  Proof. by destruct 1; constructor. Qed.\n  Lemma type_complete_valid \u0393 \u03c4 : \u2713{\u0393} (TType \u03c4) \u2192 type_complete \u0393 \u03c4 \u2192 \u2713{\u0393} \u03c4.\n  Proof. by do 2 inversion 1; constructor. Qed.\n  Lemma types_complete_valid \u0393 \u03c4s :\n    \u2713{\u0393}* (TType <$> \u03c4s) \u2192 Forall (type_complete \u0393) \u03c4s \u2192 \u2713{\u0393}* \u03c4s.\n  Proof. induction 2; decompose_Forall; eauto using type_complete_valid. Qed.\n\n  Global Instance: PartialOrder (\u2286@{env K}).\n  Proof.\n    split; [split|].\n    * done.\n    * intros ??? [??] [??]; split; etransitivity; eauto.\n    * by intros [??] [??] [??] [??]; f_equal; eapply map_subseteq_po.\n  Qed.\n  Lemma env_wf : wf (\u2282@{env K}).\n  Proof.\n    intros [\u0393c \u0393f]; revert \u0393f. induction (map_wf \u0393c) as [\u0393c _ IH]; intros \u0393f.\n    induction (map_wf \u0393f) as [\u0393f _ IHf]; constructor; intros [\u0393c' \u0393f'] H\u0393.\n    cut (\u0393c' \u2282 \u0393c \u2228 \u0393c' = \u0393c \u2227 \u0393f' \u2282 \u0393f); [intros [?|[-> ?]]; eauto|].\n    destruct H\u0393 as [[??] H\u0393];\n      destruct (map_subseteq_inv_L \u0393c' \u0393c); simplify_equality'; auto.\n    right; repeat split; auto. by contradict H\u0393.\n  Qed.\n  Lemma lookup_compound_weaken \u03931 \u03932 t \u03c4s :\n    \u03931 !! t = Some \u03c4s \u2192 \u03931 \u2286 \u03932 \u2192 \u03932 !! t = Some \u03c4s.\n  Proof. by intros ? [??]; apply (lookup_weaken (env_t \u03931)). Qed.\n  Lemma lookup_fun_weaken \u03931 \u03932 f \u03c4s \u03c4 :\n    \u03931 !! f = Some (\u03c4s,\u03c4) \u2192 \u03931 \u2286 \u03932 \u2192 \u03932 !! f = Some (\u03c4s,\u03c4).\n  Proof. by intros ? [??]; apply (lookup_weaken (env_f \u03931)). Qed.\n  Lemma lookup_compound_weaken_is_Some \u03931 \u03932 t :\n    is_Some (\u03931 !! t) \u2192 \u03931 \u2286 \u03932 \u2192 is_Some (\u03932 !! t).\n  Proof. intros [\u03c4s ?] ?; exists \u03c4s; eauto using lookup_compound_weaken. Qed.\n  Lemma lookup_insert_compound \u0393 t \u03c4s : <[t:=\u03c4s]>\u0393 !! t = Some \u03c4s.\n  Proof. apply lookup_insert. Qed.\n  Lemma lookup_insert_compound_ne \u0393 t t' \u03c4s :\n    t \u2260 t' \u2192 <[t:=\u03c4s]>\u0393 !! t' = \u0393 !! t'.\n  Proof. apply (lookup_insert_ne (env_t \u0393)). Qed.\n  Lemma lookup_fun_compound \u0393 f \u03c4s \u03c4 : <[f:=(\u03c4s,\u03c4)]>\u0393 !! f = Some (\u03c4s,\u03c4).\n  Proof. apply lookup_insert. Qed.\n  Lemma lookup_fun_compound_ne \u0393 f f' \u03c4s \u03c4 :\n    f \u2260 f' \u2192 <[f:=(\u03c4s,\u03c4)]>\u0393 !! f' = \u0393 !! f'.\n  Proof. apply (lookup_insert_ne (env_f \u0393)). Qed.\n  Lemma insert_fun_id \u0393 f \u03c4s\u03c4 : \u0393 !! f = Some \u03c4s\u03c4 \u2192 <[f:=\u03c4s\u03c4]>\u0393 = \u0393.\n  Proof.\n    destruct \u0393; intros; unfold insert, env_insert_fun; f_equal'.\n    by apply insert_id.\n  Qed.\n  Lemma delete_compound_subseteq_compat \u03931 \u03932 t :\n    \u03931 \u2286 \u03932 \u2192 delete t \u03931 \u2286 delete t \u03932.\n  Proof. intros []; split. by apply delete_mono. done. Qed.\n  Lemma delete_compound_subseteq \u0393 t : is_Some (\u0393 !! t) \u2192 delete t \u0393 \u2286 \u0393.\n  Proof. split. apply delete_subseteq. done. Qed.\n  Lemma delete_compound_subset \u0393 t : is_Some (\u0393 !! t) \u2192 delete t \u0393 \u2282 \u0393.\n  Proof.\n    split; [by apply delete_compound_subseteq|].\n    intros [??]. by destruct (delete_subset (env_t \u0393) t).\n  Qed.\n  Lemma delete_compound_subset_alt \u0393 t \u03c4s : \u0393 !! t = Some \u03c4s \u2192 delete t \u0393 \u2282 \u0393.\n  Proof. eauto using delete_compound_subset. Qed.\n  Lemma insert_compound_subseteq \u0393 t \u03c4s : \u0393 !! t = None \u2192 \u0393 \u2286 <[t:=\u03c4s]> \u0393.\n  Proof. split. by apply insert_subseteq. done. Qed.\n  Lemma insert_fun_subseteq \u0393 f \u03c4s \u03c4 : \u0393 !! f = None \u2192 \u0393 \u2286 <[f:=(\u03c4s,\u03c4)]> \u0393.\n  Proof. split. done. by apply insert_subseteq. Qed.\n\n  Lemma type_valid_weaken_help \u03931 \u03932 \u03c4 :\n    \u2713{\u03931} \u03c4 \u2192 env_t \u03931 \u2286 env_t \u03932 \u2192 \u2713{\u03932} \u03c4\n  with ptr_type_valid_weaken_help \u03931 \u03932 \u03c4p :\n    \u2713{\u03931} \u03c4p \u2192 env_t \u03931 \u2286 env_t \u03932 \u2192 \u2713{\u03932} \u03c4p\n  with base_type_valid_weaken_help \u03931 \u03932 \u03c4b :\n    \u2713{\u03931} \u03c4b \u2192 env_t \u03931 \u2286 env_t \u03932 \u2192 \u2713{\u03932} \u03c4b.\n  Proof.\n    * unfold valid, base_type_valid, type_valid in *.\n      destruct 1; constructor; eauto.\n      eapply (lookup_weaken_is_Some (env_t _)); eauto.\n    * unfold valid, base_type_valid, type_valid, ptr_type_valid in *.\n      destruct 1; econstructor; eauto using Forall_impl.\n    * unfold valid, base_type_valid, ptr_type_valid, type_valid in *.\n      destruct 1; econstructor; eauto.\n  Qed.\n  Lemma type_valid_weaken \u03931 \u03932 \u03c4 : \u2713{\u03931} \u03c4 \u2192 \u03931 \u2286 \u03932 \u2192 \u2713{\u03932} \u03c4.\n  Proof. intros ? [??]; eapply type_valid_weaken_help; eauto. Qed.\n  Lemma ptr_type_valid_weaken \u03931 \u03932 \u03c4p : \u2713{\u03931} \u03c4p \u2192 \u03931 \u2286 \u03932 \u2192 \u2713{\u03932} \u03c4p.\n  Proof. intros ? [??]; eapply ptr_type_valid_weaken_help; eauto. Qed.\n  Lemma base_type_valid_weaken \u03931 \u03932 \u03c4b : \u2713{\u03931} \u03c4b \u2192 \u03931 \u2286 \u03932 \u2192 \u2713{\u03932} \u03c4b.\n  Proof. intros ? [??]; eapply base_type_valid_weaken_help; eauto. Qed.\n  Lemma type_valid_strict_weaken \u0393 \u03a3 \u03c4  : \u2713{\u0393} \u03c4 \u2192 \u0393 \u2282 \u03a3 \u2192 \u2713{\u03a3} \u03c4.\n  Proof. intros. eapply type_valid_weaken, strict_include; eauto. Qed.\n  Lemma types_valid_weaken \u0393 \u03a3 \u03c4s : \u2713{\u0393}* \u03c4s \u2192 \u0393 \u2286 \u03a3 \u2192 \u2713{\u03a3}* \u03c4s.\n  Proof. eauto using Forall_impl, type_valid_weaken. Qed.\n  Lemma ptr_types_valid_weaken \u0393 \u03a3 \u03c4ps : \u2713{\u0393}* \u03c4ps \u2192 \u0393 \u2286 \u03a3 \u2192 \u2713{\u03a3}* \u03c4ps.\n  Proof. eauto using Forall_impl, ptr_type_valid_weaken. Qed.\n  Lemma types_valid_strict_weaken \u0393 \u03a3 \u03c4s : \u2713{\u0393}* \u03c4s \u2192 \u0393 \u2282 \u03a3 \u2192 \u2713{\u03a3}* \u03c4s.\n  Proof. eauto using Forall_impl, type_valid_strict_weaken. Qed.\n  Lemma type_complete_weaken \u0393 \u03a3 \u03c4 : type_complete \u0393 \u03c4 \u2192 \u0393 \u2286 \u03a3 \u2192 type_complete \u03a3 \u03c4.\n  Proof.\n    intros [] [??]; constructor; eauto.\n    eapply (lookup_weaken_is_Some (env_t _)); eauto.\n  Qed.\n  Lemma types_complete_weaken \u0393 \u03a3 \u03c4s :\n    Forall (type_complete \u0393) \u03c4s \u2192 \u0393 \u2286 \u03a3 \u2192 Forall (type_complete \u03a3) \u03c4s.\n  Proof. induction 1; eauto using type_complete_weaken. Qed.\n\n  Inductive env_valid : Valid () (env K) :=\n    | env_empty_valid : \u2713 \u2205\n    | env_insert_compound_valid \u0393 t \u03c4s :\n       \u2713 \u0393 \u2192 \u2713{\u0393}* \u03c4s \u2192 \u03c4s \u2260 [] \u2192 \u0393 !! t = None \u2192 \u2713 (<[t:=\u03c4s]>\u0393)\n    | env_insert_fun_valid \u0393 f \u03c4s \u03c4 :\n       \u2713 \u0393 \u2192 \u2713{\u0393}* (TType <$> \u03c4s) \u2192 \u2713{\u0393} (TType \u03c4) \u2192\n       \u0393 !! f = None \u2192 \u2713 (<[f:=(\u03c4s,\u03c4)]>\u0393).\n  #[global] Existing Instance env_valid.\n\n  Lemma env_valid_delete \u0393 t \u03c4s :\n    \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 \u2203 \u0393', \u0393' \u2286 delete t \u0393 \u2227 \u2713{\u0393'}* \u03c4s \u2227 \u03c4s \u2260 [] \u2227 \u2713 \u0393'.\n  Proof.\n    intros H\u0393 Ht. induction H\u0393\n      as [|\u0393 t' \u03c4s' H\u0393 IH H\u03c4s' Hlen|\u0393 f \u03c4s' \u03c4' ? IH]; [done| |].\n    { destruct (decide (t = t')) as [->|].\n      { rewrite lookup_insert_compound in Ht. simplify_equality'.\n        by exists \u0393; repeat split; simpl; rewrite ?delete_insert by done. }\n      rewrite lookup_insert_compound_ne in Ht by done.\n      destruct IH as (\u0393'&?&?&?&?); auto; exists \u0393'; split_and ?; auto.\n      transitivity (delete t \u0393);\n        auto using delete_compound_subseteq_compat, insert_compound_subseteq. }\n    destruct (IH Ht) as (\u0393'&?&?&?&?). exists \u0393'; split_and ?; auto.\n    transitivity (delete t \u0393);\n      auto using delete_compound_subseteq_compat, insert_fun_subseteq.\n  Qed.\n  Lemma env_valid_lookup_subset \u0393 t \u03c4s :\n    \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 \u2203 \u0393', \u0393' \u2282 \u0393 \u2227 \u2713{\u0393'}* \u03c4s \u2227 \u03c4s \u2260 [] \u2227 \u2713 \u0393'.\n  Proof.\n    intros. destruct (env_valid_delete \u0393 t \u03c4s) as (\u0393'&?&?&?&?); auto.\n    exists \u0393'; split_and ?; auto.\n    eapply strict_transitive_r; eauto using delete_compound_subset.\n  Qed.\n  Lemma env_valid_lookup \u0393 t \u03c4s : \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393}* \u03c4s.\n  Proof.\n    intros. destruct (env_valid_lookup_subset \u0393 t \u03c4s) as (?&?&?&?);\n      eauto using types_valid_strict_weaken.\n  Qed.\n  Lemma env_valid_lookup_lookup \u0393 t \u03c4s i \u03c4 : \n    \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 \u2713{\u0393} \u03c4.\n  Proof.\n    intros ? Ht Hi. eapply Forall_lookup_1, Hi; eauto using env_valid_lookup.\n  Qed.\n  Lemma env_valid_lookup_singleton \u0393 t \u03c4 : \u2713 \u0393 \u2192 \u0393 !! t = Some [\u03c4] \u2192 \u2713{\u0393} \u03c4.\n  Proof. intros. by apply (env_valid_lookup_lookup \u0393 t [\u03c4] 0 \u03c4). Qed.\n  Lemma env_valid_fun_valid \u0393 f \u03c4s \u03c4 :\n    \u2713 \u0393 \u2192 \u0393 !! f = Some (\u03c4s,\u03c4) \u2192 \u2713{\u0393}* (TType <$> \u03c4s) \u2227 \u2713{\u0393} (TType \u03c4).\n  Proof.\n    intros H\u0393 Hf. induction H\u0393 as [| |\u0393 f' \u03c4s' \u03c4' ? IH]; [done| |].\n    { naive_solver eauto using ptr_type_valid_weaken,\n        ptr_types_valid_weaken, insert_compound_subseteq. }\n    destruct (decide (f = f')) as [->|];\n      rewrite ?lookup_fun_compound, ?lookup_fun_compound_ne in Hf by done;\n      naive_solver eauto using ptr_type_valid_weaken,\n        ptr_types_valid_weaken, insert_fun_subseteq.\n  Qed.\n  Lemma env_valid_args_valid \u0393 f \u03c4s \u03c4 :\n    \u2713 \u0393 \u2192 \u0393 !! f = Some (\u03c4s,\u03c4) \u2192 \u2713{\u0393}* (TType <$> \u03c4s).\n  Proof. eapply env_valid_fun_valid. Qed.\n  Lemma env_valid_ret_valid \u0393 f \u03c4s \u03c4 :\n    \u2713 \u0393 \u2192 \u0393 !! f = Some (\u03c4s,\u03c4) \u2192 \u2713{\u0393} (TType \u03c4).\n  Proof. eapply env_valid_fun_valid. Qed.\nEnd types.\n\n(** A very inefficient decision procedure for wellformedness of environments.\nIt checks wellformedness by trying all permutations of the environment. This\ndecision procedure is not intended to be used for computation. *)\nSection env_valid_dec.\n  Context {K : iType}.\n\n  Definition env_f_valid (\u0393 : env K) : Prop :=\n    map_Forall (\u03bb _ \u03c4s\u03c4,\n      \u2713{\u0393}* (TType <$> \u03c4s\u03c4.1) \u2227 \u2713{\u0393} (TType (\u03c4s\u03c4.2))) (env_f \u0393).\n  Inductive env_c_valid : list (tag * list (type K)) \u2192 Prop :=\n    | env_nil_valid : env_c_valid []\n    | env_cons_valid \u0393c t \u03c4s :\n       env_c_valid \u0393c \u2192 \u2713{mk_env (list_to_map \u0393c) \u2205}* \u03c4s \u2192\n       \u03c4s \u2260 [] \u2192 t \u2209 (\u0393c.*1) \u2192 env_c_valid ((t,\u03c4s) :: \u0393c).\n  Lemma env_c_valid_nodup \u0393c : env_c_valid \u0393c \u2192 NoDup (\u0393c.*1).\n  Proof. by induction 1; csimpl; constructor. Qed.\n  Global Instance env_c_valid_dec : \u2200 \u0393c, Decision (env_c_valid \u0393c).\n  Proof.\n   refine (\n    fix go \u0393c :=\n    match \u0393c return Decision (env_c_valid \u0393c) with\n    | [] => left _\n    | (s,\u03c4s) :: \u0393c => cast_if_and4\n       (decide (\u2713{mk_env (list_to_map \u0393c) \u2205}* \u03c4s))\n       (decide (\u03c4s \u2260 [])) (decide (s \u2209 \u0393c.*1)) (go \u0393c)\n    end); clear go; first [by constructor |by inversion 1].\n  Defined.\n  Lemma env_c_valid_correct \u0393 :\n    \u2713 \u0393 \u2194 env_f_valid \u0393 \u2227 \u2203 \u0393c, map_to_list (env_t \u0393) \u2261\u209a \u0393c \u2227 env_c_valid \u0393c.\n  Proof.\n    split.\n    * intros H\u0393; split.\n      { intros ? [??]; split;\n          eauto using env_valid_args_valid, env_valid_ret_valid. }\n      induction H\u0393 as [|\u0393 t \u03c4s ? (\u0393c&H\u0393&?)|\u0393 f \u03c4s \u03c4 ? (\u0393c&H\u0393&?)]; simpl; eauto.\n      { eexists []. rewrite map_to_list_empty; by repeat constructor. }\n      exists ((t,\u03c4s) :: \u0393c); split; [by rewrite map_to_list_insert, H\u0393 by done|].\n      constructor; auto.\n      { erewrite <-list_to_map_flip by eauto.\n        eauto using Forall_impl, type_valid_weaken_help. }\n      by erewrite not_elem_of_list_to_map, <-list_to_map_flip by eauto.\n    * destruct \u0393 as [\u0393c \u0393f]; simpl; intros (H\u0393f&\u0393c'&H\u0393c&H\u0393c').\n      assert (\u2713 (mk_env \u0393c \u2205)).\n      { erewrite (list_to_map_flip \u0393c) by eauto; clear \u0393c H\u0393c H\u0393f.\n        induction H\u0393c' as [|\u0393c t \u03c4s ? IH]; simpl; [by constructor|].\n        change (\u2713 (<[t:=\u03c4s]> (mk_env (list_to_map \u0393c) \u2205))); constructor; auto.\n        by apply not_elem_of_list_to_map. }\n      clear \u0393c' H\u0393c H\u0393c'. revert H\u0393f. unfold env_f_valid; simpl.\n      generalize \u0393f at 1 2; intros \u0393f'; revert \u0393f.\n      refine (map_Forall_ind _ _ _ _); [done|].\n      intros \u0393f f [\u03c4s \u03c4] ? [] ??; simpl in *.\n      change (\u2713 (<[f:=(\u03c4s,\u03c4)]> (mk_env \u0393c \u0393f)));\n        constructor; eauto using Forall_impl, ptr_type_valid_weaken_help.\n  Qed.\n  Lemma env_c_valid_correct_alt \u0393 :\n    \u2713 \u0393 \u2194\n      env_f_valid \u0393 \u2227 Exists env_c_valid (permutations (map_to_list (env_t \u0393))).\n  Proof.\n    rewrite env_c_valid_correct, Exists_exists.\n    by setoid_rewrite permutations_Permutation.\n  Qed.\n  Global Instance env_valid_dec (\u0393 : env K) : Decision (\u2713 \u0393).\n  Proof.\n   refine (cast_if (decide (env_f_valid \u0393 \u2227\n     Exists env_c_valid (permutations (map_to_list (env_t \u0393))))));\n     by rewrite env_c_valid_correct_alt.\n  Defined.\nEnd env_valid_dec.\n\n(** A nice induction principle for wellformed types. *)\nSection type_env_ind.\n  Context {K : iType} `{EqDecision K}.\n  Context (\u0393 : env K) (H\u0393 : \u2713 \u0393).\n\n  Context (P : type K \u2192 Prop).\n  Context (Pbase : \u2200 \u03c4b, \u2713{\u0393} \u03c4b \u2192 P (baseT \u03c4b)).\n  Context (Parray : \u2200 \u03c4 n, \u2713{\u0393} \u03c4 \u2192 P \u03c4 \u2192 n \u2260 0 \u2192 P (\u03c4.[n])).\n  Context (Pcompound : \u2200 c t \u03c4s,\n    \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393}* \u03c4s \u2192 Forall P \u03c4s \u2192\n    \u03c4s \u2260 [] \u2192 P (compoundT{c} t)).\n\n  Lemma type_env_ind: \u2200 \u03c4, \u2713{\u0393} \u03c4 \u2192 P \u03c4.\n  Proof.\n    cut (\u2200 \u0393' \u03c4, \u0393' \u2286 \u0393 \u2192 \u2713 \u0393' \u2192 \u2713{\u0393'} \u03c4 \u2192 P \u03c4).\n    { intros help \u03c4. by apply help. }\n    induction \u0393' as [\u0393' IH] using (well_founded_induction env_wf).\n    intros \u03c4 H\u03a3\u0393 H\u03a3 H\u03c4. induction H\u03c4 as [\u03c4b H\u03c4b|\u03c4 n H\u03c4|c t Ht].\n    * by apply Pbase, (base_type_valid_weaken \u0393').\n    * apply Parray; eauto. by apply (type_valid_weaken \u0393').\n    * inversion Ht as [\u03c4s H\u03c4s].\n      destruct (env_valid_lookup_subset \u0393' t \u03c4s) as (\u0393''&?&H\u03c4s'&Hlen&?); auto.\n      assert (\u0393'' \u2282 \u0393) by eauto using (strict_transitive_l (R:=(\u2286@{env K}))).\n      apply Pcompound with \u03c4s; eauto using lookup_compound_weaken.\n      + apply Forall_impl with (\u2713{\u0393''}); auto.\n        intros. eapply type_valid_strict_weaken; eauto.\n      + clear H\u03c4s Hlen. induction H\u03c4s'; constructor; auto.\n        apply (IH \u0393''); eauto using (strict_include (R:=(\u2286):relation (env _))).\n  Qed.\nEnd type_env_ind.\n\n(** A nice iteration principle for well-formed types. *)\nSection type_iter.\n  Context {K : iType} `{EqDecision K}.\n  Context {A : Type} (R : relation A) `{!Equivalence R}.\n  Local Infix \"\u2261\" := R.\n  Implicit Type \u03c4 : type K.\n  Implicit Type \u0393 \u03a3 : env K.\n\n  Section definition.\n    Context (fb : base_type K \u2192 A)\n      (fa : type K \u2192 nat \u2192 A \u2192 A)\n      (fc: compound_kind \u2192 tag \u2192 list (type K) \u2192 (type K \u2192 A) \u2192 A).\n\n    Definition type_iter_inner\n        (g : tag \u2192 list (type K) * (type K \u2192 A)) : type K \u2192 A :=\n      fix go \u03c4 :=\n      match \u03c4 with\n      | baseT \u03c4b => fb \u03c4b\n      | \u03c4.[n] => fa \u03c4 n (go \u03c4)\n      | compoundT{c} t => let (\u03c4s,h) := g t in fc c t \u03c4s h\n      end.\n    Definition type_iter_accF (\u0393 : env K) (go : \u2200 \u03a3, \u03a3 \u2282 \u0393 \u2192 type K \u2192 A)\n        (t : tag) : list (type K) * (type K \u2192 A) :=\n      match Some_dec (\u0393 !! t) with\n      | inleft (\u03c4s\u21beH\u03c4s) => (\u03c4s, go (delete t \u0393)\n          (delete_compound_subset_alt _ _ _ H\u03c4s))\n      | inright _ => ([], \u03bb _, fb voidT) (**i dummy *)\n      end.\n    Definition type_iter_acc : \u2200 \u0393 : env K, Acc (\u2282) \u0393 \u2192 type K \u2192 A :=\n      Fix_F _ (\u03bb \u0393 go, type_iter_inner (type_iter_accF \u0393 go)).\n    Definition type_iter (\u0393 : env K) : type K \u2192 A :=\n      type_iter_acc _ (wf_guard 32 env_wf \u0393).\n  End definition.\n\n  Lemma type_iter_acc_weaken fb1 fb2 fa1 fa2 fc1 fc2 \u0393 \u03931 \u03932 acc1 acc2 \u03c4 :\n    \u2713 \u0393 \u2192\n    (\u2200 \u03c4b, \u2713{\u0393} \u03c4b \u2192 fb1 \u03c4b \u2261 fb2 \u03c4b) \u2192\n    (\u2200 \u03c4 n x y, \u2713{\u0393} \u03c4 \u2192 x \u2261 y \u2192 fa1 \u03c4 n x \u2261 fa2 \u03c4 n y) \u2192\n    (\u2200 rec1 rec2 c t \u03c4s,\n      \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393}* \u03c4s \u2192 Forall (\u03bb \u03c4, rec1 \u03c4 \u2261 rec2 \u03c4) \u03c4s \u2192\n      fc1 c t \u03c4s rec1 \u2261 fc2 c t \u03c4s rec2) \u2192\n    \u2713{\u0393} \u03c4 \u2192 \u0393 \u2286 \u03931 \u2192 \u0393 \u2286 \u03932 \u2192\n    type_iter_acc fb1 fa1 fc1 \u03931 acc1 \u03c4 \u2261 type_iter_acc fb2 fa2 fc2 \u03932 acc2 \u03c4.\n  Proof.\n    intros H\u0393 Hbase Harray. revert \u03931 \u03932 acc1 acc2 \u03c4 H\u0393.\n    induction \u0393 as [\u0393 IH] using (well_founded_induction env_wf).\n    intros \u03931 \u03932 [acc1] [acc2] \u03c4 H\u0393 Hcompound H\u03c4 H\u03931 H\u03932. simpl.\n    induction H\u03c4 as [\u03c4 H\u03c4|\u03c4 n H\u03c4|c t [\u03c4s Ht]]; simpl; try reflexivity; auto.\n    assert (\u03931 !! t = Some \u03c4s) by eauto using lookup_compound_weaken.\n    assert (\u03932 !! t = Some \u03c4s) by eauto using lookup_compound_weaken.\n    unfold type_iter_accF.\n    destruct (Some_dec (\u03931 !! t)) as [[\u03c4s1 Ht1]|?],\n      (Some_dec (\u03932 !! t)) as [[\u03c4s2 Ht2]|?]; simplify_equality'.\n    generalize (acc1 _ (delete_compound_subset_alt \u03931 t \u03c4s1 Ht1)),\n      (acc2 _ (delete_compound_subset_alt \u03932 t \u03c4s1 Ht2)); intros acc1' acc2'.\n    destruct (env_valid_delete \u0393 t \u03c4s1) as (\u0393'&?&H\u03c4s&Hlen&?); trivial.\n    assert (\u0393' \u2286 \u0393).\n    { transitivity (delete t \u0393); eauto using delete_compound_subseteq. }\n    apply Hcompound; eauto using types_valid_weaken.\n    assert (is_Some (\u0393 !! t)) by eauto. clear Ht Ht1 Ht2 Hlen acc1 acc2.\n    induction H\u03c4s as [|\u03c4 \u03c4s]; constructor; auto. apply (IH \u0393').\n    * eauto using (strict_transitive_r (R:=(\u2286@{env K}))),\n        delete_compound_subset, lookup_compound_weaken_is_Some.\n    * eauto using base_type_valid_weaken.\n    * eauto using type_valid_weaken.\n    * done.\n    * eauto using lookup_compound_weaken, types_valid_weaken.\n    * done.\n    * transitivity (delete t \u0393); eauto using delete_compound_subseteq_compat.\n    * transitivity (delete t \u0393); eauto using delete_compound_subseteq_compat.\n  Qed.\n  Lemma type_iter_weaken fb1 fb2 fa1 fa2 fc1 fc2 \u0393 \u03a3 \u03c4 :\n    \u2713 \u0393 \u2192\n    (\u2200 \u03c4b, \u2713{\u0393} \u03c4b \u2192 fb1 \u03c4b \u2261 fb2 \u03c4b) \u2192\n    (\u2200 \u03c4 n x y, \u2713{\u0393} \u03c4 \u2192 x \u2261 y \u2192 fa1 \u03c4 n x \u2261 fa2 \u03c4 n y) \u2192\n    (\u2200 rec1 rec2 c t \u03c4s,\n      \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393}* \u03c4s \u2192 Forall (\u03bb \u03c4, rec1 \u03c4 \u2261 rec2 \u03c4) \u03c4s \u2192\n      fc1 c t \u03c4s rec1 \u2261 fc2 c t \u03c4s rec2) \u2192\n    \u2713{\u0393} \u03c4 \u2192 \u0393 \u2286 \u03a3 \u2192\n    type_iter fb1 fa1 fc1 \u0393 \u03c4 \u2261 type_iter fb2 fa2 fc2 \u03a3 \u03c4.\n  Proof. intros. by apply (type_iter_acc_weaken _ _ _ _ _ _ \u0393). Qed.\n\n  Lemma type_iter_base fb fa fc \u0393 \u03c4b : type_iter fb fa fc \u0393 (baseT \u03c4b) = fb \u03c4b.\n  Proof. done. Qed.\n  Lemma type_iter_array fb fa fc \u0393 \u03c4 n :\n    type_iter fb fa fc \u0393 (\u03c4.[n]) = fa \u03c4 n (type_iter fb fa fc \u0393 \u03c4).\n  Proof. unfold type_iter. by destruct (wf_guard _ env_wf \u0393). Qed.\n  Lemma type_iter_compound fb fa fc \u0393 c t \u03c4s :\n    \u2713 \u0393 \u2192 (\u2200 \u03c4 n x y, \u2713{\u0393} \u03c4 \u2192 x \u2261 y \u2192 fa \u03c4 n x \u2261 fa \u03c4 n y) \u2192\n    (\u2200 rec1 rec2 c t \u03c4s,\n      \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393}* \u03c4s \u2192 Forall (\u03bb \u03c4, rec1 \u03c4 \u2261 rec2 \u03c4) \u03c4s \u2192\n      fc c t \u03c4s rec1 \u2261 fc c t \u03c4s rec2) \u2192\n    \u0393 !! t = Some \u03c4s \u2192\n    type_iter fb fa fc \u0393 (compoundT{c} t) \u2261 fc c t \u03c4s (type_iter fb fa fc \u0393).\n  Proof.\n    intros ? Harray Hcompound Ht. unfold type_iter at 1.\n    destruct (wf_guard _ env_wf \u0393) as [acc\u0393]. simpl.\n    unfold type_iter_accF.\n    destruct (Some_dec (\u0393 !! t)) as [[\u03c4s' Ht']|?]; [|congruence].\n    generalize (acc\u0393 _ (delete_compound_subset_alt \u0393 t \u03c4s' Ht')). intros acc\u0393'.\n    simplify_map_eq.\n    destruct (env_valid_delete \u0393 t \u03c4s) as (\u0393'&?&H\u03c4s&Hlen&?); trivial.\n    assert (\u0393' \u2286 \u0393).\n    { transitivity (delete t \u0393); eauto using delete_compound_subseteq. }\n    apply Hcompound; eauto using types_valid_weaken.\n    clear Ht Hlen. induction H\u03c4s; constructor; auto.\n    by apply (type_iter_acc_weaken _ _ _ _ _ _ \u0393');\n      eauto using lookup_compound_weaken, type_valid_weaken, types_valid_weaken.\n  Qed.\n  Lemma type_iter_compound_None fb fa fc \u0393 c t :\n    \u0393 !! t = None \u2192\n    type_iter fb fa fc \u0393 (compoundT{c} t) = fc c t [] (\u03bb _, fb voidT%BT).\n  Proof.\n    intros Ht. unfold type_iter.\n    destruct (wf_guard _ env_wf \u0393) as [acc\u0393]; simpl.\n    unfold type_iter_accF. destruct (Some_dec _) as [[??]|?]; congruence.\n  Qed.\nEnd type_iter.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/types/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.1942242441387029}}
{"text": "Require Import Coqlib.                                                              \nRequire Import Maps.            \nRequire Import LibTactics.   \n        \nRequire Import Integers.  \nOpen Scope Z_scope.        \nImport ListNotations.  \n   \nSet Asymmetric Patterns.  \n        \nRequire Import state.    \nRequire Import language.  \n \nSet Implicit Arguments.    \nUnset Strict Implicit. \n               \nRequire Import logic.\n    \nRequire Import lemmas.\nRequire Import lemmas_ins.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import integer_lemma.\n\nRequire Import sep_lemma.\nRequire Import reg_lemma.\nRequire Import derived_rule.\n\nRequire Import tm_dly_lemma.\n\nRequire Import code.\nRequire Import ctxswitch_spec.\n\nRequire Import lemma1.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\n(*+ Lemmas +*)\nLemma neq_rev_still :\n  forall {A : Type} (a b : A),\n    a <> b ->\n    b <> a.\nProof.\n  intros.\n  intro.\n  symmetry in H0.\n  tryfalse.\nQed.\n\nLemma rotate_hold_post_id_neq_oid :\n  forall oid id vi i,\n    $ 0 <=\u1d64\u1d62 oid <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 vi <=\u1d64\u1d62 $ 7 ->\n    rotate oid id vi i -> post_cwp id <> vi ->\n    post_cwp id <> oid.\nProof.\n  intros.\n  inversion H2; subst.\n  eapply post_1_neq; eauto.\n\n  inversion H4; subst.\n  eapply post_2_neq; eauto.\n\n  inversion H7; subst.\n  eapply post_3_neq; eauto.\n\n  inversion H10; subst.\n  eapply post_4_neq; eauto.\n\n  inversion H13; subst.\n  eapply post_5_neq; eauto.\n\n  clear H2 H4 H7 H10 H13.\n  inversion H16; subst.\n  eapply post_6_neq; eauto.\n\n  inversion H2; subst.\n  eapply post_7_eq; eauto.\n\n  inversion H10; subst.\n  { \n    clear - H H1 H13 H4 H17 H14 H11 H8 H5 H3.\n    eapply post_cwp_step_limit_8 with (id := id0) (vi := vi) in H; eauto.\n    do 7 (destruct H as [a | H]; [subst; tryfalse | idtac]).\n    subst; tryfalse.\n  }\n  { \n    intro.  \n    clear - H1 H22 H13 H4 H17 H14 H11 H8 H5 H3 H21.\n    eapply post_cwp_step_limit_8 with (id := id) (vi := vi) in H1; eauto.\n    do 7 (destruct H1 as [a | H1]; [subst; tryfalse | idtac]).\n    subst; tryfalse.\n  }\nQed.\n\n(*+ Lemma for stack frame relation +*)\n\nLemma stack_frame_match_fm_save :\n  forall fm F oid id cl clfp1 clfp2 cstk,\n    $ 0 <=\u1d64\u1d62 oid <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 -> ostk_lfp_rl cstk cl clfp1 clfp2 ->\n    stack_frame_match oid clfp1 (F ++ fm :: nil) id -> length F = 13 ->\n    stack_frame_save (F ++ fm :: nil) (cl, clfp1 ++ clfp2)\n                     cstk oid (post_cwp id).\nProof.\n  intros.\n  destruct cstk.\n  unfolds ostk_lfp_rl.\n  simpljoin1.\n  unfold stack_frame_save.\n  split; eauto.\n  do 14 (try destruct F; simpl in H3; tryfalse).\n  simpl in H2.\n  \n  inversion H2; subst.\n  {\n    destruct x; tryfalse.\n    simpl.\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; tryfalse.\n  destruct p.\n  inversion H11; subst.\n  {\n    simpl. \n    eapply frame_save_cons; eauto.\n    eapply post_cons_neq_still; eauto.\n    destruct x; simpl in H4; tryfalse.\n    simpl.\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H13; subst.\n  {\n    destruct x; simpl in H4; tryfalse.\n    simpl.\n    do 2 (eapply frame_save_cons; [solve_post_neq | idtac]).\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H15; subst.\n  {\n    simpl.\n    do 2 (eapply frame_save_cons; [solve_post_neq | idtac]).\n    eapply post_cons_neq_still_rev; eauto.\n    eapply frame_save_cons; [solve_post_neq | idtac].\n    destruct x; simpl in H4; tryfalse.\n    simpl.\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H17; subst.\n  {\n    simpl.\n    destruct x; simpl in H4; tryfalse.\n    do 3 (eapply frame_save_cons; [solve_post_neq | idtac];\n          try eapply post_cons_neq_still_rev; eauto).\n    eapply post_cons_neq_still_rev; eauto.\n    eapply frame_save_cons; [solve_post_neq | idtac].\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H19; subst.\n  {\n    destruct x; simpl in H4; tryfalse.\n    do 4 (eapply frame_save_cons; [solve_post_neq | idtac];\n          do 2 (try eapply post_cons_neq_still_rev; eauto)).\n    eapply post_cons_neq_still_rev; eauto.\n    eapply frame_save_cons; [solve_post_neq | idtac];\n      do 2 (try eapply post_cons_neq_still_rev; eauto).\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H21; subst.\n  {\n    destruct x; simpl in H4; tryfalse.\n    simpl.\n    do 6 (try eapply frame_save_cons; [solve_post_neq | idtac];\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply frame_save_end; eauto.\n  }\n\n  destruct x; simpl in H4; tryfalse.\n  destruct p.\n  inversion H23; subst.\n  {\n    destruct x; simpl in H4; tryfalse.\n    simpl.\n    do 7 (try eapply frame_save_cons; [solve_post_neq | idtac];\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply frame_save_end; eauto.\n  }\nQed.\n\nLemma stk_fm_match_stk_len_lt_13 :\n  forall oid clfp F id,\n    $ 0 <=\u1d64\u1d62 oid <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 ->\n    stack_frame_match oid clfp F id -> length F = 14 ->\n    length clfp < 8.\nProof.\n  intros.\n  do 15 (destruct F; simpl in H2; tryfalse).\n  \n  inversion H1; subst; simpl; try omega.\n  inversion H10; subst; simpl; try omega.\n  inversion H12; subst; simpl; try omega.\n  inversion H14; subst; simpl; try omega.\n  inversion H16; subst; simpl; try omega.\n  inversion H18; subst; simpl; try omega.\n  inversion H20; subst; simpl; try omega.\n  inversion H22; subst; simpl; try omega.\nQed.\n\nInductive frame_restore1 : Word -> FrameList -> Word -> FrameList -> Prop :=\n| restore_end1 : forall F id, frame_restore1 id F id F\n| restore_cons1 :\n    forall F F' id vi fm1 fm2,\n      id <> vi ->\n      $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 -> frame_restore1 (post_cwp id) (F' ++ fm1 :: fm2 :: nil) vi F -> \n      frame_restore1 id (fm1 :: fm2 :: F') vi F.\n\nLemma frame_restore_restore1_eq :\n  forall F F' id vi,\n    length F = 16 -> length F' = 16 ->\n    $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 vi <=\u1d64\u1d62 $ 7 ->\n    frame_restore id F vi F' ->\n    frame_restore1 id F vi F'.\nProof.\n  intros.\n  do 17 (try destruct F; simpl in H; tryfalse).\n  do 17 (try destruct F'; simpl in H0; tryfalse).\n  clear H H0.\n\n  (** step0 *)\n  inversion H3; subst.\n  {\n    eapply restore_end1; eauto.\n  }\n\n  (** step1 *)\n  clear H3.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H3.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H3; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H3.\n  inversion H8; subst.\n  {\n    simpl.\n    eapply restore_cons1; eauto.\n    eapply restore_end1; eauto.\n  }\n\n  (** step2 *)\n  clear H8.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H6.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H6; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H6.\n  inversion H10; subst.\n  {\n    do 2 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step3 *)\n  clear H10.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H8.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H8; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H8.\n  inversion H12; subst.\n  {\n    do 3 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step4 *)\n  clear H12.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H10.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H10; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H10.\n  inversion H14; subst.\n  {\n    do 4 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step5 *)\n  clear H14.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H12.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H12; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H12.\n  inversion H16; subst.\n  {\n    do 5 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step 6 *)\n  clear H16.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H14.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H14; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H14.\n  inversion H18; subst.\n  {\n    do 6 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step 7 *)\n  clear H18.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H16.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H16; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H16.\n  inversion H20; subst.\n  {\n    do 7 (eapply restore_cons1; try solve_post_neq;\n          repeat (eapply post_cons_neq_still_rev; eauto)).\n    eapply restore_end1; eauto.\n  }\n\n  (** step 8 *)\n  clear H20.\n  assert (length F' = 14).\n  {\n    assert (length (F' ++ fm1 :: fm2 :: nil) = 16).\n    rewrite H; simpl; eauto.\n    rewrite app_length in H18.\n    simpls; omega.\n  }\n  do 15 (try destruct F'; simpl in H18; tryfalse).\n  simpl in H.\n  inversion H; subst.\n  clear H H18.\n  inversion H22; subst.\n  {\n    clear - H0 H1.\n    rewrite post_8_eq in H0; tryfalse.\n    eauto.\n  }\n  clear - H1 H19 H18 H16 H14 H12 H10 H8 H6 H3.\n  eapply post_cwp_step_limit_8 in H1; eauto.\n  do 7 (destruct H1 as [a | H1]; [subst; tryfalse | idtac]).\n  subst; tryfalse.\nQed.\n\nLtac post_nth_neq :=\n  eapply neq_rev_still; try eapply post_1_neq; try eapply post_2_neq;\n  try eapply post_3_neq; try eapply post_4_neq; try eapply post_5_neq;\n  try eapply post_6_neq; try eapply post_7_eq; solve_post_inrange.\n\nLemma stk_fm_match_cons_tail_stable :\n  forall F F' oid id lfp fmo fmo' fml fml' fmi fmi' fm1 fm2,\n    post_cwp id <> oid -> $ 0 <=\u1d64\u1d62 oid <=\u1d64\u1d62 $ 7 -> $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 ->\n    length F = 13 -> length F' = 11 ->\n    stack_frame_match oid lfp (F ++ fmo :: nil) id ->\n    frame_restore oid (fmo :: fml :: fmi :: F) id\n                  (fmo' :: fml' :: fmi' :: fm1 :: fm2 :: F') ->\n    stack_frame_match oid (lfp ++ (fm1, fm2) :: nil) (F ++ fmo :: nil) (post_cwp id).\nProof.\n  introv Hpost_cwp_neq.\n  intros.\n  do 14 (destruct F; simpl in H1; tryfalse).\n  do 12 (destruct F'; simpl in H2; tryfalse).\n  clear H1 H2.\n\n  simpl in H3.\n  eapply frame_restore_restore1_eq in H4; eauto.\n\n  (** step0 *)\n  inversion H3; subst.\n  {\n    inversion H4; subst; tryfalse.\n    simpl.\n    eapply match_cons; eauto; try solve_post_neq.\n    eapply match_end; eauto.\n  }\n\n  (** step1 *)\n  clear H3.\n  inversion H4; subst; tryfalse.\n  clear H4.\n  inversion H10; subst.\n  {\n    inversion H12; subst; tryfalse.\n    simpl.\n    do 2 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step2 *)\n  clear H10.\n  inversion H12; subst; tryfalse.\n  clear H12.\n  inversion H13; subst.\n  {\n    simpl in H15.\n    inversion H15; subst; tryfalse.\n    simpl.\n    do 3 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step3 *)\n  clear H13.\n  inversion H15; subst; tryfalse.\n  clear H15.\n  inversion H16; subst.\n  {\n    simpl in H18.\n    inversion H18; subst; tryfalse.\n    simpl.\n    do 4 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step4 *)\n  clear H16.\n  inversion H18; subst; tryfalse.\n  clear H18.\n  inversion H19; subst.\n  {\n    simpl in H21.\n    inversion H21; subst; tryfalse.\n    simpl.\n    do 5 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step5 *)\n  clear H19.\n  inversion H21; subst; tryfalse.\n  clear H21.\n  inversion H22; subst.\n  {\n    simpl in H24.\n    inversion H24; subst; tryfalse.\n    simpl.\n    do 6 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step6 *)\n  clear H22.\n  inversion H24; subst; tryfalse.\n  clear H24.\n  inversion H25; subst.\n  {\n    simpl in H27.\n    inversion H27; subst; tryfalse.\n    simpl.\n    do 7 (eapply match_cons; eauto; try post_nth_neq).\n    eapply match_end; eauto.\n  }\n\n  (** step7 *)\n  clear H25.\n  inversion H27; subst; tryfalse.\n  clear H27.  \n  inversion H28; subst.\n  {\n    simpl in H30.\n    inversion H30; subst; tryfalse.\n    simpl.\n    rewrite post_8_eq in Hpost_cwp_neq; eauto.\n    tryfalse.\n  }\nQed.\n\nLemma stk_fm_contraint_fm_app_stable :\n  forall l id F lfp vi F',\n    stack_frame_constraint' l id F lfp vi ->\n    stack_frame_constraint' l id (F ++ F') lfp vi.\nProof.\n  intros.\n  generalize dependent F'.\n  induction H; intros.\n  -\n    eapply frame_invalid; eauto.\n  -\n    eapply frame_valid; eauto.\nQed.\n  \n(*+ Lemmas for Space +*)\nLemma stack'_split :\n  forall lfp1 lfp2 l s p,\n    length lfp1 < 100 ->\n    s |= stack' l (lfp1 ++ lfp2) ** p ->\n    s |= stack' l lfp1 ** stack' (l -\u1d62 ($ (64 * Z.of_nat (length lfp1)))) lfp2 ** p.\nProof.\n  intro lfp1.\n  induction lfp1; intros.\n  -\n    simpl stack' in H0.\n    simpl stack'.\n    eapply astar_emp_intro_l; eauto.\n    rewrite Int.sub_zero_l; eauto.\n  -\n    destruct a.\n    simpl stack' in H0.\n    simpl stack' at 1.\n    eapply astar_assoc_elim in H0.\n    eapply astar_assoc_intro.\n    sep_cancel1 1 1.\n    eapply IHlfp1 in H1; eauto.\n    sep_cancel1 1 1.\n    simpl length.\n    rewrite Nat2Z.inj_succ.\n    unfold Z.succ.\n    do 2 rewrite Int.sub_add_opp in H0.\n    rewrite Int.sub_add_opp.\n    rewrite Int.add_assoc in H0.\n    rewrite <- Int.neg_add_distr in H0.\n    remember (length lfp1) as lenlfp1.\n    assert (($ 64) +\u1d62 ($ (64 * Z.of_nat lenlfp1)) = $ (64 * (Z.of_nat lenlfp1 + 1))).\n    {\n      rewrite Int.add_unsigned.\n      assert (Int.unsigned $ 64 = 64%Z).\n      eauto.\n      rewrite H1; eauto.\n      rewrite Int.unsigned_repr; eauto.\n      assert ((64 * (Z.of_nat lenlfp1 + 1) = 64 + 64 * Z.of_nat lenlfp1)%Z).\n      omega.\n      rewrite H2.\n      eauto.\n      subst lenlfp1.\n      clear - H.\n      simpl in H.\n      unfold Int.max_unsigned, Int.modulus.\n      unfold two_power_nat.\n      simpl shift_nat.\n      omega.\n    }\n    rewrite H1 in H0.\n    eauto.\n    simpl in H.\n    omega.\nQed.\n\nLemma stack'_cons_tail :\n  forall lfp l s p fm1 fm2,\n    length lfp < 100 ->\n    s |= stack' l lfp ** stack_frame (l -\u1d62 ($ (64 * Z.of_nat (length lfp)))) fm1 fm2 ** p ->\n    s |= stack' l (lfp ++ (fm1, fm2) :: nil) ** p.\nProof.\n  intro lfp.\n  induction lfp; intros.\n  -\n    simpl stack' in *.\n    simpl length in *.\n    eapply astar_assoc_intro; eauto.\n    assert ((64 * Z.of_nat 0 = 0)%Z).\n    simpl. eauto.\n    rewrite H1 in H0.\n    rewrite Int.sub_zero_l in H0.\n    sep_cancel1 2 1.\n    eauto.\n  -\n    destruct a.\n    simpl length in H0.\n    simpl stack' in *.\n    eapply astar_assoc_elim in H0.\n    eapply astar_assoc_intro; eauto.\n    sep_cancel1 1 1.\n    eapply IHlfp; eauto.\n    simpl in H; omega.\n    rewrite Nat2Z.inj_succ in H1.\n    unfold Z.succ in H1.\n    sep_cancel1 1 1.\n    rewrite Int.sub_add_opp in H0.\n    do 2 rewrite Int.sub_add_opp.\n    rewrite Int.add_assoc.\n    rewrite <- Int.neg_add_distr.\n    assert (($ 64) +\u1d62 ($ (64 * Z.of_nat (length lfp))) =\n            $ (64 * (Z.of_nat (length lfp) + 1))).\n    {\n      rewrite Int.add_unsigned; eauto.\n      assert (Int.unsigned $ 64 = 64%Z).\n      eauto.\n      rewrite H1.\n      rewrite Int.unsigned_repr; eauto.\n      assert ((64 * (Z.of_nat (length lfp) + 1) = 64 + 64 * Z.of_nat (length lfp))%Z).\n      omega.\n      rewrite H2.\n      eauto.\n      unfolds Int.max_unsigned, Int.modulus, two_power_nat.\n      simpl shift_nat.\n      simpl in H.\n      omega.\n    }\n    rewrite H1.\n    eauto.\nQed.\n  \n(*+ Proof +*)\nTheorem Ta0SaveUsedWindowsProof :\n  forall vl,\n    spec |- {{ ta0_save_usedwindows_pre vl }}\n             ta0_save_usedwindows\n           {{ ta0_save_usedwindows_post vl }}.\nProof.\n  intros.\n  unfold ta0_save_usedwindows_pre.\n  unfold ta0_save_usedwindows_post.\n  hoare_ex_intro_pre.   \n  renames x'0 to fmg', x'2 to fmo', x'4 to fml', x'6 to fmi'.\n  renames x'8 to id, x'12 to vi, x'10 to F', x'11 to vy.\n  renames x'24 to vz, x'25 to vn, x'15 to ct, x'21 to nt, x'13 to ll.\n  renames x'16 to cctx, x'20 to cstk, x'17 to cl, x'18 to clfp1, x'19 to clfp2.\n  renames x'22 to nctx, x'23 to nstk.\n  renames x'7 to oid, x'1 to fmo, x'3 to fml, x'5 to fmi, x'9 to F, x'14 to i.\n\n  eapply Pure_intro_rule.\n  introv Hlgvl.\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hnctx.\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hstk_fm_match.\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hfm_restore.\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hstk_fm_constraint.\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hg4.\n  destruct Hg4 as [Hg4 [Hrot [Hoid_range [Hg4_vl Hg7] ] ] ].\n  hoare_lift_pre 15.\n  eapply Pure_intro_rule.\n  introv Hctx_win_save.\n  \n  unfold ta0_save_usedwindows.\n \n  destruct fmg', fmo', fml', fmi'.\n  \n  (** sll g4 1 g5 *)\n  hoare_lift_pre 2.\n  eapply backward_rule.\n  introv Hs.\n  eapply Regs_Global_combine_GenRegs in Hs; eauto.\n  eapply seq_rule; eauto.\n  TimReduce_simpl.\n  eapply sll_rule_reg; eauto.\n  simpl; eauto.\n  rewrite in_range1; eauto.\n  simpl upd_genreg.\n  rewrite get_range_0_4_stable; eauto.\n\n  (** srl g4 (OS_WINDOWS - 1) g4 *)\n  unfold OS_WINDOWS.\n  assert (Heq7 : ($ 8) -\u1d62 ($ 1) = ($ 7)).\n  eauto.\n  rewrite Heq7; eauto.\n  eapply seq_rule; eauto.\n  TimReduce_simpl.\n  eapply srl_rule_reg; eauto.\n  simpl; eauto.\n  rewrite in_range7; eauto.\n  simpl upd_genreg.\n  \n  simpl in Hg4.\n  inversion Hg4; subst.\n  rewrite get_range_0_4_stable; eauto.\n\n  (** or g4 g5 g4 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply or_rule_reg; eauto.\n  simpl; eauto.\n  simpl upd_genreg.\n\n  (** andcc g4 g7 g0 *)\n  hoare_lift_pre 4.\n  hoare_lift_pre 5.\n  hoare_lift_pre 3.\n  eapply seq_rule; eauto.\n  TimReduce_simpl.\n  eapply andcc_rule_reg; eauto.\n  simpl; eauto.\n  simpl upd_genreg.\n  simpl get_genreg_val; eauto.\n\n  (** bne Ta0_Task_Switch_NewContext; nop *)\n  simpl in Hg7.\n  destruct Hg7 as [Hg7 Hct_not_null].\n  inversion Hg7; subst.\n  eapply hoare_pure_gen' with (pu := $ 0 <=\u1d64\u1d62 id <=\u1d64\u1d62 $ 7 /\\ $ 0 <=\u1d64\u1d62 vi <=\u1d64\u1d62 $ 7).\n  {\n    introv Hs.\n    simpl_sep_liftn_in Hs 4.\n    unfold FrameState in Hs.\n    asrt_to_line_in Hs 3.\n    simpl_sep_liftn_in Hs 4.\n    eapply sep_pure_l_elim in Hs; eauto.\n    simpljoin1; eauto.\n  }\n  eapply Pure_intro_rule.\n  introv Hid_inrange.\n  destruct Hid_inrange as [Hid_inrange Hvi_inrange].\n  \n  assert (Hiszero : iszero ((i >>\u1d62 ($ 7)) |\u1d62 (i <<\u1d62 ($ 1))) &\u1d62 (($ 1) <<\u1d62 vi) =\n          iszero (get_range 0 7 (i >>\u1d62 ($ 7)) |\u1d62 (i <<\u1d62 ($ 1))) &\u1d62 (($ 1) <<\u1d62 vi)).\n  {\n    rewrite in_range_0_7_and; eauto.\n  }\n  rewrite Hiszero.\n  rewrite g4_val_get_range_0_7_equal with (id := id); eauto.\n  \n  eapply Bne_rule; eauto.\n  {\n    eval_spec.\n  }\n  {\n    TimReduce_simpl.\n    eapply nop_rule; eauto.\n  }\n  {\n    TimReduce_simpl.\n    introv Hs.\n    sep_cancel1 3 1.\n    simpl; eauto.\n  }\n\n  Focus 3.\n  introv Hnxt_invalid.\n  unfold iszero in Hnxt_invalid.\n  destruct (Int.eq_dec (($ 1) <<\u1d62 (post_cwp id)) &\u1d62 (($ 1) <<\u1d62 vi) $ 0); tryfalse.\n  clear Hnxt_invalid.\n  renames n to Hnxt_invalid.\n  eapply and_not_zero_eq in Hnxt_invalid; eauto.\n \n  split.\n   \n    introv Hs.\n    unfold ta0_task_switch_newcontext_pre.\n    sep_ex_intro.\n    asrt_to_line 14.\n    eapply sep_pure_l_intro; eauto.\n    simpl_sep_liftn 2.\n    eapply GenRegs_split_Regs_Global.\n    sep_cancel1 1 1.\n    sep_cancel1 3 1.\n    sep_cancel1 3 1.\n    sep_cancel1 1 2.\n    do 5 sep_cancel1 1 1.\n    sep_cancel1 3 1.\n    sep_cancel1 3 1.\n    eapply sep_pure_l_intro; eauto.\n    eapply sep_pure_l_intro; eauto.\n \n    introv Hs.\n    destruct Hctx_win_save as [Hctx_win_save [Hctx_pt_stk Hostk_lfp] ].\n    unfold ta0_task_switch_newcontext_post in Hs.\n    sep_ex_elim_in Hs.\n    asrt_to_line_in Hs 13.\n    eapply sep_pure_l_elim in Hs.\n    destruct Hs as [Hlgvl1 Hs].\n    symmetry in Hlgvl1.\n    inversion Hlgvl1; subst.\n    sep_ex_intro.   \n    eapply sep_pure_l_intro; eauto. \n    do 10 sep_cancel1 1 1.\n    sep_cancel1 4 1.\n    sep_cancel1 4 1.  \n    eapply sep_pure_l_intro; eauto.\n    do 2 sep_cancel1 1 1.\n    clear - Hostk_lfp.\n    unfolds ostk_lfp_rl.\n    destruct cstk.\n    simpljoin1.\n    simpls; eauto.\n    sep_cancel1 1 1.\n    sep_cancel1 1 1.\n    eapply sep_pure_l_intro; eauto.\n    introv Hct.\n    split; eauto.\n    split; eauto.\n    eapply stack_frame_match_fm_save; eauto.\n    simpljoin1; eauto.\n    simpljoin1; eauto.\n    eapply astar_emp_elim_r; eauto.\n    eapply in_range_0_7_post_cwp_still; eauto.\n\n  introv Hnjp.\n  clear Hiszero Heq7.\n  assert (Hlen_clfp1 : length clfp1 < 8).\n  {\n    destruct Hstk_fm_match as [Hstk_fm_match Hlen_F].\n    eapply stk_fm_match_stk_len_lt_13 with (id := id) (oid := oid); eauto.\n    rewrite app_length; eauto.\n    simpl; omega.\n  }\n\n  unfold iszero in Hnjp.\n  destruct (Int.eq_dec (($ 1) <<\u1d62 (post_cwp id)) &\u1d62 (($ 1) <<\u1d62 vi) $ 0); tryfalse.\n  renames e to Hneq.\n  eapply and_zero_not_eq in Hneq; eauto.\n  inversion Hstk_fm_constraint; tryfalse; subst.\n  match goal with\n  | H1 : stack_frame_constraint' _ (post_cwp id) _ _ _,\n         H2 : get_frame_nth _ 6 = Some (get_stk_addr _), H3 : _ = get_stk_cont _  |- _ =>\n    renames H1 to Hstk_fm_constraint1, H2 to Hpt_stk, H3 to Hlfp\n  end.\n  simpl in Hlfp.\n  subst clfp2.\n  renames lfp to clfp2.\n  simpl get_frame_nth in Hpt_stk.\n  unfold get_stk_addr in Hpt_stk.\n  unfold get_stk_addr in Hstk_fm_constraint1.\n  assert (Hval_sp : w29 = cl -\u1d62 ($ (64 * Z.of_nat (length clfp1)))).\n  {\n    inversion Hpt_stk; subst; eauto.\n  }\n\n  (** restore *)\n  hoare_lift_pre 4.\n  unfold FrameState at 1.\n  eapply backward_rule.\n  introv Hs.\n  asrt_to_line_in Hs 3.\n  simpl_sep_liftn_in Hs 4.\n  eapply sep_pure_l_elim in Hs.\n  destruct Hs as [_ Hs].\n  eauto.\n  hoare_lift_pre 3.\n  eapply Pure_intro_rule.\n  introv Hlen_F'.\n  hoare_lift_pre 2.\n  hoare_lift_pre 3.\n  do 2 (destruct F'; simpl in Hlen_F'; tryfalse).\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply restore_rule_reg; eauto.\n  simpl; eauto.\n  unfold win_masked.\n  destruct (((($ 1) <<\u1d62 (post_cwp id)) &\u1d62 (($ 1) <<\u1d62 vi)) !=\u1d62 ($ 0)) eqn:Heqe; tryfalse; eauto.\n  unfold negb in Heqe.\n  destruct (((($ 1) <<\u1d62 (post_cwp id)) &\u1d62 (($ 1) <<\u1d62 vi)) =\u1d62 ($ 0)) eqn:Heqe1; tryfalse.\n  eapply int_eq_false_neq in Heqe1; eauto.\n  eapply and_not_zero_eq in Heqe1; tryfalse.\n  eapply in_range_0_7_post_cwp_still; eauto.\n  eauto. \n  simpl upd_genreg.\n  subst w29.\n\n  hoare_lift_pre 12.\n  unfold stack at 1.\n  eapply backward_rule.\n  introv Hs.\n  eapply stack'_split in Hs.\n  simpl_sep_liftn_in Hs 2.\n  unfold stack' in Hs; fold stack' in Hs.\n  eapply astar_assoc_elim in Hs; eauto.\n  omega.\n\n  destruct fml', fmi'.\n  destruct f, f0.\n  hoare_lift_pre 4.\n\n  (** st l0 (sp + OS_CPU_STACK_FRSME_L0_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l0; eauto.\n  simpl update_frame.\n\n  (** st l1 (sp + OS_CPU_STACK_FRSME_L1_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l1; eauto.\n  simpl update_frame.\n\n  (** st l2 (sp + OS_CPU_STACK_FRSME_L2_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l2; eauto.\n  simpl update_frame.\n\n  (** st l3 (sp + OS_CPU_STACK_FRSME_L3_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l3; eauto.\n  simpl update_frame.\n\n  (** st l4 (sp + OS_CPU_STACK_FRSME_L4_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l4; eauto.\n  simpl update_frame.\n\n  (** st l5 (sp + OS_CPU_STACK_FRSME_L5_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l5; eauto.\n  simpl update_frame.\n\n  (** st l6 (sp + OS_CPU_STACK_FRSME_L6_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l6; eauto.\n  simpl update_frame.\n\n  (** st l7 (sp + OS_CPU_STACK_FRSME_L7_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_l7; eauto.\n  simpl update_frame.\n\n  (** st i0 (sp + OS_CPU_STACK_FRSME_I0_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i0; eauto.\n  simpl update_frame.\n\n  (** st i1 (sp + OS_CPU_STACK_FRSME_I1_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i1; eauto.\n  simpl update_frame.\n\n  (** st i2 (sp + OS_CPU_STACK_FRSME_I2_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i2; eauto.\n  simpl update_frame.\n\n  (** st i3 (sp + OS_CPU_STACK_FRSME_i3_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i3; eauto.\n  simpl update_frame.\n\n  (** st i4 (sp + OS_CPU_STACK_FRSME_I4_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i4; eauto.\n  simpl update_frame.\n\n  (** st i5 (sp + OS_CPU_STACK_FRSME_I5_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i5; eauto.\n  simpl update_frame.\n\n  (** st i6 (sp + OS_CPU_STACK_FRSME_I6_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i6; eauto.\n  simpl update_frame.\n\n  (** st i7 (sp + OS_CPU_STACK_FRSME_I7_OFFSET) *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply st_rule_save_stk_i7; eauto.\n  simpl update_frame.\n \n  hoare_lift_pre 5.\n  hoare_lift_pre 6.\n  eapply backward_rule.\n  introv Hs.\n  eapply FrameState_combine in Hs; eauto.\n  clear - Hlen_F'.\n  rewrite app_length; simpl; omega.\n  split; eauto.\n  eapply in_range_0_7_post_cwp_still; eauto.\n\n  (** jmpl Ta0_save_usedwindows g0; nop *)\n  eapply J1_rule; eauto.\n  {\n    TimReduce_simpl.\n    introv Hs.\n    simpl.\n    unfold Ta0_save_usedwindows at 1 2.\n    unfold Ta0_save_usedwindows at 1 2.\n    rewrite in_range228; eauto.\n  }\n  {\n    eval_spec.\n  }\n  {\n    TimReduce_simpl.\n    introv Hs.\n    simpl_sep_liftn_in Hs 2.\n    eapply GenRegs_split_one with (rr := g0) in Hs; eauto.\n  }\n  {\n    TimReduce_simpl.\n    eapply nop_rule; eauto.\n    introv Hs.\n    eapply GenRegs_upd_combine_one in Hs; eauto.\n    remember (cl -\u1d62 ($ (64 * Z.of_nat (length clfp1)))) as w29'.\n    simpl upd_genreg in Hs.\n    subst w29'.\n    unfold ta0_save_usedwindows_pre.\n    sep_ex_intro.\n    asrt_to_line 20.\n    eapply sep_pure_l_intro; eauto.\n    simpl_sep_liftn 2.\n    eapply GenRegs_split_Regs_Global. \n    sep_cancel1 1 1.\n    sep_cancel1 1 1.\n    sep_cancel1 6 1.\n    sep_cancel1 5 1.\n    sep_cancel1 4 1.\n    do 5 sep_cancel1 4 1.\n    sep_cancel1 4 2.\n    sep_cancel1 4 2.\n    match goal with\n    | H : _ |= _ |- _ => renames H to Hs\n    end.\n\n    assert (Harth : (cl -\u1d62 ($ (64 * Z.of_nat (length clfp1)))) -\u1d62 ($ 64) =\n                      cl -\u1d62 ($ (64 * Z.of_nat (length clfp1 + 1)))).\n    {\n      repeat (rewrite Int.sub_add_opp).\n      rewrite Int.add_assoc.\n      rewrite <- Int.neg_add_distr.\n      assert (Htrivil : ($ (64 * Z.of_nat (length clfp1))) +\u1d62 ($ 64) =\n                        $ (64 * Z.of_nat (length clfp1 + 1))).\n      rewrite Int.add_unsigned.\n      assert (Heq64 : Int.unsigned $ 64 = 64%Z).\n      eauto.\n      rewrite Heq64.\n      rewrite Int.unsigned_repr.\n      assert (Htrivil_eq : length clfp1 + 1 = S (length clfp1)).\n      omega.\n      rewrite Htrivil_eq.\n      rewrite Nat2Z.inj_succ.\n      unfold Z.succ.\n      rewrite <- Zred_factor4.\n      eauto.\n      clear - Hlen_clfp1.\n      unfold Int.max_unsigned, Int.modulus, two_power_nat.\n      simpl shift_nat.\n      omega.\n      rewrite Htrivil.\n      eauto.\n    }\n    \n    simpl_sep_liftn_in Hs 3.\n    eapply stack'_cons_tail in Hs; eauto.\n    eapply stack'_app in Hs; eauto.\n    sep_cancel1 1 1.\n    instantiate (1 := Aemp).\n    eapply astar_emp_intro_r; eauto.\n\n    eapply sep_pure_l_intro; eauto.\n \n    eapply sep_pure_l_intro.\n    {\n      instantiate (1 := F).\n      instantiate (1 := fmo).\n      instantiate (1 := oid).\n      destruct Hstk_fm_match as [Hstk_fm_match Hlen_F].\n      split; eauto.\n      eapply stk_fm_match_cons_tail_stable; eauto.\n      eapply rotate_hold_post_id_neq_oid; eauto.\n      omega.\n    }\n    \n    eapply sep_pure_l_intro.\n    {\n      instantiate (1 := fmi).\n      instantiate (1 := fml).\n      do 3 rewrite trivial_assoc_ls.\n      eapply restore_cons; eauto.\n      eapply rotate_hold_post_id_neq_oid; eauto.\n    }\n\n    eapply sep_pure_l_intro.\n    {\n      rewrite app_length.\n      simpl length.\n      rewrite Harth in Hstk_fm_constraint1.\n      unfold stack_frame_constraint.\n      unfold get_stk_addr.\n      unfold get_stk_cont.\n      remember (cl -\u1d62 ($ (64 * Z.of_nat (length clfp1 + 1)))) as offset.\n      simpl in Hstk_fm_constraint1.\n      do 3 rewrite trivial_assoc_ls.\n      assert\n        (Htrivial : \n          (([[w44, w45, w46, w47, w48, w49, w50, w51]])\n             :: (([[w52, w53, w54, w55, w56, w57, w58, w59]]) :: F') ++\n             ([[w7, w8, w9, w10, w11, w12, w13, w14]]) ::\n             ([[w15, w16, w17, w18, w19, w20, w21, w22]]) :: nil) =\n          (([[w44, w45, w46, w47, w48, w49, w50, w51]])\n            :: ([[w52, w53, w54, w55, w56, w57, w58, w59]]) :: F' ++\n          ([[w7, w8, w9, w10, w11, w12, w13, w14]]) :: nil) ++\n          ([[w15, w16, w17, w18, w19, w20, w21, w22]]) :: nil  \n        ).\n      rewrite trivial_assoc_ls2.\n      eauto.\n      rewrite Htrivial.\n      rewrite <- app_assoc.\n      eapply stk_fm_contraint_fm_app_stable; eauto.\n    }\n\n    instantiate (1 := Aemp).\n    eapply sep_pure_l_intro; eauto.\n    simpl get_frame_nth.\n    split; eauto.\n    split.\n    eapply rotate_cons; eauto.\n    split; eauto.\n    split.\n    eapply g4_rot_stable with (oid := oid); eauto.\n    split; eauto.\n\n    eapply sep_pure_l_intro; eauto.\n    split; eauto.\n    simpljoin1; eauto.\n    instantiate (1 := cstk).\n    clear - Hctx_win_save.\n    destruct Hctx_win_save as [_ Hctx_pt_stk].\n    unfolds ctx_pt_stk.\n    simpls. \n    destruct Hctx_pt_stk as [ [Hstk_len_gt_zero Hpt] Hostk_lfp_rl ].\n    split; eauto.\n    try rewrite app_length in *.\n    rewrite app_length.\n    simpls.\n    simpljoin1.\n    split; eauto.\n    omega.\n\n    clear - Hostk_lfp_rl.\n    unfolds ostk_lfp_rl.\n    destruct cstk.\n    simpljoin1.\n    exists (x ++ ([[w3, w6, w29, w31, w32, w33, w34, w35]],\n             [[w36, w37, w38, w39, w40, w41, w42, w43]]) :: nil).\n    repeat (split; eauto).\n    rewrite <- app_assoc.\n    simpl; eauto.\n\n    match goal with\n    | H : length clfp1 = length _ |- _ =>\n      renames H to Hlen_clfp1\n    end.\n    clear - Hlen_clfp1.\n    repeat rewrite app_length.\n    simpl.\n    rewrite Hlen_clfp1; eauto.\n\n    clear - Hlen_clfp1.\n    rewrite app_length.\n    simpl.\n    assert (Htrivial : length clfp1 + 1 + 0 = S (length clfp1)).\n    omega.\n    rewrite Htrivial.\n    rewrite Nat2Z.inj_succ.\n    unfold Z.succ.\n    omega.\n\n    rewrite Harth.\n    rewrite app_length.\n    simpl length.\n    assert (Htrivial : length clfp1 + 1 + 0 = length clfp1 + 1).\n    eauto.\n    rewrite Htrivial.\n    eauto.\n    omega.\n  }\n  {\n    introv Hs.\n    unfold ta0_save_usedwindows_post in Hs.\n    sep_ex_elim_in Hs.\n    asrt_to_line_in Hs 17.\n    sep_ex_intro.\n    do 17 sep_cancel1 1 1.\n    eapply astar_emp_elim_r; eauto.\n  }\n\n  DlyFrameFree_elim.\n  eapply in_range_0_7_post_cwp_still; eauto.\n  DlyFrameFree_elim.\nQed.", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/contextswitch/proof/SaveUsedWindows.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.19419806165129533}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Object Primitives                                      *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AuxStateDataType.\nRequire Import FlatMemory.\nRequire Import AbstractDataType.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Constant.\nRequire Import RealParams.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\nRequire Import ASTExtra.\nRequire Import ObjVMM.\nRequire Import ObjThread.\nRequire Import ObjFlatMem.\nRequire Import Observation.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import AuxLemma.\nRequire Import GlobIdent.\nRequire Import LAsmModuleSemAux.\n\nSection OBJ_SyncIPC.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** primitive: get the i-th sync_channel's count **)\n  Function get_sync_chan_count_spec (i: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid _ _ c => Some (Int.unsigned c)\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function get_sync_chan_to_spec (i: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid to _ _ => Some (Int.unsigned to)\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function get_sync_chan_paddr_spec (i: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid _ vaddr _ => Some (Int.unsigned vaddr)\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function set_sync_chan_count_spec (i count: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid t v _\n                => Some (adt {syncchpool: ZMap.set i (SyncChanValid t v (Int.repr count)) \n                                          (syncchpool adt)})\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function set_sync_chan_to_spec (i to: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid _ v c\n                => Some (adt {syncchpool: ZMap.set i (SyncChanValid (Int.repr to) v c) \n                                          (syncchpool adt)})\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function set_sync_chan_paddr_spec (i vaddr: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid t _ c\n                => Some (adt {syncchpool: ZMap.set i (SyncChanValid t (Int.repr vaddr) c) \n                                          (syncchpool adt)})\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function init_sync_chan_spec (i : Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          Some adt {syncchpool: \n                      ZMap.set i (SyncChanValid (Int.repr num_chan) (Int.repr 0) (Int.repr 0)) (syncchpool adt)}\n        else None\n      | _ => None\n    end.\n\n  Function is_pid_sending_to_spec (i to: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 i num_chan then\n          match ZMap.get i (syncchpool adt) with\n            | SyncChanValid t _ _ \n              => if Int.eq t (Int.repr to) then Some 1 else Some 0\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\n  Function syncsendto_chan_post_spec (adt : RData) : option (RData * Z) :=\n    match (pg adt, ikern adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        match ZMap.get (cid adt) (syncchpool adt) with\n          | SyncChanValid to paddr count =>\n            if zeq (Int.unsigned to) num_chan then\n              Some (adt, (Int.unsigned count))\n            else\n              let adt' := adt{syncchpool : \n                                ZMap.set (cid adt) \n                                         (SyncChanValid (Int.repr num_chan) paddr count) (syncchpool adt)} in\n                  Some (adt', 1024+3)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function get_kernel_pa_spec (pid vaddr : Z) (adt : RData) : option Z :=\n    match pg adt with\n      | true => match ptRead_spec pid vaddr adt with\n                  | Some paddr =>\n                    if zeq paddr 0 then None else Some (paddr / PgSize * PgSize + (vaddr mod PgSize))\n                  | _ => None\n                end\n      | _ => None\n    end.\n\n  Function syncsendto_chan_pre_spec (chid vaddr scount : Z) (adt : RData) : option (RData * Z) := \n    match (pg adt, ikern adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 chid num_proc then\n          match ZMap.get chid (abtcb adt) with\n            | AbTCBValid st _ => \n              if ThreadState_dec st DEAD then\n                Some (adt, 1024+2)\n              else\n                match ZMap.get (cid adt) (syncchpool adt) with\n                  | SyncChanValid to _ _ =>\n                    match get_kernel_pa_spec (cid adt) vaddr adt with\n                      | Some skpa =>\n                        if zle_le 0 skpa Int.max_unsigned then\n                           if zeq (Int.unsigned to) 64 then\n                             let asendval := Z.min (scount) (1024) in\n                             let adt' := adt {syncchpool : \n                                                ZMap.set (cid adt) \n                                                         (SyncChanValid (Int.repr chid) (Int.repr skpa) (Int.repr asendval))\n                                                         (syncchpool adt)} in\n                             Some (adt', (cid adt))\n                           else\n                             None\n                        else None\n                      | _ => None\n                    end\n                  | _ => None\n                end\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n  \n  Function syncreceive_chan_spec (fromid vaddr rcount : Z) (adt : RData) : option (RData * Z) :=\n    match (pg adt, ikern adt, ihost adt, ipt adt) with\n      | (true, true, true, true) =>\n        if zle_lt 0 fromid num_proc then\n          match ZMap.get fromid (abtcb adt) with\n            | AbTCBValid st _ => \n              if ThreadState_dec st DEAD then            \n                Some (adt, 1024+2)\n              else\n                match ZMap.get fromid (syncchpool adt) with\n                  | SyncChanValid to spaddr scount =>\n                    if zeq (Int.unsigned to) (cid adt) then\n                      let arecvcount := Z.min (Int.unsigned scount) rcount in\n                      match get_kernel_pa_spec (cid adt) vaddr adt with\n                        | Some rbuffpa =>\n                          match flatmem_copy_spec arecvcount (Int.unsigned spaddr) rbuffpa adt with\n                            | Some adt1 =>\n                              let adt2 := adt1 \n                                            {syncchpool : ZMap.set fromid (SyncChanValid (Int.repr num_chan) Int.zero \n                                                                                         (Int.repr arecvcount)) (syncchpool adt1)} in\n                              match thread_wakeup_spec fromid adt2 with\n                                | Some adt3 => Some (adt3, arecvcount)\n                                | _ => None\n                              end\n                            | _ => None\n                          end\n                        | _ => None\n                      end\n                    else\n                      Some (adt, 1024+3)\n                  | _ => None\n                end\n            | _ => None\n          end\n        else None\n      | _ => None\n    end.\n\nEnd OBJ_SyncIPC.\n\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  Local Open Scope Z_scope.\n\n  Section IS_PID_SENDING_TO.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_syncchpool}.\n    Context {re3: relate_impl_ipt}.\n\n    Lemma is_pid_sending_to_exist:\n      forall s pid to habd labd z f,\n        is_pid_sending_to_spec pid to habd = Some z\n        -> relate_AbData s f habd labd\n        -> is_pid_sending_to_spec pid to labd = Some z.\n    Proof.\n      unfold is_pid_sending_to_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n    Qed.\n\n    Lemma is_pid_sending_to_sim:\n      forall id,\n        sim (crel RData RData) (id \u21a6 gensem is_pid_sending_to_spec)\n                               (id \u21a6 gensem is_pid_sending_to_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData).\n      match_external_states_simpl.\n      erewrite is_pid_sending_to_exist; eauto. reflexivity.\n    Qed.\n\n  End IS_PID_SENDING_TO.\n\n  Section GET_SYNC_CHAN_TO.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re5: relate_impl_syncchpool}.\n\n    Lemma get_sync_chan_to_exist:\n      forall s f habd labd chid to,\n      get_sync_chan_to_spec chid habd = Some to\n      -> relate_AbData s f habd labd\n      -> get_sync_chan_to_spec chid labd = Some to.\n    Proof.\n      unfold get_sync_chan_to_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n    Qed.\n      \n  End GET_SYNC_CHAN_TO.\n\n  Section GET_SYNC_CHAN_COUNT.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re5: relate_impl_syncchpool}.\n\n    Lemma get_sync_chan_count_exist:\n      forall s f habd labd chid count,\n      get_sync_chan_count_spec chid habd = Some count\n      -> relate_AbData s f habd labd\n      -> get_sync_chan_count_spec chid labd = Some count.\n    Proof.\n      unfold get_sync_chan_count_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n    Qed.\n      \n  End GET_SYNC_CHAN_COUNT.\n\n  Section SET_SYNC_CHAN_TO.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re5: relate_impl_syncchpool}.\n\n    Lemma set_sync_chan_to_exist:\n      forall s f habd habd' labd chid to,\n        set_sync_chan_to_spec chid to habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', set_sync_chan_to_spec chid to labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold set_sync_chan_to_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n      subdestruct; inv HQ; try (refine_split'; trivial; fail).\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      subrewrite'. refine_split'; trivial.      \n      eapply relate_impl_syncchpool_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) set_sync_chan_to_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) set_sync_chan_to_spec}.\n\n  End SET_SYNC_CHAN_TO.\n\n  Section SET_SYNC_CHAN_PADDR.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re5: relate_impl_syncchpool}.\n\n    Lemma set_sync_chan_paddr_exist:\n      forall s f habd habd' labd chid vaddr,\n      set_sync_chan_paddr_spec chid vaddr habd = Some habd'\n      -> relate_AbData s f habd labd\n      -> exists labd', set_sync_chan_paddr_spec chid vaddr labd = Some labd'\n                       /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold set_sync_chan_paddr_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n      subdestruct; inv HQ; try (refine_split'; trivial; fail).\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      subrewrite'. refine_split'; trivial.      \n      eapply relate_impl_syncchpool_update. assumption.\n    Qed.\n      \n    Context {inv: PreservesInvariants (HD:= data) set_sync_chan_paddr_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) set_sync_chan_paddr_spec}.\n\n  End SET_SYNC_CHAN_PADDR.\n\n  Section GET_KERNEL_PA.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_PT}.\n    Context {re4: relate_impl_ptpool}.\n    Context {re5: relate_impl_init}.\n\n    Lemma get_kernel_pa_exist:\n      forall s f habd labd va chid pa,\n      get_kernel_pa_spec chid va habd = Some pa\n      -> relate_AbData s f habd labd\n      -> get_kernel_pa_spec chid va labd = Some pa.\n    Proof.\n      unfold get_kernel_pa_spec in *; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_PT_eq; eauto.\n      exploit relate_impl_ptpool_eq; eauto.\n      exploit relate_impl_init_eq; eauto. intros.\n\n      revert H; subrewrite.\n      subdestruct; inv HQ.\n      erewrite ptRead_exist; eauto.\n      rewrite Hdestruct1; auto.\n    Qed.\n\n  End GET_KERNEL_PA.\n\n  Section SET_SYNC_CHAN_COUNT.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re5: relate_impl_syncchpool}.\n\n    Lemma set_sync_chan_count_exist:\n      forall s f habd habd' labd chid count,\n      set_sync_chan_count_spec chid count habd = Some habd'\n      -> relate_AbData s f habd labd\n      -> exists labd', set_sync_chan_count_spec chid count labd = Some labd'\n                       /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold set_sync_chan_count_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H; subrewrite.\n      subdestruct; inv HQ; try (refine_split'; trivial; fail).\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      subrewrite'. refine_split'; trivial.      \n      eapply relate_impl_syncchpool_update. assumption.\n    Qed.\n  \n    Context {inv: PreservesInvariants (HD:= data) set_sync_chan_count_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) set_sync_chan_count_spec}.\n\n  End SET_SYNC_CHAN_COUNT.\n\n  Section SYNCSENDTO_CHAN.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_abtcb}.\n    Context {re4: relate_impl_cid}.\n    Context {re5: relate_impl_syncchpool}.\n    Context {re8: relate_impl_abq}.\n    Context {re12: relate_impl_init}.\n    Context {re7: relate_impl_PT}.\n    Context {re9: relate_impl_ptpool}.\n    \n    Lemma syncsendto_chan_pre_exist:\n      forall s f habd habd' labd chid vaddr count i,\n        syncsendto_chan_pre_spec chid vaddr count habd = Some (habd', i)\n        -> relate_AbData s f habd labd\n        -> exists labd', syncsendto_chan_pre_spec chid vaddr count labd = Some (labd', i)\n                         /\\ relate_AbData s f habd' labd'.\n\n    Proof.\n      unfold syncsendto_chan_pre_spec. intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_abtcb_eq; eauto.\n      exploit relate_impl_cid_eq; eauto.\n      exploit relate_impl_abq_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n      revert H. subrewrite.\n      subdestruct; inv HQ;\n      refine_split'; trivial.\n      - erewrite get_kernel_pa_exist; eauto.\n        rewrite Hdestruct9.\n        reflexivity.\n      - eapply relate_impl_syncchpool_update. assumption.\n    Qed.\n\n    Lemma syncsendto_chan_post_exist:\n      forall s f habd habd' labd i,\n        syncsendto_chan_post_spec habd = Some (habd', i)\n        -> relate_AbData s f habd labd\n        -> exists labd', syncsendto_chan_post_spec labd = Some (labd', i)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold syncsendto_chan_post_spec. intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_abtcb_eq; eauto.\n      exploit relate_impl_cid_eq; eauto.\n      exploit relate_impl_abq_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n\n      revert H. subrewrite.\n      subdestruct; inv HQ;\n      refine_split'; trivial.      \n      eapply relate_impl_syncchpool_update. assumption.\n    Qed.\n\n    Context {re13: match_impl_syncchpool}.\n\n    Lemma syncsendto_chan_pre_match:\n      forall s d d' m chid vaddr count i f,\n        syncsendto_chan_pre_spec chid vaddr count d = Some (d', i)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold syncsendto_chan_pre_spec; intros.\n      subdestruct; inv H; trivial.\n      eapply match_impl_syncchpool_update. assumption.\n    Qed.\n\n    Lemma syncsendto_chan_post_match:\n      forall s d d' m i f,\n        syncsendto_chan_post_spec d = Some (d', i)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold syncsendto_chan_post_spec; intros.\n      subdestruct; inv H; trivial.\n      eapply match_impl_syncchpool_update. assumption.\n    Qed.\n\n    Section PRE.\n      \n      Context {inv: PreservesInvariants (HD:= data) syncsendto_chan_pre_spec}.\n      Context {inv0: PreservesInvariants (HD:= data0) syncsendto_chan_pre_spec}.\n\n      Lemma syncsendto_chan_pre_sim :\n        forall id,\n          sim (crel RData RData) (id \u21a6 gensem syncsendto_chan_pre_spec)\n              (id \u21a6 gensem syncsendto_chan_pre_spec).\n      Proof.\n        intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n        exploit syncsendto_chan_pre_exist; eauto 1; intros [labd' [HP HM]].\n        match_external_states_simpl.\n        eapply syncsendto_chan_pre_match; eauto.\n      Qed.\n\n    End PRE.\n\n    Section POST.\n\n      Context {inv1: PreservesInvariants (HD:= data) syncsendto_chan_post_spec}.\n      Context {inv2: PreservesInvariants (HD:= data0) syncsendto_chan_post_spec}.\n\n      Lemma syncsendto_chan_post_sim :\n        forall id,\n          sim (crel RData RData) (id \u21a6 gensem syncsendto_chan_post_spec)\n              (id \u21a6 gensem syncsendto_chan_post_spec).\n      Proof.\n        intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n        exploit syncsendto_chan_post_exist; eauto 1; intros [labd' [HP HM]].\n        match_external_states_simpl.\n        eapply syncsendto_chan_post_match; eauto.\n      Qed.\n\n    End POST.\n\n  End SYNCSENDTO_CHAN.\n\n  Section SYNCRECEIVE_CHAN.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_abtcb}.\n    Context {re4: relate_impl_cid}.\n    Context {re5: relate_impl_syncchpool}.\n    Context {re8: relate_impl_abq}.\n    Context {re9: relate_impl_PT}.\n    Context {re10: relate_impl_ptpool}.\n    Context {re11: relate_impl_init}.\n    Context {re12: relate_impl_HP}.\n    Context {re13: relate_impl_pperm}.\n\n    Lemma syncreceive_chan_exist:\n    forall s f habd habd' labd fromid vaddr count i,\n      syncreceive_chan_spec fromid vaddr count habd = Some (habd', i)\n      -> relate_AbData s f habd labd\n      -> exists labd', syncreceive_chan_spec fromid vaddr count labd = Some (labd', i)\n                       /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold syncreceive_chan_spec. intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_abtcb_eq; eauto.\n      exploit relate_impl_cid_eq; eauto.\n      exploit relate_impl_abq_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto; intros.\n\n      revert H. subrewrite;\n      subdestruct; inv HQ;\n      try (refine_split'; trivial; fail).\n      erewrite get_kernel_pa_exist; eauto.\n      exploit flatmem_copy_exist; eauto.\n      intros (labd' & Hmemcpy2 & Hmemcpy3).\n      rewrite Hmemcpy2.\n      exploit thread_wakeup_exist; eauto.\n      eapply relate_impl_syncchpool_update. \n      instantiate (1:=labd').\n      instantiate (1:=f).\n      instantiate (1:=s).\n      assumption.\n\n      intros (labd'1 & Htwakeup2 & Htwakeup3).\n      eapply relate_impl_syncchpool_eq in Hmemcpy3.\n      rewrite Hmemcpy3 in Htwakeup2.\n      rewrite Htwakeup2.\n      refine_split'; trivial.\n    Qed.\n\n    Context {mt14: match_impl_abtcb}.\n    Context {mt15: match_impl_abq}.\n    Context {mt16: match_impl_syncchpool}.\n    Context {mt1: match_impl_HP}.\n\n    Lemma syncreceive_chan_match:\n      forall s d d' m i f fromid rvaddr count,\n      syncreceive_chan_spec fromid rvaddr count d = Some (d', i)\n      -> match_AbData s d m f\n      -> match_AbData s d' m f.\n    Proof.\n      unfold syncreceive_chan_spec; intros.\n      subdestruct; inv H; trivial;\n      eapply thread_wakeup_match; eauto;\n      eapply match_impl_syncchpool_update; \n      eapply flatmem_copy_match; eauto.\n    Qed.\n\n    Context {inv1: PreservesInvariants (HD:= data) syncreceive_chan_spec}.\n    Context {inv2: PreservesInvariants (HD:= data0) syncreceive_chan_spec}.\n\n    Lemma syncreceive_chan_sim:\n      forall id,\n        sim (crel RData RData) (id \u21a6 gensem syncreceive_chan_spec)\n            (id \u21a6 gensem syncreceive_chan_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData).\n      exploit syncreceive_chan_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply syncreceive_chan_match; eauto.\n    Qed.\n\n  End SYNCRECEIVE_CHAN.\n\nEnd OBJ_SIM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjSyncIPC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.19406870057818684}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Relational specification of expression simplification. *)\n\nRequire Import Coqlib (* Maps  *)Errors Integers Floats.\nRequire Import AST Linking Memory.\nRequire Import Ctypes Cop Csyntax Clight SimplExpr.\nRequire Import MoSel.\nImport Maps.PTree.\nExport weakestpre_gensym.\n\nSection SPEC.\n\n  Local Open Scope gensym_monad_scope.\n  Notation \"a ! b\" := (get b a) (at level 1).\n  (** * Relational specification of the translation. *)\n\n  (** ** Translation of expressions *)\n\n  (** This specification covers:\n- all cases of [transl_lvalue] and [transl_rvalue];\n- two additional cases for [Csyntax.Eparen], so that reductions of [Csyntax.Econdition]\n  expressions are properly tracked;\n- three additional cases allowing [Csyntax.Eval v] C expressions to match\n  any Clight expression [a] that evaluates to [v] in any environment\n  matching the given temporary environment [le].\n   *)\n\n  Ltac tac2 :=\n    match goal with\n    | |- bi_emp_valid ({{ _ }} bind2 _ (fun _ _ => _) {{ _, RET _; _ }}) =>\n      eapply bind_spec; intros; tac2\n    | _ => tac\n    end.\n  \n  Notation \"\\s l\" := (\u2203 t, l \u21a6 t) (at level 10).\n  Definition final (dst: destination) (a: expr) : list statement :=\n    match dst with\n    | For_val => nil\n    | For_effects => nil\n    | For_set sd => do_set sd a\n    end.\n\n  Definition dest_below (dst: destination) : iProp :=\n    match dst with\n    | For_set sd => \\s (sd_temp sd)\n    | _ => \\\u231cTrue\u231d\n    end.\n\n  (** Iris version *)\n  Definition tr_rvalof (ty : type) (e1 : expr) (lse : list statement * expr) : iProp :=\n    if type_is_volatile ty\n    then\n      (\u2203 t, \\\u231c lse = (make_set t e1 :: nil ,Etempvar t ty)\u231d \u2217 t \u21a6 ty )%I\n    else\n      \\\u231clse = (nil,e1)\u231d%I.\n\n  Fixpoint tr_expr (le : temp_env) (dst : destination) (e : Csyntax.expr)\n           (sla : list statement * expr) : iProp := \u231c True \u231d \u2217\n    match e with\n    | Csyntax.Evar id ty =>\n      dest_below dst \u2217\n                 \\\u231c sla = (final dst (Evar id ty),Evar id ty) \u231d\n    | Csyntax.Ederef e1 ty =>\n      \u2203 sla2, tr_expr le For_val e1 sla2 \u2217\n                      dest_below dst \u2217\n                      \\\u231csla = (sla2.1 ++ final dst (Ederef' sla2.2 ty),Ederef' sla2.2 ty)\u231d\n| Csyntax.Efield e1 f ty =>\n  \u2203 sla2, tr_expr le For_val e1 sla2 \u2217\n                  dest_below dst \u2217\n                  \\\u231c sla = (sla2.1 ++ final dst (Efield sla2.2 f ty),Efield sla2.2 f ty) \u231d\n\n| Csyntax.Eval v ty =>\n  match dst with\n  | For_effects => \u231csla.1 = nil\u231d\n  | For_val =>\n    (\u2200 tge e le' m, (\u2200 id, \\s id -\u2217 \u231c le'!id = le!id \u231d) -\u2217 \u231c eval_expr tge e le' m sla.2 v \u231d) \u2217 \u231c typeof sla.2 = ty /\\ sla.1 = nil \u231d\n  | For_set sd => \u2203 a,\n    (\u2200 tge e le' m, (\u2200 id, \\s id -\u2217 \u231c le'!id = le!id \u231d) -\u2217 \u231c eval_expr tge e le' m a v \u231d) \u2217 \u231c typeof a = ty /\\ sla.1 = do_set sd a \u231d\n  end\n| Csyntax.Esizeof ty' ty =>\n  dest_below dst \u2217\n             \\\u231c sla = (final dst (Esizeof ty' ty), Esizeof ty' ty)\u231d\n| Csyntax.Ealignof ty' ty =>\n  dest_below dst \u2217\n             \\\u231c sla = (final dst (Ealignof ty' ty), Ealignof ty' ty) \u231d\n| Csyntax.Evalof e1 ty =>\n  \u2203 sla2 sl3, tr_expr le For_val e1 sla2  \u2217\n                      tr_rvalof (Csyntax.typeof e1) sla2.2 (sl3,sla.2)  \u2217\n                      dest_below dst \u2217\n                      \\\u231c sla.1 = (sla2.1 ++ sl3 ++ final dst sla.2) \u231d\n| Csyntax.Eaddrof e1 ty =>\n  \u2203 sla2, tr_expr le For_val e1 sla2  \u2217\n                  dest_below dst \u2217\n                  \\\u231c sla = (sla2.1 ++ final dst (Eaddrof' sla2.2 ty), Eaddrof' sla2.2 ty) \u231d\n| Csyntax.Eunop ope e1 ty =>\n  \u2203 sla2, tr_expr le For_val e1 sla2  \u2217\n                  dest_below dst \u2217\n                  \\\u231c sla = (sla2.1 ++ final dst (Eunop ope sla2.2 ty), Eunop ope sla2.2 ty) \u231d\n| Csyntax.Ebinop ope e1 e2 ty =>\n  \u2203 sla2 sla3, tr_expr le For_val e1 sla2  \u2217\n                       tr_expr le For_val e2 sla3  \u2217\n                       dest_below dst \u2217\n                       \\\u231c sla = (sla2.1 ++ sla3.1 ++ final dst (Ebinop ope sla2.2 sla3.2 ty), Ebinop ope sla2.2 sla3.2 ty) \u231d\n| Csyntax.Ecast e1 ty =>\n  \u2203 sla2, tr_expr le For_val e1 sla2  \u2217\n                  dest_below dst \u2217\n                  \\\u231c sla = (sla2.1 ++ final dst (Ecast sla2.2 ty), Ecast sla2.2 ty ) \u231d\n| Csyntax.Eseqand e1 e2 ty =>\n  match dst with\n  | For_val =>\n    \u2203 sla2 sla3 t, tr_expr le For_val e1 sla2  \u2217\n                           (\\s t -\u2217 tr_expr le (For_set (sd_seqbool_val t ty)) e2 sla3)  \u2217\n                           \\s t \u2217\n                           \\\u231c sla = (sla2.1 ++ makeif sla2.2 (makeseq sla3.1) (Sset t (Econst_int Int.zero ty)) :: nil, Etempvar t ty ) \u231d\n| For_effects =>\n  \u2203 sla2 sla3, tr_expr le For_val e1 sla2  \u2217\n                       tr_expr le For_effects e2 sla3  \u2217\n                       \\\u231c  sla.1 = sla2.1 ++ makeif sla2.2 (makeseq sla3.1) Sskip :: nil \u231d\n| For_set sd =>\n  \u2203 sla2 sla3, tr_expr le For_val e1 sla2  \u2217\n                       (\\s (sd_temp sd) -\u2217 tr_expr le (For_set (sd_seqbool_set ty sd)) e2 sla3)  \u2217\n                       \\s (sd_temp sd)  \u2217\n                       \u231c sla.1 = sla2.1 ++ makeif sla2.2 (makeseq sla3.1) (makeseq (do_set sd (Econst_int Int.zero ty))) :: nil \u231d\n  end\n| Csyntax.Eseqor e1 e2 ty =>\n  match dst with\n  | For_val =>\n    \u2203 sla2 sla3 t, tr_expr le For_val e1 sla2  \u2217\n                           (\\s t -\u2217 tr_expr le (For_set (sd_seqbool_val t ty)) e2 sla3)  \u2217\n                           \\s t \u2217\n                           \\\u231c sla = (sla2.1 ++ makeif sla2.2 (Sset t (Econst_int Int.one ty)) (makeseq sla3.1) :: nil, Etempvar t ty) \u231d\n| For_effects =>\n  \u2203 sla2 sla3, tr_expr le For_val e1 sla2  \u2217\n                       tr_expr le For_effects e2 sla3  \u2217\n                       \\\u231c sla.1 = sla2.1 ++ makeif sla2.2 Sskip (makeseq sla3.1) :: nil \u231d\n| For_set sd =>\n  \u2203 sla2 sla3, tr_expr le For_val e1 sla2  \u2217\n                       (\\s (sd_temp sd) -\u2217 tr_expr le (For_set (sd_seqbool_set ty sd)) e2 sla3)  \u2217\n                       \\s (sd_temp sd)  \u2217\n                       \u231c sla.1 = sla2.1 ++ makeif sla2.2 (makeseq (do_set sd (Econst_int Int.one ty))) (makeseq sla3.1) :: nil \u231d\n  end\n\n| Csyntax.Econdition e1 e2 e3 ty =>\n  match dst with\n  | For_val =>\n    \u2203 sla2 sla3 sla4 t,\n    tr_expr le For_val e1 sla2 \u2217\n    \\s t \u2217\n    (\\s t -\u2217 (tr_expr le (For_set (SDbase ty ty t)) e2 sla3 \u2227\n    tr_expr le (For_set (SDbase ty ty t)) e3 sla4)) \u2217\n    \\\u231c sla = (sla2.1 ++ makeif sla2.2 (makeseq sla3.1) (makeseq sla4.1) :: nil,Etempvar t ty)\u231d\n| For_effects =>\n  \u2203 sla2 sla3 sla4,\n    tr_expr le For_val e1 sla2  \u2217\n    tr_expr le For_effects e2 sla3 \u2217\n    tr_expr le For_effects e3 sla4 \u2217\n    \\\u231c sla.1 = sla2.1 ++ makeif sla2.2 (makeseq sla3.1) (makeseq sla4.1) :: nil \u231d\n| For_set sd =>\n  \u2203 sla2 sla3 sla4 t,\n    tr_expr le For_val e1 sla2  \u2217\n    \\s t \u2217\n    (\\s t -\u2217 (tr_expr le (For_set (SDcons ty ty t sd)) e2 sla3 \u2227\n    tr_expr le (For_set (SDcons ty ty t sd)) e3 sla4)) \u2217\n    \u231c sla.1 = sla2.1 ++ makeif sla2.2 (makeseq sla3.1) (makeseq sla4.1) :: nil \u231d\n  end\n| Csyntax.Eassign e1 e2 ty =>\n  \u2203 sla2 sla3,\n  tr_expr le For_val e1 sla2  \u2217\n  tr_expr le For_val e2 sla3  \u2217\n  (\u231c sla.1 = sla2.1 ++ sla3.1 ++ make_assign sla2.2 sla3.2 :: nil /\\  dst = For_effects \u231d \u2228 (\u2203 t, \\s t \u2217 \u231c sla.1 = sla2.1 ++ sla3.1 ++ Sset t (Ecast sla3.2 (Csyntax.typeof e1)) :: make_assign sla2.2 (Etempvar t (Csyntax.typeof e1)) :: final dst (Etempvar t (Csyntax.typeof e1)) \u231d))\n| Csyntax.Eassignop ope e1 e2 tyres ty =>\n  \u2203 sla2 sla3 sla4,\n    tr_expr le For_val e1 sla2  \u2217\n    tr_expr le For_val e2 sla3  \u2217\n    tr_rvalof (Csyntax.typeof e1) sla2.2 sla4  \u2217\n    (\u231c dst = For_effects /\\\n     sla.1 = sla2.1 ++ sla3.1 ++ sla4.1 ++ make_assign sla2.2 (Ebinop ope sla4.2 sla3.2 tyres) :: nil \u231d \u2228 (\u2203 t, \\s t \u2217 \u231c sla = (sla2.1 ++ sla3.1 ++ sla4.1 ++ Sset t (Ecast (Ebinop ope sla4.2 sla3.2 tyres) (Csyntax.typeof e1)) :: make_assign sla2.2 (Etempvar t (Csyntax.typeof e1)) :: final dst (Etempvar t (Csyntax.typeof e1)), (Etempvar t (Csyntax.typeof e1))) \u231d))\n| Csyntax.Epostincr id e1 ty =>\n  ((\u2203 sla2 sla3,\n        tr_expr le For_val e1 sla2  \u2217\n                tr_rvalof (Csyntax.typeof e1) sla2.2 sla3  \u2217\n                \u231c sla.1 = sla2.1 ++ sla3.1 ++\n                                 make_assign sla2.2 (transl_incrdecr id sla3.2 (Csyntax.typeof e1)) :: nil \u231d) \u2228\n                                                                                                                        (\u2203 sla2 t,\n                                                                                                                             tr_expr le For_val e1 sla2  \u2217\n                                                                                                                                     \\s t  \u2217\n                                                                                                                                     \u231c sla = (sla2.1 ++ make_set t sla2.2 ::\n                                                                                                                                                     make_assign sla2.2 (transl_incrdecr id (Etempvar t (Csyntax.typeof e1)) (Csyntax.typeof e1)) ::\n                                                                                                                                                     final dst (Etempvar t (Csyntax.typeof e1)),Etempvar t (Csyntax.typeof e1))\u231d))\n\n| Csyntax.Ecomma e1 e2 ty =>\n  \u2203 sla2 sl3,\n    tr_expr le For_effects e1 sla2  \u2217\n            (dest_below dst -\u2217 tr_expr le dst e2 (sl3,sla.2))  \u2217\n            dest_below dst \u2217\n            \\\u231c sla.1 = sla2.1 ++ sl3 \u231d\n\n| Csyntax.Ecall e1 el2 ty =>\n  match dst with\n  | For_effects =>\n    \u2203 sla2 slal3,\n    tr_expr le For_val e1 sla2  \u2217\n            tr_exprlist le el2 slal3  \u2217\n            \\\u231c  sla.1 = sla2.1 ++ slal3.1 ++ Scall None sla2.2 slal3.2 :: nil \u231d\n| _ =>\n  \u2203 sla2 slal3 t,\n    tr_expr le For_val e1 sla2  \u2217\n            tr_exprlist le el2 slal3  \u2217\n            \\s t  \u2217\n            dest_below dst \u2217\n            \\\u231c sla = (sla2.1 ++ slal3.1 ++ Scall (Some t) sla2.2 slal3.2 :: final dst (Etempvar t ty), Etempvar t ty)\u231d\n  end\n\n| Csyntax.Ebuiltin ef tyargs el ty =>\n  match dst with\n  | For_effects =>\n    \u2203 slal2,\n    tr_exprlist le el (slal2)  \u2217\n                \\\u231c sla.1 = slal2.1 ++ Sbuiltin None ef tyargs slal2.2 :: nil \u231d\n| _ =>\n  \u2203 slal2 t,\n    tr_exprlist le el slal2  \u2217\n                \\s t  \u2217\n                dest_below dst \u2217\n                \\\u231c sla = (slal2.1 ++ Sbuiltin (Some t) ef tyargs slal2.2 :: final dst (Etempvar t ty), Etempvar t ty)\u231d\n  end\n\n| Csyntax.Eparen e1 tycast ty =>\n  match dst with\n  | For_val =>\n    \u2203 a2 t,\n    (\\s t  -\u2217 tr_expr le (For_set (SDbase tycast ty t)) e1 (sla.1,a2))  \u2217\n            \\s t  \u2217\n            \u231c sla.2 = Etempvar t ty \u231d\n| For_effects =>\n  \u2203 a2, tr_expr le For_effects e1 (sla.1,a2)\n| For_set sd =>\n  \u2203 a2 t,\n    (\\s t -\u2217 tr_expr le (For_set (SDcons tycast ty t sd)) e1 (sla.1,a2))  \u2217 \\s t\n  end\n\n| _ => False\n  end\n  with tr_exprlist (le : temp_env) (e : Csyntax.exprlist) (sla : list statement * list expr) : iProp := \u231c True \u231d \u2217\n         match e with\n         | Csyntax.Enil => \\\u231c sla = (nil,nil)\u231d\n         | Csyntax.Econs e1 el2 =>\n           \u2203 sla2 slal3,\n    tr_expr le For_val e1 sla2  \u2217\n            tr_exprlist le el2 slal3  \u2217\n            \\\u231c sla = (sla2.1 ++ slal3.1, sla2.2 :: slal3.2) \u231d\n  end.\n\n  Lemma transl_valof_meets_spec ty a :\n    {{ emp }} transl_valof ty a {{ r, RET r; tr_rvalof ty a r }}.\n  Proof.\n    unfold transl_valof. unfold tr_rvalof.\n    destruct (type_is_volatile ty); tac.\n    frameR. iApply ret_spec_bis.\n    iPureIntro; reflexivity.\n  Qed.\n\n\n\n  (** ** Top-level translation *)\n\n  (** The \"top-level\" translation is equivalent to [tr_expr] above\n  for source terms.  It brings additional flexibility in the matching\n  between Csyntax values and Cminor expressions: in the case of\n  [tr_expr], the Cminor expression must not depend on memory,\n  while in the case of [tr_top] it can depend on the current memory\n  state. *)\n\n  Scheme expr_ind2 := Induction for Csyntax.expr Sort Prop\n    with exprlist_ind2 := Induction for Csyntax.exprlist Sort Prop.\n  Combined Scheme tr_expr_exprlist from expr_ind2, exprlist_ind2.\n\n  Lemma tr_expr_abs : forall (Q : iProp) le dst r res,\n      tr_expr le dst r res \u2217 Q -\u2217 tr_expr le dst r res.\n  Proof.\n    induction r; iIntros \"* [[HC HA] HB]\"; iSplitL \"HC HB\"; trivial.\n  Qed.\n  \n  Lemma transl_meets_spec :\n    (forall r dst,\n        {{ emp }} transl_expr dst r {{ res, RET res; (\u2200 le, dest_below dst -\u2217 tr_expr le dst r res)}})\n    /\\\n    (forall rl,\n        {{ emp }} transl_exprlist rl {{ res, RET res; (\u2200 le, tr_exprlist le rl res) }}).\n  Proof.\n    pose transl_valof_meets_spec.\n    apply tr_expr_exprlist; intros; rewrite /transl_expr; rewrite /transl_exprlist;\n      fold transl_exprlist; fold transl_expr; tac2; rewrite /tr_expr; fold tr_expr; tac2.\n    - destruct v; tac2; iApply ret_spec_complete; destruct dst; iIntros; eauto; iSplitR; auto;\n        try (iExists _); try iSplit; eauto; iIntros; simpl;\n          iPureIntro; eauto; intros; constructor; reflexivity. \n    - iApply ret_spec_complete. iIntros \"[HA HB]\"; iFrame.\n      destruct dst; iIntros; iPureIntro; auto.\n    - apply forall_wand_true_pre. iApply ret_spec_complete. iIntros \"HA\" (?) \"HB\". iSplit; auto.\n      iExists v. iFrame.\n      iSplitL \"HA\". iApply \"HA\". iPureIntro.\n      destruct dst; simpl; eauto; rewrite app_nil_r; reflexivity.\n    - frameR; apply b.\n    - iApply ret_spec_complete.\n      iIntros \"[HA HB]\" (?) \"HC\". iSplit; auto. iExists v; iExists v0.1. iFrame. iSplitL \"HB\". iApply \"HB\". trivial.\n      destruct dst; iSimpl; iSplitL \"HA\"; try(rewrite <- surjective_pairing; iApply \"HA\");\n        iPureIntro; try(rewrite app_nil_r; reflexivity); rewrite app_assoc; reflexivity.\n    - iApply ret_spec_complete. \n      iIntros \"HA\" (le) \"HB\". iSplit; auto. iExists v. iSplitL \"HA\". iApply \"HA\". trivial. iFrame.\n      iPureIntro. destruct dst; simpl; try (rewrite app_nil_r); reflexivity.\n    - iApply ret_spec_complete.\n      iIntros \"HA\" (le) \"HB\". iSplit; auto. iExists v. iFrame. iSplitL \"HA\". iApply \"HA\". trivial.\n      iPureIntro. destruct dst; simpl; try (rewrite app_nil_r); reflexivity.\n    - iApply ret_spec_complete.\n      iIntros \"HA\" (le) \"HB\". iSplit; auto. iExists v. iSplitL \"HA\". iApply \"HA\". trivial. iFrame.\n      iPureIntro. destruct dst; simpl; try (rewrite app_nil_r); reflexivity.\n    - frameR. apply H0.\n    - iApply ret_spec_complete.\n      iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto.\n      repeat iExists _. iFrame.\n      iSplitL \"HC\". iApply \"HC\". trivial.\n      iSplitL \"HA\". iApply \"HA\". trivial.\n      iPureIntro. destruct dst; simpl; try (rewrite app_nil_r; reflexivity).\n      rewrite app_assoc. reflexivity.\n    - iApply ret_spec_complete.\n      iIntros \"HA\" (le) \"HB\". iSplit; auto. iExists _. iSplitL \"HA\". iApply \"HA\". trivial. iFrame.\n      iPureIntro. destruct dst; simpl; try (rewrite app_nil_r); reflexivity.\n    - destruct dst; repeat tac2.\n      + frameR. apply H0.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HC HD]]\" (?) \"_\". iSplit; auto. repeat iExists _.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iSplitL \"HA\". iIntros \"HB\". iApply \"HA\". iSimpl. iApply \"HB\".\n        iSplitL \"HC\". iExists ty. iApply \"HC\".\n        iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _. \n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\".  trivial.\n        iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + iApply ret_spec_complete. iIntros \"[HA HC]\" (le) \"HB\". iFrame.\n        repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\". \n        iPureIntro. reflexivity.\n    - destruct dst; repeat tac2.\n      + frameR. apply H0.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HC HD]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iSplitL \"HA\". iIntros \"HB\". iApply \"HA\". simpl. iApply \"HB\".\n        iSplitL \"HC\". iExists ty. iApply \"HC\".\n        iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\".  trivial.\n        iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + iApply ret_spec_complete. iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\". iFrame.\n        iPureIntro. reflexivity.\n    - destruct dst; repeat tac2.\n      + frameR. apply H0.\n      + frameR. apply H1.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HC [HE HD]]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iSplitL \"HE\". iExists ty. iFrame.\n        iSplitL \"HC HA\".\n        iIntros \"HB\".\n        iSplit.\n        * iDestruct (\"HC\" $! le with \"HB\") as \"HC\". iApply tr_expr_abs. iFrame. iApply \"HA\".\n        * iDestruct (\"HA\" $! le with \"HB\") as \"HA\". iApply tr_expr_abs. iFrame. iApply \"HC\".\n        * iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + frameR. apply H1.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HC HD]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\". trivial.\n        iPureIntro. reflexivity.\n      + frameR. apply H0.\n      + frameR. apply H1.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD [HE HC]]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HE\". iExists ty. iFrame.\n        iSplitL \"HD HA\".\n        iIntros \"HB\". \n        iSplit.\n        * iDestruct (\"HD\" $! le with \"HB\") as \"HC\". iApply tr_expr_abs. iFrame.\n          iApply \"HA\".\n        * iDestruct (\"HA\" $! le with \"HB\") as \"HA\". iApply tr_expr_abs. iFrame.\n          iApply \"HD\".\n        * iPureIntro. reflexivity.\n    - iApply ret_spec_complete. iIntros \"[HA HB]\". iSplit; auto. iFrame. iPureIntro. destruct dst; reflexivity.\n    - iApply ret_spec_complete. iIntros \"[HA HB]\". iSplit; auto. iFrame. iPureIntro. destruct dst; reflexivity.\n    - frameR. eapply H0.\n    - destruct dst; tac2.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD HC]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iRight. iExists v1. \n        iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\". \n        iPureIntro. reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iApply \"HA\". trivial.\n        iLeft. iPureIntro. split; reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD HC]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HD\". iApply \"HD\". trivial. iRight.\n        iExists v1. iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\". \n        iPureIntro. simpl. admit.\n    - frameR. apply H0.\n    - frameR. apply transl_valof_meets_spec.\n    - destruct dst; tac2.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD [HE HC]]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HE\". iApply \"HE\". trivial.\n        iSplitL \"HD\". iApply \"HD\".\n        iRight. iExists v2.\n        iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\". \n        iPureIntro. reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD HC]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n         iSplitL \"HC\". iApply \"HC\". trivial.\n         iSplitL \"HD\". iApply \"HD\". trivial.\n         iFrame. iLeft.\n         iPureIntro. split; reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"[HA [HD [HE HC]]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HE\". iApply \"HE\". trivial.\n        iSplitL \"HD\". iApply \"HD\".\n        iRight. iExists v2.\n        iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\". \n        iPureIntro. simpl. admit.\n    - destruct dst; tac2.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto.\n        iRight. iExists v. iExists v0.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\".\n        iPureIntro. reflexivity.\n      + frameR. apply b.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le)  \"HB\". iSplit; auto.\n        iLeft. iExists v. iExists v0.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iFrame.\n        iPureIntro. reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto.\n        iRight.\n        iExists v. iExists v0.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HA\". iExists (Csyntax.typeof l). iApply \"HA\".\n        iPureIntro. simpl. admit.\n    - frameR. apply H0.\n    - iApply ret_spec_complete. \n      iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n      iSplitL \"HC\". iApply \"HC\". trivial.\n      iSplitL \"HA\". iIntros \"HC\". iSimpl. rewrite <- surjective_pairing.\n      iApply \"HA\". iApply \"HC\".\n      iFrame. iPureIntro. reflexivity.\n    - destruct dst; tac2; fold tr_exprlist; fold tr_expr.\n      + iApply ret_spec_complete. \n        iIntros \"[HA [HD HC]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iFrame.\n        iSplitL \"HD\". iApply \"HD\".\n        iSplitL. iExists ty. iApply \"HA\". \n        iPureIntro. reflexivity.\n      + iApply ret_spec_complete. \n        iIntros \"[HA HD]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HD\". iApply \"HD\". trivial.\n        iSplitL \"HA\". iApply \"HA\". trivial.\n      + iApply ret_spec_complete. \n        iIntros \"[HA [HD HC]]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\". trivial.\n        iSplitL \"HD\". iApply \"HD\".\n        iSplitL \"HA\". iExists ty. iApply \"HA\".\n        iFrame.\n        iPureIntro. simpl. admit. \n    - fold tr_exprlist. destruct dst; tac2.\n      + iApply ret_spec_complete. \n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\".\n        iSplitL \"HA\". iExists ty. iApply \"HA\".\n        iFrame.\n        iPureIntro. reflexivity.\n      + iApply ret_spec_complete.\n        iIntros \"HA\" (le) \"HB\". iSplit; auto.\n      + iApply ret_spec_complete. \n        iIntros \"[HA HC]\" (le) \"HB\". iSplit; auto. repeat iExists _.\n        iSplitL \"HC\". iApply \"HC\".\n        iSplitL \"HA\". iExists ty. iApply \"HA\".\n        iFrame.\n        iPureIntro. simpl. admit. \n    - iApply ret_spec_bis. eauto.\n    - rewrite /tr_exprlist; fold tr_exprlist; fold tr_expr; tac2.\n      iApply ret_spec_complete. \n      iIntros \"[HA HB]\" (le). iSplit; auto. repeat iExists _.\n      iSplitL \"HB\". iApply \"HB\". trivial.\n      iSplitL \"HA\". iApply \"HA\".\n      iPureIntro. reflexivity.          \n  Admitted.\n\n \n  \n  Section TR_TOP.\n\n    Variable ge: genv.\n    Variable e: Clight.env.\n    Variable le: temp_env.\n    Variable m: mem.\n    \n    Definition tr_top_base dst r sl a := tr_expr le dst r (sl,a).\n\n    Definition tr_top_val_val (dst : destination) expr (sl : list statement) a : Prop :=\n      match sl with\n      | nil => exists v ty, typeof a = ty /\\ eval_expr ge e le m a v /\\ dst = For_val\n                  /\\ expr = Csyntax.Eval v ty\n      | _ => False\n    end.\n\n    Definition tr_top dst expr sl a := tr_top_base dst expr sl a \u2228 \\\u231ctr_top_val_val dst expr sl a\u231d.\n\n  End TR_TOP.\n\n    \n(** ** Translation of statements *)\n\n  Lemma transl_expr_meets_spec:\n    forall r dst,\n      {{ emp }} transl_expr dst r {{ res, RET res;  dest_below dst -\u2217 \u2200 ge e le m, tr_top  ge e le m dst r res.1 res.2 }}.\n  Proof.\n    intros. exploit (proj1 transl_meets_spec); eauto. intro. iIntros (?) \"_ HA\".\n    iApply H; eauto. iIntros (res) \"HB\". iApply \"HA\". iIntros. rewrite /tr_top.\n    iLeft. rewrite /tr_top_base.\n    rewrite (surjective_pairing res). iApply \"HB\". iFrame. \n  Qed.\n\n  Lemma test : forall (P : iProp) Q, (P -\u2217 \u231cQ\u231d) -> (exists tmps, P () tmps -> Q).\n  Proof.\n    MonPred.unseal. intros. destruct H. repeat red in monPred_in_entails.\n    pose (monPred_in_entails () heap_empty).\n    destruct e with (a := ()).\n    + MonPred.unseal. split; auto.\n    + exists heap_empty; exists heap_empty. repeat split; eauto.\n    + exists \u2205. intro. inversion_star H h P. destruct P2. red in H1.\n      destruct (H1 \u2205).\n      * exists \u2205. exists \u2205. repeat split; eauto. inversion H2. subst. rewrite heap_union_empty_r in P0.\n        subst. apply P1.\n      * repeat destruct H3. apply H3.\n  Qed.\n\n  Lemma test2 : forall (P : iProp) (Q : Prop), (forall tmps, P () tmps -> Q) -> (P -\u2217 \u231cQ\u231d).\n  Proof.\n    intros. split. red. red. MonPred.unseal. intros. repeat red.\n    intros. exists emp. red. exists \u2205. exists \u2205. repeat split; auto.\n    - repeat red. intros. inversion_star H h P. inversion P1. inversion H4. subst.\n      exists \u2205. exists h0.\n      repeat split; auto.\n      + apply (H h0). destruct a. apply P2.\n    - inversion H0. inversion H3. rewrite heap_union_empty_l. reflexivity.\n  Qed.\n  \n  Inductive tr_expression: Csyntax.expr -> statement -> expr -> Prop :=\n  | tr_expression_intro: forall r sl a tmps,\n      (forall ge e le m, tr_top ge e le m For_val r sl a () tmps) ->\n      tr_expression r (makeseq sl) a.\n  \n  Import adequacy.\n  Lemma transl_expression_meets_spec: forall r,\n      {{ emp }} transl_expression r {{ res, RET res; \u231c tr_expression r res.1 res.2 \u231d }}.\n  Proof.\n    intro. unfold transl_expression. epose transl_meets_spec. destruct a. tac2.\n    - apply (H r For_val).\n    - iApply ret_spec_complete. iStopProof. apply test2. intros.\n      apply (tr_expression_intro _ _ _ tmps). intros. apply soundness2. apply soundness3 in H1.\n      iIntros \"HA\". iDestruct (H1 with \"HA\") as \"HA\". unfold tr_top.\n      iLeft. unfold tr_top_base. simpl. rewrite <- surjective_pairing. iApply \"HA\".\n      trivial.\n  Qed.\n\n  \n  Inductive tr_expr_stmt: Csyntax.expr -> statement -> Prop :=\n  | tr_expr_stmt_intro: forall r sl a tmps,\n      (forall ge e le m, tr_top ge e le m For_effects r sl a () tmps) ->\n      tr_expr_stmt r (makeseq sl).\n  \n  Lemma transl_expr_stmt_meets_spec: forall r,\n      {{ emp }} transl_expr_stmt r {{ res, RET res; \u231c tr_expr_stmt r res \u231d}}.\n  Proof.\n    intro. unfold transl_expr_stmt. epose transl_meets_spec. destruct a; tac2.\n    - apply H.\n    - iApply ret_spec_complete. iStopProof. apply test2. intros.\n      apply (tr_expr_stmt_intro _ _ v.2 tmps). intros.\n      apply soundness3 in H1. apply soundness2.\n      iIntros \"HA\". iDestruct (H1 with \"HA\") as \"HA\". unfold tr_top. iLeft.\n      unfold tr_top_base. simpl. rewrite <- surjective_pairing. iApply \"HA\".\n      trivial.\n  Qed.\n\n  Inductive tr_if: Csyntax.expr -> statement -> statement -> statement -> Prop :=\n  | tr_if_intro: forall r s1 s2 sl a tmps,\n      (forall ge e le m, tr_top ge e le m For_val r sl a () tmps) ->\n      tr_if r s1 s2 (makeseq (sl ++ makeif a s1 s2 :: nil)).\n  \n  Lemma transl_if_meets_spec: forall r s1 s2,\n      {{ emp }} transl_if r s1 s2 {{ res, RET res; \u231c tr_if r s1 s2 res \u231d }}.\n  Proof.\n    intros. epose transl_meets_spec. destruct a; unfold transl_if; tac2.\n    - apply H.\n    - iApply ret_spec_complete. iStopProof. apply test2. intros.\n      apply (tr_if_intro _ _ _ _ _ tmps). intros.\n      apply soundness3 in H1. apply soundness2.\n      iIntros \"HA\". iDestruct (H1 with \"HA\") as \"HA\". unfold tr_top. iLeft.\n      unfold tr_top_base. simpl. rewrite <- surjective_pairing. iApply \"HA\".\n      trivial.\n  Qed.\n\n  Inductive tr_stmt: Csyntax.statement -> statement -> Prop :=\n  | tr_skip:\n      tr_stmt Csyntax.Sskip Sskip\n  | tr_do: forall r s,\n      tr_expr_stmt r s ->\n      tr_stmt (Csyntax.Sdo r) s\n  | tr_seq: forall s1 s2 ts1 ts2,\n      tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->\n      tr_stmt (Csyntax.Ssequence s1 s2) (Ssequence ts1 ts2)\n  | tr_ifthenelse_empty: forall r s' a,\n      tr_expression r s' a ->\n      tr_stmt (Csyntax.Sifthenelse r Csyntax.Sskip Csyntax.Sskip) (Ssequence s' Sskip)\n  | tr_ifthenelse: forall r s1 s2 s' a ts1 ts2,\n      tr_expression r s' a ->\n      tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->\n      tr_stmt (Csyntax.Sifthenelse r s1 s2) (Ssequence s' (Sifthenelse a ts1 ts2))\n  | tr_while: forall r s1 s' ts1,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s1 ts1 ->\n      tr_stmt (Csyntax.Swhile r s1)\n              (Sloop (Ssequence s' ts1) Sskip)\n  | tr_dowhile: forall r s1 s' ts1,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s1 ts1 ->\n      tr_stmt (Csyntax.Sdowhile r s1)\n              (Sloop ts1 s')\n  | tr_for_1: forall r s3 s4 s' ts3 ts4,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s3 ts3 ->\n      tr_stmt s4 ts4 ->\n      tr_stmt (Csyntax.Sfor Csyntax.Sskip r s3 s4)\n              (Sloop (Ssequence s' ts4) ts3)\n  | tr_for_2: forall s1 r s3 s4 s' ts1 ts3 ts4,\n      tr_if r Sskip Sbreak s' ->\n      s1 <> Csyntax.Sskip ->\n      tr_stmt s1 ts1 ->\n      tr_stmt s3 ts3 ->\n      tr_stmt s4 ts4 ->\n      tr_stmt (Csyntax.Sfor s1 r s3 s4)\n              (Ssequence ts1 (Sloop (Ssequence s' ts4) ts3))\n  | tr_break:\n      tr_stmt Csyntax.Sbreak Sbreak\n  | tr_continue:\n      tr_stmt Csyntax.Scontinue Scontinue\n  | tr_return_none:\n      tr_stmt (Csyntax.Sreturn None) (Sreturn None)\n  | tr_return_some: forall r s' a,\n      tr_expression r s' a ->\n      tr_stmt (Csyntax.Sreturn (Some r)) (Ssequence s' (Sreturn (Some a)))\n  | tr_switch: forall r ls s' a tls,\n      tr_expression r s' a ->\n      tr_lblstmts ls tls ->\n      tr_stmt (Csyntax.Sswitch r ls) (Ssequence s' (Sswitch a tls))\n  | tr_label: forall lbl s ts,\n      tr_stmt s ts ->\n      tr_stmt (Csyntax.Slabel lbl s) (Slabel lbl ts)\n  | tr_goto: forall lbl,\n      tr_stmt (Csyntax.Sgoto lbl) (Sgoto lbl)\n\nwith tr_lblstmts: Csyntax.labeled_statements -> labeled_statements -> Prop :=\n  | tr_ls_nil:\n      tr_lblstmts Csyntax.LSnil LSnil\n  | tr_ls_cons: forall c s ls ts tls,\n      tr_stmt s ts ->\n      tr_lblstmts ls tls ->\n      tr_lblstmts (Csyntax.LScons c s ls) (LScons c ts tls).\n\n  Lemma transl_stmt_meets_spec : forall s,\n      {{ emp }} transl_stmt s {{ res, RET res; \u231c tr_stmt s res \u231d}}\n  with transl_lblstmt_meets_spec:\n         forall s,\n           {{ emp }} transl_lblstmt s {{ res, RET res; \u231c tr_lblstmts s res \u231d }}. \n  Proof.\n    pose transl_expression_meets_spec. pose transl_if_meets_spec. pose transl_expr_stmt_meets_spec.\n    clear transl_stmt_meets_spec.\n    intro. induction s; rewrite /transl_stmt; fold transl_stmt; tac2.\n    - iApply ret_spec_bis. iPureIntro. constructor.\n    - apply (post_weaker _ _ _ _ (b1 e)). iIntros. iPureIntro. apply (tr_do _ _ a).\n    - iApply ret_spec_complete. iIntros \"[% %]\".\n      iPureIntro. apply (tr_seq _ _  _ _ H0 H).\n    - tac2. frameR. apply transl_expression_meets_spec.\n      destruct (is_Sskip s1); destruct (is_Sskip s2) eqn:?; iApply ret_spec_complete;\n        iIntros \"[% [% %]]\"; iPureIntro; subst.\n      1 : apply (tr_ifthenelse_empty _ _ _ H).\n      all : apply (tr_ifthenelse _ _ _ _ _ _ _ H H1 H0).\n    - iApply ret_spec_complete.\n      iIntros \"[% %]\". iPureIntro. apply (tr_while _ _ _ _ H0 H).\n    - iApply ret_spec_complete.\n      iIntros \"[% %]\". iPureIntro. apply (tr_dowhile _ _ _ _ H0 H).\n    - frameR. apply transl_if_meets_spec.\n    - destruct (is_Sskip); iApply ret_spec_complete;\n        iIntros \"[% [% [% %]]]\"; iPureIntro; subst.\n      + apply (tr_for_1 _ _ _ _ _ _ H1 H0 H).\n      + apply (tr_for_2 _ _ _ _ _ _ _ _ H1 n H2 H0 H).\n    - iApply ret_spec_bis. iPureIntro. constructor.\n    - iApply ret_spec_bis. iPureIntro. constructor.\n    - destruct o; tac2.\n      + iApply ret_spec_complete. iIntros. iPureIntro. apply (tr_return_some _ _ _ a).\n      + iApply ret_spec_bis. iPureIntro. constructor. \n    - fold transl_lblstmt. frameR. apply transl_lblstmt_meets_spec.\n    - iApply ret_spec_complete. iIntros \"[% %]\". iPureIntro. constructor; auto.\n    - iApply ret_spec_complete. iIntros \"%\". iPureIntro. constructor; auto.\n    - iApply ret_spec_bis. iPureIntro. constructor.\n    - induction s; rewrite /transl_lblstmt; fold transl_lblstmt; fold transl_stmt; tac2.\n      + iApply ret_spec_bis. iPureIntro. constructor.\n      + iApply ret_spec_complete. iIntros \"[% %]\". iPureIntro. constructor; auto.\n  Qed.\n\n \n  (** Relational presentation for the transformation of functions, fundefs, and variables. *)\n  \n  Inductive tr_function: Csyntax.function -> Clight.function -> Prop :=\n  | tr_function_intro: forall f tf,\n      tr_stmt f.(Csyntax.fn_body) tf.(fn_body) ->\n      fn_return tf = Csyntax.fn_return f ->\n      fn_callconv tf = Csyntax.fn_callconv f ->\n      fn_params tf = Csyntax.fn_params f ->\n      fn_vars tf = Csyntax.fn_vars f ->\n      tr_function f tf.\n  \n\n  Inductive tr_fundef: Csyntax.fundef -> Clight.fundef -> Prop :=\n  | tr_internal: forall f tf,\n      tr_function f tf ->\n      tr_fundef (Internal f) (Internal tf)\n  | tr_external: forall ef targs tres cconv,\n      tr_fundef (External ef targs tres cconv) (External ef targs tres cconv).\n  \n  \n  Lemma transl_function_spec:\n    forall f tf,\n      transl_function f = OK tf ->\n      tr_function f tf.\n  Proof.\n    unfold transl_function; intros.\n    destruct (run (transl_stmt (Csyntax.fn_body f)) \u2205) eqn:?. rewrite Heqe in H. inversion H.\n    destruct p.\n    rewrite Heqe in H. simpl in *. inversion H.\n    apply tr_function_intro; auto; simpl.\n    eapply (adequacy_pure (transl_stmt (Csyntax.fn_body f)) _ \u2205 s0 s emp).\n    2: apply Heqe.\n    iIntros \"HA\". iSplitL; eauto.\n    iApply (transl_stmt_meets_spec (Csyntax.fn_body f)). \n  Qed.\n\n  Lemma transl_fundef_spec:\n    forall fd tfd,\n      transl_fundef fd = OK tfd ->\n      tr_fundef fd tfd.\n  Proof.\n    unfold transl_fundef; intros.\n    destruct fd; Errors.monadInv H.\n    + constructor. eapply transl_function_spec; eauto.\n    + constructor.\n  Qed.\n\nEnd SPEC.\n", "meta": {"author": "Artalik", "repo": "monad-frame-src", "sha": "7aa9364eb94c10f447a215351cd84dcbc8506714", "save_path": "github-repos/coq/Artalik-monad-frame-src", "path": "github-repos/coq/Artalik-monad-frame-src/monad-frame-src-7aa9364eb94c10f447a215351cd84dcbc8506714/src/SimplExprspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "From ExtLib Require Import\n     Data.List\n     Structures.Monad.\n\nFrom Paco Require Import paco.\n\nFrom ITree Require Import\n     ITree\n     ITreeFacts\n     Events.MapDefault\n     Events.State\n     Events.StateFacts.\n\nFrom ITree.Extra Require Import\n     Dijkstra.DijkstraMonad\n     Dijkstra.PureITreeBasics\n     Dijkstra.DelaySpecMonad\n     Dijkstra.StateSpecT.\n\nImport Monads.\nImport MonadNotation.\n#[local] Open Scope monad_scope.\n#[local] Open Scope delayspec_scope.\n\n(* Defines a specification monad for the state transform of the Delay monad. Also includes encodings for pre post condition specifications. *)\n\nSection StateDelaySpec.\n\n  Context (St : Type).\n\n  Definition StateDelaySpec := StateSpecT St DelaySpec.\n\n  Definition StateDelaySpecOrder := StateSpecTOrder St DelaySpec.\n\n  Definition StateDelaySpecOrderedLaws := StateSpecTOrderedLaws St DelaySpec.\n\n  Definition StateDelaySpecEq := StateSpecTEq St DelaySpec.\n\n  Definition StateDelaySpecMonadLaws := StateSpecTMonadLaws St DelaySpec.\n\n  Definition StateDelay := StateSpecT St Delay.\n\n  Definition StateDelayObs := EffectObsStateT St DelaySpec Delay.\n\n  Definition StateDelayMonadMorph := MonadMorphimStateT St DelaySpec Delay.\n\n  Definition PrePost A : Type := (Delay (St * A) -> Prop ) * (St -> Prop).\n\n  Definition PrePostRef {A : Type} (m : StateDelay A) (pp : PrePost A) : Prop :=\n    let '(post,pre) := pp in\n    forall s, pre s -> post (m s).\n\n  Program Definition encode {A : Type} (pp : PrePost A) : StateDelaySpec A :=\n    let '(post,pre) := pp in\n    fun s p => pre s /\\ (forall r, post r -> p r).\n\n  Definition verify_cond {A : Type} := DijkstraProp StateDelay StateDelaySpec StateDelayObs A.\n\n  Lemma encode_correct : forall (A : Type) (pre : St -> Prop) (post : Delay (St * A) -> Prop)\n                                (m : StateDelay A),\n      resp_eutt post -> (PrePostRef m (post,pre) <-> verify_cond (encode (post,pre)) m).\n  Proof.\n    intros. cbn. unfold verify_cond, DijkstraProp.\n    split; intros.\n    - repeat red. simpl. intros. destruct p as [p Hp]. simpl in H1. destruct H1 as [Hpre Himp].\n      auto.\n    - repeat red in H0. simpl in H0.\n      set (exist _ post H) as p. enough ((m s) \u2208 p); auto.\n      apply H0. auto.\n  Qed.\n\n  Definition PrePostPair A : Type := PrePost A * PrePost A.\n\n  Definition PrePostPairRef {A : Type} (pppp : PrePostPair A) (m : StateDelay A) :=\n    let '((post0, pre0), (post1, pre1)) := pppp in\n    forall s, (pre0 s -> post0 (m s)) /\\ (pre1 s -> post1 (m s)) .\n\n  Program Definition encode_pair {A : Type} (pppp : PrePostPair A) : StateDelaySpec A:=\n    let '((post0, pre0), (post1, pre1)) := pppp in\n    fun s (p : DelaySpecInput (St * A)) =>\n      (pre0 s /\\ (forall r, post0 r -> p r)) \\/ (pre1 s /\\ forall r, post1 r -> p r).\n  Next Obligation.\n  destruct H0 as [H0 | H1].\n  - destruct H0 as [Hp Hr]. left. auto.\n  - destruct H1 as [Hp Hr]. right. auto.\n  Qed.\n\n  Lemma encode_pair_correct : forall (A : Type) (pre0 pre1 : St -> Prop)\n                                          (post0 post1 : Delay (St * A) -> Prop ) (m : StateDelay A),\n      let pp : PrePostPair A := ((post0,pre0),(post1,pre1)) in\n      resp_eutt post0 -> resp_eutt post1 ->\n      (PrePostPairRef pp m <-> verify_cond (encode_pair pp) m).\n  Proof.\n    intros. cbn. unfold verify_cond, DijkstraProp. split; intros.\n    - repeat red. simpl. intros. destruct p as [p Hrp].\n      specialize (H1 s). destruct H1.\n      destruct H2 as [ [Hs Hp] | [Hs Hp]  ]; simpl in *; auto.\n    - repeat red in H1. simpl in *.\n      split; intros.\n      + set (exist _ post0 H) as p. enough ((m s) \u2208 p ); auto.\n        apply H1. left. split; auto.\n      + set (exist _ post1 H0) as p. enough ((m s) \u2208 p ); auto.\n        apply H1. right. split; auto.\n  Qed.\n\n  Definition PrePostList A : Type := list (PrePost A).\n\n  Definition PrePostListRef {A : Type} (ppl : PrePostList A) (m : StateDelay A) :=\n    forall s, List.Forall (fun pp : PrePost A=> let (post,pre) := pp in pre s -> post (m s) ) ppl.\n\n  Program Definition encode_list {A : Type} (ppl : PrePostList A) : StateDelaySpec A :=\n    fun s (p : DelaySpecInput (St * A) ) =>\n      List.Exists (fun pp : PrePost A => let (post,pre) := pp in pre s /\\ forall r, post r -> p r) ppl.\n  Next Obligation.\n    induction H0; eauto.\n    destruct x as [post pre]. destruct H0 as [Hs Hr]. left. auto.\n  Qed.\n\n\n  Lemma enocde_list_correct : forall (A : Type) (ppl : PrePostList A) (m : StateDelay A),\n      List.Forall (fun pp => resp_eutt (fst pp) ) ppl->\n      (PrePostListRef ppl m <-> verify_cond (encode_list ppl) m).\n  Proof.\n    intros. unfold verify_cond, DijkstraProp. split; intros.\n    - repeat red. intros. destruct p as [p Hp]. red in H0.\n      specialize (H0 s) as Hrefine. unfold encode_list in H1. simpl in *.\n      induction ppl.\n      + inversion H1.\n      + destruct a as [post pre].\n        inversion H1; subst.\n        * destruct H3. auto.\n          assert ((pre s -> post (m s)) ); auto.\n          intros. inversion Hrefine; subst; auto.\n        * apply IHppl; auto.\n          -- inversion H; auto.\n          -- intros. specialize (H0 s0). inversion H0. auto.\n          -- specialize (H0 s). inversion H0. auto.\n    - unfold encode_list in H0. simpl in *. repeat red. repeat red in H0. simpl in *. intros.\n      induction ppl; auto.\n      destruct a as [post pre]. specialize (H0 s) as Henc.\n      assert (Heutt : resp_eutt post).\n      { inversion H. auto. }\n      set (exist _ post Heutt) as p. specialize (Henc p) as Hencp.\n      constructor; intros.\n      + enough ((m s) \u2208 p ); auto. apply Hencp.\n        left. split; auto.\n      + apply IHppl; auto.\n        * inversion H. auto.\n        * clear IHppl. intros. apply H0. eauto.\n  Qed.\n\n  Definition DynPrePost A : Type := (St -> Prop) * (St -> Delay (St * A) -> Prop).\n\n  Definition DynPrePostRef {A : Type} (pp : DynPrePost A) (m : StateDelay A) :=\n    let (pre,post) := pp in\n    forall s, pre s -> post s (m s).\n\n  Program Definition encode_dyn {A : Type} (pp : DynPrePost A) : StateDelaySpec A :=\n    let (pre,post) := pp in\n    fun s p => pre s /\\ forall r, post s r -> p r.\n\n  Lemma encode_dyn_correct : forall (A : Type) (pre : St -> Prop) (post : St -> Delay (St * A) -> Prop ) (m : StateDelay A),\n      (forall s, resp_eutt (post s)) -> (DynPrePostRef (pre,post) m <-> verify_cond (encode_dyn (pre,post) ) m).\n    Proof.\n      intros. unfold verify_cond, DijkstraProp. split; intros.\n      - repeat red. red in H0. intros. destruct p as [p Hp]. simpl in *.\n        destruct H1 as [Hs Hr]. auto.\n      - repeat red in H0. red. intros.\n        set (exist _ (post s) (H s) ) as p. specialize (H0 s p).\n        unfold p in H0. simpl in *. auto.\n    Qed.\n\n  Definition DynPrePostListRef {A : Type} (ppl : list (DynPrePost A)) (m : StateDelay A) : Prop :=\n    Forall (fun pp => DynPrePostRef pp m) ppl.\n\n  Program Definition encode_list_dyn {A : Type} (ppl : list (DynPrePost A)) : StateDelaySpec A :=\n    fun s p => List.Exists (fun pp : DynPrePost A => let (pre,post) := pp in pre s /\\ forall r, post s r -> p r ) ppl.\n  Next Obligation.\n    induction H0; eauto. left. destruct x as [pre post]. destruct H0 as [Hs Hr].\n    split; auto.\n  Qed.\n\n  Lemma enocde_list_dyn_correct : forall (A : Type) (ppl : list (DynPrePost A) ) (m : StateDelay A),\n      List.Forall (fun pp => forall s, resp_eutt (snd pp s) ) ppl->\n      (DynPrePostListRef ppl m <-> verify_cond (encode_list_dyn ppl) m).\n  Proof.\n    intros. unfold verify_cond, DijkstraProp. split; intros.\n    - repeat red. intros. destruct p as [p Hp]. simpl in H1. red in H0. rename H0 into Hrefine.\n      unfold DynPrePostRef in Hrefine.\n      induction ppl.\n      + inversion H1.\n      + destruct a as [pre post].\n        inversion H1; subst.\n        * destruct H2.\n          assert ((pre s -> post s (m s)) ); auto.\n          intros. inversion Hrefine; subst; auto.\n        * apply IHppl; auto.\n          -- inversion H; auto.\n          -- intros. inversion Hrefine; auto.\n    - unfold encode_list in H0. simpl in *. repeat red. repeat red in H0. simpl in *. intros.\n      induction ppl; auto.\n      destruct a as [pre post].\n      assert (Heutt : forall s, resp_eutt (post s)).\n      { inversion H. auto. }\n      constructor; intros.\n      + red. intros. set (exist _ (post s) (Heutt s)) as p.\n        specialize (H0 s p). enough ((m s) \u2208 p); auto. apply H0.\n        left. split; auto.\n      + apply IHppl; auto.\n        * inversion H. auto.\n        * clear IHppl. intros.\n          specialize (H0 s p). apply H0. eauto.\n  Qed.\n\n  Lemma combine_prepost_aux : forall (A B : Type) (pre1 pre2 : St -> Prop)\n                (post1 : Delay (St * A) -> Prop ) (post2 : Delay (St * B) -> Prop)\n    (m : StateDelay A) (f : A -> StateDelay B),\n    verify_cond (encode (post1,pre1) ) m ->\n    (forall (a : A) (s : St), (* this condition is not exactly what i want*)\n        post1 (Ret (s,a) ) -> post2 (f a s) ) ->\n    (post1 ITree.spin -> post2 ITree.spin) ->\n    resp_eutt post1 ->\n    verify_cond (encode (post2, pre1) ) (bind m f).\n  Proof.\n    intros. repeat red in H. repeat red. intros.\n    destruct p as [p Hp]. simpl in *.\n    destruct H3.\n    destruct (eutt_reta_or_div (m s)); basic_solve.\n    - destruct a as [s' a].\n      cbn in H5. rewrite <- H5, bind_ret_l; cbn. apply H4, H0. rewrite H5.\n      apply (H s (exist _ post1 H2)); auto.\n    - apply div_spin_eutt in H5.\n      rewrite H5, <- spin_bind. apply H4, H1. rewrite <- H5. apply (H s (exist _ post1 H2)); auto.\n  Qed.\n\n  Lemma combine_prepost : forall (A B : Type) (pre1 pre2 : St -> Prop)\n                (post1 : Delay (St * A) -> Prop ) (post2 : Delay (St * B) -> Prop)\n    (m : StateDelay A) (f : A -> StateDelay B),\n    verify_cond (encode (post1,pre1) ) m ->\n    (forall a s, post1 (Ret (s,a)) -> pre2 s)  ->\n    (forall a, verify_cond (encode (post2,pre2) ) (f a)  ) ->\n    (post1 ITree.spin -> post2 ITree.spin) ->\n    resp_eutt post1 ->\n    resp_eutt post2 ->\n    verify_cond (encode (post2, pre1) ) (bind m f).\n  Proof.\n    intros.\n    eapply combine_prepost_aux; eauto.\n    intros.\n    specialize (H1 a) as Hpp2. repeat red in Hpp2.\n    specialize (Hpp2 s (exist _ post2 H4) ). simpl in *.\n    apply Hpp2. split; eauto.\n  Qed.\n\nEnd StateDelaySpec.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/extra/Dijkstra/StateDelaySpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\nRequire Import iCompatibility.\nRequire Import SplitAcqCommon.\n\nRequire Import ITreeLang.\n\nSet Implicit Arguments.\n\n\nInductive split_acquire: forall R (i1: MemE.t R) (i2: MemE.t R), Prop :=\n| split_acquire_load\n    l:\n    split_acquire (MemE.read l Ordering.acqrel) (MemE.read l Ordering.relaxed)\n| split_acquire_update\n    l rmw ow\n    (OW: Ordering.le ow Ordering.strong_relaxed):\n    split_acquire (MemE.update l rmw Ordering.acqrel ow) (MemE.update l rmw Ordering.relaxed ow)\n.\n\nInductive sim_acquired: forall R\n                          (st_src:(Language.state (lang R))) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n                          (st_tgt:(Language.state (lang R))) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_acquired_intro\n    R\n    lc1_src sc1_src mem1_src\n    lc1_tgt sc1_tgt mem1_tgt\n    (LOCAL: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n    (SC: TimeMap.le sc1_src sc1_tgt)\n    (MEMORY: sim_memory mem1_src mem1_tgt)\n    (WF_SRC: Local.wf lc1_src mem1_src)\n    (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n    (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n    (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n    (MEM_SRC: Memory.closed mem1_src)\n    (MEM_TGT: Memory.closed mem1_tgt)\n    (r: R):\n    sim_acquired\n      (Ret r) lc1_src sc1_src mem1_src\n      (Vis (MemE.fence Ordering.acqrel Ordering.plain) (fun _ => Ret r)) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_local_sim_acquired\n      R (r: R)\n      lc_src sc_src mem_src\n      lc_tgt sc_tgt mem_tgt\n      (SIM: sim_local SimPromises.bot lc_src lc_tgt)\n      (SC1: TimeMap.le sc_src sc_tgt)\n      (MEM1: sim_memory mem_src mem_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt):\n  sim_acquired (Ret r) lc_src sc_src mem_src\n               (Vis (MemE.fence Ordering.acqrel Ordering.plain) (fun _ => Ret r)) lc_tgt sc_tgt mem_tgt.\nProof.\n  econs; eauto.\n  inv SIM. econs; ss. etrans; eauto.\n  apply TViewFacts.read_fence_tview_incr. apply WF_TGT.\nQed.\n\nLemma sim_acquired_mon\n      R\n      st_src lc_src sc1_src mem1_src\n      st_tgt lc_tgt sc1_tgt mem1_tgt\n      sc2_src mem2_src\n      sc2_tgt mem2_tgt\n      (SIM1: sim_acquired st_src lc_src sc1_src mem1_src\n                          st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt)\n      (SC1: TimeMap.le sc2_src sc2_tgt)\n      (MEM1: sim_memory mem2_src mem2_tgt)\n      (WF_SRC: Local.wf lc_src mem2_src)\n      (WF_TGT: Local.wf lc_tgt mem2_tgt)\n      (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n      (SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt)\n      (MEM_SRC: Memory.closed mem2_src)\n      (MEM_TGT: Memory.closed mem2_tgt):\n  @sim_acquired R\n                st_src lc_src sc2_src mem2_src\n                st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  destruct SIM1. econs; eauto.\nQed.\n\nLemma sim_acquired_step R\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      (SIM: sim_acquired st1_src lc1_src sc1_src mem1_src\n                         st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  @_sim_thread_step (lang R) (lang R)\n                    ((@sim_thread (lang R) (lang R) (sim_terminal eq)) \\8/ @sim_acquired R)\n                    st1_src lc1_src sc1_src mem1_src\n                    st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n  destruct SIM. ii.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv SPLIT); ss.\n  - (* promise *)\n    right.\n    exploit Local.promise_step_future; eauto. i. des.\n    exploit sim_local_promise_acquired; try exact LOCAL; eauto. i. des.\n    exploit Local.promise_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs. econs; eauto.\n    + eauto.\n    + right. econs; eauto.\n  - (* fence *)\n    right.\n    exploit Local.fence_step_future; eauto. i. des.\n    dependent destruction STATE. inv LOCAL1. ss.\n    esplits; (try by econs 1); eauto; ss.\n    left. eapply paco11_mon; [apply sim_itree_ret|]; ss. econs; ss.\n    + rewrite TViewFacts.write_fence_tview_strong_relaxed; ss. apply LOCAL.\n    + apply LOCAL.\nQed.\n\nLemma sim_acquired_sim_thread R:\n  @sim_acquired R <8= @sim_thread (lang R) (lang R) (sim_terminal eq).\nProof.\n  pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n  - inv TERMINAL_TGT. inv PR; ss.\n  - right. esplits; eauto.\n    inv PR. eapply sim_local_memory_bot; eauto.\n  - exploit sim_acquired_mon; eauto. i.\n    exploit sim_acquired_step; eauto. i. des; eauto.\n    + right. esplits; eauto.\n      left. eapply paco11_mon; eauto. ss.\n    + right. esplits; eauto.\nQed.\n\nLemma split_acquire_sim_itree R\n      (i_src i_tgt: MemE.t R)\n      (SPLIT: split_acquire i_src i_tgt):\n  sim_itree eq\n            (ITree.trigger i_src)\n            (r <- ITree.trigger i_tgt;; ITree.trigger (MemE.fence Ordering.acqrel Ordering.plain);; Ret r).\nProof.\n  replace (ITree.trigger i_src) with (Vis i_src (fun r => Ret r)).\n  2: { unfold ITree.trigger. grind. }\n  replace (r <- ITree.trigger i_tgt;; ITree.trigger (MemE.fence Ordering.acqrel Ordering.plain);; Ret r) with\n      (Vis i_tgt (fun r => Vis (MemE.fence Ordering.acqrel Ordering.plain) (fun _ => Ret r))).\n  2: { unfold ITree.trigger. grind. repeat f_equal. extensionality r. grind.\n       repeat f_equal. extensionality u. grind. }\n  pcofix CIH. ii. subst. pfold. ii. splits; ii.\n  { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }\n  { right. esplits; eauto.\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]; ss;\n    try (dependent destruction STATE; inv SPLIT); ss.\n  - (* promise *)\n    right.\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  - dependent destruction H.\n    (* load *)\n    right.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs. econs.\n    + auto.\n    + left. eapply paco11_mon; [apply sim_acquired_sim_thread|]; ss.\n  - dependent destruction H.\n    (* update-load *)\n    right.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs; eauto.\n    + auto.\n    + left. eapply paco11_mon; [apply sim_acquired_sim_thread|]; ss.\n  - dependent destruction H.\n    (* update *)\n    right.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    hexploit sim_local_write_acquired; try exact LOCAL2; try exact SC; eauto; try refl.\n    { inv LOCAL1. inv MEM_TGT. exploit CLOSED; eauto. i. des.\n      inv MSG_TS. ss. }\n    { inv STEP_SRC. inv LOCAL1. ss. repeat (condtac; aggrtac).\n      - rewrite <- ? View.join_l. apply LOCAL.\n      - apply WF_TGT.\n      - unfold TimeMap.join. rewrite <- Time.join_l. rewrite <- Time.join_l. rewrite <- Time.join_r.\n        unfold View.singleton_ur_if. condtac; ss. unfold TimeMap.singleton, LocFun.add.\n        condtac; ss. refl.\n    }\n    i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 4; eauto.\n      * econs; eauto.\n    + auto.\n    + left. eapply paco11_mon; [apply sim_acquired_sim_thread|]; ss.\n  - (* racy read *)\n    right.\n    dependent destruction H.\n    exploit sim_local_racy_read_acquired; try exact LOCAL1; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 9; eauto.\n      * econs; eauto.\n    + ss.\n    + left. eapply paco11_mon; [apply sim_acquired_sim_thread|]; ss.\n      apply sim_local_sim_acquired; eauto.\n  - (* racy read *)\n    right.\n    dependent destruction H.\n    exploit sim_local_racy_read_acquired; try exact LOCAL1; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; [|econs 9]; eauto. econs; eauto.\n    + ss.\n    + left. eapply paco11_mon; [apply sim_acquired_sim_thread|]; ss.\n      apply sim_local_sim_acquired; eauto.\n  - (* racy update *)\n    left.\n    dependent destruction H.\n    exploit sim_local_racy_update_acquired; try exact LOCAL1; eauto. i. des.\n    unfold Thread.steps_failure.\n    esplits; try refl.\n    + econs 2. econs; [|econs 11]; eauto. econs; eauto.\n    + ss.\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/iSplitAcq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.19394755000447175}}
{"text": "Require Import Coq.Program.Basics. \nRequire Import Coq.Strings.String. \nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\nRequire Import Coq.Program.Equality.\nRequire Import Bool.\n\n(* Require Import mathcomp.ssreflect.ssreflect. *)\n(* From mathcomp Require Import seq ssreflect ssrbool ssrnat eqtype. *)\n\nRequire Import FinProof.Common. \nRequire Import FinProof.MonadTransformers21.\nRequire Import FinProof.Common.\nRequire Import FinProof.StateMonad21.\nRequire Import FinProof.StateMonad21Instances.\nRequire Import FinProof.Types.IsoTypes.\nRequire Import FinProof.ProgrammingWith.\n\nRequire Import UMLang.UrsusLib.\nRequire Import UMLang.Args.CallWithArgsGenerator.\n\nRequire Import UrsusStdLib.Cpp.stdTypes.\nRequire Import UrsusStdLib.Cpp.stdErrors. \nRequire Import UrsusStdLib.Cpp.stdFunc.\nRequire Import UrsusStdLib.Cpp.stdNotations.\nRequire Import UrsusStdLib.Cpp.stdUFunc.\n\nRequire Import UrsusTVM.Cpp.tvmTypes.\nRequire Import UrsusTVM.Cpp.tvmFunc.\nRequire Import UrsusTVM.Cpp.tvmNotations.\nRequire Import UrsusTVM.Cpp.tvmProofs.\n\nRequire Import Project.CommonConstSig.\nRequire Import Project.CommonTypes.\n\n(*Fully qualified name are mandatory in multi-contract environment*)\nRequire Import DBlank.Ledger.\nRequire Import DBlank.ClassTypesNotations.\nRequire Import DBlank.ClassTypes.\nRequire Import DBlank.Functions.FuncSig.\nRequire Import DBlank.Functions.FuncNotations.\nRequire Import DBlank.Functions.Funcs.\n\n(* Require Import Blank.ClassTypesNotations. *)\n\nSet Typeclasses Iterative Deepening.\n(* Set Typeclasses Depth 100. *)\n\nImport UrsusNotations.\nLocal Open Scope ursus_scope.\nLocal Open Scope ucpp_scope.\nLocal Open Scope struct_scope.\nLocal Open Scope N_scope.\n(* Local Open Scope string_scope. *)\nLocal Open Scope xlist_scope.\n\nRequire Import Logic.FunctionalExtensionality.\nFrom QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Open Scope qc_scope.\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\n\nRequire Import Project.CommonQCEnvironment.\nRequire Import DBlank.QuickChicks.QCEnvironment.\nRequire Import DBlank.QuickChicks.Props.\nRequire Import UMLang.ExecGenerator.\n\nLemma isErrorEq : forall {R b} (cr : ControlResult R b),\n  CommonQCEnvironment.isError cr <-> isError cr = true.\nProof. unfold isError, CommonQCEnvironment.isError. destruct cr; intuition. Defined.\n\nLtac leftmost_or t :=\n  let rec tt := fun t =>\n  match t with\n  | ?A \\/ _ => tt A\n  | ?A => A\n  end in tt constr:(t).\n\nLemma elim_left_absurd : forall P : Prop,\n  true = false \\/ P <-> P.\nProof.\n  intros P. split; intros H.\n  - destruct H as [H|H]. discriminate H. apply H.\n  - right. apply H.\nDefined.\n\nClass eqb_spec A `{inst : XBoolEquable bool A} := {\n  eqb_spec_intro : forall (a b : A), Common.eqb a b = true <-> a = b\n}.\n\nLemma eqb_spec_reflect {A} `{eqb_spec A} :\n  forall a b : A, reflect (a = b) (Common.eqb a b).\nProof.\n  intros a b. destruct (Common.eqb a b) eqn:E; constructor.\n  - destruct H. rewrite eqb_spec_intro0 in E. assumption.\n  - intros eq. destruct H. rewrite <- eqb_spec_intro0, E in eq.\n    discriminate eq.\nDefined.\n\nLemma messageSentTrivial : forall {A} `{eqb_spec A}\n  (msg : OutgoingMessage A)\n  (msgMap : queue (OutgoingMessage A))\n  (stateMap : mapping address (queue (OutgoingMessage A)))\n  (ind : address),\n  is_true (isMessageSent msg ind 0 (stateMap [ind] \u2190 (hmapPush msg msgMap))).\nAdmitted.\n\nLemma insert_find : forall {K V} `{eqb_spec K}\n  (vd v : V) (k : K) (li : CommonInstances.listPair K V),\n  Common.hmapFindWithDefault vd k (xHMapInsert k v li) = v.\nAdmitted.\n\n#[export]\nInstance boolean_eqb_spec : eqb_spec boolean.\nProof.\n  constructor. intros [] []; intuition.\nDefined.\n\n#[export]\nInstance uint8_eqb_spec : forall n, eqb_spec (XUBInteger n).\nProof.\n  constructor. intros a b. destruct a, b. simpl.\n  destruct (N.eqb_spec x x0).\n  - split. subst x0. reflexivity. reflexivity.\n  - split. intros. discriminate. intros. injection H. intros.\n    exfalso. congruence.\nDefined.\n\n#[export]\nInstance cell_eqb_spec : eqb_spec cell_.\nProof.\n  constructor. intros a b. unfold Common.eqb, cellBoolEq.\n  destruct (cellEq_Dec _ _). destruct dec.\n  - subst b. split; reflexivity.\n  - split. intros H; discriminate H. intros eq. exfalso. congruence.\nDefined.\n\n#[export]\nInstance IDFromGiver_eqb_spec : eqb_spec Interface.IDFromGiver.\nProof.\n  constructor. intros a b. destruct a; (destruct b;\n  try (split; [intros H; simpl in H; discriminate H\n  |intros H; discriminate H])).\n  all: unfold Common.eqb, IDFromGiver_booleq; (\n    repeat match goal with |- context [Common.eqb ?x1 ?x2] =>\n    destruct (eqb_spec_reflect x1 x2); [subst x2|\n    simpl; split;\n    [ intros; discriminate\n    | let H := fresh \"H\" in intros H; injection H; intros; exfalso; congruence ] ] end\n  );\n  split; reflexivity.\nDefined.\n\n#[export]\nInstance ProdStrInt_eqb_spec : eqb_spec (string * nat)%type.\nProof.\n  constructor. intros [a1 a2] [b1 b2]. split.\n  - intros H. simpl in H. destruct (Nat.eqb_spec a2 b2).\n    2:{ destruct (CommonInstances.string_dec_bool a1 b1); discriminate H. }\n    unfold CommonInstances.string_dec_bool in H. destruct (string_dec a1 b1).\n    + subst a1 a2. reflexivity.\n    + discriminate H.\n  - intros H. injection H as H1 H2. subst b1 b2.\n    simpl. rewrite Nat.eqb_refl. unfold CommonInstances.string_dec_bool.\n    destruct (string_dec a1 a1). reflexivity. exfalso. apply n. reflexivity.\nDefined.\n\n#[export]\nInstance PhantomType_eqb_spec : eqb_spec PhantomType.\nProof.\n  constructor. intros [] []. split; reflexivity.\nDefined.\n\n#[export]\nInstance IKWFundParticipant_eqb_spec : eqb_spec Interface.IKWFundParticipant.\nProof.\n  constructor. intros a b. destruct a; (destruct b;\n  try (split; [intros H; simpl in H; discriminate H\n  |intros H; discriminate H])).\n  all: unfold Common.eqb, IKWFundParticipant_booleq; (\n    repeat match goal with |- context [Common.eqb ?x1 ?x2] =>\n    destruct (eqb_spec_reflect x1 x2); [subst x2|\n    simpl; split;\n    [ intros; discriminate\n    | let H := fresh \"H\" in intros H; injection H; intros; exfalso; congruence ] ] end\n  );\n  split; reflexivity.\nDefined.\n", "meta": {"author": "kwpc-io", "repo": "kwf_contracts", "sha": "3c4030ba73392bb76431d1880b383b816b3bf1e2", "save_path": "github-repos/coq/kwpc-io-kwf_contracts", "path": "github-repos/coq/kwpc-io-kwf_contracts/kwf_contracts-3c4030ba73392bb76431d1880b383b816b3bf1e2/src/Contracts/ProofsCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.19394753359820396}}
{"text": "(*\n * Copyright (c) 2020 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\n(* This file contains intensional functions necessary to\n * describe the semantics of our AST.\n *\n * It would be great if we could eliminate this, but it\n * requires some more thought.\n *\n * Another option would be to completely pre-process the\n * AST and remove these nodes.\n *)\nRequire Import Coq.ZArith.ZArith_base.\nRequire Import bedrock.lang.cpp.ast.\n\n(* this function determines whether the type is an aggregate type, i.e.\n * arrays and objects.\n *)\nFixpoint is_aggregate (t : type) : bool :=\n  match t with\n  | Tnamed _\n  | Tarray _ _ => true\n  | Tqualified _ t => is_aggregate t\n  | _ => false\n  end.\n\nFixpoint is_void (t : type) : bool :=\n  match t with\n  | Tqualified _ t => is_void t\n  | Tvoid => true\n  | _ => false\n  end.\n\n(* this determines whether a type is initializable from a primitive.\n *)\nFixpoint prim_initializable (t : type) : bool :=\n  match t with\n  | Tpointer _\n  | Tnum _ _\n  | Tbool\n  | Tenum _\n  | Tnullptr => true\n  | Tqualified _ t => prim_initializable t\n  | _ => false\n  end.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/semantics/intensional.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.19392490803244222}}
{"text": "Require Import Raft.\n\nSection NoAppendEntriesToSelfInterface.\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_append_entries_to_self (net : network) : Prop :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      pDst p = pSrc p ->\n      False.\n\n  Class no_append_entries_to_self_interface : Prop :=\n    {\n      no_append_entries_to_self_invariant :\n        forall net,\n          raft_intermediate_reachable net ->\n          no_append_entries_to_self net\n    }.\nEnd NoAppendEntriesToSelfInterface.", "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/NoAppendEntriesToSelfInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.1939248938996477}}
{"text": "Require Import VST.concurrency.conclib.\nRequire Import VST.floyd.proofauto.\nRequire Import VST.atomics.general_locks.\nRequire Import Coq.Sets.Ensembles.\nRequire Import bst.puretree.\nRequire Import bst.bst_template_coupling.\nRequire Import bst.coupling_lib.\nRequire Import bst.coupling_traverse.\nRequire Import VST.floyd.library.\n\nDefinition treebox_new_spec :=\n  DECLARE _treebox_new\n  WITH gv: globals\n  PRE  [  ]\n    PROP () PARAMS () GLOBALS (gv) SEP (mem_mgr gv)\n  POST [ tptr (tptr t_struct_tree_t) ]\n    EX p: val, EX newt: val, EX lock: val,\n    PROP ()\n    LOCAL (temp ret_temp p)\n    SEP (mem_mgr gv; atomic_int_at Ews (vint 0) lock;\n         malloc_token Ews t_struct_tree_t newt;\n         data_at Ews t_struct_tree_t (Vlong (Int64.repr 0), lock) newt;\n         malloc_token Ews (tptr t_struct_tree_t) p;\n         data_at Ews (tptr t_struct_tree_t) newt p).\n\nLemma body_treebox_new: semax_body Vprog Gprog f_treebox_new treebox_new_spec.\nProof.\n  start_function.\n  forward_call (tptr t_struct_tree_t, gv).\n  Intros p. (* treebox p *)\n  forward_call (t_struct_tree_t, gv).\n  Intros newt. (* tree_t *newt *)\n  forward.\n  forward_call (gv).\n  Intros l. (* lock_t *l *)\n  forward.\n  forward.\n  sep_apply atomic_int_isptr.\n  Intros.\n  forward_call release_nonatomic (l).\n  forward.\n  Exists p. Exists newt. Exists l.\n  entailer !.\nQed.\n\nDefinition turn_left_spec :=\n DECLARE _turn_left\n  WITH l: val, tl: val, x: Z, vx: val, tll: val,\n       r: val, tr: val, y: Z, vy: val, mid: val, trr: val\n  PRE  [tptr t_struct_tree_t, tptr t_struct_tree_t]\n    PROP (is_pointer_or_null mid)\n    PARAMS (l; r) GLOBALS ()\n    SEP (field_at Ews (t_struct_tree_t) [StructField _t] tl l;\n         field_at Ews (t_struct_tree_t) [StructField _t] tr r;\n         data_at Ews t_struct_tree (Vint (Int.repr x), (vx, (tll, r))) tl;\n         data_at Ews t_struct_tree (Vint (Int.repr y), (vy, (mid, trr))) tr)\n  POST [ Tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (field_at Ews (t_struct_tree_t) [StructField _t] tr l;\n         field_at Ews (t_struct_tree_t) [StructField _t] tl r;\n         data_at Ews t_struct_tree (Vint (Int.repr x), (vx, (tll, mid))) tl;\n         data_at Ews t_struct_tree (Vint (Int.repr y), (vy, (r, trr))) tr).\n\nLemma body_turn_left: semax_body Vprog Gprog f_turn_left turn_left_spec.\nProof.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward.\n  forward.\n  forward.\n  forward.\n  entailer!.\nQed.\n\nProgram Definition pushdown_left_spec :=\n DECLARE _pushdown_left\n ATOMIC TYPE (rmaps.ConstType\n                (val * val * lock_handle * share * Z * val *\n                 lock_handle * lock_handle * val * val *\n                   gname * gname * globals * range *\n                   gname * gname * gname))\n OBJ M INVS \u2205\n WITH p, tp, lockp, gsh, x, vx,\n      locka, lockb, ta, tb,\n       g, g_root, gv, r,\n       g_del, ga, gb\n  PRE [ tptr t_struct_tree_t ]\n    PROP (Int.min_signed <= x <= Int.max_signed;\n          tc_val (tptr Tvoid) vx;\n          key_in_range x r = true)\n    PARAMS (p) GLOBALS (gv)\n    SEP (mem_mgr gv;\n         in_tree g g_del;\n         my_half g_del gsh (r, Some (Some (x, vx, ga, gb)));\n         field_at Ews t_struct_tree_t [StructField _t] tp p;\n         data_at Ews t_struct_tree (Vint (Int.repr x), (vx, (ta, tb))) tp;\n         ltree g g_del lsh2 gsh2 gsh p lockp;\n         ltree g ga lsh1 gsh1 gsh1 ta locka;\n         ltree g gb lsh1 gsh1 gsh1 tb lockb;\n         malloc_token Ews t_struct_tree tp;\n         (* malloc_token Ews t_lock (ptr_of lockp); *)\n         malloc_token Ews t_struct_tree_t p) | (tree_rep g g_root M)\n  POST [ Tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (mem_mgr gv) | (tree_rep g g_root (base.delete x M)).\n\nProgram Definition delete_spec :=\n DECLARE _delete\n ATOMIC TYPE (rmaps.ConstType (_ * _ * _ * _ * _ * _ * _))\n         OBJ M INVS \u2205\n WITH b, x, lock, gv, sh, g, g_root\n PRE  [ tptr (tptr t_struct_tree_t), tint]\n    PROP (Int.min_signed <= x <= Int.max_signed; writable_share sh)\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 [ Tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (mem_mgr gv; nodebox_rep g g_root sh lock b) | (tree_rep g g_root (base.delete x M)).\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n     surely_malloc_spec; traverse_spec; findnext_spec; pushdown_left_spec; turn_left_spec;\n                             delete_spec; freelock_spec ]).\n\n(* Proving delete function satisfies spec *)\nLemma body_delete: semax_body Vprog Gprog f_delete delete_spec.\nProof.\n  start_function.\n  unfold nodebox_rep, ltree.\n  Intros np.\n  forward_call (t_struct_pn, gv).\n  Intros nb.\n  forward.\n  forward.\n  forward.\n  forward.\n  set (AS := atomic_shift _ _ _ _ _).\n  (* acquire(pn->n->lock); *)\n  forward_call acquire_inv_simple (sh, lock, node_lock_inv (Share.split gsh1).1 g np g_root lock).\n  {\n    set Q1:= fun (b : (bool * ( val * (val * (lock_handle * (share * (gname * node_info))))))%type) =>\n              if b.1 then AS else AS.\n    (* traverse(pn, x, nullval) *)\n    (* we assign value to nullval*)\n    forward_call (nb, np, sh, lock, x, nullval, gv, g, g_root, Q1).\n    {\n      unfold pn_rep_1, node_lock_inv'.\n      Exists (default_val t_struct_pn).1.\n      unfold node_lock_inv.\n      sep_apply self_part_eq.\n      assert (lsh2 <> Share.bot).\n      { apply readable_not_bot. apply readable_lsh2. }\n      auto.\n      entailer !.\n      rewrite -> 2sepcon_assoc. rewrite sepcon_comm.\n      rewrite -> sepcon_assoc; apply sepcon_derives; [|cancel].\n      unfold atomic_shift; iIntros \"AU\"; iAuIntro; unfold atomic_acc; simpl.\n      iMod \"AU\" as (m) \"[Hm HClose]\".\n      iModIntro.\n      iExists m.\n      iFrame \"Hm\".\n      iSplit; iFrame.\n      { by iApply bi.and_elim_l. }\n      {\n        iDestruct \"HClose\" as \"[HClose _]\".\n        iIntros (pt) \"[H _]\".\n        iMod (\"HClose\" with \"H\") as \"H\".\n        iModIntro.\n        unfold Q1.\n        destruct (decide (pt.1 = true)). { rewrite e; iFrame. }\n        { apply not_true_is_false in n; rewrite n; iFrame. }\n      }\n    }\n    Intros pt.\n    destruct pt as (fl & (p1 & (tp & (lock_in & (gsh & (g_in & r)))))).\n    simpl in H1, H2.\n    destruct fl.\n    simpl.\n    change emp with seplog.emp.\n    - destruct H2.\n      forward_if (\n          PROP ( )\n            LOCAL (temp _t'4 (ptr_of lock_in); temp _t'3 p1; temp _t'2 Vtrue;\n                   temp _t'7 (ptr_of lock); temp _t'6 np; temp _t'8 np;\n                   temp _pn__2 nb; gvars gv; temp _t b; temp _x (vint x))\n            SEP (Q; mem_mgr gv; data_at Ews t_struct_pn (p1, p1) nb;\n                 my_half g_root (Share.split gsh1).2 (Neg_Infinity, Pos_Infinity, None);\n                 data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t (DOT _lock) (ptr_of lock) np;\n                 lock_inv sh lock\n                   (selflock (node_lock_inv_pred (Share.split gsh1).1 g np g_root (ptr_of lock))\n                      gsh2 lock);\n                 malloc_token Ews t_struct_pn nb)); unfold node_lock_inv_new.\n      + pose proof (Int.one_not_zero); easy.\n      + (* prove satisfies if_condition*)\n        Intros.\n        forward.\n        forward.\n        rewrite H3.\n        unfold tree_rep_R, Q1.\n        rewrite -> if_true by auto.\n        simpl.\n        Intros.\n        gather_SEP AS (my_half g_in _ _) (in_tree g _).\n        viewshift_SEP 0 (Q * (in_tree g g_in * my_half g_in gsh r)).\n        {\n          go_lower.\n          unfold AS.\n          simpl.\n          apply sync_commit_same1.\n          intros t.\n          unfold tree_rep at 1.\n          Intros tg.\n          assert_PROP (Ensembles.In (find_ghost_set tg g_root) g_in) as Hin.\n          { sep_apply node_exist_in_tree. entailer!. }\n          sep_apply (ghost_tree_rep_public_half_ramif _ _ (Neg_Infinity, Pos_Infinity) _ Hin).\n          Intros r0.\n          iIntros \"([[? ?] Hclose] & ? & ?) !>\".\n          iExists r0; iFrame.\n          iIntros \"% !> [? ?] !>\".\n          apply node_info_incl' in H12 as []. \n          iExists tt; iFrame.\n          unfold tree_rep; iExists tg; iFrame.\n          destruct r, r0; simpl in *; subst.\n          iSplit.\n          { iPureIntro; repeat (split; auto).\n            rewrite delete_notin; auto; subst.\n            eapply range_info_not_in_gmap; last eassumption; auto.\n            eapply key_in_range_incl; eauto.\n          }\n          iApply \"Hclose\"; iFrame.\n        }\n        (*  (_release2(_t'4); *)\n        change emp with seplog.emp.\n        forward_call release_self (gsh2, lock_in,\n                    node_lock_inv_pred gsh g p1 g_in (ptr_of lock_in)).\n        {\n          unfold node_lock_inv_pred at 3, sync_inv.\n          Exists r.\n          rewrite node_rep_def.\n          unfold node_lock_inv, tree_rep_R.\n          Exists nullval.\n          rewrite -> if_true by auto.\n          entailer !.\n        }\n        entailer !.\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 np.\n        entailer !.\n   - (* _pushdown_left(_t'5);) *)\n     unfold Q1.\n     destruct H2 as ( ?  & v2 & g21 & g22 & ?).\n      simpl.\n      forward_if(\n          PROP ( )\n            LOCAL (temp _t'5 p1; temp _t'2 Vfalse; temp _t'7 (ptr_of lock); temp _t'6 np; \n                   temp _t'8 np; temp _pn__2 nb; gvars gv; temp _t b; temp _x (vint x))\n            SEP (Q; mem_mgr gv; data_at Ews t_struct_pn (p1, p1) nb;\n                 my_half g_root (Share.split gsh1).2 (Neg_Infinity, Pos_Infinity, None);\n                 data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t (DOT _lock) (ptr_of lock) np;\n                 lock_inv sh lock\n                   (selflock (node_lock_inv_pred (Share.split gsh1).1 g np g_root (ptr_of lock))\n                      gsh2 lock);\n                 malloc_token Ews t_struct_pn nb)).\n      + unfold node_lock_inv_new, tree_rep_R.\n        rewrite -> if_false; auto.\n        Intros g1 g2 x1 v p1' p2' l1 l2.\n        forward.\n        destruct r as (x0 & y0).\n        simpl in H8.\n        simpl in H5. subst y0.\n        injection H3.\n        intros. subst x1. subst v2. subst g21. subst g22.\n        assert_PROP (field_compatible t_struct_tree_t [] p1) by entailer !.\n        forward_call (p1, tp, lock_in, gsh, x, v, l1, l2, p1', p2',\n                       g, g_root, gv, x0, g_in, g1, g2, Q).\n        {\n          unfold AS.\n          unfold ltree.\n          entailer !.\n          rewrite ->  5sepcon_assoc; apply sepcon_derives; [|cancel].\n          unfold atomic_shift; iIntros \"AU\"; iAuIntro; unfold atomic_acc; simpl.\n          iMod \"AU\" as (m) \"[Hm HClose]\".\n          iModIntro.\n          iExists m.\n          iFrame \"Hm\".\n          iSplit; iFrame.\n          { by iApply bi.and_elim_l. }\n          {\n            iDestruct \"HClose\" as \"[_ HClose]\".\n            done.\n          }\n        }\n        entailer !.\n      + (* contradiction, since  Int.one = Int.zero *)\n       pose proof Int.one_not_zero; contradiction.\n      + (* _free(_pn__2); *)\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 np.\n        entailer !.\n     }\nQed.\n\nLemma body_pushdown_left: semax_body Vprog Gprog f_pushdown_left pushdown_left_spec.\nProof.\n  start_function.\n  forward_loop (\n    EX p : val, EX lockp: lock_handle, EX tb : val, EX lockb: lock_handle,\n              EX gb : gname, EX g_del : gname, EX r : range, EX gsh : share,\n    PROP (key_in_range x r = true)\n    LOCAL (temp _tgp p;  gvars gv)\n    SEP (atomic_shift (\u03bb M, tree_rep g g_root M) \u22a4 \u2205 (\u03bb M (_ : ()),\n             fold_right_sepcon [tree_rep g g_root (delete x M)]) (\u03bb _ : (), Q);\n        mem_mgr gv;\n        in_tree g g_del; my_half g_del gsh (r, Some (Some (x, vx, ga, gb)));\n        field_at Ews t_struct_tree_t [StructField _t] tp p;\n        data_at Ews t_struct_tree (vint x, (vx, (ta, tb))) tp;\n         ltree g g_del lsh2 gsh2 gsh p lockp;\n         ltree g ga lsh1 gsh1 gsh1 ta locka;\n         ltree g gb lsh1 gsh1 gsh1 tb lockb;\n        malloc_token Ews t_struct_tree tp;\n        (* malloc_token Ews t_lock (ptr_of lockp); *)\n         malloc_token Ews t_struct_tree_t p))%assert.\n  { Exists p lockp tb lockb gb g_del r gsh.\n    entailer!.\n  }\n  clear dependent g_del r gsh.\n  Intros p' lockp' tb' lockb' gb' g_del r gsh.\n  unfold ltree at 1; Intros.\n  change emp with seplog.emp.\n  forward.\n  forward.\n  forward.\n  unfold ltree at 2; Intros.\n  forward.\n  forward_call acquire_inv_simple  (gsh1, lockb', node_lock_inv gsh1 g tb' gb' lockb').\n  Local Typeclasses eauto := 5.\n  rewrite later_sepcon.\n  rewrite later_sepcon.\n  unfold sync_inv at 1.\n  rewrite <- sepcon_assoc.\n  rewrite sepcon_assoc.\n  rewrite later_exp'; [ |apply (Neg_Infinity, Pos_Infinity, None)].\n  Intros b; destruct b as (rangeb, g_infob).\n  rewrite later_sepcon.\n  rewrite node_rep_def.\n  rewrite later_exp'; last apply ta.\n  Intros tbv; simpl.\n  rewrite later_sepcon.\n  rewrite later_sepcon.\n  rewrite later_sepcon.\n  Intros.\n  forward.\n  forward_if.\n  { subst.\n    unfold tree_rep_R.\n    if_tac; [| contradiction].\n    Intros.\n    change emp with seplog.emp.\n    forward.\n    unfold ltree at 1; Intros.\n    forward.\n    forward_call acquire_inv_simple (gsh1, locka, node_lock_inv gsh1 g ta ga locka).\n    rewrite later_sepcon.\n    rewrite later_sepcon.\n    unfold sync_inv at 1.\n    rewrite <- sepcon_assoc.\n    rewrite sepcon_assoc.\n    rewrite later_exp'; [ |apply (Neg_Infinity, Pos_Infinity, None)].\n    Intros a; destruct a as (rangea, g_infoa).\n    rewrite later_sepcon.\n    rewrite node_rep_def.\n    rewrite -> later_exp'; last apply ta.\n    Intros tav; simpl. \n    rewrite later_sepcon.\n    rewrite later_sepcon.\n    rewrite later_sepcon.\n    Intros.\n    forward.\n    forward.\n    assert_PROP (tp <> nullval) by entailer !.\n    forward_call (t_struct_tree, tp, gv).\n    { rewrite if_false; auto. cancel. }\n    forward_call freelock_self (gsh1, gsh2, lockb',\n        node_lock_inv_pred gsh1 g tb' gb' (ptr_of lockb')).\n    { unfold node_lock_inv at 2; cancel. }\n    assert_PROP (tb' <> nullval) by entailer !.\n    forward_call (t_struct_tree_t, tb', gv).\n    {\n      rewrite if_false; auto.\n      unfold_data_at (data_at_ Ews t_struct_tree_t tb'); simpl; cancel.\n      rewrite <- (field_at_share_join _ _ Ews _ [StructField _lock] _ tb') by eauto; cancel.\n    }\n    forward.\n    forward_call freelock_self (gsh1, gsh2, locka, node_lock_inv_pred gsh1 g ta ga (ptr_of locka)).\n    { unfold node_lock_inv; cancel. }\n    assert_PROP (ta <> nullval) by entailer !.\n    forward_call (t_struct_tree_t, ta, gv).\n    {\n      rewrite -> if_false; auto.\n      unfold_data_at (data_at_ Ews t_struct_tree_t ta); simpl; cancel.\n      rewrite <- (field_at_share_join _ _ Ews _ [StructField _lock] _ ta) by eauto; cancel.\n    }\n    destruct r as (n, n0).\n    assert_PROP (g_infoa <> None) as infoa.\n    {\n      unfold tree_rep_R.\n      if_tac.\n      change emp with seplog.emp.\n      Intros.\n      entailer!.\n      Intros a' b' c' d' e' a1 a2 a3. entailer!.\n    }\n    gather_SEP (atomic_shift _ _ _ _ _) (my_half g_del _ _) (in_tree g g_del)\n      (in_tree g ga) (in_tree g gb') (my_half gb' _ _) (my_half ga _ _) (tree_rep_R tav _ g_infoa g).\n    rewrite -> 5sepcon_assoc.\n    viewshift_SEP 0 (Q * (EX o2, EX n1 n2: number, !!(key_in_range x (n1,n2) = true) &&\n      my_half g_del gsh ((n1, n2), o2) * in_tree g g_del * tree_rep_R tav (n1, n2) o2 g)).\n    {\n      go_lower. eapply sync_commit_gen1. rewrite <- sepcon_assoc.\n      - intros. iIntros \"[Ha Hb]\".\n        iDestruct \"Ha\" as \"((H1 & H3) & (H2 & (H4 & H5 & H6)))\".\n        iPoseProof ((ghost_tree_pushdown_left _ _ _ g_del ga gb') with \"[$H1 $H2 $Hb]\") as \"Hadd\".\n        iDestruct \"Hadd\" as (n1 n2 o) \"[[Hmya Ha] Hb]\".\n        iExists (n1, n2, Some o).\n        instantiate (1 := vx). instantiate (1 := x). iFrame.\n        iIntros \"!> %\".\n        apply node_info_incl' in H13 as [? Heq]; inv Heq.\n        iSpecialize (\"Hb\" with \"[% //]\").\n        iDestruct \"Hb\" as (o3) \"[Ha Hb]\".\n        iDestruct (\"Hb\" with \"H3\") as (o2) \"(Hb & Hd)\".\n        iDestruct (public_sub with \"[$Hb $H5]\") as %[? J1].\n        iDestruct (public_sub with \"[$Ha $H4]\") as %[? J2].\n        iPoseProof (public_update with \"[$Hb $H5]\") as \">Hga\".\n        iPoseProof (public_update with \"[$Ha $H4]\") as \">Hgb\".\n        instantiate (1:= (Finite_Integer x, n2, Some o3)).\n        instantiate (1:= (n1, Finite_Integer x, Some o2)).\n        inv J2.\n        iIntros \"!>\".\n        iExists ((n, n0), Some o2), ((n1, n2), Some o2); iSplit.\n        { iPureIntro. intros (?, ?) H_sep. destruct H_sep; split; auto; simpl in *.\n          inv H16; [constructor|].\n          simpl in *. auto. simpl in *.\n          apply sepalg.join_unit2.\n          apply psepalg.None_unit; eauto. auto.\n          inversion H20. intros; inversion H17; subst. auto.\n        }\n        iIntros \"[He Hf]\".\n        destruct g_infoa; try contradiction; inv J1.\n        repeat logic_to_iris.\n        iPoseProof (public_part_update(P := node_ghost) _ _ _ _ (n1, n2, Some o) (n1, n2, Some o)\n                     with \"[$He $Hf]\") as \"[_ >[He Hf]]\".\n        { intros. destruct H15. split. split; auto; simpl.\n          hnf in H15; hnf.\n          symmetry; rewrite puretree.merge_comm; eapply merge_again.\n          symmetry; rewrite puretree.merge_comm; eauto.\n          intros; subst; auto.\n        }\n        rewrite exp_sepcon1; iExists tt.\n        assert (key_in_range x (n1, n2) = true) by (eapply key_in_range_incl; eauto).\n        iMod (\"Hd\" with \"[$Hmya $Hf]\") as \"[$ Hf]\"; first auto.\n        iDestruct \"Hga\" as \"(Hga1 & (Hga2 & Hga3))\".\n        iDestruct \"Hgb\" as \"(Hgb1 & (Hgb2 & Hgb3))\".\n        iModIntro; iExists (Some o), n1, n2; iFrame \"Hf\".\n        iFrame \"He\".\n        iSplit; first auto.\n        rewrite range_incl_tree_rep_R; last first.\n        eapply range_incl_trans, key_in_range_l; eauto.\n        simpl in *. apply H5. iFrame; iClear \"\u2217\"; done.\n    }\n    forward_call release_self (gsh2, lockp',\n                    node_lock_inv_pred gsh g p' g_del (ptr_of lockp')).\n    {\n      Intros o2 n1 n2.\n      unfold node_lock_inv.\n      unfold node_lock_inv_pred.\n      unfold sync_inv.\n      Exists (n1, n2, o2).\n      rewrite node_rep_def.\n      simpl.\n      Exists tav.\n      cancel.\n    }\n    forward.\n  }\n  abbreviate_semax.\n  unfold tree_rep_R at 1.\n  assert_PROP (tbv <> nullval) by entailer !.\n  rewrite -> if_false; auto.\n  Intros gbl gbr k v tbl tbr ltbl ltbr.\n  forward_call (p', tp, x, vx, ta, tb', tbv, k, v, tbl, tbr).\n  forward.\n  destruct r as (rangel, rangeh).\n  gather_SEP (atomic_shift _ _ _ _ _) (my_half g_del _ _) (my_half gb' _ _)\n    (in_tree g gb') (in_tree g g_del).\n  repeat rewrite sepcon_assoc. do 2 rewrite <- sepcon_assoc.\n  replace_SEP 0 (|={\u22a4}=> atomic_shift (\u03bb M, tree_rep g g_root M) \u22a4 \u2205\n          (\u03bb M (_ : ()), tree_rep g g_root (delete x M) * emp) (\u03bb _ : (), Q) *\n                   EX rangedell, EX rangedelh: _,\n        !!(range_incl (rangel, rangeh) (rangedell, rangedelh) = true /\\\n             range_incl rangeb (rangedell, rangedelh) = true /\\ x < k) &&\n      my_half g_del gsh ((rangedell, rangedelh), Some (Some (k, v, gb', gbr))) *\n          my_half gb' gsh1 ((rangedell, Finite_Integer k), Some (Some (x, vx, ga, gbl))) *\n          (in_tree g gb' * in_tree g g_del)).\n  {\n    go_lower.\n    rewrite !sepcon_assoc.\n    eapply atomic_rollback_fupd.\n    - intros.\n      iIntros \"((g_del & (gb & (in_gb & in_gdel))) & tree_rep)\".\n      iPoseProof ((ghost_tree_pushdown_left _ _ _ g_del ga gb')\n                   with \"[$tree_rep $in_gb $in_gdel]\") as (n1 n2 o) \"[Ha Hb]\".\n      iDestruct (public_sub with \"[$g_del $Ha]\") as %[? J]; inv J.\n      instantiate (1 := vx). instantiate (1 := x).\n      iPoseProof (\"Hb\" with \"[% //]\") as (o3) \"[Hpubb Hb]\".\n      iPoseProof (bi.and_elim_r with \"Hb\") as \"Hb\".\n      iSpecialize (\"Hb\" $! gbl gbr k v).\n      logic_to_iris.\n      iDestruct (public_sub with \"[$g_del $Ha]\") as %[? J1].\n      iDestruct (public_sub with \"[$gb $Hpubb]\") as %[Hincl J2].\n      iDestruct \"Ha\" as \"[Hmya Ha]\".\n      iPoseProof (public_part_update(P := node_ghost) _ _ _ _ (n1, n2, Some (Some (k, v, gb', gbr)))\n                    (n1, n2, Some (Some (k, v, gb', gbr)))\n                   with \"[$g_del $Ha]\") as \"[_ >[Hmyga Hpubga]]\".\n      { intros. destruct H13. split. split; auto; simpl.\n        hnf in H13; hnf.\n        symmetry; rewrite puretree.merge_comm; eapply merge_again.\n        symmetry; rewrite puretree.merge_comm; eauto.\n        simpl in *.\n        inversion H14.\n        apply sepalg.join_unit2. apply psepalg.None_unit. reflexivity.\n        subst. inversion H18.\n        intros; auto.\n      }\n      iPoseProof (public_update _ _ _ (n1, Finite_Integer k, Some (Some (x, vx, ga, gbl)))\n                     with \"[$gb $Hpubb]\") as \">(Hmygb & Hpubgb)\".\n      inv J2.\n      assert (key_in_range x (n1, n2) = true).\n      { eapply key_in_range_incl; eauto. }\n      assert (x < k).\n      { eapply key_in_range_incl in Hincl; [|eauto].\n        apply andb_prop in Hincl as []; simpl in *; lia.\n      }\n      iDestruct (\"Hb\" with \"[$Hpubgb $Hmya $Hpubga]\") as \">(($ & Hgdel) & Hgb)\".\n      { iPureIntro; repeat (split; auto). simpl; lia. }\n      iExists n1, n2; iFrame.\n      iPureIntro; repeat (split; auto).\n      eapply range_incl_trans; try eassumption.\n      apply (key_in_range_r _ (_, _)); auto.\n   }\n   match goal with |-context[|={\u22a4}=> ?P] => viewshift_SEP 0 P by entailer! end.\n   Intros rangedell rangedelh.\n   gather_SEP (lock_inv _ lockb' (node_lock_inv gsh1 g tb' gb' lockb')) (self_part _ lockb').\n   unfold node_lock_inv at 1.\n   sep_apply self_part_eq.\n   apply readable_not_bot.\n   apply readable_gsh2.\n   unfold ltree at 1.\n   unfold ltree at 2.\n   Intros.\n   forward_call release_self (gsh2, lockp', node_lock_inv_pred gsh g p' g_del (ptr_of lockp')).\n   {\n     unfold node_lock_inv_pred at 4.\n     unfold sync_inv.\n     Exists ((rangedell, rangedelh), Some (Some (k, v, gb', gbr))).\n     rewrite node_rep_def; simpl. Exists tbv; cancel.\n     unfold tree_rep_R.\n     rewrite -> if_false; auto.\n     Exists gb' gbr k v tb' tbr lockb' ltbr; cancel.\n     unfold node_lock_inv. cancel.\n     unfold ltree at 1.\n     do 2 rewrite sepcon_andp_prop'.\n     apply andp_right.\n     {\n       apply prop_right.\n       repeat (split; auto).\n       eapply key_in_range_incl; eauto.\n     }\n     {\n       cancel. eapply derives_trans.\n       2: { apply sepcon_derives; [apply now_later| apply derives_refl]. }\n       entailer !.\n     }\n   }\n   Exists tb' lockb' tbl ltbl gbl gb' (rangedell, Finite_Integer k) gsh1; entailer!.\n   { eapply key_in_range_incl in H1; [|eauto].\n     unfold key_in_range in *; apply andb_prop in H1 as [-> _]; simpl; lia.\n   }\n   unfold ltree.\n   entailer !.\n   apply derives_refl.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/concurrency/templates/coupling_delete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.1939248878624196}}
{"text": "From hahn Require Import Hahn.\nRequire Import Exec.\nRequire Import Events.\n\nSection Scdrf.\n\nLemma drf_tot__hb_sc e X Y :\n  well_formed e ->\n  consistent e ->\n  data_race_free e ->\n  tot e X Y ->\n  overlap X Y ->\n  writes e X \\/ writes e Y ->\n  hb e X Y \\/ (same_loc X Y /\\ sc e X /\\ sc e Y).\nProof.\n  intros wf cst drf totXY overlapXY wXY.\n  unfold data_race_free in drf.\n  destruct drf with X Y as [hbXY | [hbYX | [[nWX nWY] | [novrlpXY | [slXY [scX scY]]]]]];\n  auto.\n  - exfalso.\n    destruct wf_tot with e as [[irrefl trans] tot]; try assumption.\n    apply irrefl with X.\n    apply trans with Y; try assumption.\n    apply cst_hb_tot; try assumption.\n    apply cst_ufxd.\n    assumption.\n  - exfalso.\n    destruct wXY; contradiction.\n  - exfalso.\n    destruct overlapXY.\n      apply novrlpXY with x.\n      destruct H.\n      split; assumption.\nQed.\n\nTheorem sc_drf e :\n  well_formed e ->\n  consistent e ->\n  data_race_free e ->\n  seqcst e.\nProof.\n\n  intros wf cst drf.\n  unfold seqcst.\n  unfolder.\n  intros n.\n  split.\n  { intros Y [X [rfbYX totXY]].\n    assert (hb e X Y \\/ (same_loc X Y /\\ sc e X /\\ sc e Y)) as [hbXY | [slXY [scX scY]]]. {\n      apply drf_tot__hb_sc; auto.\n      exists n. split; destruct (rfb__dom e X Y n wf rfbYX); try assumption.\n      right. eapply rfb__w; eassumption.\n    }\n    - apply (cst_rf_hb e (cst_ufxd e cst) X).\n      exists Y.\n      split; try assumption.\n      econstructor. eauto.\n    - destruct (wf_tot e wf) as [[irrefl trans] _].\n      apply irrefl with X.\n      apply trans with Y; try assumption. \n      apply cst_hb_tot; try apply cst_ufxd; try assumption.\n      constructor. left. right.\n      apply sw_intro; auto.\n      eexists; eauto.\n      apply same_loc_sym. auto.\n  }\n  intros Z' [Z [[eqZZ' [wZ domZn]] [X [totZX [Y [rfbYX totYZ]]]]]].\n  subst.\n  assert (in_dom n Y /\\ in_dom n X) as [domYn domXn]. {\n    apply rfb__dom with e; assumption.\n  }\n  assert (hb e Y Z \\/ (same_loc Y Z /\\ sc e Y /\\ sc e Z)) as drfYZ. {\n    apply drf_tot__hb_sc; auto.\n    exists n; auto.\n  }\n  assert (hb e Z X \\/ (same_loc Z X /\\ sc e Z /\\ sc e X)) as drfZX. {\n    apply drf_tot__hb_sc; auto.\n    exists n; auto.\n  }\n  assert (hb e Y X \\/ (same_loc Y X /\\ sc e Y /\\ sc e X)) as drfYX. {\n    apply drf_tot__hb_sc; auto.\n    - destruct (wf_tot e wf) as [[_ trans] _].\n      apply trans with Z; assumption.\n    - exists n; auto.\n    - left.\n      apply rfb__w with X n; assumption.\n  }\n  destruct drfYZ as [hbYZ | [slYZ [ScY scZ]]];\n  destruct drfZX as [hbZX | [slZX [ScZ' ScX]]];\n  [ apply (cst_rf_hb_hb e (cst_ufxd e cst) n Z) |\n    destruct drfYX as [hbYX | [slYX [ScY _]]];\n      [apply (cst_ddagger e cst Z) | apply (cst_sw_tot e (cst_ufxd e cst) Z)] |\n    destruct drfYX as [hbYX | [slYX [_ ScX]]];\n      [apply (cst_dagger e cst Z) | apply (cst_sw_tot e (cst_ufxd e cst) Z)] |\n    apply (cst_sw_tot e (cst_ufxd e cst) Z)\n  ];\n  unfolder;\n  split; auto;\n  repeat (eexists; split; eauto).\n  - split; try assumption.\n    apply rfb__rf with n.\n    assumption.\n  - apply sw_intro; auto.\n    apply rfb__rf with n.\n    assumption.\n  - split; try assumption.\n    apply rfb__rf with n.\n    assumption.\n  - split.\n    + apply (cst_hb_tot e (cst_ufxd e cst)).\n      eassumption.\n    + eapply same_loc_trans;\n      try eassumption.\n      apply same_loc_sym.\n      assumption.\n  - apply sw_intro; auto.\n    apply rfb__rf with n.\n    assumption.\n  - apply sw_intro; auto.\n    apply rfb__rf with n.\n    assumption.\n    eapply same_loc_trans;\n    eassumption.\nQed.\n\n\nEnd Scdrf.", "meta": {"author": "Biebar", "repo": "jsrelaxedmemorymodel_coq", "sha": "b0e5d5e470d7fcc579121f9013bf1df4ad5afe69", "save_path": "github-repos/coq/Biebar-jsrelaxedmemorymodel_coq", "path": "github-repos/coq/Biebar-jsrelaxedmemorymodel_coq/jsrelaxedmemorymodel_coq-b0e5d5e470d7fcc579121f9013bf1df4ad5afe69/Scdrf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.1937834969033229}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom Coq Require Import FunctionalExtensionality Reals.\nFrom stdpp Require Import prelude finite.\nFrom VLSM.Lib Require Import Preamble Measurable FinSetExtras RealsExtras ListExtras.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition Equivocation.\nFrom VLSM.Core Require Import Validator ProjectionTraces MessageDependencies.\nFrom VLSM.Core Require Import TraceableVLSM MinimalEquivocationTrace.\nFrom VLSM.Core Require Import BaseELMO UMO MO.\n\nCreate HintDb ELMO_hints.\n\n#[local] Hint Resolve submseteq_tail_l : ELMO_hints.\n\n(** * ELMO Protocol Definitions and Properties\n\n  This module contains definitions and properties of ELMO components and\n  the ELMO protocol.\n*)\n\nSection sec_ELMO.\n\nContext\n  {Address : Type}\n  (State := @State Address)\n  (Observation := @Observation Address)\n  (Message := @Message Address).\n\nContext\n  {measurable_Address : Measurable Address}\n  `{FinSet Address Ca}\n  (threshold : R)\n  `{!ReachableThreshold Address Ca threshold}\n  `{finite.Finite index}\n  (idx : index -> Address)\n  `{!Inj (=) (=) idx}.\n\nDefinition immediate_dependency (m1 m2 : Message) : Prop :=\n  m1 \u2208 messages (state m2).\n\nLemma immediate_dependency_msg_dep_rel :\n  forall dm m : Message,\n    immediate_dependency dm m <-> msg_dep_rel Message_dependencies dm m.\nProof.\n  unfold immediate_dependency, messages, messages',\n    msg_dep_rel, Message_dependencies; cbn.\n  by setoid_rewrite elem_of_list_to_set.\nQed.\n\n#[local] Notation happensBefore := (tc immediate_dependency).\n\n#[local] Infix \"<hb\" := happensBefore (at level 70).\n\nLemma happensBefore_msg_dep :\n  forall dm m : Message,\n    dm <hb m <-> msg_dep_happens_before Message_dependencies dm m.\nProof.\n  by split;\n    (induction 1; [by constructor 1; apply immediate_dependency_msg_dep_rel |]);\n    (etransitivity; [| done]);\n    constructor 1; apply immediate_dependency_msg_dep_rel.\nQed.\n\n(**\n  The full node condition says that a node can receive a message\n  only if the direct observations of that node already include\n  all messages from the direct observations of the state inside\n  the message (not necessarily with the same [Send]/[Receive] label).\n\n  This will let us define validity predicates without needing\n  to recurse into the states inside observations in a state,\n  because a correctly-operating node would have checked the\n  shallow condition for those messages when their observations\n  were added to the state.\n*)\n\nDefinition full_node (s : State) (m : Message) : Prop :=\n  messages (state m) \u2286+ messages s.\n\nLemma full_node_reachable_messages_ind\n  (P : State -> Message -> Prop)\n  (Hnew : forall s l msg\n                 (Hfull : full_node s msg)\n                 (IH : forall m, m \u2208 messages s -> P s m),\n    P (s <+> MkObservation l msg) msg)\n  (Hprev : forall s ob m (IH : P s m), P (s <+> ob) m)\n  :\n  forall s, UMO_reachable full_node s ->\n  forall m, m \u2208 messages s -> P s m.\nProof.\n  unfold full_node in Hnew.\n  by apply UMO_reachable_elem_of_messages_ind; auto.\nQed.\n\nLemma messages_hb_transitive :\n  forall s,\n    UMO_reachable full_node s ->\n  forall m,\n    m \u2208 messages s ->\n  forall m',\n    m' <hb m ->\n    m' \u2208 messages s.\nProof.\n  refine (UMO_reachable_elem_of_messages_ind _ _ _ _ _);\n    [intros | intros s Hs IH m' Hm'%tc_r_iff\n    | intros s Hs mr Hmr%submseteq_list_subseteq IH m' Hm'%tc_r_iff];\n    apply elem_of_messages_addObservation; right.\n  - by itauto.\n  - by destruct Hm' as [| (m & ? & ?)]; [| eapply IH].\n  - destruct Hm' as [| (m & ? & ?)]; [by apply Hmr |].\n    by eapply IH; [apply Hmr |].\nQed.\n\n(**\n  Some claims about the full node condition hold for any UMO-based VLSM\n  whose validity predicate implies the full node condition. By UMO-based we\n  mean a [VLSM] built over the [UMOComponentType] which also has the same\n  transition function as UMO/MO, an initial state predicate that ensures\n  [obs] of an initial state is empty, and a validity predicate that\n  implies [UMOComponentValid].\n  If that's all we know about the VLSM, knowing that a [State] is reachable\n  in that VLSM is only as informative as knowing that the state is\n  [UMO_reachable full_node].\n  (This lemma needs no assumption about [UMOComponentValid] because\n  reachability is the same anyway, because [UMOComponentValid]\n  returns the state unchanged on invalid input.)\n*)\nLemma full_node_VLSM_reachable\n  (VM : VLSMMachine ELMOComponentType)\n  (V := mk_vlsm VM)\n  (VM_transition_is_UMO :\n    forall (l : Label) (s : State) (om : option Message),\n      vtransition V l (s, om) = UMOComponent_transition l s om)\n  (VM_init_empty :\n    forall s : State, vinitial_state_prop V s -> obs s = [])\n  (VM_enforces_full_node :\n    forall (l : Label) (s : State) (m : Message),\n      vvalid V l (s, Some m) -> full_node s m) :\n  forall (s : State),\n    ram_state_prop V s ->\n    UMO_reachable full_node s.\nProof.\n  intro s.\n  induction 1 using valid_state_prop_ind.\n  - destruct s as [obs adr].\n    apply VM_init_empty in Hs; cbn in Hs; subst.\n    by apply reach_init.\n  - destruct Ht as [(_ & _ & Hvalid) Ht]; cbn in Ht, Hvalid.\n    rewrite VM_transition_is_UMO in Ht.\n    destruct l, om; injection Ht as [= <- <-]; [| done.. |].\n    + apply VM_enforces_full_node in Hvalid.\n      by apply reach_recv.\n    + by apply reach_send.\nQed.\n\n(**\n  A simplified version of [local_equivocators] that only checks for\n  incompatible messages among the immediate observations of the state.\n  This relies on the full node condition.\n*)\nSet Warnings \"-cannot-define-projection\".\nRecord local_equivocators_simple (s : State) (i : Address) : Prop :=\n{\n  les_m1 : Message;\n  les_m2 : Message;\n  les_adr1 : adr (state les_m1) = i;\n  les_adr2 : adr (state les_m2) = i;\n  les_obs_m1 : les_m1 \u2208 messages s;\n  les_obs_m2 : les_m2 \u2208 messages s;\n  les_incomparable : incomparable les_m1 les_m2;\n}.\nSet Warnings \"cannot-define-projection\".\n\n(**\n  A variant of [local equivocators] that relies more on the full node condition\n  and directly shows how the set of equivocators can grow.\n\n  Only a newly received message needs to be checked against previous messages,\n  other addresses are equivocating if they are equivocating in the previous\n  state.\n*)\nInductive local_equivocators_full_obs : list Observation -> Address -> Prop :=\n| lefo_last :\n    forall (ol : list Observation) (m1 m2 : Message),\n      m2 \u2208 receivedMessages' ol ->\n      incomparable m1 m2 ->\n      local_equivocators_full_obs (addObservation' (MkObservation Receive m1) ol) (adr (state m1))\n| lefo_prev :\n    forall (ol : list Observation) (l : Label) (m : Message) (i : Address),\n      local_equivocators_full_obs ol i ->\n      local_equivocators_full_obs (addObservation' (MkObservation l m) ol) i.\n\nLemma lefo_alt (ol : list Observation) (o : Observation) (a : Address) :\n  local_equivocators_full_obs (addObservation' o ol) a <->\n    (a = adr (state (message o))\n      /\\ label o = Receive\n      /\\ exists m2, m2 \u2208 receivedMessages' ol\n      /\\ incomparable (message o) m2)\n    \\/ local_equivocators_full_obs ol a.\nProof.\n  split.\n  - by inversion 1; subst; [left; split_and!; [.. | eexists] | right].\n  - destruct o as [l m1]; cbn.\n    by intros [(-> & -> & m2 & Hrecv & Hadr & Hincomp) |]; econstructor.\nQed.\n\n#[export] Instance local_equivocators_full_obs_dec : RelDecision local_equivocators_full_obs.\nProof.\n  intros ol a.\n  induction ol using addObservation'_rec.\n  - by right; inversion 1.\n  - apply (Decision_iff (iff_Symmetric _ _ (lefo_alt _ _ _))).\n    by pose proof @list_exist_dec; typeclasses eauto.\nDefined.\n\nDefinition local_equivocators_full (s : State) : Address -> Prop :=\n  local_equivocators_full_obs (obs s).\n\n#[export] Instance local_equivocators_full_dec : RelDecision local_equivocators_full :=\n  fun s a => local_equivocators_full_obs_dec (obs s) a.\n\n(**\n  An ELMO component has the same elements as a MO component\n  except for the validity predicate, which:\n\n  - checks message validity\n  - enforces the full-node condition\n  - only allows receiving a message if it will not bring the total [weight]\n    of the locally-visible equivocation above [equivocation_threshold]\n*)\n\nDefinition no_self_equiv (s : State) (m : Message) : Prop :=\n  adr s = adr (state m) -> m \u2208 sentMessages s.\n\nInductive MessageHasSender (m : Message) : Prop :=\n| message_has_sender : forall i, adr (state m) = idx i -> MessageHasSender m.\n\nInductive ELMO_msg_valid_full : Message -> Prop :=\n| MVF_nil :\n    forall m : Message,\n      obs (state m) = [] -> MessageHasSender m -> ELMO_msg_valid_full m\n| MVF_send :\n    forall m,\n      ELMO_msg_valid_full m ->\n      ELMO_msg_valid_full (m <*> MkObservation Send m)\n| MVF_recv :\n    forall m mo,\n      full_node (state m) mo ->\n      no_self_equiv (state m) mo ->\n      ELMO_msg_valid_full m ->\n      ELMO_msg_valid_full (m <*> MkObservation Receive mo).\n\nLemma ELMO_msg_valid_full_to_reach (m : Message) :\n  ELMO_msg_valid_full m ->\n  UMO_reachable (fun s m => full_node s m /\\ no_self_equiv s m) (state m).\nProof.\n  by induction 1; destruct m as [ms]; cbn in *;\n    [replace ms with (MkState [] (adr ms)) by (apply eq_State; done) | ..];\n    constructor.\nQed.\n\nLemma ELMO_msg_valid_full_has_sender (m : Message) :\n  ELMO_msg_valid_full m -> MessageHasSender m.\nProof.\n  by induction 1; [done | ..]; destruct IHELMO_msg_valid_full; econstructor.\nQed.\n\n#[local] Instance ELMO_local_equivocation : BasicEquivocation State Address Ca threshold :=\n{\n  is_equivocating := local_equivocators_full;\n  is_equivocating_dec := local_equivocators_full_dec;\n  state_validators := const (list_to_set (map idx (enum index)));\n}.\n\nDefinition local_equivocation_limit_ok (s : State) : Prop := not_heavy s.\n\nRecord ELMO_recv_valid (s : State) (m : Message) : Prop :=\n{\n  ELMO_mv_full_node : full_node s m;\n  ELMO_mv_no_self_equiv : no_self_equiv  s m;\n  ELMO_mv_msg_valid_full : ELMO_msg_valid_full m;\n  ELMO_mv_local_equivocation_limit_ok :\n    local_equivocation_limit_ok (s <+> MkObservation Receive m);\n}.\n\nInductive ELMOComponentValid : Label -> State -> option Message -> Prop :=\n| ELMOCV_Receive :\n    forall (s : State) (m : Message),\n      ELMO_recv_valid s m ->\n      ELMOComponentValid Receive s (Some m)\n| ELMOCV_Send :\n    forall s : State,\n      ELMOComponentValid Send s None.\n\n(**\n  This definition is closer to the way the validity condition\n  might be defined by hand, but is probably less convenient than\n  the inductive definition of [ELMOComponentValid]. So we prove\n  that they are equivalent.\n*)\nDefinition ELMOComponentValid_alt (l : Label) (s : State) (om : option Message) : Prop :=\n  UMOComponentValid l s om /\\ (l = Receive -> from_option (ELMO_recv_valid s) False om).\n\nDefinition ELMOComponentValid_alt_iff :\n  forall (l : Label) (s : State) (om : option Message),\n    ELMOComponentValid l s om <-> ELMOComponentValid_alt l s om.\nProof.\n  split.\n  - by destruct 1; split; [constructor | auto | constructor | auto].\n  - by intros [[] Hfo]; constructor; apply Hfo.\nQed.\n\nDefinition ELMOComponentMachine (i : index) : VLSMMachine ELMOComponentType :=\n{|\n  initial_state_prop := UMOComponent_initial_state_prop (idx i);\n  initial_message_prop := const False;\n  s0 := Inhabited_UMOComponent_initial_state_type (idx i);\n  transition := fun l '(st, om) => UMOComponent_transition l st om;\n  valid := fun l '(st, om) => ELMOComponentValid l st om;\n|}.\n\nDefinition ELMOComponent (i : index) : VLSM Message :=\n{|\n  vtype := ELMOComponentType;\n  vmachine := ELMOComponentMachine i;\n|}.\n\n#[export] Instance ComputableSentMessages_ELMOComponent\n  (i : index) : ComputableSentMessages (ELMOComponent i).\nProof.\n  constructor 1 with sentMessages; constructor.\n  - by intros [] []; cbn in *; subst; cbn; apply not_elem_of_nil.\n  - intros l s im s' om [(Hvsp & Hovmp & Hv) Ht] m; cbn in *.\n    destruct l, im; cbn in *; [| by exfalso; inversion Hv.. |];\n    inversion_clear Ht; destruct s; cbn.\n    + by rewrite decide_False; cbn; firstorder congruence.\n    + rewrite decide_True by done; cbn.\n      unfold Message; rewrite elem_of_cons.\n      by firstorder congruence.\nDefined.\n\n#[export] Instance ComputableReceivedMessages_ELMOComponent\n  (i : index) : ComputableReceivedMessages (ELMOComponent i).\nProof.\n  constructor 1 with receivedMessages; constructor.\n  - by intros [] []; cbn in *; subst; cbn; apply not_elem_of_nil.\n  - intros l s im s' om [(Hvsp & Hovmp & Hv) Ht] m; cbn in *.\n    destruct l, im; cbn in *; [| by exfalso; inversion Hv.. |];\n    inversion_clear Ht; destruct s; cbn.\n    + rewrite decide_True by done; cbn.\n      unfold Message; rewrite elem_of_cons.\n      by firstorder congruence.\n    + by rewrite decide_False; cbn; firstorder congruence.\nDefined.\n\n#[export] Instance HasBeenDirectlyObservedCapability_ELMOComponent\n  (i : index) : HasBeenDirectlyObservedCapability (ELMOComponent i) :=\n    HasBeenDirectlyObservedCapability_from_sent_received (ELMOComponent i).\n\nLemma ELMO_reachable_view (s : State) i :\n  ram_state_prop (ELMOComponent i) s\n    <->\n  UMO_reachable ELMO_recv_valid s /\\ adr s = idx i.\nProof.\n  eapply iff_trans.\n  - apply UMO_based_valid_reachable; [| | done].\n    + by inversion 1.\n    + by cbn; split; inversion 1; [| constructor].\n  - apply Morphisms_Prop.and_iff_morphism.\n    + by split; apply UMO_reachable_impl; inversion 1; subst; [| constructor].\n    + by firstorder.\nQed.\n\nLemma ELMOComponent_message_dependencies_full_node_condition :\n  forall i : index,\n    message_dependencies_full_node_condition_prop\n      (ELMOComponent i) Message_dependencies.\nProof.\n  intros i [] s m Hv; inversion Hv as [? ? [Hfull] |]; subst.\n  intros dm Hdm; cbn in Hdm.\n  apply elem_of_list_to_set in Hdm.\n  eapply elem_of_submseteq, elem_of_messages in Hdm; [| done].\n  by destruct Hdm as []; [left | right].\nQed.\n\nLemma ELMO_full_node_reachable i s :\n  ram_state_prop (ELMOComponent i) s -> UMO_reachable full_node s.\nProof.\n  intro Hs; apply ELMO_reachable_view in Hs as [? _].\n  eapply UMO_reachable_impl; [| done].\n  by inversion 1.\nQed.\n\nLemma ELMO_no_self_equiv_reachable i s :\n  ram_state_prop (ELMOComponent i) s -> UMO_reachable no_self_equiv s.\nProof.\n  intro Hs; apply ELMO_reachable_view in Hs as [? _].\n  eapply UMO_reachable_impl; [| done].\n  by inversion 1.\nQed.\n\nSection sec_ELMOComponent_lemmas.\n\n(** ** Component lemmas *)\n\nContext\n  (i : index)\n  (Ei : VLSM Message := ELMOComponent i)\n  (Ri : VLSM Message := pre_loaded_with_all_messages_vlsm Ei).\n\nLemma ELMO_reachable_adr (s : State) :\n  ram_state_prop Ei s -> adr s = idx i.\nProof.\n  by intros [_ Hadr]%ELMO_reachable_view.\nQed.\n\nLemma ELMO_transition_output_not_initial :\n  forall l (s : State) (om : option Message) (s' : State) (om' : option Message),\n    input_valid_transition Ri l (s, om) (s', om') ->\n    ~ vinitial_state_prop Ri s'.\nProof.\n  intros l s om [ol a] om' [(_ & _ & Hv) Ht]; compute; intros [-> _].\n  by inversion Hv; subst; inversion Ht.\nQed.\n\nLemma ELMO_transition_inj :\n  forall l (s : State) (om : option Message) (s' : State) (om' : option Message),\n    input_valid_transition Ri l (s, om) (s', om') ->\n  forall l0 s0 om0 om'0,\n    input_valid_transition Ri l0 (s0, om0) (s', om'0) ->\n      l0 = l /\\ s0 = s /\\ om0 = om /\\ om'0 = om'.\nProof.\n  intros l s om s' om' [(_ & _ & Hvalid) Ht] l0 s0 om0 om'0 [(_ & _ & Hvalid0) Ht0].\n  by inversion Hvalid; subst; cbn in Ht;\n    injection Ht as [= <- <-];\n    inversion Hvalid0; subst; inversion Ht0;\n    replace s0 with s by (apply eq_State; done).\nQed.\n\nLemma ELMOComponent_valid_transition_size :\n  forall (s1 s2 : State) (iom oom : option Message) (lbl : Label),\n    ELMOComponentValid lbl s1 iom ->\n    UMOComponent_transition lbl s1 iom = (s2, oom) ->\n      sizeState s1 < sizeState s2.\nProof. by intros [] s2 [im |] oom []; do 2 inversion_clear 1; cbn; lia. Qed.\n\n#[export] Instance ELMOTransitionMonotoneVLSM : TransitionMonotoneVLSM Ei sizeState.\nProof.\n  constructor; intros s1 s2 [? ? ? [Hv Ht]].\n  by eapply ELMOComponent_valid_transition_size; cbn in *.\nQed.\n\nLemma state_suffix_addObservation_inv :\n  forall (s1 s2 : State) (ob : Observation),\n    state_suffix s1 (s2 <+> ob) ->\n      s1 = s2 \\/ state_suffix s1 s2.\nProof.\n  intros s1 s2 ob (Hadr & [[| _o os] Hsuf] & Hstrict);\n    [by contradict Hstrict; exists [] |].\n  destruct s2; cbn in *.\n  inversion Hsuf; subst _o obs.\n  destruct os; [left; apply eq_State; cbn in *; congruence |].\n  right; constructor; [done |].\n  split; [by eexists | destruct s1; cbn; clear].\n  intros [os' Heqos].\n  apply f_equal with (f := length) in Heqos.\n  rewrite app_length in Heqos; cbn in Heqos; rewrite app_length in Heqos.\n  by lia.\nQed.\n\n(** There is a unique trace from any prefix of a reachable state to that state. *)\nLemma ELMO_unique_trace_segments (s sf : State) :\n  ram_state_prop Ei sf -> (s = sf \\/ state_suffix s sf) ->\n  exists! (tr : list transition_item),\n    finite_valid_trace_from_to Ri s sf tr.\nProof.\n  intros Hsf [-> | Hsuf];\n    [by exists []; split; [by constructor |]; intros;\n      symmetry; eapply transition_monotone_empty_trace; [typeclasses eauto |]\n    |].\n  induction Hsf using valid_state_prop_ind.\n  - unfold initial_state_prop in Hs; cbn in Hs.\n    eapply UMOComponent_initial_state_spec in Hs as ->.\n    by contradict Hsuf; apply state_suffix_empty_minimal.\n  - assert (s = s0 \\/ state_suffix s s0) as [-> | Hss0].\n    {\n      assert (exists o, s' = s0 <+> o) as [o ->]\n        by (destruct Ht as [(_ & _ & Hv) Ht]; inversion Hv; subst;\n            inversion Ht; eexists; done).\n      by apply state_suffix_addObservation_inv in Hsuf.\n    }\n    + exists [Build_transition_item l om s' om'].\n      split; [by apply finite_valid_trace_from_to_singleton |].\n      intros tr' Htr'.\n      induction Htr' using finite_valid_trace_from_to_rev_ind;\n        [by contradict Hsuf; apply Irreflexive_state_suffix | clear IHHtr'].\n      pose proof (ELMO_transition_inj _ _ _ _ _ Ht _ _ _ _ Ht0) as (-> & -> & -> & ->).\n      eapply transition_monotone_empty_trace in Htr'; [| typeclasses eauto].\n      by subst.\n    + destruct (IHHsf Hss0) as (tr & Htr & Htr_unique).\n      exists (tr ++ [Build_transition_item l om s' om']).\n      split; [by apply extend_right_finite_trace_from_to with (s2 := s0) |].\n      intros tr' Htr'.\n      induction Htr' using finite_valid_trace_from_to_rev_ind;\n        [by contradict Hsuf; apply Irreflexive_state_suffix | clear IHHtr'].\n      pose proof (ELMO_transition_inj _ _ _ _ _ Ht _ _ _ _ Ht0) as (-> & -> & -> & ->).\n      by f_equal; apply Htr_unique.\nQed.\n\n(**\n  From every reachable state of an [ELMOComponent] we can extract a unique\n  trace reaching that state from the initial state.\n*)\nLemma ELMO_unique_traces (sf : State) :\n  ram_state_prop Ei sf ->\n    exists! tr : list transition_item, exists si : State,\n      finite_valid_trace_init_to Ri si sf tr.\nProof.\n  intros Hsf.\n  pose (si := MkState [] (idx i)).\n  cut (exists! (tr : list transition_item), finite_valid_trace_from_to Ri si sf tr).\n  {\n    intros (tr & Htr & Htr_unique).\n    exists tr; split; [by exists si; split |].\n    by intros _tr [[] [H_tr []]]; cbn in *; subst; apply Htr_unique.\n  }\n  apply ELMO_unique_trace_segments; [done |].\n  destruct (decide (si = sf)) as [| Hneq]; [by left | right].\n  subst si; constructor; cbn; [by rewrite ELMO_reachable_adr |].\n  split; [by eexists; rewrite app_nil_r |].\n  intros [os Hos].\n  symmetry in Hos; apply app_nil in Hos as [_ Hosf].\n  by contradict Hneq; apply eq_State; [| symmetry; apply ELMO_reachable_adr].\nQed.\n\nLemma full_node_rebase_rec_obs :\n  forall (s s' : State) (m : Message),\n    UMO_reachable full_node s ->\n    full_node s (MkMessage s') ->\n    forall l, rec_obs s' (MkObservation l m) ->\n      exists l, rec_obs s (MkObservation l m).\nProof.\n  intros s s' m Hs Hfull l Hm.\n  remember (MkObservation l m) as ob eqn: Heq_ob.\n  revert l m Heq_ob; induction Hm; intros l0 m0 ->.\n  - assert (Hm : m0 \u2208 messages s) by (revert Hfull; apply elem_of_submseteq; constructor).\n    by apply elem_of_list_fmap in Hm as [[l' m'] [-> Hm]]; exists l'; apply obs_rec_obs.\n  - eapply IHHm; [| done].\n    by revert Hfull; apply submseteq_tail_l.\n  - assert (m \u2208 messages s) by (revert Hfull; apply elem_of_submseteq; constructor).\n    by exists l0; apply (unfold_robs _ _ Hs); right; exists m.\nQed.\n\nLemma full_node_messages_iff_rec_obs :\n  forall (s : State), UMO_reachable full_node s ->\n  forall (m : Message),\n    m \u2208 messages s <-> (exists l, rec_obs s (MkObservation l m)).\nProof.\n  intros s Hs; induction Hs using UMO_reachable_ind'.\n  - by split; [intros Hm | intros [? Hm]]; inversion Hm.\n  - intros m.\n    setoid_rewrite elem_of_messages_addObservation; rewrite (IHHs m);\n      setoid_rewrite rec_obs_addObservation_iff; cbn.\n    split.\n    + by intros [<- | [l0]]; eauto.\n    + by intros [l0 [| [[= _] | [->]]]]; eauto using full_node_rebase_rec_obs.\nQed.\n\n(**\n  Because of the [no_self_equiv] assumption,\n  a component might have received its own messages,\n  but only messages it also sent.\n*)\nLemma self_messages_sent (s : State) :\n  UMO_reachable no_self_equiv s ->\n  forall m, adr (state m) = adr s -> m \u2208 messages s -> m \u2208 sentMessages s.\nProof.\n  intros Hs m Hadr Hm; revert s Hs m Hm Hadr.\n  by apply (UMO_reachable_elem_of_messages_ind no_self_equiv\n    (fun s m => adr (state m) = adr s -> m \u2208 sentMessages s));\n    intros; apply elem_of_sentMessages_addObservation; constructor; auto.\nQed.\n\nLemma local_equivocators_simple_addObservation :\n  forall (s : State) (ob : Observation) (a : Address),\n    local_equivocators_simple (s <+> ob) a ->\n      local_equivocators_simple s a\n        \\/\n      adr (state (message ob)) = a /\\\n      message ob \u2209 messages s /\\\n      exists m, m \u2208 messages s /\\ incomparable (message ob) m.\nProof.\n  intros s ob a [].\n  apply elem_of_messages_addObservation in les_obs_m1 as [-> | Hm1], les_obs_m2 as [-> | Hm2].\n  - by destruct les_incomparable as [? []]; constructor.\n  - destruct (decide (message ob \u2208 messages s)).\n    + by left; exists (message ob) les_m2.\n    + by firstorder.\n  - symmetry in les_incomparable.\n    destruct (decide (message ob \u2208 messages s)).\n    + by left; exists les_m1 (message ob).\n    + by firstorder.\n  - by left; eauto using local_equivocators_simple.\nQed.\n\nLemma local_equivocators_simple_add_Send (s : State) :\n  UMO_reachable no_self_equiv s ->\n  forall a, local_equivocators_simple (s <+> MkObservation Send (MkMessage s)) a ->\n            local_equivocators_simple s a.\nProof.\n  intros Hs a Ha.\n  apply local_equivocators_simple_addObservation\n    in Ha as [| (<- & _ & m & Hm & Hincomp)]; [done |]; cbn in *.\n  destruct Hincomp as [Hadr []].\n  by apply self_messages_sent in Hm; [constructor | ..].\nQed.\n\n(**\n  This lemma is convenient to prove for [local_equivocators_simple],\n  and our assumption is slightly weaker than [ram_state_prop Ei].\n*)\nLemma local_equivocators_simple_no_self (s : State) :\n  UMO_reachable no_self_equiv s ->\n    ~ local_equivocators_simple s (adr s).\nProof.\n  intros Hs; induction Hs as [| | ? ? Hno_self_eqv].\n  - by destruct 1; inversion les_obs_m1.\n  - by contradict IHHs; apply local_equivocators_simple_add_Send in IHHs.\n  - contradict IHHs.\n    unfold no_self_equiv in Hno_self_eqv.\n    cbn in IHHs; destruct IHHs.\n    assert (adr (state msg) = adr s -> msg \u2208 messages s).\n    {\n      intro Hmsg; symmetry in Hmsg.\n      apply Hno_self_eqv, elem_of_list_fmap in Hmsg as (ob & Hmsg & Hob).\n      apply elem_of_list_fmap.\n      exists ob.\n      by apply list_filter_subseteq in Hob.\n    }\n    assert (les_m1 \u2208 messages s)\n      by (apply elem_of_messages_addObservation in les_obs_m1 as [-> | l]; auto).\n    assert (les_m2 \u2208 messages s)\n      by (apply elem_of_messages_addObservation in les_obs_m2 as [-> | l]; auto).\n    by exists les_m1 les_m2.\nQed.\n\nLemma local_equivocators_full_nondecreasing (s : State) l om s' om' :\n  vtransition Ri l (s, om) = (s', om') ->\n  (forall a, local_equivocators_full s a ->\n             local_equivocators_full s' a).\nProof.\n  by destruct l, om; cbn; injection 1; intros; subst; try constructor.\nQed.\n\nLemma local_equivocators_full_increase_only_received_adr (s : State) m s' om' :\n  vtransition Ri Receive (s, Some m) = (s', om') ->\n  forall a, local_equivocators_full s' a ->\n            local_equivocators_full s a \\/ a = adr (state m).\nProof.\n  by inversion 1; subst; inversion 1; subst; [right | left].\nQed.\n\nLemma local_equivocators_simple_add_Receive (s : State) (msg : Message) :\n  UMO_reachable no_self_equiv s -> no_self_equiv s msg ->\n  forall i, local_equivocators_simple (s <+> MkObservation Receive msg) i ->\n            local_equivocators_simple s i\n     \\/ adr (state msg) = i /\\ i <> adr s /\\\n          exists m, m \u2208 messages s /\\ incomparable msg m.\nProof.\n  intros Hs Hno_equiv a Ha.\n  assert (a <> adr (s <+> MkObservation Receive msg))\n    by (contradict Ha; subst; apply local_equivocators_simple_no_self; constructor; done).\n  apply local_equivocators_simple_addObservation in Ha; cbn in *.\n  by itauto.\nQed.\n\n(**\n  Any message in <<messages s>> which does not have the same address as <<s>>\n  must be found in [receivedMessages].\n*)\nLemma not_adr_received (s : State) :\n  UMO_reachable no_self_equiv s ->\n  forall msg,\n    adr (state msg) <> adr s ->\n      msg \u2208 messages s -> msg \u2208 receivedMessages s.\nProof.\n  intros Hs msg Hadr Hmsg; revert s Hs msg Hmsg Hadr.\n  by apply (UMO_reachable_elem_of_messages_ind _\n    (fun s m => adr (state m) <> adr s -> m \u2208 receivedMessages s));\n    simpl; intros; apply elem_of_receivedMessages_addObservation; constructor; auto.\nQed.\n\n(**\n  Little lemmas used while proving equivalence between\n  [local_equivocators], [local_equivocators_simple],\n  and [local_equivocators_full].\n*)\nLemma received_in_messages (s : State) :\n  forall msg, msg \u2208 receivedMessages s -> msg \u2208 messages s.\nProof.\n  intros msg Hmsg.\n  apply elem_of_list_fmap in Hmsg as (ob & Hmsg & Hob).\n  apply elem_of_list_fmap.\n  exists ob; split; [done |].\n  by eapply list_filter_subseteq.\nQed.\n\nLemma local_equivocators_simple_prev (s : State) (ob : Observation) (a : Address) :\n  local_equivocators_simple s a ->\n  local_equivocators_simple (s <+> ob) a.\nProof.\n  by destruct 1; exists les_m1 les_m2; try (apply elem_of_messages_addObservation; right).\nQed.\n\nLemma reachable_msg_obs :\n  forall P (s : State),\n    UMO_reachable P s ->\n  forall (m : Message) (ob : Observation),\n    rec_obs (state m) ob ->\n    m \u2208 messages s ->\n    rec_obs s ob.\nProof.\n  intros P s Hs m ob Hob Hm;\n  revert s Hs m Hm ob Hob.\n  by refine (UMO_reachable_elem_of_messages_ind _ _ _ _ _); auto using @rec_obs.\nQed.\n\nLemma reachable_obs_msg (s : State) :\n  UMO_reachable full_node s ->\n  forall ob, rec_obs s ob -> message ob \u2208 messages s.\nProof.\n  intros Hs ob; induction Hs as [| | ? ? Hfull]; intros Hob.\n  - by inversion Hob.\n  - by inversion Hob using rec_obs_send_inv; intros; apply elem_of_messages_addObservation; auto.\n  - apply elem_of_messages_addObservation; cbn.\n    inversion Hob using rec_obs_recv_inv; [by auto.. |].\n    pose proof (fun m H => elem_of_submseteq _ _ m H Hfull) as Hmsg.\n    intros [Hm | (m & Hm & Hob')]%unfold_rec_obs.\n    + by right; apply Hmsg, elem_of_list_fmap_1.\n    + apply (elem_of_list_fmap_1 message) in Hm.\n      by right; apply IHHs, (unfold_robs full_node); eauto.\nQed.\n\nLemma local_equivocators_simple_iff_full (s : State) :\n  UMO_reachable no_self_equiv s ->\n  forall a, local_equivocators_simple s a <-> local_equivocators_full s a.\nProof.\n  intros Hs a; split.\n  - induction Hs.\n    + by destruct 1; inversion les_obs_m1.\n    + intros Ha.\n      apply lefo_prev, IHHs.\n      revert Ha; apply local_equivocators_simple_add_Send.\n      by eapply UMO_reachable_impl.\n    + intros Ha.\n      apply local_equivocators_simple_add_Receive in Ha; [| done..].\n      destruct Ha as [| (<- & Hnot_s & m & Hm & Hincomp)]; [by apply lefo_prev, IHHs |].\n      assert (adr (state m) <> adr s) by (destruct Hincomp; congruence).\n      by revert Hincomp; apply lefo_last, not_adr_received.\n  - destruct s as [s_obs s_a].\n    unfold local_equivocators_full; cbn.\n    intro Hlefo; induction Hlefo as [? ? ? ? Hm12 |].\n    + exists m1 m2; [done | .. | done].\n      * by symmetry; apply Hm12.\n      * by apply elem_of_cons; left.\n      * apply elem_of_cons; right; change (m2 \u2208 messages (MkState ol s_a)).\n        by apply received_in_messages.\n    + change (MkState _ _) with (MkState ol s_a <+> MkObservation l m) in Hs |- *.\n      apply local_equivocators_simple_prev, IHHlefo.\n      by inversion Hs; destruct s.\nQed.\n\nLemma local_equivocators_iff_simple (s : State) :\n  UMO_reachable full_node s ->\n  forall a, local_equivocators s a <-> local_equivocators_simple s a.\nProof.\n  intro Hs; split; destruct 1.\n  - by exists (message lceqv_ob1) (message lceqv_ob2); auto using reachable_obs_msg.\n  - apply (full_node_messages_iff_rec_obs s Hs) in les_obs_m1 as [l1 Hm1], les_obs_m2 as [l2 Hm2].\n    by exists (MkObservation l1 les_m1) (MkObservation l2 les_m2); auto using reachable_obs_msg.\nQed.\n\nLemma local_equivocators_iff_full (s : State) :\n  UMO_reachable (fun s m => full_node s m /\\ no_self_equiv s m) s ->\n  forall a, local_equivocators s a <-> local_equivocators_full s a.\nProof.\n  intros Hs a.\n  by rewrite local_equivocators_iff_simple;\n    [apply local_equivocators_simple_iff_full |];\n    revert Hs; apply UMO_reachable_impl; itauto.\nQed.\n\n(**\n  The [msg_valid_full] predicate holds for any reachable state,\n  even though it is only explicitly checked when receiving messages.\n*)\n\nLemma ELMO_reachable_msg_valid_full :\n  forall s : State,\n    ram_state_prop Ei s -> ELMO_msg_valid_full (MkMessage s).\nProof.\n  intros s [Hs Hi]%ELMO_reachable_view.\n  induction Hs as [| | ? ? Hvalid]; [| specialize (IHHs Hi)..].\n  - by constructor; [| eexists].\n  - by constructor.\n  - by eapply MVF_recv in IHHs; [| apply Hvalid..].\nQed.\n\nLemma reachable_full_node_for_all_messages i' (s : State) :\n  ram_state_prop (ELMOComponent i') s ->\n  forall m, m \u2208 messages s -> full_node s m.\nProof.\n  intros [Hs _]%ELMO_reachable_view.\n  induction Hs as [| | ? ? Hvalid].\n  - by inversion 1.\n  - by intros m [-> | Hm%IHHs]%elem_of_messages_addObservation; apply submseteq_cons.\n  - intros m Hm.\n    apply submseteq_cons; change (full_node s m).\n    apply elem_of_messages_addObservation in Hm as [-> | Hm].\n    + by apply Hvalid.\n    + by apply IHHs in Hm.\nQed.\n\nLemma reachable_sent_messages_reachable i' (s ms : State) :\n  ram_state_prop (ELMOComponent i') s ->\n  MkMessage ms \u2208 sentMessages s ->\n  ram_state_prop (ELMOComponent i') ms.\nProof.\n  intros [Hs Hadr]%ELMO_reachable_view Hms.\n  apply ELMO_reachable_view.\n  induction Hs; [| | by auto].\n  - by apply not_elem_of_nil in Hms.\n  - by apply elem_of_sentMessages_addObservation in Hms as [[[= ->] _] | Hms]; auto.\nQed.\n\nLemma reachable_sent_messages_adr (s : State) (m : Message) :\n  ram_state_prop Ei s ->\n  m \u2208 sentMessages s ->\n  adr (state m) = idx i.\nProof.\n  intros Hs Hm; destruct m.\n  by eapply ELMO_reachable_adr, reachable_sent_messages_reachable.\nQed.\n\nLemma reachable_messages_are_msg_valid (s : State) (m : Message) :\n  ram_state_prop Ei s ->\n  m \u2208 messages s ->\n  ELMO_msg_valid_full m.\nProof.\n  intros [Hs Hadr]%ELMO_reachable_view Hm.\n  revert s Hs m Hm Hadr.\n  refine (UMO_reachable_elem_of_messages_ind _ _ _ _ _); [done | | by destruct 2].\n  by intros; apply ELMO_reachable_msg_valid_full, ELMO_reachable_view.\nQed.\n\nLemma equivocators_of_msg_subset_of_recv (s : State) (m : Message) :\n  full_node s m ->\n  forall a,\n    local_equivocators_simple (state m) a\n    -> local_equivocators_simple (s <+> MkObservation Receive m) a.\nProof.\n  intros Hfull a []; destruct m as [ms]; cbn in *.\n  assert (forall x, x \u2208 messages ms -> x \u2208 messages (s <+> MkObservation Receive (MkMessage ms)))\n    by (intros; apply elem_of_messages_addObservation; right; eapply elem_of_submseteq; done).\n  by eauto using local_equivocators_simple.\nQed.\n\nLemma equivocation_limit_recv_ok_msg_ok (s : State) (m : Message) :\n  full_node s m ->\n  no_self_equiv s m ->\n  UMO_reachable no_self_equiv s ->\n  UMO_reachable no_self_equiv (state m) ->\n  local_equivocation_limit_ok (s <+> MkObservation Receive m) ->\n  local_equivocation_limit_ok (state m).\nProof.\n  intros Hfull Hno_self Hs Hms Hs'.\n  eapply Rle_trans; [| done].\n  apply incl_equivocating_validators_equivocation_fault, filter_subprop; cbn; intros a Ha.\n  rewrite <- local_equivocators_simple_iff_full in Ha by done.\n  rewrite <- local_equivocators_simple_iff_full by (constructor; done).\n  by apply equivocators_of_msg_subset_of_recv.\nQed.\n\nLemma ELMO_msg_valid_prefix (m : Message) (ob : Observation) :\n  ELMO_msg_valid_full (m <*> ob) ->\n  ELMO_msg_valid_full m.\nProof.\n  inversion 1 as [? Hobs | |].\n  - by inversion Hobs.\n  - by replace m with m0 by (apply eq_Message; done).\n  - by replace m with m0 by (apply eq_Message; done).\nQed.\n\nLemma adr_neq_no_self_equiv (s : State) (m : Message) :\n  adr s <> adr (state m) ->\n  no_self_equiv s m.\nProof. by unfold no_self_equiv. Qed.\n\nLemma full_node_prefix s m ob :\n  full_node s (m <*> ob) ->\n  full_node s m.\nProof. by apply submseteq_tail_l. Qed.\n\nLemma ELMO_msg_valid_full_Send_inv\n  (P : Message -> Message -> Prop) :\n  (forall m om, m = om -> P m om) ->\n  forall (m om : Message),\n  ELMO_msg_valid_full (m <*> MkObservation Send om) ->\n  P m om.\nProof.\n  intros Hm m om.\n  inversion 1 as [? Hobs | |].\n  - by inversion Hobs.\n  - by apply Hm, eq_Message.\nQed.\n\nLemma incomparable_iff (m1 m2 : Message) :\n  incomparable m1 m2\n    <->\n  adr (state m1) = adr (state m2)\n  /\\ m1 <> m2\n  /\\ m1 \u2209 sentMessages (state m2)\n  /\\ m2 \u2209 sentMessages (state m1).\nProof.\n  split.\n  - intros [Hadr Hnot]; split; [done |].\n    by repeat split; contradict Hnot; subst; constructor.\n  - intros (Hadr & Hneq & Hnot_m12 & Hnot_m21).\n    split; [done |].\n    by destruct 1 as [| m1 m2 [] | m1 m2 []].\nQed.\n\nLemma equivocation_limit_recv_msg_prefix_ok (v : State) (m : Message) ob\n  (m' := m <*> ob)\n  (v' := v <+> MkObservation Receive m')\n  (v'' := v <+> MkObservation Receive m)\n  :\n  adr (state m) <> adr v ->\n  ram_state_prop Ei v ->\n  m' \u2209 receivedMessages v ->\n  m \u2209 receivedMessages v ->\n  ELMO_recv_valid v m' ->\n  local_equivocation_limit_ok (v <+> MkObservation Receive (m <*> ob)) ->\n  local_equivocation_limit_ok (v <+> MkObservation Receive m).\nProof.\n  intros Hadrs Hv Hfresh_m' Hfresh_m Hvalid Hs'.\n  eapply Rle_trans; [| done].\n  apply incl_equivocating_validators_equivocation_fault, filter_subprop; cbn.\n  fold v'' m' v'.\n  intros k Hk; cbn in *.\n  apply lefo_alt in Hk as [(-> & _ & u & Hu & Hincomp) |]; [| by apply lefo_prev].\n  apply (lefo_last _ m' u Hu).\n  apply incomparable_iff in Hincomp as (Hadr & Hneq & H_m1_m2 & H_m2_m1).\n  apply incomparable_iff; repeat split; [done | by intros <- | |].\n  - intro Hm'.\n    contradict Hfresh_m'.\n    apply not_adr_received; [| done |].\n    + apply UMO_reachable_impl with (1 := ELMO_mv_no_self_equiv).\n      by apply ELMO_reachable_view in Hv as [].\n    + eapply elem_of_submseteq.\n      * by apply elem_of_messages; left.\n      * apply reachable_full_node_for_all_messages with (1 := Hv).\n        by apply elem_of_messages; right.\n  - intros [[-> Hob] |]%elem_of_sentMessages_addObservation; [| done].\n    destruct ob as [[] om], Hob, Hneq; cbn in *.\n    assert (ELMO_msg_valid_full m') as Hmv by apply Hvalid.\n    by inversion Hmv; [| apply eq_Message].\nQed.\n\nHint Resolve\n  equivocation_limit_recv_msg_prefix_ok\n  : ELMO_hints.\n\nHint Resolve\n  full_node_prefix\n  adr_neq_no_self_equiv\n  ELMO_msg_valid_prefix\n  : ELMO_hints.\n\nLemma ELMO_recv_valid_prefix s (m : Message) (ob : Observation) :\n  ram_state_prop Ei s ->\n  m <*> ob \u2209 receivedMessages s ->\n  m \u2209 receivedMessages s ->\n  adr s <> adr (state m) ->\n  ELMO_recv_valid s (m <*> ob) ->\n  ELMO_recv_valid s m.\nProof.\n  intros until 4; intros Hrecv.\n  destruct (Hrecv) as [Hfull Hno_self Hmsg Hlimit].\n  by constructor; eauto with ELMO_hints.\nQed.\n\nHint Resolve ELMO_recv_valid_prefix : ELMO_hints.\n\nLemma reachable_received_messages_reachable (s : State) :\n  ram_state_prop Ei s ->\n  forall m,\n    m \u2208 receivedMessages s ->\n  forall i',\n    adr (state m) = idx i' ->\n    ram_state_prop (ELMOComponent i') (state m).\nProof.\n  intros Hs m Hm.\n  destruct (decide (adr (state m) = adr s)).\n  {\n    intros i' Hi'.\n    cut (m \u2208 sentMessages s).\n    - destruct m.\n      apply reachable_sent_messages_reachable.\n      assert (i = i') as ->; [| done].\n      by (apply ELMO_reachable_view in Hs as []; apply (inj idx); congruence).\n    - apply self_messages_sent; [| done |].\n      + apply ELMO_reachable_view in Hs as [Hs ?].\n        revert Hs; apply UMO_reachable_impl.\n        by intros ? ? [].\n      + by apply elem_of_messages; auto.\n  }\n  revert m Hm n.\n  apply ELMO_reachable_view in Hs as [Hs Hadr].\n  induction Hs as [| | ? ? Hvalid]; [by inversion 1 | by apply IHHs |].\n  intros m Hm%elem_of_receivedMessages_addObservation; cbn in Hm, Hadr.\n  destruct Hm as [[<- []] |]; [| by eauto].\n  destruct (decide (m \u2208 receivedMessages s)); [by eauto |].\n  clear IHHs; revert s Hs Hadr Hvalid n.\n  destruct m as [ms]; cbn.\n  induction ms using addObservation_ind.\n  - by intros; apply initial_state_is_valid; constructor.\n  - set (m' := ms <+> ob); cbn.\n    intros s Hs Hadr Hrecv_m' Hfresh' Hadr_neq i' Hadr_ms.\n    assert (Hrecv_if_fresh : MkMessage ms \u2209 receivedMessages s -> ELMO_recv_valid s (MkMessage ms)).\n    {\n      by intro; apply (ELMO_recv_valid_prefix s (MkMessage ms) ob); [apply ELMO_reachable_view | ..].\n    }\n    assert (Hms : ram_state_prop (ELMOComponent i') ms).\n    {\n      destruct (decide (MkMessage ms \u2208 receivedMessages s)); [| by eauto].\n      revert e; clear -Hs IHms Hadr Hadr_ms Hadr_neq.\n      induction Hs; [by inversion 1 | by eapply IHHs |].\n      destruct (decide (MkMessage ms \u2208 receivedMessages s)).\n      - by intros; eapply IHHs.\n      - intros [[Hms _] |]%elem_of_receivedMessages_addObservation; cbn in *; subst; eauto.\n    }\n    apply ELMO_reachable_view; split; [| done].\n    apply ELMO_reachable_view in Hms as [Hms _].\n    destruct ob as [[] [os]].\n    + apply reach_recv; [| done].\n      destruct Hrecv_m' as [Hfull_s_m' Hself Hmvf_m' Hlimit].\n      inversion Hmvf_m' as [| | ? ? Hfull_m_os Hself_os Hvalid Heqmo]; [done |].\n      assert (m = MkMessage ms)\n        by (destruct m; f_equal; apply eq_State; done).\n      subst m; clear mo Heqmo; cbn in *.\n      constructor; [done | done | |].\n      * apply reachable_messages_are_msg_valid with (s := s).\n        -- by apply ELMO_reachable_view.\n        -- by revert Hfull_s_m'; apply elem_of_submseteq, elem_of_list_here.\n      * apply equivocation_limit_recv_ok_msg_ok in Hlimit; try done.\n        -- by revert Hs; apply UMO_reachable_impl; intros ? ? [].\n        -- apply reach_recv; [done |].\n           by revert Hms; apply UMO_reachable_impl; intros ? ? [].\n    + destruct Hrecv_m' as [_ _ Hmvf _]; inversion Hmvf; [done |].\n      unfold m'.\n      replace os with ms by (apply eq_State; done).\n      by apply reach_send.\nQed.\n\nLemma receivable_messages_reachable (ms s : State) i' :\n  adr ms = idx i' ->\n  ram_state_prop Ei s ->\n  ELMO_recv_valid s (MkMessage ms) ->\n  ram_state_prop (ELMOComponent i') ms.\nProof.\n  intros Heq Hram Hrv.\n  change ms with (state (MkMessage ms)).\n  apply reachable_received_messages_reachable\n    with (s := s <+> MkObservation Receive (MkMessage ms))\n  ; [| constructor | done].\n  apply ELMO_reachable_view in Hram as [].\n  apply ELMO_reachable_view; cbn.\n  by split; [apply reach_recv |].\nQed.\n\nInductive ELMOComponentRAMTransition : Label -> State -> State -> Message -> Prop :=\n| ecr_valid_receive : forall (s1 s2 : State) (m : Message),\n    input_valid_transition Ri Receive (s1, Some m) (s2, None) ->\n    ELMOComponentRAMTransition Receive s1 s2 m\n| ecr_valid_send : forall (s1 s2 : State) (m : Message),\n    input_valid_transition Ri Send (s1, None) (s2, Some m) ->\n    ELMOComponentRAMTransition Send s1 s2 m.\n\nLemma ELMOComponent_input_valid_transition_iff\n  (l : Label) (s : State) (om : option Message) (s' : State) (om' : option Message) :\n  input_valid_transition Ri l (s, om) (s', om')\n    <->\n  (l = Receive /\\ exists m, om = Some m /\\ om' = None /\\ ELMOComponentRAMTransition l s s' m)\n    \\/\n  (l = Send /\\ exists m, om' = Some m /\\ om = None /\\ ELMOComponentRAMTransition Send s s' m).\nProof.\n  split; cycle 1.\n  - by intros [(-> & ? & -> & -> & Hm) | (-> & ? & -> & -> & Hm)]; inversion Hm.\n  - intros Ht; pose (Hti := Ht);  destruct Hti as [(_ & _ & Hvi) Hti];\n      inversion Hvi; subst; inversion Hti; subst; [left | right].\n    + by split; [done |]; eexists; split_and!; [done.. |]; constructor.\n    + by split; [done |]; eexists; split_and!; [done.. |]; constructor.\nQed.\n\nLemma ELMOComponent_elem_of_ram_trace\n  [s tr] (Htr : finite_valid_trace_from Ri s tr) :\n  forall item, item \u2208 tr ->\n    exists (s : State) (m : Message),\n      destination item = s <+> MkObservation (l item) m /\\\n      input_valid_transition_item Ri s item.\nProof.\n  induction Htr; [by inversion 1 |].\n  intro item; rewrite elem_of_cons; intros [-> | Hitem]; [| by apply IHHtr].\n  by pose (Hti := Ht); destruct Hti as [(_ & _ & Hvi) Hti];\n    inversion Hvi; subst; inversion Hti; subst; eexists _, _; split.\nQed.\n\nLemma ELMOComponent_receivedMessages_of_ram_trace\n  [s s' tr] (Htr : finite_valid_trace_from_to Ri s s' tr) :\n  forall item, item \u2208 tr ->\n  forall m, (field_selector input) m item -> m \u2208 receivedMessages s'.\nProof.\n  induction Htr using finite_valid_trace_from_to_rev_ind; [by inversion 1 |].\n  intros item Hitem m Hm.\n  change (has_been_received Ei sf m).\n  eapply has_been_received_step_update; [done |].\n  rewrite elem_of_app, elem_of_list_singleton in Hitem.\n  by destruct Hitem as [Hitem | ->]; [right; cbn; eapply IHHtr | left].\nQed.\n\nLemma ELMOComponent_sentMessages_of_ram_trace\n  [s s' tr] (Htr : finite_valid_trace_from_to Ri s s' tr) :\n  forall item, item \u2208 tr ->\n  forall m, (field_selector output) m item -> m \u2208 sentMessages s'.\nProof.\n  induction Htr using finite_valid_trace_from_to_rev_ind; [by inversion 1 |].\n  intros item Hitem m Hm.\n  change (has_been_sent Ei sf m).\n  eapply has_been_sent_step_update; [done |].\n  rewrite elem_of_app, elem_of_list_singleton in Hitem.\n  by destruct Hitem as [Hitem | ->]; [right; cbn; eapply IHHtr | left].\nQed.\n\nLemma ELMOComponent_sizeState_of_ram_trace_output\n  [s tr] (Htr : finite_valid_trace_from Ri s tr) :\n  forall item, item \u2208 tr ->\n  forall m, (field_selector output) m item ->\n  sizeState s <= sizeState (state m).\nProof.\n  induction Htr; [by inversion 1 |].\n  intros item Hitem m Hm.\n  apply elem_of_cons in Hitem as [-> | Hitem]; cbn in Hm;\n    destruct Ht as [(_ & _ & Hv) Ht]; inversion Hv; subst; inversion Ht; subst; [done | ..].\n  all: by etransitivity; [| eapply IHHtr]; [rewrite addObservation_size; lia | ..].\nQed.\n\nLemma ELMOComponent_messages_of_ram_trace\n  [s s' tr] (Htr : finite_valid_trace_from_to Ri s s' tr) :\n  forall item, item \u2208 tr ->\n  forall m, item_sends_or_receives m item -> m \u2208 messages s'.\nProof.\n  intros ? ? ? [|]; apply elem_of_messages.\n  - by right; eapply ELMOComponent_receivedMessages_of_ram_trace.\n  - by left; eapply ELMOComponent_sentMessages_of_ram_trace.\nQed.\n\nEnd sec_ELMOComponent_lemmas.\n\nSection sec_TraceableVLSM_ELMOComponent.\n\nContext\n  (i : index)\n  (Ei : VLSM Message := ELMOComponent i)\n  (Ri : VLSM Message := pre_loaded_with_all_messages_vlsm Ei)\n  .\n\nDefinition ELMOComponent_state_destructor (s : State)\n  : list (@transition_item Message ELMOComponentType * State) :=\n  let adr := adr s in\nmatch obs s with\n| [] => []\n| MkObservation Send msg as ob :: obs =>\n    let source := MkState obs adr in\n      [(Build_transition_item Send None s (Some msg), source)]\n| MkObservation Receive msg as ob :: obs =>\n    let source := MkState obs adr in\n      [(Build_transition_item Receive (Some msg) s None, source)]\nend.\n\nLemma ELMOComponent_state_destructor_initial :\n  forall (s' : vstate Ei), ram_state_prop Ei s' ->\n    vinitial_state_prop Ei s' <-> ELMOComponent_state_destructor s' = [].\nProof.\n  intros s' Hs'; split; intro Hs''.\n  - by cbn in Hs''; apply UMOComponent_initial_state_spec in Hs'' as ->.\n  - apply ELMO_reachable_adr in Hs'.\n    by destruct s' as [[| [[]]] adr]; cbn in *; [| done..].\nQed.\n\nLemma ELMOComponent_state_destructor_input_valid_transition :\n  forall (s' : vstate Ei), ram_state_prop Ei s' ->\n  forall (s : vstate Ei) (item : vtransition_item Ei),\n    (item, s) \u2208 ELMOComponent_state_destructor s' ->\n    input_valid_transition_item Ri s item.\nProof.\n  intros s' Hs'; apply valid_state_prop_iff in Hs' as [[[is His] ->] | (l & (s, om) & om' & Hpt)].\n  - by cbn in *; apply UMOComponent_initial_state_spec in His as ->; inversion 1.\n  - by pose (Hpt' := Hpt); destruct l, s, om, Hpt' as [(_ & _ & Hv) Ht];\n      inversion Hv; subst; inversion Ht; subst;\n      intros _s item Hitem; apply elem_of_list_singleton in Hitem; inversion Hitem.\nQed.\n\n#[export] Instance TraceableVLSM_ELMOComponent :\n  TraceableVLSM Ei ELMOComponent_state_destructor sizeState.\nProof.\n  constructor.\n  - by typeclasses eauto.\n  - by intros [[| [[] ?] ?] ?] *; [inversion 1 | ..];\n      intro Hitem; apply elem_of_list_singleton in Hitem;\n      inversion_clear Hitem.\n  - by apply ELMOComponent_state_destructor_input_valid_transition.\n  - by apply ELMOComponent_state_destructor_initial.\nQed.\n\nLemma ELMO_latest_observation_Send_state :\n  forall s' : State, ram_state_prop Ei s' ->\n  forall (s : State) (m : Message), s' = s <+> MkObservation Send m ->\n    s = state m.\nProof.\n  intros s' Hs' s m ->.\n  edestruct (ELMOComponent_state_destructor_input_valid_transition _ Hs') as [(_ & _ & Hv) Ht];\n    [by apply elem_of_list_singleton |]; cbn in *.\n  by inversion Hv; subst; inversion Ht; subst; destruct s.\nQed.\n\nEnd sec_TraceableVLSM_ELMOComponent.\n\nSection sec_MessageDependencies_ELMOComponent.\n\nContext\n  (i : index)\n  (Ei : VLSM Message := ELMOComponent i)\n  (Ri : VLSM Message := pre_loaded_with_all_messages_vlsm Ei)\n  .\n\nLemma cannot_resend_message_stepwise_ELMOComponent :\n  cannot_resend_message_stepwise_prop Ei.\nProof.\n  intros ? * [(Hs & _ & Hv) Ht];\n    inversion Hv; subst; inversion Ht; subst;\n    simpl; split; intro Hobs.\n  - by apply elem_of_sentMessages, obs_sizeState in Hobs; cbn in Hobs; lia.\n  - rewrite receivedMessages_addObservation, decide_False in Hobs by (intro; done).\n    by apply elem_of_receivedMessages, obs_sizeState in Hobs; cbn in Hobs; lia.\nQed.\n\n#[export] Instance MessageDependencies_ELMOComponent :\n  MessageDependencies Ei Message_dependencies.\nProof.\n  constructor.\n  - intros m s' ((s, iom) & l & [(_ & _ & Hv) Ht]) dm Hdm; cbn in *.\n    apply elem_of_list_to_set, elem_of_list_fmap in Hdm\n      as (o & -> & Hy).\n    inversion Hv; subst; inversion Ht; subst; cbn in *; clear Ht.\n    red; unfold Message; simpl.\n    rewrite elem_of_sentMessages_addObservation, elem_of_receivedMessages_addObservation,\n      elem_of_sentMessages, elem_of_receivedMessages; cbn.\n    by destruct o as [[] ?]; cbn; firstorder.\n  - intros m Hm.\n    apply can_emit_has_trace in Hm as (is & tr & item & Htr & Houtput).\n    apply (can_emit_from_valid_trace\n            (pre_loaded_vlsm Ei (fun msg : Message => msg \u2208 Message_dependencies m)))\n      with is (tr ++ [item]); cycle 1.\n    + apply Exists_exists; eexists.\n      by split; [apply elem_of_app; right; left |].\n    + eapply lift_preloaded_trace_to_seeded;\n        [by apply cannot_resend_message_stepwise_ELMOComponent | | done].\n      intros dm [Hrcv Hnsnd].\n      apply elem_of_list_to_set, elem_of_list_fmap.\n      exists (MkObservation Receive dm); split; [done |].\n      apply elem_of_receivedMessages.\n      destruct Htr as [Htr His].\n      apply finite_valid_trace_from_app_iff in Htr as [Htr Hitem].\n      apply valid_trace_add_default_last in Htr.\n      apply first_transition_valid in Hitem as [(_ & _ & Hv) Ht].\n      destruct item, l, input; cbn in *; inversion Hv; subst; inversion Ht; subst.\n      clear Hv Ht Hnsnd; cbn.\n      assert (Hrcv' : trace_has_message (field_selector input) dm tr).\n      {\n        apply Exists_exists in Hrcv as (dm_item & Hdm_item & Hdm).\n        rewrite elem_of_app, elem_of_list_singleton in Hdm_item.\n        destruct Hdm_item as [Hdm_item | ->]; cbn in Hdm; [| done].\n        by apply Exists_exists; eexists.\n      }\n      by eapply @has_been_received_examine_one_trace with (vlsm := Ei) in Hrcv'; cycle 1.\nQed.\n\nEnd sec_MessageDependencies_ELMOComponent.\n\nSection sec_ELMOProtocol.\n\nContext `{Inhabited index}.\n\n(** ** Protocol\n\n  An ELMO protocol is defined as the constrained composition of a collection\n  of ELMO components, under a composition constraint that checks that the\n  weight of the globally-detectable equivocation is under the threshold.\n*)\n\n(** *** Equivocators *)\n\nDefinition ELMO_global_equivocators (s : composite_state ELMOComponent) (a : Address) : Prop :=\n  exists m : Message,\n    adr (state m) = a /\\\n    (exists (k : index) (l : Label), rec_obs (s k) (MkObservation l m)) /\\\n    ~ composite_has_been_sent ELMOComponent s m.\n\nDefinition rec_obs_exists_dec\n  (P : Observation -> Prop)\n  (P_dec : forall o, Decision (P o))\n  (s : State)\n  : Decision (exists o, rec_obs s o /\\ P o).\nProof.\n  revert s; fix rec 1; destruct s as [ol a].\n  induction ol as [| ob ol]\n  ; [| specialize (rec (state (message ob))) as IHob]; clear rec.\n  - by right; intros (? & Hrec & ?); inversion Hrec.\n  - change (MkState _ _) with (MkState ol a <+> ob);\n      remember (MkState ol a) as s; clear Heqs ol a.\n    destruct (P_dec ob) as [| Hnot_new];\n      [by left; eexists; split; [constructor |] |].\n    destruct IHol as [| Hnot_prev];\n      [by left; destruct e as (o & Ho & HPo); exists o; split; [constructor 2 |] |].\n    destruct ob as [[] [os]]; cbn in IHob.\n    + destruct IHob as [| Hnot_recv];\n        [by left; destruct e as (o & Ho & HPo); exists o; split; [constructor 3 |] |].\n      by right; intros (? & Hrec & ?); inversion Hrec; subst;\n        replace s0 with s in * by (apply eq_State; done); eauto.\n    + by right; intros (? & Hrec & ?); inversion Hrec; subst;\n        replace s0 with s in * by (apply eq_State; done); eauto.\nDefined.\n\n#[export] Instance ELMO_global_equivocators_dec : RelDecision ELMO_global_equivocators.\nProof.\n  intros s a.\n  apply (@Decision_iff\n    (exists k o, rec_obs (s k) o\n      /\\ adr (state (message o)) = a\n      /\\ not (composite_has_been_sent ELMOComponent s (message o)))).\n  {\n    unfold ELMO_global_equivocators.\n    split; intros Hequ.\n    - by destruct Hequ as (k & [l m] & Hk & [Hadr Hsuff]); eauto 6.\n    - by destruct Hequ as (m & Hadr & (k & l & Hrec_obs) & Hnot_sent); eauto.\n  }\n  pose proof @rec_obs_exists_dec.\n  by typeclasses eauto.\nDefined.\n\nSet Warnings \"-cannot-define-projection\".\nRecord global_equivocators_simple (s : composite_state ELMOComponent) (a : Address) : Prop :=\n{\n  ges_m : Message;\n  ges_adr : adr (state ges_m) = a;\n  ges_recv : composite_has_been_received ELMOComponent s ges_m;\n  ges_not_sent : not (composite_has_been_sent ELMOComponent s ges_m);\n}.\nSet Warnings \"cannot-define-projection\".\n\nDefinition ELMO_global_equivocation : BasicEquivocation (composite_state ELMOComponent) Address Ca threshold :=\n{|\n  is_equivocating := ELMO_global_equivocators;\n  is_equivocating_dec := ELMO_global_equivocators_dec;\n  state_validators := const (list_to_set (map idx (enum index)));\n|}.\n\nDefinition ELMO_not_heavy : composite_state ELMOComponent -> Prop :=\n  not_heavy (1 := ELMO_global_equivocation).\n\nDefinition ELMO_equivocating_validators : composite_state ELMOComponent -> Ca :=\n  equivocating_validators (1 := ELMO_global_equivocation).\n\nDefinition ELMO_global_constraint\n  (l : composite_label ELMOComponent)\n  (som : composite_state ELMOComponent * option Message) : Prop :=\nmatch l with\n| existT _ Receive =>\n  let (s', _) := composite_transition ELMOComponent l som in\n    ELMO_not_heavy s'\n| existT _ Send => True\nend.\n\nDefinition ELMOProtocol : VLSM Message :=\n  composite_vlsm ELMOComponent ELMO_global_constraint.\n\nDefinition FreeELMO : VLSM Message :=\n  free_composite_vlsm ELMOComponent.\n\n(**\n  To talk about reachable composite states for the ELMOProtocol we also name\n  the [pre_loaded_with_all_messages_vlsm] version of the [free_composition].\n*)\n\nDefinition ReachELMO : VLSM Message :=\n  pre_loaded_with_all_messages_vlsm FreeELMO.\n\nDefinition composite_ram_state_prop\n  {message : Type} `{EqDecision index}\n  (IM : index -> VLSM message) (s : composite_state IM) : Prop :=\n    ram_state_prop (free_composite_vlsm IM) s.\n\nLemma ELMO_initial_state_equivocating_validators :\n  forall s : composite_state ELMOComponent,\n    composite_initial_state_prop ELMOComponent s ->\n      ELMO_equivocating_validators s \u2261 \u2205.\nProof.\n  intros s Hs; rewrite elem_of_equiv_empty; intros v.\n  setoid_rewrite elem_of_filter; intros [(m & _ & [(k & l & Hobs) _]) _].\n  replace (s k) with (MkState [] (idx k)) in Hobs\n    by (symmetry; apply UMOComponent_initial_state_spec, Hs).\n  by inversion Hobs.\nQed.\n\nLemma ELMO_initial_state_not_heavy :\n  forall s : composite_state ELMOComponent,\n    composite_initial_state_prop ELMOComponent s -> ELMO_not_heavy s.\nProof.\n  intros s Hs.\n  unfold ELMO_not_heavy, not_heavy.\n  replace (equivocation_fault s) with 0%R.\n  - by apply (rt_positive (H6 := H6)).\n  - by symmetry; apply sum_weights_empty, ELMO_initial_state_equivocating_validators.\nQed.\n\nLemma ELMO_not_heavy_send_message :\n  forall (sigma : composite_state ELMOComponent) (i : index),\n    ELMO_not_heavy sigma ->\n    ELMO_not_heavy\n      (state_update ELMOComponent sigma i\n        (sigma i <+> MkObservation Send (MkMessage (sigma i)))).\nProof.\n  unfold ELMO_not_heavy, not_heavy; etransitivity; [| done].\n  apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n  intro a.\n  unfold equivocating_validators; rewrite !elem_of_filter; cbn.\n  intros [(msg & ? & (k & l & Hmsh) & Hnsent) Hx].\n  split; [| done]; clear Hx.\n  exists msg; split; [done |].\n  split.\n  - exists k, l; destruct (decide (k = i)); subst; state_update_simpl; [| done].\n    by destruct (sigma i); inversion Hmsh; cbn in *; subst;\n      [contradict Hnsent; exists i; cbn; state_update_simpl; left | destruct s].\n  - contradict Hnsent; destruct Hnsent as [j Hsnd]; exists j; cbn.\n    by destruct (decide (j = i)); subst; state_update_simpl; [right |].\nQed.\n\nLemma ELMO_not_heavy_receive_observed_message :\n  forall (sigma : composite_state ELMOComponent) (m : Message) (i i_m : index),\n    UMO_reachable full_node (sigma i_m) ->\n    has_been_directly_observed (ELMOComponent i_m) (sigma i_m) m ->\n    ELMO_not_heavy sigma ->\n      ELMO_not_heavy (state_update ELMOComponent sigma i (sigma i <+> MkObservation Receive m)).\nProof.\n  intros * Hfull Hobs.\n  unfold ELMO_not_heavy, not_heavy; etransitivity; [| done].\n  apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n  intro a.\n  unfold equivocating_validators; rewrite !elem_of_filter; cbn.\n  intros [(msg & ? & (k & l & Hmsh) & Hnsent) Hx].\n  split; [| done]; clear Hx.\n  exists msg; split; [done |].\n  split; cycle 1.\n  - contradict Hnsent; destruct Hnsent as [j Hsnd]; exists j; cbn.\n    by destruct (decide (j = i)); subst; state_update_simpl.\n  - destruct (decide (k = i)); subst; state_update_simpl; [| by eexists _, _].\n    apply rec_obs_addObservation_iff in Hmsh as [Hprev | Hmsh]; [by eexists _, _ |].\n    assert (m \u2208 messages (sigma i_m)) by (apply elem_of_messages; done).\n    exists i_m.\n    apply full_node_messages_iff_rec_obs; [done |].\n    destruct Hmsh as [[= _ ->] | [_ Hmsh]]; [done |].\n    apply messages_hb_transitive with m; [done.. |].\n    apply happensBefore_msg_dep, full_message_dependencies_happens_before.\n    apply elem_of_rec_obs_fn_1 in Hmsh.\n    by apply elem_of_map; eexists; split; cycle 1.\nQed.\n\nLemma ELMO_valid_state_not_heavy :\n  forall s : composite_state ELMOComponent,\n    valid_state_prop ELMOProtocol s -> ELMO_not_heavy s.\nProof.\n  induction 1 using valid_state_prop_ind; [by apply ELMO_initial_state_not_heavy |].\n  apply input_valid_transition_destination in Ht as Hs'.\n  destruct Ht as [(Hs & _ & [Hv Hc]) Ht].\n  unfold ELMO_global_constraint in Hc; destruct l as [i []];\n    [by replace (composite_transition _ _ _) with (s', om') in Hc |].\n  inversion Hv; subst; inversion Ht; subst.\n  by apply ELMO_not_heavy_send_message.\nQed.\n\nDefinition ELMO_state_to_minimal_equivocation_trace\n  (s : composite_state ELMOComponent) (Hs : composite_ram_state_prop ELMOComponent s)\n  : composite_state ELMOComponent * list (composite_transition_item ELMOComponent) :=\n  state_to_minimal_equivocation_trace ELMOComponent\n    (fun _ : index => ELMOComponent_state_destructor) (fun _ : index => sizeState) s Hs.\n\nLemma ELMO_state_to_minimal_equivocation_trace_reachable\n  (s : composite_state ELMOComponent) (Hs : composite_ram_state_prop ELMOComponent s)\n  (is : composite_state ELMOComponent) (tr : list (composite_transition_item ELMOComponent)) :\n    ELMO_state_to_minimal_equivocation_trace s Hs = (is, tr) ->\n      finite_valid_trace_init_to ReachELMO is s tr.\nProof.\n  by apply reachable_composite_state_to_trace,\n    minimal_equivocation_choice_is_choosing_well.\nQed.\n\nLemma ELMO_has_been_directly_observed_sizeState :\n  forall i si m,\n  has_been_directly_observed (ELMOComponent i) si m ->\n  sizeState (state m) < sizeState si.\nProof.\n  intros * [Hsent | Hreceived]; cbn in *.\n  - by apply elem_of_sentMessages, obs_sizeState in Hsent.\n  - by apply elem_of_receivedMessages, obs_sizeState in Hreceived.\nQed.\n\nLemma ELMO_composite_observed_before_send_sizeState_Proper :\n  Proper\n    (composite_observed_before_send ELMOComponent Message_dependencies ==> lt)\n    (sizeState \u2218 state).\nProof.\n  intros x y Hxy; cbn.\n  apply composite_observed_before_send_iff in Hxy\n    as (i & si & itemi & [[(Hsi & _ & Hv) Ht] Hy Hobsxitem]).\n  destruct itemi, l, input; cbn in *;\n    inversion Hv; subst; inversion Ht; subst; clear Hv Ht.\n  inversion Hobsxitem as [? ? ? Hobsx | |]; subst; clear Hobsxitem; cbn.\n  inversion Hobsx; [by eapply ELMO_has_been_directly_observed_sizeState |].\n  etransitivity; [| by eapply ELMO_has_been_directly_observed_sizeState].\n  by apply Message_full_dependencies_sizeState,\n    full_message_dependencies_happens_before.\nQed.\n\n#[local] Instance ELMOComponent_tc_composite_observed_before_send_irreflexive :\n  Irreflexive (tc_composite_observed_before_send ELMOComponent Message_dependencies).\nProof.\n  apply (Proper_reflects_Irreflexive _ (<) (sizeState \u2218 state));\n    [| typeclasses eauto].\n  apply Proper_tc; [typeclasses eauto |].\n  by apply ELMO_composite_observed_before_send_sizeState_Proper.\nQed.\n\nLemma ELMO_channel_authentication_prop :\n  channel_authentication_prop ELMOComponent (ELMO_A idx) Message_sender.\nProof.\n  intros i m ((s, []) & [] & s' & [(Hs & _ & Hv) Ht]);\n    inversion Hv; subst; inversion Ht; subst.\n  unfold channel_authenticated_message; cbn; f_equal.\n  by erewrite ELMO_reachable_adr, ELMO_A_inv.\nQed.\n\nLemma ELMO_state_to_minimal_equivocation_trace_equivocation_monotonic :\n  forall (s : composite_state ELMOComponent) (Hs : composite_ram_state_prop ELMOComponent s),\n  forall (is : composite_state ELMOComponent) (tr : list (composite_transition_item ELMOComponent)),\n  ELMO_state_to_minimal_equivocation_trace s Hs = (is, tr) ->\n  forall (pre suf : list (composite_transition_item ELMOComponent))\n    (item : composite_transition_item ELMOComponent),\n    tr = pre ++ [item] ++ suf ->\n    forall v : Address,\n      msg_dep_is_globally_equivocating ELMOComponent Message_dependencies Message_sender\n        (finite_trace_last is pre) v ->\n      msg_dep_is_globally_equivocating ELMOComponent Message_dependencies Message_sender\n        (destination item) v.\nProof.\n  eapply state_to_minimal_equivocation_trace_equivocation_monotonic.\n  - by intro; apply MessageDependencies_ELMOComponent.\n  - by typeclasses eauto.\n  - by apply ELMO_channel_authentication_prop.\nQed.\n\n(**\n  The shallow and deeper version of [global_equivocators] agree on\n  states which are reachable in [ELMOProtocol].\n*)\n\nLemma ELMO_global_equivocators_iff_simple :\n  forall (s : vstate ELMOProtocol) (a : Address),\n    composite_ram_state_prop ELMOComponent s ->\n      ELMO_global_equivocators s a <-> global_equivocators_simple s a.\nProof.\n  intros s a Hs.\n  assert (forall k, UMO_reachable full_node (s k)) as Hsi;\n    [by intro; apply ELMO_full_node_reachable, preloaded_valid_state_projection |].\n  clear Hs; split; intros Hequiv.\n  - destruct Hequiv as (m & Hadr & (k & l & Hrobs) & Hnot_sent).\n    enough (composite_has_been_received _ s m) by (econstructor; done).\n    assert (m \u2208 messages (s k)) as Hm.\n    + by apply full_node_messages_iff_rec_obs; [| eexists].\n    + by apply elem_of_messages in Hm as [|];\n        [contradict Hnot_sent |]; exists k.\n  - destruct Hequiv as [m Hadr [i_rec Hrecv] Hnot_sent].\n    unfold ELMO_global_equivocators.\n    exists m; split; [done |].\n    split; [| done].\n    exists i_rec.\n    by apply full_node_messages_iff_rec_obs, received_in_messages.\nQed.\n\n(**\n   [global_equivocators_simple] is equivalent to an instance\n   of the generic definition [full_node_is_globally_equivocating].\n*)\nLemma global_equivocators_simple_iff_full_node_equivocation :\n  forall (s : vstate ELMOProtocol) (a : Address),\n    full_node_is_globally_equivocating ELMOComponent Message_sender s a\n    <->\n    global_equivocators_simple s a.\nProof.\n  split.\n  - by intros [? [?%Some_inj]]; econstructor.\n  - by intros [? <-]; econstructor.\nQed.\n\n(**\n  [ELMO_global_equivocators] can be related to\n  [msg_dep_is_globally_equivocating],\n  but the proof is more complicated because\n  it also needs to translate between [rec_obs]\n  and [CompositeHasBeenObserved]\n\n  We use a [full_node] hypothesis so we can convert\n  through claims about [m \u2208 messages (s k)] rather\n  than directly relating [rec_obs] and\n  [CompositeHasBeenObserved].\n\n  It might be possible to use something weaker than [UMO_reachable full_node]\n  to prove\n  [CompositeHasBeenObserved ELMOComponent (elements \u2218 Message_dependencies) s m\n  <-> exists (k : index) (l : label), rec_obs (s k) (MkObservation l m)]\n  but [CompositeHasBeenObserved] can recurse into sent or received messages\n  and [rec_obs] only into received messages so we need some deep structural\n  assumption about what [Send] observations are allowed, even recursively\n  within observations of observations.\n*)\nLemma ELMO_CHBO_in_messages :\n  forall s,\n    (forall k, UMO_reachable full_node (s k)) ->\n  forall m,\n    CompositeHasBeenObserved ELMOComponent Message_dependencies s m\n      <->\n    exists (k : index), m \u2208 messages (s k).\nProof.\n  intros s Hs m; split.\n  - intros [Hobs | m' Hobs Hdepth];\n      destruct Hobs as [k Hobs]; exists k.\n    + by apply elem_of_messages.\n    + assert (m' \u2208 messages (s k)) by (eapply elem_of_messages; done).\n      enough (m <hb m') by (eapply messages_hb_transitive; done).\n      revert Hdepth; apply (tc_congruence (fun m=>m)).\n      unfold msg_dep_rel, compose, immediate_dependency.\n      by intros x y Hdep; apply elem_of_list_to_set in Hdep.\n  - by intros [k Hm%elem_of_messages]; constructor; exists k.\nQed.\n\nLemma ELMO_global_equivocators_iff_msg_dep_equivocation :\n  forall (s : vstate ELMOProtocol) (a : Address),\n    composite_ram_state_prop ELMOComponent s ->\n  ELMO_global_equivocators s a\n    <->\n  msg_dep_is_globally_equivocating ELMOComponent\n    Message_dependencies Message_sender s a.\nProof.\n  intros s a Hs.\n  apply Morphisms_Prop.ex_iff_morphism; intro m.\n  assert (forall k : index, UMO_reachable full_node (s k))\n    by (intro; eapply ELMO_full_node_reachable, valid_state_project_preloaded_to_preloaded; done).\n  setoid_rewrite <- full_node_messages_iff_rec_obs; [| done].\n  setoid_rewrite <- ELMO_CHBO_in_messages; [| done].\n  (* firstorder works here but is slow *)\n  by split; intros []; constructor; [cbv; f_equal | .. | apply Some_inj |]; itauto.\nQed.\n\nLemma ELMO_global_equivocators_iff_simple_by_generic :\n  forall (s : vstate ELMOProtocol) (a : Address),\n    composite_ram_state_prop ELMOComponent s ->\n      ELMO_global_equivocators s a <-> global_equivocators_simple s a.\nProof.\n  intros s a Hs.\n  rewrite ELMO_global_equivocators_iff_msg_dep_equivocation by done.\n  rewrite <- global_equivocators_simple_iff_full_node_equivocation by done.\n  pose proof @ELMOComponent_message_dependencies_full_node_condition.\n  by rewrite full_node_is_globally_equivocating_iff; [| typeclasses eauto | ..].\nQed.\n\n(**\n  If [s] is a reachable state in E where the state of component [i] has the form [si' <+> (l, m)],\n  let [s'] be the composite state which has component [i] equal to [si'] and the other components\n  the same as those of [s]. If all global equivocators of [s'] are also\n  global equivocators in [s] then [s'] is also reachable in E and also\n  it is a valid transition in E to go from [s] to [s'] with\n  label [l] from the new observation and either sending or receiving [m]\n  as [l] says.\n*)\n\nLemma ELMO_state_to_minimal_equivocation_equivocating_validators\n  (s : composite_state ELMOComponent)\n  (Hs_pre :  composite_ram_state_prop ELMOComponent s)\n  (is : composite_state ELMOComponent)\n  (tr : list (composite_transition_item ELMOComponent))\n  (Heqtr_min : ELMO_state_to_minimal_equivocation_trace s Hs_pre = (is, tr)) :\n    Forall (fun item =>\n      ELMO_equivocating_validators (destination item) \u2286 ELMO_equivocating_validators s) tr.\nProof.\n  assert (Hall := ELMO_state_to_minimal_equivocation_trace_equivocation_monotonic _ _ _ _ Heqtr_min).\n  apply ELMO_state_to_minimal_equivocation_trace_reachable in Heqtr_min as Htr_min; clear Heqtr_min.\n  induction Htr_min using finite_valid_trace_init_to_rev_ind; [by constructor |].\n  apply Forall_app; split; [| by apply Forall_singleton].\n  apply input_valid_transition_origin in Ht as Hs.\n  apply input_valid_transition_destination in Ht as Hsf.\n  eapply Forall_impl.\n  - by apply IHHtr_min; [| intros * ->; eapply Hall; simplify_list_eq].\n  - intros x ->.\n    apply filter_subprop.\n    setoid_rewrite ELMO_global_equivocators_iff_msg_dep_equivocation; [| done..].\n    apply valid_trace_get_last in Htr_min as <-.\n    by apply (Hall tr [] _ eq_refl).\nQed.\n\nLemma ELMO_state_to_minimal_equivocation_trace_valid\n  (s : composite_state ELMOComponent)\n  (Hs : valid_state_prop ELMOProtocol s)\n  (Hs_pre := VLSM_incl_valid_state (constraint_preloaded_free_incl _ ELMO_global_constraint) _ Hs\n    : composite_ram_state_prop ELMOComponent s)\n  (is : composite_state ELMOComponent)\n  (tr : list (composite_transition_item ELMOComponent)) :\n    ELMO_state_to_minimal_equivocation_trace s Hs_pre = (is, tr) ->\n      finite_valid_trace_init_to ELMOProtocol is s tr.\nProof.\n  intros Heqtr_min.\n  assert (Hall_not_heavy : Forall (fun item => ELMO_not_heavy (destination item)) tr).\n  {\n    apply ELMO_state_to_minimal_equivocation_equivocating_validators in Heqtr_min.\n    eapply Forall_impl; cbn; [done |].\n    apply ELMO_valid_state_not_heavy in Hs as Hheavy.\n    intros item Hitem; unfold ELMO_not_heavy, not_heavy.\n    etransitivity; [| done].\n    apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n    by intro a; apply Hitem.\n  }\n  apply ELMO_state_to_minimal_equivocation_trace_reachable in Heqtr_min as Htr_min; clear Heqtr_min.\n  assert (Hall_input_valid :\n    Forall (fun item => forall m, input item = Some m -> valid_message_prop ELMOProtocol m) tr).\n  {\n    apply Forall_forall; intros item Hitem m Hobs.\n    eapply directly_observed_valid; [done |].\n    unshelve eapply EquivocationProjections.VLSM_incl_has_been_directly_observed_reflect; cycle 3;\n      [by apply preloaded_constraint_free_incl | .. | by typeclasses eauto | by typeclasses eauto].\n    - by generalize Hs; apply VLSM_incl_valid_state, vlsm_incl_pre_loaded_with_all_messages_vlsm.\n    - eapply has_been_directly_observed_examine_one_trace; [done |].\n      by apply Exists_exists; eexists; cbn; eauto.\n  }\n  clear -Htr_min Hall_input_valid Hall_not_heavy.\n  induction Htr_min using finite_valid_trace_init_to_rev_ind.\n  - by split; [rapply @finite_valid_trace_from_to_empty; apply initial_state_is_valid |].\n  - rewrite !Forall_app, !Forall_singleton in Hall_not_heavy, Hall_input_valid.\n    destruct Hall_not_heavy as [Hall_not_heavy Hsf_not_heavy],\n             Hall_input_valid as [Hall_input_valid Hmsg_valid].\n    destruct (IHHtr_min Hall_not_heavy Hall_input_valid) as [IHHtr _];\n      clear Hall_not_heavy Hall_input_valid.\n    split; [| by apply Htr_min]; clear Htr_min.\n    apply (extend_right_finite_trace_from_to _ IHHtr).\n    destruct Ht as [(Hs_pre & _ & [Hv _]) Ht].\n    repeat split; [| | done | | done].\n    + by apply valid_trace_last_pstate in IHHtr.\n    + by destruct iom; [apply Hmsg_valid | apply option_valid_message_None].\n    + destruct l as [i []]; [| done].\n      by hnf; replace (composite_transition _ _ _) with (sf, oom).\nQed.\n\n(** *** Validators\n\n  Due to the validity predicate, a transition must have either a non-empty\n  input or a non-empty output, the distinction being made by the label.\n*)\nInductive ELMOProtocolValidTransition\n  : index -> Label -> vstate ELMOProtocol -> vstate ELMOProtocol -> Message -> Prop :=\n| ep_valid_receive : forall (i : index) (s1 s2 : vstate ELMOProtocol) (m : Message),\n    ValidTransition ELMOProtocol (existT i Receive) s1 (Some m) s2 None ->\n    ELMOProtocolValidTransition i Receive s1 s2 m\n| ep_valid_send : forall (i : index) (s1 s2 : vstate ELMOProtocol) (m : Message),\n    ValidTransition ELMOProtocol (existT i Send) s1 None s2 (Some m) ->\n    ELMOProtocolValidTransition i Send s1 s2 m.\n\nLemma local_equivocators_full_step_update\n  (i : index) (l : Label) (s1 s2 : State) (m : Message) :\n    ELMOComponentRAMTransition i l s1 s2 m ->\n    forall a : Address,\n      local_equivocators_full s2 a\n        <->\n      local_equivocators_full s1 a \\/\n      a = adr (state m) /\\ l = Receive /\\\n        exists m', m' \u2208 receivedMessages s1 /\\ incomparable m m'.\nProof.\n  by inversion 1 as [? ? ? [_ Ht] | ? ? ? [_ Ht]]; inversion Ht;\n    setoid_rewrite lefo_alt; itauto.\nQed.\n\nLemma global_equivocators_simple_step_update_send\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  ELMOComponentRAMTransition i Send (sigma i) s' m ->\n  forall a : Address,\n    global_equivocators_simple (state_update ELMOComponent sigma i s') a\n      ->\n    global_equivocators_simple sigma a.\nProof.\n  inversion 1 as [| ? ? ? [(Hsi & _ & Hvi) Hti]]; inversion Hvi; inversion Hti; subst.\n  intros a [ges_m ges_adr [j Hrcv] ges_not_sent].\n  destruct (decide (j = i)); subst; state_update_simpl.\n  - cbn in Hrcv; rewrite decide_False in Hrcv by auto.\n    econstructor; [done | by exists i |].\n    intros [j Hsnd]; apply ges_not_sent; exists j.\n    destruct (decide (j = i)); subst; state_update_simpl; cbn; [| done].\n    by rewrite decide_True by done; right.\n  - econstructor; [done | by exists j |].\n    intros[k Hsnd]; apply ges_not_sent.\n    destruct (decide (k = i)); subst; [| by exists k; state_update_simpl].\n    exists i; state_update_simpl; unfold has_been_sent; cbn.\n    by rewrite decide_True by done; right.\nQed.\n\nLemma global_equivocators_simple_step_update_send_iff\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  ELMOComponentRAMTransition i Send (sigma i) s' m ->\n  ~ global_equivocators_simple sigma (idx i) ->\n  forall a : Address,\n    global_equivocators_simple (state_update ELMOComponent sigma i s') a\n      <->\n    global_equivocators_simple sigma a.\nProof.\n  intros Ht Hneqvi; split; [by eapply global_equivocators_simple_step_update_send |].\n  inversion Ht as [| ? ? ? [(Hsi & _ & Hvi) Hti]]; inversion Hvi; inversion Hti; subst.\n  destruct (decide (a = idx i)); subst; [done |].\n  intros [ges_m ges_adr ges_recv ges_not_sent].\n  econstructor; [done | ..].\n  - destruct ges_recv as [j Hrcv]; exists j.\n    destruct (decide (j = i)); subst; state_update_simpl; [| done].\n    by cbn; rewrite decide_False by auto.\n  - intros [j Hsnd]; apply ges_not_sent; exists j.\n    destruct (decide (j = i)); subst; state_update_simpl; [| done].\n    cbn in Hsnd; rewrite decide_True, map_cons in Hsnd by done.\n    inversion Hsnd; subst; [| done].\n    by contradict n; apply ELMO_reachable_adr.\nQed.\n\nLemma global_equivocators_simple_step_update_receive\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n    ELMOComponentRAMTransition i Receive (sigma i) s' m ->\n      forall a : Address,\n        global_equivocators_simple (state_update ELMOComponent sigma i s') a\n          <->\n        global_equivocators_simple sigma a\n          \\/\n        a = adr (state m) /\\ ~ composite_has_been_sent ELMOComponent sigma m.\nProof.\n  intros Ht a; inversion Ht as [? ? ? [(_ & _ & Hvi) Hti] |];\n    inversion Hvi; inversion Hti; subst; clear Ht Hvi Hti; split.\n  - intros [ges_m ges_adr [j Hrcv] ges_not_sent].\n    destruct (decide (j = i)); subst; state_update_simpl; cycle 1.\n    + left; econstructor; [done | by exists j |].\n      intros [k Hsnd]; apply ges_not_sent.\n      destruct (decide (k = i)); subst; [| by exists k; state_update_simpl].\n      exists i; state_update_simpl; unfold has_been_sent; cbn.\n      by rewrite decide_False by auto.\n    + cbn in Hrcv; rewrite decide_True, map_cons in Hrcv by done.\n      apply elem_of_cons in Hrcv as [-> | Hrcv].\n      * right; split; [done |].\n        intros [j Hsnd]; apply ges_not_sent; exists j.\n        destruct (decide (j = i)); subst; state_update_simpl; [| done].\n        by cbn; rewrite decide_False by auto.\n      * left; econstructor; [done | by exists i |].\n        intros [j Hsnd]; apply ges_not_sent; exists j.\n        destruct (decide (j = i)); subst; state_update_simpl; [| done].\n        by cbn; rewrite decide_False by auto.\n  - intros [[ges_m ges_adr ges_recv ges_not_sent] | [-> Hnsnd]].\n    + econstructor; [done | ..].\n      * destruct ges_recv as [j Hrcv]; exists j.\n        destruct (decide (j = i)); subst; state_update_simpl; [| done].\n        by cbn; rewrite decide_True, map_cons by done; right.\n      * intros [j Hsnd]; apply ges_not_sent; exists j.\n        by destruct (decide (j = i)); subst; state_update_simpl.\n    + econstructor; [done | ..].\n      * by exists i; state_update_simpl; left.\n      * intros [j Hsnd]; apply Hnsnd; exists j.\n        destruct (decide (j = i)); subst; state_update_simpl; [| done].\n        by cbn in Hsnd; rewrite decide_False in Hsnd by auto.\nQed.\n\nLemma global_equivocators_simple_step_update_receive_already_observed\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n    composite_ram_state_prop ELMOComponent sigma ->\n    ELMOComponentRAMTransition i Receive (sigma i) s' m ->\n    composite_has_been_directly_observed ELMOComponent sigma m ->\n      forall a : Address,\n        global_equivocators_simple (state_update ELMOComponent sigma i s') a\n          <->\n        global_equivocators_simple sigma a.\nProof.\n  intros Hsigma Ht Hobs a.\n  rewrite global_equivocators_simple_step_update_receive by done.\n  split; [| by left]; intros [| [-> Hnsend]]; [done |].\n  apply ELMO_global_equivocators_iff_simple; [done |].\n  exists m; repeat split; [| done].\n  destruct Hobs as [k Hobs]; exists k.\n  apply full_node_messages_iff_rec_obs; [| by apply elem_of_messages].\n  by eapply ELMO_full_node_reachable, valid_state_project_preloaded_to_preloaded.\nQed.\n\nLemma ELMO_equivocating_validators_step_update_Send\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  composite_ram_state_prop ELMOComponent sigma ->\n  ELMOComponentRAMTransition i Send (sigma i) s' m ->\n    ELMO_equivocating_validators (state_update ELMOComponent sigma i s')\n      \u2286\n    ELMO_equivocating_validators sigma.\nProof.\n  intros Hsigma Ht.\n  assert (Hte : input_valid_transition ReachELMO\n    (existT i Send) (sigma, None) (state_update ELMOComponent sigma i s', Some m)).\n  {\n    inversion Ht as [| ? ? ? [(_ & _ & Hvi) Hti]]; inversion Hvi; inversion Hti.\n    by repeat split; [| apply option_valid_message_None | constructor].\n  }\n  apply input_valid_transition_destination in Hte.\n  intro a; setoid_rewrite elem_of_filter; unfold is_equivocating; cbn.\n  rewrite !ELMO_global_equivocators_iff_simple by done.\n  intros [Heqv]; split; [| done].\n  by eapply global_equivocators_simple_step_update_send.\nQed.\n\nLemma ELMO_equivocating_validators_step_update_Receive\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  composite_ram_state_prop ELMOComponent sigma ->\n  ELMOComponentRAMTransition i Receive (sigma i) s' m ->\n    ELMO_equivocating_validators (state_update ELMOComponent sigma i s')\n      \u2286\n    ELMO_equivocating_validators sigma \u222a {[ adr (state m) ]}.\nProof.\n  intros Hsigma Ht.\n  assert (Hte : input_valid_transition ReachELMO\n    (existT i Receive) (sigma, Some m) (state_update ELMOComponent sigma i s', None)).\n  {\n    inversion Ht as [? ? ? [(_ & _ & Hvi) Hti] |]; inversion Hvi; inversion Hti.\n    by repeat split; [| apply any_message_is_valid_in_preloaded | constructor].\n  }\n  apply input_valid_transition_destination in Hte.\n  intro a; rewrite elem_of_union, elem_of_singleton.\n  setoid_rewrite elem_of_filter; unfold is_equivocating; cbn.\n  rewrite !ELMO_global_equivocators_iff_simple by done.\n  intros [Heqv Hin].\n  by eapply global_equivocators_simple_step_update_receive in Heqv as [Heqv | []];\n    [left; split | right |].\nQed.\n\nLemma ELMO_equivocating_validators_step_update_Receive_already_Observed\n  (i : index) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  composite_ram_state_prop ELMOComponent sigma ->\n  composite_has_been_directly_observed ELMOComponent sigma m ->\n  ELMOComponentRAMTransition i Receive (sigma i) s' m ->\n    ELMO_equivocating_validators (state_update ELMOComponent sigma i s')\n      \u2286\n    ELMO_equivocating_validators sigma.\nProof.\n  intros Hsigma Hsent Ht.\n  assert (Hte : input_valid_transition ReachELMO\n    (existT i Receive) (sigma, Some m) (state_update ELMOComponent sigma i s', None)).\n  {\n    inversion Ht as [? ? ? [(_ & _ & Hvi) Hti] |]; inversion Hvi; inversion Hti.\n    by repeat split; [| apply any_message_is_valid_in_preloaded | constructor].\n  }\n  apply input_valid_transition_destination in Hte.\n  intro a; setoid_rewrite elem_of_filter; unfold is_equivocating; cbn.\n  rewrite !ELMO_global_equivocators_iff_simple by done.\n  intros [Heqv]; split; [| done].\n  by eapply global_equivocators_simple_step_update_receive_already_observed.\nQed.\n\n(**\n  The following lemmas build towards proving that ELMO components are validating\n  for the ELMO protocol.\n\n  If the state <<s>> is valid in the ELMO protocol, and <<s>> can take a valid transition\n  involving a message <<m>>, then <<m>> is a valid message in the ELMO protocol.\n*)\n\nLemma ELMO_update_state_with_initial\n  (s : composite_state ELMOComponent)\n  (Hs : valid_state_prop ELMOProtocol s)\n  (i : index)\n  (Heqv : (sum_weights (ELMO_equivocating_validators s \u222a {[ idx i ]}) <= threshold)%R)\n  (si : State)\n  (Hsi : vinitial_state_prop (ELMOComponent i) si) :\n    valid_state_prop ELMOProtocol (state_update ELMOComponent s i si) /\\\n    ELMO_equivocating_validators (state_update ELMOComponent s i si)\n      \u2286\n    ELMO_equivocating_validators s \u222a {[ idx i ]}.\nProof.\n  assert (Hincl : VLSM_incl ELMOProtocol ReachELMO) by apply constraint_preloaded_free_incl.\n  assert (Htr_min := ELMO_state_to_minimal_equivocation_trace_valid _ Hs).\n  cbn in Htr_min; destruct (ELMO_state_to_minimal_equivocation_trace _ _)\n    as [is_min tr_min] eqn: Heqtr_min; specialize (Htr_min _ _ eq_refl).\n  apply ELMO_state_to_minimal_equivocation_equivocating_validators in Heqtr_min\n    as Hall; clear Hs Heqtr_min.\n  set (s_eqvs := ELMO_equivocating_validators s) in *; clearbody s_eqvs.\n  induction Htr_min using finite_valid_trace_init_to_rev_ind.\n  {\n    rewrite !state_update_id by (destruct (Hsi0 i), Hsi; apply eq_State; congruence).\n    split; [by apply initial_state_is_valid |].\n    rewrite ELMO_initial_state_equivocating_validators by done.\n    by apply empty_subseteq.\n  }\n  rewrite Forall_app, Forall_singleton in Hall.\n  destruct Hall as [Hall Hsf_eqvs].\n  destruct (IHHtr_min Hall) as [Hsisi Heqvs].\n  apply input_valid_transition_origin in Ht as Hs.\n  apply input_valid_transition_destination in Ht as Hsf.\n  apply (VLSM_incl_valid_state Hincl) in Hs, Hsf.\n  destruct l as [j lj].\n  destruct (decide (j = i)); subst; [by destruct Ht as [(_ & _ & [Hv _]) Ht];\n    inversion Hv; subst; inversion Ht; subst; rewrite state_update_twice |].\n  apply (VLSM_incl_input_valid_transition Hincl) in Ht as Ht_pre.\n  destruct Ht as [(_ & Hm & Hv & Hc) Ht].\n  assert (Ht' :\n    composite_transition ELMOComponent (existT j lj) (state_update ELMOComponent s i si, iom)\n    = (state_update ELMOComponent sf i si, oom)).\n  {\n    cbn in *; state_update_simpl; destruct UMOComponent_transition; inversion Ht; subst.\n    by rewrite state_update_twice_neq.\n  }\n  cut (ELMO_equivocating_validators (state_update ELMOComponent sf i si) \u2286\n        ELMO_equivocating_validators sf \u222a {[ idx i ]}).\n  {\n    intro Hsfisi_eqvs'.\n    assert (Hsfisi_eqvs :\n      ELMO_equivocating_validators (state_update ELMOComponent sf i si) \u2286 s_eqvs \u222a {[ idx i ]}).\n    {\n      etransitivity; [done |].\n      by apply union_subseteq; split; [apply union_subseteq_l' | apply union_subseteq_r'].\n    }\n    split; [| done].\n    cut (input_valid_transition ELMOProtocol (existT j lj)\n      (state_update ELMOComponent s i si, iom) (state_update ELMOComponent sf i si, oom));\n      [by intro; eapply input_valid_transition_destination |].\n    repeat split; [done | done | by cbn; state_update_simpl | | done].\n    destruct lj; [| done].\n    unfold ELMO_global_constraint.\n    replace (composite_transition _ _ _) with (state_update ELMOComponent sf i si, oom).\n    unfold ELMO_not_heavy, not_heavy; etransitivity; [| done].\n    apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n    by intro; apply Hsfisi_eqvs.\n  }\n  apply (VLSM_incl_finite_valid_trace_init_to Hincl) in Htr_min as Htr_min_pre.\n  apply (VLSM_incl_valid_state Hincl) in Hsisi as Hsisi_pre.\n  assert (finite_valid_trace_init_to ReachELMO si0 sf\n    (tr ++ [@Build_transition_item _ (composite_type ELMOComponent) (existT j lj) iom sf oom])).\n  {\n    split; [| by apply Htr_min].\n    apply valid_trace_add_last; [| by apply finite_trace_last_is_last].\n    eapply (extend_right_finite_trace_from ReachELMO);\n      [by eapply valid_trace_forget_last, Htr_min_pre |].\n    replace (finite_trace_last _ _) with s; [done |].\n    by apply valid_trace_get_last in Htr_min.\n  }\n  assert (Hpre_tisi : input_valid_transition ReachELMO (existT j lj)\n    (state_update ELMOComponent s i si, iom) (state_update ELMOComponent sf i si, oom)).\n  {\n    repeat split; [done | .. | done].\n    - by apply any_message_is_valid_in_preloaded.\n    - by cbn; state_update_simpl.\n  }\n  apply input_valid_transition_destination in Hpre_tisi as Hpre_sfisi.\n  unfold ELMO_equivocating_validators, equivocating_validators.\n  intro a; rewrite elem_of_union, elem_of_singleton, !elem_of_filter.\n  unfold is_equivocating; cbn; rewrite !ELMO_global_equivocators_iff_simple by done.\n  intros [[ges_m ges_adr [k Hrcv] ges_not_sent] Ha].\n  assert (k <> i); [intros -> |]; state_update_simpl.\n  {\n    by cbn in Hrcv; replace si with (MkState [] (idx i)) in Hrcv;\n      [inversion Hrcv | apply eq_State; symmetry; apply Hsi].\n  }\n  cut (~ composite_has_been_sent ELMOComponent sf ges_m \\/ a = idx i).\n  {\n    intros []; [| by right].\n    left; split; [| done].\n    by econstructor; [| eexists |].\n  }\n  apply elem_of_list_to_set, elem_of_list_fmap in Ha as (i_a & -> & _).\n  destruct (decide (i_a = i)); [by subst; right | left].\n  contradict ges_not_sent.\n  eapply has_been_sent_iff_by_sender in ges_not_sent; cycle 1.\n  - by apply channel_authentication_sender_safety, ELMO_channel_authentication_prop.\n  - done.\n  - done.\n  - rewrite ges_adr, ELMO_A_inv in ges_not_sent by done.\n    by exists i_a; state_update_simpl.\nQed.\n\nLemma ELMO_valid_states_only_receive_valid_messages :\n  forall s : vstate ELMOProtocol,\n    valid_state_prop ELMOProtocol s ->\n  forall (i : index) (l : Label) (s' : vstate ELMOProtocol) (m : Message),\n    ELMOProtocolValidTransition i l s s' m ->\n    valid_message_prop ELMOProtocol m.\nProof.\n  intros s Hs i l s' m Hvalid.\n  inversion Hvalid as [? ? ? ? Hreceive | ? ? ? ? Hsend]; subst; cycle 1.\n  {\n    apply emitted_messages_are_valid.\n    exists (s, None), (existT i Send), s'.\n    by repeat split; [| apply option_valid_message_None | apply Hsend..].\n  }\n  assert (Hincl : VLSM_incl ELMOProtocol ReachELMO) by apply constraint_preloaded_free_incl.\n  destruct (decide (composite_has_been_sent ELMOComponent s m)) as [| Hnsnd];\n    [by eapply composite_sent_valid |].\n  destruct Hreceive as [[Hv Hc] Ht]; inversion Hv as [? ? Hrcv |]; subst; inversion Ht.\n  assert (Hm_eqv : global_equivocators_simple s' (adr (state m))).\n  {\n    subst; constructor 1 with m; [done | |].\n    - by exists i; cbn; state_update_simpl; left.\n    - intros [i_m Hsnd]; apply Hnsnd; exists i_m.\n      by destruct (decide (i_m = i)); subst; state_update_simpl.\n  }\n  assert (Hs'_eqv : forall a,\n    global_equivocators_simple s' a\n      <->\n    a = adr (state m) \\/ global_equivocators_simple s a).\n  {\n    intro a; subst.\n    erewrite global_equivocators_simple_step_update_receive with (m := m); [by itauto |].\n    constructor; repeat split; [| | done].\n    - by eapply valid_state_project_preloaded.\n    - by apply any_message_is_valid_in_preloaded.\n  }\n  apply (VLSM_incl_valid_state Hincl) in Hs as Hs_pre.\n  assert (Hs' : composite_ram_state_prop ELMOComponent s').\n  {\n    apply valid_state_prop_iff; right.\n    by exists (existT i Receive), (s, Some m), None; repeat split;\n      [| apply any_message_is_valid_in_preloaded | ..].\n  }\n  pose (H_rcv := Hrcv); destruct H_rcv.\n  apply ELMO_msg_valid_full_has_sender in ELMO_mv_msg_valid_full0 as Hsender.\n  destruct Hsender as [i_m Hsender].\n  assert (Heqv :\n    (sum_weights (ELMO_equivocating_validators s \u222a {[ idx i_m ]}) <= threshold)%R).\n  {\n    etransitivity; [| apply Hc].\n    apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n    intro a; rewrite elem_of_union, elem_of_singleton.\n    unfold ELMO_equivocating_validators, equivocating_validators.\n    rewrite !elem_of_filter.\n    destruct (decide (a = adr (state m))).\n    - subst; split; cbn.\n      + by apply ELMO_global_equivocators_iff_simple.\n      + by apply elem_of_list_to_set, elem_of_list_fmap; eexists; split; [| apply elem_of_enum].\n    - intros [[] |]; [| by congruence]; split; [| done].\n      subst; apply ELMO_global_equivocators_iff_simple, Hs'_eqv; [done |].\n      by right; apply ELMO_global_equivocators_iff_simple.\n  }\n  assert (His : vinitial_state_prop (ELMOComponent i_m) (MkState [] (idx i_m))) by done.\n  destruct (ELMO_update_state_with_initial _ Hs _ Heqv _ His) as [Hsimis Hsimis_eqvs].\n  eapply valid_state_project_preloaded with (i := i) in Hs as Hsi_pre.\n  replace m with (MkMessage (state m)) in Hrcv by (destruct m; done).\n  pose proof (Hm := receivable_messages_reachable _ _ _ _ Hsender Hsi_pre Hrcv).\n  apply valid_state_has_trace in Hm as (is_m & tr_m & Htr_m).\n  assert (Hall_messages_observed :\n    Forall (fun item => forall m, item_sends_or_receives m item -> m \u2208 messages (s i)) tr_m).\n  {\n    apply Forall_forall; intros item Hitem dm Hobs.\n    eapply elem_of_submseteq; [| done].\n    apply elem_of_messages.\n    change (has_been_directly_observed (ELMOComponent i_m) (state m) dm).\n    eapply has_been_directly_observed_examine_one_trace; [done |].\n    by apply Exists_exists; eexists.\n  }\n  assert (Hall_messages_valid :\n    Forall (fun item => forall m, item_sends_or_receives m item ->\n      valid_message_prop ELMOProtocol m) tr_m).\n  {\n    eapply Forall_impl; cbn; [by apply Hall_messages_observed |].\n    intros item Hobs dm Hdm.\n    eapply directly_observed_valid; [by apply Hs |].\n    by apply Hobs, elem_of_messages in Hdm as []; [left | right]; eexists i.\n  }\n  assert (Heqis_m : is_m = MkState [] (idx i_m))\n    by (destruct is_m, Htr_m as [_ []]; cbn in *; subst; done).\n  assert (Hall_bounded_eqv :\n    Forall (fun item =>\n      ELMO_equivocating_validators (lift_to_composite_state ELMOComponent s i_m (destination item))\n        \u2286\n      ELMO_equivocating_validators s \u222a {[ idx i_m ]})\n        tr_m).\n  {\n    assert (Hall_reachable :\n      Forall (fun item =>\n        composite_ram_state_prop ELMOComponent\n          ((state_update ELMOComponent s i_m item))) (is_m :: map destination tr_m)).\n    {\n      apply (VLSM_incl_valid_state Hincl) in Hsimis as Hsimis_pre.\n      destruct Htr_m as [Htr_m _].\n      apply (VLSM_weak_embedding_finite_valid_trace_from_to\n        (lift_to_preloaded_free_weak_embedding ELMOComponent i_m _ Hs_pre)) in Htr_m.\n      state_update_simpl.\n      apply Forall_forall; intros d Hd.\n      apply elem_of_cons in Hd as [-> | Hd]; [by subst |].\n      apply elem_of_list_fmap in Hd as (item & -> & Hitem).\n      apply elem_of_list_split in Hitem as (pre & suf & ->).\n      setoid_rewrite map_app in Htr_m; cbn in Htr_m.\n      by eapply elem_of_trace_in_futures_left, in_futures_valid_fst in Htr_m;\n        [| by apply elem_of_app; right; left].\n    }\n    rewrite <- Heqis_m in Hsimis_eqvs, Hsimis.\n    remember (state m) as state_m; rewrite <- Hsender in Hsimis_eqvs |- *;\n      rewrite Heqstate_m in Hsender, Hsimis_eqvs |- *.\n    clear -Htr_m Hsimis_eqvs Hall_reachable Hall_messages_observed Hs Hs_pre Hsender.\n    induction Htr_m using finite_valid_trace_init_to_rev_ind; [by constructor |].\n    rewrite map_app in Hall_reachable; cbn in Hall_reachable.\n    rewrite app_comm_cons in Hall_reachable.\n    apply Forall_app in Hall_reachable as [Hall_reachable Hsf_reachable].\n    rewrite Forall_singleton in Hsf_reachable.\n    apply Forall_app in Hall_messages_observed as [Hall_messages_observed Hlast_obs].\n    rewrite Forall_singleton in Hlast_obs.\n    specialize (IHHtr_m Hsimis_eqvs Hall_messages_observed Hall_reachable).\n    assert (Hsis0_pre : composite_ram_state_prop ELMOComponent (state_update ELMOComponent s i_m s0)).\n    {\n      apply valid_trace_get_last in Htr_m as <-.\n      rewrite Forall_forall in Hall_reachable.\n      apply Hall_reachable; apply last_Some_elem_of.\n      by rewrite <- StdppExtras.last_last_error, unlock_finite_trace_last.\n    }\n    clear Hall_reachable Hall_messages_observed.\n    apply Forall_app; split; [done |].\n    constructor; [| by constructor].\n    assert (Hsis0_eqvs :\n      ELMO_equivocating_validators (state_update ELMOComponent s i_m s0)\n        \u2286 ELMO_equivocating_validators s \u222a {[ adr (state m) ]}).\n    {\n      apply valid_trace_get_last in Htr_m as <-.\n      destruct_list_last tr tr' lst Heq; [done |].\n      rewrite finite_trace_last_is_last.\n      rewrite Forall_forall in IHHtr_m; eapply IHHtr_m.\n      by apply elem_of_app; right; left.\n    }\n    cbn; replace (lift_to_composite_state _ _ _ _)\n      with (state_update ELMOComponent (state_update ELMOComponent s i_m s0) i_m sf)\n      by (apply state_update_twice; done).\n    destruct (Ht) as [(_ & _ & H_v) H_t];\n      inversion H_v as [? ? [] |]; subst; inversion H_t; subst; cycle 1.\n    - transitivity (ELMO_equivocating_validators (state_update ELMOComponent s i_m s0)\n        \u222a {[ adr (state m) ]}).\n      + by eapply union_subseteq_l', ELMO_equivocating_validators_step_update_Send;\n          [| by constructor; state_update_simpl].\n      + by apply union_subseteq; split; [| apply union_subseteq_r'].\n    - destruct (decide (adr (state m) = adr (state m0))) as [Hmm0 | Hnmm0].\n      {\n        transitivity (ELMO_equivocating_validators (state_update ELMOComponent s i_m s0)\n          \u222a {[ adr (state m) ]}).\n        - rewrite Hmm0.\n          by eapply ELMO_equivocating_validators_step_update_Receive;\n            [| constructor; state_update_simpl].\n        - by apply union_subseteq; split; [| apply union_subseteq_r'].\n      }\n      assert (Hm0_obs : m0 \u2208 messages (s i)) by (apply Hlast_obs; left; done).\n      destruct (decide (i_m = i)); cycle 1.\n      + transitivity (ELMO_equivocating_validators (state_update ELMOComponent s i_m s0)\n          \u222a {[ adr (state m) ]});\n          [| by apply union_subseteq; split; [| by apply union_subseteq_r']].\n        eapply union_subseteq_l', ELMO_equivocating_validators_step_update_Receive_already_Observed;\n          [done | | by constructor; state_update_simpl].\n        exists i; state_update_simpl.\n        by apply elem_of_messages in Hm0_obs.\n      + subst; intro a; setoid_rewrite elem_of_filter.\n        unfold is_equivocating; cbn.\n        rewrite ELMO_global_equivocators_iff_simple by (rewrite state_update_twice; done).\n        intros [Heqv].\n        eapply global_equivocators_simple_step_update_receive in Heqv;\n          [| by constructor; state_update_simpl].\n        assert (Hm0_not_sent : m0 \u2209 sentMessages (s i)).\n        {\n          intro Hm0; eapply adr_of_sentMessages in Hm0;\n            [| by eapply ELMO_full_node_reachable, valid_state_project_preloaded].\n          rewrite Hsender in *.\n          rewrite Hm0 in Hnmm0; contradict Hnmm0; symmetry.\n          by apply ELMO_reachable_adr, valid_state_project_preloaded.\n        }\n        destruct Heqv as [Heqv | [-> Hnsent]]; cycle 1.\n        * unfold ELMO_equivocating_validators, equivocating_validators, is_equivocating; cbn.\n          rewrite elem_of_union, elem_of_singleton, elem_of_filter,\n            ELMO_global_equivocators_iff_simple by done.\n          left; split; [| done].\n          econstructor; [done | exists i; by apply elem_of_messages in Hm0_obs as [] |].\n          intros [i_m0 Hsent].\n          assert (i <> i_m0) by (intros ->; contradict Hm0_not_sent; done).\n          by apply Hnsent; exists i_m0; state_update_simpl.\n        * apply Hsis0_eqvs.\n          unfold ELMO_equivocating_validators, equivocating_validators, is_equivocating; cbn.\n          by rewrite elem_of_filter, ELMO_global_equivocators_iff_simple.\n  }\n  assert (Htr_m_lift :\n    finite_valid_trace_from_to ELMOProtocol\n      (lift_to_composite_state ELMOComponent s i_m is_m)\n      (lift_to_composite_state ELMOComponent s i_m (state m))\n      (pre_VLSM_embedding_finite_trace_project\n      _ _ (lift_to_composite_label ELMOComponent i_m) (lift_to_composite_state ELMOComponent s i_m)\n      tr_m)).\n  {\n    remember (state m) as sm.\n    clear Heqsm Hrcv Hm_eqv Hs'_eqv Hsender Heqis_m Hall_messages_observed.\n    induction Htr_m using  finite_valid_trace_init_to_rev_ind;\n      [by constructor; destruct si, Hsi; cbn in *; subst |].\n    apply Forall_app in Hall_messages_valid as [Hall_messages_valid H_lst_msg_valid].\n    apply Forall_app in Hall_bounded_eqv as [Hall_bounded_eqv Hsf_bounded_eqv].\n    rewrite Forall_singleton in H_lst_msg_valid.\n    rewrite Forall_singleton in Hsf_bounded_eqv.\n    setoid_rewrite map_app; cbn.\n    eapply extend_right_finite_trace_from_to; [by apply IHHtr_m | cbn].\n    destruct Ht0 as [(Hs0 &  _ & Hv0) Ht0].\n    repeat split.\n    - by eapply finite_valid_trace_from_to_last_pstate, IHHtr_m.\n    - destruct iom; [| apply option_valid_message_None].\n      by apply H_lst_msg_valid; left.\n    - by cbn; state_update_simpl.\n    - destruct l as []; [| done].\n      unfold ELMO_global_constraint, lift_to_composite_label, composite_transition.\n      rewrite state_update_eq.\n      cbn in Ht0 |- *; rewrite Ht0, state_update_twice.\n      unfold ELMO_not_heavy, not_heavy.\n      etransitivity; [| done].\n      apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n      by intro; apply Hsf_bounded_eqv.\n    - cbn; state_update_simpl.\n      replace (UMOComponent_transition _ _ _) with (sf, oom).\n      by rewrite state_update_twice.\n  }\n  cut\n    (input_valid_transition ELMOProtocol (existT i_m Send)\n      (lift_to_composite_state ELMOComponent s i_m (state m), None)\n      (lift_to_composite_state ELMOComponent s i_m (state m <+> MkObservation Send m), Some m))\n    ; [by apply input_valid_transition_out |].\n  repeat split.\n  - by apply finite_valid_trace_from_to_last_pstate in Htr_m_lift.\n  - by apply option_valid_message_None.\n  - by constructor.\n  - by cbn; state_update_simpl; rewrite state_update_twice; destruct m.\nQed.\n\n(**\n  Let si be a reachable state in (ELMOComponent i) and\n  m a message such that\n  ELMOComponentValid Receive si (Some m) in (ELMOComponent i),\n  adr m <> i and adr m \u2209 local_equivocators_full si, and\n  also there is no message m' \u2208 received_messages(si) with m' \u22a5 m.\n\n  Suppose \u03c3 is a valid state in ELMOProtocol such that \u03c3 i = si,\n  having messages(si) = messages(\u03c3),\n  local_equivocators_full(si) = global_equivocators(\u03c3),\n  and components of \u03c3 other than i may only have a\n  Send observation as their latest observation,\n  and also m \u2209 sent_messages(\u03c3).\n\n  Then there exists a state \u03c3' in the future of \u03c3 such that\n  \u03c3' i = si, messages(\u03c3') = messages(si), and\n  global_equivocators(\u03c3') = global_equivocators(\u03c3),\n  components of \u03c3' other than i and adr(m) may only\n  have a Send observation as their latest observation.\n  Finally, \u03c3'(adr(m)) = m\n  (So m can be emitted immediately from \u03c3').\n\n  This is stronger than the previous message by showing,\n  at least in these conditions, that a message that\n  can be validly received by a component in a valid\n  ELMOProtocol state can be validly emitted not just\n  in some unrelated ELMOProtocol trace, but also\n  in a trace continuing from the current state.\n  (We will build from this towards proving ELMOComponents\n  are validating for ELMOProtocol by showing how to\n  construct such an ELMOProtocol state embedding\n  given an ELMOComponent state and receivable message)\n*)\n\nDefinition latest_observation_Send (s : State) : Prop :=\n  obs s = []\n    \\/\n  exists (s' : State) (m : Message),\n    s = s' <+> MkObservation Send m.\n\nDefinition component_reflects_composite_messages (s : vstate ELMOProtocol) (i : index) : Prop :=\n  forall m : Message, (exists j, m \u2208 messages (s j)) <-> m \u2208 messages (s i).\n\nDefinition component_reflects_composite_equivocators (s : vstate ELMOProtocol) (i : index) : Prop :=\n  forall a : Address, global_equivocators_simple s a <-> local_equivocators_full (s i) a.\n\nRecord component_reflects_composite (s : vstate ELMOProtocol) (i : index) : Prop :=\n{\n  component_sees_messages : component_reflects_composite_messages s i;\n  component_sees_equivocators : component_reflects_composite_equivocators s i;\n}.\n\nDefinition other_components_after_send\n  (P_allowed : index -> Prop) (s : vstate ELMOProtocol) : Prop :=\n    forall i : index, ~ P_allowed i -> latest_observation_Send (s i).\n\nLemma non_equivocating_received_message_continues_trace\n  (i : index) (si si' : vstate (ELMOComponent i))\n  (m : Message)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (si, Some m) (si', None))\n  (Hnot_local_equivocator' : ~ local_equivocators_full si' (adr (state m)))\n  (i_m : index)\n  (Hi_m : adr (state m) = idx i_m)\n  (Hadr_neq : adr (state m) <> idx i)\n  (sigma : composite_state ELMOComponent)\n  (Hcomponent : sigma i = si)\n  (Hsigma : valid_state_prop ELMOProtocol sigma)\n  (Hm_not_sent_yet : ~ composite_has_been_sent ELMOComponent sigma m)\n  (Hspecial : component_reflects_composite sigma i)\n  (H_not_i_paused : other_components_after_send (fun j : index => j = i) sigma)\n  : exists tr_m,\n      finite_valid_trace_from_to (pre_loaded_with_all_messages_vlsm (ELMOComponent i_m))\n        (sigma i_m) (state m) tr_m.\nProof.\n  assert (Hsigma_no_junk :\n    forall j, j <> i ->\n    forall mj, mj \u2208 sentMessages (sigma j) ->\n    mj \u2208 receivedMessages si).\n  {\n    intros j Hni mj Hmj.\n    eapply reachable_sent_messages_adr in Hmj as Hmj_adr;\n      [subst | by eapply valid_state_project_preloaded].\n    cut (mj \u2208 messages (sigma i)).\n    {\n      rewrite elem_of_messages; intros [Hmji |]; [| done].\n      eapply reachable_sent_messages_adr in Hmji; [| by eapply valid_state_project_preloaded].\n      by contradict Hni; eapply inj with idx; [done | congruence].\n    }\n    by apply Hspecial; exists j; apply elem_of_messages; left.\n  }\n  assert (i <> i_m) by (contradict Hadr_neq; congruence).\n  apply valid_state_project_preloaded with (i := i_m) in Hsigma as Hsi_m.\n  assert (adr (sigma i_m) = idx i_m) by (apply ELMO_reachable_adr; done).\n  destruct (ELMO_unique_trace_segments i_m (sigma i_m) (state m)) as [tr []]; [.. | by eexists].\n  - destruct Ht as [(Hsi & _ & Hv) _]; inversion Hv; subst.\n    by clear Hsi_m; destruct m; eapply receivable_messages_reachable.\n  - destruct (H_not_i_paused i_m) as [Hinit | (sim & lst_im & Hsnd)]; [done | ..].\n    + replace (sigma i_m) with (MkState [] (adr (state m)));\n        [by specialize (state_suffix_empty_minimum (state m)); itauto |].\n      by apply eq_State; [| cbn; congruence].\n    + apply ELMO_latest_observation_Send_state with (i := i_m) in Hsnd as Hsim; [| done].\n      subst sim.\n      assert (Hcmp : sent_comparable m lst_im).\n      {\n        destruct (decide (sent_comparable m lst_im)); [done |].\n        contradict Hnot_local_equivocator'.\n        eapply local_equivocators_full_step_update; [by constructor 1 |].\n        right; split_and!; [done.. |].\n        exists lst_im; split; [| split; [| done]].\n        - by eapply Hsigma_no_junk with (j := i_m); [| rewrite Hsnd; left].\n        - by transitivity (adr (sigma i_m)); [congruence | rewrite Hsnd].\n      }\n      inversion Hcmp as [| ? ? [] | ? ? Hbefore]; subst.\n      * by contradict Hm_not_sent_yet; exists i_m; rewrite Hsnd; left.\n      * contradict Hm_not_sent_yet; exists i_m; cbn.\n        apply self_messages_sent;\n          [by eapply ELMO_no_self_equiv_reachable, valid_state_project_preloaded | by congruence |].\n        apply messages_hb_transitive with lst_im.\n        -- by eapply ELMO_full_node_reachable, valid_state_project_preloaded.\n        -- by rewrite Hsnd; left.\n        -- by constructor 1; apply elem_of_messages; left.\n      * eapply was_sent_before_characterization_1 in Hbefore; [by rewrite Hsnd; itauto |].\n        eapply ELMO_reachable_view with (i := i_m).\n        destruct Ht as [(Hsi & _ & Hv) _]; inversion Hv; subst.\n        by clear Hsi_m; destruct m; eapply receivable_messages_reachable; [congruence | ..].\nQed.\n\nLemma all_intermediary_transitions_are_receive\n  (i : index) (si si' : vstate (ELMOComponent i))\n  (m : Message)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (si, Some m) (si', None))\n  (i_m : index)\n  (Hi_m : adr (state m) = idx i_m)\n  (Hadr_neq : adr (state m) <> idx i)\n  (Hnot_local_equivocator : ~ local_equivocators_full si (adr (state m)))\n  (sigma : composite_state ELMOComponent)\n  (Hsigma : composite_ram_state_prop ELMOComponent sigma)\n  (Hcomponent : sigma i = si)\n  (Hspecial : component_reflects_composite sigma i)\n  (tr_m : list transition_item)\n  (Htr_m : finite_valid_trace_from_to\n          (pre_loaded_with_all_messages_vlsm (ELMOComponent i_m))\n          (sigma i_m) (state m) tr_m)\n  : Forall (fun item : transition_item => l item = Receive) tr_m.\nProof.\n  apply Forall_forall; intros item Hitem.\n  eapply ELMOComponent_elem_of_ram_trace in Hitem as H_item;\n    [| by eapply valid_trace_forget_last].\n  destruct H_item as (s_m0 & m0 & Hs_m0 & H_item).\n  destruct item; apply ELMOComponent_input_valid_transition_iff in H_item\n    as [[] | (Hl & m_0 & Houtput & Hinput & H_item)]; [done | cbn in *; subst].\n  inversion H_item as [| ? ? ? [(_ & _ & Hvi) Hti]]; subst;\n    inversion Hvi; subst; inversion Hti; subst; clear H_item Hvi Hti.\n  contradict Hnot_local_equivocator; apply Hspecial.\n  eapply ELMOComponent_sentMessages_of_ram_trace in Hitem as Hm0; [| done..].\n  eapply reachable_sent_messages_adr in Hm0 as Hm0_adr;\n    [| by eapply finite_valid_trace_from_to_last_pstate].\n  exists (MkMessage s_m0); [by congruence | ..].\n  - exists i.\n    assert (Hm : MkMessage s_m0 \u2208 messages (sigma i)).\n    {\n      destruct Ht as [(_ & _ & Hv) _]; inversion Hv as [? ? [] |]; subst.\n      eapply elem_of_submseteq; [| done].\n      by apply elem_of_messages; left.\n    }\n    apply elem_of_messages in Hm as [Hsnd |]; [| done].\n    cbn in Hsnd; eapply reachable_sent_messages_adr in Hsnd; cycle 1.\n    + by eapply valid_state_project_preloaded_to_preloaded.\n    + by congruence.\n  - intros [j Hsnd].\n    cbn in Hsnd; eapply reachable_sent_messages_adr in Hsnd as Hsnd_adr;\n      [| by eapply valid_state_project_preloaded_to_preloaded].\n    rewrite Hm0_adr in Hsnd_adr.\n    eapply inj in Hsnd_adr; [| done]; subst j.\n    eapply ELMOComponent_sizeState_of_ram_trace_output in Hitem;\n      [| by eapply valid_trace_forget_last | done].\n    assert (sizeState s_m0 < sizeState (sigma i_m)).\n    {\n      change s_m0 with (state (MkMessage s_m0)).\n      by apply messages_sizeState, elem_of_messages; left.\n    }\n    by cbn in Hitem; lia.\nQed.\n\nLemma lift_receive_trace\n  (sigma : composite_state ELMOComponent)\n  (Hsigma : valid_state_prop ELMOProtocol sigma)\n  (m : Message)\n  (i_m : index)\n  (tr_m : list transition_item)\n  (Htr_m :\n    finite_valid_trace_from_to (pre_loaded_with_all_messages_vlsm (ELMOComponent i_m))\n      (sigma i_m) (state m) tr_m)\n  (Htr_m_receive : Forall (fun item : transition_item => l item = Receive) tr_m)\n  (Htr_m_inputs_in_sigma :\n    forall (item : transition_item) (msg : Message),\n      item \u2208 tr_m -> input item = Some msg ->\n      composite_has_been_directly_observed ELMOComponent sigma msg) :\n  finite_valid_trace_from_to ELMOProtocol\n    sigma (lift_to_composite_state ELMOComponent sigma i_m (state m))\n    (pre_VLSM_embedding_finite_trace_project\n      _ _ (lift_to_composite_label ELMOComponent i_m)\n      (lift_to_composite_state ELMOComponent sigma i_m)\n      tr_m)\n    /\\\n  forall a : Address,\n    global_equivocators_simple\n      (lift_to_composite_state ELMOComponent sigma i_m (state m)) a\n      <->\n    global_equivocators_simple sigma a.\nProof.\n  remember (pre_VLSM_embedding_finite_trace_project _ _ _ _ _) as tr.\n  remember (sigma i_m) as si_m.\n  remember (state m) as sm; clear Heqsm.\n  revert Heqsi_m Htr_m_inputs_in_sigma Htr_m_receive tr Heqtr.\n  induction Htr_m using finite_valid_trace_from_to_rev_ind; intros; subst;\n    [by unfold lift_to_composite_state; rewrite state_update_id; split; constructor |].\n  apply Forall_app in Htr_m_receive as [Htr_m_receive Hl].\n  inversion Hl as [| ? ? H_l _]; cbn in H_l; subst; clear Hl.\n  pose (Hti := Ht); destruct Hti as [(_ & _ & Hv) Hti];\n    inversion Hv; subst; inversion Hti; subst.\n  setoid_rewrite map_app; cbn.\n  assert (Hm0 : composite_has_been_directly_observed ELMOComponent sigma m0)\n    by (eapply Htr_m_inputs_in_sigma;\n      [apply elem_of_app; right; apply elem_of_list_singleton |]; done).\n  edestruct IHHtr_m as [Htr Hall];\n    [.. | split; [eapply finite_valid_trace_from_to_app; [by apply Htr |] |]].\n  - done.\n  - intros item msg Hitem Hmsg.\n    by eapply Htr_m_inputs_in_sigma; [apply elem_of_app; left |].\n  - done.\n  - done.\n  - apply finite_valid_trace_from_add_last; [| done].\n    apply first_transition_valid; cbn.\n    apply finite_valid_trace_from_to_last_pstate in Htr as Hsigma'.\n    repeat split; cbn; [done | ..].\n    + by eapply composite_directly_observed_valid; cycle 1.\n    + by constructor; state_update_simpl.\n    + eapply\n        (in_futures_preserving_oracle_from_stepwise _ _ _ _\n          (composite_has_been_directly_observed_stepwise_props ELMOComponent\n            ELMO_global_constraint)) in Hm0;\n        [| by eapply (VLSM_incl_in_futures (vlsm_incl_pre_loaded_with_all_messages_vlsm\n          ELMOProtocol)); eexists].\n      destruct Hm0 as [i_m0 Hm0].\n      eapply ELMO_not_heavy_receive_observed_message; [| done |].\n      * by eapply ELMO_full_node_reachable, valid_state_project_preloaded.\n      * by apply ELMO_valid_state_not_heavy.\n    + by state_update_simpl; rewrite state_update_twice.\n  - apply finite_valid_trace_from_to_last_pstate in Htr as Hsigma'.\n    eapply\n      (in_futures_preserving_oracle_from_stepwise _ _ _ _\n        (composite_has_been_directly_observed_stepwise_props ELMOComponent\n          ELMO_global_constraint)) in Hm0;\n      [| by eapply (VLSM_incl_in_futures (vlsm_incl_pre_loaded_with_all_messages_vlsm\n        ELMOProtocol)); eexists].\n    intro a; cbn.\n    transitivity (global_equivocators_simple (lift_to_composite_state ELMOComponent sigma i_m s) a);\n      [| apply Hall].\n    remember (lift_to_composite_state ELMOComponent sigma i_m s) as sigma_s.\n    replace s with (sigma_s i_m) by (subst; state_update_simpl; done).\n    replace (lift_to_composite_state ELMOComponent sigma i_m _) with\n      (state_update ELMOComponent sigma_s i_m (sigma_s i_m <+> MkObservation Receive m0))\n      by (subst; rewrite state_update_twice; done).\n    rewrite global_equivocators_simple_step_update_receive\n      by (subst; state_update_simpl; constructor; done).\n    split; [| by left].\n    intros [| [-> Hnsnd]]; [done |].\n    econstructor; [done | | done].\n    by apply composite_has_been_directly_observed_sent_received_iff in Hm0 as [].\nQed.\n\nLemma special_receivable_messages_emittable_in_future\n  (i : index) (si si' : vstate (ELMOComponent i))\n  (m : Message)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (si, Some m) (si', None))\n  (i_m : index)\n  (Hi_m : adr (state m) = idx i_m)\n  (Hadr_neq : adr (state m) <> idx i)\n  (Hnot_local_equivocator : ~ local_equivocators_full si (adr (state m)))\n  (Hnot_local_equivocator' : ~ local_equivocators_full si' (adr (state m)))\n  (sigma : composite_state ELMOComponent)\n  (Hsigma : valid_state_prop ELMOProtocol sigma)\n  (Hcomponent : sigma i = si)\n  (Hspecial : component_reflects_composite sigma i)\n  (H_not_i_paused : other_components_after_send (fun j : index => j = i) sigma)\n  (Hm_not_sent_yet : ~ composite_has_been_sent ELMOComponent sigma m) :\n    exists sigma' : vstate ELMOProtocol,\n      in_futures ELMOProtocol sigma sigma' /\\\n      sigma' i = si /\\\n      component_reflects_composite sigma' i /\\\n      sigma' i_m = state m /\\\n      other_components_after_send (fun j : index => j = i \\/ j = i_m) sigma'.\nProof.\n  assert (Hiim : i <> i_m) by (contradict Hadr_neq; congruence).\n  assert (Hai_m : adr (sigma i_m) = idx i_m)\n    by (apply ELMO_reachable_adr; eapply valid_state_project_preloaded; done).\n  edestruct non_equivocating_received_message_continues_trace as [tr_m Htr_m]; [done.. |].\n  assert (Htr_m_receive : Forall (fun item => l item = Receive) tr_m).\n  {\n    eapply all_intermediary_transitions_are_receive.\n    1-4, 6-8: done.\n    eapply VLSM_incl_valid_state; [| done].\n    by apply constraint_preloaded_free_incl with (constraint := ELMO_global_constraint).\n  }\n  assert (Htr_m_inputs_in_sigma :\n    forall item msg, item \u2208 tr_m -> input item = Some msg ->\n    composite_has_been_directly_observed ELMOComponent sigma msg).\n  {\n    intros item msg Hitem Hinput.\n    destruct Ht as [(Hsi & _ & Hv) _]; inversion Hv as [? ? [] |]; subst.\n    cut (has_been_received (ELMOComponent i_m) (state m) msg).\n    {\n      cbn; intro Hmsg.\n      exists i; cbn; unfold has_been_directly_observed_from_sent_received; cbn.\n      eapply elem_of_messages, elem_of_submseteq; [| done].\n      by apply elem_of_messages; right.\n    }\n    apply finite_valid_trace_from_to_complete_left in Htr_m as (is & tr & Htr & Hlst).\n    eapply has_been_received_examine_one_trace; [done |].\n    apply Exists_app; right.\n    by apply Exists_exists; eexists.\n  }\n  edestruct lift_receive_trace as [Htrsigma_m' Heqv]; [done.. |].\n  exists (lift_to_composite_state ELMOComponent sigma i_m (state m)).\n  split_and!.\n  - by eexists.\n  - by subst; apply state_update_neq.\n  - unfold lift_to_composite_state; split.\n    + intros m0; split; [| by eexists].\n      intros [j Hm0]; destruct (decide (i_m = j)); subst; state_update_simpl;\n        [| by apply Hspecial; eexists].\n      destruct Ht as [(_ & _ & Hv) _]; inversion Hv as [? ? [] |]; subst.\n      by eapply elem_of_submseteq; [| done].\n    + intros a; state_update_simpl.\n      by transitivity (global_equivocators_simple sigma a); [apply Heqv | apply Hspecial].\n  - by state_update_simpl.\n  - intros k Hnk.\n    apply Decidable.not_or in Hnk as [].\n    state_update_simpl.\n    by apply H_not_i_paused.\nQed.\n\nLemma component_reflects_composite_messages_step_update\n  (i : index) (l : Label) (sigma : composite_state ELMOComponent) (s' : State) (m : Message) :\n  ELMOComponentRAMTransition i l (sigma i) s' m ->\n  component_reflects_composite_messages sigma i ->\n  component_reflects_composite_messages (state_update ELMOComponent sigma i s') i.\nProof.\n  intros Ht Hmsgs m'; state_update_simpl.\n  replace s' with (sigma i <+> MkObservation l m).\n  - split; [| by exists i; state_update_simpl].\n    intros [j Hj]; destruct (decide (j = i)); subst; state_update_simpl; [done |].\n    by apply elem_of_messages_addObservation; right; apply Hmsgs; eexists.\n  - by inversion Ht as [? ? ? [(_ & _ & Hvi) Hti] | ? ? ? [(_ & _ & Hvi) Hti]];\n      inversion Hvi; inversion Hti; done.\nQed.\n\nLemma receiving_already_sent_global_local_equivocators\n  (i : index) (sigma : composite_state ELMOComponent) (m : Message) (s' : State)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (sigma i, Some m) (s', None))\n  (Hreflects : component_reflects_composite sigma i)\n  (Hm : composite_has_been_sent ELMOComponent sigma m)\n  : forall a : Address,\n    global_equivocators_simple (state_update ELMOComponent sigma i s') a\n      <->\n    local_equivocators_full s' a.\nProof.\n  destruct Hreflects as [Hmessages Heqvs].\n  assert (m \u2208 messages (sigma i))\n    by (destruct Hm as [j]; apply Hmessages; exists j; apply elem_of_messages; left; done).\n  pose (Hti := Ht); destruct Hti as [(_ & _ & Hvi) Hti];\n    inversion Hvi; subst; inversion Hti; subst.\n  intros a; rewrite global_equivocators_simple_step_update_receive,\n    local_equivocators_full_step_update, (Heqvs a) by (constructor; subst; done).\n  split; intros [| [-> Hsome]]; [by left | done | by left | left].\n  eapply local_equivocators_simple_iff_full; [done | |].\n  - by eapply UMO_reachable_impl, ELMO_reachable_view;\n      [intros ? ? [] | apply Ht].\n  - destruct Hsome as (_ & m' & Hm' & [Heqadr Hcmp]).\n    constructor 1 with m' m; [done | done | | | by split].\n    + by apply elem_of_messages; right.\n    + apply Hmessages.\n      destruct Hm as [j Hj]; exists j.\n      by apply elem_of_messages; left.\nQed.\n\nLemma receiving_already_equivocating_global_local_equivocators\n  (i : index) (sigma : composite_state ELMOComponent) (m : Message) (s' : State)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (sigma i, Some m) (s', None))\n  (Hreflects : component_reflects_composite sigma i)\n  (Heqv : local_equivocators_full (sigma i) (adr (state m)))\n  : forall a : Address,\n    global_equivocators_simple (state_update ELMOComponent sigma i s') a\n      <->\n    local_equivocators_full s' a.\nProof.\n  destruct Hreflects as [Hmessages Heqvs].\n  pose (Hti := Ht); destruct Hti as [(_ & _ & Hvi) Hti];\n    inversion Hvi; subst; inversion Hti; subst.\n  intros a; rewrite global_equivocators_simple_step_update_receive,\n    local_equivocators_full_step_update, (Heqvs a) by (constructor; subst; done).\n  by split; intros []; [by left | | by left |]; destruct_and!; subst; left.\nQed.\n\nLemma receiving_not_already_equivocating_global_local_equivocators\n  (i : index) (sigma : composite_state ELMOComponent) (m : Message) (s' : State)\n  (Ht : input_valid_transition (pre_loaded_with_all_messages_vlsm (ELMOComponent i))\n    Receive (sigma i, Some m) (s', None))\n  (Hreflects : component_reflects_composite sigma i)\n  (Hneqv : ~ local_equivocators_full (sigma i) (adr (state m)))\n  (Heqv : local_equivocators_full s' (adr (state m)))\n  : forall a : Address,\n    global_equivocators_simple (state_update ELMOComponent sigma i s') a\n      <->\n    local_equivocators_full s' a.\nProof.\n  destruct Hreflects as [Hmessages Heqvs].\n  pose (Hti := Ht); destruct Hti as [(_ & _ & Hvi) Hti];\n    inversion Hvi; subst; inversion Hti.\n  assert (Hm' : exists m', m' \u2208 receivedMessages (sigma i) /\\ incomparable m m')\n    by (eapply local_equivocators_full_step_update in Heqv as [| (_ & _ & Hrcv)];\n        [| | constructor 1]; done).\n  intros a; rewrite global_equivocators_simple_step_update_receive,\n    local_equivocators_full_step_update, (Heqvs a) by (constructor; subst; done).\n  split; intros []; [by left | by itauto | by left |].\n  destruct_and!; subst; right; split; [done |].\n  contradict Hneqv.\n  eapply local_equivocators_simple_iff_full; [done | |].\n  - by eapply UMO_reachable_impl, ELMO_reachable_view;\n      [intros ? ? [] | apply Ht].\n  - destruct Hm' as (m' & Hm' & Heqadr & Hcmp).\n    constructor 1 with m' m; [done | done | | | by split].\n    + by apply elem_of_messages; right.\n    + apply Hmessages.\n      destruct Hneqv as [j Hj]; exists j.\n      by apply elem_of_messages; left.\nQed.\n\n(**\n  The following lemma shows that for any reachable state in an (ELMOComponent i)\n  there is a valid state in [ELMOProtocol] where component <<i>> meets most of the\n  conditions of the previous lemma.\n*)\nLemma reflecting_composite_for_reachable_component\n  (i : index) (si : vstate (ELMOComponent i))\n  (Hreachable : ram_state_prop (ELMOComponent i) si) :\n  exists s : vstate ELMOProtocol,\n    s i = si\n    /\\ valid_state_prop ELMOProtocol s\n    /\\ component_reflects_composite s i\n    /\\ other_components_after_send (fun j : index => j = i) s\n    /\\ forall (s_prev : State) (l : Label) (m : Message),\n      si = s_prev <+> MkObservation l m ->\n      let s' := state_update ELMOComponent s i s_prev in\n      valid_state_prop ELMOProtocol s' /\\\n      ELMOProtocolValidTransition i l s' s m.\nProof.\n  induction Hreachable using valid_state_prop_ind;\n    [| destruct IHHreachable as (sigma & <- & Hsigma & Hreflects & Hsend & Hall), l; cycle 1].\n  - unfold initial_state_prop in Hs; cbn in Hs.\n    apply UMOComponent_initial_state_spec in Hs as ->.\n    exists (` (composite_s0 ELMOComponent)).\n    unfold composite_s0; cbn; split_and!; [done | ..].\n    + by apply initial_state_is_valid.\n    + repeat split; cbn; [.. | by inversion 1].\n      * by intros [j Hj].\n      * by inversion 1.\n      * by intros []; itauto.\n    + by left; cbn.\n    + by inversion 1.\n  - pose (sigma' := state_update ELMOComponent sigma i s').\n    exists sigma'; split; [by subst sigma'; state_update_simpl |].\n    pose (Hti := Ht); destruct Hti as [(_ & _ & Hv) Hti];\n      inversion Hv; subst; inversion Hti; subst.\n    assert (Htsigma : input_valid_transition ELMOProtocol (existT i Send) (sigma, None)\n                        (sigma', Some (MkMessage (sigma i))))\n      by (repeat split; [| apply option_valid_message_None |]; done).\n    eapply input_valid_transition_destination in Htsigma as Hsigma'.\n    split_and!; [done | split | ..]; cycle 2.\n    + by intros j Hnj; subst sigma'; state_update_simpl; apply Hsend.\n    + inversion 1; destruct s_prev; cbn in *; subst.\n      replace (state_update _ _ _ _) with sigma; [by split; [| constructor] |].\n      by subst sigma'; extensionality j; destruct (decide (i = j)); subst;\n        state_update_simpl; [destruct (sigma j) |].\n    + intro m; split; [| by eexists]; intros [j Hm].\n      destruct (decide (i = j)); [by subst |].\n      subst sigma'; state_update_simpl.\n      apply elem_of_messages_addObservation; right.\n      by apply Hreflects; eexists.\n    + intros a; transitivity (global_equivocators_simple sigma a); [split |]; cycle 2.\n      * etransitivity; [by apply Hreflects |].\n        subst sigma'; state_update_simpl.\n        unfold local_equivocators_full; cbn; rewrite lefo_alt; cbn.\n        by split; [right | intros [|]; [destruct_and! |]].\n      * intros [? <-]; esplit; [done | ..].\n        -- destruct ges_recv as [j Hrecv].\n           destruct (decide (i = j)); subst; subst sigma'; state_update_simpl; [| by eexists].\n           by cbn in Hrecv; rewrite decide_False in Hrecv by itauto; exists j.\n        -- intros [j Hsent]; apply ges_not_sent; exists j.\n           destruct (decide (i = j)); subst; subst sigma'; state_update_simpl; [| done].\n           by eapply has_been_sent_step_update; [| right].\n      * intros []; esplit; [done | ..].\n        -- destruct ges_recv as [j Hrecv]; exists j.\n           destruct (decide (i = j)); subst; subst sigma'; state_update_simpl; [| done].\n           by eapply has_been_received_step_update; [| right].\n        -- intros [j Hsnd]; apply ges_not_sent.\n           destruct (decide (i = j)); subst; subst sigma'; state_update_simpl; [| by eexists].\n           cbn in Hsnd; rewrite decide_True in Hsnd by done; cbn in Hsnd.\n           apply elem_of_cons in Hsnd as []; subst; [| by exists j].\n           exfalso; eapply irreflexivity with (R := lt) (x := sizeState (sigma j));\n             [typeclasses eauto |].\n           change (sigma j) with (state (MkMessage (sigma j))) at 1.\n           apply messages_sizeState, Hreflects.\n           destruct ges_recv as [j' Hrecv]; exists j'.\n           by apply elem_of_messages; right.\n  - pose (Hti := Ht); destruct Hti as [(_ & _ & Hv) Hti];\n      inversion Hv as [? ? [? ? ? Hlocal_ok] |]; subst; inversion Hti; subst om'.\n    apply ELMO_msg_valid_full_has_sender in ELMO_mv_msg_valid_full0 as Hsender.\n    cut (exists gamma,\n          in_futures ELMOProtocol sigma gamma /\\\n          gamma i = sigma i /\\\n          component_reflects_composite (state_update ELMOComponent gamma i s') i /\\\n          other_components_after_send (fun j : index => j = i) gamma).\n    {\n      intros (gamma & Hfutures & Heq_i & [Hsigma'_messages Hsigma'_eqvs] & Hgamma_send).\n      pose (sigma' := state_update ELMOComponent gamma i s'); subst s'.\n      exists sigma'; split; [by subst sigma'; state_update_simpl |].\n      assert (Hvtsigma : ValidTransition ELMOProtocol (existT i Receive) gamma (Some m) sigma' None).\n      {\n        repeat split; cbn; [by rewrite Heq_i | | by rewrite Heq_i].\n        unfold local_equivocation_limit_ok, not_heavy in Hlocal_ok.\n        unfold ELMO_not_heavy, not_heavy.\n        etransitivity; [| done].\n        apply sum_weights_subseteq; [by apply NoDup_elements.. |].\n        intros x.\n        unfold equivocating_validators, is_equivocating; cbn.\n        apply filter_subprop; intros; rewrite <- Heq_i in *.\n        unfold component_reflects_composite_equivocators in Hsigma'_eqvs.\n        state_update_simpl.\n        apply Hsigma'_eqvs, ELMO_global_equivocators_iff_simple; [| done].\n        apply input_valid_transition_destination\n          with (l := existT i Receive) (s := gamma) (om := Some m) (om' := None);\n          repeat split; [| | done].\n        - eapply in_futures_valid_snd.\n          by apply (VLSM_incl_in_futures (constraint_preloaded_free_incl _ ELMO_global_constraint)).\n        - by apply any_message_is_valid_in_preloaded.\n      }\n      split_and!.\n      - apply input_valid_transition_destination\n          with (l := existT i Receive) (s := gamma) (om := Some m) (om' := None); repeat split.\n        + by eapply in_futures_valid_snd.\n        + by eapply ELMO_valid_states_only_receive_valid_messages;\n            [eapply in_futures_valid_snd | constructor 1].\n        + by cbn; rewrite Heq_i.\n        + by apply Hvtsigma.\n        + by cbn; rewrite Heq_i.\n      - done.\n      - by intros j Hnj; subst sigma'; state_update_simpl; apply Hgamma_send.\n      - inversion 1; destruct s_prev; cbn in *; subst; rewrite <- Heq_i.\n        subst sigma'; rewrite state_update_twice, state_update_id by (destruct (gamma i); done).\n        by split; [eapply in_futures_valid_snd | constructor].\n    }\n    destruct (decide (composite_has_been_sent ELMOComponent sigma m)) as [| Hnot_sent].\n    {\n      exists sigma; split_and!; [by apply in_futures_refl | done | split | done].\n      - by eapply component_reflects_composite_messages_step_update, Hreflects; constructor 1.\n      - unfold component_reflects_composite_messages, component_reflects_composite_equivocators.\n        state_update_simpl.\n        by eapply receiving_already_sent_global_local_equivocators.\n    }\n    destruct (decide (adr (state m) = idx i)) as [| Hm_not_by_i].\n    {\n      contradict Hnot_sent; exists i.\n      cbn; apply ELMO_mv_no_self_equiv; [by split |].\n      transitivity (idx i); [| done].\n      by eapply ELMO_reachable_adr, Ht.\n    }\n    destruct (decide (local_equivocators_full (sigma i) (adr (state m)))) as [| Hneqv].\n    {\n      exists sigma; split_and!; [by apply in_futures_refl | done | split | done].\n      - by eapply component_reflects_composite_messages_step_update, Hreflects; constructor.\n      - unfold component_reflects_composite_messages, component_reflects_composite_equivocators.\n        state_update_simpl.\n        by eapply receiving_already_equivocating_global_local_equivocators.\n    }\n    destruct (decide (local_equivocators_full s' (adr (state m)))) as [| Hneqv'].\n    {\n      exists sigma; split_and!; [by apply in_futures_refl | done | split | done].\n      - by eapply component_reflects_composite_messages_step_update, Hreflects; constructor 1.\n      - unfold component_reflects_composite_messages, component_reflects_composite_equivocators.\n        state_update_simpl.\n        by eapply receiving_not_already_equivocating_global_local_equivocators.\n    }\n    destruct Hsender as [i_m Hsender].\n    destruct (special_receivable_messages_emittable_in_future _ _ _ _ Ht\n      _ Hsender Hm_not_by_i Hneqv Hneqv' _ Hsigma eq_refl Hreflects Hsend Hnot_sent)\n      as (chi & Hfutures & Heqi & [Hchi_messages Hchi_eqvs] & Heqi_m & Hchi_send).\n    pose (sigma' := state_update ELMOComponent chi i_m (chi i_m <+> MkObservation Send m)); subst s'.\n    assert (Hti_m :\n      input_valid_transition ELMOProtocol (existT i_m Send) (chi, None) (sigma', Some m)).\n    {\n      repeat split.\n      - by eapply in_futures_valid_snd.\n      - by apply option_valid_message_None.\n      - by constructor.\n      - by subst sigma'; cbn; rewrite Heqi_m; destruct m.\n    }\n    assert (i <> i_m) by (contradict Hm_not_by_i; subst; done).\n    assert (ELMOComponentRAMTransition i Receive (sigma' i) (sigma i <+> MkObservation Receive m) m).\n    {\n      subst sigma'; state_update_simpl; rewrite Heqi.\n      constructor; repeat split; [.. | done].\n      - by eapply valid_state_project_preloaded.\n      - by apply any_message_is_valid_in_preloaded.\n    }\n    exists sigma'; split_and!; cycle 3; [.. | split].\n    + intros k Hk.\n      subst sigma'.\n      destruct (decide (k = i_m)); subst; state_update_simpl; [| by apply Hchi_send; itauto].\n      by constructor 2; eexists _, _.\n    + by etransitivity; [| eapply input_valid_transition_in_futures].\n    + by subst sigma'; rewrite <- Heqi; state_update_simpl.\n    + split; [| by eexists]; intros [j Hj].\n      destruct (decide (i = j)); [by subst |].\n      subst sigma'; destruct (decide (i_m = j)); subst; state_update_simpl;\n        apply elem_of_messages_addObservation.\n      * apply elem_of_messages_addObservation in Hj as []; [by left |].\n        by right; rewrite <- Heqi; apply Hchi_messages; eexists.\n      * by right; rewrite <- Heqi; apply Hchi_messages; eexists.\n    + intros a; state_update_simpl.\n      transitivity (global_equivocators_simple chi a).\n      * subst sigma'; rewrite global_equivocators_simple_step_update_receive;\n          [| by constructor; state_update_simpl; rewrite Heqi].\n        rewrite global_equivocators_simple_step_update_send_iff; cycle 1.\n        -- by constructor; apply input_valid_transition_project_active in Hti_m; state_update_simpl.\n        -- by contradict Hneqv; rewrite Hsender, <- Heqi; apply Hchi_eqvs.\n        -- split; [| by left].\n           intros [| [_ Hnsnd]]; [done |].\n           by contradict Hnsnd; exists i_m; state_update_simpl; left.\n      * etransitivity; [by apply Hchi_eqvs |].\n        rewrite Heqi; split.\n        -- by intros Heqv; eapply local_equivocators_full_step_update; [constructor | left].\n        -- intros Heqv.\n           destruct (decide (a = adr (state m))); [by subst |].\n           eapply local_equivocators_full_step_update in Heqv; [| by constructor].\n           by destruct Heqv as [| [->]].\nQed.\n\n(** Every [ELMOComponent] is a validator for [ELMOProtocol]. *)\nTheorem ELMOComponents_validating :\n  forall i : index,\n    component_projection_validator_prop ELMOComponent ELMO_global_constraint i.\nProof.\n  intros i li si om Hvti.\n  apply input_valid_transition_iff in Hvti as [[si' om'] Hvti].\n  pose (Hvti' := Hvti); destruct Hvti' as [(_ & _ & Hvi) Hti].\n  apply input_valid_transition_destination in Hvti as Hsi'.\n  apply reflecting_composite_for_reachable_component in Hsi'\n    as (s' & <- & Hs' & _ & _ & Htransitions).\n  specialize (Htransitions si li).\n  exists (state_update ELMOComponent s' i si).\n  split; [by state_update_simpl |].\n  inversion Hvi; subst; inversion Hti as [Heqs'i]; subst;\n    symmetry in Heqs'i; destruct (Htransitions _ Heqs'i) as [Hvs'0 Hvt0];\n    inversion Hvt0 as [? ? ? ? Hvt | ? ? ? ? Hvt].\n  - repeat split; [done | | by apply Hvt..].\n    eapply composite_received_valid; [by apply Hs' |].\n    by eexists; eapply has_been_received_step_update; [| left].\n  - by repeat split; [| apply option_valid_message_None | apply Hvt].\nQed.\n\nEnd sec_ELMOProtocol.\n\nEnd sec_ELMO.\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/ELMO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19375419715760625}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The L2C verified compiler                              *)\n(*                                                                     *)\n(*            L2C Group, Tsinghua University                           *)\n(*                                                                     *)\n(*  Copyright Tsinghua University.  All rights reserved.  This file is *)\n(*  distributed under the terms of the GNU General Public License as   *)\n(*  published by the Free Software Foundation, either version 2 of the *)\n(*  License, or (at your option) any later version.  This file is also *)\n(*  distributed under the terms of the INRIA Non-Commercial License    *)\n(*  Agreement.                                                         *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import AST.\nRequire Import Lop.\nRequire Import Lustre.\nRequire Import Ctypes.\nRequire Import Cltypes.\nRequire Import Lident.\n\n(** * Common syntax *)\n\n(** Output parameters, Input parameters, and local variables*)\n\nDefinition vars := list (ident * type * clock).\n\n(** * Expressions *)\n\nInductive operator: Type:=\n  | Oiteratorcall : iterator_operation -> calldef ->  operator\n  | Omapary: binary_operationL -> operator\n  | Omaptycmp: bool -> operator\n  | Omapunary: unary_operationL -> operator\n  | Ofoldary: binary_operationL -> operator\n  | Ofoldunary: unary_operationL -> operator\n  | Oarydef: operator\n  | Oaryslc: int -> operator.\n\n(** All expressions are annotated with their types and clocks. *)\n\nInductive expr : Type := \n  | Econst : const -> type -> clock -> expr\n  | Evar : ident -> type -> clock -> expr\n  | ListExpr : expr_list -> expr                                           (**r list expression *)\n  | Ecall: calldef -> expr_list -> list (type * clock) -> expr\n  | Efor : bool -> operator -> int -> expr_list -> list (type * clock) -> expr \t              (**r operator application *)\n  | Econstruct : expr_list -> (type * clock) -> expr                                      (**r construct a struct, e.g {label1 : 3, label2 : false} *)\n  | Earrayacc : expr -> int -> (type * clock) -> expr                                     (**r expr[i], access to (i+1)th member of an array \"expr\" *)\n  | Earraydiff : expr_list -> (type * clock) -> expr                                      (**r [list expression], build an array with elements \"list expression\", e.g [1,2]*)\n  | Earrayproj: expr -> expr_list -> expr -> (type * clock) -> expr                     (**r dynamic projection, e.g (2^3^4.[7] default 100^3), value is 100^3 *) \n  | Emix : expr -> label_index_list -> expr -> (type * clock) -> expr                   (**r construct a new array or struct, e.g {label1:2^3} with label1.[0] = 7, value is {label1:[7,2]} *)\n  | Eunop : unary_operationL -> expr -> (type * clock) -> expr                            (**r unary operation *)\n  | Ebinop : binary_operationL -> expr -> expr -> (type * clock) -> expr                 (**r binary operation *)\n  | Efield : expr -> ident -> (type * clock) -> expr                                      (**r access to a member of a struct *)\n  | Epre : list ident -> expr -> list (type * clock) -> expr                              (**r pre : shift flows on the last instant backward, producing an undefined value at first instant*)\n  | Efby : list (ident) -> expr_list -> expr_list -> list (type * clock) -> expr  \n  | Efbyn : list (ident*ident*ident) -> expr_list -> int -> expr_list -> list (type * clock) -> expr  (**r fby : fby(b; n; a) = a -> pre fby(b; n-1; a) *) \n  | Earrow : expr -> expr -> list (type * clock) -> expr                                         (**r -> : fix the inital value of flows*)\n  | Ewhen : expr -> clock -> list (type * clock) -> expr                                          (**r x when h: if h=false, then no value; otherwise x *)\n  | Ecurrent: list ident -> expr ->  list (type * clock) -> expr   \n  | Emerge: ident -> type -> pattern_list -> list (type * clock) -> expr   \n  | Eif : expr -> expr -> expr -> list (type * clock) -> expr                                   (**r conditional*)\n  | Ecase : expr -> pattern_list -> list (type * clock) -> expr                                  (**r case *)\n  | Eboolred: int -> int -> expr -> (type * clock) -> expr\n  | Ediese: expr -> (type * clock) -> expr  (**r #(a1, ..., an) -> boolred(0,1,n)[a1, ..., an] *)\n  | Enor: expr -> (type * clock) -> expr  (**r nor(a1, ..., an) boolred(0,0,n)[a1, ..., an] *)\n  | Etypecmp : bool -> expr -> expr -> (type * clock) -> expr\n  | Eprefix: binary_operationL -> expr_list -> (type * clock) -> expr\n\nwith expr_list : Type :=\n  | Enil: expr_list\n  | Econs: expr -> expr_list -> expr_list\n\nwith label_index_list: Type :=\n  | Lnil: label_index_list\n  | LconsLabel: ident -> label_index_list -> label_index_list\n  | LconsIndex: expr -> label_index_list -> label_index_list\n\nwith pattern_list : Type :=\n  | PatternNil : pattern_list\n  | PatternCon : patn -> expr -> pattern_list -> pattern_list.\n\nFixpoint typeclock_of (e: expr) : list (type * clock) := \n  match e with\n  | Econst _ t c => (t,c)::nil\n  | Evar _ t c => (t,c)::nil                                                   \n  | ListExpr l => typeclocks_of l   \n  | Ecall _ _ tcl => tcl                                      \n  | Efor _ _ _ _ tcl => tcl  \n  | Econstruct _ tc => tc::nil  \n  | Earrayacc _ _ tc => tc::nil  \n  | Earraydiff _ tc => tc::nil  \n  | Earrayproj _ _ _ tc => tc::nil  \n  | Emix _ _ _ tc => tc::nil  \n  | Eunop _ _ tc => tc::nil  \n  | Ebinop _ _ _ tc => tc::nil  \n  | Efield _  _ tc => tc::nil  \n  | Epre _ _ tcl => tcl  \n  | Efby _ _ _ tcl => tcl  \n  | Efbyn _ _ _ _ tcl => tcl  \n  | Earrow _ _ tcl => tcl  \n  | Ewhen _ _ tcl => tcl\n  | Ecurrent _ _ tcl => tcl\n  | Emerge _ _ _ tcl => tcl\n  | Eif _ _ _ tcl => tcl  \n  | Ecase _ _ tcl => tcl  \n  | Eboolred _ _ _ tc => tc:: nil \n  | Ediese _ tc => tc:: nil \n  | Enor _ tc => tc :: nil\n  | Etypecmp _ _ _ tc => tc :: nil\n  | Eprefix _ _ tc => tc :: nil\n  end\n\nwith typeclocks_of (e: expr_list) : list (type * clock) :=\n  match e with \n  | Enil => nil\n  | Econs e etl => app (typeclock_of e) (typeclocks_of etl)\n  end.\n\n(** * Equation *)\n\nInductive equation : Type :=\n  | Equation: vars -> expr -> equation.\n\n(** * Node *)\n\nRecord node: Type := mknode {\n  nd_kind: bool;                 (**r node kind. *)\n  nd_args: vars;                 (**r input parameters. *)\n  nd_rets: vars;                 (**r output parameters. *)\n  nd_vars: vars;                 (**r local variables. *)\n  nd_eqs: list equation         (**r statement. *) \n}.\n\n(** * Program *)\n\nDefinition program : Type := general_program node.\n\nScheme exprs_ind2 :=\n  Induction for expr Sort Prop\nwith expr_lists_ind2 :=\n  Induction for expr_list Sort Prop\nwith pattern_lists_ind2 :=\n  Induction for pattern_list Sort Prop\nwith label_index_list_ind2 :=\n  Induction for label_index_list Sort Prop.\n\nScheme exprs_ind3 := Minimality for expr Sort Prop\n  with expr_lists_ind3 := Minimality for expr_list Sort Prop\n  with pattern_lists_ind3 := Minimality for pattern_list Sort Prop\n  with label_lindex_lists_ind3 := Minimality for label_index_list Sort Prop.  \n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/src/LustreV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.19375418408770267}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Syntax.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Semantics.\nRequire Import Extend.\nRequire Import System.\nRequire Import Uniform.\nRequire Import Ofe.\nRequire Import SemanticsKuniv.\nRequire Import SemanticsUniv.\nRequire Import Page.\nRequire Import Equality.\nRequire Import SemanticsProperty.\n\n\nDefinition agree (pg : page) (system system' : System) : Prop :=\n  sint system pg = sint system' pg\n  /\\ sintk system pg = sintk system' pg.\n\n\nLemma semantics_mono :\n  forall system system',\n    (forall pg s i a X,\n       (forall pg', str pg' << str pg -> agree pg' system system')\n       -> kbasic system pg s i a X\n       -> kbasic system' pg s i a X)\n    /\\\n    (forall pg s i a X,\n       (forall pg', str pg' << str pg -> agree pg' system system')\n       -> cbasic system pg s i a X\n       -> cbasic system' pg s i a X)\n    /\\\n    (forall pg s i a X,\n       (forall pg', str pg' << str pg -> agree pg' system system')\n       -> basic system pg s i a X\n       -> basic system' pg s i a X).\nProof.\nintros system system'.\nexploit\n  (semantics_ind system\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> kbasicv system' pg s i a X)\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> cbasicv system' pg s i a X)\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> basicv system' pg s i a X)\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> kbasic system' pg s i a X)\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> cbasic system' pg s i a X)\n     (fun pg s i a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> basic system' pg s i a X)\n     (fun pg s i A a X => \n        (forall pg', str pg' << str pg -> agree pg' system system')\n        -> functional system' pg s i A a X)) as Hind;\ntry (intros; eauto using kbasicv, cbasicv, basicv, kbasic, cbasic, basic, functional, lt_le_ord_trans; done).\n\n(* con *)\n{\nintros pg s i lv a gpg R Hlv Hle _ IH Hincl.\napply interp_con; auto.\napply IH.\nintros pg' Hlt.\napply Hincl.\neapply lt_le_ord_trans; eauto.\napply str_mono; auto.\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 Hle _ IH2 Hincl.\napply (interp_all _#7 gpg _ _ h); auto.\napply IH1.\nintros pg' Hlt.\napply Hincl.\neapply lt_le_ord_trans; eauto.\napply str_mono; auto.\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 Hle _ IH2 Hincl.\napply (interp_exist _#7 gpg _ _ h); auto.\napply IH1.\nintros pg' Hlt.\napply Hincl.\neapply lt_le_ord_trans; eauto.\napply str_mono; auto.\n}\n\n(* univ *)\n{\nintros pg s i lv gpg Hlv Hstr Hcex Hincl.\nreplace (iuuniv system i gpg) with (iuuniv system' i gpg).\n  {\n  apply interp_univ; auto.\n  }\nunfold iuuniv.\nf_equal.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\nso (Hincl gpg Hstr andel) as Heq.\npextensionality.\n  {\n  intros (Hj & R & H).\n  split; auto.\n  exists R.\n  rewrite <- Heq in H.\n  auto.\n  }\n\n  {\n  intros (Hj & R & H).\n  split; auto.\n  exists R.\n  rewrite -> Heq in H.\n  auto.\n  }\n}\n\n(* kuniv *)\n{\nintros pg s i lv gpg h Hlv Hlt Hincl.\nreplace (iukuniv system i gpg h) with (iukuniv system' i gpg h).\n  {\n  apply interp_kuniv; auto.\n  }\nunfold iukuniv.\nf_equal.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\nso (lt_le_page_trans _#3 (lt_page_succ _ _) (lt_page_impl_le_page _ _ Hlt)) as Hlt'.\nso (Hincl gpg (Hlt' andel) ander) as HeqK.\nso (Hincl (succ_page gpg h) (Hlt andel) andel) as HeqR.\npextensionality.\n  {\n  intros (Hj & K & R & H).\n  split; auto.\n  exists K, R.\n  rewrite <- HeqK in H.\n  rewrite <- HeqR in H.\n  auto.\n  }\n\n  {\n  intros (Hj & K & R & H).\n  split; auto.\n  exists K, R.\n  rewrite -> HeqK in H.\n  rewrite -> HeqR in H.\n  auto.\n  }\n}\n\n(* wrapup *)\n{\ndestruct_all Hind; do2 2 split; intros; eauto.\n}\nQed.\n\n\nLemma kbasic_mono :\n  forall system system' pg s i a R,\n    (forall pg', str pg' << str pg -> agree pg' system system')\n    -> kbasic system pg s i a R\n    -> kbasic system' pg s i a R.\nProof.\nintros system system'.\nexact (semantics_mono system system' andel).\nQed.\n\n\nLemma basic_mono :\n  forall system system' pg s i a R,\n    (forall pg', str pg' << str pg -> agree pg' system system')\n    -> basic system pg s i a R\n    -> basic system' pg s i a R.\nProof.\nintros system system'.\nexact (semantics_mono system system' anderr).\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/ProperMono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.19373854476930166}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Coq.Program.Program\n        Coq.Sets.Ensembles\n        Coq.Arith.Arith.\nRequire Import\n        Fiat.Common.IterateBoundedIndex\n        Fiat.ADT\n        Fiat.ADT.ComputationalADT\n        Fiat.ADTNotation\n        Fiat.ADTRefinement\n        Fiat.ADTRefinement.BuildADTRefinements\n        Fiat.Fiat4Monitors.RADL_Topics\n        Fiat.Fiat4Monitors.RADL_Messages\n        Fiat.Fiat4Monitors.RADL_Flags\n        Fiat.Fiat4Monitors.RADL_Nodes\n        Fiat.Fiat4Monitors.LandsharkTopics\n        Fiat.Fiat4Monitors.LandsharkNodes\n        Bedrock.Word.\n\nSection HealthMonitorSpec.\n\n  Open Scope string_scope.\n  Open Scope list_scope.\n  Open Scope ADTSig_scope.\n  Open Scope ADT_scope.\n\n  Definition HealthMonitorSig\n  : ADTSig :=                         (* A RADL Node is modeled as an ADT with a  *)\n    ADTsignature {                    (* single constructor and a step function. *)\n        Constructor RADL_Init      : unit -> rep,\n        Method      RADL_Step      : rep x ((cRep (radl_in_t health_monitor)) * (cRep (radl_in_flags_t health_monitor)))\n                                     -> rep x (Memory.W * Memory.W * (cRep (radl_out_t health_monitor))\n                                               * (cRep (radl_out_flags_t health_monitor)))\n      }.\n\n  Inductive BitAtIndex (P : nat -> bool -> Prop)\n    : forall n, Word.word n -> nat -> Prop :=\n  | WordIndex_hd : forall n b w,\n      P n b -> BitAtIndex P (@WS b n w) 0\n  | WordIndex_tl : forall n n' b w,\n      BitAtIndex P w n'\n      -> BitAtIndex P (@WS b n w) (S n').\n\n  Fixpoint Iterate_Build_Word\n             (n : nat)\n             (P : nat -> bool -> Prop)\n    : Comp (Word.word n)\n    :=  match n with\n        | S n =>\n          b <- {b | P (S n) b};\n            w <- Iterate_Build_Word P;\n            ret (WS b w)\n        | 0 => ret WO\n        end.\n\n  Definition foo :\n    forall idx, \n    snd\n    (MethodDomCod (FlagADTSig (RADL_Subscriptions health_monitor))\n                  (BuildGetFlagMethodID (RADL_Subscriptions health_monitor) idx)) -> Memory.W.\n      intro; eapply Iterate_Dep_Type_BoundedIndex_equiv_1 with (idx := idx).\n      admit.\n      cbv delta [health_monitor] beta iota.\n      cbv delta [RADL_Subscriptions] beta iota.\n      cbv delta [LiftTopics] beta iota zeta.\n      Set Printing All.\n      match goal with\n        |- context [@Build_IndexBound ?A ?B ?C ?D ?E] =>\n        let bob := fresh in \n        set (bob := C) in *\n      end.\n      match goal with\n        |- context [@Build_IndexBound ?A ?B ?C ?D ?E] =>\n        let bob := fresh in \n        set (bob := C) in *\n      end.\n      \n\n      cbv delta [map] beta iota zeta.\n      cbv beta.\n      simpl.\n      Print Iterate_Dep_Type_equiv.\n      Print Dep_Type_BoundedIndex_nth_eq.\n      with\n      (P := fun idx => snd\n                         (MethodDomCod (FlagADTSig (RADL_Subscriptions health_monitor))\n                                       (BuildGetFlagMethodID (RADL_Subscriptions health_monitor) idx)) -> Memory.W).\n      Focus 3.\n      apply Iterate_Dep_Type.\n\n      \n  Variable bar :\n    forall idx, \n    snd\n    (MethodDomCod (MessageADTSig (RADL_Subscriptions health_monitor))\n                  (BuildGetMessageMethodID (RADL_Subscriptions health_monitor) idx)) -> Memory.W.\n\n  Definition HealthMonitorSpec : ADT HealthMonitorSig :=\n    ADTRep unit (* Since RADL Nodes are untrusted, we'll treat their state as completely unknown *)\n           { Def Constructor RADL_Init (_ : _) : rep := ret tt,\n             Def Method RADL_Step (r : rep, in' : (cRep (radl_in_t health_monitor) * (cRep (radl_in_flags_t health_monitor)))) : _ :=\n               let (in_, in_flags) := in' in\n               health_reports <- {report |\n                                  forall n,\n                                    BitAtIndex\n                                      (fun n b =>\n                                         forall a nth_n t,\n                                           radl_is_timeout (foo _ (snd (CallFlagGetMethod in_flags {| bindex := a;\n                                                                              indexb := {| ibound := n;\n                                                                                           boundi := nth_n |} |} t))) = b)\n                                      report n};\n             flag_reports <- {report | \n                              forall n,\n                                BitAtIndex\n                                  (fun n b =>\n                                     forall a nth_n t,\n                                       radl_is_timeout (bar _\n                                                            (snd (CallMessageGetMethod in_ {| bindex := a;\n                                                                                                     indexb := {| ibound := n;\n                                                                                                                  boundi := nth_n |} |} t))) = b)\n                                  report n};\n             ret (tt, (health_reports, flag_reports, inil _, inil _))\n           }.\n  \n\n\n  \nEnd HealthMonitorSpec.\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/Fiat4Monitors/HealthMonitor/HealthMonitorSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.1937385379743764}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*         Xavier Leroy, Coll\u00e8ge 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(** 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 processor-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 Axioms Coqlib BoolEqual.\nRequire Import AST Integers Floats Values Memory Globalenvs Events.\n\nSet Implicit Arguments.\nLocal Transparent Archi.ptr64.\n\n(** Shift amounts *)\n\nRecord amount32 : Type := {\n  a32_amount :> int;\n  a32_range  : Int.ltu a32_amount Int.iwordsize = true }.\n\nRecord amount64 : Type := {\n  a64_amount :> int;\n  a64_range  : Int.ltu a64_amount Int64.iwordsize' = true }.\n\n(** Shifted operands *)\n\nInductive shift : Type :=\n  | Slsl                                (**r left shift *)\n  | Slsr                                (**r right unsigned shift *)\n  | Sasr                                (**r right signed shift *)\n  | Sror.                               (**r rotate right *)\n\n(** Sign- or zero-extended operands *)\n\nInductive extension : Type :=\n  | Xsgn32                              (**r from signed 32-bit integer to 64-bit integer *)\n  | Xuns32.                             (**r from unsigned 32-bit integer to 64-bit integer *)\n\n(** Conditions (boolean-valued operators). *)\n\nInductive condition: Type :=\n(** Tests over 32-bit integers *)\n  | Ccomp (c: comparison)                               (**r signed comparison *)\n  | Ccompu (c: comparison)                              (**r unsigned comparison *)\n  | Ccompimm (c: comparison) (n: int)                   (**r signed comparison with constant *)\n  | Ccompuimm (c: comparison) (n: int)                  (**r unsigned comparison with constant *)\n  | Ccompshift (c: comparison) (s: shift) (a: amount32) (**r signed comparison with shift *)\n  | Ccompushift (c: comparison) (s: shift) (a: amount32)(**r unsigned comparison width shift *)\n  | Cmaskzero (n: int)                                  (**r test [(arg & n) == 0] *)\n  | Cmasknotzero (n: int)                               (**r test [(arg & n) != 0] *)\n(** Tests over 64-bit integers *)\n  | Ccompl (c: comparison)                              (**r signed comparison *)\n  | Ccomplu (c: comparison)                             (**r unsigned comparison *)\n  | Ccomplimm (c: comparison) (n: int64)                (**r signed comparison with constant *)\n  | Ccompluimm (c: comparison) (n: int64)               (**r unsigned comparison with constant *)\n  | Ccomplshift (c: comparison) (s: shift) (a: amount64)(**r signed comparison with shift *)\n  | Ccomplushift (c: comparison) (s: shift) (a: amount64)(**r unsigned comparison width shift *)\n  | Cmasklzero (n: int64)                               (**r test [(arg & n) == 0] *)\n  | Cmasklnotzero (n: int64)                            (**r test [(arg & n) != 0] *)\n(** Tests over 64-bit floating-point numbers *)\n  | Ccompf (c: comparison)                              (**r FP comparison *)\n  | Cnotcompf (c: comparison)                           (**r negation of an FP comparison *)\n  | Ccompfzero (c: comparison)                          (**r comparison with 0.0 *)\n  | Cnotcompfzero (c: comparison)                       (**r negation of comparison with 0.0 *)\n(** Tests over 32-bit floating-point numbers *)\n  | Ccompfs (c: comparison)                             (**r FP comparison *)\n  | Cnotcompfs (c: comparison)                          (**r negation of an FP comparison *)\n  | Ccompfszero (c: comparison)                         (**r equal to 0.0 *)\n  | Cnotcompfszero (c: comparison).                     (**r not equal to 0.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                                               (**r [rd = r1] *)\n  | Ointconst (n: int)                                  (**r [rd] is set to the given integer constant *)\n  | Olongconst (n: int64)                               (**r [rd] is set to the given integer constant *)\n  | Ofloatconst (n: float)                              (**r [rd] is set to the given float constant *)\n  | Osingleconst (n: float32)                           (**r [rd] is set to the given float constant *)\n  | Oaddrsymbol (id: ident) (ofs: ptrofs)               (**r [rd] is set to the address of the symbol plus the given offset *)\n  | Oaddrstack (ofs: ptrofs)                            (**r [rd] is set to the stack pointer plus the given offset *)\n(** 32-bit integer arithmetic *)\n  | Oshift (s: shift) (a: amount32)                     (**r shift or rotate by immediate quantity *)\n  | Oadd                                                (**r [rd = r1 + r2] *)\n  | Oaddshift (s: shift) (a: amount32)                  (**r [rd = r1 + shifted r2] *)\n  | Oaddimm (n: int)                                    (**r [rd = r1 + n] *)\n  | Oneg                                                (**r [rd = - r1]   *)                     \n  | Onegshift (s: shift) (a: amount32)                  (**r [rd = - shifted r1] *)\n  | Osub                                                (**r [rd = r1 - r2] *)\n  | Osubshift (s: shift) (a: amount32)                  (**r [rd = r1 - shifted r2] *)\n  | Omul                                                (**r [rd = r1 * r2] *)\n  | Omuladd                                             (**r [rd = r1 + r2 * r3] *)\n  | Omulsub                                             (**r [rd = r1 - r2 * r3] *)\n  | Odiv                                                (**r [rd = r1 / r2] (signed) *)\n  | Odivu                                               (**r [rd = r1 / r2] (unsigned) *)\n  | Oand                                                (**r [rd = r1 & r2] *)\n  | Oandshift (s: shift) (a: amount32)                  (**r [rd = r1 & shifted r2] *)\n  | Oandimm (n: int)                                    (**r [rd = r1 & n] *)\n  | Oor                                                 (**r [rd = r1 | r2] *)\n  | Oorshift (s: shift) (a: amount32)                   (**r [rd = r1 | shifted r2] *)\n  | Oorimm (n: int)                                     (**r [rd = r1 | n] *)\n  | Oxor                                                (**r [rd = r1 ^ r2] *)\n  | Oxorshift (s: shift) (a: amount32)                  (**r [rd = r1 ^ shifted r2] *)\n  | Oxorimm (n: int)                                    (**r [rd = r1 ^ n] *)\n  | Onot                                                (**r [rd = ~r1] *)\n  | Onotshift (s: shift) (a: amount32)                  (**r [rd = ~ shifted r1] *)\n  | Obic                                                (**r [rd = r1 & ~r2] *)\n  | Obicshift (s: shift) (a: amount32)                  (**r [rd = r1 ^ ~ shifted r2] *)\n  | Oorn                                                (**r [rd = r1 | ~r2] *)\n  | Oornshift (s: shift) (a: amount32)                  (**r [rd = r1 | ~ shifted r2] *)\n  | Oeqv                                                (**r [rd = r1 ^ ~r2] *)\n  | Oeqvshift (s: shift) (a: amount32)                  (**r [rd = r1 | ~ shifted r2] *)\n  | Oshl                                                (**r [rd = r1 << r2] *)\n  | Oshr                                                (**r [rd = r1 >> r2] (signed) *)\n  | Oshru                                               (**r [rd = r1 >> r2] (unsigned) *)\n  | Oshrximm (n: int)                                   (**r [rd = r1 / 2^n] (signed) *)\n  | Ozext (s: Z)                                        (**r [rd = zero_ext(r1,s)] *)\n  | Osext (s: Z)                                        (**r [rd = sign_ext(r1,s)] *)\n  | Oshlzext (s: Z) (a: amount32)                       (**r [rd = zero_ext(r1,s) << a] *)\n  | Oshlsext (s: Z) (a: amount32)                       (**r [rd = sign_ext(r1,s) << a] *)\n  | Ozextshr (a: amount32) (s: Z)                       (**r [rd = zero_ext(r1 >> a, s)] *)\n  | Osextshr (a: amount32) (s: Z)                       (**r [rd = sign_ext(r1 >> a, s)] *)\n(** 64-bit integer arithmetic *)\n  | Oshiftl (s: shift) (a: amount64)                    (**r shift or rotate by immediate quantity *)\n  | Oextend (x: extension) (a: amount64)                (**r convert from 32 to 64 bits and shift *)\n  | Omakelong                                           (**r [rd = r1 << 32 | r2] *)\n  | Olowlong                                            (**r [rd = low-word(r1)] *)\n  | Ohighlong                                           (**r [rd = high-word(r1)] *)\n  | Oaddl                                               (**r [rd = r1 + r2] *)\n  | Oaddlshift (s: shift) (a: amount64)                 (**r [rd = r1 + shifted r2] *)\n  | Oaddlext (x: extension) (a: amount64)               (**r [rd = r1 + shifted, converted r2] *)\n  | Oaddlimm (n: int64)                                 (**r [rd = r1 + n] *)\n  | Onegl                                               (**r [rd = - r1]   *)                     \n  | Oneglshift (s: shift) (a: amount64)                 (**r [rd = - shifted r1] *)\n  | Osubl                                               (**r [rd = r1 - r2] *)\n  | Osublshift (s: shift) (a: amount64)                 (**r [rd = r1 - shifted r2] *)\n  | Osublext (x: extension) (a: amount64)               (**r [rd = r1 - shifted, converted r2] *)\n  | Omull                                               (**r [rd = r1 * r2] *)\n  | Omulladd                                            (**r [rd = r1 + r2 * r3] *)\n  | Omullsub                                            (**r [rd = r1 - r2 * r3] *)\n  | Omullhs                                             (**r [rd = high part of r1 * r2 (signed)] *)\n  | Omullhu                                             (**r [rd = high part of r1 * r2 (unsigned)] *)\n  | Odivl                                               (**r [rd = r1 / r2] (signed) *)\n  | Odivlu                                              (**r [rd = r1 / r2] (unsigned) *)\n  | Oandl                                               (**r [rd = r1 & r2] *)\n  | Oandlshift (s: shift) (a: amount64)                 (**r [rd = r1 & shifted r2] *)\n  | Oandlimm (n: int64)                                 (**r [rd = r1 & n] *)\n  | Oorl                                                (**r [rd = r1 | r2] *)\n  | Oorlshift (s: shift) (a: amount64)                  (**r [rd = r1 | shifted r2] *)\n  | Oorlimm (n: int64)                                  (**r [rd = r1 | n] *)\n  | Oxorl                                               (**r [rd = r1 ^ r2] *)\n  | Oxorlshift (s: shift) (a: amount64)                 (**r [rd = r1 ^ shifted r2] *)\n  | Oxorlimm (n: int64)                                 (**r [rd = r1 ^ n] *)\n  | Onotl                                               (**r [rd = ~r1] *)\n  | Onotlshift (s: shift) (a: amount64)                 (**r [rd = ~ shifted r1] *)\n  | Obicl                                               (**r [rd = r1 & ~r2] *)\n  | Obiclshift (s: shift) (a: amount64)                 (**r [rd = r1 ^ ~ shifted r2] *)\n  | Oornl                                               (**r [rd = r1 | ~r2] *)\n  | Oornlshift (s: shift) (a: amount64)                 (**r [rd = r1 | ~ shifted r2] *)\n  | Oeqvl                                               (**r [rd = r1 ^ ~r2] *)\n  | Oeqvlshift (s: shift) (a: amount64)                 (**r [rd = r1 | ~ shifted r2] *)\n  | Oshll                                               (**r [rd = r1 << r2] *)\n  | Oshrl                                               (**r [rd = r1 >> r2] (signed) *)\n  | Oshrlu                                              (**r [rd = r1 >> r2] (unsigned) *)\n  | Oshrlximm (n: int)                                  (**r [rd = r1 / 2^n] (signed) *)\n  | Ozextl (s: Z)                                       (**r [rd = zero_ext(r1,s)] *)\n  | Osextl (s: Z)                                       (**r [rd = sign_ext(r1,s)] *)\n  | Oshllzext (s: Z) (a: amount64)                      (**r [rd = zero_ext(r1,s) << a] *)\n  | Oshllsext (s: Z) (a: amount64)                      (**r [rd = sign_ext(r1,s) << a] *)\n  | Ozextshrl (a: amount64) (s: Z)                      (**r [rd = zero_ext(r1 >> a, s)] *)\n  | Osextshrl (a: amount64) (s: Z)                      (**r [rd = sign_ext(r1 >> a, s)] *)\n(** 64-bit floating-point arithmetic *)\n  | Onegf                                               (**r [rd = - r1] *)\n  | Oabsf                                               (**r [rd = abs(r1)] *)\n  | Oaddf                                               (**r [rd = r1 + r2] *)\n  | Osubf                                               (**r [rd = r1 - r2] *)\n  | Omulf                                               (**r [rd = r1 * r2] *)\n  | Odivf                                               (**r [rd = r1 / r2] *)\n(** 32-bit floating-point arithmetic *)\n  | Onegfs                                              (**r [rd = - r1] *)\n  | Oabsfs                                              (**r [rd = abs(r1)] *)\n  | Oaddfs                                              (**r [rd = r1 + r2] *)\n  | Osubfs                                              (**r [rd = r1 - r2] *)\n  | Omulfs                                              (**r [rd = r1 * r2] *)\n  | Odivfs                                              (**r [rd = r1 / r2] *)\n  | Osingleoffloat                                      (**r [rd] is [r1] truncated to single-precision float *)\n  | Ofloatofsingle                                      (**r [rd] is [r1] extended to double-precision float *)\n(** Conversions between int and float *)\n  | Ointoffloat                                         (**r [rd = signed_int_of_float64(r1)] *)\n  | Ointuoffloat                                        (**r [rd = unsigned_int_of_float64(r1)] *)\n  | Ofloatofint                                         (**r [rd = float64_of_signed_int(r1)] *)\n  | Ofloatofintu                                        (**r [rd = float64_of_unsigned_int(r1)] *)\n  | Ointofsingle                                        (**r [rd = signed_int_of_float32(r1)] *)\n  | Ointuofsingle                                       (**r [rd = unsigned_int_of_float32(r1)] *)\n  | Osingleofint                                        (**r [rd = float32_of_signed_int(r1)] *)\n  | Osingleofintu                                       (**r [rd = float32_of_unsigned_int(r1)] *)\n  | Olongoffloat                                        (**r [rd = signed_long_of_float64(r1)] *)\n  | Olonguoffloat                                       (**r [rd = unsigned_long_of_float64(r1)] *)\n  | Ofloatoflong                                        (**r [rd = float64_of_signed_long(r1)] *)\n  | Ofloatoflongu                                       (**r [rd = float64_of_unsigned_long(r1)] *)\n  | Olongofsingle                                       (**r [rd = signed_long_of_float32(r1)] *)\n  | Olonguofsingle                                      (**r [rd = unsigned_long_of_float32(r1)] *)\n  | Osingleoflong                                       (**r [rd = float32_of_signed_long(r1)] *)\n  | Osingleoflongu                                      (**r [rd = float32_of_unsigned_int(r1)] *)\n(** Boolean tests *)\n  | Ocmp (cond: condition)                              (**r [rd = 1] if condition holds, [rd = 0] otherwise. *)\n  | Osel (cond: condition) (ty: typ).                   (**r [rd = rs1] if condition holds, [rd = rs2] otherwise. *)\n\n(** Addressing modes.  [r1], [r2], etc, are the arguments to the addressing. *)\n\nInductive addressing: Type :=\n  | Aindexed (ofs: int64)                               (**r Address is [r1 + offset] *)\n  | Aindexed2                                           (**r Address is [r1 + r2] *)\n  | Aindexed2shift (a: amount64)                        (**r Address is [r1 + r2 << a] *)\n  | Aindexed2ext (x: extension) (a: amount64)           (**r Address is [r1 + sign-or-zero-ext(r2) << a] *)\n  | Aglobal (id: ident) (ofs: ptrofs)                   (**r Address is [global + offset] *)\n  | Ainstack (ofs: ptrofs).                             (**r Address is [stack_pointer + offset] *)\n\n(** Comparison functions (used in modules [CSE] and [Allocation]). *)\n\nDefinition eq_amount32 (x y: amount32): {x=y} + {x<>y}.\nProof.\n  destruct x as [x Px], y as [y Py].\n  destruct (Int.eq_dec x y).\n- subst y. assert (Px = Py) by (apply proof_irr). subst Py. left; auto.\n- right; congruence.\nDefined.\n\nDefinition eq_amount64 (x y: amount64): {x=y} + {x<>y}.\nProof.\n  destruct x as [x Px], y as [y Py].\n  destruct (Int.eq_dec x y).\n- subst y. assert (Px = Py) by (apply proof_irr). subst Py. left; auto.\n- right; congruence.\nDefined.\n\nDefinition eq_shift (x y: shift): {x=y} + {x<>y}.\nProof.\n  decide equality.\nDefined.\n\nDefinition eq_extension (x y: extension): {x=y} + {x<>y}.\nProof.\n  decide equality.\nDefined.\n\nDefinition eq_condition (x y: condition) : {x=y} + {x<>y}.\nProof.\n  assert (forall (x y: comparison), {x=y}+{x<>y}) by decide equality.\n  generalize Int.eq_dec Int64.eq_dec eq_shift eq_amount32 eq_amount64; intro.\n  decide equality.\nDefined.\n\nDefinition eq_addressing (x y: addressing) : {x=y} + {x<>y}.\nProof.\n  generalize ident_eq Int64.eq_dec Ptrofs.eq_dec eq_extension eq_amount64; intros.\n  decide equality.\nDefined.\n\nDefinition eq_operation: forall (x y: operation), {x=y} + {x<>y}.\nProof.\n  intros.\n  generalize Int.eq_dec Int64.eq_dec Ptrofs.eq_dec Float.eq_dec Float32.eq_dec\n             zeq ident_eq eq_shift eq_extension eq_amount32 eq_amount64\n             typ_eq eq_condition; \n  decide equality.\nDefined.\n\n(** Alternative:\n\nDefinition beq_operation: forall (x y: operation), bool.\nProof.\n  generalize Int.eq_dec Int64.eq_dec Ptrofs.eq_dec Float.eq_dec Float32.eq_dec\n             zeq ident_eq eq_shift eq_extension eq_amount32 eq_amount64\n             eq_condition typ_eq; boolean_equality.\nDefined.\n\nDefinition eq_operation: forall (x y: operation), {x=y} + {x<>y}.\nProof.\n  decidable_equality_from beq_operation.\nDefined.\n*)\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_shift (s: shift) (v: val) (n: amount32) : val :=\n  match s with\n  | Slsl => Val.shl v (Vint n)\n  | Slsr => Val.shru v (Vint n)\n  | Sasr => Val.shr v (Vint n)\n  | Sror => Val.ror v (Vint n)\n  end.\n\nDefinition eval_shiftl (s: shift) (v: val) (n: amount64) : val :=\n  match s with\n  | Slsl => Val.shll v (Vint n)\n  | Slsr => Val.shrlu v (Vint n)\n  | Sasr => Val.shrl v (Vint n)\n  | Sror => Val.rorl v (Vint n)\n  end.\n\nDefinition eval_extend (x: extension) (v: val) (n: amount64) : val :=\n  Val.shll\n    (match x with\n      | Xsgn32 => Val.longofint v\n      | Xuns32 => Val.longofintu v\n     end)\n    (Vint n).\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  | Ccompshift c s a, v1 :: v2 :: nil => Val.cmp_bool c v1 (eval_shift s v2 a)\n  | Ccompushift c s a, v1 :: v2 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 (eval_shift s v2 a)\n  | Cmaskzero n, v1 :: nil => Val.cmp_bool Ceq (Val.and v1 (Vint n)) (Vint Int.zero)\n  | Cmasknotzero n, v1 :: nil => Val.cmp_bool Cne (Val.and v1 (Vint n)) (Vint Int.zero)\n\n  | Ccompl c, v1 :: v2 :: nil => Val.cmpl_bool c v1 v2\n  | Ccomplu c, v1 :: v2 :: nil => Val.cmplu_bool (Mem.valid_pointer m) c v1 v2\n  | Ccomplimm c n, v1 :: nil => Val.cmpl_bool c v1 (Vlong n)\n  | Ccompluimm c n, v1 :: nil => Val.cmplu_bool (Mem.valid_pointer m) c v1 (Vlong n)\n  | Ccomplshift c s a, v1 :: v2 :: nil => Val.cmpl_bool c v1 (eval_shiftl s v2 a)\n  | Ccomplushift c s a, v1 :: v2 :: nil => Val.cmplu_bool (Mem.valid_pointer m) c v1 (eval_shiftl s v2 a)\n  | Cmasklzero n, v1 :: nil => Val.cmpl_bool Ceq (Val.andl v1 (Vlong n)) (Vlong Int64.zero)\n  | Cmasklnotzero n, v1 :: nil => Val.cmpl_bool Cne (Val.andl v1 (Vlong n)) (Vlong Int64.zero)\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  | Ccompfzero c, v1 :: nil => Val.cmpf_bool c v1 (Vfloat Float.zero)\n  | Cnotcompfzero c, v1 :: nil => option_map negb (Val.cmpf_bool c v1 (Vfloat Float.zero))\n\n  | Ccompfs c, v1 :: v2 :: nil => Val.cmpfs_bool c v1 v2\n  | Cnotcompfs c, v1 :: v2 :: nil => option_map negb (Val.cmpfs_bool c v1 v2)\n  | Ccompfszero c, v1 :: nil => Val.cmpfs_bool c v1 (Vsingle Float32.zero)\n  | Cnotcompfszero c, v1 :: nil => option_map negb (Val.cmpfs_bool c v1 (Vsingle Float32.zero))\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  | Olongconst n, nil => Some (Vlong 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\n  | Oshift s a, v1 :: nil => Some (eval_shift s v1 a)\n  | Oadd, v1 :: v2 :: nil => Some (Val.add v1 v2)\n  | Oaddshift s a, v1 :: v2 :: nil => Some (Val.add v1 (eval_shift s v2 a))\n  | Oaddimm n, v1 :: nil => Some (Val.add v1 (Vint n))\n  | Oneg, v1 :: nil => Some (Val.neg v1)\n  | Onegshift s a, v1 :: nil => Some (Val.neg (eval_shift s v1 a))\n  | Osub, v1 :: v2 :: nil => Some (Val.sub v1 v2)\n  | Osubshift s a, v1 :: v2 :: nil => Some (Val.sub v1 (eval_shift s v2 a))\n  | Omul, v1 :: v2 :: nil => Some (Val.mul v1 v2)\n  | Omuladd, v1 :: v2 :: v3 :: nil => Some (Val.add v1 (Val.mul v2 v3))\n  | Omulsub, v1 :: v2 :: v3 :: nil => Some (Val.sub v1 (Val.mul v2 v3))\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  | Oandshift s a, v1 :: v2 :: nil => Some (Val.and v1 (eval_shift s v2 a))\n  | Oandimm n, v1 :: nil => Some (Val.and v1 (Vint n))\n  | Oor, v1 :: v2 :: nil => Some (Val.or v1 v2)\n  | Oorshift s a, v1 :: v2 :: nil => Some (Val.or v1 (eval_shift s v2 a))\n  | Oorimm n, v1 :: nil => Some (Val.or v1 (Vint n))\n  | Oxor, v1 :: v2 :: nil => Some (Val.xor v1 v2)\n  | Oxorshift s a, v1 :: v2 :: nil => Some (Val.xor v1 (eval_shift s v2 a))\n  | Oxorimm n, v1 :: nil => Some (Val.xor v1 (Vint n))\n  | Onot, v1 :: nil => Some (Val.notint v1)\n  | Onotshift s a, v1 :: nil => Some (Val.notint (eval_shift s v1 a))\n  | Obic, v1 :: v2 :: nil => Some (Val.and v1 (Val.notint v2))\n  | Obicshift s a, v1 :: v2 :: nil => Some (Val.and v1 (Val.notint (eval_shift s v2 a)))\n  | Oorn, v1 :: v2 :: nil => Some (Val.or v1 (Val.notint v2))\n  | Oornshift s a, v1 :: v2 :: nil => Some (Val.or v1 (Val.notint (eval_shift s v2 a)))\n  | Oeqv, v1 :: v2 :: nil => Some (Val.xor v1 (Val.notint v2))\n  | Oeqvshift s a, v1 :: v2 :: nil => Some (Val.xor v1 (Val.notint (eval_shift s v2 a)))\n  | Oshl, v1 :: v2 :: nil => Some (Val.shl v1 v2)\n  | Oshr, v1 :: v2 :: nil => Some (Val.shr v1 v2)\n  | Oshru, v1 :: v2 :: nil => Some (Val.shru v1 v2)\n  | Oshrximm n, v1::nil => Val.shrx v1 (Vint n)\n  | Ozext s, v1 :: nil => Some (Val.zero_ext s v1)\n  | Osext s, v1 :: nil => Some (Val.sign_ext s v1)\n  | Oshlzext s a, v1 :: nil => Some (Val.shl (Val.zero_ext s v1) (Vint a))\n  | Oshlsext s a, v1 :: nil => Some (Val.shl (Val.sign_ext s v1) (Vint a))\n  | Ozextshr a s, v1 :: nil => Some (Val.zero_ext s (Val.shru v1 (Vint a)))\n  | Osextshr a s, v1 :: nil => Some (Val.sign_ext s (Val.shr v1 (Vint a)))\n\n  | Oshiftl s a, v1 :: nil => Some (eval_shiftl s v1 a)\n  | Oextend x a, v1 :: nil => Some (eval_extend x v1 a)\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  | Oaddl, v1 :: v2 :: nil => Some (Val.addl v1 v2)\n  | Oaddlshift s a, v1 :: v2 :: nil => Some (Val.addl v1 (eval_shiftl s v2 a))\n  | Oaddlext x a, v1 :: v2 :: nil => Some (Val.addl v1 (eval_extend x v2 a))\n  | Oaddlimm n, v1 :: nil => Some (Val.addl v1 (Vlong n))\n  | Onegl, v1 :: nil => Some (Val.negl v1)\n  | Oneglshift s a, v1 :: nil => Some (Val.negl (eval_shiftl s v1 a))\n  | Osubl, v1 :: v2 :: nil => Some (Val.subl v1 v2)\n  | Osublshift s a, v1 :: v2 :: nil => Some (Val.subl v1 (eval_shiftl s v2 a))\n  | Osublext x a, v1 :: v2 :: nil => Some (Val.subl v1 (eval_extend x v2 a))\n  | Omull, v1 :: v2 :: nil => Some (Val.mull v1 v2)\n  | Omulladd, v1 :: v2 :: v3 :: nil => Some (Val.addl v1 (Val.mull v2 v3))\n  | Omullsub, v1 :: v2 :: v3 :: nil => Some (Val.subl v1 (Val.mull v2 v3))\n  | Omullhs, v1::v2::nil => Some (Val.mullhs v1 v2)\n  | Omullhu, v1::v2::nil => Some (Val.mullhu v1 v2)\n  | Odivl, v1 :: v2 :: nil => Val.divls v1 v2\n  | Odivlu, v1 :: v2 :: nil => Val.divlu v1 v2\n  | Oandl, v1 :: v2 :: nil => Some (Val.andl v1 v2)\n  | Oandlshift s a, v1 :: v2 :: nil => Some (Val.andl v1 (eval_shiftl s v2 a))\n  | Oandlimm n, v1 :: nil => Some (Val.andl v1 (Vlong n))\n  | Oorl, v1 :: v2 :: nil => Some (Val.orl v1 v2)\n  | Oorlshift s a, v1 :: v2 :: nil => Some (Val.orl v1 (eval_shiftl s v2 a))\n  | Oorlimm n, v1 :: nil => Some (Val.orl v1 (Vlong n))\n  | Oxorl, v1 :: v2 :: nil => Some (Val.xorl v1 v2)\n  | Oxorlshift s a, v1 :: v2 :: nil => Some (Val.xorl v1 (eval_shiftl s v2 a))\n  | Oxorlimm n, v1 :: nil => Some (Val.xorl v1 (Vlong n))\n  | Onotl, v1 :: nil => Some (Val.notl v1)\n  | Onotlshift s a, v1 :: nil => Some (Val.notl (eval_shiftl s v1 a))\n  | Obicl, v1 :: v2 :: nil => Some (Val.andl v1 (Val.notl v2))\n  | Obiclshift s a, v1 :: v2 :: nil => Some (Val.andl v1 (Val.notl (eval_shiftl s v2 a)))\n  | Oornl, v1 :: v2 :: nil => Some (Val.orl v1 (Val.notl v2))\n  | Oornlshift s a, v1 :: v2 :: nil => Some (Val.orl v1 (Val.notl (eval_shiftl s v2 a)))\n  | Oeqvl, v1 :: v2 :: nil => Some (Val.xorl v1 (Val.notl v2))\n  | Oeqvlshift s a, v1 :: v2 :: nil => Some (Val.xorl v1 (Val.notl (eval_shiftl s v2 a)))\n  | Oshll, v1 :: v2 :: nil => Some (Val.shll v1 v2)\n  | Oshrl, v1 :: v2 :: nil => Some (Val.shrl v1 v2)\n  | Oshrlu, v1 :: v2 :: nil => Some (Val.shrlu v1 v2)\n  | Oshrlximm n, v1::nil => Val.shrxl v1 (Vint n)\n  | Ozextl s, v1 :: nil => Some (Val.zero_ext_l s v1)\n  | Osextl s, v1 :: nil => Some (Val.sign_ext_l s v1)\n  | Oshllzext s a, v1 :: nil => Some (Val.shll (Val.zero_ext_l s v1) (Vint a))\n  | Oshllsext s a, v1 :: nil => Some (Val.shll (Val.sign_ext_l s v1) (Vint a))\n  | Ozextshrl a s, v1 :: nil => Some (Val.zero_ext_l s (Val.shrlu v1 (Vint a)))\n  | Osextshrl a s, v1 :: nil => Some (Val.sign_ext_l s (Val.shrl v1 (Vint a)))\n\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\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\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  | Ointofsingle, v1::nil => Val.intofsingle v1\n  | Ointuofsingle, v1::nil => Val.intuofsingle v1\n  | Osingleofint, v1::nil => Val.singleofint v1\n  | Osingleofintu, v1::nil => Val.singleofintu v1\n  | Olongoffloat, v1::nil => Val.longoffloat v1\n  | Olonguoffloat, v1::nil => Val.longuoffloat v1\n  | Ofloatoflong, v1::nil => Val.floatoflong v1\n  | Ofloatoflongu, v1::nil => Val.floatoflongu v1\n  | Olongofsingle, v1::nil => Val.longofsingle v1\n  | Olonguofsingle, v1::nil => Val.longuofsingle v1\n  | Osingleoflong, v1::nil => Val.singleoflong v1\n  | Osingleoflongu, v1::nil => Val.singleoflongu v1\n\n  | Ocmp c, _ => Some (Val.of_optbool (eval_condition c vl m))\n  | Osel c ty, v1::v2::vl => Some(Val.select (eval_condition c vl m) v1 v2 ty)\n  | _, _ => None\n  end.\n\nDefinition eval_addressing\n    (F V: Type) (genv: Genv.t F V) (sp: val)\n    (addr: addressing) (vl: list val) : option val :=\n  match addr, vl with\n  | Aindexed n, v1 :: nil => Some (Val.addl v1 (Vlong n))\n  | Aindexed2, v1 :: v2 :: nil => Some (Val.addl v1 v2)\n  | Aindexed2shift a, v1 :: v2 :: nil => Some (Val.addl v1 (Val.shll v2 (Vint a)))\n  | Aindexed2ext x a, v1 :: v2 :: nil => Some (Val.addl v1 (eval_extend x v2 a))\n  | Aglobal s ofs, nil => Some (Genv.symbol_address genv s ofs)\n  | Ainstack n, nil => Some (Val.offset_ptr sp n)\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; FuncInv\n  | H: (match ?v with Vundef => _ | Vint _ => _ | Vfloat _ => _ | Vptr _ _ => _ end = Some _) |- _ =>\n      destruct v; simpl in H; FuncInv\n  | H: (if Archi.ptr64 then _ else _) = Some _ |- _ =>\n      change Archi.ptr64 with true in H; simpl in H; FuncInv\n  | H: (Some _ = Some _) |- _ =>\n      injection H; intros; clear H; FuncInv\n  | H: (None = Some _) |- _ =>\n      discriminate H\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  | Ccompshift _ _ _ => Tint :: Tint :: nil\n  | Ccompushift _ _ _ => Tint :: Tint :: nil\n  | Cmaskzero _ => Tint :: nil\n  | Cmasknotzero _ => Tint :: nil\n  | Ccompl _ => Tlong :: Tlong :: nil\n  | Ccomplu _ => Tlong :: Tlong :: nil\n  | Ccomplimm _ _ => Tlong :: nil\n  | Ccompluimm _ _ => Tlong :: nil\n  | Ccomplshift _ _ _ => Tlong :: Tlong :: nil\n  | Ccomplushift _ _ _ => Tlong :: Tlong :: nil\n  | Cmasklzero _ => Tlong :: nil\n  | Cmasklnotzero _ => Tlong :: nil\n  | Ccompf _ => Tfloat :: Tfloat :: nil\n  | Cnotcompf _ => Tfloat :: Tfloat :: nil\n  | Ccompfzero _ => Tfloat :: nil\n  | Cnotcompfzero _ => Tfloat :: nil\n  | Ccompfs _ => Tsingle :: Tsingle :: nil\n  | Cnotcompfs _ => Tsingle :: Tsingle :: nil\n  | Ccompfszero _ => Tsingle :: nil\n  | Cnotcompfszero _ => Tsingle :: 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  | Olongconst _ => (nil, Tlong)\n  | Ofloatconst f => (nil, Tfloat)\n  | Osingleconst f => (nil, Tsingle)\n  | Oaddrsymbol _ _ => (nil, Tptr)\n  | Oaddrstack _ => (nil, Tptr)\n\n  | Oshift _ _ => (Tint :: nil, Tint)\n  | Oadd => (Tint :: Tint :: nil, Tint)\n  | Oaddshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oaddimm _ => (Tint :: nil, Tint)\n  | Oneg => (Tint :: nil, Tint)\n  | Onegshift _ _ => (Tint :: nil, Tint)\n  | Osub => (Tint :: Tint :: nil, Tint)\n  | Osubshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Omul => (Tint :: Tint :: nil, Tint)\n  | Omuladd => (Tint :: Tint :: Tint :: nil, Tint)\n  | Omulsub => (Tint :: Tint :: Tint :: nil, Tint)\n  | Odiv => (Tint :: Tint :: nil, Tint)\n  | Odivu => (Tint :: Tint :: nil, Tint)\n  | Oand => (Tint :: Tint :: nil, Tint)\n  | Oandshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oandimm _ => (Tint :: nil, Tint)\n  | Oor => (Tint :: Tint :: nil, Tint)\n  | Oorshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oorimm _ => (Tint :: nil, Tint)\n  | Oxor => (Tint :: Tint :: nil, Tint)\n  | Oxorshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oxorimm _ => (Tint :: nil, Tint)\n  | Onot => (Tint :: nil, Tint)\n  | Onotshift _ _ => (Tint :: nil, Tint)\n  | Obic => (Tint :: Tint :: nil, Tint)\n  | Obicshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oorn => (Tint :: Tint :: nil, Tint)\n  | Oornshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oeqv => (Tint :: Tint :: nil, Tint)\n  | Oeqvshift _ _ => (Tint :: Tint :: nil, Tint)\n  | Oshl => (Tint :: Tint :: nil, Tint)\n  | Oshr => (Tint :: Tint :: nil, Tint)\n  | Oshru => (Tint :: Tint :: nil, Tint)\n  | Oshrximm _ => (Tint :: nil, Tint)\n  | Ozext _ => (Tint :: nil, Tint)\n  | Osext _ => (Tint :: nil, Tint)\n  | Oshlzext _ _ => (Tint :: nil, Tint)\n  | Oshlsext _ _ => (Tint :: nil, Tint)\n  | Ozextshr _ _ => (Tint :: nil, Tint)\n  | Osextshr _ _ => (Tint :: nil, Tint)\n\n  | Oshiftl _ _ => (Tlong :: nil, Tlong)\n  | Oextend _ _ => (Tint :: nil, Tlong)\n  | Omakelong => (Tint :: Tint :: nil, Tlong)\n  | Olowlong => (Tlong :: nil, Tint)\n  | Ohighlong => (Tlong :: nil, Tint)\n  | Oaddl => (Tlong :: Tlong :: nil, Tlong)\n  | Oaddlshift _ _ => (Tlong :: Tlong :: nil, Tlong) \n  | Oaddlext _ _ => (Tlong :: Tint :: nil, Tlong)\n  | Oaddlimm _ => (Tlong :: nil, Tlong)\n  | Onegl => (Tlong :: nil, Tlong)\n  | Oneglshift _ _ => (Tlong :: nil, Tlong)\n  | Osubl => (Tlong :: Tlong :: nil, Tlong)\n  | Osublshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Osublext _ _ => (Tlong :: Tint :: nil, Tlong)\n  | Omull => (Tlong :: Tlong :: nil, Tlong)\n  | Omulladd => (Tlong :: Tlong :: Tlong :: nil, Tlong)\n  | Omullsub => (Tlong :: Tlong :: Tlong :: nil, Tlong)\n  | Omullhs => (Tlong :: Tlong :: nil, Tlong)\n  | Omullhu => (Tlong :: Tlong :: nil, Tlong)\n  | Odivl => (Tlong :: Tlong :: nil, Tlong)\n  | Odivlu => (Tlong :: Tlong :: nil, Tlong)\n  | Oandl => (Tlong :: Tlong :: nil, Tlong)\n  | Oandlshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oandlimm _ => (Tlong :: nil, Tlong)\n  | Oorl => (Tlong :: Tlong :: nil, Tlong)\n  | Oorlshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oorlimm _ => (Tlong :: nil, Tlong)\n  | Oxorl => (Tlong :: Tlong :: nil, Tlong)\n  | Oxorlshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oxorlimm _ => (Tlong :: nil, Tlong)\n  | Onotl => (Tlong :: nil, Tlong)\n  | Onotlshift _ _ => (Tlong :: nil, Tlong)\n  | Obicl => (Tlong :: Tlong :: nil, Tlong)\n  | Obiclshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oornl => (Tlong :: Tlong :: nil, Tlong)\n  | Oornlshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oeqvl => (Tlong :: Tlong :: nil, Tlong)\n  | Oeqvlshift _ _ => (Tlong :: Tlong :: nil, Tlong)\n  | Oshll => (Tlong :: Tint :: nil, Tlong)\n  | Oshrl => (Tlong :: Tint :: nil, Tlong)\n  | Oshrlu => (Tlong :: Tint :: nil, Tlong)\n  | Oshrlximm _ => (Tlong :: nil, Tlong)\n  | Ozextl _ => (Tlong :: nil, Tlong)\n  | Osextl _ => (Tlong :: nil, Tlong)\n  | Oshllzext _ _ => (Tlong :: nil, Tlong)\n  | Oshllsext _ _ => (Tlong :: nil, Tlong)\n  | Ozextshrl _ _ => (Tlong :: nil, Tlong)\n  | Osextshrl _ _ => (Tlong :: nil, Tlong)\n\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\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\n  | Ointoffloat => (Tfloat :: nil, Tint)\n  | Ointuoffloat => (Tfloat :: nil, Tint)\n  | Ofloatofint => (Tint :: nil, Tfloat)\n  | Ofloatofintu => (Tint :: nil, Tfloat)\n  | Ointofsingle => (Tsingle :: nil, Tint)\n  | Ointuofsingle => (Tsingle :: nil, Tint)\n  | Osingleofint => (Tint :: nil, Tsingle)\n  | Osingleofintu => (Tint :: nil, Tsingle)\n  | Olongoffloat => (Tfloat :: nil, Tlong)\n  | Olonguoffloat => (Tfloat :: nil, Tlong)\n  | Ofloatoflong => (Tlong :: nil, Tfloat)\n  | Ofloatoflongu => (Tlong :: nil, Tfloat)\n  | Olongofsingle => (Tsingle :: nil, Tlong)\n  | Olonguofsingle => (Tsingle :: nil, Tlong)\n  | Osingleoflong => (Tlong :: nil, Tsingle)\n  | Osingleoflongu => (Tlong :: nil, Tsingle)\n\n  | Ocmp c => (type_of_condition c, Tint)\n  | Osel c ty => (ty :: ty :: type_of_condition c, ty)\n  end.\n\nDefinition type_of_addressing (addr: addressing) : list typ :=\n  match addr with\n  | Aindexed _ => Tptr :: nil\n  | Aindexed2 => Tptr :: Tlong :: nil\n  | Aindexed2shift _ => Tptr :: Tlong :: nil\n  | Aindexed2ext _ _ => Tptr :: Tint :: nil\n  | Aglobal _ _ => 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\nRemark type_add:\n  forall v1 v2, Val.has_type (Val.add v1 v2) Tint.\nProof.\n  intros. unfold Val.has_type, Val.add. destruct v1, v2; simpl; auto.\nQed.\n\nRemark type_sub:\n  forall v1 v2, Val.has_type (Val.sub v1 v2) Tint.\nProof.\n  intros. unfold Val.has_type, Val.add. destruct v1, v2; simpl; auto.\nQed.\n\nRemark type_addl:\n  forall v1 v2, Val.has_type (Val.addl v1 v2) Tlong.\nProof.\n  intros. unfold Val.has_type, Val.addl. destruct v1, v2; simpl; auto.\nQed.\n\nRemark type_subl:\n  forall v1 v2, Val.has_type (Val.subl v1 v2) Tlong.\nProof.\n  intros. unfold Val.has_type, Val.addl. destruct v1, v2; simpl; auto.\n  destruct (eq_block b b0); auto.\nQed.\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; auto using Val.Vptr_has_type).\n  intros.\n  destruct op; simpl; simpl in H0; FuncInv; subst; simpl.\n  (* move *)\n  - congruence.\n  (* intconst, longconst, floatconst, singleconst *)\n  - exact I.\n  - exact I.\n  - exact I.\n  - exact I.\n  (* addrsymbol *)\n  - unfold Genv.symbol_address. destruct (Genv.find_symbol genv id)...\n  (* addrstack *)\n  - destruct sp...\n  (* 32-bit integer operations *)\n  - destruct s, v0; try exact I; simpl; rewrite a32_range...\n  - apply type_add.\n  - apply type_add.\n  - apply type_add.\n  - destruct v0...\n  - destruct (eval_shift s v0 a)...\n  - apply type_sub.\n  - apply type_sub.\n  - destruct v0... destruct v1...\n  - apply type_add.\n  - apply type_sub.\n  - destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int.eq i0 Int.zero || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2...\n  - destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int.eq i0 Int.zero); inv H2...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\n  - destruct v0...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\n  - destruct v0...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\n  - destruct v0...\n  - destruct v0...\n  - destruct (eval_shift s v0 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shift s v1 a)...\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; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  - destruct v0; simpl in H0; try discriminate. destruct (Int.ltu n (Int.repr 31)); inv H0...\n  - destruct v0...\n  - destruct v0...\n  - destruct (Val.zero_ext s v0)... simpl; rewrite a32_range... \n  - destruct (Val.sign_ext s v0)... simpl; rewrite a32_range...\n  - destruct (Val.shru v0 (Vint a))... \n  - destruct (Val.shr v0 (Vint a))...\n  (* 64-bit integer operations *)\n  - destruct s, v0; try exact I; simpl; rewrite a64_range...\n  - unfold eval_extend. destruct (match x with\n     | Xsgn32 => Val.longofint v0\n     | Xuns32 => Val.longofintu v0\n     end)...\n    simpl; rewrite a64_range...\n  - destruct v0... destruct v1...\n  - destruct v0...\n  - destruct v0...\n  - apply type_addl.\n  - apply type_addl.\n  - apply type_addl.\n  - apply type_addl.\n  - destruct v0...\n  - destruct (eval_shiftl s v0 a)...\n  - apply type_subl.\n  - apply type_subl.\n  - apply type_subl.\n  - destruct v0... destruct v1...\n  - apply type_addl.\n  - apply type_subl.\n  - destruct v0... destruct v1...\n  - destruct v0... destruct v1...\n  - destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int64.eq i0 Int64.zero || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq i0 Int64.mone); inv H2...\n  - destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int64.eq i0 Int64.zero); inv H2...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0...\n  - destruct v0...\n  - destruct (eval_shiftl s v0 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0... destruct v1...\n  - destruct v0... destruct (eval_shiftl s v1 a)...\n  - destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  - destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  - destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  - destruct v0; simpl in H0; try discriminate. destruct (Int.ltu n (Int.repr 63)); inv H0...\n  - destruct v0...\n  - destruct v0...\n  - destruct (Val.zero_ext_l s v0)... simpl; rewrite a64_range... \n  - destruct (Val.sign_ext_l s v0)... simpl; rewrite a64_range...\n  - destruct (Val.shrlu v0 (Vint a))... \n  - destruct (Val.shrl v0 (Vint a))...\n\n  (* 64-bit FP *)\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  (* 32-bit FP *)\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  (* singleoffloat, floatofsingle *)\n  - destruct v0...\n  - destruct v0...\n  (* intoffloat, intuoffloat *)\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  (* floatofint, floatofintu *)\n  - destruct v0; simpl in H0; inv H0...\n  - destruct v0; simpl in H0; inv H0...\n  (* intofsingle, intuofsingle *)\n  - destruct v0; simpl in H0; inv H0. destruct (Float32.to_int f); inv H2...\n  - destruct v0; simpl in H0; inv H0. destruct (Float32.to_intu f); inv H2...\n  (* singleofint, singleofintu *)\n  - destruct v0; simpl in H0; inv H0...\n  - destruct v0; simpl in H0; inv H0...\n  (* longoffloat, longuoffloat *)\n  - destruct v0; simpl in H0; inv H0. destruct (Float.to_long f); inv H2...\n  - destruct v0; simpl in H0; inv H0. destruct (Float.to_longu f); inv H2...\n  (* floatoflong, floatoflongu *)\n  - destruct v0; simpl in H0; inv H0...\n  - destruct v0; simpl in H0; inv H0...\n  (* longofsingle, longuofsingle *)\n  - destruct v0; simpl in H0; inv H0. destruct (Float32.to_long f); inv H2...\n  - destruct v0; simpl in H0; inv H0. destruct (Float32.to_longu f); inv H2...\n  (* singleoflong, singleoflongu *)\n  - destruct v0; simpl in H0; inv H0...\n  - destruct v0; simpl in H0; inv H0...\n  (* cmp *)\n  - destruct (eval_condition cond vl m) as [[]|]...\n  - unfold Val.select. destruct (eval_condition cond vl m). apply Val.normalize_type. exact I.\nQed.\n\nEnd SOUNDNESS.\n\n(** * Manipulating and transforming operations *)\n\n(** Constructing shift amounts *)\n\nSection SHIFT_AMOUNT.\n\nVariable l: Z.\nHypothesis l_range: 0 <= l < 32.\nVariable N: int.\nHypothesis N_eq: Int.unsigned N = two_p l.\n\nRemark mk_amount_range:\n  forall n, Int.ltu (Int.zero_ext l n) N = true.\nProof.\n  intros; unfold Int.ltu. apply zlt_true. rewrite N_eq. apply (Int.zero_ext_range l n). assumption.\nQed.\n\nRemark mk_amount_eq:\n  forall n, Int.ltu n N = true -> Int.zero_ext l n = n.\nProof.\n  intros.\n  transitivity (Int.repr (Int.unsigned (Int.zero_ext l n))).\n  symmetry; apply Int.repr_unsigned.\n  transitivity (Int.repr (Int.unsigned n)).\n  f_equal. rewrite Int.zero_ext_mod. apply Int.ltu_inv in H. rewrite N_eq in H. \n  apply Z.mod_small. assumption. assumption.\n  apply Int.repr_unsigned.\nQed.\n\nEnd SHIFT_AMOUNT.\n\nProgram Definition mk_amount32 (n: int): amount32 :=\n  {| a32_amount := Int.zero_ext 5 n |}.\nNext Obligation.\n  apply mk_amount_range. lia. reflexivity.\nQed.\n\nLemma mk_amount32_eq: forall n,\n  Int.ltu n Int.iwordsize = true -> a32_amount (mk_amount32 n) = n.\nProof.\n  intros. eapply mk_amount_eq; eauto. lia. reflexivity.\nQed.\n\nProgram Definition mk_amount64 (n: int): amount64 :=\n  {| a64_amount := Int.zero_ext 6 n |}.\nNext Obligation.\n  apply mk_amount_range. lia. reflexivity.\nQed.\n\nLemma mk_amount64_eq: forall n,\n  Int.ltu n Int64.iwordsize' = true -> a64_amount (mk_amount64 n) = n.\nProof.\n  intros. eapply mk_amount_eq; eauto. lia. reflexivity.\nQed.\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  | Ccompshift c s a => Ccompshift (negate_comparison c) s a\n  | Ccompushift c s a => Ccompushift (negate_comparison c) s a\n  | Cmaskzero n => Cmasknotzero n\n  | Cmasknotzero n => Cmaskzero n\n  | Ccompl c => Ccompl (negate_comparison c)\n  | Ccomplu c => Ccomplu (negate_comparison c)\n  | Ccomplimm c n => Ccomplimm (negate_comparison c) n\n  | Ccompluimm c n => Ccompluimm (negate_comparison c) n\n  | Ccomplshift c s a => Ccomplshift (negate_comparison c) s a\n  | Ccomplushift c s a => Ccomplushift (negate_comparison c) s a\n  | Cmasklzero n => Cmasklnotzero n\n  | Cmasklnotzero n => Cmasklzero n\n  | Ccompf c => Cnotcompf c\n  | Cnotcompf c => Ccompf c\n  | Ccompfzero c => Cnotcompfzero c\n  | Cnotcompfzero c => Ccompfzero c\n  | Ccompfs c => Cnotcompfs c\n  | Cnotcompfs c => Ccompfs c\n  | Ccompfszero c => Cnotcompfszero c\n  | Cnotcompfszero c => Ccompfszero c\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). 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 Ceq).\n  repeat (destruct vl; auto). apply (Val.negate_cmp_bool Cne).\n  repeat (destruct vl; auto). apply Val.negate_cmpl_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmplu_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpl_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmplu_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpl_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmplu_bool.\n  repeat (destruct vl; auto). apply (Val.negate_cmpl_bool Ceq).\n  repeat (destruct vl; auto). apply (Val.negate_cmpl_bool Cne).\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.cmpf_bool c v v0) as [[]|]; auto.\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.cmpf_bool c v (Vfloat Float.zero)) as [[]|]; auto.\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.cmpfs_bool c v v0) as [[]|]; auto.\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.cmpfs_bool c v (Vsingle Float32.zero)) 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 ofs (Ptrofs.repr delta))\n  | _ => addr\n  end.\n\nDefinition shift_stack_operation (delta: Z) (op: operation) :=\n  match op with\n  | Oaddrstack ofs => Oaddrstack (Ptrofs.add ofs (Ptrofs.repr delta))\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. destruct vl; auto.\n  rewrite Ptrofs.add_zero_l, Ptrofs.add_commut; 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. destruct vl; auto.\n  rewrite Ptrofs.add_zero_l, Ptrofs.add_commut; 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 (Int64.add n (Int64.repr delta)))\n  | Aindexed2 => None\n  | Aindexed2shift _ => None\n  | Aindexed2ext _ _ => None\n  | Aglobal id n => Some(Aglobal id (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  Archi.ptr64 = false ->\n  eval_addressing ge sp addr' args = Some(Val.add v (Vint (Int.repr delta))).\nProof.\n  intros. discriminate. \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 n => Int.eq (Int.sign_ext 16 n) n\n  | Olongconst n => Int64.eq (Int64.sign_ext 16 n) n\n  | Oaddrstack _ => true\n  | _ => false\n  end.\n\n(** Operations that depend on the memory state. *)\n\nDefinition cond_depends_on_memory (c: condition) : bool :=\n  match c with\n  | Ccomplu _ | Ccompluimm _ _ | Ccomplushift _ _ _ => true\n  | _ => false\n  end.\n\nLemma cond_depends_on_memory_correct:\n  forall c args m1 m2,\n  cond_depends_on_memory c = false ->\n  eval_condition c args m1 = eval_condition c args m2.\nProof.\n  intros; destruct c; simpl; discriminate || reflexivity.\nQed.\n\nDefinition op_depends_on_memory (op: operation) : bool :=\n  match op with\n  | Ocmp c => cond_depends_on_memory c\n  | Osel c yu => cond_depends_on_memory c\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. destruct op; auto.\n  simpl. rewrite (cond_depends_on_memory_correct cond args m1 m2 H). auto.\n  simpl. destruct args; auto. destruct args; auto.\n  rewrite (cond_depends_on_memory_correct cond args m1 m2 H). auto.\nQed.\n\n(** Global variables mentioned in an operation or addressing mode *)\n\nDefinition globals_addressing (addr: addressing) : list ident :=\n  match addr with\n  | Aglobal s ofs => s :: nil\n  | _ => nil\n  end.\n\nDefinition globals_operation (op: operation) : list ident :=\n  match op with\n  | Oaddrsymbol s ofs => 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\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.\n  unfold eval_addressing; destruct addr; auto. destruct vl; auto. \n  unfold Genv.symbol_address. 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.\n  unfold eval_operation; destruct op; auto. destruct vl; auto.\n  unfold Genv.symbol_address. rewrite agree_on_symbols; auto.\nQed.\n\nEnd GENV_TRANSF.\n\n(** Compatibility of the evaluation functions with value injections. *)\n\nSection EVAL_COMPAT.\n\nVariable 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 _ (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_shift_inject:\n  forall v1 v2 s a,\n  Val.inject f v1 v2 -> Val.inject f (eval_shift s v1 a) (eval_shift s v2 a).\nProof.\n  intros; inv H; destruct s; simpl; auto; rewrite a32_range; auto.\nQed.\n\nLemma eval_shiftl_inject:\n  forall v1 v2 s a,\n  Val.inject f v1 v2 -> Val.inject f (eval_shiftl s v1 a) (eval_shiftl s v2 a).\nProof.\n  intros; inv H; destruct s; simpl; auto; rewrite a64_range; auto.\nQed.\n\nLemma eval_extend_inject:\n  forall v1 v2 x a,\n  Val.inject f v1 v2 -> Val.inject f (eval_extend x v1 a) (eval_extend x v2 a).\nProof.\n  unfold eval_extend; intros; inv H; destruct x; simpl; auto; rewrite a64_range; auto.\nQed.\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(* 32-bit integers *)\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- revert H0. generalize (eval_shift_inject s a H2); intros J; inv H3; inv J; simpl; congruence.\n- eauto 3 using Val.cmpu_bool_inject, Mem.valid_pointer_implies, eval_shift_inject.\n- inv H3; inv H0; auto.\n- inv H3; inv H0; auto.\n(* 64-bit integers *)\n- inv H3; inv H2; simpl in H0; inv H0; auto.\n- eauto 3 using Val.cmplu_bool_inject, Mem.valid_pointer_implies.\n- inv H3; simpl in H0; inv H0; auto.\n- eauto 3 using Val.cmplu_bool_inject, Mem.valid_pointer_implies.\n- revert H0. generalize (eval_shiftl_inject s a H2); intros J; inv H3; inv J; simpl; congruence.\n- eauto 3 using Val.cmplu_bool_inject, Mem.valid_pointer_implies, eval_shiftl_inject.\n- inv H3; inv H0; auto.\n- inv H3; inv H0; auto.\n(* 64-bit floats *)\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; simpl in H0; inv H0; auto.\n- inv H3; simpl in H0; inv H0; auto.\n(* 32-bit floats *)\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; simpl in H0; inv H0; auto.\n- inv H3; simpl in H0; inv H0; auto.\nQed.\n\nLtac TrivialExists :=\n  match goal with\n  | [ |- exists v2, Some ?v1 = Some v2 /\\ Val.inject _ _ v2 ] =>\n      exists v1; split; auto\n  | _ => idtac\n  end.\n\nLemma eval_operation_inj:\n  forall op sp1 vl1 sp2 vl2 v1,\n  (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  (* addrsymbol *)\n  - apply GL; simpl; auto.\n  (* addrstack *)\n  - apply Val.offset_ptr_inject; auto. \n  (* shift *)\n  - apply eval_shift_inject; auto.\n  (* add *)\n  - apply Val.add_inject; auto.\n  - apply Val.add_inject; auto using eval_shift_inject.\n  - apply Val.add_inject; auto.\n  (* neg, sub *)\n  - inv H4; simpl; auto.\n  - generalize (eval_shift_inject s a H4); intros J; inv J; simpl; auto.\n  - apply Val.sub_inject; auto.\n  - apply Val.sub_inject; auto using eval_shift_inject.\n  (* mul, muladd, mulsub *)\n  - inv H4; inv H2; simpl; auto.\n  - apply Val.add_inject; auto. inv H2; inv H3; simpl; auto.\n  - apply Val.sub_inject; auto. inv H2; inv H3; simpl; auto.\n  (* div, divu *)\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.\n    TrivialExists.\n  - inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int.eq i0 Int.zero); inv H2. TrivialExists.\n  (* and*)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* or *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* xor *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* not *)\n  - inv H4; simpl; auto.\n  - generalize (eval_shift_inject s a H4); intros J; inv J; simpl; auto.\n  (* bic *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* nor *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* eqv *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shift_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* shl *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  (* shr *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  (* shru *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  (* shrx *)\n  - inv H4; simpl in H1; try discriminate. simpl.\n    destruct (Int.ltu n (Int.repr 31)); inv H1. TrivialExists.\n  (* shift-ext *)\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto; rewrite a32_range; auto.\n  - inv H4; simpl; auto; rewrite a32_range; auto.\n  - inv H4; simpl; auto; rewrite a32_range; simpl; auto.\n  - inv H4; simpl; auto; rewrite a32_range; simpl; auto.\n\n  (* shiftl *)\n  - apply eval_shiftl_inject; auto.\n  (* extend *)\n  - apply eval_extend_inject; auto.\n  (* makelong, low, high *)\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  (* addl *)\n  - apply Val.addl_inject; auto.\n  - apply Val.addl_inject; auto using eval_shiftl_inject.\n  - apply Val.addl_inject; auto using eval_extend_inject.\n  - apply Val.addl_inject; auto.\n  (* negl, subl *)\n  - inv H4; simpl; auto.\n  - generalize (eval_shiftl_inject s a H4); intros J; inv J; simpl; auto.\n  - apply Val.subl_inject; auto.\n  - apply Val.subl_inject; auto using eval_shiftl_inject.\n  - apply Val.subl_inject; auto using eval_extend_inject.\n  (* mull, mulladd, mullsub, mullhs, mullhu *)\n  - inv H4; inv H2; simpl; auto.\n  - apply Val.addl_inject; auto. inv H2; inv H3; simpl; auto.\n  - apply Val.subl_inject; auto. inv H2; inv H3; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  (* divl, divlu *)\n  - inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int64.eq i0 Int64.zero\n              || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq i0 Int64.mone); inv H2.\n    TrivialExists.\n  - inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int64.eq i0 Int64.zero); inv H2. TrivialExists.\n  (* andl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* orl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* xorl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  - inv H4; simpl; auto.\n  (* notl *)\n  - inv H4; simpl; auto.\n  - generalize (eval_shiftl_inject s a H4); intros J; inv J; simpl; auto.\n  (* bicl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* norl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* eqvl *)\n  - inv H4; inv H2; simpl; auto. \n  - generalize (eval_shiftl_inject s a H2); intros J; inv H4; inv J; simpl; auto.\n  (* shll *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  (* shrl *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  (* shrlu *)\n  - inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  (* shrlx *)\n  - inv H4; simpl in H1; try discriminate. simpl.\n    destruct (Int.ltu n (Int.repr 63)); inv H1. TrivialExists.\n  (* shift-ext *)\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto; rewrite a64_range; auto.\n  - inv H4; simpl; auto; rewrite a64_range; auto.\n  - inv H4; simpl; auto; rewrite a64_range; simpl; auto.\n  - inv H4; simpl; auto; rewrite a64_range; simpl; auto.\n\n  (* negf, absf *)\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  (* addf, subf *)\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  (* mulf, divf *)\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  (* negfs, absfs *)\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  (* addfs, subfs *)\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  (* mulfs, divfs *)\n  - inv H4; inv H2; simpl; auto.\n  - inv H4; inv H2; simpl; auto.\n  (* singleoffloat, floatofsingle *)\n  - inv H4; simpl; auto.\n  - inv H4; simpl; auto.\n  (* intoffloat, intuoffloat *)\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  (* floatofint, floatofintu *)\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  (* intofsingle, intuofsingle *)\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float32.to_int f0); simpl in H2; inv H2.\n    exists (Vint i); auto.\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float32.to_intu f0); simpl in H2; inv H2.\n    exists (Vint i); auto.\n  (* singleofint, singleofintu *)\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  (* longoffloat, longuoffloat *)\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_long f0); simpl in H2; inv H2.\n    exists (Vlong i); auto.\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_longu f0); simpl in H2; inv H2.\n    exists (Vlong i); auto.\n  (* floatoflong, floatoflongu *)\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  (* longofsingle, longuofsingle *)\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float32.to_long f0); simpl in H2; inv H2.\n    exists (Vlong i); auto.\n  - inv H4; simpl in H1; inv H1. simpl. destruct (Float32.to_longu f0); simpl in H2; inv H2.\n    exists (Vlong i); auto.\n  (* singleoflong, singleoflongu *)\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  - inv H4; simpl in H1; inv H1. simpl. TrivialExists.\n  (* cmp, sel *)\n  - subst v1. destruct (eval_condition cond vl1 m1) eqn:?.\n    exploit eval_condition_inj; eauto. intros EQ; rewrite EQ.\n    destruct b; simpl; constructor.\n    simpl; constructor.\n  - apply Val.select_inject; auto.  \n    destruct (eval_condition cond vl1 m1) eqn:?; auto.\n    right; symmetry; eapply eval_condition_inj; eauto.\nQed.\n\nLemma eval_addressing_inj:\n  forall addr sp1 vl1 sp2 vl2 v1,\n  (forall id ofs,\n      In id (globals_addressing addr) ->\n      Val.inject f (Genv.symbol_address ge1 id ofs) (Genv.symbol_address ge2 id ofs)) ->\n  Val.inject f sp1 sp2 ->\n  Val.inject_list f vl1 vl2 ->\n  eval_addressing ge1 sp1 addr vl1 = Some v1 ->\n  exists v2, eval_addressing ge2 sp2 addr vl2 = Some v2 /\\ Val.inject f v1 v2.\nProof.\n  intros. destruct addr; simpl in H2; simpl; FuncInv; InvInject; TrivialExists.\n- apply Val.addl_inject; auto.\n- apply Val.addl_inject; auto.\n- apply Val.addl_inject; auto. inv H3; simpl; auto; rewrite a64_range; auto.\n- apply Val.addl_inject; auto using eval_extend_inject.\n- apply H; simpl; auto.\n- apply Val.offset_ptr_inject; auto. \nQed.\n\nEnd EVAL_COMPAT.\n\n(** Compatibility of the evaluation functions with the ``is less defined'' relation over values. *)\n\nSection EVAL_LESSDEF.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\n\nRemark valid_pointer_extends:\n  forall m1 m2, Mem.extends m1 m2 ->\n  forall b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.valid_pointer_extends; eauto.\nQed.\n\nRemark weak_valid_pointer_extends:\n  forall m1 m2, Mem.extends m1 m2 ->\n  forall b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.weak_valid_pointer_extends; eauto.\nQed.\n\nRemark weak_valid_pointer_no_overflow_extends:\n  forall m1 b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.\nProof.\n  intros. inv H. rewrite Z.add_0_r. apply Ptrofs.unsigned_range_2.\nQed.\n\nRemark valid_different_pointers_extends:\n  forall m1 b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  b1 <> b2 ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->\n  Mem.valid_pointer m1 b2 (Ptrofs.unsigned ofs2) = true ->\n  Some(b1, 0) = Some (b1', delta1) ->\n  Some(b2, 0) = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Ptrofs.unsigned(Ptrofs.add ofs1 (Ptrofs.repr delta1)) <> Ptrofs.unsigned(Ptrofs.add ofs2 (Ptrofs.repr delta2)).\nProof.\n  intros. inv H2; inv H3. auto.\nQed.\n\nLemma eval_condition_lessdef:\n  forall cond vl1 vl2 b m1 m2,\n  Val.lessdef_list vl1 vl2 ->\n  Mem.extends m1 m2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. eapply eval_condition_inj with (f := fun b => Some(b, 0)) (m1 := m1).\n  apply valid_pointer_extends; auto.\n  apply weak_valid_pointer_extends; auto.\n  apply weak_valid_pointer_no_overflow_extends.\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.\n  apply valid_different_pointers_extends; auto.\n  intros. apply val_inject_lessdef. auto.\n  apply val_inject_lessdef; auto.\n  eauto.\n  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(** * Handling of builtin arguments *)\n\nDefinition builtin_arg_ok_1\n       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=\n  match c, ba with\n  | OK_all, _ => true\n  | OK_const, (BA_int _ | BA_long _ | BA_float _ | BA_single _) => true\n  | OK_addrstack, BA_addrstack _ => true\n  | OK_addressing, BA_addrstack _ => true\n  | OK_addressing, BA_addptr (BA _) (BA_int _) => true\n  | OK_addressing, BA_addptr (BA _) (BA_long _) => true\n  | _, _ => false\n  end.\n\nDefinition builtin_arg_ok\n       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=\n  match ba with\n  | (BA _ | BA_splitlong (BA _) (BA _)) => true\n  | _ => builtin_arg_ok_1 ba c\n  end.  \n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/aarch64/Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19369123696199275}}
{"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.spectac x86proved.spec x86proved.safe x86proved.pointsto x86proved.cursor x86proved.x86.instr.\nRequire Import x86proved.x86.basic x86proved.x86.basicprog x86proved.x86.program x86proved.x86.instrsyntax x86proved.x86.macros x86proved.x86.instrrules.\nRequire Import Coq.Setoids.Setoid Coq.Classes.RelationClasses Coq.Classes.Morphisms.\nRequire Import x86proved.common_tactics x86proved.basicspectac x86proved.chargetac x86proved.latertac.\n\nDefinition retreg := EBP.\n\n(* Toy function calling convention *)\nDefinition toyfun f P Q :=\n  Forall iret,\n  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. by cancel1.\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  rewrite /call_toyfun.\n  basic apply * => iret.\n  rewrite /stateIsAny. specintros => *.\n\n  (* MOV retreg, iret *)\n  basic apply *.  \n\n  rewrite /basic. specintros => i j. unfold_program. specintros => *; do !subst.  \n\n  (* JMP f *)\n  superspecapply *. simpllater. apply lforallL with iret. rewrite /stateIsAny. \n  rewrite ->empSPR.\n  rewrite <-(spec_frame (i -- iret :-> JMP f)). (*reads_frame. *)\n  cancel2. cancel1. ssimpl. autorewrite with push_at. cancel1.  \nQed. \n\nGlobal Opaque call_toyfun.\nGlobal Instance: forall f : DWORD, instrrule (call_toyfun f) := @toyfun_call.\n\nLemma toyfun_mkbody (f f': DWORD) P p Q:\n  (Forall iret, basic P p Q @ (retreg ~= iret))\n    |-- toyfun f P Q c@ (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  apply limplAdj.\n  eapply safe_safe_context; first reflexivity.\n  apply landL1. rewrite /basic.\n  apply lforallL with f. apply lforallL with i1.\n  reflexivity.\n  ssimpl.\n  apply landL2.\n  \n  superspecapply *. simpllater.\n  finish_logic_with sbazooka.\nQed. \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_helper (f f': DWORD):\n  |-- ((Forall a, toyfun f (EAX ~= a) (EAX ~= a +# 2))\n      @ OSZCP?) c@ (f--f' :-> toyfun_example_callee).\nProof.\n  specintro => a. rewrite spec_at_toyfun. rewrite /toyfun_example_callee.\n  etransitivity; [|apply toyfun_mkbody]. specintro => iret.\n  rewrite {1 2 3 4 5}/stateIsAny. specintros => o s z c p. \n  basic apply *. \n  basic apply *. \n  by rewrite addIsIterInc /iter.\nQed.\n\nDefinition toyfun_example_callee_correct (f f': DWORD):\n  |-- (Forall a, toyfun f (EAX ~= a) (EAX ~= a +# 2))\n      @ OSZCP? c@ (f--f' :-> toyfun_example_callee)\n  := @toyfun_example_callee_correct_helper f f'.\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 [Opaque]. *)\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  (** FIXME: make [basic apply *] not take forever *)\n  { apply lforallL with a. simple basic apply *; ssimpl. }\n  { apply lforallL with (a +# 2). rewrite -addB_addn. simple basic apply *; ssimpl. 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?) c@ (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_at_at.\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. rewrite /basic.\n  (*rewrite <-spec_reads_merge. rewrite spec_reads_swap. *)\n  cancel2; last ssimpl. autorewrite with push_at.\n\n  - eapply lforallL. autorewrite with push_at. eapply lforallL. autorewrite with push_at.\n    cancel2; cancel1; ssimpl. \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\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    ) c@ (f--f' :-> toyfun_apply).\nProof.\n  rewrite /toyfun_apply. rewrite {2}/toyfun.\n  specintro => iret.\n  superspecapply *.\n  simpllater.\n  rewrite /toyfun.  rewrite <- spec_frame. (*rewrite <- spec_reads_frame. *) apply limplValid. \n  eapply lforallL. autorewrite with push_at.\n  cancel1. finish_logic_with sbazooka. \nQed.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.19358781864024524}}
{"text": "Require Export MinBFTass_knew0.\n\n\nSection MinBFTass_knew1.\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 on_request_implies_generates :\n    forall {eo : EventOrdering} (e : Event) r v m s1 u1 l1 s2 u2 l2,\n      loc e = MinBFT_replica r\n      -> usig_counter u2 = S (usig_counter u1)\n      -> r = usig_id u1\n      -> v = current_view s1\n      -> trigger_op e = Some (MinBFT_request m)\n      (*-> trigger_op e = Some msg\n      -> msg2request msg = Some m*)\n      -> M_run_ls_before_event (MinBFTlocalSys r) e = Some (MinBFTlocalSys_new r s1 u1 l1)\n      -> M_run_ls_on_event (MinBFTlocalSys r) e = Some (MinBFTlocalSys_new r s2 u2 l2)\n      -> disseminate_data\n           e\n           (minbft_data_rdata\n              (request_data\n                 v\n                 m\n                 (Build_UI\n                    (MkPreUI (usig_id u1) (S (usig_counter u1)))\n                    (create_hash_usig\n                       (Build_HashData\n                          v\n                          m\n                          (MkPreUI (usig_id u1) (S (usig_counter u1))))\n                       (usig_local_keys u1))))).\n  Proof.\n    introv eqloc eqc eqr eqv eqtrig runBef runOn.\n\n    unfold disseminate_data; simpl.\n    applydup @M_run_ls_on_event_M_byz_run_ls_on_event in runOn as byzRunOn.\n    applydup @M_run_ls_before_event_M_byz_run_ls_before_event in runBef as byzRunBef.\n    unfold M_byz_output_sys_on_event; simpl.\n    rewrite M_byz_output_ls_on_event_as_run; simpl.\n    unfold M_byz_output_ls_on_this_one_event.\n    apply (trigger_op_Some_implies_trigger_message e (MinBFT_request m)) in eqtrig.\n    allrw; simpl.\n\n    rewrite <- eqr.\n    rewrite byzRunBef; simpl.\n\n    clear byzRunOn byzRunBef.\n\n    rewrite M_run_ls_on_event_unroll2 in runOn.\n    rewrite runBef in runOn; simpl in *.\n    apply map_option_Some in runOn; exrepnd; rev_Some; minbft_simp.\n    unfold trigger_op in *.\n    rewrite eqtrig in *; simpl in *; ginv.\n\n    clear runBef.\n\n    unfold M_byz_run_ls_on_one_event; simpl; allrw.\n    unfold data_is_in_out, event2out; simpl; rewrite eqtrig; simpl.\n    unfold M_run_ls_on_input_ls in *; simpl in *.\n\n    remember (M_run_ls_on_input\n                (MinBFTlocalSys_new (usig_id u1) s1 u1 l1)\n                (msg_comp_name 0) (MinBFT_request m)) as run.\n    symmetry in Heqrun; repnd; simpl in *.\n    unfold M_run_ls_on_input in *; simpl in *.\n    autorewrite with minbft in *; simpl in *.\n\n    post_minbft_dest_msg;\n      repeat (simpl in *; autorewrite with minbft in *; smash_minbft2; try omega);\n      unfold lower_out_break in *; simpl in *; minbft_simp; try omega;\n        eexists; dands; eauto; simpl; tcsp.\n  Qed.\n  Hint Resolve on_request_implies_generates : minbft.\n\nEnd MinBFTass_knew1.\n\n\nHint Resolve on_request_implies_generates : 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_knew1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "(** USeq.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.MetaLanguage Require Import Notations\n                                        MetaType\n                                        MetaLan.\n\nFrom Coq Require Import Relations Classical.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(** Do not import this module. *)\nModule USeq.\n\n\n(** Syntax *)\n\nRecord syn (syn0 syn1 : Type) := seq_ {\n    S0 : syn0;\n    S1 : syn1;\n}.\n\nNotation \"s0 \u2a3e s1\" := {| S0 := s0; S1 := s1 |} : MetaLan_scope.\n\n\n(** DeSem \n    For now let's consider backward semantics.\n*)\n\nDefinition de_fun (mT : Type) (de0 de1 : deSem mT): syn de0 de1 -> mT -> mT := \n    fun s P => \u27e6 S0 s \u27e7 <de0> (\u27e6 S1 s \u27e7 <de1> P).\n\nDefinition deSem_mixin (mT : Type) (de0 de1 : deSem mT) : \n    DeSem.mixin_of mT (syn de0 de1) :=\n{|\n\tDeSem.de_fun := @de_fun mT de0 de1;\n|}.\n\nCanonical deSem (mT : Type) (de0 de1 : deSem mT) := \n    DeSem (syn de0 de1) (deSem_mixin de0 de1).\n\n\n(** monotonicity *)\n\nLemma de_fun_monot_mixin (mT : poset) (de0 de1 : deSemM mT): \n        DeSemM.mixin_of (deSem_mixin de0 de1).\nProof.\n    constructor. \n    porder_level.\n    rewrite /de_fun.\n    apply DeSemM.de_monot.\n    by apply DeSemM.de_monot. \nQed.\n\nCanonical de_fun_monot (mT : poset) (de0 de1 : deSemM mT) : deSemM mT :=\n    DeSemM (syn de0 de1) (de_fun_monot_mixin de0 de1).\n\n\nLemma de_fun_conti_mixin (mT : cpo) (de0 de1 : deSemC mT) :\n        DeSemC.mixin_of (DeSemM.class (de_fun_monot de0 de1)).\nProof.\n    constructor.\n    rewrite /ContinuousFun.mixin_of => s c //=.\n    rewrite /de_fun //=.\n    have t1 := (DeSemC.de_conti (S1 s)).\n        rewrite /ContinuousFun.mixin_of in t1. simpl in t1. rewrite {}t1.\n    have t0 := (DeSemC.de_conti (S0 s)).\n        rewrite /ContinuousFun.mixin_of in t0. simpl in t0. rewrite {}t0.\n    porder_level.\nQed.\n\nCanonical de_fun_conti (mT : cpo) (de0 de1 : deSemC mT) \n        : deSemC mT :=\n    DeSemC (syn de0 de1) (de_fun_conti_mixin de0 de1).\n\n\n\n\n\n(** AxSem *)\n\nInductive ax_sys (mT : dMT) (ax0 ax1 : axSem mT) : \n    mT -> syn ax0 ax1 -> mT -> Prop :=\n\n| RULE_SEQ \n        (s0 : ax0) (s1 : ax1) (P R Q : mT) \n        (H0 : \u22a2 { P } s0 { R }) \n        (H1 : \u22a2 { R } s1 { Q }): ax_sys P (s0 \u2a3e s1)  Q.\n\nDefinition axSem_mixin (mT : dMT) (ax0 ax1 : axSem mT) : \n        AxSem.mixin_of mT (syn ax0 ax1)\n    := AxSem.Mixin (@ax_sys _ ax0 ax1).\n\nDefinition axSem (mT : dMT) (ax0 ax1 : axSem mT) := \n    AxSem (syn ax0 ax1) (axSem_mixin ax0 ax1).\n\n\n(** VeriModS *)\n\nDefinition veriModS_mixin (mT : cpoDMT) (veriS0 veriS1 : veriModS mT): \n    VeriModS.mixin_of (axSem veriS0 veriS1) \n    (deSem (veriS0 : DeSem.Exports.deSem (mT : cpo)) veriS1).\nProof. \n    constructor. rewrite /VeriModS.axiom => [] [] s0 s1 P Q.\n    move => [] //=. intros. rewrite /de_fun.\n    apply (soundness_of veriS1) in H1 => //=.\n    apply (soundness_of veriS0) in H0 => //=.\n    \n    transitivity ((\u27e6 s2 \u27e7 < DeSem veriS0 (VeriModS.base_de veriS0) >) R).\n    - by [].\n    - by apply (DeSemM.de_monot ).\nQed.\n\nDefinition veriModS (mT : cpoDMT) (veriS0 veriS1 : veriModS mT) := \n    VeriModS (syn veriS0 veriS1) (veriModS_mixin veriS0 veriS1).\n\n    \n(** VeriModC *)\n\n\nDefinition veriModC_mixin (mT : cpoDMT) (veriC0 veriC1 : veriModC mT): \n    VeriModC.mixin_of (axSem veriC0 veriC1) (deSem veriC0 veriC1).\nProof. \n    constructor. rewrite /VeriModC.axiom => [] [] s0 s1 P Q. simpl.\n    rewrite /de_fun => //= H.\n    eapply RULE_SEQ.\n    instantiate (1 := (\u27e6 s1 \u27e7 < VeriModC.base_de veriC1 >) Q).\n\n    by apply (completeness_of _).\n    apply (completeness_of _); by reflexivity.\nQed.\n\nDefinition veriModC (mT : cpoDMT) (veriC0 veriC1 : veriModC mT) := \n    VeriModC (syn veriC0 veriC1) (veriModC_mixin veriC0 veriC1).\n\n(** VeriModSC *)\n\nDefinition veriModSC_mixin (mT : cpoDMT) (veri0 veri1 : veriModSC mT) : \n    VeriModSC.mixin_of (veriModS veri0 veri1) (veriModC veri0 veri1).\nProof. constructor. Qed.\n\nDefinition veriModSC (mT : cpoDMT) (veri0 veri1 : veriModSC mT) := \n    VeriModSC (syn veri0 veri1) (veriModSC_mixin veri0 veri1).\n\nEnd USeq.\n", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/Babel/MetaLanguage/UFeatures/USeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "(*********************************************************************************************************************************)\n(* HaskCoreTypes: basically GHC's TypeRep.Type imported into Coqland                                                             *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import HaskKinds.\nRequire Import HaskCoreVars.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\n\nVariable CoreCoercionCoAxiom : Type.  Extract Inlined Constant CoreCoercionCoAxiom => \"Coercion.CoAxiom\".\nVariable Int : Type.                  Extract Inlined Constant Int => \"Prelude.Int\".\n\nVariable classTyCon          : Class_ -> CoreTyCon.       Extract Inlined Constant classTyCon            => \"Class.classTyCon\".\nVariable coreTyConToString   : CoreTyCon   -> string.     Extract Inlined Constant coreTyConToString     => \"outputableToString\".\nVariable coreDataConToString : CoreDataCon -> string.     Extract Inlined Constant coreDataConToString   => \"outputableToString\".\n\n(* this exracts onto TypeRep.Type, on the nose *)\nInductive CoreType :=\n| TyVarTy  : CoreVar                    -> CoreType\n| AppTy    : CoreType  ->      CoreType -> CoreType   (* first arg must be AppTy or TyVarTy*)\n| TyConApp : CoreTyCon -> list CoreType -> CoreType\n| FunTy    : CoreType  ->      CoreType -> CoreType   (* technically redundant since we have FunTyCon *)\n| ForAllTy : CoreVar   ->      CoreType -> CoreType\n| PredTy   : PredType                   -> CoreType\nwith PredType :=\n| ClassP   : Class_              -> list CoreType -> PredType\n| IParam   : CoreIPName CoreName -> CoreType      -> PredType\n| EqPred   : CoreType            -> CoreType      -> PredType.\nExtract Inductive CoreType =>\n   \"TypeRep.Type\" [ \"TypeRep.TyVarTy\" \"TypeRep.AppTy\" \"TypeRep.TyConApp\" \"TypeRep.FunTy\" \"TypeRep.ForAllTy\" \"TypeRep.PredTy\" ].\nExtract Inductive PredType =>\n   \"TypeRep.PredType\" [ \"TypeRep.ClassP\" \"TypeRep.IParam\" \"TypeRep.EqPred\" ].\n\nInductive CoreCoercion : Type :=\n    CoreCoercionRefl        : CoreType                                 -> CoreCoercion\n  | CoreCoercionTyConAppCo  : CoreTyCon    -> list CoreCoercion        -> CoreCoercion\n  | CoreCoercionAppCo       : CoreCoercion -> CoreCoercion             -> CoreCoercion\n  | CoreCoercionForAllCo    : CoreVar      -> CoreCoercion             -> CoreCoercion\n  | CoreCoercionCoVarCo     : CoreVar                                  -> CoreCoercion\n  | CoreCoercionAxiomInstCo : CoreCoercionCoAxiom -> list CoreCoercion -> CoreCoercion\n  | CoreCoercionUnsafeCo    : CoreType -> CoreType                     -> CoreCoercion\n  | CoreCoercionSymCo       : CoreCoercion                             -> CoreCoercion\n  | CoreCoercionTransCo     : CoreCoercion -> CoreCoercion             -> CoreCoercion\n  | CoreCoercionNthCo       : Int -> CoreCoercion                      -> CoreCoercion\n  | CoreCoercionInstCo      : CoreCoercion -> CoreType                 -> CoreCoercion.\n\nExtract Inductive CoreCoercion =>\n  \"Coercion.Coercion\" [\n  \"Coercion.Refl\"\n  \"Coercion.TyConAppCo\"\n  \"Coercion.AppCo\"\n  \"Coercion.ForAllCo\"\n  \"Coercion.CoVarCo\"\n  \"Coercion.AxiomInstCo\"\n  \"Coercion.UnsafeCo\"\n  \"Coercion.SymCo\"\n  \"Coercion.TransCo\"\n  \"Coercion.NthCo\"\n  \"Coercion.InstCo\" ].\n\nVariable coreNameToString      : CoreName     -> string.    Extract Inlined Constant coreNameToString       => \"outputableToString\".\nVariable coreCoercionToString  : CoreCoercion -> string.    Extract Inlined Constant coreCoercionToString   => \"outputableToString\".\nVariable coreCoercionKind : Kind -> CoreType*CoreType.\n  Extract Inlined Constant coreCoercionKind => \"(Coercion.coercionKind . kindToCoreKind)\".\nVariable kindOfCoreType   : CoreType -> Kind.   Extract Inlined Constant kindOfCoreType   => \"(coreKindToKind . Kind.typeKind)\".\nVariable coreTypeToString : CoreType -> string. Extract Inlined Constant coreTypeToString => \"(outputableToString . coreViewDeep)\".\nVariable setVarType       : CoreVar -> CoreType -> CoreVar. Extract Inlined Constant setVarType       => \"Var.setVarType\".\n\n(* GHC provides decision procedures for equality on its primitive types; we tell Coq to blindly trust them *)\nVariable coreTyCon_eq         : EqDecider CoreTyCon.       Extract Inlined Constant coreTyCon_eq          => \"(==)\".\nVariable tyCon_eq             : EqDecider TyCon.           Extract Inlined Constant tyCon_eq              => \"(==)\".\nVariable tyFun_eq             : EqDecider TyFun.           Extract Inlined Constant tyFun_eq              => \"(==)\".\nVariable dataCon_eq           : EqDecider CoreDataCon.     Extract Inlined Constant dataCon_eq            => \"(==)\".\nVariable coreName_eq          : EqDecider CoreName.        Extract Inlined Constant coreName_eq           => \"(==)\".\nInstance CoreTyConEqDecidable : EqDecidable CoreTyCon   := { eqd_dec := coreTyCon_eq }.\nInstance TyConEqDecidable     : EqDecidable TyCon       := { eqd_dec := tyCon_eq }.\nInstance TyFunEqDecidable     : EqDecidable TyFun       := { eqd_dec := tyFun_eq }.\nInstance DataConEqDecidable   : EqDecidable CoreDataCon := { eqd_dec := dataCon_eq }.\nInstance CoreNameEqDecidable  : EqDecidable CoreName    := { eqd_dec := coreName_eq }.\nInstance CoreTypeToString     : ToString CoreType       := { toString := coreTypeToString }.\nInstance CoreNameToString     : ToString CoreName       := { toString := coreNameToString }.\nInstance CoreCoercionToString : ToString CoreCoercion   := { toString := coreCoercionToString }.\nInstance CoreDataConToString  : ToString CoreDataCon    := { toString := coreDataConToString }.\nInstance CoreTyConToString    : ToString CoreTyCon      := { toString := coreTyConToString }.\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/HaskCoreTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1935878186402452}}
{"text": "Require Import oeuf.Common oeuf.Monads.\nRequire Import oeuf.Metadata.\nRequire String.\nRequire oeuf.FlatReturn oeuf.FlatExpr.\nRequire Import oeuf.ListLemmas.\nRequire Import oeuf.HigherValue.\n\nRequire Import Psatz.\n\nModule A := FlatReturn.\nModule B := FlatExpr.\n\nAdd Printing Constructor A.frame.\nAdd Printing Constructor B.frame.\n\n\nDefinition compile : A.stmt -> B.stmt :=\n    let fix go e :=\n        let fix go_list (es : list A.stmt) : list B.stmt :=\n            match es with\n            | [] => []\n            | e :: es => go e :: go_list es\n            end in\n        match e with\n        | A.Skip => B.Skip\n        | A.Seq s1 s2 => B.Seq (go s1) (go s2)\n        | A.Arg dst => B.Assign dst B.Arg\n        | A.Self dst => B.Assign dst B.Self\n        | A.Deref dst e off => B.Assign dst (B.Deref (B.Var e) off)\n        | A.Call dst f a => B.Call dst (B.Var f) (B.Var a)\n        | A.MkConstr dst tag args => B.MkConstr dst tag (map B.Var args)\n        | A.Switch dst cases => B.Switch dst (go_list cases)\n        | A.MkClose dst fname free => B.MkClose dst fname (map B.Var free)\n        | A.OpaqueOp dst op args => B.OpaqueOp dst op (map B.Var args)\n        | A.Copy dst src => B.Assign dst (B.Var src)\n        end in go.\n\nDefinition compile_list :=\n    let go := compile in\n    let fix go_list es :=\n        match es with\n        | [] => []\n        | e :: es => go e :: go_list es\n        end in go_list.\n\nLtac refold_compile :=\n    fold compile_list in *.\n\nDefinition compile_func (f : A.stmt * nat) : B.stmt * nat :=\n    let '(body, ret) := f in\n    (compile body, ret).\n\nDefinition compile_cu (cu : list (A.stmt * nat) * list metadata) :\n        list (B.stmt * nat) * list metadata :=\n    let '(funcs, metas) := cu in\n    (map compile_func funcs, metas).\n\n\n\nInductive I_stmt : A.stmt -> B.stmt -> Prop :=\n| ISkip :\n        I_stmt A.Skip B.Skip\n| ISeq : forall as1 as2 bs1 bs2,\n        I_stmt as1 bs1 ->\n        I_stmt as2 bs2 ->\n        I_stmt (A.Seq as1 as2) (B.Seq bs1 bs2)\n| IArg : forall dst,\n        I_stmt (A.Arg dst) (B.Assign dst B.Arg)\n| ISelf : forall dst,\n        I_stmt (A.Self dst) (B.Assign dst B.Self)\n| IDeref : forall dst e off,\n        I_stmt (A.Deref dst e off) (B.Assign dst (B.Deref (B.Var e) off))\n| ICall : forall dst f a,\n        I_stmt (A.Call dst f a) (B.Call dst (B.Var f) (B.Var a))\n| IMkConstr : forall dst tag args,\n        I_stmt (A.MkConstr dst tag args) (B.MkConstr dst tag (map B.Var args))\n| ISwitch : forall dst acases bcases,\n        Forall2 I_stmt acases bcases ->\n        I_stmt (A.Switch dst acases) (B.Switch dst bcases)\n| IMkClose : forall dst fname free,\n        I_stmt (A.MkClose dst fname free) (B.MkClose dst fname (map B.Var free))\n| IOpaqueOp : forall dst op args,\n        I_stmt (A.OpaqueOp dst op args) (B.OpaqueOp dst op (map B.Var args))\n| ICopy : forall dst src,\n        I_stmt (A.Copy dst src) (B.Assign dst (B.Var src))\n.\nHint Resolve ISkip.\n\nInductive I_func : (A.stmt * nat) -> (B.stmt * nat) -> Prop :=\n| IFunc : forall ret acode bcode,\n        I_stmt acode bcode ->\n        I_func (acode, ret) (bcode, ret).\n\nInductive I_frame : A.frame -> B.frame -> Prop :=\n| IFrame : forall arg self locals,\n        I_frame (A.Frame arg self locals) (B.Frame arg self locals).\nHint Constructors I_frame.\n\nInductive I_cont : A.cont -> B.cont -> Prop :=\n| IkSeq : forall acode ak bcode bk,\n        I_stmt acode bcode ->\n        I_cont ak bk ->\n        I_cont (A.Kseq acode ak)\n               (B.Kseq bcode bk)\n| IkSwitch : forall ak bk,\n        I_cont ak bk ->\n        I_cont (A.Kswitch ak)\n               (B.Kswitch bk)\n| IkReturn : forall ret ak bk,\n        I_cont ak bk ->\n        I_cont (A.Kreturn ret ak)\n               (B.Kreturn ret bk)\n| IkCall : forall dst af ak bf bk,\n        I_frame af bf ->\n        I_cont ak bk ->\n        I_cont (A.Kcall dst af ak)\n               (B.Kcall dst bf bk)\n| IkStop : forall ret,\n        I_cont (A.Kstop ret)\n               (B.Kstop ret).\n\nInductive I : A.state -> B.state -> Prop :=\n| IRun : forall acode af ak  bcode bf bk,\n        I_stmt acode bcode ->\n        I_frame af bf ->\n        I_cont ak bk ->\n        I (A.Run acode af ak)\n          (B.Run bcode bf bk)\n\n| IReturn : forall v ak bk,\n        I_cont ak bk ->\n        I (A.Return v ak)\n          (B.Return v bk)\n\n| IStop : forall v,\n        I (A.Stop v) (B.Stop v).\n\n\n\nLemma compile_I_stmt : forall a b,\n    compile a = b ->\n    I_stmt a b.\ninduction a using A.stmt_rect_mut with\n    (Pl := fun a => forall b,\n        compile_list a = b ->\n        Forall2 I_stmt a b);\nintros0 Hcomp; simpl in Hcomp; try rewrite <- Hcomp; refold_compile;\ntry solve [econstructor; eauto].\nQed.\n\nLemma compile_list_I_stmt : forall a b,\n    compile_list a = b ->\n    Forall2 I_stmt a b.\ninduction a;\nintros0 Hcomp; simpl in Hcomp; try rewrite <- Hcomp; refold_compile;\ntry solve [econstructor; eauto using compile_I_stmt].\nQed.\n\nLemma compile_I_func : forall a b,\n    compile_func a = b ->\n    I_func a b.\nintros0 Hcomp. destruct a.\nunfold compile_func in Hcomp. rewrite <- Hcomp.\neconstructor. eauto using compile_I_stmt.\nQed.\n\nTheorem compile_cu_I_env : forall a ameta b bmeta,\n    compile_cu (a, ameta) = (b, bmeta) ->\n    Forall2 I_func a b.\nintros0 Hcomp. unfold compile_cu in *. inject_pair.\nremember (map compile_func a) as b.\nsymmetry in Heqb. apply map_Forall2 in Heqb.\nlist_magic_on (a, (b, tt)). eauto using compile_I_func.\nQed.\n\n\n\nLtac i_ctor := intros; econstructor; simpl; eauto.\nLtac i_lem H := intros; eapply H; simpl; eauto.\n\nLtac stk_simpl := compute [\n    A.set  A.arg A.self A.locals\n    B.set  B.arg B.self B.locals\n    ] in *.\n\nLemma set_I_frame : forall af bf dst v,\n    I_frame af bf ->\n    I_frame (A.set af dst v) (B.set bf dst v).\nintros0 II. invc II.\nstk_simpl. constructor.\nQed.\nHint Resolve set_I_frame.\n\nHint Constructors B.eval.\n\nTheorem I_sim : forall AE BE a a' b,\n    Forall2 I_func AE BE ->\n    I a b ->\n    A.sstep AE a a' ->\n    exists b',\n        B.sstep BE b b' /\\\n        I a' b'.\ndestruct a as [ae af ak | val ak | ae];\nintros0 Henv II Astep; [ | | solve [invc Astep] ];\ninv Astep; inv II;\ntry on >I_stmt, invc;\ntry on >I_frame, invc;\nsimpl in *.\n\n- (* Seq *)\n  eexists. split. eapply B.SSeq; eauto.\n  i_ctor. i_ctor.\n\n- (* Arg *)\n  eexists. split. eapply B.SAssign; eauto.\n  i_ctor.\n\n- (* Self *)\n  eexists. split. eapply B.SAssign; eauto.\n  i_ctor.\n\n- (* DerefinateConstr *)\n  eexists. split. eapply B.SAssign; eauto.\n  i_ctor.\n\n- (* DerefinateClose *)\n  eexists. split. eapply B.SAssign; eauto.\n  i_ctor.\n\n- (* MkConstr *)\n  eexists. split. eapply B.SConstrDone; eauto.\n    { instantiate (1 := vs). rewrite <- Forall2_map_l. list_magic_on (args, (vs, tt)). }\n  i_ctor.\n\n- (* MkClose *)\n  eexists. split. eapply B.SCloseDone; eauto.\n    { instantiate (1 := vs). rewrite <- Forall2_map_l. list_magic_on (free, (vs, tt)). }\n  i_ctor.\n\n- (* MkClose *)\n  eexists. split. eapply B.SOpaqueOpDone; eauto.\n    { rewrite <- Forall2_map_l. list_magic_on (args, (vs, tt)). }\n  i_ctor.\n\n- (* MakeCall *)\n  fwd eapply Forall2_nth_error_ex with (xs := AE) as HH; eauto.\n    destruct HH as ([bbody bret] & ? & ?).\n  on >I_func, invc.\n\n  eexists. split. eapply B.SMakeCall; eauto.\n  i_ctor. i_ctor. i_ctor.\n\n- (* Switchinate *)\n  fwd eapply Forall2_nth_error_ex with (xs := cases) as HH; eauto.  destruct HH as (bcase & ? & ?).\n\n  eexists. split. eapply B.SSwitchinate; eauto.\n  i_ctor. i_ctor.\n\n- (* Copy *)\n  eexists. split. eapply B.SAssign; eauto.\n  i_ctor.\n\n\n- (* ContSeq *)\n  on >I_cont, inv.\n\n  eexists. split. eapply B.SContSeq; eauto.\n  i_ctor.\n\n- (* ContSwitch *)\n  on >I_cont, inv.\n\n  eexists. split. eapply B.SContSwitch; eauto.\n  i_ctor.\n\n- (* ContReturn *)\n  on >I_cont, inv.\n\n  eexists. split. eapply B.SContReturn; eauto.\n  i_ctor.\n\n- (* ContStop *)\n  on >I_cont, inv.\n\n  eexists. split. eapply B.SContStop; eauto.\n  i_ctor.\n\n- (* ContCall *)\n  on >I_cont, inv.\n\n  eexists. split. eapply B.SContCall; eauto.\n  i_ctor.\nQed.\n\n\n\nLemma compile_cu_metas : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = (B, Bmeta) ->\n    Ameta = Bmeta.\nsimpl. inversion 1. auto.\nQed.\n\nRequire oeuf.Semantics.\n\nSection Preservation.\n\n  Variable prog : A.prog_type.\n  Variable tprog : B.prog_type.\n\n  Hypothesis TRANSF : compile_cu prog = tprog.\n\n  Theorem fsim :\n    Semantics.forward_simulation (A.semantics prog) (B.semantics tprog).\n  Proof.\n    destruct prog as [A Ameta], tprog as [B Bmeta].\n    fwd eapply compile_cu_I_env; eauto.\n    fwd eapply compile_cu_metas; eauto.\n\n    eapply Semantics.forward_simulation_step with\n        (match_states := I)\n        (match_values := @eq value).\n\n    - simpl. intros. on >B.is_callstate, invc. simpl in *.\n      destruct ltac:(i_lem Forall2_nth_error_ex') as ([abody aret] & ? & ?).\n      on >I_func, invc.\n\n      (* use `solve` to force econstructor to make the right choices *)\n      eexists. split; solve [repeat i_ctor].\n\n    - intros0 II Afinal. invc Afinal. invc II.\n      eexists; split; i_ctor.\n\n    - simpl. eauto.\n    - simpl. intros. tauto.\n\n    - intros0 Astep. intros0 II.\n      eapply I_sim; try eassumption.\n\n  Qed.\n\nEnd Preservation.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/FlatExprComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.38121955922604417, "lm_q1q2_score": 0.1935878150702741}}
{"text": "Require Import GHC.Num.\n\n(* Characters *)\n\nRequire Import NArith.\nDefinition Char := N.\nBind Scope char_scope   with N.\n\n(* Notation for literal characters in Coq source. *)\nRequire Import Coq.Strings.Ascii.\nDefinition hs_char__ : Ascii.ascii -> Char := N_of_ascii.\nNotation \"'&#' c\" := (hs_char__ c) (at level 1, format \"'&#' c\").\n\n\nDefinition chr : Int -> Char := Z.to_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/base-src/manual/GHC/Char.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19334202598069933}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Csyntax.\n\nOpen Scope error_monad_scope.\n\nSection WITHMEM.\nContext `{Hsc: SyntaxConfiguration}.\nContext `{Hmem: Mem.MemoryModel}.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr (Zpos id) ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nFixpoint constval `{mem_ops: Mem.MemoryOps mem} (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval l\n  | Eunop op r1 ty =>\n      do v1 <- constval r1;\n      match sem_unary_operation op v1 (typeof r1) with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match sem_binary_operation op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some true => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some false => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      do v3 <- constval r3;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval r1; constval r2\n  | Evar x ty =>\n      OK(Vptr (Zpos x) Int.zero)\n  | Ederef r ty =>\n      constval r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id fList _ =>\n          do delta <- field_offset f fList;\n          do v <- constval l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id fList _ =>\n          constval l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r ty =>\n      do v <- constval r; do_cast v (typeof r) ty\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_compound (il: initializer_list)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint I8 sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vfloat f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr (Zpos id) ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr (Zpos id) ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  Return the corresponding list of initialization data. *)\n\nDefinition padding (frm to: Z) : list init_data :=\n  let n := to - frm in\n  if zle n 0 then nil else Init_space n :: nil.\n\nEnd WITHMEM.\n\nFixpoint transl_init `{mem_ops: Mem.MemoryOps}\n                     (ty: type) (i: initializer)\n                     {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ty a; OK (d :: nil)\n  | Init_compound il, Tarray tyelt sz _ =>\n      if zle sz 0\n      then OK (Init_space(sizeof tyelt) :: nil)\n      else transl_init_array tyelt il sz\n  | Init_compound il, Tstruct _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tstruct id fl _ =>\n      transl_init_struct id ty fl il 0\n  | Init_compound il, Tunion _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tunion id (Fcons _ ty1 _) _ =>\n      transl_init_union id ty ty1 il\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array `{mem_ops: Mem.MemoryOps}\n                       (ty: type) (il: initializer_list) (sz: Z)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0\n      then OK nil\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do d1 <- transl_init ty i1;\n      do d2 <- transl_init_array ty il' (sz - 1);\n      OK (d1 ++ d2)\n  end\n\nwith transl_init_struct `{mem_ops: Mem.MemoryOps}\n                        (id: ident) (ty: type)\n                        (fl: fieldlist) (il: initializer_list) (pos: Z)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, Fnil =>\n      OK (padding pos (sizeof ty))\n  | Init_cons i1 il', Fcons _ ty1 fl' =>\n      let pos1 := align pos (alignof ty1) in\n      do d1 <- transl_init (unroll_composite id ty ty1) i1;\n      do d2 <- transl_init_struct id ty fl' il' (pos1 + sizeof ty1);\n      OK (padding pos pos1 ++ d1 ++ d2)\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end\n\nwith transl_init_union `{mem_ops: Mem.MemoryOps}\n                       (id: ident) (ty ty1: type) (il: initializer_list)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      Error (msg \"empty union initializer\")\n  | Init_cons i1 _ =>\n      do d <- transl_init (unroll_composite id ty ty1) i1;\n      OK (d ++ padding (sizeof ty1) (sizeof ty))\n  end.\n\n", "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/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34864514886966635, "lm_q1q2_score": 0.1933134377999613}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Z_keyed_SortedListMap.\nRequire Import coqutil.Byte.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Scalars.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import compiler.Pipeline.\nRequire Import compiler.RiscvWordProperties.\nRequire Import Bedrock2Experiments.List.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIO.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIOPropertiesUnique.\nRequire Import Bedrock2Experiments.LibBase.Bitfield.\nRequire Import Bedrock2Experiments.LibBase.BitfieldProperties.\nRequire Import HmacSoftware.Hmac.\nRequire Import HmacSoftware.HmacSemantics.\nRequire Import HmacSoftware.HmacProperties.\nRequire Import HmacSoftware.Sha256Example.\nRequire Import HmacSoftware.Sha256ExampleProperties.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.StateMachineMMIO.\n\nRequire coqutil.Word.Naive.\nRequire coqutil.Map.SortedListWord.\nRequire riscv.Utility.InstructionNotations.\nImport Syntax.Coercions.\nLocal Open Scope string_scope.\n\nInstance word: word.word 32 := Naive.word 32.\nInstance mem: map.map word Byte.byte := SortedListWord.map _ _.\nExisting Instance SortedListString.map.\nExisting Instance SortedListString.ok.\n\n(* TODO: we actually need a different word implementation than Naive here; in\n   corner cases such as a shift argument greater than the width of the word,\n   the naive implementation violates the riscv_ok requirements *)\nInstance naive_riscv_ok : word.riscv_ok word. Admitted.\n\n(* TODO match to actual Cava implementation *)\nInstance hmac_timing: timing := {\n  max_negative_done_polls := 16;\n}.\n\nNotation bytearray := (bedrock2.Array.array (mem := mem) ptsto (word.of_Z 1)).\n\n(* Plug in the right state machine parameters; typeclass inference struggles here *)\nLocal Notation execution := (execution (M:=hmac_state_machine)).\n\nDefinition funcs := [\n  b2_sha256;\n  b2_hmac_sha256_init; b2_hmac_sha256_update; b2_hmac_sha256_final;\n  abs_mmio_write32; abs_mmio_read32; abs_mmio_write8; abs_mmio_read8;\n  bitfield_bit32_write; bitfield_bit32_read;\n  bitfield_field32_write; bitfield_field32_read\n].\n\nLemma link_sha256: spec_of_sha256 funcs.\nProof.\n  (* TODO speedup, don't reprove the same specs many times *)\n  repeat first\n         [ eapply sha256_correct\n         | eapply hmac_sha256_init_correct\n         | eapply hmac_sha256_update_correct\n         | eapply hmac_sha256_final_correct\n         | eapply abs_mmio_write32_correct\n         | eapply abs_mmio_read32_correct\n         | eapply abs_mmio_write8_correct\n         | eapply abs_mmio_read8_correct\n         | eapply bitfield_bit32_write_correct\n         | eapply bitfield_field32_write_correct\n         | eapply bitfield_bit32_read_correct\n         | eapply bitfield_field32_read_correct\n         | eapply HmacProperties.execution_unique\n         | idtac ].\nQed.\n\nLemma funcs_valid: ExprImp.valid_funs (map.of_list funcs).\nProof.\n  cbv [funcs map.of_list ExprImp.valid_funs]. intros *.\n  repeat match goal with\n         | |- context[match ?p with _ => _ end] => cbv [p]\n         end.\n  rewrite !map.get_put_dec, map.get_empty.\n  repeat destruct_one_match; inversion 1; cbv [ExprImp.valid_fun].\n  all:ssplit.\n  all:apply dedup_NoDup_iff.\n  all:reflexivity.\nQed.\n\nDefinition sha256_compile_result:\n  list Decode.Instruction * (SortedListString.map (nat * nat * Z)) * Z.\n  let r := eval vm_compute in (compile compile_ext_call (map.of_list funcs)) in\n   match r with\n  | Some ?x => exact x\n  end.\nDefined.\n\nDefinition sha256_asm := Eval compute in fst (fst sha256_compile_result).\nDefinition sha256_finfo := Eval compute in snd (fst sha256_compile_result).\nDefinition sha256_req_stack := Eval compute in snd sha256_compile_result.\n\nLemma sha256_compile_result_eq:\n  compile compile_ext_call (map.of_list funcs) =\n  Some (sha256_asm, sha256_finfo, sha256_req_stack).\nProof. reflexivity. Qed.\n\nModule PrintAssembly.\n  Import riscv.Utility.InstructionNotations.\n  Goal False.\n    let r := eval unfold sha256_asm in sha256_asm in idtac (*r*).\n  Abort.\nEnd PrintAssembly.\n\nDefinition sha256_relative_pos :=\n  match map.get sha256_finfo (fst b2_sha256) with\n  | Some (_, _, p) => p\n  | None => -1111\n  end.\n\nLemma sha256_asm_valid_instructions:\n  Forall (fun instr => Encode.verify instr Decode.RV32IM) sha256_asm.\nProof.\n  repeat (apply Forall_cons || apply Forall_nil).\n  all: try (vm_compute; intuition discriminate).\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/silveroak-opentitan/hmac/sw/Sha256ToRiscV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.19331343779996124}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef.\nRequire Import IntroHeader.\nImport Plain.\n\nSet Implicit Arguments.\n\n\n\nSection PROOF.\n\n  Context `{\u03a3: GRA.t}.\n  Context `{@GRA.inG IRA.t \u03a3}.\n\n  Definition Gsbtb: list (string * fspecbody) := [(\"g\", mk_specbody g_spec (fun _ => trigger (Choose _)))].\n\n  Definition GSem: SModSem.t := {|\n    SModSem.fnsems := Gsbtb;\n    SModSem.mn := \"G\";\n    SModSem.initial_mr := GRA.embed (IRA.module true: IRA.t);\n    SModSem.initial_st := tt\u2191;\n  |}\n  .\n\n  Definition G: Mod.t := (SMod.to_tgt (fun _ => GlobalStb)) {|\n    SMod.get_modsem := fun _ => GSem;\n    SMod.sk := [(\"g\", 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/intro/IntroG1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.19331343404738263}}
{"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: Refinement Proof for PUctxtIntro            *)\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 PIPC layer and PUCtxtIntro layer*)\n\nRequire Import UCtxtIntroGenDef.\nRequire Import UCtxtIntroGenSpec.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Ltac pattern2_refinement_simpl:=  \n    pattern2_refinement_simpl' (@relate_AbData).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Lemma save_uctx_spec_ref:\n      compatsim (crel HDATA LDATA) (save_uctx_compatsem save_uctx_spec)\n                save_uctx_spec_low.\n    Proof. \n      compatsim_simpl (@match_AbData). \n      assert(HOS: kernel_mode d2 /\\ 0 <= cid d2 < num_proc\n                  /\\ cid d1' = cid d2\n                  /\\ uctxt d1' = ZMap.set (cid d1') uctx4 (uctxt d1)\n                  /\\ pg d2 = true).\n      {\n        simpl; inv match_related.\n        functional inversion H6; subst; simpl. inv Hhigh.\n        refine_split'; trivial; try congruence.\n      }\n      destruct HOS as [Hkern [HOS[Hcid [Heq Hpe]]]].\n      inv H. rename H0 into HMem. \n      set (vcid := cid d2) in *. \n      assert (HV0: forall n0, 0<= n0 < UCTXT_SIZE -> \n                              Mem.valid_access m2 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros n0 HR. specialize (HMem _ _ HOS HR).\n        destruct HMem as [_[_[HV _]]].\n        replace (17 * 4 * vcid + 4 * n0) with (vcid * 17 * 4 + n0 * 4) by omega. trivial.\n      }\n      assert (HP: exists m0, Mem.store Mint32 m2 b (UCTXT_SIZE * 4 * vcid + 4 * U_EDI) (Vint v0) = Some m0).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV0. omega.\n      }\n      destruct HP as [m0 HST0].\n      assert (HV1: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m0 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros. eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV0.        \n      assert (HP: exists m1, Mem.store Mint32 m0 b (UCTXT_SIZE * 4 * vcid + 4 * U_ESI) (Vint v1) = Some m1).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV1. omega.\n      }\n      destruct HP as [m1 HST1].\n      assert (HV2: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m1 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV1.\n      assert (HP: exists m2, Mem.store Mint32 m1 b (UCTXT_SIZE * 4 * vcid + 4 * U_EBP) (Vint v2) = Some m2).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV2. omega.\n      }\n      destruct HP as [m2' HST2].\n      assert (HV3: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m2' Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV2.\n      assert (HP: exists m3, Mem.store Mint32 m2' b (UCTXT_SIZE * 4 * vcid + 4 * U_OESP) (Vint v3) = Some m3).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV3. omega.\n      }\n      destruct HP as [m3 HST3].\n      assert (HV4: forall n0, 0<= n0 < UCTXT_SIZE ->  Mem.valid_access m3 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV3.\n      assert (HP: exists m4, Mem.store Mint32 m3 b (UCTXT_SIZE * 4 * vcid + 4 * U_EBX) (Vint v4) = Some m4).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV4. omega.\n      }\n      destruct HP as [m4 HST4].\n      assert (HV5: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m4 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV4.\n      assert (HP: exists m5, Mem.store Mint32 m4 b (UCTXT_SIZE * 4 * vcid + 4 * U_EDX) (Vint v5) = Some m5).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV5. omega.\n      }\n      destruct HP as [m5 HST5].\n      assert (HV6: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m5 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV5.\n      assert (HP: exists m6, Mem.store Mint32 m5 b (UCTXT_SIZE * 4 * vcid + 4 * U_ECX) (Vint v6) = Some m6).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV6. omega.\n      }\n      destruct HP as [m6 HST6].\n      assert (HV7: forall n0, 0<= n0 < UCTXT_SIZE ->  Mem.valid_access m6 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV6.\n      assert (HP: exists m7, Mem.store Mint32 m6 b (UCTXT_SIZE * 4 * vcid + 4 * U_EAX) (Vint v7) = Some m7).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV7. omega.\n      }\n      destruct HP as [m7 HST7].\n      assert (HV8: forall n0, 0<= n0 < UCTXT_SIZE ->  Mem.valid_access m7 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV7.\n      assert (HP: exists m8, Mem.store Mint32 m7 b (UCTXT_SIZE * 4 * vcid + 4 * U_ES) (Vint v8) = Some m8).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV8. omega.\n      }\n      destruct HP as [m8 HST8].\n      assert (HV9: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m8 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV8.\n      assert (HP: exists m9, Mem.store Mint32 m8 b (UCTXT_SIZE * 4 * vcid + 4 * U_DS) (Vint v9) = Some m9).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV9. omega.\n      }\n      destruct HP as [m9 HST9].\n      assert (HV10: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m9 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV9.\n      assert (HP: exists m10, Mem.store Mint32 m9 b (UCTXT_SIZE * 4 * vcid + 4 * U_TRAPNO) (Vint v10) = Some m10).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV10. omega.\n      }\n      destruct HP as [m10 HST10].\n      assert (HV11: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m10 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV10.\n      assert (HP: exists m11, Mem.store Mint32 m10 b (UCTXT_SIZE * 4 * vcid + 4 * U_ERR) (Vint v11) = Some m11).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV11. omega.\n      }\n      destruct HP as [m11 HST11].\n      assert (HV12: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m11 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV11.\n      assert (HP: exists m12, Mem.store Mint32 m11 b (UCTXT_SIZE * 4 * vcid + 4 * U_EIP) (Vint v12) = Some m12).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV12. omega.\n      }\n      destruct HP as [m12 HST12].\n      assert (HV13: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m12 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV12.\n      assert (HP: exists m13, Mem.store Mint32 m12 b (UCTXT_SIZE * 4 * vcid + 4 * U_CS) (Vint v13) = Some m13).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV13. omega.\n      }\n      destruct HP as [m13 HST13].\n      assert (HV14: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m13 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV13.\n      assert (HP: exists m14, Mem.store Mint32 m13 b (UCTXT_SIZE * 4 * vcid + 4 * U_EFLAGS) (Vint v14) = Some m14).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV14. omega.\n      }\n      destruct HP as [m14 HST14].\n      assert (HV15: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m14 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV14.\n      assert (HP: exists m15, Mem.store Mint32 m14 b (UCTXT_SIZE * 4 * vcid + 4 * U_ESP) (Vint v15) = Some m15).\n      {          \n        apply (Mem.valid_access_store); auto.\n        apply HV15. omega.\n      }\n      destruct HP as [m15 HST15].\n      assert (HV16: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m15 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV15.\n      assert (HP: exists m16, Mem.store Mint32 m15 b (UCTXT_SIZE * 4 * vcid + 4 * U_SS) (Vint v16) = Some m16).\n      {\n        apply (Mem.valid_access_store); auto.\n        apply HV16. omega.\n      }\n      destruct HP as [m16 HST16].\n      assert (HV: forall n0, 0<= n0 < UCTXT_SIZE -> Mem.valid_access m16 Mint32 b (UCTXT_SIZE * 4 * vcid + 4 * n0) Writable).\n      {\n        intros; eapply Mem.store_valid_access_1; eauto.\n      }\n      clear HV16.\n      \n      assert(HMCTXT: match_UCtxt s (uctxt d1') m16 \u03b9).  \n      {\n        econstructor; eauto.\n        intros n r HZ HO.\n        replace (n * 17 * 4 + r * 4) with (17 * 4 * n + 4 * r) by omega.\n        unfold UContext in Heq. rewrite Heq.\n        rewrite Hcid.             \n        destruct (zeq n vcid); subst.\n        - rewrite ZMap.gss.\n          destruct (zeq r U_SS); subst.\n          refine_split'; trivial.\n          erewrite Mem.load_store_same; eauto.      \n          Ltac simpl_valid_access m :=\n            repeat match goal with\n                     | [ |- Mem.valid_access m _ _ _ _] \n                       => eapply Mem.store_valid_access_3; eauto\n                     | _ => eapply Mem.store_valid_access_1; eauto\n                   end.\n          simpl_valid_access m15.\n          subst uctx3 uctx2 uctx1.\n          Ltac simpl_zmap_get :=\n            repeat match goal with\n                     | [ |- context[ZMap.get ?a (ZMap.set ?a _ _ )]] \n                       => rewrite ZMap.gss\n                     | [ H0: ?a <> ?b |- context[ZMap.get ?a (ZMap.set ?b _ _ )]]\n                       => rewrite (ZMap.gso _ _ H0); auto\n                     | _ => constructor\n                   end.\n          simpl_zmap_get.          \n          assert (HW0: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m15 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST16); trivial.\n            right. destruct (zlt r U_SS).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          destruct (zeq r U_ESP); subst.\n          refine_split'; trivial.\n          rewrite HW0.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m14.\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW1: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)\n                       = Mem.load Mint32 m14 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW0.\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST15); trivial.\n            right. destruct (zlt r U_ESP).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          destruct (zeq r U_EFLAGS); subst.\n          refine_split'; trivial.\n          rewrite HW1.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m13.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW2: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m13 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW1.\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST14); trivial.\n            right. destruct (zlt r U_EFLAGS).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW0 HW1.\n          destruct (zeq r U_CS); subst.\n          refine_split'; trivial.\n          rewrite HW2.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m12.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW3: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m12 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW2. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST13).\n            trivial. right. destruct (zlt r U_CS).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW2.\n          destruct (zeq r U_EIP); subst.\n          refine_split'; trivial.\n          rewrite HW3.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m11.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW4: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m11 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW3. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST12).\n            trivial. right. destruct (zlt r U_EIP).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW3.\n          destruct (zeq r U_ERR); subst.\n          refine_split'; trivial.\n          rewrite HW4.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m10.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW5: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m10 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW4. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST11).\n            trivial. right. destruct (zlt r U_ERR).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW4.\n          destruct (zeq r U_TRAPNO); subst.\n          refine_split'; trivial.\n          rewrite HW5.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m9.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW6: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m9 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW5. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST10).\n            trivial. right. destruct (zlt r U_TRAPNO).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW5.\n          destruct (zeq r U_DS); subst.\n          refine_split'; trivial.\n          rewrite HW6.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m8.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW7: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m8 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW6. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST9).\n            trivial. right. destruct (zlt r U_DS).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW6.\n          destruct (zeq r U_ES); subst.\n          refine_split'; trivial.\n          rewrite HW7.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m7.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW8: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m7 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW7. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST8).\n            trivial. right. \n            destruct (zlt r U_ES).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW7.\n          destruct (zeq r U_EAX); subst.\n          refine_split'; trivial.\n          rewrite HW8.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m6.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW9: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                       = Mem.load Mint32 m6 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW8.\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST7).\n            trivial. right. \n            destruct (zlt r U_EAX).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW8.\n          destruct (zeq r U_ECX); subst.\n          refine_split'; trivial.\n          rewrite HW9.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m5.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW10: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m5 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW9. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST6).\n            trivial. right. destruct (zlt r U_ECX).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW9.\n          destruct (zeq r U_EDX); subst.\n          refine_split'; trivial.\n          rewrite HW10.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m4.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW11: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m4 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW10. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST5).\n            trivial. right. destruct (zlt r U_EDX).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW10.\n          destruct (zeq r U_EBX); subst.\n          refine_split'; trivial.\n          rewrite HW11.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m3.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW12: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m3 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW11. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST4).\n            trivial. right. \n            destruct (zlt r U_EBX); subst.\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW11.\n          destruct (zeq r U_OESP); subst.\n          refine_split'; trivial.\n          rewrite HW12.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m2'.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW13: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m2' b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW12. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST3).\n            trivial. right. destruct (zlt r U_OESP).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW12.\n          destruct (zeq r U_EBP); subst.\n          refine_split'; trivial.\n          rewrite HW13.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m1.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW14: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m1 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW13. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST2).\n            trivial. right. destruct (zlt r U_EBP).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW13.\n          destruct (zeq r U_ESI); subst.\n          refine_split'; trivial.\n          rewrite HW14.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m0.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW15: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                        = Mem.load Mint32 m0 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW14. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST1).\n            trivial. right. destruct (zlt r U_ESI).\n            left. unfold size_chunk. omega.\n            right. unfold size_chunk. omega.\n          }\n          clear HW14.\n          destruct (zeq r U_EDI); subst.\n          refine_split'; trivial.\n          rewrite HW15.\n          erewrite Mem.load_store_same; eauto.\n          simpl_valid_access m2.\n\n          subst uctx3 uctx2 uctx1.\n          simpl_zmap_get.\n\n          assert (HW: Mem.load Mint32 m16 b (UCTXT_SIZE * 4 * cid d2 + 4 * r) \n                      = Mem.load Mint32 m2 b (UCTXT_SIZE * 4 * cid d2 + 4 * r)).\n          {\n            rewrite HW15. rewrite (Mem.load_store_other  _ _ _ _ _ _ HST0).\n            trivial. right. \n            right. unfold size_chunk. omega.\n          } \n          clear HW15. omega.\n          \n        - Opaque Z.add Z.mul Val.load_result.\n          rewrite ZMap.gso; auto.\n          simpl in *.\n          specialize (HMem _ _ HZ HO).\n          destruct HMem as [v[HL[HVa HM]]].\n          eexists v. split.\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST16); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST15); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST14); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST13); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST12); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST11); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST10); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST9); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST8); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST7); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST6); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST5);\n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST4); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST3); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST2);\n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST1); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          rewrite (Mem.load_store_other  _ _ _ _ _ _ HST0); \n            [ |destruct (zle n (cid d2)); right;[left; simpl; omega|right; simpl; omega]].\n          replace (17 * 4 * n + 4 * r) with (n * 17 * 4 + r * 4) by omega. \n          apply HL.\n\n          split; trivial.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          eapply Mem.store_valid_access_1; eauto.\n          replace (17 * 4 * n + 4 * r) with (n * 17 * 4 + r * 4) by omega. \n          apply HVa.\n      }\n\n      refine_split; eauto 2.\n      - econstructor; eauto.\n        instantiate (1:= (m0, d2)).         \n        lift_simpl. split; eauto.\n        instantiate (1:= (m1, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m2', d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m3, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m4, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m5, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m6, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m7, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m8, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m9, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m10, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m11, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m12, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m13, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m14, d2)).\n        lift_simpl. split; eauto.\n        instantiate (1:= (m15, d2)).\n        lift_simpl. split; eauto.\n        instantiate (2:= m16).\n        lift_simpl. split; eauto.\n\n      - pose proof H6 as Hspec.\n        functional inversion Hspec; subst.\n        split; eauto; pattern2_refinement_simpl. \n        econstructor; simpl; 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/proc/UCtxtIntroGenFresh0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.1933088252640336}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export type_system.\n\nLocal Open Scope expr_scope.\nLocal Open Scope ctype_scope.\n\nSet Warnings \"-fragile-hint-constr\".\n\nSection deciders.\nContext `{Env K}.\nNotation envs := (env K * memenv K * list (type K))%type.\n\n#[global] Instance assign_typed_dec (\u03c41 \u03c42 : type K) (ass : assign) :\n  Decision (assign_typed \u03c41 \u03c42 ass).\nProof.\n refine\n  match ass with\n  | Assign => cast_if (decide (cast_typed \u03c42 \u03c41))\n  | PreOp op | PostOp op =>\n     match Some_dec (binop_type_of op \u03c41 \u03c42) with\n     | inleft (\u03c3 \u21be _) => cast_if (decide (cast_typed \u03c3 \u03c41))\n     | inright _ => right _\n     end\n  end; repeat first\n    [ by subst; econstructor; eauto using binop_type_of_sound\n    | by inversion 1; repeat match goal with\n      | H : binop_typed _ _ _ _ |- _ => apply binop_type_of_complete in H\n      end; simplify_equality'\n    | destruct \u03c41 | destruct \u03c42 ].\nDefined.\n#[global] Instance lrval_type_check:\n   TypeCheck (env K * memenv K) (lrtype K) (lrval K) := \u03bb \u0393\u0394 \u03bd,\n  match \u03bd with\n  | inl p => inl <$> type_check \u0393\u0394 p\n  | inr v => inr <$> type_check \u0393\u0394 v\n  end.\n#[global] Instance expr_type_check: TypeCheck envs (lrtype K) (expr K) :=\n  fix go \u0393s e {struct e} := let _ : TypeCheck envs _ _ := @go in\n  let '(\u0393,\u0394,\u03c4s) := \u0393s in\n  match e with\n  | var n => \u03c4 \u2190 \u03c4s !! n; Some (inl (TType \u03c4))\n  | %#{\u03a9} \u03bd => guard (\u2713{\u0393,\u0394} \u03a9); type_check (\u0393,\u0394) \u03bd\n  | .* e =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe inr;\n     \u03c4p \u2190 maybe (TBase \u2218 TPtr) \u03c4;\n     Some (inl \u03c4p)\n  | & e =>\n     \u03c4p \u2190 type_check \u0393s e \u226b= maybe inl;\n     Some (inr (\u03c4p.*))\n  | e1 ::={ass} e2 =>\n     \u03c41 \u2190 type_check \u0393s e1 \u226b= maybe (inl \u2218 TType);\n     \u03c42 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     guard (assign_typed \u03c41 \u03c42 ass);\n     Some (inr \u03c41)\n  | call e @ es =>\n     '(\u03c3s,\u03c3) \u2190 (type_check \u0393s e \u226b= maybe inl) \u226b= maybe2 TFun;\n     \u03c3s' \u2190 mapM (\u03bb e, type_check \u0393s e \u226b= maybe inr) es;\n     guard ((\u03c3s' : list (type K)) = \u03c3s); guard (type_complete \u0393 \u03c3); Some (inr \u03c3)\n  | abort \u03c4 => guard (\u2713{\u0393} \u03c4); Some (inr \u03c4)\n  | load e =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe (inl \u2218 TType);\n     guard (type_complete \u0393 \u03c4);\n     Some (inr \u03c4)\n  | e %> rs =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe (inl \u2218 TType);\n     inl \u2218 TType <$> \u03c4 !!{\u0393} rs\n  | e #> rs =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe inr;\n     inr <$> \u03c4 !!{\u0393} rs\n  | alloc{\u03c4} e =>\n     _ \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase \u2218 TInt);\n     guard (\u2713{\u0393} \u03c4); Some (inl (TType \u03c4))\n  | free e =>\n     \u03c4p \u2190 type_check \u0393s e \u226b= maybe inl;\n     Some (inr voidT)\n  | .{op} e =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe inr;\n     inr <$> unop_type_of op \u03c4\n  | e1 .{op} e2 =>\n     \u03c41 \u2190 type_check \u0393s e1 \u226b= maybe inr;\n     \u03c42 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     inr <$> binop_type_of op \u03c41 \u03c42\n  | if{e1} e2 else e3 =>\n     \u03c4b \u2190 type_check \u0393s e1 \u226b= maybe (inr \u2218 TBase); guard (\u03c4b \u2260 @TVoid K);\n     \u03c4lr2 \u2190 type_check \u0393s e2;\n     \u03c4lr3 \u2190 type_check \u0393s e3;\n     guard (\u03c4lr2 = \u03c4lr3); Some \u03c4lr2\n  | e1,, e2 =>\n     _ \u2190 type_check \u0393s e1; type_check \u0393s e2\n  | cast{\u03c3} e =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe inr;\n     guard (cast_typed \u03c4 \u03c3); guard (\u2713{\u0393} \u03c3); Some (inr \u03c3)\n  | #[r:=e1] e2 =>\n     \u03c3 \u2190 type_check \u0393s e1 \u226b= maybe inr;\n     \u03c4 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     \u03c3' \u2190 \u03c4 !!{\u0393} r;\n     guard ((\u03c3':type K) = \u03c3); Some (inr \u03c4)\n  end.\n#[global] Instance ectx_item_lookup :\n    LookupE envs (ectx_item K) (lrtype K) (lrtype K) := \u03bb \u0393s Ei \u03c4lr,\n  let '(\u0393,\u0394,\u03c4s) := \u0393s in\n  match Ei, \u03c4lr with\n  | .* \u25a1, inr \u03c4 =>\n    \u03c4p \u2190 maybe (TBase \u2218 TPtr) \u03c4;\n    Some (inl \u03c4p)\n  | & \u25a1, inl \u03c4p => Some (inr (\u03c4p.*))\n  | \u25a1 ::={ass} e2, inl \u03c4p1 =>\n     \u03c41 \u2190 maybe TType \u03c4p1;\n     \u03c42 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     guard (assign_typed \u03c41 \u03c42 ass);\n     Some (inr \u03c41)\n  | e1 ::={ass} \u25a1, inr \u03c42 =>\n     \u03c41 \u2190 type_check \u0393s e1 \u226b= maybe (inl \u2218 TType);\n     guard (assign_typed \u03c41 \u03c42 ass);\n     Some (inr \u03c41)\n  | call \u25a1 @ es, inl \u03c4p =>\n     '(\u03c3s,\u03c3) \u2190 maybe2 TFun \u03c4p;\n     \u03c3s' \u2190 mapM (\u03bb e, type_check \u0393s e \u226b= maybe inr) es;\n     guard ((\u03c3s : list (type K)) = \u03c3s'); guard (type_complete \u0393 \u03c3); Some (inr \u03c3)\n  | call e @ es1 \u25a1 es2, inr \u03c4 =>\n     '(\u03c3s,\u03c3) \u2190 (type_check \u0393s e \u226b= maybe inl) \u226b= maybe2 TFun;\n     \u03c3s1 \u2190 mapM (\u03bb e, type_check \u0393s e \u226b= maybe inr) (reverse es1);\n     \u03c3s2 \u2190 mapM (\u03bb e, type_check \u0393s e \u226b= maybe inr) es2;\n     guard ((\u03c3s : list (type K)) = \u03c3s1 ++ \u03c4 :: \u03c3s2);\n     guard (type_complete \u0393 \u03c3); Some (inr \u03c3)\n  | load \u25a1, inl \u03c4p =>\n     \u03c4 \u2190 maybe TType \u03c4p;\n     guard (type_complete \u0393 \u03c4);\n     Some (inr \u03c4)\n  | \u25a1 %> rs, inl \u03c4p => \u03c4 \u2190 maybe TType \u03c4p; inl \u2218 TType <$> \u03c4 !!{\u0393} rs\n  | \u25a1 #> rs, inr \u03c4 => inr <$> \u03c4 !!{\u0393} rs\n  | alloc{\u03c4} \u25a1, inr \u03c4' =>\n     _ \u2190 maybe (TBase \u2218 TInt) \u03c4'; guard (\u2713{\u0393} \u03c4); Some (inl (TType \u03c4))\n  | free \u25a1, inl \u03c4p => Some (inr voidT)\n  | .{op} \u25a1, inr \u03c4 => inr <$> unop_type_of op \u03c4\n  | \u25a1 .{op} e2, inr \u03c41 =>\n     \u03c42 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     inr <$> binop_type_of op \u03c41 \u03c42\n  | e1 .{op} \u25a1, inr \u03c42 =>\n     \u03c41 \u2190 type_check \u0393s e1 \u226b= maybe inr;\n     inr <$> binop_type_of op \u03c41 \u03c42\n  | if{\u25a1} e2 else e3, inr \u03c41 =>\n     \u03c4b \u2190 maybe TBase \u03c41; guard (\u03c4b \u2260 @TVoid K);\n     \u03c4lr2 \u2190 type_check \u0393s e2;\n     \u03c4lr3 \u2190 type_check \u0393s e3;\n     guard (\u03c4lr2 = \u03c4lr3); Some \u03c4lr2\n  | \u25a1 ,, e2, _ => type_check \u0393s e2\n  | cast{\u03c3} \u25a1, inr \u03c4 => guard (cast_typed \u03c4 \u03c3); guard (\u2713{\u0393} \u03c3); Some (inr \u03c3)\n  | #[r:=\u25a1] e2, inr \u03c3 =>\n     \u03c4 \u2190 type_check \u0393s e2 \u226b= maybe inr;\n     \u03c3' \u2190 \u03c4 !!{\u0393} r;\n     guard ((\u03c3':type K) = \u03c3); Some (inr \u03c4)\n  | #[r:=e1] \u25a1, inr \u03c4 =>\n     \u03c3 \u2190 type_check \u0393s e1 \u226b= maybe inr;\n     \u03c3' \u2190 \u03c4 !!{\u0393} r;\n     guard ((\u03c3':type K) = \u03c3); Some (inr \u03c4)\n  | _, _ => None\n  end.\n#[global] Instance ectx_lookup :\n    LookupE envs (ectx K) (lrtype K) (lrtype K) :=\n  fix go \u0393s E \u03c4lr {struct E} := let _ : LookupE _ _ _ _ := @go in\n  match E with [] => Some \u03c4lr | Ei :: E => \u03c4lr !!{\u0393s} Ei \u226b= lookupE \u0393s E end.\nDefinition rettype_union_alt\n    (m\u03c31 m\u03c32 : option (type K)) : option (option (type K)) :=\n  match m\u03c31, m\u03c32 with\n  | Some \u03c31, Some \u03c32 => guard (\u03c31 = \u03c32); Some (Some \u03c31)\n  | None, m\u03c3 | m\u03c3, None => Some m\u03c3\n  end.\n#[global] Instance rettype_match_dec (cm\u03c3 : rettype K) \u03c3 :\n  Decision (rettype_match cm\u03c3 \u03c3).\nProof.\n refine\n  match cm\u03c3 with\n  | (true,Some \u03c3') => cast_if (decide (\u03c3' = \u03c3))\n  | (false,Some \u03c3') => cast_if (decide (\u03c3' = \u03c3 \u2227 \u03c3 = voidT))\n  | (true,None) => left _\n  | (false,None) => cast_if (decide (\u03c3 = voidT))\n  end; abstract\n    first [by intuition; subst; constructor|inversion 1; subst; intuition].\nDefined.\n#[global] Instance stmt_type_check: TypeCheck envs (rettype K) (stmt K) :=\n  fix go \u0393s s {struct s} := let _ : TypeCheck envs _ _ := @go in\n  let '(\u0393,\u0394,\u03c4s) := \u0393s in\n  match s with\n  | skip => Some (false,None)\n  | ! e =>\n     _ \u2190 type_check \u0393s e \u226b= maybe inr; guard (locks e = \u2205); Some (false,None)\n  | goto _ | throw _ => Some (true,None)\n  | ret e =>\n     \u03c4 \u2190 type_check \u0393s e \u226b= maybe inr; guard (locks e = \u2205); Some (true,Some \u03c4)\n  | label _ | scase _ => Some (false,None)\n  | local{\u03c4} s => guard (\u2713{\u0393} \u03c4); type_check (\u0393,\u0394,\u03c4 :: \u03c4s) s\n  | s1 ;; s2 =>\n     '(c1,m\u03c31) \u2190 type_check \u0393s s1;\n     '(c2,m\u03c32) \u2190 type_check \u0393s s2;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c2,m\u03c3)\n  | catch s => '(c,m\u03c3) \u2190 type_check \u0393s s; Some (false,m\u03c3)\n  | loop s => '(_,m\u03c3) \u2190 type_check \u0393s s; Some (true,m\u03c3)\n  | if{e} s1 else s2 =>\n     \u03c4b \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase); guard (\u03c4b \u2260 @TVoid K);\n     guard (locks e = \u2205);\n     '(c1,m\u03c31) \u2190 type_check \u0393s s1;\n     '(c2,m\u03c32) \u2190 type_check \u0393s s2;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c1 && c2,m\u03c3)\n  | switch{e} s =>\n     \u03c4i \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase \u2218 TInt);\n     guard (locks e = \u2205); '(_,m\u03c3) \u2190 type_check \u0393s s; Some (false,m\u03c3)\n  end%S.\n#[global] Instance sctx_item_lookup :\n    LookupE envs (sctx_item K) (rettype K) (rettype K) := \u03bb \u0393s Es \u03c4lr,\n  match Es, \u03c4lr with\n  | \u25a1 ;; s2, (c1,m\u03c31) =>\n     '(c2,m\u03c32) \u2190 type_check \u0393s s2;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c2,m\u03c3)\n  | s1 ;; \u25a1, (c2,m\u03c32) =>\n     '(c1,m\u03c31) \u2190 type_check \u0393s s1;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c2,m\u03c3)\n  | catch \u25a1, (c,m\u03c3) => Some (false,m\u03c3)\n  | loop \u25a1, (c,m\u03c3) => Some (true,m\u03c3)\n  | if{e} \u25a1 else s2, (c1,m\u03c31) =>\n     \u03c4b \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase); guard (\u03c4b \u2260 @TVoid K);\n     guard (locks e = \u2205);\n     '(c2,m\u03c32) \u2190 type_check \u0393s s2;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c1&&c2,m\u03c3)\n  | if{e} s1 else \u25a1, (c2,m\u03c32) =>\n     \u03c4b \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase); guard (\u03c4b \u2260 @TVoid K);\n     guard (locks e = \u2205);\n     '(c1,m\u03c31) \u2190 type_check \u0393s s1;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c1&&c2,m\u03c3)\n  | switch{e} \u25a1, (c,m\u03c3) =>\n     \u03c4b \u2190 type_check \u0393s e \u226b= maybe (inr \u2218 TBase \u2218 TInt);\n     guard (locks e = \u2205); Some (false,m\u03c3)\n  end%S.\n#[global] Instance esctx_item_lookup :\n    LookupE envs (esctx_item K) (rettype K) (type K) := \u03bb \u0393s Ee \u03c4lr,\n  match Ee, \u03c4lr with\n  | ! \u25a1, _ => Some (false,None)\n  | ret \u25a1, _ => Some (true,Some \u03c4lr)\n  | if{\u25a1} s1 else s2, baseT \u03c4b =>\n     guard (\u03c4b \u2260 TVoid);\n     '(c1,m\u03c31) \u2190 type_check \u0393s s1;\n     '(c2,m\u03c32) \u2190 type_check \u0393s s2;\n     m\u03c3 \u2190 rettype_union_alt m\u03c31 m\u03c32; Some (c1 && c2,m\u03c3)\n  | switch{\u25a1} s, intT \u03c4i =>\n     '(_,m\u03c3) \u2190 type_check \u0393s s; Some (false,m\u03c3)\n  | _, _ => None\n  end%S.\n#[global] Instance ctx_item_lookup :\n    LookupE envs (ctx_item K) (focustype K) (focustype K) := \u03bb \u0393s Ek \u03c4lr,\n  let '(\u0393,\u0394,\u03c4s) := \u0393s in\n  match Ek, \u03c4lr with\n  | CStmt Es, Stmt_type cm\u03c31 => Stmt_type <$> cm\u03c31 !!{\u0393s} Es\n  | CLocal o \u03c4, Stmt_type cm\u03c3 => guard (\u0394 \u22a2 o : \u03c4); Some (Stmt_type cm\u03c3)\n  | CExpr e Ee, Expr_type \u03c4 =>\n     \u03c4' \u2190 type_check \u0393s e \u226b= maybe inr; guard (locks e = \u2205);\n     guard (\u03c4 = \u03c4'); Stmt_type <$> \u03c4 !!{\u0393s} Ee\n  | CFun E, Fun_type f =>\n     '(\u03c3s,\u03c4) \u2190 \u0393 !! f; Expr_type <$> inr \u03c4 !!{\u0393s} E \u226b= maybe inr\n  | CParams f o\u03c3s, Stmt_type cm\u03c3 =>\n     '(\u03c3s,\u03c3) \u2190 \u0393 !! f;\n     let os := o\u03c3s.*1 in let \u03c3s' := o\u03c3s.*2 in\n     guard (\u03c3s' = \u03c3s); guard (\u0394 \u22a2* os :* \u03c3s); guard (rettype_match cm\u03c3 \u03c3);\n     Some (Fun_type f)\n  | _, _ => None\n  end.\n#[global] Instance focus_type_check:\n    TypeCheck envs (focustype K) (focus K) := \u03bb \u0393s \u03c6,\n  let '(\u0393,\u0394,\u03c4s) := \u0393s in\n  match \u03c6 with\n  | Stmt d s =>\n     cm\u03c3 \u2190 type_check \u0393s s;\n     match d, cm\u03c3 with\n     | \u21c8 v, (c,Some \u03c4) =>\n        \u03c4' \u2190 type_check (\u0393,\u0394) v;\n        guard ((\u03c4 : type K) = \u03c4'); Some (Stmt_type cm\u03c3)\n     | \u2198, _ | \u2197, (false,_) | \u21b7 _, _ | \u2191 _, _ | \u2193 _, _ => Some (Stmt_type cm\u03c3)\n     | _, _ => None\n     end\n  | Expr e => Expr_type <$> type_check \u0393s e \u226b= maybe inr\n  | Call f vs =>\n     '(\u03c3s,_) \u2190 \u0393 !! f;\n     \u03c3s' \u2190 mapM (type_check (\u0393,\u0394)) vs;\n     guard ((\u03c3s : list (type K)) = \u03c3s'); Some (Fun_type f)\n  | Return f v =>\n     '(_,\u03c3) \u2190 \u0393 !! f;\n     \u03c3' \u2190 type_check (\u0393,\u0394) v;\n     guard ((\u03c3 : type K) = \u03c3'); Some (Fun_type f)\n  | Undef (UndefExpr E e) =>\n     Expr_type <$> (type_check \u0393s e \u226b= lookupE \u0393s E) \u226b= maybe inr\n  | Undef (UndefBranch Es \u03a9 v) =>\n     guard (\u2713{\u0393,\u0394} \u03a9); \u03c4 \u2190 type_check (\u0393,\u0394) v; Stmt_type <$> \u03c4 !!{\u0393s} Es\n  end.\nEnd deciders.\n\nSection properties.\nContext `{EnvSpec K}.\nImplicit Types \u0393 : env K.\nImplicit Types \u0394 : memenv K.\nImplicit Types \u03c4 \u03c3 : type K.\nNotation envs := (env K * memenv K * list (type K))%type.\n\nLtac simplify :=\n  repeat match goal with\n  | mc\u03c4 : rettype _ |- _ => destruct mc\u03c4\n  | _ => progress simplify_option_eq\n  | _ => case_match\n  end.\nHint Resolve (type_check_sound (V:=val K)) (type_check_sound (V:=ptr K)): core.\nHint Resolve (mapM_type_check_sound (V:=val K)): core.\nHint Immediate (path_type_check_sound (R:=ref_seg _)): core.\nHint Immediate (path_type_check_sound (R:=ref _)): core.\nHint Immediate unop_type_of_sound binop_type_of_sound: core.\n#[global] Instance:\n  TypeCheckSpec (env K * memenv K) (lrtype K) (lrval K) (\u2713 \u2218 fst).\nProof.\n  intros [\u0393 \u0394] \u03bd \u03c4lr; split.\n  * destruct \u03bd; intros; simplify; typed_constructor; eauto.\n  * by destruct 1; simplify; erewrite ?type_check_complete by eauto.\nQed.\nHint Resolve (type_check_sound (V:=lrval K)): core.\n#[global] Instance: TypeCheckSpec envs (lrtype K) (expr K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] e \u03c4lr; simpl; split.\n  * assert (\u2200 es \u03c3s,\n      Forall (\u03bb e, \u2200 \u03c4lr, type_check (\u0393,\u0394,\u03c4s) e = Some \u03c4lr \u2192\n        (\u0393,\u0394,\u03c4s) \u22a2 e : \u03c4lr) es \u2192\n      mapM (\u03bb e, type_check (\u0393,\u0394,\u03c4s) e \u226b= maybe inr) es = Some \u03c3s \u2192\n      (\u0393,\u0394,\u03c4s) \u22a2* es :* inr <$> \u03c3s).\n    { intros ??. rewrite mapM_Some.\n      induction 2; decompose_Forall_hyps; simplify; constructor; eauto. }\n    revert \u03c4lr; induction e using @expr_ind_alt;\n      intros; simplify; typed_constructor; eauto.\n  * assert (\u2200 es \u03c3s,\n      Forall2 (\u03bb e \u03c4lr, type_check (\u0393,\u0394,\u03c4s) e = Some \u03c4lr) es (inr <$> \u03c3s) \u2192\n      mapM (\u03bb e, type_check (\u0393,\u0394,\u03c4s) e \u226b= maybe inr) es = Some \u03c3s) as help.\n    { intros es \u03c3s. rewrite Forall2_fmap_r, mapM_Some.\n      induction 1; constructor; simplify_option_eq; eauto. }\n    by induction 1 using @expr_typed_ind; simplify_option_eq;\n      erewrite ?type_check_complete, ?path_type_check_complete,\n        ?assign_type_of_complete, ?unop_type_of_complete,\n        ?binop_type_of_complete,?help by eauto; eauto; simplify_option_eq.\nQed.\nHint Resolve (type_check_sound (V:=expr K)): core.\n#[global] Instance: PathTypeCheckSpec envs\n  (lrtype K) (lrtype K) (ectx_item K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] Ei \u03c4lr; simpl; split.\n  * assert (\u2200 es \u03c3s,\n      mapM (\u03bb e, type_check (\u0393,\u0394,\u03c4s) e \u226b= maybe inr) es = Some \u03c3s \u2192\n      (\u0393,\u0394,\u03c4s) \u22a2* es :* inr <$> \u03c3s).\n    { intros es \u03c3s. rewrite mapM_Some. induction 1; simplify; eauto. }\n    destruct \u03c4lr, Ei; intros; simplify; typed_constructor; eauto.\n  * assert (\u2200 es \u03c3s, (\u0393,\u0394,\u03c4s) \u22a2* es :* inr <$> \u03c3s \u2192\n      mapM (\u03bb e, type_check (\u0393,\u0394,\u03c4s) e \u226b= maybe inr) es = Some \u03c3s) as help.\n    { intros es \u03c3s. rewrite Forall2_fmap_r, mapM_Some.\n      induction 1; constructor; erewrite ?type_check_complete by eauto; eauto. }\n    destruct 1; unfold lookupE; fold lookupE; simplify_option_eq;\n      erewrite ?type_check_complete by eauto; simpl;\n      erewrite ?path_type_check_complete, ?assign_type_of_complete,\n        ?unop_type_of_complete, ?binop_type_of_complete by eauto;\n      simplify_option_eq; eauto.\nQed.\nHint Immediate (path_type_check_sound (R:=ectx_item _)): core.\n#[global] Instance: PathTypeCheckSpec envs\n  (lrtype K) (lrtype K) (ectx K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros \u0393s Ei \u03c4lr \u03c4lr'; split.\n  * unfold lookupE. revert \u03c4lr.\n    induction Ei; intros; simplify; typed_constructor; eauto.\n  * unfold lookupE. induction 1; simplify_option_eq;\n      erewrite ?path_type_check_complete by eauto; eauto.\nQed.\nHint Immediate (path_type_check_sound (R:=ectx _)): core.\nLemma rettype_union_alt_sound m\u03c31 m\u03c32 m\u03c3 :\n  rettype_union_alt m\u03c31 m\u03c32 = Some m\u03c3 \u2192 rettype_union m\u03c31 m\u03c32 m\u03c3.\nProof.\n  destruct m\u03c31, m\u03c32; intros; simplify_option_eq; constructor; eauto.\nQed.\nHint Immediate rettype_union_alt_sound: core.\nLemma rettype_union_alt_complete m\u03c31 m\u03c32 m\u03c3 :\n  rettype_union m\u03c31 m\u03c32 m\u03c3 \u2192 rettype_union_alt m\u03c31 m\u03c32 = Some m\u03c3.\nProof. destruct 1 as [[]| |]; simplify_option_eq; eauto. Qed.\n#[global] Instance:\n  TypeCheckSpec envs (rettype K) (stmt K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] s mc\u03c4; simpl; split.\n  * revert \u03c4s mc\u03c4.\n    induction s; intros; simplify; typed_constructor; naive_solver.\n  * induction 1;\n      repeat match goal with\n      | _ : _ \u22a2 ?e : _ |- _ => erewrite (type_check_complete _ e) by eauto\n      | _ => erewrite rettype_union_alt_complete by eauto\n      | _ => progress simplify_option_eq\n      end; eauto.\nQed.\nHint Resolve (type_check_sound (V:=stmt K)): core.\n#[global] Instance: PathTypeCheckSpec envs\n  (type K) (rettype K) (esctx_item K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] Ee \u03c4lr; simpl; split.\n  * unfold lookupE; destruct \u03c4lr, Ee;\n      intros; simplify; typed_constructor; eauto.\n  * destruct 1; simplify_option_eq;\n      erewrite ?type_check_complete by eauto; simplify_option_eq;\n      erewrite ?rettype_union_alt_complete by eauto; eauto.\nQed.\nHint Immediate (path_type_check_sound (R:=esctx_item _)): core.\n#[global] Instance: PathTypeCheckSpec envs\n  (rettype K) (rettype K) (sctx_item K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] Es mc\u03c4; simpl; split.\n  * destruct mc\u03c4, Es; intros; simplify; typed_constructor; eauto.\n  * destruct 1; simplify_option_eq;\n      erewrite ?type_check_complete by eauto; simplify_option_eq;\n      erewrite ?rettype_union_alt_complete by eauto; eauto.\nQed.\nHint Immediate (path_type_check_sound (R:=sctx_item _)): core.\n#[global] Instance: PathTypeCheckSpec envs\n  (focustype K) (focustype K) (ctx_item K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] Ek \u03c4f; simpl; split.\n  * unfold lookupE; destruct \u03c4f, Ek; intros; simplify;\n      try match goal with\n      | |- context [CParams _ ?o\u03c3s] => is_var o\u03c3s; rewrite <-(zip_fst_snd o\u03c3s)\n      end; typed_constructor; eauto.\n  * destruct 1;\n      repeat match goal with\n      | _ => simpl; erewrite fst_zip, snd_zip\n         by eauto using Nat.eq_le_incl, Forall2_length, eq_sym\n      | _ => progress simplify_option_eq\n      | _ => erewrite type_check_complete by eauto\n      | _ => erewrite path_type_check_complete by eauto\n      end; eauto.\nQed.\n#[global] Instance:\n  TypeCheckSpec envs (focustype K) (focus K) (\u2713 \u2218 fst \u2218 fst).\nProof.\n  intros [[\u0393 \u0394] \u03c4s] \u03c6 \u03c4f; simpl; split.\n  * unfold type_check; destruct \u03c6, \u03c4f;\n      intros; simplify; repeat typed_constructor; eauto.\n  * destruct 1;\n      repeat match goal with\n      | _ => progress simplify_option_eq\n      | _ => case_match; typed_inversion_all\n      | _ => erewrite mapM_type_check_complete by eauto\n      | _ => erewrite type_check_complete by eauto\n      | _ => erewrite path_type_check_complete by eauto\n      end; eauto.\nQed.\nEnd properties.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/core_c/type_system_decidable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.19322384669782297}}
{"text": "Require Import POCS.\nRequire Import TwoDiskAPI.\nRequire Import TwoDiskBaseAPI.\n\n\nModule TwoDisk (b : TwoDiskBaseAPI) <: TwoDiskAPI.\n\n  Definition init := b.init.\n  Definition read := b.read.\n  Definition write := b.write.\n  Definition size := b.size.\n  Definition recover:= b.recover.\n\n  Definition abstr := b.abstr.\n\n  Ltac inv_step :=\n    match goal with\n    | [ H: op_step _ _ _ _ |- _ ] =>\n      inversion H; subst; clear H;\n      repeat sigT_eq;\n      safe_intuition\n    end.\n\n  Ltac inv_bg :=\n    match goal with\n    | [ H: bg_failure _ _ |- _ ] =>\n      inversion H; subst; clear H\n    end.\n\n  Theorem maybe_holds_stable : forall state state' F0 F1 i,\n    get_disk (other i) state ?|= F0 ->\n    get_disk i state ?|= F1 ->\n    bg_failure state state' ->\n    get_disk (other i) state' ?|= F0 /\\\n    get_disk i state' ?|= F1.\n  Proof.\n    intros.\n    destruct i; inv_bg; simpl in *; eauto.\n  Qed.\n\n  Ltac cleanup :=\n    repeat match goal with\n           | [ |- forall _, _ ] => intros\n           | |- _ /\\ _ => split; [ solve [ eauto || congruence ] | ]\n           | |- _ /\\ _ => split; [ | solve [ eauto || congruence ] ]\n           | [ H: Working _ = Working _ |- _ ] => inversion H; subst; clear H\n           | [ H: bg_failure _ _ |- _ ] =>\n             eapply maybe_holds_stable in H;\n             [ | solve [ eauto ] | solve [ eauto ] ]; destruct_ands\n           | [ H: _ ?|= eq _, H': _ = Some _ |- _ ] =>\n                    pose proof (holds_some_inv_eq _ H' H); clear H\n           | [ H: ?A * ?B |- _ ] => destruct H\n           | [ H: DiskResult _ |- _ ] => destruct H\n           | _ => deex\n           | _ => destruct_tuple\n           | _ => progress unfold pre_step in *\n           | _ => progress autounfold in *\n           | _ => progress simpl in *\n           | _ => progress subst\n           | _ => progress safe_intuition\n           | _ => solve [ eauto ]\n           | _ => congruence\n           | _ => inv_step\n           | H: context[match ?expr with _ => _ end] |- _ =>\n             destruct expr eqn:?; [ | solve [ repeat cleanup ] ]\n           | H: context[match ?expr with _ => _ end] |- _ =>\n             destruct expr eqn:?; [ solve [ repeat cleanup ] | ]\n           end.\n\n  Ltac prim :=\n    intros;\n    eapply proc_spec_weaken; [ eauto | unfold spec_impl ]; eexists;\n    intuition eauto; cleanup;\n    intuition eauto; cleanup.\n\n  Hint Resolve holds_in_some_eq.\n  Hint Resolve holds_in_none_eq.\n  Hint Resolve pred_missing.\n\n  Hint Unfold combined_step.\n\n\n  Theorem init_ok : init_abstraction init recover abstr inited_any.\n  Proof.\n    eauto.\n  Qed.\n\n  Theorem read_ok : forall i a, proc_spec (read_spec i a) (read i a) recover abstr.\n  Proof.\n    unshelve prim; eauto.\n  Qed.\n\n  Ltac destruct_all :=\n    repeat match goal with\n           | _ => solve [ auto ]\n           | [ i: diskId |- _ ] => destruct i\n           | [ |- context[match ?s with\n                         | BothDisks _ _ => _\n                         | OnlyDisk0 _ => _\n                         | OnlyDisk1 _ => _\n                         end] ] => destruct s\n           | _ => simpl in *\n           end.\n\n  Theorem write_ok : forall i a v, proc_spec (write_spec i a v) (write i a v) recover abstr.\n  Proof.\n    unshelve prim; eauto;\n      try solve [ destruct_all ].\n    destruct (le_dec (S a) (diskSize d0)).\n    destruct_all.\n    rewrite diskUpd_oob_noop by omega.\n    destruct_all.\n  Qed.\n\n  Theorem size_ok : forall i, proc_spec (size_spec i) (size i) recover abstr.\n  Proof.\n    unshelve prim.\n    eauto.\n  Qed.\n\n  Theorem recover_noop : rec_noop recover abstr no_wipe.\n  Proof.\n    eauto.\n  Qed.\n\nEnd TwoDisk.\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/TwoDiskImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"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(** Arithmetic and logical operators for the Compcert C and Clight languages *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Ctypes.\n\nSection WITHMEM.\nContext `{Hmem: Mem.MemoryModel}.\n\n(** * Syntax of operators. *)\n\nInductive unary_operation : Type :=\n  | Onotbool : unary_operation          (**r boolean negation ([!] in C) *)\n  | Onotint : unary_operation           (**r integer complement ([~] in C) *)\n  | Oneg : unary_operation.             (**r opposite (unary [-]) *)\n\nInductive binary_operation : Type :=\n  | Oadd : binary_operation             (**r addition (binary [+]) *)\n  | Osub : binary_operation             (**r subtraction (binary [-]) *)\n  | Omul : binary_operation             (**r multiplication (binary [*]) *)\n  | Odiv : binary_operation             (**r division ([/]) *)\n  | Omod : binary_operation             (**r remainder ([%]) *)\n  | Oand : binary_operation             (**r bitwise and ([&]) *)\n  | Oor : binary_operation              (**r bitwise or ([|]) *)\n  | Oxor : binary_operation             (**r bitwise xor ([^]) *)\n  | Oshl : binary_operation             (**r left shift ([<<]) *)\n  | Oshr : binary_operation             (**r right shift ([>>]) *)\n  | Oeq: binary_operation               (**r comparison ([==]) *)\n  | One: binary_operation               (**r comparison ([!=]) *)\n  | Olt: binary_operation               (**r comparison ([<]) *)\n  | Ogt: binary_operation               (**r comparison ([>]) *)\n  | Ole: binary_operation               (**r comparison ([<=]) *)\n  | Oge: binary_operation.              (**r comparison ([>=]) *)\n\nInductive incr_or_decr : Type := Incr | Decr.\n\n(** * Type classification and semantics of operators. *)\n\n(** Most C operators are overloaded (they apply to arguments of various\n  types) and their semantics depend on the types of their arguments.\n  The following [classify_*] functions take as arguments the types\n  of the arguments of an operation.  They return enough information\n  to resolve overloading for this operator applications, such as\n  ``both arguments are floats'', or ``the first is a pointer\n  and the second is an integer''.  This classification is used in the\n  compiler (module [Cshmgen]) to resolve overloading statically.\n\n  The [sem_*] functions below compute the result of an operator\n  application.  Since operators are overloaded, the result depends\n  both on the static types of the arguments and on their run-time values.\n  The corresponding [classify_*] function is first called on the \n  types of the arguments to resolve static overloading.  It is then\n  followed by a case analysis on the values of the arguments. *)\n\n(** ** Casts and truth values *)\n\nInductive classify_cast_cases : Type :=\n  | cast_case_neutral                   (**r int|pointer -> int32|pointer *)\n  | cast_case_i2i (sz2:intsize) (si2:signedness)   (**r int -> int *)\n  | cast_case_f2f (sz2:floatsize)                  (**r float -> float *)\n  | cast_case_i2f (si1:signedness) (sz2:floatsize) (**r int -> float *)\n  | cast_case_f2i (sz2:intsize) (si2:signedness)   (**r float -> int *)\n  | cast_case_f2bool                    (**r float -> bool *)\n  | cast_case_p2bool                    (**r pointer -> bool *)\n  | cast_case_struct (id1: ident) (fld1: fieldlist) (id2: ident) (fld2: fieldlist) (**r struct -> struct *)\n  | cast_case_union (id1: ident) (fld1: fieldlist) (id2: ident) (fld2: fieldlist) (**r union -> union *)\n  | cast_case_void                                 (**r any -> void *)\n  | cast_case_default.\n\nFunction classify_cast (tfrom tto: type) : classify_cast_cases :=\n  match tto, tfrom with\n  | Tint I32 si2 _, (Tint _ _ _ | Tpointer _ _ | Tarray _ _ _ | Tfunction _ _) => cast_case_neutral\n  | Tint IBool _ _, Tfloat _ _ => cast_case_f2bool\n  | Tint IBool _ _, (Tpointer _ _ | Tarray _ _ _ | Tfunction _ _) => cast_case_p2bool\n  | Tint sz2 si2 _, Tint sz1 si1 _ => cast_case_i2i sz2 si2\n  | Tint sz2 si2 _, Tfloat sz1 _ => cast_case_f2i sz2 si2\n  | Tfloat sz2 _, Tfloat sz1 _ => cast_case_f2f sz2\n  | Tfloat sz2 _, Tint sz1 si1 _ => cast_case_i2f si1 sz2\n  | Tpointer _ _, (Tint _ _ _ | Tpointer _ _ | Tarray _ _ _ | Tfunction _ _) => cast_case_neutral\n  | Tstruct id2 fld2 _, Tstruct id1 fld1 _ => cast_case_struct id1 fld1 id2 fld2\n  | Tunion id2 fld2 _, Tunion id1 fld1 _ => cast_case_union id1 fld1 id2 fld2\n  | Tvoid, _ => cast_case_void\n  | _, _ => cast_case_default\n  end.\n\n(** Semantics of casts.  [sem_cast v1 t1 t2 = Some v2] if value [v1],\n  viewed with static type [t1], can be cast to type [t2],\n  resulting in value [v2].  *)\n\nDefinition cast_int_int (sz: intsize) (sg: signedness) (i: int) : int :=\n  match sz, sg with\n  | I8, Signed => Int.sign_ext 8 i\n  | I8, Unsigned => Int.zero_ext 8 i\n  | I16, Signed => Int.sign_ext 16 i\n  | I16, Unsigned => Int.zero_ext 16 i \n  | I32, _ => i\n  | IBool, _ => if Int.eq i Int.zero then Int.zero else Int.one\n  end.\n\nDefinition cast_int_float (si : signedness) (i: int) : float :=\n  match si with\n  | Signed => Float.floatofint i\n  | Unsigned => Float.floatofintu i\n  end.\n\nDefinition cast_float_int (si : signedness) (f: float) : option int :=\n  match si with\n  | Signed => Float.intoffloat f\n  | Unsigned => Float.intuoffloat f\n  end.\n\nDefinition cast_float_float (sz: floatsize) (f: float) : float :=\n  match sz with\n  | F32 => Float.singleoffloat f\n  | F64 => f\n  end.\n\nFunction sem_cast (v: val) (t1 t2: type) : option val :=\n  match classify_cast t1 t2 with\n  | cast_case_neutral =>\n      match v with\n      | Vint _ | Vptr _ _ => Some v\n      | _ => None\n      end\n  | cast_case_i2i sz2 si2 =>\n      match v with\n      | Vint i => Some (Vint (cast_int_int sz2 si2 i))\n      | _ => None\n      end\n  | cast_case_f2f sz2 =>\n      match v with\n      | Vfloat f => Some (Vfloat (cast_float_float sz2 f))\n      | _ => None\n      end\n  | cast_case_i2f si1 sz2 =>\n      match v with\n      | Vint i => Some (Vfloat (cast_float_float sz2 (cast_int_float si1 i)))\n      | _ => None\n      end\n  | cast_case_f2i sz2 si2 =>\n      match v with\n      | Vfloat f =>\n          match cast_float_int si2 f with\n          | Some i => Some (Vint (cast_int_int sz2 si2 i))\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_f2bool =>\n      match v with\n      | Vfloat f =>\n          Some(Vint(if Float.cmp Ceq f Float.zero then Int.zero else Int.one))\n      | _ => None\n      end\n  | cast_case_p2bool =>\n      match v with\n      | Vint i => Some (Vint (cast_int_int IBool Signed i))\n      | Vptr _ _ => Some (Vint Int.one)\n      | _ => None\n      end\n  | cast_case_struct id1 fld1 id2 fld2 =>\n      if ident_eq id1 id2 && fieldlist_eq fld1 fld2 then Some v else None\n  | cast_case_union id1 fld1 id2 fld2 =>\n      if ident_eq id1 id2 && fieldlist_eq fld1 fld2 then Some v else None\n  | cast_case_void =>\n      Some v\n  | cast_case_default =>\n      None\n  end.\n\n(** The following describes types that can be interpreted as a boolean:\n  integers, floats, pointers.  It is used for the semantics of \n  the [!] and [?] operators, as well as the [if], [while], [for] statements. *)\n\nInductive classify_bool_cases : Type :=\n  | bool_case_i                           (**r integer *)\n  | bool_case_f                           (**r float *)\n  | bool_case_p                           (**r pointer *)\n  | bool_default.\n\nDefinition classify_bool (ty: type) : classify_bool_cases :=\n  match typeconv ty with\n  | Tint _ _ _ => bool_case_i\n  | Tpointer _ _ => bool_case_p\n  | Tfloat _ _ => bool_case_f\n  | _ => bool_default\n  end.\n\n(** Interpretation of values as truth values.\n  Non-zero integers, non-zero floats and non-null pointers are\n  considered as true.  The integer zero (which also represents\n  the null pointer) and the float 0.0 are false. *)\n\nFunction bool_val (v: val) (t: type) : option bool :=\n  match classify_bool t with\n  | bool_case_i =>\n      match v with\n      | Vint n => Some (negb (Int.eq n Int.zero))\n      | _ => None\n      end\n  | bool_case_f =>\n      match v with\n      | Vfloat f => Some (negb (Float.cmp Ceq f Float.zero))\n      | _ => None\n      end\n  | bool_case_p =>\n      match v with\n      | Vint n => Some (negb (Int.eq n Int.zero))\n      | Vptr b ofs => Some true\n      | _ => None\n      end\n  | bool_default => None\n  end.\n\n(** Common-sense relation between Boolean value and casting to [_Bool] type. *)\n\nLemma cast_bool_bool_val:\n  forall v t,\n  sem_cast v t (Tint IBool Signed noattr) =\n  match bool_val v t with None => None | Some b => Some(Val.of_bool b) end.\nProof.\n  intros.\n  assert (A: classify_bool t =\n    match t with\n    | Tint _ _ _ => bool_case_i\n    | Tpointer _ _ | Tarray _ _ _ | Tfunction _ _ => bool_case_p\n    | Tfloat _ _ => bool_case_f\n    | _ => bool_default\n    end).\n  unfold classify_bool; destruct t; simpl; auto. destruct i; auto. destruct s; auto.\n\n  unfold bool_val. rewrite A. unfold sem_cast. destruct t; simpl; auto; destruct v; auto.\n  destruct (Int.eq i0 Int.zero); auto. \n  destruct (Float.cmp Ceq f0 Float.zero); auto.\n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \nQed.\n\n(** ** Unary operators *)\n\n(** *** Boolean negation *)\n\nFunction sem_notbool (v: val) (ty: type) : option val :=\n  match classify_bool ty with\n  | bool_case_i =>\n      match v with\n      | Vint n => Some (Val.of_bool (Int.eq n Int.zero))\n      | _ => None\n      end\n  | bool_case_f =>\n      match v with\n      | Vfloat f => Some (Val.of_bool (Float.cmp Ceq f Float.zero))\n      | _ => None\n      end\n  | bool_case_p =>\n      match v with\n      | Vint n => Some (Val.of_bool (Int.eq n Int.zero))\n      | Vptr _ _ => Some Vfalse\n      | _ => None\n      end\n  | bool_default => None\n  end.\n\n(** Common-sense relation between Boolean value and Boolean negation. *)\n\nLemma notbool_bool_val:\n  forall v t,\n  sem_notbool v t =\n  match bool_val v t with None => None | Some b => Some(Val.of_bool (negb b)) end.\nProof.\n  intros. unfold sem_notbool, bool_val. \n  destruct (classify_bool t); auto; destruct v; auto; rewrite negb_involutive; auto.\nQed.\n\n(** *** Opposite *)\n\nInductive classify_neg_cases : Type :=\n  | neg_case_i(s: signedness)              (**r int *)\n  | neg_case_f                             (**r float *)\n  | neg_default.\n\nDefinition classify_neg (ty: type) : classify_neg_cases :=\n  match ty with\n  | Tint I32 Unsigned _ => neg_case_i Unsigned\n  | Tint _ _ _ => neg_case_i Signed\n  | Tfloat _ _ => neg_case_f\n  | _ => neg_default\n  end.\n\nFunction sem_neg (v: val) (ty: type) : option val :=\n  match classify_neg ty with\n  | neg_case_i sg =>\n      match v with\n      | Vint n => Some (Vint (Int.neg n))\n      | _ => None\n      end\n  | neg_case_f =>\n      match v with\n      | Vfloat f => Some (Vfloat (Float.neg f))\n      | _ => None\n      end\n  | neg_default => None\n  end.\n\n(** *** Bitwise complement *)\n\nInductive classify_notint_cases : Type :=\n  | notint_case_i(s: signedness)              (**r int *)\n  | notint_default.\n\nDefinition classify_notint (ty: type) : classify_notint_cases :=\n  match ty with\n  | Tint I32 Unsigned _ => notint_case_i Unsigned\n  | Tint _ _ _ => notint_case_i Signed\n  | _ => notint_default\n  end.\n\nFunction sem_notint (v: val) (ty: type): option val :=\n  match classify_notint ty with\n  | notint_case_i sg =>\n      match v with\n      | Vint n => Some (Vint (Int.xor n Int.mone))\n      | _ => None\n      end\n  | notint_default => None\n  end.\n\n(** ** Binary operators *)\n\n(** For binary operations, the \"usual binary conversions\", adapted to a 32-bit\n  platform, state that:\n- If both arguments are of integer type, an integer operation is performed.\n  For operations that behave differently at unsigned and signed types\n  (e.g. division, modulus, comparisons), the unsigned operation is selected\n  if at least one of the arguments is of type \"unsigned int32\", otherwise\n  the signed operation is performed.\n- If both arguments are of float type, a float operation is performed.\n  We choose to perform all float arithmetic in double precision,\n  even if both arguments are single-precision floats.\n- If one argument has integer type and the other has float type,\n  we convert the integer argument to float, then perform the float operation.\n*)\n\n(** *** Addition *)\n\nInductive classify_add_cases : Type :=\n  | add_case_ii(s: signedness)         (**r int, int *)\n  | add_case_ff                        (**r float, float *)\n  | add_case_if(s: signedness)         (**r int, float *)\n  | add_case_fi(s: signedness)         (**r float, int *)\n  | add_case_pi(ty: type)(a: attr)     (**r pointer, int *)\n  | add_case_ip(ty: type)(a: attr)     (**r int, pointer *)\n  | add_default.\n\nDefinition classify_add (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => add_case_ii Unsigned\n  | Tint _ _ _, Tint I32 Unsigned _ => add_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => add_case_ii Signed\n  | Tfloat _ _, Tfloat _ _ => add_case_ff\n  | Tint _ sg _, Tfloat _ _ => add_case_if sg\n  | Tfloat _ _, Tint _ sg _ => add_case_fi sg\n  | Tpointer ty a, Tint _ _ _ => add_case_pi ty a\n  | Tint _ _ _, Tpointer ty a => add_case_ip ty a\n  | _, _ => add_default\n  end.\n\nFunction sem_add (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_add t1 t2 with \n  | add_case_ii sg =>                   (**r integer addition *)\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.add n1 n2))\n      | _,  _ => None\n      end\n  | add_case_ff =>                      (**r float addition *)\n      match v1, v2 with\n      | Vfloat n1, Vfloat n2 => Some (Vfloat (Float.add n1 n2))\n      | _,  _ => None\n      end\n  | add_case_if sg =>                   (**r int plus float *)\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.add (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | add_case_fi sg =>                   (**r float plus int *)\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.add n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | add_case_pi ty _ =>                 (**r pointer plus integer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vint n2 => \n        Some (Vptr b1 (Int.add ofs1 (Int.mul (Int.repr (sizeof ty)) n2)))\n      | _,  _ => None\n      end   \n  | add_case_ip ty _ =>                 (**r integer plus pointer *)\n      match v1,v2 with\n      | Vint n1, Vptr b2 ofs2 => \n        Some (Vptr b2 (Int.add ofs2 (Int.mul (Int.repr (sizeof ty)) n1)))\n      | _,  _ => None\n      end   \n  | add_default => None\nend.\n\n(** *** Subtraction *)\n\nInductive classify_sub_cases : Type :=\n  | sub_case_ii(s: signedness)          (**r int , int *)\n  | sub_case_ff                         (**r float , float *)\n  | sub_case_if(s: signedness)          (**r int, float *)\n  | sub_case_fi(s: signedness)          (**r float, int *)\n  | sub_case_pi(ty: type)               (**r pointer, int *)\n  | sub_case_pp(ty: type)               (**r pointer, pointer *)\n  | sub_default.\n\nDefinition classify_sub (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => sub_case_ii Unsigned\n  | Tint _ _ _, Tint I32 Unsigned _ => sub_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => sub_case_ii Signed\n  | Tfloat _ _ , Tfloat _ _ => sub_case_ff\n  | Tint _ sg _, Tfloat _ _ => sub_case_if sg\n  | Tfloat _ _, Tint _ sg _ => sub_case_fi sg\n  | Tpointer ty _, Tint _ _ _ => sub_case_pi ty\n  | Tpointer ty _ , Tpointer _ _ => sub_case_pp ty\n  | _ ,_ => sub_default\n  end.\n\nFunction sem_sub (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_sub t1 t2 with\n  | sub_case_ii sg =>            (**r integer subtraction *)\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.sub n1 n2))\n      | _,  _ => None\n      end \n  | sub_case_ff =>               (**r float subtraction *)\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat(Float.sub f1 f2))\n      | _,  _ => None\n      end\n  | sub_case_if sg =>            (**r int minus float *)\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.sub (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | sub_case_fi sg =>            (**r float minus int *)\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.sub n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | sub_case_pi ty =>            (**r pointer minus integer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vint n2 => \n            Some (Vptr b1 (Int.sub ofs1 (Int.mul (Int.repr (sizeof ty)) n2)))\n      | _,  _ => None\n      end\n  | sub_case_pp ty =>          (**r pointer minus pointer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vptr b2 ofs2 =>\n          if zeq b1 b2 then\n            if Int.eq (Int.repr (sizeof ty)) Int.zero then None\n            else Some (Vint (Int.divu (Int.sub ofs1 ofs2) (Int.repr (sizeof ty))))\n          else None\n      | _, _ => None\n      end\n  | sub_default => None\n  end.\n \n(** *** Multiplication *)\n\nInductive classify_mul_cases : Type:=\n  | mul_case_ii(s: signedness) (**r int , int *)\n  | mul_case_ff                (**r float , float *)\n  | mul_case_if(s: signedness) (**r int, float *)\n  | mul_case_fi(s: signedness) (**r float, int *)\n  | mul_default.\n\nDefinition classify_mul (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => mul_case_ii Unsigned\n  | Tint _ _ _, Tint I32 Unsigned _ => mul_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => mul_case_ii Signed\n  | Tfloat _ _ , Tfloat _ _ => mul_case_ff\n  | Tint _ sg _, Tfloat _ _ => mul_case_if sg\n  | Tfloat _ _, Tint _ sg _ => mul_case_fi sg\n  | _,_  => mul_default\nend.\n\nFunction sem_mul (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n match classify_mul t1 t2 with\n  | mul_case_ii sg =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.mul n1 n2))\n      | _,  _ => None\n      end\n  | mul_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat (Float.mul f1 f2))\n      | _,  _ => None\n      end\n  | mul_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.mul (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | mul_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.mul n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | mul_default =>\n      None\nend.\n\n(** *** Division *)\n\nInductive classify_div_cases : Type:=\n  | div_case_ii(s: signedness) (**r int , int *)\n  | div_case_ff                (**r float , float *)\n  | div_case_if(s: signedness) (**r int, float *)\n  | div_case_fi(s: signedness) (**r float, int *)\n  | div_default.\n\nDefinition classify_div (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => div_case_ii Unsigned\n  | Tint _ _ _, Tint I32 Unsigned _ => div_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => div_case_ii Signed\n  | Tfloat _ _ , Tfloat _ _ => div_case_ff\n  | Tint _ sg _, Tfloat _ _ => div_case_if sg\n  | Tfloat _ _, Tint _ sg _ => div_case_fi sg\n  | _,_  => div_default\nend.\n\nFunction sem_div (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n   match classify_div t1 t2 with\n  | div_case_ii Unsigned =>\n      match v1,v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero then None else Some (Vint (Int.divu n1 n2))\n      | _,_ => None\n      end\n  | div_case_ii Signed =>\n      match v1,v2 with\n       | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero\n          || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone\n          then None else Some (Vint(Int.divs n1 n2))\n      | _,_ => None\n      end\n  | div_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat(Float.div f1 f2))\n      | _,  _ => None\n      end \n  | div_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.div (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | div_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.div n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | div_default =>\n      None\nend.\n\n(** *** Integer-only binary operations: modulus, bitwise \"and\", \"or\", and \"xor\" *)\n\nInductive classify_binint_cases : Type:=\n  | binint_case_ii(s: signedness) (**r int , int *)\n  | binint_default.\n\nDefinition classify_binint (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => binint_case_ii Unsigned\n  | Tint _ _ _, Tint I32 Unsigned _ => binint_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => binint_case_ii Signed\n  | _,_  => binint_default\nend.\n\nFunction sem_mod (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii Unsigned =>\n      match v1, v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero then None else Some (Vint (Int.modu n1 n2))\n      | _, _ => None\n      end\n  | binint_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero\n          || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone\n          then None else Some (Vint (Int.mods n1 n2))\n      | _, _ => None\n      end\n  | binint_default =>\n      None\n  end.\n\nFunction sem_and (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.and n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\nFunction sem_or (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.or n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\nFunction sem_xor (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.xor n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\n(** *** Shifts *)\n\nInductive classify_shift_cases : Type:=\n  | shift_case_ii(s: signedness) (**r int , int *)\n  | shift_default.\n\nDefinition classify_shift (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with\n  | Tint I32 Unsigned _, Tint _ _ _ => shift_case_ii Unsigned\n  | Tint _ _ _, Tint _ _ _ => shift_case_ii Signed\n  | _,_  => shift_default\nend.\n\nFunction sem_shl (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_shift t1 t2 with\n  | shift_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 =>\n         if Int.ltu n2 Int.iwordsize then Some (Vint(Int.shl n1 n2)) else None\n      | _, _ => None\n      end\n  | shift_default => None\n  end.\n\nFunction sem_shr (v1: val) (t1: type) (v2: val) (t2: type): option val :=\n  match classify_shift t1 t2 with \n  | shift_case_ii Unsigned =>\n      match v1,v2 with \n      | Vint n1, Vint n2 =>\n          if Int.ltu n2 Int.iwordsize then Some (Vint (Int.shru n1 n2)) else None\n      | _,_ => None\n      end\n   | shift_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1,  Vint n2 =>\n          if Int.ltu n2 Int.iwordsize then Some (Vint (Int.shr n1 n2)) else None\n      | _,  _ => None\n      end\n   | shift_default =>\n      None\n   end.\n\n(** *** Comparisons *)\n\nInductive classify_cmp_cases : Type:=\n  | cmp_case_ii(s: signedness) (**r int, int *)\n  | cmp_case_pp                (**r pointer, pointer *)\n  | cmp_case_ff                (**r float , float *)\n  | cmp_case_if(s: signedness) (**r int, float *)\n  | cmp_case_fi(s: signedness) (**r float, int *)\n  | cmp_default.\n\nDefinition classify_cmp (ty1: type) (ty2: type) :=\n  match typeconv ty1, typeconv ty2 with \n  | Tint I32 Unsigned _ , Tint _ _ _ => cmp_case_ii Unsigned\n  | Tint _ _ _ , Tint I32 Unsigned _ => cmp_case_ii Unsigned\n  | Tint _ _ _ , Tint _ _ _ => cmp_case_ii Signed\n  | Tfloat _ _ , Tfloat _ _ => cmp_case_ff\n  | Tint _ sg _, Tfloat _ _ => cmp_case_if sg\n  | Tfloat _ _, Tint _ sg _ => cmp_case_fi sg\n  | Tpointer _ _ , Tpointer _ _ => cmp_case_pp\n  | Tpointer _ _ , Tint _ _ _ => cmp_case_pp\n  | Tint _ _ _, Tpointer _ _ => cmp_case_pp\n  | _ , _ => cmp_default\n  end.\n\nFunction sem_cmp (c:comparison)\n                  (v1: val) (t1: type) (v2: val) (t2: type)\n                  (m: mem): option val :=\n  match classify_cmp t1 t2 with\n  | cmp_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmp c n1 n2))\n      | _,  _ => None\n      end\n  | cmp_case_ii Unsigned =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmpu c n1 n2))\n      | _,  _ => None\n      end\n  | cmp_case_pp =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmpu c n1 n2))\n      | Vptr b1 ofs1,  Vptr b2 ofs2  =>\n          if zeq b1 b2 then\n            if Mem.weak_valid_pointer m b1 (Int.unsigned ofs1)\n               && Mem.weak_valid_pointer m b2 (Int.unsigned ofs2)\n            then Some (Val.of_bool (Int.cmpu c ofs1 ofs2))\n            else None\n          else\n            if Mem.valid_pointer m b1 (Int.unsigned ofs1)\n               && Mem.valid_pointer m b2 (Int.unsigned ofs2)\n            then option_map Val.of_bool (Val.cmp_different_blocks c)\n            else None\n      | Vptr b ofs, Vint n =>\n          if Int.eq n Int.zero\n          then option_map Val.of_bool (Val.cmp_different_blocks c)\n          else None\n      | Vint n, Vptr b ofs =>\n          if Int.eq n Int.zero\n          then option_map Val.of_bool (Val.cmp_different_blocks c)\n          else None\n      | _,  _ => None\n      end\n  | cmp_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Val.of_bool (Float.cmp c f1 f2))  \n      | _,  _ => None\n      end\n  | cmp_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Val.of_bool (Float.cmp c (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | cmp_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Val.of_bool (Float.cmp c n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | cmp_default => None\n  end.\n\n(** ** Function applications *)\n\nInductive classify_fun_cases : Type:=\n  | fun_case_f (targs: typelist) (tres: type) (**r (pointer to) function *)\n  | fun_default.\n\nDefinition classify_fun (ty: type) :=\n  match ty with \n  | Tfunction args res => fun_case_f args res\n  | Tpointer (Tfunction args res) _ => fun_case_f args res\n  | _ => fun_default\n  end.\n\n(** * Combined semantics of unary and binary operators *)\n\nDefinition sem_unary_operation\n            (op: unary_operation) (v: val) (ty: type): option val :=\n  match op with\n  | Onotbool => sem_notbool v ty\n  | Onotint => sem_notint v ty\n  | Oneg => sem_neg v ty\n  end.\n\nDefinition sem_binary_operation\n    (op: binary_operation)\n    (v1: val) (t1: type) (v2: val) (t2:type)\n    (m: mem): option val :=\n  match op with\n  | Oadd => sem_add v1 t1 v2 t2\n  | Osub => sem_sub v1 t1 v2 t2 \n  | Omul => sem_mul v1 t1 v2 t2\n  | Omod => sem_mod v1 t1 v2 t2\n  | Odiv => sem_div v1 t1 v2 t2 \n  | Oand => sem_and v1 t1 v2 t2\n  | Oor  => sem_or v1 t1 v2 t2\n  | Oxor  => sem_xor v1 t1 v2 t2\n  | Oshl => sem_shl v1 t1 v2 t2\n  | Oshr  => sem_shr v1 t1 v2 t2   \n  | Oeq => sem_cmp Ceq v1 t1 v2 t2 m\n  | One => sem_cmp Cne v1 t1 v2 t2 m\n  | Olt => sem_cmp Clt v1 t1 v2 t2 m\n  | Ogt => sem_cmp Cgt v1 t1 v2 t2 m\n  | Ole => sem_cmp Cle v1 t1 v2 t2 m\n  | Oge => sem_cmp Cge v1 t1 v2 t2 m\n  end.\n\nDefinition sem_incrdecr (id: incr_or_decr) (v: val) (ty: type) :=\n  match id with\n  | Incr => sem_add v ty (Vint Int.one) type_int32s\n  | Decr => sem_sub v ty (Vint Int.one) type_int32s\n  end.\n\nEnd WITHMEM.\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/cfrontend/Cop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris_logrel.F_mu_ref_conc Require Import logrel_binary.\nFrom iris.algebra Require Import gmap dec_agree.\nFrom iris.base_logic Require Import auth.\nImport uPred.\n\nDefinition stackUR : ucmraT := gmapUR loc (dec_agreeR val).\n\nLemma stackR_self_op (h : stackUR) : h \u2261 h \u22c5 h.\nProof.\n  intros i. rewrite lookup_op.\n  match goal with\n    |- ?A \u2261 ?B \u22c5 ?B => change B with A; destruct A as [c|]\n  end; trivial.\n  destruct c as [c|]; cbv -[equiv decide];\n    try destruct decide; trivial; tauto.\nQed.\n\nClass stackG \u03a3 :=\n  StackG { stack_inG :> authG \u03a3 stackUR; stack_name : gname }.\n\nSection Rules.\n  Context `{stackG \u03a3}.\n  Notation D := (prodC valC valC -n> iProp \u03a3).\n\n  Definition stack_mapsto (l : loc) (v: val) : iProp \u03a3 :=\n    auth_own stack_name {[ l := DecAgree v ]}.\n\n  Notation \"l \u21a6\u02e2\u1d57\u1d4f v\" := (stack_mapsto l v) (at level 20) : uPred_scope.\n\n  Lemma stack_mapsto_dup l v : l \u21a6\u02e2\u1d57\u1d4f v \u22a2 l \u21a6\u02e2\u1d57\u1d4f v \u2217 l \u21a6\u02e2\u1d57\u1d4f v.\n  Proof.\n    by rewrite /stack_mapsto /auth_own -own_op -auth_frag_op -stackR_self_op.\n  Qed.\n\n  Lemma stack_mapstos_agree l v w:\n    l \u21a6\u02e2\u1d57\u1d4f v \u2217 l \u21a6\u02e2\u1d57\u1d4f w \u22a2 l \u21a6\u02e2\u1d57\u1d4f v \u2217 l \u21a6\u02e2\u1d57\u1d4f w \u2227 v = w.\n  Proof.\n    iIntros \"H\".\n    rewrite -own_op.\n    iDestruct (own_valid _ with \"H\") as %Hvalid.\n    rewrite own_op. unfold stack_mapsto, auth_own.\n    iDestruct \"H\" as \"[$ $]\".\n    specialize (Hvalid l). rewrite lookup_op ?lookup_singleton in Hvalid.\n    cbv -[decide] in Hvalid; destruct decide; trivial.\n  Qed.\n\n  Program Definition StackLink_pre (Q : D) : D -n> D := \u03bbne P v,\n    (\u2203 l w, v.1 = LocV l \u2217 l \u21a6\u02e2\u1d57\u1d4f w \u2217\n            ((w = InjLV UnitV \u2227 v.2 = FoldV (InjLV UnitV)) \u2228\n            (\u2203 y1 z1 y2 z2, w = InjRV (PairV y1 (FoldV z1)) \u2217\n              v.2 = FoldV (InjRV (PairV y2 z2)) \u2217 Q (y1, y2) \u2217 \u25b7 P(z1, z2))))%I.\n  Solve Obligations with solve_proper.\n\n  Global Instance StackLink_pre_contractive Q : Contractive (StackLink_pre Q).\n  Proof.\n    intros n P1 P2 HP v; simpl. repeat (apply exist_ne => ?).\n    repeat apply sep_ne; trivial. rewrite or_ne; trivial.\n    repeat (apply exist_ne => ?).\n    repeat apply sep_ne; trivial.\n    apply later_contractive => i ?. by apply HP.\n  Qed.\n\n  Definition StackLink Q := fixpoint (StackLink_pre Q).\n\n  Lemma StackLink_unfold Q v :\n    StackLink Q v \u2261 (\u2203 l w,\n      v.1 = LocV l \u2217 l \u21a6\u02e2\u1d57\u1d4f w \u2217\n      ((w = InjLV UnitV \u2227 v.2 = FoldV (InjLV UnitV)) \u2228\n      (\u2203 y1 z1 y2 z2, w = InjRV (PairV y1 (FoldV z1))\n                      \u2217 v.2 = FoldV (InjRV (PairV y2 z2))\n                      \u2217 Q (y1, y2) \u2217 \u25b7 @StackLink Q (z1, z2))))%I.\n  Proof. by rewrite {1}/StackLink fixpoint_unfold. Qed.\n\n  Global Opaque StackLink. (* So that we can only use the unfold above. *)\n\n  Lemma StackLink_dup (Q : D) v `{\u2200 vw, PersistentP (Q vw)} :\n    StackLink Q v \u22a2 StackLink Q v \u2217 StackLink Q v.\n  Proof.\n    iIntros \"H\". iL\u00f6b as \"Hlat\" forall (v). rewrite StackLink_unfold.\n    iDestruct \"H\" as (l w) \"[% [Hl Hr]]\"; subst.\n    iDestruct (stack_mapsto_dup with \"[Hl]\") as \"[Hl1 Hl2]\"; first eauto.\n    iDestruct \"Hr\" as \"[#Hr|Hr]\".\n    { iSplitL \"Hl1\".\n      - iExists _, _; iFrame \"Hl1\"; eauto.\n      - iExists _, _; iFrame \"Hl2\"; eauto. }\n    iDestruct \"Hr\" as (y1 z1 y2 z2) \"[#H1 [#H2 [#HQ H']]]\".\n    rewrite later_forall; setoid_rewrite later_wand.\n    iDestruct (\"Hlat\" $! (z1, z2) with \"H'\") as \"[HS1 HS2]\".\n    iSplitL \"Hl1 HS1\".\n    - iExists _, _; iFrame \"Hl1\"; eauto 10.\n    - iExists _, _; iFrame \"Hl2\"; eauto 10.\n  Qed.\n\n  Lemma stackR_valid (h : stackUR) (i : loc) :\n    \u2713 h \u2192 h !! i = None \u2228 \u2203 v, h !! i = Some (DecAgree v).\n  Proof.\n    intros Hh; specialize (Hh i).\n    by match type of Hh with\n      \u2713 ?A => match goal with\n             | |- ?B = _ \u2228 (\u2203 _, ?C = _) =>\n               change B with A; change C with A;\n                 destruct A as [[c|]|]; inversion H; eauto\n             end\n    end.\n  Qed.\n\n  Lemma stackR_alloc (h : stackUR) (i : loc) (v : val) :\n    h !! i = None \u2192 \u25cf h ~~> \u25cf (<[i := DecAgree v]> h) \u22c5 \u25ef {[i := DecAgree v]}.\n  Proof.\n    intros H1; apply cmra_total_update.\n    intros n z H2. rewrite (insert_singleton_op h); auto.\n    destruct z as [[ze |] zo];\n      unfold validN, cmra_validN in *; simpl in *; trivial.\n    destruct H2 as [H21 H22]; split.\n    - revert H21; rewrite !left_id. apply cmra_monoN_l.\n    - intros j. rewrite lookup_op.\n      destruct (decide (i = j)) as [|Hneq]; subst.\n      + rewrite H1. rewrite lookup_singleton. constructor.\n      + rewrite lookup_singleton_ne; trivial.\n        specialize (H22 j).\n        revert H22.\n        match goal with\n          |- \u2713{_} ?B \u2192 \u2713{_} (_ \u22c5 ?A) =>\n          change B with A; destruct A; by try constructor\n        end.\n  Qed.\n\n  Lemma dec_agree_valid_op_eq (x y : dec_agreeR val) :\n    \u2713 (Some x \u22c5 Some y) \u2192 x = y.\n  Proof.\n    intros H1.\n    destruct x as [x|]; destruct y as [y|]; trivial;\n      cbv -[decide] in H1; try destruct decide; subst; simpl; intuition trivial.\n  Qed.\n\n  Lemma stackR_auth_is_subheap (h h' : stackUR) :\n    \u2713 (\u25cf h \u22c5 \u25ef h') \u2192 \u2200 i x, h' !! i = Some x \u2192 h !! i = Some x.\n  Proof.\n    intros H1 i x H2.\n    destruct H1 as [H11 H12]; simpl in H11.\n    specialize (H11 1).\n    destruct H11 as [z H11].\n    revert H11; rewrite ucmra_unit_left_id => H11.\n    eapply cmra_extend in H11; [| by apply cmra_valid_validN].\n    destruct H11 as (z1 & z2 & H31 & H32 & H33); simpl in *.\n    specialize (H32 i).\n    assert (H4 : \u2713 (z1 \u22c5 z2))by (by rewrite -H31).\n    apply leibniz_equiv.\n    rewrite H31. rewrite lookup_op.\n    specialize (H4 i). rewrite ?lookup_op in H4.\n    revert H32; rewrite H2 => H32.\n    match type of H32 with\n      ?C \u2261{_}\u2261 _ =>\n      match goal with\n        |- ?A \u22c5 ?B \u2261 _ =>\n        change C with A in *; destruct A as [a|]; inversion H32; subst\n      end\n    end.\n    match type of H32 with\n      ?C \u2261{_}\u2261 _ =>\n      match goal with\n        |- ?A \u22c5 ?B \u2261 _ => destruct B\n      end\n    end.\n    - set (H5 := dec_agree_valid_op_eq _ _ H4); clearbody H5. subst.\n      inversion H3; subst.\n      destruct x as [x|]; cbv -[decide]; try destruct decide;\n        constructor; intuition trivial.\n    - inversion H3; subst. constructor; trivial.\n  Qed.\n\n  Context {iI : heapIG \u03a3}.\n\n  Definition stack_owns (h : stackUR) :=\n    (own stack_name (\u25cf h)\n        \u2217 [\u2217 map] l \u21a6 v \u2208 h, match v with\n                             | DecAgree v' => l \u21a6\u1d62 v'\n                             | _ => True\n                             end)%I.\n\n  Lemma stack_owns_alloc E h l v :\n    stack_owns h \u2217 l \u21a6\u1d62 v\n      \u22a2 |={E}=> stack_owns (<[l := DecAgree v]> h) \u2217 l \u21a6\u02e2\u1d57\u1d4f v.\n  Proof.\n    iIntros \"[[Hown Hall] Hl]\".\n    iDestruct (own_valid _ with \"Hown\") as \"#Hvalid\".\n    iDestruct (auth_validI _ with \"Hvalid\") as \"[Ha' Hb]\";\n      simpl; iClear \"Hvalid\".\n    iDestruct \"Hb\" as %H1.\n    iDestruct \"Ha'\" as (h') \"Ha'\"; iDestruct \"Ha'\" as %Ha'.\n    rewrite ->(left_id _ _) in Ha'; setoid_subst.\n    specialize (H1 l).\n    match type of H1 with\n      \u2713 ?A => change A with (h' !! l) in H1\n    end.\n    destruct (h' !! l) as [[w|]|] eqn:Heq; inversion H1.\n    - rewrite -{2}(insert_id _ _ _ Heq) -insert_delete.\n      rewrite big_sepM_insert; [|apply lookup_delete_None; auto].\n      iDestruct \"Hall\" as \"[Hl' Hall]\".\n      iExFalso. iApply heap_mapsto_dup_invalid; by iFrame \"Hl Hl'\".\n    - iMod (own_update with \"Hown\") as \"Hown\".\n      by apply stackR_alloc.\n      iDestruct \"Hown\" as \"[Hown Hl']\".\n      iModIntro. iSplitR \"Hl'\"; [|unfold stack_mapsto, auth_own; trivial].\n      iCombine \"Hl\" \"Hall\" as \"Hall\".\n      unfold stack_owns. iFrame \"Hown\".\n      rewrite big_sepM_insert; trivial.\n  Qed.\n\n  Lemma stack_owns_open h l v :\n    stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v\n      \u22a2 own stack_name (\u25cf h)\n           \u2217 ([\u2217 map] l \u21a6 v \u2208 delete l h,\n            match v with\n            | DecAgree v' => l \u21a6\u1d62 v'\n            | DecAgreeBot => True\n            end) \u2217 l \u21a6\u1d62 v \u2217 l \u21a6\u02e2\u1d57\u1d4f v.\n  Proof.\n    iIntros \"[[Hown Hall] Hl]\".\n    unfold stack_mapsto, auth_own.\n    iCombine \"Hown\" \"Hl\" as \"Hown\".\n    iDestruct (own_valid _ with \"Hown\") as %Hvalid.\n    iDestruct \"Hown\" as \"[Hown Hl]\".\n    assert (Heq : h !! l = Some (DecAgree v)).\n    eapply stackR_auth_is_subheap; eauto using lookup_singleton.\n    rewrite -{1}(insert_id _ _ _ Heq) -insert_delete.\n    rewrite big_sepM_insert; [|apply lookup_delete_None; auto].\n    iDestruct \"Hall\" as \"[$ $]\"; by iFrame.\n  Qed.\n\n  Lemma stack_owns_close h l v :\n    own stack_name (\u25cf h)\n       \u2217 ([\u2217 map] l \u21a6 v \u2208 delete l h,\n        match v with\n        | DecAgree v' => l \u21a6\u1d62 v'\n        | DecAgreeBot => True\n        end)\n       \u2217 l \u21a6\u1d62 v \u2217 l \u21a6\u02e2\u1d57\u1d4f v \u22a2 stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v.\n  Proof.\n    iIntros \"[Hown [Hall [Hl Hl']]]\".\n    unfold stack_mapsto, auth_own.\n    iCombine \"Hown\" \"Hl'\" as \"Hown\".\n    iDestruct (own_valid _ with \"Hown\") as %Hvalid.\n    iDestruct \"Hown\" as \"[Hown Hl']\".\n    assert (Heq : h !! l = Some (DecAgree v)).\n    eapply stackR_auth_is_subheap; eauto using lookup_singleton.\n    iCombine \"Hl\" \"Hall\" as \"Hall\".\n    rewrite -(big_sepM_insert (\u03bb l v,\n        match v with\n        | DecAgree v' => (l \u21a6\u1d62 v')%I\n        | DecAgreeBot => True%I\n        end) _ _ (DecAgree v)); eauto using lookup_delete.\n    rewrite insert_delete insert_id; auto using lookup_delete.\n    unfold stack_owns. by iFrame.\n  Qed.\n\n  Lemma stack_owns_open_close h l v :\n    stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v\n      \u22a2 l \u21a6\u1d62 v \u2217 (l \u21a6\u1d62 v -\u2217 (stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v)).\n  Proof.\n    iIntros \"[Howns Hls]\".\n    iDestruct (stack_owns_open with \"[Howns Hls]\") as \"[Hh [Hm [Hl Hls]]]\".\n    { by iFrame \"Howns Hls\". }\n    iFrame \"Hl\". iIntros \"Hl\".\n    iApply stack_owns_close. by iFrame.\n  Qed.\n\n  Lemma stack_owns_later_open_close h l v :\n    \u25b7 stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v\n      \u22a2 \u25b7 (l \u21a6\u1d62 v \u2217 (l \u21a6\u1d62 v -\u2217 (stack_owns h \u2217 l \u21a6\u02e2\u1d57\u1d4f v))).\n  Proof. iIntros \"H\". by iNext; iApply stack_owns_open_close. Qed.\nEnd Rules.\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/examples/stack/stack_rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19319382917512679}}
{"text": "\nAdd LoadPath \"/nfs/users/paulkline/Documents/coqs/protosynth\".\n\nAdd LoadPath \"C:\\Users\\Paul\\Documents\\coqStuff\\protosynth\". \nRequire Import TrueProtoSynth. \nModule example1.\n\nSearchAbout nat.  \nDefinition antivirusVersion := descriptor virusCheckerVersionR. \n\n\nDefinition bankwants := ConsRequestLS (requestItem antivirusVersion (requirement antivirusVersion ( fun (x:(measurementDenote antivirusVersion)) =>  Nat.leb 10 x)) \n)emptyRequestLS. \nDefinition bankPrivacy := EmptyPolicy.\n\nDefinition Tomwants := emptyRequestLS.\nDefinition tomPrivacy := @ConsPolicy antivirusVersion (free antivirusVersion) EmptyPolicy.    \n\nDefinition bankState := mkAppraiserState bankPrivacy bankwants.\nDefinition tomState := mkAttesterState tomPrivacy.\n\nTheorem finishes: exists bankState' tomState', \n((OneProtocolStep bankState,bankState), \n (OneProtocolStep tomState, tomState), nil) \n \u27f1\u27f1 \n ((StopStatement, bankState'), (StopStatement, tomState'), nil).\nProof.\neexists. eexists.\neapply dualmultistep_step. apply dualmultistep_id. apply duLeft.\n(*bank sends first message. prove it finishes *) \nstep. proto.\nstep. unfold proto_handleIsMyTurnToSend. c. simpl. auto.\nstep. c. c. simpl. refl.\nstep. proto.\nstep. unfold proto_handleCantSend. proto.\nstep. unfold proto_handleExistsNextDesire. c. c. refl.\nstep. c. c. refl.\nc. c. c.  refl. nono.\n\neapply dualmultistep_step. apply dualmultistep_id. apply duRight.\n\n(*now tom executes his protocol. *)  \nstep. proto.\nstep. unfold proto_handleNotMyTurnToSend. c. c. c. nono.\nstep. proto.\nstep. proto.\nc. c. c. refl.\n(*tom has received, now he must send. *)\n  \neapply dualmultistep_step. apply dualmultistep_id.\napply duRight.\nstep. proto.\nstep. c. simpl. refl.\nstep. c. c. refl.\nstep. proto.\nstep. c. refl.\nstep. s. c. c. refl.\nstep. c. c. refl. nono.\nstep. c. c. refl.\nstep. c. c. refl.\nc. c. c. refl.\n\n(*now the left side must  receive the measurement *)\neapply dualmultistep_step. apply dualmultistep_id. apply duLeft.\nstep. proto.\nstep. c. c. refl. nono.\nstep. proto.\nc. c. c. refl.\n\n(*Now the left side must send the stop. *)\napply dualmultistep_id. eapply duFinishLeftFirst.\nstep. unfold OneProtocolStep. apply E_ChooseTrue. simpl.\nunblock_dep_elim. simpl. simpl_eq. refl.\nstep. apply E_ChooseFalse.  simpl.  unblock_dep_elim.  simpl.  simpl_eq. refl. \nsimpl.  unblock_dep_elim.  simpl.  simpl_eq.      \nTactic Notation \"ss\" := unblock_dep_elim; simpl; simpl_eq.\nc. proto.  refl.\n\n(* now tom must also go to stop. *)\nstep. proto. unfold proto_handleNotMyTurnToSend. c. c. c. refl.\nQed. \n\nEnd example1.\n\nLemma lemma00 : forall st st' stm x x2 n n', \n(EffectStatement x  >> EndStatement, st, n) \u21d3\u21d3 (SendStatement x2 (getMe st') (notMe (getMe st')) >> stm, st', n') -> False.\nProof. intros. crush.  dep_destruct H. inv H. inv H1. inv H2. inv H1. inv H7. inv H4.\n clear H1. clear H3. clear H2.\n inv H. inv H1. inv H2. inv H1.    \n \n  inv H5. inv H1.              \nLemma lemma0 : forall st st' stm x n n', (proto_handleNotMyTurnToSend st, st, n) \u21d3\u21d3 (SendStatement x (getMe st') (notMe (getMe st')) >> stm, st', n') -> False.\nProof. intros.\ninv H. inv H1.\ninv H2. inv H1.  \n inv H7. inv H4.\n inv H5. inv H4.\ninv H11. inv H8. inv H9. inv H8.\n       \n     \nLemma lemma1 : forall st d n st' n' stm, \nvarSubst (variable toSendMESSAGE) st' = Some (constValue d (measure d)) -> \n(OneProtocolStep st, st, n) \u21d3\u21d3 (SendStatement (variable toSendMESSAGE) (getMe st') (notMe (getMe st')) >> stm,st',n') -> \n(OneProtocolStep st, st, n) \u21d3 (proto_handleIsMyTurnToSend st, st, n).\nProof. intros. inv H0. inv H2.\ninv H3. inv H2.\nexact H2.\n(* need to prove not true. *)\ninv H8. inv H5.\ninv H6. inv H5.\ninv H12.\ninv H9.\ninv H10.\ninv H9. \ninv H12.\ninv H13.\ninv H14.\ninv H13. inv H13.     \ninv H16.\ninv H18.\ninv H19. inv H18.\ninv H25. inv H22.\ninv H20. inv H22.\ninv H31.\ninv H12. inv H26. inv H27.\ninv H26. inv H23. inv H30.       inv H5.  inv H29.          \n\nsubst.       \n\nexact H\ninv ZH2.         \nTheorem privacyiscool : forall st n d stm st' n',\n(OneProtocolStep st, st, n) \u21d3\u21d3 (SendStatement (const (constValue d (measure d))) (getMe st') (notMe (getMe st')) >> stm,st',n') -> \nsnd3 (handleRequest' (getPrivacy st') d) = constValue d (measure d) .\nProof.  intros.\ninv H. \ninv H1.\n\ninv H2.  inv H1. clear H2. \n\ninv H7. inv H2. \ninv H4.  inv H2.\ninv H10.  inv H6. \ninv H8.  inv H6.  inv H6. inv H11.   \n\n(*yes *)\ninv H14.  inv H13. \ninv H15.  inv H13. \n\ninv H20.  inv H17. \ninv H18.  inv H17. clear H18.  clear H15. clear H8. clear H4. \n\ninv H24. inv H4. \ninv H8. inv H4.  simpl  in H4. \ninv H23.  inv H18. \n\nsimpl.  \ninv H2.  \ninv H2.  inv H3. \ninv H1.  inv H1.\n\ninv H4. \ninv H3. \ninv H1.\n\ninv H2.  \ninv H1.  \ninv H. \ninv H1. \nsubst.   subst.  inv H1.  subst.\ninv H2.  subst. \ninv H1.  subst. .\ninv H1.  subst. \ninv H7.  subst.  inv H5.  subst.  inv H6.  subst. \ninv H5.  subst. \ninv H5.  subst.\ninv H12.  subst.\ninv H10. subst. \ninv H11. subst. \ninv H10.  subst.\ninv H17.  subst. \ninv H14. subst.\n\ninv H17. subst. \ninv H15. subst. \ninv H14. subst. \ninv H14. subst.   \n\ninv H15. subst.\ninv H15.  subst.  \ninv H14. subst.\ninv H14. subst. \ninv H15. subst.   \n\ninv H21. subst. \ninv H14.  subst. \ninv H15. subst. \ninv H14. subst.\n\ninv H17.  subst. \ninv H18. subst.\ninv H19.  subst. \ninv H18. subst. \ninv H18. subst.  \ninv H14. subst.\ninv H14. subst.\ninv H14. subst.    \ninv H12.  subst. \ninv H11.  subst. \ninv H4. subst.\ninv H11.  subst. \ninv H11.  subst.  \ninv H4.  subst. \ninv H17.  subst. \nTheorem X : forall  ppApp ppAtt wants , exists STatt' STapp' n', \n( (OneProtocolStep (mkAppraiserState ppApp wants), mkAppraiserState ppApp wants),  \n  (OneProtocolStep (mkAttesterState ppAtt), mkAttesterState ppAtt), nil)  \u27f1\u27f1\n((StopStatement, STapp'), (StopStatement, STatt'), n') .\nProof.  intro. induction ppApp; intros.   \neexists. eexists. exists nil.\nstep.\n(*appraiser makes first move*)\neapply duFinishLeftFirst. \nstep. proto. unfold proto_handleIsMyTurnToSend.   \nproto. \nproto. \nproto.\ndestruct wants. simpl.\nproto. \nproto.  refl.\nc.  c.\n\nproto. destruct r. \nstep. c.  c.  simpl.   refl.\nproto.\nsimpl. \nproto.  \nc.  \nproto.  \nunfold proto_handleCantSend.  step.\nproto.\napply E_ChooseFalse; reflexivity.  c.  simpl.  \nproto. \nLtac proto2 := match goal with \n\n end. proto2.  refl.   proto2; [ proto|].   \nproto.  proto. .  \n (apply dualmultistep_step) || ((eapply dualmultistep_id) ; [constructor|]).\nstep. \neapply dualmultistep_step.   ", "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/Examples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19319382917512679}}
{"text": "Require Import Bool List String.\nRequire Import Lib.CommonTactics Lib.Struct.\nRequire Import Lib.ilist Lib.Word Lib.FMap Lib.StringEq Lib.ListSupport.\nRequire Import Kami.Syntax Kami.Semantics Kami.SemFacts Kami.RefinementFacts Kami.Wf Kami.Inline Kami.InlineFacts.\nRequire Import Program.Equality FunctionalExtensionality.\n\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nLemma notNamesNotIn: forall A l (x: Attribute A), ~ In (attrName x) (namesOf l) -> In x l -> False.\nProof.\n  intros A.\n  induction l; intros.\n  - intuition.\n  - simpl in *.\n    destruct H0; subst.\n    assert (sth: ~ attrName x = attrName x) by intuition.\n    intuition.\n    assert (sth: ~ In (attrName x) (namesOf l)) by intuition.\n    eapply IHl; eauto.\nQed.\n\nSection ActionNoCall.\n  Variable k: Kind.\n  Variable ty: Kind -> Type.\n  Variable aUT: ActionT typeUT k.\n  Variable dm: DefMethT.\n  Variable noCalls: ~ In (attrName dm) (getCallsA aUT).\n\n  Theorem inlineNoCallAction_matches a (aEquiv: ActionEquiv (t1 := ty) a aUT): inlineDm a dm = a.\n  Proof.\n    dependent induction aEquiv; simpl in *; intuition auto.\n    - unfold getBody.\n      case_eq (StringEq.string_eq n (attrName dm)); intros.\n      + apply eq_sym in H3.\n        apply StringEq.string_eq_dec_eq in H3.\n        intuition.\n      + f_equal; extensionality v1.\n        apply H0 with (v2 := tt); intuition auto.\n    - f_equal; extensionality v1.\n      destruct k1'; simpl in *.\n      + eapply H0; eauto.\n      + eapply H0; eauto.\n    - f_equal; extensionality v1.\n      destruct k1'; simpl in *.\n      + eapply H0; eauto.\n      + eapply H0; eauto.\n    - f_equal; extensionality v1.\n      destruct k1'; simpl in *.\n      + eapply H0; eauto.\n      + eapply H0; eauto.\n    - f_equal; intuition.\n    - f_equal.\n      + assert (In (attrName dm) (getCallsA ta2) -> False) by intuition.\n        intuition.\n      + assert (In (attrName dm) (getCallsA fa2 ++ getCallsA (cont2 tt)) -> False) by intuition.\n        assert (In (attrName dm) (getCallsA fa2) -> False) by intuition.\n        intuition.\n      + assert (In (attrName dm) (getCallsA fa2 ++ getCallsA (cont2 tt)) -> False) by intuition.\n        assert (In (attrName dm) (getCallsA (cont2 tt)) -> False) by intuition.\n        extensionality v1.\n        apply (H0 v1 tt H2).\n    - f_equal; auto.\n  Qed.\nEnd ActionNoCall.\n\nSection ActionNoCalls.\n  Variable dms: list DefMethT.\n\n  Theorem inlineNoCallsAction_matches:\n    forall k ty a (aUT: ActionT typeUT k),\n      (forall dm, In dm dms -> In (attrName dm) (getCallsA aUT) -> False) ->\n      ActionEquiv (t1 := ty) a aUT ->\n      fold_left (@inlineDm _ _) dms a = a.\n  Proof.\n    induction dms; simpl in *; intros.\n    - reflexivity.\n    - assert (sth: forall dm, In dm l -> In (attrName dm) (getCallsA aUT) -> False) by\n          (intros; specialize (H dm); intuition).\n      assert (sth2: In (attrName a) (getCallsA aUT) -> False) by\n          (specialize (H a); intuition).\n      specialize (IHl _ _ _ aUT sth H0).\n      pose proof (inlineNoCallAction_matches a sth2 H0) as sth3.\n      rewrite sth3.\n      assumption.\n  Qed.\nEnd ActionNoCalls.\n\nSection MethNoCallsInRules.\n  Variable dms: list DefMethT.\n  Variable r: Attribute (Action Void).\n  Variable rEquiv: forall ty,  ActionEquiv (attrType r ty) (attrType r typeUT).\n  \n  Theorem inlineNoCallsRule_matches:\n    (forall dm, In dm dms -> In (attrName dm) (getCallsA (attrType r typeUT)) -> False) ->\n    fold_left inlineDmToRule dms r = r.\n  Proof.\n    intros.\n    induction dms; simpl in *; intros.\n    - reflexivity.\n    - assert (sth1: In (attrName a) (getCallsA (attrType r typeUT)) -> False)\n        by (specialize (H a); intuition).\n      assert (sth2: forall dm, In dm l -> In (attrName dm) (getCallsA (attrType r typeUT)) ->\n                               False) by (intros; specialize (H dm); intuition).\n      specialize (IHl sth2).\n      rewrite <- IHl at 2; f_equal.\n      unfold inlineDmToRule; simpl; destruct r; simpl in *; f_equal.\n      extensionality ty.\n      rewrite inlineNoCallAction_matches with (aUT := attrType typeUT); auto.\n  Qed.\nEnd MethNoCallsInRules.\n\nSection MethNoCallsInMeths.\n  Variable dms: list DefMethT.\n  Variable r: DefMethT.\n  Variable rEquiv:\n    forall ty (argV1: fullType ty (SyntaxKind (arg (projT1 (attrType r)))))\n           (argV2: fullType typeUT (SyntaxKind (arg (projT1 (attrType r))))),\n      ActionEquiv (projT2 (attrType r) ty argV1)\n                  (projT2 (attrType r) typeUT argV2).\n  \n  Theorem inlineNoCallsMeth_matches:\n    (forall dm, In dm dms ->\n                In (attrName dm) (getCallsA (projT2 (attrType r) typeUT tt)) -> False) ->\n    fold_left inlineDmToDm dms r = r.\n  Proof.\n    intros.\n    induction dms; simpl in *; intros.\n    - reflexivity.\n    - assert (sth1: In (attrName a) (getCallsA (projT2 (attrType r) typeUT tt)) -> False)\n        by (specialize (H a); intuition).\n      assert (sth2: forall dm,\n                      In dm l ->\n                      In (attrName dm) (getCallsA (projT2 (attrType r) typeUT tt)) ->\n                               False) by (intros; specialize (H dm); intuition).\n      specialize (IHl sth2).\n      rewrite <- IHl at 2; f_equal.\n      unfold inlineDmToDm; simpl; destruct r; simpl in *; f_equal.\n      destruct attrType.\n      simpl in *.\n      f_equal.\n      extensionality ty.\n      extensionality argv.\n      pose (tt: fullType typeUT (SyntaxKind (arg x))) as f.\n      pose (argv: fullType ty (SyntaxKind (arg x))) as f0.\n      rewrite inlineNoCallAction_matches with (aUT := m typeUT tt); auto.\n  Qed.\nEnd MethNoCallsInMeths.\n\nSection MethNoCall.\n  Variable dms: list DefMethT.\n  Variable dm: DefMethT.\n  Variable noCallsInDefs: ~ In (attrName dm) (getCallsM dms).\n\n  Theorem inlineNoCallMeths_matches (equiv: forall ty, MethsEquiv ty typeUT dms)\n  : inlineDmToDms dms dm = dms.\n  Proof.\n    generalize dependent dms; clear.\n    intros dms.\n    induction dms; intros; simpl in *.\n    - intuition.\n    - assert (eq': forall ty, MethsEquiv ty typeUT l).\n      { intros.\n        specialize (equiv ty).\n        dependent destruction equiv.\n        assumption.\n      }\n      assert (s1: ~ In (attrName dm) (getCallsA (projT2 (attrType a) typeUT tt))) by intuition.\n      assert (s2: ~ In (attrName dm) (getCallsM l)) by intuition.\n      specialize (IHl s2 eq').  \n      f_equal; try assumption.\n      unfold inlineDmToDm.\n      destruct a; simpl in *.\n      f_equal.\n      destruct attrType.\n      f_equal.\n      simpl in *.\n      extensionality ty'.\n      extensionality arg1.\n      specialize (equiv ty').\n      dependent destruction equiv.\n      specialize (H arg1 tt).\n      eapply inlineNoCallAction_matches; eauto.\n  Qed.\nEnd MethNoCall.\n\nLemma inlineDmToMod_ModEquiv_General:\n  forall m dm ty,\n    ModEquiv ty typeUT m ->\n    ModEquiv ty typeUT (fst (inlineDmToMod m dm)).\nProof.\n  intros.\n  unfold inlineDmToMod.\n  remember (getAttribute _ _) as oattr; destruct oattr; [|auto].\n  simpl in Heqoattr.\n  apply getAttribute_Some_body in Heqoattr.\n  simpl; inversion H.\n  pose proof (proj1 (MethsEquiv_in ty typeUT (getDefsBodies m)) H1 _ Heqoattr).\n  constructor.\n  - apply inlineDmToRules_RulesEquiv; auto.\n  - apply inlineDmToDms_MethsEquiv; auto.\nQed.\n\nSection NoCallsInDefs.\n  Variable m: Modules.\n  Variable noCallsInDefs: forall i, ~ (In i (getCallsM (getDefsBodies m)) /\\ In i (getDefs m)).\n  Variable noDups: NoDup (getDefs m).\n  Variable equiv: forall ty, ModEquiv ty typeUT m.\n  \n  Definition simpleInlineDmToMod (dm: DefMethT) :=\n    Mod (getRegInits m) (inlineDmToRules (getRules m) dm)\n        (getDefsBodies m).\n\n  Lemma getAttribute_notNone:\n    forall A (l: list (Attribute A)) x, NoDup (namesOf l) -> In x l ->\n                                        getAttribute (attrName x) l = Some x.\n  Proof.\n    clear.\n    intros A.\n    induction l; intros; simpl in *.\n    - intuition.\n    - destruct H0; subst; try reflexivity.\n      + case_eq (StringEq.string_eq (attrName x) (attrName x)); intros; try reflexivity.\n        apply eq_sym in H0. apply StringEq.string_eq_dec_neq in H0; intuition.\n      + dependent destruction H.\n        specialize (IHl _ H0 H1).\n        case_eq (StringEq.string_eq (attrName x) (attrName a)); intros; subst.\n        apply eq_sym in H2; apply StringEq.string_eq_dec_eq in H2; intuition.\n        * rewrite <- H2 in H.\n          generalize H H1; clear; intros; exfalso.\n          eapply notNamesNotIn; eauto.\n        * apply eq_sym in H2; apply StringEq.string_eq_dec_neq in H2; intuition.\n  Qed.\n\n  Lemma simpleInlineDmToMod_matches:\n    forall dm, In dm (getDefsBodies m) ->\n               simpleInlineDmToMod dm = fst (inlineDmToMod m (attrName dm)).\n  Proof.\n    intros.\n    unfold inlineDmToMod, simpleInlineDmToMod.\n    rewrite getAttribute_notNone; simpl; auto.\n    f_equal.\n    rewrite inlineNoCallMeths_matches; auto.\n    specialize (noCallsInDefs (attrName dm)); intuition auto.\n    - apply notNamesNotIn in H2; intuition.\n    - intros.\n      specialize (equiv ty).\n      dependent destruction equiv; subst.\n      assumption.\n  Qed.\n\n  Lemma simpleInlineModEquiv dm (notIn: In dm (getDefsBodies m)):\n    forall ty, ModEquiv ty typeUT (simpleInlineDmToMod dm).\n  Proof.\n    rewrite simpleInlineDmToMod_matches; auto; intros.\n    eapply inlineDmToMod_ModEquiv_General; eauto.\n  Qed.\nEnd NoCallsInDefs.\n\nFixpoint simpleInlineDmsToMod m dms :=\n  match dms with\n    | nil => Mod (getRegInits m) (getRules m) (getDefsBodies m)\n    | x :: xs => simpleInlineDmsToMod (simpleInlineDmToMod m x) xs\n  end.\n\nLemma simpleInlineDmsToMod_matches dms:\n  forall m,\n    (forall dm, In dm dms -> In dm (getDefsBodies m)) ->\n    (forall i, ~ (In i (getCallsM (getDefsBodies m)) /\\ In i (getDefs m))) ->\n    NoDup (getDefs m) ->\n    (forall ty, ModEquiv ty typeUT m) ->\n    simpleInlineDmsToMod m dms = fst (inlineDms' m (namesOf dms)).\nProof.\n  unfold simpleInlineDmsToMod.\n  induction dms; intuition; simpl in *.\n  fold (simpleInlineDmsToMod (simpleInlineDmToMod m a) dms).\n  rewrite simpleInlineDmToMod_matches; auto.\n  case_eq (inlineDmToMod m (attrName a)); intros; simpl in *.\n  assert (sth: m0 = simpleInlineDmToMod m a).\n  {\n    rewrite simpleInlineDmToMod_matches; auto.\n    destruct (inlineDmToMod m (attrName a)).\n    inversion H3; subst; simpl.\n    reflexivity.\n  }\n  unfold simpleInlineDmToMod in sth.\n  assert (eq': getDefsBodies m0 = getDefsBodies m).\n  { subst.\n    reflexivity.\n  }\n  specialize (IHdms m0).\n  unfold getDefs in IHdms.\n  rewrite eq' in IHdms.\n  assert (sth2: forall dm, In dm dms -> In dm (getDefsBodies m)) by intuition.\n  fold (simpleInlineDmToMod m a) in sth.\n  specialize (IHdms sth2 H0 H1).\n  assert (sth3: In a (getDefsBodies m)) by (subst; intuition).\n  rewrite sth in *.\n  pose proof (simpleInlineModEquiv H0 H1 H2 a sth3) as sth4.\n  specialize (IHdms sth4).\n  fold (simpleInlineDmsToMod (simpleInlineDmToMod m a) dms) in IHdms.\n  destruct (inlineDms' (simpleInlineDmToMod m a) (namesOf dms)); simpl in *.\n  assumption.\nQed.\n\nLemma commuteInlineDmMeths:\n  forall rs meths,\n    fold_left inlineDmToDms meths rs =\n    map (fun r => fold_left inlineDmToDm meths r) rs.\nProof.\n  induction rs; simpl in *; intros.\n  - induction meths; simpl in *.\n    + reflexivity.\n    + assumption.\n  - specialize (IHrs meths).\n    rewrite <- IHrs.\n    clear IHrs.\n    generalize a rs; clear.\n    induction meths; simpl in *; intros.\n    + reflexivity.\n    + specialize (IHmeths (inlineDmToDm a0 a) (inlineDmToDms rs a)).\n      assumption.\nQed.\n\n\nSection MethNoCalls.\n  Variable dms1 dms2: list DefMethT.\n  Variable notInCalls: forall dm, ~ (In (attrName dm) (getCallsM dms1) /\\ In dm dms2).\n  Theorem inlineNoCallsMeths_matches (equiv: forall ty, MethsEquiv ty typeUT dms1)\n  : fold_left inlineDmToDms dms2 dms1 = dms1.\n  Proof.\n    rewrite commuteInlineDmMeths.\n    induction dms1; simpl in *.\n    - intuition.\n    - f_equal.\n      + clear IHl dms1.\n        assert (sth: forall dm,\n                       ~ (In (attrName dm)\n                             (getCallsA (projT2 (attrType a) typeUT tt)) /\\ In dm dms2))\n          by (intros; specialize (notInCalls dm); intuition).\n        induction dms2; simpl in *.\n        * reflexivity.\n        * assert\n            (sth2:\n               forall (dm: Attribute (sigT MethodT)),\n                 ~ (In (attrName dm) (getCallsA (projT2 (attrType a) typeUT tt) ++ getCallsM l)\n                    /\\ In dm l0)) by\n              (intros; specialize (notInCalls dm); intuition).\n          specialize (IHl0 sth2).\n          assert\n            (sth3:\n               forall dm, ~ (In (attrName dm) (getCallsA (projT2 (attrType a) typeUT tt)) /\\\n                             In dm l0)) by (intros; specialize (sth dm); intuition).\n          specialize (IHl0 sth3).\n          rewrite <- IHl0 at 2.\n          f_equal.\n          assert\n            (sth4:\n               forall dm,\n                 ~ (In (attrName dm) (getCallsA (projT2 (attrType a) typeUT tt))\n                    /\\ a0 = dm)) by (intros; specialize (sth dm); intuition).\n          specialize (sth4 a0).\n          assert (sth5: ~ In (attrName a0) (getCallsA (projT2 (attrType a) typeUT tt))) by\n              intuition.\n          destruct a; unfold inlineDmToDm; simpl in *.\n          f_equal.\n          destruct attrType; simpl in *.\n          f_equal.\n          extensionality ty.\n          extensionality v.\n          specialize (equiv ty).\n          dependent destruction equiv.\n          specialize (H v tt).\n          eapply inlineNoCallAction_matches; eauto.\n      + apply IHl; intros.\n        * specialize (notInCalls dm); intuition.\n        * specialize (equiv ty).\n          dependent destruction equiv.\n          assumption.\n  Qed.\nEnd MethNoCalls.\n\nDefinition inlineDmsInMod m dms :=\n  Mod (getRegInits m) (fold_left inlineDmToRules dms (getRules m))\n      (fold_left inlineDmToDms dms (getDefsBodies m)).\n\nLemma inlineDmsInMod_correct ds:\n  forall m,\n    (forall dm, In dm ds -> In dm (getDefsBodies m)) ->\n    (forall i, ~ (In i (getCallsM (getDefsBodies m)) /\\ In i (getDefs m))) ->\n    NoDup (getDefs m) ->\n    (forall ty, ModEquiv ty typeUT m) ->\n    inlineDmsInMod m ds =\n    fst (inlineDms' m (namesOf ds)).\nProof.\n  intros; rewrite <- simpleInlineDmsToMod_matches; auto.\n  unfold inlineDmsInMod; simpl in *.\n  generalize m H H0 H1 H2; clear.\n  induction ds; intros; simpl in *.\n  - reflexivity.\n  - specialize (IHds (simpleInlineDmToMod m a)).\n    unfold getDefs in IHds; simpl in *.\n    assert (forall dm, In dm ds -> In dm (getDefsBodies m))\n      by (intros;\n          specialize (H dm); intuition).\n    assert (sth: In a (getDefsBodies m)) by (specialize (H a); intuition).\n    specialize (IHds H3 H0 H1 (simpleInlineModEquiv H0 H1 H2 _ sth)).\n    rewrite inlineNoCallMeths_matches; auto.\n\n    assert (sth2: In (attrName a) (getDefs m)).\n    { unfold getDefs.\n      clear - sth.\n      induction (getDefsBodies m).\n      - intuition.\n      - destruct sth; subst; simpl in *.\n        intuition.\n        intuition.\n    }\n    specialize (H0 (attrName a)).\n    intuition.\n    intros.\n    specialize (H2 ty).\n    destruct H2.\n    assumption.\nQed.\n\nDefinition simpleInline m := simpleInlineDmsToMod m (getDefsBodies m).\n\nLemma simpleInline_matches1 m:\n  (forall i, ~ (In i (getCallsM (getDefsBodies m)) /\\ In i (getDefs m))) ->\n  NoDup (getDefs m) ->\n  (forall ty, ModEquiv ty typeUT m) ->\n  simpleInline m = fst (inlineDms m).\nProof.\n  intros.\n  unfold simpleInline, inlineDms.\n  apply simpleInlineDmsToMod_matches; auto.\nQed.\n\nLemma inNamesInList A name (l: list (Attribute A)):\n  In name (namesOf l) ->\n  exists v, In {| attrName := name; attrType := v |} l.\nProof.\n  induction l; intros; simpl in *.\n  - intuition.\n  - destruct a; simpl in *.\n    destruct H; simpl in *; subst.\n    + exists attrType.\n      intuition.\n    + specialize (IHl H); destruct IHl.\n      exists x.\n      right; intuition.\nQed.\n\nLemma simpleInline_matches2 m:\n  (forall dm dmBody, In dm (getDefsBodies m) ->\n                     In dmBody (getDefsBodies m) ->\n                     In (attrName dmBody) (getCallsDm dm) ->\n                     False) ->\n  NoDup (getDefs m) ->\n  (forall ty, ModEquiv ty typeUT m) ->\n  simpleInline m = fst (inlineDms m).\nProof.\n  intros.\n  apply simpleInline_matches1; auto.\n  clear H0 H1; unfold not; intros.\n  destruct H0.\n  unfold getDefs in H1.\n  apply inNamesInList in H1.\n  destruct H1.\n  apply getCallsM_implies_getCallsDm in H0.\n  destruct H0.\n  destruct H0.\n  apply (H _ _ H0 H1 H2).\nQed.\n\nDefinition inlineDmsIn m := inlineDmsInMod m (getDefsBodies m).\n\nLemma inlineDmsIn_matches m:\n  (forall dm dmBody, In dm (getDefsBodies m) ->\n                     In dmBody (getDefsBodies m) ->\n                     In (attrName dmBody) (getCallsDm dm) ->\n                     False) ->\n  NoDup (getDefs m) ->\n  (forall ty, ModEquiv ty typeUT m) ->\n  inlineDmsIn m = fst (inlineDms m).\nProof.\n  intros.\n  unfold inlineDmsIn.\n  rewrite inlineDmsInMod_correct; auto.\n  clear H0 H1; unfold not; intros.\n  destruct H0.\n  unfold getDefs in H1.\n  apply inNamesInList in H1.\n  destruct H1.\n  apply getCallsM_implies_getCallsDm in H0.\n  destruct H0.\n  destruct H0.\n  apply (H _ _ H0 H1 H2).\nQed.\n\nSection AboutFilter.\n  Variable A: Type.\n\n  Lemma filter_app (f: A -> bool) l1 l2:\n    filter f (l1 ++ l2) = filter f l1 ++ filter f l2.\n  Proof.\n    induction l1; simpl in *.\n    - reflexivity.\n    - destruct (f a); simpl; f_equal; auto.\n  Qed.\n  \n  Definition filterA (a dm: Attribute A) :=\n    if string_dec (attrName dm) (attrName a) then false else true.\n\n  Lemma filterA_eq (l: list (Attribute A)) a:\n    ~ In (attrName a) (namesOf l) -> filter (filterA a) l = l.\n  Proof.\n    induction l; simpl in *; intros.\n    - reflexivity.\n    - assert (attrName a0 <> attrName a) by intuition.\n      assert (~ In (attrName a) (namesOf l)) by intuition.\n      case_eq (filterA a a0); intros; try subst; f_equal; auto.\n      unfold filterA in H2.\n      destruct (string_dec (attrName a0) (attrName a)); intuition.\n  Qed.\nEnd AboutFilter.\n\nLemma inlineDmCalls c dm k (a: ActionT typeUT k): In c (getCallsA a) -> c <> (attrName dm) ->\n                                                  In c (getCallsA (inlineDm a dm)).\nProof.\n  induction a; intros; simpl in *; auto.\n  - case_eq (getBody meth dm s); intros; simpl in *; unfold getBody in *.\n    + destruct s0; simpl in *.\n      destruct x; simpl in *.\n      destruct dm; simpl in *.\n      destruct attrType; simpl in *.\n      subst.\n      rewrite getCallsA_appendAction.\n      simpl in *.\n      apply in_or_app.\n      case_eq (string_eq meth attrName0); intros; rewrite H3 in H2.\n      * apply eq_sym in H3; apply string_eq_dec_eq in H3; subst.\n        destruct H0; [intuition|].\n        destruct (SignatureT_dec (projT1 attrType0) s); [| discriminate].\n        inversion H2; clear H2.\n        rewrite <- H4, <- H5.\n        right; apply H; intuition auto.\n      * discriminate.\n    + intuition auto.\n  - apply in_app_or in H0.\n    apply in_or_app.\n    destruct H0; [left; apply IHa1; auto|].\n    right; apply in_or_app.\n    apply in_app_or in H0; destruct H0; [left; apply IHa2; auto|].\n    right; apply H; auto.\nQed.\n\nSection InlineDmsCalls.\n  Variable n : string.\n  Variable r : Attribute (Action Void).\n  Variable HDmInR : In n (getCallsA (attrType r typeUT)).\n\n  Lemma inlineDmsCalls l:\n    ~ In n (namesOf l) ->\n    In n (getCallsA (attrType (fold_right (fun dm' r' => inlineDmToRule r' dm') r l) typeUT)).\n  Proof.\n    induction l; simpl in *; intros; auto.\n    assert (sth1: attrName a <> n) by intuition auto.\n    assert (sth2: ~ In n (namesOf l)) by intuition auto.\n    specialize (IHl sth2).\n    apply inlineDmCalls; auto.\n  Qed.\nEnd InlineDmsCalls.\n  \nSection AboutList.\n  Variable A: Type.\n  Variable ls: list (Attribute A).\n  Variable HNoDup: NoDup (namesOf ls).\n  Variable a: Attribute A.\n  Variable f: A -> A.\n  Variable prefix suffix: list (Attribute A).\n  Variable HIn: ls = prefix ++ a :: suffix.\n\n  Definition attrF x := (attrName x :: f (attrType x))%struct.\n\n  Definition changeA x := if string_dec (attrName a) (attrName x)\n                          then attrF x\n                          else x.\n\n  Lemma aNotInPrefix: ~ In (attrName a) (namesOf prefix).\n  Proof.\n    generalize ls HNoDup HIn.\n    clear ls HNoDup HIn.\n    induction prefix; intros.\n    - intuition.\n    - destruct ls.\n      pose proof (@app_cons_not_nil _ _ _ _ HIn); auto.\n      simpl in HIn.\n      injection HIn; intros.\n      unfold namesOf in HNoDup.\n      simpl in HNoDup.\n      inv HNoDup.\n      apply IHl in H4; auto.\n      unfold not; intros.\n      simpl in H.\n      destruct H; subst.\n      rewrite map_app in H3; simpl in H3.\n      assert (sth: In (attrName a) (map (@attrName _) l ++\n                                        attrName a :: map (@attrName _) suffix)) by\n          (apply in_app_iff; intuition).\n      rewrite H in *.\n      auto.\n      auto.\n  Qed.\n\n  Lemma aNotInSuffix: ~ In (attrName a) (namesOf suffix).\n  Proof.\n    generalize ls HNoDup HIn.\n    clear ls HNoDup HIn.\n    induction prefix; intros.\n    - rewrite app_nil_l in HIn.\n      subst.\n      inv HNoDup.\n      unfold not; intros.\n      intuition.\n    - destruct ls.\n      pose proof (@app_cons_not_nil _ _ _ _ HIn); auto.\n      simpl in HIn.\n      injection HIn; intros.\n      unfold namesOf in HNoDup.\n      simpl in HNoDup.\n      inv HNoDup.\n      apply IHl in H4; auto.\n  Qed.\n\n\n  Lemma mapChangeNotIn: forall l, ~ In (attrName a) (namesOf l) -> map changeA l = l.\n  Proof.\n    clear.\n    induction l; simpl in *; intros.\n    - reflexivity.\n    - assert (attrName a0 <> attrName a) by intuition.\n      assert (~ In (attrName a) (namesOf l)) by intuition.\n      specialize (IHl H1).\n      f_equal; auto.\n      unfold changeA.\n      destruct (string_dec (attrName a) (attrName a0)).\n      apply eq_sym in e; intuition auto.\n      reflexivity.\n  Qed.\n\n  Lemma mapChangePrefix: map changeA prefix = prefix.\n  Proof.\n    apply mapChangeNotIn.\n    apply aNotInPrefix.\n  Qed.\n\n  Lemma mapChangeSuffix: map changeA suffix = suffix.\n  Proof.\n    apply mapChangeNotIn.\n    apply aNotInSuffix.\n  Qed.  \n\n  Lemma map_equiv': map changeA ls = map changeA prefix ++ attrF a :: map changeA suffix.\n  Proof.\n    simpl.\n    assert (sth: changeA a = attrF a) by\n        (unfold changeA; destruct (string_dec (attrName a) (attrName a)); intuition auto).\n    rewrite <- sth.\n    assert (sth2: changeA a :: map changeA suffix = map changeA (a :: suffix)) by reflexivity.\n    rewrite sth2.\n    rewrite <- map_app.\n    f_equal; auto.\n  Qed.\n\n  Lemma map_equiv: map changeA ls = prefix ++ attrF a :: suffix.\n  Proof.\n    rewrite map_equiv'.\n    rewrite mapChangePrefix.\n    rewrite mapChangeSuffix.\n    reflexivity.\n  Qed.\n\n  Lemma filter_equiv: filter (filterA a) ls = prefix ++ suffix.\n  Proof.\n    rewrite HIn.\n    rewrite filter_app.\n    f_equal.\n    apply filterA_eq.\n    apply aNotInPrefix.\n    simpl.\n    unfold filterA.\n    destruct (string_dec (attrName a) (attrName a)); auto.\n    apply filterA_eq.\n    apply aNotInSuffix.\n    tauto.\n  Qed.\nEnd AboutList.\n  \nSection Partial.\n  Variable m: Modules.\n\n  Variable dm: DefMethT. (* a method to be inlined *)\n  Variable preDm sufDm: list DefMethT.\n  Variable Hdm: getDefsBodies m = preDm ++ dm :: sufDm.\n  Hypotheses (HnoDupMeths: NoDup (namesOf (getDefsBodies m))).\n  Variable prefix suffix: list (Attribute (Action Void)).\n  Variable r: Attribute (Action Void). (* a rule calling dm *)\n  Hypothesis Hrule: getRules m = prefix ++ r :: suffix.\n  Hypothesis HnoDupRules: NoDup (namesOf (getRules m)).\n\n  Lemma inDmGetDefsBodies: In dm (getDefsBodies m).\n  Proof.\n    clear - Hdm.\n    rewrite Hdm.\n    apply in_or_app.\n    right; intuition.\n  Qed.\n  \n  Lemma inlineDmToRule_traceRefines_NoFilt:\n    m <<== (Mod (getRegInits m)\n                (prefix ++ inlineDmToRule r dm :: suffix)\n                (getDefsBodies m)).\n  Proof.\n    assert (sth: inlineDmToRule r dm = attrF (fun a type => inlineDm (a type) dm) r) by\n        (unfold inlineDmToRule; reflexivity).\n    rewrite sth.\n    rewrite <- map_equiv with (ls := getRules m); auto.\n    apply inlineDmToRule_traceRefines_1.\n    apply inDmGetDefsBodies; auto.\n    auto.\n  Qed.\n\n  Hypothesis mEquiv: ModEquiv type typeUT m.\n  Hypothesis HdmNoRule: forall r, In r (prefix ++ suffix) ->\n                                  noCallDmSigA (attrType r typeUT) (attrName dm)\n                                               (projT1 (attrType dm)) = true.\n  Hypothesis HdmNoMeth: forall d, In d (getDefsBodies m) ->\n                                  noCallDmSigA (projT2 (attrType d) typeUT tt)\n                                               (attrName dm) (projT1 (attrType dm)) = true.\n  \n  Hypothesis HDmInR: In (attrName dm) (getCallsA (attrType r typeUT)).\n  \n  Lemma inlineDmToRule_traceRefines_Filt:\n    m <<== (Mod (getRegInits m)\n                (prefix ++ inlineDmToRule r dm :: suffix)\n                (preDm ++ sufDm)).\n  Proof.\n    assert (sth: inlineDmToRule r dm = attrF (fun a type => inlineDm (a type) dm) r) by\n        (unfold inlineDmToRule; reflexivity).\n    rewrite sth.\n    rewrite <- map_equiv with (ls := getRules m); auto.\n    assert (sth2: filterDm (getDefsBodies m) (attrName dm) = preDm ++ sufDm).\n    { unfold filterDm.\n      apply filter_equiv; auto.\n    }\n    rewrite <- sth2.\n    apply inlineDmToRule_traceRefines_2; intuition auto.\n    rewrite Hdm; intuition.\n    rewrite Hrule; apply in_or_app; right; intuition.\n    apply HdmNoRule with (r := rule); auto.\n    rewrite Hrule in H.\n    apply in_app_or in H;\n      apply in_or_app; intuition auto.\n    right; simpl in H1; subst; intuition.\n    subst; intuition.\n  Qed.\nEnd Partial.\n\nSection PartialMultiDm.\n  Variable m: Modules.\n  \n  Variable dms: list DefMethT. (* a method to be inlined *)\n  Variable preDm sufDm: list DefMethT.\n  Variable Hdm: getDefsBodies m = preDm ++ dms ++ sufDm.\n  Hypotheses HnoDupMeths: NoDup (namesOf (getDefsBodies m)).\n  Variable prefix suffix: list (Attribute (Action Void)).\n  Variable r: Attribute (Action Void). (* a rule calling dm *)\n  Hypothesis Hrule: getRules m = prefix ++ r :: suffix.\n  Hypothesis HnoDupRules: NoDup (namesOf (getRules m)).\n  \n  Lemma inlineDmsToRule_traceRefines_NoFilt:\n    m <<== (Mod (getRegInits m)\n                (prefix ++ fold_right (fun dm' r' => inlineDmToRule r' dm') r dms :: suffix)\n                (getDefsBodies m)).\n  Proof.\n    generalize dms preDm Hdm.\n    clear dms preDm Hdm.\n    induction dms; simpl in *; intros.\n    - rewrite <- Hrule.\n      apply flatten_traceRefines.\n    - assert (sth: (preDm ++ [a]) ++ l ++ sufDm = preDm ++ a :: l ++ sufDm) by\n          (rewrite <- app_assoc; reflexivity).\n      assert (sth2: getDefsBodies m = (preDm ++ [a]) ++ l ++ sufDm) by\n          (rewrite sth, Hdm; reflexivity).\n      specialize (IHl (preDm ++ a :: nil) sth2).\n      rewrite idElementwiseId in *.\n      match goal with\n        | [H: traceRefines id m ?P |- _] => apply traceRefines_trans with (mb := P); auto\n      end.\n      rewrite <- idElementwiseId.\n      match goal with\n        | [|- ?m <<== _] => pose proof (@inlineDmToRule_traceRefines_NoFilt m a preDm (l ++ sufDm) Hdm HnoDupMeths prefix suffix (fold_right (fun dm' r' => inlineDmToRule r' dm') r l) eq_refl) as sth3; simpl in *\n      end.\n      apply sth3.\n      unfold namesOf in *; rewrite Hrule in HnoDupRules; repeat rewrite map_app in *; simpl in *.\n      assert (sth4: attrName r =\n                    attrName (fold_right (fun dm' r' => inlineDmToRule r' dm') r l)).\n      { clear;\n        induction l; simpl in *; auto.\n      }\n      rewrite <- sth4.\n      assumption.\n  Qed.\n\n  Variable mEquiv: ModEquiv type typeUT m.\n  Hypothesis HdmNoRule: forall r,\n                          In r (prefix ++ suffix) ->\n                          forall dm, In dm dms ->\n                                     noCallDmSigA (attrType r typeUT) (attrName dm)\n                                                  (projT1 (attrType dm)) = true.\n  Hypothesis HdmNoMeth:\n    forall d,\n      In d (getDefsBodies m) ->\n      forall dm, In dm dms ->\n                 noCallDmSigA (projT2 (attrType d) typeUT tt)\n                              (attrName dm) (projT1 (attrType dm)) = true.\n\n  Hypothesis HDmsInR: forall dm, In dm dms -> In (attrName dm) (getCallsA (attrType r typeUT)).\n\n  Lemma NoDup_app_rm A: forall (l1 l2 l3: list A), NoDup (l1 ++ l2 ++ l3) -> NoDup (l1 ++ l3).\n  Proof.\n    clear.\n    intros.\n    rewrite <- app_nil_r in H.\n    rewrite <- app_assoc in H.\n    apply NoDup_app_comm_ext in H.\n    rewrite app_assoc in H.\n    rewrite app_nil_r in H.\n    rewrite app_assoc in H.\n    apply NoDup_app_1 in H.\n    auto.\n  Qed.\n\n  Lemma inlineDmsToRule_traceRefines_Filt:\n    m <<== (Mod (getRegInits m)\n                (prefix ++ fold_right (fun dm' r' => inlineDmToRule r' dm') r dms :: suffix)\n                (preDm ++ sufDm)).\n  Proof.\n    generalize dms preDm Hdm HdmNoRule HdmNoMeth HDmsInR.\n    clear dms preDm Hdm HdmNoRule HdmNoMeth HDmsInR.\n    induction dms; simpl in *; intros.\n    - rewrite <- Hrule.\n      rewrite <- Hdm.\n      apply flatten_traceRefines.\n    - assert (sth: (preDm ++ [a]) ++ l ++ sufDm = preDm ++ a :: l ++ sufDm) by\n          (rewrite <- app_assoc; reflexivity).\n      assert (sth1: (preDm ++ [a]) ++ sufDm = preDm ++ a :: sufDm) by\n          (rewrite <- app_assoc; reflexivity).\n      assert (sth2: getDefsBodies m = (preDm ++ [a]) ++ l ++ sufDm) by\n          (rewrite sth, Hdm; reflexivity).\n      assert (sth3: forall r0, In r0 (prefix ++ suffix) ->\n                               forall dm, In dm l ->\n                                     noCallDmSigA (attrType r0 typeUT) (attrName dm)\n                                                  (projT1 (attrType dm)) = true)\n        by (intros; apply HdmNoRule; auto).\n      assert (HDmsInR1: forall dm, In dm l -> In (attrName dm) (getCallsA (attrType r typeUT)))\n        by (intros; apply HDmsInR; auto).\n      assert (HDmsInR2: In (attrName a) (getCallsA (attrType r typeUT)))\n        by (intros; apply HDmsInR; auto).\n      assert (sth4:\n                forall d, In d (getDefsBodies m) ->\n                          forall dm, In dm l ->\n                                     noCallDmSigA (projT2 (attrType d) typeUT tt)\n                                                  (attrName dm) (projT1 (attrType dm)) = true)\n        by (intros; apply HdmNoMeth; auto).\n      specialize (IHl (preDm ++ [a]) sth2 sth3 sth4 HDmsInR1); clear sth3 sth4.\n      rewrite idElementwiseId in *.\n      match goal with\n        | [H: traceRefines id m ?P |- _] => apply traceRefines_trans with (mb := P); auto\n      end.\n      rewrite <- idElementwiseId.\n      assert (sth3: NoDup (namesOf ((preDm ++ [a]) ++ sufDm))).\n      { unfold namesOf; repeat rewrite map_app.\n        apply NoDup_app_rm with (l2 := map (@attrName _) l).\n        repeat rewrite <- map_app.\n        rewrite <- sth2.\n        assumption.\n      } \n      match goal with\n        | [|- ?m <<== _] =>\n          pose proof (@inlineDmToRule_traceRefines_Filt\n                        m a preDm sufDm sth1 sth3\n                        prefix suffix (fold_right (fun dm' r' => inlineDmToRule r' dm') r l)\n                        eq_refl) as sth4; simpl in *\n      end.\n      apply sth4; auto.\n      unfold namesOf in *; rewrite Hrule in HnoDupRules; repeat rewrite map_app in *; simpl in *.\n      assert (sth5: attrName r =\n                    attrName (fold_right (fun dm' r' => inlineDmToRule r' dm') r l)).\n      { clear;\n        induction l; simpl in *; auto.\n      }\n      rewrite <- sth5.\n      assumption.\n      destruct mEquiv as [rEquiv dmEquiv].\n      rewrite Hrule in rEquiv; rewrite Hdm in dmEquiv.\n      pose proof (proj1 (RulesEquiv_in _ _ _) rEquiv) as rEquiv'; clear rEquiv.\n      pose proof (proj1 (MethsEquiv_in _ _ _) dmEquiv) as dEquiv'; clear dmEquiv.\n      constructor; simpl in *.\n      apply RulesEquiv_in; intros.\n      apply in_app_or in H; simpl in *.\n      destruct H; [apply rEquiv'; apply in_or_app; auto|].\n      destruct H; [|apply rEquiv'; apply in_or_app; auto].\n      assert (sth9: RuleEquiv type typeUT r) by (apply rEquiv'; apply in_or_app; intuition).\n      assert (sth10: forall x, In x l -> MethEquiv type typeUT x).\n      { intros; apply dEquiv'; apply in_or_app; simpl; right; right;\n        apply in_or_app; left; auto.\n      }\n      clear - H sth9 sth10.\n      { subst.\n        generalize sth10; clear sth10.\n        induction l; simpl in *; intros; auto.\n        assert (forall x, In x l -> MethEquiv type typeUT x) by (intros; apply sth10; auto).\n        assert (MethEquiv type typeUT a) by (apply sth10; auto).\n        specialize (IHl H).\n        unfold inlineDmToRule at 1; unfold RuleEquiv in *; simpl in *.\n        apply inlineDm_ActionEquiv; auto.\n      } \n      intuition.\n      apply MethsEquiv_in; intros.\n      repeat (apply in_app_or in H; destruct H);\n        (apply dEquiv'; apply in_or_app; intuition auto).\n      right; simpl in *; intuition auto.\n      right; right; apply in_or_app; intuition auto.\n      intros; apply HdmNoMeth; auto.\n      rewrite sth2.\n      repeat (try apply in_app_or in H; try apply in_or_app; try destruct H; intuition auto).\n      right; apply in_or_app; right; auto.\n      rewrite Hdm in HnoDupMeths.\n      clear - HnoDupMeths HDmsInR2.\n      unfold namesOf in *.\n      rewrite map_app in *; simpl in *.\n      apply NoDup_app_2 in HnoDupMeths; simpl in *.\n      pose proof HnoDupMeths as sth.\n      dependent destruction sth.\n      clear HnoDupMeths.\n      rewrite map_app in *; simpl in *.\n      assert (sth2: ~ In (attrName a) (map (@attrName _) l)).\n      { unfold not; intros.\n        assert (In (attrName a) (map (@attrName _) l ++ map (@attrName _) sufDm))\n          by (apply in_or_app; intuition auto).\n        intuition auto.\n      }\n      destruct a as [n nt]; simpl in *.\n      clear - sth2 HDmsInR2.\n      apply inlineDmsCalls; auto.\n  Qed.\nEnd PartialMultiDm.\n\nSection PartialMultiR.\n  Variable m: Modules.\n\n  Variable dm: DefMethT. (* a method to be inlined *)\n  Variable preDm sufDm: list DefMethT.\n  Variable Hdm: getDefsBodies m = preDm ++ dm :: sufDm.\n  Hypotheses HnoDupMeths: NoDup (namesOf (getDefsBodies m)).\n  Hypothesis HnoDupRules: NoDup (namesOf (getRules m)).\n  Variable rs: list (Attribute (Action Void)). (* a rule calling dm *)\n  Variable prefix suffix: list (Attribute (Action Void)).\n  Hypothesis Hrule: getRules m = prefix ++ rs ++ suffix.\n  \n  Lemma inlineDmToRules_traceRefines_NoFilt:\n    m <<==\n      (Mod (getRegInits m)\n           (prefix ++ map (fun r => inlineDmToRule r dm) rs ++ suffix)\n           (getDefsBodies m)).\n  Proof.\n    generalize rs prefix suffix Hrule.\n    clear rs prefix suffix Hrule.\n    induction rs; simpl in *; intros.\n    - rewrite <- Hrule.\n      apply flatten_traceRefines.\n    - assert (sth: (prefix ++ [a]) ++ l ++ suffix = prefix ++ a :: l ++ suffix) by\n          (rewrite <- app_assoc; reflexivity).\n      assert (sth2: getRules m = (prefix ++ [a]) ++ l ++ suffix) by\n          (rewrite sth, Hrule; reflexivity).\n      specialize (IHl (prefix ++ [a]) suffix sth2).\n      rewrite idElementwiseId in *.\n      match goal with\n        | [H: traceRefines id m ?P |- _] => apply traceRefines_trans with (mb := P); auto\n      end.\n      rewrite <- idElementwiseId.\n      rewrite <- app_assoc with (m := [a]); simpl.\n      match goal with\n        | |- ?m2 <<== _ =>\n          assert (sth1: getRegInits m = getRegInits m2) by reflexivity;\n            rewrite sth1 at 2; clear sth1\n      end.\n      match goal with\n        | [|- ?m <<== _] =>\n          pose proof (@inlineDmToRule_traceRefines_NoFilt\n                        m dm preDm sufDm Hdm HnoDupMeths prefix\n                        (map (fun r => inlineDmToRule r dm) l ++\n                             suffix) a eq_refl) as sth3; simpl in *\n      end.\n      apply sth3.\n      rewrite Hrule in HnoDupRules; clear - HnoDupRules.\n      unfold namesOf in *; repeat rewrite map_app in *; simpl in *.\n      assert (sth: map (@attrName _)\n                       (map (fun r => inlineDmToRule r dm) l)\n                   = map (@attrName _) l).\n      { clear.\n        induction l; simpl in *; intros.\n        - reflexivity.\n        - f_equal; auto.\n      }\n      rewrite map_app in *; simpl in *.\n      rewrite sth.\n      assumption.\n  Qed.\nEnd PartialMultiR.\n\nLemma inlineDmToRule_preserveName r l:\n  attrName\n    (fold_right\n       (fun dm' r' =>\n          inlineDmToRule r' dm') r l) = attrName r.\nProof.\n  induction l; simpl in *; auto.\nQed.\n\nSection PartialMultiR2.\n  Variable m: Modules.\n  Variable mEquiv: forall ty, ModEquiv ty typeUT m.\n\n  Variable dm: DefMethT. (* a method to be inlined *)\n  Variable preDm sufDm: list DefMethT.\n  Variable Hdm: getDefsBodies m = preDm ++ dm :: sufDm.\n  Hypotheses HnoDupMeths: NoDup (namesOf (getDefsBodies m)).\n  Hypothesis HnoDupRules: NoDup (namesOf (getRules m)).\n  Variable rs: list (Attribute (Action Void)). (* a rule calling dm *)\n  Variable prefix suffix: list (Attribute (Action Void)).\n  Hypothesis Hrule: getRules m = prefix ++ rs ++ suffix.\n  \n  Hypothesis HdmNoRule: forall r,\n                          In r (prefix ++ suffix) ->\n                          noCallDmSigA (attrType r typeUT) (attrName dm)\n                                       (projT1 (attrType dm)) = true.\n\n  Hypothesis HdmNoMeth:\n    forall d,\n      In d (getDefsBodies m) ->\n      noCallDmSigA (projT2 (attrType d) typeUT tt)\n                   (attrName dm) (projT1 (attrType dm)) = true.\n\n  Hypothesis HDmsInRs: exists r, In r rs /\\\n                                 In (attrName dm) (getCallsA (attrType r typeUT)).\n\n  Lemma inlineDmToRules_traceRefines_Filt:\n    m <<==\n      (Mod (getRegInits m)\n           (prefix ++ map (fun r => inlineDmToRule r dm) rs ++ suffix)\n           (preDm ++ sufDm)).\n  Proof.\n    destruct HDmsInRs as [r [InRRs InDmCallsR]]; clear HDmsInRs.\n    generalize rs prefix Hrule r InRRs InDmCallsR HdmNoRule.\n    clear rs prefix Hrule HdmNoRule r InRRs InDmCallsR.\n    induction rs; simpl in *; intros; [intuition auto | ].\n    destruct (in_dec string_dec (attrName dm) (getCallsA (attrType a typeUT))) as [isIn| notIn].\n    - match goal with\n        | |- _ <<== Mod ?regs (?pre ++ inlineDmToRule ?r dm :: ?rest) _ =>\n          apply traceRefines_trans with (mb := Mod regs ((pre ++ [r]) ++ rest)\n                                                   (getDefsBodies m))\n      end.\n      assert (sth: (fun f: MethsT => f) = id) by (extensionality f; reflexivity); rewrite sth.\n      unfold MethsT; rewrite <- idElementwiseId.\n      apply inlineDmToRules_traceRefines_NoFilt with (preDm := preDm) (sufDm := sufDm); auto.\n      rewrite <- app_assoc; simpl; auto.\n      rewrite <- app_assoc; simpl.\n      match goal with\n        | |- ?m2 <<== _ =>\n          assert (sth1: getRegInits m = getRegInits m2) by reflexivity;\n            rewrite sth1 at 2; clear sth1\n      end.\n      apply inlineDmToRule_traceRefines_Filt; auto; simpl in *.\n      rewrite Hrule in HnoDupRules; clear - HnoDupRules.\n      unfold namesOf in *; repeat rewrite map_app in *; simpl in *.\n      assert (sth: map (@attrName _)\n                       (map (fun r => inlineDmToRule r dm) l)\n                   = map (@attrName _) l).\n      { clear.\n        induction l; simpl in *; intros.\n        - reflexivity.\n        - f_equal; auto.\n      }\n      rewrite map_app in *; simpl in *.\n      rewrite sth.\n      assumption.\n      destruct (mEquiv type).\n      constructor; simpl in *; auto.\n      pose proof ((proj1 (RulesEquiv_in _ _ (getRules m))) H) as rEquiv; clear H.\n      apply RulesEquiv_in; simpl in *; intros.\n      rewrite Hrule in rEquiv.\n      apply in_app_or in H; simpl in *; destruct H;[\n        apply rEquiv; apply in_or_app; simpl; intuition auto|].\n      destruct H; [subst; apply rEquiv; apply in_or_app; simpl; intuition auto|].\n      apply in_app_or in H; destruct H;\n      [|\n       apply rEquiv; apply in_or_app; simpl; right; right; apply in_or_app; intuition auto].\n      assert (forall r0, In r0 l -> RuleEquiv type typeUT r0) by\n          (intros; apply rEquiv; apply in_or_app; right; right;\n           apply in_or_app; left; intuition auto).\n      apply in_map_iff in H; dest; subst.\n      specialize (H1 x H2).\n      pose proof ((proj1 (MethsEquiv_in _ _ (getDefsBodies m))) H0) as dEquiv; clear H0.\n      rewrite Hdm in dEquiv.\n      assert (MethEquiv type typeUT dm) by (apply dEquiv; apply in_or_app; right; left;\n                                            intuition auto).\n      apply inlineDm_ActionEquiv; auto.\n\n      intros.\n      apply in_app_or in H.\n      destruct H; [apply HdmNoRule; apply in_or_app; intuition auto|].\n      apply in_app_or in H.\n      destruct H; [|apply HdmNoRule; apply in_or_app; intuition auto].\n      apply in_map_iff in H; dest; subst.\n      apply inlineDmToRule_noCallDmSigA; auto.\n      apply HdmNoMeth; auto.\n      rewrite Hdm; apply in_or_app; simpl; intuition auto.\n    - destruct InRRs; subst.\n      match goal with\n        | |- _ <<== Mod ?regs (?pre ++ inlineDmToRule ?r dm :: ?rest) _ =>\n          apply traceRefines_trans with (mb := Mod regs ((pre ++ [r]) ++ rest)\n                                                   (getDefsBodies m))\n      end.\n      assert (sth: (fun f: MethsT => f) = id) by (extensionality f; reflexivity); rewrite sth.\n      unfold MethsT; rewrite <- idElementwiseId.\n      apply inlineDmToRules_traceRefines_NoFilt with (preDm := preDm) (sufDm := sufDm); auto.\n      rewrite <- app_assoc; simpl; auto.\n      rewrite <- app_assoc; simpl.\n      match goal with\n        | |- ?m2 <<== _ =>\n          assert (sth1: getRegInits m = getRegInits m2) by reflexivity;\n            rewrite sth1 at 2; clear sth1\n      end.\n      apply inlineDmToRule_traceRefines_Filt; auto; simpl in *.\n      rewrite Hrule in HnoDupRules; clear - HnoDupRules.\n      unfold namesOf in *; repeat rewrite map_app in *; simpl in *.\n      assert (sth: map (@attrName _)\n                       (map (fun r => inlineDmToRule r dm) l)\n                   = map (@attrName _) l).\n      { clear.\n        induction l; simpl in *; intros.\n        - reflexivity.\n        - f_equal; auto.\n      }\n      rewrite map_app in *; simpl in *.\n      rewrite sth.\n      assumption.\n      destruct (mEquiv type).\n      constructor; simpl in *; auto.\n      pose proof ((proj1 (RulesEquiv_in _ _ (getRules m))) H) as rEquiv; clear H.\n      apply RulesEquiv_in; simpl in *; intros.\n      rewrite Hrule in rEquiv.\n      apply in_app_or in H; simpl in *; destruct H;[\n        apply rEquiv; apply in_or_app; simpl; intuition auto|].\n      destruct H; [subst; apply rEquiv; apply in_or_app; simpl; intuition auto|].\n      apply in_app_or in H; destruct H;\n      [|\n       apply rEquiv; apply in_or_app; simpl; right; right; apply in_or_app; intuition auto].\n      assert (forall r0, In r0 l -> RuleEquiv type typeUT r0) by\n          (intros; apply rEquiv; apply in_or_app; right; right;\n           apply in_or_app; left; intuition auto).\n      apply in_map_iff in H; dest; subst.\n      specialize (H1 x H2).\n      pose proof ((proj1 (MethsEquiv_in _ _ (getDefsBodies m))) H0) as dEquiv; clear H0.\n      rewrite Hdm in dEquiv.\n      assert (MethEquiv type typeUT dm) by (apply dEquiv; apply in_or_app; right; left;\n                                            intuition auto).\n      apply inlineDm_ActionEquiv; auto.\n\n\n      assert (sth: (prefix ++ [a]) ++ l ++ suffix = prefix ++ a :: l ++ suffix) by\n          (rewrite <- app_assoc; reflexivity).\n      rewrite <- sth in Hrule.\n      specialize (IHl _ Hrule _ H InDmCallsR).\n      repeat rewrite <- app_assoc in IHl; simpl in IHl.\n      assert (forall r, In r (prefix ++ a :: suffix) ->\n                        noCallDmSigA (attrType r typeUT) (attrName dm) (projT1 (attrType dm)) =\n                        true).\n      { intros.\n        apply in_app_or in H0; simpl in *.\n        destruct H0.\n        - apply HdmNoRule.\n          apply in_or_app; intuition auto.\n        - destruct H0; subst.\n          * apply noCalls_noCallDmSigATrue; auto.\n          * apply HdmNoRule.\n            apply in_or_app; intuition auto.\n      }\n      specialize (IHl H0).\n      apply traceRefines_trans with (mb := Mod (getRegInits m)\n                                               (prefix ++\n                                                       a :: map (fun r => inlineDmToRule r dm) l\n                                                       ++ suffix) (preDm ++ sufDm)).\n      assert (sth2: (fun f: MethsT => f) = id) by (extensionality f; reflexivity); rewrite sth2.\n      unfold MethsT; rewrite <- idElementwiseId; auto.\n      assert (sth2: inlineDmToRule a dm = a).\n      { unfold inlineDmToRule.\n        assert (sth1: In a (getRules m)) by\n            (rewrite Hrule; apply in_or_app; left; apply in_or_app;\n             right; simpl; intuition auto).\n        destruct a; simpl in *; f_equal.\n        extensionality ty; simpl in *.\n        destruct (mEquiv ty).\n        pose proof (proj1 (RulesEquiv_in _ _ (getRules m)) H1 (attrName :: attrType)%struct\n                          sth1) as sth2.\n        unfold RuleEquiv in sth2; simpl in sth2.\n        apply inlineNoCallAction_matches with (aUT := attrType typeUT); auto.\n      }\n      rewrite idElementwiseId.\n      rewrite sth2.\n      apply traceRefines_refl.\n  Qed.\nEnd PartialMultiR2.\n\nSection inlineDmToRule_hasInCalls.\n  Variable a: DefMethT.\n  Variable r: Attribute (Action Void).\n  Variable inaR: In (attrName a) (getCallsA (attrType r typeUT)).\n  Variable l: list DefMethT.\n  Variable notAL: ~ In (attrName a) (namesOf l).\n  \n  Lemma inlineDmToRule_hasInCalls:\n    In (attrName a)\n       (getCallsA\n          (attrType\n             (fold_right\n                (fun dm' r' =>\n                   inlineDmToRule r' dm') r l) typeUT)).\n  Proof.\n    induction l; simpl in *; auto.\n    assert (attrName a0 <> attrName a) by intuition.\n    assert (~ In (attrName a) (namesOf l0)) by intuition.\n    specialize (IHl0 H0).\n    apply inlineDmCalls; auto.\n  Qed.\nEnd inlineDmToRule_hasInCalls.\n\nSection rEquivAfterInline.\n  Variable ty: Kind -> Type.\n  Variable ls: list DefMethT.\n\n  Lemma inlineDmsToRule_Equiv r:\n    RuleEquiv ty typeUT r ->\n    (forall d, In d ls -> MethEquiv ty typeUT d) ->\n    RuleEquiv ty typeUT\n              (fold_right\n                 (fun dm' r' => inlineDmToRule r' dm') r ls).\n  Proof.\n    intro rEquiv; induction ls; simpl in *; auto; intros.\n    assert (sth1: MethEquiv ty typeUT a) by (apply H; auto).\n    assert (sth2: forall d, In d l -> MethEquiv ty typeUT d) by (intros; apply H; auto).\n    specialize (IHl sth2).\n    apply inlineDm_ActionEquiv; auto.\n  Qed.\nEnd rEquivAfterInline.\n  \nSection PartialMultiDmMultiR.\n  Variable m: Modules.\n\n  Variable dms: list DefMethT. (* a method to be inlined *)\n  Variable preDm sufDm: list DefMethT.\n  Variable Hdm: getDefsBodies m = preDm ++ dms ++ sufDm.\n  Hypotheses HnoDupMeths: NoDup (namesOf (getDefsBodies m)).\n  Hypothesis HnoDupRules: NoDup (namesOf (getRules m)).\n  Variable rs: list (Attribute (Action Void)). (* a rule calling dm *)\n  Variable prefix suffix: list (Attribute (Action Void)).\n  Hypothesis Hrule: getRules m = prefix ++ rs ++ suffix.\n  \n  Lemma inlineDmsToRules_traceRefines_NoFilt:\n    m <<==\n      (Mod (getRegInits m)\n           (prefix ++ map (fun r => fold_right (fun dm' r' => inlineDmToRule r' dm') r dms) rs ++ suffix)\n           (getDefsBodies m)).\n  Proof.\n    generalize rs prefix suffix Hrule.\n    clear rs prefix suffix Hrule.\n    induction rs; simpl in *; intros.\n    - rewrite <- Hrule.\n      apply flatten_traceRefines.\n    - assert (sth: (prefix ++ [a]) ++ l ++ suffix = prefix ++ a :: l ++ suffix) by\n          (rewrite <- app_assoc; reflexivity).\n      assert (sth2: getRules m = (prefix ++ [a]) ++ l ++ suffix) by\n          (rewrite sth, Hrule; reflexivity).\n      specialize (IHl (prefix ++ [a]) suffix sth2).\n      rewrite idElementwiseId in *.\n      match goal with\n        | [H: traceRefines id m ?P |- _] => apply traceRefines_trans with (mb := P); auto\n      end.\n      rewrite <- idElementwiseId.\n      match goal with\n        | [|- ?m <<== _] =>\n          pose proof (@inlineDmsToRule_traceRefines_NoFilt\n                        m dms preDm sufDm Hdm HnoDupMeths prefix\n                        (map (fun r =>\n                                fold_right (fun dm' r' => inlineDmToRule r' dm') r dms) l ++\n                             suffix) a) as sth3; simpl in *\n      end.\n      apply sth3.\n      rewrite <- app_assoc.\n      f_equal.\n      rewrite sth2 in HnoDupRules; clear - HnoDupRules.\n      unfold namesOf in *; repeat rewrite map_app in *; simpl in *.\n      assert (sth: map (@attrName _)\n                       (map (fun r => fold_right (fun dm' r' =>\n                                                    inlineDmToRule r' dm') r dms) l)\n                   = map (@attrName _) l).\n      { clear.\n        induction l; simpl in *; intros.\n        - reflexivity.\n        - f_equal.\n          + clear.\n            induction dms; simpl in *; intros.\n            * reflexivity.\n            * assumption.\n          + assumption.\n      }\n      rewrite sth.\n      assumption.\n  Qed.\n\n  Hypothesis mEquiv: forall t, ModEquiv t typeUT m.\n\n  Hypothesis HdmNoRule: forall r,\n                          In r (prefix ++ suffix) ->\n                          forall dm, In dm dms ->\n                                     noCallDmSigA (attrType r typeUT) (attrName dm)\n                                                  (projT1 (attrType dm)) = true.\n\n  Hypothesis HdmNoMeth:\n    forall d,\n      In d (getDefsBodies m) ->\n      forall dm, In dm dms ->\n                 noCallDmSigA (projT2 (attrType d) typeUT tt)\n                              (attrName dm) (projT1 (attrType dm)) = true.\n\n  Hypothesis HDmsInRs: forall dm,\n                         In dm dms ->\n                         exists r, In r rs /\\\n                                   In (attrName dm) (getCallsA (attrType r typeUT)).\n\n  Lemma inlineDmsToRules_traceRefines_Filt:\n    m <<==\n      (Mod (getRegInits m)\n           (prefix ++ map (fun r => fold_right (fun dm' r' => inlineDmToRule r' dm') r dms) rs ++ suffix)\n           (preDm ++ sufDm)).\n  Proof.\n    generalize dms preDm Hdm HdmNoMeth HdmNoRule HDmsInRs.\n    clear dms preDm Hdm HdmNoMeth HdmNoRule HDmsInRs.\n    induction dms; simpl in *; intros.\n    - assert (sth: (fun r: Attribute (Action Void) => r) = id) by\n          (extensionality r; reflexivity).\n      rewrite sth.\n      rewrite map_id.\n      rewrite <- Hrule.\n      rewrite <- Hdm.\n      apply flatten_traceRefines.\n    - assert (HdmNoMeth1:\n                forall d,\n                  In d (getDefsBodies m) ->\n                  forall dm,\n                    In dm l ->\n                    noCallDmSigA (projT2 (attrType d) typeUT tt)\n                                 (attrName dm) (projT1 (attrType dm)) = true)\n        by (intros; apply HdmNoMeth; auto).\n      assert (HdmNoMeth2: forall d, In d (getDefsBodies m) ->\n                                    noCallDmSigA (projT2 (attrType d) typeUT tt)\n                                                 (attrName a) (projT1 (attrType a)) = true)\n        by (intros; apply HdmNoMeth; auto).\n      clear HdmNoMeth.\n      assert (HdmNoRule1:\n                forall r : Attribute (Action Void),\n                  In r (prefix ++ suffix) ->\n                  forall dm : DefMethT,\n                    In dm l ->\n                    noCallDmSigA (attrType r typeUT) (attrName dm)\n                                 (projT1 (attrType dm)) = true)\n        by (intros; apply HdmNoRule; auto).\n      assert (HdmNoRule2:\n                forall r : Attribute (Action Void),\n                  In r (prefix ++ suffix) ->\n                  noCallDmSigA (attrType r typeUT) (attrName a)\n                               (projT1 (attrType a)) = true)\n        by (intros; apply HdmNoRule; auto).\n      clear HdmNoRule.\n      assert (HDmsInRs1:\n                forall dm,\n                  In dm l ->\n                  exists r, In r rs /\\ In (attrName dm) (getCallsA (attrType r typeUT)))\n        by (intros; apply HDmsInRs; auto).\n      assert (HDmsInRs2:\n                exists r, In r rs /\\ In (attrName a) (getCallsA (attrType r typeUT)))\n        by (intros; apply HDmsInRs; auto).\n      clear HDmsInRs.\n      assert (sth: (preDm ++ [a]) ++ l ++ sufDm = preDm ++ a :: l ++ sufDm)\n        by (rewrite <- app_assoc; simpl; reflexivity).\n      rewrite <- sth in *.\n      specialize (IHl _ Hdm HdmNoMeth1 HdmNoRule1 HDmsInRs1).\n      rewrite <- app_assoc in IHl; simpl in IHl.\n      match goal with\n        | H: m <<== ?m2 |- _ => apply traceRefines_trans with (mb := m2)\n      end.\n      assert (sth2: (fun f: MethsT => f) = id) by (extensionality f; reflexivity).\n      rewrite sth2.\n      unfold MethsT; rewrite <- idElementwiseId.\n      auto.\n      match goal with\n        | |- ?m2 <<== _ => assert (sth2: getRegInits m = getRegInits m2) by reflexivity;\n            rewrite sth2 at 2\n      end.\n      rewrite <- map_map with (g := fun r => inlineDmToRule r a).\n      apply inlineDmToRules_traceRefines_Filt; simpl in *; auto.\n      + intros.\n        specialize (mEquiv ty).\n        destruct mEquiv as [rEquiv dEquiv].\n        rewrite sth in Hdm.\n        rewrite Hrule in rEquiv.\n        rewrite Hdm in dEquiv.\n        pose proof (proj1 (RulesEquiv_in _ _ _) rEquiv) as rEquiv'; clear rEquiv.\n        pose proof (proj1 (MethsEquiv_in _ _ _) dEquiv) as dEquiv'; clear dEquiv.\n        constructor; simpl in *.\n        * apply RulesEquiv_in; intros.\n          apply in_app_or in H.\n          destruct H; [apply rEquiv'; apply in_or_app; left; intuition auto|].\n          apply in_app_or in H.\n          destruct H;\n            [| apply rEquiv'; apply in_or_app; right; apply in_or_app; right; intuition auto].\n          assert (sth4: forall r, In r rs -> RuleEquiv ty typeUT r)\n            by (intros; apply rEquiv'; apply in_or_app; right; apply in_or_app; left;\n                intuition auto).\n          apply in_map_iff in H; dest; subst.\n          specialize (sth4 _ H0).\n          assert (sth5: forall m, In m l -> MethEquiv ty typeUT m)\n            by (intros; apply dEquiv'; apply in_or_app; simpl; right; right; apply in_or_app;\n                left; intuition auto).\n          apply inlineDmsToRule_Equiv; auto.\n        * apply MethsEquiv_in; intros.\n          apply dEquiv'.\n          apply in_or_app.\n          apply in_app_or in H.\n          destruct H; [left; intuition auto|].\n          right; simpl in *.\n          destruct H; [left; intuition auto|].\n          right; apply in_or_app.\n          intuition auto.\n      + rewrite Hdm in HnoDupMeths; clear - HnoDupMeths.\n        unfold namesOf in *.\n        repeat (rewrite map_app in *; simpl in *).\n        rewrite <- app_nil_r in HnoDupMeths.\n        rewrite <- app_assoc with (n := nil) in HnoDupMeths.\n        apply NoDup_app_comm_ext in HnoDupMeths.\n        rewrite app_nil_r in HnoDupMeths.\n        rewrite app_assoc in HnoDupMeths.\n        apply NoDup_app_1 in HnoDupMeths.\n        rewrite <- app_assoc in HnoDupMeths; simpl in *.\n        assumption.\n      + rewrite Hrule in HnoDupRules; clear - HnoDupRules.\n        unfold namesOf in *; repeat (rewrite map_app in *; simpl in *).\n        rewrite map_map.\n        match goal with\n          | H: NoDup (_ ++ ?l ++ _) |- NoDup (_ ++ ?x ++ _) =>\n            assert (sth: x = l)\n        end.\n        (f_equal;\n         extensionality x;\n         apply inlineDmToRule_preserveName).\n        rewrite sth; auto.\n      + intros.\n        rewrite sth in Hdm.\n        rewrite Hdm in HdmNoMeth2.\n        apply in_app_or in H; simpl in *.\n        apply HdmNoMeth2; auto.\n        apply in_or_app; simpl in *.\n        intuition auto.\n        right; right; apply in_or_app; auto.\n      + destruct HDmsInRs2 as [r [inR inaR]].\n        remember (fun x => fold_right (fun dm' r' => inlineDmToRule r' dm') x l) as f.\n        exists (f r).\n        constructor.\n        apply in_map; auto.\n        rewrite Heqf.\n        apply inlineDmToRule_hasInCalls; auto.\n        rewrite sth in Hdm.\n        rewrite Hdm in HnoDupMeths.\n        clear - HnoDupMeths.\n        unfold namesOf in *.\n        rewrite map_app in *.\n        apply NoDup_app_2 in HnoDupMeths; simpl in *.\n        rewrite map_app in *.\n        pose proof HnoDupMeths as sth; clear HnoDupMeths.\n        dependent destruction sth; clear sth.\n        unfold not; intros.\n        assert (In (attrName a) (map (@attrName _) l ++ map (@attrName _) sufDm))\n          by (apply in_or_app; left; auto).\n        intuition auto.\n  Qed.\nEnd PartialMultiDmMultiR.\n\nSection rsEquivAfterInline.\n  Variable ty: Kind -> Type.\n  \n  Lemma inlineDmsToRules_Equiv rs ls:\n    RulesEquiv ty typeUT rs ->\n    MethsEquiv ty typeUT ls ->\n    RulesEquiv ty typeUT \n               (map (fun r => (fold_right\n                                 (fun dm' r' => inlineDmToRule r' dm') r ls)) rs).\n  Proof.\n    induction rs; simpl in *; auto; intros.\n    dependent destruction H.\n    apply IHrs in H0; auto.\n    constructor; auto.\n    apply inlineDmsToRule_Equiv; auto.\n    apply MethsEquiv_in; auto.\n  Qed.\nEnd rsEquivAfterInline.\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/PartialInlineFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.37754066179448903, "lm_q1q2_score": 0.1931938255912395}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext machine_int uniq_tac multi_int.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_mint.\nImport expr_m.\nRequire Import simu.\nImport simu_m.\nRequire Import multi_sub_s_s_prg multi_sub_s_s_triple.\nFrom mathcomp Require Import seq.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope simu_scope.\nLocal Open Scope multi_int_scope.\n\n(** x <- x - y, x signed, y signed *)\n\nLemma pfwd_sim_multi_sub_s_s (x y : assoc.l) d k rk ry rx a0 a1 a2 a3 a4 ret rX rY :\n  uniq(x, y) ->\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, ret, rX, rY, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: a1 :: a2 :: a3 :: a4 :: ret :: rX :: rY :: nil) ->\n  x \\notin assoc.dom d -> y \\notin assoc.dom d ->\n  signed k rx \\notin assoc.cdom d -> unsign rk ry \\notin assoc.cdom d ->\n  (x <- var_e x \\- var_e y)%pseudo_expr%pseudo_cmd\n    <=p( state_mint (x |=> signed k rx \\U+ (y |=> signed k ry \\U+ d)),\n         fun s st _ => [rk ]_ st <> zero32 /\\\n                        u2Z ([rk ]_ st) < 2 ^^ 31 /\\\n                        k = '|u2Z ([rk ]_ st)| /\\\n                        `|([ x ]_ s)%pseudo_expr| < \\B^k /\\\n                        `|([ y ]_ s)%pseudo_expr| < \\B^k /\\\n                        `|([ x ]_ s)%pseudo_expr - ([y ]_ s)%pseudo_expr| < \\B^k)\n  multi_sub_s_s rk rx ry a0 a1 a2 a3 a4 ret rX rY.\nProof.\nmove=> Hvars Hreg Hd x_d y_d rx_d ry_d.\nrewrite /pfwd_sim.\nmove=> st s h [st_s_h [rk_s_neq0 [rk_s_max [k_rk [x_st [y_st x_y_st]]]]]] st' exec_pseudo s' h' exec_asm.\nhave Hd_unchanged : forall v r, assoc.get v d = Some r ->\n  disj (mint_regs r) (mips_frame.modified_regs (multi_sub_s_s rk rx ry a0 a1 a2 a3 a4 ret rX rY)).\n  move=> v r Hvr; rewrite [mips_frame.modified_regs _]/=; Disj_remove_dup.\n  apply (disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n  apply/incP/inc_mint_regs.\n  by move/assoc.get_Some_in_cdom : Hvr.\nset vx := [rx ]_ s.\nset vy := [ry ]_ s.\nlapply (state_mint_var_mint _ _ _ _ x (signed k rx) st_s_h); [move=> var_mint_x | by assoc_get_Some].\nrewrite /var_mint in var_mint_x.\ncase: var_mint_x => slen ptr X vx_fit [X_k Hlen Hsgn Sum_X] ptr_fit Hmem.\n\nlapply (state_mint_var_mint _ _ _ _ y (signed k ry) st_s_h); [move=> var_mint_y | by assoc_get_Some].\nrewrite /var_mint in var_mint_y.\ncase: var_mint_y => sleny ptry Y vy_fit [Y_k Hleny Hsgny Sum_Y] ptry_fit Hmemy.\n\nmove/multi_sub_s_s_triple : (Hreg).\nmove/(_ k vx vy ptr ptry).\nhave : k <> O.\n  contradict rk_s_neq0. apply u2Z_inj. rewrite rk_s_neq0 in k_rk.\n  symmetry in k_rk. apply Zabs_nat_0_inv in k_rk. by rewrite Z2uK.\nlet x := fresh in move=> x; move/(_ x); clear x.\nhave : Z<=nat k < 2 ^^ 31.\n  rewrite k_rk Z_of_nat_Zabs_nat //; by apply min_u2Z.\nlet x := fresh in move=> x; move/(_ x); clear x.\nmove/(_ ptr_fit ptry_fit X Y X_k Y_k slen sleny Hlen Hleny).\nrewrite -{1}Sum_X.\nrewrite -{1}Sum_Y.\nmove/(_ Hsgn Hsgny) => Hhoare_multi_sub_s_s.\n\nhave [s'' [h'' exec_asm_proj]] : exists s'' h'',\n  (Some (s, h |P| heap.dom (heap_mint (signed k ry) s h \\U heap_mint (signed k rx) s h))\n    -- multi_sub_s_s rk rx ry a0 a1 a2 a3 a4 ret rX rY --->\n    Some (s'', h''))%mips_cmd.\n  exists s', (h' |P| heap.dom (heap_mint (signed k ry) s h \\U heap_mint (signed k rx) s h)).\n  apply (mips_syntax.triple_exec_proj _ _ _ Hhoare_multi_sub_s_s) => {Hhoare_multi_sub_s_s} //.\n  split; first by [].\n  split; first by [].\n  split.\n    rewrite k_rk Z_of_nat_Zabs_nat //; exact: min_u2Z.\n  rewrite heap.proj_dom_union; last first.\n    apply (proj2 st_s_h y x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  rewrite heap.unionC; last first.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply (proj2 st_s_h y x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  apply assert_m.con_cons.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply (proj2 st_s_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  move: (heap_inclu_heap_mint_signed h s k rx).\n  move/heap.incluE => ->; exact Hmem.\n  move: (heap_inclu_heap_mint_signed h s k ry).\n  move/heap.incluE => ->; exact Hmemy.\nhave ry_s_s' : [ ry ]_ s = [ ry ]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave rk_s_s' : [ rk ]_ s = [ rk ]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave y_st_st' : ([ y ]_ st = [ y ]_ st')%pseudo_expr.\n  Var_unchanged. simpl syntax_m.seplog_m.modified_vars.\n  move/inP.\n  rewrite -/(~ _).\n  by Uniq_not_In.\nhave rx_s_s' : [ rx ]_ s = [rx ]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nset postcond := (fun s h => exists _, _) in Hhoare_multi_sub_s_s.\nhave {Hhoare_multi_sub_s_s}hoare_triple_post_condition : (postcond  ** assert_m.TT)%asm_assert s' h'.\n    move: {Hhoare_multi_sub_s_s}(mips_frame.frame_rule_R _ _ _ Hhoare_multi_sub_s_s assert_m.TT (assert_m.inde_TT _) (mips_frame.inde_cmd_mult_TT _)).\n    move/mips_seplog.hoare_prop_m.soundness.\n\nNotation \"'hoare_semantics'\" := (@while.hoare_semantics WMIPS_Hoare.store WMIPS_Hoare.heap _\nWMIPS_Hoare.exec0 _ WMIPS_Hoare.eval_b) : mips_hoare_scope.\n\n    rewrite /while.hoare_semantics.\n\nNotation \"s -- c ---> t\" := (@while.exec WMIPS_Hoare.store WMIPS_Hoare.heap _ WMIPS_Hoare.exec0 _\n  WMIPS_Hoare.eval_b s c t)  (at level 74, no associativity) : mips_cmd_scope.\n\n    move/(_ s h) => Hmulti_sub_s_u.\n    lapply Hmulti_sub_s_u; last first.\n      exists (heap_mint (signed k rx) s h \\U heap_mint (signed k ry) s h).\n      exists (h \\D\\ heap.dom (heap_mint (signed k rx) s h \\U heap_mint (signed k ry) s h)).\n      split.\n        exact/heap.disj_difs'/seq_ext.inc_refl.\n      split.\n        apply heap.union_difsK; last by [].\n        apply heap_prop_m.inclu_union; by [apply heap_inclu_heap_mint_signed | apply heap.inclu_proj].\n      split; last by [].\n      repeat (split=> //).\n      - rewrite k_rk Z_of_nat_Zabs_nat //; by apply min_u2Z.\n      - apply assert_m.con_cons.\n        + apply (proj2 st_s_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n        + exact Hmem.\n        + exact Hmemy.\n    case=> _.\n    by move/(_ _ _ exec_asm).\nrewrite /state_mint; split.\n- move=> z rz z_rz.\n  have [z_d | z_x ] : z \\in assoc.dom (y |=> signed k ry \\U+ d) \\/ z = x.\n    rewrite assoc.unionC in z_rz; last first.\n      apply assoc.disjhU.\n      apply assoc.disj_sing; apply/eqP; by Uniq_neq.\n      by apply assoc.disj_sym, assoc.disj_sing_R.\n    case/assoc.get_union_Some_inv : z_rz => z_rz.\n    left.\n    by apply assoc.get_Some_in_dom with rz.\n    case/assoc.get_sing_inv : z_rz => ? ?; subst z rz.\n    by right.\n  + (* NB: it is about proving that x is unchanged, which is true since\n       neither y nor d are touched by execution *)\n    have z_x : z <> x.\n      move=> ?; subst z.\n      case/assoc.in_dom_union_inv : z_d.\n      * case/assoc.in_dom_get_Some => x0.\n        case/assoc.get_sing_inv => x_y _.\n        move: x_y.\n        rewrite -/(~ _); by Uniq_neq.\n      * by rewrite (negbTE x_d).\n    case/orP : (orbN (z == y)) => z_y.\n    (* z = y *)\n    move/eqP : z_y => ?; subst z.\n    rewrite assoc.unionC in z_rz; last first.\n      apply assoc.disjhU.\n      apply assoc.disj_sing; apply/eqP; by auto.\n      by apply assoc.disj_sym, assoc.disj_sing_R.\n    rewrite -assoc.unionA assoc.get_union_sing_eq in z_rz.\n    case: z_rz => ?; subst rz.\n    case : hoare_triple_post_condition => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\n    case: Hh1 => X' [slen' Hh1].\n    case: Hh1 => H [H1 [H0 [H2 [H3 H4]]]].\n    case: H2 => h11 [h12 [h11_d_h12 [h11_U_h12 [Hh11 Hh12]]]].\n    move: (proj1 st_s_h y (signed k ry)).\n    rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n    rewrite assoc.get_union_sing_eq.\n    move/(_ (refl_equal _)).\n    move=> K.\n    have <- : heap_mint (signed k ry) s h = heap_mint (signed k ry) s' h'.\n      case: (Hmemy) => k1 [k2 [k1_d_k2 [k1_U_k2 [Hk1 Hk2]]]].\n      rewrite k1_U_k2.\n\n      rewrite {1}/heap_mint.\n      move: (assert_m.mapstos_get1 _ _ _ _ _ _ Hh12).\n      move/(heap.get_union_R _ _ h11_d_h12).\n      rewrite -h11_U_h12.\n      move/(heap.get_union_L _ _ h1_d_h2).\n      rewrite -h1_U_h2.\n      move=> ->.\n      move: (assert_m.mapstos_get2 _ _ _ _ _ _ Hh12).\n      move/(heap.get_union_R _ _ h11_d_h12).\n      rewrite -h11_U_h12.\n      move/(heap.get_union_L _ _ h1_d_h2).\n      rewrite -h1_U_h2.\n      move=> ->.\n      cbv zeta iota beta.\n\n      rewrite /heap_cut.\n      rewrite -ry_s_s'.\n      case: Hh12 => i1 [i2 [i1_d_i2 [i1_U_i2 [Hi1 Hi2]]]].\n      move: (Hi1) => Hi1_save.\n      apply assert_m.mapstos_inv_dom in Hi1; last first.\n        by rewrite /= -ry_s_s'.\n      move: (Hi2) => Hi2_save.\n      apply assert_m.mapstos_inv_dom in Hi2; last by rewrite Y_k.\n      rewrite ry_s_s'.\n      rewrite Hi1 -Y_k.\n      rewrite Hi2.\n      rewrite h1_U_h2.\n      rewrite h11_U_h12.\n      rewrite i1_U_i2.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_R_dom; last by heap_tac_m.Disj.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_itself.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_R_dom; last by heap_tac_m.Disj.\n      rewrite heap.proj_union_R_dom; last by heap_tac_m.Disj.\n      rewrite heap.proj_itself.\n      congr (_ \\U _).\n      apply: assert_m.strictly_exact_mapstos (conj Hk1 _); by apply: assert_m.mapstos_ext Hi1_save.\n      apply: assert_m.strictly_exact_mapstos (conj Hk2 _); by apply: assert_m.mapstos_ext Hi2_save.\n    move: K.\n    by apply var_mint_invariant_signed.\n    (* z <> y *)\n    move: {st_s_h}(proj1 st_s_h _ _ z_rz) (proj2 st_s_h) => st_s_h1 st_s_h2.\n    have z_unchanged : ( [ z ]_ st = [ z ]_st' )%pseudo_expr.\n      Var_unchanged. rewrite /= mem_seq1; exact/negP/eqP.\n    case: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm\n      (heap.dom (heap_mint (signed k ry) s h \\U heap_mint (signed k rx) s h)) _ _\n      exec_asm_proj) => H4 [H5 H_h_h'].\n    have <- : heap_mint rz s h = heap_mint rz s' h'.\n      apply (heap_mint_state_invariant (heap_mint (signed k ry) s h \\U\n                            heap_mint (signed k rx) s h) z st) => //.\n      move=> rx0 Hrx0; mips_syntax.Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs rz)); last by [].\n      apply/disj_sym/(Hd_unchanged z).\n      rewrite assoc.get_union_sing_neq in z_rz; last by [].\n      rewrite assoc.get_union_sing_neq // in z_rz.\n      by apply/eqP.\n      apply heap.disjhU.\n      apply st_s_h2 with z y => //.\n      by apply/eqP.\n      rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n      by rewrite assoc.get_union_sing_eq.\n      apply st_s_h2 with z x => //.\n      by rewrite assoc.get_union_sing_eq.\n    move: st_s_h1; apply var_mint_invariant; last exact z_unchanged.\n    move=> rx0 Hrx0; mips_syntax.Reg_unchanged.\n    apply (@disj_not_In _ (mint_regs rz)); last by [].\n    apply/disj_sym/(Hd_unchanged z) => //.\n    rewrite assoc.get_union_sing_neq in z_rz; last by [].\n    rewrite assoc.get_union_sing_neq // in z_rz.\n    by apply/eqP.\n  + subst z.\n    have rz_rx : rz = signed k rx.\n      rewrite assoc.get_union_sing_eq in z_rz; by case: z_rz.\n    subst rz.\n    move: (proj1 st_s_h x (signed k rx) z_rz).\n    rewrite /var_mint.\n    case: hoare_triple_post_condition => [h1 [h2 [Hdisj [Hunion [[X' [slen' [Hsub_s_s_1 [r_x [r_y [Hsub_s_s_2 [Hsub_s_s_3 Hsub_s_s_4]]]]]]]] HTT]]]].\n    move=> K.\n    have x'_x_y : ([ x ]_ st' = [ x ]_ st - [y ]_ st )%pseudo_expr.\n      move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n      case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n      by syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n    apply (mkVarSigned _ _ _ _ _ slen' ptr X') => //.\n    + by rewrite /vx -rx_s_s'.\n    + apply mkSignMagn.\n      * exact Hsub_s_s_1.\n      * by rewrite {1}r_x.\n      * by rewrite {1}r_y -Sum_X x'_x_y Sum_Y.\n      * rewrite x'_x_y Sum_X Sum_Y -Hsub_s_s_4.\n        case: (Z_zerop (s2Z slen')) => slen'_neq0.\n          by rewrite slen'_neq0.\n        have Hi : u2Z [a3 ]_ s' = 0.\n          have : `|Z.sgn (s2Z slen') * (\\S_{ k } X' + u2Z [a3 ]_ s' * \\B^k)| < \\B^k.\n            by rewrite Hsub_s_s_4 -Sum_X -Sum_Y.\n          rewrite Zabs_Zmult Zabs_Zsgn_1 // Zmult_1_l addZC.\n          apply: poly_Zlt1_Zabs_inv => //.\n          exact: min_lSum.\n          exact: min_u2Z.\n        rewrite Hi mul0Z addZ0 in Hsub_s_s_4.\n        by rewrite Hi mul0Z addZ0.\n    + case: Hsub_s_s_2 => h11 [h12 [h11_d_h12 [h11_U_h12 [Hh11 Hh12]]]].\n      suff : heap_mint (signed k rx) s' h' = h11 by move=> ->.\n      simpl heap_mint.\n      have K1 : heap.get '|u2Z ([ rx ]_ s')%asm_expr / 4| h' = Some slen'.\n        rewrite Hunion; apply heap.get_union_L => //.\n        rewrite h11_U_h12; apply heap.get_union_L => //.\n        by apply assert_m.mapstos_get1 in Hh11.\n      have K2 : heap.get '|u2Z ([ rx ]_ s' `+ four32) / 4| h' = Some ptr.\n        rewrite Hunion; apply heap.get_union_L => //.\n        rewrite h11_U_h12; apply heap.get_union_L => //.\n        by apply assert_m.mapstos_get2 in Hh11.\n      rewrite K1 K2.\n      rewrite /heap_cut.\n      case: Hh11 => h111 [h112 [h111_d_h112 [h111_U_h112 [Hh111 Hh112]]]].\n      apply assert_m.mapstos_inv_dom in Hh111; last first.\n        by rewrite [u2Z _]/= [Z_of_nat _]/= -rx_s_s'.\n      rewrite Hh111.\n      apply assert_m.mapstos_inv_dom in Hh112; last first.\n        by rewrite [u2Z _]/= Hsub_s_s_1.\n      rewrite -Hsub_s_s_1 Hh112.\n      rewrite h111_U_h112.\n      congr (_ \\U _).\n      rewrite Hunion h11_U_h12 h111_U_h112.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      by rewrite heap.proj_itself.\n      rewrite Hunion h11_U_h12 h111_U_h112.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n      rewrite heap.proj_union_R_dom; last by heap_tac_m.Disj.\n      by rewrite heap.proj_itself.\n- case: hoare_triple_post_condition => [h1 [h2 [Hdisj [Hunion [[X' [slen' [Hsub_s_s_1 [r_x [r_y [Hsub_s_s_2 [Hsub_s_s_3 Hsub_s_s_4]]]]]]]] HTT]]]].\n\n  have Hslen' : heap.get '|u2Z ([ rx ]_ s')%asm_expr / 4| h' = Some slen'.\n    rewrite Hunion.\n    apply heap.get_union_L => //.\n    rewrite 1!assert_m.conAE in Hsub_s_s_2.\n    by apply assert_m.mapstos_get1 in Hsub_s_s_2.\n\n  have Hptr : heap.get '|u2Z ([ rx ]_ s' `+ four32 )%asm_expr / 4| h' = Some ptr.\n    rewrite Hunion.\n    apply heap.get_union_L => //.\n    rewrite 1!assert_m.conAE in Hsub_s_s_2.\n    by apply assert_m.mapstos_get2 in Hsub_s_s_2.\n\n  have Hsleny : heap.get '|u2Z [ ry ]_ s / 4| h = Some sleny.\n    apply assert_m.mapstos_get1 in Hmemy.\n    by apply heap_get_heap_mint_inv in Hmemy.\n\n  apply state_mint_part2_two_variables with st s h => //.\n  + move/assert_m.mapstos_get2 : (Hmem).\n    move/heap_get_heap_mint_inv => ptr_vx4.\n    move/assert_m.mapstos_get1 : (Hmem).\n    move/heap_get_heap_mint_inv => slen_vx.\n    symmetry.\n    apply dom_heap_mint_sign_state_invariant with x st slen slen'.\n    exact rx_s_s'.\n    exact slen_vx.\n    exact Hslen'.\n    by rewrite Hptr.\n    rewrite assoc_prop_m.swap_heads in st_s_h; last first.\n      rewrite [Equality.sort _]/= in Hvars *. by Uniq_uniq y.\n    apply (state_mint_var_mint _ _ _ _ _ _ st_s_h).\n    rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n    by rewrite assoc.get_union_sing_eq.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + symmetry.\n    apply dom_heap_mint_sign_state_invariant with y st sleny sleny => //.\n\n  have Hptry : heap.get '| u2Z [ry ]_ s' / 4 | h' = Some sleny.\n    rewrite assert_m.conCE in Hsub_s_s_2.\n    rewrite 1!assert_m.conAE in Hsub_s_s_2.\n    apply assert_m.mapstos_get1 in Hsub_s_s_2.\n    rewrite Hunion.\n    by apply heap.get_union_L.\n    exact Hptry.\n\n    move/assert_m.mapstos_get2/heap_get_heap_mint_inv in Hmemy.\n    rewrite assert_m.conCE assert_m.conAE in Hsub_s_s_2.\n    apply assert_m.mapstos_get2 in Hsub_s_s_2.\n    rewrite Hunion.\n    symmetry.\n    rewrite Hmemy.\n    by apply heap.get_union_L.\n\n    apply (state_mint_var_mint _ _ _ _ _ _ st_s_h).\n    rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n    by rewrite assoc.get_union_sing_eq.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + move=> t Ht x0 Hx0.\n    mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs.\n    case/assoc.in_cdom_union_inv : Ht => Ht.\n    * rewrite assoc.cdom_sing /= seq.mem_seq1 in Ht.\n      move/eqP : Ht => Ht; subst t.\n      apply (@disj_not_In _ (mint_regs (signed k rx))); last by [].\n      Disj_remove_dup.\n      rewrite /=.\n      apply uniq_disj.\n      rewrite [cat _ _]/=.\n      by Uniq_uniq r0.\n    * case/assoc.in_cdom_union_inv : Ht => Ht.\n      - rewrite assoc.cdom_sing /= mem_seq1 in Ht.\n        move/eqP : Ht => Ht; subst t.\n        apply (@disj_not_In _ (mint_regs (unsign rk ry))); last by rewrite /=; auto.\n        Disj_remove_dup.\n        rewrite /=.\n        apply uniq_disj.\n        rewrite [cat _ _]/=.\n        by Uniq_uniq r0.\n      - apply (@disj_not_In _ (mint_regs t)); last by [].\n        Disj_remove_dup.\n        apply disj_sym.\n        apply (disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n        exact/incP/inc_mint_regs.\n  + by Uniq_neq.\n  + move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_asm_proj); tauto.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_sub_s_s_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.19319382355242165}}
{"text": "Require Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Coq.Structures.Orders.\nRequire Import VST.veric.base.\nRequire Import compcert.cfrontend.Ctypes. (*Require Import VST.veric.Clight_lemmas.*)\nRequire Import VST.veric.type_induction.\nRequire Import VST.veric.composite_compute.\n\n(* This file contains three computational align criteria.\n   1: the hardware alignof is not larger than alignof (and additional criterion for array).\n   2: all fields are aligned as hardware requires. size as a multiple of hardware alignof.\n   3: all value is well-aligned stored.\n   The third one is the final specification we want. *)\n\nSection align_compatible_rec.\n\nContext (cenv: composite_env).\n\nInductive align_compatible_rec: type -> Z -> Prop :=\n| align_compatible_rec_by_value: forall t ch z, access_mode t = By_value ch -> (Memdata.align_chunk ch | z) -> align_compatible_rec t z\n| align_compatible_rec_Tarray: forall t n a z, (forall i, 0 <= i < n -> align_compatible_rec t (z + sizeof cenv t * i)) -> align_compatible_rec (Tarray t n a) z\n| align_compatible_rec_Tstruct: forall i a co z, cenv ! i = Some co -> (forall i0 t0 z0, field_type i0 (co_members co) = Errors.OK t0 -> field_offset cenv i0 (co_members co) = Errors.OK z0 -> align_compatible_rec t0 (z + z0)) -> align_compatible_rec (Tstruct i a) z\n| align_compatible_rec_Tunion: forall i a co z, cenv ! i = Some co -> (forall i0 t0, field_type i0 (co_members co) = Errors.OK t0 -> align_compatible_rec t0 z) -> align_compatible_rec (Tunion i a) z.\n\nLemma align_compatible_rec_by_value_inv : forall t ch z,\n  access_mode t = By_value ch ->\n  align_compatible_rec t z -> (Memdata.align_chunk ch | z).\nProof.\n  intros.\n  inv H0.\n  + rewrite H in H1; inv H1; auto.\n  + inv H.\n  + inv H.\n  + inv H.\nQed.\n\nLemma align_compatible_rec_Tarray_inv: forall t n a z,\n  align_compatible_rec (Tarray t n a) z ->\n  (forall i : Z, 0 <= i < n -> align_compatible_rec t (z + sizeof cenv t * i)).\nProof.\n  intros.\n  inv H.\n  + inv H1.\n  + auto.\nQed.\n\nLemma align_compatible_rec_Tstruct_inv: forall i a co z,\n  cenv ! i = Some co ->\n  align_compatible_rec (Tstruct i a) z ->\n  (forall i0 t0 z0, field_type i0 (co_members co) = Errors.OK t0 -> field_offset cenv i0 (co_members co) = Errors.OK z0 -> align_compatible_rec t0 (z + z0)).\nProof.\n  intros.\n  inv H0.\n  + inv H3.\n  + rewrite H in H5; inv H5.\n    eauto.\nQed.\n  \nLemma align_compatible_rec_Tunion_inv: forall i a co z,\n  cenv ! i = Some co ->\n  align_compatible_rec (Tunion i a) z ->\n  (forall i0 t0, field_type i0 (co_members co) = Errors.OK t0 -> align_compatible_rec t0 z).\nProof.\n  intros.\n  inv H0.\n  + inv H2.\n  + rewrite H in H4; inv H4.\n    eauto.\nQed.\n\nEnd align_compatible_rec.\n\nLemma align_chunk_1248: forall ch, align_chunk ch = 1 \\/ align_chunk ch = 2 \\/ align_chunk ch = 4 \\/ align_chunk ch = 8.\nProof.\n  intros.\n  destruct ch; simpl;\n  auto.\nQed.\n\nLemma align_chunk_two_p:\n  forall ch, exists n, align_chunk ch = two_power_nat n.\nProof.\n  intros.\n  pose proof align_chunk_1248 ch as [| [| [|]]]; rewrite H.\n  + exists 0%nat; auto.\n  + exists 1%nat; auto.\n  + exists 2%nat; auto.\n  + exists 3%nat; auto.\nQed.\n\nFixpoint hardware_alignof (ha_env: PTree.t Z) t: Z :=\n  match t with\n  | Tarray t' _ _ => hardware_alignof ha_env t'\n  | Tstruct id _ =>\n      match ha_env ! id with\n      | Some ha => ha\n      | None => 1\n      end\n  | Tunion id _ =>\n      match ha_env ! id with\n      | Some ha => ha\n      | None => 1\n      end\n  | _ => match access_mode t with\n         | By_value ch => Memdata.align_chunk ch\n         | _ => 1\n         end\n  end.\n\nFixpoint hardware_alignof_composite (ha_env: PTree.t Z) (m: members): Z :=\n  match m with\n  | nil => 1\n  | (_, t) :: m' => Z.max (hardware_alignof ha_env t) (hardware_alignof_composite ha_env m')\n  end.\n\nDefinition hardware_alignof_env (cenv: composite_env): PTree.t Z :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t Z) => let (i, co) := ic in let T := T0 in PTree.set i (hardware_alignof_composite T (co_members co)) T) (PTree.empty _) l.\n\nDefinition hardware_alignof_env_consistent (cenv: composite_env) (ha_env: PTree.t Z): Prop :=\n  forall i co ha,\n    cenv ! i = Some co ->\n    ha_env ! i = Some ha ->\n    ha = hardware_alignof_composite ha_env (co_members co).\n\nDefinition hardware_alignof_env_complete (cenv: composite_env) (ha_env: PTree.t Z): Prop :=\n  forall i,\n    (exists co, cenv ! i = Some co) <->\n    (exists ha, ha_env ! i = Some ha).\n\nModule Type HARDWARE_ALIGNOF_FACTS.\n\n  Axiom hardware_alignof_consistency:\n    forall (cenv: composite_env) (ha_env: PTree.t Z),\n      composite_env_consistent cenv ->\n      ha_env = hardware_alignof_env cenv ->\n      hardware_alignof_env_consistent cenv ha_env.\n\n  Axiom hardware_alignof_completeness:\n    forall (cenv: composite_env) (ha_env: PTree.t Z),\n      ha_env = hardware_alignof_env cenv ->\n      hardware_alignof_env_complete cenv ha_env.\n\nEnd HARDWARE_ALIGNOF_FACTS.\n\nModule hardware_alignof_facts: HARDWARE_ALIGNOF_FACTS.\n\nLemma aux1: forall T co,\n  (fix fm (l : list (ident * type * Z)) : Z :=\n     match l with\n     | nil => 1\n     | (_, _, ha) :: l' => Z.max ha (fm l')\n     end)\n    (map\n       (fun it0 : positive * type =>\n        let (i0, t0) := it0 in\n        (i0, t0,\n        type_func.F\n          (fun t : type =>\n           match access_mode t with\n           | By_value ch => align_chunk ch\n           | By_reference => 1\n           | By_copy => 1\n           | By_nothing => 1\n           end) (fun (ha : Z) (_ : type) (_: Z) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha) T t0)) (co_members co)) =\n                    hardware_alignof_composite T (co_members co).\nProof.\n  intros; unfold hardware_alignof_composite, hardware_alignof.\n  induction (co_members co) as [| [i t] ?].\n  + auto.\n  + simpl.\n    f_equal; auto.\n    clear.\n    induction t; auto.\nQed.\n\nLemma aux2: forall (cenv: composite_env),\n  type_func.Env\n          (fun t : type =>\n           match access_mode t with\n           | By_value ch => align_chunk ch\n           | By_reference => 1\n           | By_copy => 1\n           | By_nothing => 1\n           end) (fun (ha : Z) (_ : type) (_: Z) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun _ : struct_or_union =>\n           fix fm (l : list (ident * type * Z)) : Z :=\n             match l with\n             | nil => 1\n             | (_, _, ha) :: l' => Z.max ha (fm l')\n             end) (composite_reorder.rebuild_composite_elements cenv) =\n  hardware_alignof_env cenv.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, hardware_alignof_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nLemma hardware_alignof_consistency (cenv: composite_env) (ha_env: PTree.t Z):\n  composite_env_consistent cenv ->\n  ha_env = hardware_alignof_env cenv ->\n  forall i co ha,\n    cenv ! i = Some co ->\n    ha_env ! i = Some ha ->\n    ha = hardware_alignof_composite ha_env (co_members co).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent Z cenv\n             (fun t =>\n                match access_mode t with\n                | By_value ch => Memdata.align_chunk ch\n                | _ => 1\n                end)\n             (fun ha _ _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun _ =>\n                fix fm (l: list (ident * type * Z)): Z :=\n                match l with\n                | nil => 1\n                | (_, _, ha) :: l' => Z.max ha (fm l')\n                end)\n             H\n    as HH.\n  hnf in HH.\n  subst ha_env.\n  rewrite aux2 in HH.\n  specialize (HH _ _ ha H1 H2).\n  rewrite HH, aux1; auto.\nQed.\n\nLemma hardware_alignof_completeness (cenv: composite_env) (ha_env: PTree.t Z):\n  ha_env = hardware_alignof_env cenv ->\n  forall i,\n    (exists co, cenv ! i = Some co) <->\n    (exists ha, ha_env ! i = Some ha).\nProof.\n  intros.\n  pose proof @composite_reorder_complete Z cenv\n             (fun t =>\n                match access_mode t with\n                | By_value ch => Memdata.align_chunk ch\n                | _ => 1\n                end)\n             (fun ha _ _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun _ =>\n                fix fm (l: list (ident * type * Z)): Z :=\n                match l with\n                | nil => 1\n                | (_, _, ha) :: l' => Z.max ha (fm l')\n                end)\n    as HH.\n  hnf in HH.\n  subst.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nEnd hardware_alignof_facts.\n\nExport hardware_alignof_facts.\n\nLemma hardware_alignof_two_p: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall t, exists n,\n  hardware_alignof ha_env t = two_power_nat n.\nProof.\n  intros ? ? CENV_CONS HA_ENV_CONS HA_ENV_COMPL ?.\n  type_induction t cenv CENV_CONS.\n  + exists 0%nat; reflexivity.\n  + destruct s, i; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + destruct s; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + destruct f; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + simpl. unfold Mptr.\n      destruct Archi.ptr64; [exists 3%nat | exists 2%nat]; reflexivity.\n  + simpl.\n    auto.\n  + exists 0%nat; reflexivity.\n  + simpl.\n    pose proof HA_ENV_CONS id; pose proof HA_ENV_COMPL id.\n    destruct (cenv ! id) as [co |] eqn:?H, (ha_env ! id) eqn:?H.\n    2: { pose proof proj1 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. }\n    2: { pose proof proj2 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. }\n    - specialize (H _ _ eq_refl eq_refl).\n      subst z.\n      clear - IH.\n      induction IH.\n      * exists 0%nat; reflexivity.\n      * destruct x as [i t], H as [n1 ?], IHIH as [n2 ?].\n        simpl in H |- *.\n        rewrite H, H0.\n        rewrite max_two_power_nat.\n        eexists; reflexivity.\n    - exists 0%nat; reflexivity.\n  + simpl.\n    pose proof HA_ENV_CONS id; pose proof HA_ENV_COMPL id.\n    destruct (cenv ! id) as [co |] eqn:?H, (ha_env ! id) eqn:?H.\n    2: { pose proof proj1 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. }\n    2: { pose proof proj2 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. }\n    - specialize (H _ _ eq_refl eq_refl).\n      subst z.\n      clear - IH.\n      induction IH.\n      * exists 0%nat; reflexivity.\n      * destruct x as [i t], H as [n1 ?], IHIH as [n2 ?].\n        simpl in H |- *.\n        rewrite H, H0.\n        rewrite max_two_power_nat.\n        eexists; reflexivity.\n    - exists 0%nat; reflexivity.\nQed.\n\nLemma hardware_alignof_pos: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall t,\n  hardware_alignof ha_env t > 0.\nProof.\n  intros.\n  pose proof hardware_alignof_two_p _ _ H H0 H1 t as [n ?].\n  rewrite H2.\n  apply two_power_nat_pos.\nQed.\n\nLemma hardware_alignof_composite_two_p: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall m, exists n,\n    hardware_alignof_composite ha_env m = two_power_nat n.\nProof.\n  intros.\n  induction m as [| [i t] ?].\n  + exists 0%nat.\n    reflexivity.\n  + destruct IHm as [n1 ?], (hardware_alignof_two_p _ _ H H0 H1 t) as [n2 ?].\n    simpl.\n    rewrite H2, H3.\n    rewrite max_two_power_nat.\n    eexists; reflexivity.\nQed.\n\nHint Resolve alignof_two_p: align.\nHint Resolve align_chunk_two_p: align.\nHint Extern 10 (exists n: nat, hardware_alignof _ _ = two_power_nat n) => (eapply hardware_alignof_two_p; eassumption): align.\nHint Extern 10 (exists n: nat, hardware_alignof_composite _ _ = two_power_nat n) => (eapply hardware_alignof_composite_two_p; eassumption): align.\n\nLemma hardware_alignof_by_value: forall ha_env t ch,\n  access_mode t = By_value ch ->\n  hardware_alignof ha_env t = align_chunk ch.\nProof.\n  intros.\n  destruct t as [| [| | |] [|] | [|] | [|] | | | | |]; inv H; auto.\nQed.\n\nLemma align_compatible_rec_hardware_alignof_divide: forall cenv ha_env t z1 z2,\n  composite_env_consistent cenv ->\n  composite_env_complete_legal_cosu_type cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  complete_legal_cosu_type cenv t = true ->\n  (hardware_alignof ha_env t | z1 - z2) ->\n  (align_compatible_rec cenv t z1 <-> align_compatible_rec cenv t z2).\nProof.\n  intros ? ? ? ? ? CENV_CONS CENV_COSU HA_ENV_CONS HA_ENV_COMPL.\n  revert t z1 z2.\n  assert (BY_VALUE: forall t z1 z2, (exists ch, access_mode t = By_value ch) -> (hardware_alignof ha_env t | z1 - z2) -> align_compatible_rec cenv t z1 <-> align_compatible_rec cenv t z2).\n  {\n    intros ? ? ? [? ?] ?.\n    split; intros.\n    + eapply align_compatible_rec_by_value_inv in H1; eauto.\n      eapply align_compatible_rec_by_value; eauto.\n      replace z2 with (z1 - (z1 - z2)) by omega.\n      erewrite hardware_alignof_by_value in H0 by eauto.\n      apply Z.divide_sub_r; auto.\n    + eapply align_compatible_rec_by_value_inv in H1; eauto.\n      eapply align_compatible_rec_by_value; eauto.\n      replace z1 with (z2 + (z1 - z2)) by omega.\n      erewrite hardware_alignof_by_value in H0 by eauto.\n      apply Z.divide_add_r; auto.\n  } \n  intro t; type_induction t cenv CENV_CONS; intros.\n  + split; intros; inv H1; inv H2.\n  + eapply BY_VALUE; auto.\n    destruct s, i; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    destruct s; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    destruct f; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    eexists; reflexivity.\n  + simpl in H0.\n    split; intros; apply align_compatible_rec_Tarray; intros;\n    eapply align_compatible_rec_Tarray_inv in H1; eauto.\n    - specialize (IH (z1 + sizeof cenv t0 * i) (z2 + sizeof cenv t0 * i)).\n      replace (z1 + sizeof cenv t0 * i - (z2 + sizeof cenv t0 * i)) with (z1 - z2) in IH by omega.\n      tauto.\n    - specialize (IH (z1 + sizeof cenv t0 * i) (z2 + sizeof cenv t0 * i)).\n      replace (z1 + sizeof cenv t0 * i - (z2 + sizeof cenv t0 * i)) with (z1 - z2) in IH by omega.\n      tauto.\n  + split; intros; inv H1; inv H2; econstructor.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    assert (forall i0 t0 ofs0,\n              field_type i0 (co_members co) = Errors.OK t0 ->\n              field_offset cenv i0 (co_members co) = Errors.OK ofs0 ->\n              (align_compatible_rec cenv t0 (z1 + ofs0) <->\n               align_compatible_rec cenv t0 (z2 + ofs0))) as HH;\n    [ | split; intros; eapply align_compatible_rec_Tstruct; eauto;\n        intros; eapply align_compatible_rec_Tstruct_inv in H; eauto;\n        eapply HH; eauto].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    clear H H1 H2 H3 ha.\n    intros. clear H1.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; [simpl; tauto |].\n        replace (z1 + ofs0 - (z2 + ofs0)) with (z1 - z2) by omega; tauto.\n      * apply IHIH; tauto.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    assert (forall i0 t0,\n              field_type i0 (co_members co) = Errors.OK t0 ->\n              (align_compatible_rec cenv t0 z1 <->\n               align_compatible_rec cenv t0 z2)) as HH;\n    [ | split; intros; eapply align_compatible_rec_Tunion; eauto;\n        intros; eapply align_compatible_rec_Tunion_inv in H; eauto;\n        eapply HH; eauto].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    clear H H1 H2 H3 ha.\n    intros.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; simpl; tauto.\n      * apply IHIH; tauto.\nQed.\n\nLemma align_compatible_rec_hardware_1: forall cenv ha_env t z,\n  composite_env_consistent cenv ->\n  composite_env_complete_legal_cosu_type cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  complete_legal_cosu_type cenv t = true ->\n  hardware_alignof ha_env t = 1 ->\n  align_compatible_rec cenv t z.\nProof.\n  intros ? ? ? ? CENV_CONS CENV_COSU HA_ENV_CONS HA_ENV_COMPL.\n  revert z; type_induction t cenv CENV_CONS; intros.\n  + inv H.\n  + destruct s, i; inv H0;\n    econstructor; try reflexivity; apply Z.divide_1_l.\n  + destruct s; inv H0.\n  + destruct f; inv H0.\n  + inv H0.\n  + apply align_compatible_rec_Tarray.\n    intros.\n    apply IH; auto.\n  + inv H.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    eapply align_compatible_rec_Tstruct; eauto.\n    clear H H1 H2 H3 ha.\n    intros; clear H1.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      destruct H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; auto.\n      * apply IHIH; auto.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    eapply align_compatible_rec_Tunion; eauto.\n    clear H H1 H2 H3 ha.\n    intros.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      destruct H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; auto.\n      * apply IHIH; auto.\nQed.\n\nModule Type LEGAL_ALIGNAS.\n\n  Parameter legal_alignas_obs: Type.\n  Parameter legal_alignas_type: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs -> type -> legal_alignas_obs.\n  Parameter legal_alignas_composite: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs -> composite -> legal_alignas_obs.\n  Parameter legal_alignas_env: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs.\n  Parameter is_aligned_aux: legal_alignas_obs -> Z -> Z -> bool.  \n\nEnd LEGAL_ALIGNAS.\n\nModule LegalAlignasDefsGen (LegalAlignas: LEGAL_ALIGNAS).\n\n  Import LegalAlignas.\n\n  Definition legal_alignas_env_consistent (cenv: composite_env) (ha_env: PTree.t Z) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall i co la,\n      cenv ! i = Some co ->\n      la_env ! i = Some la ->\n      la = legal_alignas_composite cenv ha_env la_env co.\n\n  Definition legal_alignas_env_complete (cenv: composite_env) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall i,\n      (exists co, cenv ! i = Some co) <->\n      (exists la, la_env ! i = Some la).\n\n  Definition is_aligned cenv ha_env la_env (t: type) (ofs: Z): bool := is_aligned_aux (legal_alignas_type cenv ha_env la_env t) (hardware_alignof ha_env t) ofs.\n\n  Definition legal_alignas_env_sound (cenv: composite_env) (ha_env: PTree.t Z) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall ofs t,\n      complete_legal_cosu_type cenv t = true ->\n      is_aligned cenv ha_env la_env t ofs = true ->\n      align_compatible_rec cenv t ofs.\n\nEnd LegalAlignasDefsGen.\n\nModule Type LEGAL_ALIGNAS_FACTS.\n\n  Declare Module LegalAlignas: LEGAL_ALIGNAS.\n  Module LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\n  Export LegalAlignas LegalAlignasDefs.\n\n  Axiom legal_alignas_env_consistency: forall cenv ha_env,\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\n\n  Axiom legal_alignas_env_completeness: forall cenv ha_env,\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\n\n  Axiom legal_alignas_soundness: forall cenv ha_env la_env,\n    composite_env_consistent cenv ->\n    composite_env_complete_legal_cosu_type cenv ->\n    hardware_alignof_env_consistent cenv ha_env ->\n    hardware_alignof_env_complete cenv ha_env ->\n    legal_alignas_env_consistent cenv ha_env la_env ->\n    legal_alignas_env_complete cenv la_env ->\n    legal_alignas_env_sound cenv ha_env la_env.\n\nEnd LEGAL_ALIGNAS_FACTS.\n\nModule LegalAlignasStrict <: LEGAL_ALIGNAS.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nDefinition legal_alignas_obs: Type := bool.\n\nFixpoint legal_alignas_type (la_env: PTree.t bool) t: bool :=\n  (hardware_alignof ha_env t <=? alignof cenv t) &&\n  match t with\n  | Tarray t' _ _ => (sizeof cenv t' mod alignof cenv t' =? 0) && legal_alignas_type la_env t'\n  | Tstruct id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | Tunion id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | _ => match access_mode t with\n         | By_value ch => true\n         | _ => false\n         end\n  end.\n\nFixpoint legal_alignas_members (la_env: PTree.t bool) (m: members): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (legal_alignas_type la_env t) && (legal_alignas_members la_env m')\n  end.\n\nDefinition legal_alignas_composite (la_env: PTree.t bool) (co: composite): bool :=\n  legal_alignas_members la_env (co_members co).\n\nDefinition legal_alignas_env: PTree.t bool :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t bool) => let (i, co) := ic in let T := T0 in PTree.set i (legal_alignas_composite T co) T) (PTree.empty _) l.\n\nDefinition is_aligned_aux (b: bool) (ha: Z) (ofs: Z) := b && ((ofs mod ha) =? 0).\n\nEnd legal_alignas.\n\nEnd LegalAlignasStrict.\n\nModule LegalAlignasStrictFacts: LEGAL_ALIGNAS_FACTS with Module LegalAlignas := LegalAlignasStrict.\n\nModule LegalAlignas := LegalAlignasStrict.\nModule LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\nExport LegalAlignas LegalAlignasDefs.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nLemma aux1: forall T co,\n      (fix fm (l : list (ident * type * bool)) : bool :=\n          match l with\n          | nil => true\n          | (_, _, la) :: l' => la && fm l'\n          end)\n         (map\n            (fun it0 : positive * type =>\n             let (i0, t0) := it0 in\n             (i0, t0,\n             type_func.F\n               (fun t : type =>\n                (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | By_reference => false\n                | By_copy => false\n                | By_nothing => false\n                end)\n               (fun (la : bool) (t : type) (n : Z) (a0 : attr) =>\n                (hardware_alignof ha_env (Tarray t n a0) <=? alignof cenv (Tarray t n a0)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n               (fun (la : bool) (id : ident) (a0 : attr) =>\n                (hardware_alignof ha_env (Tstruct id a0) <=? alignof cenv (Tstruct id a0)) && la)\n               (fun (la : bool) (id : ident) (a0 : attr) =>\n                (hardware_alignof ha_env (Tunion id a0) <=? alignof cenv (Tunion id a0)) && la) T t0)) (co_members co)) =\n      legal_alignas_composite cenv ha_env T co.\nProof.\n  intros; unfold legal_alignas_composite, legal_alignas_members, legal_alignas_type.\n  induction (co_members co) as [| [i t] ?].\n  + auto.\n  + simpl.\n    f_equal; auto.\n    clear.\n    induction t; auto.\n    - simpl.\n      rewrite IHt.\n      auto.\n    - simpl.\n      destruct (T ! i); auto.\n    - simpl.\n      destruct (T ! i); auto.\nQed.\n\nLemma aux2:\n    (type_func.Env\n          (fun t : type =>\n           (hardware_alignof ha_env t <=? alignof cenv t) &&\n           match access_mode t with\n           | By_value _ => true\n           | By_reference => false\n           | By_copy => false\n           | By_nothing => false\n           end)\n          (fun (la : bool) (t : type) (n : Z) (a0 : attr) =>\n           (hardware_alignof ha_env (Tarray t n a0) <=? alignof cenv (Tarray t n a0)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n          (fun (la : bool) (id : ident) (a0 : attr) =>\n           (hardware_alignof ha_env (Tstruct id a0) <=? alignof cenv (Tstruct id a0)) && la)\n          (fun (la : bool) (id : ident) (a0 : attr) =>\n           (hardware_alignof ha_env (Tunion id a0) <=? alignof cenv (Tunion id a0)) && la)\n          (fun _ : struct_or_union =>\n           fix fm (l : list (ident * type * bool)) : bool :=\n             match l with\n             | nil => true\n             | (_, _, la) :: l' => la && fm l'\n             end) (composite_reorder.rebuild_composite_elements cenv)) =\n    legal_alignas_env cenv ha_env.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, legal_alignas_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nEnd legal_alignas.\n\nTheorem legal_alignas_env_consistency:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent bool cenv\n             (fun t => (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => (hardware_alignof ha_env (Tarray t n a) <=? alignof cenv (Tarray t n a)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n             (fun la id a => (hardware_alignof ha_env (Tstruct id a) <=? alignof cenv (Tstruct id a)) && la)\n             (fun la id a => (hardware_alignof ha_env (Tunion id a) <=? alignof cenv (Tunion id a)) && la)\n             (fun _ =>\n                fix fm (l: list (ident * type * bool)): bool :=\n                match l with\n                | nil => true\n                | (_, _, la) :: l' => la && (fm l')\n                end)\n             H\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  hnf; intros.\n  specialize (HH _ _ la H0 H1).\n  rewrite HH, aux1; auto.\nQed.\n\nTheorem legal_alignas_env_completeness:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_complete bool cenv\n             (fun t => (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => (hardware_alignof ha_env (Tarray t n a) <=? alignof cenv (Tarray t n a)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n             (fun la id a => (hardware_alignof ha_env (Tstruct id a) <=? alignof cenv (Tstruct id a)) && la)\n             (fun la id a => (hardware_alignof ha_env (Tunion id a) <=? alignof cenv (Tunion id a)) && la)\n             (fun _ =>\n                fix fm (l: list (ident * type * bool)): bool :=\n                match l with\n                | nil => true\n                | (_, _, la) :: l' => la && (fm l')\n                end)\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nSection soundness.\n\nContext (cenv: composite_env)\n        (ha_env: PTree.t Z)\n        (la_env: PTree.t bool)\n        (CENV_CONSI: composite_env_consistent cenv)\n        (CENV_COSU: composite_env_complete_legal_cosu_type cenv)\n        (HA_ENV_CONSI: hardware_alignof_env_consistent cenv ha_env)\n        (HA_ENV_COMPL: hardware_alignof_env_complete cenv ha_env)\n        (LA_ENV_CONSI: legal_alignas_env_consistent cenv ha_env la_env)\n        (LA_ENV_COMPL: legal_alignas_env_complete cenv la_env).\n\nLemma legal_alignas_type_divide: forall t,\n  legal_alignas_type cenv ha_env la_env t = true ->\n  (hardware_alignof ha_env t | alignof cenv t).\nProof.\n  intros.\n  assert (hardware_alignof ha_env t <=? alignof cenv t = true).\n  {\n    destruct t; simpl in H |- *;\n    solve [inv H | rewrite andb_true_iff in H; tauto].\n  }\n  autorewrite with align in H0.\n  auto.\nQed.\n\nLemma by_value_sound:\n  forall t ofs,\n    is_aligned cenv ha_env la_env t ofs = true ->\n    (exists ch, access_mode t = By_value ch) ->\n    align_compatible_rec cenv t ofs.\nProof.\n  intros.\n  unfold is_aligned, is_aligned_aux, legal_alignas_type, hardware_alignof in H.\n  destruct H0 as [ch ?].\n  assert ((align_chunk ch <=? alignof cenv t) && true && (ofs mod align_chunk ch =? 0) = true) by\n    (destruct t; try solve [inversion H0]; rewrite H0 in H; auto); clear H.\n  autorewrite with align in H1.\n  destruct H1 as [_ ?].\n  eapply align_compatible_rec_by_value; eauto.\nQed.\n\nTheorem legal_alignas_soundness:\n  legal_alignas_env_sound cenv ha_env la_env.\nProof.\n  pose proof CENV_COSU.\n  clear CENV_COSU H.\n  intros.\n  hnf; intros ? ? _ ?.\n  revert ofs H; type_induction t cenv CENV_CONSI; intros.\n  + inversion H.\n  + eapply by_value_sound; eauto.\n    destruct i, s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct f; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    eexists; try reflexivity.\n  + apply align_compatible_rec_Tarray; intros.\n    apply IH; clear IH.\n    unfold is_aligned, is_aligned_aux in H |- *.\n    Opaque alignof. simpl in H |- *. Transparent alignof.\n    autorewrite with align in H |- *.\n    destruct H as [[? [? ?]] ?].\n    split; auto.\n    apply Z.divide_add_r; auto.\n    apply Z.divide_mul_l.\n    clear H H3.\n    apply legal_alignas_type_divide in H2.\n    eapply Z.divide_trans; try eassumption.\n  + inv H.\n  + unfold is_aligned, is_aligned_aux in H, IH.\n    Opaque alignof. simpl in H, IH. Transparent alignof.\n    destruct (la_env ! id) as [la |] eqn:?H.\n    2: {\n      rewrite (andb_comm _ false) in H.\n      inv H.\n    }\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H0) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H1) as [ha ?].\n    rewrite H1 in IH; rewrite H2 in H.\n    rewrite (HA_ENV_CONSI id _ _ H1 H2) in H.\n    rewrite (LA_ENV_CONSI id _ _ H1 H0) in H.\n    eapply align_compatible_rec_Tstruct; [eassumption | intros].\n    pose proof field_offset_aligned _ _ _ _ _ H4 H3.\n    unfold field_offset in H4.\n    clear H0 H1 H2 H4.\n    unfold legal_alignas_composite in *.\n    induction IH as [| [i t] ?].\n    - inv H3.\n    - Opaque alignof. simpl in H0, H3, H. Transparent alignof.\n      if_tac in H3.\n      * subst i0; inv H3.\n        apply H0; simpl.\n        autorewrite with align in H |- *.\n        destruct H as [[_ [? ?]] [? ?]].\n        split; auto.\n        apply Z.divide_add_r; auto.\n        apply legal_alignas_type_divide in H.\n        apply Z.divide_trans with (alignof cenv t0); try eassumption.\n      * apply IHIH; auto.\n        autorewrite with align in H |- *.\n        split; [split |]; tauto.\n  + unfold is_aligned, is_aligned_aux in H, IH.\n    Opaque alignof. simpl in H, IH. Transparent alignof.\n    destruct (la_env ! id) as [la |] eqn:?H.\n    2:{\n      rewrite (andb_comm _ false) in H.\n      inv H.\n    }\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H0) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H1) as [ha ?].\n    rewrite H1 in IH; rewrite H2 in H.\n    rewrite (HA_ENV_CONSI id _ _ H1 H2) in H.\n    rewrite (LA_ENV_CONSI id _ _ H1 H0) in H.\n    eapply align_compatible_rec_Tunion; [eassumption | intros].\n    clear H0 H1 H2.\n    unfold legal_alignas_composite in *.\n    induction IH as [| [i t] ?].\n    - inv H3.\n    - Opaque alignof. simpl in H0, H3, H. Transparent alignof.\n      if_tac in H3.\n      * subst i0; inv H3.\n        apply H0; simpl.\n        autorewrite with align in H |- *.\n        destruct H as [[_ [? ?]] [? ?]].\n        split; auto.\n      * apply IHIH; auto.\n        autorewrite with align in H |- *.\n        split; [split |]; tauto.\nQed.\n\nEnd soundness.\n\nEnd LegalAlignasStrictFacts.\n\nModule LegalAlignasStrong <: LEGAL_ALIGNAS.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nDefinition legal_alignas_obs: Type := bool.\n\nFixpoint legal_alignas_type (la_env: PTree.t bool) t: bool :=\n  match t with\n  | Tarray t' _ _ => (sizeof cenv t' mod hardware_alignof ha_env t' =? 0) && legal_alignas_type la_env t'\n  | Tstruct id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | Tunion id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | _ => match access_mode t with\n         | By_value ch => true\n         | _ => false\n         end\n  end.\n\nFixpoint legal_alignas_struct_members_rec (la_env: PTree.t bool) (m: members) (pos: Z): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && (legal_alignas_type la_env t) && (legal_alignas_struct_members_rec la_env m' (align pos (alignof cenv t) + sizeof cenv t))\n  end.\n\nFixpoint legal_alignas_union_members_rec (la_env: PTree.t bool) (m: members): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (legal_alignas_type la_env t) && (legal_alignas_union_members_rec la_env m')\n  end.\n\nDefinition legal_alignas_composite (la_env: PTree.t bool) (co: composite): bool :=\n  match co_su co with\n  | Struct => legal_alignas_struct_members_rec la_env (co_members co) 0\n  | Union => legal_alignas_union_members_rec la_env (co_members co)\n  end.\n\nDefinition legal_alignas_env: PTree.t bool :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t bool) => let (i, co) := ic in let T := T0 in PTree.set i (legal_alignas_composite T co) T) (PTree.empty _) l.\n\nDefinition is_aligned_aux (b: bool) (ha: Z) (ofs: Z) := b && ((ofs mod ha) =? 0).\n\nEnd legal_alignas.\n\nEnd LegalAlignasStrong.\n\nModule LegalAlignasStrongFacts: LEGAL_ALIGNAS_FACTS with Module LegalAlignas := LegalAlignasStrong.\n\nModule LegalAlignas := LegalAlignasStrong.\nModule LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\nExport LegalAlignas LegalAlignasDefs.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nLemma aux1: forall T co,\n  match co_su co with\n  | Struct =>\n      (fix fm (pos : Z) (l : list (ident * type * bool)) {struct l} : bool :=\n         match l with\n         | nil => true\n         | (_, t, la) :: l' =>\n             (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) &&\n             la && fm (align pos (alignof cenv t) + sizeof cenv t) l'\n         end) 0\n  | Union =>\n      fix fm (l : list (ident * type * bool)) : bool :=\n        match l with\n        | nil => true\n        | (_, _, la) :: l' => la && fm l'\n        end\n  end\n    (map\n       (fun it0 : positive * type =>\n        let (i0, t0) := it0 in\n        (i0, t0,\n        type_func.F\n          (fun t : type =>\n           match access_mode t with\n           | By_value _ => true\n           | By_reference => false\n           | By_copy => false\n           | By_nothing => false\n           end)\n          (fun (la : bool) (t : type) (_ : Z) (_ : attr) =>\n           (sizeof cenv t mod hardware_alignof ha_env t =? 0) && la)\n          (fun (la : bool) (_ : ident) (_ : attr) => la)\n          (fun (la : bool) (_ : ident) (_ : attr) => la) T t0)) \n       (co_members co)) = legal_alignas_composite cenv ha_env T co.\nProof.\n  intros; unfold legal_alignas_composite, legal_alignas_type.\n  destruct (co_su co).\n  {\n  generalize 0 at 2 4.\n  induction (co_members co) as [| [i t] ?]; intros.\n  + auto.\n  + simpl.\n    f_equal; [f_equal |]; auto.\n    clear.\n    induction t; auto.\n    simpl.\n    rewrite IHt.\n    auto.\n  }\n  {\n  induction (co_members co) as [| [i t] ?]; intros.\n  + auto.\n  + simpl.\n    f_equal; [f_equal |]; auto.\n    clear.\n    induction t; auto.\n    simpl.\n    rewrite IHt.\n    auto.\n  }\nQed.\n\nLemma aux2:\n    (type_func.Env\n                  (fun t : type =>\n                   match access_mode t with\n                   | By_value _ => true\n                   | By_reference => false\n                   | By_copy => false\n                   | By_nothing => false\n                   end)\n                  (fun (la : bool) (t : type) (_ : Z) (_ : attr) =>\n                   (sizeof cenv t mod hardware_alignof ha_env t =? 0) && la)\n                  (fun (la : bool) (_ : ident) (_ : attr) => la)\n                  (fun (la : bool) (_ : ident) (_ : attr) => la)\n                  (fun su : struct_or_union =>\n                   match su with\n                   | Struct =>\n                       (fix\n                        fm (pos : Z) (l : list (ident * type * bool)) {struct l} :\n                          bool :=\n                          match l with\n                          | nil => true\n                          | (_, t, la) :: l' =>\n                              (align pos (alignof cenv t)\n                               mod hardware_alignof ha_env t =? 0) && la &&\n                              fm (align pos (alignof cenv t) + sizeof cenv t) l'\n                          end) 0\n                   | Union =>\n                       fix fm (l : list (ident * type * bool)) : bool :=\n                         match l with\n                         | nil => true\n                         | (_, _, la) :: l' => la && fm l'\n                         end\n                   end) (composite_reorder.rebuild_composite_elements cenv)) =\n    legal_alignas_env cenv ha_env.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, legal_alignas_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nEnd legal_alignas.\n\nTheorem legal_alignas_env_consistency:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent bool cenv\n             (fun t =>\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => ((sizeof cenv t mod hardware_alignof ha_env t =? 0) && la))\n             (fun la id a => la)\n             (fun la id a => la)\n             (fun su =>\n                match su with\n                | Struct =>\n                   (fix fm (pos: Z) (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && la && (fm (align pos (alignof cenv t) + sizeof cenv t) l')\n                    end) 0\n                | Union =>\n                   (fix fm (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => la && (fm l')\n                    end)\n                end)\n             H\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  hnf; intros.\n  specialize (HH _ _ la H0 H1).\n  rewrite HH, <- aux1; auto.\nQed.\n\nTheorem legal_alignas_env_completeness:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_complete bool cenv\n             (fun t =>\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => ((sizeof cenv t mod hardware_alignof ha_env t =? 0) && la))\n             (fun la id a => la)\n             (fun la id a => la)\n             (fun su =>\n                match su with\n                | Struct =>\n                   (fix fm (pos: Z) (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && la && (fm (align pos (alignof cenv t) + sizeof cenv t) l')\n                    end) 0\n                | Union =>\n                   (fix fm (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => la && (fm l')\n                    end)\n                end)\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nSection soundness.\n\nContext (cenv: composite_env)\n        (ha_env: PTree.t Z)\n        (la_env: PTree.t bool)\n        (CENV_CONSI: composite_env_consistent cenv)\n        (CENV_COSU: composite_env_complete_legal_cosu_type cenv)\n        (HA_ENV_CONSI: hardware_alignof_env_consistent cenv ha_env)\n        (HA_ENV_COMPL: hardware_alignof_env_complete cenv ha_env)\n        (LA_ENV_CONSI: legal_alignas_env_consistent cenv ha_env la_env)\n        (LA_ENV_COMPL: legal_alignas_env_complete cenv la_env).\n\nLemma by_value_sound:\n  forall t ofs,\n    is_aligned cenv ha_env la_env t ofs = true ->\n    (exists ch, access_mode t = By_value ch) ->\n    align_compatible_rec cenv t ofs.\nProof.\n  intros.\n  unfold is_aligned, is_aligned_aux, legal_alignas_type, hardware_alignof in H.\n  destruct H0 as [ch ?].\n  assert ((ofs mod align_chunk ch =? 0) = true) by\n    (destruct t; try solve [inversion H0]; rewrite H0 in H; auto); clear H.\n  autorewrite with align in H1.\n  eapply align_compatible_rec_by_value; eauto.\nQed.\n\nTheorem legal_alignas_soundness:\n  legal_alignas_env_sound cenv ha_env la_env.\nProof.\n  intros.\n  hnf; intros.\n  revert ofs H H0; type_induction t cenv CENV_CONSI; intros.\n  + inversion H0.\n  + eapply by_value_sound; eauto.\n    destruct i, s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct f; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    eexists; try reflexivity.\n  + apply align_compatible_rec_Tarray; intros.\n    apply IH; clear IH; [auto |].\n    unfold is_aligned, is_aligned_aux in H0 |- *.\n    simpl in H0 |- *.\n    autorewrite with align in H0 |- *.\n    destruct H0 as [[? ?] ?].\n    split; auto.\n    apply Z.divide_add_r; auto.\n    apply Z.divide_mul_l; auto.\n  + inv H.\n  + unfold is_aligned, is_aligned_aux in H0, IH.\n    simpl in H, H0, IH.\n    destruct (la_env ! id) as [la |] eqn:?H; [| inv H0].\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H1) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H2) as [ha ?].\n    pose proof CENV_COSU _ _ H2.\n    rewrite H2 in IH, H; rewrite H3 in H0.\n    rewrite (HA_ENV_CONSI id _ _ H2 H3) in H0.\n    rewrite (LA_ENV_CONSI id _ _ H2 H1) in H0.\n    autorewrite with align in H0 |- *.\n    destruct H0.\n    unfold legal_alignas_composite in H0.\n    destruct (co_su co); [| inv H].\n    eapply align_compatible_rec_Tstruct; [eassumption | intros].\n    unfold field_offset in H7.\n    clear H H1 H2 H3.\n    revert H0 H4 H5 H6 H7; generalize 0;\n    induction IH as [| [i t] ?]; intros.\n    - inv H6.\n    - simpl in H, H0, H4, H5, H6, H7.\n      if_tac in H6.\n      * subst i0; inv H6; inv H7.\n        autorewrite with align in H4, H5, H0 |- *.\n        destruct H0 as [[? ?] ?], H4 as [? ?], H5 as [? ?].\n        apply H; simpl; [tauto |].\n        autorewrite with align.\n        split; auto.\n        apply Z.divide_add_r; auto.\n      * autorewrite with align in H0, H4, H5.\n        destruct H4, H5.\n        apply (IHIH (align z (alignof cenv t) + sizeof cenv t)); auto.\n        tauto.\n  + unfold is_aligned, is_aligned_aux in H0, IH.\n    simpl in H, H0, IH.\n    destruct (la_env ! id) as [la |] eqn:?H; [| inv H0].\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H1) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H2) as [ha ?].\n    pose proof CENV_COSU _ _ H2.\n    rewrite H2 in IH, H; rewrite H3 in H0.\n    rewrite (HA_ENV_CONSI id _ _ H2 H3) in H0.\n    rewrite (LA_ENV_CONSI id _ _ H2 H1) in H0.\n    autorewrite with align in H0 |- *.\n    destruct H0.\n    unfold legal_alignas_composite in H0.\n    destruct (co_su co); [inv H |].\n    eapply align_compatible_rec_Tunion; [eassumption | intros].\n    clear H H1 H2 H3.\n    revert H0 H4 H5 H6;\n    induction IH as [| [i t] ?]; intros.\n    - inv H6.\n    - simpl in H, H0, H4, H5, H6.\n      if_tac in H6.\n      * subst i0; inv H6.\n        autorewrite with align in H4, H5, H0 |- *.\n        destruct H0 as [? ?], H4 as [? ?], H5 as [? ?].\n        apply H; simpl; [tauto |].\n        autorewrite with align.\n        split; auto.\n      * autorewrite with align in H0, H4, H5.\n        destruct H4, H5.\n        apply IHIH; auto.\n        tauto.\nQed.\n\nEnd soundness.\n\nEnd LegalAlignasStrongFacts.\n\nModule Export LegalAlignasFacts := LegalAlignasStrongFacts.\n\n\n\n", "meta": {"author": "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/align_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.19316867229373744}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import LemmaNat Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import opcode_synthesis verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\nFrom bpf.verifier.simulation Require Import correct_bpf_verifier_opcode_alu64_imm  correct_bpf_verifier_opcode_alu64_reg correct_bpf_verifier_opcode_alu32_imm correct_bpf_verifier_opcode_alu32_reg correct_bpf_verifier_opcode_branch_imm correct_bpf_verifier_opcode_branch_reg correct_bpf_verifier_opcode_load_imm correct_bpf_verifier_opcode_load_reg correct_bpf_verifier_opcode_store_imm correct_bpf_verifier_opcode_store_reg.\n\n\n(**\nCheck bpf_verifier_aux2.\nbpf_verifier_aux2\n     : nat -> nat -> nat -> int64 -> M state.state bool\n\n*)\nOpen Scope Z_scope.\nLemma bpf_verifier_aux2_match:\n  forall c\n    (Hopcode : match Nat.land c 7 with\n      | 0%nat => LD_IMM\n      | 1%nat => LD_REG\n      | 2%nat => ST_IMM\n      | 3%nat => ST_REG\n      | 4%nat => ALU32\n      | 5%nat => Branch\n      | 7%nat => ALU64\n      | _ => ILLEGAL\n      end = ILLEGAL),\n        7 <> (Z.land (Z.of_nat c) 7) /\\\n        4 <> (Z.land (Z.of_nat c) 7) /\\\n        5 <> (Z.land (Z.of_nat c) 7) /\\\n        0 <> (Z.land (Z.of_nat c) 7) /\\\n        1 <> (Z.land (Z.of_nat c) 7) /\\\n        2 <> (Z.land (Z.of_nat c) 7) /\\\n        3 <> (Z.land (Z.of_nat c) 7).\nProof. \n  intros.\n  change 0 with (Z.of_nat 0%nat).\n  change 1 with (Z.of_nat 1%nat).\n  change 2 with (Z.of_nat 2%nat).\n  change 3 with (Z.of_nat 3%nat).\n  change 4 with (Z.of_nat 4%nat).\n  change 5 with (Z.of_nat 5%nat).\n  change 7 with (Z.of_nat 7%nat).\n  rewrite land_land.\n  remember (Nat.land c 7) as n.\n  do 8 (destruct n; [inversion Hopcode; split_conj | ]).\n  repeat (split; [intro Hfalse; apply Nat2Z.inj in Hfalse; inversion Hfalse |]).\n  intro Hfalse; apply Nat2Z.inj in Hfalse; inversion Hfalse.\nQed.\n\n\n\nSection Bpf_verifier_aux2.\n  Context {S:special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(nat:Type); (nat:Type); (nat:Type); (int64:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := bpf_verifier_aux2.\n\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_bpf_verifier_aux2.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (nat_correct x))\n      (dcons (fun x => StateLess _ (nat_correct x))\n        (dcons (fun x => StateLess _ (opcode_correct x))\n          (dcons (fun x => StateLess _ (int64_correct x))\n            (DList.DNil _)))).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x => StateLess _ (bool_correct x).\n\n  Instance correct_function_bpf_verifier_aux2 : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f, bpf_verifier_aux2.\n    simpl.\n    unfold INV.\n    destruct nat_to_opcode eqn: Hopcode.\n    - (**r ALU64 *)\n      eapply correct_statement_switch with (n:= 7).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        * correct_forward.\n\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_alu64_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * correct_forward.\n\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_alu64_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * intros.\n          get_invariant _op.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, opcode_correct in c3.\n          destruct c3 as (Hc3_eq & Hc3_range).\n          rewrite <- Hc3_eq.\n          simpl.\n          unfold Cop.sem_cmp, Cop.sem_binarith; simpl.\n          unfold Cop.sem_and, Cop.sem_binarith; simpl.\n          unfold Cop.sem_cast; simpl.\n          match goal with\n          | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n            change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n          end.\n          fold Int.zero.\n          f_equal.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 7%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r ALU32 *)\n      eapply correct_statement_switch with (n:= 4).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        * correct_forward.\n\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_alu32_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * correct_forward.\n\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_alu32_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * intros.\n          get_invariant _op.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, opcode_correct in c3.\n          destruct c3 as (Hc3_eq & Hc3_range).\n          rewrite <- Hc3_eq.\n          simpl.\n          unfold Cop.sem_cmp, Cop.sem_binarith; simpl.\n          unfold Cop.sem_and, Cop.sem_binarith; simpl.\n          unfold Cop.sem_cast; simpl.\n          match goal with\n          | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n            change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n          end.\n          fold Int.zero.\n          f_equal.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 4%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r Branch *)\n      eapply correct_statement_switch with (n:= 5).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        * correct_forward.\n\n          get_invariant _pc.\n          get_invariant _len.\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::v1::v2::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1, p2, p3.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_branch_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * correct_forward.\n\n          get_invariant _pc.\n          get_invariant _len.\n          get_invariant _op.\n          get_invariant _ins.\n          exists (v::v0::v1::v2::nil).\n          split.\n          unfold map_opt, exec_expr. rewrite p0, p1, p2, p3.\n          reflexivity.\n          intros; simpl.\n          unfold eval_inv in *.\n          intuition congruence.\n          intros.\n\n          correct_forward.\n          get_invariant _b.\n          exists v.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, match_res.\n          unfold eval_inv, correct_bpf_verifier_opcode_branch_imm.match_res in c3.\n          split; [reflexivity|].\n          split; [assumption|].\n          unfold bool_correct in c3.\n          rewrite c3.\n          split. unfold Cop.sem_cast; simpl.\n          destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n          intros.\n          constructor.\n          destruct x; reflexivity.\n        * intros.\n          get_invariant _op.\n          unfold exec_expr.\n          rewrite p0.\n          unfold eval_inv, opcode_correct in c3.\n          destruct c3 as (Hc3_eq & Hc3_range).\n          rewrite <- Hc3_eq.\n          simpl.\n          unfold Cop.sem_cmp, Cop.sem_binarith; simpl.\n          unfold Cop.sem_cast; simpl.\n          match goal with\n          | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n            change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n          end.\n          unfold Cop.sem_and, Cop.sem_binarith; simpl.\n          unfold Cop.sem_cast; simpl.\n          match goal with\n          | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n            change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n          end.\n          fold Int.zero.\n          f_equal.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 5%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r LD_IMM *)\n      eapply correct_statement_switch with (n:= 0).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _op.\n        get_invariant _ins.\n        exists (v::v0::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0, p1.\n        reflexivity.\n        intros; simpl.\n        unfold eval_inv in *.\n        intuition congruence.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, match_res.\n        unfold eval_inv, correct_bpf_verifier_opcode_load_imm.match_res in c3.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold bool_correct in c3.\n        rewrite c3.\n        split. unfold Cop.sem_cast; simpl.\n        destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 0%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r LD_REG *)\n      eapply correct_statement_switch with (n:= 1).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _op.\n        get_invariant _ins.\n        exists (v::v0::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0, p1.\n        reflexivity.\n        intros; simpl.\n        unfold eval_inv in *.\n        intuition congruence.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, match_res.\n        unfold eval_inv, correct_bpf_verifier_opcode_load_reg.match_res in c3.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold bool_correct in c3.\n        rewrite c3.\n        split. unfold Cop.sem_cast; simpl.\n        destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 1%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r ST_IMM *)\n      eapply correct_statement_switch with (n:= 2).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _op.\n        get_invariant _ins.\n        exists (v::v0::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0, p1.\n        reflexivity.\n        intros; simpl.\n        unfold eval_inv in *.\n        intuition congruence.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, match_res.\n        unfold eval_inv, correct_bpf_verifier_opcode_store_imm.match_res in c3.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold bool_correct in c3.\n        rewrite c3.\n        split. unfold Cop.sem_cast; simpl.\n        destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 2%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r ST_REG *)\n      eapply correct_statement_switch with (n:= 3).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _op.\n        get_invariant _ins.\n        exists (v::v0::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0, p1.\n        reflexivity.\n        intros; simpl.\n        unfold eval_inv in *.\n        intuition congruence.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, match_res.\n        unfold eval_inv, correct_bpf_verifier_opcode_store_reg.match_res in c3.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold bool_correct in c3.\n        rewrite c3.\n        split. unfold Cop.sem_cast; simpl.\n        destruct x; [rewrite Int_eq_one_zero | rewrite Int.eq_true]; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (Hc3_eq & Hc3_range).\n        rewrite <- Hc3_eq.\n        simpl.\n        unfold Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        unfold nat_to_opcode in Hopcode.\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with (Z.of_nat 7%nat).\n        rewrite Int.unsigned_repr.\n        rewrite land_land.\n        remember (Nat.land c1 7) as n.\n        assert (Hc1_and: n = 3%nat). {\n          clear - Hopcode.\n          do 8 (destruct n; [try inversion Hopcode; reflexivity | ]).\n          inversion Hopcode.\n        }\n        rewrite Hc1_and.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n      + compute. intuition congruence.\n    - (**r ILLEGAL *)\n      eapply correct_statement_switch_ex.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold eval_inv, opcode_correct in c3.\n        destruct c3 as (c3 & Hc3_range).\n        exists (Z.land (Z.of_nat c1) 7).\n        split.\n        unfold exec_expr.\n        rewrite p0.\n        rewrite <- c3.\n        unfold Cop.sem_binary_operation, Cop.sem_cast; simpl.\n        unfold Cop.sem_and, Cop.sem_binarith; simpl.\n        unfold Cop.sem_cast; simpl.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?X then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X X then Z else W) with Z; simpl\n        end.\n        match goal with\n        | |- context[ if Ctypes.intsize_eq ?X ?Y then ?Z else ?W] =>\n          change (if Ctypes.intsize_eq X Y then Z else W) with W; simpl\n        end.\n        rewrite Int.zero_ext_and.\n        rewrite Int.and_assoc.\n        change (two_p 8 - 1) with 255.\n        change (Int.and (Int.repr 7) (Int.repr 255)) with (Int.repr 7).\n        unfold Int.and.\n        change (Int.unsigned (Int.repr 7)) with 7.\n        rewrite Int.unsigned_repr.\n        reflexivity.\n        change Int.max_unsigned with 4294967295.\n        lia.\n        lia.\n        split.\n\n        change Int.modulus with 4294967296.\n        change 7 with (Z.of_nat 7%nat).\n        rewrite land_land.\n        assert (Hland7: (Nat.land 7 c1 <= 7)%nat) by apply land_bound.\n        rewrite Nat.land_comm.\n        lia.\n\n        unfold select_switch.\n        unfold select_switch_case.\n        unfold nat_to_opcode in Hopcode.\n        apply bpf_verifier_aux2_match in Hopcode.\n        destruct Hopcode as (Hfirst & Hopcode). eapply Coqlib.zeq_false in Hfirst. rewrite Hfirst; clear Hfirst.\n        repeat match goal with\n        | H: ?X <> ?Y /\\ _ |- context[Coqlib.zeq ?X ?Y] =>\n            destruct H as (Hfirst & H);\n            eapply Coqlib.zeq_false in Hfirst; rewrite Hfirst; clear Hfirst\n        end.\n        eapply Coqlib.zeq_false in Hopcode; rewrite Hopcode; clear Hopcode.\n        (* default *)\n        simpl.\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        exists (Vint (Int.repr 0)).\n        unfold exec_expr.\n        split; [reflexivity|].\n        unfold eval_inv, match_res, bool_correct, Int.one.\n        split; [reflexivity|].\n        split; [reflexivity|].\n        intros.\n        constructor.\n        reflexivity.\nQed.\n\nEnd Bpf_verifier_aux2.\n\nClose Scope Z_scope.\n\nExisting Instance correct_function_bpf_verifier_aux2.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_bpf_verifier_aux2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19313712891689486}}
{"text": "\n(* Implementation of Bitcoin Protocol *)\n(* Does not compile yet - as probability issues have not been resolved. *)\n\n\n\nFrom mathcomp.ssreflect Require Import\n     ssreflect ssrbool ssrnat eqtype fintype choice ssrfun seq path finfun.\n\n\nFrom mathcomp.ssreflect\nRequire Import tuple.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Coq.Program.Equality.\n\n\n\nFrom Probchain Require Import\n     BlockChain AddressList OracleState\n     BlockMap InvMisc Parameters FixedList FixedMap.\n\nSet Implicit Arguments.\n\nParameter adversary_internal_state : finType.\nParameter adversary_internal_initial_state : adversary_internal_state.\nParameter adversary_internal_state_change :\n  {ffun adversary_internal_state -> adversary_internal_state}.\nParameter adversary_internal_insert_transaction:\n  {ffun adversary_internal_state ->\n   {ffun Transaction -> adversary_internal_state}}.\nParameter adversary_internal_insert_chain:\n  {ffun adversary_internal_state ->\n   {ffun BlockChain -> adversary_internal_state}}.\nParameter adversary_internal_generate_block:\n  {ffun adversary_internal_state ->\n   {ffun MessagePool ->\n    (adversary_internal_state * (Nonce * Hashed * BlockRecord))}}.\nParameter adversary_internal_provide_block_hash_result:\n  {ffun adversary_internal_state ->\n   {ffun (Nonce * Hashed * BlockRecord) ->\n    {ffun Hashed -> adversary_internal_state}}}.\nParameter adversary_internal_send_chain:\n  {ffun adversary_internal_state -> (adversary_internal_state * BlockChain)}.\nParameter adversary_internal_send_transaction:\n  {ffun adversary_internal_state ->\n   (adversary_internal_state * Transaction * AddressList)}.\n\n\n\nDefinition to_addr (value : 'I_n_max_actors) : Addr :=\n  ((widen_ord (m:=n_max_actors + 2))^~ value) (leq_addr 2 n_max_actors).\n\n \nDefinition verify_hash (blk : Block) (oracle : OracleState) : option Hashed := \n   oraclestate_find (block_nonce blk, block_link blk, block_records blk) oracle.\n\n(*\n  An adversary's state consists of\n  1. Adversary's hidden state - can not be introspected\n  2. Adversary's state change transition\n  3. all transactions it has been delivered.\n  4. All chains it has ever seen\n  5. an extra parameter to persist proof of work calculations between rounds. \n  6. the last round it attempted a hash - it can only attempt hashing \n     if this value is less than the current round*)\n   (* Inner adversary's state, whose type cannot be introspected *)\nRecord Adversary (T : finType) := mkAdvrs {\n\n  adversary_state : T;\n(* Changing the state -- an operation provided by an adversary *) \n  adversary_state_change: {ffun T -> T}; \n\n  adversary_insert_transaction: {ffun T -> {ffun Transaction -> T}};\n  adversary_insert_chain: {ffun T -> {ffun BlockChain -> T}};\n\n  (* Required to allow adversary limited queries to the oracle*)\n  (* the adversary can propose a block to be hashed*)\n  adversary_generate_block:\n    {ffun T -> {ffun MessagePool -> (T * (Nonce * Hashed * BlockRecord))}};\n\n  (* the result of the hash is returned to the adversary through this method -\n     is the block necassary? *)\n  (* it has to be structured this way, as we can not allow the adversary\n     access to the oracle directly*)\n  adversary_provide_block_hash_result:\n    {ffun T -> {ffun (Nonce * Hashed * BlockRecord) -> {ffun Hashed -> T}}};\n\n  (* Required to allow the adversary to broadcast chains *)\n  (* I'm not sure how assertions about the blockchain being\n     unable to randomly guess valid blockchains will be made*)\n  adversary_send_chain: {ffun T -> (T * BlockChain)};\n  adversary_send_transaction: {ffun T -> (T * Transaction * AddressList)};\n\n  (* adversary_local_transaction_pool: seq Transaction; *)\n  (* adversary_local_message_pool: seq BlockChain; *)\n\n  (* Additional info *)\n  adversary_last_hashed_round: ordinal N_rounds;\n}.\n\n\n\nDefinition initAdversary  := \n  mkAdvrs \n    adversary_internal_initial_state \n    adversary_internal_state_change \n    adversary_internal_insert_transaction\n    adversary_internal_insert_chain\n    adversary_internal_generate_block\n    adversary_internal_provide_block_hash_result\n    adversary_internal_send_chain\n    adversary_internal_send_transaction\n    (Ordinal valid_N_rounds).\n\nDefinition Adversary_prod  (a : Adversary adversary_internal_state) :=\n  (adversary_state a,\n  adversary_state_change a,\n  adversary_insert_transaction  a,\n  adversary_insert_chain  a,\n  adversary_generate_block  a,\n  adversary_provide_block_hash_result  a,\n  adversary_send_chain a,\n  adversary_send_transaction a,\n  adversary_last_hashed_round a).\n\n\nDefinition prod_Adversary (pair : \n  (adversary_internal_state  * \n  {ffun adversary_internal_state  -> adversary_internal_state } * \n  {ffun adversary_internal_state  ->\n   {ffun Transaction -> adversary_internal_state }} *\n  {ffun adversary_internal_state  ->\n   {ffun BlockChain -> adversary_internal_state }} *\n  {ffun adversary_internal_state  ->\n   {ffun MessagePool ->\n    adversary_internal_state  * (Nonce * Hashed * BlockRecord)}} *\n  {ffun adversary_internal_state  ->\n   {ffun Nonce * Hashed * BlockRecord ->\n    {ffun Hashed -> adversary_internal_state }}} *\n  {ffun adversary_internal_state  -> adversary_internal_state  * BlockChain} * \n  {ffun adversary_internal_state   ->\n   (adversary_internal_state   * Transaction * AddressList)} *\n  ordinal N_rounds\n  )) := \n  let: (adversary_state ,\n    adversary_state_change ,\n    adversary_insert_transaction  ,\n    adversary_insert_chain  ,\n    adversary_generate_block  ,\n    adversary_provide_block_hash_result  ,\n    adversary_send_chain ,\n    adversary_send_transaction ,\n    adversary_last_hashed_round) := pair in\n    mkAdvrs \n      adversary_state \n      adversary_state_change \n      adversary_insert_transaction  \n      adversary_insert_chain  \n      adversary_generate_block  \n      adversary_provide_block_hash_result  \n      adversary_send_chain \n      adversary_send_transaction \n      adversary_last_hashed_round.\n\n\n\nLemma adversary_cancel : cancel Adversary_prod prod_Adversary .\nProof.\n  by case.\nQed.\n\nDefinition adversary_eqMixin :=\n  CanEqMixin adversary_cancel.\nCanonical adversary_eqType :=\n  Eval hnf in EqType (Adversary adversary_internal_state) adversary_eqMixin.\n\nDefinition adversary_choiceMixin :=\n  CanChoiceMixin adversary_cancel.\nCanonical adversary_choiceType :=\n  Eval hnf in\n    ChoiceType (Adversary adversary_internal_state) adversary_choiceMixin.\n\nDefinition adversary_countMixin :=\n  CanCountMixin adversary_cancel.\nCanonical adversary_countType :=\n  Eval hnf in\n    CountType (Adversary adversary_internal_state) adversary_countMixin.\n\nDefinition adversary_finMixin :=\n  CanFinMixin adversary_cancel.\nCanonical adversary_finType :=\n  Eval hnf in FinType (Adversary adversary_internal_state) adversary_finMixin.\n\n\nCanonical adversary_of_eqType :=\n  Eval hnf in [eqType of (Adversary adversary_internal_state)].\nCanonical adversary_of_choiceType :=\n  Eval hnf in [choiceType of (Adversary adversary_internal_state)].\nCanonical adversary_of_countType :=\n  Eval hnf in [countType of (Adversary adversary_internal_state)].\nCanonical adversary_of_finType :=\n  Eval hnf in [finType of (Adversary adversary_internal_state)].\n\n\n\n\nDefinition local_TransactionPool :=\n  fixlist Transaction Honest_TransactionPool_size.\n\n\n\n\n(* A node's local state consists of \n    1. it's currently held chain\n    2. all transactions it has been delivered \n    3. all chains that it has been sent since it's last activation\n    4. an extra parameter to persist proof of work calculations\n       between rounds. *)\nRecord LocalState := mkLclSt {\n  honest_current_chain: BlockChain;\n  honest_local_transaction_pool: local_TransactionPool;\n  honest_local_message_pool:\n    fixlist [eqType of BlockChain] Honest_MessagePool_size ;\n}.\n\nDefinition initLocalState := mkLclSt\n                               initBlockChain\n                               (fixlist_empty\n                                  Transaction Honest_TransactionPool_size)\n                               (fixlist_empty\n                                  [eqType of BlockChain] Honest_MessagePool_size).\n\nDefinition LocalState_prod (ls : LocalState) :=\n  (honest_current_chain ls,\n  honest_local_transaction_pool ls,\n  honest_local_message_pool ls).\n\nDefinition prod_LocalState pair :=\n  let: (honest_current_chain,\n  honest_local_transaction_pool,\n  honest_local_message_pool) := pair in \n  mkLclSt\n    honest_current_chain\n    honest_local_transaction_pool\n    honest_local_message_pool.\n\n    \nLemma localstate_cancel : cancel LocalState_prod prod_LocalState .\nProof.\n  by case.\nQed.\n\nDefinition localstate_eqMixin :=\n  CanEqMixin localstate_cancel.\nCanonical localstate_eqType :=\n  Eval hnf in EqType (LocalState) localstate_eqMixin.\n\nDefinition localstate_choiceMixin :=\n  CanChoiceMixin localstate_cancel.\nCanonical localstate_choiceType :=\n  Eval hnf in ChoiceType (LocalState) localstate_choiceMixin.\n\nDefinition localstate_countMixin :=\n  CanCountMixin localstate_cancel.\nCanonical localstate_countType :=\n  Eval hnf in CountType (LocalState) localstate_countMixin.\nDefinition localstate_finMixin :=\n  CanFinMixin localstate_cancel.\nCanonical localstate_finType :=\n  Eval hnf in FinType (LocalState) localstate_finMixin.\n\n\nCanonical local_state_of_eqType := Eval hnf in [eqType of LocalState].\nCanonical local_state_of_choiceType := Eval hnf in [choiceType of LocalState].\nCanonical local_state_of_countType := Eval hnf in [countType of LocalState].\nCanonical local_state_of_finType := Eval hnf in [finType of LocalState].\n\n\n\n(* GlobalState consists of \n      1. A sequence of LocalStates, and a boolean representing whether\n         the state is corrupted\n      2. An address representing the currently executing entity -\n         when addr == length of local states + 1,\n         the round is complete\n      3. A number representing the current round\n*)\nRecord GlobalState := mkGlobalState\n{\n  global_local_states: n_max_actors.-tuple\n                                   [eqType of\n                                           ([eqType of\n                                                    LocalState] *\n                                            [eqType of bool])];\n  global_adversary: Adversary adversary_internal_state ;\n  global_currently_active: Addr;\n  global_current_round: (ordinal N_rounds);\n}.\n\n\n\nNotation \"[ g '.actors]'\" := (global_local_states g).\nNotation \"[ g '.adv]'\" := (global_adversary g).\nNotation \"[ g '.#active]'\" := (global_currently_active g).\nNotation \"[ g '.#round]'\" := (global_current_round g).\n\nDefinition initLocalStates := \n        Tuple \n          (size_ncons_nil (initLocalState, false) n_max_actors ).\n\n\n\nDefinition initGlobalState : GlobalState := mkGlobalState\n  initLocalStates\n  initAdversary\n  (Ordinal (ltn_addr _ valid_n_max_actors))\n  (Ordinal valid_N_rounds).\n\nDefinition GlobalState_prod (g : GlobalState) :=\n  (global_local_states g,\n  global_adversary g,\n  global_currently_active g,\n  global_current_round g).\n\n\nDefinition prod_GlobalState pair :=\n  let: ( local_states, adversary, \n        currently_active, current_round) := pair in\n        mkGlobalState\n          local_states\n          adversary\n          currently_active\n          current_round.\n        \n\nLemma globalstate_cancel : cancel GlobalState_prod prod_GlobalState .\nProof.\n  by case.\nQed.\n\nDefinition globalstate_eqMixin :=\n  CanEqMixin globalstate_cancel.\nCanonical globalstate_eqType :=\n  Eval hnf in EqType (GlobalState) globalstate_eqMixin.\n\nDefinition globalstate_choiceMixin :=\n  CanChoiceMixin globalstate_cancel.\nCanonical globalstate_choiceType :=\n  Eval hnf in ChoiceType (GlobalState) globalstate_choiceMixin.\n\nDefinition globalstate_countMixin :=\n  CanCountMixin globalstate_cancel.\nCanonical globalstate_countType :=\n  Eval hnf in CountType (GlobalState) globalstate_countMixin.\nDefinition globalstate_finMixin :=\n  CanFinMixin globalstate_cancel.\nCanonical globalstate_finType :=\n  Eval hnf in FinType (GlobalState) globalstate_finMixin.\n\n\nCanonical global_state_of_eqType := Eval hnf in [eqType of GlobalState].\nCanonical global_state_of_choiceType := Eval hnf in [choiceType of GlobalState].\nCanonical global_state_of_countType := Eval hnf in [countType of GlobalState].\nCanonical global_state_of_finType := Eval hnf in [finType of GlobalState].\n\n\n\n\nRecord World := mkWorld {\n  world_global_state: GlobalState; \n  (* the transaction pools contains all sent transactions *)\n  world_transaction_pool: TransactionPool; \n  (* the inflight pool contains all messages sent in the round *)\n  world_inflight_pool: MessagePool;\n  (* the world message pool is a queue of messages sent in the past round - once\n     the length exceeds delta, the last entry is removed,\n     and all messages delivered *)\n  (* thus this achieves the simulation of a delta delay *)\n  world_message_pool: fixlist [eqType of MessagePool] delta;\n  (* represents the shared oracle state *)\n  world_hash: OracleState;\n  (* Contains every block seen *)\n  world_block_history: BlockMap;\n  (* Contains every chain ever seen *)\n  world_chain_history: fixlist [eqType of BlockChain ] ChainHistory_size;\n  (* Contains the number of messages sent by the\n     adversary for the current round *)\n  world_adversary_message_quota: (ordinal Adversary_max_Message_sends);\n  (* Contains the number of transactions sent by the adversary\n     for the current round *)\n  world_adversary_transaction_quota: (ordinal Adversary_max_Transaction_sends);\n  (* Contains the number of transactions sent by honest players *)\n  world_honest_transaction_quota: (ordinal Honest_max_Transaction_sends);\n\n  (* Contains a listing of the held chain at each round for each actor *)\n  world_adoption_history:\n    fixlist\n      [eqType of (BlockChain * ordinal N_rounds * 'I_n_max_actors)]\n      (n_max_actors * N_rounds);\n  (* contains a trace of the message_pool queue - contains\n            the inflight pool at the end of round,\n            the message queue after insertion,\n            the messages delivered\n   *)\n  world_message_trace :  fixlist [eqType of (MessagePool * (fixlist [eqType of MessagePool] delta) * MessagePool)] N_rounds.+1\n}.\n\n\nNotation \"[ w '.state]'\" := (world_global_state w).\nNotation \"[ w '.tx_pool]'\" := (world_transaction_pool w).\nNotation \"[ w '.inflight]'\" := (world_inflight_pool w).\nNotation \"[ w '.messages]'\" := (world_message_pool w).\nNotation \"[ w '.oracle]'\" := (world_hash w).\nNotation \"[ w '.blocks]'\" := (world_block_history w).\nNotation \"[ w '.chains]'\" := (world_chain_history w).\nNotation \"[ w '.#adv_msgs]'\" := (world_adversary_message_quota w).\nNotation \"[ w '.#adv_tx]'\" := (world_adversary_transaction_quota w).\nNotation \"[ w '.#hon_tx]'\" := (world_honest_transaction_quota w).\nNotation \"[ w '.adopt_history]'\" := (world_adoption_history w).\nNotation \"[ w '.msg_trace]'\" := (world_message_trace w).\n\n\nDefinition initMessagePool := (fixlist_empty [eqType of Message] MessagePool_length).\nDefinition initWorldMessagePool := (fixlist_empty [eqType of MessagePool] delta).\nDefinition initWorldChainHistory :=\n  (fixlist_empty [eqType of BlockChain] ChainHistory_size).\nDefinition initWorldAdoptionHistory :=\n  (fixlist_empty\n     [eqType of (BlockChain * ordinal N_rounds * 'I_n_max_actors)]\n     (n_max_actors * N_rounds)).\n\nDefinition initMessageTrace :=\n  (fixlist_empty\n\n     [eqType of (MessagePool * (fixlist [eqType of MessagePool] delta) * MessagePool) ]\n     N_rounds.+1).\n\n\nDefinition initWorld := \n    mkWorld   \n      initGlobalState \n      initTransactionPool \n      initMessagePool  \n      initWorldMessagePool \n      oraclestate_new \n      BlockMap_new \n      initWorldChainHistory\n       (Ordinal valid_Adversary_max_Message_sends)\n       (Ordinal valid_Adversary_max_Transaction_sends)\n       (Ordinal valid_Honest_max_Transaction_sends)\n       initWorldAdoptionHistory\n       initMessageTrace.\n\nDefinition World_prod w :=\n  (world_global_state w,\n  world_transaction_pool w,\n  world_inflight_pool w,\n  world_message_pool w,\n  world_hash w,\n  world_block_history w,\n  world_chain_history w,\n  world_adversary_message_quota w,\n  world_adversary_transaction_quota w,\n  world_honest_transaction_quota w,\n  world_adoption_history w,\n  world_message_trace w).\n\n\nDefinition prod_World pair :=\n  let: (world_global_state,\n  world_transaction_pool,\n  world_inflight_pool,\n  world_message_pool,\n  world_hash,\n  world_block_history,\n  world_chain_history,\n  world_adversary_message_quota,\n  world_adversary_transaction_quota,\n  world_honest_transaction_quota,\n  world_adoption_history,\n  world_message_trace) := pair in\n    mkWorld\n      world_global_state\n      world_transaction_pool\n      world_inflight_pool\n      world_message_pool\n      world_hash\n      world_block_history\n      world_chain_history\n      world_adversary_message_quota\n      world_adversary_transaction_quota\n      world_honest_transaction_quota\n      world_adoption_history\n      world_message_trace.\n\n\n\nLemma world_cancel : cancel World_prod prod_World .\nProof.\n  by case.\nQed.\n\nDefinition world_eqMixin :=\n  CanEqMixin world_cancel.\nCanonical world_eqType :=\n  Eval hnf in EqType (World) world_eqMixin.\n\nDefinition world_choiceMixin :=\n  CanChoiceMixin world_cancel.\nCanonical world_choiceType :=\n  Eval hnf in ChoiceType (World) world_choiceMixin.\n\nDefinition world_countMixin :=\n  CanCountMixin world_cancel.\nCanonical world_countType :=\n  Eval hnf in CountType (World) world_countMixin.\nDefinition world_finMixin :=\n  CanFinMixin world_cancel.\nCanonical world_finType :=\n  Eval hnf in FinType (World) world_finMixin.\n\n\nCanonical world_of_eqType := Eval hnf in [eqType of World].\nCanonical world_of_choiceType := Eval hnf in [choiceType of World].\nCanonical world_of_countType := Eval hnf in [countType of World].\nCanonical world_of_finType := Eval hnf in [finType of World].\n\n\n\n\n(* A round is complete if the currently_active index is one greater\n  than the length of the actors array *)\nDefinition round_ended (w: World) :=\n (nat_of_ord (global_currently_active (world_global_state w)) == n_max_actors + 1) && \n  ((global_current_round (world_global_state w)) + 1 < N_rounds).\n\nDefinition world_current_addr (w : World) :=\n  global_currently_active (world_global_state w).\n\nDefinition world_adversary (w : World) :=\n  global_adversary (world_global_state w).\n\nDefinition world_actors (w : World) :=\n  global_local_states (world_global_state w).\n\nDefinition world_round_no (w : World) :=\n  nat_of_ord (global_current_round (world_global_state w)).\n\nDefinition no_corrupted_players (state: GlobalState) :=\n    let: actors := global_local_states state in \n      length (filter (fun actor => actor.2) actors).\n\n\n\n(* A given world step is an honest activation if the current address\n   is to a node which has not been corrupted *)\nDefinition honest_activation (state: GlobalState) : option 'I_n_max_actors :=\n    match state with\n    | {|\n      global_local_states := actors;\n      global_currently_active := active\n    |} =>\n        (* if the index is valid *)\n      (if (active < n_max_actors)%N as b\n          return ((active < n_max_actors)%N = b -> option 'I_n_max_actors)\n          then\n            fun H : (active < n_max_actors)%N = true =>\n              (* if the actor is corrupted *)\n              if \n                (tnth actors (Ordinal (n:=n_max_actors) (m:=active) H)).2\n              (* it is not an honest activation *)\n              then None\n              (* otherwise return an index into the list *)\n              else Some (Ordinal (n:=n_max_actors) (m:=active) H)\n        (* if the index is invalid, return None as well *)\n       else fun _ : (active < n_max_actors)%N = false => None)\n        (erefl (active < n_max_actors)%N)\n    end. \n\n\n\n(* A given world step is an adversarial activation if the current address\n   is to a node which has been corrupted, or the current address is equal to\n   the length of the list \n   this is based on the fact that the bitcoin paper states that in the round\n   robin scheduling, once all nodes have activated, the adversary activates *)\nLemma adversary_activation (state: GlobalState): bool.\n    case state => actors _ active _.\n    case (active < n_max_actors) eqn: H.\n      case (tnth actors (Ordinal H)) => _ is_corrupted.\n      exact is_corrupted.\n    case (n_max_actors == active) eqn: H'.\n      exact true.\n    exact false.\nDefined. \n\n\nLemma round_in_range (active: Addr) :\n  nat_of_ord active != n_max_actors.+1 -> active.+1 < n_max_actors + 2.\nProof.\n  move=> H.\n  case active eqn: Haddr.\n  rewrite neq_ltn in H.\n  move: H => /orP H.\n  case H => [Hlt | Hgt].\n  rewrite -ltnS in Hlt.\n  rewrite -(addn1 n_max_actors) in Hlt.\n  by rewrite -(addn1 (n_max_actors + _)) -addnA in Hlt.\n\n  rewrite -ltnS in Hgt.\n  inversion Hgt.\n  rewrite -(addn1 m) in H1.\n  rewrite -addn2 in H1.\n  suff Hn a b : a < b -> b < a + 1 -> False.\n  move: (Hn _ _ i H1) => //=.\n  clear active m i Haddr H Hgt H1.\n  move=> Ha_ltb Hb_lta.\n  rewrite addnS addn0 ltnS in Hb_lta.\n  move: (leq_ltn_trans Hb_lta Ha_ltb) => H.\n  by rewrite ltnn in H.\nQed.\n\n(* Implements the round robin - each actor activated once a round mechanism \n   Once the last actor, and then the adversary has activated, the function does\n   not do anything else *)\nAbout ssr_suff.\nLocate \"[ eta _ ]\".\n\nDefinition update_round (state : GlobalState) : GlobalState :=\n  (* \n    the following should be equivalent to this\n    definition below:\n\n    (most of the work comes from proving that, \n    if nat_of_ord active != n_max_actors + 1\n    then active.+1 is in ordinal (n_max_actors + 2))\n\n  let: actors := global_local_states state in \n  let: active := global_currently_active state in\n  let: adversary := global_adversary state in\n  let: round := global_current_round state in\n  if ((nat_of_ord active) == (fixlist_length actors).+1) \n  then state\n  else mkGlobalState actors adversary active.+1 round. *)\n\nmatch state with\n| {| global_local_states := actors;\n     global_adversary := adversary;\n     global_currently_active :=\n  active; global_current_round := round |} =>\n    let b := nat_of_ord active == n_max_actors.+1 in\n    let H : (nat_of_ord active == n_max_actors.+1) = b := erefl b in\n    (if b as b0 return ((nat_of_ord active == n_max_actors.+1) = _ -> GlobalState)\n     then fun prf : (nat_of_ord active == n_max_actors.+1) = _ => state\n     else fun prf : (nat_of_ord active == n_max_actors.+1) = false =>\n           (fun H1 : nat_of_ord active != n_max_actors.+1 =>\n            ssr_suff (active.+1 < n_max_actors + 2)\n              (fun H' : active.+1 < n_max_actors + 2 =>\n                {|\n                    global_local_states := actors;\n                    global_adversary := adversary;\n                    global_currently_active :=\n                      Ordinal (n:=n_max_actors + 2) (m:=active.+1) H';\n                    global_current_round := round\n                |}\n              ) (round_in_range active H1)\n           ) (introN eqP (elimTF eqP prf))) H\nend .\n\n\nDefinition next_round  (state : GlobalState) : GlobalState .\n  (* \n    Once again: here is the definition of the function,\n    := let: ((actors, adversary), active, round) := state in \n      if (eqn active n_max_actors.+1) \n      then ((actors, adversary), 0, round.+1)\n      else state. *)\n      case state => actors adversary active round.\n      case ((nat_of_ord active) == (n_max_actors).+1)  eqn:H.\n      (* we can only update if the current round is less than the maximum rounds*)\n        case ((global_current_round state).+1 < N_rounds) eqn: Hact.\n        exact\n          (mkGlobalState actors adversary\n                         (Ordinal (ltn_addr _ valid_n_max_actors))\n                         (Ordinal Hact)).\n        (* if it isn't less than the maximum rounds, just return the state *)\n        exact (state).\n      (* if next round is called on a state, that has not finished execution,\n         it does nothing*)\n      exact (state).\nDefined.\n\n\n\n(* insert the corresponding message into the recipient's message pool *)\nDefinition insert_message \n  (addr: 'I_n_max_actors) \n  (bc: BlockChain) \n  (state: GlobalState) : GlobalState := \n    let: actors := global_local_states state in\n    let: adversary := global_adversary state in\n    let: active := global_currently_active state in\n    let: round := global_current_round state in\n    let: default := (initLocalState, false) in\n    let: (actor, corrupted) := nth default actors addr in \n    if corrupted \n    then\n      let: old_adv_state := adversary_state adversary in\n      let: new_adv_state := (adversary_insert_chain adversary) old_adv_state bc in\n      let: new_adversary := \n                            mkAdvrs\n                              new_adv_state\n                              (adversary_state_change adversary)\n                              (adversary_insert_transaction adversary)\n                              (adversary_insert_chain adversary)\n                              (adversary_generate_block adversary)\n                              (adversary_provide_block_hash_result adversary)\n                              (adversary_send_chain adversary)\n                              (adversary_send_transaction adversary)\n                              (adversary_last_hashed_round adversary) in\n      (mkGlobalState actors new_adversary active round)\n  else\n    let: current_chain := honest_current_chain actor in\n    let: local_transaction_pool := honest_local_transaction_pool actor in\n    (* Check whether the blockchain is already in the pool *)\n    let: message_pool := (honest_local_message_pool actor) in\n    if fixlist_contains bc message_pool then\n      state\n    else\n      let: new_message_pool := fixlist_insert message_pool bc in\n      let: new_actor := mkLclSt current_chain local_transaction_pool new_message_pool in\n      let: new_actors := set_tnth actors (new_actor, corrupted) addr in\n      (mkGlobalState new_actors adversary active round) .\n\n\nDefinition insert_multicast_message \n  (addresses: AddressList) \n  (bc: BlockChain) \n  (initial_state: GlobalState) : GlobalState := \n      foldr\n        (fun addr state => insert_message addr bc state)\n        initial_state\n        (AddressList_unwrap addresses).\n \n\n\n(* insert the corresponding message into every actor's message pool *)\nDefinition broadcast_message\n      (bc : BlockChain) (initial_state: GlobalState) : GlobalState :=\n  foldr\n    (fun index state => \n      let: actors := global_local_states state in\n      let: adversary := global_adversary state in\n      let: active := global_currently_active state in\n      let: round := global_current_round state in\n      let: (actor, is_corrupt) := (tnth actors index) in\n      if is_corrupt then\n        state\n      else\n        insert_message index bc state)\n    initial_state\n    (ord_enum  n_max_actors).\n    \n\n\n\n(* for each message in messages, send to corresponding actor *)\nDefinition deliver_messages\n  (messages : MessagePool) \n  (state : GlobalState) :  GlobalState :=\n  foldr \n    (fun (msg : Message) (st: GlobalState) => \n      match msg with\n      | MulticastMsg addr bc => insert_multicast_message addr bc st \n      | BroadcastMsg bc => broadcast_message bc st \n      end) \n    state \n    (fixlist_unwrap messages).\n\n\nDefinition update_message_pool_queue\n           (message_list_queue:\n              fixlist\n                [eqType of MessagePool] delta)\n           (new_message_list : MessagePool)\n  : (MessagePool * (fixlist [eqType of MessagePool] delta)) :=\n  let: (new_message_list, oldest_message_list) :=\n     @fixlist_enqueue _ _ (Some new_message_list) message_list_queue in\n  match oldest_message_list with\n    | None => (initMessagePool, new_message_list)\n    | Some message_list => (message_list, new_message_list)\n  end.\n\n\nDefinition update_adversary_round\n           (adversary : Adversary adversary_internal_state)\n           (round : 'I_N_rounds) : Adversary adversary_internal_state :=\n  mkAdvrs\n    (adversary_state adversary)\n    (adversary_state_change adversary)\n    (adversary_insert_transaction adversary)\n    (adversary_insert_chain adversary)\n    (adversary_generate_block adversary)\n    (adversary_provide_block_hash_result adversary)\n    (adversary_send_chain adversary)\n    (adversary_send_transaction adversary)\n    round.\n\n\n\n\n    \n\nDefinition validate_blockchain_links\n           (bc : BlockChain) (oracle_state : OracleState) : bool :=\n  match fixlist_unwrap bc with\n    | [::] => true (* Vacuously true *)\n    | h :: t =>\n        let: (_, result) := \n        foldr\n          (fun pred_block last_pair  => \n            let: (block, has_failed) := last_pair in\n            (* if the foldr has alreday seen a failure*)\n            if has_failed\n              (* then just propagate the accumulator, no changes needed*)\n              then (pred_block, has_failed)\n              else\n              (* otherwise, check that the link of the current block is equal to\n                that of the current_blocks hash *)\n                match verify_hash pred_block oracle_state with\n                  | None => (pred_block, true)\n                  | Some(hash_value) => \n                    if\n                      (block_link block == hash_value)\n                        && (hash_value < T_Hashing_Difficulty)\n                        then (pred_block, false)\n                        else (pred_block, true)\n                end\n          )\n          (h, false)  \n          t\n          in \n          ~~ result\n  end.\n\nDefinition validate_blockchain\n           (bc : BlockChain) (oracle_state: OracleState) : bool :=\n  (* a blockchain is valid if the links are well formed *)\n  validate_blockchain_links bc oracle_state && \n  (* and all transactions are valid *)\n  validate_transactions (BlockChain_unwrap bc).\n  \n(* finds the longest valid chain for a node *)\nDefinition honest_max_valid\n           (state: LocalState) (oracle_state: OracleState) : BlockChain :=\n  foldr \n  (fun (new_chain best_chain : BlockChain) => \n    (* First check whether the chain is valid *)\n    if validate_blockchain new_chain oracle_state\n      (* If it's longer, adopt it *)\n      then if length new_chain > length best_chain\n          then new_chain\n          (* in cases where the lengths are equal... *)\n          else if length new_chain == length best_chain\n            (* Use the equiv of FCR to conclude *)\n            then if BlockChain_compare_lt best_chain new_chain\n              then new_chain\n              else best_chain\n            else best_chain\n      else best_chain \n  )\n  (honest_current_chain state)\n  (fixlist_unwrap (honest_local_message_pool state)).\n\n\n(* Bitcoin Backbone Paper - Pg.29\n  Parses v as a sequence of transactions and returns the largest subsequence\n  that is valid with respect to the chain, and whoose transactions are not\n  included in xc\n\n  the following function, when given an honest node's transaction pool and chain, \n  may return a blockrecord (list containing x < MAX_BLOCK_LENGTH) and the\n  transaction pool with the corresponding values removed\n*)\nDefinition find_maximal_valid_subset\n           (transactions : local_TransactionPool)\n           (blk: BlockChain) : (BlockRecord * local_TransactionPool) :=\n(* naive approach - iterate through transactions and only include those that\n   are valid specifically it's naive because it assumes that all transactions\n   are delivered in order (i.e if invalid, reordering the sequence won't change\n   whether it's valid or not) but I believe this is a correct assumption as\n  transactions are delivered immediately *)\n   let chain_transactions := BlockChain_unwrap blk in\n   foldr\n      (fun index prev_pair => \n            let: (already_included, remaining) := prev_pair in\n            let: o_transaction := fixlist_get_nth remaining index in\n            if fixlist_length already_included == Transactions_per_block \n              (* if the block record is full, just skip to the end*)\n              then (already_included, remaining) \n              (* if it isn't full, *)\n              else match o_transaction with\n                | None =>  (already_included, remaining)\n                (* and the nth field is present*)\n                | Some transaction =>\n                  if Transaction_valid transaction\n                                       ((fixlist_unwrap already_included)\n                                          ++ chain_transactions)\n\n                    (* and the transaction is valid*)\n                    (* insert it into the blockrecord *)\n                  then\n                    (fixlist_insert\n                       already_included transaction,\n                     fixlist_remove remaining index )\n                    (* otherwise don't*)\n                    else (already_included, remaining)\n                end)\n      (initBlockRecord, transactions)\n      (iota 0 TransactionPool_length).\n\n\nDefinition retrieve_head_link\n           (b : BlockChain) (oracle_state : OracleState) : option Hashed :=\n  match fixlist_unwrap b with\n    | [::] => Some (Ordinal (ltn0Sn _))\n    | h :: t => verify_hash h oracle_state\n  end.\n\n\n    \n\nDefinition update_transaction_pool\n           (addr : 'I_n_max_actors)\n           (initial_state : LocalState)\n           (transaction_pool: TransactionPool) : LocalState :=\n  foldr\n  (fun (txMsg : TransactionMessage) state => \n      match txMsg with\n        | BroadcastTransaction tx => \n             if tx \\in fixlist_unwrap (honest_local_transaction_pool state) \n              then state\n              else \n                mkLclSt \n                  (honest_current_chain state)\n                  (fixlist_insert (honest_local_transaction_pool state) tx)\n                  (honest_local_message_pool state)\n        | MulticastTransaction (tx, recipients) =>\n          if addr \\in (AddressList_unwrap recipients)\n            then if tx \\in fixlist_unwrap (honest_local_transaction_pool state) \n              then state\n              else \n                mkLclSt \n                  (honest_current_chain state)\n                  (fixlist_insert (honest_local_transaction_pool state) tx)\n                  (honest_local_message_pool state)\n            else state\n      end)\n  initial_state\n  (fixlist_unwrap transaction_pool).\n\nDefinition update_adversary_transaction_pool\n           (initial_adv: Adversary adversary_internal_state)\n           (transaction_pool: TransactionPool)\n  : Adversary adversary_internal_state:=\n    foldr \n      (fun (txMsg : TransactionMessage) adversary => \n      let: adv_state := adversary_state adversary in\n      let: partial_adv := (adversary_insert_transaction adversary) adv_state in\n        match txMsg with\n          | BroadcastTransaction tx => \n            let: new_adv_state := partial_adv tx in\n                            mkAdvrs\n                              new_adv_state\n                              (adversary_state_change adversary)\n                              (adversary_insert_transaction adversary)\n                              (adversary_insert_chain adversary)\n                              (adversary_generate_block adversary)\n                              (adversary_provide_block_hash_result adversary)\n                              (adversary_send_chain adversary)\n                              (adversary_send_transaction adversary)\n                              (adversary_last_hashed_round adversary) \n          | MulticastTransaction (tx, _) =>\n            let: new_adv_state := partial_adv tx in\n                            mkAdvrs\n                              new_adv_state\n                              (adversary_state_change adversary)\n                              (adversary_insert_transaction adversary)\n                              (adversary_insert_chain adversary)\n                              (adversary_generate_block adversary)\n                              (adversary_provide_block_hash_result adversary)\n                              (adversary_send_chain adversary)\n                              (adversary_send_transaction adversary)\n                              (adversary_last_hashed_round adversary) \n        end)\n      initial_adv\n      (fixlist_unwrap transaction_pool).\n\n\n\n(* Implementation of the bitcoin backbone protocol *)\n\n\n\n\n(* Fixpoint reachable_internal (w w' : World) (schedule : seq RndGen) : Prop :=\n  match schedule with\n    | [::] => w = w'\n    | h :: t' => exists (y : World), world_step w y h /\\ reachable_internal y w' t'\n    end.\n\n(* Clone of function from toychain *)\nDefinition reachable (w w' : World) : Prop :=\n  exists (schedule : seq RndGen), reachable_internal w w' schedule.\n *)\nDefinition adversarial_minority (w : World) :=\n  no_corrupted_players (world_global_state w) <= t_max_corrupted.\n \n\n\n\nDefinition block_hash_round (b : Block) (w : World) :=\n  match BlockMap_find b (world_block_history w) with\n    | Some (is_corrupt, hash_round) => Some(hash_round)\n    | None => None\n    end.\n\nDefinition block_is_adversarial (b : Block) (w : World) :=\n  match BlockMap_find b (world_block_history w) with\n    | Some (is_corrupt, hash_round) => Some(is_corrupt)\n    | None => None\n    end.\n\n\nDefinition successful_round_internal (bh : BlockMap) (r : nat) : bool :=\n  length\n    (filter\n      (fun block_pair =>\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && (~~ is_corrupt))\n      (BlockMap_records bh)) > 0.\n\nDefinition successful_round (w : World) (r : nat) : bool :=\n  length\n    (filter\n      (fun block_pair =>\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && (~~ is_corrupt))\n      (BlockMap_records (world_block_history w))) > 0.\n\nLemma successful_round_internalP (w : World) r :\n  successful_round w r = successful_round_internal [w.blocks] r.\n  by rewrite /successful_round/successful_round_internal.\nQed.\n\n\nLemma successful_round_rangeP w r : (r >= N_rounds) -> ~~ successful_round w r.\n  move=> Hltn.\n  rewrite /successful_round.\n  move: (BlockMap_records_roundP (world_block_history w)) => /allP Hall.\n  rewrite -eqn0Ngt -length_sizeP size_filter.\n  apply/eqP; apply/has_countPn; apply/hasPn => r' Hrin.\n  move: (Hall r' Hrin). clear Hall. clear Hrin.\n  move: r' => [iscrpt or'] Hrlt; rewrite negb_and; apply/orP; left.\n  apply/eqP => Hreq; move: Hltn Hrlt; rewrite Hreq => /leq_ltn_trans H /H.\n  by rewrite ltnn.\nQed.\n\n\n\nDefinition unsuccessful_round_internal (bh : BlockMap) (r : nat) :=\n  length\n    (filter\n      (fun block_pair =>\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && (~~ is_corrupt))\n      (BlockMap_records bh)) == 0.\n\n\n\nDefinition unsuccessful_round (w : World) (r : nat) :=\n  length\n    (filter\n      (fun block_pair =>\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && (~~ is_corrupt))\n      (BlockMap_records (world_block_history w))) == 0.\n\nLemma unsuccessful_round_internalP (w : World) r :\n  unsuccessful_round w r = unsuccessful_round_internal [w.blocks] r.\n  by rewrite /unsuccessful_round/unsuccessful_round_internal.\nQed.\n\n\n\n\n\nLemma successful_roundP w r : successful_round w r = ~~ unsuccessful_round w r.\nProof.\n  by rewrite /successful_round/unsuccessful_round lt0n//=.\nQed.\n\nLemma unsuccessful_roundP w r : unsuccessful_round w r = ~~ successful_round w r.\nProof.\n  by rewrite /successful_round/unsuccessful_round eqn0Ngt.\nQed.\n\n\n\n\nDefinition uniquely_successful_round (w : World) (r : nat) :=\n  length\n    (filter\n      (fun block_pair =>\n\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && (~~ is_corrupt))\n      (BlockMap_records (world_block_history w))) == 1.\n\nLemma uniquely_successful_roundP w r :\n  uniquely_successful_round w r -> successful_round w r.\nProof.\n    by rewrite\n         /successful_round/successful_round_internal/uniquely_successful_round\n    => /eqP ->.\nQed.\n\n\nDefinition bounded_successful_round_internal (bh : BlockMap) (r : nat) :=\n  (all (fun r' => unsuccessful_round_internal bh r') (itoj (r + 1 - delta ) (r)))\n    && successful_round_internal bh r.\n\n\nDefinition bounded_successful_round (w : World) (r : nat) :=\n  (all (fun r' => unsuccessful_round w r') (itoj (r + 1 - delta ) (r)))\n    && successful_round w r.\n\nLemma bounded_successful_round_internalP (w : World) (r : nat) :\n  bounded_successful_round w r = bounded_successful_round_internal [w.blocks] r.\nProof.\n  by rewrite/bounded_successful_round/bounded_successful_round_internal//=.\nQed.\n\nLemma bounded_successful_round_forall w r :\n  bounded_successful_round w r -> forall r',\n    ((r - delta).+1 <= r' < r) -> unsuccessful_round w r'.\nProof.\n  case Heqn: (delta == 0).\n    move/eqP: Heqn => ->.\n    move=>Hbr r' /andP [].\n    by move=>/ltn_trans H /H ; rewrite subn0 ltnn.\n  move/negP/negP: Heqn.\n  rewrite -lt0n => Hdelta.\n  case  Heqnr: (r == 0).\n    move/eqP: Heqnr => ->.\n    rewrite sub0n.\n    move=>Hbr r' /andP [].\n    by move=>/ltn_trans H /H ; rewrite ltnn.\n  move/negP/negP: Heqnr.\n  rewrite -lt0n => Hr.\n\n  rewrite /bounded_successful_round => /andP [].\n  move=>/allP Hbs Hsc r' /andP [Hltr Hgtr].\n  apply Hbs.\n  rewrite /itoj.\n  rewrite mem_iota.\n  apply/andP; split.\n  rewrite -ltnS.\n  rewrite addn1.\n  case Hltd: (delta <= r).\n  by rewrite subSn //=.\n  move/negP/negP: Hltd.\n  rewrite -ltnNge.\n  by rewrite -subn_eq0 => /eqP ->.\n  rewrite subnKC //=.\n  rewrite addn1.\n  case Hltd: (delta <= r).\n  rewrite subSn //=.\n  by move: (ltn_trans Hltr Hgtr).\n  move/negP/negP: Hltd.\n  rewrite -ltnNge.\n  by rewrite -subn_eq0 => /eqP ->.\nQed.\n\nLemma bounded_successful_round_rangeP w r :\n  (r >= N_rounds) -> ~~ bounded_successful_round w r.\n  move=> Hltn.\n  rewrite /bounded_successful_round negb_and.\n  by apply/orP; right; apply successful_round_rangeP.\nQed.\n\n\n\n\nLemma bounded_successful_round_exists w r :\n  (exists r', ((r - delta).+1 <= r' < r) && successful_round w r') ->\n  ~~ bounded_successful_round w r.\nProof.\n  move=> [r' /andP [ /andP [Hltr Hgt] Hsuc]].\n  rewrite /bounded_successful_round.\n  rewrite negb_and ;apply/orP.\n  left.\n  apply /allPn.\n  exists r'; last first.\n  by rewrite -successful_roundP.\n  rewrite /itoj.\n  rewrite mem_iota.\n  apply/andP; split.\n  move: Hltr; rewrite addn1.\n  case Hltd: (delta <= r).\n  by rewrite subSn //=.\n  by move/negP/negP: Hltd; rewrite -ltnNge; rewrite -subn_eq0 => /eqP ->.\n  rewrite subnKC //=.\n  rewrite addn1.\n  case Hltd: (delta <= r).\n  rewrite subSn //=.\n  by move: (ltn_trans Hltr Hgt).\n  move/negP/negP: Hltd.\n  rewrite -ltnNge.\n  by rewrite -subn_eq0 => /eqP ->.\nQed.\n\n\n\n\nLemma bounded_successful_round_lim_base w : bounded_successful_round w 0 -> forall r',\n      (0 < r' < delta) -> ~~ bounded_successful_round w r'.\nProof.\n  move=> /andP [_ Hsuc] r'.\n  move=>/andP [Hgt0 Hltd].\n  rewrite /bounded_successful_round.\n  rewrite negb_and.\n  apply/orP.\n  left.\n  apply /allPn.\n  exists 0.\n  rewrite mem_iota.\n  apply/andP; split.\n  rewrite addn1.\n  rewrite -subn_eq0 in Hltd.\n  by move/eqP: Hltd => -> //=.\n\n  rewrite subnKC //=.\n  rewrite addn1.\n  rewrite -subn_eq0 in Hltd.\n  by move/eqP: Hltd => -> //=.\n\n  by rewrite -successful_roundP.\nQed.\n\n\n\n \nLemma bounded_successful_round_lim w r : \n  bounded_successful_round w r -> forall r',\n    (r < r') && (r' < r + delta) -> ~~ bounded_successful_round w r'.\nProof.\n  case Hrvld : (0 < r); last first.\n  move/negP/negP: Hrvld.\n  rewrite -eqn0Ngt => /eqP ->.\n  rewrite add0n.\n  by apply bounded_successful_round_lim_base.\n\n  rewrite /bounded_successful_round => /andP [Half Hsucc].\n\n  move=> r' /andP [Hlt Hgt].\n\n  apply bounded_successful_round_exists.\n  exists r.\n  move: Hsucc Half Hlt Hgt.\n  move=> Hsucc Halft Hlt Hgt.\n\n  apply/andP; split; last first. by [].\n  apply/andP; split; last first. by [].\n    by apply ltn_subLR => //=.\nQed.\n\n\n\n\nDefinition bounded_uniquely_successful_round (w : World) (r : nat) :=\n  (all (fun r' => (unsuccessful_round w r') || (r' == r))\n       (itoj (r - delta + 1) (r + delta)))\n    && (uniquely_successful_round w r).\n\n\nDefinition adversarial_block_count (w : World) (r : nat) :=\n  length (filter\n      (fun block_pair =>\n        let: (is_corrupt, hash_round) := block_pair in  \n      (hash_round  == r) && is_corrupt)\n      (BlockMap_records (world_block_history w))).\n\nDefinition nth_block_is_honest (c : BlockChain) (n : nat) (w : World) :=\n  match (fixlist_get_nth c n) with\n    | Some value => ~~ block_is_adversarial value w\n    | None => false\n  end.\n\n\nDefinition nth_block_hashed_in_a_uniquely_successful_round\n           (w : World) (chain : BlockChain) (n : nat) :=\n      let: o_block := (fixlist_get_nth chain n) in\n      match o_block with\n        | None => None \n        | Some block => \n          let: round := block_hash_round block w in\n          Some(bounded_uniquely_successful_round w round)\n        end.\n    \nDefinition nth_block_is_adversarial (w : World) (chain : BlockChain) (n : nat) :=\n      let: o_block := (fixlist_get_nth chain n) in\n      match o_block with\n        | None => None\n        | Some block => block_is_adversarial block w\n        end.\n \n\nDefinition nth_block_equals\n           (w : World) (chain : BlockChain) (n : nat) (block : option Block) :=\n      let: o_block := (fixlist_get_nth chain n) in\n      o_block == block.\n      \nDefinition nth_block (w : World) (chain : BlockChain) (n : nat) :=\n  (fixlist_get_nth chain n).\n\n\n\nDefinition actor_n_chain_length (w : World) (n : 'I_n_max_actors) : nat :=\n  let: (actor, is_corrupted) :=\n     tnth (global_local_states (world_global_state w)) n in\n  fixlist_length (honest_current_chain actor) .\n\nDefinition world_round (w : World) : nat := \n  let: state := world_global_state w in\n  global_current_round state.\n\n\nDefinition actor_n_is_corrupt_internal_unwrap\n           (actors : n_max_actors.-tuple\n                                 [eqType of\n                                         ([eqType of LocalState] *\n                                          [eqType of bool])])\n           (n: 'I_n_max_actors) : bool :=\n  let: (actor, is_corrupted) := tnth  actors n in\n  is_corrupted.\n\nDefinition actor_n_is_corrupt_internal\n           (gs : GlobalState) (n: 'I_n_max_actors) : bool :=\n  let: (actor, is_corrupted) := tnth  (global_local_states gs) n in\n  is_corrupted.\n\n\nLemma actor_n_is_corrupt_unwrapP (gs:GlobalState) (n:'I_n_max_actors) :\n  actor_n_is_corrupt_internal gs n =\n  actor_n_is_corrupt_internal_unwrap [gs.actors] n.\nProof.\n  by rewrite/actor_n_is_corrupt_internal//=.\nQed.\n\n\nDefinition actor_n_is_corrupt (w:World) (n:'I_n_max_actors) : bool :=\n  let: (actor, is_corrupted) := tnth\n                                  (global_local_states\n                                     (world_global_state w)) n in\n  is_corrupted.\n\nLemma actor_n_is_corrupt_internalP (w:World) (n:'I_n_max_actors) :\n    actor_n_is_corrupt w n = actor_n_is_corrupt_internal [w.state] n.\nProof.\n  by rewrite/actor_n_is_corrupt//=.\nQed.\n\n\nDefinition actor_n_is_honest_internal_unwrap\n           (actors :\n              n_max_actors.-tuple\n                          [eqType of ([eqType of LocalState] * [eqType of bool])])\n           (n: nat) : bool :=\n  let b := n < n_max_actors in\n  let H : (n < n_max_actors) = b := erefl b in\n    (if b as b0 return ((n < n_max_actors) = b0 -> bool)\n     then fun H0 : (n < n_max_actors) = true =>\n            ~~ actor_n_is_corrupt_internal_unwrap actors\n               (Ordinal (n:=n_max_actors) (m:=n) H0)\n    else xpred0) H.\n\n\nDefinition actor_n_is_honest_internal (gs: GlobalState) (n: nat) : bool :=\n  let b := n < n_max_actors in\n  let H : (n < n_max_actors) = b := erefl b in\n    (if b as b0 return ((n < n_max_actors) = b0 -> bool)\n     then fun H0 : (n < n_max_actors) = true =>\n            ~~ actor_n_is_corrupt_internal gs\n               (Ordinal (n:=n_max_actors) (m:=n) H0)\n    else xpred0) H.\n\nLemma actor_n_is_honest_unwrapP (gs: GlobalState) (n: nat) :\n  actor_n_is_honest_internal gs n =\n  actor_n_is_honest_internal_unwrap [gs.actors] n.\nProof.\n  by rewrite /actor_n_is_honest_internal//=.\nQed.\n\nDefinition actor_n_is_honest (w: World) (n: nat) : bool :=\n  let b := n < n_max_actors in\n  let H : (n < n_max_actors) = b := erefl b in\n    (if b as b0 return ((n < n_max_actors) = b0 -> bool)\n     then fun H0 : (n < n_max_actors) = true =>\n            ~~ actor_n_is_corrupt w (Ordinal (n:=n_max_actors) (m:=n) H0)\n    else xpred0) H.\n\n\n\nLemma actor_n_is_honest_internalP w n :\n  actor_n_is_honest w n = actor_n_is_honest_internal [w.state] n.\nProof.\n  by rewrite/actor_n_is_honest//=.\nQed.\n\n\n\nDefinition is_uncorrputed_actor\n           (actors: n_max_actors.-tuple\n                                [eqType of\n                                        ([eqType of LocalState] * [eqType of bool])])\n           (addr: Addr) : option ('I_n_max_actors* LocalState).\n  case addr eqn:Haddr.\n    case (m < n_max_actors) eqn: H.\n      case (tnth actors (Ordinal H)) => actor is_corrupt.\n        case is_corrupt eqn: H'.\n          (* if the actor is corrupt *)\n          exact None.\n        (* if the actor is not corrupt *)\n        exact (Some (Ordinal H, actor)).\n      (* if the address is not valid *)\n      exact None.\nDefined.\n\n\n\nDefinition adopt_at_round\n           (w' : World) (w : World) (bc : BlockChain) (agent: Addr) (r : nat) :=\n  match r with\n    | 0 => false\n    | r'.+1 => \n      if \n        (* If the two worlds represent worlds immediately after in rounds *)\n        (world_round_no w == r) && \n        (world_round_no w' == r') && \n        (* If the address is valid *)\n        (agent < n_max_actors) &&\n        (* If the agent has been activated in both rounds *)\n        (world_current_addr w  >= agent) &&\n        (world_current_addr w'  >= agent) \n      then let: (w_state, w_is_corrupt) :=\n              (nth (initLocalState, true) (world_actors w) agent) in\n           let: (w'_state, w'_is_corrupt) :=\n              (nth (initLocalState, true) (world_actors w') agent) in\n              (~~ w_is_corrupt) && (~~ w'_is_corrupt) && \n              (honest_current_chain w'_state != bc) &&\n              (honest_current_chain w_state == bc)\n        else false\n    end.\n\n\n\n\nDefinition no_adversarial_blocks' (w: World) (from to : nat) : nat:= \n  foldr (fun round acc => acc + adversarial_block_count w round) 0 (itoj from to).\n\nDefinition no_adversarial_blocks\n           (w: World) (from to : nat) : 'I_(N_rounds * n_max_actors).\n  case ((no_adversarial_blocks' w from to) < (N_rounds * n_max_actors)) eqn: H.\n  exact (Ordinal H).\n  exact (Ordinal valid_N_rounds_mul_n_max_actors).\nDefined.\n\nDefinition no_successful_rounds' (w : World) (from : nat) (to : nat) : nat :=\n  length(filter\n    (fun round => successful_round w round)\n    (itoj from to)).\n\n\nDefinition no_successful_rounds (w: World) (from to : nat) : 'I_N_rounds :=\n  let b := no_successful_rounds' w from to < N_rounds in\n  (if b as b0\n      return ((no_successful_rounds' w from to < N_rounds) = b0 -> 'I_N_rounds)\n      then fun H => Ordinal H\n      else fun _ => Ordinal valid_N_rounds) (erefl b).\n\nAbout bounded_successful_round_internal.\n\n\nDefinition no_bounded_successful_rounds'_internal (bm : BlockMap) (from to : nat) : nat :=\n  length(filter\n    (fun round => bounded_successful_round_internal bm round)\n    (itoj from to)).\n\n\nDefinition no_bounded_successful_rounds' (w : World) (from : nat) (to : nat) : nat :=\n  length(filter\n    (fun round => bounded_successful_round w round)\n    (itoj from to)).\n\nLemma no_bounded_successful_rounds'_internalP (w : World) from to :\n  no_bounded_successful_rounds' w from to =\n  no_bounded_successful_rounds'_internal [w.blocks] from to.\nProof.\n  by rewrite/no_bounded_successful_rounds'//=.\nQed.\n\nLemma valid_Sn n : n > 0 -> n.+1 > 0. by []. Qed.\n\n\n\n\nDefinition no_bounded_successful_rounds_internal\n           (bm: BlockMap) (from to : nat) : 'I_N_rounds.+1 :=\n  let b := ((no_bounded_successful_rounds'_internal bm from to) < N_rounds.+1 ) in\n  (if b as b0\n      return (((no_bounded_successful_rounds'_internal bm from to) < N_rounds.+1 ) =\n              b0 -> 'I_N_rounds.+1)\n      then fun H => Ordinal H\n      else fun _ => Ordinal (valid_Sn _ valid_N_rounds)) (erefl b).\n\n\n\nDefinition no_bounded_successful_rounds (w: World) (from to : nat) : 'I_N_rounds.+1 :=\n  let b := ((no_bounded_successful_rounds' w from to) < N_rounds.+1 ) in\n  (if b as b0 return (((no_bounded_successful_rounds' w from to) < N_rounds.+1 ) =\n                      b0 -> 'I_N_rounds.+1)\n      then fun H => Ordinal H\n      else fun _ => Ordinal (valid_Sn _ valid_N_rounds)) (erefl b).\n\n\nLemma no_bounded_successful_rounds_internalP (w : World) from to :\n  no_bounded_successful_rounds w from to =\n  no_bounded_successful_rounds_internal [w.blocks] from to.\nProof.\n  by rewrite/no_bounded_successful_rounds'//=.\nQed.\n\n\nLemma count_bounded_successful_rounds'_rangeP_weak w from to :\n  from >= N_rounds -> count [eta bounded_successful_round w] (iota from to) = 0.\n  move=> Hrlt.\n  apply has_countPn.\n  apply/hasPn => r' .\n  rewrite mem_iota => /andP .\n  move=> [Hrgtform Hrltto].\n  apply bounded_successful_round_rangeP.\n  by apply (leq_trans Hrlt).\nQed.\n\n\nLemma no_bounded_successful_rounds'_rangeP_weak w from to :\n  from >= N_rounds -> no_bounded_successful_rounds' w from to = 0.\nProof.\n  move=> Hrlt.\n  rewrite/no_bounded_successful_rounds'.\n  rewrite -length_sizeP size_filter.\n  by apply count_bounded_successful_rounds'_rangeP_weak.\nQed.\n\nLemma no_bounded_successful_rounds'_rangeP_alt w from to :\n  no_bounded_successful_rounds' w from to <= to - from.\nProof.\n  rewrite /no_bounded_successful_rounds' -length_sizeP size_filter /itoj.\n  by apply (leq_trans (count_size _ _)); rewrite size_iota //=.\nQed.\n\nLemma no_bounded_successful_rounds'_rangeP w from to :\n  0 < from ->  no_bounded_successful_rounds' w from to < N_rounds.\nProof.\n  move=> Hfrmvld.\n  move: (no_bounded_successful_rounds'_rangeP_alt w from to) => Hrng.\n  case Hlt: (to < from).\n    move: (Hlt) (Hrng) => /(ltn_addr 1).\n    rewrite addn1 -subn_eq0  subSS => /eqP ->; rewrite leqn0 => /eqP ->.\n    by exact valid_N_rounds.\n  move/negP/negP: Hlt; rewrite -leqNgt => Hlt.\n  case Hfrom: (from >= N_rounds).\n  by rewrite no_bounded_successful_rounds'_rangeP_weak //=; exact valid_N_rounds.\n  move/negP/negP: Hfrom; rewrite -ltnNge => Hfrom.\n  move: Hlt; rewrite leq_eqVlt => /orP [/eqP Htoeqf | Hlt].\n     by move: Hrng; rewrite Htoeqf subnn leqn0 => /eqP ->; exact valid_N_rounds.\n  case Hto: (to < N_rounds).\n    move/(subn_ltn_pr ): (Hto) => Ht.\n    move: (Ht from) => Hfr.\n    by apply (leq_ltn_trans Hrng).\n  move/negP/negP: Hto; rewrite -leqNgt => Hto.\n  case Htvld: (to > 0); last first.\n    move/negP/negP: Htvld; rewrite -eqn0Ngt => /eqP Heq0.\n    by move: Hto valid_N_rounds; rewrite Heq0 => /leq_ltn_trans H /H; rewrite ltnn.\n\n  rewrite /no_bounded_successful_rounds' -length_sizeP size_filter /itoj .\n  move: (Hfrom) (Hfrmvld) => /ltn_exists H /H [mid [Hmid Hmideq]]. clear H.\n  move: (Hto)  => /leq_exists [mid'].\n  rewrite -{1}Hmideq => <-.\n  rewrite addnC (addnC from) addnA -addnBA.\n  rewrite subnn addn0 addnC.\n  rewrite iota_add count_cat.\n  rewrite Hmideq.\n  rewrite (count_bounded_successful_rounds'_rangeP_weak w N_rounds).\n  rewrite addn0.\n  move: (count_size ([eta bounded_successful_round w]) (iota from mid)).\n  rewrite size_iota => /leq_ltn_trans Hltn.\n  by apply Hltn.\n  by [].\n  by [].\nQed.\n\nLemma no_bounded_successful_rounds'_rangeSP w from to :\n  no_bounded_successful_rounds' w from to < N_rounds.+1.\nProof.\n  case Hfltr: (0 < from).\n    by\n      apply (ltn_trans (no_bounded_successful_rounds'_rangeP w from to Hfltr))\n      => //=.\n  move: (no_bounded_successful_rounds'_rangeP_alt w from to) => Hrng.\n  move/negP/negP: Hfltr.\n  rewrite -eqn0Ngt => /eqP Heq0.\n  case Hto: (to < N_rounds).\n    move/(subn_ltn_pr ): (Hto) => Ht.\n    move: (Ht from) => Hfr.\n    apply (leq_ltn_trans Hrng).\n    rewrite Heq0 subn0 -(addn1 N_rounds).\n    by apply ltn_addr.\n  move/negP/negP: Hto; rewrite -leqNgt => Hto.\n  case Htvld: (to > 0); last first.\n    move/negP/negP: Htvld; rewrite -eqn0Ngt => /eqP Heq0'.\n    by rewrite Heq0 Heq0' //=.\n   \n  move: (Hto); rewrite leq_eqVlt => /orP [/eqP HNroeq| Hltn]; last first.\n    move: (Hltn) valid_N_rounds => /ltn_exists H /H [mid [Hltto Heq]].\n    rewrite -Heq.\n    rewrite Heq0.\n    rewrite /no_bounded_successful_rounds' -length_sizeP size_filter /itoj .\n    rewrite subn0 iota_add count_cat add0n addnC.\n    rewrite  count_bounded_successful_rounds'_rangeP_weak //= add0n.\n    move: (count_size [eta bounded_successful_round w] (iota 0 N_rounds)).\n    by rewrite size_iota ltnS.\n  rewrite HNroeq.\n  rewrite /no_bounded_successful_rounds' -length_sizeP size_filter /itoj .\n  rewrite Heq0 subn0.\n  move: (count_size [eta bounded_successful_round w] (iota 0 to)).\n  by rewrite size_iota ltnS.\nQed.\n\n\n\n\n\nLemma no_bounded_successful_roundsP (P : 'I_N_rounds.+1 -> Prop) w from to : \n  P (Ordinal  (valid_Sn _ valid_N_rounds)) ->\n  (forall prf :\n       ((no_bounded_successful_rounds' w from to < N_rounds.+1) = true),\n      P (Ordinal prf )) ->\n  P (no_bounded_successful_rounds w from to).\nProof.\n  move=> H0 Hind.\n  rewrite/no_bounded_successful_rounds.\n  set (Nb := ((no_bounded_successful_rounds' w from to))).\n  case Heq: (Nb >= N_rounds.+1).\n    move: (erefl _).\n    move: [eta Ordinal (n:=N_rounds.+1) (m:=Nb)].\n    rewrite leqNgt in Heq.\n    move/negP/negP: Heq.\n    rewrite -eqbF_neg => /eqP Heq.\n    by rewrite Heq.\n  move: (erefl _ ).\n  move/negP/negP: Heq.\n  rewrite -ltnNge.\n  move=> Hlt.\n  suff: [eta Ordinal (n:=N_rounds.+1) (m:=Nb)] = fun _ => Ordinal Hlt.\n  move=> ->.\n  by rewrite Hlt.\n  apply: functional_extensionality=> G.\n  by rewrite (proof_irrelevance _ Hlt G).\nQed.\n\nLemma no_bounded_successful_rounds_excl_lower w r : \n        (bounded_successful_round w r) ->\n          no_bounded_successful_rounds' w (r + 1 - delta) r = 0.\nProof.\n  rewrite/bounded_successful_round => /andP [] /allP Hall Hsucc.\n  rewrite /no_bounded_successful_rounds'.\n  rewrite -!length_sizeP !size_filter  !has_countPn //=.\n  apply /hasPn => r' Hrrng; rewrite /bounded_successful_round negb_and.\n  by apply/orP; right; rewrite -unsuccessful_roundP; apply Hall.\nQed.\n\nLemma no_bounded_successful_rounds_excl_upper w r :  \n        (bounded_successful_round w r) ->\n          no_bounded_successful_rounds' w r.+1 (r + delta) = 0.\n  case Hdlta: (0 < delta ); last first.\n  move/negP/negP: Hdlta.\n  rewrite -eqn0Ngt => /eqP dtis0 _.\n  rewrite /no_bounded_successful_rounds'.\n  rewrite -!length_sizeP !size_filter  !has_countPn //=.\n  apply /hasPn => r' .\n  rewrite dtis0 addn0.\n  rewrite mem_iota.\n  rewrite subn_eqP //= addn0 => /andP [].\n  by move=>/ltn_transPn H /H.\n  move=> /bounded_successful_round_lim Hbs.\n  rewrite /no_bounded_successful_rounds'.\n  rewrite -!length_sizeP !size_filter  !has_countPn //=.\n  apply /hasPn => r' .\n  rewrite mem_iota subnKC //=.\n  move=> Hrng.\n  by apply Hbs.\n  by elim r => //=.\nQed.\n\n\n\nLemma no_bounded_successful_rounds'_excl w s r :\n        (~~ bounded_successful_round w s) ->\n        no_bounded_successful_rounds' w r s =\n        no_bounded_successful_rounds' w r s.+1.\nProof.\n  move=> Hbnd.\n  rewrite /no_bounded_successful_rounds';\n  rewrite /itoj .\n  case Hltr: (r <= s).\n  rewrite subSn; last first. by [].\n  rewrite -addn1.\n  rewrite iota_add filter_cat //= ifN .\n  by rewrite cats0.\n  by rewrite subnKC .\n  move/negP/negP:Hltr.\n  rewrite -ltnNge => Heq0.\n  rewrite subn_eqP //=.\n  rewrite -subn_eq0 in Heq0.\n  move/eqP: Heq0 => -> //=.\n  by apply ltnW.\nQed.\n\nLemma no_bounded_successful_rounds_excl w s r :\n        (~~ bounded_successful_round w s) ->\n        no_bounded_successful_rounds w r s =\n        no_bounded_successful_rounds w r s.+1.\nProof.\n  move=> Hsb.\n  rewrite /no_bounded_successful_rounds.\n  by rewrite -no_bounded_successful_rounds'_excl //=.\nQed.\n\n\n\nLemma no_bounded_successful_rounds'_lim_gen w s r: 0 < delta ->\n  bounded_successful_round w s ->\n  no_bounded_successful_rounds' w r s =\n  no_bounded_successful_rounds' w r (s.+1 - delta).\nProof.\n  move=> Hdelta Hbounded_success; move: (Hbounded_success).\n  rewrite/bounded_successful_round => /andP [] //= /allP Hall Hsucc.\n  move: (Hbounded_success) => /no_bounded_successful_rounds_excl_lower.\n  move: (Hbounded_success) => /no_bounded_successful_rounds_excl_upper.\n  rewrite /no_bounded_successful_rounds' -!length_sizeP !size_filter  //= /itoj subnAC.\n  move=> Hupper_bound Hlower_bound.\n  case Hsltr :(s < r).\n    move: (Hsltr); rewrite -subn_eq0 => /eqP ->; rewrite sub0n.\n    by move: (Hsltr) => /(ltn_addr 1); rewrite addn1 -subn_eq0 subSS => /eqP -> //=.\n  move/negP/negP: Hsltr; rewrite -leqNgt => Hsltr.\n  case Hltn : (delta <= s - r).\n move: Hsltr.\n rewrite leq_eqVlt =>/orP [ /eqP Hrseq | ] .\n move: Hltn Hdelta.\n rewrite Hrseq subnn leqn0 => /eqP ->.\n by rewrite ltnn.\n move=> Hsltr.\n have Hsleqnr: (r <= s). by apply ltnW.\n rewrite -{1}(@subnK delta  (s - r)) //=.\n rewrite -{2}(@subnK 1 delta ) //=.\n rewrite subn1.\n rewrite (addnC delta.-1).\n rewrite addnA addn1.\n rewrite -subSn //=.\n rewrite -subSn //=.\n case HrltSs: (r <= s.+1 - delta); last first.\n    move/negP/negP: HrltSs.\n    rewrite -ltnNge => HrltSs.\n    move: (HrltSs) => /(ltn_addr 1).\n    rewrite addn1.\n    move: (Hltn).\n    move: (Hsltr)=> /(ltn_addr 1).\n    rewrite addn1.\n    rewrite -!subn_eq0.\n    rewrite !subSS subnAC subnBA //=.\n    rewrite !subn_eq0 => _ /leq_add H /H.\n    rewrite addnBA.\n    rewrite addnC.\n    rewrite -addnBA.\n    by rewrite -addnBA //= subnn addn0 addSn ltnn.\n    by apply leq_addl.\n    by rewrite -addn1; apply ltnW; apply ltn_addr.\n rewrite iota_add count_cat {2}subnAC addnBA //=.\n move: (Hltn).\n rewrite -subn_eq0 //= subnBA //= => Hltn'.\n move: (Hdelta); rewrite (addnC r) -addnBA //= subnn addn0.\n move: Hlower_bound; rewrite {1}addn1 -subnBA //= subKn. by rewrite subn1 => ->.\n rewrite leq_subLR addnC; apply (leq_trans Hltn); rewrite -ltnS -(addn1 (s + _)).\n by apply ltn_addr; rewrite addn1 ltnS; apply leq_subr.\n \n  move/negP/negP: Hltn.\n  rewrite -ltnNge => Hltn; move: (Hltn).\n  rewrite -subn_eq0 .\n  rewrite -subSn //= => /eqP -> //=.\n  apply has_countPn; apply /hasPn => r'; rewrite mem_iota => /andP[ Hgtsd ].\n  case Hlts: (r < s); last first.\n  move/negP/negP: Hlts.\n  rewrite -ltnNge  -subn_eq0 subSS => /eqP ->.\n  rewrite addn0. move/leq_ltn_trans: Hgtsd => H /H. by rewrite ltnn.\n  rewrite subnKC//= => Hrlts.\n  rewrite /bounded_successful_round negb_and.\n  apply/orP.\n  move: (Hltn).\n  rewrite -subn_eq0 -subSn; last first. by apply ltnW.\n  rewrite subnAC subn_eq0 =>/leq_trans Hlt.\n  move/Hlt: Hgtsd => Hlbndr. clear Hlt; right.\n  rewrite -unsuccessful_roundP.\n  apply Hall; rewrite /itoj addn1 mem_iota.\n  apply/andP; split=> //=.\n  move/leq_ltn_trans: (Hlbndr) => Hlt.\n  move/Hlt: (Hrlts); clear Hlt.\n  move: Hltn Hlts Hrlts.\n  case: delta => //= delta .\n  case Hdlt: (delta <= s). by rewrite !subSS subKn //= subnK //=.\n  move/negP/negP: Hdlt.\n  rewrite -ltnNge .\n  move=> Hdlt; move: (Hdlt).\n  move=>/(ltn_addr 1).\n  rewrite addn1 -subn_eq0 subSS => /eqP ->.\n  by rewrite subn0 add0n.\nQed.\n\nLemma no_bounded_successful_rounds'_lim_subd w s r : (0 < delta) -> (r <= s) ->\n  bounded_successful_round w (s) ->\n                (no_bounded_successful_rounds' w r s.+1)%nat =\n                (no_bounded_successful_rounds' w r (s.+1 - delta) + 1)%nat.\nProof.\n  move=> Hdlta0 Hrlts Hbound .\n  rewrite -no_bounded_successful_rounds'_lim_gen //=.\n  rewrite /no_bounded_successful_rounds'.\n  rewrite  -!length_sizeP !size_filter  //= /itoj subSn; last first. by [].\n  rewrite -addn1 iota_add count_cat.\n  by rewrite addnBA //= (addnC r) -addnBA //= subnn addn0 addn0 Hbound //=.\nQed.\n\n(* todo: move to invmisc *)\nLemma length_rcons A (x : A) (xs : seq.seq A) : length (rcons xs x) = (length xs).+1.\nProof.\n  by rewrite -!length_sizeP size_rcons.\nQed.\nLemma count_rcons T (P : pred T) (xs : seq T) x :\n  count P (rcons xs  x) = count P xs + nat_of_bool (P x).\nProof.\n  move: x.\n  elim: xs => //= y ys IHx x .\n  by rewrite IHx addnA.\nQed.\n\n\n\nLemma unsuccessful_round_internal_insert_adversarial bm bl hr :\n    fixlist_is_top_heavy bm ->\n    [length bm] < BlockHistory_size ->\n    [eta unsuccessful_round_internal [bm <- (bl, (true, hr))]]  = \n    [eta unsuccessful_round_internal bm].\nProof.\n  move=> Hith Hlen.\n  apply: functional_extensionality=> x.\n  rewrite /unsuccessful_round_internal/BlockMap_records//=.\n  rewrite fixlist_insert_rewrite //=.\n  rewrite map_rcons filter_rcons //=.\n  by rewrite Bool.andb_false_r //=.\nQed.\n\nLemma unsuccessful_round_internal_insert_honest bm bl hr :\n    fixlist_is_top_heavy bm ->\n    [length bm] < BlockHistory_size ->\n    [eta unsuccessful_round_internal [bm <- (bl, (false, hr))]] =\n    predI [eta unsuccessful_round_internal bm]   (fun x=> ~~ (nat_of_ord hr == x)).\nProof.\n  move=> Hith Hlen.\n  apply: functional_extensionality=> x.\n  rewrite /unsuccessful_round_internal/BlockMap_records//=.\n  rewrite -!length_sizeP !size_filter.\n  rewrite fixlist_insert_rewrite //=.\n  rewrite map_rcons count_rcons //=.\n  rewrite Bool.andb_true_r //=.\n  case: (_ == x) => //=.\n  have Haddn y : (y + 1 == 0) = false. by case: y => //=.\n  by rewrite Haddn Bool.andb_false_r.\n  by rewrite addn0 Bool.andb_true_r.\nQed.\n\n\nLemma successful_round_internal_insert_adversarial bm bl hr round :\n    fixlist_is_top_heavy bm ->\n    [length bm] < BlockHistory_size ->\n    successful_round_internal [bm <- (bl, (true, hr))] round  = \n    successful_round_internal bm round.\nProof.\n  move=> Hith Hlen.\n  rewrite /successful_round_internal/BlockMap_records//=.\n  rewrite fixlist_insert_rewrite //=.\n  rewrite map_rcons filter_rcons //=.\n  by rewrite Bool.andb_false_r //=.\nQed.\n\nLemma successful_round_internal_insert_honest bm bl hr round :\n    fixlist_is_top_heavy bm ->\n    [length bm] < BlockHistory_size ->\n    successful_round_internal [bm <- (bl, (false, hr))] round  = \n    successful_round_internal bm round ||  (nat_of_ord hr == round).\nProof.\n  move=> Hith Hlen.\n  rewrite /successful_round_internal/BlockMap_records//=.\n  rewrite fixlist_insert_rewrite //=.\n  rewrite map_rcons filter_rcons //=.\n  rewrite Bool.andb_true_r //=.\n  case: (_ == round) => //=.\n    by rewrite length_rcons //= ltn0Sn Bool.orb_true_r.\n  by rewrite  Bool.orb_false_r.\nQed.\n\n\n\n\n\n\nLemma no_bounded_successful_rounds'_internal_insert_adversarial bm hr s r bl :\n  [length bm] < BlockHistory_size  ->\n  fixlist_is_top_heavy bm ->\n  no_bounded_successful_rounds'_internal\n    (fixlist_insert bm ((bl), (true, hr))) s r =\n  no_bounded_successful_rounds'_internal\n    bm s r.\nProof.\n  move=> Hlen Hith.\n  rewrite /no_bounded_successful_rounds'_internal/bounded_successful_round_internal//=.\n  rewrite unsuccessful_round_internal_insert_adversarial //=.\n  rewrite -!length_sizeP.\n  rewrite !size_filter.\n  apply: eq_count.\n  rewrite /eqfun => x .\n  by rewrite successful_round_internal_insert_adversarial //=.\nQed.\n\nLemma all_neq_itoj hr x :\n  (hr == x) ->\n  all (fun x0 : nat => (hr) != x0) (itoj (x + 1 - delta) x) = true.\nProof.\n  move=>/eqP ->; apply/allP => x'; rewrite mem_iota => /andP [].\n  rewrite subnKC.\n    by rewrite neq_ltn => Hxdltx' Hx'ltx; apply/orP; right.\n  move: delta_valid;  case: delta => //= delta _ ; rewrite addn1 subSS.\n  apply leq_subr.\nQed.\n\n\n\n\n\nLemma no_bounded_successful_rounds'_internal_insert_honest bm hr s r bl :\n  [length bm] < BlockHistory_size  ->\n  fixlist_is_top_heavy bm ->\n    all (fun x : nat => x <= nat_of_ord hr) (itoj 0 r) ->\n  no_bounded_successful_rounds'_internal\n    (fixlist_insert bm ((bl), (false, hr))) s r =\n  no_bounded_successful_rounds'_internal\n    bm s r.\nProof.\n  move=> Hlen Hith Hleq.\n  rewrite /no_bounded_successful_rounds'_internal/bounded_successful_round_internal//=.\n  rewrite -!length_sizeP !size_filter .\n  apply: eq_in_count.\n  rewrite /eqfun  => x .\n  rewrite mem_iota => /andP [].\n  case Hrlts: (r < s).\n    move: (Hrlts) => /(ltn_addr 1); rewrite addn1 -subn_eq0 subSS => /eqP ->; rewrite addn0.\n    by move=>/leq_ltn_trans H /H; rewrite ltnn.\n  move/negP/negP:Hrlts; rewrite -leqNgt => Hrlts; rewrite subnKC //= => Hsltx Hxltr.\n  rewrite unsuccessful_round_internal_insert_honest => //=.\n  rewrite successful_round_internal_insert_honest => //=.\n  rewrite all_predI.\n  move/allP: Hleq => Hleq; move: (Hleq x); rewrite  mem_iota subnKC //=; clear Hleq .\n  move=> Hleq; move: (Hleq Hxltr); clear Hleq => Hleq.\n\nAdmitted.\n\n\n\n\n\n\nLemma no_bounded_successful_rounds'_lim w s r :\n  0 < delta ->\n  delta <= s ->\n  r <= s - delta ->\n  bounded_successful_round w (s - delta) ->\n                (no_bounded_successful_rounds' w r (s.+1 - delta))%nat =\n               (no_bounded_successful_rounds' w r (s.+1 - 2 * delta) + 1)%nat.\nProof.\n  move=> Hdlta0 Hdltas Hrbnd Hbound.\n  rewrite subSn //=.\n  rewrite no_bounded_successful_rounds'_lim_subd //=.\n  rewrite -subSn //= .\n  by rewrite -subnDA addnn -muln2 mulnC //=.\nQed.\n\nLemma no_bounded_successful_rounds_lim w s r :\n  0 < delta ->\n  delta <= s ->\n  r <= s - delta ->\n  ((no_bounded_successful_rounds' w r (s.+1 - 2 * delta)) + 1) < N_rounds.+1 ->\n  bounded_successful_round w (s - delta) ->\n  (nat_of_ord (no_bounded_successful_rounds w r\n                                            (s.+1 - delta))%nat) =\n  (nat_of_ord (no_bounded_successful_rounds w r\n                                            (s.+1 - 2 * delta)) + 1)%nat.\nProof.\n  move=> Hdlta0 Hdltas Hrbnd Hbound.\n  rewrite /no_bounded_successful_rounds => Hbounded_succ.\n  rewrite no_bounded_successful_rounds'_lim //= .\n  move: [eta _ ].\n  move: [eta _ ].\n  move: (erefl _ ).\n  move: (erefl _ ).\n  rewrite {2 4}Hbound.\n  move/ltn_weaken: (Hbound) => Hbound'.\n  by rewrite {2 4}Hbound' => prf prf' H1 H2; rewrite /nat_of_ord //=.\nQed.\n\n\n\nLemma bounded_successful_round_init round :\n  ~~  bounded_successful_round initWorld round .\nProof.\n  rewrite /bounded_successful_round//=.\n  rewrite negb_and; apply/orP; right.\n  rewrite /successful_round/initWorld//=.\n  rewrite /BlockMap_records/BlockMap_new//=.\n    by move:\n         (fixlist_empty_is_empty\n            [finType of BlockMap_keytype * BlockMap_valuetype]\n            BlockHistory_size);\n    rewrite /fixlist_is_empty => /eqP -> //=.\nQed.\n\nLemma no_bounded_successful_rounds'_init r s :\n  no_bounded_successful_rounds' initWorld r s = 0.\nProof.\n  rewrite/no_bounded_successful_rounds'//=/initWorldAdoptionHistory //=.\n  rewrite /itoj -length_sizeP size_filter;\n  apply has_countPn; apply /hasPn => round Hvldround.\n  by apply bounded_successful_round_init.\nQed.\n\n\n\n\nLemma no_bounded_successful_rounds_init r s :\n  nat_of_ord (no_bounded_successful_rounds initWorld r s) = 0.\nProof.\n  by rewrite/no_bounded_successful_rounds no_bounded_successful_rounds'_init //=.\nQed.\n\n\n\n\n\n\nDefinition no_bounded_uniquely_successful_rounds'\n           (w : World) (from : nat) (to : nat) : nat :=\n  length(filter\n    (fun round => bounded_uniquely_successful_round w round)\n    (itoj from to)).\n\nDefinition no_bounded_uniquely_successful_rounds\n           (w: World) (from to : nat) : 'I_N_rounds :=\n  let b := ((no_bounded_uniquely_successful_rounds' w from to) < N_rounds ) in\n  (if b as b0\n      return (((no_bounded_uniquely_successful_rounds' w from to) < N_rounds ) =\n              b0 -> 'I_N_rounds)\n      then fun H => Ordinal H\n      else fun _ => Ordinal valid_N_rounds) (erefl b).\n\n\n\n\n\nDefinition all_chains_after_round_have_length_ge (w : World) (s v : nat) :=\n          (all\n                        (fun pr =>\n                            let: (rec_chain, rec_round, rec_actr) := pr in\n                            (* documented after s *)\n                            if ((nat_of_ord rec_round) > s) then\n                                (* has a length of at least *)\n                                (fixlist_length rec_chain >= v)\n                            else \n                            true)\n                        (fixlist_unwrap (world_adoption_history w))) .\n\nDefinition insertion_occurred (w : World) (from to : nat)  : bool :=\n  has \n    (fun pr1 =>\n      let: (b1, ( is_adv, r1))  := pr1 in\n      has \n      (fun pr2 => \n        let: (b2, ( is_adv, r2))  := pr2 in\n        has\n        (fun pr3 =>\n          let: (b3, ( is_adv, r3))  := pr3 in\n          (* given three blocks, such that *)\n          [&&\n             (* root -> .. -> [b1] -> [b2] -> .... -> head*)\n             (* block 1 was hashed first *) (r1 < r2),\n            (* block 2 was hashed second *)\n            (* block 3 was hashed last *)\n            (r2 < r3), \n\n            (* such that r1, r2, r3 are all in the range[from..to]*)\n            (r1 \\in (itoj from to)),\n            (r2 \\in (itoj from to)),\n            (r3 \\in (itoj from to)),\n            \n            (* block 1 connects to block 2 *)\n             (if verify_hash b1 (world_hash w) is Some(hash_b1) then\n              (block_link b2 == hash_b1)\n             else false),\n\n            (* but block 1 also connects to block 3 *)\n             (if verify_hash b1 (world_hash w) is Some(hash_b1) then\n              (block_link b3 == hash_b1)\n             else false) &\n\n            (* and block 3 connects to block 2 *)\n             (if verify_hash b3 (world_hash w) is Some(hash_b3) then\n              (block_link b2 == hash_b3)\n             else false)\n          ]\n        \n        )\n        (BlockMap_pairs (world_block_history w))\n      )\n        (BlockMap_pairs (world_block_history w))\n    )\n    (BlockMap_pairs (world_block_history w)).\n\n\n(* if the same block is made multiple times *)\nDefinition copy_occurred (w : World) (from to : nat) :=\n  ~~ (uniq (map (fun pr => \n          let: (bl, (is_adv, round))  := pr in\n          bl)\n  (filter (fun pr => \n          let: (bl, (is_adv, round))  := pr in\n          round \\in (itoj from to))\n    (BlockMap_pairs (world_block_history w))))).\n\n(* TODO: Bitcoin backbone proof uses more strict formulation of these \n  stating not that nodes are hashed in different rounds, but rather in terms\n  of their position in chains\n*)\nDefinition prediction_occurred (w : World) (from to : nat)  : bool :=\n  has \n    (fun pr1 =>\n      let: (b1, ( is_adv, r1))  := pr1 in\n      has \n      (fun pr2 => \n        let: (b2, ( is_adv, r2))  := pr2 in\n         (* given two blocks, such that *)\n          [&&\n            (* root -> .. -> [b1] -> [b2] -> .... -> head*)\n            (* block 1 was hashed first *)\n            (* block 2 was hashed second *)\n            (r1 < r2), \n            (* such that r1, r2 are all in the range[from..to]*)\n            (r1 \\in (itoj from to)),\n            (r2 \\in (itoj from to)) &\n            \n            (* but block 2 connects to block 1 *)\n             (if verify_hash b2 (world_hash w) is Some(hash_b2) then\n              (block_link b1 == hash_b2)\n             else false)\n          ]\n        \n        )\n        (BlockMap_pairs (world_block_history w))\n    )\n    (BlockMap_pairs (world_block_history w)).\n\nLemma honest_activation_simplify w' addr :\n  honest_activation [w'.state] = Some addr ->\n  nat_of_ord [[w'.state].#active] = nat_of_ord addr.\nProof.\n  rewrite /honest_activation.\n  case: w'=> [ wgs wtp wif wmp whsh wblh wch wadvm wadvtx whontx wadopt ]//=.\n  case: wgs => [gls ga gca gcr].\n  move: (erefl _).\n  case: {2 3 }(gca < n_max_actors)%nat => //= prf' Htrace.\n  by case: ((tnth _ _).2) => //= [] [] <- //=.\nQed.\n\nLemma actor_n_is_honestP w r : forall prf,\n    actor_n_is_honest w r =\n    ~~ actor_n_is_corrupt w (Ordinal (n:=n_max_actors) (m:=r) prf).\nProof.\n  move=> prf.\n  rewrite /actor_n_is_honest; move: (erefl _).\n  case Hltn: {2 3}(r < n_max_actors)%nat => //= prf' .\n  by rewrite (proof_irrelevance _ prf' prf).\n  move: Hltn.\n  by rewrite {1}prf.\nQed.\n\n\n\n\nLemma local_state_base_nth addr : tnth initLocalStates addr = (initLocalState, false).\nProof.\n  rewrite (tnth_nth (initLocalState, false)).\n  rewrite /initLocalStates.\n  destruct addr as [m Hm].\n  rewrite /tnth/ncons/ssrnat.iter//=. move: m Hm.\n  elim n_max_actors => //=.\n  move=> n IHn m .\n  case m => //=.\nQed.\n\n\nDefinition honest_actor_has_chain_at_round w addr c r : bool := \n   (has\n      (* there is a record *)\n      (fun pr => \n         let: (rec_chain, rec_round, rec_actr)  := pr in \n         [&&\n            (* of the block adopting/broadcasting the chain *)\n            (rec_chain  == c),\n          (* at round r or earlier *)\n          (nat_of_ord rec_round <= r)%nat &\n          (* by the actor *) \n          (nat_of_ord rec_actr == addr) ])\n      (fixlist_unwrap (world_adoption_history w))\n   )\n.\n\n\n\n\nDefinition actor_n_has_chain_length_at_round_internal\n           (ah: fixlist [eqType of BlockChain * 'I_N_rounds * 'I_n_max_actors] (n_max_actors * N_rounds))\n           l addr r : bool :=\n   (has\n      (* there is a record *)\n      (fun pr => \n         let: (rec_chain, rec_round, rec_actr)  := pr in \n         [&&\n          (* of the block adopting/broadcasting the chain *)\n          (fixlist_length rec_chain  == l),\n          (* at round r *)\n          (eq_op ( rec_round) ( r)) &\n          (* by the actor *) \n          (nat_of_ord rec_actr == addr) ])\n      (fixlist_unwrap ah)\n   )\n   ||\n   (* or - implicit in the starting conditions, every actor has a chain length of 0 at round 0 *)\n   ((eq_op (nat_of_ord r) 0%nat)%nat && (eq_op l 0)%nat).\n\n\n\n\nDefinition actor_n_has_chain_length_at_round w l addr r : bool :=\n   (has\n      (* there is a record *)\n      (fun pr => \n         let: (rec_chain, rec_round, rec_actr)  := pr in \n         [&&\n          (* of the block adopting/broadcasting the chain *)\n          (fixlist_length rec_chain  == l),\n          (* at round r *)\n          (eq_op ( rec_round) ( r)) &\n          (* by the actor *) \n          (nat_of_ord rec_actr == addr) ])\n      (fixlist_unwrap (world_adoption_history w))\n   )\n   ||\n   (* or - implicit in the starting conditions, every actor has a chain length of 0 at round 0 *)\n   ((eq_op (nat_of_ord r) 0%nat)%nat && (eq_op l 0)%nat).\n\nLemma actor_n_has_chain_length_at_round_internalP w l addr r :\n  actor_n_has_chain_length_at_round w l addr r =\n  actor_n_has_chain_length_at_round_internal [w.adopt_history] l addr r.\nProof.\n  by rewrite /actor_n_has_chain_length_at_round//=.\nQed.\n\n\nDefinition actor_n_has_chain_length_at_round_nat (w : World) (l addr round : nat)  : bool.\n  case Hltn: (round < N_rounds).\n    exact ((actor_n_has_chain_length_at_round w l addr (Ordinal Hltn))).\n    exact false.\nDefined.\n\n\n\nDefinition actor_n_first_has_chain_length_at_round w l addr r : bool :=\n  actor_n_has_chain_length_at_round w l addr r &&\n  all (fun round => ~~ actor_n_has_chain_length_at_round_nat w l addr round) (iota 0 r).\n  \n\nDefinition actor_n_has_chain_length_ge_at_round_internal\n           (ah: fixlist [eqType of BlockChain * 'I_N_rounds * 'I_n_max_actors] (n_max_actors * N_rounds))\n           l addr (r : 'I_N_rounds) : bool :=\n   (has\n      (* then there is a record *)\n      (fun pr => \n         let: (rec_chain, rec_round, rec_actr)  := pr in \n         [&&\n          (* of the block adopting/broadcasting a chain of at least length l *)\n          (fixlist_length rec_chain >= l)%nat,\n          (* at round r or earlier *)\n          (nat_of_ord rec_round <= nat_of_ord r)%nat &\n          (* by the actor *) \n          (nat_of_ord rec_actr == addr) ])\n      (fixlist_unwrap ah)\n   )\n   ||\n   (* or - implicit in the starting conditions, every actor has a chain length of 0 at round 0 *)\n   ((eq_op l 0)%nat).\n\n\n\n\nDefinition actor_n_has_chain_length_ge_at_round w l addr (r : 'I_N_rounds) : bool :=\n   (has\n      (* then there is a record *)\n      (fun pr => \n         let: (rec_chain, rec_round, rec_actr)  := pr in \n         [&&\n          (* of the block adopting/broadcasting a chain of at least length l *)\n          (fixlist_length rec_chain >= l)%nat,\n          (* at round r or earlier *)\n          (nat_of_ord rec_round <= nat_of_ord r)%nat &\n          (* by the actor *) \n          (nat_of_ord rec_actr == addr) ])\n      (fixlist_unwrap (world_adoption_history w))\n   )\n   ||\n   (* or - implicit in the starting conditions, every actor has a chain length of 0 at round 0 *)\n   ((eq_op l 0)%nat).\n\n\nLemma actor_n_has_chain_length_ge_at_round_internalP w l addr r :\n  actor_n_has_chain_length_ge_at_round w l addr r =\n  actor_n_has_chain_length_ge_at_round_internal [w.adopt_history] l addr r.\nProof.\n  by rewrite /actor_n_has_chain_length_ge_at_round//=.\nQed.\n\n\nDefinition actor_n_has_chain_length_ge_at_round_nat (w : World) (l addr round : nat)  : bool.\n  case Hltn: (round < N_rounds).\n    exact ((actor_n_has_chain_length_ge_at_round w l addr (Ordinal Hltn))).\n    exact false.\nDefined.\n\n\n\n\nDefinition actor_n_first_has_chain_length_ge_at_round w l addr r : bool :=\n  actor_n_has_chain_length_ge_at_round w l addr r &&\n  all (fun round => ~~ actor_n_has_chain_length_ge_at_round_nat w l addr round) (iota 0 r).\n \n                                   \n\n\n\n\nLemma no_bounded_successful_rounds'_eq0 : forall w r s, (s < r \\/ (eq_op r s /\\ eq_op r 0))%nat -> (no_bounded_successful_rounds' w r s) = 0%nat.\nProof.\n  move=> w r s Hrs; rewrite /no_bounded_successful_rounds/no_bounded_successful_rounds'; apply/eqP => //=.\n  destruct Hrs .\n  by rewrite itoj_eq_0 => //=.\n  by move: H => [/eqP -> /eqP ->] //=.\nQed.\n\n\n\n\nLemma no_bounded_successful_rounds_eq0 : forall w r s, (s < r \\/ (eq_op r s ))%nat -> nat_of_ord (no_bounded_successful_rounds w r s) = 0%nat.\nProof.\n  move=> w r s Hrs; rewrite /no_bounded_successful_rounds/no_bounded_successful_rounds'; apply/eqP => //=.\n  destruct Hrs .\n  by rewrite itoj_eq_0 => //=.\n  rewrite /itoj.\n  by move/eqP: (H) ->; rewrite subnn //=.\nQed.\n\nLemma actor_has_chain_length_generalize  w l o_addr s :\n  actor_n_has_chain_length_at_round w l o_addr s ->\n  actor_n_has_chain_length_ge_at_round w l o_addr s.\nProof.\n  have blt0 (x:bool) : (x > 0)%nat = x. by case x.\n  rewrite /actor_n_has_chain_length_ge_at_round/actor_n_has_chain_length_at_round !has_count.\n  move=> /orP [ | /andP [/eqP Hseq  Hleq]]; last first.\n  by apply/orP; right.\n  move=> H; apply/orP; left; move: H.\n  elim (fixlist_unwrap _) => //= [[[c r] addr] xs] IHn.\n  rewrite add_lt0; move=>/orP; case => //=.\n  by rewrite blt0; move=>/andP; case; [move=>/andP [/eqP -> /andP [/eqP -> /eqP ->]]] => _; rewrite !leqnn eq_refl.\n  move=>/IHn Hbase.\n  by rewrite add_lt0; apply/orP; right.\nQed.  \n\n\n\nLemma  actor_has_chain_length_weaken w l o_addr s l':\n  (l' <= l)%nat ->\n  actor_n_has_chain_length_ge_at_round w l o_addr s ->  \n  actor_n_has_chain_length_ge_at_round w l' o_addr s.\nProof.\n  rewrite /actor_n_has_chain_length_ge_at_round !has_count.\n  rewrite leq_eqVlt; move=>/orP[/eqP -> |] //=.\n  move=>  Hvalid.  \n  induction (fixlist_unwrap _) => //=.\n    by move=>/eqP Heq; move: Hvalid; rewrite Heq ltn0.\n  move=> /orP [ | /eqP  Heq]; last first.\n    by move: Hvalid; rewrite Heq ltn0.\n  rewrite !add_lt0; move=>/orP; case => //= ;last first.\n  move=> /(@or_introl _ (is_true (eq_op l 0)%nat))/orP/IHl0 => /orP [ Hlt |  Hleq0]; last first.\n    by apply/orP; right.\n    by apply/orP; left; apply/orP; right.\n  move=>/andP [ Hgt0  Hlt0] //=.\n  apply/orP.\n  left .\n  apply/orP; left.\n  apply/andP;split.\n  move: Hgt0.\n  have bool_gt0 (b : bool) : (0 < b)%nat = b. by case b.\n  move: a => [[b r] a].\n  rewrite !bool_gt0 //=.\n  move=>/andP [l_leq /andP [rs eq_addr]].\n  apply/andP; split; [|apply/andP] => //=.\n  have Hlt_trans x y z : (x <= y)%nat -> (y <= z)%nat  -> (x <= z)%nat.\n    by move=>/leq_trans Himpl; move=> /Himpl.\n  by apply (Hlt_trans l' l); [apply ltnW | ] .\n  move: Hlt0.\n  rewrite leq_eqVlt ; move=>/orP[/eqP |] //=.\nQed.\n\n\nDefinition world_executed_to_max_round w :=\n  foldl (fun acc x =>\n           let: (rec_chain, rec_round, rec_actr) := x in\n           max (nat_of_ord rec_round) acc) 0%nat (fixlist_unwrap (world_adoption_history w)).\n\n\nDefinition world_executed_to_round w r : bool :=\n  (r < (global_current_round (world_global_state w)) )%nat.\n\n\n \nDefinition honest_message_has_chain_length l (msg: Message)  :=\n  match msg with\n    (* selective messages are only sent by parties with malicious intentions *)\n    | MulticastMsg _ chain =>  false\n    | BroadcastMsg chain =>  fixlist_length chain == l\n  end.\n\nDefinition honest_message_has_chain_length_ge l (msg: Message)  :=\n  match msg with\n    (* selective messages are only sent by parties with malicious intentions *)\n    | MulticastMsg _ chain =>  false\n    | BroadcastMsg chain =>  l <= fixlist_length chain \n  end.\n\nDefinition message_pool_contains_chain_of_length (ls : MessagePool) l :=\n  has (honest_message_has_chain_length l) (fixlist_unwrap ls).\n\n\nDefinition message_pool_contains_chain_of_length_ge (ls : MessagePool) l :=\n  has (honest_message_has_chain_length_ge l) (fixlist_unwrap ls).\n\nDefinition o_message_pool_contains_chain_of_length_ge (ls : option MessagePool) l :=\n  match ls with\n    | None => false\n    | Some msgs  => message_pool_contains_chain_of_length_ge msgs l\n  end.\n\n\n\n\nDefinition actor_recieved_chain_of_length (stt : LocalState) l :=\n  has (fun chain => l == fixlist_length chain) (fixlist_unwrap (honest_local_message_pool  stt)).\n\nDefinition actor_recieved_chain_of_length_ge (stt : LocalState) l :=\n  has (fun chain => l <= fixlist_length chain) (fixlist_unwrap (honest_local_message_pool  stt)).\n\nDefinition actor_n_recieved_chain_of_length (w : World) addr l :=\n  actor_recieved_chain_of_length (tnth [[w.state].actors] addr).1 l.\n\nDefinition actor_n_recieved_chain_of_length_ge (w : World) addr l :=\n  actor_recieved_chain_of_length_ge (tnth [[w.state].actors] addr).1 l.\n\nDefinition message_queue_at_round (ms : fixlist [eqType of MessagePool * fixlist [eqType of MessagePool] delta *\n               MessagePool]  N_rounds.+1) r :=\n  (@nth _\n        (initMessagePool , (fixlist_empty [eqType of MessagePool] delta), initMessagePool)\n        (fixlist_unwrap ms) r).\n\nDefinition world_message_queue_at_round (w : World) r :=\n  message_queue_at_round ([w.msg_trace]) r.\n\n", "meta": {"author": "certichain", "repo": "probchain", "sha": "5ab581529565d2234c472964966bced07ff1809b", "save_path": "github-repos/coq/certichain-probchain", "path": "github-repos/coq/certichain-probchain/probchain-5ab581529565d2234c472964966bced07ff1809b/Systems/Protocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.19296029998851522}}
{"text": "From iris.algebra Require Import auth agree excl gmap frac.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Import adequacy.\nRequire Import Eqdep_dec.\n\nFrom cap_machine Require Import\n     stdpp_extra iris_extra\n     logrel_binary fundamental_binary linking\n     counter_binary_adequacy.\n\nDefinition is_initial_configuration_left `{memory_layout} c_adv prog :=\n  \u2203 p1, is_machine_context c_adv comp1 p1 \u2227 prog = initial_state_stk p1.\n\nDefinition is_initial_configuration_right `{memory_layout} c_adv prog :=\n  \u2203 p2, is_machine_context c_adv comp2 p2 \u2227 prog = initial_state_stk p2.\n\nDefinition soundness_binary\u03a3 : gFunctors :=\n  #[GFunctor (authR cfgUR); inv\u03a3; gen_heap\u03a3 Addr Word;\n   gen_heap\u03a3 RegName Word;\n   na_inv\u03a3;\n   sealStorePre\u03a3].\n\nGlobal Instance inG_soundness_binary\u03a3 \u03a3 : subG soundness_binary\u03a3 \u03a3 \u2192 inG \u03a3 (authR cfgUR).\nProof. solve_inG. Qed.\n\n\nTheorem counter_adequacy_l `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv reg' m' (es: list cap_lang.expr):\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  rtc erased_step prog1 (of_val HaltedV :: es, (reg', m')) \u2192\n  (\u2203 es' conf', rtc erased_step prog2 (of_val HaltedV :: es', conf')).\nProof.\n  set (\u03a3 := soundness_binary\u03a3).\n  intros [p1 [? ->] ] [p2 [? ->] ] ? ?.\n  eapply (@confidentiality_adequacy_l' \u03a3);last eauto;eauto. all: try typeclasses eauto.\nQed.\n\nTheorem counter_adequacy_r `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv reg' m' (es: list cap_lang.expr):\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  rtc erased_step prog2 (of_val HaltedV :: es, (reg', m')) \u2192\n  (\u2203 es' conf', rtc erased_step prog1 (of_val HaltedV :: es', conf')).\nProof.\n  set (\u03a3 := soundness_binary\u03a3).\n  intros [p1 [? ->] ] [p2 [? ->] ] ? ?.\n  eapply (@confidentiality_adequacy_r' \u03a3);last eauto;eauto. all: try typeclasses eauto.\nQed.\n\nTheorem counter_ctx_equivalent `{MachineParameters} `{memory_layout}\n        prog1 prog2 c_adv :\n  is_initial_configuration_left c_adv prog1 \u2192\n  is_initial_configuration_right c_adv prog2 \u2192\n  is_initial_context c_adv \u2192\n  (\u2203 es conf, rtc erased_step prog1 (of_val HaltedV :: es, conf)) \u2194\n  (\u2203 es conf, rtc erased_step prog2 (of_val HaltedV :: es, conf)).\nProof.\n  intros. split.\n  - intros (?&[? ?]&?). eapply counter_adequacy_l;eauto.\n  - intros (?&[? ?]&?). eapply counter_adequacy_r;eauto.\nQed.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/examples/counter_binary_adequacy_theorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1929602961221608}}
{"text": "Require Import mailbox.verif_atomics.\nRequire Import VST.concurrency.conclib.\nRequire Import VST.progs.ghost.\nRequire Import VST.floyd.library.\nRequire Import VST.zlist.sublist.\nRequire Import mailbox.lockfree_linsearch.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n#[export] Instance 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; lia|].\n  destruct (index_of m k); simpl.\n  - destruct IHm; unfold Z.succ; rewrite Znth_pos_cons, Z.add_simpl_r; [split|]; auto; lia.\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 *; lia.\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 lia.\n    { rewrite Zlength_cons; lia. }\n    rewrite Znth_0_cons, Znth_pos_cons, Z.add_simpl_r, Hj by lia; auto.\n  - intros; exploit (H (i + 1) (j + 1)); try lia.\n    { rewrite Zlength_cons; lia. }\n    rewrite !Znth_pos_cons, !Z.add_simpl_r by lia; 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; lia.\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 lia.\n        rewrite Hlast, Hi; simpl; lia.\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 lia.\n  destruct (eq_dec j (Zlength h)).\n  - rewrite Znth_app1; auto.\n    apply Forall_Znth; auto; lia.\n  - specialize (H i j).\n    rewrite app_Znth1 by lia; apply H; auto; lia.\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; lia.\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; lia. }\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; lia. }\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_last; 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 lia; 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_last; 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; lia. }\n      split; [|apply Forall_suffix_max with (l1 := h); auto; lia].\n      rewrite Hh'; clear Hh'.\n      assert (Zlength h' <= i - 0 + Z.succ (Zlength h' - (i + 1))) by lia.\n      assert (0 <= Zlength h' - i) by lia.\n      destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)].\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try lia.\n        rewrite Z.min_l, Z.min_r, Z.max_r, Z.max_l by lia.\n        rewrite !Z.sub_0_r.\n        rewrite sublist_sublist, !Z.add_0_r by lia.\n        rewrite Forall_app; split; auto.\n        rewrite sublist_0_cons by lia.\n        constructor; [rewrite Hk'; auto|].\n        rewrite sublist_sublist by lia.\n        rewrite <- Z.sub_add_distr, Z.sub_simpl_r.\n        rewrite Z.add_0_l, sublist_parts2; try lia.\n        rewrite <- Hrest.\n        rewrite <- sublist_parts2 by lia.\n        rewrite sublist_parts1 by lia; apply Forall_sublist; auto.\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try lia.\n        rewrite !Z.sub_0_r, Z.min_l, Z.min_r, Z.max_r, Z.max_l; auto; try lia.\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 lia; 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; lia. }\n      split; [rewrite !Zlength_sublist; auto; lia|].\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; lia).\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; lia. }\n      intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try lia.\n      rewrite !Znth_sublist, Z.add_0_r in Heq2 by lia.\n      rewrite !Znth_sublist, Z.add_0_r by lia.\n      rewrite Heq1, Heq2; simpl; split; auto.\n      unfold value_of_hist in *; rewrite last_last; 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; lia).\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; lia).\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 lia.\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 lia.\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 lia; apply Forall_sublist; auto.\n      * apply Forall_sublist; eapply Forall_impl, Hwf; tauto.\n    + rewrite sublist_split with (mid := l)(hi := i) by lia.\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_last; 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_last; 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; lia].\n        rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by lia; 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 lia; 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))); lia. }\n    + erewrite sublist_next with (i0 := i) at 1 by lia; 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; lia. }\n      rewrite Znth_sublist, Z.sub_simpl_r, Hhi by lia; 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 lia; 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 lia; 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 *; lia. }\n  destruct a.\n  rewrite Zlength_cons in *.\n  rewrite sublist_0_cons, Z.add_simpl_r in Hnz, Hint by lia.\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 lia; apply IHh; rewrite ?Z.sub_simpl_r; auto; lia.\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; lia. }\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; lia. }\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_last; 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 lia; 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_last; 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_last 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; lia).\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; lia. }\n      split; [|apply Forall_suffix_max with (l1 := h); auto; lia].\n      rewrite Hh'; clear Hh'.\n      assert (Zlength h' <= i - 0 + Z.succ (Zlength h' - (i + 1))) by lia.\n      assert (0 <= Zlength h' - i) by lia.\n      destruct (Z.max_spec (i + 1) l) as [(? & ->) | (? & ->)].\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try lia.\n        rewrite Z.min_l, Z.min_r, Z.max_r, Z.max_l by lia.\n        rewrite !Z.sub_0_r.\n        rewrite sublist_sublist, !Z.add_0_r by lia.\n        rewrite Forall_app; split; auto.\n        rewrite sublist_0_cons by lia.\n        constructor; [unfold value_of_hist; simpl; rewrite last_last; auto|].\n        rewrite sublist_sublist by lia.\n        rewrite <- Z.sub_add_distr, Z.sub_simpl_r.\n        rewrite Z.add_0_l, sublist_parts2; try lia.\n        rewrite <- Hrest.\n        rewrite <- sublist_parts2 by lia.\n        rewrite sublist_parts1 by lia; apply Forall_sublist; auto.\n      * rewrite !sublist_app; rewrite ?Zlength_cons, ?Zlength_sublist; auto; try lia.\n        rewrite !Z.sub_0_r, Z.min_l, Z.min_r, Z.max_r, Z.max_l; auto; try lia.\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 lia; simpl.\n        rewrite Forall_app; split; auto.\n        constructor; auto; unfold value_of_hist; simpl; rewrite last_last; auto.\n    + rewrite Znth_make_map, Hhi'; simpl.\n      unfold value_of_hist; rewrite last_last; simpl.\n      apply Int.signed_repr; auto.\n      { lia. }\n      { rewrite sublist_split with (mid := i), Forall_app by lia; split; auto.\n        erewrite sublist_len_1, Hhi' by lia; repeat constructor; simpl.\n        unfold value_of_hist; rewrite last_last; 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_last; 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; lia. }\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; lia).\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; lia|].\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; lia).\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; lia. }\n        intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n        rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try lia.\n        rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2 by lia.\n        rewrite !Znth_sublist, Z.add_0_r by lia.\n        rewrite Heq1, Heq2; simpl; split; auto.\n        unfold value_of_hist in *; rewrite last_last; 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 lia.\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))); lia. }\n        { eapply Forall_Znth with (i0 := i) in Hl1; [|rewrite Zlength_sublist; lia].\n          rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by lia; 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 lia.\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; lia].\n      rewrite Znth_sublist, Z.add_0_r, Hhi in Hl1 by lia; contradiction Hl1. }\n    split; [lia|].\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; [lia|]; 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_last; simpl.\n        intro X; absurd (r1 = Int.zero); auto; inv X; auto.\n      * erewrite sublist_next by lia; constructor;\n          [rewrite Hi1; unfold value_of_hist; rewrite last_last; auto|].\n        rewrite <- Hrest.\n        replace (i + 1) with (i + 1 - l + l) by (apply Z.sub_simpl_r).\n        rewrite <- sublist_suffix by lia; 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; lia).\n      replace h' with (sublist 0 l h' ++ sublist l (Zlength h') h')\n        by (rewrite sublist_rejoin, sublist_same; auto; lia).\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; lia|].\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; lia).\n      assert (x < i) by lia.\n      exploit (Forall2_Znth _ _ _ ([], []) ([], []) Hfail x); auto.\n      { rewrite Zlength_sublist; lia. }\n      intros (? & r1 & ? & Heq1 & ? & ? & Heq2 & Hv).\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2, Hv, Hnz; auto; try lia.\n      rewrite !Znth_sublist, Z.add_0_r in Heq1, Heq2 by lia.\n      rewrite !Znth_sublist, Z.add_0_r by lia.\n      rewrite Heq1, Heq2; simpl; split; auto.\n      unfold value_of_hist at 2; rewrite last_last; auto.\n      { replace l with (Z.min l i) by (apply Z.min_l; lia).\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_last; 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_last; simpl.\n        rewrite Int.signed_repr; auto.\n        { lia. }\n        { erewrite sublist_split with (mid := i), sublist_len_1 by lia; 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 lia.\n        rewrite app_assoc, make_map_app, Zlength_app, make_map_length, Zlength_app, Zlength_sublist,\n          Zlength_cons, Zlength_nil by (eauto; lia).\n        pose proof (Zlength_nonneg (make_map (sublist (i + 1) (Zlength h') h'))); lia.\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 lia.\n      destruct (Z_le_dec i (Zlength h')); [lia|].\n      unfold sublist in Heq.\n      rewrite Z2Nat_neg in Heq by lia.\n      simpl in Heq; rewrite Zlength_nil in Heq; lia. }\n    assert (i <= Zlength h') by lia.\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 lia.\n      rewrite sublist_split with (al := h)(mid := i) by lia.\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 lia.\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 ENTAIL_refl. }\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 ENTAIL_refl.\n      + rewrite Int.eq_false; [apply ENTAIL_refl | 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 lia; 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; [|lia].\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; [lia|].\n        rewrite Heq, Hhi; simpl.\n        split; [rewrite sublist_upd_Znth_l; auto; lia|].\n        split.\n        - rewrite upd_Znth_same by lia.\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 lia.\n          rewrite sublist_upd_Znth_r; auto; lia. }\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 lia.\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 lia.\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 lia.\n          rewrite upd_Znth_diff; auto.\n          match goal with H : Zlength h' = _ |- _ => setoid_rewrite H; simpl in *; lia 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 ENTAIL_refl].\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; lia).\n        apply prop_right; repeat (split; auto).\n        * erewrite sublist_split, sublist_len_1 with (i1 := i); try lia.\n          erewrite sublist_split with (hi := i + 1), sublist_len_1 with (i1 := i)(d := ([] : hist, [] : hist));\n            rewrite ?upd_Znth_Zlength; try lia.\n          rewrite sublist_upd_Znth_l by lia.\n          rewrite upd_Znth_same by lia.\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 lia.\n          rewrite sublist_upd_Znth_r by lia; 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 lia.\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 lia.\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 lia.\n          rewrite upd_Znth_diff; auto.\n          setoid_rewrite Hlen; simpl in *; lia. }\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 lia.\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 lia.\n      destruct (Z_le_dec i (Zlength h')); [lia|].\n      unfold sublist in Heq.\n      rewrite Z2Nat_neg in Heq by lia.\n      simpl in Heq; rewrite Zlength_nil in Heq; lia. }\n    assert (i < Zlength h') by lia.\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 lia.\n      rewrite sublist_split with (al := h)(mid := i) by lia.\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; lia. }\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 lia; 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; [|lia].\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; [lia|].\n        split; [|split].\n        - rewrite sublist_upd_Znth_l; auto; lia.\n        - rewrite upd_Znth_same by lia.\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 lia.\n          rewrite sublist_upd_Znth_r by lia; 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 lia.\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 lia.\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 lia.\n          rewrite upd_Znth_diff; auto.\n          simpl in *; lia. }\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; [lia|].\n          split; [|split].\n          * rewrite sublist_upd_Znth_l; auto; lia.\n          * rewrite upd_Znth_same by lia.\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 lia.\n            rewrite sublist_upd_Znth_r; auto; lia. }\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 lia.\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 lia.\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 lia.\n             rewrite upd_Znth_diff; auto.\n             simpl in *; lia. }\n      * forward.\n        entailer!.\n      * intros.\n        unfold exit_tycon, overridePost.\n        destruct (eq_dec ek EK_normal); [subst | apply ENTAIL_refl].\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 lia.\n            erewrite sublist_split with (hi := i + 1), sublist_len_1 with (i1 := i)(d := ([] : hist, [] : hist));\n              rewrite ?upd_Znth_Zlength; try lia.\n            rewrite sublist_upd_Znth_l by lia.\n            rewrite upd_Znth_same by lia.\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 lia.\n            rewrite sublist_upd_Znth_r by lia; 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 lia.\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 lia.\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 lia.\n             rewrite upd_Znth_diff; auto.\n             match goal with H : Zlength h' = _ |- _ => setoid_rewrite H; simpl in *; lia 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": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/mailbox/verif_lockfree_linsearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19281264960563574}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.dxcomm Require Import DxIntegers.\n\nFrom bpf.comm Require Import Monad.\nFrom bpf.verifier.comm Require Import state monad.\n\nDefinition M (A: Type) := M state.state A.\n\nDefinition returnM {A: Type} (a: A) : M A := returnM a.\nDefinition bindM {A B: Type} (x: M A) (f: A -> M B) : M B := bindM x f.\n\nDefinition eval_ins_len : M nat := monad.eval_ins_len.\n\nDefinition eval_ins (idx: uint32_t) : M int64_t := monad.eval_ins idx.\n\nDeclare Scope monad_scope.\nNotation \"'do' x <-- a ; b\" :=\n  (bindM a (fun x => b))\n    (at level 200, x name, a at level 100, b at level 200)\n  : monad_scope.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/dxmodel/Dxmonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1928126442180458}}
{"text": "Require Import FP.CoreClasses.\nRequire Import FP.CoreData.\nRequire Import FP.Classes.\n\nImport CoreDataNotation.\nImport ClassesNotation.\nImport CoreClassesNotation.\n\nSection Deriving_Monad_Bijection.\n  Context {T U} (to:forall {A}, T A -> U A) (from:forall {A}, U A -> T A)\n    `{! F_Eqv T ,! F_PER_WF T\n     ,! F_Eqv U ,! F_PER_WF U ,! Monad U ,! MonadWF U\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, Proper eqv from\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, Proper eqv to\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, InjectionInverse (U A) (T A) from to eqv\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, InjectionInverse (T A) (U A) to from eqv\n     }.\n  Arguments to {A} _.\n  Arguments from {A} _.\n\n  Definition deriving_mret_bijection {A} (a:A) : T A := from (mret a).\n  Arguments deriving_mret_bijection {A} _ /.\n  Definition deriving_mbind_bijection {A B} (aM:T A) (k:A -> T B) : T B :=\n    from $ to aM >>= to '.' k.\n  Arguments deriving_mbind_bijection {A B} _ _ /.\n  Local Instance Deriving_Monad_Bijection : Monad T :=\n    { mret := @deriving_mret_bijection\n    ; mbind := @deriving_mbind_bijection\n    }.\n  Local Instance Deriving_MonadWF_Bijection : MonadWF T.\n  Proof.\n    constructor ; intros ; unfold mret,mbind ; simpl.\n    - rewrite InjectionInverse_inv ; logical_eqv.\n      rewrite Monad_left_unit ; logical_eqv ; simpl.\n      apply InjectionInverse_inv ; logical_eqv.\n    - unfold compose ; simpl.\n      transitivity (from (to aM >>= (fun a => mret a))) ; logical_eqv.\n      { rewrite InjectionInverse_inv ; logical_eqv. }\n      rewrite Monad_right_unit ; logical_eqv.\n      rewrite InjectionInverse_inv ; logical_eqv.\n    - rewrite InjectionInverse_inv ; logical_eqv.\n      rewrite Monad_associativity ; logical_eqv ; simpl.\n      rewrite InjectionInverse_inv ; logical_eqv.\n    - unfold Proper ; logical_eqv_intro ; simpl ; logical_eqv.\n    - unfold Proper ; logical_eqv_intro ; simpl ; logical_eqv.\n  Qed.\nEnd Deriving_Monad_Bijection.\nArguments deriving_mret_bijection {T U} from {Monad0 A} a /.\nArguments deriving_mbind_bijection {T U} to from {Monad0 A B} _ _ /.\n\nSection Deriving_MonadCatch_Bijection.\n  Context {T U E} (to:forall {A}, T A -> U A) (from:forall {A}, U A -> T A)\n    `{! Eqv E ,! PER_WF E\n     ,! F_Eqv T ,! F_PER_WF T ,! Monad T ,! MonadWF T\n     ,! F_Eqv U ,! F_PER_WF U ,! Monad U ,! MonadWF U ,! MonadCatch E U ,! MonadCatchWF E U\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, Proper eqv from\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, Proper eqv to\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, InjectionInverse (U A) (T A) from to eqv\n     ,! forall {A} `{! Eqv A ,! PER_WF A }, InjectionInverse (T A) (U A) to from eqv\n     }\n    ( mret_eqv :\n        forall {A} `{! Eqv A ,! PER_WF A } (a:A) `{! Proper eqv a }, mret a ~= from (mret a)\n    )\n    ( mbind_eqv :\n        forall\n          {A B} `{! Eqv A ,! PER_WF A ,! Eqv B ,! PER_WF B }\n          (aM:T A) `{! Proper eqv aM }\n          (k:A -> T B) `{! Proper eqv k},\n        aM >>= k ~= from (to aM >>= to '.' k)\n    ).\n  Arguments to {A} _.\n  Arguments from {A} _.\n\n  Definition deriving_mthrow_bijection {A} : E -> T A :=\n    from '.' mthrow.\n  Arguments deriving_mthrow_bijection {A} _ /.\n  Definition deriving_mcatch_bijection {A} (aM:T A) (k:E -> T A) : T A :=\n    from $ mcatch (to aM) (to '.' k).\n  Arguments deriving_mcatch_bijection {A} _ _ /.\n  Local Instance deriving_MonadCatch_Bijection : MonadCatch E T :=\n    { mthrow := @deriving_mthrow_bijection\n    ; mcatch := @deriving_mcatch_bijection\n    }.\n  Local Instance deriving_MonadCatchWF_Bijection : MonadCatchWF E T.\n  Proof.\n    constructor ; intros ; unfold mcatch,mthrow ; simpl.\n    - rewrite mret_eqv ; logical_eqv.\n      rewrite InjectionInverse_inv ; logical_eqv.\n      rewrite MonadCatch_mcatch_mret ; logical_eqv.\n    - rewrite InjectionInverse_inv ; logical_eqv.\n      rewrite MonadCatch_mcatch_mthrow ; logical_eqv ; simpl.\n      rewrite InjectionInverse_inv ; logical_eqv.\n    - rewrite mbind_eqv ; logical_eqv.\n      rewrite InjectionInverse_inv ; logical_eqv.\n      rewrite MonadCatch_mbind_mthrow ; logical_eqv.\n    - unfold Proper ; logical_eqv_intro ; simpl ; logical_eqv.\n    - unfold Proper ; logical_eqv_intro ; simpl ; logical_eqv.\n  Qed.\nEnd Deriving_MonadCatch_Bijection.\n\nSection Deriving_Applicative_Monad.\n  Context {m} `{! Monad m }.\n  Local Instance Deriving_Applicative_Monad : Applicative m :=\n    { fret := @mret _ _\n    ; fapply := @mbind_fapply _ _\n    }.\nEnd Deriving_Applicative_Monad.\n\nSection Deriving_ApplicativeWF_MonadWF.\n  Context {m}\n    `{! F_Eqv m ,! F_PER_WF m ,! Applicative m ,! Monad m ,! MonadWF m\n     }\n    ( fret_eqv :\n        forall\n          {A} `{! Eqv A ,! PER_WF A }\n          (a:A) `{! Proper eqv a },\n        fret a ~= mret a\n    )\n    ( fapply_eqv :\n        forall\n          {A} `{! Eqv A ,! PER_WF A }\n          {B} `{! Eqv B ,! PER_WF B }\n          (fM:m (A -> B)) `{! Proper eqv fM }\n          (aM:m A) `{! Proper eqv aM },\n        fapply fM aM ~= mbind_fapply fM aM\n    ).\n\n  Global Instance mbind_fapply_Proper\n      {A} `{! Eqv A ,! PER_WF A }\n      {B} `{! Eqv B ,! PER_WF B } :\n    Proper eqv (mbind_fapply (A:=A) (B:=B)).\n  Proof.\n    unfold mbind_fapply ; logical_eqv.\n  Qed.\n\n  Local Instance fret_Proper'\n      {A} `{! Eqv A ,! PER_WF A } :\n    Proper eqv (fret (A:=A)).\n  Proof.\n    unfold Proper ; logical_eqv_intro.\n    repeat rewrite fret_eqv ; logical_eqv.\n  Qed.\n\n  Local Instance fapply_Proper'\n      {A} `{! Eqv A ,! PER_WF A }\n      {B} `{! Eqv B ,! PER_WF B } :\n    Proper eqv (fapply (A:=A) (B:=B)).\n  Proof.\n    unfold Proper ; logical_eqv_intro.\n    repeat rewrite fapply_eqv ; logical_eqv.\n  Qed.\n  Local Hint Extern 9 (Proper eqv fapply) => apply fapply_Proper' : typeclass_instances.\n\n  Definition Deriving_ApplicativeWF_MonadWF : ApplicativeWF m.\n  Proof.\n    constructor ; intros ; eauto with typeclass_instances\n    ; repeat (rewrite fret_eqv ; logical_eqv) ; simpl\n    ; repeat (rewrite fapply_eqv ; logical_eqv) ; simpl.\n    - rewrite Monad_left_unit ; logical_eqv ; simpl.\n      rewrite Monad_right_unit ; auto.\n    - repeat (rewrite Monad_associativity ; logical_eqv) ; simpl.\n      repeat (rewrite Monad_left_unit ; logical_eqv) ; simpl.\n      repeat (rewrite Monad_associativity ; logical_eqv).\n      repeat (rewrite Monad_left_unit ; logical_eqv) ; simpl.\n      repeat (rewrite Monad_associativity ; logical_eqv).\n      repeat (rewrite Monad_left_unit ; logical_eqv) ; simpl.\n      logical_eqv.\n    - repeat (rewrite Monad_left_unit ; logical_eqv) ; simpl.\n    - repeat (rewrite Monad_left_unit ; logical_eqv) ; simpl.\n      logical_eqv.\n  Qed.\nEnd Deriving_ApplicativeWF_MonadWF.\n\nSection Deriving_Functor_Applicative.\n  Context {t} `{! Applicative t }.\n  Local Instance Deriving_Functor_Applicative : Functor t := { fmap := @fapply_fmap _ _ }.\nEnd Deriving_Functor_Applicative.\n\nSection Deriving_FunctorWF_ApplicativeWF.\n  Context {t}\n    `{! F_Eqv t ,! F_PER_WF t ,! Functor t ,! Applicative t ,! ApplicativeWF t }\n    ( fmap_eqv :\n        forall\n          {A} `{! Eqv A ,! PER_WF A }\n          {B} `{! Eqv B ,! PER_WF B }\n          (f:A -> B) `{! Proper eqv f }\n          (aT:t A) `{! Proper eqv aT },\n        fmap f aT ~= fapply_fmap f aT\n    ).\n\n  Global Instance fapply_fmap_respect\n      {A} `{! Eqv A ,! PER_WF A }\n      {B} `{! Eqv B ,! PER_WF B } :\n    Proper eqv (fapply_fmap (A:=A) (B:=B)).\n  Proof.\n    unfold fapply_fmap ; logical_eqv.\n  Qed.\n\n  Local Instance fmap_respect'\n      {A} `{! Eqv A ,! PER_WF A }\n      {B} `{! Eqv B ,! PER_WF B } :\n    Proper eqv (fmap (A:=A) (B:=B)).\n  Proof.\n    unfold Proper ; logical_eqv_intro.\n    repeat rewrite fmap_eqv ; logical_eqv.\n  Qed.\n\n  Definition Deriving_FunctorWF_ApplicativeWF : FunctorWF t.\n  Proof.\n    constructor ; intros ; simpl ; eauto with typeclass_instances\n    ; repeat (rewrite fmap_eqv ; logical_eqv) ; simpl.\n    - rewrite Applicative_unit ; logical_eqv.\n    - rewrite Applicative_composition ; logical_eqv ; simpl.\n      repeat (rewrite Applicative_homomorphism ; logical_eqv) ; simpl.\n  Qed.\nEnd Deriving_FunctorWF_ApplicativeWF.\n\nSection Deriving_Pointed_Applicative.\n  Context {t} `{! Applicative t }.\n  Local Instance Deriving_Pointed_Applicative : Pointed t := { point := @fret _ _ }.\nEnd Deriving_Pointed_Applicative.\n  \nSection Deriving_PointedWF_ApplicativeWF.\n  Context {t}\n    `{! F_Eqv t ,! F_PER_WF t ,! Pointed t ,! Applicative t ,! ApplicativeWF t }\n    ( point_eqv :\n        forall\n          {A} `{! Eqv A ,! PER_WF A }\n          (a:A) `{! Proper eqv a },\n        point a ~= fret a\n    ).\n\n  Local Instance Deriving_PointedWF_ApplicativeWF : PointedWF t.\n  Proof.\n    constructor ; intros ; unfold Proper ; logical_eqv_intro.\n    repeat rewrite point_eqv ; logical_eqv.\n  Qed.\nEnd Deriving_PointedWF_ApplicativeWF.\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/src/DerivingMonad/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1928126442180458}}
{"text": "Redirect \"/var/folders/lm/cpf87_lx21n9bgnl4kr72rjm0000gn/T/coqAHa5FS\"\nTest Search Output Name Only.\nTimeout 1 Print Grammar tactic.\nAdd Search Blacklist \"Private_\" \"_subproof\".\nSet Printing Depth 50.\nRemove Search Blacklist \"Private_\" \"_subproof\".\nAdd Search Blacklist \"Private_\" \"_subproof\".\nFrom Coq Require Import Basics ExtrOcamlIntConv List NArith String.\nFrom ExtLib Require Import Applicative Functor Monad StateMonad.\nFrom ITree Require Import Exception ITree Nondeterminism.\nFrom SimpleIO Require Import IO_Random SimpleIO.\nFrom QuickChick Require Import Decidability Show.\nFrom DeepWeb Require Import Exp.\nImport ApplicativeNotation FunctorNotation ListNotations MonadNotation SumNotations.\nOpen Scope N_scope.\nOpen Scope monad_scope.\nOpen Scope program_scope.\nOpen Scope sum_scope.\nDefinition secret_key := N.\nDefinition public_key := N.\nDefinition shared_key := N.\nDefinition base := 5.\nDefinition prime := 23.\nDefinition derive_public (k : secret_key) : public_key := base ^ k mod prime.\nDefinition calculate_shared (s : secret_key) (p : public_key) : shared_key := p ^ s mod prime.\nDefinition cipher_text := prod shared_key.\nDefinition cipher {plain_text} : shared_key -> plain_text -> cipher_text plain_text := pair.\nDefinition decipher {plain_text} (s : shared_key) (c : cipher_text plain_text) : option plain_text :=\n  let (k, t) := c in if s =? k then Some t else None.\nDefinition random := N.\nAnomaly \"\"Assert_failure printing/ppconstr.ml:399:14\".\" Please report at http://coq.inria.fr/bugs/.\nArguments kvs_data : clear implicits.\nInstance eqKvs_data  (x y : kvs_data id): (Dec (x = y)).\nProof.\ndec_eq.\nDefined.\nInstance showData : (Show (kvs_data id)) :=\n {|\n show := fun d =>\n         match d with\n         | Kvs_GET k => \"GET \" ++ show k\n         | Kvs_PUT k v => \"PUT \" ++ show k ++ \" \" ++ show v\n         | Kvs_CAS k x v => \"CAS \" ++ show k ++ \" \" ++ show x ++ \" \" ++ show v\n         | Kvs_OK v => \"OK  \" ++ show (v : N)\n         | Kvs_NoContent => \"204\"\n         | Kvs_BadRequest => \"400\"\n         | Kvs_PreconditionFailed => \"412\"\n         end |}.\nInstance showDataX : (Show (kvs_data exp)) :=\n {|\n show := fun d =>\n         match d with\n         | Kvs_GET k => \"GET \" ++ show k\n         | Kvs_PUT k v => \"PUT \" ++ show k ++ \" \" ++ show v\n         | Kvs_CAS k x v => \"CAS \" ++ show k ++ \" \" ++ show x ++ \" \" ++ show v\n         | Kvs_OK v => \"OK  \" ++ show v\n         | Kvs_NoContent => \"204\"\n         | Kvs_BadRequest => \"400\"\n         | Kvs_PreconditionFailed => \"412\"\n         end |}.\nDefinition kvs_get {V} (k : N) : list (N * V) -> option V := fmap snd \\226\\136\\152 find (N.eqb k \\226\\136\\152 fst).\nDefinition kvs_put {K} {V} : K -> V -> list (K * V) -> list (K * V) := compose cons \\226\\136\\152 pair.\nModule App.\nAnomaly \"\"Assert_failure printing/ppconstr.ml:399:14\".\" Please report at http://coq.inria.fr/bugs/.\nArguments appE : clear implicits.\nInstance showAppE  {T}: (Show (appE id T)) :=\n {|\n show := fun ae =>\n         match ae with\n         | App_Recv => \"Application Receive\"\n         | App_Send msg => \"Application Send \\226\\159\\185 \" ++ show msg\n         end |}.\nAnomaly \"\"Assert_failure printing/ppconstr.ml:399:14\".\" Please report at http://coq.inria.fr/bugs/.\nDefinition smE := appE exp +' evalE.\nDefinition kvs_state exp_ := list (N * exp_ N).\nDefinition kvs : itree smE void :=\n  rec\n    (fun st : kvs_state exp =>\n     req <- trigger App_Recv;;\n     match req with\n     | Kvs_GET k =>\n         match kvs_get k st with\n         | Some v => embed App_Send (Kvs_OK v);; call st\n         | None => v <- trigger Eval_Var;; embed App_Send (Kvs_OK v);; call (kvs_put k v st)\n         end\n     | Kvs_PUT k v => embed App_Send Kvs_NoContent;; call (kvs_put k (exp_int v) st)\n     | Kvs_CAS k x v' =>\n         match kvs_get k st with\n         | Some v =>\n             b <- trigger (Eval_Decide (exp_eq x v));;\n             (if b : bool\n              then embed App_Send Kvs_NoContent;; call (kvs_put k (exp_int v') st)\n              else embed App_Send Kvs_PreconditionFailed;; call st)\n         | None =>\n             v <- trigger Eval_Var;;\n             b <- trigger (Eval_Decide (exp_eq x v));;\n             (if b : bool\n              then embed App_Send Kvs_NoContent;; call (kvs_put k (exp_int v') st)\n              else embed App_Send Kvs_PreconditionFailed;; call (kvs_put k v st))\n         end\n     | _ => embed App_Send Kvs_BadRequest;; call st\n     end) [].\nDefinition unwrap_data (rx : kvs_data exp) : kvs_data id :=\n  match rx with\n  | Kvs_GET k => Kvs_GET k\n  | Kvs_PUT k v => Kvs_PUT k v\n  | Kvs_CAS k x v => Kvs_CAS k x v\n  | Kvs_OK vx => Kvs_OK (unwrap vx)\n  | Kvs_NoContent => Kvs_NoContent\n  | Kvs_BadRequest => Kvs_BadRequest\n  | Kvs_PreconditionFailed => Kvs_PreconditionFailed\n  end.\nDefinition wrap_data (r : kvs_data id) : kvs_data exp :=\n  match r with\n  | Kvs_GET k => Kvs_GET k\n  | Kvs_PUT k v => Kvs_PUT k v\n  | Kvs_CAS k x v => Kvs_CAS k x v\n  | Kvs_OK v => Kvs_OK (exp_int v)\n  | Kvs_NoContent => Kvs_NoContent\n  | Kvs_BadRequest => Kvs_BadRequest\n  | Kvs_PreconditionFailed => Kvs_PreconditionFailed\n  end.\nAnomaly \"\"Assert_failure printing/ppconstr.ml:399:14\".\" Please report at http://coq.inria.fr/bugs/.\nDefinition embed_exp {T} {E} `{appE id -< E} (ex : appE exp T) : itree E T :=\n  match ex in (appE _ T) return (itree E T) with\n  | App_Recv => trigger App_Recv\n  | App_Send rx => trigger (App_Send (unwrap_data rx))\n  end.\nVariant err :=\n  | Err_Decide : forall bx : exp bool, _\n  | Err_Guard : forall (rx : kvs_data exp) (r : kvs_data id), _\n  | Err_Mismatch : forall {X} {Y} (e0 : appE id X) (te : appE id Y), _\n  | Err_Unify : forall (bx : exp bool) (b : bool), _.\nInstance showErr : (Show err) :=\n {|\n show := fun e =>\n         match e with\n         | Err_Decide bx => \"Cannot decide: \" ++ show bx\n         | Err_Guard rx r => \"Guard error: \" ++ show rx ++ \" <> \" ++ show r\n         | Err_Mismatch e0 te => \"Events mismatch: \" ++ show e0 ++ \" <> \" ++ show te\n         | Err_Unify bx b => \"Cannot unify: \" ++ show bx ++ \" <> \" ++ show b\n         end |}.\nDefinition nmi_of_smi {T} (m : itree smE T) : itree (appE id +' exceptE err +' randomE) T :=\n  interp\n    (fun T e =>\n     match e with\n     | (ae|) => embed_exp ae\n     | (|ee) =>\n         match ee in (evalE T) return (_ T) with\n         | Eval_Var => n <- trigger (||Random_Value);; ret (exp_int n)\n         | Eval_Decide bx => match unwrap' bx with\n                             | Some b => ret b\n                             | None => ret false\n                             end\n         end\n     end) m.\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/10/user-10-session-8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.19277782022841533}}
{"text": "(************************************************************************)\n(*         *   The NaoMod Development Team                              *)\n(*  v      *   INRIA, CNRS and contributors - Copyright 2017-2019       *)\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(**\n This file is an auxilary file for type class for relational transformation\n    engine.\n\n We give here lemmas that can be directly derived from type class [core.Engine]\n\n **)\n\n\n Require Import core.Semantics.\n Require Import core.Syntax.\n Require Import core.Model.\n Require Import core.TransformationConfiguration.\n Require Import String.\n Require Import EqNat.\n Require Import List.\n Require Import Expressions.\n Require Import core.utils.Utils.\n Require Import PeanoNat.\n Require Import Lia.\n Require Import FunctionalExtensionality.\n\n(*********************************************************)\n(** * Metatheorems for relational Transformation Engines *)\n(*********************************************************)\n\n\n\n(* decompose instantiatePattern results *)\nLemma instantiatePattern_distributive:\nforall (tc: TransformationConfiguration),\n  forall a0 sp sm1 n a l,\nIn a0 (instantiatePattern (buildTransformation n (a :: l)) sm1 sp) <->\nIn a0 (instantiatePattern (buildTransformation n [a]) sm1 sp) \\/\nIn a0 (instantiatePattern (buildTransformation n l) sm1 sp).\nProof.\nintros.\nsplit.\n+ intro.\n  unfold instantiatePattern in H.\n  unfold instantiateRuleOnPattern  in H.\n  unfold instantiateIterationOnPattern in H.\n  unfold matchPattern in H.\n  simpl in H.\n  unfold instantiatePattern.\n  unfold instantiateRuleOnPattern.\n  unfold instantiateIterationOnPattern.\n  unfold matchPattern.\n  simpl. \n  remember ((fun r : Rule =>\n  flat_map\n    (fun iter : nat =>\n     flat_map\n       (fun o : OutputPatternElement =>\n        optionToList (instantiateElementOnPattern o sm1 sp iter))\n       (Rule_getOutputPatternElements r))\n    (seq 0 (evalIteratorExpr r sm1 sp)))) as f.\n  remember (filter (fun r : Rule => matchRuleOnPattern r sm1 sp) l) as l1.\n  destruct (matchRuleOnPattern a sm1 sp) eqn: ca.\n  - apply in_flat_map in H.\n    destruct H. destruct H.\n    destruct H.\n    -- rewrite <- H in H0. left. apply in_flat_map. exists x. crush.\n    -- right. apply in_flat_map. exists x. crush.\n  - right. auto.\n+ intro.\nunfold instantiatePattern.\nunfold instantiateRuleOnPattern.\nunfold instantiateIterationOnPattern.\nunfold matchPattern.\nsimpl. \nremember ((fun r : Rule =>\nflat_map\n  (fun iter : nat =>\n   flat_map\n     (fun o : OutputPatternElement =>\n      optionToList (instantiateElementOnPattern o sm1 sp iter))\n     (Rule_getOutputPatternElements r))\n  (seq 0 (evalIteratorExpr r sm1 sp)))) as f.\nremember (filter (fun r : Rule => matchRuleOnPattern r sm1 sp) l) as l1.\ndestruct (matchRuleOnPattern a sm1 sp) eqn: ca.\n++ destruct H.\n- unfold instantiatePattern in H.\nunfold instantiateRuleOnPattern in H.\nunfold instantiateIterationOnPattern in H.\nunfold matchPattern in H.\nsimpl in H.\nrewrite ca in H.\nrewrite <- Heqf in H.\napply in_flat_map in H. destruct H.\napply in_flat_map. exists x. split. crush. crush. \n- unfold instantiatePattern in H.\nunfold instantiateRuleOnPattern in H.\nunfold instantiateIterationOnPattern in H.\nunfold matchPattern in H.\nsimpl in H.\nrewrite <- Heqf in H.\napply in_flat_map in H.\ndestruct H.\napply in_flat_map.\nexists x. split; crush.\n++ destruct H. \nunfold instantiatePattern in H.\nunfold instantiateRuleOnPattern in H.\nunfold instantiateIterationOnPattern in H.\nunfold matchPattern in H.\nsimpl in H.\nrewrite ca in H.\nrewrite <- Heqf in H.\nsimpl in H. inversion H.\nunfold instantiatePattern in H.\nunfold instantiateRuleOnPattern in H.\nunfold instantiateIterationOnPattern in H.\nunfold matchPattern in H.\nsimpl in H.\nrewrite <- Heqf in H.\napply in_flat_map in H.\ndestruct H.\napply in_flat_map.\nexists x. split; crush.\nQed.\n\n(** ** maxArity **)\n\n(*Lemma tr_maxArity_in :\n  forall (eng: TransformationEngine),\n    forall (tr: Transformation) (r: Rule),\n      In r (getRules tr) ->\n      maxArity tr >= length (getInTypes r).\nProof.\n  intros. apply max_list_upperBound. do 2 apply in_map. exact H.\nQed.\n\nTheorem incl_equiv_to_surj:\n  forall (eng: TransformationEngine),\n    (forall (tr: Transformation) (sm : SourceModel)\n       (sp : list SourceModelElement) (tp: list TargetModelElement) (tp1: list TargetModelElement)\n       (r : Rule),\n        instantiateRuleOnPattern r tr sm sp = Some tp1 ->\n        In r (matchPattern tr sm sp) ->\n        instantiatePattern tr sm sp = Some tp ->\n        incl tp1 tp) <->\n    (forall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement) (tp: list TargetModelElement) (te : TargetModelElement),\n        instantiatePattern tr sm sp = Some tp ->\n        (exists (r : Rule) (tp1 : list TargetModelElement),\n            In r (matchPattern tr sm sp) /\\\n            instantiateRuleOnPattern r tr sm sp = Some tp1 /\\\n            In te tp1) ->\n        In te tp).\nProof.\n  split.\n  - intros.\n    destruct H1. destruct H1. destruct H1. destruct H2.\n    + pose (H tr sm sp tp x0 x H2 H1 H0).\n      apply i in H3.\n      assumption.\n  - intros.\n    unfold incl.\n    intros.\n    pose (H tr sm sp tp a H2).\n    apply i.\n    exists r, tp1.\n    split. assumption.\n    split. assumption.\n    assumption.\nQed.\n\nTheorem tr_match_functionality :\n  forall (eng: TransformationEngine)\n    (tr: Transformation) (sm : SourceModel) (sp : list SourceModelElement) (r1: list Rule) (r2: list Rule),\n          matchPattern tr sm sp  = r1 -> matchPattern tr sm sp = r2 -> r1 = r2.\nProof.\n    intros.\n    rewrite H in H0.\n    inversion H0.\n    reflexivity.\nQed.\n\nTheorem tr_matchPattern_None_tr : forall t: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement),\n      getRules tr = nil ->\n      matchPattern tr sm sp = nil.\nProof.\n  intros.\n  destruct (matchPattern tr sm sp) eqn:mtch. reflexivity.\n  exfalso.\n  pose (tr_matchPattern_in tr sm sp r).\n  rewrite H in i.\n  pose (in_eq r l).\n  rewrite <- mtch in i0.\n  apply i in i0.\n  simpl in i0.\n  destruct i0.\n  contradiction.\nQed.\n\n  Theorem tr_matchPattern_non_Nil :\n    forall eng: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel),\n    forall (sp : list SourceModelElement),\n      (matchPattern tr sm sp) <> nil <->\n      (exists (r: Rule),\n        In r (getRules tr) /\\\n        matchRuleOnPattern r tr sm sp = return true).\n  Proof.\n    intros.\n    split.\n    + intro.\n      assert (exists (r: Rule), In r (matchPattern tr sm sp)).\n      {\n        destruct (matchPattern tr sm sp).\n        ++ crush.\n        ++ exists r.\n           crush.\n      }\n      destruct H0.\n      rename x into r.\n      exists r.\n      apply tr_matchPattern_in. auto.\n    + intro.\n      destruct H.\n      apply tr_matchPattern_in in H.\n      destruct (matchPattern tr sm sp).\n      ++ inversion H.\n      ++ crush.\n  Qed.\n\nTheorem tr_instantiatePattern_None_tr : forall t: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement),\n      getRules tr = nil ->\n      (instantiatePattern tr sm sp = None).\nProof.\n  intros.\n  destruct (instantiatePattern tr sm sp) eqn:dst.\n  - apply tr_matchPattern_None_tr with (sm:=sm) (sp:=sp) in H.\n    assert (instantiatePattern tr sm sp <> None). { rewrite dst. discriminate. }\n    apply tr_instantiatePattern_non_None in H0.\n    destruct H0. destruct H0.\n    rewrite H in H0.\n    destruct H0.\n  - reflexivity.\nQed.\n\nTheorem tr_applyPattern_None_tr :\n  forall t: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel) (sp: list SourceModelElement),\n        getRules tr = nil ->\n        (applyPattern tr sm sp = None).\nProof.\n  intros.\n  destruct (applyPattern tr sm sp) eqn:dst.\n  - apply tr_matchPattern_None_tr with (sm:=sm) (sp:=sp) in H.\n    assert (applyPattern tr sm sp <> None). { rewrite dst. discriminate. }\n    apply tr_applyPattern_non_None in H0.\n    destruct H0. destruct H0.\n    rewrite H in H0.\n    destruct H0.\n  - reflexivity.\nQed.\n\nTheorem tr_execute_None_tr_elements : forall t: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel),\n      getRules tr = nil ->\n      allModelElements (execute tr sm) = nil.\nProof.\n  intros.\n  destruct (allModelElements (execute tr sm)) eqn:ame.\n  - reflexivity.\n  - exfalso.\n    pose (tr_execute_in_elements tr sm t0).\n    pose (in_eq t0 l).\n    rewrite <- ame in i0.\n    apply i in i0.\n    destruct i0. destruct H0. destruct H0. destruct H1.\n    pose (tr_instantiatePattern_in tr sm x t0).\n    apply tr_matchPattern_None_tr with (sm:=sm) (sp:=x) in H.\n    destruct i0. destruct H3.\n    -- exists x0.\n       split. assumption. assumption.\n    -- destruct H3.\n       destruct H3.\n       rewrite H in H3.\n       contradiction.\nQed.\n\n  Theorem tr_execute_non_Nil_elements :\n   forall eng: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel),\n      (allModelElements (execute tr sm)) <> nil <->\n      (exists (te : TargetModelElement) (sp : list SourceModelElement) (tp : list TargetModelElement),\n          incl sp (allModelElements sm) /\\\n          instantiatePattern tr sm sp = Some tp /\\\n          In te tp).\n  Proof.\n    intros.\n    split.\n    + intro.\n      assert (exists (te: TargetModelElement), In te (allModelElements (execute tr sm))).\n      {\n        destruct (allModelElements (execute tr sm)).\n        ++ crush.\n        ++ exists t.\n           crush.\n      }\n      destruct H0.\n      rename x into te.\n      exists te.\n      apply tr_execute_in_elements. auto.\n    + intro.\n      destruct H.\n      apply tr_execute_in_elements in H.\n      destruct (allModelElements (execute tr sm)).\n      ++ inversion H.\n      ++ crush.\n  Qed.\n\n\n  Theorem tr_execute_non_Nil_links :\n   forall eng: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel) ,\n      (allModelLinks (execute tr sm)) <> nil <->\n      (exists (tl : TargetModelLink) (sp : list SourceModelElement) (tpl : list TargetModelLink),\n          incl sp (allModelElements sm) /\\\n          applyPattern tr sm sp = Some tpl /\\\n          In tl tpl).\n  Proof.\n    intros.\n    split.\n    + intro.\n      assert (exists (tl: TargetModelLink), In tl (allModelLinks (execute tr sm))).\n      {\n        destruct (allModelLinks (execute tr sm)).\n        ++ crush.\n        ++ exists t.\n           crush.\n      }\n      destruct H0.\n      rename x into tl.\n      exists tl.\n      apply tr_execute_in_links. auto.\n    + intro.\n      destruct H.\n      apply tr_execute_in_links in H.\n      destruct (allModelLinks (execute tr sm)).\n      ++ inversion H.\n      ++ crush.\n  Qed.\n\nTheorem tr_execute_None_tr_links : forall t: TransformationEngine,\n    forall (tr: Transformation) (sm : SourceModel),\n      getRules tr = nil ->\n      allModelLinks (execute tr sm) = nil.\nProof.\n  intros.\n  destruct (allModelLinks (execute tr sm)) eqn:aml.\n  - reflexivity.\n  - exfalso.\n    pose (tr_execute_in_links tr sm t0).\n    pose (in_eq t0 l).\n    rewrite <- aml in i0.\n    apply i in i0.\n    destruct i0. destruct H0. destruct H0. destruct H1.\n    pose (tr_applyPattern_in tr sm x t0).\n    apply tr_matchPattern_None_tr with (sm:=sm) (sp:=x) in H.\n    destruct i0. destruct H3.\n    -- exists x0.\n       split. assumption. assumption.\n    -- destruct H3.\n       destruct H3.\n       rewrite H in H3.\n       contradiction.\nQed.\n\nTheorem tr_applyElementOnPattern_None :\n   forall eng: TransformationEngine,\n      forall (tr:Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat) (ope: OutputPatternElement (getInTypes r) (getIteratorType r)),\n        length sp <> length (getInTypes r) ->\n        applyElementOnPattern r ope tr sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  assert (exists (tl: list TargetModelLink), applyElementOnPattern r ope tr sm sp i = Some tl).\n  { specialize (option_res_dec (applyElementOnPattern r ope tr sm sp)). intros.\n    specialize (H1 i H0). destruct H1. exists x. crush. }\n  destruct H1.\n  assert (exists oper,  In oper (getOutputLinks  (getInTypes r) (getIteratorType r) ope) /\\  applyLinkOnPattern r ope oper tr sm sp i <> None).\n  { specialize (tr_applyElementOnPattern_non_None tr r sm sp i ope). intros. crush. }\n  destruct H2.\n  assert ( applyLinkOnPattern r ope x0 tr sm sp i = None).\n  { specialize (tr_applyLinkOnPattern_None tr sm r sp i ope x0). intros. crush. }\n  crush.\nQed.\n\nTheorem tr_applyIterationOnPattern_None :\n   forall eng: TransformationEngine,\n      forall (tr:Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat),\n        length sp <> length (getInTypes r) ->\n        applyIterationOnPattern r tr sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  assert (exists (tl: list TargetModelLink), applyIterationOnPattern r tr sm sp i = Some tl).\n  { specialize (option_res_dec (applyIterationOnPattern r tr sm sp)). intros.\n    specialize (H1 i H0). destruct H1. exists x. crush. }\n  destruct H1.\n  assert (exists  ope : OutputPatternElement (getInTypes r) (getIteratorType r),\n      In ope (getOutputPattern r) /\\ applyElementOnPattern r ope tr sm sp i <> None).\n  { specialize (tr_applyIterationOnPattern_non_None tr r sm sp i). crush. }\n  destruct H2.\n  destruct H2.\n  assert ( applyElementOnPattern r x0 tr sm sp i = None).\n  { specialize (tr_applyElementOnPattern_None eng tr sm r sp i x0). intros. crush. }\n  crush.\nQed.\n\nTheorem tr_applyRuleOnPattern_None :\n   forall eng: TransformationEngine,\n      forall (tr: Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement),\n        length sp <> length (getInTypes r) ->\n        applyRuleOnPattern r tr sm sp = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  assert (exists (tl: list TargetModelLink), applyRuleOnPattern r tr sm sp = Some tl).\n  { specialize (option_res_dec (applyRuleOnPattern r tr sm)). intros.\n    specialize (H1 sp H0). destruct H1. exists x. crush. }\n  destruct H1.\n  assert (exists (i: nat), i < length (evalIterator r sm sp) /\\ applyIterationOnPattern r tr sm sp i <> None).\n  { specialize (tr_applyRuleOnPattern_non_None tr r sm sp). crush. }\n  destruct H2.\n  destruct H2.\n  assert (applyIterationOnPattern r tr sm sp x0 = None).\n  { specialize (tr_applyIterationOnPattern_None eng tr sm r sp x0). crush. }\n  crush.\nQed.\n\nTheorem tr_instantiateIterationOnPattern_None :\n   forall eng: TransformationEngine,\n     forall (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat),\n        length sp <> length (getInTypes r) ->\n        instantiateIterationOnPattern r sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  assert (exists (tp: list TargetModelElement), instantiateIterationOnPattern r sm sp i = Some tp).\n  { specialize (option_res_dec (instantiateIterationOnPattern r sm sp)). intros.\n    specialize (H1 i H0). destruct H1. exists x. crush. }\n  destruct H1.\n  assert (exists  ope : OutputPatternElement (getInTypes r) (getIteratorType r),\n      In ope (getOutputPattern r) /\\ instantiateElementOnPattern r ope sm sp i <> None).\n  { specialize (tr_instantiateIterationOnPattern_non_None r sm sp i). crush. }\n  destruct H2.\n  destruct H2.\n  assert ( instantiateElementOnPattern r x0 sm sp i = None).\n  { specialize (tr_instantiateElementOnPattern_None sm r sp i x0). intros. crush. }\n  crush.\nQed.\n\nTheorem tr_instantiateRuleOnPattern_None :\n  forall eng: TransformationEngine,\n    forall (tr:Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement),\n      length sp <> length (getInTypes r) ->\n      instantiateRuleOnPattern r tr sm sp = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  assert (exists (tp: list TargetModelElement), instantiateRuleOnPattern r tr sm sp = Some tp).\n  { specialize (option_res_dec (instantiateRuleOnPattern r tr sm)). intros.\n    specialize (H1 sp H0). destruct H1. exists x. crush. }\n  destruct H1.\n  assert (exists (i: nat), i < length (evalIterator r sm sp) /\\ instantiateIterationOnPattern r sm sp i <> None).\n  { specialize (tr_instantiateRuleOnPattern_non_None tr r sm sp). crush. }\n  destruct H2.\n  destruct H2.\n  assert (instantiateIterationOnPattern r sm sp x0 = None).\n  { specialize (tr_instantiateIterationOnPattern_None eng sm r sp x0). crush. }\n  crush.\nQed.\n\nTheorem tr_instantiateIterationOnPattern_None_iterator :\n forall eng: TransformationEngine,\n  forall (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat),\n      i >= length (evalIterator r sm sp) ->\n      instantiateIterationOnPattern r sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  specialize (tr_instantiateIterationOnPattern_non_None r sm sp i).\n  intros.\n  destruct H1.\n  specialize (H1 H0).\n  destruct H1. destruct H1.\n  specialize (tr_instantiateElementOnPattern_None_iterator sm r sp x H).\n  crush.\nQed.\n\nTheorem tr_applyElementOnPattern_None_iterator :\n  forall eng: TransformationEngine,\n    forall (tr:Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat) (ope: OutputPatternElement (getInTypes r) (getIteratorType r)),\n      i >= length (evalIterator r sm sp) ->\n      applyElementOnPattern r ope tr sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  specialize (tr_applyElementOnPattern_non_None tr r sm sp i ope).\n  intros.\n  destruct H1.\n  specialize (H1 H0).\n  destruct H1. destruct H1.\n  specialize (tr_applyLinkOnPattern_None_iterator tr sm r sp).\n  intros.\n  specialize (H4 i ope x H).\n  crush.\nQed.\n\nTheorem tr_applyIterationOnPattern_None_iterator :\n   forall eng: TransformationEngine,\n    forall (tr:Transformation) (sm : SourceModel) (r: Rule) (sp: list SourceModelElement) (i : nat),\n      i >= length (evalIterator r sm sp) ->\n      applyIterationOnPattern r tr sm sp i = None.\nProof.\n  intros. apply None_is_not_non_None. intro H0.\n  specialize (tr_applyIterationOnPattern_non_None tr r sm sp i).\n  intros.\n  destruct H1.\n  specialize (H1 H0).\n  destruct H1. destruct H1.\n  specialize (tr_applyElementOnPattern_None_iterator eng tr sm r sp i x H).\n  crush.\nQed.\n*)", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/core/EngineProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.19277781663118998}}
{"text": "From cap_machine.binary_model Require Export logrel_binary.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine.binary_model Require Import ftlr_base_binary monotone_binary.\nFrom cap_machine.binary_model Require Import rules_binary_base interp_weakening_binary.\nFrom cap_machine.rules Require Import rules_Lea rules_base.\nFrom cap_machine.binary_model.rules_binary Require Import rules_binary_Lea rules_binary_base.\n\nSection fundamental.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {stsg : STSG Addr region_type \u03a3} {heapg : heapG \u03a3}\n          {nainv: logrel_na_invs \u03a3} {cfgg : cfgSG \u03a3}\n          `{MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n  Notation WORLD := (prodO STS_STD STS).\n  Implicit Types W : WORLD.\n\n  Notation D := (WORLD -n> (prodO (leibnizO Word) (leibnizO Word)) -n> iPropO \u03a3).\n  Notation R := (WORLD -n> (prodO (leibnizO Reg) (leibnizO Reg)) -n> iPropO \u03a3).\n  Implicit Types v : (prodO (leibnizO Word) (leibnizO Word)).\n  Implicit Types interp : (D).\n\n  Lemma Lea_spec_determ r dst src regs regs' retv retv' :\n    Lea_spec r dst src regs retv ->\n    Lea_spec r dst src regs' retv' ->\n    (regs = regs' \u2228 retv = FailedV) \u2227 retv = retv'.\n  Proof.\n    intros Hspec1 Hspec2.\n    inversion Hspec1; inversion Hspec2; subst; simplify_eq; split; auto; try congruence.\n    - inv H7; try congruence. rewrite H0 in H6; congruence.\n      rewrite H0 in H6. inv H6. rewrite H2 in H8. simplify_eq.\n      destruct p0;try done.\n    - inv H7; try congruence. rewrite H0 in H6; congruence.\n      rewrite H0 in H6. inv H6. rewrite H2 in H8. simplify_eq.\n      destruct p0;try done.\n    - inv H0; try congruence. rewrite H1 in H2; congruence.\n      rewrite H4 in H8. inv H8. rewrite H1 in H2. inv H2. rewrite H5 in H9. inv H9.\n      destruct p;try done.\n  Qed.\n\n  Lemma lea_case (W : WORLD) (r : prodO (leibnizO Reg) (leibnizO Reg)) (p : Perm)\n        (g : Locality) (b e a : Addr) (w : Word) (\u03c1 : region_type) (dst : RegName) (r0 : Z + RegName) (P:D):\n    ftlr_instr W r p g b e a w (Lea dst r0) \u03c1 P.\n  Proof.\n    intros Heqregs Hp Hsome i Hbae Hpers Hpwl Hregion Hnotrevoked Hnotmonostatic Hnotuninitialized Hi.\n    iIntros \"#Hspec #IH #Hinv #Hreg #Hinva #Hrcond #Hwcond Hmono Hw Hsts Hown\".\n    iIntros \"Hr Hstate Ha Ha' HPC Hmap HsPC Hsmap Hj\".\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    iDestruct ((big_sepM_delete _ _ PC) with \"[HsPC Hsmap]\") as \"Hsmap /=\";\n      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n    iApply (wp_lea with \"[$Ha $Hmap]\"); eauto.\n    { by rewrite lookup_insert. }\n    { rewrite /subseteq /map_subseteq /set_subseteq. intros rr _.\n      apply elem_of_gmap_dom. apply lookup_insert_is_Some'. destruct Hsome with rr;eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n\n    iMod (step_lea _ [SeqCtx] with \"[$Ha' $Hsmap $Hj $Hspec]\") as (retv' regs'') \"(Hj & % & Ha' & Hsmap')\";eauto.\n    { by rewrite lookup_insert. }\n    { rewrite /subseteq /map_subseteq /set_subseteq. intros rr _.\n      apply elem_of_gmap_dom. apply lookup_insert_is_Some'. destruct Hsome with rr;eauto. }\n\n    specialize (Lea_spec_determ _ _ _ _ _ _ _ HSpec H0) as [Heq ->].\n\n    destruct HSpec as [ * Hdst ? Hz Hoffset HUa HincrPC |].\n    { apply incrementPC_Some_inv in HincrPC as (p''&g''&b''&e''&a''& ? & HPC & Z & Hregs' & XX).\n\n      assert (p'' = p \u2227 g'' = g \u2227 b'' = b \u2227 e'' = e) as (-> & -> & -> & ->).\n      { destruct (decide (PC = dst)); simplify_map_eq; auto. }\n\n      destruct Heq as [<- | Hcontr];[|inversion Hcontr].\n\n      iApply wp_pure_step_later; auto. iNext.\n      iMod (do_step_pure _ [] with \"[$Hspec $Hj]\") as \"Hs' /=\";auto.\n      iDestruct (region_close with \"[$Hstate $Hr $Ha $Ha' $Hmono Hw]\") as \"Hr\"; eauto.\n      { destruct \u03c1;auto;[|specialize (Hnotmonostatic g1)|specialize (Hnotuninitialized p1)];contradiction. }\n      iApply (\"IH\" $! _ (regs',regs') with \"[] [Hmap] [Hsmap'] [$Hr] [$Hsts] [$Hown] [$Hs']\").\n      { iSplit. cbn. intros. subst regs'. iPureIntro.\n        split; repeat (apply lookup_insert_is_Some'; right);destruct Hsome with x0;eauto.\n        iIntros (ri Hri). subst regs'.\n        simpl. rewrite /RegLocate lookup_insert_ne//.\n        destruct (decide (ri = dst)).\n        { subst ri. unshelve iSpecialize (\"Hreg\" $! dst _); eauto.\n          rewrite lookup_insert. assert (Hdst':=Hdst). rewrite Heqregs in Hdst'.\n          rewrite lookup_insert_ne// in Hdst. rewrite lookup_insert_ne// in Hdst'.\n          rewrite Hdst Hdst'. iApply interp_weakening; eauto; try solve_addr.\n          - destruct p0; simpl; auto.\n          - eapply PermFlowsToReflexive.\n          - destruct g0; auto. }\n        { rewrite !lookup_insert_ne//.\n          iDestruct (\"Hreg\" $! _ Hri) as \"HH\".\n          rewrite -(lookup_insert_ne r.2 PC _ (inl 0%Z))// -Heqregs lookup_insert_ne//.\n      } }\n      { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      { subst regs'. rewrite insert_insert. iApply \"Hsmap'\". }\n      { iPureIntro. tauto. }\n      eauto. }\n    { iApply wp_pure_step_later; auto. iNext.\n      iApply wp_value; auto. iIntros; discriminate. }\n  Qed.\n\nEnd fundamental.\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/ftlr_binary/Lea_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.1927778146626685}}
{"text": "Require Import Min.\nRequire Import Arith.\nRequire Import Word.\nRequire Import Prog ProgMonad.\nRequire Import Hoare.\nRequire Import SepAuto.\nRequire Import BasicProg.\nRequire Import Omega.\nRequire Import Log.\nRequire Import Array.\nRequire Import List ListUtils.\nRequire Import Bool.\nRequire Import Setoid.\nRequire Import Rec.\nRequire Import FunctionalExtensionality.\nRequire Import NArith.\nRequire Import WordAuto.\nRequire Import RecArrayUtils LogRecArray.\nRequire Import GenSepN.\nRequire Import Balloc.\nRequire Import ListPred.\nRequire Import FSLayout.\nRequire Import AsyncDisk.\nRequire Import Inode.\nRequire Import GenSepAuto.\nRequire Import DiskSet.\nRequire Import DirTreeDef.\nRequire Import Bytes.\nRequire Import VBConv.\nRequire Import Fscq.Hashmap.\nRequire Import Errno.\nRequire Import PeanoNat.\nRequire Import Pred PredCrash.\nRequire Import Rounding.\n\nSet Implicit Arguments.\n\n\n(* Definitions *)\nDefinition attr := INODE.iattr.\nDefinition attr0 := INODE.iattr0.\n\nRecord proto_bytefile := mk_proto_bytefile {\n  PByFData : list (list byteset)\n}.\nDefinition proto_bytefile0 := mk_proto_bytefile nil.\n\nRecord unified_bytefile := mk_unified_bytefile {\n  UByFData : list byteset\n}.\nDefinition unified_bytefile0 := mk_unified_bytefile nil.\n\nRecord bytefile := mk_bytefile {\n  ByFData : list byteset;\n  ByFAttr : INODE.iattr\n}.\nDefinition bytefile0 := mk_bytefile nil attr0.\n\nDefinition bfiledata2protobytefile fd : proto_bytefile :=\nmk_proto_bytefile (map valuset2bytesets fd).\n\nDefinition protobytefile2unifiedbytefile pfy : unified_bytefile :=\nmk_unified_bytefile (concat (PByFData pfy)). \n\nDefinition unifiedbytefile2bytefiledata ufy len: list byteset :=\n(firstn len (UByFData ufy)).\n\nDefinition unifiedbytefile2bytefile ufy len iattr: bytefile :=\nmk_bytefile (firstn len (UByFData ufy)) iattr.\n\nDefinition bfiledata2bytefiledata fd len: list byteset:=\nunifiedbytefile2bytefiledata (protobytefile2unifiedbytefile (bfiledata2protobytefile fd)) len.\n\nDefinition bfile2bytefile f len: bytefile:=\nunifiedbytefile2bytefile (protobytefile2unifiedbytefile (bfiledata2protobytefile (DFData f))) len (DFAttr f).\n\nFixpoint upd_range {V} (m : @Mem.mem addr addr_eq_dec V) (a : addr) (l : list V) : @Mem.mem addr _ V :=\nmatch l with\n| nil => m\n| h::t => upd_range (Mem.upd m a h) (a+1) t\nend.\n\n\n(* Definition ext_opt T (ov: option T) def :=\nmatch ov with\n| None => def\n| Some v => v\nend.\n *)\n \nDefinition some_strip {V} (o: option V) def: V :=\nmatch o with\n\t| None => def\n\t| Some v => v\nend.\n\nLtac split_hypothesis_helper:=\n  match goal with\n  | [ H: exists _, _ |- _ ] => destruct H\n  | [ H: _ /\\ _ |- _] => destruct H\n  end.\n  \nLtac split_hypothesis:= repeat split_hypothesis_helper. \n\n\n(* rep invariants *)\nDefinition proto_bytefile_valid f pfy: Prop :=\n(PByFData pfy) = map valuset2bytesets (DFData f).\n\nDefinition unified_bytefile_valid pfy ufy: Prop := \nUByFData ufy = concat (PByFData pfy).\n\nDefinition bytefile_valid ufy fy: Prop :=\nByFData fy = firstn (length(ByFData fy)) (UByFData ufy).\n  \nDefinition rep (f:dirfile) (fy:bytefile) :=\n  exists pfy ufy,\n    proto_bytefile_valid f pfy /\\\n    unified_bytefile_valid pfy ufy /\\\n    bytefile_valid ufy fy /\\ \n    ByFAttr fy = DFAttr f /\\\n    #(INODE.ABytes (ByFAttr fy)) = length (ByFData fy) /\\\n    (roundup (length (ByFData fy)) valubytes = (length (DFData f)) * valubytes)%nat.\n\n(* Definition byte_belong_to_file ilist byn inum:=\n    (exists bn, BFILE.block_belong_to_file ilist bn inum (byn/valubytes)) /\\\n    byn < #(INODE.ABytes (INODE.IAttr (selN ilist inum INODE.inode0))). *)\n\n(* Definition ptsto_subset_b {AT AEQ} (a : AT) (bs : byteset) : @pred AT AEQ byteset :=\n(exists old, a |-> (fst bs, old) * [[incl (fst bs :: old) (fst bs :: snd bs)]])%pred. *)\n\n(* Definition isSubset (bsl bsl': @Mem.mem addr addr_eq_dec byteset):= (forall a, bsl' a = bsl a \\/ \n\t\t(bsl a <> None /\\ bsl' a = Some (fst (some_strip (bsl a) byteset0), fst (some_strip (bsl a) byteset0)::snd(some_strip (bsl a) byteset0)))).\n\nDefinition subset_invariant_bs (p: pred) : Prop :=\nforall (bsl bsl': @Mem.mem addr addr_eq_dec byteset), bsl <> bsl' -> isSubset bsl bsl' -> p bsl -> p bsl'.\n *)\n(* Helper lemmas.*)\n\nLemma diskIs_id: forall AT AEQ V (m:Mem.mem), @diskIs AT AEQ V m m.\nProof. intros; unfold diskIs; reflexivity. Qed.\n\nLemma addr_id: forall A (l: list A) a def, \na < length l ->\n((diskIs (mem_except (list2nmem l) a)) * a |-> (selN l a def))%pred (list2nmem l).\nProof.\nintros.\neapply diskIs_extract.\neapply list2nmem_ptsto_cancel in H.\npred_apply; cancel.\nfirstorder.\nQed.\n\nLemma mem_except_range_O: forall AEQ V (m: @Mem.mem _ AEQ V) a,\nmem_except_range m a 0 = m.\nProof.\nintros.\nunfold mem_except_range.\nrewrite <- plus_n_O.\napply functional_extensionality.\nintros.\ndestruct (le_dec a x);\ndestruct (lt_dec x a); try omega; try reflexivity.\nQed.\n\nFact out_except_range_then_in: forall (l: list valuset) s a n def,\na < length l ->\na < s \\/ a >= s + n ->\n(exists F0 : pred, (sep_star (AEQ:= addr_eq_dec) F0 (a |-> some_strip ((list2nmem l) a) def))%pred (@mem_except_range addr_eq_dec valuset (list2nmem l) s n)).\nProof.\nintros.\neexists.\napply sep_star_comm.\napply mem_except_ptsto with (a:= a).\nunfold mem_except_range.\ndestruct H0.\ndestruct (le_dec s a); try omega.\nunfold list2nmem, some_strip.\nerewrite selN_map.\nreflexivity. auto.\ndestruct (lt_dec a (s + n)); try omega.\ndestruct (le_dec s a); try omega.\nunfold list2nmem, some_strip.\nerewrite selN_map.\nreflexivity. auto.\ninstantiate (1:= diskIs (mem_except (mem_except_range (list2nmem l) s n) a)).\napply diskIs_id.\nGrab Existential Variables.\napply valuset0.\napply valuset0.\nQed. \n\nFact mem_ex_mem_ex_range_head: forall V AEQ i j (m: @Mem.mem _ AEQ V),\nmem_except (AEQ:= AEQ) (mem_except_range m (i + 1) j) i = mem_except_range m i (j + 1).\nProof.\nintros.\nunfold mem_except, mem_except_range.\napply functional_extensionality; intros.\ndestruct (AEQ x i).\nrewrite e.\ndestruct (le_dec i i).\ndestruct (lt_dec i (i + (j + 1))).\nreflexivity.\nomega.\nomega.\n\ndestruct (le_dec i x).\ndestruct (le_dec (i+1) x).\ndestruct (lt_dec x (i + 1 + j)).\ndestruct (lt_dec x (i + (j + 1))).\nreflexivity.\nomega.\ndestruct (lt_dec x (i + (j + 1))).\nomega.\nreflexivity.\ndestruct (lt_dec x (i + (j + 1))).\nomega.\nreflexivity.\ndestruct (le_dec (i+1) x).\ndestruct (lt_dec x (i + 1 + j)).\nomega.\nall: reflexivity.\nQed.\n\nFact mem_ex_mem_ex_range_tail: forall V AEQ i j (m: @Mem.mem _ AEQ V),\nmem_except (AEQ:= AEQ) (mem_except_range m i j) (i + j) = mem_except_range m i (j + 1).\nProof.\nintros.\nunfold mem_except, mem_except_range.\napply functional_extensionality; intros.\ndestruct (AEQ x (i + j)).\nrewrite e.\ndestruct (le_dec i (i + j)).\ndestruct (lt_dec (i + j) (i + (j + 1))).\nreflexivity.\nomega.\nomega.\n\ndestruct (le_dec i x).\ndestruct (lt_dec x (i + j)).\ndestruct (lt_dec x (i + (j + 1))).\nreflexivity.\nomega.\ndestruct (lt_dec x (i + (j + 1))).\nomega.\nreflexivity.\nreflexivity.\nQed.\n\n\nLemma block_content_match: forall F f vs block_off def, \n(F * block_off|-> vs)%pred (list2nmem(DFData f))-> \nvs = selN (DFData f) block_off def.\nProof.\nintros.\nunfold valu2list.\neapply ptsto_valid' in H.\nunfold list2nmem in H.\nerewrite selN_map in H.\nsimpl in H.\nunfold map in H.\nsymmetry;\napply some_eq. apply H.\neapply selN_map_some_range.\napply H.\nQed.\n\nLemma pick_from_block: forall F f block_off vs i def def', \ni < valubytes -> (F * block_off |-> vs)%pred (list2nmem (DFData f)) ->\nselN (valu2list (fst vs)) i def = selN (valu2list (fst (selN (DFData f) block_off def'))) i def.\nProof.\nintros.\nerewrite block_content_match with (f:=f) (vs:=vs) (block_off:= block_off) (def:= def').\nreflexivity.\napply H0.\nQed.\n\nLemma len_f_fy: forall f fy,\nByFData fy =\n     firstn (length(ByFData fy))\n       (flat_map valuset2bytesets (DFData f))->\n length (ByFData fy) <= length (DFData f) * valubytes.\nProof.\nintros.\nrewrite H.\nrewrite firstn_length.\nrewrite flat_map_len.\napply le_min_r.\nQed.\n\nLemma bytefile_unified_byte_len: forall ufy fy, \nbytefile_valid ufy fy -> \nlength(ByFData fy) <= length(UByFData ufy).\nProof.\nintros.\nrewrite H.\nrewrite firstn_length.\napply le_min_r.\nQed.\n\nLemma unified_byte_protobyte_len: forall pfy ufy k,\nunified_bytefile_valid pfy ufy ->\nForall (fun sublist : list byteset => length sublist = k) (PByFData pfy) ->\nlength(UByFData ufy) = length (PByFData pfy) * k.\nProof.\nintros.\nrewrite H.\napply concat_hom_length with (k:= k).\napply H0.\nQed.\n\nLemma byte2unifiedbyte: forall ufy fy F a b,\nbytefile_valid ufy fy ->\n(F * a|-> b)%pred (list2nmem (ByFData fy)) ->\n (F * (arrayN (ptsto (V:= byteset)) (length(ByFData fy)) \n          (skipn (length(ByFData fy)) (UByFData ufy)))\n  * a|->b)%pred (list2nmem (UByFData ufy)).\nProof.\nunfold bytefile_valid; intros.\npose proof H0.\nrewrite H in H0.\napply list2nmem_sel with (def:= byteset0) in H0.\nrewrite H0.\nrewrite selN_firstn.\napply sep_star_comm.\napply sep_star_assoc.\nreplace (list2nmem(UByFData ufy))\n    with (list2nmem(ByFData fy ++ skipn (length (ByFData fy)) (UByFData ufy))).\napply list2nmem_arrayN_app.\napply sep_star_comm.\nrewrite selN_firstn in H0.\nrewrite <- H0.\napply H1.\napply list2nmem_inbound in H1.\napply H1.\nrewrite H.\nrewrite firstn_length.\nrewrite min_l. \nrewrite firstn_skipn.\nreflexivity.\napply bytefile_unified_byte_len.\napply H.\napply list2nmem_inbound in H1.\napply H1.\nQed.\n\nLemma unifiedbyte2protobyte: forall pfy ufy a b F k,\nunified_bytefile_valid pfy ufy ->\nForall (fun sublist : list byteset => length sublist = k) (PByFData pfy) ->\nk > 0 ->\n(F * a|->b)%pred (list2nmem (UByFData ufy)) ->\n(diskIs (mem_except (list2nmem (PByFData pfy)) (a/k))  * \n(a/k) |-> get_sublist (UByFData ufy) ((a/k) * k) k)%pred (list2nmem (PByFData pfy)).\nProof.\nunfold get_sublist, unified_bytefile_valid.\nintros.\nrewrite H.\nrewrite concat_hom_skipn with (k:= k).\nreplace (k) with (1 * k) by omega.\nrewrite concat_hom_firstn.\nrewrite firstn1.\nrewrite skipn_selN.\nsimpl.\nrepeat rewrite <- plus_n_O.\napply addr_id.\napply Nat.div_lt_upper_bound.\nunfold not; intros.\nrewrite H3 in H1; inversion H1.\nrewrite Nat.mul_comm.\nrewrite <- unified_byte_protobyte_len with (ufy:= ufy).\napply list2nmem_inbound in H2.\napply H2.\napply H.\napply H0.\nsimpl;  rewrite <- plus_n_O.\napply forall_skipn.\napply H0.\napply H0.\nQed.\n\nLemma protobyte2block: forall a b f pfy,\nproto_bytefile_valid f pfy ->\n(diskIs (mem_except (list2nmem (PByFData pfy)) a) * a|->b)%pred (list2nmem (PByFData pfy)) ->\n(diskIs (mem_except (list2nmem (DFData f)) a) * a|->(bytesets2valuset b))%pred (list2nmem (DFData f)).\nProof.\nunfold proto_bytefile_valid; intros.\nrewrite H in H0.\npose proof H0.\neapply list2nmem_sel in H0.\nerewrite selN_map in H0.\nrewrite H0.\nrewrite valuset2bytesets2valuset.\napply addr_id.\napply list2nmem_inbound in H1.\nrewrite map_length in H1.\napply H1.\napply list2nmem_inbound in H1.\nrewrite map_length in H1.\napply H1.\nGrab Existential Variables.\napply nil.\napply valuset0.\nQed. \n\nLemma bytefile_bfile_eq: forall f pfy ufy fy,\nproto_bytefile_valid f pfy -> \nunified_bytefile_valid pfy ufy -> \nbytefile_valid ufy fy ->\nByFData fy = firstn (length (ByFData fy)) (flat_map valuset2bytesets (DFData f)).\nProof.\nunfold proto_bytefile_valid, \n    unified_bytefile_valid, \n    bytefile_valid.\nintros.\ndestruct_lift H.\nrewrite flat_map_concat_map.\nrewrite <- H.\nrewrite <- H0.\napply H1.\nQed.\n\nFact inlen_bfile: forall f fy i j Fd data, \nrep f fy ->\nj < valubytes -> \nlength data > 0 ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (i * valubytes + j) data)%pred (list2nmem (ByFData fy)) ->\ni < length (DFData f).\nProof.\nunfold rep; intros.\nsplit_hypothesis.\neapply list2nmem_arrayN_bound in H2.\ndestruct H2.\nrewrite H2 in H1.\ninversion H1.\nrewrite len_f_fy with (f:=f) (fy:=fy) in H2.\napply le2lt_l in H2.\napply lt_weaken_l with (m:= j) in H2.\napply lt_mult_weaken in H2.\napply H2.\napply H1.\neapply bytefile_bfile_eq; eauto.\nQed.\n\nFact block_exists: forall f pfy ufy fy i j Fd data,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\nj < valubytes -> length data > 0 ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (i * valubytes + j) data)%pred (list2nmem (ByFData fy)) ->\nexists F vs, (F \u2736 i |-> vs)%pred (list2nmem (DFData f)).\nProof.\nintros.\nrepeat eexists.\neapply unifiedbyte2protobyte with (a:= i * valubytes + j) (k:= valubytes)in H0.\nrewrite div_eq in H0.\nunfold proto_bytefile_valid in H.\neapply protobyte2block; eauto.\napply H2.\napply Forall_forall; intros.\nrewrite H in H5.\napply in_map_iff in H5.\ndestruct H5.\ninversion H5.\nrewrite <- H6.\napply valuset2bytesets_len.\nomega.\neapply byte2unifiedbyte.\neauto.\npred_apply.\nrewrite arrayN_isolate with (i:=0).\nrewrite <- plus_n_O .\ncancel.\nauto.\nGrab Existential Variables.\napply byteset0.\nQed.\n\nFact proto_len: forall f pfy,\nproto_bytefile_valid f pfy ->\nForall (fun sublist : list byteset => length sublist = valubytes) (PByFData pfy).\nProof.\nintros.\napply Forall_forall; intros.\nrewrite H in H0.\napply in_map_iff in H0.\ndestruct H0.\ninversion H0.\nrewrite <- H1.\napply valuset2bytesets_len.\nQed.\n\nFact proto_skip_len: forall f pfy i,\nproto_bytefile_valid f pfy ->\nForall (fun sublist : list byteset => length sublist = valubytes) (skipn i (PByFData pfy)).\nProof.\nintros.\napply Forall_forall; intros.\napply in_skipn_in in H0.\nrewrite H in H0.\nrewrite in_map_iff in H0.\nrepeat destruct H0.\napply valuset2bytesets_len.\nQed.\n\nFact content_match: forall Fd f pfy ufy fy i j data,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (i * valubytes + j) data)%pred (list2nmem (ByFData fy)) ->\nj < valubytes ->\nlength data > 0 ->\nj + length data <= valubytes ->\nByFAttr fy = DFAttr f ->\n# (INODE.ABytes (ByFAttr fy)) = length (ByFData fy) ->\nroundup (length (ByFData fy)) valubytes = length (DFData f) * valubytes ->\nget_sublist (valu2list (fst (bytesets2valuset (selN (PByFData pfy) i nil)))) j (length data) = map fst data.\n Proof.\n intros.\n       \nunfold get_sublist.\napply arrayN_list2nmem in H2 as H1'.\nrewrite H1 in H1'.\nrewrite <- skipn_firstn_comm in H1'.\nrewrite firstn_firstn in H1'.\nrewrite min_l in H1'.\nrewrite H0 in H1'.\n\nrewrite skipn_firstn_comm in H1'.\nrewrite Nat.add_comm in H1'.\nrewrite <- skipn_skipn with (m:= i * valubytes) in H1'.\nrewrite concat_hom_skipn in H1'.\nrewrite <- skipn_firstn_comm in H1'.\nerewrite <- concat_hom_subselect_firstn with (k:= valubytes) in H1'.\n\nrewrite H in *.\nerewrite selN_map in *.\nrewrite valuset2bytesets2valuset.\n\nrewrite skipn_firstn_comm in H1'.\nrewrite H1'.\nrewrite firstn_length.\nrewrite skipn_length.\nrewrite min_l.\nrewrite <- firstn_map_comm.\nrewrite <- skipn_map_comm.\n\nrewrite mapfst_valuset2bytesets.\nreflexivity.\n\nrewrite valuset2bytesets_len.\nomega.\n\nall: try eapply inlen_bfile; eauto.\nall: try eapply proto_len; eauto.\nunfold rep; repeat eexists; eauto.\nunfold rep; repeat eexists; eauto.\nunfold rep; repeat eexists; eauto.\n\nrewrite H; rewrite map_length.\neapply inlen_bfile; eauto.\nunfold rep; repeat eexists; eauto.\n\napply list2nmem_arrayN_bound in H2.\ndestruct H2.\nrewrite H2 in H4; inversion H4.\nomega.\n\n\napply byteset0.\n\nGrab Existential Variables.\napply valuset0.\napply nil.\nQed.\n\n\n\n(* Fact iblocks_file_len_eq: forall F bxp ixp flist ilist frees m inum,\ninum < length ilist ->\n(F * BFILE.rep bxp ixp flist ilist frees)%pred m ->\nlength (INODE.IBlocks (selN ilist inum INODE.inode0)) = length (DFData (selN flist inum BFILE.bfile0)).\nProof. \nintros.\nunfold BFILE.rep in H0.\nrepeat rewrite sep_star_assoc in H0.\napply sep_star_comm in H0.\nrepeat rewrite <- sep_star_assoc in H0.\n\nunfold BFILE.file_match in H0.\nrewrite listmatch_isolate with (i:=inum) in H0.\nsepauto.\nrewrite listmatch_length_pimpl in H0.\nsepauto.\nrewrite listmatch_length_pimpl in H0.\nsepauto.\nQed.\n *)\n\n\nFact flist_eq_ilist: forall F F' flist flist' ilist m, \n  (@sep_star addr addr_eq_dec valuset \n      F  (listmatch (fun (v : valuset) (a : addr) => a |-> v) flist ilist))%pred m ->\n  (@sep_star addr addr_eq_dec valuset \n      F'  (listmatch (fun (v : valuset) (a : addr) => a |-> v) flist' ilist))%pred m ->\n  forall i def, i < length flist -> selN flist i def = selN flist' i def.\nProof.\n  intros.\n  eapply sep_star_ptsto_some_eq with (a:= (selN ilist i _)).\n  erewrite listmatch_isolate with (i:= i) in H.\n  apply sep_star_comm.\n  eapply sep_star_assoc in H.\n  eapply H.\n  auto.\n  apply listmatch_length_r in H as H'.\n  rewrite <- H'; auto.\n  rewrite listmatch_extract with (i:= i) in H0.\n  destruct_lift H; destruct_lift H0.\n  apply ptsto_valid' in H0.\n  unfold selN in *.\n  instantiate (1:= 0).\n  eauto.\n  apply listmatch_length_r in H as H'.\n  apply listmatch_length_r in H0 as H0'.\n  omega.\nQed.\n\n\nFact unibyte_len: forall f pfy ufy fy i,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\ni * valubytes < length (ByFData fy) ->\n(S i) * valubytes <= length (UByFData ufy).\nProof.\nintros.\nerewrite unified_byte_protobyte_len with (k:= valubytes); eauto.\napply mult_le_compat_r.\napply lt_le_S.\neapply lt_le_trans with (m:= length (ByFData fy)) in H2.\n2: apply bytefile_unified_byte_len; eauto.\nerewrite unified_byte_protobyte_len with (k:= valubytes) in H2; eauto.\napply lt_mult_weaken in H2; auto.\neapply proto_len; eauto.\neapply proto_len; eauto.\nQed.\n\n\nFact inbound_bytefile_bfile: forall a  b f pfy ufy fy,\n  proto_bytefile_valid f pfy ->\n  unified_bytefile_valid pfy ufy ->\n  bytefile_valid ufy fy ->\n  a * valubytes + b < length (ByFData fy) ->\n  a < length (DFData f).\nProof.\nintros.\napply bytefile_unified_byte_len in H1.\neapply lt_le_trans with (m:= length (ByFData fy))in H2.\n2:eauto.\nerewrite unified_byte_protobyte_len with (k:= valubytes) in H2.\n2:eauto.\napply lt_weaken_l in H2.\nrewrite H in H2.\nrewrite map_length in H2.\napply lt_mult_weaken in H2.\nauto.\neapply proto_len; eauto.\nQed. \n\n\nFact bfile_bytefile_same: forall a  b f pfy ufy fy,\na * valubytes + b < length (ByFData fy) ->\nb < valubytes ->\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\nselN (ByFData fy) (a * valubytes + b) byteset0 = selN (valuset2bytesets (selN (DFData f) a valuset0)) b byteset0.\nProof.\nintros.\nrewrite H3; rewrite H2; rewrite H1.\nrewrite selN_firstn.\nrewrite concat_hom_selN.\nerewrite selN_map.\nreflexivity.\neapply inbound_bytefile_bfile; eauto.\nrewrite <- H1; eapply proto_len; eauto.\nauto.\nauto.\nQed.\n\nFact inbound_protobyte: forall f pfy ufy fy block_off m1 nb data Fd,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (block_off * valubytes) data)%pred (list2nmem (ByFData fy)) -> \nnb > 0 ->\nlength data = nb * valubytes ->\nm1 < nb ->\nblock_off + m1 < length (PByFData pfy).\nProof.\nintros.\nrewrite H.\nrewrite map_length.\napply list2nmem_arrayN_bound in H2 as H'.\ndestruct H'.\nrewrite <- length_zero_iff_nil in H6.\nrewrite H6 in H4; symmetry in H4; apply mult_is_O in H4.\ndestruct H4.\nomega.\nrewrite valubytes_is in *; omega.\napply list2nmem_arrayN_bound in H2.\ndestruct H2.\napply length_zero_iff_nil in H2; rewrite valubytes_is in *; omega.\n\n\nrewrite bytefile_unified_byte_len with (ufy:= ufy) in H6; eauto.\nrewrite unified_byte_protobyte_len with (pfy:= pfy)(k:=valubytes) in H6; eauto.\nrewrite H4 in H6.\neapply le_lt_weaken with (k:= m1 * valubytes) in H6; eauto.\nrewrite <- Nat.mul_add_distr_r in H6.\napply lt_mult_weaken in H6.\nrewrite H in H6.\nrewrite map_length in H6.\nauto.\nrewrite valubytes_is in *; omega.\neapply proto_len; eauto.\nQed.\n\n\nLemma exists_unique_bytefile_length: forall f pfy ufy fy,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\nlength (ByFData fy) mod valubytes = 0 ->\nlength (ByFData fy) > 0 ->\nexists ! x, length (ByFData fy) = x * valubytes.\nProof.\nintros.\nunfold unique.\napply Nat.mod_divides in H2; destruct H2.\nexists x.\nsplit.\nrewrite Nat.mul_comm; auto.\nintros.\nrewrite H2 in H4.\nrewrite Nat.mul_comm in H4.\napply Nat.mul_cancel_r in H4; auto.\napply valubytes_ne_O.\nunfold not; intros.\nunfold not in *; apply mod_dem_neq_dem with (a:= length (ByFData fy)) (b:= valubytes); intros; rewrite valubytes_is in *; omega.\nQed.\n\n\nLemma bfile_protobyte_len_eq: forall f pfy,\n  proto_bytefile_valid f pfy ->\n  length (PByFData pfy) = length (DFData f).\nProof.\nintros.\nrewrite H.\napply map_length.\nQed.\n\n\n\nLemma list2nmem_arrayN_middle: forall A  (l2 l1 l3: list A) a b (F:pred),\na = length l1 -> b = length l2 ->\nF (mem_except_range (list2nmem (l1 ++ l2 ++ l3)) a b ) -> (F * arrayN (ptsto (V:= A)) a l2)%pred (list2nmem (l1 ++ l2 ++ l3)).\nProof.\ninduction l2; intros.\nsimpl.\napply emp_star_r.\nsubst.\nunfold mem_except_range in H1.\nrewrite app_assoc in H1.\nrewrite app_nil_r in H1.\nsimpl in H1.\nrewrite <- plus_n_O in H1.\nreplace (list2nmem (l1 ++ l3)) with \n        (fun a' : addr =>\n       if le_dec (length l1) a' then if lt_dec a' (length l1) then None else list2nmem (l1 ++ l3) a' else list2nmem (l1 ++ l3) a').\nauto.\napply functional_extensionality; intros.\ndestruct (le_dec (length l1) x);\ndestruct (lt_dec x (length l1)); try reflexivity.\nomega.\n\nsubst.\nrewrite arrayN_isolate with (i := 0).\nsimpl.\napply sep_star_assoc.\nreplace (length l1 + 0 + 1) with (length (l1 ++ a :: nil)).\nreplace (l1 ++ a :: l2 ++ l3) with ((l1 ++ (a :: nil)) ++ l2 ++ l3).\neapply IHl2 with (F:= (F \u2736 (emp \u2736 (length l1 + 0) |-> a))%pred).\nauto.\ninstantiate (1:= length l2).\nreflexivity.\napply sep_star_assoc.\napply sep_star_comm.\napply mem_except_ptsto.\nrewrite <- plus_n_O.\nunfold list2nmem.\nunfold mem_except_range.\nerewrite selN_map.\nrewrite selN_app.\nrewrite selN_app2.\nreplace (length l1 - length l1) with 0 by omega.\nsimpl.\nrewrite app_length; simpl.\ndestruct (le_dec (length l1 + 1) (length l1)); try omega; try reflexivity.\nomega.\nrewrite app_length; simpl; omega.\nrepeat rewrite app_length; simpl; omega.\napply emp_star_r.\nunfold mem_except, mem_except_range.\nrewrite <- plus_n_O.\nrepeat rewrite app_length in *; simpl in *.\nreplace (fun a' : addr =>\n   if addr_eq_dec a' (length l1)\n   then None\n   else\n    if le_dec (length l1 + 1) a'\n    then if lt_dec a' (length l1 + 1 + length l2) then None else list2nmem ((l1 ++ a :: nil) ++ l2 ++ l3) a'\n    else list2nmem ((l1 ++ a :: nil) ++ l2 ++ l3) a')\n    \nwith (mem_except_range (list2nmem (l1 ++ a :: l2 ++ l3)) (length l1) (S (length l2))).\nauto.\nunfold mem_except_range.\napply functional_extensionality; intros.\n\nreplace ((length l1 + 1 + length l2)) with (length l1 + S (length l2)) by omega.\nreplace (((l1 ++ a :: nil) ++ l2 ++ l3)) with (l1 ++ a :: l2 ++ l3).\n\ndestruct (le_dec (length l1 + 1) x);\ndestruct (le_dec (length l1) x);\ndestruct (addr_eq_dec x (length l1)); try omega; try reflexivity.\ndestruct (lt_dec x (length l1 + S (length l2))); try omega; try reflexivity.\n\nrewrite <- app_assoc.\nrewrite <- cons_app.\nreflexivity.\n\nrewrite <- app_assoc.\nrewrite <- cons_app.\nreflexivity.\n\nrewrite app_length; simpl; omega.\nsimpl; omega.\n\nUnshelve.\nauto.\nauto.\nQed. \n\nLemma arrayN_frame_mem_ex_range: forall A (l: list A) (F:pred) a m,\n(F * arrayN (ptsto (V:= A)) a l)%pred m -> F (mem_except_range m a (length l) ).\nProof.\ninduction l; intros.\nsimpl in *.\nunfold mem_except_range.\nrewrite <- plus_n_O.\nreplace ((fun a' : addr => if le_dec a a' then if lt_dec a' a then None else m a' else m a')) with m.\napply sep_star_comm in H.\napply star_emp_pimpl in H; auto.\napply functional_extensionality; intros.\ndestruct (le_dec a x);\ndestruct (lt_dec x a);\ntry omega; try reflexivity.\nreplace (mem_except_range m a0 (length (a :: l))) with (mem_except_range (mem_except m a0) (a0 + 1) (length l)).\napply IHl.\nrewrite isolateN_fwd with (i:= 0) in H; simpl in H.\nrewrite star_emp_pimpl in H.\nrewrite <- plus_n_O in H.\napply sep_star_comm in H.\napply sep_star_assoc in H.\napply ptsto_mem_except in H. pred_apply; cancel.\nsimpl; omega.\napply functional_extensionality; intros.\nunfold mem_except, mem_except_range; simpl.\nreplace (S (length l)) with ( 1 + length l) by omega.\nrewrite Nat.add_assoc.\ndestruct (le_dec (a0 + 1) x);\ndestruct (lt_dec x (a0 + 1 + length l));\ndestruct (addr_eq_dec x a0);\ndestruct (le_dec a0 x);\ntry omega; try reflexivity.\nGrab Existential Variables.\nauto.\nQed. \n\n\n\nLemma bfile_ge_block_off: forall f fy block_off old_data Fd m1 l_old_blocks,\nm1 < l_old_blocks ->\nlength old_data = l_old_blocks * valubytes ->\nrep f fy ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (block_off * valubytes) old_data)%pred (list2nmem (ByFData fy)) ->\nblock_off <= length (DFData f).\nProof.\nintros.\napply Nat.lt_le_incl.\neapply inlen_bfile with (j:= 0); eauto; try omega.\napply valubytes_ge_O.\n\n2: {\npred_apply.\nrewrite <- plus_n_O.\ncancel.\n}\nrewrite valubytes_is in *; omega.\nQed.\n\nLemma bfile_gt_block_off_m1: forall f fy block_off Fd m1 old_blocks,\nlength old_blocks > 0 -> \nm1 < length old_blocks ->\nrep f fy ->\n(Fd \u2736 arrayN (ptsto (V:=valuset)) block_off old_blocks)%pred (list2nmem (DFData f)) ->\nblock_off + m1 < length (DFData f).\nProof.\nintros.\napply list2nmem_arrayN_bound in H2 as H''.\ndestruct H''.\napply length_zero_iff_nil in H3.\nassert (X: forall a, a = 0 -> a > 0 -> False). intros. omega.\napply X in H3.  \ncontradiction.\nauto.\neapply le_lt_weaken in H3.\neapply H3.\nauto.\nQed.\n\nLemma bfile_ge_block_off_m1: forall f fy block_off Fd m1 old_blocks,\nlength old_blocks > 0 -> \nm1 < length old_blocks ->\nrep f fy ->\n(Fd \u2736 arrayN (ptsto (V:=valuset)) block_off old_blocks)%pred (list2nmem (DFData f)) ->\nblock_off + m1 <= length (DFData f).\nProof.\nintros.\napply list2nmem_arrayN_bound in H2 as H''.\ndestruct H''.\napply length_zero_iff_nil in H3.\nassert (X: forall a, a = 0 -> a > 0 -> False). intros. omega.\napply X in H3.  \ncontradiction.\nauto.\n\neapply le_lt_weaken in H3.\n2: eauto.\nomega.\nQed.\n\nLemma bytefile_ge_block_off_v: forall fy block_off Fd old_data, \nlength old_data > 0 ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (block_off * valubytes) old_data)%pred (list2nmem (ByFData fy)) ->\nblock_off * valubytes <= length (ByFData fy).\nProof. \nintros.\napply list2nmem_arrayN_bound in H0 as H'.\ndestruct H'.\nrewrite H1 in H; inversion H.\nomega.\nQed.\n\nLemma bytefile_ge_block_off_m1_v: forall fy block_off Fd old_data m1 l_old_blocks, \nm1 < l_old_blocks ->\nlength old_data = l_old_blocks * valubytes ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) (block_off * valubytes) old_data)%pred (list2nmem (ByFData fy)) ->\n(block_off + m1 + 1) * valubytes <= length (ByFData fy).\nProof. \nintros.\napply list2nmem_arrayN_bound in H1 as H'.\ndestruct H'.\npose proof length_old_data_ge_O; eauto.\napply length_zero_iff_nil in H2.\neapply H3 in H; eauto.\ninversion H.\nomega.\nrewrite valubytes_is in *; omega.\nQed.\n\nLemma bfile_bytefile_length: forall f pfy ufy fy,\n  proto_bytefile_valid f pfy ->\n  unified_bytefile_valid pfy ufy ->\n  bytefile_valid ufy fy -> \n  length (ByFData fy) <= length (DFData f) * valubytes.\nProof.\n\tintros.\n\terewrite <- bfile_protobyte_len_eq; eauto.\n\terewrite <- unified_byte_protobyte_len; eauto.\n\tapply bytefile_unified_byte_len; eauto.\n\teapply proto_len; eauto.\nQed. \n\nLemma list2nmem_upd_updN: forall A a (l l': list A) x,\na < length l' ->\nMem.upd (list2nmem l') a x = list2nmem l -> l = updN l' a x.\nProof.\n\tintros.\n\trewrite <- listupd_memupd in H0.\n\tapply list2nmem_inj in H0.\n\tsymmetry; auto.\n\tauto.\nQed.\n\nLemma mem_except_range_unfold: forall A (l: list A) a n,\na < length l ->\nmem_except_range (list2nmem l) a (S n) = mem_except_range (mem_except (list2nmem l) a) (S a) n.\nProof.\n\tintros.\n\tapply functional_extensionality; intros.\n\tunfold mem_except_range; simpl.\n\tdestruct (le_dec a x); simpl.\n\tdestruct (le_dec (S a) x).\n\trewrite plus_n_Sm.\n\tdestruct (lt_dec x (a + S n)).\n\treflexivity.\n\tunfold mem_except; simpl.\n\tdestruct (Nat.eq_dec x a).\n\tomega.\n\treflexivity.\n\tapply Nat.nle_gt in n0.\n\tinversion n0.\n\tdestruct (lt_dec a (a + S n)).\n\trewrite mem_except_eq.\n\treflexivity.\n\tomega.\n\tomega.\n\tdestruct (le_dec (S a) x).\n\tomega.\n\tunfold mem_except.\n\tdestruct (Nat.eq_dec x a).\n\tomega.\n\treflexivity.\nQed.\n\nLemma mem_except_range_out_apply: forall A (l1 l2 l2' l3: list A) a1 a2 le1 le2,\na1 = a2 -> le1 = le2 -> a1 = length l1 -> le1 = length l2 -> length l2 = length l2' ->\nmem_except_range (list2nmem (l1++l2++l3)) a1 le1 = (mem_except_range (list2nmem (l1++l2'++l3)) a2 le2).\nProof.\n\tintros; apply functional_extensionality; intros.\n\tunfold mem_except_range; simpl; subst.\n\tdestruct (le_dec (length l1) x);\n\tdestruct (lt_dec x ((length l1) + (length l2))); try reflexivity; try omega.\n\tunfold list2nmem.\n\tapply Nat.nlt_ge in n.\n\trepeat rewrite map_app.\n\trepeat rewrite selN_app2.\n\trepeat rewrite map_length.\n\trewrite H3.\n\treflexivity.\n\tall: repeat rewrite map_length.\n\tall: subst.\n\tall: try omega.\n\tapply Nat.nle_gt in n.\n\tunfold list2nmem.\n\trepeat rewrite map_app.\n\trepeat rewrite selN_app1.\n\treflexivity.\n\tall: repeat rewrite map_length; omega.\nQed.\n\nLemma diskIs_arrayN: forall A (l: list A) a b,\na + b <= length l ->\n(diskIs (mem_except_range (list2nmem l) a b) * arrayN (ptsto (V:= A)) a (firstn b (skipn a l)))%pred (list2nmem l).\nProof.\n\tintros;\n\tremember (diskIs (mem_except_range (list2nmem l) a b)) as F;\n\tremember (firstn b (skipn a l)) as x.\n\treplace l with (firstn a l ++ firstn b (skipn a l) ++ skipn (a + b) l).\n\trewrite Heqx; eapply list2nmem_arrayN_middle.\n\trewrite firstn_length_l. reflexivity.\n\tomega.\n\tinstantiate (1:= b).\n\trewrite firstn_length_l. reflexivity.\n\trewrite skipn_length.\n\tomega.\n\trewrite app_assoc.\n\trewrite <- firstn_sum_split.\n\trewrite firstn_skipn.\n\trewrite HeqF; apply diskIs_id.\n\trewrite app_assoc.\n\trewrite <- firstn_sum_split.\n\trewrite firstn_skipn.\n\treflexivity.\nQed.\n\nLemma diskIs_eq: forall AT AEQ V (m m': @Mem.mem AT AEQ V),\n(diskIs m') m ->\nm = m'.\nProof.\n    unfold diskIs.\n    intros; symmetry; auto.\nQed.\n\n  \nLemma upd_mem_except_range_comm: forall AEQ V a a0 b v (m: _ AEQ V),\na0 < a \\/ a0 > a + b ->\nMem.upd (AEQ:= AEQ) (mem_except_range m a b) a0 v = mem_except_range (Mem.upd m a0 v) a b.\nProof.\n  intros; unfold Mem.upd, mem_except_range.\n  destruct H;\n  apply functional_extensionality; intros;\n  destruct (AEQ x a0); \n  destruct (le_dec a x);\n  destruct (lt_dec x (a+b)); try omega; try reflexivity.\nQed.\n\nLemma diskIs_combine_upd_range: forall V (l: list V) m a b ,\nb = length l ->\n(diskIs (mem_except_range m a b) * arrayN (ptsto (V:=V)) a l) =p=> diskIs (upd_range m a l).\nProof.\n  induction l; intros.\n  simpl in *.\n  rewrite H.\n  rewrite mem_except_range_O.\n  cancel.\n  destruct b.\n  simpl in H; inversion H.\n  rewrite arrayN_isolate_hd.\n  simpl.\n  rewrite <- sep_star_assoc.\n  erewrite diskIs_combine_upd.\n  replace (S b) with (b + 1) by omega.\n  rewrite <- mem_ex_mem_ex_range_head.\n  \n  rewrite diskIs_combine_upd.\n  rewrite upd_mem_except_range_comm.\n  apply IHl.\n  simpl in H; inversion H; auto.\n  left; omega.\n  destruct (m a0) eqn:D.\n  eapply ptsto_upd' with (v0:= v).\n  apply sep_star_comm.\n  apply mem_except_ptsto.\n  auto.\n  apply diskIs_id.\n  apply ptsto_upd_disjoint.\n  rewrite mem_except_none.\n  apply diskIs_id.\n  all: auto.\n  simpl; omega.\n  Grab Existential Variables.\n  trivial.\nQed.\n\nLemma upd_range_list2nmem_comm: forall A (l' l: list A) a,\na + length l' <= length l ->\nupd_range (list2nmem l) a l' = list2nmem (firstn a l ++ l' ++ skipn (a + length l') l).\nProof.\n  induction l'; intros.\n  simpl.\n  rewrite <- plus_n_O; rewrite firstn_skipn; reflexivity.\n  simpl.\n  rewrite <- listupd_memupd.\n  replace (firstn a0 l ++ a :: l' ++ skipn (a0 + S (length l')) l)\n    with (firstn (a0 + 1) (l \u27e6 a0 := a \u27e7) ++ l' ++ skipn ((a0 + 1) + length l') (l \u27e6 a0 := a \u27e7)).\n  apply IHl'.\n  rewrite length_updN.\n  simpl in H; omega.\n  rewrite updN_firstn_skipn.\n  rewrite app_comm_cons.\n  rewrite app_assoc.\n  rewrite app_assoc.\n  rewrite firstn_app_l.\n  rewrite firstn_oob.\n  rewrite skipn_app_r_ge.\n  rewrite skipn_skipn.\n  replace (a0 + 1 + length l' - length (firstn a0 l ++ a :: nil) + (a0 + 1))\n    with (a0 + S (length l')).\n  repeat rewrite app_assoc_reverse.\n  rewrite <-cons_app.\n  reflexivity.\n  all: try (rewrite app_length; rewrite firstn_length_l; simpl in *).\n  all: simpl in H; try omega.\nQed.\n\n\n\nLemma diskIs_arrayN_length: forall A b a (l l' l'': list A) ,\nlength l' = b ->\na + b <= length l ->\n(diskIs (mem_except_range (list2nmem l) a b) * arrayN (ptsto (V:= A)) a l')%pred (list2nmem l'') ->\nlength l'' = length l.\nProof.\n  intros.\n  apply diskIs_combine_upd_range in H1.\n  apply diskIs_eq in H1.\n  rewrite upd_range_list2nmem_comm in H1.\n  apply list2nmem_inj in H1.\n  rewrite H1.\n  repeat rewrite app_length.\n  rewrite skipn_length.\n  rewrite firstn_length_l.\n  all: omega.\nQed.\n\nLemma bfile_length_eq: forall a f f' v,\na < length (DFData f) ->\n(diskIs (mem_except (list2nmem (DFData f)) a) * a |-> v )%pred (list2nmem (DFData f')) ->\nlength (DFData f') = length (DFData f).\nProof.\n  intros.\n  apply diskIs_combine_upd in H0 as H'.\n  apply diskIs_eq in H'.\n  symmetry in H'; apply list2nmem_upd_updN in H'.\n  rewrite H'.\n  apply length_updN.\n  auto.\nQed.\n\nLemma bfile_range_length_eq: forall a b f f' l,\nlength l = b ->\na + b <= length (DFData f) ->\n(diskIs (mem_except_range (list2nmem (DFData f)) a b) * LOG.arrayP a l)%pred (list2nmem (DFData f')) ->\nlength (DFData f') = length (DFData f).\nProof.\n  intros.\n  apply diskIs_arrayN_length in H1.\n  all: auto.\nQed.\n\nLemma list2nmem_arrayN_updN_range: forall f f' l a,\na + length l <= length (DFData f) ->\n(diskIs (upd_range (list2nmem (DFData f)) a l)) (list2nmem (DFData f')) ->\nDFData f' = firstn a (DFData f) ++ l ++ skipn (a + length l) (DFData f).\nProof.\n  intros.\n  apply diskIs_eq in H0.\n  rewrite upd_range_list2nmem_comm in H0.\n  apply list2nmem_inj in H0.\n  all: auto.\nQed.\n\nLemma off_div_v_inlen_bfile: forall off f fy old_data length_data Fd,\nlength_data > 0 ->\nlength old_data = length_data ->\nrep f fy ->\n(Fd \u2736 arrayN (ptsto (V:=byteset)) off old_data)%pred (list2nmem (ByFData fy)) ->\noff / valubytes < length (DFData f).\n\tProof.\n\t\tintros;\n\t\teapply inlen_bfile; eauto; try omega.\n\t\tinstantiate (1:= off mod valubytes); apply Nat.mod_upper_bound.\n\t\tapply valubytes_ne_O.\n    2: {\n  \t\trewrite Nat.mul_comm.\n  \t\trewrite <- Nat.div_mod.\n  \t\teauto.\n  \t\tapply valubytes_ne_O.\n    }\n\t\tomega.\n\tQed.\n\nLemma valu2list_sublist_v: forall f i,\nForall (fun sublist : list byte => length sublist = valubytes)\n  (valu2list (fst (selN (DFData f) i valuset0))\n   :: map valu2list (snd (selN (DFData f) i valuset0))).\n\tProof.\n\t\tintros; rewrite Forall_forall; intros.\n\t\trepeat destruct H.\n\t\tapply valu2list_len.\n\t\tapply in_map_iff in H.\n\t\trepeat destruct H.\n\t\tapply valu2list_len.\n\tQed.\n\n\nLemma bytefile_equiv1: forall fy off length_data,\n0 < length_data ->\noff / valubytes * valubytes + valubytes <= length (ByFData fy) ->\nlength_data <= valubytes - off mod valubytes ->\nlength (ByFData fy) - (off / valubytes * valubytes + valubytes) =\nlength (ByFData fy) - off / valubytes * valubytes -\n(off / valubytes * valubytes + off mod valubytes - off / valubytes * valubytes +\n (length_data +\n  (off / valubytes * valubytes + valubytes -\n   (off / valubytes * valubytes + off mod valubytes + length_data)))).\n\tProof. intros; omega. Qed.\n\t\nLemma off_plus_mod_inlen_unified: forall ufy fy off,\nbytefile_valid ufy fy ->\noff < length (ByFData fy) ->\noff / valubytes * valubytes + off mod valubytes <= length (UByFData ufy).\n\tProof.\n\tintros;\nerewrite <- bytefile_unified_byte_len; eauto.\nrewrite Nat.mul_comm; rewrite <- Nat.div_mod.\napply Nat.lt_le_incl; auto.\napply valubytes_ne_O.\n\tQed.\n\nLemma off_div_mul_inlen_unified: forall ufy fy off,\nbytefile_valid ufy fy ->\noff < length (ByFData fy) ->\noff / valubytes * valubytes <= length (UByFData ufy).\n\tProof.\n\tintros;\n\terewrite <- bytefile_unified_byte_len; eauto.\n\trewrite Nat.mul_comm; rewrite Nat.mul_div_le.\n\tapply Nat.lt_le_incl; auto.\n\tapply valubytes_ne_O.\n\tQed.\n\t\n\n\n\n\tLemma list2nmem_arrayN_app': forall A (l l': list A) a (F: pred),\na = length l ->\nF (list2nmem l) ->\n(F * arrayN (ptsto (V:= A)) a l')%pred (list2nmem (l++l')).\n\tProof. intros; subst; apply list2nmem_arrayN_app; auto. Qed.\n\n\n(* Lemma ptsto_subset_b_to_ptsto: forall m l' F a,\n(F \u2736 arrayN ptsto_subset_b a l')%pred m ->\nexists l'', (F \u2736 arrayN (ptsto (V:= byteset)) a l'')%pred m /\\ length l' = length l''.\n\tProof.\n\t\tinduction l'; intros.\n\t\tsimpl in H.\n\t\texists nil.\n\t\tsimpl; auto.\n\t\trewrite arrayN_isolate_hd in H.\n\t\tsimpl in H.\n\t\tapply sep_star_assoc in H.\n\t\tapply IHl' in H.\n\t\tdestruct H.\n\t\tunfold ptsto_subset_b in H.\n\t\tsimpl in H.\n\t\tdestruct_lift H.\n\t\tapply sep_star_assoc in H.\n\t\treplace (a0 |-> (a_1, dummy) \u2736 arrayN (ptsto (V:=byteset)) (a0 + 1) x)%pred\n\t\t\twith (a0 |-> (selN ((a_1, dummy)::x) 0 byteset0) \u2736 arrayN (ptsto (V:=byteset)) (a0 + 1) (skipn 1 ((a_1, dummy)::x)))%pred in H.\n\t\trewrite <- arrayN_isolate_hd in H.\n\t\texists ((a_1, dummy)::x).\n\t\tsplit; simpl; auto.\n\t\tsimpl; omega.\n\t\treflexivity.\n\t\tsimpl; omega.\n\t\tGrab Existential Variables.\n\t\tapply byteset0.\nQed. *)\n\nLemma S_length_exists: forall A (l: list A) def,\nl <> nil -> l = (selN l 0 def)::(skipn 1 l).\n\tProof.\n\t\tintros.\n\t\tdestruct l.\n\t\tunfold not in H; destruct H; reflexivity.\n\t\treflexivity.\n\tQed.\n\nLemma mapsnd_sndsplit: forall A B (l:list (A * B)),\nmap snd l = snd (split l).\n\tProof.\n\t\tintros.\n\t\tinduction l.\n\t\treflexivity.\n\t\tsimpl.\n\t\trewrite IHl.\n\t\tdestruct a.\n\t\tsimpl.\n\t\tdestruct (split l).\n\t\treflexivity.\n\tQed.\n\n\n\n(* Lemma ptsto_subset_b_list2nmem: forall l l' F a,\n(F * arrayN ptsto_subset_b a l)%pred (list2nmem l') ->\nmap fst l = map fst (firstn (length l) (skipn a l')).\n\tProof.\n\t\tinduction l; intros.\n\t\treflexivity.\n\t\tpose proof H.\n\t\trewrite arrayN_isolate with (i:= 0) in H.\n\t\tsimpl in H.\n\t\tunfold ptsto_subset_b in H.\n\t\treplace (firstn (length (a :: l)) (skipn a0 l')) \n\t\t\t\twith ((selN (skipn a0 l') 0 byteset0)::(firstn (length l) (skipn (a0 + 1) l'))).\n\t\t\t\t\n\t\trewrite <- plus_n_O in H.\n\t\tdestruct_lift H.\n\t\tapply IHl in H as H'.\n\t\tdestruct H'.\n\t\tapply sep_star_comm in H.\n\t\tapply sep_star_assoc in H.\n\t\teapply list2nmem_sel in H.\n\t\trewrite skipn_selN.\n\t\trewrite <- plus_n_O.\n\t\trewrite <- H.\n\t\treflexivity.\n\t\trewrite cons_app.\n\t\trewrite <- firstn_1_selN.\n\t\treplace (skipn (a0 + 1) l') with (skipn 1 (skipn a0 l')).\n\t\trewrite <- firstn_sum_split.\n\t\treflexivity.\n\t\trewrite skipn_skipn.\n\t\trewrite Nat.add_comm;\n\t\treflexivity.\n\t\tunfold not; intros.\n\t\tapply length_zero_iff_nil in H1.\n\t\trewrite skipn_length in H1.\n\t\tapply ptsto_subset_b_to_ptsto in H0.\n\t\trepeat destruct H0.\n\t\tapply list2nmem_arrayN_bound in H0.\n\t\tdestruct H0.\n\t\trewrite H0 in H2; simpl in H2; inversion H2.\n\t\trewrite <- H2 in H0.\n\t\tsimpl in H0.\n\t\tomega.\n\t\tsimpl; omega.\n\t\tGrab Existential Variables.\n\t\tapply byteset0.\n\tQed. *)\n\nLemma merge_bs_nil_l: forall l,\nmerge_bs nil l = nil.\nProof. destruct l; reflexivity. Qed.\n\nLemma merge_bs_app: forall l1 l2 l1' l2',\n\tlength l1 = length l1' ->\n\tmerge_bs (l1 ++ l2) (l1'++l2') = merge_bs l1 l1' ++ merge_bs l2 l2'.\n\tProof.\n\t\tinduction l1;\tintros.\n\t\tsimpl in H; symmetry in H; apply length_zero_iff_nil in H; subst.\n\t\treflexivity.\n\t\tdestruct l1'.\n\t\tsimpl in H; inversion H.\n\t\tsimpl.\n\t\trewrite IHl1.\n\t\treflexivity.\n\t\tsimpl in H; omega.\n\tQed.\n\t\n(* Lemma arrayN_ptsto2ptsto_subset_b: forall l1 l1' m a F,\nlength l1 = length l1' ->\n(F * arrayN (ptsto (V:= byteset)) a l1)%pred m ->\n(forall i, i < length l1 -> fst (selN l1 i byteset0) = fst (selN l1' i byteset0) /\\\n\t\t\t\t\t\tincl (byteset2list (selN l1 i byteset0)) (byteset2list (selN l1' i byteset0))) ->\n(F * arrayN ptsto_subset_b a l1')%pred m.\n\tProof.\n\t\t\tinduction l1; intros.\n\t\t\tsimpl in *.\n\t\t\tsymmetry in H; apply length_zero_iff_nil in H; subst.\n\t\t\tsimpl; auto.\n\t\t\tdestruct l1'.\n\t\t\tsimpl in H; inversion H.\n\t\t\trewrite arrayN_isolate_hd.\n\t\t\tapply sep_star_assoc.\n\t\t\teapply IHl1.\n\t\t\tsimpl in *; omega.\n\t\t\tassert (0 < length (a::l1)).\n\t\t\tsimpl; omega.\n\t\t\tapply H1 in H2.\n\t\t\tdestruct H2; simpl in *.\n\t\t\treplace (a0 + 1) with (S a0) by omega.\n\t\t\tunfold ptsto_subset_b; pred_apply; cancel.\n\t\t\t\n\t\t\tintros.\n\t\t\tsimpl.\n\t\t\tsimpl in H1.\n\t\t\tapply lt_n_S in H2.\n\t\t\tapply H1 in H2.\n\t\t\tauto.\n\t\t\tsimpl; omega.\n\t\t\tGrab Existential Variables.\n\t\t\tapply byteset0.\n\t\tQed. *)\n\nLemma merge_bs_selN: forall l l' i,\ni < length l ->\ni < length l' ->\nselN (merge_bs l l') i byteset0 = ((selN l i byte0),fst (selN l' i byteset0) :: snd (selN l' i byteset0)).\n\tProof.\n\t\t\tinduction l; intros.\n\t\t\tsimpl in H; inversion H.\n\t\t\tdestruct l'.\n\t\t\tsimpl in H0; inversion H0.\n\t\t\tdestruct i; simpl.\n\t\t\treflexivity.\n\t\t\tapply IHl; simpl in *; omega.\n\tQed.\n\nLemma selN_eq: forall A (l l': list A) i def,\nl = l' ->\nselN l i def = selN l' i def.\n\tProof. intros; subst; reflexivity. Qed.\n\n(* Lemma ptsto_subset_b_incl: forall l1 l1' m a F,\nlength l1 = length l1' ->\n(F * arrayN (ptsto (V:= byteset)) a l1)%pred m ->\n(F * arrayN ptsto_subset_b a l1')%pred m ->\n(forall i, i < length l1 -> incl (byteset2list (selN l1 i byteset0)) (byteset2list (selN l1' i byteset0))).\n\tProof.\n\t\tinduction l1; intros.\n\t\tsimpl in H2; inversion H2.\n\t\tdestruct l1'.\n\t\tsimpl in H; inversion H.\n\t\tdestruct i; simpl.\n\t\trewrite arrayN_isolate_hd in H1.\n\t\tunfold ptsto_subset_b in H1.\n\t\tdestruct_lift H1.\n\t\tapply sep_star_comm in H1.\n\t\tapply sep_star_assoc in H1.\n\t\tapply ptsto_valid' in H1.\n\t \t\n\t\tapply sep_star_comm in H0.\n\t\tapply sep_star_assoc in H0.\n\t\tapply sep_star_comm in H0.\n\t \tapply ptsto_valid' in H0.\n\t \trewrite H1 in H0.\n\t \tinversion H0.\n\t \tsubst.\n\t \tapply H7.\n\t \tsimpl; omega.\n\t \teapply IHl1.\n\t \tauto.\n\n\t \tsimpl in *.\n\t \tapply sep_star_assoc in H0; eauto.\n\t \tsimpl in *.\n\t \tdestruct_lift H1.\n\t \tunfold ptsto_subset_b in H1; destruct_lift H1.\n\t \t\n\t \tapply sep_star_comm in H1 as H'.\n\t\tapply sep_star_assoc in H'.\n\t \tapply ptsto_valid' in H'.\n\t \t\n\t\tapply sep_star_comm in H0 as H''.\n\t\tapply sep_star_assoc in H''.\n\t\tapply sep_star_comm in H''.\n\t \tapply ptsto_valid' in H''.\n\t \trewrite H' in H''.\n\t \tinversion H''; subst.\n\t \tapply H1.\n\t \tsimpl in H2; omega.\n\t \tGrab Existential Variables.\n\t \tall: apply byteset0.\n \tQed. *)\n\n  \tLemma merge_bs_firstn_skipn: forall a b c l l',\n\ta + b = c ->\n\tmerge_bs (firstn c l) (firstn c l') = merge_bs (firstn a l) (firstn a l') \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t++ merge_bs (firstn b (skipn a l)) (firstn b (skipn a l')).\n\t\tProof.\n\t\t\tinduction a; intros.\n\t\t\tsimpl.\n\t\t\tsimpl in H.\n\t\t\tsubst; reflexivity.\n\t\t\tsimpl.\n\t\t\tdestruct l.\n\t\t\trepeat rewrite firstn_nil.\n\t\t\treflexivity.\n\t\t\tsimpl.\n\t\t\tdestruct l'.\n\t\t\tsimpl.\n\t\t\trepeat rewrite firstn_nil.\n\t\t\trepeat rewrite merge_bs_nil.\n\t\t\trewrite <- H.\n\t\t\tsimpl.\n\t\t\trewrite <- map_app.\n\t\t\trewrite firstn_sum_split.\n\t\t\treflexivity.\n\t\t\t\n\t\t\tsimpl.\n\t\t\trewrite <- H; simpl.\n\t\t\terewrite IHa with (b:= b).\n\t\t\treflexivity.\n\t\t\treflexivity.\n\t\tQed.\n\nLemma arrayN_app': forall VP V (a b: list V) st l pts,\n\tl = length a ->\n\t(arrayN (VP:=VP)) pts st (a++b) <=p=> (arrayN (VP:=VP)) pts st a \u2736 (arrayN (VP:=VP)) pts (st + l) b.\n\tProof. intros; subst;\tapply arrayN_app.\tQed.\n\t\n\n\n(* Lemma arrayN_ptsto_subset_b_frame_extract: forall a m l' F,\n(F * arrayN ptsto_subset_b a l')%pred m ->\nF (mem_except_range m a (length l')).\n\tProof.\n\t\tintros.\n\t\teapply ptsto_subset_b_to_ptsto in H.\n\t\trepeat destruct H.\n\t\tapply arrayN_frame_mem_ex_range in H. \n\t\trewrite H0; auto.\n\tQed. *)\n\nLemma block_off_le_length_proto_bytefile: forall  f pfy ufy fy block_off byte_off data F,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy -> \nByFAttr fy = DFAttr f ->\n# (INODE.ABytes (ByFAttr fy)) = length (ByFData fy) ->\nroundup (length (ByFData fy)) valubytes = length (DFData f) * valubytes ->\n(F * arrayN (ptsto(V:=byteset))(block_off * valubytes + byte_off) data)%pred (list2nmem (ByFData fy)) ->\nbyte_off < valubytes ->\nlength data > 0 ->\nblock_off <= length (PByFData pfy).\n\tProof.\n\t\tintros.\n\t\terewrite bfile_protobyte_len_eq; eauto.\n\t\tapply Nat.lt_le_incl; eapply inlen_bfile;\n\t\tunfold rep; repeat eexists; eauto. \n\tQed.\n\nLemma proto_len_firstn: forall f pfy a,\nproto_bytefile_valid f pfy ->\nForall (fun sublist : list byteset => length sublist = valubytes) (firstn a (PByFData pfy)).\nProof.\nintros.\napply Forall_forall; intros.\napply in_firstn_in in H0.\nrewrite H in H0.\napply in_map_iff in H0.\ndestruct H0.\ninversion H0.\nrewrite <- H1.\napply valuset2bytesets_len.\nQed.\n\nLemma valu2list_selN_fst: forall block_off a0 f pfy ufy fy,\n  proto_bytefile_valid f pfy ->\n  unified_bytefile_valid pfy ufy ->\n  bytefile_valid ufy fy ->\n  block_off < length (DFData f) ->\n  a0 < length (ByFData fy) ->\n  block_off * valubytes + valubytes > a0 ->\n  a0 >= block_off * valubytes ->\n  (selN (valu2list (fst (selN (DFData f) block_off valuset0))) (a0 - block_off * valubytes) byte0) = fst (selN (ByFData fy) a0 byteset0).\nProof.\n  intros.\n  rewrite H1; rewrite H0; rewrite H.\n  rewrite selN_firstn; auto.\n  rewrite between_exists with (a:= a0)(b:= block_off + 1) (c:= valubytes).\n  replace (block_off + 1 - 1) with block_off by omega.\n  rewrite concat_hom_selN with (k:= valubytes).\n  rewrite selN_map with (default':= valuset0).\n  unfold valuset2bytesets. simpl.\n  destruct  (snd (selN (DFData f) block_off valuset0)) eqn:D.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (nil: list valu).\n  simpl.\n  rewrite v2b_rec_nil.\n  rewrite l2b_cons_x_nil.\n  erewrite selN_map.\n  simpl.\n  replace ( block_off * valubytes + a0 mod valubytes - block_off * valubytes )\n  with (a0 mod valubytes) by omega.\n  reflexivity.\n  rewrite valu2list_len; apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  rewrite valu2list_len. reflexivity.\n\n\n  rewrite valuset2bytesets_rec_cons_merge_bs.\n  rewrite merge_bs_selN; simpl.\n  replace ( block_off * valubytes + a0 mod valubytes - block_off * valubytes )\n  with (a0 mod valubytes) by omega.\n  reflexivity.\n  rewrite valu2list_len; apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  rewrite map_length.\n  rewrite valuset2bytesets_rec_len.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (w::l).\n  unfold not; intros Hx; inversion Hx.\n  rewrite Forall_forall; intros l' Hx; destruct Hx.\n  destruct H6.\n  apply valu2list_len.\n  apply in_map_iff in H6. repeat destruct H6.\n  apply valu2list_len.\n  auto.\n  rewrite <- H; eapply proto_len; eauto.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (block_off + 1 - 1) with block_off. auto.\n  omega.\n  rewrite Nat.mul_add_distr_r; omega.\n  apply valubytes_ne_O.\nQed.\n\nLemma byteset2list_selN_snd: forall block_off a0 f pfy ufy fy,\n  proto_bytefile_valid f pfy ->\n  unified_bytefile_valid pfy ufy ->\n  bytefile_valid ufy fy ->\n  block_off < length (DFData f) ->\n  a0 < length (ByFData fy) ->\n  block_off * valubytes + valubytes > a0 ->\n  a0 >= block_off * valubytes ->\n  (snd (selN (DFData f) block_off valuset0)) <> nil ->\nfst (list2byteset byte0\n        (selN (valuset2bytesets_rec (map valu2list (snd (selN (DFData f) block_off valuset0))) valubytes) (a0 - block_off * valubytes) nil))\n   :: snd (list2byteset byte0\n           (selN (valuset2bytesets_rec (map valu2list (snd (selN (DFData f) block_off valuset0))) valubytes) (a0 - block_off * valubytes) nil)) =\n   snd (selN (ByFData fy) a0 byteset0).\nProof.\n  intros.\n  rewrite H1; rewrite H0; rewrite H.\n  rewrite selN_firstn; auto.\n  rewrite between_exists with (a:= a0)(b:= block_off + 1) (c:= valubytes).\n  replace (block_off + 1 - 1) with block_off by omega.\n  rewrite concat_hom_selN with (k:= valubytes).\n  rewrite selN_map with (default':= valuset0).\n  unfold valuset2bytesets. simpl.\n  destruct  (snd (selN (DFData f) block_off valuset0)) eqn:D.\n  destruct H6; reflexivity.\n  simpl.\n  rewrite valuset2bytesets_rec_cons_merge_bs.\n  rewrite merge_bs_selN; simpl.\n  replace ( block_off * valubytes + a0 mod valubytes - block_off * valubytes )\n  with (a0 mod valubytes) by omega.\n  erewrite selN_map.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (w::l).\n  simpl.\n  reflexivity.\n  rewrite valuset2bytesets_rec_len.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (w::l).\n  unfold not; intros Hx; inversion Hx.\n  rewrite valu2list_len; apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  rewrite map_length.\n  rewrite valuset2bytesets_rec_len.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (w::l).\n  unfold not; intros Hx; inversion Hx.\n  rewrite Forall_forall; intros l' Hx; destruct Hx.\n  destruct H7.\n  apply valu2list_len.\n  apply in_map_iff in H7. repeat destruct H7.\n  apply valu2list_len.\n  auto.\n  rewrite <- H; eapply proto_len; eauto.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (block_off + 1 - 1) with block_off. auto.\n  omega.\n  rewrite Nat.mul_add_distr_r; omega.\n  apply valubytes_ne_O.\nQed.\n\nLemma bfile_bytefile_snd_nil: forall block_off a0 f pfy ufy fy,\n  proto_bytefile_valid f pfy ->\n  unified_bytefile_valid pfy ufy ->\n  bytefile_valid ufy fy ->\n  block_off < length (DFData f) ->\n  a0 < length (ByFData fy) ->\n  block_off * valubytes + valubytes > a0 ->\n  a0 >= block_off * valubytes ->\n  snd (selN (DFData f) block_off valuset0) = nil ->\n  snd (selN (ByFData fy) a0 byteset0) = nil.\nProof.\n  intros.\n  rewrite H1; rewrite H0; rewrite H.\n  rewrite selN_firstn; auto.\n  rewrite between_exists with (a:= a0)(b:= block_off + 1) (c:= valubytes).\n  replace (block_off + 1 - 1) with block_off by omega.\n  rewrite concat_hom_selN with (k:= valubytes).\n  erewrite selN_map with (default':= valuset0).\n  unfold valuset2bytesets.\n  erewrite selN_map.\n  unfold byteset2list.\n  replace (snd (DFData f) \u27e6 block_off \u27e7) with (nil: list valu).\n  simpl.\n  rewrite v2b_rec_nil.\n  erewrite selN_map.\n  reflexivity.\n   rewrite valu2list_len; apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  rewrite valu2list_len; reflexivity.\n  rewrite valuset2bytesets_rec_len.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  unfold byteset2list, not; intros Hx; inversion Hx.\n  auto.\n  rewrite <- H; eapply proto_len; eauto.\n  apply Nat.mod_upper_bound.\n  apply valubytes_ne_O.\n  replace (block_off + 1 - 1) with block_off. auto.\n  omega.\n  rewrite Nat.mul_add_distr_r; omega.\n  Unshelve.\n  apply valubytes_ne_O.\n  apply nil.\n  apply byte0.\nQed.\n\nLemma unified_bytefile_bytefile_selN_eq: forall a0 ufy fy,\n  bytefile_valid ufy fy ->\n  a0 < length (ByFData fy) ->\n  selN (UByFData ufy) a0 byteset0 = selN (ByFData fy) a0 byteset0.\nProof.\n  intros.\n  rewrite H.\n  rewrite selN_firstn.\n  reflexivity.\n  auto.\nQed.\n\nLemma merge_bs_skipn_comm: forall l l1 a,\nskipn a (merge_bs l l1) = merge_bs (skipn a l) (skipn a l1).\nProof.\n  induction l; intros.\n  repeat rewrite skipn_nil.\n  reflexivity.\n  destruct a0.\n  reflexivity.\n  destruct l1.\n  simpl.\n  rewrite IHl.\n  rewrite skipn_nil; reflexivity.\n  simpl.\n  auto.\nQed.\n\nLemma sep_star_mem_exists: forall {AT AEQ V} (m: @Mem.mem AT AEQ V),\n    exists m1 m2 : Mem.mem,\n    m = mem_union m1 m2 /\\ mem_disjoint m1 m2.\n    Proof.\n      intros.\n      exists m.\n      exists (fun x => None).\n      split.\n      unfold mem_union.\n      apply functional_extensionality; intros.\n      destruct (m x); auto.\n      unfold mem_disjoint.\n      unfold not; intros.\n      repeat destruct H.\n      inversion H0.\n    Qed.\n\n(* Lemma subset_invariant_bs_union: forall F1 F2,\nsubset_invariant_bs F1 -> subset_invariant_bs F2 ->\n  subset_invariant_bs (F1 * F2)%pred.\nProof.\n    intros.\n    unfold subset_invariant_bs in *.\n    intros.\n    pose proof (sep_star_mem_exists bsl').\n    pose proof (sep_star_mem_exists bsl).\n    split_hypothesis.\n    edestruct H; edestruct H0.\n    split_hypothesis.\n    left.\n    unfold sep_star; rewrite sep_star_is; unfold sep_star_impl.\n    repeat eexists; repeat split; eauto.\n    split_hypothesis.\n    \n    right; intros.\n    unfold sep_star in H9; rewrite sep_star_is in H9; unfold sep_star_impl in H9.\n    split_hypothesis.\n    unfold sep_star; rewrite sep_star_is; unfold sep_star_impl.\n    exists (fun a => match x1 a with\n                     | None => None\n                     | Some v => bsl' a\n                     end).\n    exists (fun a => match x2 a with\n                     | None => None\n                     | Some v => bsl' a\n                     end).\n    repeat split; eauto.\n    apply functional_extensionality; intros.\n    unfold mem_union.\n    destruct (bsl x3) eqn:D.\n    rewrite H6 in D. unfold mem_union in D.\n    destruct (x1 x3) eqn:D1.\n    destruct (bsl' x3).\n    reflexivity.\n    destruct (x2 x3); reflexivity.\n    rewrite D; reflexivity.\n    \n    rewrite H6 in D.\n    unfold mem_union in D.\n    destruct (x1 x3) eqn:D1.\n    inversion D.\n    \n    destruct H5 with (a:= x3).\n    rewrite H6 in H10.\n    unfold mem_union in H10.\n    rewrite D1 in H10; simpl in H10; rewrite D in H10.\n    rewrite H10; rewrite D; reflexivity.\n    \n    destruct H10.\n    rewrite H6 in H10.\n    unfold mem_union in H10.\n    rewrite D1 in H10; simpl in H10; rewrite D in H10.\n    destruct H10; reflexivity.\n    \n    unfold mem_disjoint in *.\n    unfold not; intros.\n    do 4 destruct H6.\n    destruct H3.\n    destruct (x x1) eqn:D.\n    destruct (x0 x1) eqn:D1.\n    exists x1.\n    exists p.\n    exists p0.\n    split; auto.\n    inversion H7.\n    inversion H6.\n    eapply H.\n    intros.\n    2: eauto.\n    unfold isSubset in *; simpl in *; intros.\n    \n    destruct H1 with (a:= a).\n    left.\n    unfold mem_union in *.\n    rewrite H2 in H6.\n    destruct (x a) eqn:D.\n    auto.\n    reflexivity.\n    \n    destruct H6.\n    rewrite H2 in H7.\n    unfold some_strip, mem_union in *.\n    destruct (x a) eqn:D.\n    right.\n    split.\n    unfold not; intros Hx; inversion Hx.\n    auto.\n    left.\n    reflexivity. \n    \n    eapply H0.\n    intros.\n    2: eauto.\n    unfold isSubset in *; simpl in *; intros.\n    \n    destruct H1 with (a:= a).\n    left.\n    unfold mem_union in *.\n    rewrite H2 in H6.\n    destruct (x0 a) eqn:D.\n    unfold mem_disjoint in *.\n    unfold not in *.\n    destruct (x a) eqn:D1.\n    destruct H3.\n    exists a, p0, p.\n    split; auto.\n    auto.\n    reflexivity.\n    \n    destruct H6.\n    rewrite H2 in H7.\n    unfold some_strip, mem_union in *.\n    destruct (x0 a) eqn:D.\n    right.\n    split.\n    unfold not; intros Hx; inversion Hx.\n    destruct (x a) eqn:D1.\n    destruct H3.\n    exists a, p0, p.\n    split; auto.\n    auto.\n    left; reflexivity.\nQed.\n\nLemma subset_invariant_bs_ptsto_subset_b: forall l a,\nsubset_invariant_bs (arrayN ptsto_subset_b a l).\n  Proof.\n    induction l; intros.\n    unfold subset_invariant_bs; intros.\n    simpl in *.\n    unfold emp in *; intros.\n    destruct H with (a:= a0).\n    rewrite H0 in H1; auto.\n    repeat destruct H1.\n    apply H0.\n    \n    simpl in *.\n    apply subset_invariant_bs_union.\n    unfold subset_invariant_bs; intros.\n    unfold ptsto_subset_b in *;\n    destruct_lift H0.\n    \n    destruct H with (a:= a0).\n    apply emp_star in H0 as H'.\n    apply ptsto_valid' in H'.\n    \n    \n    exists dummy.\n    rewrite H' in H1.\n    apply sep_star_lift_apply'.\n    apply emp_star.\n    apply sep_star_comm.\n    apply mem_except_ptsto.\n    auto.\n    \n    assert (forall AT AEQ V (m: @Mem.mem AT AEQ V), m = Mem.empty_mem -> emp m).\n    intros.\n    rewrite H2.\n    apply emp_empty_mem.\n    apply H2.\n    unfold Mem.empty_mem.\n    apply functional_extensionality; intros.\n    unfold mem_except.\n    destruct (addr_eq_dec x a0).\n    reflexivity.\n    \n    destruct H with (a:= x).\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite H4; rewrite Hx; reflexivity.\n    unfold not; intros.\n    apply n; omega.\n    \n    \n    destruct H4.\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite Hx in H4.\n    destruct H4; reflexivity.\n    unfold not; intros.\n    apply n; omega.\n    auto.\n    \n    (* part2 *)\n    destruct H1.\n    apply emp_star in H0 as H'.\n    apply ptsto_valid' in H'.\n    rewrite H' in H2; simpl in H2.\n    \n    \n    exists (a_1::dummy).\n    apply sep_star_lift_apply'.\n    apply emp_star.\n    apply sep_star_comm.\n    apply mem_except_ptsto.\n    auto.\n    \n    assert (forall AT AEQ V (m: @Mem.mem AT AEQ V), m = Mem.empty_mem -> emp m).\n    intros.\n    rewrite H4.\n    apply emp_empty_mem.\n    apply H4.\n    unfold Mem.empty_mem.\n    apply functional_extensionality; intros.\n    unfold mem_except.\n    destruct (addr_eq_dec x a0).\n    reflexivity.\n   \n   destruct H with (a:= x).\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite H5; rewrite Hx; reflexivity.\n    unfold not; intros; apply n; omega.\n    \n    \n    destruct H5.\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite Hx in H5.\n    destruct H5; reflexivity.\n    unfold not; intros; apply n; omega.\n    unfold incl; intros.\n    apply H3.\n    repeat destruct H4.\n    apply in_eq.\n    apply in_eq.\n    apply in_cons.\n    auto.\n    auto.\n    \n    \n    unfold sep_star in H2; rewrite sep_star_is in H2; unfold sep_star_impl in H2.\n    destruct H2.\n    destruct H2.\n    destruct H2.\n    destruct H3.\n    destruct H4.\n    \n    unfold_sep_star.\n    exists (fun a => match x a with\n                     | None => None\n                     | Some v => bsl' a\n                     end).\n    exists (fun a => match x0 a with\n                     | None => None\n                     | Some v => bsl' a\n                     end).\n    repeat split.\n    apply functional_extensionality; intros.\n    unfold mem_union.\n    destruct (bsl x1) eqn:D.\n    rewrite H2 in D. unfold mem_union in D.\n    destruct (x x1) eqn:D1.\n    destruct (bsl' x1).\n    reflexivity.\n    destruct (x0 x1); reflexivity.\n    rewrite D; reflexivity.\n    \n    rewrite H2 in D.\n    unfold mem_union in D.\n    destruct (x x1) eqn:D1.\n    inversion D.\n    \n    destruct H1 with (a:= x1).\n    rewrite H2 in H6.\n    unfold mem_union in H6.\n    rewrite D1 in H6; simpl in H6; rewrite D in H6.\n    rewrite H6; rewrite D; reflexivity.\n    \n    destruct H6.\n    rewrite H2 in H6.\n    unfold mem_union in H6.\n    rewrite D1 in H6; simpl in H6; rewrite D in H6.\n    destruct H6; reflexivity.\n    \n    unfold mem_disjoint in *.\n    unfold not; intros.\n    do 4 destruct H6.\n    destruct H3.\n    destruct (x x1) eqn:D.\n    destruct (x0 x1) eqn:D1.\n    exists x1.\n    exists p.\n    exists p0.\n    split; auto.\n    inversion H7.\n    inversion H6.\n    eapply H.\n    intros.\n    2: eauto.\n    unfold isSubset in *; simpl in *; intros.\n    \n    destruct H1 with (a:= a).\n    left.\n    unfold mem_union in *.\n    rewrite H2 in H6.\n    destruct (x a) eqn:D.\n    auto.\n    reflexivity.\n    \n    destruct H6.\n    rewrite H2 in H7.\n    unfold some_strip, mem_union in *.\n    destruct (x a) eqn:D.\n    right.\n    split.\n    unfold not; intros Hx; inversion Hx.\n    auto.\n    left.\n    reflexivity. \n    \n    eapply H0.\n    intros.\n    2: eauto.\n    unfold isSubset in *; simpl in *; intros.\n    \n    destruct H1 with (a:= a).\n    left.\n    unfold mem_union in *.\n    rewrite H2 in H6.\n    destruct (x0 a) eqn:D.\n    unfold mem_disjoint in *.\n    unfold not in *.\n    destruct (x a) eqn:D1.\n    destruct H3.\n    exists a, p0, p.\n    split; auto.\n    auto.\n    reflexivity.\n    \n    destruct H6.\n    rewrite H2 in H7.\n    unfold some_strip, mem_union in *.\n    destruct (x0 a) eqn:D.\n    right.\n    split.\n    unfold not; intros Hx; inversion Hx.\n    destruct (x a) eqn:D1.\n    destruct H3.\n    exists a, p0, p.\n    split; auto.\n    auto.\n    left; reflexivity.\nQed.\n\nLemma subset_invariant_bs_ptsto_subset_b: forall l a,\nsubset_invariant_bs (arrayN ptsto_subset_b a l).\n  Proof.\n    induction l; intros.\n    unfold subset_invariant_bs; intros.\n    simpl in *.\n    unfold emp in *; intros.\n    destruct H with (a:= a0).\n    rewrite H0 in H1; auto.\n    repeat destruct H1.\n    apply H0.\n    \n    simpl in *.\n    apply subset_invariant_bs_union.\n    unfold subset_invariant_bs; intros.\n    unfold ptsto_subset_b in *;\n    destruct_lift H0.\n    \n    destruct H with (a:= a0).\n    apply emp_star in H0 as H'.\n    apply ptsto_valid' in H'.\n    \n    \n    exists dummy.\n    rewrite H' in H1.\n    apply sep_star_lift_apply'.\n    apply emp_star.\n    apply sep_star_comm.\n    apply mem_except_ptsto.\n    auto.\n    \n    assert (forall AT AEQ V (m: @Mem.mem AT AEQ V), m = Mem.empty_mem -> emp m).\n    intros.\n    rewrite H2.\n    apply emp_empty_mem.\n    apply H2.\n    unfold Mem.empty_mem.\n    apply functional_extensionality; intros.\n    unfold mem_except.\n    destruct (addr_eq_dec x a0).\n    reflexivity.\n    \n    destruct H with (a:= x).\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite H4; rewrite Hx; reflexivity.\n    unfold not; intros.\n    apply n; omega.\n    \n    \n    destruct H4.\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite Hx in H4.\n    destruct H4; reflexivity.\n    unfold not; intros.\n    apply n; omega.\n    auto.\n    \n    (* part2 *)\n    destruct H1.\n    apply emp_star in H0 as H'.\n    apply ptsto_valid' in H'.\n    rewrite H' in H2; simpl in H2.\n    \n    \n    exists (a_1::dummy).\n    apply sep_star_lift_apply'.\n    apply emp_star.\n    apply sep_star_comm.\n    apply mem_except_ptsto.\n    auto.\n    \n    assert (forall AT AEQ V (m: @Mem.mem AT AEQ V), m = Mem.empty_mem -> emp m).\n    intros.\n    rewrite H4.\n    apply emp_empty_mem.\n    apply H4.\n    unfold Mem.empty_mem.\n    apply functional_extensionality; intros.\n    unfold mem_except.\n    destruct (addr_eq_dec x a0).\n    reflexivity.\n   \n   destruct H with (a:= x).\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite H5; rewrite Hx; reflexivity.\n    unfold not; intros; apply n; omega.\n    \n    \n    destruct H5.\n    apply ptsto_ne with (a':= x) in H0 as Hx.\n    rewrite Hx in H5.\n    destruct H5; reflexivity.\n    unfold not; intros; apply n; omega.\n    unfold incl; intros.\n    apply H3.\n    repeat destruct H4.\n    apply in_eq.\n    apply in_eq.\n    apply in_cons.\n    auto.\n    auto.\nQed.\n\n\nLemma list2nmem_arrayN_ptsto_subset_b_inlen: forall F off l fy,\nlength l > 0 -> \n(F \u2736 arrayN ptsto_subset_b off l)%pred (list2nmem (ByFData fy)) ->\noff < length (ByFData fy).\n  Proof.\n    intros.\n    apply ptsto_subset_b_to_ptsto in H0.\n    repeat destruct H0.\n    apply list2nmem_arrayN_bound in H0.\n    destruct H0.\n    rewrite H0 in H1; simpl in H1.\n    omega.\n    omega.\n  Qed. *)\n\n\nLemma bsplit_list_O_byte0: forall b l sz,\nbsplit_list (natToWord (sz * 8) 0) = b::l ->\nb = byte0.\nProof.\n  intros.\n  destruct sz.\n  inversion H.\n  simpl in H.\n  unfold bsplit1_dep, bsplit2_dep in H; simpl in H.\n  inversion H.\n  unfold bsplit1.\n  eq_rect_simpl.\n  unfold natToWord.\n  simpl.\n  unfold byte0.\n  reflexivity.\nQed.\n\nLemma unified_bytefile_bytefile_same: forall ufy fy,\nbytefile_valid ufy fy ->\nlength (ByFData fy) = length (UByFData ufy) ->\nByFData fy = UByFData ufy.\nProof.\n  intros.\n  rewrite H.\n  rewrite H0; apply firstn_exact.\nQed.\n\n\nLemma list2nmem_app': forall V (F: pred) a (l: list V) v,\na = length l ->\nF (list2nmem l) ->\n(F * a |-> v)%pred (list2nmem (l ++ (v::nil))).\nProof. intros; subst; apply list2nmem_app; auto. Qed.\n\n\n\n(* Lemma subset_invariant_bs_apply: forall (F:pred) l a,\nsubset_invariant_bs F ->\nF (list2nmem l) ->\nF (list2nmem (firstn a l ++ merge_bs (map fst (skipn a l)) (skipn a l))).\nProof.\n  intros.\n  unfold subset_invariant_bs in H.\n  eapply H.\n  2: apply H0.\n  intros.\n  unfold isSubset; intros.\n  destruct (le_dec a (length l)).\n  destruct (lt_dec a0 a).\n  left.\n  unfold list2nmem.\n  repeat erewrite selN_map.\n  apply some_eq.\n  rewrite selN_app1.\n  rewrite selN_firstn.\n  reflexivity.\n  auto.\n  rewrite firstn_length_l; auto.\n  omega.\n  rewrite app_length.\n  rewrite firstn_length_l.\n  omega.\n  auto.\n  \n  destruct (lt_dec a0 (length l)).\n  right.\n  split.\n  unfold list2nmem, not; erewrite selN_map. intros Hx; inversion Hx.\n  auto.\n  unfold list2nmem.\n  erewrite selN_map. \n  rewrite selN_app2.\n  rewrite merge_bs_selN.\n  erewrite selN_map.\n  repeat rewrite skipn_selN.\n  repeat rewrite firstn_length_l.\n  repeat rewrite <- le_plus_minus.\n  apply some_eq.\n  unfold some_strip.\n  repeat erewrite selN_map.\n  reflexivity.\n  all: try rewrite firstn_length_l.\n  all: try rewrite map_length.\n  all: try rewrite skipn_length.\n  all: try omega.\n  rewrite app_length.\n  rewrite merge_bs_length.\n  rewrite map_length.\n  rewrite skipn_length.\n  rewrite firstn_length_l.\n  omega.\n  auto.\n  left.\n  unfold list2nmem.\n  repeat rewrite selN_oob.\n  reflexivity.\n  rewrite map_length; omega.\n  rewrite map_length.\n  rewrite app_length.\n  rewrite merge_bs_length.\n  rewrite map_length.\n  rewrite skipn_length.\n  rewrite firstn_length_l.\n  omega.\n  omega.\n  rewrite skipn_oob.\n  rewrite firstn_oob.\n  simpl.\n  rewrite app_nil_r.\n  left.\n  reflexivity.\n  all: omega.\n  Grab Existential Variables.\n  all: apply byteset0.\nQed.\n *)\nLemma unified_bytefile_bytefile_firstn: forall a ufy fy,\na <= length (ByFData fy) ->\nbytefile_valid ufy fy ->\nfirstn a (ByFData fy) = firstn a (UByFData ufy).\n\tProof.\n\t\tintros.\n\t\trewrite H0.\n\t\trewrite firstn_firstn.\n\t\trewrite Nat.min_l.\n\t\treflexivity.\n\t\tauto.\n\tQed.\n\nLemma unified_bytefile_minus: forall f pfy ufy fy a,\n\t\tproto_bytefile_valid f pfy ->\n\t\tunified_bytefile_valid pfy ufy ->\n\t\tbytefile_valid ufy fy ->\n\t\tlength (ByFData fy) > (length (DFData f) - 1) * valubytes ->\n\t\t a >= valubytes ->\n\t\t length (ByFData fy) >= length (UByFData ufy) - a.\n\t\t Proof.\n\t\t \tintros.\n\t\t \teapply le_trans.\n\t\t \tinstantiate (1:= length (UByFData ufy) - valubytes).\n\t\t \tomega.\n\t\t \trewrite H1.\n\t\t \trewrite H0.\n\t\t \trewrite H.\n\t\t \trewrite concat_hom_length with (k:= valubytes).\n\t\t \trewrite map_length.\n\t\t \trewrite firstn_length_l.\n\t\t \trewrite Nat.mul_sub_distr_r in H2.\n\t\t \tsimpl in H2.\n\t\t \trewrite <- plus_n_O in H2.\n\t\t \tapply Nat.lt_le_incl.\n\t\t \tauto.\n\t \t\trewrite concat_hom_length with (k:= valubytes).\n\t\t \trewrite map_length.\n\t\t \teapply bfile_bytefile_length; eauto.\n\t\t \trewrite <- H.\n\t\t \teapply proto_len; eauto.\n\t\t \trewrite <- H.\n\t\t \teapply proto_len; eauto.\n\t \tQed.\n\t\n\tLemma bfile_bytefile_length_eq: forall f pfy ufy fy a,\n\tproto_bytefile_valid f pfy ->\n\tunified_bytefile_valid pfy ufy ->\n\tbytefile_valid ufy fy ->\n\tlength (ByFData fy) = a - a mod valubytes ->\n\tlength (ByFData fy) > (length (DFData f) - 1) * valubytes ->\n\tlength (ByFData fy) = length (DFData f) * valubytes.\n\tProof. \n\t\tintros.\n\t\trewrite mod_minus in H2.\n\t\tassert (length (ByFData fy) <= length (DFData f) * valubytes).\n\t\teapply bfile_bytefile_length; eauto.\n\t\trewrite H2 in *.\n\t\tapply lt_mult_weaken in H3.\n\t\tapply le_mult_weaken in H4.\n\t\tapply eq_rect_word_mult_helper.\n\t\tomega.\n\t\tapply valubytes_ge_O.\n\t\tapply valubytes_ne_O.\n\tQed.\n\t\n\t\n\tLemma proto_bytefile_unified_bytefile_selN: forall a f pfy ufy,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\na < length (PByFData pfy) ->\nselN (PByFData pfy) a nil = get_sublist (UByFData ufy) (a * valubytes) valubytes.\nProof.\n\tintros.\n\tunfold get_sublist.\n\trewrite H0.\n\trewrite concat_hom_skipn.\n\treplace valubytes with (1* valubytes) by omega.\n\trewrite concat_hom_firstn.\n\trewrite firstn1.\n\trewrite skipn_selN.\n\trewrite <- plus_n_O. reflexivity.\n\teapply proto_skip_len; eauto.\n\teapply proto_len; eauto.\nQed.\n\n\t\n\tLemma unified_bytefile_bytefile_length_eq: forall f pfy ufy fy,\n\tproto_bytefile_valid f pfy ->\n\tunified_bytefile_valid pfy ufy ->\n\tbytefile_valid ufy fy ->\n\tlength (ByFData fy) > (length (DFData f) - 1) * valubytes ->\n\tlength (ByFData fy) mod valubytes = 0 ->\n\tlength (ByFData fy) =length (UByFData ufy).\n\tProof.\n\t\tintros.\n\t\terewrite unified_byte_protobyte_len with (k:= valubytes); eauto.\n\t\terewrite bfile_protobyte_len_eq; eauto.\n\t\teapply bfile_bytefile_length_eq; eauto.\n\t\tinstantiate (1:= length (ByFData fy)).\n\t\tomega.\n\t\teapply proto_len; eauto.\n\tQed.\n\n\t\n\t\n\tLemma bytefile_bfile_minus_lt: forall f fy fy' n, \n\t(length (ByFData fy) > 0 -> length (ByFData fy) > (length (DFData f) - 1) * valubytes) ->\n\t# (INODE.ABytes (ByFAttr fy)) = length (ByFData fy) ->\n\tByFAttr fy =\n      ($ (length (ByFData fy') + (valubytes - length (ByFData fy') mod valubytes)), snd (ByFAttr fy')) ->\n  goodSize addrlen (length (ByFData fy') + n) ->\n  0 < (n - (valubytes - length (ByFData fy') mod valubytes)) mod valubytes ->\n  length (ByFData fy) > (length (DFData f) - 1) * valubytes.\n  Proof.\n    intros.\n\t  apply H.\n\t  rewrite <- H0; rewrite H1; simpl.\n\t  rewrite wordToNat_natToWord_idempotent'; auto.\n\t  pose proof mod_minus_lt_0.\n\t  pose proof valubytes_ne_O.\n\t  apply H4 with (a:= length (ByFData fy')) in H5 as H'.\n\t  omega.\n\n\t  eapply goodSize_trans.\n\t  2: apply H2.\n\t  apply plus_le_compat_l.\n\t  apply mod_ne_0 in H3; auto.\n\t  omega.\n\t  apply valubytes_ne_O.\n  Qed.\n  \n  \n  \n\n\t\n\tLemma bytefile_mod_0: forall fy fy' n, \n\t# (INODE.ABytes (ByFAttr fy)) = length (ByFData fy) ->\n\tByFAttr fy =\n      ($ (length (ByFData fy') + (valubytes - length (ByFData fy') mod valubytes)), snd (ByFAttr fy')) ->\n  goodSize addrlen (length (ByFData fy') + n) ->\n  0 < (n - (valubytes - length (ByFData fy') mod valubytes)) mod valubytes ->\n  length (ByFData fy) mod valubytes = 0.\n\t\n\tProof.\n    intros.\n    pose proof valubytes_ne_O as Hv.\n\t  rewrite <- H; rewrite H0; simpl.\n\t  rewrite wordToNat_natToWord_idempotent'; auto.\n\t  rewrite Nat.add_sub_assoc. \n\t  rewrite Nat.add_sub_swap.\n\t  rewrite mod_minus.\n\t  replace (length (ByFData fy') / valubytes * valubytes + valubytes)\n\t\t  with ((length (ByFData fy') / valubytes + 1) * valubytes).\n\t  apply Nat.mod_mul; auto.\n\t  rewrite Nat.mul_add_distr_r.\n\t  omega.\n\t  auto.\n\t  apply Nat.mod_le; auto.\n\t  apply mod_upper_bound_le'; auto.\n\t  eapply goodSize_trans.\n\t  2: apply H1.\n\t  apply plus_le_compat_l.\n\t  apply mod_ne_0 in H2; auto.\n\t  omega.\n  Qed.\n  \n  \tLemma Forall_map_v_app: forall n fy,\n\tForall (fun sublist : list byteset => length sublist = valubytes)\n  (map valuset2bytesets\n     (synced_list (valu0_pad ((n - (valubytes - length (ByFData fy) mod valubytes)) / valubytes))) ++\n   valuset2bytesets (valu0, nil) :: nil).\n  Proof.\n    intros.\n\t\n\trewrite Forall_forall; intros.\n\tapply in_app_iff in H.\n\trepeat destruct H.\n\tapply in_map_iff in H.\n\trepeat destruct H;\n\tapply valuset2bytesets_len.\n\tapply valuset2bytesets_len.\n  Qed.\n  \n  \t\n\tLemma mod_lt_0_le: forall a b c,\n  c <> 0 ->\n  (a - b) mod c > 0 ->\n  a >= b.\n  Proof.\n    intros.\n    apply mod_ne_0 in H0; auto.\n    omega.\n  Qed.\n  \n    \n  Lemma list_zero_pad_nil_skipn: forall a n,\n  skipn (a) (list_zero_pad nil n) = list_zero_pad nil (n - a).\n  Proof.\n    induction a; intros; simpl.\n    rewrite <- minus_n_O.\n    reflexivity.\n    destruct n; simpl.\n    reflexivity.\n    rewrite list_zero_pad_expand; simpl.\n    apply IHa.\n  Qed.\n  \n  Lemma valu0_pad_length: forall a,\n\tlength (valu0_pad a) = a.\n\tProof. \n\t\tinduction a. reflexivity.\n\t\tsimpl.\n\t\trewrite IHa; reflexivity.\n\tQed.\n\t\nLemma pm_2_3_cancel: forall a b,\n\ta + b - b = a.\n\tProof. intros; omega. Qed.\n\t\n\t\tLemma list2nmem_arrayN_app_general: forall A (F: pred) a (l l' l'': list A),\n\tF (list2nmem l) ->\n\ta = length l ->\n\tl' = l'' ->\n\t(F * arrayN (ptsto (V:= A)) a l')%pred (list2nmem (l ++ l'')).\n\tProof.\n\t  intros; subst.\n\t  apply list2nmem_arrayN_app; auto.\n  Qed.\n\n\nLemma list_zero_pad_nil_app: forall a b,\nlist_zero_pad nil a ++ list_zero_pad nil b = list_zero_pad nil (a + b).\nProof.\n\tinduction a; intros; simpl.\n\treflexivity.\n\trewrite list_zero_pad_expand.\n\trewrite app_assoc_reverse.\n\trewrite IHa.\n\tsymmetry; apply list_zero_pad_expand.\nQed.\n\t\n\n\n\nLemma Forall_map_vs2bs: forall l,\nForall (fun sublist : list byteset => length sublist = valubytes)\n  (map valuset2bytesets l).\nProof.\n\tintros; rewrite Forall_forall; intros.\n\tapply in_map_iff in H.\n\trepeat destruct H.\n\tapply valuset2bytesets_len.\nQed.\n\n\n\nLemma concat_hom_length_map_vs2bs: forall l,\nlength (concat (map valuset2bytesets l)) = (length l) * valubytes.\nProof.\n\tintros.\n\trewrite concat_hom_length with (k:= valubytes).\n\trewrite map_length; reflexivity.\n\tapply Forall_map_vs2bs.\nQed.\n\nLemma skipn_exact: forall A (l: list A),\nskipn (length l) l = nil.\nProof.\n\tintros; rewrite skipn_oob.\n\treflexivity.\n\tapply le_n.\nQed.\n\n \nLemma bytefile_length_sub: forall fy a b,\n# (INODE.ABytes (ByFAttr fy)) = length (ByFData fy) ->\nByFAttr fy = ($ a, b) ->\ngoodSize addrlen a ->\nlength (ByFData fy) = a.\nProof.\n\tintros; rewrite <- H; rewrite H0; simpl;\n\trewrite wordToNat_natToWord_idempotent'; auto.\nQed.\n\nLemma bsplit_list_0_list_zero_pad_eq: forall a,\n  \tbsplit_list (natToWord (a * 8) 0) = list_zero_pad nil a.\n\tProof.\n\t\tintros.\n\t\tinduction a.\n\t\treflexivity.\n\t\tunfold natToWord in *.\n\t\tsimpl.\n\t\tunfold bsplit1_dep, bsplit2_dep; simpl.\n\t\tunfold bsplit1, bsplit2.\n\t\teq_rect_simpl.\n\t\tsimpl.\n\t\trewrite list_zero_pad_expand.\n\t\trewrite IHa.\n\t\tsimpl.\n\t\treflexivity.\n\tQed.\n\t\t\n  Lemma valu2list_valu0:\n  valu2list valu0 = list_zero_pad nil valubytes.\n  Proof.\n    unfold valu0; simpl.\n    unfold valu2list.\n    rewrite bytes2valu2bytes.\n  \tapply bsplit_list_0_list_zero_pad_eq.\n\tQed.\n  \n  Lemma valuset2bytesets_synced_list_valu0_pad_merge_bs_zero_pad_nil:\n  valuset2bytesets (valu0, nil) = merge_bs (list_zero_pad nil valubytes) nil.\n  Proof.\n  \tunfold valuset2bytesets; simpl.\n  \trewrite v2b_rec_nil.\n  \trewrite l2b_cons_x_nil.\n\trewrite valu2list_valu0.\n\trewrite merge_bs_nil.\n\treflexivity.\n\tsymmetry; apply valu2list_len.\n\tQed.\n\t\n\tLemma synced_list_map_nil_eq: forall (l:list valu),\nsynced_list l = map (fun x => (x, nil)) l.\nProof.\n\tinduction l.\n\tunfold synced_list; reflexivity.\n\tsimpl.\n\tunfold synced_list in *. simpl.\n\trewrite IHl; reflexivity.\nQed.\n\nLemma merge_bs_map_x_nil_eq: forall l,\nmap (fun x : word 8 => (x, nil)) l = merge_bs l nil.\nProof.\n\tinduction l.\n\treflexivity.\n\tsimpl.\n\trewrite IHl; reflexivity.\nQed.\n\nLemma valuset2bytesets_valu0: \n\tvaluset2bytesets (valu0, nil) = merge_bs (list_zero_pad nil valubytes) nil.\nProof.\n\tunfold valuset2bytesets; simpl.\n\trewrite v2b_rec_nil.\n\trewrite l2b_cons_x_nil.\n\trewrite valu2list_valu0.\n\tapply merge_bs_map_x_nil_eq.\n\tsymmetry; apply valu2list_len.\nQed.\n\n\nLemma merge_bs_nil_app: forall l1 l2,\nmerge_bs l1 nil ++ merge_bs l2 nil = merge_bs (l1++l2) nil.\nProof.\n\tinduction l1; intros; try reflexivity.\n\tsimpl.\n\trewrite IHl1.\n\treflexivity.\nQed.\n\nLemma concat_map_valuset2bytesets_valu0: forall a,\nconcat (map (fun x : valu => valuset2bytesets (x, nil))\n     (valu0_pad a)) =  merge_bs (list_zero_pad nil (a*valubytes)) nil.\nProof.\n\tinduction a.\n\treflexivity.\n\tsimpl.\n\trewrite valuset2bytesets_valu0.\n\trewrite IHa.\n\trewrite merge_bs_nil_app.\n\trewrite list_zero_pad_nil_app.\n\treflexivity.\nQed.\n\n\nLemma ge_1_gt_0: forall a, a > 0 -> a >= 1.\nProof. intros; omega. Qed.\n\nLemma mod_ge_0: forall a b c,\na mod b > 0 ->\nb <> 0 ->\na + c > 0.\nProof.\n  intros.\n  apply mod_ne_0 in H; omega.\nQed.\n\nLemma mod_plus_minus_0: forall c b a,\nb <> 0 ->\nc > 0 ->\n(a + ((c * b) - a mod b)) mod b = 0.\nProof.\n  intros.\n  rewrite Nat.add_sub_assoc.\n  rewrite Nat.add_sub_swap.\n  rewrite Nat.mod_add.\n  apply mod_minus_mod.\n  all: auto.\n  apply Nat.mod_le; auto.\n  destruct c; try omega.\n  simpl.\n  eapply le_trans.\n  apply mod_upper_bound_le'; eauto.\n  apply le_plus_l.\nQed.\n\nLemma div_ge_0: forall a b,\nb <> 0 ->\na / b > 0 ->\na > 0.\nProof.\n  intros.\n  destruct a.\n  rewrite Nat.div_0_l in H0; auto.\n  omega.\nQed.\n\nLemma div_minus_ge_0: forall a b c,\nb <> 0 ->\n(a - c) / b > 0 ->\na > c.\nProof.\n  intros.\n  apply div_ge_0 in H0; auto.\n  omega.\nQed.\n\n\nLemma gt_0_ge_1: forall a, a > 0 <-> a >= 1.\nProof. intros; split; omega. Qed.\n\nLemma div_mod_0: forall a b,\nb<>0 -> a/b = 0 -> a mod b = 0 -> a = 0.\nProof.\n  intros.\n  apply Nat.div_exact in H1; auto.\n  rewrite H0 in H1; simpl in H1.\n  rewrite Nat.mul_0_r in H1; auto.\nQed.\n\n\nLemma mod_plus_minus_1_0: forall a b,\nb<>0 ->\n(a + (b - a mod b)) mod b = 0.\nProof.\n\tintros.\n\treplace (b - a mod b) with (1 * b - a mod b) by omega.\n\tapply mod_plus_minus_0; eauto.\nQed.\n\nLemma goodSize_le: forall a b c d,\ngoodSize a (b + c) ->\n(c < d -> False) ->\n goodSize a (b + d).\nProof.\n\tintros.\n\teapply goodSize_trans.\n\t2: eauto.\n\tapply plus_le_compat_l.\n\tapply Nat.nlt_ge in H0; apply H0.\nQed.\n\nLemma unified_bytefile_bytefile_same': forall f pfy ufy fy,\nproto_bytefile_valid f pfy ->\nunified_bytefile_valid pfy ufy ->\nbytefile_valid ufy fy ->\nlength (ByFData fy) = length (DFData f) * valubytes ->\nByFData fy = UByFData ufy.\nProof.\n  intros.\n  rewrite H1.\n  apply firstn_oob.\n  rewrite H2.\n  erewrite <- bfile_protobyte_len_eq; eauto.\n  erewrite unified_byte_protobyte_len; eauto.\n  eapply proto_len; eauto.\nQed.\n\n\n\nLemma f_pfy_selN_eq: forall f pfy i,\nproto_bytefile_valid f pfy ->\ni < length (DFData f) ->\nvalu2list (fst (selN (DFData f) i valuset0)) = map fst (selN (PByFData pfy) i nil).\nProof.\n\tintros.\n\trewrite H.\n\trewrite selN_map with (default' := valuset0); auto.\n\trewrite mapfst_valuset2bytesets.\n\treflexivity.\nQed.\n\nLemma v2l_fst_bs2vs_map_fst_eq: forall bsl,\nbsl <> nil ->\nlength bsl = valubytes ->\nmap fst bsl = valu2list (fst (bytesets2valuset bsl)).\nProof.\n\tintros.\n\tunfold bytesets2valuset.\n\tunfold byteset2list; simpl.\n\tdestruct bsl eqn:D.\n\tunfold not in H; destruct H; reflexivity.\n\tsimpl.\n\trewrite list2valu2list.\n\tunfold selN'.\n\trewrite map_map; simpl.\n\treflexivity.\n\tsimpl.\n\trewrite map_length.\n\trewrite map_length.\n\tsimpl in H0; auto.\nQed.\n\nLemma rep_sync_invariant: forall f fy F,\nsync_invariant F -> sync_invariant ([[rep f fy ]] * F)%pred.\nProof.\n  intros.\n  unfold rep.\n  apply sync_invariant_sep_star; auto.\nQed.\n\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/AByteFile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1925532101576455}}
{"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 PQueueInit                            *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\n(*Require Import LAsmModuleSemAux.*)\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import PIPCIntro.\nRequire Import PIPC.\nRequire Import IPCGenSpec.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := pipc_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := pthread_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** Relation between raw data at two layers*)\n    Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n      mkrelate_RData {\n          flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n          vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n          devout_re: devout hadt = devout ladt;\n          CR3_re:  CR3 hadt = CR3 ladt;\n          ikern_re: ikern hadt = ikern ladt;\n          pg_re: pg hadt = pg ladt;\n          ihost_re: ihost hadt = ihost ladt;\n          AC_re: AC hadt = AC ladt;\n          ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n          ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n          LAT_re: LAT hadt = LAT ladt;\n          nps_re: nps hadt = nps ladt;\n          init_re: init hadt = init ladt;\n\n          pperm_re: pperm hadt = pperm ladt;\n          PT_re:  PT hadt = PT ladt;\n          ptp_re: ptpool hadt = ptpool ladt;\n          idpde_re: idpde hadt = idpde ladt;\n          ipt_re: ipt hadt = ipt ladt;\n          smspool_re: smspool hadt = smspool ladt;\n\n          kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n          abtcb_re:  abtcb hadt = abtcb ladt;\n          abq_re:  abq hadt = abq ladt;\n          cid_re:  cid hadt = cid ladt;\n          chpool_re:  syncchpool hadt = syncchpool ladt\n        }.\n\n    Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n    | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n    Local Hint Resolve MATCH_RDATA.\n\n    Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n      {\n        relate_AbData s f d1 d2 := relate_RData f d1 d2;\n        match_AbData s d1 m f := match_RData s d1 m f;\n        new_glbl := nil\n      }.    \n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n        - eapply kctxt_inj_incr; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      Section FRESH_PRIM.\n\n        Require Import CommonTactic.\n\n        Lemma proc_init_kern_mode:\n          forall i v d,\n            proc_init_spec i d = Some v\n            -> kernel_mode d.\n        Proof.\n          unfold proc_init_spec. simpl; intros.\n          subdestruct; auto.\n        Qed.\n\n        Lemma proc_init_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem proc_init_spec) \n                    proc_init_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit proc_init_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit proc_init_kern_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        Lemma syncreceive_chan_kern_mode:\n          forall v d i1 i2 i3,\n            syncreceive_chan_spec i1 i2 i3 d = Some v\n            -> kernel_mode d\n               /\\ 0 <= i1 < num_proc.\n        Proof.\n          unfold syncreceive_chan_spec. simpl; intros.\n          subdestruct; auto.\n        Qed.\n\n        Lemma syncreceive_chan_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem syncreceive_chan_spec) \n                    syncreceive_chan_spec_low.\n        Proof.\n          compatsim_simpl (@match_AbData).\n          exploit syncreceive_chan_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit syncreceive_chan_kern_mode; eauto. \n          intros (Hkern & Hrange).\n          refine_split; try econstructor; eauto. \n          constructor.\n        Qed.\n\n        Lemma syncsendto_chan_pre_kern_mode:\n          forall i1 i2 i3 v d,\n            syncsendto_chan_pre_spec i1 i2 i3 d = Some v\n            -> kernel_mode d.\n        Proof.\n          unfold syncsendto_chan_pre_spec. simpl; intros.\n          subdestruct; auto.\n        Qed.\n\n        Lemma syncsendto_chan_pre_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem syncsendto_chan_pre_spec) \n                    syncsendto_chan_pre_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit syncsendto_chan_pre_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit syncsendto_chan_pre_kern_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        Lemma syncsendto_chan_post_kern_mode:\n          forall v d,\n            syncsendto_chan_post_spec d = Some v\n            -> kernel_mode d.\n        Proof.\n          unfold syncsendto_chan_post_spec. simpl; intros.\n          subdestruct; auto.\n        Qed.\n\n        Lemma syncsendto_chan_post_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem syncsendto_chan_post_spec) \n                    syncsendto_chan_post_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit syncsendto_chan_post_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit syncsendto_chan_post_kern_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n      End FRESH_PRIM.\n\n      Section PASSTHROUGH_PRIM.\n\n        Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n        Proof.\n          accessor_prop_tac.\n          - eapply flatmem_store_exists; eauto.\n        Qed.          \n\n        Lemma passthrough_correct:\n          sim (crel HDATA LDATA) pipc_passthrough pipcintro.\n        Proof.\n          sim_oplus.\n          - apply fload_sim.\n          - apply fstore_sim.\n          - apply vmxinfo_get_sim.\n          - apply device_output_sim.\n          - apply pfree_sim.\n          - apply setPT_sim.\n          - apply ptRead_sim. \n          - apply ptResv_sim.\n          - apply shared_mem_status_sim.\n          - apply offer_shared_mem_sim.\n          - apply get_curid_sim.\n          - apply thread_spawn_sim.\n          - apply thread_wakeup_sim.\n          - apply ptin_sim.\n          - apply ptout_sim.\n          - apply container_get_nchildren_sim.\n          - apply container_get_quota_sim.\n          - apply container_get_usage_sim.\n          - apply container_can_consume_sim.\n          - apply alloc_sim. \n          - apply trapin_sim.\n          - apply trapout_sim.\n          - apply hostin_sim.\n          - apply hostout_sim.\n          - apply trap_info_get_sim.\n          - apply trap_info_ret_sim.\n          - apply thread_yield_sim.\n          - apply thread_sleep_sim.\n          - layer_sim_simpl.\n            + eapply load_correct2.\n            + eapply store_correct2.\n        Qed.\n\n      End PASSTHROUGH_PRIM.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\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/IPCGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1925532062601563}}
{"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.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Global.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import PFConfiguration.\nRequire Import Behavior.\n\nRequire Import OrdStep.\nRequire Import Writes.\nRequire Import WStep.\nRequire Import Stable.\nRequire Import PFtoRASim.\nRequire Import PFtoRAThread.\n\nSet Implicit Arguments.\n\n\nModule PFtoRA.\n  Section PFtoRA.\n    Variable L: Loc.t -> bool.\n\n    (* well-formedness *)\n\n    Variant wf_pf (c: Configuration.t): Prop :=\n    | wf_pf_intro\n        (WF: Configuration.wf c)\n        (PRM: forall tid lang st lc\n                (TH: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n            Local.promises lc = BoolMap.bot)\n        (GPRM: Global.promises (Configuration.global c) = BoolMap.bot)\n    .\n\n    Variant wf_ra (rels: Writes.t) (c: Configuration.t): Prop :=\n    | wf_ra_intro\n        (WF: Configuration.wf c)\n        (RELS: Writes.wf L rels (Global.memory (Configuration.global c)))\n        (PRM: forall tid lang st lc\n                (TH: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n            Local.promises lc = BoolMap.bot)\n        (GPRM: Global.promises (Configuration.global c) = BoolMap.bot)\n    .\n\n    Lemma wf_pf_thread\n          c tid lang st lc\n          (WF: wf_pf c)\n          (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)):\n      PFtoRAThread.wf_pf (Thread.mk _ st lc (Configuration.global c)).\n    Proof.\n      inv WF. inv WF0. inv WF.\n      econs; eauto.\n    Qed.\n\n    Lemma wf_ra_thread\n          rels c tid lang st lc\n          (WF: wf_ra rels c)\n          (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)):\n      PFtoRAThread.wf_ra L rels (Thread.mk _ st lc (Configuration.global c)).\n    Proof.\n      inv WF. inv WF0. inv WF.\n      econs; eauto.\n    Qed.\n\n    Lemma step_pf_future\n          e tid c1 c2\n          (WF1: wf_pf c1)\n          (STEP: PFConfiguration.estep e tid c1 c2):\n      <<WF2: wf_pf c2>>.\n    Proof.\n      exploit PFConfiguration.estep_future; try apply WF1; eauto. i. des.\n      inv STEP. ss.\n      exploit wf_pf_thread; eauto. i.\n      exploit PFtoRAThread.step_pf_future; eauto. i. des. inv x1. ss.\n      econs; ss. i. Configuration.simplify.\n      inv WF1. eauto.\n    Qed.\n\n    Lemma step_ra_future\n          ordr ordw\n          e tid rels1 rels2 c1 c2\n          (WF1: wf_ra rels1 c1)\n          (ORD: Ordering.le Ordering.plain ordw)\n          (STEP: WConfiguration.step L ordr ordw e tid rels1 rels2 c1 c2):\n      <<WF2: wf_ra rels2 c2>>.\n    Proof.\n      exploit WConfiguration.step_future; try eapply WF1; eauto. i. des.\n      inv STEP. ss.\n      exploit wf_ra_thread; eauto. i.\n      hexploit WThread.step_writes_wf; eauto; try apply x0. s. i.\n      exploit PFtoRAThread.step_ra_future; eauto. i. des. inv x1. ss.\n      econs; ss. i. Configuration.simplify; ss.\n      inv WF1. eauto.\n    Qed.\n\n    Lemma steps_pf_future\n          c1 c2\n          (WF1: wf_pf c1)\n          (STEPS: rtc (PFConfiguration.all_step) c1 c2):\n      <<WF2: wf_pf c2>>.\n    Proof.\n      induction STEPS; ss. inv H.\n      exploit step_pf_future; eauto.\n    Qed.\n\n    Lemma steps_ra_future\n          ordr ordw\n          rels1 rels2 c1 c2\n          (WF1: wf_ra rels1 c1)\n          (ORD: Ordering.le Ordering.plain ordw)\n          (STEPS: WConfiguration.steps L ordr ordw rels1 rels2 c1 c2):\n      <<WF2: wf_ra rels2 c2>>.\n    Proof.\n      induction STEPS; ss.\n      exploit step_ra_future; eauto.\n    Qed.\n\n\n    (* sim *)\n\n    Variant sim_thread_sl (rels: Writes.t) (gl_pf gl_ra: Global.t):\n      forall (sl_pf sl_ra: {lang: language & Language.state lang} * Local.t), Prop :=\n    | sim_thread_sl_intro\n        lang st_pf lc_pf st_ra lc_ra\n        (SIM: PFtoRAThread.sim_thread L rels\n                                      (Thread.mk lang st_pf lc_pf gl_pf)\n                                      (Thread.mk lang st_ra lc_ra gl_ra)):\n        sim_thread_sl rels gl_pf gl_ra\n                      (existT _ lang st_pf, lc_pf) (existT _ lang st_ra, lc_ra)\n    .\n\n    Variant sim_conf (rels: Writes.t): forall (c_pf c_ra: Configuration.t), Prop :=\n    | sim_conf_intro\n        ths_pf gl_pf\n        ths_ra gl_ra\n        (THS: forall tid,\n            option_rel\n              (sim_thread_sl rels gl_pf gl_ra)\n              (IdentMap.find tid ths_pf)\n              (IdentMap.find tid ths_ra)):\n        sim_conf rels\n                 (Configuration.mk ths_pf gl_pf)\n                 (Configuration.mk ths_ra gl_ra)\n    .\n\n    Lemma init_wf_pf syn:\n      wf_pf (Configuration.init syn).\n    Proof.\n      econs; eauto using Configuration.init_wf.\n      i. ss.\n      unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid syn); inv TH.\n      apply inj_pair2 in H1. subst. ss.\n    Qed.\n\n    Lemma init_wf_ra syn:\n      wf_ra [] (Configuration.init syn).\n    Proof.\n      econs; eauto using Configuration.init_wf; i; ss.\n      - econs; i; ss.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0. ss.\n      -unfold Threads.init in *.\n        rewrite IdentMap.Facts.map_o in *.\n        destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                    (@sigT _ (@Language.syntax ProgramEvent.t)) tid syn); inv TH.\n        apply inj_pair2 in H1. subst. ss.\n    Qed.\n\n    Lemma init_sim_conf syn:\n      sim_conf [] (Configuration.init syn) (Configuration.init syn).\n    Proof.\n      econs; ss. i. unfold option_rel.\n      destruct (IdentMap.find tid (Threads.init syn)) as [[[lang st] lc]|] eqn:FIND; ss.\n      unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid syn); inv FIND.\n      apply inj_pair2 in H1. subst.\n      econs. econs; ss.\n      (* - econs; ss; try refl. econs; try refl. ii. *)\n      (*   rewrite Memory.bot_get. ss. *)\n      (* - econs; ss. econs; ss; eauto. i. *)\n      (*   unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss. *)\n      (*   apply DOMap.singleton_find_inv in GET. des. inv GET0. ss. *)\n      - econs; ss.\n        + econs; ss. econs; ss. i. condtac; ss. refl.\n        + econs; ss; i.\n          * unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n            apply DOMap.singleton_find_inv in GET_SRC. des. inv GET_SRC0.\n            esplits; ss. econs; ss. condtac; ss.\n          * unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n            apply DOMap.singleton_find_inv in GET_TGT. des. inv GET_TGT0.\n            esplits; ss. econs; ss. condtac; ss.\n          * unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n            apply DOMap.singleton_find_inv in GET_TGT. des. inv GET_TGT0. ss.\n      - econs; ss. ii.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0.\n      - econs; ss. ii.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0.\n      - econs; ss. ii. des; ss.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET1.\n    Qed.\n\n    Lemma sim_conf_terminal\n          rels c_pf c_ra\n          (WF_RA: wf_ra rels c_ra)\n          (SIM: sim_conf rels c_pf c_ra)\n          (TERMINAL: Configuration.is_terminal c_pf):\n      Configuration.is_terminal c_ra.\n    Proof.\n      ii. inv SIM. specialize (THS tid).\n      unfold option_rel in *. ss. des_ifs.\n      destruct p as [[]]. inv THS.\n      Configuration.simplify.\n      inv SIM. inv SIM_RA. ss. subst.\n      exploit TERMINAL; eauto. i. des.\n      split; ss.\n      inv WF_RA. eauto.\n    Qed.\n\n\n    (* step *)\n\n    Lemma sim_conf_step\n          rels1 c1_pf c1_ra\n          tid e_pf c2_pf\n          (SIM1: sim_conf rels1 c1_pf c1_ra)\n          (WF1_PF: wf_pf c1_pf)\n          (WF1_RA: wf_ra rels1 c1_ra)\n          (STEP: PFConfiguration.estep e_pf tid c1_pf c2_pf):\n      (exists e_ra rels2 c2_ra,\n          (<<STEP_RA: WConfiguration.step L Ordering.acqrel Ordering.acqrel\n                                          e_ra tid rels1 rels2 c1_ra c2_ra>>) /\\\n          (<<EVENT_RA: PFtoRASim.sim_event e_ra e_pf>>) /\\\n          (<<SIM2: sim_conf rels2 c2_pf c2_ra>>)) \\/\n      (<<RACE: RARaceW.ra_race_steps L Ordering.acqrel Ordering.acqrel rels1 c1_ra>>).\n    Proof.\n      dup SIM1. inv SIM0. inv STEP. ss.\n      dup THS. specialize (THS0 tid). unfold option_rel in THS0. des_ifs.\n      inv THS0. apply inj_pair2 in H1. subst.\n      exploit wf_pf_thread; eauto. s. i.\n      exploit wf_ra_thread; try exact WF1_RA; eauto. s. i.\n      exploit PFtoRAThread.sim_thread_step; eauto. i. des; cycle 1.\n      { right. unfold RARaceW.ra_race_steps.\n        esplits; [econs 1|..]; eauto.\n      }\n      destruct e2_ra as [st2_ra lc2_ra gl2_ra].\n      left. esplits.\n      - econs; eauto.\n      - ss.\n      - econs; ss. i.\n        repeat rewrite IdentMap.gsspec. condtac; ss.\n        specialize (THS tid0). unfold option_rel in THS. des_ifs. inv THS. ss.\n        inv SIM0. econs. econs; s.\n        + inv SIM_RA. ss. subst.\n          inv SIM2. inv SIM_RA. ss.\n        + econs; try apply SIM2; try apply NORMAL_PF.\n        + econs; try apply SIM2; try apply NORMAL_RA.\n        + econs; s; try apply SIM2; try apply STABLE_RA.\n          exploit WThread.step_future; try exact STEP_RA; try apply x1. s. i. des.\n          exploit wf_ra_thread; try exact WF1_RA; try eapply Heq2. s. i.\n          exploit Stable.future_stable_tview;\n            try eapply STABLE_RA; try apply x2; try apply GL_FUTURE; eauto.\n    Qed.\n\n    Lemma sim_conf_steps\n          rels1 c1_pf c1_ra\n          c2_pf\n          (SIM1: sim_conf rels1 c1_pf c1_ra)\n          (WF1_PF: wf_pf c1_pf)\n          (WF1_RA: wf_ra rels1 c1_ra)\n          (STEPS: rtc PFConfiguration.all_step c1_pf c2_pf):\n      (exists rels2 c2_ra,\n          (<<STEPS_RA: WConfiguration.steps L Ordering.acqrel Ordering.acqrel rels1 rels2 c1_ra c2_ra>>) /\\\n          (<<SIM2: sim_conf rels2 c2_pf c2_ra>>)) \\/\n      (<<RACE: RARaceW.ra_race_steps L Ordering.acqrel Ordering.acqrel rels1 c1_ra>>).\n    Proof.\n      revert rels1  c1_ra SIM1 WF1_PF WF1_RA.\n      induction STEPS; i.\n      { left. esplits; try by econs 1. ss. }\n      inv H. exploit sim_conf_step; eauto. i. des; eauto.\n      exploit step_pf_future; eauto. i. des.\n      exploit step_ra_future; try exact STEP_RA; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des.\n      - left. esplits; (try by econs 2; eauto); ss.\n      - right. unfold RARaceW.ra_race_steps in *. des.\n        esplits; [econs 2; eauto|..]; eauto.\n    Qed.\n\n\n    (* behaviors *)\n\n    Lemma sim_conf_behavior\n          rels c_pf c_ra\n          (SIM: sim_conf rels c_pf c_ra)\n          (WF_PF: wf_pf c_pf)\n          (WF_RA: wf_ra rels c_ra)\n          (RACEFREE: RARaceW.racefree L Ordering.acqrel Ordering.acqrel rels c_ra):\n      behaviors (PFConfiguration.step ThreadEvent.get_machine_event_pf) c_pf <2=\n      behaviors (@OrdConfiguration.step L Ordering.acqrel Ordering.acqrel) c_ra.\n    Proof.\n      i. revert rels  c_ra SIM WF_PF WF_RA RACEFREE.\n      induction PR; i.\n      - econs 1. eapply sim_conf_terminal; eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit WConfiguration.step_ord_step; eauto. i.\n          inv EVENT_RA; ss. inv H0.\n          econs 2.\n          { replace (MachineEvent.syscall e2) with\n              (ThreadEvent.get_machine_event_pf (ThreadEvent.syscall e2)) by ss.\n            econs; eauto.\n          }\n          { hexploit RARaceW.step_racefree; eauto. i.\n            exploit step_pf_future; eauto. i. des.\n            exploit step_ra_future; try exact STEP_RA; eauto.\n          }\n          { ss. }\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit WConfiguration.step_ord_step; eauto. i.\n          econs 3.\n          replace MachineEvent.failure with (ThreadEvent.get_machine_event_pf e_ra); [econs; eauto|].\n          inv EVENT_RA; ss.\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit WConfiguration.step_ord_step; eauto. i.\n          econs 4.\n          { replace MachineEvent.silent with (ThreadEvent.get_machine_event_pf e_ra); cycle 1.\n            { inv EVENT_RA; ss. }\n            econs; eauto.\n          }\n          hexploit RARaceW.step_racefree; eauto. i.\n          exploit step_pf_future; eauto. i. des.\n          exploit step_ra_future; try exact STEP_RA; eauto.\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n      - econs 5.\n    Qed.\n  End PFtoRA.\nEnd PFtoRA.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/ldrfra/PFtoRA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.1924809366602316}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Typing rules for LTLin. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Memdata.\nRequire Import Op.\nRequire Import RTL.\nRequire Import Locations.\nRequire Import LTLin.\nRequire LTLtyping.\nRequire Import Conventions.\n\n(** The following predicates define a type system for LTLin similar to that\n  of LTL. *)\n\nSection WT_INSTR.\n\nVariable funsig: signature.\n\nInductive wt_instr : instruction -> Prop :=\n  | wt_Lopmove:\n      forall r1 r,\n      Loc.type r1 = Loc.type r -> loc_acceptable r1 -> loc_acceptable r ->\n      wt_instr (Lop Omove (r1 :: nil) r)\n  | wt_Lop:\n      forall op args res,\n      op <> Omove ->\n      (List.map Loc.type args, Loc.type res) = type_of_operation op ->\n      locs_acceptable args -> loc_acceptable res ->\n      wt_instr (Lop op args res)\n  | wt_Lload:\n      forall chunk addr args dst,\n      List.map Loc.type args = type_of_addressing addr ->\n      Loc.type dst = type_of_chunk chunk ->\n      locs_acceptable args -> loc_acceptable dst ->\n      wt_instr (Lload chunk addr args dst)\n  | wt_Lstore:\n      forall chunk addr args src,\n      List.map Loc.type args = type_of_addressing addr ->\n      Loc.type src = type_of_chunk chunk ->\n      locs_acceptable args -> loc_acceptable src ->\n      wt_instr (Lstore chunk addr args src)\n  | wt_Lcall:\n      forall sig ros args res,\n      List.map Loc.type args = sig.(sig_args) ->\n      Loc.type res = proj_sig_res sig ->\n      LTLtyping.call_loc_acceptable sig ros ->\n      locs_acceptable args -> loc_acceptable res ->\n      wt_instr (Lcall sig ros args res)\n  | wt_Ltailcall:\n      forall sig ros args,\n      List.map Loc.type args = sig.(sig_args) ->\n      LTLtyping.call_loc_acceptable sig ros ->\n      locs_acceptable args -> \n      sig.(sig_res) = funsig.(sig_res) ->\n      tailcall_possible sig ->\n      wt_instr (Ltailcall sig ros args)\n  | wt_Lbuiltin:\n      forall ef args res,\n      List.map Loc.type args = (ef_sig ef).(sig_args) ->\n      Loc.type res = proj_sig_res (ef_sig ef) ->\n      arity_ok (ef_sig ef).(sig_args) = true \\/ ef_reloads ef = false ->\n      locs_acceptable args -> loc_acceptable res ->\n       wt_instr (Lbuiltin ef args res)\n  | wt_Llabel: forall lbl,\n      wt_instr (Llabel lbl)\n  | wt_Lgoto: forall lbl,\n      wt_instr (Lgoto lbl)\n  | wt_Lcond:\n      forall cond args lbl,\n      List.map Loc.type args = type_of_condition cond ->\n      locs_acceptable args ->\n      wt_instr (Lcond cond args lbl)\n  | wt_Ljumptable:\n      forall arg tbl,\n      Loc.type arg = Tint ->\n      loc_acceptable arg ->\n      list_length_z tbl * 4 <= Int.max_unsigned ->\n      wt_instr (Ljumptable arg tbl)\n  | wt_Lreturn: \n      forall optres,\n      option_map Loc.type optres = funsig.(sig_res) ->\n      match optres with None => True | Some r => loc_acceptable r end ->\n      wt_instr (Lreturn optres).\n\nDefinition wt_code (c: code) : Prop :=\n  forall i, In i c -> wt_instr i.\n\nEnd WT_INSTR.\n\nRecord wt_function (f: function): Prop :=\n  mk_wt_function {\n    wt_params:\n      List.map Loc.type f.(fn_params) = f.(fn_sig).(sig_args);\n    wt_acceptable:\n      locs_acceptable f.(fn_params);\n    wt_norepet:\n      Loc.norepet f.(fn_params);\n    wt_instrs:\n      wt_code f.(fn_sig) f.(fn_code)\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef)\n  | wt_function_internal: forall f,\n      wt_function f ->\n      wt_fundef (Internal f).\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, f) (prog_funct p) -> wt_fundef f.\n", "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/LTLintyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.1924809328232811}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nImport Clightdefs.ClightNotations.\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\nLocal Open Scope clight_scope.\n\nModule Info.\n  Definition version := \"3.10\".\n  Definition build_number := \"\".\n  Definition build_tag := \"\".\n  Definition build_branch := \"\".\n  Definition arch := \"x86\".\n  Definition model := \"32sse2\".\n  Definition abi := \"standard\".\n  Definition bitsize := 32.\n  Definition big_endian := false.\n  Definition source_file := \"dotprod.c\".\n  Definition normalized := true.\nEnd Info.\n\nDefinition _N : ident := $\"N\".\nDefinition _R : ident := $\"R\".\nDefinition _REPEAT : ident := $\"REPEAT\".\nDefinition _T : ident := $\"T\".\nDefinition __155 : ident := $\"_155\".\nDefinition __156 : ident := $\"_156\".\nDefinition __229 : ident := $\"_229\".\nDefinition __230 : ident := $\"_230\".\nDefinition __231 : ident := $\"_231\".\nDefinition __Bigint : ident := $\"_Bigint\".\nDefinition ___builtin_annot : ident := $\"__builtin_annot\".\nDefinition ___builtin_annot_intval : ident := $\"__builtin_annot_intval\".\nDefinition ___builtin_bswap : ident := $\"__builtin_bswap\".\nDefinition ___builtin_bswap16 : ident := $\"__builtin_bswap16\".\nDefinition ___builtin_bswap32 : ident := $\"__builtin_bswap32\".\nDefinition ___builtin_bswap64 : ident := $\"__builtin_bswap64\".\nDefinition ___builtin_clz : ident := $\"__builtin_clz\".\nDefinition ___builtin_clzl : ident := $\"__builtin_clzl\".\nDefinition ___builtin_clzll : ident := $\"__builtin_clzll\".\nDefinition ___builtin_ctz : ident := $\"__builtin_ctz\".\nDefinition ___builtin_ctzl : ident := $\"__builtin_ctzl\".\nDefinition ___builtin_ctzll : ident := $\"__builtin_ctzll\".\nDefinition ___builtin_debug : ident := $\"__builtin_debug\".\nDefinition ___builtin_expect : ident := $\"__builtin_expect\".\nDefinition ___builtin_fabs : ident := $\"__builtin_fabs\".\nDefinition ___builtin_fabsf : ident := $\"__builtin_fabsf\".\nDefinition ___builtin_fmadd : ident := $\"__builtin_fmadd\".\nDefinition ___builtin_fmax : ident := $\"__builtin_fmax\".\nDefinition ___builtin_fmin : ident := $\"__builtin_fmin\".\nDefinition ___builtin_fmsub : ident := $\"__builtin_fmsub\".\nDefinition ___builtin_fnmadd : ident := $\"__builtin_fnmadd\".\nDefinition ___builtin_fnmsub : ident := $\"__builtin_fnmsub\".\nDefinition ___builtin_fsqrt : ident := $\"__builtin_fsqrt\".\nDefinition ___builtin_membar : ident := $\"__builtin_membar\".\nDefinition ___builtin_memcpy_aligned : ident := $\"__builtin_memcpy_aligned\".\nDefinition ___builtin_read16_reversed : ident := $\"__builtin_read16_reversed\".\nDefinition ___builtin_read32_reversed : ident := $\"__builtin_read32_reversed\".\nDefinition ___builtin_sel : ident := $\"__builtin_sel\".\nDefinition ___builtin_sqrt : ident := $\"__builtin_sqrt\".\nDefinition ___builtin_unreachable : ident := $\"__builtin_unreachable\".\nDefinition ___builtin_va_arg : ident := $\"__builtin_va_arg\".\nDefinition ___builtin_va_copy : ident := $\"__builtin_va_copy\".\nDefinition ___builtin_va_end : ident := $\"__builtin_va_end\".\nDefinition ___builtin_va_start : ident := $\"__builtin_va_start\".\nDefinition ___builtin_write16_reversed : ident := $\"__builtin_write16_reversed\".\nDefinition ___builtin_write32_reversed : ident := $\"__builtin_write32_reversed\".\nDefinition ___cleanup : ident := $\"__cleanup\".\nDefinition ___compcert_i64_dtos : ident := $\"__compcert_i64_dtos\".\nDefinition ___compcert_i64_dtou : ident := $\"__compcert_i64_dtou\".\nDefinition ___compcert_i64_sar : ident := $\"__compcert_i64_sar\".\nDefinition ___compcert_i64_sdiv : ident := $\"__compcert_i64_sdiv\".\nDefinition ___compcert_i64_shl : ident := $\"__compcert_i64_shl\".\nDefinition ___compcert_i64_shr : ident := $\"__compcert_i64_shr\".\nDefinition ___compcert_i64_smod : ident := $\"__compcert_i64_smod\".\nDefinition ___compcert_i64_smulh : ident := $\"__compcert_i64_smulh\".\nDefinition ___compcert_i64_stod : ident := $\"__compcert_i64_stod\".\nDefinition ___compcert_i64_stof : ident := $\"__compcert_i64_stof\".\nDefinition ___compcert_i64_udiv : ident := $\"__compcert_i64_udiv\".\nDefinition ___compcert_i64_umod : ident := $\"__compcert_i64_umod\".\nDefinition ___compcert_i64_umulh : ident := $\"__compcert_i64_umulh\".\nDefinition ___compcert_i64_utod : ident := $\"__compcert_i64_utod\".\nDefinition ___compcert_i64_utof : ident := $\"__compcert_i64_utof\".\nDefinition ___compcert_va_composite : ident := $\"__compcert_va_composite\".\nDefinition ___compcert_va_float64 : ident := $\"__compcert_va_float64\".\nDefinition ___compcert_va_int32 : ident := $\"__compcert_va_int32\".\nDefinition ___compcert_va_int64 : ident := $\"__compcert_va_int64\".\nDefinition ___count : ident := $\"__count\".\nDefinition ___getreent : ident := $\"__getreent\".\nDefinition ___locale_t : ident := $\"__locale_t\".\nDefinition ___sFILE64 : ident := $\"__sFILE64\".\nDefinition ___sbuf : ident := $\"__sbuf\".\nDefinition ___sdidinit : ident := $\"__sdidinit\".\nDefinition ___sf : ident := $\"__sf\".\nDefinition ___sglue : ident := $\"__sglue\".\nDefinition ___stringlit_1 : ident := $\"__stringlit_1\".\nDefinition ___stringlit_2 : ident := $\"__stringlit_2\".\nDefinition ___tm : ident := $\"__tm\".\nDefinition ___tm_hour : ident := $\"__tm_hour\".\nDefinition ___tm_isdst : ident := $\"__tm_isdst\".\nDefinition ___tm_mday : ident := $\"__tm_mday\".\nDefinition ___tm_min : ident := $\"__tm_min\".\nDefinition ___tm_mon : ident := $\"__tm_mon\".\nDefinition ___tm_sec : ident := $\"__tm_sec\".\nDefinition ___tm_wday : ident := $\"__tm_wday\".\nDefinition ___tm_yday : ident := $\"__tm_yday\".\nDefinition ___tm_year : ident := $\"__tm_year\".\nDefinition ___value : ident := $\"__value\".\nDefinition ___wch : ident := $\"__wch\".\nDefinition ___wchb : ident := $\"__wchb\".\nDefinition __add : ident := $\"_add\".\nDefinition __asctime_buf : ident := $\"_asctime_buf\".\nDefinition __atexit : ident := $\"_atexit\".\nDefinition __atexit0 : ident := $\"_atexit0\".\nDefinition __base : ident := $\"_base\".\nDefinition __bf : ident := $\"_bf\".\nDefinition __blksize : ident := $\"_blksize\".\nDefinition __close : ident := $\"_close\".\nDefinition __cookie : ident := $\"_cookie\".\nDefinition __cvtbuf : ident := $\"_cvtbuf\".\nDefinition __cvtlen : ident := $\"_cvtlen\".\nDefinition __data : ident := $\"_data\".\nDefinition __dso_handle : ident := $\"_dso_handle\".\nDefinition __emergency : ident := $\"_emergency\".\nDefinition __errno : ident := $\"_errno\".\nDefinition __file : ident := $\"_file\".\nDefinition __flags : ident := $\"_flags\".\nDefinition __flags2 : ident := $\"_flags2\".\nDefinition __fnargs : ident := $\"_fnargs\".\nDefinition __fns : ident := $\"_fns\".\nDefinition __fntypes : ident := $\"_fntypes\".\nDefinition __freelist : ident := $\"_freelist\".\nDefinition __gamma_signgam : ident := $\"_gamma_signgam\".\nDefinition __getdate_err : ident := $\"_getdate_err\".\nDefinition __glue : ident := $\"_glue\".\nDefinition __h_errno : ident := $\"_h_errno\".\nDefinition __inc : ident := $\"_inc\".\nDefinition __ind : ident := $\"_ind\".\nDefinition __iobs : ident := $\"_iobs\".\nDefinition __is_cxa : ident := $\"_is_cxa\".\nDefinition __k : ident := $\"_k\".\nDefinition __l64a_buf : ident := $\"_l64a_buf\".\nDefinition __lb : ident := $\"_lb\".\nDefinition __lbfsize : ident := $\"_lbfsize\".\nDefinition __locale : ident := $\"_locale\".\nDefinition __localtime_buf : ident := $\"_localtime_buf\".\nDefinition __lock : ident := $\"_lock\".\nDefinition __maxwds : ident := $\"_maxwds\".\nDefinition __mblen_state : ident := $\"_mblen_state\".\nDefinition __mbrlen_state : ident := $\"_mbrlen_state\".\nDefinition __mbrtowc_state : ident := $\"_mbrtowc_state\".\nDefinition __mbsrtowcs_state : ident := $\"_mbsrtowcs_state\".\nDefinition __mbstate : ident := $\"_mbstate\".\nDefinition __mbtowc_state : ident := $\"_mbtowc_state\".\nDefinition __mult : ident := $\"_mult\".\nDefinition __nbuf : ident := $\"_nbuf\".\nDefinition __new : ident := $\"_new\".\nDefinition __next : ident := $\"_next\".\nDefinition __nextf : ident := $\"_nextf\".\nDefinition __niobs : ident := $\"_niobs\".\nDefinition __nmalloc : ident := $\"_nmalloc\".\nDefinition __offset : ident := $\"_offset\".\nDefinition __on_exit_args : ident := $\"_on_exit_args\".\nDefinition __p : ident := $\"_p\".\nDefinition __p5s : ident := $\"_p5s\".\nDefinition __r : ident := $\"_r\".\nDefinition __r48 : ident := $\"_r48\".\nDefinition __rand48 : ident := $\"_rand48\".\nDefinition __rand_next : ident := $\"_rand_next\".\nDefinition __read : ident := $\"_read\".\nDefinition __reent : ident := $\"_reent\".\nDefinition __result : ident := $\"_result\".\nDefinition __result_k : ident := $\"_result_k\".\nDefinition __seed : ident := $\"_seed\".\nDefinition __seek : ident := $\"_seek\".\nDefinition __seek64 : ident := $\"_seek64\".\nDefinition __sig_func : ident := $\"_sig_func\".\nDefinition __sign : ident := $\"_sign\".\nDefinition __signal_buf : ident := $\"_signal_buf\".\nDefinition __size : ident := $\"_size\".\nDefinition __stderr : ident := $\"_stderr\".\nDefinition __stdin : ident := $\"_stdin\".\nDefinition __stdout : ident := $\"_stdout\".\nDefinition __strtok_last : ident := $\"_strtok_last\".\nDefinition __ub : ident := $\"_ub\".\nDefinition __ubuf : ident := $\"_ubuf\".\nDefinition __unspecified_locale_info : ident := $\"_unspecified_locale_info\".\nDefinition __unused : ident := $\"_unused\".\nDefinition __unused_rand : ident := $\"_unused_rand\".\nDefinition __up : ident := $\"_up\".\nDefinition __ur : ident := $\"_ur\".\nDefinition __w : ident := $\"_w\".\nDefinition __wcrtomb_state : ident := $\"_wcrtomb_state\".\nDefinition __wcsrtombs_state : ident := $\"_wcsrtombs_state\".\nDefinition __wctomb_state : ident := $\"_wctomb_state\".\nDefinition __wds : ident := $\"_wds\".\nDefinition __write : ident := $\"_write\".\nDefinition __x : ident := $\"_x\".\nDefinition _acquire : ident := $\"acquire\".\nDefinition _argc : ident := $\"argc\".\nDefinition _argv : ident := $\"argv\".\nDefinition _atoi : ident := $\"atoi\".\nDefinition _atom_int : ident := $\"atom_int\".\nDefinition _closure : ident := $\"closure\".\nDefinition _d : ident := $\"d\".\nDefinition _delta : ident := $\"delta\".\nDefinition _delta_next : ident := $\"delta_next\".\nDefinition _delta_next__1 : ident := $\"delta_next__1\".\nDefinition _do_tasks : ident := $\"do_tasks\".\nDefinition _dotprod : ident := $\"dotprod\".\nDefinition _dotprod_task : ident := $\"dotprod_task\".\nDefinition _dotprod_worker : ident := $\"dotprod_worker\".\nDefinition _dtasks : ident := $\"dtasks\".\nDefinition _exit : ident := $\"exit\".\nDefinition _fprintf : ident := $\"fprintf\".\nDefinition _freelock : ident := $\"freelock\".\nDefinition _goal : ident := $\"goal\".\nDefinition _i : ident := $\"i\".\nDefinition _initialize_task : ident := $\"initialize_task\".\nDefinition _j : ident := $\"j\".\nDefinition _main : ident := $\"main\".\nDefinition _make_dotprod_tasks : ident := $\"make_dotprod_tasks\".\nDefinition _make_tasks : ident := $\"make_tasks\".\nDefinition _makelock : ident := $\"makelock\".\nDefinition _malloc : ident := $\"malloc\".\nDefinition _n : ident := $\"n\".\nDefinition _num_threads : ident := $\"num_threads\".\nDefinition _placeholder : ident := $\"placeholder\".\nDefinition _printf : ident := $\"printf\".\nDefinition _release : ident := $\"release\".\nDefinition _result : ident := $\"result\".\nDefinition _spawn : ident := $\"spawn\".\nDefinition _t : ident := $\"t\".\nDefinition _task : ident := $\"task\".\nDefinition _tasks : ident := $\"tasks\".\nDefinition _test : ident := $\"test\".\nDefinition _tp : ident := $\"tp\".\nDefinition _vec1 : ident := $\"vec1\".\nDefinition _vec2 : ident := $\"vec2\".\nDefinition _w : ident := $\"w\".\nDefinition _t'1 : ident := 128%positive.\nDefinition _t'2 : ident := 129%positive.\nDefinition _t'3 : ident := 130%positive.\nDefinition _t'4 : ident := 131%positive.\nDefinition _t'5 : ident := 132%positive.\n\nDefinition v_tasks := {|\n  gvar_info := (tptr (Tstruct _task noattr));\n  gvar_init := (Init_space 4 :: nil);\n  gvar_readonly := false;\n  gvar_volatile := false\n|}.\n\nDefinition v_num_threads := {|\n  gvar_info := tuint;\n  gvar_init := (Init_space 4 :: nil);\n  gvar_readonly := false;\n  gvar_volatile := false\n|}.\n\nDefinition v_dtasks := {|\n  gvar_info := (tptr (Tstruct _dotprod_task noattr));\n  gvar_init := (Init_space 4 :: nil);\n  gvar_readonly := false;\n  gvar_volatile := false\n|}.\n\nDefinition f_dotprod_worker := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_closure, (tptr tvoid)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_w, (tptr (Tstruct _dotprod_task noattr))) ::\n               (_result, tdouble) :: (_n, tuint) ::\n               (_vec1, (tptr tdouble)) :: (_vec2, (tptr tdouble)) ::\n               (_i, tuint) :: (_t'2, tdouble) :: (_t'1, tdouble) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _w\n    (Ecast (Etempvar _closure (tptr tvoid))\n      (tptr (Tstruct _dotprod_task noattr))))\n  (Ssequence\n    (Sset _result (Econst_float (Float.of_bits (Int64.repr 0)) tdouble))\n    (Ssequence\n      (Sset _n\n        (Efield\n          (Ederef (Etempvar _w (tptr (Tstruct _dotprod_task noattr)))\n            (Tstruct _dotprod_task noattr)) _n tuint))\n      (Ssequence\n        (Sset _vec1\n          (Efield\n            (Ederef (Etempvar _w (tptr (Tstruct _dotprod_task noattr)))\n              (Tstruct _dotprod_task noattr)) _vec1 (tptr tdouble)))\n        (Ssequence\n          (Sset _vec2\n            (Efield\n              (Ederef (Etempvar _w (tptr (Tstruct _dotprod_task noattr)))\n                (Tstruct _dotprod_task noattr)) _vec2 (tptr tdouble)))\n          (Ssequence\n            (Ssequence\n              (Sset _i (Econst_int (Int.repr 0) tint))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                                 (Etempvar _n tuint) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Sset _t'1\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _vec1 (tptr tdouble))\n                          (Etempvar _i tuint) (tptr tdouble)) tdouble))\n                    (Ssequence\n                      (Sset _t'2\n                        (Ederef\n                          (Ebinop Oadd (Etempvar _vec2 (tptr tdouble))\n                            (Etempvar _i tuint) (tptr tdouble)) tdouble))\n                      (Sset _result\n                        (Ebinop Oadd (Etempvar _result tdouble)\n                          (Ebinop Omul (Etempvar _t'1 tdouble)\n                            (Etempvar _t'2 tdouble) tdouble) tdouble)))))\n                (Sset _i\n                  (Ebinop Oadd (Etempvar _i tuint)\n                    (Econst_int (Int.repr 1) tint) tuint))))\n            (Sassign\n              (Efield\n                (Ederef (Etempvar _w (tptr (Tstruct _dotprod_task noattr)))\n                  (Tstruct _dotprod_task noattr)) _result tdouble)\n              (Etempvar _result tdouble))))))))\n|}.\n\nDefinition f_dotprod := {|\n  fn_return := tdouble;\n  fn_callconv := cc_default;\n  fn_params := ((_vec1, (tptr tdouble)) :: (_vec2, (tptr tdouble)) ::\n                (_n, tuint) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_result, tdouble) :: (_T, tuint) :: (_t, tuint) ::\n               (_delta, tuint) :: (_delta_next, tuint) ::\n               (_tp, (tptr (Tstruct _dotprod_task noattr))) ::\n               (_delta_next__1, tuint) ::\n               (_t'4, (tptr (Tstruct _dotprod_task noattr))) ::\n               (_t'3, (tptr (Tstruct _task noattr))) :: (_t'2, tdouble) ::\n               (_t'1, (tptr (Tstruct _dotprod_task noattr))) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _T (Evar _num_threads tuint))\n  (Ssequence\n    (Sset _delta (Econst_int (Int.repr 0) tint))\n    (Ssequence\n      (Ssequence\n        (Sset _t (Econst_int (Int.repr 0) tint))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _t tuint) (Etempvar _T tuint)\n                           tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Ssequence\n                (Sset _t'4\n                  (Evar _dtasks (tptr (Tstruct _dotprod_task noattr))))\n                (Sset _tp\n                  (Ebinop Oadd\n                    (Etempvar _t'4 (tptr (Tstruct _dotprod_task noattr)))\n                    (Etempvar _t tuint)\n                    (tptr (Tstruct _dotprod_task noattr)))))\n              (Ssequence\n                (Sassign\n                  (Efield\n                    (Ederef\n                      (Etempvar _tp (tptr (Tstruct _dotprod_task noattr)))\n                      (Tstruct _dotprod_task noattr)) _vec1 (tptr tdouble))\n                  (Ebinop Oadd (Etempvar _vec1 (tptr tdouble))\n                    (Etempvar _delta tuint) (tptr tdouble)))\n                (Ssequence\n                  (Sassign\n                    (Efield\n                      (Ederef\n                        (Etempvar _tp (tptr (Tstruct _dotprod_task noattr)))\n                        (Tstruct _dotprod_task noattr)) _vec2 (tptr tdouble))\n                    (Ebinop Oadd (Etempvar _vec2 (tptr tdouble))\n                      (Etempvar _delta tuint) (tptr tdouble)))\n                  (Ssequence\n                    (Sset _delta_next__1\n                      (Ecast\n                        (Ebinop Odiv\n                          (Ebinop Omul\n                            (Ecast\n                              (Ebinop Oadd (Etempvar _t tuint)\n                                (Econst_int (Int.repr 1) tint) tuint) tulong)\n                            (Ecast (Etempvar _n tuint) tulong) tulong)\n                          (Ecast (Etempvar _T tuint) tulong) tulong) tuint))\n                    (Ssequence\n                      (Sassign\n                        (Efield\n                          (Ederef\n                            (Etempvar _tp (tptr (Tstruct _dotprod_task noattr)))\n                            (Tstruct _dotprod_task noattr)) _n tuint)\n                        (Ebinop Osub (Etempvar _delta_next__1 tuint)\n                          (Etempvar _delta tuint) tuint))\n                      (Sset _delta (Etempvar _delta_next__1 tuint))))))))\n          (Sset _t\n            (Ebinop Oadd (Etempvar _t tuint) (Econst_int (Int.repr 1) tint)\n              tuint))))\n      (Ssequence\n        (Ssequence\n          (Sset _t'3 (Evar _tasks (tptr (Tstruct _task noattr))))\n          (Scall None\n            (Evar _do_tasks (Tfunction\n                              (Tcons (tptr (Tstruct _task noattr))\n                                (Tcons tuint Tnil)) tvoid cc_default))\n            ((Etempvar _t'3 (tptr (Tstruct _task noattr))) ::\n             (Etempvar _T tuint) :: nil)))\n        (Ssequence\n          (Sset _result\n            (Econst_float (Float.of_bits (Int64.repr 0)) tdouble))\n          (Ssequence\n            (Ssequence\n              (Sset _t (Econst_int (Int.repr 0) tint))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _t tuint)\n                                 (Etempvar _T tuint) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Sset _t'1\n                      (Evar _dtasks (tptr (Tstruct _dotprod_task noattr))))\n                    (Ssequence\n                      (Sset _t'2\n                        (Efield\n                          (Ederef\n                            (Ebinop Oadd\n                              (Etempvar _t'1 (tptr (Tstruct _dotprod_task noattr)))\n                              (Etempvar _t tuint)\n                              (tptr (Tstruct _dotprod_task noattr)))\n                            (Tstruct _dotprod_task noattr)) _result tdouble))\n                      (Sset _result\n                        (Ebinop Oadd (Etempvar _result tdouble)\n                          (Etempvar _t'2 tdouble) tdouble)))))\n                (Sset _t\n                  (Ebinop Oadd (Etempvar _t tuint)\n                    (Econst_int (Int.repr 1) tint) tuint))))\n            (Sreturn (Some (Etempvar _result tdouble)))))))))\n|}.\n\nDefinition f_make_dotprod_tasks := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_T, tuint) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t, tuint) :: (_t'2, (tptr tvoid)) ::\n               (_t'1, (tptr (Tstruct _task noattr))) ::\n               (_t'5, (tptr (Tstruct _dotprod_task noattr))) ::\n               (_t'4, (tptr (Tstruct _dotprod_task noattr))) ::\n               (_t'3, (tptr (Tstruct _task noattr))) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _make_tasks (Tfunction (Tcons tuint Tnil)\n                          (tptr (Tstruct _task noattr)) cc_default))\n      ((Etempvar _T tuint) :: nil))\n    (Sassign (Evar _tasks (tptr (Tstruct _task noattr)))\n      (Etempvar _t'1 (tptr (Tstruct _task noattr)))))\n  (Ssequence\n    (Sassign (Evar _num_threads tuint) (Etempvar _T tuint))\n    (Ssequence\n      (Ssequence\n        (Scall (Some _t'2)\n          (Evar _malloc (Tfunction (Tcons tuint Tnil) (tptr tvoid)\n                          cc_default))\n          ((Ebinop Omul (Etempvar _T tuint)\n             (Esizeof (Tstruct _dotprod_task noattr) tuint) tuint) :: nil))\n        (Sassign (Evar _dtasks (tptr (Tstruct _dotprod_task noattr)))\n          (Ecast (Etempvar _t'2 (tptr tvoid))\n            (tptr (Tstruct _dotprod_task noattr)))))\n      (Ssequence\n        (Ssequence\n          (Sset _t'5 (Evar _dtasks (tptr (Tstruct _dotprod_task noattr))))\n          (Sifthenelse (Eunop Onotbool\n                         (Etempvar _t'5 (tptr (Tstruct _dotprod_task noattr)))\n                         tint)\n            (Scall None\n              (Evar _exit (Tfunction (Tcons tint Tnil) tvoid cc_default))\n              ((Econst_int (Int.repr 1) tint) :: nil))\n            Sskip))\n        (Ssequence\n          (Sset _t (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _t tuint)\n                             (Etempvar _T tuint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'3 (Evar _tasks (tptr (Tstruct _task noattr))))\n                (Ssequence\n                  (Sset _t'4\n                    (Evar _dtasks (tptr (Tstruct _dotprod_task noattr))))\n                  (Scall None\n                    (Evar _initialize_task (Tfunction\n                                             (Tcons\n                                               (tptr (Tstruct _task noattr))\n                                               (Tcons tuint\n                                                 (Tcons\n                                                   (tptr (Tfunction\n                                                           (Tcons\n                                                             (tptr tvoid)\n                                                             Tnil) tvoid\n                                                           cc_default))\n                                                   (Tcons (tptr tvoid) Tnil))))\n                                             tvoid cc_default))\n                    ((Etempvar _t'3 (tptr (Tstruct _task noattr))) ::\n                     (Etempvar _t tuint) ::\n                     (Evar _dotprod_worker (Tfunction\n                                             (Tcons (tptr tvoid) Tnil) tvoid\n                                             cc_default)) ::\n                     (Ebinop Oadd\n                       (Etempvar _t'4 (tptr (Tstruct _dotprod_task noattr)))\n                       (Etempvar _t tuint)\n                       (tptr (Tstruct _dotprod_task noattr))) :: nil)))))\n            (Sset _t\n              (Ebinop Oadd (Etempvar _t tuint) (Econst_int (Int.repr 1) tint)\n                tuint))))))))\n|}.\n\nDefinition composites : list composite_definition :=\n(Composite _dotprod_task Struct\n   (Member_plain _vec1 (tptr tdouble) :: Member_plain _vec2 (tptr tdouble) ::\n    Member_plain _n tuint :: Member_plain _result tdouble :: nil)\n   noattr :: nil).\n\nDefinition global_definitions : list (ident * globdef fundef type) :=\n((___compcert_va_int32,\n   Gfun(External (EF_runtime \"__compcert_va_int32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tvoid) Tnil) tuint cc_default)) ::\n (___compcert_va_int64,\n   Gfun(External (EF_runtime \"__compcert_va_int64\"\n                   (mksignature (AST.Tint :: nil) AST.Tlong cc_default))\n     (Tcons (tptr tvoid) Tnil) tulong cc_default)) ::\n (___compcert_va_float64,\n   Gfun(External (EF_runtime \"__compcert_va_float64\"\n                   (mksignature (AST.Tint :: nil) AST.Tfloat cc_default))\n     (Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::\n (___compcert_va_composite,\n   Gfun(External (EF_runtime \"__compcert_va_composite\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     (tptr tvoid) cc_default)) ::\n (___compcert_i64_dtos,\n   Gfun(External (EF_runtime \"__compcert_i64_dtos\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tlong cc_default)) ::\n (___compcert_i64_dtou,\n   Gfun(External (EF_runtime \"__compcert_i64_dtou\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tulong cc_default)) ::\n (___compcert_i64_stod,\n   Gfun(External (EF_runtime \"__compcert_i64_stod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tlong Tnil) tdouble cc_default)) ::\n (___compcert_i64_utod,\n   Gfun(External (EF_runtime \"__compcert_i64_utod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tulong Tnil) tdouble cc_default)) ::\n (___compcert_i64_stof,\n   Gfun(External (EF_runtime \"__compcert_i64_stof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tlong Tnil) tfloat cc_default)) ::\n (___compcert_i64_utof,\n   Gfun(External (EF_runtime \"__compcert_i64_utof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tulong Tnil) tfloat cc_default)) ::\n (___compcert_i64_sdiv,\n   Gfun(External (EF_runtime \"__compcert_i64_sdiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_udiv,\n   Gfun(External (EF_runtime \"__compcert_i64_udiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_smod,\n   Gfun(External (EF_runtime \"__compcert_i64_smod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umod,\n   Gfun(External (EF_runtime \"__compcert_i64_umod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_shl,\n   Gfun(External (EF_runtime \"__compcert_i64_shl\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_shr,\n   Gfun(External (EF_runtime \"__compcert_i64_shr\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_sar,\n   Gfun(External (EF_runtime \"__compcert_i64_sar\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_smulh,\n   Gfun(External (EF_runtime \"__compcert_i64_smulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umulh,\n   Gfun(External (EF_runtime \"__compcert_i64_umulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___builtin_bswap64,\n   Gfun(External (EF_builtin \"__builtin_bswap64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) tulong cc_default)) ::\n (___builtin_bswap,\n   Gfun(External (EF_builtin \"__builtin_bswap\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap32,\n   Gfun(External (EF_builtin \"__builtin_bswap32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap16,\n   Gfun(External (EF_builtin \"__builtin_bswap16\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::\n (___builtin_clz,\n   Gfun(External (EF_builtin \"__builtin_clz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzl,\n   Gfun(External (EF_builtin \"__builtin_clzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzll,\n   Gfun(External (EF_builtin \"__builtin_clzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctz,\n   Gfun(External (EF_builtin \"__builtin_ctz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzl,\n   Gfun(External (EF_builtin \"__builtin_ctzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzll,\n   Gfun(External (EF_builtin \"__builtin_ctzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_fabs,\n   Gfun(External (EF_builtin \"__builtin_fabs\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_fabsf,\n   Gfun(External (EF_builtin \"__builtin_fabsf\"\n                   (mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))\n     (Tcons tfloat Tnil) tfloat cc_default)) ::\n (___builtin_fsqrt,\n   Gfun(External (EF_builtin \"__builtin_fsqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_sqrt,\n   Gfun(External (EF_builtin \"__builtin_sqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_memcpy_aligned,\n   Gfun(External (EF_builtin \"__builtin_memcpy_aligned\"\n                   (mksignature\n                     (AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr tvoid)\n       (Tcons (tptr tvoid) (Tcons tuint (Tcons tuint Tnil)))) tvoid\n     cc_default)) ::\n (___builtin_sel,\n   Gfun(External (EF_builtin \"__builtin_sel\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tbool Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot,\n   Gfun(External (EF_builtin \"__builtin_annot\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot_intval,\n   Gfun(External (EF_builtin \"__builtin_annot_intval\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))\n     tint cc_default)) ::\n (___builtin_membar,\n   Gfun(External (EF_builtin \"__builtin_membar\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_va_start,\n   Gfun(External (EF_builtin \"__builtin_va_start\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_va_arg,\n   Gfun(External (EF_builtin \"__builtin_va_arg\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_va_copy,\n   Gfun(External (EF_builtin \"__builtin_va_copy\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::\n (___builtin_va_end,\n   Gfun(External (EF_builtin \"__builtin_va_end\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_unreachable,\n   Gfun(External (EF_builtin \"__builtin_unreachable\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_expect,\n   Gfun(External (EF_builtin \"__builtin_expect\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons tint (Tcons tint Tnil)) tint\n     cc_default)) ::\n (___builtin_fmax,\n   Gfun(External (EF_builtin \"__builtin_fmax\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmin,\n   Gfun(External (EF_builtin \"__builtin_fmin\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmadd,\n   Gfun(External (EF_builtin \"__builtin_fmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fmsub,\n   Gfun(External (EF_builtin \"__builtin_fmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmadd,\n   Gfun(External (EF_builtin \"__builtin_fnmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmsub,\n   Gfun(External (EF_builtin \"__builtin_fnmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_read16_reversed,\n   Gfun(External (EF_builtin \"__builtin_read16_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons (tptr tushort) Tnil) tushort\n     cc_default)) ::\n (___builtin_read32_reversed,\n   Gfun(External (EF_builtin \"__builtin_read32_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tuint) Tnil) tuint cc_default)) ::\n (___builtin_write16_reversed,\n   Gfun(External (EF_builtin \"__builtin_write16_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))\n     tvoid cc_default)) ::\n (___builtin_write32_reversed,\n   Gfun(External (EF_builtin \"__builtin_write32_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_debug,\n   Gfun(External (EF_external \"__builtin_debug\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tint Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (_exit,\n   Gfun(External (EF_external \"exit\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons tint Tnil) tvoid cc_default)) ::\n (_malloc,\n   Gfun(External EF_malloc (Tcons tuint Tnil) (tptr tvoid) cc_default)) ::\n (_make_tasks,\n   Gfun(External (EF_external \"make_tasks\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) (tptr (Tstruct _task noattr)) cc_default)) ::\n (_initialize_task,\n   Gfun(External (EF_external \"initialize_task\"\n                   (mksignature\n                     (AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr (Tstruct _task noattr))\n       (Tcons tuint\n         (Tcons (tptr (Tfunction (Tcons (tptr tvoid) Tnil) tvoid cc_default))\n           (Tcons (tptr tvoid) Tnil)))) tvoid cc_default)) ::\n (_do_tasks,\n   Gfun(External (EF_external \"do_tasks\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr (Tstruct _task noattr)) (Tcons tuint Tnil)) tvoid\n     cc_default)) :: (_tasks, Gvar v_tasks) ::\n (_num_threads, Gvar v_num_threads) :: (_dtasks, Gvar v_dtasks) ::\n (_dotprod_worker, Gfun(Internal f_dotprod_worker)) ::\n (_dotprod, Gfun(Internal f_dotprod)) ::\n (_make_dotprod_tasks, Gfun(Internal f_make_dotprod_tasks)) :: nil).\n\nDefinition public_idents : list ident :=\n(_make_dotprod_tasks :: _dotprod :: _dotprod_worker :: _dtasks ::\n _num_threads :: _tasks :: _do_tasks :: _initialize_task :: _make_tasks ::\n _malloc :: _exit :: ___builtin_debug :: ___builtin_write32_reversed ::\n ___builtin_write16_reversed :: ___builtin_read32_reversed ::\n ___builtin_read16_reversed :: ___builtin_fnmsub :: ___builtin_fnmadd ::\n ___builtin_fmsub :: ___builtin_fmadd :: ___builtin_fmin ::\n ___builtin_fmax :: ___builtin_expect :: ___builtin_unreachable ::\n ___builtin_va_end :: ___builtin_va_copy :: ___builtin_va_arg ::\n ___builtin_va_start :: ___builtin_membar :: ___builtin_annot_intval ::\n ___builtin_annot :: ___builtin_sel :: ___builtin_memcpy_aligned ::\n ___builtin_sqrt :: ___builtin_fsqrt :: ___builtin_fabsf ::\n ___builtin_fabs :: ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz ::\n ___builtin_clzll :: ___builtin_clzl :: ___builtin_clz ::\n ___builtin_bswap16 :: ___builtin_bswap32 :: ___builtin_bswap ::\n ___builtin_bswap64 :: ___compcert_i64_umulh :: ___compcert_i64_smulh ::\n ___compcert_i64_sar :: ___compcert_i64_shr :: ___compcert_i64_shl ::\n ___compcert_i64_umod :: ___compcert_i64_smod :: ___compcert_i64_udiv ::\n ___compcert_i64_sdiv :: ___compcert_i64_utof :: ___compcert_i64_stof ::\n ___compcert_i64_utod :: ___compcert_i64_stod :: ___compcert_i64_dtou ::\n ___compcert_i64_dtos :: ___compcert_va_composite ::\n ___compcert_va_float64 :: ___compcert_va_int64 :: ___compcert_va_int32 ::\n nil).\n\nDefinition prog : Clight.program := \n  mkprogram composites global_definitions public_idents _main Logic.I.\n\n\n", "meta": {"author": "VeriNum", "repo": "pardotprod", "sha": "5c8febd4e35a878a1824cedacd9cfc7d63610fb6", "save_path": "github-repos/coq/VeriNum-pardotprod", "path": "github-repos/coq/VeriNum-pardotprod/pardotprod-5c8febd4e35a878a1824cedacd9cfc7d63610fb6/dotprod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.19233999260145246}}
{"text": "(** * Definition of a boolean-returning CFG parser-recognizer *)\nRequire Import Coq.Lists.List Coq.Strings.String.\nRequire Import Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Compare_dec Coq.Arith.Wf_nat.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.List.ListMorphisms.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Common Fiat.Common.Wf Fiat.Common.Wf2 Fiat.Common.Telescope.Core.\nRequire Import Fiat.Parsers.BooleanRecognizer.\nRequire Import Fiat.Parsers.BooleanRecognizerExt.\nRequire Import Fiat.Parsers.BooleanRecognizerCorrect.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.BooleanRecognizerPreOptimized.\nRequire Import Fiat.Common.Match.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\nRequire Export Fiat.Common.SetoidInstances.\nRequire Export Fiat.Common.List.ListMorphisms.\nRequire Export Fiat.Common.OptionFacts.\nRequire Export Fiat.Common.BoolFacts.\nRequire Export Fiat.Common.NatFacts.\nRequire Export Fiat.Common.Sigma.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nGlobal Arguments string_dec : simpl never.\nGlobal Arguments string_beq : simpl never.\n\nModule Export opt.\n  Module Import opt.\n    Definition first_index_default {A} := Eval compute in @Operations.List.first_index_default A.\n    Definition map {A B} := Eval compute in @List.map A B.\n    Definition length {A} := Eval compute in @List.length A.\n    Definition uniquize {A} := Eval compute in @Operations.List.uniquize A.\n    Definition string_beq := Eval compute in Equality.string_beq.\n    Definition option_rect {A} := Eval compute in @option_rect A.\n    Definition up_to := Eval compute in Operations.List.up_to.\n    Definition rev {A} := Eval compute in @List.rev A.\n    Definition combine {A B} := Eval compute in @List.combine A B.\n    Definition fold_left {A B} := Eval compute in @List.fold_left A B.\n    Definition fold_right {A B} := Eval compute in @List.fold_right A B.\n    Definition list_rect {A} := Eval compute in @list_rect A.\n    Definition hd {A} := Eval compute in @hd A.\n    Definition tl {A} := Eval compute in @tl A.\n    Definition nth {A} := Eval compute in @nth A.\n    Definition nth' {A} := Eval cbv beta iota zeta delta -[EqNat.beq_nat] in @nth' A.\n    Definition fst {A B} := Eval compute in @fst A B.\n    Definition snd {A B} := Eval compute in @snd A B.\n    Definition list_caset {A} := Eval compute in @list_caset A.\n    Definition item_rect {A} := Eval compute in @item_rect A.\n    Definition bool_rect := Eval compute in bool_rect.\n    Definition pred := Eval compute in pred.\n    Definition minusr := Eval compute in minusr.\n    Definition id {A} := Eval compute in @id A.\n    Definition beq_nat := Eval compute in EqNat.beq_nat.\n    Definition leb := Eval compute in leb.\n  End opt.\n\n  Declare Reduction opt_red := cbv beta iota zeta delta [first_index_default map length uniquize string_beq option_rect up_to rev combine fold_left fold_right list_rect hd tl Common.opt.fst Common.opt.snd nth nth' fst snd list_caset item_rect bool_rect pred minusr id beq_nat leb].\n  Ltac opt_red x := eval opt_red in x.\nEnd opt.\n\nModule Export opt2.\n  Module Import opt2.\n    Definition first_index_default {A} := Eval compute in @Operations.List.first_index_default A.\n    Definition map {A B} := Eval compute in @List.map A B.\n    Definition length {A} := Eval compute in @List.length A.\n    Definition uniquize {A} := Eval compute in @Operations.List.uniquize A.\n    Definition string_beq := Eval compute in Equality.string_beq.\n    Definition option_rect {A} := Eval compute in @option_rect A.\n    Definition up_to := Eval compute in Operations.List.up_to.\n    Definition rev {A} := Eval compute in @List.rev A.\n    Definition combine {A B} := Eval compute in @List.combine A B.\n    Definition fold_left {A B} := Eval compute in @List.fold_left A B.\n    Definition fold_right {A B} := Eval compute in @List.fold_right A B.\n    Definition list_rect {A} := Eval compute in @list_rect A.\n    Definition hd {A} := Eval compute in @hd A.\n    Definition tl {A} := Eval compute in @tl A.\n    Definition nth {A} := Eval compute in @nth A.\n    Definition nth' {A} := Eval cbv beta iota zeta delta -[EqNat.beq_nat] in @nth' A.\n    Definition fst {A B} := Eval compute in @fst A B.\n    Definition snd {A B} := Eval compute in @snd A B.\n    Definition list_caset {A} := Eval compute in @list_caset A.\n    Definition item_rect {A} := Eval compute in @item_rect A.\n    Definition bool_rect := Eval compute in bool_rect.\n    Definition pred := Eval compute in pred.\n    Definition minusr := Eval compute in minusr.\n    Definition id {A} := Eval compute in @id A.\n    Definition beq_nat := Eval compute in EqNat.beq_nat.\n    Definition leb := Eval compute in leb.\n  End opt2.\n\n  Declare Reduction opt2_red := cbv beta iota zeta delta [first_index_default map length uniquize string_beq option_rect up_to rev combine fold_left fold_right list_rect hd tl Common.opt.fst Common.opt.snd nth nth' fst snd list_caset item_rect bool_rect pred minusr id beq_nat leb].\n  Ltac opt2_red x := eval opt2_red in x.\nEnd opt2.\n\nModule Export opt3.\n  Module Import opt3.\n    Definition first_index_default {A} := Eval compute in @Operations.List.first_index_default A.\n    Definition map {A B} := Eval compute in @List.map A B.\n    Definition length {A} := Eval compute in @List.length A.\n    Definition uniquize {A} := Eval compute in @Operations.List.uniquize A.\n    Definition string_beq := Eval compute in Equality.string_beq.\n    Definition option_rect {A} := Eval compute in @option_rect A.\n    Definition up_to := Eval compute in Operations.List.up_to.\n    Definition rev {A} := Eval compute in @List.rev A.\n    Definition combine {A B} := Eval compute in @List.combine A B.\n    Definition fold_left {A B} := Eval compute in @List.fold_left A B.\n    Definition fold_right {A B} := Eval compute in @List.fold_right A B.\n    Definition list_rect {A} := Eval compute in @list_rect A.\n    Definition hd {A} := Eval compute in @hd A.\n    Definition tl {A} := Eval compute in @tl A.\n    Definition nth {A} := Eval compute in @nth A.\n    Definition nth' {A} := Eval cbv beta iota zeta delta -[EqNat.beq_nat] in @nth' A.\n    Definition fst {A B} := Eval compute in @fst A B.\n    Definition snd {A B} := Eval compute in @snd A B.\n    Definition list_caset {A} := Eval compute in @list_caset A.\n    Definition item_rect {A} := Eval compute in @item_rect A.\n    Definition bool_rect := Eval compute in bool_rect.\n    Definition pred := Eval compute in pred.\n    Definition minusr := Eval compute in minusr.\n    Definition id {A} := Eval compute in @id A.\n    Definition beq_nat := Eval compute in EqNat.beq_nat.\n    Definition leb := Eval compute in leb.\n  End opt3.\n\n  Declare Reduction opt3_red := cbv beta iota zeta delta [first_index_default map length uniquize string_beq option_rect up_to rev combine fold_left fold_right list_rect hd tl Common.opt.fst Common.opt.snd nth nth' fst snd list_caset item_rect bool_rect pred minusr id beq_nat leb].\n  Ltac opt3_red x := eval opt3_red in x.\nEnd opt3.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}\n          {G : pregrammar Char}.\n\n  Let HNoDup' : NoDupR (fun x y => string_beq (fst x) (fst y)) (pregrammar_productions G).\n  Proof.\n    pose proof (nonterminals_unique G) as HNoDup.\n    hnf in HNoDup |- *; unfold pregrammar_nonterminals in *; simpl in *.\n    rewrite uniquize_map in HNoDup.\n    apply uniquize_length.\n    apply (f_equal (@List.length _)) in HNoDup.\n    rewrite !map_length, uniquize_length in HNoDup.\n    rewrite HNoDup; reflexivity.\n  Qed.\n\n  Context (Hvalid : is_true (grammar_rvalid G)).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Context {splitdata : @split_dataT Char _ _}.\n\n  Let data : boolean_parser_dataT :=\n    {| split_data := splitdata |}.\n  Let optdata : boolean_parser_dataT :=\n    {| split_data := optsplitdata |}.\n  Local Existing Instance data.\n\n  Let rdata' : @parser_removal_dataT' _ G predata := rdp_list_rdata'.\n  Local Existing Instance rdata'.\n\n  Local Arguments minus !_ !_.\n  Local Arguments min !_ !_.\n\n  Lemma parse_nonterminal_optdata_eq\n        {HSLP : StringLikeProperties Char}\n        {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}\n        (str : String)\n        (nt : String.string)\n    : parse_nonterminal (data := optdata) str nt = parse_nonterminal (data := data) str nt.\n  Proof.\n    pose optsplitdata_correct.\n    match goal with\n    | [ |- ?LHS = ?RHS ]\n      => destruct LHS eqn:HL;\n        destruct RHS eqn:HR\n    end;\n    try reflexivity;\n    exfalso;\n    first [ apply (@parse_nonterminal_sound _ _ _ _ G) in HR\n          | apply (@parse_nonterminal_sound _ _ _ _ G) in HL ];\n    try eassumption; [ | ];\n    try (apply grammar_rvalid_correct; eassumption);\n    [ | ];\n    first [ erewrite @parse_nonterminal_complete in HR; [ congruence | .. ]\n          | erewrite @parse_nonterminal_complete in HL; [ congruence | .. ] ];\n    instantiate;\n    try first [ eassumption\n              | apply grammar_rvalid_correct; eassumption\n              | exact _ ].\n  Defined.\n\n  Local Ltac contract_drop_take_t' :=\n    idtac;\n    match goal with\n      | [ |- context[drop_takes_offset ?ls ?offset + ?v] ]\n        => change (drop_takes_offset ls offset + v) with (drop_takes_offset (drop_of v :: ls) offset)\n      | [ |- context[drop_takes_len ?ls ?len - ?v] ]\n        => change (drop_takes_len ls len - v) with (drop_takes_len (drop_of v :: ls) len)\n    end.\n\n  Local Ltac contract_drop_take_t :=\n    idtac;\n    match goal with\n      | [ H : is_true (bool_eq ?x ?y) |- _ ] => change (beq x y) in H\n      | [ H : context[is_true (bool_eq ?x ?y)] |- _ ] => change (is_true (bool_eq x y)) with (beq x y) in H\n      | [ |- context[is_true (bool_eq ?x ?y)] ] => change (is_true (bool_eq x y)) with (beq x y)\n      | _ => progress subst\n      | [ H : beq _ _ |- _ ] => rewrite !H; clear H\n      | [ |- _ = _ ] => reflexivity\n      | [ |- beq _ _ ] => reflexivity\n      | [ |- Equivalence _ ] => split; repeat intro\n    end.\n\n  Local Arguments drop_takes_offset : simpl never.\n  Local Arguments drop_takes_len : simpl never.\n  Local Arguments drop_takes_len_pf : simpl never.\n\n  Local Ltac t_reduce_fix :=\n    repeat match goal with\n             | _ => progress simpl sumbool_rect\n             | _ => progress simpl option_rect\n             | [ |- context[lt_dec ?x ?y] ]\n               => destruct (lt_dec x y)\n             | [ |- context[dec ?x] ]\n               => destruct (dec x)\n             | [ |- @fold_right ?A ?B ?f ?x ?ls = @fold_right ?A ?B ?f ?x ?ls' ]\n               => apply (_ : Proper (_ ==> _ ==> _ ==> eq) (@fold_right A B))\n             | [ |- @fold_left ?A ?B ?f ?ls ?x = @fold_left ?A ?B ?f ?ls' ?x ]\n               => apply (_ : Proper (_ ==> _ ==> _ ==> eq) (@fold_left A B))\n             | [ |- @list_caset ?A (fun _ => ?P) _ _ ?ls = @list_caset ?A (fun _ => ?P) _ _ ?ls' ]\n               => apply (_ : Proper (_ ==> pointwise_relation _ (pointwise_relation _ _) ==> _ ==> eq) (@list_caset A (fun _ => P)))\n             | [ |- @map ?A ?B ?f ?ls = @map ?A ?B ?f' ?ls' ]\n               => apply (_ : Proper (pointwise_relation _ _ ==> _ ==> eq) (@map A B))\n             | [ |- @nth' ?A ?n ?ls ?d = @nth' ?A ?n' ?ls' ?d' ]\n               => apply f_equal3\n             | [ |- @nth ?A ?n ?ls ?d = @nth ?A ?n' ?ls' ?d' ]\n               => apply f_equal3\n             | _ => intro\n             | [ |- ?x = ?x ] => reflexivity\n             | [ |- bool_rect ?P _ _ ?b = bool_rect ?P _ _ ?b ] => apply f_equal3\n             | [ |- andb _ _ = andb _ _ ] => apply f_equal2\n             | [ |- andbr _ _ = andbr _ _ ] => apply f_equal2\n             | [ |- orb _ _ = orb _ _ ] => apply f_equal2\n             | [ |- match ?it with Terminal _ => _ | _ => _ end = match ?it with _ => _ end ] => is_var it; destruct it\n             | [ |- context[(fst ?x, snd ?x)] ] => rewrite <- !surjective_pairing\n             | [ |- context[andb _ true] ] => rewrite Bool.andb_true_r\n             | [ |- context[andb true _] ] => rewrite Bool.andb_true_l\n             | [ |- context[andb _ false] ] => rewrite Bool.andb_false_r\n             | [ |- context[andb false _] ] => rewrite Bool.andb_false_l\n             | [ |- context[andb ?x true] ] => rewrite (andbr_andb x true)\n             | [ |- context[andb true _] ] => rewrite (andbr_andb true)\n             | [ |- context[andb ?x false] ] => rewrite (andbr_andb x false)\n             | [ |- context[andbr false _] ] => rewrite (andbr_andb false)\n             | [ |- context[orb _ true] ] => rewrite Bool.orb_true_r\n             | [ |- context[orb true _] ] => rewrite Bool.orb_true_l\n             | [ |- context[orb _ false] ] => rewrite Bool.orb_false_r\n             | [ |- context[orb false _] ] => rewrite Bool.orb_false_l\n             | [ |- cons _ _ = cons _ _ ]\n               => apply f_equal2\n             (*| _ => contract_drop_take_t'\n             | _ => rewrite make_drops_eta\n             | _ => rewrite make_drops_eta'\n             | _ => rewrite make_drops_eta''*)\n             (*| [ |- context[to_string (of_string _)] ] => rewrite !to_of*)\n             | _ => contract_drop_take_t'\n             | _ => solve [ auto with nocore ]\n             | [ |- prod_relation lt lt _ _ ] => hnf; simpl; omega\n             | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n             | [ H : _ = in_left |- _ ] => clear H\n             | [ H : _ /\\ _ |- _ ] => destruct H\n             | [ H : context[negb (EqNat.beq_nat ?x ?y)] |- _ ] => destruct (EqNat.beq_nat x y) eqn:?\n             | [ H : EqNat.beq_nat _ _ = false |- _ ] => apply EqNat.beq_nat_false in H\n             | [ H : EqNat.beq_nat _ _ = true |- _ ] => apply EqNat.beq_nat_true in H\n             | [ H : snd ?x = _ |- _ ] => is_var x; destruct x\n             | _ => progress simpl negb in *\n             | [ H : false = true |- _ ] => inversion H\n             | [ |- ?f _ (match ?p with eq_refl => ?k end) = ?f' _ ?k ]\n               => destruct p\n             | [ |- match ?ls with nil => _ | _ => _ end = match ?ls with _ => _ end ]\n               => destruct ls eqn:?\n             | [ |- match ?ls with NonTerminal _ => _ | _ => _ end = match ?ls with _ => _ end ]\n               => destruct ls eqn:?\n             | [ |- (if ?e then _ else _) = (if ?e then _ else _) ]\n               => destruct e eqn:?\n             | _ => solve [ intuition ]\n             | [ H : appcontext[sub_nonterminals_listT] |- _ ]\n               => solve [ apply H;\n                          intuition;\n                          (etransitivity; [ | eapply sub_nonterminals_listT_remove_2; eassumption ]); simpl;\n                          unfold remove_nonterminal; simpl;\n                          unfold rdp_list_remove_nonterminal;\n                          reflexivity ]\n           end.\n\n  Local Ltac t_reduce_list :=\n    idtac;\n    match goal with\n    | [ |- list_rect ?P ?n ?c ?ls ?idx ?offset ?len ?y = list_rect ?P' ?n' ?c' ?ls ?idx ?offset ?len ?y ]\n      => let n0 := fresh in\n         let c0 := fresh in\n         let n1 := fresh in\n         let c1 := fresh in\n         set (n0 := n);\n           set (n1 := n');\n           set (c0 := c);\n           set (c1 := c');\n           refine (list_rect\n                     (fun ls' => forall idx' l' y', list_rect P n0 c0 ls' idx' (drop_takes_offset l' offset) (drop_takes_len l' len) y' = list_rect P' n1 c1 ls' idx' (drop_takes_offset l' offset) (drop_takes_len l' len) y')\n                     _\n                     _\n                     ls\n                     idx\n                     nil y);\n           simpl list_rect;\n           [ subst n0 c0 n1 c1; cbv beta\n           | intros; unfold n0 at 1, c0 at 1, n1 at 1, c1 at 1 ]\n    end.\n\n  Local Ltac t_reduce_list_generalize :=\n    idtac;\n    match goal with\n      | [ |- list_rect ?P ?n ?c ?ls ?offset ?len ?y = list_rect ?P' ?n' ?c' ?ls ?offset ?len ?y ]\n        => let n0 := fresh in\n           let c0 := fresh in\n           let n1 := fresh in\n           let c1 := fresh in\n           set (n0 := n);\n             set (n1 := n');\n             set (c0 := c);\n             set (c1 := c');\n             refine (list_rect\n                       (fun ls' => forall offset' len' y', list_rect P n0 c0 ls' offset' len' y' = list_rect P' n1 c1 ls' offset' len' y')\n                       _\n                       _\n                       ls\n                       offset len y);\n             simpl list_rect;\n             [ subst n0 c0 n1 c1; cbv beta\n             | intros; unfold n0 at 1, c0 at 1, n1 at 1, c1 at 1 ]\n    end.\n\n  Local Ltac refine_Fix2_5_Proper_eq :=\n    idtac;\n    (lazymatch goal with\n    | [ |- context[_ = @Fix2 ?A ?A' ?R ?Rwf ?T (fun a0 b0 c0 d0 e0 h0 i0 => @?f a0 b0 c0 d0 e0 h0 i0) ?a ?a' ?b ?c ?d ?e ?h] ]\n      => (lazymatch T with\n         | (fun a' : ?A0 => forall (b' :@?B a') (c' : @?C a' b') (d' : @?D a' b' c') (e' : @?E a' b' c' d') (h' : @?H a' b' c' d' e'), @?P a' b' c' d' e' h')\n           => let H' := fresh in\n              (*refine (_ : @Fix A R Rwf T (fun a0 b0 c0 d0 e0 h0 i0 => _) a b c d e h = _);\n                 let f' := match goal with |- @Fix _ _ _ _ ?f' _ _ _ _ _ _ = _ => constr:(f') end in*)\n              pose proof ((fun f' H0 => @Fix2_5_Proper_eq A A' B C D E H R Rwf P f' f H0 a a' b c d e h)) as H';\n          cbv beta in H';\n          (lazymatch type of H' with\n          | forall f' : ?f'T, @?H'T f' -> _\n            => let H'' := fresh in\n               let f'' := fresh in\n               assert (H'' : { f' : f'T & H'T f' });\n           [ clear H'\n           | destruct H'' as [f'' H''];\n             specialize (H' f'' H'');\n             clear H''; eexists; exact H' ]\n           end)\n          end)\n     end);\n    unfold forall_relation, pointwise_relation, respectful;\n    cbv beta;\n    eexists (fun a0 a0' b0 c0 d0 e0 h0 i0 => _); intros.\n\n  Local Ltac refine_Fix2_5_Proper_eq_with_assumptions' HP HPpf :=\n    idtac;\n      (lazymatch goal with\n        | [ |- context[_ = @Fix2 ?A ?A' ?R ?Rwf ?T (fun a0 b0 c0 d0 e0 h0 i0 => @?f a0 b0 c0 d0 e0 h0 i0) ?a ?a' ?b ?c ?d ?e ?h] ]\n          => (lazymatch T with\n               | (fun a' : ?A0 => forall (b' :@?B a') (c' : @?C a' b') (d' : @?D a' b' c') (e' : @?E a' b' c' d') (h' : @?H a' b' c' d' e'), @?P a' b' c' d' e' h')\n                 => let H' := fresh in\n                    pose proof ((fun f' H0 => @Fix2_5_Proper_eq_with_assumption A A' B C D E H R Rwf P HP f' f H0 a a' b c d e h HPpf)) as H';\n                    cbv beta in H';\n                    (lazymatch type of H' with\n                      | forall f' : ?f'T, @?H'T f' -> _\n                        => let H'' := fresh in\n                           let f'' := fresh in\n                           assert (H'' : { f' : f'T & H'T f' });\n                           [ clear H'\n                           | destruct H'' as [f'' H''];\n                             specialize (H' f'' H'');\n                             clear H''; eexists; exact H' ]\n                      end)\n               end)\n        end);\n      unfold forall_relation, pointwise_relation, respectful;\n      cbv beta;\n      eexists (fun a0 a0' b0 c0 d0 e0 h0 i0 => _); intros.\n\n  Local Ltac refine_Fix2_5_Proper_eq_with_assumptions :=\n    idtac;\n    let HPHPpf := lazymatch goal with\n        | [ |- appcontext[Fix2 _ _ (fun (a0 : ?A0) (b0 :@?B a0) (c0 : @?C a0 b0) (d0 : @?D a0 b0) (e0 : @?E a0 b0 d0) (h0 : @?H a0 b0 d0 e0) (i0 : @?I a0 b0 d0 e0 h0) (j0 : @?J a0 b0 d0 e0 h0 i0) => _) ?a ?b ?d ?e ?h ?i ?j] ]\n          => let HP := constr:(fun a0 b0 d0 e0 h0 i0 (j0 : J a0 b0 d0 e0 h0 i0) => sub_nonterminals_listT d0 initial_nonterminals_data /\\ (a0 <= h0 \\/ is_valid_nonterminal initial_nonterminals_data j0)) in\n             let HPpfT := (eval cbv beta in (HP a b d e h i j)) in\n             let HPpf := constr:(fun pf => conj pf (or_introl (reflexivity _)) : HPpfT) in\n             (eval cbv beta in (HP, HPpf))\n        end in\n    let HP := match HPHPpf with (?HP, ?HPpf) => HP end in\n    let HPpf := match HPHPpf with (?HP, ?HPpf) => HPpf end in\n    let T := match type of HPpf with ?T -> _ => T end in\n    let H0 := fresh \"H\" in\n    assert (H0 : T)\n      by (simpl; unfold rdp_list_initial_nonterminals_data; rewrite map_length; reflexivity);\n    let HPpf := constr:(HPpf H0) in\n    refine_Fix2_5_Proper_eq_with_assumptions' HP HPpf.\n\n  Local Ltac fin_step_opt :=\n    repeat match goal with\n             | [ |- _ = true ] => reflexivity\n             | [ |- _ = false ] => reflexivity\n             | [ |- ?x = ?x ] => reflexivity\n             | [ |- _ = ?x ] => is_var x; reflexivity\n             | [ |- _ = (_::_) ] => apply (f_equal2 (@cons _))\n             | [ |- _ = nil ] => reflexivity\n             | [ |- _ = 0 ] => reflexivity\n             | [ |- _ = 1 ] => reflexivity\n             | [ |- _ = None ] => reflexivity\n             | [ |- _ = EqNat.beq_nat _ _ ] => apply f_equal2\n             | [ |- _ = leb _ _ ] => apply f_equal2\n             | [ |- _ = S _ ] => apply f_equal\n             | [ |- _ = string_beq _ _ ] => apply f_equal2\n             | [ |- _ = fst ?x ] => is_var x; reflexivity\n             | [ |- _ = snd ?x ] => is_var x; reflexivity\n             | [ |- _ = pregrammar_productions ?x ] => is_var x; reflexivity\n             | [ |- context[(0 - _)%natr] ] => rewrite (minusr_minus 0); simpl (minus 0)\n             | [ |- _ = (_, _) ] => apply f_equal2\n             | _ => progress cbv beta\n             | [ |- context[orb _ false] ] => rewrite Bool.orb_false_r\n             | [ |- context[orb _ true] ] => rewrite Bool.orb_true_r\n             | [ |- context[andbr _ false] ] => rewrite (andbr_andb _ false)\n             | [ |- context[andbr _ true] ] => rewrite (andbr_andb _ true)\n             | [ |- context[andb _ false] ] => rewrite Bool.andb_false_r\n             | [ |- context[andb _ true] ] => rewrite Bool.andb_true_r\n           end.\n\n  Local Ltac step_opt' :=\n    idtac;\n    match goal with\n      | _ => rewrite <- !minusr_minus\n      | [ |- _ = @option_rect ?A ?B (fun s => _) _ _ ]\n        => refine (_ : @option_rect A B (fun s => _) _ _ = _);\n          apply (_ : Proper (pointwise_relation _ _ ==> _ ==> _ ==> eq) (@option_rect A B));\n          repeat intro\n      | [ |- _ = @bool_rect ?A _ _ _ ]\n        => refine (_ : @bool_rect A _ _ _ = _);\n          apply (_ : Proper (_ ==> _ ==> _ ==> eq) (@bool_rect A));\n          repeat intro\n      | [ |- _ = fold_right orb false _ ]\n        => rewrite <- !(@fold_symmetric _ orb) by first [ apply Bool.orb_assoc | apply Bool.orb_comm ]\n      | [ |- _ = @fold_left ?A ?B orb _ false ]\n        => refine (_ : fold_left orb _ false = _);\n          apply (_ : Proper (_ ==> _ ==> _ ==> _) (@fold_left A B)); repeat intro\n      | [ |- _ = @fold_left ?A ?B orbr _ false ]\n        => refine (_ : fold_left orbr _ false = _);\n          apply (_ : Proper (_ ==> _ ==> _ ==> _) (@fold_left A B)); repeat intro\n      | [ |- _ = @fold_right ?A ?B (fun x y => _) _ _ ]\n        => refine (_ : fold_right (fun x y => _) _ _ = _);\n          apply (_ : Proper (_ ==> _ ==> _ ==> _) (@fold_right A B)); repeat intro\n      | [ |- _ = @map ?A ?B _ _ ]\n        => refine (_ : @map A B (fun x => _) _ = _);\n          apply (_ : Proper (pointwise_relation _ _ ==> _ ==> _) (@map A B)); repeat intro\n      | [ |- _ = @list_caset ?A ?P _ _ _ ]\n        => refine (_ : @list_caset A P _ _ _ = _);\n          apply (_ : Proper (forall_relation _ ==> forall_relation (fun _ => forall_relation _) ==> forall_relation _) (@list_caset A P)); repeat intro\n      | [ |- _ = @list_caset ?A (fun _ => ?P) _ _ _ ]\n        => refine (_ : @list_caset A (fun _ => P) _ _ _ = _);\n          apply (_ : Proper (_ ==> pointwise_relation _ (pointwise_relation _ _) ==> _ ==> _) (@list_caset A (fun _ => P))); repeat intro\n      | [ |- _ = @nth ?A _ _ _ ]\n        => rewrite <- nth'_nth\n      | [ |- _ = @nth' ?A _ _ _ ]\n        => refine (_ : @nth' A _ _ _ = _);\n          apply f_equal3\n      | [ |- _ = sumbool_rect ?T ?A ?B ?c ]\n        => let A' := fresh in\n           let B' := fresh in\n           let TA := type of A in\n           let TB := type of B in\n           evar (A' : TA); evar (B' : TB);\n           refine (sumbool_rect\n                     (fun c' => sumbool_rect T A' B' c' = sumbool_rect T A B c')\n                     _ _ c); intro; subst A' B'; simpl @sumbool_rect\n      | [ |- ?e = match ?ls with nil => _ | _ => _ end ]\n        => is_evar e; refine (_ : match ls with nil => _ | _ => _ end = _)\n      | [ |- match ?ls with nil => ?A | x::xs => @?B x xs end = match ?ls with nil => ?A' | x::xs => @?B' x xs end ]\n        => refine (match ls\n                         as ls'\n                         return match ls' with nil => A | x::xs => B x xs end = match ls' with nil => A' | x::xs => B' x xs end\n                   with\n                     | nil => _\n                     | _ => _\n                   end)\n      | [ |- _ = item_rect ?T ?A ?B ?c ] (* evar kludge following *)\n        => revert c;\n          let RHS := match goal with |- forall c', _ = ?RHS c' => RHS end in\n          let f := constr:(fun TC NC =>\n                             forall c, item_rect T TC NC c = RHS c) in\n          let f := (eval cbv beta in f) in\n          let e1 := fresh in\n          let e2 := fresh in\n          match type of f with\n            | ?X -> ?Y -> _\n              => evar (e1 : X); evar (e2 : Y)\n          end;\n            intro c;\n            let ty := constr:(item_rect T e1 e2 c = RHS c) in\n            etransitivity_rev _; [ refine (_ : ty) | reflexivity ];\n            revert c;\n            refine (item_rect\n                      (fun c => item_rect T e1 e2 c = RHS c)\n                      _ _);\n            intro c; simpl @item_rect; subst e1 e2\n    end;\n    fin_step_opt.\n\n  Local Ltac step_opt := repeat step_opt'.\n\n  Local Ltac sigL_transitivity term :=\n    idtac;\n    (lazymatch goal with\n    | [ |- ?sig (fun x : ?T => @?A x = ?B) ]\n      => (let H := fresh in\n          let H' := fresh in\n          assert (H : sig (fun x : T => A x = term));\n          [\n          | assert (H' : term = B);\n            [ clear H\n            | let x' := fresh in\n              destruct H as [x' H];\n                exists x'; transitivity term; [ exact H | exact H' ] ] ])\n     end).\n\n  Local Ltac fix_trans_helper RHS x y :=\n    match RHS with\n      | appcontext G[y] => let RHS' := context G[x] in\n                           fix_trans_helper RHS' x y\n      | _ => constr:(RHS)\n    end.\n\n  Local Ltac fix2_trans :=\n    match goal with\n      | [ H : forall a0 a0' a1 a2 a3 a4 a5 a6, ?x a0 a0' a1 a2 a3 a4 a5 a6 = ?y a0 a0' a1 a2 a3 a4 a5 a6 |- _ = ?RHS ]\n        => let RHS' := fix_trans_helper RHS x y\n           in transitivity RHS'; [ clear H y | ]\n    end.\n\n  Local Ltac fix2_trans_with_assumptions :=\n    match goal with\n      | [ H : forall a0 a0' a1 a2 a3 a4 a5 a6, _ -> ?x a0 a0' a1 a2 a3 a4 a5 a6 = ?y a0 a0' a1 a2 a3 a4 a5 a6 |- _ = ?RHS ]\n        => let RHS' := fix_trans_helper RHS x y\n           in transitivity RHS'; [ clear H y | ]\n    end.\n\n  Local Ltac t_prereduce_list_evar :=\n    idtac;\n    match goal with\n      | [ |- ?e = list_rect ?P (fun a b c d => _) (fun x xs H a b c d => _) ?ls ?A ?B ?C ?D ]\n        => refine (_ : list_rect P _ _ ls A B C D = _)\n    end.\n\n  Local Ltac t_postreduce_list :=\n    idtac;\n    match goal with\n      | [ |- list_rect ?P ?N ?C ?ls ?a ?b ?c ?d = list_rect ?P ?N' ?C' ?ls ?a ?b ?c ?d ]\n        => let P0 := fresh in\n           let N0 := fresh in\n           let C0 := fresh in\n           let N1 := fresh in\n           let C1 := fresh in\n           set (P0 := P);\n             set (N0 := N);\n             set (C0 := C);\n             set (N1 := N');\n             set (C1 := C');\n             let IH := fresh \"IH\" in\n             let xs := fresh \"xs\" in\n             refine (list_rect\n                       (fun ls' => forall a' b' c' d',\n                                     list_rect P0 N0 C0 ls' a' b' c' d'\n                                     = list_rect P0 N1 C1 ls' a' b' c' d')\n                       _\n                       _\n                       ls a b c d);\n               simpl @list_rect;\n               [ subst P0 N0 C0 N1 C1; intros; cbv beta\n               | intros ? xs IH; intros; unfold C0 at 1, C1 at 1; cbv beta;\n                 setoid_rewrite <- IH; clear IH N1 C1;\n                 generalize (list_rect P0 N0 C0 xs); intro ]\n    end.\n\n  Local Ltac t_reduce_list_evar :=\n    t_prereduce_list_evar;\n    t_postreduce_list.\n\n  Local Ltac t_postreduce_list_with_hyp :=\n    idtac;\n    match goal with\n      | [ |- list_rect ?P ?N ?C (?f ?a) ?a ?b ?c ?d = list_rect ?P ?N' ?C' (?f ?a) ?a ?b ?c ?d ]\n        => let P0 := fresh in\n           let N0 := fresh in\n           let C0 := fresh in\n           let N1 := fresh in\n           let C1 := fresh in\n           set (P0 := P);\n             set (N0 := N);\n             set (C0 := C);\n             set (N1 := N');\n             set (C1 := C');\n             let IH := fresh \"IH\" in\n             let xs := fresh \"xs\" in\n             refine (list_rect\n                       (fun ls' => forall a' (pf : ls' = f a') b' c' d',\n                                     list_rect P0 N0 C0 ls' a' b' c' d'\n                                     = list_rect P0 N1 C1 ls' a' b' c' d')\n                       _\n                       _\n                       (f a) a eq_refl b c d);\n               simpl @list_rect;\n               [ subst P0 N0 C0 N1 C1; intros; cbv beta\n               | intros ? xs IH; intros; unfold C0 at 1, C1 at 1; cbv beta;\n                 match goal with\n                   | [ |- appcontext[list_rect P0 N1 C1 ?ls'' ?a''] ]\n                     => specialize (IH a'')\n                 end;\n                 let T := match type of IH with ?T -> _ => T end in\n                 let H_helper := fresh in\n                 assert (H_helper : T);\n                   [\n                     | specialize (IH H_helper);\n                       setoid_rewrite <- IH; clear IH N1 C1;\n                       generalize (list_rect P0 N0 C0 xs); intro ] ]\n    end.\n\n  Local Ltac t_postreduce_list_with_hyp_with_assumption :=\n    idtac;\n    lazymatch goal with\n      | [ H : ?HP (?HP' (?f ?a)) = true |- list_rect ?P ?N ?C (?f ?a) ?a ?b ?c ?d = list_rect ?P ?N' ?C' (?f ?a) ?a ?b ?c ?d ]\n        => let P0 := fresh in\n           let N0 := fresh in\n           let C0 := fresh in\n           let N1 := fresh in\n           let C1 := fresh in\n           set (P0 := P);\n             set (N0 := N);\n             set (C0 := C);\n             set (N1 := N');\n             set (C1 := C');\n             let IH := fresh \"IH\" in\n             let xs := fresh \"xs\" in\n             let pf := fresh \"pf\" in\n             refine (list_rect\n                       (fun ls' => forall a' (pf : ls' = f a') (H' : HP (HP' (f a')) = true) b' c' d',\n                                     list_rect P0 N0 C0 ls' a' b' c' d'\n                                     = list_rect P0 N1 C1 ls' a' b' c' d')\n                       _\n                       _\n                       (f a) a eq_refl H b c d);\n               simpl @list_rect;\n               [ subst P0 N0 C0 N1 C1; intros; cbv beta\n               | intros ? xs IH pg; intros; unfold C0 at 1, C1 at 1; cbv beta;\n                 match goal with\n                   | [ |- appcontext[list_rect P0 N1 C1 ?ls'' ?a''] ]\n                     => specialize (IH a'')\n                 end;\n                 let T := match type of IH with ?T1 -> ?T2 -> _ => constr:(T1 * T2)%type end in\n                 let H_helper := fresh in\n                 let H_helper' := fresh in\n                 assert (H_helper : T);\n                   [ split\n                     | specialize (IH (fst H_helper) (snd H_helper));\n                       setoid_rewrite <- IH; clear IH N1 C1;\n                       generalize (list_rect P0 N0 C0 xs); intro ] ]\n    end.\n\n  Local Ltac t_reduce_list_evar_with_hyp :=\n    t_prereduce_list_evar;\n    t_postreduce_list_with_hyp.\n\n  Local Ltac t_refine_item_match_terminal :=\n    idtac;\n    match goal with\n      | [ |- _ = match ?it with Terminal _ => _ | NonTerminal nt => @?NT nt end :> ?T ]\n        => refine (_ : item_rect (fun _ => T) _ NT it = _);\n          revert it;\n          refine (item_rect\n                    _\n                    _\n                    _); simpl @item_rect; intro;\n          [ | reflexivity ]\n    end.\n\n  Local Ltac t_refine_item_match :=\n    idtac;\n    (lazymatch goal with\n      | [ |- _ = match ?it with Terminal _ => _ | _ => _ end :> ?T ]\n        => (refine (_ : item_rect (fun _ => T) _ _ it = _);\n          (lazymatch goal with\n            | [ |- item_rect ?P ?TC ?NC it = match it with Terminal t => @?TC' t | NonTerminal nt => @?NC' nt end ]\n              => refine (item_rect\n                           (fun it' => item_rect (fun _ => T) TC NC it'\n                                       = item_rect (fun _ => T) TC' NC' it')\n                           _\n                           _\n                           it)\n          end;\n          clear it; simpl @item_rect; intro))\n    end).\n\n  Local Arguments leb !_ !_.\n  Local Arguments to_nonterminal / .\n\n  Local Instance good_nth_proper {A}\n  : Proper (eq ==> _ ==> _ ==> eq) (nth (A:=A))\n    := _.\n\n  Local Ltac rewrite_map_nth_rhs :=\n    idtac;\n    match goal with\n      | [ |- _ = ?RHS ]\n        => let v := match RHS with\n                      | context[match nth ?n ?ls ?d with _ => _ end]\n                        => constr:(nth n ls d)\n                      | context[nth ?n ?ls ?d]\n                        => constr:(nth n ls d)\n                    end in\n           let P := match (eval pattern v in RHS) with\n                      | ?P _ => P\n                    end in\n           rewrite <- (map_nth P)\n    end.\n\n  Local Ltac rewrite_map_nth_dep_rhs :=\n    idtac;\n    match goal with\n      | [ |- _ = ?RHS ]\n        => let v := match RHS with\n                      | context[match nth ?n ?ls ?d with _ => _ end]\n                        => constr:(nth n ls d)\n                      | context[nth ?n ?ls ?d]\n                        => constr:(nth n ls d)\n                    end in\n           let n := match v with nth ?n ?ls ?d => n end in\n           let ls := match v with nth ?n ?ls ?d => ls end in\n           let d := match v with nth ?n ?ls ?d => d end in\n           let P := match (eval pattern v in RHS) with\n                      | ?P _ => P\n                    end in\n           let P := match (eval pattern n in P) with\n                      | ?P _ => P\n                    end in\n           rewrite <- (map_nth_dep P ls d n)\n    end.\n\n  Local Ltac t_pull_nth :=\n    repeat match goal with\n             | _ => rewrite drop_all by (simpl; omega)\n             | [ |- _ = nth _ _ _ ] => step_opt'\n             | [ |- _ = nth' _ _ _ ] => step_opt'\n             | _ => rewrite !map_map\n             | _ => progress simpl\n             | _ => rewrite <- !surjective_pairing\n             | _ => progress rewrite_map_nth_rhs\n           end;\n    fin_step_opt.\n  Local Ltac t_after_pull_nth_fin :=\n    idtac;\n    match goal with\n      | [ |- appcontext[@nth] ] => fail 1\n      | [ |- appcontext[@nth'] ] => fail 1\n      | _ => repeat step_opt'\n    end.\n\n  Let Let_In' {A B} (x : A) (f : forall y : A, B y) : B x\n    := let y := x in f y.\n\n  Local Notation \"@ 'Let_In' A B\" := (@Let_In' A B) (at level 10, A at level 8, B at level 8, format \"@ 'Let_In'  A  B\").\n  Local Notation Let_In := (@Let_In' _ _).\n\n  Let Let_In_Proper {A B} x\n  : Proper (forall_relation (fun _ => eq) ==> eq) (@Let_In A B x).\n  Proof.\n    lazy; intros ?? H; apply H.\n  Defined.\n\n  Definition inner_nth' {A} := Eval unfold nth' in @nth' A.\n  Definition inner_nth'_nth' : @inner_nth' = @nth'\n    := eq_refl.\n\n  Lemma rdp_list_to_production_opt_sig x\n  : { f : _ | rdp_list_to_production (G := G) x = f }.\n  Proof.\n    eexists.\n    set_evars.\n    unfold rdp_list_to_production at 1.\n    cbv beta iota delta [Carriers.default_to_production productions production].\n    simpl @Lookup.\n    match goal with\n      | [ |- (let a := ?av in\n              let b := @?bv a in\n              let c := @?cv a b in\n              let d := @?dv a b c in\n              let e := @?ev a b c d in\n              @?v a b c d e) = ?R ]\n        => change (Let_In av (fun a =>\n                   Let_In (bv a) (fun b =>\n                   Let_In (cv a b) (fun c =>\n                   Let_In (dv a b c) (fun d =>\n                   Let_In (ev a b c d) (fun e =>\n                   v a b c d e))))) = R);\n          cbv beta\n    end.\n    lazymatch goal with\n      | [ |- Let_In ?x ?P = ?R ]\n        => subst R; refine (@Let_In_Proper _ _ x _ _ _); intro; set_evars\n    end.\n    unfold Lookup_idx.\n    symmetry; rewrite_map_nth_rhs; symmetry.\n    repeat match goal with\n             | [ |- appcontext G[@Let_In ?A ?B ?k ?f] ]\n               => first [ let h := head k in constr_eq h @nil\n                        | constr_eq k 0\n                        | constr_eq k (snd (snd x)) ];\n                 test pose f; (* make sure f is closed *)\n                 let c := constr:(@Let_In A B k) in\n                 let c' := (eval unfold Let_In' in c) in\n                 let G' := context G[c' f] in\n                 change G'; simpl\n           end.\n    rewrite drop_all by (simpl; omega).\n    unfold productions, production.\n    rewrite <- nth'_nth at 1.\n    rewrite map_map; simpl.\n    match goal with\n      | [ H := ?e |- _ ] => is_evar e; subst H\n    end.\n    match goal with\n      | [ |- nth' ?a ?ls ?d = ?e ?a ]\n        => refine (_ : inner_nth' a ls d = (fun a' => inner_nth' a' _ d) a); cbv beta;\n           apply f_equal2; [ clear a | reflexivity ]\n    end.\n    etransitivity.\n    { apply (_ : Proper (pointwise_relation _ _ ==> eq ==> eq) (@List.map _ _));\n      [ intro | reflexivity ].\n      do 2 match goal with\n             | [ |- Let_In ?x ?P = ?R ]\n               => refine (@Let_In_Proper _ _ x _ _ _); intro\n           end.\n      etransitivity.\n      { symmetry; rewrite_map_nth_rhs; symmetry.\n        unfold Let_In' at 2 3 4; simpl.\n        set_evars.\n        rewrite drop_all by (simpl; omega).\n        unfold Let_In'.\n        rewrite <- nth'_nth.\n        change @nth' with @inner_nth'.\n        subst_body; reflexivity. }\n      reflexivity. }\n    reflexivity.\n  Defined.\n\n  Definition rdp_list_to_production_opt x\n    := Eval cbv beta iota delta [proj1_sig rdp_list_to_production_opt_sig Let_In']\n      in proj1_sig (rdp_list_to_production_opt_sig x).\n\n  Lemma rdp_list_to_production_opt_correct x\n  : rdp_list_to_production (G := G) x = rdp_list_to_production_opt x.\n  Proof.\n    exact (proj2_sig (rdp_list_to_production_opt_sig x)).\n  Qed.\n\n  Lemma opt_helper_minusr_proof\n  : forall {len0 len}, len <= len0 -> forall n : nat, (len - n)%natr <= len0.\n  Proof.\n    clear.\n    intros.\n    rewrite minusr_minus; omega.\n  Qed.\n\n  Definition parse_nonterminal_opt'0\n             (str : String)\n             (nt : String.string)\n  : { b : bool | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    exists (parse_nonterminal (data := optdata) str nt).\n    reflexivity.\n  Defined.\n\n  Local Ltac optsplit_t' :=\n    idtac;\n    match goal with\n      | [ |- _ = ?f match ?v with nil => ?N | x::xs => @?C x xs end ]\n        => let RHS := match goal with |- _ = ?RHS => RHS end in\n           let P := match (eval pattern v in RHS) with ?P _ => P end in\n           transitivity (match v with\n                           | nil => P nil\n                           | x::xs => P (x::xs)\n                         end);\n             [ simpl | destruct v; reflexivity ]\n      | [ |- _ = ?f match ?v with Terminal t => @?T t | NonTerminal nt => @?NT nt end ]\n        => let RHS := match goal with |- _ = ?RHS => RHS end in\n           let P := match (eval pattern v in RHS) with ?P _ => P end in\n           transitivity (match v with\n                           | Terminal t => P (Terminal t)\n                           | NonTerminal nt => P (NonTerminal nt)\n                         end);\n             [ simpl | destruct v; reflexivity ]\n      | [ |- ?e = match ?v with nil => ?N | x::xs => @?C x xs end :> ?T ]\n        => idtac;\n          repeat match goal with\n                 | [ H : context[v] |- _ ]\n                   => hnf in H;\n                     match type of H with\n                     | context[v] => fail 1\n                     | _ => idtac\n                     end\n                 end;\n          let P := match (eval pattern v in T) with ?P _ => P end in\n          change (e = list_caset P N C v);\n            revert dependent v;\n            let NT := type of N in\n            let CT := type of C in\n            let N' := fresh in\n            let C' := fresh in\n            evar (N' : NT);\n              evar (C' : CT);\n              intro v; intros;\n              refine (_ : list_caset P N' C' v = list_caset P N C v);\n              refine (list_caset\n                        (fun v' => list_caset P N' C' v' = list_caset P N C v')\n                        _\n                        _\n                        v);\n              subst N' C'; simpl @list_caset; repeat intro\n      | [ H : is_true (item_rvalid ?G ?v)\n          |- ?e = match ?v with Terminal t => @?T t | NonTerminal nt => @?NT nt end ]\n        => idtac; let TT := type of T in\n                  let NTT := type of NT in\n                  let T' := fresh in\n                  let NT' := fresh in\n                  revert dependent v;\n                    evar (T' : TT);\n                    evar (NT' : NTT);\n                    intro v; intros;\n                    let eqP := match goal with |- _ = _ :> ?P => P end in\n                    let P := match (eval pattern v in eqP) with ?P _ => P end in\n                      change (e = item_rect P T NT v);\n                      refine (_ : item_rect P T' NT' v = item_rect P T NT v);\n                      refine (item_rect\n                                (fun v' => item_rvalid G v' -> item_rect P T' NT' v' = item_rect P T NT v')\n                                _\n                                _\n                                v H);\n                      subst T' NT';\n                      simpl @item_rect; intros ??\n      | [ |- ?e = match ?v with Terminal t => @?T t | NonTerminal nt => @?NT nt end ]\n        => idtac; let TT := type of T in\n                  let NTT := type of NT in\n                  let T' := fresh in\n                  let NT' := fresh in\n                  revert dependent v;\n                    evar (T' : TT);\n                    evar (NT' : NTT);\n                    intro v; intros;\n                    let eqP := match goal with |- _ = _ :> ?P => P end in\n                    let P := match (eval pattern v in eqP) with ?P _ => P end in\n                      change (e = item_rect P T NT v);\n                      refine (_ : item_rect P T' NT' v = item_rect P T NT v);\n                      refine (item_rect\n                                (fun v' => item_rect P T' NT' v' = item_rect P T NT v')\n                                _\n                                _\n                                v);\n                      subst T' NT';\n                      simpl @item_rect; intro\n      | [ |- _ = _::_ ] => etransitivity_rev (_::_);\n                          [ apply f_equal2\n                          | reflexivity ]\n      | _ => progress fin_step_opt\n    end.\n\n  Definition parse_nonterminal_opt'1\n             (str : String)\n             (nt : String.string)\n  : { b : bool | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'0 str nt) in\n    let h := head c in\n    let p := (eval cbv beta iota zeta delta [proj1_sig h] in (proj1_sig c)) in\n    sigL_transitivity p; [ | abstract exact (proj2_sig c) ].\n    cbv beta iota zeta delta [parse_nonterminal parse_nonterminal' parse_nonterminal_or_abort list_to_grammar].\n    change (@parse_nonterminal_step Char) with (fun b c d e f g h i j k l => @parse_nonterminal_step Char b c d e f g h i j k l); cbv beta.\n    evar (b' : bool).\n    sigL_transitivity b'; subst b';\n    [\n    | rewrite Fix5_2_5_eq by (intros; apply parse_nonterminal_step_ext; assumption);\n      reflexivity ].\n    simpl @fst; simpl @snd.\n    cbv beta iota zeta delta [parse_nonterminal parse_nonterminal' parse_nonterminal_or_abort parse_nonterminal_step parse_productions parse_productions' parse_production parse_item parse_item' Lookup list_to_grammar list_to_productions].\n    simpl.\n    cbv beta iota zeta delta [predata BaseTypes.predata initial_nonterminals_data nonterminals_length remove_nonterminal production_carrierT].\n    cbv beta iota zeta delta [rdp_list_predata Carriers.default_production_carrierT rdp_list_is_valid_nonterminal rdp_list_initial_nonterminals_data rdp_list_remove_nonterminal Carriers.default_nonterminal_carrierT rdp_list_nonterminals_listT rdp_list_production_tl Carriers.default_nonterminal_carrierT].\n    (*cbv beta iota zeta delta [rdp_list_of_nonterminal].*)\n    simpl; unfold pregrammar_nonterminals; simpl.\n    evar (b' : bool).\n    sigL_transitivity b'; subst b';\n    [\n    | simpl;\n      rewrite !map_length, !length_up_to;\n      reflexivity ].\n\n    refine_Fix2_5_Proper_eq_with_assumptions.\n    etransitivity_rev _.\n    { fix2_trans_with_assumptions;\n      [\n      | unfold parse_production', parse_production'_for, parse_item', productions, production;\n        solve [ t_reduce_fix;\n                t_reduce_list;\n                t_reduce_fix ] ].\n\n      (** Now we take advantage of the optimized splitter *)\n      etransitivity_rev _.\n      { match goal with\n        | [ |- _ = option_rect ?P (fun x => _) ?N ?v ]\n          => refine (_ : option_rect P (fun x => _) N v = _)\n        end;\n        match goal with\n        | [ |- option_rect ?P ?S ?N ?v = option_rect ?P ?S' ?N' ?v ]\n          => refine (option_rect\n                       (fun v' => v = v' -> option_rect P S N v' = option_rect P S' N' v')\n                       (fun v' Hv => _)\n                       (fun Hv => _)\n                       v\n                       eq_refl);\n             simpl @option_rect\n        end; [ | reflexivity ].\n        apply (f_equal (fun x => match x with Some _ => true | None => false end)) in Hv.\n        simpl in Hv.\n        lazymatch goal with\n        | [ H : _ /\\ (_ \\/ is_true (is_valid_nonterminal initial_nonterminals_data ?nt)) |- _ ]\n          => assert (Hvalid' : is_valid_nonterminal initial_nonterminals_data nt)\n        end.\n        { destruct_head and; destruct_head or; try assumption; [].\n          edestruct lt_dec; simpl in *; [ omega | ].\n          edestruct dec; simpl in *; [ | congruence ].\n          match goal with\n          | [ H : _ = true |- _ ] => apply Bool.andb_true_iff in H; destruct H as [? H']\n          end.\n          match goal with\n          | [ H : sub_nonterminals_listT ?ls ?init, H' : list_bin_eq ?nt ?ls = true\n              |- is_true (?R ?init ?nt) ]\n            => apply H, H'\n          end. }\n        step_opt'.\n        step_opt'.\n        let nt := match type of Hvalid' with is_true (is_valid_nonterminal _ ?nt) => nt end in\n        assert (Hvalid'' : productions_rvalid G (map to_production (nonterminal_to_production nt))).\n        { unfold grammar_rvalid in Hvalid.\n          eapply (proj1 fold_right_andb_map_in_iff) in Hvalid; [ eassumption | ].\n          rewrite nonterminal_to_production_correct' by assumption.\n          apply in_map, initial_nonterminals_correct'; assumption. }\n        simpl @nonterminal_to_production in Hvalid''.\n        unfold productions_rvalid in Hvalid''.\n        rewrite map_map in Hvalid''.\n        pose proof (proj1 fold_right_andb_map_in_iff Hvalid'') as Hvalid'''.\n        cbv beta in Hvalid'''.\n        apply map_Proper_eq_In; intros ? Hin.\n        specialize (Hvalid''' _ Hin).\n        unfold parse_production', parse_production'_for.\n        simpl.\n        etransitivity_rev _.\n        { t_reduce_list_evar_with_hyp;\n          [ reflexivity\n          |\n          | ].\n          { rewrite rdp_list_production_tl_correct.\n            match goal with\n              | [ H : _ = ?x |- context[?x] ]\n                => rewrite <- H; reflexivity\n            end. }\n          { match goal with\n              | [ H : _ = ?x |- context[match ?x with _ => _ end] ]\n                => rewrite <- H\n            end.\n            reflexivity. } }\n        (** Pull out the nil case once and for all *)\n        etransitivity_rev _.\n        { match goal with\n            | [ |- _ = list_rect ?P ?N ?C (?f ?a) ?a ?b ?c ?d ]\n              => let P0 := fresh in\n                 let N0 := fresh in\n                 let C0 := fresh in\n                 set (P0 := P);\n                   set (N0 := N);\n                   set (C0 := C);\n                   let IH := fresh \"IH\" in\n                   let xs := fresh \"xs\" in\n                   refine (list_rect\n                             (fun ls' => forall a' (pf : ls' = f a') b' c' d',\n                                           (bool_rect\n                                              (fun _ => _)\n                                              (N0 a' b' c' d')\n                                              (list_rect P0 (fun _ _ _ _ => true) C0 ls' a' b' c' d')\n                                              (EqNat.beq_nat (List.length ls') 0))\n                                           = list_rect P0 N0 C0 ls' a' b' c' d')\n                             _\n                             _\n                             (f a) a eq_refl b c d);\n                     simpl @list_rect;\n                     [ subst P0 N0 C0; intros; cbv beta\n                     | intros ? xs IH; intros; unfold C0 at 1 3; cbv beta;\n                       match goal with\n                         | [ |- appcontext[list_rect P0 N0 C0 ?ls'' ?a''] ]\n                           => specialize (IH a'')\n                       end;\n                       let T := match type of IH with ?T -> _ => T end in\n                       let H_helper := fresh in\n                       assert (H_helper : T);\n                         [\n                         | specialize (IH H_helper);\n                           setoid_rewrite <- IH; clear IH ] ]\n          end.\n          { reflexivity. }\n          { rewrite rdp_list_production_tl_correct.\n            match goal with\n              | [ H : _ = ?x |- context[?x] ]\n                => rewrite <- H; reflexivity\n            end. }\n          { simpl.\n            unfold parse_item'.\n            step_opt';\n            repeat match goal with\n                     | [ |- context[List.map _ match ?e with _ => _ end] ]\n                       => is_var e; destruct e\n                     | _ => progress simpl\n                     | [ |- ?x = ?x ] => reflexivity\n                     | _ => progress rewrite ?Bool.andb_true_r, ?Min.min_idempotent, ?Minus.minus_diag\n                     | [ H : EqNat.beq_nat _ _ = true |- _ ]\n                       => apply EqNat.beq_nat_true in H\n                     | _ => progress subst\n                     | [ |- context[EqNat.beq_nat ?x ?y] ]\n                       => is_var x; destruct (EqNat.beq_nat x y) eqn:?\n                     | [ H := _ |- _ ] => subst H\n                   end. } }\n        cbv beta.\n        step_opt'; [ | reflexivity ].\n        etransitivity_rev _.\n        { move Hvalid''' at bottom.\n          simpl @to_production in Hvalid'''.\n          unfold production_rvalid in Hvalid'''.\n          t_prereduce_list_evar.\n          t_postreduce_list_with_hyp_with_assumption;\n          [ reflexivity\n            | let lem := constr:(production_tl_correct) in\n              simpl rewrite lem;\n              match goal with\n              | [ H : _::_ = ?y |- context[tl ?y] ] => generalize dependent y; intros; subst\n              end;\n              simpl in *;\n              try reflexivity;\n              try assumption..\n            | ].\n          { match goal with\n            | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n            end.\n            split_and; assumption. }\n          match goal with\n          | [ |- context[match ?nt with Terminal _ => _ | _ => _ end] ]\n            => assert (Hvalid'''' : item_rvalid G nt)\n          end.\n          { repeat match goal with\n                   | _ => assumption\n                   | [ H : ?nt :: _ = ?ls, H' : context[?ls] |- is_true (item_rvalid _ ?nt) ]\n                     => rewrite <- H in H'\n                   | _ => progress simpl in *\n                   | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n                   | _ => progress split_and\n                   end. }\n          etransitivity_rev _.\n          { step_opt'.\n            etransitivity_rev _.\n            { repeat optsplit_t'.\n              { rewrite <- andbr_andb.\n                apply (f_equal2 andbr); [ | reflexivity ].\n                rewrite Min.min_idempotent at 2.\n                match goal with\n                  | [ |- _ = ?f ?b ?c ?d ?e ]\n                    => refine (f_equal (fun b' => f b' c d e) _)\n                end.\n                match goal with\n                  | [ |- _ = ?f (min ?x ?x) (?pf_f ?pf ?k) ]\n                    => etransitivity_rev (f x pf);\n                      [ generalize (pf_f pf k); rewrite Min.min_idempotent; intro\n                      | ]\n                end.\n                { f_equal; apply Le.le_proof_irrelevance. }\n                { reflexivity. } }\n              { apply (f_equal2 andb); [ | reflexivity ].\n                apply (f_equal2 andb); [ | reflexivity ].\n                match goal with\n                | [ |- _ = EqNat.beq_nat (min ?v ?x) ?v ]\n                  => refine (_ : Compare_dec.leb v x = _)\n                end.\n                match goal with\n                | [ |- leb 1 ?x = _ ]\n                  => is_var x; destruct x as [|[|]]; try reflexivity\n                end. }\n              { simpl in *.\n                match goal with\n                | [ H : is_true ?x |- context[?x] ] => rewrite H\n                end.\n                reflexivity. } }\n            reflexivity. }\n          etransitivity_rev _.\n          { rewrite !(@fold_symmetric _ orb) by first [ apply Bool.orb_assoc | apply Bool.orb_comm ].\n            unfold parse_item'.\n            repeat optsplit_t'; repeat step_opt';\n              [ apply (f_equal2 andb) | ];\n              repeat optsplit_t'; repeat step_opt'.\n            { reflexivity. }\n            { reflexivity. }\n            { simpl in *.\n              set_evars.\n              match goal with\n              | [ H : is_true ?x |- context[?x] ] => rewrite H\n              end.\n              match goal with\n              | [ H := ?e |- _ ] => is_evar e; subst H\n              end.\n              reflexivity. }\n            { reflexivity. } }\n            reflexivity. }\n          reflexivity. }\n\n      unfold parse_production', parse_production'_for, parse_item', productions, production.\n      cbv beta iota zeta delta [predata BaseTypes.predata initial_nonterminals_data nonterminals_length remove_nonterminal production_carrierT].\n      cbv beta iota zeta delta [rdp_list_predata Carriers.default_production_carrierT rdp_list_is_valid_nonterminal rdp_list_initial_nonterminals_data rdp_list_remove_nonterminal Carriers.default_nonterminal_carrierT rdp_list_nonterminals_listT rdp_list_production_tl Carriers.default_nonterminal_carrierT].\n\n      step_opt'; [ | reflexivity ].\n      step_opt'.\n      etransitivity_rev _.\n      { cbv beta iota delta [rdp_list_nonterminal_to_production Carriers.default_production_carrierT Carriers.default_nonterminal_carrierT].\n        simpl rewrite list_to_productions_to_nonterminal; unfold Lookup_idx.\n        etransitivity_rev _.\n        { step_opt'; [ reflexivity | ].\n          etransitivity_rev _.\n          { step_opt'.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            reflexivity. }\n          rewrite_map_nth_dep_rhs; simpl.\n          rewrite map_length.\n          reflexivity. }\n        rewrite_map_nth_rhs; rewrite !map_map; simpl.\n        apply (f_equal2 (@nth _ _)); [ | reflexivity ].\n        step_opt'; [ | reflexivity ].\n        rewrite !map_map; simpl.\n        reflexivity. }\n      rewrite_map_nth_rhs; rewrite !map_map; simpl.\n      rewrite <- nth'_nth.\n      etransitivity_rev _.\n      { step_opt'.\n        step_opt'; [ | reflexivity ].\n        reflexivity. }\n      reflexivity. }\n    etransitivity_rev _.\n    { etransitivity_rev _.\n      { repeat first [ idtac;\n                       match goal with\n                         | [ |- appcontext[@rdp_list_of_nonterminal] ] => fail 1\n                         | [ |- appcontext[@Carriers.default_production_tl] ] => fail 1\n                         | _ => reflexivity\n                       end\n                     | step_opt'\n                     | t_reduce_list_evar\n                     | apply (f_equal2 andb)\n                     | apply (f_equal2 (@cons _))\n                     | t_refine_item_match ];\n        first [ progress unfold rdp_list_of_nonterminal, Valid_nonterminals, grammar_of_pregrammar, pregrammar_nonterminals; simpl;\n                rewrite !map_length;\n                reflexivity\n              | idtac;\n                match goal with\n                  | [ |- _ = ?f ?A ?b ?c ?d ]\n                    => refine (f_equal (fun A' => f A' b c d) _)\n                end;\n                progress unfold Carriers.default_production_tl; simpl;\n                repeat step_opt'; [ reflexivity | ];\n                unfold Lookup_idx;\n                unfold productions, production;\n                rewrite_map_nth_rhs; simpl;\n                rewrite <- nth'_nth;\n                rewrite_map_nth_dep_rhs; simpl;\n                step_opt'; simpl;\n                rewrite !nth'_nth; simpl;\n                rewrite map_length;\n                rewrite <- !nth'_nth;\n                change @nth' with @inner_nth';\n                reflexivity\n              | idtac ].\n        reflexivity. }\n      etransitivity_rev _.\n      { repeat first [ idtac;\n                       match goal with\n                         | [ |- appcontext[@rdp_list_to_production] ] => fail 1\n                         | _ => reflexivity\n                       end\n                     | rewrite rdp_list_to_production_opt_correct\n                     | step_opt'\n                     | t_reduce_list_evar ].\n        reflexivity. }\n      etransitivity_rev _.\n      { step_opt'; [ | reflexivity ].\n        step_opt'.\n        step_opt'.\n        step_opt'; [ | reflexivity ].\n        unfold rdp_list_to_production_opt at 1; simpl.\n        change @inner_nth' with @nth' at 3.\n        etransitivity_rev _.\n        { step_opt'.\n          etransitivity_rev _.\n          { repeat step_opt'; [ | reflexivity ].\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth'.\n            apply (f_equal2 (inner_nth' _)); [ | reflexivity ].\n            step_opt'; [].\n            rewrite map_id.\n            change @inner_nth' with @nth' at 3.\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth'.\n            apply f_equal2; [ | reflexivity ].\n            reflexivity. }\n          etransitivity_rev _.\n          { change @inner_nth' with @nth' at 1.\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth' at 1.\n            reflexivity. }\n          etransitivity_rev _.\n          { apply f_equal2; [ reflexivity | ].\n            rewrite bool_rect_andb; simpl.\n            rewrite Bool.andb_true_r.\n            match goal with\n            | [ |- _ = (orb (negb (EqNat.beq_nat ?x 0)) (andb (EqNat.beq_nat ?x 0) ?y)) ]\n              => let z := fresh in\n                 let y' := fresh in\n                 set (z := x);\n                   set (y' := y);\n                   refine (_ : orb (Compare_dec.leb 1 x) y = _);\n                   change (orb (Compare_dec.leb 1 z) y' = orb (negb (EqNat.beq_nat z 0)) (andb (EqNat.beq_nat z 0) y'));\n                   destruct z, y'; reflexivity\n            end. }\n          etransitivity_rev _.\n          { apply (f_equal2 (inner_nth' _)); [ | reflexivity ].\n            step_opt'; [ ].\n            change @inner_nth' with @nth' at 1.\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth' at 1.\n            reflexivity. }\n          reflexivity. }\n        (*etransitivity_rev _.\n        { change @inner_nth' with @nth' at 1.\n          etransitivity_rev _.\n          { step_opt'.\n            etransitivity_rev _.\n            { step_opt'.\n              rewrite nth'_nth; reflexivity. }\n            match goal with\n              | [ |- _ = map (fun x => nth ?n (@?ls x) ?d) ?ls' ]\n                => etransitivity_rev (map (fun ls'' => nth n ls'' d) (map ls ls'));\n                  [ rewrite !map_map; reflexivity | ]\n            end.\n            reflexivity. }*)\n        reflexivity. }\n      reflexivity. }\n    etransitivity_rev _.\n    { repeat first [ step_opt'\n                   | apply (f_equal2 (inner_nth' _)); fin_step_opt\n                   | apply (f_equal2 orb); fin_step_opt\n                   | idtac;\n                     match goal with\n                     | [ |- _ = List.length (rdp_list_to_production_opt _) ]\n                       => progress unfold rdp_list_to_production_opt at 1; simpl;\n                          change @inner_nth' with @nth';\n                          repeat match goal with\n                                   | _ => progress simpl\n                                   | _ => progress fin_step_opt\n                                   | [ |- _ = @List.length ?A ?ls ]\n                                     => refine (f_equal (@List.length A) _)\n                                   | [ |- _ = nth' ?n ?ls ?d ]\n                                     => refine (f_equal2 (nth' n) _ _)\n                                   | [ |- _ = map (fun _ => nth' _ _ _) _ ]\n                                     => progress step_opt'\n                                 end;\n                          rewrite map_id;\n                          fin_step_opt\n                     end ];\n      [ | reflexivity | reflexivity | ].\n      { t_reduce_list_evar; [ reflexivity | ].\n        repeat first [ step_opt'\n                     | apply (f_equal2 andb)\n                     | apply (f_equal2 andbr)\n                     | apply (f_equal3 char_at_matches)\n                     | progress fin_step_opt ].\n        { match goal with\n          | [ |- _ = ?f (?x - ?x) ?pf ]\n            => generalize pf;\n              rewrite Minus.minus_diag;\n              let pf' := fresh in\n              intro pf';\n                assert (Le.le_0_n _ = pf') by apply Le.le_proof_irrelevance;\n                subst pf'\n          end.\n          reflexivity. }\n        { reflexivity. }\n        { rewrite Plus.plus_comm; progress simpl.\n          match goal with\n            | [ |- _ = ?f (?x - ?y) (?pf ?a ?b ?c ?d) ]\n              => let f' := fresh in\n                 set (f' := f);\n                   let ty := constr:(f' (x - y)%natr (@opt_helper_minusr_proof a b c d) = f' (x - y) (pf a b c d )) in\n                   refine (_ : ty); change ty;\n                   clearbody f'\n          end.\n          match goal with\n            | [ |- ?f ?x ?y = ?f ?x' ?y' ]\n              => generalize y; generalize y'\n          end.\n          rewrite minusr_minus; intros; f_equal.\n          apply Le.le_proof_irrelevance. }\n        { reflexivity. }\n        { match goal with\n            | [ |- _ = ?f (?x - ?y) (?pf ?a ?b ?c ?d) ]\n              => let f' := fresh in\n                 set (f' := f);\n                   let ty := constr:(f' (x - y)%natr (@opt_helper_minusr_proof a b c d) = f' (x - y) (pf a b c d )) in\n                   refine (_ : ty); change ty;\n                   clearbody f'\n          end.\n          match goal with\n            | [ |- ?f ?x ?y = ?f ?x' ?y' ]\n              => generalize y; generalize y'\n          end.\n          rewrite minusr_minus; intros; f_equal.\n          apply Le.le_proof_irrelevance. }\n        { reflexivity. } }\n      { reflexivity. } }\n    reflexivity.\n  Defined.\n\n  Definition parse_nonterminal_opt'2\n             (str : String)\n             (nt : String.string)\n  : { b : bool | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'1 str nt) in\n    let h := head c in\n    let p := (eval cbv beta iota zeta delta [proj1_sig h] in (proj1_sig c)) in\n    sigL_transitivity p; [ | abstract exact (proj2_sig c) ].\n    refine_Fix2_5_Proper_eq.\n    etransitivity_rev _.\n    { fix2_trans;\n      [\n      | solve [ change @opt3.nth' with @nth';\n                change @opt2.map with @List.map;\n                change @inner_nth' with @nth';\n                t_reduce_fix;\n                t_postreduce_list;\n                unfold item_rect;\n                t_reduce_fix ] ].\n      reflexivity. }\n\n    (** [nth'] is useful when the index is unknown at top-level, but performs poorly in [simpl] when the index is eventually known at compile-time.  So we need to remove the [nth'] *)\n    etransitivity_rev _.\n    { change @inner_nth' with @nth'.\n      step_opt'; [ | reflexivity ].\n      step_opt'; [].\n      apply (f_equal2 (nth' _)); [ | reflexivity ].\n      step_opt'; [ | reflexivity ].\n      step_opt'; [].\n      rewrite !nth'_nth; apply (f_equal2 (nth _)); [ | ].\n      { step_opt'; [ ].\n        rewrite !nth'_nth; apply (f_equal2 (nth _)); [ | ].\n        { step_opt'; [].\n          match goal with\n          | [ |- _ = @bool_rect (fun _ => ?P) _ _ _ ]\n            => apply (f_equal3 (bool_rect (fun _ => P)))\n          end; [ reflexivity | | ];\n          fin_step_opt.\n          { t_reduce_list_evar; [ reflexivity | ].\n            step_opt'; [].\n            step_opt'; [ | ].\n            { rewrite nth'_nth.\n              rewrite <- andbr_andb at 1.\n              apply (f_equal2 andbr); [ | reflexivity ].\n              match goal with\n              | [ |- _ = ?f ?x ?a ?b ?c ]\n                => refine (f_equal (fun x' => f x' a b c) _)\n              end.\n              fin_step_opt; [ reflexivity | ].\n              apply (f_equal2 (nth _)); [ | reflexivity ].\n              step_opt'; [ | reflexivity ].\n              rewrite nth'_nth; reflexivity. }\n            { step_opt'.\n              { rewrite <- andbr_andb at 1.\n                apply (f_equal2 andbr); [ reflexivity | ].\n                rewrite nth'_nth.\n                match goal with\n                | [ |- _ = ?f ?x ?a ?b ?c ]\n                  => refine (f_equal (fun x' => f x' a b c) _)\n                end.\n                fin_step_opt; [ reflexivity | ].\n                apply (f_equal2 (nth _)); [ | reflexivity ].\n                step_opt'; [ | reflexivity ].\n                rewrite nth'_nth; reflexivity. }\n              { step_opt'; [ | reflexivity ].\n                apply (f_equal2 andb); [ reflexivity | ].\n                rewrite nth'_nth.\n                match goal with\n                | [ |- _ = ?f ?x ?a ?b ?c ]\n                  => refine (f_equal (fun x' => f x' a b c) _)\n                end.\n                fin_step_opt; [ reflexivity | ].\n                apply (f_equal2 (nth _)); [ | reflexivity ].\n                step_opt'; [ | reflexivity ].\n                rewrite nth'_nth; reflexivity. } } }\n          { match goal with\n            | [ |- _ = @List.length ?A ?ls ]\n              => refine (f_equal (@List.length A) _)\n            end.\n            apply (f_equal2 (nth _)); [ | reflexivity ].\n            step_opt'; [ ].\n            step_opt'; [ progress simpl ].\n            rewrite nth'_nth.\n            apply (f_equal2 (nth _)); [ | reflexivity ].\n            reflexivity. } }\n        { etransitivity_rev _.\n          { rewrite bool_rect_andb.\n            rewrite Bool.andb_true_r.\n            match goal with\n            | [ |- _ = (orb (negb (EqNat.beq_nat ?x 0)) (andb (EqNat.beq_nat ?x 0) ?y)) ]\n              => let z := fresh in\n                 let y' := fresh in\n                 set (z := x);\n                   set (y' := y);\n                   refine (_ : orb (Compare_dec.leb 1 x) y = _);\n                   change (orb (Compare_dec.leb 1 z) y' = orb (negb (EqNat.beq_nat z 0)) (andb (EqNat.beq_nat z 0) y'));\n                   destruct z, y'; reflexivity\n            end. }\n          apply (f_equal2 orb); fin_step_opt; [].\n          match goal with\n          | [ |- _ = @List.length ?A ?ls ]\n            => refine (f_equal (@List.length A) _)\n          end.\n          apply (f_equal2 (nth _)); [ | reflexivity ].\n          step_opt'; [ ].\n          step_opt'; [ progress simpl ].\n          rewrite nth'_nth.\n          apply (f_equal2 (nth _)); [ | reflexivity ].\n          reflexivity. } }\n      { apply (f_equal2 orb); fin_step_opt; [].\n        match goal with\n        | [ |- _ = @List.length ?A ?ls ]\n          => refine (f_equal (@List.length A) _)\n        end.\n        apply (f_equal2 (nth _)); [ | reflexivity ].\n        step_opt'; [ ].\n        step_opt'; [ progress simpl ].\n        rewrite nth'_nth.\n        apply (f_equal2 (nth _)); [ | reflexivity ].\n        reflexivity. } }\n    change @nth' with @inner_nth' at 1.\n    match goal with\n      | [ |- appcontext[@nth'] ] => fail 1\n      | _ => change @inner_nth' with @nth'\n    end.\n    etransitivity_rev _.\n    { step_opt'; [ | reflexivity ].\n      rewrite nth'_nth at 1.\n      rewrite_map_nth_rhs; rewrite !map_map; simpl.\n      rewrite <- nth'_nth at 1.\n      reflexivity. }\n\n    reflexivity.\n  Defined.\n\n  Local Ltac safe_change_opt' :=\n    idtac;\n    match goal with\n    | [ |- context G[minusr (opt.id ?x) (opt.id ?y)] ]\n      => let G' := context G[opt.id (opt.minusr x y)] in\n         change G'\n    | [ |- context G[minusr (opt.id ?x) (opt2.id ?y)] ]\n      => let G' := context G[opt2.id (opt2.minusr x y)] in\n         change G'\n    | [ |- context G[fst (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.fst x)] in\n         change G'\n    | [ |- context G[snd (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.snd x)] in\n         change G'\n    | [ |- context G[fst (opt2.id ?x)] ]\n      => let G' := context G[opt2.id (opt2.fst x)] in\n         change G'\n    | [ |- context G[snd (opt2.id ?x)] ]\n      => let G' := context G[opt2.id (opt2.snd x)] in\n         change G'\n    | [ |- appcontext G[nth (opt2.id ?x) ?ls ?d] ]\n      => let G' := context G[opt2.id (opt2.nth x ls d)] in\n         change G'\n    | [ |- context G[StringLike.length (opt.id ?str)] ]\n      => let G' := context G[StringLike.length str] in\n         change G'\n    | [ |- context G[map (opt.id ?f) (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.map f x)] in\n         change G'\n    | [ |- context G[map fst (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.map opt.fst x)] in\n         change G'\n    | [ |- context G[map snd (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.map opt.snd x)] in\n         change G'\n    (*| [ |- appcontext G[snd (of_string (opt.id ?x))] ]\n               => let G' := context G[opt.snd (of_string x)] in\n                  change G'*)\n    | [ |- context G[string_beq (opt.id ?x)] ]\n      => let G' := context G[opt.id (opt.string_beq x)] in\n         change G'\n    | [ |- context G[fun x0 y0 : ?T => string_beq (fst x0) (fst y0)] ]\n      => let G' := context G[opt.id (fun x0 y0 : T => opt.string_beq (opt.fst x0) (opt.fst y0))] in\n         change G'\n    | [ |- context G[uniquize (opt.id ?beq) (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.uniquize beq ls)] in\n         change G'\n    | [ |- context G[uniquize string_beq (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.uniquize opt.string_beq ls)] in\n         change G'\n    | [ |- context G[List.length (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.length ls)] in\n         change G'\n    | [ |- context G[List.length (opt2.id ?ls)] ]\n      => let G' := context G[opt2.id (opt2.length ls)] in\n         change G'\n    | [ |- context G[first_index_default (opt.id ?x) (opt.id ?y) (opt.id ?z)] ]\n      => let G' := context G[opt.id (opt.first_index_default x y z)] in\n         change G'\n    | [ |- context G[up_to (opt.id ?n)] ]\n      => let G' := context G[opt.id (opt.up_to n)] in\n         change G'\n    | [ |- context G[pred (opt.id ?n)] ]\n      => let G' := context G[opt.id (opt.pred n)] in\n         change G'\n    | [ |- context G[rev (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.rev ls)] in\n         change G'\n    | [ |- context G[fun x0 : ?T => up_to (Datatypes.length (snd x0))] ]\n      => let G' := context G[opt.id (fun x0 : T => opt.up_to (opt.length (opt.snd x0)))] in\n         change G'\n    | [ |- context G[combine (opt.id ?ls) (opt.id ?ls')] ]\n      => let G' := context G[opt.id (opt.combine ls ls')] in\n         change G'\n    | [ |- context G[List.hd ?d (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.hd d ls)] in\n         change G'\n    | [ |- context G[fst (of_string ?str')] ]\n      => let G' := context G[opt.id (opt.fst (of_string str'))] in\n         change G'\n    | [ |- context G[snd (of_string ?str')] ]\n      => let G' := context G[opt.id (opt.snd (of_string str'))] in\n         change G'\n    | [ |- context G[EqNat.beq_nat (opt2.id ?x) 0] ]\n      => let G' := context G[opt2.id (opt2.beq_nat x 0)] in\n         change G'\n    | [ |- context G[(opt2.id ?x, 0)] ]\n      => let G' := context G[opt2.id (x, 0)] in\n         change G'\n    | [ |- context G[(opt2.id ?x, opt2.id ?y)] ]\n      => let G' := context G[opt2.id (x, y)] in\n         change G'\n    | [ |- context G[EqNat.beq_nat (opt.id ?x) 0] ]\n      => let G' := context G[opt.id (opt.beq_nat x 0)] in\n         change G'\n    | [ |- context G[S (opt2.id ?x)] ]\n      => let G' := context G[opt2.id (S x)] in\n         change G'\n    | [ |- context G[S (opt.id ?x)] ]\n      => let G' := context G[opt.id (S x)] in\n         change G'\n    | [ |- context G[leb (opt2.id ?x) (opt.id ?y)] ]\n      => let G' := context G[opt2.id (opt2.leb x y)] in\n         change G'\n    | [ |- context G[leb 1 (opt2.id ?x)] ]\n      => let G' := context G[opt2.id (opt2.leb 1 x)] in\n         change G'\n    | [ |- context G[leb 1 (opt2.length ?x)] ]\n      => let G' := context G[opt2.id (opt2.leb 1 (opt2.length x))] in\n         change G'\n    end.\n\n  Local Ltac change_opt_reduce' :=\n    idtac;\n    match goal with\n    | _ => progress safe_change_opt'\n    | [ |- ?LHS = _ ]\n      => match LHS with\n         | appcontext[opt.id] => unfold opt.id at 1\n         | appcontext[opt2.id] => unfold opt2.id at 1\n         | appcontext[opt3.id] => unfold opt3.id at 1\n         end\n    | [ |- ?e = opt.id ?x ]\n      => progress change (e = x)\n    | [ |- ?e = opt2.id ?x ]\n      => progress change (e = x)\n    | [ |- _ = opt2.map _ _ ]\n      => apply ((_ : Proper (pointwise_relation _ _ ==> eq ==> eq) (@List.map _ _))\n                : Proper (pointwise_relation _ _ ==> eq ==> eq) (@opt2.map _ _));\n        [ let x := fresh in intro x; change x with (opt2.id x)\n        | ]\n    | [ |- _ = opt.map _ _ ]\n      => apply ((_ : Proper (pointwise_relation _ _ ==> eq ==> eq) (@List.map _ _))\n                : Proper (pointwise_relation _ _ ==> eq ==> eq) (@opt.map _ _));\n        [ let x := fresh in intro x; change x with (opt.id x)\n        | ]\n    | [ |- _ = @opt.fold_left ?A ?B orb _ false ]\n      => refine (_ : opt.fold_left orb _ false = _);\n        apply ((_ : Proper (_ ==> _ ==> _ ==> _) (@fold_left A B))\n               : Proper _ (@opt.fold_left A B));\n        repeat (let x := fresh in intro x; change x with (opt.id x))\n    | [ |- _ = @opt.fold_left ?A ?B orbr _ false ]\n      => refine (_ : opt.fold_left orbr _ false = _);\n        apply ((_ : Proper (_ ==> _ ==> _ ==> _) (@fold_left A B))\n               : Proper _ (@opt.fold_left A B));\n        repeat (let x := fresh in intro x; change x with (opt.id x))\n    | [ |- _ = @opt.list_caset ?A (fun _ => ?P) _ _ _ ]\n      => refine (_ : @opt.list_caset A (fun _ => P) _ _ _ = _);\n        apply ((_ : Proper (_ ==> pointwise_relation _ (pointwise_relation _ _) ==> _ ==> _) (@list_caset A (fun _ => P)))\n               : Proper _ (@opt.list_caset A (fun _ => P)));\n        repeat (let x := fresh in intro x; change x with (opt.id x))\n    | _ => progress cbv beta\n    | [ |- _ = opt2.nth _ _ _ ]\n      => apply (f_equal2 (opt2.nth _))\n    | [ |- _ = opt2.bool_rect ?P _ _ _ ]\n      => apply (f_equal3 (opt2.bool_rect P))\n    | _ => progress fin_step_opt\n    | [ |- _ = orb _ _ ] => apply (f_equal2 orb)\n    | [ |- _ = orbr _ _ ] => apply (f_equal2 orbr)\n    | [ |- _ = andb _ _ ] => apply (f_equal2 andb)\n    | [ |- _ = andbr _ _ ] => apply (f_equal2 andbr)\n    | [ |- ?e = List.map ?f (opt2.id ?x) ]\n      => progress change (e = opt2.map f x)\n    | [ |- context G[List.map ?f (opt.id ?ls)] ]\n      => let G' := context G[opt.id (opt.map f ls)] in\n         change G'\n    | [ |- context G[bool_rect ?x ?y ?z (opt.id ?w)] ]\n      => let G' := context G[opt.id (opt.bool_rect x y z w)] in\n         change G'\n    | [ |- context G[bool_rect ?x ?y ?z (opt2.id ?w)] ]\n      => let G' := context G[opt2.id (opt2.bool_rect x y z w)] in\n         change G'\n    | [ |- context G[list_caset ?x ?y ?z (opt.id ?w)] ]\n      => let G' := context G[opt.id (opt.list_caset x y z w)] in\n         change G'\n    | [ |- context G[item_rect ?x ?y ?z (opt.id ?w)] ]\n      => let G' := context G[opt.id (opt.item_rect x y z w)] in\n         change G'\n    | [ |- context G[List.fold_left orb (opt.id ?ls) false] ]\n      => let G' := context G[opt.id (opt.fold_left orb ls false)] in\n         change G'\n    | [ |- context G[List.fold_left orbr (opt.id ?ls) false] ]\n      => let G' := context G[opt.id (opt.fold_left orbr ls false)] in\n         change G'\n    | [ |- _ = list_rect ?P ?N ?C (opt.id ?ls) (opt2.id ?idx) ?offset ?len ?pf ]\n      => t_reduce_list_evar;\n        [\n               | match goal with\n                 | [ |- ?e ?x ?xs ?H ?a ?b ?c ?d = _ ]\n                   => is_evar e;\n                     change x with (opt.id x);\n                     change xs with (opt.id xs);\n                     change a with (opt2.id a)\n                 end ]\n    | [ |- _ = opt.item_rect ?T ?A ?B ?c ] (* evar kludge following *)\n      => revert c;\n        let RHS := match goal with |- forall c', _ = ?RHS c' => RHS end in\n        let f := constr:(fun TC NC =>\n                           forall c, opt.item_rect T TC NC c = RHS c) in\n        let f := (eval cbv beta in f) in\n        let e1 := fresh in\n        let e2 := fresh in\n        match type of f with\n        | ?X -> ?Y -> _\n          => evar (e1 : X); evar (e2 : Y)\n        end;\n          intro c;\n          let ty := constr:(opt.item_rect T e1 e2 c = RHS c) in\n          etransitivity_rev _; [ refine (_ : ty) | reflexivity ];\n          revert c;\n          refine (item_rect\n                    (fun c => opt.item_rect T e1 e2 c = RHS c)\n                    _ _);\n          intro c; simpl @opt.item_rect; subst e1 e2;\n          change c with (opt.id c)\n    | [ |- _ = opt2.beq_nat _ _ ] => apply (f_equal2 opt2.beq_nat)\n    | [ |- _ = opt2.leb _ _ ] => apply (f_equal2 opt2.leb)\n    | [ |- _ = opt2.length _ ] => apply f_equal\n    | [ |- _ = opt.snd _ ] => apply f_equal\n    | [ |- _ = opt2.snd _ ] => apply f_equal\n    | [ |- _ = opt.fst _ ] => apply f_equal\n    | [ |- _ = opt2.fst _ ] => apply f_equal\n    | [ |- _ = opt.uniquize _ _ ] => reflexivity\n    | [ |- _ = opt.combine _ _ ] => reflexivity\n    | [ |- _ = char_at_matches _ _ _ ] => apply f_equal3\n    end.\n\n  Local Ltac safe_change_opt := repeat safe_change_opt'.\n  Local Ltac change_opt_reduce := repeat change_opt_reduce'.\n\n  Local Ltac do_flip_map ls :=\n    idtac;\n    progress\n      (repeat let A := match goal with |- appcontext[@List.map ?A ?B] => A end in\n              let B := match goal with |- appcontext[@List.map A ?B] => B end in\n              let flip_map := fresh \"flip_map\" in\n              pose (flip_map ls' f := @List.map A B f ls');\n                progress change (@List.map A B) with (fun f ls' => @flip_map ls' f);\n                cbv beta;\n                try change (@flip_map ls) with (@flip_map (opt.id ls)));\n    repeat match goal with\n           | [ flip_map := fun ls' f => @List.map _ _ f ls' |- _ ]\n             => subst flip_map\n           end;\n    cbv beta.\n\n  Definition parse_nonterminal_opt'3\n             (str : String)\n             (nt : String.string)\n  : { b : bool | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'2 str nt) in\n    let h := head c in\n    let p := (eval cbv beta iota zeta delta [proj1_sig h] in (proj1_sig c)) in\n    sigL_transitivity p; [ | abstract exact (proj2_sig c) ].\n    evar (b' : bool).\n    sigL_transitivity b'; subst b'.\n    Focus 2.\n    { progress unfold rdp_list_of_nonterminal; simpl.\n      unfold pregrammar_nonterminals; simpl.\n      match goal with\n        | [ |- _ = ?f ?x ]\n          => set (F := f)\n      end.\n      rewrite map_length.\n      subst F.\n      (** TODO: Come up with a robust (possibly reflective) version of\n      this, based or wheich things are recursively accessible *)\n      change @nth' with @opt3.nth' at 1.\n      change @List.map with @opt2.map at 1.\n      change (pregrammar_productions G) with (opt.id (pregrammar_productions G)).\n      change nt with (opt.id nt).\n      change str with (opt.id str).\n      safe_change_opt.\n      change (opt.id (pregrammar_productions G)) with (pregrammar_productions G).\n      change (opt.id nt) with nt.\n      change (opt.id str) with str.\n      reflexivity. }\n    Unfocus.\n    refine_Fix2_5_Proper_eq.\n    etransitivity_rev _.\n    { fix2_trans;\n      [\n      | solve [ change @opt3.nth' with @nth';\n                change @opt2.map with @List.map;\n                t_reduce_fix;\n                t_postreduce_list;\n                unfold item_rect;\n                t_reduce_fix ] ].\n\n      do_flip_map (pregrammar_productions G).\n\n      step_opt'; [ | reflexivity ].\n      apply (f_equal2 (opt3.nth' _)); [ | reflexivity ].\n      change_opt_reduce.\n      step_opt';\n        change_opt_reduce; [ | | | ].\n      { match goal with\n        | [ |- _ = ?f (opt2.id ?x) ?y ?z ?w ]\n          => refine (f_equal (fun x' => f x' y z w) _)\n        end.\n        change_opt_reduce; [].\n        match goal with\n        | [ |- _ = if opt2.id _ then opt2.id _ else opt2.id _ ]\n          => unfold opt2.id; reflexivity\n        end. }\n      { match goal with\n        | [ |- _ = ?f _ _ _ (opt.id (opt.first_index_default _ _ _)) ]\n          => unfold opt.id\n        end.\n        reflexivity. }\n      { match goal with\n        | [ |- _ = ?f (opt2.id ?x) ?y ?z ?w ]\n          => refine (f_equal (fun x' => f x' y z w) _)\n        end.\n        change_opt_reduce; [].\n        match goal with\n        | [ |- _ = if opt2.id _ then opt2.id _ else opt2.id _ ]\n          => unfold opt2.id; reflexivity\n        end. }\n      { change @List.map with @opt2.map at 1. (** FIXME: is this right? *)\n        change_opt_reduce; [ | | progress unfold opt2.id; reflexivity ].\n        { match goal with\n          | [ |- _ = ?f _ _ _ (opt.id (opt.first_index_default _ _ _)) ]\n            => unfold opt.id\n          end.\n          reflexivity. }\n        { match goal with\n          | [ |- _ = ?f (opt2.id ?x) ?y ?z ?w ]\n            => refine (f_equal (fun x' => f x' y z w) _)\n          end.\n          change_opt_reduce; [].\n          match goal with\n          | [ |- _ = if opt2.id _ then opt2.id _ else opt2.id _ ]\n            => unfold opt2.id; reflexivity\n          end. } } }\n    change @fold_left with @opt3.fold_left at 1.\n    change @list_rect with @opt.list_rect at 1.\n    reflexivity.\n  Defined.\n\n  Definition parse_nonterminal_opt\n             (str : String)\n             (nt : String.string)\n  : { b : bool | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'3 str nt) in\n    let h := head c in\n    let impl := (eval cbv beta iota zeta delta [h proj1_sig item_rect list_caset] in (proj1_sig c)) in\n    (exists impl);\n      abstract (exact (proj2_sig c)).\n  Defined.\n\n  Lemma parse_nonterminal_opt_eq\n        {HSLP : StringLikeProperties Char}\n        {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}\n        (str : String)\n        (nt : String.string)\n    : proj1_sig (parse_nonterminal_opt str nt) = parse_nonterminal (data := data) str nt.\n  Proof.\n    rewrite <- parse_nonterminal_optdata_eq.\n    apply proj2_sig.\n  Qed.\nEnd recursive_descent_parser.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/BooleanRecognizerOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1923399817715115}}
{"text": "From mathcomp Require Import\n     all_ssreflect.\n\nFrom AUChain 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    ; txs : Transactions\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 txs pt bid, MkBlock sl' txs' pt' bid' =>\n    [&& sl == sl', txs == txs', pt == pt' & bid == bid']\n  end.\n\nLemma eq_blockP : Equality.axiom eq_block.\nProof.\n  case => sl txs pt bid; case => sl'f txs' 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": "AU-COBRA", "repo": "PoS-NSB", "sha": "8cb62e382f17626150a4b75e44af4d270474d3e7", "save_path": "github-repos/coq/AU-COBRA-PoS-NSB", "path": "github-repos/coq/AU-COBRA-PoS-NSB/PoS-NSB-8cb62e382f17626150a4b75e44af4d270474d3e7/Protocol/Blocks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19229517670859297}}
{"text": "(** * Every parse tree has a corresponding minimal parse tree *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Program.Program Coq.Classes.RelationClasses Coq.Classes.Morphisms Coq.Setoids.Setoid Coq.Arith.Compare_dec.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Program.Wf Coq.Arith.Wf_nat.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core Fiat.Parsers.ContextFreeGrammar.Properties Fiat.Parsers.WellFoundedParse.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Export Fiat.Parsers.MinimalParse.\nRequire Export Fiat.Parsers.WellFoundedParseProperties.\nRequire Import Fiat.Common Fiat.Common.Le Fiat.Common.Wf.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nLocal Notation \"f \u2218 g\" := (fun x => f (g x)).\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n  Context (nonterminals_listT_R_respectful : forall x y,\n                                        sub_nonterminals_listT x y\n                                        -> x <> y\n                                        -> nonterminals_listT_R x y).\n\n  Lemma strle_from_min_parse_of_production {len0 valid strs pats}\n        (p1 : minimal_parse_of_production (G := G) len0 valid strs pats)\n  : length strs <= len0.\n  Proof.\n    destruct p1; omega.\n  Qed.\n\n  Definition parse_of_item_nonterminal__of__minimal_parse_of_nonterminal'\n             (parse_of__of__minimal_parse_of\n              : forall len0 valid str prods,\n                  minimal_parse_of (G := G) len0 valid str prods\n                  -> parse_of G str prods)\n             {len0 valid str nonterminal} (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal)\n  : parse_of_item G str (NonTerminal nonterminal)\n    := let p'\n           := (@parse_of__of__minimal_parse_of\n                 _ _ _ _\n                 (match p as p in (@MinimalParse.minimal_parse_of_nonterminal _ _ _ _ _ len0 valid str nonterminal)\n                        return minimal_parse_of (match p with\n                                                   | MinParseNonTerminalStrLt _ _ _ _ _ _ _ => _\n                                                   | MinParseNonTerminalStrEq _ _ _ _ _ _ _ _ => _\n                                                 end)\n                                                (match p with\n                                                   | MinParseNonTerminalStrLt _ _ _ _ _ _ _ => _\n                                                   | MinParseNonTerminalStrEq _ _ _ _ _ _ _ _ => _\n                                                 end)\n                                                str (Lookup G nonterminal) with\n                    | MinParseNonTerminalStrLt len0 valid nonterminal str pf pf' p' => p'\n                    | MinParseNonTerminalStrEq len0 str valid nonterminal pf H H' p' => p'\n                  end)) in\n       let pf := (match p in (@MinimalParse.minimal_parse_of_nonterminal _ _ _ _ _ len0 valid str nonterminal)\n                        return (is_valid_nonterminal initial_nonterminals_data (of_nonterminal nonterminal))\n                  with\n                    | MinParseNonTerminalStrLt _ _ _ _ _ pf _ => pf\n                    | MinParseNonTerminalStrEq _ _ _ _ _ pf _ _ => pf\n                  end) in\n       (ParseNonTerminal\n          nonterminal\n          (proj1 (initial_nonterminals_correct _) pf)\n          p').\n\n  Definition parse_of_item__of__minimal_parse_of_item'\n             (parse_of__of__minimal_parse_of\n              : forall len0 valid str prods,\n                  minimal_parse_of (G := G) len0 valid str prods\n                  -> parse_of G str prods)\n             {len0 valid str it} (p : minimal_parse_of_item (G := G) len0 valid str it)\n  : parse_of_item G str it\n    := match p in (MinimalParse.minimal_parse_of_item len0 valid str it)\n             return parse_of_item G str it\n       with\n         | MinParseTerminal len0 valid str ch P pf1 pf2\n           => ParseTerminal G str ch P pf1 pf2\n         | MinParseNonTerminal len0 valid _ _ p'\n           => @parse_of_item_nonterminal__of__minimal_parse_of_nonterminal' (@parse_of__of__minimal_parse_of) _ _ _ _ p'\n       end.\n\n  Fixpoint parse_of__of__minimal_parse_of {len0 valid str pats} (p : minimal_parse_of (G := G) len0 valid str pats)\n  : parse_of G str pats\n    := match p with\n         | MinParseHead len0 valid str pat pats p'\n           => let p'' := (parse_of_production__of__minimal_parse_of_production p') in\n              ParseHead pats p''\n         | MinParseTail len0 valid str pat pats p'\n           => let p'' := (parse_of__of__minimal_parse_of p') in\n              ParseTail pat p''\n       end\n  with parse_of_production__of__minimal_parse_of_production {len0 valid str pat} (p : minimal_parse_of_production (G := G) len0 valid str pat)\n       : parse_of_production G str pat\n       := match p with\n            | MinParseProductionNil len0 valid str pf\n              => ParseProductionNil _ _ pf\n            | MinParseProductionCons len0 valid str strs pat pats pf p' p''\n              => let p0 := (parse_of_item__of__minimal_parse_of_item' (@parse_of__of__minimal_parse_of) p') in\n                 let p1 := (parse_of_production__of__minimal_parse_of_production p'') in\n                 ParseProductionCons _ _ p0 p1\n          end.\n\n  Definition parse_of_item_nonterminal__of__minimal_parse_of_nonterminal\n  : forall {len0 valid str nonterminal} (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal),\n      parse_of_item G str (NonTerminal nonterminal)\n    := @parse_of_item_nonterminal__of__minimal_parse_of_nonterminal' (@parse_of__of__minimal_parse_of).\n\n  Definition parse_of_item__of__minimal_parse_of_item\n  : forall {len0 valid str it},\n      minimal_parse_of_item (G := G) len0 valid str it\n      -> parse_of_item G str it\n    := @parse_of_item__of__minimal_parse_of_item' (@parse_of__of__minimal_parse_of).\n\n  (** Re-add this so rewrite works *)\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; apply (@remove_nonterminal_mor _ G); try assumption; reflexivity.\n  Qed.\n\n  Local Ltac clear_not_beq\n    := repeat match goal with\n                | [ H : ?T |- _ ]\n                  => match T with\n                       | beq _ _ => fail 1\n                       | _ < _ => fail 1\n                       | _ \u2264s _ => fail 1\n                       | _ = _ => fail 1\n                       | _ <= _ => fail 1\n                       | _ ~= [ _ ] => fail 1\n                       | StringLikeProperties _ => fail 1\n                       | _ => clear H\n                     end\n              end.\n\n  Local Ltac solve_by_subst tac :=\n    repeat subst;\n    match goal with\n      | [ |- beq _ _ ] => idtac\n      | [ |- beq _ _ \\/ _ ] => idtac\n      | [ |- _ \\/ beq _ _ ] => idtac\n      | [ |- _ = _ \\/ _ ] => idtac\n      | [ |- _ \\/ _ = _ ] => idtac\n      | [ |- _ < _ ] => idtac\n      | [ |- _ <= _ ] => idtac\n      | [ |- _ = _ ] => idtac\n      | [ |- _ \u2264s _ ] => idtac\n      | [ |- False ] => idtac\n    end;\n    clear_not_beq;\n    repeat match goal with\n             | [ H : @beq ?string ?SLM ?SL _ _ |- _ ] => setoid_subst_rel (@beq string SLM SL)\n           end;\n    solve [ assumption | reflexivity | left; reflexivity | right; reflexivity | tac ].\n\n  Section expand.\n    Local Notation Hlen0T len0 len0' str str'\n      := (len0 <= len0'\n          \\/ (length str < len0 /\\ length str' < len0')\n          \\/ (length str = len0%nat /\\ length str' = len0'%nat)) (only parsing).\n\n    Definition expand_minimal_parse_of_nonterminal'\n               (expand_minimal_parse_of\n                : forall {len0 len0' valid valid' str str' prods}\n                         (Hlen0 : Hlen0T len0 len0' str str')\n                         (H : sub_nonterminals_listT valid valid')\n                         (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n                         (Hstr : str =s str')\n                         (p : minimal_parse_of (G := G) len0 valid str prods),\n                    minimal_parse_of (G := G) len0' valid' str' prods)\n               {len0 len0' valid valid' str str' nonterminal}\n               (Hlen0 : Hlen0T len0 len0' str str')\n               (H : sub_nonterminals_listT valid valid')\n               (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n               (Hstr : str =s str')\n               (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal)\n    : minimal_parse_of_nonterminal (G := G) len0' valid' str' nonterminal.\n    Proof.\n      destruct p;\n      first [ apply MinParseNonTerminalStrLt;\n              destruct_head or;\n              destruct_head and; repeat subst;\n              solve [ rewrite <- Hstr; omega\n                    | assumption\n                    | eapply expand_minimal_parse_of; [ .. | eassumption ];\n                      solve [ reflexivity\n                            | left; rewrite Hstr; reflexivity\n                            | rewrite Hstr; reflexivity ] ]\n            | idtac ];\n      [].\n      { destruct (lt_eq_lt_dec len0 len0') as [[Hlen0'|Hlen0']|Hlen0'];\n        [ apply MinParseNonTerminalStrLt\n        | apply MinParseNonTerminalStrEq\n        | destruct (lt_eq_lt_dec (length str') len0') as [[Hlen0''|Hlen0'']|Hlen0''];\n          [ apply MinParseNonTerminalStrLt\n          | apply MinParseNonTerminalStrEq\n          | exfalso ] ];\n        solve [ assumption\n              | apply H; assumption\n              | solve_by_subst idtac\n              | eapply expand_minimal_parse_of; [ .. | eassumption ];\n                solve [ reflexivity\n                      | rewrite !H;\n                        eauto using sub_nonterminals_listT_remove;\n                        reflexivity\n                      | solve_by_subst idtac\n                      | destruct Hinit as [Hinit|Hinit];\n                        [ exfalso; clear_not_beq; setoid_subst_rel beq; omega\n                        | ];\n                        rewrite ?H, !Hinit;\n                        eauto using sub_nonterminals_listT_remove;\n                        reflexivity\n                      | destruct_head or; destruct_head and; repeat subst; omega ]\n              | destruct_head or; destruct_head and; repeat subst; omega\n              | setoid_subst_rel beq; subst; assumption ]. }\n    Defined.\n\n    Definition expand_minimal_parse_of_item'\n               (expand_minimal_parse_of\n                : forall {len0 len0' valid valid' str str' prods}\n                         (Hlen0 : Hlen0T len0 len0' str str')\n                         (H : sub_nonterminals_listT valid valid')\n                         (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n                         (Hstr : str =s str')\n                         (p : minimal_parse_of (G := G) len0 valid str prods),\n                    minimal_parse_of (G := G) len0' valid' str' prods)\n               {len0 len0' valid valid' str str' it}\n               (Hlen0 : Hlen0T len0 len0' str str')\n               (H : sub_nonterminals_listT valid valid')\n               (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n               (Hstr : str =s str')\n               (p : minimal_parse_of_item (G := G) len0 valid str it)\n    : minimal_parse_of_item (G := G) len0' valid' str' it.\n    Proof.\n      destruct p.\n      { eapply MinParseTerminal; setoid_subst_rel beq; trivial; eassumption. }\n      { apply MinParseNonTerminal; [].\n        eapply expand_minimal_parse_of_nonterminal'; [..| eassumption ];\n        try assumption. }\n    Defined.\n\n    Lemma expand_helper_1 {len0 len0' str str'}\n          (pf : length str <= len0)\n          (Hlen0 : Hlen0T len0 len0' str str')\n          (Hstr : str =s str')\n    : length str' <= len0'.\n    Proof.\n      setoid_subst_rel beq.\n      destruct_head or; omega.\n    Qed.\n\n    Lemma Hlen0_take {len0 len0' str str' n}\n          (Hlen0 : Hlen0T len0 len0' str str')\n          (Hstr : str =s str')\n    : Hlen0T len0 len0' (take n str) (take n str').\n    Proof.\n      setoid_subst str'.\n      rewrite take_length.\n      apply Min.min_case_strong; omega.\n    Qed.\n\n    Lemma Hlen0_drop {len0 len0' str str' n}\n          (Hlen0 : Hlen0T len0 len0' str str')\n          (Hstr : str =s str')\n    : Hlen0T len0 len0' (drop n str) (drop n str').\n    Proof.\n      setoid_subst str'.\n      rewrite drop_length.\n      omega.\n    Qed.\n\n    Fixpoint expand_minimal_parse_of\n             {len0 len0' valid valid' str str' pats}\n             (Hlen0 : Hlen0T len0 len0' str str')\n             (H : sub_nonterminals_listT valid valid')\n             (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n             (Hstr : str =s str')\n             (p : minimal_parse_of (G := G) len0 valid str pats)\n    : minimal_parse_of (G := G) len0' valid' str' pats\n      := match p in (MinimalParse.minimal_parse_of len0 valid str pats)\n               return ((Hlen0T len0 len0' str str')\n                       -> sub_nonterminals_listT valid valid'\n                       -> len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data\n                       -> str =s str'\n                       -> minimal_parse_of (G := G) len0' valid' str' pats)\n         with\n           | MinParseHead len0 valid str pat pats p'\n             => fun Hlen0 H Hinit Hstr => MinParseHead pats (@expand_minimal_parse_of_production _ _ _ _ _ _ _ Hlen0 H Hinit Hstr p')\n           | MinParseTail len0 valid str pat pats p'\n             => fun Hlen0 H Hinit Hstr => MinParseTail pat (@expand_minimal_parse_of _ _ _ _ _ _ _ Hlen0 H Hinit Hstr p')\n         end Hlen0 H Hinit Hstr\n    with expand_minimal_parse_of_production\n           {len0 len0' valid valid' str str' pat}\n           (Hlen0 : Hlen0T len0 len0' str str')\n           (H : sub_nonterminals_listT valid valid')\n           (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n           (Hstr : str =s str')\n           (p : minimal_parse_of_production (G := G) len0 valid str pat)\n         : minimal_parse_of_production (G := G) len0' valid' str' pat\n         := match p in (MinimalParse.minimal_parse_of_production len0 valid str pats)\n                  return (Hlen0T len0 len0' str str'\n                          -> sub_nonterminals_listT valid valid'\n                          -> len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data\n                          -> str =s str'\n                          -> minimal_parse_of_production len0' valid' str' pats)\n            with\n              | MinParseProductionNil len0 valid str pf\n                => fun _ _ _ Hstr => MinimalParse.MinParseProductionNil _ _ str' (transitivity (symmetry ((_ : Proper (beq ==> eq) length) _ _ Hstr))  pf)\n              | MinParseProductionCons len0 valid str n pat pats pf p' p''\n                => fun Hlen0 H Hinit Hstr\n                   => MinParseProductionCons\n                        _\n                        n\n                        (expand_helper_1 pf Hlen0 Hstr)\n                        (expand_minimal_parse_of_item' (@expand_minimal_parse_of) (Hlen0_take Hlen0 Hstr) H Hinit ((_ : Proper (eq ==> beq ==> beq) take) _ _ eq_refl _ _ Hstr) p')\n                        (@expand_minimal_parse_of_production _ _ _ _ _ _ _ (Hlen0_drop Hlen0 Hstr) H Hinit ((_ : Proper (eq ==> beq ==> beq) drop) _ _ eq_refl _ _ Hstr) p'')\n            end Hlen0 H Hinit Hstr.\n\n    Definition expand_minimal_parse_of_nonterminal\n    : forall {len0 len0' valid valid' str str' nonterminal}\n             (Hlen0 : Hlen0T len0 len0' str str')\n             (H : sub_nonterminals_listT valid valid')\n             (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n             (Hstr : str =s str')\n             (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal),\n        minimal_parse_of_nonterminal (G := G) len0' valid' str' nonterminal\n      := @expand_minimal_parse_of_nonterminal' (@expand_minimal_parse_of).\n\n    Definition expand_minimal_parse_of_item\n    : forall {len0 len0' valid valid' str str' it}\n             (Hlen0 : Hlen0T len0 len0' str str')\n             (H : sub_nonterminals_listT valid valid')\n             (Hinit : len0 = len0' \\/ sub_nonterminals_listT valid' initial_nonterminals_data)\n             (Hstr : str =s str')\n             (p : minimal_parse_of_item (G := G) len0 valid str it),\n        minimal_parse_of_item (G := G) len0' valid' str' it\n      := @expand_minimal_parse_of_item' (@expand_minimal_parse_of).\n  End expand.\n\n  Section expand_beq.\n    Definition expand_minimal_parse_of_beq\n             {len0 valid str str' pats}\n             (Hstr : str =s str')\n             (p : minimal_parse_of (G := G) len0 valid str pats)\n    : minimal_parse_of (G := G) len0 valid str' pats.\n    Proof.\n      eapply expand_minimal_parse_of; try (eassumption || reflexivity || left; reflexivity).\n    Defined.\n\n    Definition expand_minimal_parse_of_production_beq\n               {len0 valid str str' pat}\n               (Hstr : str =s str')\n               (p : minimal_parse_of_production (G := G) len0 valid str pat)\n    : minimal_parse_of_production (G := G) len0 valid str' pat.\n    Proof.\n      eapply expand_minimal_parse_of_production; try (eassumption || reflexivity || left; reflexivity).\n    Defined.\n\n    Definition expand_minimal_parse_of_nonterminal_beq\n               {len0 valid str str' nonterminal}\n               (Hstr : str =s str')\n               (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal)\n    : minimal_parse_of_nonterminal (G := G) len0 valid str' nonterminal.\n    Proof.\n      eapply expand_minimal_parse_of_nonterminal; try (eassumption || reflexivity || left; reflexivity).\n    Defined.\n\n    Definition expand_minimal_parse_of_item_beq\n               {len0 valid str str' it}\n               (Hstr : str =s str')\n               (p : minimal_parse_of_item (G := G) len0 valid str it)\n    : minimal_parse_of_item (G := G) len0 valid str' it.\n    Proof.\n      eapply expand_minimal_parse_of_item; try (eassumption || reflexivity || left; reflexivity).\n    Defined.\n  End expand_beq.\n\n\n  Section contract.\n    Local Hint Constructors MinimalParse.minimal_parse_of_nonterminal.\n\n    Definition contract_minimal_parse_of_nonterminal_lt\n               {len0 str valid valid' nonterminal}\n               (Hlt : length str < len0)\n               (p : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal)\n    : minimal_parse_of_nonterminal (G := G) len0 valid' str nonterminal.\n    Proof.\n      destruct p.\n      { constructor (assumption). }\n      { exfalso; clear_not_beq; setoid_subst_rel beq; omega. }\n    Defined.\n\n    Definition contract_minimal_parse_of_item_lt\n               {len0 str valid valid' it}\n               (Hlt : length str < len0)\n               (p : minimal_parse_of_item (G := G) len0 valid str it)\n    : minimal_parse_of_item (G := G) len0 valid' str it.\n    Proof.\n      destruct p as [p|p].\n      { econstructor; trivial; eassumption. }\n      { constructor (eapply contract_minimal_parse_of_nonterminal_lt; eassumption). }\n    Defined.\n\n    Definition contract_minimal_parse_of_production_lt\n               {len0 str valid valid' pat}\n               (Hlt : length str < len0)\n               (p : minimal_parse_of_production (G := G) len0 valid str pat)\n    : minimal_parse_of_production (G := G) len0 valid' str pat.\n    Proof.\n      induction p.\n      { constructor; trivial. }\n      { apply (MinParseProductionCons _ n); trivial;\n        try first [ eapply contract_minimal_parse_of_item_lt; try eassumption\n                  | eapply IHp; try eassumption\n                  | assumption ];\n        clear -Hlt HSLP;\n        abstract (rewrite ?str_le_take, ?str_le_drop; assumption). }\n    Defined.\n\n    Definition contract_minimal_parse_of_lt\n               {len0 str valid valid' pats}\n               (Hlt : length str < len0)\n               (p : minimal_parse_of (G := G) len0 valid str pats)\n    : minimal_parse_of (G := G) len0 valid' str pats.\n    Proof.\n      induction p.\n      { constructor (eapply contract_minimal_parse_of_production_lt; eassumption). }\n      { constructor (eapply IHp; assumption). }\n    Defined.\n\n    Section contract_eq.\n      Lemma parse_of_contract_minimal_parse_of_item_lt\n            {len0} {str : String} {valid valid' : nonterminals_listT}\n            {Hlt : length str < len0}\n            {it}\n            (p : minimal_parse_of_item (G := G) len0 valid str it)\n      : parse_of_item__of__minimal_parse_of_item\n          (contract_minimal_parse_of_item_lt (valid' := valid') Hlt p)\n        = parse_of_item__of__minimal_parse_of_item p.\n      Proof.\n        destruct_head @MinimalParse.minimal_parse_of_item; simpl; try reflexivity.\n        destruct_head @MinimalParse.minimal_parse_of_nonterminal; try reflexivity.\n        unfold False_rect.\n        match goal with\n          | [ |- appcontext[match ?e with end] ] => destruct e\n        end.\n      Qed.\n\n      Lemma parse_of_contract_minimal_parse_of_production_lt\n            {len0} {str : String} {valid valid' : nonterminals_listT}\n            {Hlt : length str < len0}\n            {pat}\n            (p : minimal_parse_of_production (G := G) len0 valid str pat)\n      : parse_of_production__of__minimal_parse_of_production\n          (contract_minimal_parse_of_production_lt (valid' := valid') Hlt p)\n        = parse_of_production__of__minimal_parse_of_production p.\n      Proof.\n        induction p; simpl; try reflexivity.\n        rewrite IHp, parse_of_contract_minimal_parse_of_item_lt.\n        reflexivity.\n      Qed.\n\n      Lemma parse_of_contract_minimal_parse_of_lt\n            {len0} {str : String} {valid valid' : nonterminals_listT}\n            {Hlt : length str < len0}\n            {pats}\n            (p : minimal_parse_of (G := G) len0 valid str pats)\n      : parse_of__of__minimal_parse_of\n          (contract_minimal_parse_of_lt (valid' := valid') Hlt p)\n        = parse_of__of__minimal_parse_of p.\n      Proof.\n        induction p; simpl;\n        progress rewrite ?IHp, ?parse_of_contract_minimal_parse_of_production_lt;\n        reflexivity.\n      Qed.\n    End contract_eq.\n  End contract.\n\n  Section minimize.\n    Let alt_option h valid str\n      := { nonterminal : _ & (is_valid_nonterminal valid (of_nonterminal nonterminal) = false /\\ is_valid_nonterminal initial_nonterminals_data (of_nonterminal nonterminal))\n                      * { p : parse_of G str (Lookup G nonterminal)\n                        | size_of_parse p < h } }%type.\n\n    Lemma not_alt_all {h str} (ps : alt_option h initial_nonterminals_data str)\n    : False.\n    Proof.\n      destruct ps as [ ? [ H' _ ] ].\n      revert H'; clear; intros [? ?].\n      congruence.\n    Qed.\n\n    Definition alt_all_elim {h str T} (ps : T + alt_option h initial_nonterminals_data str)\n    : T.\n    Proof.\n      destruct ps as [|ps]; [ assumption | exfalso ].\n      eapply not_alt_all; eassumption.\n    Defined.\n\n    Definition expand_alt_option' {h h' str str' valid valid'}\n               (H : h <= h') (H' : sub_nonterminals_listT valid' valid) (H'' : str =s str')\n    : alt_option h valid str -> alt_option h' valid' str'.\n    Proof.\n      hnf in H'; unfold alt_option.\n      repeat match goal with\n               | [ |- sigT _ -> _ ] => intros_destruct\n               | [ |- sig _ -> _ ] => intros_destruct\n               | [ |- prod _ _ -> _ ] => intros_destruct\n               | [ |- and _ _ -> _ ] => intros_destruct\n               | _ => intro\n               | _ => progress subst\n               | _ => rewrite <- size_of_parse_respectful\n               | [ H : beq ?str ?str', p : parse_of ?G ?str ?n\n                   |- { p' : parse_of ?G ?str' ?n | _ } ]\n                 => exists (parse_of_respectful H (reflexivity _) p)\n               | [ |- sigT _ ] => esplit\n               | [ |- prod _ _ ] => split\n               | [ |- and _ _ ] => split\n               | [ H : _ = false |- _ = false ]\n                 => apply Bool.not_true_iff_false in H;\n                   apply Bool.not_true_iff_false;\n                   intro; apply H\n               | _ => eapply H'; eassumption\n               | _ => assumption\n               | [ |- _ < _ ] => eapply Lt.lt_trans; eassumption\n               | [ |- _ < _ ] => eapply Lt.lt_le_trans; eassumption\n             end.\n    Defined.\n\n    Definition expand_alt_option {h h' str str' valid valid'}\n               (H : h < h') (H' : sub_nonterminals_listT valid' valid) (H'' : str =s str')\n    : alt_option h valid str -> alt_option h' valid' str'.\n    Proof.\n      apply expand_alt_option'; try assumption.\n      apply Lt.lt_le_weak; assumption.\n    Defined.\n\n    Section wf_parts.\n      Let of_parse_item_T' h\n          {len0} {str : String} (pf : length str <= len0)\n          (valid : nonterminals_listT) {it : item Char}\n          (p : parse_of_item G str it)\n        := forall (p_small : size_of_parse_item p < h),\n             sub_nonterminals_listT valid initial_nonterminals_data\n             -> ({ p' : minimal_parse_of_item (G := G) len0 valid str it\n                 | size_of_parse_item (parse_of_item__of__minimal_parse_of_item p') <= size_of_parse_item p })%type\n                + alt_option (size_of_parse_item p) valid str.\n\n      Let of_parse_item_T len0 h\n        := forall str pf valid it p, @of_parse_item_T' h len0 str pf valid it p.\n\n      Let of_parse_production_T' h\n          {len0} {str : String} (pf : length str <= len0)\n          (valid : nonterminals_listT) {pat : production Char}\n          (p : parse_of_production G str pat)\n        := forall (p_small : size_of_parse_production p < h),\n             sub_nonterminals_listT valid initial_nonterminals_data\n             -> ({ p' : minimal_parse_of_production (G := G) len0 valid str pat\n                 | size_of_parse_production (parse_of_production__of__minimal_parse_of_production p') <= size_of_parse_production p })%type\n                + alt_option (size_of_parse_production p) valid str.\n\n      Let of_parse_production_T len0 h\n        := forall str pf valid pat p, @of_parse_production_T' h len0 str pf valid pat p.\n\n      Let of_parse_T' h\n          {len0} {str : String} (pf : length str <= len0)\n          (valid : nonterminals_listT) {pats : productions Char}\n          (p : parse_of G str pats)\n        := forall (p_small : size_of_parse p < h),\n             sub_nonterminals_listT valid initial_nonterminals_data\n             -> ({ p' : minimal_parse_of (G := G) len0 valid str pats\n                 | (size_of_parse (parse_of__of__minimal_parse_of p') <= size_of_parse p) })%type\n                + alt_option (size_of_parse p) valid str.\n\n      Let of_parse_T len0 h\n        := forall str pf valid pats p, @of_parse_T' h len0 str pf valid pats p.\n\n      Let of_parse_nonterminal_T {len0 str valid nonterminal} (p : parse_of G str (Lookup G nonterminal)) h\n        := forall Hvalid : List.In nonterminal (Valid_nonterminals G),\n             size_of_parse_item (ParseNonTerminal _ Hvalid p) < h\n             -> length str <= len0\n             -> sub_nonterminals_listT valid initial_nonterminals_data\n             -> ({ p' : minimal_parse_of_nonterminal (G := G) len0 valid str nonterminal\n                 | size_of_parse_item (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) <= size_of_parse_item (ParseNonTerminal _ Hvalid p) })%type\n                + alt_option (size_of_parse_item (ParseNonTerminal _ Hvalid p)) valid str.\n\n      Section item.\n        Context {len0 : nat} {str : String} {valid : nonterminals_listT}.\n\n        Definition minimal_parse_of_item__of__parse_of_item'\n                   h\n                   (minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                    : forall h' (pf : h' < S (S h)) {len0 str valid nonterminal}\n                             (p : parse_of G str (Lookup G nonterminal)),\n                        @of_parse_nonterminal_T len0 str valid nonterminal p h')\n        : of_parse_item_T len0 h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit'.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [ ch P pf0 pf0' |nonterminal' ? p'].\n          { left.\n            eexists (MinimalParse.MinParseTerminal _ _ _ _ _ pf0 pf0');\n              simpl; constructor. }\n          { edestruct (fun pf => @minimal_parse_of_nonterminal__of__parse_of_nonterminal (S h') pf len0 _ valid' _ p') as [ [p'' H''] | p'' ];\n            try solve [ repeat (apply Lt.lt_n_Sn || apply Lt.lt_S)\n                      | exact Hinit'\n                      | exact H_h\n                      | exact H_forall\n                      | exact pf ];\n            [|];\n            [ left | right ].\n            { exists (MinParseNonTerminal p'').\n              simpl in *.\n              exact H''. }\n            { exact p''. } }\n        Defined.\n      End item.\n\n      Section production.\n        Context {len0 : nat} {str : String} {valid : nonterminals_listT}.\n\n        Local Ltac min_parse_prod_t' :=\n          idtac;\n          match goal with\n            | _ => assumption\n            | [ |- ?R ?x ?x ]\n              => reflexivity\n            | _ => progress destruct_head prod\n            | [ H : False |- _ ]\n              => solve [ destruct H ]\n            | _ => progress simpl\n            | _ => progress subst\n            | _ => progress rewrite ?parse_of_contract_minimal_parse_of_item_lt, ?parse_of_contract_minimal_parse_of_production_lt, ?parse_of_contract_minimal_parse_of_lt\n            | [ |- context G[size_of_parse_production (ParseProductionCons ?s ?n ?a ?b)] ]\n              => let G' := context G[S (size_of_parse_item a + size_of_parse_production b)] in\n                 change G'\n            | [ H : alt_option _ initial_nonterminals_data _ |- _ ]\n              => apply not_alt_all in H\n            | [ p0 : minimal_parse_of_item ?ns' ?v (take ?n ?s) ?pat,\n                     p1 : minimal_parse_of_production ?ns' ?v (drop ?n ?s) ?pats,\n                          H : length ?s <= ?ns'\n                |- ({ p' : minimal_parse_of_production ?ns' ?v ?s (?pat :: ?pats) | _ } + _)%type ]\n              => left; exists (MinParseProductionCons _ n H p0 p1)\n            | [ p0 : minimal_parse_of_item ?ns' _ (take ?n ?s) ?pat,\n                     p1 : minimal_parse_of_production ?ns' ?v (drop ?n ?s) ?pats,\n                          H : length ?s <= ?ns'\n                |- ({ p' : minimal_parse_of_production ?ns' ?v ?s (?pat :: ?pats) | _ } + _)%type ]\n              => let H' := fresh in\n                 assert (H' : length (take n s) < ns')\n                   by (rewrite <- H, ?take_short_length by omega; omega);\n                   left; exists (MinParseProductionCons\n                                   _\n                                   n\n                                   H\n                                   (contract_minimal_parse_of_item_lt (valid' := v) H' p0)\n                                   p1)\n            | [ p0 : minimal_parse_of_item ?ns' ?v (take ?n ?s) ?pat,\n                     p1 : minimal_parse_of_production ?ns' _ (drop ?n ?s) ?pats,\n                          H : length ?s <= ?ns'\n                |- ({ p' : minimal_parse_of_production ?ns' ?v ?s (?pat :: ?pats) | _ } + _)%type ]\n              => let H' := fresh in\n                 assert (H' : length (drop n s) < ns')\n                   by (rewrite <- H, drop_length; omega);\n                   left; exists (MinParseProductionCons\n                                   _\n                                   n\n                                   H\n                                   p0\n                                   (contract_minimal_parse_of_production_lt (valid' := v) H' p1))\n            | [ p0 : minimal_parse_of_item ?ns' _ (take ?n ?s) ?pat,\n                     p1 : minimal_parse_of_production ?ns' _ (drop ?n ?s) ?pats,\n                          H : length ?s <= ?ns',\n                              H' : ?n < length ?s,\n                                   H'' : 0 < ?n\n                |- ({ p' : minimal_parse_of_production ?ns' ?v ?s (?pat :: ?pats) | _ } + _)%type ]\n              => let H0' := fresh in\n                 let H1' := fresh in\n                 assert (H1' : length (drop n s) < ns')\n                   by (rewrite <- H, drop_length; omega);\n                   assert (H0' : length (take n s) < ns')\n                   by (rewrite <- H, ?take_short_length by omega; omega);\n                   left; eexists (MinParseProductionCons\n                                    _\n                                    n\n                                    H\n                                    (contract_minimal_parse_of_item_lt (valid' := v) H0' p0)\n                                    (contract_minimal_parse_of_production_lt (valid' := v) H1' p1))\n            | [ |- (_ * _)%type ]\n              => split\n            | [ H : _ <= _ |- _ <= _ ] => apply H\n            | _ => apply Le.le_n_S\n            | _ => apply Plus.plus_le_compat\n            | [ H0 : Forall_parse_of_item _ _,\n                     H1 : Forall_parse_of_production _ _\n                |- Forall_parse_of_production _ _ ]\n              => exact (H0, H1)\n            | [ H : alt_option _ ?v (drop 0 ?x)\n                |- (_ + alt_option _ ?v ?x)%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ H : alt_option _ ?v (drop ?n ?x), H' : length ?x <= ?n\n                |- (_ + alt_option _ ?v ?x)%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ H : alt_option _ ?v (take ?n ?x), H' : length ?x = ?n\n                |- (_ + alt_option _ ?v ?x)%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ H : alt_option _ ?v (take ?n ?x), H' : length ?x <= ?n\n                |- (_ + alt_option _ ?v ?x)%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ H : length ?s = 0 |- beq _ ?s ] => apply bool_eq_empty\n            | [ H : length ?s = 0 |- beq ?s _ ] => apply bool_eq_empty\n            | _ => rewrite take_short_length by assumption\n            | _ => rewrite take_long by assumption\n            | [ H : context[min _ _] |- _ ] => rewrite min_l in H by assumption\n            | [ H : context[min _ _] |- _ ] => rewrite min_r in H by assumption\n            | [ H : context[min _ _] |- _ ] => rewrite min_l in H by omega\n            | [ H : context[min _ _] |- _ ] => rewrite min_r in H by omega\n            | _ => rewrite drop_length\n            | _\n              => solve [ eauto using le_S, Le.le_trans, Plus.le_plus_l, Plus.le_plus_r, drop_0, take_long, NPeano.Nat.eq_le_incl, bool_eq_empty, drop_length, (fun x y => proj2 (NPeano.Nat.sub_0_le x y)) with nocore ]\n          end.\n        Local Ltac min_parse_prod_t := repeat min_parse_prod_t'.\n\n        (** This is the proof where we pay the proof for conceptual\n            mismatch.  We are, conceptually, simultaneously\n            \"minimizing parse trees\" and \"producing parse traces\".  It\n            is marginally nicer(!!) to contain the ugliness in this\n            single proof, rather than have it infect everything.  So\n            we must conceptually minimize the passed parse tree while\n            in fact building a trace of the parse algorithm.  To do\n            this, in the cons case, we need to figure out how we're\n            decreasing.  According with conceptual minimization, when\n            we have parsed [s0 ++ s1] as a cons of [p0] and [p1],\n            having a smaller parse tree for, say [s0], with any other\n            pattern, does us no good, unless [s1] is empty (and [s0 =\n            s0 ++ s1]), when we can simply pass that smaller parse up\n            the function call tree.  So we must eliminate the\n            \"alternate\" option, by expanding the valid list to the\n            initial data.  Luckily(?!), in the case where [s1] is\n            non-empty, [s0] is strictly smaller than [s0 ++ s1], and\n            thus we can rebuild the minimal parse tree to contract it.\n            This, finally, allows us to either build a minimal parse\n            tree for the thing we are asked about (or to contract the\n            \"alternate option\" parse tree, passing it back up?). *)\n\n        Fixpoint minimal_parse_of_production__of__parse_of_production'\n                 h\n                 (minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                  : forall h' (pf : h' < S (S h)) {len0 str valid nonterminal}\n                           (p : parse_of G str (Lookup G nonterminal)),\n                      @of_parse_nonterminal_T len0 str valid nonterminal p h')\n                 {struct h}\n        : of_parse_production_T len0 h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit'.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [ pf0' | n pat' pats' p0' p1' ].\n          { clear minimal_parse_of_production__of__parse_of_production'.\n            left.\n            eexists (@MinimalParse.MinParseProductionNil _ _ _ _ _ _ _ _ pf0');\n              repeat (reflexivity || esplit). }\n          { specialize (fun h' pf\n                        => @minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                             h' (transitivity pf (Lt.lt_n_Sn _))).\n            change (S ((size_of_parse_item p0')\n                       + (size_of_parse_production p1'))\n                    < S h') in H_h.\n            apply Lt.lt_S_n in H_h.\n            pose proof (Lt.le_lt_trans _ _ _ (Plus.le_plus_l _ _) H_h) as H_h0.\n            pose proof (Lt.le_lt_trans _ _ _ (Plus.le_plus_r _ _) H_h) as H_h1.\n            clear H_h.\n            assert (pf0' : length (take n str') <= length str')\n              by (rewrite take_length; apply Min.min_case_strong; omega).\n            assert (pf1' : length (drop n str') <= length str')\n              by (rewrite drop_length; omega).\n            pose proof (fun valid Hinit => @minimal_parse_of_item__of__parse_of_item' _ h'  minimal_parse_of_nonterminal__of__parse_of_nonterminal _ (transitivity pf0' pf) valid _ p0' H_h0 Hinit) as p_it.\n            pose proof (fun valid Hinit => @minimal_parse_of_production__of__parse_of_production' h' minimal_parse_of_nonterminal__of__parse_of_nonterminal _ (transitivity pf1' pf) valid _ p1' H_h1 Hinit) as p_prod.\n            clear pf0' pf1'.\n            destruct (le_lt_dec (length str') n) as [ Hle | Hle ], (zerop (min n (length str'))) as [Hstr' | Hstr' ].\n            { (* empty, empty *)\n              rewrite Min.min_r in Hstr' by assumption.\n              specialize (p_it valid' Hinit'); specialize (p_prod valid' Hinit').\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t. }\n            { (* nonempty, empty *)\n              specialize (p_it valid' Hinit'); specialize (p_prod initial_nonterminals_data (reflexivity _)).\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t. }\n            { (* empty, nonempty *)\n              specialize (p_it initial_nonterminals_data (reflexivity _)); specialize (p_prod valid' Hinit').\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t. }\n            { (* nonempty, nonempty *)\n              specialize (p_it initial_nonterminals_data (reflexivity _)); specialize (p_prod initial_nonterminals_data (reflexivity _)).\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t. } }\n        Defined.\n      End production.\n\n      Section productions.\n        Context {len0 : nat} {str : String} {valid : nonterminals_listT}.\n\n        Fixpoint minimal_parse_of_productions__of__parse_of_productions'\n                 h\n                 (minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                  : forall h' (pf : h' < S h) {len0 str valid nonterminal}\n                           (p : parse_of G str (Lookup G nonterminal)),\n                      @of_parse_nonterminal_T len0 str valid nonterminal p h')\n                 {struct h}\n        : of_parse_T len0 h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit'.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [pat pats p' | pat pats p'].\n          { clear minimal_parse_of_productions__of__parse_of_productions'.\n            edestruct (@minimal_parse_of_production__of__parse_of_production' _ h' minimal_parse_of_nonterminal__of__parse_of_nonterminal _ pf valid' _ p') as [ [p'' p''H] | [nonterminal' H'] ];\n            try solve [ exact (Lt.lt_S_n _ _ H_h)\n                      | exact H_forall\n                      | exact Hinit' ];\n            [|].\n            { left.\n              exists (MinParseHead pats p'').\n              simpl.\n              exact (Le.le_n_S _ _ p''H). }\n            { right.\n              exists nonterminal'.\n              split;\n                try solve [ exact (fst H') ];\n                [].\n              exists (proj1_sig (snd H')).\n              exact (Lt.lt_S _ _ (proj2_sig (snd H'))). } }\n          { specialize (fun h' pf\n                        => @minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                             h' (transitivity pf (Lt.lt_n_Sn _))).\n            edestruct (minimal_parse_of_productions__of__parse_of_productions' h'  minimal_parse_of_nonterminal__of__parse_of_nonterminal _ pf valid' _ p') as [ [p'' p''H] | [nonterminal' H'] ];\n            try solve [ exact (Lt.lt_S_n _ _ H_h)\n                      | exact Hinit'\n                      | exact H_forall ];\n            [|].\n            { left.\n              exists (MinParseTail pat p'').\n              simpl.\n              exact (Le.le_n_S _ _ p''H). }\n            { right.\n              exists nonterminal'.\n              split;\n                try solve [ exact (fst H') ];\n                [].\n              exists (proj1_sig (snd H')).\n              exact (Lt.lt_S _ _ (proj2_sig (snd H'))). } }\n        Defined.\n      End productions.\n\n      Section nonterminal.\n        Section step.\n          Definition minimal_parse_of_nonterminal__of__parse_of_nonterminal_step\n                     h\n                     (minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                      : forall h' (pf : h' < h) {len0 str valid nonterminal}\n                               (p : parse_of G str (Lookup G nonterminal)),\n                          @of_parse_nonterminal_T len0 str valid nonterminal p h')\n                     {len0 str valid nonterminal}\n                     (p : parse_of G str (Lookup G nonterminal))\n          : @of_parse_nonterminal_T len0 str valid nonterminal p h.\n          Proof.\n            destruct h as [|h]; [ clear; repeat intro; exfalso; omega | ].\n            intros Hvalid' pf Hstr Hinit'.\n            let H := match goal with H : length str <= len0 |- _ => constr:(H) end in\n\n            destruct (le_lt_eq_dec _ _ H) as [pf_lt|pf_eq].\n            { (** [str] got smaller, so we reset the valid nonterminals list *)\n              destruct (@minimal_parse_of_productions__of__parse_of_productions' (length str) h minimal_parse_of_nonterminal__of__parse_of_nonterminal str (reflexivity _) initial_nonterminals_data (Lookup G nonterminal) p (Lt.lt_S_n _ _ pf) (reflexivity _)) as [p'|p'].\n              { left.\n                exists (MinParseNonTerminalStrLt valid _ pf_lt (proj2 (initial_nonterminals_correct _) Hvalid') (proj1_sig p'));\n                  simpl.\n                simpl in *.\n                exact (Le.le_n_S _ _ (proj2_sig p')). }\n              { simpl.\n                right; eapply expand_alt_option; [..| exact p' ];\n                solve [ apply Lt.lt_n_Sn\n                      | assumption\n                      | reflexivity ]. } }\n            { (** [str] didn't get smaller, so we cache the fact that we've hit this nonterminal already *)\n              destruct (Sumbool.sumbool_of_bool (is_valid_nonterminal valid (of_nonterminal nonterminal))) as [ Hvalid | Hinvalid ].\n              { destruct (@minimal_parse_of_productions__of__parse_of_productions' len0 h minimal_parse_of_nonterminal__of__parse_of_nonterminal str Hstr (remove_nonterminal valid (of_nonterminal nonterminal)) (Lookup G nonterminal) p (Lt.lt_S_n _ _ pf) (transitivity (R := sub_nonterminals_listT) (@sub_nonterminals_listT_remove _ _ _ _ _ _) Hinit')) as [p'|p'].\n                { left.\n                  exists (@MinimalParse.MinParseNonTerminalStrEq _ _ _ _ _ _ _ _ _ pf_eq (proj2 (initial_nonterminals_correct _) Hvalid') Hvalid (proj1_sig p')).\n                  simpl in *.\n                  exact (Le.le_n_S _ _ (proj2_sig p')). }\n                { destruct p' as [nonterminal' p'].\n                  destruct (string_dec nonterminal nonterminal') as [|n].\n                  { subst nonterminal; simpl in *.\n                    edestruct (@minimal_parse_of_nonterminal__of__parse_of_nonterminal (S (size_of_parse p)) pf len0 _ valid nonterminal' (proj1_sig (snd p'))) as [p''|p''];\n                    try solve [ apply Lt.lt_n_S, (proj2_sig (snd p'))\n                              | subst; reflexivity\n                              | assumption\n                              | split; [ exact (proj2 (fst p'))\n                                       | exact (snd (proj2_sig (snd p'))) ] ];\n                    [|].\n                    { left.\n                      exists (proj1_sig p'').\n                      etransitivity;\n                        [ exact (proj2_sig p'')\n                        | exact (Lt.lt_le_weak _ _ (Lt.lt_n_S _ _ (proj2_sig (snd p')))) ]. }\n                    { right.\n                      exists (projT1 p'').\n                      split;\n                        [ exact (fst (projT2 p''))\n                        | ].\n                      exists (proj1_sig (snd (projT2 p''))).\n                      etransitivity;\n                        [ exact (proj2_sig (snd (projT2 p'')))\n                        | exact (Lt.lt_n_S _ _ (proj2_sig (snd p'))) ]. } }\n                  { right.\n                    exists nonterminal'.\n                    destruct p' as [p'H p'p].\n                    split.\n                    { rewrite remove_nonterminal_5\n                        in p'H\n                        by repeat match goal with\n                                    | _ => assumption\n                                    | _ => progress subst\n                                    | [ H : ?x <> ?x |- _ ] => destruct (H eq_refl)\n                                    | _ => progress destruct_head' and\n                                    | _ => intro\n                                    | [ H : of_nonterminal _ = of_nonterminal _ |- _ ]\n                                      => let H' := fresh in\n                                         pose proof (f_equal to_nonterminal H) as H';\n                                           progress\n                                             (rewrite !to_of_nonterminal\n                                               in H'\n                                               by (apply initial_nonterminals_correct;\n                                                   first [ assumption\n                                                         | rewrite <- H; assumption\n                                                         | rewrite -> H; assumption ]));\n                                           clear H\n                                  end.\n                      exact p'H. }\n                    { exists (proj1_sig p'p).\n                      exact (Lt.lt_S _ _ (proj2_sig p'p)). } } } }\n              { (** oops, we already saw this nonterminal in the past.  ABORT! *)\n                right.\n                exists nonterminal.\n                pose proof (proj2 (initial_nonterminals_correct _) Hvalid').\n                split; [ split; assumption\n                       | ].\n                exists p.\n                apply Lt.lt_n_Sn. } }\n          Defined.\n        End step.\n\n        Section wf.\n          Definition minimal_parse_of_nonterminal__of__parse_of_nonterminal'\n          : forall h\n                   {len0 str valid nonterminal}\n                   (p : parse_of G str (Lookup G nonterminal)),\n              @of_parse_nonterminal_T len0 str valid nonterminal p h\n            := @Fix\n                 _ lt lt_wf\n                 (fun h => forall {len0 str valid nonterminal}\n                                  (p : parse_of G str (Lookup G nonterminal)),\n                             @of_parse_nonterminal_T len0 str valid nonterminal p h)\n                 (@minimal_parse_of_nonterminal__of__parse_of_nonterminal_step).\n        End wf.\n      End nonterminal.\n    End wf_parts.\n\n    Definition minimal_parse_of_item__of__parse_of_item\n               {str : String}\n               {it : item Char}\n               (p : parse_of_item G str it)\n    : { p' : minimal_parse_of_item (G := G) (length str) initial_nonterminals_data str it\n      | (size_of_parse_item (parse_of_item__of__minimal_parse_of_item p') <= size_of_parse_item p) }%type.\n    Proof.\n      eapply alt_all_elim, minimal_parse_of_item__of__parse_of_item';\n      hnf; intros; try (assumption || reflexivity); [].\n      eapply minimal_parse_of_nonterminal__of__parse_of_nonterminal'; try assumption.\n      hnf; reflexivity.\n    Defined.\n\n    Definition minimal_parse_of_production__of__parse_of_production\n               {str : String}\n               {its : production Char}\n               (p : parse_of_production G str its)\n    : { p' : minimal_parse_of_production (G := G) (length str) initial_nonterminals_data str its\n      | size_of_parse_production (parse_of_production__of__minimal_parse_of_production p') <= size_of_parse_production p }%type.\n    Proof.\n      eapply alt_all_elim, minimal_parse_of_production__of__parse_of_production';\n      hnf; intros; try (assumption || reflexivity); [].\n      eapply minimal_parse_of_nonterminal__of__parse_of_nonterminal'; try assumption.\n      hnf; reflexivity.\n    Defined.\n\n    Definition minimal_parse_of_productions__of__parse_of_productions\n               {str : String}\n               {ps : productions Char}\n               (p : parse_of G str ps)\n    : { p' : minimal_parse_of (G := G) (length str) initial_nonterminals_data str ps\n      | size_of_parse (parse_of__of__minimal_parse_of p') <= size_of_parse p }%type.\n    Proof.\n      eapply alt_all_elim, minimal_parse_of_productions__of__parse_of_productions';\n      hnf; intros; try (assumption || reflexivity); [].\n      eapply minimal_parse_of_nonterminal__of__parse_of_nonterminal'; try assumption.\n      hnf; reflexivity.\n    Defined.\n\n    Definition minimal_parse_of_nonterminal__of__parse_of_nonterminal\n               {str : String}\n               {nonterminal : String.string}\n               (Hvalid : In nonterminal (Valid_nonterminals G))\n               (p : parse_of G str (Lookup G nonterminal))\n    : { p' : minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data str nonterminal\n      | size_of_parse_item (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) <= size_of_parse_item (ParseNonTerminal nonterminal Hvalid p) }%type.\n    Proof.\n      eapply alt_all_elim, minimal_parse_of_nonterminal__of__parse_of_nonterminal';\n      hnf; intros; try (assumption || reflexivity).\n    Defined.\n\n    Definition minimal_parse_of_nonterminal__of__parse_of_item_nonterminal_helper\n               {str : String}\n               {nonterminal : String.string}\n               its\n               (Hits : NonTerminal nonterminal = its)\n               (p : parse_of_item G str its)\n    : { p' : minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data str nonterminal\n      | size_of_parse_item (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) <= size_of_parse_item p }%type.\n    Proof.\n      destruct p.\n      { exfalso; clear -Hits.\n        abstract inversion Hits. }\n      { inversion Hits; subst.\n        apply minimal_parse_of_nonterminal__of__parse_of_nonterminal; assumption. }\n    Defined.\n\n    Definition minimal_parse_of_nonterminal__of__parse_of_item_nonterminal\n               {str : String}\n               {nonterminal : String.string}\n               (p : parse_of_item G str (NonTerminal nonterminal))\n    : { p' : minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data str nonterminal\n      | size_of_parse_item (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) <= size_of_parse_item p }%type.\n    Proof.\n      apply minimal_parse_of_nonterminal__of__parse_of_item_nonterminal_helper.\n      { reflexivity. }\n    Defined.\n  End minimize.\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/MinimalParseOfParse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.19216348762874366}}
{"text": "Global Set Warnings \"-ambiguous-paths\".\nGlobal Set Warnings \"-uniform-inheritance\".\nGlobal Set Warnings \"-auto-template\".\nGlobal Set Warnings \"-disj-pattern-notation\".\nGlobal Set Warnings \"-notation-overridden,-ambiguous-paths\".\n\nRequire Import Lia.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Sumbool.\n\nFrom mathcomp Require Import fintype.\n\nFrom Crypt Require Import choice_type Package Prelude.\nImport PackageNotation.\nFrom extructures Require Import ord fset fmap.\n\nFrom mathcomp.word Require Import ssrZ word.\nFrom Jasmin Require Import word.\n\nFrom Coq Require Import ZArith List.\nImport List.ListNotations.\n\n(********************************************************)\n(*   Implementation of all Hacspec library functions    *)\n(* for Both types.                                      *)\n(********************************************************)\n\n(*** Integers *)\n\nDeclare Scope hacspec_scope.\n\nRequire Import ChoiceEquality.\nRequire Import LocationUtility.\nRequire Import Hacspec_Lib_Comparable.\nRequire Import Hacspec_Lib_Pre.\n\nOpen Scope bool_scope.\nOpen Scope hacspec_scope.\nOpen Scope nat_scope.\nOpen Scope list_scope.\n\nEquations lift3_both {A B C : ChoiceEquality} L1 L2 I : (A -> B -> C) -> both L1 I A -> both L2 I B -> both (L1 :|: L2) I C :=\n  lift3_both _ _ _ f x y :=\n    {| is_pure := f x y ;\n      is_state := {code temp_x \u2190 x ;; temp_y \u2190 y ;; ret (f (ct_T temp_x) (ct_T temp_y)) } |}.\nNext Obligation.\n  intros.\n  ssprove_valid ; eapply valid_injectLocations ; [ apply fsubsetUl | | apply fsubsetUr | ] ; apply (prog_valid (is_state _)).\nQed.\nNext Obligation.\n  intros.\n  pattern_both Hb Hf Hg.\n  apply (@r_bind_trans_both A C).\n  subst Hf Hg Hb ; hnf.\n  pattern_both Hb Hf Hg.\n  apply (@r_bind_trans_both B C).\n  subst Hf Hg Hb ; hnf.\n  rewrite !ct_T_id.\n  apply r_ret. easy.\nQed.\nGlobal Transparent lift3_both.\n\nEquations lift2_both {A B : ChoiceEquality} {L} {I} : (A -> B) -> both L I A -> both L I B :=\n  lift2_both f x :=\n    {| is_pure := f x ;\n      is_state := {code temp_x \u2190 x ;; ret (f (ct_T temp_x)) } |}.\nNext Obligation.\n  intros.\n  pattern_both Hb Hf Hg.\n  apply (@r_bind_trans_both A B).\n  subst Hf Hg Hb ; hnf.\n  rewrite !ct_T_id.\n  apply r_ret. easy.\nQed.\nGlobal Transparent lift2_both.\n\nSection IntType.\n  Definition int_modi {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_modi.\n  Definition int_add {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_add.\n  Definition int_sub {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_sub.\n  Definition int_opp {WS : wsize} {L} {I} := @lift2_both _ (@int WS) L I int_opp.\n  Definition int_mul {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_mul.\n  Definition int_div {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_div.\n  Definition int_mod {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_mod.\n  Definition int_xor {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I  int_xor.\n  Definition int_and {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_and.\n  Definition int_or  {WS : wsize} {L1 L2} {I} := @lift3_both _ _ (@int WS) L1 L2 I int_or.\n  Definition int_not {WS : wsize} {L} {I} := @lift2_both _ (@int WS) L I int_not.\n\n  Program Definition cast_int {WS1 WS2 : wsize} {L I} := @lift2_both (@int WS1) (@int WS2) L I (fun n => repr (unsigned n)).\nEnd IntType.\n\nDefinition secret : forall {WS : wsize},  (T (@int WS)) -> both0 (@int WS) :=\n  fun {WS} x => lift_to_both (secret x).\n\nInfix \".%%\" := int_modi (at level 40, left associativity) : Z_scope.\nInfix \".+\" := int_add (at level 77) : hacspec_scope.\nInfix \".-\" := int_sub (at level 77) : hacspec_scope.\nNotation \"-\" := int_opp (at level 77) : hacspec_scope.\nInfix \".*\" := int_mul (at level 77) : hacspec_scope.\nInfix \"./\" := int_div (at level 77) : hacspec_scope.\nInfix \".%\" := int_mod (at level 77) : hacspec_scope.\nInfix \".^\" := int_xor (at level 77) : hacspec_scope.\nInfix \".&\" := int_and (at level 77) : hacspec_scope.\nInfix \".|\" := int_or (at level 77) : hacspec_scope.\nNotation \"'not'\" := int_not (at level 77) : hacspec_scope.\n\nSection Uint.\n  Definition uint8_declassify (n : int8) : both0 int8 :=\n    lift_to_both (uint8_declassify n).\n  Definition int8_declassify (n : int8) : both0 int8 :=\n    lift_to_both (int8_declassify n).\n  Definition uint16_declassify (n : int16) : both0 int16 :=\n    lift_to_both (uint16_declassify n).\n  Definition int16_declassify (n : int16) : both0 int16 :=\n    lift_to_both (int16_declassify n).\n  Definition uint32_declassify (n : int32) : both0 int32 :=\n    lift_to_both (uint32_declassify n).\n  Definition int32_declassify (n : int32) : both0 int32 :=\n    lift_to_both (int32_declassify n).\n  Definition uint64_declassify (n : int64) : both0 int64 :=\n    lift_to_both (uint64_declassify n).\n  Definition int64_declassify (n : int64) : both0 int64 :=\n    lift_to_both (int64_declassify n).\n  Definition uint128_declassify (n : int128) : both0 int128 :=\n    lift_to_both (uint128_declassify n).\n  Definition int128_declassify (n : int128) : both0 int128 :=\n    lift_to_both (int128_declassify n).\n\n  Definition uint8_classify (n : int8) : both0 int8 :=\n    lift_to_both (uint8_classify n).\n  Definition int8_classify (n : int8) : both0 int8 :=\n    lift_to_both (int8_classify n).\n  Definition uint16_classify (n : int16) : both0 int16 :=\n    lift_to_both (uint16_classify n).\n  Definition int16_classify (n : int16) : both0 int16 :=\n    lift_to_both (int16_classify n).\n  Definition uint32_classify (n : int32) : both0 int32 :=\n    lift_to_both (uint32_classify n).\n  Definition int32_classify (n : int32) : both0 int32 :=\n    lift_to_both (int32_classify n).\n  Definition uint64_classify (n : int64) : both0 int64 :=\n    lift_to_both (uint64_classify n).\n  Definition int64_classify (n : int64) : both0 int64 :=\n    lift_to_both (int64_classify n).\n  Definition uint128_classify (n : int128) : both0 int128 :=\n    lift_to_both (uint128_classify n).\n  Definition int128_classify (n : int128) : both0 int128 :=\n    lift_to_both (int128_classify n).\n\n  (* CompCert integers' signedness is only interpreted through 'signed' and 'unsigned',\n   and not in the representation. Therefore, uints are just names for their respective ints.\n   *)\n\n  Definition declassify_usize_from_uint8 (n : uint8) : both0 uint_size :=\n    lift_to_both (declassify_usize_from_uint8 n).\n  Definition declassify_u32_from_uint32 (n : uint32) : both0 uint32 :=\n    lift_to_both (declassify_u32_from_uint32 n).\n\n  Definition uint8_rotate_left (u: int8) (s: int8) : both0 int8 := lift_to_both (uint8_rotate_left u s).\n\n  Definition uint8_rotate_right (u: int8) (s: int8) : both0 (int8) := lift_to_both0 (uint8_rotate_right u s).\n\n  Definition uint16_rotate_left (u: int16) (s: int16) : both0 (int16) :=\nlift_to_both0 (uint16_rotate_left u s).\n\n  Definition uint16_rotate_right (u: int16) (s: int16) : both0 (int16) :=\nlift_to_both0 (uint16_rotate_right u s).\n\n  Definition uint32_rotate_left (u: int32) (s: int32) : both0 (int32) :=\nlift_to_both0 (uint32_rotate_left u s).\n\n  Definition uint32_rotate_right (u: int32) (s: int32) : both0 (int32) :=\nlift_to_both0 (uint32_rotate_right u s).\n\n  Definition uint64_rotate_left (u: int64) (s: int64) : both0 (int64) :=\nlift_to_both0 (uint64_rotate_left u s).\n\n  Definition uint64_rotate_right (u: int64) (s: int64) : both0 (int64) :=\nlift_to_both0 (uint64_rotate_right u s).\n\n  Definition uint128_rotate_left (u: int128) (s: int128) : both0 (int128) :=\nlift_to_both0 (uint128_rotate_left u s).\n\n  Definition uint128_rotate_right (u: int128) (s: int128) : both0 (int128) :=\nlift_to_both0 (uint128_rotate_right u s).\n\n\n  Definition usize_shift_right_ (u: uint_size) (s: int32) : both0 (uint_size) :=\n    lift_to_both (u usize_shift_right s).\n\n  Program Definition usize_shift_left_ (u: both0 uint_size) (s: both0 int32) : both0 (uint_size) :=\n    {|\n      is_pure := (is_pure u) usize_shift_left (is_pure s) ;\n      is_state :=\n      {code\n         temp_u \u2190 is_state u ;;\n         temp_s \u2190 is_state s ;;\n         ret (T_ct (temp_u usize_shift_left temp_s))\n      }\n    |}.\n  Next Obligation.\n    intros.\n    pattern_both Hb Hf Hg.\n    apply (@r_bind_trans_both (uint_size) (uint_size)).\n    subst Hf Hg Hb ; hnf.\n    pattern_both Hb Hf Hg.\n    apply (@r_bind_trans_both (int32)).\n    subst Hf Hg Hb ; hnf.\n    apply r_ret.\n    easy.\n  Qed.\n\n  (**** Operations *)\n\n  Program Definition shift_left_ `{WS : wsize} {L1 L2} {I} :=\n    @lift3_both _ _ _ L1 L2 I (@shift_left_ WS).\n\n  Program Definition shift_right_ `{WS : wsize} {L1 L2} {I} :=\n    @lift3_both _ _ _ L1 L2 I (@shift_right_ WS).\n\nEnd Uint.\n\nInfix \"usize_shift_right\" := (usize_shift_right_) (at level 77) : hacspec_scope.\nInfix \"usize_shift_left\" := (usize_shift_left_) (at level 77) : hacspec_scope.\n\nInfix \"shift_left\" := (shift_left_) (at level 77) : hacspec_scope.\nInfix \"shift_right\" := (shift_right_) (at level 77) : hacspec_scope.\n\n(*** Loops *)\n\nSection Loops.\n\n  Fixpoint foldi_\n           {acc : ChoiceEquality}\n           (fuel : nat)\n           (i : T uint_size)\n           {L I}\n           (f: (T uint_size) -> T acc -> code L I (ct acc))\n           (cur : T acc) {struct fuel} : raw_code (ct acc) :=\n    match fuel with\n    | O => ret cur\n    | S n' =>\n        cur' \u2190 f i cur ;;\n        Si \u2190 (lift_to_both0 i) .+ (lift_to_both0 one) ;;\n        foldi_ n' Si f (ct_T cur')\n    end.\n\n  Lemma valid_foldi_ :\n    forall {acc : ChoiceEquality} L I n i (f : T uint_size -> T acc -> code L I (ct acc)) init,\n      ValidCode L I (foldi_ n i f init).\n  Proof.\n    induction n ; intros ; cbn ; ssprove_valid.\n    apply f.\n  Qed.\n\n  Definition foldi_pre\n             {acc: ChoiceEquality}\n             (lo: T uint_size)\n             (hi: T uint_size) (* {lo <= hi} *)\n             {I L}\n             (f: (T uint_size) -> T acc -> code I L (ct acc)) (* {i < hi} *)\n             (init: T acc) : raw_code (ct acc) :=\n    match Z.sub (unsigned hi) (unsigned lo) with\n    | Z0 => ret (T_ct init)\n    | Zneg p => ret (T_ct init)\n    | Zpos p => foldi_ (Pos.to_nat p) lo f init\n    end.\n\n  (* Fold done using natural numbers for bounds *)\n  Fixpoint foldi_nat_\n           {acc : ChoiceEquality}\n           (fuel : nat)\n           (i : nat)\n           (f : nat -> T acc -> raw_code (ct acc))\n           (cur : T acc) : raw_code (ct acc) :=\n    match fuel with\n    | O => ret (T_ct cur)\n    | S n' =>\n        cur' \u2190 f i cur ;;\n        foldi_nat_ n' (S i) f (ct_T cur')\n    end.\n  Definition foldi_nat\n             {acc: ChoiceEquality}\n             (lo: nat)\n             (hi: nat) (* {lo <= hi} *)\n             (f: nat -> T acc -> raw_code (ct acc)) (* {i < hi} *)\n             (init: T acc) : raw_code (ct acc) :=\n    match Nat.sub hi lo with\n    | O => ret (T_ct init)\n    | S n' => foldi_nat_ (S n') lo f init\n    end.\n\n  Lemma foldi__move_S :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : T uint_size)\n      {L I}\n      (f : T uint_size -> T acc -> code L I (ct acc))\n      (cur : T acc),\n      (cur' \u2190 f i cur ;; Si \u2190 (lift_to_both0 i) .+ (lift_to_both0 one) ;; foldi_ fuel Si f (ct_T cur')) = foldi_ (S fuel) i f cur.\n  Proof. reflexivity. Qed.\n\n  Lemma foldi__nat_move_S :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : nat)\n      (f : nat -> T acc -> raw_code (ct acc))\n      (cur : T acc),\n      (cur' \u2190 f i cur ;; foldi_nat_ fuel (S i) f (ct_T cur')) = foldi_nat_ (S fuel) i f cur.\n  Proof. reflexivity. Qed.\n\n  Lemma foldi__nat_move_S_append :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : nat)\n      (f : nat -> T acc -> raw_code (ct acc))\n      (cur : T acc),\n      (cur' \u2190 foldi_nat_ fuel i f (cur) ;; f (i + fuel) (ct_T cur')) = foldi_nat_ (S fuel) i f cur.\n  Proof.\n\n    induction fuel ; intros.\n    - rewrite <- foldi__nat_move_S.\n      unfold foldi_nat_.\n      replace (fun cur' => ret (T_ct (ct_T cur'))) with (fun cur' => @ret acc cur').\n      2: {\n        apply functional_extensionality.\n        intros. now rewrite T_ct_id.\n      }\n      rewrite bind_ret.\n      unfold bind at 1.\n      rewrite ct_T_id.\n      rewrite Nat.add_0_r.\n      reflexivity.\n    - rewrite <- foldi__nat_move_S.\n      rewrite <- foldi__nat_move_S.\n      rewrite bind_assoc.\n      f_equal.\n      apply functional_extensionality.\n      intros.\n      replace (i + S fuel) with (S i + fuel) by lia.\n      rewrite IHfuel.\n      reflexivity.\n  Qed.\n\n  Lemma foldi__nat_move_to_function :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : nat)\n      (f : nat -> T acc -> raw_code (ct acc))\n      (cur : T acc),\n      foldi_nat_ fuel i (fun x => f (S x)) (cur) = foldi_nat_ fuel (S i) f cur.\n  Proof.\n    induction fuel ; intros.\n    - reflexivity.\n    - cbn.\n      f_equal.\n      apply functional_extensionality.\n      intros.\n      rewrite IHfuel.\n      reflexivity.\n  Qed.\n\n  Lemma foldi__nat_move_to_function_add :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i j : nat)\n      (f : nat -> T acc -> raw_code (ct acc))\n      (cur : T acc),\n      foldi_nat_ fuel i (fun x => f (x + j)) (cur) = foldi_nat_ fuel (i + j) f cur.\n  Proof.\n    intros acc fuel i j. generalize dependent i.\n    induction j ; intros.\n    - rewrite Nat.add_0_r.\n      replace (fun x : nat => f (x + 0)) with f.\n      reflexivity.\n      apply functional_extensionality.\n      intros.\n      now rewrite Nat.add_0_r.\n    - replace (i + S j) with (S i + j) by lia.\n      rewrite <- IHj.\n      rewrite <- foldi__nat_move_to_function.\n      f_equal.\n      apply functional_extensionality.\n      intros.\n      f_equal.\n      lia.\n  Qed.\n\n  Lemma raw_code_type_from_choice_type_id :\n    forall (acc : ChoiceEquality) (x : raw_code (ct acc)),\n      (cur' \u2190 x ;;\n       ret (T_ct (ct_T cur')))\n      =\n        x.\n  Proof.\n    intros.\n    rewrite @bind_cong with (v := x) (g := @ret (ct acc)).\n    rewrite bind_ret.\n    reflexivity.\n    reflexivity.\n\n    apply functional_extensionality.\n    intros.\n\n    rewrite T_ct_id.\n    reflexivity.\n  Qed.\n\n  (* You can do one iteration of the fold by burning a unit of fuel *)\n  Lemma foldi__move_S_fuel :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : T uint_size)\n      {L I}\n      (f : T uint_size -> T acc -> code L I (ct acc))\n      (cur : T acc),\n      (0 <= Z.of_nat fuel <= @wmax_unsigned U32)%Z ->\n      (cur' \u2190 foldi_ fuel i f cur ;;\n       fuel_add_i \u2190 (lift_to_both0 (repr (Z.of_nat fuel))) .+ (lift_to_both0 i) ;;\n       f fuel_add_i (ct_T cur')\n      ) = foldi_ (S (fuel)) i f cur.\n  Proof.\n    intros acc fuel.\n    induction fuel ; intros.\n    - cbn.\n      replace (repr 0) with (@zero U32) by (apply word_ext ; reflexivity).\n      unfold Hacspec_Lib_Pre.int_add.\n      rewrite add0w.\n\n      rewrite ct_T_id.\n      rewrite raw_code_type_from_choice_type_id.\n      reflexivity.\n    - unfold foldi_.\n      fold (@foldi_ acc fuel).\n\n      rewrite bind_assoc.\n      f_equal.\n      apply functional_extensionality.\n      intros.\n\n      unfold int_add at 1 3.\n      unfold lift_to_both, is_state at 1 3.\n      unfold prog, lift_to_code.\n      do 2 setoid_rewrite bind_rewrite.\n\n      specialize (IHfuel (Hacspec_Lib_Pre.int_add i one) L I f (ct_T x)).\n\n\n\n      replace (Hacspec_Lib_Pre.int_add (repr (Z.of_nat (S fuel))) _)\n        with (Hacspec_Lib_Pre.int_add (repr (Z.of_nat fuel)) (Hacspec_Lib_Pre.int_add i one)).\n      2 : {\n        unfold int_add.\n        unfold Hacspec_Lib_Pre.int_add.\n        rewrite <- addwC.\n        rewrite <- addwA.\n        rewrite addwC.\n        f_equal.\n        apply word_ext.\n        rewrite Z.add_1_l.\n        rewrite Nat2Z.inj_succ.\n\n        f_equal.\n        f_equal.\n        apply Zmod_small.\n        unfold wmax_unsigned in H.\n        unfold wbase in H.\n        lia.\n      }\n\n      setoid_rewrite IHfuel.\n      reflexivity.\n      lia.\n  Qed.\n\n  (* You can do one iteration of the fold by burning a unit of fuel *)\n  Lemma foldi__nat_move_S_fuel :\n    forall {acc: ChoiceEquality}\n      (fuel : nat)\n      (i : nat)\n      (f : nat -> T acc -> raw_code (ct acc))\n      (cur : T acc),\n      (0 <= Z.of_nat fuel <= @wmax_unsigned U32)%Z ->\n      (cur' \u2190 foldi_nat_ fuel i f cur ;; f (fuel + i)%nat (ct_T cur')) = foldi_nat_ (S fuel) i f cur.\n  Proof.\n    induction fuel ; intros.\n    - cbn.\n      rewrite ct_T_id.\n      rewrite raw_code_type_from_choice_type_id.\n      reflexivity.\n    - unfold foldi_nat_.\n      fold (@foldi_nat_ acc fuel).\n      rewrite bind_assoc.\n      f_equal.\n      apply functional_extensionality.\n      intros.\n      replace (S fuel + i)%nat with (fuel + (S i))%nat by (symmetry ; apply plus_Snm_nSm).\n      rewrite IHfuel.\n      + reflexivity.\n      + lia.\n  Qed.\n\n  (* folds and natural number folds compute the same thing *)\n  Lemma foldi_to_foldi_nat :\n    forall {acc: ChoiceEquality}\n      (lo: T uint_size)\n      (hi: T uint_size) (* {lo <= hi} *)\n      {L I}\n      (f: (T uint_size) -> T acc -> code L I (ct acc)) (* {i < hi} *)\n      (init: T acc),\n      (unsigned lo <= unsigned hi)%Z ->\n      foldi_pre lo hi f init = foldi_nat (Z.to_nat (unsigned lo)) (Z.to_nat (unsigned hi)) (fun x => f (repr (Z.of_nat x))) init.\n  Proof.\n    intros.\n\n    unfold foldi_pre.\n    unfold foldi_nat.\n\n    destruct (uint_size_as_nat hi) as [ hi_n [ hi_eq hi_H ] ] ; subst.\n    rewrite (@unsigned_repr_alt U32 _ hi_H) in *.\n    rewrite Nat2Z.id.\n\n    destruct (uint_size_as_nat lo) as [ lo_n [ lo_eq lo_H ] ] ; subst.\n    rewrite (@unsigned_repr_alt U32 _ lo_H) in *.\n    rewrite Nat2Z.id.\n\n    remember (hi_n - lo_n)%nat as n.\n    apply f_equal with (f := Z.of_nat) in Heqn.\n    rewrite (Nat2Z.inj_sub) in Heqn by (apply Nat2Z.inj_le ; apply H).\n    rewrite <- Heqn.\n\n    assert (H_bound : (Z.pred 0 < Z.of_nat n < @modulus U32)%Z) by lia.\n\n    clear Heqn.\n    induction n.\n    - reflexivity.\n    - pose proof (H_max_bound := modulus_range_helper _ (range_of_nat_succ _ H_bound)).\n      rewrite <- foldi__nat_move_S_fuel by apply H_max_bound.\n      cbn.\n      rewrite SuccNat2Pos.id_succ.\n      rewrite <- foldi__move_S_fuel by apply H_max_bound.\n\n      destruct n.\n      + cbn.\n        replace (repr 0) with (@zero U32) by (apply word_ext ; reflexivity).\n        unfold Hacspec_Lib_Pre.int_add.\n        rewrite add0w.\n        reflexivity.\n      + assert (H_bound_pred: (Z.pred 0 < Z.pos (Pos.of_succ_nat n) < @modulus U32)%Z) by lia.\n        rewrite <- (IHn H_bound_pred) ; clear IHn.\n        f_equal.\n        * cbn in *.\n          setoid_rewrite foldi__move_S.\n          f_equal.\n          lia.\n        * apply functional_extensionality.\n          intros.\n\n          unfold int_add.\n\n          setoid_rewrite bind_rewrite.\n          replace (@Hacspec_Lib_Pre.int_add U32 _ _) with (@repr U32 (Z.of_nat (Init.Nat.add (S n) lo_n))). reflexivity.\n\n          apply word_ext.\n\n          replace (urepr _) with (@unsigned U32 (repr (Z.of_nat (S n)))) by reflexivity.\n          replace (urepr _) with (@unsigned U32 (repr (Z.of_nat lo_n))) by reflexivity.\n          do 2 rewrite unsigned_repr_alt by lia.\n          rewrite Nat2Z.inj_add.\n          reflexivity.\n  Qed.\n\n  Lemma foldi_nat_to_foldi :\n    forall {acc: ChoiceEquality}\n      (lo: nat)\n      (hi: nat) (* {lo <= hi} *)\n      {L I}\n      (f: nat -> T acc -> code L I (ct acc)) (* {i < hi} *)\n      (init: T acc),\n      (lo <= hi) ->\n      (Z.of_nat hi < @modulus U32)%Z ->\n      (forall x, f x = f (from_uint_size (repr (Z.of_nat x)))) ->\n      foldi_nat lo hi f init =\n        foldi_pre (usize lo) (usize hi) (fun x => f (from_uint_size x)) init.\n  Proof.\n    intros.\n    rewrite foldi_to_foldi_nat.\n    2: {\n      unfold nat_uint_sizeable.\n      unfold usize, lift_to_both, is_pure.\n      unfold Hacspec_Lib_Pre.usize.\n\n      do 2 rewrite wunsigned_repr.\n      rewrite Zmod_small by (split ; [ lia | apply Z.le_lt_trans with (m := Z.of_nat hi) ; try apply inj_le ; assumption ]).\n      rewrite Zmod_small by (split ; try easy ; lia).\n      lia.\n    }\n\n    unfold nat_uint_sizeable.\n    unfold usize, lift_to_both, is_pure.\n    unfold Hacspec_Lib_Pre.usize.\n\n    do 2 rewrite wunsigned_repr.\n    rewrite Zmod_small by (split ; [ lia | apply Z.le_lt_trans with (m := Z.of_nat hi) ; try apply inj_le ; assumption ]).\n    rewrite Zmod_small by (split ; try easy ; lia).\n    do 2 rewrite Nat2Z.id.\n\n    f_equal.\n    apply functional_extensionality. intros.\n    rewrite <- H1.\n    reflexivity.\n  Qed.\n\n  (* folds can be computed by doing one iteration and incrementing the lower bound *)\n  Lemma foldi_nat_split_S :\n    forall {acc: ChoiceEquality}\n      (lo: nat)\n      (hi: nat) (* {lo <= hi} *)\n      (f: nat -> T acc -> raw_code (ct acc)) (* {i < hi} *)\n      (init: T acc),\n      (lo < hi)%nat ->\n      foldi_nat lo hi f init = (cur' \u2190 foldi_nat lo (S lo) f init ;; foldi_nat (S lo) hi f (ct_T cur')).\n  Proof.\n    unfold foldi_nat.\n    intros.\n\n    assert (succ_sub_diag : forall n, (S n - n = 1)%nat) by lia.\n    rewrite (succ_sub_diag lo).\n\n    induction hi ; [ lia | ].\n    destruct (S hi =? S lo)%nat eqn:hi_eq_lo.\n    - apply Nat.eqb_eq in hi_eq_lo ; rewrite hi_eq_lo in *.\n      rewrite (succ_sub_diag lo).\n      rewrite Nat.sub_diag.\n\n      rewrite raw_code_type_from_choice_type_id.\n      reflexivity.\n    - apply Nat.eqb_neq in hi_eq_lo.\n      apply Nat.lt_gt_cases in hi_eq_lo.\n      destruct hi_eq_lo.\n      + lia.\n      + rewrite (Nat.sub_succ_l (S lo)) by apply (Nat.lt_le_pred _ _ H0).\n        rewrite Nat.sub_succ_l by apply (Nat.lt_le_pred _ _ H).\n        replace ((S (hi - S lo))) with (hi - lo)%nat by lia.\n\n        unfold foldi_nat_.\n        fold (@foldi_nat_ acc).\n        rewrite raw_code_type_from_choice_type_id.\n        reflexivity.\n  Qed.\n\n  (* folds can be split at some valid offset from lower bound *)\n  Lemma foldi_nat_split_add :\n    forall (k : nat),\n    forall {acc: ChoiceEquality}\n      (lo: nat)\n      (hi: nat) (* {lo <= hi} *)\n      (f: nat -> T acc -> raw_code (ct acc)) (* {i < hi} *)\n      (init: T acc),\n    forall {guarantee: (lo + k <= hi)%nat},\n      foldi_nat lo hi f init = (cur' \u2190 foldi_nat lo (k + lo) f init ;; foldi_nat (k + lo) hi f (ct_T cur')).\n  Proof.\n    induction k ; intros.\n    - cbn.\n      unfold foldi_nat.\n      rewrite Nat.sub_diag.\n      cbn.\n      rewrite ct_T_id.\n      reflexivity.\n    - rewrite foldi_nat_split_S by lia.\n      replace (S k + lo)%nat with (k + S lo)%nat by lia.\n      specialize (IHk acc (S lo) hi f).\n\n      rewrite bind_cong with (v := foldi_nat lo (S lo) (fun (x : nat) (x0 : T acc) => f x x0) init) (g := fun v => (cur' \u2190 foldi_nat (S lo) (k + S lo) (fun (x : nat) (x0 : T acc) => f x x0) (ct_T v) ;;\n                                                                                                             foldi_nat (k + S lo) hi (fun (x : nat) (x0 : T acc) => f x x0)\n                                                                                                                       (ct_T cur'))).\n\n      rewrite <- bind_assoc.\n      f_equal.\n\n      rewrite <- foldi_nat_split_S by lia.\n      reflexivity.\n\n      reflexivity.\n\n      apply functional_extensionality. intros. rewrite IHk by lia. reflexivity.\n  Qed.\n\n  (* folds can be split at some midpoint *)\n  Lemma foldi_nat_split :\n    forall (mid : nat), (* {lo <= mid <= hi} *)\n    forall {acc: ChoiceEquality}\n      (lo: nat)\n      (hi: nat) (* {lo <= hi} *)\n      (f: nat -> T acc -> raw_code (ct acc)) (* {i < hi} *)\n      (init: T acc),\n    forall {guarantee: (lo <= mid <= hi)%nat},\n      foldi_nat lo hi f init = (cur' \u2190 foldi_nat lo mid f init ;; foldi_nat mid hi f (ct_T cur')).\n  Proof.\n    intros.\n    assert (mid_is_low_plus_constant : {k : nat | (mid = lo + k)%nat})  by (exists (mid - lo)%nat ; lia).\n    destruct mid_is_low_plus_constant ; subst.\n    rewrite Nat.add_comm.\n    pose foldi_nat_split_add.\n    apply foldi_nat_split_add.\n    apply guarantee.\n  Qed.\n\n  (* folds can be split at some midpoint *)\n  Lemma foldi_split :\n    forall (mid : T uint_size), (* {lo <= mid <= hi} *)\n    forall {acc: ChoiceEquality}\n      (lo: T uint_size)\n      (hi: T uint_size) (* {lo <= hi} *)\n      {L I}\n      (f: T uint_size -> T acc -> code L I (ct acc)) (* {i < hi} *)\n      (init: T acc),\n    forall {guarantee: (unsigned lo <= unsigned mid <= unsigned hi)%Z},\n      foldi_pre lo hi f init = (cur' \u2190 foldi_pre lo mid f init ;; foldi_pre mid hi f (ct_T cur')).\n  Proof.\n    intros.\n    rewrite foldi_to_foldi_nat by lia.\n    rewrite foldi_to_foldi_nat by lia.\n\n    pose @foldi_to_foldi_nat.\n\n    rewrite bind_cong with (v := foldi_nat (Z.to_nat (unsigned lo)) (Z.to_nat (unsigned mid))\n                                           (fun x : nat => f (repr (Z.of_nat x))) init) (g := fun init => foldi_nat (Z.to_nat (unsigned mid)) (Z.to_nat (unsigned hi))\n                                                                                                            (fun x : nat => f (repr (Z.of_nat x))) (ct_T init)).\n\n    apply foldi_nat_split ; lia.\n    reflexivity.\n    apply functional_extensionality.\n    intros.\n\n    rewrite foldi_to_foldi_nat by lia.\n    reflexivity.\n  Qed.\n\n\n  Lemma valid_foldi_pre :\n    forall {acc : ChoiceEquality} (lo hi : int_type) {L : {fset Location}} {I : Interface} (f : int_type -> T _ -> code L I (ct _)),\n      forall init : (T _),\n        ValidCode L I (foldi_pre lo hi f init).\n  Proof.\n    intros.\n    unfold foldi_pre.\n    destruct (unsigned hi - unsigned lo)%Z.\n    - ssprove_valid.\n    - apply valid_foldi_.\n    - ssprove_valid.\n  Qed.\n\n  Definition foldi\n             {acc: ChoiceEquality}\n             (lo: T uint_size)\n             (hi: T uint_size) (* {lo <= hi} *)\n             (init: T acc)\n             {L}\n             {I}\n             (f: (T uint_size) -> T acc -> code L I (ct acc))\n    :\n    code L I (ct acc) :=\n    {| prog := foldi_pre lo hi f init;\n      prog_valid := @valid_foldi_pre acc lo hi L I f init |}.\n\n  Definition foldi'\n             {acc: ChoiceEquality}\n             (lo: T uint_size)\n             (hi: T uint_size) (* {lo <= hi} *)\n             (init: T acc)\n             {L1 L2 : {fset Location}} {H_loc_incl : List.incl L1 L2}\n             {I1 I2 : Interface} {H_opsig_incl : List.incl I1 I2}\n             (f: (T uint_size) -> T acc -> code L1 I1 (ct acc))\n    :\n    code L2 I2 (ct acc)\n  .\n    eapply lift_code_scope.\n    apply (foldi lo hi init f).\n    apply H_loc_incl.\n    apply H_opsig_incl.\n  Defined.\n\n  Lemma valid_remove_back :\n    forall x (xs : {fset Location}) I {ct} c,\n      ValidCode (fset xs) I c ->\n      @ValidCode (fset (xs ++ [x])) I ct c.\n  Proof.\n    intros.\n    apply (valid_injectLocations) with (L1 := fset xs).\n    - rewrite fset_cat.\n      apply fsubsetUl.\n    - apply H.\n  Qed.\n\n  Lemma list_constructor : forall {A : Type} (x : A) (xs : list A) (l : list A) (H : (x :: xs) = l), (l <> []).\n  Proof.\n    intros.\n    subst.\n    easy.\n  Qed.\n\n  Definition pop_back {A : Type} (l : list A) :=\n    match (rev l) with\n    | [] => []\n    | (x :: xs) => rev xs ++ [x]\n    end.\n\n  Theorem pop_back_ignore_front : forall {A} (a : A) (l : list A), pop_back (a :: l) = a :: pop_back l.\n  Proof.\n    intros.\n    induction l ; intros.\n    - reflexivity.\n    - unfold pop_back.\n      destruct (rev (a :: a0 :: l)) eqn:orev.\n      { apply f_equal with (f := @rev A) in orev.\n        rewrite (rev_involutive) in orev.\n        discriminate orev.\n      }\n      cbn in orev.\n\n      destruct (rev (a0 :: l)) eqn:orev2.\n      { apply f_equal with (f := @rev A) in orev2.\n        rewrite (rev_involutive) in orev2.\n        discriminate orev2.\n      }\n      cbn in orev2.\n      rewrite orev2 in orev ; clear orev2.\n\n      inversion_clear orev.\n      rewrite rev_unit.\n      reflexivity.\n  Qed.\n\n  Theorem pop_back_is_id : forall {A} (l : list A), l = pop_back l.\n  Proof.\n    intros.\n    induction l.\n    - reflexivity.\n    - destruct l.\n      + reflexivity.\n      + rewrite pop_back_ignore_front.\n        rewrite <- IHl.\n        reflexivity.\n  Qed.\n\n  Ltac valid_remove_back' :=\n    match goal with\n    | _ : _ |- (ValidCode (fset (?l)) _ _) =>\n        rewrite (@pop_back_is_id _ l)\n    end ;\n    apply valid_remove_back.\n\n\n  Lemma valid_remove_front :\n    forall x xs I {ct} c,\n      ValidCode (fset xs) I c ->\n      @ValidCode (fset (x :: xs)) I ct c.\n  Proof.\n    intros.\n    apply (@valid_injectLocations) with (L1 := fset xs).\n    - replace (x :: xs) with (seq.cat [x] xs) by reflexivity.\n      rewrite fset_cat.\n      apply fsubsetUr.\n    - apply H.\n  Qed.\n\nTheorem for_loop_unfold :\n  forall c n,\n  for_loop (fun m : nat => c m) (S n) =\n    (c 0 ;; for_loop (fun m : nat => c (S m)) (n) ).\n  cbn.\n  induction n ; intros.\n  - reflexivity.\n  - unfold for_loop ; fold for_loop.\n    cbn.\n    rewrite IHn.\n    rewrite bind_assoc.\n    reflexivity.\nQed.\n\nEnd Loops.\n\n(*** Seq *)\n\nSection Seqs.\n\n  (**** Unsafe functions *)\n\n  Definition seq_new_ {A: ChoiceEquality} (init : A) {WS} (len: @int WS) : both0 (seq A) :=\n    lift_to_both (seq_new_ init (unsigned len)).\n\n  Definition seq_new {A: ChoiceEquality} `{Default A} (len: nat) : both0 (seq A) :=\n    lift_to_both (seq_new len).\n\n  Definition seq_len {A: ChoiceEquality} (s: T (seq A)) : both0 (uint_size) :=\n    lift_to_both (seq_len s).\n\n  Definition seq_index {A: ChoiceEquality} `{Default (T A)} (s: T (seq A)) (i : uint_size) : both0 A :=\n    lift_to_both (seq_index s i).\n\n(**** Seq manipulation *)\n\nDefinition seq_slice\n  {a: ChoiceEquality}\n `{Default (T a)}\n  (s: (T (seq a)))\n  (start: uint_size)\n  (len: uint_size)\n    : both0 (seq a) :=\n  lift_to_both (seq_slice s start len).\n\nDefinition seq_slice_range\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (input: (T (seq a)))\n  (start_fin:(uint_size '\u00d7 uint_size))\n    : both0 (seq a) :=\n  lift_to_both (seq_slice_range input start_fin).\n\n(* updating a subsequence in a sequence *)\nDefinition seq_update\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (s: (T (seq a)))\n  (start: uint_size)\n  (input: (T (seq a)))\n  : both0 ((seq a)) :=\n  lift_to_both (seq_update s start input).\n\n(* updating only a single value in a sequence*)\nDefinition seq_upd\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (s: (T (seq a)))\n  (start: uint_size)\n  (v: (T (a)))\n  : both0 ((seq a)) :=\n  lift_to_both (seq_upd s start v).\n\nDefinition seq_update_start\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (s: (T (seq a)))\n  (start_s: (T (seq a)))\n    : both0 ((seq a)) :=\n    lift_to_both (seq_update_start s start_s).\n\nDefinition seq_update_slice\n  {a : ChoiceEquality}\n `{Default (T (a))}\n  (out: (T (seq a)))\n  (start_out: nat)\n  (input: (T (seq a)))\n  (start_in: nat)\n  (len: nat)\n    : both0 ((seq a)) :=\n  lift_to_both (seq_update_slice out start_out input start_in len).\n\nDefinition seq_concat\n           {a : ChoiceEquality}\n           `{Default a}\n  (s1 :(T (seq a)))\n  (s2: (T (seq a)))\n  : both0 ((seq a)) :=\n   lift_to_both (seq_concat s1 s2).\n\nDefinition seq_push\n           {a : ChoiceEquality}\n           `{Default a}\n  (s1 :(T (seq a)))\n  (s2: (T (a)))\n  : both0 ((seq a)) :=\n  lift_to_both (seq_push s1 s2).\n\nDefinition seq_from_slice\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (input: (T (seq a)))\n  (start_fin: uint_size '\u00d7 uint_size)\n  : both0 ((seq a)) :=\n  lift_to_both (seq_from_slice input start_fin).\n\nDefinition seq_from_slice_range\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (input: (T (seq a)))\n  (start_fin: uint_size '\u00d7 uint_size)\n  : both0 ((seq a)) :=\n  lift_to_both (seq_from_slice_range input start_fin).\n\nDefinition seq_from_seq {A} (l : T (seq A)) : both0 (seq A) :=\n  lift_to_both (seq_from_seq l).\n\n(**** Chunking *)\n\nDefinition seq_num_chunks {a: ChoiceEquality} (s: (T (seq a))) (chunk_len: uint_size) : both0 (uint_size) :=\n  lift_to_both (seq_num_chunks s chunk_len).\n\nDefinition seq_chunk_len\n  {a: ChoiceEquality}\n  (s: (T (seq a)))\n  (chunk_len: nat)\n  (chunk_num: nat)\n    : both0 ((nat_ChoiceEquality)) :=\n  lift_to_both (seq_chunk_len s chunk_len chunk_num).\n\nDefinition seq_get_chunk\n  {a: ChoiceEquality}\n  `{Default (T (a))}\n  (s: (T (seq a)))\n  (chunk_len: uint_size)\n  (chunk_num: uint_size)\n  : both0 (((uint_size '\u00d7 seq a))) :=\n  lift_to_both (seq_get_chunk s chunk_len chunk_num).\n\nDefinition seq_set_chunk\n  {a: ChoiceEquality}\n `{Default (T (a))}\n  (s: (T (seq a)))\n  (chunk_len: uint_size)\n  (chunk_num: uint_size)\n  (chunk: (T (seq a)) ) : both0 ((seq a)) :=\n  lift_to_both (seq_set_chunk s chunk_len chunk_num chunk).\n\n\nDefinition seq_num_exact_chunks {a} (l : (T (seq a))) (chunk_size : (T (uint_size))) : (both0 uint_size) :=\n  lift_to_both (seq_num_exact_chunks l chunk_size).\n\nDefinition seq_get_exact_chunk {a : ChoiceEquality} `{Default (T (a))} (l : (T (seq a))) (chunk_size chunk_num: (T (uint_size))) :\n  both0 ((seq a)) :=\n  lift_to_both (seq_get_exact_chunk l chunk_size chunk_num).\n\nDefinition seq_set_exact_chunk {a : ChoiceEquality} `{H : Default (T (a))} :=\n  @seq_set_chunk a H.\n\nDefinition seq_get_remainder_chunk {a : ChoiceEquality} `{Default (T (a))} (l : T (seq a)) (chunk_size : T (uint_size)) : both0 ((seq a)) :=\n  lift_to_both (seq_get_remainder_chunk l chunk_size).\n\nDefinition seq_xor_ {WS} (x y : seq (@int WS)) : both0 (seq (@int WS)) :=\n  lift_to_both (seq_xor_ x y).\n\nDefinition seq_truncate {a : ChoiceEquality} `{Default a} (x : seq a) (n : nat) : both0 (seq a) :=\n  lift_to_both (seq_truncate x n).\n\nEnd Seqs.\nInfix \"seq_xor\" := seq_xor_ (at level 33) : hacspec_scope.\n\nSection Arrays.\n  (**** types *)\n\n  (***** prelude.rs *)\n  Definition uint128_word_t : ChoiceEquality := nseq uint8 16.\n  Definition uint64_word_t : ChoiceEquality := nseq uint8 8.\n  Definition uint32_word_t : ChoiceEquality := nseq uint8 4.\n  Definition uint16_word_t : ChoiceEquality := nseq uint8 2.\n\n  (**** Array manipulation *)\n  Definition array_new_ {A: ChoiceEquality} (init:T A) `(len: nat) :\n    both0 ((nseq A len)) :=\n    lift_to_both (array_new_ init len).\n\n  Definition array_index {A: ChoiceEquality} `{Default (T A)} {len : nat} (s: T (nseq A len)) {WS} (i: @int WS) : both0 (A) :=\n    lift_to_both (array_index s i).\n\n  Definition array_upd {A: ChoiceEquality} {len : nat} (s: T (nseq A len)) {WS} (i: @int WS) (new_v: T A) : both0 ((nseq A len)) :=\n    lift_to_both (array_upd s i new_v).\n\n  (* substitutes a sequence (seq) into an array (nseq), given index interval  *)\n  Definition update_sub {A : ChoiceEquality} {len slen} `{Default (T A)} (v : T (nseq A len)) (i : nat) (n : nat) (sub : T (nseq A slen)) : both0 ((nseq A len)) :=\n    lift_to_both (update_sub v i n sub).\n\n  Definition array_from_list\n             {A: ChoiceEquality}\n             (l: list (T A))\n    : both0 (nseq A (length l)) := lift_to_both (array_from_list l).\n\n  Definition array_from_seq   {a: ChoiceEquality}\n             `{Default (T a)}\n             (out_len:nat)\n             (input: T (seq a))\n    : both0 (nseq a out_len) :=\n    lift_to_both (array_from_seq out_len input).\n\n  Definition array_to_seq {A : ChoiceEquality} `{H_default : Default A} {n} (f : nseq A n) : both0 (seq _) :=\n    @lift_to_both (seq A) _ _ (array_to_seq f).\n\n  Definition array_from_slice\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             (default_value: (T a))\n             (out_len: nat)\n             (input: T (seq a))\n             (start: uint_size)\n             (slice_len: uint_size)  : both0 ((nseq a out_len)) :=\n    lift_to_both (array_from_slice default_value out_len input (from_uint_size start) (from_uint_size slice_len)).\n\n  Definition array_slice\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             (input: T (seq a))\n             (start: nat)\n             (slice_len: nat)\n    : both0 ((nseq a slice_len)) :=\n    lift_to_both (array_slice input start slice_len).\n\n  Definition array_from_slice_range\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             (default_value: T a)\n             (out_len: nat)\n             (input: T (seq a))\n             (start_fin: (uint_size '\u00d7 uint_size))\n    : both0 ((nseq a out_len)) :=\n    lift_to_both (array_from_slice_range default_value out_len input start_fin).\n\n  Definition array_slice_range\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             {len : nat}\n             (input: T (nseq a len))\n             (start_fin:(uint_size '\u00d7 uint_size))\n    : both0 ((seq a)) :=\n    lift_to_both (array_slice_range input start_fin).\n\n  Definition array_update\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             {len: nat}\n             (s: T (nseq a len))\n             (start : uint_size)\n             (start_s: T (seq a))\n    : both0 ((nseq a len)) :=\n    lift_to_both (array_update s start start_s).\n\n  Definition array_update_start\n             {a: ChoiceEquality}\n             `{Default (T a)}\n             {len: nat}\n             (s: T (nseq a len))\n             (start_s: T (seq a))\n    : both0 ((nseq a len)) :=\n    lift_to_both (array_update_start s start_s).\n\n  Definition array_len  {a: ChoiceEquality} {len: nat} (s: T (nseq a len)) : both0 (uint_size) := lift_to_both (array_len s).\n  (* May also come up as 'length' instead of 'len' *)\n  Definition array_length  {a: ChoiceEquality} {len: nat} (s: T (nseq a len)) : both0 (uint_size) := lift_to_both (array_length s).\n\n  Definition array_update_slice\n             {a : ChoiceEquality}\n             `{Default (T (a))}\n             {l : nat}\n             (out: (T (nseq a l)))\n             (start_out: uint_size)\n             (input: (T (seq a)))\n             (start_in: uint_size)\n             (len: uint_size)\n    : both0 ((nseq a _)) :=\n    lift_to_both (array_update_slice (l := l) out start_out input start_in len).\n\n  (**** Numeric operations *)\n\n  (* takes two nseq's and joins them using a function op : a -> a -> a *)\n  Definition array_join_map\n             {a: ChoiceEquality}\n             `{Default (T (a))}\n             {len: nat}\n             (op: (T (a)) -> (T (a)) -> (T (a)))\n             (s1: (T (nseq a len)))\n             (s2 : (T (nseq a len))) : both0 ((nseq a len)) :=\n    lift_to_both (array_join_map op s1 s2).\n\n  Fixpoint array_eq_\n           {a: ChoiceEquality}\n           {len: nat}\n           (eq: (T (a)) -> (T (a)) -> bool)\n           (s1: (T (nseq a len)))\n           (s2 : (T (nseq a len)))\n           {struct len}\n    : bool.\n  Proof.\n    destruct len ; cbn in *.\n    - exact  true.\n    - destruct (getm s1 (fintype.Ordinal (m := len) (ssrnat.ltnSn _))) as [s | ].\n      + destruct (getm s2 (fintype.Ordinal (m := len) (ssrnat.ltnSn _))) as [s0 | ].\n        * exact (eq s s0).\n        * exact false.\n      + exact false.\n  Defined.\n\nEnd Arrays.\n\nInfix \"array_xor\" := (array_join_map int_xor) (at level 33) : hacspec_scope.\nInfix \"array_add\" := (array_join_map int_add) (at level 33) : hacspec_scope.\nInfix \"array_minus\" := (array_join_map int_sub) (at level 33) : hacspec_scope.\nInfix \"array_mul\" := (array_join_map int_mul) (at level 33) : hacspec_scope.\nInfix \"array_div\" := (array_join_map int_div) (at level 33) : hacspec_scope.\nInfix \"array_or\" := (array_join_map int_or) (at level 33) : hacspec_scope.\nInfix \"array_and\" := (array_join_map int_and) (at level 33) : hacspec_scope.\n\nInfix \"array_eq\" := (array_eq_ eq) (at level 33) : hacspec_scope.\nInfix \"array_neq\" := (fun s1 s2 => negb (array_eq_ eq s1 s2)) (at level 33) : hacspec_scope.\n\n\n(**** Integers to arrays *)\nDefinition uint32_to_le_bytes (n : T int32) : both0 ((nseq int8 4)) := lift_to_both (uint32_to_le_bytes n).\nDefinition uint32_to_be_bytes (n : T int32) : both0 ((nseq int8 4)) := lift_to_both (uint32_to_be_bytes n).\nDefinition uint32_from_le_bytes (n : T (nseq int8 4)) : both0 ((int32)) := lift_to_both (uint32_from_le_bytes n).\nDefinition uint32_from_be_bytes (n : T (nseq int8 4)) : both0 ((int32)) := lift_to_both (uint32_from_be_bytes n).\nDefinition uint64_to_le_bytes (n : T int64) : both0 ((nseq int8 8)) := lift_to_both (uint64_to_le_bytes n).\nDefinition uint64_to_be_bytes (n : T int64) : both0 ((nseq int8 8)) := lift_to_both (uint64_to_be_bytes n).\nDefinition uint64_from_le_bytes (n : T (nseq int8 8)) : both0 ((int64)) := lift_to_both (uint64_from_le_bytes n).\nDefinition uint64_from_be_bytes (n : T (nseq int8 8)) : both0 ((int64)) := lift_to_both (uint64_from_be_bytes n).\nDefinition uint128_to_le_bytes (n : T int128) : both0 ((nseq int8 16)) := lift_to_both (uint128_to_le_bytes n).\nDefinition uint128_to_be_bytes (n : T int128) : both0 ((nseq int8 16)) := lift_to_both (uint128_to_be_bytes n).\nDefinition uint128_from_le_bytes (n : T (nseq int8 16)) : both0 (int128) := lift_to_both (uint128_from_le_bytes n).\nDefinition uint128_from_be_bytes (n : T (nseq int8 16)) : both0 ((int128)) := lift_to_both (uint128_from_be_bytes n).\nDefinition u32_to_le_bytes (n : T int32) : both0 ((nseq int8 4)) := lift_to_both (u32_to_le_bytes n).\nDefinition u32_to_be_bytes (n : T int32) : both0 ((nseq int8 4)) := lift_to_both (u32_to_be_bytes n).\nDefinition u32_from_le_bytes (n : T (nseq int8 4)) : both0 ((int32)) := lift_to_both (u32_from_le_bytes n).\nDefinition u32_from_be_bytes (n : T (nseq int8 4)) : both0 ((int32)) := lift_to_both (u32_from_be_bytes n).\nDefinition u64_to_le_bytes (n : T int64) : both0 ((nseq int8 8)) := lift_to_both (u64_to_le_bytes n).\nDefinition u64_from_le_bytes (n : T (nseq int8 8)) : both0 ((int64)) := lift_to_both (u64_from_le_bytes n).\nDefinition u128_to_le_bytes (n : T int128) : both0 ((nseq int8 16)) := lift_to_both (u128_to_le_bytes n).\nDefinition u128_to_be_bytes (n : T int128) : both0 ((nseq int8 16)) := lift_to_both (u128_to_be_bytes n).\nDefinition u128_from_le_bytes (n : T (nseq int8 16)) : both0 ((int128)) := lift_to_both (u128_from_le_bytes n).\nDefinition u128_from_be_bytes (n : T (nseq int8 16)) : both0 ((int128)) := lift_to_both (u128_from_be_bytes n).\n\n(*** Nats *)\n\n\nSection Todosection.\n\nDefinition nat_mod_equal {p} (a b : nat_mod p) : both0 bool_ChoiceEquality :=\n  lift_to_both (@eqtype.eq_op (ordinal_eqType (S (Init.Nat.pred (Z.to_nat p)))) a b : bool_ChoiceEquality).\n\nDefinition nat_mod_equal_reflect {p} {a b} : Bool.reflect (a = b) (is_pure (@nat_mod_equal p a b)) :=\n  @eqtype.eqP (ordinal_eqType (S (Init.Nat.pred (Z.to_nat p)))) a b.\n\nDefinition nat_mod_zero {p} : both0 ((nat_mod p)) := lift_to_both (nat_mod_zero).\nDefinition nat_mod_one {p} : both0 ((nat_mod p)) := lift_to_both (nat_mod_one).\nDefinition nat_mod_two {p} : both0 ((nat_mod p)) := lift_to_both (nat_mod_two).\n\nDefinition nat_mod_add {n : Z} (a : nat_mod n) (b : nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_add a b).\nDefinition nat_mod_mul {n : Z} (a:nat_mod n) (b:nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_mul a b).\nDefinition nat_mod_sub {n : Z} (a:nat_mod n) (b:nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_sub a b).\nDefinition nat_mod_div {n : Z} (a:nat_mod n) (b:nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_div a b).\n\nDefinition nat_mod_neg {n : Z} (a:nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_neg a).\n\nDefinition nat_mod_inv {n : Z} (a:nat_mod n) : both0 (nat_mod n) := lift_to_both (nat_mod_inv a).\n\nDefinition nat_mod_exp_def {p : Z} (a:nat_mod p) (n : nat) : both0 (nat_mod p) :=\n  lift_to_both (nat_mod_exp_def a n).\n\nDefinition nat_mod_exp {WS} {p} a n := @nat_mod_exp_def p a (Z.to_nat (@unsigned WS n)).\nDefinition nat_mod_pow {WS} {p} a n := @nat_mod_exp_def p a (Z.to_nat (@unsigned WS n)).\nDefinition nat_mod_pow_felem {p} (a n : nat_mod p) := @nat_mod_exp_def p a (Z.to_nat (nat_of_ord n)).\nDefinition nat_mod_pow_self {p} (a n : nat_mod p) := nat_mod_pow_felem a n.\n\nClose Scope nat_scope.\n\nDefinition nat_mod_from_secret_literal {m : Z} (x:int128) : both0 (nat_mod m) :=\n lift_to_both (@nat_mod_from_secret_literal m x).\n\nDefinition nat_mod_from_literal (m : Z) (x:int128) : both0 ((nat_mod m)) := nat_mod_from_secret_literal x.\n\nDefinition nat_mod_to_byte_seq_le {n : Z} (m : nat_mod n) : both0 (seq int8) := lift_to_both (nat_mod_to_byte_seq_le m).\nDefinition nat_mod_to_byte_seq_be {n : Z} (m : nat_mod n) : both0 (seq int8) := lift_to_both (nat_mod_to_byte_seq_be m).\nDefinition nat_mod_to_public_byte_seq_le (n : Z) (m : nat_mod n) : both0 (seq int8) := lift_to_both (nat_mod_to_public_byte_seq_le n m).\nDefinition nat_mod_to_public_byte_seq_be (n : Z) (m : nat_mod n) : both0 (seq int8) := lift_to_both (nat_mod_to_public_byte_seq_be n m).\n\nDefinition nat_mod_bit {n : Z} (a : nat_mod n) (i : uint_size) : both0 bool_ChoiceEquality :=\n  lift_to_both (nat_mod_bit a i).\n\n(* Alias for nat_mod_bit *)\nDefinition nat_get_mod_bit {p} (a : nat_mod p) (i : uint_size) : both0 bool_ChoiceEquality := lift_to_both (nat_get_mod_bit a i).\nDefinition nat_mod_get_bit {p} (a : nat_mod p) n : both0 (nat_mod p) :=\n  lift_to_both (nat_mod_get_bit a n).\n\nDefinition array_declassify_eq {A l} (x : nseq A l) (y : nseq A l) : both0 bool_ChoiceEquality := lift_to_both0 (array_declassify_eq x y).\nDefinition array_to_le_uint32s {A l} (x : nseq A l) : both0 (seq uint32) := lift_to_both0 (array_to_le_uint32s x).\nDefinition array_to_be_uint32s {l} (x : nseq uint8 l) : both0 (seq uint32) := lift_to_both0 (array_to_be_uint32s x).\nDefinition array_to_le_uint64s {A l} (x : nseq A l) : both0 (seq uint64) := lift_to_both0 (array_to_le_uint64s x).\nDefinition array_to_be_uint64s {l} (x : nseq uint8 l) : both0 (seq uint64) := lift_to_both0 (array_to_be_uint64s x).\nDefinition array_to_le_uint128s {A l} (x : nseq A l) : both0 (seq uint128) := lift_to_both0 (array_to_le_uint128s x).\nDefinition array_to_be_uint128s {l} (x : nseq uint8 l) : both0 (seq uint128) := lift_to_both0 (array_to_be_uint128s x).\nDefinition array_to_le_bytes {A l} (x : nseq A l) : both0 (seq uint8) := lift_to_both0 (array_to_le_bytes x).\nDefinition array_to_be_bytes {A l} (x : nseq A l) : both0 (seq uint8) := lift_to_both0 (array_to_be_bytes x).\nDefinition nat_mod_from_byte_seq_le {A n} (x : seq A) : both0 (nat_mod n) := lift_to_both0 (nat_mod_from_byte_seq_le x).\nDefinition most_significant_bit {m} (x : nat_mod m) (n : uint_size) : both0 (uint_size) := lift_to_both0 (most_significant_bit x n).\n\n\n(* We assume 2^x < m *)\n\nDefinition nat_mod_pow2 (m : Z) {WS} (x : @int WS) : both0 ((nat_mod m)) :=\n  lift_to_both (nat_mod_pow2 m x).\n\nEnd Todosection.\n\nInfix \"+%\" := nat_mod_add (at level 33) : hacspec_scope.\nInfix \"*%\" := nat_mod_mul (at level 33) : hacspec_scope.\nInfix \"-%\" := nat_mod_sub (at level 33) : hacspec_scope.\nInfix \"/%\" := nat_mod_div (at level 33) : hacspec_scope.\n\n(*** Casting *)\n\nSection TodoSection2.\n\nDefinition uint128_from_usize (n : uint_size) : both0 int128 := lift_to_both (repr (unsigned n)).\nDefinition uint64_from_usize (n : uint_size) : both0 int64 := lift_to_both (repr (unsigned n)).\nDefinition uint32_from_usize (n : uint_size) : both0 int32 := lift_to_both (repr (unsigned n)).\nDefinition uint16_from_usize (n : uint_size) : both0 int16 := lift_to_both (repr (unsigned n)).\nDefinition uint8_from_usize (n : uint_size) : both0 int8 := lift_to_both (repr (unsigned n)).\n\nDefinition uint128_from_uint8 (n : int8) : both0 int128 := lift_to_both (repr (unsigned n)).\nDefinition uint64_from_uint8 (n : int8) : both0 int64 := lift_to_both (repr (unsigned n)).\nDefinition uint32_from_uint8 (n : int8) : both0 int32 := lift_to_both (repr (unsigned n)).\nDefinition uint16_from_uint8 (n : int8) : both0 int16 := lift_to_both (repr (unsigned n)).\nDefinition usize_from_uint8 (n : int8) : both0 uint_size := lift_to_both (repr (unsigned n)).\n\nDefinition uint128_from_uint16 (n : int16) : both0 int128 := lift_to_both (repr (unsigned n)).\nDefinition uint64_from_uint16 (n : int16) : both0 int64 := lift_to_both (repr (unsigned n)).\nDefinition uint32_from_uint16 (n : int16) : both0 int32 := lift_to_both (repr (unsigned n)).\nDefinition uint8_from_uint16 (n : int16) : both0 int8 := lift_to_both (repr (unsigned n)).\nDefinition usize_from_uint16 (n : int16) : both0 uint_size := lift_to_both (repr (unsigned n)).\n\nDefinition uint128_from_uint32 (n : int32) : both0 int128 := lift_to_both (repr (unsigned n)).\nDefinition uint64_from_uint32 (n : int32) : both0 int64 := lift_to_both (repr (unsigned n)).\nDefinition uint16_from_uint32 (n : int32) : both0 int16 := lift_to_both (repr (unsigned n)).\nDefinition uint8_from_uint32 (n : int32) : both0 int8 := lift_to_both (repr (unsigned n)).\nDefinition usize_from_uint32 (n : int32) : both0 uint_size := lift_to_both (repr (unsigned n)).\n\nDefinition uint128_from_uint64 (n : int64) : both0 int128 := lift_to_both (repr (unsigned n)).\nDefinition uint32_from_uint64 (n : int64) : both0 int32 := lift_to_both (repr (unsigned n)).\nDefinition uint16_from_uint64 (n : int64) : both0 int16 := lift_to_both (repr (unsigned n)).\nDefinition uint8_from_uint64 (n : int64) : both0 int8 := lift_to_both (repr (unsigned n)).\nDefinition usize_from_uint64 (n : int64) : both0 uint_size := lift_to_both (repr (unsigned n)).\n\nDefinition uint64_from_uint128 (n : int128) : both0 int64 := lift_to_both (repr (unsigned n)).\nDefinition uint32_from_uint128 (n : int128) : both0 int32 := lift_to_both (repr (unsigned n)).\nDefinition uint16_from_uint128 (n : int128) : both0 int16 := lift_to_both (repr (unsigned n)).\nDefinition uint8_from_uint128 (n : int128) : both0 int8 := lift_to_both (repr (unsigned n)).\nDefinition usize_from_uint128 (n : int128) : both0 uint_size := lift_to_both (repr (unsigned n)).\n\n\n(* Comparisons, boolean equality, and notation *)\n\nGlobal Instance int_eqdec `{WS : wsize}: EqDec (@int WS) := {\n  eqb := eqtype.eq_op ;\n  eqb_leibniz := int_eqb_eq ;\n}.\n\nGlobal Instance int_comparable `{WS : wsize} : Comparable (@int WS) :=\n    eq_dec_lt_Comparable (wlt Unsigned).\n\nDefinition uint8_equal (x y : int8) : both0 bool_ChoiceEquality := lift_to_both (eqb x y : bool_ChoiceEquality).\n\nTheorem nat_mod_eqb_spec : forall {p} (a b : nat_mod p),\n    is_pure (nat_mod_equal a b) = true <-> a = b.\nProof.\n  symmetry ; apply (ssrbool.rwP nat_mod_equal_reflect).\nQed.\n\nGlobal Instance nat_mod_eqdec {p} : EqDec (nat_mod p) := {\n  eqb a b := is_pure (nat_mod_equal a b);\n  eqb_leibniz := nat_mod_eqb_spec;\n}.\n\nGlobal Instance nat_mod_comparable `{p : Z} : Comparable (nat_mod p) :=\n  eq_dec_lt_Comparable (@order.Order.lt order.Order.OrdinalOrder.ord_display (order.Order.OrdinalOrder.porderType _)).\n\nDefinition nat_mod_rem {n : Z} (a:nat_mod n) (b:nat_mod n) : both0 (nat_mod n) :=\n  lift_to_both (nat_mod_rem a b).\n\n\nInfix \"rem\" := nat_mod_rem (at level 33) : hacspec_scope.\n\nGlobal Instance bool_eqdec : EqDec bool := {\n  eqb := Bool.eqb;\n  eqb_leibniz := Bool.eqb_true_iff;\n}.\n\nGlobal Instance string_eqdec : EqDec String.string := {\n  eqb := String.eqb;\n  eqb_leibniz := String.eqb_eq ;\n}.\n\nFixpoint list_eqdec {A} `{EqDec A} (l1 l2 : list A) : bool :=\n  match l1, l2 with\n  | x::xs, y::ys => if eqb x y then list_eqdec xs ys else false\n  | [], [] => true\n  | _,_ => false\n  end.\n\nLemma list_eqdec_refl : forall {A} `{EqDec A} (l1 : list A), list_eqdec l1 l1 = true.\nProof.\n  intros ; induction l1 ; cbn ; try rewrite eqb_refl ; easy.\nQed.\n\nLemma list_eqdec_sound : forall {A} `{EqDec A} (l1 l2 : list A), list_eqdec l1 l2 = true <-> l1 = l2.\nProof.\n  intros A H l1.\n  induction l1 ; induction l2 ; split ; intros ; simpl in * ; try easy ; try inversion H0.\n  - (* inductive case *)\n    apply Field_theory.if_true in H0; destruct H0.\n    f_equal.\n    (* show heads are equal *)\n    + apply (proj1 (eqb_leibniz a a0) H0).\n    (* show tails are equal using induction hypothesis *)\n    + apply IHl1. assumption.\n  - rewrite eqb_refl.\n    apply list_eqdec_refl.\nQed.\n\nGlobal Instance List_eqdec {A} `{EqDec A} : EqDec (list A) := {\n  eqb := list_eqdec;\n  eqb_leibniz := list_eqdec_sound;\n}.\n\nLemma vector_eqb_sound : forall {A : Type} {n : nat} `{EqDec A} (v1 v2 : VectorDef.t A n), Vector.eqb _ eqb v1 v2 = true <-> v1 = v2.\nProof.\n  intros.\n  apply Vector.eqb_eq.\n  intros.\n  apply eqb_leibniz.\nQed.\n\nGlobal Program Instance Vector_eqdec {A n} `{EqDec A}: EqDec (VectorDef.t A n) := {\n  eqb := Vector.eqb _ eqb;\n  eqb_leibniz := vector_eqb_sound;\n}.\n\nGlobal Program Instance Dec_eq_prod (A B : Type) `{EqDec A} `{EqDec B} : EqDec (A * B) := {\n  eqb '(a0, b0) '(a1, b1) := andb (eqb a0 a1) (eqb b0 b1)\n}.\nNext Obligation.\n  split ; intros ; destruct x ; destruct y.\n  - symmetry in H1.\n    apply Bool.andb_true_eq in H1. destruct H1.\n    symmetry in H1. rewrite (eqb_leibniz) in H1.\n    symmetry in H2. rewrite (eqb_leibniz) in H2.\n    rewrite H1. rewrite H2. reflexivity.\n  - inversion_clear H1. now do 2 rewrite eqb_refl.\nDefined.\n\nEnd TodoSection2.\n\n\n(*** Monad / Bind *)\n\nDefinition result_unwrap {a b} (x : result b a) : both0 (a) :=\n  lift_to_both (result_unwrap x).\nDefinition result_unwrap_safe {a b} (x : result b a) `{match x with inl _ => True | inr _ => False end} : both0 (a) :=\n  lift_to_both (result_unwrap_safe x (H := H)).\n\nModule ChoiceEqualityMonad.\n\n  Class BindCode (M : ChoiceEquality -> ChoiceEquality) `{mnd : @ChoiceEqualityMonad.CEMonad M}  :=\n    { bind_code [L : {fset Location}] {I} {A B : ChoiceEquality} (x : code L I (M A)) (f : A -> code L I (M B)) : code L I (M B) }.\n\n  Class BindBoth (M : ChoiceEquality -> ChoiceEquality) `{mnd : @ChoiceEqualityMonad.CEMonad M} `{H_bind_code : @BindCode M mnd} :=\n     {\n       code_eq : forall [L : {fset Location}] {I} {A B : ChoiceEquality} (x : both L I (M A)) (f : A -> both L I (M B)), \u22a2 \u2983 true_precond \u2984\n                     bind_code x (fun x0 : A => f x0)\n                     \u2248\n                     ret (y m(M) \u21e0 x ;; f y)\n                     \u2983 pre_to_post_ret true_precond (T_ct (y m(M) \u21e0 x ;; f y)) \u2984 ;\n       bind_both [L : {fset Location}] {I} {A B : ChoiceEquality} (x : both L I (M A)) (f : A -> both L I (M B))  :=\n       {|\n         is_state := bind_code x f ;\n         is_pure := y m(M) \u21e0 x ;; f y ;\n         code_eq_proof_statement := code_eq x f\n       |}\n    }.\n\n  Theorem bind_both_proj_code : forall  `{H_bind_code : BindCode} `{@BindBoth M mnd H_bind_code} {L : {fset Location}}  {I}  {A B : ChoiceEquality} (x : both L I (M A)) (y : code L I (M A)) (f : A -> both L I (M B)) (g : A -> code L I (M B)),\n      (prog (is_state x) = prog y) ->\n      (forall v, prog (is_state (f v)) = prog (g v)) ->\n      is_state (ChoiceEqualityMonad.bind_both x f) = ChoiceEqualityMonad.bind_code  (BindCode := H_bind_code) y g.\n    intros.\n    unfold bind_both.\n    unfold is_state at 1, lift_scope, is_state at 1.\n    f_equal.\n    apply code_ext. apply H0.\n    apply Coq.Logic.FunctionalExtensionality.functional_extensionality. intros.\n    apply code_ext. apply H1.\n  Qed.\n\n  #[global] Program Instance result_bind_code C : BindCode (result C) :=\n    {| bind_code L I A B x f :=\n      {code t_x \u2190 x ;;\n       match ct_T t_x with\n       | inl s => f s\n       | inr s => ret (Err s)\n       end} |}.\n  Next Obligation.\n    intros.\n    apply valid_bind.\n    apply prog_valid.\n    intros; cbn.\n    destruct ct_T.\n    - apply prog_valid.\n    - apply valid_ret.\n  Qed.\n\n  #[global] Program Instance result_bind_both C : BindBoth (result C).\n  Next Obligation.\n    intros.\n\n    pattern_both_fresh.\n    subst H.\n    apply (@r_bind_trans_both) with (b := x) (C := result C B).\n    intros ; subst H0 H1 ; hnf.\n\n    destruct ct_T eqn:xo ; rewrite ct_T_id in xo ; rewrite xo ; clear xo.\n    - exact (code_eq_proof_statement (f t)).\n    - now apply r_ret.\n  Qed.\n\n  #[global] Program Instance option_bind_code : BindCode (option_ChoiceEquality) :=\n    {| bind_code L I A B x f :=\n      {code t_x \u2190 x ;;\n       match ct_T t_x with\n       | Some s => f s\n       | None => ret (T_ct (@None B : option_ChoiceEquality B))\n       end} |}.\n  Next Obligation.\n    intros.\n    apply valid_bind.\n    apply prog_valid.\n    intros; cbn.\n    destruct ct_T.\n    - apply prog_valid.\n    - apply valid_ret.\n  Qed.\n\n  #[global] Program Instance option_bind_both : BindBoth (option_ChoiceEquality).\n  Next Obligation.\n    intros.\n\n    pattern_both_fresh.\n    subst H.\n    apply (@r_bind_trans_both) with (b := x) (C := option_ChoiceEquality B).\n    intros ; subst H0 H1 ; hnf.\n\n    destruct ct_T eqn:xo ; rewrite ct_T_id in xo ; rewrite xo ; clear xo.\n    - exact (code_eq_proof_statement (f t)).\n    - now apply r_ret.\n  Qed.\n\nEnd ChoiceEqualityMonad.\n\n(*** Result *)\n\nDefinition Ok {a b : ChoiceEquality} (x : a) : both0 (result b a) :=\n  lift_to_both (Ok x : result b a).\nDefinition Err {a b : ChoiceEquality} (x : b) : both0 (result b a) :=   lift_to_both (Err x : result b a).\n\nArguments Ok {_ _}.\nArguments Err {_ _}.\n\n\n(*** Notation *)\n\nProgram Definition let_both {L  : {fset Location}} {I} {A B : ChoiceEquality}\n        (x : both L I A)\n        (f : A -> both L I B)\n  : both L I B :=\n  {|\n    is_state := {code temp \u2190 is_state x ;; is_state (f (ct_T temp))} ;\n      is_pure := is_pure (f (is_pure x)) ;\n  |}.\nNext Obligation.\n  intros.\n  cbn.\n  replace (ret _) with (temp \u2190 ret (is_pure x) ;; ret (T_ct (is_pure (f (ct_T temp))))) by (cbn ; now rewrite ct_T_id).\n\n  eapply r_bind.\n  apply x.\n\n  intros.\n  apply rpre_hypothesis_rule.\n  intros ? ? [[] []]. subst.\n  eapply rpre_weaken_rule.\n  rewrite ct_T_id.\n  apply f.\n  reflexivity.\nQed.\n\nNotation \"'letb' x ':=' y 'in' f\" :=\n  (let_both (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'letb' ''' x ':=' y 'in' f\" :=\n  (let_both (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\n\nDefinition ChoiceEqualityLocation := \u2211 (t : ChoiceEquality), nat.\nDefinition CE_loc_to_loc :=\n  ((fun '(k ; n) => (ct k; n)) : ChoiceEqualityLocation -> Location).\nNotation \"'CE_loc_to_CE'\" := (@projT1 ChoiceEquality (fun _ => nat)).\nCoercion CE_loc_to_loc : ChoiceEqualityLocation >-> Location.\n\nEquations let_mut_code  {L : {fset Location}} {I} {B : ChoiceEquality}\n           (x_loc : ChoiceEqualityLocation)\n           `{H_in: is_true (ssrbool.in_mem (CE_loc_to_loc x_loc) (ssrbool.mem L))}\n           (x : code L I (CE_loc_to_CE x_loc)) (f : (CE_loc_to_CE x_loc) -> code L I B) : code L I B :=\n  let_mut_code (A; n) x f :=\n    {code\n       y \u2190 x ;;\n       #put (ct A; n) := y ;;\n       temp \u2190 get (ct A; n) ;;\n       f (ct_T temp) }.\nGlobal Transparent let_mut_code.\n\nNotation \"'letmc' x 'loc(' \u2113 ')' ':=' y 'in' f\" :=\n  (let_mut_code \u2113 (H_in := _) y (fun x => f x))\n    (at level 100, x pattern, right associativity).\nNotation \"'letmc' ''' x 'loc(' \u2113 ')' ':=' y 'in' f\" :=\n  (let_mut_code \u2113 (H_in := _) y (fun x => f x)) (at level 100, x pattern, right associativity).\n\nProgram Definition let_mut_both {L : {fset Location}} {I} {B : ChoiceEquality}\n        (x_loc : ChoiceEqualityLocation) `{H_in: is_true (ssrbool.in_mem (CE_loc_to_loc x_loc) (ssrbool.mem L))} (x : both L I (CE_loc_to_CE x_loc)) (f : (CE_loc_to_CE x_loc) -> both L I B) : both L I B :=\n  {|\n    is_state := letmc temp loc( x_loc ) := x in f ;\n     is_pure := is_pure (f (is_pure x)) ;\n  |}.\nNext Obligation.\n  intros.\n  cbn.\n  replace (ret _) with (temp \u2190 ret (is_pure x) ;; ret (T_ct (is_pure (f (ct_T temp))))) by (cbn ; now rewrite ct_T_id).\n\n  destruct x_loc as [A n].\n\n  eapply r_bind.\n  apply x.\n  intros.\n\n  apply rpre_hypothesis_rule.\n  intros ? ? [[] []]. subst.\n\n  apply better_r_put_get_lhs.\n  apply better_r_put_lhs.\n\n  rewrite !ct_T_id.\n  eapply rpre_weaken_rule with (pre := true_precond).\n  apply f.\n  reflexivity.\nQed.\n\nNotation \"'letbm' x 'loc(' \u2113 ')' ':=' y 'in' f\" :=\n  (let_mut_both \u2113 (H_in := _) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 200, x pattern, right associativity, format \"'letbm'  x  'loc(' \u2113 ')'  ':='  y  'in' '//' f\").\nNotation \"'letbm' ''' x 'loc(' \u2113 ')' ':=' y 'in' f\" :=\n  (let_mut_both \u2113 (H_in := _) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 200, x pattern, right associativity, format \"'letbm'  ''' x  'loc(' \u2113 ')'  ':='  y  'in' '//' f\").\n\nNotation \"'bnd(' M ',' A ',' B ',' L ')' x '\u21e0' y 'in' f\" := (ChoiceEqualityMonad.bind_code (BindCode := M) (A := A) (B := B) (L := L) (lift_code_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'bnd(' M ',' A ',' B ',' L ')' ' x '\u21e0' y 'in' f\" := (ChoiceEqualityMonad.bind_code (BindCode := M) (A := A) (B := B) (L := L) (lift_code_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\n\nNotation \"'letbnd(' M ')' x ':=' y 'in' f\" := (ChoiceEqualityMonad.bind_both (BindBoth := M) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'letbnd(' M ')' ' x ':=' y 'in' f\" := (ChoiceEqualityMonad.bind_both (BindBoth := M) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\n\nProgram Definition bind_code_mut  {L : {fset Location}} {I} `{H_bind_code : ChoiceEqualityMonad.BindCode} {B : ChoiceEquality} (x_loc : ChoiceEqualityLocation) {A : ChoiceEquality} `{H_loc : M A = (CE_loc_to_CE x_loc)} `{H_in: is_true (ssrbool.in_mem (CE_loc_to_loc x_loc) (ssrbool.mem L))} (x : code L I (CE_loc_to_CE x_loc)) (f : A -> code L I (M B)) : code L I (M B) .\nProof.\n  destruct x_loc as [? n].\n  cbn in *. subst.\n  refine ({code ChoiceEqualityMonad.bind_code x (fun temp => {code\n         #put (ct (M A) ; n) := T_ct (ChoiceEqualityMonad.ret temp) ;;\n                                f temp}) }).\nDefined.\n\nNotation \"'bndm(' M ',' A ',' B ',' L ')' x 'loc(' \u2113 ')'  '\u21e0' y 'in' f\" := (bind_code_mut (H_bind_code := M) (A := A) (B := B) (L := L) (H_loc := eq_refl) \u2113 y (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'bndm(' M ',' A ',' B ',' L ')' ' x 'loc(' \u2113 ')'  '\u21e0' y 'in' f\" := (bind_code_mut (H_bind_code := M) (A := A) (B := B) (L := L) (H_loc := eq_refl) \u2113 y (fun x => f)) (at level 100, x pattern, right associativity).\n\n\nDefinition bind_both_mut  {L : {fset Location}} {I} {A B : ChoiceEquality} (x_loc : ChoiceEqualityLocation) `{H_in: is_true (ssrbool.in_mem (CE_loc_to_loc x_loc) (ssrbool.mem L))} `{H_bind_both : ChoiceEqualityMonad.BindBoth} {H_loc : M A = (CE_loc_to_CE x_loc)} (x : both L I (CE_loc_to_CE x_loc)) (f : A -> both L I (M B)) : both L I (M B).\nProof.\n  destruct x_loc as [C n] eqn:x_loc_eq.\n  cbn in *.\n  rewrite <- H_loc in x , H_in.\n  refine {|\n    is_pure :=  'y m(M) \u21e0 is_pure x ;; is_pure (f y);\n      is_state := bind_code_mut ((M A ; n) : ChoiceEqualityLocation ) (is_state x) (fun x => is_state (f x)) (H_in := H_in)\n    |}.\n\n  Unshelve.\n  2: apply eq_refl.\n\n  intros.\n  subst.\n\n  unfold bind_code_mut.\n  unfold eq_rect.\n  unfold prog.\n\n  refine (code_eq_proof_statement (@ChoiceEqualityMonad.bind_both _ _ _ H_bind_both L I A B x (fun temp => {| is_state := {code #put ((ct (M A); n) : Location) := ChoiceEqualityMonad.ret temp ;; f temp } |}))).\n  unfold prog.\n  apply better_r_put_lhs.\n  eapply rpre_weaken_rule with (pre := true_precond).\n  apply (code_eq_proof_statement (f temp)).\n  easy.\nDefined.\n\nNotation \"'bndm(' M ',' A ',' B ',' L ')' x '\u21e0' y 'in' f\" := (ChoiceEqualityMonad.bind_code (BindCode := M) (A := A) (B := B) (L := L) y (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'bndm(' M ',' A ',' B ',' L ')' ' x '\u21e0' y 'in' f\" := (ChoiceEqualityMonad.bind_code (BindCode := M) (A := A) (B := B) (L := L) y (fun x => f)) (at level 100, x pattern, right associativity).\n\nNotation \"'letbndm(' M ')' x ':=' y 'in' f\" := (ChoiceEqualityMonad.bind_both (BindBoth := M) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\nNotation \"'letbndm(' M ')' ' x ':=' y 'in' f\" := (ChoiceEqualityMonad.bind_both (BindBoth := M) (lift_scope (H_loc_incl := _) (H_opsig_incl := _) y) (fun x => f)) (at level 100, x pattern, right associativity).\n\nProgram Definition foldi_bind_code' {A : ChoiceEquality} {L : {fset Location}} {I} `{H_bind_code : ChoiceEqualityMonad.BindCode} (a : uint_size) (b : uint_size)  (init : A) (f : uint_size -> A -> code (L) I (ct (M A)))  : code (L) I (M A) :=\n  {code\n   foldi\n     a b (ChoiceEqualityMonad.ret init)\n     (fun x y =>\n        ChoiceEqualityMonad.bind_code\n          (lift_to_code y)\n          (f x))\n  }.\n\nProgram Definition foldi_bind_code {A : ChoiceEquality} {L : {fset Location}} {I} `{H_bind_code : ChoiceEqualityMonad.BindCode} (lo : uint_size) (hi : uint_size)  (init : code (L) I (M A)) (f : uint_size -> A -> code (L) I (ct (M A)))  : code (L) I (M A) :=\n  {code\n     t \u2190 init ;;\n   foldi lo hi (ct_T t)\n     (fun x y =>\n        ChoiceEqualityMonad.bind_code\n          (lift_to_code y)\n          (f x))\n  }.\n\nProgram Definition foldi_both\n             {acc: ChoiceEquality}\n             (lo: T uint_size)\n             (hi: T uint_size) (* {lo <= hi} *)\n             (init: T acc)\n             {L}\n             {I}\n             (f: (T uint_size) -> T acc -> both L I acc) : both L I acc :=\n  {|\n    is_pure := Hacspec_Lib_Pre.foldi lo hi init f ;\n    is_state := foldi lo hi init f\n  |}.\nNext Obligation.\n  intros.\n  unfold foldi_pre.\n  unfold Hacspec_Lib_Pre.foldi.\n\n  destruct ((_ - unsigned lo)%Z) ; [ apply r_ret ; easy | | apply r_ret ; easy ].\n\n  generalize dependent lo.\n  clear.\n  generalize dependent init.\n\n  induction (Pos.to_nat p) ; intros.\n  - cbn.\n    apply r_ret ; easy.\n  - rewrite <- foldi__move_S.\n    rewrite <- Hacspec_Lib_Pre.foldi__move_S.\n\n    set (b' := f lo init).\n\n    pose @r_bind_trans_both.\n    specialize r with (b := b').\n\n    pattern_both_fresh.\n    apply r.\n    subst H H0 H1. hnf.\n    rewrite ct_T_id.\n\n    apply IHn.\nQed.\n\nDefinition foldi_both'\n             {acc: ChoiceEquality}\n             {L1} {L2} {L}\n             {I1} {I2} {I}\n             (lo: both L1 I1 uint_size)\n             (hi: both L2 I2 uint_size) (* {lo <= hi} *)\n             (init: acc)\n             (f: (T uint_size) -> T acc -> both L I acc)\n   : both L I acc :=\n  foldi_both lo hi init f.\n\nProgram Definition foldi_bind_both' {A : ChoiceEquality} {L1 L2 L : {fset Location}} {I1 I2 I}  `{ChoiceEqualityMonad.BindBoth} (lo : both L1 I1 uint_size) (hi : both L2 I2 uint_size) (init : A) (f : uint_size -> A -> both L I (M A))  : both L I (M A) :=\n  foldi_both lo hi (ChoiceEqualityMonad.ret init) (fun x y => ChoiceEqualityMonad.bind_both (lift_to_both y) (f x)).\n\nProgram Definition foldi_bind_both {A : ChoiceEquality} {L : {fset Location}} {I}  `{H_bind_both : ChoiceEqualityMonad.BindBoth} (lo : uint_size) (hi : uint_size) (init : both L I (M A)) (f : uint_size -> A -> both L I (M A))  : both L I (M A) :=\n  let_both init (fun init' =>\n  foldi_both lo hi init' (fun x y => ChoiceEqualityMonad.bind_both (lift_to_both y) (f x))).\n\nTheorem foldi_bind_both_proj_code' : forall {A : ChoiceEquality} {L1 L2 L : {fset Location}} {I1 I2 I}  `{H_bind_both : ChoiceEqualityMonad.BindBoth} (lo : both L1 I1 uint_size) (hi : both L2 I2 uint_size) (init : A) (f_both : uint_size -> A -> both L I (M A)) (a : uint_size) (b : uint_size) (f_code : uint_size -> A -> code (L) I (ct (M A))),\n    (forall i x, is_state (f_both i x) = f_code i x) ->\n    is_pure lo = a -> is_pure hi = b ->\n    is_state (foldi_bind_both' lo hi init f_both) = foldi_bind_code' a b init f_code.\nProof.\n  intros.\n  unfold foldi_bind_both'.\n  unfold foldi_bind_code'.\n\n  apply code_ext.\n\n  subst.\n\n  set ((fun (x0 : uint_size) (y : M A) => _)).\n  set ((fun (x0 : uint_size) (y : M A) => _)).\n  enough (y0 = y).\n  + now rewrite H0. subst y y0 ; hnf.\n    apply functional_extensionality. intros.\n    apply functional_extensionality. intros.\n    cbn.\n    f_equal.\n    apply functional_extensionality. intros.\n    now rewrite H.\nQed.\n\nTheorem foldi_bind_both_proj_code : forall {A : ChoiceEquality} {L : {fset Location}} {I}  `{H_bind_both : ChoiceEqualityMonad.BindBoth} (lo : uint_size) (hi : uint_size) (init_both : both L I (M A)) (f_both : uint_size -> A -> both L I (M A)) (init_code : code (L) I (M A)) (f_code : uint_size -> A -> code (L) I (ct (M A))),\n    is_state (init_both) = init_code ->\n    (forall i x, is_state (f_both i x) = f_code i x) ->\n    is_state (foldi_bind_both lo hi init_both f_both) = foldi_bind_code lo hi init_code f_code.\nProof.\n  intros.\n  unfold foldi_bind_both.\n  unfold let_both.\n  unfold is_state at 1.\n  unfold foldi_bind_code.\n  apply code_ext.\n  unfold prog.\n  f_equal.\n  - now rewrite H.\n  - apply functional_extensionality. intros.\n    set ((fun (x0 : uint_size) (y : M A) => _)).\n    set ((fun (x0 : uint_size) (y : M A) => _)).\n    enough (y0 = y).\n    + now rewrite H1. subst y y0 ; hnf.\n      apply functional_extensionality. intros.\n      apply functional_extensionality. intros.\n      cbn.\n      f_equal.\n      apply functional_extensionality. intros.\n      symmetry.\n      apply H0.\nQed.\n\nSection TodoSection3.\nDefinition nat_mod_from_byte_seq_be {A n} (x : seq A) : both0 (nat_mod n) := lift_to_both (nat_mod_from_byte_seq_be x).\n\n(*** Default *)\n\n(* Default instances for common types *)\nGlobal Instance nat_default : Default nat := {\n  default := 0%nat\n}.\nGlobal Instance N_default : Default N := {\n  default := 0%N\n}.\nGlobal Instance Z_default : Default Z := {\n  default := 0%Z\n}.\nGlobal Instance uint_size_default : Default uint_size := {\n  default := zero\n}.\nGlobal Instance int_size_default : Default int_size := {\n  default := zero\n}.\nGlobal Instance int_default {WS : wsize} : Default (@int WS) := {\n  default := repr 0\n  }.\n\nGlobal Instance nat_mod_default {p : Z} : Default (nat_mod p) := {\n  default := nat_mod_zero\n}.\nGlobal Instance prod_default {A B} `{Default A} `{Default B} : Default (prod A B) := {\n  default := (default, default)\n}.\n\nEnd TodoSection3.\n\nDefinition neqb {A : ChoiceEquality} `{EqDec A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (negb (eqb x y) : bool_ChoiceEquality).\nDefinition eqb {A : ChoiceEquality} `{EqDec A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (eqb x y : bool_ChoiceEquality).\n\nDefinition ltb {A : ChoiceEquality} `{Comparable A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (ltb x y : bool_ChoiceEquality).\nDefinition leb {A : ChoiceEquality} `{Comparable A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (leb x y : bool_ChoiceEquality).\nDefinition gtb {A : ChoiceEquality} `{Comparable A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (gtb x y : bool_ChoiceEquality).\nDefinition geb {A : ChoiceEquality} `{Comparable A} (x y : T A) : both0 bool_ChoiceEquality := lift_to_both (geb x y : bool_ChoiceEquality).\n\nInfix \"=.?\" := eqb (at level 40) : hacspec_scope.\nInfix \"!=.?\" := neqb (at level 40) : hacspec_scope.\nInfix \"<.?\" := ltb (at level 42) : hacspec_scope.\nInfix \"<=.?\" := leb (at level 42) : hacspec_scope.\nInfix \">.?\" := gtb (at level 42) : hacspec_scope.\nInfix \">=.?\" := geb (at level 42) : hacspec_scope.\n\nLemma foldi_nat_both :\n  forall {A : ChoiceEquality} {L : {fset Location}} {I} (lo hi : nat)\n    (b : nat -> A -> both L I A)\n    (v : A),\n  \u22a2 \u2983 true_precond \u2984\n      @foldi_nat _ lo hi b v\n  \u2248\n  lift_to_both (L := L) (I := I) (Hacspec_Lib_Pre.foldi_nat lo hi b v)\n  \u2983 pre_to_post_ret true_precond (T_ct (Hacspec_Lib_Pre.foldi_nat lo hi b v)) \u2984.\nProof.\n  intros.\n  unfold prog, lift_to_both, is_state at 2.\n  unfold foldi_nat.\n  unfold Hacspec_Lib_Pre.foldi_nat.\n\n    destruct (_ - lo).\n  { apply r_ret ; intros ; subst.\n    split.\n    - easy.\n    - easy.\n  }\n\n  generalize dependent lo.\n  clear.\n  generalize dependent v.\n\n  induction n ; intros.\n  - cbn.\n    unfold repr.\n\n    replace (fun cur' : choice.Choice.sort (chElement (ct A)) =>\n               @ret (chElement (ct A)) (@T_ct A (@ct_T A cur'))) with (@ret (chElement (ct A))) by (apply functional_extensionality ; intros ; now rewrite T_ct_id).\n    rewrite bind_ret.\n    apply (@code_eq_proof_statement).\n\n  - rewrite <- foldi__nat_move_S.\n    rewrite <- Hacspec_Lib_Pre.foldi__nat_move_S.\n\n    set (b' := b lo v).\n\n    pose @r_bind_trans_both.\n    specialize r with (b := b').\n\n    specialize r with (g := fun temp => @ret (chElement (ct A))\n       (@T_ct A\n          (@Hacspec_Lib_Pre.foldi_nat_ (T A) (S n) (S lo)\n             (fun (n0 : nat) (v0 : T A) => @is_pure L I A (b n0 v0))\n             temp))).\n    apply r.\n    intros.\n\n    rewrite ct_T_id.\n\n    apply IHn.\nQed.\n\nLemma foldi_as_both :\n  forall {A : ChoiceEquality} {L I} lo hi\n    (state : uint_size -> A -> code L I (ct A))\n    (pure : uint_size -> A -> T A)\n     v,\n    (unsigned lo <= unsigned hi)%Z ->\n    (forall x y,\n    \u22a2 \u2983 true_precond \u2984\n        state x y \u2248 lift_to_code (L := L) (I := I) (pure x y)\n    \u2983 pre_to_post_ret true_precond (T_ct (pure x y)) \u2984) ->\n  \u22a2 \u2983 true_precond \u2984\n     @foldi _ lo hi v L I state\n  \u2248\n     lift_to_both (L := L) (I := I) (Hacspec_Lib_Pre.foldi lo hi v pure)\n  \u2983 pre_to_post_ret true_precond (T_ct (Hacspec_Lib_Pre.foldi lo hi v pure)) \u2984.\nProof.\n  intros.\n  pose (fun x y => Build_both L I A (pure x y) (state x y) (H0 x y)).\n  apply (foldi_both lo hi v b).\nQed.\n\n(*** For loop again *)\n\n(* SSProve for loop is inclusive upperbound, while hacspec is exclusive upperbound *)\nDefinition for_loop_range\n  (lo: nat)\n  (hi: nat)\n  (f : nat -> raw_code 'unit) : raw_code 'unit :=\n  match hi - lo with\n  | O => @ret 'unit tt\n  | S i => for_loop (fun n => f (n + lo)) i\n  end.\n\nFixpoint CE_loc_list_to_loc_list (l : list ChoiceEqualityLocation) : list Location :=\n  match l with\n  | (t :: ts) => (CE_loc_to_loc t :: CE_loc_list_to_loc_list ts)\n  | [] => []\n  end.\nDefinition CEfset := fun x => fset (CE_loc_list_to_loc_list x).\n\nFixpoint list_types_ (l : list ChoiceEquality) (init : ChoiceEquality) : ChoiceEquality  :=\n  match l with\n  | (t :: ts) => list_types_ ts t '\u00d7 init\n  | [] => init\n  end.\n\nDefinition list_types (l : list ChoiceEquality) : ChoiceEquality :=\n  match l with\n  | [] => unit_ChoiceEquality\n  | (t :: ts) => list_types_ ts t\n  end.\n\nProgram Fixpoint vars_to_tuple (vars : list (\u2211 (t : ChoiceEquality), t)) {measure (length vars)} : list_types (seq.map (fun '(x ; y) => x) vars)  :=\n  match vars with\n  | [] => @ct_T unit_ChoiceEquality tt\n  | (x :: xs) =>\n      match xs with\n      | [] => _\n      | (s :: xs) => (vars_to_tuple (s :: xs) , _)\n      end\n  end.\n\nFixpoint for_loop_return_ (\u2113 : list ChoiceEqualityLocation) (vars : list (\u2211 (t : ChoiceEquality), t)) : raw_code (list_types (seq.cat (seq.map (fun '(x ; y) => x) vars) (seq.map (fun '(x ; y) => x) \u2113) )).\n\n  destruct \u2113 as [ | l ls ].\n  - rewrite seq.cats0.\n    pose (ret (vars_to_tuple vars)).\n    replace (fun pat : \u2211 t : ChoiceEquality, T t => _) with\n      (fun pat : @sigT ChoiceEquality\n       (fun t : ChoiceEquality => T t) =>\n         match pat return ChoiceEquality with\n         | @existT _ _ x _ => x\n         end)\n      in r by (apply functional_extensionality ; now intros []).\n    apply r.\n  - apply (getr (CE_loc_to_loc l)).\n    intros x.\n    destruct l.\n    cbn in x.\n    pose (for_loop_return_ ls (vars ++ [(_ ; ct_T x)])).\n    rewrite seq.map_cat in r.\n    cbn in r.\n    rewrite <- seq.catA in r.\n    cbn in r.\n    apply r.\nDefined.\n\nDefinition for_loop_return (\u2113 : list ChoiceEqualityLocation) : raw_code (list_types (seq.map (fun '(x ; y) => x) \u2113)) := for_loop_return_ \u2113 [].\n\nDefinition for_loop_locations\n           (lo: nat)\n           (hi: nat)\n           (\u2113 : list ChoiceEqualityLocation)\n           (f : nat -> raw_code 'unit) :=\n  match hi - lo with\n  | O => @ret 'unit tt\n  | S i => for_loop (fun n => f (n + lo)) i\n  end  ;; for_loop_return \u2113.\n\nTheorem r_bind_trans_as_both : forall {B C : ChoiceEquality} {L I} (f : choice.Choice.sort B -> raw_code C) (g : B -> raw_code C) (state : code L I (ct B))\n    (pure : T B),\n  forall (P : precond) (Q : postcond _ _),\n    (\u22a2 \u2983 true_precond \u2984\n        state \u2248 lift_to_code (L := L) (I := I) (pure)\n    \u2983 pre_to_post_ret true_precond (T_ct pure) \u2984) ->\n    (\u22a2 \u2983 true_precond \u2984 f (T_ct pure)  \u2248 g pure \u2983 Q \u2984) ->\n    (\u22a2 \u2983 P \u2984 temp \u2190 state ;; f temp \u2248 g (pure) \u2983 Q \u2984).\nProof.\n  intros.\n  eapply r_bind_trans with (P_mid := true_precond).\n\n  eapply rpre_weaken_rule.\n\n  pose (Build_both L I B (pure) (state)).\n\n  refine (code_eq_proof_statement (b _)). clear b.\n  apply H.\n\n  reflexivity.\n\n  intros.\n  apply H0.\nQed.\n\nLtac pattern_foldi_both Hx Hf Hg :=\n  match goal with\n    | [ |- context [ \u22a2 \u2983 _ \u2984 bind _ (foldi _ _ _ ?fb) \u2248 ?os \u2983 _ \u2984 ] ] =>\n        let H := fresh in\n        set (H := os)\n        ; set (Hx := Hacspec_Lib_Pre.foldi _ _ _ _) in H\n        ; pattern Hx in H\n        ; subst H\n        ; set (Hf := fb)\n        ; match goal with\n          | [ |- context [ \u22a2 \u2983 _ \u2984 _ \u2248 ?gb _ \u2983 _ \u2984 ] ] =>\n              set (Hg := gb)\n          end\n  | [ |- context [ \u22a2 \u2983 _ \u2984 prog (foldi _ _ _ ?fb) \u2248 ?os \u2983 _ \u2984 ] ] =>\n        let H := fresh in\n        set (H := os)\n        ; set (Hx := Hacspec_Lib_Pre.foldi _ _ _ _) in H\n        ; pattern Hx in H\n        ; subst H\n        ; set (Hf := fb)\n        ; match goal with\n          | [ |- context [ \u22a2 \u2983 _ \u2984 _ \u2248 ?gb _ \u2983 _ \u2984 ] ] =>\n              set (Hg := gb)\n          end\n    end.\n\nLtac pattern_foldi_both_fresh :=\n  let Hx := fresh in\n  let Hf := fresh in\n  let Hg := fresh in\n  pattern_foldi_both Hx Hf Hg.\n\nLtac progress_step_code :=\n  rewrite ct_T_id\n  || rewrite T_ct_id\n  || match_foldi_both\n  || (match_bind_trans_both)\n  || match goal with\n    | [ |- context [ \u22a2 \u2983 _ \u2984 (#put ?l := ?x ;; (getr ?l ?a)) \u2248 _ \u2983 _ \u2984 ]] =>\n        apply better_r_put_get_lhs\n    end\n  ||\n  match goal with\n  | [ |- context [ \u22a2 \u2983 _ \u2984 (#put ?l := ?x ;; (putr ?l ?y ?a)) \u2248 _ \u2983 _ \u2984 ]] =>\n      apply (r_transL (#put l := y ;; a )) ;\n      [ apply contract_put | ]\n  end\n  ||\n  match goal with\n  | [ |- context [ \u22a2 \u2983 _ \u2984 (#put ?l := ?x ;; ?a) \u2248 ?b \u2983 _ \u2984 ]] =>\n      apply (better_r_put_lhs l x a b)\n  end\n  ||\n  (unfold lift_to_code ; apply r_ret)\n  ||\n  (rewrite bind_assoc)\n    with\n    match_foldi_both :=\n    let Hx := fresh in\n    let Hf := fresh in\n    let Hg := fresh in\n    pattern_foldi_both Hx Hf Hg\n    ; try (apply (@r_bind_trans_as_both) with (f := Hf) (g := Hg))\n    ; intros ; subst Hf ; subst Hg ; subst Hx ; hnf\n    ; [apply foldi_as_both ; [ try (cbn ; Lia.lia) | intros ; unfold lift_to_code ; unfold prog ] | step_code]\n    with\n    step_code :=\n      repeat (clear_bind || progress_step_code) ; try easy\n        with\n        clear_bind :=\n        (unfold lift_to_code ;\n         match goal with\n         | [ |- context [ bind ?y (fun x => ret (T_ct _)) ] ] =>\n             let H := fresh in\n             set (H := y)\n\n             ; rewrite bind_ret\n             ; subst H\n         | [ |- context [ bind ?y (fun x => ret _) ] ] =>\n             let H := fresh in\n             set (H := y)\n\n             ; rewrite bind_ret\n             ; subst H\n         end)\n        ||\n        (repeat (rewrite bind_assoc)\n        ; match goal with\n          | [ |- context [ bind (ret (T_ct ?y)) (fun x => _) ] ] =>\n              let H := fresh in\n              set (H := y)\n\n              ; rewrite bind_rewrite\n              ; subst H\n          | [ |- context [ bind (ret ?y) (fun x => _) ] ] =>\n              let H := fresh in\n              set (H := y)\n              ; rewrite bind_rewrite\n              ; subst H\n          end).\n\n\nTheorem empty_put {B} \u2113 v (k h : raw_code B) :\n  \u22a2 \u2983 true_precond \u2984 k \u2248 h \u2983 pre_to_post true_precond \u2984 ->\n  \u22a2 \u2983 true_precond \u2984 #put \u2113 := v ;; k \u2248 h \u2983 pre_to_post true_precond \u2984.\nProof.\n  intros.\n  apply better_r_put_lhs.\n  eapply rpre_weaken_rule.\n  apply H.\n  intros.\n  reflexivity.\nQed.\n\n\nLtac ssprove_valid_step :=\n  (progress\n     (\n       cbv zeta\n       || unfold prog\n       || (repeat match goal with | [ |- context[ @T_ct (prod_ChoiceEquality ?ceA ?ceB) (?a , ?b) ] ] => rewrite @T_ct_prod_propegate end)\n       || (match goal with | [ |- context[ @bind ?A ?B (ret ?x) ?f ]] => rewrite bind_rewrite end)\n       || match goal with\n         | [ |- context[match ?x with | true => _ | false => _ end] ] =>\n             destruct x\n         end\n       || match goal with\n         | [ |- context[match ?x with | tt => _ end] ] =>\n             destruct x\n         end\n       || match goal with\n         | [ |- context[match ?x with | inl _ => _ | inr _ => _ end] ] =>\n             destruct x\n         end\n       || (match goal with | [ |- context[bind (bind ?v ?k1) ?k2] ] => rewrite bind_assoc end)\n       || (apply valid_bind ; [apply valid_scheme ; try rewrite <- fset.fset0E ; apply prog_valid | intros])\n       || (apply valid_bind ; [valid_program | intros])\n       || (apply valid_bind ; [repeat ssprove_valid_step | intros])\n       || (apply valid_opr ; [ ssprove_valid_opsig | intros ] )\n       ||  match goal with\n         | [ |- context [ putr _ _ _ ] ] => (apply valid_putr ; [ ssprove_valid_location | ])\n\n         end\n\n       || match goal with\n         | [ |- context [ getr _ _ ] ] => (apply valid_getr ; [ ssprove_valid_location | intros])\n         end\n       || apply valid_ret\n       || (match goal with\n          | [ |- context [ValidCode (fset ?ys) _ (@prog _ _ _ (@foldi _ ?lo ?hi (fset ?xs) _ ?f ?v))] ] =>\n              eapply (valid_subset_fset xs ys) ; [ | apply valid_foldi_pre ]\n              ; loc_incl_compute\n          end)\n       || (hnf in * ; destruct_choice_type_prod)\n  )).\n\nTheorem length_merge_sort_pop : forall {A} leb (l1 : list (list A)) (l2 : list A),\n    length (path.merge_sort_pop leb l2 l1) = length (seq.cat (seq.flatten l1) l2).\nProof.\n  intros.\n  generalize dependent l2.\n  induction l1 ; intros.\n  - cbn.\n    reflexivity.\n  - cbn.\n    rewrite IHl1.\n    rewrite seq.size_cat.\n    rewrite seq.size_cat.\n    rewrite seq.size_cat.\n    rewrite path.size_merge.\n    rewrite seq.size_cat.\n    rewrite ssrnat.addnA.\n    f_equal.\n    rewrite ssrnat.addnC.\n    reflexivity.\nQed.\n\nTheorem length_sort_even : forall {A} leb a x (l1 : list (list A)) (l2 : list A),\n    length (path.merge_sort_rec leb l1 (a :: x :: l2)) =\n    length (path.merge_sort_rec leb\n        (path.merge_sort_push leb (if leb a x then [a; x] else [x; a]) l1) l2).\nProof.\n  reflexivity.\nQed.\n\nTheorem length_sort_is_length' : forall {A} leb (l1 : list (list A)),\n    length (path.merge_sort_rec leb l1 []) = length (seq.flatten l1).\nProof.\n  destruct l1.\n  + cbn.\n    reflexivity.\n  + cbn.\n    rewrite length_merge_sort_pop.\n    rewrite seq.size_cat.\n    rewrite seq.size_cat.\n    rewrite path.size_merge.\n    rewrite seq.cats0.\n    rewrite ssrnat.addnC.\n    reflexivity.\nQed.\n\nLtac ssprove_valid'_2 :=\n  repeat ssprove_valid_step\n  ; ssprove_valid_program\n  ; try ssprove_valid_location.\n\nLtac ssprove_valid_package :=\n  (repeat apply valid_package_cons ; [ apply valid_empty_package | .. | try (rewrite <- fset0E ; setoid_rewrite @imfset0 ; rewrite in_fset0 ; reflexivity) ] ; intros ; progress unfold prog).\n\nLtac solve_zero :=\n  match goal with\n  | [ |- context [ (_ <= _)%Z ] ] =>\n      cbn ;\n      match goal with\n      | [ |- context [ (0 <= toword ?x)%Z ] ] =>\n          let H := fresh in\n          let H_zero := fresh in\n          let H_succ := fresh in\n          set (H := x)\n          ; destruct_uint_size_as_nat_named H H_zero H_succ\n          ; [ reflexivity | cbn in H_succ ; cbn ; try rewrite H_succ ; Lia.lia ]\n      end\n  end.\n\nLtac ssprove_package_obligation :=\n  setoid_rewrite (ssrbool.elimT (@fsetUidPl _ _ _)) ; [ reflexivity | ] ;\n  repeat rewrite fsubUset ;\n  repeat rewrite (ssrbool.introT (@ssrbool.andP _ _)) ;\n  repeat split ;\n  try reflexivity ;\n  try apply -> loc_list_incl_remove_fset ;\n  pose loc_list_incl_expand ;\n  rewrite loc_list_incl_fsubset ;\n  loc_incl_compute.\n\nLtac solve_ssprove_obligations :=\n  intros ;\n  try repeat rewrite fsetUid ;\n  try repeat rewrite <- fset_cat ;\n  try repeat rewrite fsetU0 ;\n  try repeat rewrite fset0U ;\n  try repeat rewrite fsetUid ;\n  (ssprove_valid_location || loc_incl_compute || opsig_incl_compute || ssprove_package_obligation)\n  || (match goal with\n     | [ |- context [ pkg_composition.Parable _ _ ]] =>\n         unfold pkg_composition.Parable, fdisjoint, fsetI, fset_filter,\n                fmap.domm, fmap.FMap.fmval, fmap.mkfmap, fmap.setm, fmap.fmap, fset\n         ; now rewrite ssreflect.locked_withE\n     end)\n  || now repeat rewrite <- fset_cat\n  || (ssprove_valid_package ; ssprove_valid'_2)\n  || ssprove_valid'_2\n  || (try (Tactics.program_simpl; fail))\n  .\n\nDefinition andb (x y : bool_ChoiceEquality) : both0 bool_ChoiceEquality := lift_to_both (andb x y : bool_ChoiceEquality).\n\nInfix \"&&\" := andb : bool_scope.\n\nDefinition orb (x y : bool_ChoiceEquality) : both0 bool_ChoiceEquality := lift_to_both (orb x y : bool_ChoiceEquality).\n\nInfix \"||\" := orb : bool_scope.\n\nDefinition negb (x : bool_ChoiceEquality) : both0 bool_ChoiceEquality := lift_to_both (negb x : bool_ChoiceEquality).\n\nProgram Definition ret_both  {L : {fset Location}} {I} `{ChoiceEqualityMonad.CEMonad} {A : ChoiceEquality} (x : A) : both L I (M A) := lift_to_both (ChoiceEqualityMonad.ret x).\n\nLtac init_both_proof b_state b_pure :=\n  intros ;\n  unfold lift_to_code ;\n  cbv delta [b_state] ;\n  cbn beta ;\n  let H := fresh in\n  match goal with\n  | [ |- context [(prog {code ?x})] ] =>\n      set (H := x)\n  end ;\n  unfold prog ;\n  cbv delta [b_pure] ;\n  subst H ;\n  cbn beta.\n\nLtac foldi_state_eq_code :=\n  erewrite <- @foldi_bind_both_proj_code' ; [ reflexivity | intros ; hnf | reflexivity | reflexivity  ].\nLtac bind_both_eq_code :=\n  erewrite <- @ChoiceEqualityMonad.bind_both_proj_code ; [ reflexivity | hnf | reflexivity ].\n\n\nTheorem letbm_proj_code :\n  forall (L1 L2 : {fset Location}) `{H_loc_incl : List.incl L1 L2} {I1 I2 : {fset opsig}} `{H_opsig_incl : List.incl I1 I2} B (i : ChoiceEqualityLocation),\n  forall `{H_in : is_true (ssrbool.in_mem (CE_loc_to_loc i) (ssrbool.mem L2))} (x : both L1 I1 (CE_loc_to_CE i)) (f : (CE_loc_to_CE i) -> both L2 I2 B) (y : code L1 I1 (CE_loc_to_CE i)) (g : (CE_loc_to_CE i) -> code L2 I2 B),\n    is_state x = y ->\n    (forall x, is_state (f x) = (g x)) ->\n    is_state ((let_mut_both i (H_in := H_in) (lift_scope (H_loc_incl := H_loc_incl) (H_opsig_incl := H_opsig_incl) x) f)) =\n    let_mut_code i (H_in := H_in) (lift_code_scope (H_loc_incl := H_loc_incl) (H_opsig_incl := H_opsig_incl) y) g\n    .\nProof.\n  intros L1 L2 H_loc_incl I1 I2 H_opsig_incl B [A n].\n  intros H_in x f y g H_var_eq H_fun_eq.\n  apply code_ext. unfold prog.\n  unfold let_mut_both, is_state at 1.\n  unfold lift_scope. unfold is_state at 1.\n  rewrite let_mut_code_equation_1.\n  unfold prog.\n  unfold lift_code_scope.\n  rewrite H_var_eq.\n  apply f_equal.\n  apply functional_extensionality. intros.\n  apply f_equal.\n  apply f_equal.\n  apply functional_extensionality. intros.\n  now rewrite H_fun_eq.\nQed.\n\nLtac letbm_eq_code :=\n  match goal with\n  | [ |- context [let_mut_both _ (lift_scope ?k) ?f] ] =>\n      erewrite letbm_proj_code with (g := f) (y := k) ; [ hnf | reflexivity | reflexivity ]\n  end.\nLtac f_equal_fun_ext :=\n  repeat (apply f_equal ; try (apply Coq.Logic.FunctionalExtensionality.functional_extensionality ; intros)).\n\nDefinition u32_word_t := nseq uint8 4.\nDefinition u128_word_t := nseq uint8 16.\n\nLemma letbm_ret_r :\n  forall {A : choice.Choice.type} {B : ChoiceEquality}\n    (r\u2081 : raw_code A) (pre : precond)\n    (post : postcond (choice.Choice.sort A) (choice.Choice.sort B))\n    (\u2113 : ChoiceEqualityLocation)\n    (L : {fset Location})\n    (I : Interface)\n    v (f : _ -> both L I B) (H_in : is_true (ssrbool.in_mem (CE_loc_to_loc \u2113) (ssrbool.mem L))),\n    \u22a2 \u2983 (set_rhs (@existT choice_type (fun _ : choice_type => nat) (ct (projT1 \u2113)) (projT2 \u2113)) v pre) \u2984 r\u2081 \u2248 f v \u2983 post \u2984 ->\n    \u22a2 \u2983 pre \u2984 r\u2081 \u2248 let_mut_both \u2113 (H_in := H_in) (lift_to_both (ct_T v)) f \u2983 post \u2984.\nProof.\n  intros.\n  cbn.\n  unfold let_mut_code.\n  unfold lift_to_code.\n  unfold Hacspec_Lib.let_mut_both_obligation_1.\n  cbn.\n  destruct \u2113.\n  cbn.\n  apply better_r_put_get_rhs.\n  apply better_r, r_put_rhs.\n  rewrite !T_ct_id.\n  apply H.\nQed.\n\nLemma letbm_ret_l :\n  forall {A : ChoiceEquality} {B : choice.Choice.type}\n    (r\u2080 : raw_code A)\n    (r\u2081 : raw_code B) (pre : precond)\n    (post : postcond (choice.Choice.sort A) (choice.Choice.sort B))\n    (\u2113 : ChoiceEqualityLocation)\n    (L : {fset Location})\n    (I : Interface)\n    v (f : _ -> both L I A) (H_in : is_true (ssrbool.in_mem (CE_loc_to_loc \u2113) (ssrbool.mem L))),\n    \u22a2 \u2983 (set_lhs (@existT choice_type (fun _ : choice_type => nat) (ct (projT1 \u2113)) (projT2 \u2113)) v pre) \u2984 f v \u2248 r\u2081 \u2983 post \u2984 ->\n    \u22a2 \u2983 pre \u2984 let_mut_both \u2113 (H_in := H_in) (lift_to_both (ct_T v)) f \u2248 r\u2081 \u2983 post \u2984.\nProof.\n  intros.\n  cbn.\n  unfold let_mut_code.\n  unfold lift_to_code.\n  unfold Hacspec_Lib.let_mut_both_obligation_1.\n  cbn.\n  destruct \u2113.\n  apply better_r_put_get_lhs.\n  apply better_r_put_lhs.\n  rewrite !T_ct_id.\n  apply H.\nQed.\n", "meta": {"author": "hacspec", "repo": "hacspec", "sha": "00601ff65cc9a745c5191282986721d0fcb5f4f7", "save_path": "github-repos/coq/hacspec-hacspec", "path": "github-repos/coq/hacspec-hacspec/hacspec-00601ff65cc9a745c5191282986721d0fcb5f4f7/coq_ssprove/src/Hacspec_Lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3812195521959384, "lm_q1q2_score": 0.19209888467786623}}
{"text": "Require Import Coq.Lists.ListSet.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Maps.\n\n(** External function specifications and linking *)\n\nDefinition PTree_injective {A} (t: PTree.t A) : Prop :=\n  forall id1 id2 b, t ! id1 = Some b -> t ! id2 = Some b -> id1 = id2.\n\nDefinition injective_PTree A := sig (@PTree_injective A).\n\nStructure external_specification (M E Z : Type) :=\n  { ext_spec_type : E -> Type\n  ; ext_spec_pre: forall e: E,\n    ext_spec_type e -> injective_PTree block -> list typ -> list val -> Z -> M -> Prop\n  ; ext_spec_post: forall e: E,\n    ext_spec_type e -> injective_PTree block -> rettype -> option val -> Z -> M ->  Prop\n  ; ext_spec_exit: option val -> Z -> M ->  Prop }.\n\nArguments ext_spec_type {M E Z} _ _.\nArguments ext_spec_pre {M E Z} _ _ _ _ _ _ _ _.\nArguments ext_spec_post {M E Z} _ _ _ _ _ _ _ _.\nArguments ext_spec_exit {M E Z} _ _ _ _.\n\nDefinition ext_spec := external_specification mem external_function.\n\nLemma extfunct_eqdec (ef1 ef2 : external_function) : {ef1=ef2} + {~ef1=ef2}.\nProof.\nrepeat decide equality; try apply Integers.Int.eq_dec.\nDefined.\n\nSet Implicit Arguments.\n\nDefinition ef_ext_spec (M Z : Type) :=\n  external_specification M AST.external_function Z.\n\nDefinition spec_of\n  (M Z : Type) (ef : AST.external_function) (spec : ef_ext_spec M Z) :=\n  (ext_spec_pre spec ef, ext_spec_post spec ef).\n\nDefinition oval_inject j (v tv : option val) :=\n  match v, tv with\n    | None, None => True\n    | Some v', Some tv' => Val.inject j v' tv'\n    | _, _ => False\n  end.\n\nModule ExtSpecProperties.\n\nDefinition det (M E Z : Type) (spec : external_specification M E Z) :=\n  forall ef (x x' : ext_spec_type spec ef) ge tys z vals m\n         oty' ov' z' m' oty'' ov'' z'' m'',\n  ext_spec_pre spec ef x ge tys vals z m ->\n  ext_spec_post spec ef x ge oty' ov' z' m' ->\n  ext_spec_pre spec ef x' ge tys vals z m ->\n  ext_spec_post spec ef x' ge oty'' ov'' z'' m'' ->\n  oty'=oty'' /\\ ov'=ov'' /\\ z'=z'' /\\ m'=m''.\n\nRecord closed (Z : Type) (spec : ext_spec Z) :=\n  { P_closed :\n      forall ef (x : ext_spec_type spec ef) ge j tys vals z m tvals tm,\n      ext_spec_pre spec ef x ge tys vals z m ->\n      Val.inject_list j vals tvals ->\n      Mem.inject j m tm ->\n      ext_spec_pre spec ef x ge tys tvals z tm\n  ; Q_closed :\n      forall ef (x : ext_spec_type spec ef) ge j oty ov z m otv tm,\n      ext_spec_post spec ef x ge oty ov z m ->\n      oval_inject j ov otv ->\n      Mem.inject j m tm ->\n      ext_spec_post spec ef x ge oty otv z tm\n  ; exit_closed :\n      forall j ov z m otv tm,\n      ext_spec_exit spec ov z m ->\n      oval_inject j ov otv ->\n      Mem.inject j m tm ->\n      ext_spec_exit spec otv z tm }.\n\nEnd ExtSpecProperties.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/extspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.19202965930932434}}
{"text": "Require Import Coq.omega.Omega.\n(* Structured programming (module construction) *)\n\nRequire Import Coq.Bool.Bool Coq.NArith.NArith Coq.Strings.String Coq.Lists.List.\n\nRequire Import Bedrock.Nomega Bedrock.PropX Bedrock.PropXTac Bedrock.Word Bedrock.LabelMap Bedrock.IL Bedrock.XCAP Bedrock.Structured.\nRequire Import Bedrock.StringSet.\n\nSet Implicit Arguments.\n\nLocal Open Scope N_scope.\n\nImport DefineStructured.\n\nSection module.\n  Definition import := (string * string * assert)%type.\n\n  Variable imports : list import.\n  (* Which functions from outside this module do we need? *)\n\n  Variable modName : string.\n  (* New module name *)\n\n  Definition function := (string * assert * forall imports, importsGlobal imports -> cmd imports modName)%type.\n\n  Variable functions : list function.\n  (* All functions in this module. *)\n\n  (* Build the full list of imports for the commands, including both external and internal functions.\n   * First, we build a version for only the external functions. *)\n\n  Definition importsMap : LabelMap.t assert :=\n    List.fold_left (fun m p => let '(modl, f, pre) := p in\n      LabelMap.add (modl, Global f) pre m) imports (LabelMap.empty _).\n\n  Lemma importsMapGlobal' : forall (im : list import) m,\n    importsGlobal m\n    -> importsGlobal (List.fold_left (fun m p => let '(modl, f, pre) := p in\n      LabelMap.add (modl, Global f) pre m) im m).\n    unfold importsGlobal; induction im as [ | [ ] ]; simpl; intuition.\n    apply IHim in H0; auto.\n    intros.\n    apply LabelFacts.add_mapsto_iff in H1; intuition; subst; simpl; eauto.\n  Qed.\n\n  Theorem importsMapGlobal : importsGlobal importsMap.\n    apply importsMapGlobal'; red; intros.\n    destruct (LabelMap.empty_1 H).\n  Qed.\n\n  Definition fullImports : LabelMap.t assert :=\n    List.fold_left (fun m p => let '(f, pre, _) := p in\n      LabelMap.add (modName, Global f) pre m) functions importsMap.\n\n  Lemma fullImportsGlobal' : forall (fs : list function) m,\n    importsGlobal m\n    -> importsGlobal (List.fold_left (fun m p => let '(f, pre, _) := p in\n      LabelMap.add (modName, Global f) pre m) fs m).\n    induction fs as [ | [ ] ]; simpl; intuition.\n    apply IHfs; red; intros.\n    apply LabelFacts.add_mapsto_iff in H0; intuition; subst; simpl; eauto.\n  Qed.\n\n  Theorem fullImportsGlobal : importsGlobal fullImports.\n    apply fullImportsGlobal'; apply importsMapGlobal.\n  Qed.\n\n  (* Now we are ready to generate a module out of the functions. *)\n\n  Definition buildLocals (bls : list (assert * block)) Base := snd (List.fold_left (fun b_m p => let '(b, m) := b_m in\n    (Nsucc b, LabelMap.add (modName, Local b) p m)) bls (Base, LabelMap.empty _)).\n\n  Fixpoint blocks (fs : list function) (Base : N) : LabelMap.t (assert * block) :=\n    match fs with\n      | nil => LabelMap.empty _\n      | (f, pre, c) :: fs' =>\n        let cout := c fullImports fullImportsGlobal pre in\n        let cg := Generate cout (Nsucc Base) Base in\n        LabelMap.add (modName, Global f) (pre, (nil, Uncond (RvLabel (modName, Local (Nsucc Base + Entry cg)))))\n          (LabelMap.add (modName, Local Base) (Postcondition cout, (nil, Uncond (RvLabel (modName, Local Base))))\n            (union (buildLocals (Blocks cg) (Nsucc Base))\n              (blocks fs' (Nsucc Base + N_of_nat (length (Blocks cg))))))\n    end.\n\n  Fixpoint exps (fs : list function) : LabelMap.t assert :=\n    match fs with\n      | nil => LabelMap.empty _\n      | (f, pre, _) :: fs' => LabelMap.add (modName, Global f) pre (exps fs')\n    end.\n\n  Definition bmodule_ : module := {|\n    Imports := importsMap;\n    XCAP.Blocks := blocks functions 1;\n    Exports := exps functions;\n    Modules := StringSet.singleton modName\n  |}.\n\n  Lemma Forall_MapsTo : forall A (P : _ * A -> Prop) m,\n    (forall k v, LabelMap.MapsTo k v m -> P (k, v))\n    -> List.Forall P (LabelMap.elements m).\n    intros.\n    generalize (fun k v H' => H k v (LabelMap.elements_2 H')); clear H; intro H.\n    induction (LabelMap.elements m); simpl in *; intuition.\n    constructor; auto.\n    destruct a.\n    apply H.\n    constructor; hnf; auto.\n  Qed.\n\n  Hypothesis NoSelfImport :\n    List.fold_left (fun b p => let '(m, _, _) := p in\n      b || if string_dec m modName then true else false) imports false = false.\n\n  Theorem importsNotThis : forall l, LabelMap.In (elt:=assert) (modName, l) importsMap -> False.\n    intros.\n    assert (forall k v, LabelMap.MapsTo k v (LabelMap.empty assert) -> k <> (modName, l)).\n    intros.\n    apply LabelMap.empty_1 in H0; tauto.\n    destruct H.\n    unfold importsMap in *.\n    generalize dependent (LabelMap.empty assert).\n    generalize NoSelfImport; clear NoSelfImport.\n    generalize false at 2.\n    induction imports; simpl in *; intuition.\n    apply H0 in H; auto.\n    destruct a as [ [ ] ]; simpl in *.\n    eapply IHl0 in NoSelfImport.\n    auto.\n    eauto.\n    intros; subst.\n    apply LabelFacts.add_mapsto_iff in H1; intuition; subst; [ | eauto ].\n    destruct (string_dec s modName); subst; try congruence.\n    replace (b || true) with true in NoSelfImport by (destruct b; auto).\n    generalize NoSelfImport; clear.\n    induction l0; simpl; intuition.\n    destruct a as [ [ ] ]; intuition.\n  Qed.\n\n  Hint Immediate importsNotThis.\n\n  Theorem importsNotThis' : forall l v, LabelMap.MapsTo (elt:=assert) (modName, l) v importsMap -> False.\n    intros; eapply importsNotThis.\n    hnf.\n    eauto.\n  Qed.\n\n  Hint Resolve importsNotThis'.\n\n  Lemma Forall_nth_error : forall A (P : A -> Prop) x ls,\n    List.Forall P ls\n    -> forall n, nth_error ls n = Some x\n      -> P x.\n    induction 1; destruct n; simpl; intuition; try discriminate.\n    injection H1; congruence.\n    eauto.\n  Qed.\n\n  Hypothesis NoDupFunc :\n    match (List.fold_left (fun mOpt p => let '(modl, _, _) := p in\n      match mOpt with\n        | None => None\n        | Some m => let k := (modl, Local 0) in\n          if LabelMap.mem k m then None\n          else Some (LabelMap.add k tt m)\n      end) functions (Some (LabelMap.empty unit))) with\n      | None => False\n      | Some _ => True\n    end.\n\n  Fixpoint makeVcs (fs : list function) : list Prop :=\n    match fs with\n      | nil => nil\n      | f :: fs' =>\n        let '(_, pre, c) := f in\n          let cout := c fullImports fullImportsGlobal pre in\n            (forall stn_st specs, ~interp specs (Postcondition cout stn_st))\n            :: VerifCond cout\n            ++ makeVcs fs'\n    end.\n\n  Hypothesis BlocksGood : vcs (makeVcs functions).\n\n  Lemma BlocksGood' : List.Forall (fun f : function => let '(_, pre, c) := f in\n    let cout := c fullImports fullImportsGlobal pre in\n    (forall stn_st specs, ~interp specs (Postcondition cout stn_st))\n    /\\ vcs (VerifCond cout)) functions.\n    generalize BlocksGood; clear.\n    induction functions; simpl; intuition.\n    destruct a as [ [ ] ].\n    inversion BlocksGood; subst; intuition.\n    constructor; intuition.\n    eapply vcs_app_bwd1; eauto.\n    apply IHl; eapply vcs_app_bwd2; eauto.\n  Qed.\n\n  Theorem buildLocals_notImport' : forall k v Base bls Base',\n    LabelMap.MapsTo k v (buildLocals bls Base')\n    -> Base' >= Base\n    -> exists l, k = (modName, Local l) /\\ l >= Base /\\ l < Base' + N_of_nat (length bls).\n    unfold buildLocals; intros.\n    assert (LabelMap.MapsTo k v (LabelMap.empty (assert * block)) -> exists l, k = (modName, Local l) /\\ l >= Base /\\ l < Base' + N_of_nat (length bls))\n      by (intro uhoh; destruct (LabelMap.empty_1 uhoh)).\n    generalize dependent (LabelMap.empty (assert * block)).\n    generalize dependent Base'; clear; induction bls; simpl; intuition.\n    assert (Nsucc Base' >= Base) by nomega.\n    destruct (IHbls _ H2 _ H); clear IHbls; intuition.\n    apply LabelFacts.add_mapsto_iff in H3; intuition; subst; eauto.\n    repeat esplit.\n    auto.\n    nomega.\n    destruct H4; intuition.\n    repeat esplit; eauto.\n    nomega.\n    repeat esplit; eauto.\n    nomega.\n  Qed.\n\n  Theorem buildLocals_notImport : forall k v Base bls,\n    LabelMap.MapsTo k v (buildLocals bls Base)\n    -> exists l, k = (modName, Local l) /\\ l >= Base /\\ l < Base + N_of_nat (length bls).\n    intros; eapply buildLocals_notImport'; eauto; nomega.\n  Qed.\n\n  Lemma getLocal : forall v bls Base Entry,\n    nth_error bls (nat_of_N Entry) = Some v\n    -> LabelMap.MapsTo (modName, Local (Base + Entry)) v (buildLocals bls Base).\n    unfold buildLocals; intros.\n    generalize (LabelMap.empty (assert * block)).\n    generalize dependent Base.\n    generalize dependent Entry.\n    induction bls; simpl; intuition.\n    elimtype False.\n    destruct (nat_of_N Entry); discriminate.\n    destruct (N_eq_dec Entry 0); subst; simpl in *.\n    injection H; clear H; intros; subst.\n    replace (Base + 0) with Base by nomega.\n    assert (LabelMap.MapsTo (modName, Local Base) (a0, b) (LabelMap.add (modName, Local Base) (a0, b) t))\n      by (apply LabelMap.add_1; auto).\n    generalize H; clear.\n    generalize (LabelMap.add (modName, Local Base) (a0, b) t).\n    assert (Base < Nsucc Base) by nomega.\n    generalize dependent (Nsucc Base).\n    induction bls; simpl; intuition; eauto.\n    apply IHbls.\n    nomega.\n    apply LabelMap.add_2; eauto.\n\n    replace (Base + Entry) with (Nsucc Base + (Entry - 1)) by nomega.\n    apply IHbls.\n    autorewrite with N; simpl.\n    assert (nat_of_N Entry <> O).\n    nomega.\n    destruct (nat_of_N Entry); simpl in *.\n    tauto.\n    replace (n0 - 0)%nat with n0 by omega; auto.\n  Qed.\n\n  Lemma ungetLocal' : forall A k v bls Base (m : LabelMap.t A),\n    LabelMap.MapsTo k v (snd (List.fold_left (fun b_m p => let '(b, m) := b_m in\n      (Nsucc b, LabelMap.add (modName, Local b) p m)) bls (Base, m)))\n    -> LabelMap.MapsTo k v m\n    \\/ exists n, nth_error bls n = Some v /\\ k = (modName, Local (Base + N_of_nat n)).\n    clear; induction bls; simpl; intuition.\n    apply IHbls in H; clear IHbls; intuition.\n    apply LabelFacts.add_mapsto_iff in H0; intuition; subst.\n    right; exists O; intuition.\n    do 2 f_equal; nomega.\n    destruct H0; intuition; subst.\n    right; exists (S x); intuition.\n    do 2 f_equal; nomega.\n  Qed.\n\n  Lemma ungetLocal : forall k v bls Base,\n    LabelMap.MapsTo k v (buildLocals bls Base)\n    -> exists n, nth_error bls n = Some v /\\ k = (modName, Local (Base + N_of_nat n)).\n    unfold buildLocals; intros.\n    apply ungetLocal' in H; intuition.\n    destruct (LabelMap.empty_1 H0).\n  Qed.\n\n  Hint Extern 1 (_ >= _) => nomega.\n\n  Lemma MapsTo_blocks : forall k v fs Base,\n    LabelMap.MapsTo k v (blocks fs Base)\n    -> exists f, exists pre, exists c, In (f, pre, c) fs\n      /\\ exists Base', Base' >= Base /\\\n        let cout := c fullImports fullImportsGlobal pre in\n        let cg := Generate (c fullImports fullImportsGlobal pre) (Nsucc Base') Base' in\n          (forall n v', nth_error (Blocks cg) n = Some v'\n            -> LabelMap.MapsTo (modName, Local (Nsucc Base' + N_of_nat n)) v' (blocks fs Base))\n          /\\ (exists bl, LabelMap.MapsTo (modName, Local Base') (Postcondition cout, bl) (blocks fs Base))\n          /\\ ((k = (modName, Global f)\n            /\\ v = (pre, (nil, Uncond (RvLabel (modName, Local (Nsucc Base' + Entry cg))))))\n          \\/ (k = (modName, Local Base') /\\ v = (Postcondition cout, (nil, Uncond (RvLabel (modName, Local Base')))))\n          \\/ exists n, k = (modName, Local (Nsucc Base' + N_of_nat n)) /\\ nth_error (Blocks cg) n = Some v).\n    clear; induction fs as [ | [ [ ] ] ]; simpl; intuition.\n    destruct (LabelMap.empty_1 H).\n    apply LabelFacts.add_mapsto_iff in H; intuition; subst.\n\n    do 4 esplit.\n    eauto.\n    exists Base; intuition.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union1.\n    apply getLocal; autorewrite with N; auto.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_1; auto.\n\n    apply LabelFacts.add_mapsto_iff in H1; intuition; subst.\n\n    do 4 esplit.\n    eauto.\n    exists Base; intuition.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union1.\n    apply getLocal; autorewrite with N; auto.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_1; auto.\n\n    apply MapsTo_union in H2; intuition.\n\n    apply ungetLocal in H0; destruct H0; intuition; subst.\n    do 4 esplit.\n    eauto.\n    exists Base; intuition.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union1.\n    apply getLocal; autorewrite with N; auto.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_1; auto.\n    eauto 10.\n\n    apply IHfs in H0; clear IHfs; intuition.\n    destruct H0 as [? [? [? [ ] ] ] ].\n    destruct H2; intuition; subst.\n\n    do 4 esplit.\n    right; eauto.\n    exists x2; intuition.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; intuition.\n    apply ungetLocal in H6; destruct H6; intuition.\n    elimtype False; injection H8; intros.\n    apply nth_error_bound in H7.\n    nomega.\n    destruct H4.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; eauto.\n    intros.\n    apply ungetLocal in H5; destruct H5; intuition.\n    elimtype False; injection H7; intros.\n    apply nth_error_bound in H6.\n    nomega.\n\n    do 4 esplit.\n    right; eauto.\n    exists x2; intuition.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; intuition.\n    apply ungetLocal in H6; destruct H6; intuition.\n    elimtype False; injection H8; intros.\n    apply nth_error_bound in H7.\n    nomega.\n    destruct H4.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; eauto.\n    intros.\n    apply ungetLocal in H5; destruct H5; intuition.\n    elimtype False; injection H7; intros.\n    apply nth_error_bound in H6.\n    nomega.\n\n\n    destruct H6; intuition; subst.\n    do 4 esplit.\n    right; eauto.\n    exists x2; intuition eauto.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; intuition.\n    apply ungetLocal in H6; destruct H6; intuition.\n    elimtype False; injection H9; intros.\n    apply nth_error_bound in H8.\n    nomega.\n    destruct H4.\n    eexists.\n    apply LabelMap.add_2; [ congruence | ].\n    apply LabelMap.add_2; [ intro Ho; injection Ho; nomega | ].\n    apply MapsTo_union2; eauto.\n    intros.\n    apply ungetLocal in H5; destruct H5; intuition.\n    apply nth_error_bound in H6.\n    elimtype False; injection H8; intros.\n    nomega.\n  Qed.\n\n  Lemma skipImports : forall m l p bls,\n    LabelMap.MapsTo (modName, Local l) (p, bls) m\n    -> LabelMap.MapsTo (modName, Local l) p\n    (LabelMap.fold\n      (fun (l : LabelMap.key) (x : assert * block) (m : LabelMap.t assert) =>\n        LabelMap.add l (fst x) m) m importsMap).\n    clear NoDupFunc BlocksGood.\n    unfold importsMap.\n    generalize NoSelfImport; clear NoSelfImport.\n    generalize false at 2.\n    intros; assert (forall v, ~LabelMap.MapsTo (modName, Local l) v (LabelMap.empty assert)).\n    do 2 intro.\n    apply LabelMap.empty_1 in H0; tauto.\n    apply LabelMap.elements_1 in H.\n    generalize (LabelMap.elements_3w m).\n    generalize dependent (LabelMap.empty assert).\n    induction imports; simpl in *; intuition.\n    rewrite LabelMap.fold_1.\n    generalize dependent t.\n    induction (LabelMap.elements m); simpl; intuition.\n\n    inversion H.\n    inversion H1; clear H1; subst.\n    inversion H; clear H; subst.\n    hnf in H2; simpl in H2; intuition.\n    destruct a; simpl in *; subst; simpl in *.\n    generalize H4; clear.\n    assert (LabelMap.MapsTo (modName, Local l) p (LabelMap.add (modName, Local l) p t)).\n    apply LabelMap.add_1; auto.\n    generalize dependent (LabelMap.add (modName, Local l) p t).\n    induction l0; simpl; intuition; simpl.\n    apply IHl0; auto.\n    apply LabelMap.add_2.\n    intro; subst.\n    apply H4.\n    constructor; hnf; auto.\n    auto.\n\n    intuition.\n    apply H1; clear H1.\n    intros.\n    apply LabelFacts.add_mapsto_iff in H; intuition.\n    destruct a as [ [ ] ]; simpl in *; subst; simpl in *.\n    injection H; clear H; intros; subst.\n    generalize H2 H4; clear.\n    induction 1; simpl; intuition.\n    apply H4.\n    constructor.\n    hnf in H; hnf; simpl in *; tauto.\n    eauto.\n\n    destruct a as [ [ ] ]; simpl in *.\n    apply IHl0; auto.\n\n    generalize NoSelfImport; clear.\n    match goal with\n      | [ |- context[?E || ?F] ] =>\n        assert (E || F = false -> E = false) by (destruct b; auto);\n          generalize dependent (E || F); generalize dependent E\n    end.\n    induction l0; simpl; intuition.\n    destruct a as [ [ ] ]; simpl in *.\n    eapply IHl0; [ | eassumption ].\n    destruct b0; destruct b; simpl in *; intuition congruence.\n\n    intros.\n    apply LabelFacts.add_mapsto_iff in H2; intuition; subst.\n    congruence.\n    eauto.\n  Qed.\n\n  Lemma imps_cases : forall k v ims exit post bls base,\n    LabelMap.MapsTo k v (imps ims modName bls base exit post)\n    -> (k = (modName, Local exit) /\\ v = post)\n    \\/ LabelMap.MapsTo k v ims\n    \\/ exists n, exists bl, nth_error bls n = Some (v, bl) /\\ k = (modName, Local (base + N_of_nat n)).\n    induction bls; simpl; intuition.\n\n    apply LabelFacts.add_mapsto_iff in H; intuition.\n\n    apply LabelFacts.add_mapsto_iff in H; intuition; subst.\n\n    do 2 right; exists O; exists b; intuition.\n    do 2 f_equal; nomega.\n\n    apply IHbls in H1; intuition.\n    destruct H1 as [ ? [ ] ]; intuition.\n    do 2 right; exists (S x); exists x0; intuition.\n    rewrite H2; do 2 f_equal; nomega.\n  Qed.\n\n  Lemma MapsTo_fullImports : forall k v,\n    LabelMap.MapsTo k v fullImports\n    -> LabelMap.MapsTo k v importsMap\n    \\/ (exists f, k = (modName, Global f) /\\ exists c, In (f, v, c) functions).\n    clear; unfold fullImports; do 2 intro; generalize importsMap.\n    induction functions as [ | [ [ ] ] ]; simpl; intuition.\n    apply IHl in H; clear IHl; intuition.\n    apply LabelFacts.add_mapsto_iff in H0; intuition; subst.\n    eauto 10.\n    destruct H0; intuition; subst.\n    destruct H1; eauto 10.\n  Qed.\n\n  Lemma importsMap_global' : forall l pre imps (acc : LabelMap.t assert),\n    (forall l' pre', LabelMap.MapsTo l' pre' acc\n      -> exists g, snd l' = Global g)\n    -> LabelMap.MapsTo l pre (fold_left (fun m p => let '(modl, f, pre) := p in\n      LabelMap.add (modl, Global f) pre m) imps acc)\n    -> exists g, snd l = Global g.\n    clear; induction imps; simpl; intuition eauto.\n    eapply IHimps; [ | eauto ].\n    intros.\n    destruct (LabelKey.eq_dec l' (a, Global b0)).\n    hnf in e; subst; simpl; eauto.\n    eapply LabelMap.add_3 in H1.\n    eauto.\n    auto.\n  Qed.\n\n  Lemma importsMap_global : forall l pre,\n    LabelMap.MapsTo l pre importsMap -> exists g, snd l = Global g.\n    intros; apply importsMap_global' with pre imports (LabelMap.empty _).\n    intros.\n    apply LabelMap.empty_1 in H0; tauto.\n    assumption.\n  Qed.\n\n  Lemma MapsTo_func : forall A (m : LabelMap.t A) k v v',\n    LabelMap.MapsTo k v m\n    -> LabelMap.MapsTo k v' m\n    -> v = v'.\n    intros.\n    apply LabelMap.find_1 in H.\n    apply LabelMap.find_1 in H0.\n    congruence.\n  Qed.\n\n  Lemma blocks_exps : forall (mn g : string) (pre : assert) (bl : block)\n    funcs start,\n    LabelMap.MapsTo (mn, Global g) (pre, bl) (blocks funcs start) ->\n    LabelMap.MapsTo (mn, Global g) pre (exps funcs).\n    clear; induction funcs; simpl; intuition.\n    apply LabelMap.empty_1 in H; tauto.\n    destruct a as [ [ ] ].\n    destruct (LabelKey.eq_dec (modName, Global s) (mn, Global g)).\n    generalize e; intro e'.\n    eapply LabelMap.add_1 in e'.\n\n\n    hnf in e.\n    rewrite <- e in *.\n    eapply MapsTo_func in e'.\n    2: apply H.\n    injection e'; clear e'; intros; subst.\n    eauto.\n\n    apply LabelMap.add_3 in H; [ | assumption ].\n    apply LabelMap.add_3 in H; [ | lomega ].\n    apply MapsTo_union in H; intuition.\n    apply buildLocals_notImport in H0; destruct H0; intuition congruence.\n\n    eauto.\n  Qed.\n\n  Lemma exps_blocks : forall (mn g : string) (pre : assert)\n    funcs start,\n    LabelMap.MapsTo (mn, Global g) pre (exps funcs)\n    -> exists bl, LabelMap.MapsTo (mn, Global g) (pre, bl) (blocks funcs start).\n    induction funcs; simpl; intuition.\n    apply LabelMap.empty_1 in H; tauto.\n    destruct a as [ [ ] ].\n    destruct (LabelKey.eq_dec (modName, Global s) (mn, Global g)).\n    generalize e; intro e'.\n    eapply LabelMap.add_1 in e'.\n    hnf in e.\n    rewrite <- e in *.\n    eapply MapsTo_func in e'.\n    2: apply H.\n    subst.\n    eauto.\n\n    apply LabelMap.add_3 in H; [ | assumption ].\n    eapply IHfuncs in H; destruct H.\n    exists x.\n    apply LabelMap.add_2; auto.\n    apply LabelMap.add_2; auto.\n    apply MapsTo_union2.\n    eauto.\n    intros.\n    apply buildLocals_notImport in H0; destruct H0; intuition congruence.\n  Qed.\n\n  Lemma blocks_modName : forall mn l pre_bl funcs start,\n    LabelMap.MapsTo (mn, l) pre_bl (blocks funcs start)\n    -> modName = mn.\n    clear; induction funcs; simpl; intuition.\n    apply LabelMap.empty_1 in H; tauto.\n    destruct a as [ [ ] ].\n    destruct (LabelKey.eq_dec (modName, Global s) (mn, l)).\n    congruence.\n    apply LabelMap.add_3 in H; [ | assumption ].\n    destruct (LabelKey.eq_dec (modName, Local start) (mn, l)).\n    congruence.\n    apply LabelMap.add_3 in H; [ | assumption ].\n    apply MapsTo_union in H; intuition.\n    apply buildLocals_notImport in H0; destruct H0; intuition congruence.\n    eauto.\n  Qed.\n\n  Theorem bmoduleOk : moduleOk bmodule_.\n    constructor.\n\n    clear NoDupFunc BlocksGood.\n    red; simpl.\n    apply Forall_MapsTo.\n    intros.\n    simpl.\n    generalize dependent 1.\n    induction functions; simpl; intuition.\n    apply LabelMap.empty_1 in H; tauto.\n    destruct a as [ [ ] ]; simpl in *.\n    apply LabelFacts.add_mapsto_iff in H; intuition; subst; eauto.\n    apply LabelFacts.add_mapsto_iff in H2; intuition; subst; eauto.\n    apply MapsTo_union in H3; intuition.\n\n    destruct (buildLocals_notImport _ _ H1); intuition; subst; eauto.\n    eauto.\n\n\n    red; simpl; unfold allPreconditions; simpl; intros.\n\n    generalize (MapsTo_blocks _ _ H); intros.\n    repeat match goal with\n             | [ H : ex _ |- _ ] => destruct H; intuition; subst\n           end.\n\n    injection H8; clear H8; intros; subst; simpl.\n    destruct (PreconditionOk (Generate (x1 fullImports fullImportsGlobal x0) (Nsucc x2) x2)).\n    apply H2 in H6.\n    autorewrite with N in H6.\n\n    match type of H6 with\n      | LabelMap.MapsTo ?k (?v, _) _ => destruct (H0 k v)\n    end.\n    eapply skipImports; eauto.\n    intuition.\n    rewrite H8.\n    eauto.\n\n\n    injection H8; clear H8; intros; subst; simpl.\n    match type of H5 with\n      | LabelMap.MapsTo ?k (?v, _) _ => destruct (H0 k v)\n    end.\n    eapply skipImports; eauto.\n    intuition.\n    rewrite H7.\n    eauto.\n\n\n    generalize (BlocksOk (Generate (x1 fullImports fullImportsGlobal x0) (Nsucc x2) x2)); intuition.\n    match type of H6 with\n      | ?P -> _ => assert P\n    end.\n    generalize BlocksGood' H3; clear.\n    induction functions; simpl; intuition; subst.\n    inversion H; clear H; subst.\n    tauto.\n    inversion H; clear H; subst.\n    auto.\n\n    intuition.\n    match type of H9 with\n      | ?P -> _ => assert P by nomega\n    end; intuition.\n    apply (Forall_nth_error H10) in H8; simpl in *.\n    apply H8; intuition.\n    apply H0.\n\n    apply imps_cases in H9; intuition; subst.\n\n    eapply skipImports; eauto.\n\n    apply MapsTo_fullImports in H9; intuition.\n    assert (~LabelMap.In l (blocks functions 1)).\n    pose proof importsNotThis' as importsNotThis'.\n    generalize NoSelfImport H11; clear -importsNotThis'.\n    generalize false at 2.\n    generalize 1.\n    induction functions as [ | [ [ ] ] ]; simpl; intuition.\n    destruct H.\n    destruct (LabelMap.empty_1 H).\n    destruct H.\n    apply LabelFacts.add_mapsto_iff in H; intuition; subst.\n    eapply importsNotThis'; eauto.\n    apply LabelFacts.add_mapsto_iff in H1; intuition; subst.\n    eapply importsNotThis'; eauto.\n    apply MapsTo_union in H2; intuition.\n    apply ungetLocal in H0; destruct H0; intuition; subst.\n    eapply importsNotThis'; eauto.\n    eapply IHl0 in NoSelfImport; eauto.\n    eexists; eauto.\n\n    assert (forall v, ~SetoidList.InA (@LabelMap.eq_key_elt _) (l, v) (LabelMap.elements (blocks functions 1))).\n    generalize H9; clear.\n    intros; intro.\n    apply H9.\n    eexists.\n    apply LabelMap.elements_2; eauto.\n\n    generalize H11 H12; clear.\n    rewrite LabelMap.fold_1.\n    generalize importsMap.\n    induction (LabelMap.elements (blocks functions 1)) as [ | [ [ ] ] ]; simpl; intuition; simpl.\n    apply IHl0.\n    apply LabelMap.add_2; auto.\n    intro; subst.\n    eapply H12.\n    constructor; hnf; eauto.\n    eauto.\n\n\n    destruct H11; intuition; subst.\n    destruct H12.\n\n    assert (SetoidList.NoDupA (fun p1 p2 => fst (fst p1) = fst (fst p2)) functions).\n    generalize NoDupFunc; clear.\n    generalize dependent (LabelMap.empty unit).\n    induction functions as [ | [ [ ] ] ]; simpl; intuition.\n    case_eq (LabelMap.mem (s, Local 0) t); intro Heq; rewrite Heq in *.\n    elimtype False.\n    generalize NoDupFunc; clear.\n    induction l as [ | [ [ ] ] ]; simpl; intuition.\n    specialize (IHl _ NoDupFunc).\n    constructor; auto.\n    generalize NoDupFunc; clear.\n    assert (LabelMap.MapsTo (s, Local 0) tt (LabelMap.add (s, Local 0) tt t)) by (apply LabelMap.add_1; auto).\n    generalize dependent (LabelMap.add (s, Local 0) tt t).\n    induction l as [ | [ [ ] ] ]; simpl; intuition.\n    inversion H0.\n    inversion H0; clear H0; simpl in *; subst.\n    assert (LabelMap.In (s0, Local 0) t0) by (hnf; eauto).\n    apply LabelMap.mem_1 in H0.\n    rewrite H0 in NoDupFunc.\n    elimtype False.\n    generalize NoDupFunc; clear.\n    induction l as [ | [ [ ] ] ]; simpl; intuition.\n    case_eq (LabelMap.mem (s0, Local 0) t0); intro Heq; rewrite Heq in *.\n    elimtype False.\n    generalize NoDupFunc; clear.\n    induction l as [ | [ [ ] ] ]; simpl; intuition.\n    specialize (fun H => IHl _ H NoDupFunc).\n    apply IHl; auto.\n\n    assert (exists bl, LabelMap.MapsTo (modName, Global x5) (pre0, bl) (blocks functions 1)).\n    generalize H11 H9; clear.\n    generalize 1.\n    induction functions; simpl; intuition; subst.\n    eexists; apply LabelMap.add_1; eauto.\n    destruct a as [ [ ] ].\n    inversion H11; clear H11; subst.\n    match goal with\n      | [ |- context[blocks _ ?n] ] => destruct (IHl n H3)\n    end; auto.\n    eexists.\n    apply LabelMap.add_2.\n    intro Ho; injection Ho; clear Ho; intros; subst.\n    apply H2.\n    generalize H; clear.\n    induction l; simpl; intuition; subst; auto.\n    apply LabelMap.add_2; [ congruence | ].\n    apply MapsTo_union2; eauto.\n    intros.\n    destruct (ungetLocal _ _ H1); intuition congruence.\n\n    rewrite LabelMap.fold_1.\n    destruct H12.\n    assert (SetoidList.InA (@LabelMap.eq_key_elt _) ((modName, Global x5), (pre0, x7)) (LabelMap.elements (blocks functions 1))).\n    apply LabelMap.elements_1; auto.\n    generalize H13; clear.\n    generalize (LabelMap.elements_3w (blocks functions 1)).\n    generalize importsMap.\n    induction (LabelMap.elements (blocks functions 1)); simpl; intuition.\n    inversion H13.\n    inversion H; clear H; subst.\n    inversion H13; clear H13; subst; simpl.\n    hnf in H0; simpl in H0; intuition; subst.\n    injection H1; clear H1; intros; subst.\n    assert (LabelMap.MapsTo (modName, Global x5) a (LabelMap.add (modName, Global x5) a t)) by (apply LabelMap.add_1; auto).\n    generalize H2 H; clear.\n    generalize (LabelMap.add (modName, Global x5) a t).\n    induction l; simpl; intuition; simpl.\n    apply IHl; auto.\n    apply LabelMap.add_2; auto.\n    intro; subst.\n    apply H2; constructor; hnf; auto.\n    auto.\n\n    destruct H9 as [ ? [ ] ]; intuition; subst.\n    eapply skipImports; eauto.\n\n\n    simpl.\n\n    intros; eapply importsMap_global; eauto.\n\n\n    simpl.\n\n    intros; eapply blocks_exps; eauto.\n\n\n    simpl.\n\n    intros; eapply exps_blocks; eauto.\n\n\n    simpl.\n    intros.\n    apply StringSet.singleton_2.\n\n    eapply blocks_modName; eauto.\n  Qed.\n\nEnd module.\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/StructuredModule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19196658461489657}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.OneLeaderPerTermInterface.\n\nRequire Import VerdiRaft.CandidateEntriesInterface.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.RefinementCommonTheorems.\n\nRequire Import VerdiRaft.LeaderSublogInterface.\n\n#[global]\nHint Extern 4 (@BaseParams) => apply base_params : typeclass_instances.\n#[global]\nHint Extern 4 (@MultiParams _) => apply multi_params : typeclass_instances.\n#[global]\nHint Extern 4 (@FailureParams _ _) => apply failure_params : typeclass_instances.\n\nSection LeaderSublogProof.\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 {cei : candidate_entries_interface}.\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n  Context {olpti : one_leader_per_term_interface}.\n\n  Ltac prove_in :=\n    match goal with\n      | [ _ : nwPackets ?net = _,\n              _ : In ?p _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n      | [ _ : nwPackets ?net = _,\n              _ : pBody ?p = _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n    end.\n\n\n  Notation is_append_entries m :=\n    (exists t n prevT prevI entries c,\n       m = AppendEntries t n prevT prevI entries c).\n\n  Lemma leader_sublog_invariant_same_state :\n    forall net net',\n      leader_sublog_host_invariant net ->\n      (forall h, log (nwState net h) = log (nwState net' h)) ->\n      (forall h, type (nwState net' h) = Leader ->\n            type (nwState net h) = Leader /\\\n            currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n      leader_sublog_host_invariant net'.\n  Proof using. \n    unfold leader_sublog_host_invariant in *. intros.\n    specialize (H leader e h).\n    forward H; [apply H1; auto|].\n    intuition.\n    rewrite H0 in *. specialize (H1 leader). intuition.\n    rewrite H7 in *; auto.\n    rewrite H0 in *. auto.\n  Qed.\n\n  Lemma leader_sublog_invariant_subset :\n    forall net net',\n      leader_sublog_invariant net ->\n      (forall p, is_append_entries (pBody p) -> In p (nwPackets net') -> In p (nwPackets net)) ->\n      (forall h, log (nwState net h) = log (nwState net' h)) ->\n      (forall h, type (nwState net' h) = Leader ->\n            type (nwState net h) = Leader /\\\n            currentTerm (nwState net h) = currentTerm (nwState net' h)) ->\n      leader_sublog_invariant net'.\n  Proof using. \n    unfold leader_sublog_invariant in *. intros; intuition.\n    - eauto using leader_sublog_invariant_same_state.\n    - unfold leader_sublog_nw_invariant in *. intros.\n      pose proof H1 leader.\n      pose proof H2 leader; concludes.\n      pose proof H3 leader. intuition.\n      symmetry in H13.\n      repeat find_rewrite.\n      eapply H11; simpl in *; repeat find_rewrite; eauto.\n      assert (is_append_entries (pBody p)) by (repeat eexists; eauto).\n      eauto.\n  Qed.\n\n  Theorem leader_sublog_do_leader :\n    raft_net_invariant_do_leader leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_do_leader.\n    intros.\n    unfold doLeader in *.\n    break_match; try solve [\n                       find_inversion; simpl in *;\n                       eapply leader_sublog_invariant_subset;\n                       eauto; intuition; simpl in *;\n                       repeat find_apply_hyp_hyp; intuition;\n                       repeat find_higher_order_rewrite; repeat break_if; subst; intuition].\n    break_if.\n    - unfold replicaMessage in *. find_inversion. simpl in *.\n      unfold leader_sublog_invariant in *; intuition.\n      + unfold leader_sublog_host_invariant in *. intros.\n        simpl in *. repeat find_higher_order_rewrite.\n        repeat break_if; simpl in *; intuition eauto.\n      + unfold leader_sublog_nw_invariant in *. intros.\n        simpl in *. repeat find_higher_order_rewrite.\n        find_apply_hyp_hyp.\n        break_if; intuition idtac; simpl in *; subst; intuition eauto;\n        simpl in *;\n        repeat do_in_map; subst; simpl in *;\n        find_inversion; eauto using findGtIndex_in.\n    - find_inversion.\n      unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n      leader_sublog_host_invariant, advanceCommitIndex in *.\n\n      intuition; find_higher_order_rewrite; repeat break_if; simpl in *; subst;\n      repeat break_if; simpl in *; eauto;\n      find_apply_hyp_hyp; intuition; eauto.\n  Qed.\n\n  Lemma leader_sublog_client_request :\n    raft_net_invariant_client_request leader_sublog_invariant.\n  Proof using olpti. \n    unfold raft_net_invariant_client_request.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleClientRequest in *. intuition idtac.\n    - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n      repeat break_if; subst; simpl in *;\n      intuition eauto;\n      simpl in *; in_crush_finish; intuition eauto. in_crush; eauto.\n      exfalso.\n      match goal with\n        | H : raft_intermediate_reachable _ |- _ =>\n          eapply one_leader_per_term_invariant in H\n      end.\n      assert (leader = h) by (eapply_prop one_leader_per_term; eauto).\n      intuition.\n    - break_match; find_inversion; simpl in *; repeat find_higher_order_rewrite;\n      repeat break_if; find_apply_hyp_hyp; intuition eauto; subst.\n      simpl in *.\n      in_crush; eauto.\n  Qed.\n\n  Lemma leader_sublog_timeout :\n    raft_net_invariant_timeout\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_timeout. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleTimeout, tryToBecomeLeader in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; try solve_by_inversion;\n      in_crush; repeat find_inversion; discriminate.\n  Qed.\n\n  Lemma leader_sublog_append_entries :\n    raft_net_invariant_append_entries\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_append_entries. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleAppendEntries, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion;\n      do_in_app; intuition; eauto using removeAfterIndex_in.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_append_entries_reply :\n    raft_net_invariant_append_entries_reply\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_append_entries_reply. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleAppendEntriesReply, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_request_vote :\n    raft_net_invariant_request_vote\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_request_vote. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, handleRequestVote, advanceCurrentTerm in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto; try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n\n  Definition CandidateEntriesLowered net e h :=\n      currentTerm (nwState net h) = eTerm e ->\n      wonElection (dedup name_eq_dec (votesReceived (nwState net h))) = true ->\n      type (nwState net h) <> Candidate.\n\n  Lemma candidate_entries_lowered' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall h h' e,\n        In e (log (snd (nwState net h'))) ->\n        CandidateEntriesLowered (deghost net) e h.\n  Proof using rri. \n    unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    apply_prop_hyp candidateEntries_host_invariant In.\n    eapply candidateEntries_wonElection; auto; repeat find_rewrite_lem deghost_spec; eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall h h' e,\n        In e (log (nwState net h')) ->\n        CandidateEntriesLowered net e h.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Definition CandidateEntriesLowered_rvr net e p :=\n    In p (nwPackets net) ->\n    pBody p = RequestVoteReply (eTerm e) true ->\n    currentTerm (nwState net (pDst p)) = eTerm e ->\n    wonElection (dedup name_eq_dec (pSrc p :: votesReceived (nwState net (pDst p)))) = true ->\n    type (nwState net (pDst p)) <> Candidate.\n\n  Lemma deghost_packet_exists :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    unfold deghost.\n    simpl.\n    intros.\n    do_in_map.\n    eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered_rvr' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p h e,\n        In e (log (snd (nwState net h))) ->\n        CandidateEntriesLowered_rvr (deghost net) e p.\n  Proof using rri. \n    unfold CandidateEntriesLowered_rvr, CandidateEntries.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n\n    apply_prop_hyp candidateEntries_host_invariant In.\n    eapply wonElection_candidateEntries_rvr; auto;\n    repeat find_rewrite_lem deghost_spec; eauto.\n  Qed.\n\n  Lemma candidate_entries_lowered_rvr :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p h e,\n        In e (log (nwState net h)) ->\n        CandidateEntriesLowered_rvr net e p.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_rvr';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall h p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets (deghost net)) ->\n        In e es ->\n        CandidateEntriesLowered (deghost net) e h.\n  Proof using rri. \n    unfold CandidateEntriesLowered, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists. break_and. subst.\n\n    eapply_prop_hyp candidateEntries_nw_invariant In; eauto.\n    unfold candidateEntries in *. break_exists. break_and.\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n\n    intro.\n    assert (h = x0).\n    {\n      eapply_prop one_vote_per_term;\n      eapply_prop cronies_votes.\n      - eapply_prop votes_received_cronies; eauto.\n      - find_reverse_rewrite. auto.\n    }\n    subst.\n    concludes. contradiction.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall h p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets net) ->\n        In e es ->\n        CandidateEntriesLowered net e h.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_nw';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma candidate_entries_lowered_nw_rvr' :\n    forall net,\n      CandidateEntries net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p' p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets (deghost net)) ->\n        In e es ->\n        CandidateEntriesLowered_rvr (deghost net) e p'.\n  Proof using rri. \n    unfold CandidateEntriesLowered_rvr, CandidateEntries, votes_correct, cronies_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n    eapply_prop_hyp votes_nw pBody. concludes.\n    eapply_prop_hyp candidateEntries_nw_invariant pBody; auto.\n\n    find_insterU. conclude_using eauto.\n    unfold candidateEntries in *.\n    break_exists. break_and.\n\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    simpl in *.\n    break_or_hyp.\n    - apply_prop_hyp cronies_votes In.\n      assert (pDst x = x1) by (eapply_prop one_vote_per_term; eauto).\n      subst. auto.\n    - intro.\n      assert (pDst x = x1).\n      { eapply_prop one_vote_per_term;\n        eapply_prop cronies_votes.\n        - eapply_prop votes_received_cronies; eauto.\n        - repeat find_reverse_rewrite. auto.\n      }\n      subst.\n      concludes. contradiction.\n  Qed.\n\n\n  Lemma candidate_entries_lowered_nw_rvr :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p' p e t li pli plt es lc,\n        pBody p = AppendEntries t li pli plt es lc ->\n        In p (nwPackets net) ->\n        In e es ->\n        CandidateEntriesLowered_rvr net e p'.\n  Proof using cci vci cei rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n    eapply candidate_entries_lowered_nw_rvr';\n      eauto using candidate_entries_invariant, votes_correct_invariant, cronies_correct_invariant.\n  Qed.\n\n  Lemma leader_sublog_request_vote_reply :\n    raft_net_invariant_request_vote_reply\n      leader_sublog_invariant.\n  Proof using cci vci cei rri. \n    unfold raft_net_invariant_request_vote_reply.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n           leader_sublog_host_invariant, handleRequestVoteReply, advanceCurrentTerm.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *; intuition eauto; try discriminate.\n      + exfalso. eapply candidate_entries_lowered; eauto.\n      + rewrite dedup_not_in_cons in * by auto.\n        exfalso. eapply candidate_entries_lowered_rvr; eauto.\n        do_bool.\n        find_rewrite.\n        f_equal.\n        lia.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      subst; simpl in *; intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n      + exfalso. eapply candidate_entries_lowered_nw; eauto.\n      + rewrite dedup_not_in_cons in * by auto.\n        exfalso. eapply candidate_entries_lowered_nw_rvr; eauto.\n        do_bool.\n        find_rewrite.\n        f_equal.\n        lia.\n  Qed.\n\n  Lemma leader_sublog_do_generic_server :\n    raft_net_invariant_do_generic_server\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, doGenericServer in *.\n    intuition idtac; simpl in *.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      use_applyEntries_spec;\n      subst; simpl in *;\n      intuition eauto;\n      try solve_by_inversion.\n    - repeat find_higher_order_rewrite; repeat break_match; repeat find_inversion;\n      use_applyEntries_spec;\n      subst; simpl in *;\n      intuition eauto;\n      find_apply_hyp_hyp; intuition eauto; subst; try discriminate.\n  Qed.\n\n  Lemma leader_sublog_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset.\n    intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant in *. intuition idtac;\n      repeat find_reverse_higher_order_rewrite; intuition eauto.\n  Qed.\n\n  Lemma leader_sublog_reboot :\n    raft_net_invariant_reboot\n      leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_reboot. intros.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant,\n    leader_sublog_host_invariant, reboot in *. intuition idtac.\n    - repeat find_higher_order_rewrite.\n      simpl in *. repeat break_match; subst; simpl in *; intuition eauto; discriminate.\n    - repeat find_higher_order_rewrite.\n      simpl in *. repeat find_rewrite.\n      repeat break_match; subst; simpl in *;\n      intuition eauto; try discriminate.\n  Qed.\n\n  Theorem leader_sublog_init :\n    raft_net_invariant_init leader_sublog_invariant.\n  Proof using. \n    unfold raft_net_invariant_init, leader_sublog_invariant,\n    leader_sublog_host_invariant, leader_sublog_nw_invariant;\n    intuition.\n  Qed.\n\n  Theorem leader_sublog_invariant_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      leader_sublog_invariant net.\n  Proof using olpti cci vci cei rri. \n    intros.\n    eapply raft_net_invariant; eauto.\n    - apply leader_sublog_init.\n    - apply leader_sublog_client_request.\n    - apply leader_sublog_timeout.\n    - apply leader_sublog_append_entries.\n    - apply leader_sublog_append_entries_reply.\n    - apply leader_sublog_request_vote.\n    - apply leader_sublog_request_vote_reply.\n    - apply leader_sublog_do_leader.\n    - apply leader_sublog_do_generic_server.\n    - apply leader_sublog_state_same_packet_subset.\n    - apply leader_sublog_reboot.\n  Qed.\n\n  Instance lsi : leader_sublog_interface.\n  Proof.\n    split.\n    auto using leader_sublog_invariant_invariant.\n  Qed.\nEnd LeaderSublogProof.\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/LeaderSublogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.19196657202003395}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.RefinementCommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.NoAppendEntriesToLeaderInterface.\nRequire Import VerdiRaft.NoAppendEntriesToSelfInterface.\nRequire Import VerdiRaft.TermsAndIndicesFromOneLogInterface.\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\nRequire Import VerdiRaft.LogAllEntriesInterface.\nRequire Import VerdiRaft.AppendEntriesRequestLeaderLogsInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsStrongInterface.\nRequire Import VerdiRaft.OneLeaderLogPerTermInterface.\nRequire Import VerdiRaft.MatchIndexLeaderInterface.\nRequire Import VerdiRaft.MatchIndexSanityInterface.\nRequire Import VerdiRaft.AppendEntriesReplySublogInterface.\nRequire Import VerdiRaft.CandidateEntriesInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\n\nRequire Import VerdiRaft.MatchIndexAllEntriesInterface.\n\nSection MatchIndexAllEntries.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Context {naetli : no_append_entries_to_leader_interface}.\n  Context {naetsi : no_append_entries_to_self_interface}.\n  Context {taifoli : terms_and_indices_from_one_log_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {laei : log_all_entries_interface}.\n  Context {aelli : append_entries_leaderLogs_interface}.\n  Context {lsi : leader_sublog_interface}.\n  Context {lhllsi : leaders_have_leaderLogs_strong_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n  Context {mili : match_index_leader_interface}.\n  Context {matchisi : match_index_sanity_interface}.\n  Context {aersi : append_entries_reply_sublog_interface}.\n  Context {cei : candidate_entries_interface}.\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Definition match_index_all_entries_nw (net : network) : Prop :=\n    forall p t es e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntriesReply t es true ->\n      currentTerm (snd (nwState net (pDst p))) = t ->\n      In e (log (snd (nwState net (pDst p)))) ->\n      eTerm e = t ->\n      eIndex e <= maxIndex es ->\n      type (snd (nwState net (pDst p))) = Leader ->\n      In (t, e) (allEntries (fst (nwState net (pSrc p)))).\n\n  Definition match_index_all_entries_inv (net : network) : Prop :=\n    match_index_all_entries net /\\ match_index_all_entries_nw net.\n\n  Lemma match_index_all_entries_init :\n    refined_raft_net_invariant_init match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_init,\n           match_index_all_entries_inv,\n           match_index_all_entries_nw,\n           match_index_all_entries.\n    simpl. intros.\n    intuition.\n  Qed.\n\n  Theorem handleClientRequest_matchIndex_log :\n    forall h st client id c out st' ps,\n      handleClientRequest h st client id c = (out, st', ps) ->\n      ps = nil /\\\n      (log st' = log st /\\ matchIndex st' = matchIndex st \\/\n       exists e,\n         log st' = e :: log st /\\\n         eIndex e = S (maxIndex (log st)) /\\\n         eTerm e = currentTerm st /\\\n         eClient e = client /\\\n         eInput e = c /\\\n         eId e = id /\\\n         type st = Leader /\\\n         matchIndex st' = assoc_set name_eq_dec (matchIndex st) h (S (maxIndex (log st)))).\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; subst; intuition.\n    simpl in *. eauto 10.\n  Qed.\n\n  Lemma lifted_match_index_leader :\n    forall net leader,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net leader)) = Leader ->\n      assoc_default name_eq_dec (matchIndex (snd (nwState net leader))) leader 0 =\n      maxIndex (log (snd (nwState net leader))).\n  Proof using mili rri. \n    intros.\n    pose proof lift_prop _ match_index_leader_invariant _ ltac:(eauto) leader.\n    find_rewrite_lem deghost_spec. concludes. auto.\n  Qed.\n\n  Lemma lifted_match_index_sanity :\n    forall net leader h,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net leader)) = Leader ->\n      assoc_default name_eq_dec (matchIndex (snd (nwState net leader))) h 0 <=\n      maxIndex (log (snd (nwState net leader))).\n  Proof using matchisi rri. \n    intros.\n    pose proof lift_prop _ match_index_sanity_invariant _ ltac:(eauto) leader h.\n    find_rewrite_lem deghost_spec. concludes. auto.\n  Qed.\n\n  Lemma lifted_append_entries_reply_sublog :\n    forall net p t es h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntriesReply t es true ->\n      currentTerm (snd (nwState net h)) = t ->\n      type (snd (nwState net h)) = Leader ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using aersi rri. \n    intros.\n    pose proof lift_prop _ append_entries_reply_sublog_invariant _ ltac:(eauto).\n    unfold append_entries_reply_sublog in *.\n    find_apply_lem_hyp ghost_packet.\n    eapply_prop_hyp In In; eauto; try rewrite deghost_spec; eauto.\n    find_rewrite_lem deghost_spec. auto.\n  Qed.\n\n  Lemma match_index_all_entries_client_request :\n    refined_raft_net_invariant_client_request match_index_all_entries_inv.\n  Proof using aersi matchisi mili rlmli rri. \n    unfold refined_raft_net_invariant_client_request, match_index_all_entries_inv.\n    simpl. intros. break_and. split.\n    - unfold match_index_all_entries in *. simpl in *. intros.\n      repeat find_higher_order_rewrite. update_destruct_simplify_hyp.\n      + find_copy_apply_lem_hyp handleClientRequest_type.\n        find_copy_apply_lem_hyp handleClientRequest_matchIndex_log. intuition.\n        * repeat find_rewrite.\n          { update_destruct_simplify_hyp.\n            - apply update_elections_data_clientRequest_allEntries_old'.\n              find_apply_hyp_hyp. repeat find_rewrite. auto.\n            - find_apply_hyp_hyp. repeat find_rewrite. auto.\n          }\n        * break_exists. break_and. repeat find_rewrite.\n          { update_destruct_simplify_hyp.\n            - unfold update_elections_data_client_request. find_rewrite.\n              break_if.\n              + repeat find_rewrite. simpl. break_or_hyp.\n                * auto.\n                * right.\n                  find_copy_apply_lem_hyp maxIndex_is_max; [|solve[apply entries_sorted_invariant; auto]].\n                  rewrite <- lifted_match_index_leader in * by auto.\n                  eapply_prop_hyp In In; eauto. repeat find_rewrite. auto.\n              + do_bool. find_rewrite. simpl length in *. lia.\n            - find_erewrite_lem get_set_diff_default.\n              pose proof lifted_match_index_sanity _ leader h0 ltac:(eauto) ltac:(auto).\n              break_or_hyp.\n              + simpl in *. lia.\n              + find_apply_hyp_hyp. repeat find_rewrite. auto.\n          }\n      + find_apply_hyp_hyp. update_destruct_simplify_hyp.\n        * apply update_elections_data_clientRequest_allEntries_old'.\n          repeat find_rewrite. auto.\n        * repeat find_rewrite. auto.\n    - unfold match_index_all_entries_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp. break_or_hyp.\n      + repeat find_higher_order_rewrite. update_destruct_simplify_hyp.\n        * find_copy_apply_lem_hyp handleClientRequest_type. break_and. repeat find_rewrite.\n          find_copy_apply_lem_hyp handleClientRequest_log.\n          { intuition.\n            - repeat find_rewrite.\n              eapply_prop_hyp In In; eauto.\n              update_destruct_simplify_hyp.\n              + apply update_elections_data_clientRequest_allEntries_old'.\n                repeat find_rewrite. auto.\n              + repeat find_rewrite. auto.\n            - break_exists. break_and. repeat find_rewrite.\n              assert (es <> nil).\n              {\n                apply maxIndex_gt_0_nonempty.\n                eapply Nat.lt_le_trans; [|eauto].\n                simpl in *. break_or_hyp.\n                - repeat find_rewrite. lia.\n                - eapply entries_gt_0_invariant; eauto.\n              }\n              pose proof maxIndex_non_empty es. concludes.\n              break_exists_name max_e. intuition.\n              find_eapply_lem_hyp lifted_append_entries_reply_sublog; repeat find_rewrite; eauto.\n              simpl In in *. break_or_hyp.\n              + find_apply_lem_hyp maxIndex_is_max; [|solve[apply entries_sorted_invariant; auto]].\n                lia.\n              + eapply_prop_hyp In In; eauto; [|solve[repeat find_rewrite; auto]].\n                update_destruct_simplify_hyp.\n                * apply update_elections_data_clientRequest_allEntries_old'.\n                  repeat find_rewrite. auto.\n                * repeat find_rewrite. auto.\n          }\n        * eapply_prop_hyp In In; eauto.\n          { update_destruct_simplify_hyp.\n            - apply update_elections_data_clientRequest_allEntries_old'.\n              repeat find_rewrite. auto.\n            - repeat find_rewrite. auto.\n          }\n      + find_apply_lem_hyp handleClientRequest_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma handleTimeout_matchIndex :\n    forall h st out st' l,\n       handleTimeout h st = (out, st', l) ->\n       matchIndex st' = matchIndex st.\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_update_timeout :\n    forall x h h' net d,\n      In x (allEntries (fst (nwState net h))) ->\n      In x (allEntries (fst (update name_eq_dec (nwState net) h'\n                                    (update_elections_data_timeout h' (nwState net h'), d) h))).\n  Proof using. \n    intros.\n    update_destruct_simplify_hyp.\n    - unfold update_elections_data_timeout. repeat break_match; auto.\n    - auto.\n  Qed.\n\n  Lemma handleTimeout_sends_RV :\n    forall h st out st' l m,\n      handleTimeout h st = (out, st', l) ->\n      In m l ->\n      exists node t h mi mt,\n        m = (node, RequestVote t h mi mt).\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader.\n    intros.\n    repeat break_match; repeat find_inversion.\n    - do_in_map. subst. eauto 10.\n    - do_in_map. subst. eauto 10.\n    - simpl in *. intuition.\n  Qed.\n\n  Lemma match_index_all_entries_timeout :\n    refined_raft_net_invariant_timeout match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, match_index_all_entries_inv.\n    simpl. intros. break_and. split.\n    - unfold match_index_all_entries in *. simpl. intros.\n      repeat find_higher_order_rewrite.\n      apply allEntries_update_timeout.\n      update_destruct_simplify_hyp.\n      + find_erewrite_lem handleTimeout_log_same.\n        find_copy_apply_lem_hyp handleTimeout_type. intuition; try congruence.\n        find_erewrite_lem handleTimeout_matchIndex.\n        repeat find_rewrite.\n        eapply_prop_hyp In In; eauto. congruence.\n      + eapply_prop_hyp In In; eauto. congruence.\n    - unfold match_index_all_entries_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp. break_or_hyp.\n      + repeat find_higher_order_rewrite.\n        apply allEntries_update_timeout.\n        update_destruct_simplify_hyp.\n        * find_erewrite_lem handleTimeout_log_same.\n          find_copy_apply_lem_hyp handleTimeout_type.\n          intuition; try congruence.\n          eapply_prop_hyp In In; eauto; try congruence.\n        * eapply_prop_hyp In In; eauto; congruence.\n      + do_in_map. find_eapply_lem_hyp handleTimeout_sends_RV; eauto.\n        break_exists. subst. simpl in *. discriminate.\n  Qed.\n\n  Lemma handleAppendEntries_post_leader_nop :\n    forall h st t n pli plt es ci st' m,\n      currentTerm st <> t ->\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      type st' = Leader ->\n      st' = st.\n  Proof using. \n    unfold handleAppendEntries.\n    intros.\n    repeat break_match; repeat find_inversion; auto; try discriminate.\n  Qed.\n\n  Lemma handleAppendEntries_leader_was_leader :\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      type st' = Leader ->\n      type st = Leader.\n  Proof using. \n    unfold handleAppendEntries.\n    intros.\n    repeat break_match; repeat find_inversion; auto; try discriminate.\n  Qed.\n\n  Lemma lifted_no_AE_to_leader :\n    forall net p t n pli plt es ci,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      type (snd (nwState net (pDst p))) = Leader ->\n      currentTerm (snd (nwState net (pDst p))) = t ->\n      False.\n  Proof using naetli rri. \n    intros.\n    pose proof (lift_prop _ no_append_entries_to_leader_invariant _ ltac:(eauto)).\n    unfold no_append_entries_to_leader in *.\n    find_apply_lem_hyp ghost_packet.\n    match goal with\n    | [ H : forall _ _ _ , _, H' : In _ _ |- _ ] => eapply H in H'; eauto\n    end;\n    rewrite deghost_spec;\n    rewrite pDst_deghost_packet; auto.\n  Qed.\n\n  Lemma lifted_no_AE_to_self :\n    forall net p t n pli plt es ci,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      pDst p = pSrc p ->\n      False.\n  Proof using naetsi rri. \n    intros.\n    pose proof (lift_prop _ no_append_entries_to_self_invariant _ ltac:(eauto)).\n    unfold no_append_entries_to_self in *.\n    find_apply_lem_hyp ghost_packet.\n    match goal with\n    | [ H : forall _ _ _ , _, H' : In _ _ |- _ ] => eapply H in H'; eauto\n    end.\n  Qed.\n\n  Lemma handleAppendEntries_message :\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      exists res, m = AppendEntriesReply (currentTerm st') es res.\n  Proof using. \n    unfold handleAppendEntries, advanceCurrentTerm.\n    intros. repeat break_match; repeat find_inversion; simpl in *; repeat do_bool; eauto;\n            eexists; f_equal; eauto using NPeano.Nat.le_antisymm.\n  Qed.\n\n  Lemma not_empty_true_elim :\n    forall A (l : list A),\n      not_empty l = true -> l <> nil.\n  Proof using. \n    unfold not_empty.\n    intros. break_match; congruence.\n  Qed.\n\n  Lemma not_empty_false_elim :\n    forall A (l : list A),\n      not_empty l = false -> l = nil.\n  Proof using. \n    unfold not_empty.\n    intros. break_match; congruence.\n  Qed.\n\n  Lemma handleAppendEntries_success_allEntries :\n    forall h st t n pli plt es ci st' t',\n      handleAppendEntries h st t n pli plt es ci = (st', AppendEntriesReply t' es true) ->\n      es <> nil ->\n      (forall e e' e'',\n          In e es ->\n          In e' (log st) ->\n          eIndex e = eIndex e' ->\n          eTerm e = eTerm e' ->\n          In e'' es ->\n          eIndex e'' <= eIndex e ->\n          In e'' (log st)) ->\n      sorted (log st) ->\n      exists e, In e (log st') /\\ In e es /\\\n                eIndex e = maxIndex es /\\\n                eTerm e = maxTerm es.\n  Proof using. \n    unfold handleAppendEntries, haveNewEntries.\n    intros.\n    break_if; try find_inversion.\n    break_if.\n    - break_if; find_inversion; simpl;\n      repeat (do_bool; repeat break_and).\n      + find_apply_lem_hyp not_empty_true_elim.\n        pose proof maxIndex_non_empty es ltac:(auto).\n        break_exists_exists. intuition.\n      + break_or_hyp.\n        * find_apply_lem_hyp not_empty_false_elim. congruence.\n        * break_match; try discriminate.\n          do_bool. rewrite advanceCurrentTerm_log.\n          find_apply_lem_hyp findAtIndex_elim. break_and.\n          pose proof maxIndex_non_empty es ltac:(auto).\n          break_exists_name e'. break_and.\n          match goal with\n          | [ H : forall _ _ _, In _ _ -> _ |- _ ] =>\n            specialize (H e' e e')\n          end.\n          repeat find_rewrite. repeat concludes. intuition.\n          assert (e = e').\n          { eapply uniqueIndices_elim_eq; eauto.\n            auto using sorted_uniqueIndices.\n          }\n          subst. eauto.\n    - break_match; try find_inversion.\n      break_if; try find_inversion.\n      break_if; find_inversion; simpl;\n      repeat (do_bool; repeat break_and).\n      + find_apply_lem_hyp not_empty_true_elim.\n        pose proof maxIndex_non_empty es ltac:(auto).\n        break_exists_exists. intuition.\n      + break_or_hyp.\n        * find_apply_lem_hyp not_empty_false_elim. congruence.\n        * break_match; try discriminate.\n          do_bool. rewrite advanceCurrentTerm_log.\n          find_apply_lem_hyp findAtIndex_elim. break_and.\n          pose proof maxIndex_non_empty es ltac:(auto).\n          break_exists_name e'. break_and.\n          match goal with\n          | [ H : forall _ _ _, In _ _ -> _ |- _ ] =>\n            specialize (H e' e0 e')\n          end.\n          repeat find_rewrite. repeat concludes. intuition.\n          assert (e0 = e').\n          { eapply uniqueIndices_elim_eq; eauto.\n            auto using sorted_uniqueIndices.\n          }\n          subst. eauto.\n  Qed.\n\n  Lemma handleAppendEntries_success_term :\n    forall h st t n pli plt es ci st' t',\n      handleAppendEntries h st t n pli plt es ci = (st', AppendEntriesReply t' es true) ->\n      currentTerm st' = t.\n  Proof using. \n    unfold handleAppendEntries, advanceCurrentTerm.\n    intros. repeat break_match; repeat find_inversion; simpl; auto; repeat do_bool;\n    eauto using Nat.le_antisymm.\n  Qed.\n\n  Lemma lifted_terms_and_indices_from_one_log : forall net h,\n    refined_raft_intermediate_reachable net ->\n    terms_and_indices_from_one (log (snd (nwState net h))).\n  Proof using taifoli rri. \n    intros net0;intros.\n    pose proof (lift_prop _ terms_and_indices_from_one_log_invariant).\n    unfold terms_and_indices_from_one_log in *.\n    rewrite <- deghost_spec with (net := net0). auto.\n  Qed.\n\n  Lemma lifted_leader_sublog_nw :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      type (snd (nwState net h)) = Leader ->\n      eTerm e = currentTerm (snd (nwState net h)) ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using lsi rri. \n    intros.\n    pose proof (lift_prop _ leader_sublog_invariant_invariant _ ltac:(eauto)) as Hinv.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant in *.\n    destruct Hinv as [Hhost Hnw].\n    find_apply_lem_hyp ghost_packet.\n    eapply_prop_hyp In In; eauto; try find_rewrite_lem deghost_spec; try rewrite deghost_spec; eauto.\n  Qed.\n\n  Lemma appendEntries_sublog :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      currentTerm (snd (nwState net h)) = t ->\n      type (snd (nwState net h)) = Leader ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using ollpti lhllsi lsi aelli rri. \n    intros.\n    find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n    break_exists. break_and.\n    subst es.\n    find_apply_lem_hyp in_app_or. destruct H4.\n    - find_copy_apply_hyp_hyp.\n      eapply lifted_leader_sublog_nw; eauto; [subst; auto|auto with datatypes].\n    - find_eapply_lem_hyp leaders_have_leaderLogs_strong_invariant; auto.\n      break_exists.  break_and.\n      pose proof one_leaderLog_per_term_invariant _ ltac:(eauto) h x (currentTerm (snd (nwState net h))) x3 x0.\n      concludes.\n      subst_max.\n      concludes.\n      break_and. subst.\n      find_rewrite. eauto using Prefix_In with *.\n  Qed.\n\n  Lemma match_index_all_entries_append_entries :\n    refined_raft_net_invariant_append_entries' match_index_all_entries_inv.\n  Proof using ollpti lhllsi lsi aelli laei rlmli taifoli naetsi naetli rri. \n    unfold refined_raft_net_invariant_append_entries', match_index_all_entries_inv.\n    simpl. intros. break_and.\n    split.\n    - unfold match_index_all_entries in *. simpl. intros.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify_hyp.\n      + assert (currentTerm (snd (nwState net (pDst p))) <> t).\n        { intro.\n          match goal with\n          | [ H : pBody _ = AppendEntries _ _ _ _ _ _ |- _ ] =>\n            eapply lifted_no_AE_to_leader with (net := net) in H; eauto\n          end.\n          eapply handleAppendEntries_leader_was_leader; eauto.\n        }\n        find_apply_lem_hyp handleAppendEntries_post_leader_nop; auto.\n        subst. eapply_prop_hyp In In; eauto.\n        repeat find_rewrite.\n        update_destruct_simplify_hyp; auto using update_elections_data_appendEntries_preserves_allEntries.\n      + eapply_prop_hyp In In; eauto. repeat find_rewrite.\n        update_destruct_simplify_hyp; auto using update_elections_data_appendEntries_preserves_allEntries.\n    - unfold match_index_all_entries_nw. simpl.  intros.\n      find_apply_hyp_hyp. break_or_hyp.\n      + unfold match_index_all_entries_nw in *.\n        repeat find_higher_order_rewrite.\n        update_destruct_simplify_hyp.\n        * assert (currentTerm (snd (nwState net (pDst p))) <> t).\n          { intro.\n            match goal with\n            | [ H : pBody _ = AppendEntries _ _ _ _ _ _ |- _ ] =>\n              eapply lifted_no_AE_to_leader with (net := net) in H; eauto\n            end.\n            eapply handleAppendEntries_leader_was_leader; eauto.\n          }\n          match goal with\n          | [ H : context [handleAppendEntries] |- _ ] =>\n            apply handleAppendEntries_post_leader_nop in H; auto\n          end.\n          subst.\n          match goal with\n          | [ H : In _ (_ ++ _), H' : forall _ _ _ _, In _ _ -> _ |- _ ] =>\n            eapply in_middle_insert in H; eapply H' in H; eauto; try congruence\n          end.\n          { update_destruct_simplify_hyp.\n            - apply update_elections_data_appendEntries_preserves_allEntries.\n              repeat find_rewrite. auto.\n            - auto.\n          }\n        * match goal with\n          | [ H : forall _ _ _ _, In _ _ -> _, H' : pBody _ = AppendEntriesReply _ _ _ |- _ ] =>\n            eapply H in H'; eauto\n          end.\n          { update_destruct_simplify_hyp.\n            - apply update_elections_data_appendEntries_preserves_allEntries.\n              repeat find_rewrite. auto.\n            - auto.\n          }\n      + simpl in *.\n        find_copy_apply_lem_hyp handleAppendEntries_message. break_exists.\n        subst. find_inversion.\n        repeat find_higher_order_rewrite.\n        update_destruct_simplify_hyp.\n        * exfalso. eapply lifted_no_AE_to_self with (net := net); eauto.\n        * unfold update_elections_data_appendEntries. repeat find_rewrite. simpl.\n          { find_copy_apply_lem_hyp handleAppendEntries_success_allEntries.\n            - break_exists. break_and.\n              find_copy_apply_lem_hyp handleAppendEntries_success_term.\n              assert (In x (log (snd (nwState net (pSrc p))))).\n              { eapply appendEntries_sublog; eauto. subst. repeat find_rewrite. auto. }\n              assert (entries_match (log d) (log (snd (nwState net (pSrc p))))).\n              { match goal with\n                | [ H : refined_raft_intermediate_reachable (mkNetwork ?a ?b) |- _ ] =>\n                  let H' := fresh \"H\" in\n                  pose proof entries_match_invariant _ (pDst p) (pSrc p) H as H';\n                    simpl in H'; repeat find_higher_order_rewrite; rewrite_update;\n                    simpl in H'; auto\n                end.\n              }\n              assert (In e (log d)) as Helogd.\n              { match goal with\n                | [ H : entries_match _ _ |- _ ] =>\n                  specialize (H x x e)\n                end.\n                assert (eIndex e <= eIndex x) by lia.\n                repeat concludes. intuition.\n              }\n\n              match goal with\n              | [ H : refined_raft_intermediate_reachable (mkNetwork ?a ?b) |- _ ] =>\n                let H' := fresh \"H\" in\n                pose proof log_all_entries_invariant _ H (pDst p) e as H';\n                  simpl in H'; repeat find_higher_order_rewrite; rewrite_update;\n                  simpl in H'; unfold update_elections_data_appendEntries in H';\n                  repeat find_rewrite; simpl in H'\n              end.\n              auto.\n            - find_apply_lem_hyp lifted_terms_and_indices_from_one_log; auto. break_and.\n              apply maxIndex_gt_0_nonempty. lia.\n            - intros.\n              match goal with\n              | [ H : refined_raft_intermediate_reachable (mkNetwork _ _) |- _ ] => clear H\n              end.\n              pose proof entries_match_nw_host_invariant _ ltac:(eauto) _ _ _ _ _ _ _ (pDst p)\n                   e0 e' e'' ltac:(eauto) ltac:(eauto).\n              repeat find_rewrite. auto.\n            - apply entries_sorted_invariant. auto.\n          }\n  Qed.\n\n  Lemma handleAppendEntriesReply_spec :\n    forall n st src t es b st' l,\n      handleAppendEntriesReply n st src t es b = (st', l) ->\n      (type st' = type st /\\\n       matchIndex st' = matchIndex st /\\\n       currentTerm st' = currentTerm st) \\/\n      (currentTerm st' = t /\\ type st' = Follower) \\/\n      (b = true /\\\n       t = currentTerm st' /\\\n       type st' = type st /\\\n       matchIndex st' = assoc_set name_eq_dec (matchIndex st) src\n                                  (PeanoNat.Nat.max\n                                     (assoc_default name_eq_dec (matchIndex st) src 0) (maxIndex es)) /\\\n       currentTerm st' = currentTerm st).\n  Proof using. \n    unfold handleAppendEntriesReply.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto.\n    - do_bool. intuition.\n    - unfold advanceCurrentTerm. break_match; auto.\n  Qed.\n\n  Lemma update_nop_fst :\n    forall A B f x (v2 : B) y,\n      fst (update name_eq_dec f x (fst (f x), v2) y) = fst (A := A) (f y).\n  Proof using. \n    intros.\n    update_destruct_simplify_hyp; auto.\n  Qed.\n\n  Lemma match_index_all_entries_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, match_index_all_entries_inv.\n    simpl. intros. split.\n    - { unfold match_index_all_entries in *. simpl. intros. break_and.\n        repeat find_higher_order_rewrite.\n        rewrite update_nop_fst.\n        update_destruct_simplify_hyp.\n        - find_copy_apply_lem_hyp handleAppendEntriesReply_spec.\n          intuition.\n          + match goal with\n            | [ H : forall _ _ _, type _ = _ -> _ |- _ ] => specialize (H e (pDst p) h)\n            end.\n            repeat find_rewrite. repeat concludes.\n            find_erewrite_lem handleAppendEntriesReply_log.\n            auto.\n          + congruence.\n          + repeat find_rewrite.\n            match goal with\n            | [ H : context [ assoc_default _ (assoc_set _ _ ?x _) ?y _ ]  |- _ ] =>\n              destruct (name_eq_dec x y)\n            end.\n            * subst. rewrite get_set_same_default in *.\n              find_apply_lem_hyp app_cons_in.\n              find_erewrite_lem handleAppendEntriesReply_log.\n              { find_apply_lem_hyp PeanoNat.Nat.max_le. break_or_hyp.\n                - match goal with\n                  | [ H : forall _ _ _, type _ = _ -> _ |- _ ] => specialize (H e (pDst p) (pSrc p))\n                  end. repeat find_rewrite. auto.\n                - unfold match_index_all_entries_nw in *.\n                  match goal with\n                  | [ H : pBody _ = _, H' : _  |- _ ] => eapply H' with (e := e) in H; auto\n                  end.\n              }\n            * rewrite get_set_diff_default in * by auto.\n              match goal with\n              | [ H : forall _ _ _, type _ = _ -> _ |- _ ] => specialize (H e (pDst p) h)\n              end.\n              repeat find_rewrite. repeat concludes.\n              find_erewrite_lem handleAppendEntriesReply_log.\n              auto.\n        - find_apply_hyp_hyp. congruence.\n      }\n    - break_and. unfold match_index_all_entries_nw in *. simpl. intros.\n      repeat find_higher_order_rewrite. rewrite update_nop_fst.\n      find_apply_hyp_hyp.\n      break_or_hyp.\n      + update_destruct_simplify_hyp.\n        * find_erewrite_lem handleAppendEntriesReply_log.\n          find_copy_apply_lem_hyp handleAppendEntriesReply_spec.\n          { repeat break_or_hyp; break_and.\n            - repeat find_rewrite. eauto using in_middle_insert.\n            - congruence.\n            - repeat find_rewrite. eauto using in_middle_insert.\n          }\n        * eauto using in_middle_insert.\n      + do_in_map. find_apply_lem_hyp handleAppendEntriesReply_packets. subst.\n        simpl in *. intuition.\n  Qed.\n\n  Lemma handleRequestVote_sends_RVR :\n    forall st h h' t lli llt st' m,\n      handleRequestVote h st t h' lli llt = (st', m) ->\n      exists t b, m = RequestVoteReply t b.\n  Proof using. \n    unfold handleRequestVote.\n    intros.\n    repeat break_match; repeat find_inversion; eauto.\n  Qed.\n\n  Lemma match_index_all_entries_request_vote :\n    refined_raft_net_invariant_request_vote match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, match_index_all_entries_inv.\n    simpl. intros. split.\n    - unfold match_index_all_entries in *. simpl. intros. break_and.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify_hyp.\n      + find_copy_apply_lem_hyp handleRequestVote_type.\n        intuition; try congruence.\n        find_copy_apply_lem_hyp handleRequestVote_matchIndex_preserved.\n        unfold matchIndex_preserved in *. intuition.\n        update_destruct_simplify_hyp.\n        * rewrite update_elections_data_requestVote_allEntries.\n          repeat find_reverse_rewrite.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            apply H with (leader := pDst p)\n          end; auto;\n            repeat find_rewrite; auto.\n        * repeat find_reverse_rewrite.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            apply H with (leader := pDst p)\n          end; auto;\n            repeat find_rewrite; auto.\n      + update_destruct_simplify_hyp.\n        * rewrite update_elections_data_requestVote_allEntries.\n          repeat find_reverse_rewrite.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto\n          end.\n        * repeat find_reverse_rewrite.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto\n          end.\n    - break_and.\n      unfold match_index_all_entries_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp. break_or_hyp.\n      + repeat find_higher_order_rewrite.\n        update_destruct_simplify_hyp.\n        * { find_copy_apply_lem_hyp handleRequestVote_type.\n            intuition; try congruence.\n            find_copy_apply_lem_hyp handleRequestVote_matchIndex_preserved.\n            unfold matchIndex_preserved in *. intuition.\n            update_destruct_simplify_hyp.\n            - rewrite update_elections_data_requestVote_allEntries.\n              repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                apply H with (es := es); auto using in_middle_insert; try congruence\n              end.\n            - match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                apply H with (es := es); auto using in_middle_insert; try congruence\n              end.\n          }\n        * { update_destruct_simplify_hyp.\n            - rewrite update_elections_data_requestVote_allEntries.\n              repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                apply H with (es := es); auto using in_middle_insert; try congruence\n              end.\n            - match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                apply H with (es := es); auto using in_middle_insert; try congruence\n              end.\n          }\n      + simpl in *.\n        find_apply_lem_hyp handleRequestVote_sends_RVR.\n        break_exists.\n        congruence.\n  Qed.\n\n  Lemma handleRequestVoteReply_spec :\n    forall h st h' t r st',\n      handleRequestVoteReply h st h' t r = st' ->\n      type st' = Follower \\/\n      st' = st \\/\n      (log st' = log st /\\\n       currentTerm st' = currentTerm st /\\\n       matchIndex st' = assoc_set name_eq_dec nil h (maxIndex (log st))).\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; subst; simpl; intuition.\n  Qed.\n\n  Lemma handleRequestVoteReply_spec' :\n    forall h st h' t r st',\n      handleRequestVoteReply h st h' t r = st' ->\n      type st' = Follower \\/\n      st' = st \\/\n      type st' = Candidate \\/\n      (type st' = Leader /\\\n       type st = Candidate /\\\n       log st' = log st /\\\n       r = true /\\\n       t = currentTerm st /\\\n       wonElection (dedup name_eq_dec (h' :: votesReceived st)) = true /\\\n       currentTerm st' = currentTerm st).\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; do_bool; subst; simpl; intuition.\n  Qed.\n\n\n  Lemma match_index_all_entries_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply match_index_all_entries_inv.\n  Proof using cci vci cei laei taifoli rri. \n    unfold refined_raft_net_invariant_request_vote_reply, match_index_all_entries_inv.\n    simpl. intros. split.\n    - unfold match_index_all_entries in *. simpl. intros. break_and.\n      find_apply_lem_hyp handleRequestVoteReply_spec.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify_hyp.\n      + intuition; try congruence.\n        * subst.\n          { update_destruct_simplify_hyp.\n            - rewrite update_elections_data_requestVoteReply_allEntries.\n              repeat find_reverse_rewrite. eauto.\n            - repeat find_reverse_rewrite. eauto.\n          }\n        * repeat find_rewrite.\n          unfold assoc_default in *.\n          { break_match.\n            - simpl in *. break_if; try discriminate.\n              match goal with\n              | [ H : Some _ = Some _ |- _ ] => invc H\n              end.\n              rewrite_update.\n              simpl.\n              rewrite update_elections_data_requestVoteReply_allEntries.\n              match goal with\n              | [ |- In (?t, _) _ ] => replace t with (eTerm e) by congruence\n              end.\n              eapply log_all_entries_invariant; auto.\n            - find_apply_lem_hyp lifted_terms_and_indices_from_one_log; auto.\n              intuition. lia.\n          }\n      + update_destruct_simplify_hyp.\n        * rewrite update_elections_data_requestVoteReply_allEntries.\n          repeat find_reverse_rewrite. eauto.\n        * repeat find_reverse_rewrite. eauto.\n    - unfold match_index_all_entries_nw in *.\n      simpl in *.\n      intros.\n      find_apply_lem_hyp handleRequestVoteReply_spec'.\n      repeat find_higher_order_rewrite.\n      find_apply_hyp_hyp.\n      update_destruct_simplify_hyp.\n      + intuition; try congruence.\n        * subst.\n          { update_destruct_simplify_hyp.\n            - rewrite update_elections_data_requestVoteReply_allEntries.\n              repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                eapply H; eauto; congruence\n              end.\n            - repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                eapply H; eauto; congruence\n              end.\n          }\n        * subst.\n          intro_refined_invariant candidate_entries_invariant.\n          match goal with\n          | [ H : candidateEntries_host_invariant _ |- _ ] =>\n            pose proof H (pDst p) e\n          end.\n          unfold raft_data in *.\n          conclude_using congruence.\n          { find_eapply_lem_hyp wonElection_candidateEntries_rvr; eauto.\n            - intuition.\n            - eauto using votes_correct_invariant.\n            - eauto using cronies_correct_invariant.\n            - unfold raft_refined_base_params, raft_refined_multi_params in *. congruence.\n            - unfold raft_refined_multi_params, raft_refined_base_params in *.\n              simpl in *.\n              unfold raft_data in *.\n              congruence.\n          }\n      + { update_destruct_simplify_hyp.\n            - rewrite update_elections_data_requestVoteReply_allEntries.\n              repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                eapply H; eauto; congruence\n              end.\n            - repeat find_rewrite.\n              match goal with\n              | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n                eapply H; eauto; congruence\n              end.\n          }\n  Qed.\n\n  Lemma doLeader_sends_AE :\n    forall st h os st' ms m,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      is_append_entries (snd m).\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n    subst.\n    unfold replicaMessage.\n    repeat break_match; simpl; eauto 10.\n  Qed.\n\n  Lemma match_index_all_entries_do_leader :\n    refined_raft_net_invariant_do_leader match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, match_index_all_entries_inv.\n    intros. break_and. split.\n    - unfold match_index_all_entries in *.\n      simpl in *. intros.\n      repeat find_higher_order_rewrite.\n      match goal with\n      | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n        replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n      end.\n      rewrite update_nop_fst.\n      update_destruct_simplify_hyp.\n      + repeat find_reverse_rewrite.\n        find_copy_apply_lem_hyp doLeader_type. intuition.\n        find_copy_apply_lem_hyp doLeader_matchIndex_preserved.\n        unfold matchIndex_preserved in *. intuition.\n        match goal with\n        | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n          eapply H; eauto; try congruence\n        end.\n      + repeat find_reverse_rewrite.\n        match goal with\n        | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n          eapply H; eauto; try congruence\n        end.\n    - unfold match_index_all_entries_nw in *.\n      simpl in *.\n      intros.\n      find_apply_hyp_hyp.\n      break_or_hyp.\n      + repeat find_higher_order_rewrite.\n        match goal with\n        | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n          replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n            replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n            clear H\n        end.\n        rewrite update_nop_fst in *.\n        find_copy_apply_lem_hyp doLeader_type. intuition.\n        update_destruct_simplify_hyp.\n        * find_copy_apply_lem_hyp doLeader_matchIndex_preserved.\n          unfold matchIndex_preserved in *. intuition.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto; try congruence\n          end.\n        * match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto; try congruence\n          end.\n      + do_in_map.\n        find_eapply_lem_hyp doLeader_sends_AE; [|eauto].\n        break_exists. subst.\n        simpl in *. congruence.\n  Qed.\n\n  Lemma match_index_all_entries_do_generic_server :\n    refined_raft_net_invariant_do_generic_server match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, match_index_all_entries_inv.\n    simpl. intros. break_and. split.\n    - unfold match_index_all_entries in *.\n      simpl in *. intros.\n      repeat find_higher_order_rewrite.\n      match goal with\n      | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n        replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n      end.\n      rewrite update_nop_fst.\n      update_destruct_simplify_hyp.\n      + repeat find_reverse_rewrite.\n        find_copy_apply_lem_hyp doGenericServer_type. intuition.\n        find_copy_apply_lem_hyp doGenericServer_matchIndex_preserved.\n        unfold matchIndex_preserved in *. intuition.\n        match goal with\n        | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n          eapply H; eauto; try congruence\n        end.\n      + repeat find_reverse_rewrite.\n        match goal with\n        | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n          eapply H; eauto; try congruence\n        end.\n    - unfold match_index_all_entries_nw in *.\n      simpl in *.\n      intros.\n      find_apply_hyp_hyp.\n      break_or_hyp.\n      + repeat find_higher_order_rewrite.\n        match goal with\n        | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n          replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n            replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n            clear H\n        end.\n        rewrite update_nop_fst in *.\n        find_copy_apply_lem_hyp doGenericServer_type. intuition.\n        update_destruct_simplify_hyp.\n        * find_copy_apply_lem_hyp doGenericServer_matchIndex_preserved.\n          unfold matchIndex_preserved in *. intuition.\n          match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto; try congruence\n          end.\n        * match goal with\n          | [ H : context [ In _ (allEntries _) ] |- _ ] =>\n            eapply H; eauto; try congruence\n          end.\n      + do_in_map.\n        find_apply_lem_hyp doGenericServer_packets.\n        subst. simpl in *. intuition.\n  Qed.\n\n  Lemma match_index_all_entries_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, match_index_all_entries_inv.\n    simpl. intros. break_and. split.\n    - unfold match_index_all_entries in *.\n      intros.\n      repeat find_reverse_higher_order_rewrite.\n      eauto.\n    - unfold match_index_all_entries_nw in *.\n      intros.\n      find_apply_hyp_hyp.\n      repeat find_reverse_higher_order_rewrite.\n      eauto.\n  Qed.\n\n\n  Lemma match_index_all_entries_reboot :\n    refined_raft_net_invariant_reboot match_index_all_entries_inv.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, match_index_all_entries_inv.\n    intros. break_and. subst. split.\n    - unfold match_index_all_entries in *.\n      intros.\n      repeat find_higher_order_rewrite.\n      match goal with\n      | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n        replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n          replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n          clear H\n      end.\n      rewrite update_nop_fst.\n      update_destruct_simplify_hyp.\n      + discriminate.\n      + repeat find_reverse_rewrite.\n        eauto.\n    - unfold match_index_all_entries_nw in *.\n      intros.\n      repeat find_higher_order_rewrite.\n      match goal with\n      | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n        replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n          replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n          clear H\n      end.\n      rewrite update_nop_fst.\n      update_destruct_simplify_hyp.\n      + discriminate.\n      + repeat find_reverse_rewrite.\n        eauto.\n  Qed.\n\n  Lemma match_index_all_entries_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      match_index_all_entries_inv net.\n  Proof using cci vci cei aersi matchisi mili ollpti lhllsi lsi aelli laei rlmli taifoli naetsi naetli rri. \n    intros.\n    apply refined_raft_net_invariant'; auto.\n    - apply match_index_all_entries_init.\n    - apply refined_raft_net_invariant_client_request'_weak.\n      apply match_index_all_entries_client_request.\n    - apply refined_raft_net_invariant_timeout'_weak.\n      apply match_index_all_entries_timeout.\n    - apply match_index_all_entries_append_entries.\n    - apply refined_raft_net_invariant_append_entries_reply'_weak.\n      apply match_index_all_entries_append_entries_reply.\n    - apply refined_raft_net_invariant_request_vote'_weak.\n      apply match_index_all_entries_request_vote.\n    - apply refined_raft_net_invariant_request_vote_reply'_weak.\n      apply match_index_all_entries_request_vote_reply.\n    - apply refined_raft_net_invariant_do_leader'_weak.\n      apply match_index_all_entries_do_leader.\n    - apply refined_raft_net_invariant_do_generic_server'_weak.\n      apply match_index_all_entries_do_generic_server.\n    - apply match_index_all_entries_state_same_packet_subset.\n    - apply refined_raft_net_invariant_reboot'_weak.\n      apply match_index_all_entries_reboot.\n  Qed.\n\n  Instance miaei : match_index_all_entries_interface.\n  Proof.\n    constructor.\n    apply match_index_all_entries_invariant.\n  Qed.\nEnd MatchIndexAllEntries.\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/MatchIndexAllEntriesProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.19194673887960917}}
{"text": "From Coq Require Import Utf8 RelationClasses.\nFrom PDM Require Import util structures.\n\n(* Guarded monad *)\n\nDefinition G (A : Type) :=\n  \u2211 (P : Prop), P \u2192 A.\n\n#[export] Instance Monad_G : Monad G.\nProof.\n  simple refine {|\n    ret A x := (True ; \u03bb _, x)\n  |}.\n  (* bind *)\n  intros A B x f. simpl.\n  exists (\u2203 (h : x.\u03c01), (f (x.\u03c02 h)).\u03c01).\n  simple refine (\u03bb h, (f (x.\u03c02 _)).\u03c02 _).\n  - destruct h. assumption.\n  - destruct h as [h hf]. assumption.\nDefined.\n\n#[export] Instance ReqMonad_G : ReqMonad G := {|\n  req p := (p ; \u03bb h, h)\n|}.\n", "meta": {"author": "TheoWinterhalter", "repo": "pdm4all", "sha": "570868f2e395bada6e3dc0462d7e9af065289461", "save_path": "github-repos/coq/TheoWinterhalter-pdm4all", "path": "github-repos/coq/TheoWinterhalter-pdm4all/pdm4all-570868f2e395bada6e3dc0462d7e9af065289461/theories/guarded.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.19188053494651464}}
{"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.RequestVoteMaxIndexMaxTermInterface.\nRequire Import VerdiRaft.RequestVoteTermSanityInterface.\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  Context {rri : raft_refinement_interface}.\n  Context {rvrtsi : requestVote_term_sanity_interface}.\n\n  Lemma requestVote_maxIndex_maxTerm_append_entries :\n    refined_raft_net_invariant_append_entries requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    assert (In p0 (nwPackets net)) by\n        (find_apply_hyp_hyp; repeat find_rewrite; intuition; [in_crush|];\n         exfalso; subst; simpl in *; subst;\n         unfold handleAppendEntries in *;\n           repeat break_match; find_inversion).\n    repeat find_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite votesWithLog_same_append_entries; eauto;\n    find_apply_lem_hyp handleAppendEntries_log_term_type.\n    break_or_hyp; try congruence.\n    break_and; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    assert (In p0 (nwPackets net)) by\n        (repeat find_rewrite;\n         find_apply_lem_hyp handleAppendEntriesReply_packets;\n         subst; simpl in *; find_apply_hyp_hyp; intuition; in_crush).\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log_term_type.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    break_or_hyp; try congruence; break_and; repeat find_rewrite; eauto.\n  Qed.\n  \n  Lemma requestVote_maxIndex_maxTerm_request_vote :\n    refined_raft_net_invariant_request_vote requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    assert (In p0 (nwPackets net)) by\n        (find_apply_hyp_hyp; repeat find_rewrite; intuition; [in_crush|];\n         exfalso; subst; simpl in *; subst;\n         unfold handleRequestVote in *;\n           repeat break_match; find_inversion).\n    find_copy_apply_lem_hyp handleRequestVote_log_term_type.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    break_or_hyp; try congruence; break_and; repeat find_rewrite; eauto.\n  Qed.\n  \n  Lemma requestVote_maxIndex_maxTerm_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_eapply_lem_hyp handleRequestVoteReply_log_term_type; eauto.\n    break_and; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_timeout :\n    refined_raft_net_invariant_timeout requestVote_maxIndex_maxTerm.\n  Proof using rvrtsi. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - find_apply_hyp_hyp. break_or_hyp.\n      + exfalso.\n        find_eapply_lem_hyp update_elections_data_timeout_votesWithLog_votesReceived; eauto.\n        intuition; try congruence.\n        find_apply_lem_hyp requestVote_term_sanity_invariant.\n        eapply_prop_hyp requestVote_term_sanity pBody; eauto.\n        unfold raft_data in *; simpl in *; unfold raft_data in *; simpl in *.\n        lia.\n      + do_in_map. remember (pSrc p). subst p.\n        simpl in *.\n        intuition; eapply handleTimeout_messages; eauto.\n    - find_apply_hyp_hyp. break_or_hyp; eauto.\n      do_in_map. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_client_request :\n    refined_raft_net_invariant_client_request requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    find_copy_apply_lem_hyp handleClientRequest_packets.\n    subst. simpl in *.\n    find_apply_hyp_hyp. break_or_hyp.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite votesWithLog_same_client_request; eauto;\n    find_apply_lem_hyp handleClientRequest_candidate; subst; eauto.\n    intuition.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_do_leader :\n    refined_raft_net_invariant_do_leader requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    assert (In p (nwPackets net)) by\n        (find_apply_hyp_hyp; intuition;\n         do_in_map; subst;\n         unfold doLeader, replicaMessage in *;\n           repeat break_match; find_inversion; subst; simpl in *; intuition;\n         do_in_map; subst; simpl in *; congruence).\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    find_apply_lem_hyp doLeader_candidate; subst; eauto.\n  Qed.\n  \n  Lemma requestVote_maxIndex_maxTerm_do_generic_server :\n    refined_raft_net_invariant_do_generic_server requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    find_copy_apply_lem_hyp doGenericServer_packets. subst. simpl in *.\n    find_apply_hyp_hyp. break_or_hyp.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    find_apply_lem_hyp doGenericServer_log_type_term_votesReceived;\n    break_and; repeat find_rewrite; eauto. intuition.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_reboot :\n    refined_raft_net_invariant_reboot requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto; congruence.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    subst. repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma requestVote_maxIndex_maxTerm_init :\n    refined_raft_net_invariant_init requestVote_maxIndex_maxTerm.\n  Proof using. \n    red. unfold requestVote_maxIndex_maxTerm. intros. simpl in *.\n    intuition.\n  Qed.\n\n  Instance rvmimti : requestVote_maxIndex_maxTerm_interface.\n  split.\n  intros.\n  apply refined_raft_net_invariant; auto.\n  - apply requestVote_maxIndex_maxTerm_init.\n  - apply requestVote_maxIndex_maxTerm_client_request.\n  - apply requestVote_maxIndex_maxTerm_timeout.\n  - apply requestVote_maxIndex_maxTerm_append_entries.\n  - apply requestVote_maxIndex_maxTerm_append_entries_reply.\n  - apply requestVote_maxIndex_maxTerm_request_vote.\n  - apply requestVote_maxIndex_maxTerm_request_vote_reply.\n  - apply requestVote_maxIndex_maxTerm_do_leader.\n  - apply requestVote_maxIndex_maxTerm_do_generic_server.\n  - apply requestVote_maxIndex_maxTerm_state_same_packet_subset.\n  - apply requestVote_maxIndex_maxTerm_reboot.\n  Qed.\n  \nEnd RequestVoteMaxIndexMaxTerm.\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/RequestVoteMaxIndexMaxTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.19188052770221997}}
{"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 int.Abs.\nRequire int.ComputerDivision.\nRequire int.Power.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom qtmark : Type.\nParameter qtmark_WhyType : WhyType qtmark.\nExisting Instance qtmark_WhyType.\n\n(* Why3 assumption *)\nInductive 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\nImport int.ComputerDivision.\nImport Power.\n\n(* Why3 goal *)\nTheorem WP_parameter_fast_exp_imperative : forall (x:Z) (n:Z),\n  (0%Z <= n)%Z -> forall (e:Z) (p:Z) (r:Z), ((0%Z <= e)%Z /\\\n  ((r * (int.Power.power p e))%Z = (int.Power.power x n))) -> ((0%Z < e)%Z ->\n  (((ZArith.BinInt.Z.rem e 2%Z) = 1%Z) -> forall (r1:Z), (r1 = (r * p)%Z) ->\n  forall (p1:Z), (p1 = (p * p)%Z) -> forall (e1:Z),\n  (e1 = (ZArith.BinInt.Z.quot e 2%Z)) -> ((r1 * (int.Power.power p1\n  e1))%Z = (int.Power.power x n)))).\n(* Why3 intros x n h1 e p r (h2,h3) h4 h5 r1 h6 p1 h7 e1 h8. *)\nintros x n h1 e p r (h2,h3) h4 h5 r1 h6 p1 h7 e1 h8.\nsubst.\nassert (h: (2 <> 0)%Z) by omega.\ngeneralize (Div_mod e 2 h). clear h.\nassert (h: (0 < 2)%Z) by omega.\ngeneralize (Div_bound e 2 (conj h2 h)). clear h.\nrewrite h5; clear h5.\nintros.\nrewrite <- h3; clear h3.\nrewrite H0 at 2. clear H0.\nrewrite Power_sum by omega.\nreplace (2 * (Z.quot e 2))%Z with (Z.quot e 2 + Z.quot e 2)%Z by ring.\nrewrite Power_sum by apply H.\nrewrite Power_mult2 by apply H.\nrewrite Power_1.\nring.\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/power/power_M_WP_parameter_fast_exp_imperative_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19188052408007264}}
{"text": "From SkipList.atomic Require Import proofmode weakestpre.\nFrom SkipList.lazy_list Require Import code.\nFrom SkipList.lazy_list.rw_client Require Import spec.\n\nFrom iris.heap_lang Require Import par notation.\n\n\nModule Params <: LAZY_LIST_PARAMS.\n  Local Open Scope Z.\n  Definition INT_MIN := -1000.\n  Definition INT_MAX := 1000.\n  Lemma HMIN_MAX : INT_MIN < INT_MAX.\n  Proof. unfold INT_MIN, INT_MAX; lia. Qed.\nEnd Params.\n\nModule Import Spec := RWSpec Params.\n\nDefinition exampleN := nroot .@ \"example\".\n\nDefinition example_client : expr := \n  let: \"p\" := new #() in\n    ((add \"p\" #0;; add \"p\" #1) ||| (add \"p\" #1;; add \"p\" #2));;\n    (contains \"p\" #2 ||| contains \"p\" #0).\n\nSection Proofs.\n  Context `{!heapGS \u03a3, !rwG \u03a3, !spawnG \u03a3}.\n\n  Lemma example_client_spec :\n    {{{ True }}}\n      example_client\n    {{{ RET (#true, #true); True }}}.\n  Proof.\n    iIntros (\u03a6) \"_ H\u03a6\".\n\n    unfold example_client.\n    wp_apply new_spec; first done.\n    iIntros (p \u0393l) \"Hset\".\n    iDestruct (rw_inv_alloc_mut exampleN with \"Hset\") as \">Hinv\".\n    iDestruct \"Hinv\" as (\u0393) \"[#Hinv Hmut]\".\n\n    wp_let. \n    rewrite -(Qp.div_2 1); iDestruct (mut_set_sep with \"Hmut\") as \"[Hmut1 Hmut2]\".\n    wp_smart_apply (wp_par (\u03bb _, mut_set _ _ _) (\u03bb _, mut_set _ _ _) with \"[Hmut1] [Hmut2]\").\n    {\n      awp_apply (write_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hmut1\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros \"Hmut1\". iModIntro. iExists _, _. iFrame \"Hmut1\".\n      iIntros \"Hmut1 _\". iModIntro. wp_pures.\n\n      awp_apply (write_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hmut1\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros \"Hmut1\". iModIntro. iExists _, _. iFrame \"Hmut1\".\n      by iIntros.\n    }\n    { \n      awp_apply (write_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hmut2\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros \"Hmut2\". iModIntro. iExists _, _. iFrame \"Hmut2\".\n      iIntros \"Hmut2 _\". iModIntro. wp_pures.\n\n      awp_apply (write_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hmut2\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros \"Hmut2\". iModIntro. iExists _, _. iFrame \"Hmut2\".\n      by iIntros.\n    }\n    iIntros (? ?) \"Hmut\". rewrite ?left_id_L.\n    iDestruct (mut_set_join with \"Hmut\") as \"Hmut\".\n\n    iNext; wp_pure; wp_pure.\n    rewrite Qp.div_2; iDestruct (mut_to_const with \"Hinv Hmut\") as \">Hconst\".\n    rewrite -(Qp.div_2 1); iDestruct (const_set_sep with \"Hconst\") as \"[Hconst1 Hconst2]\".\n    wp_smart_apply (wp_par (\u03bb v, \u231c v = #true \u231d%I) (\u03bb v, \u231c v = #true \u231d%I) with \"[Hconst1] [Hconst2]\").\n    {\n      awp_apply (read_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hconst1\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros (b) \"[Hconst1 %Hif]\". iModIntro. iExists _, _. iFrame \"Hconst1\".\n      iIntros; iPureIntro. destruct (b); first done; last set_solver.\n    }\n    {\n      awp_apply (read_spec with \"Hinv\"); first rewrite /Params.INT_MIN/Params.INT_MAX//.\n      iAaccIntro with \"Hconst2\"; first (iIntros \"?\"; iModIntro; iFrame).\n      iIntros (b) \"[Hconst2 %Hif]\". iModIntro. iExists _, _. iFrame \"Hconst2\".\n      iIntros; iPureIntro. destruct (b); first done; last set_solver.\n    }\n    iIntros (? ?) \"[-> ->]\"; iNext; by iApply \"H\u03a6\".\n  Qed.\nEnd Proofs.", "meta": {"author": "sr-lab", "repo": "iris-jellyfish", "sha": "51ef73143ae06731ec48740c481961cf41c595fb", "save_path": "github-repos/coq/sr-lab-iris-jellyfish", "path": "github-repos/coq/sr-lab-iris-jellyfish/iris-jellyfish-51ef73143ae06731ec48740c481961cf41c595fb/lazy_list/rw_client/example.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19188052408007264}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.sepcomp.mem_lemmas.\n\n(** * Interaction Semantics *)\n\n(** NOTE: In the code, we call interaction semantics [CoreSemantics]. *)\n\n(** The [G] type parameter is the type of global environments, the type\n   [C] is the type of core states, and the type [E] is the type of\n   extension requests. *)\n\n(** [at_external] gives a way to determine when the sequential\n   execution is blocked on an extension call, and to extract the\n   data necessary to execute the call. *)\n\n(** [after_external] give a way to inject the extension call results\n   back into the sequential state so execution can continue. *)\n\n(** [initial_core] produces the core state corresponding to an entry\n   point of a module.  The arguments are the genv, a pointer to the\n   function to run, and the arguments for that function. *)\n\n(** [halted] indicates when a program state has reached a halted state,\n   and what it's exit code/return value is when it has reached such\n   a state. *)\n\n(** [corestep] is the fundamental small-step relation for the\n   sequential semantics. *)\n\n(** The remaining properties give basic sanity properties which constrain\n   the behavior of programs. *)\n(** -1 a state cannot be both blocked on an extension call and also step, *)\n(** -2 a state cannot both step and be halted, and *)\n(** -3 a state cannot both be halted and blocked on an external call. *)\n\nRecord CoreSemantics {G C M : Type} : Type :=\n  { initial_core : nat -> G -> val -> list val -> option C\n  ; at_external : C -> option (external_function * list val)\n  ; after_external : option val -> C -> option C\n  ; halted : C -> option val\n  ; corestep : G -> C -> M -> C -> M -> Prop\n\n  ; corestep_not_at_external:\n      forall ge m q m' q', corestep ge q m q' m' -> at_external q = None\n  ; corestep_not_halted:\n      forall ge m q m' q', corestep ge q m q' m' -> halted q = None\n  ; at_external_halted_excl:\n      forall q, at_external q = None \\/ halted q = None }.\n\nArguments CoreSemantics : clear implicits.\n\nInductive mem_step m m' : Prop :=\n    mem_step_storebytes: forall b ofs bytes,\n       Mem.storebytes m b ofs bytes = Some m' -> mem_step m m'\n  | mem_step_alloc: forall lo hi b',\n       Mem.alloc m lo hi = (m',b') -> mem_step m m'\n  | mem_step_freelist: forall l,\n       Mem.free_list m l = Some m' -> mem_step m m'\n  (*Some non-observable external calls are not a single alloc/free/store-step*)\n  | mem_step_trans: forall m'',\n       mem_step m m'' -> mem_step m'' m' -> mem_step m m'.\n\nLocal Notation \"a # b\" := (PMap.get b a) (at level 1).\nRecord perm_lesseq (m m': mem):= {\n  perm_le_Cur:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Cur) ((Mem.mem_access m)#b ofs Cur)\n; perm_le_Max:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Max) ((Mem.mem_access m)#b ofs Max)\n; perm_le_cont:\n    forall b ofs, Mem.perm m b ofs Cur Readable ->\n     ZMap.get ofs (Mem.mem_contents m') !! b= ZMap.get ofs (Mem.mem_contents m) !! b\n; perm_le_nb: Mem.nextblock m = Mem.nextblock m'\n}.\n\n\n(* Memory semantics are CoreSemantics that are specialized to CompCert memories\n   and evolve memory according to mem_step. Previous notion CoopCoreSem is deprecated,\n   but for now retained in file CoopCoreSem.v *)\nRecord MemSem {G C} :=\n  { csem :> @CoreSemantics G C mem\n\n  ; corestep_mem : forall g c m c' m' (CS: corestep csem g c m c' m'), mem_step m m'\n  (*later, we'll want to add the following constraint\n  ; corestep_incr_perm: forall g c m c' m' (CS: corestep csem g c m c' m')  m1 (PLE: perm_lesseq m m1),\n         exists m1', corestep csem g c m1 c' m1' /\\ perm_lesseq m' m1'*)\n  }.\n\nArguments MemSem : clear implicits.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19188052408007264}}
{"text": "From Bits Require Import spec.\n\nFrom Coq Require Import Vectors.Vector.\n\nFrom CryptolToCoq Require Import CryptolPrimitivesForSAWCore.\nFrom CryptolToCoq Require Import CryptolPrimitivesForSAWCoreExtra.\nFrom CryptolToCoq Require Import SAWCorePrelude.\nFrom CryptolToCoq Require Import SAWCorePrelude_proofs.\nFrom CryptolToCoq Require Import SAWCoreScaffolding.\nFrom CryptolToCoq Require Import SAWCoreVectorsAsCoqVectors.\n\nFrom Lift Require Import S2N.\n\nFrom Ornamental Require Import Ornaments.\n\nFrom S2N Require Import S2N.\n\nSet DEVOID search prove equivalence.\nSet DEVOID lift type.\n\nImport CryptolPrimitives.\n\nModule Handshake.\n\n  (** [cry_handshake] is the [handshake] type as it comes out of the translation\nfrom Cryptol to Coq.  The fields have been inlined into a nested tuple type.\n\nThis is what the original [handshake] type looked like:\n\ntype handshake = {handshake_type : [32]\n                 ,message_number : [32]\n                 }\n   *)\n  Definition handshake : Type := (seq 32 bool * seq 32 bool).\n\n  (** We can define more convenient types for [handshake] and [connection] in Coq.\nIdeally, we'd like the translation to generate those, but in its current state,\nit goes through an intermediate language that does not support records and\nrecord types.\n   *)\n  Record Handshake :=\n    MkHandshake\n      {\n        handshakeType : seq 32 bool;\n        messageNumber : seq 32 bool;\n      }.\n\n  Scheme Induction for Handshake Sort Prop.\n  Scheme Induction for Handshake Sort Type.\n  Scheme Induction for Handshake Sort Set.\n\n  Definition get_handshake_type (h : handshake) : seq 32 bool :=\n    fst h.\n\n  Definition get_message_number (h : handshake) : seq 32 bool :=\n    snd h.\n\nEnd Handshake.\n\nPreprocess Module Handshake\n  as HandshakePP\n       { opaque\n           PArithSeqBool\n           PCmpSeq\n           PCmpSeqBool\n           PLiteralSeqBool\n           ecAt\n           ecGt\n           ecLt\n           ecMinus\n           ecNotEq\n           ecNumber\n           ecPlus\n           handshakes_fn\n           natToNat\n           seq\n       }.\n\nLift HandshakePP.handshake\n     HandshakePP.Handshake\n  in HandshakePP.get_handshake_type\n  as getHandshakeType.\n\nLift HandshakePP.handshake\n     HandshakePP.Handshake\n  in HandshakePP.get_message_number\n  as getMessageNumber.\n\nConfigure Lift HandshakePP.handshake HandshakePP.Handshake\n          { opaque\n              PArithSeqBool\n              PCmpSeq\n              PCmpSeqBool\n              PLiteralSeqBool\n              ecAt\n              ecGt\n              ecLt\n              ecMinus\n              ecNotEq\n              ecNumber\n              ecPlus\n              handshakes_fn\n              natToNat\n              seq\n          }.\n\nLift HandshakePP.handshake\n     HandshakePP.Handshake\n  in S2N'.ACTIVE_MESSAGE\n  as ActiveMessage0.\n\nLift HandshakePP.handshake\n     HandshakePP.Handshake\n  in S2N'.valid_handshake\n  as validHandshake.\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/Lift/Handshake.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.19188051862944522}}
{"text": "From iris.heap_lang Require Import notation lang.\n\nDefinition addConditionally: val :=\n  rec: \"addConditionally\" \"loc\" \"delta\" \"condition\" :=\n    let: \"cur\" := !\"loc\" in\n    if: \"condition\" \"cur\"\n    then if: CAS \"loc\" \"cur\" (\"cur\" + \"delta\")\n         then #true\n         else \"addConditionally\" \"loc\" \"delta\" \"condition\"\n    else #false.\n\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Import proofmode.\n\nSection proof.\n\nContext `{heapG}.\n\nTheorem addConditionally_spec (pred: Z \u2192 bool) (\u2113: loc) (\u0394: Z) (condition: val):\n  \u22a2 (\u2200 (k: Z), {{{ True }}}\n                 condition #k\n               {{{ RET #(pred k); True }}}) \u2192\n    <<< \u2200 (k: Z), \u25b7 \u2113 \u21a6 #k >>>\n      addConditionally #\u2113 #\u0394 condition @ \u22a4\n    <<< if pred k then \u2113 \u21a6 #(k + \u0394) else \u2113 \u21a6 #k, RET #(pred k) >>>.\nProof.\n  iIntros \"#HCond\" (\u03a6) \"AU\". iL\u00f6b as \"IH\". wp_lam. wp_pures.\n  wp_bind (!_)%E. iMod \"AU\" as (k) \"[H\u2113 HClose]\".\n  wp_load.\n  destruct (pred k) eqn:E; wp_pures.\n  - iDestruct \"HClose\" as \"[HClose _]\".\n    iMod (\"HClose\" with \"H\u2113\") as \"AU\". iModIntro. wp_pures.\n    wp_apply (\"HCond\" with \"[$]\"). iIntros (_).\n    rewrite E. wp_pures.\n    wp_bind (CmpXchg _ _ _). iMod \"AU\" as (k') \"[H\u2113 HClose]\".\n    destruct (decide (k = k')) as [<-|HContra].\n    + wp_cmpxchg_suc. iDestruct \"HClose\" as \"[_ HClose]\".\n      iMod (\"HClose\" with \"[H\u2113]\") as \"H\u03a6\".\n      { rewrite E. iFrame. }\n      iModIntro. wp_pures. rewrite E. iAssumption.\n    + wp_cmpxchg_fail. iDestruct \"HClose\" as \"[HClose _]\".\n      iMod (\"HClose\" with \"H\u2113\") as \"AU\".\n      iModIntro. wp_pures. iApply (\"IH\" with \"AU\").\n  - iDestruct \"HClose\" as \"[_ HClose]\".\n    iMod (\"HClose\" with \"[H\u2113]\") as \"AU\"; first by iFrame.\n    iModIntro. wp_pures.\n    wp_apply (\"HCond\" with \"[$]\"). iIntros (_).\n    rewrite E. wp_pures.\n    iAssumption.\nQed.\n\nEnd proof.\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/addConditionally.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.19175670162740874}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Coq.Lists.SetoidList.\n\nRequire Import HJ.Tid.\nRequire Import HJ.Vars.\nRequire Import HJ.Phasers.Lang.\nRequire Import HJ.Phasers.PhaseDiff.\nRequire Import HJ.Phasers.LEDec.\n\nRequire Import HJ.Phasers.TransDiff.\nRequire Import HJ.Phasers.Typesystem.\n\nRequire Coq.FSets.FMapFacts.\n\nRequire HJ.Phasers.PhaseDiff.\nRequire HJ.Phasers.Rel.\nRequire HJ.Phasers.SubjectReduction.\nRequire HJ.Phasers.Typesystem.\nRequire HJ.Phasers.WellFormed.\n\nRequire Import Phasers.SubjectReduction.\n\nModule S := HJ.Phasers.Lang.\n\nOpen Scope Z.\n\nSection SIMPLE.\n\nLemma progress_unblocking_simple:\n  forall pm t i,\n  Valid pm ->\n  Op.Valid pm t i ->\n  i <> WAIT_ALL ->\n  exists m, Reduces pm t i m.\nProof.\n  intros.\n  exists (run (get_impl i) t pm).\n  apply reduces.\n  destruct i; simpl; inversion H0; auto.\n  contradiction H1.\n  trivial.\nQed.\n\nEnd SIMPLE.\n\nSection HAS_SMALLEST.\nVariable pm: phasermap.\nLet IsA t := In t pm.\n\nLet wtid_le (t1:tid) (t2:tid) := LE pm t1 t2.\n\nLet wtid_le_inv := LE_inv pm.\n\nLet wtid_le_trans:\n  forall t1 t2 t3,\n  wtid_le t1 t2 ->\n  wtid_le t2 t3 ->\n  wtid_le t1 t3.\nProof.\n  unfold wtid_le in *.\n  apply LE_trans.\nQed.\n\nLet wtid_has_smallest :=\n  Rel.has_smallest tid IsA wtid_le (LE_inv pm) (LE_dec pm)\n  (LE_refl pm) wtid_le_trans.\n\nDefinition Smallest (t:tid) (ts:list tid)  :=\n  List.In t ts /\\\n  forall t', List.In t' ts -> (~ LE pm t t' /\\ ~ LE pm t' t) \\/ LE pm t t'.\n\nLet has_smallest:\n  forall ts,\n  ts <> nil ->\n  Forall IsA ts ->\n  exists t,\n  Smallest t ts.\nProof.\n  intros.\n  destruct (wtid_has_smallest H H0) as (x, Hx).\n  unfold Rel.Smallest in *.\n  unfold Rel.Unrelated in *.\n  unfold wtid_le in *.\n  exists x.\n  auto.\nQed.\n\nLet tids := pm_tids pm.\n\nLet smallest_inv:\n  forall t,\n  Smallest t tids ->\n  List.In t tids.\nProof.\n  intros.\n  unfold Smallest in *.\n  intuition.\nQed.\n\nLet in_tids:\n  forall p ph t,\n  Map_PHID.MapsTo p ph pm ->\n  Map_TID.In t ph ->\n  List.In t tids.\nProof.\n  intros.\n  unfold tids.\n  rewrite pm_tids_spec.\n  eauto using in_def.\nQed.\n\nLet Smallest_to_LE :\n  forall t t' p ph,\n  Smallest t tids ->\n  Map_PHID.MapsTo p ph pm ->\n  Map_TID.In t ph ->\n  Map_TID.In t' ph ->\n  LE pm t t'.\nProof.\n  intros.\n  unfold Smallest in *.\n  destruct H as (Hin, H).\n  assert (Hx := H t'); clear H.\n  assert (Hin' : List.In t' tids) by eauto using in_tids.\n  apply Hx in Hin'; clear Hx.\n  destruct Hin' as [(?,?)|?].\n  - destruct (LE_total _ _ _ _ _ H0 H1 H2); repeat contradiction. (* absurd *)\n  - assumption.\nQed.\n\nLet diff := pm_diff pm.\n\nVariable check : Valid pm.\n\nLet diff_det : TransDiffFun diff.\nProof.\n  unfold Valid in *.\n  intuition.\nQed.\n\nLemma Smallest_to_WaitPhase :\n  forall t t' v v' p ph,\n  Smallest t tids ->\n  Map_PHID.MapsTo p ph pm ->\n  Map_TID.MapsTo t v ph ->\n  Map_TID.MapsTo t' v' ph ->\n  (wait_phase v <= wait_phase v') % nat.\nProof.\n  intros.\n  assert (Hin: Map_TID.In t ph) by eauto using Map_TID_Extra.mapsto_to_in.\n  assert (Hin': Map_TID.In t' ph) by eauto using Map_TID_Extra.mapsto_to_in.\n  assert (Hle: LE pm t t') by eauto using Smallest_to_LE.\n  remember ((Z.of_nat (wait_phase v)) - (Z.of_nat (wait_phase v'))) as z.\n  assert (Hdiff : ph_diff ph (t, t') z). {\n    subst.\n    auto using ph_diff_def.\n  }\n  assert (Hz: (z <= 0 \\/ -z <= 0) % Z) by omega.\n  destruct Hz.\n  - omega.\n  - subst.\n    remember (Z.of_nat (wait_phase v) - Z.of_nat (wait_phase v')) as z.\n    assert (Hd: pm_diff pm (t, t') z) by eauto using pm_diff_def.\n    assert ((z <= 0) % Z) by eauto using LE_to_pm_diff.\n    intuition.\nQed.\n\n\nOpen Scope nat.\n\n(**\n  A crucial precondition to the wait-all working is that all tasks must have\n  performed a signal prior to waiting.\n*)\n\n\nImport HJ.Phasers.WellFormed.\n\nImport Phasermap.\n\nVariable WF : WellFormed pm.\n\n  Section Unblocked.\n  Variable check_def:\n    forall t,\n    List.In t tids ->\n    Op.Valid pm t WAIT_ALL.\n\n  Theorem has_unblocked:\n    Nonempty pm ->\n    exists t,\n    List.In t tids /\\ exists m, Reduces pm t WAIT_ALL m.\n  Proof.\n    intros.\n    apply pm_tids_nonempty in H.\n    assert (Hisa : Forall IsA tids). {\n      apply Forall_forall.\n      intros.\n      unfold IsA, tids in *.\n      auto using pm_tids_spec_1.\n    }\n    assert (Hsmall := has_smallest H Hisa).\n    destruct Hsmall as (t, Hsmall).\n    exists t.\n    split; auto.\n    exists (Phasermap.wait_all t pm).\n    apply reduces.\n    simpl.\n    apply wait_all_pre.\n    intros.\n    assert (i := H1).\n    apply Map_TID_Extra.in_to_mapsto in H1.\n    destruct H1 as (v, mt).\n    assert (v_wf:Taskview.WellFormed v). {\n      inversion WF.\n      assert (Phaser.WellFormed ph) by eauto.\n      inversion H2.\n      eauto.\n    }\n    destruct (can_wait_so (mode v)). {\n      apply try_wait_pre_can_wait.\n      apply wait_pre_def with (v:=v); auto. {\n        inversion c;\n        symmetry in H2.\n        - apply Taskview.wait_pre_sw; auto.\n          apply Taskview.tv_well_formed_inv_sw in H2; auto.\n          destruct H2; auto.\n          assert (wait_phase v <> signal_phase v). {\n            assert (Hk : Op.Valid pm t WAIT_ALL) by eauto.\n            inversion Hk.\n            assert (wait_phase v < signal_phase v) by eauto.\n            intuition.\n          }\n          contradiction.\n        - apply Taskview.wait_pre_wo; auto.\n      }\n      assert (Hs := mt).\n      (* -- *)\n      apply phase_def.\n      intros x w; intros.\n      assert (wait_phase w < signal_phase w). {\n        assert (Hk : Op.Valid pm x WAIT_ALL). {\n          eauto using in_tids, Map_TID_Extra.mapsto_to_in.\n        }\n        inversion Hk.\n        eauto.\n      }\n      assert (wait_phase v <= wait_phase w). {\n        eauto using Smallest_to_WaitPhase.\n      }\n      auto with *.\n    }\n    eauto using try_wait_pre_so.\n  Qed.\n  End Unblocked.\n\n  Let both_cases:\n    forall l,\n    (forall x, List.In x l -> In x pm) ->\n    (exists x, List.In x l /\\ ~ Op.Valid pm x WAIT_ALL) \\/\n    (forall x, List.In x l -> Op.Valid pm x WAIT_ALL).\n  Proof.\n    induction l; intros. {\n      right.\n      intros.\n      inversion H0.\n    }\n    assert (i: In a pm) by eauto using in_eq.\n    destruct (Op.valid_dec pm a WAIT_ALL). {\n      assert (j: forall x, List.In x l -> In x pm) by eauto using in_cons.\n      apply IHl in j.\n      destruct j as [(?,(?,?))|?]. {\n        eauto using in_cons.\n      }\n      right.\n      intros.\n      destruct H1; subst; auto.\n    }\n    eauto using in_eq.\n  Qed.\n\n  Theorem progress:\n    Nonempty pm ->\n    exists t,\n    In t pm /\\\n    forall o,\n    (Op.Valid pm t o ->\n    exists m, Reduces pm t o m).\n  Proof.\n    intros.\n    edestruct (both_cases) as [(?,(?,?))|?]; eauto using pm_tids_spec_1. {\n      exists x.\n      split; auto using pm_tids_spec_1.\n      intros.\n      assert (o <> WAIT_ALL). {\n        unfold not; intros; subst.\n        contradiction.\n      }\n      eauto using progress_unblocking_simple.\n    }\n    destruct (has_unblocked) as (x,(?,?)); auto.\n    apply pm_tids_nonempty in H.\n    exists x.\n    split; auto using pm_tids_spec_1.\n    intros.\n    assert (Ho: o = WAIT_ALL \\/ o <> WAIT_ALL). {\n      destruct o; auto; right; unfold not; intros N; inversion N.\n    }\n    destruct Ho. {\n      subst.\n      auto.\n    }\n    auto using progress_unblocking_simple.\n  Qed.\n\nEnd HAS_SMALLEST.\n\nSection ProgressEmpty.\n  Lemma progress_empty:\n    forall t o pm l,\n    Trace.ReducesN pm l ->\n    pm_tids pm = nil ->\n    Op.Valid pm t o ->\n    exists pm', Reduces pm t o pm'.\n  Proof.\n    intros.\n    assert (O: o = WAIT_ALL \\/ o <> WAIT_ALL). {\n      destruct o; auto; right; unfold not; intros N; inversion N.\n    }\n    destruct O as [?|?]. {\n      exists (run (get_impl o) t pm).\n      apply reduces.\n      subst; simpl.\n      apply wait_all_pre.\n      intros.\n      assert (i: In t pm) by eauto using in_def.\n      apply pm_tids_spec_2 in i.\n      rewrite H0 in *.\n      inversion i.\n    }\n    eauto using progress_unblocking_simple, reduces_n_to_valid.\n  Qed.\n\nEnd ProgressEmpty.\n\nSection ProgressEx.\n  Corollary progress_ex:\n    forall pm l,\n    Trace.ReducesN pm l ->\n    Nonempty pm ->\n    exists t,\n    In t pm /\\\n    forall o,\n    (Op.Valid pm t o ->\n    exists m, Reduces pm t o m).\n  Proof.\n    intros.\n    eauto using progress, reduces_n_to_valid, WellFormed.Phasermap.well_formed_to_reduces_n.\n  Qed.\n\nEnd ProgressEx.\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/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.19175669794579434}}
{"text": "(* Continuation-Passing Style language for the CertiCoq project.\n *   Initial design, Andrew W. Appel, June 2014\n *)\nFrom Coq Require Import ZArith.ZArith Lists.List.\nFrom CertiCoq.Common Require Import AstCommon.\nFrom CertiCoq.LambdaANF Require Import List_util map_util.\nFrom compcert.lib Require Export  Maps.\nFrom CertiCoq.LambdaANF Require Export map_util.\nFrom MetaCoq.Template Require Import BasicAst. (* For identifier names *)\n\nImport ListNotations.\n\n(* We will use several maps from identifiers to types, values, etc.\n * For now we'll use Xavier Leroy's efficient polymorphic maps from\n * positive numbers to _. When the MMaps module of the Coq stdlib is\n * created, we'll use that. *)\n\nModule M := Maps.PTree.\n\n\n\nDefinition var      := M.elt. (* value variables *)\nDefinition fun_tag  := M.elt. (* discrimination tags for functions *)\nDefinition ind_tag  := M.elt. (* discrimination tags for inductive types *)\nDefinition ctor_tag := M.elt. (* discrimination tags for constructors *)\nDefinition prim     := M.elt. (* primitive operators *)\n\n\n(* Remark.  It sure would be nice if we could use abstraction here,\n   so that M was instantiated differently for vars, types, and tags,\n   such that [var] was not beta-eta equal to [type].  But then the\n   type of maps [M.t] would have to be abstract, and that in turn\n   would mean that Coq could not determine that [M.t(A)] is covariant\n   in A.  Which, in turn, would make impossible the inductive definition\n   of [val], below.\n *)\n\n\n(* To describe the [i]th field of a record, we use type BinNat,\n   that is, [N].  This has a more efficient representation than [nat],\n   which is a consideration for programs that process large\n   abstract syntax trees.\n *)\n\n\n(* Given a list of tagged variants, return the one with the matching tag. *)\nFixpoint findtag {A} (cl: list (ctor_tag * A)) (c: ctor_tag) : option A :=\n  match cl with\n  | (c',a)::cl' => if M.elt_eq c' c then Some a else findtag cl' c\n  | nil => None\n  end.\n\n(** * LambdaANF Expressions *)\n\n(* Expressions [exp] of the LambdaANF language. *)\nInductive exp : Type :=\n| Econstr: var -> ctor_tag -> list var -> exp -> exp\n| Ecase: var -> list (ctor_tag * exp) -> exp\n| Eproj: var -> ctor_tag -> N -> var -> exp -> exp\n| Eletapp: var -> var -> fun_tag -> list var -> exp -> exp\n| Efun: fundefs -> exp -> exp\n| Eapp: var -> fun_tag -> list var -> exp\n| Eprim_val : var -> primitive -> exp -> exp\n| Eprim: var -> prim -> list var -> exp -> exp (* where prim is id *)\n| Ehalt : var -> exp\nwith fundefs : Type :=\n| Fcons: var -> fun_tag -> list var -> exp -> fundefs -> fundefs\n| Fnil: fundefs.\n\n(* [Econstr x t c ys e] applies a data constructor with tag [c] to\n           a list of values denoted by variables [ys].   The resulting\n           value is bound to variable [x] of type [t], and then execution\n           continues with expression [e].  Static typing requires that\n           the typeinfo bound to [t] has a variant consistent with [c]\n           and the types of [ys].\n   [Ecase v cl] does case-discrimination on value [v], which\n          must be a [Vconstr t c vs] value. One of the elements of\n          [cl] must be the pair [(c,e)], where [e] a expression\n          that uses [v] (and makes necessary projections).\n   [Eproj v t n y e] projects the record value [y] by selecting\n          the [n]th element of the record.   This is bound to [v] of type [t]\n          and execution continues with [e].  Typechecking requires\n          that the type of [y] be a Tdata with a single variant, whose\n          data list has length at least n.\n   [Efun x f ft ys e] applies the function f to arguments ys and binds the result\n         to x in e.\n   [Efun fl e]  binds the set of mutually recursive functions [fl]\n          into the environment, and continues with [e].\n   [Eapp f ys]   applies the function [f] to arguments [ys]\n   [Eprim x t f ys e] applies primop [f] to arguments [ys]\n          and binds the result to [x] of type [t], continues with [e].\n          The primop [f] is a primitive operator, whose type is equivalent to\n          the CPS transform of [ts->t], where [ts] are the type of the [ys].\n\n   [Fdef f t ys e]   defines a function [f] of type [t] with parameters [ys]\n          and body [e].  We do not syntactically distinguish continuations\n          from other functions, as Andrew Kennedy does [Compiling with\n          Continuations, Continued, 2007].  Instead, we rely on the type\n          system to do it; see below.  This mechanism also permits\n          classifying functions into different calling conventions, even\n          if they have the same source-language type.\n*)\n\n(* Remark.  It is conventional in LambdaANF representations to guarantee\n   that no two binding occurrences bind the same variable-name.\n   However, neither the static (typing) semantics nor the dynamic\n   (small-step) semantics requires this.  Some of the transformation\n   (optimization, rewrite) algorithms may require it.\n*)\n\n\n(** Induction principles for exp anf fundefs *)\n\nLemma exp_ind' :\n  forall P : exp -> Type,\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var), P (Ecase v nil)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)) (c : ctor_tag) (e : exp),\n        P e -> P (Ecase v l) -> P (Ecase v ((c, e) :: l))) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall (f2 : fundefs) (e : exp), P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var)  (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    forall e : exp, P e.\nProof.\n  intros P H1 H2 H3 H4 H5 H6 H7 H8 H9 H10. fix exp_ind' 1.\n  destruct e; try (now clear exp_ind'; eauto).\n  - eapply H1. eapply exp_ind'; eauto.\n  - induction l as [ | [c e] xs IHxs].\n    + eapply H2.\n    + eapply H3. apply exp_ind'. eauto.\n  - eapply H4. eapply exp_ind'; eauto.\n  - eapply H5. eapply exp_ind'; eauto.\n  - eapply H6. eapply exp_ind'; eauto.\n  - eapply H8. eapply exp_ind'; eauto.\n  - eapply H9. eapply exp_ind'; eauto.\nQed.\n\n(** Mutual induction scheme for exp and fundefs *)\nLemma exp_mut :\n  forall (P : exp -> Type) (P0 : fundefs -> Type),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var), P (Ecase v nil)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)) (c : ctor_tag) (e : exp),\n        P e -> P (Ecase v l) -> P (Ecase v ((c, e) :: l))) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> forall e : exp, P e\nwith fundefs_mut :\n  forall (P : exp -> Type) (P0 : fundefs -> Type),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var), P (Ecase v nil)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)) (c : ctor_tag) (e : exp),\n        P e -> P (Ecase v l) -> P (Ecase v ((c, e) :: l))) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> forall f7 : fundefs, P0 f7.\nProof.\n  - intros P1 P2 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12.\n    destruct e; eauto.\n    + eapply H1. eapply exp_mut; eauto.\n    + induction l as [ | [c e] xs IHxs].\n      * eapply H2.\n      * eapply H3; eauto. eapply exp_mut; eauto.\n    + eapply H4. eapply exp_mut; eauto.\n    + eapply H5. eapply exp_mut; eauto.\n    + eapply H6. eapply fundefs_mut; eauto.\n      eapply exp_mut; eauto.\n    + eapply H8. eapply exp_mut; eauto.\n    + eapply H9. eapply exp_mut; eauto.\n  - intros P1 P2 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 defs.\n    destruct defs; eauto.\n    eapply H11. eapply exp_mut; eauto.\n    eapply fundefs_mut; eauto.\nQed.\n\n\nLemma exp_mut_alt :\n  forall (P : exp -> Prop) (P0 : fundefs -> Prop),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)),\n       Forall (fun x => P (snd x)) l -> P (Ecase v l)) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> forall e : exp, P e\nwith fundefs_mut_alt :\n  forall (P : exp -> Prop) (P0 : fundefs -> Prop),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)),\n        Forall (fun x => P (snd x)) l -> P (Ecase v l)) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> forall f7 : fundefs, P0 f7.\nProof.\n  - intros P1 P2 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11.\n    destruct e; eauto.\n    + eapply H1. eapply exp_mut_alt; eauto.\n    + eapply H2. induction l as [ | [c e] xs IHxs].\n      now constructor.\n      constructor; [| eassumption ]. eapply exp_mut_alt; eauto.\n    + eapply H3. eapply exp_mut_alt; eauto.\n    + eapply H4. eapply exp_mut_alt; eauto.\n    + eapply H5. eapply fundefs_mut_alt; eauto.\n      eapply exp_mut_alt; eauto.\n    + eapply H7. eapply exp_mut_alt; eauto.\n    + eapply H8. eapply exp_mut_alt; eauto.\n  - intros P1 P2 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 defs.\n    destruct defs; eauto.\n    eapply H10. eapply exp_mut_alt; eauto.\n    eapply fundefs_mut_alt; eauto.\nQed.\n\n(* to do proofs simultaneously. *)\nLemma exp_def_mutual_ind :\n  forall (P : exp -> Prop) (P0 : fundefs -> Prop),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var), P (Ecase v nil)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)) (c : ctor_tag) (e : exp),\n        P e -> P (Ecase v l) -> P (Ecase v ((c, e) :: l))) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->\n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> (forall e : exp, P e) /\\ (forall f : fundefs, P0 f).\nProof.\n  intros. split.\n  apply (exp_mut P P0); assumption.\n  apply (fundefs_mut P P0); assumption.\nQed.\n\nLemma exp_def_mutual_ind' :\n  forall (P : exp -> Prop) (P0 : fundefs -> Prop),\n    (forall (v : var) (t : ctor_tag) (l : list var) (e : exp),\n        P e -> P (Econstr v t l e)) ->\n    (forall (v : var) (l : list (ctor_tag * exp)),\n        Forall (fun x => P (snd x)) l -> P (Ecase v l)) ->\n    (forall (v : var) (t : ctor_tag) (n : N) (v0 : var) (e : exp),\n        P e -> P (Eproj v t n v0 e)) ->\n    (forall (x f : var) (ft : fun_tag) (ys : list var) (e : exp),\n        P e -> P (Eletapp x f ft ys e)) ->    \n    (forall f2 : fundefs, P0 f2 -> forall e : exp, P e -> P (Efun f2 e)) ->\n    (forall (v : var) (t : fun_tag) (l : list var), P (Eapp v t l)) ->\n    (forall v p e, P e -> P (Eprim_val v p e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp),\n        P e -> P (Eprim v p l e)) ->\n    (forall (v : var), P (Ehalt v)) ->\n    (forall (v : var) (t : fun_tag) (l : list var) (e : exp),\n        P e -> forall f5 : fundefs, P0 f5 -> P0 (Fcons v t l e f5)) ->\n    P0 Fnil -> (forall e : exp, P e) /\\ (forall f : fundefs, P0 f).\nProof.\n  intros. split.\n  apply (exp_mut_alt P P0); assumption.\n  apply (fundefs_mut_alt P P0); assumption.\nQed.\n\n\n(** name the induction hypotheses only *)\nLtac exp_defs_induction IH1 IHl IH2 :=\n  apply exp_def_mutual_ind;\n  [ intros ? ? ? ? IH1\n  | intros ?\n  | intros ? ? ? ? IH1 IHl\n  | intros ? ? ? ? ? IH1\n  | intros ? ? ? ? ? IH1\n  | intros ? IH2 ? IH1\n  | intros ? ? ?\n  | intros ? ? ? IH1\n  | intros ? ? ? ? IH1\n  | intros ?\n  | intros ? ? ? ? IH1 ? IH2\n  | ].\n\n(** * CPS Values *)\n\nInductive val : Type :=\n| Vconstr : ctor_tag -> list val -> val\n| Vfun : M.t val -> fundefs -> var -> val\n(* [Vfun env fds f]\n     where env is the environment at the function binding site\n     fds is the list of mutually recursive functions including f *)\n| Vprim : primitive -> val\n| Vint : Z -> val.\n\n(** Induction principle for values. *)\nLemma val_ind' :\n  forall P : val -> Prop,\n    (forall (t : ctor_tag), P (Vconstr t nil)) ->\n    (forall (t : ctor_tag) (v : val) (l : list val),\n        P v -> P (Vconstr t l) -> P (Vconstr t (v :: l))) ->\n    (forall (t : M.t val) (f0 : fundefs) (v : var), P (Vfun t f0 v)) ->\n    (forall p, P (Vprim p)) ->\n    (forall z : Z, P (Vint z)) ->\n    forall v : val, P v.\nProof.\n  intros P H1 H2 H3 H4 H5.\n  fix val_ind' 1.\n  destruct v; try (now clear val_ind'; eauto).\n  - induction l as [ | x xs IHxs].\n    eapply H1. eapply H2. apply val_ind'. eauto.\nQed.\n\nFixpoint def_funs (fl0 fl: fundefs) (rho0 rho: M.t val) : M.t val :=\n  match fl with\n  | Fcons f t xs e fl' => M.set f (Vfun rho0 fl0 f) (def_funs fl0 fl' rho0 rho)\n  | Fnil => rho\n  end.\n\nFixpoint find_def (f: var) (fl:  fundefs) :=\n  match fl with\n  | Fcons f' t ys e fl' => if M.elt_eq f f' then Some (t,ys,e)\n                           else find_def f fl'\n  | Fnil => None\n  end.\n\n(** * Information associated with identifiers **)\n\n(* The info of a constructor. *)\nRecord ctor_ty_info : Set :=\n  Build_ctor_ty_info\n    { ctor_name     : name    (* the name of the constructor *)\n    ; ctor_ind_name : name    (* the name of its inductive type *)\n    ; ctor_ind_tag  : ind_tag (* ind_tag of corresponding inductive type *)\n    ; ctor_arity    : N       (* the arity of the constructor *)\n    ; ctor_ordinal  : N       (* the [ctor_tag]s ordinal in inductive defn starting at zero *)\n    }.\n\n(* The info of an inductive type is list of the ctags of its constructors *)\nDefinition ind_ty_info : Set := list (ctor_tag * N).\n\nDefinition unknown_ctor_ty_info : ctor_ty_info :=\n  {| ctor_name     := nAnon\n   ; ctor_ind_name := nAnon\n   ; ctor_ind_tag  := 1%positive\n   ; ctor_arity    := 0%N\n   ; ctor_ordinal  := 0%N\n  |}.\n\nDefinition unknown_ind_ty_info : ind_ty_info := nil.\n\n(* An constructor environment maps [ctor_tag]s to their information *)\nDefinition ctor_env : Set := M.tree ctor_ty_info.\n\n(* An inductive type environment maps [ind_tag]s to their constructors with their arities *)\nDefinition ind_env : Set := M.tree ind_ty_info.\n\n(* Every calling convention requires knowing\n   how many arguments in which slots of the arg array *)\nDefinition fun_ty_info : Set := N * list N.\n\nDefinition fun_env : Set := M.tree fun_ty_info.\n\n(** Register the tag used for closures **)\nDefinition add_closure_tag (c i : positive) (cenv : ctor_env) : ctor_env :=\n  let info := {| ctor_name     := nAnon\n               ; ctor_ind_name := nAnon\n               ; ctor_ind_tag  := i\n               ; ctor_arity    := 2%N\n               ; ctor_ordinal  := 0%N\n              |}\n  in M.set c info cenv.\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/cps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.19175669058256564}}
{"text": "From refinedc.typing Require Import typing.\nFrom refinedc.project.learning.src.circuit Require Import generated_code.\nFrom refinedc.project.learning.src.circuit Require Import generated_spec.\nSet Default Proof Using \"Type\".\n\n(* Generated from [src/circuit.c]. *)\nSection proof_set_one.\n  Context `{!typeG \u03a3} `{!globalG \u03a3}.\n\n  (* Typing proof for [set_one]. *)\n  Lemma type_set_one :\n    \u22a2 typed_function impl_set_one type_of_set_one.\n  Proof.\n    Open Scope printing_sugar.\n    start_function \"set_one\" ([[[a b] x] p]) => arg_c arg_v.\n    prepare_parameters (a b x p).\n    split_blocks ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)) ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)).\n    - repeat liRStep; liShow.\n      all: print_typesystem_goal \"set_one\" \"#0\".\n    Unshelve. all: li_unshelve_sidecond; sidecond_hook; prepare_sideconditions; normalize_and_simpl_goal; try solve_goal; unsolved_sidecond_hook.\n    all: print_sidecondition_goal \"set_one\".\n    Unshelve. all: try done; try apply: inhabitant; print_remaining_shelved_goal \"set_one\".\n  Qed.\nEnd proof_set_one.\n", "meta": {"author": "afifit", "repo": "circuit_verif", "sha": "5427a1223c5ea7e4a52f909489c45f8e51c4be54", "save_path": "github-repos/coq/afifit-circuit_verif", "path": "github-repos/coq/afifit-circuit_verif/circuit_verif-5427a1223c5ea7e4a52f909489c45f8e51c4be54/src/proofs/circuit/generated_proof_set_one.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.1917196329314851}}
{"text": "Require Import Category.Lib.\nRequire Import Category.Instance.Lambda.Ltac.\nRequire Import Category.Instance.Lambda.Ty.\nRequire Import Category.Instance.Lambda.Exp.\nRequire Import Category.Instance.Lambda.Value.\nRequire Import Category.Instance.Lambda.Ren.\nRequire Import Category.Instance.Lambda.Sub.\nRequire Import Category.Instance.Lambda.Log.\nRequire Import Category.Instance.Lambda.Sem.\nRequire Import Category.Instance.Lambda.Multi.\nRequire Import Category.Instance.Lambda.Sound.\nRequire Import Category.Instance.Lambda.Step.\n\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\nGeneralizable All Variables.\n\nSection Norm.\n\n#[local] Hint Constructors ValueP Step : core.\n\n#[local] Hint Extern 7 (_ ---> _) => repeat econstructor : core.\n\nDefinition normalizing `(R : crelation X) : Type :=\n  \u2200 t, \u2203 t', multi R t t' \u2227 normal_form R t'.\n\nDefinition halts {\u0393 \u03c4} (e : Exp \u0393 \u03c4) : Type :=\n  \u2203 e', e --->* e' \u2227 ValueP e'.\n\nNotation \" e '\u21d3' \" := (halts e) (at level 11).\n\nDefinition normal_form_of {\u0393 \u03c4} (e e' : Exp \u0393 \u03c4) : Type :=\n  (e --->* e' \u2227 normal_form Step e').\n\nLtac normality :=\n  exfalso;\n  lazymatch goal with\n    | [ H1 : ValueP ?X, H2 : ?X ---> ?Y |- False ] =>\n        apply value_is_nf in H1; destruct H1;\n        now exists Y\n    | [ H1 : normal_form ?R ?X, H2 : ?R ?X ?Y |- False ] =>\n        exfalso; now apply (H1 Y)\n  end.\n\nLtac invert_step :=\n  try lazymatch goal with\n  | [ H : _ ---> _ |- _ ] => now inv H\n  end;\n  try solve [ f_equal; intuition eauto | normality ].\n\nLemma value_halts {\u0393 \u03c4} (v : Exp \u0393 \u03c4) : ValueP v \u2192 halts v.\nProof.\n  intros X.\n  unfold halts.\n  now induction X; eexists; repeat constructor.\nQed.\n\nTheorem normal_forms_unique \u0393 \u03c4 :\n  deterministic (normal_form_of (\u0393:=\u0393) (\u03c4:=\u03c4)).\nProof.\n  unfold deterministic, normal_form_of.\n  intros x y1 y2 P1 P2.\n  destruct P1 as [P11 P12].\n  destruct P2 as [P21 P22].\n  generalize dependent y2.\n  induction P11; intros.\n  - inversion P21; auto.\n    now einduction P12; eauto.\n  - apply IHP11; auto.\n    inv P21.\n    + now edestruct P22; eauto.\n    + assert (y = y0) by now apply Step_deterministic with x.\n      now subst.\nQed.\n\nLemma step_preserves_halting {\u0393 \u03c4} (e e' : Exp \u0393 \u03c4) :\n  (e ---> e') \u2192 (halts e \u2194 halts e').\nProof.\n  intros.\n  unfold halts.\n  split.\n  - intros [e'' [H1 H2]].\n    + destruct H1.\n      * apply value_is_nf in H2.\n        now edestruct H2; eauto.\n      * rewrite (Step_deterministic _ _ _ _ _ H s).\n        now intuition eauto.\n  - intros [e'0 [H1 H2]].\n    + exists e'0.\n      split; auto.\n      now eapply multi_step; eauto.\nQed.\n\nDefinition SN {\u0393 \u03c4} : \u0393 \u22a2 \u03c4 \u2192 Type := ExpP (@halts \u0393).\nArguments SN {\u0393 \u03c4} _ /.\n\nDefinition SN_Sub {\u0393 \u0393'} : Sub \u0393' \u0393 \u2192 Type := SubP (@halts \u0393').\nArguments SN_Sub {\u0393 \u0393'} /.\n\nDefinition SN_halts {\u0393 \u03c4} {e : \u0393 \u22a2 \u03c4} : SN e \u2192 halts e := ExpP_P _.\n\n#[local] Transparent ExpP.\n\nLemma step_preserves_SN {\u0393 \u03c4} {e e' : \u0393 \u22a2 \u03c4} :\n  (e ---> e') \u2192 SN e \u2192 SN e'.\nProof.\n  intros.\n  induction \u03c4; simpl in *;\n  pose proof H as H2;\n  apply step_preserves_halting in H2;\n  firstorder.\nQed.\n\nLemma multistep_preserves_SN {\u0393 \u03c4} {e e' : \u0393 \u22a2 \u03c4} :\n  (e --->* e') \u2192 SN e \u2192 SN e'.\nProof.\n  intros.\n  induction X; auto.\n  apply IHX.\n  now eapply step_preserves_SN; eauto.\nQed.\n\nLemma step_preserves_SN' {\u0393 \u03c4} {e e' : \u0393 \u22a2 \u03c4} :\n  (e ---> e') \u2192 SN e' \u2192 SN e.\nProof.\n  intros.\n  induction \u03c4; simpl in *;\n  pose proof H as H2;\n  apply step_preserves_halting in H2;\n  firstorder.\nQed.\n\nLemma multistep_preserves_SN' {\u0393 \u03c4} {e e' : \u0393 \u22a2 \u03c4} :\n  (e --->* e') \u2192 SN e' \u2192 SN e.\nProof.\n  intros.\n  induction X; auto.\n  now eapply step_preserves_SN'; eauto.\nQed.\n\nLemma SubExp_SN {\u0393 \u0393'} (env : Sub \u0393' \u0393) {\u03c4} (e : Exp \u0393 \u03c4) :\n  SN_Sub env \u2192\n  SN (SubExp env e).\nProof.\n  generalize dependent env.\n  induction e; intros; simpl.\n  - now eexists; repeat constructor.\n  - split.\n    + destruct (SN_halts (IHe1 env X)) as [v1 [P1 Q1]].\n      destruct (SN_halts (IHe2 env X)) as [v2 [P2 Q2]].\n      exists (Pair v1 v2).\n      split.\n      * now apply multistep_Pair.\n      * now repeat constructor.\n    + split.\n      * destruct (SN_halts (IHe1 env X)) as [v1 [P1 Q1]].\n        destruct (SN_halts (IHe2 env X)) as [v2 [P2 Q2]].\n        apply (multistep_preserves_SN' (e':=v1)); auto.\n        ** rewrite (multistep_Fst1 (p':=Pair v1 v2)).\n           *** now apply multi_R; eauto.\n           *** erewrite multistep_Pair1; eauto.\n               erewrite multistep_Pair2; eauto.\n               now apply multi_refl.\n        ** apply (multistep_preserves_SN (e:=SubExp env e1));\n           now intuition.\n      * destruct (SN_halts (IHe1 env X)) as [v1 [P1 Q1]].\n        destruct (SN_halts (IHe2 env X)) as [v2 [P2 Q2]].\n        apply (multistep_preserves_SN' (e':=v2)); auto.\n        ** rewrite (multistep_Snd1 (p':=Pair v1 v2)).\n           *** now apply multi_R; eauto.\n           *** erewrite multistep_Pair1; eauto.\n               erewrite multistep_Pair2; eauto.\n               now apply multi_refl.\n        ** apply (multistep_preserves_SN (e:=SubExp env e2));\n           now intuition.\n  - now apply IHe.\n  - now apply IHe.\n  - induction env.\n    + now inv v.\n    + dependent elimination X.\n      now dependent elimination v; simpl in *; simp SubVar.\n  - split.\n    + now eexists; repeat constructor.\n    + intros.\n      destruct (SN_halts X0) as [v [P Q]].\n      apply (multistep_preserves_SN' (e':=SubExp (Push v env) e)); auto.\n      * eapply multi_trans; eauto.\n        ** now eapply multistep_AppR; eauto.\n        ** apply multi_R; auto.\n           now rewrite SubExp_Push; eauto 6.\n      * apply IHe.\n        constructor; auto.\n        now eapply multistep_preserves_SN; eauto.\n  - now apply IHe1, IHe2.\nQed.\n\nTheorem Exp_SN {\u03c4} (e : Exp nil \u03c4) : SN e.\nProof.\n  intros.\n  replace e with (SubExp (\u0393:=nil) NoSub e).\n  - apply SubExp_SN.\n    now constructor.\n  - now rewrite NoSub_idSub, SubExp_idSub.\nQed.\n\nCorollary strong_normalization {\u03c4} (e : Exp nil \u03c4) : e \u21d3.\nProof.\n  pose proof (Exp_SN e) as X.\n  now apply SN_halts.\nQed.\n\nEnd Norm.\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/Lambda/Norm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1917196308636039}}
{"text": "(** * Similar states after first rising edge  *)\n\nRequire Import sitpn.SitpnLib.\n\nRequire Import hvhdl.HVhdlCoreLib.\nRequire Import hvhdl.HVhdlElaborationLib.\nRequire Import hvhdl.HVhdlSimulationLib.\nRequire Import hvhdl.HVhdlHilecopLib.\n\nRequire Import transformation.Sitpn2HVhdl.\n\nRequire Import soundness.SemanticPreservationDefs.\n\nLemma first_rising_edge_full :\n  forall sitpn b d \u03b3 E__c E__p \u0394 \u03c3__e \u03c30 \u03c4 \u03c3__r \u03c3,\n\n    (* sitpn translates into (d, \u03b3). *)\n    sitpn2hvhdl sitpn b = (inl (d, \u03b3)) ->\n\n    (* Environments are similar. *)\n    SimEnv sitpn \u03b3 E__c E__p ->\n    \n    (* [\u0394, \u03c3__e] are the results of the elaboration of [d]. *)\n    EDesign hdstore (NatMap.empty value) d \u0394 \u03c3__e ->\n\n    (* [\u03c30] is the initial state of [d]. *)\n    Init hdstore \u0394 \u03c3__e (AbstractSyntax.beh d) \u03c30 ->\n\n    (* From [\u03c30] to [\u03c3] after [\u2191]. *)\n    VConc hdstore \u0394 (inj \u03c30 (E__p \u03c4)) rising (AbstractSyntax.beh d) \u03c3__r ->\n    Stabilize hdstore \u0394 \u03c3__r (AbstractSyntax.beh d) \u03c3 ->\n    \n    (* States [s] and [\u03c3] are similar. *)\n    FullSimStateAfterRE sitpn \u03b3 E__c \u03c4 (s0 sitpn) \u03c3.\nAdmitted.\n\n(* Tries to apply the [first_rising_edge_full] lemma when the goal is of the form\n   [SimStateAfterFE _ _ _ _] or [_ \u22a2 _ \u223c _]. *)\n#[export] Hint Resolve first_rising_edge_full : hilecop.\n#[export] Hint Extern 1 ( _ \u22a2 _ \u223c _ ) => eapply first_rising_edge_full; eauto : hilecop.\n\nLemma first_rising_edge :\n  forall sitpn b d \u03b3 E__c E__p \u0394 \u03c3__e \u03c30 \u03c4 \u03c3__r \u03c3,\n\n    (* sitpn translates into (d, \u03b3). *)\n    sitpn2hvhdl sitpn b = (inl (d, \u03b3)) ->\n\n    (* Environments are similar. *)\n    SimEnv sitpn \u03b3 E__c E__p ->\n    \n    (* [\u0394, \u03c3__e] are the results of the elaboration of [d]. *)\n    EDesign hdstore (NatMap.empty value) d \u0394 \u03c3__e ->\n\n    (* [\u03c30] is the initial state of [d]. *)\n    Init hdstore \u0394 \u03c3__e (AbstractSyntax.beh d) \u03c30 ->\n\n    (* From [\u03c30] to [\u03c3] after [\u2191]. *)\n    VConc hdstore \u0394 (inj \u03c30 (E__p \u03c4)) rising (AbstractSyntax.beh d) \u03c3__r ->\n    Stabilize hdstore \u0394 \u03c3__r (AbstractSyntax.beh d) \u03c3 ->\n    \n    (* States [s] and [\u03c3] are similar. *)\n    SimStateAfterRE sitpn \u03b3 (s0 sitpn) \u03c3.\nProof. eapply first_rising_edge_full; eauto. Qed.\n\n(* Tries to apply the [first_rising_edge] lemma when the goal is of the form\n   [SimStateAfterFE _ _ _ _] or [_ \u22a2 _ \u223c _]. *)\n#[export] Hint Resolve first_rising_edge : hilecop.\n#[export] Hint Extern 1 ( _ \u22a2 _ \u223c _ ) => eapply first_rising_edge; eauto : hilecop.\n\n(** States that, for all SITPN [sitpn] passed as input to the HM2T and\n    resulting design [d], if [\u03c30] is the initial state of [d] then a\n    rising edge phase can be computed from [\u03c30], and thus ends in\n    state [\u03c3], such that [\u03c3] is similar to the initial state [s0] of\n    [sitpn]. *)\n\nLemma first_rising_edge_lock_step_full :\n  forall sitpn b d \u03b3 E__c E__p \u0394 \u03c3__e \u03c30,\n\n    (* sitpn translates into (d, \u03b3). *)\n    sitpn2hvhdl sitpn b = (inl (d, \u03b3)) ->\n\n    (* Environments are similar. *)\n    SimEnv sitpn \u03b3 E__c E__p ->\n    \n    (* [\u0394, \u03c3__e] are the results of the elaboration of [d]. *)\n    EDesign hdstore (NatMap.empty value) d \u0394 \u03c3__e ->\n\n    (* [\u03c30] is the initial state of [d]. *)\n    Init hdstore \u0394 \u03c3__e (AbstractSyntax.beh d) \u03c30 ->\n\n    forall \u03c4,\n    exists \u03c3__r \u03c3,\n      (* From [\u03c30] to [\u03c3] after [\u2191]. *)\n      VConc hdstore \u0394 (inj \u03c30 (E__p \u03c4)) rising (AbstractSyntax.beh d) \u03c3__r \n      /\\ Stabilize hdstore \u0394 \u03c3__r (AbstractSyntax.beh d) \u03c3 \n                   \n      (* States [s] and [\u03c3] are \"fully\" similar. *)\n      /\\ FullSimStateAfterRE sitpn \u03b3 E__c \u03c4 (s0 sitpn) \u03c3.\nAdmitted.\n\n#[export] Hint Resolve first_rising_edge_lock_step_full : hilecop.\n\nLemma first_rising_edge_lock_step :\n  forall sitpn b d \u03b3 E__c E__p \u0394 \u03c3__e \u03c30,\n\n    (* sitpn translates into (d, \u03b3). *)\n    sitpn2hvhdl sitpn b = (inl (d, \u03b3)) ->\n\n    (* Environments are similar. *)\n    SimEnv sitpn \u03b3 E__c E__p ->\n    \n    (* [\u0394, \u03c3__e] are the results of the elaboration of [d]. *)\n    EDesign hdstore (NatMap.empty value) d \u0394 \u03c3__e ->\n\n    (* [\u03c30] is the initial state of [d]. *)\n    Init hdstore \u0394 \u03c3__e (AbstractSyntax.beh d) \u03c30 ->\n    \n    forall \u03c4,\n    exists \u03c3__r \u03c3,\n      (* From [\u03c30] to [\u03c3] after [\u2191]. *)\n      VConc hdstore \u0394 (inj \u03c30 (E__p \u03c4)) rising (AbstractSyntax.beh d) \u03c3__r \n      /\\ Stabilize hdstore \u0394 \u03c3__r (AbstractSyntax.beh d) \u03c3 \n                   \n      (* States [s] and [\u03c3] are similar. *)\n      /\\ SimStateAfterRE sitpn \u03b3 (s0 sitpn) \u03c3.\nProof.\n  intros until \u03c4. \n  edestruct first_rising_edge_lock_step_full as (\u03c3__r, (\u03c3, (HVConc, (Hstab, Hfsim)))); eauto.\n  exists \u03c3__r, \u03c3; eauto with hilecop. \nQed.\n\n#[export] Hint Resolve first_rising_edge_lock_step : hilecop.\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/behavior-preservation/FirstRisingEdge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.1917196308636039}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Bedrock.Word\n        Coq.ZArith.ZArith\n        Coq.NArith.NArith\n        Coq.Arith.Arith\n        Coq.Numbers.Natural.Peano.NPeano\n        Coq.Logic.Eqdep_dec\n        Fiat.Common.BoundedLookup\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.BaseFormats\n        Fiat.Narcissus.BinLib.Core\n        Fiat.Narcissus.BinLib.AlignedByteString.\n\nSection AlignedEncodeM.\n\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n  Context {S : Type}.\n\n  Definition AlignedEncodeM\n             (n : nat) :=\n    ByteBuffer.t n (* Vector of bytes that is being written to *)\n    -> nat          (* The current index *)\n    -> S\n    -> CacheFormat  (* The current environment *)\n    -> Hopefully (ByteBuffer.t n * nat * CacheFormat) (* Error monad + value + updated index + updated cache *).\n\n  Definition AppendAlignedEncodeM\n             {n : nat}\n             (a : AlignedEncodeM n)\n             (b : AlignedEncodeM n)\n    : AlignedEncodeM n :=\n    fun v idx s c => (HBind a v idx s c  as a' With (b (fst (fst a')) (snd (fst a')) s (snd a'))).\n\n  Definition ReturnAlignedEncodeM\n             {numBytes : nat}\n    : AlignedEncodeM numBytes :=\n    fun v idx s c => Ok (v, idx, c).\n\n  Definition AlignedEncodeMEquiv\n             {n}\n             (a1 a2 : AlignedEncodeM n) : Prop :=\n    forall v idx s c, a1 v idx s c = a2 v idx s c.\n\n  Lemma AlignedEncodeMEquiv_refl  {n}:\n    forall (a : AlignedEncodeM n),\n      AlignedEncodeMEquiv a a.\n  Proof.\n    unfold AlignedEncodeMEquiv; intros; reflexivity.\n  Qed.\n\n  Lemma AlignedEncodeMEquiv_sym  {n}:\n    forall (a1 a2 : AlignedEncodeM n),\n      AlignedEncodeMEquiv a1 a2 -> AlignedEncodeMEquiv a2 a1.\n  Proof.\n    unfold AlignedEncodeMEquiv; intros; congruence.\n  Qed.\n\n  Lemma AlignedEncodeMEquiv_trans  {n}:\n    forall (a1 a2 a3 : AlignedEncodeM n),\n      AlignedEncodeMEquiv a1 a2 ->\n      AlignedEncodeMEquiv a2 a3 ->\n      AlignedEncodeMEquiv a1 a3.\n  Proof.\n    unfold AlignedEncodeMEquiv; intros; congruence.\n  Qed.\n\n  Global Instance PreOrder_AlignedEncodeMEquiv  {n} :\n    PreOrder (@AlignedEncodeMEquiv n) :=\n    {| PreOrder_Reflexive := AlignedEncodeMEquiv_refl;\n       PreOrder_Transitive := AlignedEncodeMEquiv_trans|}.\n\n  Lemma AppendAlignedEncodeM_assoc {n}:\n    forall (a : AlignedEncodeM n)\n           (f : AlignedEncodeM n)\n           (g : AlignedEncodeM n),\n      AlignedEncodeMEquiv (AppendAlignedEncodeM (AppendAlignedEncodeM a f) g)\n                          (AppendAlignedEncodeM a (AppendAlignedEncodeM f g)).\n  Proof.\n    unfold AppendAlignedEncodeM, AlignedEncodeMEquiv; simpl; intros.\n    destruct (a v idx s c); simpl; eauto.\n  Qed.\n\n  Lemma ReturnAlignedEncodeM_LeftUnit {n}:\n    forall (f : AlignedEncodeM n),\n      AlignedEncodeMEquiv (AppendAlignedEncodeM (@ReturnAlignedEncodeM _) f)\n                          f.\n  Proof.\n    intros; reflexivity.\n  Qed.\n\n  Lemma ReturnAlignedEncodeM_RightUnit {n}:\n    forall (f : AlignedEncodeM n),\n      AlignedEncodeMEquiv (AppendAlignedEncodeM f ReturnAlignedEncodeM) f.\n  Proof.\n    unfold ReturnAlignedEncodeM, AppendAlignedEncodeM, AlignedEncodeMEquiv; simpl; intros.\n    destruct (f v idx s c) as [ [ [? ?] ?] | ] ; simpl; reflexivity.\n  Qed.\n  Definition ThrowAlignedEncodeM\n             {n : nat}\n    : AlignedEncodeM n:=\n    fun _ _ _ _ => OtherErrorInfo \"Alignment error (ThrowAligned)\".\n\n  Fixpoint set_nth'\n           {n : nat}\n           (v : ByteBuffer.t n)\n           (m : nat)\n           (a : char)\n    : ByteBuffer.t n :=\n    match m, v with\n    | 0,  Vector.cons _ _ v' => Vector.cons _ a _ v'\n    | Datatypes.S m', Vector.cons a' _ v' => Vector.cons _ a' _ (set_nth' v' m' a)\n    | _, _ => @Vector.nil _\n    end.\n\n  (* Equivalence Criteria:\n     A bit-aligned encoder and byte-aligned encoder are equivalent when\n\\backsimeq     - the byte aligned encoder fails when the bit aligned encoder would write past\n       the end of the bytestring\n     - encodes the same bit sequence values as the bit-aligned encoder (and who can\n       say about the rest of the .\n   *)\n\n  Definition EncodeMEquivAlignedEncodeM\n             (f : EncodeM S ByteString)\n             (f' : forall numBytes, AlignedEncodeM numBytes)\n    := forall env s idx,\n      (forall t env',\n          f s env = Ok (t, env')\n          -> padding t = 0 ->\n          forall (v1 : Vector.t char idx) v m v2,\n          exists v',\n            f' _ (Vector.append v1 (Vector.append (n := numBytes t) (p := m)\n                                                  v v2)) idx s env = Ok (v', idx + numBytes t, env') /\\\n            ByteString_enqueue_ByteString (build_aligned_ByteString v1)\n                                          (ByteString_enqueue_ByteString t (build_aligned_ByteString v2))\n            = build_aligned_ByteString v')%nat\n      /\\ (forall t env' numBytes' v,\n             f s env = Ok (t, env')\n             -> 8 + 8 * numBytes' <= length_ByteString t + (8 * idx)\n          -> is_error (f' numBytes' v idx s env))%nat\n      /\\ (forall t env' numBytes' v,\n             f s env = Ok (t, env')\n             -> padding t <> 0 -> is_error (f' numBytes' v idx s env))%nat\n      /\\ (forall numBytes' v, is_error (f s env) -> is_error(f' numBytes' v idx s env)).\n\n  Lemma EncodeMEquivAlignedEncodeM_trans :\n    forall bit_decoder1 byte_decoder1 bit_decoder2 byte_decoder2,\n      EncodeMEquivAlignedEncodeM bit_decoder1 byte_decoder1\n      -> (forall s env, bit_decoder1 s env  = bit_decoder2 s env)\n      -> (forall n, AlignedEncodeMEquiv (byte_decoder1 n) (byte_decoder2 n))\n      -> EncodeMEquivAlignedEncodeM bit_decoder2 byte_decoder2.\n  Proof.\n    unfold EncodeMEquivAlignedEncodeM; intros; intuition.\n    - revert v1 v v2 H2; rewrite <- ?H0, <- ?H1; intros.\n      destruct (proj1 (H _ _ _) _ _ H2 H3 v1 v m v2); intuition.\n      eexists; intuition eauto.\n      rewrite <- H1; eauto.\n    - rewrite <- ?H0, <- ?H1; intros.\n      eapply (proj1 (proj2 (H _ _ _))); eauto; rewrite H0; eauto.\n    - rewrite <- ?H0, <- ?H1; intros.\n      eapply (proj1 (proj2 (proj2 (H _ _ _)))); rewrite ?H0; eauto.\n    - rewrite <- ?H0 in H2.\n      rewrite <- H1; eapply H; eauto.\n  Qed.\n\n  Local Arguments mult : simpl never.\n\n  Definition AlignedEncode_Nil\n             numBytes\n    : AlignedEncodeM numBytes :=\n    (fun v idx s env => (if idx <? Datatypes.S numBytes\n                         then\n                           @ReturnAlignedEncodeM _ v idx s env\n                         else\n                           Error (LabelError \"Alignment error, reading nill (AlignedEncode_Nil)\" EndOfBuffer))).\n\n  Lemma Return_EncodeMEquivAlignedEncodeM\n    : EncodeMEquivAlignedEncodeM\n        (fun (s : S) (env : CacheFormat) => Ok (mempty, env))\n        AlignedEncode_Nil.\n  Proof.\n    unfold EncodeMEquivAlignedEncodeM, AlignedEncode_Nil, ReturnAlignedEncodeM;\n      intros; injections; simpl in *; intuition.\n    - injections; simpl.\n      assert (idx < Datatypes.S (idx + m))%nat as H' by lia;\n        rewrite <- ltb_lt in H'; rewrite H'.\n      revert v.\n      eapply Vector.case0; simpl.\n      rewrite (plus_comm idx 0); simpl; eexists _; intuition.\n      pose proof (mempty_left (build_aligned_ByteString v2)) as H'';\n        simpl in H'';\n      rewrite H'', <- build_aligned_ByteString_append; reflexivity.\n    - injections; simpl in *.\n      destruct (idx <? (Datatypes.S numBytes')) eqn: ?.\n      rewrite ltb_lt in Heqb.\n      lia.\n      constructor.\n    - injections; simpl in *; lia.\n  Qed.\n\n  Local Arguments plus : simpl never.\n\n  Lemma Append_EncodeMEquivAlignedEncodeM\n        (encode1 encode2 : EncodeM S ByteString)\n        (encode1_aligned encode2_aligned : forall {numBytes}, AlignedEncodeM numBytes)\n        (encode1_OK : forall s env t env',\n            encode1 s env = Ok (t, env') -> padding t = 0)\n    : EncodeMEquivAlignedEncodeM encode1 (@encode1_aligned)\n      -> EncodeMEquivAlignedEncodeM encode2 (@encode2_aligned)\n      -> EncodeMEquivAlignedEncodeM\n           (sequence_Encode encode1 encode2)\n           (fun numBytes => AppendAlignedEncodeM encode1_aligned encode2_aligned).\n  Proof.\n    (*\n    unfold EncodeMEquivAlignedEncodeM; intros; specialize (encode1_OK s env); repeat split; intros.\n    - destruct (H env s idx) as [ H' [? ?] ].\n      revert H1 v H' H2 H3 H4;\n        unfold sequence_Encode;\n        destruct (encode1 s env) as [ [t1 env''] | ] eqn: ? ;\n        [ | intros; try discriminate];\n        simpl; destruct (encode2 s env'') as [ [t2 env'''] | ] eqn: ? ; simpl in *;\n          try (intros; discriminate);\n          intro; injection H1; intros ? ?; subst;\n            simpl; rewrite numBytes_ByteString_enqueue_ByteString;\n              intros; eauto.\n      destruct (H0 env'' s (idx + (numBytes t1))) as [H0' [? [? ?] ] ].\n      specialize (H0' _ _ Heqh0).\n      erewrite <- padding_ByteString_enqueue_aligned_ByteString in H0'.\n      destruct (H' _ _ (eq_refl _) (encode1_OK _ _ (eq_refl _)) v1 (fst (Vector_split _ _ v)) _\n                   (Vector.append (snd (Vector_split _ _ v)) v2)) as [? [? ?] ].\n      assert (idx + (numBytes t1 + (numBytes t2 + m)) =\n              (idx + numBytes t1) + (numBytes t2 + m)) by lia; simpl in *.\n      destruct (H0' H2 (fst (Vector_split _ _ (eq_rect _ (Vector.t char) x _ H10)))\n                    (fst (Vector_split _ _ (snd (Vector_split _ _ (eq_rect _ (Vector.t char) x _ H10)))))\n                    _ (snd (Vector_split _ _ (snd (Vector_split _ _ (eq_rect _ (Vector.t char) x _ H10)))))\n               ).\n      assert (idx + numBytes t1 + (numBytes t2 + m) =\n              idx + (numBytes t1 + numBytes t2 + m)) as H11' by lia.\n      assert (idx + (numBytes t1 + (numBytes t2 + m)) =\n              (idx + (numBytes t1 + numBytes t2 + m))) by lia; simpl in *.\n      unfold AppendAlignedEncodeM.\n      replace (encode1_aligned (idx + ((numBytes t1 + numBytes t2) + m))\n                               (Vector.append v1 (Vector.append v v2)) idx s env)\n        with (Some (eq_rect _ (Vector.t char) x _ H12, idx + numBytes t1, env''));\n        simpl.\n      + revert H12; rewrite <- H11'; intros.\n        rewrite (plus_assoc idx (numBytes t1) (numBytes t2)).\n        eexists _; intuition.\n        * etransitivity; [ | apply H4].\n          f_equal.\n          rewrite <- !Vector_split_append.\n          f_equal; eapply UIP_dec; intros; decide equality.\n        * rewrite <- H15.\n          rewrite ByteString_enqueue_ByteString_assoc.\n          rewrite ByteString_enqueue_ByteString_assoc.\n          rewrite <- ByteString_enqueue_ByteString_assoc.\n          symmetry in H9; destruct (build_aligned_ByteString_split' _ _ _ H9)\n            as [? H'']; symmetry in H''; destruct (build_aligned_ByteString_split _ _ _ H'').\n          revert H16 H9; clear.\n          intro.\n          revert H10 x v.\n          assert (idx + (numBytes t1 + (numBytes t2 + m)) - idx - (numBytes t2 + m) = numBytes t1)\n            as H''' by lia; revert x2 H16; rewrite H'''; clear H'''.\n          generalize (numBytes t1); intros; subst.\n          rewrite <- !build_aligned_ByteString_append in H9;\n            apply build_aligned_ByteString_inj in H9; subst.\n          rewrite <- !build_aligned_ByteString_append; repeat f_equal.\n          erewrite Vector_append_assoc.\n          rewrite <- Equality.transport_pp.\n          erewrite (UIP_dec _ _ (eq_refl _)); simpl.\n          rewrite <- Vector_append_split_fst; reflexivity.\n          erewrite Vector_append_assoc.\n          rewrite <- Equality.transport_pp.\n          erewrite (UIP_dec _ _ (eq_refl _)); simpl.\n          rewrite <- !Vector_append_split_snd; reflexivity.\n      + generalize x H8 H12; clear; intros.\n         replace (Some\n                    (eq_rect (idx + (numBytes t1 + (numBytes t2 + m)))\n                             (Vector.t char) x (idx + (numBytes t1 + numBytes t2 + m)) H12,\n                     idx + numBytes t1, env'')) with\n             (eq_rect _ (fun x => option ((Vector.t char x) * nat * CacheFormat))%type (Some (x, idx + numBytes t1, env'')) _ H12).\n         rewrite <- H8.\n         assert (idx + (numBytes t1 + numBytes t2 + m) =\n                 idx + (numBytes t1 + (numBytes t2 + m))) by lia.\n         replace (Vector.append v1 (Vector.append (fst (Vector_split (numBytes t1) (numBytes t2) v))\n                                                  (Vector.append (snd (Vector_split (numBytes t1) (numBytes t2) v)) v2)))\n           with (eq_rect _ (Vector.t char) (Vector.append v1 (Vector.append v v2)) _ H).\n         assert (forall n m (H' : n = m) (v : Vector.t char n),\n                    encode1_aligned m (eq_rect n (Vector.t char) v _ H') idx s env =\n                    eq_rect n (fun x => option ((Vector.t char x) * nat * CacheFormat))%type\n                            (encode1_aligned _ v idx s env) _ H') as H'\n             by (intros ? ? H'; rewrite H'; reflexivity).\n         rewrite H', <- Equality.transport_pp.\n         erewrite (UIP_dec _ _ (eq_refl _)); reflexivity.\n         assert (numBytes t1 + numBytes t2 + m = numBytes t1 + (numBytes t2 + m)) by lia.\n         replace (Vector.append (fst (Vector_split (numBytes t1) (numBytes t2) v))\n                                (Vector.append (snd (Vector_split (numBytes t1) (numBytes t2) v)) v2))\n           with (eq_rect _ (Vector.t char) (Vector.append v v2) _ H0)\n           by (erewrite Vector_append_assoc, <- Vector_split_append; reflexivity).\n         erewrite Vector_append_assoc', Vector_append_assoc, <- Equality.transport_pp.\n         reflexivity.\n         destruct H12; reflexivity.\n      + eapply encode1_OK; eauto.\n    - specialize (H env s idx);\n        unfold sequence_Encode in *;\n        destruct (encode1 s env) as [ [t1 env''] | ] eqn: ? ;\n        simpl in *; [ | intros; try discriminate];\n        simpl; destruct (encode2 s env'') as [ [t2 env'''] | ] eqn: ? ; simpl in *;\n          try (intros; discriminate).\n      pose proof (proj1 H _ _ (eq_refl _) (encode1_OK _ _ (eq_refl _))).\n      injections.\n      rewrite length_ByteString_enqueue_ByteString in H2.\n      unfold AppendAlignedEncodeM; destruct (encode1_aligned numBytes' v idx s env) eqn: ? ;\n          simpl; eauto.\n        destruct (le_lt_dec (8 + 8 * numBytes')\n                            (length_ByteString t1 + 8 * idx)).\n        { eauto; simpl in l; eapply (proj1 (proj2 H)) in l; eauto; rewrite Heqo in l. discriminate. }\n        rewrite length_ByteString_no_padding in l by eauto.\n        pose proof (proj1 (proj2 (H0 env'' s (snd (fst p))))) as H'.\n        assert (numBytes t1 + idx < Datatypes.S numBytes')%nat by lia; clear l.\n        assert (idx + numBytes t1 <= numBytes')%nat by lia.\n        destruct (Vector_split_lt _ _ H4 v) as [? [? [? [? ?] ] ] ].\n        pose proof (proj1 (proj2 (H))) as H'' .\n        destruct (H3 (fst (Vector_split _ _ x0)) (snd (Vector_split _ _ x0)) _ x1) as [v' [? ?] ].\n        erewrite <- H'; f_equal; clear H'.\n      + revert p Heqo H6.\n        rewrite H5.\n        rewrite <- x2; simpl; clear.\n        rewrite Vector_append_assoc with (H := sym_eq (plus_assoc idx (numBytes t1) x)), <- Vector_split_append.\n        generalize v' (eq_sym (plus_assoc idx (numBytes t1) x)).\n        rewrite (plus_assoc idx (numBytes t1) x).\n        intros. erewrite (UIP_dec _ _ (eq_refl _)) in H6; simpl in H6.\n        rewrite Heqo in H6; destruct p as [ [? ?] ?]; simpl in *; congruence.\n      + rewrite Heqh0; simpl; eauto.\n      + replace (8 * snd (fst p)) with (length_ByteString t1 + 8 * idx); try lia.\n        rewrite length_ByteString_no_padding by eauto.\n        revert p Heqo H6.\n        rewrite H5.\n        rewrite <- x2; simpl; clear.\n        rewrite Vector_append_assoc with (H := sym_eq (plus_assoc idx (numBytes t1) x)), <- Vector_split_append.\n        generalize v' (eq_sym (plus_assoc idx (numBytes t1) x)).\n        rewrite (plus_assoc idx (numBytes t1) x).\n        intros. erewrite (UIP_dec _ _ (eq_refl _)) in H6; simpl in H6.\n        rewrite Heqo in H6; destruct p as [ [? ?] ?]; simpl in *; injections.\n        lia.\n      - specialize (H env s idx);\n        unfold sequence_Encode in *;\n        destruct (encode1 s env) as [ [t1 env''] | ] eqn: ? ;\n        simpl in *; [ | intros; try discriminate];\n        simpl; destruct (encode2 s env'') as [ [t2 env'''] | ] eqn: ? ; simpl in *;\n          try (intros; discriminate); injections.\n        pose proof (proj1 H _ _ (eq_refl _) (encode1_OK _ _ (eq_refl _))).\n        rewrite padding_ByteString_enqueue_aligned_ByteString in H2 by eauto.\n        unfold AppendAlignedEncodeM; destruct (encode1_aligned numBytes' v idx s env) eqn: ? ;\n          simpl; eauto.\n        destruct (le_lt_dec (8 + 8 * numBytes')\n                            (length_ByteString t1 + 8 * idx)).\n        { eauto; simpl in l; eapply (proj1 (proj2 H)) in l; eauto; rewrite l in Heqo; discriminate. }\n        rewrite length_ByteString_no_padding in l by eauto.\n        pose proof (proj1 (proj2 (proj2 (H0 env'' s (snd (fst p)))))) as H'.\n        assert (numBytes t1 + idx < Datatypes.S numBytes')%nat by lia; clear l.\n        assert (idx + numBytes t1 <= numBytes')%nat by lia.\n        destruct (Vector_split_lt _ _ H4 v) as [? [? [? [? ?] ] ] ].\n        pose proof (proj2 (proj2 (H))) as H'' .\n        destruct (H1 (fst (Vector_split _ _ x0)) (snd (Vector_split _ _ x0)) _ x1) as [v' [? ?] ].\n        erewrite <- H'; f_equal; clear H'; eauto.\n        * revert p Heqo H6.\n          rewrite H5.\n          rewrite <- x2; simpl; clear.\n          rewrite Vector_append_assoc with (H := sym_eq (plus_assoc idx (numBytes t1) x)), <- Vector_split_append.\n          generalize v' (eq_sym (plus_assoc idx (numBytes t1) x)).\n          rewrite (plus_assoc idx (numBytes t1) x).\n          intros. erewrite (UIP_dec _ _ (eq_refl _)) in H6; simpl in H6.\n          rewrite Heqo in H6; destruct p as [ [? ?] ?]; simpl in *; try congruence.\n      - specialize (H env s idx);\n        unfold sequence_Encode in *;\n        destruct (encode1 s env) as [ [t1 env''] | ] eqn: ? ; simpl in *.\n        + destruct (encode2 s env'') as [ [t2 env'''] | ] eqn: ? ; simpl in *;\n            try inversion H1.\n          unfold AppendAlignedEncodeM.\n          destruct (Nat.le_decidable (8 + 8 * numBytes') (length_ByteString t1 + 8 * idx)).\n          erewrite (proj1 (proj2 H)); eauto.\n          destruct (PeanoNat.Nat.eq_dec (padding t1) 0).\n          unfold length_ByteString in H2; rewrite e in H2; simpl in H2.\n          assert (exists m, numBytes' = idx + (numBytes t1 + m)).\n          exists (numBytes' - (idx + numBytes t1)).\n          lia.\n          destruct H3.\n          pose proof (proj1 H _ _ (eq_refl _) (encode1_OK _ _ (eq_refl _))) as H'.\n          destruct (H' (fst (Vector_split _ _ (eq_rect _ _ v _ H3)))\n                         (fst (Vector_split _ _ (snd (Vector_split _ _ (eq_rect _ _ v _ H3)))))\n                         _\n                         (snd (Vector_split _ _ (snd (Vector_split _ _ (eq_rect _ _ v _ H3))))))\n            as [v' [? ?] ].\n          replace (encode1_aligned _ v idx s env)\n            with (Some (eq_rect _ (Vector.t char) v' _ (sym_eq H3), idx + numBytes t1, env'')).\n          * simpl; eapply H0. rewrite Heqh0; f_equal; auto.\n          * generalize v' H3 H4; clear; intros.\n            revert v v' H4; rewrite H3; intros; simpl; f_equal.\n            unfold ByteBuffer.t in *.\n            rewrite <- H4; f_equal.\n            rewrite <- !Vector_split_append; reflexivity.\n          * erewrite (proj1 (proj2 (proj2 H))); eauto.\n        + unfold AppendAlignedEncodeM; rewrite (proj2 (proj2 (proj2 H))); simpl; eauto.\n          Unshelve.\n          all: eauto using Nat.eq_dec; lia.\n  Qed.\n     *)\n  Admitted.\n\n  Definition CorrectAlignedEncoder\n             (format : FormatM S ByteString)\n             (encoder : forall sz, AlignedEncodeM sz)\n    := {encoder' : EncodeM S ByteString &\n                   (forall s env,\n                       (forall t env', encoder' s env = Ok (t, env')\n                                       -> refine (format s env) (ret (t, env')))\n                       /\\ (is_error (encoder' s env) ->\n                           forall benv', ~ computes_to (format s env) benv'))\n                   /\\ (forall s env t env',\n                          encoder' s env = Ok (t, env')\n                       -> padding t = 0)\n                   /\\ EncodeMEquivAlignedEncodeM encoder' encoder}.\n\n  Lemma CorrectAlignedEncoderForDoneC\n    : CorrectAlignedEncoder (fun s e => Return (ByteString_id, e)) AlignedEncode_Nil.\n  Proof.\n    unfold CorrectAlignedEncoder; intros.\n    eexists (fun _ env => Ok (ByteString_id, env)); split; [ | split]; intros.\n    - split; intros.\n      + congruence.\n      + inversion H.\n    - injections; reflexivity.\n    - eapply Return_EncodeMEquivAlignedEncodeM.\n  Defined.\n\n  (* Lemma CorrectAlignedEncoderForDoneC A\n        (format_A : FormatM A ByteString)\n        (encode_A : A -> forall sz, AlignedEncodeM sz)\n        (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n    : CorrectAlignedEncoder\n        (fun a => format_A a DoneC)\n        encode_A.\n  Proof.\n    unfold CorrectAlignedEncoder; intros.\n    destruct encoder_A_OK as [encoder [? [? ?] ] ].\n    exists encoder; split; intros; eauto.\n    intros; rewrite <- H.\n    unfold compose, Bind2.\n    setoid_rewrite Monad.refineEquiv_bind_unit; simpl.\n    pose proof mempty_right as H'; simpl in H'; setoid_rewrite H'.\n    intros v Comp_v; computes_to_inv; subst.\n    destruct v; simpl in *; auto.\n    computes_to_econstructor; eauto.\n  Qed. *)\n\n  Lemma CorrectAlignedEncoderForThenC\n        (format_A format_B : FormatM S ByteString)\n        (encode_A : forall sz, AlignedEncodeM sz)\n        (encode_B : forall sz, AlignedEncodeM sz)\n        (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n        (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n        (encoder_A_OK' :\n           forall (s : S) (env : CacheFormat) (tenv' tenv'' : ByteString * CacheFormat),\n            format_B s env \u220b tenv' ->\n            format_A s (snd tenv') \u220b tenv'' ->\n            exists tenv3 tenv4 : _ * CacheFormat,\n              projT1 encoder_B_OK s env = Ok tenv3\n              /\\ format_A s (snd tenv3) \u220b tenv4)\n    : CorrectAlignedEncoder\n        (format_B ++ format_A)\n        (fun sz => AppendAlignedEncodeM (encode_B sz) (encode_A sz)).\n  Proof.\n    unfold CorrectAlignedEncoder; intros.\n    destruct encoder_A_OK as [encoder_A ?], encoder_B_OK as [encoder_B ?]; intuition.\n    destruct a0 as [? [? ?] ].\n    eexists (sequence_Encode encoder_B encoder_A); split; [ | split];\n      intros; simpl in *.\n    3: eapply Append_EncodeMEquivAlignedEncodeM.\n    4: apply e0.\n    4: apply H2.\n    3: apply e.\n    pose proof (fun H a => CorrectEncoder_sequence format_B format_A encoder_B encoder_A H encoder_A_OK' a).\n    destruct H0.\n    - unfold CorrectEncoder; split; intros.\n      specialize (proj1 (a _ _) _ _ H0); intro.\n      unfold refine in H3; eauto.\n      specialize (proj2 (a _ _) H0); intro.\n      intro.\n      eapply H3; eauto.\n    - unfold CorrectEncoder; split; intros.\n      specialize (proj1 (H _ _) _ _ H0); intro.\n      unfold refine in H3; eauto.\n      specialize (proj2 (H _ _) H0); intro.\n      intro.\n      eapply H3; eauto.\n    - split; intros.\n      + apply H0 in H4.\n        intros ? ?; computes_to_inv; subst.\n        eauto.\n      + destruct benv'.\n        eapply H3 in H4.\n        eauto.\n    - unfold sequence_Format, sequence_Encode, Bind2 in *.\n      apply_in_hyp DecodeBindOpt_inv; destruct_ex; split_and.\n      symmetry in H4.\n      apply_in_hyp DecodeBindOpt_inv; destruct_ex; split_and.\n      injections.\n      rewrite padding_ByteString_enqueue_aligned_ByteString; eauto.\n  Defined.\n\nEnd AlignedEncodeM.\n\nLemma refine_CorrectAlignedEncoder\n      {S : Type}\n      {cache : Cache}\n  : forall format format' encode,\n    (forall (s : S) (env : CacheFormat),\n        refine (format s env) (format' s env)\n        /\\ ((forall v, ~ computes_to (format' s env) v)\n            -> (forall v, ~ computes_to (format s env) v)))\n    -> (CorrectAlignedEncoder format' encode)\n    -> (CorrectAlignedEncoder format encode).\nProof.\n  unfold CorrectAlignedEncoder; intros.\n  destruct X as [? [? ?] ]; eexists; intuition eauto.\n  rewrite (proj1 (H _ _)); eauto.\n  eapply H0; eauto.\n  eapply H; eauto.\n  intros.\n  eapply H0 in H1; eauto.\nDefined.\n\nLemma EncodeMEquivAlignedEncodeM_morphism\n      {S : Type}\n      {cache : Cache}\n  : forall x (encode encode': forall sz : nat, AlignedEncodeM sz),\n    (forall sz v idx w c, encode' sz v idx w c ~= encode sz v idx w c) ->\n    EncodeMEquivAlignedEncodeM (S := S) x encode ->\n    EncodeMEquivAlignedEncodeM (S := S) x encode'.\nProof.\n  unfold EncodeMEquivAlignedEncodeM; intros * Heq Hequiv.\n  intros a b c. specialize (Hequiv a b c).\n  split_and. constructor; [|constructor].\n  - intros d e f g h i j k.\n    specialize (H d e f g h i j k).\n    destruct H as [x' [? ?]].\n    exists x'.\n    eapply Ok_eq in H as HH; try (symmetry; eapply Heq).\n    rewrite <- HH. split; eauto.\n  - intros **.\n    rewrite Heq. eauto.\n  - split; eauto; intros;\n      rewrite Heq; eauto.\nQed.\n\nLemma CorrectAlignedEncoder_morphism\n      {S : Type}\n      {cache : Cache}\n  : forall format format' (encode encode': forall sz : nat, AlignedEncodeM sz),\n    (EquivFormat format' format) ->\n    (forall sz v idx w c, encode' sz v idx w c ~= encode sz v idx w c) ->\n    CorrectAlignedEncoder (S := S) format encode ->\n    CorrectAlignedEncoder (S := S) format' encode'.\nProof.\n  unfold CorrectAlignedEncoder; intros.\n  destruct X as [? [? ?] ]; eexists; intuition eauto.\n  eapply H1 in H2; rewrite <- H2; eapply H.\n  eapply H1 in H2; eauto.\n  eapply H; eauto.\n  eauto using EncodeMEquivAlignedEncodeM_morphism.\nDefined.\n\nLemma CorrectAlignedEncoderThenCAssoc\n      {S : Type}\n      {cache : Cache}\n      (format_A format_B format_C : FormatM S ByteString)\n      (encode : forall sz, AlignedEncodeM sz)\n  : CorrectAlignedEncoder\n      ((format_A ++ format_B) ++ format_C)\n      encode\n    -> CorrectAlignedEncoder\n         (format_A ++ format_B ++ format_C)\n         encode.\nProof.\n  intros; eapply refine_CorrectAlignedEncoder; eauto.\n  unfold sequence_Format, compose; intros.\n  unfold Bind2.\n  split.\n  - repeat setoid_rewrite Monad.refineEquiv_bind_bind.\n    setoid_rewrite Monad.refineEquiv_bind_unit; simpl.\n    f_equiv; intro.\n    simpl; f_equiv; intro.\n    simpl; f_equiv; intro.\n    rewrite ByteString_enqueue_ByteString_assoc; reflexivity.\n  - intros.\n    intro; eapply (H v).\n    computes_to_inv; repeat computes_to_econstructor; eauto.\n    simpl; subst.\n    rewrite <- ByteString_enqueue_ByteString_assoc; reflexivity.\nDefined.\n\nCorollary Guarded_CorrectAlignedEncoderThenCAssoc\n          {S : Type}\n          {cache : Cache}\n          (format_A format_B format_C : FormatM S ByteString)\n          (encode : forall sz, AlignedEncodeM sz)\n  : (forall env s bs env', computes_to (format_A s env) (bs, env') ->\n                       length_ByteString bs < 8)%nat\n    -> CorrectAlignedEncoder\n         ((format_A ++ format_B) ++ format_C)\n         encode\n    -> CorrectAlignedEncoder\n         (format_A ++ format_B ++ format_C)\n         encode.\nProof.\n  intros; eapply CorrectAlignedEncoderThenCAssoc; eauto.\nDefined.\n\nLemma CorrectAlignedEncoderThenCAssoc'\n      {S : Type}\n      {cache : Cache}\n      (format_A format_B format_C : FormatM S ByteString)\n      (encode : forall sz, AlignedEncodeM sz)\n  : CorrectAlignedEncoder\n      (format_A ++ format_B ++ format_C)\n      encode\n    -> CorrectAlignedEncoder\n         ((format_A ++ format_B) ++ format_C)\n         encode.\nProof.\n  intros; eapply refine_CorrectAlignedEncoder; eauto.\n  unfold sequence_Format, compose; intros.\n  unfold Bind2.\n  split.\n  - repeat setoid_rewrite Monad.refineEquiv_bind_bind.\n    setoid_rewrite Monad.refineEquiv_bind_unit; simpl; f_equiv; intro.\n    simpl; f_equiv; intro.\n    simpl; f_equiv; intro.\n    rewrite ByteString_enqueue_ByteString_assoc; reflexivity.\n  - intros ? ? ?; eapply (H v).\n    computes_to_inv; subst; repeat computes_to_econstructor; eauto.\n    simpl; subst.\n    rewrite  ByteString_enqueue_ByteString_assoc; reflexivity.\nDefined.\n\nDefinition Format_Source_Intersection\n           {A B}\n           {cache}\n           (format : @FormatM A B cache)\n           (predicate : A -> Prop)\n  : @FormatM A B cache\n  := fun a env benv =>\n       predicate a /\\\n       format a env benv.\n\nDefinition CorrectAlignedEncoderFor {S} {cache}\n           (format : @FormatM S ByteString cache)\n  := {encode : _ & CorrectAlignedEncoder format encode}.\n\nDefinition SetCurrentByte (* Sets a single byte at the current index and increments the current index. *)\n           {cache : Cache}\n           {cacheAddNat : CacheAdd cache nat}\n           {n : nat}\n  : @AlignedEncodeM cache char n :=\n  fun v idx s ce => if (idx <? n)\n                    then Ok (set_nth' v idx s, Datatypes.S idx, addE ce 8)\n                    else Error (InfoError \"Error setting current byte\" EndOfBuffer).\n\nDefinition Projection_AlignedEncodeM\n           {S' S'' : Type}\n           {cache : Cache}\n           (encode : forall sz, AlignedEncodeM (S := S'') sz)\n           (f : S' -> S'')\n           (n : nat)\n  : AlignedEncodeM (S := S') n :=\n  fun v idx s' env =>\n    encode n v idx (f s') env.\n\nLemma CorrectAlignedEncoderProjection\n      {S S' : Type}\n      {cache : Cache}\n      (format_S : FormatM S' ByteString)\n      (f : S -> S')\n      (encode : forall sz, AlignedEncodeM sz)\n  : CorrectAlignedEncoder format_S encode\n    -> CorrectAlignedEncoder\n         (Projection_Format format_S f)\n         (Projection_AlignedEncodeM encode f).\nProof.\n  intros H; destruct H as [? [? [? ?] ] ].\n  eexists (Basics.compose x f); intuition.\n  - intros; intros ? ?.\n    eapply H in H3.\n    unfold Projection_Format, Compose_Format; apply unfold_computes; eexists; split; eauto.\n    apply H2.\n  - unfold Projection_Format, Compose_Format in H3.\n    rewrite @unfold_computes in H3; destruct_ex; intuition.\n    eapply H in H2; eauto.\n    subst; eauto.\n  - eapply H0.\n    unfold Basics.compose in H2; eauto.\n  - unfold EncodeMEquivAlignedEncodeM, Basics.compose; intuition.\n    + eapply H1; eauto.\n    + edestruct H1 as [? [? [? ?] ] ].\n      eapply H5; eassumption.\n    + edestruct H1 as [? [? [? ?] ] ].\n      eapply H6; eassumption.\n    + edestruct H1 as [? [? [? ?] ] ].\n      eapply H6; eassumption.\nDefined.\n\n(*Not used*)\nDefinition AlignEncode_Alt\n           {S : Type}\n           {cache : Cache}\n           (encode_T encode_E : forall sz, AlignedEncodeM (S := S) sz)\n           sz\n  : AlignedEncodeM sz :=\n  fun v idx s c => match (encode_T sz) v idx s c with\n                   | Ok a' => Ok a'\n                   | Error e => encode_E sz v idx s c (*TODO: This should be tagged with an error,\n                                                        in case it fails we get a better traceback.\n                                                        *)\n                   end.\n\n(*Lemma CorrectAlignedEncoderEither_Both\n      {S : Type}\n      {cache : Cache}\n      (format_T format_E : FormatM S ByteString)\n      (encode_T encode_E : forall sz, AlignedEncodeM sz)\n  : CorrectAlignedEncoder format_T encode_T\n    -> CorrectAlignedEncoder format_E encode_E\n    -> CorrectAlignedEncoder\n         (composeIf format_T format_E)\n         (AlignEncode_Alt encode_T encode_E).\nProof.\n  intros.\n  destruct X as [? [? [? ?] ] ].\n  destruct X0 as [? [? [? ?] ] ].\n  eexists (fun s ce => Ifopt x s ce as a' Then\n                                          Ifopt x0 s ce as a'' Then (If (Nat.ltb (length_ByteString (fst a')) (length_ByteString (fst a''))) Then Some a' Else Some a'')\n                                                               Else Some a' Else x0 s ce); intuition.\n  - destruct (x s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n    destruct (x0 s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n    destruct (length_ByteString\n             {|\n             padding := padding;\n             front := front;\n             paddingOK := paddingOK;\n             numBytes := numBytes;\n             byteString := byteString |} <?\n           length_ByteString\n             {|\n             padding := padding0;\n             front := front0;\n             paddingOK := paddingOK0;\n             numBytes := numBytes0;\n             byteString := byteString0 |}) eqn: ?; simpl in H5.\n    + injections; subst.\n      unfold composeIf, Union_Format.\n      intros ? ?; apply unfold_computes; eexists Fin.F1; simpl; eauto.\n      eapply H; eauto.\n    + injections; subst;\n        unfold composeIf, Union_Format.\n      intros ? ?; apply unfold_computes; eexists (Fin.FS Fin.F1); simpl; eauto.\n      eapply H2; eauto.\n    + injections; subst.\n      unfold composeIf, Union_Format.\n      intros ? ?; apply unfold_computes; eexists Fin.F1; simpl; eauto.\n      eapply H; eauto.\n    +  injections; subst;\n        unfold composeIf, Union_Format.\n      intros ? ?; apply unfold_computes; eexists (Fin.FS Fin.F1); simpl; eauto.\n      eapply H2; eauto.\n  - destruct (x s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n    + destruct (x0 s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n      destruct (length_ByteString\n             {|\n             padding := padding;\n             front := front;\n             paddingOK := paddingOK;\n             numBytes := numBytes;\n             byteString := byteString |} <?\n           length_ByteString\n             {|\n             padding := padding0;\n             front := front0;\n             paddingOK := paddingOK0;\n             numBytes := numBytes0;\n             byteString := byteString0 |}) eqn: ?; simpl in H5; try discriminate.\n      discriminate.\n    + unfold composeIf, Union_Format in H6;\n        rewrite unfold_computes in H6.\n      destruct_ex.\n      revert H6; pattern x1.\n      eapply IterateBoundedIndex.Lookup_Iterate_Dep_Type; simpl.\n      econstructor; intros.\n      eapply H in Heqo; eauto.\n      econstructor; intros.\n      eapply H2 in H5; eauto.\n      constructor.\n  - destruct (x s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *; try discriminate.\n    + destruct (x0 s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n      * destruct (length_ByteString\n                    {|\n                      padding := padding;\n                      front := front;\n                      paddingOK := paddingOK;\n                      numBytes := numBytes;\n                      byteString := byteString |} <?\n                  length_ByteString\n                    {|\n                      padding := padding0;\n                      front := front0;\n                      paddingOK := paddingOK0;\n                      numBytes := numBytes0;\n                      byteString := byteString0 |}) eqn: ?; simpl in H5.\n        -- injections.\n           eapply H0 in Heqo; simpl in *; eauto.\n        -- injections.\n           eapply H3 in Heqo0; simpl in *; eauto.\n      * injections.\n        eapply H0 in Heqo; simpl in *; eauto.\n    + eapply H3 in H5; simpl in *; eauto.\n  - unfold EncodeMEquivAlignedEncodeM; intros.\n    unfold AlignEncode_Alt.\n    destruct (x s env) as [ [ [? ?] ? ] | ] eqn: ?.\n    + destruct (x0 s env) as [ [ [? ?] ? ] | ] eqn: ?; simpl in *.\n      destruct (length_ByteString\n                    {|\n                      padding := padding;\n                      front := front;\n                      paddingOK := paddingOK;\n                      numBytes := numBytes;\n                      byteString := byteString |} <?\n                  length_ByteString\n                    {|\n                      padding := padding0;\n                      front := front0;\n                      paddingOK := paddingOK0;\n                      numBytes := numBytes0;\n                      byteString := byteString0 |}) eqn: ?; simpl.\n      * unfold EncodeMEquivAlignedEncodeM in *.\n          specialize (H1 env s idx); injections.\n          simpl If_Opt_Then_Else; intuition eauto.\n        -- injections.\n           specialize (H5 _ _ Heqo H9 v1 v m v2); simpl in *.\n           destruct H5; intuition.\n           eexists _; rewrite H7; simpl; split; eauto.\n        -- injections.\n           specialize (H1 _ _ _ v Heqo H9); simpl in *.\n           rewrite H1; simpl.\n           specialize (H4 env s idx); eapply (proj1 (proj2 H4)); eauto.\n           eapply PeanoNat.Nat.ltb_lt in Heqb.\n           lia.\n        -- injections.\n           apply H0 in Heqo.\n           rewrite Heqo in H9; intuition.\n        -- discriminate.\n      * unfold EncodeMEquivAlignedEncodeM in *.\n          specialize (H4 env s idx); injections.\n          simpl If_Opt_Then_Else; intuition eauto.\n        -- injections.\n           specialize (H5 _ _ Heqo0 H9 v1 v m v2); simpl in *.\n           destruct H5; intuition.\n           eexists _; rewrite H7; simpl; split; eauto.\n        -- injections.\n           specialize (H1 _ _ _ v Heqo H9); simpl in *.\n           rewrite H1; simpl.\n           specialize (H4 env s idx); eapply (proj1 (proj2 H4)); eauto.\n           eapply PeanoNat.Nat.ltb_lt in Heqb.\n           lia.\n        -- injections.\n           apply H0 in Heqo.\n           rewrite Heqo in H9; intuition.\n        -- discriminate.\n    + simpl; specialize (H4 env s idx); specialize (H1 env s idx);\n        intuition.\n      * rewrite H10; simpl; eauto.\n      * rewrite H10; simpl; eauto.\n      * rewrite H10; simpl; eauto.\n      * rewrite H10; simpl; eauto.\nQed. *)\n\nLemma CorrectAlignedEncoderEither_E\n      {S : Type}\n      {cache : Cache}\n      (format_T format_E : FormatM S ByteString)\n      (encode : forall sz, AlignedEncodeM sz)\n      (encode_E_OK : CorrectAlignedEncoder format_E encode)\n  : (forall s env, exists (v : ByteString * CacheFormat), projT1 encode_E_OK s env = Ok v)\n    -> CorrectAlignedEncoder\n         (composeIf format_T format_E)\n         encode.\nProof.\n  intros; eapply refine_CorrectAlignedEncoder; eauto.\n  unfold composeIf, Union_Format; split; intros.\n  - intros ? ?; apply unfold_computes; eexists (Fin.FS Fin.F1); simpl; eauto.\n  - intros ? ;\n      specialize (H s env); destruct_ex.\n    apply (H0 x); eauto.\n    destruct x.\n    apply (proj1 (projT2 encode_E_OK)) in H; eapply H.\n    eauto.\nDefined.\n\nLemma CorrectAlignedEncoderEither_T\n      {S : Type}\n      {cache : Cache}\n      (format_T format_E : FormatM S ByteString)\n      (encode : forall sz, AlignedEncodeM sz)\n      (encode_T_OK : CorrectAlignedEncoder format_T encode)\n  : (forall s env, exists (v : ByteString * CacheFormat), projT1 encode_T_OK s env = Ok v)\n    -> CorrectAlignedEncoder\n         (composeIf format_T format_E)\n         encode.\nProof.\n  intros; eapply refine_CorrectAlignedEncoder; eauto.\n  unfold composeIf, Union_Format; split; intros.\n  - intros ? ?; apply unfold_computes; eexists Fin.F1; simpl; eauto.\n  - intros ? ;\n      specialize (H s env); destruct_ex.\n    apply (H0 x); eauto.\n    destruct x.\n    apply (proj1 (projT2 encode_T_OK)) in H; eapply H.\n    eauto.\nDefined.\n\nDefinition SetByteAt (* Sets the bytes at the specified index and sets the current index\n                        to the following position. *)\n           {cache : Cache}\n           {cacheAddNat : CacheAdd cache nat}\n           {n : nat}\n           (idx' : nat)\n  : AlignedEncodeM n :=\n  fun v idx s ce => if (Coq.Init.Nat.ltb idx' n)\n                    then Ok (set_nth' v idx' s, Datatypes.S idx', addE ce 8)\n                    else Error (LabelError \"Error setting byte at index\" EndOfBuffer).\n\nDeclare Scope AlignedEncodeM_scope.\nDelimit Scope AlignedEncodeM_scope with AlignedEncodeM.\nNotation \"y >> z\" := (AppendAlignedEncodeM y z) : AlignedEncodeM_scope.\n\nLocal Open Scope vector_scope.\n\nLemma AlignedEncoder_some_inv'\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n  : forall sz (t : Vector.t Core.char sz) n1 (s : S) v ni ce ce',\n    enc _ t n1 s ce = Ok (v, ni, ce') ->\n    exists b ce', enc' s ce = Ok (b, ce').\nProof.\n  intros. destruct (enc' s ce) eqn:?; destruct_conjs; eauto.\n  eapply isError, enc_OK in Heqh.\n  rewrite H in Heqh. inversion Heqh.\nQed.\n\nLemma AlignedEncoder_sz_destruct'\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n  : forall sz (t : Vector.t Core.char sz) n1 (s : S) v ni ce ce',\n    enc _ t n1 s ce = Ok (v, ni, ce') ->\n    forall b ce', enc' s ce = Ok (b, ce') ->\n    sz = n1 + (numBytes b + (sz-(n1+numBytes b))).\nProof.\n  intros.\n  destruct (Nat.le_decidable (1 + sz) (numBytes b + n1)).\n  edestruct enc_OK as [_ [? _]].\n  eapply H2 in H0.\n  { rewrite H in H0; inversion H0. }\n  rewrite length_ByteString_no_padding by eauto. lia. lia.\nQed.\n\nLemma AlignedEncoder_sz_destruct\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      n2\n      (enc'_sz_eq : forall s ce t ce',\n          enc' s ce = Ok (t, ce') -> numBytes t = n2)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n  : forall sz (t : Vector.t Core.char sz) n1 (s : S) v ni ce ce',\n    enc _ t n1 s ce = Ok (v, ni, ce') ->\n    sz = n1 + ((ni-n1) + (sz-ni)) /\\\n    n2 = ni - n1.\nProof.\n  intros. edestruct @AlignedEncoder_some_inv' as [b [? ?]]; eauto.\n  assert (sz = n1 + (numBytes b + (sz-(n1+numBytes b)))) by eauto using AlignedEncoder_sz_destruct'.\n  revert dependent t. revert v. rewrite H1.\n  intros. destruct (Vector_append_destruct3 t) as [t1 [t2 [t3 ?]]]. subst.\n  edestruct enc_OK as [? _]. edestruct H2; eauto. clear H2. destruct_conjs.\n  rewrite H2 in H. injections.\n  split. lia.\n  erewrite enc'_sz_eq; eauto. lia.\nQed.\n\nLemma AlignedEncoder_some_inv\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n  : forall sz (t : Vector.t Core.char sz) n1 (s : S) v ni ce ce',\n    enc _ t n1 s ce = Ok (v, ni, ce') ->\n    exists b , enc' s ce = Ok (b, ce').\nProof.\n  intros. edestruct @AlignedEncoder_some_inv' as [b [? ?]]; eauto.\n  assert (sz = n1 + (numBytes b + (sz-(n1+numBytes b)))) by eauto using AlignedEncoder_sz_destruct'.\n  revert dependent t. revert v. rewrite H1.\n  intros. destruct (Vector_append_destruct3 t) as [t1 [t2 [t3 ?]]]. subst.\n  edestruct enc_OK as [? _]. edestruct H2; eauto. clear H2. destruct_conjs.\n  rewrite H2 in H. injections.\n  rewrite H0. eexists. repeat f_equal.\nQed.\n\nLemma AlignedEncoder_inv'\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n1 n3\n  : forall s ce b ce'',\n    enc' s ce = Ok (b, ce'') ->\n    forall (t1 : Vector.t Core.char n1) (t2 : Vector.t Core.char (numBytes b))\n      (t3 : Vector.t Core.char n3) v idx ce',\n      enc _ (t1++t2++t3) n1 s ce = Ok (v, idx, ce') ->\n      exists v2,\n        enc _ t2 0 s ce = Ok (v2, numBytes b, ce') /\\\n        v = t1 ++ v2 ++ t3 /\\\n        idx = n1 + numBytes b /\\\n        b = build_aligned_ByteString v2 /\\\n        ce'' = ce'.\nProof.\n  intros.\n  edestruct enc_OK as [? _].\n  edestruct H1; eauto. clear H1. destruct_conjs.\n  rewrite H1 in H0. injections.\n  edestruct enc_OK with (idx:=0) as [? _].\n  edestruct H0 with (m:=0) (v0:=t2) (v1:=Vector.nil Core.char) (v2:=Vector.nil Core.char); eauto.\n  clear H0. simpl in *. destruct_conjs.\n  revert H0. rewrite Vector_append_nil_r'. generalize (plus_n_O (numBytes b)).\n  destruct e. simpl. intros.\n  assert (b = build_aligned_ByteString x) as L. {\n    rewrite <- H3.\n    rewrite !build_aligned_ByteString_nil.\n    eauto using mempty_left.\n  }\n  eexists; intuition eauto.\n  apply build_aligned_ByteString_inj.\n  rewrite !build_aligned_ByteString_append.\n  rewrite <- H2. repeat f_equal. eauto.\nQed.\n\nLemma AlignedEncoder_inv\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n\n  : forall (t : Vector.t Core.char n) n1 s ce v idx ce',\n      enc _ t n1 s ce = Ok (v, idx, ce') ->\n      exists n2 n3 (t1 : Vector.t Core.char n1)\n        (t2 : Vector.t Core.char n2) (t3 : Vector.t Core.char n3) v2\n        (pf : n1 + (n2 + n3) = n),\n        enc _ t2 0 s ce = Ok (v2, n2, ce') /\\\n        idx = n1 + n2 /\\\n        t = eq_rect _ _ (t1 ++ t2 ++ t3) _ pf /\\\n        v = eq_rect _ _ (t1 ++ v2 ++ t3) _ pf /\\\n        enc' s ce = Ok (build_aligned_ByteString v2, ce').\nProof.\n  intros. edestruct @AlignedEncoder_some_inv' as [b [? Heqo]]; eauto.\n  pose proof Heqo as Hsz. eapply AlignedEncoder_sz_destruct' in Hsz; eauto.\n  revert dependent t. revert dependent v. rewrite Hsz. intros.\n  destruct (Vector_append_destruct3 t) as [t1 [t2 [t3 ?]]]. subst.\n  edestruct @AlignedEncoder_inv'; eauto. destruct_conjs. subst.\n  repeat eexists; eauto;\n    try (rewrite <- Eqdep_dec.eq_rect_eq_dec; eauto; apply Nat.eq_dec).\n  congruence.\n  Unshelve.\n  lia.\nQed.\n\nLemma AlignedEncoder_extr\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n n'\n  : forall (t : Vector.t Core.char n) (t' : Vector.t Core.char n')\n      n1 s v ce idx ce',\n    enc _ t n1 s ce = Ok (v, idx, ce') ->\n    enc _ (t++t') n1 s ce = Ok (v++t', idx, ce').\nProof.\n  intros. edestruct @AlignedEncoder_inv as [n2 [n3 [t1 [t2 [t3 [v2 ?]]]]]]; eauto.\n  destruct_conjs.\n  subst. simpl in *.\n  match goal with\n  | |- enc (?n1 + (?n2 + ?n3) + ?n4) ((?t1 ++ ?t2 ++ ?t3) ++ ?t4) ?a ?b ?c =\n    Ok ((?t1' ++ ?t2' ++ ?t3') ++ ?t4', ?d, ?e)=>\n    assert (enc (n1 + (n2 + (n3 + n4))) (t1 ++ t2 ++ (t3 ++ t4)) a b c =\n            Ok ((t1' ++ t2' ++ (t3' ++ t4')), d, e))\n  end.\n  assert (n2 = numBytes (build_aligned_ByteString v2)) as L by eauto.\n  edestruct enc_OK as [? _]. edestruct H0 with (v:=eq_rect _ _ t2 _ L); eauto. clear H0. destruct_conjs.\n  destruct L. simpl in *. rewrite H0.\n  repeat f_equal. apply build_aligned_ByteString_inj.\n  rewrite <- H2. rewrite !build_aligned_ByteString_append. reflexivity.\n\n  rename n' into n4. revert H0. clear. intros.\n  assert (n1 + (n2 + n3) + n4 = n1 + (n2 + (n3 + n4))) by lia.\n  assert (forall {A}\n            (t1 : Vector.t A n1) (t2 : Vector.t A n2) (t3 : Vector.t A n3) (t4 : Vector.t A n4),\n             t1 ++ t2 ++ t3 ++ t4 = eq_rect _ (Vector.t A) ((t1 ++ t2 ++ t3) ++ t4) _ H) as L. {\n    clear. intros.\n    assert (n2 + n3 + n4 = n2 + (n3 + n4)) by lia.\n    rewrite <- (Vector_append_assoc' _ _ _ _ H0). f_equal.\n    apply Vector_append_assoc.\n  }\n  revert H0. rewrite !L. clear. destruct H. simpl. eauto.\nQed.\n\nCorollary AlignedEncoder_inv2\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n\n  : forall (t : Vector.t Core.char n) n1 s ce v idx ce',\n      enc _ t n1 s ce = Ok (v, idx, ce') ->\n      exists n2 n3 (t1 : Vector.t Core.char n1) (t23 : Vector.t Core.char (n2+n3)) v23\n        (pf : n1 + (n2+n3) = n),\n        enc _ t23 0 s ce = Ok (v23, n2, ce') /\\\n        idx = n1 + n2 /\\\n        t = eq_rect _ _ (t1 ++ t23) _ pf /\\\n        v = eq_rect _ _ (t1 ++ v23) _ pf.\nProof.\n  intros. edestruct @AlignedEncoder_inv; eauto. destruct_conjs.\n  repeat eexists; eauto. eauto using AlignedEncoder_extr.\nQed.\n\nCorollary AlignedEncoder_inv0\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n\n  : forall (t : Vector.t Core.char n) s ce v ce',\n    enc _ t 0 s ce = Ok (v, n, ce') ->\n    enc' s ce = Ok (build_aligned_ByteString v, ce').\nProof.\n  intros. edestruct @AlignedEncoder_inv as [n2 [n3 [t1 [t2 [t3 [v2 ?]]]]]]; eauto.\n  destruct_conjs. subst. simpl in *.\n  rewrite H5. repeat f_equal.\n  assert (n3 = 0) by lia. subst. clear.\n  apply Vector.case0 with (v:=t1). simpl.\n  apply Vector.case0 with (v:=t3).\n  rewrite Vector_append_nil_r'. generalize (plus_n_O n2). destruct e.\n  reflexivity.\nQed.\n\nLemma AlignedEncoder_none_inv\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n  : forall s ce b ce'\n      sz (t : Vector.t Core.char sz) n1,\n    enc' s ce = Ok (b, ce') ->\n    is_error (enc _ t n1 s ce) ->\n    (sz < n1 + numBytes b)%nat.\nProof.\n  intros.\n  destruct (Nat.le_decidable (1 + sz) (numBytes b + n1)). lia.\n  assert (sz = n1 + (numBytes b + (sz - (n1+numBytes b)))) by lia.\n  revert dependent t. rewrite H2. intros. destruct (Vector_append_destruct3 t) as [t1 [t2 [t3 ?]]].\n  subst.\n  edestruct enc_OK as [? _]. edestruct H3; eauto. clear H3. destruct_conjs.\n  rewrite H3 in H0. inversion H0.\nQed.\n\nLemma AlignedEncoder_extl\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n  : forall n (t : Vector.t Core.char n) n1 s ce v ce',\n    enc _ t 0 s ce = Ok (v, n1, ce') ->\n    forall idx (t1 : Vector.t Core.char idx),\n    enc _ (t1++t) idx s ce = Ok (t1++v, idx+n1, ce').\nProof.\n  intros.\n  match goal with\n  | |- ?a = _ => destruct a eqn:?\n  end. destruct_conjs.\n  edestruct @AlignedEncoder_inv2 as [n2 [n3 [t2 [t23 [v23 ?]]]]]; try apply Heqo; eauto.\n  destruct_conjs. assert (n2 + n3 = n) as L by lia. destruct L.\n  rewrite <- Eqdep_dec.eq_rect_eq_dec in H3 by (apply Nat.eq_dec).\n  rewrite <- Eqdep_dec.eq_rect_eq_dec in H4 by (apply Nat.eq_dec).\n  subst.\n  apply Vector_append_inj in H3. destruct_conjs. subst.\n  edestruct @AlignedEncoder_some_inv; try apply H; eauto.\n  edestruct @AlignedEncoder_some_inv; try apply H1; eauto.\n  substss. injections. eauto.\n  exfalso.\n  edestruct @AlignedEncoder_some_inv; try apply H; eauto.\n  eapply isError, AlignedEncoder_none_inv in Heqh; eauto.\n  eapply AlignedEncoder_sz_destruct' in H; eauto.\n  lia.\nQed.\n\nLemma AlignedEncoder_fixed\n      {S} {cache : Cache}\n      (enc' : EncodeM S ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n      (enc'_aligned : forall s ce t ce', enc' s ce = Ok (t, ce') -> padding t = 0)\n      n n1\n  : forall (t : Vector.t Core.char n)\n      s ce v idx ce',\n    enc _ t n1 s ce = Ok (v, idx, ce') ->\n    enc _ v n1 s ce = Ok (v, idx, ce').\nProof.\n  intros. edestruct @AlignedEncoder_inv as [n2 [n3 [t1 [t2 [t3 [v2 ?]]]]]]; eauto.\n  destruct_conjs.\n  subst. simpl in *.\n  assert (n2 = numBytes (build_aligned_ByteString v2)) as L by eauto.\n  match goal with\n  | |- ?x = _ => destruct x eqn:?\n  end. destruct_conjs.\n  edestruct @AlignedEncoder_inv'; try apply Heqo; eauto. destruct_conjs.\n  subst. repeat f_equal. eauto using build_aligned_ByteString_inj.\n  exfalso. eapply isError, AlignedEncoder_none_inv in Heqh; eauto.\n  lia.\nQed.\n\nLemma AlignedEncoder_append_inv\n      {S} {cache : Cache}\n      (enc1' : EncodeM S ByteString)\n      (enc1 : forall sz, AlignedEncodeM sz)\n      (enc1_OK : EncodeMEquivAlignedEncodeM enc1' enc1)\n      (enc1'_aligned : forall s ce t ce', enc1' s ce = Ok (t, ce') -> padding t = 0)\n      (enc2' : EncodeM S ByteString)\n      (enc2 : forall sz, AlignedEncodeM sz)\n      (enc2_OK : EncodeMEquivAlignedEncodeM enc2' enc2)\n      (enc2'_aligned : forall s ce t ce', enc2' s ce = Ok (t, ce') -> padding t = 0)\n      n\n  : forall (t : Vector.t Core.char n) s ce v idx ce',\n    (enc1 n >> enc2 n)%AlignedEncodeM t 0 s ce = Ok (v, idx, ce') ->\n    exists n1 n2 n3 (t1 : Vector.t Core.char n1) (t23 : Vector.t Core.char (n2+n3)) v1 v23 ce''\n      (pf : n1 + (n2+n3) = n),\n      enc1 _ t1 0 s ce = Ok (v1, n1, ce'') /\\\n      enc2 _ t23 0 s ce'' = Ok (v23, n2, ce') /\\\n      idx = n1 + n2 /\\\n      t = eq_rect _ _ (t1 ++ t23) _ pf /\\\n      v = eq_rect _ _ (v1 ++ v23) _ pf.\nProof.\n  unfold AppendAlignedEncodeM. intros.\n  destruct enc1 eqn:?; [| discriminate]; destruct_conjs; simpl in *.\n  destruct enc2 eqn:?; [| discriminate]; destruct_conjs; simpl in *.\n  injections. rename n0 into n1. rename t0 into v0.\n  edestruct @AlignedEncoder_inv as [n1' [n23 [tnil [t1 [t23 [v1 ?]]]]]]; try apply enc1_OK; eauto.\n  destruct_conjs. subst. simpl in *.\n  revert dependent tnil. intros tnil.\n  apply Vector.case0 with (v:=tnil). clear tnil. simpl. intros. rename n1' into n1.\n  edestruct @AlignedEncoder_inv2 as [n2 [n3 [v1' [t23' [v23 ?]]]]]; try apply enc2_OK; eauto.\n  destruct_conjs. assert (n2 + n3 = n23) by lia. destruct H6.\n  rewrite <- Eqdep_dec.eq_rect_eq_dec in H3 by (apply Nat.eq_dec).\n  rewrite <- Eqdep_dec.eq_rect_eq_dec in H5 by (apply Nat.eq_dec).\n  subst. apply Vector_append_inj in H3. destruct_conjs. subst.\n  repeat eexists; eauto.\n  instantiate (1:=eq_refl). all : eauto.\nQed.\n\nLemma sequence_Encoding_padding_0\n      {cache : Cache} {S : Type}\n      enc1 enc2\n      (enc1_aligned : forall s ce t ce', enc1 s ce = Ok (t, ce') -> padding t = 0)\n      (enc2_aligned : forall s ce t ce', enc2 s ce = Ok (t, ce') -> padding t = 0)\n  : forall s ce b ce',\n    @sequence_Encode ByteString cache _ S enc1 enc2 s ce = Ok (b, ce') -> padding b = 0.\nProof.\n  unfold sequence_Encode. intros.\n  destruct enc1 eqn:?; destruct_conjs; [| discriminate]; simpl in *.\n  destruct enc2 eqn:?; destruct_conjs; [| discriminate]; simpl in *.\n  injections. apply enc1_aligned in Heqh. apply enc2_aligned in Heqh0.\n  rewrite ByteString_enqueue_ByteString_padding_eq. rewrite Heqh. rewrite Heqh0.\n  reflexivity.\nQed.\n\nLemma sequence_Encoding_inv\n      {cache : Cache} {S : Type}\n      enc1 enc2\n  : forall s ce b ce',\n    @sequence_Encode ByteString cache _ S enc1 enc2 s ce = Ok (b, ce') ->\n    exists b1 b2 ce1,\n      enc1 s ce = Ok (b1, ce1) /\\\n      enc2 s ce1 = Ok (b2, ce') /\\\n      b = mappend b1 b2.\nProof.\n  unfold sequence_Encode. intros.\n  destruct enc1 eqn:?; destruct_conjs; [| discriminate]; simpl in *.\n  destruct enc2 eqn:?; destruct_conjs; [| discriminate]; simpl in *.\n  injections. eauto 10.\nQed.\n\nDefinition EncodeAgain {S : Type} {cache : Cache}\n           {n}\n           (a : @AlignedEncodeM _ S n)\n           (b : nat -> @AlignedEncodeM _ S n)\n  : @AlignedEncodeM _ S n :=\n  fun v idx s c => (HBind a v idx s c  as a' With\n                    (HBind b (snd (fst a')) (fst (fst a')) idx s c as b' With\n                       Ok (fst (fst b'), snd (fst a'), snd b')\n                       )\n                    ).\n\nLemma EncodeMEquivAlignedEncodeMDep\n      {S A} {cache : Cache}\n      (enc1' : EncodeM S ByteString)\n      (enc2' : A -> EncodeM S ByteString)\n      (f' : ByteString -> A)\n      (enc1 : forall sz, AlignedEncodeM sz)\n      (enc2 : A -> forall sz, AlignedEncodeM sz)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> A)\n      (enc1_OK : EncodeMEquivAlignedEncodeM enc1' enc1)\n      (enc2_OK : forall a, EncodeMEquivAlignedEncodeM (enc2' a) (enc2 a))\n      (enc1'_aligned : forall s ce t ce', enc1' s ce = Ok (t, ce') -> padding t = 0)\n      (enc2'_aligned : forall a s ce t ce', enc2' a s ce = Ok (t, ce') -> padding t = 0)\n      (enc'_sz_eq : forall s a ce t1 ce1 t2 ce2,\n          enc1' s ce = Ok (t1, ce1) ->\n          enc2' a s ce = Ok (t2, ce2) ->\n          bin_measure t1 = bin_measure t2)\n      (f_OK : forall (b : ByteString)\n                idx (v1 : Vector.t Core.char idx)\n                m (v2 : Vector.t Core.char m)\n                (v : Vector.t Core.char (idx + ((numBytes b) + m))),\n          ByteString_enqueue_ByteString (build_aligned_ByteString v1)\n                                        (ByteString_enqueue_ByteString b (build_aligned_ByteString v2))\n          = build_aligned_ByteString v ->\n          f' b = f (numBytes b) v idx)\n  : EncodeMEquivAlignedEncodeM\n      (fun s ce =>\n         `(p, _) <- enc1' s ce;\n           enc2' (f' p) s ce)\n      (fun sz => EncodeAgain (enc1 sz)\n                          (fun idx' v idx s =>\n                             enc2 (f (idx'-idx) v idx) sz v idx s))%AlignedEncodeM.\nProof.\n  (*\n  repeat split; intros; simpl in *. {\n    destruct enc1' eqn:?; [| discriminate]; destruct_conjs; simpl in *.\n    assert (numBytes b = numBytes t) as L1. {\n      assert (bin_measure b = bin_measure t) by eauto.\n      rewrite !length_ByteString_no_padding in H1 by eauto.\n      lia.\n    }\n\n    edestruct enc1_OK as [? _]. specialize (H1 _ _ Heqe).\n    revert H1. rewrite L1. intros.\n    edestruct (H1 (enc1'_aligned _ _ _ _ Heqe) v1 v _ v2); eauto. clear H1. destruct_conjs.\n\n    assert (exists v, v1 ++ v ++ v2 = x) as L2. {\n      destruct L1.\n      edestruct @AlignedEncoder_inv'; eauto; eauto. destruct_conjs.\n      eauto.\n    } destruct L2 as [v' L2].\n\n    edestruct enc2_OK as [? _]. specialize (H3 _ _ H).\n    edestruct H3; eauto. clear H3. destruct_conjs.\n    rewrite L2 in H3.\n\n    eexists. split; eauto. unfold EncodeAgain.\n    rewrite H1. simpl.\n    match goal with\n    | H : enc2 ?a _ _ _ _ _ = _ |- context[enc2 ?a' _ _ _ _ _] =>\n      replace a' with a\n    end.\n    rewrite H3. simpl. reflexivity.\n    destruct L1. replace (idx + numBytes b - idx) with (numBytes b) by lia. eauto.\n  } {\n    destruct enc1' eqn:?; [| discriminate]; destruct_conjs; simpl in *.\n    edestruct enc1_OK as [_ [? _]]. eapply H1 in Heqe.\n    unfold EncodeAgain. rewrite Heqe. reflexivity.\n    assert (bin_measure b = bin_measure t) as L1 by eauto. simpl in *.\n    congruence.\n  } {\n    destruct enc1' eqn:?; [| discriminate]; destruct_conjs; simpl in *.\n    exfalso. eauto.\n  } {\n    destruct enc1' eqn:?; destruct_conjs; simpl in *; unfold EncodeAgain. {\n      destruct (Nat.le_decidable (1 + numBytes') (numBytes b + idx)).\n      edestruct enc1_OK as [_ [? _]]. erewrite H1; eauto.\n      rewrite length_ByteString_no_padding by eauto. lia.\n      assert (exists m, numBytes' = idx + (numBytes b + m)). {\n        exists (numBytes' - (idx + numBytes b)). lia.\n      } destruct H1 as [m ?]. subst.\n      edestruct (enc1_OK env s idx) as [? _]; eauto.\n      edestruct H1; eauto. destruct_conjs.\n      match goal with\n      | H : enc1 _ ?v' _ _ _ = _ |- _ => replace v with v'\n      end. rewrite H2. simpl.\n      edestruct enc2_OK as [_ [_ [_ ?]]]. rewrite H4; eauto.\n      simpl.\n      (* simpl. rewrite <- H. f_equal. *)\n      replace (idx + numBytes b - idx) with (numBytes b) by lia.\n      erewrite <- f_OK; eauto.\n      repeat (rewrite Vector_split_append; f_equal).\n    } {\n      edestruct (enc1_OK env s idx) as [_ [_ [_ ?]]]; eauto. eapply isError, H0 in Heqe; eauto.\n      rewrite Heqe. reflexivity.\n    }\n  }\nQed.\n   *)\n  Admitted.\nLemma EncodeMEquivAlignedEncodeM_const\n      {S A} {cache : Cache}\n      (enc' : EncodeM A ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n  : forall a, EncodeMEquivAlignedEncodeM (S:=S)\n           (fun _ ce => enc' a ce)\n           (fun sz v n _ ce => enc sz v n a ce).\nProof.\n  intros. repeat split; simpl; intros;\n            edestruct enc_OK as [? [? [? ?]]]; eauto.\nQed.\n\n(* This provides a more convenient side-condition used in some aligned encoder,\ne.g., list and vector. *)\nLemma encoder_format_eq_cache_OK {cache : Cache} {S1 S2}\n        (format_A : FormatM S1 ByteString)\n        (format_B : FormatM S2 ByteString)\n        (encode_B : forall sz, AlignedEncodeM sz)\n        (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n        (encode_A_OK' : forall (s1 : S1) (s2 : S2) (env: CacheFormat)\n                          (tenv' tenv'' tenv3 : ByteString * CacheFormat),\n            format_B s2 env \u220b tenv' ->\n            format_A s1 (snd tenv') \u220b tenv'' ->\n            projT1 encoder_B_OK s2 env = Ok tenv3 ->\n            snd tenv' = snd tenv3)\n    : forall (s1 : S1) (s2 : S2) (env : CacheFormat) (tenv' tenv'' : ByteString * CacheFormat),\n      format_B s2 env \u220b tenv' ->\n      format_A s1 (snd tenv') \u220b tenv'' ->\n      exists tenv3 tenv4 : _ * CacheFormat,\n        projT1 encoder_B_OK s2 env = Ok tenv3\n        /\\ format_A s1 (snd tenv3) \u220b tenv4.\nProof.\n  intros.\n  match goal with\n  | |- exists _ _, ?e = _ /\\ _ => destruct e eqn:?\n  end.\n  - repeat esplit. erewrite <- encode_A_OK'; eauto.\n  - exfalso. destruct encoder_B_OK as [? [H' ?]]; simpl in *.\n    eapply H'; eauto. rewrite Heqh; constructor.\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/BinLib/AlignedEncodeMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "From compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight.\nFrom compcert Require Import Maps Values ClightBigstep Events Clightdefs.\n\nRequire Import Clight.intmax_test.\n\nOpen Scope Z_scope.\n\nDefinition spec := 2.\n\nTheorem f_intmax_test_correct (ge : genv) (e : env) (m : Memory.Mem.mem) :\n  forall (ste : temp_env) (n1 n2 : Z),\n    (* starting environment *)\n    ste ! _a = Some (Vlong (Int64.repr 1)) ->\n    ste ! _b = Some (Vlong (Int64.repr 1)) ->\n\n    (* correct return *)\n    exists (t : trace) (rte : temp_env),\n      exec_stmt ge e ste m f_long_test.(fn_body) t rte m\n        (Out_return (Some (Vundef, tvoid))).\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/intmax_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19171963086360388}}
{"text": "Record PreCategory :=  Build_PreCategory' { object :> Type }.\nClass Foo (X : Type) := {}.\nClass Bar := {}.\nDefinition functor_category `{Bar} (C D : PreCategory)  `{Foo (object D)} : PreCategory.\nAdmitted.\nFail Definition functor_object_of `{Bar} (C1 C2 D : PreCategory) `{Foo (object D)}\n: functor_category C1 (functor_category C2 D) -> True.\n(** Anomaly: File \"toplevel/himsg.ml\", line ..., characters ...: Assertion failed.\nPlease report. *)\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_094.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1917190971645268}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri Require Import machine_extra lifting rules.rules_base.\nFrom HypVeri.algebra Require Import base reg mem pagetable mailbox base_extra.\nFrom HypVeri.lang Require Import lang_extra reg_extra current_extra.\nRequire Import stdpp.fin.\nRequire Import stdpp.listset_nodup.\n\nSection run.\n\nContext `{hypparams:HypervisorParameters}.\n  \nContext `{vmG: !gen_VMG \u03a3}.\n\nLemma run {E w1 w2 w3 q s p_tx R' Q P} ai i R P':\n  let T := (\u25b7 (PC @@ V0 ->r ai)\n            \u2217 \u25b7 (ai ->a w1)\n            \u2217 \u25b7 (V0 -@{q}A> s)\n            \u2217 \u25b7 (TX@ V0 := p_tx)\n            \u2217 \u25b7 (R0 @@ V0 ->r w2)\n            \u2217 \u25b7 (R1 @@ V0 ->r w3))%I\n  in\n  let T' := ((PC @@ V0 ->r (ai ^+ 1)%f)\n               \u2217 ai ->a w1\n               \u2217 V0 -@{q}A> s\n               \u2217 TX@ V0 := p_tx\n               \u2217 R0 @@ V0 ->r w2\n               \u2217 R1 @@ V0 ->r w3)%I\n  in\n  (tpa ai) \u2208 s ->\n  (tpa ai) \u2260 p_tx ->\n  i \u2260 V0 ->\n  decode_instruction w1 = Some Hvc ->\n  decode_hvc_func w2 = Some Run ->\n  decode_vmid w3 = Some i ->\n  {SS{{ T \u2217 \u25b7 (VMProp i (Q) (1/2)%Qp)\n          \u2217 \u25b7 (VMProp V0 P 1%Qp)\n          \u2217 \u25b7 (T' \u2217 R \u2217 VMProp V0 P' (1/2)%Qp -\u2217 (Q \u2217 R'))\n          \u2217 \u25b7 R }}}\n    ExecI @ V0 ;E\n    {{{ RET (true, ExecI); R' \u2217 VMProp V0 P' (1/2)%Qp}}}.\nProof.\n  simpl.\n  iIntros (Hin Hnottx Hneq_v Hdecode Hhvc Hvmid \u03d5) \"[(>Hpc & >Hapc & >Hacc & >tx & >Hr0 & >Hr1) (HPropi & HPropz & Himpl & HR)] H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI); [done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  iDestruct \"H\u03c3\" as \"(%Hneq & Hmemown & Hreg & Hmb & ? & Hown & Haccessown & Hrest)\".\n  (* valid regs *)\n  iDestruct (gen_reg_valid1 PC V0 ai Hcur with \"Hreg Hpc\") as \"%Hpc\".\n  iDestruct (gen_reg_valid1 R0 V0 w2 Hcur with \"Hreg Hr0\") as \"%Hr0\".\n  iDestruct (gen_reg_valid1 R1 V0 w3 Hcur with \"Hreg Hr1\") as \"%Hr1\".\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai)  with \"Haccessown Hacc\") as %Hacc;first exact Hin.\n  iDestruct (mb_valid_tx with \"Hmb tx\") as %Htx.\n  subst p_tx.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai w1 with \"Hmemown Hapc\") as \"%Hmem\".\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal V0 Hvc ai w1);eauto.\n  - iModIntro.\n    iIntros (m2 \u03c32) \"[%U PAuth] %HstepP\".\n    apply (step_ExecI_normal V0 Hvc ai w1) in HstepP; eauto.\n    remember (exec Hvc \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec /hvc in Heqc2; eauto.\n    rewrite  Hr0 /= Hhvc /run Hr1 in Heqc2.\n    simpl in Heqc2.\n    rewrite /unpack_hvc_result_yield Hvmid in Heqc2.\n    simpl in Heqc2.\n    rewrite /is_primary Hcur in Heqc2.\n    destruct HstepP as [Hstep1 Hstep2].\n    case_bool_decide;last done.\n    subst c2.\n    simpl in Hstep1, Hstep2.\n    subst \u03c32 m2.\n    simpl.\n    rewrite /gen_vm_interp /update_incr_PC.\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    all: try rewrite p_upd_id_mb p_upd_pc_mb //.\n    all: try rewrite p_upd_id_pgt p_upd_pc_pgt //.\n    all: try rewrite p_upd_id_trans p_upd_pc_trans //.\n    rewrite p_upd_id_mem p_upd_pc_mem.\n    iFrame.\n    iDestruct ((gen_reg_update1_global PC V0 ai (ai ^+ 1)%f) with \"Hreg Hpc\") as \"HpcUpd\".\n    rewrite (preserve_get_reg_gmap (update_offset_PC \u03c31 1) (update_current_vmid _ _));last rewrite p_upd_id_reg //.\n    rewrite ->(u_upd_pc_regs _ V0 ai 1); auto.\n    + iDestruct (VMProp_update V0 U P P' with \"PAuth HPropz\") as \"HTemp\".\n      iMod \"HpcUpd\".\n      iMod \"HTemp\".\n      iDestruct \"HTemp\" as \"[PAuth HPropz]\".\n      iModIntro.\n      iDestruct \"HpcUpd\" as \"[? Hpc]\".\n      iFrame.      \n      iSplitL \"PAuth\".\n      by iExists P'.\n      iSplit; first done.\n      rewrite /just_scheduled_vms /just_scheduled.\n      assert (filter\n                (\u03bb id : vmid,\n                        base.negb (scheduled \u03c31 id) &&\n                        scheduled (update_current_vmid (update_offset_PC \u03c31 1) i) id = true)\n                (seq 0 n) = [fin_to_nat i]) as ->.\n      {\n        rewrite /scheduled /machine.scheduler Hneq //= /scheduler.\n        rewrite /update_current_vmid //=.\n        pose proof (NoDup_seq 0 vm_count) as ND.\n        pose proof (NoDup_singleton ((@fin_to_nat (@vm_count H) i))) as ND'.\n        set f := (\u03bb id : nat, base.negb (bool_decide ((@fin_to_nat (@vm_count H) \u03c31.1.1.2) = id)) && bool_decide ((@fin_to_nat (@vm_count H) i) = id) = true).\n        pose proof (NoDup_filter f _ ND) as ND''.\n        assert (f i) as Prf.\n        {\n          subst f.\n          simpl.\n          unfold base.negb.\n          repeat case_bool_decide; eauto.\n          rewrite Hcur in H1.\n          exfalso.\n          apply Hneq_v.\n          symmetry.\n          apply fin_to_nat_inj.\n          done.\n        }\n        assert (In (@fin_to_nat (@vm_count H) i) (seq 0 vm_count)) as Prf'.\n        {\n          rewrite <-elem_of_list_In.\n          rewrite elem_of_seq.\n          split.\n          - solve_finz.\n          - rewrite plus_O_n.\n            pose proof (fin_to_nat_lt i).\n            auto.\n        }\n        rewrite <-elem_of_list_In in Prf'.\n        assert (In (@fin_to_nat (@vm_count H) i) (filter f (seq 0 vm_count))) as Prf''.\n        {\n          rewrite <-elem_of_list_In.\n          by apply (iffRL (elem_of_list_filter f (seq 0 vm_count) i)).\n        }\n        rewrite <-elem_of_list_In in Prf''.\n        assert (forall x, x \u2260 (@fin_to_nat (@vm_count H) i) -> not (In x (filter f (seq 0 vm_count)))) as excl.\n        {\n          intros x neq c.\n          rewrite <-elem_of_list_In in c.\n          rewrite ->elem_of_list_filter in c.\n          destruct c as [c' _].\n          subst f.\n          simpl in c'.\n          unfold base.negb in c'.\n          case_match.\n          - by rewrite andb_false_l in c'.\n          - rewrite andb_true_l in c'.\n            apply neq.\n            rewrite ->bool_decide_eq_true in c'.\n            by symmetry.\n        }\n        apply Permutation_length_1_inv.\n        apply NoDup_Permutation; auto.\n        intros x'.\n        split.\n        - intros T.\n          rewrite ->elem_of_list_singleton in T.\n          rewrite T; auto.\n        - intros T.\n          rewrite ->elem_of_list_singleton.\n          rewrite ->elem_of_list_In in T.\n          destruct (decide (x' = i)) as [? | n']; auto.\n          exfalso.\n          by apply (excl x' n').\n      }\n      iSimpl.\n      assert ((negb (scheduled (update_current_vmid (update_offset_PC \u03c31 1) i) V0) && true = true)) as ->.\n      {\n        rewrite andb_true_r.\n        rewrite /scheduled /machine.scheduler //= /scheduler.\n        rewrite /update_current_vmid //=.\n        apply eq_true_not_negb.\n        intros c.\n        rewrite ->bool_decide_eq_true in c.\n        apply Hneq_v.\n        apply fin_to_nat_inj.\n        done.\n      }\n      iDestruct (VMProp_split with \"HPropz\") as \"[HPropz1 HPropz2]\".\n      iDestruct (\"Himpl\" with \"[Hpc Hapc Hacc Hr0 Hr1 HR HPropz1 tx]\") as \"[Q R']\".\n      iFrame.\n      iSplitR \"H\u03d5 R' HPropz2\".\n      iSplit; last done.\n      iExists (Q)%I.\n      iFrame.\n      iApply (\"H\u03d5\" with \"[R' HPropz2]\").\n      iFrame.\n    + apply get_reg_gmap_get_reg_Some; auto.\nQed.\n\nLemma run_not_primary {E wi r0 r2 q s p_tx } ai i :\n  (tpa ai) \u2208 s ->\n  (tpa ai) \u2260 p_tx ->\n  decode_instruction wi = Some Hvc ->\n  decode_hvc_func r0 = Some Run ->\n  i \u2260 V0 ->\n  {SS{{ \u25b7 (PC @@ i ->r ai)\n            \u2217 \u25b7 (ai ->a wi)\n            \u2217 \u25b7 (i -@{q}A> s)\n            \u2217 \u25b7 (TX@ i := p_tx)\n            \u2217 \u25b7 (R0 @@ i ->r r0)\n            \u2217 \u25b7 (R2 @@ i ->r r2)\n            }}}\n    ExecI @ i ;E\n    {{{ RET (false, ExecI); PC @@ i ->r (ai ^+ 1)%f\n               \u2217 ai ->a wi\n               \u2217 i -@{q}A> s\n               \u2217 TX@ i := p_tx\n               \u2217 R0 @@ i ->r (encode_hvc_ret_code Error)\n               \u2217 R2 @@ i ->r (encode_hvc_error Denied) }}}.\n  Proof.\n  iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hneq_v0 \u03a6)\n          \"(>PC & >mem_ins & >acc & >tx & >R0 & >R2) H\u03a6\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (\u03c31.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 R2 r2 Heq_cur) with \"regs PC R0 R2\")\n    as \"(%Hlookup_PC & %Hlookup_R0 & %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 \u03c32) \"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 \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary  in Heqc2.\n    case_bool_decide. rewrite H0 in Heq_cur. rewrite Heq_cur // in Hneq_v0.\n    destruct HstepP;subst m2 \u03c32; 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 \">[[$ $] ?]\";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\u03a6\".\n    iFrame.\n    by iFrame.\n  Qed.\n\nLemma run_invalid_vmid {E wi r0 r1 r2 q s p_tx } ai :\n  (tpa ai) \u2208 s ->\n  (tpa ai) \u2260 p_tx ->\n  decode_instruction wi = Some Hvc ->\n  decode_hvc_func r0 = Some Run ->\n  decode_vmid r1 = None ->\n  {SS{{ \u25b7 (PC @@ V0 ->r ai)\n            \u2217 \u25b7 (ai ->a wi)\n            \u2217 \u25b7 (V0 -@{q}A> s)\n            \u2217 \u25b7 (TX@ V0 := p_tx)\n            \u2217 \u25b7 (R0 @@ V0 ->r r0)\n            \u2217 \u25b7 (R1 @@ V0 ->r r1)\n            \u2217 \u25b7 (R2 @@ V0 ->r r2)\n            }}}\n    ExecI @ V0 ;E\n    {{{ RET (false, ExecI); PC @@ V0 ->r (ai ^+ 1)%f\n               \u2217 ai ->a wi\n               \u2217 V0 -@{q}A> s\n               \u2217 TX@ V0 := p_tx\n               \u2217 R0 @@ V0 ->r (encode_hvc_ret_code Error)\n               \u2217 R1 @@ V0 ->r r1\n               \u2217 R2 @@ V0 ->r (encode_hvc_error InvParam) }}}.\n  Proof.\n  iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hdecode_vmid \u03a6)\n          \"(>PC & >mem_ins & >acc & >tx & >R0 &>R1 & >R2) H\u03a6\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (\u03c31.1.1.2 = V0) 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 V0 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) V0 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 V0 p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal V0 Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 \u03c32) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal V0 Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary in Heqc2.\n    case_bool_decide;last contradiction.\n    rewrite Hlookup_R1 /= Hdecode_vmid /= in Heqc2.\n    destruct HstepP;subst m2 \u03c32; 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 \">[[$ $] ?]\";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\u03a6\".\n    iFrame.\n    by iFrame.\n  Qed.\n\nLemma run_primary {E wi r0 r1 q s p_tx} ai :\n  (tpa ai) \u2208 s ->\n  (tpa ai) \u2260 p_tx ->\n  decode_instruction wi = Some Hvc ->\n  decode_hvc_func r0 = Some Run ->\n  decode_vmid r1 = Some V0 ->\n  {SS{{ \u25b7 (PC @@ V0 ->r ai)\n            \u2217 \u25b7 (ai ->a wi)\n            \u2217 \u25b7 (V0 -@{q}A> s)\n            \u2217 \u25b7 (TX@ V0 := p_tx)\n            \u2217 \u25b7 (R0 @@ V0 ->r r0)\n            \u2217 \u25b7 (R1 @@ V0 ->r r1)}}}\n    ExecI @ V0 ;E\n    {{{ RET (false, ExecI); PC @@ V0 ->r (ai ^+ 1)%f\n               \u2217 ai ->a wi\n               \u2217 V0 -@{q}A> s\n               \u2217 TX@ V0 := p_tx\n               \u2217 R0 @@ V0 ->r r0\n               \u2217 R1 @@ V0 ->r r1}}}.\n  Proof.\n  iIntros (Hin_acc Hneq_tx Hdecode_i Hdecode_f Hdecode_vmid \u03a6)\n          \"(>PC & >mem_ins & >acc & >tx & >R0 & >R1) H\u03a6\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche state\".\n  rewrite /scheduled /= /scheduler in Hsche.\n  assert (\u03c31.1.1.2 = V0) 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 V0 PC ai R0 r0 R1 r1 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) V0 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 V0 p_tx with \"mb tx\") as %Heq_tx.\n  (* valid tran *)\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal V0 Hvc ai wi);auto.\n    rewrite Heq_tx //.\n  - iModIntro.\n    iIntros (m2 \u03c32) \"vmprop_auth %HstepP\".\n    iFrame \"vmprop_auth\".\n    apply (step_ExecI_normal V0 Hvc ai wi) in HstepP;eauto.\n    2: rewrite Heq_tx //.\n    remember (exec Hvc \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /= /lang.run /is_primary in Heqc2.\n    case_bool_decide;last contradiction.\n    rewrite Hlookup_R1 /= Hdecode_vmid /= in Heqc2.\n    destruct HstepP;subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    all: try rewrite p_upd_id_mb p_upd_pc_mb //.\n    all: try rewrite p_upd_id_pgt p_upd_pc_pgt //.\n    all: try rewrite p_upd_id_trans p_upd_pc_trans //.\n    rewrite p_upd_id_mem p_upd_pc_mem.\n    iFrame.\n    (* upd reg*)\n    rewrite (preserve_get_reg_gmap (update_incr_PC \u03c31) (update_current_vmid _ _)).\n    2: rewrite p_upd_id_reg //.\n    rewrite (u_upd_pc_regs _ V0 ai).\n    2: rewrite //.\n    2: solve_reg_lookup.\n    iDestruct ((gen_reg_update1_global PC V0 _ (ai ^+ 1)%f) with \"regs PC\")\n      as \">($ & PC)\";eauto.\n    iModIntro.\n    iSplit. iPureIntro. auto.\n    (* just_schedule *)\n    rewrite /just_scheduled_vms /just_scheduled.\n    rewrite /scheduled /machine.scheduler /= /scheduler.\n    rewrite /update_current_vmid /= Heq_cur.\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 list.filter_app.\n        rewrite IHn.\n        simpl.\n        rewrite filter_cons_False /=.\n        rewrite filter_nil. auto.\n        rewrite andb_negb_l.\n        done.\n    }\n    iSplitR;first done.\n    case_bool_decide; last contradiction.\n    simpl.\n    iApply \"H\u03a6\".\n    iFrame.\n  Qed.\n\nEnd run.\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/run.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.19163835332743454}}
{"text": "(** \n Verified SAR-BP: A verified C implementation of SAR backprojection\n with a certified absolute error bound.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file is free software. You can redistribute it and/or modify it\n under the terms of the GNU General Public License as published by the\n Free Software Foundation, either version 3 of the License (GNU GPL\n v3), or (at your option) any later version.  A verbatim copy of the\n GNU GPL v3 is included in gpl-3.0.txt.\n \n This file is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See LICENSE for\n more details about the use and redistribution of this file and the\n whole Verified SAR-BP library.\n \n This work is sponsored in part by DARPA MTO as part of the Power\n Efficiency Revolution for Embedded Computing Technologies (PERFECT)\n program (issued by DARPA/CMO under Contract No: HR0011-12-C-0123). The\n views and conclusions contained in this work are those of the authors\n and should not be interpreted as representing the official policies,\n either expressly or implied, of the DARPA or the\n U.S. Government. Distribution Statement \"A\" (Approved for Public\n Release, Distribution Unlimited.)\n \n \n If you are using or modifying Verified SAR-BP in your work, please\n consider citing the following paper:\n \n Tahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\n Lethin.\n A Unified Coq Framework for Verifying C Programs with Floating-Point\n Computations.\n In CPP (5th ACM/SIGPLAN conference on Certified Programs and Proofs)\n 2016.\n \n \n Verified SAR-BP derives from prior work listed in ACKS along with\n their copyright and licensing information.\n \n Verified SAR-BP requires third-party libraries listed in ACKS along\n with their copyright information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nVerification of C implementation of sine.\n*)\n\nRequire Import Flocq.Appli.Fappli_IEEE.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Clight.\nRequire Import FPLang.\nRequire Import FPLangOpt.\nRequire Import ClightFacts.\nRequire Import Clight2FPOpt.\nRequire Import SARBackProjSource.\nRequire Import SARBackProjSourceSin.\n\nRequire Import RAux.\nRequire Import FieldEq.\nOpen Scope R_scope.\n\nTransparent Integers.Int.repr.\nTransparent Floats.Float32.of_bits.\nTransparent Floats.Float.of_bits.\nSet Printing Depth 1000000. \n\nLocal Existing Instances\n      Clight2FP.nans\n      map_nat compcert_map\n.\n\nRequire Import Interval.Interval_tactic.\nRequire Import ClightSep2.\n\nOpen Scope R_scope.\n\nDefinition f_sin_cos_correct f_sin_error f_cos_error ge cef_sin_cos :=\n  type_of_fundef cef_sin_cos =\n  Ctypes.Tfunction (Ctypes.Tcons (Clightdefs.tptr Clightdefs.tfloat)\n                                 (Ctypes.Tcons (Clightdefs.tptr Clightdefs.tfloat)\n                                               (Ctypes.Tcons Clightdefs.tdouble Ctypes.Tnil)))\n                   Clightdefs.tvoid\n                   cc_default\n  /\\\n  forall\n    os\n    (Hos_align: (align_chunk Mfloat32 | Int.unsigned os)%Z )\n    oc\n    (Hoc_align: (align_chunk Mfloat32 | Int.unsigned oc)%Z )\n    ps (Hps: perm_order ps Writable)\n    pc (Hpc: perm_order pc Writable)\n    bs bc\n    m P\n    (Hm:\n       holds\n         (P ++\n            Pperm bs (Int.unsigned os) ps (size_chunk_nat Mfloat32)\n            ++\n            Pperm bc (Int.unsigned oc) pc (size_chunk_nat Mfloat32))\n         m)\n    x\n    (Hx_finite: is_finite _ _ x = true)\n    (Hx_range: x_left <= B2R _ _ x <= x_right )\n  ,\n    let st0 := (Callstate cef_sin_cos\n                          (Vptr bs os :: Vptr bc oc :: Vfloat x :: nil)\n                          Kstop\n                          m) in\n    exists m',\n      star Clight.step2 ge\n           st0\n           E0\n           (Returnstate Vundef Kstop m')\n      /\\\n      exists si co,\n        holds\n          (P ++\n             Pval Mfloat32 bs (Int.unsigned os) ps (Vsingle si)\n             ++\n             Pval Mfloat32 bc (Int.unsigned oc) pc (Vsingle co))\n          m'\n        /\\\n        (\n          is_finite _ _ si = true\n          /\\\n          is_finite _ _ co = true\n        )\n        /\\\n        (\n          Rabs (B2R _ _ si - sin (B2R _ _ x)) <= f_sin_error\n          /\\\n          Rabs (B2R _ _ co - cos (B2R _ _ x)) <= f_cos_error\n        )\n.\n\nLemma round_to_error u v d e:\n  v = u * (1 + d) + e ->\n  v - u = u * d + e.\nProof.\n  intros H.\n  subst.\n  ring.\nQed.\n  \nLemma f_sin_cos_body_correct' :\n  { f_sin_error : _ &\n                        { f_cos_error |\n                          forall\n (ge: Clight.genv)\n      b_sin fn_sin\n      (Hb_sin: Globalenvs.Genv.find_symbol ge _sin = Some b_sin)\n      (Hfn_sin: Globalenvs.Genv.find_funct_ptr ge b_sin = Some fn_sin)\n      (Hfn_sin_correct: SARBackProjSourceSin.f_unary_correct sin ge fn_sin)\n      b_cos fn_cos\n      (Hb_cos: Globalenvs.Genv.find_symbol ge _cos = Some b_cos)\n      (Hfn_cos: Globalenvs.Genv.find_funct_ptr ge b_cos = Some fn_cos)\n      (Hfn_cos_correct: SARBackProjSourceSin.f_unary_correct cos ge fn_cos)\n,\n  f_sin_cos_correct f_sin_error f_cos_error ge (Clight.Internal (f_sin_cos))\n}}.\nProof.\n  esplit. esplit.\n\n  split; auto.\n  intros os Hos_align oc Hoc_align ps Hps pc Hpc bs bc m P Hm x Hx_finite Hx_range st0.\n  unfold x_left, x_right in Hx_range.\n  unfold st0.\n  clear st0.\n\n  apply f_sin_correct in Hfn_sin_correct.\n  destruct Hfn_sin_correct as (sin_type & Hfn_sin_correct).\n  apply f_cos_correct in Hfn_cos_correct.\n  destruct Hfn_cos_correct as (cos_type & Hfn_cos_correct).\n\n  unfold f_unary_error in Hfn_sin_correct, Hfn_cos_correct.\n\n  match goal with\n    |- exists m', Smallstep.star step2 ?ge ?s Events.E0 (Returnstate Vundef Kstop m') /\\ ?P =>\n    cut \n      (exists s',\n         Smallstep.star step2 ge s Events.E0 s' /\\\n         exists m',\n           s' = Returnstate Vundef Kstop m' /\\\n           P)\n  end.\n  {\n    intro H;  break H; subst; eauto 13.\n  }\n  apply star_exists_step.\n  call_fn.\n  simpl fn_body.\n\n  repeat run.\n\n  apply exec_call_exists.\n  solve_trivial.\n  eapply exists_modus_ponens.\n  {\n    eapply exists_double_elim.\n    eapply Hfn_sin_correct; eauto.\n  }\n  intros s1 Hs1.\n  simpl in Hs1.\n  destruct Hs1 as (si & ? & Hsi_finite & Hsi_val & Hsi_range).\n  subst s1.\n  solve_trivial.\n  repeat run.\n\n  apply eval_expr_exists_filter_float.\n  apply Vsingle_exists.\n  (* here comes the framework into play! *)\n  C_to_float_as sif Hsif.\n  compute_fval_as Hsif Hsif_finite Hsif_val.\n  solve_trivial.\n\n  repeat run.\n\n  holds_storev_solve.\n  intros m Hm.\n  repeat run.\n\n  apply exec_call_exists.\n  solve_trivial.\n  eapply exists_modus_ponens.\n  {\n    eapply exists_double_elim.\n    eapply Hfn_cos_correct; eauto.\n  }\n  intros s1 Hs1.\n  simpl in Hs1.\n  destruct Hs1 as (co & ? & Hco_finite & Hco_val & Hco_range).\n  subst s1.\n  solve_trivial.\n  repeat run.\n\n  apply eval_expr_exists_filter_float.\n  apply Vsingle_exists.\n  (* here comes the framework into play! *)\n  C_to_float_as cof Hcof.\n  compute_fval_as Hcof Hcof_finite Hcof_val.\n  solve_trivial.\n\n  repeat run.\n\n  holds_storev_solve.\n  intros m Hm.\n  repeat run.\n\n  apply star_exists_refl.\n  solve_trivial.\n\n  exists sif, cof.\n  split.\n  {\n    revert Hm.\n    apply holds_list_comm_aux.\n    apply count_occ_list_comm.\n    intros; repeat rewrite count_occ_app; omega.\n  }\n\n  split; auto.\n\n  split.\n  {\n    symmetry in Hsif_val.\n    rewrite Rmult_1_l in *.\n    apply round_to_error in Hsif_val.\n    match type of Hsif_val with\n        _ = ?z =>\n        interval_intro (Rabs z) upper with (i_prec 128) as Hsif_error\n    end.\n    rewrite <- Hsif_val in Hsif_error.\n    eapply Rabs_triang2.\n    {\n      eassumption.\n    }\n    eassumption.\n  }\n  symmetry in Hcof_val.\n  rewrite Rmult_1_l in *.\n  apply round_to_error in Hcof_val.\n  match type of Hcof_val with\n      _ = ?z =>\n      interval_intro (Rabs z) upper with (i_prec 128) as Hcof_error\n  end.\n  rewrite <- Hcof_val in Hcof_error.\n  eapply Rabs_triang2.\n  {\n    eassumption.\n  }\n  eassumption.\nDefined.\n\nDefinition f_sin_error' :=\n  let (x, _) := f_sin_cos_body_correct' in x.\n\nDefinition f_sin_error'_eq :=\n  $( field_eq f_sin_error' )$ .\n\nDefinition f_sin_error :=\n  $(\n      match type of f_sin_error'_eq with\n        _ = ?z => exact z\n      end\n    )$ .\n\nDefinition f_cos_error' :=\n  let (_, y) := f_sin_cos_body_correct' in\n  let (x, _) := y in x.\n\nDefinition f_cos_error'_eq :=\n  $( field_eq f_cos_error' )$ .\n\nDefinition f_cos_error :=\n  $(\n      match type of f_cos_error'_eq with\n        _ = ?z => exact z\n      end\n    )$ .\n\nLemma f_sin_cos_error_correct:\n                          forall\n (ge: Clight.genv)\n      b_sin fn_sin\n      (Hb_sin: Globalenvs.Genv.find_symbol ge _sin = Some b_sin)\n      (Hfn_sin: Globalenvs.Genv.find_funct_ptr ge b_sin = Some fn_sin)\n      (Hfn_sin_correct: SARBackProjSourceSin.f_unary_correct sin ge fn_sin)\n      b_cos fn_cos\n      (Hb_cos: Globalenvs.Genv.find_symbol ge _cos = Some b_cos)\n      (Hfn_cos: Globalenvs.Genv.find_funct_ptr ge b_cos = Some fn_cos)\n      (Hfn_cos_correct: SARBackProjSourceSin.f_unary_correct cos ge fn_cos)\n,\n  f_sin_cos_correct f_sin_error f_cos_error ge (Clight.Internal (f_sin_cos))\n.\nProof.\n  unfold f_sin_error.\n  rewrite <- f_sin_error'_eq.\n  unfold f_cos_error.\n  rewrite <- f_cos_error'_eq.\n  unfold f_sin_error', f_cos_error'.\n  destruct f_sin_cos_body_correct'.\n  destruct s.\n  assumption.\nQed.\n", "meta": {"author": "wuweh", "repo": "vsarbp", "sha": "8e4ca028ec8a73eb7f2fd27892a69971384cada5", "save_path": "github-repos/coq/wuweh-vsarbp", "path": "github-repos/coq/wuweh-vsarbp/vsarbp-8e4ca028ec8a73eb7f2fd27892a69971384cada5/sar/SARBackProjSourceSinOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.19139966318216992}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import pile.\nRequire Import spec_stdlib.\nRequire Import PileModel.\n\nRecord PileAPD := {\n  pilerep: list Z -> val -> mpred;\n  pilerep_local_facts: forall sigma p,\n    pilerep sigma p |-- !! (isptr p /\\ Forall (Z.le 0) sigma);\n  pilerep_valid_pointer: forall sigma p,\n    pilerep sigma p |-- valid_pointer p;\n  pile_freeable (p: val) : mpred (* Definitely don't expose the definition of this as malloc_token, because that would expose the fact that there's exactly one malloc'ed record in the implementation. *)\n}.\n\n#[export] Hint Resolve pilerep_local_facts : saturate_local.\n#[export] Hint Resolve pilerep_valid_pointer : valid_pointer.\n\nDefinition tpile := Tstruct _pile noattr.\n\nLocal Open Scope assert.\n\nSection PileASI.\nVariable M: MallocFreeAPD.\nVariable PILE:PileAPD.\n\nDefinition Pile_new_spec :=\n DECLARE _Pile_new\n WITH gv: globals\n PRE [ ] PROP() PARAMS() GLOBALS(gv) SEP(mem_mgr M gv)\n POST[ tptr tpile ]\n   EX p: val,\n      PROP() LOCAL(temp ret_temp p)\n      SEP(pilerep PILE nil p; pile_freeable PILE p; mem_mgr M gv).\n\nDefinition Pile_add_spec :=\n DECLARE _Pile_add\n WITH p: val, n: Z, sigma: list Z, gv: globals\n PRE [ tptr tpile, tint  ]\n    PROP(0 <= n <= Int.max_signed)\n    PARAMS (p; Vint (Int.repr n)) GLOBALS (gv)\n    SEP(pilerep PILE sigma p; mem_mgr M gv)\n POST[ tvoid ]\n    PROP() LOCAL()\n    SEP(pilerep PILE (n::sigma) p; mem_mgr M gv).\n\nDefinition Pile_count_spec :=\n DECLARE _Pile_count\n WITH p: val, sigma: list Z\n PRE [ tptr tpile  ]\n    PROP(0 <= sumlist sigma <= Int.max_signed)\n    PARAMS (p) GLOBALS ()\n    SEP (pilerep PILE sigma p)\n POST[ tint ]\n      PROP() \n      LOCAL(temp ret_temp (Vint (Int.repr (sumlist sigma))))\n      SEP(pilerep PILE sigma p).\n\nDefinition Pile_free_spec :=\n DECLARE _Pile_free\n WITH p: val, sigma: list Z, gv: globals\n PRE [ tptr tpile  ]\n    PROP()\n    PARAMS (p) (GLOBALS (gv)\n    SEP(pilerep PILE sigma p; pile_freeable PILE p; mem_mgr M gv))\n POST[ tvoid ]\n     PROP() LOCAL() SEP(mem_mgr M gv).\n\nDefinition PileASI:funspecs := [ Pile_new_spec; Pile_add_spec; Pile_count_spec; Pile_free_spec].\n\nEnd PileASI.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/VSUpile/spec_pile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.19139965954844798}}
{"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_frame mips_tactics.\nImport expr_m.\nImport assert_m.\nRequire Import multi_sub_s_u_prg multi_add_s_u_triple pick_sign_triple.\nRequire Import copy_u_u_triple multi_is_zero_u_triple multi_negate_triple.\nRequire Import multi_sub_u_u_L_triple multi_sub_u_u_R_triple.\nRequire Import multi_add_u_u_triple.\n\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope multi_int_scope.\n\n(* TODO: rename registers *)\nLemma multi_sub_s_u0_triple k a b a0 a1 a2 a3 a4 ret X :\nuniq(k, a, b, a0, a1, a2, a3, a4, ret, X, r0) ->\nforall nk va vb ptr, nk <> O -> Z_of_nat nk < 2 ^^ 31 ->\n  u2Z ptr + 4 * Z_of_nat nk < \\B^1 ->\nforall A B, size A = nk -> size B = nk -> 0 < \\S_{ nk } B ->\nforall slen, s2Z slen = sgZ (s2Z slen) * Z_of_nat nk ->\n{{ fun s h => [ a ]_s = va /\\ [ b ]_s = vb /\\  u2Z [ k ]_s = Z_of_nat nk /\\\n   ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h }}\nmulti_sub_s_u0 k a b a0 a1 a2 a3 a4 ret X\n{{ fun s h => exists A' slen', size A' = nk /\\ [ a ]_s = va /\\\n  [ b ]_s = vb /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat nk /\\\n  sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B) /\\\n  ((var_e a |--> slen' :: ptr :: nil ** int_e ptr |--> A') ** var_e b |--> B ) s h /\\\n  u2Z ([ a3 ]_ s) <= 1 /\\\n  sgZ (s2Z slen') * (\\S_{ nk } A' + u2Z ([ a3 ]_s) * \\B^nk) =\n    sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B }}.\nProof.\nmove=> Hregs nk va vb ptr Hnk Hnk' ptr_fit A B len_A len_B nk_B slen slen_not_weird.\nrewrite /multi_sub_s_u0.\n\n(** lw X four16 a *)\n\napply hoare_lw_back_alt'' with (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\\n  u2Z ([k ]_ s) = Z_of_nat nk /\\ [X ]_s = ptr /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h).\n\nrewrite /while.entails => s h [r_a [r_b [r_k Hmem]]].\nexists ptr; split.\n- rewrite conCE !conAE conCE !conAE\n  conCE !conAE in Hmem.\n  move: Hmem; apply monotony => // h'; apply mapsto_ext => //.\n  by rewrite sext_Z2u.\n- rewrite /update_store_lw.\n  repeat Reg_upd; repeat (split => //).\n  by Assert_upd.\n\n(** pick_sign a a0 a1 *)\n\napply while.hoare_seq with (fun s h =>\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_s = ptr /\\ [a0]_s = slen /\\ sgZ (s2Z [a1 ]_ s) = sgZ (s2Z slen) /\\\n  (s2Z [ a1 ]_ s = 0 \\/ s2Z [ a1 ]_ s = 1 \\/ s2Z [ a1 ]_s = - 1) /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h).\n\neapply while.hoare_conseq; last first.\n(* TODO: use machine_int notation *)\n- apply (pick_sign_triple (fun s h =>\n    [b ]_ s = vb /\\ u2Z [k ]_ s = Z_of_nat nk /\\\n    [X ]_ s = ptr) (((var_e a \\+ int_e four32 |~> int_e ptr **\n      (fun st h0 => u2Z (([a ]_ st `+ four32) `+ four32) mod 4 = 0 /\\\n        emp st h0)) ** int_e ptr |--> A) ** var_e b |--> B) va slen).\n  + by Uniq_uniq r0.\n  + Inde.\n    move=> s h x v /= [] //.\n    move=> ?; subst a1; by Reg_upd.\n    case=> // ?; subst a0; by Reg_upd.\n  + by Inde.\n- move=> s h /= [Ha [Hb [Hk [HX Hmem]]]].\n  by rewrite !conAE in Hmem *.\n- move=> s h [Ha [Ha0 [Ha1 [Ha1' [Hmem [Hb [Hk HX]]]]]]].\n  by rewrite !conAE in Hmem *.\n\n(** while.ifte (bgez a1) *)\n\napply while.hoare_ifte.\n\napply while.hoare_ifte.\n\napply while.hoare_seq with (fun s h =>\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_ s = ptr /\\ 0 = sgZ (s2Z slen) /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> B) ** var_e b |--> B) s h).\n\n(** copy k X b a2 a3 a4 *)\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\ [a0 ]_ s = slen /\\\n    sgZ (s2Z slen) = 0 /\\ (var_e a |--> slen :: ptr :: nil) s h)\n  (fun s h => [X]_s = ptr /\\ u2Z [k]_s = Z_of_nat nk /\\\n    (var_e b |--> B ** var_e X |--> A) s h)\n  (fun s h => [X]_s = ptr /\\ u2Z [k]_s = Z_of_nat nk /\\\n    (var_e b |--> B ** var_e X |--> B) s h)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply copy_u_u_triple => //; by Uniq_uniq r0.\n\nmove=> s h [ [ [Ha [Hb [Hk [HX [Ha0 [a1_slen [Ha1' mem]]]]]] _] Ha1] ].\nrewrite conAE in mem.\ncase: mem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nrepeat (split => //).\nrewrite conCE.\nmove: Hh2; apply monotony => // h'; exact: mapstos_ext.\nrewrite /= in Ha1; move/eqP/u2Z_inj in Ha1.\nrewrite store.get_r0 /= in Ha1.\nrewrite -a1_slen Ha1 s2Z_u2Z_pos'; by rewrite Z2uK.\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh2 => [Ha [Hb [Ha0 [Ha1' Hh2]]]].\ncase: Hh1 => Hx [Hk Hh1].\nrepeat (split => //).\nrewrite conAE.\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nrepeat (split => //).\nrewrite conCE.\nmove: Hh1; apply monotony => h' //; exact: mapstos_ext.\n\n(** addiu a3 r0 zero16 *)\n\napply hoare_addiu with (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\\n  u2Z [k ]_ s = Z_of_nat nk /\\ [X ]_ s = ptr /\\ [a3]_s = zero32 /\\\n  0 = sgZ (s2Z slen) /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> B) ** var_e b |--> B) s h).\nmove=> s h [Ha [Hb [Hk [HX [Hslen mem]]]]].\nrewrite /wp_addiu.\nrepeat Reg_upd.\nrepeat (split=> //).\nby rewrite sext_Z2u // addi0.\nby Assert_upd.\n\n(** sw k zero16 a *)\n\napply hoare_sw_back'' with (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\\n u2Z [k ]_ s = Z_of_nat nk /\\ [X ]_ s = ptr /\\ [a3 ]_ s = zero32 /\\\n 0 = sgZ (s2Z slen) /\\\n ((var_e a |--> Z2s 32 (Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> B) ** var_e b |--> B) s h).\n\nmove=> s h [Ha [Hb [Hk [HX [Ha3 [Hslen mem]]]]]].\nexists (int_e slen).\nrewrite !conAE /= in mem.\nmove: mem; apply monotony => // h'.\napply mapsto_ext => //; by rewrite /= sext_Z2u // addi0.\napply currying => h'' Hh''.\nrepeat (split => //).\nrewrite conCE in Hh''.\nrewrite /= !conAE.\nmove: Hh''; apply monotony => // h'''.\napply mapsto_ext => /=.\nby rewrite sext_Z2u // addi0.\napply u2Z_inj.\nrewrite Hk u2Z_Z2s_pos //.\nsplit; by [apply Zle_0_nat |(apply: @ltZ_leZ_trans; [exact: Hnk'|])].\n\n(** negate a a0 *)\n\napply hoare_prop_m.hoare_weak with (fun s h =>\n  [a ]_ s = va /\\ [b ]_ s = vb /\\\n  sgZ (- Z_of_nat nk) = sgZ (sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B) /\\\n  ((var_e a |--> Z2s 32 (- Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> B) ** var_e b |--> B) s h /\\\n  u2Z [a3 ]_ s <= 1 /\\ 0 = sgZ (s2Z slen) /\\\n  sgZ (- Z_of_nat nk) * (\\S_{ nk } B + u2Z [a3 ]_ s * \\B^nk) = sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B).\nmove=> s h [Ha [Hb [Hsgn [mem [Ha3 [Hslen HSum]]]]]].\nexists B, (Z2s 32 (- Z_of_nat nk)).\nrepeat (split=> //).\n\nrewrite Z2sK //; last lia.\nrewrite (proj2 (Zsgn_neg (- Z_of_nat nk))) //; lia.\nrewrite Z2sK //; lia.\nrewrite Z2sK //; lia.\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\ (var_e b |--> B) s h /\\\n    u2Z [a3 ]_ s <= 1 /\\ 0 = sgZ (s2Z slen) /\\\n    - sgZ (Z_of_nat nk) * (\\S_{ nk } B + u2Z [a3 ]_ s * \\B^nk) =\n    sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B)\n  (var_e a |--> Z2s 32 (Z_of_nat nk) :: ptr :: nil ** int_e ptr |--> B)\n  (var_e a |--> cplt2 (Z2s 32 (Z_of_nat nk)) :: ptr :: nil ** int_e ptr |--> B)).\n\napply frame_rule_R.\n- apply multi_negate_triple => //; by Uniq_uniq r0.\n  Inde_frame; rewrite /inde => s h x v /= [] // ?; subst x; by Reg_upd.\n- move=> ?; by Inde_mult.\n\nmove=> s h [Ha [Hb [Hk [HX [Ha3 [Hsgn mem]]]]]].\ncase: mem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h1 h2; first by exact Hh1.\nrepeat (split=> //).\nby rewrite Ha3 Z2uK.\nrewrite -Hsgn mul0Z /= Ha3 Z2uK // mul0Z addZ0 (proj2 (Zsgn_pos (Z_of_nat nk))) //; lia.\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh2 => [Ha [Hb [hSgn [Ha3 [Hslen HSum]]]]].\nrepeat (split => //).\nrewrite -Hslen mul0Z /= in HSum *.\nrewrite (proj2 (Zsgn_neg (- Z_of_nat nk))); last lia.\nrewrite (proj2 (Zsgn_neg (- \\S_{ nk } B))); lia.\nCompose_sepcon h1 h2; last by [].\nrewrite (_ : Z2s 32 (- Z_of_nat nk) = cplt2 (Z2s 32 (Z_of_nat nk))) //.\napply s2Z_inj.\nrewrite s2Z_cplt2; last first.\n  rewrite weirdE2 Z2sK; lia.\nrewrite Z2sK; last lia.\nrewrite Z2sK //; lia.\nrewrite (proj2 (Zsgn_pos (Z_of_nat nk))) in HSum; last lia.\nrewrite (proj2 (Zsgn_neg (- Z_of_nat nk))); last lia.\nrewrite -HSum; ring.\n\n(** multi_lt k X b a0 a1 ret a2 a3 a4 *)\n\napply while.hoare_seq with (fun s h =>\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_ s = ptr /\\ sgZ (s2Z slen) = 1 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h /\\\n  ((\\S_{ nk } A < \\S_{ nk } B /\\ [ret]_s = one32 /\\ [a2]_s = zero32) \\/\n   (\\S_{ nk } A > \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [a2]_s = one32) \\/\n   (\\S_{ nk } A = \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [a2]_s = zero32))).\n\neapply (before_frame\n  (fun s h => [a ]_ s = va /\\ sgZ (s2Z slen) = 1 /\\ (var_e a |--> slen :: ptr :: nil) s h)\n  (fun s h => u2Z ([k ]_ s) = Z_of_nat nk /\\ [X ]_ s = ptr /\\ [b ]_ s = vb /\\\n    (var_e X |--> A ** var_e b |--> B) s h )\n  (fun s h =>u2Z ([k ]_ s) = Z_of_nat nk /\\ [X ]_ s = ptr  /\\ [b ]_ s = vb /\\\n    (((\\S_{ nk } A < \\S_{ nk } B /\\ [ret]_s = one32 /\\ [a2]_s = zero32) \\/\n      (\\S_{ nk } A > \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [a2]_s = one32) \\/\n      (\\S_{ nk } A = \\S_{ nk } B /\\ [ret]_s = zero32 /\\ [a2]_s = zero32)) /\\\n    (var_e X |--> A ** var_e b |--> B) s h))).\n\napply frame_rule_R.\napply multi_lt_triple.multi_lt_triple => //; by Uniq_uniq r0.\nby Inde_frame.\nmove=> ?; by Inde_mult.\n\nrewrite /while.entails => s h [[[Ha [Hb [Hk [HX [Ha0 [HZsgn [Ha1 Hmem]]]]]]] Ha1''] Ha1'].\nmove/leZP in Ha1''. rewrite /= in Ha1'. move/eqP in Ha1'.\nrewrite store.get_r0 Z2uK // in Ha1'.\ncase: Ha1 => Ha1.\n  by rewrite s2Z_u2Z_pos // in Ha1.\ncase: Ha1 => Ha1; last first.\n  rewrite Ha1 in Ha1''. by move/leZP : Ha1''.\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1.\nrepeat (split=> //).\nmove: Hh2; apply monotony => // h'; exact: mapstos_ext.\nrepeat (split=> //).\nby rewrite -HZsgn Ha1.\n\nrewrite /while.entails => s h Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\ncase: Hh1 => Hk [Hb [HX [HSum Hmem]]].\ncase: Hh2 => Ha [Hsgn Hh2].\nrepeat (split=> //).\nrewrite conAE.\nCompose_sepcon h2 h1; first by [].\nmove: Hmem. apply monotony => // h'; exact: mapstos_ext.\n\n(** ifte_beq ret, r0 *)\n\napply while.hoare_ifte.\n\napply while.hoare_ifte.\n\napply hoare_addiu with (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\\n  u2Z [k ]_ s = Z_of_nat nk /\\ [X ]_ s = ptr /\\ [a3]_s = zero32 /\\\n  sgZ (s2Z slen) = 1 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h /\\\n  \\S_{ nk } A = \\S_{ nk } B).\n\nmove=> s h [ [ [Ha [Hb [Hk [HX [Hslen [mem HSum]]]]]] Hret] Ha2].\nrewrite /wp_addiu.\nrepeat Reg_upd.\nrepeat (split => //).\nby rewrite sext_Z2u // addi0.\nby Assert_upd.\nrewrite /= in Hret Ha2.\nmove/eqP/u2Z_inj in Hret.\nmove/eqP/u2Z_inj in Ha2.\nrewrite store.get_r0 in Hret Ha2.\ncase: HSum => Hsum.\n  rewrite Hret Ha2 in Hsum.\n  case: Hsum => _ [Hsum _].\n  by apply Z2u_dis in Hsum.\ncase: Hsum => Hsum; last by tauto.\nrewrite Ha2 in Hsum.\ncase: Hsum => _ [_ Hsum].\nby apply Z2u_dis in Hsum.\n\n(** sw r0 zero16 a *)\n\napply hoare_sw_back'.\nmove=> s h [Ha [Hb [Hk [HX [Ha3 [Hslen [mem HSum]]]]]]].\nexists (int_e slen).\nrewrite !conAE /= in mem.\nmove: mem; apply monotony => // h'.\napply mapsto_ext => //=; by rewrite sext_Z2u // addi0.\napply currying => h'' Hh''.\nexists A (* NB: whatever *), (Z2s 32 0).\nrepeat (split => //).\n\nby rewrite Z2sK.\n\nby rewrite Z2sK //= Hslen mul1Z HSum subZZ.\n\nrewrite conCE in Hh''.\nrewrite !conAE /=.\nmove: Hh''; apply monotony => // h3.\napply mapsto_ext => /=.\nby rewrite sext_Z2u // addi0.\nrewrite store.get_r0.\napply u2Z_inj.\nby rewrite u2Z_Z2s_pos // Z2uK.\nby rewrite Ha3 Z2uK.\nby rewrite Z2sK //= Hslen mul1Z HSum subZZ.\n\n(** multi_sub k X b X a0 a1 a2 a3 a4 ret *)\n\napply hoare_prop_m.hoare_stren with (fun s h => \\S_{ nk } A > \\S_{ nk } B /\\\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_ s = ptr /\\ sgZ (s2Z slen) = 1 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h).\n\nrewrite /while.entails => s h [[[Ha [Hb [Hk [HX [HZsgn [Hmem HSum]]]]]] Hret] Ha2].\nrewrite /= store.get_r0 Z2uK // in Hret.\nmove/eqP in Hret.\ncase: HSum => HSum.\n  case: HSum => _ [HSum _].\n  by rewrite HSum Z2uK in Hret.\nsplit; last by [].\nrewrite /= in Ha2.\nmove/eqP in Ha2.\nrewrite store.get_r0 Z2uK // in Ha2.\ncase: HSum => HSum; first by tauto.\ncase: HSum => _ [_ HSum].\nby rewrite HSum Z2uK in Ha2.\n\n(** multi_sub k X b X a0 a1 a2 a3 a4 ret *)\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => HAB.\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ sgZ (s2Z slen) = 1 /\\\n    (var_e a |--> slen :: ptr :: nil) s h )\n  (fun s h => [X ]_ s = ptr /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk/\\\n    (var_e X |--> A ** var_e b |--> B) s h)\n  (fun s h => exists A', size A' = nk /\\\n    [X ]_ s = ptr /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk/\\\n    [a3]_s = zero32 /\\\n    (var_e X |--> A' ** var_e b |--> B) s h /\\\n    \\S_{ nk } A' = \\S_{ nk } A - \\S_{ nk } B)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply multi_sub_u_u_L_triple_B_le_A => //.\nby Uniq_uniq r0.\nlia.\n\nrewrite /while.entails => s h [Ha [Hb [Hk [HX [HZsgn Hmem]]]]].\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1; last by [].\nrepeat (split => //).\nmove: Hh2. apply monotony => // h'; exact:  mapstos_ext.\n\nrewrite /while.entails => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh1 => A' [A'_nk [Hb [HX [Hk [Ha3 [Hh1 HSum]]]]]].\ncase: Hh2 => [Ha [HZsgn Hh2]].\nexists A', slen.\nrewrite Ha3 Z2uK // HZsgn !mul1Z mul0Z addZ0.\nrepeat (split => //).\n\nrewrite slen_not_weird HZsgn; ring.\n\nrewrite (proj2 (Zsgn_pos (\\S_{ nk } A - \\S_{ nk } B))) //; lia.\nrewrite conAE.\nCompose_sepcon h2 h1; first by [].\nmove: Hh1. apply monotony => // h'; exact: mapstos_ext.\n\n(** multi_sub k b X X a0 a1 a2 a3 a4 ret; *)\n\napply hoare_prop_m.hoare_stren with (fun s h => \\S_{ nk } A < \\S_{ nk } B /\\\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_ s = ptr /\\ sgZ (s2Z slen) = 1 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h).\n\nrewrite /while.entails => s h [[Ha [Hb [Hk [HX [HZsgn [Hmem HSum]]]]]] Hret].\nrewrite /= store.get_r0 Z2uK // in Hret.\nmove/eqP in Hret.\ncase: HSum => HSum; last first.\n  have {}HSum : [ret ]_ s = zero32 by tauto.\n  by rewrite HSum Z2uK in Hret.\nsplit; by [tauto | ].\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => HAB.\n\napply while.hoare_seq with (fun s h => exists A', size A' = nk /\\\n  [a ]_ s = va /\\ [b ]_ s = vb /\\ u2Z ([k ]_ s) = Z_of_nat nk /\\\n  [X ]_ s = ptr /\\ sgZ (s2Z slen) = 1 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A') ** var_e b |--> B) s h /\\\n  \\S_{ nk } A < \\S_{ nk } B /\\ [a3]_s = zero32 /\\\n  \\S_{ nk } A' = \\S_{ nk } B - \\S_{ nk } A).\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ sgZ (s2Z slen) = 1 /\\\n    (var_e a |--> slen :: ptr :: nil) s h )\n  (fun s h => ([b ]_ s) = vb /\\ ([X ]_ s) = ptr  /\\ u2Z ([k ]_ s) = Z_of_nat nk/\\\n    (var_e b |--> B ** var_e X |--> A) s h)\n  (fun s h => exists A', size A' = nk /\\\n    [b ]_ s = vb /\\ [X ]_ s = ptr /\\ u2Z ([k ]_ s) = Z_of_nat nk/\\\n    [a3]_s = zero32 /\\\n    (var_e b |--> B ** var_e X |--> A') s h /\\\n    \\S_{ nk } A' = \\S_{ nk } B - \\S_{ nk } A)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply multi_sub_u_u_R_triple_B_le_A => //.\nby Uniq_uniq r0.\nexact/ltZW.\n\nmove=> s h [Ha [Hb [Hk [HX [HZsgn Hmem]]]]].\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1; last by [].\nrepeat (split => //).\nrewrite conCE.\nmove: Hh2; apply monotony => h' //; exact: mapstos_ext.\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh1 => A' [A'_nk [Hb [HX [Hk [Ha3 [Hh1 HSum]]]]]].\ncase: Hh2 => Ha [HZsgn Hh2].\nexists A'; repeat (split => //).\nrewrite conAE.\nCompose_sepcon h2 h1; first by [].\nrewrite conCE.\nmove: Hh1; apply monotony => h' //; exact: mapstos_ext.\n\napply (hoare_prop_m.extract_exists extract_exists0) => A'.\n\n(** multi_negate_prg.negate a a0 *)\n\napply (before_frame\n  (fun s h => size A' = nk /\\ [a ]_ s = va /\\ [b ]_ s = vb /\\\n    u2Z ([k ]_ s) = Z_of_nat nk /\\ [X ]_ s = ptr /\\ sgZ (s2Z slen) = 1 /\\\n    (var_e b |--> B) s h /\\ \\S_{ nk } B > \\S_{ nk } A /\\\n    ([a3 ]_ s) = zero32 /\\ \\S_{ nk } A' = \\S_{ nk } B - \\S_{ nk } A)\n  (var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A')\n  (var_e a |--> cplt2 slen :: ptr :: nil ** int_e ptr |--> A')).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply multi_negate_triple; by Uniq_uniq r0.\n\nmove=> s h [A'_nk [Ha [Hb [Hk [HX [Hsgn [Hmem [B_A [Ha3 HSum]]]]]]]]].\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h1 h2; first by [].\nrepeat (split => //).\nexact: Z.lt_gt.\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase : Hh2 => A'_nk [Ha [Hb [Hk [HX [HZsgn [Hh2 [B_A [Ha3 HSum']]]]]]]].\nexists (cplt2 slen).\nrewrite s2Z_cplt2; last first.\n  rewrite weirdE2 slen_not_weird HZsgn; lia.\nrewrite Zsgn_Zopp Ha3 Z2uK // mul0Z addZ0.\nrepeat (split => //).\nrewrite slen_not_weird HZsgn mul1Z (proj2 (Zsgn_pos (Z_of_nat nk))) //; lia.\nrewrite HZsgn mul1Z (proj2 (Zsgn_neg (\\S_{ nk } A - \\S_{ nk } B))) //; lia.\nby Compose_sepcon h1 h2.\nrewrite HZsgn mul1Z HSum'; ring.\n\n(** addiu a3 r0 one16; *)\n\napply hoare_addiu with (fun s h => [a ]_ s = va /\\ [b ]_ s = vb /\\\n  u2Z [k ]_ s = Z_of_nat nk /\\ [X ]_ s = ptr /\\ [a0 ]_ s = slen /\\\n  sgZ (s2Z slen) = - 1 /\\ [a3]_s = one32 /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h).\n\nmove=> s h /= [[Ha [Hb [Hk [HX [Ha0 [Ha1' [Ha1'' Hmem]]]]]]] Ha1].\nmove/leZP in Ha1.\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split => //).\ncase: Ha1'' => Ha1''.\nlia.\ncase: Ha1'' => Ha1''.\nlia.\nby rewrite -Ha1' Ha1''.\nby rewrite add0i sext_Z2u.\nAssert_upd.\nmove=> s' h' x v /= [] // ?; subst a3; by Reg_upd.\n\n(** multi_add k a3 b X X a0 a1 a2 *)\n\napply while.hoare_seq with (fun s h => exists A' slen',\n  size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat nk /\\\n  sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B) /\\\n  ((var_e a |--> slen' :: ptr :: nil ** int_e ptr |--> A') ** var_e b |--> B) s h /\\\n  u2Z (store.lo s) <= 1 /\\\n  sgZ (s2Z slen') * (\\S_{ nk } A' + u2Z (store.lo s) * \\B^nk) =\n  sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B).\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ sgZ (s2Z slen) = -1 /\\\n    (var_e a |--> slen :: ptr :: List.nil) s h)\n  (fun s h => [a3]_s = one32 /\\ [b ]_ s = vb /\\ [X ]_ s = ptr /\\\n    u2Z ([k ]_ s) = Z_of_nat nk /\\ (var_e b |--> B ** var_e X |--> A) s h)\n  (fun s h => exists A', size A' = nk /\\ [b ]_ s = vb /\\ [X ]_ s = ptr /\\\n    (var_e b |--> B ** var_e X |--> A') s h/\\ u2Z (store.lo s) <= 1 /\\\n    \\S_{ nk } A' + u2Z (store.lo s) * \\B^nk = \\S_{ nk } B + \\S_{ nk } A)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply multi_add_u_u_triple => //; by Uniq_uniq r0.\n\nmove=> s h /= [Ha [Hb [Hk [HX [Ha0 [Ha1' [Ha3 Hmem]]]]]]].\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\ncase: Hh1 => h11 [h12 [h11_d_h12 [h11_U_h12 [Hh11 Hh12]]]].\nCompose_sepcon (h12 \\U h2) h11.\nrepeat (split=> //).\nCompose_sepcon h2 h12; first by [].\nexact: assert_m.mapstos_ext Hh12.\nby [].\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh1 => A' [A'_nk [r_b [HX [Hh1 [Hm HSum]]]]].\ncase: Hh2 => Ha [HZsgn Hh2].\nexists A', slen; repeat (split => //).\nrewrite HZsgn mulN1Z (proj2 (Zsgn_neg (- \\S_{ nk } A - \\S_{ nk } B))) //.\nmove: (min_lSum nk A) => ?; lia.\nrewrite conAE .\nCompose_sepcon h2 h1; first by [].\nrewrite conCE.\nmove: Hh1; apply assert_m.monotony => // h'; exact: assert_m.mapstos_ext.\nrewrite HZsgn HSum; ring.\n\n(** mflo a3 *)\n\napply hoare_mflo'.\nmove=> s h /= [A' [slen' [A'_nk [r_a [r_b [slen'_nk [HZsgn [Hmem [Hlo HSum]]]]]]]]].\nrewrite /wp_mflo.\nexists A', slen'.\nrepeat Reg_upd.\nrepeat (split => //).\nAssert_upd.\nmove=> s' h' x v /= [] // ?; subst a3; by Reg_upd.\nQed.\n\nLemma multi_sub_s_u_triple : forall k a b a0 a1 a2 a3 a4 ret X,\nuniq(k, a, b, a0, a1, a2, a3, a4, ret, X, r0) ->\nforall nk va vb ptr, nk <> O -> Z_of_nat nk < 2 ^^ 31 ->\n  u2Z ptr + 4 * Z_of_nat nk < \\B^1 -> u2Z vb + 4 * Z_of_nat nk < \\B^1 ->\nforall A B, size A = nk -> size B = nk ->\nforall slen, s2Z slen = sgZ (s2Z slen) * Z_of_nat nk ->\n    sgZ (s2Z slen) = sgZ (sgZ (s2Z slen) * \\S_{ nk } A) ->\n{{ fun s h => [ a ]_s = va /\\ [ b ]_s = vb /\\ u2Z [ k ]_s = Z_of_nat nk /\\\n   ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h }}\nmulti_sub_s_u k a b a0 a1 a2 a3 a4 ret X\n{{ fun s h => exists A', exists slen', size A' = nk /\\ [a]_s = va /\\ [b]_s = vb /\\\n  s2Z slen' = sgZ (s2Z slen') * Z_of_nat nk /\\\n  sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B) /\\\n  ((var_e a |--> slen' :: ptr :: nil ** int_e ptr |--> A') ** var_e b |--> B ) s h /\\\n  u2Z ([a3]_ s) <= 1 /\\\n  sgZ (s2Z slen') * (\\S_{ nk } A' + u2Z ([a3]_s) * \\B^nk) =\n  sgZ (s2Z slen) * \\S_{ nk } A - \\S_{ nk } B }}.\nProof.\n(* NB: similar to multi_add_s_u_triple *)\nmove=> k a b a0 a1 a2 a3 a4 ret X Hregs nk va vb ptr Hnk Hnk' ptr_fit vb_fit A B\n  len_A len_B slen slen_no_weird valid_A.\nrewrite /multi_sub_s_u.\n\n(** multi_is_zero k b a0 a1 a2 *)\n\napply while.hoare_seq with (fun s h => [a]_s = va /\\ [b]_s = vb /\\\n  u2Z [k]_s = Z_of_nat nk /\\\n  ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h /\\\n  ((0 = \\S_{ nk } B -> [a2]_s = one32) /\\ (0 < \\S_{ nk } B -> [a2]_s = zero32))).\n\napply (before_frame\n  (fun s h => [a ]_ s = va /\\ (var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) s h)\n  (fun s h => u2Z [ k ]_s = Z_of_nat nk /\\ [b]_s = vb /\\ (var_e b |--> B) s h)\n  (fun s h => u2Z [ k ]_s = Z_of_nat nk /\\ [b]_s = vb /\\ (var_e b |--> B) s h  /\\\n    ((0 = \\S_{ nk } B -> [a2]_s = one32) /\\ (0 < \\S_{ nk } B -> [a2]_s = zero32)))).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\n  apply multi_is_zero_u_triple => //; by Uniq_uniq r0.\n\nmove=> s h [Ha [Hb [Hk mem]]].\ncase: mem =>  h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nby Compose_sepcon h2 h1.\n\nmove => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\nrepeat (split; first by tauto).\nsplit; last by tauto.\nCompose_sepcon h2 h1; tauto.\n\n(** ifte (bne a2 r0) *)\n\napply while.hoare_ifte.\n\n(** addiu a3 r0 zero16 *)\n\napply hoare_addiu'.\nmove=> s h [ [Ha [Hb [Hk [mem Hret]]]] Ha2].\nrewrite /= in Ha2.\nmove/eqP in Ha2.\nmove: (min_lSum nk B).\ncase/Z_le_lt_eq_dec => Hsum.\napply (proj2 Hret) in Hsum.\nby rewrite Hsum Z2uK // store.get_r0 Z2uK // in Ha2.\nexists A, slen.\nrepeat Reg_upd; repeat (split => //).\nrewrite -Hsum subZ0; exact valid_A.\nby Assert_upd.\nby rewrite sext_Z2u // addi0 Z2uK.\nrewrite sext_Z2u // addi0 Z2uK // mul0Z addZ0 -Hsum; ring.\n\n(** multi_sub_s_u0 k a b a0 a1 a2 a3 a4 ret X *)\n\napply hoare_prop_m.hoare_stren with (!(fun s => 0 < \\S_{ nk } B) **\n  (fun s h => [a ]_ s = va /\\[b ]_ s = vb /\\ u2Z [k ]_ s = Z_of_nat nk /\\\n    ((var_e a |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e b |--> B) s h)).\n\nmove=> s h [[Ha [Hb [Hk [mem Hret]]]] Ha2].\nrewrite /= negbK in Ha2.\nmove/eqP/u2Z_inj in Ha2.\nmove: (min_lSum nk B).\ncase/Z_le_lt_eq_dec => Hsum; last first.\n apply (proj1 Hret) in Hsum.\n rewrite Hsum store.get_r0 in Ha2.\n by apply Z2u_dis in Ha2.\nby Compose_sepcon heap.emp h.\n\napply pull_out_bang => nk_B.\nexact: multi_sub_s_u0_triple.\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_u_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1913996541559289}}
{"text": "Require Import Platform.AutoSep Platform.Wrap Platform.StringOps Platform.Malloc Platform.ArrayOps Platform.Buffers Platform.Bags.\nRequire Import Platform.SinglyLinkedList Platform.ListSegment 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\nOpaque mult.\nLocal Infix \";;\" := SimpleSeq : SP_scope.\n\nSection Select.\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  (* Run this command on every matching row. *)\n  Variable body : chunk.\n\n  Definition inv (V_rw V_data : W) := (Ex head, Ex done, Ex remaining, Ex p,\n    tptr =*> head * lseg done head V_rw\n    * (V_rw ==*> V_data, p) * sll remaining p\n    * rows sch head done * rows sch head remaining\n    * [| freeable V_rw 2 |] * [| V_rw <> 0 |])%Sep.\n\n  Definition Select' : chunk := (\n    rw <-* tptr;;\n\n    [Al bs, Al a : A, Al head, Al done, Al remaining,\n      PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n        * tptr =*> head * lseg done head (V rw) * sll remaining (V rw)\n        * rows sch head done * rows sch head remaining * invPre a V\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 head, Al done, Al remaining,\n        PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n          * [| V rw <> 0 |] * tptr =*> head * lseg done head (V rw) * sll (V data :: remaining) (V rw)\n          * rows sch head remaining * rows sch head done * row sch (V data) * invPre a V\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 * lseg done head (V rw) * sll (V data :: remaining) (V rw)\n          * rows sch head remaining * rows sch head done)%Sep\n      invPost\n      sch data cond cond;;\n\n      If (\"matched\" = 0) {\n        Skip\n      } else {\n        body\n      };;\n\n      rw <-* rw + 4;;\n\n      Assert [Al bs, Al a : A, Al head, Al done, Al remaining,\n        PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n          * tptr =*> head * lseg_append (done ++ V data :: nil) head (V rw) * sll remaining (V rw)\n          * rows sch head (done ++ V data :: nil) * rows sch head remaining * invPre a V\n        POST[R] array8 bs (V \"buf\") * invPost a V R]\n    }\n  )%SP.\n\n  Definition sinvar :=\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 * invPre a V\n    POST[R] array8 bs (V \"buf\") * invPost a V R.\n\n  Definition spost :=\n    Al bs, Al a : A,\n    PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |] * [| inputOk V (exps cond) |]\n      * row sch (V data) * inv (V rw) (V data) * 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    end.\n\n  Definition noOverlapExps := List.Forall noOverlapExp.\n\n  Notation SelectVcs := (fun im ns res =>\n    (~In \"rp\" ns) :: incl svars ns :: (rw <> \"rp\")%type :: (data <> \"rp\")%type\n    :: incl baseVars 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\" -> 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\" -> sel V x = sel V' x)\n      -> invPost a V R = invPost a V' R)\n    :: (forall pre mn H,\n      (forall specs st, interp specs (pre st)\n        -> interp specs (spost true (fun w => w) ns res st))\n      -> vcs (VerifCond (toCmd body mn (im := im) H ns res pre)))\n    :: (forall specs pre mn H st,\n      (forall specs st, interp specs (pre st)\n        -> interp specs (spost true (fun w => w) ns res st))\n      -> interp specs (Postcondition (toCmd body mn (im := im) H ns res pre) st)\n      -> interp specs (spost true (fun w => w) ns res st))\n    :: \"array8\"!\"equal\" ~~ im ~~> ArrayOps.equalS\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    :: 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    :: goodSize (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  Ltac q :=\n    repeat match goal with\n             | [ H : interp ?x ?y, _ : context[Binop _ _ Plus (immInR (natToW 4) _)] |- _ ] =>\n               apply compileEqualities_post in H; auto; intros;\n                 try match goal with\n                       | [ H : interp x y |- _ ] => clear H\n                     end;\n                 try match goal with\n                       | [ |- context[_ ===> _] ] => intros;\n                         match goal with\n                           | [ H : importsGlobal _ |- _ ] => clear dependent H\n                         end\n                     end;\n                 pre; prep; evalu;\n                 try match goal with\n                       | [ _ : _ = _ :: ?ls |- _ ] => do 4 eexists; exists ls\n                     end\n             | [ H : interp ?x ?y |- _ ] => apply compileEqualities_post in H; auto; intros;\n               try match goal with\n                     | [ H : interp x y |- _ ] => clear H\n                   end\n             | [ H : _ |- vcs _ ] => apply H; intros; pre; unfold inv\n             | [ |- vcs _ ] => apply compileEqualities_vcs; auto; intros\n             | [ H : interp _ (Postcondition (toCmd body _ _ _ _ _) _) |- _ ] =>\n               invoke1; unfold inv in *\n           end; t.\n\n  Definition Select : chunk.\n    refine (WrapC Select'\n      sinvar\n      sinvar\n      SelectVcs\n      _ _); abstract (wrap0; abstract q).\n  Defined.\nEnd Select.\n\nGlobal Opaque inv.\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/RelDbSelect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.19139965228100403}}
{"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(** * The whole compiler and its proof of semantic preservation *)\n\n(** Libraries. *)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Smallstep.\n\nRequire Import compcert.cfrontend.Clight.\n(*WE NEED THIS: Require Import VST.sepcomp.Clight_eff.*)\n\nRequire Import VST.ccc26x86.Asm.\nRequire Import VST.ccc26x86.Asm_eff.\n\nRequire Import VST.sepcomp.simulations.\nRequire Import VST.sepcomp.effect_semantics.\n\nAxiom transf_clight_program : Clight.program -> res Asm.program.\n\n(*WE NEED THIS:*) Axiom CL_core : Type.\n(*WE NEED THIS:*) Axiom CL_eff_sem1 : @EffectSem (Genv.t Clight.fundef cfrontend.Ctypes.type) CL_core.\n\n(* Axiomatization of Theorem 18, Compiler Correctness: *)\nAxiom transf_clight_program_correct:\n  forall p tp (LNR: list_norepet (map fst (prog_defs p))),\n  transf_clight_program p = OK tp ->\n  SM_simulation.SM_simulation_inject\n    CL_eff_sem1 Asm_eff_sem (Genv.globalenv p) (Genv.globalenv tp).\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/CompositionalCompiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3380771308191989, "lm_q1q2_score": 0.1913579273194986}}
{"text": "From hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising Require Import Configuration TView View Time Event Cell Thread Memory.\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import Execution_eco.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_bob imm_s_ppo.\n\nRequire Import PArith.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\n\nFrom imm Require Import TraversalConfig.\nFrom imm Require Import Traversal.\nFrom imm Require Import SimTraversal.\n\nRequire Import MaxValue.\nRequire Import ViewRel.\nFrom imm Require Import ViewRelHelpers.\nRequire Import SimulationRel.\nRequire Import SimulationPlainStepAux.\nRequire Import SimulationRelAux.\nRequire Import MemoryAux.\nRequire Import SimState.\n\nSet Implicit Arguments.\n\n(* It's a version of Configuration.step which doesn't require\n   consistency of the new configuration. *)\nInductive plain_step :\n  forall (e:option Event.t) (tid:Ident.t)\n         (c1 c2:Configuration.t), Prop :=\n| plain_step_intro\n    pf e tid c1 lang st1 lc1 e2 st3 lc3 sc3 memory3\n    (TID: IdentMap.find tid c1.(Configuration.threads) = Some (existT _ lang st1, lc1))\n    (STEPS: rtc (@Thread.tau_step _) (Thread.mk _ st1 lc1 c1.(Configuration.sc) c1.(Configuration.memory)) e2)\n    (STEP: Thread.step pf e e2 (Thread.mk _ st3 lc3 sc3 memory3)):\n    plain_step (ThreadEvent.get_event e) tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) c1.(Configuration.threads)) sc3 memory3)\n.\n\nLemma pair_app :\n  forall (A B : Prop), A -> (A -> A /\\ B) -> A /\\ B.\nProof using. ins. intuition. Qed.\n\nSection PlainStepBasic.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\nVariable CON : imm_consistent G sc.\n\nNotation \"'E'\" := G.(acts_set).\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).\n\nNotation \"'fr'\" := G.(fr).\nNotation \"'coe'\" := G.(coe).\nNotation \"'coi'\" := G.(coi).\nNotation \"'deps'\" := G.(deps).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'detour'\" := G.(detour).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sw'\" := G.(sw).\n\nNotation \"'lab'\" := G.(lab).\n(* Notation \"'loc'\" := (loc lab). *)\n(* Notation \"'val'\" := (val lab). *)\n(* Notation \"'mod'\" := (mod lab). *)\n(* Notation \"'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 \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (fun a => is_true (is_rlx lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Acqrel'\" := (fun a => is_true (is_acqrel lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'W_ex'\" := G.(W_ex).\nNotation \"'W_ex_acq'\" := (W_ex \u2229\u2081 (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\n\nDefinition msg_preserved memory memory' :=\n  forall loc ts from msg (INMEM : Memory.get loc ts memory = Some (from, msg)),\n    exists from', Memory.get loc ts memory' = Some (from', msg).\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 val released\n           (ADD : Memory.add memory loc from to val released 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 val2 val3 released2 release3\n           (SPLIT : Memory.split\n                      memory loc ts1 ts2 ts3\n                      val2 val3 released2 release3 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\nLemma full_simrel_step thread PC PC' T T' label f_to f_from\n      (COVE  : covered T' \u2286\u2081 E)\n      (ISSE  : issued  T' \u2286\u2081 E)\n      (COVIN : covered T \u2286\u2081 covered T')\n      (ISSIN : issued T \u2286\u2081 issued T')\n      (NINCOV : covered T' \\\u2081 covered T \u2286\u2081 Tid_ thread)\n      (NINISS : issued  T' \\\u2081 issued  T \u2286\u2081 Tid_ thread)\n      (PCSTEP : plain_step label thread PC PC')\n      (CLOSED_PRES :\n         closedness_preserved PC.(Configuration.memory) PC'.(Configuration.memory))\n      (MSG_PRES :\n         msg_preserved PC.(Configuration.memory) PC'.(Configuration.memory))\n      (TPEQ : forall thread,\n          IdentMap.In thread PC.(Configuration.threads) <->\n          IdentMap.In thread PC'.(Configuration.threads))\n      (SIMREL_THREAD : simrel_thread G sc PC' thread T' f_to f_from sim_normal)\n      (SIMREL : simrel G sc PC T f_to f_from) :\n  simrel G sc PC' T' f_to f_from.\nProof using WF.\n  red. splits; auto.\n  { apply SIMREL_THREAD. }\n  cdes SIMREL.\n  intros thread' TP'.\n  destruct (Ident.eq_dec thread thread') as [|NEQ]; subst.\n  { apply SIMREL_THREAD. }\n  assert (IdentMap.In thread' PC.(Configuration.threads)) as TP.\n  { by apply TPEQ. }\n  specialize (THREADS thread' TP).\n  cdes THREADS.\n  assert (IdentMap.find thread' (Configuration.threads PC') =\n          Some (existT _ (PromiseLTS.thread_lts thread') state,\n                local)) as TID.\n  { destruct PCSTEP. simpls. rewrite IdentMap.gso; auto. }\n  assert\n  (forall a : actid, tid a = thread' -> covered T' a -> covered T a) as PP.\n  { intros a TT YY.\n    destruct (classic (covered T a)) as [GG|GG]; [done|].\n    exfalso.\n    assert (tid a = thread) as RR; [|by subst].\n    by apply NINCOV; split. }\n  cdes SIMREL_THREAD. cdes COMMON. cdes LOCAL.\n  red; splits; simpls.\n  rewrite TID.\n  exists state; exists local; splits; auto.\n  2: { red. ins.\n       edestruct SIM_PROM as [w H]; eauto.\n       des. exists w; splits; auto. }\n  5: { eapply sim_state_other_thread_step; eauto; desf. }\n  4: { by red; splits; ins; apply CLOSED_PRES; apply MEM_CLOSE. }\n  3: { destruct T as [C I]. destruct T' as [C' I'].\n       eapply sim_tview_other_thread_step.\n       2: by apply COVIN.\n       all: eauto.\n       etransitivity; [apply TCCOH|]. done. }\n  { clear TNNULL0 TNNULL.\n    ins. destruct (classic (thread'0 = thread)) as [|TNEQ']; subst.\n    { apply or_comm. cdes SIMREL_THREAD.\n      rewrite LLH0 in TID'. inv TID'. clear TID'.\n      eapply PROM_DISJOINT0; eauto. }\n    assert (IdentMap.find thread'0 (Configuration.threads PC) = Some (langst', local'))\n      as TT.\n    { destruct PCSTEP. simpls. rewrite IdentMap.gso in TID'; auto. }\n    eapply PROM_DISJOINT; eauto. }\n  red. ins. unnw.\n  edestruct SIM_MEM0 as [rel]; eauto.\n  simpls; desc.\n  exists rel; splits; auto.\n  intros BTID.\n  assert (~ covered T' b <-> ~ covered T b) as CCB.\n  { split; intros CC1 CC2.\n      by apply COVIN in CC2.\n      assert (tid b = thread) as TT.\n      2: by subst; desf.\n        by apply NINCOV; split. }\n  assert (issued T' b <-> issued T b) as IIB.\n  { split; auto.\n    intros II.\n    destruct (classic (issued T b)) as [|NN]; [done|].\n    assert (tid b = thread) as TT.\n    2: by subst; desf.\n      by apply NINISS; split. }\n  rewrite CCB.\n  edestruct SIM_MEM as [rel']; eauto.\n  { by apply IIB. }\n  simpls; desc.\n  intros CC.\n  destruct H2; auto.\n  assert (rel' = rel); [|subst; split; vauto].\n  { cdes COMMON0. eapply PROM_IN_MEM0 in H; eauto.\n    rewrite INMEM in H. inv H. }\n  destruct H0 as [p_rel H0]; desc.\n  eexists; split; eauto.\n  desf.\n  { left; splits; auto.\n    intros [y HH]. apply NINRMW.\n    exists y. apply seq_eqv_l in HH; destruct HH as [ISSY HH]. \n    apply seq_eqv_l; split; auto.\n    destruct (classic (issued T y)) as [|NISS]; [done|exfalso].\n    destruct (classic (tid y = thread)) as [|TNEQ]; subst.\n    2: by apply TNEQ; apply NINISS; split.\n    assert ((rfe \u2a3e rmw) y b) as RFERMW.\n    2: { apply NISS.\n         apply IIB in ISSB. apply TCCOH in ISSB.\n         apply ISSB.\n         exists b; apply seq_eqv_r; split; auto.\n         destruct RFERMW as [oo [RFE RMW]].\n         apply (dom_l WF.(wf_rfeD)) in RFE.\n         apply seq_eqv_l in RFE. destruct RFE as [WY RFE].\n         apply seq_eqv_l. split; auto.\n         apply ct_step. right.\n         exists oo. split; [by apply RFE|].\n           by apply rmw_in_ppo_loc. }\n    hahn_rewrite rfi_union_rfe in HH. hahn_rewrite seq_union_l in HH.\n    destruct HH as [HH|]; [exfalso|done].\n    assert (W y) as WY.\n    { cdes COMMON0. by apply TCCOH0. }\n    assert (~ is_init y) as NIN.\n    { intros DD. apply NISS. eapply w_covered_issued; eauto.\n      split; auto. apply TCCOH.\n      split; auto. }\n    assert (sb y b) as SBYB.\n    { edestruct HH as [z [RFI RMW]].\n      eapply (@sb_trans G); [by apply WF.(rfi_in_sbloc'); eauto|].\n        by apply WF.(rmw_in_sb). }\n    edestruct (sb_tid_init SBYB); desf. }\n  right. exists p; splits; auto.\n  assert (issued T' p) as ISSP'.\n  { apply ISSIN. apply ISSP. }\n  assert (loc lab p = Some l) as LOCP.\n  { simpls. erewrite wf_rfrmwl; eauto. }\n  assert (exists p_v', val lab p = Some p_v') as [p_v' VALP].\n  { apply WF.(wf_rfrmwD) in INRMW.\n    unfold val, is_w in *. desf.\n    all: eexists; eauto. }\n  eapply MSG_PRES in P_INMEM. desc.\n  edestruct (SIM_MEM0 l) as [p_rel''].\n  { cdes COMMON0. apply TCCOH0. apply ISSP'. }\n  all: eauto; simpls.\n  desc.\n  rewrite P_INMEM in INMEM1. inv INMEM1.\n  eexists; eexists; splits; eauto.\nQed.\n\nLemma max_event_cur PC T f_to f_from l e thread foo local smode\n      (SIMREL_THREAD : simrel_thread G sc PC thread T f_to f_from smode)\n      (NEXT : next G (covered T) e)\n      (TID_E : tid e = thread)\n      (LOC : loc lab e = Some l)\n      (TID: IdentMap.find thread PC.(Configuration.threads) = Some (foo, local)):\n  exists p_max,\n    \u27ea NEQ : p_max <> e \u27eb /\\\n    \u27ea CCUR : urr G sc l p_max e \u27eb /\\\n    \u27ea LB : Time.le\n      (View.rlx (TView.cur (Local.tview local)) l)\n      (f_to p_max) \u27eb.\nProof using WF CON.\n  cdes SIMREL_THREAD. cdes COMMON. cdes LOCAL.\n  red in SIM_TVIEW; desf.\n  red in CUR; desf.\n  specialize (CUR l); red in CUR; desc.\n  \n  assert (E e) as EE.\n  { apply NEXT. }\n  assert (~ is_init e) as NINE.\n  { intros HH. apply NEXT. by apply TCCOH. }\n\n  destruct MAX as [[MAX MAX'] | MAX].\n  { unfold LocFun.find in MAX'.\n    rewrite MAX'; ins.\n    exists (InitEvent l); splits; [ | | by apply Time.bot_spec].\n    { intros H; subst; simpls. }\n    apply hb_in_urr.\n    apply seq_eqv_l; split; red; [|right].\n    { by unfold is_w, loc; rewrite WF.(wf_init_lab). }\n    apply sb_in_hb.\n    apply init_ninit_sb; auto.\n    apply WF.(wf_init). eexists; eauto. }\n  desf.\n  exists a_max. apply and_assoc; split; auto.\n  red in INam; red in INam.\n  destruct INam as [y CCUR].\n  red in CCUR; hahn_rewrite <- seqA in CCUR.\n  apply seq_eqv_r in CCUR; destruct CCUR as [CCUR Y'].\n  apply seq_eqv_r in CCUR; destruct CCUR as [CCUR Y].\n  assert (hb y e) as HBYE.\n  { apply sb_in_hb.\n    assert (E y) as EY.\n    { eapply (@coveredE G) in Y'; eauto. }\n    destruct Y as [Y | Y].\n    2: by apply init_ninit_sb.\n    destruct (same_thread G e y) as [[ZZ|ZZ]|ZZ]; subst; auto.\n    { by apply NEXT in Y'. }\n    exfalso.\n    assert (covered T e) as Z.\n    { apply TCCOH in Y'.\n      apply Y'. eexists; apply seq_eqv_r; split; eauto. }\n      by apply NEXT in Z. }\n  assert ((urr G sc l \u2a3e hb) a_max e) as UH.\n  { exists y; split; auto. }\n  splits.\n  { intros H; subst; eapply urr_hb_irr; eauto.\n    all: apply CON. }\n  apply urr_hb.\n  destruct UH as [z [UH HH]].\n  eexists; split; eauto.\nQed.\n\nEnd PlainStepBasic.\n", "meta": {"author": "weakmemory", "repo": "promising1ToImm", "sha": "f27e87f0c2d037b30f0bc13763af39a11bb949a1", "save_path": "github-repos/coq/weakmemory-promising1ToImm", "path": "github-repos/coq/weakmemory-promising1ToImm/promising1ToImm-f27e87f0c2d037b30f0bc13763af39a11bb949a1/src/PlainStepBasic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.19134846244231382}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Data.Eq.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.ListMapT.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.Util.HListBuild.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.Util.Forwardy.\nRequire Import MirrorCore.Instantiate.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nPolymorphic Inductive hlist_Forall2@{A B C}\n            {T : Type@{A}} (F : T -> Type@{B}) (G : T -> Type@{C}) (P : forall t, F t -> G t -> Prop)\n: forall ls, hlist F ls -> hlist G ls -> Prop :=\n| hlist_Forall2_nil : hlist_Forall2 P Hnil Hnil\n| hlist_Forall2_cons : forall l ls x xs y ys,\n                         @P l x y ->\n                         hlist_Forall2 (ls := ls) P xs ys ->\n                         hlist_Forall2 P (Hcons x xs) (Hcons y ys).\n\nSection subst.\n  Variable T : Type.\n  Variable typ : Set.\n  Variable expr : Set.\n  Context {RType_type : RType typ}.\n  Context {RTypeOk_type : RTypeOk}.\n  Context {Expr_expr : Expr _ expr}.\n  Context {ExprOk_expr : ExprOk _}.\n\n  Class Subst :=\n  { subst_lookup : uvar -> T -> option expr\n  ; subst_domain : T -> list uvar\n  }.\n\n  Class SubstOk (S : Subst) : Type :=\n  { WellFormed_subst : T -> Prop\n  ; substD : forall (tus tvs : tenv typ), T -> option (exprT tus tvs Prop)\n  ; substD_lookup\n    : forall s uv e,\n        WellFormed_subst s ->\n        subst_lookup uv s = Some e ->\n        forall tus tvs sD,\n          substD tus tvs s = Some sD ->\n          exists t val get,\n            nth_error_get_hlist_nth _ tus uv = Some (@existT _ _ t get) /\\\n            exprD tus tvs t e = Some val /\\\n            forall us vs,\n              sD us vs ->\n              get us = val us vs\n  ; WellFormed_domain : forall s ls,\n      WellFormed_subst s ->\n      subst_domain s = ls ->\n      (forall n, In n ls <-> subst_lookup n s <> None)\n  ; lookup_normalized : forall s e u,\n      WellFormed_subst s ->\n      subst_lookup u s = Some e ->\n      forall u' e',\n        subst_lookup u' s = Some e' ->\n        mentionsU u' e = false\n  }.\n\n  Class SubstUpdate :=\n  { subst_set : uvar -> expr -> T -> option T\n  }.\n\n  Class SubstUpdateOk (S : Subst) (SU : SubstUpdate) (SOk : SubstOk S) :=\n  { substR : forall (tus tvs : tenv typ), T -> T -> Prop\n  ; Reflexive_substR :> forall tus tvs, Reflexive (substR tus tvs)\n  ; Transitive_substR :> forall tus tvs, Transitive (substR tus tvs)\n  ; set_sound\n      (** TODO(gmalecha): This seems to need to be rephrased as well **)\n    : forall uv e s s',\n        subst_set uv e s = Some s' ->\n        WellFormed_subst s ->\n        WellFormed_subst s' /\\\n        (subst_lookup uv s = None -> (* How important is this? *)\n         forall tus tvs t val get sD,\n           substD tus tvs s = Some sD ->\n           nth_error_get_hlist_nth typD tus uv = Some (@existT _ _ t get) ->\n           exprD tus tvs t e = Some val ->\n           exists sD',\n             substD tus tvs s' = Some sD' /\\\n             substR tus tvs s s' /\\\n             forall us vs,\n               sD' us vs <->\n               (sD us vs /\\ get us = val us vs))\n  }.\n\n  Class SubstOpen : Type :=\n  { subst_drop : uvar -> T -> option T\n  ; subst_weakenU : nat -> T -> T\n  }.\n\n  Fixpoint models (tus tvs : tenv typ) (tus' : tenv typ) (es : list (option expr))\n  : option (hlist typD tus' -> exprT tus tvs Prop) :=\n    match tus' as tus' , es\n          return option (hlist typD tus' -> exprT tus tvs Prop)\n    with\n      | nil , nil => Some (fun _ _ _ => True)\n      | tu' :: tus' , None :: es =>\n        match models (tus ++ tu' :: nil) tvs tus' es with\n          | None => None\n          | Some x => Some (fun h us vs =>\n                              x (hlist_tl h) (hlist_app us (Hcons (hlist_hd h) Hnil)) vs)\n        end\n      | tu' :: tus' , Some e :: es =>\n        match models (tus ++ tu' :: nil) tvs tus' es with\n          | None => None\n          | Some x =>\n            match exprD (tus ++ tu' :: tus') tvs tu' e with\n              | None => None\n              | Some eD =>\n                Some (fun h us vs =>\n                           hlist_hd h = eD (hlist_app us h) vs\n                        /\\ x (hlist_tl h) (hlist_app us (Hcons (hlist_hd h) Hnil)) vs)\n            end\n        end\n      | _ , _ => None\n    end.\n\n  Class SubstOpenOk (S : Subst) (SO : SubstOk S) (OS : SubstOpen) : Type :=\n  { drop_sound\n    : forall s s' u,\n        subst_drop u s = Some s' ->\n        WellFormed_subst s ->\n        WellFormed_subst s' /\\\n        exists e,\n          subst_lookup u s = Some e /\\\n          subst_lookup u s' = None /\\\n          (forall u', u' <> u -> subst_lookup u' s = subst_lookup u' s') /\\\n          forall tus tu tvs sD,\n            u = length tus ->\n            substD (tus ++ tu :: nil) tvs s = Some sD ->\n            exists sD',\n              substD tus tvs s' = Some sD' /\\\n              exists eD,\n                exprD tus tvs tu e = Some eD /\\\n                forall us vs,\n                  sD' us vs <->\n                  sD (hlist_app us (Hcons (eD us vs) Hnil)) vs\n  ; substD_weakenU\n    : forall n s s',\n        subst_weakenU n s = s' ->\n        forall tus tvs tus' sD,\n          n = length tus' ->\n          substD tus tvs s = Some sD ->\n          exists sD',\n            substD (tus ++ tus') tvs s' = Some sD' /\\\n            forall us us' vs,\n              sD us vs <-> sD' (hlist_app us us') vs\n  }.\n\n  Context {Subst_subst : Subst}.\n  Context {SubstOk_subst : SubstOk Subst_subst}.\n  Context {SubstUpdate_subst : SubstUpdate}.\n  Context {SubstUpdateOk_subst : SubstUpdateOk SubstUpdate_subst SubstOk_subst}.\n  Context {SubstOpen_subst : SubstOpen}.\n  Context {SubstOpenOk_subst : @SubstOpenOk _ _ _}.\n\n  Lemma substD_conv\n  : forall tus tus' tvs tvs' (pfu : tus' = tus) (pfv : tvs' = tvs) s,\n      substD tus tvs s =\n      match pfu in _ = u' return option (exprT u' _ Prop) with\n        | eq_refl =>\n          match pfv in _ = v' return option (exprT _ v' Prop) with\n            | eq_refl => substD tus' tvs' s\n          end\n      end.\n  Proof.\n    clear. destruct pfu. destruct pfv. reflexivity.\n  Qed.\n\n  Fixpoint all_Some (ls : list (option expr)) : bool :=\n    match ls with\n    | nil => true\n    | None :: _ => false\n    | Some _ :: ls => all_Some ls\n    end.\n\n  Fixpoint all_defined (from : uvar) (len : nat) (s : T) : bool :=\n    match len with\n    | 0 => true\n    | S len =>\n      match subst_lookup from s with\n      | None => false\n      | Some _ => all_defined (S from) len s\n      end\n    end.\n\n  (** This is the \"obvious\" extension of [drop] **)\n  Fixpoint subst_pull (from : uvar) (len : nat) (s : T) : option T :=\n    match len with\n    | 0 => Some s\n    | S len' => match subst_pull (S from) len' s with\n               | None => None\n               | Some s' => subst_drop from s'\n               end\n    end.\n\n  Fixpoint seq (start : nat) (len : nat) : list nat :=\n    match len with\n    | 0 => nil\n    | S len => start :: seq (S start) len\n    end.\n\n  Lemma getInstantiation_syntactic\n  : forall (s : T) tus tvs t (e : expr) sD,\n      subst_lookup (length tus) s = Some e ->\n      WellFormed_subst s ->\n      substD (tus ++ t :: nil) tvs s = Some sD ->\n      exists eD,\n        exprD tus tvs t e = Some eD /\\\n        forall us vs x,\n          sD (hlist_app us (Hcons x Hnil)) vs ->\n          x = eD us vs.\n  Proof.\n    intros.\n    eapply substD_lookup in H1; eauto.\n    forward_reason.\n    eapply exprD_strengthenU_single in H2; eauto.\n    { forward_reason.\n      eapply nth_error_get_hlist_nth_appR in H1; simpl in *; try omega.\n      rewrite Minus.minus_diag in H1.\n      forward_reason; inv_all; subst.\n      eexists; split; eauto.\n      intros. eapply H3 in H1; clear H3.\n      rewrite H4 in H1. rewrite H5 in H1. subst.\n      assumption. }\n    { apply (@lookup_normalized _ _ _ _ _ H0 H _ _ H). }\n  Qed.\n\n(*\n  Lemma getInstantiation_syntactic_multi\n  : forall (s : T) (tus tvs ts : tenv typ) (es : list expr) sD,\n      mapT (fun u => subst_lookup u s) (seq (length tus) (length ts)) = Some es ->\n      WellFormed_subst s ->\n      substD (tus ++ ts) tvs s = Some sD ->\n      exists esD : hlist@{Set Urefl} (fun t => exprT tus tvs (typD t)) ts,\n        @hlist_build_option typ (fun t => exprT tus tvs (typD t)) expr\n                     (fun t e => exprD tus tvs t e) ts es = Some esD /\\\n        forall (us : hlist@{Set Urefl} _ _)\n          (vs : hlist@{Set Urefl} _ _)\n          (us' : hlist@{Set Urefl} (fun _ : typ => _) ts),\n          sD (hlist_app us (hlist_map (fun t (x : exprT tus tvs (typD t)) => x us vs) us')) vs ->\n          hlist_Forall2 (fun t (x : exprT tus tvs (typD t))\n                             (y : exprT tus tvs (typD t)) =>\n                           x us vs = y us vs) us' esD.\n  Proof.\n  Abort.\n*)\n\n  Theorem pull_sound\n  : forall n s s' u,\n      subst_pull u n s = Some s' ->\n      WellFormed_subst s ->\n      WellFormed_subst s' /\\\n      forall (tus tus' tvs : tenv typ) sD,\n        u = length tus ->\n        n = length tus' ->\n        substD (tus ++ tus') tvs s = Some sD ->\n        exists eus',\n          mapT (fun u => subst_lookup u s) (seq u n) = Some eus' /\\\n          (forall u', u' < u \\/ u' > u + n -> subst_lookup u' s = subst_lookup u' s') /\\\n          (forall u', u' < n -> subst_lookup (u + u') s' = None) /\\\n        exists sD',\n          substD tus tvs s' = Some sD' /\\\n          exists us' : hlist@{Set Urefl} (fun t => hlist typD tus -> hlist typD tvs -> typD t) tus',\n            @hlist_build_option _ _ _ (fun t e => exprD tus tvs t e) tus' eus' = Some us' /\\\n            forall us vs,\n              let us' := hlist_map (fun t (x : hlist typD tus -> hlist typD tvs -> typD t) => x us vs) us' in\n              sD' us vs <->\n              sD (hlist_app us us') vs.\n  Proof.\n    Opaque mapT.\n    induction n.\n    { intros. simpl in *.\n      inv_all. subst.\n      split; auto.\n      intros. subst.\n      destruct tus'; try solve [ simpl in * ; congruence ].\n      clear H1.\n      exists nil. split; [ reflexivity | ].\n      split; try reflexivity.\n      split; [ inversion 1 | ].\n      rewrite substD_conv with (pfu := eq_sym (app_nil_r_trans tus)) (pfv := eq_refl) in H2.\n      autorewrite_with_eq_rw_in H2.\n      forward.\n      eexists; split; eauto.\n      simpl. eexists; split; eauto.\n      inv_all. subst.\n      simpl. intros. rewrite hlist_app_nil_r.\n      autorewrite with eq_rw. reflexivity. }\n    { simpl. intros. forward.\n      eapply IHn in H; clear IHn; auto.\n      forward_reason.\n      eapply drop_sound in H1; auto.\n      forward_reason; split; auto.\n      intros; subst.\n      rewrite list_mapT_cons.\n      destruct tus'; try solve [ simpl in *; congruence ].\n      specialize (H2 (tus ++ t0 :: nil) tus' tvs).\n      rewrite substD_conv with (pfv := eq_refl)\n                               (pfu := app_ass_trans tus (t0 :: nil) tus') in H9.\n      autorewrite_with_eq_rw_in H9.\n      forwardy.\n      assert (S (length tus) = length (tus ++ t0 :: nil)).\n      { rewrite app_length. simpl. omega. }\n      assert (n = length tus').\n      { simpl in *; congruence. }\n      specialize (H2 _ H10 H11 H7); clear H10 H11.\n      forward_reason.\n      rewrite H10 by omega. rewrite H3.\n      change_rewrite H2.\n      eexists; split; eauto.\n      split; [ | split ].\n      { destruct 1.\n        { rewrite H10; eauto. rewrite H5 by omega. reflexivity. }\n        { rewrite H10 by omega. rewrite H5 by omega. reflexivity. } }\n      { intros. destruct u'.\n        { replace (length tus + 0) with (length tus) by omega.\n          assumption. }\n        { replace (length tus + S u') with (S (length tus) + u') by omega.\n          rewrite <- H5 by omega.\n          eapply H11. omega. } }\n      { specialize (H6 tus _ tvs _ eq_refl H12).\n        forward_reason.\n        eexists; split; eauto.\n        simpl. rewrite H15.\n        assert (exists us',\n                  hlist_build_option\n                    (fun t1 : typ =>\n                       hlist typD tus -> hlist typD tvs -> typD t1)\n                    (fun (t1 : typ) (e : expr) => exprD tus tvs t1 e) tus' x0 = Some us' /\\\n                  forall us vs val,\n                    hlist_Forall2 (fun (t : typ)\n                                       (x : hlist typD tus -> hlist typD tvs -> typD t)\n                                       (y : hlist typD (tus ++ _ :: nil) -> hlist typD tvs -> typD t) =>\n                                     x us vs = y (hlist_app us (Hcons val Hnil)) vs) us' x2).\n        { clear H14. generalize dependent x2.\n          assert (forall e, In e x0 ->\n                            mentionsU (length tus) e = false).\n          { intros.\n            eapply mapT_In in H13; try eassumption.\n            simpl in H13.\n            forward_reason.\n            eapply lookup_normalized.\n            2: eassumption. eassumption.\n            rewrite <- H10 in H3. eapply H3.\n            left. omega. }\n          generalize tus'. clear H7 H2.\n          induction x0.\n          { intros. destruct tus'0; simpl in *; try congruence.\n            inv_all; subst. eexists; split; eauto.\n            intros. constructor. }\n          { intros. destruct tus'0; simpl in *; try congruence.\n            forwardy. inv_all; subst.\n            eapply IHx0 in H2; eauto.\n            forward_reason.\n            change_rewrite H2.\n            assert (exists val, exprD tus tvs t1 a = Some val /\\\n                                forall us vs v,\n                                  val us vs = y1 (hlist_app us (Hcons v Hnil)) vs).\n            { eapply exprD_strengthenU_single in H7; eauto.\n              forward_reason. eauto. }\n            forward_reason. rewrite H9.\n            eexists; split; eauto. intros.\n            constructor; eauto. } }\n        { forward_reason.\n          change_rewrite H17.\n          eexists; split; eauto.\n          intros.\n          inv_all; subst. clear H10 H11.\n          rewrite H16; clear H16.\n          rewrite H14; clear H14.\n          simpl.\n          rewrite hlist_app_assoc. simpl.\n          autorewrite with eq_rw.\n          match goal with\n            | |- _ ?X _ <-> _ ?Y _ =>\n              cutrewrite (X = Y); try reflexivity\n          end.\n          apply match_eq_match_eq.\n          f_equal. f_equal.\n          revert H13 H17.\n          specialize (H18 us vs (x4 us vs)).\n          clear - H18.\n          generalize dependent x0.\n          revert H18; revert x2; revert x5; revert tus'.\n          refine (@hlist_Forall2_ind _ _ _ _ _ _ _).\n          { simpl. reflexivity. }\n          { simpl; intros.\n            destruct x0; try congruence.\n            specialize (H1 x0).\n            repeat match goal with\n                     | H : context [ ?X ] , H' : match ?Y with _ => _ end = _ |- _ =>\n                       change Y with X in H' ; destruct X ; try congruence\n                   end.\n            forwardy. inv_all. subst.\n            rewrite H1; auto. rewrite H. reflexivity. } } } }\n  Qed.\n\n  Lemma In_seq : forall a c b,\n      In a (seq b c) <-> (b <= a /\\ a < b + c).\n  Proof.\n    clear.\n    induction c; simpl; intros.\n    { split. destruct 1. intros. omega. }\n    { split; intros.\n      { destruct H. subst. omega. eapply IHc in H. omega. }\n      { consider (b ?[ eq ] a).\n        { intros. subst; auto. }\n        { right. eapply IHc. omega. } } }\n  Qed.\n\n  Lemma sem_preserves_if_substD\n  : forall tus tvs s sD,\n      WellFormed_subst s ->\n      substD tus tvs s = Some sD ->\n      sem_preserves_if_ho (fun P => forall us vs, sD us vs -> P us vs)\n                          (fun u => subst_lookup u s).\n  Proof.\n    red. intros.\n    eapply substD_lookup in H1; eauto.\n    forward_reason.\n    change_rewrite H2 in H1.\n    inv_all; subst.\n    eapply nth_error_get_hlist_nth_Some in H2.\n    forward_reason. simpl in *.\n    eexists; split; eauto.\n  Qed.\n\nEnd subst.\n\nArguments SubstOk T typ expr {_ _ _}.\nArguments SubstUpdateOk T typ expr {_ _ _ _ _}.\nArguments subst_pull {T SO} _ _ _ : rename.\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/SubstI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.19134845396642655}}
{"text": "(******************************************************************************)\n(* A bit library for Coq: extraction to machine words.                        *)\n(******************************************************************************)\n(*                                                                            *)\n(* (c) 2016, ENS Lyon, LIP6, MINES ParisTech                                  *)\n(*                                                                            *)\n(* Written by Arthur Blot                                                     *)\n(*            Pierre-Evariste Dagand                                          *)\n(*            Emilio J. Gallego Arias                                         *)\n(*                                                                            *)\n(* LICENSE: Dual CECILL-B / Apache 2.0                                        *)\n(*                                                                            *)\n(******************************************************************************)\n\n\nFrom mathcomp\nRequire Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\n\nFrom mathcomp\nRequire Import tuple ssralg ssrnum zmodp.\n\nFrom CoqEAL\nRequire Import hrel param refinements.\n\nFrom ssrbit\nRequire Import bitseq notation.\n\nFrom Coq\nRequire Import ZArith.ZArith ExtrOcamlBasic.\n\nImport Refinements.Op.\nImport Logical.Op.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * An axiomatization of OCaml native integers *)\n\n(** This module should not be used directly. *)\nModule Native.\n\n(** We assume that we are running on a 64 bit machine. *)\nAxiom Int : Type.\nAxiom eq  : Int -> Int -> bool.\n\nAxiom zero : Int.\nAxiom one  : Int.\nAxiom opp  : Int -> Int.\nAxiom sub  : Int -> Int -> Int.\nAxiom add  : Int -> Int -> Int.\n\nAxiom lnot : Int -> Int.\nAxiom lor  : Int -> Int -> Int.\nAxiom land : Int -> Int -> Int.\nAxiom lxor : Int -> Int -> Int.\nAxiom lsr  : Int -> Int -> Int.\nAxiom lsl  : Int -> Int -> Int.\n\nExtract Inlined Constant Int  => \"int\".\nExtract Inlined Constant eq   => \"(=)\".\nExtract Inlined Constant zero => \"0\".\nExtract Inlined Constant one  => \"1\".\nExtract Inlined Constant lor  => \"(lor)\".\nExtract Inlined Constant land => \"(land)\".\nExtract Inlined Constant lsr  => \"(lsr)\".\nExtract Inlined Constant lxor => \"(lxor)\".\n\n(** One must be careful to re-normalize the following operations when\nusing them at smaller wordsize: *)\n\nExtract Inlined Constant lsl  => \"(lsl)\".\nExtract Inlined Constant lnot => \"lnot\".\nExtract Inlined Constant add  => \"(+)\".\nExtract         Constant opp  => \"(fun x -> -x)\".\nExtract Inlined Constant sub  => \"(-)\".\n\nEnd Native.\n\nImport Native.\n\nGlobal Instance   eq_Native : eq_of   Int := eq.\n\nGlobal Instance zero_Native : zero_of Int := zero.\nGlobal Instance  one_Native : one_of  Int := one.\nGlobal Instance  opp_Native : opp_of  Int := opp.\nGlobal Instance  sub_Native : sub_of  Int := sub.\nGlobal Instance  add_Native : add_of  Int := add.\n\nGlobal Instance  not_Native : not_of  Int := lnot.\nGlobal Instance   or_Native : or_of   Int := lor.\nGlobal Instance  and_Native : and_of  Int := land.\nGlobal Instance  xor_Native : xor_of  Int := lxor.\nGlobal Instance  shl_Native : shl_of  Int Int := lsl.\nGlobal Instance  shr_Native : shr_of  Int Int := lsr.\n\nSection BitExtract.\n\nVariable n : nat.\nImplicit Types (s : bitseq) (b : 'B_n).\n\nFixpoint bitsToInt s : Int :=\n  (match s with\n    | [::]           => 0\n    | [:: false & s] =>      bitsToInt s :<<: 1\n    | [:: true  & s] => 1 || (bitsToInt s :<<: 1)\n  end)%C.\n\nFixpoint bitsFromInt (k: nat) (n: Int) : bitseq :=\n  (match k with\n    | 0 => [::]\n    | k.+1 =>\n      let p := bitsFromInt k (n :>>: 1) in\n      ((n && 1) == 1) :: p\n  end)%C.\n\nLemma bitsFromIntP {k} (i: Int): size (bitsFromInt k i) == k.\nProof.\n  elim: k i => // [k IH] i //=; rewrite eqSS //.\nQed.\n\nCanonical bitsFromInt_tuple (i: Int): 'B_n\n  := Tuple (bitsFromIntP i).\n\n\nEnd BitExtract.\n\n(** * Extraction  *)\n\n(* Following CompCert's Integer module *)\nModule Type WORDSIZE.\n  Variable wordsize: nat.\nEnd WORDSIZE.\n\nModule MakeOps (WS: WORDSIZE).\n\nDefinition w := WS.wordsize.\n\nDefinition Int  := Native.Int.\nDefinition eq   := Native.eq.\nDefinition zero := Native.zero.\nDefinition one  := Native.one.\nDefinition lor  := Native.lor.\nDefinition land := Native.land.\nDefinition lsr  := Native.lsr.\nDefinition lxor := Native.lxor.\n\nDefinition wordsize := bitsToInt (bitn 63 WS.wordsize).\n\nDefinition bitmask := ((1 :<<: wordsize) - 1: Int)%C.\n\nDefinition mask_unop  (f : Int -> Int) x := (bitmask && f x)%C.\nDefinition mask_binop (f : Int -> Int -> Int) x y := (bitmask && f x y)%C.\n\nDefinition lnot := mask_unop Native.lnot.\nDefinition opp  := mask_unop Native.opp.\n\nDefinition lsl := mask_binop Native.lsl.\nDefinition add := mask_binop Native.add.\nDefinition sub := mask_binop Native.sub.\n\nEnd MakeOps.\n\nModule Wordsize_32.\n  Definition wordsize := 32.\nEnd Wordsize_32.\n\nModule Int32 := MakeOps(Wordsize_32).\n\nModule Wordsize_16.\n  Definition wordsize := 16.\nEnd Wordsize_16.\n\nModule Int16 := MakeOps(Wordsize_16).\n\nModule Wordsize_8.\n  Definition wordsize := 8.\nEnd Wordsize_8.\n\nModule Int8 := MakeOps(Wordsize_8).\n", "meta": {"author": "ejgallego", "repo": "ssrbit", "sha": "7b9d499852bad25b41fa4c3364316baa5e93dc66", "save_path": "github-repos/coq/ejgallego-ssrbit", "path": "github-repos/coq/ejgallego-ssrbit/ssrbit-7b9d499852bad25b41fa4c3364316baa5e93dc66/extraction/axioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.19131847374969668}}
{"text": "Require Import Verdi.TraceRelations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.OutputCorrectInterface.\nRequire Import VerdiRaft.AppliedEntriesMonotonicInterface.\nRequire Import VerdiRaft.TraceUtil.\n\nRequire Import VerdiRaft.StateMachineCorrectInterface.\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.LastAppliedCommitIndexMatchingInterface.\nRequire Import VerdiRaft.LogMatchingInterface.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\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  Context {aemi : applied_entries_monotonic_interface}.\n  Context {smci : state_machine_correct_interface}.\n  Context {si : sorted_interface}.\n  Context {lacimi : lastApplied_commitIndex_match_interface}.\n  Context {lmi : log_matching_interface}.\n\n  Section inner.\n  Variable client : clientId.\n  Variables id : nat.\n  Variable out : output.\n\n  Theorem in_output_trace_dec :\n    forall tr : list (name * (raft_input + list raft_output)),\n      {in_output_trace client id out tr} + {~ in_output_trace client id out tr}.\n  Proof using. \n    unfold in_output_trace.\n    intros.\n    destruct (find (fun p => match snd p with\n                               | inr l => match find (is_client_response client id out) l with\n                                            | Some x => true\n                                            | None => false\n                                          end\n                               | _ => false\n                             end) tr) eqn:?.\n    - find_apply_lem_hyp find_some. break_and.\n      repeat break_match; try discriminate.\n      find_apply_lem_hyp find_some. break_and.\n      unfold is_client_response, in_output_list in *.\n      break_match; try discriminate. break_if; try discriminate. do_bool. break_and. do_bool. subst.\n      left. exists l, (fst p). clean.\n      break_and. do_bool.\n      break_if; try congruence. subst. intuition.\n      find_reverse_rewrite.\n      rewrite <- surjective_pairing.\n      auto.\n    - right. intro. break_exists. break_and.\n      eapply find_none in Heqo; eauto.\n      simpl in *. break_match; try discriminate.\n      unfold in_output_list in *. break_exists.\n      find_eapply_lem_hyp find_none; eauto.\n      simpl in *. find_apply_lem_hyp Bool.andb_false_elim.\n      break_if; repeat (intuition; do_bool).\n      break_if; congruence.\n  Qed.\n\n  Lemma in_output_changed :\n    forall tr o,\n      ~ in_output_trace client id out tr ->\n      in_output_trace client id out (tr ++ o) ->\n      in_output_trace client id out o.\n  Proof using. \n    intros. unfold in_output_trace in *.\n    break_exists_exists.\n    intuition. do_in_app; intuition.\n    exfalso. eauto.\n  Qed.\n\n  Lemma in_output_list_split :\n    forall l l',\n      in_output_list client id out (l ++ l') ->\n      in_output_list client id out l \\/ in_output_list client id out l'.\n  Proof using. \n    intros.\n    unfold in_output_list in *.\n    break_exists; do_in_app; intuition eauto.\n  Qed.\n\n  Lemma in_output_list_empty :\n    ~ in_output_list client id out [].\n  Proof using. \n    intuition.\n  Qed.\n\n  Lemma doLeader_key_in_output_list :\n    forall st h os st' m,\n      doLeader st h = (os, st', m) ->\n      ~ in_output_list client id out os.\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; find_inversion; intuition eauto using key_in_output_list_empty.\n  Qed.\n\n  Lemma handleInput_key_in_output_list :\n    forall st h i os st' m,\n      handleInput h i st = (os, st', m) ->\n      ~ in_output_list client id out os.\n  Proof using. \n    intros. unfold handleInput, handleTimeout, handleClientRequest, tryToBecomeLeader in *.\n    repeat break_match; find_inversion; intuition eauto using in_output_list_empty;\n    unfold in_output_list in *; break_exists; simpl in *; intuition; congruence.\n  Qed.\n\n  Lemma deduplicate_log'_app :\n    forall l l' ks,\n      exists l'',\n        deduplicate_log' (l ++ l') ks = deduplicate_log' l ks ++ l''.\n  Proof using. \n    induction l; intros; simpl in *; intuition; eauto.\n    repeat break_match; simpl in *; eauto;\n    repeat find_insterU; break_exists; eexists; f_equal; eauto.\n  Qed.\n\n  Lemma deduplicate_log_app :\n    forall l l',\n      exists l'',\n        deduplicate_log (l ++ l') = deduplicate_log l ++ l''.\n  Proof using. \n    eauto using deduplicate_log'_app.\n  Qed.\n\n  Lemma in_output_trace_not_nil :\n      in_output_trace client id out [] -> False.\n  Proof using. \n    unfold in_output_trace.\n    simpl. intros. break_exists. intuition.\n  Qed.\n\n  Lemma in_output_trace_singleton_inv :\n    forall h l,\n      in_output_trace client id out [(h, inr l)] ->\n      in_output_list client id out l.\n  Proof using. \n    unfold in_output_trace.\n    intuition.\n    break_exists. simpl in *. intuition.\n    find_inversion. auto.\n  Qed.\n\n  Lemma in_output_list_app_or :\n    forall c i o l1 l2,\n      in_output_list c i o (l1 ++ l2) ->\n      in_output_list c i o l1 \\/\n      in_output_list c i o l2.\n  Proof using. \n    unfold in_output_list.\n    intuition.\n  Qed.\n\n  Lemma in_output_trace_inp_inv :\n    forall h i tr,\n      in_output_trace client id out ((h, inl i) :: tr) ->\n      in_output_trace client id out tr.\n  Proof using. \n    unfold in_output_trace.\n    intuition. break_exists_exists. simpl in *. intuition.\n    find_inversion.\n  Qed.\n\n  Lemma in_output_list_not_leader_singleton :\n    forall a b,\n      ~ in_output_list client id out [NotLeader a b].\n  Proof using. \n    unfold in_output_list. simpl. intuition. discriminate.\n  Qed.\n\n  Lemma handleInput_in_output_list :\n    forall h i st os st' ms,\n      handleInput h i st = (os, st', ms) ->\n      ~ in_output_list client id out os.\n  Proof using. \n    unfold handleInput, handleTimeout, handleInput, tryToBecomeLeader, handleClientRequest.\n    intuition.\n    repeat break_match; repeat find_inversion; eauto using in_output_trace_not_nil.\n    - exfalso. eapply in_output_list_not_leader_singleton; eauto.\n    - exfalso. eapply in_output_list_not_leader_singleton; eauto.\n  Qed.\n\n  Lemma in_output_list_cons_or :\n    forall a b c l,\n      in_output_list client id out (ClientResponse a b c :: l) ->\n      (a = client /\\ b = id /\\ c = out) \\/\n      in_output_list client id out l.\n  Proof using. \n    unfold in_output_list.\n    simpl. intuition.\n    find_inversion. auto.\n  Qed.\n\n  Lemma assoc_Some_In :\n    forall K V (K_eq_dec : forall k k' : K, {k = k'} + {k <> k'}) k v l,\n      assoc (V:=V) K_eq_dec l k = Some v ->\n      In (k, v) l.\n  Proof using. \n    induction l; simpl; intros; repeat break_match.\n    - discriminate.\n    - find_inversion. auto.\n    - intuition.\n  Qed.\n\n  Lemma getLastId_Some_In :\n    forall st c n o,\n      getLastId st c = Some (n, o) ->\n      In (c, (n, o)) (clientCache st).\n  Proof using. \n    unfold getLastId.\n    eauto using assoc_Some_In.\n  Qed.\n\n  Lemma middle_app_assoc :\n    forall A xs (y : A) zs,\n      xs ++ y :: zs = (xs ++ [y]) ++ zs.\n  Proof using. \n    induction xs; intros; simpl; auto using f_equal.\n  Qed.\n\n  Lemma deduplicate_log'_snoc_drop_keys :\n    forall es ks e n,\n      assoc clientId_eq_dec ks (eClient e) = Some n ->\n      eId e <= n ->\n      deduplicate_log' (es ++ [e]) ks = deduplicate_log' es ks.\n  Proof using. \n    induction es; simpl; intuition; repeat break_match; repeat find_inversion; do_bool.\n    - lia.\n    - auto.\n    - discriminate.\n    - f_equal. destruct (clientId_eq_dec (eClient a) (eClient e)).\n      + repeat find_rewrite. find_injection.\n        eapply IHes with (n := eId a); auto with *.\n        now rewrite get_set_same.\n      + eapply IHes; eauto.\n        rewrite get_set_diff by auto. auto.\n    - eauto.\n    - f_equal. destruct (clientId_eq_dec (eClient a) (eClient e)).\n      + repeat find_rewrite. discriminate.\n      + eapply IHes; eauto.\n        rewrite get_set_diff by auto. auto.\n  Qed.\n\n  Lemma deduplicate_log'_snoc_drop_es :\n    forall es ks e e',\n      In e' es ->\n      eClient e = eClient e' ->\n      eId e <= eId e' ->\n      deduplicate_log' (es ++ [e]) ks = deduplicate_log' es ks.\n  Proof using. \n    induction es; simpl; intuition; repeat break_match; eauto using f_equal;\n    repeat find_reverse_rewrite.\n    - f_equal. subst. eapply deduplicate_log'_snoc_drop_keys; eauto.\n      now rewrite get_set_same.\n    - subst. do_bool. eapply deduplicate_log'_snoc_drop_keys; eauto; auto with *.\n    - f_equal. subst. eapply deduplicate_log'_snoc_drop_keys; eauto.\n      now rewrite get_set_same.\n  Qed.\n\n  Lemma deduplicate_log_snoc_drop :\n    forall es e e',\n      In e' es ->\n      eClient e = eClient e' ->\n      eId e <= eId e' ->\n      deduplicate_log (es ++ [e]) = deduplicate_log es.\n  Proof using. \n    intros. eapply deduplicate_log'_snoc_drop_es; eauto.\n  Qed.\n\n\n  Lemma deduplicate_log'_snoc_split :\n    forall es ks e,\n      (forall e', In e' es -> eClient e' = eClient e -> eId e' < eId e) ->\n      (forall i, assoc clientId_eq_dec ks (eClient e) = Some i -> i < eId e) ->\n      deduplicate_log' (es ++ [e]) ks = deduplicate_log' es ks ++ [e].\n  Proof using. \n    induction es; intros; simpl in *; intuition.\n    - break_match; simpl in *; auto.\n      break_if; simpl in *; auto.\n      do_bool.\n      find_insterU. conclude_using eauto. lia.\n    - repeat break_match; simpl in *; auto.\n      + f_equal. eapply IHes; eauto.\n        intros. do_bool.\n        destruct (clientId_eq_dec (eClient a) (eClient e)).\n        * repeat find_rewrite.\n          find_rewrite_lem get_set_same. find_injection.\n          find_insterU. conclude_using eauto. intuition.\n        * find_erewrite_lem get_set_diff.\n          eauto.\n      + f_equal. eapply IHes; eauto.\n        intros. do_bool.\n        destruct (clientId_eq_dec (eClient a) (eClient e)).\n        * repeat find_rewrite.\n          find_rewrite_lem get_set_same. find_injection.\n          match goal with\n            | H : forall _, ?x = _ \\/ _ -> _ |- _ =>\n              specialize (H x)\n          end.\n          intuition.\n        * find_erewrite_lem get_set_diff.\n          eauto.\n  Qed.\n\n  Lemma deduplicate_log_snoc_split :\n    forall es e,\n      (forall e', In e' es -> eClient e' = eClient e -> eId e' < eId e) ->\n      deduplicate_log (es ++ [e]) = deduplicate_log es ++ [e].\n  Proof using. \n    intros.\n    eapply deduplicate_log'_snoc_split; eauto.\n    intros. simpl in *. congruence.\n  Qed.\n\n  Lemma execute_log_app :\n    forall xs ys,\n      execute_log (xs ++ ys) = let (tr, st) := execute_log xs in execute_log' ys st tr.\n  Proof using. \n    unfold execute_log.\n    intros.\n    rewrite execute_log'_app. auto.\n  Qed.\n\n  Lemma applyEntry_stateMachine_correct :\n    forall st e l st' es,\n      applyEntry st e = (l, st') ->\n      stateMachine st = snd (execute_log (deduplicate_log es)) ->\n      (forall e', In e' es -> eClient e' = eClient e -> eId e' < eId e) ->\n      stateMachine st' = snd (execute_log (deduplicate_log es ++ [e])).\n  Proof using. \n    unfold applyEntry.\n    intros.\n    repeat break_match; repeat find_inversion. simpl.\n    rewrite execute_log_app. simpl. repeat break_let.\n    simpl in *. congruence.\n  Qed.\n\n  Lemma deduplicate_log_cases :\n    forall es e,\n      (deduplicate_log (es ++ [e]) = deduplicate_log es /\\\n       exists e', In e' es /\\ eClient e' = eClient e /\\ eId e <= eId e') \\/\n      (deduplicate_log (es ++ [e]) = deduplicate_log es ++ [e] /\\\n       (forall e', In e' es -> eClient e' = eClient e -> eId e' < eId e)).\n  Proof using. \n    intros.\n    destruct (find (fun e' => andb (if clientId_eq_dec (eClient e') (eClient e) then true else false)\n                                  (eId e <=? eId e')) es) eqn:?.\n    - left. find_apply_lem_hyp find_some.\n      break_if; repeat (break_and; do_bool); try congruence.\n      intuition eauto using deduplicate_log_snoc_drop.\n    - right.\n      match goal with\n        | |- _ /\\ ?P =>\n          assert P; [|intuition; eauto using deduplicate_log_snoc_split]\n      end.\n      intros.\n      find_eapply_lem_hyp find_none; eauto.\n      simpl in *. break_if; repeat (do_bool; intuition); try congruence.\n  Qed.\n\n  (* FIXME: move to StructTact *)\n  Lemma assoc_None :\n    forall K V K_eq_dec (l : list (K * V)) k v,\n      assoc K_eq_dec l k = None ->\n      In (k, v) l ->\n      False.\n  Proof using. \n    intros; induction l; simpl in *; intuition.\n    - subst. break_if; congruence.\n    - break_match. subst. break_if; try congruence.\n      auto.\n  Qed.\n\n  Lemma getLastId_None :\n    forall st c i o,\n      getLastId st c = None ->\n      In (c, (i, o)) (clientCache st) ->\n      False.\n  Proof using. \n    intros.\n    unfold getLastId in *.\n    eauto using assoc_None.\n  Qed.\n\n  Lemma output_correct_monotonic :\n    forall c i o xs ys,\n      output_correct c i o xs ->\n      output_correct c i o (xs ++ ys).\n  Proof using. \n    unfold output_correct.\n    intros.\n    break_exists.\n    intuition.\n    pose proof (deduplicate_log_app xs ys). break_exists.\n    repeat find_rewrite.\n    rewrite app_ass in *. simpl in *.\n    eexists. eexists. eexists. eexists. eexists.\n    intuition eauto.\n  Qed.\n\n  Lemma applyEntry_output_correct :\n    forall st e l st' o es,\n      applyEntry st e = (l, st') ->\n      In o l ->\n      stateMachine st = snd (execute_log (deduplicate_log es)) ->\n      (forall e', In e' es -> eClient e' = eClient e -> eId e' < eId e) ->\n      output_correct (eClient e) (eId e) o (es ++ [e]).\n  Proof using. \n    unfold applyEntry.\n    intros.\n    repeat break_match; repeat find_inversion.\n    simpl in *. intuition.\n    subst.\n    unfold output_correct.\n    rewrite deduplicate_log_snoc_split by auto.\n    destruct (execute_log (deduplicate_log es)) eqn:?.\n    eexists. eexists. exists []. eexists. eexists. intuition eauto.\n    - rewrite execute_log_app. repeat find_rewrite. simpl in *. find_rewrite. eauto.\n    - rewrite rev_app_distr. simpl. auto.\n  Qed.\n\n  Lemma cacheApplyEntry_output_correct :\n    forall e es st l st' o,\n      cacheApplyEntry st e = (l, st') ->\n      In o l ->\n      (forall c i o,\n         getLastId st c = Some (i, o) ->\n         output_correct c i o es) ->\n      stateMachine st = snd (execute_log (deduplicate_log es)) ->\n      (forall c i o e',\n         getLastId st c = Some (i, o) ->\n         In e' es ->\n         eClient e' = c ->\n         eId e' <= i) ->\n      (forall e',\n         In e' es ->\n         exists i o,\n           getLastId st (eClient e') = Some (i, o) /\\\n           eId e' <= i) ->\n      output_correct (eClient e) (eId e) o (es ++ [e]).\n  Proof using. \n    unfold cacheApplyEntry.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    - do_bool. subst. eauto using output_correct_monotonic, getLastId_Some_In.\n    - eapply applyEntry_output_correct; eauto.\n      do_bool. assert (n < eId e) by auto with *.\n      intros. assert (eId e' <= n) by eauto. lia.\n    - eapply applyEntry_output_correct; eauto.\n      intros.\n      find_apply_hyp_hyp.\n      break_exists. break_and.\n      repeat find_rewrite. discriminate.\n  Qed.\n\n  Lemma cacheApplyEntry_stateMachine_correct :\n    forall st e l st' es,\n      cacheApplyEntry st e = (l, st') ->\n      stateMachine st = snd (execute_log (deduplicate_log es)) ->\n      (forall c i o,\n         getLastId st c = Some (i, o) ->\n         exists e,\n           In e es /\\\n           eClient e = c /\\\n           eId e = i) ->\n      (forall c i o e',\n         getLastId st c = Some (i, o) ->\n         In e' es ->\n         eClient e' = c ->\n         eId e' <= i) ->\n      (forall e',\n         In e' es ->\n         exists i o,\n           getLastId st (eClient e') = Some (i, o) /\\\n           eId e' <= i) ->\n      stateMachine st' = snd (execute_log (deduplicate_log (es ++ [e]))).\n  Proof using. \n    intros.\n    unfold cacheApplyEntry in *.\n    repeat break_match; repeat find_inversion.\n    - find_apply_hyp_hyp. break_exists. break_and.\n      erewrite deduplicate_log_snoc_drop; eauto.\n      do_bool. lia.\n    - find_apply_hyp_hyp. break_exists. break_and.\n      erewrite deduplicate_log_snoc_drop; eauto.\n      do_bool. lia.\n    - find_copy_apply_hyp_hyp. break_exists. break_and.\n      pose proof (deduplicate_log_cases es e).\n      intuition; break_exists; intuition; repeat find_rewrite.\n      + do_bool. assert (eId x0 <= n) by eauto. lia.\n      + eapply applyEntry_stateMachine_correct; eauto.\n    - pose proof (deduplicate_log_cases es e).\n      intuition; break_exists; intuition; repeat find_rewrite.\n      + eapply_prop_hyp In In. break_exists. break_and.\n        repeat find_rewrite. discriminate.\n      + eapply applyEntry_stateMachine_correct; eauto.\n  Qed.\n\n  Lemma deduplicate_log_In_if :\n    forall e l,\n      In e (deduplicate_log l) ->\n      In e l.\n  Proof using. \n    unfold deduplicate_log.\n    intros. eauto using deduplicate_log'_In_if.\n  Qed.\n\n  Lemma applyEntry_clientCache :\n    forall st e l st',\n      applyEntry st e = (l, st') ->\n      let (out, _) := handler (eInput e) (stateMachine st)\n      in (clientCache st' = assoc_set clientId_eq_dec (clientCache st) (eClient e) (eId e, out) /\\\n          In out l).\n  Proof using. \n    unfold applyEntry.\n    intros.\n    repeat break_match; repeat find_inversion. intuition.\n  Qed.\n\n  Lemma cacheApplyEntry_clientCache :\n    forall st e l st',\n      cacheApplyEntry st e = (l, st') ->\n      (clientCache st' = clientCache st /\\\n       (exists i o, getLastId st (eClient e) = Some (i, o) /\\\n                    eId e <= i) ) \\/\n      ((let (out, _) := handler (eInput e) (stateMachine st)\n       in (clientCache st' = assoc_set clientId_eq_dec (clientCache st) (eClient e) (eId e, out) /\\\n          In out l)) /\\ (getLastId st (eClient e) = None \\/\n                       (exists i o, getLastId st (eClient e) = Some (i, o) /\\\n                                    i < eId e))).\n  Proof using. \n    unfold cacheApplyEntry.\n    intros.\n    repeat break_match_hyp; repeat find_inversion; do_bool; intuition eauto with *;\n    right; (split; [solve [apply applyEntry_clientCache; auto]|]); auto.\n    right. do_bool. eexists. eexists. intuition eauto. lia.\n  Qed.\n\n  Lemma getLastId_ext :\n    forall st st' c,\n      clientCache st' = clientCache st ->\n      getLastId st' c = getLastId st c.\n  Proof using. \n    unfold getLastId.\n    intros.\n    congruence.\n  Qed.\n\n  Lemma cacheAppliedEntry_clientCache_preserved :\n    forall st e l st' c i o,\n      cacheApplyEntry st e = (l, st') ->\n      getLastId st c = Some (i, o) ->\n      exists i' o',\n        getLastId st' c = Some (i', o') /\\\n        i <= i'.\n  Proof using. \n    intros.\n    unfold cacheApplyEntry in *.\n    repeat break_match; try find_inversion; simpl in *; repeat find_rewrite; eauto.\n    - do_bool.\n      unfold applyEntry in *.\n      repeat break_match; find_inversion.\n      unfold getLastId in *. simpl in *.\n      destruct (clientId_eq_dec (eClient e) c); subst.\n      + rewrite get_set_same. find_rewrite.\n        find_inversion. eauto.\n      + rewrite get_set_diff in *; auto.\n        repeat find_rewrite. eauto.\n    - unfold applyEntry in *.\n      repeat break_match; find_inversion.\n      unfold getLastId in *. simpl in *.\n      destruct (clientId_eq_dec (eClient e) c); subst.\n      + repeat find_rewrite.  congruence.\n      + rewrite get_set_diff in *; auto.\n        repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma cacheAppliedEntry_clientCache_nondecreasing :\n    forall st e l st' c i o i' o',\n      cacheApplyEntry st e = (l, st') ->\n      getLastId st c = Some (i, o) ->\n      getLastId st' c = Some (i', o') ->\n      i <= i'.\n  Proof using. \n    intros.\n    eapply cacheAppliedEntry_clientCache_preserved in H; eauto.\n    break_exists. intuition. repeat find_rewrite. find_inversion. auto.\n  Qed.\n  \n  Lemma applyEntries_output_correct :\n    forall l c i o h st os st' es,\n      applyEntries h st l = (os, st') ->\n      in_output_list c i o os ->\n      (stateMachine st = snd (execute_log (deduplicate_log es))) ->\n      (forall c i o,\n         getLastId st c = Some (i, o) ->\n         output_correct c i o es) ->\n      (forall c i o e',\n         getLastId st c = Some (i, o) ->\n         In e' es -> eClient e' = c -> eId e' <= i) ->\n      (forall e',\n         In e' es ->\n         exists i o,\n           getLastId st (eClient e') = Some (i, o) /\\ eId e' <= i) ->\n      output_correct c i o (es ++ l).\n  Proof using out id client. \n    induction l; intros; simpl in *.\n    - find_inversion. exfalso. eapply in_output_list_empty; eauto.\n    - repeat break_let. find_inversion.\n      find_apply_lem_hyp in_output_list_app_or.\n      break_or_hyp.\n      + break_if.\n        * unfold in_output_list in *.\n          do_in_map. find_inversion.\n          rewrite middle_app_assoc. apply output_correct_monotonic.\n          eapply cacheApplyEntry_output_correct; eauto.\n        * exfalso. eapply in_output_list_empty; eauto.\n      + rewrite middle_app_assoc. eapply IHl.\n        * eauto.\n        * auto.\n        * eapply cacheApplyEntry_stateMachine_correct; eauto.\n          intros.\n          find_apply_hyp_hyp. unfold output_correct in *.\n          break_exists. break_and.\n          eexists. intuition eauto.\n          eapply deduplicate_log_In_if.\n          eauto with *.\n        * find_copy_apply_lem_hyp cacheApplyEntry_clientCache.\n          { intros. break_or_hyp.\n            - break_and.\n              apply output_correct_monotonic.\n              unfold getLastId in *. repeat find_rewrite. eauto.\n            - break_let. break_and.\n              unfold getLastId in *.\n              repeat find_rewrite.\n              destruct (clientId_eq_dec (eClient a) c0).\n              + subst.  rewrite get_set_same in *. find_inversion.\n                eapply cacheApplyEntry_output_correct; eauto.\n              + rewrite get_set_diff in * by auto. eauto using output_correct_monotonic.\n          }\n        * intros.\n          do_in_app. simpl in *.\n          { intuition.\n            - eapply_prop_hyp In In. break_exists. break_and. subst.\n              eauto using Nat.le_trans, cacheAppliedEntry_clientCache_nondecreasing.\n            - subst. find_copy_apply_lem_hyp cacheApplyEntry_clientCache.\n              intuition.\n              + break_exists. break_and.\n                eauto using Nat.le_trans, cacheAppliedEntry_clientCache_nondecreasing.\n              + unfold getLastId in *. break_let. break_and. repeat find_rewrite.\n                rewrite get_set_same in *. find_inversion. auto.\n              + unfold getLastId in *. break_let. break_and.\n                repeat find_rewrite.\n                rewrite get_set_same in *. find_inversion. auto.\n          }\n        * intros.\n          do_in_app. simpl in *.\n          { intuition.\n            - eapply_prop_hyp In In. break_exists. break_and.\n              find_copy_eapply_lem_hyp cacheAppliedEntry_clientCache_preserved; eauto.\n              break_exists_exists. intuition.\n            - subst. find_copy_apply_lem_hyp cacheApplyEntry_clientCache.\n              intuition.\n              + break_exists. break_and.\n                find_copy_eapply_lem_hyp cacheAppliedEntry_clientCache_preserved; eauto.\n                break_exists_exists. intuition.\n              + break_let. break_and. unfold getLastId. repeat find_rewrite.\n                eexists. eexists. rewrite get_set_same. intuition eauto.\n              + break_let. break_and. unfold getLastId. repeat find_rewrite.\n                eexists. eexists. rewrite get_set_same. intuition eauto.\n          }\n  Qed.\n\n  Lemma cacheApplyEntry_spec :\n    forall st a l st',\n      cacheApplyEntry st a = (l, st') ->\n      log st' = log st /\\\n      lastApplied st' = lastApplied st /\\\n      commitIndex st' = commitIndex st.\n  Proof using. \n    intros. unfold cacheApplyEntry, applyEntry in *.\n    repeat break_match; find_inversion; auto.\n  Qed.\n\n  Lemma applyEntries_spec :\n    forall es h st os st',\n      applyEntries h st es = (os, st') ->\n      log st' = log st /\\\n      lastApplied st' = lastApplied st /\\\n      commitIndex st' = commitIndex st.\n  Proof using. \n    induction es; intros; simpl in *.\n    - find_inversion. auto.\n    - repeat break_match; find_inversion;\n      find_apply_hyp_hyp;\n      find_apply_lem_hyp cacheApplyEntry_spec;\n      intuition; repeat find_rewrite; auto.\n  Qed.\n\n  Lemma output_correct_prefix :\n    forall l1 l2 client id out,\n      Prefix l1 l2 ->\n      output_correct client id out l1 ->\n      output_correct client id out l2.\n  Proof using. \n    intros.\n    find_apply_lem_hyp Prefix_exists_rest.\n    break_exists. subst.\n    eauto using output_correct_monotonic.\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_output_correct :\n    forall h ps sigma os st' ms,\n      raft_intermediate_reachable (mkNetwork ps sigma) ->\n      doGenericServer h (sigma h) = (os, st', ms) ->\n      in_output_list client id out os ->\n      output_correct client id out (applied_entries (update name_eq_dec sigma h st')).\n  Proof using lmi lacimi si smci. \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 ({| nwPackets := ps; nwState := sigma |}))\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 doGenericServer in *.\n    break_let. find_inversion.\n    find_copy_apply_lem_hyp applyEntries_spec. intuition. repeat find_rewrite.\n    eapply applyEntries_output_correct\n    with (es := rev (removeAfterIndex (log (sigma h)) (lastApplied (sigma h)))) in Heqp; eauto.\n    - rewrite <- rev_app_distr in *.\n      eapply output_correct_prefix; eauto.\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    - unfold client_cache_complete in *.\n      simpl in *.\n      intros. subst.\n      find_apply_lem_hyp In_rev. find_apply_hyp_hyp.\n      break_exists. intuition. repeat find_rewrite.\n      match goal with\n        | H : Some _ = Some _ |- _ =>\n          invcs H\n      end. auto.\n    - intros. find_apply_lem_hyp In_rev. eauto.\n  Qed.\n\n  Ltac intermediate_networks :=\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\n  Lemma in_output_trace_step_output_correct :\n    forall failed failed' (net net' : network (params := @multi_params _ _ raft_params)) os,\n      in_output_trace client id out os ->\n      @raft_intermediate_reachable _ _ raft_params net ->\n      step_failure (failed, net) (failed', net') os ->\n      output_correct client id out (applied_entries (nwState net')).\n  Proof using lmi lacimi si smci. \n    intros.\n    match goal with\n      | [ H : context [ step_failure _ _ _ ] |- _ ] => invcs H\n    end.\n    - unfold RaftNetHandler in *. repeat break_let. repeat find_inversion.\n      find_apply_lem_hyp in_output_trace_singleton_inv.\n      find_apply_lem_hyp in_output_list_app_or.\n      intuition.\n      + exfalso. eapply doLeader_key_in_output_list; eauto.      \n      + find_copy_eapply_lem_hyp RIR_handleMessage; eauto.\n        find_copy_eapply_lem_hyp RIR_doLeader; simpl; rewrite_update; eauto.\n        intermediate_networks.\n        find_copy_apply_lem_hyp doLeader_appliedEntries. \n        eapply doGenericServer_output_correct; eauto.\n    - unfold RaftInputHandler in *. repeat break_let. repeat find_inversion.\n      find_apply_lem_hyp in_output_trace_inp_inv.\n      find_apply_lem_hyp in_output_trace_singleton_inv.\n      find_apply_lem_hyp in_output_list_app_or.\n      intuition.\n      + exfalso. eapply handleInput_in_output_list; eauto.\n      + find_apply_lem_hyp in_output_list_app_or.\n        intuition.\n        * exfalso. eapply doLeader_key_in_output_list; eauto.\n          * find_copy_eapply_lem_hyp RIR_handleInput; eauto.\n            find_copy_eapply_lem_hyp RIR_doLeader; simpl; rewrite_update; eauto.\n            intermediate_networks.\n            find_copy_apply_lem_hyp doLeader_appliedEntries. \n            eapply doGenericServer_output_correct; eauto.\n    - exfalso. eauto using in_output_trace_not_nil.\n    - exfalso. eauto using in_output_trace_not_nil.\n    - exfalso. eauto using in_output_trace_not_nil.\n    - exfalso. eauto using in_output_trace_not_nil.\n  Qed.\n\n  Program Instance TR : TraceRelation step_failure :=\n    {\n      init := step_failure_init;\n      T := in_output_trace client id out ;\n      T_dec := in_output_trace_dec ;\n      R := fun s => let (_, net) := s in\n                    output_correct client id out (applied_entries (nwState net))\n    }.\n  Next Obligation.\n    repeat break_let. subst.\n    find_eapply_lem_hyp applied_entries_monotonic';\n      eauto using step_failure_star_raft_intermediate_reachable.\n    unfold output_correct in *.\n    break_exists.\n    repeat find_rewrite.\n    match goal with\n    | [ |- context [ deduplicate_log (?l ++ ?l') ] ] =>\n      pose proof deduplicate_log_app l l'; break_exists; find_rewrite\n    end.\n    repeat eexists; intuition eauto; repeat find_rewrite; auto.\n    rewrite app_ass. simpl. repeat f_equal.\n  Defined.\n  Next Obligation.\n    unfold in_output_trace in *. intuition.\n    break_exists; intuition.\n  Defined.\n  Next Obligation.\n    find_apply_lem_hyp in_output_changed; auto.\n    eauto using in_output_trace_step_output_correct, step_failure_star_raft_intermediate_reachable.\n  Defined.\n\n  Theorem output_correct :\n    forall  failed net tr,\n      step_failure_star step_failure_init (failed, net) tr ->\n      in_output_trace client id out tr ->\n      output_correct client id out (applied_entries (nwState net)).\n  Proof using lmi lacimi si smci aemi. \n    intros. pose proof (trace_relations_work (failed, net) tr).\n    repeat concludes.\n    auto.\n  Qed.\n  End inner.\n\n  Instance oci : output_correct_interface.\n  Proof using smci si lmi lacimi aemi.\n    split.\n    exact output_correct.\n  Qed.\nEnd OutputCorrect.\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/OutputCorrectProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.37387582974820255, "lm_q1q2_score": 0.19131847017970274}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nSet Implicit Arguments.\n\n(* NOTE: We currently consider only finite behaviors of program: we\n * ignore non-terminating executions.  This simplification affects two\n * aspects of the development:\n *\n * - Liveness.  In our definition, the liveness matters only for\n *   non-terminating execution.\n *\n * - Simulation.  We do not introduce simulation index for inftau\n *   behaviors (i.e. infinite loop without system call interactions).\n *\n * We will consider infinite behaviors in the future work.\n *)\n(* NOTE: We serialize all the events within a behavior, but it may not\n * be the case.  The *NIX kernels are re-entrant: system calls may\n * race.\n *)\n\nInductive behaviors\n          (step: forall (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop):\n  forall (conf:Configuration.t) (b:list Event.t) (f: bool), Prop :=\n| behaviors_nil\n    c\n    (TERMINAL: Configuration.is_terminal c):\n    behaviors step c nil true\n| behaviors_syscall\n    e1 e2 tid c1 c2 beh f\n    (STEP: step (MachineEvent.syscall e2) tid c1 c2)\n    (NEXT: behaviors step c2 beh f)\n    (EVENT: Event.le e1 e2):\n    behaviors step c1 (e1::beh) f\n| behaviors_failure\n    tid c1 c2 beh f\n    (STEP: step MachineEvent.failure tid c1 c2):\n    behaviors step c1 beh f\n| behaviors_tau\n    tid c1 c2 beh f\n    (STEP: step MachineEvent.silent tid c1 c2)\n    (NEXT: behaviors step c2 beh f):\n    behaviors step c1 beh f\n| behaviors_partial_term\n    c:\n    behaviors step c [] false\n.\n\nLemma rtc_tau_step_behavior\n      step c1 c2 b f\n      (STEPS: rtc (union (step MachineEvent.silent)) c1 c2)\n      (BEH: behaviors step c2 b f):\n  behaviors step c1 b f.\nProof.\n  revert BEH. induction STEPS; auto. inv H.\n  i. specialize (IHSTEPS BEH). econs 4; eauto.\nQed.\n\nLemma le_step_behavior_improve\n      sem0 sem1\n      (STEPLE: sem0 <4= sem1):\n  behaviors sem0 <3= behaviors sem1.\nProof.\n  i. ginduction PR; i.\n  - econs 1; eauto.\n  - econs 2; eauto.\n  - econs 3; eauto.\n  - econs 4; eauto.\n  - econs 5; eauto.\nQed.\n\nInductive behaviors_partial\n          (step: forall (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop):\n  forall (conf1 conf2:Configuration.t) (b:list Event.t), Prop :=\n| behaviors_partial_nil\n    c:\n    behaviors_partial step c c nil\n| behaviors_partial_syscall\n    e tid c1 c2 c3 beh\n    (STEP: step (MachineEvent.syscall e) tid c1 c2)\n    (NEXT: behaviors_partial step c2 c3 beh):\n    behaviors_partial step c1 c3 (e::beh)\n| behaviors_partial_tau\n    tid c1 c2 c3 beh\n    (STEP: step MachineEvent.silent tid c1 c2)\n    (NEXT: behaviors_partial step c2 c3 beh):\n    behaviors_partial step c1 c3 beh\n.\n\nLemma rtc_tau_step_behavior_partial\n      step c1 c2 c3 b\n      (STEPS: rtc (union (step MachineEvent.silent)) c1 c2)\n      (BEH: behaviors_partial step c2 c3 b):\n  behaviors_partial step c1 c3 b.\nProof.\n  revert BEH. induction STEPS; auto. inv H.\n  i. specialize (IHSTEPS BEH). econs 3; eauto.\nQed.\n\nLemma behaviors_partial_app_partial\n      step c1 c2 c3 b1 b2\n      (BEH1: behaviors_partial step c1 c2 b1)\n      (BEH2: behaviors_partial step c2 c3 b2)\n  :\n    behaviors_partial step c1 c3 (b1 ++ b2).\nProof.\n  induction BEH1.\n  - eauto.\n  - econs 2; eauto.\n  - econs 3; eauto.\nQed.\n\nLemma behaviors_partial_app\n      step c1 c2 b1 b2 f\n      (BEH1: behaviors_partial step c1 c2 b1)\n      (BEH2: behaviors step c2 b2 f)\n  :\n    behaviors step c1 (b1 ++ b2) f.\nProof.\n  induction BEH1.\n  - eauto.\n  - econs 2; eauto. refl.\n  - econs 4; 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/Behavior.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "Require Import Eqdep Lia Framework FSParameters.\nRequire Import TransactionCacheLayer TransactionalDiskLayer.\nRequire Import Transaction TransactionToTransactionalDisk.Definitions.\nRequire Import ClassicalFacts FunctionalExtensionality Lia.\n\nSet Nested Proofs Allowed.\n\nLocal Notation \"'imp'\" := TransactionCacheLang.\nLocal Notation \"'abs'\" := (TDLang data_length).\nLocal Notation \"'refinement'\" := TDRefinement.\n\nDefinition TC_reboot_f := fun s: imp.(state) => (([]: list (addr * value)), snd s).\n\nDefinition TD_reboot_f := fun s: abs.(state) => (Empty, (snd (snd s), snd (snd s))).\n\n  Definition transaction_cache_reboot_list n := repeat (fun s: imp.(state) => (([]: list (addr * value)), snd s)) n.\n\n  Definition transactional_disk_reboot_list n := repeat (fun s : abs.(state) => (Empty, (snd (snd s), snd (snd 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  Theorem abstract_oracles_exist_wrt_recover:\n    forall n u, \n      abstract_oracles_exist_wrt refinement refines_reboot u (|Recover|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; induction n;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n      intuition eauto.\n      left; eexists; intuition eauto.\n      destruct t.\n      \n      eexists; intuition eauto.\n      eapply_fresh recover_finished in H7; eauto.\n      cleanup.\n      eexists; intuition eauto.\n      left.\n      unfold transaction_reboot_rep, transaction_rep in *;\n      simpl in *. cleanup.\n      repeat cleanup_pairs; eauto.\n    }\n    { \n      eapply IHn in H11; eauto; cleanup.\n      exists ([OpToken (TDCore data_length) CrashBefore]::x0); simpl.\n      eapply_fresh recover_crashed in H10; eauto; cleanup.\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      simpl in *.\n      cleanup; eauto.\n\n      eapply_fresh recover_crashed in H10; eauto; cleanup.\n      eexists; unfold transaction_reboot_rep in *; simpl; intuition eauto.\n      eapply_fresh recover_crashed in H10; eauto; cleanup.\n      eexists; unfold transaction_reboot_rep in *; simpl; intuition eauto.\n      instantiate (1:= x); cleanup; eauto.\n    }\n  Qed.\n\n  Theorem abstract_oracles_exist_wrt_recover':\n    forall n u, \n      abstract_oracles_exist_wrt refinement refines u (|Recover|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; destruct n;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n      intuition eauto.\n      left.\n      eexists; intuition eauto.\n      destruct t.\n      \n      eexists; intuition eauto.\n      eapply_fresh recover_finished_2 in H7; eauto.\n      eexists; intuition eauto.\n      left.\n      unfold refines, transaction_rep in *; simpl in *; cleanup.\n      repeat cleanup_pairs; eauto.\n    }\n    {        \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (TDCore data_length) CrashBefore]::x0); simpl.\n      eapply_fresh recover_crashed in H10; eauto; cleanup.\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      simpl in *.\n      eexists; repeat split; eauto;\n      simpl in *.\n      cleanup; eauto.\n      \n      unfold refines, refines_reboot,\n      transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n\n      eapply_fresh recover_crashed in H10; eauto; cleanup.\n      eexists; unfold refines, refines_reboot,\n               transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n      \n      unfold refines, refines_reboot,\n      transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n    }\n  Qed.\n\n  Theorem abstract_oracles_exist_wrt_read:\n    forall n a u, \n      abstract_oracles_exist_wrt refinement refines u (|Read a|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; destruct n;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n      intuition eauto.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eapply_fresh read_finished in H7; eauto.\n      eexists; intuition eauto.     \n    }\n    {        \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (TDCore data_length) CrashBefore]::x0); simpl.\n      eapply_fresh read_crashed in H10; eauto; cleanup.\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      simpl in *.\n      eexists; repeat split; eauto;\n      simpl in *.\n      cleanup; eauto.\n      \n\n      eapply_fresh read_crashed in H10; eauto; cleanup.\n      eexists; unfold refines, refines_reboot,\n               transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n    }\n  Qed.\n  \n  Theorem abstract_oracles_exist_wrt_write:\n    forall n l_a l_v u,\n      abstract_oracles_exist_wrt refinement refines u (|Write l_a l_v|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; destruct n;\n    simpl; intros; cleanup; invert_exec.\n    {      \n      eapply_fresh write_finished in H7; eauto.\n      split_ors; cleanup.\n      {\n        exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n        intuition eauto.\n        left.\n        eexists; intuition eauto.\n        \n        eexists; intuition eauto.\n        eexists; split; eauto.\n        left.\n        do 2 eexists; split; eauto.\n        left; intuition eauto.\n        unfold refines, transaction_rep in *; simpl in *; cleanup.\n        repeat cleanup_pairs; eauto.\n        inversion H0; eauto.\n      }\n      split_ors; cleanup.\n      {\n        exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n        split; eauto. \n        left.\n        do 2 eexists; repeat (split; eauto).\n        intros; eexists; repeat (split; eauto).\n        left.\n        do 2 eexists; repeat (split; eauto).\n      }\n      {\n        exists  [ [OpToken (TDCore data_length) TxnFull] ]; simpl.\n        intuition eauto.\n        left.\n        eexists; intuition eauto.\n        \n        eexists; intuition eauto.\n        eexists; split; eauto.\n        left.\n        do 2 eexists; split; eauto.\n        right; right; intuition eauto.\n      }\n      \n    }\n    {        \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (TDCore data_length) CrashBefore]::x0); simpl.\n      eapply_fresh write_crashed in H10; eauto; cleanup.\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      simpl in *.\n      eexists; repeat split; eauto;\n      simpl in *.\n      cleanup; eauto.      \n\n      eapply_fresh write_crashed in H10; eauto; cleanup.\n      eexists; unfold refines, refines_reboot,\n               transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n    }\n    Qed.\n\n    Theorem abstract_oracles_exist_wrt_abort:\n    forall n u, \n      abstract_oracles_exist_wrt refinement refines u (|Abort|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; destruct n;\n    simpl; intros; cleanup; invert_exec.\n    {\n      exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n      intuition eauto.\n      left.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      left.\n      eexists; intuition eauto.\n\n      eapply_fresh abort_finished in H7; eauto.\n      eexists; intuition eauto.\n      unfold refines, transaction_rep in *; simpl in *; cleanup.\n      repeat cleanup_pairs; eauto.\n    }\n    {        \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      exists ([OpToken (TDCore data_length) CrashBefore]::x0); simpl.\n      eapply_fresh abort_crashed in H10; eauto; cleanup.\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      simpl in *.\n      eexists; repeat split; eauto;\n      simpl in *.\n      cleanup; eauto.\n      \n      eapply_fresh abort_crashed in H10; eauto; cleanup.\n      eexists; unfold refines, refines_reboot,\n               transaction_rep, transaction_reboot_rep in *;\n      simpl in *; cleanup; eauto.\n    }\n  Qed.\n\n  Theorem abstract_oracles_exist_wrt_commit:\n    forall n u, \n      abstract_oracles_exist_wrt refinement refines u (|Commit|) (|Recover|) (transaction_cache_reboot_list n).\n  Proof.\n    unfold abstract_oracles_exist_wrt, refines_reboot; destruct n;\n    simpl; intros; cleanup; invert_exec.\n    \n    {\n      eapply_fresh commit_finished in H7; eauto.\n      exists  [ [OpToken (TDCore data_length) Cont] ]; simpl.\n      intuition eauto.\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      unfold refines, transaction_rep in *; simpl in *; cleanup.\n      repeat cleanup_pairs; eauto.\n    }\n    {        \n      eapply abstract_oracles_exist_wrt_recover in H11; eauto; cleanup.\n      eapply_fresh commit_crashed in H10; eauto; cleanup.\n      split_ors.\n      {\n        exists ([OpToken (TDCore 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        simpl in *.\n        eexists; repeat split; eauto;\n        simpl in *.\n        cleanup; eauto.\n        right; eexists; repeat split; eauto;\n        simpl in *.\n        unfold refines, transaction_rep in *;\n        cleanup; eauto.\n      }\n      {\n        exists ([OpToken (TDCore data_length) CrashAfter]::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        simpl in *.\n        eexists; repeat split; eauto;\n        simpl in *.\n        cleanup; eauto.\n        right; eexists; repeat split; eauto;\n        simpl in *.\n        unfold refines, transaction_rep in *;\n        cleanup; eauto.\n      }\n      {\n        eapply_fresh commit_crashed in H10; eauto; cleanup.\n        split_ors;\n        unfold refines, refines_reboot,\n        transaction_rep, transaction_reboot_rep in *;\n        simpl in *; cleanup; eauto.\n        exists (Empty, (fst (snd x), fst (snd x))); simpl; eauto.\n      }\n    }\n  Qed.\n    \n  Lemma addrs_match_upd:\n    forall A AEQ V1 V2 (m1: @mem A AEQ V1) (m2: @mem A AEQ V2) a v,\n      addrs_match m1 m2 ->\n      m2 a <> None ->\n      addrs_match (upd m1 a v) m2.\n  Proof.\n    unfold addrs_match; intros; simpl.\n    destruct (AEQ a a0); subst;\n    [rewrite upd_eq in *\n    |rewrite upd_ne in *]; eauto.\n  Qed.\n\n  Lemma cons_l_neq:\n    forall V (l:list V) v,\n      ~ v::l = l.\n  Proof.\n    induction l; simpl; intros; try congruence.\n  Qed.\n\n  Lemma mem_union_some_l:\n    forall AT AEQ V (m1: @mem AT AEQ V) m2 a v,\n      m1 a = Some v ->\n      mem_union m1 m2 a = Some v.\n  Proof.\n    unfold mem_union; simpl; intros.\n    cleanup; eauto.\n  Qed.\n  \n  Lemma mem_union_some_r:\n    forall AT AEQ V (m1: @mem AT AEQ V) m2 a,\n      m1 a = None ->\n      mem_union m1 m2 a = m2 a.\n  Proof.\n    unfold mem_union; simpl; intros.\n    cleanup; eauto.\n  Qed.\n\n  Lemma addrs_match_mem_union1 :\n    forall A AEQ V (m1 m2: @mem A AEQ V),\n      addrs_match m1 (mem_union m1 m2).\n  Proof.\n    unfold addrs_match; intros.\n    destruct_fresh (m1 a); try congruence.\n    erewrite mem_union_some_l; eauto.\n  Qed.\n\n  Lemma addrs_match_empty_mem:\n    forall A AEQ V1 V2 (m: @mem A AEQ V1),\n      addrs_match (@empty_mem A AEQ V2) m.\n  Proof.\n    unfold addrs_match, empty_mem;\n    simpl; intros; congruence.\n  Qed.\n  \n  Lemma empty_mem_some_false:\n    forall A AEQ V (m: @mem A AEQ V) a v,\n      m = empty_mem ->\n      m a <> Some v.\n  Proof.\n    intros.\n    rewrite H.\n    unfold empty_mem; simpl; congruence.\n  Qed.\n  \n  \nLemma recovery_simulation :\n  forall n u,\n    SimulationForProgramGeneral _ _ _ _ refinement u _ (|Recover|) (|Recover|)\n                         (transaction_cache_reboot_list n)\n                         (transactional_disk_reboot_list n)\n                         refines_reboot refines.\nProof.\n  unfold SimulationForProgramGeneral; induction n; simpl; intros; cleanup.\n  {\n    destruct l_o_imp; intuition; simpl in *.\n    cleanup; intuition.\n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; unify_execs; cleanup;\n    cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n    \n    eexists; intuition eauto.\n    unfold transactional_disk_reboot_list in *; simpl.\n    simpl in *; try lia.\n    instantiate (1:= RFinished (Empty, (snd (snd s_abs), snd (snd s_abs))) tt). \n    repeat econstructor.\n    unfold refines, refines_reboot,\n    transaction_rep, transaction_reboot_rep in *;\n    simpl in *; cleanup; eauto.\n    intuition eauto.\n    pose proof (addr_list_to_blocks_length_le []); simpl in *; lia.\n    pose proof (addr_list_to_blocks_length_le []); simpl in *;\n    left; intuition lia.\n    simpl; destruct x3; eauto.\n    cleanup; intuition.\n  }\n  {\n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; intuition eauto; repeat (unify_execs; cleanup).\n    cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n    edestruct IHn.\n    eauto.\n    instantiate (1:= (Empty, (snd (snd s_abs), snd (snd s_abs)))).\n    eauto.\n    eauto.\n      \n    unfold refines_reboot, transaction_reboot_rep in *; simpl in *; cleanup.\n    exists (Recovered (extract_state_r x)).\n    unfold transactional_disk_reboot_list in *; simpl in *.\n    unfold refines_reboot, transaction_reboot_rep in *; cleanup.\n    split; eauto.\n    repeat econstructor; eauto.\n    repeat cleanup_pairs; eauto.\n  }\nQed.\n\n\nLemma read_simulation :\n  forall a n u,\n    SimulationForProgram refinement u (|Read a|) (|Recover|)\n                         (transaction_cache_reboot_list n)\n                         (transactional_disk_reboot_list n).\nProof.\n  unfold transaction_cache_reboot_list, SimulationForProgram,\n  SimulationForProgramGeneral; simpl; intros; cleanup.\n  \n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; try solve [intuition eauto; try congruence;\n                        unify_execs; cleanup].\n    {\n      intuition cleanup; unify_execs; cleanup.\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      eapply_fresh read_finished in H10; cleanup; eauto.\n      \n      destruct n; simpl in *; try congruence; cleanup.\n      split_ors; cleanup.\n      {\n        exists (RFinished s_abs ((fst (snd s_abs)) a));\n        simpl; intuition eauto.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n      }\n      {\n        exists (RFinished s_abs value0);\n        simpl; intuition eauto.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n      }\n    }\n    {\n      intuition cleanup; unify_execs; cleanup.\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      destruct n; simpl in *; try congruence; cleanup.\n      \n      edestruct recovery_simulation; eauto.\n      unfold refines, transaction_rep in *; cleanup.\n      instantiate (1:=(Empty, (snd (snd s_abs), snd (snd s_abs)))).\n      eauto.\n      \n      exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n      unfold transactional_disk_reboot_list; simpl.\n      eapply ExecRecovered; eauto.\n      repeat econstructor.\n    }\nQed.\n\n\n\nLemma write_simulation :\n  forall a v n u,\n    SimulationForProgram refinement u (|Write a v|) (|Recover|)\n                         (transaction_cache_reboot_list n)\n                         (transactional_disk_reboot_list n).\nProof.\n  unfold transaction_cache_reboot_list, SimulationForProgram,\n  SimulationForProgramGeneral; simpl; intros; cleanup.\n  \n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; try solve [intuition eauto; try congruence;\n                        unify_execs; cleanup].\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup;\n      destruct n; simpl in *; try congruence; cleanup;\n      simpl in *; try lia.\n\n      eapply write_finished in H10; eauto; \n      split_ors; cleanup.\n      {\n        intuition eauto; cleanup; try lia;\n        try solve [repeat cleanup_pairs;\n        exfalso; eapply cons_l_neq; eauto].\n        exists (RFinished (NotEmpty, (upd (fst (snd s_abs)) a v, snd (snd s_abs))) (Some tt));\n        simpl; split; eauto.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n      }\n      cleanup.\n      repeat split_ors; try logic_clean; try lia.\n      {\n        cleanup.\n        exists (RFinished s_abs None);\n        simpl; split; eauto.\n        intuition try lia; cleanup.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n      }\n      {\n        exfalso; eapply PeanoNat.Nat.lt_nge; eauto.\n      }\n      {\n        cleanup.\n        exists (RFinished s_abs None);\n        simpl; split; eauto.\n        intuition try lia; cleanup.\n        eapply ExecFinished.\n        do 2 econstructor.\n        solve [repeat econstructor; eauto].\n      }\n    }\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      destruct n; simpl in *; try congruence; cleanup.\n      \n      edestruct recovery_simulation; eauto.\n      unfold refines, transaction_rep in *; cleanup.\n      instantiate (1:= (Empty, (snd (snd s_abs), snd (snd s_abs)))).\n      eauto.\n      \n      exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n      unfold transactional_disk_reboot_list; simpl.\n      eapply ExecRecovered; eauto.\n      repeat econstructor.\n    }\nQed.\n\n\nLemma abort_simulation :\n  forall n u,\n    SimulationForProgram refinement u (|Abort|) (|Recover|)\n                         (transaction_cache_reboot_list n)\n                         (transactional_disk_reboot_list n).\nProof.\n  unfold transaction_cache_reboot_list, SimulationForProgram,\n  SimulationForProgramGeneral; simpl; intros; cleanup.\n  \n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; try solve [intuition eauto; try congruence;\n                        unify_execs; cleanup].\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      \n      destruct n; simpl in *; try congruence; cleanup.\n      {\n        exists (RFinished (Empty, (snd (snd s_abs), snd (snd s_abs))) tt);\n        simpl; intuition eauto.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n        unfold refines, transaction_rep in *; simpl in *; cleanup.\n        clear H1. intuition eauto.\n        pose proof (addr_list_to_blocks_length_le []); simpl in *; lia.\n        pose proof (addr_list_to_blocks_length_le []); simpl in *; \n        left; intuition lia.\n        destruct x3; eauto.\n      }\n    }\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      destruct n; simpl in *; try congruence; cleanup.\n      \n      edestruct recovery_simulation; eauto.\n      unfold refines, transaction_rep in *; cleanup.\n      instantiate (1:= (Empty, (snd (snd s_abs), snd (snd s_abs)))).\n      eauto.\n      \n      exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n      unfold transactional_disk_reboot_list; simpl.\n      eapply ExecRecovered; eauto.\n      repeat econstructor.\n    }\nQed.\n\n\nLemma commit_simulation :\n  forall n u,\n    SimulationForProgram refinement u (|Commit|) (|Recover|)\n                         (transaction_cache_reboot_list n)\n                         (transactional_disk_reboot_list n).\nProof.\n  unfold transaction_cache_reboot_list, SimulationForProgram,\n  SimulationForProgramGeneral; simpl; intros; cleanup.\n  \n    invert_exec; simpl in *; cleanup; intuition;\n    cleanup; try solve [intuition eauto; try congruence;\n                        unify_execs; cleanup].\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup.\n      \n      destruct n; simpl in *; try congruence; cleanup.\n      {\n        exists (RFinished (Empty, (fst (snd s_abs), fst (snd s_abs))) tt);\n        simpl; intuition eauto.\n        eapply ExecFinished.\n        repeat econstructor; eauto.\n        unfold refines, transaction_rep in *; simpl in *; cleanup.\n        clear H1; intuition eauto.\n        pose proof (addr_list_to_blocks_length_le []); simpl in *; lia.\n        pose proof (addr_list_to_blocks_length_le []); simpl in *; \n        left; intuition lia.\n        destruct x3; eauto.\n      }\n    }\n    {\n      intuition cleanup; unify_execs; cleanup;\n      cleanup; intuition eauto; cleanup; try unify_execs; cleanup;\n      destruct n; simpl in *; try congruence; cleanup.\n      \n      {\n        edestruct recovery_simulation; eauto.\n        unfold refines, transaction_rep in *; cleanup.\n        instantiate (1:=(Empty, (snd (snd s_abs), snd (snd s_abs)))).\n        eauto.\n\n        exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n        unfold transactional_disk_reboot_list; simpl.\n        eapply ExecRecovered; eauto.\n        repeat econstructor.\n      }\n      {\n        edestruct recovery_simulation; eauto.\n        unfold refines, transaction_rep in *; cleanup.\n        instantiate (1:=(Empty, (snd (snd s_abs), snd (snd s_abs)))).\n        eauto.\n\n        exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n        unfold transactional_disk_reboot_list; simpl.\n        eapply ExecRecovered; eauto.\n        repeat econstructor.\n      }\n      {\n        edestruct recovery_simulation; eauto.\n        unfold refines, transaction_rep in *; cleanup.\n        instantiate (1:=(Empty, (fst (snd s_abs), fst (snd s_abs)))).\n        eauto.\n        \n        exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n        unfold transactional_disk_reboot_list; simpl.\n        eapply ExecRecovered; eauto.\n        repeat econstructor.\n            simpl; eauto.\n      }\n      {\n        edestruct recovery_simulation; eauto.\n        unfold refines, transaction_rep in *; cleanup.\n        instantiate (1:=(Empty, (fst (snd s_abs), fst (snd s_abs)))).\n        eauto.\n        \n        exists (Recovered (extract_state_r x0)); simpl; intuition eauto.\n        unfold transactional_disk_reboot_list; simpl.\n        eapply ExecRecovered; eauto.\n        repeat econstructor.\n            simpl; eauto.\n      }\n    }\nQed.\n\n\n    \nLemma TC_to_TD_core_simulation_finished:\nforall u (T : Type) (o0 : transactional_disk_prog T)\n(s_imp\n s_imp' : HorizontalComposition.state' (ListOperation (addr * value))\n            (LoggedDiskOperation log_length data_length))\ns_abs (r : T)\n(o_imp : oracle' TransactionCacheOperation)\nt_abs\n(grs : HorizontalComposition.state' (ListOperation (addr * value))\n         (LoggedDiskOperation log_length data_length) ->\n       HorizontalComposition.state' (ListOperation (addr * value))\n         (LoggedDiskOperation log_length data_length)),\nexec Definitions.imp u o_imp s_imp\n(TransactionToTransactionalDisk.Definitions.compile T o0)\n(Finished s_imp' r) ->\nrefines s_imp s_abs ->\ntoken_refines T u s_imp o0 grs\no_imp t_abs ->\nexists s_abs',\nexec' data_length u t_abs s_abs o0\n  (Finished s_abs' r) /\\\nrefines s_imp' s_abs'.\nProof.\n  intros.\n  destruct o0; simpl in *; split_ors; \n  cleanup; repeat unify_execs; cleanup.\n  \n  {\n    eapply Transaction.read_finished in H1; cleanup; eauto.\n    split_ors; cleanup; eexists; split; eauto;\n    econstructor; eauto.\n  }\n  {\n    eapply Transaction.write_finished in H1; cleanup; eauto.\n    do 2 split_ors; cleanup; \n    try solve [eexists; split; eauto;\n    econstructor; eauto].\n\n    split_ors; cleanup; \n    try solve [eexists; split; eauto;\n    econstructor; eauto].\n    \n    destruct s_imp; cleanup.\n    exfalso; eapply cons_l_neq; eauto.\n    apply H5.\n\n    destruct s_imp; cleanup.\n    exfalso; eapply cons_l_neq; eauto.\n    apply H6.\n\n    destruct s_imp; cleanup.\n    exfalso; eapply cons_l_neq; eauto.\n    apply H1.\n\n    do 2 split_ors; cleanup; \n    try solve [eexists; split; eauto;\n    econstructor; eauto].\n  }\n  {\n    eapply Transaction.commit_finished in H1; cleanup; eauto.\n    cleanup; eexists; split; eauto.\n    destruct r; econstructor; eauto.\n  }\n  {\n    eapply Transaction.abort_finished in H1; cleanup; eauto.\n    cleanup; eexists; split; eauto.\n    destruct r; econstructor; eauto.\n    unfold refines,\n    Transaction.transaction_rep in *; simpl in *; cleanup.\n    clear H3; intuition eauto.\n    pose proof addr_list_to_blocks_length_le.\n    specialize (H []); simpl in *; lia.\n    pose proof (addr_list_to_blocks_length_le []); simpl in *; \n    left; intuition lia.\n  }\n  {\n    eapply Transaction.recover_finished in H1; cleanup; eauto.\n    cleanup; eexists; split; eauto.\n    destruct r; econstructor; eauto.\n    unfold refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n  }\n  {\n    eapply Transaction.init_finished in H1; cleanup; eauto.\n    cleanup; eexists; split; eauto.\n    destruct r; econstructor; eauto.\n    unfold refines,\n    Transaction.transaction_rep in *; simpl in *; cleanup.\n    clear H3; intuition eauto.\n    pose proof addr_list_to_blocks_length_le.\n    specialize (H []); simpl in *; lia.\n    pose proof (addr_list_to_blocks_length_le []); simpl in *; \n        left; intuition lia.\n  }\nQed.\n\nLemma TC_to_TD_core_simulation_crashed:\nforall u (T : Type) (o0 : operation Definitions.abs_op T)\n(s_imp s_imp' : LayerImplementation.state' TransactionCacheOperation)\ns_abs (o_imp : oracle' TransactionCacheOperation)\nt_abs,\nexec Definitions.imp u o_imp s_imp\n(compile T o0) \n(Crashed s_imp') ->\nrefines s_imp s_abs ->\ntoken_refines T u s_imp o0\nTC_reboot_f o_imp t_abs ->\n\n(forall l, ~ eq_dep Type (operation Definitions.abs_op) T o0 unit (Init l)) ->\nexists\ns_abs',\nCore.exec (TransactionalDiskLayer.TDCore data_length) u\nt_abs s_abs o0 (Crashed s_abs') /\\\nrefines_reboot\n(TC_reboot_f s_imp') (TD_reboot_f s_abs').\nProof.\n  intros.\n  destruct o0; simpl in *; split_ors; \n  cleanup; repeat unify_execs; cleanup.\n  \n  {\n    eapply Transaction.read_crashed in H1; cleanup; eauto.\n    eexists; split; eauto.\n    econstructor; eauto.\n    unfold TC_reboot_f, TD_reboot_f; simpl in *.\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n  }\n  {\n    eapply Transaction.write_crashed in H1; cleanup; eauto.\n    eexists; split; eauto.\n    econstructor; eauto.\n    unfold TC_reboot_f, TD_reboot_f; simpl in *.\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n  }\n  {\n    eapply Transaction.commit_crashed in H1; cleanup; eauto.\n    repeat split_ors; cleanup; eexists; split; eauto;\n    try solve [econstructor; eauto].\n    \n    unfold TC_reboot_f, TD_reboot_f; simpl in *;\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup_no_match; eauto.\n\n    unfold TC_reboot_f, TD_reboot_f; simpl in *;\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup_no_match; eauto.\n\n    unfold TC_reboot_f, TD_reboot_f; simpl in *;\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; logic_clean; rewrite H8; eauto.\n    \n    unfold TC_reboot_f, TD_reboot_f; simpl in *;\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup_no_match; eauto.\n  }\n  {\n    eapply Transaction.abort_crashed in H1; cleanup; eauto.\n    eexists; split; eauto.\n    econstructor; eauto.\n    unfold TC_reboot_f, TD_reboot_f; simpl in *.\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n  }\n  {\n    eapply Transaction.recover_crashed in H1; cleanup; eauto.\n    eexists; split; eauto.\n    econstructor; eauto.\n    unfold TC_reboot_f, TD_reboot_f; simpl in *.\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n\n    unfold refines_reboot , refines,\n    Transaction.transaction_rep,  Transaction.transaction_reboot_rep in *; \n    simpl in *; cleanup; eauto.\n  }\n  {\n    exfalso; eapply H2; eauto.\n  }\nQed.\n\nLemma TD_token_refines_finished :\n      forall u (T : Type) (op : operation Definitions.abs_op T)\n      (x : oracle' TransactionCacheOperation) (r0 : T)\n      (s0 s'0 : LayerImplementation.state' TransactionCacheOperation),\n    exec Definitions.imp u x s0\n      (compile_core Definitions.TDCoreRefinement op)\n      (Finished s'0 r0) ->\n    (exists s1 : Core.state Definitions.abs_op,\n       refines_core Definitions.TDCoreRefinement s0 s1) ->\n    exists\n      (grs1 : state Definitions.imp -> state Definitions.imp) t,\n      token_refines T u s0 op grs1 x t.\n      Proof.\n      intros; cleanup; destruct op; simpl in *; repeat invert_exec.\n      \n      - do 2 eexists; try exact (fst s0); try exact (snd s0);\n        left; do 2 eexists; intuition eauto.\n        eapply Transaction.read_finished; eauto.\n        \n      - eapply_fresh Transaction.write_finished in H; eauto.\n        split_ors; cleanup; intuition eauto;\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        left; do 2 eexists; intuition eauto.\n        + left; intuition eauto.\n          unfold Transaction.transaction_rep in *; simpl in *.\n          cleanup.\n          inversion H1; eauto.\n        \n      - eapply_fresh Transaction.commit_finished in H; eauto;\n        cleanup; intuition eauto;\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        left; do 2 eexists; intuition eauto.\n        destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; eauto.\n\n      - eapply_fresh Transaction.abort_finished in H; eauto;\n      cleanup; intuition eauto;\n      do 2 eexists; try exact (fst s0); try exact (snd s0);\n      left; do 2 eexists; intuition eauto.\n      destruct s'0; simpl in *; cleanup; eauto.\n\n      - eapply_fresh Transaction.recover_finished in H; eauto;\n        cleanup; intuition eauto.\n        2: {\n          unfold refines,\n          Transaction.transaction_rep, Transaction.transaction_reboot_rep in *; simpl in *;\n          cleanup; eauto.\n        }\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        left; do 2 eexists; intuition eauto.\n        destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; eauto.\n\n      - eapply_fresh Transaction.init_finished in H; eauto;\n        cleanup; intuition eauto.\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        left; do 2 eexists; intuition eauto.\n        destruct s'0; simpl in *; cleanup; eauto.\n      Qed.\n\n      Lemma TD_token_refines_crashed :\n      forall u (T : Type) (op : operation Definitions.abs_op T)\n  (x : oracle' TransactionCacheOperation)\n  (s0 s'0 : LayerImplementation.state' TransactionCacheOperation),\nexec Definitions.imp u x s0\n  (compile_core Definitions.TDCoreRefinement op) \n  (Crashed s'0) ->\n(exists s1 : Core.state Definitions.abs_op,\n   refines_core Definitions.TDCoreRefinement s0 s1) ->\n   (forall l, ~ Logic.EqdepFacts.eq_dep Type (operation Definitions.abs_op)  T op unit (Init l)) ->\n   exists\n  (grs1 : state Definitions.imp -> state Definitions.imp) t,\n  token_refines T u s0 op grs1 x t.\n      Proof.\n      intros; cleanup; destruct op; simpl in *; repeat invert_exec.\n      \n      - do 2 eexists; try exact (fst s0); try exact (snd s0);\n        right; eexists; intuition eauto.\n        eapply Transaction.read_crashed; eauto.\n        \n      - eapply_fresh Transaction.write_crashed in H; eauto.\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        right; eexists; intuition eauto.\n        \n      - eapply_fresh Transaction.commit_crashed in H; eauto;\n        cleanup; intuition eauto;\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        right; eexists; intuition eauto.\n        left; destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; eauto.\n\n        left; destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; intuition eauto.\n\n        right; destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; eauto.\n\n        right; destruct s'0; simpl in *; cleanup.\n        unfold refines, \n        Transaction.transaction_rep in *; simpl in *.\n        cleanup; intuition eauto.\n\n      - eapply_fresh Transaction.abort_crashed in H; eauto;\n      cleanup; intuition eauto;\n      do 2 eexists; try exact (fst s0); try exact (snd s0);\n      right; eexists; intuition eauto.\n\n      - eapply_fresh Transaction.recover_crashed in H; eauto;\n        cleanup; intuition eauto.\n        2: {\n          unfold refines,\n          Transaction.transaction_rep, Transaction.transaction_reboot_rep in *; simpl in *;\n          cleanup; eauto.\n        }\n        do 2 eexists; try exact (fst s0); try exact (snd s0);\n        right; eexists; intuition eauto.\n\n      - exfalso; eapply H1; eauto.\n      Qed.\n\n\nLemma TD_token_refines :\n      forall u (T : Type) (op : operation Definitions.abs_op T)\n  (x : oracle' TransactionCacheOperation)\n  (s0 : LayerImplementation.state' TransactionCacheOperation) ret,\nexec Definitions.imp u x s0\n  (compile_core Definitions.TDCoreRefinement op) \n  ret ->\n(exists s1 : Core.state Definitions.abs_op,\n   refines_core Definitions.TDCoreRefinement s0 s1) ->\n   (forall l, ~ Logic.EqdepFacts.eq_dep Type (operation Definitions.abs_op)  T op unit (Init l)) ->\n   exists\n  (grs1 : state Definitions.imp -> state Definitions.imp) t,\n  token_refines T u s0 op grs1 x t.\nProof.\n  intros.\n  destruct ret.\n  eapply TD_token_refines_finished; eauto.\n  eapply TD_token_refines_crashed; eauto.\nQed.", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/src/Refinements/TransactionToTransactionalDisk/Refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.19122012739645172}}
{"text": "From 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 Require Import util Sorts SAst SLiftSubst SCommon Equality.\n\nReserved Notation \" \u03a3 ;;; \u0393 '|-x' t : T \" (at level 50, \u0393, t, T at next level).\nReserved Notation \" \u03a3 ;;; \u0393 '|-x' t \u2261 u : T \" (at level 50, \u0393, t, u, T at next level).\n\nOpen Scope s_scope.\n\nSection XTyping.\n\nContext `{Sort_notion : Sorts.notion}.\n\nDeclare Scope x_scope.\n\nInductive typing (\u03a3 : sglobal_context) (\u0393 : scontext) : sterm -> sterm -> Type :=\n| type_Rel n :\n    forall (isdecl : n < List.length \u0393),\n      \u03a3 ;;; \u0393 |-x (sRel n) : lift0 (S n) (safe_nth \u0393 (exist _ n isdecl))\n\n| type_Sort s :\n    \u03a3 ;;; \u0393 |-x (sSort s) : sSort (succ s)\n\n| type_Prod n t b s1 s2 :\n    \u03a3 ;;; \u0393 |-x t : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, t |-x b : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x (sProd n t b) : sSort (Sorts.prod_sort s1 s2)\n\n| type_Lambda n n' t b s1 s2 bty :\n    \u03a3 ;;; \u0393 |-x t : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, t |-x bty : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, t |-x b : bty ->\n    \u03a3 ;;; \u0393 |-x (sLambda n t bty b) : sProd n' t bty\n\n| type_App n s1 s2 t A B u :\n    \u03a3 ;;; \u0393 |-x A : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A |-x B : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x t : sProd n A B ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x (sApp t A B u) : B{ 0 := u }\n\n| type_Sum n t b s1 s2 :\n    \u03a3 ;;; \u0393 |-x t : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, t |-x b : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x (sSum n t b) : sSort (Sorts.sum_sort s1 s2)\n\n| type_Pair n A B u v s1 s2 :\n    \u03a3 ;;; \u0393 |-x A : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A |-x B : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x v : B{ 0 := u } ->\n    \u03a3 ;;; \u0393 |-x sPair A B u v : sSum n A B\n\n| type_Pi1 n A B s1 s2 p :\n    \u03a3 ;;; \u0393 |-x p : sSum n A B ->\n    \u03a3 ;;; \u0393 |-x A : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A |-x B : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x sPi1 A B p : A\n\n| type_Pi2 n A B s1 s2 p :\n    \u03a3 ;;; \u0393 |-x p : sSum n A B ->\n    \u03a3 ;;; \u0393 |-x A : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A |-x B : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x sPi2 A B p : B{ 0 := sPi1 A B p }\n\n| type_Eq s A u v :\n    \u03a3 ;;; \u0393 |-x A : sSort s ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x v : A ->\n    \u03a3 ;;; \u0393 |-x sEq A u v : sSort (Sorts.eq_sort s)\n\n| type_Refl s A u :\n    \u03a3 ;;; \u0393 |-x A : sSort s ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x sRefl A u : sEq A u u\n\n| type_Ax id ty :\n    lookup_glob \u03a3 id = Some ty ->\n    \u03a3 ;;; \u0393 |-x sAx id : ty\n\n| type_conv t A B s :\n    \u03a3 ;;; \u0393 |-x t : A ->\n    \u03a3 ;;; \u0393 |-x B : sSort s ->\n    \u03a3 ;;; \u0393 |-x A \u2261 B : sSort s ->\n    \u03a3 ;;; \u0393 |-x t : B\n\nwhere \" \u03a3 ;;; \u0393 '|-x' t : T \" := (@typing \u03a3 \u0393 t T) : x_scope\n\nwith eq_term (\u03a3 : sglobal_context) (\u0393 : scontext) : sterm -> sterm -> sterm -> Type :=\n| eq_reflexivity u A :\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x u \u2261 u : A\n\n| eq_symmetry u v A :\n    \u03a3 ;;; \u0393 |-x u \u2261 v : A ->\n    \u03a3 ;;; \u0393 |-x v \u2261 u : A\n\n| eq_transitivity u v w A :\n    \u03a3 ;;; \u0393 |-x u \u2261 v : A ->\n    \u03a3 ;;; \u0393 |-x v \u2261 w : A ->\n    \u03a3 ;;; \u0393 |-x u \u2261 w : A\n\n| eq_beta s1 s2 n A B t u :\n    \u03a3 ;;; \u0393 |-x A : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A |-x B : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A |-x t : B ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x sApp (sLambda n A B t) A B u \u2261 t{ 0 := u } : B{ 0 := u }\n\n| eq_conv s T1 T2 t1 t2 :\n    \u03a3 ;;; \u0393 |-x t1 \u2261 t2 : T1 ->\n    \u03a3 ;;; \u0393 |-x T1 \u2261 T2 : sSort s ->\n    \u03a3 ;;; \u0393 |-x t1 \u2261 t2 : T2\n\n| cong_Prod n1 n2 A1 A2 B1 B2 s1 s2 :\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x (sProd n1 A1 B1) \u2261 (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    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x t1 \u2261 t2 : B1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x t1 : B1 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x t2 : B2 ->\n    \u03a3 ;;; \u0393 |-x (sLambda n1 A1 B1 t1) \u2261 (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    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x t1 \u2261 t2 : sProd n1 A1 B1 ->\n    \u03a3 ;;; \u0393 |-x u1 \u2261 u2 : A1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x t1 : sProd n1 A1 B1 ->\n    \u03a3 ;;; \u0393 |-x t2 : sProd n2 A2 B2 ->\n    \u03a3 ;;; \u0393 |-x u1 : A1 ->\n    \u03a3 ;;; \u0393 |-x u2 : A2 ->\n    \u03a3 ;;; \u0393 |-x (sApp t1 A1 B1 u1) \u2261 (sApp t2 A2 B2 u2) : B1{ 0 := u1 }\n\n| cong_Sum n1 n2 A1 A2 B1 B2 s1 s2 :\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x (sSum n1 A1 B1) \u2261 (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    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x u1 \u2261 u2 : A1 ->\n    \u03a3 ;;; \u0393 |-x v1 \u2261 v2 : B1{ 0 := u1 } ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x u1 : A1 ->\n    \u03a3 ;;; \u0393 |-x u2 : A2 ->\n    \u03a3 ;;; \u0393 |-x v1 : B1{ 0 := u1 } ->\n    \u03a3 ;;; \u0393 |-x v2 : B2{ 0 := u2 } ->\n    \u03a3 ;;; \u0393 |-x sPair A1 B1 u1 v1 \u2261 sPair A2 B2 u2 v2 : sSum n A1 B1\n\n| cong_Pi1 nx ny A1 A2 B1 B2 s1 s2 p1 p2 :\n    \u03a3 ;;; \u0393 |-x p1 \u2261 p2 : sSum nx A1 B1 ->\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x p1 : sSum nx A1 B1 ->\n    \u03a3 ;;; \u0393 |-x p2 : sSum ny A2 B2 ->\n    \u03a3 ;;; \u0393 |-x sPi1 A1 B1 p1 \u2261 sPi1 A2 B2 p2 : A1\n\n| cong_Pi2 nx ny A1 A2 B1 B2 s1 s2 p1 p2 :\n    \u03a3 ;;; \u0393 |-x p1 \u2261 p2 : sSum nx A1 B1 ->\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s1 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 \u2261 B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A1 |-x B1 : sSort s2 ->\n    \u03a3 ;;; \u0393 ,, A2 |-x B2 : sSort s2 ->\n    \u03a3 ;;; \u0393 |-x p1 : sSum nx A1 B1 ->\n    \u03a3 ;;; \u0393 |-x p2 : sSum ny A2 B2 ->\n    \u03a3 ;;; \u0393 |-x sPi2 A1 B1 p1 \u2261 sPi2 A2 B2 p2 : B1{ 0 := sPi1 A1 B1 p1 }\n\n| cong_Eq s A1 A2 u1 u2 v1 v2 :\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s ->\n    \u03a3 ;;; \u0393 |-x u1 \u2261 u2 : A1 ->\n    \u03a3 ;;; \u0393 |-x v1 \u2261 v2 : A1 ->\n    \u03a3 ;;; \u0393 |-x sEq A1 u1 v1 \u2261 sEq A2 u2 v2 : sSort (Sorts.eq_sort s)\n\n| cong_Refl s A1 A2 u1 u2 :\n    \u03a3 ;;; \u0393 |-x A1 \u2261 A2 : sSort s ->\n    \u03a3 ;;; \u0393 |-x u1 \u2261 u2 : A1 ->\n    \u03a3 ;;; \u0393 |-x sRefl A1 u1 \u2261 sRefl A2 u2 : sEq A1 u1 u1\n\n| reflection A u v e :\n    \u03a3 ;;; \u0393 |-x e : sEq A u v ->\n    \u03a3 ;;; \u0393 |-x u \u2261 v : A\n\n| eq_alpha u v A :\n    nl u = nl v ->\n    \u03a3 ;;; \u0393 |-x u : A ->\n    \u03a3 ;;; \u0393 |-x u \u2261 v : A\n\nwhere \" \u03a3 ;;; \u0393 '|-x' t \u2261 u : T \" := (@eq_term \u03a3 \u0393 t u T) : x_scope.\n\nDelimit Scope x_scope with x.\n\nOpen Scope x_scope.\n\nInductive wf (\u03a3 : sglobal_context) : scontext -> Type :=\n| wf_nil :\n    wf \u03a3 nil\n\n| wf_snoc \u0393 A s :\n    wf \u03a3 \u0393 ->\n    \u03a3 ;;; \u0393 |-x A : sSort s ->\n    wf \u03a3 (\u0393 ,, A).\n\nDerive Signature for typing.\nDerive Signature for wf.\nDerive Signature for eq_term.\n\nEnd XTyping.\n\nDeclare Scope x_scope.\n\nNotation \" \u03a3 ;;; \u0393 '|-x' t : T \" :=\n  (@typing _ \u03a3 \u0393 t T) (at level 50, \u0393, t, T at next level) : x_scope.\nNotation \" \u03a3 ;;; \u0393 '|-x' t \u2261 u : T \" :=\n  (@eq_term _ \u03a3 \u0393 t u T) (at level 50, \u0393, t, u, T at next level) : x_scope.", "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/XTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.19122011977281714}}
{"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 PROC                                             *)\n(*                                                                     *)\n(*          Refinement Proof for PAbQueue.v                            *)\n(*                                                                     *)\n(*          Yu Guo <yu.guo@yale.edu>                                   *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import PQueueInit.\nRequire Import PAbQueue.\nRequire Import LayerCalculusLemma.\nRequire Import CalRealProcModule.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := pabqueue_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := pqueueinit_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** ** Definition the refinement relation: relate_RData + match_RData *)    \n    Section REFINEMENT_REL.\n      \n      Fixpoint abqueue_match_next_prev_rec (l : list Z) (ending: Z) (hd tl: Z) (starting: Z) \n               (tcb: TCBPool) : Prop := \n        match l with\n          | nil => hd = num_proc /\\ tl = num_proc\n          | cons t nil => hd = t /\\ tl = t /\\ exists st, \n                                                ZMap.get t tcb = TCBValid st ending starting\n                                                                          \n          | cons t l' => tl = t /\\ exists st, exists prev,\n                                                ZMap.get t tcb = TCBValid st prev starting\n                                                /\\ abqueue_match_next_prev_rec l' ending hd prev t tcb\n        end.\n      \n      Definition abqueue_match_dllist (abq: AbQueuePool) (tcb: TCBPool) (tdq: TDQueuePool): Prop := \n        forall qi l, \n          0<= qi <= num_chan\n          -> ZMap.get qi abq = AbQValid l \n          -> exists hd, exists tl, \n                          ZMap.get qi tdq = TDQValid hd tl\n                          /\\ abqueue_match_next_prev_rec l num_proc hd tl num_proc tcb.\n\n      Definition abtcbpool_tcbpool (abtcb: AbTCBPool) (tcb: TCBPool) : Prop :=\n        forall i tds inq, \n          0 <= i < num_proc ->\n          ZMap.get i abtcb = AbTCBValid tds inq\n          -> exists pv, exists nx,\n                          ZMap.get i tcb = TCBValid tds pv nx.\n\n      Inductive AbQ_RealQ: AbTCBPool -> AbQueuePool -> TCBPool -> TDQueuePool -> Prop:=\n      | AbQ_RealQ_con : \n          forall abtcb abq tcb tdq,\n            abqueue_match_dllist abq tcb tdq\n            -> abtcbpool_tcbpool abtcb tcb\n            -> AbQ_RealQ abtcb abq tcb tdq.\n\n      (** Relation between raw data at two layers*)\n      Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n        mkrelate_RData {\n            flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n            vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n            devout_re: devout hadt = devout ladt;\n            CR3_re:  CR3 hadt = CR3 ladt;\n            ikern_re: ikern hadt = ikern ladt;\n            pg_re: pg hadt = pg ladt;\n            ihost_re: ihost hadt = ihost ladt;\n            AC_re: AC hadt = AC ladt;\n            ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n            ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n            LAT_re: LAT hadt = LAT ladt;\n            nps_re: nps hadt = nps ladt;\n            init_re: init hadt = init ladt;\n\n            pperm_re: pperm hadt = pperm ladt;\n            PT_re:  PT hadt = PT ladt;\n            ptp_re: ptpool hadt = ptpool ladt;\n            idpde_re: idpde hadt = idpde ladt;\n            ipt_re: ipt hadt = ipt ladt;\n            smspool_re: smspool hadt = smspool ladt;\n\n            kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n            abq_re: AbQ_RealQ (abtcb hadt) \n                              (abq hadt) \n                              (tcb ladt) \n                              (tdq ladt) \n          }.\n\n      Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n      | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n      Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n        {\n          relate_AbData s f d1 d2 := relate_RData f d1 d2;\n          match_AbData s d1 m f := match_RData s d1 m f;\n          new_glbl := nil\n        }.    \n\n    End REFINEMENT_REL.\n\n    Local Hint Resolve MATCH_RDATA.\n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n        - eapply kctxt_inj_incr; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the initial state of low level specifications can be matched*)\n    Section Init_Relation.\n\n      Lemma AbQ_RealQ_init:\n        AbQ_RealQ (ZMap.init AbTCBUndef) (ZMap.init AbQUndef) (ZMap.init TCBUndef) (ZMap.init TDQUndef).\n      Proof.\n        constructor.\n        * intros qi l Hqi Hl.\n          rewrite ZMap.gi in Hl.\n          discriminate Hl.\n        * intros i tds inq Hi H.\n          rewrite ZMap.gi in H.\n          discriminate H.\n      Qed.\n\n    End Init_Relation.\n\n    Lemma match_next_prev_presv_set_notin : \n      forall l start ending hd tl tcbp,\n        abqueue_match_next_prev_rec l ending hd tl start tcbp\n        -> forall i, ~ In i l\n                     -> forall tcb, abqueue_match_next_prev_rec l ending hd tl start (ZMap.set i tcb tcbp).\n    Proof.\n      intros l start ending hd tl tcbp.\n      assert (forall start tl, abqueue_match_next_prev_rec l ending hd tl start tcbp\n                               -> forall i : Z,\n                                    ~ In i l ->\n                                    forall tcb : TCB,\n                                      abqueue_match_next_prev_rec l ending hd tl start (ZMap.set i tcb tcbp)).\n      clear.\n      induction l; simpl in *.\n      intros; trivial.\n      \n      intros.\n      destruct l.\n      destruct H as [Hhd [Htl [st Hst]]].\n      split; trivial.\n      split; trivial.\n      exists st.\n      rewrite ZMap.gsspec.\n      unfold ZIndexed.eq.\n      destruct (zeq a i); trivial.\n      apply False_ind.\n      apply H0.\n      left; trivial.\n      (* induction step *)\n      destruct H.\n      split; trivial.\n      destruct H1 as [st [pv' H1]].\n      exists st; exists pv'.\n      split.\n      destruct H1.\n      rewrite ZMap.gsspec.\n      unfold ZIndexed.eq.\n      destruct (zeq a i); trivial.\n      apply False_ind.\n      apply H0.\n      left; trivial.\n      destruct H1.\n      apply IHl; auto.\n      intros.\n      apply H; auto.\n    Qed.\n\n    Definition abqueue_valid_Q (abq: AbQueuePool) : Prop :=\n      forall qi, \n        0<= qi <= num_chan\n        -> exists l, ZMap.get qi abq = AbQValid l.\n\n    Definition abqueue_valid_abtcb (abtcb: AbTCBPool) : Prop :=\n      forall i, \n        0<= i < num_proc\n        -> exists s inq, ZMap.get i abtcb = AbTCBValid s inq.\n\n    Definition abqueue_valid_inQ (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall i qi l, \n        0<= i < num_proc\n        -> 0<= qi <= num_chan\n        -> ZMap.get qi abq = AbQValid l\n        -> In i l\n        -> exists s, ZMap.get i abtcb = AbTCBValid s qi.          \n\n    Definition abqueue_abq_range (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall qi i l, \n        0<= qi <= num_chan\n        -> ZMap.get qi abq = AbQValid l\n        -> In i l\n        -> 0 <= i < num_proc.\n\n    Definition abqueue_disjoint (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall qi i l,\n        0 <= qi <= num_chan\n        -> 0<= i < num_proc\n        -> ZMap.get qi abq = AbQValid l \n        -> In i l\n        -> forall qi' l',\n             0 <= qi' <= num_chan\n             -> qi' <> qi\n             -> ZMap.get qi' abq = AbQValid l'\n             -> ~ In i l'.\n\n    Definition abqueue_notinQ (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall i tds, \n        0<= i < num_proc\n        -> ZMap.get i  abtcb = AbTCBValid tds (-1)\n        -> forall qi l,\n             0<= qi <= num_chan\n             -> ZMap.get qi abq = AbQValid l\n             -> ~ In i l.\n\n    Definition abqueue_valid_count (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall i s inq, \n        0<= i < num_proc\n        -> ZMap.get i abtcb = AbTCBValid s inq\n        -> (forall qi l,\n              0<= qi <= num_chan\n              -> ZMap.get qi abq = AbQValid l\n              -> ((qi = inq -> count_occ zeq l i = 1%nat)\n                  /\\ (qi <> inq -> ~ In i l))).\n\n    Definition abqueue_abq_mapto_abtcb  (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop := \n      forall i, \n        0 <= i < num_proc \n        -> exists st inq, ZMap.get i abtcb = AbTCBValid st inq\n                          /\\ ((inq = -1) \\/ (0 <= inq <= num_chan)).\n\n    Definition abqueue_queue_disjoint (abtcb: AbTCBPool) (abq: AbQueuePool) : Prop :=\n      forall qi l,\n        0 <= qi <= num_chan\n        -> ZMap.get qi abq = AbQValid l\n        -> forall i,\n             0<=i < num_proc\n             -> In i l\n             -> count_occ zeq l i = 1%nat.\n\n    Lemma abqueue_INV_implies_queue_disjoint : \n      forall abtcb abq,\n        abqueue_valid_count abtcb abq\n        -> abqueue_valid_inQ abtcb abq\n        -> abqueue_queue_disjoint abtcb abq.\n    Proof.\n      clear.\n      unfold abqueue_valid_count, abqueue_valid_inQ, abqueue_queue_disjoint.\n      intros abtcb abq.\n      intros Hcount HinQ.\n      intros qi l Hqi Hgetqi i Hi Hin.\n      destruct (HinQ _ _ _ Hi Hqi Hgetqi Hin) as [s Hgeti].\n      destruct (Hcount _ _ _ Hi Hgeti qi l Hqi Hgetqi).\n      apply H; trivial.\n    Qed.    \n\n    Lemma abqueue_INV_implies_disjoint : \n      forall abtcb abq,\n        abqueue_abq_mapto_abtcb abtcb abq\n        -> abqueue_valid_count abtcb abq\n        -> abqueue_valid_inQ abtcb abq\n        -> abqueue_disjoint abtcb abq.\n    Proof.\n      clear.\n      unfold abqueue_valid_count, abqueue_valid_inQ, abqueue_disjoint, abqueue_abq_mapto_abtcb.\n      intros abtcb abq.\n      intros Habq_abtcb Hcount HinQ.\n      intros qi i l Hqi Hi Hgetqi Hil.\n      intros qi' l' Hqi' Hneq Hgetqi'.\n      destruct (Habq_abtcb i Hi) as [st [inq [Hgeti _]]].\n      destruct (HinQ _ _ _ Hi Hqi Hgetqi Hil) as [st' Hx].\n      rewrite Hgeti in Hx.\n      inversion Hx; subst st' inq.\n      destruct (Hcount i st qi Hi Hgeti qi' l' Hqi' Hgetqi').\n      auto.\n    Qed.    \n\n    Lemma abqueue_INV_implies_notinQ: \n      forall abtcb abq,\n        abqueue_abq_mapto_abtcb abtcb abq\n        -> abqueue_valid_count abtcb abq\n        -> abqueue_valid_inQ abtcb abq\n        -> abqueue_notinQ abtcb abq. \n    Proof.\n      clear.\n      unfold abqueue_valid_count, abqueue_valid_inQ, abqueue_disjoint, abqueue_abq_mapto_abtcb.\n      intros abtcb abq.\n      intros Habq_abtcb Hcount HinQ.\n      intros i s Hi Hgeti qi l Hqi Hgetqi.\n      destruct (Hcount i s (-1) Hi Hgeti qi l Hqi Hgetqi).\n      apply H0.\n      omega.\n    Qed.    \n\n    Ltac zeq_simpl :=\n      let Heq := fresh \"Heq\" in\n      let Hneq := fresh \"Hneq\" in\n      match goal with \n        | H: _ |- context [ zeq ?z ?z ] => destruct (zeq z z) as [Heq | Hneq]\n                                           ; [ | destruct (Hneq (refl_equal _))]\n        | H: context [ zeq ?z ?z ] |- _  => destruct (zeq z z) as [Heq | Hneq]\n                                            ; [ | destruct (Hneq (refl_equal _))]\n\n        | H : ?z = ?z' |- context [ zeq ?z ?z' ] => destruct (zeq z z') as [ _ | Hneq ]\n                                                    ; [ | destruct (Hneq H) ]\n        | H : ?z = ?z',\n              H1 : context [ zeq ?z ?z' ] |- _ => destruct (zeq z z') as [ _ | Hneq]\n                                                  ; [ | destruct (Hneq H) ]\n\n        | H : ?z = ?z' |- context [ zeq ?z' ?z ] => destruct (zeq z' z) as [ _ | Hneq ]\n                                                    ; [ | destruct (Hneq (eq_sym H)) ]\n        | H : ?z = ?z',\n              H1 : context [ zeq ?z' ?z ] |- _ => destruct (zeq z' z) as [ _ | Hneq]\n                                                  ; [ | destruct (Hneq (eq_sym H)) ]\n\n        | H : ?z <> ?z' |- context [ zeq ?z ?z' ] => destruct (zeq z z') as [Heq | _ ]\n                                                     ; [ destruct (H Heq) | ]\n\n        | H : ?z <> ?z',\n              H1 : context [ zeq ?z ?z' ] |- _ => destruct (zeq z z') as [Heq | _ ]\n                                                  ; [ destruct (H Heq) | ]\n\n        | H : ?z <> ?z' |- context [ zeq ?z' ?z ] => destruct (zeq z' z) as [Heq | _ ]\n                                                     ; [ destruct (H (eq_sym Heq)) | ]\n\n        | H : ?z <> ?z',\n              H1 : context [ zeq ?z' ?z ] |- _ => destruct (zeq z' z) as [Heq | _ ]\n                                                  ; [ destruct (H (eq_sym Heq)) | ]\n\n        | H :  context [ zeq ?z ?z' ] |- _ => destruct (zeq z z') as [Heq | Hneq ]\n        | H : _ |- context [ zeq ?z ?z' ] => destruct (zeq z z') as [Heq | Hneq ]\n\n      end.\n\n    Ltac rew_arith t :=\n      let Hx := fresh \"Hx\" in \n      assert (Hx : t); [try omega; try (clear; intros; omega) | rewrite Hx; clear Hx].\n\n    Ltac rew_arith_H t H :=\n      let Hx := fresh \"Hx\" in \n      assert (Hx : t); [try omega; try (clear; intros; omega) | rewrite Hx in H; clear Hx].\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      (** ** The low level specifications exist*)\n      Section Exists.\n\n        (*Lemma trapin_exist:\n          forall habd habd' labd f,\n            PAbQueue.trapin_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.trapin_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PAbQueue.trapin_spec, PQueueInit.trapin_spec; intros until f; exist_simpl.          \n        Qed.\n\n        Lemma trapout_exist:\n          forall habd habd' labd f,\n            PAbQueue.trapout_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.trapout_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.trapout_spec, PAbQueue.trapout_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma hostin_exist:\n          forall habd habd' labd f,\n            PAbQueue.hostin_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.hostin_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.hostin_spec, PAbQueue.hostin_spec; intros until f; exist_simpl.          \n        Qed.\n\n        Lemma hostout_exist:\n          forall habd habd' labd f,\n            PAbQueue.hostout_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.hostout_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.hostout_spec, PAbQueue.hostout_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma ptin_exist:\n          forall habd habd' labd f,\n            PAbQueue.ptin_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> PAbQueue.high_level_invariant habd\n            -> exists labd', PQueueInit.ptin_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.ptin_spec, PAbQueue.ptin_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma ptout_exist:\n          forall habd habd' labd f,\n            PAbQueue.ptout_spec habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.ptout_spec labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.ptout_spec, PAbQueue.ptout_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma pfree_exist:\n          forall habd habd' labd i f,\n            PAbQueue.pfree_spec habd i = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.pfree_spec labd i = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.pfree_spec, PAbQueue.pfree_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma palloc_exist:\n          forall habd habd' labd i f,\n            PAbQueue.palloc_spec habd = Some (habd', i)\n            -> relate_RData f habd labd\n            -> exists labd', PQueueInit.palloc_spec labd = Some (labd', i) /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.palloc_spec, PAbQueue.palloc_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma setPT_exist:\n          forall habd habd' labd i f,\n            PAbQueue.setPT_spec habd i = Some habd'\n            -> relate_RData f habd labd\n            -> PAbQueue.high_level_invariant habd\n            -> exists labd', PQueueInit.setPT_spec labd i = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PQueueInit.setPT_spec, PAbQueue.setPT_spec; intros until f; exist_simpl. \n        Qed.\n\n        Lemma ptRead_exist:\n          forall habd labd n vadr z f,\n            PAbQueue.ptRead_spec habd n vadr = Some z\n            -> relate_RData f habd labd\n            -> PQueueInit.ptRead_spec labd n vadr = Some z.\n        Proof.\n          unfold PAbQueue.ptRead_spec, PAbQueue.ptRead_Arg, PQueueInit.ptRead_spec, PQueueIntro.ptRead_Arg; \n          intros until f; exist_simpl.\n        Qed.\n\n        Lemma ptResv_exist:\n          forall habd habd' labd n vadr perm f,\n            PAbQueue.ptResv_spec habd n vadr perm = Some habd'\n            -> relate_RData f habd labd\n            -> PAbQueue.high_level_invariant habd\n            -> exists labd', PQueueInit.ptResv_spec labd n vadr perm = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PAbQueue.ptResv_spec, PQueueInit.ptResv_spec, PQueueIntro.ptResv_Arg, PAbQueue.ptResv_Arg.\n          unfold PAbQueue.palloc_spec, PQueueInit.palloc_spec.\n          intros until f; exist_simpl.\n        Qed.\n\n        Lemma kctxt_new_exist:\n          forall s habd habd' labd b b' ofs' n f,\n            PAbQueue.kctxt_new_spec habd b b' ofs' = Some (habd', n)\n            -> relate_RData f habd labd\n            -> PAbQueue.high_level_invariant habd\n            -> find_symbol s STACK_LOC = Some b\n            -> (exists id, find_symbol s id = Some b') \n            -> inject_incr (Mem.flat_inj (genv_next s)) f\n            -> exists labd', PQueueInit.kctxt_new_spec labd b b' ofs' = Some (labd', n) \n                             /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold PAbQueue.kctxt_new_spec, PQueueInit.kctxt_new_spec.\n          intros until f; intros HP HR; inv HR.\n          intros HH Hsys Hsys' Hincr.\n          revert HP; subrewrite'; intros HQ; subdestruct; simpl.\n          destruct a as [Hrange1 _]. \n          inv HQ. refine_split'; eauto 2.\n          econstructor; eauto 2; simpl.\n          unfold kctxt_inj in *; kctxt_inj_simpl.\n          destruct Hsys' as [id Hsys'].\n          eapply stencil_find_symbol_inject'; eauto.\n          rewrite Int.add_zero; trivial.\n          eapply stencil_find_symbol_inject'; eauto.\n          rewrite Int.add_zero; trivial.          \n        Qed.        \n        \n        Lemma kctxt_switch_exist:\n          forall habd habd' labd n n' rs r' rs0 f,\n            PAbQueue.kctxt_switch_spec \n              habd n n' (Pregmap.init Vundef)#ESP <- (rs#ESP)#EDI <- (rs#EDI)#ESI <- (rs#ESI)\n              #EBX <- (rs#EBX)#EBP <- (rs#EBP)#RA <- (rs#RA) = Some (habd', rs0)\n            -> relate_RData f habd labd\n            -> PAbQueue.high_level_invariant habd\n            -> (forall reg : PregEq.t,\n                  val_inject f (Pregmap.get reg rs) (Pregmap.get reg r'))\n            -> let  r'0 := ZMap.get n' (PQueueInit.kctxt labd) in\n               exists labd', PQueueInit.kctxt_switch_spec \n                               labd n n' (Pregmap.init Vundef)#ESP <- (r'#ESP)#EDI <- (r'#EDI)#ESI <- (r'#ESI)\n                               #EBX <- (r'#EBX)#EBP <- (r'#EBP)#RA <- (r'#RA) = Some (labd', r'0)\n                             /\\ relate_RData f habd' labd'\n                             /\\ (forall i r,\n                                   ZtoPreg i = Some r -> val_inject f (rs0#r) (r'0#r))\n                             /\\ 0<= n' < num_proc.\n        Proof.\n          unfold PAbQueue.kctxt_switch_spec, PQueueInit.kctxt_switch_spec.\n          intros until f. exist_simpl.\n          kctxt_inj_simpl.\n          unfold kctxt_inj, Pregmap.get in *; eauto. \n        Qed.\n\n        Lemma trap_info_get_exist:\n          forall habd labd z f,\n            PAbQueue.trap_info_get_spec habd = z\n            -> relate_RData f habd labd\n            -> PQueueInit.trap_info_get_spec labd = z.\n        Proof.\n          unfold PQueueInit.trap_info_get_spec; unfold PAbQueue.trap_info_get_spec.\n          intros. inv H0. congruence.\n        Qed.*)\n\n        Lemma real_data : forall abtcb abq tcb tdq, \n                            AbQ_RealQ (real_abtcb abtcb) (real_abq abq)\n                                      (real_tcb tcb) (real_tdq tdq).\n        Proof.\n          constructor.\n          * unfold abqueue_match_dllist, real_abq, real_tcb, real_tdq.\n            intros qi l Hqi.\n            rewrite !init_zmap_inside by omega.\n            intro H; inv H.\n            exists 64.\n            exists 64.\n            unfold abqueue_match_next_prev_rec.\n            tauto.\n          * unfold abtcbpool_tcbpool, real_abtcb, real_tcb.\n            intros i tds inq Hi.\n            rewrite !init_zmap_inside by assumption.\n            intro H; inv H.\n            exists 64.\n            exists 64.\n            reflexivity.\n        Qed.\n\n        Lemma tdqueue_init_exists :\n          forall mbi_adr adt adt' ladt f,\n            tdqueue_init0_spec (Int.unsigned mbi_adr) adt = Some adt'\n            -> relate_RData f adt ladt\n            -> exists ladt',\n                 tdqueue_init_spec (Int.unsigned mbi_adr) ladt = Some ladt'\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          unfold tdqueue_init_spec, tdqueue_init0_spec.\n          intros until f. exist_simpl.\n          apply real_data.\n        Qed.\n\n        (*Lemma thread_free_exists :\n          forall n adt adt' ladt f,\n            PAbQueue.thread_free_spec adt (Int.unsigned n) = Some adt'\n            -> relate_RData f adt ladt\n            -> PAbQueue.high_level_invariant adt\n            -> exists ladt',\n                 PQueueInit.thread_free_spec ladt (Int.unsigned n) = Some ladt'\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          unfold PQueueInit.thread_free_spec, PAbQueue.thread_free_spec.\n          intros. inv H0. subrewrite'. rename H1 into INV.\n          caseEq (pe adt); intros HIP; rewrite HIP in *; contra_inv.\n          caseEq (ikern adt); intros HIK; rewrite HIK in *; contra_inv.\n          caseEq (ihost adt); intros HIH; rewrite HIH in *; contra_inv.\n          caseEq (ipt adt); intros HIT; rewrite HIT in *; contra_inv.\n          \n          assert (Hvalid_abq: abqueue_valid_Q (PAbQueue.abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_Q.\n            intros i Hi. \n            destruct (valid_TDQ HIP i Hi).\n            destruct H0.\n            exists x; trivial.\n          }\n\n          assert (Hvalid_abtcb: abqueue_valid_abtcb (PAbQueue.abtcb adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_abtcb.\n            intros i Hi. \n            destruct (valid_TCB HIP i Hi).\n            destruct H0.\n            destruct H0.\n            exists x, x0; trivial.\n          }\n\n          assert (Habq_abtcb: abqueue_abq_mapto_abtcb (PAbQueue.abtcb adt) \n                                                      (PAbQueue.abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_abq_mapto_abtcb.\n            intros i Hi.\n            destruct (valid_TCB HIP i Hi) as [s [inq [Hget Hinq]]].\n            exists s, inq.\n            split; trivial.\n            omega.\n          }\n\n          assert (Hvalid_count: abqueue_valid_count (PAbQueue.abtcb adt) \n                                                    (PAbQueue.abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_count.\n            eapply (valid_count HIP); eauto.\n          }\n\n          assert (Hvalid_inQ: abqueue_valid_inQ (PAbQueue.abtcb adt) \n                                                (PAbQueue.abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_inQ.\n            apply (valid_inQ HIP).\n          }\n\n          assert (Hvalid_notinQ': abqueue_notinQ (PAbQueue.abtcb adt) (PAbQueue.abq adt)). \n          {\n            apply abqueue_INV_implies_notinQ; trivial.\n          }\n          destruct (zlt 0 (Int.unsigned n)); contra_inv.\n          destruct (zlt (Int.unsigned n) num_proc); contra_inv.\n          caseEq (ZMap.get (Int.unsigned n) (pb adt)); intro Hget; \n          rewrite Hget in H; contra_inv.\n          caseEq (ZMap.get (Int.unsigned n) (abtcb adt)); \n            [intro Hgetn | intros tds inQ Hgetn]; rewrite Hgetn in H;\n            contra_inv.\n          caseEq (zeq inQ (-1)); intros HinQ HinQ'; rewrite HinQ' in H; contra_inv.\n          clear HinQ'.\n          refine_split'; eauto.\n          inv H; econstructor; eauto 2; simpl.\n          constructor.\n          - intros qi l' Hqi Hget'.\n            inv abq_re0.\n            rename H0 into Habtcb.\n            unfold abqueue_match_dllist in H.\n            destruct (H _ _ Hqi Hget') as [hd [tl [HLget H1]]].\n            exists hd; exists tl.\n            split; auto.\n            assert (~ In (Int.unsigned n) l').\n            {\n              eapply Hvalid_notinQ'; eauto.\n              split; trivial. omega.\n            }\n            apply match_next_prev_presv_set_notin; eauto.\n          - inv abq_re0.\n            unfold abtcbpool_tcbpool in *.\n            intros i tds0 inq Hi H1.\n            destruct (zeq i (Int.unsigned n)); subst.\n            + rewrite ZMap.gss in *.\n              inv H1. refine_split'; trivial.\n            + rewrite ZMap.gso in *; eauto.\n        Qed.*)\n\n        Lemma get_state_exists :\n          forall n i adt ladt f,\n            get_state0_spec (Int.unsigned n) adt = Some i\n            -> relate_RData f adt ladt\n            -> get_state_spec (Int.unsigned n) ladt = Some i.\n        Proof.\n          unfold get_state_spec, get_state0_spec; \n          intros. inv H0. revert H. subrewrite. subdestruct.\n          destruct (ZMap.get (Int.unsigned n) (abtcb adt)) eqn: Hget; contra_inv.\n          inv Hdestruct4. inv HQ.\n          inv abq_re0.\n          unfold abtcbpool_tcbpool in H0.\n          apply H0 in Hget; try omega.\n          destruct Hget as [pv [nx HT]].\n          rewrite HT. trivial.\n        Qed.\n\n        Lemma match_next_prev_presv_set_state : \n          forall start ending hd tl l itcbp,\n            abqueue_match_next_prev_rec l ending hd tl start itcbp\n            -> forall i tds pv nx, \n                 ZMap.get i itcbp = TCBValid tds pv nx\n                 -> forall tds', abqueue_match_next_prev_rec l ending hd tl start (ZMap.set i (TCBValid tds' pv nx) itcbp).\n        Proof.\n          clear.\n          intros start ending hd tl l itcbp Hitcbp.\n          assert (forall start tl, \n                    abqueue_match_next_prev_rec l ending hd tl start itcbp\n                    -> forall i tds prev next, \n                         ZMap.get i itcbp = TCBValid tds prev next\n                         -> forall tds', abqueue_match_next_prev_rec l ending hd tl start\n                                                                     (ZMap.set i (TCBValid tds' prev next) itcbp)).\n          clear Hitcbp.\n          induction l; simpl in *.\n          intros; trivial.\n          \n          intros.\n          destruct l.\n          destruct H as [Hhd [Htl [st Hst]]].\n          split; trivial.\n          split; trivial.\n          rewrite ZMap.gsspec.\n          unfold ZIndexed.eq.\n          destruct (zeq a i); trivial.\n          subst i.\n          rewrite H0 in Hst.\n          inversion Hst.\n          subst tds prev next.\n          exists tds'; trivial.\n          exists st; trivial.\n          (* induction step *)\n          destruct H.\n          split; trivial.\n          destruct H1 as [st [pv' [Hget H1]]].\n          rewrite ZMap.gsspec.\n          unfold ZIndexed.eq.\n          destruct (zeq a i); trivial.\n          subst i.\n          rewrite Hget in H0.\n          inversion H0.\n          subst tds prev next.\n          exists tds'; exists pv'.\n          split; trivial.\n          eapply IHl; eauto.\n          rewrite Hget.\n          exists st, pv'.\n          split; trivial.\n          eapply IHl; eauto.\n          intros.\n          eapply H; eauto.\n        Qed.\n\n        Lemma set_state_exists: \n          forall f n ts adt adt' ladt, \n            set_state0_spec (Int.unsigned n) ts adt = Some adt'\n            -> relate_RData f adt ladt\n            -> exists ladt', \n                 set_state_spec (Int.unsigned n) ts ladt = Some ladt'\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          intros f n ts adt adt' ladt HQ H.\n          inversion_clear H. \n          revert HQ.\n          unfold set_state0_spec, set_state_spec.\n          subrewrite.\n          subdestruct.\n          destruct (ZMap.get (Int.unsigned n) (abtcb adt)) eqn:Hgetn; contra_inv.\n          assert (Hget' : exists pv nx,\n                            ZMap.get (Int.unsigned n) (tcb ladt) \n                            = TCBValid tds pv nx).\n          {\n            inv abq_re0.\n            unfold abtcbpool_tcbpool in H0. inv Hdestruct5.\n            apply H0 with inQ; trivial.\n          }\n          destruct Hget' as [pv [nx Hget']].\n          rewrite Hget'.\n          destruct (ZtoThreadState ts); contra_inv.\n          eexists. \n          split; eauto.              \n          inv HQ.  constructor; eauto; simpl.\n          inv abq_re0.\n          constructor; trivial.\n          - simpl in * .\n            intros qi l' Hqi Hgetl'.\n            destruct (H _ _ Hqi Hgetl') as [hd [tl [HgetQ Hx]]].\n            exists hd; exists tl.\n            split; trivial.\n            apply match_next_prev_presv_set_state with tds; trivial.\n          - unfold abtcbpool_tcbpool in * .\n            simpl in * .\n            intros i tds' inq Hi HT.\n            destruct (zeq i (Int.unsigned n)); subst.\n            + rewrite ZMap.gss in *. inv HT.\n              refine_split'; eauto.\n            + rewrite ZMap.gso in *; eauto.\n        Qed.\n\n        Section Lists_Ext.\n\n          Variable A: Type.\n\n          Hypothesis eq_dec : forall x y : A, {x = y}+{x <> y}.\n\n          Ltac eq_dec_simpl :=\n            let Heq := fresh \"Heq\" in\n            let Hneq := fresh \"Hneq\" in\n            match goal with \n              | H: _ |- context [ eq_dec ?z ?z ] => destruct (eq_dec z z) as [Heq | Hneq]\n                                                    ; [ | destruct (Hneq (refl_equal _))]\n              | H: context [ eq_dec ?z ?z ] |- _  => destruct (eq_dec z z) as [Heq | Hneq]\n                                                     ; [ | destruct (Hneq (refl_equal _))]\n\n              | H : ?z = ?z' |- context [ eq_dec ?z ?z' ] => destruct (eq_dec z z') as [ _ | Hneq ]\n                                                             ; [ | destruct (Hneq H) ]\n              | H : ?z = ?z',\n                    H1 : context [ eq_dec ?z ?z' ] |- _ => destruct (eq_dec z z') as [ _ | Hneq]\n                                                           ; [ | destruct (Hneq H) ]\n\n              | H : ?z = ?z' |- context [ eq_dec ?z' ?z ] => destruct (eq_dec z' z) as [ _ | Hneq ]\n                                                             ; [ | destruct (Hneq (eq_sym H)) ]\n              | H : ?z = ?z',\n                    H1 : context [ eq_dec ?z' ?z ] |- _ => destruct (eq_dec z' z) as [ _ | Hneq]\n                                                           ; [ | destruct (Hneq (eq_sym H)) ]\n\n              | H : ?z <> ?z' |- context [ eq_dec ?z ?z' ] => destruct (eq_dec z z') as [Heq | _ ]\n                                                              ; [ destruct (H Heq) | ]\n\n              | H : ?z <> ?z',\n                    H1 : context [ eq_dec ?z ?z' ] |- _ => destruct (eq_dec z z') as [Heq | _ ]\n                                                           ; [ destruct (H Heq) | ]\n\n              | H : ?z <> ?z' |- context [ eq_dec ?z' ?z ] => destruct (eq_dec z' z) as [Heq | _ ]\n                                                              ; [ destruct (H (eq_sym Heq)) | ]\n\n              | H : ?z <> ?z',\n                    H1 : context [ eq_dec ?z' ?z ] |- _ => destruct (eq_dec z' z) as [Heq | _ ]\n                                                           ; [ destruct (H (eq_sym Heq)) | ]\n\n              | H :  context [ eq_dec ?z ?z' ] |- _ => destruct (eq_dec z z') as [Heq | Hneq ]\n              | H : _ |- context [ eq_dec ?z ?z' ] => destruct (eq_dec z z') as [Heq | Hneq ]\n\n            end.\n\n          Let count_occ := count_occ eq_dec.\n\n          Lemma count_occ_zero_notin:\n            forall (l : list A) (x : A),\n              count_occ l x = 0%nat \n              -> ~ In x l.\n          Proof.\n            induction l; simpl; auto.\n            intros x Hx.\n            destruct (eq_dec a x) as [ Heq | Hneq ].\n            subst a.\n            discriminate.\n            intro H.\n            destruct H.\n            destruct (Hneq H).\n            apply (IHl _ Hx); trivial.\n          Qed.\n\n          Lemma count_occ_notin_zero:\n            forall (l : list A) (x : A),\n              ~ In x l\n              -> count_occ l x = 0%nat.\n          Proof.\n            induction l; simpl; auto.\n            intros x Hx.\n            destruct (eq_dec a x) as [ Heq | Hneq ].\n            subst a.\n            apply False_ind. \n            apply Hx.\n            left; trivial.\n            apply IHl.\n            intro HF.\n            apply Hx.\n            right; trivial.\n          Qed.\n\n          Lemma count_occ_plus_app:\n            forall (l1 l2 : list A) (x : A),\n              count_occ (l1 ++ l2) x = (count_occ l1 x + count_occ l2 x) % nat.\n          Proof.\n            induction l1; simpl; auto.\n            intros l2 x.\n            destruct (eq_dec a x) as [ Heq | Hneq ].\n            subst a.\n            assert (forall n m, Datatypes.S n + m = Datatypes.S (n + m))%nat.\n            clear.\n            intros n m.\n            omega.\n            rewrite H.\n            rewrite IHl1.\n            trivial.\n            rewrite IHl1; trivial.\n          Qed.\n\n          Lemma count_occ_app_plus :\n            forall (l1 l2 : list A) (x : A) (m n : nat),\n              count_occ (l1 ++ l2) x = (m + n) % nat\n              -> count_occ l2 x = n\n              -> count_occ l1 x = m.\n          Proof.\n            intros l1 l2 x m n Hplus H.\n            rewrite count_occ_plus_app in Hplus.\n            rewrite H in Hplus.\n            rewrite plus_comm in Hplus.\n            rewrite (plus_comm m n) in Hplus.\n            rewrite (plus_reg_l _ _ _ Hplus).\n            trivial.\n          Qed.\n\n          Lemma count_occ_app_plus' :\n            forall (l1 l2 : list A) (x : A) (m n : nat),\n              count_occ (l1 ++ l2) x = (m + n) % nat\n              -> count_occ l1 x = m\n              -> count_occ l2 x = n.\n          Proof.\n            intros l1 l2 x m n Hplus H.\n            rewrite count_occ_plus_app in Hplus.\n            rewrite H in Hplus.\n            rewrite (plus_reg_l _ _ _ Hplus).\n            trivial.\n          Qed.\n\n          Lemma count_occ_app_r :\n            forall (l1 l2 : list A) (x : A) (n : nat),\n              count_occ (l1 ++ l2) x = n % nat\n              -> count_occ l2 x = n\n              -> count_occ l1 x = 0%nat.\n          Proof.\n            intros l1 l2 x n Hplus H.\n            rewrite count_occ_plus_app in Hplus.\n            rewrite H in Hplus.\n            omega. \n          Qed.\n\n          Lemma count_occ_plus_cons:\n            forall (l: list A) t t',\n              count_occ (t :: l) t' = (count_occ (t :: nil) t' + count_occ l t')%nat.\n          Proof.\n            intros.\n            assert (t :: l = (t::nil) ++ l).\n            simpl; trivial.\n            rewrite H.\n            rewrite count_occ_plus_app.\n            trivial.\n          Qed.\n\n          Lemma count_occ_sig_one: \n            forall t,\n              count_occ (t :: nil) t = 1%nat.\n          Proof.\n            intros.\n            simpl.\n            eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma count_occ_sig_zero: \n            forall t t',\n              t <> t'\n              -> count_occ (t :: nil) t' = 0%nat.\n          Proof.\n            intros.\n            simpl.\n            eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma count_occ_1_mid_elim :\n            forall (l : list A) l' z t,\n              count_occ l t = 1%nat\n              -> l = z :: l'\n              -> z <> t\n              -> (exists l'' tl, l = l'' ++ (tl :: nil) /\\ tl <> t)\n              -> (exists l' l'', l = l' ++ (t::nil) ++ l'' \n                                 /\\ l' <> nil /\\ count_occ l' t = 0%nat\n                                 /\\ l'' <> nil /\\ count_occ  l'' t = 0%nat).\n          Proof.\n            induction l.\n\n            intros.\n            inversion H0.\n\n            intros.\n            destruct l.\n            destruct l'.\n\n            simpl in H.\n            eq_dec_simpl.\n            subst a.\n            destruct H2 as [l'' [tl [Htl Htl']]].\n            elimtype False.\n            apply Htl'.\n            clear Htl'.\n            generalize t tl Htl.\n            clear.\n            rename l'' into l.\n            induction l.\n            simpl.\n            intros.\n            inversion Htl.\n            trivial.\n            intros.\n            simpl in Htl.\n            inversion Htl.\n            destruct (app_cons_not_nil _ _ _ H1).\n\n            inversion H.\n\n            destruct l'.\n            \n            inversion H0.\n            inversion H0.\n\n            assert (z = a).\n            inversion H0; trivial.\n            subst a.\n            destruct (eq_dec a0 t).\n            subst a0.\n            destruct l.\n            destruct H2 as [l'' [tl [Htl Htl']]].\n            assert (z :: t :: nil = (z ::nil) ++ (t::nil)).\n            rewrite <- app_comm_cons.\n            simpl; trivial.\n            rewrite H2 in Htl.\n            destruct (app_inj_tail _ _ _ _ Htl).\n            subst t.\n            destruct (Htl' (refl_equal _)).\n            destruct H2 as [l'' [tl [H2 Htl]]].\n            exists (z::nil), (a::l).\n            split.\n            simpl.\n            trivial.\n            split.\n            intro HF.\n            inversion HF.\n            split.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            split.\n            intro HF.\n            inversion HF.\n            apply count_occ_app_plus' with (z::t::nil) 1%nat.\n            rewrite <- app_comm_cons.\n            unfold app.\n            rewrite H.\n            simpl; trivial.\n            simpl.\n            eq_dec_simpl.\n            eq_dec_simpl.\n            trivial.\n            assert (count_occ (a0 :: l) t = 1%nat).\n            apply count_occ_app_plus' with (z::nil) 0%nat.\n            unfold app.\n            rewrite H.\n            simpl; trivial.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            destruct H2 as [l'' [tl [Htl Htl']]].\n            destruct l'' as [ | x l''].\n            simpl in Htl.\n            inversion Htl.\n            assert (exists l''' tl, a0 :: l = l''' ++ tl :: nil /\\ tl <> t).\n            exists l'', tl.\n            split.\n            rewrite <- app_comm_cons in Htl.\n            inversion Htl.\n            trivial.\n            trivial.\n            destruct l'.\n            inversion H0.\n            assert (a0 = a).\n            inversion H0.\n            trivial.\n            subst a0.\n            assert (a :: l = a :: l').\n            inversion H0; trivial.\n            destruct (IHl _ _ _ H3 H4 n H2) as [l1 [l2 [Hl [Hl1 [Hl1t [Hl2 Hl2t]]]]]].\n            exists (z::l1), l2.\n            split.\n            rewrite Hl.\n            rewrite <- app_comm_cons.\n            simpl.\n            trivial.\n            split.\n            intro HF; inversion HF.\n            split.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            split.\n            trivial.\n            trivial.\n          Qed.\n\n          Lemma app_tail_dec : \n            forall (l : list A),\n              l = nil \\/ exists l', exists tl, l = l' ++ (tl :: nil).\n          Proof.\n            intros.\n            destruct l.\n            left; trivial.\n            right.\n            exists (removelast (a::l)), (last (a::l) a).\n            rewrite <- app_removelast_last; trivial.\n            intro HF.\n            discriminate.\n          Qed.\n\n          Lemma count_occ_1_elim :\n            forall (l : list A) t,\n              count_occ l t = 1%nat\n              -> (l = t ::nil)\n                 \\/ (exists l', l = t::l' /\\ l' <> nil /\\ count_occ l' t = 0%nat)\n                 \\/ (exists l', l = l'++ (t::nil) /\\ l' <> nil /\\ count_occ l' t = 0%nat)\n                 \\/ (exists l' l'', l = l' ++ (t::nil) ++ l'' \n                                    /\\ l' <> nil /\\ count_occ l' t = 0%nat\n                                    /\\ l'' <> nil /\\ count_occ l'' t = 0%nat).\n          Proof.\n            intros l t Hocc.\n            generalize Hocc; intro Hocc'.\n            destruct l.\n            simpl in Hocc.\n            inversion Hocc.\n            destruct l.\n            simpl in Hocc.\n            destruct (eq_dec a t).\n            subst a; left; trivial.\n            inversion Hocc.\n            simpl in Hocc.\n            destruct (eq_dec a t).\n            subst t.\n            destruct (eq_dec a0 a).\n            subst a0.\n            simpl in Hocc.\n            inversion Hocc.\n            inversion Hocc.\n            right; left.\n            exists (a0::l).\n            split; trivial.\n            split.\n            intro HF; inversion HF.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            eq_dec_simpl.\n            inversion Hocc.\n            destruct l as [ | z1 l].\n            right.\n            right.\n            left.\n            exists (a ::nil).\n            split.\n            rewrite <- app_comm_cons.\n            simpl.\n            subst t.\n            trivial.\n            split.\n            intro HF.\n            inversion HF.\n            rewrite H0.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            subst a0.\n            right; right; right.\n            exists (a::nil), (z1::l).\n            split.\n            rewrite <- app_comm_cons.\n            simpl.\n            trivial.\n            split.\n            intro HF.\n            inversion HF.\n            split.\n            rewrite H0.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            split.\n            intros HF.\n            inversion HF.\n            trivial.\n            destruct (app_tail_dec (a :: a0 :: l)).\n            inversion H.\n            destruct H as [l' [tl Hl']].\n            destruct (eq_dec t tl) as [Hteq | Htneq].\n            subst tl.\n            right.\n            right.\n            left.\n            rewrite Hl'.\n            exists l'.\n            split; trivial.\n            split.\n            intros HF.\n            subst l'.\n            simpl in Hl'.\n            inversion Hl'.\n            apply count_occ_app_plus with (t::nil) 1%nat.\n            simpl.\n            rewrite <- Hl'.\n            trivial.\n            simpl.\n            eq_dec_simpl.\n            trivial.\n            right.\n            right.\n            right.\n            eapply count_occ_1_mid_elim; eauto.\n          Qed.\n\n          Lemma last_nil : forall (l : list A) (x0 : A), \n                             last l x0 = x0\n                             -> (forall x, In x l -> x <> x0)\n                             -> l = nil.\n          Proof.\n            intros  l x0 Hlast H.\n            assert (forall t l', l = t::l' -> False).\n            intros.\n            assert (l <> nil).\n            intro HF.\n            rewrite H0 in HF.\n            discriminate.\n            rewrite (app_removelast_last x0) in H; trivial.\n            apply (H x0); trivial.\n            rewrite Hlast.\n            apply in_or_app.\n            right; simpl; trivial.\n            left; trivial.\n            destruct l.\n            trivial.\n            elimtype False.\n            destruct (eq_dec a x0).\n            apply H with a; trivial.\n            simpl; trivial.\n            left; trivial.\n            apply H0 with a l; trivial.\n          Qed.\n\n          Lemma last_In : forall (l : list A) (x x0 : A), \n                            last l x0 = x\n                            -> In x l \\/ x = x0.\n          Proof.\n            intros l x x0 Hlast.\n            destruct (eq_dec x x0).\n            right; trivial.\n            left.\n            induction l.\n            simpl in Hlast.\n            subst x0.\n            destruct (n (refl_equal _)).\n\n            simpl in *.\n            destruct l.\n            left; trivial.\n            right; auto.\n          Qed.\n\n          Lemma last_In' : forall (l : list A) (x0 : A), \n                             last l x0 <> x0\n                             -> In (last l x0) l.\n          Proof.\n            intros.\n            destruct (last_In _ _ _ (refl_equal (last l x0))).\n            trivial.\n            destruct (H H0).\n          Qed.\n\n          Lemma removelast_dec : forall (l:list A), \n                                   removelast l = nil \\/ removelast l <> nil.\n          Proof.\n            intros.\n            destruct (removelast l).\n            simpl.\n            left; trivial.\n            right.\n            intro H.\n            discriminate.\n          Qed.\n\n          Lemma last_app : forall (l l': list A) x0,\n                             l' <> nil\n                             -> last (l ++ l') x0 = last l' x0.\n          Proof.\n            induction l; simpl; auto.\n            destruct l.\n            intros.\n            simpl in * .\n            destruct l'.\n            destruct (H (refl_equal _)).\n            trivial.\n            intros.\n            rewrite <- app_comm_cons.\n            apply IHl; trivial.\n          Qed.\n\n          Let remove := remove eq_dec.\n\n          Lemma remove_count_occ_neq:\n            forall l x y, y <> x -> count_occ (remove x l) y = count_occ l y.\n          Proof.\n            intros.\n            induction l.\n            simpl.\n            trivial.\n            simpl.\n            destruct (eq_dec x a).\n            destruct (eq_dec a y).\n            subst.\n            destruct (H (refl_equal _)).\n            trivial.\n            destruct (eq_dec a y).\n            subst.\n            unfold count_occ in * .\n            rewrite count_occ_cons_eq; trivial.\n            rewrite IHl.\n            trivial.\n            unfold count_occ in * .\n            rewrite count_occ_cons_neq; auto.\n          Qed.\n\n          Lemma count_occ_remove_neq:\n            forall l x, count_occ l x = 0%nat -> remove x l = l.\n          Proof.\n            induction l.\n            simpl; trivial.\n            simpl.\n            intros x H.\n            destruct (eq_dec x a).\n            subst a.\n            destruct (eq_dec x x) as [ _ | Hneq ]; [ | destruct (Hneq (refl_equal _))].\n            discriminate.\n            destruct (eq_dec a x) as [ Heq | Hneq ].\n            subst a.\n            destruct (n (refl_equal _)).\n            rewrite IHl; trivial.\n          Qed.\n\n          Lemma remove_app:\n            forall l l' x, remove x (l++l') = remove x l ++ remove x l'.\n          Proof.\n            induction l.\n            simpl; trivial.\n            simpl.\n            intros l' x.\n            destruct (eq_dec x a).\n            subst a.\n            trivial.\n            rewrite IHl; trivial.\n          Qed.\n\n          Lemma remove_sig_eq : \n            forall x,\n              remove x (x :: nil) = nil.\n          Proof.\n            intros.\n            simpl.\n            eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma remove_sig_neq : \n            forall x x',\n              x <> x'\n              -> remove x (x' :: nil) = (x' :: nil).\n          Proof.\n            intros.\n            simpl; eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma remove_cons_eq : \n            forall x l,\n              remove x (x :: l) = remove x l.\n          Proof.\n            intros.\n            simpl; eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma remove_cons_neq : \n            forall x x' l,\n              x <> x'\n              -> remove x (x' :: l) = x' :: remove x l.\n          Proof.\n            intros.\n            simpl; eq_dec_simpl; trivial.\n          Qed.\n\n          Lemma remove_neq : \n            forall x l,\n              ~ In x l\n              -> remove x l = l.\n          Proof.\n            intros.\n            apply count_occ_notin_zero in H.\n            apply count_occ_remove_neq; trivial.\n          Qed.\n\n          Lemma remove_removelast : \n            forall l x0,\n              (forall x, In x l -> count_occ l x = 1%nat)\n              -> In (last l x0) l\n              -> remove (last l x0) l = removelast l.\n          Proof.\n            intros l x0 Hocc Hin.\n            destruct l.\n            destruct (in_nil Hin).\n            assert ((a::l) = removelast (a::l) ++ last (a :: l) x0 :: nil).\n            assert (a::l <> nil).\n            intro HF.\n            discriminate.\n            rewrite <- (app_removelast_last x0 H). \n            trivial.\n            set (e := last (a :: l) x0) in * .\n            assert (count_occ (a::l) e = 1%nat).\n            apply Hocc; trivial.\n            rewrite H.\n            rewrite H in H0.\n            rewrite count_occ_plus_app in H0.\n            assert (count_occ (e :: nil) e = 1%nat).\n            simpl.\n            destruct (eq_dec e e) as [_|Hneq]; [|destruct (Hneq (refl_equal _))].\n            trivial.\n            rewrite H1 in H0.\n            assert (count_occ (removelast (a :: l)) e = 0%nat).\n            destruct (count_occ (removelast (a :: l)) e); trivial.\n            rewrite plus_comm in H0. \n            simpl in H0.\n            discriminate.\n            assert (e ::nil <> nil).\n            intro HF.\n            discriminate.\n            rewrite removelast_app; trivial.\n            rewrite remove_app; trivial.\n            rewrite count_occ_remove_neq; trivial.\n            assert (remove e (e :: nil) = removelast (e::nil)).\n            simpl.\n            destruct (eq_dec e e) as [_ | Hneq ]; [ | destruct (Hneq (refl_equal _))].\n            trivial.\n            rewrite H4; trivial.\n          Qed.\n\n          Lemma removelast_notnil : \n            forall (l : list A),\n              removelast l <> nil \n              -> exists t t' l'', l = l'' ++ (t' :: t :: nil).\n          Proof.\n            induction l.\n            simpl.\n            intros.\n            destruct (H (refl_equal _)).\n            intros.\n            simpl in H.\n            destruct l.\n            destruct (H (refl_equal _)).\n            simpl in H.\n            destruct l.\n            exists a0, a, nil.\n            rewrite app_nil_l.\n            trivial.\n            assert (removelast (a0 :: a1 :: l) <> nil).\n            assert (a0 :: a1 :: l = (a0::nil) ++ a1 ::l).\n            simpl.\n            trivial.\n            rewrite H0.\n            rewrite removelast_app.\n            simpl.\n            intro HF.\n            discriminate.\n            intro HF.\n            discriminate.\n            destruct IHl as [t [t' [l'' IH]]]; trivial.\n            exists t, t',(a::l'').\n            rewrite IH.\n            rewrite app_comm_cons.\n            trivial.\n          Qed.\n\n          Lemma removelast_last_singleton : \n            forall (l: list A) x0,\n              last l x0 <> x0\n              -> removelast l = nil\n              -> exists x, l = x::nil /\\ last l x0 = x.\n          Proof.\n            intros l x0 Hlast Hrm.\n            assert (H:= last_In' l _ Hlast).\n            destruct l.\n            simpl in H.\n            destruct H.\n            simpl in Hrm.\n            destruct l.\n            exists a; trivial.\n            split; trivial.\n            discriminate.\n          Qed.                                    \n\n        End Lists_Ext.\n\n        Lemma match_prev_next_intro_tail: \n          forall l start ending l' tcb hd tl st hd',\n            l = l' ++ hd :: nil\n            -> l' <> nil\n            -> abqueue_match_next_prev_rec l' hd hd' tl start tcb\n            -> ZMap.get hd tcb = TCBValid st ending hd'\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb.\n        Proof.\n          induction l.\n          simpl; auto.\n          intros.\n          assert (l' ++ hd :: nil = nil).\n          auto.\n          destruct (app_eq_nil _ _ H3).\n          discriminate.\n          intros.\n          destruct l.\n          assert (a = hd /\\ l' = nil).\n          assert (a :: nil = nil ++ a :: nil).\n          rewrite app_nil_l.\n          trivial.\n          rewrite H3 in H.\n          destruct (app_inj_tail _ _ _ _ H).\n          split; trivial.\n          rewrite H4; trivial.\n          destruct H3.\n          destruct (H0 H4).\n          destruct l' as [ | a' l'].\n          destruct (H0 (refl_equal _)).\n          rewrite <- app_comm_cons in H.\n          inversion H; subst a'; clear H.\n          assert (l' = nil \\/ exists a' l'', l' = a' :: l'').\n          destruct l'.\n          left; trivial.\n          right.\n          exists z0, l'.\n          trivial.\n          destruct H as [H | H].\n          (* l' = nil *)\n          subst l'.\n          simpl in H1.\n          assert (\n              (tl = a /\\ exists st, exists prev,\n                                      ZMap.get a tcb = TCBValid st prev start\n                                      /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)\n              -> abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb ).\n          simpl.\n          trivial.\n          apply H.\n          clear H.\n          destruct H1 as [Hhd' [Htl [st' H1]]].\n          split; trivial.\n          exists st', hd.\n          split; trivial.\n          simpl in H5.\n          inversion H5.\n          subst z l.\n          simpl.\n          split; trivial.\n          split; trivial.\n          subst hd'.\n          exists st; trivial.\n          (* l' = not nil *)\n          destruct l'.\n          destruct H as [a' [l'' H]].\n          discriminate.\n          clear H.\n          rename z0 into a'.\n          clear H0.\n          assert ( (tl = a /\\ exists st, exists prev,\n                                           ZMap.get a tcb = TCBValid st prev start\n                                           /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)\n                   -> abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb ).\n          simpl.\n          trivial.\n          apply H.\n          clear H.\n          assert (abqueue_match_next_prev_rec (a :: a' :: l') hd hd' tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (a' :: l') hd hd' prev a tcb)).\n          simpl.\n          trivial.\n          destruct (H H1) as [Htl [st' [pv [Hgeta Hm]]]].\n          clear H H1.\n          split; trivial.\n          exists st', pv.\n          split; trivial.\n          eapply IHl; eauto.\n          intro HF.\n          discriminate.\n        Qed.\n\n        Lemma match_prev_next_elim3 : \n          forall l t ending hd tl starting tcb,\n            abqueue_match_next_prev_rec (t :: l) ending hd tl starting tcb \n            -> l <> nil\n            -> (tl = t /\\ exists st, exists prev,\n                                       ZMap.get t tcb = TCBValid st prev starting\n                                       /\\ abqueue_match_next_prev_rec l ending hd prev t tcb).\n        Proof.\n          simpl; intros; trivial.\n          destruct l.\n          destruct (H0 (refl_equal _)).\n          trivial.\n        Qed.                                \n\n        Lemma match_prev_next_intro3 : \n          forall l t ending hd tl starting tcb,\n            l <> nil\n            -> (tl = t /\\ exists st, exists prev,\n                                       ZMap.get t tcb = TCBValid st prev starting\n                                       /\\ abqueue_match_next_prev_rec l ending hd prev t tcb)\n            -> abqueue_match_next_prev_rec (t :: l) ending hd tl starting tcb.\n        Proof.\n          simpl; intros; trivial.\n          destruct l.\n          destruct (H (refl_equal _)).\n          trivial.\n        Qed.\n\n        Lemma match_next_prev_intro_tail: \n          forall l l' i start ending tcb hd tl,\n            l = l' ++ i :: nil\n            -> l' <> nil\n            -> (exists hd', \n                  hd = i\n                  /\\ abqueue_match_next_prev_rec l' hd hd' tl start tcb\n                  /\\ exists st, ZMap.get hd tcb = TCBValid st ending hd')\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb.\n        Proof.\n          induction l.\n          simpl; auto.\n          intros.\n          assert (l' ++ i :: nil = nil).\n          auto.\n          destruct (app_eq_nil _ _ H2).\n          discriminate.\n          intros.\n          destruct l.\n          assert (a = hd /\\ l' = nil).\n          simpl in H1.\n          destruct H1.\n          destruct H1.\n          assert (a :: nil = nil ++ a :: nil).\n          rewrite app_nil_l.\n          trivial.\n          rewrite H3 in H.\n          subst hd.\n          destruct (app_inj_tail _ _ _ _ H).\n          split; trivial.\n          rewrite H1; trivial.\n          destruct H2.\n          destruct (H0 H3).\n          destruct l' as [ | a' l'].\n          destruct (H0 (refl_equal _)).\n          rewrite <- app_comm_cons in H.\n          inversion H; subst a'; clear H.\n          assert (l' = nil \\/ exists a' l'', l' = a' :: l'').\n          destruct l'.\n          left; trivial.\n          right.\n          exists z0, l'.\n          trivial.\n          destruct H as [H | H].\n          (* l' = nil *)\n          subst l'.\n          assert ((tl = a /\\ exists st, exists prev,\n                                          ZMap.get a tcb = TCBValid st prev start\n                                          /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)\n                  -> abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb).\n          simpl.\n          trivial.\n          apply H.\n          clear H.\n          simpl in H4.\n          inversion H4.\n          subst z l.\n          destruct H1 as [hd' [Hhd [Hpv [st Hget]]]].\n          simpl.\n          subst hd.\n          simpl in Hpv.\n          destruct Hpv as [Hhd' [Htl [st' Hx]]].\n          split; trivial.\n          exists st', i.\n          split; trivial.\n          split; trivial.\n          split; trivial.\n          subst hd'.\n          exists st; trivial.\n          (* l' = not nil *)\n          destruct l'.\n          destruct H as [a' [l'' H]].\n          discriminate.\n          clear H.\n          rename z0 into a'.\n          clear H0.\n          assert ((tl = a /\\ exists st, exists prev,\n                                          ZMap.get a tcb = TCBValid st prev start\n                                          /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)\n                  -> abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb).\n          simpl.\n          trivial.\n          apply H.\n          clear H.\n          destruct H1 as [hd' [Hhd [Hm Hx]]].\n          apply match_prev_next_elim3 in Hm.\n          destruct Hm as [Htl [st [pv [Hgeta Hm]]]].\n          subst hd tl.\n          split; trivial.\n          exists st, pv.\n          split; trivial.\n          apply IHl with (a' :: l') i; trivial.\n          intro HF; discriminate HF.\n          exists hd'.\n          split; trivial.\n          split; trivial.\n          intro HF; discriminate HF.\n        Qed.  \n\n        Lemma match_next_prev_elim_tail: \n          forall l l' i start ending tcb hd tl,\n            l = l' ++ i :: nil\n            -> l' <> nil\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb\n            -> exists hd', \n                 hd = i\n                 /\\ abqueue_match_next_prev_rec l' hd hd' tl start tcb\n                 /\\ exists st, ZMap.get hd tcb = TCBValid st ending hd'.\n        Proof.\n          induction l.\n          simpl; auto.\n          intros.\n          assert (l' ++ i :: nil = nil).\n          auto.\n          destruct (app_eq_nil _ _ H2).\n          discriminate.\n          intros.\n          destruct l.\n          assert (a = hd /\\ l' = nil).\n          simpl in H1.\n          destruct H1.\n          assert (a :: nil = nil ++ a :: nil).\n          rewrite app_nil_l.\n          trivial.\n          subst a.\n          rewrite H3 in H.\n          destruct (app_inj_tail _ _ _ _ H).\n          split; trivial.\n          rewrite H1; trivial.\n          destruct H2.\n          destruct (H0 H3).\n          destruct l' as [ | a' l'].\n          destruct (H0 (refl_equal _)).\n          rewrite <- app_comm_cons in H.\n          inversion H; subst a'; clear H.\n          assert (l' = nil \\/ exists a' l'', l' = a' :: l'').\n          destruct l'.\n          left; trivial.\n          right.\n          exists z0, l'.\n          trivial.\n          destruct H as [H | H].\n          (* l' = nil *)\n          subst l'.\n          assert (abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)).\n          simpl.\n          trivial.\n          apply H in H1.\n          clear H.\n          simpl in H4.\n          inversion H4.\n          subst z l.\n          destruct H1 as [Htl [st' [pv [H1 H2]]]].\n          simpl in H2.\n          destruct H2 as [Hhd [Hpv Hget]].\n          simpl.\n          subst hd pv.\n          exists a.\n          split; trivial.\n          split; trivial.\n          split; trivial.\n          split; trivial.\n          exists st'; trivial.\n          (* l' = not nil *)\n          destruct l'.\n          destruct H as [a' [l'' H]].\n          discriminate.\n          clear H.\n          rename z0 into a'.\n          clear H0.\n          assert (abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)).\n          simpl.\n          trivial.\n          apply H in H1.\n          clear H.\n          destruct H1 as [Htl [st' [pv [Hgeta Hm]]]].\n          assert (a' :: l' <> nil).\n          intro HF.\n          discriminate.\n          destruct (IHl _ _ _ _ _ _ _ H4 H Hm) as [hd' [Hx [Hy Hz]]].\n          exists hd'.\n          assert ((tl = a /\\ exists st, exists prev,\n                                          ZMap.get a tcb = TCBValid st prev start\n                                          /\\ abqueue_match_next_prev_rec (a' :: l') hd hd' prev a tcb)\n                  -> abqueue_match_next_prev_rec (a :: a' :: l') hd hd' tl start tcb).\n          simpl.\n          trivial.\n          split; trivial.\n          split.\n          apply H0.\n          clear H0.\n          split; trivial.\n          exists st', pv.\n          split; trivial.\n          trivial.\n        Qed.  \n\n        Lemma match_prev_next_elim_tail: \n          forall l start ending l' tcb hd tl,\n            l = l' ++ hd :: nil\n            -> l' <> nil\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb\n            -> exists hd', \n                 abqueue_match_next_prev_rec l' hd hd' tl start tcb\n                 /\\ exists st, ZMap.get hd tcb = TCBValid st ending hd'.\n        Proof.\n          induction l.\n          simpl; auto.\n          intros.\n          assert (l' ++ hd :: nil = nil).\n          auto.\n          destruct (app_eq_nil _ _ H2).\n          discriminate.\n          intros.\n          destruct l.\n          assert (a = hd /\\ l' = nil).\n          assert (a :: nil = nil ++ a :: nil).\n          rewrite app_nil_l.\n          trivial.\n          rewrite H2 in H.\n          destruct (app_inj_tail _ _ _ _ H).\n          split; trivial.\n          rewrite H3; trivial.\n          destruct H2.\n          destruct (H0 H3).\n          destruct l' as [ | a' l'].\n          destruct (H0 (refl_equal _)).\n          rewrite <- app_comm_cons in H.\n          inversion H; subst a'; clear H.\n          assert (l' = nil \\/ exists a' l'', l' = a' :: l'').\n          destruct l'.\n          left; trivial.\n          right.\n          exists z0, l'.\n          trivial.\n          destruct H as [H | H].\n          (* l' = nil *)\n          subst l'.\n          assert (abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)).\n          simpl.\n          trivial.\n          apply H in H1.\n          clear H.\n          simpl in H4.\n          inversion H4.\n          subst z l.\n          destruct H1 as [Htl [st' [pv [H1 H2]]]].\n          simpl in H2.\n          destruct H2 as [Hhd [Hpv Hget]].\n          simpl.\n          exists a.\n          split; trivial.\n          split; trivial.\n          split; trivial.\n          subst pv.\n          exists st'; trivial.\n          (* l' = not nil *)\n          destruct l'.\n          destruct H as [a' [l'' H]].\n          discriminate.\n          clear H.\n          rename z0 into a'.\n          clear H0.\n          assert (abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)).\n          simpl.\n          trivial.\n          apply H in H1.\n          clear H.\n          destruct H1 as [Htl [st' [pv [Hgeta Hm]]]].\n          assert (a' :: l' <> nil).\n          intro HF.\n          discriminate.\n          destruct (IHl _ _ _ _ _ _ H4 H Hm) as [hd' [Hx Hy]].\n          exists hd'.\n          assert ((tl = a /\\ exists st, exists prev,\n                                          ZMap.get a tcb = TCBValid st prev start\n                                          /\\ abqueue_match_next_prev_rec (a' :: l') hd hd' prev a tcb)\n                  -> abqueue_match_next_prev_rec (a :: a' :: l') hd hd' tl start tcb).\n          simpl.\n          trivial.\n          split.\n          apply H0.\n          clear H0.\n          split; trivial.\n          exists st', pv.\n          split; trivial.\n          trivial.\n        Qed.  \n\n        Lemma match_prev_next_elim2_tail: \n          forall l start ending l' tcb hd tl,\n            l = l' ++ hd :: nil\n            -> l' = nil\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb\n            -> exists hd', exists st, ZMap.get hd tcb = TCBValid st ending hd'.\n        Proof.\n          intros.\n          subst l'.\n          simpl in H.\n          subst l.\n          simpl in H1.\n          destruct H1 as [Hhd [Htl [st H]]].\n          exists start, st. \n          trivial.\n        Qed.\n\n        Lemma match_next_prev_implies_tl : \n          forall l t ending hd tl start tcb,\n            abqueue_match_next_prev_rec (t :: l) ending hd tl start tcb\n            -> tl = t.\n        Proof.\n          intros.\n          simpl in H.\n          destruct l.\n          destruct H as [H1 [H2 H]].\n          subst t; trivial.\n          destruct H.\n          subst tl; trivial.\n        Qed.\n\n        Lemma match_next_prev_implies_hd : \n          forall l t ending hd tl start tcb,\n            abqueue_match_next_prev_rec (l ++ t :: nil) ending hd tl start tcb\n            -> hd = t.\n        Proof.\n          intros.\n          destruct l.\n          unfold app in H.\n          simpl in H.\n          destruct H; trivial.\n          apply (match_next_prev_elim_tail ((z :: l) ++ t :: nil) (z::l) t) in H; auto.\n          destruct H as [hd' [H Hx]].\n          trivial.\n          intro HF.\n          discriminate.\n        Qed.\n        \n        Lemma match_prev_next_match_tail: \n          forall l t start ending l' tcb hd tl,\n            l = l' ++ t :: nil\n            -> abqueue_match_next_prev_rec l ending hd tl start tcb\n            -> t = hd.\n        Proof.\n          induction l.\n          simpl.\n          intros.\n          destruct l'.\n          simpl in H.\n          discriminate.\n          rewrite <- app_comm_cons in H.\n          discriminate.\n          intros.\n          destruct l.\n          assert (a :: nil = nil ++ a :: nil).\n          rewrite app_nil_l.\n          trivial.\n          rewrite H1 in H.\n          destruct (app_inj_tail _ _ _ _ H).\n          subst l' a.\n          simpl in H0.\n          destruct H0; auto.\n          assert (abqueue_match_next_prev_rec (a :: z :: l) ending hd tl start tcb\n                  -> (tl = a /\\ exists st, exists prev,\n                                             ZMap.get a tcb = TCBValid st prev start\n                                             /\\ abqueue_match_next_prev_rec (z :: l) ending hd prev a tcb)).\n          simpl.\n          trivial.\n          apply H1 in H0.\n          clear H1.\n          destruct H0 as [Htl [st [pv [Hgeta Hm]]]].\n          destruct l'.\n          simpl in H.\n          inversion H.\n          rewrite <- app_comm_cons in H.\n          inversion H.\n          eapply IHl; eauto.\n        Qed.  \n\n        Lemma match_next_prev_split: \n          forall l l' ending hd tl start tcb,\n            l <> nil\n            -> l' <> nil  \n            -> abqueue_match_next_prev_rec (l ++ l') ending hd tl start tcb\n            -> (exists tl', exists hd', \n                              abqueue_match_next_prev_rec l' ending hd tl' hd' tcb\n                              /\\ abqueue_match_next_prev_rec l tl' hd' tl start\n                                                             tcb).\n        Proof.\n          induction l as [ | t l] .\n          (* case 1 *)\n          intros.\n          destruct (H (refl_equal _)).\n          \n          (* case 2 *)\n          destruct l' as [ | t' l'].\n          intros.\n          destruct (H0 (refl_equal _)).\n          \n          (* case 3 *)\n          intros ending hd tl start tcb Htlnnil Ht'l'nnil Hm.\n          rewrite <-app_comm_cons in Hm.\n          destruct (match_prev_next_elim3 _ _ _ _ _ _ _ Hm) as [Htl [st [pv [Ht Hml]]]].\n          intro HF.\n          destruct (app_cons_not_nil _ _ _ (eq_sym HF)).\n          \n          destruct l as [ | t1 l].\n          (* case 4 *)\n          unfold app in Hml.\n          exists pv, t.\n          split; trivial.\n          simpl.\n          split; trivial.\n          split; trivial.\n          exists st; trivial.\n          \n          (* case 5 *)\n          assert (t1 :: l <> nil).\n          intro HF; discriminate HF.\n          assert (t' :: l' <> nil).\n          intro HF; discriminate HF.\n          destruct (IHl (t' :: l') _ _ _ _ _ H H0 Hml) as [tl' [hd' [Hm2 Hm3]]].\n          exists tl', hd'.\n          split; trivial.\n          apply match_prev_next_intro3.\n          intro HF; discriminate HF.\n          split; trivial.\n          exists st, pv; split; trivial.\n        Qed.\n\n        Lemma match_next_prev_split_into_three: \n          forall l l' i ending hd tl start tcb,\n            l <> nil\n            -> l' <> nil  \n            -> abqueue_match_next_prev_rec\n                 (l ++ (i :: nil) ++ l') \n                 ending hd tl start\n                 tcb\n            -> (exists tl', exists hd', exists st,\n                                          ZMap.get i tcb = TCBValid st tl' hd'\n                                          /\\ abqueue_match_next_prev_rec \n                                               l'\n                                               ending hd tl' i \n                                               tcb\n                                          /\\ abqueue_match_next_prev_rec \n                                               l\n                                               i hd' tl start\n                                               tcb).\n        Proof.\n          intros.  \n          assert ((i::nil) ++ l' <> nil).\n          simpl.\n          intro HF; discriminate HF.\n          destruct (match_next_prev_split _ _ _ _ _ _ _ H H2 H1) as [tl' [hd' [Hm1 Hm2]]].\n          unfold app in Hm1.  \n          destruct l' as [ | t l'].\n          destruct (H0 (refl_equal _)).\n          destruct (match_prev_next_elim3 _ _ _ _ _ _ _ Hm1) as [Htl [st [pv [Hx Hm]]]].\n          intro HF; discriminate HF.\n          subst tl'.\n          exists pv, hd', st.\n          split; trivial.\n          split; trivial.\n        Qed.\n\n        Lemma match_next_prev_merge:\n          forall l l' ending start hd tl tcb hd' tl',\n            l <> nil\n            -> l' <> nil\n            -> abqueue_match_next_prev_rec l tl' hd' tl start tcb\n            -> abqueue_match_next_prev_rec l' ending hd tl' hd' tcb\n            -> abqueue_match_next_prev_rec (l++l') ending hd tl start tcb.\n        Proof.\n          induction l as [ | t l].\n          intros.\n          destruct (H (refl_equal _)).\n          intros.\n          rewrite <- app_comm_cons.\n          apply match_prev_next_intro3.\n          destruct l'.\n          destruct (H0 (refl_equal _)). \n          intro HF.\n          destruct (app_cons_not_nil _ _ _ (eq_sym HF)).\n          assert (Htl := match_next_prev_implies_tl _ _ _ _ _ _ _ H1).\n          destruct l' as [| t' l'].\n          destruct (H0 (refl_equal _)). \n          split; trivial.\n          destruct l as [| t2 l].\n          simpl in H1.\n          destruct H1 as [Hhd' [_ [st Ht]]].\n          exists st, tl'.\n          split; trivial.\n          unfold app.\n          subst hd'.\n          trivial.\n          destruct (match_prev_next_elim3 _ _ _ _ _ _ _ H1) as [Htl' [st' [pv [Ht Hm]]]].\n          intro HF; discriminate HF.\n          exists st', pv; trivial.\n          split; trivial.\n          eapply IHl; eauto.\n          intro HF; discriminate HF.\n        Qed.\n\n        Lemma dequeue_exists: \n          forall f n i adt adt' ladt, \n            dequeue0_spec (Int.unsigned n) adt = Some (adt', i)\n            -> relate_RData f adt ladt\n            -> high_level_invariant adt\n            -> exists ladt', \n                 dequeue_spec (Int.unsigned n) ladt = Some (ladt', i)\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          intros f n i adt adt' ladt HQ H INV.\n          inversion_clear H.\n          revert HQ.\n          unfold dequeue_spec, dequeue0_spec.\n          subrewrite.\n          destruct (ikern ladt) eqn: HIK; contra_inv.\n          destruct (pg ladt) eqn: HIP; contra_inv.\n          destruct (ihost ladt) eqn: HIH; contra_inv.\n          destruct (ipt ladt) eqn: HIT; contra_inv.\n          destruct (zle_le 0 (Int.unsigned n) num_proc); contra_inv.\n          destruct (ZMap.get (Int.unsigned n) (abq adt)) eqn: Hgetl; contra_inv.\n          assert (Hvalid_q : AbQCorrect (ZMap.get (Int.unsigned n) (abq adt))).\n          {\n            inversion INV.\n            eapply valid_TDQ; eauto.\n          }\n          assert (Habq_abtcb: abqueue_abq_mapto_abtcb (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_abq_mapto_abtcb.\n            intros i' Hi'. \n            destruct (valid_TCB pg_re0 i' Hi') as [s [inq [Hget Hinq]]].\n            exists s, inq.\n            split; trivial.\n            omega.\n          }\n          assert (Hvalid_inQ: abqueue_valid_inQ (abtcb adt) (abq adt)).\n          {\n            inversion INV.\n            unfold abqueue_valid_inQ.\n            intros i' qi l'' Hi' Hqi Hget' Hl'.\n            destruct (valid_inQ pg_re0 i' qi l'' Hi' Hqi Hget' Hl'); eauto.\n          }\n          assert (Hvalid_count: abqueue_valid_count (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_count.\n            specialize (valid_count pg_re0).\n            intros. unfold QCount in *.\n            destruct (zeq qi inq); subst.\n            - specialize (valid_count _ _ _ H H0 H1).\n              destruct valid_count as (l' & HR1 & HR2).\n              rewrite H2 in HR1. inv HR1.\n              split; trivial.\n              intros HF. elim HF. trivial.\n            - split; intros.\n              + congruence.\n              + red; intros.\n                unfold InQ in *.\n                destruct (valid_inQ pg_re0 _ _ _ H H1 H2 H4)\n                         as (s' & HR').\n                rewrite H0 in HR'. inv HR'.\n                elim n0; trivial.\n          }\n          assert (Hvalid_notinQ': abqueue_notinQ (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_notinQ; trivial.\n          }\n          assert (Hvalid_disjoint: abqueue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_disjoint; trivial.\n          }\n          assert (Hvalid_queue_disjoint: abqueue_queue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_queue_disjoint; trivial.\n          }\n          destruct (zeq (last l num_proc) num_proc) as [ Hl | Hl].\n\n          - (* l = nil *)\n            assert (Hl_nil : l = nil).\n            {\n              apply (last_nil _ zeq) with num_proc; trivial.\n              unfold AbQCorrect in Hvalid_q.\n              destruct Hvalid_q as [l'' [Hl' Hl'valid]].\n              rewrite Hgetl in Hl'.\n              inversion Hl'.\n              subst l''.\n              clear - Hl'valid.\n              intros.\n              destruct (Hl'valid x H).\n              omega.\n            }\n            subst l. pose proof abq_re0 as abq_re1. inv abq_re0.\n            unfold abqueue_match_dllist in H.\n            destruct (H _ nil a Hgetl) as [hd [tl [Hget Hx]]].\n            rewrite Hget.\n            simpl in Hx.\n            destruct Hx as [Hhd Htl].\n            destruct (zeq hd num_proc) as [_ | Hx]; [ | destruct (Hx Hhd) ].\n            inv HQ. refine_split'; eauto.\n            constructor; eauto.\n\n          - (* l = _ :: _ *)\n            destruct (removelast_dec _ l) as [Hl2 | Hl2].\n            + (* l = _ :: nil *)\n              caseEq (ZMap.get (last l num_proc) (abtcb adt)); \n              [intro Hgettl | intros st inq Hgettl]; rewrite Hgettl in HQ; contra_inv.\n              assert (exists t, l = t:: nil /\\ last l num_proc = t).\n              {\n                eapply (removelast_last_singleton _ zeq); eauto.\n              }\n              inv abq_re0.\n              destruct H as [t [Ht Hlast]].\n              unfold abqueue_match_dllist in H0.\n              destruct (H0 (Int.unsigned n) l a Hgetl) as [hd [tl [Hqnode Hdllist]]].\n              rewrite Hqnode.\n              rewrite Ht in Hdllist.\n              simpl in Hdllist.\n              destruct Hdllist as [Hhd [Htl [st' Hnodet]]].\n              assert (Hhd2: hd <> num_proc).\n              {\n                subst t.\n                unfold AbQCorrect in Hvalid_q.\n                destruct Hvalid_q as [l'' [Hgetl' Hrange]].\n                rewrite Hgetl in Hgetl'.\n                inversion Hgetl'.\n                subst l''.\n                rewrite Ht in Hrange.\n                rewrite <- Hhd in Hrange.\n                simpl in Hrange.\n                omega.\n              }\n              destruct (zeq hd num_proc) as [Hhd1 | Hhd1 ].\n              destruct (Hhd2 Hhd1).\n              clear Hhd2.\n              rewrite <- Hhd in Hnodet.\n              rewrite Hnodet.\n              destruct (zeq num_proc num_proc) as [ _ | Hneq]; [| destruct (Hneq (refl_equal))].\n              inversion HQ.\n              subst i hd.\n              rewrite Ht.\n              refine_split'; eauto.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor; auto.\n              * (* 1st branch : abqueue_match_dllist *)\n                clear HQ.\n                rewrite <- Ht.\n                destruct (zeq t t) as [_|Hneq]; [ | destruct (Hneq (refl_equal _))].\n                unfold abqueue_match_dllist.\n                intros qi l'' Hqi Hgetl'.\n                destruct (zeq qi (Int.unsigned n)) as [ Heq | Hneq ].\n                subst qi. rewrite ZMap.gss in *.\n                inversion Hgetl'.\n                subst l''. refine_split'; eauto.\n                econstructor; trivial.\n                rewrite ZMap.gso in *; eauto.\n\n              * (* 2nd branch: abtcbpool_tcbpool *)\n                clear HQ.\n                unfold abtcbpool_tcbpool in * .\n                intros i tds inq' Hi Hget.\n                destruct (zeq i t) as [ Heq | Hneq ].\n                subst i. rewrite ZMap.gss in *.\n                rewrite Hlast in Hgettl.\n                inversion Hget; subst tds inq'; clear Hget.\n                eauto. rewrite ZMap.gso in *; eauto.\n\n            + (* l = ... :: t' :: t :: nil *)\n              caseEq (ZMap.get (last l num_proc) (abtcb adt)); [| intros st inq]; intro Hget; \n              rewrite Hget in HQ; contra_inv.\n              assert (inq = Int.unsigned n).\n              {\n                clear HQ.\n                unfold abqueue_valid_inQ in Hvalid_inQ.\n                assert (Hin: In (last l num_proc) l).\n                {\n                  destruct (last_In _ zeq l _ num_proc refl_equal); trivial.\n                  omega.\n                }\n\n                assert (Hrange: 0<= (last l num_proc) < num_proc).\n                {\n                  unfold AbQCorrect in Hvalid_q.\n                  destruct Hvalid_q as [l'' [Hgetl' Hx]].\n                  apply Hx.\n                  rewrite Hgetl in Hgetl'.\n                  inversion Hgetl'; subst l''; clear Hgetl'.\n                  trivial.\n                }\n                \n                destruct (Hvalid_inQ (last l num_proc) (Int.unsigned n) l Hrange a Hgetl Hin) as [st' Hget'].\n                rewrite Hget in Hget'.\n                inversion Hget'; subst st' inq; clear Hget'.\n                trivial.\n              }\n              subst inq.\n              inv HQ.\n              destruct (removelast_notnil _ _ Hl2) as [t [t' [l'' Hl'']]].\n              assert (exists tl, ZMap.get (Int.unsigned n) (tdq ladt) = TDQValid t tl\n                                 /\\ 0 <= t < num_proc \n                                 /\\ exists st pv, \n                                      ZMap.get t (tcb ladt) = TCBValid st pv t'\n                                      /\\ 0 <= t' < num_proc \n                                      /\\ exists st' nx', \n                                           ZMap.get t' (tcb ladt) = TCBValid st' t nx'\n                                           /\\ ((l'' <> nil /\\ abqueue_match_next_prev_rec l'' t' nx' tl num_proc\n                                                                                          (tcb ladt))\n                                               \\/ l'' = nil /\\ (tl = t' /\\ nx' = num_proc))).\n              {\n                unfold AbQCorrect in Hvalid_q.\n                destruct Hvalid_q as [l''' [Hgetl' Hx]].\n                inversion abq_re0. \n                subst abtcb abq tcb tdq.\n                rewrite Hgetl in Hgetl'.\n                inversion Hgetl'; subst l'''; clear Hgetl'.\n                destruct (H (Int.unsigned n) l a Hgetl) as [hd [tl [Hqnode Hm]]].\n                assert (Hl3 : l = (l'' ++ (t' ::nil)) ++ t::nil).\n                {\n                  assert (t' :: t :: nil = (t' :: nil) ++ (t :: nil))\n                    by (simpl; trivial).\n                  rewrite H1 in Hl''.\n                  rewrite <- app_assoc.\n                  trivial.\n                }\n                assert (Heq : t = hd).\n                {\n                  eapply match_prev_next_match_tail; eauto.\n                }\n                subst hd.\n                exists tl.\n                split; trivial.\n                assert (Hin : In t l).\n                {\n                  clear - Hl''.\n                  rewrite Hl''.\n                  apply in_or_app.\n                  right; simpl; trivial.\n                  right; left; trivial.\n                }\n                split.\n                apply Hx; trivial.\n\n                assert (Haddi : (l'' ++ t' :: nil) <> nil).\n                {\n                  clear.\n                  destruct l''.\n                  simpl.\n                  intro HF.\n                  discriminate.\n                  rewrite <- app_comm_cons.\n                  intros HF.\n                  discriminate.\n                }\n                destruct (match_next_prev_elim_tail _ _ _ _ _ _ _ _ Hl3 Haddi Hm) as [hd' [_ [Hm' [st' Hgethd]]]].\n                exists st', num_proc.\n                assert (Ht'in : In t' l).\n                {\n                  clear - Hl''.\n                  subst l.\n                  apply in_or_app.\n                  right. simpl.\n                  left; trivial.\n                }\n                assert (Ht' : t' = hd').\n                {\n                  eapply match_prev_next_match_tail; eauto.\n                }\n                subst hd'.\n                split; trivial.\n                split.\n                apply Hx; trivial.\n                \n                assert (Hl''_dec: l'' <> nil \\/ l'' = nil).\n                {\n                  clear.\n                  destruct l''.\n                  right; trivial. left. intro HF.\n                  discriminate.\n                }\n                destruct Hl''_dec as [Hl''_notnil | Hl''_nil].\n                destruct (match_next_prev_elim_tail _ _ _ _ _ _ _ _ (refl_equal (l'' ++ t' :: nil)) Hl''_notnil Hm')\n                  as [hd'' [_ [Hm'' [st'' Hgethd'']]]].\n                exists st'', hd''.\n                split; trivial.\n                left.\n                intros; auto.\n                \n                destruct (match_prev_next_elim2_tail _ _ _ _ _ _ _ (refl_equal (l'' ++ t' :: nil)) Hl''_nil Hm')\n                  as [hd'' [st'' Hgethd'']].\n                exists st'', hd''.\n                split; trivial.\n                right.\n                split; auto.\n                subst l''.\n                simpl in Hm'.\n                destruct Hm' as [Hxx [Hxy [st''' Hm']]].\n                rewrite Hgethd'' in Hm'.\n                inversion Hm'; subst st''' hd''.\n                split; trivial.\n              }\n              destruct H as [tl [Hgetn [Ht [st0 [pv [Hgett [Ht' [st' [nx' [Hgett' Hrec]]]]]]]]]].\n              rewrite Hgetn.\n              destruct (zeq t num_proc) as [Heq | _].\n              elimtype False.\n              clear - Ht Heq.\n              omega.\n              rewrite Hgett.\n              destruct (zeq t' num_proc) as [Heq | _].\n              elimtype False.\n              clear - Ht' Heq.\n              omega.\n              rewrite Hgett'.\n              eexists.\n              assert (last l num_proc = t).\n              {\n                clear - Hl''.\n                rewrite Hl''.\n                rewrite last_app.\n                simpl; trivial.\n                intro H.\n                discriminate.\n              }\n              rewrite H.\n              split; eauto.\n              constructor; eauto.\n\n              (* to prove AbQ_RealQ *)\n              simpl.\n              constructor; auto.\n\n              * (* 1st branch : abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l''' Hqi Hgetl'.\n                destruct (zeq qi (Int.unsigned n)) as [ Heq | Hneq ].\n                subst qi. rewrite ZMap.gss in *.\n                inversion Hgetl'; clear Hgetl'.\n\n                assert (Hl''_dec: l'' = nil \\/ l'' <> nil).\n                {\n                  clear.\n                  destruct l''.\n                  left; trivial.\n                  right.\n                  intro HF.\n                  discriminate.\n                }\n                assert (Hrm: remove zeq t l = removelast l).\n                {\n                  subst t.\n                  apply remove_removelast.\n                  unfold abqueue_queue_disjoint in Hvalid_queue_disjoint.\n                  intros x Hxin.\n                  eapply Hvalid_queue_disjoint; eauto.\n                  unfold AbQCorrect in Hvalid_q.\n                  destruct Hvalid_q as [lx [Hgx Hx]].\n                  rewrite Hgetl in Hgx.\n                  inversion Hgx; subst lx; clear Hgx.\n                  apply Hx; trivial.\n                  apply (last_In' _ zeq); trivial.\n                }\n                rewrite Hrm.\n                assert (Hrm': removelast l = l'' ++ t' :: nil).\n                {\n                  subst l.\n                  assert (t' :: t :: nil = (t' :: nil) ++ (t :: nil)).\n                  {\n                    simpl; trivial.\n                  }\n                  assert (t' :: t :: nil <> nil).\n                  {\n                    intro HF.\n                    discriminate.\n                  }\n                  rewrite removelast_app; trivial.\n                }\n                rewrite Hrm'.\n                destruct Hl''_dec as [Hl''_nil | Hl''_notnil].\n                subst l''.\n                simpl.\n                destruct Hrec.\n                destruct H0. elim H0. trivial.\n\n                destruct H0. destruct H2.\n                refine_split'; trivial.\n                rewrite ZMap.gss. subst nx'; trivial.\n\n                destruct Hrec as [ [_ Hrec] | [HF _] ]; [ | destruct (Hl''_notnil HF)].\n                assert (Hxx: abqueue_match_next_prev_rec l'' t' nx' tl num_proc\n                                                         (ZMap.set t' (TCBValid st' num_proc nx') (tcb ladt))).\n                {\n                  apply match_next_prev_presv_set_notin; auto.\n                  assert (count_occ zeq l t' = 1%nat).\n                  unfold abqueue_queue_disjoint in Hvalid_queue_disjoint.\n                  subst l.\n                  apply Hvalid_queue_disjoint with (Int.unsigned n); trivial.\n                  apply in_or_app.\n                  right.\n                  simpl.\n                  left; trivial.\n                  assert (count_occ zeq l'' t' = 0%nat).\n                  subst l.\n                  apply count_occ_app_r with (t' :: t :: nil) 1%nat; simpl; auto.\n                  destruct (zeq t' t') as [ _ | Hneq ]; [ | destruct (Hneq (refl_equal _))].\n                  assert (t <> t').\n                  {\n                    intro HF.\n                    subst t'.\n                    rewrite count_occ_plus_app in H0.\n                    simpl in H0.\n                    destruct (zeq t t) as [_ | Hneq]; [| destruct (Hneq (refl_equal _))].\n                    clear - H0.\n                    omega.\n                  }\n                  destruct (zeq t t') as [Heq | _].\n                  elim H2; trivial.\n                  trivial.\n                  eapply count_occ_zero_notin; eauto.\n                }\n                assert (remove zeq t l = removelast l).\n                {\n                  subst t.\n                  apply remove_removelast.\n                  unfold abqueue_queue_disjoint in Hvalid_queue_disjoint.\n                  intros x Hxin.\n                  eapply Hvalid_queue_disjoint; eauto.\n                  unfold AbQCorrect in Hvalid_q.\n                  destruct Hvalid_q as [lx [Hgx Hx]].\n                  rewrite Hgetl in Hgx.\n                  inversion Hgx; subst lx; clear Hgx.\n                  apply Hx; trivial.\n                  apply (last_In' _ zeq); trivial.\n                }\n                refine_split'; trivial.\n                eapply match_prev_next_intro_tail; eauto.\n                rewrite ZMap.gss. trivial.\n\n                assert (~ In t' l''').\n                {\n                  unfold abqueue_disjoint in Hvalid_disjoint.\n                  assert (In t' l).\n                  {\n                    subst l.\n                    apply in_or_app.\n                    right.\n                    simpl.\n                    left; trivial.\n                  }\n                  assert (exists s, ZMap.get t' (abtcb adt) =\n                                    AbTCBValid s (Int.unsigned n)).\n                  {\n                    unfold abqueue_valid_inQ in Hvalid_inQ.\n                    apply Hvalid_inQ with l; trivial.\n                  }\n                  destruct H1.\n                  apply (Hvalid_disjoint _ _ _ a Ht' Hgetl H0 qi l''' Hqi) ; eauto.\n                  rewrite ZMap.gso in *; eauto.\n                }\n                inversion abq_re0.\n                subst abtcb abq tcb tdq.\n                unfold abqueue_match_dllist in H2.\n                rewrite ZMap.gso in *; eauto.\n                destruct (H1 _ _ Hqi Hgetl') as [hd' [tl' [Hgetqi Hm]]].            \n                refine_split'; eauto.\n                apply match_next_prev_presv_set_notin; auto.          \n\n              * (* 2nd branch: abtcbpool_tcbpool *)\n                inversion abq_re0.\n                subst abtcb abq tcb tdq.\n                unfold abtcbpool_tcbpool in * .\n                intros i tds inq' Hi Hgeti.\n                assert (Ht_t': t <> t').\n                {\n                  unfold abqueue_queue_disjoint in Hvalid_queue_disjoint.\n                  assert (Htin: In t l).\n                  {\n                    subst l.\n                    apply in_or_app; trivial.\n                    right.\n                    simpl.\n                    right.\n                    left; trivial.\n                  }\n                  assert (Hocc := Hvalid_queue_disjoint _ _ a Hgetl t  Ht Htin).\n                  intro HF.\n                  subst t'.\n                  rewrite Hl'' in Hocc.\n                  rewrite count_occ_plus_app in Hocc.\n                  rewrite plus_comm in Hocc.\n                  assert (count_occ zeq (t :: t :: nil) t = 2%nat).\n                  clear.\n                  simpl.\n                  destruct (zeq t t) as [ _ | Hneq]; [ | destruct (Hneq (refl_equal _))].\n                  trivial.\n                  rewrite H2 in Hocc.\n                  simpl in Hocc.\n                  omega.\n                }\n                destruct (zeq i t) as [ Heq | Hneq ].\n                subst i.\n                rewrite ZMap.gss in *.\n                inversion Hgeti; subst tds inq'; clear Hgeti.\n                rewrite ZMap.gso; auto. subst t.\n                destruct (H1 _ _ _ Hi Hget) as [pvx [nxx Hxx]].\n                rewrite Hgett in Hxx.\n                inversion Hxx; subst st0 pvx nxx; clear Hxx.\n                exists pv, t'.\n                trivial.\n                destruct (zeq i t') as [ Heq | Hneqit' ].\n                subst i. rewrite ZMap.gss.\n                rewrite ZMap.gso in *; eauto.\n                destruct (H1 _ _ _ Hi Hgeti) as [pvx [nxx Hxx]].\n                rewrite Hgett' in Hxx.\n                inversion Hxx; subst tds pvx nxx; clear Hxx.\n                exists num_proc, nx'; trivial.\n                rewrite ZMap.gso in *; eauto.\n        Qed.\n\n        Lemma enqueue_exists : \n          forall f n i adt adt' ladt, \n            enqueue0_spec (Int.unsigned n) i adt = Some adt'\n            -> relate_RData f adt ladt\n            -> high_level_invariant adt\n            -> exists ladt', \n                 enqueue_spec (Int.unsigned n) i ladt = Some ladt'\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          intros f n i adt adt' ladt HQ H INV.\n          inversion_clear H.\n          revert HQ.\n          unfold enqueue_spec, enqueue0_spec.\n          subrewrite. subdestruct; subst. functional inversion Hdestruct3.\n          assert (Hvalid_q : AbQCorrect (ZMap.get (Int.unsigned n) (abq adt))).\n          {\n            inversion INV.\n            eapply valid_TDQ; eauto.\n          }\n          assert (Habq_abtcb: abqueue_abq_mapto_abtcb (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_abq_mapto_abtcb.\n            intros i' Hi'.\n            destruct (valid_TCB pg_re0 i' Hi') as [s [inq' [Hget Hinq]]].\n            exists s, inq'.\n            split; trivial.\n            omega.\n          }\n          assert (Hvalid_inQ: abqueue_valid_inQ (abtcb adt) (abq adt)).\n          {\n            inversion INV.\n            unfold abqueue_valid_inQ.\n            intros i' qi l' Hi' Hqi Hget' Hl'.\n            destruct (valid_inQ pg_re0 i' qi l' Hi' Hqi Hget' Hl'); eauto.\n          }\n          assert (Hvalid_count: abqueue_valid_count (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_count.\n            specialize (valid_count pg_re0).\n            intros. unfold QCount in *.\n            destruct (zeq qi inq); subst.\n            - specialize (valid_count _ _ _ H1 H2 H3).\n              destruct valid_count as (l' & HR1 & HR2).\n              rewrite H4 in HR1. inv HR1.\n              split; trivial.\n              intros HF. elim HF. trivial.\n            - split; intros.\n              + congruence.\n              + red; intros.\n                unfold InQ in *.\n                destruct (valid_inQ pg_re0 _ _ _ H1 H3 H4 H6)\n                         as (s' & HR').\n                rewrite H2 in HR'. inv HR'.\n                elim n0; trivial.\n          }\n          assert (Hvalid_notinQ': abqueue_notinQ (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_notinQ; trivial.\n          }\n          assert (Hvalid_disjoint: abqueue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_disjoint; trivial.\n          }\n          assert (Hvalid_queue_disjoint: abqueue_queue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_queue_disjoint; trivial.\n          }\n\n          inversion abq_re0.\n          subst abtcb abq tcb tdq.\n          unfold abqueue_match_dllist in H1.\n          destruct (H1 _ _ _x Hdestruct5) as [hd [tl [Hgetqi Hm]]].\n          rewrite Hgetqi.\n\n          destruct l as [ | t l].\n          - (* l = nil *)\n            simpl in Hm.\n            destruct Hm as [Hhd Htl].\n            destruct (zeq tl num_proc) as [ _ | Hneq ]; [| destruct (Hneq Htl)].\n            destruct (H2 _ _ _ _x0 Hdestruct6) as [pv [nx HLgeti]].\n            rewrite HLgeti.\n            refine_split'; eauto.\n            inversion HQ.\n            constructor; eauto; simpl.\n            \n            (* to prove AbQ_RealQ *)\n            constructor.\n            + (* 1st: abqueue_match_dllist *)\n              unfold abqueue_match_dllist.\n              intros qi l Hqi Hget.\n              destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n              * subst qi. rewrite ZMap.gss in *.\n                refine_split'; trivial.\n                inversion Hget.\n                subst l.\n                simpl.\n                split; trivial.\n                split; trivial.\n                rewrite ZMap.gss. eauto.\n              * rewrite ZMap.gso in *; eauto.\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hm]]].\n                refine_split'; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n\n            + (* 2nd: abtcbpool_tcbpool *)\n              unfold abtcbpool_tcbpool.\n              intros i' st' inq' Hi' Hgeti'.\n              destruct (zeq i' i) as [ Hieq | Hineq ].\n              subst i. rewrite ZMap.gss in *.\n              inversion Hgeti'.\n              subst st'. eauto.\n              rewrite ZMap.gso in *; eauto.\n              \n          - destruct l as [ | t' l].\n            + (* l = t :: nil *)\n              destruct (H2 _ _ _ _x0 Hdestruct6) as [pv [nx HLgeti]].\n              rewrite HLgeti.\n              simpl in Hm.\n              destruct Hvalid_q as [l' [Hl' Hvalid_q]].\n              rewrite Hdestruct5 in Hl'.\n              inversion Hl'; subst l'; clear Hl'.\n              destruct Hm as [Hhd [Htl Hm]].\n              subst tl.\n              assert (Ht: 0<= t < num_proc). \n              {\n                apply Hvalid_q; trivial.\n                simpl.\n                left; trivial.\n              }\n              destruct (zeq t num_proc) as [Hteq | Htneq].\n              omega.\n              destruct Hm as [st' Hm].\n              rewrite Hm.\n              inv HQ; refine_split'; eauto.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi. rewrite ZMap.gss in *.\n                assert (i <> t).\n                {\n                  assert (~ In i (t :: nil)).\n                  {\n                    eapply Hvalid_notinQ'; eauto.\n                  }\n                  intro HF.\n                  subst i. eapply H3.\n                  left; trivial.\n                }\n                inversion Hget. subst l.\n                refine_split'; eauto.\n                split; trivial.\n                rewrite ZMap.gss.\n                refine_split'; eauto.\n                split; trivial.\n                split; trivial.\n                rewrite ZMap.gso; auto.\n                rewrite ZMap.gss. eauto.\n\n                rewrite ZMap.gso in *; eauto.\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                refine_split'; eauto.\n                eapply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                assert (exists ts, ZMap.get t (abtcb adt) = AbTCBValid ts (Int.unsigned n)).\n                {\n                  eapply Hvalid_inQ; eauto.\n                  left; trivial.\n                }\n                destruct H3 as [ts H3].\n                assert (Htin: In t (t :: nil)).\n                {\n                  simpl; left; trivial.\n                }\n                apply (Hvalid_disjoint _ t (t::nil) _x Ht Hdestruct5 Htin \n                                       qi l Hqi Hqineq Hget).\n                \n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i. rewrite ZMap.gss in *.\n                inversion Hgeti'.\n                subst tds'. eauto.\n                rewrite ZMap.gso in *; eauto.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'. rewrite ZMap.gss.\n                assert (st' = tds').\n                {\n                  destruct (H2 _ _ _ Hi' Hgeti') as [pv' [nx' Hxx]].\n                  rewrite Hm in Hxx.\n                  inversion Hxx.\n                  trivial.\n                }\n                subst st'. eauto.\n                rewrite ZMap.gso; eauto.\n\n            + (* l = t :: t' :: l' *)\n              destruct (H2 _ _ _ _x0 Hdestruct6) as [pv [nx HLgeti]].\n              rewrite HLgeti.\n              assert (abqueue_match_next_prev_rec (t :: t' :: l) num_proc hd tl num_proc\n                                                  (tcb ladt)\n                      -> (tl = t /\\ exists st, exists prev,\n                                                 ZMap.get t (tcb ladt) = TCBValid st prev num_proc\n                                                 /\\ abqueue_match_next_prev_rec (t' :: l) num_proc hd prev t (tcb ladt))).\n              {\n                simpl. trivial.\n              }\n              apply H3 in Hm; clear H3.\n              destruct Hvalid_q as [l' [Hl' Hvalid_q]].\n              rewrite Hdestruct5 in Hl'.\n              inversion Hl'; subst l'; clear Hl'.\n              destruct Hm as [Htl [st' [pv' [Htl' Hm]]]].\n              subst tl.\n              assert (Ht: 0<= t < num_proc). \n              {\n                apply Hvalid_q; trivial.\n                simpl.\n                left; trivial.\n              }\n              destruct (zeq t num_proc) as [Hteq | Htneq].\n              omega.\n              rewrite Htl'.\n              inv HQ. refine_split'; eauto.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                rename l into l''.\n                intros qi l Hqi Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi. rewrite ZMap.gss in *.\n                assert (i <> t).\n                {\n                  assert (~ In i (t :: t' :: l'')).\n                  {\n                    apply (Hvalid_notinQ' _ _ _x0 Hdestruct6 _ _ _x); trivial.\n                  }\n                  intro HF.\n                  subst i. \n                  simpl in H3.\n                  apply H3.\n                  left; trivial.\n                }\n                refine_split'; eauto.\n                inversion Hget.\n                subst l.\n                split; trivial.\n                rewrite ZMap.gss.\n                refine_split'; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                assert ((t = t /\\ \n                         exists st, exists prev,\n                                      ZMap.get t (ZMap.set t (TCBValid st' pv' i) (tcb ladt)) = TCBValid st prev i\n                                      /\\ abqueue_match_next_prev_rec (t' :: l'') num_proc hd prev t \n                                                                     (ZMap.set t (TCBValid st' pv' i) (tcb ladt)))\n                        -> abqueue_match_next_prev_rec (t :: t' :: l'') \n                                                       num_proc hd t i\n                                                       (ZMap.set t (TCBValid st' pv' i) (tcb ladt))).\n                {\n                  clear. intro H. exact H.\n                }\n                apply H4; clear H4.\n                split; trivial.\n                rewrite ZMap.gss.\n                refine_split'; eauto.\n                assert (~ In t (t' :: l'')).\n                {\n                  unfold abqueue_queue_disjoint in Hvalid_queue_disjoint.\n                  intro Htin.\n                  assert (Htin2: In t (t::t'::l'')).\n                  {\n                    simpl; left; trivial.\n                  }\n                  assert (Hocc := Hvalid_queue_disjoint _ _ _x Hdestruct5 t  Ht Htin2).\n                  simpl in Hocc. rewrite zeq_true in Hocc.\n                  destruct (zeq t' t); inversion Hocc.\n                  apply count_occ_zero_notin in H5.\n                  simpl in Htin.\n                  destruct Htin.\n                  destruct (n0 H4).\n                  destruct (H5 H4).\n                }\n                apply match_next_prev_presv_set_notin; eauto.\n                rewrite ZMap.gso in *; eauto.\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                refine_split'; eauto.\n                assert (i <> t).\n                {\n                  assert (~ In i (t :: t' :: l'')).\n                  {\n                    apply (Hvalid_notinQ' _ _ _x0 Hdestruct6 _ _ _x); trivial.\n                  }\n                  intro HF.\n                  subst i.\n                  simpl in H3.\n                  apply H3.\n                  left; trivial.\n                }\n                apply match_next_prev_presv_set_notin; eauto.\n                assert (~ In t l).\n                {\n                  assert (In t (t :: t' :: l'')).\n                  {\n                    simpl; left; trivial.\n                  }\n                  eapply (Hvalid_disjoint _ _ _ _x Ht Hdestruct5 H4 qi l Hqi Hqineq Hget); trivial.\n                }\n                apply match_next_prev_presv_set_notin; eauto.\n\n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i. rewrite ZMap.gss in *.\n                inversion Hgeti'.\n                subst tds'. eauto.\n                rewrite ZMap.gso in *; eauto.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'. rewrite ZMap.gss.\n                assert (st' = tds').\n                {\n                  destruct (H2 _ _ _ Hi' Hgeti') as [pvx [nxx Hxx]].\n                  rewrite Htl' in Hxx.\n                  inversion Hxx.\n                  trivial.\n                }\n                subst st'. eauto.\n                rewrite ZMap.gso; eauto.\n        Qed.\n\n        Lemma queue_rmv_exists : \n          forall f n i adt adt' ladt, \n            queue_rmv0_spec (Int.unsigned n) i adt = Some adt'\n            -> relate_RData f adt ladt\n            -> PAbQueue.high_level_invariant adt\n            -> exists ladt', \n                 queue_rmv_spec (Int.unsigned n) i ladt = Some ladt'\n                 /\\ relate_RData f adt' ladt'.\n        Proof.\n          intros f n i adt adt' ladt HQ H INV.\n          inversion_clear H. revert HQ.\n          unfold queue_rmv_spec, queue_rmv0_spec.\n          subrewrite. subdestruct. functional inversion Hdestruct3.\n          rename _x into Hn, _x0 into Hi, Hdestruct4 into Hgetl, Hdestruct5 into Hgeti. subst.\n          assert (Hvalid_q : AbQCorrect (ZMap.get (Int.unsigned n) (abq adt))).\n          {\n            inversion INV.\n            eapply valid_TDQ; eauto.\n          }\n          assert (Habq_abtcb: abqueue_abq_mapto_abtcb (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_abq_mapto_abtcb.\n            intros i' Hi'.\n            destruct (valid_TCB pg_re0 i' Hi') as [s [inq' [Hget Hinq]]].\n            exists s, inq'.\n            split; trivial.\n            omega.\n          }\n          assert (Hvalid_inQ: abqueue_valid_inQ (abtcb adt) (abq adt)).\n          {\n            inversion INV.\n            unfold abqueue_valid_inQ.\n            intros i' qi l' Hi' Hqi Hget' Hl'.\n            destruct (valid_inQ pg_re0 i' qi l' Hi' Hqi Hget' Hl'); eauto.\n          }\n          assert (Hvalid_count: abqueue_valid_count (abtcb adt) (abq adt)). \n          {\n            inversion INV.\n            unfold abqueue_valid_count.\n            specialize (valid_count pg_re0).\n            intros. unfold QCount in *.\n            destruct (zeq qi inq); subst.\n            - specialize (valid_count _ _ _ H1 H2 H3).\n              destruct valid_count as (l' & HR1 & HR2).\n              rewrite H4 in HR1. inv HR1.\n              split; trivial.\n              intros HF. elim HF. trivial.\n            - split; intros.\n              + congruence.\n              + red; intros.\n                unfold InQ in *.\n                destruct (valid_inQ pg_re0 _ _ _ H1 H3 H4 H6)\n                         as (s' & HR').\n                rewrite H2 in HR'. inv HR'.\n                elim n0; trivial.\n          }\n          assert (Hvalid_notinQ': abqueue_notinQ (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_notinQ; trivial.\n          }\n          assert (Hvalid_disjoint: abqueue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_disjoint; trivial.\n          }\n          assert (Hvalid_queue_disjoint: abqueue_queue_disjoint (abtcb adt) (abq adt)). \n          {\n            apply abqueue_INV_implies_queue_disjoint; trivial.\n          }\n          assert (Hvalid_abq_range: abqueue_abq_range (abtcb adt) (abq adt)). \n          {\n            unfold abqueue_abq_range.\n            intros qi' i' l' Hqi' Hgetqi' Hin'.\n            inversion INV.\n            destruct (valid_TDQ pg_re0 qi' Hqi') as [ll' [Hgetll' Hx]].\n            rewrite Hgetqi' in Hgetll'.\n            inversion Hgetll'; subst ll'; clear Hgetll'.\n            apply Hx; trivial.\n          }\n\n          inversion abq_re0.\n          subst abtcb abq tcb tdq.\n          unfold abqueue_match_dllist in H.\n          destruct (H1 _ _ Hn Hgetl) as [hd [tl [Hgetqi Hm]]].\n          rewrite Hgetqi.\n\n          assert (Hioccl: count_occ zeq l i = 1 %nat).\n          {\n            unfold abqueue_valid_count in Hvalid_count.\n            destruct (Hvalid_count _ _ _ Hi Hgeti _ l Hn Hgetl) as [Hinq1 Hinq2].\n            apply Hinq1; trivial.\n          }\n          destruct (count_occ_1_elim _ zeq l i Hioccl) as [Hsig | [Hhead | [Htail | Hmid ]]].\n          \n          - (* cast1: l = i :: nil *)\n            subst l.\n            simpl in Hm.\n            destruct Hm as [Hhd [Htl [st' HLgeti ]]].\n            destruct (H2 _ _ _ Hi Hgeti) as [pv [nx HLgeti']].\n            rewrite HLgeti in HLgeti'.\n            inversion HLgeti'.\n            subst st' pv nx.\n            rewrite HLgeti.\n            zeq_simpl.\n            eexists; split; eauto.\n            inversion  HQ.\n            constructor; eauto; simpl.\n            \n            (* to prove AbQ_RealQ *)\n            constructor.\n            + (* 1st: abqueue_match_dllist *)\n              unfold abqueue_match_dllist.\n              intros qi l Hqi Hget.\n              rewrite ZMap.gsspec in Hget.\n              unfold ZIndexed.eq in Hget.\n              rewrite ZMap.gsspec.\n              unfold ZIndexed.eq.\n              destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n              zeq_simpl.\n              exists num_proc, num_proc.\n              split; trivial.\n              inversion Hget.\n              subst l.\n              simpl.\n              split; trivial.\n              destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hm]]].\n              exists hd', tl'.\n              split; trivial.\n\n            + (* 2nd: abtcbpool_tcbpool *)\n              unfold abtcbpool_tcbpool.\n              intros i' st' inq' Hi' Hgeti'.\n              rewrite ZMap.gsspec in Hgeti'.\n              unfold ZIndexed.eq in Hgeti'.\n              destruct (zeq i' i) as [ Hieq | Hineq ].\n              subst i'.\n              inversion Hgeti'; subst st' inq'; clear Hgeti'.\n              exists num_proc, num_proc.\n              trivial.\n              apply H2 with inq'; eauto.\n          (* AbQ_RealQ proved *)\n              \n          - (* case2: l = t::l' ,  l' <> nil *)\n            destruct Hhead as [l' [Hl [Hl' Hoccl']]].\n            destruct (H2 _ _ _ Hi Hgeti) as [pv [nx HLgeti]].\n            rewrite HLgeti.\n            subst l.\n            \n            destruct l' as [ | t l'].\n            destruct (Hl' (refl_equal _)).\n            clear Hl'.\n            assert (t :: l' <> nil).\n            intro HF; discriminate HF.\n            apply match_prev_next_elim3 in Hm; trivial.\n            destruct Hm as [Htl [st' [pv' [HLgeti_ Hm]]]].\n            subst tl.\n            rewrite HLgeti in HLgeti_. \n            inversion HLgeti_; subst st' pv' nx; clear HLgeti_.\n\n            destruct l' as [ | t' l'].\n            * (* case2-1: l = t::t'::nil  *)\n              simpl in Hm.\n              destruct Hm as [Hhd [Hpv [st' HLgett]]].\n              subst hd pv.\n              assert (Ht: 0 <= t < num_proc). \n              apply (Hvalid_abq_range (Int.unsigned n) t (i :: t :: nil) Hn); trivial.\n              simpl.\n              right; left; trivial.\n              assert (t <> num_proc).\n              omega.\n              zeq_simpl. \n              rewrite zeq_false; trivial.\n              rewrite HLgett.\n              eexists; split; eauto.\n              inversion HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              {\n                (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                {\n                  subst qi.\n                  assert (i <> t).\n                  {\n                    intro HF.\n                    subst i.\n                    simpl in Hioccl.\n                    zeq_simpl.\n                    inversion Hioccl.\n                  }\n                  rewrite zeq_false in *; trivial.\n                  inversion Hget.\n                  subst l.\n                  exists t, t.\n                  split; trivial.\n                  simpl.\n                  split; trivial.\n                  split; trivial.\n                  rewrite ZMap.gsspec.\n                  unfold ZIndexed.eq.\n                  zeq_simpl.\n                  exists st'; trivial.\n                }\n                {\n                  destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                  exists hd', tl'.\n                  split; trivial.\n                  apply match_next_prev_presv_set_notin; eauto.\n                  eapply (Hvalid_disjoint (Int.unsigned n)); eauto.\n                  simpl; right; auto.\n                }              \n              }\n              {\n                (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool in *. \n                intros i' tds' inq' Hi' Hgeti'.\n                assert (i <> t).\n                {\n                  intro HF.\n                  subst i.\n                  simpl in Hioccl.\n                  zeq_simpl.\n                  inversion Hioccl.\n                }\n                destruct (zeq i i'). subst.\n                rewrite ZMap.gss in *.\n                inv Hgeti'.\n                rewrite ZMap.gso; eauto. \n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                rewrite ZMap.gss. rewrite ZMap.gso in *; eauto.\n                assert (st' = tds').\n                {\n                  destruct (H2 _ _ _ Hi' Hgeti') as [pv' [nx' Hxx]].\n                  rewrite HLgett in Hxx.\n                  inversion Hxx.\n                  trivial.\n                }\n                subst st'. eauto.\n                rewrite ZMap.gso in *; eauto.\n              }\n\n            * (* case2-2: l = t::t'::t'' :: l'  *)\n              assert (t' :: l' <> nil).\n              {\n                intro HF.\n                discriminate.\n              }\n              apply match_prev_next_elim3 in Hm; trivial.\n              destruct Hm as [Ht' [st' [pv' [HLgett' Hm]]]].\n              subst pv.\n              assert (Ht: 0<= t < num_proc). \n              {\n                apply (Hvalid_abq_range (Int.unsigned n) t (i :: t :: t' :: l') Hn); trivial.\n                simpl.\n                right; left; trivial.\n              }\n              assert (t <> num_proc).\n              {\n                omega.\n              }\n              zeq_simpl. \n              rewrite zeq_false; trivial.\n              rewrite HLgett'.\n              assert (remove zeq i (i :: t :: t' :: l') = t :: t' :: l').\n              assert (i :: t :: t' :: l' = (i :: nil) ++ (t :: t' :: l')).\n              rewrite <- app_comm_cons.\n              simpl; trivial.\n              rewrite H6.\n              rewrite remove_app.\n              assert (remove zeq i (i::nil) = nil ).\n              {\n                simpl.\n                zeq_simpl.\n                trivial.\n              }\n              rewrite H7.\n              unfold app.\n              apply count_occ_remove_neq; eauto.\n              rewrite H6 in HQ.\n              eexists; split; eauto.\n              inversion  HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              (* 1st: abqueue_match_dllist *)\n              unfold abqueue_match_dllist.\n              intros qi l Hqi Hget.\n              rewrite ZMap.gsspec in Hget.\n              unfold ZIndexed.eq in Hget.\n              rewrite ZMap.gsspec.\n              unfold ZIndexed.eq.\n              destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n              subst qi.\n              assert (i <> t).\n              intro HF.\n              subst i.\n              simpl in Hioccl.\n              zeq_simpl.\n              inversion Hioccl.\n              exists hd, t.\n              split; trivial.\n              inversion Hget; subst l; clear Hget.\n              apply match_prev_next_intro3.\n              intro HF; discriminate HF.\n              split; trivial.\n              rewrite ZMap.gsspec.\n              unfold ZIndexed.eq.\n              zeq_simpl.\n              exists st', pv'.\n              split; trivial.\n              apply match_next_prev_presv_set_notin; trivial.\n              assert (count_occ zeq ((i :: nil) ++ (t :: nil) ++ t' :: l') t = 1%nat).\n              rewrite <- app_comm_cons.\n              unfold app.\n              eapply (Hvalid_queue_disjoint (Int.unsigned n)); eauto.\n              simpl.\n              right; left; trivial.\n              apply (count_occ_zero_notin _ zeq). \n              apply (count_occ_app_plus') with ((i :: nil) ++ (t :: nil)) 1%nat.\n              rewrite <- app_comm_cons.\n              unfold app.\n              rewrite <- app_comm_cons in H9.\n              unfold app in H9.\n              rewrite H9.\n              simpl; trivial.\n              rewrite <- app_comm_cons. \n              unfold app.\n              simpl.\n              zeq_simpl.\n              rewrite zeq_false; trivial.\n              destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n              exists hd', tl'.\n              split; trivial.\n              apply match_next_prev_presv_set_notin; eauto.\n              eapply (Hvalid_disjoint (Int.unsigned n)); eauto.\n              simpl.\n              right; left; trivial.\n              \n              (* 2nd: abtcbpool_tcbpool *)\n              unfold abtcbpool_tcbpool.\n              intros i' tds' inq' Hi' Hgeti'.\n              rewrite ZMap.gsspec in Hgeti'.\n              unfold ZIndexed.eq in Hgeti'.\n              rewrite ZMap.gsspec.\n              unfold ZIndexed.eq.\n              destruct (zeq i' i) as [ Hieq | Hineq ].\n              subst i'.\n              exists t, num_proc.\n              inversion Hgeti'.\n              subst tds.\n              assert (i <> t).\n              intro HF.\n              subst i.\n              simpl in Hioccl.\n              zeq_simpl.\n              inversion Hioccl.\n              rewrite zeq_false; trivial.\n              destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n              subst i'.\n              assert (st' = tds').\n              { \n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett' in Hxx.\n                inversion Hxx.\n                trivial.\n              }\n              subst st'.\n              exists pv', num_proc.\n              trivial.\n              apply H2 with inq'; eauto.\n          (* AbQ_RealQ proved *)\n\n          - (* case3: l = l' ++ i :: nil ,  l' <> nil *)\n            destruct Htail as [l' [Hl [Hl'notnil Hoccl']]].\n            destruct (H2 _ _ _ Hi Hgeti) as [pv [nx HLgeti]].\n            rewrite HLgeti.\n            subst l.\n            \n            rename l' into lx.\n            destruct (app_tail_dec _ lx) as [ Hl' | [l' [t Hl']]]; subst lx.\n            destruct (Hl'notnil (refl_equal _)).\n            clear Hl'notnil.\n            assert (Htin: In t ((l' ++ t :: nil) ++ i :: nil)).\n            apply in_or_app.\n            left.\n            apply in_or_app.\n            right.\n            simpl; left; trivial.\n            assert (Ht: 0 <= t < num_proc).\n            apply (Hvalid_abq_range (Int.unsigned n) _ ((l' ++ t :: nil) ++ i :: nil)); eauto.\n            assert (Hti: i <> t).\n            intro HF.\n            subst i.\n            rewrite count_occ_plus_app in Hoccl'.\n            rewrite plus_comm in Hoccl'.\n            simpl in Hoccl'.\n            zeq_simpl.\n            simpl in Hoccl'.\n            inversion Hoccl'.\n            rename l' into lx.\n            destruct (app_tail_dec _ lx) as [ Hl' | [l' [t' Hl']]]; subst lx.\n\n            + (* case3-1: l = nil ++ (t::nil) ++ i :: nil ,  l' <> nil *)\n              unfold app in * .\n              simpl in Hm.\n              destruct Hm as [Htl [st'' [pv' [HLgett [Hhd [Hpv [st' HLgeti']]]]]]].\n              subst tl hd pv'.\n              rewrite HLgeti in HLgeti'.\n              inversion HLgeti'; subst st' pv nx; clear HLgeti'.\n              zeq_simpl.\n              assert (t <> num_proc).\n              omega.\n              zeq_simpl.\n              rewrite HLgett.\n              assert (remove zeq i (t::i ::nil) = t ::nil).\n              simpl.\n              zeq_simpl.\n              rewrite zeq_false; trivial.\n              rewrite zeq_false; trivial.\n              rewrite H4 in HQ.\n              clear H4.\n              eexists; split; eauto.\n              inversion  HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists t, t.\n                split; trivial.\n                inversion Hget; subst l; clear Hget.\n                simpl.\n                split; trivial.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st''.\n                trivial.\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                exists hd', tl'.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'.\n                zeq_simpl.\n                inversion Hgeti'.\n                subst tds.\n                exists num_proc, t; trivial.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st'' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st''.\n                exists num_proc, num_proc.\n                trivial.\n                apply H2 with inq'; eauto.\n            (* AbQ_RealQ proved *)\n\n            + (* case3-2: l = l' ++ (t::nil) ++ i :: nil ,  l' <> nil *)\n              assert (Hi_l': ~ In i l').\n              intro HF.\n              rewrite count_occ_plus_app in Hoccl'.\n              rewrite count_occ_plus_app in Hoccl'.\n              rewrite <- plus_assoc in Hoccl'.\n              clear - HF Hoccl'.\n              apply (count_occ_zero_notin _ zeq) in HF; trivial.\n              destruct (count_occ zeq l' i); trivial.\n              simpl in Hoccl'.\n              inversion Hoccl'.\n              assert (Ht'in: In t' (((l' ++ t' :: nil) ++ t:: nil) ++ i :: nil)).\n              apply in_or_app.\n              left.\n              apply in_or_app.\n              left.\n              apply in_or_app.\n              right.\n              simpl; left; trivial.\n              assert (Ht': 0 <= t' < num_proc).\n              apply (Hvalid_abq_range (Int.unsigned n) _ (((l' ++ t' :: nil) ++ t:: nil) ++ i :: nil)); eauto.\n              assert (Hit': i <> t').\n              intro HF.\n              subst i.\n              rewrite count_occ_plus_app in Hoccl'.\n              rewrite count_occ_plus_app in Hoccl'.\n              rewrite <- plus_assoc in Hoccl'.\n              rewrite <- plus_comm in Hoccl'.\n              simpl in Hoccl'.\n              zeq_simpl.\n              simpl in Hoccl'.\n              inversion Hoccl'.\n              assert (Htt': t <> t').\n              intro HF.\n              subst t'.\n              assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n              rewrite count_occ_plus_app in Hx.\n              rewrite <- app_assoc in Hx.\n              rewrite count_occ_plus_app in Hx.\n              rewrite <- app_comm_cons in Hx.\n              unfold app in Hx.\n              rewrite <- plus_assoc in Hx.\n              rewrite <- plus_comm in Hx.\n              assert (count_occ zeq (t :: t :: nil) t = 2%nat).\n              simpl.\n              zeq_simpl; trivial.\n              rewrite H3 in Hx.\n              simpl in Hx.\n              inversion Hx.\n\n              assert (((l' ++ t' :: nil) ++ t :: nil) <> nil).\n              intro HF.\n              apply app_eq_nil in HF.\n              destruct HF.\n              inversion H4.\n              destruct (match_next_prev_elim_tail _ _ _ _ _ _ _ _ (refl_equal _) H3 Hm)\n                as [hd' [Hhd [Hm' [st' HLgeti_]]]].\n              subst hd.\n              rewrite HLgeti in HLgeti_; inversion HLgeti_; subst st' hd' pv; clear HLgeti_.\n              assert (Hnil2: ((l' ++ t' :: nil)) <> nil).\n              intros HF.\n              apply app_eq_nil in HF.\n              destruct HF.\n              inversion H5.\n              destruct (match_next_prev_elim_tail _ _ _ _ _ _ _ _ (refl_equal _) Hnil2 Hm')\n                as [hd' [Hhd' [Hm'' [st' HLgett]]]].\n              subst nx.\n              assert (Htneq : t <> num_proc).\n              omega.\n              zeq_simpl.\n              rewrite zeq_false; trivial.\n              rewrite HLgett.\n\n              eexists; split; eauto.\n              inversion  HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists t, tl.\n                split; trivial.\n                inversion Hget; subst l; clear Hget.\n                assert (remove zeq i (((l' ++ t' :: nil) ++ t :: nil) ++ i :: nil) = ((l' ++ t' :: nil) ++ t :: nil)).\n                rewrite remove_app.\n                rewrite remove_app.\n                rewrite remove_app.\n                assert (count_occ zeq l' i = 0%nat).\n                apply count_occ_notin_zero; auto.\n                rewrite (count_occ_remove_neq _ zeq _ i); trivial.\n                assert (remove zeq i (t'::nil) = t' :: nil).\n                simpl.\n                rewrite zeq_false; trivial.\n                rewrite H6.\n                assert (remove zeq i (t::nil) = t :: nil).\n                simpl.\n                rewrite zeq_false; trivial.\n                rewrite H7.\n                assert (remove zeq i (i::nil) = nil).\n                simpl.\n                zeq_simpl; trivial.\n                rewrite H8.\n                rewrite app_nil_r.\n                trivial.\n                rewrite H4.\n                clear H4. \n                (* new *)\n                assert (Hhd':= match_next_prev_implies_hd _ _ _ _ _ _ _ Hm'').\n                subst hd'.\n                apply match_prev_next_intro_tail with (l' ++ t' :: nil) st' t'; eauto.\n                apply match_next_prev_presv_set_notin; auto.\n                apply (count_occ_zero_notin _ zeq).\n                assert (Hx:=Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                rewrite count_occ_plus_app.\n                rewrite count_occ_sig_zero; auto.\n                rewrite plus_comm.\n                simpl.\n                inversion Hx; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                trivial.\n\n                destruct (H1 _ _ Hqi Hget) as [hd'' [tl' [HLget Hmm]]].\n                exists hd'', tl'.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'. \n                rewrite zeq_false; trivial.\n                inversion Hgeti'.\n                subst tds'.\n                exists num_proc, t; trivial.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st'.\n                exists num_proc, hd'.\n                trivial.\n                apply H2 with inq'; eauto.\n          (* AbQ_RealQ proved *)\n\n          - (* case4: l = l' ++ (i :: nil) ++ l'',  l' <> nil, l'' <> nil *)\n            destruct Hmid as [l' [l'' [Hl [Hl'nnil [Hoccl' [Hl''nnil Hoccl'']]]]]].\n            destruct (H2 _ _ _ Hi Hgeti) as [pv [nx HLgeti]].\n            rewrite HLgeti.\n            subst l.\n            \n            rename l' into lx.\n            destruct (app_tail_dec _ lx) as [ Hl | [l [t Hl]]]; subst lx.\n            destruct (Hl'nnil (refl_equal _)).\n            rename Hl'nnil into Hltnnil.\n            assert (Htin: In t ((l ++ t :: nil) ++ (i :: nil) ++ l'')).\n            apply in_or_app.\n            left.\n            apply in_or_app.\n            right.\n            simpl; left; trivial.\n            assert (Ht: 0 <= t < num_proc).\n            apply (Hvalid_abq_range (Int.unsigned n) _ ((l ++ t :: nil) ++ (i :: nil) ++ l'')); eauto.\n            assert (Hti: i <> t).\n            intro HF.\n            subst i.\n            rewrite count_occ_plus_app in Hoccl'.\n            rewrite plus_comm in Hoccl'.\n            simpl in Hoccl'.\n            zeq_simpl.\n            simpl in Hoccl'.\n            inversion Hoccl'.\n            rename l'' into lx.\n            destruct lx as [ | t' l'].\n            destruct (Hl''nnil (refl_equal _)).\n            assert (Ht'in: In t' ((l ++ t :: nil) ++ (i :: nil) ++ (t' ::l'))).\n            apply in_or_app.\n            right.\n            apply in_or_app.\n            right.\n            simpl; left; trivial.\n            assert (Ht': 0 <= t' < num_proc).\n            apply (Hvalid_abq_range (Int.unsigned n) _ ((l ++ t :: nil) ++ (i :: nil) ++ (t'::l'))); eauto.\n            assert (Ht'i: i <> t').\n            intro HF.\n            subst i.\n            simpl in Hoccl''.\n            zeq_simpl.\n            inversion Hoccl''.\n            \n            destruct (match_next_prev_split_into_three _ _ _ _ _ _ _ _ Hltnnil Hl''nnil Hm)\n              as [tl' [hd' [st' [HLgeti_ [Hmleft Hmright]]]]].\n            rewrite HLgeti in HLgeti_.\n            inversion HLgeti_; subst st' tl' hd'; clear HLgeti_.\n\n            assert (Hhd := match_next_prev_implies_tl _ _ _ _ _ _ _ Hmleft).\n            subst pv.\n            assert (Htl := match_next_prev_implies_hd _ _ _ _ _ _ _ Hmright).\n            subst nx.\n            destruct (zeq t' num_proc) as [Hx | _].\n            elimtype False.\n            omega.\n            destruct (zeq t num_proc) as [Hx | _].\n            elimtype False.\n            omega.\n\n            rename l into lx.\n            destruct (app_tail_dec _ lx) as [ Hl | [l [t1 Hl]]]; subst lx.\n            rename l' into lx.\n            destruct lx as [ | t2 l'].\n\n            + (* case4-1: l = (nil ++ (t1::nil) ++ (t::nil) ++ (i::nil) ++ (t'::nil) *)\n\n              unfold app in * .\n              simpl in Hmright.\n              destruct Hmright as [Hnx [Htl [st'' HLgett]]].\n              subst tl. clear Hnx.\n\n              simpl in Hmleft.\n              destruct Hmleft as [Hhd [_ [st' HLgett']]].\n              rewrite HLgett.\n              rewrite HLgett'.\n              \n              assert (remove zeq i (t :: i :: t' :: nil) = t :: t' :: nil).\n              simpl.\n              repeat zeq_simpl. \n              trivial.\n              rewrite H3 in HQ; clear H3.\n\n              eexists; split; eauto.\n              inversion  HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists hd, t.\n                split; trivial.\n                inversion Hget; subst l; clear Hget.\n                simpl.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st'', t'.\n                split; trivial.\n                split; trivial.\n                split; trivial.\n                exists st'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                assert (Htt' : t <> t').\n                intro HF.\n                subst t' hd.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                simpl in Hx.\n                repeat zeq_simpl. \n                inversion Hx.\n                repeat zeq_simpl. rewrite ZMap.gss. trivial.\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                exists hd', tl'.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'.\n                zeq_simpl.\n                inversion Hgeti'.\n                subst tds'.\n                exists t', t; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                repeat zeq_simpl; auto.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st'' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st''.\n                exists t', num_proc.\n                trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' t') as [ Hi'eqt' | Hi'neqt' ].\n                subst i'.\n                assert (st' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett' in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st'.\n                exists num_proc, t.\n                trivial.\n                apply H2 with inq'; eauto.\n            (* AbQ_RealQ proved *)\n\n            + (* case4-2: l = (nil ++ (t1::nil) ++ (t::nil) ++ (i::nil) ++ (t'::t2::nil) *)\n\n              assert (Hit2: i <> t2).\n              intro HF.\n              subst t2.\n              simpl in Hoccl''.\n              repeat zeq_simpl.\n              inversion Hoccl''.\n              assert (Hi_l': ~ In i l').\n              simpl in Hoccl''.\n              repeat zeq_simpl.\n              apply (count_occ_zero_notin _ zeq); trivial.\n              assert (Ht2in: In t2 ((nil ++ t :: nil) ++ (i:: nil) ++ (t' :: t2 :: l'))).\n              apply in_or_app.\n              right.\n              apply in_or_app.\n              right.\n              simpl; right; left; trivial.\n              assert (Ht2: 0 <= t2 < num_proc).\n              apply (Hvalid_abq_range (Int.unsigned n) _ \n                                      ((nil ++ t :: nil) ++ (i :: nil) ++ t' :: t2 :: l')); eauto.\n              assert (Htt': t' <> t2).\n              intro HF.\n              subst t2.\n              assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n              rewrite count_occ_plus_app in Hx.\n              rewrite count_occ_plus_app in Hx.\n              rewrite count_occ_plus_app in Hx.\n              rewrite plus_assoc in Hx.\n              rewrite plus_comm in Hx.\n\n              rewrite count_occ_plus_cons in Hx.\n              rewrite (count_occ_plus_cons _ zeq l') in Hx.\n              assert (count_occ zeq (t' :: nil) t' = 1 % nat).\n              simpl.\n              repeat zeq_simpl; trivial.\n              rewrite H3 in Hx.\n              simpl in Hx.\n              inversion Hx.\n\n              unfold app in * .\n              simpl in Hmright.\n              destruct Hmright as [Hnx [Htl [st'' HLgett]]].\n              subst tl. clear Hnx.\n\n              destruct (match_prev_next_elim3 _ _ _ _ _ _ _ Hmleft) as [_ [st' [pv' [HLgett' Hmleft']]]]. \n              intro HF; discriminate HF.\n              rewrite HLgett.\n              rewrite HLgett'.\n              \n              assert (remove zeq i (t :: i :: t' :: t2 :: l') = t :: t' :: t2 :: l').\n              simpl.\n              repeat zeq_simpl. \n              rewrite count_occ_remove_neq.\n              trivial.\n              apply count_occ_notin_zero; trivial.\n              rewrite H3 in HQ; clear H3.\n\n              eexists; split; eauto.\n              inversion  HQ.\n              constructor; eauto; simpl.\n\n              (* to prove AbQ_RealQ *)\n              constructor.\n\n              * (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists hd, t.\n                split; trivial.\n                inversion Hget; subst l; clear Hget.\n                apply match_prev_next_intro3.\n                intro HF; discriminate HF.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st'', t'.\n                split; trivial. \n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_prev_next_intro3.\n                intro HF; discriminate HF.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st', pv'.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                assert (t :: i :: t' :: t2 :: l' = (t :: i :: nil) ++ (t' :: nil) ++ (t2 :: l')).\n                simpl.\n                trivial.\n                rewrite H3 in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                assert (count_occ zeq (t' :: nil) t' = 1 %nat).\n                simpl; zeq_simpl; trivial.\n                rewrite H5 in Hx.\n                apply (count_occ_zero_notin _ zeq); trivial.\n                rewrite plus_comm in Hx.\n                rewrite <- plus_assoc in Hx.\n                assert (forall n, 1 + n = 1 -> n = 0)%nat.\n                clear; intro n; omega.\n                apply H6 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                assert (t :: i :: t' :: t2 :: l' = (t :: i :: nil) ++ (t' :: t2 :: l')).\n                simpl.\n                trivial.\n                rewrite H3 in Hx.\n                rewrite count_occ_plus_app in Hx.\n                assert (count_occ zeq (t :: i:: nil) t = 1 %nat).\n                simpl. \n                repeat zeq_simpl. \n                trivial.\n                rewrite H5 in Hx.\n                apply (count_occ_zero_notin _ zeq); trivial.\n                assert (forall n, 1 + n = 1 -> n = 0)%nat.\n                clear; intro n; omega.\n                apply H6 in Hx.\n                trivial.\n\n                destruct (H1 _ _ Hqi Hget) as [hd' [tl' [HLget Hmm]]].\n                exists hd', tl'.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n              * (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'.\n                zeq_simpl.\n                inversion Hgeti'.\n                subst tds'.\n                exists t', t; trivial.\n                repeat zeq_simpl; auto.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st'' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st''.\n                exists t', num_proc.\n                trivial.\n                destruct (zeq i' t') as [ Hi'eqt' | Hi'neqt' ].\n                subst i'.\n                assert (st' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett' in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st'.\n                exists pv', t.\n                trivial.\n                apply H2 with inq'; eauto.\n            (* AbQ_RealQ proved *)\n\n            + rename l' into lx.\n              destruct lx as [ | t2 l'].\n\n              * (* case4-3: l = (l ++ (t1::nil) ++ (t::nil) ++ (i::nil) ++ (t'::nil) *)\n\n                assert (Hit1: i <> t1).\n                intro HF.\n                subst t1.\n                rewrite count_occ_plus_app in Hoccl'.\n                apply plus_is_O in Hoccl'.\n                destruct Hoccl'.\n                rewrite count_occ_plus_app in H3.\n                apply plus_is_O in H3.\n                destruct H3.\n                simpl in H5.\n                zeq_simpl.\n                inversion H5.\n                assert (Hi_l': ~ In i l).\n                rewrite count_occ_plus_app in Hoccl'.\n                apply plus_is_O in Hoccl'.\n                destruct Hoccl'.\n                rewrite count_occ_plus_app in H3.\n                apply plus_is_O in H3.\n                destruct H3.\n                apply (count_occ_zero_notin _ zeq) ; trivial.\n                assert (Htt1: t <> t1).\n                intro HF.\n                subst t1.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n\n                rewrite count_occ_sig_one in Hx.\n                rew_arith_H (forall n m,  n + 1 + 1 + m = Datatypes.S (Datatypes.S (n+m)))%nat Hx.\n                inversion Hx.\n\n                assert (Htt': t <> t').\n                intro HF.\n                subst t'.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + (m + 1) = Datatypes.S (Datatypes.S (n+m)))%nat Hx.\n                inversion Hx.\n\n                assert (Htnin: ~ In t l).\n                apply (count_occ_zero_notin _ zeq).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rew_arith_H (forall n m,  n + 1 + m = Datatypes.S (n+m))%nat Hx.\n\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                simpl in Hx.\n                inversion Hx.\n                rewrite plus_comm.\n                simpl.\n                rewrite plus_comm.\n                simpl.\n                trivial.\n\n                assert (Htnin_2: ~ In t (l ++ t1 :: nil)).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + (0 + m) = Datatypes.S (n+m))%nat Hx.\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app.\n                rewrite count_occ_sig_zero; auto.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx; clear H3.\n                apply plus_is_O in Hx.\n                destruct Hx.\n                omega.\n\n                assert (Ht2in: In t1 (((l ++ t1 :: nil) ++ (t::nil)) ++ (i:: nil) ++ (t' :: nil))).\n                apply in_or_app.\n                left.\n                apply in_or_app.\n                left.\n                apply in_or_app.\n                right; simpl; left; trivial.\n                assert (Ht2: 0 <= t1 < num_proc).\n                apply (Hvalid_abq_range (Int.unsigned n) _ \n                                        (((l ++ t1 ::nil) ++ t :: nil) ++ (i :: nil) ++ t' :: nil)); eauto.\n                assert (Ht't1: t' <> t1).\n                intro HF.\n                subst t1.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx.\n                rewrite count_occ_sig_zero in Hx.\n                simpl in Hx.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                rewrite plus_comm in Hx.\n                simpl in Hx.\n                inversion Hx.\n                auto.\n                auto.\n                assert (Htinin : ~ In t' (l ++ t1 :: nil)).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 0 + (m + 1) = Datatypes.S (n+m))%nat Hx.\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app.\n                rewrite count_occ_sig_zero; auto.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx; clear H3.\n                apply plus_is_O in Hx.\n                destruct Hx.\n                omega.\n\n                simpl in Hmleft.\n                destruct Hmleft as [Hhd [_ [st'' HLgett']]].\n                subst hd. \n\n                assert (Hx : (l++t1::nil) <> nil).\n                intro HF. \n                destruct (app_cons_not_nil _ _ _ (eq_sym HF)). \n                destruct (match_next_prev_elim_tail _ (l++t1::nil) t _ _ _ _ _ (refl_equal _) Hx Hmright) \n                  as [hd' [Hhd [Hmright' [st' HLgett]]]]. \n                rewrite HLgett.\n                rewrite HLgett'.\n                \n                assert ((remove zeq i (((l ++ t1 :: nil) ++ t :: nil) \n                                         ++ (i :: nil) ++ t' :: nil)) = l ++ t1 :: t :: t' :: nil).\n                simpl.\n                rewrite remove_app.\n                rewrite remove_app.\n                rewrite remove_app.\n\n                rewrite remove_cons_eq.\n                rewrite remove_sig_neq; auto.\n                rewrite remove_sig_neq; auto.\n                rewrite remove_sig_neq; auto.\n                rewrite remove_neq; auto.\n                rewrite <- app_assoc.\n                rewrite <- app_assoc.\n                rewrite <- app_comm_cons.\n                rewrite <- app_comm_cons.\n                simpl.\n                trivial.\n                rewrite H3 in HQ; clear H3.\n\n                eexists; split; eauto.\n                inversion  HQ.\n                constructor; eauto; simpl.\n\n                (* to prove AbQ_RealQ *)\n                constructor.\n\n                (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi l' Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists t', tl.\n                split; trivial.\n                inversion Hget; subst l'; clear Hget.\n\n                assert (HL : l ++ t1 :: t :: t' :: nil = (l ++ t1 ::nil) ++ (t :: t' :: nil)).\n                rewrite <- app_assoc.\n                rewrite <- app_comm_cons.\n                simpl.\n                trivial.\n                rewrite HL.\n                apply match_next_prev_merge with hd' t; auto.\n                intro HF; discriminate HF.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_prev_next_intro3.\n                intro HF; discriminate HF.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st', t'.\n                split; trivial. \n                apply match_next_prev_presv_set_notin; eauto.\n                simpl.\n                split; trivial.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st''; trivial.\n                intro HF.\n                simpl in HF.\n                destruct HF; auto.\n\n                destruct (H1 _ _ Hqi Hget) as [hdx [tlx [HLget Hmm]]].\n                exists hdx, tlx.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n                (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'.\n                zeq_simpl.\n                inversion Hgeti'.\n                subst tds'.\n                repeat zeq_simpl.\n                exists t', t; trivial.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st'.\n                exists t', hd'.\n                trivial.\n                destruct (zeq i' t') as [ Hi'eqt' | Hi'neqt' ].\n                subst i'.\n                assert (st'' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett' in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st''.\n                exists num_proc, t.\n                trivial.\n                apply H2 with inq'; eauto.\n              (* AbQ_RealQ proved *)\n\n              * (* case4-4: l = (l ++ (t1::nil) ++ (t::nil) ++ (i::nil) ++ (t':: t2 :: l') *)\n                assert (Hit1: i <> t1).\n                intro HF.\n                subst t1.\n                rewrite count_occ_plus_app in Hoccl'.\n                apply plus_is_O in Hoccl'.\n                destruct Hoccl'.\n                rewrite count_occ_plus_app in H3.\n                apply plus_is_O in H3.\n                destruct H3.\n                simpl in H5.\n                zeq_simpl.\n                inversion H5.\n                assert (Hi_l': ~ In i l).\n                rewrite count_occ_plus_app in Hoccl'.\n                apply plus_is_O in Hoccl'.\n                destruct Hoccl'.\n                rewrite count_occ_plus_app in H3.\n                apply plus_is_O in H3.\n                destruct H3.\n                apply (count_occ_zero_notin _ zeq) ; trivial.\n                assert (Htt1: t <> t1).\n                intro HF.\n                subst t1.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n\n                rewrite count_occ_sig_one in Hx.\n                rew_arith_H (forall n m,  n + 1 + 1 + m = Datatypes.S (Datatypes.S (n+m)))%nat Hx.\n                inversion Hx.\n\n                assert (Htt': t <> t').\n                intro HF.\n                subst t'.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite (count_occ_cons_eq zeq (t2::l')) in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + (0 + Datatypes.S m) = Datatypes.S (Datatypes.S (n+m)))%nat Hx.\n                inversion Hx.\n\n                assert (Htnin: ~ In t l).\n                apply (count_occ_zero_notin _ zeq).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + ( 0 + m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n\n                assert (Ht't1: t' <> t1).\n                intro HF.\n                subst t1.\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 1 + 0 + (0 + m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx.\n                rewrite count_occ_cons_eq in H5; trivial.\n                inversion H5.\n\n                assert (Htinin : ~ In t' (l ++ t1 :: nil)).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite (count_occ_cons_eq zeq (t2::l') (refl_equal t')) in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 0 + ( 0 + Datatypes.S m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n                rewrite count_occ_plus_app.\n                rewrite H4.\n                rewrite count_occ_cons_neq; auto.\n\n                assert (Htnin_2 : ~ In t (l ++ t1 :: nil)).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + ( 0 + m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n                rewrite count_occ_plus_app.\n                rewrite H4.\n                rewrite count_occ_cons_neq; auto.\n\n                assert (Hit2: i <> t2).\n                intro HF.\n                subst t2.\n                assert (t' :: i :: l' = (t' :: nil) ++ (i::nil) ++ l').\n                simpl.\n                trivial.\n                rewrite H3 in Hoccl''. \n                rewrite count_occ_plus_app in Hoccl''.\n                rewrite count_occ_plus_app in Hoccl''.\n                apply plus_is_O in Hoccl''.\n                destruct Hoccl''.\n                apply plus_is_O in H5.\n                destruct H5.\n                simpl in H5.\n                zeq_simpl.\n                inversion H5.\n\n                assert (Hinin : ~ In i l').\n                assert (t' :: t2 :: l' = (t' :: nil) ++ (t2::nil) ++ l').\n                simpl.\n                trivial.\n                rewrite H3 in Hoccl''. \n                rewrite count_occ_plus_app in Hoccl''; auto.\n                rewrite count_occ_plus_app in Hoccl''; auto.\n                apply plus_is_O in Hoccl''.\n                destruct Hoccl''.\n                apply plus_is_O in H5.\n                destruct H5.\n                apply (count_occ_zero_notin _ zeq) ; trivial.\n                \n\n                assert (Htnin_3:  ~ In t (t' :: t2 :: l')).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t Ht Htin).\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_sig_one in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 1 + ( 0 + m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n\n                assert (Ht'nin: ~ In t' (t2 :: l')).\n                assert (Hx := Hvalid_queue_disjoint (Int.unsigned n) _ Hn Hgetl t' Ht' Ht'in).\n                apply (count_occ_zero_notin _ zeq).\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite count_occ_plus_app in Hx.\n                rewrite (count_occ_cons_eq zeq (t2::l') (refl_equal t')) in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rewrite count_occ_sig_zero in Hx; auto.\n                rew_arith_H (forall n m,  n + 0 + 0 + ( 0 + Datatypes.S m) = Datatypes.S (n+m))%nat Hx.\n                assert (forall n, Datatypes.S n = 1 -> n = 0)%nat.\n                clear. intros. omega.\n                apply H3 in Hx.\n                apply plus_is_O in Hx.\n                destruct Hx; trivial.\n\n                destruct (match_prev_next_elim3 _ _ _ _ _ _ _ Hmleft) as [_ [st' [pv' [HLgett' Hmleft']]]].\n                intro HF; discriminate HF.\n\n                assert (Hx : (l++t1::nil) <> nil).\n                intro HF.\n                destruct (app_cons_not_nil _ _ _ (eq_sym HF)).\n                destruct (match_next_prev_elim_tail _ (l++t1::nil) t _ _ _ _ _ (refl_equal _) Hx Hmright) \n                  as [hd' [_ [Hmright' [st'' HLgett]]]]. \n                rewrite HLgett.\n                rewrite HLgett'.\n                \n                assert ((remove zeq i (((l ++ t1 :: nil) ++ t :: nil) \n                                         ++ (i :: nil) ++ t' :: t2 :: l')) = l ++ t1 :: t :: t' :: t2 :: l').\n                simpl.\n                rewrite remove_app.\n                rewrite remove_app.\n                rewrite remove_app.\n\n                rewrite remove_cons_eq.\n                rewrite remove_sig_neq; auto.\n                rewrite remove_sig_neq; auto.\n                rewrite remove_neq; auto.\n                rewrite <- app_assoc.\n                rewrite <- app_assoc.\n                rewrite <- app_comm_cons.\n                rewrite <- app_comm_cons.\n                rewrite remove_cons_neq; auto.\n                rewrite remove_cons_neq; auto.\n                rewrite remove_neq; auto.\n                rewrite H3 in HQ; clear H3.\n\n                eexists; split; eauto.\n                inversion  HQ.\n                constructor; eauto; simpl.\n\n                (* to prove AbQ_RealQ *)\n                constructor.\n\n                (* 1st: abqueue_match_dllist *)\n                unfold abqueue_match_dllist.\n                intros qi lx Hqi Hget.\n                rewrite ZMap.gsspec in Hget.\n                unfold ZIndexed.eq in Hget.\n                destruct (zeq qi (Int.unsigned n)) as [ Hqieq | Hqineq].\n                subst qi.\n                exists hd, tl.\n                split; trivial.\n                inversion Hget; subst lx; clear Hget.\n\n                assert (HL : l ++ t1 :: t :: t' :: t2 :: l' = (l ++ t1 ::nil) ++ (t :: nil) ++ (t' :: t2 :: l')).\n                simpl.\n                rewrite <- app_assoc.\n                simpl.\n                trivial.\n                rewrite HL.\n                apply match_next_prev_merge with hd' t; auto.\n                intro HF; discriminate HF.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_prev_next_intro3.\n                intro HF; discriminate HF.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st'', t'.\n                split; trivial. \n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_prev_next_intro3.\n                intro HF; discriminate HF.\n                split; trivial.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                zeq_simpl.\n                exists st', pv'; trivial.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n\n                destruct (H1 _ _ Hqi Hget) as [hdx [tlx [HLget Hmm]]].\n                exists hdx, tlx.\n                split; trivial.\n                apply match_next_prev_presv_set_notin; eauto.\n                apply match_next_prev_presv_set_notin; eauto.\n                \n                (* 2nd: abtcbpool_tcbpool *)\n                unfold abtcbpool_tcbpool.\n                intros i' tds' inq' Hi' Hgeti'.\n                rewrite ZMap.gsspec in Hgeti'.\n                unfold ZIndexed.eq in Hgeti'.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                rewrite ZMap.gsspec.\n                unfold ZIndexed.eq.\n                destruct (zeq i' i) as [ Hieq | Hineq ].\n                subst i'.\n                zeq_simpl.\n                inversion Hgeti'.\n                subst tds'.\n                repeat zeq_simpl.\n                exists t', t; trivial.\n                destruct (zeq i' t) as [ Hi'eq | Hi'neq ].\n                subst i'.\n                assert (st'' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st''.\n                exists t', hd'.\n                trivial.\n                destruct (zeq i' t') as [ Hi'eqt' | Hi'neqt' ].\n                subst i'.\n                assert (st' = tds').\n                destruct (H2 _ _ _ Hi' Hgeti') as [pv'x [nx'x Hxx]].\n                rewrite HLgett' in Hxx.\n                inversion Hxx.\n                trivial.\n                subst st'.\n                exists pv', t.\n                trivial.\n                apply H2 with inq'; eauto.\n        (* AbQ_RealQ proved *)\n        Qed.\n\n      End Exists.\n      \n      Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n      Proof.\n        accessor_prop_tac.\n        - eapply flatmem_store_exists; eauto.\n      Qed.          \n\n      Ltac sim_oplus_split_final D :=\n        match goal with\n          | |- sim _ ?T1 ?T2 =>\n            let L1 := construct_passthrough_layer T1 T2 in\n            let L2 := construct_left_layer T1 T2 D in\n            match L2 with\n              | \u2205 => change T2 with L1; sim_oplus_split_straight\n              | _ => change T2 with (L1 \u2295 L2); apply sim_left; sim_oplus_split_straight\n            end\n        end.\n\n      Lemma passthrough_correct:\n        sim (crel HDATA LDATA) pabqueue pqueueinit.\n      Proof.\n        sim_oplus.\n        - apply fload_sim.\n        - apply fstore_sim.\n        - apply flatmem_copy_sim.\n        - apply vmxinfo_get_sim.\n        - apply device_output_sim.\n        - apply pfree_sim.\n        - apply setPT_sim.\n        - apply ptRead_sim. \n        - apply ptResv_sim.\n        - apply kctxt_new_sim.\n        - apply shared_mem_status_sim.\n        - apply offer_shared_mem_sim.\n        - (* get_state *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          match_external_states_simpl.\n          erewrite get_state_exists; simpl; eauto 1; reflexivity.\n        - (* set_state *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          exploit set_state_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.\n        - (* tdqueue_init *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          exploit tdqueue_init_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.\n        - (* enqueue *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          exploit enqueue_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.\n        - (* dequeue *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          exploit dequeue_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.\n        - (* queue_rmv *)\n          layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n          exploit queue_rmv_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.\n        - apply ptin_sim.\n        - apply ptout_sim.\n        - apply clearCR2_sim.\n        - apply container_get_nchildren_sim.\n        - apply container_get_quota_sim.\n        - apply container_get_usage_sim.\n        - apply container_can_consume_sim.\n        - apply alloc_sim. \n        - apply trapin_sim.\n        - apply trapout_sim.\n        - apply hostin_sim.\n        - apply hostout_sim.\n        - apply trap_info_get_sim.\n        - apply trap_info_ret_sim.\n        - apply kctxt_switch_sim.\n        - layer_sim_simpl.\n          + eapply load_correct2.\n          + eapply store_correct2.\n        (*- (* thread_free *)\n          exploit thread_free_exists; eauto 1; intros (labd' & HP & HM).\n          match_external_states_simpl.*)\n      Qed.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\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/AbQueueGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.19119741574172447}}
{"text": "Require Import Prog.\nRequire Import Log.\nRequire Import BFile.\nRequire Import Word.\nRequire Import Omega.\nRequire Import Hashmap.   (* must go before basicprog, because notation using hashmap *)\nRequire Import BasicProg.\nRequire Import Bool.\nRequire Import Pred PredCrash.\nRequire Import DiskSet.\nRequire Import DirTree.\nRequire Import Pred.\nRequire Import String.\nRequire Import List.\nRequire Import BFile.\nRequire Import Inode.\nRequire Import Hoare.\nRequire Import GenSepN.\nRequire Import ListPred.\nRequire Import SepAuto.\nRequire Import Idempotent.\nRequire Import AsyncDisk.\nRequire Import Array.\nRequire Import ListUtils.\nRequire Import DirTree.\nRequire Import DirSep.\nRequire Import Arith.\nRequire Import SepAuto.\nRequire Import Omega.\nRequire Import SuperBlock.\nRequire Import FSLayout.\nRequire Import AsyncFS.\nRequire Import Arith.\nRequire Import Errno.\nRequire Import List ListUtils.\nRequire Import GenSepAuto.\nRequire Import DirTreePath.\nRequire Import DirTreeDef.\nRequire Import DirTreeRep.\nRequire Import DirTreePred.\nRequire Import DirTreeNames.\nRequire Import DirTreeInodes.\nRequire Import DirTreeSafe.\n\n\nImport DIRTREE.\nImport ListNotations.\n\nModule TREESEQ.\n\n  (**\n   * A layer over AFS that provides the same functions but with treeseq\n   * and dirsep specs. This layer provides the treeseq_safe property (see below),\n   * which makes it easier for application writers to reason about the file system,\n   * compared to using the AFS specs directly.\n   *)\n\n  Notation MSLL := BFILE.MSLL.\n  Notation MSAlloc := BFILE.MSAlloc.\n\n  Record treeseq_one := mk_tree {\n    TStree  : dirtree;\n    TSilist : list INODE.inode;\n    TSfree  : list addr * list addr\n  }.\n\n  Definition treeseq_one_safe t1 t2 mscs :=\n    dirtree_safe (TSilist t1) (BFILE.pick_balloc (TSfree t1) (MSAlloc mscs)) (TStree t1)\n                         (TSilist t2) (BFILE.pick_balloc (TSfree t2) (MSAlloc mscs)) (TStree t2).\n\n  Theorem treeseq_one_safe_refl : forall t mscs,\n    treeseq_one_safe t t mscs.\n  Proof.\n    intros.\n    apply dirtree_safe_refl.\n  Qed.\n\n  Theorem treeseq_one_safe_trans : forall t1 t2 t3 mscs,\n    treeseq_one_safe t1 t2 mscs ->\n    treeseq_one_safe t2 t3 mscs ->\n    treeseq_one_safe t1 t3 mscs.\n  Proof.\n    unfold treeseq_one_safe; intros.\n    eapply dirtree_safe_trans; eauto.\n  Qed.\n\n  Definition treeseq := nelist treeseq_one.\n\n  Definition tree_rep F Ftop fsxp t :=\n    (exists bfms sm,\n     F * rep fsxp Ftop (TStree t) (TSilist t) (TSfree t) bfms sm)%pred.\n\n  Definition tree_rep_latest F Ftop fsxp sm t bfms :=\n    (F * rep fsxp Ftop (TStree t) (TSilist t) (TSfree t) bfms sm)%pred.\n\n  Definition treeseq_in_ds F Ftop fsxp sm mscs (ts : treeseq) (ds : diskset) :=\n    NEforall2\n      (fun t d => tree_rep F Ftop fsxp t (list2nmem d) /\\\n                  treeseq_one_safe t (latest ts) mscs)\n      ts ds /\\\n    tree_rep_latest F Ftop fsxp sm (ts!!) mscs (list2nmem ds!!).\n\n  Definition treeseq_pred (p : treeseq_one -> Prop) (ts : treeseq) := NEforall p ts.\n\n  Theorem treeseq_pred_pushd : forall (p : treeseq_one -> Prop) t ts,\n    p t ->\n    treeseq_pred p ts ->\n    treeseq_pred p (pushd t ts).\n  Proof.\n    unfold treeseq_pred, NEforall, pushd; simpl; intros.\n    intuition.\n  Qed.\n\n  Theorem treeseq_in_ds_pushd : forall F Ftop fsxp sm mscs ts ds t mscs' d,\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    tree_rep_latest F Ftop fsxp sm t mscs' (list2nmem d) ->\n    treeseq_one_safe (latest ts) t mscs ->\n    BFILE.MSAlloc mscs' = BFILE.MSAlloc mscs ->\n    treeseq_in_ds F Ftop fsxp sm mscs' (pushd t ts) (pushd d ds).\n  Proof.\n    unfold treeseq_in_ds; simpl; intuition.\n    apply NEforall2_pushd; intuition.\n    rewrite latest_pushd.\n    eapply NEforall2_impl; eauto.\n    intuition.\n    intuition.\n    unfold treeseq_one_safe in *; intuition.\n    rewrite H2 in *.\n    eapply dirtree_safe_trans; eauto.\n    unfold tree_rep; unfold tree_rep_latest in *. pred_apply; cancel.\n    eapply dirtree_safe_refl.\n  Qed.\n\n  Definition treeseq_one_upd (t: treeseq_one) pathname off v :=\n    match find_subtree pathname (TStree t) with\n    | None => t\n    | Some (TreeFile inum f) => mk_tree (update_subtree pathname \n                                  (TreeFile inum (mk_dirfile (updN (DFData f) off v) (DFAttr f))) (TStree t))\n                           (TSilist t) (TSfree t)\n    | Some (TreeDir inum d) => t\n    end.\n\n  Definition tsupd (ts: treeseq) pathname off v :=\n    d_map (fun t => treeseq_one_upd t pathname off v) ts.\n\n  Lemma tsupd_latest: forall (ts: treeseq) pathname off v,\n    (tsupd ts pathname off v) !! = treeseq_one_upd (ts !!) pathname off v.\n  Proof.\n    intros.\n    unfold tsupd.\n    rewrite d_map_latest; eauto.\n  Qed.\n\n  Theorem treeseq_pred_impl : forall ts (p q : treeseq_one -> Prop),\n    treeseq_pred p ts ->\n    (forall t, p t -> q t) ->\n    treeseq_pred q ts.\n  Proof.\n    unfold treeseq_pred; intros.\n    eapply NEforall_impl; eauto.\n  Qed.\n\n  (**\n   * [treeseq_safe] helps applications prove their own correctness properties, at\n   * the cost of placing some restrictions on how the file system interface should\n   * be used by the application.\n   *\n   * The two nice things about [treeseq_safe] is that, first, it names files by\n   * pathnames (and, in particular, [treeseq_safe] for a file does not hold after\n   * that file has been renamed).  Second, [treeseq_safe] avoids the shrink-and-regrow\n   * problem that might arise if we were to [fdatasync] a file that has been shrunk\n   * and re-grown.  Without [treeseq_safe], [fdatasync] on a shrunk-and-regrown file\n   * would fail to sync the blocks that were shrunk and regrown, because the current\n   * inode no longer points to those old blocks.  As a result, the contents of the\n   * file on disk remains unsynced; this makes the spec of [fdatasync] complicated\n   * in the general case when the on-disk inode block pointers differ from the in-memory\n   * inode block pointers.\n   *\n   * [treeseq_safe] solves shrink-and-regrow by requiring that files monotonically\n   * grow (or, otherwise, [treeseq_safe] does not hold).  When [treeseq_safe] stops\n   * holding, the application can invoke [fsync] to flush metadata and, trivially,\n   * re-establish [treeseq_safe] because there is only one tree in the sequence now.\n   *\n   * [treeseq_safe] is defined with respect to a specific pathname.  What it means for\n   * [treeseq_safe] to hold for a pathname is that, in all previous trees, that pathname\n   * must refer to a file that has all the same blocks as the current file (modulo being\n   * shorter), or that pathname does not exist.  If, in some previous tree, the file does\n   * not exist or is shorter, then the \"leftover\" blocks must be unused.\n   *\n   * The reason why [treeseq_safe] is defined per pathname is that we imagine that some\n   * application may want to violate these rules for other pathnames.  For example, other\n   * files might shrink and re-grow over time, without calling [tree_sync] before re-growing.\n   * Or, the application might rename a file and continue writing to it using [update_fblock_d],\n   * which (below) will be not supported unless the caller can prove [treeseq_safe] for the\n   * current pathname of the file being modified.  The other behavior prohibited by [treeseq_safe]\n   * is re-using a pathname without [tree_sync].\n   *\n   * The per-pathname aspect of [treeseq_safe] might also come in handy for concurrency,\n   * where one thread does not know if other threads have already issued their [tree_sync]\n   * or not for other pathnames.\n   *)\n\n  (**\n   * [treeseq_safe] is defined as an if-and-only-if implication.  This captures two\n   * important properties.  First, the file is monotonically growing: if the file existed\n   * and some block belonged to it in the past, then the file must continue to exist and\n   * the block must continue to belong to the file at the same offset.  The forward\n   * implication captures this.  Second, we also need to know that all blocks used by\n   * the current file were never used by other files.  The reverse implication captures\n   * this part (the currently-used blocks were either free or used for the same file at\n   * the same pathname).\n   *)\n\n Definition treeseq_safe_fwd pathname (tnewest tolder : treeseq_one) :=\n    forall inum off bn,\n    (exists f, find_subtree pathname (TStree tolder) = Some (TreeFile inum f) /\\\n      BFILE.block_belong_to_file (TSilist tolder) bn inum off)\n   ->\n    (exists f', find_subtree pathname (TStree tnewest) = Some (TreeFile inum f') /\\\n     BFILE.block_belong_to_file (TSilist tnewest) bn inum off).\n\n  Definition treeseq_safe_bwd pathname flag (tnewest tolder : treeseq_one) :=\n    forall inum off bn,\n    (exists f', find_subtree pathname (TStree tnewest) = Some (TreeFile inum f') /\\\n     BFILE.block_belong_to_file (TSilist tnewest) bn inum off) ->\n    ((exists f, find_subtree pathname (TStree tolder) = Some (TreeFile inum f) /\\\n      BFILE.block_belong_to_file (TSilist tolder) bn inum off) \\/\n     BFILE.block_is_unused (BFILE.pick_balloc (TSfree tolder) flag) bn).\n\n  Definition treeseq_safe pathname flag (tnewest tolder : treeseq_one) :=\n    treeseq_safe_fwd pathname tnewest tolder /\\\n    treeseq_safe_bwd pathname flag tnewest tolder /\\\n    BFILE.ilist_safe (TSilist tolder)  (BFILE.pick_balloc (TSfree tolder)  flag)\n                     (TSilist tnewest) (BFILE.pick_balloc (TSfree tnewest) flag).\n\n  Theorem treeseq_safe_trans: forall pathname flag t0 t1 t2,\n    treeseq_safe pathname flag t0 t1 ->\n    treeseq_safe pathname flag t1 t2 ->\n    treeseq_safe pathname flag t0 t2.\n  Proof.\n    unfold treeseq_safe; intuition.\n    - unfold treeseq_safe_fwd in *; intuition.\n    - unfold treeseq_safe_bwd in *; intuition.\n      specialize (H0 _ _ _ H3).\n      inversion H0; eauto.\n      right.\n      unfold BFILE.ilist_safe in H5; destruct H5.\n      eapply In_incl.\n      apply H6.\n      eauto.\n    - eapply BFILE.ilist_safe_trans; eauto.\n  Qed.\n\n  Lemma tree_file_flist: forall F Ftop flist tree pathname inum f,\n    find_subtree pathname tree = Some (TreeFile inum f) ->\n    (F * tree_pred Ftop tree)%pred (list2nmem flist) ->\n    tree_names_distinct tree ->\n    exists c,\n    selN flist inum BFILE.bfile0 = dirfile_to_bfile f c.\n  Proof.\n    intros.\n    rewrite subtree_extract with (fnlist := pathname) (subtree := (TreeFile inum f)) in H0; eauto.\n    unfold tree_pred in H0.\n    destruct_lift H0.\n    eapply list2nmem_sel in H0; eauto.\n  Qed.\n\n\n  Ltac distinct_names :=\n    match goal with\n      [ H: (_ * rep _ _ ?tree _ _ _ _)%pred (list2nmem _) |- tree_names_distinct ?tree ] =>\n        eapply rep_tree_names_distinct; eapply H\n    end.\n\n  Ltac distinct_inodes :=\n    match goal with\n      [ H: (_ * rep _ _ ?tree _ _ _ _)%pred (list2nmem _) |- tree_inodes_distinct ?tree ] => \n        eapply rep_tree_inodes_distinct; eapply H\n    end.\n\n  Lemma tree_file_length_ok: forall F Ftop fsxp ilist frees mscs sm d tree pathname off bn inum f,\n      (F * rep Ftop fsxp tree ilist frees mscs sm)%pred d ->\n      find_subtree pathname tree = Some (TreeFile inum f) ->\n      BFILE.block_belong_to_file ilist bn inum off ->\n      off < Datatypes.length (DFData f).\n  Proof.\n    intros.\n    eapply rep_tree_names_distinct in H as Hdistinct.\n    apply BFILE.block_belong_to_file_inum_ok in H1 as H1'.\n\n    unfold rep in H.\n    unfold BFILE.rep in H.\n    destruct_lift H.\n\n    denote find_subtree as Hf.\n    denote tree_pred as Ht.\n    eapply tree_file_flist in Hf; eauto.\n    2: eapply pimpl_apply; [| exact Ht]; cancel.\n    2: eassign Ftop; cancel.\n    deex.\n\n    erewrite listmatch_extract with (i := inum) in H.\n    unfold BFILE.file_match at 2 in H.\n    rewrite listmatch_length_pimpl with (a := BFILE.BFData _) in H.\n    destruct_lift H.\n    rewrite map_length in *.\n    unfold BFILE.datatype, datatype in *.\n    unfold BFILE.block_belong_to_file in H1.\n    intuition.\n    subst.\n    denote dirfile_to_bfile as Hd.\n    rewrite Hd in *.\n    unfold dirfile_to_bfile in *. cbn in *.\n    simplen.\n\n    rewrite listmatch_length_pimpl in H.\n    destruct_lift H.\n    simplen.\n  Qed.\n\n\n  Lemma treeseq_in_ds_tree_pred_latest: forall Fm Ftop fsxp sm mscs ts ds,\n   treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n   (Fm \u2736 rep fsxp Ftop (TStree ts !!) (TSilist ts!!) (TSfree ts!!) mscs sm)%pred (list2nmem ds !!).\n  Proof.\n    intros.\n    unfold treeseq_in_ds in H.\n    intuition.\n  Qed.\n\n  Lemma treeseq_in_ds_tree_pred_nth: forall Fm Ftop fsxp mscs ts ds n sm,\n   treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n   (exists bfms sm,\n    Fm \u2736 rep fsxp Ftop (TStree (nthd n ts)) (TSilist (nthd n ts)) (TSfree (nthd n ts)) bfms sm)%pred (list2nmem (nthd n ds)).\n  Proof.\n    intros.\n    unfold treeseq_in_ds in H.\n    intuition.\n    unfold tree_rep in H0.\n    eapply NEforall2_d_in with (x := nthd n ts) in H0 as H0'.\n    intuition.\n    eassumption.\n    reflexivity.\n    reflexivity.\n  Qed.\n\n\n  Lemma treeseq_safe_refl : forall pathname flag tree,\n   treeseq_safe pathname flag tree tree.\n  Proof.\n    intros.\n    unfold treeseq_safe, treeseq_safe_fwd, treeseq_safe_bwd.\n    intuition.\n    apply BFILE.ilist_safe_refl.\n  Qed.\n\n  Lemma treeseq_safe_pushd: forall ts pathname flag tree',\n    treeseq_pred (treeseq_safe pathname flag tree') ts ->\n    treeseq_pred (treeseq_safe pathname flag tree') (pushd tree' ts).\n  Proof.\n    intros.\n    eapply NEforall_d_in'; intros.\n    eapply d_in_pushd in H0.\n    intuition.\n    rewrite H1.\n    eapply treeseq_safe_refl.\n    eapply NEforall_d_in; eauto.\n  Qed.\n\n\n  Ltac distinct_names' :=\n    repeat match goal with\n      | [ H: treeseq_in_ds _ _ _ _ _ ?ts _ |- tree_names_distinct (TStree ?ts !!) ] =>\n        eapply treeseq_in_ds_tree_pred_latest in H as Hpred;\n        destruct_lift Hpred;\n        eapply rep_tree_names_distinct; eassumption\n      | [ H: treeseq_in_ds _ _ _ _ _ ?ts _ |- tree_names_distinct (TStree (nthd ?n ?ts)) ] => \n        eapply treeseq_in_ds_tree_pred_nth in H as Hpred;\n        destruct_lift Hpred;\n        eapply rep_tree_names_distinct; eassumption\n    end.\n\n  Theorem treeseq_file_getattr_ok : forall fsxp inum mscs,\n  {< ds sm ts pathname Fm Ftop Ftree f,\n  PRE:hm LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ (Ftree * pathname |-> File inum f)%pred  (dir2flatmem2 (TStree ts!!)) ]] \n  POST:hm' RET:^(mscs',r)\n         LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n         [[ r = DFAttr f /\\ MSAlloc mscs' = MSAlloc mscs ]] *\n         [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]]\n  CRASH:hm'\n         LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm'\n  >} AFS.file_get_attr fsxp inum mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.file_getattr_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H6 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n    step.\n\n    unfold treeseq_in_ds in *; intuition.\n    eapply NEforall2_impl; eauto; intros; simpl in *; intuition.\n    unfold treeseq_one_safe in *; msalloc_eq; eauto.\n  Qed.\n\n  Theorem treeseq_lookup_ok: forall fsxp dnum fnlist mscs,\n    {< ds sm ts Fm Ftop,\n    PRE:hm\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ dirtree_inum (TStree ts !!) = dnum ]] *\n      [[ dirtree_isdir (TStree ts !!) = true ]]\n    POST:hm' RET:^(mscs', r)\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n      [[ (isError r /\\ None = find_name fnlist (TStree ts !!)) \\/\n         (exists v, r = OK v /\\ Some v = find_name fnlist (TStree ts !!))%type ]] *\n      [[ MSAlloc mscs' = MSAlloc mscs ]] *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]]\n    CRASH:hm'  LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm'\n     >} AFS.lookup fsxp dnum fnlist mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.lookup_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    step.\n\n    unfold treeseq_in_ds in *; intuition.\n    eapply NEforall2_impl; eauto; intros; simpl in *; intuition.\n    unfold treeseq_one_safe in *; msalloc_eq; eauto.\n\n    unfold treeseq_in_ds in *; intuition.\n    eapply NEforall2_impl; eauto; intros; simpl in *; intuition.\n    unfold treeseq_one_safe in *; msalloc_eq; eauto.\n  Qed.\n\n  Theorem treeseq_read_fblock_ok : forall fsxp inum off mscs,\n    {< ds sm ts Fm Ftop Ftree pathname f Fd vs,\n    PRE:hm LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ (Ftree * pathname |-> File inum f)%pred  (dir2flatmem2 (TStree ts!!)) ]] *\n      [[[ (DFData f) ::: (Fd * off |-> vs) ]]]\n    POST:hm' RET:^(mscs', r)\n           LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n           [[ r = fst vs /\\ MSAlloc mscs' = MSAlloc mscs ]] *\n           [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]]\n    CRASH:hm'\n           LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm'\n    >} AFS.read_fblock fsxp inum off mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.read_fblock_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n    eassumption.\n    step.\n\n    unfold treeseq_in_ds in *; intuition.\n    eapply NEforall2_impl; eauto; intros; simpl in *; intuition.\n    unfold treeseq_one_safe in *; msalloc_eq; eauto.\n  Qed.\n\n  Lemma treeseq_block_belong_to_file: forall F Ftop fsxp t d pathname inum f off,\n    tree_rep F Ftop fsxp t (list2nmem d) ->\n    find_subtree pathname (TStree t) = Some (TreeFile inum f)  ->\n    off < Datatypes.length (DFData f) ->\n    exists bn, BFILE.block_belong_to_file (TSilist t) bn inum off.\n  Proof.\n    unfold BFILE.block_belong_to_file.\n    intros.\n    eexists; intuition.\n    unfold tree_rep in H; destruct_lift H.\n    eapply rep_tree_names_distinct in H as Hdistinct.\n    unfold rep in H; destruct_lift H.\n\n    rewrite subtree_extract in H3; eauto.\n    simpl in H3.\n    destruct_lift H3.\n    assert (inum < Datatypes.length dummy1).\n    eapply list2nmem_inbound. \n    pred_apply; cancel.\n\n    replace (DFData f) with (BFILE.BFData {|\n             BFILE.BFData := DFData f;\n             BFILE.BFAttr := DFAttr f;\n             BFILE.BFCache := dummy4 |}) in H1 by reflexivity.\n\n    erewrite list2nmem_sel with (x := {|\n             BFILE.BFData := DFData f;\n             BFILE.BFAttr := DFAttr f;\n             BFILE.BFCache := dummy4 |}) (i := inum) (l := dummy1) in H1.\n    2: pred_apply; cancel.\n\n    clear H2.\n    unfold BFILE.rep in H; destruct_lift H.\n    rewrite listmatch_extract in H; eauto.\n\n    unfold BFILE.file_match at 2 in H.\n    erewrite listmatch_length_pimpl with (a := (BFILE.BFData dummy1 \u27e6 inum \u27e7)) in H.\n    destruct_lift H.\n\n    rewrite H17 in H1.\n    rewrite map_length in H1.\n    eauto.\n\n  Grab Existential Variables.\n    exact BFILE.bfile0.\n  Qed.\n\n  (* BFILE *)\n  Fact block_belong_to_file_bn_eq: forall tree bn bn0 inum off,\n    BFILE.block_belong_to_file tree bn inum off ->\n    BFILE.block_belong_to_file tree bn0 inum off ->\n    bn = bn0.\n  Proof.\n    intros;\n    unfold BFILE.block_belong_to_file in *.\n    intuition.\n  Qed.\n\n  Lemma find_subtree_none_not_pathname_prefix_1 : forall t pn1 pn2 inum2 f2,\n    find_subtree pn2 t = Some (TreeFile inum2 f2) ->\n    find_subtree pn1 t = None ->\n    ~ pathname_prefix pn1 pn2.\n  Proof.\n    unfold pathname_prefix; intros. intro; deex.\n    erewrite find_subtree_app_none in H.\n    inversion H.\n    eauto.\n  Qed.\n\n  Lemma find_subtree_dir_not_pathname_prefix_2 : forall t pn1 pn2 inum f dnum d,\n      pn1 <> pn2 ->\n      find_subtree pn1 t = Some (TreeDir dnum d) ->\n      find_subtree pn2 t = Some (TreeFile inum f) ->\n      ~ pathname_prefix pn2 pn1.\n  Proof.\n      unfold pathname_prefix; intros. intro; deex.\n      erewrite find_subtree_app in H0; eauto.\n      destruct suffix.\n      eapply H. rewrite app_nil_r; eauto.\n      rewrite find_subtree_file_none in H0.\n      inversion H0.\n  Qed.\n\n  Lemma find_subtree_file_not_pathname_prefix : forall t pn1 pn2 inum1 f1 inum2 f2,\n    find_subtree pn1 t = Some (TreeFile inum1 f1) ->\n    find_subtree pn2 t = Some (TreeFile inum2 f2) ->\n    pn1 <> pn2 ->\n    ~ pathname_prefix pn1 pn2.\n  Proof.\n    intros. unfold pathname_prefix; intro.\n    deex.\n    erewrite find_subtree_app in H0 by eauto.\n    destruct suffix; simpl in *; try congruence.\n    rewrite app_nil_r in *; eauto.\n  Qed.\n\n  Lemma find_subtree_update_subtree_file_not_pathname_prefix_1 : forall t pn1 old pn2 inum1 f1 inum2 f2,\n    find_subtree pn2 (update_subtree pn1 (TreeFile inum1 f1) t) = Some (TreeFile inum2 f2) ->\n    find_subtree pn1 t = Some old ->\n    pn1 <> pn2 ->\n    ~ pathname_prefix pn1 pn2.\n  Proof.\n    unfold pathname_prefix; intros. intro; deex.\n    erewrite find_subtree_app in * by eauto.\n    destruct suffix; simpl in *; try congruence.\n    rewrite app_nil_r in *; eauto.\n  Qed.\n\n  Lemma find_subtree_update_subtree_file_not_pathname_prefix_2 : forall t pn1 old pn2 inum1 f1 inum2 f2,\n    find_subtree pn2 (update_subtree pn1 (TreeFile inum1 f1) t) = Some (TreeFile inum2 f2) ->\n    find_subtree pn1 t = Some old ->\n    pn1 <> pn2 ->\n    ~ pathname_prefix pn2 pn1.\n  Proof.\n    unfold pathname_prefix; intros. intro; deex.\n    case_eq (find_subtree pn2 t); intros.\n    destruct d.\n    erewrite find_subtree_app in * by eauto. destruct suffix; simpl in *; try congruence. rewrite app_nil_r in *; eauto.\n    erewrite find_subtree_update_subtree_child in * by eauto.\n    destruct suffix; simpl in *; try congruence. rewrite app_nil_r in *; eauto.\n    erewrite find_subtree_app_none in * by eauto. congruence.\n  Qed.\n\n  Lemma treeseq_safe_pushd_update_subtree : forall Ftree ts pathname ilist' f f' inum  mscs pathname' free2,\n    let tree' := {|\n        TStree := update_subtree pathname\n                    (TreeFile inum f') \n                    (TStree ts !!);\n        TSilist := ilist';\n        TSfree := free2 |} in\n    tree_names_distinct (TStree ts !!) ->\n    tree_inodes_distinct (TStree ts !!) ->\n    Datatypes.length ilist' = Datatypes.length (TSilist ts!!) ->\n    (Ftree * pathname |-> File inum f)%pred (dir2flatmem2 (TStree ts !!)) ->\n    BFILE.ilist_safe (TSilist ts!!) (BFILE.pick_balloc (TSfree ts!!) (MSAlloc mscs))\n                     ilist' (BFILE.pick_balloc free2 (MSAlloc mscs)) ->\n    BFILE.treeseq_ilist_safe inum (TSilist ts!!) ilist' ->\n    treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) ts !!) ts ->\n    treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (pushd tree' ts) !!) (pushd tree' ts).\n  Proof.\n    intros.\n    subst tree'.\n    eapply dir2flatmem2_find_subtree_ptsto in H as Hfind; eauto.\n    eapply treeseq_safe_pushd; eauto.\n    eapply NEforall_d_in'; intros.\n    eapply NEforall_d_in in H5.\n    2: instantiate (1 := x); eauto.\n    destruct (list_eq_dec string_dec pathname pathname'); simpl.\n    - rewrite e in *; simpl.\n      unfold treeseq_safe in *.\n      intuition; simpl.\n      * unfold treeseq_safe_fwd in *.\n        intros; simpl.\n        specialize (H7 inum0 off bn).\n        destruct H7.\n        destruct H8.\n        eexists x0.\n        intuition.\n        intuition.\n        exists f'.\n        erewrite find_update_subtree; eauto.\n        rewrite Hfind in H10.\n        inversion H10.\n        unfold BFILE.treeseq_ilist_safe in *.\n        intuition.\n        specialize (H7 off bn).\n        destruct H7.\n        subst.\n        eauto.\n        subst.\n        split; eauto.\n      * unfold treeseq_safe_bwd in *; intros.\n        destruct (BFILE.block_is_unused_dec (BFILE.pick_balloc (TSfree ts!!) (MSAlloc mscs)) bn).\n        ++ deex.\n           right.\n           unfold BFILE.ilist_safe in H9; intuition.\n           eapply In_incl.\n           apply b.\n           eauto.\n\n        ++ \n        specialize (H5 inum off bn).\n        destruct H5.\n        ** eexists f.\n        split; eauto.\n        simpl in *.\n        subst.\n        erewrite find_update_subtree in H8 by eauto.\n        deex.\n        inversion H8.\n        unfold BFILE.ilist_safe in H3.\n        intuition.\n        specialize (H13 inum off bn).\n        subst.\n        destruct H13; eauto.\n\n        exfalso. eauto.\n\n        ** \n        destruct H5.\n        simpl in *.\n        erewrite find_update_subtree in H8.\n        intuition. deex.\n        inversion H8; eauto.\n        subst.\n        left.\n        eauto.\n        eauto.\n        **\n        right; eauto.\n\n     * eapply BFILE.ilist_safe_trans; eauto.\n\n     - unfold treeseq_safe in *.\n      intuition; simpl.\n      (* we updated pathname, but pathname' is still safe, if it was safe. *)\n      * unfold treeseq_safe_fwd in *; simpl.\n        intros; deex.\n        erewrite find_subtree_update_subtree_ne_path; eauto.\n        intros.\n        edestruct H7; eauto.\n        intuition.\n        eexists.\n        intuition. eauto.\n        destruct (addr_eq_dec inum inum0).\n        ** subst.\n          exfalso. apply n.\n          eapply find_subtree_inode_pathname_unique; eauto.\n\n        **\n        unfold BFILE.treeseq_ilist_safe in H4; intuition.\n        unfold BFILE.block_belong_to_file.\n        rewrite <- H14.\n        apply H13.\n        intuition.\n        **\n          unfold pathname_prefix; intro; deex.\n          edestruct H7; eauto; intuition.\n          erewrite find_subtree_app in H12 by eauto.\n          destruct suffix; simpl in *; try congruence.\n          rewrite app_nil_r in *; eauto.\n        **\n          unfold pathname_prefix; intro; deex.\n          edestruct H7; eauto; intuition.\n          erewrite find_subtree_app in Hfind by eauto.\n          destruct suffix; simpl in *; try congruence.\n          rewrite app_nil_r in *; eauto.\n      * unfold treeseq_safe_bwd in *; simpl; intros.\n        deex; intuition.\n        erewrite find_subtree_update_subtree_ne_path in *; eauto.\n\n        destruct (addr_eq_dec inum inum0).\n        ** subst.\n          exfalso. apply n.\n          eapply find_subtree_inode_pathname_unique; eauto.\n        **\n\n        eapply H5.\n        eexists. intuition eauto.\n\n        unfold BFILE.treeseq_ilist_safe in H4; intuition.\n        unfold BFILE.block_belong_to_file.\n        rewrite H12.\n        apply H11.\n        intuition.\n        **\n          unfold pathname_prefix; intro; deex.\n          erewrite find_subtree_app in * by eauto.\n          destruct suffix; simpl in *; try congruence.\n          rewrite app_nil_r in *; eauto.\n        **\n          eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n      * eapply BFILE.ilist_safe_trans; eauto.\n  Qed.\n\n  Ltac xcrash_solve :=\n    repeat match goal with\n           | [ H: forall _ _ _,  _ =p=> (?crash _) |- _ =p=> (?crash _) ] => eapply pimpl_trans; try apply H; cancel\n           | [ |- crash_xform (LOG.rep _ _ _ _ _) =p=> _ ] => rewrite LOG.notxn_intact; cancel\n           | [ H: crash_xform ?rc =p=> _ |- crash_xform ?rc =p=> _ ] => rewrite H; xform_norm\n           end.\n\n\n  Lemma mscs_same_except_log_tree_rep_latest : forall mscs mscs' F Ftop fsxp t sm,\n    BFILE.mscs_same_except_log mscs mscs' ->\n    tree_rep_latest F Ftop fsxp sm t mscs =p=>\n    tree_rep_latest F Ftop fsxp sm t mscs'.\n  Proof.\n    unfold tree_rep_latest; intros.\n    rewrite mscs_same_except_log_rep by eassumption.\n    cancel.\n  Qed.\n\n  Lemma mscs_parts_eq_tree_rep_latest : forall mscs mscs' F Ftop fsxp t sm,\n    MSCache mscs' = MSCache mscs ->\n    MSICache mscs' = MSICache mscs ->\n    MSAllocC mscs' = MSAllocC mscs ->\n    MSIAllocC mscs' = MSIAllocC mscs ->\n    MSDBlocks mscs' = MSDBlocks mscs ->\n    tree_rep_latest F Ftop fsxp t sm mscs =p=>\n    tree_rep_latest F Ftop fsxp t sm mscs'.\n  Proof.\n    unfold tree_rep_latest; intros.\n    unfold rep. unfold Balloc.IAlloc.rep. unfold Balloc.IAlloc.Alloc.rep; simpl.\n    msalloc_eq.\n    apply pimpl_refl.\n  Qed.\n\n  Lemma mscs_same_except_log_treeseq_one_safe : forall mscs mscs' t t',\n    BFILE.mscs_same_except_log mscs mscs' ->\n    treeseq_one_safe t t' mscs ->\n    treeseq_one_safe t t' mscs'.\n  Proof.\n    unfold BFILE.mscs_same_except_log, treeseq_one_safe; intuition msalloc_eq.\n    eauto.\n  Qed.\n\n  Lemma mscs_same_except_log_rep_treeseq_in_ds : forall F Ftop fsxp sm mscs mscs' ts ds,\n    BFILE.mscs_same_except_log mscs mscs' ->\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    treeseq_in_ds F Ftop fsxp sm mscs' ts ds.\n  Proof.\n    unfold treeseq_in_ds.\n    intuition eauto.\n    eapply NEforall2_impl; eauto.\n    intuition. intuition. intuition.\n    eapply mscs_same_except_log_treeseq_one_safe; eauto.\n    eapply mscs_same_except_log_tree_rep_latest; eauto.\n  Qed.\n\n  Lemma treeseq_in_ds_eq: forall Fm Ftop fsxp sm mscs a ts ds,\n    BFILE.mscs_same_except_log a mscs ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds <->\n    treeseq_in_ds Fm Ftop fsxp sm a ts ds.\n  Proof.\n    split; eapply mscs_same_except_log_rep_treeseq_in_ds; eauto.\n    apply BFILE.mscs_same_except_log_comm; eauto.\n  Qed.\n\n  Lemma treeseq_in_ds_mscs' : forall Fm Ftop fsxp sm mscs mscs' ts ds,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    (Fm * rep fsxp Ftop (TStree ts !!) (TSilist ts !!) (TSfree ts !!) mscs' sm)%pred (list2nmem ds !!) ->\n    MSAlloc mscs = MSAlloc mscs' ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds.\n  Proof.\n    unfold treeseq_in_ds, tree_rep_latest; intuition.\n    eapply NEforall2_impl; eauto.\n    intros; intuition.\n    intuition.\n    unfold treeseq_one_safe in *; intuition msalloc_eq.\n    eauto.\n  Qed.\n\n  Theorem treeseq_file_set_attr_ok : forall fsxp inum attr mscs,\n  {< ds sm ts pathname Fm Ftop Ftree f,\n  PRE:hm LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n     [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n     [[ (Ftree * pathname |-> File inum f)%pred (dir2flatmem2 (TStree ts!!)) ]] \n  POST:hm' RET:^(mscs', ok)\n     [[ MSAlloc mscs' = MSAlloc mscs ]] *\n     ([[ isError ok ]] * LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]] \\/\n      [[ ok = OK tt  ]] * exists d ds' ts' tree' ilist' f',\n        LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm hm' *\n        [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n        [[ forall pathname',\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n        [[ ds' = pushd d ds ]] *\n        [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' (TSfree ts !!) mscs' sm) ]]] *\n        [[ tree' = update_subtree pathname (TreeFile inum f') (TStree ts!!) ]] *\n        [[ ts' = pushd (mk_tree tree' ilist' (TSfree ts !!)) ts ]] *\n        [[ f' = mk_dirfile (DFData f) attr ]] *\n        [[ (Ftree * pathname |-> File inum f')%pred (dir2flatmem2 tree') ]])\n   XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm' \\/\n       exists d ds' ts' mscs' tree' ilist' f',\n         LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds' hm' *\n         [[ MSAlloc mscs' = MSAlloc mscs ]] *\n         [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds' ]] *\n         [[ forall pathname',\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n         [[ ds' = pushd d ds ]] *\n         [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' (TSfree ts !!) mscs' sm) ]]] *\n         [[ tree' = update_subtree pathname (TreeFile inum f') (TStree ts!!) ]] *\n         [[ ts' = pushd (mk_tree tree' ilist' (TSfree ts !!)) ts ]] *\n         [[ f' = mk_dirfile (DFData f) attr ]] *\n         [[ (Ftree * pathname |-> File inum f')%pred (dir2flatmem2 tree') ]]\n    >} AFS.file_set_attr fsxp inum attr mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2. \n    eapply AFS.file_set_attr_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H6 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n    step.\n    or_l. cancel.\n    eapply treeseq_in_ds_eq; eauto.\n    unfold BFILE.mscs_same_except_log; intuition.\n    or_r.\n    cancel.\n    eapply treeseq_in_ds_pushd; eauto.\n    unfold tree_rep.\n    unfold treeseq_one_safe.\n    simpl.\n    rewrite H in H12.\n    eassumption.\n    rewrite H in *.\n    eapply treeseq_in_ds_tree_pred_latest in H6 as Hpred.\n    eapply treeseq_safe_pushd_update_subtree; eauto.\n    distinct_names.\n    distinct_inodes.\n    rewrite rep_length in Hpred; destruct_lift Hpred.\n    rewrite rep_length in H10; destruct_lift H10.\n    congruence.\n\n    unfold dirtree_safe in *.\n    intuition.\n\n    eapply dir2flatmem2_update_subtree.\n    distinct_names'.\n    eassumption.\n\n    xcrash_solve.\n    - xform_normr.\n      or_l. cancel.\n    - or_r. cancel. repeat (progress xform_norm; safecancel).\n      eassumption.\n      5: reflexivity.\n      5: reflexivity.\n      5: reflexivity.\n      eapply treeseq_in_ds_pushd; eauto.\n      unfold treeseq_one_safe.\n      simpl.\n      repeat rewrite <- surjective_pairing in *.\n      rewrite H4 in *; eauto.\n      eapply treeseq_in_ds_tree_pred_latest in H6 as Hpred.\n      eapply treeseq_safe_pushd_update_subtree; eauto.\n      distinct_names.\n      distinct_inodes.\n      rewrite rep_length in Hpred; destruct_lift Hpred.\n      rewrite rep_length in H5; destruct_lift H5.\n      congruence.\n      unfold dirtree_safe in *.\n      repeat rewrite <- surjective_pairing in *.\n      rewrite H4 in *; eauto.\n      intuition.\n      eauto.\n      repeat rewrite <- surjective_pairing in *.\n      eauto.\n      eapply dir2flatmem2_update_subtree.\n      distinct_names'.\n      eassumption.\n  Qed.\n\n  Theorem treeseq_file_grow_ok : forall fsxp inum newlen mscs,\n  {< ds sm ts pathname Fm Ftop Ftree f,\n  PRE:hm LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n     [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n     [[ treeseq_pred (treeseq_safe pathname (MSAlloc mscs) (ts !!)) ts ]] *\n     [[ (Ftree * pathname |-> File inum f)%pred  (dir2flatmem2 (TStree ts!!)) ]] *\n     [[ newlen >= Datatypes.length (DFData f) ]]\n  POST:hm' RET:^(mscs', ok)\n      [[ MSAlloc mscs' = MSAlloc mscs ]] *\n     ([[ isError ok ]] *\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]] \\/\n      [[ ok = OK tt ]] * exists d ds' ts' ilist' frees' tree' f',\n        LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm hm' *\n        [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n        [[ forall pathname',\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n        [[ ds' = pushd d ds ]] *\n        [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm)]]] *\n        [[ f' = mk_dirfile (setlen (DFData f) newlen ($0, nil)) (DFAttr f) ]] *\n        [[ tree' = update_subtree pathname (TreeFile inum f') (TStree ts !!) ]] *\n        [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n        [[ (Ftree * pathname |-> File inum f')%pred (dir2flatmem2 tree') ]])\n  XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm' \\/\n       exists d ds' sm' ts' mscs' tree' ilist' f' frees',\n         LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds' hm' *\n         [[ MSAlloc mscs' = MSAlloc mscs ]] *\n         [[ treeseq_in_ds Fm Ftop fsxp sm' mscs' ts' ds' ]] *\n         [[ forall pathname',\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n         [[ ds' = pushd d ds ]] *\n         [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm) ]]] *\n         [[ f' = mk_dirfile (setlen (DFData f) newlen ($0, nil)) (DFAttr f) ]] *\n         [[ tree' = update_subtree pathname (TreeFile inum f') (TStree ts !!) ]] *\n         [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n         [[ (Ftree * pathname |-> File inum f')%pred (dir2flatmem2 tree') ]]\n  >} AFS.file_truncate fsxp inum newlen mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.file_truncate_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n    step.\n\n    or_l. cancel.\n    eapply treeseq_in_ds_mscs'; eauto.\n\n    or_r.\n    cancel.\n    eapply treeseq_in_ds_pushd; eauto.\n    unfold tree_rep.\n    unfold treeseq_one_safe.\n    simpl in *.\n    rewrite H in H14.\n    eassumption.\n    eapply treeseq_safe_pushd_update_subtree; eauto.\n    distinct_names'.\n    eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred.\n    distinct_inodes.\n    eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred.\n    rewrite rep_length in Hpred; destruct_lift Hpred.\n    rewrite rep_length in H12; destruct_lift H12.\n    congruence. \n\n    unfold dirtree_safe in *.\n    intuition.\n    rewrite H in H10; eauto.\n\n    eapply dir2flatmem2_update_subtree; eauto.\n    distinct_names'.\n    xcrash_solve.\n    - xform_normr. or_l. cancel.\n    - or_r. cancel. repeat (progress xform_norm; safecancel).\n      eassumption.\n      5: reflexivity.\n      5: reflexivity.\n      5: reflexivity.\n      eapply treeseq_in_ds_pushd; eauto.\n      unfold treeseq_one_safe.\n      simpl in *.\n      rewrite H4 in *.\n      repeat rewrite <- surjective_pairing in *.\n      eassumption.\n      eapply treeseq_safe_pushd_update_subtree; eauto.\n      distinct_names'.\n      eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred.\n      distinct_inodes.\n      eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred.\n      rewrite rep_length in Hpred; destruct_lift Hpred.\n      rewrite rep_length in H6; destruct_lift H6.\n      congruence. \n      unfold dirtree_safe in *.\n      repeat rewrite <- surjective_pairing in *.\n      rewrite H4 in *; eauto.\n      intuition.\n      eauto.\n      repeat rewrite <- surjective_pairing in *.\n      eauto.\n      eapply dir2flatmem2_update_subtree; eauto.\n      distinct_names'.\n  Qed.\n\n  Lemma block_is_unused_xor_belong_to_file : forall F Ftop fsxp t m flag bn inum off,\n    tree_rep F Ftop fsxp t m ->\n    BFILE.block_is_unused (BFILE.pick_balloc (TSfree t) flag) bn ->\n    BFILE.block_belong_to_file (TSilist t) bn inum off ->\n    False.\n  Proof.\n    unfold tree_rep; intros.\n    destruct t; simpl in *.\n    unfold rep in H; destruct_lift H.\n    eapply BFILE.block_is_unused_xor_belong_to_file with (m := m); eauto.\n    pred_apply.\n    cancel.\n  Qed.\n\n  Lemma tree_rep_nth_upd: forall F Ftop fsxp sm mscs ts ds n pathname bn off v inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file (TSilist (ts !!)) bn inum off ->\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    tree_rep F Ftop fsxp (nthd n ts) (list2nmem (nthd n ds)) ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    tree_rep F Ftop fsxp (treeseq_one_upd (nthd n ts) pathname off v) (list2nmem (nthd n ds) \u27e6 bn := v \u27e7).\n  Proof.\n    intros.\n    eapply NEforall_d_in in H3 as H3'; [ | apply nthd_in_ds with (n := n) ].\n    unfold treeseq_safe in H3'.\n    intuition.\n    unfold treeseq_one_upd.\n    unfold treeseq_safe_bwd in *.\n    edestruct H6; eauto.\n    - repeat deex.\n      rewrite H8.\n      unfold tree_rep; simpl.\n      unfold tree_rep in H2. destruct_lift H2.\n      eapply dirtree_update_block with (bn := bn) (m := (nthd n ds)) (v := v) in H2 as H2'; eauto.\n      pred_apply.\n      erewrite dirtree_update_inode_update_subtree; eauto.\n      cancel.\n      eapply rep_tree_inodes_distinct; eauto.\n      eapply rep_tree_names_distinct; eauto.\n      eapply tree_file_length_ok.\n      eapply H2.\n      eauto.\n      eauto.\n    - unfold tree_rep in *. destruct_lift H2.\n      eapply dirtree_update_free with (bn := bn) (v := v) in H2 as H2'; eauto.\n      case_eq (find_subtree pathname (TStree (nthd n ts))); intros; [ destruct d | ]; eauto.\n      2: pred_apply; cancel.\n      2: pred_apply; cancel.\n      rewrite updN_oob.\n      erewrite update_subtree_same; eauto.\n      unfold tree_rep. pred_apply. cancel.\n      eapply rep_tree_names_distinct; eauto.\n      destruct d; simpl in *; eauto.\n\n      destruct (lt_dec off (Datatypes.length (DFData d))); try omega.\n      exfalso.\n      edestruct treeseq_block_belong_to_file; eauto.\n      eassign (nthd n ds). unfold tree_rep. pred_apply; cancel.\n\n      unfold treeseq_safe_fwd in H4.\n      edestruct H4; eauto; intuition.\n      rewrite H11 in H; inversion H; subst.\n      eapply block_belong_to_file_bn_eq in H0; [ | apply H12 ].\n      subst.\n      eapply block_is_unused_xor_belong_to_file; eauto.\n      eassign (list2nmem (nthd n ds)). unfold tree_rep. pred_apply; cancel.\n  Qed.\n\n  Lemma tree_rep_latest_upd: forall F Ftop fsxp sm mscs ts ds pathname bn off v inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file (TSilist (ts !!)) bn inum off ->\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    tree_rep_latest F Ftop fsxp sm (ts !!) mscs (list2nmem (ds !!)) ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    tree_rep_latest F Ftop fsxp sm (treeseq_one_upd (ts !!) pathname off v) mscs (list2nmem (ds !!) \u27e6 bn := v \u27e7).\n  Proof.\n    intros.\n    eapply NEforall_d_in in H3 as H3'; [ | apply latest_in_ds ].\n    unfold treeseq_safe in H3'.\n    intuition.\n    unfold treeseq_one_upd.\n    unfold treeseq_safe_bwd in *.\n    edestruct H6; eauto.\n    - repeat deex.\n      rewrite H8.\n      unfold tree_rep; simpl.\n      unfold tree_rep in H2. destruct_lift H2.\n      eapply dirtree_update_block with (bn := bn) (m := (ds !!)) (v := v) in H2 as H2'; eauto.\n      pred_apply.\n      erewrite dirtree_update_inode_update_subtree; eauto.\n      eapply rep_tree_inodes_distinct; eauto.\n      eapply rep_tree_names_distinct; eauto.\n      eapply tree_file_length_ok.\n      eapply H2.\n      eauto.\n      eauto.\n    - unfold tree_rep in *. destruct_lift H2.\n      eapply dirtree_update_free with (bn := bn) (v := v) in H2 as H2'; eauto.\n      case_eq (find_subtree pathname (TStree (ts !!))); intros; [ destruct d | ]; eauto.\n      rewrite updN_oob.\n      erewrite update_subtree_same; eauto.\n      eapply rep_tree_names_distinct; eauto.\n      destruct d; simpl in *; eauto.\n\n      destruct (lt_dec off (Datatypes.length (DFData d))); try omega.\n      exfalso.\n      edestruct treeseq_block_belong_to_file; eauto.\n      eassign (ds !!). unfold tree_rep. pred_apply; cancel.\n\n      unfold treeseq_safe_fwd in H4.\n      edestruct H4; eauto; intuition.\n      rewrite H8 in H; inversion H; subst.\n      eapply block_belong_to_file_bn_eq in H0; [ | apply H9 ].\n      subst.\n      eapply block_is_unused_xor_belong_to_file; eauto.\n      eassign (list2nmem (ds !!)). pred_apply. unfold tree_rep, tree_rep_latest. cancel.\n  Qed.\n\n  Lemma treeseq_one_upd_alternative : forall t pathname off v,\n    treeseq_one_upd t pathname off v =\n    mk_tree (match find_subtree pathname (TStree t) with\n             | Some (TreeFile inum f) => update_subtree pathname (TreeFile inum (mk_dirfile (updN (DFData f) off v) (DFAttr f))) (TStree t)\n             | Some (TreeDir _ _) => TStree t\n             | None => TStree t\n             end) (TSilist t) (TSfree t).\n  Proof.\n    intros.\n    unfold treeseq_one_upd.\n    case_eq (find_subtree pathname (TStree t)); intros.\n    destruct d; auto.\n    destruct t; auto.\n    destruct t; auto.\n  Qed.\n\n  Lemma treeseq_one_safe_dsupd_1 : forall tolder tnewest mscs mscs' pathname off v inum f,\n    tree_names_distinct (TStree tolder) ->\n    treeseq_one_safe tolder tnewest mscs ->\n    find_subtree pathname (TStree tnewest) = Some (TreeFile inum f) ->\n    MSAlloc mscs' = MSAlloc mscs ->\n    treeseq_one_safe (treeseq_one_upd tolder pathname off v) tnewest mscs'.\n  Proof.\n    unfold treeseq_one_safe; intros.\n    repeat rewrite treeseq_one_upd_alternative; simpl.\n    rewrite H2; clear H2 mscs'.\n    unfold dirtree_safe in *; intuition.\n    destruct (list_eq_dec string_dec pathname0 pathname); subst.\n    - edestruct H3; eauto.\n      left.\n      intuition.\n      repeat deex.\n      exists pathname'.\n      case_eq (find_subtree pathname (TStree tolder)); intros; eauto.\n      destruct d; eauto.\n      destruct (list_eq_dec string_dec pathname' pathname); subst.\n      + erewrite find_update_subtree; eauto.\n        rewrite H5 in H7; inversion H7. eauto.\n      + rewrite find_subtree_update_subtree_ne_path; eauto.\n        eapply find_subtree_file_not_pathname_prefix; eauto.\n        eapply find_subtree_file_not_pathname_prefix; eauto.\n    - edestruct H3; eauto.\n      left.\n      intuition.\n      repeat deex.\n      exists pathname'.\n      case_eq (find_subtree pathname (TStree tolder)); intros; eauto.\n      destruct d; eauto.\n      destruct (list_eq_dec string_dec pathname' pathname); subst.\n      + erewrite find_update_subtree; eauto.\n        rewrite H5 in H7; inversion H7. eauto.\n      + rewrite find_subtree_update_subtree_ne_path; eauto.\n        eapply find_subtree_file_not_pathname_prefix; eauto.\n        eapply find_subtree_file_not_pathname_prefix; eauto.\n  Qed.\n\n  Lemma treeseq_one_safe_dsupd_2 : forall tolder tnewest mscs mscs' pathname off v inum f,\n    tree_names_distinct (TStree tnewest) ->\n    treeseq_one_safe tolder tnewest mscs ->\n    find_subtree pathname (TStree tnewest) = Some (TreeFile inum f) ->\n    MSAlloc mscs' = MSAlloc mscs ->\n    treeseq_one_safe tolder (treeseq_one_upd tnewest pathname off v) mscs'.\n  Proof.\n    unfold treeseq_one_safe; intros.\n    repeat rewrite treeseq_one_upd_alternative; simpl.\n    rewrite H1; simpl.\n    rewrite H2; clear H2 mscs'.\n    unfold dirtree_safe in *; intuition.\n    destruct (list_eq_dec string_dec pathname0 pathname); subst.\n    - erewrite find_update_subtree in H0; eauto.\n      inversion H0; subst.\n      edestruct H2; eauto.\n    - rewrite find_subtree_update_subtree_ne_path in H0.\n      edestruct H2; eauto.\n      eassumption.\n      eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n      eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n  Qed.\n\n  Lemma treeseq_one_safe_dsupd : forall tolder tnewest mscs mscs' pathname off v inum f,\n    tree_names_distinct (TStree tolder) ->\n    tree_names_distinct (TStree tnewest) ->\n    treeseq_one_safe tolder tnewest mscs ->\n    find_subtree pathname (TStree tnewest) = Some (TreeFile inum f) ->\n    MSAlloc mscs' = MSAlloc mscs ->\n    treeseq_one_safe (treeseq_one_upd tolder pathname off v)\n      (treeseq_one_upd tnewest pathname off v) mscs'.\n  Proof.\n    intros.\n    eapply treeseq_one_safe_trans.\n    eapply treeseq_one_safe_dsupd_1; eauto.\n    eapply treeseq_one_safe_dsupd_2; eauto.\n    eapply treeseq_one_safe_refl.\n  Qed.\n\n  Theorem treeseq_in_ds_upd : forall F Ftop fsxp sm mscs ts ds sm' mscs' pathname bn off v inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file (TSilist (ts !!)) bn inum off ->\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    treeseq_pred (treeseq_safe pathname  (BFILE.MSAlloc mscs) (ts !!)) ts ->\n    MSAlloc mscs = MSAlloc mscs' ->\n    (F * rep fsxp Ftop (TStree (tsupd ts pathname off v) !!) (TSilist ts !!) (TSfree ts !!) mscs' sm')%pred\n      (list2nmem (dsupd ds bn v) !!) ->\n    treeseq_in_ds F Ftop fsxp sm' mscs' (tsupd ts pathname off v) (dsupd ds bn v).\n  Proof.\n    intros.\n    unfold treeseq_in_ds in *; intuition.\n    unfold tsupd.\n    unfold dsupd.\n    eapply NEforall2_d_map; eauto.\n    simpl; intros.\n    intuition; subst.\n    eapply tree_rep_nth_upd; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n    rewrite d_map_latest.\n    unfold tree_rep in H9. destruct_lift H9.\n    eapply treeseq_one_safe_dsupd; eauto.\n    eapply rep_tree_names_distinct.\n    eapply H1.\n    eapply rep_tree_names_distinct.\n    eapply H6.\n\n    unfold tsupd in *. rewrite d_map_latest in *.\n    unfold dsupd in *. rewrite d_map_latest in *.\n    unfold tree_rep_latest.\n    unfold treeseq_one_upd at 2.\n    unfold treeseq_one_upd at 2.\n    destruct (find_subtree pathname (TStree ts !!)); [ destruct d | ]; simpl in *; eauto.\n  Qed.\n\n  Theorem treeseq_in_ds_upd' : forall F Ftop fsxp sm mscs ts ds pathname bn off v inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file (TSilist (ts !!)) bn inum off ->\n    treeseq_in_ds F Ftop fsxp sm mscs ts ds ->\n    treeseq_pred (treeseq_safe pathname  (BFILE.MSAlloc mscs) (ts !!)) ts ->\n    treeseq_in_ds F Ftop fsxp sm mscs (tsupd ts pathname off v) (dsupd ds bn v).\n  Proof.\n    intros.\n    unfold treeseq_in_ds in *; intuition.\n    unfold tsupd.\n    unfold dsupd.\n    eapply NEforall2_d_map; eauto.\n    simpl; intros.\n    intuition; subst.\n    eapply tree_rep_nth_upd; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n    rewrite d_map_latest.\n    unfold tree_rep in H7. destruct_lift H7.\n    eapply treeseq_one_safe_dsupd; eauto.\n    eapply rep_tree_names_distinct.\n    eapply H1.\n    eapply rep_tree_names_distinct.\n    eapply H4.\n\n    unfold tsupd. rewrite d_map_latest.\n    unfold dsupd. rewrite d_map_latest.\n    eapply tree_rep_latest_upd; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n  Qed.\n\n  Lemma seq_upd_safe_upd_fwd_ne: forall pathname pathname' inum n ts off v f mscs,\n    pathname' <> pathname ->\n    tree_names_distinct (TStree (nthd n ts)) ->\n    tree_names_distinct (TStree ts !!) ->\n     find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    treeseq_safe_fwd pathname ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname (MSAlloc mscs) ts !! (nthd n ts) ->\n    treeseq_safe_fwd pathname' ts !! (nthd n ts) ->\n    treeseq_safe_fwd pathname'\n      {|\n      TStree := update_subtree pathname\n                  (TreeFile inum\n                     {|\n                     DFData := (DFData f) \u27e6 off := v \u27e7;\n                     DFAttr := DFAttr f |}) (TStree ts !!);\n      TSilist := TSilist ts !!;\n      TSfree := TSfree ts !! |}\n      {|\n      TStree := match find_subtree pathname (TStree (nthd n ts)) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0\n                         {|\n                         DFData := (DFData f0) \u27e6 off := v \u27e7;\n                         DFAttr := DFAttr f0 |}) (TStree (nthd n ts))\n                | Some (TreeDir _ _) => TStree (nthd n ts)\n                | None => TStree (nthd n ts)\n                end;\n      TSilist := TSilist (nthd n ts);\n      TSfree := TSfree (nthd n ts) |}.\n  Proof.\n    unfold treeseq_safe_fwd in *; simpl in *; eauto. \n    intros.\n    case_eq (find_subtree pathname (TStree (nthd n ts))); intros.\n    destruct d.\n    erewrite find_subtree_update_subtree_ne_path; eauto.\n    rewrite H7 in H6.\n    erewrite find_subtree_update_subtree_ne_path in H6; eauto.\n    deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n    deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n    rewrite H7 in H6.\n    deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n    rewrite H7 in H6.\n    deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n    (* directory *)\n    rewrite H7 in H6.\n    deex.\n    {\n      destruct (pathname_decide_prefix pathname pathname'). deex. subst.\n      +\n       edestruct H5.\n       eexists.\n       intuition eauto.\n       intuition.\n       destruct suffix. rewrite app_nil_r in *. try congruence.\n       erewrite find_subtree_app in H10 by eauto.\n       simpl in *. try congruence.\n\n      + erewrite find_subtree_update_subtree_ne_path; eauto.\n        eapply find_subtree_dir_not_pathname_prefix_2; eauto.\n    }\n    (* None *)\n    rewrite H7 in H6.\n    deex.\n    {\n      destruct (pathname_decide_prefix pathname' pathname). deex. subst.\n      +  (* pathname' was a directory and now a file. *)\n        edestruct H5.\n        eexists.\n        intuition eauto.\n        intuition.\n        destruct suffix. rewrite app_nil_r in *. try congruence.\n        erewrite find_subtree_app in H2 by eauto.\n        simpl in *; congruence.\n\n      + erewrite find_subtree_update_subtree_ne_path; eauto.\n        eapply find_subtree_none_not_pathname_prefix_1; eauto.\n    }\n  Qed.\n\nLemma seq_upd_safe_upd_bwd_ne: forall pathname pathname' inum n ts off v f mscs,\n    pathname' <> pathname ->\n    tree_names_distinct (TStree (nthd n ts)) ->\n    tree_names_distinct (TStree ts !!) ->\n    tree_inodes_distinct (TStree ts !!) ->\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    treeseq_safe_fwd pathname ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname (MSAlloc mscs) ts !! (nthd n ts) ->\n    treeseq_safe_fwd pathname' ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname' (MSAlloc mscs) ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname' (MSAlloc mscs)\n      {|\n      TStree := update_subtree pathname\n                  (TreeFile inum\n                     {|\n                     DFData := (DFData f) \u27e6 off := v \u27e7;\n                     DFAttr := DFAttr f |}) (TStree ts !!);\n      TSilist := TSilist ts !!;\n      TSfree := TSfree ts !! |}\n      {|\n      TStree := match find_subtree pathname (TStree (nthd n ts)) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0\n                         {|\n                         DFData := (DFData f0) \u27e6 off := v \u27e7;\n                         DFAttr := DFAttr f0 |}) (TStree (nthd n ts))\n                | Some (TreeDir _ _) => TStree (nthd n ts)\n                | None => TStree (nthd n ts)\n                end;\n      TSilist := TSilist (nthd n ts);\n      TSfree := TSfree (nthd n ts) |}.\n  Proof.\n    unfold treeseq_safe_bwd in *; simpl; intros.\n    deex; intuition.\n    destruct (pathname_decide_prefix pathname pathname'). deex.\n    destruct suffix. rewrite app_nil_r in *. try congruence.\n    erewrite find_subtree_app in H9 by eauto.\n    simpl in *; congruence.\n    destruct (pathname_decide_prefix pathname' pathname). deex.\n    destruct suffix. rewrite app_nil_r in *. try congruence.\n    case_eq (find_subtree pathname' (TStree ts!!)); intros.\n    destruct d.\n    erewrite find_subtree_app in H3 by eauto.\n    simpl in *. congruence.\n\n    edestruct find_subtree_update_subtree_oob_general.\n    exact H8.\n    eassumption.\n    intuition.\n    rewrite H11 in H13; inversion H13; subst.\n    simpl in *. congruence.\n\n    rewrite find_subtree_app_none in H3 by eauto. congruence.\n    assert (~ pathname_prefix pathname pathname').\n    unfold pathname_prefix.\n    intro. deex. eauto.\n    assert (~ pathname_prefix pathname' pathname).\n    unfold pathname_prefix.\n    intro. deex. eauto.\n    erewrite find_subtree_update_subtree_ne_path in *; eauto.\n    case_eq (find_subtree pathname (TStree (nthd n ts))); intros.\n    destruct d.\n    erewrite find_subtree_update_subtree_ne_path; eauto.\n    specialize (H7 inum0 off0 bn).\n    edestruct H7.\n    eexists.\n    split; eauto.\n    destruct (addr_eq_dec inum inum0).\n    ** subst.\n      exfalso.\n      eapply find_subtree_inode_pathname_unique in H2; eauto.\n    ** destruct H15.\n      left.\n      exists x; eauto.\n    ** right; eauto.\n    ** \n      specialize (H7 inum0 off0 bn).\n      edestruct H7.\n      exists f'.\n      split; eauto.\n      destruct H15.\n      intuition.\n      left.\n      exists x.\n      split; eauto.\n      right; eauto.\n  Qed.\n\n  Lemma treeseq_upd_safe_upd: forall Fm fsxp Ftop mscs mscs' Ftree sm ts ds n pathname pathname' f f' off v inum bn,\n    (Fm \u2736 rep fsxp Ftop (update_subtree pathname (TreeFile inum f') (TStree ts !!)) (TSilist ts !!)\n         (fst (TSfree ts !!), snd (TSfree ts !!)) mscs' sm)%pred (list2nmem (dsupd ds bn v) !!) ->\n    (Ftree \u2736 pathname |-> File inum f)%pred (dir2flatmem2 (TStree ts !!)) -> \n    MSAlloc mscs = MSAlloc mscs' ->\n    True ->\n    BFILE.block_belong_to_file (TSilist ts !!) bn inum off ->\n    treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) ts !!) ts ->\n    treeseq_safe pathname (MSAlloc mscs) ts !! (nthd n ts) ->\n    tree_names_distinct (TStree ts !!) ->\n    tree_inodes_distinct (TStree ts !!) ->\n    tree_rep Fm Ftop fsxp (nthd n ts) (list2nmem (nthd n ds)) ->\n    treeseq_safe pathname' (MSAlloc mscs)\n      (treeseq_one_upd ts !! pathname off v)\n      (treeseq_one_upd (nthd n ts) pathname off v).\n  Proof.\n    intros.\n    eapply dir2flatmem2_find_subtree_ptsto in H0 as H0'; eauto.\n    repeat rewrite treeseq_one_upd_alternative; simpl.\n    rewrite H0' in *; simpl.\n    destruct (list_eq_dec string_dec pathname' pathname); subst; simpl in *.\n    - unfold treeseq_safe in *.\n      intuition.\n      + unfold treeseq_safe_fwd in *; intros; simpl in *.\n        erewrite find_update_subtree in *; eauto.\n        exists {|\n             DFData := (DFData f) \u27e6 off := v \u27e7;\n             DFAttr := DFAttr f; |}.\n        specialize (H9 inum0 off0 bn0).\n        case_eq (find_subtree pathname (TStree (nthd n ts))); intros.\n        destruct d.\n        -- rewrite H12 in *; simpl in *.\n          erewrite find_update_subtree in *; eauto.\n          destruct H10.\n          intuition.\n          inversion H13; subst. clear H13.\n          edestruct H9.\n          eexists d.\n          split; eauto.\n          intuition.\n          rewrite H0' in H13.\n          inversion H13; subst; eauto.\n          edestruct H9.\n          eexists d.\n          intuition.\n          inversion H13; subst; eauto.\n          intuition.\n        -- (* a directory *)\n          rewrite H12 in *; subst; simpl in *.\n          exfalso.\n          edestruct H10.\n          intuition.\n          rewrite H12 in H14; inversion H14.\n        -- (* None *)\n          rewrite H12 in *; subst; simpl in *.\n          exfalso.\n          edestruct H10.\n          intuition.\n          rewrite H12 in H14; inversion H14.\n      + unfold treeseq_safe_bwd in *. intros; simpl in *.\n        erewrite find_update_subtree in *; eauto.\n        destruct H10.\n        intuition.\n        inversion H12.\n        subst.\n        clear H12.\n        case_eq (find_subtree pathname (TStree (nthd n ts))).\n        intros.\n        destruct d.\n        -- (* a file *)\n          specialize (H5 inum0 off0 bn0).\n          destruct H5.\n          eexists f.\n          intuition.\n \n          destruct H5.\n          unfold BFILE.ilist_safe in H11.\n          intuition.\n          specialize (H14 inum0 off0 bn0).\n          destruct H14; auto.\n\n          left.\n          eexists.\n          split.\n          intuition.\n          rewrite H10 in H11.\n          inversion H11; subst.\n          eauto.\n          intuition.\n\n          right; eauto.\n\n        -- (* a directory *)\n        destruct (BFILE.block_is_unused_dec (BFILE.pick_balloc (TSfree ts!!) (MSAlloc mscs)) bn0).\n        ++ right.\n          unfold BFILE.ilist_safe in H11; intuition.\n          eapply In_incl.\n          apply b.\n          eauto.\n        ++ \n          specialize (H5 inum0 off0 bn0).\n          destruct H5.\n          eexists.\n          split; eauto.\n          destruct H5.\n          intuition.\n          rewrite H10 in H12.\n          exfalso; inversion H12.\n          right; eauto.\n\n        -- (* None *)\n          intros.\n          right.\n          specialize (H5 inum0 off0 bn0).\n          edestruct H5.\n          exists f; eauto.\n          deex.\n          exfalso.\n          rewrite H10 in H14; congruence.\n          eassumption.\n   - (* different pathnames, but pathname' is still safe, if it was safe. *)\n     unfold treeseq_safe in *.\n     unfold treeseq_pred in H4.\n     eapply NEforall_d_in with (x := (nthd n ts)) in H4 as H4'.  \n     2: eapply nthd_in_ds.\n     unfold tree_rep in H8; destruct_lift H8.\n     intuition; simpl.\n      *\n        eapply seq_upd_safe_upd_fwd_ne; eauto.\n        eapply rep_tree_names_distinct; eapply H8.\n      * \n        eapply seq_upd_safe_upd_bwd_ne; eauto.\n        eapply rep_tree_names_distinct; eapply H8.\n  Qed.\n\n  Theorem treeseq_update_fblock_d_ok : forall fsxp inum off v mscs,\n    {< ds sm ts Fm Ftop Ftree pathname f Fd vs,\n    PRE:hm\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ treeseq_pred (treeseq_safe pathname (MSAlloc mscs) (ts !!)) ts ]] *\n      [[ (Ftree * pathname |-> File inum f)%pred  (dir2flatmem2 (TStree ts!!)) ]] *\n      [[[ (DFData f) ::: (Fd * off |-> vs) ]]]\n    POST:hm' RET:^(mscs')\n      exists ts' f' ds' sm' bn,\n       LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm' hm' *\n       [[ treeseq_in_ds Fm Ftop fsxp sm' mscs' ts' ds']] *\n        [[ forall pathname',\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n       [[ ts' = tsupd ts pathname off (v, vsmerge vs) ]] *\n       [[ ds' = dsupd ds bn (v, vsmerge vs) ]] *\n       [[ MSAlloc mscs' = MSAlloc mscs ]] *\n       [[ MSCache mscs' = MSCache mscs ]] *\n       [[ MSAllocC mscs' = MSAllocC mscs ]] *\n       [[ MSIAllocC mscs' = MSIAllocC mscs ]] *\n       [[ (Ftree * pathname |-> File inum f')%pred (dir2flatmem2 (TStree ts' !!)) ]] *\n       [[[ (DFData f') ::: (Fd * off |-> (v, vsmerge vs)) ]]] *\n       [[ DFAttr f' = DFAttr f ]]\n    XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm' \\/\n       exists ds' ts' mscs' sm' bn,\n         LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds' hm' *\n         [[ ds' = dsupd ds bn (v, vsmerge vs) ]] *\n         [[ MSAlloc mscs' = MSAlloc mscs ]] *\n         [[ ts' = tsupd ts pathname off (v, vsmerge vs) ]] *\n         [[ treeseq_in_ds Fm Ftop fsxp sm' mscs' ts' ds' ]] *\n         [[ BFILE.block_belong_to_file (TSilist ts !!) bn inum off ]]\n   >} AFS.update_fblock_d fsxp inum off v mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.update_fblock_d_ok.\n    safecancel.\n    eapply treeseq_in_ds_tree_pred_latest in H8 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n\n\n    pose proof (list2nmem_array (DFData f)).\n    pred_apply.\n    erewrite arrayN_except with (i := off).\n    cancel.\n\n    eapply list2nmem_inbound; eauto.\n\n    safestep.\n\n    eapply treeseq_in_ds_upd; eauto.\n\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n\n    unfold tsupd. rewrite d_map_latest.\n    unfold treeseq_one_upd.\n    erewrite dir2flatmem2_find_subtree_ptsto; eauto; simpl.\n    2: distinct_names'.\n    denote! (DFAttr _ = DFAttr _) as Hx; rewrite <- Hx; clear Hx.\n    erewrite <- list2nmem_array_updN; eauto.\n    destruct f'; eassumption.\n    simplen.\n\n    eapply NEforall_d_in'; intros.\n    apply d_in_d_map in H4; deex; intuition.\n    eapply NEforall_d_in in H7 as H7'; try eassumption.\n    unfold tsupd; rewrite d_map_latest.\n    unfold treeseq_in_ds in H8.\n    eapply d_in_nthd in H6 as H6'; deex.\n    eapply NEforall2_d_in  with (x := (nthd n ts)) in H9 as Hd'; eauto.\n    intuition.\n    eapply treeseq_upd_safe_upd; eauto.\n    unfold tree_rep_latest in *; distinct_names.\n    unfold tree_rep_latest in *; distinct_inodes.\n\n    unfold tsupd.\n    unfold treeseq_one_upd.\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite H5'; eauto.\n\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite H5'; eauto.\n    3: eassumption.\n\n    unfold tsupd.\n    erewrite d_map_latest; eauto.\n    unfold treeseq_one_upd.\n    eapply dir2flatmem2_find_subtree_ptsto in H0 as H0'.\n    rewrite H0'; simpl.\n\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite <- H5'.\n\n    assert( f' = {|\n           DFData := (DFData f) \u27e6 off := (v, vsmerge vs) \u27e7;\n           DFAttr := DFAttr f |}).\n    destruct f'.\n    f_equal.\n    simpl in H15.\n    eapply list2nmem_array_updN in H15.\n    rewrite H15.\n    subst; eauto.\n    eapply list2nmem_ptsto_bound in H5 as H5''; eauto.\n    eauto.\n    eauto.\n    rewrite H4.\n    eapply dir2flatmem2_update_subtree; eauto.\n    distinct_names'.\n    distinct_names'.\n\n    pred_apply.\n    rewrite arrayN_ex_frame_pimpl; eauto.\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite H5'.\n    cancel.\n\n    xcrash_rewrite.\n    xcrash_rewrite.\n    xform_norm.\n    cancel.\n    or_r.\n    eapply pimpl_exists_r; eexists.\n    repeat (xform_deex_r).\n    xform_norm; safecancel.\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite H5'; eauto.\n    eauto.\n\n    eapply list2nmem_sel in H5 as H5'.\n    rewrite H5'; eauto.\n    eapply treeseq_in_ds_upd'; eauto.\n\n    eapply dir2flatmem2_find_subtree_ptsto; eauto.\n    distinct_names'.\n\n    eassumption.\n\n  Grab Existential Variables.\n    all: eauto.\n  Qed.\n\n  (* XXX maybe inum should be an argument and the TreeFile case should be split into two cases. *)\n  Definition treeseq_one_file_sync (t: treeseq_one) pathname :=\n      match find_subtree pathname (TStree t) with\n      | None => t\n      | Some (TreeFile inum f) => \n        mk_tree (update_subtree pathname (TreeFile inum (synced_dirfile f)) (TStree t)) (TSilist t) (TSfree t)\n      | Some (TreeDir _ _) => t\n      end.\n\n  Definition ts_file_sync pathname (ts: treeseq) :=\n    d_map (fun t => treeseq_one_file_sync t pathname) ts.\n\n  Fixpoint synced_up_to_n n (vsl : list valuset) : list valuset :=\n    match n with\n    | O => vsl\n    | S n' =>\n      match vsl with\n      | nil => nil\n      | vs :: vsl' => (fst vs, nil) :: (synced_up_to_n n' vsl')\n      end\n    end.\n\n  Theorem synced_list_up_to_n : forall vsl,\n    synced_list (map fst vsl) = synced_up_to_n (length vsl) vsl.\n  Proof.\n    induction vsl; eauto.\n    simpl.\n    unfold synced_list; simpl.\n    f_equal.\n    eauto.\n  Qed.\n\n  Lemma length_synced_up_to_n : forall n vsl,\n    length vsl = length (synced_up_to_n n vsl).\n  Proof.\n    induction n; simpl; eauto; intros.\n    destruct vsl; eauto.\n    simpl; eauto.\n  Qed.\n\n  Lemma synced_up_to_n_nil : forall n, synced_up_to_n n nil = nil.\n  Proof.\n    induction n; eauto.\n  Qed.\n\n  Lemma synced_up_to_n_too_long : forall vsl n,\n    n >= Datatypes.length vsl ->\n    synced_up_to_n n vsl = synced_up_to_n (Datatypes.length vsl) vsl.\n  Proof.\n    induction vsl; simpl; intros; eauto.\n    rewrite synced_up_to_n_nil; eauto.\n    destruct n; try omega.\n    simpl; f_equal.\n    eapply IHvsl.\n    omega.\n  Qed.\n\n  Lemma cons_synced_up_to_n' : forall synclen d l default,\n    synclen <= Datatypes.length l ->\n    (fst d, []) :: synced_up_to_n synclen l =\n    synced_up_to_n synclen (d :: l) \u27e6 synclen := (fst (selN (d :: l) synclen default), nil) \u27e7.\n  Proof.\n    induction synclen; simpl; intros; eauto.\n    f_equal.\n    destruct l; simpl.\n    rewrite synced_up_to_n_nil; eauto.\n    erewrite IHsynclen; simpl in *; eauto.\n    omega.\n  Qed.\n\n  Lemma cons_synced_up_to_n : forall synclen d l default,\n    (fst d, []) :: synced_up_to_n synclen l =\n    synced_up_to_n synclen (d :: l) \u27e6 synclen := (fst (selN (d :: l) synclen default), nil) \u27e7.\n  Proof.\n    intros.\n    destruct (le_dec synclen (Datatypes.length l)).\n    eapply cons_synced_up_to_n'; eauto.\n    rewrite updN_oob by (simpl; omega).\n    rewrite synced_up_to_n_too_long by omega. rewrite <- synced_list_up_to_n.\n    rewrite synced_up_to_n_too_long by (simpl; omega). rewrite <- synced_list_up_to_n.\n    firstorder.\n  Qed.\n\n  Fixpoint synced_file_alt_helper f off :=\n    match off with\n    | O => f\n    | S off' =>\n      let f' := mk_dirfile (updN (DFData f) off' (fst (selN (DFData f) off' ($0, nil)), nil)) (DFAttr f) in\n      synced_file_alt_helper f' off'\n    end.\n\n  Fixpoint synced_file_alt_helper2 f off {struct off} :=\n    match off with\n    | O => f\n    | S off' =>\n      let f' := synced_file_alt_helper2 f off' in\n      mk_dirfile (updN (DFData f') off' (fst (selN (DFData f') off' ($0, nil)), nil)) (DFAttr f')\n    end.\n\n  Lemma synced_file_alt_helper2_oob : forall off f off' v,\n    let f' := synced_file_alt_helper f off in\n    off' >= off ->\n    (mk_dirfile (updN (DFData f') off' v) (DFAttr f')) =\n    synced_file_alt_helper (mk_dirfile (updN (DFData f) off' v) (DFAttr f)) off.\n  Proof.\n    induction off; simpl; intros; eauto.\n    - rewrite IHoff by omega; simpl.\n      f_equal.\n      f_equal.\n      rewrite updN_comm by omega.\n      rewrite selN_updN_ne by omega.\n      auto.\n  Qed.\n\n  Lemma synced_file_alt_helper_selN_oob : forall off f off' default,\n    off' >= off ->\n    selN (DFData (synced_file_alt_helper f off)) off' default =\n    selN (DFData f) off' default.\n  Proof.\n    induction off; simpl; eauto; intros.\n    rewrite IHoff by omega; simpl.\n    rewrite selN_updN_ne by omega.\n    auto.\n  Qed.\n\n  Theorem synced_file_alt_helper_helper2_equiv : forall off f,\n    synced_file_alt_helper f off = synced_file_alt_helper2 f off.\n  Proof.\n    induction off; intros; simpl; auto.\n    rewrite <- IHoff; clear IHoff.\n    rewrite synced_file_alt_helper2_oob by omega.\n    f_equal.\n    f_equal.\n    rewrite synced_file_alt_helper_selN_oob by omega.\n    auto.\n  Qed.\n\n  Lemma synced_file_alt_helper2_selN_oob : forall off f off' default,\n    off' >= off ->\n    selN (DFData (synced_file_alt_helper2 f off)) off' default =\n    selN (DFData f) off' default.\n  Proof.\n    intros.\n    rewrite <- synced_file_alt_helper_helper2_equiv.\n    eapply synced_file_alt_helper_selN_oob; auto.\n  Qed.\n\n  Lemma synced_file_alt_helper2_length : forall off f,\n    Datatypes.length (DFData (synced_file_alt_helper2 f off)) = Datatypes.length (DFData f).\n  Proof.\n    induction off; simpl; intros; auto.\n    rewrite length_updN.\n    eauto.\n  Qed.\n\n  Definition synced_file_alt f :=\n    synced_file_alt_helper f (Datatypes.length (DFData f)).\n\n  Theorem synced_file_alt_equiv : forall f,\n    synced_dirfile f = synced_file_alt f.\n  Proof.\n    unfold synced_dirfile, synced_file_alt; intros.\n    rewrite synced_list_up_to_n.\n    unfold datatype.\n    remember (@Datatypes.length valuset (DFData f)) as synclen.\n    assert (synclen <= Datatypes.length (DFData f)) by simplen.\n    clear Heqsynclen.\n    generalize dependent f.\n    induction synclen; simpl; intros.\n    - destruct f; eauto.\n    - rewrite <- IHsynclen; simpl.\n      f_equal.\n      destruct (DFData f).\n      simpl in *; omega.\n      eapply cons_synced_up_to_n.\n      rewrite length_updN. omega.\n  Qed.\n\n  Lemma treeseq_one_upd_noop : forall t pathname off v inum f def,\n    tree_names_distinct (TStree t) ->\n    find_subtree pathname (TStree t) = Some (TreeFile inum f) ->\n    off < Datatypes.length (DFData f) ->\n    selN (DFData f) off def = v ->\n    t = treeseq_one_upd t pathname off v.\n  Proof.\n    unfold treeseq_one_upd; intros.\n    rewrite H0.\n    destruct t; simpl in *; f_equal.\n    rewrite update_subtree_same; eauto.\n    rewrite H0.\n    f_equal.\n    f_equal.\n    destruct f; simpl in *.\n    f_equal.\n    rewrite <- H2.\n    rewrite updN_selN_eq; eauto.\n  Qed.\n\n  Fixpoint treeseq_one_file_sync_alt_helper (t : treeseq_one) (pathname : list string) off fdata :=\n    match off with\n    | O => t\n    | S off' =>\n      let t' := treeseq_one_upd t pathname off' (selN fdata off' $0, nil) in\n      treeseq_one_file_sync_alt_helper t' pathname off' fdata\n    end.\n\n  Definition treeseq_one_file_sync_alt (t : treeseq_one) (pathname : list string) :=\n    match find_subtree pathname (TStree t) with\n    | None => t\n    | Some (TreeDir _ _) => t\n    | Some (TreeFile inum f) =>\n      treeseq_one_file_sync_alt_helper t pathname (length (DFData f)) (map fst (DFData f))\n    end.\n\n  Lemma treeseq_one_file_sync_alt_equiv : forall t pathname,\n    tree_names_distinct (TStree t) ->\n    treeseq_one_file_sync t pathname = treeseq_one_file_sync_alt t pathname.\n  Proof.\n    unfold treeseq_one_file_sync, treeseq_one_file_sync_alt; intros.\n    case_eq (find_subtree pathname (TStree t)); eauto.\n    destruct d; eauto.\n    intros.\n    rewrite synced_file_alt_equiv. unfold synced_file_alt.\n    remember (@Datatypes.length datatype (DFData d)) as synclen; intros.\n    assert (synclen <= Datatypes.length (DFData d)) by simplen.\n    clear Heqsynclen.\n\n    remember (map fst (DFData d)) as synced_blocks.\n    generalize dependent synced_blocks.\n    generalize dependent t.\n    generalize dependent d.\n    induction synclen; intros.\n    - simpl.\n      destruct t; destruct d; simpl in *; f_equal.\n      eapply update_subtree_same; eauto.\n    - simpl.\n      erewrite <- IHsynclen.\n      f_equal.\n      + unfold treeseq_one_upd. rewrite H0; simpl.\n        rewrite update_update_subtree_same. reflexivity.\n      + unfold treeseq_one_upd. rewrite H0. destruct t; eauto.\n      + unfold treeseq_one_upd. rewrite H0. destruct t; eauto.\n      + simpl. rewrite length_updN. omega.\n      + unfold treeseq_one_upd. rewrite H0. simpl.\n        eapply tree_names_distinct_update_subtree.\n        eauto. constructor.\n      + subst; simpl.\n        unfold treeseq_one_upd. rewrite H0; simpl.\n        erewrite selN_map.\n        erewrite find_update_subtree; eauto.\n        unfold datatype in *; omega.\n      + subst; simpl.\n        rewrite map_updN; simpl.\n        erewrite selN_eq_updN_eq; eauto.\n        erewrite selN_map; eauto.\n  Grab Existential Variables.\n    exact $0.\n  Qed.\n\n  Lemma treeseq_one_file_sync_alt_equiv_d_map : forall pathname ts,\n    NEforall (fun t => tree_names_distinct (TStree t)) ts ->\n    d_map (fun t => treeseq_one_file_sync t pathname) ts =\n    d_map (fun t => treeseq_one_file_sync_alt t pathname) ts.\n  Proof.\n    unfold d_map; destruct ts; intros.\n    f_equal; simpl.\n    - eapply treeseq_one_file_sync_alt_equiv.\n      eapply H.\n    - eapply map_ext_in; intros.\n      eapply treeseq_one_file_sync_alt_equiv.\n      destruct H; simpl in *.\n      eapply Forall_forall in H1; eauto.\n  Qed.\n\n  Theorem dirtree_update_safe_pathname_vssync_vecs_file:\n    forall pathname f tree fsxp F F0 ilist freeblocks mscs sm inum m al,\n    let tree_newest := update_subtree pathname (TreeFile inum (synced_dirfile f)) tree in\n    find_subtree pathname tree = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (forall i, i < length al -> BFILE.block_belong_to_file ilist (selN al i 0) inum i) ->\n    (F0 * rep fsxp F tree ilist freeblocks mscs sm)%pred (list2nmem m) ->\n    (F0 * rep fsxp F tree_newest ilist freeblocks mscs sm)%pred (list2nmem (vssync_vecs m al)).\n  Proof.\n    intros.\n    subst tree_newest.\n    rewrite synced_file_alt_equiv.\n    unfold synced_file_alt.\n    rewrite synced_file_alt_helper_helper2_equiv.\n    rewrite <- H0.\n    assert (Datatypes.length al <= Datatypes.length (DFData f)) by omega.\n    clear H0.\n\n    induction al using rev_ind; simpl; intros.\n    - rewrite update_subtree_same; eauto.\n      distinct_names.\n    - rewrite vssync_vecs_app.\n      unfold vssync.\n      erewrite <- update_update_subtree_same.\n      eapply pimpl_trans; [ apply pimpl_refl | | ].\n      2: eapply dirtree_update_block.\n      erewrite dirtree_update_inode_update_subtree.\n      rewrite app_length; simpl.\n      rewrite plus_comm; simpl.\n\n      rewrite synced_file_alt_helper2_selN_oob by omega.\n      replace (selN (vssync_vecs m al) x ($0, nil)) with\n              (selN (DFData f) (Datatypes.length al) ($0, nil)).\n\n      reflexivity.\n\n      erewrite <- synced_file_alt_helper2_selN_oob.\n      eapply dirtree_rep_used_block_eq.\n      eapply IHal.\n      {\n        intros. specialize (H1 i).\n        rewrite selN_app1 in H1 by omega.\n        eapply H1. rewrite app_length. omega.\n      }\n      rewrite app_length in *; omega.\n\n      erewrite find_update_subtree. reflexivity. eauto.\n      {\n        specialize (H1 (Datatypes.length al)).\n        rewrite selN_last in H1 by omega.\n        eapply H1. rewrite app_length. simpl. omega.\n      }\n      omega.\n\n      3: eapply find_update_subtree; eauto.\n\n      eapply rep_tree_inodes_distinct. eapply IHal.\n      {\n        intros. specialize (H1 i).\n        rewrite selN_app1 in H1 by omega.\n        eapply H1. rewrite app_length. omega.\n      }\n      rewrite app_length in *; omega.\n\n      eapply rep_tree_names_distinct. eapply IHal.\n      {\n        intros. specialize (H1 i).\n        rewrite selN_app1 in H1 by omega.\n        eapply H1. rewrite app_length. omega.\n      }\n      rewrite app_length in *; omega.\n\n      {\n        rewrite synced_file_alt_helper2_length.\n        rewrite app_length in *; simpl in *; omega.\n      }\n\n      eapply IHal.\n      {\n        intros. specialize (H1 i).\n        rewrite selN_app1 in H1 by omega.\n        eapply H1. rewrite app_length. omega.\n      }\n      rewrite app_length in *; omega.\n\n      eapply find_update_subtree; eauto.\n      specialize (H1 (Datatypes.length al)).\n      rewrite selN_last in * by auto.\n      eapply H1.\n      rewrite app_length; simpl; omega.\n  Qed.\n\n  Lemma block_belong_to_file_off_ok : forall Fm Ftop fsxp sm mscs ts t ds inum off pathname f,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    d_in t ts ->\n    find_subtree pathname (TStree t) = Some (TreeFile inum f) ->\n    off < Datatypes.length (DFData f) ->\n    BFILE.block_belong_to_file\n      (TSilist t)\n      (wordToNat (selN (INODE.IBlocks (selN (TSilist t) inum INODE.inode0)) off $0))\n      inum off.\n  Proof.\n    intros.\n    edestruct d_in_nthd; eauto; subst.\n    unfold treeseq_in_ds in H; intuition.\n    eapply NEforall2_d_in in H3; try reflexivity; intuition.\n    unfold tree_rep in H.\n    unfold rep in H.\n    destruct_lift H.\n    rewrite subtree_extract in H6 by eauto.\n    simpl in *.\n    destruct_lift H6.\n    eapply BFILE.block_belong_to_file_off_ok; eauto.\n    eapply pimpl_apply; [ | exact H ]. cancel.\n    pred_apply.\n    cancel.\n    simpl; eauto.\n  Qed.\n\n  Lemma block_belong_to_file_bfdata_length : forall Fm Ftop fsxp mscs sm ts ds inum off t pathname f bn,\n    treeseq_in_ds Fm Ftop fsxp mscs sm ts ds ->\n    d_in t ts ->\n    find_subtree pathname (TStree t) = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file (TSilist t) bn inum off ->\n    off < Datatypes.length (DFData f).\n  Proof.\n    intros.\n    edestruct d_in_nthd; eauto; subst.\n    unfold treeseq_in_ds in H; intuition.\n    eapply NEforall2_d_in in H3; try reflexivity; intuition.\n    unfold tree_rep in H.\n    unfold rep in H.\n    destruct_lift H.\n    rewrite subtree_extract in H6 by eauto.\n    simpl in *.\n    destruct_lift H6.\n    replace (DFData f) with (BFILE.BFData {|\n             BFILE.BFData := DFData f;\n             BFILE.BFAttr := DFAttr f;\n             BFILE.BFCache := dummy4 |}) by reflexivity.\n    erewrite list2nmem_sel with (x := {|\n             BFILE.BFData := DFData f;\n             BFILE.BFAttr := DFAttr f;\n             BFILE.BFCache := dummy4 |}).\n    eapply BFILE.block_belong_to_file_bfdata_length; eauto.\n    eapply pimpl_apply; [ | exact H ]; cancel.\n    pred_apply; cancel.\n  Qed.\n\n  Lemma treeseq_safe_fwd_length : forall Fm Ftop fsxp mscs sm ts ds n inum inum' f b pathname,\n    treeseq_in_ds Fm Ftop fsxp mscs sm ts ds ->\n    treeseq_safe_fwd pathname (ts !!) (nthd n ts) ->\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    find_subtree pathname (TStree (nthd n ts)) = Some (TreeFile inum' b) ->\n    length (DFData b) <= length (DFData f).\n  Proof.\n    intros.\n    case_eq (length (DFData b)); intros; try omega.\n    edestruct H0; intuition.\n    eexists; intuition eauto.\n    eapply block_belong_to_file_off_ok with (off := n0); eauto; try omega.\n    eapply nthd_in_ds.\n\n    eapply Nat.le_succ_l.\n    eapply block_belong_to_file_bfdata_length; eauto.\n    eapply latest_in_ds.\n\n    rewrite H1 in H5; inversion H5; subst.\n    eauto.\n  Qed.\n\n  Lemma tree_rep_nth_file_sync: forall Fm Ftop fsxp mscs sm ds ts n al pathname inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    tree_rep Fm Ftop fsxp (nthd n ts) (list2nmem (nthd n ds)) ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    tree_rep Fm Ftop fsxp (treeseq_one_file_sync (nthd n ts) pathname) (list2nmem (vssync_vecs (nthd n ds) al)).\n  Proof.\n    intros.\n    eapply NEforall_d_in in H4 as H4'; [ | apply nthd_in_ds with (n := n) ].\n    unfold treeseq_safe in H4'.\n    unfold treeseq_one_file_sync.\n    intuition.\n    case_eq (find_subtree pathname (TStree (nthd n ts))); intros.\n    destruct d.\n    - (* a file *)\n      unfold tree_rep; simpl.\n\n      rewrite <- firstn_skipn with (l := al) (n := length (DFData d)).\n      remember (skipn (Datatypes.length (DFData d)) al) as al_tail.\n\n      assert (forall i, i < length al_tail -> selN al_tail i 0 = selN al (length (DFData d) + i) 0).\n      subst; intros.\n      apply skipn_selN.\n\n      assert (length (DFData d) + length al_tail <= length al).\n      subst.\n      rewrite <- firstn_skipn with (l := al) (n := (length (DFData d))) at 2.\n      rewrite app_length.\n      eapply Plus.plus_le_compat; try omega.\n      rewrite firstn_length.\n      rewrite H0.\n      rewrite min_l; eauto.\n      eapply treeseq_safe_fwd_length; eauto.\n\n      clear Heqal_tail.\n\n      induction al_tail using rev_ind.\n\n      + (* No more tail remaining; all blocks correspond to file [b] *)\n        clear H9.\n        rewrite app_nil_r.\n        unfold tree_rep in H3; destruct_lift H3.\n        eexists.\n        eexists.\n        eapply dirtree_update_safe_pathname_vssync_vecs_file; eauto.\n\n        * rewrite firstn_length.\n          rewrite Nat.min_l; eauto.\n\n          case_eq (Datatypes.length (DFData d)); intros; try omega.\n\n        * intros.\n          rewrite firstn_length in H9.\n          apply PeanoNat.Nat.min_glb_lt_iff in H9.\n          intuition.\n\n          rewrite selN_firstn by auto.\n          edestruct H7.\n          eexists; intuition eauto.\n\n          **\n            deex.\n            rewrite H6 in H13. inversion H13; subst.\n            eauto.\n\n          **\n            exfalso.\n            edestruct H5; intuition.\n            eexists; intuition eauto.\n            eapply block_belong_to_file_off_ok with (off := i); eauto; try omega.\n            eapply nthd_in_ds.\n\n            rewrite H in H14; inversion H14; subst.\n            eapply block_belong_to_file_bn_eq in H15.\n            2: eapply H1; eauto.\n            rewrite H15 in H9.\n\n            eapply block_is_unused_xor_belong_to_file; eauto.\n            eassign (list2nmem (nthd n ds)). unfold tree_rep; pred_apply; cancel.\n            eapply block_belong_to_file_off_ok; eauto.\n            eapply nthd_in_ds.\n\n      + unfold tree_rep in H3; destruct_lift H3.\n        rewrite app_assoc. rewrite vssync_vecs_app.\n        unfold vssync.\n        edestruct IHal_tail.\n        shelve. shelve.\n        destruct H11.\n        eexists.\n        eexists.\n        eapply dirtree_update_free.\n        eassumption.\n        shelve.\n        Unshelve.\n        intros.\n        specialize (H9 i).\n        rewrite selN_app1 in H9 by omega. apply H9. rewrite app_length. omega.\n\n        rewrite app_length in *; simpl in *; omega.\n\n        shelve.\n\n        edestruct H7 with (off := length (DFData d) + length al_tail).\n        eexists. intuition eauto.\n        eapply H1.\n        rewrite app_length in *; simpl in *; omega.\n\n        (* [treeseq_safe_bwd] says that the block is present in the old file.  Should be a contradiction. *)\n        deex.\n        eapply block_belong_to_file_bfdata_length in H14; eauto.\n        rewrite H13 in H6; inversion H6; subst. omega.\n        eapply nthd_in_ds.\n\n        (* [treeseq_safe_bwd] says the block is unused. *)\n        rewrite <- H9 in H12.\n        rewrite selN_last in H12 by omega.\n        eapply H12.\n        rewrite app_length. simpl. omega.\n\n    - (* TreeDir *)\n      assert (length al <= length (DFData f)) by omega.\n      clear H0.\n      induction al using rev_ind; simpl; eauto.\n\n      rewrite vssync_vecs_app.\n      unfold vssync.\n      edestruct IHal. shelve. shelve. eexists.\n      destruct H0.\n      eexists.\n      eapply dirtree_update_free.\n      eassumption.\n      shelve. Unshelve.\n      intros. specialize (H1 i).\n      rewrite selN_app1 in H1 by omega. apply H1. rewrite app_length. omega.\n      rewrite app_length in *; simpl in *; omega.\n\n      shelve.\n\n      edestruct H7.\n      eexists; intuition eauto.\n      eapply H1 with (i := length al); rewrite app_length; simpl; omega.\n\n      deex; congruence.\n      rewrite selN_last in H0; eauto.\n\n    - (* None *)\n      assert (length al <= length (DFData f)) by omega.\n      clear H0.\n      induction al using rev_ind; simpl; eauto.\n\n      rewrite vssync_vecs_app.\n      unfold vssync.\n      edestruct IHal. shelve. shelve. eexists.\n      destruct H0.\n      eexists.\n      eapply dirtree_update_free.\n      eassumption.\n      shelve. Unshelve.\n      intros. specialize (H1 i).\n      rewrite selN_app1 in H1 by omega. apply H1. rewrite app_length. omega.\n      rewrite app_length in *; simpl in *; omega.\n\n      shelve.\n\n      edestruct H7.\n      eexists; intuition eauto.\n      eapply H1 with (i := length al); rewrite app_length; simpl; omega.\n\n      deex; congruence.\n      rewrite selN_last in H0; eauto.\n  Qed.\n\n  Lemma tree_rep_latest_file_sync: forall Fm Ftop fsxp mscs sm ds ts al pathname inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    tree_rep_latest Fm Ftop fsxp sm (ts !!) mscs (list2nmem (ds !!)) ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    tree_rep_latest Fm Ftop fsxp sm (treeseq_one_file_sync (ts !!) pathname) mscs (list2nmem (vssync_vecs (ds !!) al)).\n  Proof.\n    intros.\n    eapply NEforall_d_in in H4 as H4'; [ | apply latest_in_ds ].\n    unfold treeseq_safe in H4'.\n    unfold treeseq_one_file_sync.\n    intuition.\n    case_eq (find_subtree pathname (TStree (ts !!))); intros.\n    destruct d.\n    - (* a file *)\n      unfold tree_rep; simpl.\n\n      rewrite <- firstn_skipn with (l := al) (n := length (DFData d)).\n      remember (skipn (Datatypes.length (DFData d)) al) as al_tail.\n\n      assert (forall i, i < length al_tail -> selN al_tail i 0 = selN al (length (DFData d) + i) 0).\n      subst; intros.\n      apply skipn_selN.\n\n      assert (length (DFData d) + length al_tail <= length al).\n      subst.\n      rewrite <- firstn_skipn with (l := al) (n := (length (DFData d))) at 2.\n      rewrite app_length.\n      eapply Plus.plus_le_compat; try omega.\n      rewrite firstn_length.\n      rewrite H0.\n      rewrite min_l; eauto.\n      eapply treeseq_safe_fwd_length; eauto.\n\n      rewrite <- latest_nthd; eauto.\n      rewrite <- latest_nthd; eauto.\n\n      clear Heqal_tail.\n\n      induction al_tail using rev_ind.\n\n      + (* No more tail remaining; all blocks correspond to file [b] *)\n        clear H9.\n        rewrite app_nil_r.\n        unfold tree_rep in H3; destruct_lift H3.\n        eapply dirtree_update_safe_pathname_vssync_vecs_file; eauto.\n\n        * rewrite firstn_length.\n          rewrite Nat.min_l; eauto.\n\n          case_eq (Datatypes.length (DFData d)); intros; try omega.\n\n        * intros.\n          rewrite firstn_length in H9.\n          apply PeanoNat.Nat.min_glb_lt_iff in H9.\n          intuition.\n          simpl.\n\n          rewrite selN_firstn by auto.\n          edestruct H7.\n          exists f; intuition eauto.\n\n          **\n            deex.\n            rewrite H6 in H13. inversion H13; subst.\n            eauto.\n\n          **\n            exfalso.\n            edestruct H5; intuition.\n            eexists; intuition eauto.\n            eapply block_belong_to_file_off_ok with (off := i); eauto; try omega.\n            eapply latest_in_ds.\n\n            rewrite H in H14; inversion H14; subst.\n            eapply block_belong_to_file_bn_eq in H15.\n            2: eapply H1; eauto.\n            rewrite H15 in H9.\n\n            eapply block_is_unused_xor_belong_to_file; eauto.\n            eassign (list2nmem (ds !!)). pred_apply. unfold tree_rep, tree_rep_latest. cancel.\n            eapply block_belong_to_file_off_ok; eauto.\n            eapply latest_in_ds.\n\n      + rewrite app_assoc. rewrite vssync_vecs_app.\n        unfold vssync.\n        eapply dirtree_update_free.\n        eapply IHal_tail.\n        intros.\n        specialize (H9 i).\n        rewrite selN_app1 in H9 by omega. apply H9. rewrite app_length. omega.\n\n        rewrite app_length in *; simpl in *; omega.\n\n        edestruct H7 with (off := length (DFData d) + length al_tail).\n        exists f. intuition eauto.\n        eapply H1.\n        rewrite app_length in *; simpl in *; omega.\n\n        (* [treeseq_safe_bwd] says that the block is present in the old file.  Should be a contradiction. *)\n        deex.\n        eapply block_belong_to_file_bfdata_length in H13; eauto.\n        rewrite H12 in H6; inversion H6; subst. omega.\n        eapply latest_in_ds.\n\n        (* [treeseq_safe_bwd] says the block is unused. *)\n        rewrite <- H9 in H11.\n        rewrite selN_last in H11 by omega.\n        eapply H11.\n        rewrite app_length. simpl. omega.\n\n    - (* TreeDir *)\n      assert (length al <= length (DFData f)) by omega.\n      clear H0.\n      induction al using rev_ind; simpl; eauto.\n\n      rewrite vssync_vecs_app.\n      unfold vssync.\n      eapply dirtree_update_free.\n      eapply IHal.\n      intros. specialize (H1 i).\n      rewrite selN_app1 in H1 by omega. apply H1. rewrite app_length. omega.\n      rewrite app_length in *; simpl in *; omega.\n\n      edestruct H7.\n      eexists; intuition eauto.\n      eapply H1 with (i := length al); rewrite app_length; simpl; omega.\n\n      deex; congruence.\n      rewrite selN_last in H0; eauto.\n\n    - (* None *)\n      assert (length al <= length (DFData f)) by omega.\n      clear H0.\n      induction al using rev_ind; simpl; eauto.\n\n      rewrite vssync_vecs_app.\n      unfold vssync.\n      eapply dirtree_update_free.\n      eapply IHal.\n      intros. specialize (H1 i).\n      rewrite selN_app1 in H1 by omega. apply H1. rewrite app_length. omega.\n      rewrite app_length in *; simpl in *; omega.\n\n      edestruct H7.\n      eexists; intuition eauto.\n      eapply H1 with (i := length al); rewrite app_length; simpl; omega.\n\n      deex; congruence.\n      rewrite selN_last in H0; eauto.\n  Qed.\n\n  Lemma tree_safe_file_sync_1 : forall Fm Ftop fsxp mscs sm ds ts mscs' pathname,\n    (exists inum f, find_subtree pathname (TStree ts !!) = Some (TreeFile inum f)) ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    BFILE.MSAlloc mscs' = BFILE.MSAlloc mscs -> \n    treeseq_one_safe (ts !!) (treeseq_one_file_sync (ts !!) pathname) mscs'.\n  Proof.\n    intros.\n    rewrite treeseq_one_file_sync_alt_equiv.\n    unfold treeseq_one_file_sync_alt.\n    inversion H.\n    destruct H2.\n    rewrite H2.\n    remember (Datatypes.length (DFData x0)) as len; clear Heqlen.\n    remember (ts !!) as y. rewrite Heqy at 1.\n\n    assert (tree_names_distinct (TStree y)) as Hydistinct.\n    rewrite Heqy.\n    distinct_names'.\n\n    assert (treeseq_one_safe ts !! y mscs').\n    subst; eapply treeseq_one_safe_refl.\n    clear Heqy. clear H2.\n    generalize dependent y.\n    induction len; simpl; intros; eauto.\n    eapply IHlen.\n\n    repeat deex.\n    do 2 eexists.\n    unfold treeseq_one_upd.\n    rewrite H; simpl.\n    erewrite find_update_subtree; eauto.\n\n    repeat deex.\n\n    unfold treeseq_one_upd.\n    rewrite H; simpl.\n    eapply tree_names_distinct_update_subtree; eauto.\n    constructor.\n \n    repeat deex.\n    eapply treeseq_one_safe_dsupd_2; eauto.\n    distinct_names'.\n  Qed.\n\n  Lemma treeseq_in_ds_one_safe : forall Fm Ftop fsxp mscs mscs' sm ts ds n,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    MSAlloc mscs' = MSAlloc mscs ->\n    treeseq_one_safe (nthd n ts) ts !! mscs'.\n  Proof.\n    unfold treeseq_in_ds; intros.\n    intuition.\n    eapply NEforall2_d_in in H1; intuition.\n    unfold treeseq_one_safe.\n    rewrite H0.\n    eauto.\n  Qed.\n\n  Lemma tree_safe_file_sync_2 : forall Fm Ftop fsxp mscs sm ds ts mscs' n pathname,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    BFILE.MSAlloc mscs' = BFILE.MSAlloc mscs -> \n    treeseq_one_safe (treeseq_one_file_sync (nthd n ts) pathname) (ts !!) mscs'.\n  Proof.\n    intros.\n    rewrite treeseq_one_file_sync_alt_equiv.\n    unfold treeseq_one_file_sync_alt.\n    case_eq (find_subtree pathname (TStree (nthd n ts))); intros.\n    2: eapply treeseq_in_ds_one_safe; eauto.\n    destruct d.\n    2: eapply treeseq_in_ds_one_safe; eauto.\n\n    remember (Datatypes.length (DFData d)) as len; clear Heqlen.\n    remember (nthd n ts) as y.\n    assert (treeseq_one_safe y (nthd n ts) mscs').\n    subst; eapply treeseq_one_safe_refl.\n    remember H1 as H1'. clear HeqH1'. rewrite Heqy in H1'.\n\n    assert (tree_names_distinct (TStree y)) as Hydistinct.\n    rewrite Heqy.\n    distinct_names'.\n\n    clear Heqy.\n\n    assert (exists b0, find_subtree pathname (TStree y) = Some (TreeFile n0 b0) (* /\\ map fst (BFILE.BFData b) = map fst (BFILE.BFData b0) *)).\n    eexists; intuition eauto.\n    clear H1.\n\n    generalize dependent y.\n    induction len; simpl; intros; eauto.\n\n    eapply treeseq_one_safe_trans; eauto.\n    eapply treeseq_in_ds_one_safe; eauto.\n\n    eapply IHlen.\n    destruct H3; intuition.\n    eapply treeseq_one_safe_dsupd_1; eauto.\n\n    destruct H3; intuition.\n\n    unfold treeseq_one_upd.\n    rewrite H1; simpl.\n    eapply tree_names_distinct_update_subtree; eauto.\n    constructor.\n \n    destruct H3.\n    eexists.\n    unfold treeseq_one_upd.\n    rewrite H1; simpl.\n    erewrite find_update_subtree by eauto. reflexivity.\n\n    distinct_names'.\n  Qed.\n\n  Lemma tree_safe_file_sync: forall Fm Ftop fsxp mscs sm ds ts mscs' n al pathname inum f,\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (length al = length (DFData f) /\\ forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    BFILE.MSAlloc mscs' = BFILE.MSAlloc mscs -> \n    treeseq_one_safe (treeseq_one_file_sync (nthd n ts) pathname) \n     (d_map (fun t : treeseq_one => treeseq_one_file_sync t pathname) ts) !! mscs'.\n  Proof.\n    intros.\n    rewrite d_map_latest.\n    eapply treeseq_one_safe_trans.\n    eapply tree_safe_file_sync_2; eauto.\n    eapply tree_safe_file_sync_1; eauto.\n  Qed.\n\n  Lemma treeseq_in_ds_file_sync: forall  Fm Ftop fsxp mscs mscs' sm sm' ds ts al pathname inum  f,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (length al = length (DFData f) /\\ forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    MSAlloc mscs = MSAlloc mscs' ->\n    (Fm * rep fsxp Ftop (TStree (ts_file_sync pathname ts) !!) (TSilist ts !!) (TSfree ts !!) mscs' sm')%pred\n        (list2nmem (dssync_vecs ds al) !!) ->\n    treeseq_in_ds Fm Ftop fsxp sm' mscs' (ts_file_sync pathname ts) (dssync_vecs ds al).\n  Proof.\n    unfold treeseq_in_ds.\n    intros.\n    simpl; intuition.\n    unfold ts_file_sync, dssync_vecs.\n    eapply NEforall2_d_map; eauto.\n    simpl; intros.\n    intuition; subst.\n    eapply tree_rep_nth_file_sync; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n    eapply tree_safe_file_sync; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n\n    unfold dssync_vecs in *; rewrite d_map_latest in *.\n    unfold ts_file_sync in *; rewrite d_map_latest in *.\n    unfold tree_rep_latest.\n    unfold treeseq_one_file_sync at 2.\n    unfold treeseq_one_file_sync at 2.\n    destruct (find_subtree pathname (TStree ts !!)); [ destruct d | ]; simpl in *; eauto.\n  Qed.\n\n  Lemma treeseq_in_ds_file_sync' : forall  Fm Ftop fsxp sm mscs ds ts al pathname inum  f,\n    treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ->\n    treeseq_pred (treeseq_safe pathname (MSAlloc mscs) ts !!) ts ->\n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (length al = length (DFData f) /\\ forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    treeseq_in_ds Fm Ftop fsxp sm mscs (ts_file_sync pathname ts) (dssync_vecs ds al).\n  Proof.\n    unfold treeseq_in_ds.\n    intros.\n    simpl; intuition.\n    unfold ts_file_sync, dssync_vecs.\n    eapply NEforall2_d_map; eauto.\n    simpl; intros.\n    intuition; subst.\n    eapply tree_rep_nth_file_sync; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n    eapply tree_safe_file_sync; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n    unfold BFILE.mscs_same_except_log in *; intuition eauto.\n\n    unfold dssync_vecs; rewrite d_map_latest.\n    unfold ts_file_sync; rewrite d_map_latest.\n    eapply tree_rep_latest_file_sync; eauto.\n    unfold treeseq_in_ds; intuition eauto.\n  Qed.\n\n  Lemma treeseq_one_file_sync_alternative : forall t pathname,\n    treeseq_one_file_sync t pathname =\n    mk_tree (match find_subtree pathname (TStree t) with\n             | Some (TreeFile inum f) => update_subtree pathname (TreeFile inum (synced_dirfile f)) (TStree t)\n             | Some (TreeDir _ _) => TStree t\n             | None => TStree t\n             end) (TSilist t) (TSfree t).\n  Proof.\n    intros.\n    unfold treeseq_one_file_sync.\n    case_eq (find_subtree pathname (TStree t)); intros.\n    destruct d; auto.\n    destruct t; auto.\n    destruct t; auto.\n  Qed.\n\n  Lemma treeseq_safe_fwd_ne: forall pathname pathname' n ts inum f,\n    pathname <> pathname' ->\n    tree_names_distinct (TStree ts !!) ->\n    tree_names_distinct (TStree (nthd n ts)) -> \n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    treeseq_safe_fwd pathname ts !! (nthd n ts) ->\n    treeseq_safe_fwd pathname' ts !! (nthd n ts) ->\n    treeseq_safe_fwd pathname'\n      {|\n      TStree := match find_subtree pathname (TStree ts !!) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0 (synced_dirfile f0)) (TStree ts !!)\n                | Some (TreeDir _ _) => TStree ts !!\n                | None => TStree ts !!\n                end;\n      TSilist := TSilist ts !!;\n      TSfree := TSfree ts !! |}\n      {|\n      TStree := match find_subtree pathname (TStree (nthd n ts)) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0 (synced_dirfile f0))\n                      (TStree (nthd n ts))\n                | Some (TreeDir _ _) => TStree (nthd n ts)\n                | None => TStree (nthd n ts)\n                end;\n      TSilist := TSilist (nthd n ts);\n      TSfree := TSfree (nthd n ts) |}.\n  Proof.\n      unfold treeseq_safe_fwd in *; simpl in *; eauto. \n      intros.\n      case_eq (find_subtree pathname (TStree ts!!)); intros.\n      destruct d.\n      specialize (H4 inum0 off bn).\n      edestruct H4.\n      case_eq (find_subtree pathname (TStree (nthd n ts))); intros.        \n      destruct d0.\n      rewrite H7 in H5.\n      erewrite find_subtree_update_subtree_ne_path in H5; eauto.\n      deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n      deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n      rewrite H7 in H5.\n      deex; eauto.\n      rewrite H7 in H5.\n      deex; eauto.\n      intuition.\n      erewrite find_subtree_update_subtree_ne_path; eauto.\n      deex. eapply find_subtree_file_not_pathname_prefix with (pn1 := pathname) (pn2 := pathname'); eauto.\n      deex. eapply find_subtree_file_not_pathname_prefix with (pn1 := pathname') (pn2 := pathname) in H8; eauto.\n      rewrite H2 in H6.\n      exfalso.\n      inversion H6.\n      rewrite H2 in H6.\n      exfalso.\n      inversion H6.\n  Qed.\n\n  Lemma treeseq_safe_bwd_ne: forall pathname pathname' ts n inum f mscs,\n    pathname <> pathname' ->\n    tree_names_distinct (TStree ts !!) ->\n    tree_names_distinct (TStree (nthd n ts)) -> \n    find_subtree pathname (TStree ts !!) = Some (TreeFile inum f) ->\n    treeseq_safe_bwd pathname (MSAlloc mscs) ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname' (MSAlloc mscs) ts !! (nthd n ts) ->\n    treeseq_safe_bwd pathname' (MSAlloc mscs)\n      {|\n      TStree := match find_subtree pathname (TStree ts !!) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0 (synced_dirfile f0)) (TStree ts !!)\n                | Some (TreeDir _ _) => TStree ts !!\n                | None => TStree ts !!\n                end;\n      TSilist := TSilist ts !!;\n      TSfree := TSfree ts !! |}\n      {|\n      TStree := match find_subtree pathname (TStree (nthd n ts)) with\n                | Some (TreeFile inum0 f0) =>\n                    update_subtree pathname\n                      (TreeFile inum0 (synced_dirfile f0))\n                      (TStree (nthd n ts))\n                | Some (TreeDir _ _) => TStree (nthd n ts)\n                | None => TStree (nthd n ts)\n                end;\n      TSilist := TSilist (nthd n ts);\n      TSfree := TSfree (nthd n ts) |}.\n  Proof.\n        unfold treeseq_safe_bwd in *; simpl in *; eauto.\n        intros.\n        case_eq (find_subtree pathname (TStree (nthd n ts))); intros.        \n        destruct d.\n        erewrite find_subtree_update_subtree_ne_path; eauto.\n        specialize (H4 inum0 off bn).\n        edestruct H4.      \n        case_eq (find_subtree pathname (TStree ts!!)); intros.\n        destruct d0.\n        rewrite H7 in H5.\n        deex; eauto.\n        erewrite find_subtree_update_subtree_ne_path in H8; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n        deex.\n        left.\n        exists f0; eauto.\n        right; eauto.\n        rewrite H2 in H5.\n        deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n        rewrite H2 in H5.\n        deex. eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n        (* directory *)\n        case_eq (find_subtree pathname (TStree ts!!)); intros.\n        destruct d.\n        rewrite H7 in H5.\n        deex.\n        erewrite find_subtree_update_subtree_ne_path in H8; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n        (* None *)\n        case_eq (find_subtree pathname (TStree ts!!)); intros.\n        destruct d.\n        rewrite H7 in H5.\n        deex.\n        erewrite find_subtree_update_subtree_ne_path in H8; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_1; eauto.\n        eapply find_subtree_update_subtree_file_not_pathname_prefix_2; eauto.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n        rewrite H2 in H7.\n        exfalso.\n        inversion H7.\n  Qed.\n\n  Lemma treeseq_sync_safe_sync: forall Fm fsxp Ftop mscs sm Ftree ts ds n pathname pathname' f inum al,\n    (Fm \u2736 rep fsxp Ftop (update_subtree pathname (TreeFile inum (synced_dirfile f)) (TStree ts !!))\n           (TSilist ts !!) (fst (TSfree ts !!), snd (TSfree ts !!)) mscs sm)%pred\n        (list2nmem (dssync_vecs ds al) !!) ->\n    (Ftree \u2736 pathname |-> File inum f)%pred (dir2flatmem2 (TStree ts !!)) -> \n    Datatypes.length al = Datatypes.length (DFData f) ->\n    (length al = length (DFData f) /\\ forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i) ->\n    treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) ts !!) ts ->\n    treeseq_safe pathname (MSAlloc mscs) ts !! (nthd n ts) ->\n    tree_names_distinct (TStree ts !!) ->\n    tree_inodes_distinct (TStree ts !!) ->\n    tree_rep Fm Ftop fsxp (nthd n ts) (list2nmem (nthd n ds)) ->\n    treeseq_safe pathname' (MSAlloc mscs) \n      (treeseq_one_file_sync ts !! pathname)\n      (treeseq_one_file_sync (nthd n ts) pathname).\n  Proof.\n    intros.\n    eapply dir2flatmem2_find_subtree_ptsto in H0 as H0'; eauto.\n    repeat rewrite treeseq_one_file_sync_alternative; simpl.\n    destruct (list_eq_dec string_dec pathname' pathname); subst; simpl in *.\n    - unfold treeseq_safe in *.\n      intuition.\n      + unfold treeseq_safe_fwd in *; intros; simpl in *.\n        intuition.\n        specialize (H2 inum0 off bn).\n        deex.\n        case_eq (find_subtree pathname (TStree (nthd n ts))); intros; simpl.\n        destruct d.\n        -- (* a file *)\n          rewrite H10 in H12; simpl.\n          erewrite find_update_subtree in H12; eauto.\n          inversion H12.\n          subst n0; subst f0; clear H12.\n          edestruct H2.\n          eexists d.\n          intuition.\n          intuition.\n          rewrite H14.\n          exists (synced_dirfile x); eauto.\n       -- (* a directory *)\n          rewrite H10 in H12; simpl.\n          exfalso.\n          rewrite H10 in H12.\n          inversion H12.\n       -- (* None *)\n          rewrite H10 in H12; simpl.\n          exfalso.\n          rewrite H10 in H12.\n          inversion H12.\n      + unfold treeseq_safe_bwd in *; intros; simpl in *.\n        destruct H10.\n        specialize (H4 inum0 off bn).\n        case_eq (find_subtree pathname (TStree ts!!)); intros; simpl.\n        destruct d.\n        -- (* a file *)\n          rewrite H12 in H10; simpl.\n          erewrite find_update_subtree in H10; eauto.\n          intuition.\n          inversion H13.\n          subst n0; subst x.\n          clear H13.\n          edestruct H4.\n          eexists d.\n          intuition; eauto.\n          deex.\n          rewrite H13.\n          left.\n          exists (synced_dirfile f0).\n          erewrite find_update_subtree; eauto.\n          right; eauto.\n        -- (* a directory *)\n          rewrite H12 in H10.\n          intuition.\n          exfalso.\n          rewrite H13 in H12.\n          inversion H12.\n        -- (* None *)\n          rewrite H12 in H10.\n          intuition.\n          exfalso.\n          rewrite H13 in H12.\n          inversion H12.\n    - (* different pathnames, but pathname' is still safe, if it was safe. *)\n      unfold treeseq_safe in *.\n      unfold treeseq_pred in H3.\n      eapply NEforall_d_in with (x := (nthd n ts)) in H3 as H3'.  \n      2: eapply nthd_in_ds.\n      unfold tree_rep in H7; destruct_lift H7.\n      intuition; simpl.\n      + \n        eapply treeseq_safe_fwd_ne; eauto.\n        eapply rep_tree_names_distinct; eapply H7.\n      + \n        eapply treeseq_safe_bwd_ne; eauto.\n        eapply rep_tree_names_distinct; eapply H7.\n  Qed.\n\n\n  Ltac distinct_inodes' :=\n    repeat match goal with\n      | [ H: treeseq_in_ds _ _ _ _ _ ?ts _ |- tree_inodes_distinct (TStree ?ts !!) ] => \n        eapply treeseq_in_ds_tree_pred_latest in H as Hpred;\n        eapply rep_tree_inodes_distinct; eapply Hpred\n    end.\n\n  Theorem treeseq_file_sync_ok : forall fsxp inum mscs,\n    {< ds sm ts Fm Ftop Ftree pathname f,\n    PRE:hm\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ treeseq_pred (treeseq_safe pathname (MSAlloc mscs) (ts !!)) ts ]] *\n      [[ (Ftree * pathname |-> File inum f)%pred (dir2flatmem2 (TStree ts!!)) ]]\n    POST:hm' RET:^(mscs')\n      exists ds' al sm',\n       let ts' := ts_file_sync pathname ts in\n         LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm' hm' *\n         [[ treeseq_in_ds Fm Ftop fsxp sm' mscs' ts' ds']] *\n          [[ forall pathname',\n             treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n             treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n         [[ ds' = dssync_vecs ds al]] *\n         [[ length al = length (DFData f) /\\ forall i, i < length al ->\n                BFILE.block_belong_to_file (TSilist ts !!) (selN al i 0) inum i ]] *\n         [[ MSAlloc mscs = MSAlloc mscs' ]] *\n         [[ (Ftree * pathname |-> File inum (synced_dirfile f))%pred (dir2flatmem2 (TStree ts' !!)) ]]\n    XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm'\n   >} AFS.file_sync fsxp inum mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.file_sync_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto.\n    distinct_names'.\n    eassumption.\n    step.\n\n    eapply treeseq_in_ds_file_sync; eauto.\n    eapply dir2flatmem2_find_subtree_ptsto in H4 as H4'.\n    eassumption.\n    distinct_names'.\n\n    unfold ts_file_sync. rewrite d_map_latest.\n    unfold treeseq_one_file_sync.\n    erewrite dir2flatmem2_find_subtree_ptsto; try eassumption.\n    distinct_names'.\n\n    unfold ts_file_sync.\n    rewrite d_map_latest.\n\n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    eapply NEforall_d_in'; intros.\n    apply d_in_d_map in H8; deex; intuition.\n    eapply NEforall_d_in in H6 as H6'; try eassumption.\n    eapply d_in_nthd in H9 as H9'; deex.\n\n    msalloc_eq.\n    eapply treeseq_sync_safe_sync.\n    denote dssync_vecs as Hx; exact Hx.\n    all: eauto.\n    distinct_names.\n    distinct_inodes.\n\n    unfold treeseq_in_ds in H7. intuition.\n    eapply NEforall2_d_in  with (x := (nthd n ts)) in H as Hd'; eauto.\n    intuition.\n\n    unfold ts_file_sync.\n    rewrite d_map_latest.\n    unfold treeseq_one_file_sync.\n    eapply dir2flatmem2_find_subtree_ptsto in H4 as H4'; eauto.\n    rewrite H4'; simpl.\n    eapply dir2flatmem2_update_subtree; eauto.\n    distinct_names'.\n    distinct_names'.\n  Qed.\n\n  Lemma treeseq_latest: forall (ts : treeseq),\n    (ts !!, []) !! = ts !!.\n  Proof.\n    intros.\n    unfold latest.\n    simpl; reflexivity.\n  Qed.\n\n  Theorem treeseq_tree_sync_ok : forall fsxp mscs,\n    {< ds sm ts Fm Ftop,\n    PRE:hm\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]]\n    POST:hm' RET:^(mscs')\n      exists sm',\n       LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn (ds!!, nil)) (MSLL mscs') sm' hm' *\n       [[ treeseq_in_ds Fm Ftop fsxp sm' mscs' ((ts !!), nil) (ds!!, nil)]]\n    XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm'\n   >} AFS.tree_sync fsxp mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.tree_sync_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H5 as Hpred; eauto.\n    step.\n\n    unfold treeseq_in_ds.\n    unfold NEforall2.\n    simpl in *.\n    split.\n    split.\n    unfold treeseq_in_ds in H5; intuition;\n      eapply NEforall2_latest in H0; intuition.\n    eapply treeseq_one_safe_refl.\n    unfold treeseq_in_ds in H5; intuition;\n      eapply NEforall2_latest in H0; intuition.\n    eapply mscs_parts_eq_tree_rep_latest; eauto.\n    unfold treeseq_in_ds in H5; intuition.\n  Qed.\n\n  Lemma treeseq_safe_rename: forall pathname' mscs cwd dstnum0 dstents \n    dstbase dstname srcnum0 srcents srcbase srcname dnum tree_elem ts\n      frees'_1 frees'_2 ilist' subtree,\n    tree_names_distinct (TStree ts!!) ->\n    tree_inodes_distinct (TStree ts!!) ->\n    find_subtree cwd (TStree ts !!) = Some (TreeDir dnum tree_elem) ->\n    find_subtree srcbase (TreeDir dnum tree_elem) = Some (TreeDir srcnum0 srcents) ->\n    find_dirlist srcname srcents = Some subtree ->\n    find_subtree dstbase\n            (tree_prune srcnum0 srcents srcbase srcname (TreeDir dnum tree_elem)) =\n          Some (TreeDir dstnum0 dstents) ->\n    (forall inum' def', inum' <> srcnum0 -> inum' <> dstnum0 ->\n               In inum' (tree_inodes\n           (update_subtree cwd\n              (tree_graft dstnum0 dstents dstbase dstname subtree\n                 (tree_prune srcnum0 srcents srcbase srcname\n                    (TreeDir dnum tree_elem))) (TStree ts !!))) ->\n               selN (TSilist ts !!) inum' def' = selN ilist' inum' def') ->\n    (~pathname_prefix (cwd ++ srcbase ++ [srcname]) pathname') ->\n    (~pathname_prefix (cwd ++ dstbase ++ [dstname]) pathname') ->\n    dirtree_safe (TSilist ts !!)\n            (BFILE.pick_balloc (fst (TSfree ts !!), snd (TSfree ts !!))\n               (MSAlloc mscs)) (TStree ts !!) ilist'\n            (BFILE.pick_balloc (frees'_1, frees'_2) (MSAlloc mscs))\n            (update_subtree cwd\n               (tree_graft dstnum0 dstents dstbase dstname subtree\n                  (tree_prune srcnum0 srcents srcbase srcname\n                     (TreeDir dnum tree_elem))) (TStree ts !!)) ->\n    treeseq_safe pathname' (MSAlloc mscs)\n      {|\n      TStree := update_subtree cwd\n                  (tree_graft dstnum0 dstents dstbase dstname subtree\n                     (tree_prune srcnum0 srcents srcbase srcname\n                        (TreeDir dnum tree_elem))) (TStree ts !!);\n      TSilist := ilist';\n      TSfree := (frees'_1, frees'_2) |} ts !!.\n  Proof.\n    unfold treeseq_safe; intuition.\n\n    - unfold treeseq_safe_fwd.\n      intros; simpl.\n      deex.\n      exists f; eauto.\n      intuition.\n      eapply find_rename_oob; eauto.\n\n      unfold BFILE.block_belong_to_file in *.\n      rewrite H5 in *; eauto.\n\n      intro. subst.\n\n      erewrite <- find_subtree_app in H2 by eassumption.\n      assert (pathname' = cwd ++ srcbase).\n      eapply find_subtree_inode_pathname_unique; eauto.\n      congruence.\n\n      intro. subst.\n      eapply find_subtree_before_prune in H4.\n      deex.\n      erewrite <- find_subtree_app in H4 by eassumption.\n      assert (pathname' = cwd ++ dstbase).\n      eapply find_subtree_inode_pathname_unique; eauto.\n      congruence.\n      eapply find_subtree_tree_names_distinct; eauto.\n      eauto.\n\n      eapply tree_inodes_in_rename_oob; eauto.\n\n    - unfold treeseq_safe_bwd in *.\n      intros.\n      left.\n      repeat deex; intuition.\n      denote pathname' as Hp.\n      eexists f'; intuition; simpl in *.\n      eapply find_rename_oob'. 7: eauto.\n      all: auto.\n      unfold BFILE.block_belong_to_file in *.\n      rewrite H5 in *; eauto.\n      -- intro. subst.\n        destruct (pathname_decide_prefix cwd pathname').\n        + deex.\n          erewrite find_subtree_app in Hp by eauto.\n          eapply find_subtree_graft_subtree_oob' in Hp.\n          2: eauto.\n          eapply find_subtree_prune_subtree_oob' in Hp.\n          2: eauto.\n          assert (srcbase = suffix).\n          eapply find_subtree_inode_pathname_unique with (tree := (TreeDir dnum tree_elem)); eauto.\n          eapply find_subtree_tree_inodes_distinct; eauto.\n          eapply find_subtree_tree_names_distinct; eauto.\n          congruence.\n          intro; apply H6.  apply pathname_prefix_trim; eauto.\n          intro; apply H7.  apply pathname_prefix_trim; eauto.\n        + \n          eapply find_subtree_update_subtree_oob' in Hp.\n          assert (cwd++srcbase = pathname').\n\n          erewrite <- find_subtree_app in H2 by eauto.\n          eapply find_subtree_inode_pathname_unique; eauto.\n          contradiction H9; eauto.\n          eauto.\n      -- intro. subst.\n       destruct (pathname_decide_prefix cwd pathname').\n        + deex.\n          erewrite find_subtree_app in Hp by eauto.\n          eapply find_subtree_graft_subtree_oob' in Hp.\n          2: eauto.\n          eapply find_subtree_prune_subtree_oob' in Hp.\n          2: eauto.\n          eapply find_subtree_before_prune in H4; eauto.\n          deex.\n          assert (dstbase = suffix).\n          eapply find_subtree_inode_pathname_unique with (tree := (TreeDir dnum tree_elem)); eauto.\n          eapply find_subtree_tree_inodes_distinct; eauto.\n          eapply find_subtree_tree_names_distinct; eauto.\n          congruence.\n          eapply find_subtree_tree_names_distinct; eauto.\n          intro; apply H6.  apply pathname_prefix_trim; eauto.\n          intro; apply H7.  apply pathname_prefix_trim; eauto.\n        + \n          eapply find_subtree_update_subtree_oob' in Hp.\n          eapply find_subtree_before_prune in H4; eauto.\n          deex.\n          assert (cwd++dstbase = pathname').\n          erewrite <- find_subtree_app in H4 by eauto.\n          eapply find_subtree_inode_pathname_unique; eauto.\n          contradiction H9; eauto.\n          eapply find_subtree_tree_names_distinct; eauto.\n          eauto.\n      --\n        replace inum with (dirtree_inum (TreeFile inum f')) by reflexivity.\n        eapply find_subtree_inum_present; eauto.\n    - simpl.\n      unfold dirtree_safe in *; intuition.\n  Qed.\n\n\n  Theorem treeseq_rename_ok : forall fsxp dnum srcbase (srcname:string) dstbase dstname mscs,\n    {< ds sm ts Fm Ftop Ftree cwd tree_elem srcnum dstnum srcfile dstfile,\n    PRE:hm\n    LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ find_subtree cwd (TStree ts !!) = Some (TreeDir dnum tree_elem) ]] *\n      [[ (Ftree * (cwd ++ srcbase ++ [srcname]) |-> File srcnum srcfile\n                * (cwd ++ dstbase ++ [dstname]) |-> File dstnum dstfile)%pred (dir2flatmem2 (TStree ts !!)) ]]\n    POST:hm' RET:^(mscs', ok)\n      [[ MSAlloc mscs' = MSAlloc mscs ]] *\n      ([[ isError ok ]] *\n       LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n       [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]] \\/\n       [[ ok = OK tt ]] * exists d ds' ts' ilist' frees' tree',\n       LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm hm' *\n       [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n       [[ forall pathname',\n           ~ pathname_prefix (cwd ++ srcbase ++ [srcname]) pathname' ->\n           ~ pathname_prefix (cwd ++ dstbase ++ [dstname]) pathname' ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n       [[ ds' = (pushd d ds) ]] *\n       [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm) ]]] *\n       [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n       [[ (Ftree * (cwd ++ srcbase ++ [srcname]) |-> Nothing\n                 * (cwd ++ dstbase ++ [dstname]) |-> File srcnum srcfile)%pred (dir2flatmem2 (TStree ts' !!)) ]])\n    XCRASH:hm'\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm' \\/\n       exists d ds' ts' ilist' frees' tree' mscs',\n       LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds' hm' *\n       [[ MSAlloc mscs' = MSAlloc mscs ]] *\n       [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n       [[ forall pathname',\n           ~ pathname_prefix (cwd ++ srcbase ++ [srcname]) pathname' ->\n           ~ pathname_prefix (cwd ++ dstbase ++ [dstname]) pathname' ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n       [[ ds' = (pushd d ds) ]] *\n       [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm) ]]] *\n       [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n       [[ (Ftree * (cwd ++ srcbase ++ [srcname]) |-> Nothing\n                 * (cwd ++ dstbase ++ [dstname]) |-> File srcnum srcfile)%pred (dir2flatmem2 (TStree ts' !!)) ]]\n   >} AFS.rename fsxp dnum srcbase srcname dstbase dstname mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.rename_ok.\n    cancel. \n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    eassumption.\n    step.\n\n    or_l. cancel. eapply treeseq_in_ds_mscs'; eauto.\n\n    unfold AFS.rename_rep, AFS.rename_rep_inner.\n    cancel.\n    or_r.\n\n    (* a few obligations need subtree *)\n    eapply sep_star_split_l in H4 as H4'.\n    destruct H4'.\n    eapply dir2flatmem2_find_subtree_ptsto in H8.\n    erewrite find_subtree_app in H8.\n    2: eassumption.\n    erewrite find_subtree_app in H8.\n    2: eassumption.\n    2: distinct_names'.\n\n    cancel.\n\n    - eapply treeseq_in_ds_pushd; eauto.\n      unfold treeseq_one_safe; simpl.\n      rewrite H in H11.\n      eassumption.\n\n    - eapply treeseq_safe_pushd; eauto.\n      eapply NEforall_d_in'; intros.\n      eapply NEforall_d_in in H13; eauto.\n      eapply treeseq_safe_trans; eauto.\n\n      (* clear all goals mentioning x0 *)\n      clear H13 H15 x0.\n\n      eapply treeseq_safe_rename; eauto.\n      distinct_names'.\n      distinct_inodes'.\n      rewrite H in *; eauto.\n\n    - eapply dir2flatmem2_rename; eauto.\n      distinct_names'.\n      distinct_inodes'.\n\n    - unfold AFS.rename_rep_inner in *.\n      xcrash_solve.\n      or_l. cancel. xform_normr. cancel.\n      or_r. cancel. repeat (progress xform_norm; safecancel).\n\n      eassumption.\n      3: reflexivity.\n      4: reflexivity.\n      3: pred_apply; cancel.\n\n      + eapply treeseq_in_ds_pushd; eauto.\n        unfold treeseq_one_safe; simpl.\n        rewrite <- surjective_pairing in H11.\n        rewrite H0 in H11.\n        eassumption.\n\n      + eapply treeseq_safe_pushd; eauto.\n        eapply NEforall_d_in'; intros.\n        eapply NEforall_d_in in H22; eauto.\n        eapply treeseq_safe_trans; eauto.\n\n        eapply treeseq_safe_rename; eauto.\n        distinct_names'.\n        distinct_inodes'.\n        rewrite H0 in *; eauto.\n\n      + eapply dir2flatmem2_rename; eauto.\n        distinct_names'.\n        distinct_inodes'.\n  Qed.\n\n  Lemma treeseq_safe_delete: forall pathname' pathname name dnum tree_elem ts ilist' mscs \n    frees'_1 frees'_2 Ftree file finum,\n    tree_names_distinct (TStree ts !!) ->\n    tree_inodes_distinct (TStree ts !!) ->\n    (Ftree \u2736 (pathname ++ [name]) |-> File finum file)%pred(dir2flatmem2 (TStree ts !!)) ->\n    find_subtree pathname (TStree ts !!) = Some (TreeDir dnum tree_elem) ->\n    (forall inum def',\n        (inum = dnum -> False) ->\n        In inum (tree_inodes (TStree ts !!)) ->\n        In inum\n          (tree_inodes\n             (update_subtree pathname\n                (TreeDir dnum (delete_from_list name tree_elem)) (TStree ts !!))) ->\n        selN (TSilist ts !!) inum def' = selN ilist' inum def')  ->\n     dirtree_safe (TSilist ts !!)\n          (BFILE.pick_balloc (fst (TSfree ts !!), snd (TSfree ts !!))\n             (MSAlloc mscs)) (TStree ts !!) ilist'\n          (BFILE.pick_balloc (frees'_1, frees'_2) (MSAlloc mscs))\n          (update_subtree pathname\n             (TreeDir dnum (delete_from_list name tree_elem)) (TStree ts !!)) ->\n     (~pathname_prefix (pathname ++ [name]) pathname') -> \n     treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) ts !!) ts ->\n     treeseq_pred\n        (treeseq_safe pathname' (MSAlloc mscs)\n           (pushd\n              {|\n              TStree := update_subtree pathname\n                          (TreeDir dnum (delete_from_list name tree_elem))\n                          (TStree ts !!);\n              TSilist := ilist';\n              TSfree := (frees'_1, frees'_2) |} ts) !!)\n        (pushd\n           {|\n           TStree := update_subtree pathname\n                       (TreeDir dnum (delete_from_list name tree_elem))\n                       (TStree ts !!);\n           TSilist := ilist';\n           TSfree := (frees'_1, frees'_2) |} ts).\n  Proof.\n    intros.\n    eapply treeseq_safe_pushd; eauto.\n    eapply NEforall_d_in'; intros.\n    eapply NEforall_d_in in H6; eauto.\n    eapply treeseq_safe_trans; eauto.\n    unfold treeseq_safe; intuition.\n    - unfold treeseq_safe_fwd.\n      intros; simpl.\n      deex.\n      exists f; eauto.\n      intuition.\n\n      eapply find_subtree_prune_subtree_oob in H9; eauto.\n\n      unfold BFILE.block_belong_to_file in *.\n      rewrite H3 in *; eauto.\n      intros; subst.\n      assert (pathname' = pathname).\n      eapply find_subtree_inode_pathname_unique; eauto.\n      congruence.\n\n      replace inum with (dirtree_inum (TreeFile inum f)) by reflexivity.\n      eapply find_subtree_inum_present; eauto.\n\n      eapply tree_inodes_in_delete_oob; eauto.\n\n    - unfold treeseq_safe_bwd.\n      intros.\n      left.\n      deex.\n      eexists f'; intuition; simpl in *.\n      eapply find_subtree_prune_subtree_oob' in H9; eauto. \n\n      unfold BFILE.block_belong_to_file in *.\n      rewrite H3 in *; eauto.\n      intros; subst.\n      assert (pathname' = pathname).\n      eapply find_subtree_inode_pathname_unique with (tree := \n        (update_subtree pathname \n                    (TreeDir dnum \n                     (delete_from_list name tree_elem)) (TStree ts !!))); eauto.\n\n      destruct (TStree ts !!).\n\n      eapply find_subtree_file_dir_exfalso in H2.\n      exfalso; eauto.\n      eapply tree_inodes_distinct_prune; eauto.\n      eapply tree_names_distinct_prune_subtree'; eauto.\n      subst.\n      erewrite find_update_subtree in H9; eauto.\n      congruence.\n\n      apply find_subtree_inum_present in H9; simpl in H9.\n      eapply In_incl; eauto.\n      eapply incl_appr'.\n      eapply incl_count_incl.\n      eapply permutation_incl_count.\n      eapply tree_inodes_after_prune'; eauto.\n\n      erewrite <- find_subtree_dirlist.\n      erewrite <- find_subtree_app with (p0 := pathname); eauto.\n      eapply dir2flatmem2_find_subtree_ptsto with (tree := TStree ts !!).\n      eauto.\n      pred_apply; cancel.\n\n      replace inum with (dirtree_inum (TreeFile inum f')) by reflexivity.\n      eapply find_subtree_inum_present; eauto.\n\n    - simpl.\n      unfold dirtree_safe in *; intuition.\n  Qed.\n\n  (* restricted to deleting files *)\n  Theorem treeseq_delete_ok : forall fsxp dnum name mscs,\n    {< ds sm ts pathname Fm Ftop Ftree tree_elem finum file,\n    PRE:hm\n      LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs) sm hm *\n      [[ treeseq_in_ds Fm Ftop fsxp sm mscs ts ds ]] *\n      [[ find_subtree pathname (TStree ts !!) = Some (TreeDir dnum tree_elem) ]] *\n      [[ (Ftree * ((pathname++[name])%list) |-> File finum file)%pred (dir2flatmem2 (TStree ts !!)) ]]\n    POST:hm' RET:^(mscs', ok)\n      [[ MSAlloc mscs' = MSAlloc mscs ]] *\n      ([[ isError ok ]] *\n       LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds) (MSLL mscs') sm hm' *\n       [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts ds ]] \\/\n       [[ ok = OK tt ]] * exists d ds' ts' tree' ilist' frees',\n        LOG.rep (FSXPLog fsxp) (SB.rep fsxp) (LOG.NoTxn ds') (MSLL mscs') sm hm' *\n        [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n        [[ forall pathname',\n           ~ pathname_prefix (pathname ++ [name]) pathname' ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n        [[ ds' = pushd d ds ]] *\n        [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm) ]]] *\n        [[ tree' = update_subtree pathname\n                      (delete_from_dir name (TreeDir dnum tree_elem)) (TStree ts !!) ]] *\n        [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n        [[ (Ftree * (pathname ++ [name]) |-> Nothing)%pred (dir2flatmem2 (TStree ts' !!)) ]])\n    XCRASH:hm'\n      LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds hm' \\/\n      exists d ds' ts' mscs' tree' ilist' frees',\n        LOG.idempred (FSXPLog fsxp) (SB.rep fsxp) ds' hm' *\n        [[ MSAlloc mscs' = MSAlloc mscs ]] *\n        [[ treeseq_in_ds Fm Ftop fsxp sm mscs' ts' ds']] *\n        [[ forall pathname',\n           ~ pathname_prefix (pathname ++ [name]) pathname' ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts !!)) ts ->\n           treeseq_pred (treeseq_safe pathname' (MSAlloc mscs) (ts' !!)) ts' ]] *\n        [[ ds' = pushd d ds ]] *\n        [[[ d ::: (Fm * rep fsxp Ftop tree' ilist' frees' mscs' sm) ]]] *\n        [[ tree' = update_subtree pathname\n                      (delete_from_dir name (TreeDir dnum tree_elem)) (TStree ts !!) ]] *\n        [[ ts' = (pushd (mk_tree tree' ilist' frees') ts) ]] *\n        [[ (Ftree * (pathname ++ [name]) |-> Nothing)%pred (dir2flatmem2 (TStree ts' !!)) ]]\n\n    >} AFS.delete fsxp dnum name mscs.\n  Proof.\n    intros.\n    eapply pimpl_ok2.\n    eapply AFS.delete_ok.\n    cancel.\n    eapply treeseq_in_ds_tree_pred_latest in H7 as Hpred; eauto.\n    eassumption.\n    step.\n    or_l. cancel.\n    eapply treeseq_in_ds_mscs'; eauto.\n    or_r. cancel.\n\n    - eapply treeseq_in_ds_pushd; eauto.\n      unfold treeseq_one_safe; simpl.\n      rewrite H in H13.\n      eassumption.\n\n    - eapply treeseq_safe_delete; eauto.\n      distinct_names'.\n      distinct_inodes'.\n      rewrite H in *.\n      eauto.\n\n    - eapply dir2flatmem2_delete_file; eauto; distinct_names'.\n\n    - xcrash_solve.\n      or_l. cancel. xform_normr. cancel.\n      or_r. cancel. repeat (progress xform_norm; safecancel).\n      eassumption.\n      3: reflexivity.\n      4: reflexivity.\n      4: reflexivity.\n      3: pred_apply; cancel.\n      clear H1. clear H2. clear H.\n\n      + eapply treeseq_in_ds_pushd; eauto.\n        unfold treeseq_one_safe; simpl.\n        rewrite <- surjective_pairing in H11.\n        rewrite H5 in *; eauto.\n\n      + eapply treeseq_safe_delete; eauto.\n        distinct_names'.\n        distinct_inodes'.\n        rewrite H5 in *; eauto.\n\n      + eapply dir2flatmem2_delete_file; eauto; distinct_names'.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (AFS.file_get_attr _ _ _) _) => apply treeseq_file_getattr_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.lookup _ _ _ _) _) => apply treeseq_lookup_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.read_fblock _ _ _ _) _) => apply treeseq_read_fblock_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.file_set_attr _ _ _ _) _) => apply treeseq_file_set_attr_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.update_fblock_d _ _ _ _ _) _) => apply treeseq_update_fblock_d_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.file_sync _ _ _ ) _) => apply treeseq_file_sync_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.file_truncate _ _ _ _) _) => apply treeseq_file_grow_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.tree_sync _ _ ) _) => apply treeseq_tree_sync_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.rename _ _ _ _ _ _ _) _) => apply treeseq_rename_ok : prog.\n  Hint Extern 1 ({{_}} Bind (AFS.delete _ _ _ _) _) => apply treeseq_delete_ok : prog.\n\nEnd TREESEQ.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/TreeSeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.19093870611543648}}
{"text": "Require Import Bool Vector List String Peano_dec Lia.\nRequire Import Common FMap HVector IndexSupport Topology Syntax Semantics StepM SemFacts.\nRequire Import RqRsTopo RqRsUtil.\n\nRequire Import Ex.SpecInds Ex.Template Ex.RuleTransform Ex.RuleTransformOk.\nRequire Import Ex.Msi.Msi Ex.Msi.MsiTopo Ex.Msi.MsiImp Ex.Msi.MsiSim.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\nSection MsiImpOk.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n  Let topo := fst (tree2Topo tr 0).\n  Let cifc := snd (tree2Topo tr 0).\n\n  Lemma msi_ImplRules: ImplRules tr (MsiImp.impl Htr) (Msi.impl Htr).\n  Proof.\n    red; intros.\n    destruct H; [subst|apply in_app_or in H; destruct H].\n\n    - (** Main memory *)\n      eexists; repeat split; [left; reflexivity|].\n      red; simpl; intros.\n      left; split; [|assumption].\n      unfold memRulesFromChildren in H.\n      apply concat_In in H; dest.\n      apply in_map_iff in H; dest; subst.\n      dest_in.\n      all: apply immDownRule_RssEquivRule; red; simpl; auto.\n\n    - (** Li cache *)\n      apply in_map_iff in H; destruct H as [oidx [? ?]]; subst; simpl in *.\n      eexists; repeat split;\n        [right; apply in_or_app; left;\n         apply in_map_iff; eexists; repeat split; eassumption\n        |reflexivity|].\n\n      red; intros.\n      apply in_app_or in H; destruct H.\n\n      + apply concat_In in H; destruct H as [crls [? ?]].\n        apply in_map_iff in H; destruct H as [cidx [? ?]]; subst.\n        pose proof (subtreeChildrenIndsOf_parentIdxOf\n                      (tree2Topo_WfDTree tr 0) _ _ H2) as Hp.\n        dest_in.\n\n        Ltac li_cidx_RssEquivRule equiv_thm cidx :=\n          left; split;\n          [apply equiv_thm; red; simpl; auto; fail\n          |apply in_or_app; left;\n           apply in_concat;\n           eexists; split;\n           [apply in_map_iff; exists cidx; split; [reflexivity|assumption]\n           |simpl; tauto]].\n\n        all: try (li_cidx_RssEquivRule immDownRule_RssEquivRule cidx).\n        all: try (li_cidx_RssEquivRule rqUpUpRule_RssEquivRule cidx).\n        all: try (li_cidx_RssEquivRule rqUpDownRule_RssEquivRule cidx).\n        all: try (right; right; right; repeat eexists; assumption).\n\n      + dest_in.\n\n        Ltac li_RssEquivRule equiv_thm :=\n          left; split;\n          [apply equiv_thm; red; simpl; auto; fail\n          |apply in_or_app; right; simpl; tauto].\n\n        all: try (li_RssEquivRule immRule_RssEquivRule).\n        all: try (li_RssEquivRule immUpRule_RssEquivRule).\n        all: try (li_RssEquivRule rqUpUpRuleS_RssEquivRule).\n        all: try (li_RssEquivRule rqDownDownRule_RssEquivRule).\n        all: try (li_RssEquivRule rsDownDownRule_RssEquivRule).\n        all: try (li_RssEquivRule rsDownDownRuleS_RssEquivRule).\n        all: try (right; left; repeat eexists;\n                  apply in_or_app; right; simpl; tauto).\n        all: try (right; right; left; repeat eexists;\n                  apply in_or_app; right; simpl; tauto).\n\n        * left; split.\n          { apply rsDownDownRule_RssEquivRule.\n            red; unfold getUpLockIdxBackI, getUpLockIdxBack; simpl; intros.\n            red in H1; dest.\n            congruence.\n          }\n          { apply in_or_app; right; simpl; tauto. }\n        * left; split.\n          { apply rsDownRqDownRule_RssEquivRule.\n            red; unfold RsDownRqDownSoundPrec, getUpLockIdxBackI, getUpLockIdxBack; simpl; intros.\n            red in H1; dest.\n            rewrite <-H1.\n            repeat split; assumption.\n          }\n          { apply in_or_app; right; simpl; tauto. }\n\n    - (** L1 cache *)\n      apply in_map_iff in H; destruct H as [oidx [? ?]]; subst.\n      eexists; repeat split;\n        [right; apply in_or_app; right;\n         apply in_map_iff; eexists; repeat split; assumption|].\n      red; intros.\n      dest_in.\n\n      Ltac l1_RssEquivRule equiv_thm :=\n        left; split;\n        [apply equiv_thm; red; simpl; auto; fail\n        |simpl; tauto].\n\n      all: try (l1_RssEquivRule immUpRule_RssEquivRule).\n      all: try (l1_RssEquivRule immDownRule_RssEquivRule).\n      all: try (l1_RssEquivRule rqUpUpRule_RssEquivRule).\n      all: try (l1_RssEquivRule rqUpUpRuleS_RssEquivRule).\n      all: try (l1_RssEquivRule rsDownDownRule_RssEquivRule).\n      all: try (l1_RssEquivRule rsDownDownRuleS_RssEquivRule).\n  Qed.\n\n  Lemma msi_imp_msi_ok:\n    (steps step_m) # (steps step_m) |-- (MsiImp.impl Htr) \u2291 (Msi.impl Htr).\n  Proof.\n    apply rss_holder_ok with (tr:= tr); try reflexivity.\n    - apply msi_ImplRules.\n    - simpl; rewrite !map_app, !map_map, !map_id.\n      rewrite app_comm_cons.\n      rewrite <-c_li_indices_head_rootOf by assumption.\n      reflexivity.\n    - apply msi_GoodRqRsSys.\n    - apply msi_GoodExtRssSys.\n  Qed.\n\n  Local Definition spec :=\n    @SpecInds.spec (c_l1_indices cifc) (tree2Topo_l1_NoPrefix tr 0).\n\n  Theorem msi_imp_ok:\n    (steps step_m) # (steps step_m) |-- (MsiImp.impl Htr) \u2291 spec.\n  Proof.\n    eapply refines_trans.\n    - apply msi_imp_msi_ok.\n    - apply MsiSim.msi_ok.\n  Qed.\n\nEnd MsiImpOk.\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/Msi/MsiImpOk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.19089760431881414}}
{"text": "Require Import extraction.\nRequire Import syntax lang Integers.\nOpen Scope hdl_type_scope.\nOpen Scope hdl_exp_scope.\nOpen Scope hdl_stmt_scope.\n\nDefinition m : interp_ty (tarr 16<<<tvec32>>>).\n  refine (arr_init _ _).\n  apply (Int.repr 0).\n  intros.\n  inversion H.\n  apply (Int.repr (Z_of_nat' n)).\n  apply (Int.repr (Z_of_nat' n)).\n  Defined.\n\nDefinition loop : prog.\n  (* refine (@ADecl Output 64 TVec32 \"w\" _ ). *)\n  refine (@ADecl Input 16 TVec32 \"m\" _).\n  refine (Output vec \"x\" ::== Int.repr 0;;; _).\n  refine (syntax.iter 0 16 (fun i => _ )).\n  refine (SAssign Blocking \"x\" _ ).\n  refine ((EBinop OAdd (EVar \"x\") _)).\n  refine (EDeref _ _).\n  exact i.\n  apply (\"m\").\nDefined.\n\nDefinition loop_print_tb : verilog :=\n  pretty_print_tb_results \"looper\" \"380\" loop.\n(* Definition loop_print : verilog :=  *)\n(*   pretty_print \"looper\" loop. *)\n\nExtract Constant main => \"Prelude.putStrLn loop_print_tb\".\n\nExtraction \"looper.hs\" loop_print_tb main.\n", "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/tests/makeLooper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35936413829896485, "lm_q1q2_score": 0.19089759871879297}}
{"text": "From iris.algebra Require Import excl auth gmap agree gset.\nFrom iris.heap_lang Require Export lifting notation locations lang.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.program_logic Require Export atomic.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode notation par.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.bi Require Import derived_laws_sbi.\nSet Default Proof Using \"Type*\".\n\nDefinition lockNode : val :=\n  rec: \"lockN\" \"y\" :=\n    if: CAS \"y\" #false #true\n    then #()\n    else \"lockN\" \"y\".\n\nDefinition unlockNode : val :=\n  \u03bb: \"y\",\n  \"y\" <- #false.\n\nDefinition prog : val :=\n  \u03bb: \"x\" \"y\" \"v\",\n  lockNode \"y\";;\n  \"x\" <- \"v\";;\n  unlockNode \"y\";; \"v\".\n\nSection Toy_Template.\n  Context `{!heapG \u03a3} (N : namespace).\n  Notation iProp := (iProp \u03a3).\n\n  (* We should be able to prove the following specs: *)\n\n  Lemma lock_spec (y: loc) :\n    <<< \u2200 (b: bool), y \u21a6 #b >>>\n        lockNode #y @ \u22a4\n    <<< y \u21a6 #true \u2217 if b then False else True, RET #() >>>.\n  Proof.\n    iIntros (\u03a6) \"HP\". iL\u00f6b as \"IH\".\n    rewrite /lockNode.\n    wp_pures.\n    wp_apply (aacc_aupd_commit with \"IH\"). first done.\n    awp_apply \"IH\".\n    awp_apply \"HP\".\n    iPoseProof (aupd_aacc with \"HP\") as \"AC\".\n    wp_cmpxchg as H1 | H2.\n    wp_cmpxchg.\n    wp_apply . *)\n  Admitted.\n\n  Lemma unlock_spec (y: loc) :\n    <<< y \u21a6 #true >>>\n        unlockNode #y @ \u22a4\n    <<< y \u21a6 #false, RET #() >>>.\n  Proof. Admitted.\n\n  Definition is_locked_ref x y v : iProp :=\n    (\u2203 (b: bool), y \u21a6 #b \u2217 if b then True else x \u21a6 v)%I.\n\n  Lemma prog_spec (x y: loc) (v: val) :\n    <<< \u2200 (u: val), is_locked_ref x y u >>>\n        prog #x #y v @ \u22a4\n    <<< is_locked_ref x y v, RET #() >>>.\n  Proof.\n    unfold is_locked_ref.\n    iIntros (\u03a6) \"HP\". iL\u00f6b as \"IH\".\n    wp_lam. wp_pures. wp_bind (lockNode _)%E.\n    wp_apply lock_spec.\n    About atomic_update.\n    SearchAbout atomic_update. (AU << _ >> @ _, _ << _ COMM >>).\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/toy2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.19089759507409276}}
{"text": "(** Refinement rules for disjoint rules *)\nRequire Import Coq.omega.Omega.\nRequire Import Fiat.Parsers.Refinement.PreTactics.\nRequire Import Fiat.Computation.Refinements.General.\nRequire Import Fiat.Parsers.StringLike.LastCharSuchThat.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.Refinement.DisjointLemmas.\nRequire Import Fiat.Parsers.Refinement.DisjointRulesCommon.\nRequire Import Fiat.Parsers.Refinement.PossibleTerminalsSets.\nRequire Import Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Common.List.DisjointFacts.\nExport DisjointLemmas.Exports.\n\nSet Implicit Arguments.\n\nLocal Arguments minus !_ !_.\n\nLemma find_after_last_char_such_that'_short {Char HSLM HSL}\n      str P len\n  : @find_after_last_char_such_that' Char HSLM HSL P len str <= len.\nProof.\n  revert str; induction len; simpl; intros; [ omega | ].\n  destruct (get len str) eqn:H.\n  { edestruct P; try omega.\n    rewrite IHlen; omega. }\n  { rewrite IHlen; omega. }\nQed.\n\nLemma find_after_last_char_such_that_short {Char HSLM HSL}\n      str P\n  : @find_after_last_char_such_that Char HSLM HSL str P <= length str.\nProof.\n  apply find_after_last_char_such_that'_short.\nQed.\n\nLemma refine_find_after_last_char_such_that {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n      (str : String)\n      (P : Char -> bool)\n  : refine { n : nat | n <= length str\n                       /\\ ((exists n', is_after_last_char_such_that str n' P)\n                           -> is_after_last_char_such_that str n P) }\n           (ret (find_after_last_char_such_that str P)).\nProof.\n  intros v H.\n  computes_to_inv; subst.\n  apply PickComputes.\n  split; [ apply find_after_last_char_such_that_short | ].\n  apply is_after_last_char_such_that__find_after_last_char_such_that.\nQed.\n\nSection with_grammar.\n  Context {HSLM : StringLikeMin Ascii.ascii}\n          {HSL : StringLike Ascii.ascii}\n          {HSI : StringIso Ascii.ascii}\n          {HSLP : StringLikeProperties Ascii.ascii}\n          {HSIP : StringIsoProperties Ascii.ascii}\n          {G : pregrammar' Ascii.ascii}\n          (pdata : possible_data G).\n\n  Local Notation possible_terminals_of nt\n    := (@all_possible_ascii_of_nt G pdata nt).\n  Local Notation possible_terminals_of_production its\n    := (@all_possible_ascii_of_production G pdata its).\n  Local Notation possible_first_terminals_of_production its\n    := (@possible_first_ascii_of_production G pdata its).\n  Local Notation possible_last_terminals_of nt\n    := (@possible_last_ascii_of_nt G pdata nt).\n\n  Definition rev_search_for_condition\n             str nt (n : nat)\n    := is_after_last_char_such_that\n         str\n         n\n         (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt)).\n\n  Lemma refine_disjoint_rev_search_for'\n        {str offset len nt its}\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete\n                 G str offset len\n                 (NonTerminal nt::its) splits}\n             (n <- { n : nat | n <= length (substring offset len str)\n                               /\\ ((exists n', rev_search_for_condition (substring offset len str) nt n')\n                                   -> rev_search_for_condition (substring offset len str) nt n) };\n                ret [n]).\n  Proof.\n    intros ls H.\n    computes_to_inv; subst.\n    destruct H as [H0 H1].\n    apply PickComputes.\n    hnf; cbv zeta.\n    intros Hlen it' its' Heq n ? H_reachable pit pits.\n    inversion Heq; subst it' its'; clear Heq.\n    left.\n    pose proof (terminals_disjoint_rev_search_for _ _ H_disjoint pit pits H_reachable) as H'.\n    specialize (H1 (ex_intro _ n H')).\n    unfold rev_search_for_condition in H1.\n    pose proof (is_after_last_char_such_that_eq_nat_iff H1 H') as H''.\n    destruct_head or; destruct_head and; subst;\n      rewrite ?Min.min_r, ?Min.min_l by assumption;\n      omega.\n  Qed.\n\n  Definition rev_search_for_not_condition\n             str its n\n    := is_after_last_char_such_that\n         str\n         n\n         (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its))).\n\n  Lemma refine_disjoint_rev_search_for_not'\n        {str offset len nt its}\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete\n                 G str offset len\n                 (NonTerminal nt::its)\n                 splits}\n             (n <- { n : nat | n <= length (substring offset len str)\n                               /\\ ((exists n', rev_search_for_not_condition (substring offset len str) its n')\n                                   -> rev_search_for_not_condition (substring offset len str) its n) };\n                ret [n]).\n  Proof.\n    intros ls H.\n    computes_to_inv; subst.\n    destruct H as [H0 H1].\n    apply PickComputes.\n    hnf; cbv zeta.\n    intros Hlen it' its' Heq n ? H_reachable pit pits.\n    inversion Heq; subst it' its'; clear Heq.\n    left.\n    pose proof (terminals_disjoint_rev_search_for_not _ _ H_disjoint pit pits H_reachable) as H'.\n    specialize (H1 (ex_intro _ n H')).\n    pose proof (is_after_last_char_such_that_eq_nat_iff H1 H') as H''.\n    destruct_head or; destruct_head and; subst;\n      rewrite ?Min.min_r by assumption;\n      omega.\n  Qed.\n\n  Lemma refine_disjoint_rev_search_for\n        {str offset len nt its}\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete\n                 G str offset len\n                 (NonTerminal nt::its)\n                 splits}\n             (ret [find_after_last_char_such_that (substring offset len str) (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt))]).\n  Proof.\n    rewrite refine_disjoint_rev_search_for' by assumption.\n    setoid_rewrite refine_find_after_last_char_such_that.\n    simplify with monad laws; reflexivity.\n  Qed.\n\n  Lemma refine_disjoint_rev_search_for_not\n        {str offset len nt its}\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete\n                 G str offset len\n                 (NonTerminal nt::its)\n                 splits}\n             (ret [find_after_last_char_such_that (substring offset len str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its)))]).\n  Proof.\n    rewrite refine_disjoint_rev_search_for_not' by assumption.\n    setoid_rewrite refine_find_after_last_char_such_that.\n    simplify with monad laws; reflexivity.\n  Qed.\n\n  Lemma refine_disjoint_rev_search_for_idx\n        {str offset len nt its idx}\n        (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete_idx\n                 G str offset len\n                 idx\n                 splits}\n             (ret [find_after_last_char_such_that (substring offset len str) (fun ch => list_bin ascii_beq ch (possible_last_terminals_of nt))]).\n  Proof.\n    unfold split_list_is_complete_idx.\n    erewrite <- refine_disjoint_rev_search_for by eassumption.\n    rewrite Heq.\n    apply refine_pick_pick; intro; trivial.\n  Qed.\n\n  Lemma refine_disjoint_rev_search_for_not_idx\n        {str offset len nt its idx}\n        (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n        (H_disjoint : disjoint ascii_beq\n                               (possible_last_terminals_of nt)\n                               (possible_terminals_of_production its))\n    : refine {splits : list nat\n             | split_list_is_complete_idx\n                 G str offset len\n                 idx\n                 splits}\n             (ret [find_after_last_char_such_that (substring offset len str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of_production its)))]).\n  Proof.\n    unfold split_list_is_complete_idx.\n    erewrite <- refine_disjoint_rev_search_for_not by eassumption.\n    rewrite Heq.\n    apply refine_pick_pick; intro; trivial.\n  Qed.\nEnd with_grammar.\n\nLtac solve_disjoint_side_conditions :=\n  idtac;\n  lazymatch goal with\n  | [ |- Carriers.default_to_production (G := ?G) ?k = ?e ]\n    => cbv -[Equality.ascii_beq orb andb BinNat.N.leb Reflective.opt.N_of_ascii];\n       try reflexivity\n  | [ |- is_true (Operations.List.disjoint _ _ _) ]\n    => vm_compute; try reflexivity\n  end.\n\nLtac pose_disjoint_rev_search_for lem :=\n  idtac;\n  lazymatch goal with\n  | [ HSLP : @StringLikeProperties _ ?HSLM ?HSL, pdata : possible_data ?G\n      |- context[@ParserInterface.split_list_is_complete_idx ?Char ?G ?HSLM ?HSL ?str ?offset ?len ?idx] ]\n    => pose proof (fun idx' nt its => @refine_disjoint_rev_search_for_idx HSLM HSL HSLP G pdata str offset len nt its idx') as lem\n  end.\nLtac replace_with_native_compute_in c H :=\n  let c' := (eval native_compute in c) in\n  (* By constrast [set ... in ...] seems faster than [change .. with ... in ...] in 8.4?! *)\n  replace c with c' in H by (clear; native_cast_no_check (eq_refl c')).\n\nLtac rewrite_once_disjoint_rev_search_for_specialize alt_side_condition_tac lem lem' :=\n  idtac;\n  let G := (lazymatch goal with\n             | [ |- context[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n               => G\n             end) in\n  match goal with\n  | [ |- context[ParserInterface.split_list_is_complete_idx G ?str ?offset ?len ?idx] ]\n    => pose proof (lem idx) as lem';\n       do 2 (lazymatch type of lem' with\n              | forall a : ?T, _ => idtac; let x := fresh in evar (x : T); specialize (lem' x); subst x\n              end);\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve [ solve_disjoint_side_conditions | alt_side_condition_tac () ];\n       specialize (lem' H'); clear H';\n       cbv beta delta [id\n                         all_possible_ascii_of_nt all_possible_ascii_of_production\n                         possible_first_ascii_of_nt possible_first_ascii_of_production\n                         possible_last_ascii_of_nt possible_last_ascii_of_production] in lem';\n       do 2 (let x := match type of lem' with\n                      | context[characters_set_to_ascii_list ?ls]\n                        => constr:(characters_set_to_ascii_list ls)\n                      end in\n             replace_with_vm_compute_in x lem');\n       unfold Equality.list_bin in lem';\n       change (orb false) with (fun bv : bool => bv) in lem';\n       cbv beta in lem';\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve [ solve_disjoint_side_conditions | alt_side_condition_tac () ];\n       specialize (lem' H'); clear H'\n  end.\nLtac rewrite_once_disjoint_rev_search_for alt_side_condition_tac lem :=\n  let lem' := fresh \"lem'\" in\n  rewrite_once_disjoint_rev_search_for_specialize alt_side_condition_tac lem lem';\n  setoid_rewrite lem'; clear lem'.\nLtac rewrite_disjoint_rev_search_for_no_clear alt_side_condition_tac lem :=\n  pose_disjoint_rev_search_for lem;\n  progress repeat rewrite_once_disjoint_rev_search_for alt_side_condition_tac lem.\nLtac rewrite_disjoint_rev_search_for_with_alt alt_side_condition_tac :=\n  idtac;\n  let lem := fresh \"lem\" in\n  rewrite_disjoint_rev_search_for_no_clear alt_side_condition_tac lem;\n  clear lem.\nLtac leave_side_conditions _ :=\n  try rewrite disjoint_uniquize by auto using Equality.ascii_bl, Equality.ascii_lb;\n  shelve.\nLtac rewrite_disjoint_rev_search_for_leaving_side_conditions :=\n  unshelve rewrite_disjoint_rev_search_for_with_alt leave_side_conditions.\nLtac rewrite_disjoint_rev_search_for :=\n  rewrite_disjoint_rev_search_for_with_alt ltac:(fun _ => fail).\nLtac refine_disjoint_rev_search_for_with_alt alt_side_condition_tac :=\n  idtac;\n  let lem := fresh \"lem\" in\n  pose_disjoint_rev_search_for lem;\n  let lem' := fresh \"lem'\" in\n  rewrite_once_disjoint_rev_search_for_specialize alt_side_condition_tac lem lem';\n  refine lem'; clear lem'.\nLtac refine_disjoint_rev_search_for_leaving_side_conditions :=\n  unshelve refine_disjoint_rev_search_for_with_alt leave_side_conditions.\nLtac refine_disjoint_rev_search_for :=\n  refine_disjoint_rev_search_for_with_alt ltac:(fun _ => fail).\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/DisjointRulesRev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.19083695412020948}}
{"text": "From SFS Require Import cps cps_util set_util identifiers ctx Ensembles_util\n     List_util functions tactics map_util.\n\nFrom SFS Require Import heap heap_defs heap_equiv space_sem\n     cc_log_rel closure_conversion closure_conversion_util bounds GC.\n\nFrom Coq Require Import ZArith.Znumtheory Relations.Relations Arith.Wf_nat\n                        Lists.List MSets.MSets MSets.MSetRBT Numbers.BinNums\n                        NArith.BinNat PArith.BinPos Sets.Ensembles Omega Permutation.\n\nImport ListNotations.\n\nOpen Scope ctx_scope.\nOpen Scope fun_scope.\nClose Scope Z_scope.\n\n\nModule Invariants (H : Heap).\n\n  Module Size := Size H.\n\n  Import H Size.Util.C.LR.Sem.GC.Equiv Size.Util.C.LR.Sem.GC.Equiv.Defs\n         Size.Util.C.LR.Sem.GC Size.Util.C.LR.Sem Size.Util.C.LR Size.Util.C\n         Size.Util Size.\n\n  (** Invariant about the free variables *) \n  Definition FV_inv (k j : nat) (IP : GIInv) (P : GInv) (b : Inj)\n             (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n             (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) : Prop :=\n    well_formed (reach' H2 (env_locs rho2 [set \u0393])) H2 /\\ (* True when the environment is created *)\n    key_set rho1 <--> FV Scope Funs FVs /\\ \n    exists (vs : list value) (l : loc),\n      M.get \u0393 rho2 = Some (Loc l) /\\\n      get l H2 = Some (Constr c vs) /\\\n      Forall2_P (Scope :|: Funs)\n                (fun (x : var) (v2 : value)  =>\n                   exists v1, M.get x rho1 = Some v1 /\\\n                         Res (v1, H1) \u227a ^ ( k ; j ; IP ; P ; b) Res (v2, H2)) FVs vs.\n\n  (** Invariant about the functions currently in scope not yet packed as closures *)\n  Definition Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs :=\n    forall f, ~ f \\in Scope -> f \\in Funs ->\n         exists l1 lenv1 lenv2 B1 g1 B2 g2,\n           M.get f rho1 = Some (Loc l1) /\\\n\n           (* Funs locations are fresh, and there are no references to them  *)\n           ~ l1 \\in (reach' H1 ((env_locs rho1 (FV Scope Funs FVs \\\\ [set f])) :|: post H1 [set l1])) /\\\n\n           M.get f rho2 = Some (FunPtr B2 g2) /\\\n           get l1 H1 = Some (Clos (FunPtr B1 g1) (Loc lenv1)) /\\\n\n           M.get (fenv f) rho2 = Some (Loc lenv2) /\\\n\n           (* Environments are related (before allocation) *)\n           (lenv1, H1) << ^ (k; j; GI; GP; b) (lenv2, H2) /\\\n\n           (* We can alloc a related function *)\n           let '(l2, H2') := alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc lenv2]) H2 in\n           Res (Loc l1, H1) \u227a ^ (k; j; GI; GP; b{l1 ~> l2}) Res (Loc l2, H2'). \n\n  (** Version without the logical relation. Useful when we're only interested in other invariants. *)\n  \n  (** Invariant about the free variables *) \n  Definition FV_inv_weak (rho1 : env) (rho2 : env) (H2 : heap block)\n             (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) : Prop :=\n    exists (vs : list value) (l : loc),\n      M.get \u0393 rho2 = Some (Loc l) /\\\n      get l H2 = Some (Constr c vs) /\\\n      Forall2_P (Scope :|: Funs)\n                (fun (x : var) (v2 : value)  =>\n                   exists v1, M.get x rho1 = Some v1) FVs vs.\n  \n  Definition Fun_inv_weak rho1 rho2 Scope Funs fenv :=\n    forall f, ~ f \\in Scope -> f \\in Funs ->\n         exists l1 lenv B g,\n           M.get f rho1 = Some (Loc l1) /\\\n           M.get f rho2 = Some (FunPtr B g) /\\\n           M.get (fenv f) rho2 = Some (Loc lenv). \n  \n  (** * Lemmas about [FV_inv] *)  \n\n  Lemma Forall2_P_Forall2 {A B : Type} S P (ls1 : list A) (ls2 : list B) :  \n    Forall2_P S P ls1 ls2 ->\n    Disjoint A S (FromList ls1) ->\n    Forall2 P ls1 ls2.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hall Hd. induction Hall.\n    - now constructor.\n    - constructor.\n      + eapply H. intros Hc. eapply Hd. constructor; eauto.\n        now left.\n      + eapply IHHall.\n        eapply Disjoint_Included_r; eauto.\n        normalize_sets...\n  Qed. \n\n  Lemma key_set_get S `{_ : ToMSet S} x rho :\n    x \\in S ->\n    M.get x rho = M.get x (restrict_env (@mset S _) rho).\n  Proof.\n    intros Hin.\n    assert (Hset : Restrict_env S rho (restrict_env (@mset S _) rho)). \n    { eapply restrict_env_correct. eapply H. }\n    destruct Hset as [Hin' [Hs1 Hs2]].  \n    eapply Hin'. eassumption. \n  Qed.\n\n  Lemma key_set_binding_in_map S `{_ : ToMSet S} (rho : env) :\n    binding_in_map S rho ->\n    key_set (restrict_env (@mset S _) rho) <--> S.\n  Proof. \n    intros Hbin.\n    split.\n    eapply key_set_Restrict_env. eapply restrict_env_correct. \n    now eapply H.\n\n    intros x Hin. edestruct Hbin as [v Hget]. eassumption.\n    unfold In, key_set. rewrite <- key_set_get; [| eassumption ].\n    now rewrite Hget.\n  Qed. \n\n  Lemma FV_inv_cc_approx_clos  (k j : nat) (IP : GIInv) (P : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (\u0393 : var) (FVs : list var) l1 l2 : \n    FV_inv k j IP P b rho1 H1 rho2 H2 c (Empty_set _) (Empty_set _) \u0393 FVs ->\n    binding_in_map (FromList FVs) rho1 ->\n\n    NoDup FVs ->\n\n    get l1 H1 = Some (Env rho1) ->\n    M.get \u0393 rho2 = Some (Loc l2) ->\n\n    l2 = b l1 ->\n    \n    (l1, H1) << ^ (k; j; IP; P; b) (l2, H2).\n  Proof with (now eauto with Ensembles_DB).\n    intros (Hwf & Hkey & vs & l' & Hget1 & Hget2 & Hall) Hbin Hnd Hget1' Hget2' Hbeq.\n    subst_exp.\n    clear Hget1. split. reflexivity.\n    do 4 eexists.\n    split; [| split; [| split; [| split ]]]; try eassumption.\n    - rewrite Hkey. unfold FV.\n      rewrite !Union_Empty_set_neut_l.\n      rewrite !Setminus_Empty_set_neut_r. \n      rewrite !Union_Empty_set_neut_l.\n      reflexivity. \n    - eapply Forall2_monotonic_strong; [| eapply Forall2_P_Forall2; try eassumption ].\n      intros x1 x2 Hin1 Hin2 [[l1' |] [Hget1 Hcc1]]; try contradiction. \n      eexists; split; eauto.\n      rewrite cc_approx_val_eq. eassumption.\n\n      now eauto with Ensembles_DB. \n  Qed.\n  \n  Lemma FV_inv_j_monotonic (k j' j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    j' <= j ->\n    FV_inv k j' GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs.\n  Proof.\n    intros Hfv Hlt. \n    destruct Hfv as (Hwf & Hkey & v & vs & Hget1 & Hget2 & Hall).\n    split. eassumption. \n    split. eassumption. \n    \n    repeat eexists; eauto.\n    eapply Forall2_P_monotonic_strong; [| eassumption ].\n    intros x1 x2 Hin1 Hin3 Hnp [v' [Hget Hres]]; eauto.\n    eexists; split; eauto.\n    eapply cc_approx_val_j_monotonic; eauto.\n  Qed.\n  \n  Lemma FV_inv_monotonic (k k' j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    k' <= k ->\n    FV_inv k' j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs.\n  Proof.\n    intros Hfv Hlt. \n    destruct Hfv as (Hwf & Hkey & v & vs & Hget1 & Hget2 & Hall).\n    split. eassumption.\n    split. eassumption.\n\n    repeat eexists; eauto.\n    eapply Forall2_P_monotonic_strong; [| eassumption ].\n    intros x1 x2 Hin1 Hin3 Hnp [v' [Hget Hres]]; eauto.\n    eexists; split; eauto.\n    eapply cc_approx_val_monotonic; eauto.\n  Qed.\n      \n  Lemma FV_inv_weak_in_FV_inv k j P1 P2 rho1 H1 rho2 H2 \u03b2 c Scope Funs \u0393 FVs :\n    FV_inv k j P1 P2 \u03b2 rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    FV_inv_weak rho1 rho2 H2 c Scope Funs  \u0393 FVs.\n  Proof.\n    intros (Hwf & Hkey & x1 & x2  & Hget1 & Hget2 & Hall).\n    repeat eexists; eauto.\n    eapply Forall2_P_monotonic_strong; [| eassumption ].\n    intros ? ? ? ? ? [? [? ? ]]. eexists; eauto.\n  Qed.\n\n  Lemma Fun_inv_weak_in_Fun_inv k j P1 P2 rho1 H1 rho2 H2 \u03b2\n        Scope Funs fenv FVs :\n    Fun_inv k j P1 P2 \u03b2 rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    Fun_inv_weak rho1 rho2 Scope Funs fenv.\n  Proof.\n    intros Hfun x Hin Hnin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq); try eassumption.\n    repeat eexists; eauto.\n  Qed.\n\n  Lemma FV_inv_dom1 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope Funs \u0393 FVs :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    env_locs rho1 (FromList FVs \\\\ (Scope :|: Funs)) \\subset dom H1.\n  Proof.\n    intros Hres l [x1 [Hgetx1 Heq1]].\n    destruct (M.get x1 rho1) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres 0) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    edestruct (@Forall2_P_exists loc) with (x := x1) as [v2 [Hin'' Hv]]; try eassumption.\n    \n    now eapply Hgetx1.\n    now eapply Hgetx1.\n\n    destruct Hv as [v1' [Hgety' Hv']]. repeat subst_exp.\n\n    eapply cc_approx_val_dom1. eassumption. reflexivity.\n  Qed.\n\n  Lemma FV_inv_dom2 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope Funs \u0393 FVs :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    env_locs rho2 [set \u0393] \\subset dom H2.\n  Proof.\n    intros Hres l [x2 [Hgetx2 Heq1]].\n    destruct (M.get x2 rho2) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    inv Hgetx2.\n    edestruct (Hres 0) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    repeat subst_exp. eexists; eauto.\n  Qed.\n\n  Lemma FV_inv_reach1 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope Funs \u0393 FVs :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    well_formed (reach' H1 (env_locs rho1 (FromList FVs \\\\ (Scope :|: Funs)))) H1.\n  Proof.\n    intros Hres l1 b1 [n [_ Hp]].\n    edestruct post_n_exists_Singleton as [lr [Hin Hp']].\n    eassumption.\n    destruct Hin as [x1 [Hin1 Heq1]].\n    \n    destruct (M.get x1 rho1) as [ [|] | ] eqn:Hgety; try inv Heq1.\n\n    edestruct (Hres (1 + n)) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    edestruct (@Forall2_P_exists loc) with (x := x1) as [v2 [Hin Hv]]; try eassumption.\n    now eapply Hin1.\n    now eapply Hin1.    \n    destruct Hv as [v1' [Hgety' Hv1]]. repeat subst_exp.\n    eapply cc_approx_val_post_n_cc with (v1 := Loc lr) (j := 1) in Hp';\n      [| eapply cc_approx_val_j_monotonic; try eassumption; omega ].\n    intros Hget.\n    inv Hp'. \n    \n    eapply cc_approx_val_well_formed_post1 with (v1 := Loc l1) (j := 0).\n    eassumption. reflexivity. eassumption.\n\n    eapply Included_trans; [| eapply cc_approx_clos_post_dom1 ]; try eassumption.\n    rewrite post_Singleton; try eassumption. reflexivity. \n  Qed.\n   \n  Lemma FV_inv_reach2 k j P1 P2 rho1 H1 rho2 H2 b c\n        \u0393 FVs :\n    FV_inv k j P1 P2 b rho1 H1 rho2 H2 c (Empty_set _) (Empty_set _) \u0393 FVs ->\n    well_formed (reach' H2 (env_locs rho2 [set \u0393])) H2.\n  Proof.\n    intros (Henv & _). eassumption.\n  Qed.\n  \n\n  Lemma FV_inv_image_reach k P1 P2 rho1 H1 rho2 H2 b c\n        Scope Funs \u0393 FVs :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    image b (reach' H1 (env_locs rho1 (FromList FVs \\\\ (Scope :|: Funs)))) \\subset\n    reach' H2 (post H2 (env_locs rho2 [set \u0393])).\n  Proof.\n    intros Hres l' [l [Hin Heq]]; subst.\n    destruct Hin as [n [_ Hp]].\n    edestruct post_n_exists_Singleton as [l1 [Hin Hp']]; try eassumption.\n\n    edestruct (Hres n) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    \n    rewrite env_locs_Singleton; eauto.\n    simpl. rewrite post_Singleton; eauto. simpl. subst.\n\n    destruct Hin as [y [Hin' Hall']].\n    destruct (M.get y rho1) as [ [|] | ] eqn:Hgety; try inv Hall'. \n    \n    inv Hin'.\n    edestruct (@Forall2_P_exists loc) with (x := y) as [v2 [Hin'' Hv]]; try eassumption.\n    \n    destruct Hv as [v1' [Hgety' Hv]]. repeat subst_exp.\n    edestruct v2 as [ l2' |]; try contradiction.\n    \n    eapply reach'_set_monotonic. \n    eapply In_Union_list. eapply in_map. eassumption. \n    eapply cc_approx_val_image_eq with (v1 := Loc l1); try eassumption;\n    [| eexists; split; eauto; eexists; split; eauto; now constructor ].\n\n    intros j.\n\n    edestruct (Hres j) as (vs1' & loc_env' & Hget1' & Hget2' & Hall').\n    repeat subst_exp.\n\n    edestruct (@Forall2_P_exists loc) with (x := y) as [v2' [Hin2' Hv']];\n      [| | now apply Hall' |]; try eassumption.\n    \n    destruct Hv' as [v1' [Hgety' Hv']]. repeat subst_exp.\n\n    assert (Heq1 : v2' = Loc (b l1)).\n    { destruct v2'; try contradiction.\n      destruct Hv' as [Heqv _]. subst. reflexivity. }\n\n    assert (Heq2 : l2' = b l1).\n    { destruct Hv as [Heqv _]. subst. reflexivity. }\n    subst. repeat subst_exp. eassumption.\n  Qed.\n\n  Lemma FV_inv_image_reach_eq k P1 P2 rho1 H1 rho2 H2 b c\n         \u0393 FVs :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c (Empty_set _) (Empty_set _) \u0393 FVs) ->\n    image b (reach' H1 (env_locs rho1 (FromList FVs))) <-->\n    reach' H2 (post H2 (env_locs rho2 [set \u0393])).\n  Proof with (now eauto with Ensembles_DB).\n    intros Hres. \n    edestruct (Hres 0) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    rewrite env_locs_Singleton; eauto. simpl. rewrite post_Singleton; eauto.\n    simpl. \n    \n    eapply Forall2_P_Forall2 in Hall.\n    assert (Hallj : forall j, Forall2\n                           (fun (x : var) (v2 : value) =>\n                              exists v1 : value,\n                                M.get x rho1 = Some v1 /\\\n                                Res (v1, H1) \u227a ^ (k; j; P1; P2; b) Res (v2, H2)) FVs vs1).\n    { intros j'.\n      edestruct (Hres j') as (Hwf' & Hkey' & vs1' & loc_env' & Hget1' & Hget2' & Hall').\n      repeat subst_exp. eapply Forall2_P_Forall2. eassumption.\n      now eauto with Ensembles_DB. } \n    eapply Forall2_forall in Hallj.\n    clear Hget1 Hget2 Hall Hres Hkey. induction Hallj.\n    - normalize_sets. rewrite !env_locs_Empty_set, !reach'_Empty_set, image_Empty_set...\n    - simpl. normalize_sets. rewrite !env_locs_Union, !reach'_Union, !image_Union.\n      eapply Same_set_Union_compat.\n      destruct (H 0) as [v1 [Hgetx _]]. \n      rewrite env_locs_Singleton; eauto.\n      eapply cc_approx_val_image_eq. \n      intros j. \n      destruct (H j) as [v1' [Hgetx' Hij]]. repeat subst_exp. eassumption.\n\n      eassumption. \n    - tci.\n    - now eauto with Ensembles_DB.\n  Qed.\n\n  Lemma FV_inv_heap_equiv k Scope Funs P1 P2 rho1 H1 rho2 H2 b c\n        \u0393 FVs j :\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    reach' H1 (env_locs rho1 (FromList FVs \\\\ (Scope :|: Funs))) |- H1 \u227c ^ (k; j; P1; P2; b) H2.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hres. \n    edestruct (Hres 0) as (Hwf & Hkey & vs1 & loc_env & Hget1 & Hget2 & Hall).\n    intros l [m [_ Hp]].\n    edestruct post_n_exists_Singleton as [l' [Hpl Hrl]]; try eassumption.\n    edestruct Hpl as [x1 [Hgetx2 Hinx]].\n    destruct (M.get x1 rho1) as [[ l1 | ] | ] eqn:Hgetx1; try contradiction.\n    inv Hinx.\n\n    edestruct (Hres (m + j)) as (Hwf'' & Hkey'' & vs1'' & loc_env'' & Hget1'' & Hget2'' & Hall'').\n    repeat subst_exp.\n\n    inv Hgetx2.\n    eapply Forall2_P_exists in Hall''; try eassumption.\n\n    edestruct Hall'' as [y1 [Hnin [v1 [Hgetv1 Hcc1]]]].\n    repeat subst_exp. \n    \n    eapply cc_approx_val_post_n_cc; eassumption.\n  Qed.\n\n  \n  (* TODO move *)\n  Lemma FV_Union1_eq Scope Funs FVs S {_ : Decidable S}:\n    FV (S :|: Scope) Funs FVs <-->\n    S :|: FV Scope Funs FVs.\n  Proof.   \n    unfold FV. rewrite <- !Union_assoc.\n    rewrite (Union_commut S Scope).\n    rewrite (Union_commut S (Scope :|: Funs)).\n    do 2 rewrite <- Setminus_Union.\n    rewrite !Union_assoc.\n    rewrite (Union_Setminus_Included _ _ S); tci.\n    rewrite (Union_Setminus_Included _ _ S); tci.\n    reflexivity. \n    now eauto with Ensembles_DB.\n    now eauto with Ensembles_DB.\n  Qed.\n\n  Lemma key_set_set {A} x (v : A) rho :\n    key_set (M.set x v rho) <--> x |: key_set rho.\n  Proof.\n    split; intros y; unfold In, key_set; destruct (Coqlib.peq x y); subst;\n    try rewrite !M.gss; eauto.\n    - intros _. now left.\n    - rewrite !M.gso; eauto. intros H.\n      right. eassumption.\n    - rewrite !M.gso; eauto. intros H.\n      inv H. inv H0. now exfalso; eauto. eassumption.\n  Qed.\n\n\n  Lemma FV_inv_set_not_in_FVs_l (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) x v  :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    FV_inv k j GII GI b (M.set x v rho1) H1 rho2 H2 c (x |: Scope) Funs \u0393 FVs.\n  Proof.\n    intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall).\n    split; eauto. split; eauto.\n    rewrite key_set_set, FV_Union1_eq, Hkey. reflexivity. \n    now tci. \n\n    repeat eexists; eauto.\n    \n    eapply Forall2_P_monotonic_strong; [| eapply Forall2_P_monotonic;\n                                          [ eassumption |] ].\n    intros y1 v2 Hin Hnin Hp [v1 [Hget Hall1]].\n    eexists; split; eauto.\n    rewrite M.gso; eauto.\n    intros Hc; subst. eapply Hp; eauto. now left; left.\n    now eauto with Ensembles_DB. \n  Qed.\n  \n  Lemma FV_inv_set_not_in_FVs_r (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) x v  :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    x <> \u0393 ->\n    FV_inv k j GII GI b rho1 H1 (M.set x v rho2) H2 c Scope Funs \u0393 FVs.\n  Proof.\n    intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall) Hnin.\n    split; eauto.\n    rewrite env_locs_set_not_In; eauto. now intros Hc; inv Hc; eauto.\n    split. eassumption. \n    rewrite M.gso; eauto.\n  Qed. \n  \n  Lemma FV_inv_set_not_in_FVs (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 : heap block) (rho2 : env) (H2 : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) x y v v'  :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    y <> \u0393 ->\n    FV_inv k j GII GI b (M.set x v rho1) H1 (M.set y v' rho2) H2 c (x |: Scope) Funs \u0393 FVs.\n  Proof.\n    intros. eapply FV_inv_set_not_in_FVs_r; eauto.\n    eapply FV_inv_set_not_in_FVs_l; eauto.\n  Qed.\n  \n\n  (** [FV_inv] is heap monotonic  *)\n  Lemma FV_inv_heap_mon (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 H1' : heap block) (rho2 : env) (H2 H2' : heap block)\n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) :\n    H1 \u2291 H1' ->\n    H2 \u2291 H2' ->\n    (forall j, FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ) ->\n    FV_inv k j GII GI b rho1 H1' rho2 H2' c Scope Funs \u0393 FVs.\n  Proof.\n    intros Hs1 Hs2.\n    intros Henv. edestruct (Henv 0) as (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall).\n    split; [| split ].\n    - rewrite <- reach'_subheap.\n      eapply well_formed_subheap.\n      eassumption.\n      eapply reachable_in_dom.\n      eassumption.\n      rewrite env_locs_Singleton; eauto. eapply Singleton_Included.\n      eexists; eassumption.\n      eassumption. eassumption.\n      rewrite env_locs_Singleton; eauto. eapply Singleton_Included.\n      eexists; eassumption.\n      eassumption.\n    - eassumption.\n    - repeat eexists; eauto.\n      eapply Forall2_P_monotonic_strong; [| eassumption ].\n      intros y1 v2 Hin1 Hin2 Hp [v1 [Hget3 Hrel]].\n      eexists; split; eauto. \n      eapply cc_approx_val_heap_monotonic; try eassumption.\n      intros j'. \n      edestruct (Henv j') as (Hwf' & Hkey' & x1' & x2' & Hget1' & Hget2' & Hall').\n      repeat subst_exp. \n      edestruct (Forall2_P_exists _ _ _ _ _ Hin1 Hp Hall') as [v1' [Hin' [v2' [Hget2' Hp']]]]. repeat subst_exp.\n      destruct v2'; [| contradiction ]. \n      eapply cc_approx_val_loc_eq in Hrel. subst.\n      assert (Hrel := Hp'). \n      eapply cc_approx_val_loc_eq in Hrel. subst.\n      eassumption. \n  Qed.\n  \n  (** [FV_inv] under rename extension  *)\n  Lemma FV_inv_rename_ext (k j : nat) (GII : GIInv) (GI : GInv) (b b' : Inj)\n        (rho1 : env) (H1 H2 : heap block) (rho2 : env) \n        (c : cTag) (Scope Funs : Ensemble var) (\u0393 : var) (FVs : list var) :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    f_eq_subdomain (reach' H1 (env_locs rho1 (FromList FVs \\\\ (Scope :|: Funs)))) b' b ->\n    FV_inv k j GII GI b' rho1 H1 rho2 H2 c Scope Funs \u0393 FVs.\n  Proof.\n    intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall) Hfeq.\n    split. eassumption. split. eassumption. repeat eexists; eauto.\n    eapply Forall2_P_monotonic_strong; [| eassumption ].\n    intros y1 v2 Hin1 Hin2 Hp [v1 [Hget3 Hrel]].\n    eexists; split; eauto.\n    eapply cc_approx_val_rename_ext; try eassumption.\n    eapply f_eq_subdomain_antimon; try eassumption.\n    eapply reach'_set_monotonic.\n    eapply get_In_env_locs; eauto.\n    constructor; eauto.\n  Qed.\n  \n\n  (** [FV_inv] monotonic *)\n  (* Lemma FV_inv_Scope_mon (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj) *)\n  (*       (rho1 : env) (H1 H2 : heap block) (rho2 : env)  *)\n  (*       (c : cTag) (Scope Scope' Funs : Ensemble var) (\u0393 : var) (FVs : list var) : *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs -> *)\n  (*   Scope \\subset Scope' ->  *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope' Funs \u0393 FVs. *)\n  (* Proof. *)\n  (*   intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall) Hfeq. *)\n  (*   split. eassumption. split. eassumption. repeat eexists; eauto. *)\n  (*   eapply Forall2_P_monotonic. eassumption. *)\n  (*   now eauto with Ensembles_DB.  *)\n  (* Qed. *)\n\n  (* Lemma FV_inv_Funs_mon (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj) *)\n  (*       (rho1 : env) (H1 H2 : heap block) (rho2 : env)  *)\n  (*       (c : cTag) (Scope Funs Funs' : Ensemble var) (\u0393 : var) (FVs : list var) : *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs -> *)\n  (*   Funs \\subset Funs' ->  *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs' \u0393 FVs. *)\n  (* Proof. *)\n  (*   intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall) Hfeq. *)\n  (*   split. eassumption. split. eassumption. repeat eexists; eauto. *)\n  (*   eapply Forall2_P_monotonic. eassumption. *)\n  (*   now eauto with Ensembles_DB.  *)\n  (* Qed. *)\n\n  (* Lemma FV_inv_mon (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj) *)\n  (*       (rho1 : env) (H1 H2 : heap block) (rho2 : env)  *)\n  (*       (c : cTag) (Scope Scope' Funs Funs' : Ensemble var) (\u0393 : var) (FVs : list var) : *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs -> *)\n  (*   Scope :|: Funs \\subset Scope' :|: Funs' ->  *)\n  (*   FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope' Funs' \u0393 FVs. *)\n  (* Proof. *)\n  (*   intros (Hwf & x1 & x2 & Hget1 & Hget2 & Hall) Hfeq. *)\n  (*   split. eassumption. repeat eexists; eauto. *)\n  (*   eapply Forall2_P_monotonic. eassumption. *)\n  (*   now eauto with Ensembles_DB.  *)\n  (* Qed. *)\n\n\n  Lemma FV_inv_FV_eq (k j : nat) (GII : GIInv) (GI : GInv) (b : Inj)\n        (rho1 : env) (H1 H2 : heap block) (rho2 : env)\n        (c : cTag) (Scope Scope' Funs Funs' : Ensemble var)\n        {_ : ToMSet Scope} {_ : ToMSet Scope'}\n        (\u0393 : var) FVs :\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    Scope :|: Funs <--> Scope' :|: Funs' ->\n    FV_inv k j GII GI b rho1 H1 rho2 H2 c Scope' Funs' \u0393 FVs.\n  Proof.\n    intros (Hwf & Hkey & x1 & x2 & Hget1 & Hget2 & Hall) Hfeq.\n    split. eassumption. split.\n    unfold FV in *. \n    rewrite <- Hfeq. rewrite (Union_Setminus_Included Scope' Funs'), <- Hfeq.\n    rewrite <- (Union_Setminus_Included Scope Funs) at 1.\n    eassumption. tci. reflexivity. tci. reflexivity. \n    repeat eexists; eauto.\n    eapply Forall2_P_monotonic. eassumption.\n    rewrite Hfeq. reflexivity. \n  Qed.\n\n\n  Instance Proper_FV_inv_Funs k j GI GP b rho1 H1 rho2 H2 c Scope :\n    Proper (Same_set _ ==> eq ==> eq ==> iff)\n           (FV_inv k j GI GP b rho1 H1 rho2 H2 c Scope). \n  Proof.\n    intros S1 S2 Hseq x1 x2 Heq1 y1 y2 Heq2; subst.\n    split; intros (Hwf & Hkey & vs & l & Hget1 & Hget2 & Hall1).\n    split. eassumption. split. unfold FV. rewrite <- !Hseq at 1. eassumption.\n    do 2 eexists.\n    split. eassumption.\n    split. eassumption.\n    eapply Forall2_P_monotonic; eauto. rewrite Hseq. reflexivity.\n    split. eassumption. split. unfold FV. rewrite !Hseq at 1. eassumption.\n    do 2 eexists.\n    split. eassumption.\n    split. eassumption.\n    eapply Forall2_P_monotonic; eauto. rewrite Hseq. reflexivity.\n  Qed.\n\n\n  Instance Proper_FV_inv_Scope k j GI GP b rho1 H1 rho2 H2 c :\n    Proper (Same_set _ ==> eq ==> eq ==> eq ==> iff)\n           (FV_inv k j GI GP b rho1 H1 rho2 H2 c). \n  Proof.\n    intros S1 S2 Hseq x1 x2 Heq1 y1 y2 Heq2 z1 z2 Heq3; subst.\n    split; intros (Hwf & Hkey & vs & l & Hget1 & Hget2 & Hall1).\n    split. eassumption. split. unfold FV. rewrite <- !Hseq at 1.    \n    eassumption.\n    do 2 eexists.\n    split. eassumption.\n    split. eassumption.\n    eapply Forall2_P_monotonic; eauto. rewrite Hseq. reflexivity.\n    split. eassumption. split. unfold FV. rewrite !Hseq at 1. eassumption.\n    do 2 eexists.\n    split. eassumption.\n    split. eassumption.\n    eapply Forall2_P_monotonic; eauto. rewrite Hseq. reflexivity.\n  Qed.\n\n\n  Lemma Fun_inv_image_reach k P1 P2 rho1 H1 rho2 H2 b\n        Scope Funs fenv FVs :\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    image b (reach' H1 (post H1 (env_locs rho1 (Funs \\\\ Scope)))) \\subset\n    reach' H2 (env_locs rho2 (image fenv (Funs \\\\ Scope))).\n  Proof.\n    intros Hres l' [l [Hin Heq]].\n    destruct Hin as [n [_ Hp]]. \n    edestruct post_n_exists_Singleton as [l1 [Hin Hp']]; try eassumption.\n    edestruct Hin as [l2 [b1 [Henv [Hgetl1 Hinl1]]]].\n    edestruct Henv as [x1 [Hinx Hm]].\n    destruct (M.get x1 rho1) as [[l3|] | ] eqn:Hgetx; inv Hm.\n    \n    inv Hinx. \n    edestruct (Hres n) as (l1' & lenv & l2' & g1 & rhoc & B2 & g2 & Hget1 & Hdis' (* & Hsub *)\n                               & Hget2 & Hget3 & Hget4 & Henv' & Heq').\n    eassumption. eassumption.\n    repeat subst_exp.\n    simpl in Hinl1. \n\n    rewrite Union_Empty_set_neut_l in Hinl1. \n    inv Hinl1.\n    eapply reach'_set_monotonic; [| eapply cc_approx_clos_image_eq ].\n    \n    eapply Singleton_Included. eexists (fenv x1). split.\n\n    eexists. split; [| reflexivity ]. now constructor; eauto.\n    rewrite Hget4. reflexivity.\n\n    intros j. \n\n    edestruct (Hres j) as (l1'' & lenv' & l2'' & g1' & rhoc' & B2' & g2' & Hget1' & Hdis'' (* & Hsub *)\n                           & Hget2' & Hget3' & Hget4' & Henv'' & Heq'').\n    eassumption. eassumption.\n    repeat subst_exp. eassumption.\n\n    eexists. split; [| reflexivity ]. eexists; split; try eassumption. now constructor. \n  Qed.\n\n\n  Lemma FV_image_reach k P1 P2 rho1 H1 rho2 H2 b c\n        Scope Funs \u0393 fenv FVs :\n    (forall j, (H1, rho1) \u22de ^ (Scope; k; j; P1; P2; b) (H2, rho2)) ->\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    image b (reach' H1 (env_locs rho1 (FV Scope Funs FVs)) \\\\ env_locs rho1 (Funs \\\\ Scope)) \\subset\n    reach' H2 (env_locs rho2 (Scope :|: image fenv (Funs \\\\ Scope) :|: [set \u0393])).\n  Proof with (now eauto with Ensembles_DB).\n    intros Hcc Hfun Henv l' [l [Hin Heq]]; subst.\n    unfold FV in Hin.\n    rewrite !env_locs_Union, !reach'_Union, !Setminus_Union_distr in Hin.\n    inv Hin. inv H. \n    \n    + eapply reach'_set_monotonic; [| eapply cc_approx_env_image_reach_included; try eassumption ].\n      eapply env_locs_monotonic...\n      eexists. split; eauto. inv H0. eassumption.\n\n    + rewrite !env_locs_Union, !reach'_Union. left. right.\n      eapply Fun_inv_image_reach. eassumption.\n      eexists. split; eauto.\n      rewrite reach_unfold, Setminus_Union_distr in H0.\n      rewrite Setminus_Same_set_Empty_set, Union_Empty_set_neut_l in H0. \n      inv H0; eassumption.\n\n    + rewrite !env_locs_Union, !reach'_Union. right.\n      rewrite reach_unfold. right.\n      eapply FV_inv_image_reach. eassumption.\n\n      eexists; split; eauto. \n      inv H. eassumption.\n  Qed.\n\n\n  Lemma def_closures_FV_inv' Scope Funs FVs \u0393 k j GIP GP b B1 B2 envc c rho1 H1 rho1' H1' rho2 H2 :\n    (forall j, FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    def_closures B1 B2 rho1 H1 envc = (H1', rho1') ->\n    FV_inv k j GIP GP b rho1' H1' rho2 H2 c (name_in_fundefs B1 :|: Scope) Funs \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    revert H1 rho1 H1' rho1' j.\n    induction B1; intros H1 rho1 H1' rho1' j Hfv Hdef.\n    - simpl in Hdef.\n      destruct (def_closures B1 B2 rho1 H1) as (H1'', rho1'') eqn:Hdef'.\n      destruct (alloc (Clos _ _) H1'') as [la H1a] eqn:Hal.\n      inv Hdef.\n      simpl. eapply Proper_FV_inv_Scope. rewrite <- Union_assoc. reflexivity. reflexivity.\n      reflexivity. reflexivity. \n      eapply FV_inv_set_not_in_FVs_l.\n      eapply FV_inv_heap_mon; [ | | ].\n      * eapply HL.alloc_subheap. eassumption.\n      * eapply HL.subheap_refl.\n      * intros j'.\n        eapply IHB1 in Hdef'.\n        eassumption.\n        eassumption.\n    - inv Hdef. simpl.\n      eapply Proper_FV_inv_Scope. rewrite Union_Empty_set_neut_l. reflexivity. \n      reflexivity. reflexivity. reflexivity. auto. \n  Qed.\n\n  Lemma def_funs_FV_inv Scope Funs \u0393 FVs c k j GIP GP b B1 B2 rho1 H1 rho2 H2 :\n    FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    name_in_fundefs B1 \\subset Scope :|: Funs ->\n    ~ \u0393 \\in name_in_fundefs B1 ->\n    FV_inv k j GIP GP b rho1 H1 (def_funs B1 B2 rho2) H2 c Scope Funs \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    induction B1; intros Hcc Hsub Hnin.\n    - simpl def_funs.\n      eapply FV_inv_set_not_in_FVs_r.\n      eapply IHB1. eassumption.\n      eapply Included_trans; [| eassumption ]... \n      intros Hc. eapply Hnin; now right.\n      intros Hc; inv Hc. eapply Hnin; now left.\n    - simpl. eassumption.\n  Qed.\n\n  Lemma FV_inv_env_constr k j PG QG b rho1 H1 rho2 H2 c FVs \u0393 lenv vs1 vs2 :\n    key_set rho1 <--> FromList FVs ->\n    M.get \u0393 rho2 = Some (Loc lenv) ->\n    get lenv H2 = Some (Constr c vs2) ->\n    getlist FVs rho1 = Some vs1 ->\n    (forall j,  Forall2\n             (fun v1 v2 : value =>\n                Res (v1, H1) \u227a ^ (k; j; PG; QG; b) Res (v2, H2)) vs1 vs2) ->\n    FV_inv k j PG QG b rho1 H1 rho2 H2 c (Empty_set _) (Empty_set _) \u0393 FVs. \n  Proof.\n    intros Hkey Hget1 Hget2 Hgl Hall.\n    split; [| split ].\n    - rewrite env_locs_Singleton; [| eassumption ]. simpl.\n      rewrite reach_unfold. eapply well_formed_Union.\n      + intros x bl Hinx Hget. inv Hinx. repeat subst_exp. simpl.\n        eapply Forall2_dom2. exact 0. eassumption. eassumption. (* XXX redundant params *)\n        eapply Forall2_forall. tci. eassumption.\n      + rewrite post_Singleton; [| eassumption ]. simpl. \n        eapply Forall2_reach2. eassumption. exact Some.  (* XXX redundant params *)\n        eapply Forall2_forall. tci. eassumption.\n    - rewrite Hkey. \n      + unfold FV. rewrite !Union_Empty_set_neut_l, !Setminus_Empty_set_neut_r, Union_Empty_set_neut_l. \n        reflexivity.\n    - do 2 eexists. split; [| split ]; try eassumption.\n      specialize (Hall j). revert Hgl Hall. clear.\n      intros Hgl Hall. revert FVs Hgl.\n      induction Hall; intros FVs Hgl.\n      + destruct FVs as [| x FVs ]; try inv Hgl.\n        now constructor.\n        destruct (M.get x rho1) eqn:Hgetx; try congruence.\n        destruct (getlist FVs rho1) eqn:Hgetlst; try congruence. \n      + destruct FVs as [| z FVs ]; try inv Hgl.\n        destruct (M.get z rho1) eqn:Hgetx; try congruence.\n        destruct (getlist FVs rho1) eqn:Hgetlst; try congruence. \n        inv H3. constructor; eauto.\n  Qed.\n\n  \n  (** * Lemmas about [Fun_inv] *)\n\n  Lemma Fun_inv_set_r k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs f v :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    ~ f \\in (Funs \\\\ Scope) -> ~ f \\in (image fenv (Funs \\\\ Scope)) ->\n    Fun_inv k j GI GP b rho1 H1 (M.set f v rho2) H2 Scope Funs fenv FVs.\n  Proof.\n    intros Hfun Hnin1 Hnin2 x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                      & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption. rewrite M.gso. eassumption.\n    \n    intros Hc. subst. eapply Hnin1; eauto. now constructor; eauto.\n\n    rewrite M.gso; try eassumption.\n\n    intros Hc; subst. eapply Hnin2. eexists; split; constructor; eauto.\n  Qed.\n\n    Lemma Fun_inv_set_l k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs f v :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    Disjoint _ (val_loc v) (dom H1) -> \n    (* post H1 (val_loc v) \\subset reach' H1 (env_locs rho1 Scope) ->  *)\n    Fun_inv k j GI GP b  (M.set f v rho1) H1 rho2 H2 (f |: Scope) Funs fenv FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hfun Hnin1 (* Hin1 *) x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    intros Hc. eapply Hnin. right. eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption. rewrite M.gso. eassumption.\n    \n    intros Hc. subst. eapply Hnin; now eauto.\n    repeat subst_exp. \n    \n    intros Hc; subst. eapply Hsub.\n    rewrite reach'_Union in *. inv Hc; [| now eauto ].\n    left. \n    eapply reach'_set_monotonic in H; [| eapply env_locs_set_Inlcuded' ].\n    rewrite reach'_Union in H. inv H. \n    - rewrite reach_unfold in H0. inv H0. \n      + exfalso. eapply Hnin1. constructor; eauto. eexists; eauto.\n      + rewrite post_Disjoint in H; [| eassumption ].\n        rewrite reach'_Empty_set in H.\n        now inv H. \n    - eapply reach'_set_monotonic; [| eassumption ].\n      eapply env_locs_monotonic. unfold FV.\n      rewrite !Setminus_Union_distr.\n        \n      eapply Included_Union_compat; [| now eauto with Ensembles_DB ].\n      eapply Included_Union_compat; [| now eauto with Ensembles_DB ]. \n      rewrite Setminus_Union, (Union_commut [set x]), <- Setminus_Union. \n      rewrite Setminus_Same_set_Empty_set. rewrite Setminus_Empty_set_abs_r... \n  Qed.\n\n  Lemma Fun_inv_set_l_alt k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs f v :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    val_loc v \\subset reach' H1 (env_locs rho1 Scope) ->\n    (* f \\in Scope -> *)\n    Fun_inv k j GI GP b  (M.set f v rho1) H1 rho2 H2 (f |: Scope) Funs fenv FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hfun Hnin1  x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    intros Hc. eapply Hnin. right. eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption. rewrite M.gso. eassumption.\n    \n    intros Hc. subst. eapply Hnin; now eauto.\n    repeat subst_exp. \n    \n    intros Hc; subst. eapply Hsub.\n    rewrite reach'_Union in *. inv Hc; [| now eauto ].\n    left. \n    eapply reach'_set_monotonic in H; [| eapply env_locs_set_Inlcuded' ].\n    rewrite reach'_Union in H. inv H. \n    - rewrite reach'_idempotent. eapply reach'_set_monotonic; [| eassumption ].\n      eapply Included_trans. eassumption.\n      eapply reach'_set_monotonic. eapply env_locs_monotonic.\n      unfold FV. rewrite !Setminus_Union_distr. do 2 eapply Included_Union_preserv_l. \n      rewrite Setminus_Disjoint. reflexivity. eapply Disjoint_Singleton_r. eauto.\n    - eapply reach'_set_monotonic; [| eassumption ].\n      eapply env_locs_monotonic.\n      eapply Included_trans. eapply Included_Setminus_compat.\n      eapply Included_Setminus_compat. eapply FV_Union1. \n      reflexivity. reflexivity.\n      rewrite Setminus_Union. rewrite (Union_commut [set x] [set f]), <- Setminus_Union.\n\n      rewrite Setminus_Union_distr. rewrite Setminus_Same_set_Empty_set, Union_Empty_set_neut_l...\n  Qed.\n\n\n  Lemma Fun_inv_Scope_monotonic k j GI GP b rho1 H1 rho2 H2 Scope S Funs \u0393 FVs {_ : Decidable S}:\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    FV (S :|: Scope) Funs FVs <--> FV Scope Funs FVs ->\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 (S :|: Scope) Funs \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hfun Heq y Hin Hnin. \n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                      & Hget2 & Hget3 & Hget4 & Henv & Heq').\n    now eauto. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    \n    intros Hc. eapply Hsub. rewrite <- Heq. eassumption.\n  Qed.\n\n  Lemma Fun_inv_monotonic k k' j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    k' <= k -> \n    Fun_inv k' j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hfun Hleq x Hin Hnin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n\n    do 7 eexists. repeat (split; [ eassumption |]). split.\n\n    eapply cc_approx_clos_monotonic; eassumption.\n\n    destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc B1]) H2). \n\n    eapply cc_approx_val_monotonic; eassumption. \n  Qed.\n\n\n  Lemma Fun_inv_Scope_monotonic' k j GI GP b rho1 H1 rho2 H2 Scope S Funs \u0393 FVs {_ : Decidable S}:\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    FV (S :|: Scope) (Funs \\\\ S) FVs <--> FV Scope Funs FVs ->\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 (S :|: Scope) (Funs \\\\ S) \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hfun Heq y Hin Hnin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                      & Hget2 & Hget3 & Hget4 & Henv & Heq').\n    now eauto. inv Hnin. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    do 7 eexists. repeat split; try eassumption.\n    \n    intros Hc. eapply Hsub. rewrite <- Heq. eassumption.\n  Qed.\n\n\n\n  Lemma Fun_inv_dom1 k GI GP rho1 H1 rho2 H2 b\n        Scope Funs \u0393 FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    env_locs rho1 (Funs \\\\ Scope) \\subset dom H1.\n  Proof.\n    intros Hres l [x1 [Hgetx1 Heq1]].\n    destruct (M.get x1 rho1) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres 0) as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hgetx1. now eapply Hgetx1.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    edestruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc (b lenv)]) H2) as [l2 H2'] eqn:Ha. \n    repeat subst_exp. \n    eapply cc_approx_val_dom1. eassumption. reflexivity. \n  Qed.\n  \n  Lemma Fun_inv_dom2 k GI GP rho1 H1 rho2 H2 b\n        Scope Funs \u0393 FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    env_locs rho2 (Funs \\\\ Scope) \\subset dom H2.\n  Proof.\n    intros Hres l [x2 [Hgetx1 Heq1]].\n    destruct (M.get x2 rho2) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres 0) as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hgetx1. now eapply Hgetx1.\n    repeat subst_exp.\n  Qed.\n  \n  Lemma Fun_inv_reach1 k GI GP rho1 H1 rho2 H2 b\n        Scope Funs \u0393 FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    well_formed (reach' H1 (env_locs rho1 (Funs \\\\ Scope))) H1.\n  Proof.\n    intros Hres l b1 [n [_ Hp]] Hget.\n    edestruct post_n_exists_Singleton as [lr [Hin' Hp']].\n    eassumption.\n    destruct Hin' as [x1 [Hin1 Heq1]].\n    destruct (M.get x1 rho1) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres (1 + n))\n      as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n         & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hin1. now eapply Hin1. repeat subst_exp.\n    destruct Henv as [Hbeq Henv]. subst.\n\n    assert (Hp'' := Hp'). \n    edestruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc (b lenv)]) H2) as [l2 H2'] eqn:Ha.\n    eapply cc_approx_val_post_n_cc with (v1 := Loc l1) (j := 1) in Hp';\n      [| eapply cc_approx_val_j_monotonic; try eassumption; omega ].\n\n    \n    intros Hget1. \n    eapply cc_approx_val_well_formed_post1 with (v1 := Loc l1) (j := n); try eassumption.\n    eapply cc_approx_val_j_monotonic. eassumption. omega.\n  Qed.\n\n\n  Lemma Fun_inv_reach2 k GI GP rho1 H1 rho2 H2 b\n        Scope Funs \u0393 FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    well_formed (reach' H2 (env_locs rho2 (Funs \\\\ Scope))) H2.\n  Proof.\n    intros Hres l b1 [n [_ Hp]] Hget.\n    edestruct post_n_exists_Singleton as [lr [Hin' Hp']].\n    eassumption.\n    destruct Hin' as [x1 [Hin1 Heq1]].\n    destruct (M.get x1 rho2) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres (1 + n))\n      as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n         & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hin1. now eapply Hin1. repeat subst_exp.\n  Qed.\n\n  Lemma Fun_inv_dom2_funs k GI GP rho1 H1 rho2 H2 b\n        Scope Funs fenv FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    env_locs rho2 (image fenv (Funs \\\\ Scope)) \\subset dom H2.\n  Proof.\n    intros Hres l [x2 [Hgetx1 Heq1]].\n    destruct (M.get x2 rho2) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct Hgetx1 as [f1 [Hin Heq]]; subst. \n    edestruct (Hres 1) as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hin. now eapply Hin.\n    repeat subst_exp. \n    eapply cc_approx_clos_dom2. eassumption. \n  Qed.\n\n  Lemma Fun_inv_reach2_funs k GI GP rho1 H1 rho2 H2 b\n        Scope Funs fenv FVs :\n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    well_formed (reach' H2 (env_locs rho2 (image fenv (Funs \\\\ Scope)))) H2.\n  Proof.\n    intros Hres l b1 [n [_ Hp]] Hget.\n    edestruct post_n_exists_Singleton as [lr [Hin' Hp']].\n    eassumption.\n    destruct Hin' as [x1 [[f1 [Hin1 Heq2]] Heq1]]; subst.\n    destruct (M.get (fenv f1) rho2) as [ [|] | ] eqn:Hgety; try inv Heq1.\n    edestruct (Hres 0) as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    now eapply Hin1.\n    now eapply Hin1. \n    \n    eapply cc_approx_clos_well_formed_reac2 with (l2 := lr); (* TODO typo *)\n      [ | | eassumption ].\n    \n    intros j.\n    edestruct (Hres j) as (l1' & lenv' & B1' & g1' & rhoc' & B2' & g2' & Hget1' &\n                           Hsub' (* & Hdis' *) & Hget2' & Hget3' & Hget4' & Henv' & Heq').\n    now eapply Hin1.\n    now eapply Hin1. \n    repeat subst_exp. eassumption. \n    eexists. split. now constructor. eassumption.\n  Qed.\n  \n\n  Lemma Fun_inv_alloc k j GI GP b rho1 H1 H1' rho2 H2 H2' Scope Funs fenv FVs l1 l2 b1 b2 z:\n    closed (reach' H1 (env_locs rho1 (FV Scope Funs FVs))) H1 -> \n    alloc b1 H1 = (l1, H1') ->\n    alloc b2 H2 = (l2, H2') ->\n\n    locs b1 \\subset reach' H1 (env_locs rho1 Scope) ->\n                    \n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n\n    ~ z \\in image fenv (Funs \\\\ Scope) ->\n    Fun_inv k j GI GP b (M.set z (Loc l1) rho1) H1' (M.set z (Loc l2) rho2) H2' (z |: Scope) Funs fenv FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hwf Ha1 Ha2 Hsub Hfun Hninz x Hin Hnin.\n    edestruct (Hfun j) as (l1' & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq);\n      try eassumption.\n    intros Hc. eapply Hin. now right. \n    assert (Hneq : x <> z). { intros Hc; inv Hc. eauto. } \n    rewrite !M.gso with (i := x) (j := z) in *; eauto. \n    \n    do 7 eexists; split; [| split; [| split; [| split; [| split; [| split ] ]]]]; try eassumption.\n    - intros Hc. rewrite post_Singleton in Hdis; eauto. simpl in Hdis.\n\n      rewrite Union_Empty_set_neut_l in Hdis. eapply Hdis.\n      rewrite post_Singleton in Hc; [| eapply HL.alloc_subheap; eassumption ].\n      simpl in Hc. rewrite Union_Empty_set_neut_l in Hc.\n      rewrite reach'_Union in *. inv Hc. \n      + eapply reach'_set_monotonic with (S2 := env_locs (M.set z (Loc l1) rho1)\n                                                         (FV Scope Funs FVs \\\\ [set x] :|: [set z])) in H.\n        eapply reach'_alloc_set in H; try eassumption. inv H.\n        \n        * inv H0. erewrite alloc_fresh in Hget3; eauto. congruence.\n        * left. eassumption.\n        * eapply Included_trans. eassumption.\n          eapply reach'_set_monotonic. eapply env_locs_monotonic.\n          eapply Included_Setminus. eapply Disjoint_Singleton_r.\n          now intros Hc'; eauto. now eauto with Ensembles_DB.\n        * eapply env_locs_monotonic. eapply Setminus_Included_Included_Union.\n\n          eapply Included_trans. eapply FV_Union1. rewrite <- Union_assoc. \n          rewrite <- (Union_Included_Union_Setminus _ (z |: [set x])). \n          now eauto with Ensembles_DB. tci.\n          now eauto with Ensembles_DB.\n      + rewrite <- well_formed_reach_subheap_same in H. right. eassumption.\n        eapply well_formed_antimon; [| eapply well_formed'_closed; eassumption ].\n        rewrite (reach'_idempotent H1 (env_locs rho1 (FV Scope Funs FVs))).\n        eapply reach'_set_monotonic.\n        eapply Singleton_Included. eexists 1. split. now constructor.\n        simpl. do 2 eexists. split; eauto. eapply get_In_env_locs with (x := x); eauto.\n        left. right. now constructor; eauto.\n        reflexivity. split; eauto. now right.\n        eapply Singleton_Included. eapply cc_approx_clos_dom1. eassumption.\n        eapply HL.alloc_subheap; eauto.\n    - eapply HL.alloc_subheap; eauto.\n    - rewrite M.gso. eassumption. intros Hc. eapply Hninz. subst.\n      eexists; split; eauto. constructor; eauto.\n    - eapply cc_approx_clos_heap_monotonic.\n      now eapply HL.alloc_subheap; eauto.\n      now eapply HL.alloc_subheap; eauto.\n      intros j'.\n      edestruct (Hfun j') as (l1'' & lenv' & B1' & g1' & rhoc' & B2' & g2' & Hget1' & Hdis' (* & Hsub *)\n                                   & Hget2' & Hget3' & Hget4' & Henv' & Heq');\n        try eassumption. intros Hc. eapply Hin. now right.\n      repeat subst_exp. eassumption. \n    - destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc B1]) H2)\n        as [l4 H4] eqn:Ha.\n      destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc B1]) H2')\n        as [l4' H4'] eqn:Ha'.\n      \n      eapply cc_approx_val_rename_ext\n      with (\u03b2' := ((id {l4 ~> l4'}) \u2218 (b {l1' ~> l4}) \u2218 id)).\n      + eapply cc_approx_val_res_eq.\n        eassumption.\n        eapply res_equiv_subheap; try eassumption; [| | now eapply reach'_extensive |].\n        eapply well_formed_antimon; [| eapply well_formed'_closed; eassumption ].\n        eapply reach'_set_monotonic. eapply get_In_env_locs; eauto. left. right.\n        constructor; eauto. \n        eapply Singleton_Included. eapply cc_approx_val_dom1. eassumption.\n        reflexivity.\n        now eapply HL.alloc_subheap; eauto.\n        clear. now firstorder.\n        \n        * rewrite res_equiv_eq. simpl. split.\n          rewrite extend_gss; reflexivity.\n          \n          do 2 (erewrite gas; eauto). simpl. split.\n          reflexivity.\n          constructor.\n          rewrite res_equiv_eq. split; reflexivity.\n          \n          constructor; [| now constructor ].\n           \n          eapply res_equiv_rename_ext;\n            [| eapply f_eq_subdomain_extend_not_In_S_r; [| reflexivity ] | reflexivity ].\n          \n          eapply res_equiv_weakening;\n            [| | | now eapply HL.alloc_subheap; eauto\n             | eapply HL.subheap_trans; [| now eapply HL.alloc_subheap; eauto ];\n               now eapply HL.alloc_subheap; eauto\n             | | ].\n             \n          eapply reach'_closed.\n          eapply Fun_inv_reach2_funs. eassumption. \n          eapply Fun_inv_dom2_funs. eassumption. \n          eapply reach'_closed. \n          eapply Fun_inv_reach2_funs. eassumption. \n          eapply Fun_inv_dom2_funs. eassumption. \n          reflexivity.\n          \n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply get_In_env_locs; [| eassumption ].\n          eexists; split; eauto. now constructor; eauto.\n          \n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply get_In_env_locs; eauto.\n          eexists; split; eauto. now constructor; eauto.\n          \n          intros Hc1.\n          rewrite <- env_locs_Singleton with (v := Loc B1) in Hc1; try eassumption. \n          rewrite <- well_formed_reach_alloc_same in Hc1;\n          [| | | eassumption ].\n          \n          eapply reachable_in_dom in Hc1; try eassumption. destruct Hc1 as [b' Hget].\n          erewrite alloc_fresh in Hget; eauto. congruence.\n          \n          eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n          eapply reach'_set_monotonic. eapply env_locs_monotonic.\n          eapply Singleton_Included.\n          eexists; split; eauto. now constructor; eauto.\n          eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n          eapply env_locs_monotonic.\n          eapply Singleton_Included.\n          eexists; split; eauto. now constructor; eauto.\n          \n          eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n          eapply reach'_set_monotonic. eapply env_locs_monotonic.\n          eapply Singleton_Included.\n          eexists; split; eauto. now constructor; eauto.\n          eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n          eapply env_locs_monotonic.\n          eapply Singleton_Included.\n          eexists; split; eauto. now constructor; eauto.\n          \n        * eapply injective_subdomain_extend'. now firstorder.\n          rewrite image_id.\n          rewrite reach_unfold. rewrite Setminus_Union_distr.\n          rewrite Setminus_Same_set_Empty_set, Union_Empty_set_neut_l.\n          simpl. rewrite post_Singleton; [| erewrite gas; eauto ]. simpl.\n          rewrite Union_Empty_set_neut_l, Union_Empty_set_neut_r.\n          intros Hc. inv Hc.\n          rewrite reach'_alloc in H; [| eassumption |].\n          eapply reachable_in_dom in H. destruct H as [v' Hgetv'].\n          eapply HL.alloc_subheap in Hgetv'; [| now apply Ha2 ]. \n          erewrite alloc_fresh in Hgetv'; eauto. congruence.\n\n          eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ]. \n          eapply reach'_set_monotonic.\n          eapply Singleton_Included. eapply get_In_env_locs; eauto.\n          eexists; split; eauto. now constructor; eauto. reflexivity. \n          \n          eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ]. \n          eapply Singleton_Included. eapply get_In_env_locs; eauto.\n          eexists; split; eauto. now constructor; eauto. reflexivity. \n\n          eapply Included_trans; [| eapply reach'_extensive ].\n          simpl...\n      + rewrite Combinators.compose_id_right. \n        rewrite compose_extend. rewrite extend_gss.\n        eapply f_eq_subdomain_antimon.\n        eapply Included_Union_Setminus with (s2 := [set l1']). \n        now tci.\n        rewrite Union_commut. eapply f_eq_subdomain_extend. \n        symmetry. eapply compose_id_extend.\n        \n        \n        rewrite reach_unfold, Setminus_Union_distr,\n        Setminus_Same_set_Empty_set, Union_Empty_set_neut_l.\n         \n        assert (Hsub' : (post H1 (val_loc (Loc l1'))) \\subset\n                        reach' H1 (env_locs rho1 (Funs \\\\ Scope))).\n        { rewrite (reach_unfold H1 (env_locs rho1 (Funs \\\\ Scope))).\n          eapply Included_Union_preserv_r.\n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply post_set_monotonic.\n          eapply get_In_env_locs. constructor; eauto. eassumption. }\n        simpl. rewrite post_Singleton; [| eapply HL.alloc_subheap; eassumption ].\n        simpl. rewrite Union_Empty_set_neut_l.\n        \n        assert (Henvj : forall j, (lenv, H1) << ^ (k; j; GI; GP; b) (B1, H2)). \n        { intros j'.\n          edestruct (Hfun j') as (l1'' & lenv' & B1' & g1' & rhoc' & B2' & g2' & Hget1' & Hdis' (* & Hsub *)\n                                   & Hget2' & Hget3' & Hget4' & Henv' & Heq');\n            try eassumption. intros Hc'. eapply Hin. now right.\n          repeat subst_exp. eassumption. }\n        \n        rewrite <- well_formed_reach_subheap_same; [| | | now eapply HL.alloc_subheap; eauto ] .\n        intros Hc.\n\n        eapply image_monotonic in Hc; [| eapply Setminus_Included ].\n\n        rewrite cc_approx_clos_image_eq in Hc; [| try eassumption ].\n        eapply reachable_in_dom in Hc.\n\n        destruct Hc as [v1 Hgetv1]. erewrite alloc_fresh in Hgetv1. congruence.\n        eassumption.\n        eapply cc_approx_clos_well_formed_reac2. eassumption.\n        eapply Singleton_Included. eapply cc_approx_clos_dom2. eassumption.\n        eapply cc_approx_clos_well_formed_reach1. eassumption.\n        eapply Singleton_Included. eapply cc_approx_clos_dom1. eassumption.\n  Qed.\n  \n  Lemma Fun_inv_rename_ext k j GI GP b b' rho1 H1 rho2 H2 Funs Scope \u0393 FVs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    f_eq_subdomain (reach' H1 (env_locs rho1 (Funs \\\\ Scope))) b b' ->\n    Fun_inv k j GI GP b' rho1 H1 rho2 H2 Scope Funs \u0393 FVs.\n  Proof.\n    intros Hfun Heq1 x Hin Hnin.\n    edestruct Hfun\n      as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *)\n         & Hget2 & Hget3 & Hget4 & Henv & Heq);\n      try eassumption.\n    assert (Henv' := Henv). \n    destruct Henv as [Hbeq Henv]. subst.\n\n    assert (Hbeq : b lenv = b' lenv). \n    { rewrite <- Heq1. reflexivity.\n      eapply Included_post_reach'. eapply post_set_monotonic.\n      eapply Singleton_Included. eexists. split. \n      now constructor; eauto. rewrite Hget1. reflexivity. \n      rewrite post_Singleton; [| eassumption ]. simpl. right. reflexivity. } \n\n    do 7 eexists; repeat split; try eassumption.\n    \n    - rewrite <- Heq1. eassumption.\n      eapply Included_post_reach'. eapply post_set_monotonic.\n      eapply Singleton_Included. eexists. split. \n      now constructor; eauto. rewrite Hget1. reflexivity. \n      rewrite post_Singleton; [| eassumption ]. simpl. right. reflexivity. \n\n    - eapply cc_approx_clos_rename_ext; try eassumption. \n      rewrite <- Hbeq. eassumption. \n\n      eapply f_eq_subdomain_antimon; [ | eassumption ].\n      eapply Included_trans; [| eapply reach'_set_monotonic; eapply get_In_env_locs; try eassumption ]. \n      rewrite (reach_unfold H1 (val_loc (Loc l1))).\n      eapply Included_Union_preserv_r. simpl. \n      rewrite post_Singleton; eauto.\n      simpl. rewrite Union_Empty_set_neut_l. reflexivity.\n      now constructor; eauto.\n\n    - rewrite <- Hbeq in *. \n      destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc (b lenv)]) H2) as [l2 H2'].\n      \n\n      assert (Hseq : l1 |: (reach' H1 (val_loc (Loc l1))) <--> reach' H1 (val_loc (Loc l1))).\n      { split. eapply Union_Included. eapply Singleton_Included. eapply reach'_extensive.\n        reflexivity. reflexivity.\n        eapply Included_Union_preserv_r. reflexivity. }\n      eapply cc_approx_val_rename_ext. eassumption.\n      \n      rewrite <- Hseq.  eapply f_eq_subdomain_extend. symmetry.\n      eapply f_eq_subdomain_antimon; [ | eassumption ]. eapply reach'_set_monotonic.\n      eapply get_In_env_locs. constructor; eauto. eassumption.\n  Qed.\n  \n\n  Instance Proper_Fun_inv_Funs k j GI GP b rho1 H1 rho2 H2 Scope :\n    Proper (Same_set _ ==> eq ==> eq ==> iff)\n           (Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope). \n  Proof.\n    intros S1 S2 Hseq x1 x2 Heq1 f1 f2 Heq3; subst.\n    split; intros Hfv f Hin Hnin.\n    - edestruct (Hfv f)\n        as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *)\n           & Hget2 & Hget3 & Hget4 & Henv & Heq);\n      try eassumption.\n      rewrite Hseq. eassumption.\n\n      destruct Henv as [Hbeq Henv]. subst.\n      \n      do 7 eexists; repeat split; try eassumption.\n      rewrite <- Hseq. eassumption.\n      (* rewrite <- Hseq. eassumption. *)\n    - edestruct (Hfv f)\n        as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *)\n               & Hget2 & Hget3 & Hget4 & Henv & Heq);\n      try eassumption.\n      rewrite <- Hseq. eassumption.\n      destruct Henv as [Hbeq Henv]. subst.\n\n      do 7 eexists; repeat split; try eassumption.\n      rewrite Hseq. eassumption.\n      (* rewrite Hseq. eassumption. *)\n  Qed.\n  \n  Instance Proper_Fun_inv_Scope k j GI GP b rho1 H1 rho2 H2 :\n    Proper (Same_set _ ==> eq ==> eq ==> eq ==> iff)\n           (Fun_inv k j GI GP b rho1 H1 rho2 H2). \n  Proof.\n    intros S1 S2 Hseq x1 x2 Heq1 y1 y2 Heq2 f1 f2 Heq3; subst.\n    split; intros Hfv f Hin Hnin. \n    - edestruct (Hfv f) as\n          (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *) &\n              Hget2 & Hget3 & Hget4 & Henv & Heq); try eassumption.\n      rewrite Hseq. eassumption.\n      \n      destruct Henv as [Hbeq Henv]. subst.\n      \n      do 7 eexists; repeat split; try eassumption.\n      rewrite <- Hseq. eassumption.\n    - (* rewrite <- !Hseq at 1. eassumption. *)\n      edestruct (Hfv f) as\n          (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *) &\n              Hget2 & Hget3 & Hget4 & Henv & Heq); try eassumption.\n      rewrite <- Hseq. eassumption.\n      destruct Henv as [Hbeq Henv]. subst.\n\n      do 7 eexists; repeat split; try eassumption.\n      rewrite Hseq. eassumption.\n      (* rewrite !Hseq at 1. eassumption. *)\n  Qed.\n  \n  Lemma Fun_inv_locs_Disjoint1 k j GI GP b rho1 H1 rho2 H2 Funs Scope \u0393 FVs f :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    f \\in (Funs \\\\ Scope) ->\n    Disjoint _ (env_locs rho1 [set f])\n             (reach' H1 (env_locs rho1 (FV Scope Funs FVs \\\\ [set f]))).\n  Proof.\n    intros Hfun [Hin Hnin].\n    edestruct Hfun as\n        (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis & (* Hsub & *)\n            Hget2 & Hget3 & Hget4 & Henv & Heq); try eassumption.\n    rewrite env_locs_Singleton; [| eassumption ].\n    eapply Disjoint_Singleton_l. intros Hc. eapply Hdis.\n    rewrite reach'_Union. now left. \n  Qed.\n\n  Lemma Fun_inv_locs_Disjoint2 k j GI GP b rho1 H1 rho2 H2 Funs Scope \u0393 FVs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    Disjoint _ (env_locs rho1 (Funs \\\\ Scope))\n             (reach' H1 (post H1 (env_locs rho1 (Funs \\\\ Scope)))).\n  Proof.\n    intros Hfun. constructor. intros l [l' [f [Hin Hm]] Hin'].\n    destruct (M.get f rho1) as [[l1|] | ] eqn:Hget; inv Hm.\n    inv Hin.\n    edestruct Hfun as\n        (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis & (* Hsub & *)\n            Hget2 & Hget3 & Hget4 & Henv & Heq); try eassumption.\n    eapply Hdis. repeat subst_exp.\n    rewrite reach'_Union.\n    assert (Hseq : Funs \\\\ Scope <--> Funs \\\\ Scope \\\\ [set f] :|: [set f]).\n    { rewrite <- Union_Setminus. rewrite Union_commut, Union_Same_set.\n      reflexivity. eapply Singleton_Included. constructor; eauto. tci. }\n\n    rewrite Hseq in Hin'. rewrite env_locs_Union, post_Union, reach'_Union in Hin'.\n    inv Hin'.\n    - left. rewrite reach'_idempotent. eapply reach'_set_monotonic; [| eassumption ].\n      eapply Included_trans. eapply Included_post_reach'.\n      eapply reach'_set_monotonic. eapply env_locs_monotonic.\n      now eauto with Ensembles_DB.\n    - right. eapply reach'_set_monotonic; [| eassumption ].\n      rewrite env_locs_Singleton; eauto. reflexivity. \n  Qed.\n  \n  Lemma Fun_inv_post_Included k j GI GP b rho1 H1 rho2 H2 Funs Scope \u0393 FVs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs \u0393 FVs ->\n    post H1 (env_locs rho1 (Funs \\\\ Scope)) \\subset\n    reach' H1 (env_locs rho1 (FV Scope Funs FVs)) \\\\ env_locs rho1 (Funs \\\\ Scope).\n  Proof. \n    intros Hfun l Hpost.\n    edestruct post_exists_Singleton as [l' [Hin Hpin]]. eassumption. \n    constructor.\n\n    eapply Included_post_reach'. eapply post_set_monotonic; [| eassumption ].\n    eapply Singleton_Included. eapply env_locs_monotonic; [| eassumption ].\n    now eauto with Ensembles_DB.\n\n    intros Hc. eapply Fun_inv_locs_Disjoint2. eassumption.\n    constructor. eassumption. eapply reach'_extensive.\n    eapply post_set_monotonic; [| eassumption ].\n    eapply Singleton_Included; eassumption. \n  Qed.\n\n  Lemma FV_dom1 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope {Hs : ToMSet Scope} Funs \u0393 FVs fenv :\n    (forall j, (H1, rho1) \u22de ^ (Scope; k; j; P1; P2; b) (H2, rho2)) ->\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs fenv FVs) ->\n    env_locs rho1 (FV Scope Funs FVs) \\subset dom H1.\n  Proof.\n    intros Hcc Hfun Henv.\n    unfold FV.\n    rewrite <- (Union_Setminus_Included Scope Funs) at 1; [| | reflexivity ]; tci. \n    rewrite !env_locs_Union.\n    eapply Union_Included. \n    eapply Union_Included.\n    \n    eapply cc_approx_env_P_dom1. now eapply (Hcc 0). \n    eapply Fun_inv_dom1. eassumption.\n\n    rewrite (Union_Setminus_Included Scope Funs) at 1; [| | reflexivity ]; tci.     \n    eapply FV_inv_dom1.\n    eassumption.\n  Qed.\n\n  Lemma FV_dom2 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope {Hs : ToMSet Scope} Funs \u0393 FVs fenv :\n    (forall j, (H1, rho1) \u22de ^ (Scope; k; j; P1; P2; b) (H2, rho2)) ->\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    binding_in_map Scope rho1 ->\n    env_locs rho2 (FV_cc Scope Funs fenv \u0393) \\subset dom H2.\n  Proof.\n    intros Hcc Hfun Henv Hbin.\n    unfold FV_cc.\n    rewrite !env_locs_Union.\n    eapply Union_Included. \n    eapply Union_Included.\n    eapply Union_Included.\n\n    eapply cc_approx_env_P_dom2. now eapply (Hcc 0). \n    eassumption.\n    \n    eapply Fun_inv_dom2. eassumption.\n    eapply Fun_inv_dom2_funs. eassumption.\n\n    eapply FV_inv_dom2. eassumption.\n  Qed.\n  \n  Lemma FV_reach1 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope {Hd : Decidable Scope} Funs \u0393 fenv FVs :\n    (forall j, (H1, rho1) \u22de ^ (Scope; k; j; P1; P2; b) (H2, rho2)) ->\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs \u0393 FVs) ->\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs fenv FVs) ->\n    well_formed (reach' H1 (env_locs rho1 (FV Scope Funs FVs))) H1.\n  Proof.\n    intros Hcc Hfun Henv.\n    unfold FV.\n    rewrite <- (Union_Setminus_Included Scope Funs) at 1; [| | reflexivity ]; tci. \n    rewrite !env_locs_Union, !reach'_Union. eapply well_formed_Union.\n    eapply well_formed_Union.\n    \n    eapply cc_approx_env_P_well_formed_reach1. eassumption.\n\n    eapply Fun_inv_reach1. eassumption.\n    \n    rewrite (Union_Setminus_Included Scope Funs) at 1; [| | reflexivity ]; tci.     \n    eapply FV_inv_reach1.\n    eassumption.\n  Qed.\n\n  Lemma FV_reach2 k P1 P2 rho1 H1 rho2 H2 b c\n        Scope {Hd : Decidable Scope} Funs \u0393 fenv FVs :\n    (forall j, (H1, rho1) \u22de ^ (Scope; k; j; P1; P2; b) (H2, rho2)) ->\n    (forall j, Fun_inv k j P1 P2 b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    (forall j, FV_inv k j P1 P2 b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    binding_in_map Scope rho1 ->\n    well_formed (reach' H2 (env_locs rho2 (FV_cc Scope Funs fenv \u0393))) H2.\n  Proof.\n    intros Hcc Hfun Henv Hbin.\n    unfold FV_cc. \n    rewrite !env_locs_Union, !reach'_Union. eapply well_formed_Union.\n    eapply well_formed_Union.\n    eapply well_formed_Union.\n    \n    eapply cc_approx_env_P_well_formed_reach2. eassumption.\n    eassumption.\n    \n    eapply Fun_inv_reach2. eassumption.\n    \n    eapply Fun_inv_reach2_funs. eassumption.\n    destruct (Henv 0) as (Hr & _). \n    eassumption.\n  Qed.\n\n    Lemma def_closures_FV_inv Scope {Hc : ToMSet Scope} Funs FVs \u0393 k j GIP GP b B1 B2 envc c rho1 H1 rho1' H1' rho2 H2 :\n    (forall j, FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs) ->\n    def_closures B1 B2 rho1 H1 envc = (H1', rho1') ->\n    FV_inv k j GIP GP b rho1' H1' rho2 H2 c Scope (name_in_fundefs B1 :|: Funs) \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    revert H1 rho1 H1' rho1' j.\n    induction B1; intros H1 rho1 H1' rho1' j Hfv Hdef.\n    - simpl in Hdef.\n      destruct (def_closures B1 B2 rho1 H1) as (H1'', rho1'') eqn:Hdef'.\n      destruct (alloc (Clos _ _) H1'') as [la H1a] eqn:Hal.\n      inv Hdef. \n      simpl. eapply Proper_FV_inv_Funs. rewrite <- Union_assoc. reflexivity. reflexivity. reflexivity.\n      eapply FV_inv_FV_eq with (Scope := v |: Scope) (Funs := name_in_fundefs B1 :|: Funs). \n      tci. tci.\n      eapply FV_inv_set_not_in_FVs_l.\n      eapply FV_inv_heap_mon; [ | | ].\n      * eapply HL.alloc_subheap. eassumption.\n      * eapply HL.subheap_refl.\n      * intros j'.\n        eapply IHB1 in Hdef'.\n        eassumption.\n        eassumption.\n      * now eauto with Ensembles_DB. \n    - inv Hdef. simpl.\n      eapply Proper_FV_inv_Funs. rewrite Union_Empty_set_neut_l. reflexivity. \n      reflexivity. reflexivity. eauto.\n  Qed.\n\n  Lemma setlist_FV_inv Scope {Hc : ToMSet Scope} Funs FVs \u0393 k j GIP GP b c rho1 H1 rho1' rho2 H2\n        xs vs :\n    FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    setlist xs vs rho1 = Some rho1' ->\n    FV_inv k j GIP GP b rho1' H1 rho2 H2 c (FromList xs :|: Scope) Funs \u0393 FVs.\n  Proof with (now eauto with Ensembles_DB).\n    revert vs H1 rho1 rho1' j.\n    induction xs; intros vs H1 rho1 rho1' j Hfv Hdef.\n    - destruct vs; try inv Hdef.\n      eapply Proper_FV_inv_Scope. normalize_sets. rewrite Union_Empty_set_neut_l. reflexivity. \n      reflexivity. reflexivity. reflexivity. eauto.\n    - simpl in Hdef.\n      eapply Proper_FV_inv_Scope. normalize_sets. rewrite <- Union_assoc. reflexivity.\n      reflexivity. reflexivity. reflexivity.\n      destruct vs; try congruence. \n      destruct (setlist xs vs rho1) as [rho1''| ] eqn:Hset; try congruence.\n      inv Hdef. \n      eapply FV_inv_set_not_in_FVs_l.\n      eapply IHxs. eassumption. eassumption.\n  Qed.\n\n  Lemma FV_inv_rho_swap Scope {Hc : ToMSet Scope} Funs FVs \u0393 \u0393' k j GIP GP b c rho1 H1 rho2 rho2' H2 :\n    FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    M.get \u0393 rho2 = M.get \u0393' rho2' ->\n    FV_inv k j GIP GP b rho1 H1 rho2' H2 c Scope Funs \u0393' FVs.\n  Proof.\n    intros Hfvs Heq. \n    destruct Hfvs as (Hwf & Hkey & vs & lenv'' & Hgetlenv & Hget' & HallP).\n    split; [| split ]; try eassumption.\n    - rewrite env_locs_Singleton in *; eauto.\n      rewrite <- Heq. eassumption.\n    - do 2 eexists. split.\n      rewrite <- Heq. eassumption.\n      split; eassumption.\n  Qed.\n\n  Lemma FV_inv_heap_env_equiv Scope Funs FVs \u0393 k j GIP GP b c rho1 H1 rho1' H1' rho2 H2 rho2' H2' \n        (\u03b21 \u03b22 : Inj) :\n    FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n\n    Full_set _ |- (H1, rho1) \u2a6a_(id, \u03b21) (H1', rho1') ->\n    injective_subdomain (reach' H1' (env_locs rho1' (Full_set _))) \u03b21 -> \n    [set \u0393] |- (H2, rho2) \u2a6a_(\u03b22, id) (H2', rho2') ->\n    injective_subdomain (reach' H2 (env_locs rho2 (Full_set _))) \u03b22 ->\n\n    FV_inv k j GIP GP (\u03b22 \u2218 b \u2218 \u03b21) rho1' H1' rho2' H2' c Scope Funs \u0393 FVs.\n  Proof.\n    intros Hfvs Heq1 Hinj1 Heq2 Hinj2. \n    destruct Hfvs as (Hwf & Hkey & vs & lenv'' & Hgetlenv & Hget' & HallP).\n    split; [| split ]; try eassumption.\n    - eapply well_formed_respects_heap_env_equiv. eassumption.\n      eapply heap_env_equiv_antimon. eassumption. reflexivity.\n    - rewrite <- heap_env_equiv_key_set. eassumption. eassumption.\n    - edestruct heap_env_equiv_env_get as [lenv' [Hget Hres]]. eassumption.\n      eapply heap_env_equiv_antimon. eassumption. reflexivity. reflexivity.\n      rewrite res_equiv_eq in *. destruct lenv'; try contradiction. \n      rewrite <- res_equiv_eq in *.\n      edestruct res_equiv_get_Constr as [vs' [Hhget Hres']]; eauto.\n      \n      do 2 eexists. split; eauto. split; eauto. \n      assert (Hinj2' : injective_subdomain (reach' H2 (Union_list (map val_loc vs))) \u03b22).\n      { eapply injective_subdomain_antimon. eassumption. \n        rewrite (reach'_idempotent H2 (env_locs _ _)). \n        eapply reach'_set_monotonic. eapply Included_trans; [| eapply Included_post_reach' ].\n        eapply Included_trans; [| eapply post_set_monotonic; eapply get_In_env_locs; eauto; now constructor ].\n        simpl. rewrite post_Singleton; eauto. reflexivity. }\n\n      clear Hhget. \n      revert HallP vs' Hres' Heq1 Hinj1 Hinj2'; clear.\n      intros Hall1.\n      induction Hall1; intros vs' Hall2 Heq1 Hinj1 Hinj2.\n      + inv Hall2.\n        now constructor. \n      + inv Hall2. eapply IHHall1 in H6; eauto. constructor; [| eassumption ].\n        intros Hnin.\n        edestruct H as [v1 [Hgetx1 Hres1]]. eassumption.        \n        edestruct heap_env_equiv_env_get as [lenv' [Hget Hres]]. eassumption.\n        eassumption. now constructor. \n        eexists; split; eauto. \n        eapply cc_approx_val_res_eq.\n\n        eassumption. eassumption.\n        eapply injective_subdomain_antimon. eassumption.\n        eapply reach'_set_monotonic. eapply get_In_env_locs. now constructor.\n        eassumption.\n        \n        eassumption.\n        eapply injective_subdomain_antimon. eassumption.\n        eapply reach'_set_monotonic. simpl. now eauto with Ensembles_DB.\n\n        eapply injective_subdomain_antimon. eassumption.\n        eapply reach'_set_monotonic. simpl. now eauto with Ensembles_DB.\n  Qed.     \n\n  Lemma FV_inv_heap_f_eq_subdomain Scope Funs FVs \u0393 k j GIP GP b c rho1 H1 rho2 H2 b':\n    FV_inv k j GIP GP b rho1 H1 rho2 H2 c Scope Funs \u0393 FVs ->\n    f_eq_subdomain (reach' H1 (env_locs rho1 (FromList FVs))) b b' ->\n    FV_inv k j GIP GP b' rho1 H1 rho2 H2 c Scope Funs \u0393 FVs.\n  Proof. \n    intros Hfvs Heq1. \n    destruct Hfvs as (Hwf & Hkey & vs & lenv'' & Hgetlenv & Hget' & HallP).\n    split; [| split ]; try eassumption.\n    do 2 eexists. split; eauto. split; eauto.\n    revert HallP Heq1; clear.\n    intros Hall1. induction Hall1; intros Heq.\n    + now constructor.\n    + constructor; eauto.\n      intros Hc.\n      edestruct H as [v1 [Hgetx1 Hcc]]. eassumption.\n      eexists; split; eauto.\n      eapply cc_approx_val_rename_ext. eassumption.\n\n      eapply f_eq_subdomain_antimon; [| symmetry; eassumption ].\n      normalize_sets. rewrite env_locs_Union, reach'_Union. eapply Included_Union_preserv_l.\n      eapply reach'_set_monotonic. eapply get_In_env_locs; try eassumption. reflexivity.\n\n      eapply IHHall1. \n      eapply f_eq_subdomain_antimon; [| eassumption ].\n      normalize_sets. rewrite env_locs_Union, reach'_Union. eapply Included_Union_preserv_r.\n      reflexivity.\n  Qed. \n\n  (** * Lemmas about [project_var] and [project_vars] *)\n  \n    \n  Lemma project_var_ctx_to_heap_env Scope Scope' Funs Funs' c fenv FVs x C v1 rho1 rho2 H2 \u0393:\n    project_var Size.Util.clo_tag Scope Funs fenv c \u0393 FVs x C Scope' Funs' ->\n    Fun_inv_weak rho1 rho2 Scope Funs fenv ->\n    FV_inv_weak rho1 rho2 H2 c Scope Funs \u0393 FVs ->\n    M.get x rho1 = Some v1 ->\n    exists H2' rho2' s, ctx_to_heap_env_CC C H2 rho2 H2' rho2' s.\n  Proof.\n    intros Hproj Hfun HFV Hget. inv Hproj.\n    - repeat eexists; econstructor; eauto.\n    - edestruct Hfun as (l1 & lenv & B & f' & Hget1 & Hget2 & Hget3); try eassumption.\n      edestruct (alloc (Constr Size.Util.clo_tag [FunPtr B f'; Loc lenv]) H2) as [l' H2'] eqn:Ha. \n      do 3 eexists.\n      econstructor; [ | | now econstructor ].\n      + simpl. rewrite Hget2, Hget3. reflexivity.\n      + eassumption. \n    - edestruct HFV as (v & vs  & Hget1 & Hget2 & Hall).   \n      edestruct Forall2_P_nthN as [v2 [Hnth Hr]]; eauto.\n      repeat eexists. intros Hc. now inv Hc; eauto.\n      do 3 eexists. econstructor; try eassumption. constructor.\n  Qed.\n  \n  Lemma project_vars_ctx_to_heap_env Scope Scope' {Hs : ToMSet Scope} Funs Funs' c \u0393 FVs xs C vs1 rho1 rho2 H2 fenv :\n    ~ \u0393 \\in FV Scope Funs FVs ->\n    Disjoint _ (image fenv (Funs \\\\ Scope)) (FV Scope Funs FVs) ->\n    project_vars Size.Util.clo_tag Scope Funs fenv c \u0393 FVs xs C Scope' Funs'  ->\n    Fun_inv_weak rho1 rho2 Scope Funs fenv ->\n    FV_inv_weak rho1 rho2 H2 c Scope Funs \u0393 FVs ->\n    getlist xs rho1 = Some vs1 ->\n    exists H2' rho2' s, ctx_to_heap_env_CC C H2 rho2 H2' rho2' s.\n  Proof.\n    revert Scope Hs Scope' Funs \u0393 FVs C vs1\n           rho1 rho2 H2.\n    induction xs;\n      intros Scope Hs Scope' Funs \u0393 FVs C vs1\n             rho1 rho2 H2 Hnin Hdis Hvars Hfun HFV Hget.\n    - inv Hvars. repeat eexists; econstructor; eauto.\n    - inv Hvars. simpl in Hget.\n      destruct (M.get a rho1) eqn:Hgeta1; try discriminate.\n      destruct (getlist xs rho1) eqn:Hgetlist1; try discriminate. \n      edestruct project_var_ctx_to_heap_env with (rho1 := rho1)\n        as [H2' [rho2' [s Hctx1]]]; eauto.\n      inv Hget.\n      assert (Hs2 := project_var_ToMSet _ _ _ _ _ _ _ _ _ _ H8).  \n      edestruct IHxs with (H2 := H2') (rho2 := rho2') as [H2'' [rho2'' [s' Hctx2]]];\n        [ eassumption | | | eassumption | | | eassumption | ].\n   \n      + intros Hd; eapply Hnin. erewrite project_var_FV_eq; eassumption.\n      + erewrite <- project_var_FV_eq; try eassumption.\n        eapply Disjoint_Included_l; [| eassumption ].\n        eapply image_monotonic. eapply Included_Setminus_compat.\n        eapply project_var_Funs_l. eassumption.\n        eapply project_var_Scope_l. eassumption.   \n      + intros f Hnin' Hin.\n        edestruct Hfun as (l1 & lenv & B & f' & Hget1 & Hget2 & Hget3); try eassumption.\n        intros Hc; eapply Hnin'. eapply project_var_Scope_l; eassumption.\n        eapply project_var_Funs_l; eassumption.\n        erewrite <- !project_var_get with (rho1 := rho2) (rho2 := rho2'); try eassumption.\n        \n        now repeat eexists; eauto.\n        intros Hc. inv Hc. eapply Hdis.\n        erewrite project_var_FV_eq; try eassumption.\n        constructor. eexists; split; eauto.\n        constructor. \n        eapply project_var_Funs_l; eassumption.\n        intros Hc. eapply Hnin'. \n        eapply project_var_Scope_l; eassumption.   \n        left. now left.\n        \n        intros Hc; inv Hc; eauto.\n      + edestruct HFV as [v' [vs [Hget [Hget1 Hall]]]]; eauto.\n        repeat eexists; eauto.\n        * erewrite <- project_var_get; try eassumption.\n          intros Hin'. inv Hin'. eapply Hnin.\n          erewrite project_var_FV_eq; try eassumption.\n          left. now left.\n        * erewrite <- (project_var_subheap _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H8). reflexivity.\n          eassumption. eassumption.\n        * eapply Forall2_P_monotonic. eassumption.\n          rewrite project_var_Scope_Funs_eq with (Funs' := Funs2); [| eassumption ].\n          rewrite Union_Setminus_Included. \n          eapply Included_Union_compat; [| reflexivity ].\n          eapply project_var_Scope_l. eassumption. now tci. \n          now eauto with Ensembles_DB.\n      + exists H2'', rho2'', (s + s'). eapply ctx_to_heap_env_CC_comp_ctx_f_r; eassumption.\n  Qed.\n\n    Lemma Fun_inv_subheap k j GI GP b rho1 H1 H1' rho2 H2 H2' Scope Funs fenv FVs :\n    well_formed (reach' H1 (env_locs rho1 (FV Scope Funs FVs))) H1 ->\n    env_locs rho1 (FV Scope Funs FVs) \\subset dom H1 ->\n    \n    image b (reach' H1 (post H1 (env_locs rho1 (Funs \\\\ Scope)))) \\subset dom H2 ->\n    \n    (forall j, Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs) ->\n    H1 \u2291 H1' ->\n    H2 \u2291 H2' ->\n    Fun_inv k j GI GP b rho1 H1' rho2 H2' Scope Funs fenv FVs.\n  Proof with (now eauto with Ensembles_DB).\n    intros Hwf1 Henv1  Him Hfun Hsub1 Hsub2 x Hin Hnin.\n    edestruct (Hfun j) as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hdis (* & Hsub *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq);\n      try eassumption.\n    do 7 eexists; repeat split; try eassumption.\n    \n    - intros Hc. eapply Hdis. rewrite reach'_subheap; [ | | | eassumption ].\n\n      rewrite well_formed_post_subheap_same. eassumption.\n\n      eapply well_formed_antimon; [| now apply Hwf1 ].\n\n      eapply reach'_set_monotonic. eapply get_In_env_locs with (v := Loc l1); [| eassumption ].\n      left. right. constructor; eauto.\n\n      eapply Singleton_Included. now eexists; eauto.\n\n      eassumption.\n\n      eapply well_formed_antimon; [| now apply Hwf1 ].\n      rewrite reach'_Union. eapply Union_Included.\n      eapply reach'_set_monotonic. eapply env_locs_monotonic...\n      \n      rewrite (reach'_idempotent H1 (env_locs rho1 (FV Scope Funs FVs))). eapply reach'_set_monotonic.\n      eapply Included_trans; [|  eapply Included_post_reach' ]. eapply post_set_monotonic.\n      eapply get_In_env_locs with (v := Loc l1); [| eassumption ].\n      left. right. constructor; eauto.\n\n      eapply Included_trans; [| eapply reachable_in_dom; try eassumption ].\n      eapply Union_Included. eapply Included_trans; [| eapply reach'_extensive ].\n      eapply env_locs_monotonic...\n\n      eapply Included_trans; [|  eapply Included_post_reach' ]. eapply post_set_monotonic.\n      eapply get_In_env_locs with (v := Loc l1); [| eassumption ].\n      left. right. constructor; eauto.\n    - eapply Hsub1. eassumption.\n    - destruct Henv as [Hbeq _]; subst. eassumption.\n    - eapply cc_approx_clos_heap_monotonic; try eassumption.\n      destruct Henv as [Hbeq _]; subst.\n      intros j'.\n      edestruct (Hfun j') as (l1' & lenv' & B1' & g1' & rhoc' & B2' & g2' & Hget1' & Hdis' (* & Hsub' *) & Hget2'\n                             & Hget3' & Hget4' & Henv' & Heq');\n        try eassumption.\n      repeat subst_exp. eassumption.\n\n    - destruct Henv as [Hbeq Henv]; subst. \n      destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc (b lenv)]) H2)\n        as [l2 H4] eqn:Ha.\n      destruct (alloc (Constr Size.Util.clo_tag [FunPtr B2 g2; Loc (b lenv)]) H2')\n        as [l2' H4'] eqn:Ha'.\n      \n      eapply cc_approx_val_rename_ext\n      with (\u03b2' := ((id {l2 ~> l2'}) \u2218 (b {l1 ~> l2}) \u2218 id)).\n      + eapply cc_approx_val_res_eq.\n        eassumption. eapply res_equiv_subheap; try eassumption.\n        eapply Included_trans; [| eapply reach'_extensive ].\n        eapply get_In_env_locs; try eassumption. left; right.\n        constructor; eassumption. \n        \n        now firstorder.\n        \n        * rewrite res_equiv_eq. simpl. split.\n          rewrite extend_gss; reflexivity.\n          \n          do 2 (erewrite gas; eauto). simpl. split.\n          reflexivity.\n          constructor.\n          rewrite res_equiv_eq. split; reflexivity.\n          \n          constructor; [| now constructor ].\n          \n          eapply res_equiv_rename_ext;\n            [| eapply f_eq_subdomain_extend_not_In_S_r; [| reflexivity ] | reflexivity ].\n          \n          eapply res_equiv_weakening;\n            [| | reflexivity | now eapply HL.alloc_subheap; eauto\n             | eapply HL.subheap_trans; [| eapply HL.alloc_subheap]; eassumption | | ].\n          \n          eapply reach'_closed.\n          eapply Fun_inv_reach2_funs. eassumption. \n          eapply Fun_inv_dom2_funs. eassumption. \n          eapply reach'_closed.\n          eapply Fun_inv_reach2_funs. eassumption. \n          eapply Fun_inv_dom2_funs. eassumption. \n          \n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply get_In_env_locs; [| eassumption ].\n          now eexists; split; eauto. \n          \n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply get_In_env_locs; eauto.\n          now eexists; split; eauto. \n          \n          intros Hc1.\n          rewrite <- env_locs_Singleton with (v := Loc (b lenv)) in Hc1; try eassumption. \n          rewrite <- well_formed_reach_alloc_same in Hc1;\n          [| | | eassumption ].\n        \n        eapply reachable_in_dom in Hc1; try eassumption. destruct Hc1 as [b' Hget].\n        erewrite alloc_fresh in Hget; eauto. congruence.\n        \n        eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n        eapply reach'_set_monotonic. eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto. \n        eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n        eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto.\n\n        eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n        eapply reach'_set_monotonic. eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto. \n        eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n        eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto.\n        \n      * eapply injective_subdomain_extend'. now firstorder.\n        rewrite image_id.\n        rewrite reach_unfold. rewrite Setminus_Union_distr.\n        rewrite Setminus_Same_set_Empty_set, Union_Empty_set_neut_l.\n        simpl. rewrite post_Singleton; [| erewrite gas; eauto ]. simpl.\n        rewrite Union_Empty_set_neut_l, Union_Empty_set_neut_r.\n        intros Hc. destruct Hc as [Hc1 Hc2].\n        \n        rewrite <- env_locs_Singleton with (v := Loc (b lenv)) in Hc1; try eassumption. \n        \n        rewrite <- well_formed_reach_alloc_same in Hc1;\n          [| | | eassumption ].\n        \n        eapply reachable_in_dom in Hc1; try eassumption. destruct Hc1 as [b' Hget].\n        eapply Hsub2 in Hget.  \n        erewrite alloc_fresh in Hget; eauto. congruence.\n        \n        eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n        eapply reach'_set_monotonic. eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto. \n        eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n        eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto.\n\n        eapply well_formed_antimon; [| eapply Fun_inv_reach2_funs; eassumption ].\n        eapply reach'_set_monotonic. eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto. \n        eapply Included_trans; [| eapply Fun_inv_dom2_funs; eassumption ].\n        eapply env_locs_monotonic.\n        eapply Singleton_Included. eexists; split; now eauto.\n      + rewrite Combinators.compose_id_right. \n        rewrite compose_extend. rewrite extend_gss.\n        eapply f_eq_subdomain_antimon.\n        eapply Included_Union_Setminus with (s2 := [set l1]). \n        now tci.\n        rewrite Union_commut. eapply f_eq_subdomain_extend.\n        symmetry. eapply compose_id_extend.\n      \n        intros Hc.\n        rewrite reach_unfold, Setminus_Union_distr,\n        Setminus_Same_set_Empty_set, Union_Empty_set_neut_l in Hc.\n        \n        assert (Hsub' : (post H1 (val_loc (Loc l1))) \\subset\n                        reach' H1 (env_locs rho1 (Funs \\\\ Scope))).\n        { rewrite (reach_unfold H1 (env_locs rho1 (Funs \\\\ Scope))).\n          eapply Included_Union_preserv_r.\n          eapply Included_trans; [| eapply reach'_extensive ].\n          eapply post_set_monotonic.\n          eapply get_In_env_locs. constructor; eauto. eassumption. }\n        \n        assert (Hin2 : l2 \\in dom H2).\n        { eapply Him. \n          eapply image_monotonic; [| eassumption ].\n          eapply Included_trans. eapply Setminus_Included.\n          \n          \n          rewrite <- well_formed_post_subheap_same, <- well_formed_reach_subheap_same;\n            try eassumption.\n          \n          eapply reach'_set_monotonic. eapply post_set_monotonic.\n          eapply get_In_env_locs; try eassumption. now constructor; eauto.\n          \n          eapply well_formed_antimon; [| eassumption ].\n          rewrite (reach'_idempotent H1 (env_locs rho1 (FV Scope Funs FVs))).\n          eapply reach'_set_monotonic.  \n          eapply Included_trans. eassumption.\n          eapply reach'_set_monotonic. eapply env_locs_monotonic...\n          eapply Included_trans; [| eapply reachable_in_dom; eassumption ].\n          eapply Included_trans. eassumption.\n          eapply reach'_set_monotonic. eapply env_locs_monotonic...\n          \n          eapply well_formed_antimon; [| eassumption ].\n          eapply reach'_set_monotonic.\n          eapply get_In_env_locs; try eassumption.\n          now left; right; constructor; eassumption. \n          \n          eapply Included_trans; [| eassumption ]. \n          \n          eapply get_In_env_locs; try eassumption.\n          now left; right; constructor; eassumption.\n          \n        }\n      \n        destruct Hin2 as [b' Hget].\n        erewrite alloc_fresh in Hget; eauto. congruence. \n        \n  Qed.\n\n    Lemma Fun_inv_setlist_l k j GI GP b rho1 rho1' H1 rho2 H2 Scope Funs fenv FVs xs vs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    Disjoint _ (FromList xs) (Funs \\\\ Scope) ->\n    Disjoint _ (reach' H1 (Union_list (map val_loc vs))) (env_locs rho1 (Funs \\\\ Scope)) ->\n    setlist xs vs rho1 = Some rho1' ->\n    Fun_inv k j GI GP b rho1' H1 rho2 H2 Scope Funs fenv FVs.\n  Proof.\n    intros Hfun Hnin1 Hnin2 Hset x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                      & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    erewrite <- setlist_not_In; eauto.\n    intros Hc. eapply Hnin1. constructor; eauto. now constructor; eauto.\n    rewrite reach'_Union in *. intros Hc. eapply Hsub.\n    inv Hc; [| now right ].\n    eapply reach'_set_monotonic in H;\n      [| eapply env_locs_monotonic; eapply Included_Union_preserv_l; reflexivity ].\n    eapply reach'_set_monotonic in H; [| eapply env_locs_setlist_Included; eassumption ]. \n    rewrite reach'_Union in H. inv H. now left.\n    exfalso. eapply Hnin2. constructor; eauto.\n    eexists; split; eauto. now constructor; eauto.\n    rewrite Hget1. reflexivity. \n  Qed.\n\n  Lemma Fun_inv_setlist_r k j GI GP b rho1 H1 rho2 rho2' H2 Scope Funs fenv FVs xs vs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    Disjoint _ (FromList xs) (Funs \\\\ Scope) ->\n    Disjoint _ (FromList xs) (image fenv (Funs \\\\ Scope)) ->\n    setlist xs vs rho2 = Some rho2' ->\n    Fun_inv k j GI GP b rho1 H1 rho2' H2 Scope Funs fenv FVs.\n  Proof.\n    intros Hfun Hnin1 Hnin2 Hset x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    erewrite <- setlist_not_In; eauto.\n    intros Hc. eapply Hnin1. constructor; eauto. now constructor; eauto.\n    erewrite <- setlist_not_In; eauto.    \n    intros Hc. eapply Hnin2. constructor; eauto.\n    eexists; split; eauto. now constructor; eauto.\n  Qed.\n\n  Lemma Fun_inv_suffle_setlist k j GI GP b rho1 H1 rho2 rho2' rho2'' H2 Scope Funs fenv FVs\n        x v xs vs:\n    Fun_inv k j GI GP b rho1 H1 (M.set x v rho2') H2 Scope Funs fenv FVs ->\n    setlist xs vs rho2 = Some rho2' ->\n    setlist xs vs (M.set x v rho2) = Some rho2'' ->\n    ~ x \\in FromList xs ->\n    Fun_inv k j GI GP b rho1 H1 rho2'' H2 Scope Funs fenv FVs.\n  Proof. \n    intros Hfun Hset1 Hset2 Hninx y Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    - destruct (var_dec x y); subst.\n      + rewrite M.gss in *.  inv Hget2.\n        erewrite <- setlist_not_In; eauto.\n        rewrite M.gss. reflexivity.\n      + edestruct (set_setlist_permut rho2 rho2') as [rho2''' [Hset3 Heqr]].\n        eassumption. eassumption. rewrite Hset2 in Hset3. inv Hset3.\n        rewrite <- Heqr. eassumption.\n    - destruct (var_dec x (fenv y)); subst.\n      + rewrite M.gss in *. inv Hget4.\n        erewrite <- setlist_not_In; eauto.\n        rewrite M.gss. reflexivity.\n      + edestruct (set_setlist_permut rho2 rho2') as [rho2''' [Hset3 Heqr]].\n        eassumption. eassumption. rewrite Hset2 in Hset3. inv Hset3.\n        rewrite <- Heqr. eassumption.\n  Qed.\n\n  Lemma Fun_inv_suffle_def_funs k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs\n        x v B1 B2:\n    Fun_inv k j GI GP b rho1 H1 (M.set x v (def_funs B1 B2 rho2)) H2 Scope Funs fenv FVs ->\n    ~ x \\in (name_in_fundefs B1) ->\n    Fun_inv k j GI GP b rho1 H1 (def_funs B1 B2 (M.set x v rho2)) H2 Scope Funs fenv FVs.\n  Proof.\n    intros Hfun Hninx y Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1' & g1 & rhoc & B2' & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    - destruct (var_dec y x); subst.\n      + rewrite M.gss in *. inv Hget2.\n        erewrite def_funs_neq; [| reflexivity | eassumption ].\n        rewrite M.gss. reflexivity.\n      + rewrite M.gso in Hget2; [| eassumption ].\n        destruct (@Dec _ (name_in_fundefs B1) _ y).\n        * erewrite def_funs_eq in Hget2; [| reflexivity | eassumption ].\n          inv Hget2.\n          erewrite def_funs_eq; [| reflexivity | eassumption ].\n          reflexivity.\n        * erewrite def_funs_neq in Hget2; [| reflexivity | eassumption ].\n          erewrite def_funs_neq; [| reflexivity | eassumption ].\n          rewrite M.gso; eassumption.\n    - destruct (var_dec (fenv y) x); subst.\n      + rewrite M.gss in *. inv Hget4.\n        erewrite def_funs_neq; [| reflexivity | eassumption ].\n        rewrite M.gss. reflexivity.\n      + rewrite M.gso in Hget4; [| eassumption ].\n        destruct (@Dec _ (name_in_fundefs B1) _ (fenv y)).\n        * erewrite def_funs_eq in Hget4; [| reflexivity |  eassumption ].\n          inv Hget4.\n        * erewrite def_funs_neq in Hget4; [| reflexivity | eassumption ].\n          erewrite def_funs_neq; [| reflexivity | eassumption ].\n          rewrite M.gso; eassumption.\n  Qed.\n\n  Lemma Fun_inv_suffle_setlist_l k j GI GP b rho1 H1 rho2 rho2' rho2'' H2 Scope Funs fenv FVs\n        x v xs vs:\n    Fun_inv k j GI GP b rho1 H1 rho2'' H2 Scope Funs fenv FVs ->\n    setlist xs vs rho2 = Some rho2' ->\n    setlist xs vs (M.set x v rho2) = Some rho2'' ->\n    ~ x \\in FromList xs ->\n            Fun_inv k j GI GP b rho1 H1 (M.set x v rho2') H2 Scope Funs fenv FVs.\n  Proof. \n    intros Hfun Hset1 Hset2 Hninx y Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1 & g1 & rhoc & B2 & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    - destruct (var_dec x y); subst.\n      + rewrite M.gss in *.  inv Hget2.\n        erewrite <- setlist_not_In; eauto.\n        rewrite M.gss. reflexivity.\n      + edestruct (set_setlist_permut rho2 rho2') as [rho2''' [Hset3 Heqr]].\n        eassumption. eassumption. rewrite Hset2 in Hset3. inv Hset3.\n        rewrite Heqr. eassumption.\n    - destruct (var_dec x (fenv y)); subst.\n      + rewrite M.gss in *. inv Hget4.\n        erewrite <- setlist_not_In; eauto.\n        rewrite M.gss. reflexivity.\n      + edestruct (set_setlist_permut rho2 rho2') as [rho2''' [Hset3 Heqr]].\n        eassumption. eassumption. rewrite Hset2 in Hset3. inv Hset3.\n        rewrite Heqr. eassumption.\n  Qed.\n\n  Lemma Fun_inv_suffle_def_funs_l k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs\n        x v B1 B2:\n    Fun_inv k j GI GP b rho1 H1 (def_funs B1 B2 (M.set x v rho2)) H2 Scope Funs fenv FVs ->\n    ~ x \\in (name_in_fundefs B1) ->\n    Fun_inv k j GI GP b rho1 H1 (M.set x v (def_funs B1 B2 rho2)) H2 Scope Funs fenv FVs.\n  Proof.\n    intros Hfun Hninx y Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1' & g1 & rhoc & B2' & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n    \n    do 7 eexists. repeat split; try eassumption.\n    - destruct (var_dec y x); subst.\n      + rewrite M.gss in *. inv Hget2.\n        erewrite def_funs_neq; [| reflexivity | eassumption ].\n        rewrite M.gss. reflexivity.\n      + rewrite M.gso; [| eassumption ].\n        destruct (@Dec _ (name_in_fundefs B1) _ y).\n        * erewrite def_funs_eq in Hget2; [| reflexivity | eassumption ].\n          inv Hget2.\n          erewrite def_funs_eq; [| reflexivity | eassumption ].\n          reflexivity.\n        * erewrite def_funs_neq in Hget2; [| reflexivity | eassumption ].\n          erewrite def_funs_neq; [| reflexivity | eassumption ].\n          rewrite M.gso in Hget2; eassumption.\n    - destruct (var_dec (fenv y) x); subst.\n      + rewrite M.gss in *. inv Hget4.\n        erewrite def_funs_neq; [| reflexivity | eassumption ].\n        rewrite M.gss. reflexivity.\n      + rewrite M.gso; [| eassumption ].\n        destruct (@Dec _ (name_in_fundefs B1) _ (fenv y)).\n        * erewrite def_funs_eq in Hget4; [| reflexivity |  eassumption ].\n          inv Hget4.\n        * erewrite def_funs_neq in Hget4; [| reflexivity | eassumption ].\n          erewrite def_funs_neq; [| reflexivity | eassumption ].\n          rewrite M.gso in Hget4; eassumption.\n  Qed.\n\n  Lemma Fun_inv_Scope_Disjoint k j GI GP b rho1 H1 rho2 H2 Scope Scope' Funs fenv FVs :\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 Scope Funs fenv FVs ->\n    Disjoint _ (env_locs rho1 Funs) (reach' H1 (env_locs rho1 Scope')) ->\n    Fun_inv k j GI GP b rho1 H1 rho2 H2 (Scope' :|: Scope) Funs fenv FVs.\n  Proof.\n    intros Hfun Hdis1 x Hnin Hin.\n    edestruct Hfun as (l1 & lenv & B1' & g1 & rhoc & B2' & g2 & Hget1 & Hsub (* & Hdis *)\n                          & Hget2 & Hget3 & Hget4 & Henv & Heq).\n    intros Hc. eapply Hnin. right. eassumption. eassumption.\n    destruct Henv as [Hbeq Henv]. subst.\n\n    do 7 eexists. repeat split; try eassumption.\n\n\n    intros Hc. eapply Hsub. rewrite reach'_Union in *.\n    inv Hc; [| now right ].\n    left.\n    eapply reach'_set_monotonic in H; [| eapply env_locs_monotonic;\n                                         eapply Included_Setminus_compat;\n                                         [ eapply FV_Union1 | reflexivity ] ].\n    rewrite Setminus_Union_distr in H.\n    rewrite env_locs_Union, reach'_Union in H.\n    inv H; [| eassumption ].\n    exfalso. eapply Hdis1. constructor.\n    eexists; split; eauto. rewrite Hget1. reflexivity.\n    eapply reach'_set_monotonic; [| eassumption ].\n    eapply env_locs_monotonic. now eauto with Ensembles_DB.\n  Qed.\n\n\nEnd Invariants.\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/invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.19066668890283953}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool eqtype ssrnat seq fintype finset.\nFrom extructures Require Import ord fset fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils lib.fmap_utils common.types.\nRequire Import symbolic.symbolic.\nRequire Import lib.haskell_notation.\nRequire Import lib.ssr_list_utils.\nRequire Import compartmentalization.common compartmentalization.isolate_sets.\nRequire Import compartmentalization.abstract compartmentalization.symbolic.\n\nSet Bullet Behavior \"Strict Subproofs\".\nImport DoNotation.\n\nSection RefinementSA.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport Abs.Notations.\nImport Abs.Hints.\nImport Sym.EnhancedDo.\n\n(* ssreflect exposes `succn' as a synonym for `S' *)\nLocal Notation II := Logic.I.\n\nContext\n  (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\nNotation word     := (mword mt).\nNotation pc_tag   := (Sym.pc_tag mt).\nNotation data_tag := (Sym.data_tag mt).\nNotation sym_compartmentalization := (@Sym.sym_compartmentalization mt).\n\nNotation spcatom := (atom word pc_tag).\nNotation smatom  := (atom word data_tag).\nNotation sratom  := (atom word unit).\nNotation svalue  := (@vala word _).\nNotation slabel  := (@taga word _).\n\nNotation astate    := (@Abs.state mt).\nNotation sstate    := (@Symbolic.state mt sym_compartmentalization).\nNotation AState    := (@Abs.State mt).\nNotation SState    := (@Symbolic.State mt sym_compartmentalization).\nNotation SInternal := (@Sym.Internal mt).\n\nNotation astep := Abs.step.\nNotation sstep := Sym.step.\n\n(* Avoiding some type class resolution problems *)\n\nArguments Sym.sget {_ _} s p : simpl never.\nArguments Sym.supd {_ _} s p tg : simpl never.\n\nCanonical compartment_eqType :=\n  Eval hnf in EqType (Abs.compartment mt) (Abs.compartment_eqMixin mt).\n\n(* We check the compartment stuff later *)\nDefinition refine_pc_b (apc : word) (spc : spcatom) :=\n  match spc with\n    | spc' @ _ => apc == spc'\n  end.\n\n(* We check the compartment stuff later *)\nDefinition refine_mem_loc_b (ax : word) (sx : smatom) : bool :=\n  match sx with\n    | sx' @ _ => ax == sx'\n  end.\n\nDefinition refine_reg_b (ar : word) (sr : sratom) : bool :=\n  match sr with\n    | sr' @ _ => ar == sr'\n  end.\n\nDefinition refine_memory : memory mt -> Sym.memory mt -> Prop :=\n  pointwise refine_mem_loc_b.\n\nDefinition refine_registers : registers mt -> Sym.registers mt -> Prop :=\n  pointwise refine_reg_b.\n\nSection WithSym.\nImport Sym.\n\nDefinition get_compartment_id (sst : sstate)\n                              (c   : Abs.compartment mt) : option word :=\n  [pick cid |\n    ((omap data_tag_compartment \\o Sym.sget sst) @: Abs.address_space c) ==\n    [set Some cid]].\n\nDefinition well_defined_compartments (sst : sstate)\n                                     (C   : seq (Abs.compartment mt)) : Prop :=\n  forall p, sget sst p -> Abs.in_compartment_opt C p.\n\nDefinition well_defined_ids (sst : sstate)\n                            (C   : seq (Abs.compartment mt)) : Prop :=\n  forall c, c \\in C -> get_compartment_id sst c.\n\n(* AAA: Does this imply disjointness? *)\nDefinition unique_ids (sst : sstate)\n                      (C   : seq (Abs.compartment mt)) : Prop :=\n  forall c1 c2,\n    c1 \\in C ->\n    c2 \\in C ->\n    get_compartment_id sst c1 = get_compartment_id sst c2 ->\n    c1 = c2.\n\nDefinition well_formed_targets (targets : Abs.compartment mt -> {set word})\n                               (sources : data_tag _         -> {set word})\n                               (sst     : sstate)\n                               (C       : seq (Abs.compartment mt)) : Prop :=\n  forall c cid,\n    c \\in C ->\n    get_compartment_id sst c = Some cid ->\n    targets c =\n    [set p | oapp (fun s : {set word} => cid \\in s) false\n                  (omap sources (Sym.sget sst p)) ].\n\nDefinition well_formed_jump_targets : sstate -> seq (Abs.compartment mt) -> Prop :=\n  well_formed_targets (fun c => Abs.jump_targets c) data_tag_incoming.\n\nDefinition well_formed_store_targets : sstate -> seq (Abs.compartment mt) -> Prop :=\n  well_formed_targets (fun c => Abs.store_targets c) data_tag_writers.\n\nEnd WithSym.\n\nDefinition refine_previous_b (sk : where_from) (prev : Abs.compartment mt)\n                             (sst : sstate) : bool :=\n  match Symbolic.pc sst with\n    | _ @ (Sym.PC F cid) => (sk == F) &&\n                            (get_compartment_id sst prev == Some cid)\n  end.\n\nDefinition refine_syscall_addrs_b (AM : memory mt) (SM : Sym.memory mt) : bool :=\n  [&& all (fun x => ~~ AM x) syscall_addrs ,\n      all (fun x => ~~ SM x) syscall_addrs &\n      uniq syscall_addrs ].\n\nRecord refine (ast : astate) (sst : sstate) : Prop := RefineState\n  { pc_refined           : refine_pc_b               (Abs.pc           ast)\n                                                     (Symbolic.pc      sst)\n  ; regs_refined         : refine_registers          (Abs.regs         ast)\n                                                     (Symbolic.regs    sst)\n  ; mems_refined         : refine_memory             (Abs.mem          ast)\n                                                     (Symbolic.mem     sst)\n  ; compartments_wd      : well_defined_compartments sst\n                                                     (Abs.compartments ast)\n  ; ids_well_defined     : well_defined_ids          sst\n                                                     (Abs.compartments ast)\n  ; ids_unique           : unique_ids                sst\n                                                     (Abs.compartments ast)\n  ; jump_targets_wf      : well_formed_jump_targets  sst\n                                                     (Abs.compartments ast)\n  ; store_targets_wf     : well_formed_store_targets sst\n                                                     (Abs.compartments ast)\n  ; previous_refined     : refine_previous_b         (Abs.step_kind    ast)\n                                                     (Abs.previous     ast)\n                                                     sst\n  ; syscalls_refined     : refine_syscall_addrs_b    (Abs.mem          ast)\n                                                     (Symbolic.mem     sst)\n  ; internal_refined     : Sym.good_internal         sst }.\n\nGeneralizable All Variables.\n\nTheorem refine_good : forall `(REFINE : refine ast sst),\n  Abs.good_state ast ->\n  Sym.good_state sst.\nProof.\n  move=> [Apc AR AM AC Ask Aprev]\n         [SM SR [Spc Lpc] [Snext SiT SaJT SaST]]\n         [RPC RREGS RMEMS WDCOMPS WDIDS UIDS WFJTS WFSTS RPREV RSCS RINT]\n         /and4P [ELEM GOODS SS SP];\n    simpl in *.\n  split.\n  - destruct Lpc; try discriminate.\n    move: RPREV => /andP [/eqP? /eqP RPREV]; subst.\n    rewrite /get_compartment_id in RPREV.\n    case: pickP RPREV => //= => x /eqP RPREV.\n    have: Some x == Some x by apply eq_refl.\n    rewrite -(in_set1 (Some x)) -RPREV => /imsetP [y IN_y ->] SGET.\n      clear x RPREV.\n      exists y; move: SGET.\n    case SGET: (Sym.sget _ y) => [L|//].\n    case: L SGET => //=  [c' I W] SGET.\n    + rewrite SGET /= => [[?]]. subst c'.\n      by eauto.\n    + by have /= -> := SGET.\n  - assumption.\nQed.\n\nLtac unoption :=\n  repeat match goal with\n    | EQ  : Some _ = Some _ |- _ => inversion EQ; subst; clear EQ\n    | NEQ : Some _ = None   |- _ => discriminate\n    | NEQ : None   = Some   |- _ => discriminate\n    | EQ  : None   = None   |- _ => clear EQ\n  end.\n\nLemma get_compartment_id_in_compartment_eq (C : seq (Abs.compartment mt)) sst c p :\n  well_defined_compartments sst C ->\n  well_defined_ids sst C ->\n  unique_ids sst C ->\n  c \\in C ->\n  (get_compartment_id sst c == (omap Sym.data_tag_compartment (Sym.sget sst p))) =\n  (p \\in Abs.address_space c).\nProof.\n  move=> /(_ p) WDC WDID UNIQUE IN.\n  move: (WDID c IN).\n  case ID: (get_compartment_id sst c) => [cid|] // _.\n  apply/(sameP idP)/(iffP idP).\n\n  - move: ID.\n    rewrite /get_compartment_id.\n    case: pickP => // cid' /eqP Hcid' [E]. subst cid'.\n    move/(mem_imset (omap Sym.data_tag_compartment \\o Sym.sget sst)) => /=.\n    rewrite Hcid' in_set1.\n    by rewrite eq_sym.\n\n  - case GET: (Sym.sget sst p) WDC => [[cid' Ia Sa]|] //= /(_ erefl).\n    case E: (Abs.in_compartment_opt C p) => [c'|] // _ /eqP [E']. subst cid'.\n    case/Abs.in_compartment_opt_correct/andP: E => IN' INp.\n    suff {UNIQUE} ID' : get_compartment_id sst c' = Some cid.\n    { rewrite -ID' in ID.\n      by rewrite (UNIQUE _ _ IN IN' ID). }\n    move: (WDID c' IN').\n    rewrite /get_compartment_id.\n    case: pickP => // cid' /eqP Hcid' _.\n    move/(mem_imset (omap Sym.data_tag_compartment \\o Sym.sget sst)): INp.\n    rewrite Hcid' in_set1 /= GET /=.\n    by move/eqP=> ->.\nQed.\n\nLemma get_compartment_id_in_compartment (C : seq (Abs.compartment mt)) sst c p :\n  well_defined_compartments sst C ->\n  well_defined_ids sst C ->\n  unique_ids sst C ->\n  c \\in C ->\n  (get_compartment_id sst c = (omap Sym.data_tag_compartment (Sym.sget sst p))) ->\n  (p \\in Abs.address_space c).\nProof.\n  move=> WDC WDID UNIQUE IN H.\n  by rewrite -(get_compartment_id_in_compartment_eq _ WDC WDID UNIQUE IN) H.\nQed.\n\nLemma in_compartment_get_compartment_id (C : seq (Abs.compartment mt)) sst c p :\n  well_defined_compartments sst C ->\n  well_defined_ids sst C ->\n  unique_ids sst C ->\n  c \\in C ->\n  (p \\in Abs.address_space c) ->\n  get_compartment_id sst c = (omap Sym.data_tag_compartment (Sym.sget sst p)).\nProof.\n  move=> WDC WDID UNIQUE IN H.\n  apply/eqP.\n  by rewrite (get_compartment_id_in_compartment_eq _ WDC WDID UNIQUE IN) H.\nQed.\n\nLemma refined_reg_value : forall AR SR,\n  refine_registers AR SR ->\n  forall r, getm AR r = (svalue <$> getm SR r).\nProof.\n  move=> AR SR REFINE r;\n    rewrite /refine_registers /refine_reg_b /pointwise in REFINE.\n  specialize REFINE with r.\n  set oax := getm AR r in REFINE *; set osv := getm SR r in REFINE *;\n    destruct oax as [|], osv as [[? []]|]; simpl in *; try done.\n  by move/eqP in REFINE; subst.\nQed.\n\nLemma refined_mem_value : forall AM SM,\n  refine_memory AM SM ->\n  forall p, getm AM p = (svalue <$> getm SM p).\nProof.\n  move=> AM SM REFINE p;\n    rewrite /refine_memory /refine_mem_loc_b /pointwise in REFINE.\n  specialize REFINE with p.\n  set oax := getm AM p in REFINE *; set osv := getm SM p in REFINE *;\n    destruct oax as [|], osv as [[? []]|]; simpl in *; try done.\n  by move/eqP in REFINE; subst.\nQed.\n\nDefinition equilabeled (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some L1 , Some L2 => L1 = L2\n      | None    , None        => True\n      | _       , _           => False\n    end.\n\nDefinition equicompartmental (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some L1 , Some L2 => Sym.data_tag_compartment L1 =\n                             Sym.data_tag_compartment L2\n      | None    , None        => True\n      | _       , _           => False\n    end.\n\nDefinition tags_subsets (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some (Sym.DATA c1 I1 W1) , Some (Sym.DATA c2 I2 W2) =>\n        c1 = c2 /\\ I1 \\subset I2 /\\ W1 \\subset W2\n      | None , None =>\n        True\n      | _ , _ =>\n        False\n    end.\n\nDefinition tags_subsets_in (ps : {set word}) (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some (Sym.DATA c1 I1 W1) , Some (Sym.DATA c2 I2 W2) =>\n        (p \\in ps -> c1 = c2) /\\ I1 \\subset I2 /\\ W1 \\subset W2\n      | None , None =>\n        True\n      | _ , _ =>\n        False\n    end.\n\nDefinition tags_subsets_cid (cid : word) (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some (Sym.DATA c1 I1 W1) , Some (Sym.DATA c2 I2 W2) =>\n        (c1 = cid \\/ c2 = cid -> c1 = c2) /\\\n        I1 \\subset I2 /\\ W1 \\subset W2\n      | None , None =>\n        True\n      | _ , _ =>\n        False\n    end.\n\nDefinition tags_subsets_add_1 (c' : word)\n                              (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some (Sym.DATA c1 I1 W1) , Some (Sym.DATA c2 I2 W2) =>\n        c1 = c2                    /\\\n        (I1 = I2 \\/ c' |: I1 = I2) /\\\n        (W1 = W2 \\/ c' |: W1 = W2)\n      | None , None =>\n        True\n      | _ , _ =>\n        False\n    end.\n\nDefinition tags_subsets_add_1_in (ps : {set word})\n                                 (c' : word)\n                                 (sst1 sst2 : sstate) : Prop :=\n  forall p,\n    match Sym.sget sst1 p , Sym.sget sst2 p with\n      | Some (Sym.DATA c1 I1 W1) , Some (Sym.DATA c2 I2 W2) =>\n        (p \\in ps -> c1 = c2)      /\\\n        (I1 = I2 \\/ c' |: I1 = I2) /\\\n        (W1 = W2 \\/ c' |: W1 = W2)\n      | None , None =>\n        True\n      | _ , _ =>\n        False\n    end.\n\nLemma tags_subsets_in_tail : forall p ps sst sst',\n  tags_subsets_in (p |: ps) sst sst' ->\n  tags_subsets_in ps sst sst'.\nProof.\n  rewrite /tags_subsets_in /=; move=> p ps sst sst' TSI a.\n  specialize TSI with a.\n  destruct (Sym.sget sst  a) as [[ ]|],\n           (Sym.sget sst' a) as [[ ]|];\n    try done.\n  move: TSI => [EQ [? ?]]; repeat split; auto => Hin.\n  suff: a \\in p |: ps by auto.\n  by rewrite in_setU1 Hin orbT.\nQed.\n\nLemma tags_subsets_trans : forall sst sst' sst'',\n  tags_subsets sst  sst'  ->\n  tags_subsets sst' sst'' ->\n  tags_subsets sst  sst''.\nProof.\n  move=> sst sst' sst'' TSI TSI' p.\n  specialize (TSI p); specialize (TSI' p).\n  destruct (Sym.sget sst   p) as [[ ]|],\n           (Sym.sget sst'  p) as [[ ]|],\n           (Sym.sget sst'' p) as [[ ]|];\n    try done.\n  repeat invh and; subst; auto.\n  by eauto using subset_trans.\nQed.\n\nLemma tags_subsets_in_trans : forall ps sst sst' sst'',\n  tags_subsets_in ps sst  sst'  ->\n  tags_subsets_in ps sst' sst'' ->\n  tags_subsets_in ps sst  sst''.\nProof.\n  move=> ps sst sst' sst'' TSI TSI' p.\n  specialize (TSI p); specialize (TSI' p).\n  destruct (Sym.sget sst   p) as [[ ]|],\n           (Sym.sget sst'  p) as [[ ]|],\n           (Sym.sget sst'' p) as [[ ]|];\n    try done.\n  move: TSI TSI' => [H1 [H2 H3]] [H1' [H2' H3']].\n  repeat split; solve [intuition congruence|eauto using subset_trans].\nQed.\n\nLemma tags_subsets_add_1_trans : forall c' sst sst' sst'',\n  tags_subsets_add_1 c' sst  sst'  ->\n  tags_subsets_add_1 c' sst' sst'' ->\n  tags_subsets_add_1 c' sst  sst''.\nProof.\n  move=> c' sst sst' sst'' TSA TSA' p.\n  specialize (TSA p); specialize (TSA' p).\n  destruct (Sym.sget sst   p) as [[ ]|],\n           (Sym.sget sst'  p) as [[ ]|],\n           (Sym.sget sst'' p) as [[ ]|];\n    try done.\n  move: TSA TSA' => [H1 [H2 H3]] [H1' [H2' H3']].\n  repeat split.\n  - by subst.\n  - destruct H2,H2'; subst; try rewrite setUA setUid; auto.\n  - destruct H3,H3'; subst; try rewrite setUA setUid; auto.\nQed.\n\nLemma tags_subsets_add_1_in_trans : forall ps c' sst sst' sst'',\n  tags_subsets_add_1_in ps c' sst  sst'  ->\n  tags_subsets_add_1_in ps c' sst' sst'' ->\n  tags_subsets_add_1_in ps c' sst  sst''.\nProof.\n  move=> ps c' sst sst' sst'' TSAI TSAI' p.\n  specialize (TSAI p); specialize (TSAI' p).\n  destruct (Sym.sget sst   p) as [[ ]|],\n           (Sym.sget sst'  p) as [[ ]|],\n           (Sym.sget sst'' p) as [[ ]|];\n    try done.\n  move: TSAI TSAI' => [H1 [H2 H3]] [H1' [H2' H3']].\n  repeat split.\n  - intuition congruence.\n  - destruct H2,H2'; subst; try rewrite setUA setUid; auto.\n  - destruct H3,H3'; subst; try rewrite setUA setUid; auto.\nQed.\n\nLemma tags_subsets_any_in : forall ps sst sst',\n  tags_subsets       sst sst' ->\n  tags_subsets_in ps sst sst'.\nProof.\n  move=> ps sst sst' TS p; specialize (TS p).\n  destruct (Sym.sget sst  p) as [[ ]|],\n           (Sym.sget sst' p) as [[ ]|];\n    try done.\n  repeat invh and; subst; auto.\nQed.\n\nLemma tags_subsets_add_1_any_in : forall ps c' sst sst',\n  tags_subsets_add_1       c' sst sst' ->\n  tags_subsets_add_1_in ps c' sst sst'.\nProof.\n  move=> ps c' sst sst' TSA p; specialize (TSA p).\n  destruct (Sym.sget sst  p) as [[ ]|],\n           (Sym.sget sst' p) as [[ ]|];\n    try done.\n  repeat invh and; subst; auto.\nQed.\n\nLemma get_compartment_id_same : forall sst sst' c,\n  equilabeled sst sst' ->\n  get_compartment_id sst c = get_compartment_id sst' c.\nProof.\n  intros sst sst' [A J S] SAME.\n  rewrite /get_compartment_id.\n  apply eq_pick => p.\n  apply f_equal2 => //.\n  apply eq_imset => {p} p /=.\n  move: (SAME p).\n  case: (Sym.sget sst p) => [l|]; case: (Sym.sget sst' p) => [l'|] //.\n  congruence.\nQed.\n\nTheorem isolate_create_set_refined : forall AM SM,\n  refine_memory AM SM ->\n  forall p, isolate_create_set id AM p = isolate_create_set svalue SM p.\nProof.\n  move=> AM SM REFINE p;\n    rewrite /refine_memory /refine_mem_loc_b /pointwise in REFINE.\n  rewrite /isolate_create_set.\n\n  erewrite refined_mem_value; [|eassumption].\n  set G := getm SM p; destruct G as [[wpairs ?]|]; subst; simpl; try done.\n\n  move: (_ (ord_of_word wpairs)) (p + 1)%w => pairs.\n\n  induction pairs as [|pairs]; simpl; [reflexivity | intros start].\n  rewrite IHpairs; f_equal.\n  rewrite /isolate_get_range.\n\n  repeat (erewrite refined_mem_value; [|eassumption]).\n  set G := getm SM start; destruct G as [[low ?]|]; subst; simpl; try done.\n  by set G := getm SM (start + 1)%w; destruct G as [[high ?]|]; subst; simpl.\nQed.\n\nTheorem retag_set_preserves_memory_refinement : forall ok retag ps sst sst' AM,\n  Sym.retag_set ok retag ps sst ?= sst' ->\n  refine_memory AM (Symbolic.mem sst) ->\n  refine_memory AM (Symbolic.mem sst').\nProof.\n  rewrite /Sym.retag_set /Sym.retag_one.\n  intros ok retag ps; induction ps as [|p ps]; simpl;\n    intros sst sst'' AM RETAG REFINE.\n  - by inversion RETAG; subst.\n  - let I := fresh \"I\"\n    in undo1 RETAG sst'; undoDATA def_sst' x c I W; undo1 def_sst' OK;\n       destruct (retag p c I W) as [c' I' W'] eqn:TAG; try discriminate.\n    apply IHps with (AM := AM) in RETAG; [assumption|].\n    rewrite /refine_memory /refine_mem_loc_b /pointwise in REFINE *; intros a;\n      specialize REFINE with a.\n    destruct (getm AM) as [w|],\n             (getm (Symbolic.mem sst)) as [[w' []]|] eqn:GET';\n      try done;\n      try (move/eqP in REFINE; subst w').\n    + destruct (a == p) eqn:EQ; move/eqP in EQ; subst.\n      * generalize def_sst' => SUPD.\n        eapply Sym.sget_supd_eq in def_sst'.\n        destruct sst as [SM SR SPC [snext SiT SaJT SaST]];\n          rewrite /Sym.sget /= GET' in def_xcIW.\n        inversion def_xcIW; subst.\n        eapply Sym.get_supd_eq in SUPD; [|eassumption].\n        by rewrite SUPD.\n      * eapply Sym.get_supd_neq in def_sst'; try eassumption.\n        by rewrite def_sst' GET'.\n    + eapply Sym.get_supd_none in def_sst'; [|eassumption].\n      by rewrite def_sst'.\nQed.\n\nLemma in_compartment_update A J Sa J' Sa' AC p c :\n  AC \u22a2 p \u2208 c ->\n  exists c', <<A,J,Sa>> :: rem_all <<A,J',Sa'>> AC \u22a2 p \u2208 c'.\nProof.\n  rewrite /rem_all.\n  elim: AC => [|c' AC IH]; first by rewrite /Abs.in_compartment.\n  rewrite /Abs.in_compartment in_cons => /andP [/orP [/eqP <-| Hin] Has].\n  - rewrite /=.\n    have [E|NE] := altP (c =P <<A,J',Sa'>>).\n    + exists <<A,J,Sa>> => /=.\n      rewrite E in Has.\n      by rewrite Has /= in_cons eqxx.\n    + exists c.\n      by rewrite Has /= !inE eqxx orbT.\n  - have /IH {IH} [c'' /andP [Hin' ?]] : AC \u22a2 p \u2208 c by rewrite /Abs.in_compartment Has Hin.\n    exists c''.\n    apply/andP; split => //.\n    rewrite !inE in Hin' *.\n    case/orP: Hin' => [-> //| Hin' /=].\n    have [E|NE] := altP (c' =P <<A,J',Sa'>>).\n    + by rewrite /= Hin' orbT.\n    + by rewrite inE Hin' !orbT.\nQed.\n\nLemma in_compartment_update' A J Sa J' Sa' AC p :\n  Abs.in_compartment_opt AC p ->\n  Abs.in_compartment_opt (<<A,J,Sa>> :: rem_all <<A,J',Sa'>> AC) p.\nProof.\n  case E: (Abs.in_compartment_opt _ _) => [c|] // _.\n  move/Abs.in_compartment_opt_correct in E.\n  suff [? -> //] : exists c', Abs.in_compartment_opt (<<A,J,Sa>> :: rem_all <<A,J',Sa'>> AC) p ?= c'.\n  have [c' Hc'] := @in_compartment_update A J Sa J' Sa' AC p c E.\n  by apply/Abs.in_compartment_opt_present; eassumption.\nQed.\n\nLemma supd_refine_memory AM sst sst' p c i w :\n  Sym.supd sst p (Sym.DATA c i w) ?= sst' ->\n  refine_memory AM (Symbolic.mem sst) ->\n  refine_memory AM (Symbolic.mem sst').\nProof.\n  case: sst => m r pc [? ? ? ?]; case: sst' => m' r' pc' [? ? ? ?].\n  rewrite /Sym.supd /=.\n  move=> UPD REF p'.\n  case REP: (repm m p _) UPD => [m''|].\n  - generalize (repmE REP p') => {REP} REP [<- _ _ _ _ _ _].\n    rewrite REP.\n    have [->|NE] := (p' =P p); last exact: REF.\n    move: {REF} (REF p).\n    case: (getm AM p) => [v1|];\n    by case: (getm m p) => [[v2 [? ? ?]]|].\n  - repeat case: (p =P _) => _ //=; move=> [<- _ _ _ _ _ _]; by apply REF.\nQed.\n\nLemma supd_refine_syscall_addrs_b AM sst sst' p l :\n  Sym.supd sst p l ?= sst' ->\n  refine_syscall_addrs_b AM (Symbolic.mem sst) ->\n  refine_syscall_addrs_b AM (Symbolic.mem sst').\nProof.\n  move=> UPD /and3P [Ha Hs Hu].\n  apply/and3P; split=> // {Ha Hu}; apply/allP=> x /(allP Hs).\n  case E: (getm _ _) => [//|] _.\n  by rewrite (Sym.get_supd_none E UPD).\nQed.\n\nLemma sget_supd_good_internal (sst sst' : sstate) p (c : mword mt) I1 W1 I2 W2 :\n  (forall c' : mword mt, c' \\in I2 :|: W2 -> (c' < Sym.next_id (Symbolic.internal sst))%ord) ->\n  Sym.sget sst p ?= Sym.DATA c I1 W1 ->\n  Sym.supd sst p (Sym.DATA c I2 W2) ?= sst' ->\n  Sym.good_internal sst ->\n  Sym.good_internal sst'.\nProof.\n  move=> Hbounded_new Hsget Hsupd [Hbounded Hisolate].\n  split.\n  - move=> p' cid I W.\n    rewrite (Sym.sget_supd Hsupd)\n           -(Sym.supd_preserves_next_id Hsupd).\n    have [_ {p'} [<- <- <- {cid I W}]|_] := p' =P p; last by apply Hbounded.\n    move=> cid.\n    rewrite -setUA in_setU1.\n    case/orP => [/eqP -> {cid}|]; last by eauto.\n    apply: (Hbounded _ _ _ _ Hsget).\n    by rewrite in_setU in_setU1 eqxx.\n  - move=> p' sc.\n    rewrite !(Sym.sget_supd Hsupd).\n    have [-> {p'}|_] := p' =P p;\n    have [-> {sc}|_] := sc =P p => //=.\n    + move=> sc_is_sc E.\n      apply: (Hisolate p sc sc_is_sc).\n      by rewrite Hsget /=.\n    + move=> sc_is_sc E.\n      apply: (Hisolate p' p sc_is_sc).\n      by rewrite E Hsget.\n    + move=> sc_is_sc E.\n      by apply: (Hisolate p' sc sc_is_sc).\nQed.\n\nLemma sget_irrelevancies r' pc' m int r pc :\n  Sym.sget (SState m r pc int) =\n  Sym.sget (SState m r' pc' int).\nProof. reflexivity. Qed.\n\nLemma sget_next_irrelevant next' next m r pc iT aJT aST :\n  Sym.sget (SState m r pc (SInternal next  iT aJT aST)) =\n  Sym.sget (SState m r pc (SInternal next' iT aJT aST)).\nProof. reflexivity. Qed.\n\nLemma supd_tags_subsets sst sst' p c I1 W1 I2 W2 :\n  Sym.sget sst p ?= Sym.DATA c I1 W1 ->\n  Sym.supd sst p (Sym.DATA c I2 W2) ?= sst' ->\n  I1 \\subset I2 -> W1 \\subset W2 ->\n  tags_subsets sst sst'.\nProof.\n  move=> GET UPD HI HW p'.\n  have [{p'} -> //|NE] := altP (p' =P p).\n  { by rewrite GET (Sym.sget_supd UPD) eqxx. }\n  rewrite (Sym.sget_supd UPD) (negbTE NE).\n  by case: (Sym.sget _ _) => [[]|] //=.\nQed.\n\nLemma tags_subsets_irrelevancies r' pc' m int r pc sst :\n  tags_subsets sst (SState m r' pc' int) ->\n  tags_subsets sst (SState m r pc int).\nProof.\n  move=> H p.\n  move: H => /(_ p).\n  by rewrite (sget_irrelevancies r' pc').\nQed.\n\nLemma get_compartment_id_supd_same sst sst' p cid I1 W1 I2 W2 :\n  Sym.sget sst p = Some (Sym.DATA cid I1 W1) ->\n  Sym.supd sst p (Sym.DATA cid I2 W2) = Some sst' ->\n  get_compartment_id sst =1 get_compartment_id sst'.\nProof.\n  move=> GET UPD c.\n  apply/eq_pick => c'.\n  apply/f_equal2 => // {c'}.\n  apply/eq_imset => p' /=.\n  rewrite (Sym.sget_supd UPD).\n  have [{p'} -> /=|//] := (p' =P p); by rewrite GET.\nQed.\n\nLemma get_compartment_id_irrelevancies r' pc' m int r pc :\n  get_compartment_id (SState m r pc int) =1\n  get_compartment_id (SState m r' pc' int).\nProof. by []. Qed.\n\nLemma get_compartment_id_irrelevancies' r' pc' next' m r pc next a b c :\n  get_compartment_id (SState m r pc (Sym.Internal next a b c)) =\n  get_compartment_id (SState m r' pc' (Sym.Internal next' a b c)).\nProof. by []. Qed.\n\nLemma get_compartment_id_irrelevancies_bump m r pc si :\n  get_compartment_id (SState m r pc (Sym.bump_next_id si)) =\n  get_compartment_id (SState m r pc si).\nProof. by case: si. Qed.\n\nLemma unique_ids_replace sst sst' p pcid I1 I2 W1 W2 C A J1 J2 S1 S2 :\n  unique_ids sst C ->\n  Sym.sget sst p = Some (Sym.DATA pcid I1 W1) ->\n  Sym.supd sst p (Sym.DATA pcid I2 W2) = Some sst' ->\n  <<A,J1,S1>> \\in C ->\n  unique_ids sst' (<<A,J2,S2>> :: rem_all <<A,J1,S1>> C).\nProof.\n  move=> UNIQUE GET UPD IN c1 c2.\n  rewrite !in_cons !mem_filter.\n  case/orP=> [/eqP -> {c1}|/andP [not_prev1 IN1]];\n  case/orP=> [/eqP -> {c2}|/andP [not_prev2 IN2]] //.\n  - rewrite -!(get_compartment_id_supd_same GET UPD) => /(UNIQUE _ _ IN IN2) E.\n    by rewrite -E /= eqxx in not_prev2.\n  - rewrite -!(get_compartment_id_supd_same GET UPD) => /(UNIQUE _ _ IN1 IN) E.\n    by rewrite -E /= eqxx in not_prev1.\n  - by rewrite -!(get_compartment_id_supd_same GET UPD) => /(UNIQUE _ _ IN1 IN2) E.\nQed.\n\nLemma well_formed_targets_augment (targets : Abs.compartment mt -> {set word})\n                                  (sources : data_tag -> {set word})\n                                  sst sst' p pcid I1 I2 W1 W2 Ss C c cid c' :\n  well_formed_targets targets sources sst C ->\n  unique_ids sst C ->\n  Sym.sget sst p = Some (Sym.DATA pcid I1 W1) ->\n  Sym.supd sst p (Sym.DATA pcid I2 W2) = Some sst' ->\n  get_compartment_id sst c = Some cid ->\n  c \\in C ->\n  Abs.address_space c = Abs.address_space c' ->\n  targets c' = p |: targets c ->\n  sources (Sym.DATA pcid I2 W2) = cid |: Ss ->\n  sources (Sym.DATA pcid I1 W1) = Ss ->\n  well_formed_targets targets sources sst' (c' :: rem_all c C).\nProof.\n  move=> WF UNIQUE GET UPD ID c_in_C AS TARGETS SOURCES2 SOURCES1  c'' cid''.\n  rewrite in_cons mem_filter\n          -(get_compartment_id_supd_same GET UPD)\n          => /orP [/eqP ->|/= /andP [Hneq c''_in_C]] ID'.\n  - have {cid'' ID'} ->: cid'' = cid.\n    { rewrite /get_compartment_id ?AS in ID ID'.\n      congruence. }\n    rewrite TARGETS (WF _ _ c_in_C ID).\n    apply/eqP. rewrite eqEsubset. apply/andP. split.\n    + rewrite subUset sub1set in_set (Sym.sget_supd UPD)\n              eqxx /= SOURCES2 /= in_setU1 eqxx /=.\n      apply/subsetP => p'.\n      rewrite !in_set (Sym.sget_supd UPD).\n      have [{p'} -> /=|//] := (p' =P p).\n      by rewrite SOURCES2 /= in_setU1 eqxx.\n    + apply/subsetP => p'.\n      rewrite !in_set (Sym.sget_supd UPD).\n      by have [{p'} ->|] := (p' =P p).\n  - rewrite (WF _ _ c''_in_C ID').\n    apply/eqP. rewrite eqEsubset. apply/andP.\n    split; apply/subsetP => p';\n    rewrite !in_set\n            (Sym.sget_supd UPD);\n    have [{p'} ->|] //= := (p' =P p);\n    rewrite SOURCES2 GET /= SOURCES1 /= in_setU1; first by rewrite orbC => ->.\n    case/orP => [/eqP E|//].\n    rewrite E -?ID{cid'' E} in ID' *.\n    by rewrite (UNIQUE _ _ c''_in_C c_in_C ID') eqxx in Hneq.\nQed.\n\nLemma well_formed_targets_same (targets : Abs.compartment mt -> {set word})\n                               (sources : data_tag -> {set word})\n                               sst sst' p pcid I1 I2 W1 W2 Ss C c cid c' :\n  well_formed_targets targets sources sst C ->\n  unique_ids sst C ->\n  Sym.sget sst p = Some (Sym.DATA pcid I1 W1) ->\n  Sym.supd sst p (Sym.DATA pcid I2 W2) = Some sst' ->\n  get_compartment_id sst c = Some cid ->\n  c \\in C ->\n  Abs.address_space c = Abs.address_space c' ->\n  targets c' = targets c ->\n  sources (Sym.DATA pcid I2 W2) = Ss ->\n  sources (Sym.DATA pcid I1 W1) = Ss ->\n  well_formed_targets targets sources sst' (c' :: rem_all c C).\nProof.\n  move=> WF UNIQUE GET UPD ID c_in_C AS TARGETS SOURCES2 SOURCES1  c'' cid''.\n  rewrite in_cons mem_filter\n          -(get_compartment_id_supd_same GET UPD)\n          => /orP [/eqP ->|/= /andP [Hneq c''_in_C]] ID'.\n  - have {cid'' ID'} ->: cid'' = cid.\n    { rewrite /get_compartment_id ?AS in ID ID'.\n      congruence. }\n    rewrite TARGETS (WF _ _ c_in_C ID).\n    apply/eqP. rewrite eqEsubset. apply/andP. split.\n    + apply/subsetP => p'.\n      rewrite !in_set (Sym.sget_supd UPD).\n      have [{p'} -> /=|//] := (p' =P p).\n      by rewrite SOURCES2 GET /= SOURCES1 /=.\n    + apply/subsetP => p'.\n      rewrite !in_set (Sym.sget_supd UPD).\n      have [{p'} ->/=|//] := (p' =P p).\n      by rewrite SOURCES2 /= GET /= SOURCES1 /=.\n  - rewrite (WF _ _ c''_in_C ID').\n    apply/eqP. rewrite eqEsubset. apply/andP.\n    by split; apply/subsetP => p';\n    rewrite !in_set\n            (Sym.sget_supd UPD);\n    have [{p'} ->/=|//] := (p' =P p);\n    rewrite SOURCES2 GET /= SOURCES1 /=.\nQed.\n\nLemma unique_ids_irrelevancies r' pc' m int r pc :\n  unique_ids (SState m r pc int) =\n  unique_ids (SState m r' pc' int).\nProof. by []. Qed.\n\nLemma well_formed_targets_irrelevancies r' pc' m int r pc targets sources :\n  well_formed_targets targets sources (SState m r pc int) =\n  well_formed_targets targets sources (SState m r' pc' int).\nProof. by []. Qed.\n\nTheorem add_to_jump_targets_refined : forall ast sst sst',\n  Abs.good_state ast ->\n  refine ast sst ->\n  Sym.add_to_jump_targets sst ?= sst' ->\n  exists ast',\n    Abs.semantics (Abs.add_to_jump_targets (mt:=mt)) ast ?= ast' /\\\n    refine ast' sst'.\nProof.\n  move=> ast sst sst' AGOOD REFINE ADD.\n  assert (SGOOD : Sym.good_state sst) by (eapply refine_good; eassumption).\n  destruct REFINE as [RPC RREGS RMEMS COMPSWD IDSWD IDSU JTWF STWF RPREV RSC RINT],\n           ast    as [Apc AR    AM    AC    Ask Aprev],\n           sst    as [SM SR Spc [Snext SiT SaJT SaST]].\n  generalize SGOOD; move=> [SGPC SGINT].\n  case/and4P: (AGOOD) => AIN /andP [ANOL ACC] ASS ASP.\n  rewrite /Abs.semantics /Abs.add_to_jump_targets\n          /Abs.add_to_compartment_component\n          (lock Abs.in_compartment_opt);\n    simpl in *.\n  rewrite /refine_pc_b in RPC.\n  destruct Spc as [pc [F cid']]; try done; move/eqP in RPC; subst.\n\n  move/id in ADD;\n    undo1 ADD LI;\n    undo1 ADD cid_sys;\n    destruct LI as [cid I W]; try discriminate;\n    undo1 ADD NEQ_cid_sys;\n    undo2 ADD p Lp;\n    undoDATA ADD x cid'' I'' W'';\n    undo1 ADD OK;\n    undo1 ADD s';\n    undo2 ADD pc' Lpc';\n    undoDATA ADD i' cid_next I_next W_next;\n    undo1 ADD NEXT_EQ; move/eqP in NEXT_EQ; subst cid_next;\n    undo1 ADD NEXT;\n    destruct s' as [M_next R_next not_pc si_next];\n    unoption.\n\n  move: (COMPSWD pc).\n  rewrite def_LI => /(_ erefl).\n  case IN_c: (Abs.in_compartment_opt AC pc) => [c_sys|] _ //.\n  move/Abs.in_compartment_opt_correct in IN_c.\n\n  rewrite /Sym.can_execute /= in def_cid_sys.\n  undo1 def_cid_sys COND; unoption.\n\n  move: RPREV => /andP [/eqP ? /eqP RPREV]; subst.\n  have -> /=: Abs.permitted_now_in AC F Aprev pc ?= c_sys.\n  { rewrite /Abs.permitted_now_in\n            (Abs.in_compartment_opt_sound ANOL IN_c) /=.\n    rewrite eq_sym (negbTE NEQ_cid_sys) /= in COND.\n    case/andP: COND => /eqP -> Hin.\n    by rewrite eqxx /= (JTWF _ _ AIN RPREV) in_set def_LI /= Hin orbT. }\n\n  have R_c_sys: get_compartment_id\n                      (SState SM SR pc@(Sym.PC F cid')\n                              (SInternal Snext SiT SaJT SaST))\n                      c_sys\n                    = Some cid_sys.\n  { case/andP: IN_c => IN1 IN2.\n    by rewrite (in_compartment_get_compartment_id COMPSWD IDSWD IDSU IN1 IN2) def_LI. }\n\n  rewrite /Sym.good_pc_tag in SGPC; move: SGPC => [p' [I' [W' def_cid']]].\n\n  assert (SYS_SEP : Aprev != c_sys). {\n    apply/eqP; intro; subst.\n    replace cid_sys with cid' in * by congruence.\n    rewrite eq_refl in NEQ_cid_sys; discriminate.\n  }\n  rewrite SYS_SEP; simpl.\n\n  move/(_ syscall_arg1): (RREGS).\n  rewrite def_p_Lp.\n  case: (AR syscall_arg1) => [Ap|]; destruct Lp; try done;\n    move/eqP => ?; subst; simpl.\n\n  destruct Aprev as [Aprev Jprev Sprev]; simpl.\n\n  have IC_p': p' \\in Aprev.\n  { apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    by rewrite def_cid'. }\n\n  have ->: p \\in Aprev :|: Jprev. {\n    rewrite in_setU. apply/orP.\n    case/orP: OK => [/eqP E|OK].\n    - subst cid''. left.\n      apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n      by rewrite RPREV def_xcIW.\n    - right.\n      have /= -> := JTWF _ _ AIN RPREV.\n      by rewrite in_set def_xcIW.\n  }\n\n  move/(_ ra): (RREGS).\n  rewrite def_pc'_Lpc'.\n  case: (AR ra) => [Apc'|]; destruct Lpc'; try done;\n    move/eqP => ?; subst Apc'; simpl.\n\n  have IN_pc' : pc' \\in Aprev.\n  { apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    have [E|NE] := (pc' =P p).\n    - subst pc'.\n      rewrite (Sym.sget_supd_eq def_s') in def_xcIW0.\n      rewrite def_xcIW /=.\n      congruence.\n    - by rewrite -(Sym.sget_supd_neq NE def_s') def_xcIW0 /=. }\n\n  rewrite -(lock _) /= IN_pc' /= eq_refl.\n\n  have IN_Jsys : pc' \\in Abs.jump_targets c_sys. {\n    rewrite eq_sym (negbTE NEQ_cid_sys) /= in COND.\n    case/andP: IN_c => IC_c _.\n    rewrite (JTWF _ _ IC_c R_c_sys) in_set.\n    have [E|NE] := (pc' =P p).\n    - subst pc'.\n      rewrite def_xcIW /=.\n      rewrite (Sym.sget_supd def_s') eqxx in def_xcIW0.\n      move: def_xcIW0 => [? ? ?]; subst cid'' I_next W_next.\n      by rewrite (in_setU1 cid_sys) eq_sym (negbTE NEQ_cid_sys) /= in NEXT.\n    - by rewrite -(Sym.sget_supd_neq NE def_s') def_xcIW0 /=.\n  }\n\n  rewrite IN_Jsys. eexists; split; [reflexivity|].\n  have /= E := Sym.supd_preserves_regs def_s'.\n  subst R_next.\n\n  constructor => //=.\n  - exact: (supd_refine_memory def_s' RMEMS).\n  - move=> p''.\n    rewrite (sget_irrelevancies SR not_pc).\n    move=> /(Sym.sget_supd_inv def_s')/COMPSWD.\n    by apply/in_compartment_update'.\n  - move=> c''.\n    rewrite  (get_compartment_id_irrelevancies SR not_pc)\n            -(get_compartment_id_supd_same def_xcIW def_s')\n             in_cons mem_filter => /orP [/eqP {c''} -> | /andP [_ Hc'']].\n    + exact: (IDSWD _ AIN).\n    + exact: (IDSWD _ Hc'').\n  - rewrite (unique_ids_irrelevancies SR not_pc).\n    apply/(unique_ids_replace IDSU def_xcIW def_s' AIN).\n  - rewrite /well_formed_jump_targets\n            (well_formed_targets_irrelevancies SR not_pc).\n    apply/(well_formed_targets_augment JTWF IDSU def_xcIW def_s' RPREV AIN);\n    try reflexivity.\n  - rewrite /well_formed_store_targets\n            (well_formed_targets_irrelevancies SR not_pc).\n    apply/(well_formed_targets_same STWF IDSU def_xcIW def_s' RPREV AIN);\n    try reflexivity.\n  - by rewrite /refine_previous_b /=\n               (get_compartment_id_irrelevancies SR not_pc)\n              -(get_compartment_id_supd_same def_xcIW def_s')\n               R_c_sys.\n  - exact: (supd_refine_syscall_addrs_b def_s').\n  - have in_range : forall c' : [ordType of mword mt],\n                      c' \\in (cid' |: I'') :|: W'' ->\n                      (c' < Sym.next_id\n                              (Symbolic.internal\n                                 (SState SM SR\n                                         pc@(Sym.PC F cid')\n                                         (SInternal Snext SiT SaJT SaST))))%ord.\n    { move=> c'.\n      case: SGINT => Hbounded Hisolate.\n      rewrite -setUA in_setU1=> /orP [/eqP->{c'}|IN_IW].\n      - apply: Hbounded; try eapply def_cid'.\n        by rewrite in_setU in_setU1 eqxx.\n      - apply: Hbounded; try apply def_xcIW.\n        by rewrite -setUA in_setU1 IN_IW orbT.\n    }\n    exact: (sget_supd_good_internal in_range def_xcIW def_s').\nQed.\n\nTheorem add_to_store_targets_refined : forall ast sst sst',\n  Abs.good_state ast ->\n  refine ast sst ->\n  Sym.add_to_store_targets sst ?= sst' ->\n  exists ast',\n    Abs.semantics (Abs.add_to_store_targets (mt:=mt)) ast ?= ast' /\\\n    refine ast' sst'.\nProof.\n  move=> ast sst sst' AGOOD REFINE ADD.\n  assert (SGOOD : Sym.good_state sst) by (eapply refine_good; eassumption).\n  destruct REFINE as [RPC RREGS RMEMS COMPSWD IDSWD IDSU JTWF STWF RPREV RSC RINT],\n           ast    as [Apc AR    AM    AC    Ask Aprev],\n           sst    as [SM SR Spc [Snext SiT SaJT SaST]].\n  generalize SGOOD; move=> [SGPC SGINT].\n  case/and4P: (AGOOD) => AIN /andP [ANOL ACC] ASS ASP.\n  rewrite /Abs.semantics /Abs.add_to_store_targets\n          /Abs.add_to_compartment_component\n          (lock Abs.in_compartment_opt);\n    simpl in *.\n  rewrite /refine_pc_b in RPC.\n  destruct Spc as [pc [F cid']]; try done; move/eqP in RPC; subst.\n\n  move/id in ADD;\n    undo1 ADD LI;\n    undo1 ADD cid_sys;\n    destruct LI as [cid I W]; try discriminate;\n    undo1 ADD NEQ_cid_sys;\n    undo2 ADD p Lp;\n    undoDATA ADD x cid'' I'' W'';\n    undo1 ADD OK;\n    undo1 ADD s';\n    undo2 ADD pc' Lpc';\n    undoDATA ADD i' cid_next I_next W_next;\n    undo1 ADD NEXT_EQ; move/eqP in NEXT_EQ; subst cid_next;\n    undo1 ADD NEXT;\n    destruct s' as [M_next R_next not_pc si_next];\n    unoption.\n\n  move: (COMPSWD pc).\n  rewrite def_LI => /(_ erefl).\n  case IN_c: (Abs.in_compartment_opt AC pc) => [c_sys|] _ //.\n  move/Abs.in_compartment_opt_correct in IN_c.\n\n  rewrite /Sym.can_execute /= in def_cid_sys.\n  undo1 def_cid_sys COND; unoption.\n\n  move: RPREV => /andP [/eqP ? /eqP RPREV]; subst.\n  have -> /=: Abs.permitted_now_in AC F Aprev pc ?= c_sys.\n  { rewrite /Abs.permitted_now_in\n            (Abs.in_compartment_opt_sound ANOL IN_c) /=.\n    rewrite eq_sym (negbTE NEQ_cid_sys) /= in COND.\n    case/andP: COND => /eqP -> Hin.\n    by rewrite eqxx /= (JTWF _ _ AIN RPREV) in_set def_LI /= Hin orbT. }\n\n  have R_c_sys: get_compartment_id\n                      (SState SM SR pc@(Sym.PC F cid')\n                              (SInternal Snext SiT SaJT SaST))\n                      c_sys\n                    = Some cid_sys.\n  { case/andP: IN_c => IN1 IN2.\n    by rewrite (in_compartment_get_compartment_id COMPSWD IDSWD IDSU IN1 IN2) def_LI. }\n\n  rewrite /Sym.good_pc_tag in SGPC; move: SGPC => [p' [I' [W' def_cid']]].\n\n  have -> /=: Aprev != c_sys. {\n    apply/eqP; intro; subst.\n    replace cid_sys with cid' in * by congruence.\n    rewrite eq_refl in NEQ_cid_sys; discriminate.\n  }\n\n  move/(_ syscall_arg1): (RREGS).\n  rewrite def_p_Lp.\n  case: (AR syscall_arg1) => [Ap|]; destruct Lp; try done;\n    move/eqP => ?; subst Ap; simpl.\n\n  destruct Aprev as [Aprev Jprev Sprev]; simpl.\n\n  have IC_p': p' \\in Aprev.\n  { apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    by rewrite def_cid'. }\n\n  have ->: p \\in Aprev :|: Sprev. {\n    rewrite in_setU. apply/orP.\n    case/orP: OK => [/eqP E|OK].\n    - subst cid''. left.\n      apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n      by rewrite RPREV def_xcIW.\n    - right.\n      have /= -> := STWF _ _ AIN RPREV.\n      by rewrite in_set def_xcIW.\n  }\n\n  move/(_ ra): (RREGS).\n  rewrite def_pc'_Lpc'.\n  case: (AR ra) => [Apc'|]; destruct Lpc'; try done;\n    move/eqP=> ?; subst Apc'; simpl.\n\n  have IN_pc' : pc' \\in Aprev.\n  { apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    have [E|NE] := (pc' =P p).\n    - subst pc'.\n      rewrite (Sym.sget_supd_eq def_s') in def_xcIW0.\n      rewrite def_xcIW /=.\n      congruence.\n    - by rewrite -(Sym.sget_supd_neq NE def_s') def_xcIW0 /=. }\n\n  rewrite -(lock _) /= IN_pc' /= eq_refl.\n\n  have IN_Jsys : pc' \\in Abs.jump_targets c_sys. {\n    rewrite eq_sym (negbTE NEQ_cid_sys) /= in COND.\n    case/andP: IN_c => IC_c _.\n    rewrite (JTWF _ _ IC_c R_c_sys) in_set.\n    have [E|NE] := (pc' =P p).\n    - subst pc'.\n      rewrite def_xcIW /=.\n      rewrite (Sym.sget_supd def_s') eqxx in def_xcIW0.\n      by move: def_xcIW0 => [? ? ?]; subst cid'' I_next W_next.\n    - by rewrite -(Sym.sget_supd_neq NE def_s') def_xcIW0 /=.\n  }\n\n  rewrite IN_Jsys. eexists; split; [reflexivity|].\n  have /= E := Sym.supd_preserves_regs def_s'.\n  subst R_next.\n\n  constructor => //=.\n  - exact: (supd_refine_memory def_s' RMEMS).\n  - move=> p''.\n    rewrite (sget_irrelevancies SR not_pc).\n    move=> /(Sym.sget_supd_inv def_s')/COMPSWD.\n    by apply/in_compartment_update'.\n  - move=> c''.\n    rewrite  (get_compartment_id_irrelevancies SR not_pc)\n            -(get_compartment_id_supd_same def_xcIW def_s')\n             in_cons mem_filter => /orP [/eqP {c''} -> | /andP [_ Hc'']].\n    + exact: (IDSWD _ AIN).\n    + exact: (IDSWD _ Hc'').\n  - rewrite (unique_ids_irrelevancies SR not_pc).\n    apply/(unique_ids_replace IDSU def_xcIW def_s' AIN).\n  - rewrite /well_formed_jump_targets\n            (well_formed_targets_irrelevancies SR not_pc).\n    apply/(well_formed_targets_same JTWF IDSU def_xcIW def_s' RPREV AIN);\n    try reflexivity.\n  - rewrite /well_formed_store_targets\n            (well_formed_targets_irrelevancies SR not_pc).\n    apply/(well_formed_targets_augment STWF IDSU def_xcIW def_s' RPREV AIN);\n    try reflexivity.\n  - by rewrite /refine_previous_b /=\n               (get_compartment_id_irrelevancies SR not_pc)\n              -(get_compartment_id_supd_same def_xcIW def_s')\n               R_c_sys.\n  - exact: (supd_refine_syscall_addrs_b def_s').\n  - have in_range : forall c',\n                      c' \\in I'' :|: (cid' |: W'') ->\n                      (c' < Sym.next_id\n                              (Symbolic.internal\n                                 (SState SM SR\n                                         pc@(Sym.PC F cid')\n                                         (SInternal Snext SiT SaJT SaST))))%ord.\n    { move=> c'.\n      case: SGINT => Hbounded Hisolate.\n      rewrite setUA (setUC I'') -setUA in_setU1=> /orP [/eqP->{c'}|IN_IW].\n      - apply: Hbounded; try eapply def_cid'.\n        by rewrite in_setU in_setU1 eqxx.\n      - apply: Hbounded; try apply def_xcIW.\n        by rewrite -setUA in_setU1 IN_IW orbT.\n    }\n    exact: (sget_supd_good_internal in_range def_xcIW def_s').\nQed.\n\nLemma retag_set_get_compartment_id_disjoint ok retag ps sst sst' c :\n  Sym.retag_set ok retag ps sst = Some sst' ->\n  [disjoint Abs.address_space c & ps] ->\n  get_compartment_id sst' c = get_compartment_id sst c.\nProof.\n  rewrite /Sym.retag_set /Sym.retag_one.\n  move=> Hretag /pred0P Hdis.\n  have {Hdis} Hdis: forall p, p \\in Abs.address_space c -> p \\notin ps.\n  { move=> p Hin_c.\n    apply/negP => Hin_ps.\n    move: (Hdis p) => /=.\n    by rewrite Hin_c Hin_ps. }\n  elim: ps sst Hretag Hdis => [|p ps IH] sst /=; first congruence.\n  case GET: (Sym.sget sst p) => [[cid' I' W']|] //=.\n  case: (ok p cid' I' W') => //.\n  case: (retag p cid' I' W') => [cid'' I'' W''] //.\n  case UPD: (Sym.supd _ _ _) => [sst''|] //= Hretag Hdis.\n  rewrite (IH sst'') //.\n  - rewrite /get_compartment_id.\n    apply eq_pick => cid //=.\n    apply f_equal2 => // {cid}.\n    apply eq_in_imset => p' /= p'_in_c.\n    rewrite (Sym.sget_supd_neq _ UPD) // => ?. subst p'.\n    move: (Hdis _ p'_in_c).\n    by rewrite in_cons eqxx.\n  - move=> pp Hin.\n    by case/norP: (Hdis pp Hin).\nQed.\n\nLemma get_compartment_id_subset sst c c' cid p :\n  p \\in Abs.address_space c' ->\n  Abs.address_space c' \\subset Abs.address_space c ->\n  get_compartment_id sst c = Some cid ->\n  get_compartment_id sst c' = Some cid.\nProof.\n  move=> Hp Hsub.\n  rewrite /get_compartment_id.\n  case: pickP => [cid' /eqP Hcid|] // [E].\n  subst cid'.\n  suff ->: [set (omap Sym.data_tag_compartment \\o @Sym.sget _ cmp_syscalls sst) x | x in Abs.address_space c'] =\n           [set (omap Sym.data_tag_compartment \\o @Sym.sget _ cmp_syscalls sst) x | x in Abs.address_space c].\n  { rewrite Hcid.\n    case: pickP => [cid''' /eqP/set1_inj H//|/(_ cid) contra].\n    by rewrite eqxx in contra. }\n  apply/eqP. rewrite eqEsubset.\n  rewrite imsetS //= Hcid sub1set.\n  apply/imsetP.\n  exists p => //.\n  apply/eqP. rewrite eq_sym -in_set1 -Hcid.\n  apply/imsetP.\n  exists p => //.\n  move/subsetP: Hsub.\n  by apply.\nQed.\n\nLemma retag_set_get_compartment_id_same_ids ok retag ps sst sst' c :\n  Sym.retag_set ok retag ps sst = Some sst' ->\n  (forall p cid I W, p \\in Abs.address_space c -> Sym.data_tag_compartment (retag p cid I W) = cid) ->\n  get_compartment_id sst' c = get_compartment_id sst c.\nProof.\n  rewrite /Sym.retag_set /Sym.retag_one.\n  move=> Hretag_set Hretag.\n  elim: ps sst Hretag_set => [|p ps IH] sst //=; first congruence.\n  case GET: (Sym.sget _ _) => [[cid I W]|] //=.\n  case: (ok _ _ _ _) => //.\n  have [p_in_c|p_nin_c] := boolP (p \\in Abs.address_space c).\n  - move: Hretag => /(_ p cid I W p_in_c).\n    case RETAG: (retag _ _ _ _) => [cid' I' W'] //= ->.\n    case UPD: (Sym.supd _ _ _) => [sst''|] //= Hretag_set.\n    rewrite (IH sst'' Hretag_set).\n    apply eq_pick=> cid''.\n    apply f_equal2=> // {cid''}.\n    apply eq_imset=> p' //=.\n    rewrite (Sym.sget_supd UPD).\n    have [{p'} ->|//] := p' =P p.\n    by rewrite GET.\n  - case RETAG: (retag _ _ _ _) => [cid' I' W'] //=.\n    case UPD: (Sym.supd _ _ _) => [sst''|] //= Hretag_set.\n    rewrite (IH sst'' Hretag_set).\n    apply eq_pick=> cid''.\n    apply f_equal2=> // {cid''}.\n    apply eq_in_imset=> p' p'_in_c //=.\n    rewrite (Sym.sget_supd_neq _ UPD) // => ?.\n    subst p'.\n    by rewrite (negbTE p_nin_c) in p'_in_c.\nQed.\n\nLemma get_compartment_idP sst c cid :\n  get_compartment_id sst c = Some cid <->\n  [set (omap Sym.data_tag_compartment \\o @Sym.sget _ cmp_syscalls sst) p | p in Abs.address_space c] =\n  [set Some cid].\nProof.\n  rewrite /get_compartment_id.\n  split.\n  - by case: pickP => [cid' /eqP Hcid' [<-] //|].\n  - move=> ->.\n    case: pickP => [cid' /eqP/set1_inj [->] //|/(_ cid)].\n    by rewrite eqxx.\nQed.\n\nLemma get_compartment_id_set0 sst J S :\n  get_compartment_id sst <<set0,J,S>> = None.\nProof.\n  case H: (get_compartment_id _ _) => [cid|//].\n  move/get_compartment_idP: H => /=.\n  rewrite imset0=> /setP/(_ (Some cid)).\n  by rewrite in_set0 in_set1 eqxx.\nQed.\n\nLemma get_compartment_id_setU1 sst (A J S : {set word}) p :\n  get_compartment_id sst <<p |: A,J,S>> =\n  if A == set0 then\n    omap Sym.data_tag_compartment (Sym.sget sst p)\n  else\n    match omap Sym.data_tag_compartment (Sym.sget sst p), get_compartment_id sst <<A,J,S>> with\n    | Some cid1, Some cid2 => if cid2 == cid1 then Some cid1 else None\n    | _, _ => None\n    end.\nProof.\n  have [{A} ->|/set0Pn [p' p'_in_A]] := altP (A =P set0).\n  { rewrite setU0 /get_compartment_id /= imset_set1.\n    case: pickP => [cid /eqP/set1_inj <- //|] /=.\n    case: (Sym.sget _ _) => [[cid ? ?]|] //= /(_ cid).\n    by rewrite eqxx. }\n  rewrite /get_compartment_id /= imsetU1 /=.\n  case: (Sym.sget _ _) => [[cid I W]|] //=; last first.\n  { case: pickP => [cid' /eqP/setP/(_ None)|//].\n    by rewrite in_setU1 eqxx /= in_set1. }\n  case: pickP => [cid' /eqP Hcid'|/(_ cid)].\n  { move/setP/(_ (Some cid)): (Hcid').\n    rewrite in_setU1 eqxx /= in_set1 => /esym/eqP [E]. subst cid'.\n    case: pickP => [cid' /eqP Hcid''|/(_ cid) contra].\n    - rewrite Hcid'' in Hcid'.\n      by rewrite -[cid' == cid]/(Some cid' == Some cid) -in_set1 -Hcid' set22.\n    - have: [set (omap Sym.data_tag_compartment \u2218 Sym.sget sst) x | x in A] \\subset [set Some cid]\n        by rewrite -Hcid' subsetUr.\n      rewrite subset1 contra {contra} /= imset_eq0 => /eqP/setP/(_ p').\n      by rewrite p'_in_A in_set0. }\n  case: pickP => [cid' /eqP ->|//].\n  have [{cid'} ->|//] := cid' =P cid.\n  by rewrite setUid eqxx.\nQed.\n\nLemma retag_one_get_compartment_id_new_id b ok retag p sst sst' (A J S : {set word}) cid' :\n  Sym.retag_one ok retag sst p = Some sst' ->\n  p \\notin A ->\n  (if b then\n     forall cid I W, Sym.data_tag_compartment (retag p cid I W) = cid'\n   else true) ->\n  get_compartment_id sst' <<if b then p |: A else A,J,S>> =\n  if b then\n    match get_compartment_id sst <<A,J,S>> with\n    | Some cid => if cid == cid' then Some cid'\n                  else None\n    | None => if A == set0 then Some cid' else None\n    end\n  else get_compartment_id sst <<A,J,S>>.\nProof.\n  rewrite /Sym.retag_one.\n  case Hsget: (Sym.sget _ _) => [[cid I W]|] //=.\n  case: (ok p cid I W) => //=.\n  case Hretag: (retag _ _ _ _) => [cid'' I' W'] /= Hsupd p_notin_A.\n  case: b => [Hnew|_]; last first.\n  { rewrite /get_compartment_id /=.\n    apply eq_pick => p'.\n    apply f_equal2 => // {p'}.\n    apply eq_in_imset => p' /=.\n    rewrite (Sym.sget_supd Hsupd).\n    have [->|//] := altP (p' =P p).\n    by rewrite (negbTE p_notin_A). }\n  have := Hnew cid I W. rewrite Hretag /= => ?. subst cid''.\n  rewrite get_compartment_id_setU1 (Sym.sget_supd Hsupd) eqxx /=.\n  have [->|NE] := altP (A =P set0).\n  { rewrite /get_compartment_id imset0.\n    case: pickP => [cid'' /eqP/setP/(_ (Some cid''))|//].\n    by rewrite in_set0 in_set1 eqxx. }\n  suff ->: get_compartment_id sst' <<A,J,S>> = get_compartment_id sst <<A,J,S>> by [].\n  rewrite /get_compartment_id /=.\n  apply eq_pick=> cid''.\n  apply f_equal2 => // {cid''}.\n  apply eq_in_imset=> p' /=.\n  rewrite (Sym.sget_supd Hsupd).\n  have [->|//] := p' =P p.\n  by rewrite (negbTE p_notin_A).\nQed.\n\nLemma retag_set_get_compartment_id_new_id ok retag (ps : seq word) sst sst' c cid' :\n  uniq ps ->\n  Sym.retag_set ok retag ps sst = Some sst' ->\n  Abs.address_space c \\subset ps ->\n  Abs.address_space c != set0 ->\n  (forall p cid I W,\n     p \\in Abs.address_space c ->\n     Sym.data_tag_compartment (retag p cid I W) = cid') ->\n  get_compartment_id sst' c = Some cid'.\nProof.\n  case: c => [A J S] /= Huniq Hretag Hsubset Hnot0 Hnew.\n  suff /(_ set0 A Hsubset _ Hnew):\n    forall (A A' : {set word}),\n      A' \\subset ps ->\n      [disjoint A & ps] ->\n      (forall p cid I W,\n         p \\in A' ->\n         Sym.data_tag_compartment (retag p cid I W) = cid') ->\n      get_compartment_id sst' <<A' :|: A,J,S>> =\n      if A' == set0 then get_compartment_id sst <<A,J,S>>\n      else if A == set0 then Some cid'\n      else match get_compartment_id sst <<A,J,S>> with\n           | Some cid0 => if cid0 == cid' then Some cid' else None\n           | None => None\n           end.\n  { rewrite setU0 eqxx (negbTE Hnot0) => -> //.\n    rewrite disjoint_subset.\n    apply/subsetP => ?.\n    by rewrite in_set0. }\n  move=> {A Hsubset Hnot0 Hnew} A A' Hsubset Hdis Hnew.\n  elim: ps Huniq sst Hretag A A' Hsubset Hdis Hnew\n        => [_ sst [<-] {sst'} A A'|\n            p ps IH /= /andP [p_notin_ps Huniq] sst Hretag_set A A' /subsetP Hsubset Hdis Hnew].\n  { have [{A'} ->|/set0Pn [p p_in_A'] /subsetP/(_ _ p_in_A') //] := altP (A' =P set0).\n    by rewrite set0U. }\n  move: (Hretag_set).\n  rewrite /Sym.retag_set /=.\n  case Hretag_one: (Sym.retag_one _ _ _ _) => [sst''|] //= Hretag_set'.\n  have [->|A'_not_0] := altP (A' =P set0).\n  { rewrite set0U. by eapply retag_set_get_compartment_id_disjoint; eauto. }\n  have [p_in_A'|p_nin_A'] := boolP (p \\in A').\n  - rewrite -(setD1K p_in_A') (setUC [set p : word]) -setUA (IH _ sst'') {IH} //.\n    + have ->: (p |: A == set0) = false.\n      { apply/negbTE/eqP=> /setP/(_ p).\n        by rewrite in_setU1 eqxx in_set0. }\n      have:= (@retag_one_get_compartment_id_new_id (p \\in A') ok retag p sst sst'' A J S cid' Hretag_one).\n      move: (Hdis).\n      rewrite p_in_A' disjoint_sym disjoint_subset => /subsetP/(_ p).\n      rewrite in_cons eqxx=> /(_ erefl) p_notin_A /(_ p_notin_A) {p_notin_A} ->; last by eauto.\n      have [->|_] := A =P set0.\n      { rewrite get_compartment_id_set0 eqxx.\n        by case: (A' :\\ p == set0). }\n      case: (A' :\\ p == set0); case: (get_compartment_id _ _) => [cid|] //.\n      have [/= _ {cid}|//] := cid =P cid'.\n      by rewrite eqxx.\n    + apply/subsetP=> p'.\n      rewrite in_setD1 => /andP [p'_neq_p /Hsubset].\n      by rewrite in_cons (negbTE p'_neq_p).\n    + move: Hdis.\n      rewrite !disjoint_subset=> /subsetP Hdis.\n      apply/subsetP => p'.\n      rewrite in_setU1=> /orP [/eqP -> {p'}//|/Hdis //].\n      by rewrite /predC /in_mem /= => /norP [].\n    + move=> p' cid I W.\n      rewrite in_setD1=> /andP []. by auto.\n  - rewrite (IH _ sst'') {IH} ?(negbTE A'_not_0) //.\n    + have:= (@retag_one_get_compartment_id_new_id (p \\in A') ok retag p sst sst'' A J S cid' Hretag_one).\n      move: (Hdis).\n      rewrite (negbTE p_nin_A') disjoint_sym disjoint_subset => /subsetP/(_ p).\n      rewrite in_cons eqxx=> /(_ erefl) p_notin_A /(_ p_notin_A) {p_notin_A} ->; last by eauto.\n      by have [|] := A =P set0.\n    + apply/subsetP => p'.\n      have [-> {p'}|p'_nin_p /Hsubset] := altP (p' =P p); first by rewrite (negbTE p_nin_A').\n      by rewrite in_cons (negbTE p'_nin_p).\n    + move: Hdis.\n      rewrite !disjoint_subset=> /subsetP Hdis.\n      apply/subsetP => p' /Hdis.\n      by rewrite /predC /in_mem /= => /norP [].\nQed.\n\n(* XXX: Not really needed anymore. *)\nLemma bounded_tags sst p c c' II WW :\n  Sym.good_internal sst ->\n  Sym.sget sst p = Some (Sym.DATA c II WW) ->\n  c' \\in II :|: WW ->\n  (c' < (Sym.next_id (Symbolic.internal sst)))%ord.\nProof.\n  move=> [Hbounded _] Hsget Hin.\n  apply: Hbounded; try eapply Hsget.\n  by rewrite -setUA in_setU1 Hin orbT.\nQed.\n\nTheorem isolate_refined : forall ast sst sst',\n  Abs.pc ast = isolate_addr ->\n  Abs.good_state ast ->\n  refine ast sst ->\n  Sym.isolate sst = Some sst' ->\n  exists ast',\n    Abs.isolate_fn ast = Some ast' /\\\n    refine ast' sst'.\nProof.\n  move=> ast sst sst' IS_ISOLATE AGOOD REFINE ISOLATE;\n    rewrite (lock eq) in IS_ISOLATE.\n  have [SGPC SGINT] : Sym.good_state sst by eapply refine_good; eassumption.\n  destruct REFINE as [RPC RREGS RMEMS COMPSWD IDSWD IDSU JTWF STWF RPREV RSC RINT],\n           ast    as [Apc AR    AM    AC    Ask Aprev],\n           sst    as [SM SR Spc [Snext SiT SaJT SaST]].\n  case/and4P: (AGOOD) => AIN /andP [ANOL ACC] ASS ASP.\n  rewrite /Abs.semantics /Abs.isolate /Abs.isolate_fn\n          (lock Abs.in_compartment_opt);\n    simpl in *.\n\n  rewrite /refine_pc_b in RPC.\n  destruct Spc as [pc [F cid]]; try done; move/eqP in RPC; subst.\n\n  move/id in ISOLATE;\n    undo1 ISOLATE LI;\n    undo1 ISOLATE cid_sys;\n    destruct LI as [cid' I_sys W_sys]; try discriminate;\n    rewrite /Sym.can_execute /= in def_cid_sys;\n    generalize def_cid_sys => TEMP; rewrite (lock orb) in def_cid_sys;\n      undo1 TEMP COND_sys; move: TEMP => [?]; subst cid';\n      rewrite -(lock orb) in def_cid_sys;\n    undo1 ISOLATE c';\n    undo2 ISOLATE pA LpA; undo2 ISOLATE pJ LpJ; undo2 ISOLATE pS LpS;\n    undo1 ISOLATE A'; undo1 ISOLATE NE_A';\n    undo1 ISOLATE J';\n    undo1 ISOLATE S';\n    undo1 ISOLATE s';\n    undo2 ISOLATE pc' Lpc';\n    undoDATA ISOLATE i' cid_next I_next W_next;\n    undo1 ISOLATE NEXT_EQ; move/eqP in NEXT_EQ; subst cid_next;\n    undo1 ISOLATE NEXT;\n    destruct s' as [SM' SR' pc'' si'];\n    unoption.\n\n  have /= ? := Sym.retag_set_preserves_pc def_s'.\n  have /= ? := Sym.retag_set_preserves_regs def_s'.\n  move: def_c'.\n  rewrite /Sym.fresh' /=.\n  have [//|NEQ [?]] := Snext =P monew.\n  subst pc'' SR' c'.\n\n  move: (COMPSWD pc).\n  rewrite def_LI => /(_ erefl).\n  case IN_c: (Abs.in_compartment_opt AC pc) => [c_sys|] _ //.\n  case/Abs.in_compartment_opt_correct/andP: (IN_c) => c_sys_in_AC pc_in_c_sys {COND_sys}.\n\n  undo1 def_cid_sys COND; unoption.\n\n  repeat (erewrite refined_reg_value; [|eassumption]).\n  rewrite def_pA_LpA def_pJ_LpJ def_pS_LpS def_pc'_Lpc' /=.\n\n  move: RPREV => /andP [/eqP ? /eqP RPREV]; subst Ask.\n  have -> /=: Abs.permitted_now_in AC F Aprev pc ?= c_sys.\n  { rewrite /Abs.permitted_now_in IN_c /=.\n    case/orP: COND => [/eqP E| /andP [/eqP E cid_in_I_sys]].\n    - subst cid_sys.\n      suff ->: c_sys = Aprev by rewrite eqxx.\n      apply/(IDSU _ _ c_sys_in_AC AIN).\n      by rewrite RPREV\n                 (in_compartment_get_compartment_id COMPSWD IDSWD IDSU c_sys_in_AC pc_in_c_sys)\n                 def_LI.\n    - by rewrite E {E} eqxx /= (JTWF _ _ AIN RPREV) in_set def_LI /= cid_in_I_sys orbT. }\n\n  destruct Aprev as [Aprev Jprev Sprev].\n\n  repeat (erewrite isolate_create_set_refined; [|eassumption]).\n  rewrite def_A' def_J' def_S' /= NE_A' /=.\n\n  rewrite /Sym.good_pc_tag in SGPC; move: SGPC => [p [I [W def_cid]]].\n\n  have SUBSET_A' : A' \\subset Aprev. {\n    apply/subsetP; intros a IN.\n    have /(_ a) := (Sym.retag_set_forall (enum_uniq (mem (A' :|: J' :|: S'))) def_s').\n    rewrite /Sym.do_ok (mem_enum (mem (A' :|: J' :|: S'))) !in_setU IN /= => /(_ erefl).\n    move=> /= [c' [I' [W' [SGET /and3P [/eqP OK _ _]]]]]. subst c'.\n    apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    by rewrite SGET.\n  }\n  rewrite SUBSET_A'.\n\n  have SUBSET_J' : J' \\subset Aprev :|: Jprev. {\n    apply/subsetP; move=> a IN.\n    rewrite in_setU. apply/orP.\n    have /(_ a) := Sym.retag_set_forall (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n    rewrite /Sym.do_retag /Sym.do_ok\n            (mem_enum (mem (A' :|: J' :|: S'))) !in_setU IN orbT /=\n            => /(_ erefl) [cid' [I' [W' [EQ /and3P [_ /orP [/eqP ? | cid'_in_I'] _]]]]].\n    - subst cid'. left.\n      apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n      by rewrite EQ.\n    - right.\n      have /= -> := JTWF _ _ AIN RPREV.\n      by rewrite in_set EQ.\n  }\n  rewrite SUBSET_J'.\n\n  have SUBSET_S' : S' \\subset Aprev :|: Sprev. {\n    apply/subsetP; move=> a IN.\n    rewrite in_setU. apply/orP.\n    have /(_ a) := Sym.retag_set_forall (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n    rewrite /Sym.do_retag /Sym.do_ok\n            (mem_enum (mem (A' :|: J' :|: S'))) !in_setU IN orbT /=\n            => /(_ erefl) [cid' [I' [W' [EQ /and3P [_ _ /orP [/eqP ? | cid'_in_S']]]]]].\n    - subst cid'. left.\n      apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n      by rewrite EQ.\n    - right.\n      have /= -> := STWF _ _ AIN RPREV.\n      by rewrite in_set EQ.\n  }\n  rewrite SUBSET_S'.\n\n  have IN_pc' : pc' \\in Aprev.\n  { apply/(get_compartment_id_in_compartment COMPSWD IDSWD IDSU AIN).\n    have [OLD | [cid' [I' [W' [OLD []]]]]] :=\n      Sym.retag_set_or_ok (enum_uniq (mem (A' :|: J' :|: S'))) def_s' pc';\n      first by rewrite OLD def_xcIW.\n    rewrite OLD RPREV {RPREV} /= def_xcIW /Sym.do_ok /Sym.do_retag.\n    by have [IN /= /and3P [/eqP -> _ _] _|_ _ [-> _ _]] := boolP (pc' \\in A'). }\n\n  have DIFF : cid <> Snext. {\n    intros ?; subst cid.\n    eapply Sym.sget_lt_next in RINT; [simpl in RINT | exact: def_cid].\n    by rewrite Ord.ltxx in RINT.\n  }\n\n  have DIFF_sys : cid_sys <> Snext. {\n    intros ?; subst cid_sys.\n    eapply Sym.sget_lt_next in RINT; [simpl in RINT | exact: def_LI].\n    by rewrite Ord.ltxx in RINT.\n  }\n\n  have NIN : pc' \\notin A'. {\n    apply/negP => IN.\n    have /(_ pc') := Sym.retag_set_in_ok (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n    rewrite /Sym.do_ok /Sym.do_retag (mem_enum (mem (A' :|: J' :|: S'))) !in_setU IN /=\n            => /(_ erefl) [cpc' [Ipc' [Wpc' [THEN [/and3P [/eqP ? _ _] NOW]]]]].\n    subst cpc'.\n    abstract congruence.\n  }\n\n  rewrite -(lock _) /= in_setD IN_pc' NIN /= eqxx.\n\n  have c_sys_id : get_compartment_id (SState SM SR pc@(Sym.PC F cid)\n                                             (SInternal Snext SiT SaJT SaST)) c_sys = Some cid_sys.\n  { by rewrite (in_compartment_get_compartment_id COMPSWD IDSWD IDSU c_sys_in_AC pc_in_c_sys)\n               def_LI. }\n\n  have IN_Jsys : pc' \\in Abs.jump_targets c_sys.\n  { have /= -> := JTWF _ cid_sys c_sys_in_AC c_sys_id.\n    rewrite in_set.\n    have [->|[c' [I' [W' [-> /=]]]]] :=\n      @Sym.retag_set_or_ok _ _ _ _ _ _ _ (enum_uniq (mem (A' :|: J' :|: S'))) def_s' pc';\n      first by rewrite def_xcIW /=.\n    rewrite def_xcIW /Sym.do_retag.\n    case=> _ [_ E _].\n    move: NEXT.\n    rewrite E {E}.\n    case: (pc' \\in J') => //.\n    by rewrite in_setU1 (introF (cid_sys =P Snext) DIFF_sys) /=. }\n\n  rewrite IN_Jsys.\n\n  eexists; split; [reflexivity|].\n\n  (* Some useful lemmas *)\n\n  move: (RSC) => /and3P; rewrite {1 2}/syscall_addrs => - [ANGET SNGET RSCU].\n  move: (RSCU);\n    rewrite /= !inE negb_or -!andbA => /and4P[] NEQiaJ NEQiaS NEQaJaS _.\n\n  have NIN_sc : forall sc : word, sc \\in syscall_addrs -> sc \\notin A'.\n  { move=> sc sc_is_sc.\n    have {ANGET} ANGET := allP ANGET _ sc_is_sc.\n    apply/negP; move=> IN.\n    move: ASS => /allP/(_ _ AIN)/orP [UAS | SAS].\n    - have IN' : sc \\in Aprev by move/subsetP in SUBSET_A'; apply SUBSET_A'.\n      move/forall_inP/(_ _ IN') in UAS.\n      by rewrite UAS in ANGET.\n    - rewrite /Abs.syscall_address_space /Abs.address_space /= in SAS.\n      move: SAS => /existsP [sc' /and3P [NONE ELEM /eqP?]]; subst Aprev.\n      move: SUBSET_A'; rewrite subset1; move => /orP [] /eqP?; subst A'.\n      + move: IN_pc' IN NIN; rewrite !in_set1; move=> /eqP->.\n        by rewrite eq_refl.\n      + by rewrite in_set0 in IN. }\n\n  have TSAI_s_s' : forall X : {set word},\n                      [disjoint A' & X] ->\n                      tags_subsets_add_1_in\n                        X\n                        Snext\n                        (SState SM SR pc@(Sym.PC F cid)\n                                (SInternal Snext SiT SaJT SaST))\n                        (SState SM' SR pc@(Sym.PC F cid) si').\n  {\n    move=> X DJX a.\n    have [a_in_sets|a_nin_sets] := boolP (a \\in A' :|: J' :|: S').\n    - have /(_ a) := Sym.retag_set_in (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n      rewrite -(mem_enum (mem (A' :|: J' :|: S')) a) in a_in_sets\n        => /(_ a_in_sets) [cid' [I' [W' [Hold Hnew]]]].\n      rewrite Hold Hnew /Sym.do_retag.\n      split3.\n      + move=> a_in_X.\n        move/pred0P: DJX=> /(_ a) /=.\n        by rewrite a_in_X andbT=> ->.\n      + by case: (a \\in J'); auto.\n      + by case: (a \\in S'); auto.\n    - have /(_ a) := Sym.retag_set_not_in def_s'.\n      rewrite -(mem_enum (mem (A' :|: J' :|: S')) a) in a_nin_sets\n        => /(_ a_nin_sets) <-.\n      by case: (Sym.sget _ _) => [[*]|]; auto. }\n\n  have TSAI_s_s'' : forall X : {set word},\n                       [disjoint A' & X] ->\n                       tags_subsets_add_1_in\n                         X\n                         Snext\n                         (SState SM SR pc@(Sym.PC F cid)\n                                 (SInternal Snext SiT SaJT SaST))\n                         (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si'))\n  by exact: TSAI_s_s'.\n\n  have TSAI_rest : forall c,\n                     c \\in rem_all <<Aprev,Jprev,Sprev>> AC ->\n                     tags_subsets_add_1_in\n                       (Abs.address_space c)\n                       Snext\n                       (SState SM SR pc@(Sym.PC F cid)\n                               (SInternal Snext SiT SaJT SaST))\n                       (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si')).\n  {\n    move=> c; rewrite in_rem_all => /andP [NEQ' IN] a.\n    apply/TSAI_s_s''/pred0P=> p' /=.\n    apply/negbTE/negP=> /andP [p'_in_A' p'_in_c].\n    suff contra: c = <<Aprev,Jprev,Sprev>> by rewrite contra eqxx in NEQ'.\n    move/Abs.non_overlappingP: ANOL.\n    apply=> //.\n    apply/negP=> /pred0P/(_ p') /=.\n    rewrite p'_in_c /=.\n    by move/subsetP: SUBSET_A' => /(_ _ p'_in_A') ->. }\n\n  have RC_rest : forall c,\n                   c \\in rem_all <<Aprev,Jprev,Sprev>> AC ->\n                   get_compartment_id\n                     (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si')) c =\n                   get_compartment_id\n                     (SState SM SR pc@(Sym.PC F cid) (SInternal Snext SiT SaJT SaST)) c.\n  {\n    move=> c.\n    rewrite in_rem_all=> /andP [c_neq_prev c_in_AC].\n    apply (retag_set_get_compartment_id_same_ids def_s')=> p' cid' I' W' p'_in_c.\n    rewrite /Sym.do_retag.\n    have [p'_in_A'|//] := boolP (p' \\in A').\n    suff E : c = <<Aprev,Jprev,Sprev>> by rewrite E eqxx in c_neq_prev.\n    move/Abs.non_overlappingP: ANOL.\n    apply=> //.\n    apply/pred0P => /(_ p').\n    rewrite /predI /= p'_in_c /=.\n    by move/subsetP/(_ _ p'_in_A'): SUBSET_A'=> ->.\n  }\n\n  have NOT_SYSCALL_prev : ~ Abs.syscall_address_space\n                            AM <<Aprev,Jprev,Sprev>>.\n  {\n    rewrite /Abs.syscall_address_space /=; move=> /existsP [sc].\n    rewrite !inE => /and3P [NGET /or3P EQ_sc /eqP?]; subst Aprev.\n    move: IN_pc'; rewrite in_set1 => /eqP?; subst sc.\n    move: SUBSET_A'; rewrite subset1 => /orP [] /eqP?; subst A'.\n    - by rewrite in_set1 eq_refl in NIN.\n    - by rewrite eq_refl in NE_A'.\n  }\n\n  have USER_prev : Abs.user_address_space AM <<Aprev,Jprev,Sprev>>. {\n    move/allP in ASS.\n    by move: (ASS _ AIN) => /orP [UAS | SAS].\n  }\n\n  have NOT_USER_c_sys : ~ Abs.user_address_space AM c_sys. {\n    move=> /forall_inP UAS.\n    specialize (UAS _ pc_in_c_sys); simpl in UAS.\n    rewrite -(lock eq) in IS_ISOLATE; subst.\n\n    by rewrite /= UAS in ANGET.\n  }\n\n  have SYSCALL_c_sys : Abs.syscall_address_space AM c_sys. {\n    move/allP in ASS.\n    by move: (ASS _ c_sys_in_AC) => /orP [UAS | SAS].\n  }\n\n  have DIFF_prev_c_sys : <<Aprev,Jprev,Sprev>> <> c_sys\n    by move=> ?; subst.\n\n  have R_c_sys' : get_compartment_id\n                    (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si'))\n                    c_sys\n                    ?= cid_sys.\n  {\n    rewrite -RC_rest in c_sys_id => //.\n    rewrite in_rem_all; apply/andP; split=> //.\n    by rewrite eq_sym; apply/eqP.\n  }\n\n  have Hres: get_compartment_id (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si'))\n                                <<Aprev :\\: A',Jprev,Sprev>> = Some cid.\n  { rewrite (get_compartment_id_irrelevancies SR pc@(Sym.PC F cid))\n            get_compartment_id_irrelevancies_bump.\n    rewrite (retag_set_get_compartment_id_same_ids def_s') //; last first.\n    { rewrite /= => p' cid' _ _.\n      by rewrite in_setD => /andP [/negbTE -> ?]. }\n    have := (@get_compartment_id_subset _ _ _ _ pc' _ _ RPREV).\n    apply.\n    - by rewrite in_setD IN_pc' NIN.\n    - by rewrite subDset subsetUr. }\n\n  have Hnew: get_compartment_id (SState SM' SR pc'@(Sym.PC JUMPED cid_sys) (Sym.bump_next_id si'))\n                                <<A',J',S'>> = Some Snext.\n  { rewrite (get_compartment_id_irrelevancies SR pc@(Sym.PC F cid))\n            get_compartment_id_irrelevancies_bump.\n    have := (@retag_set_get_compartment_id_new_id _ _ _ _ _ <<A',J',S'>>\n                                                  Snext (enum_uniq (mem (A' :|: J' :|: S'))) def_s' _ NE_A').\n    apply.\n    - apply/subsetP => p'.\n      by rewrite (mem_enum (mem (A' :|: _ :|: _))) !in_setU=> ->.\n    - by rewrite /Sym.do_retag=> ? ? ? ? /= ->. }\n\n(* REFINEMENT *)\n\n  constructor=> //=.\n  - move/id in def_s'.\n    eapply retag_set_preserves_memory_refinement in def_s'; last eassumption.\n    assumption.\n  - move=> p' Hp'.\n    move: (COMPSWD p').\n    rewrite (Sym.retag_set_preserves_definedness def_s' p') => /(_ Hp') {Hp'}.\n    case Hp': (Abs.in_compartment_opt AC p') => [cp'|] // _.\n    case/Abs.in_compartment_opt_correct/andP: Hp'.\n    have [{cp'} ->|NE] := altP (cp' =P <<Aprev,Jprev,Sprev>>) => cp'_in_AC p'_in_cp'.\n    { rewrite /= in_setD p'_in_cp' andbT.\n      by case: (p' \\in A'). }\n    apply (@Abs.in_compartment_opt_is_some _ _ _ cp').\n    by rewrite /Abs.in_compartment !in_cons in_rem_all NE cp'_in_AC !orbT /=.\n  - move=> c'.\n    rewrite !in_cons => /or3P [/eqP -> {c'}|/eqP -> {c'}|c'_in].\n    + by rewrite Hres.\n    + by rewrite Hnew.\n    + rewrite RC_rest //.\n      apply IDSWD.\n      rewrite in_rem_all in c'_in.\n      by case/andP: c'_in.\n  - move=> c1 c2.\n    rewrite !in_cons /=\n            => /or3P [/eqP -> {c1}|/eqP -> {c1}|c1_in_AC]\n               /or3P [/eqP -> {c2}|/eqP -> {c2}|c2_in_AC] //=;\n    rewrite ?Hres ?Hnew; try congruence.\n    + rewrite -RPREV RC_rest // => NEW.\n      rewrite in_rem_all in c2_in_AC.\n      case/andP: c2_in_AC => [/eqP ? ?].\n      by apply IDSU in NEW; try congruence.\n    + rewrite RC_rest // /get_compartment_id.\n      case: pickP => [cid'' /eqP Hcid''|]//= [E].\n      subst cid''.\n      move: (set11 (Some Snext)).\n      rewrite -Hcid'' => /imsetP /= [p' _].\n      case GETp': (Sym.sget _ _) => [[cp' Ip' Wp']|] //= [E].\n      subst cp'.\n      move: (Sym.sget_lt_next RINT GETp') => /=.\n      by rewrite Ord.ltxx.\n    + rewrite -RPREV RC_rest // => NEW.\n      rewrite in_rem_all in c1_in_AC.\n      case/andP: c1_in_AC => [/eqP ? ?].\n      by apply IDSU in NEW; try congruence.\n    + rewrite RC_rest // /get_compartment_id.\n      case: pickP => [cid'' /eqP Hcid''|]//= [E].\n      subst cid''.\n      move: (set11 (Some Snext)).\n      rewrite -Hcid'' => /imsetP /= [p' _].\n      case GETp': (Sym.sget _ _) => [[cp' Ip' Wp']|] //= [E].\n      subst cp'.\n      move: (Sym.sget_lt_next RINT GETp') => /=.\n      by rewrite Ord.ltxx.\n    + rewrite !RC_rest //.\n      rewrite !in_rem_all in c1_in_AC c2_in_AC.\n      case/andP: c1_in_AC => ? ?; case/andP: c2_in_AC => ? ?.\n      by apply IDSU.\n  - move=> c' cid'.\n    rewrite !inE => /or3P [ /eqP{c'}-> | /eqP{c'}-> | c'_in_AC'].\n    + (* This case (Aprev :\\: A') ends up being very similar to the third\n         (neither Aprev :\\: A' nor A') -- in fact, after a certain point,\n         identical (up to some stylistic changes. *)\n      rewrite Hres; move=> [] <-{cid'} /=.\n      move/(_ <<Aprev,Jprev,Sprev>> cid AIN RPREV) in JTWF; simpl in JTWF.\n      rewrite JTWF.\n      apply/setP; rewrite /eq_mem /= => a; rewrite !in_set.\n      have DJ : [disjoint A' & Aprev :\\: A']\n        by rewrite -setI_eq0 setIDA setIC -setIDA setDv setI0.\n      move: TSAI_s_s'' => /(_ (Aprev :\\: A') DJ a).\n      case: (Sym.sget _ a) => [[cid1 I1 W1]|] //=;\n        [|by case: (Sym.sget _ a) => [[]|] //].\n      case: (Sym.sget _ a) => [[cid2 I2 W2]|] //=.\n      move=> [cid_eq [OR_Is OR_Ws]].\n      case: OR_Is => [-> // | <-{I2}].\n      rewrite inE in_set1.\n      suff: cid != Snext by move=> /negbTE-> //.\n      suff: (cid < Snext)%ord.\n        rewrite Ord.ltNge.\n        by apply: contra => /eqP ->; rewrite Ord.leqxx.\n      move: RPREV; rewrite /get_compartment_id.\n      case: pickP => // x /eqP cid_set []?; subst x.\n      have: Some cid == Some cid by apply eq_refl.\n      rewrite -(in_set1 (Some cid)) -cid_set => /imsetP [p' p'_in_prev] /=.\n      case SGET: (Sym.sget _ p') => [[d I' W']|] //= => [[?]]; subst d.\n      replace Snext\n        with (Sym.next_id\n                (Symbolic.internal\n                   (SState SM SR pc@(Sym.PC F cid)\n                           (SInternal Snext SiT SaJT SaST))))\n        by reflexivity.\n      eapply Sym.sget_lt_next; eassumption.\n    + rewrite Hnew /= => [[E]]. subst cid'.\n      apply/setP => p'.\n      rewrite in_set.\n      have [p'_in_sets|p'_nin_sets] := boolP (p' \\in (A' :|: J' :|: S')).\n      * have /(_ p') := Sym.retag_set_in (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n        move: p'_in_sets.\n        rewrite -(mem_enum (mem (A' :|: J' :|: S')))\n                => H /(_ H) {H} [cid' [I' [W' [Hold']]]].\n        rewrite /Sym.sget /= /Sym.do_retag => -> /=.\n        case: (p' \\in J'); first by rewrite in_setU1 eqxx.\n        apply/esym/negbTE/negP=> Snext_in_I'.\n        have /(_ Snext)/= := bounded_tags RINT Hold'.\n        by rewrite in_setU Snext_in_I' Ord.ltxx => /(_ erefl).\n      * have /(_ p') := Sym.retag_set_not_in def_s'.\n        move: (p'_nin_sets).\n        rewrite -(mem_enum (mem (A' :|: J' :|: S'))) {2 3}/Sym.sget /= => H /(_ H) {H} <-.\n        rewrite !in_setU !negb_or -andbA in p'_nin_sets.\n        case/and3P: p'_nin_sets => _ /negbTE -> _.\n        case Hold': (Sym.sget _ _)=> [[cid' I' W']|//] /=.\n        apply/esym/negbTE/negP=> Snext_in_I'.\n        have /(_ Snext)/= := bounded_tags RINT Hold'.\n        by rewrite in_setU Snext_in_I' Ord.ltxx => /(_ erefl).\n    + move/(_ c' c'_in_AC') in RC_rest.\n      rewrite RC_rest => GCI_cid'.\n      move: (c'_in_AC'); rewrite in_rem_all => /andP [c'_neq_prev c'_in_AC].\n      move/(_ c' cid' c'_in_AC GCI_cid') in JTWF.\n      rewrite JTWF.\n      apply/setP.\n      rewrite /eq_mem /= => a; rewrite !in_set.\n      move: TSAI_rest => /(_ c' c'_in_AC' a).\n      case: (Sym.sget _ a) => [[]|] //=; [|by case: (Sym.sget _ a) => [[]|]].\n      move=> cid1 I1 W1.\n      case: (Sym.sget _ a) => [[]|] //=.\n      move=> cid2 I2 W2.\n      move=> [cid_eq [OR_Is OR_Ws]].\n      case: OR_Is => [-> // | <-{I2}].\n      rewrite inE in_set1.\n      suff: cid' != Snext by move=> /negbTE-> //.\n      suff: (cid' < Snext)%ord.\n        rewrite Ord.ltNge.\n        by apply: contra => /eqP ->; rewrite Ord.leqxx.\n      move: GCI_cid'; rewrite /get_compartment_id.\n      case: pickP => // x /eqP cid'_set []?; subst x.\n      have: Some cid' == Some cid' by apply eq_refl.\n      rewrite -(in_set1 (Some cid')) -cid'_set => /imsetP [p' p'_in_c'] /=.\n      case SGET: (Sym.sget _ p') => [[d I' W']|] //= => [[?]]; subst d.\n      replace Snext\n        with (Sym.next_id\n                (Symbolic.internal\n                   (SState SM SR pc@(Sym.PC F cid)\n                           (SInternal Snext SiT SaJT SaST))))\n        by reflexivity.\n      eapply Sym.sget_lt_next; eassumption.\n  - move=> c' cid'.\n    rewrite !inE => /or3P [ /eqP{c'}-> | /eqP{c'}-> | c'_in_AC'].\n    + (* This case (Aprev :\\: A') ends up being very similar to the third\n         (neither Aprev :\\: A' nor A') -- in fact, after a certain point,\n         identical (up to some stylistic changes. *)\n      rewrite Hres; move=> [] <-{cid'} /=.\n      move/(_ <<Aprev,Jprev,Sprev>> cid AIN RPREV) in STWF; simpl in STWF.\n      rewrite STWF.\n      apply/setP; rewrite /eq_mem /= => a; rewrite !in_set.\n      have DJ : [disjoint A' & Aprev :\\: A']\n        by rewrite -setI_eq0 setIDA setIC -setIDA setDv setI0.\n      move: TSAI_s_s'' => /(_ (Aprev :\\: A') DJ a).\n      case: (Sym.sget _ a) => [[cid1 I1 W1]|] //=;\n        [|by case: (Sym.sget _ a) => [[]|] //].\n      case: (Sym.sget _ a) => [[cid2 I2 W2]|] //=.\n      move=> [cid_eq [OR_Is OR_Ws]].\n      case: OR_Ws => [-> // | <-{W2}].\n      rewrite inE in_set1.\n      suff: cid != Snext by move=> /negbTE-> //.\n      suff: (cid < Snext)%ord by rewrite Ord.ltNge; apply: contra => /eqP ->; rewrite Ord.leqxx.\n      move: RPREV; rewrite /get_compartment_id.\n      case: pickP => // x /eqP cid_set []?; subst x.\n      have: Some cid == Some cid by apply eq_refl.\n      rewrite -(in_set1 (Some cid)) -cid_set => /imsetP [p' p'_in_prev] /=.\n      case SGET: (Sym.sget _ p') => [[d I' W']|] //= => [[?]]; subst d.\n      replace Snext\n        with (Sym.next_id\n                (Symbolic.internal\n                   (SState SM SR pc@(Sym.PC F cid)\n                           (SInternal Snext SiT SaJT SaST))))\n        by reflexivity.\n      eapply Sym.sget_lt_next; eassumption.\n    + rewrite Hnew /= => [[E]]. subst cid'.\n      apply/setP => p'.\n      rewrite in_set.\n      have [p'_in_sets|p'_nin_sets] := boolP (p' \\in (A' :|: J' :|: S')).\n      * have /(_ p') := Sym.retag_set_in (enum_uniq (mem (A' :|: J' :|: S'))) def_s'.\n        move: p'_in_sets.\n        rewrite -(mem_enum (mem (A' :|: J' :|: S')))\n                => H /(_ H) {H} [cid' [I' [W' [Hold']]]].\n        rewrite /Sym.sget /= /Sym.do_retag => -> /=.\n        case: (p' \\in S'); first by rewrite in_setU1 eqxx.\n        apply/esym/negbTE/negP=> Snext_in_W'.\n        have /(_ Snext)/= := bounded_tags RINT Hold'.\n        by rewrite in_setU Snext_in_W' orbT Ord.ltxx => /(_ erefl).\n      * have /(_ p') := Sym.retag_set_not_in def_s'.\n        move: (p'_nin_sets).\n        rewrite -(mem_enum (mem (A' :|: J' :|: S'))) {2 3}/Sym.sget /= => H /(_ H) {H} <-.\n        rewrite !in_setU !negb_or -andbA in p'_nin_sets.\n        case/and3P: p'_nin_sets => _ _ /negbTE ->.\n        case Hold': (Sym.sget _ _)=> [[cid' I' W']|//] /=.\n        apply/esym/negbTE/negP=> Snext_in_W'.\n        have /(_ Snext)/= := bounded_tags RINT Hold'.\n        by rewrite in_setU Snext_in_W' orbT Ord.ltxx => /(_ erefl).\n    + move/(_ c' c'_in_AC') in RC_rest.\n      rewrite RC_rest => GCI_cid'.\n      move: (c'_in_AC'); rewrite in_rem_all => /andP [c'_neq_prev c'_in_AC].\n      move/(_ c' cid' c'_in_AC GCI_cid') in STWF.\n      rewrite STWF.\n      apply/setP.\n      rewrite /eq_mem /= => a; rewrite !in_set.\n      move: TSAI_rest => /(_ c' c'_in_AC' a).\n      case: (Sym.sget _ a) => [[]|] //=; [|by case: (Sym.sget _ a) => [[]|]].\n      move=> cid1 I1 W1.\n      case: (Sym.sget _ a) => [[]|] //=.\n      move=> cid2 I2 W2.\n      move=> [cid_eq [OR_Is OR_Ws]].\n      case: OR_Ws => [-> // | <-{W2}].\n      rewrite inE in_set1.\n      suff: cid' != Snext by move=> /negbTE-> //.\n      suff: (cid' < Snext)%ord by rewrite Ord.ltNge; apply: contra => /eqP ->; rewrite Ord.leqxx.\n      move: GCI_cid'; rewrite /get_compartment_id.\n      case: pickP => // x /eqP cid'_set []?; subst x.\n      have: Some cid' == Some cid' by apply eq_refl.\n      rewrite -(in_set1 (Some cid')) -cid'_set => /imsetP [p' p'_in_c'] /=.\n      case SGET: (Sym.sget _ p') => [[d I' W']|] //= => [[?]]; subst d.\n      replace Snext\n        with (Sym.next_id\n                (Symbolic.internal\n                   (SState SM SR pc@(Sym.PC F cid)\n                           (SInternal Snext SiT SaJT SaST))))\n        by reflexivity.\n      eapply Sym.sget_lt_next; eassumption.\n  - apply/andP; split; [apply eq_refl | apply/eqP; apply R_c_sys'].\n  - rewrite /refine_syscall_addrs_b.\n    case/and3P: RSC => ? Hs ?.\n    apply/and3P.\n    split=> //; apply/allP=> x /(allP Hs).\n    by rewrite -!mem_domm -(Sym.retag_set_preserves_get_definedness def_s') /=.\n  - have := (Sym.retag_set_preserves_good_internal _ RINT def_s').\n    apply => //.\n    + move=> sc cid' I' W' sc_is_sc.\n      rewrite /Sym.do_retag.\n      by rewrite (negbTE (NIN_sc _ sc_is_sc)).\n    + move=> p' cid' I' W'.\n      rewrite /Sym.do_retag /= !inE.\n      by case: (p' \\in A'); rewrite eqxx ?orbT.\n    + move=> p' cid' I' W'.\n      rewrite /Sym.do_retag /= -{3}(setUid [set Snext])\n             -[[set Snext] :|: _ :|: _]setUA [_ :|: (_ :|: _)]setUC -setUA.\n      apply setUSS.\n      * by case: (p' \\in J'); rewrite ?subxx ?subsetUr.\n      * by case: (p' \\in S'); rewrite ?subxx ?subsetUr.\nQed.\n\nLemma prove_permitted_now_in AR AM AC Ask Aprev mem reg pc extra c i cid cid' cid'' II WW F :\n  let ast := AState pc AR AM AC Ask Aprev in\n  let sst := SState mem reg pc@(Sym.PC F cid') extra in\n  Abs.good_state ast ->\n  Sym.good_state sst ->\n  getm (Symbolic.mem sst) (vala (Symbolic.pc sst)) ?= i@(Sym.DATA cid'' II WW) ->\n  (do! guard (cid'' == cid') || (F == JUMPED) && (cid' \\in II);\n   Some cid'') ?= cid ->\n  refine_previous_b (Abs.step_kind ast) (Abs.previous ast) sst ->\n  well_defined_compartments sst AC ->\n  well_defined_ids sst AC ->\n  unique_ids sst AC ->\n  well_formed_jump_targets sst AC ->\n  Abs.in_compartment_opt (Abs.compartments ast) (vala (Symbolic.pc sst)) ?= c ->\n  Abs.permitted_now_in (Abs.compartments ast) (Abs.step_kind ast) (Abs.previous ast) (vala (Symbolic.pc sst)) ?= c.\nProof.\n  rewrite /=.\n  move=> AGOOD SGOOD PC def_cid RPREV COMPSWD IDSWD IDSU JTWF COMP.\n undo1 def_cid COND.\n        have ? : cid'' = cid by congruence.\n        subst cid''.\n        rewrite /Abs.permitted_now_in COMP /=.\n        case/Abs.in_compartment_opt_correct/andP: COMP => c_in_AC pc_in_c.\n        rewrite/refine_previous_b /= in RPREV.\n        case/andP: RPREV => /eqP ? /eqP Aprev_id. subst Ask.\n        case: SGOOD => [[SGMEM ? ?] ].\n        have c_id : get_compartment_id (SState mem reg pc@(Sym.PC F cid') extra) c ?= cid.\n        { rewrite (in_compartment_get_compartment_id COMPSWD IDSWD IDSU c_in_AC pc_in_c).\n          by rewrite /Sym.sget PC /=. }\n        case/and4P: AGOOD => /= Aprev_in_AC *.\n        case/orP: COND => [/eqP ? | /andP [/eqP ? cid'_in_I]].\n          subst cid'.\n          suff -> : c = Aprev by rewrite eqxx.\n          apply (IDSU _ _ c_in_AC Aprev_in_AC).\n          by rewrite c_id Aprev_id.\n        subst F. rewrite eqxx /=.\n        by rewrite (JTWF _ _ Aprev_in_AC Aprev_id) in_set /Sym.sget PC /= cid'_in_I orbT.\nQed.\n\nLemma prove_get_compartment_id AC mem reg pc F cid cid' cid'' extra i II WW c :\n  Sym.good_state (SState mem reg pc@(Sym.PC F cid') extra) ->\n  getm mem pc ?= i@(Sym.DATA cid'' II WW) ->\n  (do! guard (cid'' == cid') || (F == JUMPED) && (cid' \\in II);\n   Some cid'') ?= cid ->\n  well_defined_compartments (SState mem reg pc@(Sym.PC F cid') extra) AC ->\n  well_defined_ids(SState mem reg pc@(Sym.PC F cid') extra) AC ->\n  unique_ids (SState mem reg pc@(Sym.PC F cid') extra) AC ->\n  Abs.in_compartment_opt AC pc ?= c ->\n  get_compartment_id (SState mem reg pc@(Sym.PC F cid') extra) c == Some cid.\nProof.\n  move=> SGOOD PC def_cid COMPSWD IDSWD IDSU /Abs.in_compartment_opt_correct/andP [c_in_AC pc_in_c].\n  apply/eqP.\n  case: SGOOD => [[SGMEM _] _].\n  rewrite (in_compartment_get_compartment_id COMPSWD IDSWD IDSU c_in_AC pc_in_c)\n          /Sym.sget PC.\n  by undo1 def_cid COND; unoption.\nQed.\n\nTheorem backward_simulation : forall ast sst sst',\n  Abs.good_state ast ->\n  refine ast sst ->\n  sstep sst sst' ->\n  exists ast',\n    astep ast ast' /\\\n    refine ast' sst'.\nProof.\n  move=> ast sst sst' AGOOD REFINE SSTEP.\n  assert (SGOOD : Sym.good_state sst) by (eapply refine_good; eassumption).\n  destruct REFINE as [RPC RREGS RMEMS COMPSWD IDSWD IDSU JTWF STWF RPREV RSC RINT],\n           ast    as [Apc AR    AM    AC    Ask Aprev];\n    simpl in *.\n  destruct SSTEP; subst; try subst mvec;\n    unfold Symbolic.next_state_reg, Symbolic.next_state_pc,\n           Symbolic.next_state_reg_and_pc, Symbolic.next_state in *;\n    simpl in *;\n    unfold Sym.rvec_next, Sym.rvec_jump, Sym.rvec_store, Sym.rvec_simple,\n           Sym.rvec_step in *;\n    simpl in *.\n\n  - (* Nop *)\n    undo1 NEXT rvec; undo1 def_rvec cid;\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    exists (AState (pc+1)%w AR AM AC INTERNAL c). split.\n    + eapply Abs.step_nop; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n\n  - (* Const *)\n    undo1 NEXT rvec;\n      destruct told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 NEXT regs';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    evar (AR' : registers mt);\n      exists (AState (pc+1)%w AR' AM AC INTERNAL c); split;\n      subst AR'.\n    + eapply Abs.step_const; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eassumption.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * unfold updm; rewrite /refine_registers /pointwise in RREGS;\n          specialize RREGS with r.\n        case: (getm AR r) RREGS => [a|] RREGS;\n          [reflexivity | rewrite OLD in RREGS; done].\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n      rewrite /refine_registers /pointwise in RREGS *; intros r'.\n      rewrite setmE.\n      destruct (r' == r) eqn:EQ_r; move/eqP in EQ_r; [subst r'|].\n      * erewrite getm_upd_eq by eauto.\n        by unfold refine_reg_b.\n      * erewrite getm_upd_neq with (m' := regs') by eauto.\n        apply RREGS.\n\n  - (* Mov *)\n    undo1 NEXT rvec;\n      destruct t1,told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 NEXT regs';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    rewrite /refine_registers /pointwise in RREGS.\n    destruct (getm AR r1) as [x1|] eqn:GET1;\n      [| specialize RREGS with r1; rewrite R1W GET1 in RREGS; done].\n    destruct (getm AR r2) as [x2|] eqn:GET2;\n      [| specialize RREGS with r2; rewrite OLD GET2 in RREGS; done].\n    evar (AR' : registers mt);\n      exists (AState (pc+1)%w AR' AM AC INTERNAL c); split;\n      subst AR'.\n    + eapply Abs.step_mov; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS => [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * eassumption.\n      * unfold updm; rewrite GET2; reflexivity.\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n      rewrite /refine_registers /pointwise in RREGS *; intros r2'.\n      rewrite setmE.\n      destruct (r2' == r2) eqn:EQ_r2; move/eqP in EQ_r2; [subst r2'|].\n      * erewrite getm_upd_eq by eauto.\n        by specialize RREGS with r1; rewrite GET1 R1W /refine_reg_b in RREGS *.\n      * erewrite getm_upd_neq with (m' := regs') by eauto.\n        apply RREGS.\n\n  - (* Binop *)\n    undo1 NEXT rvec;\n      destruct t1,t2,told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 NEXT regs';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    rewrite /refine_registers /pointwise in RREGS.\n    destruct (getm AR r1) as [x1|] eqn:GET1;\n      [| specialize RREGS with r1; rewrite R1W GET1 in RREGS; done].\n    destruct (getm AR r2) as [x2|] eqn:GET2;\n      [| specialize RREGS with r2; rewrite R2W GET2 in RREGS; done].\n    destruct (getm AR r3) as [x3|] eqn:GET3;\n      [| specialize RREGS with r3; rewrite OLD GET3 in RREGS; done].\n    evar (AR' : registers mt);\n      exists (AState (pc+1)%w AR' AM AC INTERNAL c); split;\n      subst AR'.\n    + eapply Abs.step_binop; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * eassumption.\n      * eassumption.\n      * unfold updm; rewrite GET3; reflexivity.\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n      unfold updm; rewrite /refine_registers /pointwise in RREGS *; intros r3'.\n      rewrite setmE.\n      destruct (r3' == r3) eqn:EQ_r3; move/eqP in EQ_r3; [subst r3'|].\n      * erewrite getm_upd_eq by eauto.\n        { unfold refine_reg_b. apply/eqP; f_equal.\n          - by specialize RREGS with r1;\n               rewrite GET1 R1W /refine_reg_b in RREGS *; apply/eqP.\n          - by specialize RREGS with r2;\n               rewrite GET2 R2W /refine_reg_b in RREGS *; apply/eqP. }\n      * erewrite getm_upd_neq with (m' := regs') by eauto.\n        apply RREGS.\n\n  - (* Load *)\n    undo1 NEXT rvec;\n      destruct t1,t2,told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 NEXT regs';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I'' W'']; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [ac|] // _.\n    rewrite /refine_registers /refine_memory /pointwise  in RREGS RMEMS.\n    destruct (getm AR r1) as [x1|] eqn:GET1;\n      [| specialize RREGS with r1; rewrite R1W GET1 in RREGS; done].\n    destruct (getm AR r2) as [xold|] eqn:GET2;\n      [| specialize RREGS with r2; rewrite OLD GET2 in RREGS; done].\n    assert (EQ1 : x1 = w1) by\n      (by specialize RREGS with r1;\n          rewrite R1W GET1 /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x1.\n    destruct (getm AM w1) as [x2|] eqn:GETM1;\n      [|specialize RMEMS with w1; rewrite MEM1 GETM1 in RMEMS; done].\n    evar (AR' : registers mt);\n      exists (AState (pc+1)%w AR' AM AC INTERNAL ac); split;\n      subst AR'.\n    + eapply Abs.step_load; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * eassumption.\n      * eassumption.\n      * unfold updm; rewrite GET2; reflexivity.\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          (* eassumption picked the wrong thing first *)\n                          solve [ apply def_cid\n                                | eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n      unfold updm; rewrite /refine_registers /pointwise in RREGS *; intros r2'.\n      rewrite setmE.\n      destruct (r2' == r2) eqn:EQ_r2; move/eqP in EQ_r2; [subst r2'|].\n      * erewrite getm_upd_eq by eauto.\n        by specialize RMEMS with w1;\n           rewrite GETM1 MEM1 /refine_mem_loc_b /refine_reg_b in RMEMS *.\n      * erewrite getm_upd_neq with (m' := regs') by eauto.\n        apply RREGS.\n\n  - (* Store *)\n    undo1 NEXT rvec;\n      destruct t1,t2,told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 def_rvec WRITE_OK;\n      undo1 NEXT mem';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I'' W'']; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [ac|] // _.\n    rewrite /refine_registers /refine_memory /pointwise  in RREGS RMEMS.\n    destruct (getm AR r1) as [x1|] eqn:GET1;\n      [| specialize RREGS with r1; rewrite R1W GET1 in RREGS; done].\n    destruct (getm AR r2) as [x2|] eqn:GET2;\n      [| specialize RREGS with r2; rewrite R2W GET2 in RREGS; done].\n    assert (EQ1 : x1 = w1) by\n      (by specialize RREGS with r1;\n          rewrite R1W GET1 /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x1.\n    assert (EQ1 : x2 = w2) by\n      (by specialize RREGS with r2;\n          rewrite R2W GET2 /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x2.\n    destruct (getm AM w1) as [xold|] eqn:GETM1;\n      [|specialize RMEMS with w1; rewrite OLD GETM1 in RMEMS; done].\n    evar (AM' : memory mt);\n      exists (AState (pc+1)%w AR AM' AC INTERNAL ac); split;\n      subst AM'.\n    + eapply Abs.step_store; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS => [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * eassumption.\n      * eassumption.\n      * { have ac_cid: get_compartment_id (SState mem reg pc@(Sym.PC F cid') extra) ac ?= cid.\n            apply/eqP.\n            by eapply prove_get_compartment_id; eauto.\n          undo1 def_cid COND; unoption.\n          rewrite in_setU.\n          case/Abs.in_compartment_opt_correct/andP: COMP => ac_in_AC ?.\n          case/orP: WRITE_OK => [/eqP ?|cid_in_W].\n          - subst cid.\n            case: SGOOD => [[SGMEM _] _].\n            apply/orP. left.\n            apply (get_compartment_id_in_compartment COMPSWD IDSWD IDSU ac_in_AC).\n            by rewrite /Sym.sget OLD /=.\n          - by rewrite (STWF _ _ ac_in_AC ac_cid) in_set /Sym.sget OLD /= cid_in_W orbT. }\n      * unfold updm; rewrite GETM1; reflexivity.\n    + assert (SAME :\n                equilabeled\n                  (SState mem  reg pc@(Sym.PC F cid')             extra)\n                  (SState mem' reg (pc+1)%w@(Sym.PC INTERNAL cid) extra)). {\n        rewrite /equilabeled; intros p.\n        destruct (p == w1) eqn:EQ_w1; move/eqP in EQ_w1; [subst p|].\n        - apply getm_upd_eq in def_mem'; auto.\n          by rewrite /Sym.sget OLD def_mem'.\n        - apply getm_upd_neq with (key' := p) in def_mem'; auto.\n          rewrite /Sym.sget def_mem';\n          case GET: (getm mem p) => [[x L]|]; try by [].\n          destruct (if      p == isolate_addr              then _\n                    else if p == add_to_jump_targets_addr  then _\n                    else if p == add_to_store_targets_addr then _\n                    else None)\n            as [[]|]; auto.\n      }\n      constructor; simpl; try done.\n      * { unfold updm;\n            rewrite /refine_memory /refine_mem_loc_b /pointwise in RMEMS *;\n            intros p.\n        rewrite setmE.\n        destruct (p == w1) eqn:EQ_w1; move/eqP in EQ_w1; [subst p|].\n        - erewrite getm_upd_eq by eauto.\n          by specialize RMEMS with w1; rewrite GETM1 in RMEMS *.\n        - erewrite getm_upd_neq with (m' := mem') by eauto.\n          apply RMEMS. }\n      * move=> c' Hc'.\n        apply COMPSWD.\n        move: def_mem' Hc'.\n        rewrite !/Sym.sget /updm.\n        case GET': (getm mem w1) => [[x tg]|] // [<-].\n        rewrite setmE.\n        by have [->|NE //] := (c' =P w1); rewrite GET'.\n      * move=> c' c'_in_AC.\n        rewrite -(get_compartment_id_same _ SAME).\n        by apply IDSWD.\n      * move=> c1 c2 c1_in_AC c2_in_AC.\n        rewrite -!(get_compartment_id_same _ SAME).\n        by apply IDSU.\n      * move=> c' c'_id c'_in_AC.\n        rewrite -(get_compartment_id_same _ SAME) => Hc'_id.\n        rewrite (JTWF _ _ c'_in_AC Hc'_id).\n        apply/setP => p.\n        rewrite !in_set.\n        move: (SAME p).\n        rewrite !/Sym.sget.\n        case: (getm mem p) => [[? ?]|]; case: (getm mem' p) => [[? ?]|] //=;\n        by [congruence | repeat case: (p =P _) => //= _; try congruence].\n      * move=> c' c'_id c'_in_AC.\n        rewrite -(get_compartment_id_same _ SAME) => Hc'_id.\n        rewrite (STWF _ _ c'_in_AC Hc'_id).\n        apply/setP => p.\n        rewrite !in_set.\n        move: (SAME p).\n        rewrite !/Sym.sget.\n        case: (getm mem p) => [[? ?]|]; case: (getm mem' p) => [[? ?]|] //=;\n        by [congruence | repeat case: (p =P _) => //= _; try congruence].\n      * rewrite /refine_previous_b; simpl.\n        erewrite <-get_compartment_id_same; [|eassumption].\n        (* eassumption picked the wrong thing first *)\n        eapply prove_get_compartment_id; try apply def_cid; try eassumption;\n          rewrite /Sym.sget /= PC; reflexivity.\n      * have not_syscall : w1 \\notin syscall_addrs.\n        { apply/negP => contra; case/and3P: RSC => /allP /(_ _ contra).\n          by rewrite GETM1. }\n        case/and3P: RSC => [Ha Hs Hu]; apply/and3P; split=> //.\n          apply/allP=> x x_in_sc; rewrite setmE; move: x_in_sc not_syscall.\n          by have [{x}-> ->|_ /(allP Ha _)] := altP (x =P _).\n        apply/allP=> x x_in_sc.\n        move: def_mem'; rewrite /updm OLD /= => - [<-].\n        rewrite setmE; move: x_in_sc not_syscall.\n        by have [{x}-> ->|_ /(allP Hs _)] := altP (x =P _).\n      * rewrite /Sym.good_internal /= in RINT *.\n        case: RINT=> /= Hbounded Hisolate.\n        { split.\n          - move=> p cid''' I''' W'''.\n            rewrite /Sym.sget.\n            have [{p} -> | NEQ] := (p =P w1).\n            + rewrite (getm_upd_eq def_mem'); move => [<- <- <-].\n              apply (Hbounded w1 c I W).\n              by rewrite /Sym.sget OLD.\n            + rewrite (getm_upd_neq NEQ def_mem').\n              by apply (Hbounded p cid''' I''' W''').\n          - move=> p sc.\n            have [{p} ->|NEQp] := p =P w1;\n            have [{sc} ->|NEQsc] := sc =P w1 => //.\n            + rewrite /Sym.sget\n                      (getm_upd_eq def_mem')\n                      (getm_upd_neq NEQsc def_mem') => sc_is_sc E.\n              by rewrite (Hisolate w1 sc sc_is_sc) // -E /Sym.sget OLD.\n            + rewrite /Sym.sget\n                      (getm_upd_eq def_mem')\n                      (getm_upd_neq NEQp def_mem') => sc_is_sc E.\n              by rewrite (Hisolate p w1 sc_is_sc) // E /Sym.sget OLD.\n            + rewrite /Sym.sget\n                      (getm_upd_neq NEQp def_mem')\n                      (getm_upd_neq NEQsc def_mem').\n              by apply (Hisolate p sc). }\n  - (* Jump *)\n    undo1 NEXT rvec;\n      destruct t1; try discriminate;\n      undo1 def_rvec cid;\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    rewrite /refine_registers /pointwise in RREGS.\n    destruct (getm AR r) as [x|] eqn:GET;\n      [| specialize RREGS with r; rewrite RW GET in RREGS; done].\n    assert (EQ : x = w) by\n      (by specialize RREGS with r;\n          rewrite RW GET /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x.\n    evar (AR' : registers mt);\n      exists (AState w AR' AM AC JUMPED c); split;\n      subst AR'.\n    + eapply Abs.step_jump; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * assumption.\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n  - (* Bnz *)\n    undo1 NEXT rvec;\n      destruct t1; try discriminate;\n      undo1 def_rvec cid;\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    rewrite /refine_registers /pointwise in RREGS.\n    destruct (getm AR r) as [x|] eqn:GET;\n      [| specialize RREGS with r; rewrite RW GET in RREGS; done].\n    assert (EQ : x = w) by\n      (by specialize RREGS with r;\n          rewrite RW GET /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x.\n    evar (AR' : registers mt);\n      exists (AState (pc + (if w == 0 then 1 else swcast n))%w\n                     AR' AM AC INTERNAL c); split;\n      subst AR'.\n    + eapply Abs.step_bnz; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eauto.\n      * eassumption.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n\n  - (* Jal *)\n    undo1 NEXT rvec;\n      destruct t1; try discriminate;\n      destruct told; try discriminate;\n      undo1 def_rvec cid;\n      undo1 NEXT regs';\n      unfold Sym.can_execute,Sym.compartmentalization_rvec in *;\n      unoption; simpl in *.\n    destruct tpc as [F cid']; try discriminate;\n      destruct ti as [cid'' I W]; try discriminate.\n    move/eqP in RPC; subst Apc.\n    move: (COMPSWD pc).\n    rewrite /Sym.sget PC => /(_ erefl).\n    case COMP: (Abs.in_compartment_opt _ _) => [c|] // _.\n    rewrite /refine_registers /pointwise in RREGS.\n    destruct (getm AR r) as [x|] eqn:GET;\n      [| specialize RREGS with r; rewrite RW GET in RREGS; done].\n    assert (EQ : x = w) by\n      (by specialize RREGS with r;\n          rewrite RW GET /refine_reg_b in RREGS; move/eqP in RREGS);\n      subst x.\n    evar (AR' : registers mt);\n      exists (AState w AR' AM AC JUMPED c); split;\n      subst AR'.\n    + eapply Abs.step_jal; try reflexivity.\n      * unfold Abs.decode.\n        unfold refine_memory,pointwise,refine_mem_loc_b in RMEMS;\n          specialize RMEMS with pc; rewrite PC in RMEMS.\n        by case: (AM pc) RMEMS=> [?|] //= /eqP ->; eauto.\n      * by apply (prove_permitted_now_in AGOOD SGOOD PC def_cid).\n      * assumption.\n      * unfold updm; rewrite /refine_registers /pointwise in RREGS.\n        match goal with |- context[getm AR ?ra] =>\n          (* This finds the type class instances *)\n          case: (getm AR ra) (RREGS ra) => {RREGS} RREGS;\n            [reflexivity | rewrite OLD in RREGS; done]\n        end.\n    + constructor; simpl;\n        try solve [done | eapply (prove_get_compartment_id SGOOD);\n                          solve [ eassumption\n                                | rewrite /Sym.sget /= PC; reflexivity ]].\n      rewrite /refine_registers /pointwise in RREGS *; intros r'.\n      rewrite setmE.\n      destruct (r' == ra) eqn:EQ_r'; move/eqP in EQ_r'; [subst r'|].\n      * erewrite getm_upd_eq by eauto.\n        by simpl.\n      * erewrite getm_upd_neq with (m' := regs') by eauto.\n        apply RREGS.\n  - (* Syscall *)\n    rewrite mkfmapE /= !(eq_sym pc) in GETCALL.\n    destruct (isolate_addr == pc) eqn:EQ;\n      [ move/eqP in EQ; subst\n      | clear EQ; destruct (add_to_jump_targets_addr == pc) eqn:EQ;\n        [ move/eqP in EQ; subst\n        | clear EQ; destruct (add_to_store_targets_addr == pc) eqn:EQ;\n          [ move/eqP in EQ; subst\n          | discriminate ]]];\n      inversion GETCALL; subst;\n      rewrite /Symbolic.run_syscall /Symbolic.transfer /sym_compartmentalization\n              /Sym.compartmentalization_handler /Symbolic.sem\n        in CALL;\n      [ eapply isolate_refined              in CALL\n      | eapply add_to_jump_targets_refined  in CALL\n      | eapply add_to_store_targets_refined in CALL ];\n      try constructor; try eassumption;\n      try solve [by destruct tpc; try done; move/eqP in RPC; subst];\n      destruct CALL as [ast' [STEP REFINE]];\n      exists ast'; split; auto;\n      [ eapply Abs.step_syscall with (sc := Abs.isolate              (mt:=mt))\n      | eapply Abs.step_syscall with (sc := Abs.add_to_jump_targets  (mt:=mt))\n      | eapply Abs.step_syscall with (sc := Abs.add_to_store_targets (mt:=mt)) ];\n      try solve [reflexivity | eassumption];\n      destruct tpc as []; try discriminate; move/eqP in RPC; subst;\n      try match goal with |- context[getm AM ?addr] =>\n        by move/(_ addr): RMEMS; rewrite PC; case: (getm AM addr)\n      end;\n      rewrite /refine_syscall_addrs_b in RSC;\n      case/and3P: RSC => /= RS1 RS2 /and3P [RS3 RS4 _];\n      rewrite mkfmapE /= -!(eq_sym isolate_addr) eq_refl;\n      rewrite !in_cons /= in RS3 RS4.\n      * done.\n      * by destruct (isolate_addr == add_to_jump_targets_addr).\n      * by rewrite (eq_sym add_to_store_targets_addr);\n           destruct (isolate_addr == add_to_jump_targets_addr),\n                    (isolate_addr == add_to_store_targets_addr),\n                    (add_to_jump_targets_addr == add_to_store_targets_addr).\nQed.\n\nEnd RefinementSA.\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/refinementSA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.19066668023330938}}
{"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 TableDataOpsIntro.Specs.table_destroy.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition table_destroy1_spec (g_rd: Pointer) (map_addr: Z64) (rtt_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level, rtt_addr with\n    | VZ64 map_addr, VZ64 level, VZ64 rtt_addr =>\n      rely is_int64 map_addr; rely is_int64 rtt_addr; rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      rely is_int64 idx0; rely is_int64 idx1; rely is_int64 idx2; rely is_int64 idx3;\n      let rtt_gidx := __addr_to_gidx rtt_addr in\n      rely is_gidx rtt_gidx;\n      rely (peq (base g_rd) ginfo_loc);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RTT2 = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx;\n      when adt == query_oracle adt;\n      (* hold root lock *)\n      rely is_gidx root_gidx;\n      let adt := adt {log: EVT CPU_ID (ACQ root_gidx) :: log adt} in\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n      rely (gtype groot =? GRANULE_STATE_TABLE);\n      if level =? 1 then\n        (* walk until root *)\n        let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n        let adt :=  adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n        destroy_table root_gidx idx0 rtt_addr rtt_gidx 1 map_addr adt\n      else\n        (* walk deeper root *)\n        rely (level >? 1);\n        let entry0 := (g_data (gnorm groot)) @ idx0 in\n          rely is_int64 entry0;\n          let phys0 := __entry_to_phys entry0 3 in\n          let lv1_gidx := __addr_to_gidx phys0 in\n          rely is_int64 phys0;\n          if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n            (* level 1 valid, hold level 1 lock *)\n            let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n            let glv1 := (gs (share adt)) @ lv1_gidx in\n            rely prop_dec (glock glv1 = None);\n            rely (tbl_level (gaux glv1) =? 1);\n            if level =? 2 then\n              (* walk until level 1 *)\n              let adt :=  adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n              destroy_table lv1_gidx idx1 rtt_addr rtt_gidx 2 map_addr adt\n            else\n              (* walk deeper level 1 *)\n              rely (level >? 2);\n              rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n              rely (gtype glv1 =? GRANULE_STATE_TABLE);\n              let entry1 := (g_data (gnorm glv1)) @ idx1 in\n              rely is_int64 entry1;\n              let phys1 := __entry_to_phys entry1 3 in\n              let lv2_gidx := __addr_to_gidx phys1 in\n              rely is_int64 phys1;\n              if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n                (* level 2 valid, hold level 2 lock *)\n                let adt := adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv2_gidx) :: log adt} in\n                let glv2 := (gs (share adt)) @ lv2_gidx in\n                rely (tbl_level (gaux glv2) =? 2);\n                rely prop_dec (glock glv2 = None);\n                if level =? 3 then\n                  (* walk until level 2 *)\n                  let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n                  destroy_table lv2_gidx idx2 rtt_addr rtt_gidx 3 map_addr adt\n                else None\n              else\n                (* level 2 invalid *)\n                rely is_int lv2_gidx;\n                Some (adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: log adt}\n                          {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n          else\n            (* level 1 invalid *)\n            rely is_int lv1_gidx;\n            Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef1/Specs/table_destroy1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.19061759699090713}}
{"text": "Require Import 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.\nRequire Import sha.verif_sha_bdo2.\nRequire Import sha.verif_sha_bdo4.\nRequire Import sha.verif_sha_bdo7.\nRequire Import sha.verif_sha_bdo8.\nLocal Open Scope logic.\n\nLemma exp_prop: forall A P, exp (fun x: A => prop (P x)) = prop (exists x: A, P x).\nProof.\n  intros.\n  apply pred_ext; normalize.\n  + exists x; auto.\n  + destruct H as [x ?].\n    apply (exp_right x).\n    normalize.\nQed.\n(* move somewhere else *)\n\n\nLemma body_sha256_block_data_order: semax_body Vprog Gtot f_sha256_block_data_order sha256_block_data_order_spec.\nProof.\nstart_function.\nname a_ _a.\nname b_ _b.\nname c_ _c.\nname d_ _d.\nname e_ _e.\nname f_ _f.\nname g_ _g.\nname h_ _h.\nname l_ _l.\nname Ki _Ki.\nname in_ _in.\nname ctx_ _ctx.\nname i_ _i.\nname data_ _data.\nsimpl_stackframe_of.\nunfold POSTCONDITION, abbreviate.\n\nremember (hash_blocks init_registers hashed) as regs eqn:Hregs.\nassert (Lregs: length regs = 8%nat) \n  by (subst regs; apply length_hash_blocks; auto).\nassert (Zregs: Zlength regs = 8%Z)\n by (rewrite Zlength_correct; rewrite Lregs; reflexivity).\nforward. (* data = in; *)\napply (assert_PROP (isptr data)); [  entailer | intro ].\n normalize. \n match goal with |- semax _ _ ?c _ =>\n  eapply seq_assocN with (cs := sequenceN 8 c)\n end.\n*\n eapply semax_frame1.\n + eapply sha256_block_load8 with (ctx:=ctx); eassumption.\n + simplify_Delta; reflexivity.\n + rewrite Zregs.\n    instantiate (1:=[`(data_at_ Tsh (tarray tuint 16)) (eval_var _X (tarray tuint 16)),\n                         `(data_block sh (intlist_to_Zlist b) data),\n                         `(K_vector kv)]).\n    instantiate (1:=kv).\n   entailer!.\n + auto 50 with closed.\n*\nabbreviate_semax.\nsimpl.\nforward.  (* i = 0; *)\neapply semax_frame_seq\n with (Frame:= [`(array_at tuint Tsh (tuints (hash_blocks init_registers hashed)) 0 8) (eval_id _ctx) ]).\n+ replace Delta with Delta_loop1\n    by (simplify_Delta; reflexivity).\n    simple apply (sha256_block_data_order_loop1_proof\n     _ sh b ctx data regs); auto.\n    apply Zlength_length in H; auto.\n + rewrite Zregs.\n    unfold data_at_, tarray.\n    erewrite data_at_array_at; [| reflexivity | omega | reflexivity].\n   (* unfold_data_at 1%nat. (* this line should be like this *)*)\n        instantiate (1:=kv).\n   entailer!.\n + auto 50 with closed.\n +  simpl; abbreviate_semax.\n eapply semax_frame_seq\n with (Frame := [`(array_at tuint Tsh (tuints (hash_blocks init_registers hashed)) 0 8) (eval_id _ctx),\n                          `(data_block sh (intlist_to_Zlist b) data)]).\nmatch goal with |- semax _ _ ?c _ =>\n  change c with block_data_order_loop2\nend.\napply sha256_block_data_order_loop2_proof\n              with (regs:=regs)(b:=b); eassumption.\n instantiate (1:=kv).\nentailer!.\nauto 50 with closed.\nabbreviate_semax.\neapply seq_assocN with (cs := add_them_back).\neapply semax_frame1\n with (Frame := [\n   `(K_vector kv),\n  `(array_at_ tuint Tsh 0 16) (eval_var _X (tarray tuint 16)),\n  `(data_block sh (intlist_to_Zlist b) data)]).\napply (add_them_back_proof _ regs (Round regs (nthi b) 63) ctx); try assumption.\napply length_Round; auto.\nsimplify_Delta; reflexivity.\nrewrite <- Hregs.\n        instantiate (1:=kv).\nentailer!.\nauto 50 with closed.\nsimpl; abbreviate_semax.\nunfold POSTCONDITION, abbreviate; clear POSTCONDITION.\nreplace Delta with (initialized _t Delta_loop1) \n by (simplify_Delta; reflexivity).\nclear Delta.\nfold (hash_block regs b).\nsimple apply sha256_block_data_order_return; auto.\nQed.\n\n\n\n\n\n\n\n\n\n\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_bdo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1906175969909071}}
{"text": "Require Import Arith.\nRequire Import Setoid.\nRequire Import Pred PredCrash.\nRequire Import Word.\nRequire Import Prog ProgMonad.\nRequire Import Hoare.\nRequire Import BasicProg.\nRequire Import Omega.\nRequire Import Lia.\nRequire Import Log.\nRequire Import Array.\nRequire Import List ListUtils.\nRequire Import Bool.\nRequire Import Eqdep_dec.\nRequire Import SepAuto.\nRequire Import Rec.\nRequire Import FunctionalExtensionality.\nRequire Import NArith.\nRequire Import WordAuto.\nRequire Import RecArrayUtils LogRecArray.\nRequire Import GenSepN.\nRequire Import Balloc.\nRequire Import ListPred.\nRequire Import FSLayout.\nRequire Import AsyncDisk.\nRequire Import Rounding.\nRequire Import Errno.\nRequire Import DiskSet.\n\nImport SyncedMem.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nModule Type BlockPtrSig.\n\n  Parameter irec     : Type.               (* inode record type *)\n  Parameter iattr    : Type.               (* part of irec that BlockPtr does not touch *)\n  Parameter NDirect  : addr.               (* number of direct blocks *)\n\n  (* Number of direct blocks should be quite small to avoid word overflow \n     Using addrlen as its bound is arbitrary *)\n  Parameter NDirect_bound : NDirect <= addrlen.\n\n  Parameter IRLen    : irec -> addr.       (* get length *)\n  Parameter IRIndPtr : irec -> addr.       (* get indirect block pointer *)\n  Parameter IRDindPtr: irec -> addr.       (* doubly-indirect block pointer *)\n  Parameter IRTindPtr: irec -> addr.       (* triply-indirect block pointer *)\n  Parameter IRBlocks : irec -> list waddr. (* get direct block numbers *)\n  Parameter IRAttrs  : irec -> iattr.      (* get untouched attributes *)\n\n  (* setters *)\n  Parameter upd_len  : irec -> addr -> irec.\n  Parameter upd_irec : forall (r : irec) (len : addr) (ibptr : addr)\n                                                      (dibptr : addr)\n                                                      (tibptr : addr)\n                                                      (dbns : list waddr), irec.\n\n  (* setter equivalence *)\n  Parameter upd_irec_eq_upd_len : forall ir len, goodSize addrlen len ->\n    upd_len ir len = upd_irec ir len (IRIndPtr ir) (IRDindPtr ir) (IRTindPtr ir) (IRBlocks ir).\n\n  (* getter/setter lemmas *)\n  Parameter upd_len_get_len    : forall ir n, goodSize addrlen n -> IRLen (upd_len ir n) = n.\n  Parameter upd_len_get_ind    : forall ir n, IRIndPtr (upd_len ir n) = IRIndPtr ir.\n  Parameter upd_len_get_dind   : forall ir n, IRDindPtr (upd_len ir n) = IRDindPtr ir.\n  Parameter upd_len_get_tind   : forall ir n, IRTindPtr (upd_len ir n) = IRTindPtr ir.\n  Parameter upd_len_get_blk    : forall ir n, IRBlocks (upd_len ir n) = IRBlocks ir.\n  Parameter upd_len_get_iattr  : forall ir n, IRAttrs (upd_len ir n) = IRAttrs ir.\n\n  Parameter upd_irec_get_len   : forall ir len ibptr dibptr tibptr dbns,\n     goodSize addrlen len -> IRLen (upd_irec ir len ibptr dibptr tibptr dbns) = len.\n  Parameter upd_irec_get_ind   : forall ir len ibptr dibptr tibptr dbns,\n     goodSize addrlen ibptr -> IRIndPtr (upd_irec ir len ibptr dibptr tibptr dbns) = ibptr.\n  Parameter upd_irec_get_dind  : forall ir len ibptr dibptr tibptr dbns,\n     goodSize addrlen dibptr -> IRDindPtr (upd_irec ir len ibptr dibptr tibptr dbns) = dibptr.\n  Parameter upd_irec_get_tind  : forall ir len ibptr dibptr tibptr dbns,\n     goodSize addrlen tibptr -> IRTindPtr (upd_irec ir len ibptr dibptr tibptr dbns) = tibptr.\n  Parameter upd_irec_get_blk   : forall ir len ibptr dibptr tibptr dbns,\n     IRBlocks (upd_irec ir len ibptr dibptr tibptr dbns) = dbns.\n  Parameter upd_irec_get_iattr : forall ir len ibptr dibptr tibptr dbns,\n      IRAttrs (upd_irec ir len ibptr dibptr tibptr dbns) = IRAttrs ir.\n\n  Parameter get_len_goodSize  : forall ir, goodSize addrlen (IRLen ir).\n  Parameter get_ind_goodSize  : forall ir, goodSize addrlen (IRIndPtr ir).\n  Parameter get_dind_goodSize : forall ir, goodSize addrlen (IRDindPtr ir).\n  Parameter get_tind_goodSize : forall ir, goodSize addrlen (IRTindPtr ir).\n\nEnd BlockPtrSig.\n\n\n(* block pointer abstraction for individule inode *)\nModule BlockPtr (BPtr : BlockPtrSig).\n\n  Import BPtr.\n\n\n  (* RecArray for indirect blocks *)\n\n  Definition indrectype := Rec.WordF addrlen.\n\n  Module IndSig <: RASig.\n\n    Definition xparams := addr.\n    Definition RAStart := fun (x : xparams) => x.\n    Definition RALen := fun (_ : xparams) => 1.\n    Definition xparams_ok (_ : xparams) := True.\n\n    Definition itemtype := indrectype.\n    Definition items_per_val := valulen / (Rec.len itemtype).\n\n    Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n    Proof.\n      unfold items_per_val.\n      rewrite valulen_is; apply Nat.eqb_eq; compute; reflexivity.\n    Qed.\n\n  End IndSig.\n\n  Module IndRec  := LogRecArray IndSig.\n  Hint Extern 0 (okToUnify (IndRec.rep _ _) (IndRec.rep _ _)) => constructor : okToUnify.\n\n  Notation \"'NIndirect'\" := IndSig.items_per_val.\n  Notation \"'NBlocks'\"   := (NDirect + NIndirect + NIndirect ^ 2 + NIndirect ^ 3)%nat.\n\n  (* Various bounds *)\n  Lemma NIndirect_is : NIndirect = 512.\n  Proof.\n    unfold IndSig.items_per_val.\n    rewrite valulen_is; compute; auto.\n  Qed.\n\n  Lemma NBlocks_roundtrip : # (natToWord addrlen NBlocks) = NBlocks.\n  Proof.\n    rewrite wordToNat_natToWord_idempotent. auto.\n    repeat rewrite Nat2N.inj_add.\n    simpl. repeat rewrite Nat2N.inj_mul. simpl.\n    rewrite NIndirect_is.\n    eapply N.le_lt_trans.\n    repeat rewrite <- N.add_assoc.\n    apply N.add_le_mono_r.\n    unfold N.le.\n    rewrite <- Nat2N.inj_compare.\n    apply nat_compare_le.\n    apply NDirect_bound.\n    compute. reflexivity.\n  Qed.\n\n  Lemma NDirect_roundtrip : # (natToWord addrlen NDirect) = NDirect.\n  Proof.\n    intros.\n    eapply wordToNat_natToWord_bound with (bound := natToWord addrlen NBlocks).\n    rewrite NBlocks_roundtrip; omega.\n  Qed.\n\n  Lemma NIndirect_roundtrip : # (natToWord addrlen NIndirect) = NIndirect.\n  Proof.\n    intros.\n    eapply wordToNat_natToWord_bound with (bound := natToWord addrlen NBlocks).\n    rewrite NBlocks_roundtrip; omega.\n  Qed.\n\n  Lemma le_ndirect_goodSize : forall n,\n    n <= NDirect -> goodSize addrlen n.\n  Proof.\n    intros; eapply goodSize_word_bound; eauto.\n    rewrite NDirect_roundtrip; auto.\n  Qed.\n\n  Lemma le_nindirect_goodSize : forall n,\n    n <= NIndirect -> goodSize addrlen n.\n  Proof.\n    intros; eapply goodSize_word_bound; eauto.\n    rewrite NIndirect_roundtrip; auto.\n  Qed.\n\n  Lemma le_nblocks_goodSize : forall n,\n    n <= NBlocks -> goodSize addrlen n.\n  Proof.\n    intros; eapply goodSize_word_bound; eauto.\n    rewrite NBlocks_roundtrip; auto.\n  Qed.\n\n  Local Hint Resolve le_ndirect_goodSize le_nindirect_goodSize le_nblocks_goodSize.\n\n  (************** indirect blocks *)\n\n   Definition indrep_n_helper (Fs : @pred _ addr_eq_dec bool) bxp ibn iblocks :=\n    (if (addr_eq_dec ibn 0)\n      then [[ iblocks = repeat $0 NIndirect]] *\n           [[ Fs <=p=> emp ]]\n      else [[ BALLOCC.bn_valid bxp ibn ]] * IndRec.rep ibn iblocks *\n          [[ (Fs <=p=> ibn |->?) ]]\n    )%pred.\n\n  (* indlvl = 0 if ibn is the address of an indirect block,\n     indlvl = 1 for doubly indirect, etc. *)\n\n  Fixpoint indrep_n_tree indlvl bxp Fs ibn l :=\n    (match indlvl with\n    | 0 => indrep_n_helper Fs bxp ibn l\n    | S indlvl' =>\n      exists iblocks Fs' lFs,\n        [[ length lFs = length iblocks ]] *\n        [[ Fs <=p=> Fs' * pred_fold_left lFs ]] *\n        indrep_n_helper Fs' bxp ibn iblocks *\n        exists l_part, [[ l = concat l_part ]] *\n        listmatch (fun ibn'_fs l' =>\n          indrep_n_tree indlvl' bxp (snd ibn'_fs) (# (fst ibn'_fs)) l') (combine iblocks lFs) l_part\n    end)%pred.\n\n  Hint Extern 0 (okToUnify (indrep_n_helper _ _ _ _) (indrep_n_helper _ _ _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (indrep_n_tree _ _ _ _ _) (indrep_n_tree _ _ _ _ _ )) => constructor : okToUnify.\n  Local Hint Extern 0 (okToUnify (listmatch _ ?a _) (listmatch _ ?a _)) => constructor : okToUnify.\n  Local Hint Extern 0 (okToUnify (listmatch _ _ ?b) (listmatch _ _ ?b)) => constructor : okToUnify.\n  Local Hint Extern 0 (okToUnify (listmatch _ (combine ?a _) _) (listmatch _ (combine ?a _) _)) => constructor : okToUnify.\n\n  (* Necessary to make subst work when there's a recursive term like:\n     l = firstn (length l) ... *)\n  Set Regular Subst Tactic.\n  Local Hint Resolve IndRec.Defs.items_per_val_not_0.\n  Local Hint Resolve IndRec.Defs.items_per_val_gt_0'.\n\n  Lemma off_mod_len_l : forall T off (l : list T), length l = NIndirect -> off mod NIndirect < length l.\n  Proof.\n    intros. rewrite H; apply Nat.mod_upper_bound; auto.\n  Qed.\n\n  Fact divmod_n_zeros : forall n, fst (Nat.divmod n 0 0 0) = n.\n  Proof.\n    exact Nat.div_1_r.\n  Qed.\n\n  Hint Rewrite divmod_n_zeros using auto.\n  Local Hint Resolve Nat.pow_nonzero off_mod_len_l mult_neq_0.\n  Local Hint Resolve mul_ge_l mul_ge_r.\n\n  Fact sub_sub_comm : forall a b c, a - b - c = a - c - b.\n  Proof.\n    intros.\n    rewrite <- Nat.sub_add_distr. rewrite plus_comm.\n    rewrite Nat.sub_add_distr. auto.\n  Qed.\n\n  Fact sub_S_1 : forall n, n > 0 -> S (n - 1) = n.\n  Proof.\n    intros. omega.\n  Qed.\n\n  Fact sub_le_eq_0 : forall a b, a <= b -> a - b = 0.\n  Proof.\n    intros. omega.\n  Qed.\n\n  Local Hint Resolve mod_le_r.\n  Local Hint Resolve divup_gt_0.\n\n  Ltac min_cases :=\n    let H := fresh in let H' := fresh in\n    edestruct Min.min_spec as [ [H H']|[H H'] ];\n    rewrite H' in *; clear H'.\n\n  Ltac mult_nonzero := \n    repeat (match goal with\n    | [ |- mult _ _ <> 0 ] => apply mult_neq_0\n    | [ |- mult _ _ > 0 ] => apply lt_mul_mono\n    | [ |- _ ^ _ <> 0 ] => apply Nat.pow_nonzero\n    | [ |- _ > 0 ] => unfold gt\n    | [ |- 0 < _ ] => apply neq_0_lt\n    | [ |- 0 <> _ ] => apply not_eq_sym\n    | [ |- _] => solve [auto]\n    | [ |- ?N <> 0 ] => subst N\n    end).\n\n  Ltac divide_solve := match goal with\n    | [ |- Nat.divide 1 ?n ] => apply Nat.divide_1_l\n    | [ |- Nat.divide ?n 0 ] => apply Nat.divide_0_r\n    | [ |- Nat.divide ?a ?a ] => apply Nat.divide_refl\n    | [ |- Nat.divide ?a (?b * ?c) ] => solve [apply Nat.divide_mul_l; divide_solve |\n                                               apply Nat.divide_mul_r; divide_solve ]\n    | [ |- Nat.divide ?a (?b + ?c) ] => apply Nat.divide_add_r; solve [divide_solve]\n    | [ |- Nat.divide ?a (?b - ?c) ] => apply Nat.divide_sub_r; solve [divide_solve]\n    | [ |- Nat.divide ?n (roundup _ ?n) ] => unfold roundup; solve [divide_solve]\n    | [H : ?a mod ?b = 0 |- Nat.divide ?b ?a ] => apply Nat.mod_divide; mult_nonzero; solve [divide_solve]\n  end.\n\n  Local Hint Extern 1 (Nat.divide ?a ?b) => divide_solve.\n  Local Hint Extern 1 (?a <= roundup ?a ?b) => apply roundup_ge; mult_nonzero.\n  Local Hint Extern 1 (?a mod ?b < ?b) => apply Nat.mod_upper_bound; mult_nonzero.\n  Local Hint Resolve roundup_le.\n\n  Ltac incl_solve := match goal with\n    | [|- incl ?a ?a ] => apply incl_refl\n    | [|- incl (remove _ _ ?l) ?l ] => apply incl_remove\n    | [|- incl ?l (_ :: ?l)] => apply incl_tl; solve [incl_solve]\n    | [H : incl ?a ?b |- incl ?a ?c ] => eapply incl_tran; [> apply H|]; solve [incl_solve]\n    | [H : incl ?b ?c |- incl ?a ?c ] => eapply incl_tran; [> |apply H]; solve [incl_solve]\n  end.\n\n  Local Hint Extern 1 (incl ?a ?b) => incl_solve.\n\n  Ltac psubst :=\n    repeat match goal with p: pred |- _ =>\n      match goal with\n      | H: p <=p=> _ |- _ =>\n        rewrite H in *; clear H; clear p\n      | H: _ <=p=> p |- _ =>\n        rewrite <- H in *; clear H; clear p\n      end\n    end.\n\n  Theorem indrep_n_helper_valid : forall bxp bn Fs l,\n    bn <> 0 -> indrep_n_helper Fs bxp bn l <=p=> [[ BALLOCC.bn_valid bxp bn ]] * IndRec.rep bn l * [[ (Fs <=p=> bn |->?) ]].\n  Proof.\n    intros. unfold indrep_n_helper.\n    destruct addr_eq_dec; try congruence.\n    split; cancel; eauto.\n  Qed.\n\n  Theorem indrep_n_tree_valid : forall indlvl bxp Fs ir l,\n    ir <> 0 -> indrep_n_tree indlvl bxp Fs ir l <=p=> indrep_n_tree indlvl bxp Fs ir l * [[ BALLOCC.bn_valid bxp ir ]].\n  Proof.\n    destruct indlvl; intros; simpl.\n    repeat rewrite indrep_n_helper_valid by auto. split; cancel; eauto.\n    split; intros m' H'; destruct_lift H'; pred_apply; cancel.\n    rewrite indrep_n_helper_valid in * by auto.\n    destruct_lifts. auto.\n  Qed.\n\n  Lemma indrep_n_helper_0 : forall Fs bxp l,\n    indrep_n_helper Fs bxp 0 l <=p=> [[ l = repeat $0 NIndirect ]] * [[ Fs <=p=> emp ]].\n  Proof.\n    unfold indrep_n_helper; intros; split; cancel.\n  Qed.\n\n  Lemma indrep_n_helper_0' : forall bxp l,\n    indrep_n_helper emp bxp 0 l <=p=> [[ l = repeat $0 NIndirect ]].\n  Proof.\n    unfold indrep_n_helper; intros; split; cancel.\n  Qed.\n\n  Lemma pred_fold_left_Forall_emp: forall AT AEQ V (l : list (@pred AT AEQ V)),\n    Forall (fun x => x <=p=> emp) l ->\n    pred_fold_left l <=p=> emp.\n  Proof.\n    unfold pred_fold_left.\n    destruct l; auto; intros.\n    inversion H; subst.\n    clear H.\n    generalize dependent p.\n    induction l; cbn; intros.\n    auto.\n    inversion H3; subst.\n    apply IHl; auto.\n    rewrite H2.\n    rewrite H1.\n    split; cancel.\n  Qed.\n\n  Lemma pred_fold_left_cons: forall AT AEQ V (l : list (@pred AT AEQ V)) x,\n    pred_fold_left (x :: l) <=p=> x * pred_fold_left l.\n  Proof.\n    intros.\n    destruct l; cbn.\n    split; cancel.\n    generalize dependent p.\n    generalize dependent x.\n    induction l; cbn; intros.\n    split; cancel.\n    rewrite IHl.\n    rewrite IHl.\n    split; cancel.\n  Qed.\n\n  Lemma pred_fold_left_repeat_emp: forall AT AEQ V n,\n    pred_fold_left (repeat (@emp AT AEQ V) n) <=p=> emp.\n  Proof.\n    intros.\n    rewrite pred_fold_left_Forall_emp; auto.\n    auto using Forall_repeat.\n  Qed.\n\n  Lemma pred_fold_left_app: forall AT AEQ V (l l' : list (@pred AT AEQ V)),\n    pred_fold_left (l ++ l') <=p=> pred_fold_left l * pred_fold_left l'.\n  Proof.\n    induction l; intros.\n    split; cancel.\n    intros.\n    cbn [app].\n    repeat rewrite pred_fold_left_cons.\n    rewrite IHl.\n    split; cancel.\n  Qed.\n\n  Lemma pred_fold_left_selN_removeN: forall AT AEQ V (l : list (@pred AT AEQ V)) i,\n    pred_fold_left l <=p=> (selN l i emp) * pred_fold_left (removeN l i).\n  Proof.\n    unfold removeN.\n    intros.\n    destruct (lt_dec i (length l)).\n    rewrite <- firstn_skipn with (l := l) at 1.\n    repeat rewrite pred_fold_left_app.\n    erewrite skipn_selN_skipn by eauto.\n    rewrite pred_fold_left_cons.\n    split; cancel.\n    rewrite selN_oob, firstn_oob, skipn_oob by omega.\n    rewrite app_nil_r.\n    split; cancel.\n  Qed.\n\n  Lemma pred_fold_left_updN_removeN: forall AT AEQ V l (p : @pred AT AEQ V) i,\n    i < length l ->\n    pred_fold_left (updN l i p) <=p=> pred_fold_left (removeN l i) * p.\n  Proof.\n    intros.\n    rewrite pred_fold_left_selN_removeN.\n    rewrite selN_updN_eq, removeN_updN by auto.\n    split; cancel.\n  Qed.\n\n  Lemma in_combine_repeat_l : forall A B (a : A) n (b : list B) x,\n    In x (combine (repeat a n) b) ->\n    fst x = a.\n  Proof.\n    induction n; cbn; intuition.\n    destruct b; cbn in *; intuition eauto.\n    subst; auto.\n  Qed.\n\n  Lemma listmatch_combine_l_length: forall A B C AT AEQ V (prd : _ -> _ -> @pred AT AEQ V) F m\n    (a : list A) (b : list B) (c : list C),\n    length a = length b ->\n    (F * listmatch prd (combine a b) c)%pred m -> length a = length c /\\ length b = length c.\n  Proof.\n    intros.\n    rewrite listmatch_length_pimpl in H0.\n    destruct_lifts.\n    rewrite combine_length in *.\n    rewrite Nat.min_l in * by omega.\n    omega.\n  Qed.\n\n  Lemma listmatch_combine_l_length_l: forall A B C AT AEQ V (prd : _ -> _ -> @pred AT AEQ V) F m\n    (a : list A) (b : list B) (c : list C),\n    length a = length b ->\n    (F * listmatch prd (combine a b) c)%pred m -> length a = length c.\n  Proof.\n    intros.\n    eapply listmatch_combine_l_length with (a := a) (b := b).\n    auto.\n    pred_apply' H0; cancel.\n  Qed.\n\n  Lemma listmatch_combine_l_length_r: forall A B C AT AEQ V (prd : _ -> _ -> @pred AT AEQ V) F m\n    (a : list A) (b : list B) (c : list C),\n    length a = length b ->\n    (F * listmatch prd (combine a b) c)%pred m -> length b = length c.\n  Proof.\n    intros.\n    eapply listmatch_combine_l_length with (a := a) (b := b).\n    auto.\n    pred_apply' H0; cancel.\n  Qed.\n\n  Lemma listmatch_combine_l_length_pimpl: forall A B C AT AEQ V (prd : _ -> _ -> @pred AT AEQ V)\n    (a : list A) (b : list B) (c : list C),\n    length a = length b ->\n    listmatch prd (combine a b) c =p=> [[ length a = length c /\\ length b = length c ]]\n      * listmatch prd (combine a b) c.\n  Proof.\n    intros.\n    rewrite listmatch_length_pimpl at 1.\n    rewrite combine_length.\n    substl (length a).\n    rewrite Nat.min_id.\n    cancel.\n  Qed.\n\n  Theorem indrep_n_tree_0 : forall indlvl bxp Fs l,\n    indrep_n_tree indlvl bxp Fs 0 l <=p=> [[ l = repeat $0 (NIndirect ^ S indlvl)]] * [[ Fs <=p=> emp ]].\n  Proof.\n    induction indlvl; simpl; intros.\n    rewrite mult_1_r, indrep_n_helper_0; split; cancel.\n    setoid_rewrite indrep_n_helper_0.\n    split.\n    - norml.\n      cbv [stars pred_fold_left fold_left].\n      rewrite listmatch_combine_l_length_pimpl by auto.\n      rewrite listmatch_lift_r.\n      rewrite listmatch_lift_l.\n      rewrite listmatch_emp. cancel.\n      erewrite concat_hom_repeat; eauto.\n      autorewrite with lists in *|-.\n      repeat f_equal; eauto.\n      psubst.\n      denote combine as Hc.\n      rewrite Forall_combine_r in Hc.\n      rewrite pred_fold_left_Forall_emp by eauto.\n      split; cancel.\n      auto.\n      instantiate (1 := fun x => (snd x) <=p=> emp).\n      cbn; intros. reflexivity.\n      instantiate (1 := fun _ _ => emp).\n      cancel.\n      cbn beta; intros.\n      apply piff_refl.\n      cbn beta. intros.\n      erewrite in_combine_repeat_l by eauto.\n      rewrite IHindlvl. split; cancel.\n    - norm.\n      cancel.\n      eassign (repeat (@emp _ addr_eq_dec bool) NIndirect).\n      rewrite listmatch_emp_piff. cancel.\n      rewrite combine_repeat.\n      repeat rewrite repeat_length. reflexivity.\n      rewrite combine_repeat.\n      intros x y; intros.\n      erewrite repeat_spec with (y := x) by eauto.\n      erewrite repeat_spec with (y := y) by eauto.\n      cbn.\n      repeat match goal with H: In _ _ |- _ => eapply repeat_spec in H end.\n      subst.\n      eassign (@natToWord addrlen 0).\n      rewrite IHindlvl.\n      split; cancel.\n      autorewrite with lists.\n      rewrite pred_fold_left_repeat_emp.\n      intuition eauto.\n      split; cancel.\n      erewrite concat_hom_repeat.\n      2: eapply Forall_repeat; reflexivity.\n      autorewrite with lists; eauto.\n  Qed.\n\n  Lemma listmatch_indrep_n_tree_empty': forall indlvl n bxp,\n    listmatch (fun x y => indrep_n_tree indlvl bxp (snd x) # (fst x) y)\n      (combine (repeat (@natToWord addrlen 0) n) (repeat emp n)) (repeat (repeat $0 (NIndirect ^ (S indlvl))) n) <=p=> emp.\n  Proof.\n    intros.\n    rewrite listmatch_emp_piff.\n    autorewrite with lists; auto.\n    split; cancel.\n    intros.\n    rewrite combine_repeat in *.\n    eapply repeat_spec in H.\n    eapply repeat_spec in H0.\n    subst.\n    rewrite indrep_n_tree_0.\n    split; cancel.\n  Qed.\n\n  Lemma listmatch_indrep_n_tree_empty'': forall indlvl n fsl l bxp,\n    length fsl = n ->\n    listmatch (fun x y => indrep_n_tree indlvl bxp (snd x) # (fst x) y)\n      (combine (repeat (@natToWord addrlen 0) n) fsl) l =p=> [[ pred_fold_left fsl <=p=> emp ]] *\n        [[ l = (repeat (repeat $0 (NIndirect ^ (S indlvl))) n) ]].\n  Proof.\n    cbn -[Nat.div]; intros.\n    rewrite listmatch_lift_l with (P := fun x => snd x <=p=> emp).\n    erewrite listmatch_lift_r with (P := fun x => x = repeat $0 (NIndirect ^ (S indlvl))).\n    rewrite listmatch_emp_piff.\n    autorewrite with lists.\n    rewrite Nat.min_l by omega.\n    do 2 intro; destruct_lifts.\n    - repeat eapply sep_star_lift_apply'; unfold lift_empty; intuition.\n      rewrite Forall_combine_r in H1.\n      rewrite pred_fold_left_Forall_emp; eauto.\n      autorewrite with lists; eauto.\n      reflexivity.\n      eapply list_selN_ext.\n      autorewrite with lists; auto.\n      intros.\n      rewrite Forall_forall in *.\n      rewrite H2 with (x := selN l pos nil).\n      rewrite repeat_selN; auto; omega.\n      eapply in_selN; auto.\n    - instantiate (1 := fun x y => emp).\n      auto.\n    - instantiate (1 := fun x y => ([[ y = repeat $0 (NIndirect ^ (S indlvl)) ]])%pred).\n      split; cancel.\n    - intros.\n      erewrite in_combine_repeat_l in * by eauto.\n      rewrite indrep_n_tree_0.\n      split; cancel.\n  Qed.\n\n  Lemma listmatch_indrep_n_tree_empty: forall indlvl bxp,\n    let iblocks := (repeat $0 NIndirect) in\n    indrep_n_helper emp bxp 0 iblocks *\n    listmatch (fun x y => indrep_n_tree indlvl bxp (snd x) # (fst x) y)\n      (combine iblocks (repeat emp NIndirect)) (repeat (repeat $0 (NIndirect ^ (S indlvl))) NIndirect) <=p=> emp.\n  Proof.\n    cbn -[Nat.div]; intros.\n    rewrite listmatch_indrep_n_tree_empty'.\n    split; cancel.\n  Qed.\n\n  Theorem indrep_n_helper_bxp_switch : forall Fs bxp bxp' ir iblocks,\n    BmapNBlocks bxp = BmapNBlocks bxp' ->\n    indrep_n_helper Fs bxp ir iblocks <=p=> indrep_n_helper Fs bxp' ir iblocks.\n  Proof.\n    intros. unfold indrep_n_helper, BALLOCC.bn_valid. rewrite H. reflexivity.\n  Qed.\n\n  Theorem indrep_n_tree_bxp_switch : forall bxp bxp' indlvl Fs ir l,\n    BmapNBlocks bxp = BmapNBlocks bxp' ->\n    indrep_n_tree indlvl bxp Fs ir l <=p=> indrep_n_tree indlvl bxp' Fs ir l.\n  Proof.\n    induction indlvl; intros; simpl.\n    rewrite indrep_n_helper_bxp_switch by eassumption.\n    split; cancel.\n    split; cancel; eauto; rewrite indrep_n_helper_bxp_switch.\n    all : try rewrite listmatch_piff_replace; try cancel; auto.\n    all : intros x; destruct x; intros; simpl; rewrite IHindlvl; auto.\n  Qed.\n\n  Theorem indrep_n_helper_sm_sync_invariant : forall Fs bxp ir l m F,\n    (F * indrep_n_helper Fs bxp ir l)%pred m ->\n    sm_sync_invariant Fs.\n  Proof.\n    unfold indrep_n_helper.\n    intros.\n    destruct addr_eq_dec.\n    destruct_lifts.\n    erewrite sm_sync_invariant_piff by eauto.\n    apply sm_sync_invariant_emp.\n    destruct_lifts.\n    erewrite sm_sync_invariant_piff by eauto.\n    apply sm_sync_invariant_exis_ptsto.\n  Qed.\n\n  Lemma sm_sync_invariant_pred_fold_left: forall l,\n    Forall sm_sync_invariant l ->\n    sm_sync_invariant (pred_fold_left l).\n  Proof.\n    intros.\n    unfold pred_fold_left.\n    destruct l; cbn.\n    auto using sm_sync_invariant_emp.\n    inversion H; subst.\n    clear H.\n    generalize dependent p.\n    generalize dependent l.\n    induction l; cbn; intros.\n    auto.\n    inversion H3; subst.\n    apply IHl; auto.\n  Qed.\n\n  Theorem indrep_n_tree_sm_sync_invariant : forall bxp indlvl Fs ir l F m,\n    (F * indrep_n_tree indlvl bxp Fs ir l)%pred m ->\n    sm_sync_invariant Fs.\n  Proof.\n    induction indlvl; cbn; intros.\n    eapply indrep_n_helper_sm_sync_invariant.\n    pred_apply' H; cancel.\n    destruct_lifts.\n    erewrite sm_sync_invariant_piff by eauto.\n    apply sm_sync_invariant_sep_star.\n    eapply indrep_n_helper_sm_sync_invariant.\n    pred_apply' H; cancel.\n    apply sm_sync_invariant_pred_fold_left.\n    rewrite listmatch_lift_l in H.\n    destruct_lifts.\n    eapply Forall_combine_r; try eassumption.\n    auto.\n    intros; split; intro H'; apply H'.\n    intros.\n    split.\n    intros m' H'.\n    apply sep_star_comm.\n    apply sep_star_lift_apply'.\n    exact H'.\n    eapply IHindlvl with (m := m') (F := emp) (ir := # (fst x)).\n    pred_apply; cancel.\n    cancel.\n  Qed.\n\n  Theorem listpred_indrep_n_tree_0 : forall indlvl bxp Fs l,\n    listpred (fun l' => indrep_n_tree indlvl bxp Fs 0 l') l <=p=>\n      [[ Forall (fun x => x = repeat $0 (NIndirect ^ S indlvl) /\\ (Fs <=p=> emp))%type l ]].\n  Proof.\n    induction l; intros.\n    - split; cancel. constructor.\n    - simpl. rewrite IHl.\n      rewrite indrep_n_tree_0.\n      split; cancel.\n      all : match goal with [H : Forall _ _ |- _] => inversion H; intuition end.\n  Qed.\n\n  Lemma indrep_n_helper_length : forall F Fs bxp ibn l m,\n    (F * indrep_n_helper Fs bxp ibn l)%pred m -> length l = NIndirect.\n  Proof.\n    unfold indrep_n_helper, IndRec.rep, IndRec.items_valid.\n    intros; destruct addr_eq_dec; destruct_lift H; unfold lift_empty in *;\n    intuition; subst; autorewrite with lists; auto.\n    unfold IndRec.Defs.item in *; simpl in *. omega.\n  Qed.\n\n  Lemma indrep_n_helper_length_piff : forall Fs bxp ibn l,\n    indrep_n_helper Fs bxp ibn l <=p=> indrep_n_helper Fs bxp ibn l * [[ length l = NIndirect ]].\n  Proof.\n    intros.\n    split.\n    - intros m H.\n      pred_apply; cancel.\n      eapply indrep_n_helper_length with (m := m).\n      pred_apply; cancel.\n    - cancel.\n  Qed.\n\n  Lemma indrep_n_length_pimpl : forall indlvl bxp ibn Fs l,\n    indrep_n_tree indlvl bxp Fs ibn l <=p=>\n    [[ length l = NIndirect ^ (S indlvl) ]] * indrep_n_tree indlvl bxp Fs ibn l.\n  Proof.\n    induction indlvl; simpl; intros.\n    intros; split; intros m H; destruct_lift H; pred_apply; cancel.\n    erewrite indrep_n_helper_length with (m := m); eauto; try omega.\n    pred_apply; cancel.\n    intros; split; intros m H; destruct_lift H; pred_apply; cancel.\n    rewrite indrep_n_helper_length_piff, listmatch_length_pimpl in H; destruct_lift H.\n    rewrite listmatch_lift_r in H; destruct_lift H.\n    erewrite concat_hom_length; eauto.\n    rewrite combine_length_eq in * by congruence.\n    eassign (NIndirect ^ S indlvl).\n    f_equal; omega.\n    intros x y; destruct x.\n    intros.\n    rewrite IHindlvl.\n    instantiate (1 := fun x y => indrep_n_tree indlvl bxp (snd x) (# (fst x)) y).\n    split; cancel.\n  Qed.\n\n  Lemma listmatch_indrep_n_tree_forall_length : forall indlvl bxp (l1 : list (waddr * _)) l2,\n    listmatch (fun a l' => indrep_n_tree indlvl bxp (snd a) # (fst a) l') l1 l2 <=p=>\n    listmatch (fun a l' => indrep_n_tree indlvl bxp (snd a) # (fst a) l') l1 l2 *\n    [[Forall (fun sublist : list waddr => (length sublist = NIndirect * NIndirect ^ indlvl)%nat) l2]].\n  Proof.\n    intros.\n    split; [> | cancel].\n    rewrite listmatch_lift_r at 1. cancel. eauto.\n    intros.\n    destruct x.\n    rewrite indrep_n_length_pimpl. split; cancel.\n  Qed.\n\n  Local Hint Extern 1 (Forall (fun x => length x = _) _) => match goal with\n    | [H : context [listmatch (fun x y => indrep_n_tree _ _ (snd x) # (fst x) y) _ ?l]\n        |- Forall (fun x => length x = _) ?l ] =>\n          rewrite listmatch_indrep_n_tree_forall_length with (l2 := l) in H; destruct_lift H; solve [eassumption]\n    | [|- Forall _ (upd_range ?l _ _ _)] => apply forall_upd_range; autorewrite with lists; eauto\n  end.\n\n  Theorem indrep_n_helper_pts_piff : forall Fs bxp ir l,\n    ir <> 0 -> indrep_n_helper Fs bxp ir l <=p=> [[ length l = NIndirect ]] *\n                [[ BALLOCC.bn_valid bxp ir ]] * [[ Fs <=p=> ir |->? ]] *\n                ir |-> (IndRec.Defs.block2val l, []).\n  Proof.\n    intros.\n    unfold indrep_n_helper, IndRec.rep. destruct addr_eq_dec; try omega.\n    unfold IndRec.items_valid, IndSig.xparams_ok, IndSig.RAStart, IndSig.RALen.\n    rewrite mult_1_l. unfold Rec.well_formed. simpl.\n    split; cancel;\n    rewrite IndRec.Defs.ipack_one by (unfold IndRec.Defs.item in *; auto).\n    all : cancel.\n  Qed.\n\n  Lemma indrep_n_tree_balloc_goodSize: forall F1 F2 bxp freelist ms indlvl Fs ir l m1 m2,\n    (F1 * BALLOCC.rep bxp freelist ms)%pred m1 ->\n     (F2 * indrep_n_tree indlvl bxp Fs ir l)%pred m2 ->\n      goodSize addrlen ir.\n  Proof.\n    intros.\n    destruct (addr_eq_dec ir 0); subst.\n    apply DiskLogHash.PaddedLog.goodSize_0.\n    rewrite indrep_n_tree_valid in * by auto.\n    destruct_lifts.\n    eapply BALLOCC.bn_valid_goodSize; eauto.\n  Qed.\n\n  Lemma indrep_n_tree_length: forall indlvl F ir l1 l2 lfs bxp Fs m,\n    length lfs = NIndirect ->\n    (F *\n    indrep_n_helper Fs bxp ir l1 *\n    listmatch\n     (fun x l' => indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine l1 lfs) l2)%pred m->\n     length (concat l2) = NIndirect * (NIndirect ^ (S indlvl)).\n  Proof.\n    intros.\n    rewrite indrep_n_helper_length_piff in H0.\n    rewrite listmatch_length_pimpl in H0.\n    erewrite listmatch_lift_r in H0.\n    destruct_lift H0.\n    rewrite combine_length_eq in * by congruence.\n    erewrite concat_hom_length; eauto.\n    f_equal; omega.\n\n    intros.\n    destruct_lift H0.\n    instantiate (1 := fun x y => indrep_n_tree indlvl bxp (snd x) (# (fst x)) y).\n    rewrite indrep_n_length_pimpl. split; cancel.\n  Qed.\n\n  Lemma indrep_n_indlist_forall_length : forall F indlvl Fs bxp ir l1 fsl l2 m,\n    length fsl = NIndirect ->\n    ((F \u2736 indrep_n_helper Fs bxp ir l1)\n        \u2736 listmatch\n            (fun x l' => indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine l1 fsl) l2)%pred m ->\n    Forall (fun sublist : list waddr => length sublist = NIndirect * NIndirect ^ indlvl) l2.\n  Proof.\n    intros.\n    rewrite indrep_n_helper_length_piff, listmatch_lift_r in H0.\n    destruct_lifts; eauto.\n    intros x; intros.\n    rewrite indrep_n_length_pimpl.\n    split; cancel.\n  Qed.\n\n  Lemma indrep_n_indlist_forall_length' : forall F F' indlvl Fs bxp ir fsl l1 l2 m,\n    length fsl = NIndirect ->\n    (((F \u2736 indrep_n_helper Fs bxp ir l1)\n        \u2736 listmatch\n            (fun x l' => indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine l1 fsl) l2) * F')%pred m ->\n    Forall (fun sublist : list waddr => length sublist = NIndirect * NIndirect ^ indlvl) l2.\n  Proof.\n    intros. eapply indrep_n_indlist_forall_length.\n    2: eassign m; pred_apply; cancel.\n    auto.\n  Qed.\n\n  Lemma indrep_index_bound_helper : forall Fm Fs off indlvl bxp bn iblocks fsl l_part m,\n      off < length (concat l_part) ->\n      length fsl = NIndirect ->\n      ((Fm * indrep_n_helper Fs bxp bn iblocks) *\n       listmatch (fun x l' =>\n                    indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine iblocks fsl) l_part)%pred m\n      -> off / (NIndirect * NIndirect ^ indlvl) < NIndirect.\n  Proof.\n    intros.\n    apply Nat.div_lt_upper_bound; mult_nonzero.\n    erewrite indrep_n_tree_length in * by eauto.\n    rewrite mult_comm; simpl in *. auto.\n  Qed.\n\n  Lemma indrep_index_bound_helper' : forall Fm Fm' off indlvl bxp Fs bn iblocks l_part fsl m,\n      off < length (concat l_part) ->\n      length fsl = NIndirect ->\n    ((Fm * indrep_n_helper Fs bxp bn iblocks) *\n          listmatch (fun x (l' : list waddr) =>\n            indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine iblocks fsl) l_part *\n            Fm')%pred m\n    -> off / (NIndirect * NIndirect ^ indlvl) < NIndirect.\n  Proof.\n    intros.\n    eapply indrep_index_bound_helper; eauto.\n    eassign m.\n    pred_apply; cancel.\n  Qed.\n\n  Local Hint Resolve indrep_n_indlist_forall_length indrep_n_indlist_forall_length'.\n\n  Lemma indrep_n_roundup_helper_1 : forall a b n, n <> 0 ->\n    n - a mod n < b -> roundup a n - a <= b.\n  Proof.\n    intros.\n    destruct (addr_eq_dec (a mod n) 0).\n    unfold roundup. rewrite divup_eq_div by auto. rewrite mul_div by mult_nonzero. omega.\n    rewrite roundup_eq by mult_nonzero. rewrite minus_plus. omega.\n  Qed.\n  Local Hint Resolve indrep_n_roundup_helper_1.\n\n  Theorem roundup_round : forall a n, roundup a n / n * n = roundup a n.\n  Proof.\n    intros.\n    destruct (Nat.eq_dec n 0). subst. unfold roundup. auto.\n    unfold roundup. rewrite Nat.div_mul by auto. auto.\n  Qed.\n\n  Theorem indclear_upd_range_helper_1 : forall T l l' l'' start (v : T) n k d,\n    k <> 0 -> n <> 0 ->\n    start mod (n * k) <> 0 ->\n    start <= length (concat l) ->\n    length l'' = n * k ->\n    concat l' = upd_range l'' (start mod (n * k)) (roundup (start mod (n * k)) k - start mod (n * k)) v ->\n    selN l (start / (n * k)) d = l'' ->\n    Forall (fun x => length x = k) l' ->\n    Forall (fun x => length x = n * k) l ->\n    concat (updN l (start / (n * k)) (\n      concat (upd_range l' (divup (start mod (n * k)) k) (n - divup (start mod (n * k)) k)\n                (repeat v k)\n    ))) = upd_range (concat l) start (n * k - start mod (n * k)) v.\n  Proof.\n    intros.\n    erewrite concat_hom_length in * by eauto.\n    erewrite upd_range_concat_hom_small.\n    rewrite concat_hom_upd_range by eauto.\n    substl (concat l'). f_equal. f_equal.\n    substl l''.\n    erewrite eq_trans with (x := divup _ _ * _); [> | reflexivity|].\n    rewrite upd_range_upd_range by eauto. f_equal.\n    rewrite Nat.mul_sub_distr_r.\n    rewrite <- Nat.add_sub_swap. rewrite le_plus_minus_r. auto.\n    apply roundup_le. auto.\n    all : eauto; autorewrite with core.\n    all : ((apply roundup_le; auto) ||\n           (apply roundup_ge; mult_nonzero) ||\n           solve [mult_nonzero] ||\n           unfold roundup; auto with *).\n    - rewrite le_plus_minus_r. auto.\n      apply roundup_ge; omega.\n    - erewrite concat_hom_length by eauto.\n      rewrite Nat.add_sub_assoc by auto. rewrite plus_comm.\n      rewrite <- Nat.add_sub_assoc by (apply Nat.mod_le; mult_nonzero).\n      rewrite sub_mod_eq_round by mult_nonzero.\n      rewrite <- mult_1_l with (n := _ * _) at 1. rewrite <- Nat.mul_add_distr_r.\n      apply mult_le_compat_r. simpl.\n      apply Nat.div_lt_upper_bound; mult_nonzero.\n      rewrite mult_comm. edestruct le_lt_eq_dec; eauto.\n      subst. rewrite Nat.mod_mul in * by mult_nonzero. intuition.\n    - rewrite le_plus_minus_r; auto.\n    - apply Nat.lt_add_lt_sub_r. apply Nat.mod_upper_bound. auto.\n  Qed.\n\n  Theorem indrep_bound_helper_1 : forall a b n N,\n    N <> 0 ->\n    b <> 0 ->\n    a + b <= n * N ->\n    N - a mod N < b ->\n    (a + (N - a mod N)) / N + (b - (N - a mod N)) / N <= n.\n  Proof.\n    intros.\n    rewrite Nat.add_sub_assoc by auto.\n    rewrite plus_comm with (n := a).\n    rewrite <- Nat.add_sub_assoc by (apply Nat.mod_le; auto).\n    rewrite sub_mod_eq_round by auto.\n    rewrite <- mult_1_l with (n := N) at 1.\n    repeat rewrite <- Nat.mul_add_distr_r.\n    rewrite Nat.div_mul by auto.\n    simpl. apply lt_le_S. eapply le_lt_trans.\n    apply div_add_distr_le.\n    eapply le_lt_trans. apply Nat.div_le_mono. auto.\n    instantiate (1 := a + b - 1).\n    assert (a mod N < N) by (apply Nat.mod_upper_bound; auto).\n    omega.\n    apply Nat.div_lt_upper_bound; auto.\n    rewrite mult_comm. omega.\n  Qed.\n\n\n\n  Theorem xform_indrep_n_helper : forall Fs bxp ir l,\n    crash_xform (indrep_n_helper Fs bxp ir l) <=p=> indrep_n_helper Fs bxp ir l.\n  Proof.\n    unfold indrep_n_helper. intros.\n    destruct addr_eq_dec; xform_norm.\n    - auto.\n    - rewrite IndRec.xform_rep. auto.\n  Qed.\n\n  Theorem xform_indrep_n_tree : forall xp indlvl Fs ir l,\n    crash_xform (indrep_n_tree indlvl xp Fs ir l) <=p=> indrep_n_tree indlvl xp Fs ir l.\n  Proof.\n    induction indlvl; intros; simpl.\n    + rewrite xform_indrep_n_helper. auto.\n    + split; xform_norm.\n      - rewrite xform_indrep_n_helper.\n        rewrite xform_listmatch.\n        rewrite listmatch_piff_replace. cancel.\n        intros; simpl. eauto.\n      - cancel. xform_normr.\n        rewrite xform_indrep_n_helper. cancel.\n        xform_normr.\n        rewrite xform_listmatch.\n        rewrite listmatch_piff_replace. cancel.\n        intros. simpl. rewrite IHindlvl.\n        all: auto.\n  Qed.\n\n  Hint Rewrite Nat.mul_1_r.\n\n  Ltac indrep_n_tree_bound_step := match goal with\n    | [ |- _ ] => reflexivity\n    | [ |- _ ] => assumption\n    | [ |- Forall _ _ ] => auto\n    | [ H : context [IndRec.Defs.item] |- _ ] => unfold IndRec.Defs.item in *; simpl Rec.data in *\n    | [ |- context [IndRec.Defs.item] ] => unfold IndRec.Defs.item in *; simpl Rec.data in *\n    | [ |- context [length (combine ?a ?b)] ] => rewrite combine_length_eq by congruence\n    | [ |- _ ] => progress autorewrite with core lists\n    | [ |- ?a * ?b = ?c * ?b ] => rewrite Nat.mul_cancel_r by mult_nonzero\n    | [ |- ?a * ?b = ?b * ?c ] => rewrite mult_comm with (n := b) (m := c)\n    | [ |- ?b * ?a = ?b * ?c ] => rewrite mult_comm with (n := b) (m := a)\n    | [ H : ?a < ?b * ?c |- ?a < ?d * ?c] => replace d with b; [ eauto | ]\n    | [ H : ?a < ?x |- ?a < ?y ] => replace y with x; [ auto | ]\n    | [ H : ?a <= ?x |- ?a <= ?y ] => replace y with x; [ auto | ]\n    | [ H : context [indrep_n_tree _ _ _ _ ?l] |- context [length ?l] ] =>\n      rewrite indrep_n_tree_length in H; destruct_lift H\n    | [ H : context [indrep_n_helper _ _ _ ?l] |- context [length ?l] ] =>\n      replace (length l) with NIndirect by (erewrite indrep_n_helper_length; auto; pred_apply' H; cancel)\n    | [ |- ?off / ?N < ?N' ] => apply Nat.div_lt_upper_bound; [ mult_nonzero |]\n    | [ |- ?off < ?N * NIndirect] => rewrite mult_comm\n    | [ |- context [Nat.min ?a ?b] ] => rewrite Nat.min_r by auto\n    | [ |- context [Nat.min ?a ?b] ] => rewrite Nat.min_l by auto\n    | [ H : ?a + ?b <= ?c |- ?a < ?d ] => eapply lt_le_trans with (m := a + b); [omega |]\n    (* try to get an argument to indrep_n_tree or indrep_n_helper *)\n    | [ H : context [listmatch ?P (combine ?A ?B) ?C] |- context [length ?C] ] =>\n      replace (length C) with (length A) in * by (\n        erewrite listmatch_combine_l_length_l with (a := A) (b := B) (c := C) (prd := P); auto;\n        pred_apply' H; cancel)\n    | [ H : context [listmatch ?P (combine ?A ?B) ?c] |- context [length ?C] ] =>\n      replace (length c) with (length B) in * by (\n        erewrite listmatch_combine_l_length_r with (a := A) (b := B) (c := C) (prd := P); auto;\n        pred_apply' H; cancel)\n    | [ H : context [listmatch _ (combine ?A ?B) _] |- context [length ?B] ] =>\n      replace (length B) with (length A) by auto\n\n    | [ H : context [listmatch _ ?A ?b] |- context [length ?b] ] =>\n      replace (length b) with (length A) in * by (\n        erewrite listmatch_length with (a := A); auto; pred_apply' H; cancel)\n    | [ H : context [listmatch _ ?A ?b], H': context [length ?b] |- _ ] =>\n      replace (length b) with (length A) in * by (\n        erewrite listmatch_length with (a := A); auto; pred_apply' H; cancel)\n\n    | [ H : context [lift_empty _] |- _ ] => progress destruct_lift H\n    | [ |- context [length (concat _)] ] => erewrite concat_hom_length; eauto\n    | [ |- context [Nat.min _ _] ] => rewrite min_l by omega\n    | [ H: context [Nat.min _ _] |- _ ] => rewrite min_l in H by omega\n    | [ |- _ ] => omega\n    | [ |- ?a < ?b * ?c ] => rewrite mult_comm; omega\n    | [ H : context [length (concat ?l)] |- _ ] => erewrite concat_hom_length in H by eauto\n    end.\n\n  Ltac indrep_n_tree_bound :=\n    match goal with\n    | [l : list _ |- context [?x] ] => is_evar x; unify x l; solve [indrep_n_tree_bound]\n    | _ => repeat indrep_n_tree_bound_step\n  end.\n\n  Ltac indrep_n_extract := match goal with\n    | [|- context [listmatch _ ?l] ] =>\n      match goal with [l : list _ |- context [listmatch _ (removeN ?l ?n)] ] =>\n        rewrite listmatch_isolate with (i := n) (a := l);\n        autorewrite with lists in *; try omega; try erewrite snd_pair by eauto\n      end\n    | [|- context [selN ?l ?n] ] => rewrite listmatch_isolate with (i := n) (a := l);\n        autorewrite with lists in *; try omega; try erewrite snd_pair by eauto\n    | [|- context [selN ?l ?n] ] => rewrite listmatch_isolate with (i := n) (a := combine l _);\n        autorewrite with lists in *; try rewrite selN_combine; try omega; try erewrite snd_pair by eauto;\n        cbn [fst snd] in *\n    | [H: context [listmatch _ (combine ?l _)] |- context [selN ?l ?n] ] =>\n        rewrite listmatch_isolate with (i := n) (a := combine l _) in H;\n        autorewrite with lists in *; erewrite ?selN_combine in H; try omega; erewrite ?snd_pair by eauto;\n        cbn [fst snd] in *\n    | [H: context [listmatch _ _ ?l] |- context [selN ?l ?n] ] =>\n        rewrite listmatch_isolate with (i := n) (b := l) in H;\n        autorewrite with lists in *; erewrite ?selN_combine in H; try omega; erewrite ?snd_pair by eauto;\n        cbn [fst snd] in *\n  end.\n\n  Ltac indrep_n_tree_extract_lengths :=\n    repeat match goal with [H : context [indrep_n_tree _ _ _ _ ?x] |- _] =>\n      match goal with\n      | [H' : length ?y = _ |- _] => tryif (unify x y) then fail 1 else fail\n      | [|- _] => rewrite indrep_n_length_pimpl with (l := x) in H; destruct_lift H\n      end\n    end; try rewrite mult_1_r in *.\n\n  Theorem indrep_n_tree_repeat_concat:\n    forall indlvl F Fs lfs l1 l2 bxp m,\n    length lfs = NIndirect ->\n    ((F \u2736 indrep_n_helper Fs bxp 0 l1)\n     \u2736 listmatch (fun x y => indrep_n_tree indlvl bxp (snd x) # (fst x) y) (combine l1 lfs) l2)%pred m ->\n    concat l2 = repeat $0 (NIndirect * NIndirect ^ S indlvl).\n  Proof.\n    intros. rewrite indrep_n_helper_0 in *. destruct_lifts.\n    rewrite listmatch_length_pimpl in *; autorewrite with lists in *; destruct_lifts.\n    rewrite min_l in * by omega.\n    erewrite concat_hom_repeat. repeat f_equal; auto.\n    rewrite listmatch_lift_r in *. destruct_lifts; eauto.\n    intros. instantiate (1 := fun x y => ([[ snd x <=p=> emp ]])%pred).\n    erewrite in_combine_repeat_l by eauto.\n    rewrite indrep_n_tree_0. split; cancel.\n  Qed.\n\n  Theorem indrep_n_tree_repeat_Fs:\n    forall indlvl F Fs lfs l1 l2 bxp m,\n    length lfs = NIndirect ->\n    ((F \u2736 indrep_n_helper Fs bxp 0 l1)\n     \u2736 listmatch (fun x y => indrep_n_tree indlvl bxp (snd x) # (fst x) y) (combine l1 lfs) l2)%pred m ->\n    Fs * pred_fold_left lfs <=p=> emp.\n  Proof.\n    intros. rewrite indrep_n_helper_0 in *. destruct_lifts.\n    rewrite listmatch_lift_l in *.\n    destruct_lifts.\n    rewrite Forall_combine_r in *.\n    rewrite pred_fold_left_Forall_emp; eauto.\n    psubst; split; cancel.\n    autorewrite with lists; auto.\n    intros.\n    instantiate (1 := fun x => (snd x) <=p=> emp).\n    reflexivity.\n    intros.\n    erewrite in_combine_repeat_l by eauto.\n    rewrite roundTrip_0.\n    rewrite indrep_n_tree_0 at 1.\n    instantiate (1 := fun x y => ([[ y = _ ]])%pred).\n    split; cancel.\n  Qed.\n\n\n  Local Hint Extern 1 (BALLOCC.bn_valid _ _) => match goal with\n    [H : context [indrep_n_helper _ _ ?ir] |- BALLOCC.bn_valid _ ?ir] =>\n    rewrite indrep_n_helper_valid in H by omega; destruct_lift H; auto end.\n\n  Local Hint Extern 1 (goodSize _ _) => match goal with\n  | [H: context [indrep_n_tree _ _ _ ?i] |- goodSize _ ?i ] =>\n    match goal with H' : context [BALLOCC.rep ?B ?l] |- _ =>\n      eapply indrep_n_tree_balloc_goodSize with (bxp := B) (freelist := l); eapply pimpl_apply;\n      [| exact H' | | exact H]; cancel\n    end\n  end.\n\n  Hint Rewrite le_plus_minus_r using auto.\n  Local Hint Extern 1 (?a mod ?b < ?b) => apply Nat.mod_bound_pos; mult_nonzero.\n  Local Hint Extern 1 (0 < ?n - ?m) => (apply Nat.lt_add_lt_sub_r; simpl; auto).\n\n  Local Hint Resolve repeat_selN'.\n  Local Hint Extern 1 (Forall (fun x => length x = _) _) => eapply indrep_n_indlist_forall_length.\n\n  Lemma IndRec_items_valid_repeat : forall bn x,\n    bn <> 0 -> IndRec.items_valid bn (repeat x NIndirect).\n  Proof.\n    unfold IndRec.items_valid, IndSig.RAStart, IndSig.RALen, IndSig.xparams_ok.\n    simpl. intros. autorewrite with lists. auto.\n  Qed.\n\n  Local Hint Resolve IndRec_items_valid_repeat IndRec.items_valid_updN IndRec.items_valid_upd_range.\n  Local Hint Extern 1 (Rec.well_formed _) => unfold Rec.well_formed; cbn.\n\n  Lemma indrep_n_helper_items_valid : forall Fs bxp bn l,\n    bn <> 0 ->\n    indrep_n_helper Fs bxp bn l <=p=> [[ IndRec.items_valid bn l]] * indrep_n_helper Fs bxp bn l.\n  Proof.\n    intros.\n    rewrite indrep_n_helper_length_piff.\n    unfold IndRec.items_valid, IndSig.xparams_ok, IndSig.RALen, IndSig.RAStart, IndRec.Defs.item.\n    split; cancel.\n  Qed.\n\n  Local Hint Extern 1 (IndRec.items_valid _ _) => match goal with\n    [H : context [indrep_n_helper _ _ ?bn] |- IndRec.items_valid ?bn _] =>\n    rewrite indrep_n_helper_items_valid in H; destruct_lift H end.\n\n\n  (************* n-indirect program *)\n\n  Fixpoint indget (indlvl : nat) lxp (bn : addr) off ms :=\n    If (addr_eq_dec bn 0) {\n      Ret ^(ms, $ 0)\n    } else {\n      let divisor := NIndirect ^ indlvl in\n      let^ (ms, v) <- IndRec.get lxp bn (off / divisor) ms;\n      match indlvl with\n      | 0 => Ret ^(ms, v)\n      | S indlvl' => indget indlvl' lxp (# v) (off mod divisor) ms\n      end\n    }.\n\n  Theorem indget_ok : forall indlvl lxp bxp bn off ms,\n    {< F Fm Fs m0 sm m l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * indrep_n_tree indlvl Fs bxp bn l ]]] *\n           [[ off < length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = selN l off $0 ]]\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} indget indlvl lxp bn off ms.\n  Proof.\n    induction indlvl; simpl.\n    + repeat safestep; autorewrite with core; eauto.\n      rewrite indrep_n_helper_0 in *. destruct_lifts. auto.\n      rewrite indrep_n_helper_valid by omega. cancel.\n    + repeat safestep; autorewrite with core; try eassumption; clear IHindlvl.\n    3: rewrite indrep_n_helper_valid by auto; cancel.\n      - erewrite indrep_n_tree_repeat_concat with (m := list2nmem m).\n        3: pred_apply; cancel.\n        auto.\n        indrep_n_tree_bound.\n      - indrep_n_tree_bound.\n      - rewrite listmatch_isolate with (i := off / (NIndirect ^ S indlvl)) by indrep_n_tree_bound.\n        rewrite selN_combine by indrep_n_tree_bound.\n        cbn [fst snd]; cancel.\n      - match goal with [H : context [indrep_n_helper] |-_] => assert (HH := H) end.\n        match goal with |- ?a mod ?n < ?b => replace b with n; auto end.\n        rewrite listmatch_extract in HH; autorewrite with lists in HH.\n        rewrite indrep_n_length_pimpl in HH.\n        destruct_lift HH. eauto.\n        indrep_n_tree_bound.\n      - apply selN_selN_hom; eauto.\n        indrep_n_tree_bound.\n      Unshelve.\n      all: eauto.\n           exact ($0, emp).\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indget _ _ _ _ _ ) _) => apply indget_ok : prog.\n  Opaque indget.\n\n  Fixpoint indread (indlvl : nat) lxp (ir : addr) ms :=\n    If (addr_eq_dec ir 0) {\n      Ret ^(ms, repeat $0 (NIndirect ^ S indlvl))\n    } else {\n      let^ (ms, indbns) <- IndRec.read lxp ir 1 ms;\n      match indlvl with\n        | 0 => Ret ^(ms, indbns)\n        | S indlvl' =>\n          let N := (NIndirect ^ (S indlvl')) in\n          r <- ForEach b indbns' (rev indbns)\n            Hashmap hm\n            Ghost [ F Fm Fs fsl iblocks l_part l bxp crash m0 sm m ]\n            Loopvar [ ms r ]\n            Invariant\n              exists remlen, [[ remlen = length indbns' ]] *\n              LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n              [[[ m ::: Fm * indrep_n_helper Fs bxp ir iblocks *\n                        listmatch (fun x l' => indrep_n_tree indlvl' bxp (snd x) (# (fst x)) l')\n                          (combine iblocks fsl) l_part ]]] *\n              [[ r = skipn (remlen * (NIndirect ^ indlvl)) l ]]\n            OnCrash crash\n            Begin\n              let^ (ms, v) <- indread indlvl' lxp (# b) ms;\n              Ret ^(ms, v ++ r)\n            Rof ^(ms, nil);\n            Ret r\n      end\n    }.\n\n  Theorem indread_ok : forall indlvl lxp bxp ir ms,\n  {< F Fm Fs m0 sm m l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * indrep_n_tree indlvl Fs bxp ir l ]]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = l ]]\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} indread indlvl lxp ir ms.\n  Proof.\n    induction indlvl; simpl.\n    + hoare.\n      - rewrite indrep_n_helper_0 in *. destruct_lifts. rewrite mult_1_r. auto.\n      - rewrite indrep_n_helper_valid by auto; cancel.\n      - rewrite indrep_n_helper_length_piff in *.\n        destruct_lifts. unfold IndRec.Defs.item in *; simpl in *.\n        rewrite firstn_oob by omega. auto.\n    + hoare.\n      - erewrite indrep_n_tree_repeat_concat; eauto. auto.\n        indrep_n_tree_bound.\n      - rewrite indrep_n_helper_valid by omega. cancel.\n      - rewrite firstn_oob by indrep_n_tree_bound.\n        autorewrite with list.\n        rewrite skipn_oob; auto.\n        indrep_n_tree_bound.\n      - rewrite firstn_oob in * by indrep_n_tree_bound; subst.\n        rewrite rev_eq_iff, rev_app_distr in *; cbn [rev] in *; subst.\n        rewrite listmatch_extract.\n        rewrite selN_combine.\n        rewrite selN_app1.\n        rewrite selN_app2.\n        rewrite sub_le_eq_0 by reflexivity; cbn [selN].\n        cancel.\n        all: rewrite indrep_n_helper_length_piff in *; destruct_lifts.\n        all : autorewrite with list in *; cbn -[Nat.div] in *; try omega.\n        rewrite combine_length_eq; autorewrite with list; cbn; omega.\n      - rewrite firstn_oob in * by indrep_n_tree_bound; subst.\n        rewrite rev_eq_iff, rev_app_distr in *; cbn [rev] in *; subst.\n        rewrite listmatch_length_pimpl in *; destruct_lifts.\n        rewrite indrep_n_helper_length_piff in *; destruct_lifts.\n        autorewrite with list in *; cbn [length] in *.\n        rewrite <- (Nat.mul_1_l (NIndirect * NIndirect ^ indlvl)) at 1.\n        rewrite <- Nat.mul_add_distr_r.\n        repeat erewrite concat_hom_skipn by eauto.\n        erewrite skipn_selN_skipn with (off := length _).\n        reflexivity.\n        match goal with H: length (combine _ _) = _ |- _ => rename H into Hc end.\n        rewrite combine_length_eq in Hc.\n        autorewrite with list in *; cbn [length] in *; omega.\n        autorewrite with list; cbn [length]. omega.\n      - apply LOG.rep_hashmap_subset; eauto.\n    Grab Existential Variables.\n      all : eauto; split.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread _ _ _ _ ) _) => apply indread_ok : prog.\n  Opaque indread.\n\n  Definition indread_aligned indlvl lxp (indbns : list waddr) ms :=\n    ForEach bn rest (rev indbns)\n      Hashmap hm\n      Ghost [ F Fm l_part fsl bxp crash m0 sm m ]\n      Loopvar [ ms r ]\n      Invariant\n        LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n        [[ length indbns = length fsl ]] *\n        [[ r = concat (skipn (length rest) l_part) ]] *\n        [[[ m ::: Fm * listmatch (fun x l' => indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine (rev indbns) (rev fsl)) (rev l_part) ]]]\n      OnCrash crash\n      Begin\n        let^ (ms, blks) <- indread indlvl lxp # bn ms;\n        Ret ^(ms, blks ++ r)\n      Rof ^(ms, nil).\n\n  Hint Rewrite rev_length rev_involutive rev_app_distr : lists.\n\n  Theorem indread_aligned_ok : forall indlvl lxp indbns ms,\n    {< F Fm m0 sm m bxp fsl l_part,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) # (fst x) l) (combine indbns fsl) l_part) ]]] *\n           [[ length fsl = length indbns ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = concat l_part ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_aligned indlvl lxp indbns ms.\n  Proof.\n    unfold indread_aligned.\n    step.\n    eassign l_part.\n    autorewrite with lists core.\n    rewrite skipn_oob; auto.\n    indrep_n_tree_bound.\n    rewrite <- combine_rev by auto.\n    rewrite listmatch_rev. cancel.\n    assert (length l_part = length fsl) by indrep_n_tree_bound.\n    prestep. norml.\n    denote app as Hr.\n    apply f_equal with (f := @rev _) in Hr.\n    autorewrite with lists in Hr; cbn [rev] in Hr; subst.\n    autorewrite with lists in *.\n    cbn [length] in *.\n    denote listmatch as Hl.\n    erewrite list_isolate with (l := fsl) (d := emp) in Hl, H by eauto.\n    erewrite list_isolate with (l := l_part) (d := nil) in Hl, H by (substl (length l_part); eauto).\n    autorewrite with lists in Hl, H.\n    cbn [rev app] in Hl, H.\n    repeat rewrite app_assoc_reverse in Hl, H.\n    rewrite combine_app in Hl, H.\n    cbn [app combine] in Hl, H.\n    rewrite listmatch_app_rev, listmatch_cons in Hl.\n    cancel.\n    step.\n    indrep_n_tree_bound.\n    autorewrite with lists core.\n    rewrite skipn_app_r_ge by indrep_n_tree_bound.\n    erewrite skipn_selN_skipn by indrep_n_tree_bound.\n    cbn.\n    autorewrite with core lists.\n    rewrite min_l by omega.\n    autorewrite with core.\n    rewrite firstn_rev by auto.\n    autorewrite with lists core.\n    replace (length l_part - length prefix) with (S (length lst')) by omega.\n    auto.\n    rewrite <- listmatch_app, listmatch_cons.\n    cancel.\n    cancel.\n    auto using LOG.active_intact.\n    left.\n    autorewrite with core lists.\n    rewrite Min.min_assoc, Nat.min_id.\n    congruence.\n    indrep_n_tree_bound.\n    indrep_n_tree_bound.\n    step.\n    eauto using LOG.intact_hashmap_subset.\n  Unshelve.\n    all: constructor.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread_aligned _ _ _ _ ) _) => apply indread_aligned_ok : prog.\n\n  Fixpoint indread_to_aligned indlvl lxp ir start ms :=\n    let N := (NIndirect ^ S indlvl) in\n    If (addr_eq_dec ir 0) {\n      Ret ^(ms, repeat $0 (N - start))\n    } else {\n      let^ (ms, indbns) <- IndRec.read lxp ir 1 ms;\n      match indlvl with\n      | 0 =>\n        Ret ^(ms, skipn start indbns)\n      | S indlvl' =>\n        let N := (NIndirect ^ S indlvl') in\n        let^ (ms, r) <- indread_aligned indlvl' lxp (skipn (S (start / N)) indbns) ms;\n        let ir' := selN indbns (start / N) $0 in\n        let^ (ms, r') <- indread_to_aligned indlvl' lxp # ir' (start mod N) ms;\n        Ret ^(ms, r' ++ r)\n      end\n    }.\n\n  Theorem indread_to_aligned_ok : forall indlvl lxp ir start ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm IFs m0 sm m bxp l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * indrep_n_tree indlvl bxp IFs ir l ]]] *\n           [[ start < length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = skipn start l ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_to_aligned indlvl lxp ir start ms.\n  Proof.\n    induction indlvl; cbn [indread_to_aligned].\n    - hoare.\n      rewrite indrep_n_helper_0 in *; destruct_lifts.\n      autorewrite with core.\n      rewrite skipn_repeat; auto.\n      rewrite indrep_n_helper_valid by auto.\n      cancel.\n      rewrite firstn_oob by indrep_n_tree_bound.\n      auto.\n    - step.\n      step.\n      erewrite indrep_n_tree_repeat_concat with (m := list2nmem m).\n      3: pred_apply; cancel.\n      rewrite skipn_repeat; eauto.\n      indrep_n_tree_bound.\n      step.\n      rewrite indrep_n_helper_valid by auto. cancel.\n      rewrite firstn_oob by indrep_n_tree_bound.\n      step.\n      match goal with |- context [skipn ?k] =>\n        rewrite listmatch_split with (n := S k)\n      end.\n      rewrite skipn_combine by auto.\n      cancel.\n      repeat match goal with |- context [match ?x with _ => _ end] => destruct x end;\n        cbn [length] in *; autorewrite with core; congruence.\n      step.\n      indrep_n_extract. cancel.\n      indrep_n_tree_bound.\n      indrep_n_tree_bound.\n      eapply lt_le_trans; [eapply Nat.mod_upper_bound|]; auto.\n      indrep_n_extract.\n      erewrite indrep_n_length_pimpl in *.\n      destruct_lifts.\n      match goal with H: context [selN] |- _ => rewrite H; omega end.\n      indrep_n_tree_bound.\n      indrep_n_tree_bound.\n      step.\n      erewrite <- skipn_hom_concat by eauto.\n      auto.\n  Unshelve.\n    all: solve [eauto | exact $0].\n  Qed.\n\n  Opaque indread_to_aligned.\n  Local Hint Extern 1 ({{_}} Bind (indread_to_aligned _ _ _ _ _ ) _) => apply indread_to_aligned_ok : prog.\n\n  Fixpoint indread_from_aligned indlvl lxp ir len ms :=\n    let N := (NIndirect ^ S indlvl) in\n    If (addr_eq_dec ir 0) {\n      Ret ^(ms, repeat $0 len)\n    } else {\n      let^ (ms, indbns) <- IndRec.read lxp ir 1 ms;\n      match indlvl with\n      | 0 =>\n        Ret ^(ms, firstn len indbns)\n      | S indlvl' =>\n        let N := (NIndirect ^ S indlvl') in\n        let^ (ms, r) <- indread_aligned indlvl' lxp (firstn (len / N) indbns) ms;\n        If (addr_eq_dec (len mod N) 0) {\n          Ret ^(ms, r)\n        } else {\n          let ir' := selN indbns (len / N) $0 in\n          let^ (ms, r') <- indread_from_aligned indlvl' lxp # ir' (len mod N) ms;\n          Ret ^(ms, r ++ r')\n        }\n      end\n    }.\n\n\n  Theorem indread_from_aligned_ok : forall indlvl lxp ir len ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm IFs m0 sm m bxp l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * indrep_n_tree indlvl bxp IFs ir l ]]] *\n           [[ len <= length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = firstn len l ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_from_aligned indlvl lxp ir len ms.\n  Proof.\n    induction indlvl; cbn [indread_from_aligned].\n    + hoare.\n      rewrite indrep_n_helper_0 in *; destruct_lifts.\n      autorewrite with core.\n      rewrite firstn_repeat; auto.\n      rewrite repeat_length in *; omega.\n      rewrite indrep_n_helper_valid by auto.\n      cancel.\n      f_equal.\n      rewrite firstn_oob by indrep_n_tree_bound.\n      auto.\n    + step.\n      step.\n      erewrite indrep_n_tree_repeat_concat with (m := list2nmem m).\n      3: pred_apply; cancel.\n      rewrite firstn_repeat; eauto.\n      indrep_n_tree_bound.\n      indrep_n_tree_bound.\n      step.\n      rewrite indrep_n_helper_valid by auto. cancel.\n      rewrite firstn_oob by indrep_n_tree_bound.\n      step.\n      match goal with |- context [firstn ?k] =>\n        rewrite listmatch_split with (n := k)\n      end.\n      rewrite firstn_combine_comm.\n      cancel.\n      indrep_n_tree_bound.\n      step.\n      step.\n      erewrite <- concat_hom_firstn by eauto.\n      rewrite mul_div by mult_nonzero. auto.\n      denote listmatch as Hl; pose proof Hl.\n      prestep. norml.\n      indrep_n_extract.\n      erewrite indrep_n_length_pimpl in *.\n      destruct_lifts.\n      match goal with H: context [selN] |- _ => rename H into Hr end.\n      cancel; hoare.\n      - rewrite Hr; auto using mod_le_r.\n      - erewrite <- firstn_hom_concat by eauto.\n        auto.\n      - indrep_n_tree_bound.\n        denote le as He.\n        destruct (le_lt_eq_dec _ _ He); subst.\n        indrep_n_tree_bound.\n        rewrite Nat.mod_mul in * by auto.\n        congruence.\n      - indrep_n_tree_bound.\n        denote le as He.\n        destruct (le_lt_eq_dec _ _ He); subst.\n        indrep_n_tree_bound.\n        rewrite Nat.mod_mul in * by auto.\n        congruence.\n  Unshelve.\n    all: solve [eauto | exact $0].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread_from_aligned _ _ _ _ _ ) _) => apply indread_from_aligned_ok : prog.\n\n  Definition indread_multiple_blocks indlvl lxp (indbns : list waddr) start len ms :=\n    let N := NIndirect ^ S indlvl in\n    (* reads up to N blocks if start mod N = 0 *)\n    let^ (ms, rl) <- indread_to_aligned indlvl lxp #(selN indbns (start / N) $0) (start mod N) ms;\n    let start' := start + (N - start mod N) in\n    let len' := len - (N - start mod N) in\n    let^ (ms, rm) <- indread_aligned indlvl lxp (firstn (len' / N) (skipn (start' / N) indbns)) ms;\n    let len'' := len' mod N in\n    let start'' := start' + (len' / N * N) in\n    let^ (ms, rr) <- indread_from_aligned indlvl lxp #(selN indbns (start'' / N) $0) len'' ms;\n    Ret ^(ms, rl ++ (rm ++ rr)).\n\n  Theorem indread_multiple_blocks_ok : forall indlvl lxp indbns start len ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm m0 sm m bxp l_part fsl,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns fsl) l_part) ]]] *\n           [[ start < length (concat l_part) ]] *\n           [[ (N - start mod N) < len ]] *\n           [[ start + len < length (concat l_part) ]] *\n           [[ length indbns = length fsl ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = firstn len (skipn start (concat l_part)) ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_multiple_blocks indlvl lxp indbns start len ms.\n  Proof.\n    cbv [indread_multiple_blocks].\n    prestep. norml.\n    denote listmatch as Hl. pose proof Hl.\n    assert (length indbns = length l_part) by indrep_n_tree_bound.\n    cancel.\n    indrep_n_extract. cancel.\n    indrep_n_tree_bound.\n    indrep_n_tree_bound.\n    indrep_n_extract.\n    erewrite indrep_n_length_pimpl in *.\n    destruct_lifts.\n    match goal with H: context [selN] |- _ => rewrite H; auto end.\n    indrep_n_tree_bound.\n    indrep_n_tree_bound.\n    step.\n    match goal with |- context [firstn ?m (skipn ?k _)] =>\n      rewrite listmatch_split with (n := k);\n      rewrite listmatch_split with (n := m) (a := skipn _ _)\n    end.\n    rewrite <- firstn_combine_comm.\n    rewrite <- skipn_combine by eauto.\n    cancel.\n    autorewrite with core. congruence.\n    denote (list2nmem m) as Hm. pose proof Hm.\n    indrep_n_extract.\n    rewrite Nat.div_add in * by auto.\n    hoare.\n    - erewrite indrep_n_length_pimpl in *.\n      destruct_lifts.\n      match goal with H: context [selN] |- _ => rewrite H; auto end.\n    - erewrite <- skipn_selN.\n      rewrite <- firstn_hom_concat by eauto using forall_skipn.\n      erewrite skipn_hom_concat by eauto.\n      indrep_n_extract; [ | solve [indrep_n_tree_bound].. ].\n      erewrite indrep_n_length_pimpl in *; destruct_lifts.\n      rewrite firstn_app.\n      rewrite firstn_oob with (n := len).\n      autorewrite with core.\n      match goal with H: context [selN] |- _ => rewrite H end.\n      f_equal.\n      match goal with |- context [?a mod ?b] => destruct (addr_eq_dec 0 (a mod b));\n        try (substl (a mod b)) end.\n      + cbn [skipn firstn].\n        autorewrite with core.\n        repeat f_equal.\n        match goal with |- context [(?a + ?b) / ?b] =>\n          replace ((a + b) / b) with ((a + 1 * b) / b) by (do 2 f_equal; omega)\n        end.\n        rewrite Nat.div_add, plus_comm; auto.\n      + rewrite <- roundup_eq by auto.\n        unfold roundup.\n        rewrite Nat.div_mul by auto.\n        rewrite divup_eq_div_plus_1 by auto.\n        rewrite plus_comm; auto.\n      + autorewrite with core.\n        match goal with H: context [selN] |- _ => rewrite H end.\n        omega.\n    - apply Nat.div_lt_upper_bound; auto.\n      eapply le_lt_trans.\n      apply plus_le_compat_l, div_mul_le.\n      rewrite plus_assoc_reverse.\n      rewrite le_plus_minus_r by omega.\n      indrep_n_tree_bound.\n    - apply Nat.div_lt_upper_bound; auto.\n      eapply le_lt_trans.\n      apply plus_le_compat_l, div_mul_le.\n      rewrite plus_assoc_reverse.\n      rewrite le_plus_minus_r by omega.\n      indrep_n_tree_bound.\n  Unshelve.\n    all: solve [eauto | apply emp | exact $0].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread_multiple_blocks _ _ _ _ _ _ ) _) => apply indread_multiple_blocks_ok : prog.\n\n  Fixpoint indread_range indlvl lxp (root : addr) start len ms :=\n    let N := NIndirect ^ indlvl in\n    If (addr_eq_dec len 0) {\n      Ret ^(ms, nil)\n    } else {\n      (* not necessary, but it makes the proof much easier *)\n      If (addr_eq_dec (start + len) (NIndirect * N)) {\n        indread_to_aligned indlvl lxp root start ms\n      } else {\n        If (addr_eq_dec root 0) {\n          Ret ^(ms, repeat $0 len)\n        } else {\n          let^ (ms, indbns) <- IndRec.read lxp root 1 ms;\n          match indlvl with\n          | 0 =>\n             Ret ^(ms, firstn len (skipn start indbns))\n          | S indlvl' =>\n            If (le_dec len (N - start mod N)) {\n              indread_range indlvl' lxp #(selN indbns (start / N) $0) (start mod N) len ms\n            } else {\n              indread_multiple_blocks indlvl' lxp indbns start len ms\n            }\n          end\n        }\n      }\n    }.\n\n  Theorem indread_range_ok : forall indlvl lxp ir start len ms,\n  {< F Fm Fs m0 sm m bxp l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * indrep_n_tree indlvl Fs bxp ir l ]]] *\n           [[ start + len <= length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = firstn len (skipn start l) ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_range indlvl lxp ir start len ms.\n  Proof.\n    induction indlvl; cbn [indread_range].\n    + hoare.\n      rewrite firstn_oob; indrep_n_tree_bound.\n      rewrite indrep_n_helper_0 in *.\n      destruct_lifts.\n      rewrite skipn_repeat, firstn_repeat; auto.\n      rewrite repeat_length in *; omega.\n      rewrite indrep_n_helper_valid by auto. cancel.\n      repeat f_equal.\n      apply firstn_oob.\n      indrep_n_tree_bound.\n    + step; step.\n      hoare.\n      rewrite firstn_oob; indrep_n_tree_bound.\n      step.\n      step.\n      erewrite indrep_n_tree_repeat_concat with (m := list2nmem m).\n      3: pred_apply; cancel.\n      rewrite skipn_repeat, firstn_repeat; auto.\n      indrep_n_tree_bound.\n      match goal with H: _ + _ <= length ?l * _ |- _ =>\n        replace (length l) with NIndirect in *; indrep_n_tree_bound\n      end.\n      indrep_n_tree_bound.\n      step.\n      rewrite indrep_n_helper_valid by auto. cancel.\n      rewrite firstn_oob by indrep_n_tree_bound.\n      denote listmatch as Hl. pose proof Hl.\n      step.\n      indrep_n_extract.\n      erewrite indrep_n_length_pimpl in *.\n      destruct_lifts.\n      hoare.\n      erewrite skipn_hom_concat by eauto.\n      rewrite firstn_app_l; auto.\n      match goal with H: context [selN] |- _ => rename H into Hr end.\n      autorewrite with core; rewrite Hr.\n      omega.\n      indrep_n_tree_bound.\n      indrep_n_tree_bound.\n      hoare.\n      indrep_n_tree_bound.\n      match goal with H: _ + _ <= length ?l * _ |- _ =>\n        replace (length l) with NIndirect in *; indrep_n_tree_bound\n      end.\n  Unshelve.\n    apply emp.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread_range _ _ _ _ _ _ ) _) => apply indread_range_ok : prog.\n\n  Fixpoint indclear_all indlvl lxp bxp root ms :=\n    If (addr_eq_dec root 0) {\n      Ret ms\n    } else {\n      let N := NIndirect ^ indlvl in\n      ms <- match indlvl with\n      | 0 => Ret ms\n      | S indlvl' =>\n        let^ (lms, indbns) <- IndRec.read lxp root 1 (BALLOCC.MSLog ms);\n        let msn := BALLOCC.upd_memstate lms ms in\n        let^ (msn) <- ForEach bn indbns' indbns\n          Hashmap hm\n          Ghost [ F Fm Fs bxp crash m0 sm freelist l_part fsl ]\n          Loopvar [ msn ]\n          Invariant\n            exists m freelist',\n            LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog msn) sm hm *\n            let n := length indbns - length indbns' in\n            [[[ m ::: Fm * listmatch (fun x l' => indrep_n_tree indlvl' bxp (snd x) (# (fst x)) l')\n                          (combine (skipn n indbns) (skipn n fsl)) (skipn n l_part)\n                         * BALLOCC.rep bxp freelist' msn ]]] *\n            [[ incl freelist freelist' ]] *\n            [[ (Fs * pred_fold_left (skipn n fsl) * BALLOCC.smrep freelist')%pred sm ]]\n          OnCrash crash\n          Begin\n            msn <- indclear_all indlvl' lxp bxp # bn msn;\n            Ret ^(msn)\n          Rof ^(msn);\n          Ret msn\n      end;\n      BALLOCC.free lxp bxp root ms\n    }.\n\n\n  Theorem indclear_all_ok : forall indlvl lxp bxp ir ms,\n    let N := NIndirect ^ indlvl in\n    {< F Fm Fs IFS m0 sm m l freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * indrep_n_tree indlvl bxp IFS ir l *\n              BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFS * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET: ms\n           exists m' freelist' l',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * indrep_n_tree indlvl bxp emp 0 l' *\n              BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ (Fs * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ incl freelist freelist' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear_all indlvl lxp bxp ir ms.\n    Proof.\n      induction indlvl; simpl.\n      + step.\n        hoare.\n        repeat rewrite indrep_n_helper_0. cancel.\n        rewrite indrep_n_helper_0 in *.\n        denote lift_empty as Hf; destruct_lift Hf.\n        psubst; auto.\n        destruct (addr_eq_dec ir 0). step.\n        rewrite indrep_n_helper_pts_piff in * by auto.\n        denote lift_empty as Hf; destruct_lift Hf.\n        psubst. denote exis as Hf; destruct_lift Hf.\n        hoare.\n        rewrite indrep_n_helper_0 by auto.\n        cancel.\n      + step.\n        psubst.\n        step.\n        symmetry. eapply indrep_n_tree_repeat_Fs with (m := list2nmem m).\n        indrep_n_tree_bound.\n        pred_apply; cancel.\n        eapply indrep_n_tree_repeat_Fs with (m := list2nmem m).\n        indrep_n_tree_bound.\n        pred_apply; cancel.\n        step.\n        rewrite indrep_n_helper_valid by auto. cancel.\n        rewrite indrep_n_helper_length_piff in *.\n        denote indrep_n_helper as Hi; destruct_lift Hi.\n        unfold IndRec.Defs.item in *; simpl in *. rewrite firstn_oob by omega.\n        prestep. norm. cancel.\n        rewrite Nat.sub_diag; cbn [skipn].\n        intuition auto.\n        - pred_apply. cancel.\n        - apply incl_refl.\n        - psubst.\n          pred_apply; cancel.\n        - match goal with H: context [listmatch _ _ ?l] |- _ =>\n            assert (length l = NIndirect) by indrep_n_tree_bound end.\n          prestep. norml.\n          assert (length prefix < NIndirect).\n          rewrite indrep_n_helper_length_piff in *; destruct_lifts.\n          autorewrite with lists in *; cbn [length] in *; omega.\n          cancel.\n          autorewrite with lists; cbn [length].\n          repeat rewrite ?Nat.add_sub, ?Nat.sub_diag, ?skipn_app_r_ge by omega.\n          cbn [skipn].\n          erewrite skipn_selN_skipn by omega.\n          cbn [combine].\n          erewrite skipn_selN_skipn with (off := length prefix) by omega.\n          rewrite listmatch_cons.\n          cancel.\n          autorewrite with lists; cbn [length].\n          repeat rewrite Nat.add_sub.\n          erewrite skipn_selN_skipn with (l := dummy1) by omega.\n          rewrite pred_fold_left_cons.\n          cancel.\n          reflexivity.\n          step.\n          autorewrite with lists; cbn [length].\n          rewrite skipn_app_r_ge by omega.\n          repeat match goal with |- context [?b + S ?a - ?a] => replace (b + S a - a) with (S b) by omega end.\n          repeat match goal with |- context [S ?a - ?a] => replace (S a - a) with 1 by omega end.\n          rewrite indrep_n_tree_0. cancel.\n          autorewrite with lists; cbn [length].\n          repeat match goal with |- context [?b + S ?a - ?a] => replace (b + S a - a) with (S b) by omega end.\n          cancel.\n          cancel.\n        - rewrite indrep_n_helper_valid in * by auto.\n          denote lift_empty as Hl; destruct_lift Hl.\n          psubst.\n          denote piff as Hp. rewrite Hp in *.\n          match goal with H: context [(_ |->?)%pred] |- _ => progress destruct_lift H end.\n          prestep. norml.\n          repeat rewrite skipn_oob in * by omega.\n          rewrite Hp in *.\n          cancel.\n          rewrite skipn_oob by indrep_n_tree_bound.\n          rewrite indrep_n_helper_pts_piff by auto.\n          unfold listmatch; cancel.\n          safestep.\n          apply listmatch_indrep_n_tree_empty.\n          autorewrite with lists; auto.\n          rewrite pred_fold_left_repeat_emp.\n          split; cancel.\n          reflexivity.\n          cancel.\n        - cancel.\n          eauto using LOG.intact_hashmap_subset.\n    Grab Existential Variables.\n    all: try exact addr_eq_dec.\n    all : eauto using tt.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indclear_all _ _ _ _ _ ) _) => apply indclear_all_ok : prog.\n\n  Definition indclear_aligned indlvl lxp bxp (indbns : list waddr) start len ms :=\n    let N := NIndirect ^ S indlvl in\n    let indbns := firstn (len / N) (skipn (start / N) indbns) in\n    ForEach bn rest indbns\n      Hashmap hm\n      Ghost [ F Fm Fs l_part fsl bxp crash m0 sm freelist ]\n      Loopvar [ ms ]\n      Invariant\n        exists l_part' indbns' fsl' freelist' m,\n        LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n        let n := length indbns - length rest in\n        [[ l_part' = skipn n l_part ]] *\n        [[ indbns' = skipn n indbns ]] *\n        [[ fsl' = skipn n fsl ]] *\n        [[[ m ::: Fm * listmatch (fun x l' => indrep_n_tree indlvl bxp (snd x) # (fst x) l') (combine indbns' fsl') l_part' *\n                  BALLOCC.rep bxp freelist' ms ]]] *\n        [[ (Fs * pred_fold_left fsl' * BALLOCC.smrep freelist')%pred sm ]] *\n        [[ incl freelist freelist' ]]\n      OnCrash crash\n      Begin\n        ms <- indclear_all indlvl lxp bxp # bn ms;\n        Ret ^(ms)\n      Rof ^(ms).\n\n  Theorem indclear_aligned_ok : forall indlvl lxp bxp indbns start len ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm Fs m0 sm m l_part fsl freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) # (fst x) l) (combine indbns fsl) l_part\n                         * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ start / N + len / N <= length l_part ]] * [[ Nat.divide N start ]] * [[ Nat.divide N len ]] *\n           [[ length fsl = length indbns ]] *\n           [[ (Fs * BALLOCC.smrep freelist * pred_fold_left fsl)%pred sm ]]\n    POST:hm' RET:^(ms)\n           exists m' freelist' indbns' fsl' l_part', \n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns' fsl') l_part'\n                          * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ indbns' = upd_range indbns (start / N) (len / N) $0 ]] *\n           [[ l_part' = upd_range l_part (start / N) (len / N) (repeat $0 N) ]] *\n           [[ incl freelist freelist' ]] *\n           [[ length fsl' = length indbns' ]] *\n           [[ (Fs * BALLOCC.smrep freelist' * pred_fold_left fsl')%pred sm ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear_aligned indlvl lxp bxp indbns start len ms.\n    Proof.\n      unfold indclear_aligned. unfold Nat.divide.\n      prestep. norml.\n      repeat rewrite Nat.div_mul in * by mult_nonzero.\n      rewrite listmatch_length_pimpl in *. destruct_lifts.\n      cancel.\n      all: repeat rewrite Nat.sub_diag; auto.\n      - cbn [skipn].\n        rewrite <- firstn_combine_comm.\n        rewrite <- skipn_combine by eauto.\n        rewrite listmatch_split with (n := z0).\n        rewrite listmatch_split with (n := z) (a := skipn _ _).\n        repeat cancel.\n      - cbn [skipn].\n        erewrite <- firstn_skipn with (n := z0) (l := fsl) at 1.\n        erewrite <- firstn_skipn with (n := z) (l := skipn _ fsl) at 1.\n        repeat rewrite pred_fold_left_app. cancel.\n      - prestep. norml.\n        assert (length (firstn z (skipn z0 fsl)) = length (firstn z (skipn z0 indbns))) by\n          (repeat rewrite ?firstn_length, ?skipn_length; congruence).\n        assert (length (firstn z (skipn z0 l_part)) = length (firstn z (skipn z0 indbns))) by\n          (rewrite firstn_length, skipn_length; indrep_n_tree_bound).\n        assert (length prefix < length (firstn z (skipn z0 indbns))) by\n          (substl (firstn z (skipn z0 indbns)); rewrite app_length; cbn; omega).\n        match goal with H: _ ++ _ = _ |- _ => rename H into Hp; repeat rewrite <- Hp in * end.\n        autorewrite with lists in *. cbn [length] in *.\n        repeat rewrite Nat.add_sub in *.\n        rewrite skipn_app in *.\n        cancel.\n        + erewrite skipn_selN_skipn with (l := firstn _ (skipn _ fsl)) at 1.\n          erewrite skipn_selN_skipn with (l := firstn _ (skipn _ l_part)) at 1.\n          cbn [combine].\n          rewrite listmatch_cons.\n          cancel.\n          all: omega.\n        + erewrite skipn_selN_skipn with (off := length prefix).\n          rewrite pred_fold_left_cons.\n          cancel. reflexivity.\n          omega.\n        + step.\n          repeat match goal with |- context [?b + S ?a - ?a] => replace (b + S a - a) with (b + 1) by omega end.\n          rewrite skipn_app_r_ge by omega.\n          rewrite minus_plus. rewrite <- plus_n_Sm, <- plus_n_O.\n          rewrite indrep_n_tree_0.\n          cancel.\n          repeat match goal with |- context [?b + S ?a - ?a] => replace (b + S a - a) with (b + 1) by omega end.\n          rewrite <- plus_n_Sm, <- plus_n_O.\n          cancel.\n        + cancel.\n      - step.\n        match goal with H: context [lift_empty] |- _ => destruct_lift H end.\n        rewrite combine_length_eq in * by auto.\n        repeat rewrite upd_range_eq_upd_range' by omega.\n        unfold upd_range'.\n        repeat rewrite combine_app.\n        repeat rewrite skipn_skipn.\n        replace (z0 + z) with (z + z0) in * by omega.\n        rewrite firstn_combine_comm, skipn_combine by auto.\n        repeat rewrite <- listmatch_app; cancel.\n        repeat rewrite Nat.sub_0_r.\n        repeat rewrite skipn_oob by indrep_n_tree_bound.\n        rewrite listmatch_indrep_n_tree_empty'.\n        unfold listmatch; cancel.\n        autorewrite with lists; auto.\n        indrep_n_tree_bound.\n        autorewrite with lists.\n        match goal with H: context [lift_empty] |- _ => destruct_lift H end.\n        rewrite combine_length_eq in * by auto.\n        rewrite firstn_length_l, skipn_length by omega.\n        omega.\n        repeat rewrite pred_fold_left_app.\n        cancel.\n        rewrite skipn_skipn.\n        rewrite skipn_oob by indrep_n_tree_bound.\n        rewrite pred_fold_left_repeat_emp.\n        cancel.\n      - cancel.\n        eauto using LOG.intact_hashmap_subset.\n    Grab Existential Variables. all : eauto; split.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indclear_aligned _ _ _ _ _ _ _ ) _) => apply indclear_aligned_ok : prog.\n\n  Definition update_block lxp bxp bn contents new ms :=\n    If (list_eq_dec waddr_eq_dec new (repeat $0 NIndirect)) {\n      ms <- BALLOCC.free lxp bxp bn ms;\n      Ret ^(ms, 0)\n    } else {\n      If (list_eq_dec waddr_eq_dec contents new) {\n        Ret ^(ms, bn)\n      } else {\n        lms <- IndRec.write lxp bn new (BALLOCC.MSLog ms);\n        Ret ^(BALLOCC.upd_memstate lms ms, bn)\n      }\n    }.\n\n  Lemma indrep_n_helper_valid_sm: forall Fs bxp ir l,\n    ir <> 0 ->\n    indrep_n_helper Fs bxp ir l =p=> indrep_n_helper Fs bxp ir l * [[ Fs <=p=> ir |->? ]].\n  Proof.\n    unfold indrep_n_helper.\n    intros.\n    destruct addr_eq_dec; try congruence.\n    cancel.\n  Qed.\n\n  Theorem update_block_ok : forall lxp bxp ir indbns indbns' ms,\n    {< F Fm Fs IFs m0 sm m freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n            [[ BALLOCC.bn_valid bxp ir ]] *\n            [[ IndRec.items_valid ir indbns' ]] *\n           [[[ m ::: (Fm * indrep_n_helper IFs bxp ir indbns) *\n              BALLOCC.rep bxp freelist ms ]]] *\n            [[ (Fs * BALLOCC.smrep freelist * IFs)%pred sm ]]\n    POST:hm' RET: ^(ms, ir')\n           exists m' freelist' IFs',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * indrep_n_helper IFs' bxp ir' indbns' *\n              BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ (Fs * BALLOCC.smrep freelist' * IFs')%pred sm ]] *\n           [[ incl freelist freelist' ]] *\n           ([[ ir' = 0 ]] \\/ [[ ir' = ir ]])\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} update_block lxp bxp ir indbns indbns' ms.\n  Proof.\n    unfold update_block.\n    prestep. norml.\n    assert (ir <> 0) by (unfold BALLOCC.bn_valid in *; intuition).\n    rewrite indrep_n_helper_valid_sm in * by auto.\n    denote lift_empty as Hf; destruct_lift Hf.\n    denote IFs as Hf; rewrite Hf in *.\n    denote BALLOCC.smrep as Hs; destruct_lift Hs.\n    step.\n    rewrite indrep_n_helper_pts_piff by auto. cancel.\n    + step.\n      rewrite indrep_n_helper_0 by auto.\n      cancel.\n    + step.\n      rewrite Hf; cancel.\n    + step.\n      rewrite indrep_n_helper_valid by auto; cancel.\n      prestep. norm. repeat cancel.\n      intuition idtac.\n      rewrite indrep_n_helper_valid by auto.\n      pred_apply; cancel; reflexivity.\n      pred_apply; cancel.\n      auto.\n      auto.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (update_block _ _ _ _ _ _) _) => apply update_block_ok : prog.\n\n  Fixpoint indclear_from_aligned indlvl lxp bxp iblocks start len ms :=\n    (* indlvl is for each block in iblocks *)\n    If (addr_eq_dec len 0) {\n      Ret ^(ms, iblocks)\n    } else {\n      let N := (NIndirect ^ S indlvl) in\n      let ragged_bn := #(selN iblocks (start / N) $0) in\n      If (addr_eq_dec ragged_bn 0) {\n        Ret ^(ms, iblocks)\n      } else {\n        let^ (lms, indbns) <- IndRec.read lxp ragged_bn 1 (BALLOCC.MSLog ms);\n        let ms := BALLOCC.upd_memstate lms ms in\n        match indlvl with\n        | 0 => \n          let indbns' := upd_range indbns 0 len $0 in\n          let^ (ms, v) <- update_block lxp bxp ragged_bn indbns indbns' ms;\n          Ret ^(ms, updN iblocks (start / N) $ v)\n        | S indlvl' =>\n          let N' := NIndirect ^ (S indlvl') in\n          let^ (ms) <- indclear_aligned indlvl' lxp bxp indbns 0 (len / N' * N') ms;\n          let indbns' := upd_range indbns 0 (len / N') $0 in\n          let^ (ms, indbns'') <- indclear_from_aligned indlvl' lxp bxp indbns' (len / N' * N') (len mod N') ms;\n          let^ (ms, v) <- update_block lxp bxp ragged_bn indbns indbns'' ms;\n          Ret ^(ms, updN iblocks (start / N) $ v)\n        end\n      }\n    }.\n\n  Theorem indclear_from_aligned_ok : forall indlvl lxp bxp indbns start len ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm Fs m0 sm m l_part freelist fsl,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns fsl) l_part\n                         * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ start + len <= length (concat l_part) ]] * [[ Nat.divide N start ]] * [[ len < N ]] *\n           [[ length fsl = length indbns ]] *\n           [[ (Fs * pred_fold_left fsl * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, indbns')\n           exists m' freelist' l_part' fsl',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns' fsl') l_part'\n                          * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ concat (l_part') = upd_range (concat l_part) start len $0 ]] *\n           [[ length indbns' = length indbns ]] *\n           [[ length fsl' = length indbns' ]] *\n           [[ incl freelist freelist' ]] *\n           [[ (Fs * pred_fold_left fsl' * BALLOCC.smrep freelist')%pred sm ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear_from_aligned indlvl lxp bxp indbns start len ms.\n  Proof.\n    induction indlvl.\n    + simpl. step; [> solve [hoare] |].\n      pose proof listmatch_indrep_n_tree_forall_length 0 as H'.\n      simpl in H'. rewrite H' in *.\n      denote combine as Hc. destruct_lift Hc. rewrite mult_1_r in *.\n      prestep. norml.\n      erewrite concat_hom_length in * by eauto.\n      assert (start / NIndirect < length l_part) by indrep_n_tree_bound.\n      assert (start / NIndirect < length indbns) by indrep_n_tree_bound.\n      cancel.\n      - hoare.\n        rewrite listmatch_extract in *.\n        erewrite selN_combine in * by auto.\n        cbn [fst snd] in *.\n        denote (# _ = _) as Ha. rewrite Ha in *.\n        rewrite indrep_n_helper_0 in *.\n        destruct_lifts.\n        erewrite upd_range_concat_hom_start_aligned; eauto.\n        denote (selN _ _ _ = repeat _ _) as Hb. rewrite Hb.\n        rewrite upd_range_same by omega.\n        erewrite selN_eq_updN_eq; eauto.\n        indrep_n_tree_bound.\n        omega.\n        indrep_n_tree_bound.\n      - step.\n        indrep_n_extract.\n        rewrite indrep_n_helper_valid by eauto. cancel.\n        indrep_n_tree_bound.\n        rewrite firstn_oob.\n        safestep.\n        1, 2: match goal with |- context [selN ?l ?ind ?d] =>\n            erewrite listmatch_extract with (a := combine l _) (i := ind) (ad := (d, _)) in *\n          end; rewrite ?selN_combine in * by auto; cbn [fst snd] in *;\n          auto; indrep_n_tree_bound.\n        * rewrite indrep_n_helper_items_valid in * by auto; destruct_lifts.\n          cbv [IndRec.items_valid] in *.\n          autorewrite with lists. intuition eauto.\n        * indrep_n_extract. cancel. indrep_n_tree_bound.\n        * rewrite pred_fold_left_selN_removeN with (i := start / NIndirect).\n          cancel. reflexivity.\n        * step.\n        **  rewrite combine_updN, listmatch_updN_removeN. cancel. all: indrep_n_tree_bound.\n        **  erewrite upd_range_concat_hom_start_aligned; eauto. indrep_n_tree_bound. omega.\n        **  indrep_n_tree_bound.\n        **  autorewrite with lists; omega.\n        **  rewrite pred_fold_left_selN_removeN with (l := updN _ _ _).\n            rewrite selN_updN_eq, removeN_updN by omega. cancel.\n        **  rewrite natToWord_wordToNat. rewrite combine_updN.\n            rewrite listmatch_updN_removeN by (eauto; indrep_n_tree_bound). cancel.\n        **  erewrite upd_range_concat_hom_start_aligned; eauto. indrep_n_tree_bound. omega.\n        **  indrep_n_tree_bound.\n        **  autorewrite with lists; omega.\n        **  rewrite pred_fold_left_selN_removeN with (l := updN _ _ _).\n            rewrite selN_updN_eq, removeN_updN by omega. cancel.\n        * cancel.\n        * match goal with |- context [selN ?l ?ind ?d] =>\n            rewrite listmatch_extract with (b := l) (i := ind) (bd := d) in *\n          end. rewrite indrep_n_helper_length_piff in *.\n          destruct_lifts.\n          denote (length (selN _ _ _) = _) as Ha. rewrite Ha.\n          omega.\n          indrep_n_tree_bound.\n    + cbn [indclear_from_aligned].\n      prestep. norml.\n      pose proof listmatch_indrep_n_tree_forall_length (S indlvl) as H'.\n      simpl in H'. rewrite H' in *.\n      denote (combine indbns fsl) as Hc; destruct_lift Hc.\n      cancel; [ solve [hoare] |].\n      prestep. norml.\n      erewrite concat_hom_length in * by eauto.\n      assert (start / (NIndirect ^ S (S indlvl)) < length l_part) by indrep_n_tree_bound.\n      assert (start / (NIndirect ^ S (S indlvl)) < length indbns) by indrep_n_tree_bound.\n      cancel.\n      step.\n      {\n        rewrite listmatch_extract in *.\n        erewrite selN_combine in * by auto. cbn [fst snd] in *.\n        denote (# _ = _) as Ha. rewrite Ha in *.\n        destruct_lifts.\n        rewrite indrep_n_helper_0 in *.\n        destruct_lift H.\n        rewrite listmatch_indrep_n_tree_empty'' in *.\n        destruct_lifts.\n        erewrite upd_range_concat_hom_start_aligned; eauto.\n        denote (selN _ _ _ = _) as Hs. rewrite Hs.\n        rewrite concat_repeat in *.\n        rewrite upd_range_same by omega.\n        erewrite selN_eq_updN_eq; eauto.\n        indrep_n_tree_bound.\n        omega.\n        omega.\n        rewrite repeat_length in *; eauto.\n        indrep_n_tree_bound.\n      }\n      match goal with [|- context [selN ?L ?N] ] => \n        rewrite listmatch_extract with (a := combine L _) (i := N) in * by indrep_n_tree_bound end.\n      destruct_lifts.\n      rewrite combine_length_eq in * by omega.\n      step.\n      {\n        rewrite selN_combine by indrep_n_tree_bound; cbn [fst snd].\n        rewrite indrep_n_helper_valid by eauto. cancel.\n      }\n      rewrite firstn_oob.\n      match goal with [H : context [listmatch _ (combine ?l _)] |- context [?c = ?l] ] =>\n        rewrite listmatch_length_pimpl with (a := combine l _) in H;\n        rewrite indrep_n_helper_length_piff in H; destruct_lift H end.\n      rewrite combine_length_eq in * by omega.\n      prestep. norm. cancel.\n      intuition auto.\n      pred_apply; cancel.\n      {\n        rewrite Nat.div_mul, Nat.div_0_l by auto. simpl in *.\n        apply Nat.div_le_upper_bound; mult_nonzero. rewrite mult_comm.\n        apply Nat.lt_le_incl. congruence.\n      }\n      indrep_n_tree_bound.\n      {\n        denote (snd (selN _ _ _)) as Hp.\n        rewrite selN_combine in Hp by indrep_n_tree_bound.\n        cbn [snd] in Hp.\n        pred_apply.\n        rewrite pred_fold_left_selN_removeN.\n        rewrite Hp.\n        cancel.\n      }\n      safestep.\n      { rewrite Nat.div_0_l, Nat.div_mul by auto. cancel. }\n      {\n        rewrite mult_comm, <- Nat.div_mod by auto.\n        erewrite concat_hom_length by eauto.\n        autorewrite with lists.\n        apply Nat.lt_le_incl. congruence.\n      }\n      autorewrite with lists; indrep_n_tree_bound.\n      cancel.\n      prestep. norm. cancel.\n      rewrite selN_combine with (a := indbns) in * by eauto.\n      cbn [fst snd] in *.\n      intuition auto.\n      unfold IndRec.items_valid, IndSig.xparams_ok, IndSig.RAStart, IndSig.RALen.\n      rewrite mult_1_l. intuition.\n      rewrite upd_range_length in *.\n      match goal with |- length ?x = _ => substl (length x) end.\n      indrep_n_tree_bound.\n      pred_apply; cancel.\n      pred_apply; cancel.\n      - step; clear IHindlvl.\n        5: match goal with |- context [removeN _ ?i] =>\n          erewrite pred_fold_left_selN_removeN with (l := updN fsl i (pred_fold_left fsl'0));\n          rewrite selN_updN_eq, removeN_updN by omega\n        end.\n        * rewrite indrep_n_helper_0. cancel.\n          rewrite combine_updN, listmatch_updN_removeN.\n          norm. cancel. eassign IFs'. rewrite indrep_n_helper_0. cancel.\n          intuition eauto.\n          denote (IFs' <=p=> emp) as Hf. rewrite Hf. split; cancel.\n          all: indrep_n_tree_bound.\n        * erewrite upd_range_concat_hom_start_aligned; eauto.\n          repeat f_equal.\n          denote (concat _ = _) as Hc. rewrite Hc.\n          denote (selN _ _ _ = _) as Hs. rewrite Hs.\n          rewrite concat_hom_upd_range by eauto. cbn -[Nat.div Nat.modulo].\n          autorewrite with lists. simpl.\n          rewrite mult_comm, <- Nat.div_mod; auto.\n          erewrite concat_hom_length; eauto.\n          all: omega.\n        * autorewrite with lists; auto.\n        * autorewrite with lists; omega.\n        * denote (indrep_n_helper _ _ 0) as Hi. rewrite indrep_n_helper_0 in Hi.\n          destruct_lift Hi. denote (IFs' <=p=> emp) as Hf. rewrite Hf. cancel.\n        * rewrite natToWord_wordToNat. rewrite combine_updN.\n          rewrite listmatch_updN_removeN. cancel. reflexivity.\n          indrep_n_tree_bound.\n          reflexivity.\n          all: indrep_n_tree_bound.\n        * denote (concat _ = _) as Hc. rewrite Hc.\n          symmetry.\n          erewrite upd_range_concat_hom_start_aligned; eauto.\n          rewrite concat_hom_upd_range; eauto.\n          rewrite upd_range_upd_range; eauto.\n          repeat f_equal; eauto.\n          rewrite mult_comm with (n := len / _), <- Nat.div_mod; auto.\n          erewrite concat_hom_length by eauto. omega.\n          all: omega.\n        * autorewrite with lists; auto.\n        * autorewrite with lists; auto.\n        * rewrite pred_fold_left_selN_removeN with (l := updN _ _ _).\n          rewrite selN_updN_eq, removeN_updN by omega. cancel.\n      - cancel.\n      - cancel.\n      - cancel.\n      - indrep_n_tree_bound.\n    Grab Existential Variables.\n    all : intros; eauto.\n    all : try solve [exact unit | exact nil | exact $ 0 | exact 0 | exact True | exact ($0, emp) ].\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (indclear_from_aligned _ _ _ _ _ _ _) _) => apply indclear_from_aligned_ok : prog.\n\n  Fixpoint indclear_to_aligned indlvl lxp bxp iblocks start ms :=\n    let N := (NIndirect ^ S indlvl) in\n    If (addr_eq_dec (start mod N) 0) {\n      Ret ^(ms, iblocks)\n    } else {\n      let ragged_bn := #(selN iblocks (start / N) $0) in\n      If (addr_eq_dec ragged_bn 0) {\n        Ret ^(ms, iblocks)\n      } else {\n        let^ (lms, indbns) <- IndRec.read lxp ragged_bn 1 (BALLOCC.MSLog ms);\n        let ms := BALLOCC.upd_memstate lms ms in\n        match indlvl with\n        | 0 =>\n          let indbns' := upd_range indbns (start mod NIndirect) (NIndirect - (start mod NIndirect)) $0 in\n          let^ (ms, v) <- update_block lxp bxp ragged_bn indbns indbns' ms;\n          Ret ^(ms, updN iblocks (start / N) $ v)\n        | S indlvl' =>\n          let N' := NIndirect ^ S indlvl' in\n          let start' := start mod N in\n          let^ (ms, indbns') <- indclear_to_aligned indlvl' lxp bxp indbns start' ms;\n          let^ (ms) <- indclear_aligned indlvl' lxp bxp indbns' (roundup start' N') (N - (roundup start' N')) ms;\n          let indbns'' := upd_range indbns' (divup start' N') (NIndirect - (divup start' N')) $0 in\n          let^ (ms, v) <- update_block lxp bxp ragged_bn indbns indbns'' ms;\n          Ret ^(ms, updN iblocks (start / N) $ v)\n        end\n      }\n    }.\n\n  Theorem indclear_to_aligned_ok : forall indlvl lxp bxp indbns start ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm Fs m0 sm m fsl l_part freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns fsl) l_part\n                         * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * pred_fold_left fsl * BALLOCC.smrep freelist)%pred sm ]] *\n           [[ start <= length (concat l_part) ]] *\n           [[ length fsl = length indbns ]]\n    POST:hm' RET:^(ms, indbns')\n           exists m' freelist' fsl' l_part',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns' fsl') l_part'\n                          * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ concat (l_part') = upd_range (concat l_part) start (roundup start N - start) $0 ]] *\n           [[ incl freelist freelist' ]] *\n           [[ (Fs * pred_fold_left fsl' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ length fsl' = length indbns' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear_to_aligned indlvl lxp bxp indbns start ms.\n  Proof.\n    induction indlvl.\n    intros.\n    + simpl in *. subst N. rewrite mult_1_r in *.\n      step. hoare.\n      {\n        unfold roundup. rewrite divup_eq_div by auto.\n        rewrite mul_div by auto. autorewrite with core lists. auto.\n      }\n      denote indrep_n_helper as Hi.\n      setoid_rewrite (listmatch_indrep_n_tree_forall_length 0) in Hi.\n      destruct_lift Hi. rewrite mult_1_r in *.\n      rewrite listmatch_length_pimpl in *. destruct_lifts.\n      prestep. norml.\n      assert (start / NIndirect < length l_part).\n        erewrite concat_hom_length in *; eauto.\n        apply Nat.div_lt_upper_bound; auto. rewrite mult_comm.\n        edestruct le_lt_eq_dec; [> | eauto |]; eauto.\n        subst. rewrite Nat.mod_mul in * by auto. intuition.\n      cancel.\n      prestep. norm. cancel.\n      intuition auto.\n      2: {\n        rewrite roundup_eq, minus_plus by auto.\n        rewrite listmatch_extract in *.\n        erewrite <- upd_range_concat_hom_small; eauto.\n        all : autorewrite with core lists; auto with *; eauto.\n        rewrite <- roundup_eq by auto.\n        erewrite concat_hom_length in * by eauto.\n        apply roundup_le. omega.\n        eassign (start / NIndirect).\n        rewrite min_l by omega.\n        rewrite combine_length_eq in *; omega.\n      }\n      {\n        pred_apply; cancel.\n        erewrite <- updN_selN_eq with (l := combine _ _) at 2.\n        rewrite listmatch_updN_removeN.\n        indrep_n_extract.\n        repeat rewrite selN_combine by auto. cbn [fst snd].\n        denote (# _ = _) as Hn. repeat rewrite Hn. rewrite indrep_n_helper_0 in *.\n        cancel. rewrite indrep_n_helper_0.\n        cancel.\n        denote (_ = repeat _ _) as Hl. rewrite Hl.\n        apply upd_range_same.\n        eauto.\n        all: omega.\n      }\n      auto.\n      pred_apply; cancel.\n      omega.\n      step.\n      indrep_n_extract. rewrite indrep_n_helper_valid by eauto. cancel.\n      rewrite firstn_oob.\n      prestep. norm. cancel.\n      intuition auto.\n      - match goal with [|- context [selN ?L ?N ?d] ] =>\n          erewrite listmatch_extract with (a := combine L _) (i := N) (ad := (d, _)) in * by omega\n        end. rewrite selN_combine in * by auto. cbn [fst snd] in *. eauto.\n      - match goal with [|- context [selN ?L ?N ?d] ] =>\n          erewrite listmatch_extract with (a := combine L _) (i := N) (ad := (d, _)) in * by omega\n        end. rewrite selN_combine in * by auto. cbn [fst snd] in *.\n        rewrite indrep_n_helper_items_valid in * by eauto; destruct_lifts.\n        unfold IndRec.items_valid in *; intuition.\n        autorewrite with lists; eauto.\n      - pred_apply. indrep_n_extract. cancel.\n      - pred_apply. rewrite pred_fold_left_selN_removeN with (i := start/NIndirect) (l := fsl).\n        cancel. instantiate (1 := emp). cancel.\n      - prestep; norm; try cancel.\n        all: intuition auto.\n        * pred_apply. erewrite combine_updN. rewrite listmatch_updN_removeN. cancel. all: omega.\n        * rewrite roundup_eq by auto. rewrite minus_plus.\n          erewrite upd_range_concat_hom_small; eauto.\n          all : autorewrite with core; eauto.\n          rewrite <- roundup_eq by auto.\n          erewrite concat_hom_length in *; eauto.\n        * auto.\n        * rewrite pred_fold_left_updN_removeN by (rewrite combine_length_eq in *; omega).\n          pred_apply; cancel.\n        * autorewrite with lists; auto.\n        * rewrite natToWord_wordToNat. rewrite combine_updN.\n          rewrite listmatch_updN_removeN. pred_apply; cancel.\n          all: rewrite ?combine_length_eq; try omega; indrep_n_tree_bound.\n        * rewrite roundup_eq by auto. rewrite minus_plus.\n          erewrite upd_range_concat_hom_small; eauto.\n          rewrite <- roundup_eq by auto.\n          erewrite concat_hom_length in * by eauto. auto.\n          rewrite le_plus_minus_r; auto.\n        * auto.\n        * rewrite pred_fold_left_updN_removeN by (rewrite combine_length_eq in *; omega).\n          pred_apply; cancel.\n        * autorewrite with lists; auto.\n      - cancel.\n      - match goal with [|- context [selN ?L ?N ?d] ] =>\n          rewrite listmatch_extract with (b := L) (i := N) (bd := d) in * by omega\n        end. rewrite indrep_n_helper_length_piff in *.\n        destruct_lifts. autorewrite with core. apply Nat.eq_le_incl. assumption.\n    + cbn [indclear_to_aligned].\n      prestep. norml.\n      pose proof listmatch_indrep_n_tree_forall_length (S indlvl) as H'.\n      simpl in H'. match goal with H: _ |- _ => rewrite H' in H; destruct_lift H end.\n      cancel. hoare.\n      {\n        unfold roundup. rewrite divup_eq_div by auto. rewrite mul_div by mult_nonzero.\n        autorewrite with core. auto.\n      }\n      prestep. norml.\n      rewrite listmatch_length_pimpl in *. destruct_lifts.\n      assert (start / (NIndirect ^ S (S indlvl)) < length l_part); simpl in *.\n        erewrite concat_hom_length in *; eauto.\n        apply Nat.div_lt_upper_bound; auto. rewrite mult_comm.\n        edestruct le_lt_eq_dec; [> | eauto |]; eauto.\n        subst. rewrite Nat.mod_mul in * by auto. intuition.\n      cancel. prestep. norm. cancel.\n      instantiate (1 := updN _ _ _). intuition auto.\n      {\n        erewrite <- updN_selN_eq with (l := indbns) at 1.\n        rewrite combine_updN. rewrite listmatch_updN_removeN.\n        denote (# _ = 0) as Hn. cbn [fst snd].\n        pred_apply. rewrite listmatch_extract. rewrite selN_combine.\n        cbn [fst snd]. repeat rewrite Hn. cancel. reflexivity.\n        all: eauto; omega.\n      }\n      {\n        rewrite roundup_eq, minus_plus by auto.\n        rewrite listmatch_extract in *. destruct_lifts.\n        erewrite upd_range_concat_hom_small; eauto.\n        erewrite selN_combine in *. cbn [fst snd] in *.\n        denote (# _ = 0) as Hn. rewrite Hn in *.\n        rewrite indrep_n_helper_0 in *. destruct_lifts.\n        rewrite listmatch_indrep_n_tree_empty'' in *. destruct_lifts.\n        do 2 f_equal.\n        denote (selN _ _ _ = _) as Hs. repeat rewrite Hs.\n        erewrite concat_hom_repeat by (auto using Forall_repeat).\n        rewrite upd_range_same; auto.\n        all: try omega; mult_nonzero.\n        indrep_n_tree_bound.\n        erewrite concat_hom_length in * by eauto.\n        rewrite <- roundup_eq; auto.\n        indrep_n_tree_bound.\n      }\n      auto.\n      rewrite updN_selN_eq. auto.\n      autorewrite with lists; auto.\n      match goal with [|- context [selN ?L ?N ?d] ] =>\n        rewrite listmatch_extract with (a := combine L _) (i := N) (ad := (d, emp)) in * by omega\n      end. simpl in *. destruct_lifts.\n      rewrite selN_combine in * by omega; cbn [fst snd] in *.\n      step.\n      { rewrite indrep_n_helper_valid by eauto. cancel. }\n      rewrite firstn_oob.\n      match goal with [H : context [listmatch _ (combine ?l _)] |- context [?c = ?l] ] =>\n        rewrite listmatch_length_pimpl with (a := combine l _) in H;\n        rewrite indrep_n_helper_length_piff in H; destruct_lift H end.\n      prestep. norm. cancel.\n      intuition auto.\n      pred_apply; cancel.\n      pred_apply. rewrite pred_fold_left_selN_removeN with (l := fsl).\n      denote (selN fsl) as Hs. rewrite Hs. cancel.\n      {\n        erewrite concat_hom_length by eauto.\n        eapply le_trans; [> | apply mult_le_compat_r]. eauto. indrep_n_tree_bound.\n      }\n      omega.\n      safestep.\n      {\n        unfold roundup. rewrite <- Nat.mul_sub_distr_r. repeat rewrite Nat.div_mul by auto.\n        autorewrite with core.\n        match goal with [H : context [concat ?l] |- context [length ?l] ] =>\n          apply f_equal with (f := @length _) in H; erewrite concat_hom_length in H; eauto end.\n        rewrite upd_range_length in *; autorewrite with core; auto with *.\n        erewrite concat_hom_length in * by eauto.\n        rewrite Nat.mul_cancel_r in *; mult_nonzero.\n        rewrite combine_length_eq in * by omega. omega.\n        apply divup_le. rewrite mult_comm. eauto.\n      }\n      prestep. norm. cancel. intuition idtac.\n      auto.\n      {\n        unfold IndRec.items_valid, IndSig.xparams_ok, IndSig.RAStart, IndSig.RALen.\n        rewrite mult_1_l.\n        match goal with [H : context [listmatch _ (combine ?l _)] |- context [length (upd_range ?l _ _ _)] ] =>\n          rewrite listmatch_length_pimpl with (a := (combine l _)) in H; destruct_lift H end.\n        denote (concat _ = upd_range _ _ _ _) as Hc.\n        apply f_equal with (f := @length _) in Hc.\n        rewrite combine_length_eq in * by omega.\n        erewrite concat_hom_length in Hc; eauto.\n        autorewrite with lists in *.\n        erewrite concat_hom_length in * by eauto.\n        rewrite Nat.mul_cancel_r in *; mult_nonzero.\n        intuition; omega.\n      }\n      pred_apply; cancel.\n      pred_apply; cancel.\n      step; clear IHindlvl.\n      - rewrite indrep_n_helper_0. cancel.\n        rewrite combine_updN, listmatch_updN_removeN.\n        norm. cancel. rewrite indrep_n_helper_0'. cancel.\n        unfold roundup. rewrite <- Nat.mul_sub_distr_r.\n        repeat rewrite Nat.div_mul by auto.\n        denote (upd_range _ _ _) as Hu. rewrite Hu.\n        cancel. reflexivity.\n        intuition eauto.\n        rewrite upd_range_length, repeat_length in *.\n        match goal with H: upd_range ?l _ _ _ = _ |- length ?l' = _ =>\n          assert (length l' = length l) as Hl by indrep_n_tree_bound; rewrite Hl;\n          eapply f_equal with (f := @length _) in H; autorewrite with lists in H\n        end.\n        all : omega.\n      - rewrite roundup_eq with (a := start) by mult_nonzero.\n        rewrite minus_plus.\n        eapply indclear_upd_range_helper_1; eauto.\n        erewrite concat_hom_length by eauto.\n        rewrite combine_length_eq2 in * by omega. congruence.\n      - rewrite pred_fold_left_updN_removeN.\n        rewrite indrep_n_helper_0 with (Fs := IFs') in *.\n        denote (IFs' <=p=> emp) as Hf; destruct_lift Hf.\n        psubst. cancel.\n        rewrite combine_length_eq in * by omega. omega.\n      - autorewrite with lists; auto.\n      - rewrite natToWord_wordToNat.\n        unfold roundup. rewrite <- Nat.mul_sub_distr_r. repeat rewrite Nat.div_mul by auto.\n        rewrite combine_updN.\n        rewrite listmatch_updN_removeN. cancel; eauto.\n        indrep_n_tree_bound.\n        all : omega.\n      - erewrite indclear_upd_range_helper_1; eauto.\n        f_equal. rewrite roundup_eq by auto. omega.\n        erewrite concat_hom_length by eauto.\n        rewrite combine_length_eq in * by omega. congruence.\n      - rewrite pred_fold_left_updN_removeN. cancel.\n        rewrite combine_length_eq in * by omega. omega.\n      - autorewrite with lists; auto.\n      - cancel.\n      - cancel.\n      - cancel.\n      - rewrite indrep_n_helper_length_piff in *. destruct_lifts.\n        unfold IndRec.Defs.item in *. simpl in *. omega.\n    Unshelve.\n    all : intros; try solve [exact unit | exact nil | exact $0 | exact emp | exact ($0, emp) | constructor].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indclear_to_aligned _ _ _ _ _ _) _) => apply indclear_to_aligned_ok : prog.\n\n  Definition indclear_multiple_blocks indlvl lxp bxp indbns start len ms :=\n    let N := NIndirect ^ S indlvl in\n    let^ (ms, indbns') <- indclear_to_aligned indlvl lxp bxp indbns start ms;\n    let len' := len - (roundup start N - start) in\n    let start' := start + (roundup start N - start) in\n    let^ (ms) <- indclear_aligned indlvl lxp bxp indbns' start' (len' / N * N) ms;\n    let indbns'' := upd_range indbns' (start' / N) (len' / N) $0 in\n    let start'' := start' + (len' / N * N) in\n    let len'' := len' mod N in\n    indclear_from_aligned indlvl lxp bxp indbns'' start'' len'' ms.\n\n  Theorem indclear_multiple_blocks_ok : forall indlvl lxp bxp indbns start len ms,\n    let N := NIndirect ^ S indlvl in\n    {< F Fm Fs m0 sm m l_part freelist fsl,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns fsl) l_part\n                         * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ start <= length (concat l_part) ]] * [[ (N - start mod N) < len ]] *\n           [[ start + len <= length (concat l_part) ]] *\n           [[ (Fs * pred_fold_left fsl * BALLOCC.smrep freelist)%pred sm ]] *\n           [[ length indbns = length fsl ]]\n    POST:hm' RET:^(ms, indbns')\n           exists m' freelist' l_part' fsl',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * listmatch (fun x l => indrep_n_tree indlvl bxp (snd x) #(fst x) l) (combine indbns' fsl') l_part'\n                          * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ concat (l_part') = upd_range (concat l_part) start len $0 ]] *\n           [[ (Fs * pred_fold_left fsl' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ length indbns' = length fsl' ]] *\n           [[ incl freelist freelist' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear_multiple_blocks indlvl lxp bxp indbns start len ms.\n  Proof.\n    intros. subst N.\n    unfold indclear_multiple_blocks.\n    step.\n    step.\n    { repeat rewrite Nat.div_mul by mult_nonzero.\n      eapply le_trans. apply div_add_distr_le.\n      denote (concat _ = _) as Hc.\n      apply f_equal with (f := @length _) in Hc.\n      rewrite upd_range_length in *.\n      repeat erewrite concat_hom_length in * by eauto.\n      rewrite Nat.mul_cancel_r in * by mult_nonzero.\n      apply Nat.div_le_upper_bound; auto. rewrite mult_comm with (m := length _).\n      destruct (addr_eq_dec (start mod (NIndirect * NIndirect ^ indlvl)) 0).\n      - unfold roundup. rewrite divup_eq_div by auto. rewrite mul_div by mult_nonzero.\n        autorewrite with core. congruence.\n      - rewrite roundup_eq by auto. rewrite minus_plus.\n        rewrite <- plus_assoc. autorewrite with core; solve [congruence | omega].\n    }\n    { autorewrite with core; auto. }\n    prestep. norm. cancel.\n    intuition auto.\n    + pred_apply. repeat rewrite Nat.div_mul by auto. cancel.\n    + erewrite concat_hom_length by auto. autorewrite with lists.\n      rewrite mult_comm with (m := _ * _ ^ _).\n      rewrite <- plus_assoc, <- Nat.div_mod by auto.\n      denote (concat _ = _) as Hc.\n      apply f_equal with (f := @length _) in Hc.\n      rewrite upd_range_length in *.\n      repeat erewrite concat_hom_length in * by eauto.\n      rewrite Nat.mul_cancel_r in * by mult_nonzero.\n      destruct (addr_eq_dec (start mod (NIndirect * NIndirect ^ indlvl)) 0).\n      - unfold roundup. rewrite divup_eq_div by auto. rewrite mul_div by mult_nonzero.\n        autorewrite with core. congruence.\n      - rewrite roundup_eq by auto. rewrite minus_plus.\n        rewrite <- plus_assoc. autorewrite with core; solve [congruence | omega].\n    + autorewrite with core. auto.\n    + autorewrite with lists in *. omega.\n    + pred_apply; cancel.\n    + step.\n      rewrite concat_hom_upd_range in * by eauto.\n      set (N := _ * _ ^ _) in *.\n      rewrite le_plus_minus_r in * by auto.\n      rewrite roundup_round in *.\n      match goal with H: concat _ = _, H' : concat _ = _ |- _ => rewrite H, H' end.\n      autorewrite with lists.\n      rewrite mult_comm with (m := N), <- Nat.div_mod by mult_nonzero.\n      erewrite <- le_plus_minus_r with (m := roundup start N) at 2.\n      rewrite upd_range_upd_range. f_equal.\n      destruct (addr_eq_dec (start mod N) 0).\n      - unfold roundup. rewrite divup_eq_div by auto. rewrite mul_div by mult_nonzero. omega.\n      - rewrite roundup_eq by mult_nonzero. autorewrite with core; omega.\n      - auto.\n    + cancel.\n    Unshelve.\n      all : solve [exact unit | exact nil].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indclear_multiple_blocks _ _ _ _ _ _ _) _) => apply indclear_multiple_blocks_ok : prog.\n\n  Fixpoint indclear indlvl lxp bxp (root : addr) start len ms :=\n    let N := NIndirect ^ indlvl in\n    If (addr_eq_dec root 0) {\n      Ret ^(ms, 0)\n    } else {\n      If (addr_eq_dec len 0) {\n        Ret ^(ms, root)\n      } else {\n        let^ (lms, indbns) <- IndRec.read lxp root 1 (BALLOCC.MSLog ms);\n        let ms := BALLOCC.upd_memstate lms ms in\n        let^ (ms, indbns') <- match indlvl with\n        | 0 =>\n           Ret ^(ms, upd_range indbns start len $0)\n        | S indlvl' =>\n          If (le_lt_dec len (N - start mod N)) {\n            let^ (ms, v) <- indclear indlvl' lxp bxp #(selN indbns (start / N) $0) (start mod N) len ms;\n            Ret ^(ms, updN indbns (start / N) $ v)\n          } else {\n            indclear_multiple_blocks indlvl' lxp bxp indbns start len ms\n          }\n        end;\n        update_block lxp bxp root indbns indbns' ms\n      }\n    }.\n\n  Theorem indclear_ok : forall indlvl lxp bxp ir start len ms,\n    {< F Fm Fs m0 sm m l freelist IFs,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * indrep_n_tree indlvl bxp IFs ir l *\n            BALLOCC.rep bxp freelist ms) ]]] *\n           [[ start + len <= length l ]] *\n           [[ (Fs * IFs * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, ir')\n           exists m' freelist' l' IFs',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * indrep_n_tree indlvl bxp IFs' ir' l' *\n              BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ incl freelist freelist' ]] * [[ l' = upd_range l start len $0 ]] *\n           [[ (Fs * IFs' * BALLOCC.smrep freelist')%pred sm ]] *\n           ([[ ir = ir' ]] \\/ [[ ir' = 0 ]])\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indclear indlvl lxp bxp ir start len ms.\n    Proof.\n      induction indlvl.\n      + cbn -[Nat.div].\n        prestep. norml.\n        denote indrep_n_helper as Hi.\n        rewrite indrep_n_helper_length_piff in Hi; destruct_lift Hi.\n        step.\n        rewrite indrep_n_helper_0 in *. destruct_lifts.\n        autorewrite with lists; auto.\n        - hoare.\n        - step.\n          rewrite indrep_n_helper_valid by auto; cancel.\n          rewrite firstn_oob by indrep_n_tree_bound.\n          hoare.\n      + cbn [indclear].\n        step. step.\n        {\n          denote indrep_n_helper as Hi.\n          rewrite indrep_n_helper_0 in Hi. destruct_lift Hi.\n          rewrite listmatch_indrep_n_tree_empty'' in H.\n          destruct_lift H.\n          erewrite concat_hom_repeat by eauto using Forall_repeat.\n          autorewrite with lists. reflexivity.\n          rewrite repeat_length in *; auto.\n        }\n        step. solve [step].\n        step.\n        { rewrite indrep_n_helper_valid by auto. cancel. }\n        rewrite indrep_n_helper_length_piff in *. destruct_lifts.\n        unfold IndRec.Defs.item in *; simpl in *.\n        rewrite firstn_oob by indrep_n_tree_bound.\n        step.\n        - safestep.\n          erewrite concat_hom_length in * by eauto.\n          match goal with |- context [listmatch _ _ ?l] =>\n            replace (length l) with NIndirect in * by indrep_n_tree_bound end.\n          indrep_n_extract; [cancel | indrep_n_tree_bound..].\n          match goal with [H : context [listmatch _ _ ?l] |- context [selN ?l ?n] ] =>\n            rewrite listmatch_extract with (i := n) in H\n          end.\n          indrep_n_tree_extract_lengths.\n          denote (length _ = _) as Hl. rewrite Hl. omega.\n          indrep_n_tree_bound.\n          psubst.\n          match goal with |- context [selN _ ?n] =>\n            rewrite pred_fold_left_selN_removeN with (i := n) end. cancel.\n          instantiate (1 := emp). cancel.\n          safestep; rewrite ?natToWord_wordToNat, ?updN_selN_eq.\n          * prestep. norm. cancel. cancel.\n            assert (dummy = repeat $0 NIndirect).\n            rewrite indrep_n_helper_0 in H8. destruct_lift H8. auto.\n            subst.\n            rewrite repeat_selN' in *.\n            {\n              match goal with H: context [concat ?l] |- _ => cut (length l = NIndirect) end.\n              intuition auto. pred_apply. cancel.\n              erewrite listmatch_isolate with (a := combine _ _).\n              erewrite combine_updN_r with (x := IFs').\n              rewrite removeN_updN, selN_updN_eq.\n              cbn [fst snd].\n              rewrite repeat_selN'. rewrite removeN_updN, selN_updN_eq.\n              cancel.\n              all: rewrite ?repeat_length in *; auto.\n              indrep_n_tree_bound.\n              indrep_n_tree_bound.\n              indrep_n_tree_bound.\n              indrep_n_tree_bound.\n              indrep_n_tree_bound.\n\n              eauto.\n              erewrite upd_range_concat_hom_small by (eauto; mult_nonzero; omega). auto.\n              pred_apply.\n              rewrite pred_fold_left_updN_removeN.\n              cancel.\n              indrep_n_tree_bound.\n              match goal with H: context [listmatch _ _ ?l] |- length ?l = _ =>\n                erewrite <- listmatch_length_l by (pred_apply' H; cancel)\n              end.\n              indrep_n_tree_bound.\n            }\n            repeat cancel.\n            intuition auto.\n            pred_apply. norm; intuition.\n            rewrite combine_updN. cancel.\n            rewrite listmatch_updN_removeN. cancel.\n            rewrite updN_selN_eq. cancel.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            autorewrite with lists; omega.\n            eauto.\n            erewrite upd_range_concat_hom_small by (eauto; mult_nonzero; omega). auto.\n            auto.\n            rewrite pred_fold_left_updN_removeN.\n            pred_apply; cancel.\n            replace (length dummy1) with NIndirect by indrep_n_tree_bound.\n            indrep_n_tree_bound.\n          * cancel.\n          * prestep. norm. cancel. cancel. intuition auto.\n            pred_apply. norm; intuition.\n            rewrite combine_updN. cancel.\n            rewrite listmatch_updN_removeN. repeat rewrite indrep_n_helper_0. cancel.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            autorewrite with lists; auto.\n            eauto.\n            erewrite upd_range_concat_hom_small by (eauto; mult_nonzero; omega).\n            auto.\n            auto.\n            rewrite pred_fold_left_updN_removeN by (substl (length dummy1); indrep_n_tree_bound).\n            pred_apply; cancel.\n            repeat cancel.\n            intuition auto.\n            pred_apply. norm; intuition.\n            rewrite combine_updN. cancel.\n            rewrite listmatch_updN_removeN. repeat rewrite indrep_n_helper_0. cancel.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            autorewrite with lists; auto.\n            eauto.\n            erewrite upd_range_concat_hom_small by (eauto; mult_nonzero; omega).\n            auto.\n            auto.\n            rewrite pred_fold_left_updN_removeN by (substl (length dummy1); indrep_n_tree_bound).\n            pred_apply; cancel.\n          * cancel.\n          * cancel.\n      - step.\n        psubst. cancel.\n        step.\n        unfold IndRec.items_valid, IndSig.xparams_ok, IndSig.RAStart, IndSig.RALen, Rec.well_formed.\n        simpl. intuition auto.\n        (* indrep_n_tree_bound is not smart enough to switch from one tree to another *)\n        match goal with [H : concat _ = _|- _] => apply f_equal with (f := @length _) in H end.\n        autorewrite with lists in *.\n        repeat erewrite concat_hom_length in * by eauto.\n        erewrite <- combine_length_eq by eassumption.\n        rewrite Nat.mul_cancel_r in *; auto.\n        match goal with H: context [listmatch _ ?l] |- length ?l = _ =>\n          erewrite listmatch_length_l by (pred_apply' H; cancel) end.\n        match goal with H: _ = _ |- _ => rewrite H end.\n        indrep_n_tree_bound.\n        step.\n    Grab Existential Variables.\n    all : eauto.\n    all: try constructor; solve [exact $0 | exact emp].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indclear _ _ _ _ _ _ _ ) _) => apply indclear_ok : prog.\n  Opaque indclear.\n\n  Definition indput_get_blocks {P} {Q} lxp (is_alloc : {P} + {Q}) ir ms :=\n    If (is_alloc) {\n      Ret ^(ms, repeat $0 NIndirect)\n    } else {\n      IndRec.read lxp ir 1 ms\n    }.\n\n  Theorem indput_get_blocks_ok : forall P Q lxp (is_alloc : {P} + {Q}) ir ms,\n    {< F Fm m0 sm m bxp indbns Fs,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[ BALLOCC.bn_valid bxp ir ]] *\n           [[ P -> ir = 0 ]] * [[ Q -> ir <> 0 ]] *\n           [[[ m ::: (Fm * indrep_n_helper Fs bxp ir indbns) ]]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = indbns ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indput_get_blocks lxp is_alloc ir ms.\n    Proof.\n      unfold indput_get_blocks. unfold indrep_n_helper. intros.\n      hoare. destruct_lifts. auto.\n      destruct addr_eq_dec; try omega. cancel.\n      apply firstn_oob.\n      unfold IndRec.rep, IndRec.items_valid, IndSig.RALen in *.\n      destruct addr_eq_dec; destruct_lifts; autorewrite with lists; omega.\n    Qed.\n\n  Local Hint Extern 0 ({{_}} Bind (indput_get_blocks _ _ _ _) _) => apply indput_get_blocks_ok : prog.\n\n  (* This is a wrapper for IndRec.write that will use an alternate spec *)\n  Definition indrec_write_blind lxp xp items ms :=\n    IndRec.write lxp xp items ms.\n\n  (* This is an alternate spec for IndRec.write that does not require IndRec.rep\n    to hold beforehand. This allows blind writes to blocks that have not been\n    initialized beforehand with IndRec.init *)\n  Theorem indrec_write_blind_ok : forall lxp xp items ms,\n    {< F Fm m0 sm m old,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ IndRec.items_valid xp items ]] * [[ xp <> 0 ]] *\n          [[[ m ::: Fm * arrayN (@ptsto _ addr_eq_dec _) xp [old] ]]]\n    POST:hm' RET:ms exists m',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms sm hm' *\n          [[[ m' ::: Fm * IndRec.rep xp items ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} indrec_write_blind lxp xp items ms.\n  Proof.\n    unfold indrec_write_blind, IndRec.write, IndRec.rep, IndRec.items_valid.\n    hoare.\n    unfold IndSig.RAStart. instantiate (1 := [_]). cancel.\n    rewrite IndRec.Defs.ipack_one. auto.\n    unfold IndRec.Defs.item in *. simpl in *. omega.\n    rewrite vsupsyn_range_synced_list; auto.\n    rewrite IndRec.Defs.ipack_one. auto.\n    unfold IndRec.Defs.item in *. simpl in *. omega.\n  Qed.\n\n  Local Hint Extern 0 ({{_}} Bind (indrec_write_blind _ _ _ _) _) => apply indrec_write_blind_ok : prog.\n\n  Definition indput_upd_if_necessary lxp ir v indbns to_grow ms := \n    If (addr_eq_dec v #(selN indbns to_grow $0)) {\n      Ret ms\n    } else {\n      indrec_write_blind lxp ir (indbns \u27e6 to_grow := ($ v)\u27e7) ms\n    }.\n\n  Theorem indput_upd_if_necessary_ok : forall lxp ir v indbns to_grow ms,\n    {< F Fm m0 sm m bxp Fs,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[ BALLOCC.bn_valid bxp ir ]] *\n           [[[ m ::: (Fm * indrep_n_helper Fs bxp ir indbns) ]]]\n    POST:hm' RET: ms\n           exists m' indbns', \n           LOG.rep lxp F (LOG.ActiveTxn m0 m') ms sm hm' *\n           [[ indbns' = updN indbns to_grow ($ v) ]] *\n           [[[ m' ::: (Fm * indrep_n_helper Fs bxp ir indbns') ]]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indput_upd_if_necessary lxp ir v indbns to_grow ms.\n  Proof.\n    unfold indput_upd_if_necessary. unfold BALLOCC.bn_valid.\n    unfold indrec_write_blind.\n    hoare.\n    rewrite natToWord_wordToNat. rewrite updN_selN_eq. cancel.\n    unfold indrep_n_helper. destruct (addr_eq_dec ir 0); try congruence. cancel.\n    unfold indrep_n_helper. destruct (addr_eq_dec ir 0); try congruence. cancel.\n    rewrite indrep_n_helper_valid_sm in * by auto.\n    denote lift_empty as Hl. destruct_lift Hl. auto.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indput_upd_if_necessary _ _ _ _ _ _) _) => apply indput_upd_if_necessary_ok : prog.\n\n  Fixpoint indput indlvl lxp bxp root off bn ms :=\n    let N := NIndirect ^ indlvl in\n    let is_alloc := (addr_eq_dec root 0) in\n    let^ (ms, ir) <- If (is_alloc) {\n        BALLOCC.alloc lxp bxp ms\n      } else {\n        Ret ^(ms, Some root)\n      };\n    match ir with\n    | None => Ret ^(ms, 0)\n    | Some ir =>\n      match indlvl with\n      | 0 => lms <- If (is_alloc) {\n                      indrec_write_blind lxp ir ((repeat $0 NIndirect) \u27e6 off := bn \u27e7) (BALLOCC.MSLog ms)\n                   } else {\n                      IndRec.put lxp ir off bn (BALLOCC.MSLog ms)\n                   };\n        Ret ^((BALLOCC.upd_memstate lms ms), ir)\n      | S indlvl' =>\n        let to_grow := off / N in\n        let^ (lms, indbns) <- indput_get_blocks lxp is_alloc ir (BALLOCC.MSLog ms);\n        let ir_to_grow := #(selN indbns to_grow $0) in\n        let^ (ms, v) <- indput indlvl' lxp bxp ir_to_grow (off mod N) bn \n                (BALLOCC.upd_memstate lms ms);\n        If (addr_eq_dec v 0) {\n          Ret ^(ms, 0)\n        } else {\n          lms <- indput_upd_if_necessary lxp ir v indbns to_grow (BALLOCC.MSLog ms);\n          Ret ^((BALLOCC.upd_memstate lms ms), ir)\n        }\n      end\n    end.\n\n  Lemma indrep_n_helper_0_sm: forall bxp l Fs,\n    indrep_n_helper Fs bxp 0 l =p=> [[ Fs <=p=> emp ]] * indrep_n_helper Fs bxp 0 l.\n  Proof.\n    intros.\n    rewrite indrep_n_helper_0.\n    cancel.\n  Qed.\n\n  Theorem indput_ok : forall indlvl lxp bxp ir off bn ms,\n    {< F Fm Fs m0 sm m l freelist IFs,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * indrep_n_tree indlvl bxp IFs ir l *\n              BALLOCC.rep bxp freelist ms) ]]] *\n           [[ off < length l ]] *\n           [[ (Fs * IFs * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, ir')\n           exists m', LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           ([[ ir' = 0 ]] \\/\n           exists freelist' l' IFs',\n           [[ ir = 0 \\/ ir = ir' ]] *\n           [[[ m' ::: (Fm * indrep_n_tree indlvl bxp IFs' ir' l' *\n             BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ incl freelist' freelist ]] * [[ l' = updN l off bn ]] *\n           [[ (Fs * IFs' * BALLOCC.smrep freelist')%pred sm ]])\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indput indlvl lxp bxp ir off bn ms.\n    Proof.\n      induction indlvl; intros; simpl.\n      + step.\n        - hoare.\n          * unfold BALLOCC.bn_valid in *. intuition auto.\n          * unfold BALLOCC.bn_valid in *. intuition auto.\n          * or_r. norm. cancel.\n            unfold BALLOCC.bn_valid in *; intuition auto.\n            rewrite indrep_n_helper_valid by omega.\n            pred_apply.\n            rewrite indrep_n_helper_0. cancel.\n            unfold BALLOCC.bn_valid. intuition.\n            reflexivity.\n            auto.\n            rewrite indrep_n_helper_0 in *.\n            destruct_lifts.\n            psubst.\n            pred_apply. cancel.\n        - hoare.\n          * rewrite indrep_n_helper_valid by omega. cancel.\n          * or_r. cancel.\n            rewrite indrep_n_helper_valid in * by omega. cancel.\n            match goal with [H : context [?P] |- ?P] => destruct_lift H end. auto.\n            match goal with [H : context [?P] |- ?P] => destruct_lift H end. auto.\n      + step.\n        - step. prestep. norm. congruence. congruence.\n          cancel. intuition auto.\n          { rewrite repeat_selN'. pred_apply. cancel.\n            rewrite indrep_n_helper_0, indrep_n_tree_0.\n            instantiate (1 := emp). cancel.\n          }\n          { rewrite repeat_length. apply Nat.mod_bound_pos; mult_nonzero. omega. }\n          rewrite indrep_n_helper_0_sm in *.\n          match goal with H: context [lift_empty] |- _ => destruct_lift H end.\n          pred_apply; cancel.\n          (* the spec given is for updates, not blind writes *)\n          unfold indput_upd_if_necessary.\n          repeat rewrite repeat_selN'. rewrite roundTrip_0.\n          step; try solve [step].\n          step. solve [repeat step].\n          step.\n          unfold BALLOCC.bn_valid in *. intuition auto.\n          unfold BALLOCC.bn_valid in *. intuition auto.\n          prestep. cancel.\n          * or_r. norm. cancel.\n            match goal with H: context [listmatch _ (combine _ _) ?l] |- _ =>\n              assert (length l = NIndirect) by indrep_n_tree_bound end.\n            intuition auto.\n            pred_apply. norm. cancel.\n            unfold BALLOCC.bn_valid in *.\n            rewrite indrep_n_helper_valid by intuition auto.\n            cancel.\n            rewrite combine_updN.\n            match goal with |- context[updN ?l ?i_] =>\n              rewrite listmatch_isolate with (a := l) (i := i_), listmatch_updN_removeN\n            end. rewrite selN_combine. cbn [fst snd]. rewrite repeat_selN'.\n            rewrite indrep_n_tree_0.\n            rewrite wordToNat_natToWord_idempotent'. cancel.\n            rewrite indrep_n_tree_valid in * by auto.\n            destruct_lifts.\n            eauto using BALLOCC.bn_valid_goodSize.\n            all: autorewrite with lists; auto.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            cbv; auto.\n            reflexivity.\n            intuition.\n            indrep_n_tree_bound.\n            reflexivity.\n            eapply updN_concat'; auto.\n            indrep_n_tree_bound.\n            match goal with H: _ |- _ =>\n              rewrite listmatch_indrep_n_tree_empty'' in H; destruct_lift H\n            end.\n            rewrite repeat_selN; eauto.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            pred_apply; cancel.\n            psubst.\n            rewrite pred_fold_left_updN_removeN by indrep_n_tree_bound.\n            rewrite pred_fold_left_selN_removeN.\n            match goal with H: _ |- _ =>\n              rewrite indrep_n_helper_0_sm in H; destruct_lift H\n            end.\n            denote (_ <=p=> emp) as Hi. rewrite Hi; clear Hi.\n            match goal with H: context [listmatch _ (combine (repeat _ _) _)] |- _ =>\n              rewrite listmatch_isolate with (a := combine (repeat _ _) _) in H;\n              [ erewrite selN_combine in H; cbn [fst snd] in H;\n                [rewrite repeat_selN', roundTrip_0, indrep_n_tree_0 in H;\n                destruct_lift H |..] |..]\n            end.\n            denote (_ <=p=> emp) as Hi. rewrite Hi; clear Hi.\n            cancel.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n            indrep_n_tree_bound.\n          * cancel.\n          * cancel. cancel.\n        - step.\n          safestep.\n          indrep_n_extract; [cancel | try solve [indrep_n_tree_bound]..].\n          indrep_n_tree_bound.\n          match goal with |- ?a mod ?b < ?c => replace c with b; auto end.\n          symmetry. apply Forall_selN. eauto.\n          indrep_n_tree_bound.\n          psubst.\n          match goal with |- context [selN _ ?I ?d] =>\n            rewrite pred_fold_left_selN_removeN with (i := I);\n            unify d (@emp _ addr_eq_dec bool); cancel\n          end.\n          match goal with [H : context [indrep_n_helper] |- _] =>\n            pose proof H; rewrite indrep_n_helper_length_piff,\n                            indrep_n_helper_valid in H by omega;\n            destruct_lift H end.\n          hoare.\n          or_r. cancel.\n          rewrite combine_updN. rewrite listmatch_updN_removeN. cbn [fst snd].\n          rewrite wordToNat_natToWord_idempotent' by auto.\n          cancel.\n          indrep_n_tree_bound.\n          indrep_n_tree_bound.\n          autorewrite with lists; auto.\n          rewrite pred_fold_left_updN_removeN. split; cancel.\n          replace (length dummy1) with NIndirect by indrep_n_tree_bound.\n          indrep_n_tree_bound.\n          erewrite <- updN_concat.\n          rewrite plus_comm, mult_comm, <- Nat.div_mod; auto.\n          auto.\n          auto.\n          or_r. cancel.\n          rewrite combine_updN. rewrite listmatch_updN_removeN. cbn [fst snd].\n          rewrite wordToNat_natToWord_idempotent' by auto.\n          cancel.\n          indrep_n_tree_bound.\n          indrep_n_tree_bound.\n          autorewrite with lists; auto.\n          rewrite pred_fold_left_updN_removeN. split; cancel.\n          replace (length dummy1) with NIndirect by indrep_n_tree_bound.\n          indrep_n_tree_bound.\n          erewrite <- updN_concat.\n          rewrite plus_comm, mult_comm, <- Nat.div_mod; auto.\n          auto.\n          auto.\n          cancel.\n    Grab Existential Variables. all : eauto.\n        all: solve [exact nil | exact $0].\n  Qed.\n\n  Local Hint Extern 0 ({{_}} Bind (indput _ _ _ _ _ _ _) _) => apply indput_ok : prog.\n  Opaque indput.\n\n  (************** rep invariant *)\n\n  Opaque indrep_n_tree.\n\n  Definition indrep bxp Fs ir (indlist : list waddr) :=\n    (exists Fs0 Fs1 Fs2, [[ Fs <=p=> Fs0 * Fs1 * Fs2 ]] *\n      indrep_n_tree 0 bxp Fs0 (IRIndPtr ir) (firstn NIndirect indlist) *\n      indrep_n_tree 1 bxp Fs1 (IRDindPtr ir) (firstn (NIndirect ^ 2) (skipn NIndirect indlist)) *\n      indrep_n_tree 2 bxp Fs2 (IRTindPtr ir) (skipn (NIndirect + NIndirect ^ 2) indlist)\n    )%pred.\n\n  Definition rep bxp Fs (ir : irec) (l : list waddr) :=\n    ( [[ length l = (IRLen ir) /\\ length l <= NBlocks ]] *\n      [[ length (IRBlocks ir) = NDirect ]] *\n      exists indlist, indrep bxp Fs ir indlist *\n      [[ l = firstn (length l) ((IRBlocks ir) ++ indlist) ]] *\n      [[ list_same $0 (skipn (length l) ((IRBlocks ir) ++ indlist)) ]] )%pred.\n\n  Definition rep_direct bxp Fs (ir : irec) (l : list waddr) : @pred _ addr_eq_dec valuset :=\n    ( [[ length l = (IRLen ir) /\\ length l <= NBlocks /\\ length l <= NDirect ]] *\n      [[ length (IRBlocks ir) = NDirect ]] *\n      exists indlist, indrep bxp Fs ir indlist *\n      [[ l = firstn (length l) (IRBlocks ir) ]] *\n      [[ list_same $0 (skipn (length l) (IRBlocks ir)) ]] *\n      [[ list_same $0 indlist ]] )%pred.\n\n  Definition rep_indirect bxp Fs (ir : irec) (l : list waddr) :=\n    ( [[ length l = (IRLen ir) /\\ length l <= NBlocks /\\ length l > NDirect ]] *\n      [[ length (IRBlocks ir) = NDirect ]] *\n      exists indlist, indrep bxp Fs ir indlist *\n      [[ l = (IRBlocks ir) ++ firstn (length l - NDirect) indlist ]] *\n      [[ list_same $0 (skipn (length l - NDirect) indlist) ]] )%pred.\n\n\n  Hint Resolve list_same_app_l.\n  Hint Resolve list_same_app_r.\n  Hint Resolve list_same_app_both.\n\n  Lemma rep_piff_direct : forall bxp Fs ir l,\n    length l <= NDirect ->\n    rep bxp Fs ir l <=p=> rep_direct bxp Fs ir l.\n  Proof.\n    intros. unfold rep, rep_direct. split; cancel.\n    - rewrite firstn_app_l in * by omega; auto.\n    - rewrite skipn_app_l in * by omega; eauto.\n    - rewrite skipn_app_l in * by omega; eauto.\n    - substl l at 1; rewrite firstn_app_l by omega; auto.\n    - rewrite skipn_app_l by omega; eauto.\n  Qed.\n\n  Lemma rep_piff_indirect : forall bxp Fs ir l,\n    length l > NDirect ->\n    rep bxp Fs ir l <=p=> rep_indirect bxp Fs ir l.\n  Proof.\n    unfold rep, rep_indirect; intros; split; cancel; try omega.\n    - rewrite <- firstn_app_r; setoid_rewrite H3.\n      replace (NDirect + (length l - NDirect)) with (length l) by omega; auto.\n    - rewrite skipn_app_r_ge in * by omega. congruence.\n    - substl l at 1; rewrite <- firstn_app_r. setoid_rewrite H3.\n      replace (NDirect + (length l - NDirect)) with (length l) by omega; auto.\n    - rewrite skipn_app_r_ge by omega. congruence.\n  Qed.\n\n  Lemma rep_selN_direct_ok : forall F bxp Fs ir l m off,\n    (F * rep bxp Fs ir l)%pred m ->\n    off < NDirect ->\n    off < length l ->\n    selN (IRBlocks ir) off $0 = selN l off $0.\n  Proof.\n    unfold rep. intros; destruct_lift H.\n    substl.\n    rewrite selN_firstn by auto.\n    rewrite selN_app1 by omega; auto.\n  Qed.\n\n  Theorem indrep_length_pimpl : forall bxp Fs ir l,\n    indrep bxp Fs ir l <=p=> indrep bxp Fs ir l * [[ length l = NBlocks - NDirect ]].\n  Proof.\n    intros.\n    unfold indrep.\n    split; [> | cancel].\n    intros m' H'. pred_apply. cancel.\n    destruct_lift H'.\n    repeat rewrite <- plus_assoc. rewrite minus_plus.\n    indrep_n_tree_extract_lengths.\n    erewrite <- firstn_skipn with (l := l). rewrite app_length. f_equal; eauto.\n    erewrite <- firstn_skipn with (l := skipn _ _). rewrite app_length.\n    f_equal; eauto. rewrite skipn_skipn'. auto.\n  Qed.\n\n  Theorem indrep_bxp_switch : forall bxp bxp' Fs xp ilist,\n    BmapNBlocks bxp = BmapNBlocks bxp' ->\n    indrep bxp Fs xp ilist <=p=> indrep bxp' Fs xp ilist.\n  Proof.\n    intros. unfold indrep.\n    split; norm; intuition eauto; cbv [pred_fold_left stars fold_left].\n    repeat match goal with [|- context [indrep_n_tree ?i] ] =>\n      rewrite indrep_n_tree_bxp_switch with (indlvl := i) by eassumption\n    end. cancel.\n    repeat match goal with [|- context [indrep_n_tree ?i] ] =>\n      rewrite indrep_n_tree_bxp_switch with (indlvl := i) by (symmetry; eassumption)\n    end. cancel.\n  Qed.\n\n  Theorem indrep_0 : forall bxp Fs ir l,\n    IRIndPtr ir = 0 -> IRDindPtr ir = 0 -> IRTindPtr ir = 0 ->\n    indrep bxp Fs ir l <=p=> [[l = repeat $0 (NBlocks - NDirect)]] * [[ Fs <=p=> emp ]].\n  Proof.\n    unfold indrep. intros.\n    repeat match goal with [H : _ = 0 |- _] => rewrite H end.\n    repeat rewrite indrep_n_tree_0. simpl.\n    repeat rewrite <- plus_assoc. rewrite minus_plus.\n    rewrite mult_1_r in *.\n    setoid_rewrite indrep_n_tree_0.\n    split; norm; psubst; try cancel;\n      rewrite Nat.mul_1_r in *; intuition eauto.\n    erewrite <- firstn_skipn with (l := l).\n    erewrite <- firstn_skipn with (l := skipn _ l).\n    rewrite skipn_skipn'.\n    repeat rewrite <- repeat_app.\n    repeat (f_equal; eauto).\n    split; cancel.\n    split; cancel.\n    all : repeat rewrite skipn_repeat;\n          repeat rewrite firstn_repeat by lia; f_equal; lia.\n  Qed.\n\n\n  Lemma rep_keep_blocks : forall bxp Fs ir ir' l,\n    IRIndPtr ir = IRIndPtr ir' ->\n    IRDindPtr ir = IRDindPtr ir' ->\n    IRTindPtr ir = IRTindPtr ir' ->\n    IRLen ir = IRLen ir' ->\n    IRBlocks ir = IRBlocks ir' ->\n    rep bxp Fs ir l =p=> rep bxp Fs ir' l.\n  Proof.\n    intros.\n    unfold rep, indrep.\n    repeat match goal with H : _ = _ |- _ =>\n      rewrite H in *; clear H\n    end.\n    reflexivity.\n  Qed.\n\n  Theorem rep_bxp_switch : forall bxp bxp' Fs xp ilist,\n    BmapNBlocks bxp = BmapNBlocks bxp' ->\n    rep bxp Fs xp ilist <=p=> rep bxp' Fs xp ilist.\n  Proof.\n    intros. unfold rep.\n    split; norm; intuition eauto; cbv [pred_fold_left stars fold_left].\n    all: rewrite indrep_bxp_switch.\n    all: try cancel.\n    all: eauto.\n  Qed.\n\n\n  Theorem xform_indrep : forall xp Fs ir l,\n    crash_xform (indrep xp Fs ir l) <=p=> indrep xp Fs ir l.\n  Proof.\n    unfold indrep. intros.\n    split; xform_norm.\n    repeat rewrite xform_indrep_n_tree.\n    cancel.\n    cancel. xform_norm.\n    cancel. xform_norm.\n    cancel. xform_norm.\n    repeat rewrite xform_indrep_n_tree.\n    cancel; eauto.\n  Qed.\n\n  (************* program *)\n\n  Definition get lxp (ir : irec) off ms :=\n    If (lt_dec off NDirect) {\n      Ret ^(ms, selN (IRBlocks ir) off $0)\n    } else {\n      let off := off - NDirect in\n      If (lt_dec off NIndirect) {\n        indget 0 lxp (IRIndPtr ir) off ms\n      } else {\n        let off := off - NIndirect in\n        If (lt_dec off (NIndirect ^ 2)) {\n          indget 1 lxp (IRDindPtr ir) off ms\n        } else {\n          let off := off - NIndirect ^ 2 in\n          indget 2 lxp (IRTindPtr ir) off ms\n        }\n      }\n    }.\n\n  Definition read lxp (ir : irec) ms :=\n    If (le_dec (IRLen ir) NDirect) {\n      Ret ^(ms, firstn (IRLen ir) (IRBlocks ir))\n    } else {\n      let^ (ms, indbns) <- indread 0 lxp (IRIndPtr ir) ms;\n      let^ (ms, dindbns) <- indread 1 lxp (IRDindPtr ir) ms;\n      let^ (ms, tindbns) <- indread 2 lxp (IRTindPtr ir) ms;\n      Ret ^(ms, (firstn (IRLen ir) ((IRBlocks ir) ++ indbns ++ dindbns ++ tindbns)))\n    }.\n\n  Definition indread_range_helper indlvl lxp bn start len ms :=\n    let localstart := fold_left plus (map (fun i => NIndirect ^ S i) (seq 0 indlvl)) 0 in\n    let maxlen := NIndirect ^ S indlvl in\n    If (lt_dec localstart (start + len)) {\n      If (lt_dec start (localstart + maxlen)) {\n        let start' := start - localstart in\n        let len' := len - (localstart - start) in\n        let len'' := Nat.min len' (maxlen - start') in\n        indread_range indlvl lxp bn start' len'' ms\n      } else {\n        Ret ^(ms, nil)\n      }\n    } else {\n      Ret ^(ms, nil)\n    }.\n\n  Definition read_range lxp ir start len ms :=\n    rdir <- Ret (firstn len (skipn start (IRBlocks ir)));\n    let len := len - (NDirect - start) in\n    let start := start - NDirect in\n    let^ (ms, rind) <- indread_range_helper 0 lxp (IRIndPtr ir) start len ms;\n    let^ (ms, rdind) <- indread_range_helper 1 lxp (IRDindPtr ir) start len ms;\n    let^ (ms, rtind) <- indread_range_helper 2 lxp (IRTindPtr ir) start len ms;\n    Ret ^(ms, rdir ++ rind ++ rdind ++ rtind).\n\n  Definition indshrink_helper indlvl lxp bxp bn nl ms :=\n    let start := fold_left plus (map (fun i => NIndirect ^ S i) (seq 0 indlvl)) 0 in\n    let len := NIndirect ^ S indlvl in\n    If (lt_dec nl (start + len)) {\n      indclear indlvl lxp bxp bn (nl - start) (len - (nl - start)) ms\n    } else {\n      Ret ^(ms, bn)\n    }.\n\n  Definition indshrink lxp bxp ir nl ms :=\n    let^ (ms, indptr)  <- indshrink_helper 0 lxp bxp (IRIndPtr ir)  nl ms;\n    let^ (ms, dindptr) <- indshrink_helper 1 lxp bxp (IRDindPtr ir) nl ms;\n    let^ (ms, tindptr) <- indshrink_helper 2 lxp bxp (IRTindPtr ir) nl ms;\n    Ret ^(ms, indptr, dindptr, tindptr).\n\n  Definition shrink lxp bxp (ir : irec) nr ms :=\n    let ol := (IRLen ir) in\n    let nl := (ol - nr) in\n    If (le_dec ol NDirect) {\n      Ret ^(ms, upd_irec ir nl (IRIndPtr ir) (IRDindPtr ir) (IRTindPtr ir)\n                         (upd_range_fast (IRBlocks ir) nl (NDirect - nl) $0))\n    } else {\n      let ol' := ol - NDirect in\n      let nl' := nl - NDirect in\n      let^ (ms, indptr, dindptr, tindptr) <- indshrink lxp bxp ir nl' ms;\n      Ret ^(ms, upd_irec ir nl indptr dindptr tindptr\n                         (upd_range_fast (IRBlocks ir) nl (NDirect - nl) $0))\n    }.\n\n  Definition indgrow lxp bxp ir off bn ms :=\n    If (lt_dec off NIndirect) {\n      let^ (ms, v) <- indput 0 lxp bxp (IRIndPtr ir) off bn ms;\n      Ret ^(ms, v, v, (IRDindPtr ir), (IRTindPtr ir))\n    } else {\n      let off := off - NIndirect in\n      If (lt_dec off (NIndirect ^ 2)) {\n        let^ (ms, v) <- indput 1 lxp bxp (IRDindPtr ir) off bn ms;\n        Ret ^(ms, v, (IRIndPtr ir), v, (IRTindPtr ir))\n      } else {\n        let off := off - NIndirect ^ 2 in\n        let^ (ms, v) <- indput 2 lxp bxp (IRTindPtr ir) off bn ms;\n        Ret ^(ms, v, (IRIndPtr ir), (IRDindPtr ir), v)\n      }\n    }.\n\n  Definition grow lxp bxp (ir : irec) bn ms :=\n    let len := (IRLen ir) in\n    If (lt_dec len NDirect) {\n      (* change direct block address *)\n      Ret ^(ms, OK (upd_irec ir (S len) (IRIndPtr ir) (IRDindPtr ir) (IRTindPtr ir) (updN (IRBlocks ir) len bn)))\n    } else {\n      let off := (len - NDirect) in\n      If (waddr_eq_dec bn $0) {\n        Ret ^(ms, OK (upd_len ir (S len)))\n      } else {\n        let^ (ms, v, indptr, dindptr, tindptr) <- indgrow lxp bxp ir off bn ms;\n        If (addr_eq_dec v 0) {\n          Ret ^(ms, Err ENOSPCBLOCK)\n        } else {\n          Ret ^(ms, OK (upd_irec ir (S len) indptr dindptr tindptr (IRBlocks ir)))\n        }\n      }\n    }.\n\n  Theorem get_ok : forall lxp bxp ir off ms,\n    {< F Fm IFs m0 sm m l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * rep bxp IFs ir l ]]] *\n           [[ off < length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = selN l off $0 ]]\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} get lxp ir off ms.\n  Proof.\n    unfold get.\n    step.\n    step.\n    eapply rep_selN_direct_ok; eauto.\n    prestep; norml.\n    rewrite rep_piff_indirect in * by omega.\n    unfold rep_indirect, indrep in *. destruct_lifts.\n    indrep_n_tree_extract_lengths.\n    hoare.\n    all : substl l.\n    all : repeat rewrite selN_app2 by omega.\n    all : repeat rewrite selN_firstn by omega.\n    all : repeat rewrite skipn_selN.\n    all : repeat (congruence || omega || f_equal).\n  Qed.\n\n  Theorem read_ok : forall lxp bxp ir ms,\n    {< F Fm IFs m0 sm m l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * rep bxp IFs ir l ]]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = l ]]\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} read lxp ir ms.\n  Proof.\n    unfold read.\n    step; denote rep as Hx.\n    step.\n    rewrite rep_piff_direct in Hx; unfold rep_direct in Hx; destruct_lift Hx.\n    substl; substl (length l); auto.\n    unfold rep in H; destruct_lift H; omega.\n\n    unfold rep, indrep in Hx. destruct_lifts.\n    indrep_n_tree_extract_lengths.\n    hoare.\n    rewrite app_assoc with (l := firstn _ _).\n    rewrite <- firstn_sum_split. rewrite firstn_skipn.\n    congruence.\n  Qed.\n\n  Theorem indread_range_helper_ok : forall lxp bn indlvl start len ms,\n    let localstart := fold_left plus (map (fun i => NIndirect ^ S i) (seq 0 indlvl)) 0 in\n    {< F Fm IFs m0 sm m l bxp,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: (Fm * indrep_n_tree indlvl bxp IFs bn l) ]]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           let len' := (len - (localstart - start)) in\n           [[ r = firstn len' (skipn (start - localstart) l) ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indread_range_helper indlvl lxp bn start len ms.\n  Proof.\n    unfold indread_range_helper.\n    step; indrep_n_tree_extract_lengths; hoare.\n    match goal with H : length l = _ |- _ => setoid_rewrite <- H end.\n    let H := fresh in\n    edestruct Min.min_spec as [ [? H]|[? H] ]; rewrite H; clear H.\n    reflexivity.\n    rewrite firstn_oob.\n    rewrite firstn_oob; auto.\n    autorewrite with core.\n    omega.\n    autorewrite with core.\n    omega.\n    rewrite skipn_oob, firstn_nil by omega. auto.\n    rewrite sub_le_eq_0 by omega.\n    auto.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indread_range_helper _ _ _ _ _ _ ) _) => apply indread_range_helper_ok : prog.\n\n(*\n  Theorem read_range_ok : forall lxp bxp ir start len ms,\n    {< F Fm IFs m0 sm m l,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n           [[[ m ::: Fm * rep bxp IFs ir l ]]] *\n           [[ start + len <= length l ]]\n    POST:hm' RET:^(ms, r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm' *\n           [[ r = firstn len (skipn start l) ]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} read_range lxp ir start len ms.\n  Proof.\n    unfold read_range, rep, indrep.\n    hoare.\n    autorewrite with core.\n    substl l.\n    match goal with H: context [firstn NIndirect ?l] |- _ =>\n      rename l into ind\n    end.\n    rewrite firstn_app.\n    rewrite skipn_app_split.\n    rewrite firstn_app.\n    f_equal.\n    rewrite firstn_double_skipn by omega; auto.\n    (* TODO finish proving this and use read_range to implement BFILE.shrink *)\n  Abort.\n*)\n\n  Lemma indrec_ptsto_pimpl : forall ibn indrec,\n    IndRec.rep ibn indrec =p=> exists v, ibn |-> (v, nil).\n  Proof.\n    unfold IndRec.rep; cancel.\n    assert (length (synced_list (IndRec.Defs.ipack indrec)) = 1).\n    unfold IndRec.items_valid in H2; intuition.\n    rewrite synced_list_length; subst.\n    rewrite IndRec.Defs.ipack_length.\n    setoid_rewrite H0.\n    rewrite Rounding.divup_mul; auto.\n\n    rewrite arrayN_isolate with (i := 0) by omega.\n    unfold IndSig.RAStart; rewrite Nat.add_0_r.\n    rewrite skipn_oob by omega; simpl.\n    instantiate (2 := ($0, nil)).\n    rewrite synced_list_selN; cancel.\n  Qed.\n\n  Hint Rewrite cuttail_length : core.\n  Hint Rewrite upd_len_get_len upd_len_get_ind upd_len_get_dind upd_len_get_tind upd_len_get_blk upd_len_get_iattr : core.\n  Hint Rewrite upd_irec_get_len upd_irec_get_ind upd_irec_get_dind upd_irec_get_tind upd_irec_get_blk upd_irec_get_iattr : core.\n  Local Hint Resolve upd_len_get_iattr upd_irec_get_iattr.\n\n  Theorem upd_len_indrep : forall bxp Fs ir l n,\n    indrep bxp Fs ir l <=p=> indrep bxp Fs (upd_len ir n) l.\n  Proof.\n    intros.\n    unfold indrep. autorewrite with core. auto.\n  Qed.\n\n  Theorem upd_len_direct_indrep : forall bxp Fs ir l n b,\n    indrep bxp Fs ir l <=p=> indrep bxp Fs (upd_irec ir n (IRIndPtr ir) (IRDindPtr ir) (IRTindPtr ir) b) l.\n  Proof.\n    intros.\n    unfold indrep. autorewrite with core. auto.\n    all: eauto using get_ind_goodSize, get_dind_goodSize, get_tind_goodSize.\n  Qed.\n\n  Theorem indshrink_helper_ok : forall lxp bxp bn nl indlvl ms,\n    let start := fold_left plus (map (fun i => NIndirect ^ S i) (seq 0 indlvl)) 0 in\n    {< F Fm Fs IFs m0 sm m l freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * indrep_n_tree indlvl bxp IFs bn l * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFs * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, r)  exists m' freelist' IFs' l',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * indrep_n_tree indlvl bxp IFs' r l' * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ l' = upd_range l (nl - start) (length l - (nl - start)) $0 ]] *\n           [[ (Fs * IFs' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ incl freelist freelist' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indshrink_helper indlvl lxp bxp bn nl ms.\n  Proof.\n    unfold indshrink_helper.\n    prestep. norml.\n    indrep_n_tree_extract_lengths.\n    hoare.\n    replace (_ - (_ - _)) with 0 by omega. rewrite upd_range_0. auto.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indshrink_helper _ _ _ _ _ _ ) _) => apply indshrink_helper_ok : prog.\n\n  Theorem indshrink_ok : forall lxp bxp ir nl ms,\n    {< F Fm Fs IFs0 IFs1 IFs2 m0 sm m l0 l1 l2 freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[ nl <= length (l0 ++ l1 ++ l2) ]] *\n           [[[ m ::: (Fm * indrep_n_tree 0 bxp IFs0 (IRIndPtr ir) l0 *\n                           indrep_n_tree 1 bxp IFs1 (IRDindPtr ir) l1 *\n                           indrep_n_tree 2 bxp IFs2 (IRTindPtr ir) l2 *\n                           BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFs0 * IFs1 * IFs2 * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, indptr', dindptr', tindptr')\n           exists m' freelist' l0' l1' l2' IFs0' IFs1' IFs2',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * indrep_n_tree 0 bxp IFs0' indptr' l0' *\n                            indrep_n_tree 1 bxp IFs1' dindptr' l1' *\n                            indrep_n_tree 2 bxp IFs2' tindptr' l2' * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ l0' ++ l1' ++ l2' = upd_range (l0 ++ l1 ++ l2) nl (length (l0 ++ l1 ++ l2) - nl) $0 ]] *\n           [[ (Fs * IFs0' * IFs1' * IFs2' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ incl freelist freelist' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indshrink lxp bxp ir nl ms.\n  Proof.\n    unfold indshrink.\n    hoare.\n    repeat rewrite app_length in *.\n    indrep_n_tree_extract_lengths.\n    autorewrite with core.\n    repeat rewrite upd_range_eq_app_firstn_repeat by (repeat rewrite app_length; omega).\n    destruct (le_dec nl NIndirect);\n    destruct (le_dec nl (NIndirect + NIndirect * NIndirect)); try omega.\n    all : repeat match goal with\n      | [|- context [?a - ?b] ] => replace (a - b) with 0 by omega\n      | [|- context [firstn ?x ?l'] ] => rewrite firstn_oob with (n := x) (l := l') by omega\n      | [|- context [firstn ?x ?l'] ] => rewrite firstn_app_le with (n := x) by omega\n      | [|- context [firstn ?x ?l'] ] => rewrite firstn_app_l with (n := x) by omega\n    end; repeat rewrite <- app_assoc; simpl; autorewrite with core; repeat rewrite repeat_app.\n    all : repeat rewrite app_length; solve [repeat (omega || f_equal)].\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indshrink _ _ _ _ _) _) => apply indshrink_ok : prog.\n\n  Theorem shrink_ok : forall lxp bxp ir nr ms,\n    {< F Fm Fs IFs m0 sm m l freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[[ m ::: (Fm * rep bxp IFs ir l * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFs * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, r)  exists m' freelist' l' IFs',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * rep bxp IFs' r l' * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ (Fs * IFs' * BALLOCC.smrep freelist')%pred sm ]] *\n           exists ind dind tind dirl, [[ r = upd_irec ir ((IRLen ir) - nr) ind dind tind dirl ]] *\n           [[ l' = firstn (IRLen ir - nr) l ]] *\n           [[ incl freelist freelist' ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} shrink lxp bxp ir nr ms.\n  Proof.\n    unfold shrink. intros.\n    repeat rewrite upd_range_fast_eq.\n    prestep; norml.\n    denote rep as Hx. unfold rep in Hx. destruct_lifts.\n    cancel.\n    + (* case 1: all in direct blocks *)\n      step. unfold rep.\n      autorewrite with core. cancel.\n      - apply upd_len_direct_indrep.\n      - rewrite upd_range_length; eauto.\n      - rewrite min_l by omega.\n        substl l at 1. rewrite firstn_firstn, min_l by omega.\n        rewrite firstn_app_l by omega.\n        rewrite firstn_app_l by ( rewrite upd_range_length; omega ).\n        rewrite firstn_upd_range by omega.\n        reflexivity.\n      - rewrite min_l by omega.\n        rewrite skipn_app_l by ( rewrite upd_range_length; omega ).\n        rewrite skipn_app_l in * by omega.\n        eapply list_same_app_both; eauto.\n        rewrite upd_range_eq_upd_range' by omega; unfold upd_range'.\n        rewrite skipn_app_r_ge by ( rewrite firstn_length; rewrite min_l by omega; auto ).\n        eapply list_same_skipn.\n        eapply list_same_app_both; try apply list_same_repeat.\n        eapply list_same_skipn_ge.\n        2: denote list_same as Hls; apply list_same_app_l in Hls; eauto.\n        omega.\n      - apply le_ndirect_goodSize. omega.\n    + (* case 2 : indirect blocks *)\n      unfold indrep in *.\n      destruct_lift Hx.\n      hoare.\n      - repeat rewrite app_length.\n        indrep_n_tree_extract_lengths. omega.\n      - psubst. cancel.\n      - unfold rep, indrep. autorewrite with core; auto.\n        cancel; rewrite mult_1_r in *.\n        rewrite indrep_n_length_pimpl with (indlvl := 0).\n        rewrite indrep_n_length_pimpl with (indlvl := 1).\n        rewrite indrep_n_length_pimpl with (indlvl := 2). cancel. rewrite mult_1_r in *.\n        substl (NIndirect * NIndirect). substl NIndirect.\n        rewrite firstn_app2. rewrite skipn_app_r. repeat rewrite skipn_app. rewrite firstn_app2.\n        cancel.\n        all : try rewrite upd_range_length.\n        all : eauto.\n        all : rewrite ?min_l by omega; try omega.\n        all : indrep_n_tree_extract_lengths.\n        substl l.\n        rewrite firstn_firstn, min_l by omega.\n        destruct (le_dec (IRLen ir - nr) NDirect).\n        {\n          rewrite firstn_app_l by omega.\n          rewrite firstn_app_l by ( rewrite upd_range_length; omega ).\n          rewrite firstn_upd_range by omega.\n          auto.\n        }\n        {\n          rewrite not_le_minus_0 with (n := NDirect) by omega.\n          rewrite upd_range_0.\n\n          match goal with [H : _ ++ _ = _ |- _] => rewrite H end.\n          repeat rewrite firstn_app_split. f_equal.\n          rewrite firstn_upd_range by (repeat rewrite app_length; omega). f_equal.\n          rewrite <- skipn_skipn'.\n          repeat match goal with [|- ?x = _] =>\n            erewrite <- firstn_skipn with (l := x) at 1; f_equal end.\n        }\n        match goal with [H : _ ++ _ = _ |- _] => rewrite H end.\n        destruct (le_dec (IRLen ir - nr) NDirect).\n        {\n          rewrite skipn_app_l by ( rewrite upd_range_length; omega ).\n          apply list_same_app_both.\n\n          eapply list_same_skipn_upd_range_mid; [ | omega ].\n          replace (IRLen ir - nr + (NDirect - (IRLen ir - nr))) with NDirect by omega.\n          rewrite skipn_oob by omega. constructor.\n\n          replace (IRLen ir - nr - NDirect) with 0 by omega.\n          rewrite upd_range_eq_upd_range' by omega; unfold upd_range'; simpl.\n          eapply list_same_app_both.\n          eapply list_same_repeat.\n\n          rewrite skipn_oob; [ constructor | ].\n          omega.\n        }\n        {\n          replace (NDirect - (IRLen ir - nr)) with 0 by omega; rewrite upd_range_0.\n          denote list_same as Hls.\n          rewrite skipn_app_r_ge by omega.\n          rewrite skipn_app_r_ge in Hls by omega.\n          replace (length (IRBlocks ir)) with (NDirect) by omega.\n          eapply list_same_skipn_upd_range_tail.\n        }\n        apply le_nblocks_goodSize. simpl. rewrite mult_1_r. omega.\n      - cancel.\n    Grab Existential Variables.\n    all: eauto.\n  Qed.\n\n  Theorem indgrow_ok : forall lxp bxp ir off bn ms,\n    {< F Fm Fs m0 sm m l0 l1 l2 freelist IFs0 IFs1 IFs2,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[ off < NBlocks - NDirect ]] * [[ bn <> $0 ]] *\n           [[[ m ::: (Fm * indrep_n_tree 0 bxp IFs0 (IRIndPtr ir) l0 *\n                           indrep_n_tree 1 bxp IFs1 (IRDindPtr ir) l1 *\n                           indrep_n_tree 2 bxp IFs2 (IRTindPtr ir) l2 * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFs0 * IFs1 * IFs2 * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, v, indptr', dindptr', tindptr')\n           exists m', LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           ([[ v = 0 ]] \\/ [[ v <> 0 ]] *\n           exists freelist' l0' l1' l2' IFs0' IFs1' IFs2',\n           [[ updN (l0 ++ l1 ++ l2) off bn = l0' ++ l1' ++ l2' ]] *\n           [[[ m' ::: (Fm * indrep_n_tree 0 bxp IFs0' indptr' l0' *\n                            indrep_n_tree 1 bxp IFs1' dindptr' l1' *\n                            indrep_n_tree 2 bxp IFs2' tindptr' l2' * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ (Fs * IFs0' * IFs1' * IFs2' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ incl freelist' freelist ]])\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} indgrow lxp bxp ir off bn ms.\n  Proof.\n    unfold indgrow. prestep. norml.\n    indrep_n_tree_extract_lengths.\n    hoare.\n    all: match goal with |- context [?a = 0] =>\n      destruct (addr_eq_dec a 0); [or_l|or_r]; cancel\n    end.\n    all : match goal with\n          | [|- _ = _ ] =>\n            repeat rewrite updN_app2 by omega; try rewrite updN_app1 by omega; congruence\n          | [H : ?bn = $ 0 -> False, H2 : ?a = 0 |- False ] =>\n              rewrite H2 in *; rewrite indrep_n_tree_0 in *; destruct_lifts;\n              apply H; eapply repeat_eq_updN; [> | eauto];\n              rewrite mult_1_r; omega\n          end.\n  Qed.\n\n  Local Hint Extern 1 ({{_}} Bind (indgrow _ _ _ _ _ _) _) => apply indgrow_ok : prog.\n\n  Theorem grow_ok : forall lxp bxp ir bn ms,\n    {< F Fm Fs m0 sm m IFs l freelist,\n    PRE:hm\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (BALLOCC.MSLog ms) sm hm *\n           [[ length l < NBlocks ]] *\n           [[[ m ::: (Fm * rep bxp IFs ir l * BALLOCC.rep bxp freelist ms) ]]] *\n           [[ (Fs * IFs * BALLOCC.smrep freelist)%pred sm ]]\n    POST:hm' RET:^(ms, r)\n           exists m',\n           [[ isError r ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' \\/\n           exists freelist' ir' IFs',\n           [[ r = OK ir' ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (BALLOCC.MSLog ms) sm hm' *\n           [[[ m' ::: (Fm * rep bxp IFs' ir' (l ++ [bn]) * BALLOCC.rep bxp freelist' ms) ]]] *\n           [[ IRAttrs ir' = IRAttrs ir /\\ length (IRBlocks ir') = length (IRBlocks ir) ]] *\n           [[ (Fs * IFs' * BALLOCC.smrep freelist')%pred sm ]] *\n           [[ incl freelist' freelist ]]\n    CRASH:hm'  LOG.intact lxp F m0 sm hm'\n    >} grow lxp bxp ir bn ms.\n  Proof.\n    unfold grow.\n    prestep; norml.\n    assert (length l = (IRLen ir)); denote rep as Hx.\n    unfold rep in Hx; destruct_lift Hx; omega.\n    cancel.\n\n    (* only update direct block *)\n    prestep; norml.\n    rewrite rep_piff_direct in Hx by omega.\n    unfold rep_direct in Hx; destruct_lift Hx.\n    cancel.\n    or_r; cancel.\n    rewrite rep_piff_direct by (autorewrite with lists; simpl; omega).\n    unfold rep_direct; autorewrite with core lists; simpl.\n    cancel; try omega.\n    unfold indrep.\n    intros m' H'. destruct_lift H'. pred_apply. autorewrite with core. cancel.\n    all : auto.\n    substl l at 1. substl (length l).\n    apply firstn_app_updN_eq; omega.\n    rewrite skipN_updN' by omega.\n    eapply list_same_skipn_ge; try eassumption. omega.\n    autorewrite with core lists; auto.\n\n    (* update indirect blocks *)\n    step.\n    + (* write 0 block *)\n      unfold rep in *. destruct_lift Hx.\n      rewrite indrep_length_pimpl in *. unfold indrep in *. destruct_lifts.\n      indrep_n_tree_extract_lengths.\n      hoare.\n      rewrite <- skipn_skipn' in *. repeat rewrite firstn_skipn in *.\n      indrep_n_tree_extract_lengths.\n      or_r; cancel; autorewrite with core; (cancel || auto).\n      rewrite <- skipn_skipn'.\n      cancel.\n      all : try rewrite app_length; simpl; try omega.\n      - apply le_nblocks_goodSize. simpl. rewrite mult_1_r. omega.\n      - eauto.\n      - substl l at 1.\n        rewrite plus_comm.\n        repeat match goal with [|- context [firstn ?a (?b ++ ?c)] ] =>\n          rewrite firstn_app_split with (l1 := b); rewrite firstn_oob with (l := b) by omega\n        end. rewrite <- app_assoc. f_equal.\n        replace (1 + length l - length (IRBlocks ir)) with ((length l - length (IRBlocks ir)) + 1) by omega.\n        erewrite firstn_plusone_selN by omega. f_equal. f_equal.\n        denote list_same as Hls. rewrite skipn_app_r_ge in Hls by omega.\n        eapply list_same_skipn_selN; eauto; omega.\n      - eapply list_same_skipn_ge; [ | eassumption ]. omega.\n    + (* write nonzero block *)\n      unfold rep in *. destruct_lift Hx.\n      rewrite indrep_length_pimpl in *. unfold indrep in *. destruct_lifts.\n      indrep_n_tree_extract_lengths.\n      hoare.\n      - psubst; cancel.\n      - rewrite <- skipn_skipn' in *. repeat rewrite firstn_skipn in *.\n        indrep_n_tree_extract_lengths.\n        or_r. cancel; autorewrite with core.\n        rewrite <- skipn_skipn'.\n        rewrite firstn_app2. rewrite skipn_app_l. rewrite skipn_oob. rewrite app_nil_l.\n        rewrite firstn_app2. rewrite skipn_app_l. rewrite skipn_oob. rewrite app_nil_l.\n        (* `cancel` calls `simpl` which raises a Not_found exception here; don't know why *)\n        norm; intuition cancel.\n        all : repeat rewrite app_length; try solve [auto | simpl; omega].\n       -- apply le_nblocks_goodSize. simpl. rewrite mult_1_r. omega.\n       -- split; cancel.\n       -- substl l at 1. cbn.\n          match goal with [H : updN _ _ _ = _ |- _] => rewrite <- H end.\n          rewrite plus_comm. erewrite firstn_S_selN.\n          repeat rewrite firstn_app_le by omega.\n          rewrite firstn_updN_oob by omega. rewrite selN_app2 by omega.\n          erewrite eq_trans with (x := _ - _); [> | reflexivity |].\n          rewrite selN_updN_eq by omega. reflexivity.\n          all : try rewrite app_length, length_updN; omega.\n       -- cbn.\n          match goal with [H : updN _ _ _ = _ |- _] => rewrite <- H end.\n          denote list_same as Hls. rewrite skipn_app_r_ge in Hls by omega.\n          rewrite skipn_app_r_ge by omega.\n          rewrite skipN_updN' by omega.\n          eapply list_same_skipn_ge; [ | eassumption ]. omega.\n    Grab Existential Variables.\n    all : eauto; exact $0.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (get _ _ _ _) _) => apply get_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read _ _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (shrink _ _ _ _ _) _) => apply shrink_ok : prog.\n  Hint Extern 1 ({{_}} Bind (grow _ _ _ _ _) _) => apply grow_ok : prog.\n\n  Hint Extern 0 (okToUnify (rep _ _ _ _) (rep _ _ _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (@selN (@pred _ _ bool) ?l _ _) (@selN (@pred _ _ bool) ?l _ _)) => constructor : okToUnify.\n\n  Lemma rep_IFs_sync_invariant: forall bxp IFs ir iblocks m F,\n    (F * rep bxp IFs ir iblocks)%pred m ->\n    sm_sync_invariant IFs.\n  Proof.\n    unfold rep, indrep.\n    intros.\n    destruct_lifts.\n    eapply sm_sync_invariant_piff; eauto.\n    repeat eapply sm_sync_invariant_sep_star;\n      eapply indrep_n_tree_sm_sync_invariant with (m := m).\n    all: pred_apply; cancel.\n  Qed.\n\n  Theorem xform_rep : forall xp Fs ir l,\n    crash_xform (rep xp Fs ir l) <=p=> rep xp Fs ir l.\n  Proof.\n    unfold rep; intros; split.\n    xform_norm.\n    rewrite xform_indrep.\n    cancel; eauto.\n\n    cancel.\n    xform_normr.\n    rewrite crash_xform_exists_comm; cancel.\n    xform_normr.\n    rewrite xform_indrep.\n    cancel; eauto.\n  Qed.\n\nEnd BlockPtr.\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/BlockPtr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.19056182356311965}}
{"text": "Require Import GenericVerifierIface.\nRequire Import GenericVerifier.\nRequire Import ClassDatatypesIface.\nRequire Import ILLInterfaces.\nRequire Import BasicMachineTypes.\nRequire Import OptionMonad.\nRequire Import OptionExt.\nRequire Import ClasspoolIface.\nRequire Import CertRuntimeTypesIface.\nRequire Import List.\nRequire Import Execution.\nRequire Import ResInstructionVerifier.\nRequire Import Certificates.\n\nModule ResourceVerifier\n        (B : BASICS)\n        (SYN : ILL_SYNTAX with Module SYN.B := B)\n        (CERT : CERTIFICATE with Definition asn := SYN.SYN.formula)\n        (ANN : ILLANNOTATIONS with Module B:= B with Module SYN := SYN with Module CERT := CERT)\n        (RA : RESOURCE_ALGEBRA with Module B := B)\n        (C : CLASSDATATYPES with Module B := B with Module A := ANN)\n        (CP : CLASSPOOL with Module B := B with Module C := C)\n        (RT : CERTRUNTIMETYPES with Module B := B with Module C := C with Module CP := CP)\n        (RSEM : ILL_SEMANTICS with Module RA := RA with Module SYN := SYN).\n\nModule E := Execution.Execution B RA C CP RT.\n\nModule RIV := ResInstructionVerifier.ResInstructionVerifier B SYN CERT C.\n\nModule RCV := MkCodeVerifier B SYN CERT ANN C RIV.\n\nImport SYN.\nImport CERT.\nImport RCV.\nImport RSEM.\nImport RA.\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/ResourceVerifier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.19051553723801348}}
{"text": "\nRequire Import RelationClasses.\nRequire Import List.\nRequire Import Basics.\nRequire Import Coqlib.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import DenseOrder.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\n\nRequire Import Memory.\nRequire Import Cell.\nRequire Import Time.\nRequire Import Thread.\nRequire Import Local.\nRequire Import CompAuxDef.\n\nRequire Import Kildall.\nRequire Import AveAnalysis.\nRequire Import CorrectOpt.\nRequire Import MsgMapping.\nRequire Import CSE.\nRequire Import LocalSim.\nRequire Import LibTactics.\nRequire Import Event.\nRequire Import View.\nRequire Import TView.\n\nRequire Import CSEProofAux.\nRequire Import CSEProofMState.\n\n(** Correctness for individual steps *)\n\n(** Match State implies Framework's Step Invariant*)\nTheorem cse_match_state_implies_si:\nforall inj lo (st_tgt st_src: Language.state rtl_lang) \n              (lc_tgt lc_src: Local.t) \n              (mem_tgt mem_src: Memory.t) \n              sc_tgt sc_src \n              b,\n  cse_match_state inj lo \n    (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b -> \n  @SI rtl_lang nat inj lo (st_tgt, lc_tgt, mem_tgt) (st_src, lc_src, mem_src) DelaySet.dset_init.\nProof.\n    intros.\n    inv H. \n    inv INVARIANT.\n    inv MATCH_LOCAL.\n    destruct lc_tgt as (tview_tgt, prm_tgt) eqn:EqLcTgt.\n    destruct lc_src as (tview_src, prm_src) eqn:EqLcSrc.    \n\n    eapply SI_intro; simpls; eauto.\n    3: {\n    destruct H0. unfolds Mem_at_eq.\n    intros. rewrite H0. unfolds Mem_approxEq_loc. tauto.  \n    }\n    {\n    (* SI.a: mapping *)\n    intros.\n    destruct H0.  \n    destruct PREEMPT.\n    { \n        unfolds eq_ident_mapping.\n        destruct H3.\n        destruct H4 as (PREEMPT & EQ_INJ).\n        unfold eq_inj in EQ_INJ.\n        rewrite EQ_INJ in H1.\n        eapply H5 in H1.\n        rewrite <- H1.\n        rewrite <- TVIEW_EQ.\n        trivial.\n    }\n    { (** FIXME: dup *)\n        unfolds eq_ident_mapping.\n        destruct H3.\n        unfold incr_inj in H4.\n        apply H4 in H1.\n        eapply H5 in H1.\n        rewrite <- H1.\n        rewrite <- TVIEW_EQ.\n        trivial.\n    }\n    }\n    { (** delay set *)\n        exists (@DelaySet.dset_init nat).\n        splits.\n        eapply DelaySet.init_dset_subset.\n        rewrite PROMISES_EQ.\n        eapply rel_promises_intro; eauto.\n        {\n        intros.\n        pose proof (DelaySet.dset_gempty nat loc t).\n        rewrite H2 in H1. discriminate. \n        }\n        {\n        intros.\n        exists t f val R; eauto. splits; eauto.\n        destruct H0.\n        rewrite PROMISES_EQ in INJ_PROMISES.\n        unfolds mem_injected.\n        eapply INJ_PROMISES in H1. destruct H1.\n        \n        unfolds eq_ident_mapping. destruct H2.\n        destruct PREEMPT as [(B&EQ_INJ) | (B&INCR_INJ)].\n        { unfolds eq_inj.\n            pose proof H1.\n            apply EQ_INJ in H1.\n            apply H3 in H1.\n            rewrite <- H1 in H4; trivial.\n        }\n        { unfolds incr_inj.\n            pose proof H1.\n            apply INCR_INJ in H1.\n            apply H3 in H1.\n            rewrite <- H1 in H4; trivial.\n        }\n        }\n    { \n        intros.\n        exists t'.\n        splits.\n        2: { right. repeat eexists; eauto. }\n        destruct H0. (** FIXME: dup *)\n        rewrite PROMISES_EQ in INJ_PROMISES.\n        unfolds mem_injected.\n        eapply INJ_PROMISES in H1. destruct H1.\n        unfolds eq_ident_mapping. destruct H2.\n        destruct PREEMPT as [(B&EQ_INJ) | (B&INCR_INJ)].\n        { unfolds eq_inj.\n        pose proof H1.\n        apply EQ_INJ in H1.\n        apply H3 in H1.\n        rewrite <- H1 in H4; trivial.\n        }\n        { unfolds incr_inj.\n        pose proof H1.\n        apply INCR_INJ in H1.\n        apply H3 in H1.\n        rewrite <- H1 in H4; trivial.\n        }\n    } \n    }\nQed.\n\n(** Tgt Abort implies Src Abort *)\nTheorem cse_match_state_implies_abort_preserving:\n  forall inj lo e_tgt e_src b,\n  (cse_match_state inj lo e_tgt e_src b /\\ Thread.is_abort e_tgt lo) \n  -> Thread.is_abort e_src lo.\nProof.\n  intros.\n  destruct H as (MatchState, AbortTgt).\n  destruct e_tgt as (st_tgt, lc_tgt, sc_tgt, mem_tgt) eqn:EqETgt.\n  destruct e_src as (st_src, lc_src, sc_src, mem_src) eqn:EqESrc.\n  unfolds Thread.is_abort.\n  destruct AbortTgt as (CsstTgt & AbortTgt).\n  destruct AbortTgt as [StuckTgt | [RWOrdNotMatch | UpdOrdNotMatch]];\n  destruct lc_tgt as (tview_tgt, prm_tgt) eqn:EqLcTgt;\n  destruct lc_src as (tview_src, prm_src) eqn:EqLcSrc;\n  assert (LcEq: lc_tgt = lc_src).\n  {\n    inv MatchState.\n    inv MATCH_LOCAL.\n    inv MATCH_RTL_STATE;\n    simpls;\n    rewrite <- TVIEW_EQ;\n    rewrite <- PROMISES_EQ;\n    trivial. \n  }\n  - (** tgt is stuck -> src is stuck *)\n    splits; eauto; simpls.\n    { \n      rewrite <- EqLcSrc.\n      rewrite <- LcEq.\n      rewrite <- EqLcTgt in CsstTgt.\n      trivial.\n    }\n    left.\n    (** stuck tgt: no step & not done *)\n    eapply not_or_and in StuckTgt. \n    destruct StuckTgt as (NotStepTgt, NotDoneTgt).\n    eapply and_not_or. \n    destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt).\n    destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src).\n    splits.\n    { (** no step *) \n      inv MatchState.\n      inv MATCH_LOCAL.\n      inv MATCH_RTL_STATE.\n      (** frame match *)\n      simpls.\n      inversion MATCH_FRAME.  \n      simpls.\n      intro. \n      apply NotStepTgt.\n      destruct H as (e & st_src' & STEP).\n      destruct st_src' as (regs_src', blk_src', cdhp_src', cont_src', code_src') eqn:EqStSrcMid.\n      inversion STEP. \n      - (** skip *)\n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        *   \n          exists (ProgramEvent.silent) {|\n                State.regs := regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          eapply State.step_skip; eauto.\n          rewrite B_TGT.\n          unfolds transform_inst.\n          rewrite TRSF_INST.\n          trivial.\n      - (** assign *)\n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        *   \n          exists (ProgramEvent.silent) {|\n                State.regs := RegFun.add r (RegFile.eval_expr e0 regs_src) regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          eapply transform_assign_rhs_eval_eq in TRSF_INST; eauto. \n          destruct TRSF_INST as (e' & I' & EQEVAL).\n          eapply State.step_assign with (r:=r) (e:= e'); eauto.\n          rewrite I' in B_TGT; trivial.\n          rewrite EQEVAL; rewrite REG_EQ. trivial.\n       - (** load *)\n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        * (** load -> assign | load -> load \u4e0d\u53d8 *)\n          unfolds transform_inst.\n          pose proof (classic (or = Ordering.plain)).\n          destruct H0.\n          2: {\n            destruct or; try contradiction; eauto; \n            exists (e) {|\n              State.regs := RegFun.add r v regs_tgt;\n              State.blk := b_tgt';\n              State.cdhp := cdhp_tgt;\n              State.cont := cont_tgt;\n              State.code := code_tgt\n            |}; \n            rewrite <- H;\n            eapply State.step_load with (r:=r); eauto;\n            rewrite <- TRSF_INST in B_TGT; trivial.\n          }\n          destruct or; try contradiction; try discriminate; eauto.\n          remember (AveLat.GetRegByLoc loc (AveAI.getFirst analysis_blk)) as cse.\n          destruct cse eqn:EqCse; try discriminate; eauto.\n          2: { (** no cse for load, no opt *)\n              exists (e) {|\n              State.regs := RegFun.add r v regs_tgt;\n              State.blk := b_tgt';\n              State.cdhp := cdhp_tgt;\n              State.cont := cont_tgt;\n              State.code := code_tgt\n            |}.\n            rewrite <- H.\n            eapply State.step_load with (r:=r); eauto.\n            rewrite <- TRSF_INST in B_TGT; trivial.\n          }\n          (** there is cse, transform load to assign *)\n          rename t into reg'.\n          exists (ProgramEvent.silent) {|\n               (* State.regs := RegFun.add r v regs_tgt; *)\n                State.regs := RegFun.add r (RegFile.eval_expr (Inst.expr_reg reg') regs_tgt) regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          (** load r loc or -> assign r r'. \u8bc1\u660eabort\u4f7f\u7528\u7684\u8fd8\u662f\u53cd\u8bc1\u6cd5\uff0c\u53ea\u8981\u8bf4\u660esrc not abort \u53ef\u4ee5\u63a8\u51fatgt\u4e5f\u53ef\u80fdnot abort\u5c31\u597d\uff0c\u8bc1\u660e\u662f\u7b80\u5355\u7684*)\n          eapply State.step_assign with (r:=r) (e:= (Inst.expr_reg reg')); eauto.\n          (* destruct or; try contradiction; eauto. *)\n          rewrite <- TRSF_INST in B_TGT; trivial.\n      - (** store *)\n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        * \n          exists (e) {|\n                State.regs := regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          rewrite <- H.          \n          eapply State.step_store with(e:=e0); eauto.\n          rewrite B_TGT.\n          unfolds transform_inst.\n          rewrite TRSF_INST.\n          trivial.\n          rewrite REG_EQ.\n          rewrite <- H in STEP. inversion STEP. trivial.\n      - (** syscall *) \n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n          * \n            exists (e) {|\n                  State.regs := regs_tgt;\n                  State.blk := b_tgt';\n                  State.cdhp := cdhp_tgt;\n                  State.cont := cont_tgt;\n                  State.code := code_tgt\n                |}.\n            rewrite <- H.          \n          eapply State.step_out with(e:=e0); eauto.\n          rewrite B_TGT.\n          unfolds transform_inst.\n          rewrite TRSF_INST.\n          trivial.\n          rewrite REG_EQ.\n          rewrite <- H in STEP. inversion STEP. trivial.\n      - (** cas1 *) \n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n          * \n            exists (e) {|\n                  State.regs := RegFun.add r Integers.Int.one regs_tgt;\n                  State.blk := b_tgt';\n                  State.cdhp := cdhp_tgt;\n                  State.cont := cont_tgt;\n                  State.code := code_tgt\n                |}.\n            rewrite <- H.          \n          eapply State.step_cas_same with (r:=r) (er:=er) (ew:=ew); eauto.\n          rewrite B_TGT.\n          unfolds transform_inst.\n          rewrite TRSF_INST.\n          trivial.\n          rewrite REG_EQ. trivial.\n          rewrite REG_EQ. trivial.\n      - (** cas2 *) \n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n          * \n            exists (e) {|\n                  State.regs := RegFun.add r Integers.Int.zero regs_tgt;\n                  State.blk := b_tgt';\n                  State.cdhp := cdhp_tgt;\n                  State.cont := cont_tgt;\n                  State.code := code_tgt\n                |}.\n            rewrite <- H.          \n          eapply State.step_cas_flip with (r:=r) (er:=er) (ew:=ew); eauto.\n          rewrite B_TGT.\n          unfolds transform_inst.\n          rewrite TRSF_INST.\n          trivial.\n          rewrite REG_EQ. \n          rewrite VALR.\n          trivial.\n      - (** call *) \n        rewrite BLK0 in TRANSF_BLK.\n        unfold transform_blk in TRANSF_BLK.\n        (* destruct blk_tgt; destruct analysis_blk; try discriminate; eauto. *)\n        assert (blk_tgt = BBlock.call f fret). {\n          destruct blk_tgt; destruct analysis_blk; try discriminate; eauto.\n        }\n        rewrite <- H10 in FIND_FUNC.\n        eapply cse_wf_transform_blk in OPT; eauto.\n        destruct OPT as (cdhp_tgt' & blk_tgt' & TgtCdhp & TgtBlk).\n        eapply eq_sym in TRANSL_CDHP.\n        eapply cse_wf_transform_cdhp in TRANSL_CDHP; eauto.\n        destruct TRANSL_CDHP as (b'' & TCDHP).\n        exists e {|\n                  State.regs := RegFile.init;\n                  State.blk := blk_tgt';\n                  State.cdhp := cdhp_tgt';\n                  State.cont := Continuation.stack regs_tgt b'' cdhp_tgt cont_tgt;\n                  State.code := code_tgt\n                |}.\n        rewrite <- H.\n        eapply State.step_call; eauto.\n      - (** ret *) \n        exists e.\n        inversion MATCH_CONT.\n        * destruct DONE.\n          rewrite BLK0 in STEP.\n          rewrite H11 in STEP.\n          inversion STEP; try discriminate; eauto.\n        *  \n          exists {|\n            State.regs := regs_t;\n            State.blk := blk_t;\n            State.cdhp := cdhp_t;\n            State.cont := cont_tgt';\n            State.code := code_tgt\n          |}.\n        rewrite <- H.\n        eapply State.step_ret; eauto.\n        unfold transform_blk in TRANSF_BLK.\n        rewrite BLK0 in TRANSF_BLK. \n        destruct analysis_blk; try discriminate; eauto.\n      - (** fence_rel *) \n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        * \n          exists (e) {|\n                State.regs := regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          rewrite <- H.          \n        eapply State.step_fence_rel; eauto.\n        rewrite B_TGT.\n        unfolds transform_inst.\n        rewrite TRSF_INST.\n        trivial.\n\n      - (** fence_acq *)\n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        * \n          exists (e) {|\n                State.regs := regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          rewrite <- H.          \n        eapply State.step_fence_acq; eauto.\n        rewrite B_TGT.\n        unfolds transform_inst.\n        rewrite TRSF_INST.\n        trivial.\n\n      - (** fence_sc *) \n        rewrite BLK0 in TRANSF_BLK.\n        eapply transform_blk_induction in TRANSF_BLK; eauto.\n        destruct TRANSF_BLK as (i' & b_tgt' & B_TGT & TRSF).  \n        destruct TRSF as (TRSF_INST & TRSF_BLK).\n        * \n          exists (e) {|\n                State.regs := regs_tgt;\n                State.blk := b_tgt';\n                State.cdhp := cdhp_tgt;\n                State.cont := cont_tgt;\n                State.code := code_tgt\n              |}.\n          rewrite <- H.          \n        eapply State.step_fence_sc; eauto.\n        rewrite B_TGT.\n        unfolds transform_inst.\n        rewrite TRSF_INST.\n        trivial.\n      - (** jmp *) \n         exists e.\n         eapply eq_sym in TRANSL_CDHP. \n         rewrite <- H8 in TGT.\n         eapply cse_wf_transform_cdhp with (f:=f) in TRANSL_CDHP; eauto.\n         destruct TRANSL_CDHP as (b_tgt' & TCDHP).\n         rewrite <- H.\n         exists {|\n          State.regs := regs_tgt;\n          State.blk := b_tgt';\n          State.cdhp := cdhp_tgt;\n          State.cont := cont_tgt;\n          State.code := code_tgt\n          |}.\n          eapply State.step_jmp; eauto.\n          unfold transform_blk in TRANSF_BLK.\n          rewrite BLK0 in TRANSF_BLK. \n          destruct analysis_blk; try discriminate; eauto.\n      - (** be *)  \n        exists e.\n        destruct BRANCH as [(CdhpSrc & Cond) | (CdhpSrc & Cond)].\n        *  \n        eapply eq_sym in TRANSL_CDHP. \n        rewrite <- H8 in CdhpSrc.\n        eapply cse_wf_transform_cdhp with (f:=f1) in TRANSL_CDHP; eauto.\n        destruct TRANSL_CDHP as (b_tgt' & TCDHP).\n        rewrite <- H.\n        exists {|\n          State.regs := regs_tgt;\n          State.blk := b_tgt';\n          State.cdhp := cdhp_tgt;\n          State.cont := cont_tgt;\n          State.code := code_tgt\n          |}.\n        eapply State.step_be; eauto.\n        unfold transform_blk in TRANSF_BLK.\n        rewrite BLK0 in TRANSF_BLK. \n        destruct analysis_blk; try discriminate; eauto.\n        left. splits; eauto.\n        rewrite REG_EQ; rewrite H6; rewrite <- COND in Cond; eauto.\n        * \n          eapply eq_sym in TRANSL_CDHP. \n          rewrite <- H8 in CdhpSrc.\n          eapply cse_wf_transform_cdhp with (f:=f2) in TRANSL_CDHP; eauto.\n          destruct TRANSL_CDHP as (b_tgt' & TCDHP).\n          rewrite <- H.\n          exists {|\n            State.regs := regs_tgt;\n            State.blk := b_tgt';\n            State.cdhp := cdhp_tgt;\n            State.cont := cont_tgt;\n            State.code := code_tgt\n            |}.\n          eapply State.step_be; eauto.\n          unfold transform_blk in TRANSF_BLK.\n          rewrite BLK0 in TRANSF_BLK. \n          destruct analysis_blk; try discriminate; eauto.\n          right. splits; eauto.\n          rewrite REG_EQ; rewrite H6; rewrite <- COND in Cond; eauto.\n    }\n    { (** not done *)\n      inv MatchState.\n      inv MATCH_LOCAL.\n      inv MATCH_RTL_STATE.\n      (** frame match *)\n      simpls. \n      inversion MATCH_FRAME.  \n      simpls.\n      intro. \n      apply NotDoneTgt.\n      unfolds State.is_terminal; simpls.\n      inv MATCH_CONT. \n      destruct DONE; trivial. subst.\n      destruct H. subst.\n      simpl. destruct (AveAI.br_from_i analysis !! l i); eauto.\n      destruct H. discriminate.\n    } \n  - (** tgt -> src: load/store unmatch access*) \n    { (** FIXME: dup*)\n      inv MatchState.\n      inv MATCH_LOCAL.\n      inv MATCH_RTL_STATE;\n      simpls;\n      rewrite <- TVIEW_EQ;\n      rewrite <- PROMISES_EQ;\n      trivial. \n    }\n    - \n    splits; eauto; simpls.\n    { \n      rewrite <- EqLcSrc.\n      rewrite <- LcEq.\n      rewrite <- EqLcTgt in CsstTgt.\n      trivial.\n    }\n    inv MatchState.\n    inv MATCH_LOCAL.\n    inv MATCH_RTL_STATE.\n    (** frame match *)\n    simpls.\n    inversion MATCH_FRAME.  \n    simpls.\n    right. \n    trivial. left. \n    destruct RWOrdNotMatch as (st_tgt' & x & o & v & RW & NOT_MATCH).\n    destruct RW.\n      * inversion H.\n         { \n          destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc.\n          rewrite <- H0 in REG_EQ.\n          simpls.\n          (* rewrite REG_EQ in VAL. *)\n          rewrite <- H0 in TRANSF_BLK; simpls. rewrite BLK0 in TRANSF_BLK.\n          pose proof TRANSF_BLK.\n          eapply load_transformed_by_load in H5.\n          destruct H5 as (b'' & H').\n          eexists.\n          exists x o v. \n          splits; eauto.\n          left.\n          eapply State.step_load; eauto.\n         }\n         { \n          destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc.\n          rewrite <- H0 in REG_EQ.\n          simpls.\n          (* rewrite REG_EQ in VAL. *)\n          rewrite <- H0 in TRANSF_BLK; simpls. rewrite BLK0 in TRANSF_BLK.\n          pose proof TRANSF_BLK.\n          eapply cas_transformed_by_cas in H5.\n          destruct H5 as (b'' & H').\n          eexists.\n          exists x o v. \n          splits; eauto.\n          left.\n          eapply State.step_cas_flip with (er:= er); eauto.\n          {\n            rewrite REG_EQ in VALR. rewrite VALR.\n            unfold Integers.Int.cmp. trivial.\n          }\n         }\n      * inversion H.\n        destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc.\n        rewrite <- H0 in REG_EQ.\n        simpls.\n        rewrite REG_EQ in VAL.\n        rewrite <- H0 in TRANSF_BLK; simpls. rewrite BLK0 in TRANSF_BLK.\n        pose proof TRANSF_BLK.\n        eapply store_transformed_by_store in H5.\n        destruct H5 as (b'' & H').\n        eexists.\n        exists x o v. \n        splits; eauto.\n        right.\n        eapply State.step_store with (e:=e); eauto.\n  - (** tgt -> src: upd unmatch access *)\n    { (** FIXME: dup*)\n      inv MatchState.\n      inv MATCH_LOCAL.\n      inv MATCH_RTL_STATE;\n      simpls;\n      rewrite <- TVIEW_EQ;\n      rewrite <- PROMISES_EQ;\n      trivial. \n    }\n    - \n    splits; eauto; simpls.\n    { \n      rewrite <- EqLcSrc.\n      rewrite <- LcEq.\n      rewrite <- EqLcTgt in CsstTgt.\n      trivial.\n    }\n    inv MatchState.\n    inv MATCH_LOCAL.\n    inv MATCH_RTL_STATE.\n    (** frame match *)\n    simpls.\n    inversion MATCH_FRAME.  \n    simpls.\n    right; right. \n    destruct UpdOrdNotMatch as (st_tgt' & x & vr & vw & or & ow & UPD & NOT_MATCH).\n    inversion UPD.\n    destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc.\n    rewrite <- H5 in REG_EQ.\n    simpls.\n    (* rewrite REG_EQ in VAL. *)\n    rewrite <- H5 in TRANSF_BLK; simpls. rewrite BLK0 in TRANSF_BLK.\n    pose proof TRANSF_BLK.\n    eapply cas_transformed_by_cas in H.\n    destruct H as (b'' & H).\n    eexists.\n    exists x vr vw or ow. \n    splits; eauto.\n    eapply State.step_cas_same with (er:= er); eauto.\n    {\n      rewrite REG_EQ in VALR. rewrite VALR.\n      unfold Integers.Int.cmp. trivial.\n    }\n    {\n      rewrite REG_EQ in VALW. rewrite VALW.\n      unfold Integers.Int.cmp. trivial.\n    }\nQed.\n\n(** Local step's correctness: [skip], [assign], [jmp], [be], [call], [ret] *)\nTheorem cse_match_state_preserving_na_silent:\n  forall te lo inj st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src b st_tgt' lc_tgt' sc_tgt' mem_tgt', \n    Thread.program_step te lo \n        (@Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n        (@Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') \n    -> \n    ThreadEvent.silent = te \n    ->   \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n      (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b)\n    -> \n      (exists st_src' lc_src' sc_src' mem_src' te,\n          (te = ThreadEvent.silent \\/ ThreadEvent.is_na_read te)\n          /\\\n          Thread.program_step te lo (@Thread.mk rtl_lang st_src lc_src sc_src mem_src) \n                                    (@Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') \n          /\\\n          (cse_match_state inj lo \n          (Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') false)\n      ).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt).\n  destruct st_tgt' as (regs_tgt', blk_tgt', cdhp_tgt', cont_tgt', code_tgt').\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src); simpls.\n  inv H1.\n  pose proof MATCH_LOCAL as MATCH_LOCAL'.\n  inv MATCH_LOCAL.\n  inv MATCH_RTL_STATE; simpls. \n  inv MATCH_FRAME; simpls.\n  inv H; simpls. \n  inversion STATE; simpls; subst.\n\n  - (*** skip *) \n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n    eapply transform_blk_induction' in Heqblk_tgt; eauto.\n    destruct Heqblk_tgt as (inst & b_src' & EqBlkSrc & TRSF).\n    destruct TRSF as (TRSF_INST & TRSF_BLK).\n    * \n      exists {|\n          State.regs := regs_tgt';\n          State.blk := b_src';\n          State.cdhp := cdhp_src;\n          State.cont := cont_src;\n          State.code := code_src\n        |} lc_src sc_src mem_src (ThreadEvent.silent).\n      splits; eauto.\n      { (** skip -> skip  *)\n          eapply Thread.program_step_intro; simpls; eauto.\n          eapply State.step_skip; eauto.\n          eapply skip_transformed_inst_by_skip in TRSF_INST.\n          rewrite <- TRSF_INST; trivial.\n      }\n      { (** match state *)\n        inversion LOCAL.\n        eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n        { (** invariant *)\n          rewrite <- H5. rewrite <- H4. trivial.\n        }\n        {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { \n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H7 in H.\n                folds AveAI.b.\n                rewrite H.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H.\n              eapply skip_transformed_inst_by_skip in TRSF_INST.\n              rewrite TRSF_INST in H.\n              unfolds Ave_I.transf.\n              rewrite <- H.\n              trivial.\n            }\n            {\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H; eauto.\n              rewrite <- H. trivial.\n            }\n            {\n              destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n              eapply transf_step_psrv_loc_fact_valid; eauto.\n              eapply Ave_B.wf_transf_blk_step; eauto.\n              pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n              apply A in ANALYSIS.\n              folds AveAI.b.\n              rewrite ANALYSIS. \n              eapply top_is_loc_fact_valid.\n            }\n        }\n        {\n          right. \n          splits; trivial.\n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n        {\n          rewrite <- H3; rewrite <- H5.\n          trivial.\n        }\n        {\n          rewrite <- H4; rewrite <- H5. \n          trivial.\n        }\n        {\n          rewrite <- H5.\n          trivial.\n        }\n      }\n  - (** assign *)\n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n    eapply transform_blk_induction' in Heqblk_tgt; eauto.\n    destruct Heqblk_tgt as (inst & b_src' & EqBlkSrc & TRSF).\n    destruct TRSF as (TRSF_INST & TRSF_BLK).\n    * \n      eapply assign_transformed_inst_by_assign_or_na_load in TRSF_INST.\n      destruct TRSF_INST as [ASSIGN|[(loc & r' & LOAD & GET_REG & E) | (expr & r' & ASSIGN & GET_REG & E)]].\n      { (** assign = assign, seems no need for this case... *)\n        exists {|\n            State.regs := RegFun.add r (RegFile.eval_expr e regs_src) regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_src sc_src mem_src (ThreadEvent.silent). \n        splits; eauto. \n        { (** assign = assign  *)\n            eapply Thread.program_step_intro; simpls.\n            eapply State.step_assign; eauto.\n            rewrite <- ASSIGN; trivial.\n            eapply Local.step_silent; eauto.\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H5. rewrite <- H4. trivial.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { \n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H7 in H.\n                folds AveAI.b.\n                rewrite H.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H.\n              rewrite ASSIGN in H.\n              pose proof MATCH_AI as MATCH_AI'.\n              unfold match_abstract_interp in MATCH_AI.\n              unfold match_abstract_interp.\n              remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n              remember (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai'.\n              unfold Ave_I.transf in H.\n              remember (AveLat.opt_expr_with_ave e (AveLat.kill_reg ai r)) as opt_e.\n              remember (AveLat.GetRegByExpr opt_e (AveLat.kill_reg ai r)) as GetReg.\n              destruct GetReg eqn:EqGetReg.\n              {\n                destruct ai eqn:EqAi.\n                { \n                  unfold AveLat.kill_reg in H. rewrite <- H. trivial.\n                }\n                {\n                  unfold AveLat.kill_reg in H. rewrite <- H.\n                  intros.\n                  rename t into r'.\n                  simpls. discriminate. \n                }\n                {\n                  unfold AveLat.kill_reg in H. rewrite <- H.\n                  intros.\n                  rename t into r'.\n                  des_ifH H.\n                  2: {\n                    intros.\n                    assert (W.In tu tuples). {\n                      eapply W.filter_1 in H7; trivial.\n                      eapply AveTuple.compat_bool_freeOfReg.\n                    }\n                    specialize (MATCH_AI tu H8).\n                    (** get_reg tu <> r *)\n                    unfolds match_abstract_fact.\n                    destruct tu eqn:EqTu.\n                    { (** (r, e) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n\n                      inv H.\n\n                      pose proof H9.\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                        eapply W.filter_2 in H7.\n                        unfolds AveTuple.freeOfReg.\n                        intro.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        des_ifH H1; try discriminate; eauto.\n                        rewrite H0 in H2. discriminate.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr e regs_src)) in H0.\n                        folds Const.t.\n                        rewrite <- H0.\n                        trivial.\n                    }\n                    { (** (r, x) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9.\n                      trivial.\n                    } \n                  }\n                  intros.\n                  pose proof (classic (tu = AveTuple.AExpr r' (Inst.expr_reg r))) as IS_R_R'.\n                  destruct IS_R_R' as [IS_R_R' | NOT_R_R'].\n                  { (** (r', r) *)\n                    rewrite IS_R_R'.\n                    unfolds match_abstract_fact.\n                      unfolds AveLat.GetRegByExpr.\n                      pose proof Heqai'.\n                      remember  (RegFile.eval_expr e regs_src) as val.\n                      unfold RegFile.eval_expr. rewrite RegFun.add_spec_eq.\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn: KillReg; try discriminate.\n                      remember (W.choose (W.filter (AveTuple.isSameExpr opt_e) tuples0)) as Choose.\n                      destruct Choose eqn:EqChoose; try discriminate.\n                      inversion H2.\n                      eapply eq_sym in HeqChoose.\n                      eapply W.choose_1 in HeqChoose.\n                      pose proof HeqChoose.\n                      eapply W.filter_1 in HeqChoose.\n                      eapply W.filter_2 in H10.\n                      unfold AveTuple.isSameExpr in H10.\n                      destruct e0 eqn:EqE; try discriminate.\n                      eapply Inst.beq_expr_eq in H10.\n                      unfolds AveTuple.get_reg.\n                      inversion HeqGetReg.\n                      subst reg. \n                      assert (r' <> r). {\n                        eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) (r:=r)in KillReg; eauto.\n                        unfolds AveTuple.get_reg. trivial.\n                      }\n                      subst val.\n                      inv STATE; try discriminate.\n                      rewrite Loc_add_neq; eauto.\n                      assert (regs_src r' = RegFile.eval_expr e regs_src). {\n                        clear - MATCH_AI' MATCH_AI HeqChoose KillReg.\n                        remember ((AveLat.opt_expr_with_ave e (AveLat.CSet tuples0))) as opt_e.\n                        remember (AveTuple.AExpr r' opt_e) as tu.\n                        unfolds AveLat.kill_reg. inversion KillReg.\n                        rewrite <- H0 in HeqChoose.\n                        eapply W.filter_1 in HeqChoose.\n                        specialize (MATCH_AI tu HeqChoose).\n                        rewrite Heqtu in MATCH_AI.\n                        rewrite MATCH_AI.\n                        eapply eq_sym.\n                        subst opt_e.\n                        eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                        eapply ge_prsv_match_ai; eauto.\n                        { \n                          unfold AveAI.ge.\n                          unfold AveDS.L.ge.\n                          unfold W.Subset.\n                          intros.\n                          rewrite <- H0 in H.\n                          eapply W.filter_1 in H; eauto.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      trivial.\n                      eapply AveTuple.compat_bool_isSameExpr.\n                      eapply AveTuple.compat_bool_isSameExpr.\n                  }\n                  (** old tu *)\n                  assert (W.In tu tuples). {\n                    eapply W.add_3 in H7.\n                    eapply W.filter_1 in H7; trivial.\n                    eapply AveTuple.compat_bool_freeOfReg.\n                    intro. rewrite H8 in NOT_R_R'. contradiction.\n                  }\n                  specialize (MATCH_AI tu H8).\n                  unfolds match_abstract_fact.\n                  destruct tu eqn:EqTu.\n                  { (** (r, e) *)\n                    assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inv H.\n                        eapply W.add_3 in H7.\n                        2: {\n                          intro. \n                          rewrite H in NOT_R_R'.\n                          contradiction.\n                        }\n                        eapply W.filter_2 in H7. \n                        unfolds AveTuple.freeOfReg.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        destruct (reg =? r)%positive eqn:RegEq.\n                        try discriminate; eauto.\n                        rewrite Pos.eqb_sym in RegEq.\n                        eapply Pos.eqb_neq; eauto. \n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                    }\n\n                    inv H.\n                    eapply W.add_3 in H7; eauto.\n                    pose proof H9.\n                    eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                    folds Const.t.\n                    rewrite H9. \n                    assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                      eapply W.filter_2 in H7.\n                      unfolds AveTuple.freeOfReg.\n                      intro.\n                      eapply sflib__andb_split in H7.\n                      destruct H7.\n                      unfolds negb.\n                      des_ifH H1; try discriminate; eauto.\n                      rewrite H0 in H2. discriminate.\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr e regs_src)) in H0.\n                      folds Const.t.\n                      rewrite <- H0.\n                      trivial.\n                  }\n                  { (** (r, x) *)\n                    assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inv H.\n                        eapply W.add_3 in H7.\n                        2: {\n                          intro. \n                          rewrite H in NOT_R_R'.\n                          contradiction.\n                        }\n                        eapply W.filter_2 in H7. \n                        unfolds AveTuple.freeOfReg.\n                        unfolds negb.\n                        destruct (reg =? r)%positive eqn:RegEq.\n                        try discriminate; eauto.\n                        rewrite Pos.eqb_sym in RegEq.\n                        eapply Pos.eqb_neq; eauto. \n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                    }\n                    eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                    folds Const.t.\n                    rewrite H9.\n                    trivial.\n                  } \n                }\n              }\n              {\n                destruct ai eqn:EqAi.\n                { \n                  unfold AveLat.kill_reg in H. rewrite <- H. trivial.\n                }\n                {\n                  unfold AveLat.kill_reg in H. rewrite <- H. \n                  intros.\n                  destruct (negb (RegSet.mem r (Inst.regs_of_expr opt_e))) eqn:MEM.\n                  2: {\n                    contradiction.\n                  }\n                  intros.\n\n                  pose proof classic (tu = (AveTuple.AExpr r opt_e)).\n                  destruct H8.\n                  2: {\n                    eapply W.add_3 in H7.\n                    2: {\n                      intro.\n                      rewrite H9 in H8; contradiction.\n                    }\n                    pose proof W.empty_1. unfolds W.Empty. \n                    specialize (H9 tu). \n                    contradiction.\n                  }\n                  rewrite H8.\n                  unfold match_abstract_fact.\n                  rewrite Loc_add_eq.\n                  subst opt_e.\n                  unfolds AveLat.kill_reg.\n                  assert (RegFile.eval_expr (AveLat.opt_expr_with_ave e AveLat.Undef)\n                  (RegFun.add r (RegFile.eval_expr e regs_src) regs_src) = RegFile.eval_expr (AveLat.opt_expr_with_ave e AveLat.Undef) regs_src). {\n                    eapply eq_sym.\n                    eapply regs_add_nonfree_var_eq_eval_expr.\n                    intro.\n                    rewrite H9 in MEM. \n                    unfolds negb.\n                    discriminate.\n                  }\n                  rewrite H9.\n                  eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                }\n                {\n                  remember (AveLat.kill_reg (AveLat.CSet tuples) r ) as Kill.\n                  destruct Kill; try discriminate; eauto.\n                  destruct (negb (RegSet.mem r (Inst.regs_of_expr opt_e))) eqn:MEM.\n                  2: {\n                    rewrite <- H.\n                    intros.\n                    assert (W.In tu tuples). {\n                      unfold AveLat.kill_reg in HeqKill.\n                      inv HeqKill.\n                      eapply W.filter_1 in H7; subst; trivial.\n                      eapply AveTuple.compat_bool_freeOfReg.\n                    }\n                    specialize (MATCH_AI tu H8). \n                    unfolds match_abstract_fact.\n                    destruct tu eqn:EqTu.\n                    { (** (r, e) *)\n                      assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inversion HeqKill.\n                        rewrite H10 in H7.\n                        unfold AveLat.kill_reg in EqKillReg.\n                        inversion EqKillReg.\n                        rewrite <- H11 in H7.\n                        eapply W.filter_2 in H7. \n                        unfolds AveTuple.freeOfReg.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        destruct (reg =? r)%positive eqn:RegEq.\n                        try discriminate; eauto.\n                        rewrite Pos.eqb_sym in RegEq.\n                        eapply Pos.eqb_neq; eauto. \n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      }\n                      inversion HeqKill.\n                      rewrite H11 in H7.\n\n                      pose proof H9.\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                        eapply W.filter_2 in H7.\n                        unfold AveTuple.freeOfReg in H7.\n                        intro.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        des_ifH H13; try discriminate; eauto.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr e regs_src)) in H12.\n                      folds Const.t.\n                      rewrite <- H12.\n                      trivial.\n                    }\n                    { (** (r, x) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inversion HeqKill.\n                          rewrite H10 in H7.\n                          unfold AveLat.kill_reg in EqKillReg.\n                          inversion EqKillReg.\n                          rewrite <- H11 in H7.\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9.\n                      trivial.\n                    }\n                  }\n                  rewrite <- H.\n                  intros.\n                  unfolds match_abstract_fact.\n                  destruct tu eqn:EqTu.\n                  { (** (r, e) *)\n                    pose proof (classic (tu = AveTuple.AExpr r opt_e)).\n                    destruct H8.\n                    { (** (r, opt_e) *)\n                      rewrite EqTu in H8.\n                      inversion H8. subst expr. subst reg.\n                      rewrite Loc_add_eq.\n                      subst opt_e.\n                      unfolds AveLat.kill_reg.\n                      assert (RegFile.eval_expr (AveLat.opt_expr_with_ave e (AveLat.CSet tuples0))\n                      (RegFun.add r (RegFile.eval_expr e regs_src) regs_src) = RegFile.eval_expr (AveLat.opt_expr_with_ave e (AveLat.CSet tuples0)) regs_src). {\n                        eapply eq_sym.\n                        eapply regs_add_nonfree_var_eq_eval_expr.\n                        intro.\n                        rewrite H9 in MEM. \n                        unfolds negb.\n                        discriminate.\n                      }\n                      rewrite H9.\n                      eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                      eapply ge_prsv_match_ai; eauto.\n                      inversion HeqKill.\n                      {\n                        unfold AveAI.ge.\n                        unfold AveDS.L.ge.\n                        unfold W.Subset.\n                        intros.\n                        eapply W.filter_1 in H10; eauto.\n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                    }\n                    { (** old (r, e) *)\n                      eapply W.add_3 in H7; eauto.\n                      2: {subst; eauto. }\n                      clear H8.\n                      assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inversion HeqKill.\n                        rewrite H9 in H7.\n                        unfold AveLat.kill_reg in EqKillReg.\n                        inversion EqKillReg.\n                        rewrite <- H10 in H7.\n                        eapply W.filter_2 in H7. \n                        unfolds AveTuple.freeOfReg.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        destruct (reg =? r)%positive eqn:RegEq.\n                        try discriminate; eauto.\n                        rewrite Pos.eqb_sym in RegEq.\n                        eapply Pos.eqb_neq; eauto. \n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      }\n                      inversion HeqKill.\n                      rewrite H10 in H7.\n\n                      pose proof H8.\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H8.\n                      folds Const.t.\n                      rewrite H8. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                        eapply W.filter_2 in H7.\n                        unfold AveTuple.freeOfReg in H7.\n                        intro.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        des_ifH H12; try discriminate; eauto.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr e regs_src)) in H11.\n                      folds Const.t.\n                      rewrite <- H11.\n                      trivial.\n                      assert (W.In tu tuples). {\n                        eapply W.filter_1 in H7; subst; trivial.\n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      specialize (MATCH_AI tu H12).\n                      rewrite EqTu in MATCH_AI. trivial.\n                    }\n                  }\n                  { (** (r, x) *)\n                    assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inversion HeqKill.\n                        rewrite H9 in H7.\n                        unfold AveLat.kill_reg in EqKillReg.\n                        inversion EqKillReg.\n                        rewrite <- H10 in H7.\n                        eapply W.add_3 in H7.\n                        2: {intro. discriminate. }\n                        eapply W.filter_2 in H7. \n                        unfolds AveTuple.freeOfReg.\n                        unfolds negb.\n                        destruct (reg =? r)%positive eqn:RegEq.\n                        try discriminate; eauto.\n                        rewrite Pos.eqb_sym in RegEq.\n                        eapply Pos.eqb_neq; eauto. \n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                    }\n                    eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr e regs_src)) (regs:=regs_src) in H8.\n                    folds Const.t.\n                    rewrite H8.\n                    assert (W.In tu tuples). {\n                      eapply W.add_3 in H7.\n                      inv HeqKill.\n                      eapply W.filter_1 in H7; subst; trivial.\n                      eapply AveTuple.compat_bool_freeOfReg.\n                      intro; discriminate.\n                    }\n                    specialize (MATCH_AI tu H9). subst; trivial.                    \n                  }\n                }\n              }\n            }\n            { \n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H; eauto.\n              rewrite <- H. trivial.\n            }\n            {\n              destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n              eapply transf_step_psrv_loc_fact_valid; eauto.\n              eapply Ave_B.wf_transf_blk_step; eauto.\n              pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n              apply A in ANALYSIS.\n              folds AveAI.b.\n              rewrite ANALYSIS. \n              eapply top_is_loc_fact_valid.\n            }\n        }\n          {\n            right. \n            splits; trivial.\n            destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n            apply eq_inj_implies_incr; trivial.\n            trivial.\n          }\n          {\n            rewrite <- H3; rewrite <- H5.\n            trivial.\n          }\n          {\n            rewrite <- H4; rewrite <- H5. \n            trivial.\n          }\n          {\n            rewrite <- H5.\n            trivial.\n          }\n        }\n      }\n      { (** load -opt-> assign *)\n      assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n        {\n          destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n          eapply transf_step_psrv_loc_fact_valid; eauto.\n          eapply Ave_B.wf_transf_blk_step; eauto.\n          pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n          apply A in ANALYSIS.\n          folds AveAI.b.\n          rewrite ANALYSIS. \n          eapply top_is_loc_fact_valid.\n        }\n      }\n      rename H into LOC_FACT_VALID.\n        exists {|\n            State.regs := RegFun.add r (RegFile.eval_expr e regs_src) regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_src sc_src mem_src. \n\n        remember ((AveAI.getFirst (AveAI.br_from_i analysis !! l i))) as ai.\n        pose proof GET_REG as GET_REG'.\n        unfold AveLat.GetRegByLoc in GET_REG.\n        destruct ai eqn:EqAi; try discriminate; eauto.\n        remember (W.choose (W.filter (AveTuple.isSameLoc loc) tuples)) as ai_tmp.\n        destruct ai_tmp eqn:EqAiTmp; try discriminate; eauto.\n        rename e0 into tu.\n        eapply eq_sym in Heqai_tmp.\n        eapply W.choose_1 in Heqai_tmp.\n        pose proof Heqai_tmp as TU.\n        eapply W.filter_1 in Heqai_tmp.\n        eapply W.filter_2 in TU.\n        unfold AveTuple.isSameLoc in TU.\n        destruct tu eqn:EqTu; try discriminate; eauto.\n        pose proof (MATCH_AI tu).\n        rewrite <- EqTu in Heqai_tmp.\n        apply H in Heqai_tmp.\n        clear H.\n        unfolds match_abstract_fact. rewrite EqTu in Heqai_tmp. \n        destruct Heqai_tmp as (NON_ATOMIC & t & f & R & PLN & RLX & MSG).\n        eapply Pos.eqb_eq in TU. \n        rewrite <- TU in MSG.\n        2: {eapply AveTuple.compat_bool_isSameLoc. }\n        2: {eapply AveTuple.compat_bool_isSameLoc. }\n        pose proof MSG as MSG'.\n        assert (regs_src reg = regs_src r'). {\n          inv GET_REG. trivial. }\n        rename H into REG_R'.\n\n        assert (exists te, te = ThreadEvent.read loc t (RegFile.eval_expr e regs_src) R Ordering.plain). {\n          eexists; eauto.\n        }\n        destruct H as (te & TE).  \n        exists te.\n        splits; eauto. \n        {\n          right. unfold ThreadEvent.is_na_read. rewrite TE. trivial. \n        }\n        { (** load -> assign  *)\n            eapply Thread.program_step_intro; simpls.\n            unfold ThreadEvent.get_program_event.\n            rewrite TE.\n            eapply State.step_load; eauto.\n            rewrite <- LOAD; trivial.\n            rewrite TE.\n            eapply Local.step_read; eauto.\n\n            (** get abstract fact *)\n            eapply Local.read_step_intro with (from:=f); eauto.\n            {\n              rewrite MSG.\n              rewrite E.\n              unfold RegFile.eval_expr.\n              assert (regs_src reg = regs_src r'). {\n                inv GET_REG. trivial. }\n              rewrite H.\n              trivial.\n            }\n            { \n              subst.\n              unfold Ordering.mem_ord_match.\n              rewrite NON_ATOMIC. trivial.\n            }\n            { \n              econs; subst; eauto.\n              replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n              unfold is_true.\n              intro. discriminate.\n            }\n            {\n              assert (lc_src = lc_tgt). {eapply cse_match_local_state_implies_eq_local; eauto. }\n              pose proof TU as TU'.\n              subst. destruct lc_tgt eqn:EqLcTgt; simpls. \n              unfold TView.read_tview.\n              replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n              replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n              unfold View.singleton_ur_if.\n              unfold View.singleton_rw.\n              unfold View.join; unfold View.bot; simpls.\n              repeat rewrite TimeMap.join_bot.\n              destruct tview eqn:EqTview; simpls; eauto.\n              destruct cur eqn:EqCur; simpls; eauto.\n              destruct acq eqn:EqAcq; simpls; eauto.\n              assert (TimeMap.join rlx (TimeMap.singleton loc0 t) = rlx). {\n                eapply TimeMap.le_join_l; eauto.\n                unfold TimeMap.singleton.  \n                unfold TimeMap.le. intro. \n                pose proof (classic (loc = loc0)).\n                destruct H.\n                rewrite H. rewrite Loc_add_eq; eauto.\n                rewrite Loc_add_neq; eauto. \n                unfold LocFun.init.\n                eapply Time.bot_spec.\n              }\n              assert (TimeMap.join rlx0 (TimeMap.singleton loc0 t) = rlx0). {\n                inv LOCAL_WF.\n                inv TVIEW_WF. \n                simpls.\n                inv CUR_ACQ. simpls.\n                eapply TimeMap.le_join_l.\n                assert (TimeMap.le  (TimeMap.singleton loc0 t) rlx). {\n                  unfold TimeMap.singleton.  \n                  unfold TimeMap.le. intro. \n                  pose proof (classic (loc = loc0)).\n                  destruct H0.\n                  rewrite H0. rewrite Loc_add_eq; eauto.\n                  rewrite Loc_add_neq; eauto. \n                  unfold LocFun.init.\n                  eapply Time.bot_spec.\n                }\n                unfolds TimeMap.le.\n                intros.\n                specialize (RLX0 loc).\n                specialize (H0 loc).\n                auto_solve_time_rel. \n              }\n              rewrite H.\n              rewrite H0.\n              trivial.\n            }\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H5. rewrite <- H4. trivial.\n          }\n          {\n              eapply cse_match_local_state_intro; \n              try rewrite <- H3; eauto.\n              eapply cse_match_rtl_state_intro; eauto.\n              simpls.\n              eapply cse_match_frame_intro with(i:=i+1); eauto.\n              rewrite EqBlkSrc in PARTIAL_BLK.\n              eapply bb_from_i_plus_one; eauto.\n              rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n              { (** match ai *)\n                destruct ANALYSIS.\n                2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H7 in H.\n                folds AveAI.b.\n                rewrite H.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H.\n              rewrite LOAD in H.\n              unfolds Ave_I.transf.\n                rewrite <- H.\n                subst.\n                unfolds match_abstract_interp.\n                rename loc0 into loc.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.GetRegByLoc loc (AveLat.kill_reg ai r)) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  discriminate.\n                }\n                { discriminate.\n                }\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai''.\n                destruct ai'' eqn:EqAi''.\n                {subst. rewrite H. \n                  destruct (AveLat.kill_reg (AveLat.CSet tuples0) r ) eqn:Eq1; \n                  destruct (AveLat.GetRegByLoc loc (AveLat.kill_reg (AveLat.CSet tuples) r)) eqn:Eq2; try discriminate;  eauto.\n                }\n                {subst. rewrite H. \n                  destruct (AveLat.kill_reg (AveLat.CSet tuples0) r ) eqn:Eq1; \n                  destruct (AveLat.GetRegByLoc loc (AveLat.kill_reg (AveLat.CSet tuples) r)) eqn:Eq2; try discriminate;  eauto.\n                }\n                rewrite H.\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  destruct ai' eqn:EqAi'.\n                  { \n                    rename t0 into reg'.\n                    pose proof (classic (tu = AveTuple.AExpr reg' (Inst.expr_reg r))).\n                    destruct H1.\n                    { (** (r', r) *)\n                      assert (r' = reg'). {\n                        assert (W.In (AveTuple.AVar r' loc) tuples). {\n                          clear - GET_REG'.\n                          remember (W.choose (W.filter (AveTuple.isSameLoc loc) tuples)) as Choose.\n                          destruct Choose eqn:EqChoose; try discriminate.\n                          eapply eq_sym in HeqChoose.\n                          eapply W.choose_1 in HeqChoose.\n                          pose proof HeqChoose.\n                          eapply W.filter_1 in HeqChoose.\n                          eapply W.filter_2 in H.\n                          unfolds AveTuple.isSameLoc.\n                          destruct e eqn:EqE; try discriminate.\n                          eapply Pos.eqb_eq in H. subst loc0.\n                          unfolds AveTuple.get_reg. inv GET_REG'. trivial.\n                          eapply AveTuple.compat_bool_isSameLoc.\n                          eapply AveTuple.compat_bool_isSameLoc.\n                        }\n                        assert (W.In (AveTuple.AVar reg' loc) tuples). {\n                          inv Heqai.\n                          clear - Heqai'.\n                          unfolds AveLat.GetRegByLoc.\n                          remember (AveLat.kill_reg (AveLat.CSet tuples0) r) as KillReg.\n                          destruct KillReg; try discriminate; eauto.\n                          remember (W.choose (W.filter (AveTuple.isSameLoc loc) tuples)) as Choose.\n                          destruct Choose; try discriminate.\n                          inv Heqai'.\n                          eapply eq_sym in HeqChoose.\n                          eapply W.choose_1 in HeqChoose.\n                          pose proof HeqChoose.\n                          eapply W.filter_1 in HeqChoose.\n                          eapply W.filter_2 in H.\n                          unfolds AveTuple.isSameLoc.\n                          destruct e eqn:EqE; try discriminate.\n                          eapply Pos.eqb_eq in H. subst loc0.\n                          unfolds AveTuple.get_reg. \n                          unfolds AveLat.kill_reg.\n                          inv HeqKillReg.\n                          eapply W.filter_1 in HeqChoose. trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                          eapply AveTuple.compat_bool_isSameLoc.\n                          eapply AveTuple.compat_bool_isSameLoc.\n                        }\n                        specialize (LOC_FACT r' reg' loc H2 H3). trivial.\n                      }\n                      rename H2 into CHOOSE_EQ.\n                      rewrite H1 in EqTu.\n                      inversion EqTu.\n                      rewrite <- H3.\n                      unfolds transform_inst.\n                      unfolds AveLat.GetRegByLoc.\n                      pose proof Heqai'.\n                      remember (RegFile.eval_expr (Inst.expr_reg r') regs_src) as val.\n                      unfold RegFile.eval_expr. rewrite RegFun.add_spec_eq.\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples0) r) eqn: KillReg; try discriminate.\n                      remember (W.choose (W.filter (AveTuple.isSameLoc loc) tuples2)) as Choose.\n                      destruct Choose eqn:EqChoose; try discriminate.\n                      inversion H2.\n                      eapply eq_sym in HeqChoose.\n                      eapply W.choose_1 in HeqChoose.\n                      pose proof HeqChoose.\n                      eapply W.filter_1 in HeqChoose.\n                      eapply W.filter_2 in H5.\n                      unfold AveTuple.isSameLoc in H5.\n                      destruct e eqn:EqE; try discriminate.\n                      eapply Pos.eqb_eq in H5.\n                      unfolds AveTuple.get_reg.\n                      subst reg'. subst reg0.\n                      assert (reg1 <> r). {\n                        eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples0) (r:=r)in KillReg; eauto.\n                        unfolds AveTuple.get_reg. trivial.\n                      }\n                      inv STATE; try discriminate.\n                      rewrite Loc_add_neq; eauto.\n                      eapply AveTuple.compat_bool_isSameLoc.\n                      eapply AveTuple.compat_bool_isSameLoc.\n                    } \n                    {\n                      (** similar proof *)\n                      inv GET_REG.\n                      rename reg0 into reg.\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.add_3 in H0.\n                          2: {\n                            intro. \n                            inversion H. simpls. try contradiction.\n                            rewrite <- H in H1. \n                            simpls. subst.\n                            try contradiction. \n                          }\n                          remember (AveLat.kill_reg (AveLat.CSet tuples) r) as _ai.\n                          remember (AveTuple.AExpr reg expr) as tu.\n                          eapply W.filter_2 in H0.\n                          unfold AveTuple.freeOfReg in H0. subst tu.\n                          eapply sflib__andb_split in H0.\n                          destruct H0.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      inv H.\n                      eapply W.add_3 in H0; eauto.\n                      pose proof H0.\n                      eapply W.filter_1 in H0.\n                      inv Heqai.\n                      pose proof (MATCH_AI (AveTuple.AExpr reg expr)).\n                      apply H3 in H0.\n                      pose proof H2.\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr (Inst.expr_reg r') regs_src)) (regs:=regs_src) in H2.\n                      folds Const.t.\n                      rewrite H2. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                        eapply W.filter_2 in H.\n                        unfolds AveTuple.freeOfReg.\n                        intro.\n                        eapply sflib__andb_split in H.\n                        destruct H.\n                        unfolds negb.\n                        des_ifH H; try discriminate; eauto.\n                        rewrite H5 in H6. discriminate.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr (Inst.expr_reg r') regs_src)) in H5.\n                      folds Const.t.\n                      rewrite <- H5.\n                      trivial.\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                  }\n                  { \n                    inv GET_REG.\n                    inv Heqai.\n                    rename reg0 into reg.\n                    rename tuples0 into tuples.\n                    assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inv H.\n                        eapply W.add_3 in H0.\n                        2: {\n                          intro. try discriminate.\n                        }\n                        remember (AveLat.kill_reg (AveLat.CSet tuples) r) as _ai.\n                        remember (AveTuple.AExpr reg expr) as tu.\n                        eapply AveLat.mem_of_kill_reg_implies_neq with (tuples':=tuples0) (tuples:=tuples) (r:=r) in H0; eauto.\n                        unfolds AveTuple.get_reg. rewrite Heqtu in H0.  \n                        intro. rewrite H in H0. contradiction. \n                      }\n                    }\n                    inv H.\n                    eapply W.add_3 in H0; eauto.\n                    2: {\n                      intro. discriminate.\n                    }\n                    pose proof H0.\n                    eapply W.filter_1 in H0.\n                    pose proof (MATCH_AI (AveTuple.AExpr reg expr)).\n                    apply H2 in H0.\n                    pose proof H1.\n                    eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr (Inst.expr_reg r') regs_src)) (regs:=regs_src) in H1.\n                    folds Const.t.\n                    rewrite H1. \n                    assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                      eapply W.filter_2 in H.\n                      unfolds AveTuple.freeOfReg.\n                      intro.\n                      eapply sflib__andb_split in H.\n                      destruct H.\n                      unfolds negb.\n                      des_ifH H; try discriminate; eauto.\n                      rewrite H4 in H5. discriminate.\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr (Inst.expr_reg r') regs_src)) in H4.\n                    folds Const.t.\n                    rewrite <- H4.\n                    trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  inversion GET_REG.\n                  inversion Heqai.\n                  subst reg.\n                  subst tuples.\n                  rename reg0 into reg.\n                  rename tuples0 into tuples.\n\n                  pose proof (classic (tu = AveTuple.AVar r loc)).\n                  destruct H1.\n                  { (** (r, x) is newly inserted *)\n                    splits; eauto.\n                    { (** lo loc = non-atomic *)\n                      inv LOCAL.\n                      unfolds Ordering.mem_ord_match.\n                      inv H1.\n                      destruct (lo loc) eqn:EqLocOr; trivial. \n                    }\n                    {\n                      rewrite EqTu in H1. \n                      inversion H1.\n                      inv LOCAL. simpls.\n                      rewrite Loc_add_eq.\n                      do 3 eexists; eauto. \n                    }\n                  }\n                  { (** (r, x) is old *)\n                    rewrite EqTu in H1. \n                    assert (W.In tu tuples). {\n                      (* clear - H2 Heqai'' H14. *)\n                      destruct ai'.\n                      {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.add_3 in H0; eauto.\n                          2: { intro. discriminate. }\n                          unfolds AveLat.kill_reg.\n                          inv EqKillReg.\n                          eapply W.filter_1 in H0. trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.add_3 in H0; eauto.\n                          inv EqKillReg.\n                          eapply W.filter_1 in H0. trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                    }\n                    pose proof (MATCH_AI tu). apply H3 in H2.\n                    rewrite EqTu in H2. \n                    assert (regs_src reg = RegFun.add r (RegFile.eval_expr (Inst.expr_reg r') regs_src) regs_src reg). {\n                      apply eq_sym.\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          destruct ai' eqn:EqAi'.\n                          {\n                            rename t into reg'.\n                            \n                            inv H.\n                            eapply W.add_3 in H0; eauto.\n                            intro.\n                            eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) in EqKillReg; eauto.\n                            unfolds AveTuple.get_reg.\n                            trivial.\n                            rewrite H. trivial.\n                            intro.\n                            discriminate.\n                          }\n                          {\n                            inv H.\n                            eapply W.add_3 in H0; eauto.\n                            intro.\n                            eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) in EqKillReg; eauto.\n                            unfolds AveTuple.get_reg.\n                            rewrite H.\n                            trivial.\n                          }\n                        }\n                      }\n                      eapply regs_add_neg; eauto.\n                    }\n                    destruct H2.\n                    splits; eauto.\n                    subst.\n                    rewrite <- H4.\n                    trivial.\n                  }\n              }\n            }\n            { \n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H; eauto.\n              rewrite <- H. trivial.\n            }\n          }\n          {\n            right. \n            splits; trivial.\n            destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n            apply eq_inj_implies_incr; trivial.\n            trivial.\n          }\n          {\n            rewrite <- H3; rewrite <- H5.\n            trivial.\n          }\n          {\n            rewrite <- H4; rewrite <- H5. \n            trivial.\n          }\n          {\n            rewrite <- H5.\n            trivial.\n          }\n        }\n      }\n      { (** assign -opt-> assign*)\n        assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n          {\n            destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n            eapply transf_step_psrv_loc_fact_valid; eauto.\n            eapply Ave_B.wf_transf_blk_step; eauto.\n            pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n            apply A in ANALYSIS.\n            folds AveAI.b.\n            rewrite ANALYSIS. \n            eapply top_is_loc_fact_valid.\n          }\n        }\n        rename H into LOC_FACT_VALID.\n        exists {|\n            State.regs := RegFun.add r (RegFile.eval_expr expr regs_src) regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_src sc_src mem_src (ThreadEvent.silent). \n        splits; eauto. \n        { (** load/assign -> assign  *)\n            eapply Thread.program_step_intro; simpls.\n            eapply State.step_assign; eauto.\n            rewrite <- ASSIGN; trivial.\n            eapply Local.step_silent; eauto.\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H5. rewrite <- H4. trivial.\n          }\n          {\n              eapply cse_match_local_state_intro; \n              try rewrite <- H3; eauto.\n              eapply cse_match_rtl_state_intro; eauto.\n              simpls.\n              remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n              assert (e = AveLat.opt_expr_with_ave expr ai). {\n                unfolds AveLat.opt_expr_with_ave.\n                subst. \n                destruct expr; rewrite GET_REG; trivial.\n              }\n              rename H into OPT_EXPR.\n              eapply cse_match_frame_intro with(i:=i+1); eauto.\n              {\n                assert (RegFile.eval_expr e regs_src = RegFile.eval_expr expr regs_src). {\n                  rewrite OPT_EXPR.\n                  eapply eq_sym.\n                  eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                }\n                rewrite H; trivial.\n              }\n              {\n                eapply bb_from_i_plus_one with (inst:=inst); eauto.\n                subst. trivial.\n              }\n              rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n              { \n                destruct ANALYSIS.\n                2: { (** case: analysis = top; always match_ai *)\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                  eapply H7 in H.\n                  folds AveAI.b.\n                  rewrite H.\n                  eapply always_match_top.\n                }\n                eapply Ave_B.wf_transf_blk_step in H; eauto.\n                unfolds Ave_B.transf_step.\n                rewrite EqBlkSrc in H.\n                rewrite ASSIGN in H.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai'.\n\n                pose proof MATCH_AI as MATCH_AI'.\n                unfold match_abstract_interp in MATCH_AI.\n                unfold match_abstract_interp.\n                unfold Ave_I.transf in H.\n                rewrite <- Heqai in H.\n                remember (AveLat.opt_expr_with_ave expr (AveLat.kill_reg ai r)) as opt_e.\n                remember (AveLat.GetRegByExpr opt_e (AveLat.kill_reg ai r)) as GetReg.\n                destruct GetReg eqn:EqGetReg.\n                2: { (** r \\in fv(rhs) *)\n                  destruct ai eqn:EqAi.\n                  { \n                    unfold AveLat.kill_reg in H. rewrite <- H. trivial.\n                  }\n                  {\n                    unfold AveLat.kill_reg in H. rewrite <- H. \n                    intros.\n                    destruct (negb (RegSet.mem r (Inst.regs_of_expr opt_e))) eqn:MEM.\n                    2: {\n                      contradiction.\n                    }\n                    intros.\n\n                    pose proof classic (tu = (AveTuple.AExpr r opt_e)).\n                    destruct H8.\n                    2: {\n                      eapply W.add_3 in H7.\n                      2: {\n                        intro.\n                        rewrite H9 in H8; contradiction.\n                      }\n                      pose proof W.empty_1. unfolds W.Empty. \n                      specialize (H9 tu). \n                      contradiction.\n                    }\n                    rewrite H8.\n                    unfold match_abstract_fact.\n                    rewrite Loc_add_eq.\n                    subst opt_e.\n                    unfolds AveLat.kill_reg.\n                    assert (RegFile.eval_expr (AveLat.opt_expr_with_ave expr AveLat.Undef)\n                    (RegFun.add r (RegFile.eval_expr expr regs_src) regs_src) = RegFile.eval_expr (AveLat.opt_expr_with_ave expr AveLat.Undef) regs_src). {\n                      eapply eq_sym.\n                      eapply regs_add_nonfree_var_eq_eval_expr.\n                      intro.\n                      rewrite H9 in MEM. \n                      unfolds negb.\n                      discriminate.\n                    }\n                    rewrite H9.\n                    eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                  }\n                  {\n                    remember (AveLat.kill_reg (AveLat.CSet tuples) r ) as Kill.\n                    destruct Kill; try discriminate; eauto.\n                    destruct (negb (RegSet.mem r (Inst.regs_of_expr opt_e))) eqn:MEM.\n                    2: {\n                      rewrite <- H.\n                      intros.\n                      assert (W.In tu tuples). {\n                        unfold AveLat.kill_reg in HeqKill.\n                        inv HeqKill.\n                        eapply W.filter_1 in H7; subst; trivial.\n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      specialize (MATCH_AI tu H8). \n                      unfolds match_abstract_fact.\n                      destruct tu eqn:EqTu.\n                      { (** (r, e) *)\n                        assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inversion HeqKill.\n                          rewrite H10 in H7.\n                          unfold AveLat.kill_reg in EqKillReg.\n                          inversion EqKillReg.\n                          rewrite <- H11 in H7.\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                        }\n                        inversion HeqKill.\n                        rewrite H11 in H7.\n\n                        pose proof H9.\n                        eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                        folds Const.t.\n                        rewrite H9. \n                        assert (~RegSet.mem r (Inst.regs_of_expr expr0)). {\n                          eapply W.filter_2 in H7.\n                          unfold AveTuple.freeOfReg in H7.\n                          intro.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          des_ifH H13; try discriminate; eauto.\n                          eapply (AveTuple.compat_bool_freeOfReg r).\n                        }\n                        eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr expr regs_src)) in H12.\n                        folds Const.t.\n                        rewrite <- H12.\n                        trivial.\n                      }\n                      { (** (r, x) *)\n                        assert (r <> reg). {\n                          destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            inversion HeqKill.\n                            rewrite H10 in H7.\n                            unfold AveLat.kill_reg in EqKillReg.\n                            inversion EqKillReg.\n                            rewrite <- H11 in H7.\n                            eapply W.filter_2 in H7. \n                            unfolds AveTuple.freeOfReg.\n                            unfolds negb.\n                            destruct (reg =? r)%positive eqn:RegEq.\n                            try discriminate; eauto.\n                            rewrite Pos.eqb_sym in RegEq.\n                            eapply Pos.eqb_neq; eauto. \n                            eapply AveTuple.compat_bool_freeOfReg.\n                          }\n                        }\n                        eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                        folds Const.t.\n                        rewrite H9.\n                        trivial.\n                      }\n                    }\n                    rewrite <- H.\n                    intros.\n                    unfolds match_abstract_fact.\n                    destruct tu eqn:EqTu.\n                    { (** (r, e) *)\n                      pose proof (classic (tu = AveTuple.AExpr r opt_e)).\n                      destruct H8.\n                      { (** (r, opt_e) *)\n                        rewrite EqTu in H8.\n                        inversion H8. subst expr0. subst reg.\n                        rewrite Loc_add_eq.\n                        subst opt_e.\n                        unfolds AveLat.kill_reg.\n                        assert (RegFile.eval_expr (AveLat.opt_expr_with_ave expr (AveLat.CSet tuples0))\n                        (RegFun.add r (RegFile.eval_expr expr regs_src) regs_src) = RegFile.eval_expr (AveLat.opt_expr_with_ave expr (AveLat.CSet tuples0)) regs_src). {\n                          eapply eq_sym.\n                          eapply regs_add_nonfree_var_eq_eval_expr.\n                          intro.\n                          rewrite H9 in MEM. \n                          unfolds negb.\n                          discriminate.\n                        }\n                        rewrite H9.\n                        eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                        eapply ge_prsv_match_ai; eauto.\n                        inversion HeqKill.\n                        {\n                          unfold AveAI.ge.\n                          unfold AveDS.L.ge.\n                          unfold W.Subset.\n                          intros.\n                          eapply W.filter_1 in H10; eauto.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      { (** old (r, e) *)\n                        eapply W.add_3 in H7; eauto.\n                        2: {subst; eauto. }\n                        clear H8.\n                        assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inversion HeqKill.\n                          rewrite H9 in H7.\n                          unfold AveLat.kill_reg in EqKillReg.\n                          inversion EqKillReg.\n                          rewrite <- H10 in H7.\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                        }\n                        inversion HeqKill.\n                        rewrite H10 in H7.\n\n                        pose proof H8.\n                        eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H8.\n                        folds Const.t.\n                        rewrite H8. \n                        assert (~RegSet.mem r (Inst.regs_of_expr expr0)). {\n                          eapply W.filter_2 in H7.\n                          unfold AveTuple.freeOfReg in H7.\n                          intro.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          des_ifH H12; try discriminate; eauto.\n                          eapply (AveTuple.compat_bool_freeOfReg r).\n                        }\n                        eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr expr regs_src)) in H11.\n                        folds Const.t.\n                        rewrite <- H11.\n                        trivial.\n                        assert (W.In tu tuples). {\n                          eapply W.filter_1 in H7; subst; trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                        specialize (MATCH_AI tu H12).\n                        rewrite EqTu in MATCH_AI. trivial.\n                      }\n                    }\n                    { (** (r, x) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inversion HeqKill.\n                          rewrite H9 in H7.\n                          unfold AveLat.kill_reg in EqKillReg.\n                          inversion EqKillReg.\n                          rewrite <- H10 in H7.\n                          eapply W.add_3 in H7.\n                          2: {intro. discriminate. }\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H8.\n                      folds Const.t.\n                      rewrite H8.\n                      assert (W.In tu tuples). {\n                        eapply W.add_3 in H7.\n                        inv HeqKill.\n                        eapply W.filter_1 in H7; subst; trivial.\n                        eapply AveTuple.compat_bool_freeOfReg.\n                        intro; discriminate.\n                      }\n                      specialize (MATCH_AI tu H9). subst; trivial.                    \n                    }\n                  }\n                }\n                {\n                  destruct ai eqn:EqAi.\n                  { \n                    unfold AveLat.kill_reg in H. rewrite <- H. trivial.\n                  }\n                  {\n                    unfold AveLat.kill_reg in H. rewrite <- H.\n                    intros.\n                    rename t into r''.\n                    simpls. discriminate. \n                  }\n                  {\n                    unfold AveLat.kill_reg in H. rewrite <- H.\n                    intros.\n                    rename t into r''.\n                    des_ifH H.\n                    2: {\n                      intros.\n                      assert (W.In tu tuples). {\n                        eapply W.filter_1 in H7; trivial.\n                        eapply AveTuple.compat_bool_freeOfReg.\n                      }\n                      specialize (MATCH_AI tu H8).\n                      unfolds match_abstract_fact.\n                      destruct tu eqn:EqTu.\n                      { (** (r, e) *)\n                        assert (r <> reg). {\n                          destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            inv H.\n                            eapply W.filter_2 in H7. \n                            unfolds AveTuple.freeOfReg.\n                            eapply sflib__andb_split in H7.\n                            destruct H7.\n                            unfolds negb.\n                            destruct (reg =? r)%positive eqn:RegEq.\n                            try discriminate; eauto.\n                            rewrite Pos.eqb_sym in RegEq.\n                            eapply Pos.eqb_neq; eauto. \n                            eapply AveTuple.compat_bool_freeOfReg.\n                          }\n                        }\n\n                        inv H.\n\n                        pose proof H9.\n                        eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                        folds Const.t.\n                        rewrite H9. \n                        assert (~RegSet.mem r (Inst.regs_of_expr expr0)). {\n                          eapply W.filter_2 in H7.\n                          unfolds AveTuple.freeOfReg.\n                          intro.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          des_ifH H1; try discriminate; eauto.\n                          rewrite H0 in H2. discriminate.\n                          eapply (AveTuple.compat_bool_freeOfReg r).\n                        }\n                        eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr expr regs_src)) in H0.\n                          folds Const.t.\n                          rewrite <- H0.\n                          trivial.\n                      }\n                      { (** (r, x) *)\n                        assert (r <> reg). {\n                          destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            subst. discriminate. \n                          }\n                          {\n                            inv H.\n                            eapply W.filter_2 in H7. \n                            unfolds AveTuple.freeOfReg.\n                            unfolds negb.\n                            destruct (reg =? r)%positive eqn:RegEq.\n                            try discriminate; eauto.\n                            rewrite Pos.eqb_sym in RegEq.\n                            eapply Pos.eqb_neq; eauto. \n                            eapply AveTuple.compat_bool_freeOfReg.\n                          }\n                        }\n                        eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                        folds Const.t.\n                        rewrite H9.\n                        trivial.\n                      } \n                    }\n                    intros.\n                    pose proof (classic (tu = AveTuple.AExpr r'' (Inst.expr_reg r))) as IS_R_R'.\n                    destruct IS_R_R' as [IS_R_R' | NOT_R_R'].\n                    { (** (r', r) *)\n                      rewrite IS_R_R'.\n                      unfolds match_abstract_fact.\n                        unfolds AveLat.GetRegByExpr.\n                        pose proof Heqai'.\n                        remember  (RegFile.eval_expr e regs_src) as val.\n                        unfold RegFile.eval_expr. rewrite RegFun.add_spec_eq.\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn: KillReg; try discriminate.\n                        remember (W.choose (W.filter (AveTuple.isSameExpr opt_e) tuples0)) as Choose.\n                        destruct Choose eqn:EqChoose; try discriminate.\n                        inversion H2.\n                        eapply eq_sym in HeqChoose.\n                        eapply W.choose_1 in HeqChoose.\n                        pose proof HeqChoose.\n                        eapply W.filter_1 in HeqChoose.\n                        eapply W.filter_2 in H10.\n                        unfold AveTuple.isSameExpr in H10.\n                        destruct e0 eqn:EqE; try discriminate.\n                        eapply Inst.beq_expr_eq in H10.\n                        unfolds AveTuple.get_reg.\n                        inversion HeqGetReg.\n                        subst reg. \n                        assert (r'' <> r). {\n                          eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) (r:=r)in KillReg; eauto.\n                          unfolds AveTuple.get_reg. trivial.\n                        }\n                        subst val.\n                        inv STATE; try discriminate.\n                        rewrite Loc_add_neq; eauto.\n                        assert (regs_src r'' = RegFile.eval_expr expr regs_src). {\n                          clear - MATCH_AI' MATCH_AI HeqChoose KillReg.\n                          remember ((AveLat.opt_expr_with_ave expr (AveLat.CSet tuples0))) as opt_e.\n                          remember (AveTuple.AExpr r'' opt_e) as tu.\n                          unfolds AveLat.kill_reg. inversion KillReg.\n                          rewrite <- H0 in HeqChoose.\n                          eapply W.filter_1 in HeqChoose.\n                          specialize (MATCH_AI tu HeqChoose).\n                          rewrite Heqtu in MATCH_AI.\n                          rewrite MATCH_AI.\n                          eapply eq_sym.\n                          subst opt_e.\n                          eapply match_ai_implies_opt_expr_eval_eq; eauto.\n                          eapply ge_prsv_match_ai; eauto.\n                          { \n                            unfold AveAI.ge.\n                            unfold AveDS.L.ge.\n                            unfold W.Subset.\n                            intros.\n                            rewrite <- H0 in H.\n                            eapply W.filter_1 in H; eauto.\n                            eapply AveTuple.compat_bool_freeOfReg.\n                          }\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                        trivial.\n                        eapply AveTuple.compat_bool_isSameExpr.\n                        eapply AveTuple.compat_bool_isSameExpr.\n                    }\n                    (** old tu *)\n                    assert (W.In tu tuples). {\n                      eapply W.add_3 in H7.\n                      eapply W.filter_1 in H7; trivial.\n                      eapply AveTuple.compat_bool_freeOfReg.\n                      intro. rewrite H8 in NOT_R_R'. contradiction.\n                    }\n                    specialize (MATCH_AI tu H8).\n                    unfolds match_abstract_fact.\n                    destruct tu eqn:EqTu.\n                    { (** (r, e) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.add_3 in H7.\n                          2: {\n                            intro. \n                            rewrite H in NOT_R_R'.\n                            contradiction.\n                          }\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          eapply sflib__andb_split in H7.\n                          destruct H7.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      inv H.\n                      eapply W.add_3 in H7; eauto.\n                      pose proof H9.\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr0)). {\n                        eapply W.filter_2 in H7.\n                        unfolds AveTuple.freeOfReg.\n                        intro.\n                        eapply sflib__andb_split in H7.\n                        destruct H7.\n                        unfolds negb.\n                        des_ifH H1; try discriminate; eauto.\n                        rewrite H0 in H2. discriminate.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=(RegFile.eval_expr expr regs_src)) in H0.\n                        folds Const.t.\n                        rewrite <- H0.\n                        trivial.\n                    }\n                    { (** (r, x) *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H.\n                          eapply W.add_3 in H7.\n                          2: {\n                            intro. \n                            rewrite H in NOT_R_R'.\n                            contradiction.\n                          }\n                          eapply W.filter_2 in H7. \n                          unfolds AveTuple.freeOfReg.\n                          unfolds negb.\n                          destruct (reg =? r)%positive eqn:RegEq.\n                          try discriminate; eauto.\n                          rewrite Pos.eqb_sym in RegEq.\n                          eapply Pos.eqb_neq; eauto. \n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      eapply regs_add_neg with (r:=r) (v:=(RegFile.eval_expr expr regs_src)) (regs:=regs_src) in H9.\n                      folds Const.t.\n                      rewrite H9.\n                      trivial.\n                    } \n                  }\n                }\n              }\n              { \n                eapply subblk_same_succ in EqBlkSrc.\n                rewrite <- EqBlkSrc; trivial.\n                destruct ANALYSIS.\n                2: {\n                  intros.\n                  eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                  folds AveAI.b.\n                  rewrite H.\n                  eapply AveLat.ge_top.\n                }\n                eapply Ave_B.wf_transf_blk_getlast in H; eauto.\n                rewrite <- H. trivial.\n              }\n              \n          }\n          {\n            right. \n            splits; trivial.\n            destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n            apply eq_inj_implies_incr; trivial.\n            trivial.\n          }\n          {\n            rewrite <- H3; rewrite <- H5.\n            trivial.\n          }\n          {\n            rewrite <- H4; rewrite <- H5. \n            trivial.\n          }\n          {\n            rewrite <- H5.\n            trivial.\n          }\n        }\n      }\n  - (** call *)\n    (** call is init match state + jmp*)\n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n    pose proof Heqblk_tgt as TRSF.\n    eapply call_transformed_by_call in Heqblk_tgt.\n    pose proof STACK as STACK'.\n    pose proof ENTRY_BLK as ENTRY_BLK'.\n    (** code_src' ! f = Some (cdhp_src', f0) *)\n    assert (exists cdhp_src', code_src ! f = Some (cdhp_src', f0)). {\n      unfold cse_optimizer in OPT. inversion OPT. \n      rewrite <- H0 in FIND_FUNC.\n      unfolds transform_prog.\n      rewrite PTree.gmap in FIND_FUNC.\n      unfolds Coqlib.option_map.\n\n      destruct (code_src ! f) eqn:CodeSFunc; try discriminate.\n      inv FIND_FUNC.\n\n      unfold transform_func in H1.\n      destruct f1 eqn:EqF1.\n      destruct ((AveDS.analyze_program code_src succ AveLat.top Ave_B.transf_blk) ! f) eqn:Eq.\n      { \n        inv H1. eexists; eauto.\n      }\n      { \n        inv H1. eexists; eauto.\n      }\n    }\n    destruct H as (cdhp_src' & CDHP_SRC').\n    pose proof CDHP_SRC' as CDHP_SRC''.\n    pose proof (AveDS.wf_analyze_func code_src f cdhp_src' f0 (AveLat.top) Ave_B.transf_blk) as G.\n    apply G in CDHP_SRC''.\n    destruct CDHP_SRC'' as (acdhp & ACDHP).\n    assert (\n          transform_cdhp cdhp_src' acdhp = cdhp_tgt'\n          ). \n    {\n      clear G.\n      unfold cse_optimizer in OPT. inversion OPT. \n      unfolds transform_prog.\n      subst.\n      rewrite PTree.gmap in FIND_FUNC.\n      unfolds Coqlib.option_map.\n      destruct (code_src ! f) eqn:CodeSFunc; try discriminate.\n      inv FIND_FUNC.\n      unfold transform_func in H0. inv CDHP_SRC'. rewrite ACDHP in H0. inv H0. trivial. \n    }\n    rename H into TSF_CDHP'.\n    pose proof ACDHP as H.\n    eapply cse_wf_transform_cdhp_reverse with (cdhp_src := cdhp_src') in ENTRY_BLK; eauto.\n    eapply cse_wf_transform_cdhp_reverse in STACK; eauto.\n    destruct ENTRY_BLK as (b_src_entry, ENTRY_BLK).\n    destruct STACK as (b_src', CDHP_SRC).\n      exists {|\n          State.regs := RegFile.init;\n          State.blk := b_src_entry;\n          State.cdhp := cdhp_src';\n          State.cont := Continuation.stack regs_src b_src' cdhp_src cont_src;\n          State.code := code_src\n        |} lc_src sc_src mem_src (ThreadEvent.silent).\n      splits; eauto.\n      { (** call -> call  *)\n          eapply Thread.program_step_intro; simpls; eauto.\n          eapply State.step_call with (f0:=f0); eauto.\n      }\n      { (** match state *)\n        inversion LOCAL.\n        eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n        { (** invariant *)\n          rewrite <- H5. rewrite <- H6. trivial.\n        }\n        {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls. \n            eapply cse_match_frame_intro with (i:=0) (l:=f0) (enode:=f0) (analysis:=acdhp);  eauto.\n            { \n              pose proof TSF_CDHP'.\n              unfold AveDS.analyze_program in H.\n              rewrite PTree.gmap1 in H.\n              unfolds Coqlib.option_map.\n              rewrite CDHP_SRC' in H. simpls.\n              inversion H. \n              remember (AveDS.fixpoint_blk cdhp_src' succ f0 AveLat.top\n                  (fun (n : positive) (ai : AveDS.AI.t) =>\n                  match cdhp_src' ! n with\n                  | Some b => Ave_B.transf_blk ai b\n                  | None => AveDS.AI.Atom ai\n                  end)) as acdhp_partial.\n              destruct acdhp_partial eqn:acdhp_partial_eq.\n               - left.  trivial.\n               - right. trivial.  \n            }\n            { (** prove transform_blk *)\n              unfold AveAI.br_from_i; simpls.\n              unfold transform_cdhp in TSF_CDHP'.\n              rewrite <- TSF_CDHP' in ENTRY_BLK'.\n              rewrite PTree.gmap in ENTRY_BLK'; unfolds Coqlib.option_map; simpls.\n              rewrite ENTRY_BLK in ENTRY_BLK'. \n              inv ENTRY_BLK'. \n              unfold transform_blk'. \n              trivial. \n            }\n            {\n              unfolds match_abstract_interp; unfolds AveAI.br_from_i; simpls.\n              assert (AveAI.ge (AveAI.getFirst (acdhp !! f0)) AveLat.top).\n              {\n                eapply AveDS.analyze_func_entry; eauto.\n                eapply Ave_B.wf_transf_blk.\n              }\n              remember (AveAI.getFirst acdhp!!f0) as aentry.\n              - destruct aentry; eauto. \n                simpls.\n                intros.\n                pose proof W.empty_1. unfolds W.Empty. unfolds W.Subset.\n                eapply H0 in H8. \n                pose proof (H9 tu). contradiction.\n            }\n            {\n              unfold AveAI.br_from_i; simpls.\n              intros.\n              eapply AveDS.analyze_func_solution; eauto.\n              eapply Ave_B.wf_transf_blk.\n              eapply Ave_B.wf_transf_blk2.\n            }\n            {\n              {\n                unfolds AveAI.br_from_i; simpls.\n                assert (AveAI.ge (AveAI.getFirst (acdhp !! f0)) AveLat.top).\n                {\n                  eapply AveDS.analyze_func_entry; eauto.\n                  eapply Ave_B.wf_transf_blk.\n                }\n                unfold AveAI.ge in H0. unfold AveDS.L.ge in H0.\n                destruct (AveAI.getFirst acdhp !! f0) eqn:EqEntry; unfolds AveLat.top; try contradiction; eauto.\n                assert (W.Empty tuples). {\n                  unfolds W.Subset.\n                  pose proof (classic (exists a, W.In a tuples)). destruct H8; trivial.\n                  2: {\n                    unfold W.Empty.\n                    eapply not_ex_all_not. trivial.\n                  }\n                  destruct H8.\n                  specialize (H0 x H8).\n                  pose proof W.empty_1. unfolds W.Empty. \n                  specialize (H9 x). contradiction.\n                }\n                unfolds loc_fact_valid.\n                intros. \n                unfolds W.Empty. \n                specialize (H8 (AveTuple.AVar r loc)). \n                contradiction.\n              }\n            }\n            { (** match_cont *)\n              simpls.\n              eapply cse_match_cont_step; eauto.\n              intros.\n              eapply cse_match_frame_intro with (i:=0); eauto.\n              {\n                unfold transform_cdhp in Heqcdhp_tgt.\n                rewrite Heqcdhp_tgt in STACK'.\n                rewrite PTree.gmap in STACK'. unfolds option_map. rewrite CDHP_SRC in STACK'. inv STACK'; trivial.\n              }\n              { \n                pose proof (FIXPOINT fret).\n                assert (In fret (succ blk_src)). {\n                  unfold succ.\n                  unfold BBlock.get_out_fids.\n                  rewrite Heqblk_tgt.\n                  unfold In. left; trivial.\n                }\n                apply H0 in H8.\n                unfold AveAI.br_from_i. unfold AveAI.br_from_i_opt.\n                destruct ANALYSIS. \n                2: {\n                  rewrite H9.\n                  unfold \"!!\".\n                  simpls.\n                  rewrite PTree.gempty.\n                  unfolds AveAI.getFirst. \n                  eapply always_match_top.\n                }\n                pose proof H9 as TRSF_BLK.\n                eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H9; eauto.\n                rename Heqblk_tgt into BLK_SRC.\n                rewrite BLK_SRC in H9.\n                unfold Ave_B.transf_step in H9.\n                (** \n                  1. getFirst from i+1 <-> getLast\n                  2. MATCH_AI + AI.ge => MATCH_AI\n                *)\n                assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n                {\n                  eapply get_last_ablk; eauto.\n                  intros. \n                  rewrite BLK_SRC. \n                  intro.\n                  discriminate.\n                }\n                rewrite <- H10 in H8.\n                rewrite <- H9 in H8.\n                clear - MATCH_AI H8 H9 H10.\n                assert (AveAI.ge (AveLat.GetExprs (AveAI.getFirst (AveAI.br_from_i analysis !! l i))) (AveAI.getFirst (AveAI.br_from_i analysis !! l i))). {\n                  eapply AveLat.get_exprs_implies_ge; eauto.\n                }\n                assert (match_abstract_interp regs_src (Local.tview lc_src) mem_src\n                  (AveAI.getFirst analysis !! fret) lo). {\n                    eapply AveLat.ge_trans in H; eauto. \n                    eapply ge_prsv_match_ai; eauto.\n                }\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                assert (exists tuples, ai = AveLat.CSet tuples). {\n                  destruct ai eqn:EqAi.\n                  eapply never_match_bot in MATCH_AI; contradiction.\n                  eapply never_match_undef in MATCH_AI; contradiction.\n                  eexists; eauto.\n                }\n                eapply generalize_no_expr_match_ai; eauto.\n            }\n            {\n              intros.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H0; eauto.\n                folds AveAI.b.\n                rewrite H0.\n                eapply AveLat.ge_top.\n              }\n              unfolds AveAI.br_from_i; simpls.\n              eapply AveDS.analyze_func_solution' with (fentry_s:=enode) (eval := AveLat.top) (transf_blk := Ave_B.transf_blk); eauto.\n              eapply Ave_B.wf_transf_blk.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid; eauto.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              rename H0 into LOC_FACT_VALID.\n\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! fret (0)))).  {\n                destruct ANALYSIS.\n                2: {\n                  intros.\n                  eapply (AveAI.get_head_from_eval) with (l:=fret) in H0; eauto.\n                  folds AveAI.b.\n                  unfolds AveAI.br_from_i; simpls.\n                  rewrite H0.\n                  eapply top_is_loc_fact_valid.\n                }\n                assert (AveAI.ge (AveAI.getFirst (AveAI.br_from_i analysis !! fret (0))) (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))). {\n                  pose proof (FIXPOINT fret).\n                  assert (In fret (succ blk_src)). {\n                    unfold succ.\n                    unfold BBlock.get_out_fids.\n                    rewrite Heqblk_tgt.\n                    unfold In. left; trivial.\n                  }\n                  eapply H8 in H9.\n                  assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n                  {\n                    eapply get_last_ablk; eauto.\n                    intros.\n                    subst blk_src. \n                    intro.\n                    discriminate.\n                  }\n                  rewrite <- H10 in H9.\n                  trivial.\n                }\n                eapply ge_prsv_loc_fact_valid; eauto. \n              }\n              trivial.\n            }\n          }\n          {\n            subst; trivial.\n          }\n          {\n            subst; trivial.\n          }\n          {\n            subst; trivial.\n          }\n        }\n        {\n          right. \n          splits; trivial.\n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n        {\n          subst; trivial.\n        }\n        {\n          subst; trivial.\n        }\n        {\n          subst; trivial.\n        }\n      } \n  - (** ret *) \n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n    pose proof Heqblk_tgt as TRSF.\n    eapply ret_transformed_by_ret in Heqblk_tgt.\n\n    inversion MATCH_CONT.\n    {\n      destruct DONE; try discriminate.\n    }\n      exists {|\n          State.regs := regs_s;\n          State.blk := blk_s;\n          State.cdhp := cdhp_s;\n          State.cont := cont_src';\n          State.code := code_src\n        |} lc_src sc_src mem_src (ThreadEvent.silent).\n      splits; eauto.\n      { (** ret -> ret  *)\n          eapply Thread.program_step_intro; simpls; eauto.\n          eapply State.step_ret; eauto.\n      }\n      { (** match state *)\n        inversion LOCAL.\n        eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n        { (** invariant *)\n          rewrite <- H5. rewrite <- H4. trivial.\n        }\n        {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            pose proof (FRAME_MATCH (Local.tview lc_src) mem_src).\n            rewrite BLK0 in STATE.\n            inv STATE; try discriminate; eauto. \n            inv CONT_T.\n            trivial.\n            { (** match_cont *)\n              simpls.\n              inv CONT_T.\n              trivial.\n            }\n        }\n        {\n          right. \n          splits; trivial.\n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n        {\n          rewrite <- H3; rewrite <- H5.\n          trivial.\n        }\n        {\n          rewrite <- H4; rewrite <- H5. \n          trivial.\n        }\n        {\n          rewrite <- H5.\n          trivial.\n        }\n      } \n  - (** jmp *)\n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n    pose proof Heqblk_tgt as TRSF.\n    eapply jmp_transformed_by_jmp in Heqblk_tgt.\n    pose proof TGT as TGT'.\n    eapply cse_wf_transform_cdhp_reverse in TGT; eauto.\n    destruct TGT as (b_src', CDHP_SRC).\n      exists {|\n          State.regs := regs_tgt';\n          State.blk := b_src';\n          State.cdhp := cdhp_src;\n          State.cont := cont_src;\n          State.code := code_src\n        |} lc_src sc_src mem_src (ThreadEvent.silent).\n      splits; eauto.\n      { (** jmp -> jmp  *)\n          eapply Thread.program_step_intro; simpls; eauto.\n          eapply State.step_jmp; eauto.\n      }\n      { (** match state *)\n        inversion LOCAL.\n        eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n        { (** invariant *)\n          rewrite <- H5. rewrite <- H4. trivial.\n        }\n        {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=0); eauto.\n            { \n              clear - Heqcdhp_tgt TGT' CDHP_SRC.\n              unfold transform_cdhp in Heqcdhp_tgt.\n              rewrite Heqcdhp_tgt in TGT'.\n              rewrite PTree.gmap in TGT'. unfolds option_map. rewrite CDHP_SRC in TGT'. inv TGT'; trivial.\n            }\n            { \n              pose proof (FIXPOINT f).\n              assert (In f (succ blk_src)). {\n                unfold succ.\n                unfold BBlock.get_out_fids.\n                rewrite Heqblk_tgt.\n                unfold In. left; trivial.\n              }\n              apply H in H7.\n              unfold AveAI.br_from_i. unfold AveAI.br_from_i_opt.\n              destruct ANALYSIS. \n              2: {\n                rewrite H8.\n                unfold \"!!\".\n                simpls.\n                rewrite PTree.gempty.\n                unfolds AveAI.getFirst. \n                eapply always_match_top.\n              }\n              pose proof H8 as TRSF_BLK.\n              eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H8; eauto.\n              rename Heqblk_tgt into BLK_SRC.\n              rewrite BLK_SRC in H8.\n              unfold Ave_B.transf_step in H8.\n              (** \n                1. getFirst from i+1 <-> getLast\n                2. MATCH_AI + AI.ge => MATCH_AI\n              *)\n              assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n              {\n                eapply get_last_ablk; eauto.\n                intros. \n                rewrite BLK_SRC. \n                intro.\n                discriminate.\n              }\n              rewrite <- H9 in H7.\n              rewrite <- H8 in H7.\n              clear - MATCH_AI H7.\n              eapply ge_prsv_match_ai; eauto. \n            }\n            {\n              intros.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              unfolds AveAI.br_from_i; simpls.\n              eapply AveDS.analyze_func_solution' with (fentry_s:=enode) (eval := AveLat.top) (transf_blk := Ave_B.transf_blk); eauto.\n              eapply Ave_B.wf_transf_blk.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! f (0)))).  {\n                destruct ANALYSIS.\n                2: {\n                  intros.\n                  eapply (AveAI.get_head_from_eval) with (l:=f) in H; eauto.\n                  folds AveAI.b.\n                  unfolds AveAI.br_from_i; simpls.\n                  rewrite H.\n                  eapply top_is_loc_fact_valid.\n                }\n                assert (AveAI.ge (AveAI.getFirst (AveAI.br_from_i analysis !! f (0))) (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))). {\n                  pose proof (FIXPOINT f).\n                  assert (In f (succ blk_src)). {\n                    unfold succ.\n                    unfold BBlock.get_out_fids.\n                    rewrite Heqblk_tgt.\n                    unfold In. left; trivial.\n                  }\n                  eapply H7 in H8.\n                  assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n                  {\n                    eapply get_last_ablk; eauto.\n                    intros.\n                    subst blk_src. \n                    intro.\n                    discriminate.\n                  }\n                  rewrite <- H9 in H8.\n                  trivial.\n                }\n                eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H; eauto.\n                rename Heqblk_tgt into BLK_SRC.\n                rewrite BLK_SRC in H.\n                unfold Ave_B.transf_step in H.\n                rewrite <- H in H7.\n                eapply ge_prsv_loc_fact_valid; eauto. \n              }\n              trivial.\n            }\n        }\n        {\n          right. \n          splits; trivial.\n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n        {\n          rewrite <- H3; rewrite <- H5.\n          trivial.\n        }\n        {\n          rewrite <- H4; rewrite <- H5. \n          trivial.\n        }\n        {\n          rewrite <- H5.\n          trivial.\n        }\n      } \n  - (** be *)\n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply eq_sym in Heqblk_tgt.\n    rewrite BLK0 in Heqblk_tgt.\n\n    eapply be_transformed_by_be in Heqblk_tgt.\n    destruct BRANCH as [(TGT & COND) | (TGT & COND)].\n    {\n      pose proof TGT as TGT'.\n      eapply cse_wf_transform_cdhp_reverse in TGT; eauto.\n      destruct TGT as (b_src', CDHP_SRC).\n        exists {|\n            State.regs := regs_tgt';\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_src sc_src mem_src (ThreadEvent.silent).\n        splits; eauto.\n        { (** skip -> skip  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_be; eauto.\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H5. rewrite <- H4. trivial.\n          }\n          {\n              eapply cse_match_local_state_intro; \n              try rewrite <- H3; eauto.\n              eapply cse_match_rtl_state_intro; eauto.\n              simpls.\n              eapply cse_match_frame_intro with(i:=0); eauto.\n              { \n              clear - Heqcdhp_tgt TGT' CDHP_SRC.\n              unfold transform_cdhp in Heqcdhp_tgt.\n              rewrite Heqcdhp_tgt in TGT'.\n              rewrite PTree.gmap in TGT'. unfolds option_map. rewrite CDHP_SRC in TGT'. inv TGT'; trivial.\n            }\n            {\n              pose proof (FIXPOINT f1).\n              assert (In f1 (succ blk_src)). {\n                unfold succ.\n                unfold BBlock.get_out_fids.\n                rewrite Heqblk_tgt.\n                unfold In. left; trivial.\n              }\n              apply H in H7.\n              unfold AveAI.br_from_i. unfold AveAI.br_from_i_opt.\n              destruct ANALYSIS. \n              2: {\n                rewrite H8.\n                unfold \"!!\".\n                simpls.\n                rewrite PTree.gempty.\n                unfolds AveAI.getFirst. \n                eapply always_match_top.\n              }\n              pose proof H8 as TRSF_BLK.\n              eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H8; eauto.\n              rename Heqblk_tgt into BLK_SRC.\n              rewrite BLK_SRC in H8.\n              unfold Ave_B.transf_step in H8.\n              (** \n                1. getFirst from i+1 <-> getLast\n                2. MATCH_AI + AI.ge => MATCH_AI\n              *)\n              assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n              {\n                eapply get_last_ablk; eauto.\n                intros. \n                rewrite BLK_SRC. \n                intro.\n                discriminate.\n              }\n              rewrite <- H9 in H7.\n              rewrite <- H8 in H7.\n              clear - MATCH_AI H7.\n              eapply ge_prsv_match_ai; eauto. \n            }\n            {\n              intros.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              unfolds AveAI.br_from_i; simpls.\n              eapply AveDS.analyze_func_solution' with (fentry_s:=enode) (eval := AveLat.top) (transf_blk := Ave_B.transf_blk); eauto.\n              eapply Ave_B.wf_transf_blk.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! f1 (0)))).  {\n                destruct ANALYSIS.\n                2: {\n                  intros.\n                  eapply (AveAI.get_head_from_eval) with (l:=f1) in H; eauto.\n                  folds AveAI.b.\n                  unfolds AveAI.br_from_i; simpls.\n                  rewrite H.\n                  eapply top_is_loc_fact_valid.\n                }\n                assert (AveAI.ge (AveAI.getFirst (AveAI.br_from_i analysis !! f1 (0))) (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))). {\n                  pose proof (FIXPOINT f1).\n                  assert (In f1 (succ blk_src)). {\n                    unfold succ.\n                    unfold BBlock.get_out_fids.\n                    rewrite Heqblk_tgt.\n                    unfold In. left; trivial.\n                  }\n                  eapply H7 in H8.\n                  assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n                  {\n                    eapply get_last_ablk; eauto.\n                    intros.\n                    subst blk_src. \n                    intro.\n                    discriminate.\n                  }\n                  rewrite <- H9 in H8.\n                  trivial.\n                }\n                eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H; eauto.\n                rename Heqblk_tgt into BLK_SRC.\n                rewrite BLK_SRC in H.\n                unfold Ave_B.transf_step in H.\n                rewrite <- H in H7.\n                eapply ge_prsv_loc_fact_valid; eauto. \n              }\n              trivial.\n            }\n          }\n          {\n            right. \n            splits; trivial.\n            destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n            apply eq_inj_implies_incr; trivial.\n            trivial.\n          }\n          {\n            rewrite <- H3; rewrite <- H5.\n            trivial.\n          }\n          {\n            rewrite <- H4; rewrite <- H5. \n            trivial.\n          }\n          {\n            rewrite <- H5.\n            trivial.\n          }\n        } \n    }\n    { (** fixme: equal proof *)\n      pose proof TGT as TGT'.\n      eapply cse_wf_transform_cdhp_reverse in TGT; eauto.\n      destruct TGT as (b_src', CDHP_SRC).\n        exists {|\n            State.regs := regs_tgt';\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_src sc_src mem_src (ThreadEvent.silent).\n        splits; eauto.\n        { (** skip -> skip  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_be; eauto.\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H5. rewrite <- H4. trivial.\n          }\n          {\n              eapply cse_match_local_state_intro; \n              try rewrite <- H3; eauto.\n              eapply cse_match_rtl_state_intro; eauto.\n              simpls.\n              eapply cse_match_frame_intro with(i:=0); eauto.\n              { \n              clear - Heqcdhp_tgt TGT' CDHP_SRC.\n              unfold transform_cdhp in Heqcdhp_tgt.\n              rewrite Heqcdhp_tgt in TGT'.\n              rewrite PTree.gmap in TGT'. unfolds option_map. rewrite CDHP_SRC in TGT'. inv TGT'; trivial.\n            }\n            {\n              pose proof (FIXPOINT f2).\n              assert (In f2 (succ blk_src)). {\n                unfold succ.\n                unfold BBlock.get_out_fids.\n                rewrite Heqblk_tgt.\n                unfold In. right; left; trivial.\n              }\n              apply H in H7.\n              unfold AveAI.br_from_i. unfold AveAI.br_from_i_opt.\n              destruct ANALYSIS. \n              2: {\n                rewrite H8.\n                unfold \"!!\".\n                simpls.\n                rewrite PTree.gempty.\n                unfolds AveAI.getFirst. \n                eapply always_match_top.\n              }\n              pose proof H8 as TRSF_BLK.\n              eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H8; eauto.\n              rename Heqblk_tgt into BLK_SRC.\n              rewrite BLK_SRC in H8.\n              unfold Ave_B.transf_step in H8.\n              (** \n                1. getFirst from i+1 <-> getLast\n                2. MATCH_AI + AI.ge => MATCH_AI\n              *)\n              assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n              {\n                eapply get_last_ablk; eauto.\n                intros. \n                rewrite BLK_SRC. \n                intro.\n                discriminate.\n              }\n              rewrite <- H9 in H7.\n              rewrite <- H8 in H7.\n              clear - MATCH_AI H7.\n              eapply ge_prsv_match_ai; eauto. \n            }\n            {\n              intros.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H; eauto.\n                folds AveAI.b.\n                rewrite H.\n                eapply AveLat.ge_top.\n              }\n              unfolds AveAI.br_from_i; simpls.\n              eapply AveDS.analyze_func_solution' with (fentry_s:=enode) (eval := AveLat.top) (transf_blk := Ave_B.transf_blk); eauto.\n              eapply Ave_B.wf_transf_blk.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! f2 (0)))).  {\n                destruct ANALYSIS.\n                2: {\n                  intros.\n                  eapply (AveAI.get_head_from_eval) with (l:=f2) in H; eauto.\n                  folds AveAI.b.\n                  unfolds AveAI.br_from_i; simpls.\n                  rewrite H.\n                  eapply top_is_loc_fact_valid.\n                }\n                assert (AveAI.ge (AveAI.getFirst (AveAI.br_from_i analysis !! f2 (0))) (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))). {\n                  pose proof (FIXPOINT f2).\n                  assert (In f2 (succ blk_src)). {\n                    unfold succ.\n                    unfold BBlock.get_out_fids.\n                    rewrite Heqblk_tgt.\n                    unfold In. right; left; trivial.\n                  }\n                  eapply H7 in H8.\n                  assert (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)) =  (AveAI.getLast (AveAI.br_from_i analysis !! l i))).\n                  {\n                    eapply get_last_ablk; eauto.\n                    intros.\n                    subst blk_src. \n                    intro.\n                    discriminate.\n                  }\n                  rewrite <- H9 in H8.\n                  trivial.\n                }\n                eapply Ave_B.wf_transf_blk_step with (blk:=blk) (i:=i) (blk_part := blk_src) in H; eauto.\n                rename Heqblk_tgt into BLK_SRC.\n                rewrite BLK_SRC in H.\n                unfold Ave_B.transf_step in H.\n                rewrite <- H in H7.\n                eapply ge_prsv_loc_fact_valid; eauto. \n              }\n              trivial.\n            }\n          }\n          {\n            right. \n            splits; trivial.\n            destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n            apply eq_inj_implies_incr; trivial.\n            trivial.\n          }\n          {\n            rewrite <- H3; rewrite <- H5.\n            trivial.\n          }\n          {\n            rewrite <- H4; rewrite <- H5. \n            trivial.\n          }\n          {\n            rewrite <- H5.\n            trivial.\n          }\n        } \n    }\nQed.\n\n(** Correctness of non-atomic memory access: na read & na write*)\nTheorem cse_match_state_preserving_na_access:\n  forall te lo inj st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src b st_tgt' lc_tgt' sc_tgt' mem_tgt', \n    Thread.program_step te lo \n        (@Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n        (@Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') \n    -> \n    ThreadEvent.is_na_access te \n    ->   \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n      (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b)\n    -> \n      (exists st_src' lc_src' sc_src' mem_src',\n          Thread.program_step te lo (@Thread.mk rtl_lang st_src lc_src sc_src mem_src) \n                                    (@Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') \n          /\\\n          (cse_match_state inj lo \n          (Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') false)\n      ).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt) eqn:EqStTgt.\n  destruct st_tgt' as (regs_tgt', blk_tgt', cdhp_tgt', cont_tgt', code_tgt') eqn:EqStTgt'.\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc; simpls.\n  unfold ThreadEvent.is_na_access in H0.\n  destruct te; try contradiction; eauto.\n  { (** read *)\n    pose proof (nonatomic_or_atomic ord) as ORD; \n    destruct ORD. \n    2:{destruct ord; subst; try contradiction. }\n    rewrite H2 in H0; try contradiction; eauto.\n    inversion H. unfolds ThreadEvent.get_program_event.\n    inv STATE.\n    { (** non-atomic read: Inst.load r loc ord *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      *              \n          exists {|\n            State.regs :=  RegFun.add r val regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt'.\n        splits; eauto.\n        { (** load -> load  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_load; eauto.\n            eapply load_transformed_inst_by_load in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL.\n            rewrite <- H12; rewrite MEM_EQ_START.  \n            rewrite <- H11.\n            rewrite SC_EQ_START.\n            eapply Local.step_read; eauto.\n            rewrite <- H12 in LOCAL0; rewrite MEM_EQ_START in LOCAL0. \n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H14. \n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H12.\n            unfold cse_invariant; simpls. splits; eauto.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            { rewrite REG_EQ. trivial. }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H15 in H14.\n                folds AveAI.b.\n                rewrite H14.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H14; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H14.\n              pose proof TRSF_INST as TRSF_INST'.\n              eapply load_transformed_inst_by_load in TRSF_INST; eauto.\n              rewrite TRSF_INST in H14.\n              unfolds Ave_I.transf.\n              destruct ord eqn:EqOrd; try discriminate; eauto.\n                rewrite <- H14.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.GetRegByLoc loc (AveLat.kill_reg ai r)) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  unfolds AveLat.GetRegByLoc.\n                  rewrite Heqai'.\n                  rewrite Heqai' in H14.\n                  intros.\n                  assert (tu = (AveTuple.AVar r loc)). {\n                    eapply W.singleton_1 in H2. subst; trivial.\n                  }\n                  unfold match_abstract_fact. rewrite H3. \n                  splits; eauto.\n                  {\n                    subst.\n                    inv LOCAL0; simpls.\n                    unfolds Ordering.mem_ord_match. \n                    destruct (lo loc) eqn:EqLo.\n                    destruct LO as [A|[A|A]]; try discriminate.\n                    trivial.\n                  }\n                  {\n                    subst.\n                    inv LOCAL0; simpls.\n                    rewrite MEM_EQ_START in GET.\n                    exists ts from released. \n                    splits; eauto.\n                    3: {\n                      pose proof RegFun.add_spec_eq.\n                      unfold RegFun.find in *.\n                      rewrite H3. trivial.\n                    }\n                    { (** pln view *)\n                      inv READABLE.\n                      replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n                      replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n                      unfold View.singleton_ur_if.\n                      unfold View.bot; simpls.\n                      rewrite TimeMap.join_bot.\n                      rewrite TimeMap.join_bot.\n                      trivial.\n                    }\n                    { (** pln view *)\n                      inv READABLE.\n                      replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n                      replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n                      simpls.\n                      rewrite TimeMap.join_bot.\n                      unfold TimeMap.singleton.\n                      eapply TimeMap.time_le_TimeMap_join_r.\n                      pose proof LocFun.add_spec_eq. unfold LocFun.find in *.\n                      rewrite H3.\n                      eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1.\n                    }\n                  }\n                }\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai''.\n                destruct ai'' eqn:EqAi''.\n                {subst. rewrite H14. \n                  destruct (AveLat.kill_reg (AveLat.CSet tuples) r ) eqn:Eq1; \n                  destruct (AveLat.GetRegByLoc loc (AveLat.kill_reg (AveLat.CSet tuples) r)) eqn:Eq2; try discriminate;  eauto.\n                  destruct (AveLat.GetRegByLoc loc (AveLat.CSet tuples0)) eqn:Eq3; try  discriminate; eauto.\n                  destruct (AveLat.GetRegByLoc loc (AveLat.CSet tuples0)) eqn:Eq3; try  discriminate; eauto.\n                }\n                {subst. rewrite H14. \n                  destruct (AveLat.kill_reg (AveLat.CSet tuples) r ) eqn:Eq1; \n                  destruct (AveLat.GetRegByLoc loc (AveLat.kill_reg (AveLat.CSet tuples) r)) eqn:Eq2; try discriminate;  eauto.\n                  destruct (AveLat.GetRegByLoc loc (AveLat.CSet tuples0)) eqn:Eq3; try  discriminate; eauto.\n                  destruct (AveLat.GetRegByLoc loc (AveLat.CSet tuples0)) eqn:Eq3; try  discriminate; eauto.\n                }\n                rewrite H14.\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  destruct ai' eqn:EqAi'.\n                  { \n                    rename t into reg'.\n                    pose proof (classic (tu = AveTuple.AExpr reg' (Inst.expr_reg r))).\n                    destruct H3.\n                    { (** (r', r) *)\n                      rewrite H3 in EqTu.\n                      inversion EqTu.\n                      rewrite <- H5.\n                      unfolds transform_inst.\n                      pose proof Heqai'.\n                      eapply AveLat.getByLoc_implies_valid_tuple in Heqai'; eauto.\n                      eapply W.filter_1 in Heqai'.\n                      2: {eapply AveTuple.compat_bool_freeOfReg. }\n                      remember (AveLat.GetRegByLoc loc (AveLat.CSet tuples)) as tmp.\n                      destruct tmp eqn:EqTmp; try discriminate; eauto.\n                      eapply AveLat.getByLoc_none_implies_kill_none with (r:=r) in Heqtmp; eauto.\n                      rewrite <- Heqtmp in H4.\n                      try discriminate.\n                    } \n                    {\n                      (** similar proof *)\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H14.\n                          eapply W.add_3 in H2.\n                          2: {\n                            intro. rewrite H4 in H3. try contradiction. \n                          }\n                          remember (AveLat.kill_reg (AveLat.CSet tuples) r) as _ai.\n                          remember (AveTuple.AExpr reg expr) as tu.\n                          eapply AveLat.mem_of_kill_reg_implies_neq with (tuples':=tuples1) (tuples:=tuples) (r:=r) in H2; eauto.\n                          unfolds AveTuple.get_reg. rewrite Heqtu in H2.  \n                          intro. rewrite H4 in H2. contradiction. \n                        }\n                      }\n                      inv H14.\n                      eapply W.add_3 in H2; eauto.\n                      \n                      pose proof H2.\n                      eapply W.filter_1 in H2.\n                      pose proof (MATCH_AI (AveTuple.AExpr reg expr)).\n                      apply H6 in H2.\n                      pose proof H4.\n                      eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n                      rewrite H4. \n                      assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                        eapply W.filter_2 in H5.\n                        unfolds AveTuple.freeOfReg.\n                        intro.\n                        eapply sflib__andb_split in H5.\n                        destruct H5.\n                        unfolds negb.\n                        des_ifH H5; try discriminate; eauto.\n                        rewrite H9 in H10. discriminate.\n                        eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=val) in H9.\n                      folds Const.t.\n                      rewrite <- H9.\n                      trivial.\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                  }\n                  { \n                    assert (r <> reg). {\n                      destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        subst. discriminate. \n                      }\n                      {\n                        inv H14.\n                        eapply W.add_3 in H2.\n                        2: {\n                          intro. try discriminate.\n                        }\n                        remember (AveLat.kill_reg (AveLat.CSet tuples) r) as _ai.\n                        remember (AveTuple.AExpr reg expr) as tu.\n                        eapply AveLat.mem_of_kill_reg_implies_neq with (tuples':=tuples1) (tuples:=tuples) (r:=r) in H2; eauto.\n                        unfolds AveTuple.get_reg. rewrite Heqtu in H2.  \n                        intro. rewrite H3 in H2. contradiction. \n                      }\n                    }\n                    inv H14.\n                    eapply W.add_3 in H2; eauto.\n                    2: {\n                      intro. discriminate.\n                    }\n                    pose proof H2.\n                    eapply W.filter_1 in H2.\n                    pose proof (MATCH_AI (AveTuple.AExpr reg expr)).\n                    apply H5 in H2.\n                    pose proof H3.\n                    eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H3.\n                    rewrite H3. \n                    assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                      eapply W.filter_2 in H4.\n                      unfolds AveTuple.freeOfReg.\n                      intro.\n                      eapply sflib__andb_split in H4.\n                      destruct H4.\n                      unfolds negb.\n                      des_ifH H4; try discriminate; eauto.\n                      rewrite H8 in H9. discriminate.\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=val) in H8.\n                    folds Const.t.\n                    rewrite <- H8.\n                    trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  pose proof (classic (tu = AveTuple.AVar r loc)).\n                  destruct H3.\n                  { (** (r, x) is newly inserted *)\n                    splits; eauto.\n                    { (** lo loc = non-atomic *)\n                      inv LOCAL0.\n                      unfolds Ordering.mem_ord_match.\n                      inv H3.\n                      destruct (lo loc); trivial.\n                      destruct LO as [A|[A|A]]; try discriminate.\n                    }\n                    {\n                      rewrite EqTu in H3. \n                      inversion H3.\n                      inv LOCAL.\n                      inv LOCAL1. simpls.\n                      inv READABLE. \n                      exists ts from released.\n                      replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n                      replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n                      unfolds View.singleton_ur_if.\n                      unfolds View.singleton_rw. simpls.\n                      do 3 rewrite TimeMap.join_bot.\n                      unfold TimeMap.singleton.\n                      splits; eauto.\n                      eapply TimeMap.time_le_TimeMap_join_r.\n                      pose proof LocFun.add_spec_eq. unfold LocFun.find in *.\n                      rewrite H4.\n                      eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1.\n                      assert (RegFun.add r val regs_src r = val). {\n                        pose proof RegFun.add_spec_eq.\n                        unfold RegFun.find in *.\n                        rewrite H4. trivial.\n                       }\n                      rewrite H4. \n                      rewrite <- MEM_EQ_START.\n                      trivial.\n                    }\n                  }\n                  { (** (r, x) is old *)\n                    rewrite EqTu in H3. \n                    assert (W.In tu tuples). {\n                      destruct ai'.\n                      {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H14.\n                          eapply W.add_3 in H2; eauto.\n                          2: { intro. discriminate. }\n                          unfolds AveLat.kill_reg.\n                          inv EqKillReg.\n                          eapply W.filter_1 in H2. trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                      {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          inv H14.\n                          eapply W.add_3 in H2; eauto.\n                          inv EqKillReg.\n                          eapply W.filter_1 in H2. trivial.\n                          eapply AveTuple.compat_bool_freeOfReg.\n                        }\n                      }\n                    }\n                    pose proof (MATCH_AI tu). apply H5 in H4.\n                    rewrite EqTu in H4. \n                    assert (regs_src reg = RegFun.add r val regs_src reg). {\n                      apply eq_sym.\n                      assert (r <> reg). {\n                        destruct (AveLat.kill_reg (AveLat.CSet tuples) r) eqn:EqKillReg.\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          subst. discriminate. \n                        }\n                        {\n                          destruct ai' eqn:EqAi'.\n                          {\n                            rename t into reg'.\n                            \n                            inv H14.\n                            eapply W.add_3 in H2; eauto.\n                            intro.\n                            rewrite <- H6 in H2.\n                            eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) in EqKillReg; eauto.\n                            unfolds AveTuple.get_reg.\n                            trivial.\n                            intro. try discriminate.\n                          }\n                          {\n                            \n                            inv H14.\n                            eapply W.add_3 in H2; eauto.\n                            intro.\n                            rewrite <- H6 in H2.\n                            eapply AveLat.mem_of_kill_reg_implies_neq with (tuples:=tuples) in EqKillReg; eauto.\n                            unfolds AveTuple.get_reg.\n                            trivial.\n                          }\n                          \n\n                        }\n                      }\n                      eapply regs_add_neg; eauto.\n                    }\n                    rewrite <- H6.\n                    destruct H4.\n                    splits; eauto.\n                    destruct H8 as (t & f & R & PLN & RLX & MSG).\n                    exists t f R. splits; eauto. \n                    { (** plain *)\n                      inv LOCAL0. simpls.\n                      replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n                      replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n                      unfolds View.singleton_ur_if.\n                      unfolds View.singleton_rw. simpls.\n                      do 2 rewrite TimeMap.join_bot.\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite H8. trivial.\n                    }\n                    { (** rlx *)\n                      inv LOCAL0. simpls.\n                      replace (Ordering.le Ordering.acqrel Ordering.plain) with false; trivial.\n                      replace (Ordering.le Ordering.relaxed Ordering.plain) with false; trivial.\n                      unfolds View.singleton_ur_if.\n                      unfolds View.singleton_rw. simpls.\n                      rewrite TimeMap.join_bot.\n                      unfold TimeMap.singleton.\n                      eapply TimeMap.time_le_TimeMap_join_l.\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite H8. trivial.\n                    }\n                  }\n              }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H14; eauto.\n                folds AveAI.b.\n                rewrite H14.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H14; eauto.\n              rewrite <- H14. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n            }\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              eapply incr_inj_refl.\n            }\n        }\n        { \n          right.\n          splits; eauto. \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n          (* unfold eq_inj; intros; tauto. *)\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        { \n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        }\n    }\n    { (** non-atomic cas is invalid *)\n      contradiction.\n    }\n  }\n  { (** na write *)\n    pose proof (nonatomic_or_atomic ord) as ORD; \n    destruct ORD. \n    2:{destruct ord; subst; try contradiction. }\n    rewrite H2 in H0; try contradiction; eauto.\n    inversion H. unfolds ThreadEvent.get_program_event.\n    inv STATE.\n    { (** non-atomic read: Inst.load r loc ord *)\n    inversion H1; simpls.\n    inversion INVARIANT. \n    inversion MATCH_LOCAL.\n    inversion MATCH_RTL_STATE; simpls.\n    rename H2 into SC_EQ_START.\n    destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n    inversion MATCH_FRAME; simpls.\n\n    remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n    remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n    eapply transform_blk_induction' in TRANSF_BLK; eauto.\n    destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n    destruct TRSF as (TRSF_INST & TRSF_BLK).\n    * \n      exists {|\n          State.regs :=  regs_src;\n          State.blk := b_src';\n          State.cdhp := cdhp_src;\n          State.cont := cont_src;\n          State.code := code_src\n        |} lc_tgt' sc_tgt' mem_tgt'.\n      splits; eauto.\n      { (** load -> load  *)\n          eapply Thread.program_step_intro; simpls; eauto.\n          eapply State.step_store; eauto.\n          eapply store_transformed_inst_by_store in TRSF_INST; eauto.\n          rewrite <- TRSF_INST; trivial.\n          {subst; eauto. }\n          inversion LOCAL.\n          inversion LOCAL0.\n          eapply Local.step_write with (kind := kind); eauto.\n          rewrite <- H12 in LOCAL0; rewrite MEM_EQ_START in LOCAL0. \n          assert (lc_tgt = lc_src). {\n            eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n          }\n          rewrite <- H12.\n          rewrite <- SC_EQ_START.\n          rewrite <- H15.\n          trivial. \n      }\n      { (** match state *)\n        inversion LOCAL.\n        remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''. \n\n        eapply cse_match_state_intro with(inj':=inj''); simpls; eauto.\n        { (** invariant *)\n          rewrite <- H12.\n          { (** invariant *)\n            unfold cse_invariant; splits; simpls; eauto.\n            unfolds eq_ident_mapping.\n            destruct INJ_MAP_MEM_TGT.\n            inversion LOCAL0. inversion WRITE.\n            eapply prm_keeps_mem_inj_dom_eq with (inj' := inj'') (mem' := mem_tgt') in H15; eauto.\n            2: {\n              intro. discriminate.\n            }\n            splits; eauto.\n            intros.\n            rewrite Heqinj'' in H17.\n            des_ifH H17; simpls.\n            {\n              destruct a. subst. \n              inv H17. \n              eapply eq_refl.\n            }\n            apply H16 in H17. trivial.\n          }\n        }\n        {\n          eapply cse_match_local_state_intro; \n          try rewrite <- H3; eauto.\n          2: {eapply eq_refl. }\n          eapply cse_match_rtl_state_intro; eauto.\n          simpls.\n          eapply cse_match_frame_intro with(i:=i+1); eauto.\n          rewrite EqBlkSrc in PARTIAL_BLK.\n          {\n            rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n          }\n          rewrite EqBlkSrc in PARTIAL_BLK.\n          eapply bb_from_i_plus_one; eauto.\n          {\n              rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n              rewrite AI_BLK; trivial. \n          }\n          rewrite <- AI_BLK in TRSF_BLK.\n          rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n          { (** match ai *)\n            destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H16 in H15.\n                folds AveAI.b.\n                rewrite H15.\n                eapply always_match_top.\n              }\n            eapply Ave_B.wf_transf_blk_step in H15; eauto.\n            unfolds Ave_B.transf_step.\n            rewrite EqBlkSrc in H15.\n            pose proof TRSF_INST as TRSF_INST'.\n            eapply store_transformed_inst_by_store in TRSF_INST; eauto.\n            rewrite TRSF_INST in H15.\n            unfolds Ave_I.transf.\n            destruct ord eqn:EqOrd; try discriminate; eauto.\n            (* relaxed *)  \n              rewrite <- H15.\n              rewrite <- AI_BLK in MATCH_AI.\n              subst.\n              unfolds match_abstract_interp.\n              remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n              remember (AveLat.kill_var ai loc) as ai'.\n              destruct ai eqn:EqAi.\n              {\n                unfolds AveLat.kill_reg.\n                rewrite Heqai'. trivial.\n              }\n              {\n                unfolds AveLat.kill_reg.\n                rewrite Heqai'. trivial.\n              }\n              \n              destruct ai' eqn:EqAi'; trivial.\n              {\n                unfold AveLat.kill_var in Heqai'. \n                destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n              }\n              {\n                unfold AveLat.kill_var in Heqai'. \n                destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n              }\n              intros.\n              unfolds match_abstract_fact.\n              assert (W.In tu tuples). {\n                unfolds AveLat.kill_var.\n                destruct (AveLat.GetExprs (AveLat.CSet tuples)) eqn:EqGetExpr.\n                {\n                  inv Heqai'.\n                  eapply W.filter_1 in H2; trivial.\n                  eapply AveTuple.compat_bool_isNotSameLoc.\n                }\n                {\n                  inv Heqai'.\n                  eapply W.filter_1 in H2; trivial.\n                  eapply AveTuple.compat_bool_isNotSameLoc.\n                }\n                {\n                  inv Heqai'.\n                  eapply W.union_1 in H2.\n                  destruct H2.\n                  {\n                    unfolds AveLat.GetExprs. inv EqGetExpr.\n                    eapply W.filter_1 in H2; trivial.\n                    eapply AveTuple.compat_bool_isExpr.\n                  }\n                  eapply W.filter_1 in H2; trivial.\n                  eapply AveTuple.compat_bool_isNotSameLoc.\n                }\n              }\n              pose proof (MATCH_AI tu).\n              apply H4 in H3. \n              destruct tu eqn:EqTu.\n              {\n                trivial.\n              }\n              {\n                destruct H3 as (LO & t & f & R & PLN & RLX & MSG).\n                splits; eauto.\n                rewrite <- MEM_EQ_START in MSG.\n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Local.write_step_future; eauto.\n                }\n                eapply Memory.future_get1 in H3; eauto.\n                destruct H3 as (from' & msg' & MSG' & _ & LE).\n                inv LE.\n                do 3 eexists; splits; eauto.\n                { (** plain *)\n                  inv LOCAL0. simpls.\n                  assert (loc0 <> loc). {\n                    inv Heqai'.\n                    eapply W.union_1 in H2. \n                    destruct H2.\n                    {\n                      eapply AveLat.mem_of_getExprs_implies_non_loc_in_ai' in H2; eauto.\n                      unfolds AveLat.GetExprs. auto.\n                    }\n                    { \n                      eapply W.filter_2 in H2.\n                      unfolds AveTuple.isNotSameLoc.\n                      eapply negb_true_iff in H2.\n                      rewrite Pos.eqb_sym in H2.\n                      eapply Pos.eqb_neq in H2. trivial.\n                      eapply AveTuple.compat_bool_isNotSameLoc.\n                    }\n                  }\n                  unfold TimeMap.join.\n                  unfold TimeMap.singleton.\n                  rewrite  Loc_add_neq; eauto.\n                  unfold LocFun.init.\n                  rewrite Time_join_bot. \n                  assert (lc_src = lc_tgt). {\n                    eapply cse_match_local_state_implies_eq_local; eauto.\n                  } \n                  rewrite <- H5. trivial.\n                }\n                { (** rlx *)\n                  inv LOCAL0. simpls.\n                  eapply TimeMap.time_le_TimeMap_join_l.\n                  assert (lc_src = lc_tgt). {\n                    eapply cse_match_local_state_implies_eq_local; eauto.\n                  } \n                  rewrite <- H3. trivial.\n                }\n              }   \n          }\n          { (** blk-level fixpoint *)\n            eapply subblk_same_succ in EqBlkSrc.\n            rewrite <- EqBlkSrc; trivial.\n            destruct ANALYSIS.\n            2: {\n              intros.\n              eapply (AveAI.get_head_from_eval) with (l:=lp) in H15; eauto.\n              folds AveAI.b.\n              rewrite H15.\n              eapply AveLat.ge_top.\n            }\n            eapply Ave_B.wf_transf_blk_getlast in H15; eauto.\n            rewrite <- H15. \n            rewrite <- AI_BLK in FIXPOINT. trivial.\n          }\n          {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n          { (** mem_injected inj'' promises_tgt' *)\n            inv LOCAL0; simpls.\n            pose proof WRITE as WRITE'.\n            inv WRITE; simpls.\n            inv PROMISE.\n            { (** promise-add *)\n              inv PROMISES.\n              inv REMOVE.\n              unfolds mem_injected.\n              intros.\n              pose proof (classic (loc = loc0)).\n              destruct H2.\n              {\n                unfold Memory.get in MSG.\n                pose proof (classic (to = t)).\n                destruct H3.\n                { \n                  eapply Memory.write_get2 in WRITE'.\n                  destruct WRITE'.\n                  unfold Memory.get in H4.\n                  rewrite H3 in H4.\n                  rewrite H2 in H4.\n                  rewrite H2 in MSG.\n                  rewrite H4 in MSG.\n                  discriminate.\n                }\n                {\n                  rewrite <- H2 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  eapply Cell.add_o with (t:=t) in ADD; eauto.\n                  eapply Cell.remove_o with (t:=t) in REMOVE0; eauto.\n                  des_ifH ADD; try contradiction. rewrite e0 in H3. contradiction.\n                  rewrite REMOVE0 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  rewrite ADD in MSG.\n                  eapply INJ_PROMISES in MSG.\n                  rewrite H2 in MSG.\n                  trivial.\n                }\n              }\n              { \n                unfold Memory.get in MSG.\n                rewrite Loc_add_neq in MSG; trivial.\n                rewrite Loc_add_neq in MSG; trivial.\n                assert (Memory.get loc0 t (Local.promises lc_tgt) =\n                Some (f, Message.concrete val R)). { \n                  unfold Memory.get. trivial.\n                }\n                eapply INJ_PROMISES in H3. trivial.\n              }\n            }\n            { (** promise-split *)\n              inv PROMISES.\n              inv REMOVE.\n              unfolds mem_injected.\n              intros.\n              pose proof (classic (loc = loc0)).\n              destruct H2.\n              {\n                unfold Memory.get in MSG.\n                pose proof (classic (to = t)).\n                destruct H3.\n                { \n                  eapply Memory.write_get2 in WRITE'.\n                  destruct WRITE'.\n                  unfold Memory.get in H4.\n                  rewrite H3 in H4.\n                  rewrite H2 in H4.\n                  rewrite H2 in MSG.\n                  rewrite H4 in MSG.\n                  discriminate.\n                }\n                {\n                  rewrite <- H2 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  eapply Cell.split_o with (t:=t) in SPLIT; eauto.\n                  eapply Cell.remove_o with (t:=t) in REMOVE0; eauto.\n                  des_ifH SPLIT; try contradiction. rewrite e0 in H3. contradiction.\n                  rewrite REMOVE0 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  rewrite SPLIT in MSG.\n                  pose proof (classic (ts3 = t)).\n                  destruct H4.\n                  { \n                    des_ifH SPLIT.\n                    rewrite Loc_add_eq in REMOVE0.\n                    inv MSG.\n                    {\n                      inv WRITE'.\n                      inv PROMISE.\n                      eapply Memory.split_get0 in PROMISES.\n                      destruct PROMISES as (_ & MSG' & _).\n                      eapply INJ_PROMISES in MSG'.\n                      trivial.\n                    }\n                    rewrite H4 in n0. contradiction.\n                  }\n                  {\n                    des_ifH SPLIT.\n                    rewrite e0 in H4; try contradiction.\n                    eapply INJ_PROMISES in MSG.\n                    rewrite H2 in MSG. trivial.\n                  }\n                }\n              }\n              { \n                unfold Memory.get in MSG.\n                rewrite Loc_add_neq in MSG; trivial.\n                rewrite Loc_add_neq in MSG; trivial.\n                assert (Memory.get loc0 t (Local.promises lc_tgt) =\n                Some (f, Message.concrete val R)). { \n                  unfold Memory.get. trivial.\n                }\n                eapply INJ_PROMISES in H3. trivial.\n              }\n            }\n            { (** promise-lower *)\n              inv PROMISES.\n              inv REMOVE.\n              unfolds mem_injected.\n              intros.\n              pose proof (classic (loc = loc0)).\n              destruct H2.\n              {\n                unfold Memory.get in MSG.\n                pose proof (classic (to = t)).\n                destruct H3.\n                { \n                  eapply Memory.write_get2 in WRITE'.\n                  destruct WRITE'.\n                  unfold Memory.get in H4.\n                  rewrite H3 in H4.\n                  rewrite H2 in H4.\n                  rewrite H2 in MSG.\n                  rewrite H4 in MSG.\n                  discriminate.\n                }\n                {\n                  rewrite <- H2 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  eapply Cell.lower_o with (t:=t) in LOWER; eauto.\n                  eapply Cell.remove_o with (t:=t) in REMOVE0; eauto.\n                  des_ifH LOWER; try contradiction. rewrite e0 in H3. contradiction.\n                  rewrite REMOVE0 in MSG.\n                  rewrite Loc_add_eq in MSG.\n                  rewrite LOWER in MSG.\n                  eapply INJ_PROMISES in MSG.\n                  rewrite H2 in MSG.\n                  trivial.\n                }\n              }\n              { \n                unfold Memory.get in MSG.\n                rewrite Loc_add_neq in MSG; trivial.\n                rewrite Loc_add_neq in MSG; trivial.\n                assert (Memory.get loc0 t (Local.promises lc_tgt) =\n                Some (f, Message.concrete val R)). { \n                  unfold Memory.get. trivial.\n                }\n                eapply INJ_PROMISES in H3. trivial.\n              }\n            }\n            { (** non-cancel *)\n              discriminate.\n            }\n          }\n        }\n      { \n        right.\n        splits; eauto.\n        assert (incr_inj inj' inj''). {\n          eapply construct_incr_inj1; eauto.\n        }\n        destruct PREEMPT as [EQ_INJ|INCR_INJ].\n        destruct EQ_INJ as (_ & EQ_INJ).\n        apply eq_inj_implies_incr in EQ_INJ.\n        eapply incr_inj_transitivity; eauto.\n        destruct INCR_INJ as (_ & EQ_INJ).\n        eapply incr_inj_transitivity; eauto. \n      }\n      {\n        eapply Local.program_step_future; eauto.\n      }\n      { \n        eapply Local.program_step_future; eauto.\n      }\n      {\n        eapply Local.program_step_future; eauto.\n      }\n      }\n  }\n  }\nQed.\n\n(** Correctness of atomic memory access: read/write/case/fence/print *)\nTheorem cse_match_state_preserving_at:\n  forall te lo inj st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src b st_tgt' lc_tgt' sc_tgt' mem_tgt', \n    Thread.program_step te lo \n        (@Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n        (@Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') \n    -> \n    ThreadEvent.is_at_or_out_step te \n    ->   \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n      (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b)\n    -> \n      (exists st_src' lc_src' sc_src' mem_src' inj',\n          Thread.program_step te lo (@Thread.mk rtl_lang st_src lc_src sc_src mem_src) \n                                    (@Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') \n          /\\\n          (cse_match_state inj' lo \n          (Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') true)\n          /\\ \n          incr_inj inj inj'\n      ).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt) eqn:EqStTgt.\n  destruct st_tgt' as (regs_tgt', blk_tgt', cdhp_tgt', cont_tgt', code_tgt') eqn:EqStTgt'.\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc; simpls.\n  unfold ThreadEvent.is_at_or_out_step in H0.\n  destruct te; try contradiction; eauto.\n  {\n    pose proof (nonatomic_or_atomic ord) as ORD; \n    destruct ORD. rewrite H2 in H0; try contradiction; eauto.\n    (** atomic read *)\n    inversion H. unfolds ThreadEvent.get_program_event.\n    inv STATE.\n    { (** Inst.load r loc ord *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H3 into SC_EQ_START.\n      destruct H4 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  RegFun.add r val regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_src mem_tgt' inj'.\n        splits; eauto.\n        { (** load -> load  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_load; eauto.\n            eapply at_load_transformed_inst_by_at_load in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL.\n            rewrite <- H13; rewrite MEM_EQ_START.  \n            eapply Local.step_read; eauto.\n            rewrite <- H13 in LOCAL0; rewrite MEM_EQ_START in LOCAL0. \n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H15. \n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H12.\n            rewrite SC_EQ_START.\n            unfold cse_invariant; simpls. splits; eauto.\n            rewrite <- H13. trivial.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            { rewrite REG_EQ. trivial. }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H16 in H15.\n                folds AveAI.b.\n                rewrite H15.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H15; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H15.\n              eapply at_load_transformed_inst_by_at_load in TRSF_INST; eauto.\n              rewrite TRSF_INST in H15.\n              unfolds Ave_I.transf.\n              destruct ord eqn:EqOrd; try contradiction; eauto.\n              - (* relaxed read *)  \n                rewrite <- H15.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (ai) r) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_reg in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_reg in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n                  simpls.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3. \n                    (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=val) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  intros.\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H7 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  pose proof H4.\n                  rewrite H7.\n                  apply H5 in H6.\n                  rewrite EqTu in H6. destruct H6. splits; eauto.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H9.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H10.\n                    2: {\n                      apply NNPP in H10.\n                      inv LOCAL0.\n                      rewrite H6 in LO.\n                      unfold Ordering.mem_ord_match in LO. discriminate.\n                    }\n                    eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                }\n\n                  assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H10.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H11.\n                    2: {\n                      apply NNPP in H11.\n                      inv LOCAL0.\n                      rewrite H6 in LO.\n                      unfold Ordering.mem_ord_match in LO. discriminate.\n                    }\n                    eapply rlx_read_step_keep_na_cur_pln; eauto.\n                }\n                rewrite <- H9.\n                rewrite <- H10.\n                trivial.\n                }\n              - (** strong relaxed, same as relaxed *)\n                rewrite <- H15.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (ai) r) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n                  simpls.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3. (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=val) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  intros.\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H7 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  pose proof H4.\n                  rewrite H7.\n                  apply H5 in H6.\n                  rewrite EqTu in H6. destruct H6. splits; eauto.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H9.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H10.\n                    2: {\n                      apply NNPP in H10.\n                      inv LOCAL0.\n                      rewrite H6 in LO.\n                      unfold Ordering.mem_ord_match in LO. discriminate.\n                    }\n                    eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                }\n                    assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H10.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H11.\n                      2: {\n                        apply NNPP in H11.\n                        inv LOCAL0.\n                        rewrite H6 in LO.\n                        unfold Ordering.mem_ord_match in LO. discriminate.\n                      }\n                      eapply rlx_read_step_keep_na_cur_pln; eauto.\n                  }\n                  rewrite <- H9.\n                  rewrite <- H10.\n                  trivial.\n                }\n              - (** acq case, a little difference *)\n                rewrite <- H15.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.GetExprs ai) r) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                intros.\n                unfolds match_abstract_fact.\n                {\n                  unfold AveLat.GetExprs in Heqai'.\n                  unfold AveLat.kill_reg in Heqai'. \n                  discriminate.\n                }\n                {\n                  unfold AveLat.GetExprs in Heqai'.\n                  unfold AveLat.kill_reg in Heqai'. \n                  discriminate.\n                }\n                intros.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=val) (regs:=regs_src) in H4.\n                  simpls.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3.\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=val) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** no more (r, x) in ai' *)\n                  intros.\n                  rewrite <- EqTu in H3. \n                  eapply AveLat.mem_of_getExprs_implies_non_loc_in_ai \n                    with (r:=r) in EqTu; try contradiction; eauto.\n                }\n              - (** sc, invalid case *)\n                rewrite <- H15.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp. simpls. intros.\n                pose proof W.empty_1. unfolds W.Empty. \n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember ( AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai'.\n                destruct ai; trivial.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H15; eauto.\n                folds AveAI.b.\n                rewrite H15.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H15; eauto.\n              rewrite <- H15. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              {\n                assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                  {\n                    destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                    eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                    subst analysis_blk.\n                    eapply Ave_B.wf_transf_blk_step; eauto.\n                    pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                    apply A in ANALYSIS.\n                    folds AveAI.b.\n                    rewrite ANALYSIS. \n                    eapply top_is_loc_fact_valid.\n                  }\n                }\n                trivial.\n            }\n  \n            }\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          rewrite <- H13 in LOCAL0.\n          rewrite <- H13.\n          eapply Local.read_step_future; eauto.\n        }\n        { rewrite <- H12.\n          rewrite <- H13.\n          trivial.\n        }\n        {\n          rewrite <- H13. trivial.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n    }\n    { (** Inst.cas r loc er ew ord ow *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H3 into SC_EQ_START.\n      destruct H4 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  RegFun.add r Integers.Int.zero regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_src mem_tgt' inj'.\n        splits; eauto.\n        { (** cas -> cas  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_cas_flip; eauto.\n            eapply at_cas_transformed_inst_by_at_cas in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            2: {\n                inversion LOCAL.\n                rewrite <- H13; \n              rewrite MEM_EQ_START.  \n              eapply Local.step_read; eauto.\n              rewrite <- H13 in LOCAL0; rewrite MEM_EQ_START in LOCAL0. \n              assert (lc_tgt = lc_src). {\n                eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n              }\n              rewrite <- H15. \n              trivial. \n            }\n            subst; trivial.\n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H12.\n            rewrite SC_EQ_START.\n            unfold cse_invariant; simpls. splits; eauto.\n            rewrite <- H13. trivial.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            { rewrite REG_EQ. trivial. }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H16 in H15.\n                folds AveAI.b.\n                rewrite H15.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H15; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H15.\n              eapply at_cas_transformed_inst_by_at_cas in TRSF_INST; eauto.\n              rewrite TRSF_INST in H15.\n              unfolds Ave_I.transf.\n              destruct ord eqn:EqOrd; try contradiction; eauto.\n              - (* relaxed laod *)  \n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                pose proof (classic (ow = Ordering.seqcst)). \n                destruct H3.\n                {\n                  rewrite H3 in H15.\n                  rewrite <- H15.\n                  destruct (AveAI.getFirst (AveAI.br_from_i analysis !! l i)); \n                  try eapply always_match_top; try rewrite always_match_bot; trivial.\n                }\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.kill_var ai loc) r) as ai'.\n                assert (ai' = AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))).\n                {\n                  destruct ow; try contradiction; trivial.\n                }\n                rewrite <- H4.\n                clear H15.\n                rename H4 into H15.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                clear H3.\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.zero) (regs:=regs_src) in H4.\n                  simpls.\n                  folds Const.t.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3. (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=(regs_src)) (val:=Integers.Int.zero) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.union_1 in H3; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  intros.\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.zero) (regs:=regs_src) in H4.\n\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H7 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.union_1 in H3; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  pose proof H4.\n                  apply H5 in H6.  \n                  rewrite EqTu in H6. destruct H6. splits; eauto.\n                  folds Const.t.\n                  rewrite H7.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H9.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H10.\n                    2: {\n                      apply NNPP in H10.\n                      inv LOCAL0.\n                      rewrite H6 in LO.\n                      unfold Ordering.mem_ord_match in LO. discriminate.\n                    }\n                    eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                  }\n                  assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H10.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H11.\n                      2: {\n                        apply NNPP in H11.\n                        inv LOCAL0.\n                        rewrite H6 in LO.\n                        unfold Ordering.mem_ord_match in LO. discriminate.\n                      }\n                      eapply rlx_read_step_keep_na_cur_pln; eauto.\n                  }\n                  rewrite <- H9.\n                  rewrite <- H10.\n                  trivial.\n                }\n              - (** strong relaxed, same as relaxed *)\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                pose proof (classic (ow = Ordering.seqcst)). \n                destruct H3.\n                {\n                  rewrite H3 in H15.\n                  rewrite <- H15.\n                  destruct (AveAI.getFirst (AveAI.br_from_i analysis !! l i)); try \n                  eapply always_match_top; try rewrite always_match_bot; eauto.\n                }\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.kill_var ai loc) r) as ai'.\n                assert (ai' = AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))).\n                {\n                  destruct ow; try contradiction; trivial.\n                }\n                rewrite <- H4.\n                clear H15.\n                rename H4 into H15.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                clear H3.\n                destruct ai' eqn:EqAi'; trivial.\n                intros.\n                unfolds match_abstract_fact.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.zero) (regs:=regs_src) in H4.\n                  simpls.\n                  folds Const.t.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3. (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=Integers.Int.zero) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.union_1 in H3; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  intros.\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.zero) (regs:=regs_src) in H4.\n\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H7 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.union_1 in H3; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  pose proof H4.\n                  apply H5 in H6.\n                  rewrite EqTu in H6. destruct H6. splits; eauto.\n                  folds Const.t.\n                  rewrite H7.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H9.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H10.\n                    2: {\n                      apply NNPP in H10.\n                      inv LOCAL0.\n                      rewrite H6 in LO.\n                      unfold Ordering.mem_ord_match in LO. discriminate.\n                    }\n                    eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                  }\n                    assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H10.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H11.\n                      2: {\n                        apply NNPP in H11.\n                        inv LOCAL0.\n                        rewrite H6 in LO.\n                        unfold Ordering.mem_ord_match in LO. discriminate.\n                      }\n                      eapply rlx_read_step_keep_na_cur_pln; eauto.\n                  }\n                    rewrite <- H9.\n                    rewrite <- H10.\n                    trivial.\n                  }\n              - (** acq case, a little difference *)\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                pose proof (classic (ow = Ordering.seqcst)). \n                destruct H3.\n                {\n                  rewrite H3 in H15.\n                  rewrite <- H15.\n                  destruct (AveAI.getFirst (AveAI.br_from_i analysis !! l i)); trivial; \n                  eapply always_match_top.\n                }\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.GetExprs ai) r) as ai'.\n                assert (ai' = AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))).\n                {\n                  destruct ow; try contradiction; trivial.\n                }\n                rewrite <- H4.\n                clear H15.\n                rename H4 into H15.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                clear H3.\n                destruct ai' eqn:EqAi'; trivial.\n                intros.\n                unfolds match_abstract_fact.\n                {\n                  unfold AveLat.GetExprs in Heqai'.\n                  unfold AveLat.kill_reg in Heqai'. \n                  discriminate.\n                }\n                {\n                  unfold AveLat.GetExprs in Heqai'.\n                  unfold AveLat.kill_reg in Heqai'. \n                  discriminate.\n                }\n                intros.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H4 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H4.\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.zero) (regs:=regs_src) in H4.\n                  simpls.\n                  folds Const.t.\n                  rewrite H4.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H7 in H3.\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=Integers.Int.zero) in H6.\n                  folds Const.t.\n                  rewrite <- H6.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H9 in H3.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                  }\n                  apply H7 in H8. rewrite EqTu in H8. trivial.\n                }\n                { (** no more (r, x) in ai' *)\n                  intros.\n                  rewrite <- EqTu in H3. \n                  eapply AveLat.mem_of_getExprs_implies_non_loc_in_ai \n                    with (r:=r) in EqTu; try contradiction; eauto.\n                }\n              - (** sc, invalid case *)\n                remember ( AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                destruct ow; destruct ai; rewrite <- H15; try rewrite always_match_bot; try eapply always_match_top; trivial; subst; rewrite <- Heqai in MATCH_AI; try eapply never_match_bot in MATCH_AI; contradiction.\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H15; eauto.\n                folds AveAI.b.\n                rewrite H15.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H15; eauto.\n              rewrite <- H15. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              {\n                assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                  {\n                    destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                    eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                    subst analysis_blk.\n                    eapply Ave_B.wf_transf_blk_step; eauto.\n                    pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                    apply A in ANALYSIS.\n                    folds AveAI.b.\n                    rewrite ANALYSIS. \n                    eapply top_is_loc_fact_valid.\n                  }\n                }\n                trivial.\n            }\n  \n            }\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          rewrite <- H13 in LOCAL0.\n          rewrite <- H13.\n          eapply Local.read_step_future; eauto.\n        }\n        { rewrite <- H12.\n          rewrite <- H13.\n          trivial.\n        }\n        {\n          rewrite <- H13. trivial.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n  }\n  }\n  { (**atomic write *)\n    pose proof (nonatomic_or_atomic ord) as ORD; \n    destruct ORD. rewrite H2 in H0; try contradiction; eauto.\n    inversion H. \n    inv STATE.\n    { (** Inst.store r loc ord *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H3 into SC_EQ_START.\n      destruct H4 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n      inversion LOCAL.\n      pose proof (classic (exists msg3 ts3, kind = Memory.op_kind_split ts3 msg3)).\n      destruct H16.\n      { (** promise split *) (** FIXME: \u611f\u89c9split\u4e0d\u9700\u8981\u5355\u72ec\u5206\u4e00\u4e2acase *)\n        remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''. \n        exists {|\n            State.regs := regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj''.\n        splits; eauto.\n        { (** store -> store  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_store; eauto.\n            eapply at_store_transformed_inst_by_at_store in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL. subst; eauto.\n            (* rewrite <- MEM_EQ_START.   *)\n            inv H.\n            rewrite MEM_EQ_START in LOCAL0. \n            eapply Local.step_write with (kind:=kind); eauto. \n            assert (lc_src = lc_tgt). {eapply cse_match_local_state_implies_eq_local; eauto. }\n            rewrite H. \n            rewrite <- SC_EQ_START. trivial.\n        }\n        { (** match state *)\n          eapply cse_match_state_intro with(inj':=inj''); simpls; eauto.\n          { (** invariant *)\n            rewrite <- H14.\n            unfold cse_invariant; splits; simpls; eauto.\n            unfolds eq_ident_mapping.\n            destruct INJ_MAP_MEM_TGT.\n            split.\n            2: {\n              intros.\n              rewrite Heqinj'' in H19.\n              des_ifH H19; simpls.\n              { \n                destruct a. subst. \n                inv H19. \n                eapply eq_refl.\n              }\n            apply H18 in H19. trivial.\n          }\n          { (** dom equal*)\n            rewrite H14.\n            inversion LOCAL0.\n            inversion WRITE.\n            destruct H16 as (msg3 & ts3 & SPLIT).\n            eapply prm_split_incr_mem_with_inj; eauto.\n            intro. try discriminate.\n          }\n\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H18 in H17.\n                folds AveAI.b.\n                rewrite H17.\n                eapply always_match_top.\n            }\n              eapply Ave_B.wf_transf_blk_step in H17; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H17.\n              eapply at_store_transformed_inst_by_at_store in TRSF_INST; eauto.\n              rewrite TRSF_INST in H17.\n              unfolds Ave_I.transf.\n              pose proof (classic (ord = Ordering.seqcst)).\n              destruct H18. \n              { (** sc case *)\n                rewrite <- H15.\n                rewrite <- H17.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                unfolds match_abstract_interp. simpls. intros.\n                pose proof W.empty_1. unfolds W.Empty. \n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember ( AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai'.\n                destruct ai; trivial.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n              }\n              assert (ord <> Ordering.plain). {\n                destruct ord eqn:EqOrd; try contradiction; eauto.\n              }\n                rewrite <- H17.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                (* rewrite MEM_EQ_START. *)\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_var ai loc) as ai'.\n                replace ( match ord with\n                    | Ordering.seqcst => \n                      match ai with\n                      | AveLat.Bot => AveLat.Bot\n                      | _ => AveLat.top\n                      end\n                    | _ => ai'\n                    end) with ai'.\n                2: {\n                  destruct ord; try contradiction; trivial.\n                }\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H6 in H3.\n                    eapply W.union_1 in H3; trivial.\n                    destruct H3; \n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_isNotSameLoc loc).\n                  }\n                  apply H4 in H5. rewrite EqTu in H5. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)               \n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H6 in H3.\n                    eapply W.union_1 in H3; trivial.\n                    destruct H3; \n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_isNotSameLoc loc).\n                  }\n                  pose proof H4.\n                  apply H4 in H5.\n                  rewrite EqTu in H5. destruct H5; splits; eauto.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H8.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H9.\n                    2: {\n                      apply NNPP in H9.\n                      inv LOCAL0.\n                      rewrite H5 in LO.\n                      unfold Ordering.mem_ord_match in LO. rewrite LO in H19; try contradiction.\n                    }\n                    eapply atomic_write_step_keep_na_cur_rlx; eauto.\n                    destruct ord; try contradiction; try splits; eauto.\n                }\n                assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                  assert (lc_tgt = lc_src). {\n                    eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                  }\n                  rewrite <- H9.\n                  pose proof (classic (loc <> loc0)).\n                  destruct H10.\n                  2: {\n                    apply NNPP in H10.\n                    inv LOCAL0.\n                    rewrite H5 in LO.\n                    unfold Ordering.mem_ord_match in LO. rewrite LO in H19; try contradiction.\n                  }\n                  eapply atomic_write_step_keep_na_cur_pln; eauto.\n                  destruct ord; try contradiction; try splits; eauto.\n                }\n                rewrite <- H9.\n                rewrite <- H8.\n                trivial.\n                destruct H7 as (t & f & R & PLN & RLX & MSG).\n                rewrite <- MEM_EQ_START in MSG.\n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Local.write_step_future; eauto.\n                }\n                eapply Memory.future_get1 in H7; eauto.\n                destruct H7 as (from' & msg' & MSG' & _ & LE).\n                inv LE.\n                do 3 eexists; splits; eauto.\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H17; eauto.\n                folds AveAI.b.\n                rewrite H17.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H17; eauto.\n              rewrite <- H17. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              {\n                assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                  {\n                    destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                    eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                    subst analysis_blk.\n                    eapply Ave_B.wf_transf_blk_step; eauto.\n                    pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                    apply A in ANALYSIS.\n                    folds AveAI.b.\n                    rewrite ANALYSIS. \n                    eapply top_is_loc_fact_valid.\n                  }\n                }\n                trivial.\n            }\n  \n            }\n            { (** mem_injected inj'' promises_tgt' *)\n              assert (incr_inj inj inj'). {\n                destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n                eapply eq_inj_implies_incr; trivial.\n                trivial.\n              }\n              eapply incr_inj_preserve_mem_injected in H17; eauto.\n              inv LOCAL0. simpls.\n              inversion WRITE. \n              eapply remove_keeps_promises_injected; eauto.\n              destruct H16 as (msg3 & ts3 & H16).\n              eapply prm_split_keeps_promises_injected; eauto. \n            }\n        }\n        {\n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          rewrite <- H13 in LOCAL0.\n          (* rewrite <- H13. *)\n          eapply Local.write_step_future; eauto.\n        }\n        {\n          inversion LOCAL0. inv WRITE. simpls.\n          eapply Memory.promise_closed_timemap; eauto. \n        }\n        {\n          assert (Memory.future mem_tgt mem_tgt'). {\n            inversion LOCAL_WF.\n            eapply Local.write_step_future; eauto.\n          }\n          eapply Memory.future_closed; eauto.\n        } \n        }\n        { \n          assert (incr_inj inj' inj''). {\n            eapply construct_incr_inj1; eauto.\n\n          }\n          destruct PREEMPT as [EQ_INJ|INCR_INJ].\n          destruct EQ_INJ as (_ & EQ_INJ).\n          apply eq_inj_implies_incr in EQ_INJ.\n          eapply incr_inj_transitivity; eauto.\n          destruct INCR_INJ as (_ & EQ_INJ).\n          eapply incr_inj_transitivity; eauto.\n        }\n      }\n      (*non split case*)\n        remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''. \n\n        exists {|\n            State.regs := regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj''.\n        splits; eauto.\n        { (** store -> store  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_store; eauto.\n            eapply at_store_transformed_inst_by_at_store in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL. subst; eauto.\n            (* rewrite <- MEM_EQ_START.   *)\n            inv H.\n            rewrite MEM_EQ_START in LOCAL0. \n            eapply Local.step_write with (kind:=kind); eauto. \n            assert (lc_src = lc_tgt). {eapply cse_match_local_state_implies_eq_local; eauto. }\n            rewrite H. \n            rewrite <- SC_EQ_START. trivial.\n        }\n        { (** match state *)\n          (* inversion LOCAL. *)\n          (* remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''.  *)\n          eapply cse_match_state_intro with(inj':=inj''); simpls; eauto.\n          { (** invariant *)\n            unfold cse_invariant; simpls. splits; eauto.\n            econs; eauto.\n            {\n              econs. \n              {\n                intros. exists t.\n                rewrite Heqinj''.\n                inv INVARIANT; simpls. destruct H18. inv H4.\n                inv H5.\n\n                des_if; simpls; try destruct a; subst; eauto.\n                eapply non_split_write_o with (l:=loc1) (t:=t) in LOCAL0; eauto. \n                des_ifH LOCAL0; simpls. \n                - destruct a. rewrite H4 in o; rewrite H5 in o. destruct o; try contradiction. \n                - rewrite LOCAL0 in MSG. eapply SOUND in MSG.\n                destruct MSG.  \n                  exploit H6; eauto. intro. rewrite <- x0 in H4; trivial.\n              }\n              {\n                intros.  \n                pose proof INJ.\n                rewrite Heqinj'' in INJ.\n                inv INVARIANT; simpls. destruct H19.\n                inv H4. inv H5.\n                eapply non_split_write_o with (l:=loc1) (t:=t) in LOCAL0; eauto. \n\n                des_ifH INJ; simpls. \n                {\n                  destruct a.\n                  destruct INJ.\n                  do 3 eexists; eauto.\n                  rewrite H5 in LOCAL0; rewrite H4 in LOCAL0. \n                  des_ifH LOCAL0; simpls.\n                  2: { destruct o; try contradiction. }\n                  rewrite LOCAL0. eauto.\n                }\n                {\n                  des_ifH LOCAL0; simpls. destruct a. rewrite H4 in o; rewrite H5 in o.\n                  destruct o; try contradiction.\n                  rewrite LOCAL0.\n                  apply COMPLETE in INJ.\n                  trivial.\n                }\n              }\n            }\n            {\n              rewrite Heqinj''. \n              intros.\n              des_ifH H17; simpls; eauto.\n              destruct a. rewrite H19 in H17; inv H17; eapply eq_refl.\n              inv INJ_MAP_MEM_TGT.\n              apply H19 in H17; trivial.\n            }\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n              pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n              eapply H18 in H17.\n              folds AveAI.b.\n              rewrite H17.\n              eapply always_match_top.\n          }\n              eapply Ave_B.wf_transf_blk_step in H17; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H17.\n              eapply at_store_transformed_inst_by_at_store in TRSF_INST; eauto.\n              rewrite TRSF_INST in H17.\n              unfolds Ave_I.transf.\n              pose proof (classic (ord = Ordering.seqcst)).\n              destruct H18. \n              { (** sc case *)\n                rewrite <- H15.\n                rewrite <- H17.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                unfolds match_abstract_interp. simpls. intros.\n                pose proof W.empty_1. unfolds W.Empty.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember ( AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1))) as ai'.\n                destruct ai; trivial.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n                unfolds AveLat.top.\n                intros.\n                pose proof (H3 tu). \n                contradiction.\n              }\n              assert (ord <> Ordering.plain). {\n                destruct ord eqn:EqOrd; try contradiction; eauto.\n              }\n                rewrite <- H17.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                (* rewrite MEM_EQ_START. *)\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_var ai loc) as ai'.\n                replace ( match ord with\n                    | Ordering.seqcst =>\n                      match ai with\n                      | AveLat.Bot => AveLat.Bot\n                      | _ => AveLat.top\n                      end\n                    | _ => ai'\n                    end) with ai'.\n                2: {\n                  destruct ord; try contradiction; trivial.\n                }\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                intros.\n                unfolds match_abstract_fact.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H6 in H3.\n                    eapply W.union_1 in H3; trivial.\n                    destruct H3; \n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_isNotSameLoc loc).\n                  }\n                  apply H4 in H5. rewrite EqTu in H5. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)               \n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H3.\n                    inversion Heqai'.\n                    rewrite H6 in H3.\n                    eapply W.union_1 in H3; trivial.\n                    destruct H3; \n                    eapply W.filter_1 in H3; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply (AveTuple.compat_bool_isNotSameLoc loc).\n                  }\n                  pose proof H4.\n                  apply H4 in H5.\n                  rewrite EqTu in H5. destruct H5; splits; eauto.\n\n                  assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                    assert (lc_tgt = lc_src). {\n                      eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                    }\n                    rewrite <- H8.\n                    pose proof (classic (loc <> loc0)).\n                    destruct H9.\n                    2: {\n                      apply NNPP in H9.\n                      inv LOCAL0.\n                      rewrite H5 in LO.\n                      unfold Ordering.mem_ord_match in LO. rewrite LO in H19; try contradiction.\n                    }\n                    eapply atomic_write_step_keep_na_cur_rlx; eauto.\n                    destruct ord; try contradiction; try splits; eauto.\n                }\n                assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                  assert (lc_tgt = lc_src). {\n                    eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                  }\n                  rewrite <- H9.\n                  pose proof (classic (loc <> loc0)).\n                  destruct H10.\n                  2: {\n                    apply NNPP in H10.\n                    inv LOCAL0.\n                    rewrite H5 in LO.\n                    unfold Ordering.mem_ord_match in LO. rewrite LO in H19; try contradiction.\n                  }\n                  eapply atomic_write_step_keep_na_cur_pln; eauto.\n                  destruct ord; try contradiction; try splits; eauto.\n                }\n                rewrite <- H9.\n                rewrite <- H8.\n                trivial.\n                destruct H7 as (t & f & R & PLN & RLX & MSG).\n                rewrite <- MEM_EQ_START in MSG.\n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Local.write_step_future; eauto.\n                }\n                eapply Memory.future_get1 in H7; eauto.\n                destruct H7 as (from' & msg' & MSG' & _ & LE).\n                inv LE.\n                do 3 eexists; splits; eauto.\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H17; eauto.\n                folds AveAI.b.\n                rewrite H17.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H17; eauto.\n              rewrite <- H17. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              {\n                assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                  {\n                    destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                    eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                    subst analysis_blk.\n                    eapply Ave_B.wf_transf_blk_step; eauto.\n                    pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                    apply A in ANALYSIS.\n                    folds AveAI.b.\n                    rewrite ANALYSIS. \n                    eapply top_is_loc_fact_valid.\n                  }\n                }\n                trivial.\n            }\n  \n            }\n            { (** mem_injected inj'' promises_tgt' *)\n              assert (incr_inj inj inj'). {\n                destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n                eapply eq_inj_implies_incr; trivial.\n                trivial.\n              }\n              eapply incr_inj_preserve_mem_injected in H17; eauto.\n              inv LOCAL0. simpls.\n              inversion WRITE. \n              eapply remove_keeps_promises_injected; eauto.\n              eapply prm_concrete_keeps_promises_injected; eauto.\n            }\n        }\n        {\n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          rewrite <- H13 in LOCAL0.\n          (* rewrite <- H13. *)\n          eapply Local.write_step_future; eauto.\n        }\n        {\n          inversion LOCAL0. inv WRITE. simpls.\n          eapply Memory.promise_closed_timemap; eauto. \n        }\n        {\n          assert (Memory.future mem_tgt mem_tgt'). {\n            inversion LOCAL_WF.\n            eapply Local.write_step_future; eauto.\n          }\n          eapply Memory.future_closed; eauto.\n        } \n        }\n        { \n          assert (incr_inj inj' inj''). {\n            eapply construct_incr_inj1; eauto.\n\n          }\n          destruct PREEMPT as [EQ_INJ|INCR_INJ].\n          destruct EQ_INJ as (_ & EQ_INJ).\n          apply eq_inj_implies_incr in EQ_INJ.\n          eapply incr_inj_transitivity; eauto.\n          destruct INCR_INJ as (_ & EQ_INJ).\n          eapply incr_inj_transitivity; eauto.\n        }\n    }\n  } \n  { (** atomic cas, upd *)\n    assert (ORDR: ordr <> Ordering.plain). {\n      remember (ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw) as e.\n      inv H.\n      eapply Local.update_step_ord_not_pln in LOCAL; eauto. tauto. \n    }\n    assert (ORDW: ordw <> Ordering.plain). {\n      inv H.\n      eapply Local.update_step_ord_not_pln in LOCAL; eauto. tauto. \n    }\n    (* rewrite H2 in H; try contradiction; eauto. *)\n    inversion H. \n    unfolds ThreadEvent.get_program_event.\n    inv STATE.\n\n    (** Inst.cas r loc er ew ord ow *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n      remember (fun loc1 to1 => if loc_ts_eq_dec (loc, tsw) (loc1, to1) then Some tsw else (inj' loc1 to1)) as inj''. \n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  RegFun.add r Integers.Int.one regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj''.\n        splits; eauto.\n        { (** cas -> cas  *)\n            rewrite REG_EQ.\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_cas_same; eauto.\n            eapply at_cas_transformed_inst_by_at_cas in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n              inversion LOCAL.\n              trivial.\n              assert (lc_tgt = lc_src). {\n                eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n              }\n              rewrite <- H15. \n              rewrite REG_EQ in LOCAL1. rewrite REG_EQ in LOCAL2.\n              eapply Local.step_update with (lc2:=lc2) (kind:=kind); eauto.\n              rewrite MEM_EQ_START in LOCAL1. rewrite H18 in LOCAL1. trivial.\n              rewrite SC_EQ_START in LOCAL2. rewrite MEM_EQ_START in LOCAL2.\n              subst.\n              trivial.\n        }\n        { (** match state *)\n          inversion LOCAL. pose proof LOCAL as LOCAL'.\n          eapply cse_match_state_intro with(inj':=inj''); simpls; eauto.\n          { (** invariant *)\n            unfold cse_invariant; splits; simpls; eauto.\n            unfolds eq_ident_mapping.\n            destruct INJ_MAP_MEM_TGT.\n            split.\n            2: {\n              intros.\n              rewrite Heqinj'' in H20.\n              des_ifH H20; simpls.\n              { \n                destruct a. subst. \n                inv H20. \n                eapply eq_refl.\n              }\n            apply H19 in H20. trivial. \n            }\n            { (** dom eq *)\n              inversion H18.\n              inversion LOCAL2.\n              inversion WRITE.\n              eapply prm_keeps_mem_inj_dom_eq with (inj:=inj') (inj':=inj'') in PROMISE; eauto.\n              intro. discriminate.\n            }\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            { rewrite REG_EQ. trivial. }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H19 in H18.\n                folds AveAI.b.\n                rewrite H18.\n                eapply always_match_top.\n            }\n              eapply Ave_B.wf_transf_blk_step in H18; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H18.\n              eapply at_cas_transformed_inst_by_at_cas in TRSF_INST; eauto.\n              rewrite TRSF_INST in H18.\n              unfolds Ave_I.transf.\n              pose proof (classic (ordw = Ordering.seqcst)) as G.\n              destruct G. \n              {\n                rewrite H19 in H18. rewrite <- H18. \n                destruct (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) eqn:Eq; try \n                eapply always_match_top; eauto.\n                {\n                  subst. rewrite Eq in MATCH_AI. eapply never_match_bot in MATCH_AI.\n                  contradiction.\n                }\n\n              }\n              assert (ordw = Ordering.relaxed \\/ ordw = Ordering.strong_relaxed \\/ ordw = Ordering.acqrel). {\n                destruct ordw; tauto.\n              }\n\n              (* Set Printing All. *)\n              (* destruct ordw; try contradiction. *)\n              assert ( (match ordr with\n                | Ordering.relaxed | Ordering.strong_relaxed =>\n                    AveLat.kill_reg\n                      (AveLat.kill_var\n                        (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) loc) r\n                | Ordering.acqrel =>\n                    AveLat.kill_reg\n                      (AveLat.GetExprs\n                        (AveAI.getFirst (AveAI.br_from_i analysis !! l i))) r\n                | _ =>\n                    match AveAI.getFirst (AveAI.br_from_i analysis !! l i) with\n                    | AveLat.Bot => AveLat.Bot\n                    | _ => AveLat.top\n                    end\n                end)= ( AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))). {\n                  destruct H20 as [G|[G|G]]; rewrite G in H18; eauto.\n                }\n                clear H18. rename H21 into H18.\n\n              destruct ordr eqn:EqOrdR; try contradiction; eauto.\n              - (** relaxed *)\n                rewrite <- H18.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                (* rewrite MEM_EQ_START. *)\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.kill_var ai loc) r) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  unfold AveLat.kill_reg in Heqai'. \n\n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  unfold AveLat.kill_reg in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H3 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H3.\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.one) (regs:=regs_src) in H3.\n                  simpls.\n                  folds Const.t.\n                  rewrite H3.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H6 in H2. (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=Integers.Int.one) in H5.\n                  folds Const.t.\n                  rewrite <- H5.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H2.\n                    inversion Heqai'.\n                    rewrite H8 in H2.\n                    eapply W.filter_1 in H2; trivial.\n                    eapply W.union_1 in H2; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H2.\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  apply H6 in H7. rewrite EqTu in H7. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                    intros.\n                    assert (r <> reg). {\n                      unfolds AveLat.kill_reg. inversion Heqai'.\n                      rewrite <- EqAi' in Heqai'.\n                      eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                      rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                      intro. rewrite H3 in Heqai'. contradiction. \n                      subst; trivial.\n                    }\n                    eapply regs_add_neg with (r:=r) (v:=Integers.Int.one) (regs:=regs_src) in H3.\n\n                    pose proof (MATCH_AI tu).\n                    assert (W.In tu tuples). {\n                      rewrite <- EqTu in H2.\n                      inversion Heqai'.\n                      rewrite H6 in H2.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply W.union_1 in H2; trivial.\n                      2: {\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      destruct H2.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply (AveTuple.compat_bool_isExpr).\n                      eapply W.filter_1 in H2; trivial.\n                      eapply (AveTuple.compat_bool_isNotSameLoc).\n                    }\n                    pose proof H3.\n                    apply H4 in H5.\n                    rewrite EqTu in H5. destruct H5. splits; eauto.\n                    folds Const.t.\n                    rewrite H6.\n                    assert (View.rlx (TView.cur (Local.tview lc2)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                      pose proof (classic (loc <> loc0)).\n                      destruct H8.\n                      2: {\n                        apply NNPP in H8.\n                        inv LOCAL2.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO. \n                        rewrite LO in H20. destruct H20 as [G|[G|G]]; try discriminate. \n                      }\n                      eapply atomic_write_step_keep_na_cur_rlx; eauto.\n                    }\n\n                    assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc2)) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H9. clear H9.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H9.\n                      2: {\n                        apply NNPP in H9.\n                        inv LOCAL1.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO. \n                        discriminate.\n                      }\n                      eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                    }\n                    rewrite H8 in H9.\n                    rewrite <- H9.\n\n                    assert (View.pln (TView.cur (Local.tview lc2)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                        pose proof (classic (loc <> loc0)).\n                        destruct H10.\n                        2: {\n                          apply NNPP in H10.\n                          inv LOCAL2.\n                          rewrite H5 in LO.\n                          unfold Ordering.mem_ord_match in LO. \n                        rewrite LO in H20. destruct H20 as [G|[G|G]]; try discriminate. \n\n                        }\n                        eapply atomic_write_step_keep_na_cur_pln; eauto.\n                    }\n\n                    assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc2)) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H11. clear H11.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H11.\n                      2: {\n                        apply NNPP in H11.\n                        inv LOCAL1.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO. \n                        discriminate.\n                      }\n                        eapply rlx_read_step_keep_na_cur_pln; eauto.\n                    }\n                    rewrite H10 in H11.\n                    rewrite <- H11.\n                    destruct H7 as (t & f & R & PLN & RLX & MSG).\n                    rewrite <- MEM_EQ_START in MSG.\n                    assert (Memory.future mem_tgt mem_tgt'). {\n                      inversion LOCAL_WF.\n                      eapply Local.program_step_future; eauto.\n                    }\n                    eapply Memory.future_get1 in H7; eauto.\n                    destruct H7 as (from' & msg' & MSG' & _ & LE).\n                    inv LE.\n                    do 3 eexists; splits; eauto.\n                }\n              - (** strong relaxed *)\n                rewrite <- H18.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                (* rewrite MEM_EQ_START. *)\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.kill_reg (AveLat.kill_var ai loc) r) as ai'.\n                destruct ai eqn:EqAi.\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                }\n                {\n                  unfolds AveLat.kill_reg.\n                  rewrite Heqai'. trivial.\n                } (** ai = CSet tuples *)\n                destruct ai' eqn:EqAi'; trivial.\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                {\n                  unfold AveLat.kill_var in Heqai'. \n                  destruct (AveLat.GetExprs (AveLat.CSet tuples)); try discriminate;  eauto.\n                }\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { (** proof for: any (r', e) in ai' is still correct *)\n                  (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                  assert (r <> reg). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    rewrite <- EqAi' in Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                    rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                    intro. rewrite H3 in Heqai'. contradiction. \n                    subst; trivial.\n                  }\n                  pose proof H3.\n                  eapply regs_add_neg with (r:=r) (v:=Integers.Int.one) (regs:=regs_src) in H3.\n                  simpls.\n                  folds Const.t.\n                  rewrite H3.\n                  assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                    unfolds AveLat.kill_reg. inversion Heqai'.\n                    eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                    rewrite H6 in H2. (**TOOD: a little bad, coupled, seems cannot extract a lemma for `kill_reg` *)\n                    trivial.\n                  }\n                  eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=Integers.Int.one) in H5.\n                  folds Const.t.\n                  rewrite <- H5.\n                  pose proof (MATCH_AI tu).\n                  assert (W.In tu tuples). {\n                    rewrite <- EqTu in H2.\n                    inversion Heqai'.\n                    rewrite H8 in H2.\n                    eapply W.filter_1 in H2; trivial.\n                    eapply W.union_1 in H2; trivial.\n                    2: {\n                    eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    destruct H2.\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isNotSameLoc).\n                  }\n                  apply H6 in H7. rewrite EqTu in H7. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                    intros.\n                    assert (r <> reg). {\n                      unfolds AveLat.kill_reg. inversion Heqai'.\n                      rewrite <- EqAi' in Heqai'.\n                      eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                      rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                      intro. rewrite H3 in Heqai'. contradiction. \n                      subst; trivial.\n                    }\n                    eapply regs_add_neg with (r:=r) (v:=Integers.Int.one) (regs:=regs_src) in H3.\n\n                    pose proof (MATCH_AI tu).\n                    assert (W.In tu tuples). {\n                      rewrite <- EqTu in H2.\n                      inversion Heqai'.\n                      rewrite H6 in H2.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply W.union_1 in H2; trivial.\n                      2: {\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                      }\n                      destruct H2.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply (AveTuple.compat_bool_isExpr).\n                      eapply W.filter_1 in H2; trivial.\n                      eapply (AveTuple.compat_bool_isNotSameLoc).\n                    }\n                    pose proof H3.\n                    apply H4 in H5.\n                    rewrite EqTu in H5. destruct H5. splits; eauto.\n                    folds Const.t.\n                    rewrite H6.\n                    assert (View.rlx (TView.cur (Local.tview lc2)) loc0 = View.rlx (TView.cur (Local.tview lc_tgt')) loc0). {\n                      pose proof (classic (loc <> loc0)).\n                      destruct H8.\n                      2: {\n                        apply NNPP in H8.\n                        inv LOCAL2.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO.\n                        rewrite LO in ORDW.\n                        contradiction.\n                      }\n                      eapply atomic_write_step_keep_na_cur_rlx; eauto.\n                    }\n\n                    assert (View.rlx (TView.cur (Local.tview lc_src)) loc0 = View.rlx (TView.cur (Local.tview lc2)) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H9. clear H9.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H9.\n                      2: {\n                        apply NNPP in H9.\n                        inv LOCAL1.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO. \n                        discriminate.\n                      }\n                      eapply rlx_read_step_keep_na_cur_rlx; eauto.\n                    }\n                    rewrite H8 in H9.\n                    rewrite <- H9.\n\n                    assert (View.pln (TView.cur (Local.tview lc2)) loc0 = View.pln (TView.cur (Local.tview lc_tgt')) loc0). {\n                        pose proof (classic (loc <> loc0)).\n                        destruct H10.\n                        2: {\n                          apply NNPP in H10.\n                          inv LOCAL2.\n                          rewrite H5 in LO.\n                          unfold Ordering.mem_ord_match in LO. \n                          rewrite LO in ORDW.\n                          contradiction.\n                        }\n                        eapply atomic_write_step_keep_na_cur_pln; eauto.\n                    }\n\n                    assert (View.pln (TView.cur (Local.tview lc_src)) loc0 = View.pln (TView.cur (Local.tview lc2)) loc0). {\n                      assert (lc_tgt = lc_src). {\n                        eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                      }\n                      rewrite <- H11. clear H11.\n                      pose proof (classic (loc <> loc0)).\n                      destruct H11.\n                      2: {\n                        apply NNPP in H11.\n                        inv LOCAL1.\n                        rewrite H5 in LO.\n                        unfold Ordering.mem_ord_match in LO. \n                        discriminate.\n                      }\n                        eapply rlx_read_step_keep_na_cur_pln; eauto.\n                    }\n                    rewrite H10 in H11.\n                    rewrite <- H11.\n                    destruct H7 as (t & f & R & PLN & RLX & MSG).\n                    rewrite <- MEM_EQ_START in MSG.\n                    assert (Memory.future mem_tgt mem_tgt'). {\n                      inversion LOCAL_WF.\n                      eapply Local.program_step_future; eauto.\n                    }\n                    eapply Memory.future_get1 in H7; eauto.\n                    destruct H7 as (from' & msg' & MSG' & _ & LE).\n                    inv LE.\n                    do 3 eexists; splits; eauto.\n                }\n                - (** acq case, a little difference *)\n                  rewrite <- H18.\n                  rewrite <- AI_BLK in MATCH_AI.\n                  subst.\n                  (* rewrite MEM_EQ_START. *)\n                  unfolds match_abstract_interp.\n                  remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                  remember (AveLat.kill_reg (AveLat.GetExprs ai) r) as ai'.\n                  destruct ai eqn:EqAi.\n                  {\n                    unfolds AveLat.kill_reg.\n                    rewrite Heqai'. trivial.\n                  }\n                  {\n                    unfolds AveLat.kill_reg.\n                    rewrite Heqai'. trivial.\n                  } (** ai = CSet tuples *)\n                  destruct ai' eqn:EqAi'; trivial.\n                  {\n                    unfold AveLat.GetExprs in Heqai'.\n                    unfold AveLat.kill_reg in Heqai'. \n                    discriminate.\n                  }\n                  {\n                    unfold AveLat.GetExprs in Heqai'.\n                    unfold AveLat.kill_reg in Heqai'. \n                    discriminate.\n                  }\n                  intros.\n                  unfolds match_abstract_fact.\n                  destruct tu eqn:EqTu.\n                  { (** proof for: any (r', e) in ai' is still correct *)\n                    (** kill_reg r implies r' <> r /\\ r not in fv(e), implies eval(e) & eval(r) not changed, still match as in ai *)\n                    assert (r <> reg). {\n                      unfolds AveLat.kill_reg. inversion Heqai'.\n                      rewrite <- EqAi' in Heqai'.\n                      eapply AveLat.mem_of_kill_reg_implies_neq with (tu := tu) in Heqai'; eauto.\n                      rewrite EqTu in Heqai'. unfold AveTuple.get_reg in Heqai'. \n                      intro. rewrite H3 in Heqai'. contradiction. \n                      subst; trivial.\n                    }\n                    rename H3 into H4.\n                    pose proof H4.\n                    eapply regs_add_neg with (r:=r) (v:=Integers.Int.one) (regs:=regs_src) in H4.\n                    simpls.\n                    folds Const.t.\n                    rewrite H4.\n                    assert (~RegSet.mem r (Inst.regs_of_expr expr)). {\n                      unfolds AveLat.kill_reg. inversion Heqai'.\n                      eapply AveLat.mem_of_kill_reg_implies_nonfree_var with (r':=reg); eauto.\n                      rewrite H6 in H2.\n                      trivial.\n                    }\n                    eapply regs_add_nonfree_var_eq_eval_expr with (regs:=regs_src) (val:=Integers.Int.one) in H5.\n                    folds Const.t.\n                    rewrite <- H5.\n                    pose proof (MATCH_AI tu).\n                    assert (W.In tu tuples). {\n                      rewrite <- EqTu in H2.\n                      inversion Heqai'.\n                      rewrite H8 in H2.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply W.filter_1 in H2; trivial.\n                      eapply (AveTuple.compat_bool_isExpr).\n                      eapply (AveTuple.compat_bool_freeOfReg r).\n                    }\n                    apply H6 in H7. rewrite EqTu in H7. trivial.\n                  }\n                  { (** no more (r, x) in ai' *)\n                    rewrite <- EqTu in H2. \n                    eapply AveLat.mem_of_getExprs_implies_non_loc_in_ai \n                      with (r:=r) in EqTu; try contradiction; eauto.\n                  }\n                - (** sc, invalid case *)\n                  remember ( AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                  destruct ai eqn:Eq; rewrite <- H18.\n                  rewrite <- AI_BLK in MATCH_AI.\n                  rewrite <- Heqai in MATCH_AI. eapply never_match_bot in MATCH_AI. contradiction.\n                  eapply always_match_top.\n                  eapply always_match_top.\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H18; eauto.\n                folds AveAI.b.\n                rewrite H18.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H18; eauto.\n              rewrite <- H18. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n\n            { (** mem_injected inj;' promises_tgt' *)\n              assert (mem_inj_dom_eq inj'' mem_tgt'). {\n                unfolds eq_ident_mapping.\n                destruct INJ_MAP_MEM_TGT.\n                inversion LOCAL2.\n                inversion WRITE.\n                eapply prm_keeps_mem_inj_dom_eq with (inj:=inj') (inj':=inj'') in PROMISE; eauto.\n                intro. discriminate.\n              }\n              eapply Local.program_step_future in LOCAL'; eauto.\n              destruct LOCAL'. \n              inversion H19.\n              unfolds Memory.le.\n              inversion H18.\n              unfolds mem_injected.\n              intros.\n              apply PROMISES in MSG.\n              apply SOUND in MSG. trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto. \n        }\n        {\n          eapply Local.program_step_future; eauto. \n        } \n        }\n        {\n          assert (incr_inj inj' inj''). {\n            eapply construct_incr_inj1; eauto.\n\n          }\n          destruct PREEMPT as [EQ_INJ|INCR_INJ].\n          destruct EQ_INJ as (_ & EQ_INJ).\n          apply eq_inj_implies_incr in EQ_INJ.\n          eapply incr_inj_transitivity; eauto.\n          destruct INCR_INJ as (_ & EQ_INJ).\n          eapply incr_inj_transitivity; eauto.\n        }\n  } \n  { (** fence *)\n    inversion H. \n    inv STATE.\n    { (** fence_rel *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj'.\n        splits; eauto.\n        { (** fence -> fence  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_fence_rel; eauto.\n            eapply fence_rel_transformed_inst_by_fence_rel in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL.\n            rewrite <- H9.\n            rewrite MEM_EQ_START.  \n            eapply Local.step_fence; eauto.\n            (* rewrite <- H9 in LOCAL0; rewrite MEM_EQ_START in LOCAL0.  *)\n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H11. \n            rewrite SC_EQ_START in LOCAL0.\n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            subst.\n            unfold cse_invariant; simpls. splits; eauto.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H12 in H11.\n                folds AveAI.b.\n                rewrite H11.\n                eapply always_match_top.\n            }\n              eapply Ave_B.wf_transf_blk_step in H11; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H11.\n              eapply fence_rel_transformed_inst_by_fence_rel in TRSF_INST; eauto.\n              rewrite TRSF_INST in H11.\n              unfolds Ave_I.transf.\n                rewrite <- H11.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                unfolds match_abstract_interp.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                (* remember (AveLat.kill_reg (ai) r) as ai'. *)\n                destruct ai eqn:EqAi; trivial.\n                (** ai = CSet tuples *)\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { \n                  pose proof (MATCH_AI tu).\n                  rewrite <- EqTu in H2.\n                  apply H3 in H2. rewrite EqTu in H2. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                \n                  pose proof (MATCH_AI tu).\n                  rewrite <- EqTu in H2.\n                  apply H3 in H2.\n                  rewrite EqTu in H2. destruct H2. splits; eauto.\n                  assert (lc_tgt = lc_src). {\n                    eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                  }\n                  rewrite <- H5 in H4.\n                  (** TODO: fence preserve pln/rlx*)\n                  assert ((View.pln (TView.cur (Local.tview lc_tgt)) loc) = (View.pln (TView.cur (Local.tview lc_tgt')) loc)). {\n                    eapply fence_rel_step_keep_na_cur_pln; eauto. \n                  }\n                  assert ((View.rlx (TView.cur (Local.tview lc_tgt)) loc) = (View.rlx (TView.cur (Local.tview lc_tgt')) loc)). {\n                    eapply fence_rel_step_keep_na_cur_rlx; eauto. \n                  }\n                  rewrite <- H6. rewrite <- H7. trivial.\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H11; eauto.\n                folds AveAI.b.\n                rewrite H11.\n                eapply AveLat.ge_top.\n              }\n            \n              eapply Ave_B.wf_transf_blk_getlast in H11; eauto.\n              rewrite <- H11. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        { \n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n    }\n    { (** fence_acq *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj'.\n        splits; eauto.\n        { (** fence -> fence  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_fence_acq; eauto.\n            eapply fence_acq_transformed_inst_by_fence_acq in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL.\n            rewrite <- H9.\n            rewrite MEM_EQ_START.  \n            eapply Local.step_fence; eauto.\n            (* rewrite <- H9 in LOCAL0; rewrite MEM_EQ_START in LOCAL0.  *)\n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H11. \n            rewrite SC_EQ_START in LOCAL0.\n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            subst.\n            unfold cse_invariant; simpls. splits; eauto.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                eapply H12 in H11.\n                folds AveAI.b.\n                rewrite H11.\n                eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H11; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H11.\n              eapply fence_acq_transformed_inst_by_fence_acq in TRSF_INST; eauto.\n              rewrite TRSF_INST in H11.\n              unfolds Ave_I.transf.\n                rewrite <- H11.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.GetExprs (ai)) as ai'.\n                destruct ai eqn:EqAi; trivial.\n                {\n                  subst. \n                  eapply never_match_bot; trivial. \n                }\n                {\n                  subst. unfolds AveLat.GetExprs. \n                  unfold match_abstract_interp. trivial.\n                }\n                (** ai = CSet tuples *)\n                unfolds match_abstract_interp.\n                rewrite Heqai'. unfold AveLat.GetExprs.\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { \n                  pose proof (MATCH_AI tu).\n                  rewrite <- EqTu in H2.\n                  assert (W.In tu tuples). {\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                  }\n                  apply H3 in H4. rewrite EqTu in H4. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  eapply W.filter_2 in H2. unfolds AveTuple.isExpr. discriminate.\n                  eapply (AveTuple.compat_bool_isExpr).\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H11; eauto.\n                folds AveAI.b.\n                rewrite H11.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H11; eauto.\n              rewrite <- H11. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        { \n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n    }\n    { (** fence_sc *)\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj'.\n        splits; eauto.\n        { (** fence -> fence  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_fence_sc; eauto.\n            eapply fence_sc_transformed_inst_by_fence_sc in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            inversion LOCAL.\n            rewrite <- H9.\n            rewrite MEM_EQ_START.  \n            eapply Local.step_fence; eauto.\n            (* rewrite <- H9 in LOCAL0; rewrite MEM_EQ_START in LOCAL0.  *)\n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H11. \n            rewrite SC_EQ_START in LOCAL0.\n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            subst.\n            unfold cse_invariant; simpls. splits; eauto.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                  eapply H12 in H11.\n                  folds AveAI.b.\n                  rewrite H11.\n                  eapply always_match_top.\n              }\n              eapply Ave_B.wf_transf_blk_step in H11; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H11.\n              eapply fence_sc_transformed_inst_by_fence_sc in TRSF_INST; eauto.\n              rewrite TRSF_INST in H11.\n              unfolds Ave_I.transf.\n                rewrite <- H11.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.GetExprs (ai)) as ai'.\n                destruct ai eqn:EqAi; trivial.\n                {\n                  subst. \n                  eapply never_match_bot; trivial. \n                }\n                {\n                  subst. unfolds AveLat.GetExprs. \n                  unfold match_abstract_interp. trivial.\n                }\n                (** ai = CSet tuples *)\n                unfolds match_abstract_interp.\n                rewrite Heqai'. unfold AveLat.GetExprs.\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { \n                  pose proof (MATCH_AI tu).\n                  rewrite <- EqTu in H2.\n                  assert (W.In tu tuples). {\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                  }\n                  apply H3 in H4. rewrite EqTu in H4. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  eapply W.filter_2 in H2. unfolds AveTuple.isExpr. discriminate.\n                  eapply (AveTuple.compat_bool_isExpr).\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H11; eauto.\n                folds AveAI.b.\n                rewrite H11.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H11; eauto.\n              rewrite <- H11. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        { \n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n    }\n  }\n  { (** syscall *)\n    inversion H. \n    inv STATE.\n    {\n      inversion H1; simpls.\n      inversion INVARIANT. \n      inversion MATCH_LOCAL.\n      inversion MATCH_RTL_STATE; simpls.\n      rename H2 into SC_EQ_START.\n      destruct H3 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n\n      inversion MATCH_FRAME; simpls.\n\n      remember (transform_cdhp cdhp_src analysis) as cdhp_tgt.\n      remember (transform_blk blk_src (AveAI.br_from_i analysis !! l i)) as blk_tgt.\n      eapply transform_blk_induction' in TRANSF_BLK; eauto.\n      destruct TRANSF_BLK as (inst & b_src' & EqBlkSrc & TRSF).\n\n      destruct TRSF as (TRSF_INST & TRSF_BLK).\n      * \n        exists {|\n            State.regs :=  regs_src;\n            State.blk := b_src';\n            State.cdhp := cdhp_src;\n            State.cont := cont_src;\n            State.code := code_src\n          |} lc_tgt' sc_tgt' mem_tgt' inj'.\n        splits; eauto.\n        { (** fence -> fence  *)\n            eapply Thread.program_step_intro; simpls; eauto.\n            eapply State.step_out; eauto.\n            eapply out_transformed_inst_by_out in TRSF_INST; eauto.\n            rewrite <- TRSF_INST; trivial.\n            {\n              subst; trivial.\n            }\n            inversion LOCAL.\n            rewrite <- H8.\n            rewrite MEM_EQ_START.  \n            eapply Local.step_syscall; eauto.\n            assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n            }\n            rewrite <- H10. \n            rewrite SC_EQ_START in LOCAL0.\n            trivial. \n        }\n        { (** match state *)\n          inversion LOCAL.\n          eapply cse_match_state_intro with(inj':=inj'); simpls; eauto.\n          { (** invariant *)\n            subst.\n            unfold cse_invariant; simpls. splits; eauto.\n          }\n          {\n            eapply cse_match_local_state_intro; \n            try rewrite <- H3; eauto.\n            2: {eapply eq_refl. }\n            eapply cse_match_rtl_state_intro; eauto.\n            simpls.\n            eapply cse_match_frame_intro with(i:=i+1); eauto.\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            {\n              rewrite <- TRANSL_CDHP in Heqcdhp_tgt. trivial.\n            }\n            rewrite EqBlkSrc in PARTIAL_BLK.\n            eapply bb_from_i_plus_one; eauto.\n            {\n                rewrite <- AveAI.get_tail_from_i_eq_i_plus_one; \n                rewrite AI_BLK; trivial. \n            }\n            rewrite <- AI_BLK in TRSF_BLK.\n            rewrite AveAI.get_tail_from_i_eq_i_plus_one in TRSF_BLK; eauto. \n            { (** match ai *)\n              destruct ANALYSIS.\n              2: { (** case: analysis = top; always match_ai *)\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top). \n                  eapply H11 in H10.\n                  folds AveAI.b.\n                  rewrite H10.\n                  eapply always_match_top.\n              }\n              rename H10 into H11.\n              eapply Ave_B.wf_transf_blk_step in H11; eauto.\n              unfolds Ave_B.transf_step.\n              rewrite EqBlkSrc in H11.\n              eapply out_transformed_inst_by_out in TRSF_INST; eauto.\n              rewrite TRSF_INST in H11.\n              unfolds Ave_I.transf.\n                rewrite <- H11.\n                rewrite <- AI_BLK in MATCH_AI.\n                subst.\n                rewrite MEM_EQ_START.\n                remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n                remember (AveLat.GetExprs (ai)) as ai'.\n                destruct ai eqn:EqAi; trivial.\n                {\n                  subst. \n                  eapply never_match_bot; eauto. \n                }\n                {\n                  subst. unfolds AveLat.GetExprs. \n                  unfold match_abstract_interp. trivial.\n                }\n                (** ai = CSet tuples *)\n                unfolds match_abstract_interp.\n                rewrite Heqai'. unfold AveLat.GetExprs.\n                intros.\n                unfolds match_abstract_fact.\n                destruct tu eqn:EqTu.\n                { \n                  pose proof (MATCH_AI tu).\n                  rewrite <- EqTu in H2.\n                  assert (W.In tu tuples). {\n                    eapply W.filter_1 in H2; trivial.\n                    eapply (AveTuple.compat_bool_isExpr).\n                  }\n                  apply H3 in H4. rewrite EqTu in H4. trivial.\n                }\n                { (** proof for: (r, x) in ai' is still correct *)\n                  eapply W.filter_2 in H2. unfolds AveTuple.isExpr. discriminate.\n                  eapply (AveTuple.compat_bool_isExpr).\n                }\n            }\n            { (** blk-level fixpoint *)\n              eapply subblk_same_succ in EqBlkSrc.\n              rewrite <- EqBlkSrc; trivial.\n              destruct ANALYSIS.\n              2: {\n                intros.\n                eapply (AveAI.get_head_from_eval) with (l:=lp) in H10; eauto.\n                folds AveAI.b.\n                rewrite H10.\n                eapply AveLat.ge_top.\n              }\n              eapply Ave_B.wf_transf_blk_getlast in H10; eauto.\n              rewrite <- H10. \n              rewrite <- AI_BLK in FIXPOINT. trivial.\n            }\n            {\n              assert (loc_fact_valid (AveAI.getFirst (AveAI.br_from_i analysis !! l (i + 1)))).  {\n                {\n                  destruct ANALYSIS as [ANALYSIS | ANALYSIS].\n                  eapply transf_step_psrv_loc_fact_valid with (bb:=blk_src); eauto.\n                  subst analysis_blk.\n                  eapply Ave_B.wf_transf_blk_step; eauto.\n                  pose proof (AveAI.get_first_from_eval analysis l (i+1) AveLat.top) as A.\n                  apply A in ANALYSIS.\n                  folds AveAI.b.\n                  rewrite ANALYSIS. \n                  eapply top_is_loc_fact_valid.\n                }\n              }\n              trivial.\n          }\n\n            { (** mem_injected inj' promises_tgt' *)\n              inv LOCAL0. simpls.\n              eapply incr_inj_preserve_mem_injected with (inj:=inj); eauto.\n              destruct PREEMPT as [(_&EQ_INJ)|(_&INCR_INJ)].\n              eapply eq_inj_implies_incr in EQ_INJ; trivial.\n              trivial.\n            }\n        }\n        { \n          left.\n          splits; eauto.\n          unfold eq_inj; intros; tauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        }\n        { \n          eapply Local.program_step_future; eauto.\n        }\n        {\n          eapply Local.program_step_future; eauto.\n        } \n        }\n        { \n          destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n          apply eq_inj_implies_incr; trivial.\n          trivial.\n        }\n   }\n  }\n  Unshelve. eauto. \n  exact TView.bot.\n  trivial.\n  trivial.\n  trivial.\n  exact TView.bot.\n  trivial.\n  trivial.\n  trivial.\n  exact TView.bot.\n  trivial.\n  trivial.\nQed.\n\n(** Correctness of promise transition *)\nTheorem cse_match_state_preserving_prm:\n  forall te lo inj st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src b st_tgt' lc_tgt' sc_tgt' mem_tgt', \n    Thread.promise_step false te \n        (@Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n        (@Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') \n    ->   \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n      (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b)\n    -> \n      (exists st_src' lc_src' sc_src' mem_src' inj',\n          Thread.promise_step false te (@Thread.mk rtl_lang st_src lc_src sc_src mem_src) \n                                    (@Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') \n          /\\\n          (cse_match_state inj' lo \n          (Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') true)\n          /\\ \n          incr_inj inj inj'\n      ).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt) eqn:EqStTgt.\n  destruct st_tgt' as (regs_tgt', blk_tgt', cdhp_tgt', cont_tgt', code_tgt') eqn:EqStTgt'.\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc; simpls.\n  inversion H0.\n  inversion MATCH_LOCAL.\n  simpls.\n  inversion H.\n  inversion LOCAL.\n  inversion PROMISE.\n  { (** add *)\n    exists st_src lc_tgt'.\n    do 2 eexists.\n    pose proof (classic (msg = Message.reserve)). \n    destruct H16 as [RSV_MSG | NOT_RSV].\n    { \n    (** MSG is RSV *) \n      exists inj'; eauto.\n      (** FIXME: may equal proof *)\n      splits; eauto.\n      { (** tgt promise step -> src promise step *)\n        inversion H.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. destruct H16.\n        subst.\n        eapply Thread.promise_step_intro; eauto.\n        eapply Local.promise_step_intro with (promises2:=promises2); eauto.\n        rewrite <- PROMISES_EQ. destruct H31. rewrite <- H1; trivial.\n        rewrite <- TVIEW_EQ; trivial.\n      }\n       (** match state preserve *)\n       inversion H.\n       inversion LOCAL.\n       inversion INVARIANT. simpls. \n       destruct H31.\n       rewrite EqStSrc.\n       rewrite <- H18. rewrite H14.\n       eapply cse_match_state_intro with (inj':=inj'); simpls; eauto.\n       {\n         rewrite <- H14.\n         unfold cse_invariant; splits; simpls; eauto.\n         unfolds eq_ident_mapping.\n         destruct H32.\n         split.\n         2: {\n           intros.\n           apply H33 in H34. trivial.\n         }\n         { (** dom equal: no new reserve msg *)\n            eapply promise_resv_preserve_mem_inj_dom_eq; eauto.\n         }\n       }\n       {\n         inv MATCH_RTL_STATE; simpls.\n         inv MATCH_FRAME; simpls.\n         eapply cse_match_local_state_intro; simpls; eauto.\n         eapply cse_match_rtl_state_intro; simpls; eauto.\n         eapply cse_match_frame_intro; simpls; eauto.\n         { \n           remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n           unfolds match_abstract_interp.\n           destruct ai eqn:EqAi; eauto.\n           intros.\n           unfolds match_abstract_fact.\n           destruct tu eqn:EqTu; eauto.\n           - pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. apply H2 in H1; trivial.\n           - \n             pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. \n             apply H2 in H1; trivial. destruct H1; splits; eauto.\n             \n             destruct H3 as (t & f & R & PLN & RLX & MSG).\n             assert (lc_tgt = lc_src). {\n              eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n              }\n              rewrite H3.\n \n               assert (Memory.future mem_tgt mem_tgt'). {\n                 inversion LOCAL_WF.\n                 eapply Memory.promise_future; eauto.\n               }\n               clear H3; rename H4 into H3.\n               rewrite H31 in H3.\n               eapply Memory.future_get1 in H3; eauto. \n               destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n               inversion MLE.\n               rewrite <- H3 in MSG'.\n               do 3 eexists. splits; eauto.\n               (* rewrite TVIEW_EQ. *)\n               rewrite MSG'.\n               eapply f_equal.\n\n               rewrite H5.\n               subst.\n               econs.\n         } \n         { \n           eapply eq_refl.\n         }\n         { (** still mem_injected *)\n           assert (incr_inj inj inj'). {\n             destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n             eapply eq_inj_implies_incr; trivial.\n             trivial.\n           }\n           eapply incr_inj_preserve_mem_injected in H1; eauto.\n           assert (promises2 = promises0). {inv LC0. trivial. }\n           rewrite H2.\n           eapply promise_resv_keeps_promises_injected; eauto.\n         }\n       }\n       {\n         left.\n         splits; trivial.\n         eapply eq_inj_refl.\n       }\n       {\n         eapply Local.promise_step_future; eauto.\n       }\n       {\n         eapply Memory.promise_closed_timemap; eauto. \n         rewrite <- H14. trivial.\n       }\n       {\n         assert (Memory.future mem_tgt mem_tgt'). {\n           inversion LOCAL_WF.\n           eapply Memory.promise_future; eauto.\n         }\n         eapply Memory.future_closed; eauto.\n       }\n       {\n         destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n         eapply eq_inj_implies_incr; trivial.\n         trivial.\n       }\n     }\n    (** msg is not RSV *)\n    {\n      remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''. \n      exists (inj''); eauto.\n      splits; eauto.\n      { (** tgt promise step -> src promise step *)\n        inversion H.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. destruct H16.\n        subst.\n        eapply Thread.promise_step_intro; eauto.\n        eapply Local.promise_step_intro with (promises2:=promises2); eauto.\n        rewrite <- PROMISES_EQ. destruct H31. rewrite <- H1; trivial.\n        rewrite <- TVIEW_EQ; trivial.\n      }\n      { (** match state preserve *)\n        inversion H.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. \n        destruct H31.\n        rewrite EqStSrc.\n        rewrite <- H18. rewrite H14.\n        eapply cse_match_state_intro with (inj':=inj''); simpls; eauto.\n        {\n          rewrite <- H14.\n          unfold cse_invariant; splits; simpls; eauto.\n          unfolds eq_ident_mapping.\n          destruct H32.\n          split.\n          2: {\n            intros.\n            rewrite Heqinj'' in H34.\n            (* remember (loc_ts_eq_dec (loc, to) (loc1, t)) as LOC_TS_EQ. *)\n            des_ifH H34; simpls.\n            2: {\n              destruct o.\n              apply H33 in H34. trivial.\n              apply H33 in H34. trivial.\n            }\n            { \n              destruct a.\n              inv H34. apply eq_refl.\n            }\n          }\n          { (** dom equal *)\n            eapply prm_add_incr_mem_with_inj; eauto.\n          }\n        }\n        {\n          inv MATCH_RTL_STATE; simpls.\n          inv MATCH_FRAME; simpls.\n          eapply cse_match_local_state_intro; simpls; eauto.\n          eapply cse_match_rtl_state_intro; simpls; eauto.\n          eapply cse_match_frame_intro; simpls; eauto.\n          { \n            remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n            unfolds match_abstract_interp.\n            destruct ai eqn:EqAi; eauto.\n            intros.\n            unfolds match_abstract_fact.\n            destruct tu eqn:EqTu; eauto.\n            - pose proof (MATCH_AI tu).\n              rewrite EqTu in H2. apply H2 in H1; trivial.\n            -   \n              pose proof (MATCH_AI tu).\n              rewrite EqTu in H2. \n              apply H2 in H1; trivial. destruct H1; splits; eauto.\n              \n              destruct H3 as (t & f & R & PLN & RLX & MSG).\n              assert (lc_tgt = lc_src). {\n                eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                }\n                rewrite H3.\n   \n                 assert (Memory.future mem_tgt mem_tgt'). {\n                   inversion LOCAL_WF.\n                   eapply Memory.promise_future; eauto.\n                 }\n                 clear H3; rename H4 into H3.\n                 rewrite H31 in H3.\n                 eapply Memory.future_get1 in H3; eauto. \n                 destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                 inversion MLE.\n                 rewrite <- H3 in MSG'.\n                 do 3 eexists. splits; eauto.\n                 (* rewrite TVIEW_EQ. *)\n                 rewrite MSG'.\n                 eapply f_equal.\n  \n                 rewrite H5.\n                 subst.\n                 econs.\n          } \n          { \n            eapply eq_refl.\n          }\n          { (** still mem_injected *)\n            assert (incr_inj inj inj'). {\n              destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n              eapply eq_inj_implies_incr; trivial.\n              trivial.\n            }\n            eapply incr_inj_preserve_mem_injected in H1; eauto.\n            assert (promises2 = promises0). {inv LC0. trivial. }\n            rewrite H2.\n            eapply prm_add_keeps_promises_injected; eauto.\n          }\n        }\n        {\n          left.\n          splits; trivial.\n          eapply eq_inj_refl.\n        }\n        {\n          eapply Local.promise_step_future; eauto.\n        }\n        {\n          eapply Memory.promise_closed_timemap; eauto. \n          rewrite <- H14. trivial.\n        }\n        {\n          assert (Memory.future mem_tgt mem_tgt'). {\n            inversion LOCAL_WF.\n            eapply Memory.promise_future; eauto.\n          }\n          eapply Memory.future_closed; eauto.\n        }\n      }\n      {\n        assert (incr_inj inj' inj''). {\n          unfolds incr_inj.\n          intros.\n          rewrite Heqinj''.\n          des_ifs. destruct a. simpls.\n          rewrite <- H2 in H16.\n          inv INVARIANT.\n          destruct H4.\n          unfolds eq_ident_mapping; simpls. destruct H2.\n          apply H4 in H16. apply f_equal. trivial.\n        }\n        destruct PREEMPT as [EQ_INJ|INCR_INJ].\n        destruct EQ_INJ as (_ & EQ_INJ).\n        apply eq_inj_implies_incr in EQ_INJ.\n        eapply incr_inj_transitivity; eauto.\n        destruct INCR_INJ as (_ & EQ_INJ).\n        eapply incr_inj_transitivity; eauto.\n      }\n    }\n  }\n  { (** split *)\n    exists st_src lc_tgt'.\n    do 2 eexists.\n    pose proof (classic (msg = Message.reserve)). \n    destruct H16 as [RSV_MSG | NOT_RSV].\n    { (** msg cannot be RSV *)\n      inv PROMISES. destruct RESERVE as (val' & R' & G).\n      try discriminate.\n    }\n    (** split concrete msg: add one, change another's [from] *)\n    { \n        remember (fun loc1 to1 => if loc_ts_eq_dec (loc, to) (loc1, to1) then Some to else (inj' loc1 to1)) as inj''. \n        exists (inj''); eauto.\n        splits; eauto.\n        { (** tgt promise step -> src promise step *)\n          inversion H.\n          inversion LOCAL.\n          inversion INVARIANT. simpls. destruct H16.\n          subst.\n          eapply Thread.promise_step_intro; eauto.\n          eapply Local.promise_step_intro with (promises2:=promises2); eauto.\n          rewrite <- PROMISES_EQ. destruct H31. rewrite <- H1; trivial.\n          rewrite <- TVIEW_EQ; trivial.\n        }\n        (** match state preserve *)\n         inversion H.\n         inversion LOCAL.\n         inversion INVARIANT. simpls. \n         destruct H31.\n         rewrite EqStSrc.\n         rewrite <- H18. rewrite H14.\n         eapply cse_match_state_intro with (inj':=inj''); simpls; eauto.\n         {\n           rewrite <- H14.\n           unfold cse_invariant; splits; simpls; eauto.\n           unfolds eq_ident_mapping.\n           destruct H32.\n           split.\n           2: {\n             intros.\n             rewrite Heqinj'' in H34.\n             des_ifH H34; simpls.\n             { \n               destruct a. subst. \n                inv H34. \n                eapply eq_refl.\n             }\n             apply H33 in H34. trivial.\n           }\n           { (** dom equal*)\n              eapply prm_split_incr_mem_with_inj; eauto.\n           }\n         }\n         {\n           inv MATCH_RTL_STATE; simpls.\n           inv MATCH_FRAME; simpls.\n           eapply cse_match_local_state_intro; simpls; eauto.\n           eapply cse_match_rtl_state_intro; simpls; eauto.\n           eapply cse_match_frame_intro; simpls; eauto.\n           { \n             remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n             unfolds match_abstract_interp.\n             destruct ai eqn:EqAi; eauto.\n             intros.\n             unfolds match_abstract_fact.\n             destruct tu eqn:EqTu; eauto.\n             - pose proof (MATCH_AI tu).\n               rewrite EqTu in H2. apply H2 in H1; trivial.\n             - \n               pose proof (MATCH_AI tu).\n               rewrite EqTu in H2. \n               apply H2 in H1; trivial. destruct H1; splits; eauto. clear H1. rename H3 into H1.\n               rename H1 into H3.\n\n               destruct H3 as (t & f & R & PLN & RLX & MSG).\n               assert (lc_tgt = lc_src). {\n                 eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                 }\n                 rewrite H1.\n    \n                  assert (Memory.future mem_tgt mem_tgt'). {\n                    inversion LOCAL_WF.\n                    eapply Memory.promise_future; eauto.\n                  }\n                  rewrite H31 in H3.\n                  eapply Memory.future_get1 in H3; eauto. \n                  destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                  inversion MLE.\n                  rewrite <- H3 in MSG'.\n                  do 3 eexists. splits; eauto.\n                  rewrite MSG'.\n                  eapply f_equal.\n   \n                  rewrite H5.\n                  subst.\n                  econs.\n           } \n           { \n             eapply eq_refl.\n           }\n           { (** still promises injected *)\n             assert (incr_inj inj inj'). {\n               destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n               eapply eq_inj_implies_incr; trivial.\n               trivial.\n             }\n             eapply incr_inj_preserve_mem_injected in H1; eauto.\n             assert (promises2 = promises0). {inv LC0. trivial. }\n             rewrite H2.\n              eapply prm_split_keeps_promises_injected; eauto.\n           }\n         }\n         {\n           left.\n           splits; trivial.\n           eapply eq_inj_refl.\n         }\n         {\n           eapply Local.promise_step_future; eauto.\n         }\n         {\n           eapply Memory.promise_closed_timemap; eauto. \n           rewrite <- H14. trivial.\n         }\n         {\n           assert (Memory.future mem_tgt mem_tgt'). {\n             inversion LOCAL_WF.\n             eapply Memory.promise_future; eauto.\n           }\n           eapply Memory.future_closed; eauto.\n         }\n         {\n            assert (incr_inj inj' inj''). {\n              unfolds incr_inj.\n              intros.\n              rewrite Heqinj''.\n              des_ifs. destruct a. simpls.\n              rewrite <- H2 in H16.\n              inv INVARIANT.\n              destruct H4.\n              unfolds eq_ident_mapping; simpls. destruct H2.\n              apply H4 in H16. apply f_equal. trivial.\n            }\n            destruct PREEMPT as [EQ_INJ|INCR_INJ].\n            destruct EQ_INJ as (_ & EQ_INJ).\n            apply eq_inj_implies_incr in EQ_INJ.\n            eapply incr_inj_transitivity; eauto.\n            destruct INCR_INJ as (_ & EQ_INJ).\n            eapply incr_inj_transitivity; eauto.\n         }\n    }\n  }\n  { (** lower *)\n    exists st_src lc_tgt'.\n    do 2 eexists.\n    pose proof (classic (msg = Message.reserve)). \n    destruct H16 as [RSV_MSG | NOT_RSV].\n    { (** msg cannot be RSV *)\n      inv PROMISES. destruct RESERVE as (val' & R' & G).\n      inversion LOWER.\n      rewrite G in MSG_LE.\n      inversion MSG_LE.\n    }\n    (** concrete msg: need not change inj, msg's timestamp not changed *)\n    {\n      exists inj'; eauto.\n      (** FIXME: may equal proof *)\n      splits; eauto.\n      { (** tgt promise step -> src promise step *)\n        inversion H.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. destruct H16.\n        subst.\n        eapply Thread.promise_step_intro; eauto.\n        eapply Local.promise_step_intro with (promises2:=promises2); eauto.\n        rewrite <- PROMISES_EQ. destruct H31. rewrite <- H1; trivial.\n        rewrite <- TVIEW_EQ; trivial.\n      }\n      (** match state preserve *)\n       inversion H.\n       inversion LOCAL.\n       inversion INVARIANT. simpls. \n       destruct H31.\n       rewrite EqStSrc.\n       rewrite <- H18. rewrite H14.\n       eapply cse_match_state_intro with (inj':=inj'); simpls; eauto.\n       {\n         rewrite <- H14.\n         unfold cse_invariant; splits; simpls; eauto.\n         unfolds eq_ident_mapping.\n         destruct H32.\n         split.\n         2: {\n           intros.\n           apply H33 in H34. trivial.\n         }\n         { (** dom equal: no new reserve msg *)\n            (* eapply promise_resv_preserve_mem_inj_dom_eq; eauto. *)\n            eapply prm_lower_keeps_mem_inj_dom_eq; eauto.\n         }\n       }\n       {\n         inv MATCH_RTL_STATE; simpls.\n         inv MATCH_FRAME; simpls.\n         eapply cse_match_local_state_intro; simpls; eauto.\n         eapply cse_match_rtl_state_intro; simpls; eauto.\n         eapply cse_match_frame_intro; simpls; eauto.\n         { \n           remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n           unfolds match_abstract_interp.\n           destruct ai eqn:EqAi; eauto.\n           intros.\n           unfolds match_abstract_fact.\n           destruct tu eqn:EqTu; eauto.\n           - pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. apply H2 in H1; trivial.\n           - \n             pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. \n             apply H2 in H1; trivial. destruct H1; splits; eauto. clear H1; rename H3 into H1.\n             rename H1 into H3.\n\n             destruct H3 as (t & f & R & PLN & RLX & MSG).\n             assert (lc_tgt = lc_src). {\n               eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n               }\n               rewrite H1.\n  \n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Memory.promise_future; eauto.\n                }\n                rewrite H31 in H3.\n                eapply Memory.future_get1 in H3; eauto. \n                destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                inversion MLE.\n                rewrite <- H3 in MSG'.\n                do 3 eexists. splits; eauto.\n                rewrite MSG'.\n                eapply f_equal.\n \n                rewrite H5.\n                subst.\n                econs.\n         } \n         { \n           eapply eq_refl.\n         }\n         { (** still promises injected *)\n           assert (incr_inj inj inj'). {\n             destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n             eapply eq_inj_implies_incr; trivial.\n             trivial.\n           }\n           eapply incr_inj_preserve_mem_injected in H1; eauto.\n           assert (promises2 = promises0). {inv LC0. trivial. }\n           rewrite H2.\n           eapply prm_lower_keeps_promises_injected; eauto.\n         }\n       }\n       {\n         left.\n         splits; trivial.\n         eapply eq_inj_refl.\n       }\n       {\n         eapply Local.promise_step_future; eauto.\n       }\n       {\n         eapply Memory.promise_closed_timemap; eauto. \n         rewrite <- H14. trivial.\n       }\n       {\n         assert (Memory.future mem_tgt mem_tgt'). {\n           inversion LOCAL_WF.\n           eapply Memory.promise_future; eauto.\n         }\n         eapply Memory.future_closed; eauto.\n       }\n       {\n         destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n         eapply eq_inj_implies_incr; trivial.\n         trivial.\n       }\n    }\n  }\n  { (** remove *)\n    exists st_src lc_tgt'.\n    do 2 eexists.\n    pose proof (classic (msg = Message.reserve)). \n    destruct H16 as [RSV_MSG | NOT_RSV].\n    2: { (** msg cannot to concrete *)\n      rewrite RESERVE in NOT_RSV. try contradiction.\n    }\n    { (** remove a reserve msg, no need to change inj *)\n      exists inj'; eauto.\n      (** FIXME: may equal proof *)\n      splits; eauto.\n      { (** tgt promise step -> src promise step *)\n        inversion H.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. destruct H16.\n        subst.\n        eapply Thread.promise_step_intro; eauto.\n        eapply Local.promise_step_intro with (promises2:=promises2); eauto.\n        rewrite <- PROMISES_EQ. destruct H31. rewrite <- H1; trivial.\n        rewrite <- TVIEW_EQ; trivial.\n      }\n      (** match state preserve *)\n       inversion H.\n       inversion LOCAL.\n       inversion INVARIANT. simpls. \n       destruct H31.\n       rewrite EqStSrc.\n       rewrite <- H18. rewrite H14.\n       eapply cse_match_state_intro with (inj':=inj'); simpls; eauto.\n       {\n         rewrite <- H14.\n         unfold cse_invariant; splits; simpls; eauto.\n         unfolds eq_ident_mapping.\n         destruct H32.\n         split.\n         2: {\n           intros.\n           apply H33 in H34. trivial.\n         }\n         { (** dom equal: no new reserve msg *)\n            eapply promise_resv_preserve_mem_inj_dom_eq; eauto.\n         }\n       }\n       {\n         inv MATCH_RTL_STATE; simpls.\n         inv MATCH_FRAME; simpls.\n         eapply cse_match_local_state_intro; simpls; eauto.\n         eapply cse_match_rtl_state_intro; simpls; eauto.\n         eapply cse_match_frame_intro; simpls; eauto.\n         { \n           remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n           unfolds match_abstract_interp.\n           destruct ai eqn:EqAi; eauto.\n           intros.\n           unfolds match_abstract_fact.\n           destruct tu eqn:EqTu; eauto.\n           - pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. apply H2 in H1; trivial.\n           - \n             pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. \n             apply H2 in H1; trivial. destruct H1; splits; eauto. clear H1; rename H3 into H1. \n             rename H1 into H3.\n\n             destruct H3 as (t & f & R & PLN & RLX & MSG).\n             assert (lc_tgt = lc_src). {\n               eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n               }\n               rewrite H1.\n  \n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Memory.promise_future; eauto.\n                }\n                rewrite H31 in H3.\n                eapply Memory.future_get1 in H3; eauto. \n                destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                inversion MLE.\n                rewrite <- H3 in MSG'.\n                do 3 eexists. splits; eauto.\n                rewrite MSG'.\n                eapply f_equal.\n \n                rewrite H5.\n                subst.\n                econs.\n         } \n         { \n           eapply eq_refl.\n         }\n         { (** still mem_injected *)\n           assert (incr_inj inj inj'). {\n             destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n             eapply eq_inj_implies_incr; trivial.\n             trivial.\n           }\n           eapply incr_inj_preserve_mem_injected in H1; eauto.\n           assert (promises2 = promises0). {inv LC0. trivial. }\n           rewrite H2.\n\n           eapply promise_ccl_keeps_promises_injected; eauto.\n         }\n       }\n       {\n         left.\n         splits; trivial.\n         eapply eq_inj_refl.\n       }\n       {\n         eapply Local.promise_step_future; eauto.\n       }\n       {\n         eapply Memory.promise_closed_timemap; eauto. \n         rewrite <- H14. trivial.\n       }\n       {\n         assert (Memory.future mem_tgt mem_tgt'). {\n           inversion LOCAL_WF.\n           eapply Memory.promise_future; eauto.\n         }\n         eapply Memory.future_closed; eauto.\n       }\n       {\n         destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n         eapply eq_inj_implies_incr; trivial.\n         trivial.\n       }\n    }\n  }\nQed.\n\nTheorem cse_match_state_preserving_pf_prm:\n  forall lo inj st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src b st_tgt' lc_tgt' sc_tgt' mem_tgt', \n    Thread.pf_promise_step \n        (@Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n        (@Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') \n    ->   \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) \n      (Thread.mk rtl_lang st_src lc_src sc_src mem_src) b)\n    -> \n      (exists st_src' lc_src' sc_src' mem_src',\n          Thread.pf_promise_step (@Thread.mk rtl_lang st_src lc_src sc_src mem_src) \n                                    (@Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') \n          /\\\n          (cse_match_state inj lo \n          (Thread.mk rtl_lang st_tgt' lc_tgt' sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src' lc_src' sc_src' mem_src') b)\n      ).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt) eqn:EqStTgt.\n  destruct st_tgt' as (regs_tgt', blk_tgt', cdhp_tgt', cont_tgt', code_tgt') eqn:EqStTgt'.\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc; simpls.\n  inversion H0.\n  inversion MATCH_LOCAL.\n  simpls.\n  inversion H.\n  inversion PF_STEP.\n  inversion LOCAL.\n  inversion PROMISE.\n  { (** not add *)\n    rewrite <- H3 in PF. simpls. discriminate.\n  }\n  { (** split *)\n    rewrite <- H3 in PF. simpls. discriminate.  \n  }\n  { (** lower *)\n    exists st_src lc_tgt' sc_src mem_tgt'.\n    pose proof (classic (msg = Message.reserve)). \n    destruct H16 as [RSV_MSG | NOT_RSV].\n    { (** msg cannot be RSV *)\n      inv PROMISES. destruct RESERVE as (val' & R' & G).\n      inversion LOWER.\n      rewrite G in MSG_LE.\n      inversion MSG_LE.\n    }\n    (** concrete msg: need not change inj, msg's timestamp not changed *)\n    {\n      (** FIXME: may equal proof *)\n      splits; eauto.\n      { (** tgt promise step -> src promise step *) \n        inversion H.\n        inversion PF_STEP0.\n        inversion LOCAL.\n        inversion INVARIANT. simpls. destruct H31.\n        subst.\n        eapply Thread.pf_promise_step_intro; eauto.\n        eapply Thread.promise_step_intro with (loc:=loc) (from:=from) (to:=to) (kind:= Memory.op_kind_lower msg0); eauto.\n        assert (lc_tgt = lc_src). {\n          eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n        }\n        rewrite <- H31.\n        rewrite <- H1. \n        eapply Local.promise_step_intro with (promises2:=promises0); eauto.    \n    }\n      (** match state preserve *)\n       inversion H.\n       inversion LOCAL.\n       inversion INVARIANT. simpls. \n       destruct H17.\n       rewrite EqStSrc.\n       (* rewrite <- H18.  *)\n       (* rewrite H14. *)\n       eapply cse_match_state_intro with (inj':=inj'); simpls; eauto.\n       {\n         rewrite <- H14.\n         unfold cse_invariant; splits; simpls; eauto.\n         unfolds eq_ident_mapping.\n         destruct H18.\n         split.\n         2: {\n           intros.\n           apply H19 in H20. trivial.\n         }\n         { (** dom equal: no new reserve msg *)\n            (* eapply promise_resv_preserve_mem_inj_dom_eq; eauto. *)\n            eapply prm_lower_keeps_mem_inj_dom_eq; eauto.\n         }\n       }\n       {\n         inv MATCH_RTL_STATE; simpls.\n         inv MATCH_FRAME; simpls.\n         eapply cse_match_local_state_intro; simpls; eauto.\n         eapply cse_match_rtl_state_intro; simpls; eauto.\n         eapply cse_match_frame_intro; simpls; eauto.\n         { \n           remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n           unfolds match_abstract_interp.\n           destruct ai eqn:EqAi; eauto.\n           intros.\n           unfolds match_abstract_fact.\n           destruct tu eqn:EqTu; eauto.\n           - pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. apply H2 in H1; trivial.\n           - \n             pose proof (MATCH_AI tu).\n             rewrite EqTu in H2. \n             apply H2 in H1; trivial. destruct H1; splits; eauto. clear H1; rename H3 into H1.\n             rename H1 into H3.\n\n             destruct H3 as (t & f & R & PLN & RLX & MSG).\n             assert (lc_tgt = lc_src). {\n               eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n               }\n               rewrite H1.\n  \n                assert (Memory.future mem_tgt mem_tgt'). {\n                  inversion LOCAL_WF.\n                  eapply Memory.promise_future; eauto.\n                }\n                rewrite H17 in H3.\n                eapply Memory.future_get1 in H3; eauto. \n                destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                inversion MLE.\n                rewrite <- H3 in MSG'.\n                do 3 eexists. splits; eauto.\n                rewrite MSG'.\n                eapply f_equal.\n \n                rewrite H5.\n                subst.\n                econs.\n         } \n         { \n           eapply eq_refl.\n         }\n         { (** still promises injected *)\n           assert (incr_inj inj inj'). {\n             destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n             eapply eq_inj_implies_incr; trivial.\n             trivial.\n           }\n           eapply incr_inj_preserve_mem_injected in H1; eauto.\n           assert (promises2 = promises0). {inv LC0. trivial. }\n           rewrite H2.\n           eapply prm_lower_keeps_promises_injected; eauto.\n         }\n       }\n       {\n         eapply Local.promise_step_future; eauto.\n       }\n       {\n         eapply Memory.promise_closed_timemap; eauto. \n         rewrite <- H14. trivial.\n       }\n       {\n         assert (Memory.future mem_tgt mem_tgt'). {\n           inversion LOCAL_WF.\n           eapply Memory.promise_future; eauto.\n         }\n         eapply Memory.future_closed; eauto.\n       }\n    }\n  }\n  { (** cancel *)\n      exists st_src lc_tgt' sc_src mem_tgt'.\n      pose proof (classic (msg = Message.reserve)). \n      destruct H16 as [RSV_MSG | NOT_RSV].\n      2: { (** msg cannot to concrete *)\n        rewrite RESERVE in NOT_RSV. try contradiction.\n      }\n      { (** remove a reserve msg, no need to change inj *)\n        splits; eauto.\n        { (** tgt promise step -> src promise step *) \n          inversion H.\n          inversion PF_STEP0.\n          inversion LOCAL.\n          inversion INVARIANT. simpls. destruct H16.\n          subst.\n          eapply Thread.pf_promise_step_intro; eauto.\n          eapply Thread.promise_step_intro with (kind:= Memory.op_kind_cancel); eauto.\n          (* inv PF0. *)\n          destruct H31. rewrite <- n; trivial.\n          assert (lc_tgt = lc_src). {\n            eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n          }\n          rewrite <- H1. \n          eapply Local.promise_step_intro with (promises2:=promises0); eauto.\n        }\n        (** match state preserve *)\n        inversion H.\n        inversion PF_STEP0.\n\n        inversion LOCAL.\n        inversion INVARIANT. simpls. \n        destruct H31.\n        rewrite EqStSrc.\n        rewrite <- H18. rewrite H14.\n        eapply cse_match_state_intro with (inj':=inj'); simpls; eauto.\n        {\n          rewrite <- H14.\n          unfold cse_invariant; splits; simpls; eauto.\n          unfolds eq_ident_mapping.\n          destruct H32.\n          split.\n          2: {\n            intros.\n            apply H33 in H34. trivial.\n          }\n          { (** dom equal: no new reserve msg *)\n              eapply promise_resv_preserve_mem_inj_dom_eq; eauto.\n          }\n        }\n        {\n          inv MATCH_RTL_STATE; simpls.\n          inv MATCH_FRAME; simpls.\n          eapply cse_match_local_state_intro; simpls; eauto.\n          eapply cse_match_rtl_state_intro; simpls; eauto.\n          eapply cse_match_frame_intro; simpls; eauto.\n          { \n            remember (AveAI.getFirst (AveAI.br_from_i analysis !! l i)) as ai.\n            unfolds match_abstract_interp.\n            destruct ai eqn:EqAi; eauto.\n            intros.\n            unfolds match_abstract_fact.\n            destruct tu eqn:EqTu; eauto.\n            - pose proof (MATCH_AI tu).\n              rewrite EqTu in H2. apply H2 in H1; trivial.\n            - \n              pose proof (MATCH_AI tu).\n              rewrite EqTu in H2. \n              apply H2 in H1; trivial. destruct H1; split; eauto. clear H1; rename H3 into H1.\n              rename H1 into H3.\n\n              destruct H3 as (t & f & R & PLN & RLX & MSG).\n              assert (lc_tgt = lc_src). {\n                eapply cse_match_local_state_implies_eq_local in MATCH_LOCAL; eauto.\n                }\n                rewrite H1.\n   \n                 assert (Memory.future mem_tgt mem_tgt'). {\n                   inversion LOCAL_WF.\n                   eapply Memory.promise_future; eauto.\n                 }\n                 rewrite H31 in H3.\n                 eapply Memory.future_get1 in H3; eauto. \n                 destruct H3 as (f' &  m' & MSG' & TLE & MLE); eauto.\n                 inversion MLE.\n                 rewrite <- H3 in MSG'.\n                 do 3 eexists. splits; eauto.\n                 rewrite MSG'.\n                 eapply f_equal.\n  \n                 rewrite H5.\n                 subst.\n                 econs.\n          } \n          { \n            eapply eq_refl.\n          }\n          { (** still mem_injected *)\n            assert (incr_inj inj inj'). {\n              destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n              eapply eq_inj_implies_incr; trivial.\n              trivial.\n            }\n            eapply incr_inj_preserve_mem_injected in H1; eauto.\n            assert (promises2 = promises0). {inv LC0. trivial. }\n            rewrite H2.\n\n            eapply promise_ccl_keeps_promises_injected; eauto.\n          }\n        }\n        {\n          eapply Local.promise_step_future; eauto.\n        }\n        {\n          eapply Memory.promise_closed_timemap; eauto. \n          rewrite <- H14. trivial.\n        }\n        {\n          assert (Memory.future mem_tgt mem_tgt'). {\n            inversion LOCAL_WF.\n            eapply Memory.promise_future; eauto.\n          }\n          eapply Memory.future_closed; eauto.\n        }\n      }\n    }\nQed.\n\nTheorem incr_mem_preserve_match_ai:\nforall regs tview mem ai lo mem',\n    match_abstract_interp regs tview mem ai lo\n    -> \n    concrete_mem_incr mem mem'\n    -> \n    match_abstract_interp regs tview mem' ai lo.\nProof.\n    intros.\n    unfolds match_abstract_interp.\n    destruct ai eqn:EqAi; eauto.\n    intros.\n    apply H in H1.\n    clear H.\n    unfolds match_abstract_fact.\n    destruct tu eqn:EqTu; eauto. destruct H1; splits; eauto.\n    unfolds concrete_mem_incr. clear H. rename H1 into H.\n    destruct H as (t & f & R & PLN & RLX & MSG).\n\n    pose proof (H0 loc f t (regs reg) R).\n    apply H in MSG.\n    destruct MSG as (f' & R' & _ & _ & MSG' & _).\n    exists t f' R'. \n    splits; eauto.\nQed.\n\n(** proof for rely transition *)\nTheorem cse_match_state_preserving_rely:\n  forall lo inj inj' st_tgt st_src sc_tgt lc_src lc_tgt mem_tgt sc_src mem_src \n         sc_tgt' mem_tgt' sc_src' mem_src', \n    (cse_match_state inj lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt mem_tgt) (Thread.mk rtl_lang st_src lc_src sc_src mem_src) true)\n    ->\n      (Rely inj (Build_Rss sc_tgt mem_tgt sc_src mem_src)\n            inj' (Build_Rss sc_tgt' mem_tgt' sc_src' mem_src')\n            (Local.promises lc_tgt) (Local.promises lc_src) lo)\n    ->\n      (cse_invariant lo inj' (Build_Rss sc_tgt' mem_tgt' sc_src' mem_src'))\n     -> \n    (cse_match_state inj' lo \n      (Thread.mk rtl_lang st_tgt lc_tgt sc_tgt' mem_tgt') (Thread.mk rtl_lang st_src lc_src sc_src' mem_src') true).\nProof.\n  intros.\n  destruct st_tgt as (regs_tgt, blk_tgt, cdhp_tgt, cont_tgt, code_tgt) eqn:EqStTgt.\n  destruct st_src as (regs_src, blk_src, cdhp_src, cont_src, code_src) eqn:EqStSrc; simpls.\n  inv H; simpls. rename inj'0 into inj1.\n\n  inversion INVARIANT. \n  inversion MATCH_LOCAL.\n  inversion MATCH_RTL_STATE; simpls.\n  rename H into SC_EQ_START.\n  destruct H2 as (MEM_EQ_START & INJ_MAP_MEM_TGT).\n  inversion MATCH_FRAME; simpls.\n  inv H0.\n  inv ENV_STEPS.\n  simpls.\n  eapply cse_match_state_intro; simpls; eauto.\n  eapply cse_match_local_state_intro; simpls; eauto.\n  eapply cse_match_rtl_state_intro; simpls; eauto.\n  eapply cse_match_frame_intro; simpls; eauto.\n  eapply incr_mem_preserve_match_ai; eauto. \n  eapply incr_inj_preserve_mem_injected; eauto.\n  left. splits; trivial. eapply eq_inj_refl.\n  eapply incr_mem_preserve_local_wf; eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/CSEProofStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.28776781576105315, "lm_q1q2_score": 0.19048009634726937}}
{"text": "Require Export Coq.Lists.ListSet. \nRequire Export Coq.Classes.SetoidDec.\nRequire Export Coq.Lists.List.\nRequire Export Coq.Bool.Bool.\nRequire Export Coq.Classes.RelationClasses. \nRequire Export featuremodelrefinement_def.\nRequire Export featuremodelrefinement_int.\nImport FeatureModelRefinimentTheory.\nRequire Export formulatheory_def.\nRequire Export formulatheory_proofs.\nRequire Export formulatheory_int.\nImport FormulaTheory.\n\nProgram Instance FeatureModelRefinement_Ins: FeatureModelRefinement Formula Name FM := \n{\n  addMandatoryNode:= addMandatoryNode_func;\n  addOptionalNode := addOptionalNode_func;\n\n}. Next Obligation. {\n  apply name_dec_axiom.\n} Qed. Next Obligation. {\n  apply form_dec_axiom.\n} Qed. Next Obligation. {\n  unfold not in H4. unfold ns_func. unfold ns_func in H0, H3, H4, H2.\n  intuition. admit.\n  \n} Admitted. Next Obligation. {\n  unfold FeatureModelSemantics.wfFM_func. split. unfold addMandatoryNode_func in H.\n  destruct H. destruct H0. intuition. admit.\n  admit.\n\n} Admitted. Next Obligation. {\n  admit.\n} Admitted. Next Obligation. {\n  admit.\n} Admitted. Next Obligation. {\n  admit.\n} Admitted. Next Obligation. {\n  admit.\n\n} Admitted. Next Obligation. {\n  admit.\n\n} Admitted.\n\n\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/featuremodelrefinement_inst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.19045118083299223}}
{"text": "Require Import CoqlibC Maps.\nRequire Import ASTC Integers ValuesC EventsC Memory Globalenvs.\nRequire Import Op Registers.\nRequire Import sflib.\nRequire Import SmallstepC.\nRequire Export Simulation.\nRequire Import Skeleton Mod ModSem.\nRequire Import CtypesC CtypingC.\nRequire Import ClightC AsmC.\nRequire Import LinkingC.\nRequire Import MutrecHeader.\nRequire Import MutrecA MutrecB.\n\nSet Implicit Arguments.\n\nLocal Obligation Tactic := ii; ss; des; inv_all_once; ss; clarify.\n\nDefinition sk_link: Sk.t :=\n  match link (CSk.of_program signature_of_function MutrecA.prog) (Sk.of_program fn_sig MutrecB.prog) with\n  | Some sk => sk\n  | None => Sk.empty\n  end\n.\n\nSection MODSEM.\n\n  Variable skenv_link: SkEnv.t.\n  Variable p: unit.\n  Let skenv: SkEnv.t := (SkEnv.project skenv_link) sk_link.\n  Let ge: SkEnv.t := skenv.\n\n  Inductive state: Type :=\n  | Callstate\n      (i: int)\n      (m: mem)\n  | Returnstate\n      (s: int)\n      (m: mem)\n  .\n\n  Definition get_mem (st: state): mem :=\n    match st with\n    | Callstate _ m => m\n    | Returnstate _ m => m\n    end\n  .\n\n  Inductive initial_frame (args: Args.t): state -> Prop :=\n  | initial_frame1_intro\n      i m func_fg\n      (FINDF: Genv.find_funct ge (Args.fptr args) = Some (AST.Internal func_fg))\n      (VS: (Args.vs args) = [Vint i])\n      (M: (Args.m args) = m)\n      (RANGE: 0 <= i.(Int.intval) < MAX)\n    :\n      initial_frame args (Callstate i m)\n  .\n\n  Inductive step (se: Senv.t) (ge: SkEnv.t): state -> trace -> state -> Prop :=\n  | step_zero\n      i m\n    :\n      step se ge (Callstate i m) E0 (Returnstate (sum i) m)\n  .\n\n  Inductive final_frame: state -> Retv.t -> Prop :=\n  | final_frame_return\n      s m\n    :\n      final_frame (Returnstate s m) (Retv.mk (Vint s) m)\n  .\n\n  Program Definition modsem: ModSem.t :=\n    {|\n      ModSem.step := step;\n      ModSem.at_external := bot2;\n      ModSem.initial_frame := initial_frame;\n      ModSem.final_frame := final_frame;\n      ModSem.after_external := bot3;\n      ModSem.globalenv := ge;\n      ModSem.skenv := skenv;\n      ModSem.skenv_link := skenv_link;\n    |}\n  .\n\nEnd MODSEM.\n\nProgram Definition module: Mod.t :=\n  {| Mod.data := tt; Mod.get_sk := fun _ => sk_link; Mod.get_modsem := modsem; |}.\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/MutrecABspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.1903745990494368}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nRequire sha.sha.\nRequire Import sha.SHA256.\nLocal Open Scope logic.\n\nRequire Import sha.spec_sha.\nRequire Import sha.sha_lemmas.\nRequire Import sha.HMAC_functional_prog.\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.hmac.\nRequire Import sha.spec_hmac.\nRequire Import sha.vst_lemmas.\nRequire Import sha.hmac_pure_lemmas.\nRequire Import sha.hmac_common_lemmas.\n\nRequire Import sha.verif_hmac_init_part1.\nRequire Import sha.verif_hmac_init_part2.\n\nLemma initbodyproof Espec c k l key kv h1 pad ctxkey:\n@semax CompSpecs Espec (func_tycontext f_HMAC_Init HmacVarSpecs HmacFunSpecs)\n  (PROP  ()\n   LOCAL  (lvar _ctx_key (tarray tuchar 64) ctxkey;\n           lvar _pad (tarray tuchar 64) pad; temp _ctx c; temp _key k;\n           temp _len (Vint (Int.repr l)); gvar sha._K256 kv)\n   SEP  (data_at_ Tsh (tarray tuchar 64) ctxkey;\n         data_at_ Tsh (tarray tuchar 64) pad;\n         K_vector kv; initPre c k h1 l key))\n  (Ssequence (fn_body f_HMAC_Init) (Sreturn None))\n  (frame_ret_assert\n     (function_body_ret_assert tvoid\n        (PROP  ()\n         LOCAL ()\n         SEP  (hmacstate_ (hmacInit key) c; initPostKey k key; K_vector kv)))\n     (stackframe_of f_HMAC_Init)).\nProof. abbreviate_semax.\nfreeze [1; 2; 3] FR1. simpl.\nTime forward. (*0.8 versus 1.3*)\n\nTime assert_PROP (isptr ctxkey) as Pckey by entailer!. (*0.7*)\napply isptrD in Pckey; destruct Pckey as [ckb [ckoff PcKey]].\n  (*Issue subst ctxkey. fails*) rewrite PcKey in *.\n\n(*isolate branch if (key != NULL) *)\napply seq_assoc.\n(*from init_part1:\nDefinition initPostKeyNullConditional r (c:val) (k: val) h key ctxkey: mpred:=\n  match k with\n    Vint z => if Int.eq z Int.zero\n              then if zeq r Z0\n                   then (hmacstate_PreInitNull key h c) * (data_at_ Tsh (tarray tuchar 64) ctxkey)\n                   else FF\n              else FF\n  | Vptr b ofs => if zeq r 0 then FF\n                  else !!(Forall isbyteZ key) &&\n                    ((data_at Tsh t_struct_hmac_ctx_st keyedHMS c) *\n                     (data_at Tsh (tarray tuchar 64) (map Vint (map Int.repr (HMAC_SHA256.mkKey key)))\n                      ctxkey)  *\n                     (data_at Tsh (tarray tuchar (Zlength key)) (map Vint (map Int.repr key))\n                      (Vptr b ofs)))\n  | _ => FF\n  end.*)\n(*remember (EX  cb : block,\n                 (EX  cofs : int,\n                   (EX  r : Z,\n                    PROP  (c = Vptr cb cofs /\\ (r=0 \\/ r=1))\n                    LOCAL  (temp _reset (Vint (Int.repr r));\n                      lvar _ctx_key (tarray tuchar 64) (Vptr ckb ckoff);\n                      lvar _pad (tarray tuchar 64) pad;\n                      temp _ctx c; temp _key k; temp _len (Vint (Int.repr l));\n                      gvar sha._K256 kv)\n                    SEP  (data_at_ Tsh (tarray tuchar 64) pad;\n                    initPostKeyNullConditional r c k h1 key (Vptr ckb ckoff);\n                    K_vector kv)))) as PostKeyNull. *)\nforward_seq. instantiate (1:= PostKeyNull c k pad kv h1 l key ckb ckoff).\n{  assert (DD: Delta= initialized _reset Delta) by reflexivity.\n   rewrite DD.\n   eapply semax_pre_simple.\n   2: eapply hmac_init_part1; eassumption.\n   thaw' FR1. Time entailer!. (*2.2 versus 2.3*) }\n(*subst PostKeyNull.*)\nunfold PostKeyNull. Intros cb cofs r.\n(*Time normalize. (*2.3*)*)\nunfold POSTCONDITION, abbreviate. subst c.\nrename H0 into R.\n\n(*isolate branch if (reset) *)\napply seq_assoc.\n(*from init_part2:\nDefinition postResetHMS (iS oS: s256state): hmacstate :=\n  (default_val t_struct_SHA256state_st, (iS, oS)).\nDefinition initPostResetConditional r (c:val) (k: val) h key iS oS: mpred:=\n  match k with\n    Vint z => if Int.eq z Int.zero\n              then if zeq r Z0 then hmacstate_PreInitNull key h c else FF\n              else FF\n  | Vptr b ofs => if zeq r 0 then FF\n                  else !!(Forall isbyteZ key) &&\n                       ((data_at Tsh t_struct_hmac_ctx_st (postResetHMS iS oS) c) *\n                        (data_at Tsh (tarray tuchar (Zlength key)) (map Vint (map Int.repr key)) (Vptr b ofs)))\n  | _ => FF\n  end.*)\nremember (EX shaStates:_ ,\n          PROP  (innerShaInit (map Byte.repr (HMAC_SHA256.mkKey key))\n                           =(fst shaStates) /\\\n                  s256_relate (fst shaStates) (fst (snd shaStates)) /\\\n                  outerShaInit (map Byte.repr (HMAC_SHA256.mkKey key))\n                          = (fst (snd (snd shaStates))) /\\\n                  s256_relate (fst (snd (snd shaStates))) (snd (snd (snd shaStates))))\n          LOCAL  (lvar _pad (tarray tuchar 64) pad;\n                  lvar _ctx_key (tarray tuchar 64) (Vptr ckb ckoff);\n                  temp _ctx (Vptr cb cofs); temp _key k;\n                  temp _len (Vint (Int.repr l));\n                  gvar sha._K256 kv)\n          SEP  (data_at_ Tsh (tarray tuchar 64) pad;\n                data_at_ Tsh (Tarray tuchar 64 noattr) (Vptr ckb ckoff);\n                initPostResetConditional r (Vptr cb cofs) k h1 key (fst (snd shaStates)) (snd (snd (snd shaStates)));\n                K_vector kv))\n  as PostResetBranch.\nclear FR1.\neapply semax_seq. instantiate (1:=PostResetBranch).\n{ apply sequential'.\n  eapply semax_pre_post'.\n  Focus 3 . apply init_part2; try eassumption.\n  apply andp_left2. apply derives_refl. apply ENTAIL_refl. }\n\n{ (*Continuation after if (reset*)\n  subst PostResetBranch.\n  simpl update_tycon.\n  apply semax_extensionality_Delta with (Delta).\n  apply tycontext_sub_refl.\n  apply extract_exists_pre; intros [iSA [iS [oSA oS]]]. simpl.\n  assert_PROP (is_pointer_or_null k) as Ptr_null_k by entailer!.\n  destruct k; simpl in Ptr_null_k; try contradiction.\n  { (*Case key==null*)\n    subst i.\n    destruct R; subst r; simpl.\n    2: solve [apply semax_pre with (P':=FF); try entailer!; try apply semax_ff].\n    freeze [0; 1; 3] FR2.\n    Time normalize. (*5.7*)\n    rename H into InnerRelate.\n    rename H0 into OuterRelate.\n    unfold hmacstate_PreInitNull.\n    Intros s v.\n    rename H into Hs.\n    unfold hmac_relate_PreInitNull in Hs.\n    clear InnerRelate OuterRelate iS oS.\n    destruct h1.\n    destruct Hs as [IREL [OREL [ILEN [OLEN [ISHA OSHA]]]]].\n    destruct s as [mdS [iS oS]].\n\n(* Issue: why is update_reptype not simplifying? *)\n     match goal with |- context [@upd_reptype ?cs ?t ?gfs ?x ?v] =>\n           change (@upd_reptype cs t gfs x v) with (v,(iS,oS)) end.\n     simpl in *.\n\n     Time assert_PROP (field_compatible t_struct_hmac_ctx_st [] (Vptr cb cofs))\n       as FC_cb by entailer!. (*1.8 versus 3.9*)\n     assert (FC_cb_ictx: field_compatible t_struct_hmac_ctx_st [StructField _i_ctx] (Vptr cb cofs)).\n     { red in FC_cb. repeat split; try solve [apply FC_cb]. right; left; reflexivity. }\n     assert (FC_cb_md: field_compatible t_struct_hmac_ctx_st [StructField _md_ctx] (Vptr cb cofs)).\n     { red in FC_cb. repeat split; try solve [apply FC_cb]. left. reflexivity. }\n\n     Time unfold_data_at 1%nat. (*0.8, was slow*)\n     rewrite (field_at_data_at _ _ [StructField _i_ctx]).\n     (*VST Issue: why does rewrite field_at_data_at at 2 FAIL, but focus_SEP 3; rewrite field_at_data_at at 1. SUCCEED???\n        Answer: instead of using \"at 2\", use the field-specificer in the line above.*)\n     rewrite field_address_offset by auto with field_compatible.\n\n     freeze [0; 3] FR3.\n     Time forward_call ((Tsh, Tsh),\n             Vptr cb cofs,\n             Vptr cb (Ptrofs.add cofs (Ptrofs.repr 108)),\n             mkTrep t_struct_SHA256state_st iS,\n             @sizeof (@cenv_cs CompSpecs) t_struct_SHA256state_st).\n     (*5.9 versus 13*)\n     { rewrite sepcon_comm.\n       rewrite (field_at_data_at _ _ [StructField _md_ctx]).\n       rewrite field_address_offset by auto with field_compatible.\n       apply sepcon_derives.\n         eapply derives_trans. apply data_at_memory_block. apply derives_refl'. f_equal.\n         apply isptr_offset_val_zero; simpl; trivial.\n       Time cancel. (*0 versus 2*)\n     }\n\n     freeze [0; 1; 2] FR4.\n     Time forward. (*return*) (* 3 versus 13*) (*Issue : leaves a somewhat messy subgoal*)\n     unfold hmacInit.\n     remember (Int.unsigned (Int.repr (if zlt 64 (Zlength key) then 32 else Zlength key)))as KL.\n     Time entailer!. (*1.6 versus 7.4*)\n     unfold hmacstate_, hmac_relate.\n      Exists (iS, (iS, oS)).\n      simpl. Time entailer!. (*1.9 versus 5.6*)\n\n     unfold_data_at 1%nat.\n     rewrite (field_at_data_at _ _ [StructField _md_ctx]).\n     rewrite (field_at_data_at _ _ [StructField _i_ctx]).\n      rewrite field_address_offset by auto with field_compatible.\n      rewrite field_address_offset by auto with field_compatible.\n      simpl; rewrite Ptrofs.add_zero.\n      change (Tarray tuchar 64 noattr) with (tarray tuchar 64).\n      thaw FR4. thaw FR3. thaw FR2.\n      Time cancel. (*1.6 versus 0.7*)\n  }\n\n  { (*k is Vptr, key!=NULL*)\n    freeze [0;1;3] FR5.\n    destruct R as [R | R]; rewrite R; simpl.\n    solve [apply semax_pre with (P':=FF); try entailer; try apply semax_ff].\n    Intros.\n    rename H0 into InnerRelate.\n    rename H2 into OuterRelate. rename H3 into isbyteKey.\n    unfold postResetHMS. simpl.\n    freeze [0; 2] FR6.\n    Time assert_PROP (field_compatible t_struct_hmac_ctx_st [] (Vptr cb cofs)) as FC_cb by entailer!. (*2.8*)\n    assert (FC_cb_ictx: field_compatible t_struct_hmac_ctx_st [StructField _i_ctx] (Vptr cb cofs)).\n    { red in FC_cb. repeat split; try solve [apply FC_cb]. right; left; reflexivity. }\n    assert (FC_cb_md: field_compatible t_struct_hmac_ctx_st [StructField _md_ctx] (Vptr cb cofs)).\n    { red in FC_cb. repeat split; try solve [apply FC_cb]. left; reflexivity. }\n\n    unfold_data_at 1%nat.\n    freeze [0; 3] FR7.\n    rewrite (field_at_data_at Tsh t_struct_hmac_ctx_st [StructField _i_ctx]).\n    rewrite (field_at_data_at Tsh t_struct_hmac_ctx_st [StructField _md_ctx]).\n    rewrite field_address_offset by auto with field_compatible.\n    rewrite field_address_offset by auto with field_compatible.\n    simpl; rewrite Ptrofs.add_zero.\n\n    Time forward_call ((Tsh, Tsh),\n             Vptr cb cofs,\n             Vptr cb (Ptrofs.add cofs (Ptrofs.repr 108)),\n             mkTrep t_struct_SHA256state_st iS,\n             @sizeof (@cenv_cs CompSpecs) t_struct_SHA256state_st).\n    (* 4.7 versus 14.7 *)\n    { rewrite sepcon_comm.\n      apply sepcon_derives.\n          eapply derives_trans. apply data_at_memory_block. apply derives_refl.\n          Time cancel. (*0 versus 2*)\n    }\n    freeze [0; 1; 2] FR8.\n    Time forward. (*return*) (*3.4 versus 17*) (*Issue: leaves messy subgoal*)\n    Time entailer!. (* 1.2 versus 9*)\n    unfold data_block, hmacstate_, hmac_relate.\n    Exists (iS, (iS, oS)).\n    change (@data_at spec_sha.CompSpecs Tsh (tarray tuchar (@Zlength Z key)))\n       with (@data_at CompSpecs Tsh (tarray tuchar (@Zlength Z key))).\n    change (Tarray tuchar 64 noattr) with (tarray tuchar 64). simpl.\n    Time entailer!. (*2.9*)\n      unfold s256a_len, innerShaInit, outerShaInit.\n           repeat rewrite Zlength_mkArgZ,\n           map_length, mkKey_length. split; reflexivity.\n    unfold_data_at 1%nat.\n      rewrite (field_at_data_at _ _ [StructField _md_ctx]).\n      rewrite (field_at_data_at _ _ [StructField _i_ctx]).\n    rewrite field_address_offset by auto with field_compatible.\n    rewrite field_address_offset by auto with field_compatible.\n    simpl; rewrite Ptrofs.add_zero.\n    thaw FR8. thaw FR7. thaw FR6. thaw FR5.\n    Time cancel. (*1.7 versus 1.2 penalty when melting*)\n  }\n}\nTime Qed. (*25 versus 49*)\n\nLemma body_hmac_init: semax_body HmacVarSpecs HmacFunSpecs\n       f_HMAC_Init HMAC_Init_spec.\nProof.\nstart_function.\napply initbodyproof.\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/sha/verif_hmac_init.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.19037459377410101}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.assert_lemmas.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.jmeq_lemmas.\nRequire Export VST.floyd.fieldlist.\nRequire Export VST.floyd.compact_prod_sum.\nRequire Export VST.zlist.sublist.\n\nDefinition proj_struct (i : ident) (m : members) {A: member -> Type} (v: compact_prod (map A m)) \n    (d: A (get_member i m)): A (get_member i m) :=\n  proj_compact_prod (get_member i m) m v d member_dec.\n\nDefinition proj_union (i : ident) (m : members) {A: member -> Type} (v: compact_sum (map A m)) \n   (d: A (get_member i m)): A (get_member i m) :=\n  proj_compact_sum (get_member i m) m v d member_dec.\n\nDefinition members_union_inj {m: members} {A} (v: compact_sum (map A m)) (it: member): Prop :=\n  compact_sum_inj v it member_dec.\n\n(* TODO: We should use the following two definition in replace_refill lemmas in the future. And avoid using compact prod/sum directly. *)\n\nDefinition upd_struct (i : ident) (m : members) {A: member -> Type} (v: compact_prod (map A m)) \n   (v0: A (get_member i m)): compact_prod (map A m) :=\n  upd_compact_prod _ v (get_member i m) v0 member_dec.\n\nDefinition upd_union (i : ident) (m : members) {A: member -> Type} (v: compact_sum (map A m)) \n   (v0: A (get_member i m)): compact_sum (map A m) :=\n  upd_compact_sum _ v (get_member i m) v0 member_dec.\n\nLemma get_member_name: forall a m,\n  members_no_replicate m = true ->\n  In a m ->\n  get_member (name_member a) m = a.\nProof.\n intros.\n unfold members_no_replicate in H.\n apply compute_list_norepet_e in H.\n induction m.\n inv H0.\n simpl in H. inv H.\n  destruct H0.\n subst. simpl. rewrite if_true by auto. auto.\n simpl. rewrite if_false; auto.\n contradict H3.\n rewrite <- H3.\n apply in_map. auto.\nQed.\n\nLemma in_get_member:\n  forall i m,\n   in_members i m ->\n   In (get_member i m) m.\nProof.\nintros.\n induction m.\n inv H.\n simpl in *.\n  if_tac. auto.\n  destruct H. subst. contradiction.\n  right. auto.\nQed.\n \n\nLemma proj_struct_JMeq: forall (i: ident) (m : members) \n   {A1 A2: member -> Type} \n   (v1: compact_prod (map A1 m)) (v2: compact_prod (map A2 m)) \n  (d1: A1 (get_member i m)) (d2: A2 (get_member i m)),\n  (forall i, in_members i m -> @eq Type (A1 (get_member i m)) (A2 (get_member i m))) ->\n  members_no_replicate m = true ->\n  in_members i m ->\n  JMeq v1 v2 ->\n  JMeq (proj_struct i m v1 d1) (proj_struct i m v2 d2).\nProof.\n  intros.\n  apply proj_compact_prod_JMeq; auto.\n  + clear - H H0.\n    intros.\n    rewrite <- (get_member_name i m); auto.\n    apply H.\n    apply List.in_map with (f := name_member) in H1.\n    auto.\n  +\n   apply in_get_member; auto.\nQed.\n\nLemma members_union_inj_JMeq: forall (m : members) \n  {A1 A2: member -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)),\n  (forall i, in_members i m -> @eq Type (A1 (get_member i m)) (A2 (get_member i m))) ->\n  members_no_replicate m = true ->\n  JMeq v1 v2 ->\n  (forall it, members_union_inj v1 it <-> members_union_inj v2 it).\nProof.\n  intros.\n  apply compact_sum_inj_JMeq; auto.\n  intros a ?.\n  specialize (H (name_member a)).\n  spec H.\n  + \n    apply in_map; auto.\n  +\n     rewrite <- (get_member_name a m); auto.\nQed.\n\nLemma proj_union_JMeq: forall (i: ident) (m : members)\n  {A1 A2: member -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)) (d1: A1 (get_member i m)) (d2: A2 (get_member i m)),\n  (forall i, in_members i m -> @eq Type (A1 (get_member i m)) (A2 (get_member i m))) ->\n  members_no_replicate m = true ->\n  members_union_inj v1 (get_member i m) ->\n  JMeq v1 v2 ->\n  JMeq (proj_union i m v1 d1) (proj_union i m v2 d2).\nProof.\n  intros.\n  apply proj_compact_sum_JMeq; auto.\n  + clear - H H0.\n    intros.\n    rewrite <- (get_member_name i m); auto.\n    apply H.\n    apply List.in_map with (f := name_member) in H1.\n    auto.\nQed.\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/aggregate_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.19037458280886504}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import riscv.util.BitWidths.\nRequire Import riscv.util.Monads.\nRequire Import riscv.Decode.\nRequire Import riscv.Memory. (* should go before Program because both define loadByte etc *)\nRequire Import riscv.Program.\nRequire Import riscv.Execute.\nRequire Import riscv.util.PowerFunc.\nRequire Import riscv.Utility.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import riscv.Minimal.\n\nSection Riscv.\n\n  Context {t: Set}.\n\n  Context {MW: MachineWidth t}.\n\n  Context {Mem: Set}.\n\n  Context {MemIsMem: Memory Mem t}.\n\n  Context {RF: Type}.\n  Context {RFI: RegisterFile RF Register t}.\n\n  Inductive LogEvent :=\n  | EvLoadWord(addr: Z)(i: Instruction)\n  | EvStoreWord(addr: Z)(v: word 32).\n  \n  Definition Log := list LogEvent.\n  \n  Record RiscvMachineL := mkRiscvMachineL {\n    machine: @RiscvMachine t Mem RF;\n    log: Log;\n  }.\n\n  Definition with_machine m ml := mkRiscvMachineL m ml.(log).\n  Definition with_log l ml := mkRiscvMachineL ml.(machine) l.  \n\n  Definition liftL0{B: Type}(f: OState RiscvMachine B):  OState RiscvMachineL B :=\n    fun s => let (ob, ma) := f s.(machine) in (ob, with_machine ma s).\n\n  Definition liftL1{A B: Type}(f: A -> OState RiscvMachine B): A -> OState RiscvMachineL B :=\n    fun a s => let (ob, ma) := f a s.(machine) in (ob, with_machine ma s).\n\n  Definition liftL2{A1 A2 B: Type}(f: A1 -> A2 -> OState RiscvMachine B):\n    A1 -> A2 -> OState RiscvMachineL B :=\n    fun a1 a2 s => let (ob, ma) := f a1 a2 s.(machine) in (ob, with_machine ma s).\n                                           \n  Instance IsRiscvMachineL: RiscvProgram (OState RiscvMachineL) t :=  {|\n      getRegister := liftL1 getRegister;\n      setRegister := liftL2 setRegister;\n      getPC := liftL0 getPC;\n      setPC := liftL1 setPC;\n      loadByte   := liftL1 loadByte;\n      loadHalf   := liftL1 loadHalf;\n      loadWord a :=\n        m <- get;\n        res <- (liftL1 loadWord a);\n        put (with_log (m.(log) ++ [EvLoadWord (regToZ_unsigned a) (decode RV64IM (uwordToZ res))]) m);;\n        Return res;\n      loadDouble := liftL1 loadDouble;\n      storeByte   := liftL2 storeByte;\n      storeHalf   := liftL2 storeHalf;\n      storeWord a v :=\n        m <- get;\n        put (with_log (m.(log) ++ [EvStoreWord (regToZ_unsigned a) v]) m);;\n        liftL2 storeWord a v;\n      storeDouble := liftL2 storeDouble;\n      step := liftL0 step;\n      getCSRField_MTVecBase := liftL0 getCSRField_MTVecBase;\n      endCycle A := Return None;\n  |}.\n\n  Definition putProgram(prog: list (word 32))(addr: t)(ma: RiscvMachineL): RiscvMachineL :=\n    with_machine (putProgram prog addr ma.(machine)) ma.\n\nEnd Riscv.\n\nExisting Instance IsRiscvMachineL. (* needed because it was defined inside a Section *)\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/MinimalLogging.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406758018019, "lm_q1q2_score": 0.1902450761622471}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\n\n(* Borrow from CompCert *)\nRequire Import Coqlib.\nRequire Import Bitvectors.\n\nRequire Import AST.\nRequire Import Semantics.\nRequire Import Utils.\nRequire Import Builtins.\nRequire Import BuiltinSem.\nRequire Import Values.        \n\nRequire Import EvalTac.\nRequire Import SplitTest.\n\nLemma eval_a :\n  eval_expr ge empty a (bits (v 1)).\nProof.\n  g.\n  e. e. e. e. e. g.\n  e. e. e. e. e. e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. e. g.\n  e. e. e. repeat e. e.\n  repeat e.\n  e. e. e. e. g.\n  e. e. e. repeat e. e.\n  repeat e. \n  e. e. e. e.\n  e. e. e. e. e. e.\n  e. e. e. e. g.\n  e. e. e. e. e. e. e. e.\n  e. e. repeat e. e.\n  eapply select_split. e. reflexivity.\n  simpl. reflexivity.\n  e. e. e. g.\n  e. e. e. e. e. e. e. e.\n  e.\n  e. repeat e.\n  e. eapply select_slice.\n  repeat e. reflexivity.\n  simpl. repeat e.\n  Unshelve.\n  all: exact nz.\nQed.  \n  ", "meta": {"author": "GaloisInc", "repo": "cryptol-semantics", "sha": "b4d8b55ec9b3b796427eb9e270e73e1857c597bf", "save_path": "github-repos/coq/GaloisInc-cryptol-semantics", "path": "github-repos/coq/GaloisInc-cryptol-semantics/cryptol-semantics-b4d8b55ec9b3b796427eb9e270e73e1857c597bf/.old/SplitTestA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.19024507263306137}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import DenseOrder.\nRequire Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import WFConfig.\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 lo\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2 lo)\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 lo\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind lo)\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 lo e th1 th2\n      (STEP: @Thread.step lo 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 lo\n      (STEP: @Thread.opt_step lang lo 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 lo\n      (STEP: rtc (@Thread.all_step lang lo) 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 lo\n      (STEP: rtc (@Thread.tau_step lang lo) 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  intros. inv H; econstructor; eauto.\nQed.\n\nLemma rtc_reserve_step_promise_consistent\n      lang th1 th2 lo\n      (STEPS: rtc (@Thread.reserve_step lang lo) 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 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 lo\n      (STEPS: rtc (@Thread.cancel_step lang lo) 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 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) lo\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (STEPS: rtc (@Thread.reserve_step lang lo) th1 th2)\n  :\n    Local.promise_consistent (Thread.local th2).\nProof.\n  ginduction STEPS; eauto.  i. eapply IHSTEPS.\n  inv H. inv STEP. 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) lo\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (STEPS: rtc (@Thread.cancel_step lang lo) th1 th2)\n  :\n    Local.promise_consistent (Thread.local th2).\nProof.\n  ginduction STEPS; eauto.  i. eapply IHSTEPS.\n  inv H. inv STEP. 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 lo\n      (CONS: @Thread.consistent lang th lo)\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  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 lo\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2 lo)\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 lo\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind lo)\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\nHint Resolve read_step_promise_consistent write_step_promise_consistent promise_step_promise_consistent:\n  solve_promise_consistent.\n\nLemma promise_consistent_prsv_thread_nprm_step:\n  forall n lang lo (e e': Thread.t lang)\n         (CLOSED_MEM: Memory.closed (Thread.memory e))\n         (LOCAL_WF: Local.wf (Thread.local e) (Thread.memory e))\n         (NPRM_STEPS: rtcn (@Thread.nprm_step lang lo) n e e')\n         (CONS: Local.promise_consistent (Thread.local e')),\n    Local.promise_consistent (Thread.local e).\nProof.\n  induction n; intros.\n  - inv NPRM_STEPS; eauto.\n  - inv NPRM_STEPS.  \n    inv A12.\n    {\n      (* program step *)\n      des.\n      inv PROG; simpls.\n      Ltac solve_not_sc_fence A IHn:=\n        eapply IHn in A; eauto with solve_promise_consistent.\n      \n      inv LOCAL.\n      {\n        (* silent *)\n        solve_not_sc_fence A23 IHn.\n      }\n      {\n        (* read *)\n        solve_not_sc_fence A23 IHn.\n        simpl.\n        eapply local_wf_read; eauto.\n      }\n      {\n        (* write *)\n        solve_not_sc_fence A23 IHn; simpl.\n        eapply write_step_closed_mem; eauto.\n        eapply local_wf_write; eauto.\n      }\n      {\n        (* update *)\n        solve_not_sc_fence A23 IHn; simpl.\n        eapply write_step_closed_mem with (releasedr := releasedr); eauto.\n        inv LOCAL1.\n        eapply closed_mem_implies_closed_msg; eauto.\n        eapply local_wf_read; eauto.\n        eapply local_wf_upd; eauto.\n      }\n      {\n        (* fence *)\n        destruct (Ordering.le Ordering.seqcst ordw) eqn:SEQCST.\n        {\n          (* sc fence *)\n          destruct ordw; simpls.\n          inv LOCAL0.\n          eapply Local.bot_promise_consistent.\n          exploit PROMISES; eauto.\n        }\n        {\n          (* not sc fence *)\n          solve_not_sc_fence A23 IHn; simpl.\n          eapply fence_step_promise_consistent; eauto.\n          inv LOCAL0.\n          eapply local_wf_fence_not_seqcst; eauto.\n          destruct lc1; eauto.\n        }\n      }\n      {\n        ss.\n      }\n    }\n    {\n      (* cancel step *)\n      inv PF. ss.\n      destruct kind; ss.\n      destruct msg1; ss.\n      solve_not_sc_fence A23 IHn; eauto; simpl.\n      inv LOCAL.\n      inv PROMISE.\n      eapply Memory.lower_closed; eauto.\n      inv LOCAL.\n      eapply local_wf_promise; eauto.\n      destruct lc1; eauto.\n      inv LOCAL; simpls.\n      inv PROMISE; ss.\n      solve_not_sc_fence A23 IHn; eauto; simpl.\n      eapply Memory.cancel_closed; eauto.\n      eapply local_wf_promise; eauto.\n      destruct lc1; eauto.\n    }\nQed.\n\nLemma read_promise_not_consistent\n      lc mem loc from to msg lc' mem' kind loc0 to0 val0 released ord lc'' lo\n      (PROMISE: Local.promise_step lc mem loc from to msg lc' mem' kind)\n      (LOCAL: Local.read_step lc' mem' loc0 to0 val0 released ord lc'' lo)\n      (CONS: Local.promise_consistent lc''):\n  (loc, to) <> (loc0, to0).\nProof.\n  intro CONTR; inv CONTR.\n  inv PROMISE.\n  cut(Memory.op_kind_is_cancel kind = false); ii.\n  eapply Memory.promise_get2 in PROMISE0; eauto.\n  des.\n  dup LOCAL.\n  inv LOCAL0; ss.\n  rewrite GET_MEM in GET. inv GET.\n  eapply promise_consistent_promise_read in LOCAL; eauto.\n  eapply Time.lt_strorder in LOCAL; eauto.\n  destruct (Memory.op_kind_is_cancel kind) eqn:IS_CCL; eauto.\n  destruct kind; ss.\n  inv PROMISE0.\n  eapply Memory.remove_get0 in MEM; des.\n  inv LOCAL; ss.\n  rewrite GET0 in GET1; ss.\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/PromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.19018713091644482}}
{"text": "Require Import Util LengthEq AllInRel Map SetOperations.\nRequire Import Var Val EqDec Computable Var Fresh Envs IL Annotation AppExpFree.\nRequire Import Liveness.Liveness LabelsDefined.\nRequire Import SimF Filter ReplaceIf ListToStmt.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\n\nFixpoint compile s {struct s}\n  : stmt  :=\n  match s with\n    | stmtLet x e s => stmtLet x e (compile s)\n    | stmtIf x s t => stmtIf x (compile s) (compile t)\n    | stmtApp l Y  =>\n      let Y' := List.filter NotVar Y in\n      let xl := @fresh_list var _\n                           fresh\n                           (list_union (List.map Ops.freeVars Y)) (length Y') in\n      list_to_stmt xl Y' (stmtApp l (replace_if NotVar Y (Var \u229d xl)))\n    | stmtReturn x => stmtReturn x\n    | stmtFun F t => stmtFun (List.map (fun Zs => (fst Zs, compile (snd Zs))) F) (compile t)\n  end.\n\nInstance SR : PointwiseProofRelationF params := {\n   ParamRelFP G VL VL' :=   VL = VL' /\\ length VL = length G;\n   ArgRelFP E E' G Z Z' := Z = Z' /\\ length Z = length G\n}.\n\nLemma sim_EAE' r L L' V s\n  : labenv_sim SimExt (sim r) SR (block_Z \u229d L) L L'\n    -> \u276cL\u276d = \u276cL'\u276d\n    -> sim r SimExt (L, V, s) (L',V, compile s).\nProof.\n  revert_except s.\n  sind s; destruct s; simpl; intros; simpl in * |- *.\n  - destruct e.\n    + eapply (sim_let_op il_statetype_F); eauto.\n    + eapply (sim_let_call il_statetype_F); eauto.\n  - eapply (sim_cond il_statetype_F); eauto.\n  - case_eq (omap (op_eval V) (List.filter NotVar Y)); intros.\n    + destruct (get_dec L (counted l)) as [[[bE bZ bs n]]|].\n      * decide (length Y = length bZ).\n        -- eapply sim_expansion_closed;\n             [\n             | eapply star2_refl\n             | eapply list_to_stmt_correct;\n               eauto using fresh_spec, fresh_list_nodup, fresh_list_spec\n             ]; eauto.\n           ++ eapply labenv_sim_app; eauto. simpl.\n             intros; split; intros; eauto; dcr; subst.\n             case_eq (omap (op_eval V) (List.filter IsVar Y)); intros.\n             ** exploit (omap_filter_partitions _ _ _ H4 H1).\n                intros; repeat cases; eauto.\n                exists Yv; repeat split; eauto with len.\n                erewrite omap_replace_if.\n                --- rewrite <- H7; eauto.\n                --- erewrite omap_op_eval_agree; eauto.\n                    rewrite <-  update_with_list_agree';\n                      eauto using fresh_spec, fresh_list_nodup,\n                      fresh_list_spec with len.\n                    eapply agree_on_incl.\n                    symmetry.\n                    eapply update_with_list_agree_minus; eauto.\n                    eapply not_incl_minus. reflexivity.\n                    symmetry.\n                    eapply disj_2_incl.\n                    eapply fresh_list_spec; eauto using fresh_spec.\n                    eapply list_union_incl; intros; eauto with cset.\n                    inv_get.\n                    eapply incl_list_union; eauto using map_get_1.\n                    eapply fresh_list_nodup; eauto using fresh_spec.\n                --- erewrite omap_op_eval_agree; [ eapply H1 | | ].\n                    Focus 2.\n                    rewrite omap_lookup_vars;\n                      eauto using fresh_list_nodup, fresh_spec with len.\n                    eapply fresh_list_nodup; eauto using fresh_spec.\n                    rewrite <-  update_with_list_agree';\n                      eauto using fresh_spec, fresh_list_nodup,\n                      fresh_list_spec with len. reflexivity.\n                    eapply fresh_list_nodup; eauto using fresh_spec.\n             ** exfalso. eapply omap_filter_none in H4. congruence.\n           ++ eauto with len.\n           ++ eapply fresh_list_nodup; eauto using fresh_spec.\n           ++ eapply disj_2_incl.\n             eapply fresh_list_spec; eauto using fresh_spec.\n             eapply list_union_incl; intros; eauto with cset.\n             inv_get. eapply incl_list_union; eauto using map_get_1.\n        -- perr.\n      * perr.\n    + perr.\n      erewrite omap_filter_none in def; eauto. congruence.\n  - pno_step.\n  - pone_step.\n    left. eapply IH; eauto 20 with len.\n    + rewrite List.map_app.\n      eapply labenv_sim_extension_ptw; eauto with len.\n      * intros; hnf; intros; inv_get; simpl in *; dcr; subst.\n        get_functional. eapply IH; eauto 20 with len.\n        rewrite List.map_app. eauto.\n      * hnf; intros; simpl in *; subst; inv_get; simpl; eauto.\nQed.\n\nLemma sim_EAE V s\n  : @sim _ statetype_F _ statetype_F bot3 SimExt (nil, V, s) (nil,V, compile s).\nProof.\n  eapply sim_EAE'; eauto.\n  eapply labenv_sim_nil.\nQed.\n\nLemma EAE_app_expfree s\n  : app_expfree (compile s).\nProof.\n  sind s; destruct s; simpl; eauto using app_expfree.\n  - eapply list_to_stmt_app_expfree.\n    intros.\n    eapply replace_if_get_inv in H as [A [B [[C D]|[C D]]]].\n    + dcr; subst; inv_get; eauto using isVar.\n    + subst. cases in C; isabsurd. decide (isVar A); eauto.\n      exfalso; eauto.\n  - econstructor; intros; inv_get; eauto using app_expfree.\nQed.\n\nLemma EAE_paramsMatch_app Y'' L f Y Y'\n  :  get L (counted f) (\u276cY''\u276d + \u276cY\u276d)\n     -> disj (of_list Y') (list_union (Ops.freeVars \u229d Y)\n                                     \u222a list_union (Ops.freeVars \u229d Y''))\n     -> NoDupA _eq Y'\n     -> \u276cY'\u276d = \u276cList.filter NotVar Y\u276d\n     -> paramsMatch\n         (list_to_stmt Y'\n            (List.filter NotVar Y)\n            (stmtApp f (Y'' ++ replace_if NotVar Y (Var \u229d Y')))) L.\nProof.\n  intros. general induction Y.\n  - simpl. destruct Y'; isabsurd.\n    econstructor; eauto with len.\n  - simpl in *; cases.\n    destruct Y'; isabsurd; simpl.\n    econstructor.\n    + rewrite cons_app. rewrite app_assoc.\n      eapply IHY.\n      * rewrite app_length; simpl. rewrite <- plus_assoc; eauto.\n      * rewrite List.map_app. rewrite list_union_app.\n        simpl in *.\n        rewrite <- union_assoc.\n        rewrite disj_app.\n        split.\n        eapply (disj_incl H0).\n        eauto with cset.\n        setoid_rewrite list_union_start_swap at 3.\n        clear. cset_tac.\n        hnf; intros. invt NoDupA.\n        rewrite of_list_1 in H3.\n        revert H4 H7 H3. clear. cset_tac.\n      * eauto.\n      * eauto.\n    + rewrite cons_app, app_assoc.\n      eapply IHY.\n      * rewrite app_length; simpl. rewrite <- plus_assoc; eauto.\n      * rewrite List.map_app. rewrite list_union_app.\n        simpl in *.\n        rewrite <- union_assoc.\n        rewrite disj_app.\n        split.\n        eapply (disj_incl H0).\n        eauto with cset.\n        setoid_rewrite list_union_start_swap at 3.\n        clear. cset_tac.\n        eapply disj_2_incl; eauto.\n        rewrite list_union_start_swap.\n        clear; cset_tac.\n      * eauto.\n      * eauto.\nQed.\n\nLemma EAE_paramsMatch s L\n  : paramsMatch s L\n    -> paramsMatch (compile s) L.\nProof.\n  intros.\n  general induction H; simpl; eauto using paramsMatch.\n  - eapply (EAE_paramsMatch_app nil); eauto.\n    + simpl. eapply disj_2_incl.\n      eapply fresh_list_spec; eauto using fresh_spec with cset.\n      eauto with cset.\n    + eapply fresh_list_nodup; eauto using fresh_spec.\n    + eauto with len.\n  - econstructor; intros; inv_get; rewrite !map_map in *; simpl; eauto.\nQed.\n\nLemma freeVars_filter_Var Y\n  : list_union (Ops.freeVars \u229d Y) [=]\n               list_union (Ops.freeVars \u229d List.filter NotVar Y)\n               \u222a list_union (Ops.freeVars \u229d List.filter IsVar Y).\nProof.\n  general induction Y; simpl; norm_lunion; eauto with cset.\n  - repeat cases; simpl; norm_lunion; try now (exfalso; eauto).\n    + rewrite IHY. rewrite !union_assoc. reflexivity.\n    + rewrite IHY. clear IHY n.\n      cset_tac.\nQed.\n\nLtac norm_lunion :=\n repeat match goal with\n      | [ |- context [ fold_left union ?A ?B ]] =>\n        match B with\n          | empty => fail 1\n          | _ => rewrite (list_union_start_swap A B)\n        end\n      | [ H : context [ fold_left union ?A ?B ] |- _ ] =>\n        match B with\n          | empty => fail 1\n          | _ => rewrite (list_union_start_swap A B) in H\n        end\n    end.\n\nLtac clr_prtct :=\n        repeat match goal with\n               | [ H : protected_setin_fnc _ _ |- _ ] => clear H\n               | [ H : protected _ |- _ ] => clear H\n               end.\n\nLemma freeVars_replaceIf Y (xl:list var) (Len:\u276cList.filter NotVar Y\u276d = \u276cxl\u276d)\n      (Disj:disj (of_list xl) (list_union (Ops.freeVars \u229d Y)))\n  : list_union (Ops.freeVars \u229d replace_if NotVar Y (Var \u229d xl)) \\ of_list xl\n               [=] list_union (Ops.freeVars \u229d List.filter IsVar Y).\n\nProof.\n  rewrite freeVars_filter_Var in Disj.\n  general induction Y; simpl in *; eauto with cset.\n  - cset_tac.\n  - do 2 cases; simpl in *; try now (exfalso; eauto).\n    + destruct xl; simpl in *; clear_trivial_eqs;\n      norm_lunion; simpl in *.\n      * rewrite minus_dist_union.\n        setoid_rewrite minus_minus_add at 2.\n        rewrite IHY; eauto.\n        -- revert Disj; clear; cset_tac.\n        -- eapply disj_incl; eauto.\n           eauto with cset.\n           clear. cset_tac.\n    + norm_lunion.\n      rewrite minus_dist_union.\n      rewrite (IHY (xl)); eauto.\n      * revert Disj; clear; cset_tac.\n      * eapply disj_incl; eauto.\n        clear; cset_tac.\nQed.\n\n\nLemma EAE_freeVars s\n  : freeVars (compile s) [=] freeVars s.\nProof.\n  sind s; destruct s; simpl;\n    try rewrite !IH; eauto with cset.\n  - rewrite list_to_stmt_freeVars; eauto with len.\n    + simpl.\n      setoid_rewrite freeVars_filter_Var at 5.\n      eapply eq_union_lr; eauto.\n      rewrite freeVars_replaceIf; eauto.\n      rewrite fresh_list_length; eauto.\n      eapply fresh_list_spec, fresh_spec.\n    + eapply disj_2_incl.\n      eapply fresh_list_spec.\n      eapply fresh_spec.\n      setoid_rewrite freeVars_filter_Var at 2; eauto with cset.\n  - eapply eq_union_lr; eauto.\n    eapply list_union_eq; eauto with len.\n    intros; inv_get; simpl.\n    rewrite IH; eauto.\nQed.\n\n(*\nFixpoint compile_live (LV:list (set var)) (s:stmt) (a:ann (set var)) : ann (set var) :=\n  match s, a with\n  | stmtLet x e s, ann1 lv an as a =>\n    let an' := compile_live LV s an in\n    ann1 (getAnn an' \\ singleton x) an'\n  | stmtIf e s t, ann2 lv ans ant =>\n    let ans' := compile_live LV s ans in\n    let ant' := compile_live LV t ant in\n    ann2 (getAnn ans' \u222a getAnn ant') ans' ant'\n  | stmtApp f Y, ann0 lv =>\n    let lv := nth (counted f) LV \u2205 in\n    ann0 (list_union (Ops.freeVars \u229d Y) \u222a lv)\n  | stmtReturn e, ann0 lv => ann0 (Ops.freeVars e)\n  | stmtFun F t, annF lv ans ant =>\n    let ans' := zip (fun Zs a => compile_live (getAnn \u229d ans ++ LV) (snd Zs) a) F ans in\n    annF lv ans' (compile_live (getAnn \u229d ans ++ LV) t ant)\n  | _, a => a\n  end.\n*)\n\n(*\nFixpoint live_for_stmts (Y:list op) (xl:list var) (lv:set var) : ann (set var) :=\n  match Y, xl with\n  | e::Y, x::xl =>\n    let an' := live_for_stmts Y xl lv in\n    ann1 (Ops.freeVars e \u222a (getAnn an' \\ singleton x)) an'\n  | _, _ => ann0 lv\n  end.\n\nFixpoint compile_live (LV:list (set var)) (s:stmt) (a:ann (set var)) : ann (set var) :=\n  match s, a with\n  | stmtLet x e s, ann1 lv an as a => ann1 lv (compile_live LV s an)\n  | stmtIf e s t, ann2 lv ans ant =>\n    ann2 lv (compile_live LV s ans) (compile_live LV t ant)\n  | stmtApp f Y, ann0 lv =>\n    let lv_f := nth (counted f) LV \u2205 in\n    let Y' := (List.filter NotVar Y) in\n    let xl := (fresh_list fresh (list_union (List.map Ops.freeVars Y)) (length Y')) in\n    let lv' := list_union (Ops.freeVars \u229d (List.filter IsVar Y)) \u222a of_list xl \u222a lv_f in\n    setTopAnn (live_for_stmts Y' xl lv') lv\n  | stmtReturn e, ann0 lv => ann0 lv\n  | stmtFun F t, annF lv ans ant =>\n    let ans' := zip (fun Zs a => compile_live (getAnn \u229d ans ++ LV) (snd Zs) a) F ans in\n    annF lv ans' (compile_live (getAnn \u229d ans ++ LV) t ant)\n  | _, a => a\n  end.\n\nLemma compile_live_getAnn LV s a\n  : getAnn (compile_live LV s a) [=] getAnn a.\nProof.\n  general induction s; destruct a; simpl; eauto.\n  rewrite getAnn_setTopAnn; eauto.\nQed.\n\nLemma incl_set_right (X : Type) `{H : OrderedType X} s t\n  : s [=] t -> t \u2286 s.\nProof.\n  intros. rewrite H0. reflexivity.\nQed.\n\nLemma EAE_live i ZL Lv s lv\n  : live_sound i ZL Lv s lv\n    -> live_sound i ZL Lv (compile s) (compile_live Lv s lv).\nProof.\n  intros.\n  general induction H; simpl;\n    eauto 20 using live_sound, compile_live_getAnn.\n  - econstructor; eauto; rewrite compile_live_getAnn; eauto.\n  - econstructor; eauto; rewrite compile_live_getAnn; eauto.\n  -\n  - econstructor; eauto.\n    + rewrite !map_map; simpl.\n      eapply live_sound_monotone; eauto.\n      eapply PIR2_get; intros; inv_get; eauto with len.\n      rewrite map_zip in H5.\n      eapply get_app_cases in H6. destruct H6; dcr; inv_get.\n      rewrite get_app_lt in H5; eauto with len. inv_get.\n      rewrite compile_live_getAnn. eauto.\n      rewrite get_app_ge in H5; eauto with len.\n      rewrite zip_length2 in H5; eauto. rewrite map_length in H7.\n      rewrite H0 in H5. inv_get. eauto.\n      rewrite zip_length2; eauto. rewrite map_length in H8. omega.\n    + eauto with len.\n    + intros; inv_get. simpl.\n      rewrite !map_map; simpl.\n      eapply live_sound_monotone; eauto.\n      eapply PIR2_get; intros; inv_get; eauto with len.\n      rewrite map_zip in H5.\n      eapply get_app_cases in H8. destruct H8; dcr; inv_get.\n      rewrite get_app_lt in H5; eauto with len. inv_get.\n      rewrite compile_live_getAnn. eauto.\n      rewrite get_app_ge in H5; eauto with len.\n      rewrite zip_length2 in H5; eauto. rewrite map_length in H9.\n      rewrite H0 in H5. inv_get. eauto.\n      rewrite zip_length2; eauto. rewrite map_length in H10. omega.\n    + intros; inv_get; simpl.\n      exploit H3; eauto; dcr.\n      destruct i; simpl in *; rewrite compile_live_getAnn; eauto.\n    + rewrite compile_live_getAnn; eauto.\nQed.\n*)", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Lowering/EAE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.32082130082460697, "lm_q1q2_score": 0.1901400741689652}}
{"text": "\n(*\nabhishek@brixpro:~/parametricity/reflective-paramcoq/test-suite$ ./coqid.sh indFunArg\n*)\n\nRequire Import SquiggleEq.terms.\n\n\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.PIWNew.\n\nRequire Import Template.Template.\n\n\n(* Inductive nat : Set :=  O : nat | S : forall ns:nat, nat. *)\n\nRun TemplateProgram (genParamInd [] true true \"Coq.Init.Datatypes.bool\").\nRun TemplateProgram (mkIndEnv \"indTransEnv\" [\"Coq.Init.Datatypes.bool\"]).\n\n(*\nDefinition xx :=\n(fix\n Coq_Init_Datatypes_nat_pmtcty_RR0_iso (tind tind\u2082 tind\u2082o : nat)\n                                       (tind_R : Coq_Init_Datatypes_nat_pmtcty_RR0\n                                                 tind tind\u2082)\n                                       (tind_Ro : \n                                        Coq_Init_Datatypes_nat_pmtcty_RR0\n                                          tind tind\u2082o) {struct tind} :\n   tind\u2082 = tind\u2082o :=\n   match\n     tind as tind0\n     return\n       (Coq_Init_Datatypes_nat_pmtcty_RR0 tind0 tind\u2082 ->\n        Coq_Init_Datatypes_nat_pmtcty_RR0 tind0 tind\u2082o -> tind\u2082 = tind\u2082o)\n   with\n   | 0%nat =>\n       match\n         tind\u2082 as tind\u20820\n         return\n           (forall tind\u2082o0 : nat,\n            Coq_Init_Datatypes_nat_pmtcty_RR0 0 tind\u20820 ->\n            Coq_Init_Datatypes_nat_pmtcty_RR0 0 tind\u2082o0 -> tind\u20820 = tind\u2082o0)\n       with\n       | 0%nat =>\n           fun (tind\u2082o0 : nat)\n             (tind_R0 : Coq_Init_Datatypes_nat_pmtcty_RR0 0 0)\n             (tind_Ro0 : Coq_Init_Datatypes_nat_pmtcty_RR0 0 tind\u2082o0) =>\n           let Hexeq :=\n             Coq_Init_Datatypes_nat_pmtcty_RR0_constr_0_inv tind_R0\n               (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 0 0 =>\n                0%nat = tind\u2082o0)\n               (match\n                  tind\u2082o0 as tind\u2082o1\n                  return\n                    (Coq_Init_Datatypes_nat_pmtcty_RR0 0 tind\u2082o1 ->\n                     0%nat = tind\u2082o1)\n                with\n                | 0%nat =>\n                    fun tind_Ro1 : Coq_Init_Datatypes_nat_pmtcty_RR0 0 0 =>\n                    Coq_Init_Datatypes_nat_pmtcty_RR0_constr_0_inv tind_Ro1\n                      (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 0 0 =>\n                       0%nat = 0%nat) (fiat (0%nat = 0%nat))\n                | S o =>\n                    fun tind_Ro1 : Coq_Init_Datatypes_nat_pmtcty_RR0 0 (S o)\n                    => match tind_Ro1 return (0%nat = S o) with\n                       end\n                end tind_Ro0) in\n           Hexeq\n       | S x =>\n           fun (tind\u2082o0 : nat)\n             (tind_R0 : Coq_Init_Datatypes_nat_pmtcty_RR0 0 (S x))\n             (_ : Coq_Init_Datatypes_nat_pmtcty_RR0 0 tind\u2082o0) =>\n           match tind_R0 return (S x = tind\u2082o0) with\n           end\n       end tind\u2082o\n   | S x =>\n       match\n         tind\u2082 as tind\u20820\n         return\n           (forall tind\u2082o0 : nat,\n            Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) tind\u20820 ->\n            Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) tind\u2082o0 ->\n            tind\u20820 = tind\u2082o0)\n       with\n       | 0%nat =>\n           fun (tind\u2082o0 : nat)\n             (tind_R0 : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) 0)\n             (_ : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) tind\u2082o0) =>\n           match tind_R0 return (0%nat = tind\u2082o0) with\n           end\n       | S x0 =>\n           fun (tind\u2082o0 : nat)\n             (tind_R0 : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) (S x0))\n             (tind_Ro0 : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) tind\u2082o0) =>\n           let Hexeq :=\n             Coq_Init_Datatypes_nat_pmtcty_RR0_constr_1_inv x x0 tind_R0\n               (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) (S x0) =>\n                S x0 = tind\u2082o0)\n               (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 x x0 =>\n                match\n                  tind\u2082o0 as tind\u2082o1\n                  return\n                    (Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) tind\u2082o1 ->\n                     S x0 = tind\u2082o1)\n                with\n                | 0%nat =>\n                    fun tind_Ro1 : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) 0\n                    => match tind_Ro1 return (S x0 = 0%nat) with\n                       end\n                | S o =>\n                    fun\n                      tind_Ro1 : Coq_Init_Datatypes_nat_pmtcty_RR0 \n                                   (S x) (S o) =>\n                    Coq_Init_Datatypes_nat_pmtcty_RR0_constr_1_inv x o\n                      tind_Ro1\n                      (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 (S x) (S o)\n                       => S x0 = S o)\n                      (fun _ : Coq_Init_Datatypes_nat_pmtcty_RR0 x (*x0*) o =>\n                       fiat (S x0 = S o))\n                end tind_Ro0) in\n           Hexeq\n       end tind\u2082o\n   end tind_R tind_Ro).\n   *)\n\nRun TemplateProgram (genParamIndTotAll [] true \"Coq.Init.Datatypes.bool\").\n\n\n\n(* functions wont work until we fully produce the goodness of inductives *)", "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/bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.1900590146841838}}
{"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 Vector.\nImport VectorNotations.\nRequire Import Kami.AllNotations.\nRequire Import FpuKami.Definitions.\nRequire Import FpuKami.MulAdd.\nRequire Import FpuKami.Compare.\nRequire Import FpuKami.NFToIN.\nRequire Import FpuKami.INToNF.\nRequire Import FpuKami.Classify.\nRequire Import FpuKami.ModDivSqrt.\nRequire Import ProcKami.FU.\nRequire Import ProcKami.RiscvIsaSpec.Insts.Fpu.FpuFuncs.\nRequire Import List.\nImport ListNotations.\n\nSection Fpu.\n  Context `{procParams: ProcParams}.\n  Context `{fpuParams : FpuParams}.\n\n  Open Scope kami_expr.\n\n  Section ty.\n    Variable ty : Kind -> Type.\n\n    Definition FDivSqrtInput\n      (sqrt : Bool @# ty)\n      (_ : ContextCfgPkt @# ty)\n      (context_pkt_expr : ExecContextPkt ## ty)\n      :  inpK expWidthMinus2 sigWidthMinus2 ## ty\n      := LETE context_pkt\n           :  ExecContextPkt\n           <- context_pkt_expr;\n         RetE\n           (STRUCT {\n              \"isSqrt\" ::= sqrt;\n              \"nfA\"    ::= bitToNF (fp_get_float Flen (#context_pkt @% \"reg1\"));\n              \"nfB\"    ::= bitToNF (fp_get_float Flen (#context_pkt @% \"reg2\"));\n              \"round\"  ::= rounding_mode (#context_pkt);\n              \"tiny\"   ::= $$true\n            } : inpK expWidthMinus2 sigWidthMinus2 @# ty).\n\n    Definition FDivSqrtOutput (sem_out_pkt_expr : outK expWidthMinus2 sigWidthMinus2 ## ty)\n      :  PktWithException ExecUpdPkt ## ty\n      := LETE sem_out_pkt\n           :  outK expWidthMinus2 sigWidthMinus2\n                   <- sem_out_pkt_expr;\n         LETC val1 : RoutedReg <- (STRUCT {\n                                       \"tag\" ::= Const ty (natToWord RoutingTagSz FloatRegTag);\n                                       \"data\"\n                                       ::= (OneExtendTruncLsb Rlen\n                                                              (pack (NFToBit (#sem_out_pkt @% \"outNf\")))\n                                            : Bit Rlen @# ty)\n                                  });\n         LETC val2 : RoutedReg <- (STRUCT {\n                               \"tag\"  ::= Const ty (natToWord RoutingTagSz FflagsTag);\n                               \"data\" ::= (csr (#sem_out_pkt @% \"exception\") : 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\" ::= #fstVal;\n              \"snd\" ::= Invalid\n            } : PktWithException ExecUpdPkt @# ty).\n  End ty.\n\n  Definition FDivSqrt\n    :  FUEntry\n    := {|\n         fuName := append \"fdivsqrt\" fpu_suffix;\n         fuFunc\n           := fun ty (sem_in_pkt_expr : inpK expWidthMinus2 sigWidthMinus2 ## ty)\n                => LETE sem_in_pkt\n                     :  inpK expWidthMinus2 sigWidthMinus2\n                     <- sem_in_pkt_expr;\n                   div_sqrt_expr (#sem_in_pkt);\n         fuInsts\n           := [\n                {|\n                  instName   := append \"fdiv\" fpu_suffix;\n                  xlens      := xlens_all;\n                  extensions := fpu_exts;\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal fmtField fpu_format_field;\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal rs3Field      ('b\"00011\")\n                       ];\n                  inputXform  := fun ty => FDivSqrtInput (ty := ty) ($$false);\n                  outputXform := fun ty => FDivSqrtOutput (ty := ty);\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrs2 := true|><|hasFrd := true|>\n                |};\n                {|\n                  instName   := append \"fsqrt\" fpu_suffix;\n                  xlens      := xlens_all;\n                  extensions := fpu_exts;\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal fmtField fpu_format_field;\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal rs2Field      ('b\"00000\");\n                         fieldVal rs3Field      ('b\"01011\")\n                       ];\n                  inputXform  := fun ty => FDivSqrtInput (ty := ty) ($$true);\n                  outputXform := fun ty => FDivSqrtOutput (ty := 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/FDivSqrt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.19001749898465178}}
{"text": "Require Import HoareDef MutHeader MutF0 MutF1 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics ProofMode.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\nSection SIMMODSEM.\n\n  Context `{\u03a3: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: _ -> W -> Prop :=\n    mk_wf (fun (_: unit) _ _ => (True: iProp)%I).\n\n  Ltac check_o :=\n    match goal with\n    | [ |- (gpaco8 _ _ _ _ _ _ _ ?o_src ?o_tgt _ _ _) ] =>\n      pose o_src; pose o_tgt\n    end.\n\n  Theorem correct: refines2 [MutF0.F] [MutF1.F].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); et.\n    { ss. }\n    2: { exists tt. econs; ss; rr; uipropall. }\n    econs; ss. init. harg. mDesAll.\n    des; clarify. unfold fF, ccallU. steps. astart 10.\n    force_r.\n    { eapply mut_max_intrange. auto. } steps.\n    destruct (dec (Z.of_nat x) 0%Z).\n    - destruct x; ss. astop. steps. force_l. eexists. steps.\n      hret _; ss.\n    - destruct x; [ss|]. rewrite Nat2Z.inj_succ. steps.\n      acatch. hcall _ _ with \"*\"; auto.\n      { iPureIntro.\n        replace (Z.succ (Z.of_nat x) - 1)%Z with (Z.of_nat x) by lia.\n        esplits; et. lia. }\n      { splits; ss; eauto with ord_step. }\n      i. mDesAll. des; clarify.\n      steps. astop. steps.\n      force_l. eexists. steps.\n      hret _; ss. iPureIntro. esplits; ss.\n      f_equal. f_equal. lia.\n      Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/mutsum/MutF01proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.19001749898465178}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import AbstractMachine.Spec.\nRequire Import Locks.Spec.\nRequire Import MmioSPTWalk.Layer.\nRequire Import MmioSPTWalk.Spec.\nRequire Import RData.\nRequire Import Constants.\nRequire Import HypsecCommLib.\n\nLocal Open Scope Z_scope.\n\nSection MmioSPTOpsSpec.\n\n  Definition init_spt_spec (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    rely is_smmu index; rely is_smmu_cfg cbndx;\n    if halt adt then Some adt else\n    let id := SPT_ID in\n    let cpu := curid adt in\n    match id @ (lock adt) with\n    | LockFalse =>\n      let l := id @ (log adt) in\n      let orac := id @ (oracle adt) in\n      let l0 := orac cpu l in\n      let spt0 := spts (shared adt) in\n      let spt := CalSPT spt0 (orac cpu l) in\n      let l' := TEVENT cpu (TSHARED (OPULL id)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: ((orac cpu l) ++ l) in\n      let ttbr := SMMU_TTBR index cbndx in\n      let spt' := spt {spt_pt: (spt_pt spt) # ttbr == (ZMap.init (0, 0))}\n                      {spt_pgd_t: (spt_pgd_t spt) # ttbr == (ZMap.init false)}\n                      {spt_pmd_t: (spt_pmd_t spt) # ttbr == (ZMap.init (ZMap.init false))} in\n\n      let l'' := (TEVENT cpu (TTICKET REL_LOCK)) :: (TEVENT cpu (TSHARED (OSPT spt'))) :: l' in\n      let adt' := adt {tstate: 1} {shared: (shared adt) {spts: spt'}} {log: (log adt) # id == l''} {lock: (lock adt) # id == LockFalse} in\n      match H_CalLock l'' with\n      | Some _ => Some adt'\n      | _ => None\n      end\n    | _ => None\n    end.\n\n  Definition walk_spt_spec (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match addr with\n    | VZ64 addr =>\n      rely is_smmu index; rely is_smmu_cfg cbndx; rely is_smmu_addr addr;\n      if halt adt then Some (adt, (VZ64 0)) else\n      let id := SPT_ID in\n      let cpu := curid adt in\n      match id @ (lock adt) with\n      | LockFalse =>\n        let l := id @ (log adt) in\n        let orac := id @ (oracle adt) in\n        let l0 := orac cpu l in\n        let spt0 := spts (shared adt) in\n        let spt := CalSPT spt0 (orac cpu l) in\n        let l' := TEVENT cpu (TSHARED (OPULL id)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: ((orac cpu l) ++ l) in\n        let ttbr := SMMU_TTBR index cbndx in\n        let pt := ttbr @ (spt_pt spt) in\n        let gfn := addr / PAGE_SIZE in\n        match ZMap.get gfn pt with\n        | (pfn, pte) =>\n          rely is_int64 pte;\n          let l'' := (TEVENT cpu (TTICKET REL_LOCK)) :: (TEVENT cpu (TSHARED (OSPT spt))) :: l' in\n          let adt' := adt {tstate: 1} {shared: (shared adt) {spts: spt}} {log: (log adt) # id == l''} {lock: (lock adt) # id == LockFalse} in\n          match H_CalLock l'' with\n          | Some _ => Some (adt', (VZ64 pte))\n          | _ => None\n          end\n        end\n      | _ => None\n      end\n    end.\n\n  Definition map_spt_spec (cbndx: Z) (index: Z) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match addr, pte with\n    | VZ64 addr, VZ64 pte =>\n      rely is_smmu index; rely is_smmu_cfg cbndx; rely is_smmu_addr addr; rely is_int64 pte;\n      if halt adt then Some adt else\n      let id := SPT_ID in\n      let cpu := curid adt in\n      match id @ (lock adt) with\n      | LockFalse =>\n        let l := id @ (log adt) in\n        let orac := id @ (oracle adt) in\n        let l0 := orac cpu l in\n        let spt0 := spts (shared adt) in\n        let spt := CalSPT spt0 (orac cpu l) in\n        let l' := TEVENT cpu (TSHARED (OPULL id)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: ((orac cpu l) ++ l) in\n        match local_spt_map cbndx index addr pte spt with\n        | Some (halt', spt') =>\n          let l'' := (TEVENT cpu (TTICKET REL_LOCK)) :: (TEVENT cpu (TSHARED (OSPT spt'))) :: l' in\n          let adt' := adt {halt: halt'} {tstate: if halt' then 0 else 1}\n                          {shared: (shared adt) {spts: spt'}}\n                          {log: (log adt) # id == (if halt' then l' else l'')}\n                          {lock: (lock adt) # id == (if halt' then LockOwn true else LockFalse)} in\n          match H_CalLock l'' with\n          | Some _ => Some adt'\n          | _ => None\n          end\n        | _ => None\n        end\n      | _ => None\n      end\n    end.\n\n  Definition unmap_spt_spec (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match addr with\n    | VZ64 addr =>\n      rely is_smmu index; rely is_smmu_cfg cbndx; rely is_smmu_addr addr;\n      if halt adt then Some (adt, (VZ64 0)) else\n      let id := SPT_ID in\n      let cpu := curid adt in\n      match id @ (lock adt) with\n      | LockFalse =>\n        let l := id @ (log adt) in\n        let orac := id @ (oracle adt) in\n        let l0 := orac cpu l in\n        let spt0 := spts (shared adt) in\n        let spt := CalSPT spt0 (orac cpu l) in\n        let l' := TEVENT cpu (TSHARED (OPULL id)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: ((orac cpu l) ++ l) in\n        let ttbr := SMMU_TTBR index cbndx in\n        let pt := ttbr @ (spt_pt spt) in\n        let gfn := addr / PAGE_SIZE in\n        match ZMap.get gfn pt with\n        | (pfn, pte) =>\n          rely is_int64 pte;\n          match (if pte =? 0 then Some (false, spt) else local_spt_map cbndx index addr 0 spt) with\n          | Some (halt', spt') =>\n            let l'' := (TEVENT cpu (TTICKET REL_LOCK)) :: (TEVENT cpu (TSHARED (OSPT spt'))) :: l' in\n            let adt' := adt {halt: halt'} {tstate: if halt' then 0 else 1}\n                            {shared: (shared adt) {spts: spt'}}\n                            {log: (log adt) # id == (if halt' then l' else l'')}\n                            {lock: (lock adt) # id == (if halt' then LockOwn true else LockFalse)} in\n            match H_CalLock l'' with\n            | Some _ => Some (adt', (VZ64 (if halt' then 0 else pte)))\n            | _ => None\n            end\n          | _ => None\n          end\n        end\n      | _ => None\n      end\n    end.\n\nEnd MmioSPTOpsSpec.\n\nSection MmioSPTOpsSpecLow.\n\n  Context `{real_params: RealParams}.\n\n  Notation LDATA := RData.\n\n  Notation LDATAOps := (cdata (cdata_ops := MmioSPTWalk_ops) LDATA).\n\n  Definition init_spt_spec0 (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    when adt1 == acquire_lock_spt_spec adt;\n    when adt2 == clear_smmu_pt_spec cbndx index adt1;\n    release_lock_spt_spec adt2.\n\n  Definition walk_spt_spec0 (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    when adt1 == acquire_lock_spt_spec adt;\n    when' ret == walk_smmu_pt_spec cbndx index addr adt1;\n    rely is_int64 ret;\n    when adt2 == release_lock_spt_spec adt1;\n    when' res == check64_spec (VZ64 ret) adt2;\n    Some (adt2, VZ64 res).\n\n  Definition map_spt_spec0 (cbndx: Z) (index: Z) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    when adt1 == acquire_lock_spt_spec adt;\n    when adt2 == set_smmu_pt_spec cbndx index addr pte adt1;\n    release_lock_spt_spec adt2.\n\n  Definition unmap_spt_spec0 (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option (RData * Z64) :=\n    when adt1 == acquire_lock_spt_spec adt;\n    when' res == walk_smmu_pt_spec cbndx index addr adt1;\n    rely is_int64 res;\n    if res =? 0 then\n      when adt2 == release_lock_spt_spec adt1;\n      when' ret == check64_spec (VZ64 res) adt2;\n      Some (adt2, VZ64 ret)\n    else\n      when adt2 == set_smmu_pt_spec cbndx index addr (VZ64 0) adt1;\n      when adt3 == release_lock_spt_spec adt2;\n      when' ret == check64_spec (VZ64 res) adt3;\n      Some (adt3, VZ64 ret).\n\n  Inductive init_spt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | init_spt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx index\n      (Hinv: high_level_invariant labd)\n      (Hspec: init_spt_spec0 (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n      init_spt_spec_low_step s WB ((Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive walk_spt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_spt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx index addr res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_spt_spec0 (Int.unsigned cbndx) (Int.unsigned index) (VZ64 (Int64.unsigned addr)) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      walk_spt_spec_low_step s WB ((Vint cbndx)::(Vint index)::(Vlong addr)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Inductive map_spt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | map_spt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx index addr pte\n      (Hinv: high_level_invariant labd)\n      (Hspec: map_spt_spec0 (Int.unsigned cbndx) (Int.unsigned index) (VZ64 (Int64.unsigned addr)) (VZ64 (Int64.unsigned pte)) labd = Some labd'):\n      map_spt_spec_low_step s WB ((Vint cbndx)::(Vint index)::(Vlong addr)::(Vlong pte)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive unmap_spt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | unmap_spt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx index addr res\n      (Hinv: high_level_invariant labd)\n      (Hspec: unmap_spt_spec0 (Int.unsigned cbndx) (Int.unsigned index) (VZ64 (Int64.unsigned addr)) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      unmap_spt_spec_low_step s WB ((Vint cbndx)::(Vint index)::(Vlong addr)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModelX}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Definition init_spt_spec_low: compatsem LDATAOps :=\n      csem init_spt_spec_low_step (type_of_list_type (Tint32::Tint32::nil)) Tvoid.\n\n    Definition walk_spt_spec_low: compatsem LDATAOps :=\n      csem walk_spt_spec_low_step (type_of_list_type (Tint32::Tint32::Tint64::nil)) Tint64.\n\n    Definition map_spt_spec_low: compatsem LDATAOps :=\n      csem map_spt_spec_low_step (type_of_list_type (Tint32::Tint32::Tint64::Tint64::nil)) Tvoid.\n\n    Definition unmap_spt_spec_low: compatsem LDATAOps :=\n      csem unmap_spt_spec_low_step (type_of_list_type (Tint32::Tint32::Tint64::nil)) Tint64.\n\n  End WITHMEM.\n\nEnd MmioSPTOpsSpecLow.\n\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/sekvm/MmioSPTOps/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.18998546641629585}}
{"text": "Require Import List.\nRequire Import String.\nRequire Import ZArith.\n\nOpen Scope list_scope.\nOpen Scope string_scope.\nOpen Scope Z_scope.\n\nRequire Import StructTactics.\nRequire Import ImpSyntax.\nRequire Import ImpCommon.\nRequire Import ImpExprTransf.\nRequire Import ImpInterpNock.\nRequire Import ImpConstFold.\n\nRequire Import ImpEval.\nRequire Import ImpStep.\nRequire Import ImpSemanticsFacts.\nRequire Import ImpInterpProof.\nRequire Import ImpInterpNockProof.\n\nSection PROOF.\n\nVariable transf : expr -> expr.\n\nVariable transf_fwd :\n  forall s h e v,\n    eval_e s h e v ->\n    eval_e s h (transf e) v.\n\nVariable transf_bwd :\n  forall s h e v,\n    eval_e s h (transf e) v ->\n    eval_e s h e v \\/\n    (forall v', ~ eval_e s h e v').\n\nLemma transf_e_fwd :\n  forall s h e v,\n    eval_e s h e v ->\n    eval_e s h (transf_e transf e) v.\nProof.\n  induction e; simpl; intros;\n    apply transf_fwd; auto.\n  - on (eval_e _ _ _ _), invc.\n    find_copy_apply_hyp_hyp. ee.\n  - on (eval_e _ _ _ _), invc.\n    do 2 find_copy_apply_hyp_hyp. ee.\n  - on (eval_e _ _ _ _), invc.\n    + find_copy_apply_hyp_hyp. ee.\n    + find_copy_apply_hyp_hyp.\n      eapply eval_len_s; eauto.\n  - on (eval_e _ _ _ _), invc.\n    + find_copy_apply_hyp_hyp. ee.\n    + find_copy_apply_hyp_hyp.\n      eapply eval_idx_s; eauto.\nQed.\n\nLemma transf_e_bwd :\n  forall s h e v,\n    eval_e s h (transf_e transf e) v ->\n    eval_e s h e v \\/\n    (forall v', ~ eval_e s h e v').\nProof.\n  induction e; simpl; intros;\n    find_apply_hyp_hyp;\n    on (or _ _), invc; auto.\n  - on (eval_e _ _ _ _), inv.\n    find_apply_hyp_hyp.\n    on (or _ _), invc; auto.\n    + left; ee.\n    + right; unfold not in *; intros.\n      on (eval_e _ _ _ _), inv. firstorder.\n  - right; unfold not in *; intros.\n    on (eval_e _ _ _ _), inv.\n    eapply H0; eauto. ee.\n    eapply transf_e_fwd; eauto.\n  - on (eval_e _ _ _ _), invc.\n    repeat find_apply_hyp_hyp.\n    repeat on (or _ _), invc; auto.\n    + left; ee.\n    + right; unfold not in *; intros.\n      on (eval_e _ _ _ _), inv. firstorder.\n    + right; unfold not in *; intros.\n      on (eval_e _ _ _ _), inv. firstorder.\n    + right; unfold not in *; intros.\n      on (eval_e _ _ _ _), inv. firstorder.\n  - right; unfold not in *; intros.\n    on (eval_e _ _ _ _), inv.\n    eapply H0; eauto. ee.\n    + eapply transf_e_fwd; eauto.\n    + eapply transf_e_fwd; eauto.\n  (* len and idx are copy paste *)\n  - on (eval_e _ _ _ _), invc.\n    + find_apply_hyp_hyp.\n      on (or _ _), invc; auto.\n      * left; ee.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n    + find_apply_hyp_hyp.\n      on (or _ _), invc; auto.\n      * left; eapply eval_len_s; eauto.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n  - right; unfold not in *; intros.\n    on (eval_e _ _ _ _), inv.\n    + eapply H0; eauto. ee.\n      eapply transf_e_fwd; eauto.\n    + eapply H0; eauto.\n      eapply eval_len_s; eauto.\n      eapply transf_e_fwd; eauto.\n  - on (eval_e _ _ _ _), invc.\n    + repeat find_apply_hyp_hyp.\n      repeat on (or _ _), invc; auto.\n      * left; ee.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n    + repeat find_apply_hyp_hyp.\n      repeat on (or _ _), invc; auto.\n      * left; eapply eval_idx_s; eauto.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n      * right; unfold not in *; intros.\n        on (eval_e _ _ _ _), inv.\n        firstorder. firstorder.\n  - right; unfold not in *; intros.\n    on (eval_e _ _ _ _), inv.\n    + eapply H0; eauto. ee.\n      * eapply transf_e_fwd; eauto.\n      * eapply transf_e_fwd; eauto.\n    + eapply H0; eauto.\n      eapply eval_idx_s; eauto.\n      * eapply transf_e_fwd; eauto.\n      * eapply transf_e_fwd; eauto.\nQed.\n\nLemma transfs_e_fwd :\n  forall s h es vs,\n    evals_e s h es vs ->\n    evals_e s h (List.map transf es) vs.\nProof.\n  induction es; simpl; intros.\n  - auto.\n  - on (evals_e _ _ _ _), invc.\n    find_apply_hyp_hyp. repeat ee.\nQed.\n\nLemma transfs_e_bwd :\n  forall s h es vs,\n    evals_e s h (List.map transf es) vs ->\n    evals_e s h es vs \\/\n    (forall vs', ~ evals_e s h es vs').\nProof.\n  induction es; simpl; intros.\n  - auto.\n  - on (evals_e _ _ _ _), invc.\n    find_apply_hyp_hyp.\n    on (or _ _), invc; auto.\n    + find_apply_lem_hyp transf_bwd.\n      on (or _ _), invc; auto.\n      * left; ee.\n      * right; unfold not in *; intros.\n        on (evals_e _ _ _ _), invc.\n        eapply H0; eauto.\n    + right; unfold not in *; intros.\n      on (evals_e _ _ _ _), invc.\n      eapply H; eauto.\nQed.\n\nLemma locate_some_transf :\n  forall env x f,\n    locate env x = Some f ->\n    locate (transf_env transf env) x =\n      Some (transf_f transf f).\nProof.\n  induction env; simpl; intros.\n  - discriminate.\n  - repeat break_match; subst.\n    + congruence.\n    + simpl in *. find_inversion. congruence.\n    + simpl in *. find_inversion. congruence.\n    + auto.\nQed.\n\nLemma locate_none_transf :\n  forall env x,\n    locate env x = None ->\n    locate (transf_env transf env) x = None.\nProof.\n  induction env; simpl; intros.\n  - auto.\n  - repeat break_match; subst.\n    + congruence.\n    + simpl in *. find_inversion. congruence.\n    + simpl in *. find_inversion. congruence.\n    + auto.\nQed.\n\nLemma transf_locate_some :\n  forall env x f',\n    locate (transf_env transf env) x = Some f' ->\n    exists f,\n      locate env x = Some f /\\\n      transf_f transf f = f'.\nProof.\n  induction env; simpl; intros.\n  - discriminate.\n  - repeat break_match; subst.\n    + find_inversion; repeat ee.\n    + simpl in *; find_inversion; congruence.\n    + simpl in *; find_inversion; congruence.\n    + auto.\nQed.\n\nLemma transf_locate_none :\n  forall env x,\n    locate (transf_env transf env) x = None ->\n    locate env x = None.\nProof.\n  induction env; simpl; intros.\n  - auto.\n  - repeat break_match; subst.\n    + congruence.\n    + simpl in *. find_inversion. congruence.\n    + simpl in *. find_inversion. congruence.\n    + auto.\nQed.\n\nLemma transf_s_fwd :\n  forall env s1 h1 p1 s2 h2 p2,\n    step env\n      s1 h1 p1\n      s2 h2 p2 ->\n    step (transf_env transf env)\n      s1 h1 (transf_s transf p1)\n      s2 h2 (transf_s transf p2).\nProof.\n  induction 1; simpl; intros.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee.\n    + find_apply_lem_hyp locate_some_transf; auto.\n    + apply transfs_e_fwd; auto.\n  - repeat ee.\n    + find_apply_lem_hyp locate_none_transf; auto.\n    + eapply transfs_e_fwd; eauto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\n  - repeat ee; apply transf_e_fwd; auto.\nQed.\n\n(* Need to slightly strengthen IH for env locate,\n   and add lame equalities b/c prep_induction\n   does not work well with sections(?). *)\nLemma transf_s_bwd' :\n  forall env' s1 h1 p1' s2 h2 p2,\n    step env'\n      s1 h1 p1'\n      s2 h2 p2 ->\n  forall env p1,\n    env' = transf_env transf env ->\n    p1' = transf_s transf p1 ->\n    (exists p,\n      step env\n        s1 h1 p1\n        s2 h2 p\n      /\\ transf_s transf p = p2) \\/\n    (forall s2 h2 p,\n      p1 <> Snop /\\\n      ~ step env\n        s1 h1 p1\n        s2 h2 p).\nProof.\n  induction 1; intros; subst.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    repeat find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [|right].\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      firstorder.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    repeat find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [|right].\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      firstorder.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    find_apply_lem_hyp transf_locate_some.\n    break_exists; break_and.\n    repeat find_inversion.\n    repeat find_apply_lem_hyp transfs_e_bwd.\n    on (or _ _), invc; [left |right].\n    + destruct f0; simpl in *.\n      repeat find_inversion. repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    find_apply_lem_hyp transf_locate_none.\n    repeat find_inversion.\n    repeat find_apply_lem_hyp transfs_e_bwd.\n    on (or _ _), invc; [left |right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p0; simpl in *; try discriminate.\n    repeat find_inversion.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p0; simpl in *; try discriminate.\n    repeat find_inversion.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + exists Snop; repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * firstorder.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    destruct p1_1; simpl in *; try discriminate.\n    left; repeat ee.\n  - destruct p0; simpl in *; try discriminate.\n    repeat find_inversion.\n    edestruct IHstep; eauto.\n    + break_exists; break_and.\n      left; repeat ee.\n      subst; auto.\n    + right; unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), inv; simpl in *.\n      * inversion H.\n      * eapply H0; eauto.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    destruct p1; simpl in *; try discriminate.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc; [left | right].\n    + exists Snop; repeat ee.\n    + unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), invc.\n      * firstorder.\n      * inv H11.\n  - destruct p1; simpl in *; try discriminate.\n    repeat find_inversion.\n    edestruct IHstep; eauto.\n    + break_exists; break_and.\n      left; repeat ee.\n      subst; auto.\n    + right; unfold not in *; intros.\n      split; [congruence | intros].\n      on (step _ _ _ _ _ _ _), inv; simpl in *.\n      * inversion H.\n      * eapply H0; eauto.\nQed.\n\nLemma transf_s_bwd :\n  forall env s1 h1 p1 s2 h2 p2,\n    step (transf_env transf env)\n      s1 h1 (transf_s transf p1)\n      s2 h2 p2 ->\n    (exists p,\n      step env\n        s1 h1 p1\n        s2 h2 p\n      /\\ transf_s transf p = p2) \\/\n    (forall s2 h2 p,\n      p1 <> Snop /\\\n      ~ step env\n        s1 h1 p1\n        s2 h2 p).\nProof.\n  intros.\n  eapply transf_s_bwd'; eauto.\nQed.\n\nLemma transfs_s_fwd :\n  forall env s1 h1 p1 s2 h2 p2,\n    step_star env\n      s1 h1 p1\n      s2 h2 p2 ->\n    step_star (transf_env transf env)\n      s1 h1 (transf_s transf p1)\n      s2 h2 (transf_s transf p2).\nProof.\n  induction 1.\n  - repeat ee.\n  - find_apply_lem_hyp transf_s_fwd.\n    repeat ee.\nQed.\n\nInductive can_get_stuck :\n  env -> store -> heap -> stmt -> Prop :=\n| cgs_stuck :\n    forall env s1 h1 p1,\n      p1 <> Snop ->\n      (forall s2 h2 p2,\n        ~ step env\n            s1 h1 p1\n            s2 h2 p2) ->\n      can_get_stuck env s1 h1 p1\n| cgs_step :\n    forall env s1 h1 p1 s2 h2 p2,\n      step env\n        s1 h1 p1\n        s2 h2 p2 ->\n      can_get_stuck env s2 h2 p2 ->\n      can_get_stuck env s1 h1 p1.\n\nLemma transfs_s_bwd :\n  forall env' s1 h1 p1' s2 h2 p2,\n    step_star env'\n      s1 h1 p1'\n      s2 h2 p2 ->\n  forall env p1,\n    env' = transf_env transf env ->\n    p1' = transf_s transf p1 ->\n    (exists p,\n      step_star env\n        s1 h1 p1\n        s2 h2 p\n      /\\ transf_s transf p = p2) \\/\n    can_get_stuck env s1 h1 p1.\nProof.\n  induction 1; intros; subst.\n  - left; repeat ee.\n  - find_apply_lem_hyp transf_s_bwd.\n    on (or _ _), invc.\n    + break_exists; break_and.\n      edestruct IHstep_star; eauto.\n      * break_exists; break_and.\n        left; repeat ee.\n      * right. eapply cgs_step; eauto.\n    + right. ee.\n      * firstorder.\n      * firstorder.\nQed.\n\nLemma transf_p_fwd :\n  forall p v,\n    steps_p p v ->\n    steps_p (transf_p transf p) v.\nProof.\n  destruct p; intros.\n  on (steps_p _ _), invc. ee.\n  change Snop\n    with (transf_s transf Snop).\n  eapply transfs_s_fwd; eauto.\nQed.\n\nInductive can_get_stuck_prog : prog -> Prop :=\n| cgsp_body :\n    forall funcs main ret,\n      can_get_stuck funcs store_0 heap_0 main ->\n      can_get_stuck_prog (Prog funcs main ret)\n| cgsp_ret :\n    forall funcs main ret s2 h2,\n      step_star funcs\n        store_0 heap_0 main\n        s2 h2 Snop ->\n      (forall v,\n        ~ eval_e s2 h2 ret v) ->\n      can_get_stuck_prog (Prog funcs main ret).\n\nLemma transf_p_bwd :\n  forall p v,\n    steps_p (transf_p transf p) v ->\n    steps_p p v \\/ can_get_stuck_prog p.\nProof.\n  destruct p; intros.\n  on (steps_p _ _), invc.\n  find_eapply_lem_hyp transfs_s_bwd; eauto.\n  on (or _ _), invc.\n  - break_exists; break_and.\n    destruct p; simpl in *; try discriminate.\n    find_apply_lem_hyp transf_bwd.\n    on (or _ _), invc.\n    + left; ee.\n    + right. eapply cgsp_ret; eauto.\n  - right; ee.\nQed.\n\nEnd PROOF.\n", "meta": {"author": "palmskog", "repo": "street-fighting-proof-assistants", "sha": "f89660fab17a8c1a6c9cd9c14484ed8d72fb0088", "save_path": "github-repos/coq/palmskog-street-fighting-proof-assistants", "path": "github-repos/coq/palmskog-street-fighting-proof-assistants/street-fighting-proof-assistants-f89660fab17a8c1a6c9cd9c14484ed8d72fb0088/IMP/coq/ImpExprTransfProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.18998545920254892}}
{"text": "From iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import frac.\nFrom cap_machine Require Export rules_base.\n\nSection cap_lang_rules.\n  Context `{memG \u03a3, regG \u03a3}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03c3 : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Lemma wp_jmp_success E pc_p pc_b pc_e pc_a w r w' :\n    decodeInstrW w = Jmp r \u2192\n     isCorrectPC (WCap pc_p pc_b pc_e pc_a) \u2192\n\n     {{{ \u25b7 PC \u21a6\u1d63 WCap pc_p pc_b pc_e pc_a\n         \u2217 \u25b7 pc_a \u21a6\u2090 w\n         \u2217 \u25b7 r \u21a6\u1d63 w' }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC \u21a6\u1d63 updatePcPerm w'\n           \u2217 pc_a \u21a6\u2090 w\n           \u2217 r \u21a6\u1d63 w' }}}.\n  Proof.\n    iIntros (Hinstr Hvpc \u03d5) \"(>HPC & >Hpc_a & >Hr) H\u03c6\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (\u03c31 ns l1 l2 nt) \"H\u03c31 /=\". destruct \u03c31; simpl.\n    iDestruct \"H\u03c31\" as \"[Hr0 Hm]\".\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %?; auto.\n    iDestruct (@gen_heap_valid with \"Hr0 HPC\") as %?.\n    iDestruct (@gen_heap_valid with \"Hr0 Hr\") as %Hr_r0.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 \u03c32 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iIntros \"_\".\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n    unfold exec, exec_opt in Hstep. rewrite Hr_r0 /= in Hstep. simplify_pair_eq.\n\n    iMod (@gen_heap_update with \"Hr0 HPC\") as \"[Hr0 HPC]\". iFrame.\n    iApply \"H\u03c6\". by iFrame.\n  Qed.\n\n  Lemma wp_jmp_successPC E pc_p pc_b pc_e pc_a w :\n    decodeInstrW w = Jmp PC \u2192\n     isCorrectPC (WCap pc_p pc_b pc_e pc_a) \u2192\n\n     {{{ \u25b7 PC \u21a6\u1d63 WCap pc_p pc_b pc_e pc_a\n         \u2217 \u25b7 pc_a \u21a6\u2090 w }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC \u21a6\u1d63 updatePcPerm (WCap pc_p pc_b pc_e pc_a)\n           \u2217 pc_a \u21a6\u2090 w }}}.\n  Proof.\n    iIntros (Hinstr Hvpc \u03d5) \"(>HPC & >Hpc_a) H\u03c6\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (\u03c31 ns l1 l2 nt) \"H\u03c31 /=\". destruct \u03c31; cbn.\n    iDestruct \"H\u03c31\" as \"[Hr0 Hm]\".\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %?; auto.\n    iDestruct (@gen_heap_valid with \"Hr0 HPC\") as %Hr_PC.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 \u03c32 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iIntros \"_\".\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n    unfold exec, exec_opt in Hstep. rewrite Hr_PC /= in Hstep. simplify_pair_eq.\n\n    iMod (@gen_heap_update with \"Hr0 HPC\") as \"[Hr0 HPC]\". iFrame.\n    iApply \"H\u03c6\". by iFrame.\n  Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/rules/rules_Jmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.1899562421601335}}
{"text": "Require Import VST.floyd.base.\nRequire Import VST.floyd.assert_lemmas.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.nested_pred_lemmas.\nRequire Import VST.floyd.mapsto_memory_block.\n\nRequire Import RamifyCoq.msl_ext.abs_addr.\nRequire Import RamifyCoq.msl_ext.seplog.\nRequire Import RamifyCoq.msl_ext.log_normalize.\nRequire Import RamifyCoq.veric_ext.SeparationLogic.\n\nLocal Open Scope logic.\n\nModule Mapsto.\nSection Mapsto.\n\nDefinition empty_compspecs : compspecs.\nProof.\n  refine (mkcompspecs (PTree.empty _) _ _ _).\n  + constructor.\n    - rewrite PTree.gempty in H; inv H.\n    - rewrite PTree.gempty in H; inv H.\n    - rewrite PTree.gempty in H; inv H.\n    - rewrite PTree.gempty in H; inv H.\n  + hnf; intros.\n    rewrite PTree.gempty in H; inv H.\n  + hnf; intros.\n    rewrite PTree.gempty in H; inv H.\nDefined.\n\nDefinition adr_conflict (sh: share) : val * type -> val * type -> bool :=\n  fun a1 a2 =>\n  if (dec_share_nonunit sh)\n  then match a1, a2 with\n       | (p1, t1), (p2, t2) => \n         if (pointer_range_overlap_dec p1 (BV_sizeof t1) p2 (BV_sizeof t2)) then true else false\n       end\n  else false.\n\nInstance AA (sh: share) : AbsAddr (val * type) val.\n  apply (mkAbsAddr (val * type) val (adr_conflict sh)); intros; unfold adr_conflict in *; destruct p1, p2.\n  + destruct (pointer_range_overlap_dec v (BV_sizeof t) v0 (BV_sizeof t0)); subst;\n    destruct (pointer_range_overlap_dec v0 (BV_sizeof t0) v (BV_sizeof t)); subst; auto;\n    pose proof pointer_range_overlap_comm v (BV_sizeof t) v0 (BV_sizeof t0);\n    tauto.\n  + destruct (pointer_range_overlap_dec v (BV_sizeof t) v0 (BV_sizeof t0)); [| if_tac; auto].\n    destruct (pointer_range_overlap_isptr _ _ _ _ p).\n    destruct (zlt 0 (BV_sizeof t)).\n    - assert (pointer_range_overlap v (BV_sizeof t) v (BV_sizeof t))\n        by (apply pointer_range_overlap_refl; auto; omega).\n      destruct (pointer_range_overlap_dec v (BV_sizeof t) v (BV_sizeof t)); [congruence | tauto].\n    - apply pointer_range_overlap_non_zero in p.\n      omega.\nDefined.\n\nInstance MSL sh: MapstoSepLog (AA sh) (fun pt v => let (p, t) := pt in mapsto sh t p v).\nProof.\n  apply mkMapstoSepLog.\n  intros [p t].\n  apply exp_mapsto_precise.\nDefined.\n\nInstance sMSL (sh: share): StaticMapstoSepLog (AA sh) (fun pt v => let (p, t) := pt in mapsto sh t p v).\nProof.\n  apply mkStaticMapstoSepLog.\n  + intros [p t] v ?.\n    unfold addr_empty in H. simpl in H. unfold adr_conflict in H.\n    if_tac in H.\n    - destruct (pointer_range_overlap_dec p (BV_sizeof t) p (BV_sizeof t)); [congruence |].\n      unfold mapsto.\n      destruct (access_mode t) eqn:?H; try apply FF_left.\n      destruct (type_is_volatile t), p; try apply FF_left.\n      assert (pointer_range_overlap (Vptr b i) (BV_sizeof t) (Vptr b i) (BV_sizeof t)); [| tauto].\n      apply pointer_range_overlap_refl.\n      * simpl; tauto.\n      * eapply BV_sizeof_pos; eauto.\n      * eapply BV_sizeof_pos; eauto.\n    - apply mapsto_memory_block.mapsto_not_nonunit; auto.\n  + intros [p1 t1] [p2 t2] v1 v2 ?.\n    simpl in H; unfold adr_conflict in H.\n    if_tac in H; [| congruence].\n    apply mapsto_memory_block.mapsto_overlap with empty_compspecs; auto.\n    apply pointer_range_overlap_BV_sizeof.\n    destruct (pointer_range_overlap_dec p1 (BV_sizeof t1) p2 (BV_sizeof t2)); [auto | congruence].\n  + intros [p1 t1] [p2 t2] ?.\n    simpl in H; unfold adr_conflict in H.\n    if_tac in H.\n    1: {\n     destruct (pointer_range_overlap_dec p1 (BV_sizeof t1) p2 (BV_sizeof t2)); [congruence |].\n     destruct (pointer_range_overlap_dec p1 (@sizeof (PTree.empty _) t1) p2 (@sizeof (PTree.empty _) t2)).\n      - apply pointer_range_overlap_sizeof with (sh0 := sh) in p.\n        destruct p as [? | [? | ?]].\n        * tauto.\n        * eapply disj_derives; [exact H1 | apply derives_refl |].\n          pose proof log_normalize.FF_disj.\n          simpl in H2; apply H2.\n        * eapply disj_derives; [apply derives_refl | exact H1 |].\n          pose proof log_normalize.disj_FF.\n          simpl in H2; apply H2.\n      - apply @disj_mapsto_ with (PTree.empty _); auto.\n    }\n    1: {\n      unfold mapsto_.\n      simpl.\n      eapply disj_derives.\n      + apply exp_left; intro; apply mapsto_memory_block.mapsto_not_nonunit; auto.\n      + apply exp_left; intro; apply mapsto_memory_block.mapsto_not_nonunit; auto.\n      + apply (@emp_disj _ Nveric).\n    }\nDefined.\n\nEnd Mapsto.\nEnd Mapsto.\n\nModule MemoryBlock.\nSection MemoryBlock.\n\nDefinition adr_conflict (a1 a2 : val * Z) : bool :=\n  match a1, a2 with\n  | (p1, n1), (p2, n2) => \n    if (pointer_range_overlap_dec p1 n1 p2 n2) then true else false\n  end.\n\nInstance AA : AbsAddr (val * Z) unit.\n  apply (mkAbsAddr (val * Z) unit adr_conflict); intros; unfold adr_conflict in *; destruct p1, p2.\n  + destruct (pointer_range_overlap_dec v z v0 z0); subst;\n    destruct (pointer_range_overlap_dec v0 z0 v z); subst; auto;\n    pose proof pointer_range_overlap_comm v z v0 z0;\n    tauto.\n  + destruct (pointer_range_overlap_dec v z v0 z0); auto.\n    destruct (pointer_range_overlap_isptr _ _ _ _ p).\n    destruct (zlt 0 z).\n    - assert (pointer_range_overlap v z v z)\n        by (apply pointer_range_overlap_refl; auto; omega).\n      destruct (pointer_range_overlap_dec v z v z); [congruence | tauto].\n    - apply pointer_range_overlap_non_zero in p.\n      omega.\nDefined.\n\nInstance MSL sh: MapstoSepLog AA (fun pn v => let (p, n) := pn in memory_block sh n p).\nProof.\n  apply mkMapstoSepLog.\n  intros [p n].\n  rewrite exp_unit.\n  apply memory_block_precise.\nDefined.\n\nInstance sMSL (sh: share) (H_non_unit: sepalg.nonunit sh): StaticMapstoSepLog AA (fun pn v => let (p, n) := pn in memory_block sh n p).\nProof.\n  apply mkStaticMapstoSepLog.\n  + intros [p n] v ?.\n    unfold addr_empty in H; simpl in H.\n    destruct (pointer_range_overlap_dec p n p n); [congruence |].\n    rewrite memory_block_isptr.\n    normalize.\n    destruct p; try inversion Pp.\n    destruct (zlt 0 n).\n    - assert (pointer_range_overlap (Vptr b i) n (Vptr b i) n); [| tauto].\n      apply pointer_range_overlap_refl; simpl; try tauto; omega.\n    - change memory_block with mapsto_memory_block.memory_block.\n      unfold mapsto_memory_block.memory_block.\n      rewrite nat_of_Z_neg by omega.\n      simpl.\n      change (predicates_hered.andp\n        (predicates_hered.prop (Int.unsigned i + n <= Int.modulus))\n        predicates_sl.emp) with (!! (Int.unsigned i + n <= Int.modulus) && emp)%logic.\n      apply andp_left2; auto.\n  + intros [p1 n1] [p2 n2] _ _ ?.\n    apply mapsto_memory_block.memory_block_overlap; auto.\n    simpl in H.\n    destruct (pointer_range_overlap_dec p1 n1 p2 n2); [auto | congruence].\n  + intros [p1 n1] [p2 n2] ?.\n    simpl in H.\n    unfold mapsto_.\n    rewrite !exp_unit.\n    destruct (pointer_range_overlap_dec p1 n1 p2 n2); [congruence |].\n    destruct (pointer_range_overlap_dec p1 n1 p2 n2); [tauto |].\n    apply disj_memory_block; auto.\nDefined.\n\nEnd MemoryBlock.\nEnd MemoryBlock.\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/floyd_ext/MapstoSL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.1899562325062737}}
{"text": "(******************************************************************************)\n(* PipeCheck: Specifying and Verifying Microarchitectural                     *)\n(* Enforcement of Memory Consistency Models                                   *)\n(*                                                                            *)\n(* Copyright (c) 2014 Daniel Lustig, Princeton University                     *)\n(* All rights reserved.                                                       *)\n(*                                                                            *)\n(* This library is free software; you can redistribute it and/or              *)\n(* modify it under the terms of the GNU Lesser General Public                 *)\n(* License as published by the Free Software Foundation; either               *)\n(* version 2.1 of the License, or (at your option) any later version.         *)\n(*                                                                            *)\n(* This library is distributed in the hope that it will be useful,            *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of             *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU          *)\n(* Lesser General Public License for more details.                            *)\n(*                                                                            *)\n(* You should have received a copy of the GNU Lesser General Public           *)\n(* License along with this library; if not, write to the Free Software        *)\n(* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  *)\n(* USA                                                                        *)\n(******************************************************************************)\n\nRequire Import List.\nImport ListNotations.\nRequire Import Arith.\nRequire Import Ascii.\nRequire Import String.\nRequire Import wmm.\nRequire Import util2.\nRequire Import tree.\nRequire Import stages.\n\nOpen Scope string_scope.\n\n(** [geid] is a helper function that assigns to each [GlobalEvent] a unique\n  identifier in the global ordering graph. *)\nDefinition geid\n  (p : Pipeline)\n  (ge : GlobalEvent)\n  : nat :=\n  let (n, e) := ge in\n  e * (List.length (stages p)) + n.\n\n(** [gepid] applies [geid] to each value in a pair of [GlobalEvent]s. *)\nDefinition gepid\n  (p : Pipeline)\n  (gep : GlobalEvent * GlobalEvent * string)\n  : (nat * nat * string) :=\n  let (ge1, ge2) := fst gep in\n  (geid p ge1, geid p ge2, snd gep).\n\n(** [getid] applies [gepid] to each value in a [GraphTree] of [GlobalEvent]s. *)\nFixpoint getid\n  (p : Pipeline)\n  (t : GraphTree GlobalEvent)\n  : GraphTree nat :=\n  match t with\n  | GraphTreeOr     l => GraphTreeOr   _   (map (getid p) l)\n  | GraphTreeAnd    l => GraphTreeAnd  _   (map (getid p) l)\n  | GraphTreeLeaf n l => GraphTreeLeaf _ n (map (gepid p) l)\n  end.\n\n(** [ungeid'] is a helper function for [ungeid] that performs division\n  slowly. *)\nFixpoint ungeid'\n (p : Pipeline)\n (n s e : nat)\n : (location * program_order_index) :=\n  match (n, nat_compare s (List.length (stages p))) with\n  | (0   , Lt) => (s, e)\n  | (0   , Eq) => (0, S e)\n  | (S n', Lt) => ungeid' p n' (S s) e\n  | (S n', Eq) => ungeid' p n' 1 (S e)\n  | (_   , Gt) => (0, 0) (* ERROR *)\n  end.\n\n(** [ungeid] is the opposite of [geid]: it converts a global ordering vertex\n  identifier and returns the corresponding [location] and [Event].  It is used\n  to print human-readable information about the vertex. *)\nDefinition ungeid\n  (p : Pipeline)\n  (n : nat)\n  : location * program_order_index :=\n  ungeid' p n 0 0.\n\nDefinition GlobalEventString\n  (p : Pipeline)\n  (ge : GlobalEvent)\n  : string :=\n  let (n, e) := ge in\n  match (nth_error (stages p) n, n - List.length (stages p)) with\n  | (Some s, _) =>\n    append \"Event\"\n    (append (String (ascii_of_nat (nat_of_ascii \"0\" + e)) \"\")\n     (append \"at\"\n      (name s)))\n  | (None, 0) =>\n    fold_left append [\"CacheLine\"; stringOfNat e; \"Create\"] \"\"\n  | (None, 1) =>\n    fold_left append [\"CacheLine\"; stringOfNat e; \"Invalidate\"] \"\"\n  | _ => \"Unknown\"\n  end.\n\nFixpoint GraphString\n  (g : list (nat * nat * string))\n  : string :=\n  match g with\n  | h::t =>\n    let (s, d) := fst h in\n    fold_left append [stringOfNat s; \" --\"; (snd h); \"-> \"; stringOfNat d;\n      newline]\n      (GraphString t)\n  | [] => \"\"\n  end.\n\nFixpoint GlobalGraphString\n  (g : list (GlobalEvent * GlobalEvent * string))\n  : string :=\n  match g with\n  | h::t =>\n    let (s, d) := fst h in\n    fold_left append [\"(\"; stringOfNat (fst s); \", \"; stringOfNat (snd s);\n      \") --\"; (snd h); \"-> (\"; stringOfNat (fst d); \", \"; stringOfNat (snd d);\n      \")\"; newline]\n      (GlobalGraphString t)\n  | [] => \"\"\n  end.\n\nModule GraphStringExample.\n\nDefinition ExampleGraph := [(0, 1, \"a\"); (0, 2, \"b\")].\n\nExample e1 : GraphString ExampleGraph = \"0 --b-> 2\n0 --a-> 1\n\".\nProof.\nauto.\nQed.\n\nDefinition ExampleGlobalGraph := [((0, 0), (0, 1), \"a\"); ((0, 0), (1, 0), \"b\")].\n\nExample e2 : GlobalGraphString ExampleGlobalGraph = \"(0, 0) --b-> (1, 0)\n(0, 0) --a-> (0, 1)\n\".\nProof.\nauto.\nQed.\n\nEnd GraphStringExample.\n\n", "meta": {"author": "daniellustig", "repo": "pipecheck", "sha": "7b70b585be8c0a946869e991f459c57c29f73c9b", "save_path": "github-repos/coq/daniellustig-pipecheck", "path": "github-repos/coq/daniellustig-pipecheck/pipecheck-7b70b585be8c0a946869e991f459c57c29f73c9b/globalgraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1899529411989373}}
{"text": "From RecordUpdate Require Import RecordSet.\nFrom aneris.aneris_lang Require Import network resources.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\nFrom aneris.examples.reliable_communication.prelude Require Import ser_inj.\n\nDefinition Key := string.\n\n(** Arguments that user supplies to the interface *)\n\nClass DB_params := {\n  DB_addr :  socket_address;\n  DB_addrF :  socket_address;\n  DB_followers : gset socket_address;\n  DB_keys : gset Key;\n  DB_InvName : namespace;\n  DB_serialization : serialization;\n  DB_ser_inj : ser_is_injective DB_serialization;\n  DB_ser_inj_alt : ser_is_injective_alt DB_serialization;\n}.\n\nNotation DB_Serializable v := (Serializable DB_serialization v).\n\nRecord SerializableVal `{!DB_params} :=\n  SerVal {SV_val : val;\n          SV_ser : DB_Serializable SV_val }.\n\nCoercion SV_val : SerializableVal >-> val.\n\nExisting Instance SV_ser.\n\nArguments SerVal {_} _ {_}.\n\nDefinition socket_address_to_str (sa : socket_address) : string :=\n    match sa with SocketAddressInet ip p => ip +:+ (string_of_pos p) end.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/reliable_communication/lib/repdb/spec/db_params.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.18949864975607286}}
{"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: Refinement Proof for PShareIntro           *)\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 MPTNew layer and PShareIntro layer*)\nRequire Export ShareIntroGenDef.\nRequire Export ShareIntroGenFresh.\nRequire Export ShareIntroGenPassthrough.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/ShareIntroGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.18949864803510413}}
{"text": "(*========================================================================*)\n(*                                                                        *)\n(*                    CompcertTSO                                         *)\n(*                                                                        *)\n(*          Jaroslav Sevcik, University of Cambridge                      *)\n(*          Viktor Vafeiadis, University of Cambridge                     *)\n(*          Francesco Zappa Nardelli, INRIA Rocquencourt                  *)\n(*          Suresh Jagannathan, Purdue University                         *)\n(*          Peter Sewell, University of Cambridge                         *)\n(*                                                                        *)\n(*          (building on CompCert 1.5 and a 1.8 pre-release)              *)\n(*                                                                        *)\n(*  This document and the CompCertTSO sources are copyright 2005, 2006,   *)\n(*  2007, 2008, 2009, 2010, 2011 Institut National de Recherche en        *)\n(*  Informatique et en Automatique (INRIA), and Suresh Jagannathan,       *)\n(*  Jaroslav Sevcik, Peter Sewell and Viktor Vafeiadis.                   *)\n(*                                                                        *)\n(*  All rights reserved.  This file is distributed under the terms of     *)\n(*  the INRIA Non-Commercial License Agreement.                           *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*========================================================================*)\n\n(** Equivalence relations on memories. *)\n\nRequire Import Coqlib.\nRequire Import Specif.\nRequire Import Maps.\nRequire Import Ast.\nRequire Import Pointers.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Mem.\nRequire Import Libtactics.\nRequire Import Permutation.\n(* Require Import TSOmachine. *)\n\n(*============================================================================*)\n(** * Quotienting on range lists *)\n\nLemma range_lists_disjoint_ext:\n  forall {l1 l1' l2 l2'}\n    (EQ1: list_equiv l1 l1')\n    (EQ2: list_equiv l2 l2')\n    (DISJ: range_lists_disjoint l1 l2),\n    range_lists_disjoint l1' l2'.\nProof.\n  unfold range_lists_disjoint, range_not_in; intros.\n  by apply DISJ; [apply (proj2 (EQ1 _)) | apply (proj2 (EQ2 _))].\nQed.\n\n(*============================================================================*)\n(** * Load equality on memories *)\n\nLemma load_eq_preserved_by_store:\n  forall {c m mx p c' p' v' m' mx'}\n    (Leq: load_ptr c m p = load_ptr c mx p)\n    (ST: store_ptr c' m  p' v' = Some m')\n    (STx: store_ptr c' mx p' v' = Some mx'),\n  load_ptr c m' p = load_ptr c mx' p.\nProof.\n  intros.\n  pose proof (load_chunk_allocated_spec c m p) as LDAL.\n  pose proof (load_chunk_allocated_spec c mx p) as LDALX.\n  pose proof (load_chunk_allocated_spec c m' p) as LDAL'.\n  pose proof (load_chunk_allocated_spec c mx' p) as LDALX'.\n  destruct (load_ptr c m p) as [v|] _eqn : SMLD.\n    (* Load SUCCESS *)\n    destruct (range_eq_dec (range_of_chunk p' c') (range_of_chunk p c))\n      as [RCeq | RCneq].\n      (* Reading exactly the memory written by the unbuffered store *)\n      injection RCeq. \n      intro SCeqm.\n      assert (SCeq: size_chunk c' = size_chunk c).\n      destruct c; destruct c'; simpl in *; compute in SCeqm; done.\n      intro Peq; subst.\n      by rewrite (load_store_similar ST SCeq), (load_store_similar STx SCeq).\n    (* Reading from different memory; two cases: *)\n    destruct (ranges_disjoint_dec (range_of_chunk p' c') \n                                         (range_of_chunk p c)) \n        as [RDISJ | ROVER].\n      (* Ranges completely disjoint *)\n      rewrite <- (load_store_other ST RDISJ), SMLD.\n      by rewrite <- (load_store_other STx RDISJ).\n      (* Ranges overlap *)\n      apply (store_preserves_chunk_allocation ST _ _) in LDAL.\n      rewrite (load_store_overlap ST ROVER RCneq LDAL).\n      destruct (load_ptr c mx p) as [v''|] _eqn : SMLD'.\n      apply (store_preserves_chunk_allocation STx p c) in LDALX.\n      rewrite (load_store_overlap STx ROVER RCneq LDALX).\n      done.\n      by destruct (load_ptr c mx' p);\n        [apply (store_preserves_chunk_allocation STx _ _) in LDALX'|].\n    (* Load FAIL *)\n    apply sym_eq in Leq. rewrite Leq in LDALX.\n    destruct (load_ptr c m' p) as [cmv|] _eqn : E2;\n      destruct (load_ptr c mx' p) as [cmv'|] _eqn : E3;\n        try apply (store_preserves_chunk_allocation STx _ _) in LDALX';\n          try apply (store_preserves_chunk_allocation ST _ _) in LDAL';\n            try done.\nQed.\n\nLemma load_eq_preserved_by_alloc:\n  forall {c m mx p r' k' m' mx'}\n    (Leq: load_ptr c m p = load_ptr c mx p)\n    (AP: alloc_ptr r' k' m = Some m')\n    (APx: alloc_ptr r' k' mx = Some mx'),\n  load_ptr c m' p = load_ptr c mx' p.\nProof.\n  intros; destruct r' as [p' n'].\n  pose proof (load_chunk_allocated_spec c m p) as LDAL.\n  pose proof (load_chunk_allocated_spec c mx p) as LDALX.\n  pose proof (load_chunk_allocated_spec c m' p) as LDAL'.\n  pose proof (load_chunk_allocated_spec c mx' p) as LDALX'.\n  destruct (pointer_chunk_aligned_dec p c) as [CA | CNA].\n    2: destruct (load_ptr c m' p); destruct (load_ptr c mx' p);\n      try done; destruct LDAL'; destruct LDALX'; done.\n  destruct (range_inside_dec (range_of_chunk p c) (p', n')) as [RI | RNI].\n    (* loads inside the newly allocated region *)\n    rewrite (load_alloc_inside AP); try done;\n      rewrite (load_alloc_inside APx); done.\n  destruct (ranges_disjoint_dec (range_of_chunk p c) \n                                       (p', n')) as [DISJ | OVER].\n    (* loads outside *)\n    rewrite (load_alloc_other AP); try done;\n      rewrite (load_alloc_other APx); done.\n  (* loads overlap *)\n  destruct (alloc_someD AP) as [APA _].\n  destruct (alloc_someD APx) as [APA' _].\n  destruct (load_ptr c m' p).\n    destruct LDAL' as [[r [k [RI RA]]] _].\n    destruct (ranges_are_disjoint RA APA) as [[-> ->] | DISJ]; try done. \n    eby elim OVER; eapply disjoint_inside_disjoint.\n  destruct (load_ptr c mx' p); try done.\n  destruct LDALX' as [[r [k [RI RA]]] _].\n  destruct (ranges_are_disjoint RA APA') as [[-> ->] | DISJ]; try done. \n  eby elim OVER; eapply disjoint_inside_disjoint.\nQed.\n\nLemma load_eq_preserved_by_free_same_size:\n  forall {c m mx p p' n' k' m' mx'}\n    (Leq: load_ptr c m p = load_ptr c mx p)\n    (RA: range_allocated (p', n') k' m)\n    (FP: free_ptr p' k' m = Some m')\n    (RAx: range_allocated (p', n') k' mx)\n    (FPx: free_ptr p' k' mx = Some mx'),\n  load_ptr c m' p = load_ptr c mx' p.\nProof.\n  intros.\n  destruct (ranges_disjoint_dec (range_of_chunk p c) \n                                       (p', n')) as [DISJ | OVER].\n    by rewrite (load_free_other FP RA DISJ),\n               (load_free_other FPx RAx DISJ).\n  by rewrite (load_free_overlap FP RA OVER), \n             (load_free_overlap FPx RAx OVER).\nQed.\n\nLemma load_eq_preserved_by_free_diff_block:\n  forall {c m mx p p' k' m' mx'}\n    (Leq: load_ptr c m p = load_ptr c mx p)\n    (DB: MPtr.block p <> MPtr.block p')\n    (FP: free_ptr p' k' m = Some m')\n    (FPx: free_ptr p' k' mx = Some mx'),\n  load_ptr c m' p = load_ptr c mx' p.\nProof.\n  intros.\n  destruct (free_someD FP) as [n RA].\n  destruct (free_someD FPx) as [nx RAx].\n  rewrite (load_free_other FP RA); \n    [|by destruct p; destruct p'; simpl in *; left].\n  by rewrite (load_free_other FPx RAx);\n    [|by destruct p; destruct p'; simpl in *; left].\nQed.\n\n(*============================================================================*)\n(** * Equality on allocated ranges *)\n\n(** The allocation ranges are equal *)\nDefinition arange_eq (Cond: _ -> bool) m1 m2 :=\n    (forall r k (COND: Cond k), range_allocated r k m1 <-> range_allocated r k m2)\n /\\ (mrestr m1 = mrestr m2).\n\nLemma arange_eq_sub:\n  forall {m1 m2} C D,\n    arange_eq C m1 m2 ->\n    (forall k, D k = true -> C k) ->\n    arange_eq D m1 m2.\nProof. by destruct 1; split; auto. Qed.\n\nLemma arange_eq_refl:\n forall C m, arange_eq C m m. \nProof. done. Qed.\n\nLemma arange_eq_sym:\n  forall {C m1 m2}, arange_eq C m1 m2 -> arange_eq C m2 m1.\nProof. by destruct 1 as [A R]; repeat split; try done; by eapply A. Qed.  \n\nLemma arange_eq_trans:\n  forall C x y z,\n    arange_eq C x y ->\n    arange_eq C y z ->\n    arange_eq C x z.\nProof.\n  intros C x y z (X & ?) (Y & ?); split; [intros r k|congruence].\n  specialize (X r k); specialize (Y r k); tauto.\nQed.\n\nLemma arange_eq_store:\n  forall {m m' chunk p v} C,\n    store_ptr chunk m p v = Some m' ->\n    arange_eq C m' m.\nProof.\n  intros m m' chunk p v STO.\n  split; [split|].\n      eby apply <- @store_preserves_allocated_ranges.\n    eby apply -> @store_preserves_allocated_ranges. \n  eby eapply restr_of_store.\nQed.\n\nLemma range_in_allocated_arange:\n  forall {m1 m2 r}\n    (EQ: arange_eq (fun _ => true) m1 m2)\n    (RA: range_in_allocated r m1),\n    range_in_allocated r m2.\nProof.\n  intros; destruct RA as (? & ? & ? & ?).\n  eby do 2 eexists; split; [|eapply (proj1 EQ)].\nQed.\n\nLemma chunk_allocated_and_aligned_arange:\n  forall {m1 m2 chunk p}\n    (EQ: arange_eq (fun _ => true) m1 m2)\n    (CA: chunk_allocated_and_aligned p chunk m1),\n    chunk_allocated_and_aligned p chunk m2.\nProof.\n  intros; destruct CA as [? ?]; split; try done.\n  eby eapply range_in_allocated_arange.\nQed.\n\nLemma range_list_of_mem_arange:\n  forall {m1 m2}\n    (EQ: arange_eq (fun _ => true) m1 m2),\n  list_equiv (range_list_of_mem m1) (range_list_of_mem m2).\nProof.\n  intros; intro x.\n  eapply iff_trans; [apply range_list_of_mem_alloc|].\n  eapply iff_trans; [|apply iff_sym; apply range_list_of_mem_alloc].\n  split; intros [k RA]; exists k; pose proof (proj1 EQ x k (refl_equal _)); tauto.\nQed.\n\n\nLemma load_ptr_none_arange:\n  forall {m1 m2 chunk p}\n    (LD: load_ptr chunk m1 p = None)\n    (EQ: arange_eq (fun _ => true) m1 m2),\n    load_ptr chunk m2 p = None.\nProof.\n  intros.\n  assert (X1 := load_chunk_allocated_spec chunk m1 p).\n  assert (X2 := load_chunk_allocated_spec chunk m2 p).\n  do 2 destruct load_ptr; try done. \n  eby elim X1; eapply chunk_allocated_and_aligned_arange; try apply @arange_eq_sym.\nQed.\n\nLemma load_ptr_some_arange:\n  forall m1 m2 chunk p v1\n    (H1: load_ptr chunk m1 p = Some v1)\n    (EQ: arange_eq (fun _ => true) m1 m2),\n  exists v2, load_ptr chunk m2 p = Some v2.\nProof.\n  intros.\n  assert (X1 := load_chunk_allocated_spec chunk m1 p).\n  assert (X2 := load_chunk_allocated_spec chunk m2 p).\n  do 2 destruct load_ptr; vauto. \n  eby elim X2; eapply chunk_allocated_and_aligned_arange.\nQed.\n\nLemma store_ptr_none_arange:\n  forall {m1 m2 chunk p v} v'\n    (STO: store_ptr chunk m1 p v = None)\n    (EQ: arange_eq (fun _ => true) m1 m2),\n    store_ptr chunk m2 p v' = None.\nProof.\n  intros.\n  assert (X1 := store_chunk_allocated_spec chunk m1 p v).\n  assert (X2 := store_chunk_allocated_spec chunk m2 p v').\n  do 2 destruct store_ptr; try done. \n  eby elim X1; eapply chunk_allocated_and_aligned_arange; try apply @arange_eq_sym.\nQed.\n\nLemma store_ptr_some_arange1:\n  forall C m1 m2 chunk p v v' m1' m2'\n    (STO1: store_ptr chunk m1 p v = Some m1')\n    (STO2: store_ptr chunk m2 p v' = Some m2')\n    (REQ: arange_eq C m1 m2),\n    arange_eq C m1' m2'.\nProof. \n  intros; destruct REQ as [RA ?].\n  split.\n    intros.\n    pose proof (store_preserves_allocated_ranges STO1 r k).\n    pose proof (store_preserves_allocated_ranges STO2 r k).\n    specialize (RA r k).\n    tauto.\n  by rewrite (restr_of_store STO1), (restr_of_store STO2).\nQed.\n\nLemma store_ptr_some_arange:\n  forall m1 m2 chunk p v v' m1'\n    (H1: store_ptr chunk m1 p v = Some m1')\n    (EQ: arange_eq (fun _ => true) m1 m2),\n  exists m2', store_ptr chunk m2 p v' = Some m2' /\\ arange_eq (fun _ => true) m1' m2'.\nProof.\n  intros; destruct (store_ptr chunk m2 p v') as [m2'|] _eqn: H2;\n    [|by rewrite (store_ptr_none_arange _ H2 (arange_eq_sym EQ)) in H1].\n  exists m2'; split; try done.\n  eby eapply store_ptr_some_arange1.\nQed.\n\nLemma alloc_ptr_none_arange:\n  forall m1 m2 r k,\n    alloc_ptr r k m1 = None ->\n    arange_eq (fun _ => true) m1 m2 ->\n    alloc_ptr r k m2 = None.\nProof.\n  intros m1 m2 r k H EQ.\n  pose proof (alloc_cond_spec r k m1) as A1; destruct (alloc_ptr r k m1); try done.\n  pose proof (alloc_cond_spec r k m2) as A2; destruct (alloc_ptr r k m2); try done.\n  destruct A2 as [RA [? [? AL]]].\n  destruct A1 as [|[|[[? ?] [? [? RA']]]]]; try done.\n    destruct (fst r) as [b ofs]; simpl in *.\n    by rewrite (proj2 EQ) in *.\n  exploit AL; try edone.\n  eby eapply (proj1 ((proj1 EQ) _ _ (refl_equal _))).\nQed.\n\nLemma alloc_ptr_some_arange1:\n  forall C m1 m2 r k m1' m2',\n    alloc_ptr r k m1 = Some m1' ->\n    alloc_ptr r k m2 = Some m2' ->\n    arange_eq C m1 m2 ->\n    arange_eq C m1' m2'.\nProof.\n  intros C m1 m2 r k m1' m2' H1 H2 [RA ?]; split.\n    intros r0 k0.\n    pose proof (RA r0 k0) as EQ'.\n    pose proof (alloc_preserves_allocated_iff H1 r0 k0) as A1.\n    pose proof (alloc_preserves_allocated_iff H2 r0 k0) as A2.\n    tauto.\n  by rewrite (restr_of_alloc H1), (restr_of_alloc H2).\nQed.\n\nLemma alloc_ptr_some_arange:\n  forall m1 m2 r k m1',\n    alloc_ptr r k m1 = Some m1' ->\n    arange_eq (fun _ => true) m1 m2 ->\n    (exists m2', alloc_ptr r k m2 = Some m2' /\\ arange_eq (fun _ => true) m1' m2').\nProof.\n  intros m1 m2 r k m1' H1 EQ.\n  destruct (alloc_ptr r k m2) as [m2'|] _eqn: H2;\n    [|by rewrite (alloc_ptr_none_arange _ _ _ _ H2 (arange_eq_sym EQ)) in H1].\n  exists m2'; split; try done.\n  eby eapply alloc_ptr_some_arange1.\nQed.\n\nLemma free_ptr_none_arange:\n  forall C m1 m2 p k,\n    free_ptr p k m1 = None ->\n    arange_eq C m1 m2 ->\n    C k ->\n    free_ptr p k m2 = None.\nProof.\n  intros C m1 m2 p k H [EQ ?] CC.\n  pose proof (free_noneD H) as A1.\n  pose proof (free_cond_spec p k m2) as A2; destruct (free_ptr p k m2); try done.\n  destruct A2 as [n ?].\n  by elim (A1 n); apply (proj2 (EQ _ _ CC)).\nQed.\n\nLemma free_ptr_some_arange1:\n  forall C m1 m2 p k m1' m2',\n    free_ptr p k m1 = Some m1' ->\n    free_ptr p k m2 = Some m2' ->\n    arange_eq C m1 m2 ->\n    arange_eq C m1' m2'.\nProof.\n  intros C m1 m2 p k m1' m2' H1 H2 [RA ?].\n  split.\n    split; intro H3.\n      pose proof (free_preserves_allocated_back H1 _ _ H3) as X.\n      apply (proj1 (RA r k0 COND)) in X.\n      destruct (free_preserves_allocated H2 _ _ X) as [|[]]; clarify.\n      eby destruct r; eapply free_not_allocated in H1; elim H1.\n    pose proof (free_preserves_allocated_back H2 _ _ H3) as X.\n    apply (proj2 (RA r k0 COND)) in X.\n    destruct (free_preserves_allocated H1 _ _ X) as [|[]]; clarify.\n    eby destruct r; eapply free_not_allocated in H2; elim H2.\n  by rewrite (restr_of_free H1), (restr_of_free H2).\nQed.\n\nLemma free_ptr_some_arange:\n  forall C m1 m2 p k m1',\n    free_ptr p k m1 = Some m1' ->\n    arange_eq C m1 m2 ->\n    C k ->\n    (exists m2', free_ptr p k m2 = Some m2' /\\ arange_eq C m1' m2').\nProof.\n  intros C m1 m2 p k m1' H1 EQ CC.\n  destruct (free_ptr p k m2) as [m2'|] _eqn: H2;\n    [|by rewrite (free_ptr_none_arange _ _ _ _ _ H2 (arange_eq_sym EQ)) in H1].\n  exists m2'; split; try done.\n  eby eapply free_ptr_some_arange1.\nQed.\n\nLemma load_eq_preserved_by_free_arange:\n  forall {c m mx p p' k' m' mx'}\n    (Leq: load_ptr c m p = load_ptr c mx p)\n    (FP: free_ptr p' k' m = Some m')\n    (FPx: free_ptr p' k' mx = Some mx')\n    (Req: arange_eq (fun _ => true) m mx),\n  load_ptr c m' p = load_ptr c mx' p.\nProof.\n  intros.\n  pose proof (free_someD FP) as [n RA].\n  pose proof (proj1 (proj1 Req _ _ (refl_equal _)) RA).\n  eby eapply load_eq_preserved_by_free_same_size.  \nQed.\n\n(*============================================================================*)\n(** * Less definedness on memories *)\n\nDefinition opt_lessdef vo vo' := \n  match vo, vo' with\n    | Some v, Some v' => Val.lessdef v v'\n    | None, _ => True\n    | _, _ => False\n  end.\n\nDefinition mem_lessdef (m m': mem) :=\n  forall p c, opt_lessdef (load_ptr c m p) (load_ptr c m' p).\n\nDefinition mem_lessdef_in_range (m m': mem) (r: arange) :=\n  forall p c,\n    range_inside (range_of_chunk p c) r -> \n    opt_lessdef (load_ptr c m p) (load_ptr c m' p).\n\nLemma opt_lessdef_refl:\n  forall v, opt_lessdef v v.\nProof. by intros [[]|]; vauto. Qed.\n\nHint Resolve opt_lessdef_refl.\n\nLemma mem_lessdef_refl:\n  forall m, mem_lessdef m m.\nProof. by intros m p c; destruct load_ptr. Qed.\n\nHint Resolve mem_lessdef_refl.\n\nLemma opt_lessdef_sim_write:\n  forall tm sm tm' sm' p c v v' p' c'\n    (LDrel: opt_lessdef (load_ptr c' sm p') (load_ptr c' tm p'))\n    (tSTO: store_ptr c tm p v = Some tm')\n    (sSTO: store_ptr c sm p v' = Some sm')\n    (vLDEF: Val.lessdef v' v),\n    opt_lessdef (load_ptr c' sm' p') (load_ptr c' tm' p').\nProof.\n  intros.\n  pose proof (load_chunk_allocated_spec c' tm p') as Ct.\n  pose proof (load_chunk_allocated_spec c' tm' p') as Ct'.\n  pose proof (load_chunk_allocated_spec c' sm p') as Cs.\n  pose proof (load_chunk_allocated_spec c' sm' p') as Cs'.\n\n     destruct (load_ptr c' tm p') as [v1|] _eqn: tLD;\n     destruct (load_ptr c' sm p') as [v2|] _eqn: sLD; clarify;\n     destruct (load_ptr c' tm' p') as [] _eqn: tLD';\n     destruct (load_ptr c' sm' p') as [] _eqn: sLD'; clarify;\n     try apply (store_preserves_chunk_allocation tSTO _ _) in Ct;\n     try apply (store_preserves_chunk_allocation tSTO _ _) in Ct';\n     try apply (store_preserves_chunk_allocation sSTO _ _) in Cs; \n     try apply (store_preserves_chunk_allocation sSTO _ _) in Cs'; simpl in *; clarify.\n\n    destruct (range_eq_dec (range_of_chunk p c) (range_of_chunk p' c'))\n      as [RCeq | RCneq].\n      (* Reading exactly the memory written by the unbuffered store *)\n      injection RCeq. \n      intro SCeqm.\n      assert (SCeq: size_chunk c = size_chunk c').\n      destruct c; destruct c'; simpl in *; compute in SCeqm; done.\n      intro Peq; subst.\n      rewrite (load_store_similar tSTO SCeq), (load_store_similar sSTO SCeq) in *; vauto.\n      by destruct compatible_chunks; auto using Val.load_result_lessdef. \n\n    (* Reading from different memory; two cases: *)\n    destruct (ranges_disjoint_dec (range_of_chunk p c) \n                                         (range_of_chunk p' c')) \n        as [RDISJ | ROVER].\n      (* Ranges completely disjoint *)\n     by rewrite <- (load_store_other tSTO RDISJ), <- (load_store_other sSTO RDISJ) in *; clarify'. \n\n      (* Ranges overlap *)\n     by  rewrite (load_store_overlap tSTO ROVER RCneq Ct),\n              (load_store_overlap sSTO ROVER RCneq Cs) in *; vauto.\nQed.\n\nLemma opt_lessdef_sim_alloc:\n  forall tm sm tm' sm' p n k p' c'\n    (LREL: opt_lessdef (load_ptr c' sm p') (load_ptr c' tm p'))\n    (ACT: alloc_ptr (p, n) k tm = Some tm')\n    (ACS: alloc_ptr (p, n) k sm = Some sm'),\n    opt_lessdef (load_ptr c' sm' p') (load_ptr c' tm' p').\nProof.\n  intros.\n  destruct (ranges_disjoint_dec (range_of_chunk p' c') (p, n))\n    as [DISJ | OVER].\n    by rewrite (load_alloc_other ACT), (load_alloc_other ACS).\n  destruct (range_inside_dec (range_of_chunk p' c') (p, n))\n    as [RI | NRI].\n    destruct (pointer_chunk_aligned_dec p' c') as [ALG | NALG].\n      by rewrite (load_alloc_inside ACT), (load_alloc_inside ACS); vauto.\n    assert (LDT := load_chunk_allocated_spec c' tm' p'). \n    assert (LDS := load_chunk_allocated_spec c' sm' p'). \n    destruct (load_ptr c' tm' p'); [by case NALG; destruct LDT|].\n    by destruct (load_ptr c' sm' p'); [by case NALG; destruct LDS|].\n  by rewrite (load_alloc_overlap ACT), (load_alloc_overlap ACS).\nQed.\n\nLemma opt_lessdef_sim_free_same_size:\n  forall tm sm tm' sm' p k n p' c'\n    (LREL: opt_lessdef (load_ptr c' sm p') (load_ptr c' tm p'))\n    (Ft: free_ptr p k tm = Some tm')\n    (Fs: free_ptr p k sm = Some sm')\n    (RAt: range_allocated (p, n) k tm)\n    (RAs: range_allocated (p, n) k sm),\n    opt_lessdef (load_ptr c' sm' p') (load_ptr c' tm' p').\nProof.\n  intros.\n  destruct (ranges_disjoint_dec (range_of_chunk p' c') (p, n))\n    as [DISJ | OVER].\n    by rewrite (load_free_other Ft RAt DISJ);\n       rewrite (load_free_other Fs RAs DISJ).\n  by rewrite (load_free_overlap Ft RAt OVER);\n     rewrite (load_free_overlap Fs RAs OVER).\nQed.\n\nLemma mem_lessdef_sim_write:\n  forall tm sm tm' sm' c p v v' \n    (LREL: mem_lessdef sm tm)\n    (tSTO: store_ptr c tm p v = Some tm')\n    (sSTO: store_ptr c sm p v' = Some sm')\n    (vLDEF: Val.lessdef v' v),\n    mem_lessdef sm' tm'.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  eby eapply opt_lessdef_sim_write.\nQed.\n\nLemma mem_lessdef_sim_alloc:\n  forall tm sm tm' sm' p n k\n    (LREL: mem_lessdef sm tm)\n    (ACT: alloc_ptr (p, n) k tm = Some tm')\n    (ACS: alloc_ptr (p, n) k sm = Some sm'),\n    mem_lessdef sm' tm'.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  eby eapply opt_lessdef_sim_alloc.\nQed.\n\nLemma mem_lessdef_sim_free_same_size:\n  forall tm sm tm' sm' p n k\n    (LREL: mem_lessdef sm tm)\n    (Ft: free_ptr p k tm = Some tm')\n    (Fs: free_ptr p k sm = Some sm')\n    (RAt: range_allocated (p, n) k tm)\n    (RAs: range_allocated (p, n) k sm),\n    mem_lessdef sm' tm'.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  eby eapply opt_lessdef_sim_free_same_size.\nQed.\n\nLemma mem_lessdef_alloc_src:\n  forall tm sm sm' p n k\n    (LREL: mem_lessdef sm tm)\n    (RA: range_in_allocated (p, n) tm)\n    (ACS: alloc_ptr (p, n) k sm = Some sm'),\n    mem_lessdef sm' tm.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  destruct RA as (r' & k' & IN & RA).\n  destruct (ranges_disjoint_dec (range_of_chunk p' c') (p, n))\n    as [DISJ | OVER].\n    by rewrite (load_alloc_other ACS).\n  destruct (range_inside_dec (range_of_chunk p' c') (p, n))\n    as [RI | NRI].\n    destruct (pointer_chunk_aligned_dec p' c') as [ALG | NALG].\n      rewrite (load_alloc_inside ACS); try done.\n      assert (CA:= load_chunk_allocated_spec c' tm p').\n      destruct (load_ptr c' tm p'); vauto.\n      case CA; split; try done; exists r'; exists k'; split; try done. \n      eby eapply range_inside_trans.\n    assert (LDS := load_chunk_allocated_spec c' sm' p'). \n    by destruct (load_ptr c' sm' p'); [by case NALG; destruct LDS|destruct load_ptr].\n  by rewrite (load_alloc_overlap ACS); destruct load_ptr.\nQed.\n\nLemma mem_lessdef_free_src:\n  forall tm sm sm' p k\n    (LREL: mem_lessdef sm tm)\n    (F: free_ptr p k sm = Some sm'),\n    mem_lessdef sm' tm.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  pose proof (free_someD F) as [n RA].\n  destruct (ranges_disjoint_dec (range_of_chunk p' c') (p, n))\n    as [DISJ | OVER].\n    eby erewrite (load_free_other F).\n  erewrite (load_free_overlap F); try eassumption.\n  by destruct (load_ptr c' sm p').\nQed.\n\nLemma mem_lessdef_clear_src:\n  forall tm sm r\n    (LREL: mem_lessdef sm tm),\n    mem_lessdef (clear_range r sm) tm.\nProof.\n  intros; intros p' c'; specialize (LREL p' c').\n  destruct (load_ptr c' (clear_range r sm) p') as [] _eqn: LD.\n  destruct (load_clear_back LD) as (? & LD' & LDEF); rewrite LD' in *.\n    destruct (load_ptr c' tm p'); simpl in *; clarify.\n    by inv LREL; clarify; inv LDEF; clarify.\n  by eapply load_clear_none in LD; rewrite LD in *.\nQed.\n\n(*============================================================================*)\n(** * Partial load equality *)\n\nDefinition mem_agrees_on (m m' : mem) (rs : list arange) : Prop :=\n  forall r p c,\n    In r rs ->\n    range_inside (range_of_chunk p c) r ->\n    load_ptr c m p = load_ptr c m' p.\n\nLemma mem_agrees_on_sym:\n  forall {m m' rs} (H: mem_agrees_on m m' rs),\n  mem_agrees_on m' m rs.\nProof.\n  eby unfold mem_agrees_on; intros; symmetry; eapply H.\nQed.\n\nLemma mem_agrees_on_trans:\n  forall {x y z rs}\n    (X: mem_agrees_on x y rs)\n    (Y: mem_agrees_on y z rs),\n  mem_agrees_on x z rs.\nProof.\n  intros; intros r p c IN RI; \n  specialize (X _ _ _ IN RI);\n  specialize (Y _ _ _ IN RI); congruence.\nQed.\n\nLemma mem_agrees_on_app:\n  forall {m m' s1 s2},\n    mem_agrees_on m m' (s1 ++ s2) <->\n    mem_agrees_on m m' s1 /\\ mem_agrees_on m m' s2.\nProof.\n  split; [by intros MA; split; intros r p c IN; apply MA; auto using in_or_app|].\n  intros [MA1 MA2]; intros r p c IN. apply -> in_app in IN; destruct IN;\n    [by apply MA1 | by apply MA2].\nQed.\n\nLemma mem_agrees_on_perm:\n  forall {m m' l l'}\n    (P: Permutation l l')\n    (MA: mem_agrees_on m m' l),\n    mem_agrees_on m m' l'.\nProof.\n  intros; intros r p c IN; apply MA.\n  eby eapply Permutation_in; try apply Permutation_sym.\nQed.\n\nLemma mem_agrees_on_list_equiv:\n  forall {m m' l l'}\n    (EQ: list_equiv l l')\n    (MA: mem_agrees_on m m' l),\n    mem_agrees_on m m' l'.\nProof.\n  by intros; intros r p c IN; eapply MA, EQ.\nQed.\n\nLemma mem_agrees_on_preserved_by_store:\n  forall {m mx l c p v m' mx'}\n    (EQ: mem_agrees_on m mx l)\n    (ST: store_ptr c m p v = Some m')\n    (STx: store_ptr c mx p v = Some mx'),\n  mem_agrees_on m' mx' l.\nProof.\n  intros; intros r p' c' IN P; specialize (EQ r p' c' IN P).\n  eby eapply load_eq_preserved_by_store.\nQed.\n\nLemma mem_agrees_on_preserved_by_alloc:\n  forall {m mx l r k m' mx'}\n    (EQ: mem_agrees_on m mx l)\n    (A: alloc_ptr r k m = Some m')\n    (Ax: alloc_ptr r k mx = Some mx'),\n  mem_agrees_on m' mx' l.\nProof.\n  intros; intros r' p' c' IN P; specialize (EQ r' p' c' IN P).\n  eby eapply load_eq_preserved_by_alloc.\nQed.\n\nLemma mem_agrees_on_preserved_by_free_same_size:\n  forall {m mx l p n k m' mx'}\n    (EQ: mem_agrees_on m mx l)\n    (RA: range_allocated (p, n) k m)\n    (F: free_ptr p k m = Some m')\n    (RAx: range_allocated (p, n) k mx)\n    (Fx: free_ptr p k mx = Some mx'),\n  mem_agrees_on m' mx' l.\nProof.\n  intros; intros r' p' c' IN P; specialize (EQ r' p' c' IN P).\n  eby eapply load_eq_preserved_by_free_same_size.\nQed.\n\nLemma mem_agrees_on_preserved_by_free_arange:\n  forall {m mx l p k m' mx'}\n    (EQ: mem_agrees_on m mx l)\n    (REQ: arange_eq (fun _ => true) m mx)\n    (F: free_ptr p k m = Some m')\n    (Fx: free_ptr p k mx = Some mx'),\n  mem_agrees_on m' mx' l.\nProof.\n  intros; intros r' p' c' IN P; specialize (EQ r' p' c' IN P).\n  eby eapply load_eq_preserved_by_free_arange.\nQed.\n\n(*============================================================================*)\n(** * Extensional equality on memories *)\n\nDefinition mem_eq m1 m2:=\n   (forall chunk p, load_ptr chunk m1 p = load_ptr chunk m2 p)\n/\\ (forall r k, range_allocated r k m1 <-> range_allocated r k m2)\n/\\ (mrestr m1 = mrestr m2).\n\nLemma in_block1:\n  forall lbnd hbnd l h k ba,\n  alloclist_hbound lbnd (mkmobj l h k :: ba) = Some hbnd -> 0 < lbnd -> hbnd <= Int.modulus ->\n  valid_access Mint8unsigned (l mod Int.modulus) (mkmobj l h k :: ba).\nProof.\n  intros.\n  constructor 1 with (k:=k); [|by apply Zone_divide].\n  exists l; exists h.\n  split; [by left|].\n  exploit (@alloclist_hbound_impl_l_lt_h); [eassumption|by left|intro].  \n  rewrite Zmod_small; simpl; omega.\nQed.\n\nLemma alloclist1:\n  forall lbnd hbnd l h k a,\n  alloclist_hbound lbnd (mkmobj l h k :: a) = Some hbnd ->\n  lbnd <= l /\\ l < h /\\ h <= hbnd /\\ (align_size (h - l) | l).\nProof.\n  intros lbnd hbnd l h k a H.\n  by destruct (alloclist_hbound_impl_l_lt_h H (in_eq _ _)) as (? & ? & ? & ?).\nQed.\n\nLemma range_allocated_al_cons:\n  forall l h k l' h' k' ba',\n  range_allocated_al l h k (mkmobj l' h' k' :: ba') ->\n  l = l' /\\ h = h' /\\ k = k' \\/ range_allocated_al l h k ba'.\nProof.\n  unfold range_allocated_al.\n  by inversion 1; clarify; [left|right].\nQed.\n\n\nLemma valid_access_bounded:\n  forall c ofs al lbnd hbnd,\n   alloclist_hbound lbnd al = Some hbnd ->\n   valid_access c ofs al ->\n   lbnd <= ofs < hbnd.\nProof.\n  intros until 0; intros H [k [l [h [RA ?]]] AL].\n  eapply @alloclist_hbound_impl_l_lt_h in H; try edone.\n  destruct c; simpl in *; omega.\nQed.\n\n\nLemma Zabs_nat_of_nat: forall n, Zabs_nat (Z_of_nat n) = n.\nProof.\n  by destruct n; simpl; auto using nat_of_P_o_P_of_succ_nat_eq_succ.\nQed.\n\nLemma contents_eq_ext:\n  forall bc bc' ba, \n    block_valid (mkblock bc ba) ->\n    block_valid (mkblock bc' ba) ->\n    (forall c ofs,\n      valid_access c ofs ba ->\n      Val.load_result c (getN (pred_size_chunk c) (ofs mod Int.modulus) bc)\n      = Val.load_result c (getN (pred_size_chunk c) (ofs mod Int.modulus) bc')) ->\n  bc = bc'.\nProof.\n  intros bc bc' ba (UU & OK & hbnd & B & M) (UU' & OK' & hbnd' & B' & M') LD.\n  apply ZTree.ext; intros ofs.\n  destruct (ZTree.get ofs bc) as [[]|] _eqn: G.\n\n  Case \"Datum\".\n    pose proof (proj1 (proj2 OK _ _ _ G)) as [c [SZ [VOK ACCOK]]].\n    generalize (LD c ofs ACCOK).\n    assert (ofsRNG: 0 <= ofs < Int.modulus) \n      by (pose proof (valid_access_bounded _ _ _ _ _ B ACCOK); omega).\n    rewrite Zmod_small; try done.\n    destruct ACCOK as [k ? ?]; simpl in *.\n\n    unfold getN. \n    rewrite G, SZ, dec_eq_true, value_chunk_ok1; try done.\n    destruct (ZTree.get ofs bc') as [[]|] _eqn: G'; try done; try destruct eq_nat_dec;\n    try rewrite load_result_undef; intro X; clarify; try by revert VOK; clear; destruct c.\n\n    pose proof (proj1 (proj2 OK' _ _ _ G')) as [c' [SZ' [VOK' ACCOK']]].\n    rewrite value_chunk_ok1; try done.\n    by revert VOK VOK' SZ'; clear; destruct c'; destruct c; destruct v0.\n\n  Case \"Cont\".\n    pose proof (proj1 OK _ _ G) as (l & v & Gm).\n    pose proof (proj1 (proj2 OK _ _ _ Gm)) as [c [SZ [VOK ACCOK]]].\n    generalize (LD _ _ ACCOK).\n    assert (ofsRNG: 0 <= ofs - Z_of_nat n < Int.modulus) \n      by (pose proof (valid_access_bounded _ _ _ _ _ B ACCOK); omega).\n    rewrite Zmod_small; try done.\n    destruct ACCOK as [k ? ?]; simpl in *.\n    unfold getN. \n    rewrite Gm, SZ, dec_eq_true, value_chunk_ok1; try done.\n    destruct (ZTree.get (ofs - Z_of_nat n) bc') as [[]|] _eqn: G'; try done; try destruct eq_nat_dec;\n    try rewrite load_result_undef; intro X; clarify; try by revert VOK; clear; destruct c.\n    destruct n.\n      by simpl in *; rewrite Zminus_0_r in *; rewrite G in Gm.\n\n    pose proof (proj1 (proj2 OK' _ _ _ G')) as [c' [SZ' [VOK' ACCOK']]].\n    exploit (check_cont_inside _ _ _ _ ofs (proj2 (proj2 OK' _ _ _ G'))); \n      unfold contents; rewrite inj_S.\n    omega.\n    intros ->; f_equal; f_equal.\n    replace (ofs - (ofs - Zsucc (Z_of_nat n) + 1)) with (Z_of_nat n); [rewrite Zabs_nat_of_nat|]; omega.\n    \n  Case \"None\".\n    destruct (ZTree.get ofs bc') as [[]|] _eqn: G'; try done.\n\n    SCase \"Datum\".\n      pose proof (proj1 (proj2 OK' _ _ _ G')) as [c [SZ [VOK ACCOK]]].\n      generalize (LD c ofs ACCOK).\n      assert (ofsRNG: 0 <= ofs < Int.modulus) \n        by (pose proof (valid_access_bounded _ _ _ _ _ B ACCOK); omega).\n      rewrite Zmod_small; try done.\n      destruct ACCOK as [k ? ?]; simpl in *.\n      unfold getN. \n      rewrite G, G', SZ, dec_eq_true, load_result_undef, value_chunk_ok1; try done.\n      by revert VOK; clear; destruct c; destruct v.\n\n    SCase \"Cont\".\n      pose proof (proj1 OK' _ _ G') as (l & v & Gm').\n      pose proof (proj1 (proj2 OK' _ _ _ Gm')) as [c [SZ [VOK ACCOK]]].\n      generalize (LD _ _ ACCOK).\n      assert (ofsRNG: 0 <= ofs - Z_of_nat n < Int.modulus) \n        by (pose proof (valid_access_bounded _ _ _ _ _ B ACCOK); omega).\n      rewrite Zmod_small; try done.\n      destruct ACCOK as [k ? ?]; simpl in *.\n      unfold getN. \n      rewrite Gm', SZ, dec_eq_true. \n      destruct (ZTree.get (ofs - Z_of_nat n) bc) as [[]|] _eqn: Gm; try done; try destruct eq_nat_dec;\n      try rewrite load_result_undef; try (by revert VOK; destruct c; destruct v). \n      intro X; clarify. \n      destruct n.\n        by simpl in *; rewrite Zminus_0_r in *; rewrite G in Gm.\n\n      pose proof (proj1 (proj2 OK _ _ _ Gm)) as [c' [SZ' [VOK' ACCOK']]].\n      exploit (check_cont_inside _ _ _ _ ofs (proj2 (proj2 OK _ _ _ Gm))); \n        unfold contents; rewrite inj_S.\n      omega.\n      by rewrite G. \nQed.\n\nLemma range_allocated_implies_allocs_eq:\n  forall m m' b bc bc',\n  (forall (r : arange) (k : mobject_kind), range_allocated r k m  <-> range_allocated r k m') ->\n  ZTree.get b (mcont m) = Some bc ->\n  ZTree.get b (mcont m') = Some bc' ->\n  allocs bc = allocs bc'.\nProof.\n  intros [mc mr mv] [mc' mr' mv'] b [bc ba] [bc' ba'] RA EQ EQ'; simpl in *.\n  pose proof (proj2 (proj2 (proj1 (proj2 (proj2 mv _ _ EQ))))) as [hbnd [B M]].\n  pose proof (proj2 (proj2 (proj1 (proj2 (proj2 mv' _ _ EQ'))))) as [hbnd' [B' M']].\n  unfold range_allocated in *; simpl in *. \n\n    assert (Y: forall ofs s k,\n           range_allocated_al (Int.unsigned ofs)\n              (Int.unsigned ofs + Int.unsigned s) k ba <->\n            range_allocated_al (Int.unsigned ofs)\n              (Int.unsigned ofs + Int.unsigned s) k ba').\n      by intros; generalize (RA (Ptr b ofs, s) k); simpl; rewrite EQ, EQ'.\n    clear RA; revert Y.\n    simpl in *.\n    clear EQ' EQ.\n    revert B B' M'; cut (1 > 0); [|omega]; generalize 1 as lbnd; revert ba' hbnd'.\n\n    induction ba as [|[l h k] ba IH]; destruct ba' as [|[l' h' k'] ba']; try done; intros hbnd' lbnd POS B B' M' Y.\n    (*1*)  \n      exploit (proj2 (Y (Int.repr l') (Int.repr (h' - l')) k')); try done.\n      apply alloclist1 in B'.\n      left; simpl; f_equal; rewrite ?Zmod_small; omega.\n    (*2*)\n      exploit (proj1 (Y (Int.repr l) (Int.repr (h - l)) k)); try done. \n      apply alloclist1 in B.\n      left; simpl; f_equal; rewrite ?Zmod_small; omega.\n    (* Main case *)\n    assert (l = l' /\\ h = h' /\\ k = k') as [-> [-> ->]].\n      pose proof (alloclist1 _ _ _ _ _ _ B).\n      pose proof (alloclist1 _ _ _ _ _ _ B').\n      exploit (proj1 (Y (Int.repr l) (Int.repr (h - l)) k)); simpl; \n        rewrite ?Zmod_small, Zplus_minus; try omega; [by left|].\n      exploit (proj2 (Y (Int.repr l') (Int.repr (h' - l')) k')); simpl; \n        rewrite ?Zmod_small, Zplus_minus; try omega; [by left|].\n      intros X' X.\n      apply range_allocated_al_cons in X; destruct X as [X|X]; try done.\n      apply range_allocated_al_cons in X'; destruct X' as [[-> [-> ->]]|X']; try done.\n      simpl in B; destruct aligned_rng_dec; try done; destruct Z_le_dec; try done.\n      simpl in B'; destruct aligned_rng_dec; try done; destruct Z_le_dec; try done.\n      pose proof (alloclist_hbound_impl_l_lt_h B' X).\n      pose proof (alloclist_hbound_impl_l_lt_h B X').\n      omegaContradiction.\n    f_equal.\n    simpl in B, B'; destruct aligned_rng_dec; clarify; destruct Z_le_dec; clarify.\n    apply IH with (hbnd' := hbnd') (lbnd := h'); try done. \n      omega.\n    intros ofs s k.\n    split; intro IN.\n      destruct (proj1 (Y ofs s k) (or_intror _ IN)) as [|]; clarify.\n      pose proof (alloclist_hbound_impl_l_lt_h B IN).\n      omegaContradiction.\n    destruct (proj2 (Y ofs s k) (or_intror _ IN)) as [|]; clarify.\n    pose proof (alloclist_hbound_impl_l_lt_h B' IN).\n    omegaContradiction.\nQed.\n\nLemma mem_eq_ext:\n  forall m1 m2, mem_eq m1 m2 -> m1 = m2.\nProof.\n  intros [mc mr mv] [mc' mr' mv'] [LD [RA MR]]; simpl in *; subst mr'.\n  cut (mc = mc'); [by intro; subst mc'; rewrite (proof_irrelevance _ mv mv')|].\n  apply ZTree.ext; intros b. \n  destruct (ZTree.get b mc) as [[bc ba]|] _eqn: EQ; \n  destruct (ZTree.get b mc') as [[bc' ba']|] _eqn: EQ'; try done.\n\n  Case \"SomeSome\".\n  generalize (range_allocated_implies_allocs_eq _ _ _ _ _ RA EQ EQ'); simpl; intros <-.\n  f_equal; f_equal.\n  pose proof (proj1 (proj2 (proj2 mv _ _ EQ))) as V.  \n  pose proof (proj1 (proj2 (proj2 mv' _ _ EQ'))) as V'.\n  apply (contents_eq_ext _ _ _ V V'); intros c ofs VA.\n  generalize (LD c (Ptr b (Int.repr ofs))).\n  simpl; unfold load; simpl; rewrite EQ, EQ'; simpl.\n  rewrite Zmod_small, !in_block_true; try done.\n    by intro; clarify.\n  by destruct V as (? & ? & ? & B & ?);\n     pose proof (valid_access_bounded _ _ _ _ _ B VA); omega.\n\n  Case \"SomeNone\".\n  case mv; intros _ V.\n  pose proof (proj2 (V _ _ EQ)) as [[V1 [_ [hbnd [? ?]]]] M].\n  destruct ba as [|[l h k] ?].\n    assert (bc = ZTree.empty _); [|by elim M; subst].\n    apply ZTree.ext; intro x; rewrite ZTree.gempty; apply V1; simpl.\n    by intros k [? [? [RA' _]]]; inversion RA'.\n  generalize (LD Mint8unsigned (Ptr b (Int.repr l))); unfold load_ptr, load; \n  simpl; rewrite EQ, EQ'; simpl.\n  eby rewrite in_block_empty, in_block_true; [|eapply in_block1].\n\n  Case \"NoneSome\".\n  case mv'; intros _ V.\n  pose proof (proj2 (V _ _ EQ')) as [[V1 [_ [hbnd [? ?]]]] M].\n  destruct ba' as [|[l h k] ?].\n    assert (bc' = ZTree.empty _); [|by elim M; subst].\n    apply ZTree.ext; intro x; rewrite ZTree.gempty; apply V1; simpl.\n    by intros k [? [? [RA' _]]]; inversion RA'.\n  generalize (LD Mint8unsigned (Ptr b (Int.repr l))); unfold load_ptr, load; \n  simpl; rewrite EQ, EQ'; simpl.\n  eby rewrite in_block_empty, in_block_true; [|eapply in_block1].\nQed.\n", "meta": {"author": "shenghaoyuan", "repo": "CompCertTSO", "sha": "938a2ef6a398531cbd813453d7d0d20e2f4c62de", "save_path": "github-repos/coq/shenghaoyuan-CompCertTSO", "path": "github-repos/coq/shenghaoyuan-CompCertTSO/CompCertTSO-938a2ef6a398531cbd813453d7d0d20e2f4c62de/common/Memeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.18949864441711325}}
{"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.\nRequire map.Occ.\nRequire map.MapPermut.\nRequire map.MapInjection.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom qtmark : Type.\nParameter qtmark_WhyType : WhyType qtmark.\nExisting Instance qtmark_WhyType.\n\n(* Why3 assumption *)\nInductive array (a:Type) :=\n  | mk_array : Z -> (map.Map.map Z a) -> array a.\nAxiom array_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (array a).\nExisting Instance array_WhyType.\nImplicit Arguments mk_array [[a]].\n\n(* Why3 assumption *)\nDefinition elts {a:Type} {a_WT:WhyType a} (v:(array a)): (map.Map.map Z a) :=\n  match v with\n  | (mk_array x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition length {a:Type} {a_WT:WhyType a} (v:(array a)): Z :=\n  match v with\n  | (mk_array x x1) => x\n  end.\n\n(* Why3 assumption *)\nDefinition get {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z): a :=\n  (map.Map.get (elts a1) i).\n\n(* Why3 assumption *)\nDefinition set {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z) (v:a): (array\n  a) := (mk_array (length a1) (map.Map.set (elts a1) i v)).\n\n(* Why3 assumption *)\nDefinition make {a:Type} {a_WT:WhyType a} (n:Z) (v:a): (array a) :=\n  (mk_array n (map.Map.const v: (map.Map.map Z a))).\n\n(* Why3 assumption *)\nDefinition is_common_prefix (a:(array Z)) (x:Z) (y:Z) (l:Z): Prop :=\n  (0%Z <= l)%Z /\\ (((x + l)%Z <= (length a))%Z /\\\n  (((y + l)%Z <= (length a))%Z /\\ forall (i:Z), ((0%Z <= i)%Z /\\\n  (i < l)%Z) -> ((get a (x + i)%Z) = (get a (y + i)%Z)))).\n\nAxiom not_common_prefix_if_last_char_are_different : forall (a:(array Z))\n  (x:Z) (y:Z) (l:Z), ((0%Z <= l)%Z /\\ (((x + l)%Z < (length a))%Z /\\\n  (((y + l)%Z < (length a))%Z /\\ ~ ((get a (x + l)%Z) = (get a\n  (y + l)%Z))))) -> ~ (is_common_prefix a x y (l + 1%Z)%Z).\n\n(* Why3 assumption *)\nDefinition is_longest_common_prefix (a:(array Z)) (x:Z) (y:Z) (l:Z): Prop :=\n  (is_common_prefix a x y l) /\\ forall (m:Z), (l < m)%Z ->\n  ~ (is_common_prefix a x y m).\n\nAxiom longest_common_prefix_succ : forall (a:(array Z)) (x:Z) (y:Z) (l:Z),\n  ((is_common_prefix a x y l) /\\ ~ (is_common_prefix a x y (l + 1%Z)%Z)) ->\n  (is_longest_common_prefix a x y l).\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 *)\nDefinition lt (a:(array Z)) (x:Z) (y:Z): Prop := let n := (length a) in\n  (((0%Z <= x)%Z /\\ (x <= n)%Z) /\\ (((0%Z <= y)%Z /\\ (y <= n)%Z) /\\\n  exists l:Z, (is_common_prefix a x y l) /\\ (((y + l)%Z < n)%Z /\\\n  (((x + l)%Z = n) \\/ ((get a (x + l)%Z) < (get a (y + l)%Z))%Z)))).\n\n(* Why3 assumption *)\nDefinition range (a:(array Z)): Prop := (map.MapInjection.range (elts a)\n  (length a)).\n\n(* Why3 assumption *)\nDefinition map_eq_sub {a:Type} {a_WT:WhyType a} (a1:(map.Map.map Z a))\n  (a2:(map.Map.map Z a)) (l:Z) (u:Z): Prop := forall (i:Z), ((l <= i)%Z /\\\n  (i < u)%Z) -> ((map.Map.get a1 i) = (map.Map.get a2 i)).\n\n(* Why3 assumption *)\nDefinition array_eq_sub {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array\n  a)) (l:Z) (u:Z): Prop := ((length a1) = (length a2)) /\\ (((0%Z <= l)%Z /\\\n  (l <= (length a1))%Z) /\\ (((0%Z <= u)%Z /\\ (u <= (length a1))%Z) /\\\n  (map_eq_sub (elts a1) (elts a2) l u))).\n\n(* Why3 assumption *)\nDefinition array_eq {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array\n  a)): Prop := ((length a1) = (length a2)) /\\ (map_eq_sub (elts a1) (elts a2)\n  0%Z (length a1)).\n\n(* Why3 assumption *)\nDefinition exchange {a:Type} {a_WT:WhyType a} (a1:(map.Map.map Z a))\n  (a2:(map.Map.map Z a)) (l:Z) (u:Z) (i:Z) (j:Z): Prop := ((l <= i)%Z /\\\n  (i < u)%Z) /\\ (((l <= j)%Z /\\ (j < u)%Z) /\\ (((map.Map.get a1\n  i) = (map.Map.get a2 j)) /\\ (((map.Map.get a1 j) = (map.Map.get a2 i)) /\\\n  forall (k:Z), ((l <= k)%Z /\\ (k < u)%Z) -> ((~ (k = i)) -> ((~ (k = j)) ->\n  ((map.Map.get a1 k) = (map.Map.get a2 k))))))).\n\nAxiom exchange_set : forall {a:Type} {a_WT:WhyType a},\n  forall (a1:(map.Map.map Z a)) (l:Z) (u:Z) (i:Z) (j:Z), ((l <= i)%Z /\\\n  (i < u)%Z) -> (((l <= j)%Z /\\ (j < u)%Z) -> (exchange a1\n  (map.Map.set (map.Map.set a1 i (map.Map.get a1 j)) j (map.Map.get a1 i)) l\n  u i j)).\n\n(* Why3 assumption *)\nDefinition exchange1 {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array a))\n  (i:Z) (j:Z): Prop := ((length a1) = (length a2)) /\\ (exchange (elts a1)\n  (elts a2) 0%Z (length a1) i j).\n\n(* Why3 assumption *)\nDefinition permut {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array a))\n  (l:Z) (u:Z): Prop := ((length a1) = (length a2)) /\\ (((0%Z <= l)%Z /\\\n  (l <= (length a1))%Z) /\\ (((0%Z <= u)%Z /\\ (u <= (length a1))%Z) /\\\n  (map.MapPermut.permut (elts a1) (elts a2) l u))).\n\n(* Why3 assumption *)\nDefinition permut_sub {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array a))\n  (l:Z) (u:Z): Prop := (map_eq_sub (elts a1) (elts a2) 0%Z l) /\\ ((permut a1\n  a2 l u) /\\ (map_eq_sub (elts a1) (elts a2) u (length a1))).\n\n(* Why3 assumption *)\nDefinition permut_all {a:Type} {a_WT:WhyType a} (a1:(array a)) (a2:(array\n  a)): Prop := ((length a1) = (length a2)) /\\ (map.MapPermut.permut (elts a1)\n  (elts a2) 0%Z (length a1)).\n\nAxiom exchange_permut_sub : forall {a:Type} {a_WT:WhyType a},\n  forall (a1:(array a)) (a2:(array a)) (i:Z) (j:Z) (l:Z) (u:Z), (exchange1 a1\n  a2 i j) -> (((l <= i)%Z /\\ (i < u)%Z) -> (((l <= j)%Z /\\ (j < u)%Z) ->\n  ((0%Z <= l)%Z -> ((u <= (length a1))%Z -> (permut_sub a1 a2 l u))))).\n\nAxiom permut_sub_weakening : forall {a:Type} {a_WT:WhyType a},\n  forall (a1:(array a)) (a2:(array a)) (l1:Z) (u1:Z) (l2:Z) (u2:Z),\n  (permut_sub a1 a2 l1 u1) -> (((0%Z <= l2)%Z /\\ (l2 <= l1)%Z) ->\n  (((u1 <= u2)%Z /\\ (u2 <= (length a1))%Z) -> (permut_sub a1 a2 l2 u2))).\n\nAxiom exchange_permut_all : forall {a:Type} {a_WT:WhyType a},\n  forall (a1:(array a)) (a2:(array a)) (i:Z) (j:Z), (exchange1 a1 a2 i j) ->\n  (permut_all a1 a2).\n\n(* Why3 assumption *)\nDefinition le (a:(array Z)) (x:Z) (y:Z): Prop := (x = y) \\/ (lt a x y).\n\nAxiom lcp_same_index : forall (a:(array Z)) (x:Z), ((0%Z <= x)%Z /\\\n  (x <= (length a))%Z) -> (is_longest_common_prefix a x x\n  ((length a) - x)%Z).\n\nAxiom le_trans : forall (a:(array Z)) (x:Z) (y:Z) (z:Z), ((le a x y) /\\ (le a\n  y z)) -> (le a x z).\n\n(* Why3 assumption *)\nDefinition sorted_sub (a:(array Z)) (data:(map.Map.map Z Z)) (l:Z)\n  (u:Z): Prop := forall (i1:Z) (i2:Z), ((l <= i1)%Z /\\ ((i1 <= i2)%Z /\\\n  (i2 < u)%Z)) -> (le a (map.Map.get data i1) (map.Map.get data i2)).\n\n(* Why3 assumption *)\nDefinition sorted (a:(array Z)) (data:(array Z)): Prop := (sorted_sub a\n  (elts data) 0%Z (length data)).\n\n(* Why3 assumption *)\nDefinition permutation (m:(map.Map.map Z Z)) (u:Z): Prop :=\n  (map.MapInjection.range m u) /\\ (map.MapInjection.injective m u).\n\n(* Why3 assumption *)\nInductive suffixArray :=\n  | mk_suffixArray : (array Z) -> (array Z) -> suffixArray.\nAxiom suffixArray_WhyType : WhyType suffixArray.\nExisting Instance suffixArray_WhyType.\n\n(* Why3 assumption *)\nDefinition suffixes (v:suffixArray): (array Z) :=\n  match v with\n  | (mk_suffixArray x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition values (v:suffixArray): (array Z) :=\n  match v with\n  | (mk_suffixArray x x1) => x\n  end.\n\n(* Why3 goal *)\nTheorem permut_permutation : forall (a1:(array Z)) (a2:(array Z)),\n  ((permut_all a1 a2) /\\ (permutation (elts a1) (length a1))) -> (permutation\n  (elts a2) (length a2)).\n(* Why3 intros a1 a2 (h1,h2). *)\nintros (n, m1) (n2, m2) ((h1a, h1b), (h2a, h2b)).\nsimpl in *. subst n2.\nsplit.\nred; intros.\n(* range *)\ngeneralize (MapPermut.permut_exists _ _ _ _ _ h1b H).\nintros (j, (h1,h2)). rewrite <- h2. auto.\n(* injective *)\nrewrite MapInjection.injection_occ.\nintros v; rewrite <- h1b.\ngeneralize v; rewrite <- MapInjection.injection_occ.\nassumption.\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/verifythis_fm2012_LRS/verifythis_fm2012_lcp_SuffixArray_permut_permutation_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18945048798577616}}
{"text": "(*\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     AdversaryUniverse\n\n     ModelCheck.ProtocolFunctions\n.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations.\n\nFrom Frap Require 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 ShareSecretSymmetricEncProtocol.\n\n  (* User ids *)\n  Notation USR1 := 0.\n  Notation USR2 := 1.\n  \n  Section IW_Simple.\n    Import IdealWorld.\n\n    Notation perms_CH := 0.\n    Notation CH := (Single perms_CH).\n\n    Notation empty_chs := (#0 #+ (CH, [])).\n\n    Definition PERMS := $0 $+ (perms_CH, {| read := true; write := true |}).\n\n    Definition simple_users :=\n      [\n        (mkiUsr USR1 PERMS \n                (\n                  n <- Gen\n                  ; _ <- Send (Content n) CH\n                  ; @Return (Base Nat) n\n        ));\n        (mkiUsr USR2 PERMS\n                ( m <- @Recv Nat CH\n                ; @Return (Base Nat) (extractContent m)))\n        ].\n\n    Definition simple_univ_start :=\n      mkiU empty_chs simple_users.\n\n  End IW_Simple.\n\n  Section IW.\n    Import IdealWorld.\n\n    Notation pCH12 := 0.\n    Notation pCH21 := 1.\n    Notation CH12  := (# pCH12).\n    Notation CH21  := (# pCH21).\n\n    Notation empty_chs := (#0 #+ (CH12, []) #+ (CH21, [])).\n\n    Notation PERMS1 := ($0 $+ (pCH12, owner) $+ (pCH21, reader)).\n    Notation PERMS2 := ($0 $+ (pCH12, reader) $+ (pCH21, owner)).\n\n    Notation ideal_users :=\n      [\n        (mkiUsr USR1 PERMS1 \n                ( chid <- CreateChannel\n                  ; _ <- Send (sharePerm chid writer) CH12\n                  ; m <- @Recv Access (chid #& pCH21)\n                  ; n <- Gen\n                  ; _ <- Send (Content n) (getPerm m #& pCH12)\n                  ; @Return (Base Nat) n\n        )) ;\n      (mkiUsr USR2 PERMS2\n              ( m <- @Recv Access CH12\n                ; chid <- CreateChannel\n                ; _ <- Send (sharePerm chid owner) (getPerm m #& pCH21)\n                ; m <- @Recv Nat (chid #& pCH12)\n                ; @Return (Base Nat) (extractContent m)\n      ))\n      ].\n\n    Definition ideal_univ_start :=\n      mkiU empty_chs ideal_users.\n\n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    Notation KID1 := 0.\n    Notation KID2 := 1.\n\n    Notation KEYS := [ skey KID1 ; skey KID2 ].\n\n    Notation KEYS1 := ($0 $+ (KID1, true) $+ (KID2, false)).\n    Notation KEYS2 := ($0 $+ (KID1, false) $+ (KID2, true)).\n\n    Definition real_users :=\n      [\n        MkRUserSpec USR1 KEYS1\n                    ( kp <- GenerateKey AsymKey Encryption\n                      ; c1 <- Sign KID1 USR2 (sharePubKey kp)\n                      ; _  <- Send USR2 c1\n                      ; c2 <- @Recv Access (SignedEncrypted KID2 (fst kp) true)\n                      ; m  <- Decrypt c2\n                      ; n  <- Gen\n                      ; c3 <- SignEncrypt KID1 (getKey m) USR2 (message.Content n)\n                      ; _  <- Send USR2 c3\n                      ; @Return (Base Nat) n) ;\n\n      MkRUserSpec USR2 KEYS2\n                  ( c1 <- @Recv Access (Signed KID1 true)\n                    ; v  <- Verify KID1 c1\n                    ; kp <- GenerateKey SymKey Encryption\n                    ; c2 <- SignEncrypt KID2 (getKey (snd v)) USR1 (sharePrivKey kp)\n                    ; _  <- Send USR1 c2\n                    ; c3 <- @Recv Nat (SignedEncrypted KID1 (fst kp) true)\n                    ; m  <- Decrypt c3\n                    ; @Return (Base Nat) (extractContent m) )\n      ].\n\n    Definition real_univ_start :=\n      mkrU (mkKeys KEYS) real_users.\n  End RW.\n\n  #[export] Hint Unfold\n       simple_univ_start\n       ideal_univ_start\n       real_univ_start\n    : user_build.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with user_build; simpl) : core.\n  \nEnd ShareSecretSymmetricEncProtocol.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/protocols/ShareSecretProtocolSymmetricEnc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18945048087428024}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.reverse_client.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nDefinition t_struct_list := Tstruct _list noattr.\n\nFixpoint listrep (sigma: list int) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (Vint h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros. entailer!. intuition.\nIntros y. entailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\n#[export] Hint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep; intros; Intros; subst.\n auto with valid_pointer.\n Intros y.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\n#[export] Hint Resolve listrep_valid_pointer : valid_pointer.\n\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sigma : list int, p: val\n  PRE  [ tptr t_struct_list ]\n     PROP ()\n     PARAMS (p)\n     SEP (listrep sigma p)\n  POST [ (tptr t_struct_list) ]\n    EX q:val,\n     PROP () RETURN (q)\n     SEP (listrep (rev sigma) q).\n\nDefinition last_foo_spec :=\n DECLARE _last_foo\n  WITH sigma : list int, p: val, sigma': list int, x: int\n  PRE  [ tptr t_struct_list ]\n     PROP (sigma = sigma' ++ x :: nil)\n     PARAMS (p)\n     SEP (listrep sigma p)\n  POST [ tuint ]\n     PROP () RETURN (Vint x)\n     SEP (TT).\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ reverse_spec; last_foo_spec ]).\n\nLemma body_last_foo: semax_body Vprog Gprog\n                                    f_last_foo last_foo_spec.\nProof.\n  start_function.\n  subst sigma.\n  forward_call (sigma' ++ [x], p). (* p = reverse (p); *)\n  Intros p'.\n  rewrite rev_app_distr; simpl.\n  unfold listrep; fold listrep.\n  Intros q.\n  forward. (* res = p -> head; *)\n  forward. (* return res; *)\nQed.\n", "meta": {"author": "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_reverse_client.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18945048087428015}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Function calling conventions and other conventions regarding the use of \n    machine registers and stack slots. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Events.\nRequire Import Locations.\n\n(** * Classification of machine registers *)\n\n(** Machine registers (type [mreg] in module [Locations]) are divided in\n  the following groups:\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/EABI application binary interface (ABI) in our choice\n  of callee- and caller-save registers.\n*)\n\nDefinition int_caller_save_regs :=\n  R3 :: R4 :: R5 :: R6 :: R7 :: R8 :: R9 :: R10 :: R11 :: R12 :: nil.\n\nDefinition float_caller_save_regs :=\n  F0 :: F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: F8 :: F9 :: F10 :: F11 :: F12 :: F13 :: nil.\n\nDefinition int_callee_save_regs :=\n  R31 :: R30 :: R29 :: R28 :: R27 :: R26 :: R25 :: R24 :: R23 ::\n  R22 :: R21 :: R20 :: R19 :: R18 :: R17 :: R16 :: R15 :: R14 :: nil.\n\nDefinition float_callee_save_regs :=\n  F31 :: F30 :: F29 :: F28 :: F27 :: F26 :: F25 :: F24 :: F23 ::\n  F22 :: F21 :: F20 :: F19 :: F18 :: F17 :: F16 :: F15 :: F14 :: nil.\n\nDefinition destroyed_at_call :=\n  int_caller_save_regs ++ float_caller_save_regs.\n\nDefinition dummy_int_reg := R3.     (**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  | R14 => 17 | R15 => 16 | R16 => 15 | R17 => 14\n  | R18 => 13 | R19 => 12 | R20 => 11 | R21 => 10\n  | R22 => 9  | R23 => 8  | R24 => 7  | R25 => 6 \n  | R26 => 5  | R27 => 4  | R28 => 3  | R29 => 2 \n  | R30 => 1  | R31 => 0  | _ => -1\n  end.\n\nDefinition index_float_callee_save (r: mreg) :=\n  match r with\n  | F14 => 17 | F15 => 16 | F16 => 15 | F17 => 14\n  | F18 => 13 | F19 => 12 | F20 => 11 | F21 => 10\n  | F22 => 9  | F23 => 8  | F24 => 7  | F25 => 6 \n  | F26 => 5  | F27 => 4  | F28 => 3  | F29 => 2 \n  | F30 => 1  | F31 => 0  | _ => -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 = Tany32.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLemma float_callee_save_type:\n  forall r, In r float_callee_save_regs -> mreg_type r = Tany64.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLtac NoRepet :=\n  match goal with\n  | |- list_norepet nil =>\n      apply list_norepet_nil\n  | |- list_norepet (?a :: ?b) =>\n      apply list_norepet_cons; [simpl; intuition discriminate | NoRepet]\n  end.\n\nLemma int_callee_save_norepet:\n  list_norepet int_callee_save_regs.\nProof.\n  unfold int_callee_save_regs; NoRepet.\nQed.\n\nLemma float_callee_save_norepet:\n  list_norepet float_callee_save_regs.\nProof.\n  unfold float_callee_save_regs; NoRepet.\nQed.\n\n(** * Function calling conventions *)\n\n(** The functions in this section determine the locations (machine registers\n  and stack slots) used to communicate arguments and results between the\n  caller and the callee during function calls.  These locations are functions\n  of the signature of the function and of the call instruction.  \n  Agreement between the caller and the callee on the locations to use\n  is guaranteed by our dynamic semantics for Cminor and RTL, which demand \n  that the signature of the call instruction is identical to that of the\n  called function.\n\n  Calling conventions are largely arbitrary: they must respect the properties\n  proved in this section (such as no overlapping between the locations\n  of function arguments), but this leaves much liberty in choosing actual\n  locations.  To ensure binary interoperability of code generated by our\n  compiler with libraries compiled by another PowerPC compiler, we\n  implement the standard conventions defined in the PowerPC/EABI\n  application binary interface. *)\n\n(** ** Location of function result *)\n\n(** The result value of a function is passed back to the caller in\n  registers [R3] or [F1] or [R3, R4], depending on the type of the returned value.\n  We treat a function without result as a function with one integer result. *)\n\nDefinition loc_result (s: signature) : list mreg :=\n  match s.(sig_res) with\n  | None => R3 :: nil\n  | Some (Tint | Tany32) => R3 :: nil\n  | Some (Tfloat | Tsingle | Tany64) => F1 :: nil\n  | Some Tlong => R3 :: R4 :: nil\n  end.\n\n(** The result registers have types compatible with that given in the signature. *)\n\nLemma loc_result_type:\n  forall sig,\n  subtype_list (proj_sig_res' sig) (map mreg_type (loc_result sig)) = true.\nProof.\n  intros. unfold proj_sig_res', loc_result. destruct (sig_res sig) as [[]|]; auto.\nQed.\n\n(** The result locations are caller-save registers *)\n\nLemma loc_result_caller_save:\n  forall (s: signature) (r: mreg), \n  In r (loc_result s) -> In r destroyed_at_call.\nProof.\n  intros.\n  assert (r = R3 \\/ r = R4 \\/ r = F1).\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(** The PowerPC EABI states the following convention for passing arguments\n  to a function:\n- The first 8 integer arguments are passed in registers [R3] to [R10].\n- The first 8 float arguments are passed in registers [F1] to [F8].\n- The first 4 long integer arguments are passed in register pairs [R3,R4] ... [R9,R10].\n- Extra arguments are passed on the stack, in [Outgoing] slots, consecutively\n  assigned (1 word for an integer argument, 2 words for a float),\n  starting at word offset 0.\n- No stack space is reserved for the arguments that are passed in registers.\n*)\n\nDefinition int_param_regs :=\n  R3 :: R4 :: R5 :: R6 :: R7 :: R8 :: R9 :: R10 :: nil.\nDefinition float_param_regs :=\n  F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: F8 :: nil.\n\nFixpoint loc_arguments_rec\n    (tyl: list typ) (ir fr ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | (Tint | Tany32) as ty :: tys =>\n      match list_nth_z int_param_regs ir with\n      | None =>\n          S Outgoing ofs ty :: loc_arguments_rec tys ir fr (ofs + 1)\n      | Some ireg =>\n          R ireg :: loc_arguments_rec tys (ir + 1) fr ofs\n      end\n  | (Tfloat | Tsingle | Tany64) as ty :: tys =>\n      match list_nth_z float_param_regs fr with\n      | None =>\n          let ofs := align ofs 2 in\n          S Outgoing ofs ty :: loc_arguments_rec tys ir fr (ofs + 2)\n      | Some freg =>\n          R freg :: loc_arguments_rec tys ir (fr + 1) ofs\n      end\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      match list_nth_z int_param_regs ir, list_nth_z int_param_regs (ir + 1) with\n      | Some r1, Some r2 =>\n          R r1 :: R r2 :: loc_arguments_rec tys (ir + 2) fr ofs\n      | _, _ =>\n          let ofs := align ofs 2 in\n          S Outgoing ofs Tint :: S Outgoing (ofs + 1) Tint :: loc_arguments_rec tys ir fr (ofs + 2)\n      end\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) 0 0 0.\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) (ir fr ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => ofs\n  | (Tint | Tany32) :: tys =>\n      match list_nth_z int_param_regs ir with\n      | None => size_arguments_rec tys ir fr (ofs + 1)\n      | Some ireg => size_arguments_rec tys (ir + 1) fr ofs\n      end\n  | (Tfloat | Tsingle | Tany64) :: tys =>\n      match list_nth_z float_param_regs fr with\n      | None => size_arguments_rec tys ir fr (align ofs 2 + 2)\n      | Some freg => size_arguments_rec tys ir (fr + 1) ofs\n      end\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      match list_nth_z int_param_regs ir, list_nth_z int_param_regs (ir + 1) with\n      | Some r1, Some r2 => size_arguments_rec tys (ir + 2) fr ofs\n      | _, _ => size_arguments_rec tys ir fr (align ofs 2 + 2)\n      end\n  end.\n\nDefinition size_arguments (s: signature) : Z :=\n  size_arguments_rec s.(sig_args) 0 0 0.\n\n(** A tail-call is possible for a signature if the corresponding\n    arguments are all passed in registers. *)\n\nDefinition tailcall_possible (s: signature) : Prop :=\n  forall l, In l (loc_arguments s) ->\n  match l with R _ => True | S _ _ _ => False end.\n\n(** Argument locations are either caller-save 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 loc_arguments_rec_charact:\n  forall tyl ir fr ofs l,\n  In l (loc_arguments_rec tyl ir fr ofs) ->\n  match l with\n  | R r => In r int_param_regs \\/ In r float_param_regs\n  | S Outgoing ofs' ty => ofs' >= ofs /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\nOpaque list_nth_z.\n  induction tyl; simpl loc_arguments_rec; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct (list_nth_z int_param_regs ir) as [r|] eqn:E; destruct H.\n  subst. left. eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  subst. split. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n- (* float *)\n  destruct (list_nth_z float_param_regs fr) as [r|] eqn:E; destruct H. \n  subst. right. eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  intuition omega.\n- (* long *)\n  set (ir' := align ir 2) in *.\n  destruct (list_nth_z int_param_regs ir') as [r1|] eqn:E1.\n  destruct (list_nth_z int_param_regs (ir' + 1)) as [r2|] eqn:E2.\n  destruct H. subst; left; eapply list_nth_z_in; eauto.\n  destruct H. subst; left; eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  destruct H. subst. split. omega. congruence.\n  destruct H. subst. split. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  destruct H. subst. split. omega. congruence.\n  destruct H. subst. split. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega. \n- (* single *)\n  destruct (list_nth_z float_param_regs fr) as [r|] eqn:E; destruct H. \n  subst. right. eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  intuition omega.\n- (* any32 *)\n  destruct (list_nth_z int_param_regs ir) as [r|] eqn:E; destruct H.\n  subst. left. eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  subst. split. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto. intuition omega.\n- (* any64 *)\n  destruct (list_nth_z float_param_regs fr) as [r|] eqn:E; destruct H. \n  subst. right. eapply list_nth_z_in; eauto.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  exploit IHtyl; eauto. destruct l; auto. destruct sl; auto.\n  assert (ofs <= align ofs 2) by (apply align_le; omega). \n  intuition omega.\nQed.\n\nLemma loc_arguments_acceptable:\n  forall (s: signature) (l: loc),\n  In l (loc_arguments s) -> loc_argument_acceptable l.\nProof.\n  unfold loc_arguments; intros.\n  generalize (loc_arguments_rec_charact _ _ _ _ _ H).\n  destruct l.\n  intro H0; elim H0; simpl; ElimOrEq; OrEq.\n  destruct sl; try contradiction. simpl. intuition omega.\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 ir fr ofs0,\n  ofs0 <= size_arguments_rec tyl ir fr ofs0.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a.\n  destruct (list_nth_z int_param_regs ir); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (list_nth_z float_param_regs fr); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  set (ir' := align ir 2).\n  destruct (list_nth_z int_param_regs ir'); eauto.\n  destruct (list_nth_z int_param_regs (ir' + 1)); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  destruct (list_nth_z float_param_regs fr); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  destruct (list_nth_z int_param_regs ir); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (list_nth_z float_param_regs fr); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\nQed.\n\nLemma size_arguments_above:\n  forall s, size_arguments s >= 0.\nProof.\n  intros; unfold size_arguments. apply Zle_ge.  \n  apply size_arguments_rec_above.\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 ir fr ofs0,\n    In (S Outgoing ofs ty) (loc_arguments_rec tyl ir fr ofs0) ->\n    ofs + typesize ty <= size_arguments_rec tyl ir fr ofs0).\n{\n  induction tyl; simpl; intros.\n  elim H0.\n  destruct a.\n- (* int *)\n  destruct (list_nth_z int_param_regs ir); destruct H0. \n  congruence.\n  eauto.\n  inv H0. apply size_arguments_rec_above.\n  eauto.\n- (* float *)\n  destruct (list_nth_z float_param_regs fr); destruct H0. \n  congruence.\n  eauto.\n  inv H0. apply size_arguments_rec_above. eauto. \n- (* long *)\n  set (ir' := align ir 2) in *.\n  destruct (list_nth_z int_param_regs ir').\n  destruct (list_nth_z int_param_regs (ir' + 1)).\n  destruct H0. congruence. destruct H0. congruence. eauto.\n  destruct H0. inv H0. \n  transitivity (align ofs0 2 + 2). simpl; omega. eauto.  apply size_arguments_rec_above.\n  destruct H0. inv H0.\n  transitivity (align ofs0 2 + 2). simpl; omega. eauto.  apply size_arguments_rec_above.\n  eauto. \n  destruct H0. inv H0. \n  transitivity (align ofs0 2 + 2). simpl; omega. eauto.  apply size_arguments_rec_above.\n  destruct H0. inv H0.\n  transitivity (align ofs0 2 + 2). simpl; omega. eauto.  apply size_arguments_rec_above.\n  eauto.\n- (* single *)\n  destruct (list_nth_z float_param_regs fr); destruct H0. \n  congruence.\n  eauto.\n  inv H0. transitivity (align ofs0 2 + 2). simpl; omega. apply size_arguments_rec_above.\n  eauto.\n- (* any32 *)\n  destruct (list_nth_z int_param_regs ir); destruct H0. \n  congruence.\n  eauto.\n  inv H0. apply size_arguments_rec_above.\n  eauto.\n- (* any64 *)\n  destruct (list_nth_z float_param_regs fr); destruct H0. \n  congruence.\n  eauto.\n  inv H0. apply size_arguments_rec_above. eauto. \n  }\n  eauto.\nQed.\n\nLemma loc_arguments_main:\n  loc_arguments signature_main = nil.\nProof.\n  reflexivity.\nQed.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/powerpc/Conventions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.18945047891626912}}
{"text": "Require Import Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Coq.Structures.OrderedType.\n\nRequire Import\n        Fiat.BinEncoders.Env.BinLib.Core\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.Compose\n        Fiat.BinEncoders.Env.Common.ComposeOpt\n        Fiat.BinEncoders.Env.Automation.Solver\n        Fiat.BinEncoders.Env.Lib2.WordOpt\n        Fiat.BinEncoders.Env.Lib2.NatOpt\n        Fiat.BinEncoders.Env.Lib2.StringOpt\n        Fiat.BinEncoders.Env.Lib2.EnumOpt\n        Fiat.BinEncoders.Env.Lib2.FixListOpt\n        Fiat.BinEncoders.Env.Lib2.SumTypeOpt.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Examples.Tutorial.Tutorial\n        Fiat.Examples.DnsServer.DecomposeEnumField\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.BagADT\n        Fiat.QueryStructure.Automation.IndexSelection\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix\n        Fiat.QueryStructure.Automation.SearchTerms.FindPrefixSearchTerms\n        Fiat.Examples.HACMSDemo.DuplicateFree\n        Fiat.QueryStructure.Automation.MasterPlan.\n\nRequire Import\n        Bedrock.Word\n        Bedrock.Memory.\n\nLemma exists_CompletelyUnConstrFreshIdx:\n  forall (qs_schema : RawQueryStructureSchema)\n    (BagIndexKeys : ilist3 (qschemaSchemas qs_schema))\n    (r_o : UnConstrQueryStructure qs_schema)\n    (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n  DelegateToBag_AbsR r_o r_n ->\n  exists bnd : nat,\n  forall idx : Fin.t (numRawQSschemaSchemas qs_schema),\n    UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd.\nProof.\n  intros.\n  generalize (exists_UnConstrFreshIdx H); clear H.\n  remember (GetUnConstrRelation r_o); clear.\n  destruct qs_schema; simpl in *.\n  clear qschemaConstraints.\n  induction numRawQSschemaSchemas; simpl in *; intros.\n  - exists 0; intros; inversion idx.\n  - revert i IHnumRawQSschemaSchemas H.\n    pattern numRawQSschemaSchemas, qschemaSchemas;\n      apply Vector.caseS; simpl; intros.\n    destruct (IHnumRawQSschemaSchemas\n                t\n                (fun idx => i (Fin.FS idx))\n                (fun idx => H (Fin.FS idx))\n             ).\n    destruct (H Fin.F1).\n    exists (max x x0).\n    unfold UnConstrFreshIdx in *; simpl in *; intros.\n    pose proof (Max.le_max_l x x0);\n      pose proof (Max.le_max_r x x0).\n    generalize dependent idx; intro; generalize t i x x0 H0 H1 H3 H4;\n      clear; pattern n, idx; apply Fin.caseS; simpl; intros.\n    apply H1 in H2; omega.\n    apply H0 in H2; omega.\nQed.\n\nLemma refine_Pick_CompletelyUnConstrFreshIdx\n  : forall (qs_schema : RawQueryStructureSchema)\n    (BagIndexKeys : ilist3 (qschemaSchemas qs_schema))\n    (r_o : UnConstrQueryStructure qs_schema)\n    (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n    DelegateToBag_AbsR r_o r_n ->\n    forall (bnd : nat),\n      (forall (idx : Fin.t (numRawQSschemaSchemas qs_schema)),\n          UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd) ->\n      refine {bnd0 : nat | forall idx, UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd0} (ret bnd).\nProof.\n  intros; refine pick val _; eauto.\n  reflexivity.\nQed.\n\nInstance Query_eq_word32 : Query_eq (word 32) :=\n  {| A_eq_dec := @weq 32 |}.\n\nGlobal Instance GetAttributeRawTermCounter' {A : Type} {qsSchema}\n         {Ridx : Fin.t _}\n         {tup : @RawTuple (Vector.nth _ Ridx)}\n         {BAidx : _ }\n         a\n    : (TermAttributeCounter qsSchema (@GetAttributeRaw {| NumAttr := S _;\n                                                          AttrList := Vector.cons _ A _ _ |} {|prim_fst := a; prim_snd := tup |} (Fin.FS BAidx)) Ridx BAidx) | 0 := Build_TermAttributeCounter qsSchema _ Ridx BAidx.\n\nLtac GetAttributeRawTermCounterTac t ::=\n     lazymatch goal with\n       _ =>\n       match goal with\n         |- TermAttributeCounter\n              ?qs_schema\n              (GetAttributeRaw {| prim_fst := ?a;\n                             prim_snd := ?tup |} (Fin.FS ?BAidx))\n         _ _ =>\n    match type of tup with\n    | @RawTuple (@GetNRelSchemaHeading _ _ ?Ridx) =>\n      apply (@GetAttributeRawTermCounter' _ qs_schema Ridx tup _ a)\n    end\n    end\n  end.\n\nLemma refineEquiv_Query_Where_And\n      {ResultT}\n  : forall P P' bod,\n    (P \\/ ~ P)\n    -> refineEquiv (@Query_Where ResultT (P /\\ P') bod)\n                (Query_Where P (Query_Where P' bod)).\nProof.\n  split; unfold refine, Query_Where; intros;\n    computes_to_inv; computes_to_econstructor;\n      intuition.\n  - computes_to_inv; intuition.\n  - computes_to_inv; intuition.\n  - computes_to_econstructor; intuition.\nQed.\n\nCorollary refineEquiv_For_Query_Where_And\n          {ResultT}\n          {qs_schema}\n  : forall (r : UnConstrQueryStructure qs_schema) idx P P' bod,\n    (forall tup, P tup \\/ ~ P tup)\n    -> refine (For (UnConstrQuery_In\n                      r idx\n                      (fun tup => @Query_Where ResultT (P tup /\\ P' tup) (bod tup))))\n              (For (UnConstrQuery_In\n                      r idx\n                      (fun tup => Where (P tup) (Where (P' tup) (bod tup))))).\nProof.\n  intros; apply refine_refine_For_Proper.\n  apply refine_UnConstrQuery_In_Proper.\n  intro; apply refineEquiv_Query_Where_And; eauto.\nQed.\n\nLemma refine_If_IfOpt {A B}\n  : forall (a_opt : option A) (t e : Comp B),\n    refine (If_Then_Else (If_Opt_Then_Else a_opt (fun _ => false) true)\n                         t e)\n           (If_Opt_Then_Else a_opt (fun _ => e) t).\nProof.\n  destruct a_opt; simpl; intros; reflexivity.\nQed.\n\nGlobal Arguments icons2 _ _ _ _ _ _ _ / .\nGlobal Arguments GetAttributeRaw {heading} !tup !attr .\nGlobal Arguments ilist2_tl _ _ _ _ !il / .\nGlobal Arguments ilist2_hd _ _ _ _ !il / .\n\nGlobal Opaque If_Opt_Then_Else.\nLtac implement_DecomposeRawQueryStructure :=\n  first [ simplify with monad laws; simpl\n        | rewrite refine_If_IfOpt\n        | match goal with\n            |- refine (b <- If_Opt_Then_Else _ _ _; _) _ =>\n            etransitivity;\n            [ apply refine_If_Opt_Then_Else_Bind\n            | simpl; eapply refine_If_Opt_Then_Else_trans;\n              intros; set_refine_evar ]\n          end\n        | match goal with\n            H0 : DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ ?r_o ?r_n |- refine _ ?H => unfold H;\n                                                                                            apply (refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv H0 Fin.F1)\n          end\n        | match goal with\n            H0 : DecomposeRawQueryStructureSchema_AbsR' (qs_schema := ?qs_schema) _ _ _ _ ?r_o ?r_n |- refine (Query_For _ ) _ =>\n            rewrite (refineEquiv_For_Query_Where_And r_o Fin.F1); eauto\n          end\n        |\n        match goal with\n          H0 : DecomposeRawQueryStructureSchema_AbsR' (qs_schema := ?qs_schema) _ _ _ _ ?r_o ?r_n |- refine (Query_For _ ) _ =>\n          rewrite (@refine_QueryIn_Where _ qs_schema Fin.F1 _ _ _ _ _ H0 _ _ _ );\n          unfold Tuple_DecomposeRawQueryStructure_inj; simpl\n        end\n        | match goal with\n            H0 : DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ ?r_o ?r_n\n            |- refine { r_n | DecomposeRawQueryStructureSchema_AbsR' _ _ _ _ _ r_n} _ =>\n            first [refine pick val _; [ | eassumption ]\n                  | refine pick val _;\n                    [ | apply (DecomposeRawQueryStructureSchema_Insert_AbsR_eq H0) ] ]\n          end\n        ].\n\nLtac implement_DecomposeRawQueryStructure' H :=\n  first [\n      simplify with monad laws; simpl\n    | rewrite H\n    | apply refine_pick_eq'\n    | etransitivity;\n      [ apply refine_If_Opt_Then_Else_Bind\n      | simpl; eapply refine_If_Opt_Then_Else_trans;\n        intros; set_refine_evar ] ].\n\n  Lemma GetAttributeRaw_FS\n    : forall {A} {heading} (a : A) (tup : @RawTuple heading) n,\n      @GetAttributeRaw {| AttrList := Vector.cons _ A _ (AttrList heading) |}\n                       {| prim_fst := a; prim_snd := tup |} (Fin.FS n)\n    = GetAttributeRaw tup n.\n  Proof.\n    unfold GetAttributeRaw; simpl; reflexivity.\n  Qed.\n\n    Lemma GetAttributeRaw_F1\n    : forall {A} {heading} (a : A) (tup : @RawTuple heading),\n      @GetAttributeRaw {| AttrList := Vector.cons _ A _ (AttrList heading) |}\n                       {| prim_fst := a; prim_snd := tup |} Fin.F1\n    = a.\n  Proof.\n    unfold GetAttributeRaw; simpl; reflexivity.\n  Qed.\n\n  Module word_as_OT <: OrderedType.\n    Definition t := word 32.\n    Definition eq (c1 c2 : t) := c1 = c2.\n    Definition lt (c1 c2 : t) := wlt c1 c2.\n\n    Definition eq_dec : forall l l', {eq l l'} + {~eq l l'} := @weq 32 .\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.\n      intros. unfold eq, lt, wlt in *. intro.\n      rewrite <- N.compare_lt_iff in H.\n      subst; rewrite N.compare_refl in H; discriminate.\n    Qed.\n\n    Lemma compare : forall x y, Compare lt eq x y.\n    Proof.\n      intros. unfold lt, eq, wlt.\n      destruct (N.compare (wordToN x) (wordToN y)) eqn: eq.\n      - eapply EQ. apply N.compare_eq_iff in eq; apply wordToN_inj; eauto.\n      - eapply LT. abstract (rewrite <- N.compare_lt_iff; eauto).\n      - eapply GT. abstract (rewrite <- N.compare_gt_iff; eauto).\n    Defined.\nEnd word_as_OT.\n\nModule wordIndexedMap := FMapAVL.Make word_as_OT.\n\nModule wordTreeBag := TreeBag wordIndexedMap.\n\nLtac BuildQSIndexedBag heading AttrList BuildEarlyBag BuildLastBag k ::=\n  lazymatch AttrList with\n  | (?Attr :: [ ])%list =>\n    let AttrKind := eval simpl in (KindIndexKind Attr) in\n        let AttrIndex := eval simpl in (KindIndexIndex Attr) in\n            let is_equality := eval compute in (string_dec AttrKind \"EqualityIndex\") in\n\n                lazymatch is_equality with\n                | left _ =>\n                  let AttrType := eval compute in (Domain heading AttrIndex) in\n                      lazymatch AttrType with\n                      | BinNums.N =>\n                        k (@NTreeBag.IndexedBagAsCorrectBag\n                             _ _ _ _ _ _ _\n                             (@CountingListAsCorrectBag\n                                (@RawTuple heading)\n                                (IndexedTreeUpdateTermType heading)\n                                (IndexedTreebupdate_transform heading))\n                             (fun x => GetAttributeRaw (heading := heading) x AttrIndex)\n                          )\n                      | word 32 =>\n                        k (@wordTreeBag.IndexedBagAsCorrectBag\n                             _ _ _ _ _ _ _\n                             (@CountingListAsCorrectBag\n                                (@RawTuple heading)\n                                (IndexedTreeUpdateTermType heading)\n                                (IndexedTreebupdate_transform heading))\n                             (fun x => GetAttributeRaw (heading := heading) x AttrIndex)\n                          )\n\n                      | BinNums.Z =>\n                        k (@ZTreeBag.IndexedBagAsCorrectBag\n                             _ _ _ _ _ _ _\n                             (@CountingListAsCorrectBag\n                                (@RawTuple heading)\n                                (IndexedTreeUpdateTermType heading)\n                                (IndexedTreebupdate_transform heading))\n                             (fun x => GetAttributeRaw (heading := heading) x AttrIndex)\n                          )\n                      | nat =>\n                        k (@NatTreeBag.IndexedBagAsCorrectBag\n                             _ _ _ _ _ _ _\n                             (@CountingListAsCorrectBag\n                                (@RawTuple heading)\n                                (IndexedTreeUpdateTermType heading)\n                                (IndexedTreebupdate_transform heading))\n                             (fun x => GetAttributeRaw (heading := heading) x AttrIndex)\n                          )\n                      | string =>\n                        k (@StringTreeBag.IndexedBagAsCorrectBag\n                             _ _ _ _ _ _ _\n                             (@CountingListAsCorrectBag\n                                (@RawTuple heading)\n                                (IndexedTreeUpdateTermType heading)\n                                (IndexedTreebupdate_transform heading))\n                             (fun x => GetAttributeRaw (heading := heading) x AttrIndex)\n                          )\n                      end\n                | right _ =>\n                  BuildLastBag heading AttrList AttrKind AttrIndex k\n                end\n  | (?Attr :: ?AttrList')%list =>\n    let AttrKind := eval simpl in (KindIndexKind Attr) in\n        let AttrIndex := eval simpl in (KindIndexIndex Attr) in\n            let is_equality := eval compute in (string_dec AttrKind \"EqualityIndex\") in\n                lazymatch is_equality with\n                | left _ =>\n                  let AttrType := eval compute in (Domain heading AttrIndex) in\n                      lazymatch AttrType with\n                      | BinNums.N =>\n                        BuildQSIndexedBag\n                          heading AttrList'\n                          BuildEarlyBag BuildLastBag\n                          ltac:(fun subtree =>\n                                  k (@NTreeBag.IndexedBagAsCorrectBag\n                                       _ _ _ _ _ _ _ subtree\n                                       (fun x => GetAttributeRaw (heading := heading) x AttrIndex)))\n                      | BinNums.Z =>\n                        BuildQSIndexedBag\n                          heading AttrList'\n                          BuildEarlyBag BuildLastBag\n                          (fun x => GetAttributeRaw x AttrIndex)\n                          ltac:(fun subtree =>\n                                  k (@ZTreeBag.IndexedBagAsCorrectBag\n                                       _ _ _ _ _ _ _ subtree\n                                       (fun x => GetAttributeRaw (heading := heading) x AttrIndex)))\n                      | nat =>\n                        BuildQSIndexedBag\n                          heading AttrList'\n                          BuildEarlyBag BuildLastBag\n                          ltac:(fun subtree =>\n                                  k (@NatTreeBag.IndexedBagAsCorrectBag\n                                       _ _ _ _ _ _ _ subtree\n                                       (fun x => GetAttributeRaw (heading := heading) x AttrIndex)))\n                      | string =>\n                        BuildQSIndexedBag\n                          heading AttrList'\n                          BuildEarlyBag BuildLastBag\n                          ltac:(fun subtree =>\n                                  k (@StringTreeBag.IndexedBagAsCorrectBag\n                                       _ _ _ _ _ _ _ subtree\n                                       (fun x => GetAttributeRaw (heading := heading) x AttrIndex)))\n                      end\n                | right _ =>\n                  BuildQSIndexedBag\n                    heading AttrList'\n                    BuildEarlyBag BuildLastBag\n                    ltac:(fun subtree =>\n                            BuildEarlyBag\n                                 heading AttrList AttrKind AttrIndex subtree k)\n                end\n  | ([ ])%list =>\n    k (@CountingListAsCorrectBag\n         (@RawTuple heading)\n         (IndexedTreeUpdateTermType heading)\n         (IndexedTreebupdate_transform heading))\n  end.\n\n  Ltac rewrite_drill ::=\n       subst_refine_evar; (first\n                             [\n                               match goal with\n                                 |- refine (b <- If_Opt_Then_Else _ _ _; _) _ =>\n                                 etransitivity;\n                                 [ apply refine_If_Opt_Then_Else_Bind\n                                 | simpl; eapply refine_If_Opt_Then_Else_trans;\n                                   intros; set_refine_evar ]\n                               end\n                             | eapply refine_under_bind_both; [ set_refine_evar | intros; set_refine_evar ]\n                             | eapply refine_If_Then_Else; [ set_refine_evar | set_refine_evar ] ] ).\n\n\n  Ltac implement_insert CreateTerm EarlyIndex LastIndex\n       makeClause_dep EarlyIndex_dep LastIndex_dep ::=\n    repeat first\n           [simplify with monad laws; simpl\n           | match goal with\n               |- context [(@GetAttributeRaw ?heading {| prim_fst := ?a;\n                                                         prim_snd := ?tup |} (Fin.FS ?BAidx)) ] =>\n               setoid_rewrite (@GetAttributeRaw_FS\n                                 (Vector.hd (AttrList heading))\n                                 {| AttrList := Vector.tl (AttrList heading)|} a _ BAidx)\n             end\n           | match goal with\n             | |- context [(@GetAttributeRaw ?heading {| prim_fst := ?a;\n                                                         prim_snd := ?tup |} Fin.F1) ] =>\n               rewrite (@GetAttributeRaw_F1\n                          (Vector.hd (AttrList heading))\n                          {| AttrList := Vector.tl (AttrList heading) |} a)\n             end\n           | setoid_rewrite refine_If_Then_Else_Bind\n           | match goal with\n               H : DelegateToBag_AbsR ?r_o ?r_n\n               |- context[Pick (fun idx => forall Ridx, UnConstrFreshIdx (GetUnConstrRelation ?r_o Ridx) idx)] =>\n               let freshIdx := fresh in\n               destruct (exists_CompletelyUnConstrFreshIdx _ _ _ _ H) as [? freshIdx];\n               rewrite (refine_Pick_CompletelyUnConstrFreshIdx _ _ _ _ H _ freshIdx)\n             end\n           | implement_Query CreateTerm EarlyIndex LastIndex\n                             makeClause_dep EarlyIndex_dep LastIndex_dep\n           | progress (rewrite ?refine_BagADT_QSInsert; try setoid_rewrite refine_BagADT_QSInsert); [ | solve [ eauto ] .. ]\n           | progress (rewrite ?refine_Pick_DelegateToBag_AbsR; try setoid_rewrite refine_Pick_DelegateToBag_AbsR); [ | solve [ eauto ] .. ] ].\n\n  Ltac choose_data_structures :=\n    simpl; pose_string_ids; pose_headings_all;\n    pose_search_term;  pose_SearchUpdateTerms;\n    match goal with\n      |- context [ @Build_IndexedQueryStructure_Impl_Sigs _ ?indices ?SearchTerms _ ] => try unfold SearchTerms\n    end; BuildQSIndexedBags' BuildEarlyBag BuildLastBag.\n\n  Ltac insertOne :=\n    insertion CreateTerm EarlyIndex LastIndex\n              makeClause_dep EarlyIndex_dep LastIndex_dep.\n\nGlobal Instance cache : Cache :=\n  {| CacheEncode := unit;\n     CacheDecode := unit;\n     Equiv ce cd := True |}.\nGlobal Instance cacheAddNat : CacheAdd cache nat :=\n  {| addE ce n := tt;\n     addD cd n := tt;\n     add_correct ce cd t m := I |}.\n\nDefinition transformer : Transformer bin := btransformer.\nGlobal Instance transformerUnit : TransformerUnitOpt transformer bool :=\n  {| T_measure t := 1;\n     transform_push_opt b t := (b :: t)%list;\n     transform_pop_opt t :=\n       match t with\n       | b :: t' => Some (b, t')\n       | _ => None\n       end%list\n  |}.\nabstract (simpl; intros; omega).\nabstract (simpl; intros; omega).\nabstract (destruct b;\n          [ simpl; discriminate\n          | intros; injections; simpl; omega ] ).\nreflexivity.\nreflexivity.\nabstract (destruct b; destruct b'; simpl; intros; congruence).\nDefined.\nDefinition Empty : CacheEncode := tt.\n\n  Ltac decompose_EnumField Ridx Fidx :=\n    match goal with\n      |- appcontext[ @BuildADT (UnConstrQueryStructure (QueryStructureSchemaRaw ?qs_schema)) ]\n      =>\n      let n := eval compute in (NumAttr (GetHeading qs_schema Ridx)) in\n    let AbsR' := constr:(@DecomposeRawQueryStructureSchema_AbsR' n qs_schema ``Ridx ``Fidx id (fun i => ibound (indexb i))\n                                                (fun val =>\n                                                   {| bindex := _;\n                                                      indexb := {| ibound := val;\n                                                                   boundi := @eq_refl _ _ |} |})) in hone representation using AbsR'\n    end;\n      try first [ solve [simplify with monad laws;\n                         apply refine_pick_val;\n                         apply DecomposeRawQueryStructureSchema_empty_AbsR ]\n                | doAny ltac:(implement_DecomposeRawQueryStructure)\n                               rewrite_drill ltac:(cbv beta; simpl; finish honing) ];\n  simpl; hone representation using (fun r_o r_n => snd r_o = r_n);\n    try first [\n        solve [simplify with monad laws; apply refine_pick_val; reflexivity ]\n      |\n      match goal with\n        H : snd ?r_o = ?r_n |- _\n        => doAny ltac:(implement_DecomposeRawQueryStructure' H)\n                        ltac:(rewrite_drill; simpl)\n                               ltac:(finish honing)\n      end\n        ];\n    cbv beta; unfold DecomposeRawQueryStructureSchema, DecomposeSchema; simpl.\n\n\n  Ltac makeEvar T k :=\n    let x := fresh in evar (x : T); let y := eval unfold x in x in clear x; k y.\n\n  Ltac shelve_inv :=\n    let H' := fresh in\n    let data := fresh in\n    intros data H';\n    repeat destruct H';\n    match goal with\n    | H : ?P data |- ?P_inv' =>\n      is_evar P;\n      let P_inv' := (eval pattern data in P_inv') in\n      let P_inv := match P_inv' with ?P_inv data => P_inv end in\n      let new_P_T := type of P in\n      makeEvar new_P_T\n               ltac:(fun new_P =>\n                       unify P (fun data => new_P data /\\ P_inv data)); apply (Logic.proj2 H)\n    end.\n\n  Ltac solve_data_inv :=\n    first [ intros; exact I\n          | solve\n              [ let data := fresh in\n                let H' := fresh in\n                let H'' := fresh in\n                intros data H' *;\n                match goal with\n                  proj : BoundedIndex _ |- _ =>\n                  instantiate (1 := ibound (indexb proj));\n                  destruct H' as [? H'']; intuition;\n                  try (rewrite <- H''; reflexivity);\n                  destruct data; simpl; eauto\n                end ]\n          | shelve_inv ].\n\n  Ltac apply_compose :=\n    intros;\n    match goal with\n      H : cache_inv_Property ?P ?P_inv |- _ =>\n      first [eapply (compose_encode_correct_no_dep H); clear H\n            | eapply (compose_encode_correct H); clear H\n            ]\n    end.\n\n  Ltac build_decoder :=\n    first [ solve [eapply Enum_decode_correct; [   repeat econstructor; simpl; intuition;\n    repeat match goal with\n            H : @Vector.In _ _ _ _ |- _ =>\n            inversion H;\n              apply_in_hyp Eqdep.EqdepTheory.inj_pair2; subst\n          end\n | .. ]; eauto  ]\n          | solve [eapply Word_decode_correct ]\n          | solve [eapply Nat_decode_correct ]\n          | solve [eapply String_decode_correct ]\n          | eapply (SumType_decode_correct\n            [ _ ]%vector\n            (icons _ inil)\n            (icons _ inil)\n            (@Iterate_Dep_Type_equiv' 1 _ (icons _ inil))\n            (@Iterate_Dep_Type_equiv' 1 _ (icons _ inil)));\n            [let idx' := fresh in\n             intro idx'; pattern idx';\n             eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;\n             repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I end)\n            | .. ]\n          | eapply (SumType_decode_correct\n            [ _; _]%vector\n            (icons _ (icons _ inil))\n            (icons _ (icons _ inil))\n            (@Iterate_Dep_Type_equiv' 2 _ (icons _ (icons _ inil)))\n            (@Iterate_Dep_Type_equiv' 2 _ (icons _ (icons _ inil))));\n            [let idx' := fresh in\n             intro idx'; pattern idx';\n             eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;\n             repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I end)\n                     | .. ]\n          | eapply (SumType_decode_correct\n            [ _; _; _ ]%vector\n            (icons _ (icons _ (icons _ inil)))\n            (icons _ (icons _ (icons _ inil)))\n            (@Iterate_Dep_Type_equiv' 3 _ (icons _ (icons _ (icons _ inil))))\n            (@Iterate_Dep_Type_equiv' 3 _ (icons (icons _ (icons _ inil)))));\n            [let idx' := fresh in\n             intro idx'; pattern idx';\n             eapply Iterate_Ensemble_equiv' with (idx := idx'); simpl;\n             repeat (match goal with |- prim_and _ _ => apply Build_prim_and; try exact I  end)\n            | .. ]\n          | intros;\n            match goal with\n              |- encode_decode_correct_f\n                   _ _ _\n                   (encode_list_Spec _) _ _ =>\n              eapply FixList_decode_correct end\n          | apply_compose ].\n\n  Lemma Fin_inv :\n    forall n (idx : Fin.t (S n)),\n      idx = Fin.F1 \\/ exists n', idx = Fin.FS n'.\n  Proof. apply Fin.caseS; eauto. Qed.\n\n  Ltac solve_cache_inv :=\n    repeat instantiate (1 := fun _ => True);\n    unfold cache_inv_Property; intuition;\n    repeat match goal with\n           | idx : Fin.t (S _) |- _ =>\n             destruct (Fin_inv _ idx) as [? | [? ?] ]; subst; simpl; eauto\n           | idx : Fin.t 0 |- _ =>  inversion idx\n           end.\n\n  Ltac finalize_decoder P_inv :=\n  (unfold encode_decode_correct_f; intuition eauto);\n    [ computes_to_inv; injections; subst; simpl;\n      match goal with\n        H : Equiv _ ?env |- _ =>\n        eexists env; intuition eauto;\n        simpl;\n        match goal with\n          |- ?f ?a ?b ?c = ?P =>\n          let P' := (eval pattern a, b, c in P) in\n          let f' := match P' with ?f a b c => f end in\n          unify f f'; reflexivity\n        end\n      end\n    | injections; eauto\n    | eexists _; eexists _;\n      intuition eauto; injections; eauto using idx_ibound_eq;\n      try match goal with\n        |- P_inv ?data => destruct data;\n                                 simpl in *; eauto\n      end\n    ].\n\n  Ltac build_decoder_component :=\n    (build_decoder || solve_data_inv).\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Examples/HACMSDemo/HACMSDemo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.18938383408468976}}
{"text": "Require Import VerdiRaft.Raft.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.RefinementSpecLemmas.\nRequire Import VerdiRaft.SpecLemmas.\n\nRequire Import VerdiRaft.AllEntriesLeaderLogsTermInterface.\nRequire Import VerdiRaft.AppendEntriesRequestLeaderLogsInterface.\n\nSection AllEntriesLeaderLogsTerm.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Context {aerlli : append_entries_leaderLogs_interface}.\n\n  Lemma allEntries_leaderLogs_term_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_leaderLogs_term.\n  Proof using aerlli. \n    red. unfold allEntries_leaderLogs_term. intros. simpl in *. subst.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    [|find_apply_hyp_hyp; intuition;\n      right; break_exists_exists; intuition;\n      find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto;\n      rewrite update_elections_data_appendEntries_leaderLogs; eauto].\n    find_apply_lem_hyp update_elections_data_appendEntries_allEntries_term.\n    intuition;\n      [find_apply_hyp_hyp; intuition;\n       right; break_exists_exists; intuition;\n       find_higher_order_rewrite;\n       destruct_update; simpl in *; eauto;\n       rewrite update_elections_data_appendEntries_leaderLogs; eauto|].\n    subst.\n    match goal with\n      | H : context [pBody] |- _ =>\n        eapply append_entries_leaderLogs_invariant in H; eauto\n    end.\n    break_exists. break_and. subst. do_in_app.\n    case H7; intros; try find_apply_hyp_hyp; auto.\n    right.\n    find_eapply_lem_hyp Prefix_In; eauto.\n    repeat eexists; eauto.\n    find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto;\n      rewrite update_elections_data_appendEntries_leaderLogs; subst; eauto.\n  Qed.\n\n  (* rest of cases are easy *)\n  Lemma allEntries_leaderLogs_term_init :\n    refined_raft_net_invariant_init allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_init, allEntries_leaderLogs_term.\n    simpl. intuition.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_client_request :\n    refined_raft_net_invariant_client_request allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, allEntries_leaderLogs_term.\n    simpl.\n    intros.\n    subst.\n    repeat find_higher_order_rewrite.\n    destruct_update.\n    - simpl in *.\n      find_copy_apply_lem_hyp update_elections_data_client_request_allEntries.\n      intuition.\n      + repeat find_rewrite.\n        find_apply_hyp_hyp.\n        intuition.\n        right.\n        break_exists_exists.\n        find_higher_order_rewrite.\n        destruct_update.\n        * simpl in *. rewrite update_elections_data_client_request_leaderLogs.\n          intuition.\n        * intuition.\n      + break_exists. intuition.\n        find_rewrite. simpl in *. intuition.\n        * find_inversion.\n          find_copy_apply_lem_hyp handleClientRequest_type.\n          intuition.\n          repeat find_rewrite. intuition.\n        * find_apply_hyp_hyp.\n          intuition.\n          right.\n          break_exists_exists.\n          find_higher_order_rewrite.\n          { destruct_update.\n            * simpl in *. rewrite update_elections_data_client_request_leaderLogs.\n              intuition.\n            * intuition.\n          }\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      { destruct_update.\n        * simpl in *. rewrite update_elections_data_client_request_leaderLogs.\n          intuition.\n        * intuition.\n      }\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_timeout :\n    refined_raft_net_invariant_timeout allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, allEntries_leaderLogs_term.\n    simpl. intros.\n    repeat find_higher_order_rewrite.\n    destruct_update.\n    - simpl in *.\n      find_rewrite_lem update_elections_data_timeout_allEntries.\n      find_apply_hyp_hyp.\n      intuition.\n      right. break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. rewrite update_elections_data_timeout_leaderLogs. intuition.\n      + intuition.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. rewrite update_elections_data_timeout_leaderLogs. intuition.\n      + intuition.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, allEntries_leaderLogs_term.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    destruct_update.\n    - simpl in *. find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. auto.\n      + intuition.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. auto.\n      + intuition.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, allEntries_leaderLogs_term.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    destruct_update.\n    - simpl in *. find_rewrite_lem update_elections_data_requestVote_allEntries.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. rewrite leaderLogs_update_elections_data_requestVote. auto.\n      + intuition.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl in *. rewrite leaderLogs_update_elections_data_requestVote. auto.\n      + intuition.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote_reply, allEntries_leaderLogs_term.\n    simpl. intros.\n    repeat find_higher_order_rewrite.\n    destruct_update.\n    - simpl in *. find_rewrite_lem update_elections_data_requestVoteReply_allEntries.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl. intuition.\n        apply update_elections_data_requestVoteReply_old.\n        auto.\n      + auto.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl. intuition.\n        apply update_elections_data_requestVoteReply_old.\n        auto.\n      + auto.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, allEntries_leaderLogs_term.\n    simpl. intros.\n    repeat find_higher_order_rewrite.\n    match goal with\n    | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n      ((replace gd with (fst (nwState net h)) in * by (now rewrite H));\n        (replace d with (snd (nwState net h)) in * by (now rewrite H))); clear H\n    end.\n    destruct_update.\n    - simpl in *.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update; auto.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      repeat find_higher_order_rewrite.\n      destruct_update; auto.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, allEntries_leaderLogs_term.\n    simpl. intros.\n    repeat find_higher_order_rewrite.\n    match goal with\n    | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n      ((replace gd with (fst (nwState net h)) in * by (now rewrite H));\n        (replace d with (snd (nwState net h)) in * by (now rewrite H))); clear H\n    end.\n    destruct_update.\n    - simpl in *.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update; auto.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      repeat find_higher_order_rewrite.\n      destruct_update; auto.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, allEntries_leaderLogs_term.\n    simpl.\n    intros.\n    find_reverse_higher_order_rewrite.\n    find_apply_hyp_hyp.\n    intuition.\n    right. break_exists_exists.\n    find_reverse_higher_order_rewrite.\n    auto.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_reboot :\n    refined_raft_net_invariant_reboot allEntries_leaderLogs_term.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, allEntries_leaderLogs_term.\n    simpl. intros.\n    find_higher_order_rewrite.\n    match goal with\n    | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n      ((replace gd with (fst (nwState net h)) in * by (now rewrite H));\n        (replace d with (snd (nwState net h)) in * by (now rewrite H))); clear H\n    end.\n    subst.\n    destruct_update.\n    - simpl in *.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl. intuition.\n      + auto.\n    - find_apply_hyp_hyp.\n      intuition.\n      right.\n      break_exists_exists.\n      find_higher_order_rewrite.\n      destruct_update.\n      + simpl. intuition.\n      + auto.\n  Qed.\n\n  Lemma allEntries_leaderLogs_term_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      allEntries_leaderLogs_term net.\n  Proof using aerlli rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply allEntries_leaderLogs_term_init.\n    - apply allEntries_leaderLogs_term_client_request.\n    - apply allEntries_leaderLogs_term_timeout.\n    - apply allEntries_leaderLogs_term_append_entries.\n    - apply allEntries_leaderLogs_term_append_entries_reply.\n    - apply allEntries_leaderLogs_term_request_vote.\n    - apply allEntries_leaderLogs_term_request_vote_reply.\n    - apply allEntries_leaderLogs_term_do_leader.\n    - apply allEntries_leaderLogs_term_do_generic_server.\n    - apply allEntries_leaderLogs_term_state_same_packet_subset.\n    - apply allEntries_leaderLogs_term_reboot.\n  Qed.\n\n  Instance aellti : allEntries_leaderLogs_term_interface.\n  split.\n  exact allEntries_leaderLogs_term_invariant.\n  Qed.\nEnd AllEntriesLeaderLogsTerm.\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/AllEntriesLeaderLogsTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.18932355014276117}}
{"text": "Require Import msl.msl_standard.\nRequire Import Maps.\nRequire Import FuncListMachine.\nRequire Import lemmas.\nRequire Import hoare_total.\nRequire Import wp.\n\n(* This is some tentative work-in-progress *)\n\nFixpoint list_nat (n:nat) (x:value) {struct n} :=\n  match n, x with\n  | 0, value_label 1%positive => True\n  | S n', value_cons (value_label 1%positive) x' => list_nat n' x'\n  | _, _ => False\n  end.\n\nFixpoint list_length (x:value) :=\n  match x with\n  | value_cons _ x' => S (list_length x')\n  | _ => 0\n  end.\n\nDefinition list_nat_var (n:nat) (v:var) (r:store) :=\n  match r#v with\n  | None => False\n  | Some x => list_nat n x\n  end.\n\nProgram Definition add_term_measure : termMeas :=\n  fun r n =>\n  match r#(V 1) with\n  | Some x => list_length x = n\n  | None => False\n  end.\nNext Obligation.\n  destruct x; intuition.\n  destruct x1; intuition.\n  destruct o0; intuition.\nQed.\n\nDefinition add_P' n m st :=\n    list_nat_var n (V 1) st /\\\n    list_nat_var m (V 2) st.\n\nDefinition add_Q' n m st := list_nat_var (n+m) (V 2) st.\n\nDefinition add_P (nm:nat*nat) := store_op (add_P' (fst nm) (snd nm)).\nDefinition add_Q (nm:nat*nat) := store_op (add_Q' (fst nm) (snd nm)).\n\nDefinition valueTermMeas :=\n  { R: value -> nat -> Prop |\n    forall v n n', R v n -> R v n' -> n = n' }.\n\nRecord stdFunspec A :=\n  { sfs_t     : valueTermMeas\n  ; sfs_P     : A -> value -> pred prog\n  ; sfs_Q     : A -> value -> pred prog\n  }.\n\nImplicit Arguments sfs_t.\nImplicit Arguments sfs_P.\nImplicit Arguments sfs_Q.\n\nProgram Definition value_to_store_termMeas (vt:valueTermMeas) : termMeas :=\n  fun s n => match s#(V 0) with\n             | Some v => proj1_sig vt v n\n             | None   => False\n             end.\nNext Obligation.\n  destruct x; intuition. destruct o; intuition. destruct vt; simpl in *.\n  eauto.\nQed.\n\n(* Define a simple calling convention for \"standard\"\n   functions.  register 0 is for arguments and results.\n   registers 1 2 3 and 4 are callee-saves registers,\n   and registers >= 5 are caller-saves.\n\n   It is not specified, but register 1 is usually\n   used as a value stack.\n *)\nDefinition stdfun (l:label) (fs:{A:Type & stdFunspec A}) :=\n  funptr l (projT1 fs * (value*value*value*value))\n         (value_to_store_termMeas (sfs_t (projT2 fs)))\n         (fun avs =>\n           match avs with\n             (a,(v1,v2,v3,v4)) =>\n             EX v0:_,\n             world_op\n               (sfs_P (projT2 fs) a v0)\n               (fun s =>\n                 s#(V 0) = Some v0 /\\\n                 s#(V 1) = Some v1 /\\\n                 s#(V 2) = Some v2 /\\\n                 s#(V 3) = Some v3 /\\\n                 s#(V 4) = Some v4)\n           end)\n         (fun avs =>\n           match avs with\n             (a,(v1,v2,v3,v4)) =>\n             EX v0:_,\n             world_op\n                (sfs_Q (projT2 fs) a v0)\n                (fun s =>\n                  s#(V 0) = Some v0 /\\\n                  s#(V 1) = Some v1 /\\\n                  s#(V 2) = Some v2 /\\\n                  s#(V 3) = Some v3 /\\\n                  s#(V 4) = Some v4)\n           end).\n\nDefinition apply_P (fs:{ A:Type & stdFunspec A}) (x:projT1 fs) (v:value) : pred prog :=\n  match v with\n  | value_cons (value_label l) v' =>\n       stdfun l fs && sfs_P (projT2 fs) x v'\n  | _ => FF\n  end.\n\nDefinition apply_Q (fs:{A :Type & stdFunspec A}) (x:projT1 fs) (v:value) : pred prog :=\n  sfs_Q (projT2 fs) x v.\n\nProgram Definition apply_tm (fs:{A:Type & stdFunspec A}) : valueTermMeas :=\n  fun v n =>\n  match v, n with\n  | value_cons (value_label l) v', S n' =>\n      sfs_t (projT2 fs) v' n'\n  | _, _ => False\n  end.\nNext Obligation.\n  destruct v; intuition. destruct v1; intuition. destruct n; intuition. destruct n'; intuition.\n  destruct (sfs_t X); simpl in *. eauto.\nQed.\n\nDefinition apply_fs (fs:{A:Type & stdFunspec A}) : {A:Type & stdFunspec A} :=\n  existT _ (projT1 fs)\n     (Build_stdFunspec (projT1 fs) (apply_tm fs) (apply_P fs) (apply_Q fs)).\n\nProgram Definition phi : map instruction :=\n  set _ (set _ (set _ (set _ (set _ (set _ (empty _)\n\n  (* The \"map\" wrapper function *)\n  (L 5)\n    ( (* push the values of V2 and V3 *)\n      instr_cons (V 2) (V 1) (V 1) ;;\n      instr_cons (V 3) (V 1) (V 1) ;;\n      (* load the function pointer into V2 *)\n      instr_fetch_field (V 0) 0 (V 2) ;;\n      (* load the remainder of the list into V3 *)\n      instr_fetch_field (V 0) 1 (V 3) ;;\n      (* call the map worker function *)\n      instr_getlabel (L 4) (V 5) ;;\n      instr_call (V 5) ;;\n      (* restore V3 *)\n      instr_fetch_field (V 1) 0 (V 3) ;;\n      instr_fetch_field (V 1) 1 (V 1) ;;\n      (* restore V2 *)\n      instr_fetch_field (V 1) 0 (V 2) ;;\n      instr_fetch_field (V 1) 1 (V 1) ;;\n      instr_return\n    ))\n\n  (* The \"map\" worker function *)\n  (L 4)\n    ( instr_if_nil (V 3)\n       (*if nil, return nil *)\n        ( instr_getlabel (L 0) (V 0) ;;\n          instr_return )\n       (*otherwise, recursive call*)\n        ( (* get the head of the list *)\n          instr_fetch_field (V 3) 0 (V 0) ;;\n          (* call the mapping function *)\n          instr_call (V 2) ;;\n          (* push the mapped value *)\n          instr_cons (V 0) (V 1) (V 1) ;;\n          (* pop the head of the list *)\n          instr_fetch_field (V 3) 1 (V 3) ;;\n          (* recursive \"map\" call *)\n          instr_getlabel (L 4) (V 5) ;;\n          instr_call (V 5) ;;\n          (* add the new list head *)\n          instr_fetch_field (V 1) 0 (V 5) ;;\n          instr_cons (V 5) (V 0) (V 0) ;;\n          (* pop the stack *)\n          instr_fetch_field (V 1) 1 (V 1) ;;\n          instr_return\n         )\n       (* endif *)\n    ))\n\n  (* The \"succ\" function *)\n  (L 3)\n    ( instr_getlabel (L 0) (V 5) ;;\n      instr_cons (V 5) (V 0) (V 0) ;;\n      instr_return\n    ))\n\n  (* Set up a double-indirect call to succ.\n     Call apply, which indirectly calls apply to\n     call succ.\n  *)\n  (L 2)\n    ( instr_getlabel (L 0) (V 0) ;;\n      instr_getlabel (L 3) (V 1) ;;\n      instr_getlabel (L 0) (V 2) ;;\n      instr_getlabel (L 0) (V 3) ;;\n      instr_getlabel (L 0) (V 4) ;;\n      instr_cons (V 2) (V 0) (V 0) ;;\n      instr_cons (V 2) (V 0) (V 0) ;;\n      instr_cons (V 1) (V 0) (V 0) ;;\n      instr_getlabel (L 1) (V 1) ;;\n      instr_cons (V 1) (V 0) (V 0) ;;\n      instr_call (V 1) ;;\n      instr_return\n    ))\n\n  (* The \"apply\" function *)\n  (L 1)\n    ( instr_fetch_field (V 0) 0 (V 5) ;;\n      instr_fetch_field (V 0) 1 (V 0) ;;\n      instr_call (V 5) ;;\n      instr_return\n    ))\n\n  (* An addition function *)\n  (L 0)\n    ( instr_assert (EX nm:_, add_P nm) ;;\n      instr_if_nil (V 1)\n        (*then *) (\n          instr_return\n        ) (*else *) (\n          (instr_fetch_field (V 1) 0 (V 3) ;;\n          instr_fetch_field (V 1) 1 (V 1) ;;\n          instr_cons (V 3) (V 2) (V 2)) ;;\n          instr_getlabel (L 0) (V 0) ;;\n          (instr_call (V 0) ;;\n           instr_return)\n        )\n    ).\n\nProgram Definition succ_fs : stdFunspec nat :=\n  Build_stdFunspec nat\n    (fun _ n => n = 0)\n    (fun n v => !!(list_nat n v))\n    (fun n v => !!(list_nat (S n) v)).\n\nDefinition succ_fs' : {A:Type & stdFunspec A} :=\n  existT (fun X => stdFunspec X) nat succ_fs.\n\nLemma succ_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    (stdfun (L 3) succ_fs' && G).\nProof.\n  intros.\n  eapply verify_func_simple; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]].\n  intuition.\n  rewrite H7 in H5.\n  inv H5.\n  inv H3.\n  simpl in H0.\n  rewrite get_set_same.\n  rewrite get_set_other. 2: discriminate.\n  do 2 econstructor. intuition; eauto.\n  inv H3.\n  econstructor; split.\n  2: repeat split;\n    repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  simpl. auto.\nQed.\n\nSection map_tm.\n  Variable (f_tm : valueTermMeas).\n\n  Fixpoint map_inner_tm (v:value) : nat -> Prop :=\n    fun n =>\n    match v with\n      | value_label _ => n = 0\n      | value_cons v1 v2 =>\n          exists x1, exists x2,\n           proj1_sig f_tm v1 x1 /\\\n           map_inner_tm v2 x2  /\\\n           n = 1 + x1 + 1 + x2\n    end.\n\n  Lemma map_inner_tm_fun : forall v x1 x2,\n    map_inner_tm v x1 ->\n    map_inner_tm v x2 ->\n    x1 = x2.\n  Proof.\n    induction v; simpl; intros. congruence.\n    destruct H as [a1 [a2 [? [? ?]]]].\n    destruct H0 as [b1 [b2 [? [? ?]]]].\n    subst.\n    cut (a1 = b1 /\\ a2 = b2).\n    intuition congruence.\n    split; auto.\n    eapply (proj2_sig f_tm); eauto.\n  Qed.\nEnd map_tm.\n\nProgram Definition map_worker_tm (fs:{A:Type & stdFunspec A}) : termMeas :=\n  fun s n =>\n  match s#(V 3) with\n  | Some v => map_inner_tm (sfs_t (projT2 fs)) v n\n  | _ => False\n  end.\nNext Obligation.\n  destruct (x#4); intuition.\n  eapply map_inner_tm_fun; eauto.\nQed.\n\nProgram Definition map_tm (fs:{A:Type & stdFunspec A}) : valueTermMeas :=\n  fun v n =>\n  match v, n with\n  | value_cons _ v, S n'  =>\n     map_inner_tm (sfs_t (projT2 fs)) v n'\n  | _, _ => False\n  end.\nNext Obligation.\n  destruct v. elim H.\n  destruct n; destruct n'; try tauto.\n  f_equal.\n  eapply map_inner_tm_fun; eauto.\nQed.\n\nSection map_pre_post.\n  Variable A:Type.\n  Variable P:A->value->pred prog.\n\n  Fixpoint list_val_match (l:list A) (v:value) {struct l} : pred prog :=\n    match l, v with\n    | nil, value_label 1%positive => TT\n    | x::l', value_cons v1 v2 => P x v1 && list_val_match l' v2\n    | _, _ => FF\n    end.\nEnd map_pre_post.\n\nDefinition map_worker_pre (fs:{A:Type & stdFunspec A}) (x:value*label*list (projT1 fs)*value) :=\n  match x with\n    (v1,lab,l,v4) =>\n    EX v3:_,\n    world_op\n      (stdfun lab fs &&\n       list_val_match (projT1 fs) (sfs_P (projT2 fs)) l v3)\n      (fun s =>\n         s#(V 1) = Some v1 /\\\n         s#(V 2) = Some (value_label lab) /\\\n         s#(V 3) = Some v3 /\\\n         s#(V 4) = Some v4)\n  end.\n\nDefinition map_worker_post (fs:{A:Type & stdFunspec A}) (x:value*label*list (projT1 fs)*value) :=\n  match x with\n    (v1,lab,l,v4) =>\n    EX v0:_,\n    world_op\n      (stdfun lab fs &&\n        list_val_match (projT1 fs) (sfs_Q (projT2 fs)) l v0)\n      (fun s =>\n         s#(V 0) = Some v0 /\\\n         s#(V 1) = Some v1 /\\\n         s#(V 2) = Some (value_label lab) /\\\n         s#(V 4) = Some v4)\n  end.\n\nDefinition map_pre\n  (fs:{A:Type & stdFunspec A})\n  l\n  (x:value) :=\n  match x with\n  | value_cons (value_label lab) v =>\n      stdfun lab fs &&\n      list_val_match (projT1 fs) (sfs_P (projT2 fs)) l v\n  | _ => FF\n  end.\n\nDefinition map_post\n  (fs:{A:Type & stdFunspec A})\n  l\n  (x:value) :=\n  list_val_match (projT1 fs) (sfs_Q (projT2 fs)) l x.\n\nDefinition map_spec (fs:{A:Type & stdFunspec A}) : {A:Type & stdFunspec A} :=\n  existT (fun X => stdFunspec X) (list (projT1 fs))\n    (Build_stdFunspec _ (map_tm fs) (map_pre fs) (map_post fs)).\n\nLemma map_worker_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A},\n         funptr (L 4) _ (map_worker_tm fs) (map_worker_pre fs) (map_worker_post fs)) && G).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [[[v1 lab] l] v4].\n  clear H2. unfold map_worker_pre in H0.\n  destruct H0 as [v3 [[? ?] ?]].\n  intuition.\n  clear H.\n  econstructor. intuition.\n  eauto.\n  destruct l; simpl in H2; [ left | right ].\n  destruct v3; try (elim H2; fail).\n  destruct l; try (elim H2; fail).\n  split; auto.\n  intros. inv H.\n  unfold map_worker_post.\n  simpl. exists (value_label 1%positive).\n  intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  destruct v3; try (elim H2; fail).\n  destruct H2.\n  split. eauto.\n  do 2 econstructor; intuition.\n  eauto.\n  hnf in H5.\n  unfold map_worker_tm in H5.\n  simpl in H7.\n  rewrite H7 in H5. simpl in H5.\n  destruct H5 as [n0 [n1 [? [? ?]]]].\n  subst n.\n  exists (1+n0). exists (1+n1).\n  split. 2: omega.\n  inv H8.\n  do 5 econstructor; intuition.\n  exists n0.\n  econstructor.\n  intuition.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  2: apply H0.\n  simpl.\n  rewrite get_set_same; auto.\n  simpl.\n  instantiate (1:=(p0,(v1,(value_label lab),value_cons v3_1 v3_2,v4))).\n  simpl. econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  simpl in H12.\n  destruct a'.\n  hnf in H8. simpl in H8. subst.\n  destruct a'0.\n  rewrite worldNec_unfold in H11.\n  destruct H11; subst.\n  destruct H12; intuition.\n  do 2 econstructor; intuition; eauto.\n  inv H16.\n  do 2 econstructor. intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  inv H16. inv H18.\n  do 5 econstructor. exists n1.\n  exists (value_cons x v1,lab,l,v4).\n  intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  2: eapply pred_nec_hereditary; [ | apply H1 ]; auto.\n  unfold map_worker_tm. simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl. split.\n  econstructor; intuition; auto.\n  eapply pred_nec_hereditary; eauto.\n  eapply pred_nec_hereditary; eauto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  split. auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl.\n  exists n1. split. auto.\n  omega.\n  destruct a'. destruct a'0.\n  inv H16. rewrite worldNec_unfold in H18.\n  destruct H18; simpl in *; subst.\n  destruct H19 as [? [? ?] ?]; intuition.\n  do 2 econstructor; intuition; eauto.\n  inv H23.\n  do 2 econstructor; intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H23.\n  do 2 econstructor; intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H23.\n  exists (value_cons x x0); intuition.\n  split; auto.\n  eapply pred_nec_hereditary; eauto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\nQed.\n\nLemma map_verify : forall G,\n    verify_prog phi G ->\n    verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 5) (map_spec fs)) &&\n    ((ALL fs:{A:Type & stdFunspec A},\n         funptr (L 4) _ (map_worker_tm fs) (map_worker_pre fs) (map_worker_post fs))\n        && G)).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func.\n  simpl. auto.\n  2: apply map_worker_verify; auto.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]]. intuition.\n  rewrite H7 in H5.\n  clear H H2.\n  unfold map_pre in H0.\n  destruct v0; try (elim H0; fail).\n  destruct v0_1; try (elim H0; fail).\n  destruct H0.\n  do 2 econstructor; intuition; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2; inv H10.\n  simpl in H5.\n  destruct n; try tauto.\n  do 5 econstructor.\n  exists n.\n  exists (value_cons v3 (value_cons v2 v1),l,x,v4).\n  intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  unfold map_worker_tm. simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl. econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  destruct a'; destruct a'0.\n  rewrite worldNec_unfold in H10.\n  destruct H10; subst.\n  destruct H12 as [? [? ?] ?]; intuition.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  destruct H2. simpl in *; subst.\n  econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\nQed.\n\nLemma apply_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 1) (apply_fs fs)) && G).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]]. intuition.\n  rewrite H6 in H5.\n  unfold apply_tm in H5.\n  destruct v0; try tauto.\n  destruct v0_1; try tauto.\n  destruct n; try tauto.\n  do 2 econstructor.\n  intuition; eauto.\n  inv H9.\n  do 2 econstructor.\n  intuition; eauto.\n  rewrite get_set_other. 2: discriminate.\n  eauto.\n  inv H9.\n  do 5 econstructor.\n  exists n.\n  exists (x,(v1,v2,v3,v4)).\n  econstructor.\n  intuition.\n  destruct H0.\n  3: apply H0.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  simpl.\n  simpl. rewrite get_set_same. auto.\n  simpl.\n  destruct H0.\n  econstructor. split. eauto.\n  repeat split;\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  simpl. intros. auto.\nQed.\n\nLemma add_verify : forall G,\n  verify_prog phi G ->\n  verify_prog phi (funptr (L 0) _ add_term_measure add_P add_Q && G).\nProof.\n  intros. eapply verify_func_simple; auto.\n\nTransparent get set.\n  simpl. reflexivity.\n  intros.\nOpaque get set funptr.\n  intros. apply hoare_wp.\n  subst Pr Pr'. simpl.\n  intros [? ?].\n  destruct a as [n1 m1]; simpl in *.\n  simpl; intuition.\n  exists (n1,m1). simpl; split; auto.\n  intuition; subst; auto.\n  destruct H6.\n  hnf in H4, H6. simpl V in *.\n  case_eq (s#2); intros;\n    rewrite H8 in H4; try tauto.\n  case_eq (s#3); intros;\n    rewrite H9 in H6; try tauto.\n  unfold add_term_measure in H7.\n  simpl in H7; rewrite H8 in H7.\n  inv H7.\n  exists v; intuition.\n  destruct n1; simpl in H4;\n    destruct v; try tauto.\n  destruct l; try tauto.\n  left; simpl; intuition.\n  hnf. simpl. rewrite H9. auto.\n  destruct v1; try tauto.\n  destruct l; try tauto.\n  simpl in *.\n  right; simpl; intuition.\n  eauto.\n  do 2 econstructor; intuition.\n  inv H7.\n  do 2 econstructor; intuition.\n  rewrite get_set_other. 2: discriminate. eauto.\n  inv H7.\n  do 2 econstructor; intuition.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  eauto.\n  inv H7. inv H10.\n  exists (L 0). exists (nat * nat)%type.\n  exists add_term_measure.\n  do 2 econstructor.\n  exists (list_length v2).\n  exists (n1, S m1).\n  intuition.\n  rewrite get_set_same. auto.\n  unfold add_term_measure; simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  apply H2.\n  simpl; intuition.\n  split; hnf; simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  exists (list_length v2).\n  unfold add_term_measure. simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  destruct a' as [? ?].\n  inv H7. simpl in *.\n  destruct a'0 as [? ?].\n  intuition; subst.\n  apply worldNec_unfold in H10. destruct H10; subst.\n  hnf in H13. hnf.\n  simpl V in *.\n  destruct (s1#3).\n  replace (S n1 + m1) with (n1 + S m1) by omega. auto.\n  auto.\nQed.\n\nProgram Definition main_tm : termMeas :=\n  fun _ n => n = 5.\n\nLet PROG_G :=\n  (funptr (L 2) unit main_tm\n                     (fun _ => TT)\n                     (fun _ => store_op (fun r => exists v, r#(V 0) = Some v /\\ list_nat 3 v))) &&\n  ((stdfun (L 3) succ_fs') &&\n   ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 1) (apply_fs fs)) &&\n    ((funptr (L 0) _ add_term_measure add_P add_Q) && TT))).\n\nLemma main_verify :\n  verify_prog phi PROG_G.\nProof.\n  unfold PROG_G.\n  eapply verify_func_simple.\nTransparent get set.\n  simpl. reflexivity.\n  2: apply succ_verify.\n  2: apply apply_verify.\n  2: apply add_verify.\n  2: repeat intro; hnf; auto.\n  intros.\nOpaque get set funptr list_nat.\n  apply hoare_wp; subst.\n  simpl. intros [? ?]. subst Pr Pr'.\n  simpl; intuition.\n  inv H5.\n  inv H7; inv H9; inv H10; inv H11; inv H12.\n  clear H H0 H2 H8.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H. inv H0.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  do 5 econstructor.\n  exists 2.\n  evar (x1:value).\n  evar (x2:value).\n  evar (x3:value).\n  evar (x4:value).\n  exists (2,(x1,x2,x3,x4)).\n  subst x1 x2 x3 x4.\n  intuition.\n  2: apply (H4 (apply_fs succ_fs')).\n  simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  econstructor; split.\n  2: repeat split;\n   repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  unfold apply_P.\n  simpl. intuition.\nTransparent list_nat.\n  simpl. auto.\nOpaque list_nat.\n  simpl in H2.\n  destruct H2.\n  hnf in H. simpl in H. subst.\n  destruct a'0.\n  intuition.\n  exists x. split; auto.\nQed.\n\nLemma main_totally_correct :\n  forall r c,\n    phi#(L 2) = Some c ->\n    exists n', exists p', exists r',\n      stepstar (K.squash (n',phi)) p'\n        r ((c ;; instr_assert FF)::nil)\n        r' nil /\\\n        exists v, r'#(V 0) = Some v /\\ list_nat 3 v.\nProof.\n  intros.\n  generalize (verify_totally_correct PROG_G unit (fun _ => TT)\n    (fun _ => store_op (fun r => exists v, r#(V 0) = Some v /\\ list_nat 3 v))\n    phi (L 2) main_tm tt); intros.\n  spec H0. apply main_verify.\n  spec H0. unfold PROG_G. hnf; simpl; intuition.\n  spec H0 r. spec H0. intros; hnf. auto.\n  spec H0 5.\n  spec H0 c.\n  spec H0. simpl; auto.\n  spec H0. auto.\n  destruct H0 as [p' [r' [? ?]]].\n  econstructor.\n  exists p'. exists r'.\n  split; eauto.\n  destruct H1; auto.\nQed.\n\n(* For every store satisfying the addition precondition,\n   calling the addition function will halt with a store\n   satisfing the postcondition.\n *)\n\nTransparent list_nat.\nLemma addition_totally_correct :\n  forall r n m c,\n    add_P' n m r ->\n    phi#(L 0) = Some c ->\n    exists n', exists p', exists r',\n      stepstar (K.squash (n',phi)) p'\n        r ((c ;; instr_assert FF)::nil)\n        r' nil /\\\n      add_Q' n m r'.\nProof.\n  intros.\n  generalize (verify_totally_correct (funptr (L 0) _ add_term_measure add_P add_Q && TT) _ add_P add_Q phi (L 0) add_term_measure (n,m)); intros.\n  spec H1. apply add_verify.\n  repeat intro; hnf; auto.\n  spec H1. hnf; simpl; intuition.\n  spec H1 r. spec H1.\n  simpl; intuition.\n  spec H1 n c.\n  spec H1.\n  destruct H. simpl.\n  unfold list_nat_var in *.\n  simpl in *.\n  destruct (r#2); auto.\n\n  clear - H.\n  revert v H; induction n; simpl; intros;\n    destruct v; try tauto.\n  destruct v1; try tauto.\n  destruct l; try tauto.\n  simpl. f_equal. auto.\n  spec H1; auto.\n  destruct H1 as [p' [r' [? ?]]].\n  do 3 econstructor; split; eauto.\n  destruct H2; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/examples/funclistmach3/programs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1893235462914881}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\n\n\n(**\nCheck is_well_jump.\nis_well_jump\n     : int64 -> M bool\n*)\n\nSection Is_well_jump.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(nat:Type); (nat:Type); (int:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := is_well_jump.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_is_well_jump.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (nat_correct x))\n      (dcons (fun x => StateLess _ (nat_correct x))\n        (dcons (fun x => StateLess _ (sint32_correct x))\n          (DList.DNil _))).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x => StateLess _ (bool_correct x).\n\n  Instance correct_function_is_well_jump : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f. unfold is_well_jump.\n    correct_forward.\n\n    get_invariant _pc.\n    get_invariant _len.\n    get_invariant _ofs.\n    unfold eval_inv, nat_correct in c2, c3.\n    unfold eval_inv, sint32_correct in c4.\n    destruct c2 as (c2 & Hc2_range).\n    destruct c3 as (c3 & Hc3_range).\n    destruct c4 as (c4 & Hc4_range).\n    subst.\n\n    eexists.\n\n    split_and; auto.\n    {\n      unfold exec_expr. repeat\n      match goal with\n      | H: ?X = _ |- context [match ?X with _ => _ end] =>\n        rewrite H\n      end. simpl.\n      unfold Cop.sem_cmp; simpl.\n      unfold Cop.sem_binarith; simpl.\n      unfold Val.of_bool; simpl.\n      unfold Vtrue, Vfalse.\n      reflexivity.\n    }\n    unfold eval_inv, match_res, state.is_well_jump'.\n    unfold bool_correct, Val.of_bool.\n    unfold Int.cmpu.\n    match goal with\n    | |- context[if ?X then _ else _] =>\n      destruct X; reflexivity\n    end.\n    unfold Cop.sem_cast; simpl.\n    match goal with\n    | |- context[if ?X then _ else _] =>\n      destruct X; reflexivity\n    end.\n    intros.\n    match goal with\n    | |- Cop.val_casted (if ?X then _ else _) _ =>\n      destruct X; constructor; reflexivity\n    end.\n  Qed.\n\nEnd Is_well_jump.\n\nExisting  Instance correct_function_is_well_jump.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_is_well_jump.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.18922692504227262}}
{"text": "From iris.algebra Require Import base.\nFrom iris.program_logic Require Import language ectx_language ectxi_language.\nFrom stdpp Require Import gmap fin_maps list finite.\nFrom cap_machine Require Export addr_reg machine_base machine_parameters linking.\nFrom cap_machine.overlay Require Import base call.\n(* From Equations Require Import Equations. *)\n\nInductive ConfFlag : Type :=\n| Executable\n| Halted\n| Failed\n| NextI.\n\nDefinition Conf: Type := ConfFlag * ExecConf.\n\nDefinition updatePC (\u03c6: ExecConf): Conf :=\n  match RegLocate (reg \u03c6) PC with\n  | inr (Regular ((p, g), b, e, a)) =>\n    match (a + 1)%a with\n    | Some a' =>\n      match p with\n      | E | URWLX | URWX | URWL | URW => (Failed, \u03c6)\n      | _ => let \u03c6' := (update_reg \u03c6 PC (inr (Regular ((p, g), b, e, a')))) in (NextI, \u03c6')\n      end\n    | None => (Failed, \u03c6)\n    end\n  | inr (Stk d p b e a) =>\n    match (a + 1)%a with\n    | Some a' =>\n      match p with\n      | E | URWLX | URWX | URWL | URW => (Failed, \u03c6)\n      | _ => let \u03c6' := (update_reg \u03c6 PC (inr (Stk d p b e a'))) in\n                  (NextI, \u03c6')\n      end\n    | None => (Failed, \u03c6)\n    end\n  | _ => (Failed, \u03c6)\n  end.\n\nDefinition updatePcPerm (w: base.Word): base.Word :=\n  match w with\n  | inr (Regular ((E, g), b, e, a)) => inr (Regular ((RX, g), b, e, a))\n  | inr (Stk d E b e a) => inr (Stk d RX b e a)\n  | _ => w\n  end.\n\nFixpoint stack (d: nat) (cs: list Stackframe) :=\n  match cs with\n  | sf::cs => if nat_eq_dec d (length cs) then Some (snd sf) else stack d cs\n  | [] => None\n  end.\n\nDefinition nonZero (w: base.Word): bool :=\n  match w with\n  | inr _ => true\n  | inl n => Zneq_bool n 0\n  end.\n\nDefinition canReadUpTo (w: base.Word): Addr :=\n  match w with\n  | inl _ => za\n  | inr (Regular ((p, g), b, e, a)) => match p with\n                                      | O => za\n                                      | RO | RW | RWL | RX | RWX | RWLX | E => e\n                                      | URW | URWL | URWX | URWLX => a\n                                      end\n  | inr (Stk d p b e a) => match p with\n                          | O => za\n                          | RO | RW | RWL | RX | RWX | RWLX | E => e\n                          | URW | URWL | URWX | URWLX => a\n                          end\n  | inr (Ret b e a) => e\n  end.\n\nDefinition canStore (p: Perm) (a: Addr) (w: base.Word): bool :=\n  match w with\n  | inl _ => true\n  | inr (Regular ((_, g), _, _, _)) => match g with\n                                      | Global => true\n                                      | Local => pwl p\n                                      | Directed => pwl p && leb_addr (canReadUpTo w) a\n                                      end\n  | inr (Stk _ _ _ _ _) | inr (Ret _ _ _) => pwl p && leb_addr (canReadUpTo w) a\n  end.\n\nDefinition canStoreU (p: Perm) (a: Addr) (w: base.Word): bool :=\n  match w with\n  | inl _ => true\n  | inr (Regular ((_, g), _, _, _)) => match g with\n                                      | Global => true\n                                      | Local => pwlU p\n                                      | Directed => pwlU p && leb_addr (canReadUpTo w) a\n                                      end\n  | inr (Stk _ _ _ _ _) | inr (Ret _ _ _) => pwlU p && leb_addr (canReadUpTo w) a\n  end.\n\nDefinition isWithin (n1 n2 b e: Addr) : bool :=\n  ((b <=? n1) && (n2 <=? e))%a.\n\nInductive access_kind: Type :=\n| LoadU_access (b e a: Addr) (offs: Z): access_kind\n| StoreU_access (b e a: Addr) (offs: Z): access_kind.\n\nDefinition verify_access (a: access_kind): option Addr :=\n  match a with\n  | LoadU_access b e a offs =>\n    match (a + offs)%a with\n    | None => None\n    | Some a' => if Addr_le_dec b a' then\n                  if Addr_lt_dec a' a then\n                    if Addr_le_dec a e then\n                      Some a' else None else None else None\n    end\n  | StoreU_access b e a offs =>\n    match (a + offs)%a with\n    | None => None\n    | Some a' => if Addr_le_dec b a' then\n                  if Addr_le_dec a' a then\n                    if Addr_lt_dec a e then\n                      Some a' else None else None else None\n    end\n  end.\n\nDefinition z_of_argument (regs: base.Reg) (a: Z + RegName) : option Z :=\n  match a with\n  | inl z => Some z\n  | inr r =>\n    match regs !! r with\n    | Some (inl z) => Some z\n    | _ => None\n    end\n  end.\n\nInductive isCorrectPC: base.Word \u2192 Prop :=\n| isCorrectPC_intro:\n    forall p g (b e a : Addr),\n      (b <= a < e)%a \u2192\n      p = RX \\/ p = RWX \\/ p = RWLX \u2192\n      isCorrectPC (inr (Regular ((p, g), b, e, a)))\n| isCorrectPC_intro':\n    forall d p (b e a : Addr),\n      (b <= a < e)%a \u2192\n      p = RX \\/ p = RWX \\/ p = RWLX \u2192\n      isCorrectPC (inr (Stk d p b e a)).\n\nLemma isCorrectPC_dec:\n  forall w, { isCorrectPC w } + { not (isCorrectPC w) }.\nProof.\n  destruct w.\n  - right. red; intros H. inversion H.\n  - destruct c.\n    + destruct c as ((((p & g) & b) & e) & a).\n      case_eq (match p with RX | RWX | RWLX => true | _ => false end); intros.\n      * destruct (Addr_le_dec b a).\n        { destruct (Addr_lt_dec a e).\n          { left. econstructor; simpl; eauto. by auto.\n            destruct p; naive_solver. }\n          { right. red; intro HH. inversion HH; subst. solve_addr. } }\n        { right. red; intros HH; inversion HH; subst. solve_addr. }\n      * right. red; intros HH; inversion HH; subst. naive_solver.\n    + case_eq (match p with RX | RWX | RWLX => true | _ => false end); intros.\n      * destruct (Addr_le_dec a a1).\n        { destruct (Addr_lt_dec a1 a0).\n          { left. econstructor; simpl; eauto. by auto.\n            destruct p; naive_solver. }\n          { right. red; intro HH. inversion HH; subst. solve_addr. } }\n        { right. red; intros HH; inversion HH; subst. solve_addr. }\n      * right. red; intros HH; inversion HH; subst. naive_solver.\n    + right. red; intros H. inversion H.\nQed.\n\n(* TODO: move into stdpp_extra, already upstreamed to stdpp *)\nSection surjective_finite.\n  Context {A} `{Finite A, EqDecision B} (f : A \u2192 B).\n  Context `{!Surj (=) f}.\n\n  Program Instance surjective_finite: Finite B :=\n    {| enum := remove_dups (f <$> enum A) |}.\n  Next Obligation. apply NoDup_remove_dups. Qed.\n  Next Obligation.\n    intros. rewrite elem_of_remove_dups elem_of_list_fmap.\n    destruct (surj f x). eauto using elem_of_enum.\n  Qed.\nEnd surjective_finite.\n\nSection opsem.\n  Context `{MachineParameters}.\n\n  Definition exec (i: instr) (\u03c6: ExecConf): Conf :=\n    match i with\n    | Fail => (Failed, \u03c6)\n    | Halt => (Halted, \u03c6)\n    | Jmp r =>\n      match (RegLocate (reg \u03c6) r) with\n      | inr (Ret b e a) => match (callstack \u03c6) with\n                           | [] => (Failed, \u03c6)\n                           | ((reg', m') :: cs) => (NextI, (reg', mem \u03c6, m', cs))\n                           end\n      | _ => let \u03c6' := (update_reg \u03c6 PC (updatePcPerm (RegLocate (reg \u03c6) r))) in (NextI, \u03c6')\n      end\n    | Jnz r1 r2 =>\n      if nonZero (RegLocate (reg \u03c6) r2) then\n        match (RegLocate (reg \u03c6) r1) with\n        | inr (Ret b e a) => match (callstack \u03c6) with\n                             | [] => (Failed, \u03c6)\n                             | ((reg', m') :: cs) => (NextI, (reg', mem \u03c6, m', cs))\n                             end\n        | _ => let \u03c6' := (update_reg \u03c6 PC (updatePcPerm (RegLocate (reg \u03c6) r1))) in (NextI, \u03c6')\n        end\n      else updatePC \u03c6\n    | Load dst src =>\n      match RegLocate (reg \u03c6) src with\n      | inl n => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        (* Fails for U cap *)\n        if readAllowed p && withinBounds ((p, g), b, e, a) then updatePC (update_reg \u03c6 dst (MemLocate (mem \u03c6) a))\n        else (Failed, \u03c6)\n      | inr (Ret b e a) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        if readAllowed p && withinBounds ((p, Directed), b, e, a) then\n          match stack d ((reg \u03c6, stk \u03c6)::(callstack \u03c6)) with\n          | None => (Failed, \u03c6)\n          | Some m => updatePC (update_reg \u03c6 dst (MemLocate m a))\n          end\n        else (Failed, \u03c6)\n      end\n    | Store dst (inr src) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl n => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        (* Fails for U cap *)\n        if writeAllowed p && withinBounds ((p, g), b, e, a) && canStore p a (RegLocate (reg \u03c6) src) then\n          updatePC (update_mem \u03c6 a (RegLocate (reg \u03c6) src))\n        else (Failed, \u03c6)\n      | inr (Ret b e a) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        if writeAllowed p && withinBounds ((p, Directed), b, e, a) && canStore p a (RegLocate (reg \u03c6) src) then\n        if nat_eq_dec d (length (callstack \u03c6)) then\n          updatePC (update_stk \u03c6 a (RegLocate (reg \u03c6) src))\n        else match update_stack \u03c6 d a (RegLocate (reg \u03c6) src) with\n             | None => (Failed, \u03c6)\n             | Some \u03c6' => updatePC \u03c6'\n             end\n        else (Failed, \u03c6)\n      end\n    | Store dst (inl n) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl n => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        (* Fails for U cap *)\n        if writeAllowed p && withinBounds ((p, g), b, e, a) then updatePC (update_mem \u03c6 a (inl n)) else (Failed, \u03c6)\n      | inr (Ret b e a) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        if writeAllowed p && withinBounds ((p, Directed), b, e, a) then\n        if nat_eq_dec d (length (callstack \u03c6)) then\n          updatePC (update_stk \u03c6 a (inl n))\n        else match update_stack \u03c6 d a (inl n) with\n             | None => (Failed, \u03c6)\n             | Some \u03c6' => updatePC \u03c6'\n             end\n        else (Failed, \u03c6)\n      end\n    | Mov dst (inl n) => updatePC (update_reg \u03c6 dst (inl n))\n    | Mov dst (inr src) => updatePC (update_reg \u03c6 dst (RegLocate (reg \u03c6) src))\n    | Lea dst (inl n) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        (* Make sure that we can only decrease pointer for uninitialized capabilities *)\n        | URW | URWL | URWX | URWLX => match (a + n)%a with\n                                      | Some a' => if Addr_le_dec a' a then\n                                                    let c := Regular ((p, g), b, e, a') in\n                                                    updatePC (update_reg \u03c6 dst (inr c))\n                                                  else (Failed, \u03c6)\n                                      | None => (Failed, \u03c6)\n                                      end\n        | _ => match (a + n)%a with\n               | Some a' => let c := Regular ((p, g), b, e, a') in\n                            updatePC (update_reg \u03c6 dst (inr c))\n               | None => (Failed, \u03c6)\n               end\n        end\n      | inr (Ret b e a) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        (* Make sure that we can only decrease pointer for uninitialized capabilities *)\n        | URW | URWL | URWX | URWLX => match (a + n)%a with\n                                      | Some a' => if Addr_le_dec a' a then\n                                                    let c := Stk d p b e a' in\n                                                    updatePC (update_reg \u03c6 dst (inr c))\n                                                  else (Failed, \u03c6)\n                                      | None => (Failed, \u03c6)\n                                      end\n        | _ => match (a + n)%a with\n               | Some a' => let c := Stk d p b e a' in\n                            updatePC (update_reg \u03c6 dst (inr c))\n               | None => (Failed, \u03c6)\n               end\n        end\n      end\n    | Lea dst (inr r) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        (* Make sure that we can only decrease pointer for uninitialized capabilities *)\n        | URW | URWL | URWX | URWLX => match RegLocate (reg \u03c6) r with\n                                      | inr _ => (Failed, \u03c6)\n                                      | inl n => match (a + n)%a with\n                                                | Some a' => if Addr_le_dec a' a then\n                                                              let c := Regular ((p, g), b, e, a') in\n                                                              updatePC (update_reg \u03c6 dst (inr c))\n                                                            else (Failed, \u03c6)\n                                                | None => (Failed, \u03c6)\n                                                end\n                                      end\n        | _ => match RegLocate (reg \u03c6) r with\n              | inr _ => (Failed, \u03c6)\n              | inl n => match (a + n)%a with\n                        | Some a' => let c := Regular ((p, g), b, e, a') in\n                                    updatePC (update_reg \u03c6 dst (inr c))\n                        | None => (Failed, \u03c6)\n                        end\n              end\n        end\n      | inr (Ret b e a) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        (* Make sure that we can only decrease pointer for uninitialized capabilities *)\n        | URW | URWL | URWX | URWLX => match RegLocate (reg \u03c6) r with\n                                      | inr _ => (Failed, \u03c6)\n                                      | inl n => match (a + n)%a with\n                                                | Some a' => if Addr_le_dec a' a then\n                                                              let c := Stk d p b e a' in\n                                                              updatePC (update_reg \u03c6 dst (inr c))\n                                                            else (Failed, \u03c6)\n                                                | None => (Failed, \u03c6)\n                                                end\n                                      end\n        | _ => match RegLocate (reg \u03c6) r with\n              | inr _ => (Failed, \u03c6)\n              | inl n => match (a + n)%a with\n                        | Some a' => let c := Stk d p b e a' in\n                                    updatePC (update_reg \u03c6 dst (inr c))\n                        | None => (Failed, \u03c6)\n                        end\n              end\n        end\n      end\n    | Restrict dst (inl n) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular (permPair, b, e, a)) =>\n        match permPair with\n        | (E, _) => (Failed, \u03c6)\n        | _ => if PermPairFlowsTo (decodePermPair n) permPair then\n                updatePC (update_reg \u03c6 dst (inr (Regular (decodePermPair n, b, e, a))))\n              else (Failed, \u03c6)\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ => if PermPairFlowsTo (decodePermPair n) (p, Directed) then\n                                updatePC (update_reg \u03c6 dst (inr (Stk d (fst (decodePermPair n)) b e a)))\n              else (Failed, \u03c6)\n        end\n      end\n    | Restrict dst (inr r) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular (permPair, b, e, a)) =>\n        match RegLocate (reg \u03c6) r with\n        | inr _ => (Failed, \u03c6)\n        | inl n =>\n          match permPair with\n          | (E, _) => (Failed, \u03c6)\n          | _ => if PermPairFlowsTo (decodePermPair n) permPair then\n                  updatePC (update_reg \u03c6 dst (inr (Regular (decodePermPair n, b, e, a))))\n                else (Failed, \u03c6)\n          end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match RegLocate (reg \u03c6) r with\n        | inr _ => (Failed, \u03c6)\n        | inl n =>\n          match p with\n          | E => (Failed, \u03c6)\n          | _ => if PermPairFlowsTo (decodePermPair n) (p, Directed) then\n                  updatePC (update_reg \u03c6 dst (inr (Stk d (fst (decodePermPair n)) b e a)))\n                else (Failed, \u03c6)\n          end\n        end\n      end\n    | Add dst (inr r1) (inr r2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => match RegLocate (reg \u03c6) r2 with\n                 | inr _ => (Failed, \u03c6)\n                 | inl n2 => updatePC (update_reg \u03c6 dst (inl (n1 + n2)%Z))\n                 end\n      end\n    | Add dst (inl n1) (inr r2) =>\n      match RegLocate (reg \u03c6) r2 with\n      | inr _ => (Failed, \u03c6)\n      | inl n2 => updatePC (update_reg \u03c6 dst (inl (n1 + n2)%Z))\n      end\n    | Add dst (inr r1) (inl n2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => updatePC (update_reg \u03c6 dst (inl (n1 + n2)%Z))\n      end\n    | Add dst (inl n1) (inl n2) =>\n      updatePC (update_reg \u03c6 dst (inl (n1 + n2)%Z))\n    | Sub dst (inr r1) (inr r2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => match RegLocate (reg \u03c6) r2 with\n                 | inr _ => (Failed, \u03c6)\n                 | inl n2 => updatePC (update_reg \u03c6 dst (inl (n1 - n2)%Z))\n                 end\n      end\n    | Sub dst (inl n1) (inr r2) =>\n      match RegLocate (reg \u03c6) r2 with\n      | inr _ => (Failed, \u03c6)\n      | inl n2 => updatePC (update_reg \u03c6 dst (inl (n1 - n2)%Z))\n      end\n    | Sub dst (inr r1) (inl n2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => updatePC (update_reg \u03c6 dst (inl (n1 - n2)%Z))\n      end\n    | Sub dst (inl n1) (inl n2) =>\n      updatePC (update_reg \u03c6 dst (inl (n1 - n2)%Z))\n    | Lt dst (inr r1) (inr r2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => match RegLocate (reg \u03c6) r2 with\n                 | inr _ => (Failed, \u03c6)\n                 | inl n2 => updatePC (update_reg \u03c6 dst (inl (Z.b2z (Z.ltb n1 n2))))\n                 end\n      end\n    | Lt dst (inl n1) (inr r2) =>\n      match RegLocate (reg \u03c6) r2 with\n      | inr _ => (Failed, \u03c6)\n      | inl n2 => updatePC (update_reg \u03c6 dst (inl (Z.b2z (Z.ltb n1 n2))))\n      end\n    | Lt dst (inr r1) (inl n2) =>\n      match RegLocate (reg \u03c6) r1 with\n      | inr _ => (Failed, \u03c6)\n      | inl n1 => updatePC (update_reg \u03c6 dst (inl (Z.b2z (Z.ltb n1 n2))))\n      end\n    | Lt dst (inl n1) (inl n2) =>\n      updatePC (update_reg \u03c6 dst (inl (Z.b2z (Z.ltb n1 n2))))\n    | Subseg dst (inr r1) (inr r2) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r1 with\n          | inr _ => (Failed, \u03c6)\n          | inl n1 =>\n            match RegLocate (reg \u03c6) r2 with\n            | inr _ => (Failed, \u03c6)\n            | inl n2 =>\n              match z_to_addr n1, z_to_addr n2 with\n              | Some a1, Some a2 =>\n                if isWithin a1 a2 b e then\n                  updatePC (update_reg \u03c6 dst (inr (Regular ((p, g), a1, a2, a))))\n                else (Failed, \u03c6)\n              | _,_ => (Failed, \u03c6)\n              end\n            end\n          end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r1 with\n          | inr _ => (Failed, \u03c6)\n          | inl n1 =>\n            match RegLocate (reg \u03c6) r2 with\n            | inr _ => (Failed, \u03c6)\n            | inl n2 =>\n              match z_to_addr n1, z_to_addr n2 with\n              | Some a1, Some a2 =>\n                if isWithin a1 a2 b e then\n                  updatePC (update_reg \u03c6 dst (inr (Stk d p a1 a2 a)))\n                else (Failed, \u03c6)\n              | _,_ => (Failed, \u03c6)\n              end\n            end\n          end\n        end\n      end\n    | Subseg dst (inl n1) (inr r2) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r2 with\n          | inr _ => (Failed, \u03c6)\n          | inl n2 =>\n            match z_to_addr n1, z_to_addr n2 with\n            | Some a1, Some a2 =>\n              if isWithin a1 a2 b e then\n                updatePC (update_reg \u03c6 dst (inr (Regular ((p, g), a1, a2, a))))\n                     else (Failed, \u03c6)\n            | _,_ => (Failed, \u03c6)\n            end\n          end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r2 with\n          | inr _ => (Failed, \u03c6)\n          | inl n2 =>\n            match z_to_addr n1, z_to_addr n2 with\n            | Some a1, Some a2 =>\n              if isWithin a1 a2 b e then\n                updatePC (update_reg \u03c6 dst (inr (Stk d p a1 a2 a)))\n                     else (Failed, \u03c6)\n            | _,_ => (Failed, \u03c6)\n            end\n          end\n        end\n      end\n    | Subseg dst (inr r1) (inl n2) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r1 with\n          | inr _ => (Failed, \u03c6)\n          | inl n1 =>\n            match z_to_addr n1, z_to_addr n2 with\n            | Some a1, Some a2 =>\n              if isWithin a1 a2 b e then\n                updatePC (update_reg \u03c6 dst (inr (Regular ((p, g), a1, a2, a))))\n              else (Failed, \u03c6)\n            | _,_ => (Failed, \u03c6)\n            end\n          end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match RegLocate (reg \u03c6) r1 with\n          | inr _ => (Failed, \u03c6)\n          | inl n1 =>\n            match z_to_addr n1, z_to_addr n2 with\n            | Some a1, Some a2 =>\n              if isWithin a1 a2 b e then\n                updatePC (update_reg \u03c6 dst (inr (Stk d p a1 a2 a)))\n              else (Failed, \u03c6)\n            | _,_ => (Failed, \u03c6)\n            end\n          end\n        end\n      end\n    | Subseg dst (inl n1) (inl n2) =>\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match z_to_addr n1, z_to_addr n2 with\n          | Some a1, Some a2 =>\n            if isWithin a1 a2 b e then\n              updatePC (update_reg \u03c6 dst (inr (Regular ((p, g), a1, a2, a))))\n            else (Failed, \u03c6)\n          | _,_ => (Failed, \u03c6)\n          end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match p with\n        | E => (Failed, \u03c6)\n        | _ =>\n          match z_to_addr n1, z_to_addr n2 with\n          | Some a1, Some a2 =>\n            if isWithin a1 a2 b e then\n              updatePC (update_reg \u03c6 dst (inr (Stk d p a1 a2 a)))\n            else (Failed, \u03c6)\n          | _,_ => (Failed, \u03c6)\n          end\n        end\n      end\n    | GetA dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular (_, _, _, a)) | inr (Ret _ _ a) | inr (Stk _ _ _ _ a) =>\n        match a with\n        | A a' _ _ => updatePC (update_reg \u03c6 dst (inl a'))\n        end\n      end\n    | GetB dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular (_, b, _, _)) | inr (Ret b _ _) | inr (Stk _ _ b _ _) =>\n        match b with\n        | A b' _ _ => updatePC (update_reg \u03c6 dst (inl b'))\n        end\n      end\n    | GetE dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular (_, _, e, _)) | inr (Ret _ e _) | inr (Stk _ _ _ e _) =>\n        match e with\n        | A e' _ _ => updatePC (update_reg \u03c6 dst (inl e'))\n        end\n      end\n    | GetP dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, _), _, _, _))\n      | inr (Stk _ p _ _ _) =>\n        updatePC (update_reg \u03c6 dst (inl (encodePerm p)))\n      | inr (Ret _ _ _) =>\n        updatePC (update_reg \u03c6 dst (inl (encodePerm E)))\n      end\n    | GetL dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((_, g), _, _, _)) => updatePC (update_reg \u03c6 dst (inl (encodeLoc g)))\n      | inr (Stk _ _ _ _ _)\n      | inr (Ret _ _ _) =>\n        updatePC (update_reg \u03c6 dst (inl (encodeLoc Directed)))\n      end\n    | IsPtr dst r =>\n      match RegLocate (reg \u03c6) r with\n      | inl _ => updatePC (update_reg \u03c6 dst (inl 0%Z))\n      | inr _ => updatePC (update_reg \u03c6 dst (inl 1%Z))\n      end\n    | LoadU rdst rsrc offs =>\n      match RegLocate (reg \u03c6) rsrc with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        if isU p then\n          match z_of_argument (reg \u03c6) offs with\n          | None => (Failed, \u03c6)\n          | Some noffs => match verify_access (LoadU_access b e a noffs) with\n                         | None => (Failed, \u03c6)\n                         | Some a' => updatePC (update_reg \u03c6 rdst (MemLocate (mem \u03c6) a'))\n                         end\n          end\n        else (Failed, \u03c6)\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        if isU p then\n          match z_of_argument (reg \u03c6) offs with\n          | None => (Failed, \u03c6)\n          | Some noffs => match verify_access (LoadU_access b e a noffs) with\n                         | None => (Failed, \u03c6)\n                         | Some a' => match stack d ((reg \u03c6, stk \u03c6)::(callstack \u03c6)) with\n                                     | None => (Failed, \u03c6)\n                                     | Some m => updatePC (update_reg \u03c6 rdst (MemLocate m a'))\n                                     end\n                         end\n          end\n        else (Failed, \u03c6)\n      end\n    | StoreU dst offs src =>\n      let w := match src with\n               | inl n => inl n\n               | inr rsrc => (RegLocate (reg \u03c6) rsrc)\n               end in\n      match RegLocate (reg \u03c6) dst with\n      | inl _ => (Failed, \u03c6)\n      | inr (Regular ((p, g), b, e, a)) =>\n        match z_of_argument (reg \u03c6) offs with\n        | None => (Failed, \u03c6)\n        | Some noffs => match verify_access (StoreU_access b e a noffs) with\n                       | None => (Failed, \u03c6)\n                       | Some a' => if isU p && canStoreU p a' w then\n                                     if addr_eq_dec a a' then\n                                       match (a + 1)%a with\n                                       | Some a => updatePC (update_reg (update_mem \u03c6 a' w) dst (inr (Regular ((p, g), b, e, a))))\n                                       | None => (Failed, \u03c6)\n                                       end\n                                     else updatePC (update_mem \u03c6 a' w)\n                                   else (Failed, \u03c6)\n                       end\n        end\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        match z_of_argument (reg \u03c6) offs with\n        | None => (Failed, \u03c6)\n        | Some noffs => match verify_access (StoreU_access b e a noffs) with\n                       | None => (Failed, \u03c6)\n                       | Some a' => if isU p && canStoreU p a' w then\n                                     if addr_eq_dec a a' then\n                                       match (a + 1)%a with\n                                       | Some a =>\n                                         if nat_eq_dec d (length (callstack \u03c6)) then\n                                           updatePC (update_reg (update_stk \u03c6 a' w) dst (inr (Stk d p b e a)))\n                                         else match update_stack \u03c6 d a' w with\n                                              | None => (Failed, \u03c6)\n                                              | Some \u03c6' => updatePC (update_reg \u03c6' dst (inr (Stk d p b e a)))\n                                              end\n                                       | None => (Failed, \u03c6)\n                                       end\n                                     else if nat_eq_dec d (length (callstack \u03c6))\n                                         then\n                                           updatePC (update_stk \u03c6 a' w)\n                                         else match update_stack \u03c6 d a' w with\n                                              | None => (Failed, \u03c6)\n                                              | Some \u03c6' => updatePC \u03c6'\n                                              end\n                                   else (Failed, \u03c6)\n                       end\n        end\n      end\n    | PromoteU dst =>\n      match RegLocate (reg \u03c6) dst with\n      | inr (Regular ((p, g), b, e, a)) =>\n        if perm_eq_dec p E then (Failed, \u03c6)\n        else updatePC (update_reg \u03c6 dst (inr (Regular ((promote_perm p, g), b, min a e, a))))\n      | inr (Ret _ _ _) => (Failed, \u03c6)\n      | inr (Stk d p b e a) =>\n        if perm_eq_dec p E then (Failed, \u03c6)\n        else updatePC (update_reg \u03c6 dst (inr (Stk d (promote_perm p) b (min a e) a)))\n      | inl _ => (Failed, \u03c6)\n      end\n    end.\n\n  Definition clear_regs (reg: base.Reg) (l: list RegName) :=\n    foldr (fun r reg => <[r := inl 0%Z]> reg) reg l.\n\n  Fixpoint exec_instrs (l: list instr) (\u03c6: ExecConf): option ExecConf :=\n    match l with\n    | [] => Some \u03c6\n    | i::l => match exec i \u03c6 with\n              | (NextI, \u03c6) => exec_instrs l \u03c6\n              | _ => None\n              end\n    end.\n\n  Definition addPC (w: base.Word) (n: nat) :=\n    match w with\n    | inr (Regular (p, l, b, e, a)) =>\n      match (a + n)%a with\n      | Some a' => inr (Regular (p, l, b, e, a'))\n      | None => w\n      end\n    | inr (Stk d p b e a) =>\n      match (a + n)%a with\n      | Some a' => inr (Stk d p b e a')\n      | None => w\n      end\n    | _ => w\n    end.\n\n  (* Remove all words over some bounds *)\n  Fixpoint clear_stk_aux (m: base.Mem) (a: Addr) (n: nat) :=\n    match n with\n    | 0 => delete a m\n    | S n => match (a + 1)%a with\n             | None => delete a m\n             | Some a' => clear_stk_aux (delete a m) a' n\n             end\n    end.\n\n  Lemma clear_stk_aux_spec:\n    forall n m a,\n      (forall a' k, k <= n -> (a + k)%a = Some a' -> (clear_stk_aux m a n) !! a' = None) /\\\n      (forall a', (a' < a)%a -> (clear_stk_aux m a n) !! a' = m !! a').\n  Proof.\n    induction n; intros.\n    - split; intros.\n      + assert (k = 0) as -> by lia.\n        rewrite addr_add_0 in H1.\n        inversion H1. simpl. rewrite lookup_delete //.\n      + simpl. rewrite lookup_delete_ne //. solve_addr.\n    - split; intros.\n      + destruct (nat_eq_dec k (S n)).\n        * subst k. simpl. generalize (incr_addr_spec a 1).\n          intros [[a'' [HA [HB [HC HD]]]] | [HA HB]].\n          { rewrite HA. assert ((a'' + n)%a = Some a') by solve_addr.\n            destruct (IHn (delete a m) a'') as [X Y].\n            eapply (X a' n ltac:(lia) H2). }\n          { exfalso. solve_addr. }\n        * simpl. destruct (a + 1)%a as [a''|] eqn:Ha''.\n          { destruct (nat_eq_dec k 0).\n            - subst k. rewrite addr_add_0 in H1. inversion H1.\n              subst a'. destruct (IHn (delete a m) a'') as [X Y].\n              rewrite (Y a ltac:(solve_addr)).\n              rewrite lookup_delete //.\n            - destruct (IHn (delete a m) a'') as [X Y].\n              rewrite (X a' (k - 1) ltac:(lia) ltac:(solve_addr)) //. }\n          { assert (k = 0) as -> by solve_addr.\n            rewrite addr_add_0 in H1; inversion H1; subst a'.\n            rewrite lookup_delete //. }\n      + simpl. destruct (a + 1)%a as [a''|] eqn:Ha''.\n        * destruct (IHn (delete a m) a'') as [X Y].\n          rewrite (Y a' ltac:(solve_addr)).\n          rewrite lookup_delete_ne //. solve_addr.\n        * rewrite lookup_delete_ne //. solve_addr.\n  Qed.\n\n  Definition clear_stk (m: base.Mem) (a: Addr) :=\n    clear_stk_aux m a (Z.to_nat MemNum).\n\n  Lemma clear_stk_spec:\n    forall m a,\n      (forall a', (a <= a')%a -> (clear_stk m a) !! a' = None) /\\\n      (forall a', (a' < a)%a -> (clear_stk m a) !! a' = m !! a').\n  Proof.\n    intros.\n    generalize (clear_stk_aux_spec (Z.to_nat MemNum) m a). intros [A B].\n    split; intros.\n    - assert ((a + (a' - a)%Z)%a = Some a') by solve_addr.\n      assert (Z.to_nat (a' - a)%Z <= (Z.to_nat MemNum)) by solve_addr.\n      eapply A; eauto. solve_addr.\n    - eapply B; eauto.\n  Qed.\n\n  Definition decodeInstrW' (w: base.Word) :=\n    match w with\n    | inl n => decodeInstrW (inl n)\n    | inr _ => Fail\n    end.\n\n  (* Definition measure (w: base.Word): nat := *)\n  (*   match w with *)\n  (*   | inr (Stk d p b e a) => Z.to_nat (canReadUpTo w) *)\n  (*   | _ => 0 *)\n  (*   end. *)\n\n  (* Inductive legal: list Stackframe -> Prop := *)\n  (* | legal_nil: *)\n  (*     legal [] *)\n  (* | legal_cons: *)\n  (*     forall reg stk cs *)\n  (*     (Hcons_legal: map_Forall (fun a w => canReadUpTo w <= a)%a stk) *)\n  (*     (Hlegal: legal cs), *)\n  (*     legal ((reg, stk)::cs). *)\n\n  (* Lemma is_legal_dec cs: *)\n  (*   Decision (legal cs). *)\n  (* Proof. *)\n  (*   induction cs. *)\n  (*   - left; constructor. *)\n  (*   - destruct IHcs. *)\n  (*     + destruct a as [reg stk]. *)\n  (*       assert (forall a w, Decision ((fun a w => canReadUpTo w <= a)%a a w)). *)\n  (*       { intros. apply (Addr_le_dec (canReadUpTo w) a). } *)\n  (*       destruct (map_Forall_dec (fun a w => canReadUpTo w <= a)%a stk). *)\n  (*       * left; econstructor; eauto. *)\n  (*       * right. intro Y. inversion Y; subst; clear Y. *)\n  (*         apply n; auto. *)\n  (*     + right. intro Y. apply n. inversion Y; auto. *)\n  (* Qed. *)\n\n  (* Fixpoint region_addrs_aux (b: Addr) (n: nat): list Addr := *)\n  (*   match n with *)\n  (*   | 0 => nil *)\n  (*   | S n => b :: (region_addrs_aux (^(b + 1)%a) n) *)\n  (*   end. *)\n\n  (* Definition region_size : Addr \u2192 Addr \u2192 nat := *)\n  (*   \u03bb b e, Z.to_nat (e - b). *)\n\n  (* Definition region_addrs (b e: Addr): list Addr := *)\n  (*   region_addrs_aux b (region_size b e). *)\n\n  (* Equations is_safe_generalized (cs: list Stackframe) (w: base.Word): bool by wf (measure w) lt := *)\n  (* is_safe_generalized cs (inr (Stk d p b e a)) := *)\n  (*   if is_legal_dec cs then *)\n  (*     if nat_eq_dec d (length cs) then true *)\n  (*     else match cs !! d with *)\n  (*          | None => false *)\n  (*          | Some (reg, stk) => *)\n  (*            match reg !! r_stk with *)\n  (*            | Some (inr (Stk d' p' b' e' a')) => *)\n  (*              if Addr_lt_dec e a' then *)\n  (*                foldl (fun b a => match stk !! a with | Some w => b && (is_safe_generalized cs w) | _ => false end) true (region_addrs b (addr_reg.min e (canReadUpTo (inr (Stk d p b e a))))) *)\n  (*              else false *)\n  (*            | _ => false *)\n  (*            end *)\n  (*          end *)\n  (*   else false; *)\n  (* is_safe_generalized _ _ := true. *)\n  (* Next Obligation. *)\n  (* (* (* Cannot prove the obligation because Coq forgets that w is within (region_addrs b (addr_reg.min e (canReadUpTo w))) *) *) *)\n\n  Definition is_safe (w: base.Word): Prop :=\n    match w with\n    | inl _ => True\n    | inr (Stk d p b e a) => False\n    | inr (Ret b e a) => False\n    | inr (Regular _) => True\n    end.\n\n  Lemma is_safe_dec:\n    forall w, Decision (is_safe w).\n  Proof.\n    destruct w.\n    - left; simpl; auto.\n    - destruct c.\n      + left; simpl; auto.\n      + right; simpl; auto.\n      + right; simpl; auto.\n  Qed.\n\n  Definition is_call (regs: base.Reg) rf rargs (m: base.Mem) a e: Prop :=\n    exists a',\n      PC \u2209 rf::rargs /\\\n      r_stk \u2209 rf::rargs /\\\n      (R 0 eq_refl) \u2209 rf::rargs /\\\n      (R 1 eq_refl) \u2209 rf::rargs /\\\n      (R 2 eq_refl) \u2209 rf::rargs /\\\n      (a + (141 + length rargs))%a = Some a' /\\\n      (a' < e)%a /\\\n      (forall i, (i < (141 + length rargs))%nat ->\n            exists a_i, (a + i)%a = Some a_i /\\ (call_instrs rf rargs) !! i = m !! a_i) /\\\n      (forall r, r \u2208 rf::rargs -> is_safe (regs !r! r)).\n\n  Lemma is_call_determ:\n    forall regs rf1 rf2 rargs1 rargs2 m a e,\n    is_call regs rf1 rargs1 m a e ->\n    is_call regs rf2 rargs2 m a e ->\n    rf1 = rf2 /\\ rargs1 = rargs2.\n  Proof.\n    Local Opaque app. (* Hack so Qed terminates *)\n    intros. destruct H0 as [a' [HA1 [HA2 [HA3 [HA4 [HA5 [HA6 [HA7 [HA8 HA9]]]]]]]]].\n    destruct H1 as [a'' [HB1 [HB2 [HB3 [HB4 [HB5 [HB6 [HB7 [HB8 HB9]]]]]]]]].\n    eapply not_elem_of_cons in HA1. destruct HA1 as [HA1 HA1'].\n    eapply not_elem_of_cons in HA2. destruct HA2 as [HA2 HA2'].\n    eapply not_elem_of_cons in HB1. destruct HB1 as [HB1 HB1'].\n    eapply not_elem_of_cons in HB2. destruct HB2 as [HB2 HB2'].\n    assert (Hleneq: length rargs1 = length rargs2).\n    { destruct (HA8 100 ltac:(lia)) as [a_i [Ha_i Hinstr]].\n      destruct (HB8 100 ltac:(lia)) as [a_i' [Ha_i' Hinstr']].\n      rewrite Ha_i' in Ha_i; inversion Ha_i; subst.\n      unfold call_instrs in Hinstr, Hinstr'.\n      rewrite (@lookup_app_l (base.Word) (call_instrs_prologue rargs1) _ 100) in Hinstr; [|rewrite call_instrs_prologue_length; lia].\n      rewrite lookup_app_l in Hinstr'; [|rewrite call_instrs_prologue_length; lia].\n      rewrite /call_instrs_prologue lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite /= lookup_app_r in Hinstr; [|rewrite push_env_instrs_length; lia].\n      rewrite /= lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite /= lookup_app_r in Hinstr; [|rewrite push_instrs_length !app_length map_length pop_env_instrs_length /=; lia].\n      rewrite push_instrs_length !app_length map_length pop_env_instrs_length /= in Hinstr.\n      rewrite lookup_app_l /= in Hinstr; [|simpl; lia].\n      rewrite /call_instrs_prologue lookup_app_r in Hinstr'; [|simpl; lia].\n      rewrite /= lookup_app_r in Hinstr'; [|rewrite push_env_instrs_length; lia].\n      rewrite /= lookup_app_r in Hinstr'; [|simpl; lia].\n      rewrite /= lookup_app_r in Hinstr'; [|rewrite push_instrs_length !app_length map_length pop_env_instrs_length /=; lia].\n      rewrite push_instrs_length !app_length map_length pop_env_instrs_length /= in Hinstr'.\n      rewrite lookup_app_l /= in Hinstr'; [|simpl; lia].\n      rewrite -Hinstr' in Hinstr. inversion Hinstr.\n      eapply encode_instr_inj in H1. inversion H1. lia. }\n    split.\n    { destruct (HA8 (140 + length rargs1) ltac:(lia)) as [a_i [Ha_i Hinstr]].\n      destruct (HB8 (140 + length rargs1) ltac:(lia)) as [a_i' [Ha_i' Hinstr']].\n      rewrite Ha_i' in Ha_i; inversion Ha_i; subst.\n      rewrite /call_instrs in Hinstr, Hinstr'.\n      rewrite lookup_app_r in Hinstr; [|rewrite call_instrs_prologue_length; lia].\n      rewrite lookup_app_r in Hinstr'; [|rewrite call_instrs_prologue_length; lia].\n      rewrite call_instrs_prologue_length lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite lookup_app_r in Hinstr; [|simpl; lia].\n      simpl length in Hinstr.\n      rewrite lookup_app_r in Hinstr; [|rewrite push_instrs_length /=; lia].\n      rewrite push_instrs_length in Hinstr. simpl length in Hinstr.\n      rewrite lookup_app_r in Hinstr; [|rewrite push_instrs_length map_length; lia].\n      rewrite lookup_app_r in Hinstr; [|rewrite rclear_instrs_length all_registers_list_difference_length // push_instrs_length map_length; lia].\n      rewrite rclear_instrs_length all_registers_list_difference_length // push_instrs_length map_length in Hinstr.\n      rewrite call_instrs_prologue_length lookup_app_r in Hinstr'; [|simpl; lia].\n      rewrite lookup_app_r in Hinstr'; [|simpl; lia].\n      simpl length in Hinstr'.\n      rewrite lookup_app_r in Hinstr'; [|rewrite push_instrs_length /=; lia].\n      rewrite push_instrs_length in Hinstr'. simpl length in Hinstr'.\n      rewrite lookup_app_r in Hinstr'; [|rewrite push_instrs_length map_length; lia].\n      rewrite lookup_app_r in Hinstr'; [|rewrite rclear_instrs_length all_registers_list_difference_length // push_instrs_length map_length; lia].\n      rewrite rclear_instrs_length all_registers_list_difference_length // push_instrs_length map_length in Hinstr'.\n      replace (140 + length rargs1 - 102 - 4 - 3 - 1 - length rargs1 - 30) with 0 in Hinstr by lia.\n      replace (140 + length rargs1 - 102 - 4 - 3 - 1 - length rargs2 - 30) with 0 in Hinstr' by lia.\n      simpl in Hinstr, Hinstr'. rewrite -Hinstr' in Hinstr. inversion Hinstr.\n      eapply encode_instr_inj in H1. inversion H1; auto. }\n    destruct (nat_eq_dec (length rargs1) 0).\n    { eapply nil_length_inv in e0. subst rargs1.\n      destruct rargs2; auto. simpl in Hleneq. inversion Hleneq. }\n    assert (Hpush_regs_eq: forall i, i < length rargs1 -> (push_instrs (map (fun r => inr r) rargs1)) !! i = (push_instrs (map (fun r => inr r) rargs2)) !! i).\n    { intros. destruct (HA8 (110 + i) ltac:(lia)) as [a_i [Ha_i Hinstr]].\n      destruct (HB8 (110 + i) ltac:(lia)) as [a_i' [Ha_i' Hinstr']].\n      rewrite Ha_i' in Ha_i; inversion Ha_i; subst.\n      rewrite /call_instrs in Hinstr, Hinstr'.\n      rewrite lookup_app_r in Hinstr; [|rewrite call_instrs_prologue_length; lia].\n      rewrite lookup_app_r in Hinstr'; [|rewrite call_instrs_prologue_length; lia].\n      rewrite call_instrs_prologue_length in Hinstr.\n      rewrite call_instrs_prologue_length in Hinstr'.\n      rewrite lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite lookup_app_r in Hinstr'; [|simpl; lia].\n      simpl length in Hinstr, Hinstr'.\n      rewrite lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite lookup_app_r in Hinstr'; [|simpl; lia].\n      simpl length in Hinstr, Hinstr'.\n      rewrite lookup_app_r in Hinstr; [|simpl; lia].\n      rewrite lookup_app_r in Hinstr'; [|simpl; lia].\n      simpl length in Hinstr, Hinstr'.\n      rewrite lookup_app_l in Hinstr; [|rewrite push_instrs_length map_length; lia].\n      rewrite lookup_app_l in Hinstr'; [|rewrite push_instrs_length map_length; lia].\n      replace (110 + i - 102 - 4 - 3 - 1) with i in Hinstr by lia.\n      replace (110 + i - 102 - 4 - 3 - 1) with i in Hinstr' by lia.\n      rewrite -Hinstr' in Hinstr; inversion Hinstr. auto. }\n    assert (Hpush_regs_eq': push_instrs (map (\u03bb r : RegName, inr r) rargs1) = push_instrs (map (\u03bb r : RegName, inr r) rargs2)).\n    { eapply list_eq_same_length; [eauto|rewrite !push_instrs_length !map_length //|].\n      rewrite push_instrs_length map_length -Hleneq. intros.\n      rewrite (Hpush_regs_eq _ H0) in H1. rewrite H1 in H2; inversion H2; auto. }\n    clear Hpush_regs_eq. eapply push_instrs_inj in Hpush_regs_eq'.\n    eapply fmap_inj in Hpush_regs_eq'; auto.\n    inversion 1; auto.\n  Qed.\n\n  (* Pushing a list of words starting at address a *)\n  Definition push_words (stk: base.Mem) (a: Addr) (ws: list base.Word) :=\n    match (foldl (fun oastk w => match oastk with None => None | Some (a, stk) => if canStoreU URWLX a w then Some (^(a + 1)%a, <[a:=w]> stk) else None end) (Some (a, stk)) ws) with\n    | Some (_, stk) => Some stk\n    | None => None\n    end.\n\n  Definition exec_call (\u03c6: ExecConf) (rf: RegName) (rargs: list RegName) pcp pcg (pcb pce pca: Addr): Conf :=\n    match pcg with\n    | Directed => (Failed, \u03c6) (* Can't store PC if it's monotone because we currently assume heap is above stack *)\n    | _ =>\n    match (reg \u03c6) !r! r_stk with\n    | inr (Stk d URWLX b e a) =>\n      if (Addr_lt_dec b a) then\n      (* We know that d = length (callstack \u03c6) *)\n      match (a + (100 + length rargs))%a with\n      | Some a' => match (pca + (length (call_instrs rf rargs)))%a with\n                   | Some pca' =>\n                     if (Addr_le_dec a' e) then\n                     let saved_regs := <[PC := inr (Regular (pcp, pcg, pcb, pce, pca'))]> (<[r_stk := inr (Stk d URWLX b e ^(a + 1)%a)]> (reg \u03c6)) in\n                     match push_words (stk \u03c6) a ([inr (Regular (pcp, pcg, pcb, pce, ^(pca' + -1)%a))] ++ (map (fun r => ((reg \u03c6) !r! r)) (list_difference all_registers [PC; r_stk])) ++ [inr (Stk d URWLX b e ^(a + 32)%a)] ++ ([inl (encodeInstr (Mov (R 1 eq_refl) (inr PC))); inl (encodeInstr (Lea (R 1 eq_refl) (inl (- 1)%Z))); inl (encodeInstr (Load r_stk (R 1 eq_refl)))] ++ List.map inl pop_env_instrs ++ [inl (encodeInstr (LoadU PC r_stk (inl (- 1)%Z)))])) with\n                     | Some saved_stk =>\n                       match push_words \u2205 ^(a + 99)%a ([inr (Ret b ^(a + 99)%a ^(a + 33)%a)] ++ (map (fun r => ((reg \u03c6) !r! r)) rargs)) with\n                       | Some new_stk => (NextI, (<[PC := updatePcPerm ((reg \u03c6 !r! rf))]> (<[r_stk := inr (Stk (d + 1) URWLX ^(a + 99)%a e ^(a + (100 + length rargs))%a)]> (<[rf := (reg \u03c6) !r! rf]> (gset_to_gmap (inl 0%Z) (list_to_set all_registers)))), mem \u03c6, new_stk, (saved_regs, clear_stk saved_stk ^(a + 99)%a)::callstack \u03c6))\n                       | None => (Failed, \u03c6)\n                       end\n                     | None => (Failed, \u03c6)\n                     end\n                     else (Failed, \u03c6)\n                   | None => (Failed, \u03c6)\n                   end\n      | None => (Failed, \u03c6) (* Not enough space to push everything on the stack *)\n      end\n      else (Failed, \u03c6)\n    | _ =>\n      (* Won't be able to store the return capability if not URWLX *)\n      (Failed, \u03c6)\n    end\n    end.\n\n  Definition depth_of (w: base.Word): option nat :=\n    match w with\n    | inr (Stk d _ _ _ _) => Some d\n    | _ => None\n    end.\n\n  Inductive step: Conf \u2192 Conf \u2192 Prop :=\n  | step_exec_fail:\n      forall \u03c6,\n        not (isCorrectPC ((reg \u03c6) !r! PC)) \u2192\n        step (Executable, \u03c6) (Failed, \u03c6)\n  | step_exec_fail': (* This should never happen *)\n      forall \u03c6 d p b e a,\n        RegLocate (reg \u03c6) PC = inr (Stk d p b e a) ->\n        stack d ((reg \u03c6, stk \u03c6)::(callstack \u03c6)) = None ->\n        step (Executable, \u03c6) (Failed, \u03c6)\n  | step_exec_instr:\n      forall \u03c6 p g b e a i c,\n        RegLocate (reg \u03c6) PC = inr (Regular ((p, g), b, e, a)) ->\n        isCorrectPC ((reg \u03c6) !r! PC) \u2192\n        decodeInstrW' ((mem \u03c6) !m! a) = i \u2192\n        exec i \u03c6 = c \u2192\n        (~ exists rf rargs, is_call (reg \u03c6) rf rargs (mem \u03c6) a e /\\ (exec_call \u03c6 rf rargs p g b e a).1 = NextI) \\/ (match depth_of ((reg \u03c6) !r! r_stk) with Some d => d <> length (callstack \u03c6) | None => True end) ->\n        step (Executable, \u03c6) (c.1, c.2)\n  | step_exec_instr':\n      forall \u03c6 d p b e a i c m,\n        RegLocate (reg \u03c6) PC = inr (Stk d p b e a) ->\n        isCorrectPC ((reg \u03c6) !r! PC) \u2192\n        stack d ((reg \u03c6, stk \u03c6)::(callstack \u03c6)) = Some m ->\n        decodeInstrW' (m !m! a) = i \u2192\n        exec i \u03c6 = c \u2192\n        step (Executable, \u03c6) (c.1, c.2)\n  | step_exec_call:\n      forall \u03c6 p g b e a \u03c6' rf rargs,\n        RegLocate (reg \u03c6) PC = inr (Regular ((p, g), b, e, a)) ->\n        isCorrectPC ((reg \u03c6) !r! PC) \u2192\n        is_call (reg \u03c6) rf rargs (mem \u03c6) a e ->\n        depth_of ((reg \u03c6) !r! r_stk) = Some (length (callstack \u03c6)) ->\n        exec_call \u03c6 rf rargs p g b e a  = (NextI, \u03c6') ->\n        step (Executable, \u03c6) (NextI, \u03c6').\n\n  (* TODO: move into stdpp_extra and maybe upstream *)\n  Global Instance lists_finite {A} `{Finite A} n:\n    Finite { l : list A | length l <=? n = true }.\n  Proof.\n    induction n.\n    - refine {| enum := [[]\u21beeq_refl]; NoDup_enum := _; elem_of_enum := _ |}.\n      + repeat econstructor. intro. inversion H1.\n      + intros. destruct x. destruct x.\n        * apply elem_of_list_singleton. by apply (sig_eq_pi _).\n        * simpl in e. inversion e.\n    - assert (Hf1: forall (l: list A), (length l <=? n) = true -> (length l <=? S n) = true) by (intros l Hl; erewrite Nat.leb_le in Hl; rewrite Nat.leb_le; lia).\n      assert (Hf2: forall (l: list A), length l = S n -> (length l <=? S n) = true) by (intros; rewrite Nat.leb_le; lia).\n      set (f := fun (x: sum {l : list A | (length l <=? n) = true} {l : list A | length l = S n}) => match x return {l : list A | (length l <=? S n) = true} with | inl (l \u21be p) => l \u21be (Hf1 l p) | inr (l \u21be p) => l \u21be (Hf2 l p) end).\n      eapply @surjective_finite with (f := f).\n      + eapply sum_finite.\n      + intro y. destruct y as [l Hl].\n        destruct (Nat.eq_dec (length l) (S n)).\n        * exists (inr (l \u21be e)). simpl. by apply (sig_eq_pi _).\n        * generalize (proj1 (Nat.leb_le _ _) Hl); intros Hl'.\n          assert (Hl'': length l <= n) by lia.\n          exists (inl (l \u21be (proj2 (Nat.leb_le _ _) Hl''))).\n          simpl. by apply (sig_eq_pi _).\n  Qed.\n\n  (* TODO: move into stdpp_extra and maybe upstream *)\n  Lemma sig_exists_dec {A} {P Q: A -> Prop} `{Finite { x : A | Q x }}:\n    (forall x, P x -> Q x) ->\n    (\u2200 x : A, Decision (P x)) ->\n    Decision (\u2203 x : A, P x).\n  Proof.\n    intros. generalize (exists_dec (fun x => P (proj1_sig x))).\n    intros. destruct H2.\n    - left. destruct e. eauto.\n    - right. intro. eapply n.\n      destruct H2. generalize (H1 _ H2). intros.\n      exists (exist _ x H3). simpl. auto.\n  Qed.\n\n  Lemma is_call_dec:\n    forall regs m a e,\n      Decision (exists rf rargs, is_call regs rf rargs m a e).\n  Proof.\n    intros. eapply exists_dec. intros rf.\n    eapply @sig_exists_dec with (Q := fun l => length l <=? Z.to_nat (e - a)%Z = true).\n    - eapply _.\n    - intros. destruct H0 as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n      revert HD HE. clear. intros HD HE.\n      eapply Nat.leb_le. solve_addr.\n    - intros rargs. destruct (elem_of_list_dec PC (rf::rargs)).\n      { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n        eapply HPC; auto. }\n      destruct (elem_of_list_dec r_stk (rf::rargs)).\n      { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n        eapply Hstk; auto. }\n      eapply not_elem_of_cons in n; destruct n as [n Hn].\n      eapply not_elem_of_cons in n0; destruct n0 as [n0 Hn0].\n      destruct (elem_of_list_dec (R 0 eq_refl) (rf::rargs)).\n      { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n        eapply HA; auto. }\n      destruct (elem_of_list_dec (R 1 eq_refl) (rf::rargs)).\n      { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n        eapply HB; auto. }\n      destruct (elem_of_list_dec (R 2 eq_refl) (rf::rargs)).\n      { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n        eapply HC; auto. }\n      destruct ((a + (141 + length rargs))%a) as [a'|] eqn:Ha'.\n      2: { right. intro X. destruct X as [a' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n           congruence. }\n      destruct (Addr_lt_dec a' e).\n      2: { right. intro X. destruct X as [a'' [HPC [Hstk [HA [HB [HC [HD [HE HF]]]]]]]].\n           rewrite HD in Ha'; inversion Ha'; subst.\n           eapply n4; auto. }\n      assert (Decision (\u2200 (i : fin (141 + length rargs)), \u2203 a_i : Addr, (a + fin_to_nat i)%a = Some a_i \u2227 call_instrs rf rargs !! (fin_to_nat i) = m !! a_i)).\n      { eapply forall_dec. intros. destruct (a + x)%a as [a_i|] eqn:Ha_i.\n        - case_eq ((call_instrs rf rargs) !! (fin_to_nat x)); intros.\n          + destruct (m !! a_i) as [w'|] eqn:Hw'.\n            * destruct (base.word_eq_dec w w').\n              { subst w; left; eauto. }\n              { right. intros [a_i' [A B]].\n                inversion A; subst a_i'; clear A.\n                rewrite B in H0; inversion H0; subst. congruence. }\n            * right. intros [a_i' [A B]].\n              inversion A; subst a_i'; clear A.\n              rewrite B in H0; inversion H0; subst. congruence.\n          + exfalso. rewrite list_lookup_lookup_total_lt in H0; [congruence|].\n            rewrite call_instrs_length; auto. eapply fin_to_nat_lt.\n        - right; intros [a_i' [A B]].\n          inversion A. }\n      assert (Decision (\u2200 r : RegName, r \u2208 rf::rargs \u2192 is_safe (regs !r! r))).\n      { clear. induction (rf::rargs).\n        - left. intros. inversion H.\n        - destruct (is_safe_dec (regs !r! a)).\n          + destruct IHl.\n            * left. intros. eapply elem_of_cons in H.\n              destruct H; [subst a|]; auto.\n            * right. red; intros. eapply n.\n              intros. eapply H. right. auto.\n          + right. red; intros. eapply n.\n            eapply H. left. }\n      destruct H0.\n      2: { right. intro X. destruct X as [a'' [HPC [Hstk [HA [HB [HC [HD [HE [HF HG]]]]]]]]].\n           eapply n4. intros. eapply (HF (fin_to_nat i)).\n           generalize (fin_to_nat_lt i). lia. }\n      destruct H1.\n      { left. exists a'. repeat split; eauto; [eapply not_elem_of_cons; auto|eapply not_elem_of_cons; auto|].\n        intros. assert (i0 < (141 + length rargs)) by lia.\n        generalize (e0 (nat_to_fin H1)). rewrite fin_to_nat_to_fin. auto. }\n      right. intro X. destruct X as [a'' [HPC [Hstk [HA [HB [HC [HD [HE [HF HG]]]]]]]]].\n      eapply n4; auto.\n  Qed.\n\n  Lemma normal_always_step:\n    forall \u03c6, exists cf \u03c6', step (Executable, \u03c6) (cf, \u03c6').\n  Proof.\n    intros. destruct (isCorrectPC_dec (RegLocate (reg \u03c6) PC)).\n    - inversion i; subst.\n      + destruct (is_call_dec (reg \u03c6) (mem \u03c6) a e) as [Hiscall|Hiscall].\n        * destruct Hiscall as [rf [rargs Hiscall]].\n          destruct (depth_of (RegLocate (reg \u03c6) r_stk)) eqn:X.\n          { destruct (nat_eq_dec n (length (callstack \u03c6))).\n            - subst n.\n              + destruct (exec_call \u03c6 rf rargs p g b e a) as [cf \u03c6'] eqn:Hexec.\n                assert (cf = NextI \\/ cf <> NextI) as [->|Hne] by (destruct cf; auto).\n                * do 2 eexists. eapply step_exec_call; eauto.\n                * do 2 eexists; eapply step_exec_instr; eauto.\n                  left. intro Y. destruct Y as [rf' [rargs' [HY HZ]]].\n                  generalize (is_call_determ _ _ _ _ _ _ _ _ HY Hiscall).\n                  intros [-> ->]. rewrite Hexec /= in HZ. elim Hne; auto.\n            - do 2 eexists; eapply step_exec_instr; eauto.\n              right; rewrite X /=; auto. }\n          { do 2 eexists; eapply step_exec_instr; eauto.\n            right; rewrite X /=; auto. }\n        * do 2 eexists; eapply step_exec_instr; eauto.\n          left. intro X. eapply Hiscall. destruct X as [rf [rargs [Hiscall' ?]]].\n          eauto.\n      + destruct (stack d ((reg \u03c6, stk \u03c6)::(callstack \u03c6))) as [m|] eqn:Hstk.\n        * do 2 eexists; eapply step_exec_instr'; eauto.\n        * do 2 eexists. eapply step_exec_fail'; eauto.\n    - exists Failed, \u03c6. constructor 1; eauto.\n  Qed.\n\n  Lemma step_deterministic:\n    forall c1 c2 c2' \u03c31 \u03c32 \u03c32',\n      step (c1, \u03c31) (c2, \u03c32) \u2192\n      step (c1, \u03c31) (c2', \u03c32') \u2192\n      c2 = c2' \u2227 \u03c32 = \u03c32'.\n  Proof.\n    Ltac inv H := inversion H; clear H; subst.\n    intros * H1 H2; split; inv H1; inv H2; auto; try congruence.\n    - rewrite H4 in H6; inv H6.\n      destruct H10 as [X | X]; [elim X; eexists; eexists; split; eauto; rewrite H11; eauto|rewrite H9 in X; elim X; eauto].\n    - rewrite H4 in H6; inv H6.\n      destruct H13 as [X | X]; [elim X; eexists; eexists; split; eauto; rewrite H10; eauto|rewrite H9 in X; elim X; eauto].\n    - rewrite H4 in H6; inv H6.\n      destruct H10 as [X | X]; [elim X; eexists; eexists; split; eauto; rewrite H11; eauto|rewrite H9 in X; elim X; eauto].\n    - rewrite H4 in H6; inv H6.\n      destruct H13 as [X | X]; [elim X; eexists; eexists; split; eauto; rewrite H10; eauto|rewrite H9 in X; elim X; eauto].\n    - rewrite H4 in H6; inv H6.\n      destruct (is_call_determ _ _ _ _ _ _ _ _ H8 H11) as [<- <-].\n      rewrite H10 in H13; inv H13; auto.\n  Qed.\n\n  Inductive val: Type :=\n  | HaltedV: val\n  | FailedV: val\n  | NextIV: val.\n\n  Inductive expr: Type :=\n  | Instr (c : ConfFlag)\n  | Seq (e : expr).\n  Definition state : Type := ExecConf.\n\n  Definition of_val (v: val): expr :=\n    match v with\n    | HaltedV => Instr Halted\n    | FailedV => Instr Failed\n    | NextIV => Instr NextI\n    end.\n\n  Definition to_val (e: expr): option val :=\n    match e with\n    | Instr c =>\n      match c with\n      | Executable => None\n      | Halted => Some HaltedV\n      | Failed => Some FailedV\n      | NextI => Some NextIV\n      end\n    | Seq _ => None\n    end.\n\n  Lemma of_to_val:\n    forall e v, to_val e = Some v \u2192\n           of_val v = e.\n  Proof.\n    intros * HH. destruct e; try destruct c; simpl in HH; inv HH; auto.\n  Qed.\n\n  Lemma to_of_val:\n    forall v, to_val (of_val v) = Some v.\n  Proof. destruct v; reflexivity. Qed.\n\n  (** Evaluation context *)\n  Inductive ectx_item :=\n  | SeqCtx.\n\n  Notation ectx := (list ectx_item).\n\n  Definition fill_item (Ki : ectx_item) (e : expr) : expr :=\n    match Ki with\n    | SeqCtx => Seq e\n    end.\n\n  Inductive prim_step: expr \u2192 state \u2192 list Empty_set \u2192 expr \u2192 state \u2192 list expr \u2192 Prop :=\n  | PS_no_fork_instr \u03c3 e' \u03c3' :\n      step (Executable, \u03c3) (e', \u03c3') \u2192 prim_step (Instr Executable) \u03c3 [] (Instr e') \u03c3' []\n  | PS_no_fork_seq \u03c3 : prim_step (Seq (Instr NextI)) \u03c3 [] (Seq (Instr Executable)) \u03c3 []\n  | PS_no_fork_halt \u03c3 : prim_step (Seq (Instr Halted)) \u03c3 [] (Instr Halted) \u03c3 []\n  | PS_no_fork_fail \u03c3 : prim_step (Seq (Instr Failed)) \u03c3 [] (Instr Failed) \u03c3 [].\n\n  Lemma val_stuck:\n    forall e \u03c3 o e' \u03c3' efs,\n      prim_step e \u03c3 o e' \u03c3' efs \u2192\n      to_val e = None.\n  Proof. intros * HH. by inversion HH. Qed.\n\n  Lemma prim_step_exec_inv \u03c31 l1 e2 \u03c32 efs :\n    prim_step (Instr Executable) \u03c31 l1 e2 \u03c32 efs \u2192\n    l1 = [] \u2227 efs = [] \u2227\n    exists (c: ConfFlag),\n      e2 = Instr c \u2227\n      step (Executable, \u03c31) (c, \u03c32).\n  Proof. inversion 1; subst; split; eauto. Qed.\n\n  Lemma prim_step_and_step_exec \u03c31 e2 \u03c32 l1 e2' \u03c32' efs :\n    step (Executable, \u03c31) (e2, \u03c32) \u2192\n    prim_step (Instr Executable) \u03c31 l1 e2' \u03c32' efs \u2192\n    l1 = [] \u2227 e2' = (Instr e2) \u2227 \u03c32' = \u03c32 \u2227 efs = [].\n  Proof.\n    intros* Hstep Hpstep. inversion Hpstep as [? ? ? Hstep' | | |]; subst.\n    generalize (step_deterministic _ _ _ _ _ _ Hstep Hstep'). intros [-> ->].\n    auto.\n  Qed.\n\n  Lemma overlay_lang_determ e1 \u03c31 \u03ba \u03ba' e2 e2' \u03c32 \u03c32' efs efs' :\n    prim_step e1 \u03c31 \u03ba e2 \u03c32 efs \u2192\n    prim_step e1 \u03c31 \u03ba' e2' \u03c32' efs' \u2192\n    \u03ba = \u03ba' \u2227 e2 = e2' \u2227 \u03c32 = \u03c32' \u2227 efs = efs'.\n  Proof.\n    intros Hs1 Hs2. inv Hs1; inv Hs2. all: auto.\n    generalize (step_deterministic _ _ _ _ _ _ H0 H1).\n    intros [? ?]; subst. auto.\n  Qed.\n\n  Lemma fill_item_val Ki e :\n    is_Some (to_val (fill_item Ki e)) \u2192 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 head_ctx_step_val Ki e \u03c31 \u03ba e2 \u03c32 ef :\n    prim_step (fill_item Ki e) \u03c31 \u03ba e2 \u03c32 ef \u2192 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 \u2192 to_val e2 = None \u2192\n    fill_item Ki1 e1 = fill_item Ki2 e2 \u2192 Ki1 = Ki2.\n  Proof.\n    destruct Ki1, Ki2; intros; try discriminate; simplify_eq;\n    repeat match goal with\n           | HH : to_val (of_val _) = None |- _ => by rewrite to_of_val in HH\n           end; auto.\n  Qed.\n\n  Lemma overlay_lang_mixin : EctxiLanguageMixin of_val to_val fill_item prim_step.\n  Proof.\n    constructor;\n    apply _ || eauto using to_of_val, of_to_val, val_stuck,\n           fill_item_val, fill_item_no_val_inj, head_ctx_step_val.\n  Qed.\n\n  Definition is_atomic (e : expr) : Prop :=\n    match e with\n    | Instr _ => True\n    | _ => False\n    end.\n\n  Lemma updatePC_atomic \u03c6 :\n    \u2203 \u03c6', updatePC \u03c6 = (Failed,\u03c6') \u2228 (updatePC \u03c6 = (NextI,\u03c6')) \u2228\n          (updatePC \u03c6 = (Halted,\u03c6')).\n  Proof.\n    rewrite /updatePC; repeat case_match; eauto.\n  Qed.\n\n  Lemma instr_atomic i \u03c6 :\n    \u2203 \u03c6', (exec i \u03c6 = (Failed, \u03c6')) \u2228 (exec i \u03c6 = (NextI, \u03c6')) \u2228\n          (exec i \u03c6 = (Halted, \u03c6')).\n  Proof.\n    unfold exec; repeat case_match; eauto; try (eapply updatePC_atomic; eauto).\n  Qed.\n\nEnd opsem.\n\nCanonical Structure overlay_ectxi_lang `{MachineParameters} := EctxiLanguage overlay_lang_mixin.\nCanonical Structure overlay_ectx_lang `{MachineParameters} := EctxLanguageOfEctxi overlay_ectxi_lang.\nCanonical Structure overlay_lang `{MachineParameters} := LanguageOfEctx overlay_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 _) =>\neexists; rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\n\nLocal Hint Resolve language.val_irreducible.\nLocal Hint Resolve to_of_val.\nLocal Hint Unfold language.irreducible.\n\nGlobal Instance dec_pc c : Decision (isCorrectPC c).\nProof. apply isCorrectPC_dec. Qed.\n\n(* There is probably a more general instance to be stated there...*)\nInstance Reflexive_ofe_equiv_Word : (Reflexive (ofe_equiv (leibnizO base.Word))).\nProof. intro; reflexivity. Qed.\n\n(****)\n\nLemma updatePC_not_executable `{MachineParameters}:\n  forall \u03c6,\n    (updatePC \u03c6).1 <> Executable.\nProof.\n  intros; unfold updatePC.\n  repeat match goal with\n           |- context [match ?X with | _ => _ end] => destruct X\n         end; simpl; auto.\nQed.\n\nLemma exec_not_executable `{MachineParameters}:\n  forall i \u03c6,\n    (exec i \u03c6).1 <> Executable.\nProof.\n  intros. destruct i; simpl; auto;\n            repeat match goal with\n                     |- context [match ?X with | _ => _ end] => destruct X\n                   end; simpl; auto; apply updatePC_not_executable.\nQed.\n\nLemma exec_call_not_executable `{MachineParameters}:\n  forall \u03c3 rf rargs p g b e a,\n    (exec_call \u03c3 rf rargs p g b e a).1 <> Executable.\nProof.\n  intros. rewrite /exec_call.\n  repeat match goal with\n           |- context [match ?X with | _ => _ end] => destruct X\n  end; simpl; auto.\nQed.\n\nGlobal Instance is_atomic_correct `{MachineParameters} s (e : expr) : is_atomic e \u2192 Atomic s e.\nProof.\n  intros Ha; apply strongly_atomic_atomic, ectx_language_atomic.\n  - destruct e.\n    + destruct c; rewrite /Atomic; intros ????? Hstep;\n        inversion Hstep.\n      match goal with HH : step _ _ |- _ => inversion HH end; subst; simpl; eauto.\n      * case_eq (exec (decodeInstrW' (mem \u03c3 !m! a)) \u03c3); intros.\n        destruct c; eauto.\n        generalize (exec_not_executable (decodeInstrW' (mem \u03c3 !m! a)) \u03c3).\n        rewrite H1. simpl; congruence.\n      * case_eq (exec (decodeInstrW' (m !m! a)) \u03c3); intros.\n        destruct c; eauto.\n        generalize (exec_not_executable (decodeInstrW' (m !m! a)) \u03c3).\n        rewrite H1. simpl; congruence.\n    + inversion Ha.\n  - intros K e' -> Hval%eq_None_not_Some.\n    induction K using rev_ind; first done.\n    simpl in Ha; rewrite fill_app in Ha; simpl in Ha.\n    destruct Hval. apply (fill_val K e'); simpl in *.\n    destruct x; naive_solver.\nQed.\n\nLtac solve_atomic :=\n  apply is_atomic_correct; simpl; repeat split;\n    rewrite ?to_of_val; eapply mk_is_Some; fast_done.\n\nHint Extern 0 (Atomic _ _) => solve_atomic.\nHint Extern 0 (Atomic _ _) => solve_atomic : typeclass_instances.\n\nLemma head_reducible_from_step `{MachineParameters} \u03c31 e2 \u03c32 :\n  step (Executable, \u03c31) (e2, \u03c32) \u2192\n  head_reducible (Instr Executable) \u03c31.\nProof. intros * HH. rewrite /head_reducible /head_step //=.\n       eexists [], (Instr _), \u03c32, []. by constructor.\nQed.\n\nLemma normal_always_head_reducible `{MachineParameters} \u03c3 :\n  head_reducible (Instr Executable) \u03c3.\nProof.\n  generalize (normal_always_step \u03c3); intros (?&?&?).\n  eapply head_reducible_from_step. eauto.\nQed.\n\nDefinition overlay_component: Type := component nat _ _ overlay.base.Word.\n\nDefinition initial_state `{MachineParameters} (b_stk e_stk: Addr) (c: overlay_component): cfg overlay_lang :=\n  match c with\n  | Lib _ _ _ _ pre_comp => ([Seq (Instr Executable)], (\u2205, \u2205, \u2205, [])) (* dummy value *)\n  | Main _ _ _ _ (ms, _, _) c_main => ([Seq (Instr Executable)], (<[r_stk := inr (Stk 0 URWLX b_stk e_stk b_stk)]> (<[PC := c_main]> (gset_to_gmap (inl 0%Z) (list_to_set all_registers))), ms, \u2205, []))\n  end.\n\nDefinition can_address_only (w: base.Word) (addrs: gset Addr): Prop :=\n  match w with\n  | inl _ => True\n  | inr (Regular (_, _, b, e, _)) =>\n    forall a, (b <= a < e)%a -> a \u2208 addrs\n  | _ => False\n  end.\n\nDefinition pwlW (w: base.Word): bool :=\n  match w with\n  | inl _ => false\n  | inr (Regular (p, _, _, _, _)) => pwlU p\n  | inr (Stk _ p _ _ _) => pwlU p\n  | inr (Ret _ _ _) => false\n  end.\n\nDefinition is_global (w: base.Word): bool :=\n  match w with\n  | inl _ => true\n  | inr (Regular (_, l, _, _, _)) =>\n    match l with\n    | Global => true\n    | _ => false\n    end\n  | inr _ => false\n  end.\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/overlay/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.18922692125072405}}
{"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. \nRequire Import soundness.\n \nRequire Import lemmas.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nOpen Scope nat.\nOpen Scope code_scope.\n\n(*+ Lemmas for Memory Model +*)\nLemma memset_l_l_indom :\n  forall rn v m,\n    indom rn (MemMap.set rn (Some v) m).\nProof.\n  intros.\n  unfold indom.\n  exists v.\n  unfolds MemMap.set.\n  destruct_addreq.\nQed.\n\nLemma memset_twice :\n  forall (A : Type) l (v v1 : A) m,\n    MemMap.set l (Some v) (MemMap.set l (Some v1) m) =\n    MemMap.set l (Some v) m.\nProof.\n  intros.\n  eapply functional_extensionality.\n  intro.\n  unfolds MemMap.set.\n  destruct_addreq.\nQed.\n\nLemma indom_memset_merge_eq :\n  forall M m l v,\n    indom l M ->\n    MemMap.set l (Some v) (merge M m) = merge (MemMap.set l (Some v) M) m.\nProof.\n  intros.\n  unfold MemMap.set, merge in *.\n  eapply functional_extensionality.\n  intro.\n  unfold indom in *.\n  simpljoin1. \n  destruct_addreq.\nQed.\n\nLemma disj_indom_memset_still :\n  forall M1 M2 l v,\n    disjoint M1 M2 ->\n    indom l M1 ->\n    disjoint (MemMap.set l (Some v) M1) M2.\nProof.\n  intros.\n  unfold disjoint in *.\n  intros.\n  specialize (H x).\n  destruct (M1 x) eqn:Heqe1; eauto.\n  {\n    destruct (M2 x) eqn:Heqe2; tryfalse.\n    unfold MemMap.set.\n    destruct_addreq.\n    rewrite Heqe1; eauto.\n  }\n  {\n    destruct (M2 x) eqn:Heqe2.\n    {\n      unfold MemMap.set.\n      destruct_addreq; subst.\n      unfold indom in *.\n      simpljoin1.\n      tryfalse.\n      rewrite Heqe1; eauto.\n    }\n    {\n      unfold MemMap.set.\n      destruct_addreq.\n      rewrite Heqe1; eauto.\n    }\n  }\nQed.\n\nLemma MemSet_same_addr_disj_stable :\n  forall l v v' M M',\n    disjoint (MemMap.set l (Some v') M) M' ->\n    disjoint (MemMap.set l (Some v) M) M'.\nProof.\n  intros.\n  unfold disjoint.\n  intros.\n  unfold disjoint in H.\n  specialize (H x).\n\n  unfolds MemMap.set.\n  destruct_addreq.\nQed.\n\nLemma disj_merge_disj_sep :\n  forall (tp : Type) (m1 m2 m3 : tp -> option Word),\n    disjoint m1 (merge m2 m3) ->\n    disjoint m1 m2 /\\ disjoint m1 m3.\nProof.\n  intros.\n  split.\n  eapply disj_merge_disj_sep1; eauto.\n  eapply disj_merge_disj_sep2; eauto.\nQed.\n\nLemma dom_eq_merge_some_addr_stable :\n  forall m1 m2 l w w',\n    dom_eq m1 m2 ->\n    dom_eq (merge (RegMap.set l (Some w) empR) m1)\n           (merge (RegMap.set l (Some w') empR) m2).\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  split.\n  {\n    intros.\n    unfold indom in H1.\n    simpljoin1.\n    unfold merge in *.\n    unfold indom.\n    unfolds RegMap.set.\n    destruct_rneq.\n    {\n      simpl in H1.\n      simpl.\n      assert (indom l0 m1).\n      unfold indom; eauto.\n      eapply H in H3.\n      unfold indom in *; eauto.\n    }\n  }\n  { \n    intros.\n    unfold indom in H1.\n    simpljoin1.\n    unfold merge in *.\n    unfold RegMap.set in *.\n    destruct_rneq_H.\n    inversion H1; subst.\n    unfold indom.\n    destruct_rneq.\n    unfold indom.\n    destruct_rneq.\n    simpls.  \n    assert (indom l0 m2).\n    {\n      unfold indom; eauto.\n    }\n    eapply H0 in H4.\n    unfold indom in *; eauto.\n  }\nQed.\n\nLemma disj_dom_eq_still :\n  forall (tp : Type) (m1 m2 m1' m2' : tp -> option Word),\n    disjoint m1 m2 ->\n    dom_eq m1 m1' -> dom_eq m2 m2' ->\n    disjoint m1' m2'.\nProof.\n  intros.\n  unfold disjoint in *.\n  intros.\n  specialize (H x).\n  destruct (m1 x) eqn:Heqe1.\n  {\n    destruct (m1' x) eqn:Heqe1';\n      destruct (m2 x) eqn:Heqe2;\n      destruct (m2' x) eqn:Heqe2'; eauto.\n    clear - Heqe2 H1 Heqe2'.\n    unfold dom_eq in *.\n    simpljoin1.\n    assert (indom x m2').\n    unfold indom; eauto.\n    eapply H0 in H1; eauto.\n    unfold indom in *.\n    simpljoin1.\n    tryfalse.\n  }\n  {\n    destruct (m1' x) eqn:Heqe1';\n      destruct (m2 x) eqn:Heqe2;\n      destruct (m2' x) eqn:Heqe2'; eauto.\n    clear - Heqe1 Heqe1' H0.\n    unfold dom_eq in *.\n    simpljoin1.\n    assert (indom x m1').\n    unfold indom; eauto.\n    eapply H0 in H1; eauto.\n    unfold indom in *.\n    simpljoin1.\n    tryfalse.\n    clear - Heqe1 H0 Heqe1'.\n    unfold dom_eq in *.\n    simpljoin1.\n    assert (indom x m1').\n    unfold indom; eauto.\n    eapply H0 in H1.\n    unfold indom in *.\n    simpljoin1.\n    tryfalse.\n  }\nQed.\n\nLemma dom_eq_merge_still :\n  forall tp (m1 m1' m2 m2' : tp -> option Word),\n    dom_eq m1 m1' -> dom_eq m2 m2' ->\n    dom_eq (merge m1 m2) (merge m1' m2').\nProof.\n  intros.\n  unfold dom_eq in *.\n  split.\n  {\n    intros.\n    simpljoin1.\n    unfold indom in H1.\n    simpljoin1.\n    unfold merge in *.\n    destruct (m1 l) eqn:Heqe.\n    {\n      inversion H1; subst.\n      assert (indom l m1).\n      unfold indom; eauto.\n      eapply H in H4.\n      unfold indom in *; simpljoin1.\n      eexists.\n      rewrite H4; eauto.\n    }\n    {\n      unfold indom.\n      destruct (m1' l) eqn:Heqe'.\n      assert (indom l m1').\n      unfold indom; eauto.\n      eapply H3 in H4.\n      unfold indom in *.\n      simpljoin1.\n      rewrite Heqe in H4. tryfalse.\n      assert (indom l m2).\n      unfold indom; eauto.\n      eapply H0 in H4; eauto.\n    }\n  }\n  {\n    intros.\n    unfold indom in H1.\n    simpljoin1.\n    unfold merge in *.\n    destruct (m1' l) eqn:Heqe.\n    {\n      inversion H1; subst.\n      assert (indom l m1').\n      {\n        unfold indom; eauto.\n      }\n      eapply H3 in H4.\n      unfold indom in *.\n      simpljoin1.\n      rewrite H4; eauto.\n    }\n    {\n      unfold indom.\n      destruct (m1 l) eqn:Heqe1.\n      {\n        assert (indom l m1).\n        unfold indom; eauto.\n        eapply H in H4.\n        unfold indom in *; simpljoin1.\n        rewrite Heqe in H4.\n        tryfalse.\n      }\n      {\n        assert (indom l m2').\n        unfold indom; eauto.\n        eapply H2 in H4; eauto.\n      }\n    }\n  }\nQed.\n\nLemma same_m_dom_eq:\n  forall tp (m : tp -> option Word),\n    dom_eq m m.\nProof.\n  unfold dom_eq.\n  intros.\n  split; intros; eauto.\nQed.\n\nLemma dom_eq_trans :\n  forall tp (m1 m2 m3 : tp -> option Word),\n    dom_eq m1 m2 -> dom_eq m2 m3 ->\n    dom_eq m1 m3.\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  split.\n  {\n    intros.\n    eapply H in H3.\n    eauto.\n  }\n  {\n    intros.\n    eapply H1 in H3; eauto.\n  }\nQed.\n\nLemma indom_dom_eq_subst :\n  forall tp l (m m' : tp -> option Word),\n    indom l m ->\n    dom_eq m m' ->\n    indom l m'.\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  eauto.\nQed.\n\nLemma indom_dom_eq_merge_subst :\n  forall tp l (m1 m1' m2 : tp -> option Word),\n    indom l (merge m1 m2) ->\n    dom_eq m1 m1' ->\n    indom l (merge m1' m2).\nProof.\n  intros.\n  unfold indom in *.\n  unfold dom_eq in *.\n  simpljoin1.\n  unfold merge in *.\n  destruct (m1 l) eqn:Heqe1.\n  {\n    assert (indom l m1).\n    unfold indom; eauto.\n    eapply H0 in H2; eauto.\n    unfold indom in *.\n    simpljoin1; eauto.\n    eexists.\n    rewrite H2; eauto.\n  }\n  {\n    destruct (m1' l) eqn:Heqe2; eauto.\n  }\nQed.\n\nLemma indom_dom_eq_merge_subst2 :\n  forall tp l (m1 m2 m2' : tp -> option Word),\n    indom l (merge m1 m2) ->\n    dom_eq m2 m2' ->\n    indom l (merge m1 m2').\nProof.\n  intros.\n  unfold indom in *.\n  unfold dom_eq in *.\n  simpljoin1.\n  unfold merge in *. \n  destruct (m1 l) eqn:Heqe1.\n  {\n    inversion H; eauto.\n  }\n  {\n    assert (indom l m2).\n    unfold indom; eauto.\n    eapply H0 in H2; eauto.\n  }\nQed.\n\nLemma dom_eq_merge_subst1 :\n  forall tp (m m' m1 m2 : tp -> option Word),\n    dom_eq m m' ->\n    dom_eq (merge m m1) m2 ->\n    dom_eq (merge m' m1) m2.\nProof.\n  intros.\n  unfold dom_eq in *.\n  split.\n  {\n    intros.\n    simpljoin1.\n    eapply H0.\n    eapply indom_dom_eq_merge_subst; eauto.\n    unfold dom_eq; eauto.\n  }\n  {\n    simpljoin1.\n    intros.\n    eapply H1 in H3.\n    eapply indom_dom_eq_merge_subst; eauto.\n    unfold dom_eq; eauto.\n  }\nQed.\n\nLemma dom_eq_sym :\n  forall tp (m m' : tp -> option Word),\n    dom_eq m m' -> dom_eq m' m.\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  split.\n  {\n    intros; eauto.\n  }\n  {\n    intros; eauto.\n  }\nQed.\n\nLemma disj_in_m1_merge_still :\n  forall tp (m1 m2 : tp -> option Word) l v,\n    disjoint m1 m2 -> m1 l = Some v ->\n    merge m1 m2 l = Some v.\nProof.\n  intros.\n  unfold merge.\n  rewrite H0; eauto.\nQed.\n\nLemma disj_in_m2_merge_still :\n  forall tp (m1 m2 : tp -> option Word) l v,\n    disjoint m1 m2 -> m2 l = Some v ->\n    merge m1 m2 l = Some v.\nProof.\n  intros.\n  unfold merge.\n  destruct (m1 l) eqn:Heqe.\n  {\n    unfold disjoint in *.\n    specialize (H l).\n    rewrite Heqe in H.\n    rewrite H0 in H; tryfalse.\n  }\n  {\n    eauto.\n  }\nQed.\n\nLemma empM_merge_still_l :\n  forall M,\n    merge empM M = M.\nProof.\n  intros.\n  unfold merge.\n  eapply functional_extensionality; eauto.\nQed.\n\nLemma empM_merge_still_r :\n  forall M,\n    merge M empM = M.\nProof.\n  intros.\n  unfold merge.\n  eapply functional_extensionality; eauto.\n  intro.\n  destruct (M x); eauto.\nQed.\n\n(*+ Lemmas for expression +*)\nLemma get_R_merge_still2 :\n  forall R r l v,\n    disjoint R r -> get_R r l = Some v ->\n    get_R (merge R r) l = Some v.\nProof.\n  intros.\n  unfolds get_R.\n  unfold merge.\n  destruct (R l) eqn:Heqe; eauto; tryfalse.\n  destruct (r l) eqn:Heqe1; eauto; tryfalse.\n  clear - H Heqe Heqe1.\n  unfold disjoint in *.\n  specialize (H l).\n  rewrite Heqe in H; eauto.\n  rewrite Heqe1 in H; tryfalse.\nQed.\n\nLemma eval_opexp_merge_still2 :\n  forall R r oexp l,\n    eval_opexp r oexp = Some l -> disjoint R r ->\n    eval_opexp (merge R r) oexp = Some l.\nProof.\n  intros.\n  destruct oexp.\n  {\n    simpls.\n    eapply get_R_merge_still2; eauto.\n  }\n  {\n    simpls.\n    eauto.\n  }\nQed.\n\n(*+ Lemmas for Register State +*)\nLemma indom_setR_still :\n  forall l rn R v,\n    indom l R ->\n    indom l (set_R R rn v).\nProof.\n  intros.\n  unfold indom in *.\n  simpljoin1.\n  unfold set_R in *.\n  unfold is_indom in *.\n  destruct (R rn) eqn:Heqe.\n  {\n    unfolds RegMap.set.\n    destruct_rneq.\n  }\n  {\n    eauto.\n  }\nQed.\n\nLemma indom_regset_still:\n  forall l l' M w,\n    indom l M ->\n    indom l (RegMap.set l' (Some w) M).\nProof.\n  intros.\n  unfold indom in *.\n  simpljoin1.\n  unfold RegMap.set.\n  destruct_rneq.\nQed.\n\nLemma RegSet_same_addr_disj_stable2 :\n  forall l v v' m m',\n    disjoint m (RegMap.set l (Some v') m') ->\n    disjoint m (RegMap.set l (Some v) m').\nProof.\n  intros.\n  unfold disjoint in *.\n  intro.\n  specialize (H x).\n\n  destruct (m x) eqn:Heqe1; eauto.\n  {\n    unfolds RegMap.set.\n    destruct_rneq.\n  }\n  {\n    unfolds RegMap.set.\n    destruct_rneq.\n  }\nQed.\n\nLemma disj_indom_regset_still :\n  forall R1 R2 rn v,\n    disjoint R1 R2 ->\n    indom rn R1 ->\n    disjoint (RegMap.set rn (Some v) R1) R2.\nProof.\n  intros.\n  unfold disjoint in *.\n  intros.\n  specialize (H x).\n  destruct (R1 x) eqn:Heqe1; eauto.\n  {\n    destruct (R2 x) eqn:Heqe2; tryfalse.\n    unfold RegMap.set.\n    destruct_rneq.\n    rewrite Heqe1; eauto.\n  }\n  {\n    destruct (R2 x) eqn:Heqe2.\n    {\n      unfold RegMap.set.\n      destruct_rneq; subst.\n      unfold indom in *.\n      simpljoin1.\n      tryfalse.\n      rewrite Heqe1; eauto.\n    }\n    {\n      unfold RegMap.set.\n      destruct_rneq.\n      rewrite Heqe1; eauto.\n    }\n  }\nQed.\n\nLemma notindom_R_setR_merge_eq :\n  forall rn R r v,\n    ~ indom rn R ->\n    set_R (merge R r) rn v = merge R (set_R r rn v).\nProof.\n  intros.\n  unfolds set_R.\n  unfold is_indom in *.\n  unfold merge in *.\n  destruct (R rn) eqn:Heqe; tryfalse.\n  {\n    eapply functional_extensionality.\n    intro.\n    unfolds RegMap.set.\n    false.\n    eapply H.\n    unfold indom.\n    eauto.\n  }\n  {\n    eapply functional_extensionality.\n    intros. \n    destruct (r rn) eqn:Heqe1; eauto.\n    unfolds RegMap.set.\n    destruct_rneq; subst.\n    rewrite Heqe; eauto.\n  }\nQed.\n\nLemma regst_indom :\n  forall M R F D rn v,\n    (M, (R, F), D) |= rn |=> v ->\n    indom rn R.\nProof.\n  intros.\n  simpls.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  eapply regset_l_l_indom; eauto.\nQed.\n\nLemma reg_vl_change :\n  forall M R F D rn v v1 p,\n    (M, (R, F), D) |= rn |=> v ** p ->\n    (M, (set_R R rn v1, F), D) |= rn |=> v1 ** p.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpls.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  exists (empM, (set_R (RegMap.set rn (Some v) empR) rn v1, f0), d0)\n    (m0, (r0, f0), d0).\n  simpl.\n  repeat (split; eauto).\n  eapply disjoint_setR_still1; eauto.\n  rewrite indom_setR_merge_eq1; eauto.\n  eapply regset_l_l_indom; eauto.\n  rewrite indom_setR_eq_RegMap_set; eauto.\n  rewrite regset_twice; eauto.\n  eapply regset_l_l_indom; eauto.\nQed.\n\nLemma reg_vl_change' :\n  forall M R F D rn v v1 p,\n    (M, (R, F), D) |= rn |=> v ** p ->\n    (M, (RegMap.set rn (Some v1) R, F), D) |= rn |=> v1 ** p.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpls.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  exists (empM, (RegMap.set rn (Some v1) (RegMap.set rn (Some v) empR), f0), d0)\n    (m0, (r0, f0), d0).\n  simpl.\n  repeat (split; eauto).\n  rewrite regset_twice; eauto.\n  eapply RegSet_same_addr_disj_stable; eauto.\n  rewrite indom_setR_merge_eq; eauto.\n  eapply regset_l_l_indom; eauto.\n  rewrite regset_twice; eauto.\nQed.\n\nLemma notin_dom_set_delay_asrt_stable :\n  forall p M R F D (rsp : SpReg) v,\n    (M, (R, F), D) |= p ->\n    ~ indom rsp R -> ~ In rsp (getRegs D) ->\n    (M, (R, F), set_delay rsp v D) |= p.\nProof.\n  intro p.\n  induction p; intros;\n    try solve [simpls; eauto].\n \n  -\n    simpls.\n    unfolds regSt; simpls; eauto.\n    simpljoin1.\n    repeat (split; eauto).\n    intro.\n    eapply H3.\n    unfolds regInDlyBuff.\n    destruct r; tryfalse.\n    assert (rsp <> s).\n    {\n      clear - H0.\n      intro.\n      eapply H0.\n      subst.\n      eapply regset_l_l_indom; eauto.\n    }\n    clear - H H2.\n    unfolds set_delay.\n    simpls.\n    destruct H; subst; tryfalse; eauto.\n\n  -\n    unfold set_delay, X.\n    simpls.\n    simpljoin1.\n    exists x.\n    repeat (split; eauto).\n    destruct H3.\n    {\n      left.\n      eapply regdlySt_dlycons_stable; eauto.\n      clear - H0.\n      intro.\n      eapply H0.\n      subst.\n      eapply regset_l_l_indom; eauto.\n    }\n    {\n      right.\n      unfolds regSt.\n      simpls.\n      simpljoin1.\n      repeat (split; eauto).\n      intro.\n      destruct H2.\n      {\n        subst.\n        eapply H0.\n        eapply regset_l_l_indom; eauto.\n      }\n      {\n        tryfalse.\n      }\n    }\n\n  -\n    simpl in H.\n    simpljoin1.\n    simpl; eauto.\n\n  -\n    simpl in H.\n    simpl.\n    destruct H; eauto.\n\n  -\n    sep_star_split_tac.\n    simpl in H5.\n    simpljoin1.\n    simpl.\n    exists (m, (r, f0), set_delay rsp v d0) (m0, (r0, f0), set_delay rsp v d0).\n    simpl.\n    repeat (split; eauto).\n    eapply IHp1; eauto.\n    intro.\n    eapply H0.\n    eapply indom_merge_still; eauto.\n    eapply IHp2; eauto.\n    intro.\n    eapply H0.\n    eapply indom_merge_still2; eauto.\n\n  -\n    simpl in H0.\n    simpljoin1.\n    simpl.\n    exists x.\n    eauto.\nQed.\n\nLemma dlyfrmfree_notin_changeDly_still :\n  forall p M R F D (rsp : SpReg) v,\n    (M, (R, F), D) |= p -> DlyFrameFree p ->\n    ~ indom rsp R ->\n    (M, (R, F), set_delay rsp v D) |= p.\nProof.\n  intro p.\n  induction p; intros;\n    try solve [simpls; tryfalse; eauto].\n \n  -\n    simpls.\n    unfolds regSt; simpls; eauto.\n    simpljoin1.\n    repeat (split; eauto).\n    intro.\n    eapply H3.\n    unfolds regInDlyBuff.\n    destruct r; tryfalse.\n    assert (rsp <> s).\n    {\n      clear - H1.\n      intro.\n      eapply H1.\n      subst.\n      eapply regset_l_l_indom; eauto.\n    }\n    clear - H H0.\n    unfolds set_delay.\n    simpls.\n    destruct H; subst; tryfalse; eauto.\n\n  -\n    simpl in H, H0.\n    simpljoin1.\n    simpl; eauto.\n\n  -\n    simpl in H, H0.\n    simpljoin1.\n    simpl.\n    destruct H; eauto.\n\n  -\n    simpl in H0.\n    simpljoin1.\n    sep_star_split_tac.\n    simpl in H6.\n    simpljoin1.\n    simpl.\n    exists (m, (r, f0), set_delay rsp v d0) (m0, (r0, f0), set_delay rsp v d0).\n    simpl.\n    repeat (split; eauto).\n    eapply IHp1; eauto.\n    intro.\n    eapply H1.\n    eapply indom_merge_still; eauto.\n    eapply IHp2; eauto.\n    intro.\n    eapply H1.\n    eapply indom_merge_still2; eauto.\n\n  -\n    simpl in H0, H1.\n    simpljoin1.\n    specialize (H1 x).\n    simpl.\n    exists x.\n    eauto.\nQed.\n  \nLemma regdlySt_changeFrm_stable :\n  forall n s w M R F F' D,\n    regdlySt n s w (M, (R, F), D) ->\n    regdlySt n s w (M, (R, F'), D).\nProof.\n  intro n.\n  induction n; intros.\n  -\n    unfolds regdlySt; eauto.\n  -\n    simpls.\n    destruct H; eauto.\nQed.\n\nLemma dom_eq_emp :\n  dom_eq empR empR.\nProof.\n  unfold dom_eq in *.\n  split; intros; eauto.\nQed.\n\nLemma dom_eq_memset_same_addr_stable :\n  forall m1 m2 l v v',\n    dom_eq m1 m2 ->\n    dom_eq (RegMap.set l (Some v) m1) (RegMap.set l (Some v') m2).\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  split.\n  {\n    clear - H.\n    intros.\n    unfold indom in H0.\n    simpljoin1.\n    unfolds RegMap.set.\n    destruct_rneq_H.\n    {\n      subst.\n      inversion H0; subst.\n      unfold indom.\n      exists v'.\n      destruct_rneq.\n    }\n    {\n      unfold indom.\n      assert (indom l0 m1).\n      unfold indom in *; eauto.\n      eapply H in H2.\n      unfold indom in *.\n      simpljoin1.\n      destruct_rneq.\n    }\n  }\n  {\n    intros.\n    unfold indom in H1.\n    simpljoin1.\n    unfolds RegMap.set.\n    destruct_rneq_H.\n    {\n      inversion H1; subst.\n      unfold indom.\n      exists v.\n      destruct_rneq.\n    }\n    {\n      assert (indom l0 m2).\n      unfold indom; eauto.\n      eapply H0 in H3.\n      unfold indom in *.\n      simpljoin1.\n      exists x0.\n      destruct_rneq.\n    }\n  }\nQed.\n \nLemma rn_st_v_eval_reg_v :\n  forall M R F D rn w p,\n    (M, (R, F), D) |= rn |=> w ** p ->\n    R rn = Some w.\nProof.\n  intros.\n  simpls.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n  simpls.\n  simpljoin1.\n  unfolds regSt.\n  simpls; simpljoin1.\n  unfold merge.\n  unfold RegMap.set.\n  destruct_rneq.\nQed.\n\nLtac disj_reg_solve :=\n  match goal with\n  | H : disjoint (RegMap.set ?l1 (Some ?v1) empR)\n                 (merge (RegMap.set ?l2 (Some ?v2) empR) ?m) |-\n    disjoint (RegMap.set ?l1 (Some ?v1') empR)\n             (merge (RegMap.set ?l2 (Some ?v2') empR) ?m') =>\n    eapply disj_merge_disj_sep in H;\n    let H1 := fresh in\n    let H2 := fresh in\n    destruct H as [H1 H2];\n    eapply disj_sep_merge_still;\n    [\n      eapply RegSet_same_addr_disj_stable;\n      eapply RegSet_same_addr_disj_stable2; eauto |\n      disj_reg_solve\n    ]\n  | _ =>\n    try (eapply RegSet_same_addr_disj_stable;\n         eapply RegSet_same_addr_disj_stable2; eauto)\n  end.\n\nLemma reg_frame_upd :\n  forall (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg)\n    w0 w1 w2 w3 w4 w5 w6 w7 w0' w1' w2' w3' w4' w5' w6' w7' \n    M R F F' D,\n    (M, (R, F), D) |=\n                   rr0 |=> w0 **\n                   rr1 |=> w1 **\n                   rr2 |=> w2 ** rr3 |=> w3 ** rr4 |=> w4 **\n                   rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n  exists R',\n    (M, (R', F'), D) |=\n                   rr0 |=> w0' **\n                   rr1 |=> w1' **\n                   rr2 |=> w2' ** rr3 |=> w3' ** rr4 |=> w4' **\n                   rr5 |=> w5' ** rr6 |=> w6' ** rr7 |=> w7' /\\ dom_eq R R'.\nProof.\n  intros.\n  sep_star_split_tac. \n  simpl in H3, H2, H5, H7, H9, H11, H13.\n  simpljoin1.\n\n  simpl in H, H0, H1, H4, H6, H8, H10, H12.\n  unfolds regSt.\n  simpl in H, H0, H1, H4, H6, H8, H10, H12.\n  simpljoin1.\n\n  exists\n    (merge (RegMap.set rr0 (Some w0') empR)\n    (merge (RegMap.set rr1 (Some w1') empR)\n           (merge (RegMap.set rr2 (Some w2') empR)\n                  (merge (RegMap.set rr3 (Some w3') empR)\n                         (merge (RegMap.set rr4 (Some w4') empR)\n                                (merge (RegMap.set rr5 (Some w5') empR)\n                                       (merge (RegMap.set rr6 (Some w6') empR)\n                                              (RegMap.set rr7 (Some w7') empR)))))))).\n  split.\n \n  eapply disj_sep_star_merge; eauto.\n  simpl. unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  simpl; unfold regSt.\n  simpl; eauto.\n  \n  simpl; unfold regSt.\n  simpl; eauto.\n\n  disj_reg_solve.\n  disj_reg_solve.\n  disj_reg_solve.\n  disj_reg_solve.\n  disj_reg_solve.\n  disj_reg_solve.\n  disj_reg_solve.\n\n  repeat (eapply dom_eq_merge_some_addr_stable; eauto).\n  eapply dom_eq_memset_same_addr_stable.\n  eapply dom_eq_emp.\nQed.\n\nLemma OutRegs_asrt_upd :\n  forall M R F F' D fm fm',\n    (M, (R, F), D) |= OutRegs fm ->\n    exists R', (M, (R', F'), D) |= OutRegs fm' /\\ dom_eq R R'.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm, fm'.\n  eapply reg_frame_upd; eauto.\nQed.\n\nLemma LocalRegs_asrt_upd :\n  forall M R F F' D fm fm',\n    (M, (R, F), D) |= LocalRegs fm ->\n    exists R', (M, (R', F'), D) |= LocalRegs fm' /\\ dom_eq R R'.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm, fm'.\n  eapply reg_frame_upd; eauto.\nQed.\n\nLemma InRegs_asrt_upd :\n  forall M R F F' D fm fm',\n    (M, (R, F), D) |= InRegs fm ->\n    exists R', (M, (R', F'), D) |= InRegs fm' /\\ dom_eq R R'.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm, fm'.\n  eapply reg_frame_upd; eauto.\nQed.\n\nLemma Regs_asrt_upd :\n  forall M R F F' D fm1 fm1' fm2 fm2' fm3 fm3',\n    (M, (R, F), D) |= Regs fm1 fm2 fm3 ->\n    exists R', (M, (R', F'), D) |= Regs fm1' fm2' fm3' /\\ dom_eq R R'.\nProof.\n  intros.\n  unfolds Regs.\n  eapply sep_star_split in H.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n  eapply sep_star_split in H0.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n  \n  eapply OutRegs_asrt_upd with (F' := F') (fm' := fm1') in H.\n  eapply LocalRegs_asrt_upd with (F' := F') (fm' := fm2') in H0.\n  eapply InRegs_asrt_upd with (F' := F') (fm' := fm3') in H2.\n  simpljoin1.\n  renames x1 to r0', x0 to r1', x to r2'.\n  simpl in H3, H1.\n  simpljoin1.\n  exists (merge r0' (merge r1' r2')).\n  split.\n  {\n    eapply disj_sep_star_merge; eauto.\n    eapply disj_sep_star_merge; eauto.    \n    eapply disj_dom_eq_still.\n    eapply H11.\n    eauto.\n    eauto.\n    eapply disj_dom_eq_still; eauto.\n    eapply dom_eq_merge_still; eauto.\n  }\n  {\n    eapply dom_eq_merge_still; eauto.\n    eapply dom_eq_merge_still; eauto.\n  }\nQed.\n\nLemma indoms_merge_still1 :\n  forall tp vl (m1 m2 : tp -> option Word),\n    indoms vl m1 ->\n    indoms vl (merge m1 m2).\nProof.\n  intros tp vl.\n  induction vl; intros.\n  -\n    simpl; eauto.\n\n  -\n    simpl in H.\n    simpljoin1.\n    simpl. \n    split; eauto.\n    eapply indom_merge_still; eauto.\nQed.\n\nLemma indoms_merge_still2 :\n  forall tp vl (m1 m2 : tp -> option Word),\n    indoms vl m2 ->\n    indoms vl (merge m1 m2).\nProof.\n  intros tp vl.\n  induction vl; intros.\n  -\n    simpl; eauto.\n\n  -\n    simpl in H.\n    simpljoin1.\n    simpl.\n    split; eauto.\n    eapply indom_merge_still2; eauto.\nQed.\n\nLemma indoms_setR_still :\n  forall vl R rn w, \n    indoms (getRs vl) R ->\n    indoms (getRs vl) (set_R R rn w).\nProof.\n  intro vl.\n  induction vl; intros.\n  -\n    simpls.\n    eauto.\n  -\n    destruct a.\n    simpls.\n    simpljoin1.\n    split.\n    eapply indom_setR_still; eauto.\n    eauto.\nQed.\n\nLemma indoms_setRs_merge_eq :\n  forall vl R r,\n    indoms (getRs vl) R ->\n    set_Rs (merge R r) vl = merge (set_Rs R vl) r.\nProof.\n  intros vl.\n  induction vl; intros.\n  -\n    simpls.\n    eauto.\n  -\n    destruct a.\n    simpl in H.\n    simpl. \n    simpljoin1.\n    rewrite indom_setR_merge_eq1; eauto.\n    eapply IHvl.\n    eapply indoms_setR_still; eauto.\nQed.\n\nLemma indoms_setRs_merge_eq2 :\n  forall vl (R : RegFile) r,\n    disjoint R r ->\n    indoms (getRs vl) r ->\n    set_Rs (merge R r) vl = merge R (set_Rs r vl).\nProof.\n  intros vl.\n  induction vl; intros.\n  -\n    simpls.\n    eauto.\n  -\n    destruct a.\n    simpl in H0.\n    simpl.\n    simpljoin1.\n     \n    rewrite indom_setR_merge_eq2; eauto.\n    eapply IHvl.\n    eapply disjoint_setR_still2; eauto.\n    eapply indoms_setR_still; eauto.\n    clear - H H0.\n    intro.\n    unfold disjoint in *.\n    specialize (H r0).\n    unfold indom in *.\n    simpljoin1.\n    rewrite H1 in H; eauto.\n    rewrite H0 in H; eauto.\nQed.\n\nLemma Reg_upd :\n  forall M R F D rn w w' p,\n    (M, (R, F), D) |= rn |=> w ** p ->\n    (M, (RegMap.set rn (Some w') R, F), D) |= rn |=> w' ** p.\nProof.\n  intros.\n  simpl in H.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n  simpl in H.\n  simpljoin1.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  exists (empM, (RegMap.set rn (Some w') empR, f0), d0) (m0, (r0, f0), d0).\n  repeat (split; eauto).\n  eapply RegSet_same_addr_disj_stable; eauto.\n\n  rewrite indom_setR_merge_eq; eauto.\n  rewrite regset_twice; eauto.\n  eapply regset_l_l_indom; eauto.\nQed.\n\nLemma dom_eq_setR_stable :\n  forall  R rn w,\n    dom_eq R (set_R R rn w).\nProof.\n  intros.\n  unfold dom_eq.\n  split.\n  {\n    intros.\n    unfolds set_R.\n    destruct (is_indom rn R) eqn:Heqe.\n    {\n      unfolds RegMap.set.\n      unfold indom in *.\n      destruct_rneq.\n    }\n    {\n      eauto.\n    }\n  }\n  {\n    intros.\n    unfold set_R in *.\n    destruct (is_indom rn R) eqn:Heqe; eauto.\n    unfolds RegMap.set.\n    unfold indom in *.\n    destruct_rneq_H.\n    subst.\n    simpljoin1.\n    inversion H; subst.\n    unfold is_indom in *.\n    destruct (R rn); eauto; tryfalse.\n  }\nQed.\n\nLemma dom_eq_setRs_stable :\n  forall vl R,\n    dom_eq R (set_Rs R vl).\nProof.\n  intro vl.\n  induction vl; intros.\n  -\n    simpls; eauto.\n    eapply same_m_dom_eq; eauto.\n  -\n    destruct a.\n    simpl.\n    assert (dom_eq (set_R R r w) (set_Rs (set_R R r w) vl)).\n    eauto.\n    eapply dom_eq_trans with (m2 := (set_R R r w)); eauto.\n    eapply dom_eq_setR_stable; eauto.\nQed.\n\nDefinition precise_asrt (p : asrt) :=\n  forall M M' R R' F D,\n    (M, (R, F), D) |= p -> (M', (R', F), D) |= p ->\n    M = M' /\\ R = R'.\n\nLemma regst_precise :\n  forall rn w,\n    precise_asrt (rn |=> w).\nProof.   \n  unfold precise_asrt.\n  intros.\n  simpls.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  eauto.\nQed.\n\nLemma precise_star :\n  forall p1 p2,\n    precise_asrt p1 -> precise_asrt p2 ->\n    precise_asrt (p1 ** p2).\nProof. \n  intros.\n  unfolds precise_asrt.\n  intros.\n  sep_star_split_tac.\n  simpl in H4, H6.\n  simpljoin1.\n  eapply H in H1; eauto.\n  eapply H0 in H3; eauto.\n  subst.\n  eauto.\n  simpljoin1.\n  subst.\n  eauto.\nQed.\n\nLemma Reg_frm_precise :\n  forall (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) w0 w1 w2 w3 w4 w5 w6 w7,\n    precise_asrt (rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                      rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7).\nProof.\n  intros.\n  repeat (eapply precise_star; [eapply regst_precise | idtac]).\n  eapply regst_precise; eauto.\nQed.\n\n(*+ Lemmas for exe-delay +*)\nLemma dlyfrmfree_changeFrm_stable :\n  forall p M R F F' D,\n    DlyFrameFree p ->\n    (M, (R, F), D) |= p ->\n    (M, (R, F'), D) |= p.\nProof. \n  intro p.\n  induction p; intros; simpls; eauto; tryfalse.\n\n  simpljoin1. \n  eapply IHp1 in H0; eauto.\n\n  simpljoin1.\n  destruct H0.\n  eapply IHp1 in H0; eauto.\n  eapply IHp2 in H0; eauto.\n\n  simpljoin1.\n  destruct x, x0.\n  destruct p, p0.\n  destruct r, r0.\n  simpls.\n  simpljoin1. \n  exists (m, (r, F'), d0) (m0, (r0, F'), d0).\n  simpl.\n  repeat (split; eauto).\n \n  simpljoin1.\n  exists x.\n  specialize (H0 x).\n  eauto.\nQed.\n\n(*+ Lemmas for Frame List +*)\nLemma frame_asrt_upd :\n  forall M R D id id' F F',\n    (M, (R, F), D) |= {| id, F |} ->\n    exists R', (M, (R', F'), D) |= {| id', F' |} /\\ dom_eq R R'.\nProof. \n  intros.\n  simpls.\n  simpljoin1.\n  unfolds regSt.\n  simpljoin1.\n  simpls.\n  exists (RegMap.set cwp (Some id') empR).\n  repeat (split; eauto).\n  {\n    subst.\n    intros.\n    clear - H.\n    unfold indom in *.\n    simpljoin1.\n    unfolds RegMap.set.\n    destruct_rneq_H.\n  }\n  {\n    subst.\n    intros.\n    clear - H.\n    unfold indom in *.\n    simpljoin1.\n    unfolds RegMap.set.\n    destruct_rneq_H.\n  }\nQed.\n\nLemma asrt_FrmFree_changefrm_stable :\n  forall p M R F F' D,\n    (M, (R, F), D) |= p -> ~ indom cwp R ->\n    (M, (R, F'), D) |= p.\nProof.\n  intros p.\n  induction p; intros; simpl; eauto; tryfalse.\n\n  -\n    simpl in H.\n    simpljoin1.\n    exists x.\n    repeat (split; eauto).\n    destruct H2.\n    left.\n    eapply regdlySt_changeFrm_stable; eauto.\n    eauto.\n\n  - \n    simpl in H.\n    simpljoin1.\n    unfolds regSt.\n    simpls.\n    simpljoin1.\n    false.\n    eapply H0.\n    eapply regset_l_l_indom; eauto.\n\n  - \n    simpl in H0.\n    simpljoin1.\n    simpl in H. \n    destruct H.\n    eauto.\n    \n  - \n    simpl in H.\n    destruct H.\n    eauto.\n    eauto.\n\n  -\n    simpl in H.\n    simpljoin1.\n    destruct_state x.\n    destruct_state x0.\n    simpls.\n    simpljoin1.\n    exists (m, (r, F'), d0) (m0, (r0, F'), d0).\n    simpl.\n    repeat (split; eauto).\n    eapply IHp1; eauto.\n    intro.\n    eapply H0.\n    eapply indom_merge_still; eauto.\n    eapply IHp2; eauto.\n    intro.\n    eapply H0.\n    eapply indom_merge_still2; eauto.\n    \n  -\n    simpljoin1; eauto.\n    simpl in H0.\n    simpljoin1; eauto.\nQed.\n\nLemma reg_st_fetch_frame :\n  forall (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) w0 w1 w2 w3 w4 w5 w6 w7\n    M R F D,\n    (M, (R, F), D)\n      |= rr0 |=> w0 **\n      rr1 |=> w1 **\n      rr2 |=> w2 ** rr3 |=> w3 ** rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n    fetch_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 =\n    Some ([[w0, w1, w2, w3, w4, w5, w6, w7]]).\nProof.\n  intros.\n  unfold fetch_frame.\n\n  assert (R rr0 = Some w0).\n  {\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr1 = Some w1).\n  {\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr2 = Some w2).\n  {\n    eapply sep_star_assoc in H.\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr3 = Some w3).\n  {\n    do 2 eapply sep_star_assoc in H.\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr4 = Some w4).\n  {\n    do 3 eapply sep_star_assoc in H.\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr5 = Some w5).\n  {\n    do 4 eapply sep_star_assoc in H.\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr6 = Some w6).\n  {\n    do 5 eapply sep_star_assoc in H.\n    eapply sep_star_lift in H.\n    eapply rn_st_v_eval_reg_v; eauto.\n  }\n  assert (R rr7 = Some w7).\n  {\n    do 6 eapply sep_star_assoc in H.\n    eapply sep_star_sym in H.\n    eapply rn_st_v_eval_reg_v in H; eauto.\n  }\n  \n  rewrite H0; eauto.\n  rewrite H1; eauto.\n  rewrite H2; eauto.\n  rewrite H3; eauto.\n  rewrite H4; eauto.\n  rewrite H5; eauto.\n  rewrite H6; eauto.\n  rewrite H7; eauto.\nQed.\n\nLtac fetch_frame_merge_solve1 :=\n  match goal with\n  | H : context [?R ?rr] |- _ =>\n    let Heqe := fresh in\n    destruct (R rr) eqn:Heqe;\n    [eapply disj_in_m1_merge_still in Heqe;\n     [rewrite Heqe; simpl; fetch_frame_merge_solve1 | eauto]\n    | tryfalse]\n  | _ => idtac\n  end.\n\nLtac fetch_frame_merge_solve2 :=\n  match goal with\n  | H : context [?R ?rr] |- _ =>\n    let Heqe := fresh in\n    destruct (R rr) eqn:Heqe;\n    [eapply disj_in_m2_merge_still in Heqe;\n     [rewrite Heqe; simpl; fetch_frame_merge_solve2 | eauto]\n    | tryfalse]\n  | _ => idtac\n  end.\n\nLemma fetch_frm_disj_merge_still1 :\n  forall R R1 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    fetch_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm ->\n    disjoint R R1 ->\n    fetch_frame (merge R R1) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm.\nProof. \n  intros.\n  unfolds fetch_frame.\n  fetch_frame_merge_solve1.\n  inversion H.\n  eauto.\nQed.\n\nLemma fetch_frm_disj_merge_still2 :\n  forall R R1 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    fetch_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm ->\n    disjoint R1 R ->\n    fetch_frame (merge R1 R) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm.\nProof.\n  intros.\n  unfolds fetch_frame.\n  fetch_frame_merge_solve2.\n  inversion H.\n  eauto.\nQed.\n\nLtac eval_reg_merge_solve1 :=\n  match goal with\n  | H : context [?R ?rn] |- context [(merge ?R ?R') ?rn] =>\n    let Heqe := fresh in\n    destruct (R rn) eqn:Heqe;\n    [ eapply get_vl_merge_still in Heqe; eauto;\n      try rewrite Heqe; eval_reg_merge_solve1 | tryfalse]\n  | _ => idtac\n  end.\n\nLtac eval_reg_merge_solve2 :=\n  match goal with\n  | H : context [?R ?rn] |- context [(merge ?R' ?R) ?rn] =>\n    let Heqe := fresh in\n    destruct (R rn) eqn:Heqe;\n    [ eapply get_vl_merge_still2 in Heqe; eauto;\n      try rewrite Heqe; eval_reg_merge_solve2 | tryfalse]\n  | _ => idtac\n  end.\n\nLemma fetch_frame_disj_merge_stable1 :\n  forall R1 R2 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    disjoint R1 R2 ->\n    fetch_frame R1 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm ->\n    fetch_frame (merge R1 R2) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm.\nProof.\n  intros.\n  unfolds fetch_frame.\n\n  eval_reg_merge_solve1.\n  eauto.\nQed.\n\nLemma fetch_frame_disj_merge_stable2 :\n  forall R1 R2 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    disjoint R1 R2 ->\n    fetch_frame R2 rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm ->\n    fetch_frame (merge R1 R2) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm.\nProof.\n  intros.\n  unfolds fetch_frame.\n\n  eval_reg_merge_solve2.\n  eauto.\nQed.\n\nLemma disjoint_setfrm_still :\n  forall R r rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    disjoint R r ->\n    disjoint (set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm) r.\nProof. \n  intros.\n  unfold set_frame.\n  destruct fm.\n  simpl.\n  repeat (eapply disjoint_setR_still1; eauto).\nQed.\n\nLemma dom_eq_set_frame_stable2 :\n  forall R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    dom_eq R (set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intros.\n  unfold set_frame.\n  destruct fm.\n  eapply dom_eq_setRs_stable; eauto.\nQed.\n\nLemma disjoint_setfrm_still2 :\n  forall R r (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) fm,\n    disjoint R r ->\n    disjoint R (set_frame r rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intros.\n  eapply disj_dom_eq_still; eauto.\n  eapply same_m_dom_eq; eauto.\n  eapply dom_eq_set_frame_stable2; eauto.\nQed.\n\nLemma disjoint_setwin_still :\n  forall R r fm1 fm2 fm3,\n    disjoint R r ->\n    disjoint (set_window R fm1 fm2 fm3) r.\nProof.\n  intros.\n  unfold set_window.\n  repeat (eapply disjoint_setfrm_still; eauto).\nQed.\n\nLemma fetch_disj_merge_still1 :\n  forall R R1 fms,\n    fetch R = Some fms ->\n    disjoint R R1 ->\n    fetch (merge R R1) = Some fms.\nProof.\n  intros.\n  unfolds fetch.\n  destruct (fetch_frame R r8 r9 r10 r11 r12 r13 r14 r15) eqn:Heqe1; tryfalse.\n  eapply fetch_frm_disj_merge_still1 in Heqe1; eauto.\n  rewrite Heqe1. \n  destruct (fetch_frame R r16 r17 r18 r19 r20 r21 r22 r23) eqn:Heqe2; tryfalse.\n  eapply fetch_frm_disj_merge_still1 in Heqe2; eauto.\n  rewrite Heqe2.\n  destruct (fetch_frame R r24 r25 r26 r27 r28 r29 r30 r31) eqn:Heqe3; tryfalse.\n  eapply fetch_frm_disj_merge_still1 in Heqe3; eauto.\n  rewrite Heqe3; eauto.\nQed.\n\nLemma fetch_disj_merge_still2 :\n  forall R R1 fms,\n    fetch R = Some fms ->\n    disjoint R1 R ->\n    fetch (merge R1 R) = Some fms.\nProof.\n  intros.\n  unfolds fetch.\n  destruct (fetch_frame R r8 r9 r10 r11 r12 r13 r14 r15) eqn:Heqe1; tryfalse.\n  eapply fetch_frm_disj_merge_still2 in Heqe1; eauto.\n  rewrite Heqe1. \n  destruct (fetch_frame R r16 r17 r18 r19 r20 r21 r22 r23) eqn:Heqe2; tryfalse.\n  eapply fetch_frm_disj_merge_still2 in Heqe2; eauto.\n  rewrite Heqe2.\n  destruct (fetch_frame R r24 r25 r26 r27 r28 r29 r30 r31) eqn:Heqe3; tryfalse.\n  eapply fetch_frm_disj_merge_still2 in Heqe3; eauto.\n  rewrite Heqe3; eauto.\nQed.\n\nLemma OutRegs_fetch :\n  forall M R F D fm,\n    (M, (R, F), D) |= OutRegs fm ->\n    fetch_frame R r8 r9 r10 r11 r12 r13 r14 r15 = Some fm.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm.\n  eapply reg_st_fetch_frame; eauto.\nQed.\n\nLemma LocalRegs_fetch :\n  forall M R F D fm,\n    (M, (R, F), D) |= LocalRegs fm ->\n    fetch_frame R r16 r17 r18 r19 r20 r21 r22 r23 = Some fm.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm.\n  eapply reg_st_fetch_frame; eauto.\nQed.\n\nLemma InRegs_fetch :\n  forall M R F D fm,\n    (M, (R, F), D) |= InRegs fm ->\n    fetch_frame R r24 r25 r26 r27 r28 r29 r30 r31 = Some fm.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm.\n  eapply reg_st_fetch_frame; eauto.\nQed.\n\nLemma Regs_fetch :\n  forall M R F D fm1 fm2 fm3,\n    (M, (R, F), D) |= Regs fm1 fm2 fm3 ->\n    fetch R = Some [fm1; fm2; fm3].\nProof.\n  intros.\n  unfolds Regs.\n  eapply sep_star_split in H.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n  eapply sep_star_split in H0.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x0.\n\n  simpl in H1, H3.\n  simpljoin1.\n\n  eapply OutRegs_fetch in H; eauto.\n  eapply LocalRegs_fetch in H0; eauto.\n  eapply InRegs_fetch in H2; eauto.\n\n  unfold fetch.\n\n  eapply fetch_frame_disj_merge_stable1 with (R2 := merge r1 r2) in H; eauto.\n  rewrite H.\n\n  eapply fetch_frame_disj_merge_stable1 with (R2 := r2) in H0; eauto.\n  eapply fetch_frame_disj_merge_stable2 in H0; eauto.\n  rewrite H0; eauto.\n\n  eapply fetch_frame_disj_merge_stable2 with (R1 := r1) in H2; eauto.\n  eapply fetch_frame_disj_merge_stable2 with (R1 := r) in H2; eauto.\n\n  rewrite H2; eauto.\nQed.\n\nLemma indom_setfrm_still :\n  forall l R fm rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7,\n    indom l R ->\n    indom l (set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intros.\n  unfold set_frame.\n  destruct fm; eauto.\n  simpl.\n  repeat (eapply indom_setR_still); eauto.\nQed.\n  \nLemma indom_setwin_still :\n  forall l R fm1 fm2 fm3,\n    indom l R ->\n    indom l (set_window R fm1 fm2 fm3).\nProof.\n  intros.\n  unfold set_window.\n  repeat (eapply indom_setfrm_still; eauto).\nQed.\n\nLemma indoms_set_frm_still :\n  forall (vl : list GenReg) (R : RegFile) fm (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg),\n    indoms vl R ->\n    indoms vl (set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intro vl.\n  induction vl; intros.\n  -\n    simpls. eauto.\n  -\n    simpls.\n    simpljoin1.\n    split.\n    eapply indom_setfrm_still; eauto.\n    eauto.\nQed.\n\nLemma regfrm_indoms :\n  forall M R F D (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg)\n    (w0 w1 w2 w3 w4 w5 w6 w7 : Word),\n    (M, (R, F), D) |=\n                   rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                   rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n    indoms [rr0; rr1; rr2; rr3; rr4; rr5; rr6; rr7] R.\nProof.\n  intros.\n  simpl.\n  \n  split.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  do 2 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  do 3 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  do 4 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  do 5 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  split.\n  do 6 eapply sep_star_assoc in H.\n  eapply sep_star_sym in H.\n  eapply rn_st_v_eval_reg_v in H.\n  unfold indom; eauto.\n\n  eauto.\nQed.\n\nLemma OutRegs_indoms :\n  forall M R F D fm,\n    (M, (R, F), D) |= OutRegs fm ->\n    indoms [r8; r9; r10; r11; r12; r13; r14; r15] R.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm.\n  eapply regfrm_indoms; eauto.\nQed.\n\nLemma LocalRegs_indoms :\n  forall M R F D fm,\n    (M, (R, F), D) |= LocalRegs fm ->\n    indoms [r16; r17; r18; r19; r20; r21; r22; r23] R.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm.\n  eapply regfrm_indoms; eauto.\nQed.\n\nLemma InRegs_indoms :\n  forall M R F D fm,\n    (M, (R, F), D) |= InRegs fm ->\n    indoms [r24; r25; r26; r27; r28; r29; r30; r31] R.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm.\n  eapply regfrm_indoms; eauto.\nQed.\n\nLemma fetch_some_set_frm_merge_eq :\n  forall (R r : RegFile) fm (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg),\n    indoms [rr0; rr1; rr2; rr3; rr4; rr5; rr6; rr7] R ->\n    set_frame (merge R r) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm =\n    merge (set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm) r.\nProof.\n  intros.\n  unfolds set_frame.\n  destruct fm.\n  eapply indoms_setRs_merge_eq; eauto.\nQed.\n\nLemma fetch_some_set_frm_merge_eq2 :\n  forall (R r : RegFile) fm (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg),\n    disjoint R r ->\n    indoms [rr0; rr1; rr2; rr3; rr4; rr5; rr6; rr7] r ->\n    set_frame (merge R r) rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm =\n    merge R (set_frame r rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intros.\n  unfolds set_frame.\n  destruct fm.\n  eapply indoms_setRs_merge_eq2; eauto.\nQed.\n\nLemma setR_dom_eq2 :\n  forall R R' rn w,\n    dom_eq R R' ->\n    dom_eq R (set_R R' rn w).\nProof.\n  intros.\n  unfold dom_eq in *.\n  simpljoin1.\n  split.\n  {\n    intros.\n    eapply H in H1.\n    clear - H1.\n    unfold indom in *.\n    simpljoin1.\n    unfold set_R.\n    unfold is_indom.\n    destruct (R' rn); eauto.\n    unfold RegMap.set.\n    destruct_rneq.\n  }\n  {\n    intros.\n    eapply H0.\n    clear - H1.\n    unfold indom in *.\n    simpljoin1.\n    unfolds set_R.\n    unfold is_indom in *.\n    destruct (R' rn) eqn:Heqe; eauto.\n    unfolds RegMap.set.\n    destruct_rneq_H.\n    subst.\n    inversion H; subst.\n    eauto.\n  }\nQed.\n\nLemma setframe_dom_eq :\n  forall R R' (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) fm,\n    dom_eq R R' ->\n    dom_eq R (set_frame R' rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm).\nProof.\n  intros.\n  unfold set_frame.\n  destruct fm.\n  simpls.\n  repeat (eapply setR_dom_eq2; eauto).\nQed.\n\nLemma fetch_frm_indoms :\n  forall R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 fm,\n    fetch_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 = Some fm ->\n    indoms [rr0; rr1; rr2; rr3; rr4; rr5; rr6; rr7] R.\nProof. \n  intros.   \n  unfolds fetch_frame. \n  do 8\n    match goal with\n    | H : context [R ?v] |- _ =>\n      let Heqe := fresh in\n      (destruct (R v) eqn:Heqe; tryfalse)\n    end.\n  simpl.\n  unfold indom.\n  repeat (split; eauto).\nQed.\n\nLemma fetch_some_set_win_merge_eq :\n  forall R r fm1 fm1' fm2 fm2' fm3 fm3',\n    fetch R = Some [fm1 ; fm2 ; fm3] ->\n    set_window (merge R r) fm1' fm2' fm3' =\n    merge (set_window R fm1' fm2' fm3') r.\nProof. \n  intros.\n  unfolds set_window.\n  unfolds fetch.\n   \n  destruct (fetch_frame R r8 r9 r10 r11 r12 r13 r14 r15) eqn:Heqe1; tryfalse.\n  erewrite fetch_some_set_frm_merge_eq; eauto. \n  destruct (fetch_frame R r16 r17 r18 r19 r20 r21 r22 r23) eqn:Heqe2; tryfalse.\n  erewrite fetch_some_set_frm_merge_eq; eauto.\n  destruct (fetch_frame R r24 r25 r26 r27 r28 r29 r30 r31) eqn:Heqe3; tryfalse.\n  inversion H; subst.\n  erewrite fetch_some_set_frm_merge_eq; eauto.\n\n  {\n    clear - Heqe3.\n    eapply fetch_frm_indoms in Heqe3; eauto.\n    repeat (eapply indoms_set_frm_still; eauto).\n  }\n\n  {\n    clear - Heqe2. \n    eapply fetch_frm_indoms in Heqe2; eauto.\n    eapply indoms_set_frm_still; eauto.\n  }\n\n  {\n    eapply fetch_frm_indoms in Heqe1; eauto.\n  }\nQed.\n\nLemma set_win_merge1 :\n  forall (R1 R2 : RegFile) fm1 fm2 fm3,\n    indoms Fmr R1 ->\n    disjoint R1 R2 ->\n    set_window (merge R1 R2) fm1 fm2 fm3 = merge (set_window R1 fm1 fm2 fm3) R2.\nProof.  \n  intros.\n  unfolds set_window.\n  rewrite fetch_some_set_frm_merge_eq; eauto.\n  rewrite fetch_some_set_frm_merge_eq; eauto.\n  rewrite fetch_some_set_frm_merge_eq; eauto.\n\n  do 2 eapply indoms_set_frm_still; eauto.\n  simpls.\n  simpljoin1.\n  repeat (split; eauto).\n\n  eapply indoms_set_frm_still.\n  simpls.\n  simpljoin1.\n  repeat (split; eauto).\n\n  simpls.\n  simpljoin1.\n  repeat (split; eauto).\nQed.\n\nLemma set_win_merge2 :\n  forall (R1 R2 : RegFile) fm1 fm2 fm3,\n    indoms Fmr R2 ->\n    disjoint R1 R2 ->\n    set_window (merge R1 R2) fm1 fm2 fm3 = merge R1 (set_window R2 fm1 fm2 fm3).\nProof. \n  intros.\n  unfolds set_window.\n  rewrite fetch_some_set_frm_merge_eq2; eauto.\n  rewrite fetch_some_set_frm_merge_eq2; eauto.\n  rewrite fetch_some_set_frm_merge_eq2; eauto. \n\n  eapply disj_dom_eq_still; eauto.\n  eapply same_m_dom_eq; eauto.\n  repeat (eapply setframe_dom_eq; eauto).\n  eapply same_m_dom_eq; eauto.\n  \n  do 2 eapply indoms_set_frm_still; eauto.\n  simpl in H.\n  simpl.\n  simpljoin1.\n  repeat (split; eauto).\n\n  eapply disj_dom_eq_still; eauto.\n  eapply same_m_dom_eq; eauto.\n  repeat (eapply setframe_dom_eq; eauto).\n  eapply same_m_dom_eq; eauto.\n  eapply indoms_set_frm_still; eauto.\n  simpl in H.\n  simpljoin1.\n  simpl.\n  repeat (split; eauto).\n\n  simpls.\n  simpljoin1.\n  repeat (split; eauto).\nQed.\n\nLemma frm_empM :\n  forall M R F D (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg)\n    w0 w1 w2 w3 w4 w5 w6 w7,\n    (M, (R, F), D) |=\n                   rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                   rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n    M = empM.\nProof.\n  intros.\n  sep_star_split_tac.\n  simpls.\n  simpljoin1.\n  unfolds regSt.\n  simpls.\n  simpljoin1.\n  clear.\n  repeat (eapply empM_merge_still_l; eauto).\nQed.\n\nLemma OutRegs_empM :\n  forall M R F D fm,\n    (M, (R, F), D) |= OutRegs fm ->\n    M = empM.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm.\n  eapply frm_empM; eauto.\nQed.\n\nLemma LocalRegs_empM :\n  forall M R F D fm,\n    (M, (R, F), D) |= LocalRegs fm ->\n    M = empM.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm.\n  eapply frm_empM; eauto.\nQed.\n\nLemma InRegs_empM :\n  forall M R F D fm,\n    (M, (R, F), D) |= InRegs fm ->\n    M = empM.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm.\n  eapply frm_empM; eauto.\nQed.\n\nLemma Reg_frm_upd :\n  forall M R R' F D (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) \n    w0 w1 w2 w3 w4 w5 w6 w7 w0' w1' w2' w3' w4' w5' w6' w7',\n    (M, (R, F), D) |=\n                   rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                   rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n    (M, (R', F), D) |=\n                    rr0 |=> w0' ** rr1 |=> w1' ** rr2 |=> w2' ** rr3 |=> w3' **\n                    rr4 |=> w4' ** rr5 |=> w5' ** rr6 |=> w6' ** rr7 |=> w7' ->\n    R' = set_frame R rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7\n                   ([[w0', w1', w2', w3', w4', w5', w6', w7']]).\nProof.\n  intros.\n\n  lets Hindom : regfrm_indoms H ___; eauto.\n  eapply Reg_upd with (w' := w0') in H.\n\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w1') in H.\n  eapply sep_star_lift in H.\n   \n  eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w2') in H.\n  eapply sep_star_lift in H.\n  eapply sep_star_assoc2 in H; eauto.\n\n  do 2 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w3') in H.\n  eapply sep_star_lift in H.\n  do 2 eapply sep_star_assoc2 in H; eauto.\n\n  do 3 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w4') in H.\n  eapply sep_star_lift in H.\n  do 3 eapply sep_star_assoc2 in H; eauto.\n\n  do 4 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w5') in H.\n  eapply sep_star_lift in H.\n  do 4 eapply sep_star_assoc2 in H; eauto.\n\n  do 5 eapply sep_star_assoc in H.\n  eapply sep_star_lift in H.\n  eapply Reg_upd with (w' := w6') in H.\n  eapply sep_star_lift in H.\n  do 5 eapply sep_star_assoc2 in H; eauto.\n\n  do 6 eapply sep_star_assoc in H.\n  eapply sep_star_sym in H.\n  eapply Reg_upd with (w' := w7') in H.\n  eapply sep_star_sym in H.\n  do 6 eapply sep_star_assoc2 in H.\n\n  lets Ht : Reg_frm_precise ___; eauto.\n  unfolds precise_asrt.  \n  eapply Ht in H; eauto.\n  simpljoin1.\n  subst.\n  unfold set_frame.\n  unfold set_Rs.\n\n  simpl in Hindom.\n  simpljoin1.\n  do 8 (rewrite indom_setR_eq_RegMap_set; eauto;\n        try (repeat eapply indom_regset_still; eauto)).\nQed.\n\nLemma OutRegs_setframe :\n  forall M R R' F D fm fm',\n    (M, (R, F), D) |= OutRegs fm ->\n    (M, (R', F), D) |= OutRegs fm' ->\n    R' = set_frame R r8 r9 r10 r11 r12 r13 r14 r15 fm'.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm, fm'.    \n  eapply Reg_frm_upd; eauto.\nQed.\n\nLemma LocalRegs_setframe :\n  forall M R R' F D fm fm',\n    (M, (R, F), D) |= LocalRegs fm ->\n    (M, (R', F), D) |= LocalRegs fm' ->\n    R' = set_frame R r16 r17 r18 r19 r20 r21 r22 r23 fm'.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm, fm'.    \n  eapply Reg_frm_upd; eauto.\nQed.\n\nLemma InRegs_setframe :\n  forall M R R' F D fm fm',\n    (M, (R, F), D) |= InRegs fm ->\n    (M, (R', F), D) |= InRegs fm' ->\n    R' = set_frame R r24 r25 r26 r27 r28 r29 r30 r31 fm'.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm, fm'.    \n  eapply Reg_frm_upd; eauto.\nQed.\n\nLemma set_window_res :\n  forall M R R' F D fm1 fm2 fm3 fm1' fm2' fm3',\n    (M, (R, F), D) |= Regs fm1 fm2 fm3 ->\n    (M, (R', F), D) |= Regs fm1' fm2' fm3' ->\n    set_window R fm1' fm2' fm3' = R'.\nProof.\n  intros. \n  unfold set_window.\n\n  unfolds Regs.\n  eapply sep_star_split in H.\n  simpljoin1.\n  renames x to s1, x0 to s.\n  eapply sep_star_split in H1.\n  simpljoin1.\n  renames x to s2, x0 to s3.\n\n  eapply sep_star_split in H0.\n  simpljoin1.\n  renames x to s1', x0 to s'.\n  eapply sep_star_split in H5.\n  simpljoin1.\n  renames x to s2', x0 to s3'.\n\n  destruct_state s1.\n  destruct_state s2.\n  destruct_state s3.\n  destruct_state s.\n  simpl in H2, H4.\n  simpljoin1.\n\n  destruct_state s1'.\n  destruct_state s2'.\n  destruct_state s3'.\n  destruct_state s'.\n  simpl in H8, H6.\n  simpljoin1.\n  \n  rewrite fetch_some_set_frm_merge_eq.\n  rewrite fetch_some_set_frm_merge_eq2.\n\n  assert (set_frame (merge r0 r1) r16 r17 r18 r19 r20 r21 r22 r23 fm2' =\n          merge (set_frame r0 r16 r17 r18 r19 r20 r21 r22 r23 fm2') r1).\n  {\n    rewrite fetch_some_set_frm_merge_eq; eauto.\n    eapply LocalRegs_indoms; eauto.\n  }\n  rewrite H11.\n\n  rewrite fetch_some_set_frm_merge_eq2.\n  rewrite fetch_some_set_frm_merge_eq2.\n  \n  erewrite <- OutRegs_setframe with (R' := r2); eauto.\n  erewrite <- InRegs_setframe with (R' := r4); eauto. \n  erewrite <- LocalRegs_setframe with (R' := r3); eauto.\n\n  lets Hm0 : H1.\n  eapply LocalRegs_empM in Hm0; eauto.\n  subst.\n  lets Hm3 : H5.\n  eapply LocalRegs_empM in Hm3; eauto.\n  subst.\n  eauto.\n\n  lets Hm1 : H3.\n  eapply InRegs_empM in Hm1; eauto.\n  subst.\n  lets Hm4 : H7.\n  eapply InRegs_empM in Hm4; eauto.\n  subst.\n  eauto.\n\n  lets Hm : H.\n  eapply OutRegs_empM in Hm; eauto.\n  subst.\n  lets Hm0 : H0.\n  eapply OutRegs_empM in Hm0; eauto.\n  subst.\n  eauto.\n   \n  eapply disjoint_setfrm_still; eauto.\n  eapply InRegs_indoms; eauto.\n\n  eapply disjoint_setfrm_still; eauto.\n  eapply disj_sep_merge_still; eauto.\n  eapply disjoint_setfrm_still2; eauto. \n  eapply disj_merge_disj_sep1 in H9; eauto.\n  eapply disj_merge_disj_sep2 in H9; eauto.\n\n  eapply indoms_merge_still2; eauto.\n  eapply InRegs_indoms; eauto.\n\n  eapply disjoint_setfrm_still; eauto.\n\n  eapply indoms_merge_still1; eauto.\n  eapply LocalRegs_indoms; eauto.\n\n  eapply OutRegs_indoms; eauto.\nQed.\n\nLemma Regs_frm_frm_free :\n  forall M R F F' D rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 w0 w1 w2 w3 w4 w5 w6 w7,\n    (M, (R, F), D) |= rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                      rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7 ->\n    (M, (R, F'), D) |= rr0 |=> w0 ** rr1 |=> w1 ** rr2 |=> w2 ** rr3 |=> w3 **\n                       rr4 |=> w4 ** rr5 |=> w5 ** rr6 |=> w6 ** rr7 |=> w7.\nProof.\n  intros. \n  sep_star_split_tac.\n  simpl in H13, H11, H9, H7, H5, H2, H3.\n  simpljoin1.\n \n  do 7 (eapply disj_sep_star_merge; eauto).\nQed.\n\nLemma OutRegs_frm_free :\n  forall M R F F' D fm,\n    (M, (R, F), D) |= OutRegs fm ->\n    (M, (R, F'), D) |= OutRegs fm.\nProof.\n  intros.\n  unfolds OutRegs.\n  destruct fm.\n  eapply Regs_frm_frm_free; eauto.\nQed.\n\nLemma LocalRegs_frm_free :\n  forall M R F F' D fm,\n    (M, (R, F), D) |= LocalRegs fm ->\n    (M, (R, F'), D) |= LocalRegs fm.\nProof.\n  intros.\n  unfolds LocalRegs.\n  destruct fm.\n  eapply Regs_frm_frm_free; eauto.\nQed.\n\nLemma InRegs_frm_free :\n  forall M R F F' D fm,\n    (M, (R, F), D) |= InRegs fm ->\n    (M, (R, F'), D) |= InRegs fm.\nProof.\n  intros.\n  unfolds InRegs.\n  destruct fm.\n  eapply Regs_frm_frm_free; eauto.\nQed.\n\nLemma Regs_frm_free :\n  forall M R F F' D fm1 fm2 fm3,\n    (M, (R, F), D) |= Regs fm1 fm2 fm3 ->\n    (M, (R, F'), D) |= Regs fm1 fm2 fm3.\nProof.\n  intros.\n  unfolds Regs.\n  eapply sep_star_split in H; eauto.\n  simpljoin1.\n  eapply sep_star_split in H0; eauto.\n  simpljoin1.\n  destruct_state x.\n  destruct_state x1.\n  destruct_state x2.\n\n  simpl in H1, H3.\n  destruct_state x0.\n  simpljoin1.\n\n  eapply disj_sep_star_merge; eauto.\n  eapply OutRegs_frm_free; eauto.\n\n  eapply disj_sep_star_merge; eauto.\n  eapply LocalRegs_frm_free; eauto.\n  eapply InRegs_frm_free; eauto.\nQed.\n\nLemma Regs_indom_Fmr :\n  forall M R F D fm1 fm2 fm3,\n    (M, (R, F), D) |= Regs fm1 fm2 fm3 ->\n    indoms Fmr R.\nProof.\n  intros.\n  unfolds Regs.\n  sep_star_split_tac.\n  simpl in H2, H3.\n  simpljoin1.\n  \n  eapply OutRegs_indoms in H; eauto.\n  eapply LocalRegs_indoms in H0; eauto.\n  eapply InRegs_indoms in H1; eauto.\n\n  simpls.\n  simpljoin1.\n\n  repeat\n    (\n      split;\n      [\n        try solve [eapply indom_merge_still; eauto];\n        try solve [eapply indom_merge_still2; eapply indom_merge_still; eauto];\n        try solve [eapply indom_merge_still2; eapply indom_merge_still2; eauto] |\n        idtac\n      ]\n    ).\n  eauto.\nQed.\n\n(*+ Lemmas about instruction +*)\nLemma ins_exec_deterministic :\n  forall s s1 s2 i,\n    Q__ s (cntrans i) s1 -> Q__ s (cntrans i) s2 -> s1 = s2.\nProof. \n  intros.\n  destruct i.\n  - (* ld aexp rd *)\n    inversion H; inversion H0.\n    subst.\n    inversion H6; subst.\n    inversion H3; inversion H7.\n    subst.\n    rewrite H10 in H21.\n    inversion H21.\n    subst; eauto.\n    rewrite H12 in H23; inversion H23.\n    subst; eauto.\n    \n  - (* st rs aexp *)\n    inversion H. inversion H0.\n    subst.\n    inversion H6.\n    subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21.\n    subst; eauto.\n    rewrite H12 in H23; eauto.\n    inversion H23; eauto.\n\n  - (* nop *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    eauto.\n\n  - (* add rs aexp rd *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* sub rs aexp rd *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* subcc rs aexp rd *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H11 in H25.\n    inversion H25; subst.\n    rewrite H12 in H26.\n    inversion H26; subst.\n    eauto.\n\n  - (* and *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* andcc *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H11 in H25.\n    inversion H25; subst.\n    rewrite H12 in H26.\n    inversion H26; subst.\n    eauto.\n\n  - (* or *) \n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* sll *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* srl *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H10 in H21.\n    inversion H21; subst.\n    rewrite H12 in H23.\n    inversion H23; subst.\n    eauto.\n\n  - (* set *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    eauto.\n\n  - (* save *)  \n    inversion H; inversion H0; subst.\n    inversion H3.\n    inversion H3. \n    inversion H19.\n    inversion H28; subst.\n    rewrite H4 in H20.\n    inversion H20; subst.\n    rewrite H5 in H21.\n    inversion H21; subst.\n    rewrite H8 in H24.\n    inversion H24; subst.\n    rewrite H9 in H25.\n    inversion H25; subst.\n\n    assert (F'0 = F' /\\ fm0 = fm1 /\\ fm3 = fm2).\n    { \n      clear - H10.\n      eapply ls_leneq_cons in H10; eauto.\n      destruct H10.\n      inversion H0.\n      eauto. \n    }\n\n    destruct H1 as [HF [Hf1 Hf2] ].\n    subst.\n    rewrite H6 in H22.\n    inversion H22.\n    subst; eauto.\n\n  - (* restore *)\n    inversion H; inversion H0; subst.\n    inversion H3.\n    inversion H3.\n    inversion H19.\n    inversion H28; subst.\n    rewrite H4 in H20.\n    inversion H20; subst.\n    rewrite H5 in H21; subst.\n    inversion H21; subst.\n    rewrite H8 in H24.\n    inversion H24; subst.\n    rewrite H9 in H25.\n    inversion H25; subst.\n    rewrite H6 in H22.\n    inversion H22.\n    subst.\n    eauto.\n\n  - (* rd *) \n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H9 in H18.\n    inversion H18; subst; eauto.\n\n  - (* wr *)\n    inversion H; inversion H0; subst.\n    inversion H3.\n    inversion H3.\n    inversion H13.\n    inversion H16; subst; eauto.\n    rewrite H4 in H14.\n    inversion H14; subst.\n    rewrite H5 in H15.\n    inversion H15; subst.\n    eauto.\n\n  - (* getcwp *)\n    inversion H; inversion H0; subst.\n    inversion H6; subst.\n    inversion H3; inversion H7; subst.\n    rewrite H9 in H17.\n    inversion H17; subst.\n    eauto.\nQed.\n\nLemma ins_frm_property :\n  forall s1 s1' s2 s i,\n    state_union s1 s2 s -> (Q__ s1 (cntrans i) s1') ->\n    exists s' s2', state_union s1' s2' s' /\\ getmem s2 = getmem s2' /\\ getregs s2 = getregs s2'.\nProof.\n  intros.\n  destruct i.\n    \n  - (* ld *) \n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H. \n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g v) r, f), d).\n    exists (m, (r, f), d).\n    simpl. \n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* st *) \n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge (MemMap.set addr (Some v) M) m, (merge R' r, f), d).\n    exists (m, (r, f), d). \n    simpl.\n    repeat (split; eauto).\n    eapply disj_indom_memset_still; eauto.\n\n  - (* nop *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge R' r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n\n  - (* add *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 +\u1d62 v2) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* sub *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 -\u1d62 v2) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* subcc *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m,\n       (merge (set_Rs R [(Rr g0, v1 -\u1d62 v2);\n                         (Rpsr n, get_range 31 31 v1 -\u1d62 v2); (Rpsr z, iszero v1 -\u1d62 v2)]) r,\n      f), d).\n    exists (m, (r, f), d).\n    simpl. \n    repeat (split; eauto). \n    repeat (eapply disjoint_setR_still1; eauto).\n\n  - (* and *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 &\u1d62 v2) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* andcc *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m,\n       (merge (set_Rs R [(Rr g0, v1 &\u1d62 v2);\n                         (Rpsr n, get_range 31 31 v1 &\u1d62 v2); (Rpsr z, iszero v1 &\u1d62 v2)]) r,\n      f), d).\n    exists (m, (r, f), d).\n    simpl. \n    repeat (split; eauto). \n    repeat (eapply disjoint_setR_still1; eauto).\n\n  - (* or *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 |\u1d62 v2) r, f), d).\n    exists (m, (r, f), d).\n    simpl. \n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* sll *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 <<\u1d62 (get_range 0 4 v2)) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* srl *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g0 v1 >>\u1d62 (get_range 0 4 v2)) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* set *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g w) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* save *)\n    inversion H0; subst.\n    inversion H3.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M m,\n       (merge (set_Rs (set_window R fm1 fm2 fmo)\n                      [(Rpsr cwp, pre_cwp k); (Rr g0, v1 +\u1d62 v2)]) r,\n        fml :: fmi :: F'), d).\n    exists (m, (r, fml :: fmi :: F'), d).\n    simpl. \n    repeat (split; eauto).\n    repeat (eapply disjoint_setR_still); eauto.\n    do 2 eapply disjoint_setR_still1; eauto.\n    eapply disjoint_setwin_still; eauto.\n\n  - (* restore *)\n    inversion H0; subst.\n    inversion H3.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M m,\n       (merge (set_Rs (set_window R fmi fm1 fm2)\n                      [(Rpsr cwp, post_cwp k); (Rr g0, v1 +\u1d62 v2)]) r,\n        F' ++ fmo :: fml :: nil), d).\n    exists (m, (r, F' ++ fmo :: fml :: nil), d).\n    simpl.\n    repeat (split; eauto).\n    repeat (eapply disjoint_setR_still1); eauto.\n    eapply disjoint_setwin_still; eauto.\n\n  - (* rd *)\n    inversion H0; subst.\n    inversion H3; subst.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g v) r, f), d).\n    exists (m, (r, f), d).\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n\n  - (* wr *)\n    inversion H0; subst.\n    inversion H3.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1. \n    exists (merge M m, (merge R r, f), set_delay s0 (set_spec_reg s0 v1 xor v2) d).\n    exists (m, (r, f), set_delay s0 (set_spec_reg s0 v1 xor v2) d).\n    simpl.\n    repeat (split; eauto).\n\n  - (* getcwp *)\n    inversion H0; subst.\n    inversion H3.\n    destruct s2.\n    destruct p.\n    destruct r.\n    simpl in H.\n    simpljoin1.\n    exists (merge M' m, (merge (set_R R g v) r, f), d).\n    exists (m, (r, f), d).\n    simpls.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\nQed.\n\nLemma ins_safety_property :\n  forall s1 s1' s2 s i r,\n    state_union s1 s2 s -> (Q__ s1 (cntrans i) s1') -> s2 |= r -> DlyFrameFree r ->\n    exists s' s2', Q__ s (cntrans i) s' /\\ state_union s1' s2' s' /\\ s2' |= r.\nProof.\n  intros.\n  lets Ht : H.\n  eapply ins_frm_property in Ht; eauto.\n  simpljoin1.\n  renames x0 to s2', x to s'.\n  \n  destruct i.\n  \n  - (* ld *) \n    inversion H0; subst.\n    inversion H8; subst. \n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3.\n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g v) r1, f0), d0).\n    exists (m0, (r1, f0), d0). \n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Ld_step; eauto.\n    eapply eval_addrexp_merge_still; eauto.\n    eapply get_vl_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* st *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge (MemMap.set addr (Some v) M) m0, (merge R' r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply ST_step; eauto.\n    eapply eval_addrexp_merge_still; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_memset_merge_eq; eauto.\n\n  - (* nop *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge R' r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Nop_step; eauto.\n  \n  - (* add *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 +\u1d62 v2) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Add_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* sub *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 -\u1d62 v2) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Sub_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* subcc *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0,\n       (merge (set_R (set_R\n                        (set_R R g0 v1 -\u1d62 v2) n\n                        (get_range 31 31 v1 -\u1d62 v2)) z (iszero v1 -\u1d62 v2)) r1, f0), d0\n      ).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Subcc_step; try eapply indom_merge_still; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    simpl. \n    erewrite indom_setR_merge_eq1; eauto.\n    erewrite indom_setR_merge_eq1; repeat (eapply indom_setR_still; eauto).\n    erewrite indom_setR_merge_eq1; repeat (eapply indom_setR_still; eauto).\n    eauto.\n    eauto.\n    eauto.\n\n  - (* and *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 &\u1d62 v2) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply And_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* andcc *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0,\n       (merge (set_R (set_R\n                        (set_R R g0 v1 &\u1d62 v2) n\n                        (get_range 31 31 v1 &\u1d62 v2)) z (iszero v1 &\u1d62 v2)) r1, f0), d0\n      ).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Andcc_step; try eapply indom_merge_still; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    simpl.\n    erewrite indom_setR_merge_eq1; eauto.\n    erewrite indom_setR_merge_eq1; repeat (eapply indom_setR_still; eauto).\n    erewrite indom_setR_merge_eq1; repeat (eapply indom_setR_still; eauto).\n    eauto.\n    eauto.\n    eauto.\n\n  - (* or *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 |\u1d62 v2) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Or_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* sll *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 <<\u1d62 (get_range 0 4 v2)) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Sll_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* srl *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g0 v1 >>\u1d62 (get_range 0 4 v2)) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Srl_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* set *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g w) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns; eauto.\n    eapply Set_step; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n    \n  - (* Save *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M m0,\n       (merge (set_R (set_R (set_window R fm1 fm2 fmo) cwp (pre_cwp k)) g0 v1 +\u1d62 v2) r1,\n        fml :: fmi :: F'), d0\n      ).\n    exists (m0, (r1, fml :: fmi :: F'), d0).  \n    repeat (split; simpl; eauto).\n    eapply SSave; try eapply get_R_merge_still; eauto.\n    eapply fetch_disj_merge_still1; eauto.\n    eapply indom_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    simpl.\n    rewrite <- indom_setR_merge_eq1; eauto.\n    rewrite <- indom_setR_merge_eq1; eauto.\n    erewrite fetch_some_set_win_merge_eq; eauto.\n    eapply indom_setwin_still; eauto.\n    unfold indom.\n    clear - H9.\n    unfolds get_R.\n    destruct (R cwp); eauto.\n    eapply indom_setR_still; eauto.\n    eapply indom_setwin_still; eauto.\n    eapply dlyfrmfree_changeFrm_stable; eauto.\n\n  - (* Restore *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3. \n    simpljoin1.\n    simpls. \n    subst.\n    exists (merge M m0,\n       (merge (set_R (set_R (set_window R fmi fm1 fm2) cwp (post_cwp k)) g0 v1 +\u1d62 v2) r1,\n        F' ++ fmo :: fml :: nil), d0\n      ).\n    exists (m0, (r1, F' ++ fmo :: fml :: nil), d0).\n    repeat (split; simpl; eauto).\n    eapply RRestore; try eapply get_R_merge_still; eauto.\n    eapply fetch_disj_merge_still1; eauto.\n    eapply indom_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    simpl.\n    rewrite <- indom_setR_merge_eq1; eauto.\n    rewrite <- indom_setR_merge_eq1; eauto. \n    erewrite fetch_some_set_win_merge_eq; eauto.\n    eapply indom_setwin_still; eauto.\n    unfold indom.\n    clear - H9.\n    unfolds get_R.\n    destruct (R cwp); eauto.\n    eapply indom_setR_still; eauto.\n    eapply indom_setwin_still; eauto.\n    eapply dlyfrmfree_changeFrm_stable; eauto.\n\n  - (* rd *)\n    inversion H0; subst.\n    inversion H8; subst.\n    destruct s2, p, r0.\n    simpl in H.\n    simpljoin1.\n    destruct s2', p, r1.\n    simpl in H3.\n    simpljoin1.\n    simpls.\n    subst.\n    exists (merge M' m0, (merge (set_R R g v) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns.\n    eapply Rd_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n\n  - (* wr *)\n    inversion H0; subst.\n    inversion H8.\n    destruct s2, p, r0.\n    destruct s2', p, r1.\n    simpls.\n    simpljoin1.\n    exists (merge M m0, (merge R r1, f0), set_delay s0 (set_spec_reg s0 v1 xor v2) d).\n    exists (m0, (r1, f0), set_delay s0 (set_spec_reg s0 v1 xor v2) d).\n    repeat (split; simpl; eauto).\n    eapply Wr; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply eval_opexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    eapply dlyfrmfree_notin_changeDly_still; eauto.\n    eapply indom_m1_disj_notin_m2 with (m1 := R); eauto.\n\n  - (* getcwp *)\n    inversion H0; subst.\n    inversion H8.\n    destruct s2, p, r0.\n    destruct s2', p, r1.\n    simpls.\n    simpljoin1. \n    exists (merge M' m0, (merge (set_R R g v) r1, f0), d0).\n    exists (m0, (r1, f0), d0).\n    repeat (split; simpl; eauto).\n    eapply NormalIns.\n    eapply GetCwp_step; eauto.\n    eapply get_R_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\nQed.\n    \nLemma program_step_safety_property :\n  forall s1 s1' s2 s r pc pc' npc npc' C,\n    state_union s1 s2 s -> (P__ C (s1, pc, npc) (s1', pc', npc')) ->\n    s2 |= r -> DlyFrameFree r ->\n    exists s' s2',\n      P__ C (s, pc, npc) (s', pc', npc') /\\ state_union s1' s2' s' /\\\n      s2' |= r.\nProof.\n  intros.\n  destruct_state s1.\n  destruct_state s2.\n  destruct_state s.\n  simpl in H.\n  simpljoin1.\n  inversion H0; subst.\n  eapply exe_delay_safety_property in H7; eauto.\n  simpljoin1.\n  rename x into R1'.\n  inversion H15; subst.\n  - (** NTrans ins *)\n    eapply ins_safety_property in H17; eauto.\n    simpljoin1.\n    destruct_state x.\n    destruct_state x0.\n    do 2 eexists.\n    split.\n    econstructor.\n    eapply H5.\n    eapply NTrans; eauto.\n    split; eauto.\n    simpl.\n    repeat (split; eauto).\n  - (** jumpl *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Jumpl; eauto.\n    eapply eval_addrexp_merge_still; eauto.\n    eapply indom_merge_still; eauto.\n    split; eauto.\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n  - (** call *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Call; eauto.\n    eapply indom_merge_still; eauto.\n    split; eauto.\n    simpl.\n    repeat (split; eauto).\n    eapply disjoint_setR_still1; eauto.\n    rewrite indom_setR_merge_eq1; eauto.\n  - (** retl *)\n    do 2 eexists.\n    split. \n    econstructor; eauto.\n    eapply Retl; eauto.\n    eapply get_R_merge_still; eauto.\n    simpl.\n    repeat (split; eauto).\n  - (** be-true *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Be_true; eauto.\n    eapply get_R_merge_still; eauto.\n    simpls.\n    repeat (split; eauto).\n  - (** be-false *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Be_false; eauto.\n    eapply get_R_merge_still; eauto.\n    split; eauto.\n    simpls.\n    repeat (split; eauto).\n  - (** bne-true *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Bne_true; eauto.\n    eapply get_R_merge_still; eauto.\n    split; eauto.\n    simpls.\n    repeat (split; eauto).\n  - (** bne-false *)\n    do 2 eexists.\n    split.\n    econstructor; eauto.\n    eapply Bne_false; eauto.\n    eapply get_R_merge_still; eauto.\n    split; eauto.\n    simpls.\n    repeat (split; eauto).\nQed.\n\nLemma program_step_deterministic :\n  forall s s1 s2 C pc npc pc1 npc1 pc2 npc2,\n    P__ C (s, pc, npc) (s1, pc1, npc1) -> P__ C (s, pc, npc) (s2, pc2, npc2) ->\n    s1 = s2 /\\ pc1 = pc2 /\\ npc1 = npc2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  rewrite <- H4 in H5.\n  inversion H5; subst.\n  inversion H9; subst;\n    inversion H14; get_ins_diff_false; eauto.\n  -\n    eapply ins_exec_deterministic in H12; eauto.\n  -\n    rewrite H19 in H23.\n    inversion H23; eauto.\n  - \n    rewrite H19 in H21.\n    inversion H21; subst; eauto.\nQed.", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/framework/soundness/lemmas_ins.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18902097608368892}}
{"text": "Require Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.Equality.\nRequire Import SpecCert.Map.\nRequire Import SpecCert.Memory.\nRequire Import SpecCert.x86.Architecture.Architecture_func.\nRequire Import SpecCert.x86.Architecture.Architecture_rec.\nRequire Import SpecCert.x86.Architecture.MemoryController.\nRequire Import SpecCert.x86.Architecture.ProcessorUnit.\nRequire Import SpecCert.x86.Value.\n\nLemma update_proc_changes_only_proc\n      {Label: Type}\n      (a a':  Architecture Label)\n      (p:     ProcessorUnit)\n      (Heqa': a' = update_proc a p)\n  : memory_controller a = memory_controller a'\n    /\\ memory a = memory a'\n    /\\ cache a = cache a'.\nProof.\n  unfold update_proc in Heqa'.\n  rewrite Heqa'.\n  simpl.\n  repeat split; reflexivity.\nQed.\n\nLemma update_proc_is_proc\n      {Label: Type}\n      (a a':  Architecture Label)\n      (p:     ProcessorUnit)\n      (Heqa': a' = update_proc a p)\n  : proc a' = p.\nProof.\n  rewrite Heqa'.\n  unfold proc, update_proc.\n  reflexivity.\nQed.\n\nLemma update_memory_controller_changes_only_memory_controller\n      {Label: Type}\n      (a a':  Architecture Label)\n      (mc:    MemoryController)\n      (Heqa': a' = update_memory_controller a mc)\n  : proc a = proc a'\n    /\\ memory a = memory a'\n    /\\ cache a = cache a'.\nProof.\n  unfold update_memory_controller in Heqa'.\n  rewrite Heqa'.\n  simpl.\n  repeat split; reflexivity.\nQed.\n\nLemma update_memory_controller_is_memory_controller\n      {Label: Type}\n      (a a':  Architecture Label)\n      (mc:    MemoryController)\n      (Heqa': a' = update_memory_controller a mc)\n  : memory_controller a' = mc.\nProof.\n  rewrite Heqa'.\n  unfold memory_controller, update_memory_controller.\n  reflexivity.\nQed.\n\nLemma update_memory_changes_only_memory\n      {Label: Type}\n      (a a':  Architecture Label)\n      (ha:    HardwareAddress)\n      (c:     (Value*Label))\n      (Heqa': a' = update_memory_content a ha c)\n  : memory_controller a = memory_controller a'\n    /\\ proc a = proc a'\n    /\\ cache a = cache a'.\nProof.\n  repeat split;\n    unfold update_memory_content in Heqa';\n    rewrite Heqa';\n    unfold memory_controller, proc; reflexivity.\nQed.\n\nLemma update_ha_in_memory_changes_only_ha\n      {Label: Type}\n      (a:     Architecture Label)\n      (ha ha': HardwareAddress)\n      (c:      (Value*Label))\n      (Hdiff:  ~ eq ha ha')\n  : find_memory_content a ha' = find_memory_content (update_memory_content a ha c) ha'.\nProof.\n  apply update_memory_2.\n  trivial.\nQed.\n\nLemma update_ha_in_memory_is_ha\n      {Label: Type}\n      (a:     Architecture Label)\n      (ha:    HardwareAddress)\n      (c:      (Value*Label))\n  : find_memory_content (update_memory_content a ha c) ha = c.\nProof.\n  unfold find_memory_content.\n  apply update_memory_1.\nQed.\n\nLemma update_cache_content_is_find\n      {Label: Type}\n      (a:     Architecture Label)\n      (pa:    PhysicalAddress)\n      (c:      (Value*Label))\n  : find_cache_content (update_cache_content a pa c) pa = Some c.\nProof.\n  unfold find_cache_content, update_cache_content.\n  simpl.\n  apply update_is_find_in_cache.\nQed.\n\nLemma update_cache_changes_only_cache\n      {Label: Type}\n      (a a':  Architecture Label)\n      (pa:    PhysicalAddress)\n      (c:      (Value*Label))\n      (Heqa': a' = update_cache_content a pa c)\n  : proc a = proc a'\n    /\\ memory_controller a = memory_controller a'\n    /\\ memory a = memory a'.\nProof.\n  unfold update_cache_content in Heqa'.\n  rewrite Heqa'.\n  simpl.\n  intuition.\nQed.\n\nLemma update_ha_in_memory_changes_only_memory\n      {Label: Type}\n      (a a':  Architecture Label)\n      (ha:    HardwareAddress)\n      (c:      (Value*Label))\n      (Heqa': a' = update_memory_content a ha c)\n  : proc a = proc a'\n    /\\ memory_controller a = memory_controller a'\n    /\\ cache a = cache a'.\nProof.\n  unfold update_memory_content in Heqa'.\n  rewrite Heqa'.\n  simpl.\n  intuition.\nQed.\n\nLemma load_in_cache_from_memory_changes_only_mem_and_cache\n      {Label: Type}\n      (a a':  Architecture Label)\n      (pa:    PhysicalAddress)\n      (Heqa': a' = load_in_cache_from_memory a pa)\n  : proc a = proc a'\n    /\\ memory_controller a = memory_controller a'.\nProof.\n  unfold load_in_cache_from_memory in Heqa'.\n  destruct (cache_location_is_dirty_dec (cache a) pa).\n  + apply update_cache_changes_only_cache in Heqa'.\n    destruct Heqa' as [Hproc [Hmc Hmem]].\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))\n      as a'' eqn:Ha''.\n    apply update_ha_in_memory_changes_only_memory in Ha''.\n    destruct Ha'' as [Hproc' [Hmc' Hcache']].\n    rewrite <- Hproc' in Hproc.\n    rewrite <- Hmc' in Hmc.\n    intuition.\n  + apply update_cache_changes_only_cache in Heqa'.\n    destruct Heqa' as [Hproc [Hmc Hmem]].\n    intuition.\nQed.\n\nLemma update_cache_content_changes_only_index\n      {Label:  Type}\n      (a:      Architecture Label)\n      (pa pa': PhysicalAddress)\n      (c:      (Value*Label))\n      (Hneq:   ~ eq (phys_to_index pa) (phys_to_index pa'))\n  : find_cache_content (update_cache_content a pa c) pa'\n    = find_cache_content a pa'.\nProof.\n  unfold find_cache_content, update_cache_content.\n  unfold find_in_cache.\n  unfold global_update_in_cache.\n  unfold update_in_cache.\n  unfold load_in_cache.\n  simpl.\n  repeat destruct cache_hit_dec.\n  rewrite <- add_2; trivial.\n  assert (~ cache_hit\n            (add_in_map (cache a) (phys_to_index pa)\n                                  {| dirty := true; content := c; tag := pa |}) pa'\n         ); [\n    | intuition\n    ].\n  clear c0.\n  unfold not; intro Hhit'.\n  unfold cache_hit in Hhit'.\n  rewrite <- add_2 with (k:=phys_to_index pa)\n                                   (v:=\n                                      {|\n                                        dirty := true;\n                                        content := c;\n                                        tag := pa\n                                      |}\n                                   )\n    in Hhit'.\n  unfold cache_hit in n.\n  intuition.\n  trivial.\n  rewrite <- add_2; trivial.\n  assert (~ cache_hit\n            (add_in_map (cache a) (phys_to_index pa)\n                                  {| dirty := false; content := c; tag := pa |}) pa'\n         ); [\n    | intuition\n    ].\n  unfold not; intro Hhit'.\n  unfold cache_hit in Hhit'.\n  rewrite <- add_2 with (k:=phys_to_index pa)\n                                   (v:=\n                                      {|\n                                        dirty := false;\n                                        content := c;\n                                        tag := pa\n                                      |}\n                                   )\n    in Hhit'.\n  intuition.\n  trivial.\n  assert (cache_hit\n            (add_in_map (cache a) (phys_to_index pa)\n                                  {| dirty := true; content := c; tag := pa |}) pa'\n         ); [\n    | intuition\n    ].\n  unfold cache_hit.\n  rewrite <- add_2.\n  unfold cache_hit in c1.\n  apply eq_equal in c1.\n  rewrite <- c1.\n  apply eq_refl.\n  trivial.\n  reflexivity.\n  assert (cache_hit\n            (add_in_map (cache a) (phys_to_index pa)\n                                  {| dirty := false; content := c; tag := pa |}) pa'\n         ); [\n    | intuition\n    ].\n  unfold cache_hit.\n  rewrite <- add_2.\n  unfold cache_hit in c0.\n  apply eq_equal in c0.\n  rewrite <- c0.\n  apply eq_refl.\n  trivial.\n  reflexivity.\nQed.\n\nLemma update_same_index_is_find_in_cache\n      {Label:  Type}\n      (a:      Architecture Label)\n      (pa pa': PhysicalAddress)\n      (c:      (Value*Label))\n      (Heq:    eq (phys_to_index pa) (phys_to_index pa'))\n  : find_cache_location_content (update_cache_content a pa c) pa' = c.\nProof.\n  unfold find_cache_location_content, update_cache_content.\n  simpl.\n  apply eq_equal in Heq.\n  unfold find_in_cache_location, global_update_in_cache.\n  repeat destruct cache_hit_dec.\n  + unfold update_in_cache.\n    rewrite Heq.\n    rewrite add_1.\n    simpl.\n    reflexivity.\n  + unfold load_in_cache.\n    rewrite Heq.\n    rewrite add_1.\n    simpl.\n    reflexivity.\nQed.", "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/Architecture_proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.1890209689473546}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.semantics_lemmas.\nRequire Import sepcomp.effect_semantics.\nRequire Import sepcomp.structured_injections.\nRequire Import sepcomp.reach.\nRequire Import sepcomp.simulations.\n\n(** * Simulations Lemmas *)\n\n(** This file specializes [simulations] in a number of useful ways. *)\n\nSection Eff_INJ_SIMU_DIAGRAMS.\n  Context {F1 V1 C1 F2 V2 C2:Type}\n          {Sem1 : @EffectSem (Genv.t F1 V1) C1}\n          {Sem2 : @EffectSem (Genv.t F2 V2) C2}\n\n          {ge1: Genv.t F1 V1}\n          {ge2: Genv.t F2 V2}.\n(*  (CS1_RDO: forall c m c' m', corestep Sem1 ge1 c m c' m' ->\n                  (forall b, isGlobalBlock ge1 b = true -> Mem.valid_block m b) ->\n                  RDOnly_fwd m m' (ReadOnlyBlocks ge1))\n  (CS2_RDO: forall c m c' m', corestep Sem2 ge2 c m c' m' ->\n                  (forall b, isGlobalBlock ge2 b = true -> Mem.valid_block m b) ->\n                  RDOnly_fwd m m' (ReadOnlyBlocks ge2)).\n*)\n  Let core_data := C1.\n\n  Variable match_states: core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop.\n\n   Hypothesis genvs_dom_eq: genvs_domain_eq ge1 ge2.\n\n   Hypothesis ginfo_preserved : gvar_infos_eq ge1 ge2 /\\ findsymbols_preserved ge1 ge2.\n\n   Hypothesis match_sm_wd: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          SM_wd mu.\n\n   Hypothesis match_visible: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          REACH_closed m1 (vis mu).\n\n(* Removed in Jan 2015\n    Hypothesis match_restrict: forall d mu c1 m1 c2 m2 X,\n          match_states d mu c1 m1 c2 m2 ->\n          (forall b, vis mu b = true -> X b = true) ->\n          REACH_closed m1 X ->\n          match_states d (restrict_sm mu X) c1 m1 c2 m2.\n*)\n\n   Hypothesis match_validblocks: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          sm_valid mu m1 m2.\n\n   Hypothesis match_genv: forall d mu c1 m1 c2 m2 (MC:match_states d mu c1 m1 c2 m2),\n          meminj_preserves_globals ge1 (extern_of mu) /\\\n          (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true).\n\n   Hypothesis inj_initial_cores: forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n          initial_core Sem1 ge1 v vals1 = Some c1 ->\n          Mem.inject j m1 m2 ->\n          Forall2 (val_inject j) vals1 vals2 ->\n          meminj_preserves_globals ge1 j ->\n          globalfunction_ptr_inject ge1 j ->\n\n        (*the next two conditions are required to guarantee intialSM_wd*)\n         (forall b1 b2 d, j b1 = Some (b2, d) ->\n                          DomS b1 = true /\\ DomT b2 = true) ->\n         (forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true -> DomT b = true) ->\n\n         mem_respects_readonly ge1 m1 -> mem_respects_readonly ge2 m2 ->\n\n        (*the next two conditions ensure the initialSM satisfies sm_valid*)\n         (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n         (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n       exists c2,\n            initial_core Sem2 ge2 v vals2 = Some c2 /\\\n            match_states c1 (initial_SM DomS\n                                       DomT\n                                       (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n                                       (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n                           c1 m1 c2 m2.\n\n  Hypothesis inj_halted : forall cd mu c1 m1 c2 m2 v1,\n      match_states cd mu c1 m1 c2 m2 ->\n      halted Sem1 c1 = Some v1 ->\n\n      exists v2,\n             Mem.inject (as_inj mu) m1 m2 /\\\n             mem_respects_readonly ge1 m1 /\\ mem_respects_readonly ge2 m2 /\\\n             val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n             halted Sem2 c2 = Some v2.\n\n  Hypothesis inj_at_external :\n      forall mu c1 m1 c2 m2 e vals1,\n        match_states c1 mu c1 m1 c2 m2 ->\n        at_external Sem1 c1 = Some (e,vals1) ->\n        Mem.inject (as_inj mu) m1 m2\n        /\\ mem_respects_readonly ge1 m1 /\\ mem_respects_readonly ge2 m2\n        /\\ exists vals2,\n            Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\\n            at_external Sem2 c2 = Some (e,vals2)\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_states c1 nu c1 m1 c2 m2\n       /\\ Mem.inject (shared_of nu) m1 m2.\n\nSection EFF_INJ_SIMULATION_STAR_WF.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n             (forall\n               (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n                b ofs (Ub: U2 b ofs = true),\n               visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty))).\n\nLemma  inj_simulation_star_wf:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - ginfo_preserved. assumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\n(* RESTRICT : clear - match_restrict. intros. destruct H; subst. eauto.*)\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores . intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H\n         H0 H1 H2 H3 H4 H5 H6 H7 H8 H9)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram genvs_dom_eq.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n\n    [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split. eapply gsep_domain_eq; try eassumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [MRR1 [MRR2 [vals2 [VALS [AtExt2 SH]]]]]].\n  intuition. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ INC GSep\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt RDO1 RDO2\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]]; try eassumption.\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF.\n\nSection EFF_INJ_SIMULATION_STAR_WF_TYPED.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n            (forall\n             (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n             b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                U1 b1 (ofs-delta1) = true /\\\n                Mem.perm m1 b1 (ofs-delta1) Max Nonempty))).\n\nLemma  inj_simulation_star_wf_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - ginfo_preserved. assumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\n(* RESTRICT: clear - match_restrict. intros. destruct H; subst. eauto.*)\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram genvs_dom_eq.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n    [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split. eapply gsep_domain_eq; eassumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [MRR1 [MRR2 [vals2 [VALS [AtExt2 SH]]]]]].\n  intuition. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ HasTy1 HasTy2 INC GSep\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt RDO1 RDO2\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]]; try assumption.\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF_TYPED.\n\nSection EFF_INJ_SIMULATION_STAR.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             (forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma inj_simulation_star:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf.\n  apply  (well_founded_ltof _ measure).\n  apply inj_after_external.\n  clear - inj_effcore_diagram genvs_dom_eq.  intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  (*split. eapply globalsep_domain_eq. eassumption.*)\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR.\n\nSection EFF_INJ_SIMULATION_STAR_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             (forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n              visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma inj_simulation_star_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf_typed.\n  apply  (well_founded_ltof _ measure).\n  intros. eapply inj_after_external with (mu := mu); eauto.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [GSEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_TYPED.\n\nSection EFF_INJ_SIMULATION_PLUS.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n            ( forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                 b ofs (Ub: U2 b ofs = true),\n                 visTgt mu b = true /\\\n                 (locBlocksTgt mu b = false ->\n                     exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma inj_simulation_plus:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS.\n\nSection EFF_INJ_SIMULATION_PLUS_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (GSep: globals_separate ge2 nu nu')\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n        (RDO1: RDOnly_fwd m1 m1' (ReadOnlyBlocks ge1))\n        (RDO1: RDOnly_fwd m2 m2' (ReadOnlyBlocks ge2))\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          globals_separate ge1 mu mu' /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ (forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                  b ofs (Ub: U2 b ofs = true),\n                visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                    exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                    U1 b1 (ofs-delta1) = true /\\\n                    Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma inj_simulation_plus_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star_typed with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS_TYPED.\n\nEnd Eff_INJ_SIMU_DIAGRAMS.\n\nDefinition compose_sm (mu1 mu2 : SM_Injection) : SM_Injection :=\n Build_SM_Injection\n   (locBlocksSrc mu1) (locBlocksTgt mu2)\n   (pubBlocksSrc mu1) (pubBlocksTgt mu2)\n   (compose_meminj (local_of mu1) (local_of mu2))\n   (extBlocksSrc mu1) (extBlocksTgt mu2)\n   (frgnBlocksSrc mu1) (frgnBlocksTgt mu2)\n   (compose_meminj (extern_of mu1) (extern_of mu2)).\n\nLemma compose_sm_valid: forall mu1 mu2 m1 m2 m2' m3\n          (SMV1: sm_valid mu1 m1 m2) (SMV2: sm_valid mu2 m2' m3),\n       sm_valid (compose_sm mu1 mu2) m1 m3.\nProof.  split. apply SMV1. apply SMV2. Qed.\n\nLemma compose_sm_pub: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      pub_of (compose_sm mu12 mu23) =\n      compose_meminj (pub_of mu12) (pub_of mu23).\nProof. intros. unfold compose_sm, pub_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (pubSrc _ WD1 _ Heqd) as [b2 [d1 [LOC1 Tgt1]]]; simpl in *.\n    rewrite Heqd in LOC1. apply HypPub in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite LOC1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_DomSrc: forall mu12 mu23,\n  DomSrc (compose_sm mu12 mu23) = DomSrc mu12.\nProof. intros. unfold compose_sm, DomSrc; simpl. trivial. Qed.\n\nLemma compose_sm_DomTgt: forall mu12 mu23,\n  DomTgt (compose_sm mu12 mu23) = DomTgt mu23.\nProof. intros. unfold compose_sm, DomTgt; simpl. trivial. Qed.\n\nLemma compose_sm_foreign: forall mu12 mu23\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      foreign_of (compose_sm mu12 mu23) =\n      compose_meminj (foreign_of mu12) (foreign_of mu23).\nProof. intros. unfold compose_sm, foreign_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (fSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (frgnSrc _ WD1 _ Heqd) as [b2 [d1 [EXT1 Tgt1]]]; simpl in *.\n    rewrite Heqd in EXT1. apply HypFrg in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite EXT1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_priv: forall mu12 mu23,\n   priv_of (compose_sm mu12 mu23) =\n   compose_meminj (priv_of mu12) (local_of mu23).\nProof. intros. unfold priv_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_unknown: forall mu12 mu23,\n   unknown_of (compose_sm mu12 mu23) =\n   compose_meminj (unknown_of mu12) (extern_of mu23).\nProof. intros. unfold unknown_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (locBSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  remember (fSrc1 b) as q; destruct q; apply eq_sym in Heqq.\n    unfold compose_meminj. rewrite Heqd. rewrite Heqq. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. rewrite Heqq. trivial.\nQed.\n\nLemma compose_sm_local: forall mu12 mu23,\n   local_of (compose_sm mu12 mu23) =\n   compose_meminj (local_of mu12) (local_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_extern: forall mu12 mu23,\n   extern_of (compose_sm mu12 mu23) =\n   compose_meminj (extern_of mu12) (extern_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_shared: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12) (WD2:SM_wd mu23),\n      shared_of (compose_sm mu12 mu23) =\n      compose_meminj (shared_of mu12) (shared_of mu23).\nProof. intros. unfold shared_of.\n  rewrite compose_sm_pub; trivial.\n  rewrite compose_sm_foreign; trivial.\n  unfold join, compose_meminj. extensionality b.\n  remember (foreign_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    destruct (foreign_DomRng _ WD1 _ _ _ Heqf) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypFrg in F.\n    destruct (frgnSrc _ WD2 _ F) as [b3 [d2 [FRG2 TGT2]]].\n    rewrite FRG2. trivial.\n  remember (pub_of mu12 b) as d; destruct d; apply eq_sym in Heqd; trivial.\n    destruct p as [b2 d1].\n    destruct (pub_locBlocks _ WD1 _ _ _ Heqd) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypPub in B.\n    destruct (pubSrc _ WD2 _ B) as [b3 [d2 [PUB2 TGT2]]].\n    rewrite PUB2.\n    apply (pubBlocksLocalSrc _ WD2) in B.\n    apply (locBlocksSrc_frgnBlocksSrc _ WD2) in B.\n    unfold foreign_of. destruct mu23. simpl in *. rewrite B. trivial.\nQed.\n\nLemma compose_sm_wd: forall mu1 mu2 (WD1: SM_wd mu1) (WD2:SM_wd mu2)\n         (HypPub: forall b, pubBlocksTgt mu1 b = true ->\n                            pubBlocksSrc mu2 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu1 b = true ->\n                            frgnBlocksSrc mu2 b = true),\n      SM_wd (compose_sm mu1 mu2).\nProof. intros.\n  destruct mu1 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu2 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\nsplit; simpl in *.\napply WD1.\napply WD2.\n(*local_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [PUB1 [PUB2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply PUB1.\n         eapply WD2. apply PUB2.\n(*extern_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [EXT1 [EXT2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply EXT1.\n         eapply WD2. apply EXT2.\n(*pubSrc*)\n  intros.\n  destruct (pubSrc _ WD1 _ H) as [b2 [d1 [Loc1 Tgt1]]]. simpl in *.\n  apply HypPub in Tgt1.\n  destruct (pubSrc _ WD2 _ Tgt1) as [b3 [d2 [Loc2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Loc1. rewrite Loc2. auto.\n(*frgnSrc*)\n  intros.\n  destruct (frgnSrc _ WD1 _ H) as [b2 [d1 [Ext1 Tgt1]]]. simpl in *.\n  apply HypFrg in Tgt1.\n  destruct (frgnSrc _ WD2 _ Tgt1) as [b3 [d2 [Ext2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Ext1. rewrite Ext2. auto.\n(*locBlocksDomTgt*)\n  apply WD2.\n(*frgnBlocksDomTgt*)\n  apply WD2.\nQed.\n\nLemma compose_sm_as_inj: forall mu12 mu23 (WD1: SM_wd mu12) (WD2: SM_wd mu23)\n   (SrcTgtLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n   (SrcTgtExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n   as_inj (compose_sm mu12 mu23) =\n   compose_meminj (as_inj mu12) (as_inj mu23).\nProof. intros.\n  unfold as_inj.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_local.\n  unfold join, compose_meminj. extensionality b.\n  remember (extern_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    remember (extern_of mu23 b2) as d; destruct d; apply eq_sym in Heqd.\n      destruct p as [b3 d2]. trivial.\n    destruct (disjoint_extern_local _ WD1 b).\n       rewrite H in Heqf. discriminate.\n    rewrite H.\n    destruct (extern_DomRng _ WD1 _ _ _ Heqf) as [A B].\n    rewrite SrcTgtExt in B.\n    remember (local_of mu23 b2) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b3 d2].\n    destruct (local_DomRng _ WD2 _ _ _ Heqq) as [AA BB].\n    destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\n  remember (local_of mu12 b) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b2 d1].\n    destruct (local_DomRng _ WD1 _ _ _ Heqq) as [AA BB].\n    remember (extern_of mu23 b2) as d; destruct d; trivial; apply eq_sym in Heqd.\n      destruct p as [b3 d2].\n      destruct (extern_DomRng _ WD2 _ _ _ Heqd) as [A B].\n      rewrite SrcTgtLoc in BB.\n      destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\nQed.\n\nLemma compose_sm_intern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: intern_incr mu12 mu12')\n            (inc23: intern_incr mu23 mu23'),\n      intern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; simpl in *.\n    eapply compose_meminj_inject_incr.\n        apply inc12.\n        apply intern_incr_local; eassumption.\nsplit. rewrite (intern_incr_extern _ _ inc12).\n       rewrite (intern_incr_extern _ _ inc23).\n       trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma compose_sm_extern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: extern_incr mu12 mu12')\n            (inc23: extern_incr mu23 mu23')\n  (FRG': forall b1 b2 d1, foreign_of mu12' b1 = Some(b2,d1) ->\n         exists b3 d2, foreign_of mu23' b2 = Some(b3,d2))\n  (WD12': SM_wd mu12') (WD23': SM_wd mu23'),\n  extern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; intros.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_extern.\n  eapply compose_meminj_inject_incr.\n    apply inc12.\n    apply extern_incr_extern; eassumption.\nsplit; simpl.\n  rewrite (extern_incr_local _ _ inc12).\n  rewrite (extern_incr_local _ _ inc23).\n  trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma extern_incr_inject_incr:\n      forall nu12 nu23 nu' (WDnu' : SM_wd nu')\n          (EXT: extern_incr (compose_sm nu12 nu23) nu')\n          (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                      locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                      extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                      (forall b, pubBlocksTgt nu12 b = true ->\n                                 pubBlocksSrc nu23 b = true) /\\\n                      (forall b, frgnBlocksTgt nu12 b = true ->\n                                 frgnBlocksSrc nu23 b = true)),\n      inject_incr (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu').\nProof. intros.\n  intros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [Nu12 [Nu23 D]]]]]; subst; clear H.\n  unfold extern_incr in EXT. simpl in EXT.\n  destruct EXT as [EXT [LOC [extBSrc12 [extBTgt23 [locBSrc12 [locBTgt23 [pubBSrc12 [pubBTgt23 [frgnBSrc12 frgnBTgt23]]]]]]]]].\n  destruct (joinD_Some _ _ _ _ _ Nu12); clear Nu12.\n  (*extern12*)\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        apply join_incr_left. apply EXT.\n        unfold compose_meminj. rewrite H. rewrite H0. trivial.\n     (*local*)\n        destruct H0.\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLa _ _ _ H) as [? [? [? [? [? [? [? ?]]]]]]].\n        destruct (local_locBlocks _ GLb _ _ _ H1) as [? [? [? [? [? [? [? ?]]]]]]].\n        rewrite GLd in *. congruence.\n  (*local*)\n     destruct H.\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLb _ _ _ H1) as [? [? [? [? [? ?]]]]].\n        destruct (local_locBlocks _ GLa _ _ _ H0) as [? [? [? [? [? ?]]]]].\n        rewrite GLd in *. congruence.\n     (*local*)\n        destruct H1.\n        apply join_incr_right. eapply disjoint_extern_local. apply WDnu'.\n        rewrite <- LOC. unfold compose_meminj.\n        rewrite H0, H2. trivial.\nQed.\n\nLemma compose_sm_as_injD: forall mu1 mu2 b1 b3 d\n      (I: as_inj (compose_sm mu1 mu2) b1 = Some (b3, d))\n      (WD1: SM_wd mu1) (WD2: SM_wd mu2),\n      exists b2 d1 d2, as_inj mu1 b1 = Some(b2,d1) /\\\n                       as_inj mu2 b2 = Some(b3,d2) /\\\n                       d=d1+d2.\nProof. intros.\ndestruct (joinD_Some _ _ _ _ _ I); clear I.\n(*extern*)\n  rewrite compose_sm_extern in H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n      as [b2 [d1 [d2 [EXT1 [EXT2 D]]]]]; clear H.\n  exists b2, d1, d2.\n  split. apply join_incr_left. assumption.\n  split. apply join_incr_left. assumption.\n         assumption.\n(*local*)\n  destruct H.\n  rewrite compose_sm_extern in H.\n  rewrite compose_sm_local in H0.\n  destruct (compose_meminjD_Some _ _ _ _ _ H0)\n      as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; clear H0.\n  exists b2, d1, d2.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n         assumption.\nQed.\n\nLemma compose_sm_as_injD_None:\n  forall (mu1 mu2 : SM_Injection) b1,\n       SM_wd mu1 ->\n       SM_wd mu2 ->\n    (locBlocksTgt mu1 = locBlocksSrc mu2 /\\\n         extBlocksTgt mu1 = extBlocksSrc mu2) ->\n       as_inj (compose_sm mu1 mu2) b1 = None ->\n         as_inj mu1 b1 = None  \\/\n         exists b2 d, (as_inj mu1 b1 = Some (b2, d) /\\ as_inj mu2 b2 = None).\nProof.\nintros mu1 mu2 b1 SMWD1 SMWD2 [GLUEloc GLUEext].\nunfold as_inj, join, compose_sm; simpl.\ndestruct (Values.compose_meminj (extern_of mu1) (extern_of mu2) b1) as [[b2 delta]| ] eqn:extmap.\ndiscriminate.\ndestruct (Values.compose_meminj (local_of mu1) (local_of mu2) b1) as [[b2 delta]| ] eqn:locmap.\ndiscriminate.\nintros tautology.\ndestruct (compose_meminjD_None _ _ _ extmap) as [extmap' | [b' [ofs' [extmap1 extmap2]]]];\ndestruct (compose_meminjD_None _ _ _ locmap) as [locmap' | [b'' [ofs'' [locmap1 locmap2]]]].\n- rewrite extmap'; simpl.  rewrite locmap'; auto.\n- rewrite extmap'; simpl. right.\n  exists b'', ofs''. split.\n  + auto.\n  + destruct (extern_of mu2 b'') as [[b0 d]| ] eqn:extmap0.\n    * apply SMWD2 in extmap0. apply SMWD1 in locmap1.\n      destruct locmap1; destruct extmap0.\n      rewrite GLUEloc in *.\n      destruct SMWD2 as [disj_src _].\n      destruct (disj_src b'') as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\n    * assumption.\n- rewrite extmap1; simpl. right.\n  exists b', ofs'. split.\n  + reflexivity.\n  + rewrite extmap2; simpl.\n    destruct (local_of mu2 b') as [[b0 d]| ] eqn:locmap0.\n    * apply SMWD2 in locmap0. apply SMWD1 in extmap1.\n      destruct extmap1; destruct locmap0.\n      rewrite GLUEext in *.\n      destruct SMWD2 as [disj_src _].\n      destruct (disj_src b') as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\n    * assumption.\n- apply SMWD1 in extmap1; apply SMWD1 in locmap1.\n  destruct locmap1; destruct extmap1.\n  destruct SMWD1 as [disj_src _].\n  destruct (disj_src b1) as [theFalse | theFalse]; rewrite theFalse in *; discriminate.\nQed.\n\n(*\nLemma compose_sm_intern_separated:\n      forall mu12 mu12' mu23 mu23' m1 m2 m3\n        (inc12: intern_incr mu12 mu12')\n        (inc23: intern_incr mu23 mu23')\n        (InjSep12 : sm_inject_separated mu12 mu12' m1 m2)\n        (InjSep23 : sm_inject_separated mu23 mu23' m2 m3)\n        (WD12: SM_wd mu12) (WD12': SM_wd mu12') (WD23: SM_wd mu23) (WD23': SM_wd mu23')\n        (BlocksLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n        (BlocksExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n      sm_inject_separated (compose_sm mu12 mu23)\n                          (compose_sm mu12' mu23') m1 m3.\nProof. intros.\ndestruct InjSep12 as [AsInj12 [DomTgt12 Sep12]].\ndestruct InjSep23 as [AsInj23 [DomTgt23 Sep23]].\nsplit.\n  intros b1 b3 d; intros.\n  simpl.\n  destruct (compose_sm_as_injD _ _ _ _ _ H0)\n     as [b2 [d1 [d2 [AI12' [AI23' X]]]]]; subst; trivial; clear H0.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n  assert (DomSrc (compose_sm mu12' mu23') b1 = true /\\\n          DomTgt (compose_sm mu12' mu23') b3 = true).\n    rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n    split. eapply as_inj_DomRng; eassumption.\n           eapply as_inj_DomRng; eassumption.\n  destruct H0 as [DOM1 TGT3]; simpl in *.\n  assert (TGT2: DomTgt mu12' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD12'.\n  assert (DOMB2: DomSrc mu23' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD23'.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt in *.\n  remember (as_inj mu12 b1) as q.\n  destruct q; apply eq_sym in Heqq.\n    destruct p.\n    specialize (intern_incr_as_inj _ _ inc12 WD12' _ _ _ Heqq); intros.\n    rewrite AI12' in H0. apply eq_sym in H0. inv H0.\n    destruct (joinD_Some _ _ _ _ _ Heqq); clear Heqq.\n    (*extern12Some*)\n       assert (extern_of mu12' b1 = Some (b2, d1)).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         assert (extern_of mu23 b2 = Some (b3, d2)).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_extern in H2.\n         unfold compose_meminj in H2.\n         rewrite H0 in H2. rewrite H4 in H2. inv H2.\n       (*extern23'None*)\n         destruct H.\n         rewrite compose_sm_extern in H2.\n         destruct (compose_meminjD_None _ _ _ H2); clear H2.\n            rewrite H5 in H0. discriminate.\n         destruct H5 as [bb2 [dd1 [EXT12 EXT23]]].\n         rewrite EXT12 in H0. inv H0.\n         rewrite compose_sm_local in H3.\n         remember (local_of mu23 b2) as qq.\n         destruct qq; apply eq_sym in Heqqq.\n            destruct p.\n            specialize (intern_incr_local _ _ inc23); intros.\n            specialize (H0 _ _ _ Heqqq). rewrite H0 in H4. inv H4.\n            destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [A B].\n            destruct (local_DomRng _ WD23 _ _ _ Heqqq) as [AA BB].\n            rewrite BlocksExt in B.\n            destruct (disjoint_extern_local_Src _ WD23 b2); congruence.\n         destruct (AsInj23 b2 b3 d2).\n            apply joinI_None. assumption. assumption.\n            apply join_incr_right.\n              apply disjoint_extern_local. assumption.\n              assumption.\n         destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [XX YY].\n           rewrite BlocksExt in YY. unfold DomSrc in H0.\n           rewrite YY in H0. rewrite orb_comm in H0. discriminate.\n    (*extern12None*)\n       destruct H0.\n       assert (extern_of mu12' b1 = None).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       assert (local_of mu12' b1 = Some (b2, d1)).\n          eapply (intern_incr_local _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         destruct (local_DomRng _ WD12' _ _ _ H3) as [AA BB].\n         destruct (extern_DomRng _ WD23' _ _ _ H) as [A B].\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AAA BBB].\n         rewrite BlocksLoc in BBB.\n         assert (locBlocksSrc mu23' b2 = true). apply inc23. assumption.\n         destruct (disjoint_extern_local_Src _ WD23' b2); congruence.\n       (*extern23'None*)\n         destruct H.\n         assert (extern_of mu23 b2 = None).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_local in H5.\n         unfold compose_meminj in H5. rewrite H1 in H5.\n         remember (local_of mu23 b2).\n         destruct o. destruct p. inv H5. clear H5. apply eq_sym in Heqo.\n         clear H4.\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AA BB].\n         assert (DomSrc mu23 b2 = false /\\ DomTgt mu23 b3 = false).\n            eapply AsInj23.\n              apply joinI_None; assumption.\n              apply join_incr_right; try eassumption.\n                apply disjoint_extern_local; eassumption.\n         destruct H4.\n         destruct (local_locBlocks _ WD12 _ _ _ H1)\n           as [AAA [BBB [CCC [DDD [EEE FFF]]]]].\n         rewrite BlocksLoc in BBB. unfold DomSrc in H4.\n             rewrite BBB in H4. discriminate.\n   (*as_inj mu12 b1 = None*)\n     destruct (AsInj12 _ _ _ Heqq AI12'). split; trivial. clear H.\n     remember (as_inj mu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n       destruct p.\n       specialize (intern_incr_as_inj _ _ inc23 WD23' _ _ _ Heqd).\n       intros ZZ; rewrite AI23' in ZZ. apply eq_sym in ZZ; inv ZZ.\n       destruct (as_inj_DomRng _ _ _ _ Heqd WD23).\n       unfold DomSrc in H. unfold DomTgt in H1.\n       rewrite BlocksLoc, BlocksExt in H1. rewrite H1 in H; discriminate.\n     eapply AsInj23. eassumption. eassumption.\nsimpl.\n  split. apply DomTgt12. apply Sep23.\nQed.*)\n\nLemma vis_compose_sm: forall mu nu, vis (compose_sm mu nu) = vis mu.\nProof. intros. unfold vis. destruct mu; simpl. reflexivity. Qed.\n\nLemma restrict_compose: forall j k X,\n  restrict (compose_meminj j k) X = compose_meminj (restrict j X) k.\nProof. intros.\n  extensionality b.\n  unfold compose_meminj, restrict.\n  remember (X b) as d.\n  destruct d; trivial.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/sepcomp/simulations_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.18902096181102032}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import ITreeLang.\nRequire Import Sequential.\nRequire Import SequentialITree.\nRequire Import SequentialCompatibility.\nRequire Import SequentialAdequacy.\nRequire Import NoMix.\n\nSet Implicit Arguments.\n\n\nSection ADEQUACY.\n  Variable loc_na: Loc.t -> Prop.\n  Variable loc_at: Loc.t -> Prop.\n  Hypothesis LOCDISJOINT: forall loc (NA: loc_na loc) (AT: loc_at loc), False.\n\n  Theorem sequential_adequacy_context A B\n          (prog_src prog_tgt: (lang A).(Language.syntax))\n          (SIM: sim_seq_itree eq prog_src prog_tgt)\n          (ctx_seq: itree MemE.t A -> itree MemE.t B)\n          (ctx_ths: Threads.syntax) (tid: Ident.t)\n          (CTX: @itree_context loc_na loc_at A B ctx_seq)\n          (NOMIX_SRC: nomix loc_na loc_at _ ((lang A).(Language.init) prog_src))\n          (NOMIX_TGT: nomix loc_na loc_at _ ((lang A).(Language.init) prog_tgt))\n          (NOMIX_CTX:\n             forall tid lang syn\n                    (FIND: IdentMap.find tid ctx_ths = Some (existT _ lang syn)),\n               nomix loc_na loc_at lang (lang.(Language.init) syn))\n  :\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ (lang B) (ctx_seq prog_tgt)) ctx_ths))\n      <2=\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ (lang B) (ctx_seq prog_src)) ctx_ths)).\n  Proof.\n    eapply sequential_adequacy_concurrent_context; auto.\n    { eauto. }\n    { esplits. hexploit itree_sim_seq_context; eauto. ii. eapply H. }\n    { clear NOMIX_TGT. exploit itree_nomix_context; eauto. }\n    { clear NOMIX_SRC. exploit itree_nomix_context; eauto. }\n    { eauto. }\n  Qed.\nEnd ADEQUACY.\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/SequentialITreeAdequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18899095098846289}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export permission_bits ctrees.\nLocal Open Scope ctype_scope.\n\nNotation mtree K := (ctree K (pbit K)).\n\nSection operations.\n  Context `{Env K}.\n\n  Global Instance type_of_ctree : TypeOf (type K) (mtree K) := \u03bb w,\n    match w with\n    | MBase \u03c4b _ => baseT \u03c4b\n    | MArray \u03c4 ws => \u03c4.[length ws]\n    | MStruct t _ => structT t\n    | MUnion t _ _ _ | MUnionAll t _ => unionT t\n    end.\n  Inductive ctree_typed' (\u0393 : env K) (\u0394 : memenv K) :\n       mtree K \u2192 type K \u2192 Prop :=\n    | MBase_typed \u03c4b \u03b3bs :\n       \u2713{\u0393} \u03c4b \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192 length \u03b3bs = bit_size_of \u0393 (baseT \u03c4b) \u2192\n       ctree_typed' \u0393 \u0394 (MBase \u03c4b \u03b3bs) (baseT \u03c4b)\n    | MArray_typed \u03c4 n ws :\n       n = length ws \u2192 Forall (\u03bb w, ctree_typed' \u0393 \u0394 w \u03c4) ws \u2192 n \u2260 0 \u2192\n       ctree_typed' \u0393 \u0394 (MArray \u03c4 ws) (\u03c4.[n])\n    | MStruct_typed t w\u03b3bss \u03c4s :\n       \u0393 !! t = Some \u03c4s \u2192 Forall2 (ctree_typed' \u0393 \u0394 \u2218 fst) w\u03b3bss \u03c4s \u2192\n       \u2713{\u0393,\u0394}2** w\u03b3bss \u2192\n       Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss \u2192\n       length \u2218 snd <$> w\u03b3bss = field_bit_padding \u0393 \u03c4s \u2192\n       ctree_typed' \u0393 \u0394 (MStruct t w\u03b3bss) (structT t)\n    | MUnion_typed t i \u03c4s w \u03b3bs \u03c4 :\n       \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 ctree_typed' \u0393 \u0394 w \u03c4 \u2192\n       \u2713{\u0393,\u0394}* \u03b3bs \u2192 pbit_indetify <$> \u03b3bs = \u03b3bs \u2192\n       bit_size_of \u0393 (unionT t) = bit_size_of \u0393 \u03c4 + length \u03b3bs \u2192\n       \u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs) \u2192\n       ctree_typed' \u0393 \u0394 (MUnion t i w \u03b3bs) (unionT t)\n    | MUnionAll_typed t \u03c4s \u03b3bs :\n       \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192 length \u03b3bs = bit_size_of \u0393 (unionT t) \u2192\n       ctree_typed' \u0393 \u0394 (MUnionAll t \u03b3bs) (unionT t).\n  Global Instance ctree_typed:\n    Typed (env K * memenv K) (type K) (mtree K) := uncurry ctree_typed'.\n\n  Lemma ctree_typed_inv_l \u0393 \u0394 (P : type K \u2192 Prop) w \u03c4 :\n    (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n    match w with\n    | MBase \u03c4b \u03b3bs =>\n       (\u2713{\u0393} \u03c4b \u2192 length \u03b3bs = bit_size_of \u0393 (baseT \u03c4b) \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 P (baseT \u03c4b)) \u2192 P \u03c4\n    | MArray \u03c4' ws =>\n       ((\u0393,\u0394) \u22a2* ws : \u03c4' \u2192 length ws \u2260 0 \u2192 P (\u03c4'.[length ws])) \u2192 P \u03c4\n    | MStruct t w\u03b3bss =>\n       (\u2200 \u03c4s, \u0393 !! t = Some \u03c4s \u2192 (\u0393,\u0394) \u22a21* w\u03b3bss :* \u03c4s \u2192 \u2713{\u0393,\u0394}2** w\u03b3bss \u2192\n         Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss \u2192\n         length \u2218 snd <$> w\u03b3bss = field_bit_padding \u0393 \u03c4s \u2192 P (structT t)) \u2192 P \u03c4\n    | MUnion t i w \u03b3bs =>\n       (\u2200 \u03c4s \u03c4, \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 pbit_indetify <$> \u03b3bs = \u03b3bs \u2192\n         bit_size_of \u0393 (unionT t) = bit_size_of \u0393 \u03c4 + length \u03b3bs \u2192\n         \u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs) \u2192 P (unionT t)) \u2192 P \u03c4\n    | MUnionAll t \u03b3bs =>\n       (\u2200 \u03c4s, \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192\n         length \u03b3bs = bit_size_of \u0393 (unionT t) \u2192 P (unionT t)) \u2192 P \u03c4\n    end.\n  Proof. destruct 1; simplify_equality'; eauto. Qed.\n  Lemma ctree_typed_inv_r \u0393 \u0394 (P : mtree K \u2192 Prop) w \u03c4 :\n    (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n    match \u03c4 with\n    | baseT \u03c4b =>\n       (\u2200 \u03b3bs, \u2713{\u0393} \u03c4b \u2192 length \u03b3bs = bit_size_of \u0393 (baseT \u03c4b) \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 P (MBase \u03c4b \u03b3bs)) \u2192 P w\n    | \u03c4.[n] =>\n       (\u2200 ws, n = length ws \u2192 (\u0393,\u0394) \u22a2* ws : \u03c4 \u2192 n \u2260 0 \u2192 P (MArray \u03c4 ws)) \u2192 P w\n    | structT t =>\n       (\u2200 w\u03b3bss \u03c4s, \u0393 !! t = Some \u03c4s \u2192 (\u0393,\u0394) \u22a21* w\u03b3bss :* \u03c4s \u2192\n         \u2713{\u0393,\u0394}2** w\u03b3bss \u2192\n         Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss \u2192\n         length \u2218 snd <$> w\u03b3bss = field_bit_padding \u0393 \u03c4s \u2192\n         P (MStruct t w\u03b3bss)) \u2192 P w\n    | unionT t =>\n       (\u2200 i \u03c4s w \u03b3bs \u03c4, \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 pbit_indetify <$> \u03b3bs = \u03b3bs \u2192\n         bit_size_of \u0393 (unionT t) = bit_size_of \u0393 \u03c4 + length \u03b3bs \u2192\n         \u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs) \u2192\n         P (MUnion t i w \u03b3bs)) \u2192\n       (\u2200 \u03c4s \u03b3bs, \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192\n         length \u03b3bs = bit_size_of \u0393 (unionT t) \u2192 P (MUnionAll t \u03b3bs)) \u2192\n       P w\n    end.\n  Proof. destruct 1; eauto. Qed.\n  Lemma ctree_typed_inv \u0393 \u0394 (P : Prop) w \u03c4 :\n    (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n    match w, \u03c4 with\n    | MBase \u03c4b \u03b3bs, baseT \u03c4b' =>\n       (\u03c4b' = \u03c4b \u2192 \u2713{\u0393} \u03c4b \u2192 length \u03b3bs = bit_size_of \u0393 (baseT \u03c4b) \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 P) \u2192 P\n    | MArray \u03c4' ws, \u03c4''.[n] =>\n       (\u03c4'' = \u03c4' \u2192 n = length ws \u2192 (\u0393,\u0394) \u22a2* ws : \u03c4' \u2192 length ws \u2260 0 \u2192 P) \u2192 P\n    | MStruct t w\u03b3bss, structT t' =>\n       (\u2200 \u03c4s, t' = t \u2192 \u0393 !! t = Some \u03c4s \u2192 (\u0393,\u0394) \u22a21* w\u03b3bss :* \u03c4s \u2192\n         \u2713{\u0393,\u0394}2** w\u03b3bss \u2192\n         Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss \u2192\n         length \u2218 snd <$> w\u03b3bss = field_bit_padding \u0393 \u03c4s \u2192 P) \u2192 P\n    | MUnion t i w \u03b3bs, unionT t' =>\n       (\u2200 \u03c4s \u03c4, t' = t \u2192 \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n         \u2713{\u0393,\u0394}* \u03b3bs \u2192 pbit_indetify <$> \u03b3bs = \u03b3bs \u2192\n         bit_size_of \u0393 (unionT t) = bit_size_of \u0393 \u03c4 + length \u03b3bs \u2192\n         \u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs) \u2192 P) \u2192 P\n    | MUnionAll t \u03b3bs, unionT t' =>\n       (\u2200 \u03c4s, t' = t \u2192 \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192\n         length \u03b3bs = bit_size_of \u0393 (unionT t) \u2192 P) \u2192 P\n    | _, _ => P\n    end.\n  Proof. destruct 1; simplify_equality'; eauto. Qed.\n  Section ctree_typed_ind.\n    Context (\u0393 : env K) (\u0394 : memenv K) (P : mtree K \u2192 type K \u2192 Prop).\n    Context (Pbase : \u2200 \u03c4b \u03b3bs,\n      \u2713{\u0393} \u03c4b \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192\n      length \u03b3bs = bit_size_of \u0393 (baseT \u03c4b) \u2192 P (MBase \u03c4b \u03b3bs) (baseT \u03c4b)).\n    Context (Parray : \u2200 ws \u03c4,\n      (\u0393,\u0394) \u22a2* ws : \u03c4 \u2192 Forall (\u03bb w, P w \u03c4) ws \u2192\n      length ws \u2260 0 \u2192 P (MArray \u03c4 ws) (\u03c4.[length ws])).\n    Context (Pstruct : \u2200 t w\u03b3bss \u03c4s,\n      \u0393 !! t = Some \u03c4s \u2192 (\u0393,\u0394) \u22a21* w\u03b3bss :* \u03c4s \u2192 Forall2 (P \u2218 fst) w\u03b3bss \u03c4s \u2192\n      \u2713{\u0393,\u0394}2** w\u03b3bss \u2192\n      Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss \u2192\n      length \u2218 snd <$> w\u03b3bss = field_bit_padding \u0393 \u03c4s \u2192\n      P (MStruct t w\u03b3bss) (structT t)).\n    Context (Punion : \u2200 t i \u03c4s w \u03b3bs \u03c4,\n      \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 P w \u03c4 \u2192\n      \u2713{\u0393,\u0394}* \u03b3bs \u2192 pbit_indetify <$> \u03b3bs = \u03b3bs \u2192\n      bit_size_of \u0393 (unionT t) = bit_size_of \u0393 \u03c4 + length \u03b3bs \u2192\n      \u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs) \u2192\n      P (MUnion t i w \u03b3bs) (unionT t)).\n    Context (Punion_all : \u2200 t \u03c4s \u03b3bs,\n      \u0393 !! t = Some \u03c4s \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192 length \u03b3bs = bit_size_of \u0393 (unionT t) \u2192\n      P (MUnionAll t \u03b3bs) (unionT t)).\n    Definition ctree_typed_ind : \u2200 w \u03c4, ctree_typed' \u0393 \u0394 w \u03c4 \u2192 P w \u03c4.\n    Proof.\n      fix H'3 3; destruct 1; simplify_equality';\n        eauto using Forall2_impl, Forall_impl.\n    Qed.\n  End ctree_typed_ind.\n\n  Global Instance mtree_check :\n      TypeCheck (env K * memenv K) (type K) (mtree K) :=\n    fix go \u0393\u0394 w {struct w} := let _ : TypeCheck _ _ _ := @go in\n    match w with\n    | MBase \u03c4b \u03b3bs =>\n       guard (\u2713{\u0393\u0394.1} \u03c4b);\n       guard (\u2713{\u0393\u0394}* \u03b3bs);\n       guard (length \u03b3bs = bit_size_of (\u0393\u0394.1) (baseT \u03c4b));\n       Some (baseT \u03c4b)\n    | MArray \u03c4 ws =>\n       \u03c4s \u2190 mapM (type_check \u0393\u0394) ws;\n       guard (length ws \u2260 0);\n       guard (Forall (\u03c4 =.) \u03c4s);\n       Some (\u03c4.[length ws])\n    | MStruct t w\u03b3bss =>\n       \u03c4s \u2190 \u0393\u0394.1 !! t;\n       \u03c4s' \u2190 mapM (type_check \u0393\u0394 \u2218 fst) w\u03b3bss;\n       guard (\u03c4s' = \u03c4s);\n       guard (\u2713{\u0393\u0394}2** w\u03b3bss);\n       guard (Forall (\u03bb w\u03b3bs, pbit_indetify <$> w\u03b3bs.2 = w\u03b3bs.2) w\u03b3bss);\n       guard (length \u2218 snd <$> w\u03b3bss = field_bit_padding (\u0393\u0394.1) \u03c4s);\n       Some (structT t)\n    | MUnion t i w \u03b3bs =>\n       \u03c4 \u2190 \u0393\u0394.1 !! t \u226b= (.!! i);\n       \u03c4' \u2190 type_check \u0393\u0394 w;\n       guard (\u03c4' = \u03c4);\n       guard (\u2713{\u0393\u0394}* \u03b3bs);\n       guard (pbit_indetify <$> \u03b3bs = \u03b3bs);\n       guard (bit_size_of (\u0393\u0394.1) (unionT t)\n         = bit_size_of (\u0393\u0394.1) \u03c4 + length \u03b3bs);\n       guard (\u00ac(ctree_unmapped w \u2227 Forall sep_unmapped \u03b3bs));\n       Some (unionT t)\n    | MUnionAll t \u03b3bs =>\n       \u03c4s \u2190 \u0393\u0394.1 !! t;\n       guard (\u2713{\u0393\u0394}* \u03b3bs);\n       guard (length \u03b3bs = bit_size_of (\u0393\u0394.1) (unionT t));\n       Some (unionT t)\n    end.\n\n  Inductive union_free : mtree K \u2192 Prop :=\n    | MBase_union_free \u03c4b \u03b3bs : union_free (MBase \u03c4b \u03b3bs)\n    | MArray_union_free \u03c4 ws : Forall union_free ws \u2192 union_free (MArray \u03c4 ws)\n    | MStruct_union_free t w\u03b3bss :\n       Forall (union_free \u2218 fst) w\u03b3bss \u2192 union_free (MStruct t w\u03b3bss)\n    | MUnionAll_union_free t \u03b3bs : union_free (MUnionAll t \u03b3bs).\n  Definition union_reset : mtree K \u2192 mtree K :=\n    fix go w :=\n    match w with\n    | MBase \u03c4b \u03b3bs => MBase \u03c4b \u03b3bs\n    | MArray \u03c4 ws => MArray \u03c4 (go <$> ws)\n    | MStruct t w\u03b3bss => MStruct t (prod_map go id <$> w\u03b3bss)\n    | MUnion t i w \u03b3bs => MUnionAll t (ctree_flatten w ++ \u03b3bs)\n    | MUnionAll t \u03b3bs => MUnionAll t \u03b3bs\n    end.\n  Section union_free_ind.\n    Context (P : mtree K \u2192 Prop).\n    Context (Pbase : \u2200 \u03c4 \u03b3bs, P (MBase \u03c4 \u03b3bs)).\n    Context (Parray : \u2200 \u03c4 ws,\n      Forall union_free ws \u2192 Forall P ws \u2192 P (MArray \u03c4 ws)).\n    Context (Pstruct : \u2200 t w\u03b3bss,\n      Forall (union_free \u2218 fst) w\u03b3bss \u2192 Forall (P \u2218 fst) w\u03b3bss \u2192\n      P (MStruct t w\u03b3bss)).\n    Context (Punion_bits : \u2200 t \u03b3bs, P (MUnionAll t \u03b3bs)).\n    Definition union_free_ind_alt: \u2200 w, union_free w \u2192 P w.\n    Proof. fix H'2 2; destruct 1; eauto using Forall_impl. Qed.\n  End union_free_ind.\n  Global Instance union_free_dec: \u2200 w : mtree K, Decision (union_free w).\n  Proof.\n   refine (\n    fix go w :=\n    match w return Decision (union_free w) with\n    | MBase _ _ => left _\n    | MArray _ ws => cast_if (decide (Forall union_free ws))\n    | MStruct _ w\u03b3bss => cast_if (decide (Forall (union_free \u2218 fst) w\u03b3bss))\n    | MUnion _ _ _ _ => right _\n    | MUnionAll _ _ => left _\n    end); clear go; abstract first [by constructor | by inversion 1].\n  Defined.\n\n  Definition array_unflatten {A B} (\u0393 : env K) (f : list A \u2192 B)\n      (\u03c4 : type K) : nat \u2192 list A \u2192 list B :=\n    let sz := bit_size_of \u0393 \u03c4 in fix go n bs :=\n    match n with 0 => [] | S n => f (take sz bs) :: go n (drop sz bs) end.\n  Definition struct_unflatten_aux {A B}\n      (f : type K \u2192 list A \u2192 B) : list (nat * type K) \u2192 list A \u2192 list B :=\n    fix go \u03c4s bs :=\n    match \u03c4s with\n    | [] => [] | (sz,\u03c4) :: \u03c4s => f \u03c4 (take sz bs) :: go \u03c4s (drop sz bs)\n    end.\n  Definition struct_unflatten {A B} (\u0393 : env K)\n      (f : type K \u2192 list A \u2192 B) (\u03c4s : list (type K)) : list A \u2192 list B :=\n    struct_unflatten_aux f (zip (field_bit_sizes \u0393 \u03c4s) \u03c4s).\n  Definition ctree_unflatten (\u0393 : env K) :\n      type K \u2192 list (pbit K) \u2192 mtree K := type_iter\n    (**i TBase =>     *) (\u03bb \u03c4b \u03b3bs, MBase \u03c4b \u03b3bs)\n    (**i TArray =>    *) (\u03bb \u03c4 n go \u03b3bs, MArray \u03c4 (array_unflatten \u0393 go \u03c4 n \u03b3bs))\n    (**i TCompound => *) (\u03bb c t \u03c4s go \u03b3bs,\n      match c with\n      | Struct_kind =>\n         MStruct t (struct_unflatten \u0393 (\u03bb \u03c4 \u03b3bs,\n           let \u03c4sz := bit_size_of \u0393 \u03c4\n           in (go \u03c4 (take \u03c4sz \u03b3bs), pbit_indetify <$> drop \u03c4sz \u03b3bs)\n         ) \u03c4s \u03b3bs)\n      | Union_kind => MUnionAll t \u03b3bs\n      end) \u0393.\n\n  Definition ctree_new (\u0393 : env K) (\u03b3b : pbit K) (\u03c4 : type K) : mtree K :=\n    ctree_unflatten \u0393 \u03c4 (replicate (bit_size_of \u0393 \u03c4) \u03b3b).\n\n  Global Instance ctree_lookup_seg:\n      LookupE (env K) (ref_seg K) (mtree K) (mtree K) := \u03bb \u0393 rs w,\n    match rs, w with\n    | RArray i \u03c4 n, MArray \u03c4' ws =>\n       guard (n = length ws); guard (\u03c4 = \u03c4'); ws !! i\n    | RStruct i t, MStruct t' w\u03b3bss => guard (t = t'); fst <$> w\u03b3bss !! i\n    | RUnion i t \u03b2, MUnion t' j w \u03b3bs =>\n       guard (t = t');\n       if decide (i = j) then Some w else\n       guard (\u03b2 = false);\n       \u03c4 \u2190 \u0393 !! t \u226b= (.!! i);\n       guard (ctree_unshared w);\n       guard (Forall sep_unshared \u03b3bs);\n       let \u03b3bs' := ctree_flatten w ++ \u03b3bs in\n       Some (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4) \u03b3bs'))\n    | RUnion i t _, MUnionAll t' \u03b3bs =>\n       guard (t = t'); \n       \u03c4 \u2190 \u0393 !! t \u226b= (.!! i);\n       guard (Forall sep_unshared \u03b3bs);\n       Some (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4) \u03b3bs))\n    | _, _ => None\n    end.\n  Global Instance ctree_lookup:\n      LookupE (env K) (ref K) (mtree K) (mtree K) :=\n    fix go \u0393 r w {struct r} := let _ : LookupE _ _ _ _ := @go in\n    match r with [] => Some w | rs :: r => w !!{\u0393} r \u226b= lookupE \u0393 rs end.\n\n  Definition ctree_alter_seg (\u0393 : env K) (g : mtree K \u2192 mtree K)\n      (rs : ref_seg K) (w : mtree K) : mtree K :=\n    match rs, w with\n    | RArray i _ _, MArray \u03c4 ws => MArray \u03c4 (alter g i ws)\n    | RStruct i _, MStruct t w\u03b3bss => MStruct t (alter (prod_map g id) i w\u03b3bss)\n    | RUnion i _ _, MUnion t j w' \u03b3bs' =>\n        if decide (i = j) then MUnion t i (g w') \u03b3bs'\n        else from_option\n          (\u03bb \u03c4, \n            let \u03b3bs := ctree_flatten w' ++ \u03b3bs' in\n            MUnion t i (g (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4) \u03b3bs)))\n                       (pbit_indetify <$> drop (bit_size_of \u0393 \u03c4) \u03b3bs))\n        w (\u0393 !! t \u226b= (.!! i))\n    | RUnion i _ _, MUnionAll t \u03b3bs => \n        from_option\n          (\u03bb \u03c4,\n            MUnion t i (g (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4) \u03b3bs)))\n                      (pbit_indetify <$> drop (bit_size_of \u0393 \u03c4) \u03b3bs))\n          w (\u0393 !! t \u226b= (.!! i))\n    | _, _ => w\n    end.\n  Fixpoint ctree_alter (\u0393 : env K) (g : mtree K \u2192 mtree K)\n      (r : ref K) : mtree K \u2192 mtree K :=\n    match r with\n    | [] => g | rs :: r => ctree_alter \u0393 (ctree_alter_seg \u0393 g rs) r\n    end.\n\n  Global Instance ctree_lookup_byte:\n      LookupE (env K) nat (mtree K) (mtree K) :=\n    \u03bb \u0393 i w, ctree_unflatten \u0393 ucharT <$>\n      sublist_lookup (i * char_bits) char_bits (ctree_flatten w).\n  Definition ctree_alter_byte (\u0393 : env K) (f : mtree K \u2192 mtree K)\n      (i : nat) (w : mtree K) : mtree K :=\n    ctree_unflatten \u0393 (type_of w) $\n      sublist_alter (ctree_flatten \u2218 f \u2218 ctree_unflatten \u0393 ucharT)\n                    (i * char_bits) char_bits (ctree_flatten w).\n\n  Definition ctree_singleton_seg (\u0393 : env K)\n    (rs : ref_seg K) (w : mtree K) : mtree K :=\n    match rs with\n    | RArray i \u03c4 n => MArray \u03c4 (<[i:=w]>(replicate n (ctree_new \u0393 \u2205 \u03c4)))\n    | RStruct i t =>\n        from_option\n          (\u03bb \u03c4s,\n            MStruct t (zip (<[i:=w]>(ctree_new \u0393 \u2205 <$> \u03c4s))\n                      (flip replicate \u2205 <$> field_bit_padding \u0393 \u03c4s)))\n          w (\u0393 !! t)\n    | RUnion i t _ =>\n        if decide (ctree_unmapped w)\n        then MUnionAll t (resize (bit_size_of \u0393 (unionT t)) \u2205 (ctree_flatten w))\n        else from_option \n          (\u03bb \u03c4,\n            let sz := bit_size_of \u0393 (unionT t) - bit_size_of \u0393 \u03c4 in\n            MUnion t i w (replicate sz \u2205)) \n          w (\u0393 !! t \u226b= (.!!i))\n    end.\n  Fixpoint ctree_singleton (\u0393 : env K)\n      (r : ref K) (w : mtree K) : mtree K :=\n    match r with\n    | [] => w\n    | rs :: r => ctree_singleton \u0393 r (ctree_singleton_seg \u0393 rs w)\n    end.\nEnd operations.\n\nSection memory_trees.\nContext `{EnvSpec K}.\nImplicit Types \u0393 : env K.\nImplicit Types \u03b1 : bool.\nImplicit Types \u0394 : memenv K.\nImplicit Types \u03c4b : base_type K.\nImplicit Types \u03c4 \u03c3 : type K.\nImplicit Types \u03c4s \u03c3s : list (type K).\nImplicit Types o : index.\nImplicit Types \u03b3b : pbit K.\nImplicit Types \u03b3bs : list (pbit K).\nImplicit Types w : mtree K.\nImplicit Types ws : list (mtree K).\nImplicit Types w\u03b3bs : mtree K * list (pbit K).\nImplicit Types w\u03b3bss : list (mtree K * list (pbit K)).\nImplicit Types rs : ref_seg K.\nImplicit Types r : ref K.\nImplicit Types g : mtree K \u2192 mtree K.\n\nLocal Hint Resolve Forall_take Forall_drop Forall_app_2 Forall_replicate: core.\nLocal Hint Resolve Forall2_take Forall2_drop Forall2_app: core.\nLocal Hint Immediate env_valid_lookup env_valid_lookup_lookup: core.\nLocal Hint Immediate TArray_valid_inv_type pbit_empty_valid: core.\n\n(** ** General properties of the typing judgment *)\nLemma ctree_typed_type_valid \u0393 \u0394 w \u03c4 : (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u2713{\u0393} \u03c4.\nProof.\n  induction 1 using @ctree_typed_ind; econstructor; decompose_Forall_hyps;\n    try match goal with\n    | H : length ?ws \u2260 0, H2 : Forall _ ?ws |- _ => destruct H2; [done|]\n    end; eauto.\nQed.\nLocal Hint Immediate ctree_typed_type_valid: core.\n#[global] Instance: TypeOfSpec (env K * memenv K) (type K) (mtree K).\nProof.\n  intros [\u0393 \u0394]. induction 1 using @ctree_typed_ind; decompose_Forall_hyps;\n    try match goal with\n    | H : length ?ws \u2260 0, H2 : Forall _ ?ws |- _ => destruct H2; [done|]\n    end; simpl; eauto with f_equal.\nQed.\nLocal Arguments type_check _ _ _ _ _ !_ /.\n#[global] Instance:\n  TypeCheckSpec (env K * memenv K) (type K) (mtree K) (\u03bb _, True).\nProof.\n  intros [\u0393 \u0394]. assert (\u2200 ws \u03c4s,\n    Forall (\u03bb w, \u2200 \u03c4, type_check (\u0393,\u0394) w = Some \u03c4 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4) ws \u2192\n    Forall2 (\u03bb w \u03c4, type_check (\u0393,\u0394) w = Some \u03c4) ws \u03c4s \u2192\n    (\u0393,\u0394) \u22a2* ws :* \u03c4s) by (intros; decompose_Forall; eauto).\n  assert (\u2200 ws \u03c4,\n    (\u0393,\u0394) \u22a2* ws : \u03c4 \u2192 Forall (\u03bb w, type_check (\u0393,\u0394) w = Some \u03c4) ws \u2192\n    mapM (type_check (\u0393,\u0394)) ws = Some (replicate (length ws) \u03c4)).\n  { intros. apply mapM_Some,Forall2_replicate_r; decompose_Forall_hyps; eauto. }\n  intros w \u03c4 _. split.\n  * revert \u03c4. induction w using @ctree_ind_alt; intros;\n      repeat (progress simplify_option_eq || case_match);\n      repeat match goal with\n      | H : mapM _ _ = Some _ |- _ => apply mapM_Some_1 in H\n      end; typed_constructor;\n      eauto using Forall2_Forall_typed; decompose_Forall; subst; eauto.\n  * by induction 1 using @ctree_typed_ind;\n      repeat (simplify_option_eq || case_match\n        || decompose_Forall_hyps || erewrite ?mapM_Some_2 by eauto);\n      repeat match goal with\n      | H : \u00acForall _ (replicate _ _) |- _ =>\n        by destruct H; apply Forall_replicate_eq\n      end.\nQed.\nLemma ctree_typed_weaken \u03931 \u03932 \u03941 \u03942 w \u03c4 :\n  \u2713 \u03931 \u2192 (\u03931,\u03941) \u22a2 w : \u03c4 \u2192 \u03931 \u2286 \u03932 \u2192 \u03941 \u21d2\u2098 \u03942 \u2192 (\u03932,\u03942) \u22a2 w : \u03c4.\nProof.\n  intros ? Hw ??. induction Hw using @ctree_typed_ind; typed_constructor;\n    eauto using base_type_valid_weaken,\n      lookup_compound_weaken, Forall_impl, pbit_valid_weaken;\n    by erewrite <-?(bit_size_of_weaken \u03931 \u03932),\n      <-?(field_bit_padding_weaken \u03931 \u03932)\n      by eauto using TBase_valid, TCompound_valid.\nQed.\nLemma ctree_typed_sep_valid \u0393 \u0394 w \u03c4 : (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_valid w.\nProof.\n  induction 1 using @ctree_typed_ind; constructor; eauto using Forall_impl,\n    Forall2_Forall_l, Forall_true, pbit_valid_sep_valid.\nQed.\n\n(** ** Properties of the [ctree_flatten] function *)\nLemma ctree_flatten_length \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 length (ctree_flatten w) = bit_size_of \u0393 \u03c4.\nProof.\n  intros H\u0393. revert w \u03c4. refine (ctree_typed_ind _ _ _ _ _ _ _ _); simpl.\n  * done.\n  * intros ws \u03c4 _ IH _; simpl. rewrite bit_size_of_array.\n    induction IH; csimpl; rewrite ?app_length; f_equal; auto.\n  * intros t w\u03b3bss \u03c4s Ht _ IH _ _ H\u03b3bss; erewrite bit_size_of_struct by eauto.\n    clear Ht. revert w\u03b3bss H\u03b3bss IH. unfold field_bit_padding.\n    induction (bit_size_of_fields _ \u03c4s H\u0393); intros [|??] ??;\n      decompose_Forall_hyps; rewrite ?app_length; f_equal; auto with lia.\n  * intros t i \u03c4s w \u03b3bs \u03c4 ?? _ <- _ _ ? _. by rewrite app_length.\n  * done.\nQed.\nLemma ctree_flatten_valid \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u2713{\u0393,\u0394}* (ctree_flatten w).\nProof.\n  intros H\u0393. revert w \u03c4.\n  refine (ctree_typed_ind _ _ _ _ _ _ _ _); simpl; auto 2.\n  * intros ws \u03c4 _ IH _. induction IH; decompose_Forall_hyps; auto.\n  * intros t w\u03b3bss \u03c4s _ _ IH ? _ _. induction IH; decompose_Forall_hyps; auto.\nQed.\nLemma ctree_flatten_union_reset w :\n  ctree_flatten (union_reset w) = ctree_flatten w.\nProof.\n  induction w as [| |s w\u03b3bss IH| |] using @ctree_ind_alt; simpl;\n    rewrite ?list_fmap_bind; auto using Forall_bind_ext.\n  induction IH; f_equal'; auto with f_equal.\nQed.\nLemma ctree_Forall_not P \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_Forall (not \u2218 P) w \u2192 \u00acctree_Forall P w.\nProof.\n  intros ??. apply Forall_not.\n  erewrite ctree_flatten_length by eauto. eauto using bit_size_of_ne_0.\nQed.\n\n(** ** Properties of the [union_reset] function *)\nLemma union_free_base \u0393 \u0394 w \u03c4b : (\u0393,\u0394) \u22a2 w : baseT \u03c4b \u2192 union_free w.\nProof. inversion 1; constructor. Qed.\nLemma union_reset_typed \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 (\u0393,\u0394) \u22a2 union_reset w : \u03c4.\nProof.\n  intros H\u0393. revert w \u03c4. refine (ctree_typed_ind _ _ _ _ _ _ _ _); simpl.\n  * by typed_constructor.\n  * intros ws \u03c4 Hws IH Hlen; typed_constructor; auto.\n    + by rewrite fmap_length.\n    + clear Hlen. induction IH; decompose_Forall_hyps; auto.\n  * intros t w\u03b3bss \u03c4s Ht Hws IH ? Hindet Hlen; typed_constructor; eauto.\n    + clear Ht Hlen Hindet. induction IH; decompose_Forall_hyps; auto.\n    + clear Hindet. eapply Forall_fmap, Forall_impl; eauto.\n    + elim Hindet; intros; constructor; simpl; auto.\n    + rewrite <-Hlen, <-list_fmap_compose. by apply list_fmap_ext.\n  * intros t i \u03c4s w \u03b3bs \u03c4 ??????? Hemp; simpl. typed_constructor; eauto.\n    + eauto using ctree_flatten_valid.\n    + by erewrite app_length, ctree_flatten_length by eauto.\n  * typed_constructor; eauto.\nQed.\nLemma union_free_reset w : union_free w \u2192 union_reset w = w.\nProof.\n  induction 1 as [|? ws _ IH|s w\u03b3bss _ IH|]\n    using @union_free_ind_alt; f_equal'; auto.\n  * by induction IH; f_equal'.\n  * induction IH as [|[]]; f_equal'; auto with f_equal.\nQed.\nLemma union_reset_free w : union_free (union_reset w).\nProof.\n  by induction w as [|ws IH|s w\u03b3bss IH| |]\n    using ctree_ind_alt; simpl; constructor; apply Forall_fmap.\nQed.\nLemma union_free_unmapped w :\n  ctree_valid w \u2192 ctree_Forall sep_unmapped w \u2192 union_free w.\nProof.\n  induction 1 as [|? ws ? IH|? w\u03b3bss ? IH| |] using @ctree_valid_ind_alt;\n    intros; decompose_Forall_hyps; try constructor.\n  * induction IH; decompose_Forall_hyps; auto.\n  * induction IH; decompose_Forall_hyps; auto.\n  * tauto.\nQed.\n\n(** ** The [type_mask] function *)\nDefinition type_mask (\u0393 : env K) : type K \u2192 list bool := type_iter\n  (**i TBase =>     *) (\u03bb \u03c4b, replicate (bit_size_of \u0393 \u03c4b) false)\n  (**i TArray =>    *) (\u03bb _ n go, mjoin (replicate n go))\n  (**i TCompound => *) (\u03bb c t \u03c4s go,\n    match c with\n    | Struct_kind =>\n       let \u03c4szs := field_bit_sizes \u0393 \u03c4s in\n       mjoin (zip_with (\u03bb \u03c4 sz, resize sz true (go \u03c4)) \u03c4s \u03c4szs)\n    | Union_kind => replicate (bit_size_of \u0393 (unionT t)) false\n   end) \u0393.\nLemma type_mask_base \u0393 \u03c4b : type_mask \u0393 \u03c4b = replicate (bit_size_of \u0393 \u03c4b) false.\nProof. done. Qed.\nLemma type_mask_array \u0393 \u03c4 n :\n  type_mask \u0393 (\u03c4.[n]) = mjoin (replicate n (type_mask \u0393 \u03c4)).\nProof. unfold type_mask. by rewrite type_iter_array. Qed.\nLemma type_mask_compound \u0393 c t \u03c4s :\n  \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 type_mask \u0393 (compoundT{c} t)\n  = match c with\n    | Struct_kind =>\n       let flds := field_bit_sizes \u0393 \u03c4s in\n       mjoin (zip_with (\u03bb \u03c4 sz, resize sz true (type_mask \u0393 \u03c4)) \u03c4s flds)\n    | Union_kind => replicate (bit_size_of \u0393 (unionT t)) false\n    end.\nProof.\n  intros H\u0393 Ht. unfold type_mask. erewrite (type_iter_compound (=)); try done.\n  { by intros ????? ->. }\n  clear t \u03c4s Ht. intros f g [] t \u03c4s _ _ Hfg; f_equal.\n  induction (bit_size_of_fields \u0393 \u03c4s H\u0393);\n    decompose_Forall_hyps; f_equal; auto with congruence.\nQed.\nLemma type_mask_length \u0393 \u03c4 :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 length (type_mask \u0393 \u03c4) = bit_size_of \u0393 \u03c4.\nProof.\n  intros H\u0393. revert \u03c4. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * intros \u03c4b _. by rewrite type_mask_base, replicate_length.\n  * intros \u03c4 n _ IH _. rewrite type_mask_array, bit_size_of_array, <-IH.\n    induction n; simpl; rewrite ?app_length; auto.\n  * intros [] t \u03c4s Ht _ _ _; erewrite !type_mask_compound by eauto; simpl.\n    { erewrite bit_size_of_struct by eauto. clear Ht.\n      induction (bit_size_of_fields _ \u03c4s H\u0393); simpl; [done|].\n      rewrite app_length, resize_length; auto. }\n    by rewrite replicate_length.\nQed.\n\n(** ** Properties of the [ctree_unflatten] function *)\nSection array_unflatten.\n  Context {A B} (f : list A \u2192 B).\n  Lemma array_unflatten_weaken (g : list A \u2192 B) \u03931 \u03932 \u03c4 n xs :\n    \u2713 \u03931 \u2192 \u2713{\u03931} \u03c4 \u2192 \u03931 \u2286 \u03932 \u2192 (\u2200 xs, f xs = g xs) \u2192\n    array_unflatten \u03931 f \u03c4 n xs = array_unflatten \u03932 g \u03c4 n xs.\n  Proof.\n    intros. unfold array_unflatten. erewrite bit_size_of_weaken by eauto.\n    revert xs; induction n; intros; f_equal'; auto.\n  Qed.\n  Lemma array_unflatten_length \u0393 \u03c4 n xs :\n    length (array_unflatten \u0393 f \u03c4 n xs) = n.\n  Proof. revert xs. induction n; simpl; auto. Qed.\nEnd array_unflatten.\nSection struct_unflatten.\n  Context {A B} (f : type K \u2192 list A \u2192 B).\n  Lemma struct_unflatten_weaken (g : type K \u2192 list A \u2192 B) \u03931 \u03932 \u03c4s xs :\n    \u2713 \u03931 \u2192 \u2713{\u03931}* \u03c4s \u2192 \u03931 \u2286 \u03932 \u2192\n    Forall (\u03bb \u03c4, \u2713{\u03931} \u03c4 \u2192 \u2200 xs, f \u03c4 xs = g \u03c4 xs) \u03c4s \u2192\n    struct_unflatten \u03931 f \u03c4s xs = struct_unflatten \u03932 g \u03c4s xs.\n  Proof.\n    unfold struct_unflatten. intros H\u03931 H\u03c4s H\u0393 Hfg.\n    erewrite <-(field_bit_sizes_weaken \u03931 \u03932) by eauto. revert xs.\n    induction (bit_size_of_fields _ \u03c4s H\u03931); intros;\n      decompose_Forall_hyps; f_equal'; eauto.\n  Qed.\n  Lemma struct_unflatten_type_of `{TypeOf (type K) B} \u0393 \u03c4s xs :\n    \u2713 \u0393 \u2192 (\u2200 \u03c4 xs, \u2713{\u0393} \u03c4 \u2192 type_of (f \u03c4 xs) = \u03c4) \u2192 \u2713{\u0393}* \u03c4s \u2192\n    type_of <$> struct_unflatten \u0393 f \u03c4s xs = \u03c4s.\n  Proof.\n    intros H\u0393 ??. unfold struct_unflatten. revert xs.\n    induction (bit_size_of_fields _ \u03c4s H\u0393); intros;\n      decompose_Forall_hyps; f_equal'; auto.\n  Qed.\nEnd struct_unflatten.\n\nLemma ctree_unflatten_base \u0393 \u03c4b \u03b3bs : ctree_unflatten \u0393 \u03c4b \u03b3bs = MBase \u03c4b \u03b3bs.\nProof. unfold ctree_unflatten. by rewrite type_iter_base. Qed.\nLemma ctree_unflatten_array \u0393 \u03c4 n \u03b3bs :\n  ctree_unflatten \u0393 (\u03c4.[n]) \u03b3bs =\n    MArray \u03c4 (array_unflatten \u0393 (ctree_unflatten \u0393 \u03c4) \u03c4 n \u03b3bs).\nProof. unfold ctree_unflatten. by rewrite type_iter_array. Qed.\nLemma ctree_unflatten_compound \u0393 c t \u03c4s \u03b3bs :\n  \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 ctree_unflatten \u0393 (compoundT{c} t) \u03b3bs\n  = match c with\n    | Struct_kind =>\n       MStruct t (struct_unflatten \u0393 (\u03bb \u03c4 \u03b3bs,\n        let \u03c4sz := bit_size_of \u0393 \u03c4 in\n        (ctree_unflatten \u0393 \u03c4 (take \u03c4sz \u03b3bs), pbit_indetify <$> drop \u03c4sz \u03b3bs)\n       ) \u03c4s \u03b3bs)\n    | Union_kind => MUnionAll t \u03b3bs\n    end.\nProof.\n  intros ? Ht. unfold ctree_unflatten.\n  erewrite (type_iter_compound (pointwise_relation _ (=))); try done.\n  { intros ???????; f_equal. by apply array_unflatten_weaken. }\n  clear t \u03c4s Ht \u03b3bs. intros f g [] t \u03c4s Ht H\u03c4s Hfg \u03b3bs; f_equal; auto.\n  eapply struct_unflatten_weaken, Forall_impl; eauto with f_equal.\nQed.\nLemma ctree_unflatten_weaken \u03931 \u03932 \u03c4 \u03b3bs :\n  \u2713 \u03931 \u2192 \u2713{\u03931} \u03c4 \u2192 \u03931 \u2286 \u03932 \u2192\n  ctree_unflatten \u03931 \u03c4 \u03b3bs = ctree_unflatten \u03932 \u03c4 \u03b3bs.\nProof.\n  intros. apply (type_iter_weaken (pointwise_relation _ (=))); try done.\n  { intros ???????; f_equal. by apply array_unflatten_weaken. }\n  clear \u03b3bs. intros f g [] t \u03c4s Ht H\u03c4s Hfg \u03b3bs; intros; f_equal; auto.\n  eapply struct_unflatten_weaken, Forall_impl; eauto 1; intros.\n  erewrite bit_size_of_weaken by eauto; f_equal; auto.\nQed.\n\nLtac solve_length := simplify_equality'; repeat first \n  [ rewrite take_length | rewrite drop_length | rewrite app_length\n  | rewrite fmap_length | erewrite ctree_flatten_length by eauto\n  | rewrite type_mask_length by eauto | rewrite replicate_length\n  | rewrite bit_size_of_int | rewrite int_width_char | rewrite resize_length\n  | rewrite insert_length | erewrite sublist_lookup_length by eauto\n  | erewrite sublist_alter_length by eauto\n  | match goal with\n    | |- context [ bit_size_of ?\u0393 ?\u03c4 ] =>\n      match goal with\n        | H : \u0393 !! ?t = Some ?\u03c4s, H2 : ?\u03c4s !! _ = Some \u03c4 |- _ =>\n          unless (bit_size_of \u0393 \u03c4 \u2264 bit_size_of \u0393 (unionT t)) by done;\n          assert (bit_size_of \u0393 \u03c4 \u2264 bit_size_of \u0393 (unionT t))\n            by eauto using bit_size_of_union_lookup\n        end\n    | H : Forall2 _ _ _ |- _ => apply Forall2_length in H\n    end ]; lia.\nLocal Hint Extern 0 (length _ = _) => solve_length: core.\nLocal Hint Extern 0 (_ = length _) => solve_length: core.\nLocal Hint Extern 0 (_ \u2264 length _) => solve_length: core.\nLocal Hint Extern 0 (length _ \u2264 _) => solve_length: core.\n\nLemma ctree_unflatten_typed \u0393 \u0394 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 \u2713{\u0393,\u0394}* \u03b3bs \u2192 length \u03b3bs = bit_size_of \u0393 \u03c4 \u2192\n  (\u0393,\u0394) \u22a2 ctree_unflatten \u0393 \u03c4 \u03b3bs : \u03c4.\nProof.\n  intros H\u0393 H\u03c4. revert \u03c4 H\u03c4 \u03b3bs. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * intros \u03c4 ? \u03b3bs ??. rewrite ctree_unflatten_base. by typed_constructor.\n  * intros \u03c4 n H\u03c4 IH Hn \u03b3bs H\u03b3bs.\n    rewrite ctree_unflatten_array, bit_size_of_array.\n    intros H\u03b3bs'. typed_constructor; auto using array_unflatten_length.\n    clear Hn. revert \u03b3bs H\u03b3bs H\u03b3bs'. induction n; simpl; auto.\n  * intros [] t \u03c4s Ht H\u03c4s IH H\u03c4s_len \u03b3bs H\u03b3bs;\n      erewrite ctree_unflatten_compound, ?bit_size_of_struct by eauto;\n      intros H\u03b3bs'; simpl; typed_constructor; eauto.\n    + unfold struct_unflatten. clear Ht H\u03c4s H\u03c4s_len. revert \u03b3bs H\u03b3bs H\u03b3bs'.\n      induction (bit_size_of_fields \u0393 \u03c4s H\u0393);\n        intros; decompose_Forall_hyps; constructor; eauto.\n    + clear Ht IH H\u03c4s H\u03c4s_len H\u03b3bs'. unfold struct_unflatten. revert \u03b3bs H\u03b3bs.\n      induction (bit_size_of_fields _ \u03c4s H\u0393); constructor;\n        simpl; auto using pbits_indetify_valid.\n    + clear Ht IH H\u03c4s H\u03c4s_len H\u03b3bs H\u03b3bs'. unfold struct_unflatten. revert \u03b3bs.\n      induction (bit_size_of_fields _ \u03c4s H\u0393); constructor;\n        simpl; auto using pbits_indetify_idempotent.\n    + clear Ht IH H\u03c4s H\u03c4s_len H\u03b3bs.\n      unfold struct_unflatten, field_bit_padding. revert \u03b3bs H\u03b3bs'.\n      induction (bit_size_of_fields _ \u03c4s H\u0393); intros; f_equal'; auto.\nQed.\nLemma ctree_unflatten_type_of \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 type_of (ctree_unflatten \u0393 \u03c4 \u03b3bs) = \u03c4.\nProof.\n  intros H\u0393 H\u03c4. revert \u03c4 H\u03c4 \u03b3bs. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * done.\n  * intros \u03c4 n _ IH ? \u03b3bs. rewrite ctree_unflatten_array; simpl.\n    destruct n; simplify_equality'. by rewrite array_unflatten_length.\n  * by intros [] t \u03c4s ? _ _ _ \u03b3bs; erewrite ctree_unflatten_compound by eauto.\nQed.\nLemma ctree_unflatten_union_free \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 union_free (ctree_unflatten \u0393 \u03c4 \u03b3bs).\nProof.\n  intros H\u0393 H\u03c4. revert \u03c4 H\u03c4 \u03b3bs. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * intros \u03c4b _ \u03b3bs. rewrite ctree_unflatten_base. constructor.\n  * intros \u03c4 n _ IH _ \u03b3bs. rewrite ctree_unflatten_array. constructor.\n    revert \u03b3bs. elim n; simpl; constructor; auto.\n  * intros [] t \u03c4s Ht _ IH _ \u03b3bs;\n      erewrite !ctree_unflatten_compound by eauto; constructor.\n    clear Ht. unfold struct_unflatten. revert \u03b3bs.\n    induction (bit_size_of_fields _ \u03c4s H\u0393); intros;\n      decompose_Forall_hyps; constructor; eauto.\nQed.\nLemma ctree_unflatten_flatten \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_unflatten \u0393 \u03c4 (ctree_flatten w) = union_reset w.\nProof.\n  intros H\u0393. revert w \u03c4. refine (ctree_typed_ind _ _ _ _ _ _ _ _); simpl.\n  * intros. by rewrite ctree_unflatten_base.\n  * intros ws \u03c4 ? IH _. rewrite ctree_unflatten_array. f_equal.\n    induction IH; [done |]; intros; decompose_Forall_hyps; auto.\n    rewrite take_app_alt, drop_app_alt by auto. f_equal; auto.\n  * intros t w\u03b3bss \u03c4s Ht Hws IH _ Hindet Hlen.\n    erewrite ctree_unflatten_compound by eauto; f_equal'. clear Ht.\n    revert w\u03b3bss Hindet Hlen Hws IH. unfold struct_unflatten, field_bit_padding.\n    induction (bit_size_of_fields _ \u03c4s H\u0393);\n      intros [|[] ?] ????; decompose_Forall_hyps; [done|].\n    rewrite ?take_app_alt, ?drop_app_alt by auto. repeat f_equal; auto.\n  * intros. by erewrite ctree_unflatten_compound by eauto.\n  * intros. by erewrite ctree_unflatten_compound by eauto.\nQed.\nLemma ctree_flatten_unflatten_le \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 length \u03b3bs \u2264 bit_size_of \u0393 \u03c4 \u2192\n  ctree_flatten (ctree_unflatten \u0393 \u03c4 \u03b3bs)\n  = mask pbit_indetify (type_mask \u0393 \u03c4) \u03b3bs.\nProof.\n  intros H\u0393 H\u03c4. revert \u03c4 H\u03c4 \u03b3bs. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * intros. by rewrite ctree_unflatten_base, type_mask_base, mask_false.\n  * intros \u03c4 n ? IH _ \u03b3bs.\n    rewrite ctree_unflatten_array, bit_size_of_array, type_mask_array; simpl.\n    revert \u03b3bs. induction n as [|n IHn]; intros \u03b3bs ?; simplify_equality'.\n    { symmetry; apply nil_length_inv; lia. }\n    by rewrite IH, IHn, mask_app, type_mask_length by auto.\n  * intros [] t \u03c4s Ht H\u03c4s IH _ \u03b3bs; erewrite ctree_unflatten_compound,\n      ?type_mask_compound, ?bit_size_of_struct, ?mask_false by eauto; eauto.\n    clear Ht; simpl. revert \u03b3bs IH. unfold struct_unflatten.\n    induction (bit_size_of_fields _ \u03c4s H\u0393) as [|\u03c4 sz \u03c4s szs ?? IH\u03c4]; simpl.\n    { intros [|??] _ ?; simpl in *; auto with lia. }\n    intros \u03b3bs. rewrite Forall_cons. intros [IH ?] ?; decompose_Forall_hyps.\n    by rewrite IH, IH\u03c4, mask_app, resize_length, resize_ge, mask_app,\n      type_mask_length, mask_true by eauto.\nQed.\nLemma ctree_flatten_unflatten \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 length \u03b3bs = bit_size_of \u0393 \u03c4 \u2192\n  ctree_flatten (ctree_unflatten \u0393 \u03c4 \u03b3bs)\n  = mask pbit_indetify (type_mask \u0393 \u03c4) \u03b3bs.\nProof. intros. apply ctree_flatten_unflatten_le; auto with lia. Qed.\nLemma ctree_mask_flatten \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n  mask pbit_indetify (type_mask \u0393 \u03c4) (ctree_flatten w) = ctree_flatten w.\nProof.\n  intros. by erewrite <-ctree_flatten_unflatten,\n    ctree_unflatten_flatten, ctree_flatten_union_reset by eauto.\nQed.\nLemma ctree_unflatten_Forall_le (P : pbit K \u2192 Prop) \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192 Forall P \u03b3bs \u2192\n  length \u03b3bs \u2264 bit_size_of \u0393 \u03c4 \u2192 ctree_Forall P (ctree_unflatten \u0393 \u03c4 \u03b3bs).\nProof.\n  intros ??? H\u03b3bs Hlen. rewrite ctree_flatten_unflatten_le by done.\n  generalize (type_mask \u0393 \u03c4). clear Hlen.\n  induction H\u03b3bs; intros [|[] ?]; simpl; auto.\nQed.\nLemma ctree_unflatten_Forall (P : pbit K \u2192 Prop) \u0393 \u03c4 \u03b3bs :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192 Forall P \u03b3bs \u2192\n  length \u03b3bs = bit_size_of \u0393 \u03c4 \u2192 ctree_Forall P (ctree_unflatten \u0393 \u03c4 \u03b3bs).\nProof. intros. apply ctree_unflatten_Forall_le; auto with lia. Qed.\nLemma ctree_merge_unflatten {B} \u0393 (h : pbit K \u2192 B \u2192 pbit K) \u03b3bs ys \u03c4 :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 length \u03b3bs = bit_size_of \u0393 \u03c4 \u2192\n  zip_with h (pbit_indetify <$> \u03b3bs) ys = pbit_indetify <$> zip_with h \u03b3bs ys \u2192\n  ctree_merge h (ctree_unflatten \u0393 \u03c4 \u03b3bs) ys\n  = ctree_unflatten \u0393 \u03c4 (zip_with h \u03b3bs ys).\nProof.\n  intros H\u0393 H\u03c4 Hle. revert \u03c4 H\u03c4 \u03b3bs ys Hle. refine (type_env_ind _ H\u0393 _ _ _ _).\n  * intros. by rewrite !ctree_unflatten_base.\n  * intros \u03c4 n ? IH _ \u03b3bs ys; rewrite bit_size_of_array,\n      !ctree_unflatten_array; intros H\u03b3bs Hh; f_equal'.\n    revert \u03b3bs ys H\u03b3bs Hh. induction n as [|n IHn]; intros; simpl;\n      rewrite ?ctree_flatten_unflatten_le, ?zip_with_take, ?zip_with_drop,\n      ?mask_length, ?take_length_le by auto; f_equal; auto.\n    + apply IH; auto. by rewrite !fmap_take, <-!zip_with_take, fmap_take, Hh.\n    + apply IHn; auto. by rewrite !fmap_drop, <-!zip_with_drop, fmap_drop, Hh.\n  * intros [] t \u03c4s Ht H\u03c4s IH _ \u03b3bs ys; erewrite ?bit_size_of_struct,\n      !ctree_unflatten_compound by eauto; intros H\u03b3bs Hh; f_equal'.\n    clear Ht. revert \u03b3bs ys H\u03b3bs Hh. unfold struct_unflatten. revert IH.\n    induction (bit_size_of_fields _ \u03c4s H\u0393) as [|\u03c4 sz \u03c4s szs ?? IH\u03c4s]; [done|].\n    rewrite Forall_cons; intros [IH ?]; intros; decompose_Forall_hyps;\n      rewrite ?ctree_flatten_unflatten_le, ?zip_with_take, ?zip_with_drop,\n      ?fmap_length, ?drop_length, ?mask_length, ?take_length_le, ?take_take,\n      ?Min.min_l, ?take_drop_commute, ?drop_drop, ?le_plus_minus_r by auto;\n      repeat f_equal; auto.\n    + apply IH; auto. by rewrite !fmap_take, <-!zip_with_take, fmap_take, Hh.\n    + by rewrite !fmap_drop, !fmap_take, <-!zip_with_drop,\n        <-!zip_with_take, fmap_drop, fmap_take, Hh.\n    + apply IH\u03c4s; auto. by rewrite !fmap_drop, <-!zip_with_drop, fmap_drop, Hh.\nQed.\n\n(** ** Properties of the [ctree_new] function *)\nLemma ctree_new_base \u0393 \u03b3b \u03c4b :\n  ctree_new \u0393 \u03b3b \u03c4b = MBase \u03c4b (replicate (bit_size_of \u0393 \u03c4b) \u03b3b).\nProof. done. Qed.\nLemma ctree_new_array \u0393 \u03b3b \u03c4 n :\n  ctree_new \u0393 \u03b3b (\u03c4.[n]) = MArray \u03c4 (replicate n (ctree_new \u0393 \u03b3b \u03c4)).\nProof.\n  unfold ctree_new; rewrite ctree_unflatten_array, bit_size_of_array; f_equal.\n  by induction n; f_equal'; rewrite ?take_replicate_plus, ?drop_replicate_plus.\nQed.\nLemma ctree_new_compound \u0393 \u03b3b c t \u03c4s :\n  \u2713 \u0393 \u2192 \u0393 !! t = Some \u03c4s \u2192 ctree_new \u0393 \u03b3b (compoundT{c} t)\n  = match c with\n    | Struct_kind => MStruct t (zip (ctree_new \u0393 \u03b3b <$> \u03c4s)\n       (flip replicate (pbit_indetify \u03b3b) <$> field_bit_padding \u0393 \u03c4s))\n    | Union_kind => MUnionAll t (replicate (bit_size_of \u0393 (unionT t)) \u03b3b)\n    end.\nProof.\n  intros H\u0393 Ht; unfold ctree_new; erewrite ctree_unflatten_compound by eauto.\n  destruct c; f_equal. erewrite ?bit_size_of_struct by eauto; clear Ht.\n  unfold struct_unflatten, field_bit_padding.\n  by induction (bit_size_of_fields _ \u03c4s H\u0393); decompose_Forall_hyps;\n    rewrite ?take_replicate_plus, ?drop_replicate_plus, ?take_replicate,\n    ?drop_replicate, ?Min.min_l, ?fmap_replicate by done; repeat f_equal.\nQed.\nLemma ctree_new_weaken \u03931 \u03932 \u03b3b \u03c4 :\n  \u2713 \u03931 \u2192 \u2713{\u03931} \u03c4 \u2192 \u03931 \u2286 \u03932 \u2192 ctree_new \u03931 \u03b3b \u03c4 = ctree_new \u03932 \u03b3b \u03c4.\nProof.\n  intros. unfold ctree_new.\n  by erewrite ctree_unflatten_weaken, bit_size_of_weaken by eauto.\nQed.\nLemma ctree_news_weaken \u03931 \u03932 \u03b3b \u03c4s :\n  \u2713 \u03931 \u2192 \u2713{\u03931}* \u03c4s \u2192 \u03931 \u2286 \u03932 \u2192 ctree_new \u03931 \u03b3b <$> \u03c4s = ctree_new \u03932 \u03b3b <$> \u03c4s.\nProof. induction 2; intros; f_equal'; eauto using ctree_new_weaken. Qed.\nLemma ctree_new_Forall (P : pbit K \u2192 Prop) \u0393 \u03b3b \u03c4 :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 P \u03b3b \u2192 P (pbit_indetify \u03b3b) \u2192 ctree_Forall P (ctree_new \u0393 \u03b3b \u03c4).\nProof.\n  intros. unfold ctree_new. rewrite ctree_flatten_unflatten_le by done.\n  generalize (type_mask \u0393 \u03c4).\n  induction (bit_size_of \u0393 \u03c4); intros [|[]?]; simpl; constructor; auto.\nQed.\nLemma ctree_new_type_of \u0393 \u03b3b \u03c4 :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 type_of (ctree_new \u0393 \u03b3b \u03c4) = \u03c4.\nProof. by apply ctree_unflatten_type_of. Qed.\nLemma ctree_new_typed \u0393 \u0394 \u03b3b \u03c4 :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 \u2713{\u0393,\u0394} \u03b3b \u2192 (\u0393,\u0394) \u22a2 ctree_new \u0393 \u03b3b \u03c4 : \u03c4.\nProof. intros; apply ctree_unflatten_typed; auto using replicate_length. Qed.\nLemma ctree_new_union_free \u0393 \u03b3b \u03c4: \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 union_free (ctree_new \u0393 \u03b3b \u03c4).\nProof. by apply ctree_unflatten_union_free. Qed.\nLemma ctree_flatten_new \u0393 \u03c4 \u03b3b :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 pbit_indetify \u03b3b = \u03b3b \u2192\n  ctree_flatten (ctree_new \u0393 \u03b3b \u03c4) = replicate (bit_size_of \u0393 \u03c4) \u03b3b.\nProof.\n  intros; unfold ctree_new; rewrite ctree_flatten_unflatten by done.\n  generalize (type_mask \u0393 \u03c4).\n  induction (bit_size_of _ _); intros [|[] ?]; f_equal'; auto.\nQed.\nLemma ctree_flatten_replicate_new \u0393 \u03c4 n \u03b3b :\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 pbit_indetify \u03b3b = \u03b3b \u2192\n  replicate n (ctree_new \u0393 \u03b3b \u03c4) \u226b= ctree_flatten\n  = replicate (n * bit_size_of \u0393 \u03c4) \u03b3b.\nProof.\n  intros; induction n as [|n IH]; csimpl; auto.\n  by rewrite replicate_plus, ctree_flatten_new, IH by done.\nQed.\n\n(** ** The map operation *)\nLemma ctree_map_typed_alt \u0393 \u0394 h w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u2713{\u0393,\u0394}* (h <$> ctree_flatten w) \u2192\n  ctree_Forall (\u03bb \u03b3b, sep_unmapped (h \u03b3b) \u2192 sep_unmapped \u03b3b) w \u2192\n  (\u2200 \u03b3b, pbit_indetify \u03b3b = \u03b3b \u2192 pbit_indetify (h \u03b3b) = h \u03b3b) \u2192\n  (\u0393,\u0394) \u22a2 ctree_map h w : \u03c4.\nProof.\n  intros ? Hw Hw' Hw'' ?. revert w \u03c4 Hw Hw' Hw''. assert (\u2200 \u03b3bs,\n    pbit_indetify <$> \u03b3bs = \u03b3bs \u2192 pbit_indetify <$> (h <$> \u03b3bs) = h <$> \u03b3bs).\n  { induction \u03b3bs; intros; simplify_equality'; f_equal; auto. }\n  assert (\u2200 \u03b3bs, Forall (\u03bb \u03b3b, sep_unmapped (h \u03b3b) \u2192 sep_unmapped \u03b3b) \u03b3bs \u2192\n    Forall sep_unmapped (h <$> \u03b3bs) \u2192 Forall sep_unmapped \u03b3bs).\n  { induction 1; intros; decompose_Forall_hyps; auto. }\n  refine (ctree_typed_ind _ _ _ _ _ _ _ _); simpl.\n  * typed_constructor; auto.\n  * intros ws \u03c4 _ IH Hlen Hw' Hw''. typed_constructor; auto. clear Hlen.\n    revert Hw' Hw''. induction IH; csimpl; rewrite ?fmap_app; intros;\n      decompose_Forall_hyps; constructor; auto.\n  * intros t w\u03b3bss \u03c4s Ht _ IH H\u03b3bs Hindet Hlen Hw' Hw''.\n    typed_constructor; eauto.\n    + revert Hw' Hw''. elim IH; [|intros [??] ???]; csimpl; rewrite ?fmap_app;\n        intros; decompose_Forall_hyps; auto.\n    + revert Hw' Hw''. elim H\u03b3bs; [|intros [??] ???]; csimpl; rewrite ?fmap_app;\n        intros; decompose_Forall_hyps; auto.\n    + elim Hindet; intros; constructor; simpl; auto.\n    + rewrite <-Hlen. elim w\u03b3bss; intros; f_equal'; auto.\n  * intros t i \u03c4s w \u03b3bs \u03c4; rewrite fmap_app; intros; decompose_Forall_hyps.\n    typed_constructor; eauto using ctree_flatten_valid; try solve_length.\n    rewrite ctree_flatten_map; intuition eauto using ctree_flatten_valid.\n  * typed_constructor; eauto.\nQed.\nLemma ctree_map_typed \u0393 \u0394 h w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u2713{\u0393,\u0394}* (h <$> ctree_flatten w) \u2192\n  (\u2200 \u03b3b, \u2713{\u0393,\u0394} \u03b3b \u2192 sep_unmapped (h \u03b3b) \u2192 sep_unmapped \u03b3b) \u2192\n  (\u2200 \u03b3b, pbit_indetify \u03b3b = \u03b3b \u2192 pbit_indetify (h \u03b3b) = h \u03b3b) \u2192\n  (\u0393,\u0394) \u22a2 ctree_map h w : \u03c4.\nProof. eauto using ctree_map_typed_alt, Forall_impl, ctree_flatten_valid. Qed.\nLemma ctree_map_type_of h w : type_of (ctree_map h w) = type_of w.\nProof. destruct w; simpl; unfold MUnion'; repeat case_decide; auto. Qed.\n\n(** ** Lookup operation *)\nLemma ctree_lookup_nil \u0393 : lookupE \u0393 (@nil (ref_seg K)) = (@Some (mtree K)).\nProof. done. Qed.\nLemma ctree_lookup_cons \u0393 rs r :\n  lookupE \u0393 (rs :: r) = \u03bb w : mtree K, w !!{\u0393} r \u226b= lookupE \u0393 rs.\nProof. done. Qed.\nLemma ctree_lookup_app \u0393 r1 r2 w :\n  w !!{\u0393} (r1 ++ r2) = (w !!{\u0393} r2) \u226b= lookupE \u0393 r1.\nProof.\n  induction r1 as [|rs1 r1 IH]; simpl; [by destruct (w !!{_} r2)|].\n  by rewrite ctree_lookup_cons, IH, option_bind_assoc.\nQed.\nLemma ctree_lookup_snoc \u0393 r rs w :\n  w !!{\u0393} (r ++ [rs]) = (w !!{\u0393} rs) \u226b= lookupE \u0393 r.\nProof. apply ctree_lookup_app. Qed.\nLemma ctree_lookup_seg_le \u0393 w rs1 rs2 w' :\n  w !!{\u0393} rs1 = Some w' \u2192 rs1 \u2286 rs2 \u2192 w !!{\u0393} rs2 = Some w'.\nProof.\n  destruct 2 as [| |?? [][]]; simpl in *; intuition.\n  destruct w; simplify_option_eq; auto.\nQed.\nLemma ctree_lookup_le \u0393 w r1 r2 w' :\n  w !!{\u0393} r1 = Some w' \u2192 r1 \u2286* r2 \u2192 w !!{\u0393} r2 = Some w'.\nProof.\n  intros Hw Hr; revert w' Hw. induction Hr; intros w'; [done|].\n  rewrite !ctree_lookup_cons, !bind_Some; intros (?&?&?);\n    eauto using ctree_lookup_seg_le.\nQed.\nLemma ctree_lookup_seg_freeze_proper \u0393 q1 q2 w rs1 rs2 w1 w2 :\n  w !!{\u0393} rs1 = Some w1 \u2192 w !!{\u0393} rs2 = Some w2 \u2192\n  freeze q1 rs1 = freeze q2 rs2 \u2192 w1 = w2.\nProof. intros. by destruct w, rs1, rs2; simplify_option_eq. Qed.\nLemma ctree_lookup_freeze_proper \u0393 q1 q2 w r1 r2 w1 w2 :\n  w !!{\u0393} r1 = Some w1 \u2192 w !!{\u0393} r2 = Some w2 \u2192\n  freeze q1 <$> r1 = freeze q2 <$> r2 \u2192 w1 = w2.\nProof.\n  revert r2 w1 w2. induction r1 as [|rs1 r1 IH]; intros [|rs2 r2] ??; try done.\n  { intros. by simplify_equality. }\n  rewrite !ctree_lookup_cons; intros; simplify_option_eq.\n  efeed pose proof IH; eauto. subst. eauto using ctree_lookup_seg_freeze_proper.\nQed.\nLemma ctree_lookup_seg_inv P \u0393 rs w w' :\n  w !!{\u0393} rs = Some w' \u2192\n  match rs, w with\n  | RArray i \u03c4 n, MArray \u03c4' ws =>\n     (\u2200 w'', \u03c4' = \u03c4 \u2192 n = length ws \u2192 ws !! i = Some w'' \u2192 P w'') \u2192 P w'\n  | RStruct i t, MStruct t' w\u03b3bss =>\n     (\u2200 w'' \u03b3bs, t = t' \u2192 w\u03b3bss !! i = Some (w'',\u03b3bs) \u2192 P w'') \u2192 P w'\n  | RUnion i t q, MUnion t' j w'' \u03b3bs =>\n     (t = t' \u2192 i = j \u2192 P w'') \u2192\n     (\u2200 \u03c4s \u03c4, t = t' \u2192 i \u2260 j \u2192 q = false \u2192\n       \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192\n       ctree_unshared w'' \u2192 Forall sep_unshared \u03b3bs \u2192\n       P (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4)\n          (ctree_flatten w'' ++ \u03b3bs)))) \u2192\n     P w'\n  | RUnion i t _, MUnionAll t' \u03b3bs =>\n     (\u2200 \u03c4s \u03c4, t = t' \u2192 \u0393 !! t = Some \u03c4s \u2192 \u03c4s !! i = Some \u03c4 \u2192\n       Forall sep_unshared \u03b3bs \u2192\n       P (ctree_unflatten \u0393 \u03c4 (take (bit_size_of \u0393 \u03c4) \u03b3bs))) \u2192\n     P w'\n  | _, _ => P w'\n  end.\nProof.\n  destruct rs, w; intros; simplify_option_eq;\n    repeat match goal with p : prod _ _ |- _ => destruct p end; eauto.\nQed.\n\nLemma ctree_lookup_seg_weaken \u03931 \u03932 rs w w' :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 w !!{\u03931} rs = Some w' \u2192 w !!{\u03932} rs = Some w'.\nProof.\n  intros ?? Hrs. by destruct w, rs; pattern w';\n    apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); intros;\n    simplify_option_eq by eauto using lookup_compound_weaken;\n    erewrite <-?(bit_size_of_weaken \u03931 \u03932),\n      <-?(ctree_unflatten_weaken \u03931 \u03932) by eauto.\nQed.\nLemma ctree_lookup_weaken \u03931 \u03932 r w w' :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 w !!{\u03931} r = Some w' \u2192 w !!{\u03932} r = Some w'.\nProof.\n  intros ??. revert w'. induction r as [|rs r IH]; intros w'; [done|].\n  rewrite !ctree_lookup_cons; intros; simplify_option_eq;\n    eauto using ctree_lookup_seg_weaken.\nQed.\nLemma ctree_lookup_seg_union_free \u0393 w rs w' :\n  \u2713 \u0393 \u2192 union_free w \u2192 w !!{\u0393} rs = Some w' \u2192 union_free w'.\nProof.\n  intros ? Hw Hrs; destruct Hw, rs; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs).\n  * by intros; decompose_Forall_hyps.\n  * by intros; decompose_Forall_hyps.\n  * eauto using ctree_unflatten_union_free, env_valid_lookup_singleton.\nQed.\nLemma ctree_lookup_union_free \u0393 w r w' :\n  \u2713 \u0393 \u2192 union_free w \u2192 w !!{\u0393} r = Some w' \u2192 union_free w'.\nProof.\n  intros H\u0393. revert w. induction r using rev_ind; intros w Hw Hr;\n    rewrite ?ctree_lookup_snoc in Hr; simplify_option_eq;\n    simplify_type_equality; eauto using ctree_lookup_seg_union_free.\nQed.\nLemma ctree_lookup_seg_Some \u0393 \u0394 w \u03c4 rs w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192\n  \u2203 \u03c3, \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2227 (\u0393,\u0394) \u22a2 w' : \u03c3.\nProof.\n  intros ? Hw Hrs; destruct rs as [i \u03c4' n|i|i]; destruct Hw as\n    [\u03c4 \u03b3bs|ws|s w\u03b3bss \u03c4s ? Hws|s j \u03c4s w \u03b3bs \u03c4|s \u03c4s \u03b3bs];\n    change (ctree_typed' \u0393 \u0394) with (typed (\u0393,\u0394)) in *;\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n  * intros w'' -> -> ?. exists \u03c4'. decompose_Forall_hyps.\n    repeat constructor; eauto using lookup_lt_is_Some_1.\n  * intros w'' \u03b3bs -> ?.\n    destruct (Forall2_lookup_l _ _ _ i (w'',\u03b3bs) Hws) as [\u03c3 [??]]; eauto.\n    exists \u03c3; repeat econstructor; eauto.\n  * intros -> ->. exists \u03c4; repeat econstructor; eauto.\n  * intros ? \u03c4' ???????; simplify_equality'. exists \u03c4'; repeat econstructor;\n      eauto 6 using ctree_unflatten_typed, ctree_flatten_valid.\n  * intros ?? -> ???; simplify_equality'.\n    exists \u03c4; repeat econstructor; eauto using ctree_unflatten_typed.\nQed.\nLemma ctree_lookup_seg_Some_type_of \u0393 \u0394 w \u03c4 rs w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : type_of w'.\nProof.\n  intros. destruct (ctree_lookup_seg_Some \u0393 \u0394 w \u03c4 rs w')\n    as (?&?&?); eauto using type_of_typed.\nQed.\nLemma ctree_lookup_Some \u0393 \u0394 w \u03c4 r w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192\n  \u2203 \u03c3, \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2227 (\u0393,\u0394) \u22a2 w' : \u03c3.\nProof.\n  intros H\u0393. revert w \u03c4.\n  induction r as [|rs r IH] using rev_ind; intros w \u03c4 Hv\u03c4 Hr.\n  { simplify_type_equality'. eexists; split; [econstructor |]; eauto. }\n  rewrite ctree_lookup_snoc in Hr. simplify_option_eq.\n  edestruct ctree_lookup_seg_Some as (?&?&?); eauto.\n  edestruct IH as (?&?&?); eauto.\n  eexists; split; [eapply ref_typed_snoc |]; eauto.\nQed.\nLemma ctree_lookup_Some_type_of \u0393 \u0394 w \u03c4 r w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : type_of w'.\nProof.\n  intros. destruct (ctree_lookup_Some \u0393 \u0394 w \u03c4 r w')\n    as (?&?&?); eauto using type_of_typed.\nQed.\nLemma ctree_lookup_seg_typed \u0393 \u0394 w \u03c4 rs w' \u03c3 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w' :\u03c3.\nProof.\n  intros H\u0393 Hv\u03c4 Hw ?. by destruct (ctree_lookup_seg_Some _ _ _ _ _ _ H\u0393 Hv\u03c4 Hw)\n    as (\u03c3'&Hr\u03c3'&?); simplify_type_equality.\nQed.\nLemma ctree_lookup_typed \u0393 \u0394 w \u03c4 r w' \u03c3 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w' : \u03c3.\nProof.\n  intros H\u0393 Hv\u03c4 Hw' ?. by destruct (ctree_lookup_Some _ _ _ _ _ _ H\u0393 Hv\u03c4 Hw')\n    as (\u03c3'&Hr\u03c3'&?); simplify_type_equality.\nQed.\nLemma ctree_lookup_seg_Forall (P : pbit K \u2192 Prop) \u0393 w rs w' :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} rs = Some w' \u2192 ctree_Forall P w'.\nProof.\n  intros ??.\n  assert (\u2200 \u03b2s \u03b3bs, Forall P \u03b3bs \u2192 Forall P (mask pbit_indetify \u03b2s \u03b3bs)).\n  { intros \u03b2s \u03b3bs H\u03b3bs. revert \u03b2s. induction H\u03b3bs; intros [|[]]; simpl; auto. }\n  intros Hw Hrs; destruct w, rs; simpl in Hw; rewrite ?Forall_bind in Hw;\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs;\n    intros; decompose_Forall_hyps; eauto 7 using ctree_unflatten_Forall_le.\nQed.\nLemma ctree_lookup_Forall (P : pbit K \u2192 Prop) \u0393 w r w' :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} r = Some w' \u2192 ctree_Forall P w'.\nProof.\n  intros H\u0393 ?. revert w. induction r as [|rs r] using rev_ind;\n    intros w; rewrite ?ctree_lookup_snoc; intros; simplify_option_eq;\n    simplify_type_equality; eauto using ctree_lookup_seg_Forall.\nQed.\nLemma ctree_lookup_Forall_typed (P : pbit K \u2192 Prop) \u0393 \u0394 w \u03c4 r w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 (\u2200 \u03b3b, \u2713{\u0393,\u0394} \u03b3b \u2192 P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} r = Some w' \u2192 ctree_Forall P w'.\nProof.\n  intros. eapply Forall_and_l with \u2713{\u0393,\u0394}, ctree_lookup_Forall; eauto.\n  * intros ? [??]; eauto using pbit_indetify_valid.\n  * rewrite Forall_and; eauto using ctree_flatten_valid.\nQed.\nLemma ctree_new_lookup_seg \u0393 \u03c4 \u03b3 rs \u03c3 :\n  \u2713 \u0393 \u2192 sep_unshared \u03b3 \u2192 \u2713{\u0393} \u03c4 \u2192\n  \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 ctree_new \u0393 \u03b3 \u03c4 !!{\u0393} rs = Some (ctree_new \u0393 \u03b3 \u03c3).\nProof.\n  destruct 4 as [\u03c4 n i|s i \u03c4s \u03c4 Ht H\u03c4s|s i q \u03c4s \u03c4].\n  * rewrite ctree_new_array; simplify_option_eq.\n    by rewrite lookup_replicate by done.\n  * erewrite ctree_new_compound by eauto; simplify_option_eq.\n    by rewrite <-list_lookup_fmap, fst_zip, list_lookup_fmap, H\u03c4s\n      by (by rewrite !fmap_length, field_bit_padding_length).\n  * erewrite ctree_new_compound by eauto; simplify_option_eq by eauto.\n    by rewrite take_replicate,Min.min_l by eauto using bit_size_of_union_lookup.\nQed.\nLemma ctree_new_lookup \u0393 \u03b3 \u03c4 r \u03c3 :\n  \u2713 \u0393 \u2192 sep_unshared \u03b3 \u2192 \u2713{\u0393} \u03c4 \u2192\n  \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 ctree_new \u0393 \u03b3 \u03c4 !!{\u0393} r = Some (ctree_new \u0393 \u03b3 \u03c3).\nProof.\n  induction 4 as [|r rs \u03c41 \u03c42 \u03c43 ?? IH] using @ref_typed_ind; [done|].\n  rewrite ctree_lookup_cons, IH; simpl;\n    eauto using ctree_new_lookup_seg, ref_typed_type_valid.\nQed.\nLemma ctree_lookup_seg_unfreeze_exists \u0393 \u0394 w \u03c4 rs \u03c3 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_unshared w \u2192\n  \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 \u2203 w', w !!{\u0393} freeze false rs = Some w'.\nProof.\n  destruct 2 as [|ws \u03c4|s w\u03b3bss \u03c4s| | ];\n    inversion 2; decompose_Forall_hyps; simplify_option_eq; eauto.\n  by apply lookup_lt_is_Some_2.\nQed.\nLemma ctree_lookup_unfreeze_exists \u0393 \u0394 w \u03c4 r \u03c3 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_unshared w \u2192\n  \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 \u2203 w', w !!{\u0393} (freeze false <$> r) = Some w'.\nProof.\n  intros H\u0393. revert w \u03c4.\n  induction r as [|rs r IH] using rev_ind; intros w \u03c4 Hw\u03c4 Hw Hr.\n  { rewrite ref_typed_nil in Hr; subst. by exists w. }\n  rewrite ref_typed_snoc in Hr; destruct Hr as (\u03c3'&?&?).\n  destruct (ctree_lookup_seg_unfreeze_exists \u0393 \u0394 w \u03c4 rs \u03c3') as (w'&?); auto.\n  destruct (IH w' \u03c3') as (w''&?); eauto using ctree_lookup_seg_union_free,\n    ctree_lookup_seg_Forall, ctree_lookup_seg_typed, pbit_indetify_unshared,\n    ref_seg_typed_le, ref_seg_freeze_le_r.\n  exists w''. rewrite fmap_app; csimpl.\n  rewrite ctree_lookup_snoc. by simplify_option_eq.\nQed.\nLemma type_mask_ref_seg \u0393 \u03c4 rs \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 \u2713{\u0393} \u03c4 \u2192\n  take (bit_size_of \u0393 \u03c3) (drop (ref_seg_object_offset \u0393 rs) (type_mask \u0393 \u03c4))\n  =.>* type_mask \u0393 \u03c3.\nProof.\n  intros H\u0393 Hrs H\u03c4.\n  destruct Hrs as [\u03c4 i n Hin|s i \u03c4s \u03c4 Ht Hi|]; simplify_option_eq.\n  * rewrite type_mask_array; apply reflexive_eq. revert i Hin.\n    apply TArray_valid_inv_type in H\u03c4.\n    induction n as [|n]; intros [|i] ?; simplify_equality'; rewrite ?drop_0,\n      ?take_app_alt, <-?drop_drop, ?drop_app_alt by done; auto with lia.\n  * erewrite type_mask_compound by eauto; simpl; apply reflexive_eq.\n    assert (\u2713{\u0393}* \u03c4s) as H\u03c4s by eauto; revert i Hi H\u03c4s. clear Ht H\u03c4.\n    unfold bit_offset_of.\n    induction (bit_size_of_fields _ \u03c4s H\u0393); intros [|i] ??;\n      decompose_Forall_hyps; rewrite <-?drop_drop, ?drop_app_alt, ?drop_0,\n        ?resize_ge, <-?(assoc_L (++)), ?take_app_alt by done; auto.\n  * erewrite type_mask_compound by eauto; simpl.\n    rewrite drop_0, take_replicate, Min.min_l by solve_length.\n    by apply replicate_false.\nQed.\nLemma ctree_lookup_seg_flatten \u0393 \u0394 w \u03c4 rs w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  mask pbit_indetify (type_mask \u0393 \u03c4') $ take (bit_size_of \u0393 \u03c4') $\n    drop (ref_seg_object_offset \u0393 rs) $ ctree_flatten w = ctree_flatten w'.\nProof.\n  intros H\u0393 Hw Hrs Hw'. rewrite <-(type_of_correct (\u0393,\u0394) w' \u03c4') by done.\n  clear Hw'. revert w \u03c4 Hw Hrs. refine (ctree_typed_ind _ _ _ _ _ _ _ _).\n  * by destruct rs.\n  * intros ws \u03c4 Hws _ _ Hrs; destruct rs as [i| |]; pattern w';\n      apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs.\n    assert (\u2200 ws', (\u0393,\u0394) \u22a2* ws' : \u03c4 \u2192\n      length (ws' \u226b= ctree_flatten) = length ws' * bit_size_of \u0393 \u03c4) as help.\n    { induction 1; f_equal'; auto. }\n    intros w <- -> ?; decompose_Forall_hyps; simplify_type_equality.\n    rewrite <-(take_drop_middle ws i w), bind_app, bind_cons by done.\n    rewrite drop_app_alt by (by rewrite help, take_length_le\n      by eauto using Nat.lt_le_incl, lookup_lt_Some).\n    by erewrite take_app_alt, ctree_mask_flatten by eauto.\n  * intros t w\u03b3bss \u03c4s Ht Hws _ _ Hindet Hlen Hrs; destruct rs as [|i|];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    intros w \u03b3bs -> Hi; destruct (Forall2_lookup_l (typed (\u0393,\u0394) \u2218 fst)\n      w\u03b3bss \u03c4s i (w,\u03b3bs)) as (\u03c4&Hi'&Hw); auto;\n      simplify_option_eq; simplify_type_equality'.\n    assert (bit_offset_of \u0393 \u03c4s i =\n      length (take i w\u03b3bss \u226b= \u03bb w\u03b3bs, ctree_flatten (w\u03b3bs.1) ++ w\u03b3bs.2))\n      as help2.\n    { clear Ht Hi' Hw Hindet. apply lookup_lt_Some in Hi.\n      unfold field_bit_padding, bit_offset_of in *.\n      revert i w\u03b3bss Hi Hlen Hws. induction (bit_size_of_fields _ \u03c4s H\u0393);\n        intros [|?] ????; decompose_Forall_hyps;\n        rewrite ?app_length; f_equal; auto; solve_length. }\n    rewrite <-(take_drop_middle w\u03b3bss i (w,\u03b3bs)), bind_app by done; csimpl.\n    by erewrite drop_app_alt, <-(assoc_L (++)), take_app_alt,\n      ctree_mask_flatten by eauto.\n  * intros t i \u03c4s w \u03b3bs \u03c4 Ht H\u03c4 ? _ _ Hindet ? _ Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    { intros -> ->; simplify_option_eq; simplify_type_equality.\n      by erewrite drop_0, take_app_alt, ctree_mask_flatten by eauto. }\n    intros ? \u03c4'' -> ? -> ?? _ _; simplify_option_eq.\n    rewrite ctree_unflatten_type_of by eauto.\n    by rewrite ctree_flatten_unflatten by eauto.\n  * intros t \u03c4s \u03b3bs ? _ ? Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    intros ?? -> ?? _; simplify_option_eq.\n    rewrite ctree_unflatten_type_of by eauto.\n    by rewrite ctree_flatten_unflatten by eauto.\nQed.\nLemma ctree_lookup_flatten \u0393 \u0394 w \u03c4 r w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  mask pbit_indetify (type_mask \u0393 \u03c4') $\n    take (bit_size_of \u0393 \u03c4') $\n    drop (ref_object_offset \u0393 r) $ ctree_flatten w = ctree_flatten w'.\nProof.\n  intros H\u0393 ?. unfold ref_object_offset.\n  revert w' \u03c4'. induction r as [|rs r IH]; intros w'' \u03c4''.\n  { intros; simplify_type_equality'.\n    by erewrite drop_0, take_ge, ctree_mask_flatten by eauto. }\n  rewrite ctree_lookup_cons; intros.\n  destruct (w !!{\u0393} r) as [w'|] eqn:?; simplify_equality'.\n  destruct (ctree_lookup_Some \u0393 \u0394 w \u03c4 r w') as (\u03c4'&?&?); auto.\n  destruct (ctree_lookup_seg_Some \u0393 \u0394 w' \u03c4' rs w'') as (?&?&?); auto.\n  simplify_type_equality'.\n  assert (ref_seg_object_offset \u0393 rs + bit_size_of \u0393 \u03c4'' \u2264 bit_size_of \u0393 \u03c4')\n    by eauto using ref_seg_object_offset_size'.\n  rewrite Nat.add_comm, <-drop_drop, <-(Min.min_l (bit_size_of \u0393 \u03c4'')\n    (bit_size_of \u0393 \u03c4' - ref_seg_object_offset \u0393 rs)), <-take_take,\n    take_drop_commute, le_plus_minus_r by lia.\n  by erewrite <-(mask_mask _ pbit_indetify), <-take_mask, <-drop_mask,\n    IH, ctree_lookup_seg_flatten by eauto using type_mask_ref_seg.\nQed.\nLemma ctree_lookup_seg_merge {B} \u0393 \u0394 (h : pbit K \u2192 B \u2192 pbit K) w ys \u03c4 rs w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b y, h (pbit_indetify \u03b3b) y = pbit_indetify (h \u03b3b y)) \u2192\n  (\u2200 \u03b3b y, sep_unshared \u03b3b \u2192 sep_unshared (h \u03b3b y)) \u2192\n  (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 length ys = bit_size_of \u0393 \u03c4 \u2192\n  w !!{\u0393} rs = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  ctree_merge h w ys !!{\u0393} rs = Some (ctree_merge h w' (take (bit_size_of \u0393 \u03c4')\n                                     (drop (ref_seg_object_offset \u0393 rs) ys))).\nProof.\n  intros H\u0393 ?? Hw Hlen Hrs Hw'.\n  rewrite <-(type_of_correct (\u0393,\u0394) w' \u03c4') by done.\n  assert (\u2200 \u03b3bs ys,\n   zip_with h (pbit_indetify <$> \u03b3bs) ys = pbit_indetify <$> zip_with h \u03b3bs ys).\n  { induction \u03b3bs; intros [|??]; f_equal'; auto. }\n  clear Hw'. revert w \u03c4 Hw Hlen Hrs. assert (\u2200 \u03b3bs ys,\n    Forall sep_unshared \u03b3bs \u2192 Forall sep_unshared (zip_with h \u03b3bs ys)).\n  { induction \u03b3bs; intros [|??] ?; decompose_Forall_hyps; auto. }\n  refine (ctree_typed_ind _ _ _ _ _ _ _ _).\n  * by destruct rs.\n  * intros ws \u03c4 Hws _ _ _ Hrs. destruct rs as [i| |]; pattern w';\n      apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs.\n    intros w <- -> Hw; simplify_equality'.\n    erewrite type_of_correct by (decompose_Forall_hyps; eauto).\n    assert (length (ctree_merge_array (ctree_merge h) ws ys) = length ws)\n      as Hlen by (generalize ys; elim ws; intros; f_equal'; auto).\n    simplify_option_eq; clear Hlen.\n    revert i w ys Hw. induction Hws as [|w ws ?? IH];\n      intros [|i] w' ys ?; simplify_equality'.\n    { by erewrite ctree_flatten_length by eauto. }\n    by erewrite IH, ctree_flatten_length, drop_drop by eauto.\n  * intros t w\u03b3bss \u03c4s Ht Hws _ _ _ Hlen _ Hrs; destruct rs as [|i|];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs.\n    intros w \u03b3bs -> Hw\u03b3bs; destruct (Forall2_lookup_l (typed (\u0393,\u0394) \u2218 fst)\n      w\u03b3bss \u03c4s i (w,\u03b3bs)) as (\u03c4&H\u03c4&Hw); auto;\n      simplify_option_eq; simplify_type_equality'.\n    clear Ht Hw. revert w\u03b3bss i w \u03b3bs \u03c4 ys H\u03c4 Hws Hlen Hw\u03b3bs.\n    unfold field_bit_padding, bit_offset_of.\n    induction (bit_size_of_fields _ \u03c4s H\u0393) as [|\u03c4 sz \u03c4s szs ?? IH];\n      intros [|[w' \u03b3bs'] w\u03b3bss] [|i] ??? ys ????; decompose_Forall_hyps.\n    { by erewrite ctree_flatten_length by eauto. }\n    erewrite IH, ctree_flatten_length, !drop_drop by eauto.\n    do 4 f_equal; lia.\n  * intros t i \u03c4s w \u03b3bs \u03c4 Ht H\u03c4 ? _ _ Hindet ? _ ? Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    { intros -> ->; simplify_option_eq; simplify_type_equality.\n      by erewrite ctree_flatten_length, drop_0 by eauto. }\n    intros ? \u03c4'' -> ? -> ????; simplify_equality'.\n    rewrite ctree_flatten_merge; simplify_option_eq; f_equal.\n    rewrite ctree_unflatten_type_of, ctree_merge_unflatten, drop_0 by eauto.\n    by rewrite <-zip_with_app, zip_with_take, take_drop by auto.\n  * intros t \u03c4s \u03b3bs ? _ ? _ Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    intros ?? -> ???; simplify_option_eq; f_equal.\n    rewrite ctree_unflatten_type_of by eauto.\n    by rewrite ctree_merge_unflatten, drop_0, zip_with_take by eauto.\nQed.\nLemma ctree_lookup_merge {B} \u0393 \u0394 (h : pbit K \u2192 B \u2192 pbit K) w ys \u03c4 r w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b y, h (pbit_indetify \u03b3b) y = pbit_indetify (h \u03b3b y)) \u2192\n  (\u2200 \u03b3b y, sep_unshared \u03b3b \u2192 sep_unshared (h \u03b3b y)) \u2192\n  (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 length ys = bit_size_of \u0393 \u03c4 \u2192\n  w !!{\u0393} r = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  ctree_merge h w ys !!{\u0393} r = Some (ctree_merge h w' (take (bit_size_of \u0393 \u03c4')\n                                    (drop (ref_object_offset \u0393 r) ys))).\nProof.\n  intros ?????. unfold ref_object_offset. revert w' \u03c4'.\n  induction r as [|rs r IH]; intros w'' \u03c4''.\n  { intros; simplify_type_equality'. by rewrite drop_0, take_ge by auto. }\n  rewrite !ctree_lookup_cons; intros.\n  destruct (w !!{\u0393} r) as [w'|] eqn:?; simplify_equality'.\n  destruct (ctree_lookup_Some \u0393 \u0394 w \u03c4 r w') as (\u03c4'&?&?); auto.\n  destruct (ctree_lookup_seg_Some \u0393 \u0394 w' \u03c4' rs w'') as (?&?&?); auto.\n  erewrite IH by eauto; simplify_type_equality'.\n  assert (sum_list (ref_seg_object_offset \u0393 <$> r) + bit_size_of \u0393 \u03c4'\n    \u2264 bit_size_of \u0393 \u03c4) by (by apply ref_object_offset_size').\n  assert (ref_seg_object_offset \u0393 rs + bit_size_of \u0393 \u03c4'' \u2264 bit_size_of \u0393 \u03c4')\n    by eauto using ref_seg_object_offset_size'.\n  erewrite ctree_lookup_seg_merge by eauto; do 2 f_equal.\n  rewrite <-drop_drop, !take_drop_commute, !drop_drop, take_take.\n  repeat (lia || f_equal).\nQed.\n\n(** ** Alter operation *)\nLemma ctree_alter_nil \u0393 g : ctree_alter \u0393 g [] = g.\nProof. done. Qed.\nLemma ctree_alter_cons \u0393 g rs r :\n  ctree_alter \u0393 g (rs :: r) = ctree_alter \u0393 (ctree_alter_seg \u0393 g rs) r.\nProof. done. Qed.\nLemma ctree_alter_app \u0393 g w r1 r2 :\n  ctree_alter \u0393 g (r1 ++ r2) w = ctree_alter \u0393 (ctree_alter \u0393 g r1) r2 w.\nProof.\n  revert g. induction r1; simpl; intros; rewrite ?ctree_alter_cons; auto.\nQed.\nLemma ctree_alter_snoc \u0393 g w r rs :\n  ctree_alter \u0393 g (r ++ [rs]) w = ctree_alter_seg \u0393 (ctree_alter \u0393 g r) rs w.\nProof. apply ctree_alter_app. Qed.\nLemma ctree_alter_seg_le \u0393 g rs1 rs2 :\n  rs1 \u2286 rs2 \u2192 ctree_alter_seg \u0393 g rs1 = ctree_alter_seg \u0393 g rs2.\nProof. by destruct 1. Qed.\nLemma ctree_alter_le \u0393 g r1 r2 :\n  r1 \u2286* r2 \u2192 ctree_alter \u0393 g r1 = ctree_alter \u0393 g r2.\nProof.\n  intros Hr. revert g.\n  induction Hr as [|rs1 rs2 r1 r2 ?? IH]; intros g; simpl; auto.\n  by erewrite IH, ctree_alter_seg_le by eauto.\nQed.\nLemma ctree_alter_seg_ext \u0393 g1 g2 w rs :\n  (\u2200 w', g1 w' = g2 w') \u2192 ctree_alter_seg \u0393 g1 rs w = ctree_alter_seg \u0393 g2 rs w.\nProof.\n  intros. destruct rs, w; simpl; unfold default; simplify_option_eq;\n    repeat case_match; f_equal; auto using list_fmap_ext, list_alter_ext.\n  by apply list_alter_ext; [intros [??] ?; f_equal'; auto|].\nQed.\nLemma ctree_alter_ext \u0393 g1 g2 w r :\n  (\u2200 w, g1 w = g2 w) \u2192 ctree_alter \u0393 g1 r w = ctree_alter \u0393 g2 r w.\nProof.\n  intros. revert w. induction r as [|rs r IH] using rev_ind; intros w; [done|].\n  rewrite !ctree_alter_snoc. by apply ctree_alter_seg_ext.\nQed.\nLemma ctree_alter_seg_ext_typed \u0393 \u0394 g1 g2 w \u03c4 rs :\n  \u2713 \u0393 \u2192 (\u2200 w' \u03c4', (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192 g1 w' = g2 w') \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n  ctree_alter_seg \u0393 g1 rs w = ctree_alter_seg \u0393 g2 rs w.\nProof.\n  intros ? Hg. destruct rs, 1; simpl;\n    unfold default; simplify_option_eq; f_equal; eauto.\n  * apply list_alter_ext; intros; decompose_Forall_hyps; eauto.\n  * apply list_alter_ext; auto.\n    intros [??] ?; decompose_Forall_hyps; f_equal'; eauto.\n  * case_match; f_equal; eauto.\n    eapply Hg; eauto using ctree_unflatten_typed, ctree_flatten_valid.\n  * case_match; decompose_Forall; f_equal; eauto using ctree_unflatten_typed.\nQed.\nLemma ctree_alter_ext_typed \u0393 \u0394 g1 g2 w \u03c4 r :\n  \u2713 \u0393 \u2192 (\u2200 w' \u03c4', (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192 g1 w' = g2 w') \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n  ctree_alter \u0393 g1 r w = ctree_alter \u0393 g2 r w.\nProof.\n  intros ?. revert g1 g2 w \u03c4.\n  induction r as [|rs r IH]; intros g1 g2 w \u03c4 ??; eauto.\n  rewrite !ctree_alter_cons; eauto using ctree_alter_seg_ext_typed.\nQed.\nLemma ctree_alter_seg_compose \u0393 g1 g2 w rs :\n  ctree_alter_seg \u0393 (g1 \u2218 g2) rs w\n  = ctree_alter_seg \u0393 g1 rs (ctree_alter_seg \u0393 g2 rs w).\nProof.\n  destruct w as [| |s w\u03b3bss| |], rs as [i|i|i]; simpl; unfold default;\n    repeat (simplify_option_eq || case_match);\n    f_equal; auto using list_alter_compose, list_fmap_compose.\n  rewrite <-list_alter_compose. by apply list_alter_ext.\nQed.\nLemma ctree_alter_compose \u0393 g1 g2 w r :\n  ctree_alter \u0393 (g1 \u2218 g2) r w = ctree_alter \u0393 g1 r (ctree_alter \u0393 g2 r w).\nProof.\n  intros. revert w. induction r as [|rs r IH] using rev_ind; intros w; [done|].\n  rewrite !ctree_alter_snoc, <-ctree_alter_seg_compose.\n  by apply ctree_alter_seg_ext.\nQed.\nLemma ctree_alter_seg_commute \u0393 g1 g2 w rs1 rs2 :\n  rs1 ## rs2 \u2192 ctree_alter_seg \u0393 g1 rs1 (ctree_alter_seg \u0393 g2 rs2 w)\n  = ctree_alter_seg \u0393 g2 rs2 (ctree_alter_seg \u0393 g1 rs1 w).\nProof.\n  destruct 1 as [|i1 i2 ? Hi], w as [| |? w\u03b3bss| |]; intros;\n    simplify_option_eq; f_equal; auto using list_alter_commute.\nQed.\nLemma ctree_alter_commute \u0393 g1 g2 w r1 r2 :\n  r1 ## r2 \u2192 ctree_alter \u0393 g1 r1 (ctree_alter \u0393 g2 r2 w)\n  = ctree_alter \u0393 g2 r2 (ctree_alter \u0393 g1 r1 w).\nProof.\n  rewrite ref_disjoint_alt. intros (r1'&rs1'&r1''&r2'&rs2'&r2''&->&->&?&Hr).\n  rewrite !ctree_alter_app, !ctree_alter_cons, !ctree_alter_nil.\n  erewrite <-!(ctree_alter_le _ _ (freeze true <$> r1'')), Hr,\n    !(ctree_alter_le _ _ (freeze true <$> r2'') r2'')\n    by eauto using ref_freeze_le_l.\n  rewrite <-!ctree_alter_compose. apply ctree_alter_ext; intros w'; simpl; auto.\n  by apply ctree_alter_seg_commute.\nQed.\nLemma ctree_alter_seg_weaken \u03931 \u03932 \u0394 g rs w \u03c4 :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 (\u03931,\u0394) \u22a2 w : \u03c4 \u2192\n  ctree_alter_seg \u03931 g rs w = ctree_alter_seg \u03932 g rs w.\nProof.\n  destruct rs as [| |j], 3; simplify_option_eq; auto.\n  * erewrite lookup_compound_weaken by eauto; simpl.\n    destruct (_ !! j) eqn:?; f_equal'; by erewrite !(bit_size_of_weaken \u03931 \u03932),\n      ?ctree_unflatten_weaken by eauto using TCompound_valid.\n  * erewrite lookup_compound_weaken by eauto; simpl.\n    destruct (_ !! j) eqn:?; f_equal'; by erewrite !(bit_size_of_weaken \u03931 \u03932),\n      ?ctree_unflatten_weaken by eauto using TCompound_valid.\nQed.\nLemma ctree_alter_weaken \u03931 \u03932 \u0394 g r w \u03c4 :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 (\u03931,\u0394) \u22a2 w : \u03c4 \u2192 ctree_alter \u03931 g r w = ctree_alter \u03932 g r w.\nProof.\n  intros ??. revert g w \u03c4. induction r as [|rs r IH]; intros g w \u03c4 ?; [done|].\n  erewrite !ctree_alter_cons, <-IH by eauto.\n  eapply ctree_alter_ext_typed; eauto using ctree_alter_seg_weaken.\nQed.\nLemma ctree_alter_lookup_seg_Forall (P : pbit K \u2192 Prop) \u0393 g w rs w' :\n  ctree_Forall P (ctree_alter_seg \u0393 g rs w) \u2192\n  w !!{\u0393} rs = Some w' \u2192 ctree_Forall P (g w').\nProof.\n  intros Hgw Hrs. destruct w as [|\u03c4 ws|s w\u03b3bss|s i w \u03b3bs|], rs as [i'|i'|i'];\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs.\n  * intros w -> -> Hw; simplify_equality'; rewrite Forall_bind in Hgw.\n    apply (Forall_lookup_1 (\u03bb w, ctree_Forall P w) (alter g i' ws) i'); auto.\n    by rewrite list_lookup_alter, Hw.\n  * intros w \u03b3bs -> Hw\u03b3bs; simplify_equality'; rewrite Forall_bind in Hgw.\n    assert (alter (prod_map g id) i' w\u03b3bss !! i' = Some (g w, \u03b3bs)).\n    { by rewrite list_lookup_alter, Hw\u03b3bs. }\n    by decompose_Forall_hyps.\n  * by intros; simplify_option_eq; decompose_Forall_hyps.\n  * by intros; simplify_option_eq; decompose_Forall_hyps.\n  * by intros; simplify_option_eq; decompose_Forall_hyps.\nQed.\nLemma ctree_alter_lookup_Forall (P : pbit K \u2192 Prop) \u0393 g w r w' :\n  ctree_Forall P (ctree_alter \u0393 g r w) \u2192\n  w !!{\u0393} r = Some w' \u2192 ctree_Forall P (g w').\nProof.\n  revert g w. induction r as [|rs r IH] using @rev_ind.\n  { intros g w. rewrite ctree_lookup_nil. naive_solver. }\n  intros g w. rewrite ctree_alter_snoc, ctree_lookup_snoc.\n  intros. destruct (w !!{\u0393} rs) as [w''|] eqn:Hw''; simplify_equality'.\n  eauto using ctree_alter_lookup_seg_Forall.\nQed.\nLemma ctree_alter_seg_Forall (P : pbit K \u2192 Prop) \u0393 g w rs w' :\n  (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} rs = Some w' \u2192 ctree_Forall P (g w') \u2192\n  ctree_Forall P (ctree_alter_seg \u0393 g rs w).\nProof.\n  intros ?. assert (\u2200 \u03b3bs, Forall P \u03b3bs \u2192 Forall P (pbit_indetify <$> \u03b3bs)).\n  { induction 1; simpl; auto. }\n  intros Hw Hrs. destruct w as [|\u03c4 ws|s w\u03b3bss|s i w \u03b3bs|], rs as [i'|i'|i'];\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs.\n  * intros w -> -> ??; simplify_equality'. rewrite Forall_bind in Hw |- *.\n    apply Forall_alter; intros; simplify_equality; auto.\n  * intros w \u03b3bs -> ??; simplify_equality'. rewrite Forall_bind in Hw |- *.\n    apply Forall_alter; intros; decompose_Forall_hyps; auto.\n  * intros; simplify_option_eq; decompose_Forall_hyps; auto.\n  * intros; simplify_option_eq; decompose_Forall_hyps; auto.\n  * intros; simplify_option_eq; decompose_Forall_hyps; auto.\nQed.\nLemma ctree_alter_Forall (P : pbit K \u2192 Prop) \u0393 g w r w' :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} r = Some w' \u2192 ctree_Forall P (g w') \u2192\n  ctree_Forall P (ctree_alter \u0393 g r w).\nProof.\n  intros ??. revert g w. induction r as [|rs r IH] using @rev_ind.\n  { intros g w. rewrite ctree_lookup_nil. naive_solver. }\n  intros g w. rewrite ctree_alter_snoc, ctree_lookup_snoc.\n  intros. destruct (w !!{\u0393} rs) as [w''|] eqn:Hw''; simplify_equality'.\n  eauto using ctree_alter_seg_Forall, ctree_lookup_seg_Forall.\nQed.\nLemma ctree_alter_seg_typed \u0393 \u0394 g w rs \u03c4 w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192\n  (\u0393,\u0394) \u22a2 g w' : type_of w' \u2192 \u00acctree_unmapped (g w') \u2192\n  (\u0393,\u0394) \u22a2 ctree_alter_seg \u0393 g rs w : \u03c4.\nProof.\n  intros H\u0393 Hw Hrs.\n  destruct rs as [i|i|i], Hw as [|\u03c4 ? ws|s w\u03b3bss \u03c4s ??? Hindet Hlen| |];\n    change (ctree_typed' \u0393 \u0394) with (typed (\u0393,\u0394)) in *;\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n  * intros; simplify_option_eq.\n    typed_constructor; auto using alter_length.\n    apply (Forall_alter _ g _ i); auto. by intros; simplify_type_equality'.\n  * intros; simplify_option_eq. typed_constructor; eauto.\n    + apply Forall2_alter_l; auto 1. by intros [] ????; simplify_type_equality'.\n    + apply Forall_alter; auto.\n    + apply Forall_alter; auto.\n    + rewrite <-Hlen. generalize i. elim w\u03b3bss; [done|].\n      intros [??] w\u03b3bss' ? [|?]; f_equal'; auto.\n  * intros; simplify_option_eq. typed_constructor; eauto.\n    + by simplify_type_equality.\n    + intuition.\n  * intros ? \u03c4'; intros; simplify_option_eq.\n    typed_constructor; eauto using pbits_indetify_idempotent.\n    + erewrite <-ctree_unflatten_type_of by eauto; eauto.\n    + eauto using pbits_indetify_valid, ctree_flatten_valid.\n    + erewrite fmap_length, drop_length,\n        app_length, ctree_flatten_length by eauto; solve_length.\n    + by intros [? _].\n  * intros ? \u03c4'; intros; simplify_option_eq. typed_constructor;\n      eauto using pbits_indetify_valid, pbits_indetify_idempotent.\n    + erewrite <-ctree_unflatten_type_of by eauto; eauto.\n    + solve_length.\n    + by intros [? _].\nQed.\nLemma ctree_alter_typed \u0393 \u0394 g w r \u03c4 w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192\n  (\u0393,\u0394) \u22a2 g w' : type_of w' \u2192 \u00acctree_unmapped (g w') \u2192\n  (\u0393,\u0394) \u22a2 ctree_alter \u0393 g r w : \u03c4.\nProof.\n  intros H\u0393. revert g \u03c4 w. induction r as [|rs r IH] using @rev_ind.\n  { by intros; simplify_type_equality'. }\n  intros g \u03c4 w; rewrite ctree_alter_snoc, ctree_lookup_snoc; intros.\n  destruct (w !!{\u0393} rs) as [w''|] eqn:?; simplify_equality'.\n  destruct (ctree_lookup_seg_Some \u0393 \u0394 w \u03c4 rs w'') as (?&_&?); eauto.\n  eapply ctree_alter_seg_typed; eauto using\n    ctree_lookup_seg_typed, ctree_alter_lookup_Forall, type_of_typed.\nQed.\nLemma ctree_alter_seg_type_of \u0393 g w rs :\n  (\u2200 w', type_of (g w') = type_of w') \u2192\n  type_of (ctree_alter_seg \u0393 g rs w) = type_of w.\nProof.\n  intros; destruct w as [|[]| | |], rs as [[]| |];\n    simpl; unfold default; repeat (simplify_option_eq || case_match);\n    f_equal'; rewrite ?alter_length; auto.\nQed.\nLemma ctree_alter_type_of \u0393 g w r :\n  (\u2200 w', type_of (g w') = type_of w') \u2192\n  type_of (ctree_alter \u0393 g r w) = type_of w.\nProof. revert g w. induction r; simpl; auto using ctree_alter_seg_type_of. Qed.\nLemma ctree_alter_seg_type_of_weak \u0393 \u0394 g w rs \u03c4 w' :\n  (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192\n  type_of (g w') = type_of w' \u2192 type_of (ctree_alter_seg \u0393 g rs w) = \u03c4.\nProof.\n  intros Hw Hrs. destruct rs as [[]| |], Hw as [|?? []| | |];\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs; intros;\n    simplify_option_eq; simplify_type_equality; by rewrite ?alter_length.\nQed.\nLemma ctree_alter_type_of_weak \u0393 \u0394 g w r \u03c4 w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192\n  type_of (g w') = type_of w' \u2192 type_of (ctree_alter \u0393 g r w) = \u03c4.\nProof.\n  revert g \u03c4 w. induction r as [|rs r IH] using @rev_ind.\n  { by intros; simplify_type_equality'. }\n  intros g \u03c4 w; rewrite ctree_alter_snoc, ctree_lookup_snoc; intros.\n  destruct (w !!{\u0393} rs) as [w''|] eqn:?; simplify_equality'.\n  destruct (ctree_lookup_seg_Some \u0393 \u0394 w \u03c4 rs w'') as (?&_&?); eauto.\n  eapply ctree_alter_seg_type_of_weak; eauto using type_of_typed.\nQed.\nLemma ctree_lookup_alter_seg_freeze \u0393 g w rs w' :\n  \u2713 \u0393 \u2192 w !!{\u0393} freeze false rs = Some w' \u2192\n  ctree_alter_seg \u0393 g rs w !!{\u0393} freeze true rs = Some (g w').\nProof.\n  destruct w, rs; intros; simplify_option_eq; try done.\n  * rewrite list_lookup_alter. simplify_option_eq. done.\n  * exfalso. eauto using alter_length.\n  * rewrite list_lookup_alter. by simplify_option_eq.\nQed.\nLemma ctree_lookup_alter_freeze \u0393 g w r w' :\n  \u2713 \u0393 \u2192 w !!{\u0393} (freeze false <$> r) = Some w' \u2192\n  ctree_alter \u0393 g r w !!{\u0393} (freeze true <$> r) = Some (g w').\nProof.\n  intros H\u0393. revert g w. induction r as [|rs r IH] using rev_ind; simpl.\n  { intros g w. rewrite !ctree_lookup_nil. congruence. }\n  intros g w. rewrite !fmap_app, !fmap_cons, !fmap_nil, !ctree_alter_snoc,\n    !ctree_lookup_snoc; intros; simplify_option_eq.\n  erewrite ctree_lookup_alter_seg_freeze by eauto; eauto.\nQed.\nLemma ctree_lookup_alter \u0393 g w r1 r2 w' :\n  \u2713 \u0393 \u2192 w !!{\u0393} (freeze false <$> r1) = Some w' \u2192\n  freeze true <$> r1 = freeze true <$> r2 \u2192\n  ctree_alter \u0393 g r2 w !!{\u0393} r1 = Some (g w').\nProof.\n  intros ?? Hr. apply ctree_lookup_le with (freeze true <$> r1);\n    auto using ref_freeze_le_l; rewrite Hr.\n  eapply ctree_lookup_alter_freeze;\n    eauto using ctree_lookup_le, ref_freeze_le_r.\n  by rewrite <-(ref_freeze_freeze _ true), <-Hr, ref_freeze_freeze.\nQed.\nLemma ctree_lookup_alter_seg_inv \u0393 \u0394 g w rs \u03c4 \u03c3 w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192\n  ctree_alter_seg \u0393 g rs w !!{\u0393} rs = Some w' \u2192\n  \u2203 w'', w' = g w'' \u2227 (\u0393,\u0394) \u22a2 w'' : \u03c3.\nProof.\n  intros ? Hw. destruct 1 as [\u03c4 i|s i \u03c4s|s i q \u03c4s \u03c4];\n    pattern w; apply (ctree_typed_inv_r _ _ _ _ _ Hw); clear w Hw.\n  * intros ws -> ?? Hw'.\n    simplify_option_eq; rewrite list_lookup_alter in Hw'.\n    destruct (ws !! i) as [w''|] eqn:?; simplify_equality'.\n    exists w''; split; auto. eapply (Forall_lookup_1 (\u03bb w', _ \u22a2 w' : _)); eauto.\n  * intros w\u03b3bss ?????? Hw'; simplify_equality'; case_option_guard; try done.\n    rewrite list_lookup_alter in Hw'.\n    destruct (w\u03b3bss !! i) as [[w'' \u03b3bs]|] eqn:?; simplify_equality'.\n    exists w''; split; auto. by decompose_Forall_hyps.\n  * intros; simplify_option_eq;\n      eauto 8 using ctree_unflatten_typed, ctree_flatten_valid.\n  * intros; simplify_option_eq; eauto 7 using ctree_unflatten_typed.\nQed.\nLemma ctree_lookup_alter_inv \u0393 \u0394 g w r \u03c4 \u03c3 w' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192\n  ctree_alter \u0393 g r w !!{\u0393} r = Some w' \u2192\n  \u2203 w'', w' = g w'' \u2227 (\u0393,\u0394) \u22a2 w'' : \u03c3.\nProof.\n  intros ? Hw Hr. revert g w w' Hw.\n  induction Hr as [|r rs ????? IH] using @ref_typed_ind.\n  { intros ? w ???; simplify_type_equality. by exists w. }\n  intros g w w' Hw'. rewrite ctree_alter_cons, ctree_lookup_cons; intros.\n  destruct (ctree_alter \u0393 (ctree_alter_seg \u0393 g rs) r w !!{\u0393} r)\n    as [w''|] eqn:Hw''; simplify_equality'.\n  apply IH in Hw''; auto; destruct Hw'' as (w'''&->&?).\n  eauto using ctree_lookup_alter_seg_inv.\nQed.\nLemma ctree_lookup_alter_seg_disjoint \u0393 g w rs1 rs2 :\n  rs1 ## rs2 \u2192 ctree_alter_seg \u0393 g rs2 w !!{\u0393} rs1 = w !!{\u0393} rs1.\nProof.\n  destruct w; destruct 1; simpl; auto.\n  * by rewrite alter_length, list_lookup_alter_ne by done.\n  * by rewrite list_lookup_alter_ne by done.\nQed.\nLemma ctree_lookup_alter_disjoint \u0393 g w r1 r2 w' :\n  \u2713 \u0393 \u2192 r1 ## r2 \u2192 w !!{\u0393} r1 = Some w' \u2192\n  ctree_alter \u0393 g r2 w !!{\u0393} r1 = Some w'.\nProof.\n  intros H\u0393. rewrite ref_disjoint_alt. intros (r1'&rs1&r&r2'&rs2&r'&->&->&?&Hr).\n  rewrite !ctree_alter_app, !ctree_lookup_app, !ctree_alter_cons,\n    !ctree_alter_nil, !ctree_lookup_cons, !ctree_lookup_nil; intros.\n  destruct (w !!{_} r) as [w1'|] eqn:Hw1'; simplify_equality'.\n  destruct (w1' !!{_} rs1) as [w2'|] eqn:Hw2'; simplify_equality'.\n  erewrite ctree_lookup_alter by eauto using ctree_lookup_le, ref_freeze_le_r.\n  by csimpl; rewrite ctree_lookup_alter_seg_disjoint, Hw2' by done.\nQed.\nLemma ctree_alter_seg_ext_lookup \u0393 g1 g2 w rs w' :\n  w !!{\u0393} rs = Some w' \u2192 g1 w' = g2 w' \u2192\n  ctree_alter_seg \u0393 g1 rs w = ctree_alter_seg \u0393 g2 rs w.\nProof.\n  destruct w, rs; intros Hrs;\n    pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs;\n    intros; simplify_option_eq; f_equal; auto.\n  * apply list_alter_ext; naive_solver.\n  * apply list_alter_ext; auto 1. by intros [] ?; simplify_equality'; f_equal.\nQed.\nLemma ctree_alter_ext_lookup \u0393 g1 g2 w r w' :\n  w !!{\u0393} r = Some w' \u2192 g1 w' = g2 w' \u2192\n  ctree_alter \u0393 g1 r w = ctree_alter \u0393 g2 r w.\nProof.\n  revert g1 g2 w'. induction r as [|rs r]; simpl; intros g1 g2 w'.\n  { by intros; simplify_type_equality'. }\n  rewrite ctree_lookup_cons; intros; simplify_option_eq;\n    eauto using ctree_alter_seg_ext_lookup.\nQed.\nLemma ctree_alter_seg_perm_flatten \u0393 \u0394 g w \u03c4 rs w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} rs = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  tagged_perm <$> ctree_flatten (ctree_alter_seg \u0393 g rs w) = tagged_perm <$>\n    take (ref_seg_object_offset \u0393 rs) (ctree_flatten w) ++\n    ctree_flatten (g w') ++\n    drop (ref_seg_object_offset \u0393 rs + bit_size_of \u0393 \u03c4') (ctree_flatten w).\nProof.\n  intros H\u0393 Hw Hrs Hw'. rewrite <-(type_of_correct (\u0393,\u0394) w' \u03c4') by done.\n  clear Hw'. revert w \u03c4 Hw Hrs. refine (ctree_typed_ind _ _ _ _ _ _ _ _).\n  * by destruct rs.\n  * intros ws \u03c4 Hws _ _ Hrs; destruct rs as [i| |]; pattern w';\n      apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear w' Hrs; simpl.\n    intros w'' <- ->. revert i w''.\n    induction Hws as [|w ws ?? IH]; intros [|i] w'' ?;\n      decompose_Forall_hyps; simplify_type_equality.\n    { by rewrite drop_app_alt by done. }\n    erewrite fmap_app, IH, !fmap_app by eauto; simplify_type_equality.\n    rewrite take_plus_app, fmap_app, <-!(assoc_L (++)) by done.\n    by rewrite <-Nat.add_assoc, drop_plus_app by done.\n  * intros t w\u03b3bss \u03c4s Ht Hws _ _ Hindet Hlen Hrs; destruct rs as [|i|];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    intros w \u03b3bs -> Hi; destruct (Forall2_lookup_l (typed (\u0393,\u0394) \u2218 fst)\n      w\u03b3bss \u03c4s i (w,\u03b3bs)) as (\u03c4&Hi'&Hw); auto;\n      simplify_option_eq; simplify_type_equality'.\n    assert (bit_offset_of \u0393 \u03c4s i =\n      length (take i w\u03b3bss \u226b= \u03bb w\u03b3bs, ctree_flatten (w\u03b3bs.1) ++ w\u03b3bs.2))\n      as help2.\n    { clear Ht Hi' Hw Hindet. apply lookup_lt_Some in Hi.\n      unfold field_bit_padding, bit_offset_of in *.\n      revert i w\u03b3bss Hi Hlen Hws. induction (bit_size_of_fields _ \u03c4s H\u0393);\n        intros [|?] ????; decompose_Forall_hyps;\n        rewrite ?app_length; f_equal; auto; solve_length. }\n    rewrite <-(take_drop_middle w\u03b3bss i (w,\u03b3bs)), bind_app by done; csimpl.\n    erewrite take_app_alt, drop_plus_app,\n      <-(assoc_L (++)), drop_app_alt, alter_app_r_alt by done.\n    rewrite take_length_le by eauto using Nat.lt_le_incl, lookup_lt_Some.\n    rewrite Nat.sub_diag; simpl; rewrite bind_app, bind_cons; simpl.\n    by rewrite !(assoc_L (++)).\n  * intros t i \u03c4s w \u03b3bs \u03c4 Ht H\u03c4 ? _ _ Hindet ? _ Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    { intros -> ->; simplify_option_eq; simplify_type_equality.\n      by rewrite drop_app_alt by done. }\n    intros ? \u03c4'' -> ? -> ?? _ _; simplify_option_eq.\n    by rewrite ctree_unflatten_type_of, !fmap_app, <-list_fmap_compose by eauto.\n  * intros t \u03c4s \u03b3bs ? _ ? Hrs; destruct rs as [| |i'];\n      pattern w'; apply (ctree_lookup_seg_inv _ _ _ _ _ Hrs); clear Hrs.\n    intros ?? -> ?? _; simplify_option_eq.\n    by rewrite ctree_unflatten_type_of, !fmap_app, <-list_fmap_compose by eauto.\nQed.\nLemma ctree_alter_perm_flatten \u0393 \u0394 g w \u03c4 r w' \u03c4' :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} r = Some w' \u2192 (\u0393,\u0394) \u22a2 w' : \u03c4' \u2192\n  tagged_perm <$> ctree_flatten (ctree_alter \u0393 g r w) = tagged_perm <$>\n    take (ref_object_offset \u0393 r) (ctree_flatten w) ++\n    ctree_flatten (g w') ++\n    drop (ref_object_offset \u0393 r + bit_size_of \u0393 \u03c4') (ctree_flatten w).\nProof.\n  intros H\u0393 ?. unfold ref_object_offset.\n  revert g w' \u03c4'. induction r as [|rs r IH]; intros g w'' \u03c4''.\n  { intros; simplify_type_equality'.\n    by rewrite drop_ge, (right_id_L [] (++)) by auto. }\n  rewrite ctree_lookup_cons; intros.\n  destruct (w !!{\u0393} r) as [w'|] eqn:?; simplify_equality'.\n  destruct (ctree_lookup_Some \u0393 \u0394 w \u03c4 r w') as (\u03c4'&?&?); auto.\n  destruct (ctree_lookup_seg_Some \u0393 \u0394 w' \u03c4' rs w'') as (?&?&?); auto.\n  simplify_type_equality'.\n  assert (ref_seg_object_offset \u0393 rs + bit_size_of \u0393 \u03c4'' \u2264 bit_size_of \u0393 \u03c4')\n    by eauto using ref_seg_object_offset_size'.\n  erewrite !fmap_app, IH, !fmap_app, ctree_alter_seg_perm_flatten by eauto.\n  rewrite !fmap_app, <-!(assoc_L (++)), (assoc_L (++)).\n  repeat f_equal.\n  { erewrite <-(ctree_lookup_flatten _ _ w _ _ w'), !fmap_take,\n      pbits_perm_mask by eauto using ctree_lookup_typed.\n    rewrite fmap_take, fmap_drop, take_take, Min.min_l by lia.\n    by rewrite take_take_drop, Nat.add_comm. }\n  erewrite <-(ctree_lookup_flatten _ _ w _ _ w'), !fmap_drop,\n    pbits_perm_mask by eauto using ctree_lookup_typed; unfold ref_object_offset.\n  rewrite fmap_take, fmap_drop, take_drop_commute, drop_drop.\n  rewrite drop_take_drop by lia; f_equal; lia.\nQed.\n\n(** ** Non-aliasing resuls *)\nLemma ctree_lookup_non_aliasing_help \u0393 \u0394 g w \u03c4 t \u03c4s r \u03c41 i1 \u03c42 i2 :\n  let r1' := RUnion i1 t true :: r in\n  let r2' := RUnion i2 t true :: r in\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 unionT t \u2192 \u0393 !! t = Some \u03c4s \u2192\n  \u03c4s !! i1 = Some \u03c41 \u2192 \u03c4s !! i2 = Some \u03c42 \u2192\n  i1 \u2260 i2 \u2192 ctree_alter \u0393 g r1' w !!{\u0393} r2' = None.\nProof.\n  intros r1' r2' ? Hw\u03c4 Hw Hr ?? Hi. unfold r1', r2'; clear r1' r2'.\n  rewrite !ctree_alter_cons, !ctree_lookup_cons.\n  destruct (ctree_alter \u0393 (ctree_alter_seg \u0393 g\n    (RUnion i1 t true)) r w !!{\u0393} r) as [w'|] eqn:Hw'; simpl; [|done].\n  eapply ctree_lookup_alter_inv in Hw'; eauto. destruct Hw' as (w''&->&?).\n  by pattern w''; apply (ctree_typed_inv_r \u0393 \u0394 _ w'' (unionT t));\n    intros; simplify_option_eq.\nQed.\nLemma ctree_lookup_non_aliasing \u0393 \u0394 g w \u03c4 t r r1 j1 \u03c31 i1 r2 j2 \u03c32 i2 :\n  let r1' := r1 ++ RUnion i1 t true :: r in\n  let r2' := r2 ++ RUnion i2 t true :: r in\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \u0393 \u22a2 r1' : \u03c4 \u21a3 \u03c31 \u2192 \u0393 \u22a2 r2' : \u03c4 \u21a3 \u03c32 \u2192 i1 \u2260 i2 \u2192\n  ctree_alter \u0393 g (ref_set_offset j1 r1') w\n    !!{\u0393} (ref_set_offset j2 r2') = None.\nProof.\n  assert (\u2200 j r3 i3, ref_set_offset j (r3 ++ RUnion i3 t true :: r) =\n    ref_set_offset j r3 ++ RUnion i3 t true :: r) as Hrhelp.\n  { by intros ? [|??] ?. }\n  intros r1' r2' H\u0393; unfold r1', r2'; clear r1' r2'.\n  rewrite !Hrhelp, !ref_typed_app; setoid_rewrite ref_typed_cons.\n  intros Hw\u03c4 (\u03c41&(\u03c4'&?&Hr1)&?) (\u03c42&(\u03c4''&?&Hr2)&?) Hi; simplify_type_equality.\n  inversion Hr1; inversion Hr2; simplify_option_eq.\n  rewrite ctree_lookup_app, ctree_alter_app, bind_None; left.\n  eauto using ctree_lookup_non_aliasing_help.\nQed.\n\n(** ** Looking up individual bytes *)\nLemma ctree_lookup_byte_typed \u0393 \u0394 w \u03c4 i c :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 c : ucharT.\nProof.\n  unfold lookupE, ctree_lookup_byte; intros; simplify_option_eq.\n  apply ctree_unflatten_typed; eauto using TBase_valid, TInt_valid,\n    Forall_sublist_lookup, ctree_flatten_valid.\nQed.\nLemma ctree_lookup_byte_length \u0393 \u0394 w \u03c4 i c :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} i = Some c \u2192 i < size_of \u0393 \u03c4.\nProof.\n  unfold lookupE, ctree_lookup_byte, sublist_lookup.\n  intros; simplify_option_eq.\n  apply (Nat.mul_lt_mono_pos_r (char_bits)); auto using char_bits_pos.\n  change (size_of \u0393 \u03c4 * char_bits) with (bit_size_of \u0393 \u03c4).\n  erewrite <-ctree_flatten_length by eauto. pose proof char_bits_pos; lia.\nQed.\nLemma ctree_lookup_byte_Forall (P : pbit K \u2192 Prop) \u0393 w i c :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 w !!{\u0393} i = Some c \u2192 ctree_Forall P c.\nProof.\n  unfold lookupE, ctree_lookup_byte; intros; simplify_option_eq.\n  eauto using TBase_valid, TInt_valid, Forall_sublist_lookup.\nQed.\nLemma ctree_flatten_mask \u0393 \u0394 w \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \n  mask pbit_indetify (type_mask \u0393 \u03c4) (ctree_flatten w) = ctree_flatten w.\nProof.\n  intros. rewrite <-ctree_flatten_union_reset at 2.\n  by erewrite <-ctree_unflatten_flatten, ctree_flatten_unflatten by eauto.\nQed.\nDefinition ctree_lookup_byte_after (\u0393 : env K)\n    (\u03c4 : type K) (i : nat) : mtree K \u2192 mtree K :=\n  ctree_unflatten \u0393 ucharT \u2218\n    mask pbit_indetify (take char_bits (drop (i * char_bits) (type_mask \u0393 \u03c4))) \u2218\n    ctree_flatten.\nLemma ctree_lookup_byte_after_spec \u0393 \u0394 w \u03c4 i :\n  \u2713\u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} i = ctree_lookup_byte_after \u0393 \u03c4 i <$> w !!{\u0393} i.\nProof.\n  intros. unfold lookupE, ctree_lookup_byte, ctree_lookup_byte_after.\n  destruct (sublist_lookup (i * char_bits) _ _) as [\u03b3bs|] eqn:?; f_equal'.\n  unfold sublist_lookup in *; simplify_option_eq.\n  by erewrite <-take_mask, <-drop_mask, ctree_flatten_mask by eauto.\nQed.\nLemma ctree_lookup_byte_after_Forall (P : pbit K \u2192 Prop) \u0393 \u03c4 i w :\n  (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  ctree_Forall P w \u2192 ctree_Forall P (ctree_lookup_byte_after \u0393 \u03c4 i w).\nProof.\n  intros ? Hw. unfold ctree_lookup_byte_after; simpl.\n  generalize (take char_bits (drop (i * char_bits) (type_mask \u0393 \u03c4))).\n  induction Hw; intros [|[] ?]; simpl; auto.\nQed.\nLemma ctree_lookup_byte_ext \u0393 \u0394 w1 w2 \u03c4 :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w1 : \u03c4 \u2192 union_free w1 \u2192 (\u0393,\u0394) \u22a2 w2 : \u03c4 \u2192 union_free w2 \u2192\n  (\u2200 i, i < size_of \u0393 \u03c4 \u2192 w1 !!{\u0393} i = w2 !!{\u0393} i) \u2192 w1 = w2.\nProof.\n  intros ????? Hlookup. erewrite <-(union_free_reset w1),\n    <-(union_free_reset w2), <-!ctree_unflatten_flatten by eauto.\n  f_equal; apply sublist_eq_same_length with (size_of \u0393 \u03c4) char_bits.\n  { by erewrite ctree_flatten_length by eauto. }\n  { by erewrite ctree_flatten_length by eauto. }\n  intros i Hi. specialize (Hlookup i Hi).\n  unfold lookupE, ctree_lookup_byte in Hlookup.\n  destruct (sublist_lookup _ _(ctree_flatten w1)) as [bs1|] eqn:?,\n    (sublist_lookup _ _(ctree_flatten w2)) as [bs2|] eqn:?; try done.\n  apply (inj Some) in Hlookup; rewrite !ctree_unflatten_base in Hlookup.\n  congruence.\nQed.\nLemma ctree_lookup_byte_char \u0393 \u0394 w :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : ucharT \u2192 w !!{\u0393} 0 = Some w.\nProof.\n  intros ? Hw. unfold lookupE, ctree_lookup_byte; simpl.\n  rewrite sublist_lookup_all by auto. f_equal'.\n  erewrite ctree_unflatten_flatten by eauto. by inversion Hw.\nQed.\nLemma ctree_lookup_reshape \u0393 \u0394 w \u03c4 i :\n  let szs := replicate (size_of \u0393 \u03c4) char_bits in\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n  w !!{\u0393} i = ctree_unflatten \u0393 ucharT <$> reshape szs (ctree_flatten w) !! i.\nProof.\n  intros szs ? Hw\u03c4. unfold lookupE at 1, ctree_lookup_byte. unfold szs.\n  by rewrite sublist_lookup_reshape\n    by (erewrite ?ctree_flatten_length by eauto; eauto using char_bits_pos).\nQed.\nLemma ctree_lookup_byte_flatten \u0393 w i w' :\n  w !!{\u0393} i = Some w' \u2192\n  take (char_bits) (drop (i * char_bits) (ctree_flatten w)) = ctree_flatten w'.\nProof.\n  unfold lookupE, ctree_lookup_byte, sublist_lookup; intros.\n  by simplify_option_eq.\nQed.\n\n(** ** Altering individual bytes *)\nLemma ctree_alter_byte_typed \u0393 \u0394 g w i c \u03c4 :\n  \u2713 \u0393 \u2192 w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192\n  (\u0393,\u0394) \u22a2 g c : ucharT \u2192 (\u0393,\u0394) \u22a2 ctree_alter_byte \u0393 g i w : \u03c4.\nProof.\n  unfold lookupE, ctree_lookup_byte, ctree_alter_byte. intros ? Hw ??.\n  destruct (sublist_lookup _ _ _) as [\u03b3bs|] eqn:?; simplify_type_equality'.\n  set (G := ctree_flatten \u2218 g \u2218 ctree_unflatten \u0393 ucharT).\n  assert (length (G \u03b3bs) = char_bits).\n  { unfold G; simplify_option_eq; auto. }\n  apply ctree_unflatten_typed; eauto 2.\n  eapply Forall_sublist_alter; unfold G; simpl; eauto using ctree_flatten_valid.\nQed.\nLemma ctree_alter_byte_Forall (P : pbit K \u2192 Prop) \u0393 \u0394 g w i c \u03c4 :\n  \u2713 \u0393 \u2192 (\u2200 \u03b3b, P \u03b3b \u2192 P (pbit_indetify \u03b3b)) \u2192\n  w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 (\u0393,\u0394) \u22a2 g c : ucharT \u2192\n  ctree_Forall P w \u2192 ctree_Forall P (g c) \u2192\n  ctree_Forall P (ctree_alter_byte \u0393 g i w).\nProof.\n  unfold lookupE, ctree_lookup_byte, ctree_alter_byte. intros.\n  destruct (sublist_lookup _ _ _) as [\u03b3bs|] eqn:?; simplify_type_equality'.\n  set (G := ctree_flatten \u2218 g \u2218 ctree_unflatten \u0393 ucharT).\n  assert (length (G \u03b3bs) = char_bits).\n  { unfold G; simplify_option_eq; auto. }\n  eapply ctree_unflatten_Forall; eauto 1 using ctree_typed_type_valid.\n  eapply Forall_sublist_alter; unfold G; simpl; eauto.\nQed.\nLemma ctree_alter_byte_type_of \u0393 g i w :\n  \u2713 \u0393 \u2192 \u2713{\u0393} (type_of w) \u2192 type_of (ctree_alter_byte \u0393 g i w) = type_of w.\nProof. apply ctree_unflatten_type_of. Qed.\nLemma ctree_alter_byte_union_free \u0393 g w i :\n  \u2713 \u0393 \u2192 \u2713{\u0393} (type_of w) \u2192 union_free (ctree_alter_byte \u0393 g i w).\nProof. apply ctree_unflatten_union_free. Qed.\nLemma ctree_alter_byte_char \u0393 \u0394 g w :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : ucharT \u2192 (\u0393,\u0394) \u22a2 g w : ucharT \u2192\n  ctree_alter_byte \u0393 g 0 w = g w.\nProof.\n  intros ?? Hc. unfold ctree_alter_byte; simplify_type_equality'.\n  erewrite sublist_alter_all by auto; simpl.\n  by erewrite (ctree_unflatten_flatten _ _ w), union_free_reset,\n    ctree_unflatten_flatten, union_free_reset by eauto using union_free_base.\nQed.\nLemma ctree_lookup_alter_byte \u0393 \u0394 g w \u03c4 i c :\n  \u2713 \u0393 \u2192 w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 g c : ucharT \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 \n  ctree_alter_byte \u0393 g i w !!{\u0393} i\n  = ctree_lookup_byte_after \u0393 \u03c4 i <$> (g <$> w !!{\u0393} i).\nProof.\n  unfold lookupE, ctree_lookup_byte, ctree_alter_byte. intros.\n  destruct (sublist_lookup _ _ (ctree_flatten w))\n    as [\u03b3bs|] eqn:?; simplify_type_equality'.\n  set (G:=ctree_flatten \u2218 g \u2218 ctree_unflatten \u0393 ucharT).\n  assert (length (G \u03b3bs) = char_bits).\n  { unfold G; simplify_option_eq; auto. }\n  erewrite ctree_flatten_unflatten\n    by (rewrite ?sublist_alter_length by auto; eauto).\n  erewrite sublist_lookup_mask, sublist_lookup_alter by eauto.\n  unfold G, ctree_lookup_byte_after. by simplify_option_eq.\nQed.\nLemma ctree_lookup_alter_byte_ne \u0393 \u0394 g w \u03c4 i j c :\n  \u2713 \u0393 \u2192 w !!{\u0393} j = Some c \u2192 (\u0393,\u0394) \u22a2 g c : ucharT \u2192\n  (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 i \u2260 j \u2192 ctree_alter_byte \u0393 g j w !!{\u0393} i = w !!{\u0393} i.\nProof.\n  unfold lookupE, ctree_lookup_byte, ctree_alter_byte. intros.\n  destruct (sublist_lookup (j * _) _ (ctree_flatten w))\n    as [\u03b3bs|] eqn:?; simplify_type_equality'.\n  set (G:=ctree_flatten \u2218 g \u2218 ctree_unflatten \u0393 ucharT).\n  assert (length (G \u03b3bs) = char_bits).\n  { unfold G; simplify_option_eq; auto. }\n  assert (i * char_bits + char_bits \u2264 j * char_bits\n    \u2228 j * char_bits + char_bits \u2264 i * char_bits).\n  { destruct (decide (i < j)); [left|right];\n      rewrite <-Nat.mul_succ_l; apply Nat.mul_le_mono_r; lia. }\n  erewrite ctree_flatten_unflatten, sublist_lookup_mask,\n    sublist_lookup_alter_ne by eauto.\n  destruct (sublist_lookup (i * char_bits) _ _) as [\u03b3bs'|] eqn:?; f_equal'.\n  unfold sublist_lookup in *; simplify_option_eq.\n  by erewrite <-take_mask, <-drop_mask, ctree_flatten_mask by eauto.\nQed.\nLemma ctree_alter_byte_commute \u0393 \u0394 g1 g2 w \u03c4 i j c1 c2 :\n  \u2713 \u0393 \u2192 w !!{\u0393} i = Some c1 \u2192 (\u0393,\u0394) \u22a2 g1 c1 : ucharT \u2192\n  w !!{\u0393} j = Some c2 \u2192 (\u0393,\u0394) \u22a2 g2 c2 : ucharT \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 i \u2260 j \u2192\n  ctree_alter_byte \u0393 g1 i (ctree_alter_byte \u0393 g2 j w)\n  = ctree_alter_byte \u0393 g2 j (ctree_alter_byte \u0393 g1 i w).\nProof.\n  intros. assert (ctree_alter_byte \u0393 g2 j w !!{\u0393} i = Some c1).\n  { by erewrite ctree_lookup_alter_byte_ne by eauto. }\n  assert (ctree_alter_byte \u0393 g1 i w !!{\u0393} j = Some c2).\n  { by erewrite ctree_lookup_alter_byte_ne by eauto. }\n  assert (\u2713{\u0393} (type_of (ctree_alter_byte \u0393 g1 i w))).\n  { rewrite ctree_alter_byte_type_of; simplify_type_equality; eauto. }\n  assert (\u2713{\u0393} (type_of (ctree_alter_byte \u0393 g2 j w))).\n  { rewrite ctree_alter_byte_type_of; simplify_type_equality; eauto. }\n  eapply ctree_lookup_byte_ext;\n    eauto using ctree_alter_byte_union_free, ctree_alter_byte_typed.\n  intros ii _. destruct (decide (ii = i)) as [->|].\n  { by erewrite ctree_lookup_alter_byte, ctree_lookup_alter_byte_ne,\n      ctree_lookup_alter_byte_ne, ctree_lookup_alter_byte\n      by eauto using ctree_alter_byte_typed. }\n  destruct (decide (ii = j)) as [->|].\n  { by erewrite ctree_lookup_alter_byte, ctree_lookup_alter_byte_ne,\n      ctree_lookup_alter_byte, ctree_lookup_alter_byte_ne\n      by eauto using ctree_alter_byte_typed. }\n  by erewrite !ctree_lookup_alter_byte_ne by eauto using ctree_alter_byte_typed.\nQed.\nLemma ctree_alter_byte_unmapped \u0393 \u0394 g w i \u03c4 c :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 ctree_unmapped (ctree_alter_byte \u0393 g i w) \u2192\n  w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 g c : ucharT \u2192 ctree_unmapped (g c).\nProof.\n  unfold lookupE,ctree_lookup_byte,ctree_alter_byte. intros ?? Hw ??; revert Hw.\n  destruct (sublist_lookup _ _ _) as [\u03b3bs|] eqn:?; simplify_type_equality'.\n  rewrite ctree_flatten_unflatten\n    by (unfold compose; eauto 1 using ctree_typed_type_valid); intros Hw.\n  eapply (Forall_sublist_alter_inv _ (ctree_flatten \u2218 g \u2218 _)),\n    pbits_unmapped_indetify_inv; eauto.\n  eapply Forall_impl with \u2713{\u0393,\u0394}; eauto using pbit_valid_sep_valid.\n  eapply Forall_sublist_alter; simpl; eauto 2 using ctree_flatten_valid.\nQed.\nLemma ctree_alter_byte_perm_flatten \u0393 \u0394 g w \u03c4 i c :\n  \u2713 \u0393 \u2192 (\u0393,\u0394) \u22a2 w : \u03c4 \u2192 w !!{\u0393} i = Some c \u2192 (\u0393,\u0394) \u22a2 g c : ucharT \u2192\n  tagged_perm <$> ctree_flatten (ctree_alter_byte \u0393 g i w) = tagged_perm <$>\n    take (i * char_bits) (ctree_flatten w) ++\n    ctree_flatten (g c) ++\n    drop (char_bits + i * char_bits) (ctree_flatten w).\nProof.\n  unfold lookupE, ctree_lookup_byte, ctree_alter_byte,\n    sublist_alter, sublist_lookup; intros; simplify_type_equality'.\n  case_option_guard as Hlen; simplify_equality'.\n  erewrite ctree_flatten_length in Hlen by eauto.\n  by rewrite ctree_flatten_unflatten, pbits_perm_mask, Nat.add_comm by eauto.\nQed.\n\n(** * Properties of [ctree_singleton] *)\nLemma ctree_singleton_seg_le \u0393 rs1 rs2 w :\n  rs1 \u2286 rs2 \u2192 ctree_singleton_seg \u0393 rs1 w = ctree_singleton_seg \u0393 rs2 w.\nProof. by destruct 1. Qed.\nLemma ctree_singleton_le \u0393 r1 r2 w :\n  r1 \u2286* r2 \u2192 ctree_singleton \u0393 r1 w = ctree_singleton \u0393 r2 w.\nProof.\n  intros Hr. revert w. induction Hr; intros w; simpl; auto.\n  erewrite ctree_singleton_seg_le by eauto; eauto.\nQed.\nLemma ctree_singleton_seg_typed \u0393 \u0394 \u03c4 rs w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192\n  (\u0393,\u0394) \u22a2 ctree_singleton_seg \u0393 rs w : \u03c4.\nProof.\n  destruct 2 as [\u03c4 i n|s i \u03c4s|s i ? \u03c4s]; intros; simpl.\n  * typed_constructor; auto with lia. rewrite list_insert_alter.\n    apply Forall_alter; eauto using ctree_new_typed.\n  * assert (length (field_bit_padding \u0393 \u03c4s) = length \u03c4s) as Hlen\n      by eauto using field_bit_padding_length.\n    simplify_option_eq; typed_constructor; eauto.\n    + rewrite <-Forall2_fmap_l, fst_zip, list_insert_alter by done.\n      apply Forall2_alter_l; [|naive_solver].\n      eapply Forall2_fmap_l, Forall_Forall2_diag,\n        Forall_impl; eauto using ctree_new_typed.\n    + rewrite <-Forall_fmap, snd_zip by done.\n      elim (field_bit_padding \u0393 \u03c4s); constructor; auto.\n      apply Forall_replicate; auto.\n    + generalize (<[i:=w]> (ctree_new \u0393 \u2205 <$> \u03c4s)); clear Hlen.\n      by induction (field_bit_padding \u0393 \u03c4s); intros [|??];\n        constructor; csimpl; rewrite ?fmap_replicate.\n    + rewrite list_fmap_compose, snd_zip by done.\n      by induction (field_bit_padding \u0393 \u03c4s) in |- *; f_equal'.\n  * simplify_option_eq; typed_constructor;\n      eauto using Forall_resize, ctree_flatten_valid.\n    + by induction (_ - _); f_equal'.\n    + solve_length.\n    + naive_solver.\nQed.\nLemma ctree_singleton_typed \u0393 \u0394 \u03c4 r \u03c3 w :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192 (\u0393,\u0394) \u22a2 ctree_singleton \u0393 r w : \u03c4.\nProof.\n  intros ? Hr. revert w.\n  induction Hr using @ref_typed_ind; eauto 10 using ctree_singleton_seg_typed.\nQed.\nLemma ctree_singleton_seg_Forall_inv P \u0393 \u0394 \u03c4 rs w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192\n  ctree_Forall P (ctree_singleton_seg \u0393 rs w) \u2192 ctree_Forall P w.\nProof.\n  destruct 2 as [\u03c4 i n|s i \u03c4s \u03c4 ? Hi|]; intros ?; simplify_option_eq.\n  * rewrite Forall_bind, Forall_lookup; intros Hw; apply (Hw i).\n    by rewrite list_lookup_insert by auto.\n  * rewrite Forall_bind, Forall_lookup; intros Hw; apply lookup_lt_Some in Hi.\n    destruct (lookup_lt_is_Some_2 (field_bit_padding \u0393 \u03c4s) i) as [sz Htz].\n    { by rewrite field_bit_padding_length. }\n    eapply (Forall_app _ _ (replicate _ _)), (Hw i (w,replicate sz \u2205)).\n    by rewrite lookup_zip_with,\n      list_lookup_insert, list_lookup_fmap, Htz by auto.\n  * apply Forall_resize_inv; auto.\n  * rewrite Forall_app; by intros [].\nQed.\nLemma ctree_singleton_Forall_inv P \u0393 \u0394 \u03c4 r w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192\n  ctree_Forall P (ctree_singleton \u0393 r w) \u2192 ctree_Forall P w.\nProof.\n  intros ? Hr. revert w. induction Hr using @ref_typed_ind; simpl;\n    eauto using ctree_singleton_seg_Forall_inv, ctree_singleton_seg_typed.\nQed.\nLemma ctree_singleton_seg_flatten \u0393 \u0394 \u03c4 rs w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192\n  ctree_flatten (ctree_singleton_seg \u0393 rs w) =\n   replicate (ref_seg_object_offset \u0393 rs) \u2205 ++\n   ctree_flatten w ++\n   replicate (bit_size_of \u0393 \u03c4 - ref_seg_object_offset \u0393 rs - bit_size_of \u0393 \u03c3) \u2205.\nProof.\n  intros H\u0393. destruct 1 as [\u03c4 i n Hi|s i \u03c4s \u03c4 Ht Hi|s i ? \u03c4s];\n    intros H\u03c4; simplify_option_eq.\n  * pattern n at 1; replace n with (i + S (n - i - 1)) by lia.\n    rewrite replicate_plus; simpl.\n    rewrite insert_app_r_alt, replicate_length, Nat.sub_diag by auto; simpl.\n    rewrite bind_app, bind_cons, !ctree_flatten_replicate_new by eauto.\n    by rewrite bit_size_of_array, !Nat.mul_sub_distr_r, Nat.mul_1_l.\n  * erewrite bit_size_of_struct by eauto.\n    assert (\u2713{\u0393}* \u03c4s) by eauto; clear Ht H\u03c4; revert i Hi.\n    unfold bit_offset_of, field_bit_padding.\n    induction (bit_size_of_fields _ \u03c4s H\u0393) as [|\u03c4' sz \u03c4s szs ? Htzs IH];\n      intros [|i] Hi; decompose_Forall_hyps.\n    { rewrite Nat.sub_0_r, Nat.add_sub_swap, replicate_plus by done.\n      rewrite !(assoc_L (++)); f_equal. clear IH.\n      induction Htzs as [|\u03c4' sz' \u03c4s szs ?? IH]; decompose_Forall_hyps; auto.\n      rewrite ctree_flatten_new, IH, <-!replicate_plus by done; f_equal; lia. }\n    rewrite IH, ctree_flatten_new, (assoc_L (++)),\n      <-!replicate_plus by done; do 2 f_equal; auto with f_equal lia.\n  * by erewrite Nat.sub_0_r, resize_ge, ctree_flatten_length by eauto.\n  * by rewrite Nat.sub_0_r.\nQed.\nLemma ctree_singleton_flatten \u0393 \u0394 \u03c4 r w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192\n  ctree_flatten (ctree_singleton \u0393 r w) =\n   replicate (ref_object_offset \u0393 r) \u2205 ++\n   ctree_flatten w ++\n   replicate (bit_size_of \u0393 \u03c4 - ref_object_offset \u0393 r - bit_size_of \u0393 \u03c3) \u2205.\nProof.\n  unfold ref_object_offset. intros ? Hrs; revert w.\n  induction Hrs as [|r rs \u03c41 \u03c42 \u03c43 Hrs Hr IH]\n    using @ref_typed_ind; intros w ?; csimpl.\n  { by rewrite Nat.sub_0_r, Nat.sub_diag; simpl; rewrite (right_id_L [] (++)). }\n  erewrite IH, ctree_singleton_seg_flatten\n    by eauto using ctree_singleton_seg_typed; clear IH.\n  apply ref_seg_object_offset_size' in Hrs; auto.\n  apply ref_object_offset_size' in Hr; auto; unfold ref_object_offset in Hr.\n  rewrite !(assoc_L (++)), <-replicate_plus,\n    <-!(assoc_L (++)), <-replicate_plus; f_lia.\nQed.\nLemma ctree_singleton_seg_weaken \u03931 \u03932 \u03c4 rs w \u03c3 :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 \u03931 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 \u2713{\u03931} \u03c4 \u2192 \n  ctree_singleton_seg \u03931 rs w = ctree_singleton_seg \u03932 rs w.\nProof.\n  by destruct 3; intros;\n    simplify_option_eq by eauto using lookup_compound_weaken;\n    erewrite ?ctree_new_weaken, ?ctree_news_weaken,\n    ?field_bit_padding_weaken, ?(bit_size_of_weaken \u03931 \u03932) by eauto.\nQed.\nLemma ctree_singleton_weaken \u03931 \u03932 \u03c4 r w \u03c3 :\n  \u2713 \u03931 \u2192 \u03931 \u2286 \u03932 \u2192 \u03931 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 \u2713{\u03931} \u03c4 \u2192\n  ctree_singleton \u03931 r w = ctree_singleton \u03932 r w.\nProof.\n  intros ?? Hr. revert w. induction Hr using @ref_typed_ind; intros; simpl;\n    erewrite ?ctree_singleton_seg_weaken by eauto using ref_typed_type_valid;\n    eauto.\nQed.\nLemma ctree_lookup_singleton_seg \u0393 \u03c4 rs w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192\n  \u00acctree_unmapped w \u2192 ctree_singleton_seg \u0393 rs w !!{\u0393} rs = Some w.\nProof.\n  destruct 2 as [|s i \u03c4s|]; intros; simplify_option_eq.\n  * by rewrite list_lookup_insert by solve_length.\n  * assert (length (field_bit_padding \u0393 \u03c4s) = length \u03c4s) as Hlen\n      by eauto using field_bit_padding_length.\n    assert (i < length \u03c4s) by eauto using lookup_lt_Some.\n    by rewrite <-list_lookup_fmap, fst_zip, list_lookup_insert by solve_length.\n  * done.\nQed.\nLemma ctree_lookup_singleton \u0393 \u0394 \u03c4 r w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192 \u00acctree_unmapped w \u2192\n  ctree_singleton \u0393 r w !!{\u0393} r = Some w.\nProof.\n  intros ? Hr. revert w. induction Hr as [|r rs \u03c41 \u03c42 \u03c43 ?? IH]\n    using @ref_typed_ind; intros; simpl; auto.\n  rewrite ctree_lookup_cons, IH by eauto using\n    ctree_singleton_seg_Forall_inv, ctree_singleton_seg_typed; simpl.\n  eauto using ctree_lookup_singleton_seg.\nQed.\nLemma ctree_alter_singleton_seg \u0393 g \u03c4 rs w \u03c3 :\n  \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 \u00acctree_unmapped w \u2192 \u00acctree_unmapped (g w) \u2192\n  ctree_alter_seg \u0393 g rs (ctree_singleton_seg \u0393 rs w)\n  = ctree_singleton_seg \u0393 rs (g w).\nProof.\n  destruct 1; intros ??; simplify_option_eq; f_equal.\n  * by rewrite !list_insert_alter, <-list_alter_compose.\n  * rewrite !list_insert_alter. generalize i (ctree_new \u0393 \u2205 <$> \u03c4s).\n    induction (_ <$> _); intros [|?] [|??]; f_equal'; auto.\nQed.\nLemma ctree_alter_singleton \u0393 \u0394 g \u03c4 r w \u03c3 :\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 \n  (\u0393,\u0394) \u22a2 w : \u03c3 \u2192 \u00acctree_unmapped w \u2192 \u00acctree_unmapped (g w) \u2192\n  ctree_alter \u0393 g r (ctree_singleton \u0393 r w) = ctree_singleton \u0393 r (g w).\nProof.\n  intros ? Hr. revert g w. induction Hr as [|r rs \u03c41 \u03c42 \u03c43 ?? IH]\n    using @ref_typed_ind; intros; simpl; auto.\n  by erewrite IH, ctree_alter_singleton_seg\n    by eauto using ctree_alter_lookup_seg_Forall, ctree_lookup_singleton_seg,\n    ctree_singleton_seg_typed, ctree_singleton_seg_Forall_inv.\nQed.\nLemma ctree_merge_new {B} \u0393 f \u03c4 (ys : list B) \u03b3b :\n  (\u2200 y, f \u03b3b y = \u03b3b) \u2192 pbit_indetify \u03b3b = \u03b3b \u2192\n  \u2713 \u0393 \u2192 \u2713{\u0393} \u03c4 \u2192 length ys = bit_size_of \u0393 \u03c4 \u2192\n  ctree_merge f (ctree_new \u0393 \u03b3b \u03c4) ys = ctree_new \u0393 \u03b3b \u03c4.\nProof.\n  intros ???? Hlen; unfold ctree_new.\n  assert (zip_with f (pbit_indetify <$> replicate (bit_size_of \u0393 \u03c4) \u03b3b) ys\n    = pbit_indetify <$> zip_with f (replicate (bit_size_of \u0393 \u03c4) \u03b3b) ys).\n  { rewrite fmap_replicate, !zip_with_replicate_l, <-list_fmap_compose by done.\n    apply list_fmap_ext; simpl; intros; congruence. }\n  by erewrite ctree_merge_unflatten,\n    zip_with_replicate_l, const_fmap, Hlen by eauto.\nQed.\nLemma ctree_merge_singleton_seg {B} \u0393 \u0394 f \u03c4 rs w (ys : list B) \u03c3 :\n  (\u2200 y, f \u2205 y = \u2205) \u2192\n  (\u2200 \u03b3b y, sep_valid \u03b3b \u2192 sep_unmapped (f \u03b3b y) \u2192 sep_unmapped \u03b3b) \u2192\n  \u2713 \u0393 \u2192 \u0393 \u22a2 rs : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192 \u00acctree_unmapped w \u2192\n  length ys = bit_size_of \u0393 \u03c4 \u2192\n  ctree_merge f (ctree_singleton_seg \u0393 rs w) ys\n  = ctree_singleton_seg \u0393 rs (ctree_merge f w\n      (take (bit_size_of \u0393 \u03c3) (drop (ref_seg_object_offset \u0393 rs) ys))).\nProof.\n  intros ?? H\u0393. assert (\u2200 \u03b3bs ys,\n    Forall sep_valid \u03b3bs \u2192 Forall sep_unmapped (zip_with f \u03b3bs ys) \u2192\n    length \u03b3bs = length ys \u2192 Forall sep_unmapped \u03b3bs).\n  { intros \u03b3bs ys' H\u03b3bs; revert ys'; induction H\u03b3bs; intros [|??] ??;\n      decompose_Forall_hyps; constructor; eauto. }\n  destruct 1 as [\u03c4 i n _|s i \u03c4s \u03c4 Ht Hi|s i ? \u03c4s];\n    intros Hw ? Hys; simplify_option_eq by\n      (rewrite ?ctree_flatten_merge;\n       eauto 6 using @ctree_valid_Forall, ctree_typed_sep_valid); f_equal.\n  * revert i ys Hys. rewrite bit_size_of_array.\n    induction n; intros [|?] ??; f_equal';\n      erewrite <-?drop_drop, ?ctree_flatten_length, ?ctree_merge_new\n      by eauto using (ctree_new_typed _ \u0394); eauto.\n    cut (length (drop (bit_size_of \u0393 \u03c4) ys) = n * bit_size_of \u0393 \u03c4); [|auto].\n    generalize (drop (bit_size_of \u0393 \u03c4) ys).\n    elim n; intros; f_equal'; erewrite ?ctree_flatten_length,\n      ?ctree_merge_new by eauto using (ctree_new_typed _ \u0394); eauto.\n  * revert i ys Hi Hys. erewrite bit_size_of_struct by eauto.\n    assert (\u2713{\u0393}* \u03c4s) by eauto. clear Ht.\n    unfold field_bit_sizes,bit_offset_of, field_bit_padding, field_bit_sizes.\n    induction (size_of_fields _ \u03c4s H\u0393) as [|\u03c4' sz \u03c4s szs ? Htzs IH];\n      intros [|i] ys Hi Hlen; decompose_Forall_hyps.\n    + erewrite ctree_flatten_length, replicate_length, drop_0,\n        zip_with_replicate_l, const_fmap, take_length_le by eauto; f_equal.\n      assert (bit_size_of \u0393 \u03c4 \u2264 sz * char_bits).\n      { by apply Nat.mul_le_mono_r. }\n      rewrite drop_drop, le_plus_minus_r by done.\n      cut (length (drop (sz * char_bits) ys)\n        = sum_list ((\u03bb sz, sz * char_bits) <$> szs)); [|solve_length].\n      generalize (drop (sz * char_bits) ys); clear IH Hlen.\n      induction Htzs as [|\u03c4' sz' ???? IH];\n        decompose_Forall_hyps; intros ys' ?; auto.\n      assert (bit_size_of \u0393 \u03c4' \u2264 sz' * char_bits).\n      { by apply Nat.mul_le_mono_r. }\n      by erewrite ctree_flatten_length, IH, zip_with_replicate_l,\n         const_fmap,replicate_length, take_length_le, ctree_merge_new\n        by eauto using (ctree_new_typed _ \u0394).\n    + assert (bit_size_of \u0393 \u03c4' \u2264 sz * char_bits)\n        by (by apply Nat.mul_le_mono_r).\n      erewrite ctree_flatten_length, ctree_merge_new, replicate_length,\n        zip_with_replicate_l, const_fmap, take_length_le, IH, !drop_drop\n        by eauto using (ctree_new_typed _ \u0394); f_lia.\n  * by erewrite ctree_flatten_length by eauto.\n  * erewrite ctree_flatten_length, zip_with_replicate_l by eauto.\n    erewrite const_fmap by done; f_equal; auto.\nQed.\nLemma ctree_merge_singleton {B} \u0393 \u0394 f \u03c4 r w (ys : list B) \u03c3 :\n  (\u2200 y, f \u2205 y = \u2205) \u2192\n  (\u2200 \u03b3b y, sep_valid \u03b3b \u2192 sep_unmapped (f \u03b3b y) \u2192 sep_unmapped \u03b3b) \u2192\n  \u2713 \u0393 \u2192 \u0393 \u22a2 r : \u03c4 \u21a3 \u03c3 \u2192 (\u0393,\u0394) \u22a2 w : \u03c3 \u2192 \u00acctree_unmapped w \u2192\n  length ys = bit_size_of \u0393 \u03c4 \u2192\n  ctree_merge f (ctree_singleton \u0393 r w) ys\n  = ctree_singleton \u0393 r (ctree_merge f w\n      (take (bit_size_of \u0393 \u03c3) (drop (ref_object_offset \u0393 r) ys))).\nProof.\n  unfold ref_object_offset. intros ??? Hr. revert w ys.\n  induction Hr as [|r rs \u03c41 \u03c42 \u03c43 Hrs Hr IH] using @ref_typed_ind;\n    intros w ys ???; simplify_equality'; [by rewrite drop_0, take_ge by done|].\n  apply ref_object_offset_size' in Hr; auto; unfold ref_object_offset in Hr.\n  assert (ref_seg_object_offset \u0393 rs + bit_size_of \u0393 \u03c43 \u2264 bit_size_of \u0393 \u03c42)\n    by auto using  ref_seg_object_offset_size'.\n  erewrite IH, ctree_merge_singleton_seg\n    by eauto using ctree_singleton_seg_Forall_inv, ctree_singleton_seg_typed.\n  rewrite !take_drop_commute,\n    drop_drop, take_take, Min.min_l by solve_length; f_lia.\nQed.\nEnd memory_trees.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/memory/memory_trees.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.18899095098846289}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableWalk.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition data_create_spec0 (g_rd: Pointer) (data_addr: Z64) (map_addr: Z64) (g_data: Pointer) (g_src: Pointer) (adt: RData) : option (RData * Z64) :=\n    match g_rd, data_addr, map_addr, g_data, g_src with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _data_addr, VZ64 _map_addr, (_g_data_base, _g_data_ofst), (_g_src_base, _g_src_ofst) =>\n      rely is_int (4 - 1);\n      rely is_int64 _map_addr;\n      rely is_int64 (4 - 1);\n      when adt == table_walk_lock_unlock_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 (4 - 1)) adt;\n      when'' _g_llt_base, _g_llt_ofst == get_wi_g_llt_spec  adt;\n      rely is_int _g_llt_ofst;\n      when' _index == get_wi_index_spec  adt;\n      rely is_int64 _index;\n      when _t'7 == is_null_spec (_g_llt_base, _g_llt_ofst) adt;\n      rely is_int _t'7;\n      if (_t'7 =? 1) then\n        let _ret := 1 in\n        Some (adt, (VZ64 _ret))\n      else\n        when'' _ll_table_base, _ll_table_ofst, adt == granule_map_spec (_g_llt_base, _g_llt_ofst) 5 adt;\n        rely is_int _ll_table_ofst;\n        when' _pte_val == pgte_read_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) adt;\n        rely is_int64 _pte_val;\n        rely is_int64 (Z.land _pte_val 504403158265495552);\n        rely is_int64 ((Z.land _pte_val 504403158265495552) / 72057594037927936);\n        if (negb (((Z.land _pte_val 504403158265495552) / 72057594037927936) =? 0)) 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          when'' _data_base, _data_ofst, adt == granule_map_spec (_g_data_base, _g_data_ofst) 1 adt;\n          rely is_int _data_ofst;\n          when adt == ns_granule_map_spec 0 (_g_src_base, _g_src_ofst) adt;\n          when _ns_access_ok, adt == ns_buffer_read_data_spec 0 (_data_base, _data_ofst) adt;\n          rely is_int _ns_access_ok;\n          when adt == ns_buffer_unmap_spec 0 adt;\n          if (_ns_access_ok =? 0) then\n            when adt == granule_memzero_mapped_spec (_data_base, _data_ofst) adt;\n            let _ret := 1 in\n            when adt == buffer_unmap_spec (_data_base, _data_ofst) 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          else\n            rely is_int64 (1 * 72057594037927936);\n            rely is_int64 (Z.lor (1 * 72057594037927936) _data_addr);\n            let _pte_val := (Z.lor (1 * 72057594037927936) _data_addr) in\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _pte_val) adt;\n            rely is_int64 _data_addr;\n            when adt == set_mapping_spec (VZ64 _map_addr) (VZ64 _data_addr) adt;\n            when adt == granule_get_spec (_g_llt_base, _g_llt_ofst) adt;\n            let _ret := 0 in\n            when adt == buffer_unmap_spec (_data_base, _data_ofst) 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/data_create.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.1889281731502934}}
{"text": "Require Import Rel.Definitions.\nRequire Import LibReflect LibList.\nRequire Import Util.Wf_natnat.\nRequire Import Lang.Static.\nRequire Import Lang.BindingsFacts.\nRequire Import Lang.StaticFacts.\nSet Implicit Arguments.\n\nImplicit Types EV HV : Set.\n\nSection section_X_weaken_aux.\n\nLocal Hint Extern 1 => match goal with\n| [ |- ?n \u22a8 ?X \u2248\u1d62 ?X ] => repeat iintro ; apply auto_contr_id\n| [ |- ?n \u22a8 ?X \u21d4 ?X ] => apply auto_contr_id\n| [ |- Acc lt' (_, _) ] => try lt'_solve\nend.\n\nFixpoint\n  X_weaken_\ud835\udcfe_aux\n  (n : nat)\n  (EV HV : Set)\n  (\u039e \u039e' : XEnv EV HV)\n  (Wf_\u039e\u039e' : wf_XEnv (\u039e & \u039e'))\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (t\u2081 t\u2082 : tm0) (\u03c8 : IRel \ud835\udce3_Sig) l\u2081 l\u2082 (\u03b5 : ef EV HV \u2205)\n  (Wf_\u03b5 : wf_ef \u039e \u03b5)\n  (W : Acc lt' (n, 0))\n  {struct W} :\n  (n \u22a8\n    \ud835\udcfe\u27e6 \u039e \u22a2 \u03b5 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 \u21d4\n    \ud835\udcfe\u27e6 (\u039e & \u039e') \u22a2 \u03b5 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082)\n\nwith\n  X_weaken_\ud835\udce4_aux\n  (n : nat)\n  (EV HV : Set)\n  (\u039e \u039e' : XEnv EV HV)\n  (Wf_\u039e\u039e' : wf_XEnv (\u039e & \u039e'))\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (t\u2081 t\u2082 : tm0) (\u03c8 : IRel \ud835\udce3_Sig) l\u2081 l\u2082 (\ud835\udcd4 : eff EV HV \u2205)\n  (Wf_\ud835\udcd4 : wf_eff \u039e \ud835\udcd4)\n  (W : Acc lt' (n, size_eff \ud835\udcd4))\n  {struct W} :\n  (n \u22a8\n    \ud835\udce4\u27e6 \u039e \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 \u21d4\n    \ud835\udce4\u27e6 (\u039e & \u039e') \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082)\n\nwith\n  X_weaken_\ud835\udce5_aux\n  (n : nat)\n  (EV HV : Set)\n  (\u039e \u039e' : XEnv EV HV)\n  (Wf_\u039e\u039e' : wf_XEnv (\u039e & \u039e'))\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (v\u2081 v\u2082 : val0) (T : ty EV HV \u2205)\n  (Wf_T : wf_ty \u039e T)\n  (W : Acc lt' (n, size_ty T))\n  {struct W} :\n  (n \u22a8\n    \ud835\udce5\u27e6 \u039e \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 \u21d4\n    \ud835\udce5\u27e6 (\u039e & \u039e') \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082)\n.\n\nProof.\n\n{\ndestruct \u03b5 as [ \u03b1 | [ p | [ | X ] ] ] ; simpl.\n+ auto_contr.\n+ auto_contr.\n+ auto_contr.\n+ inversion Wf_\u03b5 as [ | ? [ ? HX | ] ] ; subst.\n  repeat (apply auto_contr_exists ; intro).\n  apply auto_contr_conj ; [ apply auto_contr_id | ].\n  apply auto_contr_conj ; [ apply auto_contr_id | ].\n  apply auto_contr_conj ; [ apply auto_contr_id | ].\n  apply auto_contr_conj ; [ | apply auto_contr_id ].\n  repeat (apply auto_contr_exists ; intro).\n  apply auto_contr_conj ; [ apply auto_contr_id | ].\n  repeat (apply auto_contr_exists ; intro).\n  isplit ; iintro' H.\n  - idestruct H as BindsX H ; isplit.\n    * clear - BindsX HX Wf_\u039e\u039e'.\n      iintro_prop ; ielim_prop BindsX.\n      apply binds_concat_left ; [ apply BindsX | ].\n      clear - Wf_\u039e\u039e' HX.\n      apply wf_XEnv_ok in Wf_\u039e\u039e'.\n      eapply ok_concat_indom_l ; eauto.\n    * later_shift.\n      ielim_prop BindsX.\n      apply wf_XEnv_concat_inv_l in Wf_\u039e\u039e' as Wf_\u039e.\n      specialize (binds_wf Wf_\u039e BindsX) as Wf_T\ud835\udcd4.\n      erewrite <- I_iff_elim_M ; [ apply H | clear H ].\n      apply \ud835\udcd7_Fun'_nonexpansive ; repeat iintro ; [auto|].\n      eapply I_iff_transitive ; [ | apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3 ].\n      eapply I_iff_transitive ; [ apply I_iff_symmetric ; apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3 | ].\n      apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; crush.\n  - idestruct H as BindsX H.\n    assert (binds X (x8, x9) \u039e) as BindsX'.\n    { clear - BindsX HX Wf_\u039e\u039e'.\n      ielim_prop BindsX.\n      eapply binds_concat_left_inv ; [ apply BindsX | ].\n      apply wf_XEnv_ok in Wf_\u039e\u039e'.\n      eapply ok_concat_indom_l ; eauto.\n    }\n    isplit ; [crush|].\n    later_shift.\n    apply wf_XEnv_concat_inv_l in Wf_\u039e\u039e' as Wf_\u039e.\n    specialize (binds_wf Wf_\u039e BindsX') as Wf_T\ud835\udcd4.\n    erewrite I_iff_elim_M ; [ apply H | clear H ].\n    apply \ud835\udcd7_Fun'_nonexpansive ; repeat iintro ; [auto|].\n    eapply I_iff_transitive ; [ | apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3 ].\n    eapply I_iff_transitive ; [ apply I_iff_symmetric ; apply fold_\ud835\udce5\ud835\udce4_in_\ud835\udce3 | ].\n    apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; crush.\n}\n\n{\ndestruct \ud835\udcd4 ; simpl ; [auto|].\ninversion Wf_\ud835\udcd4 ; auto_contr ; auto.\n}\n\n{\ndestruct T ; simpl.\n+ crush.\n+ inversion Wf_T.\n  auto_contr.\n  - apply X_weaken_\ud835\udce5_aux ; auto.\n  - apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; crush.\n+ inversion Wf_T.\n  auto_contr.\n  apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; [|auto].\n  rewrite EV_map_XEnv_concat.\n  apply X_weaken_\ud835\udce5_aux ; [|crush|crush].\n  rewrite <- EV_map_XEnv_concat.\n  apply EV_map_wf_XEnv ; assumption.\n+ inversion Wf_T.\n  auto_contr.\n  apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; [|auto].\n  rewrite HV_map_XEnv_concat.\n  apply X_weaken_\ud835\udce5_aux ; [|crush|crush].\n  rewrite <- HV_map_XEnv_concat.\n  apply HV_map_wf_XEnv ; assumption.\n}\n\nQed.\n\nEnd section_X_weaken_aux.\n\n\nSection section_X_weaken.\n\nContext (n : nat).\nContext (EV HV : Set).\nContext (\u039e \u039e' : XEnv EV HV).\nContext (Wf_\u039e\u039e' : wf_XEnv (\u039e & \u039e')).\nContext (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig).\nContext (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig).\n\nHint Resolve lt'_wf.\n\nLemma X_weaken_\ud835\udce5 T (Wf_T : wf_ty \u039e T) \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 :\nn \u22a8 \ud835\udce5\u27e6 \u039e \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 \u21d4\n    \ud835\udce5\u27e6 (\u039e & \u039e') \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082.\nProof.\napply X_weaken_\ud835\udce5_aux ; auto.\nQed.\n\nLemma X_weaken_\ud835\udce4 \ud835\udcd4 (Wf_\ud835\udcd4 : wf_eff \u039e \ud835\udcd4) \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 :\nn \u22a8 \ud835\udce4\u27e6 \u039e \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 \u21d4\n    \ud835\udce4\u27e6 (\u039e & \u039e') \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082.\nProof.\napply X_weaken_\ud835\udce4_aux ; auto.\nQed.\n\nHint Resolve X_weaken_\ud835\udce5 X_weaken_\ud835\udce4.\n\nLemma X_weaken_\ud835\udce3 T (Wf_T : wf_ty \u039e T) \ud835\udcd4 (Wf_\ud835\udcd4 : wf_eff \u039e \ud835\udcd4) \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 :\nn \u22a8 \ud835\udce3\u27e6 \u039e \u22a2 T # \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u21d4\n    \ud835\udce3\u27e6 (\u039e & \u039e') \u22a2 T # \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082.\nProof.\napply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\nQed.\n\nEnd section_X_weaken.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Compat_weaken_X.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.18875758458022}}
{"text": "(* -*- mode: coq; coq-prog-args: (\"-indices-matter\") -*- *)\n(* File reduced by coq-bug-finder from original input, then from 11678 lines to 11330 lines, then from 10721 lines to 9544 lines, then from 9549 lines to 794 lines, then from 810 lines to 785 lines, then from 628 lines to 246 lines, then from 220 lines to 89 lines, then from 80 lines to 47 lines *)\n(* coqc version trunk (August 2014) compiled on Aug 22 2014 4:17:28 with OCaml 4.01.0\n   coqtop version cagnode17:/afs/csail.mit.edu/u/j/jgross/coq-trunk,trunk (a67cc6941434124465f20b14a1256f2ede31a60e) *)\n\nSet Implicit Arguments.\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.\nDefinition transport {A : Type} (P : A -> Type) {x y : A} (p : x = y) (u : P x) : P y := match p with idpath => u end.\nLocal Set Primitive Projections.\nRecord prod (A B : Type) := pair { fst : A ; snd : B }.\nNotation \"x * y\" := (prod x y) : type_scope.\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\nAxiom path_prod : forall {A B : Type} (z z' : A * B), (fst z = fst z') -> (snd z = snd z') -> (z = z').\nAxiom transport_path_prod : forall A B (P : A * B -> Type) (x y : A * B) (HA : fst x = fst y) (HB : snd x = snd y) Px,\n                              transport P (path_prod _ _ HA HB) Px\n                              = transport (fun x => P (x, snd y)) HA (transport (fun y => P (fst x, y)) HB Px).\nGoal forall (T0 : Type) (snd1 snd0 f : T0) (p : @paths T0 f snd0)\n            (f0 : T0) (p1 : @paths T0 f0 snd1) (T1 : Type)\n            (fst1 fst0 : T1) (p0 : @paths T1 fst0 fst0) (p2 : @paths T1 fst1 fst1)\n            (T : Type) (x2 : T) (T2 : Type) (T3 : forall (_ : T2) (_ : T2), Type)\n            (x' : forall (_ : T1) (_ : T), T2) (m : T3 (x' fst1 x2) (x' fst0 x2)),\n       @paths (T3 (x' fst1 x2) (x' fst0 x2))\n              (@transport (prod T1 T0)\n                          (fun x : prod T1 T0 =>\n                             T3 (x' fst1 x2) (x' (fst x) x2))\n                          (@pair T1 T0 fst0 f) (@pair T1 T0 fst0 snd0)\n                          (@path_prod T1 T0 (@pair T1 T0 fst0 f)\n                                      (@pair T1 T0 fst0 snd0) p0 p)\n                          (@transport (prod T1 T0)\n                                      (fun x : prod T1 T0 =>\n                                         T3 (x' (fst x) x2) (x' fst0 x2))\n                                      (@pair T1 T0 fst1 f0) (@pair T1 T0 fst1 snd1)\n                                      (@path_prod T1 T0 (@pair T1 T0 fst1 f0)\n                                                  (@pair T1 T0 fst1 snd1) p2 p1) m)) m.\n  intros.\n  match goal with\n    | [ |- context[transport ?P (path_prod ?x ?y ?HA ?HB) ?Px] ]\n      => rewrite (transport_path_prod P x y HA HB Px)\n  end || fail \"bad\".\n  Undo.\n  Set Printing All.\n  rewrite transport_path_prod. (* Toplevel input, characters 15-43:\nError:\nIn environment\nT0 : Type\nsnd1 : T0\nsnd0 : T0\nf : T0\np : @paths T0 f snd0\nf0 : T0\np1 : @paths T0 f0 snd1\nT1 : Type\nfst1 : T1\nfst0 : T1\np0 : @paths T1 fst0 fst0\np2 : @paths T1 fst1 fst1\nT : Type\nx2 : T\nT2 : Type\nT3 : forall (_ : T2) (_ : T2), Type\nx' : forall (_ : T1) (_ : T), T2\nm : T3 (x' fst1 x2) (x' fst0 x2)\nUnable to unify \"?25 (@pair ?23 ?24 (fst ?27) (snd ?27))\" with\n\"?25 ?27\".\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/3539.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.1887575808566295}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\n\nLemma ReseedRes: forall X r v, @return_value_relate_result X r (Vint v) -> Int.eq v (Int.repr (-20864)) = false.\nProof. intros.\n  unfold return_value_relate_result in H.\n  destruct r. inversion H; reflexivity.\n  destruct e; inversion H; try reflexivity.\n  apply Int.eq_false. eapply ENT_GenErrAx.\nQed.\n\nLemma hmac_interp_empty d r: hmac_interp d r |-- md_empty r.\nProof.\ndestruct d; simpl. auto.\neapply derives_trans. apply md_relate_full. apply md_full_empty.\napply md_full_empty.\nQed.\n\nLemma instantiate256_reseed d s pr_flag rc ri (ZLc'256F : (Zlength d >? 256) = false):\n      instantiate_function_256 s pr_flag  d =\n      mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs initial_key initial_value rc 48 pr_flag ri) d.\nProof. intros.\n  unfold instantiate_function_256; simpl.\n  rewrite ZLc'256F, andb_negb_r.\n  assert (MaxString': Zlength d >? max_personalization_string_length = false).\n  { apply Zgt_is_gt_bool_f. apply Zgt_is_gt_bool_f in ZLc'256F.\n    unfold max_personalization_string_length. lia. }\n  rewrite MaxString' in *; trivial.\nQed.", "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_seed_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.18868221808365662}}
{"text": "From iris.base_logic.lib Require Export fancy_updates.\nFrom iris.program_logic Require Export language.\nFrom iris.bi Require Export weakestpre.\nFrom iris.proofmode Require Import base tactics classes.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nClass irisG (\u039b : language) (\u03a3 : gFunctors) := IrisG {\n  iris_invG :> invG \u03a3;\n\n  (** The state interpretation is an invariant that should hold in between each\n  step of reduction. Here [\u039bstate] is the global state, [list \u039bobservation] are\n  the remaining observations, and [nat] is the number of forked-off threads\n  (not the total number of threads, which is one higher because there is always\n  a main thread). *)\n  state_interp : state \u039b \u2192 list (observation \u039b) \u2192 nat \u2192 iProp \u03a3;\n\n  (** A fixed postcondition for any forked-off thread. For most languages, e.g.\n  heap_lang, this will simply be [True]. However, it is useful if one wants to\n  keep track of resources precisely, as in e.g. Iron. *)\n  fork_post : val \u039b \u2192 iProp \u03a3;\n}.\nGlobal Opaque iris_invG.\n\nDefinition wp_pre `{irisG \u039b \u03a3} (s : stuckness)\n    (wp : coPset -c> expr \u039b -c> (val \u039b -c> iProp \u03a3) -c> iProp \u03a3) :\n    coPset -c> expr \u039b -c> (val \u039b -c> iProp \u03a3) -c> iProp \u03a3 := \u03bb E e1 \u03a6,\n  match to_val e1 with\n  | Some v => |={E}=> \u03a6 v\n  | None => \u2200 \u03c31 \u03ba \u03bas n,\n     state_interp \u03c31 (\u03ba ++ \u03bas) n ={E,\u2205}=\u2217\n       \u231cif s is NotStuck then reducible e1 \u03c31 else True\u231d \u2217\n       \u2200 e2 \u03c32 efs, \u231cprim_step e1 \u03c31 \u03ba e2 \u03c32 efs\u231d ={\u2205,\u2205,E}\u25b7=\u2217\n         state_interp \u03c32 \u03bas (length efs + n) \u2217\n         wp E e2 \u03a6 \u2217\n         [\u2217 list] i \u21a6 ef \u2208 efs, wp \u22a4 ef fork_post\n  end%I.\n\nLocal Instance wp_pre_contractive `{irisG \u039b \u03a3} s : Contractive (wp_pre s).\nProof.\n  rewrite /wp_pre=> n wp wp' Hwp E e1 \u03a6.\n  repeat (f_contractive || f_equiv); apply Hwp.\nQed.\n\nDefinition wp_def `{irisG \u039b \u03a3} (s : stuckness) :\n  coPset \u2192 expr \u039b \u2192 (val \u039b \u2192 iProp \u03a3) \u2192 iProp \u03a3 := fixpoint (wp_pre s).\nDefinition wp_aux `{irisG \u039b \u03a3} : seal (@wp_def \u039b \u03a3 _). by eexists. Qed.\nInstance wp' `{irisG \u039b \u03a3} : Wp \u039b (iProp \u03a3) stuckness := wp_aux.(unseal).\nDefinition wp_eq `{irisG \u039b \u03a3} : wp = @wp_def \u039b \u03a3 _ := wp_aux.(seal_eq).\n\nSection wp.\nContext `{irisG \u039b \u03a3}.\nImplicit Types s : stuckness.\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 iProp \u03a3.\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\n\n(* Weakest pre *)\nLemma wp_unfold s E e \u03a6 :\n  WP e @ s; E {{ \u03a6 }} \u22a3\u22a2 wp_pre s (wp (PROP:=iProp \u03a3)  s) E e \u03a6.\nProof. rewrite wp_eq. apply (fixpoint_unfold (wp_pre s)). Qed.\n\nGlobal Instance wp_ne s E e n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (wp (PROP:=iProp \u03a3) s E e).\nProof.\n  revert e. induction (lt_wf n) as [n _ IH]=> e \u03a6 \u03a8 H\u03a6.\n  rewrite !wp_unfold /wp_pre.\n  (* FIXME: figure out a way to properly automate this proof *)\n  (* FIXME: reflexivity, as being called many times by f_equiv and f_contractive\n  is very slow here *)\n  do 24 (f_contractive || f_equiv). apply IH; first lia.\n  intros v. eapply dist_le; eauto with lia.\nQed.\nGlobal Instance wp_proper s E e :\n  Proper (pointwise_relation _ (\u2261) ==> (\u2261)) (wp (PROP:=iProp \u03a3) s E e).\nProof.\n  by intros \u03a6 \u03a6' ?; apply equiv_dist=>n; apply wp_ne=>v; apply equiv_dist.\nQed.\n\nLemma wp_value' s E \u03a6 v : \u03a6 v \u22a2 WP of_val v @ s; E {{ \u03a6 }}.\nProof. iIntros \"H\u03a6\". rewrite wp_unfold /wp_pre to_of_val. auto. Qed.\nLemma wp_value_inv' s E \u03a6 v : WP of_val v @ s; E {{ \u03a6 }} ={E}=\u2217 \u03a6 v.\nProof. by rewrite wp_unfold /wp_pre to_of_val. Qed.\n\nLemma wp_strong_mono s1 s2 E1 E2 e \u03a6 \u03a8 :\n  s1 \u2291 s2 \u2192 E1 \u2286 E2 \u2192\n  WP e @ s1; E1 {{ \u03a6 }} -\u2217 (\u2200 v, \u03a6 v ={E2}=\u2217 \u03a8 v) -\u2217 WP e @ s2; E2 {{ \u03a8 }}.\nProof.\n  iIntros (? HE) \"H H\u03a6\". iL\u00f6b as \"IH\" forall (e E1 E2 HE \u03a6 \u03a8).\n  rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:?.\n  { iApply (\"H\u03a6\" with \"[> -]\"). by iApply (fupd_mask_mono E1 _). }\n  iIntros (\u03c31 \u03ba \u03bas n) \"H\u03c3\". iMod (fupd_intro_mask' E2 E1) as \"Hclose\"; first done.\n  iMod (\"H\" with \"[$]\") as \"[% H]\".\n  iModIntro. iSplit; [by destruct s1, s2|]. iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!> !>\".\n  iMod \"H\" as \"(H\u03c3 & H & Hefs)\".\n  iMod \"Hclose\" as \"_\". iModIntro. iFrame \"H\u03c3\". iSplitR \"Hefs\".\n  - iApply (\"IH\" with \"[//] H H\u03a6\").\n  - iApply (big_sepL_impl with \"Hefs\"); iIntros \"!#\" (k ef _).\n    iIntros \"H\". iApply (\"IH\" with \"[] H\"); auto.\nQed.\n\nLemma fupd_wp s E e \u03a6 : (|={E}=> WP e @ s; E {{ \u03a6 }}) \u22a2 WP e @ s; E {{ \u03a6 }}.\nProof.\n  rewrite wp_unfold /wp_pre. iIntros \"H\". destruct (to_val e) as [v|] eqn:?.\n  { by iMod \"H\". }\n  iIntros (\u03c31 \u03ba \u03bas n) \"H\u03c31\". iMod \"H\". by iApply \"H\".\nQed.\nLemma wp_fupd s E e \u03a6 : WP e @ s; E {{ v, |={E}=> \u03a6 v }} \u22a2 WP e @ s; E {{ \u03a6 }}.\nProof. iIntros \"H\". iApply (wp_strong_mono s s E with \"H\"); auto. Qed.\n\nLemma wp_atomic s E1 E2 e \u03a6 `{!Atomic (stuckness_to_atomicity s) e} :\n  (|={E1,E2}=> WP e @ s; E2 {{ v, |={E2,E1}=> \u03a6 v }}) \u22a2 WP e @ s; E1 {{ \u03a6 }}.\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 (\u03c31 \u03ba \u03bas n) \"H\u03c3\". iMod \"H\". iMod (\"H\" $! \u03c31 with \"H\u03c3\") as \"[$ H]\".\n  iModIntro. iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!>!>\".\n  iMod \"H\" as \"(H\u03c3 & H & Hefs)\". destruct s.\n  - rewrite !wp_unfold /wp_pre. destruct (to_val e2) as [v2|] eqn:He2.\n    + iDestruct \"H\" as \">> $\". by iFrame.\n    + iMod (\"H\" $! _ [] with \"[$]\") as \"[H _]\". iDestruct \"H\" as %(? & ? & ? & ? & ?).\n      by edestruct (atomic _ _ _ _ _ Hstep).\n  - destruct (atomic _ _ _ _ _ Hstep) as [v <-%of_to_val].\n    iMod (wp_value_inv' with \"H\") as \">H\".\n    iModIntro. iFrame \"H\u03c3 Hefs\". by iApply wp_value'.\nQed.\n\nLemma wp_step_fupd s E1 E2 e P \u03a6 :\n  to_val e = None \u2192 E2 \u2286 E1 \u2192\n  (|={E1,E2}\u25b7=> P) -\u2217 WP e @ s; E2 {{ v, P ={E1}=\u2217 \u03a6 v }} -\u2217 WP e @ s; E1 {{ \u03a6 }}.\nProof.\n  rewrite !wp_unfold /wp_pre. iIntros (-> ?) \"HR H\".\n  iIntros (\u03c31 \u03ba \u03bas n) \"H\u03c3\". iMod \"HR\". iMod (\"H\" with \"[$]\") as \"[$ H]\".\n  iIntros \"!>\" (e2 \u03c32 efs Hstep). iMod (\"H\" $! e2 \u03c32 efs with \"[% //]\") as \"H\".\n  iIntros \"!>!>\". iMod \"H\" as \"(H\u03c3 & H & Hefs)\".\n  iMod \"HR\". iModIntro. iFrame \"H\u03c3 Hefs\".\n  iApply (wp_strong_mono s s E2 with \"H\"); [done..|].\n  iIntros (v) \"H\". by iApply \"H\".\nQed.\n\nLemma wp_bind K `{!LanguageCtx K} s E e \u03a6 :\n  WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ \u03a6 }} }} \u22a2 WP K e @ s; E {{ \u03a6 }}.\nProof.\n  iIntros \"H\". iL\u00f6b as \"IH\" forall (E e \u03a6). rewrite wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. by iApply fupd_wp. }\n  rewrite wp_unfold /wp_pre fill_not_val //.\n  iIntros (\u03c31 \u03ba \u03bas n) \"H\u03c3\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { iPureIntro. destruct s; last done.\n    unfold reducible in *. naive_solver eauto using fill_step. }\n  iIntros (e2 \u03c32 efs Hstep).\n  destruct (fill_step_inv e \u03c31 \u03ba e2 \u03c32 efs) as (e2'&->&?); auto.\n  iMod (\"H\" $! e2' \u03c32 efs with \"[//]\") as \"H\". iIntros \"!>!>\".\n  iMod \"H\" as \"(H\u03c3 & H & Hefs)\".\n  iModIntro. iFrame \"H\u03c3 Hefs\". by iApply \"IH\".\nQed.\n\nLemma wp_bind_inv K `{!LanguageCtx K} s E e \u03a6 :\n  WP K e @ s; E {{ \u03a6 }} \u22a2 WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ \u03a6 }} }}.\nProof.\n  iIntros \"H\". iL\u00f6b as \"IH\" forall (E e \u03a6). 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 (\u03c31 \u03ba \u03bas n) \"H\u03c3\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_fill. }\n  iIntros (e2 \u03c32 efs Hstep).\n  iMod (\"H\" $! (K e2) \u03c32 efs with \"[]\") as \"H\"; [by eauto using fill_step|].\n  iIntros \"!>!>\". iMod \"H\" as \"(H\u03c3 & H & Hefs)\".\n  iModIntro. iFrame \"H\u03c3 Hefs\". by iApply \"IH\".\nQed.\n\n(** * Derived rules *)\nLemma wp_mono s E e \u03a6 \u03a8 : (\u2200 v, \u03a6 v \u22a2 \u03a8 v) \u2192 WP e @ s; E {{ \u03a6 }} \u22a2 WP e @ s; E {{ \u03a8 }}.\nProof.\n  iIntros (H\u03a6) \"H\"; iApply (wp_strong_mono with \"H\"); auto.\n  iIntros (v) \"?\". by iApply H\u03a6.\nQed.\nLemma wp_stuck_mono s1 s2 E e \u03a6 :\n  s1 \u2291 s2 \u2192 WP e @ s1; E {{ \u03a6 }} \u22a2 WP e @ s2; E {{ \u03a6 }}.\nProof. iIntros (?) \"H\". iApply (wp_strong_mono with \"H\"); auto. Qed.\nLemma wp_stuck_weaken s E e \u03a6 :\n  WP e @ s; E {{ \u03a6 }} \u22a2 WP e @ E ?{{ \u03a6 }}.\nProof. apply wp_stuck_mono. by destruct s. Qed.\nLemma wp_mask_mono s E1 E2 e \u03a6 : E1 \u2286 E2 \u2192 WP e @ s; E1 {{ \u03a6 }} \u22a2 WP e @ s; E2 {{ \u03a6 }}.\nProof. iIntros (?) \"H\"; iApply (wp_strong_mono with \"H\"); auto. Qed.\nGlobal Instance wp_mono' s E e :\n  Proper (pointwise_relation _ (\u22a2) ==> (\u22a2)) (wp (PROP:=iProp \u03a3) s E e).\nProof. by intros \u03a6 \u03a6' ?; apply wp_mono. Qed.\n\nLemma wp_value s E \u03a6 e v : IntoVal e v \u2192 \u03a6 v \u22a2 WP e @ s; E {{ \u03a6 }}.\nProof. intros <-. by apply wp_value'. Qed.\nLemma wp_value_fupd' s E \u03a6 v : (|={E}=> \u03a6 v) \u22a2 WP of_val v @ s; E {{ \u03a6 }}.\nProof. intros. by rewrite -wp_fupd -wp_value'. Qed.\nLemma wp_value_fupd s E \u03a6 e v `{!IntoVal e v} :\n  (|={E}=> \u03a6 v) \u22a2 WP e @ s; E {{ \u03a6 }}.\nProof. intros. rewrite -wp_fupd -wp_value //. Qed.\nLemma wp_value_inv s E \u03a6 e v : IntoVal e v \u2192 WP e @ s; E {{ \u03a6 }} ={E}=\u2217 \u03a6 v.\nProof. intros <-. by apply wp_value_inv'. Qed.\n\nLemma wp_frame_l s E e \u03a6 R : R \u2217 WP e @ s; E {{ \u03a6 }} \u22a2 WP e @ s; E {{ v, R \u2217 \u03a6 v }}.\nProof. iIntros \"[? H]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\nLemma wp_frame_r s E e \u03a6 R : WP e @ s; E {{ \u03a6 }} \u2217 R \u22a2 WP e @ s; E {{ v, \u03a6 v \u2217 R }}.\nProof. iIntros \"[H ?]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\n\nLemma wp_frame_step_l s E1 E2 e \u03a6 R :\n  to_val e = None \u2192 E2 \u2286 E1 \u2192\n  (|={E1,E2}\u25b7=> R) \u2217 WP e @ s; E2 {{ \u03a6 }} \u22a2 WP e @ s; E1 {{ v, R \u2217 \u03a6 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 \u03a6 R :\n  to_val e = None \u2192 E2 \u2286 E1 \u2192\n  WP e @ s; E2 {{ \u03a6 }} \u2217 (|={E1,E2}\u25b7=> R) \u22a2 WP e @ s; E1 {{ v, \u03a6 v \u2217 R }}.\nProof.\n  rewrite [(WP _ @ _; _ {{ _ }} \u2217 _)%I]comm; setoid_rewrite (comm _ _ R).\n  apply wp_frame_step_l.\nQed.\nLemma wp_frame_step_l' s E e \u03a6 R :\n  to_val e = None \u2192 \u25b7 R \u2217 WP e @ s; E {{ \u03a6 }} \u22a2 WP e @ s; E {{ v, R \u2217 \u03a6 v }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_l s E E); try iFrame; eauto. Qed.\nLemma wp_frame_step_r' s E e \u03a6 R :\n  to_val e = None \u2192 WP e @ s; E {{ \u03a6 }} \u2217 \u25b7 R \u22a2 WP e @ s; E {{ v, \u03a6 v \u2217 R }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_r s E E); try iFrame; eauto. Qed.\n\nLemma wp_wand s E e \u03a6 \u03a8 :\n  WP e @ s; E {{ \u03a6 }} -\u2217 (\u2200 v, \u03a6 v -\u2217 \u03a8 v) -\u2217 WP e @ s; E {{ \u03a8 }}.\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 \u03a6 \u03a8 :\n  (\u2200 v, \u03a6 v -\u2217 \u03a8 v) \u2217 WP e @ s; E {{ \u03a6 }} \u22a2 WP e @ s; E {{ \u03a8 }}.\nProof. iIntros \"[H Hwp]\". iApply (wp_wand with \"Hwp H\"). Qed.\nLemma wp_wand_r s E e \u03a6 \u03a8 :\n  WP e @ s; E {{ \u03a6 }} \u2217 (\u2200 v, \u03a6 v -\u2217 \u03a8 v) \u22a2 WP e @ s; E {{ \u03a8 }}.\nProof. iIntros \"[Hwp H]\". iApply (wp_wand with \"Hwp H\"). Qed.\nEnd wp.\n\n(** Proofmode class instances *)\nSection proofmode_classes.\n  Context `{irisG \u039b \u03a3}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03a6 : val \u039b \u2192 iProp \u03a3.\n\n  Global Instance frame_wp p s E e R \u03a6 \u03a8 :\n    (\u2200 v, Frame p R (\u03a6 v) (\u03a8 v)) \u2192\n    Frame p R (WP e @ s; E {{ \u03a6 }}) (WP e @ s; E {{ \u03a8 }}).\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 \u03a6 : IsExcept0 (WP e @ s; E {{ \u03a6 }}).\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 \u03a6 :\n    ElimModal True p false (|==> P) P (WP e @ s; E {{ \u03a6 }}) (WP e @ s; E {{ \u03a6 }}).\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 \u03a6 :\n    ElimModal True p false (|={E}=> P) P (WP e @ s; E {{ \u03a6 }}) (WP e @ s; E {{ \u03a6 }}).\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 \u03a6 :\n    Atomic (stuckness_to_atomicity s) e \u2192\n    ElimModal True p false (|={E1,E2}=> P) P\n            (WP e @ s; E1 {{ \u03a6 }}) (WP e @ s; E2 {{ v, |={E2,E1}=> \u03a6 v }})%I.\n  Proof.\n    intros. by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r wp_atomic.\n  Qed.\n\n  Global Instance add_modal_fupd_wp s E e P \u03a6 :\n    AddModal (|={E}=> P) P (WP e @ s; E {{ \u03a6 }}).\n  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_wp. Qed.\n\n  Global Instance elim_acc_wp {X} E1 E2 \u03b1 \u03b2 \u03b3 e s \u03a6 :\n    Atomic (stuckness_to_atomicity s) e \u2192\n    ElimAcc (X:=X) (fupd E1 E2) (fupd E2 E1)\n            \u03b1 \u03b2 \u03b3 (WP e @ s; E1 {{ \u03a6 }})\n            (\u03bb x, WP e @ s; E2 {{ v, |={E2}=> \u03b2 x \u2217 (\u03b3 x -\u2217? \u03a6 v) }})%I.\n  Proof.\n    intros ?. rewrite /ElimAcc.\n    iIntros \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[H\u03b1 Hclose]\".\n    iApply (wp_wand with \"[Hinner H\u03b1]\"); first by iApply \"Hinner\".\n    iIntros (v) \">[H\u03b2 H\u03a6]\". iApply \"H\u03a6\". by iApply \"Hclose\".\n  Qed.\n\n  Global Instance elim_acc_wp_nonatomic {X} E \u03b1 \u03b2 \u03b3 e s \u03a6 :\n    ElimAcc (X:=X) (fupd E E) (fupd E E)\n            \u03b1 \u03b2 \u03b3 (WP e @ s; E {{ \u03a6 }})\n            (\u03bb x, WP e @ s; E {{ v, |={E}=> \u03b2 x \u2217 (\u03b3 x -\u2217? \u03a6 v) }})%I.\n  Proof.\n    rewrite /ElimAcc.\n    iIntros \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[H\u03b1 Hclose]\".\n    iApply wp_fupd.\n    iApply (wp_wand with \"[Hinner H\u03b1]\"); first by iApply \"Hinner\".\n    iIntros (v) \">[H\u03b2 H\u03a6]\". iApply \"H\u03a6\". by iApply \"Hclose\".\n  Qed.\nEnd proofmode_classes.\n", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/theories/program_logic/weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.18868221440107333}}
{"text": "Require Import Coq.Bool.Sumbool.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Crypto.Reflection.SmartMap.\nRequire Import Crypto.Reflection.Relations.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Named.Syntax.\nRequire Import Crypto.Reflection.Named.ContextDefinitions.\nRequire Import Crypto.Reflection.Named.ContextProperties.\nRequire Import Crypto.Reflection.Named.ContextProperties.SmartMap.\nRequire Import Crypto.Reflection.Named.Wf.\nRequire Import Crypto.Reflection.Named.MapCast.\nRequire Import Crypto.Util.PointedProp.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.Bool.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Sigma.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.DestructHead.\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          {FullContext : Context Name (fun t => { b : interp_base_type_bounds t & interp_base_type (pick_typeb t b) }%type)}\n          (FullContextOk : ContextOk FullContext)\n          {Context : Context Name interp_base_type}\n          (ContextOk : ContextOk Context)\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    | _ => progress unfold option_map in *\n    end.\n\n  Local Ltac handle_lookupb_step_extra := fail.\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 (fun C => lookupb_extend C base_type_dec Name_dec) in H by assumption\n               | setoid_rewrite (fun C => lookupb_extend C 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 (fun C => lookupb_extend C 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    | _ => progress handle_lookupb_step_extra\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, Some ?k = Some v ]\n      => exists k; 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 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 c, ?x = Some _ -> _ |- _ ]\n      => specialize (IH _ _ _ H)\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 x y z, lookupb ?ctx n = _ -> _, H' : lookupb ?ctx ?n' = _ |- _ ]\n      => specialize (H _ _ _ _ _ H')\n    | [ H : forall t n x y, lookupb ?ctx n = _ -> _, H' : lookupb ?ctx ?n' = _ |- _ ]\n      => specialize (H _ _ _ _ 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 subst\n          | progress destruct_head'_ex\n          | progress destruct_head'_and\n          | progress inversion_option\n          | progress inversion_prod\n          | progress inversion_sigma\n          | progress autorewrite with push_prop_of_option in *\n          | progress break_match_hyps ].\n\n  Local Ltac do_specialize_IHe_step :=\n    match goal with\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 w, Some _ = Some _ -> _ |- _ ]\n      => first [ specialize (H _ _ _ _ eq_refl)\n               | specialize (fun x y => H x y _ _ eq_refl) ]\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    | [ H : forall a b, prop_of_option (Named.wff a ?e) -> _, H' : prop_of_option (Named.wff _ ?e) |- _ ]\n      => specialize (fun b => H _ b H')\n    | [ H : forall b v, _ -> prop_of_option (Named.wff b ?e) |- prop_of_option (Named.wff ?ctx ?e) ]\n      => specialize (H ctx)\n    | [ H : forall b v, _ -> _ -> prop_of_option (Named.wff b ?e) |- prop_of_option (Named.wff ?ctx ?e) ]\n      => specialize (H ctx)\n    | [ H : forall a b, _ -> _ -> _ -> prop_of_option (Named.wff b ?e) |- prop_of_option (Named.wff ?ctx ?e) ]\n      => specialize (fun a => H a ctx)\n    | [ H : forall a b, prop_of_option (Named.wff a ?e) -> _, H' : forall v, prop_of_option (Named.wff _ ?e) |- _ ]\n      => specialize (fun b v => H _ b (H' v))\n    end.\n  Ltac do_specialize_IHe := repeat do_specialize_IHe_step.\n\n  Definition make_fContext_value {t} {b : interp_flat_type interp_base_type_bounds t}\n             (v : interp_flat_type interp_base_type (pick_type t b))\n    : interp_flat_type\n        (fun t => { b : interp_base_type_bounds t & interp_base_type (pick_typeb t b)})\n        t\n    := SmartFlatTypeMapUnInterp2\n         (fun t b (v : interp_flat_type _ (Tbase _))\n          => existT (fun b => interp_base_type (pick_typeb t b)) b v)\n         v.\n\n  Local Ltac t_step :=\n    first [ progress intros\n          | progress simpl in *\n          | break_t_step\n          | handle_lookupb_step\n          | handle_exists_in_goal\n          | apply conj\n          | solve [ auto | exfalso; auto ]\n          | specializer_t_step\n          | progress do_specialize_IHe\n          | match goal with\n            | [ IH : forall v, _ -> ?T, v' : interp_flat_type _ _ |- ?T ]\n              => apply (IH (make_fContext_value v')); clear IH\n            end ].\n  Local Ltac t := repeat t_step.\n\n  Lemma find_Name_and_val_make_fContext_value_Some {T}\n        {N : interp_flat_type (fun _ : base_type_code => Name) T}\n        {B : interp_flat_type interp_base_type_bounds T}\n        {V : interp_flat_type interp_base_type (pick_type T B)}\n        {n : Name}\n        {t : base_type_code}\n        {v : { b : interp_base_type_bounds t & interp_base_type (pick_typeb t b)}}\n        {b}\n        (Hn : find_Name Name_dec n N = Some t)\n        (Hf : find_Name_and_val base_type_dec Name_dec t n N (make_fContext_value V) None = Some v)\n        (Hb : find_Name_and_val base_type_dec Name_dec t n N B None = Some b)\n        (N' := SmartFlatTypeMapInterp2 (var'':=fun _ => Name) (f:=pick_typeb) (fun _ _ n => n) _ N)\n    : b = projT1 v /\\ find_Name_and_val base_type_dec Name_dec (pick_typeb t (projT1 v)) n N' V None = Some (projT2 v).\n  Proof.\n    eapply (find_Name_and_val_SmartFlatTypeMapUnInterp2_Some_Some base_type_dec Name_dec (h:=@projT1 _ _) (i:=@projT2 _ _) (f:=pick_typeb) (g:=fun _ => existT _));\n      auto.\n  Qed.\n\n  Local Ltac handle_lookupb_step_extra ::=\n        lazymatch goal with\n        | [ H : find_Name _ ?n ?N = Some ?t,\n                H' : find_Name_and_val _ _ ?t ?n ?N (@make_fContext_value ?T ?B ?v) None = Some ?v',\n                     H'' : find_Name_and_val _ _ ?t ?n ?N ?B None = Some _\n            |- _ ]\n          => pose proof (find_Name_and_val_make_fContext_value_Some H H' H''); clear H'\n        end.\n\n  Lemma wff_mapf_cast\n        {t} (e:exprf base_type_code op Name t)\n    : forall\n        (fValues:FullContext)\n        (newValues:Context)\n        (varBounds:BoundsContext)\n        {b} e' (He':mapf_cast varBounds e = Some (existT _ b e'))\n        (Hwf : prop_of_option (Named.wff fValues e))\n        (Hctx:forall {t} n v,\n            lookupb (t:=t) fValues n = Some v\n            -> lookupb (t:=t) varBounds n = Some (projT1 v)\n               /\\ lookupb (t:=pick_typeb t (projT1 v)) newValues n = Some (projT2 v)),\n      prop_of_option (Named.wff newValues e').\n  Proof. induction e; t. Qed.\n\n  Lemma wf_map_cast\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        (fValues:FullContext)\n        (newValues:Context)\n        (varBounds:BoundsContext)\n        {b} e' (He':map_cast varBounds e input_bounds = Some (existT _ b e'))\n        (Hwf : Named.wf fValues e)\n        (Hctx:forall {t} n v,\n            lookupb (t:=t) fValues n = Some v\n            -> lookupb (t:=t) varBounds n = Some (projT1 v)\n               /\\ lookupb (t:=pick_typeb t (projT1 v)) newValues n = Some (projT2 v)),\n      Named.wf newValues e'.\n  Proof.\n    unfold Named.wf, 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    match goal with v : _ |- _ => specialize (Hwf (make_fContext_value v)) end.\n    eapply wff_mapf_cast; eauto; [].\n    t.\n  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/MapCastWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.18857024863946326}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.NameOverlay.\n\nRequire Import TreeStatic.\nRequire Import NameAdjacency.\nRequire Import TreeAux.\nRequire Import StructTact.Fin.\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\nRequire Import ExtrOcamlString.\n\nRequire Import Verdi.ExtrOcamlBasicExt.\nRequire Import Verdi.ExtrOcamlNatIntExt.\n\nRequire Import Verdi.ExtrOcamlBool.\nRequire Import Verdi.ExtrOcamlList.\nRequire Import Verdi.ExtrOcamlFinInt.\n\nModule NumNames : NatValue. Definition n := 5. End NumNames.\nModule Names := FinName NumNames.\nModule NamesOT := FinNameOrderedType NumNames Names.\nModule NamesOTCompat := FinNameOrderedTypeCompat NumNames Names.\nModule RootNames := FinRootNameType NumNames Names.\nModule AdjacentNames := FinCompleteAdjacentNameType NumNames Names.\n\nRequire Import MSetList.\nModule NamesSet <: MSetInterface.S := MSetList.Make NamesOT.\n\nRequire Import FMapList.\nModule NamesMap <: FMapInterface.S := FMapList.Make NamesOTCompat.\n\nModule AdjacencyNames := FinAdjacency NumNames Names NamesOT NamesSet AdjacentNames.\n\nModule TAuxNames := NameTypeTAux Names NamesOT NamesSet NamesOTCompat NamesMap.\n\nModule TreeNames :=\n  Tree Names NamesOT NamesSet NamesOTCompat NamesMap RootNames AdjacentNames AdjacencyNames TAuxNames.\nImport TreeNames.\n\nExtraction \"extraction/tree/ocaml/Tree.ml\" seq Tree_BaseParams Tree_MultiParams.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/extraction/tree/coq/ExtractTreeStatic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18857024147945223}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import PromiseConsistent.\n\nRequire Import SimCommon.\n\nSet Implicit Arguments.\n\n\nModule PromotionProgress.\n  Import SimCommon.\n\n  Lemma progress_read_aux\n        l view released b ts\n        (RELEASED: View.le released view):\n    sim_view l view (View.join (View.join view (View.singleton_ur_if b l ts)) released).\n  Proof.\n    destruct b; ss.\n    - unfold View.singleton_ur, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n      econs; ss; ii.\n      + unfold TimeMap.join. condtac; ss.\n        apply TimeFacts.antisym.\n        * etrans; eauto using Time.join_l.\n        * inv RELEASED.\n          repeat eapply Time.join_spec; eauto using Time.bot_spec; try refl.\n      + unfold TimeMap.join. condtac; ss.\n        apply TimeFacts.antisym.\n        * etrans; eauto using Time.join_l.\n        * inv RELEASED.\n          repeat eapply Time.join_spec; eauto using Time.bot_spec; try refl.\n    - unfold View.singleton_rw, TimeMap.bot, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n      econs; ss; ii.\n      + unfold TimeMap.join.\n        apply TimeFacts.antisym.\n        * etrans; eauto using Time.join_l.\n        * inv RELEASED.\n          repeat eapply Time.join_spec; eauto using Time.bot_spec; try refl.\n      + unfold TimeMap.join. condtac; ss.\n        apply TimeFacts.antisym.\n        * etrans; eauto using Time.join_l.\n        * inv RELEASED.\n          repeat eapply Time.join_spec; eauto using Time.bot_spec; try refl.\n  Qed.\n\n  Lemma progress_read\n        l lc1 mem1 from val released ord\n        (WF1: Local.wf lc1 mem1)\n        (MEM1: Memory.closed mem1)\n        (LATEST: Memory.get l (Memory.max_ts l mem1) mem1 = Some (from, Message.concrete val released))\n        (SAFE: View.le (View.unwrap released) (TView.cur (Local.tview lc1))):\n    exists lc2,\n      <<STEP: Local.read_step lc1 mem1 l (Memory.max_ts l mem1) val released ord lc2>> /\\\n      <<LC: sim_local l lc1 lc2>>.\n  Proof.\n    esplits.\n    - econs; eauto; try refl.\n      econs; i; eapply Memory.max_ts_spec2; apply WF1.\n    - econs; try refl. econs; ss.\n      + eapply progress_read_aux.\n        condtac; ss. apply View.bot_spec.\n      + eapply progress_read_aux.\n        condtac; ss; eauto using View.bot_spec.\n        etrans; eauto. apply WF1.\n  Qed.\n\n  Lemma progress_write_aux l view ts:\n    sim_view l view (View.join view (View.singleton_ur l ts)).\n  Proof.\n    unfold View.singleton_ur, TimeMap.singleton, LocFun.init,\n    LocFun.add, LocFun.find, View.join, TimeMap.join.\n    econs; ss; ii.\n    - condtac; ss.\n      apply TimeFacts.antisym; try apply Time.join_l.\n      apply Time.join_spec; try refl.\n      apply Time.bot_spec.\n    - condtac; ss.\n      apply TimeFacts.antisym; try apply Time.join_l.\n      apply Time.join_spec; try refl.\n      apply Time.bot_spec.\n  Qed.\n\n  Lemma progress_write\n        l lc1 sc1 mem1 val releasedm ord\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: forall to, Memory.get l to (Local.promises lc1) = None)\n        (SAFE1: View.le (View.unwrap releasedm) (TView.cur (Local.tview lc1))):\n    exists released lc2 sc2 mem2,\n      <<STEP: Local.write_step lc1 sc1 mem1 l (Memory.max_ts l mem1) (Time.incr (Memory.max_ts l mem1))\n                               val releasedm released ord lc2 sc2 mem2 Memory.op_kind_add>> /\\\n      <<LC: sim_local l lc1 lc2>> /\\\n      <<SC: sc1 = sc2>> /\\\n      <<MEM: sim_memory l mem1 mem2>> /\\\n      <<PROMISES2: forall to, Memory.get l to (Local.promises lc2) = None>> /\\\n      <<SAFE2: View.le (View.unwrap released) (TView.cur (Local.tview lc2))>>.\n  Proof.\n    exploit (@progress_write_step lc1 sc1 mem1 l (Time.incr (Memory.max_ts l mem1)) val releasedm ord); eauto.\n    { apply Time.incr_spec. }\n    { ii. rewrite PROMISES1 in GET. ss. }\n    i. des.\n    destruct lc1, lc2. ss.\n    replace promises0 with promises in *; cycle 1.\n    { apply Memory.ext. i.\n      inv x0. inv WRITE. inv PROMISE. ss. inv LC2.\n      erewrite (@Memory.remove_o promises2); eauto. condtac; ss.\n      - des. subst.\n        exploit Memory.add_get0; try exact PROMISES. i. des. ss.\n      - erewrite (@Memory.add_o promises1); eauto. condtac; ss.\n    }\n    esplits; eauto.\n    - econs; try refl. ss.\n      inv x0. inv LC2. ss.\n      econs; ss; eauto using progress_write_aux; i.\n      unfold LocFun.add. condtac; ss.\n    - inv x0. ss.\n    - inv x0. inv WRITE. inv PROMISE. ss.\n      econs; i.\n      + erewrite Memory.add_o; eauto. condtac; ss.\n        * des. ss.\n        * esplits; eauto. refl.\n      + revert GET_TGT. erewrite Memory.add_o; eauto. condtac; ss; i.\n        * des. ss.\n        * esplits; eauto. refl.\n    - inv x0. inv LC2. ss.\n      unfold TView.write_released. condtac; ss; try apply View.bot_spec.\n      apply View.join_spec.\n      + etrans; eauto. apply View.join_l.\n      + unfold LocFun.add. condtac; ss.\n        condtac; ss; try refl.\n        apply View.join_spec; try apply View.join_r.\n        etrans; try eapply WF1. apply View.join_l.\n  Qed.\nEnd PromotionProgress.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/promotion/PromotionProgress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.18849689057519586}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Asm.\nRequire Import Integers.\nRequire Import Maps.\nRequire Import Errors.\nRequire Import Machregs.\n\nRequire Import ProofIrrelevance.\n\nRequire Import PeekLiveness.\nRequire Import SplitLib.\nRequire Import FindInstrLib.\nRequire Import StepLib.\nRequire Import SameBlockLib.\nRequire Import PeekTactics.\nRequire Import PregTactics.\nRequire Import AsmCallingConv. \nRequire Import Union.\nRequire Import StepIn.\nRequire Import PeekLivenessProof.\nRequire Import Use.\nRequire Import PeekLib. \nRequire Import StepEquiv. (* Where rewrite is defined *)\nRequire Import ProgPropDec. \nRequire Import ForwardJumps. \nRequire Import Zlen.\n\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\n\nRequire Import Peephole.\nRequire Import PeepholeLib.\nRequire Import PeepholeDec.\n\nRequire Import ValEq.\nRequire Import MemEq.\n\nSection PRESERVATION.\n\n\n  \nVariable rwr: rewrite.\n\nVariable prog: program.\nVariable tprog: program.\nHypothesis TRANSF: transf_program rwr prog = OK tprog.\nHypothesis CALLING_CONV : calling_conv_correct_bits prog.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nDefinition outside_range := PeepholeDec.outside_range rwr prog.\nDefinition in_transf := PeepholeDec.in_transf rwr prog.\nDefinition at_entry := PeepholeDec.at_entry rwr prog.\nDefinition match_states := PeepholeDec.match_states rwr prog.\nDefinition transf_index := PeepholeLib.transf_index rwr prog.\nDefinition transf_idx_end := PeepholeLib.transf_idx_end rwr prog.\n\n\nLemma match_states_match_live :\n  forall s1 s2,\n    match_states s1 s2 ->\n    outside_range s1 ->\n    match_live liveness_fun_f prog s1 s2.\nProof.\n  intros.\n  inv H.\n  * simpl. intros. split; auto.\n    break_and; auto.\n    split; break_and; auto.\n    split; auto.\n    split; auto.\n    intros. apply H5. unfold ge in *.\n    unify_PC. unify_psur. assumption.\n  * assert (at_entry (State_bits rs m md)).\n      econstructor; eauto.\n      apply at_entry_not_out in H.\n      apply H in H0. inv_false.\n  * assert (in_transf (State_bits rsl' m' md')).\n    econstructor. Focus 3. apply H4.\n    Focus 3. apply H5. eauto. eauto.\n    eauto. eauto.\n    app outside_not_in H0.\n    apply H0 in H. inv_false.\n  * simpl. intros. split; auto.\n    break_and; eauto.\n    split; break_and; auto.\n    split; auto.\n    split; auto.\n    intros. \n    apply H4. unfold ge in *. unify_PC. unify_psur.\n    replace (Int.intval) with (Int.unsigned) in * by auto.\n    rewrite Int.unsigned_zero in *. unfold ge in *.\n    assumption.\nQed.\n\n\nLemma function_blocks_same :\n  forall b,\n    Genv.find_funct_ptr (Genv.globalenv prog) b = None ->\n    Genv.find_funct_ptr (Genv.globalenv tprog) b = None.\nProof.\n  intros.\n  unfold transf_program in *.\n  repeat break_match_hyp; try congruence.\n  inversion TRANSF.\n  destruct (Genv.find_funct_ptr\n              (Genv.globalenv (transform_program (transf_fundef rwr) prog)) b) eqn:?; try reflexivity.\n\n  app Genv.find_funct_ptr_rev_transf Heqo0.\n  break_and. congruence.\nQed.\n\nLemma is_global_translated :\n  forall b ofs,\n    is_global (Genv.globalenv prog) b ofs <->\n    is_global (Genv.globalenv tprog) b ofs.\nProof.\n  intros. split; intros.\n  - unfold is_global in *.\n    break_or.\n    * left. unfold in_code_range in *.\n      break_match_hyp; try inv_false.\n      app functions_translated Heqo.\n      collapse_match.\n      break_match_hyp. simpl.\n      destruct f0. simpl.\n      unfold Zlen.zlen. rewrite length_pres.\n      unfold Zlen.zlen in *.\n      simpl in *. omega.\n      simpl. omega.\n    * right.\n      unfold in_var_range in *.\n      break_match_hyp; try inv_false.\n      erewrite varinfo_preserved; eauto.\n      collapse_match. omega.\n  - unfold is_global in *.\n    break_or.\n    * left.\n      unfold in_code_range in *.\n      break_match. app functions_translated Heqo.\n      rewrite Heqo in H0.\n      \n      unfold transf_fundef in *.\n      destruct f; simpl in *.\n      destruct f; simpl in *.\n      unfold zlen in *.\n      rewrite length_pres in H0.\n      assumption.\n      assumption.\n      \n      app function_blocks_same Heqo.\n      rewrite Heqo in *. inv_false.\n    * right.\n      unfold in_var_range in *.\n      erewrite <- varinfo_preserved; eauto.\nQed.\n\nLemma global_perms_translated :\n  forall m,\n    global_perms (Genv.globalenv prog) m ->\n    global_perms (Genv.globalenv tprog) m.\nProof.\n  intros. unfold global_perms in *.\n  intros. eapply H.\n  rewrite is_global_translated. eauto.\nQed.\n\n(* MOVE THESE TO MEMORY AXIOMS *)\nAxiom md_ec'_ge :\n  forall md ge1 ge2 ef vargs m t vl m',\n    external_call' ef ge1 vargs m t vl m' ->\n    external_call' ef ge2 vargs m t vl m' ->\n    md_ec' md ef ge1 vargs m t vl m' = md_ec' md ef ge2 vargs m t vl m'.\n\nAxiom md_ec_ge :\n  forall md ge1 ge2 ef vargs m t vl m',\n    external_call ef ge1 vargs m t vl m' ->\n    external_call ef ge2 vargs m t vl m' ->\n    md_ec md ef ge1 vargs m t vl m' = md_ec md ef ge2 vargs m t vl m'.\n\n\nLemma step_outside :\n  forall st t st',\n    step_bits (Genv.globalenv prog) st t st' ->\n    outside_range st ->\n    step_bits (Genv.globalenv tprog) st t st'.\nProof.\n  intros. inv_step H.\n  * subst st. subst st'.\n    app functions_translated H5.\n    destruct f. simpl in *.\n    app instrs_translated H6.\n    econstructor; eauto.\n    destruct i; simpl in H7; simpl;\n    try assumption;\n    repeat break_match_hyp;\n    try (erewrite symbol_address_pres; eauto);\n    simpl; eauto;\n    try find_rewrite; simpl; eauto;\n    try eapply exec_load_bits_pres; eauto;\n    try eapply exec_store_bits_pres; eauto;\n    try eapply exec_big_load_bits_pres; eauto;\n    try eapply exec_big_store_bits_pres; eauto;\n    try erewrite eval_addrmode_no_ptr_pres; eauto;\n    try eapply goto_label_pres; eauto;\n    try find_rewrite; eauto; unfold is_label_instr in *; eauto.\n    erewrite <- eval_addrmode_bits_pres in Heqo; eauto.\n    rewrite Heqo. eauto. \n    erewrite <- eval_addrmode_bits_pres in Heqo; eauto.\n    rewrite Heqo. eauto.\n    \n    app list_nth_z_in Heqo.\n    find_rewrite. eauto.\n\n    eapply global_perms_translated; eauto.\n    \n  * subst st. subst st'.\n    app functions_translated H3.\n    destruct f; simpl in *.\n    app instrs_translated H4.\n\n    erewrite md_ec'_ge.\n    eapply exec_step_builtin_bits; eauto.\n    inv H5.\n    eapply external_call_symbols_preserved_gen in H14.\n    econstructor; eauto.\n    intros. unfold Senv.find_symbol.\n    simpl. eapply symbols_preserved; eauto.\n    intros. unfold Senv.public_symbol. simpl.\n    eapply public_symbols_preserved; eauto.\n    intros. unfold Senv.block_is_volatile. simpl.\n    unfold Genv.block_is_volatile.\n    erewrite varinfo_preserved. unfold ge.\n    reflexivity. eauto.\n    eapply global_perms_translated; eauto.\n    assumption.\n    eapply external_call_symbols_preserved'; eauto.\n    intros. erewrite symbols_preserved; eauto.\n    intros. erewrite public_symbols_preserved; eauto.\n    intros. erewrite varinfo_preserved; eauto.\n    \n  * subst st. subst st'. \n    app functions_translated H5.\n    destruct f; simpl in *.    \n    app instrs_translated H6.\n    app eval_annot_args_bits_pres H7.\n    name H8 Horig_call.\n    eapply external_call_symbols_preserved_gen in H8; try (intros; apply symbols_preserved).\n    instantiate (1 := (Genv.globalenv tprog)) in H8.\n    erewrite md_ec_ge; try instantiate (1 := (Genv.globalenv tprog)); eauto.\n    eapply exec_step_annot_bits; eauto.\n    eapply global_perms_translated; eauto.\n    intros. unfold Senv.public_symbol. simpl.\n    intros. eapply symbols_preserved; eauto.\n    eapply public_symbols_preserved; eauto.\n    intros. unfold Senv.block_is_volatile. simpl.\n    unfold Genv.block_is_volatile.\n    erewrite varinfo_preserved.\n    reflexivity.\n    exact TRANSF.\n    \n  * subst st. subst st'. \n    app functions_translated H3.\n    unfold transf_fundef in H3.\n    name H5 Horig_call.\n    \n    eapply external_call_symbols_preserved' in H5; try (intros; apply symbols_preserved).\n    erewrite md_ec'_ge;\n      try instantiate (1 := Genv.globalenv tprog);\n      try instantiate (1 := Genv.globalenv tprog) in H5;\n      eauto.\n    \n    eapply exec_step_external_bits; eauto.\n    eapply global_perms_translated; eauto.\n    intros. unfold Senv.public_symbol. simpl.\n    intros. eapply symbols_preserved; eauto.\n    eapply public_symbols_preserved; eauto.\n    intros. erewrite varinfo_preserved.\n    reflexivity. exact TRANSF.\nQed.\n\nLemma measure_decr_entry_in :\n  forall s s' t,\n    at_entry s ->\n    in_transf s' ->\n    step_bits (Genv.globalenv prog) s t s' ->\n    (measure rwr (transf_idx_end s') s' < measure rwr (transf_idx_end s) s)%nat.\nProof.\n  name (measure_decr rwr) mdr.\n\n  intros.\n  app transf_step_same_block H1.\n  destruct s. destruct s'.\n  inv H. inv H0. inv H1.\n  inv H. inv H0.\n  repeat unify_PC.\n  repeat unify_psur.\n  assert (at_entry (State_bits rsl m1 md)).\n  econstructor; eauto.\n  app transf_step_same_block H11.\n  inv H11.\n  inv H1. inv H6.\n  \n  NP _app star_step_in_same_block star. subst b1.\n\n  repeat unify_PC. repeat unify_psur.\n  eapply transf_range_unique in H10; try eapply H8; eauto.\n  break_and. subst j.\n  assert (in_transf (State_bits rs' m' md')).\n  econstructor; eauto.\n  rewrite H5. eauto.\n\n  name (conj H1 H12) Hstin.\n  rewrite <- st_in_eq in Hstin.\n  app star_step_in_in' Hstin.\n\n  unfold transf_idx_end. unfold PeepholeLib.transf_idx_end.\n  repeat collapse_match.\n  inv Hstin. inv H13.\n  repeat unify_PC. repeat unify_psur.\n  unfold fundef in *.\n  inv H8. repeat break_and.\n  unfold fundef in *.\n  repeat collapse_match.\n  \n  unfold transf_code in H15.\n  rewrite H8 in H15.\n  app split_pat_spec H8.\n  break_match_hyp.\n  eapply mdr; eauto.\n  split. eapply has_no_PC_overflow; eauto.\n  unfold transf_program in *.\n  repeat break_match_hyp; inversion TRANSF; eauto.\n  app is_proper_check_sound Heqb0.\n  break_and.\n  unfold is_proper_rewrite_location in *.\n  repeat break_and.\n  unfold not_after_label. intros.\n  econstructor; eauto;\n  inv H46;\n  inv H41;\n  repeat unify_PC;\n  repeat unify_psur;\n  repeat unify_find_funct_ptr;\n  simpl in H30;\n  eapply list_eq_middle_therefore_eq in H13; eauto;\n  eapply list_eq_middle_therefore_eq in H30; eauto;\n  repeat break_and;\n  subst;\n  eauto;\n  eapply list_eq_middle_therefore_eq in H30; congruence.\n  \n  exists 0.\n  econstructor; eauto.\n  omega.\n\n  name (find_nonempty rwr) fn.\n  destruct (find rwr); try congruence.\n  rewrite zlen_cons. name (zlen_nonneg _ c4) zlnc. omega.\n\n\n  exists ofs.\n  econstructor; eauto.\n  omega.\n\n\n  rewrite H8 in H15.\n  eapply list_neq in H15. inv_false.\n  apply (not_same rwr).\n\nQed.\n\nLemma in_transf_in_code :\n  forall st i j,\n    in_transf st ->\n    transf_index st i j ->\n    in_code i (find rwr) ge st.\nProof.\n  intros. inv H.\n  unfold transf_index in H0.\n  unfold PeepholeLib.transf_index in *.\n  specialize (H0 _ _ _ eq_refl).\n  name (conj H6 H5) Hstin.\n  rewrite <- st_in_eq in Hstin.\n  app star_step_in_in' Hstin.\n  inv Hstin. inv H8.\n  assert (at_entry (State_bits rsl m md)) by (econstructor; eauto).\n  app transf_step_same_block H4.\n  inv H4.\n  inv H11. inv H12.\n  repeat unify_PC.\n  repeat unify_psur.\n  app star_step_in_same_block H6.\n  subst.\n  \n  specialize (H0 _ _ _ H13 H14).\n  eapply transf_range_unique in H0; try apply H3.\n  break_and. subst.\n  rewrite <- H9.\n  econstructor.\n  Focus 2.\n  econstructor; eauto.\n  omega.\nQed.\n\n\nLemma measure_decr_rewr :\n  forall s1 s1' t i,\n    in_transf s1' ->\n    transf_index s1' i (i + zlen (find rwr)) ->\n    in_transf s1 ->\n    transf_index s1 i (i + zlen (find rwr)) ->\n    step_bits (Genv.globalenv prog) s1 t s1' ->\n    ((measure rwr (i + zlen (find rwr))) s1' < (measure rwr (i + zlen (find rwr))) s1)%nat.\nProof.\n  intros.\n  eapply (measure_decr rwr); eauto.\n  Focus 2. app in_transf_in_code H1.\n  inv H1. eauto.\n  Focus 2. app in_transf_in_code H.\n  inv H. eauto.\n  \n  split.\n  unfold transf_program in TRANSF.\n  repeat break_match_hyp; inversion TRANSF.\n  auto.\n\n  unfold not_after_label.\n  intros. subst.\n\n  unfold transf_index in H2.\n  unfold PeepholeLib.transf_index in H2.\n  \n  specialize (H2 _ _ _ eq_refl _ _ _ H5 H6).\n  inv H2.\n  unify_find_funct_ptr.\n  break_and.\n  unfold transf_code in H4.\n  rewrite H2 in H4.\n  app split_pat_spec H2.\n  eapply list_eq_middle_therefore_eq in H2; try omega.\n  break_and. subst.\n  \n  break_match_hyp.\n  Focus 2. eapply list_neq in H4. inv_false.\n  apply (not_same rwr).\n  \n  app is_proper_check_sound Heqb0.\n  break_and.\n\n  unfold is_proper_rewrite_location in H12.\n  repeat break_and; eauto.\nQed.\n\nLemma in_transf_step_match :\n  forall sl sl' sr,\n    match_states sl sr ->\n    in_transf sl ->\n    in_transf sl' ->\n    step_bits (Genv.globalenv prog) sl E0 sl' ->\n    match_states sl' sr.\nProof.\n\n  intros.\n  name H Hmatch.\n  inv H.\n  * app outside_not_in H6.\n    app H6 H0. inv_false.\n  * assert (at_entry (State_bits rs m md)).\n      econstructor; eauto.\n    app at_entry_not_in H.\n    app H H0. inv_false.\n  * destruct sl'.\n\n    \n    \n    assert (step_in (Int.unsigned i) (find rwr) (Genv.globalenv prog) (State_bits rsl' m' md') E0 (State_bits r m a)).\n    {\n      econstructor; eauto.\n      name (conj H9 H8) Hstin.\n      rewrite <- st_in_eq in Hstin.\n      app star_step_in_in' Hstin.\n\n      app transf_step_same_block H2.\n      assert (Hentry : at_entry (State_bits rsl ml md)) by (econstructor; eauto).\n      app transf_step_same_block H7.\n\n      inv H8. inv H2.\n      repeat match goal with\n               | [ H : State_bits _ _ _ = State_bits _ _ _ |- _ ] => inv H\n             end;\n        repeat unify_PC;\n        repeat unify_psur.\n      inv H1.\n      assert (Hentry2 : at_entry (State_bits rsl m md)) by (econstructor; eauto).\n      name (conj H26 H25) Hstin.\n      rewrite <- st_in_eq in Hstin.\n      app star_step_in_in' Hstin.\n      app transf_step_same_block H24.\n      inv H18.\n      inv H24. inv H8. inv H18.\n      inv H15.\n      repeat match goal with\n               | [ H : State _ _ = State _ _ |- _ ] => inv H\n             end;\n        repeat unify_PC;\n        repeat unify_psur.\n      \n      app star_step_in_same_block H26.\n      subst b0.\n\n      app star_step_in_same_block H9. subst b2.\n\n      inv H7. inv H9. inv H21.\n        repeat unify_PC;\n        repeat unify_psur.\n\n        eapply transf_range_unique in H23; try apply H6.\n        break_and. congruence.\n\n        right. econstructor; eauto.\n      \n    }\n    \n    eapply inside; try eapply star_right;\n    try apply H9; try apply H2; try apply H7; eauto.\n\n  * inv H0.\n    app transf_step_same_block H14.\n    inv H14.\n    find_inversion. find_inversion.\n    repeat unify_PC. repeat unify_psur.\n    app star_step_in_same_block H16.\n    subst b1. inv H13.\n    \n    unify_find_funct_ptr.\n\n    right. econstructor; eauto.\nQed.\n\nLemma zlen_same :\n  zlen (find rwr) = zlen (repl rwr).\nProof.\n  unfold zlen. rewrite (len_same rwr).\n  reflexivity.\nQed.\n\nLemma at_entry_match :\n  forall rs m md rs' m' md',\n    at_entry (State_bits rs m md) ->\n    match_states (State_bits rs m md) (State_bits rs' m' md') ->\n    (forall reg, In reg (live_in rwr) ->\n                 val_eq (rs reg) (rs' reg)) /\\ mem_eq md m m'.\nProof.\n  intros.\n  inv H0.\n  * app at_entry_not_out H.\n    app H H10. inv_false.\n  * split; eauto.\n    intros.\n    apply H11.\n    inv H10. break_and.\n    unfold transf_code in H4.\n    assert (c1 ++ find rwr ++ c2 <> c1 ++ repl rwr ++ c2).\n    apply list_neq. apply (not_same rwr).\n    repeat break_match_hyp; try congruence.\n    inv H2.\n    unfold is_proper_location_check in Heqb0.\n    repeat break_match_hyp; try congruence.\n    Focus 2.\n    inv H2. app split_pat_spec Heqo.\n    congruence.\n    repeat break_and.\n    unfold liveness_check_correct in l0.\n    repeat break_and.\n    app i2 H0.\n    unfold liveness_fun_f.\n    repeat unify_find_funct_ptr.\n    rewrite p1.\n    app split_pat_spec Heqo.\n    rewrite Heqo. rewrite Heqo0.\n    rewrite H3. eauto.\n  * assert (in_transf (State_bits rs m md)).\n    econstructor; try apply H11; eauto.\n    app at_entry_not_in H.\n    app H H0. inv_false.\n  * inv H. unify_PC.\n    unify_psur.\n    inv H5. unify_find_funct_ptr.\nQed.\n\nLemma transf_did_happen :\n  forall b f x y,\n    Genv.find_funct_ptr ge b = Some (Internal f) ->\n    transf_range rwr prog b x y ->\n    transf_code rwr (fn_code f) <> fn_code f.\nProof.\n  intros. inv H0.\n  unfold ge in *. unfold fundef in *.\n  unify_find_funct_ptr.\n  simpl. break_and.\n  rewrite H1.\n  app split_pat_spec H0.\n  rewrite H0.\n  apply list_neq.\n  name (not_same rwr) ns. congruence.\nQed.\n\nLemma entry_or_in_range :\n  forall rs m md bits b i x y,\n    (at_entry (State_bits rs m md) \\/ in_transf (State_bits rs m md)) ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    transf_range rwr prog b x y ->\n    x <= Int.unsigned i < y.\nProof.\n  intros. break_or.\n  inv H3.\n  unify_PC. unify_psur.\n  eapply transf_range_unique in H2; try eapply H8.\n  break_and. subst.\n  inv H8. rewrite H2.\n  rewrite zlen_app.\n  name (zlen_find rwr) zlnf. omega.\n  inv H3.\n  assert (at_entry (State_bits rsl m0 md0)) by (econstructor; eauto).\n  app transf_step_same_block H9.\n  inv H9. inv H4. inv H5. \n  repeat unify_PC.\n  repeat unify_psur.\n  app star_step_in_same_block H11. subst b1.\n  name (conj H4 H10) Hstin.\n  rewrite <- st_in_eq in Hstin.\n  app star_step_in_in' Hstin.\n  inv Hstin. inv H9.\n  repeat unify_PC.\n  repeat unify_psur.\n  eapply transf_range_unique in H8; try eapply H2.\n  break_and. subst.\n  inv H2. repeat unify_PC. repeat unify_psur.\n  unfold ge in *.\n  repeat unify_find_funct_ptr.\n  rewrite zlen_app. name (zlen_find rwr) zlnf.\n  \n  omega.\nQed.\n\n(* TODO: Move somewhere higher up *)\nLemma at_code_in_range :\n  forall z c ofs prog rs m md bits b i,\n    no_PC_overflow_prog prog ->\n    at_code z c ofs (Genv.globalenv prog) (State_bits rs m md) ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    in_code_range (Genv.globalenv prog) b i.\nProof.\n  intros. inv H0. unfold in_code_range.\n  unfold fundef in *.\n  unify_PC. unify_psur.\n  collapse_match.\n  find_rewrite.\n  repeat rewrite zlen_app.\n  name (zlen_nonneg _ c) zlnc.\n  name (zlen_nonneg _ c1) zlnc1.\n  name (zlen_nonneg _ c2) zlnc2.\n\n  unfold no_PC_overflow_prog in H.\n  assert (code_of_prog (fn_code fd) prog0).\n  unfold code_of_prog. NP _app Genv.find_funct_ptr_inversion Genv.find_funct_ptr.\n  destruct fd. eauto.\n  NP1 _app H code_of_prog.\n  unfold no_PC_overflow in *.\n  \n\n  assert (zlen c1 + ofs >= 0 /\\ zlen c1 + ofs < zlen (fn_code fd)). {\n    split; try omega. rewrite H15. repeat rewrite zlen_app. omega. }\n                                                                    app in_range_find_instr H3.\n  \n  app H0 H3; omega.\nQed.    \n\n\nLemma straightlineish_single_exit :\n  forall rs m md rs' m' md' instr,\n    step_t (instr :: nil) ge (State_bits rs m md) E0 (State_bits rs' m' md') ->\n    forall z ofs,\n      at_code z (find rwr) ofs ge (State_bits rs m md) ->\n      rs' PC = (nextinstr rs) PC ->\n      (in_transf (State_bits rs m md) \\/ at_entry (State_bits rs m md)) ->\n      outside_range (State_bits rs' m' md') ->\n      forall bits b i,\n        rs PC = Values.Vint bits ->\n        psur md bits = Some (b,i) ->\n        transf_range rwr prog b z (z + zlen (find rwr)) ->\n        exists bits' i',\n          rs' PC = Values.Vint bits' /\\\n          psur md' bits' = Some (b,i') /\\\n          Int.unsigned i' = z + zlen (find rwr).\nProof.\n  intros.\n  assert (z <= Int.unsigned i < z + zlen (find rwr)).\n  {\n    eapply entry_or_in_range; eauto. break_or; eauto.\n  }\n  preg_simpl_hyp H1. rewrite H4 in H1.\n  simpl in H1.\n\n  NP _app step_t_md_extends step_t.\n  NP _app step_t_md step_t; try congruence.\n  NP _app step_t_gp step_t; try congruence.\n  repeat break_and.\n  app psur_add_one H5.\n\n  eexists; eexists; split; eauto; split; eauto.\n\n  name H6 Htransf_range. inv H6.\n  assert (Hrange : Int.unsigned i >= 0 /\\ Int.unsigned i < zlen (c1 ++ find rwr ++ c2)).\n  repeat rewrite zlen_app. name (zlen_find rwr) zlnf.\n  name (zlen_nonneg _ c2) zlnc. name (zlen_nonneg _ c1) zlnc1. omega.\n  rewrite in_range_find_instr in Hrange.\n  break_exists.\n  unfold Int.add.\n  rewrite Int.unsigned_one.\n  \n  erewrite unsigned_repr_PC; eauto.\n  Focus 2. unfold transf_program in *. repeat break_match_hyp; inversion TRANSF; eauto.\n  Focus 2. left. replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n  simpl. repeat break_and.\n  NP _app split_pat_spec split_pat. subst c. eauto.\n\n  \n  inv H3.\n  break_exists. break_and.\n  repeat unify_PC.\n  repeat unify_psur.\n  simpl in *. unfold ge in *. unfold fundef in *.\n  repeat unify_find_funct_ptr.\n  destruct H17.\n  Focus 2. app transf_did_happen Htransf_range.\n  simpl in Htransf_range. congruence.\n\n  repeat break_exists.\n  break_and. \n  eapply transf_range_unique in H15; try eapply Htransf_range.\n  break_and. subst.\n  \n  unfold Int.add in H17. rewrite Int.unsigned_one in H17.\n  erewrite unsigned_repr_PC in H17; eauto.\n\n  omega.\n\n  eapply has_no_PC_overflow; eauto.\n\n  left. replace (Int.unsigned i + 1 - 1) with (Int.unsigned i) by omega.\n  simpl. break_and.\n  NP _app split_pat_spec split_pat. subst c. eauto.\n  \n\n  eapply at_code_in_range; eauto.\n  eapply has_no_PC_overflow; eauto.\n  app step_t_to_at_code_0 H10.\n  inv H10.\n  repeat unify_PC. repeat unify_psur.\n  eapply in_range_PC; eauto.\n  eapply has_no_PC_overflow; eauto.\n  rewrite H21. rewrite H28.\n  rewrite find_instr_append_head by omega.\n  simpl. reflexivity.\nQed.\n\n\n\nLemma jump_to_label_contra :\n  forall rs m rs' m' instr md md',\n    step_t (instr :: nil) ge (State_bits rs m md) E0 (State_bits rs' m' md') ->\n    forall z ofs bits b i fd,\n      at_code z (find rwr) ofs ge (State_bits rs m md) ->\n      rs PC = Values.Vint bits ->\n      psur md bits = Some (b,i) ->\n      transf_range rwr prog b z (z + zlen (find rwr)) ->\n      Genv.find_funct_ptr ge b = Some (Internal fd) ->\n      (exists jmp l, goto_label_bits md fd l b rs m = Nxt rs' m' md' /\\\n      find_instr (Int.unsigned i) (fn_code fd) = Some jmp /\\\n      is_label_instr jmp l) ->\n      (in_transf (State_bits rs m md) \\/ at_entry (State_bits rs m md)) ->\n      outside_range (State_bits rs' m' md') ->\n      False.\nProof.\n  intros.\n  repeat break_exists.\n  repeat break_and.\n  unfold goto_label_bits in *.\n  repeat break_match_hyp; try state_inv.\n\n  assert (HnoPC : no_PC_overflow_prog prog) by (\n  eapply has_no_PC_overflow; eauto).\n  \n  assert (psur md' i0 = Some (b,Int.repr z0)). {\n  NP _app step_t_md step_t; try congruence.\n  NP _app step_t_gp step_t; try congruence.\n  repeat break_and.\n  erewrite weak_valid_pointer_sur; eauto.\n  split; eauto.\n  NP1 _app global_perms_valid_globals global_perms.\n  unfold valid_globals in *.\n  eapply Memory.Mem.weak_valid_pointer_spec. right.\n  NP _app label_pos_find_instr label_pos.\n  erewrite unsigned_repr_PC; eauto.\n  erewrite <- (unsigned_repr_PC _ _ (z0-1)); eauto.\n  eapply H11.\n  NP _app label_pos_find_instr label_pos.\n  unfold is_global. left.\n  unfold in_code_range. collapse_match.\n  apex in_range_find_instr Heqo.\n  erewrite unsigned_repr_PC; eauto.\n  omega. \n  }\n\n\n  \n  assert (z <= Int.unsigned i < z + zlen (find rwr)).\n  {\n    inv H1.\n    eapply entry_or_in_range; eauto; break_or; eauto.\n  }\n\n  name H3 Htransf.\n  inv H3. repeat break_and.\n  name H13 Htc.\n  unfold transf_code in H13.\n  rewrite H12 in H13. break_match_hyp.\n  Focus 2. app transf_did_happen Htransf. simpl in Htransf. congruence.\n  app is_proper_check_sound Heqb0.\n  repeat break_and. unfold is_proper_rewrite_location in *.\n  repeat break_and.\n  unfold ge in *. unfold fundef in *.\n  repeat unify_find_funct_ptr.\n  simpl in *.\n  app split_pat_spec H12. subst c.\n\n  assert (z0 < zlen c1 \\/ z0 >= zlen (c1 ++ find rwr)).\n  {\n    inv H7. preg_simpl_hyp H30. inv H30.\n    break_exists. break_and.\n    inv H1.\n    repeat unify_PC. repeat unify_psur.\n    unfold ge in *. unfold fundef in *.\n    repeat unify_find_funct_ptr.\n\n    destruct H12. Focus 2. app transf_did_happen Htransf.\n    simpl in Htransf. congruence.\n    repeat break_exists.\n    repeat break_and.\n    eapply transf_range_unique in H1; try apply Htransf.\n    break_and. subst.\n    assert (Int.unsigned (Int.repr z0) = z0).\n    erewrite unsigned_repr_PC; eauto.\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF; eauto.\n    app label_pos_find_instr Heqo.\n    rewrite H1 in *. omega.\n  }\n  destruct H12.\n  eapply no_labels_jump_out_contra_c1; eauto; try omega.\n  eapply no_labels_jump_out_contra_c2; eauto; try omega.\n\nQed.\n\nLemma straightline_step_t_nextinstr :\n  forall i ge rs m md t rs' m' md',\n    straightline i ->\n    step_t (i :: nil) ge (State_bits rs m md) t (State_bits rs' m' md') ->\n    rs' PC = nextinstr rs PC.\nProof.\n  intros.\n  copy H0. inv H1.\n  inv H10. inv H4.\n  app straightline_step_t H0.\n  break_instr_exec i;\n    preg_simpl;\n    try reflexivity;\n    try inv_false;\n    repeat break_match;\n    preg_simpl;\n    try congruence.\n  simpl in Heqo.\n  inv Heqo.\nQed.\n        \n\nLemma single_exit :\n  forall rs m rs' m' bits b i x y md md',\n    (in_transf (State_bits rs m md) \\/ at_entry (State_bits rs m md)) ->\n    outside_range (State_bits rs' m' md') ->\n    step_bits (Genv.globalenv prog) (State_bits rs m md) E0 (State_bits rs' m' md') ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    transf_range rwr prog b x y ->\n    exists bits' i',\n      rs' PC = Values.Vint bits' /\\\n      psur md' bits' = Some (b,i') /\\\n      Int.unsigned i' = y.\nProof.\n  intros.\n  assert (exists ofs, at_code x (find rwr) ofs ge (State_bits rs m md)).\n  {\n    break_or. eapply in_transf_in_code in H5.\n    Focus 2. unfold transf_index. unfold PeepholeLib.transf_index.\n    intros. inv H.\n    repeat unify_PC. repeat unify_psur. apply H4.\n    inv H5. eexists; apply H6.\n    inv H5. repeat unify_PC.\n    repeat unify_psur.\n    eapply transf_range_unique in H4; try eapply H10.\n    break_and. subst.\n    inv H10. exists 0.\n    rewrite H4. econstructor; eauto. omega.\n    name (zlen_find rwr) zln. omega.\n    simpl. break_and. app split_pat_spec H3.\n  }\n\n  assert (y = x + zlen (find rwr)).\n  {\n    inv H4.\n    rewrite zlen_app.\n    reflexivity.\n  }\n  subst y.\n  break_exists.\n  app step_at_step_t H5.\n  break_and.\n  rewrite find_instr_in in H7.\n  break_exists.\n  name (instr_class x1) ic.\n  name (forward_find rwr) ff.\n  unfold only_forward_jumps in ff.\n  repeat break_and.\n  unfold no_calls in *.\n  unfold no_trace_code in *.\n  destruct ic;\n    try destruct H11;\n    try destruct H11;\n    app H9 H7;\n    try app H8 H;\n    try app H8 H12;\n    try congruence;\n    try solve [app no_trace_trace H7; try inv_false].\n\n\n  \n  NP _app straightlineish_single_exit outside_range; eauto.\n  inv H4.\n  NP _app straightline_step_t step_t.\n  NP _app straightline_step_t_nextinstr step_t.\n\n  name H6 Hat. inv H6.\n  app step_t_labeled_jump H5.\n  break_or.\n\n  app jump_to_label_contra H14. inv_false.\n  repeat unify_PC. repeat unify_psur. apply H4.\n\n  app straightlineish_single_exit H6; inv H14.\n  reflexivity.\n  repeat unify_PC.\n  eauto.\nQed.\n\nLemma star_step_md_extends :\n  forall ge s1 s2 t,\n    star step_bits ge s1 t s2 ->\n    forall rs m md rs' m' md',\n    s1 = State_bits rs m md ->\n    s2 = State_bits rs' m' md' ->\n    md_extends md md'.\nProof.\n  induction 1; intros.\n  subst. inv H0. econstructor; eauto.\n  subst. destruct s2.\n  app md_extends_step H.\n  eapply ex_trans; eauto.\nQed.\n\nLemma step_through_transf_same_block :\n  forall rs m bits b i x y rs' m' b' i' bits' md md',\n    at_entry (State_bits rs m md) ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    transf_range rwr prog b x y ->\n    step_through x (find rwr) ge (State_bits rs m md) E0 (State_bits rs' m' md') ->\n    rs' PC = Values.Vint bits' ->\n    psur md' bits' = Some (b',i') ->\n    b = b'.\nProof.\n  intros.\n  inv H3.\n  app transf_step_same_block H7. inv H7.\n  repeat match goal with\n           | [ H : State_bits _ _ _ = State_bits _ _ _ |- _ ] => inv H\n         end.\n  repeat unify_PC. repeat unify_psur.\n  reflexivity.\n  assert (t1 = E0).\n  {\n    destruct t1; simpl in H6. reflexivity.\n    inv H6.\n  }\n  subst t1. simpl in H6.\n  assert (t2 = E0).\n  {\n    destruct t2; simpl in H6. reflexivity.\n    inv H6.\n  }\n  subst t2. simpl in H6.\n  assert (t3 = E0).\n  {\n    destruct t3; simpl in H6. reflexivity.\n    inv H6.\n  }\n  subst t3.  \n  destruct (stB). destruct stC.\n  name H2 Htransf. inv H2.\n  inv H7. break_and.\n  repeat unify_PC. repeat unify_psur. simpl. \n  assert (in_transf (State_bits r0 m1 a0)).\n  {\n    econstructor; eauto.\n    rewrite H18. rewrite H2.\n    replace (zlen c1 + 0) with (zlen c1) by omega.\n    apply Htransf.\n    name H10 Hstin.\n    rewrite st_in_eq in H10. break_and.\n    rewrite H18. rewrite H2.\n    replace (zlen c1 + 0) with (zlen c1) by omega.\n    eauto. \n    rewrite H18. rewrite H2.\n    replace (zlen c1 + 0) with (zlen c1) by omega.\n    rewrite st_in_eq in H10. break_and.\n    eauto.\n  }\n  app transf_step_same_block H15.\n  inv H15.\n  repeat match goal with\n           | [ H : State_bits _ _ _ = State_bits _ _ _ |- _ ] => inv H\n         end.\n  repeat unify_PC.\n  repeat unify_psur.\n  app transf_step_same_block H9.\n  inv H9.\n  repeat match goal with\n           | [ H : State_bits _ _ _ = State_bits _ _ _ |- _ ] => inv H\n         end.\n  repeat unify_PC.\n  repeat unify_psur.\n  rewrite st_in_eq in H10.\n  break_and.\n  repeat unify_PC. repeat unify_psur.\n  symmetry.\n\n  eapply star_step_in_same_block; eauto.\n  \nQed.\n\n\n\nLemma match_entry_match_live :\n  forall rs m rs' m' bits b i md md',\n    at_entry (State_bits rs m md) ->\n    match_states (State_bits rs m md) (State_bits rs' m' md') ->\n    rs PC = Values.Vint bits ->\n    psur md bits = Some (b,i) ->\n    (forall r, In r (liveness_fun_f ge b (Int.unsigned i)) ->\n               val_eq (rs r) (rs' r) /\\ mem_eq md m m').\nProof.\n  intros rs m rs' m' bits b i md md' Hat Hmatch HPC Hpsur.\n  inv Hmatch; repeat unify_PC; repeat unify_psur; eauto.\n  assert (in_transf (State_bits rs m md)).\n  econstructor; try apply H9; try apply H7; eauto.\n  \n  app at_entry_not_in Hat. app Hat H. inv_false.\nQed.\n\n\nLemma match_exit :\n  forall z rsl ml rsr mr ml' mr' rsl' rsr' b ofs bits mdl mdr mdl' mdr',\n    match_states (State_bits rsl ml mdl) (State_bits rsr mr mdr)->\n    rsl PC = Values.Vint bits ->\n    psur mdl bits = Some (b,ofs) ->\n    Int.unsigned ofs = z + 0 ->\n    step_through z (find rwr) (Genv.globalenv prog) (State_bits rsl ml mdl) E0 (State_bits rsl' ml' mdl') ->\n    step_through z (repl rwr) (Genv.globalenv tprog) (State_bits rsr mr mdr) E0 (State_bits rsr' mr' mdr') ->\n    ((forall r, In r (live_out rwr) -> val_eq (rsl' r) (rsr' r)) /\\ mem_eq mdl' ml' mr' /\\ mdl = mdr) ->\n    genv_equiv_code z (Genv.globalenv prog) (Genv.globalenv tprog) b (find rwr) (repl rwr) ->\n    transf_range rwr prog b z (z + zlen (find rwr)) ->\n    match_states (State_bits rsl' ml' mdl') (State_bits rsr' mr' mdr').\nProof.\n  intros.\n  assert (HPC : In PC (live_out rwr)) by (apply (PC_live_out rwr)).\n  (* need a state right prior to rs m, in order to use single exit *)\n  assert (exists rsi mi mdi, (at_entry (State_bits rsi mi mdi) \\/ in_transf (State_bits rsi mi mdi)) /\\\n                         step_bits ge (State_bits rsi mi mdi) E0 (State_bits rsl' ml' mdl')).\n  {\n\n    inv H3. exists rsl. exists ml. exists mdl.\n    split; auto. left. econstructor; eauto.\n    rewrite H2. instantiate (1 := z + zlen (find rwr)).\n    inv H7; econstructor; eauto. omega. \n    destruct stC. exists r. exists m. exists a.\n    rewrite H8.\n    destruct t1; simpl in H8; try solve [inv H8].\n    destruct t2; simpl in H8; try solve [inv H8].\n    destruct t3; simpl in H8; try solve [inv H8].\n    simpl in H8. rewrite H8 in *.\n    unfold ge. unfold fundef in *.\n    split; auto.\n    destruct stB.    \n    right. econstructor; eauto.\n    rewrite H2. instantiate (1 := z + zlen (find rwr)).\n    inv H7; econstructor; eauto. omega.\n    rewrite st_in_eq in H12. break_and.\n    rewrite H2. replace (z + 0) with z by omega.\n    assumption.\n    rewrite st_in_eq in H12. break_and.\n    rewrite H2. replace (z + 0) with z by omega.\n    simpl.\n    assumption.\n  }\n  break_exists. break_exists. break_and.\n\n  app step_through_at_end H3.\n  inv H3.\n  destruct fd.\n\n  repeat break_and. subst.\n\n  \n  assert (mdl' = mdr'). {\n    app (steps_pres_find rwr) H10. break_and.\n    app (steps_pres_repl rwr) H4. break_and.\n    congruence.\n    eapply no_PC_ovf_tprog; eauto.\n    inv H13; eauto.\n    unfold transf_program in TRANSF;\n    repeat break_match_hyp;\n    inversion TRANSF; eauto.\n    inv H10; eauto.\n  } idtac.\n  subst.\n\n  assert (at_entry (State_bits rsl ml mdr)). {\n    econstructor. eauto.\n    eauto. rewrite H2. replace (zlen c0 + 0) with (zlen c0) by omega.\n    eassumption.\n  } idtac.\n  \n  app step_through_transf_same_block H10. subst.\n\n  (* Construct the match_states relation here *)\n  eapply outside; eauto.\n\n  \n  * name (H5 PC HPC) Hrsr'PC.\n    rewrite H14 in Hrsr'PC. simpl in Hrsr'PC. congruence.\n\n  * econstructor; eauto.\n    eexists. split. \n    eassumption. simpl.\n    simpl. left. eexists; eexists.\n    split; eauto. omega.\n\n  * \n\n  name H7 Htransf.\n  inv H7. break_and.\n  name H13 Htc.\n  unfold transf_code in H13.\n\n  rewrite H7 in H13.\n  break_match_hyp.\n  Focus 2.\n  app transf_did_happen Htransf. simpl in Htransf.\n  rewrite H13 in Htransf. congruence.\n  NP _app is_proper_check_sound is_proper_location_check.\n  unfold is_proper_rewrite_location in *.\n  repeat break_and.\n  unfold liveness_check_correct in *.\n  repeat break_and. \n\n  intro.\n  unfold liveness_fun_f.\n  repeat collapse_match.\n  NP _app split_pat_spec split_pat.\n  subst c.\n  collapse_match.\n  rewrite H19.\n  rewrite H16.\n  intros.\n  \n  assert (In r (live_out rwr ++ pres rwr)).\n  {\n\n    apply H34.\n    rewrite zlen_app.\n    assumption.\n  }\n  \n  rewrite in_app in *. break_or.\n  apply H5. auto.\n  rewrite <- zlen_app in H7.\n  rewrite <- H35 in H7 by auto.\n\n  name (steps_pres_find rwr) spf.\n  name (steps_pres_repl rwr) spr.\n\n  unfold step_through_preserve in *.\n  app step_through_at H4.\n  app step_through_at H12.\n  assert (Hnpc : no_PC_overflow_prog prog).\n  {\n    unfold transf_program in TRANSF;\n    repeat break_match_hyp;\n    inversion TRANSF; eauto.\n  }\n  assert (Hnpc' : no_PC_overflow_prog tprog).\n  {\n    eapply no_PC_ovf_tprog; eauto.\n  }\n  \n  name (spf _ _ _ _ _ _ _ _ _ Hnpc H12 H39) spf''.\n  name (spr _ _ _ _ _ _ _ _ _ Hnpc' H4 H37) spr''.\n  repeat break_and. clear H43. clear H41.\n  rename H42 into spf'.\n  rename H40 into spr'.\n  rewrite <- spf' by eauto.\n  rewrite <- spr' by eauto.\n\n  assert (Hlve : forall r0 : preg,\n            In r0 (liveness_fun_f (Genv.globalenv prog) b0 (Int.unsigned ofs)) ->\n            val_eq (rsl r0) (rsr r0)).\n  {\n    eapply match_entry_match_live; eauto.\n  }\n  apply Hlve. unfold liveness_fun_f.\n  repeat collapse_match.\n  match goal with\n    | [ H : Int.unsigned ofs = _ |- _ ] => rewrite H\n  end.\n  replace (zlen c0 + 0) with (zlen c0) by omega.\n  congruence.\n\n  * \n  \n  assert (no_ptr_regs rsr /\\ no_ptr_mem mr).\n  {\n    inv H;break_and; split; auto;\n    eapply no_ptr_mem_eq; eauto.\n  }\n  \n  eapply no_ptr_preserved_step_through; eauto.\n\nQed.\n\nLemma step_through_match :\n  forall z st st' str,\n    at_entry st ->\n    step_through z (find rwr) (Genv.globalenv prog) st E0 st' ->\n    match_states st str ->\n    exists str',\n      plus step_bits (Genv.globalenv tprog) str E0 str' /\\\n      match_states st' str'.\nProof.\n  intros.\n  name (steps_equiv_live rwr) selr.\n  destruct st'.  \n  unfold step_through_equiv_live in selr.\n  assert (at_code z (find rwr) 0 (Genv.globalenv prog) st).\n  {\n    inv H0; eauto.\n  }\n\n  name H2 Hat_code.\n  inv H2.\n  assert (genv_equiv_code (zlen c0) (Genv.globalenv prog) (Genv.globalenv tprog) b (find rwr) (repl rwr)).\n  {\n    econstructor; eauto;\n    repeat unify_find_funct_ptr;\n    simpl in *.\n\n    erewrite functions_translated in H9; eauto.\n    subst c.\n    inversion H9. inversion H. inversion H16.\n    subst.\n    unify_PC. unify_psur. break_and.\n        app split_pat_spec H2. simpl in H9.\n        unify_find_funct_ptr.\n    rewrite H13. rewrite H4.\n    replace (zlen c0) with (zlen c2) by omega.\n    rewrite nat_zlen.\n    eapply pat_at_n_sane.\n    inv H. inv H14.\n    unify_PC. unify_psur.\n    erewrite functions_translated in H9; eauto.\n    repeat unify_find_funct_ptr.\n    inv H15. inv H9.\n    break_and.\n\n    NP _app split_pat_spec split_pat. subst.\n    unify_find_funct_ptr.\n    eapply list_eq_middle_therefore_eq in H13; try omega.\n    break_and. subst.\n    rewrite H9.\n                                        \n    rewrite nat_zlen.\n    repeat rewrite firstn_len.\n    reflexivity.\n  }\n\n\n  assert (exists (s : signature) (c : code), Genv.find_funct_ptr (Genv.globalenv tprog) b = Some (Internal {| fn_sig := s; fn_code := c |})).\n  {\n    destruct fd.   \n    eexists. eexists. erewrite functions_translated; eauto.\n    simpl. reflexivity.\n  }\n\n  assert (no_PC_overflow_prog prog).\n  {\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF; eauto.\n  }\n\n  \n  name H0 Hst_thru_left.\n  destruct str.\n  app at_entry_match H1.\n  break_and. \n\n  assert (t = a0). {\n    simpl.\n    inv H11; auto.\n    assert (in_transf (State_bits rs m0 t)).\n    econstructor; try apply H23; eauto.\n    app at_entry_not_in H.\n    app H H11. inv_false.\n  } subst.\n\n  eapply selr with (rsr := r0) in H0;\n    try solve [eapply no_PC_ovf_tprog; eauto];\n    eauto.\n\n  Focus 2.\n  (* clear -TRANSF H. *)\n  P inv at_entry.\n  P inv PeepholeLib.transf_range.\n  break_and.\n  unfold transf_code in *.\n  NP1 app_new split_pat_spec (Some (c2, c3)).\n  subst.\n  assert (c2 ++ find rwr ++ c3 <> c2 ++ repl rwr ++ c3).\n  eapply list_neq.  \n  eapply (not_same rwr).  \n  repeat (break_match_hyp; try congruence); [].\n  NP app_new is_proper_check_sound is_proper_location_check.\n  break_and.\n  unfold is_proper_rewrite_location in *.\n  repeat break_and.\n  apply mk_not_after_label_in_code.\n  unfold not_after_label.\n  intros.\n  repeat match goal with\n           | [ H : State_bits _ _ _ = State_bits _ _ _ |- _ ] => inv H\n           | [ H : Some _ = Some _ |- _ ] => inv H\n         end.\n  unify_stuff.\n  inv Hat_code.\n  unify_stuff.\n  P1 _simpl fn_code.\n  assert (zlen c0 = zlen c2) by omega.\n  assert (zlen c5 = zlen c2) by omega.\n  eapply list_eq_middle_therefore_eq in H4.\n  repeat break_and.  \n  subst c5.\n  subst c6.\n  split.\n  assumption.\n  auto.\n  auto.  \n  \n  repeat break_exists. repeat break_and.\n  \n  exists (State_bits x1 x2 a).\n\n  split.\n  \n  eapply step_through_plus_step; eauto.\n\n  eapply match_exit; eauto.\n  destruct fd.\n  inv H. repeat unify_PC.\n  repeat unify_psur.\n\n  \n  rewrite H5 in H21.\n  inv H21.\n\n  inv H. repeat unify_PC. repeat unify_psur.\n  econstructor; eauto. \n  omega. rewrite zlen_app. omega.  \n  inv H11; eauto.  \n  intros.\n  exploit symbol_address_pres; eauto.\n\n  assert (global_perms (Genv.globalenv prog) m0).\n  inv H0.\n  app step_gp H14.\n  tauto.\n  destruct stB.\n  app step_gp H16.  \n  tauto.\n  apply global_perms_translated.\n  eapply global_perms_mem_eq; eauto.  \nQed. \n\n\nLemma step_out :\n  forall sl sl' sr t,\n    match_states sl sr ->\n    step_bits (Genv.globalenv prog) sl t sl' ->\n    in_transf sl ->\n    outside_range sl' ->\n    exists sr',\n      plus step_bits (Genv.globalenv tprog) sr E0 sr' /\\ match_states sl' sr'.\nProof.\n  intros.\n  (* Here we appeal to the correctness of symbolic evaluation *)\n  (* what does that look like? *)\n  inv H.\n  * (* contradiction *)\n    eapply outside_not_in in H6; eauto.\n    app H6 H1. inv_false.\n  \n  * (* contradiction *)\n    \n    assert (at_entry (State_bits rs m md)).\n      econstructor; eauto.\n\n      eapply at_entry_not_in in H; eauto.\n      app H H1. inv_false.\n\n  * (* interesting case *)\n    \n    name (steps_equiv_live rwr) selr.\n    name (steps_pres_find rwr) spf.\n    name (steps_pres_repl rwr) spr.\n\n    assert (t = E0).\n      eapply no_trace_step; eauto.\n    subst.\n\n    destruct sl'.\n\n\n    assert (Hat_entry : at_entry (State_bits rsl ml md)) by (econstructor; eauto).\n    \n    assert (Hat_code: at_code (Int.unsigned i) (find rwr) 0 (Genv.globalenv prog) (State_bits rsl ml md)).\n    {\n      inv H6. rewrite H14. break_and.\n      econstructor; eauto. omega.\n      name (zlen_find rwr) zlnf.\n      omega. simpl.\n      app split_pat_spec H6.\n    }\n\n    assert (Hat_end: at_code_end (Int.unsigned i) (find rwr) (Genv.globalenv prog) (State_bits r m a)).\n    {\n      app transf_step_same_block H0.\n      inv H0. find_inversion. find_inversion.\n      app transf_step_same_block H7.\n      inv H7.\n      find_inversion. find_inversion.\n      repeat unify_PC. repeat unify_psur.\n      app star_step_in_same_block H9. subst b0.\n      name H6 Htransf_range.\n      inv H6. \n      rewrite H13.\n      econstructor; eauto.\n      rewrite <- H13.\n\n      app single_exit H;\n        repeat break_and.\n\n      repeat unify_PC.\n      repeat unify_psur.\n      rewrite zlen_app in H21. omega.\n\n      repeat break_and.\n      app split_pat_spec H6.\n    }\n\n    \n    assert (Hst_thru: step_through (Int.unsigned i) (find rwr) (Genv.globalenv prog) (State_bits rsl ml md) E0 (State_bits r m a)).\n    {\n      replace E0 with (E0 ** E0 ** E0) by (simpl; auto).\n      eapply st_thru_mult_step; eauto.\n      rewrite st_in_eq. split. eauto.\n      eauto.\n    }\n\n    app step_through_match Hst_thru; eauto.\n    eapply entry; eauto.\n\n  * (* contradiction *)\n    simpl.\n    inv H1.\n    app transf_step_same_block H14.\n    inv H14. find_inversion. find_inversion.\n    repeat unify_PC. repeat unify_psur.\n    app star_step_in_same_block H16.\n    subst b1.\n    inv H13. unify_find_funct_ptr.\n    right. econstructor; eauto.\nQed.\n\n\nLemma match_not_in :\n  forall sl sl' sr sr' t,\n    outside_range sl ->\n    match_states sl sr ->\n    step_bits (Genv.globalenv prog) sl t sl' ->\n    step_bits (Genv.globalenv prog) sr t sr' ->\n    outside_range sl' ->\n    match_live liveness_fun_f prog sl' sr' ->\n    match_states sl' sr'.\nProof.\n  intros. name H Hout_start. name H3 Hout_end.\n  inv H0.\n  * unfold match_live in H4. destruct sl'. destruct sr'. \n    inv H3.\n    specialize (H4 _ _ _ H15 H14).\n    repeat break_and.\n    subst a.\n    eapply outside; eauto.\n    \n    exploit (H13 PC).\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF. \n    eapply PC_always_live; eauto. destruct u. eassumption.\n    intros.\n    rewrite H14 in H12.\n    simpl in H12. congruence.\n  * assert (at_entry (State_bits rs m md)).\n      econstructor; eauto.\n    app at_entry_not_out H0.\n    app H0 H. inv_false.\n  * assert (in_transf (State_bits rsl' m' md')) by (\n      econstructor; try apply H5; eauto).\n    app inside_not_out H0.\n    app H0 H. inv_false.\n  * unfold match_live in H4. destruct sl'. destruct sr'. \n    inv H3. \n    specialize (H4 _ _ _ H14 H13).\n    repeat break_and.\n    subst a.\n    eapply outside; eauto.\n    exploit (H12 PC).\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF. \n    eapply PC_always_live; eauto.\n    destruct u. eassumption.\n    intros. rewrite H13 in H11. simpl in H11. congruence.\nQed.\n\nLemma match_at_entry :\n  forall sl sl' sr sr' t,\n    outside_range sl ->\n    match_states sl sr ->\n    step_bits (Genv.globalenv prog) sl t sl' ->\n    step_bits (Genv.globalenv prog) sr t sr' ->\n    at_entry sl' ->\n    match_live liveness_fun_f prog sl' sr' ->\n    match_states sl' sr'.\nProof.\n  intros. name H Houtside. name H3 Hat_entry.\n  inv H0.\n  * unfold match_live in H4. destruct sl'. destruct sr'. \n    inv H3. \n    specialize (H4 _ _ _ H15 H14).\n    repeat break_and. \n    name H16 Htransf_range. inv H16.\n    eapply entry; eauto. \n    exploit (H13 PC).\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF. \n    eapply PC_always_live; eauto. destruct u.\n    eassumption.\n    intros. rewrite H14 in H12. simpl in H12. congruence.\n  * assert (at_entry (State_bits rs m md)) by (\n      econstructor; eauto).\n    app at_entry_not_out H0.\n    app H0 H. inv_false.\n  * assert (in_transf (State_bits rsl' m' md')) by (\n      econstructor; try apply H11; try apply H9; eauto).\n    app outside_not_in Houtside.\n    app Houtside H0. inv_false.\n  * unfold match_live in H4. destruct sl'. destruct sr'. \n    inv H3. \n    specialize (H4 _ _ _ H14 H13).\n    repeat break_and. \n    \n    name H15 Htransf_range. inv H15.\n    eapply entry; eauto.\n    exploit (H12 PC).\n    unfold transf_program in TRANSF.\n    repeat break_match_hyp; inversion TRANSF. \n    eapply PC_always_live; eauto.\n    destruct u. eassumption.\n    intros. rewrite H13 in H11. simpl in H11. congruence.\nQed.\n\nLemma step_out_at_entry :\n  forall sl sl' sr t,\n    match_states sl sr ->\n    step_bits (Genv.globalenv prog) sl t sl' ->\n    at_entry sl ->\n    outside_range sl' ->\n    exists sr',\n      plus step_bits (Genv.globalenv tprog) sr E0 sr' /\\ match_states sl' sr'.\nProof.\n  intros.\n  app at_entry_at_code H1.\n  app no_trace_entry_step H0. subst t.  \n  eapply step_through_match; eauto.\n  econstructor; eauto.\n\n  inv H1. destruct sl'.\n  name H3 Hat_entry.\n  inv H3. repeat unify_PC. repeat unify_psur.\n  app single_exit H0.\n  repeat break_and.\n  econstructor; eauto.\n  inv H14. \n  rewrite zlen_app in H16.\n  omega.\nQed.\n\nLemma entry_step_in :\n  forall s1 s2 s1',\n    match_states s1 s2 ->\n    at_entry s1 ->\n    step_bits (Genv.globalenv prog) s1 E0 s1' ->\n    in_transf s1' ->\n    match_states s1' s2.\nProof.\n  intros.\n  inv H.\n  * app at_entry_not_out H0.\n    app H0 H6. inv_false.\n  * app transf_step_same_block H1.\n    inv H1. find_inversion.\n    repeat unify_PC.\n    repeat unify_psur.\n    eapply inside; try apply star_refl; eauto.\n\n    inv H2.\n    assert (at_entry (State_bits rsl m md)) by (econstructor; eauto).\n    app transf_step_same_block H17.\n    inv H17. find_inversion. find_inversion.\n    repeat unify_PC. repeat unify_psur.\n\n    app star_step_in_same_block H19. subst b0.\n\n    eapply transf_range_unique in H6; try apply H16.\n    break_and. rewrite H6.\n\n    name (conj H3 H18) Hstin.\n    rewrite <- st_in_eq in Hstin.\n    app star_step_in_in' Hstin.\n    \n  * assert (in_transf (State_bits rsl' m' md')) by (\n    econstructor; try apply H7; eauto).\n    app at_entry_not_in H0.\n    app H0 H. inv_false.\n  * inv H0. unify_PC. unify_psur.\n    inv H13. unify_find_funct_ptr.\nQed.\n\nEnd PRESERVATION.\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/PeepholeMatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.1884846601983331}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nImport Clightdefs.ClightNotations.\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\nLocal Open Scope clight_scope.\n\nModule Info.\n  Definition version := \"3.9\".\n  Definition build_number := \"\".\n  Definition build_tag := \"\".\n  Definition build_branch := \"\".\n  Definition arch := \"x86\".\n  Definition model := \"32sse2\".\n  Definition abi := \"standard\".\n  Definition bitsize := 32.\n  Definition big_endian := false.\n  Definition source_file := \"tweetnacl20140427/tweetnaclVerifiableC.c\".\n  Definition normalized := true.\nEnd Info.\n\nDefinition _A : ident := 101%positive.\nDefinition _Ch : ident := 118%positive.\nDefinition _D : ident := 43%positive.\nDefinition _D2 : ident := 44%positive.\nDefinition _I : ident := 47%positive.\nDefinition _K : ident := 124%positive.\nDefinition _L : ident := 139%positive.\nDefinition _L32 : ident := 50%positive.\nDefinition _M : ident := 103%positive.\nDefinition _Maj : ident := 119%positive.\nDefinition _R : ident := 117%positive.\nDefinition _S : ident := 104%positive.\nDefinition _Sigma0 : ident := 120%positive.\nDefinition _Sigma1 : ident := 121%positive.\nDefinition _X : ident := 45%positive.\nDefinition _Y : ident := 46%positive.\nDefinition _Z : ident := 102%positive.\nDefinition __0 : ident := 38%positive.\nDefinition __121665 : ident := 42%positive.\nDefinition __9 : ident := 39%positive.\nDefinition ___builtin_annot : ident := 17%positive.\nDefinition ___builtin_annot_intval : ident := 18%positive.\nDefinition ___builtin_bswap : ident := 2%positive.\nDefinition ___builtin_bswap16 : ident := 4%positive.\nDefinition ___builtin_bswap32 : ident := 3%positive.\nDefinition ___builtin_bswap64 : ident := 1%positive.\nDefinition ___builtin_clz : ident := 5%positive.\nDefinition ___builtin_clzl : ident := 6%positive.\nDefinition ___builtin_clzll : ident := 7%positive.\nDefinition ___builtin_ctz : ident := 8%positive.\nDefinition ___builtin_ctzl : ident := 9%positive.\nDefinition ___builtin_ctzll : ident := 10%positive.\nDefinition ___builtin_debug : ident := 36%positive.\nDefinition ___builtin_expect : ident := 25%positive.\nDefinition ___builtin_fabs : ident := 11%positive.\nDefinition ___builtin_fabsf : ident := 12%positive.\nDefinition ___builtin_fmadd : ident := 28%positive.\nDefinition ___builtin_fmax : ident := 26%positive.\nDefinition ___builtin_fmin : ident := 27%positive.\nDefinition ___builtin_fmsub : ident := 29%positive.\nDefinition ___builtin_fnmadd : ident := 30%positive.\nDefinition ___builtin_fnmsub : ident := 31%positive.\nDefinition ___builtin_fsqrt : ident := 13%positive.\nDefinition ___builtin_membar : ident := 19%positive.\nDefinition ___builtin_memcpy_aligned : ident := 15%positive.\nDefinition ___builtin_read16_reversed : ident := 32%positive.\nDefinition ___builtin_read32_reversed : ident := 33%positive.\nDefinition ___builtin_sel : ident := 16%positive.\nDefinition ___builtin_sqrt : ident := 14%positive.\nDefinition ___builtin_unreachable : ident := 24%positive.\nDefinition ___builtin_va_arg : ident := 21%positive.\nDefinition ___builtin_va_copy : ident := 22%positive.\nDefinition ___builtin_va_end : ident := 23%positive.\nDefinition ___builtin_va_start : ident := 20%positive.\nDefinition ___builtin_write16_reversed : ident := 34%positive.\nDefinition ___builtin_write32_reversed : ident := 35%positive.\nDefinition ___compcert_i64_dtos : ident := 159%positive.\nDefinition ___compcert_i64_dtou : ident := 160%positive.\nDefinition ___compcert_i64_sar : ident := 171%positive.\nDefinition ___compcert_i64_sdiv : ident := 165%positive.\nDefinition ___compcert_i64_shl : ident := 169%positive.\nDefinition ___compcert_i64_shr : ident := 170%positive.\nDefinition ___compcert_i64_smod : ident := 167%positive.\nDefinition ___compcert_i64_smulh : ident := 172%positive.\nDefinition ___compcert_i64_stod : ident := 161%positive.\nDefinition ___compcert_i64_stof : ident := 163%positive.\nDefinition ___compcert_i64_udiv : ident := 166%positive.\nDefinition ___compcert_i64_umod : ident := 168%positive.\nDefinition ___compcert_i64_umulh : ident := 173%positive.\nDefinition ___compcert_i64_utod : ident := 162%positive.\nDefinition ___compcert_i64_utof : ident := 164%positive.\nDefinition ___compcert_va_composite : ident := 158%positive.\nDefinition ___compcert_va_float64 : ident := 157%positive.\nDefinition ___compcert_va_int32 : ident := 155%positive.\nDefinition ___compcert_va_int64 : ident := 156%positive.\nDefinition _a : ident := 90%positive.\nDefinition _add : ident := 128%positive.\nDefinition _add1305 : ident := 82%positive.\nDefinition _b : ident := 75%positive.\nDefinition _c : ident := 49%positive.\nDefinition _car25519 : ident := 93%positive.\nDefinition _carry : ident := 140%positive.\nDefinition _chk : ident := 146%positive.\nDefinition _core : ident := 71%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet : ident := 115%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet_afternm : ident := 113%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet_beforenm : ident := 112%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet_keypair : ident := 111%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet_open : ident := 116%positive.\nDefinition _crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm : ident := 114%positive.\nDefinition _crypto_core_hsalsa20_tweet : ident := 73%positive.\nDefinition _crypto_core_salsa20_tweet : ident := 72%positive.\nDefinition _crypto_hash_sha512_tweet : ident := 127%positive.\nDefinition _crypto_hashblocks_sha512_tweet : ident := 125%positive.\nDefinition _crypto_onetimeauth_poly1305_tweet : ident := 86%positive.\nDefinition _crypto_onetimeauth_poly1305_tweet_verify : ident := 87%positive.\nDefinition _crypto_scalarmult_curve25519_tweet : ident := 109%positive.\nDefinition _crypto_scalarmult_curve25519_tweet_base : ident := 110%positive.\nDefinition _crypto_secretbox_xsalsa20poly1305_tweet : ident := 88%positive.\nDefinition _crypto_secretbox_xsalsa20poly1305_tweet_open : ident := 89%positive.\nDefinition _crypto_sign_ed25519_tweet : ident := 145%positive.\nDefinition _crypto_sign_ed25519_tweet_keypair : ident := 138%positive.\nDefinition _crypto_sign_ed25519_tweet_open : ident := 154%positive.\nDefinition _crypto_stream_salsa20_tweet : ident := 78%positive.\nDefinition _crypto_stream_salsa20_tweet_xor : ident := 77%positive.\nDefinition _crypto_stream_xsalsa20_tweet : ident := 80%positive.\nDefinition _crypto_stream_xsalsa20_tweet_xor : ident := 81%positive.\nDefinition _crypto_verify_16_tweet : ident := 61%positive.\nDefinition _crypto_verify_32_tweet : ident := 62%positive.\nDefinition _cswap : ident := 129%positive.\nDefinition _d : ident := 59%positive.\nDefinition _den : ident := 148%positive.\nDefinition _den2 : ident := 149%positive.\nDefinition _den4 : ident := 150%positive.\nDefinition _den6 : ident := 151%positive.\nDefinition _dl64 : ident := 54%positive.\nDefinition _e : ident := 107%positive.\nDefinition _f : ident := 108%positive.\nDefinition _g : ident := 85%positive.\nDefinition _gf0 : ident := 40%positive.\nDefinition _gf1 : ident := 41%positive.\nDefinition _h : ident := 66%positive.\nDefinition _i : ident := 53%positive.\nDefinition _in : ident := 64%positive.\nDefinition _inv25519 : ident := 105%positive.\nDefinition _iv : ident := 126%positive.\nDefinition _j : ident := 69%positive.\nDefinition _k : ident := 65%positive.\nDefinition _ld32 : ident := 52%positive.\nDefinition _m : ident := 70%positive.\nDefinition _main : ident := 174%positive.\nDefinition _minusp : ident := 83%positive.\nDefinition _mlen : ident := 153%positive.\nDefinition _modL : ident := 141%positive.\nDefinition _n : ident := 58%positive.\nDefinition _neq25519 : ident := 98%positive.\nDefinition _num : ident := 147%positive.\nDefinition _o : ident := 92%positive.\nDefinition _out : ident := 63%positive.\nDefinition _p : ident := 94%positive.\nDefinition _pack : ident := 133%positive.\nDefinition _pack25519 : ident := 97%positive.\nDefinition _par25519 : ident := 99%positive.\nDefinition _pk : ident := 136%positive.\nDefinition _pow2523 : ident := 106%positive.\nDefinition _q : ident := 95%positive.\nDefinition _r : ident := 84%positive.\nDefinition _randombytes : ident := 37%positive.\nDefinition _reduce : ident := 142%positive.\nDefinition _s : ident := 79%positive.\nDefinition _scalarbase : ident := 135%positive.\nDefinition _scalarmult : ident := 134%positive.\nDefinition _sel25519 : ident := 96%positive.\nDefinition _set25519 : ident := 91%positive.\nDefinition _sigma : ident := 74%positive.\nDefinition _sigma0 : ident := 122%positive.\nDefinition _sigma1 : ident := 123%positive.\nDefinition _sk : ident := 137%positive.\nDefinition _sm : ident := 143%positive.\nDefinition _smlen : ident := 144%positive.\nDefinition _st32 : ident := 55%positive.\nDefinition _t : ident := 68%positive.\nDefinition _ts64 : ident := 56%positive.\nDefinition _tx : ident := 130%positive.\nDefinition _ty : ident := 131%positive.\nDefinition _u : ident := 51%positive.\nDefinition _unpack25519 : ident := 100%positive.\nDefinition _unpackneg : ident := 152%positive.\nDefinition _vn : ident := 60%positive.\nDefinition _w : ident := 67%positive.\nDefinition _x : ident := 48%positive.\nDefinition _y : ident := 57%positive.\nDefinition _z : ident := 76%positive.\nDefinition _zi : ident := 132%positive.\nDefinition _t'1 : ident := 175%positive.\nDefinition _t'10 : ident := 184%positive.\nDefinition _t'11 : ident := 185%positive.\nDefinition _t'12 : ident := 186%positive.\nDefinition _t'13 : ident := 187%positive.\nDefinition _t'14 : ident := 188%positive.\nDefinition _t'15 : ident := 189%positive.\nDefinition _t'16 : ident := 190%positive.\nDefinition _t'17 : ident := 191%positive.\nDefinition _t'18 : ident := 192%positive.\nDefinition _t'19 : ident := 193%positive.\nDefinition _t'2 : ident := 176%positive.\nDefinition _t'20 : ident := 194%positive.\nDefinition _t'21 : ident := 195%positive.\nDefinition _t'22 : ident := 196%positive.\nDefinition _t'23 : ident := 197%positive.\nDefinition _t'24 : ident := 198%positive.\nDefinition _t'25 : ident := 199%positive.\nDefinition _t'26 : ident := 200%positive.\nDefinition _t'27 : ident := 201%positive.\nDefinition _t'28 : ident := 202%positive.\nDefinition _t'29 : ident := 203%positive.\nDefinition _t'3 : ident := 177%positive.\nDefinition _t'30 : ident := 204%positive.\nDefinition _t'31 : ident := 205%positive.\nDefinition _t'32 : ident := 206%positive.\nDefinition _t'33 : ident := 207%positive.\nDefinition _t'34 : ident := 208%positive.\nDefinition _t'4 : ident := 178%positive.\nDefinition _t'5 : ident := 179%positive.\nDefinition _t'6 : ident := 180%positive.\nDefinition _t'7 : ident := 181%positive.\nDefinition _t'8 : ident := 182%positive.\nDefinition _t'9 : ident := 183%positive.\n\nDefinition v__0 := {|\n  gvar_info := (tarray tuchar 16);\n  gvar_init := (Init_space 16 :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v__9 := {|\n  gvar_info := (tarray tuchar 32);\n  gvar_init := (Init_int8 (Int.repr 9) :: Init_space 31 :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_gf0 := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_space 128 :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_gf1 := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 1) :: Init_space 120 :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v__121665 := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 56129) :: Init_int64 (Int64.repr 1) ::\n                Init_space 112 :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_D := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 30883) ::\n                Init_int64 (Int64.repr 4953) ::\n                Init_int64 (Int64.repr 19914) ::\n                Init_int64 (Int64.repr 30187) ::\n                Init_int64 (Int64.repr 55467) ::\n                Init_int64 (Int64.repr 16705) ::\n                Init_int64 (Int64.repr 2637) ::\n                Init_int64 (Int64.repr 112) ::\n                Init_int64 (Int64.repr 59544) ::\n                Init_int64 (Int64.repr 30585) ::\n                Init_int64 (Int64.repr 16505) ::\n                Init_int64 (Int64.repr 36039) ::\n                Init_int64 (Int64.repr 65139) ::\n                Init_int64 (Int64.repr 11119) ::\n                Init_int64 (Int64.repr 27886) ::\n                Init_int64 (Int64.repr 20995) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_D2 := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 61785) ::\n                Init_int64 (Int64.repr 9906) ::\n                Init_int64 (Int64.repr 39828) ::\n                Init_int64 (Int64.repr 60374) ::\n                Init_int64 (Int64.repr 45398) ::\n                Init_int64 (Int64.repr 33411) ::\n                Init_int64 (Int64.repr 5274) ::\n                Init_int64 (Int64.repr 224) ::\n                Init_int64 (Int64.repr 53552) ::\n                Init_int64 (Int64.repr 61171) ::\n                Init_int64 (Int64.repr 33010) ::\n                Init_int64 (Int64.repr 6542) ::\n                Init_int64 (Int64.repr 64743) ::\n                Init_int64 (Int64.repr 22239) ::\n                Init_int64 (Int64.repr 55772) ::\n                Init_int64 (Int64.repr 9222) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_X := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 54554) ::\n                Init_int64 (Int64.repr 36645) ::\n                Init_int64 (Int64.repr 11616) ::\n                Init_int64 (Int64.repr 51542) ::\n                Init_int64 (Int64.repr 42930) ::\n                Init_int64 (Int64.repr 38181) ::\n                Init_int64 (Int64.repr 51040) ::\n                Init_int64 (Int64.repr 26924) ::\n                Init_int64 (Int64.repr 56412) ::\n                Init_int64 (Int64.repr 64982) ::\n                Init_int64 (Int64.repr 57905) ::\n                Init_int64 (Int64.repr 49316) ::\n                Init_int64 (Int64.repr 21502) ::\n                Init_int64 (Int64.repr 52590) ::\n                Init_int64 (Int64.repr 14035) ::\n                Init_int64 (Int64.repr 8553) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_Y := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 26200) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) ::\n                Init_int64 (Int64.repr 26214) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition v_I := {|\n  gvar_info := (tarray tlong 16);\n  gvar_init := (Init_int64 (Int64.repr 41136) ::\n                Init_int64 (Int64.repr 18958) ::\n                Init_int64 (Int64.repr 6951) ::\n                Init_int64 (Int64.repr 50414) ::\n                Init_int64 (Int64.repr 58488) ::\n                Init_int64 (Int64.repr 44335) ::\n                Init_int64 (Int64.repr 6150) ::\n                Init_int64 (Int64.repr 12099) ::\n                Init_int64 (Int64.repr 55207) ::\n                Init_int64 (Int64.repr 15867) ::\n                Init_int64 (Int64.repr 153) ::\n                Init_int64 (Int64.repr 11085) ::\n                Init_int64 (Int64.repr 57099) ::\n                Init_int64 (Int64.repr 20417) ::\n                Init_int64 (Int64.repr 9344) ::\n                Init_int64 (Int64.repr 11139) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_L32 := {|\n  fn_return := tuint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tuint) :: (_c, tint) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oor\n                 (Ebinop Oshl (Etempvar _x tuint) (Etempvar _c tint) tuint)\n                 (Ebinop Oshr\n                   (Ebinop Oand (Etempvar _x tuint)\n                     (Econst_int (Int.repr (-1)) tuint) tuint)\n                   (Ebinop Osub (Econst_int (Int.repr 32) tint)\n                     (Etempvar _c tint) tint) tuint) tuint)))\n|}.\n\nDefinition f_ld32 := {|\n  fn_return := tuint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_u, tuint) :: (_t'3, tuchar) :: (_t'2, tuchar) ::\n               (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _u\n    (Ederef\n      (Ebinop Oadd (Etempvar _x (tptr tuchar)) (Econst_int (Int.repr 3) tint)\n        (tptr tuchar)) tuchar))\n  (Ssequence\n    (Ssequence\n      (Sset _t'3\n        (Ederef\n          (Ebinop Oadd (Etempvar _x (tptr tuchar))\n            (Econst_int (Int.repr 2) tint) (tptr tuchar)) tuchar))\n      (Sset _u\n        (Ebinop Oor\n          (Ebinop Oshl (Etempvar _u tuint) (Econst_int (Int.repr 8) tint)\n            tuint) (Etempvar _t'3 tuchar) tuint)))\n    (Ssequence\n      (Ssequence\n        (Sset _t'2\n          (Ederef\n            (Ebinop Oadd (Etempvar _x (tptr tuchar))\n              (Econst_int (Int.repr 1) tint) (tptr tuchar)) tuchar))\n        (Sset _u\n          (Ebinop Oor\n            (Ebinop Oshl (Etempvar _u tuint) (Econst_int (Int.repr 8) tint)\n              tuint) (Etempvar _t'2 tuchar) tuint)))\n      (Ssequence\n        (Sset _t'1\n          (Ederef\n            (Ebinop Oadd (Etempvar _x (tptr tuchar))\n              (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar))\n        (Sreturn (Some (Ebinop Oor\n                         (Ebinop Oshl (Etempvar _u tuint)\n                           (Econst_int (Int.repr 8) tint) tuint)\n                         (Etempvar _t'1 tuchar) tuint)))))))\n|}.\n\nDefinition f_dl64 := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_u, tulong) :: (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _u (Ecast (Econst_int (Int.repr 0) tint) tulong))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                         (Econst_int (Int.repr 8) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'1\n              (Ederef\n                (Ebinop Oadd (Etempvar _x (tptr tuchar)) (Etempvar _i tint)\n                  (tptr tuchar)) tuchar))\n            (Sset _u\n              (Ebinop Oor\n                (Ebinop Oshl (Etempvar _u tulong)\n                  (Econst_int (Int.repr 8) tint) tulong)\n                (Etempvar _t'1 tuchar) tulong))))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n            tint))))\n    (Sreturn (Some (Etempvar _u tulong)))))\n|}.\n\nDefinition f_st32 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_u, tuint) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 4) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Etempvar _x (tptr tuchar)) (Etempvar _i tint)\n              (tptr tuchar)) tuchar) (Etempvar _u tuint))\n        (Sset _u\n          (Ebinop Oshr (Etempvar _u tuint) (Econst_int (Int.repr 8) tint)\n            tuint))))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_ts64 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_u, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 7) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Oge (Etempvar _i tint)\n                     (Econst_int (Int.repr 0) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Etempvar _x (tptr tuchar)) (Etempvar _i tint)\n              (tptr tuchar)) tuchar) (Etempvar _u tulong))\n        (Sset _u\n          (Ebinop Oshr (Etempvar _u tulong) (Econst_int (Int.repr 8) tint)\n            tulong))))\n    (Sset _i\n      (Ebinop Osub (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_vn := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_y, (tptr tuchar)) :: (_n, tint) ::\n                nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tuint) :: (_d, tuint) :: (_t'2, tuchar) ::\n               (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _d (Econst_int (Int.repr 0) tint))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tuint) (Etempvar _n tint)\n                         tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'1\n              (Ederef\n                (Ebinop Oadd (Etempvar _x (tptr tuchar)) (Etempvar _i tuint)\n                  (tptr tuchar)) tuchar))\n            (Ssequence\n              (Sset _t'2\n                (Ederef\n                  (Ebinop Oadd (Etempvar _y (tptr tuchar))\n                    (Etempvar _i tuint) (tptr tuchar)) tuchar))\n              (Sset _d\n                (Ebinop Oor (Etempvar _d tuint)\n                  (Ebinop Oxor (Etempvar _t'1 tuchar) (Etempvar _t'2 tuchar)\n                    tint) tuint)))))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tuint) (Econst_int (Int.repr 1) tint)\n            tuint))))\n    (Sreturn (Some (Ebinop Osub\n                     (Ebinop Oand (Econst_int (Int.repr 1) tint)\n                       (Ebinop Oshr\n                         (Ebinop Osub (Etempvar _d tuint)\n                           (Econst_int (Int.repr 1) tint) tuint)\n                         (Econst_int (Int.repr 8) tint) tuint) tuint)\n                     (Econst_int (Int.repr 1) tint) tuint)))))\n|}.\n\nDefinition f_crypto_verify_16_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_y, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _vn (Tfunction\n                (Tcons (tptr tuchar) (Tcons (tptr tuchar) (Tcons tint Tnil)))\n                tint cc_default))\n    ((Etempvar _x (tptr tuchar)) :: (Etempvar _y (tptr tuchar)) ::\n     (Econst_int (Int.repr 16) tint) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_crypto_verify_32_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_y, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _vn (Tfunction\n                (Tcons (tptr tuchar) (Tcons (tptr tuchar) (Tcons tint Tnil)))\n                tint cc_default))\n    ((Etempvar _x (tptr tuchar)) :: (Etempvar _y (tptr tuchar)) ::\n     (Econst_int (Int.repr 32) tint) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_core := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_out, (tptr tuchar)) :: (_in, (tptr tuchar)) ::\n                (_k, (tptr tuchar)) :: (_c, (tptr tuchar)) :: (_h, tint) ::\n                nil);\n  fn_vars := ((_w, (tarray tuint 16)) :: (_x, (tarray tuint 16)) ::\n              (_y, (tarray tuint 16)) :: (_t, (tarray tuint 4)) :: nil);\n  fn_temps := ((_i, tint) :: (_j, tint) :: (_m, tint) :: (_t'10, tuint) ::\n               (_t'9, tuint) :: (_t'8, tuint) :: (_t'7, tuint) ::\n               (_t'6, tuint) :: (_t'5, tuint) :: (_t'4, tuint) ::\n               (_t'3, tuint) :: (_t'2, tuint) :: (_t'1, tuint) ::\n               (_t'34, tuint) :: (_t'33, tuint) :: (_t'32, tuint) ::\n               (_t'31, tuint) :: (_t'30, tuint) :: (_t'29, tuint) ::\n               (_t'28, tuint) :: (_t'27, tuint) :: (_t'26, tuint) ::\n               (_t'25, tuint) :: (_t'24, tuint) :: (_t'23, tuint) ::\n               (_t'22, tuint) :: (_t'21, tuint) :: (_t'20, tuint) ::\n               (_t'19, tuint) :: (_t'18, tuint) :: (_t'17, tuint) ::\n               (_t'16, tuint) :: (_t'15, tuint) :: (_t'14, tuint) ::\n               (_t'13, tuint) :: (_t'12, tuint) :: (_t'11, tuint) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                       (Econst_int (Int.repr 4) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Scall (Some _t'1)\n              (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                            cc_default))\n              ((Ebinop Oadd (Etempvar _c (tptr tuchar))\n                 (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                   (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _x (tarray tuint 16))\n                  (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                    (Etempvar _i tint) tint) (tptr tuint)) tuint)\n              (Etempvar _t'1 tuint)))\n          (Ssequence\n            (Ssequence\n              (Scall (Some _t'2)\n                (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                              cc_default))\n                ((Ebinop Oadd (Etempvar _k (tptr tuchar))\n                   (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                     (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Evar _x (tarray tuint 16))\n                    (Ebinop Oadd (Econst_int (Int.repr 1) tint)\n                      (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                (Etempvar _t'2 tuint)))\n            (Ssequence\n              (Ssequence\n                (Scall (Some _t'3)\n                  (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                                cc_default))\n                  ((Ebinop Oadd (Etempvar _in (tptr tuchar))\n                     (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                       (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                      (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                        (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                  (Etempvar _t'3 tuint)))\n              (Ssequence\n                (Scall (Some _t'4)\n                  (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                                cc_default))\n                  ((Ebinop Oadd\n                     (Ebinop Oadd (Etempvar _k (tptr tuchar))\n                       (Econst_int (Int.repr 16) tint) (tptr tuchar))\n                     (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                       (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                      (Ebinop Oadd (Econst_int (Int.repr 11) tint)\n                        (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                  (Etempvar _t'4 tuint)))))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'34\n              (Ederef\n                (Ebinop Oadd (Evar _x (tarray tuint 16)) (Etempvar _i tint)\n                  (tptr tuint)) tuint))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _y (tarray tuint 16)) (Etempvar _i tint)\n                  (tptr tuint)) tuint) (Etempvar _t'34 tuint))))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n            tint))))\n    (Ssequence\n      (Ssequence\n        (Sset _i (Econst_int (Int.repr 0) tint))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                           (Econst_int (Int.repr 20) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Ssequence\n                (Sset _j (Econst_int (Int.repr 0) tint))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _j tint)\n                                   (Econst_int (Int.repr 4) tint) tint)\n                      Sskip\n                      Sbreak)\n                    (Ssequence\n                      (Ssequence\n                        (Sset _m (Econst_int (Int.repr 0) tint))\n                        (Sloop\n                          (Ssequence\n                            (Sifthenelse (Ebinop Olt (Etempvar _m tint)\n                                           (Econst_int (Int.repr 4) tint)\n                                           tint)\n                              Sskip\n                              Sbreak)\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)\n                                  (tptr tuint)) tuint))\n                            (Ssequence\n                              (Sset _t'32\n                                (Ederef\n                                  (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                    (Econst_int (Int.repr 3) tint)\n                                    (tptr tuint)) tuint))\n                              (Scall (Some _t'5)\n                                (Evar _L32 (Tfunction\n                                             (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) :: nil))))\n                          (Ssequence\n                            (Sset _t'30\n                              (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                  (Econst_int (Int.repr 1) tint)\n                                  (tptr 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)\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 (Tfunction\n                                               (Tcons tuint\n                                                 (Tcons tint Tnil)) tuint\n                                               cc_default))\n                                  ((Ebinop Oadd (Etempvar _t'28 tuint)\n                                     (Etempvar _t'29 tuint) tuint) ::\n                                   (Econst_int (Int.repr 9) tint) :: nil))))\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 (Tfunction\n                                                 (Tcons tuint\n                                                   (Tcons tint Tnil)) tuint\n                                                 cc_default))\n                                    ((Ebinop Oadd (Etempvar _t'25 tuint)\n                                       (Etempvar _t'26 tuint) tuint) ::\n                                     (Econst_int (Int.repr 13) tint) :: nil))))\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 (Tfunction\n                                                   (Tcons tuint\n                                                     (Tcons tint Tnil)) tuint\n                                                   cc_default))\n                                      ((Ebinop Oadd (Etempvar _t'22 tuint)\n                                         (Etempvar _t'23 tuint) tuint) ::\n                                       (Econst_int (Int.repr 18) tint) ::\n                                       nil))))\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                              (Ssequence\n                                (Sset _m (Econst_int (Int.repr 0) tint))\n                                (Sloop\n                                  (Ssequence\n                                    (Sifthenelse (Ebinop Olt\n                                                   (Etempvar _m tint)\n                                                   (Econst_int (Int.repr 4) tint)\n                                                   tint)\n                                      Sskip\n                                      Sbreak)\n                                    (Ssequence\n                                      (Sset _t'20\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (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)\n                      (Econst_int (Int.repr 1) tint) tint))))\n              (Ssequence\n                (Sset _m (Econst_int (Int.repr 0) tint))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _m tint)\n                                   (Econst_int (Int.repr 16) tint) tint)\n                      Sskip\n                      Sbreak)\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)\n                      (Econst_int (Int.repr 1) tint) tint))))))\n          (Sset _i\n            (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n              tint))))\n      (Sifthenelse (Etempvar _h tint)\n        (Ssequence\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 16) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Sset _t'17\n                    (Ederef\n                      (Ebinop Oadd (Evar _x (tarray tuint 16))\n                        (Etempvar _i tint) (tptr tuint)) tuint))\n                  (Ssequence\n                    (Sset _t'18\n                      (Ederef\n                        (Ebinop Oadd (Evar _y (tarray tuint 16))\n                          (Etempvar _i tint) (tptr tuint)) tuint))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _x (tarray tuint 16))\n                          (Etempvar _i tint) (tptr tuint)) tuint)\n                      (Ebinop Oadd (Etempvar _t'17 tuint)\n                        (Etempvar _t'18 tuint) tuint)))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Ssequence\n            (Ssequence\n              (Sset _i (Econst_int (Int.repr 0) tint))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                 (Econst_int (Int.repr 4) tint) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Ssequence\n                      (Scall (Some _t'9)\n                        (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil)\n                                      tuint cc_default))\n                        ((Ebinop Oadd (Etempvar _c (tptr tuchar))\n                           (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                             (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                      (Ssequence\n                        (Sset _t'16\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuint 16))\n                              (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                                (Etempvar _i tint) tint) (tptr tuint)) tuint))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuint 16))\n                              (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                                (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                          (Ebinop Osub (Etempvar _t'16 tuint)\n                            (Etempvar _t'9 tuint) tuint))))\n                    (Ssequence\n                      (Scall (Some _t'10)\n                        (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil)\n                                      tuint cc_default))\n                        ((Ebinop Oadd (Etempvar _in (tptr tuchar))\n                           (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                             (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                      (Ssequence\n                        (Sset _t'15\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuint 16))\n                              (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                                (Etempvar _i tint) tint) (tptr tuint)) tuint))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuint 16))\n                              (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                                (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                          (Ebinop Osub (Etempvar _t'15 tuint)\n                            (Etempvar _t'10 tuint) tuint))))))\n                (Sset _i\n                  (Ebinop Oadd (Etempvar _i tint)\n                    (Econst_int (Int.repr 1) tint) tint))))\n            (Ssequence\n              (Sset _i (Econst_int (Int.repr 0) tint))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                 (Econst_int (Int.repr 4) tint) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Ssequence\n                      (Sset _t'14\n                        (Ederef\n                          (Ebinop Oadd (Evar _x (tarray tuint 16))\n                            (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                              (Etempvar _i tint) tint) (tptr tuint)) tuint))\n                      (Scall None\n                        (Evar _st32 (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons tuint Tnil)) tvoid cc_default))\n                        ((Ebinop Oadd (Etempvar _out (tptr tuchar))\n                           (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                             (Etempvar _i tint) tint) (tptr tuchar)) ::\n                         (Etempvar _t'14 tuint) :: nil)))\n                    (Ssequence\n                      (Sset _t'13\n                        (Ederef\n                          (Ebinop Oadd (Evar _x (tarray tuint 16))\n                            (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                              (Etempvar _i tint) tint) (tptr tuint)) tuint))\n                      (Scall None\n                        (Evar _st32 (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons tuint Tnil)) tvoid cc_default))\n                        ((Ebinop Oadd\n                           (Ebinop Oadd (Etempvar _out (tptr tuchar))\n                             (Econst_int (Int.repr 16) tint) (tptr tuchar))\n                           (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                             (Etempvar _i tint) tint) (tptr tuchar)) ::\n                         (Etempvar _t'13 tuint) :: nil)))))\n                (Sset _i\n                  (Ebinop Oadd (Etempvar _i tint)\n                    (Econst_int (Int.repr 1) tint) tint))))))\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                             (Econst_int (Int.repr 16) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'11\n                  (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                      (Etempvar _i tint) (tptr tuint)) tuint))\n                (Ssequence\n                  (Sset _t'12\n                    (Ederef\n                      (Ebinop Oadd (Evar _y (tarray tuint 16))\n                        (Etempvar _i tint) (tptr tuint)) tuint))\n                  (Scall None\n                    (Evar _st32 (Tfunction\n                                  (Tcons (tptr tuchar) (Tcons tuint Tnil))\n                                  tvoid cc_default))\n                    ((Ebinop Oadd (Etempvar _out (tptr tuchar))\n                       (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                         (Etempvar _i tint) tint) (tptr tuchar)) ::\n                     (Ebinop Oadd (Etempvar _t'11 tuint)\n                       (Etempvar _t'12 tuint) tuint) :: nil)))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint))))))))\n|}.\n\nDefinition f_crypto_core_salsa20_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_out, (tptr tuchar)) :: (_in, (tptr tuchar)) ::\n                (_k, (tptr tuchar)) :: (_c, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _core (Tfunction\n                  (Tcons (tptr tuchar)\n                    (Tcons (tptr tuchar)\n                      (Tcons (tptr tuchar)\n                        (Tcons (tptr tuchar) (Tcons tint Tnil))))) tvoid\n                  cc_default))\n    ((Etempvar _out (tptr tuchar)) :: (Etempvar _in (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: (Etempvar _c (tptr tuchar)) ::\n     (Econst_int (Int.repr 0) tint) :: nil))\n  (Sreturn (Some (Econst_int (Int.repr 0) tint))))\n|}.\n\nDefinition f_crypto_core_hsalsa20_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_out, (tptr tuchar)) :: (_in, (tptr tuchar)) ::\n                (_k, (tptr tuchar)) :: (_c, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _core (Tfunction\n                  (Tcons (tptr tuchar)\n                    (Tcons (tptr tuchar)\n                      (Tcons (tptr tuchar)\n                        (Tcons (tptr tuchar) (Tcons tint Tnil))))) tvoid\n                  cc_default))\n    ((Etempvar _out (tptr tuchar)) :: (Etempvar _in (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: (Etempvar _c (tptr tuchar)) ::\n     (Econst_int (Int.repr 1) tint) :: nil))\n  (Sreturn (Some (Econst_int (Int.repr 0) tint))))\n|}.\n\nDefinition v_sigma := {|\n  gvar_info := (tarray tuchar 16);\n  gvar_init := (Init_int8 (Int.repr 101) :: Init_int8 (Int.repr 120) ::\n                Init_int8 (Int.repr 112) :: Init_int8 (Int.repr 97) ::\n                Init_int8 (Int.repr 110) :: Init_int8 (Int.repr 100) ::\n                Init_int8 (Int.repr 32) :: Init_int8 (Int.repr 51) ::\n                Init_int8 (Int.repr 50) :: Init_int8 (Int.repr 45) ::\n                Init_int8 (Int.repr 98) :: Init_int8 (Int.repr 121) ::\n                Init_int8 (Int.repr 116) :: Init_int8 (Int.repr 101) ::\n                Init_int8 (Int.repr 32) :: Init_int8 (Int.repr 107) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_crypto_stream_salsa20_tweet_xor := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_b, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_z, (tarray tuchar 16)) :: (_x, (tarray tuchar 64)) :: nil);\n  fn_temps := ((_u, tuint) :: (_i, tuint) :: (_t'2, tint) :: (_t'1, tint) ::\n               (_t'8, tuchar) :: (_t'7, tuchar) :: (_t'6, tuchar) ::\n               (_t'5, tuchar) :: (_t'4, tuchar) :: (_t'3, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Eunop Onotbool (Etempvar _b tulong) tint)\n    (Sreturn (Some (Econst_int (Int.repr 0) tint)))\n    Sskip)\n  (Ssequence\n    (Ssequence\n      (Sset _i (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _z (tarray tuchar 16)) (Etempvar _i tuint)\n                (tptr tuchar)) tuchar) (Econst_int (Int.repr 0) tint)))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tuint) (Econst_int (Int.repr 1) tint)\n            tuint))))\n    (Ssequence\n      (Ssequence\n        (Sset _i (Econst_int (Int.repr 0) tint))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                           (Econst_int (Int.repr 8) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Sset _t'8\n                (Ederef\n                  (Ebinop Oadd (Etempvar _n (tptr tuchar))\n                    (Etempvar _i tuint) (tptr tuchar)) tuchar))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Evar _z (tarray tuchar 16))\n                    (Etempvar _i tuint) (tptr tuchar)) tuchar)\n                (Etempvar _t'8 tuchar))))\n          (Sset _i\n            (Ebinop Oadd (Etempvar _i tuint) (Econst_int (Int.repr 1) tint)\n              tuint))))\n      (Ssequence\n        (Swhile\n          (Ebinop Oge (Etempvar _b tulong) (Econst_int (Int.repr 64) tint)\n            tint)\n          (Ssequence\n            (Scall None\n              (Evar _crypto_core_salsa20_tweet (Tfunction\n                                                 (Tcons (tptr tuchar)\n                                                   (Tcons (tptr tuchar)\n                                                     (Tcons (tptr tuchar)\n                                                       (Tcons (tptr tuchar)\n                                                         Tnil)))) tint\n                                                 cc_default))\n              ((Evar _x (tarray tuchar 64)) ::\n               (Evar _z (tarray tuchar 16)) :: (Etempvar _k (tptr tuchar)) ::\n               (Evar _sigma (tarray tuchar 16)) :: nil))\n            (Ssequence\n              (Ssequence\n                (Sset _i (Econst_int (Int.repr 0) tint))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                                   (Econst_int (Int.repr 64) tint) tint)\n                      Sskip\n                      Sbreak)\n                    (Ssequence\n                      (Sifthenelse (Etempvar _m (tptr tuchar))\n                        (Ssequence\n                          (Sset _t'7\n                            (Ederef\n                              (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                                (Etempvar _i tuint) (tptr tuchar)) tuchar))\n                          (Sset _t'1 (Ecast (Etempvar _t'7 tuchar) tint)))\n                        (Sset _t'1\n                          (Ecast (Econst_int (Int.repr 0) tint) tint)))\n                      (Ssequence\n                        (Sset _t'6\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuchar 64))\n                              (Etempvar _i tuint) (tptr tuchar)) tuchar))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _c (tptr tuchar))\n                              (Etempvar _i tuint) (tptr tuchar)) tuchar)\n                          (Ebinop Oxor (Etempvar _t'1 tint)\n                            (Etempvar _t'6 tuchar) tint)))))\n                  (Sset _i\n                    (Ebinop Oadd (Etempvar _i tuint)\n                      (Econst_int (Int.repr 1) tint) tuint))))\n              (Ssequence\n                (Sset _u (Econst_int (Int.repr 1) tint))\n                (Ssequence\n                  (Ssequence\n                    (Sset _i (Econst_int (Int.repr 8) tint))\n                    (Sloop\n                      (Ssequence\n                        (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                                       (Econst_int (Int.repr 16) tint) tint)\n                          Sskip\n                          Sbreak)\n                        (Ssequence\n                          (Ssequence\n                            (Sset _t'5\n                              (Ederef\n                                (Ebinop Oadd (Evar _z (tarray tuchar 16))\n                                  (Etempvar _i tuint) (tptr tuchar)) tuchar))\n                            (Sset _u\n                              (Ebinop Oadd (Etempvar _u tuint)\n                                (Ecast (Etempvar _t'5 tuchar) tuint) tuint)))\n                          (Ssequence\n                            (Sassign\n                              (Ederef\n                                (Ebinop Oadd (Evar _z (tarray tuchar 16))\n                                  (Etempvar _i tuint) (tptr tuchar)) tuchar)\n                              (Etempvar _u tuint))\n                            (Sset _u\n                              (Ebinop Oshr (Etempvar _u tuint)\n                                (Econst_int (Int.repr 8) tint) tuint)))))\n                      (Sset _i\n                        (Ebinop Oadd (Etempvar _i tuint)\n                          (Econst_int (Int.repr 1) tint) tuint))))\n                  (Ssequence\n                    (Sset _b\n                      (Ebinop Osub (Etempvar _b tulong)\n                        (Econst_int (Int.repr 64) tint) tulong))\n                    (Ssequence\n                      (Sset _c\n                        (Ebinop Oadd (Etempvar _c (tptr tuchar))\n                          (Econst_int (Int.repr 64) tint) (tptr tuchar)))\n                      (Sifthenelse (Etempvar _m (tptr tuchar))\n                        (Sset _m\n                          (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                            (Econst_int (Int.repr 64) tint) (tptr tuchar)))\n                        Sskip))))))))\n        (Ssequence\n          (Sifthenelse (Etempvar _b tulong)\n            (Ssequence\n              (Scall None\n                (Evar _crypto_core_salsa20_tweet (Tfunction\n                                                   (Tcons (tptr tuchar)\n                                                     (Tcons (tptr tuchar)\n                                                       (Tcons (tptr tuchar)\n                                                         (Tcons (tptr tuchar)\n                                                           Tnil)))) tint\n                                                   cc_default))\n                ((Evar _x (tarray tuchar 64)) ::\n                 (Evar _z (tarray tuchar 16)) ::\n                 (Etempvar _k (tptr tuchar)) ::\n                 (Evar _sigma (tarray tuchar 16)) :: nil))\n              (Ssequence\n                (Sset _i (Econst_int (Int.repr 0) tint))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _i tuint)\n                                   (Etempvar _b tulong) tint)\n                      Sskip\n                      Sbreak)\n                    (Ssequence\n                      (Sifthenelse (Etempvar _m (tptr tuchar))\n                        (Ssequence\n                          (Sset _t'4\n                            (Ederef\n                              (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                                (Etempvar _i tuint) (tptr tuchar)) tuchar))\n                          (Sset _t'2 (Ecast (Etempvar _t'4 tuchar) tint)))\n                        (Sset _t'2\n                          (Ecast (Econst_int (Int.repr 0) tint) tint)))\n                      (Ssequence\n                        (Sset _t'3\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuchar 64))\n                              (Etempvar _i tuint) (tptr tuchar)) tuchar))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _c (tptr tuchar))\n                              (Etempvar _i tuint) (tptr tuchar)) tuchar)\n                          (Ebinop Oxor (Etempvar _t'2 tint)\n                            (Etempvar _t'3 tuchar) tint)))))\n                  (Sset _i\n                    (Ebinop Oadd (Etempvar _i tuint)\n                      (Econst_int (Int.repr 1) tint) tuint)))))\n            Sskip)\n          (Sreturn (Some (Econst_int (Int.repr 0) tint))))))))\n|}.\n\nDefinition f_crypto_stream_salsa20_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_d, tulong) :: (_n, (tptr tuchar)) ::\n                (_k, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _crypto_stream_salsa20_tweet_xor (Tfunction\n                                             (Tcons (tptr tuchar)\n                                               (Tcons (tptr tuchar)\n                                                 (Tcons tulong\n                                                   (Tcons (tptr tuchar)\n                                                     (Tcons (tptr tuchar)\n                                                       Tnil))))) tint\n                                             cc_default))\n    ((Etempvar _c (tptr tuchar)) :: (Econst_int (Int.repr 0) tint) ::\n     (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_crypto_stream_xsalsa20_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_d, tulong) :: (_n, (tptr tuchar)) ::\n                (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_s, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_core_hsalsa20_tweet (Tfunction\n                                        (Tcons (tptr tuchar)\n                                          (Tcons (tptr tuchar)\n                                            (Tcons (tptr tuchar)\n                                              (Tcons (tptr tuchar) Tnil))))\n                                        tint cc_default))\n    ((Evar _s (tarray tuchar 32)) :: (Etempvar _n (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: (Evar _sigma (tarray tuchar 16)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_stream_salsa20_tweet (Tfunction\n                                           (Tcons (tptr tuchar)\n                                             (Tcons tulong\n                                               (Tcons (tptr tuchar)\n                                                 (Tcons (tptr tuchar) Tnil))))\n                                           tint cc_default))\n      ((Etempvar _c (tptr tuchar)) :: (Etempvar _d tulong) ::\n       (Ebinop Oadd (Etempvar _n (tptr tuchar))\n         (Econst_int (Int.repr 16) tint) (tptr tuchar)) ::\n       (Evar _s (tarray tuchar 32)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_crypto_stream_xsalsa20_tweet_xor := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_s, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_core_hsalsa20_tweet (Tfunction\n                                        (Tcons (tptr tuchar)\n                                          (Tcons (tptr tuchar)\n                                            (Tcons (tptr tuchar)\n                                              (Tcons (tptr tuchar) Tnil))))\n                                        tint cc_default))\n    ((Evar _s (tarray tuchar 32)) :: (Etempvar _n (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: (Evar _sigma (tarray tuchar 16)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_stream_salsa20_tweet_xor (Tfunction\n                                               (Tcons (tptr tuchar)\n                                                 (Tcons (tptr tuchar)\n                                                   (Tcons tulong\n                                                     (Tcons (tptr tuchar)\n                                                       (Tcons (tptr tuchar)\n                                                         Tnil))))) tint\n                                               cc_default))\n      ((Etempvar _c (tptr tuchar)) :: (Etempvar _m (tptr tuchar)) ::\n       (Etempvar _d tulong) ::\n       (Ebinop Oadd (Etempvar _n (tptr tuchar))\n         (Econst_int (Int.repr 16) tint) (tptr tuchar)) ::\n       (Evar _s (tarray tuchar 32)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_add1305 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_h, (tptr tuint)) :: (_c, (tptr tuint)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_j, tuint) :: (_u, tuint) :: (_t'2, tuint) ::\n               (_t'1, tuint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _u (Econst_int (Int.repr 0) tint))\n  (Ssequence\n    (Sset _j (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _j tuint)\n                       (Econst_int (Int.repr 17) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Sset _t'1\n              (Ederef\n                (Ebinop Oadd (Etempvar _h (tptr tuint)) (Etempvar _j tuint)\n                  (tptr tuint)) tuint))\n            (Ssequence\n              (Sset _t'2\n                (Ederef\n                  (Ebinop Oadd (Etempvar _c (tptr tuint)) (Etempvar _j tuint)\n                    (tptr tuint)) tuint))\n              (Sset _u\n                (Ebinop Oadd (Etempvar _u tuint)\n                  (Ebinop Oadd (Etempvar _t'1 tuint) (Etempvar _t'2 tuint)\n                    tuint) tuint))))\n          (Ssequence\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Etempvar _h (tptr tuint)) (Etempvar _j tuint)\n                  (tptr tuint)) tuint)\n              (Ebinop Oand (Etempvar _u tuint)\n                (Econst_int (Int.repr 255) tint) tuint))\n            (Sset _u\n              (Ebinop Oshr (Etempvar _u tuint) (Econst_int (Int.repr 8) tint)\n                tuint)))))\n      (Sset _j\n        (Ebinop Oadd (Etempvar _j tuint) (Econst_int (Int.repr 1) tint)\n          tuint)))))\n|}.\n\nDefinition v_minusp := {|\n  gvar_info := (tarray tuint 17);\n  gvar_init := (Init_int32 (Int.repr 5) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 0) :: Init_int32 (Int.repr 0) ::\n                Init_int32 (Int.repr 252) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_crypto_onetimeauth_poly1305_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_out, (tptr tuchar)) :: (_m, (tptr tuchar)) ::\n                (_n, tulong) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_x, (tarray tuint 17)) :: (_r, (tarray tuint 17)) ::\n              (_h, (tarray tuint 17)) :: (_c, (tarray tuint 17)) ::\n              (_g, (tarray tuint 17)) :: nil);\n  fn_temps := ((_s, tuint) :: (_i, tuint) :: (_j, tuint) :: (_u, tuint) ::\n               (_t'3, tuint) :: (_t'2, tint) :: (_t'1, tuint) ::\n               (_t'28, tuchar) :: (_t'27, tuint) :: (_t'26, tuint) ::\n               (_t'25, tuint) :: (_t'24, tuint) :: (_t'23, tuint) ::\n               (_t'22, tuint) :: (_t'21, tuint) :: (_t'20, tuchar) ::\n               (_t'19, tuint) :: (_t'18, tuint) :: (_t'17, tuint) ::\n               (_t'16, tuint) :: (_t'15, tuint) :: (_t'14, tuint) ::\n               (_t'13, tuint) :: (_t'12, tuint) :: (_t'11, tuint) ::\n               (_t'10, tuint) :: (_t'9, tuint) :: (_t'8, tuint) ::\n               (_t'7, tuint) :: (_t'6, tuint) :: (_t'5, tuchar) ::\n               (_t'4, tuint) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _j (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _j tuint)\n                       (Econst_int (Int.repr 17) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Sset _t'1 (Ecast (Econst_int (Int.repr 0) tint) tuint))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _h (tarray tuint 17)) (Etempvar _j tuint)\n                  (tptr tuint)) tuint) (Etempvar _t'1 tuint)))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _r (tarray tuint 17)) (Etempvar _j tuint)\n                (tptr tuint)) tuint) (Etempvar _t'1 tuint))))\n      (Sset _j\n        (Ebinop Oadd (Etempvar _j tuint) (Econst_int (Int.repr 1) tint)\n          tuint))))\n  (Ssequence\n    (Ssequence\n      (Sset _j (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _j tuint)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'28\n              (Ederef\n                (Ebinop Oadd (Etempvar _k (tptr tuchar)) (Etempvar _j tuint)\n                  (tptr tuchar)) tuchar))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _r (tarray tuint 17)) (Etempvar _j tuint)\n                  (tptr tuint)) tuint) (Etempvar _t'28 tuchar))))\n        (Sset _j\n          (Ebinop Oadd (Etempvar _j tuint) (Econst_int (Int.repr 1) tint)\n            tuint))))\n    (Ssequence\n      (Ssequence\n        (Sset _t'27\n          (Ederef\n            (Ebinop Oadd (Evar _r (tarray tuint 17))\n              (Econst_int (Int.repr 3) tint) (tptr tuint)) tuint))\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Evar _r (tarray tuint 17))\n              (Econst_int (Int.repr 3) tint) (tptr tuint)) tuint)\n          (Ebinop Oand (Etempvar _t'27 tuint) (Econst_int (Int.repr 15) tint)\n            tuint)))\n      (Ssequence\n        (Ssequence\n          (Sset _t'26\n            (Ederef\n              (Ebinop Oadd (Evar _r (tarray tuint 17))\n                (Econst_int (Int.repr 4) tint) (tptr tuint)) tuint))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _r (tarray tuint 17))\n                (Econst_int (Int.repr 4) tint) (tptr tuint)) tuint)\n            (Ebinop Oand (Etempvar _t'26 tuint)\n              (Econst_int (Int.repr 252) tint) tuint)))\n        (Ssequence\n          (Ssequence\n            (Sset _t'25\n              (Ederef\n                (Ebinop Oadd (Evar _r (tarray tuint 17))\n                  (Econst_int (Int.repr 7) tint) (tptr tuint)) tuint))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _r (tarray tuint 17))\n                  (Econst_int (Int.repr 7) tint) (tptr tuint)) tuint)\n              (Ebinop Oand (Etempvar _t'25 tuint)\n                (Econst_int (Int.repr 15) tint) tuint)))\n          (Ssequence\n            (Ssequence\n              (Sset _t'24\n                (Ederef\n                  (Ebinop Oadd (Evar _r (tarray tuint 17))\n                    (Econst_int (Int.repr 8) tint) (tptr tuint)) tuint))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Evar _r (tarray tuint 17))\n                    (Econst_int (Int.repr 8) tint) (tptr tuint)) tuint)\n                (Ebinop Oand (Etempvar _t'24 tuint)\n                  (Econst_int (Int.repr 252) tint) tuint)))\n            (Ssequence\n              (Ssequence\n                (Sset _t'23\n                  (Ederef\n                    (Ebinop Oadd (Evar _r (tarray tuint 17))\n                      (Econst_int (Int.repr 11) tint) (tptr tuint)) tuint))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _r (tarray tuint 17))\n                      (Econst_int (Int.repr 11) tint) (tptr tuint)) tuint)\n                  (Ebinop Oand (Etempvar _t'23 tuint)\n                    (Econst_int (Int.repr 15) tint) tuint)))\n              (Ssequence\n                (Ssequence\n                  (Sset _t'22\n                    (Ederef\n                      (Ebinop Oadd (Evar _r (tarray tuint 17))\n                        (Econst_int (Int.repr 12) tint) (tptr tuint)) tuint))\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Evar _r (tarray tuint 17))\n                        (Econst_int (Int.repr 12) tint) (tptr tuint)) tuint)\n                    (Ebinop Oand (Etempvar _t'22 tuint)\n                      (Econst_int (Int.repr 252) tint) tuint)))\n                (Ssequence\n                  (Ssequence\n                    (Sset _t'21\n                      (Ederef\n                        (Ebinop Oadd (Evar _r (tarray tuint 17))\n                          (Econst_int (Int.repr 15) tint) (tptr tuint))\n                        tuint))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _r (tarray tuint 17))\n                          (Econst_int (Int.repr 15) tint) (tptr tuint))\n                        tuint)\n                      (Ebinop Oand (Etempvar _t'21 tuint)\n                        (Econst_int (Int.repr 15) tint) tuint)))\n                  (Ssequence\n                    (Swhile\n                      (Ebinop Ogt (Etempvar _n tulong)\n                        (Econst_int (Int.repr 0) tint) tint)\n                      (Ssequence\n                        (Ssequence\n                          (Sset _j (Econst_int (Int.repr 0) tint))\n                          (Sloop\n                            (Ssequence\n                              (Sifthenelse (Ebinop Olt (Etempvar _j tuint)\n                                             (Econst_int (Int.repr 17) tint)\n                                             tint)\n                                Sskip\n                                Sbreak)\n                              (Sassign\n                                (Ederef\n                                  (Ebinop Oadd (Evar _c (tarray tuint 17))\n                                    (Etempvar _j tuint) (tptr tuint)) tuint)\n                                (Econst_int (Int.repr 0) tint)))\n                            (Sset _j\n                              (Ebinop Oadd (Etempvar _j tuint)\n                                (Econst_int (Int.repr 1) tint) tuint))))\n                        (Ssequence\n                          (Ssequence\n                            (Sset _j (Econst_int (Int.repr 0) tint))\n                            (Sloop\n                              (Ssequence\n                                (Ssequence\n                                  (Sifthenelse (Ebinop Olt\n                                                 (Etempvar _j tuint)\n                                                 (Econst_int (Int.repr 16) tint)\n                                                 tint)\n                                    (Sset _t'2\n                                      (Ecast\n                                        (Ebinop Olt (Etempvar _j tuint)\n                                          (Etempvar _n tulong) tint) tbool))\n                                    (Sset _t'2\n                                      (Econst_int (Int.repr 0) tint)))\n                                  (Sifthenelse (Etempvar _t'2 tint)\n                                    Sskip\n                                    Sbreak))\n                                (Ssequence\n                                  (Sset _t'20\n                                    (Ederef\n                                      (Ebinop Oadd\n                                        (Etempvar _m (tptr tuchar))\n                                        (Etempvar _j tuint) (tptr tuchar))\n                                      tuchar))\n                                  (Sassign\n                                    (Ederef\n                                      (Ebinop Oadd\n                                        (Evar _c (tarray tuint 17))\n                                        (Etempvar _j tuint) (tptr tuint))\n                                      tuint) (Etempvar _t'20 tuchar))))\n                              (Sset _j\n                                (Ebinop Oadd (Etempvar _j tuint)\n                                  (Econst_int (Int.repr 1) tint) tuint))))\n                          (Ssequence\n                            (Sassign\n                              (Ederef\n                                (Ebinop Oadd (Evar _c (tarray tuint 17))\n                                  (Etempvar _j tuint) (tptr tuint)) tuint)\n                              (Econst_int (Int.repr 1) tint))\n                            (Ssequence\n                              (Sset _m\n                                (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                                  (Etempvar _j tuint) (tptr tuchar)))\n                              (Ssequence\n                                (Sset _n\n                                  (Ebinop Osub (Etempvar _n tulong)\n                                    (Etempvar _j tuint) tulong))\n                                (Ssequence\n                                  (Scall None\n                                    (Evar _add1305 (Tfunction\n                                                     (Tcons (tptr tuint)\n                                                       (Tcons (tptr tuint)\n                                                         Tnil)) tvoid\n                                                     cc_default))\n                                    ((Evar _h (tarray tuint 17)) ::\n                                     (Evar _c (tarray tuint 17)) :: nil))\n                                  (Ssequence\n                                    (Ssequence\n                                      (Sset _i\n                                        (Econst_int (Int.repr 0) tint))\n                                      (Sloop\n                                        (Ssequence\n                                          (Sifthenelse (Ebinop Olt\n                                                         (Etempvar _i tuint)\n                                                         (Econst_int (Int.repr 17) tint)\n                                                         tint)\n                                            Sskip\n                                            Sbreak)\n                                          (Ssequence\n                                            (Sassign\n                                              (Ederef\n                                                (Ebinop Oadd\n                                                  (Evar _x (tarray tuint 17))\n                                                  (Etempvar _i tuint)\n                                                  (tptr tuint)) tuint)\n                                              (Econst_int (Int.repr 0) tint))\n                                            (Ssequence\n                                              (Sset _j\n                                                (Econst_int (Int.repr 0) tint))\n                                              (Sloop\n                                                (Ssequence\n                                                  (Sifthenelse (Ebinop Olt\n                                                                 (Etempvar _j tuint)\n                                                                 (Econst_int (Int.repr 17) tint)\n                                                                 tint)\n                                                    Sskip\n                                                    Sbreak)\n                                                  (Ssequence\n                                                    (Sifthenelse (Ebinop Ole\n                                                                   (Etempvar _j tuint)\n                                                                   (Etempvar _i tuint)\n                                                                   tint)\n                                                      (Ssequence\n                                                        (Sset _t'19\n                                                          (Ederef\n                                                            (Ebinop Oadd\n                                                              (Evar _r (tarray tuint 17))\n                                                              (Ebinop Osub\n                                                                (Etempvar _i tuint)\n                                                                (Etempvar _j tuint)\n                                                                tuint)\n                                                              (tptr tuint))\n                                                            tuint))\n                                                        (Sset _t'3\n                                                          (Ecast\n                                                            (Etempvar _t'19 tuint)\n                                                            tuint)))\n                                                      (Ssequence\n                                                        (Sset _t'18\n                                                          (Ederef\n                                                            (Ebinop Oadd\n                                                              (Evar _r (tarray tuint 17))\n                                                              (Ebinop Osub\n                                                                (Ebinop Oadd\n                                                                  (Etempvar _i tuint)\n                                                                  (Econst_int (Int.repr 17) tint)\n                                                                  tuint)\n                                                                (Etempvar _j tuint)\n                                                                tuint)\n                                                              (tptr tuint))\n                                                            tuint))\n                                                        (Sset _t'3\n                                                          (Ecast\n                                                            (Ebinop Omul\n                                                              (Econst_int (Int.repr 320) tint)\n                                                              (Etempvar _t'18 tuint)\n                                                              tuint) tuint))))\n                                                    (Ssequence\n                                                      (Sset _t'16\n                                                        (Ederef\n                                                          (Ebinop Oadd\n                                                            (Evar _x (tarray tuint 17))\n                                                            (Etempvar _i tuint)\n                                                            (tptr tuint))\n                                                          tuint))\n                                                      (Ssequence\n                                                        (Sset _t'17\n                                                          (Ederef\n                                                            (Ebinop Oadd\n                                                              (Evar _h (tarray tuint 17))\n                                                              (Etempvar _j tuint)\n                                                              (tptr tuint))\n                                                            tuint))\n                                                        (Sassign\n                                                          (Ederef\n                                                            (Ebinop Oadd\n                                                              (Evar _x (tarray tuint 17))\n                                                              (Etempvar _i tuint)\n                                                              (tptr tuint))\n                                                            tuint)\n                                                          (Ebinop Oadd\n                                                            (Etempvar _t'16 tuint)\n                                                            (Ebinop Omul\n                                                              (Etempvar _t'17 tuint)\n                                                              (Etempvar _t'3 tuint)\n                                                              tuint) tuint))))))\n                                                (Sset _j\n                                                  (Ebinop Oadd\n                                                    (Etempvar _j tuint)\n                                                    (Econst_int (Int.repr 1) tint)\n                                                    tuint))))))\n                                        (Sset _i\n                                          (Ebinop Oadd (Etempvar _i tuint)\n                                            (Econst_int (Int.repr 1) tint)\n                                            tuint))))\n                                    (Ssequence\n                                      (Ssequence\n                                        (Sset _i\n                                          (Econst_int (Int.repr 0) tint))\n                                        (Sloop\n                                          (Ssequence\n                                            (Sifthenelse (Ebinop Olt\n                                                           (Etempvar _i tuint)\n                                                           (Econst_int (Int.repr 17) tint)\n                                                           tint)\n                                              Sskip\n                                              Sbreak)\n                                            (Ssequence\n                                              (Sset _t'15\n                                                (Ederef\n                                                  (Ebinop Oadd\n                                                    (Evar _x (tarray tuint 17))\n                                                    (Etempvar _i tuint)\n                                                    (tptr tuint)) tuint))\n                                              (Sassign\n                                                (Ederef\n                                                  (Ebinop Oadd\n                                                    (Evar _h (tarray tuint 17))\n                                                    (Etempvar _i tuint)\n                                                    (tptr tuint)) tuint)\n                                                (Etempvar _t'15 tuint))))\n                                          (Sset _i\n                                            (Ebinop Oadd (Etempvar _i tuint)\n                                              (Econst_int (Int.repr 1) tint)\n                                              tuint))))\n                                      (Ssequence\n                                        (Sset _u\n                                          (Econst_int (Int.repr 0) tint))\n                                        (Ssequence\n                                          (Ssequence\n                                            (Sset _j\n                                              (Econst_int (Int.repr 0) tint))\n                                            (Sloop\n                                              (Ssequence\n                                                (Sifthenelse (Ebinop Olt\n                                                               (Etempvar _j tuint)\n                                                               (Econst_int (Int.repr 16) tint)\n                                                               tint)\n                                                  Sskip\n                                                  Sbreak)\n                                                (Ssequence\n                                                  (Ssequence\n                                                    (Sset _t'14\n                                                      (Ederef\n                                                        (Ebinop Oadd\n                                                          (Evar _h (tarray tuint 17))\n                                                          (Etempvar _j tuint)\n                                                          (tptr tuint))\n                                                        tuint))\n                                                    (Sset _u\n                                                      (Ebinop Oadd\n                                                        (Etempvar _u tuint)\n                                                        (Etempvar _t'14 tuint)\n                                                        tuint)))\n                                                  (Ssequence\n                                                    (Sassign\n                                                      (Ederef\n                                                        (Ebinop Oadd\n                                                          (Evar _h (tarray tuint 17))\n                                                          (Etempvar _j tuint)\n                                                          (tptr tuint))\n                                                        tuint)\n                                                      (Ebinop Oand\n                                                        (Etempvar _u tuint)\n                                                        (Econst_int (Int.repr 255) tint)\n                                                        tuint))\n                                                    (Sset _u\n                                                      (Ebinop Oshr\n                                                        (Etempvar _u tuint)\n                                                        (Econst_int (Int.repr 8) tint)\n                                                        tuint)))))\n                                              (Sset _j\n                                                (Ebinop Oadd\n                                                  (Etempvar _j tuint)\n                                                  (Econst_int (Int.repr 1) tint)\n                                                  tuint))))\n                                          (Ssequence\n                                            (Ssequence\n                                              (Sset _t'13\n                                                (Ederef\n                                                  (Ebinop Oadd\n                                                    (Evar _h (tarray tuint 17))\n                                                    (Econst_int (Int.repr 16) tint)\n                                                    (tptr tuint)) tuint))\n                                              (Sset _u\n                                                (Ebinop Oadd\n                                                  (Etempvar _u tuint)\n                                                  (Etempvar _t'13 tuint)\n                                                  tuint)))\n                                            (Ssequence\n                                              (Sassign\n                                                (Ederef\n                                                  (Ebinop Oadd\n                                                    (Evar _h (tarray tuint 17))\n                                                    (Econst_int (Int.repr 16) tint)\n                                                    (tptr tuint)) tuint)\n                                                (Ebinop Oand\n                                                  (Etempvar _u tuint)\n                                                  (Econst_int (Int.repr 3) tint)\n                                                  tuint))\n                                              (Ssequence\n                                                (Sset _u\n                                                  (Ebinop Omul\n                                                    (Econst_int (Int.repr 5) tint)\n                                                    (Ebinop Oshr\n                                                      (Etempvar _u tuint)\n                                                      (Econst_int (Int.repr 2) tint)\n                                                      tuint) tuint))\n                                                (Ssequence\n                                                  (Ssequence\n                                                    (Sset _j\n                                                      (Econst_int (Int.repr 0) tint))\n                                                    (Sloop\n                                                      (Ssequence\n                                                        (Sifthenelse \n                                                          (Ebinop Olt\n                                                            (Etempvar _j tuint)\n                                                            (Econst_int (Int.repr 16) tint)\n                                                            tint)\n                                                          Sskip\n                                                          Sbreak)\n                                                        (Ssequence\n                                                          (Ssequence\n                                                            (Sset _t'12\n                                                              (Ederef\n                                                                (Ebinop Oadd\n                                                                  (Evar _h (tarray tuint 17))\n                                                                  (Etempvar _j tuint)\n                                                                  (tptr tuint))\n                                                                tuint))\n                                                            (Sset _u\n                                                              (Ebinop Oadd\n                                                                (Etempvar _u tuint)\n                                                                (Etempvar _t'12 tuint)\n                                                                tuint)))\n                                                          (Ssequence\n                                                            (Sassign\n                                                              (Ederef\n                                                                (Ebinop Oadd\n                                                                  (Evar _h (tarray tuint 17))\n                                                                  (Etempvar _j tuint)\n                                                                  (tptr tuint))\n                                                                tuint)\n                                                              (Ebinop Oand\n                                                                (Etempvar _u tuint)\n                                                                (Econst_int (Int.repr 255) tint)\n                                                                tuint))\n                                                            (Sset _u\n                                                              (Ebinop Oshr\n                                                                (Etempvar _u tuint)\n                                                                (Econst_int (Int.repr 8) tint)\n                                                                tuint)))))\n                                                      (Sset _j\n                                                        (Ebinop Oadd\n                                                          (Etempvar _j tuint)\n                                                          (Econst_int (Int.repr 1) tint)\n                                                          tuint))))\n                                                  (Ssequence\n                                                    (Ssequence\n                                                      (Sset _t'11\n                                                        (Ederef\n                                                          (Ebinop Oadd\n                                                            (Evar _h (tarray tuint 17))\n                                                            (Econst_int (Int.repr 16) tint)\n                                                            (tptr tuint))\n                                                          tuint))\n                                                      (Sset _u\n                                                        (Ebinop Oadd\n                                                          (Etempvar _u tuint)\n                                                          (Etempvar _t'11 tuint)\n                                                          tuint)))\n                                                    (Sassign\n                                                      (Ederef\n                                                        (Ebinop Oadd\n                                                          (Evar _h (tarray tuint 17))\n                                                          (Econst_int (Int.repr 16) tint)\n                                                          (tptr tuint))\n                                                        tuint)\n                                                      (Etempvar _u tuint))))))))))))))))))\n                    (Ssequence\n                      (Ssequence\n                        (Sset _j (Econst_int (Int.repr 0) tint))\n                        (Sloop\n                          (Ssequence\n                            (Sifthenelse (Ebinop Olt (Etempvar _j tuint)\n                                           (Econst_int (Int.repr 17) tint)\n                                           tint)\n                              Sskip\n                              Sbreak)\n                            (Ssequence\n                              (Sset _t'10\n                                (Ederef\n                                  (Ebinop Oadd (Evar _h (tarray tuint 17))\n                                    (Etempvar _j tuint) (tptr tuint)) tuint))\n                              (Sassign\n                                (Ederef\n                                  (Ebinop Oadd (Evar _g (tarray tuint 17))\n                                    (Etempvar _j tuint) (tptr tuint)) tuint)\n                                (Etempvar _t'10 tuint))))\n                          (Sset _j\n                            (Ebinop Oadd (Etempvar _j tuint)\n                              (Econst_int (Int.repr 1) tint) tuint))))\n                      (Ssequence\n                        (Scall None\n                          (Evar _add1305 (Tfunction\n                                           (Tcons (tptr tuint)\n                                             (Tcons (tptr tuint) Tnil)) tvoid\n                                           cc_default))\n                          ((Evar _h (tarray tuint 17)) ::\n                           (Evar _minusp (tarray tuint 17)) :: nil))\n                        (Ssequence\n                          (Ssequence\n                            (Sset _t'9\n                              (Ederef\n                                (Ebinop Oadd (Evar _h (tarray tuint 17))\n                                  (Econst_int (Int.repr 16) tint)\n                                  (tptr tuint)) tuint))\n                            (Sset _s\n                              (Eunop Oneg\n                                (Ebinop Oshr (Etempvar _t'9 tuint)\n                                  (Econst_int (Int.repr 7) tint) tuint)\n                                tuint)))\n                          (Ssequence\n                            (Ssequence\n                              (Sset _j (Econst_int (Int.repr 0) tint))\n                              (Sloop\n                                (Ssequence\n                                  (Sifthenelse (Ebinop Olt\n                                                 (Etempvar _j tuint)\n                                                 (Econst_int (Int.repr 17) tint)\n                                                 tint)\n                                    Sskip\n                                    Sbreak)\n                                  (Ssequence\n                                    (Sset _t'6\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Evar _h (tarray tuint 17))\n                                          (Etempvar _j tuint) (tptr tuint))\n                                        tuint))\n                                    (Ssequence\n                                      (Sset _t'7\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (Evar _g (tarray tuint 17))\n                                            (Etempvar _j tuint) (tptr tuint))\n                                          tuint))\n                                      (Ssequence\n                                        (Sset _t'8\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _h (tarray tuint 17))\n                                              (Etempvar _j tuint)\n                                              (tptr tuint)) tuint))\n                                        (Sassign\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _h (tarray tuint 17))\n                                              (Etempvar _j tuint)\n                                              (tptr tuint)) tuint)\n                                          (Ebinop Oxor (Etempvar _t'6 tuint)\n                                            (Ebinop Oand (Etempvar _s tuint)\n                                              (Ebinop Oxor\n                                                (Etempvar _t'7 tuint)\n                                                (Etempvar _t'8 tuint) tuint)\n                                              tuint) tuint))))))\n                                (Sset _j\n                                  (Ebinop Oadd (Etempvar _j tuint)\n                                    (Econst_int (Int.repr 1) tint) tuint))))\n                            (Ssequence\n                              (Ssequence\n                                (Sset _j (Econst_int (Int.repr 0) tint))\n                                (Sloop\n                                  (Ssequence\n                                    (Sifthenelse (Ebinop Olt\n                                                   (Etempvar _j tuint)\n                                                   (Econst_int (Int.repr 16) tint)\n                                                   tint)\n                                      Sskip\n                                      Sbreak)\n                                    (Ssequence\n                                      (Sset _t'5\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (Etempvar _k (tptr tuchar))\n                                            (Ebinop Oadd (Etempvar _j tuint)\n                                              (Econst_int (Int.repr 16) tint)\n                                              tuint) (tptr tuchar)) tuchar))\n                                      (Sassign\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (Evar _c (tarray tuint 17))\n                                            (Etempvar _j tuint) (tptr tuint))\n                                          tuint) (Etempvar _t'5 tuchar))))\n                                  (Sset _j\n                                    (Ebinop Oadd (Etempvar _j tuint)\n                                      (Econst_int (Int.repr 1) tint) tuint))))\n                              (Ssequence\n                                (Sassign\n                                  (Ederef\n                                    (Ebinop Oadd (Evar _c (tarray tuint 17))\n                                      (Econst_int (Int.repr 16) tint)\n                                      (tptr tuint)) tuint)\n                                  (Econst_int (Int.repr 0) tint))\n                                (Ssequence\n                                  (Scall None\n                                    (Evar _add1305 (Tfunction\n                                                     (Tcons (tptr tuint)\n                                                       (Tcons (tptr tuint)\n                                                         Tnil)) tvoid\n                                                     cc_default))\n                                    ((Evar _h (tarray tuint 17)) ::\n                                     (Evar _c (tarray tuint 17)) :: nil))\n                                  (Ssequence\n                                    (Ssequence\n                                      (Sset _j\n                                        (Econst_int (Int.repr 0) tint))\n                                      (Sloop\n                                        (Ssequence\n                                          (Sifthenelse (Ebinop Olt\n                                                         (Etempvar _j tuint)\n                                                         (Econst_int (Int.repr 16) tint)\n                                                         tint)\n                                            Sskip\n                                            Sbreak)\n                                          (Ssequence\n                                            (Sset _t'4\n                                              (Ederef\n                                                (Ebinop Oadd\n                                                  (Evar _h (tarray tuint 17))\n                                                  (Etempvar _j tuint)\n                                                  (tptr tuint)) tuint))\n                                            (Sassign\n                                              (Ederef\n                                                (Ebinop Oadd\n                                                  (Etempvar _out (tptr tuchar))\n                                                  (Etempvar _j tuint)\n                                                  (tptr tuchar)) tuchar)\n                                              (Etempvar _t'4 tuint))))\n                                        (Sset _j\n                                          (Ebinop Oadd (Etempvar _j tuint)\n                                            (Econst_int (Int.repr 1) tint)\n                                            tuint))))\n                                    (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))))))))))))))))\n|}.\n\nDefinition f_crypto_onetimeauth_poly1305_tweet_verify := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_h, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_n, tulong) ::\n                (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_x, (tarray tuchar 16)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_onetimeauth_poly1305_tweet (Tfunction\n                                               (Tcons (tptr tuchar)\n                                                 (Tcons (tptr tuchar)\n                                                   (Tcons tulong\n                                                     (Tcons (tptr tuchar)\n                                                       Tnil)))) tint\n                                               cc_default))\n    ((Evar _x (tarray tuchar 16)) :: (Etempvar _m (tptr tuchar)) ::\n     (Etempvar _n tulong) :: (Etempvar _k (tptr tuchar)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_verify_16_tweet (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons (tptr tuchar) Tnil)) tint\n                                      cc_default))\n      ((Etempvar _h (tptr tuchar)) :: (Evar _x (tarray tuchar 16)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_crypto_secretbox_xsalsa20poly1305_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Ebinop Olt (Etempvar _d tulong)\n                 (Econst_int (Int.repr 32) tint) tint)\n    (Sreturn (Some (Eunop Oneg (Econst_int (Int.repr 1) tint) tint)))\n    Sskip)\n  (Ssequence\n    (Scall None\n      (Evar _crypto_stream_xsalsa20_tweet_xor (Tfunction\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar)\n                                                    (Tcons tulong\n                                                      (Tcons (tptr tuchar)\n                                                        (Tcons (tptr tuchar)\n                                                          Tnil))))) tint\n                                                cc_default))\n      ((Etempvar _c (tptr tuchar)) :: (Etempvar _m (tptr tuchar)) ::\n       (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n       (Etempvar _k (tptr tuchar)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _crypto_onetimeauth_poly1305_tweet (Tfunction\n                                                   (Tcons (tptr tuchar)\n                                                     (Tcons (tptr tuchar)\n                                                       (Tcons tulong\n                                                         (Tcons (tptr tuchar)\n                                                           Tnil)))) tint\n                                                   cc_default))\n        ((Ebinop Oadd (Etempvar _c (tptr tuchar))\n           (Econst_int (Int.repr 16) tint) (tptr tuchar)) ::\n         (Ebinop Oadd (Etempvar _c (tptr tuchar))\n           (Econst_int (Int.repr 32) tint) (tptr tuchar)) ::\n         (Ebinop Osub (Etempvar _d tulong) (Econst_int (Int.repr 32) tint)\n           tulong) :: (Etempvar _c (tptr tuchar)) :: nil))\n      (Ssequence\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                             (Econst_int (Int.repr 16) tint) tint)\n                Sskip\n                Sbreak)\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _c (tptr tuchar)) (Etempvar _i tint)\n                    (tptr tuchar)) tuchar) (Econst_int (Int.repr 0) tint)))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint))))\n        (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))\n|}.\n\nDefinition f_crypto_secretbox_xsalsa20poly1305_tweet_open := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_m, (tptr tuchar)) :: (_c, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := ((_x, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_i, tint) :: (_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Ebinop Olt (Etempvar _d tulong)\n                 (Econst_int (Int.repr 32) tint) tint)\n    (Sreturn (Some (Eunop Oneg (Econst_int (Int.repr 1) tint) tint)))\n    Sskip)\n  (Ssequence\n    (Scall None\n      (Evar _crypto_stream_xsalsa20_tweet (Tfunction\n                                            (Tcons (tptr tuchar)\n                                              (Tcons tulong\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar) Tnil))))\n                                            tint cc_default))\n      ((Evar _x (tarray tuchar 32)) :: (Econst_int (Int.repr 32) tint) ::\n       (Etempvar _n (tptr tuchar)) :: (Etempvar _k (tptr tuchar)) :: nil))\n    (Ssequence\n      (Ssequence\n        (Scall (Some _t'1)\n          (Evar _crypto_onetimeauth_poly1305_tweet_verify (Tfunction\n                                                            (Tcons\n                                                              (tptr tuchar)\n                                                              (Tcons\n                                                                (tptr tuchar)\n                                                                (Tcons tulong\n                                                                  (Tcons\n                                                                    (tptr tuchar)\n                                                                    Tnil))))\n                                                            tint cc_default))\n          ((Ebinop Oadd (Etempvar _c (tptr tuchar))\n             (Econst_int (Int.repr 16) tint) (tptr tuchar)) ::\n           (Ebinop Oadd (Etempvar _c (tptr tuchar))\n             (Econst_int (Int.repr 32) tint) (tptr tuchar)) ::\n           (Ebinop Osub (Etempvar _d tulong) (Econst_int (Int.repr 32) tint)\n             tulong) :: (Evar _x (tarray tuchar 32)) :: nil))\n        (Sifthenelse (Ebinop One (Etempvar _t'1 tint)\n                       (Econst_int (Int.repr 0) tint) tint)\n          (Sreturn (Some (Eunop Oneg (Econst_int (Int.repr 1) tint) tint)))\n          Sskip))\n      (Ssequence\n        (Scall None\n          (Evar _crypto_stream_xsalsa20_tweet_xor (Tfunction\n                                                    (Tcons (tptr tuchar)\n                                                      (Tcons (tptr tuchar)\n                                                        (Tcons tulong\n                                                          (Tcons\n                                                            (tptr tuchar)\n                                                            (Tcons\n                                                              (tptr tuchar)\n                                                              Tnil))))) tint\n                                                    cc_default))\n          ((Etempvar _m (tptr tuchar)) :: (Etempvar _c (tptr tuchar)) ::\n           (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n           (Etempvar _k (tptr tuchar)) :: nil))\n        (Ssequence\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 32) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                      (Etempvar _i tint) (tptr tuchar)) tuchar)\n                  (Econst_int (Int.repr 0) tint)))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Sreturn (Some (Econst_int (Int.repr 0) tint))))))))\n|}.\n\nDefinition f_set25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_r, (tptr tlong)) :: (_a, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 16) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Sset _t'1\n          (Ederef\n            (Ebinop Oadd (Etempvar _a (tptr tlong)) (Etempvar _i tint)\n              (tptr tlong)) tlong))\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Etempvar _r (tptr tlong)) (Etempvar _i tint)\n              (tptr tlong)) tlong) (Etempvar _t'1 tlong))))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_car25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_c, tlong) :: (_t'4, tlong) :: (_t'3, tlong) ::\n               (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 16) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Ssequence\n          (Sset _t'4\n            (Ederef\n              (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong)\n            (Ebinop Oadd (Etempvar _t'4 tlong)\n              (Ebinop Oshl (Econst_long (Int64.repr 1) tlong)\n                (Econst_int (Int.repr 16) tint) tlong) tlong)))\n        (Ssequence\n          (Ssequence\n            (Sset _t'3\n              (Ederef\n                (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                  (tptr tlong)) tlong))\n            (Sset _c\n              (Ebinop Oshr (Etempvar _t'3 tlong)\n                (Econst_int (Int.repr 16) tint) tlong)))\n          (Ssequence\n            (Ssequence\n              (Sset _t'2\n                (Ederef\n                  (Ebinop Oadd (Etempvar _o (tptr tlong))\n                    (Ebinop Omul\n                      (Ebinop Oadd (Etempvar _i tint)\n                        (Econst_int (Int.repr 1) tint) tint)\n                      (Ebinop Olt (Etempvar _i tint)\n                        (Econst_int (Int.repr 15) tint) tint) tint)\n                    (tptr tlong)) tlong))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _o (tptr tlong))\n                    (Ebinop Omul\n                      (Ebinop Oadd (Etempvar _i tint)\n                        (Econst_int (Int.repr 1) tint) tint)\n                      (Ebinop Olt (Etempvar _i tint)\n                        (Econst_int (Int.repr 15) tint) tint) tint)\n                    (tptr tlong)) tlong)\n                (Ebinop Oadd (Etempvar _t'2 tlong)\n                  (Ebinop Oadd\n                    (Ebinop Osub (Etempvar _c tlong)\n                      (Econst_int (Int.repr 1) tint) tlong)\n                    (Ebinop Omul\n                      (Ebinop Omul (Econst_int (Int.repr 37) tint)\n                        (Ebinop Osub (Etempvar _c tlong)\n                          (Econst_int (Int.repr 1) tint) tlong) tlong)\n                      (Ebinop Oeq (Etempvar _i tint)\n                        (Econst_int (Int.repr 15) tint) tint) tlong) tlong)\n                  tlong)))\n            (Ssequence\n              (Sset _t'1\n                (Ederef\n                  (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                    (tptr tlong)) tlong))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                    (tptr tlong)) tlong)\n                (Ebinop Osub (Etempvar _t'1 tlong)\n                  (Ebinop Oshl (Etempvar _c tlong)\n                    (Econst_int (Int.repr 16) tint) tlong) tlong)))))))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_sel25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_p, (tptr tlong)) :: (_q, (tptr tlong)) :: (_b, tint) ::\n                nil);\n  fn_vars := nil;\n  fn_temps := ((_t, tlong) :: (_i, tlong) :: (_c, tlong) :: (_t'4, tlong) ::\n               (_t'3, tlong) :: (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _c\n    (Ecast\n      (Eunop Onotint\n        (Ebinop Osub (Etempvar _b tint) (Econst_int (Int.repr 1) tint) tint)\n        tint) tlong))\n  (Ssequence\n    (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                       (Econst_int (Int.repr 16) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Sset _t'3\n              (Ederef\n                (Ebinop Oadd (Etempvar _p (tptr tlong)) (Etempvar _i tlong)\n                  (tptr tlong)) tlong))\n            (Ssequence\n              (Sset _t'4\n                (Ederef\n                  (Ebinop Oadd (Etempvar _q (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong))\n              (Sset _t\n                (Ebinop Oand (Etempvar _c tlong)\n                  (Ebinop Oxor (Etempvar _t'3 tlong) (Etempvar _t'4 tlong)\n                    tlong) tlong))))\n          (Ssequence\n            (Ssequence\n              (Sset _t'2\n                (Ederef\n                  (Ebinop Oadd (Etempvar _p (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _p (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong)\n                (Ebinop Oxor (Etempvar _t'2 tlong) (Etempvar _t tlong) tlong)))\n            (Ssequence\n              (Sset _t'1\n                (Ederef\n                  (Ebinop Oadd (Etempvar _q (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _q (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong)\n                (Ebinop Oxor (Etempvar _t'1 tlong) (Etempvar _t tlong) tlong))))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n          tlong)))))\n|}.\n\nDefinition f_pack25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tuchar)) :: (_n, (tptr tlong)) :: nil);\n  fn_vars := ((_m, (tarray tlong 16)) :: (_t, (tarray tlong 16)) :: nil);\n  fn_temps := ((_i, tint) :: (_j, tint) :: (_b, tint) :: (_t'11, tlong) ::\n               (_t'10, tlong) :: (_t'9, tlong) :: (_t'8, tlong) ::\n               (_t'7, tlong) :: (_t'6, tlong) :: (_t'5, tlong) ::\n               (_t'4, tlong) :: (_t'3, tlong) :: (_t'2, tlong) ::\n               (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                       (Econst_int (Int.repr 16) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'11\n            (Ederef\n              (Ebinop Oadd (Etempvar _n (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _t (tarray tlong 16)) (Etempvar _i tint)\n                (tptr tlong)) tlong) (Etempvar _t'11 tlong))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Scall None\n      (Evar _car25519 (Tfunction (Tcons (tptr tlong) Tnil) tvoid cc_default))\n      ((Evar _t (tarray tlong 16)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _car25519 (Tfunction (Tcons (tptr tlong) Tnil) tvoid\n                          cc_default)) ((Evar _t (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _car25519 (Tfunction (Tcons (tptr tlong) Tnil) tvoid\n                            cc_default))\n          ((Evar _t (tarray tlong 16)) :: nil))\n        (Ssequence\n          (Ssequence\n            (Sset _j (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _j tint)\n                               (Econst_int (Int.repr 2) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Ssequence\n                    (Sset _t'10\n                      (Ederef\n                        (Ebinop Oadd (Evar _t (tarray tlong 16))\n                          (Econst_int (Int.repr 0) tint) (tptr tlong)) tlong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _m (tarray tlong 16))\n                          (Econst_int (Int.repr 0) tint) (tptr tlong)) tlong)\n                      (Ebinop Osub (Etempvar _t'10 tlong)\n                        (Econst_int (Int.repr 65517) tint) tlong)))\n                  (Ssequence\n                    (Ssequence\n                      (Sset _i (Econst_int (Int.repr 1) tint))\n                      (Sloop\n                        (Ssequence\n                          (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                         (Econst_int (Int.repr 15) tint)\n                                         tint)\n                            Sskip\n                            Sbreak)\n                          (Ssequence\n                            (Ssequence\n                              (Sset _t'8\n                                (Ederef\n                                  (Ebinop Oadd (Evar _t (tarray tlong 16))\n                                    (Etempvar _i tint) (tptr tlong)) tlong))\n                              (Ssequence\n                                (Sset _t'9\n                                  (Ederef\n                                    (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                      (Ebinop Osub (Etempvar _i tint)\n                                        (Econst_int (Int.repr 1) tint) tint)\n                                      (tptr tlong)) tlong))\n                                (Sassign\n                                  (Ederef\n                                    (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                      (Etempvar _i tint) (tptr tlong)) tlong)\n                                  (Ebinop Osub\n                                    (Ebinop Osub (Etempvar _t'8 tlong)\n                                      (Econst_int (Int.repr 65535) tint)\n                                      tlong)\n                                    (Ebinop Oand\n                                      (Ebinop Oshr (Etempvar _t'9 tlong)\n                                        (Econst_int (Int.repr 16) tint)\n                                        tlong) (Econst_int (Int.repr 1) tint)\n                                      tlong) tlong))))\n                            (Ssequence\n                              (Sset _t'7\n                                (Ederef\n                                  (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                    (Ebinop Osub (Etempvar _i tint)\n                                      (Econst_int (Int.repr 1) tint) tint)\n                                    (tptr tlong)) tlong))\n                              (Sassign\n                                (Ederef\n                                  (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                    (Ebinop Osub (Etempvar _i tint)\n                                      (Econst_int (Int.repr 1) tint) tint)\n                                    (tptr tlong)) tlong)\n                                (Ebinop Oand (Etempvar _t'7 tlong)\n                                  (Econst_int (Int.repr 65535) tint) tlong)))))\n                        (Sset _i\n                          (Ebinop Oadd (Etempvar _i tint)\n                            (Econst_int (Int.repr 1) tint) tint))))\n                    (Ssequence\n                      (Ssequence\n                        (Sset _t'5\n                          (Ederef\n                            (Ebinop Oadd (Evar _t (tarray tlong 16))\n                              (Econst_int (Int.repr 15) tint) (tptr tlong))\n                            tlong))\n                        (Ssequence\n                          (Sset _t'6\n                            (Ederef\n                              (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                (Econst_int (Int.repr 14) tint) (tptr tlong))\n                              tlong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                (Econst_int (Int.repr 15) tint) (tptr tlong))\n                              tlong)\n                            (Ebinop Osub\n                              (Ebinop Osub (Etempvar _t'5 tlong)\n                                (Econst_int (Int.repr 32767) tint) tlong)\n                              (Ebinop Oand\n                                (Ebinop Oshr (Etempvar _t'6 tlong)\n                                  (Econst_int (Int.repr 16) tint) tlong)\n                                (Econst_int (Int.repr 1) tint) tlong) tlong))))\n                      (Ssequence\n                        (Ssequence\n                          (Sset _t'4\n                            (Ederef\n                              (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                (Econst_int (Int.repr 15) tint) (tptr tlong))\n                              tlong))\n                          (Sset _b\n                            (Ecast\n                              (Ebinop Oand\n                                (Ebinop Oshr (Etempvar _t'4 tlong)\n                                  (Econst_int (Int.repr 16) tint) tlong)\n                                (Econst_int (Int.repr 1) tint) tlong) tint)))\n                        (Ssequence\n                          (Ssequence\n                            (Sset _t'3\n                              (Ederef\n                                (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                  (Econst_int (Int.repr 14) tint)\n                                  (tptr tlong)) tlong))\n                            (Sassign\n                              (Ederef\n                                (Ebinop Oadd (Evar _m (tarray tlong 16))\n                                  (Econst_int (Int.repr 14) tint)\n                                  (tptr tlong)) tlong)\n                              (Ebinop Oand (Etempvar _t'3 tlong)\n                                (Econst_int (Int.repr 65535) tint) tlong)))\n                          (Scall None\n                            (Evar _sel25519 (Tfunction\n                                              (Tcons (tptr tlong)\n                                                (Tcons (tptr tlong)\n                                                  (Tcons tint Tnil))) tvoid\n                                              cc_default))\n                            ((Evar _t (tarray tlong 16)) ::\n                             (Evar _m (tarray tlong 16)) ::\n                             (Ebinop Osub (Econst_int (Int.repr 1) tint)\n                               (Etempvar _b tint) tint) :: nil))))))))\n              (Sset _j\n                (Ebinop Oadd (Etempvar _j tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 16) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Ssequence\n                    (Sset _t'2\n                      (Ederef\n                        (Ebinop Oadd (Evar _t (tarray tlong 16))\n                          (Etempvar _i tint) (tptr tlong)) tlong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _o (tptr tuchar))\n                          (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                            (Etempvar _i tint) tint) (tptr tuchar)) tuchar)\n                      (Ebinop Oand (Etempvar _t'2 tlong)\n                        (Econst_int (Int.repr 255) tint) tlong)))\n                  (Ssequence\n                    (Sset _t'1\n                      (Ederef\n                        (Ebinop Oadd (Evar _t (tarray tlong 16))\n                          (Etempvar _i tint) (tptr tlong)) tlong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _o (tptr tuchar))\n                          (Ebinop Oadd\n                            (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                              (Etempvar _i tint) tint)\n                            (Econst_int (Int.repr 1) tint) tint)\n                          (tptr tuchar)) tuchar)\n                      (Ebinop Oshr (Etempvar _t'1 tlong)\n                        (Econst_int (Int.repr 8) tint) tlong)))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint)))))))))\n|}.\n\nDefinition f_neq25519 := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_a, (tptr tlong)) :: (_b, (tptr tlong)) :: nil);\n  fn_vars := ((_c, (tarray tuchar 32)) :: (_d, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _pack25519 (Tfunction\n                       (Tcons (tptr tuchar) (Tcons (tptr tlong) Tnil)) tvoid\n                       cc_default))\n    ((Evar _c (tarray tuchar 32)) :: (Etempvar _a (tptr tlong)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _pack25519 (Tfunction\n                         (Tcons (tptr tuchar) (Tcons (tptr tlong) Tnil))\n                         tvoid cc_default))\n      ((Evar _d (tarray tuchar 32)) :: (Etempvar _b (tptr tlong)) :: nil))\n    (Ssequence\n      (Scall (Some _t'1)\n        (Evar _crypto_verify_32_tweet (Tfunction\n                                        (Tcons (tptr tuchar)\n                                          (Tcons (tptr tuchar) Tnil)) tint\n                                        cc_default))\n        ((Evar _c (tarray tuchar 32)) :: (Evar _d (tarray tuchar 32)) :: nil))\n      (Sreturn (Some (Etempvar _t'1 tint))))))\n|}.\n\nDefinition f_par25519 := {|\n  fn_return := tuchar;\n  fn_callconv := cc_default;\n  fn_params := ((_a, (tptr tlong)) :: nil);\n  fn_vars := ((_d, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _pack25519 (Tfunction\n                       (Tcons (tptr tuchar) (Tcons (tptr tlong) Tnil)) tvoid\n                       cc_default))\n    ((Evar _d (tarray tuchar 32)) :: (Etempvar _a (tptr tlong)) :: nil))\n  (Ssequence\n    (Sset _t'1\n      (Ederef\n        (Ebinop Oadd (Evar _d (tarray tuchar 32))\n          (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar))\n    (Sreturn (Some (Ebinop Oand (Etempvar _t'1 tuchar)\n                     (Econst_int (Int.repr 1) tint) tint)))))\n|}.\n\nDefinition f_unpack25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_n, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_t'3, tuchar) :: (_t'2, tuchar) ::\n               (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                       (Econst_int (Int.repr 16) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'2\n            (Ederef\n              (Ebinop Oadd (Etempvar _n (tptr tuchar))\n                (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                  (Etempvar _i tint) tint) (tptr tuchar)) tuchar))\n          (Ssequence\n            (Sset _t'3\n              (Ederef\n                (Ebinop Oadd (Etempvar _n (tptr tuchar))\n                  (Ebinop Oadd\n                    (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                      (Etempvar _i tint) tint) (Econst_int (Int.repr 1) tint)\n                    tint) (tptr tuchar)) tuchar))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                  (tptr tlong)) tlong)\n              (Ebinop Oadd (Etempvar _t'2 tuchar)\n                (Ebinop Oshl (Ecast (Etempvar _t'3 tuchar) tlong)\n                  (Econst_int (Int.repr 8) tint) tlong) tlong)))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Sset _t'1\n      (Ederef\n        (Ebinop Oadd (Etempvar _o (tptr tlong))\n          (Econst_int (Int.repr 15) tint) (tptr tlong)) tlong))\n    (Sassign\n      (Ederef\n        (Ebinop Oadd (Etempvar _o (tptr tlong))\n          (Econst_int (Int.repr 15) tint) (tptr tlong)) tlong)\n      (Ebinop Oand (Etempvar _t'1 tlong) (Econst_int (Int.repr 32767) tint)\n        tlong))))\n|}.\n\nDefinition f_A := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_a, (tptr tlong)) ::\n                (_b, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 16) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Sset _t'1\n          (Ederef\n            (Ebinop Oadd (Etempvar _a (tptr tlong)) (Etempvar _i tint)\n              (tptr tlong)) tlong))\n        (Ssequence\n          (Sset _t'2\n            (Ederef\n              (Ebinop Oadd (Etempvar _b (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong)\n            (Ebinop Oadd (Etempvar _t'1 tlong) (Etempvar _t'2 tlong) tlong)))))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_Z := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_a, (tptr tlong)) ::\n                (_b, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 16) tint) tint)\n        Sskip\n        Sbreak)\n      (Ssequence\n        (Sset _t'1\n          (Ederef\n            (Ebinop Oadd (Etempvar _a (tptr tlong)) (Etempvar _i tint)\n              (tptr tlong)) tlong))\n        (Ssequence\n          (Sset _t'2\n            (Ederef\n              (Ebinop Oadd (Etempvar _b (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _i tint)\n                (tptr tlong)) tlong)\n            (Ebinop Osub (Etempvar _t'1 tlong) (Etempvar _t'2 tlong) tlong)))))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_M := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_a, (tptr tlong)) ::\n                (_b, (tptr tlong)) :: nil);\n  fn_vars := ((_t, (tarray tlong 31)) :: nil);\n  fn_temps := ((_i, tlong) :: (_j, tlong) :: (_t'6, tlong) ::\n               (_t'5, tlong) :: (_t'4, tlong) :: (_t'3, tlong) ::\n               (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                       (Econst_int (Int.repr 31) tint) tint)\n          Sskip\n          Sbreak)\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Evar _t (tarray tlong 31)) (Etempvar _i tlong)\n              (tptr tlong)) tlong) (Econst_int (Int.repr 0) tint)))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n          tlong))))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _j (Ecast (Econst_int (Int.repr 0) tint) tlong))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _j tlong)\n                               (Econst_int (Int.repr 16) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Sset _t'4\n                    (Ederef\n                      (Ebinop Oadd (Evar _t (tarray tlong 31))\n                        (Ebinop Oadd (Etempvar _i tlong) (Etempvar _j tlong)\n                          tlong) (tptr tlong)) tlong))\n                  (Ssequence\n                    (Sset _t'5\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _a (tptr tlong))\n                          (Etempvar _i tlong) (tptr tlong)) tlong))\n                    (Ssequence\n                      (Sset _t'6\n                        (Ederef\n                          (Ebinop Oadd (Etempvar _b (tptr tlong))\n                            (Etempvar _j tlong) (tptr tlong)) tlong))\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tlong 31))\n                            (Ebinop Oadd (Etempvar _i tlong)\n                              (Etempvar _j tlong) tlong) (tptr tlong)) tlong)\n                        (Ebinop Oadd (Etempvar _t'4 tlong)\n                          (Ebinop Omul (Etempvar _t'5 tlong)\n                            (Etempvar _t'6 tlong) tlong) tlong))))))\n              (Sset _j\n                (Ebinop Oadd (Etempvar _j tlong)\n                  (Econst_int (Int.repr 1) tint) tlong)))))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n            tlong))))\n    (Ssequence\n      (Ssequence\n        (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                           (Econst_int (Int.repr 15) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Sset _t'2\n                (Ederef\n                  (Ebinop Oadd (Evar _t (tarray tlong 31))\n                    (Etempvar _i tlong) (tptr tlong)) tlong))\n              (Ssequence\n                (Sset _t'3\n                  (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tlong 31))\n                      (Ebinop Oadd (Etempvar _i tlong)\n                        (Econst_int (Int.repr 16) tint) tlong) (tptr tlong))\n                    tlong))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tlong 31))\n                      (Etempvar _i tlong) (tptr tlong)) tlong)\n                  (Ebinop Oadd (Etempvar _t'2 tlong)\n                    (Ebinop Omul (Econst_int (Int.repr 38) tint)\n                      (Etempvar _t'3 tlong) tlong) tlong)))))\n          (Sset _i\n            (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n              tlong))))\n      (Ssequence\n        (Ssequence\n          (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                             (Econst_int (Int.repr 16) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'1\n                  (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tlong 31))\n                      (Etempvar _i tlong) (tptr tlong)) tlong))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _o (tptr tlong))\n                      (Etempvar _i tlong) (tptr tlong)) tlong)\n                  (Etempvar _t'1 tlong))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n                tlong))))\n        (Ssequence\n          (Scall None\n            (Evar _car25519 (Tfunction (Tcons (tptr tlong) Tnil) tvoid\n                              cc_default))\n            ((Etempvar _o (tptr tlong)) :: nil))\n          (Scall None\n            (Evar _car25519 (Tfunction (Tcons (tptr tlong) Tnil) tvoid\n                              cc_default))\n            ((Etempvar _o (tptr tlong)) :: nil)))))))\n|}.\n\nDefinition f_S := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_a, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None\n  (Evar _M (Tfunction\n             (Tcons (tptr tlong)\n               (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n             cc_default))\n  ((Etempvar _o (tptr tlong)) :: (Etempvar _a (tptr tlong)) ::\n   (Etempvar _a (tptr tlong)) :: nil))\n|}.\n\nDefinition f_inv25519 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_i, (tptr tlong)) :: nil);\n  fn_vars := ((_c, (tarray tlong 16)) :: nil);\n  fn_temps := ((_a, tint) :: (_t'1, tint) :: (_t'3, tlong) ::\n               (_t'2, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _a (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _a tint)\n                       (Econst_int (Int.repr 16) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'3\n            (Ederef\n              (Ebinop Oadd (Etempvar _i (tptr tlong)) (Etempvar _a tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _c (tarray tlong 16)) (Etempvar _a tint)\n                (tptr tlong)) tlong) (Etempvar _t'3 tlong))))\n      (Sset _a\n        (Ebinop Oadd (Etempvar _a tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Ssequence\n      (Sset _a (Econst_int (Int.repr 253) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Oge (Etempvar _a tint)\n                         (Econst_int (Int.repr 0) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Scall None\n              (Evar _S (Tfunction\n                         (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)) tvoid\n                         cc_default))\n              ((Evar _c (tarray tlong 16)) :: (Evar _c (tarray tlong 16)) ::\n               nil))\n            (Ssequence\n              (Sifthenelse (Ebinop One (Etempvar _a tint)\n                             (Econst_int (Int.repr 2) tint) tint)\n                (Sset _t'1\n                  (Ecast\n                    (Ebinop One (Etempvar _a tint)\n                      (Econst_int (Int.repr 4) tint) tint) tbool))\n                (Sset _t'1 (Econst_int (Int.repr 0) tint)))\n              (Sifthenelse (Etempvar _t'1 tint)\n                (Scall None\n                  (Evar _M (Tfunction\n                             (Tcons (tptr tlong)\n                               (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                             tvoid cc_default))\n                  ((Evar _c (tarray tlong 16)) ::\n                   (Evar _c (tarray tlong 16)) ::\n                   (Etempvar _i (tptr tlong)) :: nil))\n                Sskip))))\n        (Sset _a\n          (Ebinop Osub (Etempvar _a tint) (Econst_int (Int.repr 1) tint)\n            tint))))\n    (Ssequence\n      (Sset _a (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _a tint)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'2\n              (Ederef\n                (Ebinop Oadd (Evar _c (tarray tlong 16)) (Etempvar _a tint)\n                  (tptr tlong)) tlong))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _a tint)\n                  (tptr tlong)) tlong) (Etempvar _t'2 tlong))))\n        (Sset _a\n          (Ebinop Oadd (Etempvar _a tint) (Econst_int (Int.repr 1) tint)\n            tint))))))\n|}.\n\nDefinition f_pow2523 := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_o, (tptr tlong)) :: (_i, (tptr tlong)) :: nil);\n  fn_vars := ((_c, (tarray tlong 16)) :: nil);\n  fn_temps := ((_a, tint) :: (_t'2, tlong) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _a (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _a tint)\n                       (Econst_int (Int.repr 16) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'2\n            (Ederef\n              (Ebinop Oadd (Etempvar _i (tptr tlong)) (Etempvar _a tint)\n                (tptr tlong)) tlong))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _c (tarray tlong 16)) (Etempvar _a tint)\n                (tptr tlong)) tlong) (Etempvar _t'2 tlong))))\n      (Sset _a\n        (Ebinop Oadd (Etempvar _a tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Ssequence\n      (Sset _a (Econst_int (Int.repr 250) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Oge (Etempvar _a tint)\n                         (Econst_int (Int.repr 0) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Scall None\n              (Evar _S (Tfunction\n                         (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)) tvoid\n                         cc_default))\n              ((Evar _c (tarray tlong 16)) :: (Evar _c (tarray tlong 16)) ::\n               nil))\n            (Sifthenelse (Ebinop One (Etempvar _a tint)\n                           (Econst_int (Int.repr 1) tint) tint)\n              (Scall None\n                (Evar _M (Tfunction\n                           (Tcons (tptr tlong)\n                             (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                           tvoid cc_default))\n                ((Evar _c (tarray tlong 16)) ::\n                 (Evar _c (tarray tlong 16)) :: (Etempvar _i (tptr tlong)) ::\n                 nil))\n              Sskip)))\n        (Sset _a\n          (Ebinop Osub (Etempvar _a tint) (Econst_int (Int.repr 1) tint)\n            tint))))\n    (Ssequence\n      (Sset _a (Econst_int (Int.repr 0) tint))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _a tint)\n                         (Econst_int (Int.repr 16) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'1\n              (Ederef\n                (Ebinop Oadd (Evar _c (tarray tlong 16)) (Etempvar _a tint)\n                  (tptr tlong)) tlong))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Etempvar _o (tptr tlong)) (Etempvar _a tint)\n                  (tptr tlong)) tlong) (Etempvar _t'1 tlong))))\n        (Sset _a\n          (Ebinop Oadd (Etempvar _a tint) (Econst_int (Int.repr 1) tint)\n            tint))))))\n|}.\n\nDefinition f_crypto_scalarmult_curve25519_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_q, (tptr tuchar)) :: (_n, (tptr tuchar)) ::\n                (_p, (tptr tuchar)) :: nil);\n  fn_vars := ((_z, (tarray tuchar 32)) :: (_x, (tarray tlong 80)) ::\n              (_a, (tarray tlong 16)) :: (_b, (tarray tlong 16)) ::\n              (_c, (tarray tlong 16)) :: (_d, (tarray tlong 16)) ::\n              (_e, (tarray tlong 16)) :: (_f, (tarray tlong 16)) :: nil);\n  fn_temps := ((_r, tlong) :: (_i, tlong) :: (_t'3, tlong) ::\n               (_t'2, tlong) :: (_t'1, tlong) :: (_t'12, tuchar) ::\n               (_t'11, tuchar) :: (_t'10, tuchar) :: (_t'9, tlong) ::\n               (_t'8, tuchar) :: (_t'7, tlong) :: (_t'6, tlong) ::\n               (_t'5, tlong) :: (_t'4, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                       (Econst_int (Int.repr 31) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'12\n            (Ederef\n              (Ebinop Oadd (Etempvar _n (tptr tuchar)) (Etempvar _i tlong)\n                (tptr tuchar)) tuchar))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _z (tarray tuchar 32)) (Etempvar _i tlong)\n                (tptr tuchar)) tuchar) (Etempvar _t'12 tuchar))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n          tlong))))\n  (Ssequence\n    (Ssequence\n      (Sset _t'11\n        (Ederef\n          (Ebinop Oadd (Etempvar _n (tptr tuchar))\n            (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n      (Sassign\n        (Ederef\n          (Ebinop Oadd (Evar _z (tarray tuchar 32))\n            (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n        (Ebinop Oor\n          (Ebinop Oand (Etempvar _t'11 tuchar)\n            (Econst_int (Int.repr 127) tint) tint)\n          (Econst_int (Int.repr 64) tint) tint)))\n    (Ssequence\n      (Ssequence\n        (Sset _t'10\n          (Ederef\n            (Ebinop Oadd (Evar _z (tarray tuchar 32))\n              (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar))\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Evar _z (tarray tuchar 32))\n              (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar)\n          (Ebinop Oand (Etempvar _t'10 tuchar)\n            (Econst_int (Int.repr 248) tint) tint)))\n      (Ssequence\n        (Scall None\n          (Evar _unpack25519 (Tfunction\n                               (Tcons (tptr tlong)\n                                 (Tcons (tptr tuchar) Tnil)) tvoid\n                               cc_default))\n          ((Evar _x (tarray tlong 80)) :: (Etempvar _p (tptr tuchar)) :: nil))\n        (Ssequence\n          (Ssequence\n            (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                               (Econst_int (Int.repr 16) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Ssequence\n                    (Sset _t'9\n                      (Ederef\n                        (Ebinop Oadd (Evar _x (tarray tlong 80))\n                          (Etempvar _i tlong) (tptr tlong)) tlong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _b (tarray tlong 16))\n                          (Etempvar _i tlong) (tptr tlong)) tlong)\n                      (Etempvar _t'9 tlong)))\n                  (Ssequence\n                    (Ssequence\n                      (Ssequence\n                        (Ssequence\n                          (Sset _t'1\n                            (Ecast (Econst_int (Int.repr 0) tint) tlong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Evar _c (tarray tlong 16))\n                                (Etempvar _i tlong) (tptr tlong)) tlong)\n                            (Etempvar _t'1 tlong)))\n                        (Sset _t'2 (Ecast (Etempvar _t'1 tlong) tlong)))\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Evar _a (tarray tlong 16))\n                            (Etempvar _i tlong) (tptr tlong)) tlong)\n                        (Etempvar _t'2 tlong)))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _d (tarray tlong 16))\n                          (Etempvar _i tlong) (tptr tlong)) tlong)\n                      (Etempvar _t'2 tlong)))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tlong)\n                  (Econst_int (Int.repr 1) tint) tlong))))\n          (Ssequence\n            (Ssequence\n              (Ssequence\n                (Sset _t'3 (Ecast (Econst_int (Int.repr 1) tint) tlong))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _d (tarray tlong 16))\n                      (Econst_int (Int.repr 0) tint) (tptr tlong)) tlong)\n                  (Etempvar _t'3 tlong)))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Evar _a (tarray tlong 16))\n                    (Econst_int (Int.repr 0) tint) (tptr tlong)) tlong)\n                (Etempvar _t'3 tlong)))\n            (Ssequence\n              (Ssequence\n                (Sset _i (Ecast (Econst_int (Int.repr 254) tint) tlong))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Oge (Etempvar _i tlong)\n                                   (Econst_int (Int.repr 0) tint) tint)\n                      Sskip\n                      Sbreak)\n                    (Ssequence\n                      (Ssequence\n                        (Sset _t'8\n                          (Ederef\n                            (Ebinop Oadd (Evar _z (tarray tuchar 32))\n                              (Ebinop Oshr (Etempvar _i tlong)\n                                (Econst_int (Int.repr 3) tint) tlong)\n                              (tptr tuchar)) tuchar))\n                        (Sset _r\n                          (Ecast\n                            (Ebinop Oand\n                              (Ebinop Oshr (Etempvar _t'8 tuchar)\n                                (Ebinop Oand (Etempvar _i tlong)\n                                  (Econst_int (Int.repr 7) tint) tlong) tint)\n                              (Econst_int (Int.repr 1) tint) tint) tlong)))\n                      (Ssequence\n                        (Scall None\n                          (Evar _sel25519 (Tfunction\n                                            (Tcons (tptr tlong)\n                                              (Tcons (tptr tlong)\n                                                (Tcons tint Tnil))) tvoid\n                                            cc_default))\n                          ((Evar _a (tarray tlong 16)) ::\n                           (Evar _b (tarray tlong 16)) ::\n                           (Etempvar _r tlong) :: nil))\n                        (Ssequence\n                          (Scall None\n                            (Evar _sel25519 (Tfunction\n                                              (Tcons (tptr tlong)\n                                                (Tcons (tptr tlong)\n                                                  (Tcons tint Tnil))) tvoid\n                                              cc_default))\n                            ((Evar _c (tarray tlong 16)) ::\n                             (Evar _d (tarray tlong 16)) ::\n                             (Etempvar _r tlong) :: nil))\n                          (Ssequence\n                            (Scall None\n                              (Evar _A (Tfunction\n                                         (Tcons (tptr tlong)\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong) Tnil)))\n                                         tvoid cc_default))\n                              ((Evar _e (tarray tlong 16)) ::\n                               (Evar _a (tarray tlong 16)) ::\n                               (Evar _c (tarray tlong 16)) :: nil))\n                            (Ssequence\n                              (Scall None\n                                (Evar _Z (Tfunction\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong) Tnil)))\n                                           tvoid cc_default))\n                                ((Evar _a (tarray tlong 16)) ::\n                                 (Evar _a (tarray tlong 16)) ::\n                                 (Evar _c (tarray tlong 16)) :: nil))\n                              (Ssequence\n                                (Scall None\n                                  (Evar _A (Tfunction\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong) Tnil)))\n                                             tvoid cc_default))\n                                  ((Evar _c (tarray tlong 16)) ::\n                                   (Evar _b (tarray tlong 16)) ::\n                                   (Evar _d (tarray tlong 16)) :: nil))\n                                (Ssequence\n                                  (Scall None\n                                    (Evar _Z (Tfunction\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong)\n                                                   (Tcons (tptr tlong) Tnil)))\n                                               tvoid cc_default))\n                                    ((Evar _b (tarray tlong 16)) ::\n                                     (Evar _b (tarray tlong 16)) ::\n                                     (Evar _d (tarray tlong 16)) :: nil))\n                                  (Ssequence\n                                    (Scall None\n                                      (Evar _S (Tfunction\n                                                 (Tcons (tptr tlong)\n                                                   (Tcons (tptr tlong) Tnil))\n                                                 tvoid cc_default))\n                                      ((Evar _d (tarray tlong 16)) ::\n                                       (Evar _e (tarray tlong 16)) :: nil))\n                                    (Ssequence\n                                      (Scall None\n                                        (Evar _S (Tfunction\n                                                   (Tcons (tptr tlong)\n                                                     (Tcons (tptr tlong)\n                                                       Tnil)) tvoid\n                                                   cc_default))\n                                        ((Evar _f (tarray tlong 16)) ::\n                                         (Evar _a (tarray tlong 16)) :: nil))\n                                      (Ssequence\n                                        (Scall None\n                                          (Evar _M (Tfunction\n                                                     (Tcons (tptr tlong)\n                                                       (Tcons (tptr tlong)\n                                                         (Tcons (tptr tlong)\n                                                           Tnil))) tvoid\n                                                     cc_default))\n                                          ((Evar _a (tarray tlong 16)) ::\n                                           (Evar _c (tarray tlong 16)) ::\n                                           (Evar _a (tarray tlong 16)) ::\n                                           nil))\n                                        (Ssequence\n                                          (Scall None\n                                            (Evar _M (Tfunction\n                                                       (Tcons (tptr tlong)\n                                                         (Tcons (tptr tlong)\n                                                           (Tcons\n                                                             (tptr tlong)\n                                                             Tnil))) tvoid\n                                                       cc_default))\n                                            ((Evar _c (tarray tlong 16)) ::\n                                             (Evar _b (tarray tlong 16)) ::\n                                             (Evar _e (tarray tlong 16)) ::\n                                             nil))\n                                          (Ssequence\n                                            (Scall None\n                                              (Evar _A (Tfunction\n                                                         (Tcons (tptr tlong)\n                                                           (Tcons\n                                                             (tptr tlong)\n                                                             (Tcons\n                                                               (tptr tlong)\n                                                               Tnil))) tvoid\n                                                         cc_default))\n                                              ((Evar _e (tarray tlong 16)) ::\n                                               (Evar _a (tarray tlong 16)) ::\n                                               (Evar _c (tarray tlong 16)) ::\n                                               nil))\n                                            (Ssequence\n                                              (Scall None\n                                                (Evar _Z (Tfunction\n                                                           (Tcons\n                                                             (tptr tlong)\n                                                             (Tcons\n                                                               (tptr tlong)\n                                                               (Tcons\n                                                                 (tptr tlong)\n                                                                 Tnil)))\n                                                           tvoid cc_default))\n                                                ((Evar _a (tarray tlong 16)) ::\n                                                 (Evar _a (tarray tlong 16)) ::\n                                                 (Evar _c (tarray tlong 16)) ::\n                                                 nil))\n                                              (Ssequence\n                                                (Scall None\n                                                  (Evar _S (Tfunction\n                                                             (Tcons\n                                                               (tptr tlong)\n                                                               (Tcons\n                                                                 (tptr tlong)\n                                                                 Tnil)) tvoid\n                                                             cc_default))\n                                                  ((Evar _b (tarray tlong 16)) ::\n                                                   (Evar _a (tarray tlong 16)) ::\n                                                   nil))\n                                                (Ssequence\n                                                  (Scall None\n                                                    (Evar _Z (Tfunction\n                                                               (Tcons\n                                                                 (tptr tlong)\n                                                                 (Tcons\n                                                                   (tptr tlong)\n                                                                   (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                               tvoid\n                                                               cc_default))\n                                                    ((Evar _c (tarray tlong 16)) ::\n                                                     (Evar _d (tarray tlong 16)) ::\n                                                     (Evar _f (tarray tlong 16)) ::\n                                                     nil))\n                                                  (Ssequence\n                                                    (Scall None\n                                                      (Evar _M (Tfunction\n                                                                 (Tcons\n                                                                   (tptr tlong)\n                                                                   (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                                 tvoid\n                                                                 cc_default))\n                                                      ((Evar _a (tarray tlong 16)) ::\n                                                       (Evar _c (tarray tlong 16)) ::\n                                                       (Evar __121665 (tarray tlong 16)) ::\n                                                       nil))\n                                                    (Ssequence\n                                                      (Scall None\n                                                        (Evar _A (Tfunction\n                                                                   (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                                   tvoid\n                                                                   cc_default))\n                                                        ((Evar _a (tarray tlong 16)) ::\n                                                         (Evar _a (tarray tlong 16)) ::\n                                                         (Evar _d (tarray tlong 16)) ::\n                                                         nil))\n                                                      (Ssequence\n                                                        (Scall None\n                                                          (Evar _M (Tfunction\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                                    tvoid\n                                                                    cc_default))\n                                                          ((Evar _c (tarray tlong 16)) ::\n                                                           (Evar _c (tarray tlong 16)) ::\n                                                           (Evar _a (tarray tlong 16)) ::\n                                                           nil))\n                                                        (Ssequence\n                                                          (Scall None\n                                                            (Evar _M \n                                                            (Tfunction\n                                                              (Tcons\n                                                                (tptr tlong)\n                                                                (Tcons\n                                                                  (tptr tlong)\n                                                                  (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                              tvoid\n                                                              cc_default))\n                                                            ((Evar _a (tarray tlong 16)) ::\n                                                             (Evar _d (tarray tlong 16)) ::\n                                                             (Evar _f (tarray tlong 16)) ::\n                                                             nil))\n                                                          (Ssequence\n                                                            (Scall None\n                                                              (Evar _M \n                                                              (Tfunction\n                                                                (Tcons\n                                                                  (tptr tlong)\n                                                                  (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                                tvoid\n                                                                cc_default))\n                                                              ((Evar _d (tarray tlong 16)) ::\n                                                               (Evar _b (tarray tlong 16)) ::\n                                                               (Evar _x (tarray tlong 80)) ::\n                                                               nil))\n                                                            (Ssequence\n                                                              (Scall None\n                                                                (Evar _S \n                                                                (Tfunction\n                                                                  (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil))\n                                                                  tvoid\n                                                                  cc_default))\n                                                                ((Evar _b (tarray tlong 16)) ::\n                                                                 (Evar _e (tarray tlong 16)) ::\n                                                                 nil))\n                                                              (Ssequence\n                                                                (Scall None\n                                                                  (Evar _sel25519 \n                                                                  (Tfunction\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    tint\n                                                                    Tnil)))\n                                                                    tvoid\n                                                                    cc_default))\n                                                                  ((Evar _a (tarray tlong 16)) ::\n                                                                   (Evar _b (tarray tlong 16)) ::\n                                                                   (Etempvar _r tlong) ::\n                                                                   nil))\n                                                                (Scall None\n                                                                  (Evar _sel25519 \n                                                                  (Tfunction\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    tint\n                                                                    Tnil)))\n                                                                    tvoid\n                                                                    cc_default))\n                                                                  ((Evar _c (tarray tlong 16)) ::\n                                                                   (Evar _d (tarray tlong 16)) ::\n                                                                   (Etempvar _r tlong) ::\n                                                                   nil)))))))))))))))))))))))))\n                  (Sset _i\n                    (Ebinop Osub (Etempvar _i tlong)\n                      (Econst_int (Int.repr 1) tint) tlong))))\n              (Ssequence\n                (Ssequence\n                  (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n                  (Sloop\n                    (Ssequence\n                      (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                                     (Econst_int (Int.repr 16) tint) tint)\n                        Sskip\n                        Sbreak)\n                      (Ssequence\n                        (Ssequence\n                          (Sset _t'7\n                            (Ederef\n                              (Ebinop Oadd (Evar _a (tarray tlong 16))\n                                (Etempvar _i tlong) (tptr tlong)) tlong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Evar _x (tarray tlong 80))\n                                (Ebinop Oadd (Etempvar _i tlong)\n                                  (Econst_int (Int.repr 16) tint) tlong)\n                                (tptr tlong)) tlong) (Etempvar _t'7 tlong)))\n                        (Ssequence\n                          (Ssequence\n                            (Sset _t'6\n                              (Ederef\n                                (Ebinop Oadd (Evar _c (tarray tlong 16))\n                                  (Etempvar _i tlong) (tptr tlong)) tlong))\n                            (Sassign\n                              (Ederef\n                                (Ebinop Oadd (Evar _x (tarray tlong 80))\n                                  (Ebinop Oadd (Etempvar _i tlong)\n                                    (Econst_int (Int.repr 32) tint) tlong)\n                                  (tptr tlong)) tlong) (Etempvar _t'6 tlong)))\n                          (Ssequence\n                            (Ssequence\n                              (Sset _t'5\n                                (Ederef\n                                  (Ebinop Oadd (Evar _b (tarray tlong 16))\n                                    (Etempvar _i tlong) (tptr tlong)) tlong))\n                              (Sassign\n                                (Ederef\n                                  (Ebinop Oadd (Evar _x (tarray tlong 80))\n                                    (Ebinop Oadd (Etempvar _i tlong)\n                                      (Econst_int (Int.repr 48) tint) tlong)\n                                    (tptr tlong)) tlong)\n                                (Etempvar _t'5 tlong)))\n                            (Ssequence\n                              (Sset _t'4\n                                (Ederef\n                                  (Ebinop Oadd (Evar _d (tarray tlong 16))\n                                    (Etempvar _i tlong) (tptr tlong)) tlong))\n                              (Sassign\n                                (Ederef\n                                  (Ebinop Oadd (Evar _x (tarray tlong 80))\n                                    (Ebinop Oadd (Etempvar _i tlong)\n                                      (Econst_int (Int.repr 64) tint) tlong)\n                                    (tptr tlong)) tlong)\n                                (Etempvar _t'4 tlong)))))))\n                    (Sset _i\n                      (Ebinop Oadd (Etempvar _i tlong)\n                        (Econst_int (Int.repr 1) tint) tlong))))\n                (Ssequence\n                  (Scall None\n                    (Evar _inv25519 (Tfunction\n                                      (Tcons (tptr tlong)\n                                        (Tcons (tptr tlong) Tnil)) tvoid\n                                      cc_default))\n                    ((Ebinop Oadd (Evar _x (tarray tlong 80))\n                       (Econst_int (Int.repr 32) tint) (tptr tlong)) ::\n                     (Ebinop Oadd (Evar _x (tarray tlong 80))\n                       (Econst_int (Int.repr 32) tint) (tptr tlong)) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _M (Tfunction\n                                 (Tcons (tptr tlong)\n                                   (Tcons (tptr tlong)\n                                     (Tcons (tptr tlong) Tnil))) tvoid\n                                 cc_default))\n                      ((Ebinop Oadd (Evar _x (tarray tlong 80))\n                         (Econst_int (Int.repr 16) tint) (tptr tlong)) ::\n                       (Ebinop Oadd (Evar _x (tarray tlong 80))\n                         (Econst_int (Int.repr 16) tint) (tptr tlong)) ::\n                       (Ebinop Oadd (Evar _x (tarray tlong 80))\n                         (Econst_int (Int.repr 32) tint) (tptr tlong)) ::\n                       nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _pack25519 (Tfunction\n                                           (Tcons (tptr tuchar)\n                                             (Tcons (tptr tlong) Tnil)) tvoid\n                                           cc_default))\n                        ((Etempvar _q (tptr tuchar)) ::\n                         (Ebinop Oadd (Evar _x (tarray tlong 80))\n                           (Econst_int (Int.repr 16) tint) (tptr tlong)) ::\n                         nil))\n                      (Sreturn (Some (Econst_int (Int.repr 0) tint))))))))))))))\n|}.\n\nDefinition f_crypto_scalarmult_curve25519_tweet_base := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_q, (tptr tuchar)) :: (_n, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _crypto_scalarmult_curve25519_tweet (Tfunction\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar)\n                                                    (Tcons (tptr tuchar)\n                                                      Tnil))) tint\n                                                cc_default))\n    ((Etempvar _q (tptr tuchar)) :: (Etempvar _n (tptr tuchar)) ::\n     (Evar __9 (tarray tuchar 32)) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet_keypair := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_y, (tptr tuchar)) :: (_x, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _randombytes (Tfunction (Tcons (tptr tuchar) (Tcons tulong Tnil))\n                         tvoid cc_default))\n    ((Etempvar _x (tptr tuchar)) :: (Econst_int (Int.repr 32) tint) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_scalarmult_curve25519_tweet_base (Tfunction\n                                                       (Tcons (tptr tuchar)\n                                                         (Tcons (tptr tuchar)\n                                                           Tnil)) tint\n                                                       cc_default))\n      ((Etempvar _y (tptr tuchar)) :: (Etempvar _x (tptr tuchar)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet_beforenm := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_k, (tptr tuchar)) :: (_y, (tptr tuchar)) ::\n                (_x, (tptr tuchar)) :: nil);\n  fn_vars := ((_s, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_scalarmult_curve25519_tweet (Tfunction\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar)\n                                                    (Tcons (tptr tuchar)\n                                                      Tnil))) tint\n                                                cc_default))\n    ((Evar _s (tarray tuchar 32)) :: (Etempvar _x (tptr tuchar)) ::\n     (Etempvar _y (tptr tuchar)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_core_hsalsa20_tweet (Tfunction\n                                          (Tcons (tptr tuchar)\n                                            (Tcons (tptr tuchar)\n                                              (Tcons (tptr tuchar)\n                                                (Tcons (tptr tuchar) Tnil))))\n                                          tint cc_default))\n      ((Etempvar _k (tptr tuchar)) :: (Evar __0 (tarray tuchar 16)) ::\n       (Evar _s (tarray tuchar 32)) :: (Evar _sigma (tarray tuchar 16)) ::\n       nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet_afternm := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _crypto_secretbox_xsalsa20poly1305_tweet (Tfunction\n                                                     (Tcons (tptr tuchar)\n                                                       (Tcons (tptr tuchar)\n                                                         (Tcons tulong\n                                                           (Tcons\n                                                             (tptr tuchar)\n                                                             (Tcons\n                                                               (tptr tuchar)\n                                                               Tnil))))) tint\n                                                     cc_default))\n    ((Etempvar _c (tptr tuchar)) :: (Etempvar _m (tptr tuchar)) ::\n     (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_m, (tptr tuchar)) :: (_c, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_k, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _crypto_secretbox_xsalsa20poly1305_tweet_open (Tfunction\n                                                          (Tcons\n                                                            (tptr tuchar)\n                                                            (Tcons\n                                                              (tptr tuchar)\n                                                              (Tcons tulong\n                                                                (Tcons\n                                                                  (tptr tuchar)\n                                                                  (Tcons\n                                                                    (tptr tuchar)\n                                                                    Tnil)))))\n                                                          tint cc_default))\n    ((Etempvar _m (tptr tuchar)) :: (Etempvar _c (tptr tuchar)) ::\n     (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n     (Etempvar _k (tptr tuchar)) :: nil))\n  (Sreturn (Some (Etempvar _t'1 tint))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_c, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_y, (tptr tuchar)) ::\n                (_x, (tptr tuchar)) :: nil);\n  fn_vars := ((_k, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_box_curve25519xsalsa20poly1305_tweet_beforenm (Tfunction\n                                                                  (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    Tnil)))\n                                                                  tint\n                                                                  cc_default))\n    ((Evar _k (tarray tuchar 32)) :: (Etempvar _y (tptr tuchar)) ::\n     (Etempvar _x (tptr tuchar)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_box_curve25519xsalsa20poly1305_tweet_afternm (Tfunction\n                                                                   (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    tulong\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    Tnil)))))\n                                                                   tint\n                                                                   cc_default))\n      ((Etempvar _c (tptr tuchar)) :: (Etempvar _m (tptr tuchar)) ::\n       (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n       (Evar _k (tarray tuchar 32)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_crypto_box_curve25519xsalsa20poly1305_tweet_open := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_m, (tptr tuchar)) :: (_c, (tptr tuchar)) :: (_d, tulong) ::\n                (_n, (tptr tuchar)) :: (_y, (tptr tuchar)) ::\n                (_x, (tptr tuchar)) :: nil);\n  fn_vars := ((_k, (tarray tuchar 32)) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_box_curve25519xsalsa20poly1305_tweet_beforenm (Tfunction\n                                                                  (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    Tnil)))\n                                                                  tint\n                                                                  cc_default))\n    ((Evar _k (tarray tuchar 32)) :: (Etempvar _y (tptr tuchar)) ::\n     (Etempvar _x (tptr tuchar)) :: nil))\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm \n      (Tfunction\n        (Tcons (tptr tuchar)\n          (Tcons (tptr tuchar)\n            (Tcons tulong (Tcons (tptr tuchar) (Tcons (tptr tuchar) Tnil)))))\n        tint cc_default))\n      ((Etempvar _m (tptr tuchar)) :: (Etempvar _c (tptr tuchar)) ::\n       (Etempvar _d tulong) :: (Etempvar _n (tptr tuchar)) ::\n       (Evar _k (tarray tuchar 32)) :: nil))\n    (Sreturn (Some (Etempvar _t'1 tint)))))\n|}.\n\nDefinition f_R := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: (_c, tint) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oor\n                 (Ebinop Oshr (Etempvar _x tulong) (Etempvar _c tint) tulong)\n                 (Ebinop Oshl (Etempvar _x tulong)\n                   (Ebinop Osub (Econst_int (Int.repr 64) tint)\n                     (Etempvar _c tint) tint) tulong) tulong)))\n|}.\n\nDefinition f_Ch := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: (_y, tulong) :: (_z, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oxor\n                 (Ebinop Oand (Etempvar _x tulong) (Etempvar _y tulong)\n                   tulong)\n                 (Ebinop Oand (Eunop Onotint (Etempvar _x tulong) tulong)\n                   (Etempvar _z tulong) tulong) tulong)))\n|}.\n\nDefinition f_Maj := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: (_y, tulong) :: (_z, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oxor\n                 (Ebinop Oxor\n                   (Ebinop Oand (Etempvar _x tulong) (Etempvar _y tulong)\n                     tulong)\n                   (Ebinop Oand (Etempvar _x tulong) (Etempvar _z tulong)\n                     tulong) tulong)\n                 (Ebinop Oand (Etempvar _y tulong) (Etempvar _z tulong)\n                   tulong) tulong)))\n|}.\n\nDefinition f_Sigma0 := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'3, tulong) :: (_t'2, tulong) :: (_t'1, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Ssequence\n      (Scall (Some _t'1)\n        (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong\n                   cc_default))\n        ((Etempvar _x tulong) :: (Econst_int (Int.repr 28) tint) :: nil))\n      (Scall (Some _t'2)\n        (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong\n                   cc_default))\n        ((Etempvar _x tulong) :: (Econst_int (Int.repr 34) tint) :: nil)))\n    (Scall (Some _t'3)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 39) tint) :: nil)))\n  (Sreturn (Some (Ebinop Oxor\n                   (Ebinop Oxor (Etempvar _t'1 tulong) (Etempvar _t'2 tulong)\n                     tulong) (Etempvar _t'3 tulong) tulong))))\n|}.\n\nDefinition f_Sigma1 := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'3, tulong) :: (_t'2, tulong) :: (_t'1, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Ssequence\n      (Scall (Some _t'1)\n        (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong\n                   cc_default))\n        ((Etempvar _x tulong) :: (Econst_int (Int.repr 14) tint) :: nil))\n      (Scall (Some _t'2)\n        (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong\n                   cc_default))\n        ((Etempvar _x tulong) :: (Econst_int (Int.repr 18) tint) :: nil)))\n    (Scall (Some _t'3)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 41) tint) :: nil)))\n  (Sreturn (Some (Ebinop Oxor\n                   (Ebinop Oxor (Etempvar _t'1 tulong) (Etempvar _t'2 tulong)\n                     tulong) (Etempvar _t'3 tulong) tulong))))\n|}.\n\nDefinition f_sigma0 := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'2, tulong) :: (_t'1, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 1) tint) :: nil))\n    (Scall (Some _t'2)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 8) tint) :: nil)))\n  (Sreturn (Some (Ebinop Oxor\n                   (Ebinop Oxor (Etempvar _t'1 tulong) (Etempvar _t'2 tulong)\n                     tulong)\n                   (Ebinop Oshr (Etempvar _x tulong)\n                     (Econst_int (Int.repr 7) tint) tulong) tulong))))\n|}.\n\nDefinition f_sigma1 := {|\n  fn_return := tulong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tulong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'2, tulong) :: (_t'1, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 19) tint) :: nil))\n    (Scall (Some _t'2)\n      (Evar _R (Tfunction (Tcons tulong (Tcons tint Tnil)) tulong cc_default))\n      ((Etempvar _x tulong) :: (Econst_int (Int.repr 61) tint) :: nil)))\n  (Sreturn (Some (Ebinop Oxor\n                   (Ebinop Oxor (Etempvar _t'1 tulong) (Etempvar _t'2 tulong)\n                     tulong)\n                   (Ebinop Oshr (Etempvar _x tulong)\n                     (Econst_int (Int.repr 6) tint) tulong) tulong))))\n|}.\n\nDefinition v_K := {|\n  gvar_info := (tarray tulong 80);\n  gvar_init := (Init_int64 (Int64.repr 4794697086780616226) ::\n                Init_int64 (Int64.repr 8158064640168781261) ::\n                Init_int64 (Int64.repr (-5349999486874862801)) ::\n                Init_int64 (Int64.repr (-1606136188198331460)) ::\n                Init_int64 (Int64.repr 4131703408338449720) ::\n                Init_int64 (Int64.repr 6480981068601479193) ::\n                Init_int64 (Int64.repr (-7908458776815382629)) ::\n                Init_int64 (Int64.repr (-6116909921290321640)) ::\n                Init_int64 (Int64.repr (-2880145864133508542)) ::\n                Init_int64 (Int64.repr 1334009975649890238) ::\n                Init_int64 (Int64.repr 2608012711638119052) ::\n                Init_int64 (Int64.repr 6128411473006802146) ::\n                Init_int64 (Int64.repr 8268148722764581231) ::\n                Init_int64 (Int64.repr (-9160688886553864527)) ::\n                Init_int64 (Int64.repr (-7215885187991268811)) ::\n                Init_int64 (Int64.repr (-4495734319001033068)) ::\n                Init_int64 (Int64.repr (-1973867731355612462)) ::\n                Init_int64 (Int64.repr (-1171420211273849373)) ::\n                Init_int64 (Int64.repr 1135362057144423861) ::\n                Init_int64 (Int64.repr 2597628984639134821) ::\n                Init_int64 (Int64.repr 3308224258029322869) ::\n                Init_int64 (Int64.repr 5365058923640841347) ::\n                Init_int64 (Int64.repr 6679025012923562964) ::\n                Init_int64 (Int64.repr 8573033837759648693) ::\n                Init_int64 (Int64.repr (-7476448914759557205)) ::\n                Init_int64 (Int64.repr (-6327057829258317296)) ::\n                Init_int64 (Int64.repr (-5763719355590565569)) ::\n                Init_int64 (Int64.repr (-4658551843659510044)) ::\n                Init_int64 (Int64.repr (-4116276920077217854)) ::\n                Init_int64 (Int64.repr (-3051310485924567259)) ::\n                Init_int64 (Int64.repr 489312712824947311) ::\n                Init_int64 (Int64.repr 1452737877330783856) ::\n                Init_int64 (Int64.repr 2861767655752347644) ::\n                Init_int64 (Int64.repr 3322285676063803686) ::\n                Init_int64 (Int64.repr 5560940570517711597) ::\n                Init_int64 (Int64.repr 5996557281743188959) ::\n                Init_int64 (Int64.repr 7280758554555802590) ::\n                Init_int64 (Int64.repr 8532644243296465576) ::\n                Init_int64 (Int64.repr (-9096487096722542874)) ::\n                Init_int64 (Int64.repr (-7894198246740708037)) ::\n                Init_int64 (Int64.repr (-6719396339535248540)) ::\n                Init_int64 (Int64.repr (-6333637450476146687)) ::\n                Init_int64 (Int64.repr (-4446306890439682159)) ::\n                Init_int64 (Int64.repr (-4076793802049405392)) ::\n                Init_int64 (Int64.repr (-3345356375505022440)) ::\n                Init_int64 (Int64.repr (-2983346525034927856)) ::\n                Init_int64 (Int64.repr (-860691631967231958)) ::\n                Init_int64 (Int64.repr 1182934255886127544) ::\n                Init_int64 (Int64.repr 1847814050463011016) ::\n                Init_int64 (Int64.repr 2177327727835720531) ::\n                Init_int64 (Int64.repr 2830643537854262169) ::\n                Init_int64 (Int64.repr 3796741975233480872) ::\n                Init_int64 (Int64.repr 4115178125766777443) ::\n                Init_int64 (Int64.repr 5681478168544905931) ::\n                Init_int64 (Int64.repr 6601373596472566643) ::\n                Init_int64 (Int64.repr 7507060721942968483) ::\n                Init_int64 (Int64.repr 8399075790359081724) ::\n                Init_int64 (Int64.repr 8693463985226723168) ::\n                Init_int64 (Int64.repr (-8878714635349349518)) ::\n                Init_int64 (Int64.repr (-8302665154208450068)) ::\n                Init_int64 (Int64.repr (-8016688836872298968)) ::\n                Init_int64 (Int64.repr (-6606660893046293015)) ::\n                Init_int64 (Int64.repr (-4685533653050689259)) ::\n                Init_int64 (Int64.repr (-4147400797238176981)) ::\n                Init_int64 (Int64.repr (-3880063495543823972)) ::\n                Init_int64 (Int64.repr (-3348786107499101689)) ::\n                Init_int64 (Int64.repr (-1523767162380948706)) ::\n                Init_int64 (Int64.repr (-757361751448694408)) ::\n                Init_int64 (Int64.repr 500013540394364858) ::\n                Init_int64 (Int64.repr 748580250866718886) ::\n                Init_int64 (Int64.repr 1242879168328830382) ::\n                Init_int64 (Int64.repr 1977374033974150939) ::\n                Init_int64 (Int64.repr 2944078676154940804) ::\n                Init_int64 (Int64.repr 3659926193048069267) ::\n                Init_int64 (Int64.repr 4368137639120453308) ::\n                Init_int64 (Int64.repr 4836135668995329356) ::\n                Init_int64 (Int64.repr 5532061633213252278) ::\n                Init_int64 (Int64.repr 6448918945643986474) ::\n                Init_int64 (Int64.repr 6902733635092675308) ::\n                Init_int64 (Int64.repr 7801388544844847127) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_crypto_hashblocks_sha512_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_x, (tptr tuchar)) :: (_m, (tptr tuchar)) :: (_n, tulong) ::\n                nil);\n  fn_vars := ((_z, (tarray tulong 8)) :: (_b, (tarray tulong 8)) ::\n              (_a, (tarray tulong 8)) :: (_w, (tarray tulong 16)) :: nil);\n  fn_temps := ((_t, tulong) :: (_i, tint) :: (_j, tint) :: (_t'9, tulong) ::\n               (_t'8, tulong) :: (_t'7, tulong) :: (_t'6, tulong) ::\n               (_t'5, tulong) :: (_t'4, tulong) :: (_t'3, tulong) ::\n               (_t'2, tulong) :: (_t'1, tulong) :: (_t'31, tulong) ::\n               (_t'30, tulong) :: (_t'29, tulong) :: (_t'28, tulong) ::\n               (_t'27, tulong) :: (_t'26, tulong) :: (_t'25, tulong) ::\n               (_t'24, tulong) :: (_t'23, tulong) :: (_t'22, tulong) ::\n               (_t'21, tulong) :: (_t'20, tulong) :: (_t'19, tulong) ::\n               (_t'18, tulong) :: (_t'17, tulong) :: (_t'16, tulong) ::\n               (_t'15, tulong) :: (_t'14, tulong) :: (_t'13, tulong) ::\n               (_t'12, tulong) :: (_t'11, tulong) :: (_t'10, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                       (Econst_int (Int.repr 8) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Ssequence\n              (Scall (Some _t'1)\n                (Evar _dl64 (Tfunction (Tcons (tptr tuchar) Tnil) tulong\n                              cc_default))\n                ((Ebinop Oadd (Etempvar _x (tptr tuchar))\n                   (Ebinop Omul (Econst_int (Int.repr 8) tint)\n                     (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n              (Sset _t'2 (Ecast (Etempvar _t'1 tulong) tulong)))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _a (tarray tulong 8)) (Etempvar _i tint)\n                  (tptr tulong)) tulong) (Etempvar _t'2 tulong)))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _z (tarray tulong 8)) (Etempvar _i tint)\n                (tptr tulong)) tulong) (Etempvar _t'2 tulong))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n  (Ssequence\n    (Swhile\n      (Ebinop Oge (Etempvar _n tulong) (Econst_int (Int.repr 128) tint) tint)\n      (Ssequence\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                             (Econst_int (Int.repr 16) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Scall (Some _t'3)\n                  (Evar _dl64 (Tfunction (Tcons (tptr tuchar) Tnil) tulong\n                                cc_default))\n                  ((Ebinop Oadd (Etempvar _m (tptr tuchar))\n                     (Ebinop Omul (Econst_int (Int.repr 8) tint)\n                       (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _w (tarray tulong 16))\n                      (Etempvar _i tint) (tptr tulong)) tulong)\n                  (Etempvar _t'3 tulong))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint))))\n        (Ssequence\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 80) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Ssequence\n                    (Sset _j (Econst_int (Int.repr 0) tint))\n                    (Sloop\n                      (Ssequence\n                        (Sifthenelse (Ebinop Olt (Etempvar _j tint)\n                                       (Econst_int (Int.repr 8) tint) tint)\n                          Sskip\n                          Sbreak)\n                        (Ssequence\n                          (Sset _t'31\n                            (Ederef\n                              (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                (Etempvar _j tint) (tptr tulong)) tulong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Evar _b (tarray tulong 8))\n                                (Etempvar _j tint) (tptr tulong)) tulong)\n                            (Etempvar _t'31 tulong))))\n                      (Sset _j\n                        (Ebinop Oadd (Etempvar _j tint)\n                          (Econst_int (Int.repr 1) tint) tint))))\n                  (Ssequence\n                    (Ssequence\n                      (Ssequence\n                        (Ssequence\n                          (Sset _t'30\n                            (Ederef\n                              (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                (Econst_int (Int.repr 4) tint) (tptr tulong))\n                              tulong))\n                          (Scall (Some _t'4)\n                            (Evar _Sigma1 (Tfunction (Tcons tulong Tnil)\n                                            tulong cc_default))\n                            ((Etempvar _t'30 tulong) :: nil)))\n                        (Ssequence\n                          (Sset _t'27\n                            (Ederef\n                              (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                (Econst_int (Int.repr 4) tint) (tptr tulong))\n                              tulong))\n                          (Ssequence\n                            (Sset _t'28\n                              (Ederef\n                                (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                  (Econst_int (Int.repr 5) tint)\n                                  (tptr tulong)) tulong))\n                            (Ssequence\n                              (Sset _t'29\n                                (Ederef\n                                  (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                    (Econst_int (Int.repr 6) tint)\n                                    (tptr tulong)) tulong))\n                              (Scall (Some _t'5)\n                                (Evar _Ch (Tfunction\n                                            (Tcons tulong\n                                              (Tcons tulong\n                                                (Tcons tulong Tnil))) tulong\n                                            cc_default))\n                                ((Etempvar _t'27 tulong) ::\n                                 (Etempvar _t'28 tulong) ::\n                                 (Etempvar _t'29 tulong) :: nil))))))\n                      (Ssequence\n                        (Sset _t'24\n                          (Ederef\n                            (Ebinop Oadd (Evar _a (tarray tulong 8))\n                              (Econst_int (Int.repr 7) tint) (tptr tulong))\n                            tulong))\n                        (Ssequence\n                          (Sset _t'25\n                            (Ederef\n                              (Ebinop Oadd (Evar _K (tarray tulong 80))\n                                (Etempvar _i tint) (tptr tulong)) tulong))\n                          (Ssequence\n                            (Sset _t'26\n                              (Ederef\n                                (Ebinop Oadd (Evar _w (tarray tulong 16))\n                                  (Ebinop Omod (Etempvar _i tint)\n                                    (Econst_int (Int.repr 16) tint) tint)\n                                  (tptr tulong)) tulong))\n                            (Sset _t\n                              (Ebinop Oadd\n                                (Ebinop Oadd\n                                  (Ebinop Oadd\n                                    (Ebinop Oadd (Etempvar _t'24 tulong)\n                                      (Etempvar _t'4 tulong) tulong)\n                                    (Etempvar _t'5 tulong) tulong)\n                                  (Etempvar _t'25 tulong) tulong)\n                                (Etempvar _t'26 tulong) tulong))))))\n                    (Ssequence\n                      (Ssequence\n                        (Ssequence\n                          (Ssequence\n                            (Sset _t'23\n                              (Ederef\n                                (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                  (Econst_int (Int.repr 0) tint)\n                                  (tptr tulong)) tulong))\n                            (Scall (Some _t'6)\n                              (Evar _Sigma0 (Tfunction (Tcons tulong Tnil)\n                                              tulong cc_default))\n                              ((Etempvar _t'23 tulong) :: nil)))\n                          (Ssequence\n                            (Sset _t'20\n                              (Ederef\n                                (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                  (Econst_int (Int.repr 0) tint)\n                                  (tptr tulong)) tulong))\n                            (Ssequence\n                              (Sset _t'21\n                                (Ederef\n                                  (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                    (Econst_int (Int.repr 1) tint)\n                                    (tptr tulong)) tulong))\n                              (Ssequence\n                                (Sset _t'22\n                                  (Ederef\n                                    (Ebinop Oadd (Evar _a (tarray tulong 8))\n                                      (Econst_int (Int.repr 2) tint)\n                                      (tptr tulong)) tulong))\n                                (Scall (Some _t'7)\n                                  (Evar _Maj (Tfunction\n                                               (Tcons tulong\n                                                 (Tcons tulong\n                                                   (Tcons tulong Tnil)))\n                                               tulong cc_default))\n                                  ((Etempvar _t'20 tulong) ::\n                                   (Etempvar _t'21 tulong) ::\n                                   (Etempvar _t'22 tulong) :: nil))))))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _b (tarray tulong 8))\n                              (Econst_int (Int.repr 7) tint) (tptr tulong))\n                            tulong)\n                          (Ebinop Oadd\n                            (Ebinop Oadd (Etempvar _t tulong)\n                              (Etempvar _t'6 tulong) tulong)\n                            (Etempvar _t'7 tulong) tulong)))\n                      (Ssequence\n                        (Ssequence\n                          (Sset _t'19\n                            (Ederef\n                              (Ebinop Oadd (Evar _b (tarray tulong 8))\n                                (Econst_int (Int.repr 3) tint) (tptr tulong))\n                              tulong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Evar _b (tarray tulong 8))\n                                (Econst_int (Int.repr 3) tint) (tptr tulong))\n                              tulong)\n                            (Ebinop Oadd (Etempvar _t'19 tulong)\n                              (Etempvar _t tulong) tulong)))\n                        (Ssequence\n                          (Ssequence\n                            (Sset _j (Econst_int (Int.repr 0) tint))\n                            (Sloop\n                              (Ssequence\n                                (Sifthenelse (Ebinop Olt (Etempvar _j tint)\n                                               (Econst_int (Int.repr 8) tint)\n                                               tint)\n                                  Sskip\n                                  Sbreak)\n                                (Ssequence\n                                  (Sset _t'18\n                                    (Ederef\n                                      (Ebinop Oadd\n                                        (Evar _b (tarray tulong 8))\n                                        (Etempvar _j tint) (tptr tulong))\n                                      tulong))\n                                  (Sassign\n                                    (Ederef\n                                      (Ebinop Oadd\n                                        (Evar _a (tarray tulong 8))\n                                        (Ebinop Omod\n                                          (Ebinop Oadd (Etempvar _j tint)\n                                            (Econst_int (Int.repr 1) tint)\n                                            tint)\n                                          (Econst_int (Int.repr 8) tint)\n                                          tint) (tptr tulong)) tulong)\n                                    (Etempvar _t'18 tulong))))\n                              (Sset _j\n                                (Ebinop Oadd (Etempvar _j tint)\n                                  (Econst_int (Int.repr 1) tint) tint))))\n                          (Sifthenelse (Ebinop Oeq\n                                         (Ebinop Omod (Etempvar _i tint)\n                                           (Econst_int (Int.repr 16) tint)\n                                           tint)\n                                         (Econst_int (Int.repr 15) tint)\n                                         tint)\n                            (Ssequence\n                              (Sset _j (Econst_int (Int.repr 0) tint))\n                              (Sloop\n                                (Ssequence\n                                  (Sifthenelse (Ebinop Olt (Etempvar _j tint)\n                                                 (Econst_int (Int.repr 16) tint)\n                                                 tint)\n                                    Sskip\n                                    Sbreak)\n                                  (Ssequence\n                                    (Ssequence\n                                      (Ssequence\n                                        (Sset _t'17\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _w (tarray tulong 16))\n                                              (Ebinop Omod\n                                                (Ebinop Oadd\n                                                  (Etempvar _j tint)\n                                                  (Econst_int (Int.repr 1) tint)\n                                                  tint)\n                                                (Econst_int (Int.repr 16) tint)\n                                                tint) (tptr tulong)) tulong))\n                                        (Scall (Some _t'8)\n                                          (Evar _sigma0 (Tfunction\n                                                          (Tcons tulong Tnil)\n                                                          tulong cc_default))\n                                          ((Etempvar _t'17 tulong) :: nil)))\n                                      (Ssequence\n                                        (Sset _t'16\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _w (tarray tulong 16))\n                                              (Ebinop Omod\n                                                (Ebinop Oadd\n                                                  (Etempvar _j tint)\n                                                  (Econst_int (Int.repr 14) tint)\n                                                  tint)\n                                                (Econst_int (Int.repr 16) tint)\n                                                tint) (tptr tulong)) tulong))\n                                        (Scall (Some _t'9)\n                                          (Evar _sigma1 (Tfunction\n                                                          (Tcons tulong Tnil)\n                                                          tulong cc_default))\n                                          ((Etempvar _t'16 tulong) :: nil))))\n                                    (Ssequence\n                                      (Sset _t'14\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (Evar _w (tarray tulong 16))\n                                            (Etempvar _j tint) (tptr tulong))\n                                          tulong))\n                                      (Ssequence\n                                        (Sset _t'15\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _w (tarray tulong 16))\n                                              (Ebinop Omod\n                                                (Ebinop Oadd\n                                                  (Etempvar _j tint)\n                                                  (Econst_int (Int.repr 9) tint)\n                                                  tint)\n                                                (Econst_int (Int.repr 16) tint)\n                                                tint) (tptr tulong)) tulong))\n                                        (Sassign\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _w (tarray tulong 16))\n                                              (Etempvar _j tint)\n                                              (tptr tulong)) tulong)\n                                          (Ebinop Oadd\n                                            (Etempvar _t'14 tulong)\n                                            (Ebinop Oadd\n                                              (Ebinop Oadd\n                                                (Etempvar _t'15 tulong)\n                                                (Etempvar _t'8 tulong)\n                                                tulong)\n                                              (Etempvar _t'9 tulong) tulong)\n                                            tulong))))))\n                                (Sset _j\n                                  (Ebinop Oadd (Etempvar _j tint)\n                                    (Econst_int (Int.repr 1) tint) tint))))\n                            Sskip)))))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Ssequence\n            (Ssequence\n              (Sset _i (Econst_int (Int.repr 0) tint))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                 (Econst_int (Int.repr 8) tint) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Ssequence\n                      (Sset _t'12\n                        (Ederef\n                          (Ebinop Oadd (Evar _a (tarray tulong 8))\n                            (Etempvar _i tint) (tptr tulong)) tulong))\n                      (Ssequence\n                        (Sset _t'13\n                          (Ederef\n                            (Ebinop Oadd (Evar _z (tarray tulong 8))\n                              (Etempvar _i tint) (tptr tulong)) tulong))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _a (tarray tulong 8))\n                              (Etempvar _i tint) (tptr tulong)) tulong)\n                          (Ebinop Oadd (Etempvar _t'12 tulong)\n                            (Etempvar _t'13 tulong) tulong))))\n                    (Ssequence\n                      (Sset _t'11\n                        (Ederef\n                          (Ebinop Oadd (Evar _a (tarray tulong 8))\n                            (Etempvar _i tint) (tptr tulong)) tulong))\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Evar _z (tarray tulong 8))\n                            (Etempvar _i tint) (tptr tulong)) tulong)\n                        (Etempvar _t'11 tulong)))))\n                (Sset _i\n                  (Ebinop Oadd (Etempvar _i tint)\n                    (Econst_int (Int.repr 1) tint) tint))))\n            (Ssequence\n              (Sset _m\n                (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                  (Econst_int (Int.repr 128) tint) (tptr tuchar)))\n              (Sset _n\n                (Ebinop Osub (Etempvar _n tulong)\n                  (Econst_int (Int.repr 128) tint) tulong)))))))\n    (Ssequence\n      (Ssequence\n        (Sset _i (Econst_int (Int.repr 0) tint))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                           (Econst_int (Int.repr 8) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Sset _t'10\n                (Ederef\n                  (Ebinop Oadd (Evar _z (tarray tulong 8)) (Etempvar _i tint)\n                    (tptr tulong)) tulong))\n              (Scall None\n                (Evar _ts64 (Tfunction\n                              (Tcons (tptr tuchar) (Tcons tulong Tnil)) tvoid\n                              cc_default))\n                ((Ebinop Oadd (Etempvar _x (tptr tuchar))\n                   (Ebinop Omul (Econst_int (Int.repr 8) tint)\n                     (Etempvar _i tint) tint) (tptr tuchar)) ::\n                 (Etempvar _t'10 tulong) :: nil))))\n          (Sset _i\n            (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n              tint))))\n      (Sreturn (Some (Etempvar _n tulong))))))\n|}.\n\nDefinition v_iv := {|\n  gvar_info := (tarray tuchar 64);\n  gvar_init := (Init_int8 (Int.repr 106) :: Init_int8 (Int.repr 9) ::\n                Init_int8 (Int.repr 230) :: Init_int8 (Int.repr 103) ::\n                Init_int8 (Int.repr 243) :: Init_int8 (Int.repr 188) ::\n                Init_int8 (Int.repr 201) :: Init_int8 (Int.repr 8) ::\n                Init_int8 (Int.repr 187) :: Init_int8 (Int.repr 103) ::\n                Init_int8 (Int.repr 174) :: Init_int8 (Int.repr 133) ::\n                Init_int8 (Int.repr 132) :: Init_int8 (Int.repr 202) ::\n                Init_int8 (Int.repr 167) :: Init_int8 (Int.repr 59) ::\n                Init_int8 (Int.repr 60) :: Init_int8 (Int.repr 110) ::\n                Init_int8 (Int.repr 243) :: Init_int8 (Int.repr 114) ::\n                Init_int8 (Int.repr 254) :: Init_int8 (Int.repr 148) ::\n                Init_int8 (Int.repr 248) :: Init_int8 (Int.repr 43) ::\n                Init_int8 (Int.repr 165) :: Init_int8 (Int.repr 79) ::\n                Init_int8 (Int.repr 245) :: Init_int8 (Int.repr 58) ::\n                Init_int8 (Int.repr 95) :: Init_int8 (Int.repr 29) ::\n                Init_int8 (Int.repr 54) :: Init_int8 (Int.repr 241) ::\n                Init_int8 (Int.repr 81) :: Init_int8 (Int.repr 14) ::\n                Init_int8 (Int.repr 82) :: Init_int8 (Int.repr 127) ::\n                Init_int8 (Int.repr 173) :: Init_int8 (Int.repr 230) ::\n                Init_int8 (Int.repr 130) :: Init_int8 (Int.repr 209) ::\n                Init_int8 (Int.repr 155) :: Init_int8 (Int.repr 5) ::\n                Init_int8 (Int.repr 104) :: Init_int8 (Int.repr 140) ::\n                Init_int8 (Int.repr 43) :: Init_int8 (Int.repr 62) ::\n                Init_int8 (Int.repr 108) :: Init_int8 (Int.repr 31) ::\n                Init_int8 (Int.repr 31) :: Init_int8 (Int.repr 131) ::\n                Init_int8 (Int.repr 217) :: Init_int8 (Int.repr 171) ::\n                Init_int8 (Int.repr 251) :: Init_int8 (Int.repr 65) ::\n                Init_int8 (Int.repr 189) :: Init_int8 (Int.repr 107) ::\n                Init_int8 (Int.repr 91) :: Init_int8 (Int.repr 224) ::\n                Init_int8 (Int.repr 205) :: Init_int8 (Int.repr 25) ::\n                Init_int8 (Int.repr 19) :: Init_int8 (Int.repr 126) ::\n                Init_int8 (Int.repr 33) :: Init_int8 (Int.repr 121) :: nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_crypto_hash_sha512_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_out, (tptr tuchar)) :: (_m, (tptr tuchar)) ::\n                (_n, tulong) :: nil);\n  fn_vars := ((_h, (tarray tuchar 64)) :: (_x, (tarray tuchar 256)) :: nil);\n  fn_temps := ((_i, tulong) :: (_b, tulong) :: (_t'3, tuchar) ::\n               (_t'2, tuchar) :: (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _b (Etempvar _n tulong))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tulong))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tulong)\n                         (Econst_int (Int.repr 64) tint) tint)\n            Sskip\n            Sbreak)\n          (Ssequence\n            (Sset _t'3\n              (Ederef\n                (Ebinop Oadd (Evar _iv (tarray tuchar 64))\n                  (Etempvar _i tulong) (tptr tuchar)) tuchar))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _h (tarray tuchar 64))\n                  (Etempvar _i tulong) (tptr tuchar)) tuchar)\n              (Etempvar _t'3 tuchar))))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tulong) (Econst_int (Int.repr 1) tint)\n            tulong))))\n    (Ssequence\n      (Scall None\n        (Evar _crypto_hashblocks_sha512_tweet (Tfunction\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar)\n                                                    (Tcons tulong Tnil)))\n                                                tint cc_default))\n        ((Evar _h (tarray tuchar 64)) :: (Etempvar _m (tptr tuchar)) ::\n         (Etempvar _n tulong) :: nil))\n      (Ssequence\n        (Sset _m\n          (Ebinop Oadd (Etempvar _m (tptr tuchar)) (Etempvar _n tulong)\n            (tptr tuchar)))\n        (Ssequence\n          (Sset _n\n            (Ebinop Oand (Etempvar _n tulong)\n              (Econst_int (Int.repr 127) tint) tulong))\n          (Ssequence\n            (Sset _m\n              (Ebinop Osub (Etempvar _m (tptr tuchar)) (Etempvar _n tulong)\n                (tptr tuchar)))\n            (Ssequence\n              (Ssequence\n                (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tulong))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _i tulong)\n                                   (Econst_int (Int.repr 256) tint) tint)\n                      Sskip\n                      Sbreak)\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _x (tarray tuchar 256))\n                          (Etempvar _i tulong) (tptr tuchar)) tuchar)\n                      (Econst_int (Int.repr 0) tint)))\n                  (Sset _i\n                    (Ebinop Oadd (Etempvar _i tulong)\n                      (Econst_int (Int.repr 1) tint) tulong))))\n              (Ssequence\n                (Ssequence\n                  (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tulong))\n                  (Sloop\n                    (Ssequence\n                      (Sifthenelse (Ebinop Olt (Etempvar _i tulong)\n                                     (Etempvar _n tulong) tint)\n                        Sskip\n                        Sbreak)\n                      (Ssequence\n                        (Sset _t'2\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                              (Etempvar _i tulong) (tptr tuchar)) tuchar))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Evar _x (tarray tuchar 256))\n                              (Etempvar _i tulong) (tptr tuchar)) tuchar)\n                          (Etempvar _t'2 tuchar))))\n                    (Sset _i\n                      (Ebinop Oadd (Etempvar _i tulong)\n                        (Econst_int (Int.repr 1) tint) tulong))))\n                (Ssequence\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Evar _x (tarray tuchar 256))\n                        (Etempvar _n tulong) (tptr tuchar)) tuchar)\n                    (Econst_int (Int.repr 128) tint))\n                  (Ssequence\n                    (Sset _n\n                      (Ecast\n                        (Ebinop Osub (Econst_int (Int.repr 256) tint)\n                          (Ebinop Omul (Econst_int (Int.repr 128) tint)\n                            (Ebinop Olt (Etempvar _n tulong)\n                              (Econst_int (Int.repr 112) tint) tint) tint)\n                          tint) tulong))\n                    (Ssequence\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Evar _x (tarray tuchar 256))\n                            (Ebinop Osub (Etempvar _n tulong)\n                              (Econst_int (Int.repr 9) tint) tulong)\n                            (tptr tuchar)) tuchar)\n                        (Ebinop Oshr (Etempvar _b tulong)\n                          (Econst_int (Int.repr 61) tint) tulong))\n                      (Ssequence\n                        (Scall None\n                          (Evar _ts64 (Tfunction\n                                        (Tcons (tptr tuchar)\n                                          (Tcons tulong Tnil)) tvoid\n                                        cc_default))\n                          ((Ebinop Osub\n                             (Ebinop Oadd (Evar _x (tarray tuchar 256))\n                               (Etempvar _n tulong) (tptr tuchar))\n                             (Econst_int (Int.repr 8) tint) (tptr tuchar)) ::\n                           (Ebinop Oshl (Etempvar _b tulong)\n                             (Econst_int (Int.repr 3) tint) tulong) :: nil))\n                        (Ssequence\n                          (Scall None\n                            (Evar _crypto_hashblocks_sha512_tweet (Tfunction\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    (tptr tuchar)\n                                                                    (Tcons\n                                                                    tulong\n                                                                    Tnil)))\n                                                                    tint\n                                                                    cc_default))\n                            ((Evar _h (tarray tuchar 64)) ::\n                             (Evar _x (tarray tuchar 256)) ::\n                             (Etempvar _n tulong) :: nil))\n                          (Ssequence\n                            (Ssequence\n                              (Sset _i\n                                (Ecast (Econst_int (Int.repr 0) tint) tulong))\n                              (Sloop\n                                (Ssequence\n                                  (Sifthenelse (Ebinop Olt\n                                                 (Etempvar _i tulong)\n                                                 (Econst_int (Int.repr 64) tint)\n                                                 tint)\n                                    Sskip\n                                    Sbreak)\n                                  (Ssequence\n                                    (Sset _t'1\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Evar _h (tarray tuchar 64))\n                                          (Etempvar _i tulong) (tptr tuchar))\n                                        tuchar))\n                                    (Sassign\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Etempvar _out (tptr tuchar))\n                                          (Etempvar _i tulong) (tptr tuchar))\n                                        tuchar) (Etempvar _t'1 tuchar))))\n                                (Sset _i\n                                  (Ebinop Oadd (Etempvar _i tulong)\n                                    (Econst_int (Int.repr 1) tint) tulong))))\n                            (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))))))))))))\n|}.\n\nDefinition f_add := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_p, (tptr (tarray tlong 16))) ::\n                (_q, (tptr (tarray tlong 16))) :: nil);\n  fn_vars := ((_a, (tarray tlong 16)) :: (_b, (tarray tlong 16)) ::\n              (_c, (tarray tlong 16)) :: (_d, (tarray tlong 16)) ::\n              (_t, (tarray tlong 16)) :: (_e, (tarray tlong 16)) ::\n              (_f, (tarray tlong 16)) :: (_g, (tarray tlong 16)) ::\n              (_h, (tarray tlong 16)) :: nil);\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _Z (Tfunction\n               (Tcons (tptr tlong)\n                 (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n               cc_default))\n    ((Evar _a (tarray tlong 16)) ::\n     (Ederef\n       (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n         (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) ::\n     (Ederef\n       (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n         (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _Z (Tfunction\n                 (Tcons (tptr tlong)\n                   (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                 cc_default))\n      ((Evar _t (tarray tlong 16)) ::\n       (Ederef\n         (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n           (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) ::\n       (Ederef\n         (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n           (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _M (Tfunction\n                   (Tcons (tptr tlong)\n                     (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                   cc_default))\n        ((Evar _a (tarray tlong 16)) :: (Evar _a (tarray tlong 16)) ::\n         (Evar _t (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _A (Tfunction\n                     (Tcons (tptr tlong)\n                       (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                     cc_default))\n          ((Evar _b (tarray tlong 16)) ::\n           (Ederef\n             (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n               (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n             (tarray tlong 16)) ::\n           (Ederef\n             (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n               (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n             (tarray tlong 16)) :: nil))\n        (Ssequence\n          (Scall None\n            (Evar _A (Tfunction\n                       (Tcons (tptr tlong)\n                         (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                       tvoid cc_default))\n            ((Evar _t (tarray tlong 16)) ::\n             (Ederef\n               (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n                 (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n               (tarray tlong 16)) ::\n             (Ederef\n               (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n                 (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n               (tarray tlong 16)) :: nil))\n          (Ssequence\n            (Scall None\n              (Evar _M (Tfunction\n                         (Tcons (tptr tlong)\n                           (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                         tvoid cc_default))\n              ((Evar _b (tarray tlong 16)) :: (Evar _b (tarray tlong 16)) ::\n               (Evar _t (tarray tlong 16)) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _M (Tfunction\n                           (Tcons (tptr tlong)\n                             (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                           tvoid cc_default))\n                ((Evar _c (tarray tlong 16)) ::\n                 (Ederef\n                   (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n                     (Econst_int (Int.repr 3) tint) (tptr (tarray tlong 16)))\n                   (tarray tlong 16)) ::\n                 (Ederef\n                   (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n                     (Econst_int (Int.repr 3) tint) (tptr (tarray tlong 16)))\n                   (tarray tlong 16)) :: nil))\n              (Ssequence\n                (Scall None\n                  (Evar _M (Tfunction\n                             (Tcons (tptr tlong)\n                               (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                             tvoid cc_default))\n                  ((Evar _c (tarray tlong 16)) ::\n                   (Evar _c (tarray tlong 16)) ::\n                   (Evar _D2 (tarray tlong 16)) :: nil))\n                (Ssequence\n                  (Scall None\n                    (Evar _M (Tfunction\n                               (Tcons (tptr tlong)\n                                 (Tcons (tptr tlong)\n                                   (Tcons (tptr tlong) Tnil))) tvoid\n                               cc_default))\n                    ((Evar _d (tarray tlong 16)) ::\n                     (Ederef\n                       (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n                         (Econst_int (Int.repr 2) tint)\n                         (tptr (tarray tlong 16))) (tarray tlong 16)) ::\n                     (Ederef\n                       (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n                         (Econst_int (Int.repr 2) tint)\n                         (tptr (tarray tlong 16))) (tarray tlong 16)) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _A (Tfunction\n                                 (Tcons (tptr tlong)\n                                   (Tcons (tptr tlong)\n                                     (Tcons (tptr tlong) Tnil))) tvoid\n                                 cc_default))\n                      ((Evar _d (tarray tlong 16)) ::\n                       (Evar _d (tarray tlong 16)) ::\n                       (Evar _d (tarray tlong 16)) :: nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _Z (Tfunction\n                                   (Tcons (tptr tlong)\n                                     (Tcons (tptr tlong)\n                                       (Tcons (tptr tlong) Tnil))) tvoid\n                                   cc_default))\n                        ((Evar _e (tarray tlong 16)) ::\n                         (Evar _b (tarray tlong 16)) ::\n                         (Evar _a (tarray tlong 16)) :: nil))\n                      (Ssequence\n                        (Scall None\n                          (Evar _Z (Tfunction\n                                     (Tcons (tptr tlong)\n                                       (Tcons (tptr tlong)\n                                         (Tcons (tptr tlong) Tnil))) tvoid\n                                     cc_default))\n                          ((Evar _f (tarray tlong 16)) ::\n                           (Evar _d (tarray tlong 16)) ::\n                           (Evar _c (tarray tlong 16)) :: nil))\n                        (Ssequence\n                          (Scall None\n                            (Evar _A (Tfunction\n                                       (Tcons (tptr tlong)\n                                         (Tcons (tptr tlong)\n                                           (Tcons (tptr tlong) Tnil))) tvoid\n                                       cc_default))\n                            ((Evar _g (tarray tlong 16)) ::\n                             (Evar _d (tarray tlong 16)) ::\n                             (Evar _c (tarray tlong 16)) :: nil))\n                          (Ssequence\n                            (Scall None\n                              (Evar _A (Tfunction\n                                         (Tcons (tptr tlong)\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong) Tnil)))\n                                         tvoid cc_default))\n                              ((Evar _h (tarray tlong 16)) ::\n                               (Evar _b (tarray tlong 16)) ::\n                               (Evar _a (tarray tlong 16)) :: nil))\n                            (Ssequence\n                              (Scall None\n                                (Evar _M (Tfunction\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong) Tnil)))\n                                           tvoid cc_default))\n                                ((Ederef\n                                   (Ebinop Oadd\n                                     (Etempvar _p (tptr (tarray tlong 16)))\n                                     (Econst_int (Int.repr 0) tint)\n                                     (tptr (tarray tlong 16)))\n                                   (tarray tlong 16)) ::\n                                 (Evar _e (tarray tlong 16)) ::\n                                 (Evar _f (tarray tlong 16)) :: nil))\n                              (Ssequence\n                                (Scall None\n                                  (Evar _M (Tfunction\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong) Tnil)))\n                                             tvoid cc_default))\n                                  ((Ederef\n                                     (Ebinop Oadd\n                                       (Etempvar _p (tptr (tarray tlong 16)))\n                                       (Econst_int (Int.repr 1) tint)\n                                       (tptr (tarray tlong 16)))\n                                     (tarray tlong 16)) ::\n                                   (Evar _h (tarray tlong 16)) ::\n                                   (Evar _g (tarray tlong 16)) :: nil))\n                                (Ssequence\n                                  (Scall None\n                                    (Evar _M (Tfunction\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong)\n                                                   (Tcons (tptr tlong) Tnil)))\n                                               tvoid cc_default))\n                                    ((Ederef\n                                       (Ebinop Oadd\n                                         (Etempvar _p (tptr (tarray tlong 16)))\n                                         (Econst_int (Int.repr 2) tint)\n                                         (tptr (tarray tlong 16)))\n                                       (tarray tlong 16)) ::\n                                     (Evar _g (tarray tlong 16)) ::\n                                     (Evar _f (tarray tlong 16)) :: nil))\n                                  (Scall None\n                                    (Evar _M (Tfunction\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong)\n                                                   (Tcons (tptr tlong) Tnil)))\n                                               tvoid cc_default))\n                                    ((Ederef\n                                       (Ebinop Oadd\n                                         (Etempvar _p (tptr (tarray tlong 16)))\n                                         (Econst_int (Int.repr 3) tint)\n                                         (tptr (tarray tlong 16)))\n                                       (tarray tlong 16)) ::\n                                     (Evar _e (tarray tlong 16)) ::\n                                     (Evar _h (tarray tlong 16)) :: nil)))))))))))))))))))\n|}.\n\nDefinition f_cswap := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_p, (tptr (tarray tlong 16))) ::\n                (_q, (tptr (tarray tlong 16))) :: (_b, tuchar) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _i (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                     (Econst_int (Int.repr 4) tint) tint)\n        Sskip\n        Sbreak)\n      (Scall None\n        (Evar _sel25519 (Tfunction\n                          (Tcons (tptr tlong)\n                            (Tcons (tptr tlong) (Tcons tint Tnil))) tvoid\n                          cc_default))\n        ((Ederef\n           (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n             (Etempvar _i tint) (tptr (tarray tlong 16))) (tarray tlong 16)) ::\n         (Ederef\n           (Ebinop Oadd (Etempvar _q (tptr (tarray tlong 16)))\n             (Etempvar _i tint) (tptr (tarray tlong 16))) (tarray tlong 16)) ::\n         (Etempvar _b tuchar) :: nil)))\n    (Sset _i\n      (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n|}.\n\nDefinition f_pack := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_r, (tptr tuchar)) :: (_p, (tptr (tarray tlong 16))) :: nil);\n  fn_vars := ((_tx, (tarray tlong 16)) :: (_ty, (tarray tlong 16)) ::\n              (_zi, (tarray tlong 16)) :: nil);\n  fn_temps := ((_t'1, tuchar) :: (_t'2, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _inv25519 (Tfunction (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                      tvoid cc_default))\n    ((Evar _zi (tarray tlong 16)) ::\n     (Ederef\n       (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n         (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _M (Tfunction\n                 (Tcons (tptr tlong)\n                   (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                 cc_default))\n      ((Evar _tx (tarray tlong 16)) ::\n       (Ederef\n         (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n           (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) :: (Evar _zi (tarray tlong 16)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _M (Tfunction\n                   (Tcons (tptr tlong)\n                     (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                   cc_default))\n        ((Evar _ty (tarray tlong 16)) ::\n         (Ederef\n           (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n             (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n           (tarray tlong 16)) :: (Evar _zi (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _pack25519 (Tfunction\n                             (Tcons (tptr tuchar) (Tcons (tptr tlong) Tnil))\n                             tvoid cc_default))\n          ((Etempvar _r (tptr tuchar)) :: (Evar _ty (tarray tlong 16)) ::\n           nil))\n        (Ssequence\n          (Scall (Some _t'1)\n            (Evar _par25519 (Tfunction (Tcons (tptr tlong) Tnil) tuchar\n                              cc_default))\n            ((Evar _tx (tarray tlong 16)) :: nil))\n          (Ssequence\n            (Sset _t'2\n              (Ederef\n                (Ebinop Oadd (Etempvar _r (tptr tuchar))\n                  (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Etempvar _r (tptr tuchar))\n                  (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n              (Ebinop Oxor (Etempvar _t'2 tuchar)\n                (Ebinop Oshl (Etempvar _t'1 tuchar)\n                  (Econst_int (Int.repr 7) tint) tint) tint))))))))\n|}.\n\nDefinition f_scalarmult := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_p, (tptr (tarray tlong 16))) ::\n                (_q, (tptr (tarray tlong 16))) :: (_s, (tptr tuchar)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_i, tint) :: (_b, tuchar) :: (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _set25519 (Tfunction (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                      tvoid cc_default))\n    ((Ederef\n       (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n         (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) :: (Evar _gf0 (tarray tlong 16)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _set25519 (Tfunction\n                        (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)) tvoid\n                        cc_default))\n      ((Ederef\n         (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n           (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) :: (Evar _gf1 (tarray tlong 16)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _set25519 (Tfunction\n                          (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                          tvoid cc_default))\n        ((Ederef\n           (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n             (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n           (tarray tlong 16)) :: (Evar _gf1 (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _set25519 (Tfunction\n                            (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                            tvoid cc_default))\n          ((Ederef\n             (Ebinop Oadd (Etempvar _p (tptr (tarray tlong 16)))\n               (Econst_int (Int.repr 3) tint) (tptr (tarray tlong 16)))\n             (tarray tlong 16)) :: (Evar _gf0 (tarray tlong 16)) :: nil))\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 255) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Oge (Etempvar _i tint)\n                             (Econst_int (Int.repr 0) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Ssequence\n                  (Sset _t'1\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _s (tptr tuchar))\n                        (Ebinop Odiv (Etempvar _i tint)\n                          (Econst_int (Int.repr 8) tint) tint) (tptr tuchar))\n                      tuchar))\n                  (Sset _b\n                    (Ecast\n                      (Ebinop Oand\n                        (Ebinop Oshr (Etempvar _t'1 tuchar)\n                          (Ebinop Oand (Etempvar _i tint)\n                            (Econst_int (Int.repr 7) tint) tint) tint)\n                        (Econst_int (Int.repr 1) tint) tint) tuchar)))\n                (Ssequence\n                  (Scall None\n                    (Evar _cswap (Tfunction\n                                   (Tcons (tptr (tarray tlong 16))\n                                     (Tcons (tptr (tarray tlong 16))\n                                       (Tcons tuchar Tnil))) tvoid\n                                   cc_default))\n                    ((Etempvar _p (tptr (tarray tlong 16))) ::\n                     (Etempvar _q (tptr (tarray tlong 16))) ::\n                     (Etempvar _b tuchar) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _add (Tfunction\n                                   (Tcons (tptr (tarray tlong 16))\n                                     (Tcons (tptr (tarray tlong 16)) Tnil))\n                                   tvoid cc_default))\n                      ((Etempvar _q (tptr (tarray tlong 16))) ::\n                       (Etempvar _p (tptr (tarray tlong 16))) :: nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _add (Tfunction\n                                     (Tcons (tptr (tarray tlong 16))\n                                       (Tcons (tptr (tarray tlong 16)) Tnil))\n                                     tvoid cc_default))\n                        ((Etempvar _p (tptr (tarray tlong 16))) ::\n                         (Etempvar _p (tptr (tarray tlong 16))) :: nil))\n                      (Scall None\n                        (Evar _cswap (Tfunction\n                                       (Tcons (tptr (tarray tlong 16))\n                                         (Tcons (tptr (tarray tlong 16))\n                                           (Tcons tuchar Tnil))) tvoid\n                                       cc_default))\n                        ((Etempvar _p (tptr (tarray tlong 16))) ::\n                         (Etempvar _q (tptr (tarray tlong 16))) ::\n                         (Etempvar _b tuchar) :: nil)))))))\n            (Sset _i\n              (Ebinop Osub (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint))))))))\n|}.\n\nDefinition f_scalarbase := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_p, (tptr (tarray tlong 16))) :: (_s, (tptr tuchar)) :: nil);\n  fn_vars := ((_q, (tarray (tarray tlong 16) 4)) :: nil);\n  fn_temps := nil;\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _set25519 (Tfunction (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                      tvoid cc_default))\n    ((Ederef\n       (Ebinop Oadd (Evar _q (tarray (tarray tlong 16) 4))\n         (Econst_int (Int.repr 0) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) :: (Evar _X (tarray tlong 16)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _set25519 (Tfunction\n                        (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)) tvoid\n                        cc_default))\n      ((Ederef\n         (Ebinop Oadd (Evar _q (tarray (tarray tlong 16) 4))\n           (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) :: (Evar _Y (tarray tlong 16)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _set25519 (Tfunction\n                          (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                          tvoid cc_default))\n        ((Ederef\n           (Ebinop Oadd (Evar _q (tarray (tarray tlong 16) 4))\n             (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n           (tarray tlong 16)) :: (Evar _gf1 (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _M (Tfunction\n                     (Tcons (tptr tlong)\n                       (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                     cc_default))\n          ((Ederef\n             (Ebinop Oadd (Evar _q (tarray (tarray tlong 16) 4))\n               (Econst_int (Int.repr 3) tint) (tptr (tarray tlong 16)))\n             (tarray tlong 16)) :: (Evar _X (tarray tlong 16)) ::\n           (Evar _Y (tarray tlong 16)) :: nil))\n        (Scall None\n          (Evar _scalarmult (Tfunction\n                              (Tcons (tptr (tarray tlong 16))\n                                (Tcons (tptr (tarray tlong 16))\n                                  (Tcons (tptr tuchar) Tnil))) tvoid\n                              cc_default))\n          ((Etempvar _p (tptr (tarray tlong 16))) ::\n           (Evar _q (tarray (tarray tlong 16) 4)) ::\n           (Etempvar _s (tptr tuchar)) :: nil))))))\n|}.\n\nDefinition f_crypto_sign_ed25519_tweet_keypair := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_pk, (tptr tuchar)) :: (_sk, (tptr tuchar)) :: nil);\n  fn_vars := ((_d, (tarray tuchar 64)) ::\n              (_p, (tarray (tarray tlong 16) 4)) :: nil);\n  fn_temps := ((_i, tint) :: (_t'4, tuchar) :: (_t'3, tuchar) ::\n               (_t'2, tuchar) :: (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _randombytes (Tfunction (Tcons (tptr tuchar) (Tcons tulong Tnil))\n                         tvoid cc_default))\n    ((Etempvar _sk (tptr tuchar)) :: (Econst_int (Int.repr 32) tint) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _crypto_hash_sha512_tweet (Tfunction\n                                        (Tcons (tptr tuchar)\n                                          (Tcons (tptr tuchar)\n                                            (Tcons tulong Tnil))) tint\n                                        cc_default))\n      ((Evar _d (tarray tuchar 64)) :: (Etempvar _sk (tptr tuchar)) ::\n       (Econst_int (Int.repr 32) tint) :: nil))\n    (Ssequence\n      (Ssequence\n        (Sset _t'4\n          (Ederef\n            (Ebinop Oadd (Evar _d (tarray tuchar 64))\n              (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar))\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Evar _d (tarray tuchar 64))\n              (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar)\n          (Ebinop Oand (Etempvar _t'4 tuchar)\n            (Econst_int (Int.repr 248) tint) tint)))\n      (Ssequence\n        (Ssequence\n          (Sset _t'3\n            (Ederef\n              (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n            (Ebinop Oand (Etempvar _t'3 tuchar)\n              (Econst_int (Int.repr 127) tint) tint)))\n        (Ssequence\n          (Ssequence\n            (Sset _t'2\n              (Ederef\n                (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                  (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                  (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n              (Ebinop Oor (Etempvar _t'2 tuchar)\n                (Econst_int (Int.repr 64) tint) tint)))\n          (Ssequence\n            (Scall None\n              (Evar _scalarbase (Tfunction\n                                  (Tcons (tptr (tarray tlong 16))\n                                    (Tcons (tptr tuchar) Tnil)) tvoid\n                                  cc_default))\n              ((Evar _p (tarray (tarray tlong 16) 4)) ::\n               (Evar _d (tarray tuchar 64)) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _pack (Tfunction\n                              (Tcons (tptr tuchar)\n                                (Tcons (tptr (tarray tlong 16)) Tnil)) tvoid\n                              cc_default))\n                ((Etempvar _pk (tptr tuchar)) ::\n                 (Evar _p (tarray (tarray tlong 16) 4)) :: nil))\n              (Ssequence\n                (Ssequence\n                  (Sset _i (Econst_int (Int.repr 0) tint))\n                  (Sloop\n                    (Ssequence\n                      (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                     (Econst_int (Int.repr 32) tint) tint)\n                        Sskip\n                        Sbreak)\n                      (Ssequence\n                        (Sset _t'1\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _pk (tptr tuchar))\n                              (Etempvar _i tint) (tptr tuchar)) tuchar))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _sk (tptr tuchar))\n                              (Ebinop Oadd (Econst_int (Int.repr 32) tint)\n                                (Etempvar _i tint) tint) (tptr tuchar))\n                            tuchar) (Etempvar _t'1 tuchar))))\n                    (Sset _i\n                      (Ebinop Oadd (Etempvar _i tint)\n                        (Econst_int (Int.repr 1) tint) tint))))\n                (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))))))\n|}.\n\nDefinition v_L := {|\n  gvar_info := (tarray tulong 32);\n  gvar_init := (Init_int64 (Int64.repr 237) :: Init_int64 (Int64.repr 211) ::\n                Init_int64 (Int64.repr 245) :: Init_int64 (Int64.repr 92) ::\n                Init_int64 (Int64.repr 26) :: Init_int64 (Int64.repr 99) ::\n                Init_int64 (Int64.repr 18) :: Init_int64 (Int64.repr 88) ::\n                Init_int64 (Int64.repr 214) :: Init_int64 (Int64.repr 156) ::\n                Init_int64 (Int64.repr 247) :: Init_int64 (Int64.repr 162) ::\n                Init_int64 (Int64.repr 222) :: Init_int64 (Int64.repr 249) ::\n                Init_int64 (Int64.repr 222) :: Init_int64 (Int64.repr 20) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 0) ::\n                Init_int64 (Int64.repr 0) :: Init_int64 (Int64.repr 16) ::\n                nil);\n  gvar_readonly := true;\n  gvar_volatile := false\n|}.\n\nDefinition f_modL := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_r, (tptr tuchar)) :: (_x, (tptr tlong)) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_carry, tlong) :: (_i, tlong) :: (_j, tlong) ::\n               (_t'16, tulong) :: (_t'15, tlong) :: (_t'14, tlong) ::\n               (_t'13, tlong) :: (_t'12, tlong) :: (_t'11, tlong) ::\n               (_t'10, tulong) :: (_t'9, tlong) :: (_t'8, tlong) ::\n               (_t'7, tlong) :: (_t'6, tlong) :: (_t'5, tulong) ::\n               (_t'4, tlong) :: (_t'3, tlong) :: (_t'2, tlong) ::\n               (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Ecast (Econst_int (Int.repr 63) tint) tlong))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Oge (Etempvar _i tlong)\n                       (Econst_int (Int.repr 32) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _carry (Ecast (Econst_int (Int.repr 0) tint) tlong))\n          (Ssequence\n            (Ssequence\n              (Sset _j\n                (Ebinop Osub (Etempvar _i tlong)\n                  (Econst_int (Int.repr 32) tint) tlong))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _j tlong)\n                                 (Ebinop Osub (Etempvar _i tlong)\n                                   (Econst_int (Int.repr 12) tint) tlong)\n                                 tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Ssequence\n                      (Sset _t'14\n                        (Ederef\n                          (Ebinop Oadd (Etempvar _x (tptr tlong))\n                            (Etempvar _j tlong) (tptr tlong)) tlong))\n                      (Ssequence\n                        (Sset _t'15\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _x (tptr tlong))\n                              (Etempvar _i tlong) (tptr tlong)) tlong))\n                        (Ssequence\n                          (Sset _t'16\n                            (Ederef\n                              (Ebinop Oadd (Evar _L (tarray tulong 32))\n                                (Ebinop Osub (Etempvar _j tlong)\n                                  (Ebinop Osub (Etempvar _i tlong)\n                                    (Econst_int (Int.repr 32) tint) tlong)\n                                  tlong) (tptr tulong)) tulong))\n                          (Sassign\n                            (Ederef\n                              (Ebinop Oadd (Etempvar _x (tptr tlong))\n                                (Etempvar _j tlong) (tptr tlong)) tlong)\n                            (Ebinop Oadd (Etempvar _t'14 tlong)\n                              (Ebinop Osub (Etempvar _carry tlong)\n                                (Ebinop Omul\n                                  (Ebinop Omul\n                                    (Econst_int (Int.repr 16) tint)\n                                    (Etempvar _t'15 tlong) tlong)\n                                  (Etempvar _t'16 tulong) tulong) tulong)\n                              tulong)))))\n                    (Ssequence\n                      (Ssequence\n                        (Sset _t'13\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _x (tptr tlong))\n                              (Etempvar _j tlong) (tptr tlong)) tlong))\n                        (Sset _carry\n                          (Ebinop Oshr\n                            (Ebinop Oadd (Etempvar _t'13 tlong)\n                              (Econst_int (Int.repr 128) tint) tlong)\n                            (Econst_int (Int.repr 8) tint) tlong)))\n                      (Ssequence\n                        (Sset _t'12\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _x (tptr tlong))\n                              (Etempvar _j tlong) (tptr tlong)) tlong))\n                        (Sassign\n                          (Ederef\n                            (Ebinop Oadd (Etempvar _x (tptr tlong))\n                              (Etempvar _j tlong) (tptr tlong)) tlong)\n                          (Ebinop Osub (Etempvar _t'12 tlong)\n                            (Ebinop Oshl (Etempvar _carry tlong)\n                              (Econst_int (Int.repr 8) tint) tlong) tlong))))))\n                (Sset _j\n                  (Ebinop Oadd (Etempvar _j tlong)\n                    (Econst_int (Int.repr 1) tint) tlong))))\n            (Ssequence\n              (Ssequence\n                (Sset _t'11\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _x (tptr tlong))\n                      (Etempvar _j tlong) (tptr tlong)) tlong))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _x (tptr tlong))\n                      (Etempvar _j tlong) (tptr tlong)) tlong)\n                  (Ebinop Oadd (Etempvar _t'11 tlong) (Etempvar _carry tlong)\n                    tlong)))\n              (Sassign\n                (Ederef\n                  (Ebinop Oadd (Etempvar _x (tptr tlong)) (Etempvar _i tlong)\n                    (tptr tlong)) tlong) (Econst_int (Int.repr 0) tint))))))\n      (Sset _i\n        (Ebinop Osub (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n          tlong))))\n  (Ssequence\n    (Sset _carry (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Ssequence\n      (Ssequence\n        (Sset _j (Ecast (Econst_int (Int.repr 0) tint) tlong))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Olt (Etempvar _j tlong)\n                           (Econst_int (Int.repr 32) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Ssequence\n                (Sset _t'8\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _x (tptr tlong))\n                      (Etempvar _j tlong) (tptr tlong)) tlong))\n                (Ssequence\n                  (Sset _t'9\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Econst_int (Int.repr 31) tint) (tptr tlong)) tlong))\n                  (Ssequence\n                    (Sset _t'10\n                      (Ederef\n                        (Ebinop Oadd (Evar _L (tarray tulong 32))\n                          (Etempvar _j tlong) (tptr tulong)) tulong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _x (tptr tlong))\n                          (Etempvar _j tlong) (tptr tlong)) tlong)\n                      (Ebinop Oadd (Etempvar _t'8 tlong)\n                        (Ebinop Osub (Etempvar _carry tlong)\n                          (Ebinop Omul\n                            (Ebinop Oshr (Etempvar _t'9 tlong)\n                              (Econst_int (Int.repr 4) tint) tlong)\n                            (Etempvar _t'10 tulong) tulong) tulong) tulong)))))\n              (Ssequence\n                (Ssequence\n                  (Sset _t'7\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Etempvar _j tlong) (tptr tlong)) tlong))\n                  (Sset _carry\n                    (Ebinop Oshr (Etempvar _t'7 tlong)\n                      (Econst_int (Int.repr 8) tint) tlong)))\n                (Ssequence\n                  (Sset _t'6\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Etempvar _j tlong) (tptr tlong)) tlong))\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Etempvar _j tlong) (tptr tlong)) tlong)\n                    (Ebinop Oand (Etempvar _t'6 tlong)\n                      (Econst_int (Int.repr 255) tint) tlong))))))\n          (Sset _j\n            (Ebinop Oadd (Etempvar _j tlong) (Econst_int (Int.repr 1) tint)\n              tlong))))\n      (Ssequence\n        (Ssequence\n          (Sset _j (Ecast (Econst_int (Int.repr 0) tint) tlong))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _j tlong)\n                             (Econst_int (Int.repr 32) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'4\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _x (tptr tlong))\n                      (Etempvar _j tlong) (tptr tlong)) tlong))\n                (Ssequence\n                  (Sset _t'5\n                    (Ederef\n                      (Ebinop Oadd (Evar _L (tarray tulong 32))\n                        (Etempvar _j tlong) (tptr tulong)) tulong))\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Etempvar _j tlong) (tptr tlong)) tlong)\n                    (Ebinop Osub (Etempvar _t'4 tlong)\n                      (Ebinop Omul (Etempvar _carry tlong)\n                        (Etempvar _t'5 tulong) tulong) tulong)))))\n            (Sset _j\n              (Ebinop Oadd (Etempvar _j tlong) (Econst_int (Int.repr 1) tint)\n                tlong))))\n        (Ssequence\n          (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                             (Econst_int (Int.repr 32) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Ssequence\n                  (Sset _t'2\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Ebinop Oadd (Etempvar _i tlong)\n                          (Econst_int (Int.repr 1) tint) tlong) (tptr tlong))\n                      tlong))\n                  (Ssequence\n                    (Sset _t'3\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _x (tptr tlong))\n                          (Etempvar _i tlong) (tptr tlong)) tlong))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _x (tptr tlong))\n                          (Ebinop Oadd (Etempvar _i tlong)\n                            (Econst_int (Int.repr 1) tint) tlong)\n                          (tptr tlong)) tlong)\n                      (Ebinop Oadd (Etempvar _t'2 tlong)\n                        (Ebinop Oshr (Etempvar _t'3 tlong)\n                          (Econst_int (Int.repr 8) tint) tlong) tlong))))\n                (Ssequence\n                  (Sset _t'1\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _x (tptr tlong))\n                        (Etempvar _i tlong) (tptr tlong)) tlong))\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _r (tptr tuchar))\n                        (Etempvar _i tlong) (tptr tuchar)) tuchar)\n                    (Ebinop Oand (Etempvar _t'1 tlong)\n                      (Econst_int (Int.repr 255) tint) tlong)))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n                tlong))))))))\n|}.\n\nDefinition f_reduce := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_r, (tptr tuchar)) :: nil);\n  fn_vars := ((_x, (tarray tlong 64)) :: nil);\n  fn_temps := ((_i, tlong) :: (_t'1, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                       (Econst_int (Int.repr 64) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Sset _t'1\n            (Ederef\n              (Ebinop Oadd (Etempvar _r (tptr tuchar)) (Etempvar _i tlong)\n                (tptr tuchar)) tuchar))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _x (tarray tlong 64)) (Etempvar _i tlong)\n                (tptr tlong)) tlong) (Ecast (Etempvar _t'1 tuchar) tulong))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n          tlong))))\n  (Ssequence\n    (Ssequence\n      (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n      (Sloop\n        (Ssequence\n          (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                         (Econst_int (Int.repr 64) tint) tint)\n            Sskip\n            Sbreak)\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Etempvar _r (tptr tuchar)) (Etempvar _i tlong)\n                (tptr tuchar)) tuchar) (Econst_int (Int.repr 0) tint)))\n        (Sset _i\n          (Ebinop Oadd (Etempvar _i tlong) (Econst_int (Int.repr 1) tint)\n            tlong))))\n    (Scall None\n      (Evar _modL (Tfunction (Tcons (tptr tuchar) (Tcons (tptr tlong) Tnil))\n                    tvoid cc_default))\n      ((Etempvar _r (tptr tuchar)) :: (Evar _x (tarray tlong 64)) :: nil))))\n|}.\n\nDefinition f_crypto_sign_ed25519_tweet := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_sm, (tptr tuchar)) :: (_smlen, (tptr tulong)) ::\n                (_m, (tptr tuchar)) :: (_n, tulong) ::\n                (_sk, (tptr tuchar)) :: nil);\n  fn_vars := ((_d, (tarray tuchar 64)) :: (_h, (tarray tuchar 64)) ::\n              (_r, (tarray tuchar 64)) :: (_x, (tarray tlong 64)) ::\n              (_p, (tarray (tarray tlong 16) 4)) :: nil);\n  fn_temps := ((_i, tlong) :: (_j, tlong) :: (_t'10, tuchar) ::\n               (_t'9, tuchar) :: (_t'8, tuchar) :: (_t'7, tuchar) ::\n               (_t'6, tuchar) :: (_t'5, tuchar) :: (_t'4, tuchar) ::\n               (_t'3, tuchar) :: (_t'2, tuchar) :: (_t'1, tlong) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _crypto_hash_sha512_tweet (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons (tptr tuchar)\n                                          (Tcons tulong Tnil))) tint\n                                      cc_default))\n    ((Evar _d (tarray tuchar 64)) :: (Etempvar _sk (tptr tuchar)) ::\n     (Econst_int (Int.repr 32) tint) :: nil))\n  (Ssequence\n    (Ssequence\n      (Sset _t'10\n        (Ederef\n          (Ebinop Oadd (Evar _d (tarray tuchar 64))\n            (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar))\n      (Sassign\n        (Ederef\n          (Ebinop Oadd (Evar _d (tarray tuchar 64))\n            (Econst_int (Int.repr 0) tint) (tptr tuchar)) tuchar)\n        (Ebinop Oand (Etempvar _t'10 tuchar) (Econst_int (Int.repr 248) tint)\n          tint)))\n    (Ssequence\n      (Ssequence\n        (Sset _t'9\n          (Ederef\n            (Ebinop Oadd (Evar _d (tarray tuchar 64))\n              (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n        (Sassign\n          (Ederef\n            (Ebinop Oadd (Evar _d (tarray tuchar 64))\n              (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n          (Ebinop Oand (Etempvar _t'9 tuchar)\n            (Econst_int (Int.repr 127) tint) tint)))\n      (Ssequence\n        (Ssequence\n          (Sset _t'8\n            (Ederef\n              (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar))\n          (Sassign\n            (Ederef\n              (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                (Econst_int (Int.repr 31) tint) (tptr tuchar)) tuchar)\n            (Ebinop Oor (Etempvar _t'8 tuchar)\n              (Econst_int (Int.repr 64) tint) tint)))\n        (Ssequence\n          (Sassign (Ederef (Etempvar _smlen (tptr tulong)) tulong)\n            (Ebinop Oadd (Etempvar _n tulong) (Econst_int (Int.repr 64) tint)\n              tulong))\n          (Ssequence\n            (Ssequence\n              (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n              (Sloop\n                (Ssequence\n                  (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                                 (Etempvar _n tulong) tint)\n                    Sskip\n                    Sbreak)\n                  (Ssequence\n                    (Sset _t'7\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                          (Etempvar _i tlong) (tptr tuchar)) tuchar))\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                          (Ebinop Oadd (Econst_int (Int.repr 64) tint)\n                            (Etempvar _i tlong) tlong) (tptr tuchar)) tuchar)\n                      (Etempvar _t'7 tuchar))))\n                (Sset _i\n                  (Ebinop Oadd (Etempvar _i tlong)\n                    (Econst_int (Int.repr 1) tint) tlong))))\n            (Ssequence\n              (Ssequence\n                (Sset _i (Ecast (Econst_int (Int.repr 0) tint) tlong))\n                (Sloop\n                  (Ssequence\n                    (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                                   (Econst_int (Int.repr 32) tint) tint)\n                      Sskip\n                      Sbreak)\n                    (Ssequence\n                      (Sset _t'6\n                        (Ederef\n                          (Ebinop Oadd (Evar _d (tarray tuchar 64))\n                            (Ebinop Oadd (Econst_int (Int.repr 32) tint)\n                              (Etempvar _i tlong) tlong) (tptr tuchar))\n                          tuchar))\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                            (Ebinop Oadd (Econst_int (Int.repr 32) tint)\n                              (Etempvar _i tlong) tlong) (tptr tuchar))\n                          tuchar) (Etempvar _t'6 tuchar))))\n                  (Sset _i\n                    (Ebinop Oadd (Etempvar _i tlong)\n                      (Econst_int (Int.repr 1) tint) tlong))))\n              (Ssequence\n                (Scall None\n                  (Evar _crypto_hash_sha512_tweet (Tfunction\n                                                    (Tcons (tptr tuchar)\n                                                      (Tcons (tptr tuchar)\n                                                        (Tcons tulong Tnil)))\n                                                    tint cc_default))\n                  ((Evar _r (tarray tuchar 64)) ::\n                   (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                     (Econst_int (Int.repr 32) tint) (tptr tuchar)) ::\n                   (Ebinop Oadd (Etempvar _n tulong)\n                     (Econst_int (Int.repr 32) tint) tulong) :: nil))\n                (Ssequence\n                  (Scall None\n                    (Evar _reduce (Tfunction (Tcons (tptr tuchar) Tnil) tvoid\n                                    cc_default))\n                    ((Evar _r (tarray tuchar 64)) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _scalarbase (Tfunction\n                                          (Tcons (tptr (tarray tlong 16))\n                                            (Tcons (tptr tuchar) Tnil)) tvoid\n                                          cc_default))\n                      ((Evar _p (tarray (tarray tlong 16) 4)) ::\n                       (Evar _r (tarray tuchar 64)) :: nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _pack (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons (tptr (tarray tlong 16)) Tnil))\n                                      tvoid cc_default))\n                        ((Etempvar _sm (tptr tuchar)) ::\n                         (Evar _p (tarray (tarray tlong 16) 4)) :: nil))\n                      (Ssequence\n                        (Ssequence\n                          (Sset _i\n                            (Ecast (Econst_int (Int.repr 0) tint) tlong))\n                          (Sloop\n                            (Ssequence\n                              (Sifthenelse (Ebinop Olt (Etempvar _i tlong)\n                                             (Econst_int (Int.repr 32) tint)\n                                             tint)\n                                Sskip\n                                Sbreak)\n                              (Ssequence\n                                (Sset _t'5\n                                  (Ederef\n                                    (Ebinop Oadd (Etempvar _sk (tptr tuchar))\n                                      (Ebinop Oadd (Etempvar _i tlong)\n                                        (Econst_int (Int.repr 32) tint)\n                                        tlong) (tptr tuchar)) tuchar))\n                                (Sassign\n                                  (Ederef\n                                    (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                                      (Ebinop Oadd (Etempvar _i tlong)\n                                        (Econst_int (Int.repr 32) tint)\n                                        tlong) (tptr tuchar)) tuchar)\n                                  (Etempvar _t'5 tuchar))))\n                            (Sset _i\n                              (Ebinop Oadd (Etempvar _i tlong)\n                                (Econst_int (Int.repr 1) tint) tlong))))\n                        (Ssequence\n                          (Scall None\n                            (Evar _crypto_hash_sha512_tweet (Tfunction\n                                                              (Tcons\n                                                                (tptr tuchar)\n                                                                (Tcons\n                                                                  (tptr tuchar)\n                                                                  (Tcons\n                                                                    tulong\n                                                                    Tnil)))\n                                                              tint\n                                                              cc_default))\n                            ((Evar _h (tarray tuchar 64)) ::\n                             (Etempvar _sm (tptr tuchar)) ::\n                             (Ebinop Oadd (Etempvar _n tulong)\n                               (Econst_int (Int.repr 64) tint) tulong) ::\n                             nil))\n                          (Ssequence\n                            (Scall None\n                              (Evar _reduce (Tfunction\n                                              (Tcons (tptr tuchar) Tnil)\n                                              tvoid cc_default))\n                              ((Evar _h (tarray tuchar 64)) :: nil))\n                            (Ssequence\n                              (Ssequence\n                                (Sset _i\n                                  (Ecast (Econst_int (Int.repr 0) tint)\n                                    tlong))\n                                (Sloop\n                                  (Ssequence\n                                    (Sifthenelse (Ebinop Olt\n                                                   (Etempvar _i tlong)\n                                                   (Econst_int (Int.repr 64) tint)\n                                                   tint)\n                                      Sskip\n                                      Sbreak)\n                                    (Sassign\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Evar _x (tarray tlong 64))\n                                          (Etempvar _i tlong) (tptr tlong))\n                                        tlong)\n                                      (Econst_int (Int.repr 0) tint)))\n                                  (Sset _i\n                                    (Ebinop Oadd (Etempvar _i tlong)\n                                      (Econst_int (Int.repr 1) tint) tlong))))\n                              (Ssequence\n                                (Ssequence\n                                  (Sset _i\n                                    (Ecast (Econst_int (Int.repr 0) tint)\n                                      tlong))\n                                  (Sloop\n                                    (Ssequence\n                                      (Sifthenelse (Ebinop Olt\n                                                     (Etempvar _i tlong)\n                                                     (Econst_int (Int.repr 32) tint)\n                                                     tint)\n                                        Sskip\n                                        Sbreak)\n                                      (Ssequence\n                                        (Sset _t'4\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _r (tarray tuchar 64))\n                                              (Etempvar _i tlong)\n                                              (tptr tuchar)) tuchar))\n                                        (Sassign\n                                          (Ederef\n                                            (Ebinop Oadd\n                                              (Evar _x (tarray tlong 64))\n                                              (Etempvar _i tlong)\n                                              (tptr tlong)) tlong)\n                                          (Ecast (Etempvar _t'4 tuchar)\n                                            tulong))))\n                                    (Sset _i\n                                      (Ebinop Oadd (Etempvar _i tlong)\n                                        (Econst_int (Int.repr 1) tint) tlong))))\n                                (Ssequence\n                                  (Ssequence\n                                    (Sset _i\n                                      (Ecast (Econst_int (Int.repr 0) tint)\n                                        tlong))\n                                    (Sloop\n                                      (Ssequence\n                                        (Sifthenelse (Ebinop Olt\n                                                       (Etempvar _i tlong)\n                                                       (Econst_int (Int.repr 32) tint)\n                                                       tint)\n                                          Sskip\n                                          Sbreak)\n                                        (Ssequence\n                                          (Sset _j\n                                            (Ecast\n                                              (Econst_int (Int.repr 0) tint)\n                                              tlong))\n                                          (Sloop\n                                            (Ssequence\n                                              (Sifthenelse (Ebinop Olt\n                                                             (Etempvar _j tlong)\n                                                             (Econst_int (Int.repr 32) tint)\n                                                             tint)\n                                                Sskip\n                                                Sbreak)\n                                              (Ssequence\n                                                (Sset _t'1\n                                                  (Ederef\n                                                    (Ebinop Oadd\n                                                      (Evar _x (tarray tlong 64))\n                                                      (Ebinop Oadd\n                                                        (Etempvar _i tlong)\n                                                        (Etempvar _j tlong)\n                                                        tlong) (tptr tlong))\n                                                    tlong))\n                                                (Ssequence\n                                                  (Sset _t'2\n                                                    (Ederef\n                                                      (Ebinop Oadd\n                                                        (Evar _h (tarray tuchar 64))\n                                                        (Etempvar _i tlong)\n                                                        (tptr tuchar))\n                                                      tuchar))\n                                                  (Ssequence\n                                                    (Sset _t'3\n                                                      (Ederef\n                                                        (Ebinop Oadd\n                                                          (Evar _d (tarray tuchar 64))\n                                                          (Etempvar _j tlong)\n                                                          (tptr tuchar))\n                                                        tuchar))\n                                                    (Sassign\n                                                      (Ederef\n                                                        (Ebinop Oadd\n                                                          (Evar _x (tarray tlong 64))\n                                                          (Ebinop Oadd\n                                                            (Etempvar _i tlong)\n                                                            (Etempvar _j tlong)\n                                                            tlong)\n                                                          (tptr tlong))\n                                                        tlong)\n                                                      (Ebinop Oadd\n                                                        (Etempvar _t'1 tlong)\n                                                        (Ebinop Omul\n                                                          (Etempvar _t'2 tuchar)\n                                                          (Ecast\n                                                            (Etempvar _t'3 tuchar)\n                                                            tulong) tulong)\n                                                        tulong))))))\n                                            (Sset _j\n                                              (Ebinop Oadd\n                                                (Etempvar _j tlong)\n                                                (Econst_int (Int.repr 1) tint)\n                                                tlong)))))\n                                      (Sset _i\n                                        (Ebinop Oadd (Etempvar _i tlong)\n                                          (Econst_int (Int.repr 1) tint)\n                                          tlong))))\n                                  (Ssequence\n                                    (Scall None\n                                      (Evar _modL (Tfunction\n                                                    (Tcons (tptr tuchar)\n                                                      (Tcons (tptr tlong)\n                                                        Tnil)) tvoid\n                                                    cc_default))\n                                      ((Ebinop Oadd\n                                         (Etempvar _sm (tptr tuchar))\n                                         (Econst_int (Int.repr 32) tint)\n                                         (tptr tuchar)) ::\n                                       (Evar _x (tarray tlong 64)) :: nil))\n                                    (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))))))))))))))))\n|}.\n\nDefinition f_unpackneg := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_r, (tptr (tarray tlong 16))) :: (_p, (tptr tuchar)) :: nil);\n  fn_vars := ((_t, (tarray tlong 16)) :: (_chk, (tarray tlong 16)) ::\n              (_num, (tarray tlong 16)) :: (_den, (tarray tlong 16)) ::\n              (_den2, (tarray tlong 16)) :: (_den4, (tarray tlong 16)) ::\n              (_den6, (tarray tlong 16)) :: nil);\n  fn_temps := ((_t'3, tuchar) :: (_t'2, tint) :: (_t'1, tint) ::\n               (_t'4, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall None\n    (Evar _set25519 (Tfunction (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                      tvoid cc_default))\n    ((Ederef\n       (Ebinop Oadd (Etempvar _r (tptr (tarray tlong 16)))\n         (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n       (tarray tlong 16)) :: (Evar _gf1 (tarray tlong 16)) :: nil))\n  (Ssequence\n    (Scall None\n      (Evar _unpack25519 (Tfunction\n                           (Tcons (tptr tlong) (Tcons (tptr tuchar) Tnil))\n                           tvoid cc_default))\n      ((Ederef\n         (Ebinop Oadd (Etempvar _r (tptr (tarray tlong 16)))\n           (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n         (tarray tlong 16)) :: (Etempvar _p (tptr tuchar)) :: nil))\n    (Ssequence\n      (Scall None\n        (Evar _S (Tfunction (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                   tvoid cc_default))\n        ((Evar _num (tarray tlong 16)) ::\n         (Ederef\n           (Ebinop Oadd (Etempvar _r (tptr (tarray tlong 16)))\n             (Econst_int (Int.repr 1) tint) (tptr (tarray tlong 16)))\n           (tarray tlong 16)) :: nil))\n      (Ssequence\n        (Scall None\n          (Evar _M (Tfunction\n                     (Tcons (tptr tlong)\n                       (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))) tvoid\n                     cc_default))\n          ((Evar _den (tarray tlong 16)) :: (Evar _num (tarray tlong 16)) ::\n           (Evar _D (tarray tlong 16)) :: nil))\n        (Ssequence\n          (Scall None\n            (Evar _Z (Tfunction\n                       (Tcons (tptr tlong)\n                         (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                       tvoid cc_default))\n            ((Evar _num (tarray tlong 16)) ::\n             (Evar _num (tarray tlong 16)) ::\n             (Ederef\n               (Ebinop Oadd (Etempvar _r (tptr (tarray tlong 16)))\n                 (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n               (tarray tlong 16)) :: nil))\n          (Ssequence\n            (Scall None\n              (Evar _A (Tfunction\n                         (Tcons (tptr tlong)\n                           (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil)))\n                         tvoid cc_default))\n              ((Evar _den (tarray tlong 16)) ::\n               (Ederef\n                 (Ebinop Oadd (Etempvar _r (tptr (tarray tlong 16)))\n                   (Econst_int (Int.repr 2) tint) (tptr (tarray tlong 16)))\n                 (tarray tlong 16)) :: (Evar _den (tarray tlong 16)) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _S (Tfunction\n                           (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                           tvoid cc_default))\n                ((Evar _den2 (tarray tlong 16)) ::\n                 (Evar _den (tarray tlong 16)) :: nil))\n              (Ssequence\n                (Scall None\n                  (Evar _S (Tfunction\n                             (Tcons (tptr tlong) (Tcons (tptr tlong) Tnil))\n                             tvoid cc_default))\n                  ((Evar _den4 (tarray tlong 16)) ::\n                   (Evar _den2 (tarray tlong 16)) :: nil))\n                (Ssequence\n                  (Scall None\n                    (Evar _M (Tfunction\n                               (Tcons (tptr tlong)\n                                 (Tcons (tptr tlong)\n                                   (Tcons (tptr tlong) Tnil))) tvoid\n                               cc_default))\n                    ((Evar _den6 (tarray tlong 16)) ::\n                     (Evar _den4 (tarray tlong 16)) ::\n                     (Evar _den2 (tarray tlong 16)) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _M (Tfunction\n                                 (Tcons (tptr tlong)\n                                   (Tcons (tptr tlong)\n                                     (Tcons (tptr tlong) Tnil))) tvoid\n                                 cc_default))\n                      ((Evar _t (tarray tlong 16)) ::\n                       (Evar _den6 (tarray tlong 16)) ::\n                       (Evar _num (tarray tlong 16)) :: nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _M (Tfunction\n                                   (Tcons (tptr tlong)\n                                     (Tcons (tptr tlong)\n                                       (Tcons (tptr tlong) Tnil))) tvoid\n                                   cc_default))\n                        ((Evar _t (tarray tlong 16)) ::\n                         (Evar _t (tarray tlong 16)) ::\n                         (Evar _den (tarray tlong 16)) :: nil))\n                      (Ssequence\n                        (Scall None\n                          (Evar _pow2523 (Tfunction\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong) Tnil)) tvoid\n                                           cc_default))\n                          ((Evar _t (tarray tlong 16)) ::\n                           (Evar _t (tarray tlong 16)) :: nil))\n                        (Ssequence\n                          (Scall None\n                            (Evar _M (Tfunction\n                                       (Tcons (tptr tlong)\n                                         (Tcons (tptr tlong)\n                                           (Tcons (tptr tlong) Tnil))) tvoid\n                                       cc_default))\n                            ((Evar _t (tarray tlong 16)) ::\n                             (Evar _t (tarray tlong 16)) ::\n                             (Evar _num (tarray tlong 16)) :: nil))\n                          (Ssequence\n                            (Scall None\n                              (Evar _M (Tfunction\n                                         (Tcons (tptr tlong)\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong) Tnil)))\n                                         tvoid cc_default))\n                              ((Evar _t (tarray tlong 16)) ::\n                               (Evar _t (tarray tlong 16)) ::\n                               (Evar _den (tarray tlong 16)) :: nil))\n                            (Ssequence\n                              (Scall None\n                                (Evar _M (Tfunction\n                                           (Tcons (tptr tlong)\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong) Tnil)))\n                                           tvoid cc_default))\n                                ((Evar _t (tarray tlong 16)) ::\n                                 (Evar _t (tarray tlong 16)) ::\n                                 (Evar _den (tarray tlong 16)) :: nil))\n                              (Ssequence\n                                (Scall None\n                                  (Evar _M (Tfunction\n                                             (Tcons (tptr tlong)\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong) Tnil)))\n                                             tvoid cc_default))\n                                  ((Ederef\n                                     (Ebinop Oadd\n                                       (Etempvar _r (tptr (tarray tlong 16)))\n                                       (Econst_int (Int.repr 0) tint)\n                                       (tptr (tarray tlong 16)))\n                                     (tarray tlong 16)) ::\n                                   (Evar _t (tarray tlong 16)) ::\n                                   (Evar _den (tarray tlong 16)) :: nil))\n                                (Ssequence\n                                  (Scall None\n                                    (Evar _S (Tfunction\n                                               (Tcons (tptr tlong)\n                                                 (Tcons (tptr tlong) Tnil))\n                                               tvoid cc_default))\n                                    ((Evar _chk (tarray tlong 16)) ::\n                                     (Ederef\n                                       (Ebinop Oadd\n                                         (Etempvar _r (tptr (tarray tlong 16)))\n                                         (Econst_int (Int.repr 0) tint)\n                                         (tptr (tarray tlong 16)))\n                                       (tarray tlong 16)) :: nil))\n                                  (Ssequence\n                                    (Scall None\n                                      (Evar _M (Tfunction\n                                                 (Tcons (tptr tlong)\n                                                   (Tcons (tptr tlong)\n                                                     (Tcons (tptr tlong)\n                                                       Tnil))) tvoid\n                                                 cc_default))\n                                      ((Evar _chk (tarray tlong 16)) ::\n                                       (Evar _chk (tarray tlong 16)) ::\n                                       (Evar _den (tarray tlong 16)) :: nil))\n                                    (Ssequence\n                                      (Ssequence\n                                        (Scall (Some _t'1)\n                                          (Evar _neq25519 (Tfunction\n                                                            (Tcons\n                                                              (tptr tlong)\n                                                              (Tcons\n                                                                (tptr tlong)\n                                                                Tnil)) tint\n                                                            cc_default))\n                                          ((Evar _chk (tarray tlong 16)) ::\n                                           (Evar _num (tarray tlong 16)) ::\n                                           nil))\n                                        (Sifthenelse (Etempvar _t'1 tint)\n                                          (Scall None\n                                            (Evar _M (Tfunction\n                                                       (Tcons (tptr tlong)\n                                                         (Tcons (tptr tlong)\n                                                           (Tcons\n                                                             (tptr tlong)\n                                                             Tnil))) tvoid\n                                                       cc_default))\n                                            ((Ederef\n                                               (Ebinop Oadd\n                                                 (Etempvar _r (tptr (tarray tlong 16)))\n                                                 (Econst_int (Int.repr 0) tint)\n                                                 (tptr (tarray tlong 16)))\n                                               (tarray tlong 16)) ::\n                                             (Ederef\n                                               (Ebinop Oadd\n                                                 (Etempvar _r (tptr (tarray tlong 16)))\n                                                 (Econst_int (Int.repr 0) tint)\n                                                 (tptr (tarray tlong 16)))\n                                               (tarray tlong 16)) ::\n                                             (Evar _I (tarray tlong 16)) ::\n                                             nil))\n                                          Sskip))\n                                      (Ssequence\n                                        (Scall None\n                                          (Evar _S (Tfunction\n                                                     (Tcons (tptr tlong)\n                                                       (Tcons (tptr tlong)\n                                                         Tnil)) tvoid\n                                                     cc_default))\n                                          ((Evar _chk (tarray tlong 16)) ::\n                                           (Ederef\n                                             (Ebinop Oadd\n                                               (Etempvar _r (tptr (tarray tlong 16)))\n                                               (Econst_int (Int.repr 0) tint)\n                                               (tptr (tarray tlong 16)))\n                                             (tarray tlong 16)) :: nil))\n                                        (Ssequence\n                                          (Scall None\n                                            (Evar _M (Tfunction\n                                                       (Tcons (tptr tlong)\n                                                         (Tcons (tptr tlong)\n                                                           (Tcons\n                                                             (tptr tlong)\n                                                             Tnil))) tvoid\n                                                       cc_default))\n                                            ((Evar _chk (tarray tlong 16)) ::\n                                             (Evar _chk (tarray tlong 16)) ::\n                                             (Evar _den (tarray tlong 16)) ::\n                                             nil))\n                                          (Ssequence\n                                            (Ssequence\n                                              (Scall (Some _t'2)\n                                                (Evar _neq25519 (Tfunction\n                                                                  (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil))\n                                                                  tint\n                                                                  cc_default))\n                                                ((Evar _chk (tarray tlong 16)) ::\n                                                 (Evar _num (tarray tlong 16)) ::\n                                                 nil))\n                                              (Sifthenelse (Etempvar _t'2 tint)\n                                                (Sreturn (Some (Eunop Oneg\n                                                                 (Econst_int (Int.repr 1) tint)\n                                                                 tint)))\n                                                Sskip))\n                                            (Ssequence\n                                              (Ssequence\n                                                (Scall (Some _t'3)\n                                                  (Evar _par25519 (Tfunction\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)\n                                                                    tuchar\n                                                                    cc_default))\n                                                  ((Ederef\n                                                     (Ebinop Oadd\n                                                       (Etempvar _r (tptr (tarray tlong 16)))\n                                                       (Econst_int (Int.repr 0) tint)\n                                                       (tptr (tarray tlong 16)))\n                                                     (tarray tlong 16)) ::\n                                                   nil))\n                                                (Ssequence\n                                                  (Sset _t'4\n                                                    (Ederef\n                                                      (Ebinop Oadd\n                                                        (Etempvar _p (tptr tuchar))\n                                                        (Econst_int (Int.repr 31) tint)\n                                                        (tptr tuchar))\n                                                      tuchar))\n                                                  (Sifthenelse (Ebinop Oeq\n                                                                 (Etempvar _t'3 tuchar)\n                                                                 (Ebinop Oshr\n                                                                   (Etempvar _t'4 tuchar)\n                                                                   (Econst_int (Int.repr 7) tint)\n                                                                   tint)\n                                                                 tint)\n                                                    (Scall None\n                                                      (Evar _Z (Tfunction\n                                                                 (Tcons\n                                                                   (tptr tlong)\n                                                                   (Tcons\n                                                                    (tptr tlong)\n                                                                    (Tcons\n                                                                    (tptr tlong)\n                                                                    Tnil)))\n                                                                 tvoid\n                                                                 cc_default))\n                                                      ((Ederef\n                                                         (Ebinop Oadd\n                                                           (Etempvar _r (tptr (tarray tlong 16)))\n                                                           (Econst_int (Int.repr 0) tint)\n                                                           (tptr (tarray tlong 16)))\n                                                         (tarray tlong 16)) ::\n                                                       (Evar _gf0 (tarray tlong 16)) ::\n                                                       (Ederef\n                                                         (Ebinop Oadd\n                                                           (Etempvar _r (tptr (tarray tlong 16)))\n                                                           (Econst_int (Int.repr 0) tint)\n                                                           (tptr (tarray tlong 16)))\n                                                         (tarray tlong 16)) ::\n                                                       nil))\n                                                    Sskip)))\n                                              (Ssequence\n                                                (Scall None\n                                                  (Evar _M (Tfunction\n                                                             (Tcons\n                                                               (tptr tlong)\n                                                               (Tcons\n                                                                 (tptr tlong)\n                                                                 (Tcons\n                                                                   (tptr tlong)\n                                                                   Tnil)))\n                                                             tvoid\n                                                             cc_default))\n                                                  ((Ederef\n                                                     (Ebinop Oadd\n                                                       (Etempvar _r (tptr (tarray tlong 16)))\n                                                       (Econst_int (Int.repr 3) tint)\n                                                       (tptr (tarray tlong 16)))\n                                                     (tarray tlong 16)) ::\n                                                   (Ederef\n                                                     (Ebinop Oadd\n                                                       (Etempvar _r (tptr (tarray tlong 16)))\n                                                       (Econst_int (Int.repr 0) tint)\n                                                       (tptr (tarray tlong 16)))\n                                                     (tarray tlong 16)) ::\n                                                   (Ederef\n                                                     (Ebinop Oadd\n                                                       (Etempvar _r (tptr (tarray tlong 16)))\n                                                       (Econst_int (Int.repr 1) tint)\n                                                       (tptr (tarray tlong 16)))\n                                                     (tarray tlong 16)) ::\n                                                   nil))\n                                                (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))))))))))))))))))))))\n|}.\n\nDefinition f_crypto_sign_ed25519_tweet_open := {|\n  fn_return := tint;\n  fn_callconv := cc_default;\n  fn_params := ((_m, (tptr tuchar)) :: (_mlen, (tptr tulong)) ::\n                (_sm, (tptr tuchar)) :: (_n, tulong) ::\n                (_pk, (tptr tuchar)) :: nil);\n  fn_vars := ((_t, (tarray tuchar 32)) :: (_h, (tarray tuchar 64)) ::\n              (_p, (tarray (tarray tlong 16) 4)) ::\n              (_q, (tarray (tarray tlong 16) 4)) :: nil);\n  fn_temps := ((_i, tint) :: (_t'2, tint) :: (_t'1, tint) ::\n               (_t'5, tuchar) :: (_t'4, tuchar) :: (_t'3, tuchar) :: nil);\n  fn_body :=\n(Ssequence\n  (Sassign (Ederef (Etempvar _mlen (tptr tulong)) tulong)\n    (Eunop Oneg (Econst_int (Int.repr 1) tint) tint))\n  (Ssequence\n    (Sifthenelse (Ebinop Olt (Etempvar _n tulong)\n                   (Econst_int (Int.repr 64) tint) tint)\n      (Sreturn (Some (Eunop Oneg (Econst_int (Int.repr 1) tint) tint)))\n      Sskip)\n    (Ssequence\n      (Ssequence\n        (Scall (Some _t'1)\n          (Evar _unpackneg (Tfunction\n                             (Tcons (tptr (tarray tlong 16))\n                               (Tcons (tptr tuchar) Tnil)) tint cc_default))\n          ((Evar _q (tarray (tarray tlong 16) 4)) ::\n           (Etempvar _pk (tptr tuchar)) :: nil))\n        (Sifthenelse (Etempvar _t'1 tint)\n          (Sreturn (Some (Eunop Oneg (Econst_int (Int.repr 1) tint) tint)))\n          Sskip))\n      (Ssequence\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                             (Etempvar _n tulong) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'5\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                      (Etempvar _i tint) (tptr tuchar)) tuchar))\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                      (Etempvar _i tint) (tptr tuchar)) tuchar)\n                  (Etempvar _t'5 tuchar))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint))))\n        (Ssequence\n          (Ssequence\n            (Sset _i (Econst_int (Int.repr 0) tint))\n            (Sloop\n              (Ssequence\n                (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                               (Econst_int (Int.repr 32) tint) tint)\n                  Sskip\n                  Sbreak)\n                (Ssequence\n                  (Sset _t'4\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _pk (tptr tuchar))\n                        (Etempvar _i tint) (tptr tuchar)) tuchar))\n                  (Sassign\n                    (Ederef\n                      (Ebinop Oadd (Etempvar _m (tptr tuchar))\n                        (Ebinop Oadd (Etempvar _i tint)\n                          (Econst_int (Int.repr 32) tint) tint)\n                        (tptr tuchar)) tuchar) (Etempvar _t'4 tuchar))))\n              (Sset _i\n                (Ebinop Oadd (Etempvar _i tint)\n                  (Econst_int (Int.repr 1) tint) tint))))\n          (Ssequence\n            (Scall None\n              (Evar _crypto_hash_sha512_tweet (Tfunction\n                                                (Tcons (tptr tuchar)\n                                                  (Tcons (tptr tuchar)\n                                                    (Tcons tulong Tnil)))\n                                                tint cc_default))\n              ((Evar _h (tarray tuchar 64)) :: (Etempvar _m (tptr tuchar)) ::\n               (Etempvar _n tulong) :: nil))\n            (Ssequence\n              (Scall None\n                (Evar _reduce (Tfunction (Tcons (tptr tuchar) Tnil) tvoid\n                                cc_default))\n                ((Evar _h (tarray tuchar 64)) :: nil))\n              (Ssequence\n                (Scall None\n                  (Evar _scalarmult (Tfunction\n                                      (Tcons (tptr (tarray tlong 16))\n                                        (Tcons (tptr (tarray tlong 16))\n                                          (Tcons (tptr tuchar) Tnil))) tvoid\n                                      cc_default))\n                  ((Evar _p (tarray (tarray tlong 16) 4)) ::\n                   (Evar _q (tarray (tarray tlong 16) 4)) ::\n                   (Evar _h (tarray tuchar 64)) :: nil))\n                (Ssequence\n                  (Scall None\n                    (Evar _scalarbase (Tfunction\n                                        (Tcons (tptr (tarray tlong 16))\n                                          (Tcons (tptr tuchar) Tnil)) tvoid\n                                        cc_default))\n                    ((Evar _q (tarray (tarray tlong 16) 4)) ::\n                     (Ebinop Oadd (Etempvar _sm (tptr tuchar))\n                       (Econst_int (Int.repr 32) tint) (tptr tuchar)) :: nil))\n                  (Ssequence\n                    (Scall None\n                      (Evar _add (Tfunction\n                                   (Tcons (tptr (tarray tlong 16))\n                                     (Tcons (tptr (tarray tlong 16)) Tnil))\n                                   tvoid cc_default))\n                      ((Evar _p (tarray (tarray tlong 16) 4)) ::\n                       (Evar _q (tarray (tarray tlong 16) 4)) :: nil))\n                    (Ssequence\n                      (Scall None\n                        (Evar _pack (Tfunction\n                                      (Tcons (tptr tuchar)\n                                        (Tcons (tptr (tarray tlong 16)) Tnil))\n                                      tvoid cc_default))\n                        ((Evar _t (tarray tuchar 32)) ::\n                         (Evar _p (tarray (tarray tlong 16) 4)) :: nil))\n                      (Ssequence\n                        (Sset _n\n                          (Ebinop Osub (Etempvar _n tulong)\n                            (Econst_int (Int.repr 64) tint) tulong))\n                        (Ssequence\n                          (Ssequence\n                            (Scall (Some _t'2)\n                              (Evar _crypto_verify_32_tweet (Tfunction\n                                                              (Tcons\n                                                                (tptr tuchar)\n                                                                (Tcons\n                                                                  (tptr tuchar)\n                                                                  Tnil)) tint\n                                                              cc_default))\n                              ((Etempvar _sm (tptr tuchar)) ::\n                               (Evar _t (tarray tuchar 32)) :: nil))\n                            (Sifthenelse (Etempvar _t'2 tint)\n                              (Ssequence\n                                (Ssequence\n                                  (Sset _i (Econst_int (Int.repr 0) tint))\n                                  (Sloop\n                                    (Ssequence\n                                      (Sifthenelse (Ebinop Olt\n                                                     (Etempvar _i tint)\n                                                     (Etempvar _n tulong)\n                                                     tint)\n                                        Sskip\n                                        Sbreak)\n                                      (Sassign\n                                        (Ederef\n                                          (Ebinop Oadd\n                                            (Etempvar _m (tptr tuchar))\n                                            (Etempvar _i tint) (tptr tuchar))\n                                          tuchar)\n                                        (Econst_int (Int.repr 0) tint)))\n                                    (Sset _i\n                                      (Ebinop Oadd (Etempvar _i tint)\n                                        (Econst_int (Int.repr 1) tint) tint))))\n                                (Sreturn (Some (Eunop Oneg\n                                                 (Econst_int (Int.repr 1) tint)\n                                                 tint))))\n                              Sskip))\n                          (Ssequence\n                            (Ssequence\n                              (Sset _i (Econst_int (Int.repr 0) tint))\n                              (Sloop\n                                (Ssequence\n                                  (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                                                 (Etempvar _n tulong) tint)\n                                    Sskip\n                                    Sbreak)\n                                  (Ssequence\n                                    (Sset _t'3\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Etempvar _sm (tptr tuchar))\n                                          (Ebinop Oadd (Etempvar _i tint)\n                                            (Econst_int (Int.repr 64) tint)\n                                            tint) (tptr tuchar)) tuchar))\n                                    (Sassign\n                                      (Ederef\n                                        (Ebinop Oadd\n                                          (Etempvar _m (tptr tuchar))\n                                          (Etempvar _i tint) (tptr tuchar))\n                                        tuchar) (Etempvar _t'3 tuchar))))\n                                (Sset _i\n                                  (Ebinop Oadd (Etempvar _i tint)\n                                    (Econst_int (Int.repr 1) tint) tint))))\n                            (Ssequence\n                              (Sassign\n                                (Ederef (Etempvar _mlen (tptr tulong))\n                                  tulong) (Etempvar _n tulong))\n                              (Sreturn (Some (Econst_int (Int.repr 0) tint))))))))))))))))))\n|}.\n\nDefinition composites : list composite_definition :=\nnil.\n\nDefinition global_definitions : list (ident * globdef fundef type) :=\n((___compcert_va_int32,\n   Gfun(External (EF_runtime \"__compcert_va_int32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tvoid) Tnil) tuint cc_default)) ::\n (___compcert_va_int64,\n   Gfun(External (EF_runtime \"__compcert_va_int64\"\n                   (mksignature (AST.Tint :: nil) AST.Tlong cc_default))\n     (Tcons (tptr tvoid) Tnil) tulong cc_default)) ::\n (___compcert_va_float64,\n   Gfun(External (EF_runtime \"__compcert_va_float64\"\n                   (mksignature (AST.Tint :: nil) AST.Tfloat cc_default))\n     (Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::\n (___compcert_va_composite,\n   Gfun(External (EF_runtime \"__compcert_va_composite\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     (tptr tvoid) cc_default)) ::\n (___compcert_i64_dtos,\n   Gfun(External (EF_runtime \"__compcert_i64_dtos\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tlong cc_default)) ::\n (___compcert_i64_dtou,\n   Gfun(External (EF_runtime \"__compcert_i64_dtou\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tulong cc_default)) ::\n (___compcert_i64_stod,\n   Gfun(External (EF_runtime \"__compcert_i64_stod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tlong Tnil) tdouble cc_default)) ::\n (___compcert_i64_utod,\n   Gfun(External (EF_runtime \"__compcert_i64_utod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tulong Tnil) tdouble cc_default)) ::\n (___compcert_i64_stof,\n   Gfun(External (EF_runtime \"__compcert_i64_stof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tlong Tnil) tfloat cc_default)) ::\n (___compcert_i64_utof,\n   Gfun(External (EF_runtime \"__compcert_i64_utof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tulong Tnil) tfloat cc_default)) ::\n (___compcert_i64_sdiv,\n   Gfun(External (EF_runtime \"__compcert_i64_sdiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_udiv,\n   Gfun(External (EF_runtime \"__compcert_i64_udiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_smod,\n   Gfun(External (EF_runtime \"__compcert_i64_smod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umod,\n   Gfun(External (EF_runtime \"__compcert_i64_umod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_shl,\n   Gfun(External (EF_runtime \"__compcert_i64_shl\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_shr,\n   Gfun(External (EF_runtime \"__compcert_i64_shr\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_sar,\n   Gfun(External (EF_runtime \"__compcert_i64_sar\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_smulh,\n   Gfun(External (EF_runtime \"__compcert_i64_smulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umulh,\n   Gfun(External (EF_runtime \"__compcert_i64_umulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___builtin_bswap64,\n   Gfun(External (EF_builtin \"__builtin_bswap64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) tulong cc_default)) ::\n (___builtin_bswap,\n   Gfun(External (EF_builtin \"__builtin_bswap\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap32,\n   Gfun(External (EF_builtin \"__builtin_bswap32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap16,\n   Gfun(External (EF_builtin \"__builtin_bswap16\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::\n (___builtin_clz,\n   Gfun(External (EF_builtin \"__builtin_clz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzl,\n   Gfun(External (EF_builtin \"__builtin_clzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzll,\n   Gfun(External (EF_builtin \"__builtin_clzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctz,\n   Gfun(External (EF_builtin \"__builtin_ctz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzl,\n   Gfun(External (EF_builtin \"__builtin_ctzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzll,\n   Gfun(External (EF_builtin \"__builtin_ctzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_fabs,\n   Gfun(External (EF_builtin \"__builtin_fabs\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_fabsf,\n   Gfun(External (EF_builtin \"__builtin_fabsf\"\n                   (mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))\n     (Tcons tfloat Tnil) tfloat cc_default)) ::\n (___builtin_fsqrt,\n   Gfun(External (EF_builtin \"__builtin_fsqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_sqrt,\n   Gfun(External (EF_builtin \"__builtin_sqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_memcpy_aligned,\n   Gfun(External (EF_builtin \"__builtin_memcpy_aligned\"\n                   (mksignature\n                     (AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr tvoid)\n       (Tcons (tptr tvoid) (Tcons tuint (Tcons tuint Tnil)))) tvoid\n     cc_default)) ::\n (___builtin_sel,\n   Gfun(External (EF_builtin \"__builtin_sel\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tbool Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot,\n   Gfun(External (EF_builtin \"__builtin_annot\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot_intval,\n   Gfun(External (EF_builtin \"__builtin_annot_intval\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))\n     tint cc_default)) ::\n (___builtin_membar,\n   Gfun(External (EF_builtin \"__builtin_membar\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_va_start,\n   Gfun(External (EF_builtin \"__builtin_va_start\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_va_arg,\n   Gfun(External (EF_builtin \"__builtin_va_arg\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_va_copy,\n   Gfun(External (EF_builtin \"__builtin_va_copy\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::\n (___builtin_va_end,\n   Gfun(External (EF_builtin \"__builtin_va_end\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_unreachable,\n   Gfun(External (EF_builtin \"__builtin_unreachable\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_expect,\n   Gfun(External (EF_builtin \"__builtin_expect\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons tint (Tcons tint Tnil)) tint\n     cc_default)) ::\n (___builtin_fmax,\n   Gfun(External (EF_builtin \"__builtin_fmax\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmin,\n   Gfun(External (EF_builtin \"__builtin_fmin\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmadd,\n   Gfun(External (EF_builtin \"__builtin_fmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fmsub,\n   Gfun(External (EF_builtin \"__builtin_fmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmadd,\n   Gfun(External (EF_builtin \"__builtin_fnmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmsub,\n   Gfun(External (EF_builtin \"__builtin_fnmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_read16_reversed,\n   Gfun(External (EF_builtin \"__builtin_read16_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons (tptr tushort) Tnil) tushort\n     cc_default)) ::\n (___builtin_read32_reversed,\n   Gfun(External (EF_builtin \"__builtin_read32_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tuint) Tnil) tuint cc_default)) ::\n (___builtin_write16_reversed,\n   Gfun(External (EF_builtin \"__builtin_write16_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))\n     tvoid cc_default)) ::\n (___builtin_write32_reversed,\n   Gfun(External (EF_builtin \"__builtin_write32_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_debug,\n   Gfun(External (EF_external \"__builtin_debug\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tint Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (_randombytes,\n   Gfun(External (EF_external \"randombytes\"\n                   (mksignature (AST.Tint :: AST.Tlong :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuchar) (Tcons tulong Tnil))\n     tvoid cc_default)) :: (__0, Gvar v__0) :: (__9, Gvar v__9) ::\n (_gf0, Gvar v_gf0) :: (_gf1, Gvar v_gf1) :: (__121665, Gvar v__121665) ::\n (_D, Gvar v_D) :: (_D2, Gvar v_D2) :: (_X, Gvar v_X) :: (_Y, Gvar v_Y) ::\n (_I, Gvar v_I) :: (_L32, Gfun(Internal f_L32)) ::\n (_ld32, Gfun(Internal f_ld32)) :: (_dl64, Gfun(Internal f_dl64)) ::\n (_st32, Gfun(Internal f_st32)) :: (_ts64, Gfun(Internal f_ts64)) ::\n (_vn, Gfun(Internal f_vn)) ::\n (_crypto_verify_16_tweet, Gfun(Internal f_crypto_verify_16_tweet)) ::\n (_crypto_verify_32_tweet, Gfun(Internal f_crypto_verify_32_tweet)) ::\n (_core, Gfun(Internal f_core)) ::\n (_crypto_core_salsa20_tweet, Gfun(Internal f_crypto_core_salsa20_tweet)) ::\n (_crypto_core_hsalsa20_tweet, Gfun(Internal f_crypto_core_hsalsa20_tweet)) ::\n (_sigma, Gvar v_sigma) ::\n (_crypto_stream_salsa20_tweet_xor, Gfun(Internal f_crypto_stream_salsa20_tweet_xor)) ::\n (_crypto_stream_salsa20_tweet, Gfun(Internal f_crypto_stream_salsa20_tweet)) ::\n (_crypto_stream_xsalsa20_tweet, Gfun(Internal f_crypto_stream_xsalsa20_tweet)) ::\n (_crypto_stream_xsalsa20_tweet_xor, Gfun(Internal f_crypto_stream_xsalsa20_tweet_xor)) ::\n (_add1305, Gfun(Internal f_add1305)) :: (_minusp, Gvar v_minusp) ::\n (_crypto_onetimeauth_poly1305_tweet, Gfun(Internal f_crypto_onetimeauth_poly1305_tweet)) ::\n (_crypto_onetimeauth_poly1305_tweet_verify, Gfun(Internal f_crypto_onetimeauth_poly1305_tweet_verify)) ::\n (_crypto_secretbox_xsalsa20poly1305_tweet, Gfun(Internal f_crypto_secretbox_xsalsa20poly1305_tweet)) ::\n (_crypto_secretbox_xsalsa20poly1305_tweet_open, Gfun(Internal f_crypto_secretbox_xsalsa20poly1305_tweet_open)) ::\n (_set25519, Gfun(Internal f_set25519)) ::\n (_car25519, Gfun(Internal f_car25519)) ::\n (_sel25519, Gfun(Internal f_sel25519)) ::\n (_pack25519, Gfun(Internal f_pack25519)) ::\n (_neq25519, Gfun(Internal f_neq25519)) ::\n (_par25519, Gfun(Internal f_par25519)) ::\n (_unpack25519, Gfun(Internal f_unpack25519)) :: (_A, Gfun(Internal f_A)) ::\n (_Z, Gfun(Internal f_Z)) :: (_M, Gfun(Internal f_M)) ::\n (_S, Gfun(Internal f_S)) :: (_inv25519, Gfun(Internal f_inv25519)) ::\n (_pow2523, Gfun(Internal f_pow2523)) ::\n (_crypto_scalarmult_curve25519_tweet, Gfun(Internal f_crypto_scalarmult_curve25519_tweet)) ::\n (_crypto_scalarmult_curve25519_tweet_base, Gfun(Internal f_crypto_scalarmult_curve25519_tweet_base)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet_keypair, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet_keypair)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet_beforenm, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet_beforenm)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet_afternm, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet_afternm)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet)) ::\n (_crypto_box_curve25519xsalsa20poly1305_tweet_open, Gfun(Internal f_crypto_box_curve25519xsalsa20poly1305_tweet_open)) ::\n (_R, Gfun(Internal f_R)) :: (_Ch, Gfun(Internal f_Ch)) ::\n (_Maj, Gfun(Internal f_Maj)) :: (_Sigma0, Gfun(Internal f_Sigma0)) ::\n (_Sigma1, Gfun(Internal f_Sigma1)) :: (_sigma0, Gfun(Internal f_sigma0)) ::\n (_sigma1, Gfun(Internal f_sigma1)) :: (_K, Gvar v_K) ::\n (_crypto_hashblocks_sha512_tweet, Gfun(Internal f_crypto_hashblocks_sha512_tweet)) ::\n (_iv, Gvar v_iv) ::\n (_crypto_hash_sha512_tweet, Gfun(Internal f_crypto_hash_sha512_tweet)) ::\n (_add, Gfun(Internal f_add)) :: (_cswap, Gfun(Internal f_cswap)) ::\n (_pack, Gfun(Internal f_pack)) ::\n (_scalarmult, Gfun(Internal f_scalarmult)) ::\n (_scalarbase, Gfun(Internal f_scalarbase)) ::\n (_crypto_sign_ed25519_tweet_keypair, Gfun(Internal f_crypto_sign_ed25519_tweet_keypair)) ::\n (_L, Gvar v_L) :: (_modL, Gfun(Internal f_modL)) ::\n (_reduce, Gfun(Internal f_reduce)) ::\n (_crypto_sign_ed25519_tweet, Gfun(Internal f_crypto_sign_ed25519_tweet)) ::\n (_unpackneg, Gfun(Internal f_unpackneg)) ::\n (_crypto_sign_ed25519_tweet_open, Gfun(Internal f_crypto_sign_ed25519_tweet_open)) ::\n nil).\n\nDefinition public_idents : list ident :=\n(_crypto_sign_ed25519_tweet_open :: _crypto_sign_ed25519_tweet ::\n _crypto_sign_ed25519_tweet_keypair :: _crypto_hash_sha512_tweet ::\n _crypto_hashblocks_sha512_tweet ::\n _crypto_box_curve25519xsalsa20poly1305_tweet_open ::\n _crypto_box_curve25519xsalsa20poly1305_tweet ::\n _crypto_box_curve25519xsalsa20poly1305_tweet_open_afternm ::\n _crypto_box_curve25519xsalsa20poly1305_tweet_afternm ::\n _crypto_box_curve25519xsalsa20poly1305_tweet_beforenm ::\n _crypto_box_curve25519xsalsa20poly1305_tweet_keypair ::\n _crypto_scalarmult_curve25519_tweet_base ::\n _crypto_scalarmult_curve25519_tweet ::\n _crypto_secretbox_xsalsa20poly1305_tweet_open ::\n _crypto_secretbox_xsalsa20poly1305_tweet ::\n _crypto_onetimeauth_poly1305_tweet_verify ::\n _crypto_onetimeauth_poly1305_tweet :: _crypto_stream_xsalsa20_tweet_xor ::\n _crypto_stream_xsalsa20_tweet :: _crypto_stream_salsa20_tweet ::\n _crypto_stream_salsa20_tweet_xor :: _crypto_core_hsalsa20_tweet ::\n _crypto_core_salsa20_tweet :: _crypto_verify_32_tweet ::\n _crypto_verify_16_tweet :: _randombytes :: ___builtin_debug ::\n ___builtin_write32_reversed :: ___builtin_write16_reversed ::\n ___builtin_read32_reversed :: ___builtin_read16_reversed ::\n ___builtin_fnmsub :: ___builtin_fnmadd :: ___builtin_fmsub ::\n ___builtin_fmadd :: ___builtin_fmin :: ___builtin_fmax ::\n ___builtin_expect :: ___builtin_unreachable :: ___builtin_va_end ::\n ___builtin_va_copy :: ___builtin_va_arg :: ___builtin_va_start ::\n ___builtin_membar :: ___builtin_annot_intval :: ___builtin_annot ::\n ___builtin_sel :: ___builtin_memcpy_aligned :: ___builtin_sqrt ::\n ___builtin_fsqrt :: ___builtin_fabsf :: ___builtin_fabs ::\n ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz :: ___builtin_clzll ::\n ___builtin_clzl :: ___builtin_clz :: ___builtin_bswap16 ::\n ___builtin_bswap32 :: ___builtin_bswap :: ___builtin_bswap64 ::\n ___compcert_i64_umulh :: ___compcert_i64_smulh :: ___compcert_i64_sar ::\n ___compcert_i64_shr :: ___compcert_i64_shl :: ___compcert_i64_umod ::\n ___compcert_i64_smod :: ___compcert_i64_udiv :: ___compcert_i64_sdiv ::\n ___compcert_i64_utof :: ___compcert_i64_stof :: ___compcert_i64_utod ::\n ___compcert_i64_stod :: ___compcert_i64_dtou :: ___compcert_i64_dtos ::\n ___compcert_va_composite :: ___compcert_va_float64 ::\n ___compcert_va_int64 :: ___compcert_va_int32 :: nil).\n\nDefinition prog : Clight.program := \n  mkprogram composites global_definitions public_idents _main Logic.I.\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/tweetnacl20140427/tweetnaclVerifiableC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18846262013331805}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Eqdep_dec.\nRequire Import Classes.SetoidTactics.\nRequire Import Hashmap.\nRequire Import HashmapProg.\nRequire Import Pred PredCrash.\nRequire Import Prog ProgMonad.\nRequire Import Hoare.\nRequire Import SepAuto.\nRequire Import BasicProg.\nRequire Import Omega.\nRequire Import Word.\nRequire Import Rec.\nRequire Import Array.\nRequire Import WordAuto.\nRequire Import Cache.\nRequire Import FSLayout.\nRequire Import Rounding.\nRequire Import List ListUtils.\nRequire Import Psatz.\nRequire Import AsyncDisk.\nRequire Import RecArrayUtils.\nRequire Import AsyncRecArray.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n\nModule PaddedLog.\n\n  Module DescSig <: RASig.\n\n    Definition xparams := log_xparams.\n    Definition RAStart := LogDescriptor.\n    Definition RALen := LogDescLen.\n    Definition xparams_ok (xp : xparams) := goodSize addrlen ((RAStart xp) + (RALen xp)).\n\n    Definition itemtype := Rec.WordF addrlen.\n    Definition items_per_val := valulen / addrlen.\n\n    Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n    Proof.\n      unfold items_per_val; simpl.\n      rewrite valulen_is. apply Nat.eqb_eq. compute. reflexivity.\n    Qed.\n\n  End DescSig.\n\n\n  Module DataSig <: RASig.\n\n    Definition xparams := log_xparams.\n    Definition RAStart := LogData.\n    Definition RALen := LogLen.\n    Definition xparams_ok (xp : xparams) := goodSize addrlen ((RAStart xp) + (RALen xp)).\n\n    Definition itemtype := Rec.WordF valulen.\n    Definition items_per_val := 1.\n\n    Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n    Proof.\n      unfold items_per_val; simpl.\n      rewrite valulen_is. apply Nat.eqb_eq. compute; reflexivity.\n    Qed.\n\n  End DataSig.\n\n  Module Desc := AsyncRecArray DescSig.\n  Module Data := AsyncRecArray DataSig.\n  Module DescDefs := Desc.Defs.\n  Module DataDefs := Data.Defs.\n\n\n  (************* Log header *)\n  Module Hdr.\n\n    Definition header_type := Rec.RecF ([(\"previous_ndesc\", Rec.WordF addrlen);\n                                         (\"previous_ndata\", Rec.WordF addrlen);\n                                         (\"ndesc\", Rec.WordF addrlen);\n                                         (\"ndata\", Rec.WordF addrlen);\n                                         (\"addr_checksum\", Rec.WordF hashlen);\n                                         (\"valu_checksum\", Rec.WordF hashlen)]).\n    Definition header := Rec.data header_type.\n    Definition hdr := ((nat * nat) * (nat * nat) * (word hashlen * word hashlen))%type.\n    Definition previous_length (header : hdr) := fst (fst header).\n    Definition current_length (header : hdr) := snd (fst header).\n    Definition checksum (header : hdr) := snd header.\n    Definition mk_header (len : hdr) : header :=\n      ($ (fst (previous_length len)),\n      ($ (snd (previous_length len)),\n      ($ (fst (current_length len)),\n      ($ (snd (current_length len)),\n      (fst (checksum len),\n      (snd (checksum len), tt)))))).\n\n    Theorem hdrsz_ok : Rec.len header_type <= valulen.\n    Proof.\n      rewrite valulen_is. apply leb_complete. compute. trivial.\n    Qed.\n    Local Hint Resolve hdrsz_ok.\n\n    Lemma plus_minus_header : Rec.len header_type + (valulen - Rec.len header_type) = valulen.\n    Proof.\n      apply le_plus_minus_r; auto.\n    Qed.\n\n    Definition hdr2val (h : header) : valu.\n      set (zext (Rec.to_word h) (valulen - Rec.len header_type)) as r.\n      rewrite plus_minus_header in r.\n      refine r.\n    Defined.\n\n    Definition val2hdr (v : valu) : header.\n      apply Rec.of_word.\n      rewrite <- plus_minus_header in v.\n      refine (split1 _ _ v).\n    Defined.\n\n    Arguments hdr2val: simpl never.\n\n    Lemma val2hdr2val : forall h,\n      val2hdr (hdr2val h) = h.\n    Proof.\n      unfold val2hdr, hdr2val.\n      unfold eq_rec_r, eq_rec.\n      intros.\n      rewrite <- plus_minus_header.\n      unfold zext.\n      autorewrite with core; auto.\n      simpl; destruct h; tauto.\n    Qed.\n\n    Arguments val2hdr: simpl never.\n    Opaque val2hdr.  (* for some reason \"simpl never\" doesn't work *)\n\n\n    Definition xparams := log_xparams.\n    Definition LAHdr := LogHeader.\n\n    Inductive state : Type :=\n    | Synced : hdr -> state\n    | Unsync : hdr -> hdr -> state\n    .\n\n    Definition hdr_goodSize header :=\n      goodSize addrlen (fst (previous_length header)) /\\\n      goodSize addrlen (snd (previous_length header)) /\\\n      goodSize addrlen (fst (current_length header)) /\\\n      goodSize addrlen (snd (current_length header)).\n\n    Definition state_goodSize st :=\n      match st with\n      | Synced n => hdr_goodSize n\n      | Unsync n o => hdr_goodSize n /\\ hdr_goodSize o\n      end.\n\n    Definition rep xp state : @rawpred :=\n      ([[ state_goodSize state ]] *\n      match state with\n      | Synced n =>\n         (LAHdr xp) |+> (hdr2val (mk_header n), nil)\n      | Unsync n o =>\n         (LAHdr xp) |+> (hdr2val (mk_header n), [hdr2val (mk_header o)]%list)\n      end)%pred.\n\n    Definition xform_rep_synced : forall xp n,\n      crash_xform (rep xp (Synced n)) =p=> rep xp (Synced n).\n    Proof.\n      unfold rep; intros; simpl.\n      xform; auto.\n      rewrite crash_xform_ptsto_subset'.\n      cancel.\n      rewrite H1; auto.\n    Qed.\n\n    Definition xform_rep_unsync : forall xp n o,\n      crash_xform (rep xp (Unsync n o)) =p=> rep xp (Synced n) \\/ rep xp (Synced o).\n    Proof.\n      unfold rep; intros; simpl.\n      xform.\n      rewrite crash_xform_ptsto_subset; unfold ptsto_subset.\n      cancel.\n      or_l; cancel.\n      cancel.\n    Qed.\n\n    Definition read xp cs := Eval compute_rec in\n      let^ (cs, v) <- BUFCACHE.read (LAHdr xp) cs;\n      let header := (val2hdr v) in\n      Ret ^(cs, ((# (header :-> \"previous_ndesc\"), # (header :-> \"previous_ndata\")),\n                (# (header :-> \"ndesc\"), # (header :-> \"ndata\")),\n                (header :-> \"addr_checksum\", header :-> \"valu_checksum\"))).\n\n    Definition write xp n cs :=\n      cs <- BUFCACHE.write (LAHdr xp) (hdr2val (mk_header n)) cs;\n      Ret cs.\n\n    Definition sync xp cs :=\n      cs <- BUFCACHE.sync (LAHdr xp) cs;\n      Ret cs.\n\n    Definition sync_now xp cs :=\n      cs <- BUFCACHE.begin_sync cs;\n      cs <- BUFCACHE.sync (LAHdr xp) cs;\n      cs <- BUFCACHE.end_sync cs;\n      Ret cs.\n\n    Definition init xp cs :=\n      h <- Hash default_valu;\n      cs <- BUFCACHE.write (LAHdr xp) (hdr2val (mk_header ((0, 0), (0, 0), (h, h)))) cs;\n      cs <- BUFCACHE.begin_sync cs;\n      cs <- BUFCACHE.sync (LAHdr xp) cs;\n      cs <- BUFCACHE.end_sync cs;\n      Ret cs.\n\n    Local Hint Unfold rep state_goodSize : hoare_unfold.\n\n    Theorem write_ok : forall xp n cs,\n    {< F d old,\n    PRE:hm         BUFCACHE.rep cs d *\n                   [[ hdr_goodSize n ]] *\n                   [[ previous_length n = current_length old \\/\n                      previous_length old = current_length n ]] *\n                   [[ (F * rep xp (Synced old))%pred d ]]\n    POST:hm' RET: cs\n                   exists d', BUFCACHE.rep cs d' *\n                   [[ (F * rep xp (Unsync n old))%pred d' ]]\n    XCRASH:hm'     exists cs' d', BUFCACHE.rep cs' d' * \n                   [[ (F * rep xp (Unsync n old))%pred d' ]]\n    >} write xp n cs.\n    Proof.\n      unfold write.\n      step.\n      step.\n      xcrash.\n      step.\n      xcrash.\n    Qed.\n\n    Theorem read_ok : forall xp cs,\n    {< F d n,\n    PRE:hm         BUFCACHE.rep cs d *\n                   [[ (F * rep xp (Synced n))%pred d ]]\n    POST:hm' RET: ^(cs, r)\n                   BUFCACHE.rep cs d *\n                   [[ (F * rep xp (Synced n))%pred d ]] *\n                   [[ r = n ]]\n    CRASH:hm' exists cs', BUFCACHE.rep cs' d\n    >} read xp cs.\n    Proof.\n      unfold read.\n      hoare.\n      subst; rewrite val2hdr2val; simpl.\n      unfold hdr_goodSize in *; intuition.\n      repeat rewrite wordToNat_natToWord_idempotent'; auto.\n      destruct n; auto.\n      destruct p as (p1 , p2); destruct p1, p2, p0; auto.\n    Qed.\n\n    Theorem sync_ok : forall xp cs,\n    {< F d0 d n old,\n    PRE:hm         BUFCACHE.synrep cs d0 d *\n                   [[ (F * rep xp (Unsync n old))%pred d ]] *\n                   [[ sync_invariant F ]]\n    POST:hm' RET: cs\n                   exists d', BUFCACHE.synrep cs d0 d' *\n                   [[ (F * rep xp (Synced n))%pred d' ]]\n    CRASH:hm'  exists cs', BUFCACHE.rep cs' d0\n    >} sync xp cs.\n    Proof.\n      unfold sync.\n      step.\n      step.\n    Qed.\n\n    Theorem sync_now_ok : forall xp cs,\n    {< F d n old,\n    PRE:hm         BUFCACHE.rep cs d *\n                   [[ (F * rep xp (Unsync n old))%pred d ]] *\n                   [[ sync_invariant F ]]\n    POST:hm' RET: cs\n                   exists d', BUFCACHE.rep cs d' *\n                   [[ (F * rep xp (Synced n))%pred d' ]]\n    CRASH:hm'  exists cs', BUFCACHE.rep cs' d\n    >} sync_now xp cs.\n    Proof.\n      unfold sync_now; intros.\n      hoare.\n    Qed.\n\n    Theorem init_ok : forall xp cs,\n    {< F d v0,\n    PRE:hm         BUFCACHE.rep cs d *\n                   [[ (F * (LAHdr xp) |+> v0)%pred d ]] *\n                   [[ sync_invariant F ]]\n    POST:hm' RET: cs\n                   exists d', BUFCACHE.rep cs d' *\n                   [[ (F * rep xp (Synced ((0, 0), (0, 0),\n                          (hash_fwd default_valu, hash_fwd default_valu))))%pred d' ]]\n    CRASH:hm'  any\n    >} init xp cs.\n    Proof.\n      unfold init, rep; intros.\n      step.\n      step.\n      step.\n      step.\n      step.\n      prestep; unfold rep; safecancel.\n      unfold hdr_goodSize; cbn.\n      repeat split; apply zero_lt_pow2.\n      all: apply pimpl_any.\n      Unshelve. exact tt.\n    Qed.\n\n\n    Theorem sync_invariant_rep : forall xp st,\n      sync_invariant (rep xp st).\n    Proof.\n      unfold rep; destruct st; eauto.\n    Qed.\n\n    Hint Resolve sync_invariant_rep.\n    Hint Extern 1 ({{_}} Bind (write _ _ _) _) => apply write_ok : prog.\n    Hint Extern 1 ({{_}} Bind (read _ _) _) => apply read_ok : prog.\n    Hint Extern 1 ({{_}} Bind (sync _ _) _) => apply sync_ok : prog.\n    Hint Extern 1 ({{_}} Bind (sync_now _ _) _) => apply sync_now_ok : prog.\n    Hint Extern 1 ({{_}} Bind (init _ _) _) => apply init_ok : prog.\n\n  End Hdr.\n\n\n  (****************** Log contents and states *)\n\n  Definition entry := (addr * valu)%type.\n  Definition contents := list entry.\n\n  Inductive state :=\n  (* The log is synced on disk *)\n  | Synced (l: contents)\n\n  (* The log has been truncated; but the length (0) is unsynced *)\n  | Truncated (old: contents)\n\n  (* The log is being extended; only the content has been updated (unsynced) *)\n  | Extended (old: contents) (new: contents)\n\n  (* The log immediately after a crash during an extend, when the new header\n  gets synced to disk, but we're not sure what data is there yet. This state\n  should be hidden from all higher layers. *)\n  | ExtendedCrashed (old: contents) (new: contents)\n\n  (* A special case of ExtendedCrashed. The data in the log definitely does\n  not match the header on disk, so we are guaranteed to roll back to the\n  previous length during recovery. *)\n  | Rollback (old: contents)\n\n  (* The log during recovery, when the data in the log doesn't match the\n  header and we're rolling back to the previous log length. The header we will\n  recover to hasn't been synced yet *)\n  | RollbackUnsync (old: contents)\n  .\n\n  Definition ent_addr (e : entry) := addr2w (fst e).\n  Definition ent_valu (e : entry) := snd e.\n\n  Definition ndesc_log (log : contents) := (divup (length log) DescSig.items_per_val).\n  Definition ndesc_list T (l : list T) := (divup (length l) DescSig.items_per_val).\n\n  Fixpoint log_nonzero (log : contents) : list entry :=\n    match log with\n    | (0, _) :: rest => log_nonzero rest\n    | e :: rest => e :: log_nonzero rest\n    | nil => nil\n    end.\n\n  Definition vals_nonzero (log : contents) := map ent_valu (log_nonzero log).\n\n  Fixpoint nonzero_addrs (al : list addr) : nat :=\n    match al with\n    | 0 :: rest => nonzero_addrs rest\n    | e :: rest => S (nonzero_addrs rest)\n    | nil => 0\n    end.\n\n  Fixpoint combine_nonzero (al : list addr) (vl : list valu) : contents :=\n    match al, vl with\n    | 0 :: al', v :: vl' => combine_nonzero al' vl\n    | a :: al', v :: vl' => (a, v) :: (combine_nonzero al' vl')\n    | _, _ => nil\n    end.\n\n  Definition ndata_log (log : contents) := nonzero_addrs (map fst log) .\n\n  Definition addr_valid (e : entry) := goodSize addrlen (fst e).\n\n  Definition entry_valid (ent : entry) := fst ent <> 0 /\\ addr_valid ent.\n\n  Definition rep_contents xp (log : contents) : rawpred :=\n    ( [[ Forall addr_valid log ]] *\n     Desc.array_rep xp 0 (Desc.Synced (map ent_addr log)) *\n     Data.array_rep xp 0 (Data.Synced (vals_nonzero log)) *\n     Desc.avail_rep xp (ndesc_log log) (LogDescLen xp - (ndesc_log log)) *\n     Data.avail_rep xp (ndata_log log) (LogLen xp - (ndata_log log))\n     )%pred.\n\n  Definition padded_addr (al : list addr) :=\n    setlen al (roundup (length al) DescSig.items_per_val) 0.\n\n  Definition padded_log (log : contents) :=\n    setlen log (roundup (length log) DescSig.items_per_val) (0, $0).\n\n  Definition rep_contents_unmatched xp (old : contents) new_addr new_valu : rawpred :=\n    ( [[ Forall addr_valid old ]] *\n      (*[[ Forall addr_valid new ]] **)\n     Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old))) *\n     Desc.array_rep xp (ndesc_log old) (Desc.Synced new_addr) *\n     Data.array_rep xp 0 (Data.Synced (vals_nonzero (padded_log old))) *\n     Data.array_rep xp (ndata_log old) (Data.Synced new_valu) *\n     Desc.avail_rep xp (ndesc_log old + ndesc_list new_addr) (LogDescLen xp - (ndesc_log old) - (ndesc_list new_addr)) *\n     Data.avail_rep xp (ndata_log old + length new_valu) (LogLen xp - (ndata_log old) - (length new_valu))\n     )%pred.\n\n  Definition loglen_valid xp ndesc ndata :=\n    ndesc <= LogDescLen xp  /\\ ndata <= LogLen xp.\n\n  Definition loglen_invalid xp ndesc ndata :=\n    ndesc > LogDescLen xp \\/ ndata > LogLen xp.\n\n  Definition checksums_match (l : contents) h hm :=\n    hash_list_rep (rev (DescDefs.ipack (map ent_addr l))) (fst h) hm /\\\n    hash_list_rep (rev (vals_nonzero l)) (snd h) hm.\n\n  Definition hide_or (P : Prop) := P.\n  Opaque hide_or.\n\n  Definition rep_inner xp (st : state) hm : rawpred :=\n  (match st with\n  | Synced l =>\n      exists prev_len h,\n       Hdr.rep xp (Hdr.Synced (prev_len,\n                              (ndesc_log l, ndata_log l),\n                              h)) *\n       rep_contents xp l *\n       [[ checksums_match l h hm ]]\n\n  | Truncated old =>\n      exists prev_len h h',\n       Hdr.rep xp (Hdr.Unsync ((ndesc_log old, ndata_log old), (0, 0), h')\n                              (prev_len, (ndesc_log old, ndata_log old), h)) *\n       rep_contents xp old *\n       [[ checksums_match old h hm ]] *\n       [[ checksums_match [] h' hm ]]\n\n  | Extended old new =>\n      exists prev_len h h',\n       Hdr.rep xp (Hdr.Unsync ((ndesc_log old, ndata_log old),\n                                (ndesc_log old + ndesc_log new,\n                                 ndata_log old + ndata_log new), h')\n                               (prev_len, (ndesc_log old, ndata_log old), h)) *\n       rep_contents xp old *\n       [[ loglen_valid xp (ndesc_log old + ndesc_log new)\n                          (ndata_log old + ndata_log new) ]] *\n       [[ checksums_match old h hm ]] *\n       [[ checksums_match (padded_log old ++ new) h' hm ]] *\n       [[ Forall entry_valid new ]]\n\n  | ExtendedCrashed old new =>\n      exists h synced_addr synced_valu ndesc,\n        Hdr.rep xp (Hdr.Synced ((ndesc_log old, ndata_log old),\n                                (ndesc_log old + ndesc_log new,\n                                 ndata_log old + ndata_log new),\n                                h)) *\n        rep_contents_unmatched xp old synced_addr synced_valu *\n        [[ loglen_valid xp (ndesc_log old + ndesc_log new)\n                           (ndata_log old + ndata_log new) ]] *\n        (* Whatever got synced on disk takes up just as many desc blocks as new should've. *)\n        [[ length synced_addr = (ndesc * DescSig.items_per_val)%nat ]] *\n        [[ ndesc = ndesc_log new ]] *\n        [[ length synced_valu = ndata_log new ]] *\n        [[ checksums_match (padded_log old ++ new) h hm ]] *\n        [[ Forall entry_valid new ]]\n\n  | Rollback old =>\n      exists synced_addr synced_valu h new,\n        Hdr.rep xp (Hdr.Synced ((ndesc_log old, ndata_log old),\n                                (ndesc_log old + ndesc_log new,\n                                 ndata_log old + ndata_log new),\n                                 h)) *\n        rep_contents_unmatched xp old synced_addr synced_valu *\n        [[ loglen_valid xp (ndesc_log old + ndesc_log new)\n                           (ndata_log old + ndata_log new) ]] *\n        (* Whatever got synced on disk takes up just as many desc blocks as new should've. *)\n        [[ length synced_addr = ((ndesc_log new) * DescSig.items_per_val)%nat ]] *\n        [[ length synced_valu = ndata_log new ]] *\n        [[ checksums_match (padded_log old ++ new) h hm ]] *\n        [[ hide_or (DescDefs.ipack (map ent_addr (padded_log new)) <> DescDefs.ipack synced_addr \\/\n            vals_nonzero new <> synced_valu) ]] *\n        [[ Forall entry_valid new ]]\n\n  | RollbackUnsync old =>\n      exists synced_addr synced_valu h h' new prev_len,\n         Hdr.rep xp (Hdr.Unsync (prev_len, (ndesc_log old, ndata_log old), h')\n                                ((ndesc_log old, ndata_log old),\n                                 (ndesc_log old + ndesc_log new,\n                                  ndata_log old + ndata_log new), h)) *\n        rep_contents_unmatched xp old synced_addr synced_valu *\n        [[ loglen_valid xp (ndesc_log old + ndesc_log new)\n                           (ndata_log old + ndata_log new) ]] *\n        (* Whatever got synced on disk takes up just as many desc blocks as new should've. *)\n        [[ length synced_addr = ((ndesc_log new) * DescSig.items_per_val)%nat ]] *\n        [[ length synced_valu = ndata_log new ]] *\n        [[ checksums_match old h' hm ]] *\n        [[ checksums_match (padded_log old ++ new) h hm ]] *\n        [[ hide_or (DescDefs.ipack (map ent_addr (padded_log new)) <> DescDefs.ipack synced_addr \\/\n            vals_nonzero new <> synced_valu) ]] *\n        [[ Forall entry_valid new ]]\n\n  end)%pred.\n\n  Definition xparams_ok xp := \n    DescSig.xparams_ok xp /\\ DataSig.xparams_ok xp /\\\n    (LogLen xp) = DescSig.items_per_val * (LogDescLen xp).\n\n  Definition rep xp st hm:=\n    ([[ xparams_ok xp ]] * rep_inner xp st hm)%pred.\n\n  Definition would_recover' xp l hm :=\n    (rep xp (Synced l) hm \\/\n      rep xp (Rollback l) hm \\/\n      rep xp (RollbackUnsync l) hm)%pred.\n\n  Definition would_recover xp F l hm :=\n    (exists cs d,\n      BUFCACHE.rep cs d *\n      [[ (F * would_recover' xp l hm)%pred d ]])%pred.\n\n\n  Theorem sync_invariant_rep : forall xp st hm,\n    sync_invariant (rep xp st hm).\n  Proof.\n    unfold rep, rep_inner, rep_contents, rep_contents_unmatched.\n    destruct st; intros; eauto 50.\n  Qed.\n\n  Hint Resolve sync_invariant_rep.\n\n  Theorem sync_invariant_would_recover' : forall xp l hm,\n    sync_invariant (would_recover' xp l hm).\n  Proof.\n    unfold would_recover'; intros; eauto.\n  Qed.\n\n  Theorem sync_invariant_would_recover : forall xp F l hm,\n    sync_invariant (would_recover xp F l hm).\n  Proof.\n    unfold would_recover; intros; eauto.\n  Qed.\n\n  Hint Resolve sync_invariant_would_recover sync_invariant_would_recover'.\n\n  Local Hint Unfold rep rep_inner rep_contents xparams_ok: hoare_unfold.\n\n  Definition avail xp cs :=\n    let^ (cs, nr) <- Hdr.read xp cs;\n    let '(_, (ndesc, _), _) := nr in\n    Ret ^(cs, ((LogLen xp) - ndesc * DescSig.items_per_val)).\n\n  Definition read xp cs :=\n    let^ (cs, nr) <- Hdr.read xp cs;\n    let '(_, (ndesc, ndata), _) := nr in\n    let^ (cs, wal) <- Desc.read_all xp ndesc cs;\n    let al := map (@wordToNat addrlen) wal in\n    let^ (cs, vl) <- Data.read_all xp ndata cs;\n    Ret ^(cs, combine_nonzero al vl).\n\n  (* this is an evil hint *)\n  Remove Hints Forall_nil.\n\n  Lemma Forall_True : forall A (l : list A),\n    Forall (fun _ : A => True) l.\n  Proof.\n    intros; rewrite Forall_forall; auto.\n  Qed.\n  Hint Resolve Forall_True.\n\n  Lemma combine_nonzero_ok : forall l,\n    combine_nonzero (map fst l) (vals_nonzero l) = log_nonzero l.\n  Proof.\n    unfold vals_nonzero.\n    induction l; intros; simpl; auto.\n    destruct a, n; simpl.\n    case_eq (map ent_valu (log_nonzero l)); intros; simpl.\n    apply map_eq_nil in H; auto.\n    rewrite <- H; auto.\n    rewrite IHl; auto.\n  Qed.\n\n  Lemma combine_nonzero_nil : forall a,\n    combine_nonzero a nil = nil.\n  Proof.\n    induction a; intros; simpl; auto.\n    destruct a; simpl; auto.\n  Qed.\n  Local Hint Resolve combine_nonzero_nil.\n\n  Lemma combine_nonzero_app_zero : forall a b,\n    combine_nonzero (a ++ [0]) b = combine_nonzero a b.\n  Proof.\n    induction a; intros; simpl; auto.\n    destruct b; auto.\n    destruct a, b; simpl; auto.\n    rewrite IHa; auto.\n  Qed.\n\n  Lemma combine_nonzero_app_zeros : forall n a b,\n    combine_nonzero (a ++ repeat 0 n) b = combine_nonzero a b.\n  Proof.\n    induction n; intros; simpl.\n    rewrite app_nil_r; auto.\n    rewrite <- cons_nil_app.\n    rewrite IHn.\n    apply combine_nonzero_app_zero.\n  Qed.\n\n  Local Hint Resolve roundup_ge DescDefs.items_per_val_gt_0.\n\n  Lemma combine_nonzero_padded_addr : forall a b,\n    combine_nonzero (padded_addr a) b = combine_nonzero a b.\n  Proof.\n    unfold padded_addr, vals_nonzero.\n    induction a; intros; simpl; auto.\n    unfold setlen, roundup; simpl.\n    rewrite divup_0; simpl; auto.\n\n    unfold setlen, roundup; simpl.\n    destruct a, b; simpl; auto;\n    rewrite firstn_oob; simpl; auto;\n    rewrite combine_nonzero_app_zeros; auto.\n  Qed.\n\n  Lemma map_fst_repeat : forall A B n (a : A) (b : B),\n    map fst (repeat (a, b) n) = repeat a n.\n  Proof.\n    induction n; intros; simpl; auto.\n    rewrite IHn; auto.\n  Qed.\n\n  Lemma map_entaddr_repeat_0 : forall n b,\n    map ent_addr (repeat (0, b) n) = repeat $0 n.\n  Proof.\n    induction n; intros; simpl; auto.\n    rewrite IHn; auto.\n  Qed.\n\n  Lemma combine_nonzero_padded_log : forall l b,\n    combine_nonzero (map fst (padded_log l)) b = combine_nonzero (map fst l) b.\n  Proof.\n    unfold padded_log, setlen, roundup; intros.\n    induction l; simpl.\n    rewrite divup_0; simpl; auto.\n    \n    rewrite <- IHl.\n    destruct a, b, n; simpl; auto;\n    repeat rewrite firstn_oob; simpl; auto;\n    repeat rewrite map_app;\n    setoid_rewrite map_fst_repeat;\n    repeat rewrite combine_nonzero_app_zeros; auto.\n  Qed.\n\n  Lemma addr_valid_padded : forall l,\n    Forall addr_valid l -> Forall addr_valid (padded_log l).\n  Proof.\n    unfold padded_log, setlen, roundup; intros.\n    rewrite firstn_oob; simpl; auto.\n    apply Forall_append; auto.\n    rewrite Forall_forall; intros.\n    apply repeat_spec in H0; subst.\n    unfold addr_valid; simpl.\n    apply zero_lt_pow2.\n  Qed.\n\n  Lemma padded_addr_valid : forall l,\n    Forall addr_valid (padded_log l) ->\n    Forall addr_valid l.\n  Proof.\n    unfold padded_log, setlen; intros.\n    rewrite firstn_oob in H; auto.\n    eapply forall_app_r; eauto.\n  Qed.\n\n  Local Hint Resolve addr_valid_padded padded_addr_valid.\n\n  Lemma map_wordToNat_ent_addr : forall l,\n    Forall addr_valid l ->\n    (map (@wordToNat _) (map ent_addr l)) = map fst l.\n  Proof.\n    unfold ent_addr, addr2w.\n    induction l; intros; simpl; auto.\n    rewrite IHl; f_equal.\n    rewrite wordToNat_natToWord_idempotent'; auto.\n    apply Forall_inv in H; unfold addr_valid in H; auto.\n    eapply Forall_cons2; eauto.\n  Qed.\n\n  Lemma combine_nonzero_padded_wordToNat : forall l,\n    Forall addr_valid l ->\n    combine_nonzero (map (@wordToNat _) (map ent_addr (padded_log l))) (vals_nonzero l) = log_nonzero l.\n  Proof.\n    intros; unfold ent_addr, addr2w.\n    rewrite <- combine_nonzero_ok.\n    rewrite <- combine_nonzero_padded_log.\n    f_equal.\n    rewrite map_wordToNat_ent_addr; auto.\n  Qed.\n\n  Lemma vals_nonzero_addrs : forall l,\n    length (vals_nonzero l) = nonzero_addrs (map fst l).\n  Proof.\n    induction l; intros; simpl; auto.\n    destruct a, n; simpl; auto.\n  Qed.\n\n  Lemma log_nonzero_addrs : forall l,\n    length (log_nonzero l) = nonzero_addrs (map fst l).\n  Proof.\n    induction l; intros; simpl; auto.\n    destruct a, n; simpl; auto.\n  Qed.\n\n  Lemma desc_ipack_padded : forall l,\n    DescDefs.ipack (map ent_addr l) = DescDefs.ipack (map ent_addr (padded_log l)).\n  Proof.\n    unfold padded_log, setlen; intros.\n    rewrite firstn_oob, map_app, map_entaddr_repeat_0 by auto.\n    rewrite DescDefs.ipack_app_item0; auto.\n    rewrite map_length; auto.\n  Qed.\n\n  Local Hint Resolve combine_nonzero_padded_wordToNat.\n\n  Lemma desc_padding_synced_piff : forall xp a l,\n    Desc.array_rep xp a (Desc.Synced (map ent_addr (padded_log l)))\n    <=p=> Desc.array_rep xp a (Desc.Synced (map ent_addr l)).\n  Proof.\n     unfold Desc.array_rep, Desc.synced_array, Desc.rep_common; intros.\n     split; cancel; subst.\n     unfold padded_log, setlen, roundup in H0.\n     rewrite firstn_oob, map_app in H0 by auto.\n     apply Desc.items_valid_app in H0; intuition.\n     apply eq_sym; apply desc_ipack_padded.\n     unfold padded_log, setlen, roundup.\n     rewrite firstn_oob, map_app by auto.\n     apply Desc.items_valid_app2; auto.\n     autorewrite with lists; auto.\n     apply desc_ipack_padded.\n  Qed.\n\n  Lemma desc_padding_unsync_piff : forall xp a l,\n    Desc.array_rep xp a (Desc.Unsync (map ent_addr (padded_log l)))\n    <=p=> Desc.array_rep xp a (Desc.Unsync (map ent_addr l)).\n  Proof.\n     unfold Desc.array_rep, Desc.unsync_array, Desc.rep_common; intros.\n     split; cancel; subst.\n     unfold padded_log, setlen, roundup in H.\n     rewrite firstn_oob, map_app in H by auto.\n     apply Desc.items_valid_app in H; intuition.\n     apply eq_sym; apply desc_ipack_padded.\n     unfold padded_log, setlen, roundup.\n     rewrite firstn_oob, map_app by auto.\n     apply Desc.items_valid_app2; auto.\n     autorewrite with lists; auto.\n     apply desc_ipack_padded.\n  Qed.\n\n  Lemma goodSize_ndesc : forall l,\n    goodSize addrlen (length l) -> goodSize addrlen (ndesc_log l).\n  Proof.\n    intros; unfold ndesc_log.\n    eapply goodSize_trans; [ apply divup_le | eauto ].\n    destruct (mult_O_le (length l) DescSig.items_per_val); auto.\n    contradict H0; apply DescDefs.items_per_val_not_0.\n  Qed.\n  Local Hint Resolve goodSize_ndesc.\n\n  Lemma padded_log_length: forall l,\n    length (padded_log l) = roundup (length l) DescSig.items_per_val.\n  Proof.\n    unfold padded_log, roundup; intros.\n    rewrite setlen_length; auto.\n  Qed.\n\n  Lemma nonzero_addrs_app_zero : forall a,\n    nonzero_addrs (a ++ [0]) = nonzero_addrs a.\n  Proof.\n    induction a; intros; simpl; auto.\n    destruct a; simpl; auto.\n  Qed.\n\n  Lemma nonzero_addrs_app_zeros : forall n a,\n    nonzero_addrs (a ++ repeat 0 n) = nonzero_addrs a.\n  Proof.\n    induction n; intros; simpl.\n    rewrite app_nil_r; auto.\n    rewrite <- cons_nil_app.\n    rewrite IHn.\n    apply nonzero_addrs_app_zero.\n  Qed.\n\n  Lemma nonzero_addrs_padded_log : forall l,\n    nonzero_addrs (map fst (padded_log l)) = nonzero_addrs (map fst l).\n  Proof.\n    unfold padded_log; induction l; simpl; auto.\n    rewrite setlen_nil, repeat_is_nil; simpl; auto.\n    unfold roundup; rewrite divup_0; omega.\n    \n    destruct a, n; simpl;\n    rewrite <- IHl;\n    unfold setlen, roundup;\n    repeat rewrite firstn_oob, map_app by auto;\n    setoid_rewrite map_fst_repeat;\n    repeat rewrite nonzero_addrs_app_zeros; simpl; auto.\n  Qed.\n\n  Lemma vals_nonzero_length : forall l,\n    length (vals_nonzero l) <= length l.\n  Proof.\n    unfold vals_nonzero; induction l; intros; simpl; auto.\n    destruct a, n; simpl; auto.\n    autorewrite with lists in *; omega.\n  Qed.\n\n  Lemma vals_nonzero_app : forall a b,\n    vals_nonzero (a ++ b) = vals_nonzero a ++ vals_nonzero b.\n  Proof.\n    unfold vals_nonzero; induction a; intros; simpl; auto.\n    destruct a, n; simpl; auto.\n    rewrite IHa; auto.\n  Qed.\n\n  Lemma log_nonzero_repeat_0 : forall n,\n    log_nonzero (repeat (0, $0) n) = nil.\n  Proof.\n    induction n; simpl; auto.\n  Qed.\n\n  Lemma log_nonzero_app : forall a b,\n    log_nonzero (a ++ b) = log_nonzero a ++ log_nonzero b.\n  Proof.\n    induction a; simpl; intros; auto.\n    destruct a, n; simpl; auto.\n    rewrite IHa; auto.\n  Qed.\n\n  Lemma vals_nonzero_padded_log : forall l,\n    vals_nonzero (padded_log l) = vals_nonzero l.\n  Proof.\n    unfold vals_nonzero, padded_log, setlen, roundup; simpl.\n    induction l; intros; simpl; auto.\n    rewrite firstn_oob; simpl; auto.\n    rewrite log_nonzero_repeat_0; auto.\n\n    destruct a, n.\n    rewrite <- IHl.\n    repeat rewrite firstn_oob; simpl; auto.\n    repeat rewrite log_nonzero_app, map_app.\n    repeat rewrite log_nonzero_repeat_0; auto.\n\n    repeat rewrite firstn_oob; simpl; auto.\n    f_equal.\n    repeat rewrite log_nonzero_app, map_app.\n    repeat rewrite log_nonzero_repeat_0; auto.\n    simpl; rewrite app_nil_r; auto.\n  Qed.\n\n  Lemma ndata_log_goodSize : forall l,\n    goodSize addrlen (length l) -> goodSize addrlen (ndata_log l).\n  Proof.\n    unfold ndata_log; intros.\n    rewrite <- vals_nonzero_addrs.\n    eapply goodSize_trans.\n    apply vals_nonzero_length; auto.\n    auto.\n  Qed.\n  Local Hint Resolve ndata_log_goodSize.\n\n  Lemma padded_log_idem : forall l,\n    padded_log (padded_log l) = padded_log l.\n  Proof.\n    intros.\n    unfold padded_log.\n    rewrite setlen_length.\n    rewrite roundup_roundup; auto.\n    rewrite setlen_exact; auto.\n    rewrite setlen_length; auto.\n  Qed.\n\n  Lemma padded_log_app : forall l1 l2,\n    padded_log (padded_log l1 ++ l2) = padded_log l1 ++ padded_log l2.\n  Proof.\n    intros.\n    unfold padded_log.\n    rewrite setlen_app_r.\n    f_equal.\n    rewrite app_length, setlen_length.\n    rewrite roundup_roundup_add; auto.\n    f_equal; omega.\n    rewrite app_length, setlen_length.\n    rewrite roundup_roundup_add; auto.\n    omega.\n  Qed.\n\n  Ltac solve_checksums :=\n  try (match goal with\n    | [ |- checksums_match _ _ _ ]\n      => unfold checksums_match in *\n    end; intuition;\n    [\n      solve_hash_list_rep;\n      try (rewrite map_app;\n      erewrite DescDefs.ipack_app;\n      try solve [ rewrite map_length, padded_log_length; unfold roundup; eauto ];\n      rewrite rev_app_distr)\n      | solve_hash_list_rep;\n      try rewrite vals_nonzero_app, vals_nonzero_padded_log, rev_app_distr;\n      try rewrite padded_log_app, map_app, rev_app_distr\n    ];\n    repeat match goal with\n    | [ H: context[hash_list_rep (_ ++ [])] |- _ ]\n      => rewrite app_nil_r in H\n    end;\n    try rewrite <- desc_ipack_padded in *;\n    solve_hash_list_rep).\n\n\n  Arguments Desc.array_rep : simpl never.\n  Arguments Data.array_rep : simpl never.\n  Arguments Desc.avail_rep : simpl never.\n  Arguments Data.avail_rep : simpl never.\n  Arguments divup : simpl never.\n  Hint Extern 0 (okToUnify (Hdr.rep _ _) (Hdr.rep _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (Desc.array_rep _ _ _) (Desc.array_rep _ _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (Data.array_rep _ _ _) (Data.array_rep _ _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (Desc.avail_rep _ _ _) (Desc.avail_rep _ _ _)) => constructor : okToUnify.\n  Hint Extern 0 (okToUnify (Data.avail_rep _ _ _) (Data.avail_rep _ _ _)) => constructor : okToUnify.\n\n\n  Definition avail_ok : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm)%pred d ]]\n    POST:hm' RET: ^(cs, r)\n          BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm')%pred d ]] *\n          [[ r = (LogLen xp) - roundup (length l) DescSig.items_per_val ]]\n    CRASH:hm_crash exists cs',\n          BUFCACHE.rep cs' d *\n          [[ (F * rep xp (Synced l) hm_crash)%pred d ]]\n    >} avail xp cs.\n  Proof.\n    unfold avail.\n    safestep.\n    safestep.\n    solve_checksums.\n    cancel.\n    solve_checksums.\n  Qed.\n\n  Definition read_ok : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm)%pred d ]]\n    POST:hm' RET: ^(cs, r)\n          BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm')%pred d ]] *\n          [[ r = log_nonzero l ]]\n    CRASH:hm_crash exists cs',\n          BUFCACHE.rep cs' d *\n          [[ (F * rep xp (Synced l) hm_crash)%pred d ]]\n    >} read xp cs.\n  Proof.\n    unfold read.\n    safestep.\n\n    prestep. norm. cancel. intuition simpl.\n    eassign (map ent_addr (padded_log l)).\n    rewrite map_length, padded_log_length.\n    auto. auto.\n    pred_apply.\n    rewrite desc_padding_synced_piff; cancel.\n\n    safestep; subst.\n    setoid_rewrite vals_nonzero_addrs; unfold ndata_log.\n    replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n    replace (map ent_valu (log_nonzero l)) with (vals_nonzero l); auto.\n    safestep.\n    rewrite desc_padding_synced_piff; cancel.\n    solve_checksums.\n\n    pimpl_crash; cancel.\n    rewrite desc_padding_synced_piff; cancel.\n    solve_checksums.\n\n    cancel.\n    solve_checksums.\n    cancel.\n    solve_checksums.\n  Qed.\n\n  Lemma goodSize_0 : forall sz, goodSize sz 0.\n  Proof.\n    unfold goodSize; intros.\n    apply zero_lt_pow2.\n  Qed.\n\n  Lemma ndesc_log_nil : ndesc_log nil = 0.\n  Proof.\n    unfold ndesc_log; simpl.\n    rewrite divup_0; auto.\n  Qed.\n\n  Lemma ndata_log_nil : ndata_log nil = 0.\n  Proof.\n    unfold ndata_log; simpl; auto.\n  Qed.\n\n  Local Hint Resolve goodSize_0.\n\n\n  Definition init xp cs :=\n    cs <- Hdr.init xp cs;\n    Ret cs.\n\n  Definition trunc xp cs :=\n    let^ (cs, nr) <- Hdr.read xp cs;\n    let '(_, current_length, _) := nr in\n    h <- Hash default_valu;\n    cs <- Hdr.write xp (current_length, (0, 0), (h, h)) cs;\n    cs <- Hdr.sync_now xp cs;\n    Ret cs.\n\n  Local Hint Resolve Forall_nil.\n\n\n  Definition initrep xp :=\n    (exists hdr, LogHeader xp |+> hdr *\n     Desc.avail_rep xp 0 (LogDescLen xp) *\n     Data.avail_rep xp 0 (LogLen xp))%pred.\n\n\n  Definition init_ok' : forall xp cs,\n    {< F d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * initrep xp)%pred d ]] *\n          [[ xparams_ok xp /\\ sync_invariant F ]]\n    POST:hm' RET: cs  exists d',\n          BUFCACHE.rep cs d' *\n          [[ (F * rep xp (Synced nil) hm')%pred d' ]]\n    XCRASH:hm_crash any\n    >} init xp cs.\n  Proof.\n    unfold init, initrep.\n    prestep; unfold rep, Hdr.LAHdr; safecancel.\n    auto.\n    step.\n    unfold ndesc_log, ndata_log; rewrite divup_0; simpl; cancel.\n    repeat rewrite Nat.sub_0_r; cbn; cancel.\n    rewrite Desc.array_rep_sync_nil, Data.array_rep_sync_nil by (auto; omega); cancel.\n    solve_checksums; simpl; auto.\n    setoid_rewrite DescDefs.ipack_nil; simpl.\n    solve_hash_list_rep; auto.\n  Qed.\n\n  Definition init_ok : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * arrayS (LogHeader xp) l)%pred d ]] *\n          [[ length l = (1 + LogDescLen xp + LogLen xp) /\\\n             LogDescriptor xp = LogHeader xp + 1 /\\\n             LogData xp = LogDescriptor xp + LogDescLen xp /\\\n             xparams_ok xp ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET: cs  exists d',\n          BUFCACHE.rep cs d' *\n          [[ (F * rep xp (Synced nil) hm')%pred d' ]]\n    XCRASH:hm_crash any\n    >} init xp cs.\n  Proof.\n    intros.\n    eapply pimpl_ok2. apply init_ok'.\n    intros; unfold initrep; safecancel.\n    unfold Desc.avail_rep, Data.avail_rep.\n    rewrite arrayN_isolate_hd by omega.\n    repeat rewrite Nat.add_0_r.\n    rewrite arrayN_split with (i := LogDescLen xp).\n    rewrite surjective_pairing with (p := selN l 0 ($0, nil)).\n    substl (LogData xp); substl (LogDescriptor xp).\n    cancel.\n    rewrite firstn_length_l; auto.\n    setoid_rewrite skipn_length with (n := 1); omega.\n    setoid_rewrite skipn_skipn with (m := 1).\n    rewrite skipn_length; omega.\n    auto.\n    step.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (init _ _) _) => apply init_ok : prog.\n\n\n  Lemma helper_sep_star_reorder : forall (a b c d : rawpred),\n    a * b * c * d =p=> (a * c) * (b * d).\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_add_sub_0 : forall a b,\n    a <= b -> a + (b - a) + 0 = b.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma helper_trunc_ok : forall xp l prev_len h,\n    Desc.array_rep xp 0 (Desc.Synced (map ent_addr l)) *\n    Data.array_rep xp 0 (Data.Synced (vals_nonzero l)) *\n    Desc.avail_rep xp (ndesc_log l) (LogDescLen xp - ndesc_log l) *\n    Data.avail_rep xp (ndata_log l) (LogLen xp - ndata_log l) *\n    Hdr.rep xp (Hdr.Synced (prev_len, (0, 0), h))\n    =p=>\n    Hdr.rep xp (Hdr.Synced (prev_len, (ndesc_log [], ndata_log []), h)) *\n    Desc.array_rep xp 0 (Desc.Synced []) *\n    Data.array_rep xp 0 (Data.Synced (vals_nonzero [])) *\n    Desc.avail_rep xp (ndesc_log []) (LogDescLen xp - ndesc_log []) *\n    Data.avail_rep xp (ndata_log []) (LogLen xp - ndata_log []).\n  Proof.\n    intros.\n    unfold ndesc_log, vals_nonzero; simpl; rewrite divup_0.\n    rewrite Desc.array_rep_sync_nil_sep_star, Data.array_rep_sync_nil_sep_star; auto.\n    cancel.\n    unfold ndata_log; simpl; repeat rewrite Nat.sub_0_r.\n    rewrite <- log_nonzero_addrs.\n    rewrite Data.array_rep_size_ok_pimpl, Desc.array_rep_size_ok_pimpl.\n    rewrite Data.array_rep_avail, Desc.array_rep_avail.\n    simpl; rewrite divup_1; autorewrite with lists.\n    cancel.\n    rewrite helper_sep_star_reorder.\n    rewrite Desc.avail_rep_merge by auto.\n    rewrite Data.avail_rep_merge by auto.\n    rewrite !le_plus_minus_r by auto.\n    cancel.\n  Qed.\n\n\n  (* XXX:\n    Ideally XCRASH can contain only Truncated state, whose crash_xform \n    covers the Synced state's crash_xform. However, to prove that, we need \n    to construct a raw disk that satisifies the Truncated state given a raw\n    disk of Synced state.  This involves reverse engineering Hdr.rep.\n  *)\n  Definition trunc_ok : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm)%pred d ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET: cs  exists d',\n          BUFCACHE.rep cs d' *\n          [[ (F * rep xp (Synced nil) hm')%pred d' ]]\n    XCRASH:hm_crash exists cs' d',\n          BUFCACHE.rep cs' d' * (\n          [[ (F * (rep xp (Synced l) hm_crash))%pred d' ]] \\/\n          [[ (F * (rep xp (Truncated l) hm_crash))%pred d' ]] )\n    >} trunc xp cs.\n  Proof.\n    unfold trunc.\n    step.\n    step.\n    step.\n\n    unfold Hdr.rep in H0.\n    destruct_lift H0.\n    unfold Hdr.hdr_goodSize in *; intuition.\n\n    step.\n    step.\n\n    (* post condition *)\n    cancel_by helper_trunc_ok.\n    solve_checksums.\n    replace (DescDefs.ipack (map ent_addr [])) with (@nil valu).\n    solve_hash_list_rep; auto.\n    symmetry. apply DescDefs.ipack_nil.\n    auto.\n\n    (* crash conditions *)\n    repeat xcrash_rewrite.\n    xform_norm. cancel. xform_normr; cancel.\n    or_r; cancel.\n    solve_checksums.\n    solve_checksums; auto.\n    setoid_rewrite DescDefs.ipack_nil; simpl.\n    solve_hash_list_rep; auto.\n\n    repeat xcrash_rewrite.\n    xform_norm; cancel. xform_normr; cancel.\n    or_r; cancel.\n    solve_checksums.\n    solve_checksums; auto.\n    setoid_rewrite DescDefs.ipack_nil; simpl.\n    solve_hash_list_rep; auto.\n\n    xcrash_rewrite.\n    xform_normr; cancel.\n    or_l; cancel.\n    solve_checksums.\n\n    xcrash_rewrite.\n    xform_normr; cancel.\n    or_l; cancel.\n    solve_checksums.\n\n    Unshelve.\n    constructor.\n  Qed.\n\n  Theorem loglen_valid_dec xp ndesc ndata :\n    {loglen_valid xp ndesc ndata} + {loglen_invalid xp ndesc ndata }.\n  Proof.\n    unfold loglen_valid, loglen_invalid.\n    destruct (lt_dec (LogDescLen xp) ndesc);\n    destruct (lt_dec (LogLen xp) ndata); simpl; auto.\n    left; intuition.\n  Defined.\n\n  Remove Hints goodSize_0.\n\n  Definition entry_valid_ndata : forall l,\n    Forall entry_valid l -> ndata_log l = length l.\n  Proof.\n    unfold ndata_log; induction l; rewrite Forall_forall; intuition.\n    destruct a, n; simpl.\n    exfalso; intuition.\n    apply (H (0, w)); simpl; auto.\n    rewrite IHl; auto.\n    rewrite Forall_forall; intros.\n    apply H; simpl; intuition.\n  Qed.\n\n  Lemma loglen_valid_desc_valid : forall xp old new,\n    DescSig.xparams_ok xp ->\n    loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    Desc.items_valid xp (ndesc_log old) (map ent_addr new).\n  Proof.\n    unfold Desc.items_valid, loglen_valid.\n    intuition.\n    unfold DescSig.RALen; omega.\n    autorewrite with lists; unfold DescSig.RALen.\n    apply divup_ge; auto.\n    unfold ndesc_log in *; omega.\n  Qed.\n  Local Hint Resolve loglen_valid_desc_valid.\n\n\n  Lemma loglen_valid_data_valid : forall xp old new,\n    DataSig.xparams_ok xp ->\n    Forall entry_valid new ->\n    loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    Data.items_valid xp (ndata_log old) (map ent_valu new).\n  Proof.\n    unfold Data.items_valid, loglen_valid.\n    intuition.\n    unfold DataSig.RALen; omega.\n    autorewrite with lists; unfold DataSig.RALen.\n    apply divup_ge; auto.\n    rewrite divup_1; rewrite <- entry_valid_ndata by auto.\n    unfold ndata_log in *; omega.\n  Qed.\n  Local Hint Resolve loglen_valid_data_valid.\n\n  Lemma helper_loglen_desc_valid_extend : forall xp new old,\n    loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    ndesc_log new + (LogDescLen xp - ndesc_log old - ndesc_log new) \n      = LogDescLen xp - ndesc_log old.\n  Proof.\n    unfold loglen_valid, ndesc_log; intros.\n    omega.\n  Qed.\n\n  Lemma helper_loglen_data_valid_extend : forall xp new old,\n    loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    ndata_log new + (LogLen xp - ndata_log old - ndata_log new) \n      = LogLen xp - ndata_log old.\n  Proof.\n    unfold loglen_valid, ndata_log; intros.\n    omega.\n  Qed.\n\n  Lemma helper_loglen_data_valid_extend_entry_valid : forall xp new old,\n    Forall entry_valid new ->\n    loglen_valid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    length new + (LogLen xp - ndata_log old - ndata_log new) \n      = LogLen xp - ndata_log old.\n  Proof.\n    intros.\n    rewrite <- entry_valid_ndata by auto.\n    apply helper_loglen_data_valid_extend; auto.\n  Qed.\n\n  Lemma padded_desc_valid : forall xp st l,\n    Desc.items_valid xp st (map ent_addr l)\n    -> Desc.items_valid xp st (map ent_addr (padded_log l)).\n  Proof.\n    unfold Desc.items_valid; intuition.\n    autorewrite with lists in *.\n    rewrite padded_log_length; unfold roundup.\n    apply Nat.mul_le_mono_pos_r.\n    apply DescDefs.items_per_val_gt_0.\n    apply divup_le; lia.\n  Qed.\n\n  Lemma mul_le_mono_helper : forall a b,\n    b > 0 -> a <= a * b.\n  Proof.\n    intros; rewrite Nat.mul_comm.\n    destruct (mult_O_le a b); auto; omega.\n  Qed.\n\n  Lemma loglen_valid_goodSize_l : forall xp a b,\n    loglen_valid xp a b -> DescSig.xparams_ok xp -> DataSig.xparams_ok xp ->\n    goodSize addrlen a.\n  Proof.\n    unfold loglen_valid, DescSig.xparams_ok, DataSig.xparams_ok; intuition.\n    eapply goodSize_trans.\n    eapply le_trans. eauto.\n    apply le_plus_r. eauto.\n  Qed.\n\n  Lemma loglen_valid_goodSize_r : forall xp a b,\n    loglen_valid xp a b -> DescSig.xparams_ok xp -> DataSig.xparams_ok xp ->\n    goodSize addrlen b.\n  Proof.\n    unfold loglen_valid, DescSig.xparams_ok, DataSig.xparams_ok; intuition.\n    eapply goodSize_trans.\n    eapply le_trans. eauto.\n    apply le_plus_r. eauto.\n  Qed.\n\n  Lemma ent_valid_addr_valid : forall l,\n    Forall entry_valid l -> Forall addr_valid l.\n  Proof.\n    intros; rewrite Forall_forall in *; intros.\n    apply H; auto.\n  Qed.\n  Local Hint Resolve ent_valid_addr_valid.\n  Local Hint Resolve Forall_append DescDefs.items_per_val_not_0.\n\n  Lemma helper_add_sub : forall a b,\n    a <= b -> a + (b - a) = b.\n  Proof.\n    intros; omega.\n  Qed.\n\n\n  Lemma nonzero_addrs_app : forall a b,\n    nonzero_addrs (a ++ b) = nonzero_addrs a + nonzero_addrs b.\n  Proof.\n    induction a; intros; simpl; auto.\n    destruct a; auto.\n    rewrite IHa; omega.\n  Qed.\n\n  Lemma ndata_log_app : forall a b,\n    ndata_log (a ++ b) = ndata_log a + ndata_log b.\n  Proof.\n    unfold ndata_log;  intros.\n    repeat rewrite map_app.\n    rewrite nonzero_addrs_app; auto.\n  Qed.\n\n  Lemma ndesc_log_padded_log : forall l,\n    ndesc_log (padded_log l) = ndesc_log l.\n  Proof.\n    unfold ndesc_log; intros.\n    rewrite padded_log_length.\n    unfold roundup; rewrite divup_divup; auto.\n  Qed.\n\n  Lemma ndesc_log_app : forall a b,\n    length a = roundup (length a) DescSig.items_per_val ->\n    ndesc_log (a ++ b) = ndesc_log a + ndesc_log b.\n  Proof.\n    unfold ndesc_log; intros.\n    rewrite app_length, H at 1.\n    unfold roundup.\n    rewrite Nat.add_comm, Nat.mul_comm.\n    rewrite divup_add by auto.\n    omega.\n  Qed.\n\n  Lemma ndesc_log_padded_app : forall a b,\n    ndesc_log (padded_log a ++ b) = ndesc_log a + ndesc_log b.\n  Proof.\n    intros.\n    rewrite ndesc_log_app.\n    rewrite ndesc_log_padded_log; auto.\n    rewrite padded_log_length.\n    rewrite roundup_roundup; auto.\n  Qed.\n\n  Lemma ndata_log_padded_log : forall a,\n    ndata_log (padded_log a) = ndata_log a.\n  Proof.\n    unfold ndata_log, padded_log, setlen, roundup; intros.\n    rewrite firstn_oob by auto.\n    repeat rewrite map_app.\n    rewrite repeat_map; simpl.\n    rewrite nonzero_addrs_app.\n    setoid_rewrite <- app_nil_l at 3.\n    rewrite nonzero_addrs_app_zeros; auto.\n  Qed.\n\n\n  Lemma ndata_log_padded_app : forall a b,\n    ndata_log (padded_log a ++ b) = ndata_log a + ndata_log b.\n  Proof.\n    intros.\n    rewrite ndata_log_app.\n    rewrite ndata_log_padded_log; auto.\n  Qed.\n\n  Lemma log_nonzero_rev_comm : forall l,\n    log_nonzero (rev l) = rev (log_nonzero l).\n  Proof.\n    induction l; simpl; intros; auto.\n    destruct a, n; simpl; auto;\n    rewrite log_nonzero_app; simpl.\n    rewrite app_nil_r. congruence.\n    congruence.\n  Qed.\n\n  Lemma entry_valid_vals_nonzero : forall l,\n    Forall entry_valid l ->\n    log_nonzero l = l.\n  Proof.\n    unfold entry_valid; induction l; simpl; auto.\n    destruct a, n; simpl; auto; intros.\n    exfalso.\n    rewrite Forall_forall in H; intuition.\n    apply (H (0, w)); simpl; auto.\n    rewrite IHl; auto.\n    eapply Forall_cons2; eauto.\n  Qed.\n\n  Lemma nonzero_addrs_entry_valid : forall l,\n    Forall entry_valid l ->\n    nonzero_addrs (map fst l) = length l.\n  Proof.\n    induction l; simpl; intros; auto.\n    destruct a, n; simpl.\n    exfalso.\n    rewrite Forall_forall in H.\n    apply (H (0, w)); simpl; auto.\n    rewrite IHl; auto.\n    eapply Forall_cons2; eauto.\n  Qed.\n\n  Lemma desc_ipack_injective : forall l1 l2 n1 n2,\n    length l1 = n1 * DescSig.items_per_val ->\n    length l2 = n2 * DescSig.items_per_val ->\n    DescDefs.ipack l1 = DescDefs.ipack l2 ->\n    l1 = l2.\n  Proof.\n    intros.\n    erewrite <- DescDefs.iunpack_ipack; eauto.\n    erewrite <- DescDefs.iunpack_ipack at 1; eauto.\n    congruence.\n  Qed.\n\n  Lemma ndesc_log_ndesc_list : forall l,\n    ndesc_log l = ndesc_list (map ent_addr (padded_log l)).\n  Proof.\n    unfold ndesc_log, ndesc_list.\n    intros.\n    autorewrite with lists.\n    rewrite padded_log_length.\n    unfold roundup.\n    rewrite divup_divup; auto.\n  Qed.\n\n\n  Lemma extend_ok_helper : forall F xp old new,\n    Forall entry_valid new ->\n    Data.array_rep xp (ndata_log old) (Data.Synced (map ent_valu new)) *\n    Desc.array_rep xp 0 (Desc.Synced (map ent_addr old)) *\n    Data.array_rep xp 0 (Data.Synced (vals_nonzero old)) *\n    Desc.avail_rep xp (ndesc_log old + divup (length (map ent_addr new)) DescSig.items_per_val)\n      (LogDescLen xp - ndesc_log old - ndesc_log new) *\n    Data.avail_rep xp (ndata_log old + divup (length (map ent_valu new)) DataSig.items_per_val)\n      (LogLen xp - ndata_log old - ndata_log new) *\n    Desc.array_rep xp (ndesc_log old) (Desc.Synced (map ent_addr (padded_log new))) * F\n    =p=>\n    Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old ++ new))) *\n    Data.array_rep xp 0 (Data.Synced (vals_nonzero (padded_log old ++ new))) *\n    Desc.avail_rep xp (ndesc_log (padded_log old ++ new)) \n                      (LogDescLen xp - ndesc_log (padded_log old ++ new)) *\n    Data.avail_rep xp (ndata_log (padded_log old ++ new))\n                      (LogLen xp - ndata_log (padded_log old ++ new)) * F.\n  Proof.\n    intros.\n    repeat rewrite ndesc_log_padded_app, ndata_log_padded_app.\n    setoid_rewrite Nat.sub_add_distr.\n    unfold ndesc_log.\n    rewrite divup_1.\n    rewrite entry_valid_ndata with (l := new); auto.\n    repeat rewrite map_length.\n    rewrite map_app, vals_nonzero_app.\n    rewrite <- Desc.array_rep_synced_app.\n    rewrite <- Data.array_rep_synced_app.\n    repeat rewrite Nat.add_0_l.\n    repeat rewrite desc_padding_synced_piff.\n    repeat rewrite map_length.\n    repeat rewrite vals_nonzero_padded_log.\n    rewrite divup_1, padded_log_length.\n    unfold roundup; rewrite divup_mul; auto.\n    unfold ndata_log; rewrite vals_nonzero_addrs.\n    unfold vals_nonzero; rewrite entry_valid_vals_nonzero with (l := new); auto.\n    cancel.\n\n    rewrite Nat.mul_1_r; auto.\n    rewrite map_length, padded_log_length.\n    unfold roundup; auto.\n  Qed.\n\n  Lemma nonzero_addrs_bound : forall l,\n    nonzero_addrs l <= length l.\n  Proof.\n    induction l; simpl; auto.\n    destruct a; omega.\n  Qed.\n\n  Lemma extend_ok_synced_hdr_helper : forall xp prev_len old new h,\n    Hdr.rep xp (Hdr.Synced (prev_len,\n                            (ndesc_log old + ndesc_log new,\n                             ndata_log old + ndata_log new),\n                            h))\n    =p=>\n    Hdr.rep xp (Hdr.Synced (prev_len,\n                            (ndesc_log (padded_log old ++ new),\n                             ndata_log (padded_log old ++ new)),\n                            h)).\n  Proof.\n    intros.\n    rewrite ndesc_log_padded_app, ndata_log_padded_app; auto.\n  Qed.\n\n  Local Hint Resolve extend_ok_synced_hdr_helper.\n\n  Lemma nonzero_addrs_roundup : forall B (l : list (addr * B)) n,\n    n > 0 ->\n    nonzero_addrs (map fst l) <= (divup (length l) n) * n.\n  Proof.\n    intros.\n    eapply le_trans.\n    apply nonzero_addrs_bound.\n    rewrite map_length.\n    apply roundup_ge; auto.\n  Qed.\n\n  Lemma loglen_invalid_overflow : forall xp old new,\n    LogLen xp = DescSig.items_per_val * LogDescLen xp ->\n    loglen_invalid xp (ndesc_log old + ndesc_log new) (ndata_log old + ndata_log new) ->\n    length (padded_log old ++ new) > LogLen xp.\n  Proof.\n    unfold loglen_invalid, ndesc_log, ndata_log; intros.\n    rewrite app_length; repeat rewrite padded_log_length.\n    unfold roundup; intuition.\n    rewrite H.\n    setoid_rewrite <- Nat.mul_comm at 2.\n    apply divup_add_gt; auto.\n\n    eapply lt_le_trans; eauto.\n    apply Nat.add_le_mono.\n    apply nonzero_addrs_roundup; auto.\n    erewrite <- map_length.\n    apply nonzero_addrs_bound.\n  Qed.\n\n  Hint Rewrite Desc.array_rep_avail Data.array_rep_avail\n     padded_log_length divup_mul divup_1 map_length\n     ndesc_log_padded_log nonzero_addrs_padded_log using auto: extend_crash.\n  Hint Unfold roundup ndata_log : extend_crash.\n\n  Ltac extend_crash :=\n     repeat (autorewrite with extend_crash; autounfold with extend_crash; simpl);\n     setoid_rewrite <- Desc.avail_rep_merge at 3;\n     [ setoid_rewrite <- Data.avail_rep_merge at 3 | ];\n     [ cancel\n     | apply helper_loglen_data_valid_extend_entry_valid; auto\n     | apply helper_loglen_desc_valid_extend; auto ].\n\n  Lemma log_nonzero_padded_log : forall l,\n    log_nonzero (padded_log l) = log_nonzero l.\n  Proof.\n    unfold padded_log, setlen, roundup; intros.\n    rewrite firstn_oob by auto.\n    rewrite log_nonzero_app.\n    rewrite log_nonzero_repeat_0, app_nil_r; auto.\n  Qed.\n\n  Lemma log_nonzero_padded_app : forall l new,\n    Forall entry_valid new ->\n    log_nonzero l ++ new = log_nonzero (padded_log l ++ padded_log new).\n  Proof.\n    intros.\n    rewrite log_nonzero_app.\n    repeat rewrite log_nonzero_padded_log.\n    f_equal.\n    rewrite entry_valid_vals_nonzero; auto.\n  Qed.\n\n  Lemma log_nonzero_app_padded : forall l new,\n    Forall entry_valid new ->\n    log_nonzero l ++ new = log_nonzero (l ++ padded_log new).\n  Proof.\n    intros.\n    rewrite log_nonzero_app, log_nonzero_padded_log.\n    f_equal.\n    rewrite entry_valid_vals_nonzero; auto.\n  Qed.\n\n  Definition extend xp log cs :=\n    (* Synced *)\n    let^ (cs, nr) <- Hdr.read xp cs;\n    let '(_, (ndesc, ndata), (h_addr, h_valu)) := nr in\n    let '(nndesc, nndata) := ((ndesc_log log), (ndata_log log)) in\n    If (loglen_valid_dec xp (ndesc + nndesc) (ndata + nndata)) {\n      h_addr <- hash_list h_addr (DescDefs.nopad_ipack (map ent_addr log));\n      h_valu <- hash_list h_valu (vals_nonzero log);\n      cs <- Desc.write_aligned xp ndesc (map ent_addr log) cs;\n      cs <- Data.write_aligned xp ndata (map ent_valu log) cs;\n      cs <- Hdr.write xp ((ndesc, ndata),\n                          (ndesc + nndesc, ndata + nndata),\n                          (h_addr, h_valu)) cs;\n      (* Extended *)\n      cs <- BUFCACHE.begin_sync cs;\n      cs <- Desc.sync_aligned xp ndesc nndesc cs;\n      cs <- Data.sync_aligned xp ndata nndata cs;\n      cs <- Hdr.sync xp cs;\n      cs <- BUFCACHE.end_sync cs;\n      (* Synced *)\n      Ret ^(cs, true)\n    } else {\n      Ret ^(cs, false)\n    }.\n\n  Lemma rep_hashmap_subset : forall xp hm hm',\n    (exists l, hashmap_subset l hm hm')\n    -> forall st, rep xp st hm\n        =p=> rep xp st hm'.\n  Proof.\n    intros.\n    destruct st; unfold rep, rep_inner; cancel; solve_checksums.\n    auto.\n  Qed.\n\n  Lemma would_recover'_hashmap_subset : forall xp l hm hm',\n    (exists l, hashmap_subset l hm hm') ->\n    would_recover' xp l hm\n    =p=> would_recover' xp l hm'.\n  Proof.\n    unfold would_recover'.\n    intros.\n    cancel;\n    rewrite rep_hashmap_subset; auto; cancel.\n  Qed.\n\n  Definition extend_ok : forall xp new cs,\n    {< F old d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced old) hm)%pred d ]] *\n          [[ Forall entry_valid new /\\ sync_invariant F ]]\n    POST:hm' RET: ^(cs, r) exists d',\n          BUFCACHE.rep cs d' * (\n          [[ r = true /\\\n             (F * rep xp (Synced ((padded_log old) ++ new)) hm')%pred d' ]] \\/\n          [[ r = false /\\ length ((padded_log old) ++ new) > LogLen xp /\\\n             (F * rep xp (Synced old) hm')%pred d' ]])\n    XCRASH:hm_crash exists cs' d',\n          BUFCACHE.rep cs' d' * (\n          [[ (F * rep xp (Synced old) hm_crash)%pred d' ]] \\/\n          [[ (F * rep xp (Extended old new) hm_crash)%pred d' ]])\n    >} extend xp new cs.\n  Proof.\n    unfold extend.\n    step.\n    step.\n\n    (* true case *)\n    - (* write content *)\n      rewrite <- DescDefs.ipack_nopad_ipack_eq.\n      step.\n      unfold checksums_match in *; intuition.\n      solve_hash_list_rep.\n      step.\n      unfold checksums_match in *; intuition.\n      solve_hash_list_rep.\n\n      safestep.\n      rewrite Desc.avail_rep_split. cancel.\n      autorewrite with lists; apply helper_loglen_desc_valid_extend; auto.\n\n      safestep.\n      rewrite Data.avail_rep_split. cancel.\n      autorewrite with lists.\n      rewrite divup_1; rewrite <- entry_valid_ndata by auto.\n      apply helper_loglen_data_valid_extend; auto.\n\n      (* write header *)\n      safestep.\n      denote Hdr.rep as Hx; unfold Hdr.rep in Hx.\n      destruct_lift Hx.\n      unfold Hdr.hdr_goodSize in *; intuition.\n      eapply loglen_valid_goodSize_l; eauto.\n      eapply loglen_valid_goodSize_r; eauto.\n\n      (* sync content *)\n      step.\n      eauto 10.\n      prestep. norm. cancel. intuition simpl.\n      instantiate ( 1 := map ent_addr (padded_log new) ).\n      rewrite desc_padding_unsync_piff.\n      pred_apply; cancel.\n      rewrite map_length, padded_log_length; auto.\n      apply padded_desc_valid.\n      apply loglen_valid_desc_valid; auto.\n      eauto 10.\n\n      safestep.\n      autorewrite with lists.\n      rewrite entry_valid_ndata, Nat.mul_1_r; auto.\n      eauto 10.\n\n      (* sync header *)\n      safestep.\n      eauto 10.\n      step.\n\n      (* post condition *)\n      safestep.\n      or_l; cancel.\n      cancel_by extend_ok_helper; auto.\n      solve_checksums.\n\n      (* crash conditons *)\n      (* after sync data : Extended *)\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm. cancel. xform_normr. cancel.\n      or_r. cancel.\n      extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_r. cancel. extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_r. cancel. extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_r. cancel. extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_r. cancel. extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_r. cancel. extend_crash.\n      solve_checksums.\n      solve_checksums.\n\n\n      (* before writes *)\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_l; cancel. extend_crash.\n      solve_checksums.\n\n      cancel.\n      repeat xcrash_rewrite.\n      xform_norm; cancel. xform_normr; cancel.\n      or_l; cancel.\n      rewrite Desc.avail_rep_merge. cancel.\n      rewrite map_length.\n      apply helper_loglen_desc_valid_extend; auto.\n      solve_checksums.\n\n      xcrash.\n      or_l; cancel.\n      solve_checksums.\n\n      xcrash.\n      or_l; cancel.\n      solve_checksums.\n\n    (* false case *)\n    - safestep.\n      or_r; cancel.\n      apply loglen_invalid_overflow; auto.\n      solve_checksums.\n\n    (* crash for the false case *)\n    - xcrash.\n      or_l; cancel.\n      solve_checksums.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (avail _ _) _) => apply avail_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (trunc _ _) _) => apply trunc_ok : prog.\n  Hint Extern 1 ({{_}} Bind (extend _ _ _) _) => apply extend_ok : prog.\n\n  Theorem entry_valid_dec : forall ent,\n    {entry_valid ent} + {~ entry_valid ent}.\n  Proof.\n    unfold entry_valid, addr_valid, goodSize; intuition.\n    destruct (addr_eq_dec (fst ent) 0); destruct (lt_dec (fst ent) (pow2 addrlen)).\n    right; tauto.\n    right; tauto.\n    left; tauto.\n    right; tauto.\n  Defined.\n\n  Theorem rep_synced_length_ok : forall F xp l d hm,\n    (F * rep xp (Synced l) hm)%pred d -> length l <= LogLen xp.\n  Proof.\n    unfold rep, rep_inner, rep_contents, xparams_ok.\n    unfold Desc.array_rep, Desc.synced_array, Desc.rep_common, Desc.items_valid.\n    intros; destruct_lifts.\n    rewrite map_length, Nat.sub_0_r in H17.\n    rewrite H5, Nat.mul_comm; auto.\n  Qed.\n\n  Lemma xform_rep_synced : forall xp l hm,\n    crash_xform (rep xp (Synced l) hm) =p=> rep xp (Synced l) hm.\n  Proof.\n    unfold rep; simpl; unfold rep_contents; intros.\n    xform.\n    norm'l. unfold stars; cbn.\n    xform.\n    norm'l. unfold stars; cbn.\n    xform.\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Hdr.xform_rep_synced.\n    cancel.\n  Qed.\n\n  Lemma xform_rep_truncated : forall xp l hm,\n    crash_xform (rep xp (Truncated l) hm) =p=>\n      rep xp (Synced l) hm \\/ rep xp (Synced nil) hm.\n  Proof.\n    unfold rep; simpl; unfold rep_contents; intros.\n    xform; cancel.\n    xform; cancel.\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Hdr.xform_rep_unsync.\n    norm; auto.\n\n    or_r; cancel.\n    cancel_by helper_trunc_ok.\n    auto.\n    or_l; cancel.\n  Qed.\n\n  Lemma xform_rep_extendedcrashed : forall xp old new hm,\n    crash_xform (rep xp (ExtendedCrashed old new) hm) =p=> rep xp (ExtendedCrashed old new) hm.\n  Proof.\n    unfold rep; simpl; unfold rep_contents_unmatched; intros.\n    do 4 (xform;\n      norm'l; unfold stars; cbn).\n    xform.\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Hdr.xform_rep_synced.\n    cancel.\n    congruence.\n  Qed.\n\n  Theorem rep_extended_facts' : forall xp d old new hm,\n    (rep xp (Extended old new) hm)%pred d ->\n    Forall entry_valid new /\\\n    LogLen xp >= ndata_log old + ndata_log new /\\ LogDescLen xp >= ndesc_log old + ndesc_log new.\n  Proof.\n    unfold rep, rep_inner, rep_contents, xparams_ok.\n    unfold Desc.array_rep, Desc.synced_array, Desc.rep_common, Desc.items_valid.\n    intros; destruct_lifts.\n    intuition.\n    unfold loglen_valid in *; intuition.\n    unfold loglen_valid in *; intuition.\n  Qed.\n\n  Theorem rep_extended_facts : forall xp old new hm,\n    rep xp (Extended old new) hm =p=>\n    (rep xp (Extended old new) hm *\n      [[ LogLen xp >= ndata_log old + ndata_log new ]] *\n      [[ LogDescLen xp >= ndesc_log old + ndesc_log new ]] *\n      [[ Forall entry_valid new ]] )%pred.\n  Proof.\n    unfold pimpl; intros.\n    pose proof rep_extended_facts' H.\n    pred_apply; cancel.\n  Qed.\n\n  Lemma helper_sep_star_distr: forall AT AEQ V (a b c d : @pred AT AEQ V),\n    a * b * c * d =p=> (c * a) * (d * b).\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_add_sub_add : forall a b c,\n    b >= c + a -> a + (b - (c + a)) = b - c.\n  Proof.\n    intros; omega.\n  Qed.\n\n  Lemma xform_rep_extended_helper : forall xp old new,\n    xparams_ok xp\n    -> LogLen xp >= ndata_log old + ndata_log new\n    -> LogDescLen xp >= ndesc_log old + ndesc_log new\n    -> Forall addr_valid old\n    -> Forall entry_valid new\n    -> crash_xform (Data.avail_rep xp (ndata_log old) (LogLen xp - ndata_log old)) *\n        crash_xform (Desc.avail_rep xp (ndesc_log old) (LogDescLen xp - ndesc_log old)) *\n        crash_xform (Data.array_rep xp 0 (Data.Synced (vals_nonzero old))) *\n        crash_xform (Desc.array_rep xp 0 (Desc.Synced (map ent_addr old)))\n      =p=> exists synced_addr synced_valu ndesc,\n        rep_contents_unmatched xp old synced_addr synced_valu *\n        [[ length synced_addr = (ndesc * DescSig.items_per_val)%nat ]] *\n        [[ ndesc = ndesc_log new ]] *\n        [[ length synced_valu = ndata_log new ]].\n  Proof.\n    intros.\n    rewrite Data.avail_rep_split with (n1:=ndata_log new).\n    rewrite Desc.avail_rep_split with (n1:=ndesc_log new).\n    xform.\n    erewrite Data.xform_avail_rep_array_rep, Desc.xform_avail_rep_array_rep.\n    norml. unfold stars; simpl.\n    norm.\n    unfold stars; simpl.\n    cancel.\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    unfold rep_contents_unmatched.\n    rewrite vals_nonzero_padded_log, desc_padding_synced_piff.\n    cancel.\n    replace (ndesc_list _) with (ndesc_log new).\n    replace (length l) with (ndata_log new).\n    cancel.\n\n    replace DataSig.items_per_val with 1 in * by (cbv; auto); try omega.\n    unfold ndesc_list.\n    substl (length l0).\n    unfold ndesc_log.\n    rewrite divup_divup; auto.\n\n    replace DataSig.items_per_val with 1 in * by (cbv; auto); try omega.\n    intuition; auto.\n    all: unfold DescSig.RALen, DataSig.RALen, xparams_ok in *;\n          try omega; auto; intuition.\n\n    apply mult_le_compat_r; omega.\n\n    replace DataSig.items_per_val with 1 in * by (cbv; auto); try omega.\n  Qed.\n\n  Lemma sep_star_pimpl_trans : forall AT AEQ V (F p q r: @pred AT AEQ V),\n    p =p=> q ->\n    F * q =p=> r ->\n    F * p =p=> r.\n  Proof.\n    intros.\n    cancel; auto.\n  Qed.\n\n  Lemma xform_rep_extended' : forall xp old new hm,\n    crash_xform (rep xp (Extended old new) hm) =p=>\n       rep xp (Synced old) hm \\/\n       rep xp (ExtendedCrashed old new) hm.\n  Proof.\n    intros; rewrite rep_extended_facts.\n    unfold rep; simpl; unfold rep_contents; intros.\n    xform; cancel.\n    xform; cancel.\n    rewrite Hdr.xform_rep_unsync; cancel.\n\n    - or_r.\n      repeat rewrite sep_star_assoc.\n      eapply sep_star_pimpl_trans.\n      eapply pimpl_trans.\n      2: apply xform_rep_extended_helper; try eassumption.\n      cancel.\n      cancel.\n      subst; auto.\n\n    - or_l.\n      cancel.\n      rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n      rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n      cancel.\n  Qed.\n\n  Lemma rep_synced_app_pimpl : forall xp old new hm,\n    rep xp (Synced (padded_log old ++ new)) hm =p=>\n    rep xp (Synced (padded_log old ++ padded_log new)) hm.\n  Proof.\n    unfold rep; simpl; intros; unfold rep_contents; cancel.\n    repeat rewrite ndesc_log_padded_app.\n    repeat rewrite ndata_log_padded_app.\n    repeat rewrite ndesc_log_padded_log.\n    repeat rewrite ndata_log_padded_log.\n    repeat rewrite map_app.\n    repeat rewrite vals_nonzero_app.\n    repeat rewrite vals_nonzero_padded_log.\n    cancel.\n\n    rewrite Desc.array_rep_synced_app_rev.\n    setoid_rewrite <- desc_padding_synced_piff at 2.\n    eapply pimpl_trans2.\n    eapply Desc.array_rep_synced_app.\n    rewrite map_length, padded_log_length; unfold roundup; eauto.\n    cancel.\n    rewrite map_length, padded_log_length; unfold roundup; eauto.\n    apply Forall_append.\n    eapply forall_app_r; eauto.\n    apply addr_valid_padded; auto.\n    eapply forall_app_l; eauto.\n    solve_checksums.\n    rewrite <- rev_app_distr.\n    erewrite <- DescDefs.ipack_app.\n    rewrite <- map_app.\n    solve_hash_list_rep.\n    rewrite map_length, padded_log_length; unfold roundup; eauto.\n    rewrite <- rev_app_distr.\n    rewrite vals_nonzero_padded_log.\n    rewrite <- vals_nonzero_padded_log.\n    rewrite <- vals_nonzero_app.\n    solve_hash_list_rep.\n  Qed.\n\n  Lemma rep_extendedcrashed_pimpl : forall xp old new hm,\n    rep xp (ExtendedCrashed old new) hm\n    =p=> rep xp (Synced ((padded_log old) ++ new)) hm \\/\n          rep xp (Rollback old) hm.\n  Proof.\n    intros.\n    unfold rep at 1, rep_inner; simpl.\n    norm'l. unfold stars; simpl.\n    destruct (list_eq_dec (@weq valulen) (DescDefs.ipack (map ent_addr (padded_log new))) (DescDefs.ipack synced_addr)).\n    destruct (list_eq_dec (@weq valulen) (vals_nonzero new) synced_valu).\n\n    - eapply desc_ipack_injective in e.\n      unfold rep, rep_inner, rep_contents_unmatched, rep_contents.\n      or_l; cancel.\n      rewrite map_app.\n      rewrite vals_nonzero_app.\n      rewrite vals_nonzero_padded_log.\n      rewrite <- Data.array_rep_synced_app.\n      replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n      rewrite divup_1; simpl.\n      repeat rewrite vals_nonzero_addrs.\n      rewrite ndata_log_app, ndata_log_padded_log.\n      rewrite Nat.sub_add_distr.\n      cancel.\n\n      rewrite <- Desc.array_rep_synced_app.\n      simpl.\n      replace (divup _ _) with (ndesc_log old).\n      rewrite ndesc_log_app, ndesc_log_padded_log.\n      rewrite Nat.sub_add_distr.\n      replace (ndesc_list _) with (ndesc_log new).\n      cancel.\n      rewrite desc_padding_synced_piff.\n      cancel.\n\n      rewrite ndesc_log_ndesc_list; auto.\n      rewrite padded_log_length.\n      unfold roundup.\n      rewrite divup_divup; auto.\n      autorewrite with lists.\n      rewrite padded_log_length.\n      unfold roundup.\n      rewrite divup_divup; auto.\n      autorewrite with lists.\n      rewrite padded_log_length.\n      unfold roundup; eauto.\n      replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n      rewrite Nat.mul_1_r; eauto.\n      auto.\n      autorewrite with lists.\n      rewrite padded_log_length.\n      unfold roundup; eauto.\n      eauto.\n\n    - unfold rep, rep_inner.\n      or_r; cancel.\n      eauto.\n      right; auto.\n\n    - unfold rep, rep_inner.\n      or_r; cancel.\n      eauto.\n      left; eauto.\n  Qed.\n\n  Lemma xform_rep_extended : forall xp old new hm,\n    crash_xform (rep xp (Extended old new) hm) =p=>\n       rep xp (Synced old) hm \\/\n       rep xp (Synced (padded_log old ++ new)) hm \\/\n       rep xp (Rollback old) hm.\n  Proof.\n    intros.\n    rewrite xform_rep_extended'.\n    rewrite rep_extendedcrashed_pimpl.\n    auto.\n  Qed.\n\n  Lemma xform_rep_rollback : forall xp old hm,\n    crash_xform (rep xp (Rollback old) hm) =p=>\n      rep xp (Rollback old) hm.\n  Proof.\n    unfold rep; simpl; unfold rep_contents_unmatched; intros.\n    do 6 (xform; norm'l; unfold stars; simpl).\n    xform.\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    repeat rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Hdr.xform_rep_synced.\n    cancel.\n    all: eauto.\n  Qed.\n\n  Lemma recover_desc_avail_helper : forall T xp old (new : list T) ndata,\n    loglen_valid xp (ndesc_log old + ndesc_list new) ndata ->\n    (Desc.avail_rep xp (ndesc_log old) (ndesc_list new)\n     * Desc.avail_rep xp (ndesc_log old + ndesc_list new)\n         (LogDescLen xp - ndesc_log old - ndesc_list new))\n    =p=> Desc.avail_rep xp (ndesc_log old) (LogDescLen xp - ndesc_log old).\n  Proof.\n    intros.\n    rewrite Desc.avail_rep_merge;\n    eauto.\n    rewrite le_plus_minus_r;\n    auto.\n    unfold loglen_valid in *;\n    omega.\n  Qed.\n\n  Lemma recover_data_avail_helper : forall T xp old (new : list T) ndesc,\n    loglen_valid xp ndesc (ndata_log old + length new) ->\n    Data.avail_rep xp (ndata_log old)\n          (divup (length new) DataSig.items_per_val)\n    * Data.avail_rep xp (ndata_log old + length new)\n        (LogLen xp - ndata_log old - length new)\n    =p=> Data.avail_rep xp (nonzero_addrs (map fst old))\n           (LogLen xp - nonzero_addrs (map fst old)).\n  Proof.\n    intros.\n    replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n    rewrite divup_1, Data.avail_rep_merge;\n    eauto.\n    rewrite le_plus_minus_r;\n    auto.\n    unfold loglen_valid in *;\n    omega.\n  Qed.\n\n  Lemma xform_rep_rollbackunsync : forall xp l hm,\n    crash_xform (rep xp (RollbackUnsync l) hm) =p=>\n      rep xp (Rollback l) hm \\/\n      rep xp (Synced l) hm.\n  Proof.\n    unfold rep; simpl; unfold rep_contents_unmatched; intros.\n    do 7 (xform; norm'l; unfold stars; simpl).\n    rewrite Data.xform_avail_rep, Desc.xform_avail_rep.\n    repeat rewrite Data.xform_synced_rep, Desc.xform_synced_rep.\n    rewrite Hdr.xform_rep_unsync.\n    cancel.\n\n    unfold rep_contents.\n    or_r.\n    rewrite desc_padding_synced_piff, vals_nonzero_padded_log.\n    cancel.\n    rewrite Desc.array_rep_avail_synced, Data.array_rep_avail_synced.\n    rewrite <- recover_desc_avail_helper.\n    setoid_rewrite <- recover_data_avail_helper.\n    cancel.\n    denote (length _ = ndata_log _) as Hndata.\n    rewrite Hndata; eauto.\n    denote (length _ = _ * _) as Hndesc.\n    unfold ndesc_list.\n    rewrite Hndesc, divup_mul; eauto.\n\n    Unshelve.\n    all: eauto.\n  Qed.\n\n\n  Lemma xform_would_recover' : forall xp l hm,\n    crash_xform (would_recover' xp l hm) =p=>\n      rep xp (Synced l) hm \\/\n      rep xp (Rollback l) hm.\n  Proof.\n    unfold would_recover'.\n    intros.\n    xform.\n    cancel; (rewrite xform_rep_synced ||\n              rewrite xform_rep_rollback ||\n              rewrite xform_rep_rollbackunsync); cancel.\n  Qed.\n\n  Lemma weq2 : forall sz (x y : word sz) (a b : word sz),\n    {x = y /\\ a = b} + {(x = y /\\ a <> b) \\/\n                        (x <> y /\\ a = b) \\/\n                        (x <> y /\\ a <> b)}.\n  Proof.\n    intros.\n    destruct (weq x y); destruct (weq a b); intuition.\n  Defined.\n\n  Definition recover xp cs :=\n    let^ (cs, header) <- Hdr.read xp cs;\n    let '((prev_ndesc, prev_ndata),\n          (ndesc, ndata),\n          (addr_checksum, valu_checksum)) := header in\n    let^ (cs, wal) <- Desc.read_all xp ndesc cs;\n    let^ (cs, vl) <- Data.read_all xp ndata cs;\n    default_hash <- Hash default_valu;\n    h_addr <- hash_list default_hash (DescDefs.ipack wal);\n    h_valu <- hash_list default_hash vl;\n    If (weq2 addr_checksum h_addr valu_checksum h_valu) {\n      Ret cs\n    } else {\n      Debug \"hash mismatch\" 0;;\n      let^ (cs, wal) <- Desc.read_all xp prev_ndesc cs;\n      let^ (cs, vl) <- Data.read_all xp prev_ndata cs;\n      addr_checksum <- hash_list default_hash (DescDefs.ipack wal);\n      valu_checksum <- hash_list default_hash vl;\n      cs <- Hdr.write xp ((prev_ndesc, prev_ndata),\n                          (prev_ndesc, prev_ndata),\n                          (addr_checksum, valu_checksum)) cs;\n      cs <- Hdr.sync_now xp cs;\n      Ret cs\n    }.\n\n  Lemma recover_read_ok_helper : forall xp old new,\n     Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old ++ new))) =p=>\n      Desc.array_rep xp 0 (Desc.Synced (map ent_addr (padded_log old ++ padded_log new))).\n  Proof.\n    intros.\n    repeat rewrite map_app.\n    rewrite Desc.array_rep_synced_app_rev.\n    rewrite <- Desc.array_rep_synced_app.\n    cancel.\n    rewrite desc_padding_synced_piff.\n    cancel.\n    rewrite map_length, padded_log_length. unfold roundup; eauto.\n    rewrite map_length, padded_log_length. unfold roundup; eauto.\n  Qed.\n\n  Lemma recover_ok_addr_helper : forall xp old new,\n    Desc.array_rep xp 0\n        (Desc.Synced\n          (map ent_addr (padded_log old) ++ map ent_addr (padded_log new))) =p=>\n    Desc.array_rep xp 0\n      (Desc.Synced (map ent_addr (padded_log old ++ new))).\n  Proof.\n    intros.\n    rewrite map_app.\n    eapply pimpl_trans; [ | eapply Desc.array_rep_synced_app ].\n    rewrite Desc.array_rep_synced_app_rev.\n    cancel.\n    apply desc_padding_synced_piff.\n    rewrite map_length, padded_log_length; unfold roundup; eauto.\n    rewrite map_length, padded_log_length; unfold roundup; eauto.\n  Qed.\n\n  Definition recover_ok_Synced : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced l) hm)%pred d ]]\n    POST:hm' RET:cs'\n          BUFCACHE.rep cs' d *\n          [[ (F * rep xp (Synced l) hm')%pred d ]]\n    CRASH:hm_crash exists cs',\n          BUFCACHE.rep cs' d *\n          [[ (F * rep xp (Synced l) hm_crash)%pred d ]]\n    >} recover xp cs.\n  Proof.\n    unfold recover.\n    step.\n    prestep. norm. cancel. intuition simpl.\n    eassign (map ent_addr (padded_log l)).\n    rewrite map_length, padded_log_length.\n    all: auto.\n    rewrite desc_padding_synced_piff.\n    pred_apply; cancel.\n\n    safestep.\n    rewrite vals_nonzero_addrs.\n    replace DataSig.items_per_val with 1 by (cbv; auto).\n    unfold ndata_log; omega.\n    step.\n\n    intros.\n    eapply pimpl_ok2; monad_simpl.\n    eapply hash_list_ok. cancel.\n    solve_hash_list_rep; auto.\n    step.\n    solve_hash_list_rep; auto.\n\n    step.\n\n    {\n      step.\n      apply desc_padding_synced_piff.\n      solve_checksums.\n    }\n    {\n      eapply pimpl_ok2; monad_simpl; eauto with prog.\n      intros.\n      unfold pimpl; intros.\n      unfold checksums_match in *; intuition.\n      rewrite app_nil_r, <- desc_ipack_padded in *.\n      denote (_ m) as Hx; destruct_lift Hx; intuition.\n      all: denote (_ -> False) as Hx; contradict Hx;\n          eapply hash_list_injective2; solve_hash_list_rep.\n    }\n\n    all: try cancel;\n          solve [ apply desc_padding_synced_piff | solve_checksums ].\n\n    Unshelve. all: eauto; easy.\n  Qed.\n\n  Definition recover_ok_Rollback : forall xp cs,\n    {< F old d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * rep xp (Rollback old) hm)%pred d ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET:cs' exists d',\n          BUFCACHE.rep cs' d' *\n          [[ (F * rep xp (Synced old) hm')%pred d' ]]\n    XCRASH:hm_crash exists cs' d',\n          BUFCACHE.rep cs' d' * (\n          [[ (F * rep xp (Rollback old) hm_crash)%pred d' ]] \\/\n          [[ (F * rep xp (RollbackUnsync old) hm_crash)%pred d' ]])\n    >} recover xp cs.\n  Proof.\n    unfold recover.\n    prestep. norm. cancel.\n    denote (length _ = ndata_log _) as Hndata.\n    denote (length _ = _ * _) as Hndesc.\n    intuition simpl.\n    pred_apply; cancel.\n\n    safestep. subst.\n    instantiate (1:=(map ent_addr (padded_log old) ++ dummy)).\n    autorewrite with lists.\n    rewrite Nat.mul_add_distr_r.\n    rewrite padded_log_length.\n    all: auto.\n\n    unfold rep_contents_unmatched.\n    rewrite <- Desc.array_rep_synced_app.\n    repeat rewrite desc_padding_synced_piff.\n    autorewrite with lists.\n    rewrite <- ndesc_log_padded_log.\n    unfold ndesc_log; cancel.\n    autorewrite with lists.\n    rewrite padded_log_length; unfold roundup; eauto.\n\n    prestep. norm. cancel. intuition simpl.\n    eassign (vals_nonzero (padded_log old) ++ dummy0).\n    autorewrite with lists.\n    rewrite vals_nonzero_addrs, nonzero_addrs_padded_log, Nat.mul_add_distr_r.\n    unfold ndata_log.\n    replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n    repeat rewrite Nat.mul_1_r.\n    all: auto.\n\n    rewrite <- Data.array_rep_synced_app.\n    pred_apply.\n    replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n    rewrite vals_nonzero_addrs, nonzero_addrs_padded_log, divup_1.\n    cancel.\n    replace DataSig.items_per_val with 1 by (cbv; auto); try omega.\n    rewrite Nat.mul_1_r; eauto.\n\n    step.\n    intros.\n    eapply pimpl_ok2; monad_simpl.\n    eapply hash_list_ok.\n    cancel.\n    solve_hash_list_rep; auto.\n    intros.\n    eapply pimpl_ok2; monad_simpl.\n    eapply hash_list_ok.\n    cancel.\n    solve_hash_list_rep; auto.\n    step.\n\n    (* Impossible case case: the hash could not have matched what was on disk. *)\n    {\n      prestep. norm'l.\n      Transparent hide_or.\n      unfold hide_or in *.\n      intuition; exfalso;\n      denote (False) as Hcontra; apply Hcontra.\n\n      rewrite <- desc_ipack_padded.\n      eapply app_inv_head.\n      repeat erewrite <- DescDefs.ipack_app.\n      erewrite <- map_app.\n      eapply rev_injective.\n      rewrite app_nil_r in *.\n      unfold checksums_match in *; intuition.\n      eapply hash_list_injective; [ | solve_hash_list_rep ].\n      solve_hash_list_rep.\n      (* Not sure why hashmap_subset automation isn't kicking in here. *)\n      eapply hashmap_subset_trans; eauto.\n      eapply hashmap_subset_trans; eauto.\n      eapply hashmap_subset_trans; eauto.\n      eapply hashmap_subset_trans; eauto.\n\n      autorewrite with lists.\n      rewrite padded_log_length.\n      unfold roundup; eauto.\n      autorewrite with lists.\n      rewrite padded_log_length.\n      unfold roundup; eauto.\n\n      eapply app_inv_head.\n      erewrite <- vals_nonzero_app.\n      eapply rev_injective.\n      rewrite app_nil_r in *.\n      unfold checksums_match in *; intuition.\n      eapply hash_list_injective; [ | solve_hash_list_rep ].\n      solve_hash_list_rep.\n\n      Opaque hide_or.\n    }\n\n    (* False case: the hash did not match what was on disk and we need to recover. *)\n    {\n      denote (Data.avail_rep) as Hx; clear Hx.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      prestep. norm.\n      cancel.\n      match goal with\n      | [ Hor: (_ \\/ _ \\/ _) |- _ ] => clear Hor\n      end.\n      intuition simpl.\n      instantiate (1:= map ent_addr (padded_log old)).\n      rewrite map_length, padded_log_length.\n      all: auto.\n      pred_apply.\n      unfold rep_contents_unmatched.\n      cancel.\n\n      safestep.\n      rewrite vals_nonzero_padded_log, vals_nonzero_addrs.\n      unfold ndata_log.\n      replace DataSig.items_per_val with 1 by (cbv; auto); omega.\n\n      step.\n      solve_hash_list_rep; eauto.\n      eapply pimpl_ok2; monad_simpl; try apply hash_list_ok.\n      cancel.\n      solve_hash_list_rep; eauto.\n\n      step.\n      match goal with\n      | [ H: ( _ )%pred d |- _ ]\n        => unfold Hdr.rep in H; destruct_lift H\n      end.\n      unfold Hdr.hdr_goodSize in *; intuition.\n\n      denote (Data.avail_rep) as Hx; clear Hx.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      step.\n      eauto 10.\n      step.\n\n      (* post condition: Synced old *)\n      rewrite desc_padding_synced_piff, vals_nonzero_padded_log.\n      cancel.\n      rewrite Desc.array_rep_avail_synced, Data.array_rep_avail_synced.\n      rewrite <- recover_desc_avail_helper.\n      setoid_rewrite <- recover_data_avail_helper.\n      cancel.\n      rewrite Hndata; eauto.\n      unfold ndesc_list.\n      rewrite Hndesc, divup_mul; eauto.\n      match goal with\n      | [ H: context[rep_contents_unmatched] |- _ ]\n        => unfold rep_contents_unmatched in H; destruct_lift H\n      end;\n      auto.\n      rewrite vals_nonzero_padded_log in *.\n      solve_checksums.\n\n      (* Crash conditions. *)\n      (* After header write, before header sync: RollbackUnsync *)\n      xcrash.\n      or_r.\n      safecancel.\n      unfold rep_contents_unmatched.\n      rewrite desc_padding_synced_piff, vals_nonzero_padded_log.\n      cancel.\n      match goal with\n      | [ H: context[rep_contents_unmatched] |- _ ]\n        => unfold rep_contents_unmatched in H; destruct_lift H\n      end;\n      auto.\n      all: auto.\n      rewrite vals_nonzero_padded_log in *.\n      solve_checksums.\n      solve_checksums.\n\n      xcrash.\n      or_r.\n      safecancel.\n      unfold rep_contents_unmatched.\n      rewrite desc_padding_synced_piff, vals_nonzero_padded_log.\n      cancel.\n      match goal with\n      | [ H: context[rep_contents_unmatched] |- _ ]\n        => unfold rep_contents_unmatched in H; destruct_lift H\n      end;\n      auto.\n      all: auto.\n      rewrite vals_nonzero_padded_log in *.\n      solve_checksums.\n      solve_checksums.\n\n      (* Before header write: Rollback *)\n      norm'l.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      xcrash.\n      or_l.\n      cancel.\n      solve_checksums.\n\n      denote (Data.avail_rep) as Hx; clear Hx.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      xcrash.\n      or_l.\n      cancel.\n      solve_checksums.\n\n      norm'l.\n      denote (Data.avail_rep) as Hx; clear Hx.\n      xcrash.\n      or_l.\n      cancel.\n      solve_checksums.\n\n      norm'l.\n      xcrash.\n      or_l.\n      cancel.\n      solve_checksums.\n    }\n\n    (* Rest of the crash conditions. All before header write: Rollback. *)\n    all: norm'l.\n\n    denote (Data.avail_rep) as Hx; clear Hx.\n    denote (Data.avail_rep) as Hx; clear Hx.\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    denote (Data.avail_rep) as Hx; clear Hx.\n    denote (Data.avail_rep) as Hx; clear Hx.\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    denote (Data.avail_rep) as Hx; clear Hx.\n    denote (Data.avail_rep) as Hx; clear Hx.\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    denote (Data.avail_rep) as Hx; clear Hx.\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    xcrash.\n    or_l.\n    cancel.\n    solve_checksums.\n\n    Grab Existential Variables.\n    all: eauto; try econstructor.\n  Qed.\n\n\n  Definition recover_ok : forall xp cs,\n    {< F st l,\n    PRE:hm\n      exists d, BUFCACHE.rep cs d *\n          [[ (F * rep xp st hm)%pred d ]] *\n          [[ st = Synced l \\/ st = Rollback l ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET:cs' exists d',\n          BUFCACHE.rep cs' d' *\n          [[ (F * rep xp (Synced l) hm')%pred d' ]]\n    XCRASH:hm'\n          would_recover xp F l hm'\n    >} recover xp cs.\n  Proof.\n    unfold would_recover, would_recover'; intros.\n    eapply pimpl_ok2; monad_simpl; try eapply nop_ok.\n    intros. norm'l. unfold stars; cbn.\n    intuition; subst.\n\n    (* Synced *)\n    - cancel.\n      eapply pimpl_ok2; monad_simpl; try apply recover_ok_Synced.\n      cancel.\n      eassign l.\n      cancel.\n      hoare.\n      norm'l. xcrash.\n      xcrash.\n      xcrash.\n      or_l; cancel.\n\n    (* Rollback *)\n    - cancel.\n      eapply pimpl_ok2; monad_simpl; try apply recover_ok_Rollback.\n      intros; norm. cancel. intuition simpl. eauto. auto.\n      step.\n      cancel.\n      xcrash.\n      or_r; or_l; cancel.\n      or_r; or_r; cancel.\n      xcrash.\n      or_r; or_l; cancel.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (recover _ _) _) => apply recover_ok : prog.\n\n\n  (**\n   * It seems like [recover'] is the important thing here, and the [recover] below\n   * is actually not needed; higher layers already take care of first calling\n   * BUFCACHE.init_recover, then sb_load, and finally calling the log's [recover]\n   **)\n\n  (*\n  Definition recover cs lxp :=\n    cs <- BUFCACHE.init_recover 1;\n    let^ (cs, fsxp) <- sb_load cs;\n    cs <- recover' (FSXPLog fsxp) cs;\n    Ret ^(fsxp, cs).\n\n  Definition recover_ok :\n    {< fsxp old new,\n    PRE:hm\n      crash_xform (would_recover_either (FSXPLog fsxp) (sb_rep fsxp) old new hm)\n    POST:hm' RET:^(fsxp', cs') exists d',\n      [[ fsxp = fsxp' ]] *\n      BUFCACHE.rep cs' d' * (\n      [[ ((sb_rep fsxp) * rep (FSXPLog fsxp) (Synced old) hm')%pred d' ]] \\/\n      [[ ((sb_rep fsxp) * rep (FSXPLog fsxp) (Synced (padded_log old ++ new)) hm')%pred d' ]])\n    CRASH:hm_crash\n      would_recover_either (FSXPLog fsxp) (sb_rep fsxp) old new hm_crash\n    >} recover.\n  Proof.\n    unfold recover, would_recover_either.\n    intros.\n    eapply pimpl_ok2; eauto with prog.\n    intros. norm'l. unfold stars; cbn.\n\n    rewrite crash_xform_exists_comm.\n    norm'l. unfold stars; cbn.\n    rewrite crash_xform_exists_comm.\n    norm'l. unfold stars; cbn.\n    rewrite crash_xform_sep_star_dist.\n    rewrite crash_xform_lift_empty.\n    norm'l. unfold stars; cbn.\n    cancel. cancel. eauto.\n    eauto.\n\n    step.\n    autorewrite with crash_xform. cancel.\n\n    eapply pimpl_ok2; eauto with prog.\n    intros. norm'l. unfold stars; cbn.\n    cancel.\n    rewrite would_recover_either'_hashmap_subset; eauto.\n\n    step.\n    or_l. cancel.\n    autorewrite with crash_xform. eauto.\n\n    or_r. cancel.\n    autorewrite with crash_xform. eauto.\n\n    unfold would_recover_either.\n    norm'l; unfold stars; cbn.\n    cancel.\n    autorewrite with crash_xform; eauto.\n\n    autorewrite with crash_xform; eauto.\n    cancel.\n    rewrite xform_would_recover_either'.\n    rewrite would_recover_either'_hashmap_subset; eauto.\n\n    norm'l; unfold stars; cbn.\n    autorewrite with crash_xform.\n    rewrite <- H1.\n    norm'l. unfold stars; cbn.\n    norm'r.\n    cancel.\n    intuition.\n\n\n    assert (Hxform: crash_xform (sb_rep fsxp * would_recover_either' (FSXPLog fsxp) old new hm)%pred m').\n    unfold crash_xform.\n    exists x0; intuition.\n\n    pred_apply.\n    autorewrite with crash_xform.\n    rewrite xform_would_recover_either'.\n    rewrite would_recover_either'_hashmap_subset; eauto.\n  Qed.\n  *)\n\n\n  (**\n   * The below proofs are not actually necessary, though they are useful as a\n   * sanity check.  The [corr3] statements should probably show up in AsyncFS.v.\n   *)\n\n  (*\n  Definition extend_recover_ok : forall fsxp new cs,\n    {<< old d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ Forall entry_valid new ]] *\n          [[ (sb_rep fsxp * rep (FSXPLog fsxp) (Synced old) hm)%pred d ]]\n    POST:hm' RET: ^(cs', r) exists d',\n          BUFCACHE.rep cs' d' * (\n          [[ r = true /\\\n             (sb_rep fsxp * rep (FSXPLog fsxp) (Synced ((padded_log old) ++ new)) hm')%pred d' ]] \\/\n          [[ r = false /\\ length ((padded_log old) ++ new) > LogLen (FSXPLog fsxp) /\\\n             (sb_rep fsxp * rep (FSXPLog fsxp) (Synced old) hm')%pred d' ]])\n    REC:hm' RET:^(fsxp', cs') exists d',\n          [[ fsxp = fsxp' ]] *\n          BUFCACHE.rep cs' d' * (\n          [[ (sb_rep fsxp * rep (FSXPLog fsxp) (Synced old) hm')%pred d' ]] \\/\n          [[ (sb_rep fsxp * rep (FSXPLog fsxp) (Synced (padded_log old ++ new)) hm')%pred d' ]])\n    >>} extend (FSXPLog fsxp) new cs >> recover.\n  Proof.\n    unfold forall_helper; intros.\n    eexists.\n\n    Require Import Idempotent.\n    intros.\n    eapply pimpl_ok3.\n    eapply corr3_from_corr2; eauto with prog.\n    apply extend_ok.\n    apply recover_ok.\n\n    cancel.\n    cancel. eauto.\n\n    step.\n    cancel.\n    xform.\n    norm'l; unfold stars; cbn.\n    cancel.\n    cancel. eauto.\n\n    step.\n    all: rewrite H3; cancel.\n\n    or_l; cancel.\n    or_r; cancel.\n  Qed.\n  *)\n\nEnd PaddedLog.\n\n\nModule DLog.\n\n  Definition entry := (addr * valu)%type.\n  Definition contents := list entry.\n\n  Inductive state :=\n  (* The log is synced on disk *)\n  | Synced (navail : nat) (l: contents)\n  (* The log has been truncated; but the length (0) is unsynced *)\n  | Truncated  (old: contents)\n  (* The log is being extended; only the content has been updated (unsynced) *)\n  | ExtendedUnsync (old: contents)\n  (* The log has been extended; the new contents are synced but the length is unsynced *)\n  | Extended  (old: contents) (new: contents)\n  (* The log will roll back to these contents during recovery. *)\n  | Rollback (l: contents)\n  (* In the process of recovering. Recovery will definitely end with these\n  contents on disk. *)\n  | Recovering (l: contents).\n\n  Definition rep_common l padded : rawpred :=\n      ([[ l = PaddedLog.log_nonzero padded /\\\n         length padded = roundup (length padded) PaddedLog.DescSig.items_per_val ]])%pred.\n\n  Definition rep xp st hm :=\n    (match st with\n    | Synced navail l =>\n          exists padded, rep_common l padded *\n          [[ navail = (LogLen xp) - (length padded) ]] *\n          PaddedLog.rep xp (PaddedLog.Synced padded) hm\n    | Truncated l =>\n          exists padded, rep_common l padded *\n          PaddedLog.rep xp (PaddedLog.Truncated padded) hm\n    | ExtendedUnsync l =>\n          exists padded, rep_common l padded *\n          PaddedLog.rep xp (PaddedLog.Synced padded) hm\n    | Extended l new =>\n          exists padded, rep_common l padded *\n          PaddedLog.rep xp (PaddedLog.Extended padded new) hm\n    | Rollback l =>\n          exists padded, rep_common l padded *\n          PaddedLog.rep xp (PaddedLog.Rollback padded) hm\n    | Recovering l =>\n          exists padded, rep_common l padded *\n          PaddedLog.would_recover' xp padded hm\n    end)%pred.\n\n  Theorem sync_invariant_rep : forall xp st hm,\n    sync_invariant (rep xp st hm).\n  Proof.\n    unfold rep, rep_common; destruct st; intros; eauto.\n  Qed.\n\n  Hint Resolve sync_invariant_rep.\n  Local Hint Unfold rep rep_common : hoare_unfold.\n\n  Section UnifyProof.\n  Hint Extern 0 (okToUnify (PaddedLog.rep _ _) (PaddedLog.rep _ _)) => constructor : okToUnify.\n\n  Definition read xp cs :=\n    r <- PaddedLog.read xp cs;\n    Ret r.\n\n  Definition read_ok : forall xp cs,\n    {< F l d nr,\n    PRE:hm    BUFCACHE.rep cs d * \n              [[ (F * rep xp (Synced nr l) hm)%pred d ]]\n    POST:hm'   RET: ^(cs, r)\n              BUFCACHE.rep cs d *\n              [[ r = l /\\ (F * rep xp (Synced nr l) hm')%pred d ]]\n    CRASH:hm' exists cs',\n              BUFCACHE.rep cs' d *\n              [[ (F * rep xp (Synced nr l) hm')%pred d ]]\n    >} read xp cs.\n  Proof.\n    unfold read.\n    hoare.\n  Qed.\n\n  Definition init xp cs :=\n    cs <- PaddedLog.init xp cs;\n    Ret cs.\n\n  Definition trunc xp cs :=\n    cs <- PaddedLog.trunc xp cs;\n    Ret cs.\n\n  Definition trunc_ok : forall xp cs,\n    {< F l d nr,\n    PRE:hm    BUFCACHE.rep cs d *\n              [[ (F * rep xp (Synced nr l) hm)%pred d ]] * \n              [[  sync_invariant F ]]\n    POST:hm' RET: cs exists d',\n              BUFCACHE.rep cs d' *\n              [[ (F * rep xp (Synced (LogLen xp) nil) hm')%pred d' ]]\n    XCRASH:hm' exists cs d',\n              BUFCACHE.rep cs d' * (\n              [[ (F * rep xp (Synced nr l) hm')%pred d' ]] \\/\n              [[ (F * rep xp (Truncated l) hm')%pred d' ]])\n    >} trunc xp cs.\n  Proof.\n    unfold trunc.\n    safestep.\n    eassign F; cancel.\n    eauto.\n    step.\n    unfold roundup; rewrite divup_0; omega.\n\n    (* crashes *)\n    xcrash.\n    or_l; cancel.\n    or_r; cancel.\n  Qed.\n\n\n  Definition avail xp cs :=\n    r <- PaddedLog.avail xp cs;\n    Ret r.\n\n  Definition avail_ok : forall xp cs,\n    {< F l d nr,\n    PRE:hm BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced nr l) hm)%pred d ]]\n    POST:hm' RET: ^(cs, r)\n          BUFCACHE.rep cs d *\n          [[ (F * rep xp (Synced nr l) hm')%pred d ]] *\n          [[ r = nr ]]\n    CRASH:hm' exists cs',\n          BUFCACHE.rep cs' d *\n          [[ (F * rep xp (Synced nr l) hm')%pred d ]]\n    >} avail xp cs.\n  Proof.\n    unfold avail.\n    step.\n    step.\n    cancel.\n  Qed.\n\n  End UnifyProof.\n\n  Definition init_ok : forall xp cs,\n    {< F l d,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * arrayS (LogHeader xp) l)%pred d ]] *\n          [[ length l = (1 + LogDescLen xp + LogLen xp) /\\\n             LogDescriptor xp = LogHeader xp + 1 /\\\n             LogData xp = LogDescriptor xp + LogDescLen xp /\\\n             LogLen xp = (LogDescLen xp * PaddedLog.DescSig.items_per_val)%nat /\\\n             goodSize addrlen ((LogHeader xp) + length l) ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET: cs  exists d' nr,\n          BUFCACHE.rep cs d' *\n          [[ (F * rep xp (Synced nr nil) hm')%pred d' ]]\n    XCRASH:hm_crash any\n    >} init xp cs.\n  Proof.\n    unfold init, rep.\n    step.\n    unfold PaddedLog.xparams_ok, PaddedLog.DescSig.xparams_ok, PaddedLog.DataSig.xparams_ok; intuition.\n    substl (LogDescriptor xp); unfold PaddedLog.DescSig.RALen.\n    eapply goodSize_trans; [ | eauto ]; omega.\n    substl (LogData xp); substl (LogDescriptor xp); unfold PaddedLog.DataSig.RALen.\n    eapply goodSize_trans; [ | eauto ]; omega.\n    step.\n    rewrite roundup_0; auto.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (init _ _) _) => apply init_ok : prog.\n\n  Local Hint Resolve PaddedLog.DescDefs.items_per_val_gt_0.\n\n  Lemma extend_length_ok' : forall l new,\n    length l = roundup (length l) PaddedLog.DescSig.items_per_val ->\n    length (l ++ PaddedLog.padded_log new)\n      = roundup (length (l ++ PaddedLog.padded_log new)) PaddedLog.DescSig.items_per_val.\n  Proof.\n    intros.\n    repeat rewrite app_length.\n    repeat rewrite PaddedLog.padded_log_length.\n    rewrite H.\n    rewrite roundup_roundup_add, roundup_roundup; auto.\n  Qed.\n\n  Lemma extend_length_ok : forall l new,\n    length l = roundup (length l) PaddedLog.DescSig.items_per_val ->\n    length (PaddedLog.padded_log l ++ PaddedLog.padded_log new)\n      = roundup (length (PaddedLog.padded_log l ++ PaddedLog.padded_log new)) PaddedLog.DescSig.items_per_val.\n  Proof.\n    intros.\n    apply extend_length_ok'.\n    rewrite PaddedLog.padded_log_length.\n    rewrite roundup_roundup; auto.\n  Qed.\n\n  Lemma helper_extend_length_ok : forall xp padded new F d hm,\n    length padded = roundup (length padded) PaddedLog.DescSig.items_per_val\n    -> length (PaddedLog.padded_log padded ++ new) > LogLen xp\n    -> (F * PaddedLog.rep xp (PaddedLog.Synced padded) hm)%pred d\n    -> length new > LogLen xp - length padded.\n  Proof.\n    intros.\n    rewrite app_length in H0.\n    pose proof (PaddedLog.rep_synced_length_ok H1).\n    generalize H2.\n    rewrite H.\n    rewrite <- PaddedLog.padded_log_length.\n    intro; omega.\n  Qed.\n\n  Local Hint Resolve extend_length_ok helper_extend_length_ok PaddedLog.log_nonzero_padded_app.\n\n  Definition extend xp new cs :=\n    r <- PaddedLog.extend xp new cs;\n    Ret r.\n\n  Definition rounded n := roundup n PaddedLog.DescSig.items_per_val.\n\n  Definition entries_valid l := Forall PaddedLog.entry_valid l.\n\n  Lemma extend_navail_ok : forall xp padded new, \n    length padded = roundup (length padded) PaddedLog.DescSig.items_per_val ->\n    LogLen xp - length padded - rounded (length new)\n    = LogLen xp - length (PaddedLog.padded_log padded ++ PaddedLog.padded_log new).\n  Proof.\n    unfold rounded; intros.\n    rewrite extend_length_ok by auto.\n    rewrite app_length.\n    rewrite H.\n    repeat rewrite PaddedLog.padded_log_length.\n    rewrite roundup_roundup_add by auto.\n    rewrite roundup_roundup by auto.\n    omega.\n  Qed.\n\n  Local Hint Resolve extend_navail_ok PaddedLog.rep_synced_app_pimpl.\n\n\n  Definition extend_ok : forall xp new cs,\n    {< F old d nr,\n    PRE:hm    BUFCACHE.rep cs d *\n              [[ (F * rep xp (Synced nr old) hm)%pred d ]] *\n              [[ entries_valid new /\\ sync_invariant F ]]\n    POST:hm' RET: ^(cs, r) exists d',\n              BUFCACHE.rep cs d' * (\n              [[ r = true /\\\n                (F * rep xp (Synced (nr - (rounded (length new))) (old ++ new)) hm')%pred d' ]] \\/\n              [[ r = false /\\ length new > nr /\\\n                (F * rep xp (Synced nr old) hm')%pred d' ]])\n    XCRASH:hm' exists cs' d',\n              BUFCACHE.rep cs' d' * (\n              [[ (F * rep xp (Synced nr old) hm')%pred d' ]] \\/\n              [[ (F * rep xp (Extended old new) hm')%pred d' ]])\n    >} extend xp new cs.\n  Proof.\n    unfold extend.\n\n    prestep.\n    safecancel.\n    eassign F; cancel. auto.\n    step.\n\n    or_l. norm; [ cancel | intuition; pred_apply; norm ].\n    eassign (PaddedLog.padded_log dummy ++ PaddedLog.padded_log new).\n    cancel; auto.\n    intuition.\n\n    xcrash.\n    or_l; cancel.\n    or_r; cancel.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (avail _ _) _) => apply avail_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (trunc _ _) _) => apply trunc_ok : prog.\n  Hint Extern 1 ({{_}} Bind (extend _ _ _) _) => apply extend_ok : prog.\n\n  Definition recover xp cs :=\n    cs <- PaddedLog.recover xp cs;\n    Ret cs.\n\n  Definition recover_ok : forall xp cs,\n    {< F nr l,\n    PRE:hm\n      exists d, BUFCACHE.rep cs d * (\n          [[ (F * rep xp (Synced nr l) hm)%pred d ]] \\/\n          [[ (F * rep xp (Rollback l) hm)%pred d ]]) *\n          [[ sync_invariant F ]]\n    POST:hm' RET:cs' exists d',\n          BUFCACHE.rep cs' d' *\n          [[ (F * exists nr', rep xp (Synced nr' l) hm')%pred d' ]]\n    XCRASH:hm' exists cs' d',\n          BUFCACHE.rep cs' d' * (\n          [[ (F * rep xp (Recovering l) hm')%pred d' ]])\n    >} recover xp cs.\n  Proof.\n    unfold recover.\n    prestep. norm. cancel.\n    intuition simpl.\n    pred_apply.\n    eassign F; cancel.\n    eauto.\n\n    step.\n    norm'l.\n    unfold PaddedLog.would_recover in *.\n    xcrash.\n    xform.\n    cancel.\n\n    eassign (PaddedLog.Rollback dummy).\n    intuition simpl.\n    pred_apply; cancel.\n    auto.\n\n    step.\n    norm'l.\n    unfold PaddedLog.would_recover in *.\n    xcrash.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (recover _ _) _) => apply recover_ok : prog.\n\n  Lemma xform_rep_synced : forall xp na l hm,\n    crash_xform (rep xp (Synced na l) hm) =p=> rep xp (Synced na l) hm.\n  Proof.\n    unfold rep, rep_common; intros.\n    xform; cancel.\n    apply PaddedLog.xform_rep_synced.\n    all: auto.\n  Qed.\n\n  Lemma xform_rep_truncated : forall xp l hm,\n    crash_xform (rep xp (Truncated l) hm) =p=> exists na,\n      rep xp (Synced na l) hm \\/ rep xp (Synced (LogLen xp) nil) hm.\n  Proof.\n    unfold rep, rep_common; intros.\n    xform; cancel.\n    rewrite PaddedLog.xform_rep_truncated.\n    cancel.\n    or_r; cancel.\n    rewrite roundup_0; auto.\n  Qed.\n\n  Lemma xform_rep_extended_unsync : forall xp l hm,\n    crash_xform (rep xp (ExtendedUnsync l) hm) =p=> exists na, rep xp (Synced na l) hm.\n  Proof.\n    unfold rep, rep_common; intros.\n    xform; cancel.\n    apply PaddedLog.xform_rep_synced.\n    all: auto.\n  Qed.\n\n  Lemma xform_rep_extended : forall xp old new hm,\n    crash_xform (rep xp (Extended old new) hm) =p=>\n       (exists na, rep xp (Synced na old) hm) \\/\n       (exists na, rep xp (Synced na (old ++ new)) hm) \\/\n       (rep xp (Rollback old) hm).\n  Proof.\n    unfold rep, rep_common; intros.\n    xform.\n    rewrite PaddedLog.rep_extended_facts.\n    xform; cancel.\n    rewrite PaddedLog.xform_rep_extended.\n    cancel.\n    rewrite PaddedLog.rep_synced_app_pimpl.\n    or_r; or_l; cancel.\n  Qed.\n\n  Lemma xform_rep_rollback : forall xp l hm,\n    crash_xform (rep xp (Rollback l) hm) =p=>\n      rep xp (Rollback l) hm.\n  Proof.\n    unfold rep, rep_common; intros.\n    xform.\n    rewrite PaddedLog.xform_rep_rollback.\n    cancel.\n  Qed.\n\n  Lemma xform_rep_recovering : forall xp l hm,\n    crash_xform (rep xp (Recovering l) hm) =p=>\n      rep xp (Rollback l) hm \\/\n        exists na, rep xp (Synced na l) hm.\n  Proof.\n    unfold rep, rep_common; intros.\n    xform.\n    rewrite PaddedLog.xform_would_recover'.\n    cancel.\n  Qed.\n\n  Lemma rep_synced_pimpl : forall xp nr l hm,\n    rep xp (Synced nr l) hm =p=>\n    rep xp (Recovering l) hm.\n  Proof.\n    unfold rep, PaddedLog.would_recover'; intros.\n    cancel.\n    eassign padded; cancel.\n    or_l; cancel.\n  Qed.\n\n  Lemma rep_rollback_pimpl : forall xp l hm,\n    rep xp (Rollback l) hm =p=>\n      rep xp (Recovering l) hm.\n  Proof.\n    unfold rep, PaddedLog.would_recover'; intros.\n    cancel.\n    eassign padded; cancel.\n    or_r; or_l; cancel.\n  Qed.\n\n  Lemma rep_hashmap_subset : forall xp hm hm',\n    (exists l, hashmap_subset l hm hm')\n    -> forall st, rep xp st hm\n        =p=> rep xp st hm'.\n  Proof.\n    unfold rep; intros.\n    destruct st; cancel;\n    try erewrite PaddedLog.rep_hashmap_subset; eauto.\n    all: cancel; eauto.\n    rewrite PaddedLog.would_recover'_hashmap_subset; eauto.\n  Qed.\n\nEnd DLog.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/DiskLogHash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1884576217296456}}
{"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 Morphisms.\nRequire Import Basics.\nRequire Import BrandRelation.\nRequire Import Utils.\nRequire Import Types.\nRequire Import ForeignData.\nRequire Import DataModel.\nRequire Import ForeignDataTyping.\n\nSection TData.\n  (** Data is:\n     - unit - used for undefined results.\n     - nat - an integer\n     - float - a floating point number (IEEE 754 double precision)\n     - bool - true or false\n     - string - a character string\n     - coll - a bag\n     - rec - a record\n     - left - left sum value\n     - right - right sum value\n     - foreign - foreign data\n   *)\n\n  Context {fdata:foreign_data}.\n  Context {ftype:foreign_type}.\n  Context {fdtyping:foreign_data_typing}.\n  Context {m:brand_model}.\n\n  Definition Rrec (r1 r2:(string*data)) :=\n    ODT_lt_dec (fst r1) (fst r2).\n\n  Inductive data_type : data -> rtype -> Prop :=\n  | dttop d : data_normalized brand_relation_brands d -> data_type d Top\n  | dtunit : data_type dunit Unit\n  | dtnat n : data_type (dnat n) Nat\n  | dtfloat n : data_type (dfloat n) Float\n  | dtbool b : data_type (dbool b) Bool\n  | dtstring s : data_type (dstring s) String               \n  | dtcoll dl r : Forall (fun d => data_type d r) dl ->\n                  data_type (dcoll dl) (Coll r)\n  | dtrec k dl rl rl_sub pf\n          (pf':is_list_sorted ODT_lt_dec (domain rl) = true) :\n      sublist rl_sub rl ->\n      (k = Closed -> rl_sub = rl) ->\n      Forall2\n        (fun d r => (fst d) = (fst r) /\\ data_type (snd d) (snd r))\n        dl rl ->\n      data_type (drec dl) (Rec k rl_sub pf)\n  | dtleft {d \u03c4l} \u03c4r : data_type d \u03c4l -> data_type (dleft d) (Either \u03c4l \u03c4r)\n  | dtright {d} \u03c4l {\u03c4r} : data_type d \u03c4r -> data_type (dright d) (Either \u03c4l \u03c4r)\n  | dtbrand b b' d :\n      (* Ensure that only normalized brands are well typed *)\n      is_canon_brands brand_relation_brands b ->\n      data_normalized brand_relation_brands d ->\n      Forall (fun bb =>\n                forall \u03c4, \n                  lookup string_dec brand_context_types bb = Some \u03c4 ->\n                  data_type d \u03c4\n                ) b ->\n      b \u2264 b' ->\n      data_type (dbrand b d) (Brand b')\n  | dtforeign {fd f\u03c4} :\n      foreign_data_typing_has_type fd f\u03c4 ->\n      data_type (dforeign fd) (Foreign f\u03c4)\n  .\n  \n  Notation \"d \u25b9 r\" := (data_type d r) (at level 70). (* \\triangleright *)\n\n  Section opt.\n    (* synonym for option type *)\n\n    Lemma dtsome {d \u03c4} :\n      data_type d \u03c4 ->\n      data_type (dsome d) (Option \u03c4).\n    Proof.\n      intros; eapply dtleft; trivial.\n    Qed.\n\n    Lemma dtnone \u03c4 :\n      data_type dnone (Option \u03c4).\n    Proof.\n      intros; eapply dtright; econstructor.\n    Qed.\n\n    Lemma dtsome_inv {d \u03c4} :\n      data_type (dsome d) (Option \u03c4) ->\n      data_type d \u03c4.\n    Proof.\n      inversion 1; rtype_equalizer. subst.\n      trivial.\n    Qed.\n\n  End opt.\n  \n  Lemma dtrec_closed_inv {dl rl pf} :\n    data_type (drec dl) (Rec Closed rl pf) ->\n    Forall2\n      (fun d r => (fst d) = (fst r) /\\ data_type (snd d) (snd r))\n      dl rl.\n  Proof.\n    inversion 1; intuition; subst; rtype_equalizer; subst; trivial.\n  Qed.\n  \n  Lemma dtrec_full k {dl rl} pf:\n       Forall2\n         (fun d r => (fst d) = (fst r) /\\ data_type (snd d) (snd r))\n         dl rl ->\n       data_type (drec dl) (Rec k rl pf).\n  Proof.\n    intros. apply (dtrec _ _ rl rl); intuition.\n  Qed.\n\n  Lemma dtrec_open {dl : list (string*data)} {rl rl_sub : list (string*rtype)}\n        pf (pf':is_list_sorted ODT_lt_dec (domain rl) = true) :\n       sublist rl_sub rl ->\n       Forall2\n         (fun d r => (fst d) = (fst r) /\\ data_type (snd d) (snd r))\n         dl rl ->\n       data_type (drec dl) (Rec Open rl_sub pf).\n  Proof.\n    intros; apply (dtrec _ _  rl rl_sub); intuition; try discriminate.\n  Qed.\n\n  Lemma dtrec_open_pf {dl : list (string*data)} {rl rl_sub : list (string*rtype)}\n        (pf':is_list_sorted ODT_lt_dec (domain rl) = true) :\n    forall (sub:sublist rl_sub rl),\n       Forall2\n         (fun d r => (fst d) = (fst r) /\\ data_type (snd d) (snd r))\n         dl rl ->\n       data_type (drec dl) (Rec Open rl_sub (is_list_sorted_sublist pf' (sublist_domain sub))).\n  Proof.\n    intros; apply (dtrec _ _  rl rl_sub); intuition; try discriminate.\n  Qed.\n\n  Lemma dtrec_closed_is_open k dl rl pf :\n    data_type (drec dl) (Rec Closed rl pf) ->\n    data_type (drec dl) (Rec k rl pf).\n  Proof.\n    intros dt. apply dtrec_closed_inv in dt; apply dtrec_full; trivial.\n  Qed.\n\n  Lemma dtbrand_inv b b' d :\n    data_type (dbrand b d) (Brand b') ->\n      is_canon_brands brand_relation_brands b /\\\n      data_normalized brand_relation_brands d /\\\n      Forall (fun bb =>\n                forall \u03c4, \n                  lookup string_dec brand_context_types bb = Some \u03c4 ->\n                  data_type d \u03c4\n                ) b /\\\n      b \u2264 b'.\n  Proof.\n    inversion 1; subst.\n    apply canon_equiv in H2.\n    rewrite H2 in H6.\n    intuition.\n  Qed.\n\n  Lemma dtbrand_refl {b d}:\n    is_canon_brands brand_relation_brands b ->\n    data_normalized brand_relation_brands d ->\n    Forall (fun bb =>\n                forall \u03c4, \n                  lookup string_dec brand_context_types bb = Some \u03c4 ->\n                  data_type d \u03c4\n           ) b   ->\n    data_type (dbrand b d) (Brand b).\n  Proof.\n    intros; eapply dtbrand; try eassumption; intuition.\n  Qed.\n\n  Lemma  data_type_ext d \u03c4\u2080 pf1 pf2: \n    d \u25b9 (exist _ \u03c4\u2080 pf1) <-> d \u25b9 (exist _ \u03c4\u2080 pf2).\n  Proof.\n    rewrite (wf_rtype\u2080_ext pf1 pf2). intuition.\n  Qed.\n\n  Lemma  data_type_fequal d \u03c4\u2081 \u03c4\u2082: \n    (proj1_sig \u03c4\u2081) = (proj1_sig \u03c4\u2082) ->\n    (d \u25b9 \u03c4\u2081 <-> d \u25b9 \u03c4\u2082).\n  Proof.\n    destruct \u03c4\u2081; destruct \u03c4\u2082; simpl; intros; subst.\n    apply data_type_ext.\n  Qed.\n\n  Lemma data_type_not_bottom {d} : d \u25b9 \u22a5 -> False.\n  Proof.\n    induction d; inversion 1.\n  Qed.\n    \nSection inv.\n\n  Lemma data_type_dunit_inv {\u03c4}:\n    isTop \u03c4 = false ->\n    dunit \u25b9 \u03c4 -> \u03c4 = Unit.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros HH HH0; assert False; [inversion HH0|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dnat_inv {n \u03c4}:\n    isTop \u03c4 = false ->\n    dnat n \u25b9 \u03c4 -> \u03c4 = Nat.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dfloat_inv {n \u03c4}:\n    isTop \u03c4 = false ->\n    dfloat n \u25b9 \u03c4 -> \u03c4 = Float.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dbool_inv {b \u03c4}:\n    isTop \u03c4 = false ->\n    dbool b \u25b9 \u03c4 -> \u03c4 = Bool.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dstring_inv {s \u03c4}:\n    isTop \u03c4 = false ->\n    dstring s \u25b9 \u03c4 -> \u03c4 = String.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dcoll_inv {d \u03c4}:\n    isTop \u03c4 = false ->\n    dcoll d \u25b9 \u03c4 ->\n    {\u03c4' | \u03c4 = Coll \u03c4'}.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_drec_inv {sdl \u03c4}:\n    isTop \u03c4 = false ->\n    drec sdl \u25b9 \u03c4 ->\n    {k : record_kind & {\u03c4' | exists pf, \u03c4 = Rec k \u03c4' pf}}.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dleft_inv {d \u03c4} :\n    isTop \u03c4 = false ->\n    dleft d \u25b9 \u03c4 ->\n    {\u03c4l : rtype & {\u03c4r | \u03c4 = Either \u03c4l \u03c4r}}.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n    Lemma data_type_dright_inv {d \u03c4} :\n    isTop \u03c4 = false ->\n    dright d \u25b9 \u03c4 ->\n    {\u03c4l : rtype & {\u03c4r | \u03c4 = Either \u03c4l \u03c4r}}.\n  Proof.\n    induction \u03c4 using rtype_rect; \n    try solve [intros ? HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_dsome_inv {d \u03c4} :\n    isTop \u03c4 = false ->\n    dsome d \u25b9 \u03c4 ->\n    {\u03c4l : rtype & {\u03c4r | \u03c4 = Either \u03c4l \u03c4r}}.\n  Proof.\n    apply data_type_dleft_inv.\n  Qed.\n\n    Lemma data_type_dnone_inv {\u03c4} :\n    isTop \u03c4 = false ->\n    dnone \u25b9 \u03c4 ->\n    {\u03c4l : rtype & {\u03c4r | \u03c4 = Either \u03c4l \u03c4r}}.\n  Proof.\n    apply data_type_dright_inv.\n  Qed.\n\n  Lemma data_type_Unit_inv {d}:\n    d \u25b9 Unit ->\n    d = dunit.\n  Proof.\n    induction d;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_Nat_inv {d}:\n    d \u25b9 Nat ->\n    {n | d = dnat n}.\n  Proof.\n    induction d;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_Float_inv {d}:\n    d \u25b9 Float ->\n    {n | d = dfloat n}.\n  Proof.\n    induction d;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_Bool_inv {d}:\n    d \u25b9 Bool ->\n    {b | d = dbool b}.\n  Proof.\n    induction d;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_String_inv {d}:\n    d \u25b9 String ->\n    {s | d = dstring s}.\n  Proof.\n    induction d;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma data_type_Col_inv {d \u03c4}:\n    d \u25b9 Coll \u03c4 ->\n    {dl | d = dcoll dl}.\n  Proof.\n    revert \u03c4.\n    induction d; intros \u03c4;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n  Lemma Col_inv {d \u03c4}:\n    dcoll d \u25b9 Coll \u03c4 ->\n    Forall (fun c => c \u25b9 \u03c4) d.\n  Proof.\n    inversion 1; rtype_equalizer.\n    subst.\n    trivial.\n  Qed.\n\n  Lemma data_type_Rec_inv {d k \u03c4 pf} :\n    d \u25b9 Rec k \u03c4 pf ->\n    {dl | d = drec dl}.\n  Proof.\n    revert \u03c4 pf.\n    induction d; intros \u03c4 pf;\n    try solve [intros HH; assert False; [inversion HH|intuition]];\n    eauto; simpl; try discriminate.\n  Qed.\n\n    Lemma data_type_Arrow_inv {d \u03c4in \u03c4out}:\n    d \u25b9 Arrow \u03c4in \u03c4out ->\n    False.\n    Proof.\n      inversion 1.\n    Qed.\n\n    Lemma data_type_Foreign_inv {d ft}:\n    d \u25b9 Foreign ft ->\n    {fd | d = dforeign fd}.\n    Proof.\n      revert ft.\n      induction d; intros ft;\n        try solve [intros HH; assert False; [inversion HH|intuition]];\n        eauto; simpl; try discriminate.\n    Qed.\n\n  Lemma data_type_Either_inv {d \u03c4l \u03c4r}:\n    d \u25b9 Either \u03c4l \u03c4r ->\n    {dl | d = dleft dl /\\ dl \u25b9 \u03c4l} + {dr | d = dright dr /\\ dr \u25b9 \u03c4r}.\n  Proof.\n    revert \u03c4l \u03c4r.\n    induction d; intros \u03c4 pf;\n    try solve [intros HH; assert False; [inversion HH|intuition]].\n    - left. econstructor. inversion H; rtype_equalizer. subst; intuition.\n    - right. econstructor. inversion H; rtype_equalizer. subst; intuition.\n  Qed.\n\n    Lemma data_type_Option_inv {d \u03c4}:\n    d \u25b9 Option \u03c4 ->\n    {ds | d = dsome ds /\\ ds \u25b9 \u03c4} + {d = dnone}.\n    Proof.\n      intros inn. apply data_type_Either_inv in inn.\n      unfold dsome, dnone.\n      destruct inn as [[?[??]]|[?[??]]]; subst; eauto.\n      eapply data_type_Unit_inv in H0.\n      subst; eauto.\n    Qed.\n\n    Lemma data_type_Brand_inv {d br} :\n    d \u25b9 Brand br ->\n    {bs:brands & {d' | d = dbrand bs d'}}.\n  Proof.\n    revert br.\n    induction d; intros br;\n    try solve [intros H; assert False; [inversion H|intuition]];\n    eauto; simpl; try discriminate.\n    - intros. assert False; [inversion H0|intuition].\n    - intros. assert False; [inversion H0|intuition].\n  Qed.\n\nEnd inv.\n\n(** Inversion tactic for typed data *)\n    Ltac data_type_inverter :=\n  match goal with\n    | [H: dunit \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false |- _ ] => \n      match \u03c4 with\n        | Unit => fail 1\n        | _ => generalize (data_type_dunit_inv H1 H); intros ?; try subst\n      end\n    | [H: dnat _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | Nat => fail 1\n        | _ => generalize (data_type_dnat_inv H1 H); intros ?; try subst\n      end\n    | [H: dfloat _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | Float => fail 1\n        | _ => generalize (data_type_dfloat_inv H1 H); intros ?; try subst\n      end\n    | [H: dbool _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | Bool => fail 1\n        | _ => generalize (data_type_dbool_inv H1 H); intros ?; try subst\n      end\n    | [H: dstring _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | String => fail 1\n        | _ => generalize (data_type_dstring_inv H1 H); intros ?; try subst\n      end\n    | [H: dcoll _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | Coll _ => fail 1\n        | _ => destruct (data_type_dcoll_inv H1 H); try subst\n      end\n    | [H: drec _ \u25b9 ?\u03c4,  H1: isTop ?\u03c4 = false  |- _ ] => \n      match \u03c4 with\n        | Rec _ _ => fail 1\n        | _ => destruct (data_type_drec_inv H1 H) as [?[?[??]]]; try subst\n      end\n  end.\n\nLemma data_type_Rec_sublist {r k l l' pf} pf' :\n      drec r \u25b9 Rec k l pf ->\n      sublist l' l ->\n      drec r \u25b9 Rec Open l' pf'.\nProof.\n  inversion 1; subst; intros.\n  inversion H2; clear H2; simpl in *; rtype_equalizer; subst.\n  econstructor.\n  - eassumption.\n  - rewrite H0; eassumption.\n  - intros; discriminate.\n  - trivial.\nQed.\n\nLemma sorted_forall_same_domain {dl \u03c4}:\n    Forall2 (fun (d : string * data) (r : string * rtype) =>\n          fst d = fst r /\\ data_type (snd d) (snd r)) dl \u03c4 ->\n    (domain dl) = (domain \u03c4).\nProof.\n  intros.\n  assert (Forall2 (fun (d : string * data) (r : string * rtype) =>\n                     fst d = fst r) dl \u03c4)\n    by (eapply Forall2_incl; try apply H; intuition).\n  apply Forall2_map in H0.\n  apply Forall2_eq in H0.\n  assumption.\nQed. \n\nLemma data_type_Rec_domain {r k l pf} :\n      drec r \u25b9 Rec k l pf ->\n      sublist (domain l) (domain r).\nProof.\n  revert l pf. induction r; inversion 1; rtype_equalizer; subst;\n               inversion H5; subst; clear H5.\n  - apply sublist_nil_r in H3; subst; simpl; qauto.\n  - simpl. intuition.\n    rewrite H0.\n    apply sublist_domain in H3.\n    rewrite H3.\n    simpl.\n    apply sublist_cons.\n    apply (IHr _ (is_list_sorted_cons_inv _ pf')).\n    apply dtrec_full; trivial.\nQed.\n\nLemma data_type_Rec_closed_domain {r l pf} :\n      drec r \u25b9 Rec Closed l pf ->\n      domain r = domain l.\nProof.\n  intros.\n  symmetry.\n  apply sublist_length_eq.\n  - apply (data_type_Rec_domain H).\n  - apply dtrec_closed_inv in H.\n    repeat rewrite domain_length.\n    symmetry.\n    eapply Forall2_length; eauto.\nQed.\n\nLemma data_type_Recs_domain {r k l pf l' pf'} :\n  drec r \u25b9 Rec k l pf ->\n  drec r \u25b9 Rec Closed l' pf' ->\n  sublist (domain l) (domain l').\nProof.\n  intros t1 t2.\n  rewrite (data_type_Rec_domain t1).\n  rewrite (data_type_Rec_closed_domain t2).\n  reflexivity.\nQed.\n\nLemma data_type_Recs_closed_domain {r l l' pf pf'} :\n  drec r \u25b9 Rec Closed l pf ->\n  drec r \u25b9 Rec Closed l' pf' ->\n  domain l = domain l'.\nProof.\n  intros t1 t2.\n  rewrite <- (data_type_Rec_closed_domain t1).\n  rewrite <- (data_type_Rec_closed_domain t2).\n  trivial.\nQed.\n\nLemma dtrec_edot_parts a k \u03c4 pf s x y:\n  drec a \u25b9 Rec k \u03c4 pf ->\n  edot a s = Some x ->\n  edot \u03c4 s = Some y ->\n  x \u25b9 y.\nProof.\n  unfold edot.\n  intros dt ina in\u03c4.\n  invcs dt; rtype_equalizer.\n  subst.\n  apply is_list_sorted_NoDup_strlt in pf'.\n  apply (assoc_lookupr_nodup_sublist pf' H2 (R_dec:=ODT_eqdec)) in in\u03c4.\n  clear H3 H2.\n  induction H4; simpl in *; try discriminate.\n  destruct x0; destruct y0; destruct H; simpl in *; subst.\n  invcs pf'.\n  destruct (string_eqdec s s1); unfold Equivalence.equiv in *; subst.\n  - apply sorted_forall_same_domain in H4.\n    assert (nd2:~ In s1 (domain l)) by (rewrite H4; trivial).\n    apply (assoc_lookupr_nin_none) with (dec:=string_eqdec) in H2.\n    rewrite H2 in in\u03c4.\n    invcs in\u03c4.\n    apply (assoc_lookupr_nin_none) with (dec:=string_eqdec) in nd2.\n    unfold Equivalence.equiv, RelationClasses.complement, not in *.\n    simpl in *.\n    rewrite nd2 in ina.\n    invcs ina.\n    trivial.\n  - match_case_in in\u03c4\n    ; [intros ? eqq1 | intros eqq1]; rewrite eqq1 in in\u03c4\n    ; try discriminate.\n    invcs in\u03c4.\n    match_case_in ina\n    ; [intros ? eqq2 | intros eqq2]; rewrite eqq2 in ina\n    ; try discriminate.\n    invcs ina.\n    intuition.\nQed.\n\nLemma coll_type_cons a c x:\n  dcoll (a :: c) \u25b9 Coll x ->\n  a \u25b9 x /\\ dcoll c \u25b9 Coll x.\nProof.\n  intros.\n  inversion H.\n  assert (r = x) by (apply rtype_fequal; assumption).\n  rewrite Forall_forall in H2; simpl in H2.\n  rewrite H3 in *; clear H3 H1.\n  split.\n  apply (H2 a); left; reflexivity.\n  apply dtcoll; rewrite Forall_forall; intros.\n  apply (H2 x0); right; assumption.\nQed.\n\nLemma dcoll_coll_in_inv {d \u03c4 a} :\n  In a d -> dcoll d \u25b9 Coll \u03c4 -> a \u25b9 \u03c4.\nProof.\n  induction d; [simpl; intuition| ]; intros.\n  apply coll_type_cons in H0.\n  simpl in *; intuition; subst; intuition.\nQed.\n\nLemma rec_type_closed_cons {x y l l' pf} pf':\n  drec (x :: l) \u25b9 Rec Closed (y :: l') pf ->\n  (snd x) \u25b9 (snd y) /\\ drec l \u25b9 Rec Closed l' pf'.\nProof.\n  intros H.\n  apply dtrec_closed_inv in H.\n  inversion H; subst; intuition.\n  apply dtrec_full; auto.\nQed.\n\nLemma rec_type_cons {k x y l l' pf} pf':\n  drec (x :: l) \u25b9 Rec k (y :: l') pf ->\n  ((fst x) = (fst y) /\\ (snd x) \u25b9 (snd y) /\\ drec l \u25b9 Rec k l' pf')\n  \\/ ((fst x) <> (fst y) /\\ drec l \u25b9 Rec k (y::l') pf).\nProof.\n  intros H.\n  inversion H; clear H; subst.\n  inversion H5; clear H5; subst.\n  destruct rl_sub; simpl in *; try discriminate.\n  inversion H2; clear H2.\n  rtype_equalizer; subst.\n  intuition.\n  destruct p; destruct x; destruct y; destruct y0; simpl in *; subst.\n  inversion H3; subst.\n  - left; intuition.\n    econstructor; try apply H7; trivial.\n    eapply is_list_sorted_cons_inv; eassumption.\n    intros kc; specialize (H4 kc); inversion H4.\n    trivial.\n  - assert (neq:s2 = s1 -> False).\n    + intro; subst.\n       generalize pf'0.\n       generalize (sublist_In H1 (s1, r0)); clear; simpl; intuition.\n       apply (@is_list_sorted_cons string) in pf'0.\n       apply (@is_list_sorted_cons string) in pf'0.\n       apply is_list_sorted_NoDup in pf'0\n       ; [ | eapply StringOrder.lt_strorder].\n       inversion pf'0; subst.\n       apply in_dom in H.\n       tauto.\n    + right; split; trivial.\n       econstructor; try apply H1; auto.\n       apply (is_list_sorted_cons_inv _ pf'0).\n       intros kc; specialize (H4 kc).\n       inversion H4; subst.\n       elim neq; trivial.\nQed.\n  \n  Lemma sorted_forall_sorted (dl:list (string*data)) (\u03c4:list (string*rtype)):\n    is_list_sorted ODT_lt_dec (domain \u03c4) = true ->\n    Forall2 (fun (d : string * data) (r : string * rtype) =>\n          fst d = fst r /\\ data_type (snd d) (snd r)) dl \u03c4 ->\n    is_list_sorted ODT_lt_dec (domain dl) = true.\n  Proof.\n    intros.\n    assert (domain dl = domain \u03c4).\n    apply sorted_forall_same_domain; assumption.\n    rewrite H1; assumption.\n  Qed.\n\n  Lemma insert_and_foralls_mean_same_sort l1 l2 \u03c4\u2081 \u03c4\u2082 x y:\n    is_list_sorted ODT_lt_dec (domain (rec_sort (\u03c4\u2081 ++ \u03c4\u2082))) = true ->\n    Forall2\n      (fun (d : string * data) (r : string * rtype) =>\n         fst d = fst r /\\ data_type (snd d) (snd r))\n      (rec_sort (l1 ++ l2)) (rec_sort (\u03c4\u2081 ++ \u03c4\u2082)) ->\n    (fst x = fst y) ->\n    is_list_sorted\n      ODT_lt_dec\n      (domain\n         (insertion_sort_insert rec_field_lt_dec y (rec_sort (\u03c4\u2081 ++ \u03c4\u2082)))) = true ->\n    is_list_sorted\n      ODT_lt_dec\n      (domain\n         (insertion_sort_insert rec_field_lt_dec x (rec_sort (l1 ++ l2)))) = true.\n  Proof.\n    intros.\n    assert (domain (rec_sort (l1 ++ l2)) = domain (rec_sort (\u03c4\u2081 ++ \u03c4\u2082))).\n    apply sorted_forall_same_domain; assumption.\n    assert (domain (insertion_sort_insert rec_field_lt_dec x (rec_sort (l1 ++ l2))) =\n            domain (insertion_sort_insert rec_field_lt_dec y (rec_sort (\u03c4\u2081 ++ \u03c4\u2082)))).\n    generalize (same_domain_insert (rec_sort (l1++l2)) (rec_sort (\u03c4\u2081++\u03c4\u2082)) x y); intros.\n    simpl.\n    unfold rec_cons_sort in *. rewrite H4; try assumption; try reflexivity.\n    rewrite H4; assumption.\n  Qed.\n\n  Lemma sorted_cons_skip {A} (l:list (string*A)) (x x0:string*A) :\n    is_list_sorted\n      ODT_lt_dec\n      (domain (rec_cons_sort x (x0 :: l))) = true\n    -> is_list_sorted\n         ODT_lt_dec\n         (domain (rec_cons_sort x l)) = true.\n  Proof.\n    intros; simpl in *.\n    revert H; elim (rec_field_lt_dec x x0); intros.\n    assert (is_list_sorted ODT_lt_dec (domain (x :: l)) = true).\n    apply (@rec_sorted_skip_second string ODT_string _ l x x0); assumption.\n    assert ((rec_cons_sort x l) = x::l).\n    apply rec_cons_sorted_id; assumption.\n    rewrite H1; assumption.\n    revert H; elim (rec_field_lt_dec x0 x); intros.\n    apply (@rec_sorted_skip_first string ODT_string _ (rec_cons_sort x l) x0); assumption.\n    assert (fst x = fst x0).\n    apply lt_contr1; assumption.\n    simpl in H.\n    rewrite <- H0 in H.\n    assert ((rec_cons_sort x l) = x::l).\n    apply rec_cons_sorted_id; assumption.\n    rewrite H1; assumption.\n  Qed.\n\n  Lemma Forall2_cons_sorted l1 l2 x y :\n    Forall2\n      (fun (d : string * data) (r : string * rtype) =>\n         fst d = fst r /\\ data_type (snd d) (snd r))\n      l1 l2 ->\n    is_list_sorted ODT_lt_dec\n                   (domain\n                      (insertion_sort_insert rec_field_lt_dec x l1)) =\n    true ->\n    is_list_sorted ODT_lt_dec\n                   (domain\n                      (insertion_sort_insert rec_field_lt_dec y l2)) =\n    true -> fst x = fst y -> data_type (snd x) (snd y) ->\n    Forall2\n      (fun (d : string * data) (r : string * rtype) =>\n         fst d = fst r /\\ data_type (snd d) (snd r))\n      (insertion_sort_insert rec_field_lt_dec x l1)\n      (insertion_sort_insert rec_field_lt_dec y l2).\n  Proof.\n    intros.\n    induction H.\n    - apply Forall2_cons.\n      split; assumption; apply Forall2_nil.\n      apply Forall2_nil.\n    - assert (is_list_sorted\n                ODT_lt_dec\n                (domain (insertion_sort_insert rec_field_lt_dec x l)) = true)\n       by (apply (sorted_cons_skip l x x0); assumption).\n      assert (is_list_sorted\n                ODT_lt_dec\n                (domain (insertion_sort_insert rec_field_lt_dec y l')) = true)\n        by (apply (sorted_cons_skip l' y y0); assumption).\n      specialize (IHForall2 H5 H6).\n      simpl in *.\n      revert H0 H1.\n      elim (rec_field_lt_dec x x0); elim (rec_field_lt_dec y y0); intros.\n      + apply Forall2_cons. split; assumption.\n        apply Forall2_cons; assumption.\n      + revert H1.\n        elim (rec_field_lt_dec y0 y); intros.\n        apply Forall2_cons.\n        elim H; intros; clear H.\n        congruence.\n        elim H; intros; clear H.\n        congruence.\n        assert ((fst y) = (fst y0)).\n        apply lt_contr1; assumption.\n        assert ((fst x) = (fst x0)).\n        elim H; intros; clear H.\n        rewrite <- H7 in H8.\n        rewrite <- H2 in H8.\n        rewrite H8; reflexivity.\n        congruence.\n      + revert H0.\n        elim (rec_field_lt_dec x0 x); intros.\n        apply Forall2_cons.\n        elim H; intros; clear H.\n        congruence.\n        elim H; intros; clear H.\n        congruence.\n        assert ((fst x) = (fst x0)).\n        apply lt_contr1; assumption.\n        assert ((fst y) = (fst y0)).\n        elim H; intros; clear H.\n        rewrite <- H8.\n        rewrite <- H2.\n        assumption.\n        congruence.\n      + revert H0 H1.\n        elim (rec_field_lt_dec x0 x); elim (rec_field_lt_dec y0 y); intros.\n        apply Forall2_cons; assumption.\n        assert ((fst y) = (fst y0)).\n        apply lt_contr1; assumption.\n        assert ((fst x) = (fst x0)).\n        elim H; intros; clear H.\n        rewrite <- H7 in H8.\n        rewrite <- H2 in H8.\n        rewrite H8; reflexivity.\n        congruence.\n        assert ((fst x) = (fst x0)).\n        apply lt_contr1; assumption.\n        assert ((fst y) = (fst y0)).\n        elim H; intros; clear H.\n        rewrite <- H8.\n        rewrite <- H2.\n        assumption.\n        congruence.\n        apply Forall2_cons; assumption.\n  Qed.\n\n  Lemma dtrec_rec_concat_sort {x xt pfx y yt pfy} pxyt :\n    drec x \u25b9 Rec Closed xt pfx ->\n    drec y \u25b9 Rec Closed yt pfy ->\n    drec (rec_concat_sort x y) \u25b9 Rec Closed (rec_concat_sort xt yt) pxyt.\n  Proof.\n    intros typ1 typ2.\n    apply dtrec_closed_inv in typ1.\n    apply dtrec_closed_inv in typ2.\n    apply dtrec_full.\n    unfold rec_concat_sort.\n    apply rec_sort_Forall2.\n    - repeat rewrite domain_app.\n      rewrite (sorted_forall_same_domain typ1).\n      rewrite (sorted_forall_same_domain typ2).\n      trivial.\n    - apply Forall2_app; trivial.\n  Qed.\n  \n  Lemma dttop' d : data_normalized brand_relation_brands d -> d \u25b9 \u22a4.\n  Proof.\n    apply dttop.\n  Qed.\n  \n  Hint Resolve dttop dttop' : qcert.\n\n  Lemma Forall_map {A B} P (f:A->B) l :\n    Forall P (map f l) <-> Forall (fun x => P (f x)) l.\n  Proof.\n    induction l; simpl; intuition.\n    - inversion H1; subst; auto.\n    - inversion H1; subst; auto.\n  Qed.\n\n  (** Well typed data must be normalized *)\n  Lemma data_type_normalized d \u03c4 :\n    d \u25b9 \u03c4 -> data_normalized brand_relation_brands d.\n  Proof.\n    Hint Constructors data_normalized : qcert.\n    revert \u03c4.\n    induction d using dataInd2; intros; try assumption; simpl in *;\n    auto 2 with qcert.\n    - constructor. inversion H0; subst.\n      + inversion H1; trivial.\n      + revert H2; apply Forall_impl_in.\n        eauto.\n    - inversion H0; subst; trivial.\n      constructor; trivial.\n      + apply Forall_forall. intros.\n        destruct x; simpl.\n        specialize (H _ _ H1).\n        revert H H1 H4. clear.\n        revert rl.\n        induction r; inversion 3; subst; simpl in *;\n        intuition; subst; simpl in *; subst; eauto.\n      + apply sorted_forall_same_domain in H4.\n        rewrite H4.\n        trivial.\n    - inversion H; subst; trivial; qeauto.\n    - inversion H; subst; trivial; qeauto.\n    - inversion H; subst; trivial; constructor; qeauto.\n    - invcs H.\n      + eauto.\n      + constructor.\n        eapply foreign_data_typing_normalized; qeauto.\n  Qed.\n\n  (** Lemma showing that normalization preserves typing *)\n  Lemma normalize_preserves_type d \u03c4 :\n    d \u25b9 \u03c4 -> normalize_data brand_relation_brands d \u25b9 \u03c4.\n  Proof.\n    intros.\n    rewrite normalize_normalized_eq; trivial.\n    eapply data_type_normalized; eauto.\n  Qed.\n  \n  Lemma dttop_weaken {d \u03c4} : data_type d \u03c4 -> data_type d \u22a4.\n  Proof.\n    intros H; apply data_type_normalized in H.\n    auto 2 with qcert.\n  Qed.\n\nEnd TData.\n\n(* expands well-typed data with a specific type *)\nNotation \"d \u25b9 r\" := (data_type d r) (at level 70). (* \\vdash, \\triangleright *)\n\nLtac dtype_inverter\n  := repeat progress\n            match goal with\n            | [H:?d \u25b9 Unit |- _ ] =>\n              apply data_type_Unit_inv in H; try subst d\n            | [H:?d \u25b9 Nat |- _ ] =>\n              apply data_type_Nat_inv in H; destruct H; try subst d\n            | [H:?d \u25b9 Float |- _ ] =>\n              apply data_type_Float_inv in H; destruct H; try subst d\n            | [H:?d \u25b9 Bool |- _ ] =>\n              apply data_type_Bool_inv in H;  destruct H; try subst d\n            | [H:?d \u25b9 String |- _ ] =>\n              apply data_type_String_inv in H;  destruct H; try subst d\n            | [H:?d \u25b9 (Coll ?\u03c4) |- _ ] =>\n              match d with\n              | dcoll ?d => fail 1\n              | _ =>\n                let XX := fresh in \n                destruct (data_type_Col_inv H) as [XX ?];\n                  (discriminate || (subst d; rename XX into d))\n              end\n            | [H:?d \u25b9 Arrow _ _ |- _ ] =>\n              apply data_type_Arrow_inv in H; tauto\n            | [H:?d \u25b9 (Foreign ?\u03c4) |- _ ] =>\n              match d with\n              | dforeign _ => fail 1\n              | _ =>\n                let XX := fresh in \n                destruct (data_type_Foreign_inv H) as [XX ?];\n                  (discriminate || (subst d; rename XX into d))\n              end\n            | [H:?d \u25b9 (Brand _) |- _ ] =>\n              match d with\n              | dbrand _ _ => fail 1\n              | _ =>\n                let XX := fresh in \n                destruct (data_type_Brand_inv H) as [? [XX ?]];\n                  (discriminate || (subst d; rename XX into d))\n              end\n            | [H:?d \u25b9 (Rec ?k ?\u03c4 ?pf) |- _ ] =>\n              match d with\n              | drec _ => fail 1\n              | _ =>\n                let XX := fresh in \n                destruct (data_type_Rec_inv H) as [XX ?];\n                  (discriminate || (subst d; rename XX into d))\n              end\n            |   [H:?d \u25b9 Bool |- _ ] =>\n                let XX := fresh in \n                destruct (data_type_Bool_inv H) as [XX ?]; try subst d; clear H;\n                rename XX into d\n            | [H:proj1_sig _ =\n                 Rec\u2080 Closed\n                   (map\n                      (fun x : string * {\u03c4\u2080 : rtype\u2080 | wf_rtype\u2080 \u03c4\u2080 = true} =>\n                         (fst x, proj1_sig (snd x))) _) |- _ ] \n              => apply Rec\u2080_eq_proj1_Rec in H; destruct H as [??]\n            end; simpl.\n\n  Ltac dtype_inverter_with_either \n    := repeat progress\n              try dtype_inverter; \n      try match goal with\n            | [H:?d \u25b9 (Either _ _) |- _ ] =>\n              match d with\n                | dleft ?d => fail 1\n                | dright ?d => fail 1\n                | _ =>\n                let XX := fresh in \n                destruct (data_type_Either_inv H) as [[XX [??]]|[XX [??]]];\n                  (discriminate || (subst d; rename XX into d))\n              end\n          end.\n\n(* adds type information about the data when it can be inferred *)\nLtac dtype_enrich :=\n  match goal with\n    | [H: In ?a ?l, H2: (dcoll ?l) \u25b9 (Coll ?\u03c4) |- _ ] =>\n      extend (dcoll_coll_in_inv H H2)\n  end.\n\nGlobal Hint Immediate dttop dttop' : qcert.\nGlobal Hint Resolve dttop_weaken : qcert.\n\nSection subtype.\n\n  Lemma subtype_Rec_sublist_strengthen\n        {fdata:foreign_data}\n        {ftype:foreign_type}\n        {fdtyping:foreign_data_typing}\n        {m:brand_model} {dl rl srl k1 pf srl0 pf0 k2} :\n  forall (f2:Forall2\n         (fun (d : string * data) (r : string * rtype) =>\n            fst d = fst r /\\ data_type (snd d) (snd r)) dl rl)\n         (subl:sublist srl rl)\n         (subt:Rec k1 srl pf <: Rec k2 srl0 pf0)\n         (pf3:is_list_sorted ODT_lt_dec (domain rl) = true)\n         (ft:Forallt\n        (fun ab : string * rtype =>\n         forall (d : data) (\u03c4\u2082 : rtype),\n         snd ab <: \u03c4\u2082 -> data_type d (snd ab) -> data_type d \u03c4\u2082) srl),\n  exists l2,\n    Forall2\n         (fun (d : string * data) (r : string * rtype) =>\n            fst d = fst r /\\ data_type (snd d) (snd r)) dl l2\n    /\\\n    sublist srl0 l2.\nProof.\n  revert dl srl k1 pf srl0 pf0 k2.\n  induction rl; intros dl srl k1 pf srl0 pf0 k2 f2 subl subt pf3; inversion f2; clear f2; subst; intros.\n  -  apply sublist_nil_r in subl; subst. exists nil.\n     apply subtype_Rec_sublist in subt.\n     apply sublist_nil_r in subt.\n     unfold domain in subt; apply map_eq_nil in subt. subst.\n     intuition.\n  - destruct x; destruct a. unfold fst, snd in H2; destruct H2; subst.\n    destruct (sublist_cons_inv subl pf3).\n    + destruct H as [?[??]]. subst.\n      inversion ft; subst; clear ft.\n       case_eq (lookup string_dec srl0 s0); intros.\n      * (* clear subl. revert x H1 pf subt. *)\n         destruct srl0; intros; simpl in H; try discriminate.\n         destruct p. destruct (string_dec s0 s).\n          inversion H; clear H; subst.\n          destruct (Rec_subtype_cons_inv subt) as [? [??]].\n          specialize (IHrl _ _ k1 _ _ _ _ H3 H1 H (\n                             is_list_sorted_cons_inv ODT_lt_dec pf3) H5).\n          destruct (IHrl) as [? [??]].\n          exists ((s,r0)::x2); intuition;[ | apply sublist_cons; auto].\n          constructor; intuition.\n          simpl.\n          inversion subt; rtype_equalizer; subst; trivial.\n          destruct rl2; inversion H11; rtype_equalizer; clear H11.\n          destruct rl1; inversion H8; rtype_equalizer; clear H8.\n          destruct p; destruct p0; unfold fst in H11; subst.\n          simpl.\n          simpl in H0.\n          specialize (H10 s0 r1). simpl in H10.\n          destruct (string_dec s0 s0); [| congruence].\n          destruct H10 as [? [??]]; trivial.\n          invcs H7.\n          eauto.\n          \n          generalize (subtype_Rec_sublist subt); intros subl'.\n          repeat rewrite domain_cons in subl'; unfold fst in subl'.\n          inversion subl'; subst; [congruence | ].\n          apply lookup_in in H.\n          apply in_dom in H.\n          generalize (sublist_In H7 s0); simpl; intuition.\n          generalize (is_list_sorted_NoDup _ _ pf).\n          inversion 1; congruence.\n      * apply Rec_subtype_cons_inv1 in subt; trivial.\n          destruct subt as [pf' subt].\n          specialize (IHrl _ _ k1 pf' _ pf0 _ H3 H1 subt (\n                             is_list_sorted_cons_inv ODT_lt_dec pf3) H5).\n          destruct IHrl as [? [? ?]].\n          exists ((s0,r)::x0).\n          intuition.\n          apply sublist_skip; auto 1.\n    + simpl in H; destruct H.\n      specialize (IHrl _ _ k1 pf _ pf0 _ H3 H1 subt (\n                             is_list_sorted_cons_inv ODT_lt_dec pf3) ft).\n          destruct IHrl as [? [? ?]].\n          exists ((s0,r)::x).\n          intuition.\n          apply sublist_skip; auto 1.\nQed.\n\nGlobal Instance data_type_subtype_prop\n       {fdata:foreign_data}\n       {ftype:foreign_type}\n       {fdtyping:foreign_data_typing}\n       {m:brand_model} : Proper (eq ==> subtype ==> impl) (data_type).\n  Proof.\n    unfold Proper, respectful, impl, flip.\n    intros ? d ? \u03c4\u2081 \u03c4\u2082 sub ; subst.\n    Hint Resolve data_type_ext : qcert.\n    Hint Resolve data_type_not_bottom : qcert.\n    Hint Resolve dtrec_closed_is_open : qcert.\n    Hint Constructors data_normalized : qcert.\n    \n    revert d \u03c4\u2082 sub.\n      induction \u03c4\u2081 using rtype_rect;\n        induction \u03c4\u2082 using rtype_rect; simpl;\n        try autorewrite with rtype_join;\n        try solve[inversion 1; subst; intros; \n                  try solve [intros; dtype_inverter; eauto 2 with qcert\n                            | eelim data_type_not_bottom; qeauto\n                            | unfold Top, Bottom, Unit, Nat, Float, Bool, String, Coll, Rec in *;\n                              eauto 2 with qcert; try r_ext]].\n    - clear IH\u03c4\u2082. intros.\n      inversion H; rtype_equalizer.\n      subst.\n      inversion sub; rtype_equalizer.\n      + subst; trivial.\n      + subst. constructor.\n        revert H2; apply Forall_impl; auto. \n    - clear H0.\n      intros.\n      inversion H0; rtype_equalizer; subst. \n      destruct (subtype_Rec_sublist_strengthen H6 H3 sub) as [?[??]]; trivial.\n      eapply dtrec; try exact H1; trivial.\n      rewrite <- (sorted_forall_same_domain H1).\n      rewrite (sorted_forall_same_domain H6).\n      trivial.\n      intros; subst.\n      generalize (subtype_Rec_closed2_closed1 sub); intros; subst.\n      intuition; subst.\n      generalize (subtype_Rec_closed_domain sub); intros eqd.\n      rewrite <- (sorted_forall_same_domain H6) in eqd.\n      rewrite (sorted_forall_same_domain H1) in eqd.\n      apply sublist_length_eq; trivial.\n      rewrite <- (domain_length srl0), <- (domain_length x).\n      congruence.\n    - intros e sub. apply subtype_Either_inv in e.\n      destruct e as [e1 e2].\n      inversion sub; subst; rtype_equalizer.\n      + subst. econstructor; intuition.\n      + subst. econstructor; intuition.\n    - inversion 1; trivial; subst.\n      + apply canon_equiv in H1.\n        rewrite H1; trivial.\n      + apply canon_equiv in H; apply canon_equiv in H0.\n        rewrite H, H0 in H1.\n        inversion 1; subst.\n        apply canon_equiv in H3. rewrite H3 in H8.\n        econstructor; trivial.\n        etransitivity; eauto.\n    - intros sub dt.\n      invcs sub; trivial.\n      invcs dt.\n      constructor.\n      eapply foreign_data_typing_subtype; eauto.\n  Qed.\n\n  Global Instance data_type_subtype_prop'\n         {fdata:foreign_data}\n         {ftype:foreign_type}\n         {fdtyping:foreign_data_typing}\n         {m:brand_model} d : Proper (subtype ==> impl) (data_type d).\n  Proof.\n    apply data_type_subtype_prop; trivial.\n  Qed.\n\n  Lemma join_preserves_data_type\n        {fdata:foreign_data}\n        {ftype:foreign_type}\n        {fdtyping:foreign_data_typing}\n        {m:brand_model} {d \u03c4}:\n    d \u25b9 \u03c4 -> forall \u03c4\u2080, d \u25b9 (\u03c4 \u2294 \u03c4\u2080).\n  Proof.\n    intros.\n    rewrite (join_leq_l \u03c4 \u03c4\u2080) in H; trivial.\n  Qed.\n\n  (* Just so we can refer to it in the paper *)\n  Theorem subtyping_preserves_data_type\n          {fdata:foreign_data}\n          {ftype:foreign_type}\n          {fdtyping:foreign_data_typing}\n          {m:brand_model} {d \u03c4\u2081 \u03c4\u2082}:\n    d \u25b9 \u03c4\u2081 -> \u03c4\u2081 \u2264 \u03c4\u2082 -> d \u25b9 \u03c4\u2082.\n  Proof.\n    intros.\n    rewrite <- H0.\n    trivial.\n  Qed.\n\n  Lemma map_rtype_meet_cons2_nin\n        {ftype:foreign_type}\n        {br:brand_relation} s x l1 l2 :\n    ~ In s (domain l1) ->\n    map_rtype_meet l1 ((s, x) :: l2)\n    = map_rtype_meet l1 l2.\n  Proof.\n    induction l1; simpl; trivial.\n    destruct a; simpl.\n    intuition.\n    rewrite H.\n    destruct (string_dec s0 s); intuition.\n  Qed.\n\n  Lemma lookup_diff_cons2_nin {A B C} dec s x (l1:list (A*B)) (l2:list (A*C)) :\n    ~ In s (domain l1) ->\n  lookup_diff dec l1 ((s, x) :: l2)\n  = lookup_diff dec l1 l2.\n  Proof.\n    induction l1; simpl; trivial.\n    intuition.\n    rewrite H. destruct (dec (fst a) s); intuition.\n  Qed.\n\n  Lemma lookup_diff_sublist {A B C} (dec:forall a a':A, {a=a'} + {a<>a'})\n        (l1:list (A*B)) (l2:list (A*C)):\n    sublist (lookup_diff dec l1 l2) l1.\n  Proof.\n    induction l1; simpl; trivial.\n    - intuition.\n    - match_destr.\n      + apply sublist_skip; trivial.\n      + apply sublist_cons; trivial.\n  Qed.\n  \n  Theorem meet_preserves_data_type\n          {fdata:foreign_data}\n          {ftype:foreign_type}\n          {fdtyping:foreign_data_typing}\n          {m:brand_model} {d \u03c4\u2081 \u03c4\u2082}:\n    d \u25b9 \u03c4\u2081 -> d \u25b9 \u03c4\u2082 -> d \u25b9 (\u03c4\u2081 \u2293 \u03c4\u2082).\n  Proof.\n    Hint Resolve data_type_ext : qcert.\n    Hint Resolve data_type_not_bottom : qcert.\n    Hint Resolve dtrec_closed_is_open : qcert.\n    Hint Constructors data_normalized : qcert.\n    \n    revert d \u03c4\u2082.\n      induction \u03c4\u2081 using rtype_rect;\n        induction \u03c4\u2082 using rtype_rect; simpl;\n        try autorewrite with rtype_meet;\n        try solve[inversion 1; subst; intros; \n                  try solve [intros; dtype_inverter_with_either; try discriminate; eauto 2 with qcert\n                            | eelim data_type_not_bottom; qeauto\n                            | unfold Top, Bottom, Unit, Nat, Float, Bool, String, Coll, Rec in *;\n                              eauto 2 with qcert; try r_ext]].\n    - intros; dtype_inverter.\n      inversion H; clear H; subst.\n      inversion H0; clear H0; subst.\n      rtype_equalizer. subst.\n      constructor.\n      rewrite Forall_forall in *.\n      intros ? inn.\n      apply IH\u03c4\u2081; intuition.\n    - intros; dtype_inverter.\n      invcs H1; rtype_equalizer.\n      invcs H2; rtype_equalizer.\n      subst.\n      match_destr.\n      + { clear H0.\n          assert (F2:Forall2 (fun (d : string * data) (r : string * rtype) =>\n                             fst d = fst r /\\ snd d \u25b9 snd r) d\n                          (rec_concat_sort\n                             (map_rtype_meet srl srl0)\n                             (lookup_diff string_dec rl0 srl))).\n          {\n            clear H7 H10 r k k0.\n            revert rl rl0 srl srl0 pf pf' pf0 pf'0 H H6 H9 H8 H11.\n            induction d; simpl; intros;\n              invcs H8; invcs H11; simpl.\n            - apply sublist_nil_r in H6; subst.\n              simpl. constructor.\n            - destruct H3; destruct H2; destruct a; destruct y; destruct y0.\n              simpl in H, H0, H1, H2 |- *. repeat subst.\n              apply sublist_cons_inv_simple in H6;\n                [| apply NoDup_domain_NoDup;\n                 eapply is_list_sorted_NoDup; [ eapply StringOrder.lt_strorder | ];\n                 eauto].\n              apply sublist_cons_inv_simple in H9;\n                [| apply NoDup_domain_NoDup;\n                 eapply is_list_sorted_NoDup; [ eapply StringOrder.lt_strorder | ];\n                 eauto].\n              destruct H6 as [[srl' [eqq subl']]|[nin subl']].\n              + subst. simpl.\n                invcs H.\n                destruct (string_dec s1 s1); [ | congruence].\n                destruct H9 as [[srl0' [eqq0 subl0']]|[nin0 subl'0]].\n                * subst. simpl.\n                  destruct (string_dec s1 s1); [ | congruence].\n                  unfold rec_concat_sort.\n                  simpl.\n                  { rewrite insertion_sort_insert_forall_lt.\n                    - constructor; simpl.\n                      + split; eauto.\n                      + rewrite map_rtype_meet_cons2_nin;\n                        [rewrite lookup_diff_cons2_nin | ].\n                        *  apply (IHd l' l'0); trivial;\n                           try solve[eapply is_list_sorted_cons_inv; eauto].\n                        * apply is_list_sorted_NoDup in pf'0;\n                          [ | eapply StringOrder.lt_strorder ].\n                          inversion pf'0; subst; trivial.\n                        * apply is_list_sorted_NoDup in pf;\n                          [ | eapply StringOrder.lt_strorder ].\n                          inversion pf; subst; trivial.\n                    - apply Forall_sorted.\n                      apply Forall_rec_field_lt.\n                      simpl.\n                      rewrite domain_app.\n                      rewrite map_rtype_meet_domain.\n                      apply Forall_app.\n                      + apply sorted_StronglySorted in pf;\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf. inversion pf; subst.\n                        trivial.\n                      + eapply Forall_sublist.\n                        * eapply sublist_domain.\n                          eapply lookup_diff_sublist.\n                      * apply sorted_StronglySorted in pf'0;\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf'0. inversion pf'0; subst.\n                        trivial.\n                  }\n                * assert (nind: ~ In s1 (domain srl0)).\n                  { apply is_list_sorted_NoDup in pf'0;\n                    [ | eapply StringOrder.lt_strorder ].\n                    inversion pf'0; subst; trivial.\n                    intros inn; apply H2. eapply sublist_In; try eapply inn.\n                    eapply sublist_domain; trivial.\n                  } \n                  apply (lookup_nin_none string_dec) in nind.\n                  rewrite nind.\n                  unfold rec_concat_sort. simpl.\n                  {rewrite insertion_sort_insert_forall_lt.\n                    - constructor; simpl.\n                      + split; eauto.\n                      + rewrite lookup_diff_cons2_nin.\n                        *  apply (IHd l' l'0); trivial;\n                           try solve[eapply is_list_sorted_cons_inv; eauto].\n                        * apply is_list_sorted_NoDup in pf'0;\n                          [ | eapply StringOrder.lt_strorder ].\n                          inversion pf'0; subst; trivial.\n                    - apply Forall_sorted.\n                      apply Forall_rec_field_lt.\n                      simpl.\n                      rewrite domain_app.\n                      rewrite map_rtype_meet_domain.\n                      apply Forall_app.\n                      + apply sorted_StronglySorted in pf;\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf. inversion pf; subst.\n                        trivial.\n                      + eapply Forall_sublist.\n                        * eapply sublist_domain.\n                          eapply lookup_diff_sublist.\n                      * apply sorted_StronglySorted in pf'0;\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf'0. inversion pf'0; subst.\n                        trivial.\n                  }\n              + assert (nind: ~ In s1 (domain srl)).\n                  { apply is_list_sorted_NoDup in pf';\n                    [ | eapply StringOrder.lt_strorder ].\n                    inversion pf'; subst; trivial.\n                    intros inn; apply H5. eapply sublist_In; try eapply inn.\n                    eapply sublist_domain; trivial.\n                  } \n                  apply (lookup_nin_none string_dec) in nind.\n                  rewrite nind.\n                  unfold rec_concat_sort.\n                  unfold rec_sort.\n                  rewrite <- insertion_sort_insert_middle.\n                * {rewrite insertion_sort_insert_forall_lt.\n                   - constructor; simpl.\n                      + split; eauto.\n                      + destruct H9 as [[srl0' [eqq0 subl0']]|[nin0 subl0']].\n                        * subst.\n                          { rewrite map_rtype_meet_cons2_nin.\n                            - apply (IHd l' ); trivial;\n                              try solve[eapply is_list_sorted_cons_inv; eauto].\n                            - apply lookup_none_nin in nind; trivial.\n                          }\n                        * apply (IHd l' ); trivial;\n                          try solve[eapply is_list_sorted_cons_inv; eauto].\n                   - change (Forall (rec_field_lt (s1, r0))\n                                     (rec_sort\n                                        (map_rtype_meet srl srl0 ++\n                                                        lookup_diff string_dec l'0 srl))).\n                      apply Forall_sorted.\n                      apply Forall_rec_field_lt.\n                      simpl.\n                      rewrite domain_app.\n                      rewrite map_rtype_meet_domain.\n                      apply Forall_app.\n                      + apply sorted_StronglySorted in pf';\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf'. inversion pf'; subst.\n                        eapply Forall_sublist; eauto.\n                        apply sublist_domain; trivial.\n                      + eapply Forall_sublist.  \n                        * eapply sublist_domain.\n                          eapply lookup_diff_sublist.\n                      * apply sorted_StronglySorted in pf'0;\n                        [ | eapply StrictOrder_Transitive ].\n                        simpl in pf'0. inversion pf'0; subst.\n                        trivial.\n                  }\n                * rewrite map_rtype_meet_domain.\n                  apply lookup_none_nin in nind.\n                  trivial.\n          }\n          econstructor; try eapply F2.\n          - eapply rec_concat_sort_sorted; reflexivity.\n          - unfold rec_concat_sort.\n            apply Sorted_incl_sublist; try apply insertion_sort_Sorted.\n            intros ? inn.\n            rewrite <- rec_sort_perm in inn |- *.\n            + rewrite in_app_iff in inn |- *.\n              destruct inn as [inn|inn]; [tauto | ].\n              right.\n              apply lookup_diff_inv in inn.\n              destruct inn as [inn ninn].\n              destruct x.\n              apply (lookup_in string_dec).\n              simpl in *.\n              rewrite lookup_diff_none2.\n              * apply in_lookup_nodup.\n                { eapply is_list_sorted_NoDup ;\n                  [ eapply StringOrder.lt_strorder | ]; eauto. }\n                eapply sublist_In; eauto.\n              * apply lookup_nin_none; trivial.\n            + apply NoDup_map_rtype_meet_lookup_diff.\n              * eapply is_list_sorted_NoDup;\n                [ eapply StringOrder.lt_strorder | ].\n                apply sublist_domain in H6.\n                eapply is_list_sorted_sublist; try eapply H6; eauto.\n              * eapply is_list_sorted_NoDup;\n                [ eapply StringOrder.lt_strorder | ].\n                apply sublist_domain in H9.\n                eapply is_list_sorted_sublist; try eapply H9; eauto.\n            + rewrite domain_app, map_rtype_meet_domain.\n              apply NoDup_app; eauto 2 with qcert.\n              * symmetry; apply lookup_diff_disjoint.\n              * apply NoDup_lookup_diff; qeauto.\n          - intros.\n            destruct k; destruct k0; simpl in H0.\n            + discriminate.\n            + rewrite H10 by trivial; reflexivity.\n            + rewrite H7 by trivial.\n              repeat rewrite lookup_diff_domain_bounded.\n              * reflexivity.\n              * rewrite <- (sorted_forall_same_domain H8).\n                rewrite <- (sorted_forall_same_domain H11).\n                reflexivity.\n              * rewrite <- (sorted_forall_same_domain H8).\n                rewrite  (sorted_forall_same_domain H11).\n                rewrite H9; reflexivity.\n            + rewrite H10 by trivial; reflexivity.\n        }\n      + elim n; clear n.\n        assert (domeq:domain rl = domain rl0).\n        {\n          rewrite <- (sorted_forall_same_domain H8).\n          rewrite (sorted_forall_same_domain H11).\n          trivial.\n        }\n        destruct k; destruct k0; simpl; trivial.\n        * rewrite H10 in * by trivial.\n          rewrite <- domeq.\n          apply sublist_domain; trivial.\n        *  rewrite H7 in * by trivial.\n           rewrite domeq.\n           apply sublist_domain; trivial.\n        * rewrite H7, H10 by trivial.\n          congruence.\n    - intros; dtype_inverter_with_either.\n      + inversion H; rtype_equalizer. subst.\n        econstructor. apply IH\u03c4\u20811; trivial.\n      + inversion H; rtype_equalizer. subst.\n        econstructor. apply IH\u03c4\u20812; trivial.\n    - intros; dtype_inverter.\n      inversion H; clear H; subst.\n      inversion H0; clear H0; subst.\n      constructor; trivial.\n      apply canon_equiv in H3.\n      apply canon_equiv in H2.\n      rewrite H3 in H7.\n      rewrite H2 in H11.\n      apply (meet_most (olattice:=brands_olattice)); trivial.\n    - intros dt1 dt2.\n      invcs dt1.\n      invcs dt2.\n      constructor.\n      apply foreign_data_typing_meet; trivial.\n  Qed.\n\n  Theorem meet_data_type_iff\n          {fdata:foreign_data}\n          {ftype:foreign_type}\n          {fdtyping:foreign_data_typing}\n          {m:brand_model} d \u03c4\u2081 \u03c4\u2082:\n    d \u25b9 (\u03c4\u2081 \u2293 \u03c4\u2082) <-> (d \u25b9 \u03c4\u2081 /\\ d \u25b9 \u03c4\u2082).\n  Proof.\n    split; intros HH.\n    - split.\n      + rewrite meet_leq_l in HH; trivial.\n      + rewrite meet_leq_r in HH; trivial.\n    - apply meet_preserves_data_type; tauto.\n  Qed.\n  \n  Lemma brands_type_Forall\n        {fdata:foreign_data}\n        {ftype:foreign_type}\n        {fdtyping:foreign_data_typing}\n        {m:brand_model} d b :\n    d \u25b9 (brands_type b)\n     <->\n     (data_normalized brand_relation_brands d /\\ \n    Forall (fun bb =>\n              forall \u03c4, \n                lookup string_dec brand_context_types bb = Some \u03c4 ->\n                d \u25b9 \u03c4\n           ) b).\n  Proof.\n    Hint Resolve data_type_normalized : qcert.\n    rewrite brands_type_alt.\n    induction b; simpl; [ intuition; qeauto | ].\n    destruct IHb as [IHb1 IHb2].\n    case_eq ( lookup string_dec brand_context_types a); intros; simpl.\n    - generalize (meet_data_type_iff d r (fold_right rtype_meet \u22a4 (brands_type_list b))); simpl; intros eqq.\n      rewrite eqq; clear eqq.\n      { split; intros [dt dtf].\n        - split; [qeauto | ].\n          constructor.\n          + rewrite H. intro; inversion 1; subst; trivial.\n          + apply IHb1; trivial.\n        - inversion dtf; clear dtf; subst.\n          specialize (H2 _ H). split; trivial.\n          apply IHb2; split; trivial.\n      }\n    - { split; [intros dt | intros [dt dtf]].\n        - split; [ qeauto | ].\n          constructor.\n          + rewrite H; intros; discriminate.\n          + apply IHb1; trivial.\n        - inversion dtf; clear dtf; subst.\n          apply IHb2; split; trivial.\n      } \n  Qed.\n\n  Lemma dtbrand'\n        {fdata:foreign_data}\n        {ftype:foreign_type}\n        {fdtyping:foreign_data_typing}\n        {m:brand_model} b b' d:\n      is_canon_brands brand_relation_brands b ->\n      d \u25b9 (brands_type b) ->\n      b \u2264 b' ->\n      data_type (dbrand b d) (Brand b').\n  Proof.\n    intros.\n    apply brands_type_Forall in H0.\n    apply dtbrand; intuition.\n  Qed.\n\n  Lemma dtbrand'_inv\n        {fdata:foreign_data}\n        {ftype:foreign_type}\n        {fdtyping:foreign_data_typing}\n        {m:brand_model} b b' d:\n    data_type (dbrand b d) (Brand b') ->\n    is_canon_brands brand_relation_brands b /\\\n    d \u25b9 (brands_type b) /\\\n    b \u2264 b'.\n  Proof.\n    intros dt.\n    apply dtbrand_inv in dt.\n    intuition.\n    apply brands_type_Forall; intuition.\n  Qed.\n    \n(*\n  Global Instance data_type_sub_model_prop : Proper (sub_model ==> eq ==> eq ==> impl) (data_type).\n  Proof.\n    unfold Proper, respectful, flip, impl; intros; subst.\n    revert x y H y1 H2.\n    Hint Resolve data_type_normalized.\n    Hint Constructors data_type.\n    induction y0; simpl; inversion 2; subst; eauto 2.\n    - constructor. revert H3. apply Forall_impl_in. intros.\n      generalize (Forallt_In H _ H1 _ _ H0). eauto.\n    -  inversion H2; rtype_equalizer; subst.\n       econstructor; eauto. revert H10.\n       apply Forall2_incl; intros. intuition.\n       generalize (Forallt_In H _ H1 _ _ H0); intros.\n       eauto.\n    - specialize (IHy0 _ _ H _ H3).\n      case_eq (lookup string_dec (brand_context_types y) b); intros.\n      + apply lookup_in in H0.\n         generalize (Rec_subtype_In H H5 H0); intros.\n         rewrite H1 in IHy0. eauto.\n      + apply lookup_none_nin in H0.\n         eauto.\n    - apply dtbrand_unknown; trivial.\n      intro inn.\n      generalize (SRec_closed_in_domain H _ inn).\n      congruence.\n  Qed.\n*)\nEnd subtype.\n\nGlobal Hint Resolve data_type_normalized : qcert. \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/ModelTyping/TData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.18839833410629483}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paco.\nFrom Paco Require Import paconotation_internal paco_internal pacotac_internal.\nFrom Paco Require Export paconotation.\nFrom Fairness Require Import pind_internal.\nSet Implicit Arguments.\n\nSection PIND12.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.\nVariable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.\nVariable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.\nVariable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.\nVariable T11 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), Type.\n\n(** ** Predicates of Arity 12\n*)\n\nDefinition pind12(gf : rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)(r: rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) : rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 :=\n  @curry12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 (pind (fun R0 => @uncurry12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 (gf (@curry12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 R0))) (@uncurry12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 r)).\n\nDefinition upind12(gf : rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)(r: rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) := pind12 gf r /12\\ r.\nArguments pind12 : clear implicits.\nArguments upind12 : clear implicits.\n#[local] Hint Unfold upind12 : core.\n\nLemma monotone12_inter (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11)\n      (MON1: monotone12 gf)\n      (MON2: monotone12 gf'):\n  monotone12 (gf /13\\ gf').\nProof.\n  red; intros. destruct IN. split; eauto.\nQed.\n\nLemma _pind12_mon_gen (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r r'\n    (LEgf: gf <13= gf')\n    (LEr: r <12= r'):\n  pind12 gf r <12== pind12 gf' r'.\nProof.\n  apply curry_map12. red; intros. eapply pind_mon_gen. apply PR.\n  - intros. apply LEgf, PR0.\n  - intros. apply LEr, PR0.\nQed.\n\nLemma pind12_mon_gen (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: pind12 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf')\n    (LEr: r <12= r'):\n  pind12 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  eapply _pind12_mon_gen; [apply LEgf | apply LEr | apply REL].\nQed.\n\nLemma pind12_mon_bot (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: pind12 gf bot12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf'):\n  pind12 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  eapply pind12_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nDefinition top12 { T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3) (x5: T5 x0 x1 x2 x3 x4) (x6: T6 x0 x1 x2 x3 x4 x5) (x7: T7 x0 x1 x2 x3 x4 x5 x6) (x8: T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) := True.\n\nLemma pind12_mon_top (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: pind12 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf'):\n  pind12 gf' top12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  eapply pind12_mon_gen; eauto. red. auto.\nQed.\n\nLemma upind12_mon_gen (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: upind12 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf')\n    (LEr: r <12= r'):\n  upind12 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  destruct REL. split; eauto.\n  eapply pind12_mon_gen; [apply H | apply LEgf | apply LEr].\nQed.\n\nLemma upind12_mon_bot (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: upind12 gf bot12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf'):\n  upind12 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  eapply upind12_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nLemma upind12mon_top (gf gf': rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11) r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11\n    (REL: upind12 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)\n    (LEgf: gf <13= gf'):\n  upind12 gf' top12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11.\nProof.\n  eapply upind12_mon_gen; eauto. red. auto.\nQed.\n\nSection Arg12.\n\nVariable gf : rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 -> rel12 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11.\nArguments gf : clear implicits.\n\nTheorem _pind12_mon: _monotone12 (pind12 gf).\nProof.\n  red; intros. eapply curry_map12, _pind_mon; apply uncurry_map12; assumption.\nQed.\n\nTheorem _pind12_acc: forall\n  l r (OBG: forall rr (DEC: rr <12== r) (IH: rr <12== l), pind12 gf rr <12== l),\n  pind12 gf r <12== l.\nProof.\n  intros. apply curry_adjoint2_12.\n  eapply _pind_acc. intros.\n  apply curry_adjoint2_12 in DEC. apply curry_adjoint2_12 in IH.\n  apply curry_adjoint1_12.\n  eapply le12_trans. 2: eapply (OBG _ DEC IH).\n  apply curry_map12.\n  apply _pind_mon; try apply le1_refl; apply curry_bij2_12.\nQed.\n\nTheorem _pind12_mult_strong: forall r,\n  pind12 gf r <12== pind12 gf (upind12 gf r).\nProof.\n  intros. apply curry_map12.\n  eapply le1_trans; [eapply _pind_mult_strong |].\n  apply _pind_mon; intros [] H. apply H.\nQed.\n\nTheorem _pind12_fold: forall r,\n  gf (upind12 gf r) <12== pind12 gf r.\nProof.\n  intros. apply uncurry_adjoint1_12.\n  eapply le1_trans; [| apply _pind_fold]. apply le1_refl.\nQed.\n\nTheorem _pind12_unfold: forall (MON: _monotone12 gf) r,\n  pind12 gf r <12== gf (upind12 gf r).\nProof.\n  intros. apply curry_adjoint2_12.\n  eapply _pind_unfold; apply monotone12_map; assumption.\nQed.\n\nTheorem pind12_acc: forall\n  l r (OBG: forall rr (DEC: rr <12= r) (IH: rr <12= l), pind12 gf rr <12= l),\n  pind12 gf r <12= l.\nProof.\n  apply _pind12_acc.\nQed.\n\nTheorem pind12_mon: monotone12 (pind12 gf).\nProof.\n  apply monotone12_eq.\n  apply _pind12_mon.\nQed.\n\nTheorem upind12_mon: monotone12 (upind12 gf).\nProof.\n  red; intros.\n  destruct IN. split; eauto.\n  eapply pind12_mon. apply H. apply LE.\nQed.\n\nTheorem pind12_mult_strong: forall r,\n  pind12 gf r <12= pind12 gf (upind12 gf r).\nProof.\n  apply _pind12_mult_strong.\nQed.\n\nCorollary pind12_mult: forall r,\n  pind12 gf r <12= pind12 gf (pind12 gf r).\nProof. intros; eapply pind12_mult_strong in PR. eapply pind12_mon; eauto. intros. destruct PR0. eauto. Qed.\n\nTheorem pind12_fold: forall r,\n  gf (upind12 gf r) <12= pind12 gf r.\nProof.\n  apply _pind12_fold.\nQed.\n\nTheorem pind12_unfold: forall (MON: monotone12 gf) r,\n  pind12 gf r <12= gf (upind12 gf r).\nProof.\n  intro. eapply _pind12_unfold; apply monotone12_eq; assumption.\nQed.\n\nEnd Arg12.\n\nArguments pind12_acc : clear implicits.\nArguments pind12_mon : clear implicits.\nArguments upind12_mon : clear implicits.\nArguments pind12_mult_strong : clear implicits.\nArguments pind12_mult : clear implicits.\nArguments pind12_fold : clear implicits.\nArguments pind12_unfold : clear implicits.\n\nEnd PIND12.\n\nGlobal Opaque pind12.\n\n#[export] Hint Unfold upind12 : core.\n#[export] Hint Resolve pind12_fold : core.\n#[export] Hint Unfold monotone12 : core.\n\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/pico/pind12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.18839832707528614}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.GLabel Platform.Cito.GLabelMap Platform.Cito.GLabelMapFacts Platform.Cito.ConvertLabel Platform.Cito.GoodModule Platform.Cito.GoodFunction Platform.Cito.NameDecoration Platform.Cito.Label2Word.\nExport GLabel GLabelMap GLabelMapFacts ConvertLabel GoodModule GoodFunction Cito.NameDecoration Label2Word.\nImport GLabelMap.\n\nSection TopSection.\n\n  Variable ADTValue : Type.\n\n  Variable modules : list GoodModule.\n  \n  Require Import Platform.Cito.Semantics.\n  Require Import Platform.Cito.AxSpec.\n\n  Variable imports : GLabelMap.t (AxiomaticSpec ADTValue).\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  Notation Internal := (@Internal ADTValue).\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  Notation Callee := (@Callee ADTValue).\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 glabel2w (stn : settings) (lbl : glabel) : option W := Labels stn lbl.\n  \n  Definition env_good_to_use stn fs :=\n    stn_good_to_use stn /\\\n    stn_injective label_in (glabel2w 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 Platform.Cito.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 is_export := find_by_word (glabel2w stn) (elements exports_IFS).\n\n    Definition is_import := find_by_word (glabel2w stn) (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\nEnd TopSection.\n\nDefinition name_marker (id : glabel) : PropX W (settings * state) := (Ex s, [| s = id |])%PropX.\n\nRequire Import Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Platform.Cito.Semantics.\n  Module Import SemanticsMake := Make E.\n  Export Semantics SemanticsMake.\n\n  Require Import Platform.Cito.RepInv.\n\n  Module Make (Import M : RepInv E).\n\n    Require Import Platform.Cito.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      (* the exported Bedrock spec format *)\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      (* the imported Bedrock spec format *)\n      Definition foreign_func_spec id spec : assert := \n        st ~> name_marker id /\\ ExX, foreign_spec _ spec st.\n\n      (* the imported Bedrock specs *)\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      (* the exported Bedrock specs (barring the exports from internal implementation, which shouldn't be used) *)\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      (* the imported Bedrock specs (including the exports from internal implementation, which shouldn't be used) *)\n      Definition all_exports := update exports impl_exports.\n\n    End TopSection.\n\n  End Make.\n\nEnd Make.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/LinkSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18809850625490437}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining *)\n\nRequire Import Coqlib.\nRequire Import Wfsimpl.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\n\nLtac xomega := unfold Plt, Ple in *; zify; omega.\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 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_fundef (fenv: funenv) (idf: ident * fundef) : funenv :=\n  match idf with\n  | (id, External ef) =>\n      PTree.remove id fenv\n  | (id, Internal f) =>\n      if should_inline id f\n      then PTree.set id f fenv\n      else PTree.remove id fenv\n  end.\n\nDefinition remove_vardef (fenv: funenv) (idv: ident * globvar unit) : funenv :=\n  PTree.remove (fst idv) fenv.\n\nDefinition funenv_program (p: program) : funenv :=\n  List.fold_left remove_vardef p.(prog_vars)\n    (List.fold_left add_fundef p.(prog_funct) (PTree.empty function)).\n\n(** Resources used by a function. *)\n\n(** Maximum PC (node number) in the CFG of a function.  All nodes of\n  the CFG of [f] are between 1 and [max_pc_function f] (inclusive). *)\n\nDefinition max_pc_function (f: function) :=\n  PTree.fold (fun m pc i => Pmax m pc) f.(fn_code) 1%positive.\n\n(** Maximum pseudo-register defined in a function.  All results of\n  an instruction of [f], as well as all parameters of [f], are between\n  1 and [max_def_function] (inclusive). *)\n\nDefinition max_def_instr (i: instruction) :=\n  match i with\n  | Iop op args res s => res\n  | Iload chunk addr args dst s => dst\n  | Icall sg ros args res s => res\n  | Ibuiltin ef args res s => res\n  | _ => 1%positive\n  end.\n\nDefinition max_def_function (f: function) :=\n  Pmax\n    (PTree.fold (fun m pc i => Pmax m (max_def_instr i)) f.(fn_code) 1%positive)\n    (List.fold_left (fun m r => Pmax m r) f.(fn_params) 1%positive).\n\n(** State monad *)\n\n(** To construct incrementally the CFG of a function after inlining,\n  we use a state monad similar to that used in module [RTLgen].\n  It records the current state of the CFG, plus counters to generate\n  fresh pseudo-registers and fresh CFG nodes.  It also records the\n  stack size needed for the inlined function. *)\n\nRecord state : Type := mkstate {\n  st_nextreg: positive;                 (**r last used pseudo-register *)\n  st_nextnode: positive;                (**r last used CFG node *)\n  st_code: code;                        (**r current CFG  *)\n  st_stksize: Z                         (**r current stack size *)\n}.\n\n(** Monotone evolution of the state. *)\n\nInductive sincr (s1 s2: state) : Prop :=\n  Sincr (NEXTREG: Ple s1.(st_nextreg) s2.(st_nextreg))\n        (NEXTNODE: Ple s1.(st_nextnode) s2.(st_nextnode))\n        (STKSIZE: s1.(st_stksize) <= s2.(st_stksize)).\n\nRemark sincr_refl: forall s, sincr s s.\nProof.\n  intros; constructor; xomega.\nQed.\n\nLemma sincr_trans: forall s1 s2 s3, sincr s1 s2 -> sincr s2 s3 -> sincr s1 s3.\nProof.\n  intros. inv H; inv H0. constructor; xomega.\nQed.\n\n(** Dependently-typed state monad, ensuring that the final state is\n  greater or equal (in the sense of predicate [sincr] above) than\n  the initial state. *)\n\nInductive res {A: Type} {s: state}: Type := R (x: A) (s': state) (I: sincr s s').\n\nDefinition mon (A: Type) : Type := forall (s: state), @res A s.\n\n(** Operations on this monad. *)\n\nDefinition ret {A: Type} (x: A): mon A :=\n  fun s => R x s (sincr_refl s).\n\nDefinition bind {A B: Type} (x: mon A) (f: A -> mon B): mon B :=\n  fun s1 => match x s1 with R vx s2 I1 =>\n              match f vx s2 with R vy s3 I2 =>\n                R vy s3 (sincr_trans s1 s2 s3 I1 I2)\n              end\n            end.\n\nNotation \"'do' X <- A ; B\" := (bind A (fun X => B))\n   (at level 200, X ident, A at level 100, B at level 200).\n\nDefinition initstate :=\n  mkstate 1%positive 1%positive (PTree.empty instruction) 0.\n\nProgram Definition set_instr (pc: node) (i: instruction): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition add_instr (i: instruction): mon node :=\n  fun s =>\n    let pc := Psucc s.(st_nextnode) in\n    R pc\n      (mkstate s.(st_nextreg) pc (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_nodes (numnodes: positive): mon positive :=\n  fun s =>\n    R s.(st_nextnode)\n      (mkstate s.(st_nextreg) (Pplus s.(st_nextnode) numnodes) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_regs (numregs: positive): mon positive :=\n  fun s =>\n    R s.(st_nextreg)\n      (mkstate (Pplus s.(st_nextreg) numregs) s.(st_nextnode) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition request_stack (sz: Z): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) s.(st_code) (Zmax s.(st_stksize) sz))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nFixpoint mlist_iter2 {A B: Type} (f: A -> B -> mon unit) (l: list (A*B)): mon unit :=\n  match l with\n  | nil => ret tt\n  | (x,y) :: l' => do z <- f x y; mlist_iter2 f l'\n  end.\n\n(** ** Inlining contexts *)\n\n(** A context describes how to insert the CFG for a source function into\n  the CFG for the function after inlining:\n- a source instruction at PC [n] is relocated to PC [n + ctx.(dpc)];\n- all pseudo-registers of this instruction are shifted by [ctx.(dreg)];\n- all stack references are shifted by [ctx.(dstk)];\n- \"return\" instructions are transformed into \"return\" or \"move\" instructions\n  as governed by [ctx.(retinfo)].\n*)\n\nRecord context: Type := mkcontext {\n  dpc: positive;                        (**r offset for PCs *)\n  dreg: positive;                       (**r offset for pseudo-regs *)\n  dstk: Z;                              (**r offset for stack references *)\n  mreg: positive;                       (**r max pseudo-reg number *)\n  mstk: Z;                              (**r original stack block size *)\n  retinfo: option(node * reg)           (**r where to branch on return *)\n                                        (**r and deposit return value *)\n}.\n\n(** The following functions \"shift\" (relocate) PCs, registers, operations, etc. *)\n\nDefinition spc (ctx: context) (pc: node) := Pplus pc ctx.(dpc).\n\nDefinition sreg (ctx: context) (r: reg) := Pplus r ctx.(dreg).\n\nDefinition sregs (ctx: context) (rl: list reg) := List.map (sreg ctx) rl.\n\nDefinition sros (ctx: context) (ros: reg + ident) := sum_left_map (sreg ctx) ros.\n\nDefinition sop (ctx: context) (op: operation) :=\n  shift_stack_operation (Int.repr ctx.(dstk)) op.\n\nDefinition saddr (ctx: context) (addr: addressing) :=\n  shift_stack_addressing (Int.repr ctx.(dstk)) addr.\n\n(** The initial context, used to copy the CFG of a toplevel function. *)\n\nDefinition initcontext (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := 0;\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := None |}.\n\n(** The context used to inline a call to another function. *)\n\nDefinition min_alignment (sz: Z) :=\n  if zle sz 1 then 1\n  else if zle sz 2 then 2\n  else if zle sz 4 then 4 else 8.\n\nDefinition callcontext (ctx: context)\n                      (dpc dreg nreg: positive) (sz: Z)\n                      (retpc: node) (retreg: reg) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align (ctx.(dstk) + ctx.(mstk)) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := Some (spc ctx retpc, sreg ctx retreg) |}.\n\n(** The context used to inline a tail call to another function. *)\n\nDefinition tailcontext (ctx: context) (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align ctx.(dstk) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := ctx.(retinfo) |}.\n\n(** ** Recursive expansion and copying of a CFG *)\n\n(** Insert \"move\" instructions to copy the arguments of an inlined\n    function into its parameters. *)\n\nFixpoint add_moves (srcs dsts: list reg) (succ: node): mon node :=\n  match srcs, dsts with\n  | s1 :: sl, d1 :: dl =>\n      do n <- add_instr (Iop Omove (s1 :: nil) d1 succ);\n      add_moves sl dl n\n  | _, _ =>\n      ret succ\n  end.\n\n(** To prevent infinite inlining of a recursive function, when we\n  inline the body of a function [f], this function is removed from the\n  environment of inlinable functions and therefore becomes ineligible\n  for inlining.  This decreases the size (number of entries) of the\n  environment and guarantees termination.  Inlining is, therefore,\n  presented as a well-founded recursion over the size of the environment. *)\n\nSection EXPAND_CFG.\n\nVariable fenv: funenv.\n\n(** The [rec] parameter is the recursor: [rec fenv' P ctx f] copies \n  the body of function [f], with inline expansion within, as governed\n  by context [ctx].  It can only be called for function environments\n  [fenv'] strictly smaller than the current environment [fenv]. *)\n\nVariable rec: forall fenv', (size_fenv fenv' < size_fenv fenv)%nat -> context -> function -> mon unit.\n\n(** Given a register-or-symbol [ros], can we inline the corresponding call? *)\n\nInductive inline_decision (ros: reg + ident) : Type :=\n  | Cannot_inline\n  | Can_inline (id: ident) (f: function) (P: ros = inr reg id) (Q: fenv!id = Some f).\n\nProgram Definition can_inline (ros: reg + ident): inline_decision ros :=\n  match ros with\n  | inl r => Cannot_inline _\n  | inr id => match fenv!id with Some f => Can_inline _ id f _ _ | None => Cannot_inline _ end\n  end.\n\n(** Inlining of a call to function [f].  An appropriate context is\n  created, then the CFG of [f] is recursively copied, then moves\n  are inserted to copy the arguments of the call to the parameters of [f]. *)\n\nDefinition inline_function (ctx: context) (id: ident) (f: function)\n                           (P: PTree.get id fenv = Some f)\n                           (args: list reg)\n                           (retpc: node) (retreg: reg) : mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := callcontext ctx dpc dreg nreg f.(fn_stacksize) retpc retreg in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** Inlining of a tail call to function [f].  Similar to [inline_function],\n  but the new context is different. *)\n\nDefinition inline_tail_function (ctx: context) (id: ident) (f: function)\n                               (P: PTree.get id fenv = Some f)\n                               (args: list reg): mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := tailcontext ctx dpc dreg nreg f.(fn_stacksize) in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** The instruction generated for a [Ireturn] instruction found in an\n  inlined function body. *)\n\nDefinition inline_return (ctx: context) (or: option reg) (retinfo: node * reg) :=\n  match retinfo, or with\n  | (retpc, retreg), Some r => Iop Omove (sreg ctx r :: nil) retreg retpc\n  | (retpc, retreg), None   => Inop retpc\n  end.\n\n(** Expansion and copying of an instruction.  For most instructions,\n  its registers and successor PC are shifted as per the context [ctx],\n  then the instruction is inserted in the final CFG at its final position\n  [spc ctx pc].  \n\n  [Icall] instructions are either replaced by a \"goto\" to the expansion\n  of the called function, or shifted as described above.\n\n  [Itailcall] instructions are similar, with one additional case.  If\n  the [Itailcall] occurs in the body of an inlined function, and\n  cannot be inlined itself, it must be turned into an [Icall]\n  instruction that branches to the return point of the inlined\n  function.\n\n  Finally, [Ireturn] instructions within an inlined function are\n  turned into a \"move\" or \"goto\" that stores the result, if any,\n  into the destination register, then branches back to the successor\n  of the inlined call. *)\n\nDefinition expand_instr (ctx: context) (pc: node) (i: instruction): mon unit :=\n  match i with\n  | Inop s =>\n      set_instr (spc ctx pc) (Inop (spc ctx s))\n  | Iop op args res s =>\n      set_instr (spc ctx pc)\n                (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Iload chunk addr args dst s =>\n      set_instr (spc ctx pc)\n                (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx dst) (spc ctx s))\n  | Istore chunk addr args src s =>\n      set_instr (spc ctx pc)\n                (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s))\n  | Icall sg ros args res s =>\n      match can_inline ros with\n      | Cannot_inline =>\n          set_instr (spc ctx pc)\n                    (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s))\n      | Can_inline id f P Q =>\n          do n <- inline_function ctx id f Q args s res;\n          set_instr (spc ctx pc) (Inop n)\n      end\n  | Itailcall sg ros args =>\n      match can_inline ros with\n      | Cannot_inline =>\n          match ctx.(retinfo) with\n          | None =>\n              set_instr (spc ctx pc)\n                        (Itailcall sg (sros ctx ros) (sregs ctx args))\n          | Some(rpc, rreg) =>\n              set_instr (spc ctx pc)\n                        (Icall sg (sros ctx ros) (sregs ctx args) rreg rpc)\n          end\n      | Can_inline id f P Q =>\n          do n <- inline_tail_function ctx id f Q args;\n          set_instr (spc ctx pc) (Inop n)\n      end          \n  | Ibuiltin ef args res s =>\n      set_instr (spc ctx pc)\n                (Ibuiltin ef (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Icond cond args s1 s2 =>\n      set_instr (spc ctx pc)\n                (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2))\n  | Ijumptable r tbl =>\n      set_instr (spc ctx pc)\n                (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl))\n  | Ireturn or =>\n      match ctx.(retinfo) with\n      | None =>\n          set_instr (spc ctx pc) (Ireturn (option_map (sreg ctx) or))\n      | Some rinfo =>\n          set_instr (spc ctx pc) (inline_return ctx or rinfo)\n      end\n  end.\n\n(** The expansion of a function [f] iteratively expands all its\n  instructions, after recording how much stack it needs. *)\n\nDefinition expand_cfg_rec (ctx: context) (f: function): mon unit :=\n  do x <- request_stack (ctx.(dstk) + ctx.(mstk));\n  mlist_iter2 (expand_instr ctx) (PTree.elements f.(fn_code)).\n\nEnd EXPAND_CFG.\n\n(** Here we \"tie the knot\" of the recursion, taking the fixpoint\n  of [expand_cfg_rec]. *)\n\nDefinition expand_cfg := Fixm size_fenv expand_cfg_rec.\n\n(** Start of the recursion: copy and inline function [f] in the\n  initial context. *)\n\nDefinition expand_function (fenv: funenv) (f: function): mon context :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx := initcontext dpc dreg nreg f.(fn_stacksize) in \n  do x <- expand_cfg fenv ctx f;\n  ret ctx.\n\n(** ** Inlining in functions and whole programs. *)\n\nLocal Open Scope string_scope.\n\n(** Inlining can increase the size of the function's stack block.  We must\n  make sure that the new size does not exceed [Int.max_unsigned], otherwise\n  address computations within the stack would overflow and produce incorrect\n  results. *)\n\nDefinition transf_function (fenv: funenv) (f: function) : Errors.res function :=\n  let '(R ctx s _) := expand_function fenv f initstate in\n  if zle s.(st_stksize) Int.max_unsigned then\n    OK (mkfunction f.(fn_sig) \n                   (sregs ctx f.(fn_params))\n                   s.(st_stksize)\n                   s.(st_code)\n                   (spc ctx f.(fn_entrypoint)))\n  else\n    Error(msg \"Inlining: stack too big\").\n\nDefinition transf_fundef (fenv: funenv) (fd: fundef) : Errors.res fundef :=\n  AST.transf_partial_fundef (transf_function fenv) fd.\n\nDefinition transf_program (p: program): Errors.res program :=\n  let fenv := funenv_program p in\n  AST.transform_partial_program (transf_fundef fenv) p.\n\n", "meta": {"author": "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/Inlining.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18809850625490437}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*       for the C functions implemented in the MShareIntro layer      *)\n(*                                                                     *)\n(*                                                                     *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import PTNewGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import XOmega.\n\nRequire Import AbstractDataType.\n\nRequire Import MShare.\nRequire Import MShareOpCSource.\nRequire Import ShareGenSpec.\n\nModule MSHARECODE.\n\n  Lemma shared_mem_arg_rev: forall pid1 pid2,\n                              shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                              = shared_mem_arg (Int.unsigned pid2) (Int.unsigned pid1).\n  Proof.\n    unfold shared_mem_arg. intros.\n    destruct (zle_lt 0 (Int.unsigned pid1) 64), (zle_lt 0 (Int.unsigned pid2) 64),\n             (zeq (Int.unsigned pid1) (Int.unsigned pid2)) eqn:peq; trivial;\n    try rewrite e, zeq_true; try rewrite zeq_false; trivial; auto.\n  Qed.\n\n  Lemma SharedMemInfo2Z_valid: forall x,\n                                 SharedMemInfo2Z x =\n                                 Int.unsigned (Int.repr (SharedMemInfo2Z x)).\n  Proof.\n    destruct x; simpl; reflexivity.\n  Qed.\n\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n\n    Section SHAREDMEMSTATUS.\n\n      Let L: compatlayer (cdata RData) :=\n        get_shared_mem_seen \u21a6 gensem get_shared_mem_seen_spec\n      \u2295 set_shared_mem_seen \u21a6 gensem set_shared_mem_seen_spec\n      \u2295 get_shared_mem_state \u21a6 gensem get_shared_mem_state_spec\n      \u2295 get_shared_mem_status_seen \u21a6 gensem get_shared_mem_status_seen_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n\n      Section SharedMemStatusBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        Variable bget_shared_mem_state: block.\n\n        Hypothesis hget_shared_mem_state1 : Genv.find_symbol ge get_shared_mem_state = Some bget_shared_mem_state.\n\n        Hypothesis hget_shared_mem_state2 : Genv.find_funct_ptr ge bget_shared_mem_state =\n        Some (External (EF_external get_shared_mem_state\n                                    (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default))\n                       (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (**)\n\n        Variable bset_shared_mem_seen: block.\n\n        Hypothesis hset_shared_mem_seen1 : Genv.find_symbol ge set_shared_mem_seen = Some bset_shared_mem_seen.\n\n        Hypothesis hset_shared_mem_seen2 : Genv.find_funct_ptr ge bset_shared_mem_seen =\n        Some (External (EF_external set_shared_mem_seen\n                                    (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil)))\n                                                       tvoid cc_default))\n                       (Tcons tint (Tcons tint (Tcons tint Tnil))) tvoid cc_default).\n\n        (**)\n\n        Variable bget_shared_mem_seen: block.\n\n        Hypothesis hget_shared_mem_seen1 : Genv.find_symbol ge get_shared_mem_seen = Some bget_shared_mem_seen.\n\n        Hypothesis hget_shared_mem_seen2 : Genv.find_funct_ptr ge bget_shared_mem_seen =\n        Some (External (EF_external get_shared_mem_seen\n                                    (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default))\n                       (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (**)\n\n        Variable bget_shared_mem_status_seen: block.\n\n        Hypothesis hget_shared_mem_status_seen1 : Genv.find_symbol ge get_shared_mem_status_seen =\n                                                  Some bget_shared_mem_status_seen.\n\n        Hypothesis hget_shared_mem_status_seen2 : Genv.find_funct_ptr ge bget_shared_mem_status_seen =\n        Some (External (EF_external get_shared_mem_status_seen\n                                    (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default))\n                       (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n      (*******************)\n\n        Function ll_shared_mem_status_spec (pid1 pid2: Z) (adt: RData) : option (RData * Z) :=\n          match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n            | (true, true, true, true, true) =>\n              match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n                | SHRDValid i' true _ => \n                  match get_shared_mem_status_seen_spec pid1 pid2 adt with\n                    | Some j => Some (adt, j)\n                    | _ => None\n                  end\n                | SHRDValid i' false vadr => \n                  Some (adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid i' true vadr) \n                                                              (ZMap.get pid1 (smspool adt)))\n                                               (smspool adt)}, SharedMemInfo2Z i')\n                | _ => None\n              end \n            | _ => None\n          end.\n\n        Lemma ll_shared_mem_status__correct: forall m d d' (z: Z) env le pid1 pid2 n,\n                                      env = PTree.empty _ ->\n                                      PTree.get _source le = Some (Vint pid1) ->\n                                      PTree.get _dest le = Some (Vint pid2) ->\n                                      (*pg d = true ->*)\n                                      ll_shared_mem_status_spec (Int.unsigned pid1) (Int.unsigned pid2) d\n                                      = Some (d', Int.unsigned n) ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_status_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          intros. subst.\n          inversion H4. (*high_level_invariant d *)\n          functional inversion H3; subst.\n          - esplit.\n            unfold exec_stmt.\n            change E0 with (E0 ** E0).\n            repeat vcgen.\n            + unfold get_shared_mem_seen_spec.\n              rewrite H7, H8, H9, H10, H6.\n              rewrite H11.\n              unfold BooltoZ.\n              cutrewrite (1 = Int.unsigned (Int.repr 1)); reflexivity.\n            + repeat vcgen.\n            + repeat vcgen.\n          - esplit.\n            unfold exec_stmt.\n            change E0 with (E0 ** E0).\n            repeat vcgen.\n            + unfold get_shared_mem_seen_spec.\n              rewrite H7, H8, H9, H10, H6.\n              rewrite H11.\n              unfold BooltoZ.\n              cutrewrite (0 = Int.unsigned (Int.repr 0)); reflexivity.\n            + unfold exec_stmt.\n              change E0 with (E0 ** E0).\n              repeat vcgen.\n              unfold get_shared_mem_state_spec. simpl.\n              rewrite H7, H8, H9, H10, H6.\n              repeat rewrite ZMap.gss.\n              rewrite SharedMemInfo2Z_valid.\n              reflexivity.\n            + rewrite H5. repeat vcgen.\n        Qed.\n\n        Lemma ll_shared_mem_status_spec__correct: forall (pid1 pid2: Z) (adt: RData),\n                                                    ll_shared_mem_status_spec pid1 pid2 adt =\n                                                    shared_mem_status_spec pid1 pid2 adt.\n        Proof.\n          intros.\n          unfold ll_shared_mem_status_spec, shared_mem_status_spec.\n          unfold get_shared_mem_status_seen_spec.\n          destruct (ikern adt), (ihost adt), (pg adt), (ipt adt), (shared_mem_arg pid1 pid2); try trivial.\n          destruct (ZMap.get pid2 (ZMap.get pid1 (smspool adt))); try trivial.\n          destruct seen; try trivial.\n          destruct (ZMap.get pid1 (ZMap.get pid2 (smspool adt))); try trivial.\n          destruct (SharedMemInfo_dec info0 SHRDPEND); try trivial.\n        Qed.\n\n        Lemma shared_mem_status__correct: forall m d d' (z: Z) env le pid1 pid2 n,\n                                      env = PTree.empty _ ->\n                                      PTree.get _source le = Some (Vint pid1) ->\n                                      PTree.get _dest le = Some (Vint pid2) ->\n                                      (*pg d = true ->*)\n                                      shared_mem_status_spec (Int.unsigned pid1) (Int.unsigned pid2) d\n                                      = Some (d', Int.unsigned n) ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_status_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          intros.\n          rewrite <- ll_shared_mem_status_spec__correct in H2.\n          apply ll_shared_mem_status__correct with pid1 pid2; auto.\n        Qed.\n\n      End SharedMemStatusBody.\n\n      Theorem shared_mem_status_code_correct:\n        spec_le (shared_mem_status \u21a6 shared_mem_status_spec_low) (\u301ashared_mem_status \u21a6 f_shared_mem_status \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (shared_mem_status__correct s (Genv.globalenv p) makeglobalenv\n                                             b2 Hb2fs Hb2fp\n                                             b1 Hb1fs Hb1fp\n                                             b0 Hb0fs Hb0fp\n                                             b3 Hb3fs Hb3fp\n                                             m'0 labd labd'\n                                             (Int.unsigned n)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_shared_mem_status)\n                                                                    (Vint pid1 :: Vint pid2 :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_shared_mem_status))))\n                 H0.\n      Qed.\n\n    End SHAREDMEMSTATUS.\n\n\n    (**************************************)\n\n    Section OFFERSHAREDMEM.\n\n      Let resv2_sem := pt_resv2 \u21a6 gensem ptResv2_spec.\n\n      Let L: compatlayer (cdata RData) := \n          resv2_sem\n        (*\u2295 container_alloc \u21a6 gensem alloc_spec*)\n        \u2295 shared_mem_to_ready \u21a6 gensem shared_mem_to_ready_spec\n        \u2295 shared_mem_to_pending \u21a6 gensem shared_mem_to_pending_spec\n        \u2295 shared_mem_to_dead \u21a6 gensem shared_mem_to_dead_spec\n        \u2295 get_shared_mem_state \u21a6 gensem get_shared_mem_state_spec.\n\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section OfferSharedMemBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n\n        (**)\n\n        Variable bpt_resv2: block.\n\n        Hypothesis hpt_resv21 : Genv.find_symbol ge pt_resv2 = Some bpt_resv2.\n\n        Hypothesis hpt_resv22 : Genv.find_funct_ptr ge bpt_resv2 =\n                      Some (External (EF_external pt_resv2 (signature_of_type\n(Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))))) tint cc_default))\n(Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))))) tint cc_default).\n\n\n        (**)\n\n        Variable bshared_mem_to_ready: block.\n\n        Hypothesis hshared_mem_to_ready1 : Genv.find_symbol ge shared_mem_to_ready = Some bshared_mem_to_ready.\n\n        Hypothesis hshared_mem_to_ready2 : Genv.find_funct_ptr ge bshared_mem_to_ready =\n                      Some (External (EF_external shared_mem_to_ready (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) tint cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) tint cc_default).\n\n\n        (**)\n\n        Variable bshared_mem_to_dead: block.\n\n        Hypothesis hshared_mem_to_dead1 : Genv.find_symbol ge shared_mem_to_dead = Some bshared_mem_to_dead.\n\n        Hypothesis hshared_mem_to_dead2 : \n          Genv.find_funct_ptr ge bshared_mem_to_dead =\n          Some (External (EF_external shared_mem_to_dead\n                                      (signature_of_type\n                                         (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default))\n                         (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n        (**)\n\n        Variable bshared_mem_to_pending: block.\n\n        Hypothesis hshared_mem_to_pending1 : Genv.find_symbol ge shared_mem_to_pending = Some bshared_mem_to_pending.\n\n        Hypothesis hshared_mem_to_pending2 :\n          Genv.find_funct_ptr ge bshared_mem_to_pending =\n          Some (External (EF_external shared_mem_to_pending\n                                      (signature_of_type\n                                         (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default))\n                         (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n\n        (**)\n\n        Variable bget_shared_mem_state: block.\n\n        Hypothesis hget_shared_mem_state1 : Genv.find_symbol ge get_shared_mem_state = Some bget_shared_mem_state.\n\n        Hypothesis hget_shared_mem_state2 : Genv.find_funct_ptr ge bget_shared_mem_state =\n                                            Some (External (EF_external get_shared_mem_state (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (**)\n\n        Require Import CommonTactic.\n\n        Lemma ptInsert0_presv:\n          forall pid1 vadr b v d adt n,\n            ptInsert0_spec pid1 vadr b v d = Some (adt, n)\n            -> pg adt = true /\\ ipt adt = true\n               /\\ smspool adt = smspool d /\\ ikern adt = true /\\ ihost adt = true.\n        Proof.\n          intros. functional inversion H; subst.\n          - functional inversion H9; simpl; eauto.\n          - functional inversion H9; simpl; eauto.\n          - functional inversion H9; simpl; eauto 2;\n            functional inversion H11; simpl; eauto 2.\n            + rewrite <- H19, <- H0 in *. simpl in *.\n              refine_split'; try congruence.\n            + rewrite <- H20, <- H0 in *. simpl in *.\n              refine_split'; try congruence.\n        Qed.\n\n        Lemma ptResv2_presv_pg_idt': forall pid1 pid2 d vadr vadr' adt n v v',\n                                ptResv2_spec pid1 vadr v pid2 vadr' v' d = Some (adt, n)\n                                -> pg adt = true /\\ ipt adt = true\n                                   /\\ smspool adt = smspool d /\\ ikern adt = true /\\ ihost adt = true.\n        Proof.\n          intros. functional inversion H; subst.\n          - functional inversion H2; subst; eauto.\n          - functional inversion H2; subst; eauto.\n            + eapply ptInsert0_presv in H4. assumption.\n            + eapply ptInsert0_presv; eauto.\n          - functional inversion H1; subst; eauto.\n            + eapply ptInsert0_presv in H0. \n              eapply ptInsert0_presv in H3. simpl in *.\n              destruct H0 as (HE1 & HE2 & HE3 & HE4 & H6).\n              destruct H3 as ( _ & _ & HE5 & _ & _).\n              refine_split'; eauto. congruence.\n            + eapply ptInsert0_presv in H0. \n              eapply ptInsert0_presv in H3. simpl in *.\n              destruct H0 as (HE1 & HE2 & HE3 & Hk & Hh).\n              destruct H3 as ( _ & _ & HE5 & _ & _).\n              refine_split'; eauto. congruence.\n        Qed.\n\n        Hypothesis smspool_vadr_valid: forall pid1 pid2 d vadr i s,\n                                      shared_mem_arg (Int.unsigned pid1)\n                                                     (Int.unsigned pid2) = true ->\n                                      ZMap.get (Int.unsigned pid1)\n                                               (ZMap.get (Int.unsigned pid2) (smspool d)) =\n                                          SHRDValid i s vadr ->\n                                      vadr = Int.unsigned (Int.repr vadr).\n\n        Lemma ptResv2_presv_pg: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> pg adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_ipt: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> ipt adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_ikern: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> ikern adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c & r & e).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_ihost: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> ihost adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c & r & e).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_smspool: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> smspool adt = smspool d.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c & r & e).\n          assumption.\n        Qed.\n\n\n  (*Function ll_offer_shared_mem_spec (pid1 pid2 vadr: Z) (adt: RData) : option (RData * Z) :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid st _ _ => \n            if SharedMemInfo_dec st SHRDPEND then Some (adt, SHARED_MEM_PEND)\n            else\n              match ZMap.get pid1 (ZMap.get pid2 (smspool adt)) with\n                | SHRDValid st' _ vadr' => \n                  if SharedMemInfo_dec st' SHRDPEND then\n                    match shared_mem_to_ready_spec pid1 pid2 vadr adt with\n                      | Some (adt', re) =>\n                        if zeq re MagicNumber\n                        then match shared_mem_to_dead_spec pid1 pid2 vadr adt' with\n                                 | Some adt'' => Some (adt'', SHARED_MEM_DEAD)\n                                 | _ => None\n                             end\n                        else Some (adt', SHARED_MEM_READY)\n                      | _ => None\n                    end\n                  else match shared_mem_to_pending_spec pid1 pid2 vadr adt with\n                                 | Some adt'' => Some (adt'', SHARED_MEM_PEND)\n                                 | _ => None\n                       end\n                | _ => None\n              end\n          | _ => None\n        end\n      | _ => None\n    end.*)\n        Lemma ll_offer_shared_mem_spec__correct: forall (pid1 pid2 vadr: Z) (adt: RData),\n                                      ll_offer_shared_mem_spec pid1 pid2 vadr adt =\n                                      offer_shared_mem_spec pid1 pid2 vadr adt.\n        Proof.\n          intros.\n          unfold ll_offer_shared_mem_spec, offer_shared_mem_spec.\n          unfold shared_mem_to_ready_spec, shared_mem_to_dead_spec, shared_mem_to_pending_spec.\n          destruct (ikern adt), (ihost adt), (pg adt), (ipt adt), (shared_mem_arg pid1 pid2); try trivial.\n          destruct (ZMap.get pid2 (ZMap.get pid1 (smspool adt))) eqn:M21; try trivial.\n          destruct (SharedMemInfo_dec info SHRDPEND); try trivial.\n          destruct (ZMap.get pid1 (ZMap.get pid2 (smspool adt))) eqn:M12; try trivial.\n          destruct (zle_lt 0 vadr1 4294967296) as [x | x]; try trivial.\n          destruct (SharedMemInfo_dec info0 SHRDPEND); try trivial.\n          destruct (ptResv2_spec pid1 vadr 7 pid2 vadr1 7 adt) eqn:resq; try trivial.\n          destruct p. destruct (zeq z MagicNumber) eqn:zeq; try trivial.\n            - simpl.\n              destruct (ptResv2_presv_pg_idt' pid1 pid2 adt vadr vadr1 r z 7 7 resq) as (a & b & c & q & t).\n              cutrewrite (ikern r = true).\n              cutrewrite (ihost r = true).\n              cutrewrite (pg r = true).\n              cutrewrite (ipt r = true).\n              cutrewrite (smspool r = smspool adt).\n              rewrite M21, M12. reflexivity.\n              assumption. assumption. assumption. assumption. assumption.\n            - destruct (Coqlib.zeq z MagicNumber). discriminate zeq.\n              simpl. reflexivity.   \n         Qed.\n\n\n        Require Import AuxLemma.\n\n        Lemma ptInsert0_range:\n          forall p1 p2 v d d' re n,\n            ptInsert0_spec p1 p2 v n d = Some (d', re) ->\n            262144 <= nps d <= 1048576 ->\n            0 <= re <= Int.max_unsigned.\n        Proof.\n          intros. rewrite_omega.\n          functional inversion H; subst; try omega.\n          functional inversion H10; try subst; try omega.\n        Qed.\n\n        Lemma ptInsert0_range':\n          forall p1 p2 v d d' re n,\n            ptInsert0_spec p1 p2 v n d = Some (d', re) ->\n            262144 <= nps d <= 1048576 ->\n            262144 <= nps d' <= 1048576.\n        Proof.\n          intros. \n          functional inversion H; subst;\n          functional inversion H10; try subst; try subst d'; trivial;\n          try rewrite H1 in *; trivial;\n          functional inversion H12; trivial.\n        Qed.\n\n        Lemma shared_mem_to_ready_range:\n          forall p1 p2 v d d' re,\n            shared_mem_to_ready_spec p1 p2 v d = Some (d', re) ->\n            262144 <= nps d <= 1048576 ->\n            0 <= re <= Int.max_unsigned.\n        Proof.\n          intros. rewrite_omega.\n          functional inversion H; clear H; [omega|].\n          functional inversion H11; clear H11; subst; try omega.\n          eapply ptInsert0_range; eauto.\n          eapply ptInsert0_range'; eauto.\n          functional inversion H13; clear H13; subst; trivial.\n        Qed.\n\n        Lemma ll_offer_shared_mem__correct: forall m d d' (z: Z) env le pid1 pid2 vadr n,\n                                      env = PTree.empty _ ->\n                                      PTree.get _source le = Some (Vint pid1) ->\n                                      PTree.get _dest le = Some (Vint pid2) ->\n                                      PTree.get _source_va le = Some (Vint vadr) ->\n                                      (*pg d = true ->*)\n                                      ll_offer_shared_mem_spec (Int.unsigned pid1) (Int.unsigned pid2) (Int.unsigned vadr) d = Some (d', Int.unsigned n) ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) offer_shared_mem_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          intros. subst.\n          inversion H5.\n          functional inversion H4; subst.\n            - esplit.\n              unfold exec_stmt.\n              change E0 with (E0 ** E0).\n              repeat vcgen.\n                + unfold get_shared_mem_state_spec.\n                  rewrite H8, H9, H10, H11, H7.\n                  rewrite H12.\n                  simpl.\n                  cutrewrite (1 = Int.unsigned (Int.repr 1));\n                    reflexivity.\n                + simpl. destruct (zeq (Int.unsigned (Int.repr 1)) 1). reflexivity.\n                  contradiction n0. reflexivity.\n                + repeat vcgen.\n                + rewrite PTree.gss. rewrite H6, Int.repr_unsigned. reflexivity.\n            - esplit;\n              unfold exec_stmt;\n              change E0 with (E0 ** E0);\n              repeat vcgen.\n                + unfold get_shared_mem_state_spec.\n                  rewrite H8, H9, H10, H11, H7.\n                  rewrite H12.\n                  simpl.\n                  rewrite SharedMemInfo2Z_valid.\n                  reflexivity.\n                + destruct (zeq (Int.unsigned (Int.repr (SharedMemInfo2Z st))) 1).\n                    * rewrite <- SharedMemInfo2Z_valid in e.\n                      functional inversion e.\n                      clear H13. rewrite <- H20 in _x1.\n                      apply False_rect; auto.\n                    * repeat vcgen.\n                + repeat vcgen.\n                    * unfold get_shared_mem_state_spec.\n                      rewrite shared_mem_arg_rev.\n                      rewrite H8, H9, H10, H11, H7.\n                      rewrite H14. rewrite SharedMemInfo2Z_valid.\n                      reflexivity.\n                    * repeat vcgen.\n                    * repeat vcgen.\n                + rewrite PTree.gss, H6, Int.repr_unsigned. trivial.\n            - esplit;\n              unfold exec_stmt;\n              change E0 with (E0 ** E0);\n              repeat vcgen.\n                + unfold get_shared_mem_state_spec.\n                  rewrite H8, H9, H10, H11, H7.\n                  rewrite H12.\n                  simpl.\n                  rewrite SharedMemInfo2Z_valid.\n                  reflexivity.\n                + destruct (zeq (Int.unsigned (Int.repr (SharedMemInfo2Z st))) 1).\n                    * rewrite <- SharedMemInfo2Z_valid in e.\n                      functional inversion e.\n                      clear H13. rewrite <- H19 in _x1.\n                      apply False_rect; auto.\n                    * repeat vcgen.\n                + assert (re_range: 0 <= re <= Int.max_unsigned). {\n                    eapply shared_mem_to_ready_range; eauto.\n                  } \n                  repeat vcgen.\n                  * unfold get_shared_mem_state_spec.\n                    rewrite shared_mem_arg_rev.\n                    rewrite H8, H9, H10, H11, H7.\n                    rewrite H14. rewrite SharedMemInfo2Z_valid.\n                    reflexivity.\n                  * repeat vcgen.\n                  * repeat vcgen. \n                + rewrite PTree.gss, H6, Int.repr_unsigned. trivial.\n            - esplit.\n              unfold exec_stmt.\n              change E0 with (E0 ** E0).\n              repeat vcgen.\n              + unfold get_shared_mem_state_spec.\n                rewrite H8, H9, H10, H11, H7.\n                rewrite H12.\n                simpl.\n                rewrite SharedMemInfo2Z_valid.\n                reflexivity.\n              + destruct (zeq (Int.unsigned (Int.repr (SharedMemInfo2Z st))) 1).\n                * rewrite <- SharedMemInfo2Z_valid in e.\n                  functional inversion e.\n                  clear H13. rewrite <- H18 in _x1.\n                  apply False_rect; auto.\n                * repeat vcgen.\n              + repeat vcgen.\n                * unfold get_shared_mem_state_spec.\n                  rewrite shared_mem_arg_rev.\n                  rewrite H8, H9, H10, H11, H7.\n                  rewrite H14. rewrite SharedMemInfo2Z_valid.\n                  reflexivity.\n                * destruct (zeq (Int.unsigned (Int.repr (SharedMemInfo2Z st'))) 1). \n                  {\n                    rewrite <- SharedMemInfo2Z_valid in e.\n                    functional inversion e.\n                    clear H16. rewrite <- H18 in _x4.\n                    apply False_rect; auto.\n                  }\n                  repeat vcgen.\n                * repeat vcgen.\n              + rewrite PTree.gss, H6, Int.repr_unsigned. trivial.\n        Qed.\n\n        Lemma offer_shared_mem__correct: forall m d d' (z: Z) env le pid1 pid2 vadr n,\n                                      env = PTree.empty _ ->\n                                      PTree.get _source le = Some (Vint pid1) ->\n                                      PTree.get _dest le = Some (Vint pid2) ->\n                                      PTree.get _source_va le = Some (Vint vadr) ->\n                                      (*pg d = true ->*)\n                                      offer_shared_mem_spec (Int.unsigned pid1) (Int.unsigned pid2) (Int.unsigned vadr) d = Some (d', Int.unsigned n) ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) offer_shared_mem_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          intros.\n          rewrite <- ll_offer_shared_mem_spec__correct in H3.\n          apply ll_offer_shared_mem__correct with pid1 pid2 vadr; auto.\n        Qed.\n\n      End OfferSharedMemBody.\n\n      Theorem offer_shared_mem_code_correct:\n        spec_le (offer_shared_mem \u21a6 offer_shared_mem_spec_low) (\u301aoffer_shared_mem \u21a6 f_offer_shared_mem \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (offer_shared_mem__correct s (Genv.globalenv p) makeglobalenv\n                                             b0 Hb0fs Hb0fp\n                                             b2 Hb2fs Hb2fp\n                                             b1 Hb1fs Hb1fp\n                                             b3 Hb3fs Hb3fp\n                                             m'0 labd labd'\n                                             (Int.unsigned n)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_offer_shared_mem)\n                                                                    (Vint pid1 :: Vint pid2 :: Vint vadr :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_offer_shared_mem))))\n                 H0.\n      Qed.\n\n    End OFFERSHAREDMEM.\n\n  End WithPrimitives.\n\nEnd MSHARECODE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MShareOpCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.18809832131705043}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import LogicalRelations.\nRequire Import SimulationRelation.\nRequire Import Structures.\nRequire Import OptionOrders.\nRequire Import compcert.lib.Floats.\nRequire Import compcert.common.Values.\nLocal Opaque mwd_ops.\n\n(** * [lessdef] (and [Mem.extends]) as a simulation relation *)\n\nSection LESSDEF_SIMREL.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D: layerdata}.\n\n  Definition simrel_lessdef_ops: simrel_components D D :=\n    {|\n      simrel_world := unit;\n      simrel_acc := {| Structures.le x y := True |};\n      simrel_undef_matches_values_bool := true;\n      simrel_undef_matches_block p b := True;\n      simrel_new_glbl := nil;\n      simrel_meminj p := inject_id;\n      match_mem p := Mem.extends\n    |}.\n\n  Require Import ExtensionalityAxioms.\n\n  Lemma match_ptr_simrel_lessdef p:\n    match_ptr simrel_lessdef_ops p = eq.\n  Proof.\n    eapply functional_extensionality; intros [b1 o1].\n    eapply functional_extensionality; intros [b2 o2].\n    eapply prop_ext.\n    split.\n    - destruct 1; simpl in *; subst; try constructor.\n      inversion H; subst.\n      f_equal.\n      omega.\n    - destruct 1.\n      apply match_block_sameofs_ptr; auto.\n      reflexivity.\n  Qed.\n\n  Lemma match_ptrbits_simrel_lessdef p:\n    match_ptrbits simrel_lessdef_ops p = eq.\n  Proof.\n    eapply functional_extensionality; intros [b1 o1].\n    eapply functional_extensionality; intros [b2 o2].\n    eapply prop_ext.\n    split.\n    - destruct 1; simpl in *; subst; try constructor.\n      inversion H; subst.\n      rewrite Ptrofs.add_zero.\n      reflexivity.\n    - destruct 1.\n      apply match_block_sameofs_ptrbits; auto.\n      reflexivity.\n  Qed.\n\n  Lemma match_ptrrange_simrel_lessdef p:\n    match_ptrrange simrel_lessdef_ops p = eq.\n  Proof.\n    eapply functional_extensionality; intros [[b1 lo1] hi1].\n    eapply functional_extensionality; intros [[b2 lo2] hi2].\n    eapply prop_ext.\n    split.\n    - destruct 1.\n      inversion H; simpl in *.\n      inversion H1; simpl in *.\n      rewrite Z.add_0_r.\n      reflexivity.\n    - inversion 1; subst.\n      replace hi2 with (lo2 + (hi2 - lo2)) by omega.\n      constructor.\n      pattern lo2 at 2.\n      replace lo2 with (lo2 + 0) by omega.\n      constructor.\n      reflexivity.\n  Qed.\n\n  Lemma match_block_simrel_lessdef p:\n    match_block simrel_lessdef_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - intros b1 b2 [delta Hdelta].\n      inversion Hdelta.\n      reflexivity.\n    - intros b1 b2 H; subst.\n      eexists.\n      reflexivity.\n  Qed.\n\n  Lemma match_block_sameofs_simrel_lessdef p:\n    match_block_sameofs simrel_lessdef_ops p = eq.\n  Proof.\n    apply eqrel_eq; split.\n    - intros b1 b2 Hb.\n      inversion Hb.\n      reflexivity.\n    - intros b1 b2 H; subst.\n      constructor.\n  Qed.\n\n  Lemma match_val_simrel_lessdef p:\n    match_val simrel_lessdef_ops p = Val.lessdef.\n  Proof.\n    eapply functional_extensionality; intro v1.\n    eapply functional_extensionality; intro v2.\n    eapply prop_ext.\n    split.\n    - destruct 1; simpl in *; subst; try constructor.\n      rewrite match_ptrbits_simrel_lessdef in H.\n      inversion H; subst.\n      reflexivity.\n    - destruct 1.\n      + destruct v; try constructor.\n        rewrite match_ptrbits_simrel_lessdef.\n        reflexivity.\n      + destruct v; constructor; constructor.\n  Qed.\n\n  Lemma match_memval_simrel_lessdef p:\n    match_memval simrel_lessdef_ops p = memval_lessdef.\n  Proof.\n    eapply functional_extensionality; intro v1.\n    eapply functional_extensionality; intro v2.\n    eapply prop_ext.\n    split.\n    - destruct 1; simpl in *; subst; try constructor.\n      destruct H; try constructor.\n      inversion H; subst.\n      inversion H1; subst.\n      econstructor.      \n      reflexivity.\n      reflexivity.\n    - destruct 1.\n      + constructor.\n      + constructor.\n        rewrite match_val_simrel_lessdef.\n        destruct H; try constructor; eauto.\n        inversion H; clear H; subst.\n        rewrite Ptrofs.add_zero.\n        reflexivity.\n      + destruct mv; constructor; try constructor.\n        rewrite match_val_simrel_lessdef.\n        constructor.\n  Qed.\n\n  (** Initial memory *)\n\n  Require Import InitMemRel.\n\n  Lemma store_zeros_right_extends:\n    forall (m2: mwd D) b lo hi m2',\n      store_zeros m2 b lo hi = Some m2' ->\n      forall m1, Mem.extends m1 m2 ->\n                 (forall o k p, Mem.perm m1 b o k p -> False) ->\n                 Mem.extends m1 m2'.\n  Proof.\n    intros until hi.\n    functional induction (store_zeros m2 b lo hi); try congruence.\n    intros. eapply IHo; eauto using (Mem.store_outside_extends (mem := mwd D)).\n  Qed.\n\n(* XXX: coqrel *)\n\nGlobal Instance prod_rel_fst {A1 A2 B1 B2} (RA: rel A1 A2) (RB: rel B1 B2):\n  Related (prod_rel RA RB) (RA @@ fst)%rel subrel.\nProof.\n  clear.\n  firstorder.\nQed.\n\nGlobal Instance prod_rel_snd {A1 A2 B1 B2} (RA: rel A1 A2) (RB: rel B1 B2):\n  Related (prod_rel RA RB) (RB @@ snd)%rel subrel.\nProof.\n  clear.\n  firstorder.\nQed.\n\nGlobal Instance option_ifsome_le_subrel {A B} (R: rel A B):\n  Related (option_le R) (option_ifsome_rel R) subrel.\nProof.\n  destruct 1; red; congruence.\nQed.\n\nGlobal Instance: Params (@Mem.drop_perm) 5.\n\n  Global Instance simrel_lessdef_init_mem {F1 F2 V} ng umv:\n    InitMemSimrel (D1:=D) (D2:=D) (F1:=F1) (F2:=F2) (V:=V)\n      ng umv\n      (fun _ _ _ _ => Mem.extends).\n  Proof.\n    assert (forall i, simrel_newfun_ok nil true i).\n    {\n      intros i.\n      split; reflexivity.\n    }\n    assert (forall i init, simrel_newvar_ok nil true i init).\n    {\n      intros i init.\n      right.\n      split; reflexivity.\n    }\n    split; intros.\n    - apply Mem.extends_refl.\n    - intros m1 m2 Hm.\n      unfold alloc_none.\n      destruct (Mem.alloc m1 _ _) as [m1' b] eqn:Hm1'.\n      edestruct (Mem.alloc_extends m1 m2) as (m2' & Hm2' & Hm'); eauto.\n      + reflexivity.\n      + reflexivity.\n      + rewrite Hm2'.\n        constructor.\n        eauto.\n    - intros m1 m2 Hm.\n      unfold alloc_none, alloc_fun.\n      destruct (Mem.alloc m1 _ _) as [m1' b] eqn:Hm1'.\n      edestruct (Mem.alloc_extends m1 m2) as (m2' & Hm2' & Hm'); eauto.\n      + reflexivity.\n      + instantiate (1:=1).\n        omega.\n      + rewrite Hm2'.\n        edestruct (Mem.range_perm_drop_2 m2' b 0 1 Nonempty) as [m2'' Hm2''].\n        {\n          intros ofs Hofs.\n          eapply Mem.perm_alloc_2; eauto.\n        }\n        rewrite Hm2''.\n        constructor.\n        eapply Mem.drop_perm_right_extends; eauto.\n        intros ofs k p Hp Hofs.\n        eapply Mem.perm_alloc_3 in Hp; eauto.\n        omega.\n    - split.\n      + assumption.\n      + intros sz Hsz m1 m2 Hm.\n        destruct (Mem.alloc m1 _ _) as [m1' b1] eqn:Hm1'; simpl.\n        edestruct (Mem.alloc_extends m1 m2) as (m2' & Hm2' & Hm');\n        rewrite ?Hm2'; eauto.\n        * reflexivity.\n        * subst.\n          apply genv_init_data_list_size_pos.\n      + intros p sz m1 m2 m2' Hsz Hm1 Hm2' Hm.\n        eapply Mem.store_outside_extends; eauto.\n        intros ofs Hofs _.\n        eapply Hm1; eauto.\n      + intros sz ge1 ge2 base next m1 m2 m2' Hsz Hm1 Hge Hm2' Hm.\n        eapply Genv.store_init_data_right_extends; eauto.\n        intros.\n        eapply Hm1; eauto.\n      + intros sz m1 m2 m2' Hsz Hm1 Hm2' Hm.\n        eapply Mem.drop_perm_right_extends; eauto.\n        intros.\n        eapply Hm1; eauto.\n    - intros m1 m2 Hm.\n      unfold alloc_fun.\n      destruct (Mem.alloc m1 _ _) as [m1' b1] eqn:Hm1'.\n      transport Hm1'.\n      rewrite H1; subst.\n      solve_monotonic.\n    - split.\n      + reflexivity.\n      + intros.\n        solve_monotonic.\n      + intros.\n        solve_monotonic.\n      + intros sz base next Hsz ge1 ge2 Hge m1 m2 Hm m1' m2' Hm1' Hm2'.\n        edestruct (Genv.store_init_data_parallel_extends (mem := mwd D) ge1) as (?&?&?); eauto.\n        erewrite (Genv.store_init_data_symbols_preserved ge1 ge2) in Hm2'.\n        congruence.\n        intro.\n        rewrite !stencil_matches_symbols by eauto.\n        reflexivity.\n      + unfold alloc_var_perm.\n        intros.\n        solve_monotonic.\n  Qed.\n\n  Global Instance simrel_lessdef_prf:\n    SimulationRelation simrel_lessdef_ops.\n  Proof.\n    assert (Heqsub: forall A B, subrel (@eqrel A B) (@subrel A B)).\n    {\n      intros A B x y H.\n      repeat red in H.\n      tauto.\n    }\n    constructor; try now repeat constructor.\n\n    (** [Genv.init_mem] *)\n    - intros.\n      eapply genv_init_mem_simrel.\n      + typeclasses eauto.\n      + simpl.\n        intros m1 m2 Hm.\n        exists tt; solve_monotonic.\n\n    (** [Mem.alloc] *)\n    - exists tt.\n      split; simpl; eauto.\n      destruct (Mem.alloc x _ _) eqn:Halloc1.\n      simpl in H.\n      edestruct (Mem.alloc_extends x) as (? & Halloc2 & ?); eauto; try reflexivity.\n      rewrite Halloc2.\n      constructor; eauto.\n      reflexivity.\n\n    (** [Mem.free] *)\n    - repeat red.\n      simpl.\n      inversion 2; subst.\n      rewrite match_ptr_simrel_lessdef in H1.\n      inversion H1; subst.\n      simpl.\n      destruct (Mem.free x _ _ _) eqn:Hfree1; try constructor.\n      edestruct (Mem.free_parallel_extends x) as (? & Hfree2 & ?); eauto.\n      rewrite Hfree2.\n      constructor.\n      exists p; eauto.\n\n    (** [Mem.load] *)\n    - intro p.\n      rewrite match_val_simrel_lessdef.\n      rewrite match_ptr_simrel_lessdef.\n      simpl.\n      repeat red.\n      intros a x y H x0 y0 H0.\n      subst.\n      destruct y0.\n      simpl.\n      destruct (Mem.load _ x _ _) eqn:Hload; try constructor.\n      edestruct (Mem.load_extends a x) as (? & Hload2 & ?); eauto.\n      rewrite Hload2.\n      constructor; assumption.\n\n    (** [Mem.store] *)\n    - intro p.\n      rewrite match_val_simrel_lessdef.\n      rewrite match_ptr_simrel_lessdef.\n      simpl.\n      repeat red.\n      intros a x y H x0 y0 H0 x1 y1 H1.\n      subst.\n      destruct y0.\n      simpl.\n      destruct (Mem.store _ x _ _ _) eqn:Hstore1; try constructor.\n      edestruct (Mem.store_within_extends a x) as (? & Hstore2 & ?); eauto.\n      rewrite Hstore2.\n      constructor.\n      exists p; eauto.\n\n    (** [Mem.loadbytes] *)\n    - intro p.\n      rewrite match_memval_simrel_lessdef.\n      rewrite match_ptr_simrel_lessdef.\n      repeat red.\n      intros x y H x0 y0 H0 a.\n      subst.\n      destruct y0.\n      simpl in *.\n      destruct (Mem.loadbytes x _ _ _) eqn:Hlb1; try constructor.\n      edestruct (Mem.loadbytes_extends x) as (? & Hlb2 & ?); eauto.\n      rewrite Hlb2.\n      constructor.\n      rewrite <- CompcertStructures.list_forall2_list_rel; assumption.\n\n    (** [Mem.storebytes] *)\n    - intro p.\n      rewrite match_memval_simrel_lessdef.\n      rewrite match_ptr_simrel_lessdef.\n      repeat red.\n      intros x y H x0 y0 H0 x1 y1 H1.\n      subst.\n      destruct y0.\n      simpl in *.\n      destruct (Mem.storebytes x _ _ _) eqn:Hsb1; try constructor.\n      edestruct (Mem.storebytes_within_extends x) as (? & Hsb2 & ?); eauto.\n      { rewrite CompcertStructures.list_forall2_list_rel; eassumption. }\n      rewrite Hsb2.\n      constructor.\n      exists p; eauto.\n\n    (** [Mem.perm] *)\n    - intros p.\n      rewrite match_ptr_simrel_lessdef.\n      repeat red.\n      intros x y H x0 y0 H0 a a0 H1.\n      subst.\n      destruct y0.\n      simpl in *.\n      eapply Mem.perm_extends; eauto.\n\n    (** [Mem.valid_block] *)\n    - intros p.\n      rewrite match_block_simrel_lessdef.\n      simpl.\n      intros m1 m2 Hm b1 b2 Hb; subst.\n      eapply Mem.valid_block_extends; eauto.\n\n    (** [Mem.different_pointers_inject] *)\n    - inversion 5; subst.\n      inversion 1; subst.\n      tauto.\n\n    (** [Mem.weak_valid_pointer_inject_val] *)\n    - intros p m1 m2 b1 ofs1 b2 ofs2 H H0 H1.\n      rewrite match_ptrbits_simrel_lessdef in H1.\n      inversion H1; clear H1; subst.\n      eapply Mem.weak_valid_pointer_extends; eauto.\n\n    (** [Mem.weak_valid_pointer_address_inject_weak] *)\n    - intros p m1 m2 b1 b2 delta H H0.\n      inversion H0; clear H0; subst.\n      exists 0.\n      intros ofs1 H0.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    (** [Mem.address_inject *)\n    - simpl.\n      inversion 4; subst.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    (** [Mem.aligned_area_inject] *)\n    - simpl.\n      inversion 8; subst.\n      rewrite Z.add_0_r.\n      assumption.\n\n    (** [Mem.disjoint_or_equal_inject] *)\n    - simpl.\n      inversion 3; subst.\n      inversion 1; subst.\n      repeat rewrite Z.add_0_r.\n      tauto.\n  Qed.\n\n  Definition ext :=\n    {|\n      simrel_ops := simrel_lessdef_ops\n    |}.\nEnd LESSDEF_SIMREL.\n\n(* Memory extension is absorbed by any other simulation relation\n   with Vundef/Undef as lower bounds. *)\n\nSection EXTENDS_COMPOSE.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D1 D2} (R: simrel D1 D2).\n\n  Program  (* improves type checking. *)\n  Definition equiv_extends_compose_left:\n    simrel_equiv_maps (simrel_compose (ext (D:=D1)) R) R\n    :=\n      {|\n        simrel_equiv_fw := snd;\n        simrel_equiv_bw q := (tt, q)\n      |}.\n\n  Program  (* improves type checking. *)\n  Definition equiv_extends_compose_right:\n    simrel_equiv_maps (simrel_compose R (ext (D:=D2))) R\n    :=\n      {|\n        simrel_equiv_fw := fst;\n        simrel_equiv_bw q := (q, tt)\n      |}.\n\n  Hypothesis undef_values:\n    simrel_undef_matches_values R.\n\n  Section LEFT.\n\n    Hypothesis undef_block:\n      forall p b,\n        (exists b' : block, match_block R p b' b) ->\n        simrel_undef_matches_block R p b.\n\n    Hypothesis compose_left:\n      forall p m1 m2 m3,\n        Mem.extends m1 m2 ->\n        match_mem R p m2 m3 ->\n        match_mem R p m1 m3.\n\n    Theorem extends_compose_left:\n      SimulationRelationEquivalence _ _ equiv_extends_compose_left.\n    Proof.\n      constructor; simpl; auto; try tauto; try (compute; tauto).\n      + intros p.\n        intro b.\n        destruct 1 as [ [ ? [ ? ? ] ] | ] ; eauto.\n      + intros p.\n        intros m1 m3 (m2 & Hm1 & Hm2). eauto.\n      + intros p m1 m2 Hm.\n        exists m1; split; auto. apply Mem.extends_refl.\n      + intros p b. unfold compose_meminj, inject_id.\n        destruct (simrel_meminj R (snd p) b) as [ [ ? ? ] | ] ; constructor; auto.\n      + intros p b.\n        unfold compose_meminj, inject_id.\n        destruct (simrel_meminj R p b) as [ [ ? ? ] | ] ; constructor; auto.\n      + intros [u p]. split; simpl; auto. reflexivity.\n      + intros p. reflexivity.\n    Qed.\n\n  End LEFT.\n\n  Section RIGHT.\n\n    Hypothesis undef_block:\n      forall p b,\n        simrel_undef_matches_block R p b.\n\n    Hypothesis compose_right:\n      forall p m1 m2 m3,\n        match_mem R p m1 m2 ->\n        Mem.extends m2 m3 ->\n        match_mem R p m1 m3.\n\n    Theorem extends_compose_right:\n      SimulationRelationEquivalence _ _ equiv_extends_compose_right.\n    Proof.\n      constructor; simpl; auto; try tauto; try (compute; tauto).\n      + red in undef_values.\n        rewrite undef_values.\n        reflexivity.\n      + symmetry; apply app_nil_end.\n      + intros p b. intro H. apply undef_block.\n      + intros p m1 m3 (m2 & Hm12 & Hm23). eauto.\n      + intros p m1 m2 Hm12.\n        exists m2; split; auto.\n        apply Mem.extends_refl.\n      + intros p b.\n        unfold compose_meminj, inject_id.\n        destruct (simrel_meminj R (fst p) b) as [ [ ? ? ] | ] ; constructor; auto.\n        rewrite Z.add_0_r; reflexivity.\n      + intros p b. unfold compose_meminj, inject_id.\n        destruct (simrel_meminj R p b) as [ [ ? ? ] | ] ; constructor; auto.\n        rewrite Z.add_0_r; reflexivity.\n      + intros [u p]; split; simpl; reflexivity.\n      + intros p; simpl; reflexivity.\n    Qed.\n\n  End RIGHT.\n\nEnd EXTENDS_COMPOSE.\n\n(* As an application, memory extension is idempotent. *)\n\nSection EXTENDS_IDEM.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D: layerdata}.\n\n  Global Instance extends_compose:\n    SimulationRelationEquivalence _ _ (equiv_extends_compose_right (ext (D:=D))).\n  Proof.\n    apply extends_compose_right; simpl; auto.\n    - reflexivity.\n    - intro.\n      apply Mem.extends_extends_compose.\n  Qed.\nEnd EXTENDS_IDEM.\n\n\n(** * Strong version of extends for [ec_mem_extends]. Coincidentally,\n      it will also work for [ec_max_perm] and [ec_valid_block] (which\n      are necessary for Mem.unchanged_on to work).\n      To factor proofs, we enrich it with [ec_readonly].\n *)\n\nSection STRONG_LESSDEF_SIMREL.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D: layerdata}.\n\n  Record strong_extends_carrier: Type :=\n    mk_strong_extends_carrier\n    {\n      strong_extends_high: mwd D;\n      strong_extends_low: mwd D;\n      strong_extends_prop: Mem.extends strong_extends_high strong_extends_low\n    }.\n\n  Lemma strong_extends_carrier_eq mm1 mm2:\n    strong_extends_high mm1 = strong_extends_high mm2 ->\n    strong_extends_low mm1 = strong_extends_low mm2 ->\n    mm1 = mm2.\n  Proof.\n    intros H H0.\n    destruct mm1; destruct mm2; simpl in * |- * ; subst.\n    f_equal;\n      apply ProofIrrelevance.proof_irrelevance.\n  Qed.\n\n  Definition strong_extends (mm: strong_extends_carrier) m m': Prop :=\n    m = strong_extends_high mm /\\\n    m' = strong_extends_low mm.\n\n  Lemma strong_extends_intro m m':\n    Mem.extends m m' ->\n    { mm | strong_extends mm m m' }.\n  Proof.\n    intros H.\n    exists (mk_strong_extends_carrier _ _ H).\n    split; auto.\n  Qed.\n\n  Lemma strong_extends_elim mm m m':\n    strong_extends mm m m' ->\n    Mem.extends m m'.\n  Proof.\n    unfold strong_extends.\n    destruct mm; simpl; intuition congruence.\n  Qed.\n\n  Hint Resolve strong_extends_elim.\n\n  Definition strong_extends_le (mm1 mm2: strong_extends_carrier): Prop :=\n    let m1 := strong_extends_high mm1 in\n      let m'1 := strong_extends_low mm1 in\n      let m2 := strong_extends_high mm2 in\n      let m'2 := strong_extends_low mm2 in\n      Mem.unchanged_on (Events.loc_not_writable m1) m1 m2 /\\\n      Mem.unchanged_on (Events.loc_out_of_bounds m1) m'1 m'2 /\\\n      (forall b, Mem.valid_block m1 b -> Mem.valid_block m2 b) /\\\n      (forall b o p, Mem.valid_block m1 b -> Mem.perm m2 b o Max p -> Mem.perm m1 b o Max p).\n\n  Local Instance strong_extends_le_refl:\n    Reflexive strong_extends_le.\n  Proof.\n    red. intros [m m' ?]; simpl.\n    unfold strong_extends_le. simpl.\n    constructor; auto using (Mem.unchanged_on_refl (mem := mwd D)).\n  Qed.\n\n  Local Instance strong_extends_le_trans:\n    Transitive strong_extends_le.\n  Proof.\n    red.\n    intros [m1 m'1 ?] [m2 m'2 ?] [m3 m'3 ?].\n    unfold strong_extends_le. simpl.\n    destruct 1 as (? & ? & ? & ?).\n    destruct 1 as (? & ? & ? & ?).\n    split.\n    {\n      eapply Mem.unchanged_on_trans_strong with (Q := Events.loc_not_writable m2); eauto.\n      unfold Events.loc_not_writable.\n      intros b H5_ o H6_.\n      intro ABSURD.\n      apply H6_.\n      eapply H2; eauto.\n    }\n    split; auto.\n    eapply Mem.unchanged_on_trans_strong with (Q := Events.loc_out_of_bounds m2); eauto.\n    unfold Events.loc_out_of_bounds.\n    intros b H5_ o H6_.\n    intro ABSURD.\n    apply H6_.\n    eapply H2; eauto.\n    erewrite Mem.valid_block_extends; eauto.\n  Qed.\n\n  Lemma strong_extends_le_intro mm1 m1 m'1 m2 m'2:\n    strong_extends mm1 m1 m'1 ->\n    Mem.extends m2 m'2 ->\n    Mem.unchanged_on (Events.loc_not_writable m1) m1 m2 ->\n    Mem.unchanged_on (Events.loc_out_of_bounds m1) m'1 m'2 ->\n    (forall b, Mem.valid_block m1 b -> Mem.valid_block m2 b) ->\n    (forall b o p, Mem.valid_block m1 b -> Mem.perm m2 b o Max p -> Mem.perm m1 b o Max p) ->\n    { mm2 | strong_extends mm2 m2 m'2 /\\\n            strong_extends_le mm1 mm2 }.\n  Proof.\n    intros H H0 H1 H2 H3 H4.\n    exists (mk_strong_extends_carrier _ _ H0).\n    split.\n    { constructor; auto. }\n    inversion H; subst.\n    constructor; auto.\n  Qed.\n\n  Lemma strong_extends_le_elim mm1 m1 m'1 mm2 m2 m'2:\n    strong_extends mm1 m1 m'1 ->\n    strong_extends mm2 m2 m'2 ->\n    strong_extends_le mm1 mm2 ->\n    Mem.unchanged_on (Events.loc_not_writable m1) m1 m2 /\\\n    Mem.unchanged_on (Events.loc_out_of_bounds m1) m'1 m'2 /\\\n    (forall b, Mem.valid_block m1 b -> Mem.valid_block m2 b) /\\\n    (forall b o p, Mem.valid_block m1 b -> Mem.perm m2 b o Max p -> Mem.perm m1 b o Max p).\n  Proof.\n    inversion 1; subst.\n    inversion 1; subst.\n    inversion 1; subst.\n    tauto.\n  Qed.    \n\n  Definition simrel_strong_extends_ops :=\n    {|\n      simrel_world := strong_extends_carrier;\n      simrel_acc := {| Structures.le := strong_extends_le |};\n      simrel_undef_matches_values_bool := true;\n      simrel_undef_matches_block p b := True;\n      simrel_meminj p := inject_id;\n      simrel_new_glbl := nil;\n      match_mem := strong_extends\n    |}.\n\n  Require Import ExtensionalityAxioms.\n\n  (* We try to take advantage of the fact that simrel_meminj is\n     the same as for lessdef, to share proofs. *)\n\n  Lemma match_strong_extends_ptr p:\n    match_ptr simrel_strong_extends_ops p = eq.\n  Proof.\n    rewrite <- (match_ptr_simrel_lessdef (D:=D) tt).\n    eapply functional_extensionality; intros [b1 o1].\n    eapply functional_extensionality; intros [b2 o2].\n    eapply prop_ext.\n    split; inversion 1; constructor; auto.\n  Qed.\n\n  Lemma match_strong_extends_ptrbits p:\n    match_ptrbits simrel_strong_extends_ops p = eq.\n  Proof.\n    rewrite <- (match_ptrbits_simrel_lessdef (D:=D) tt).\n    eapply functional_extensionality; intros [b1 o1].\n    eapply functional_extensionality; intros [b2 o2].\n    eapply prop_ext.\n    split; inversion 1; constructor; auto.\n  Qed.\n\n  Lemma match_strong_extends_block p:\n    match_block simrel_strong_extends_ops p = eq.\n  Proof.\n    rewrite <- (match_block_simrel_lessdef (D:=D) tt).\n    apply eqrel_eq; split; repeat red; tauto.\n  Qed.\n\n  Lemma match_strong_extends_val p:\n    match_val simrel_strong_extends_ops p = Val.lessdef.\n  Proof.\n    rewrite <- (match_val_simrel_lessdef (D:=D) tt).\n    eapply functional_extensionality; intro v1.\n    eapply functional_extensionality; intro v2.\n    eapply prop_ext; split; inversion 1; constructor; auto;\n    (try rewrite (match_ptrbits_simrel_lessdef tt) in * |- *);\n    (try rewrite (match_strong_extends_ptrbits p) in * |- *);\n    auto.\n    match goal with\n        K: match_ptrbits simrel_lessdef_ops _ _ _ |- _ =>\n        rewrite (match_ptrbits_simrel_lessdef tt) in K\n    end.\n    congruence.\n  Qed.\n\n  Lemma match_strong_extends_memval p:\n    match_memval simrel_strong_extends_ops p = memval_lessdef.\n  Proof.\n    rewrite <- (match_memval_simrel_lessdef (D:=D) tt).\n    eapply functional_extensionality; intro v1.\n    eapply functional_extensionality; intro v2.\n    eapply prop_ext; split; inversion 1; constructor; auto;\n    (try rewrite (match_ptrbits_simrel_lessdef tt) in * |- *);\n    (try rewrite (match_strong_extends_ptrbits p) in * |- *);\n    (try rewrite (match_strong_extends_val p) in * |- *);\n    (try rewrite (match_val_simrel_lessdef tt) in * |- *);\n    auto.\n    rewrite (match_val_simrel_lessdef tt) in H0.\n    assumption.\n  Qed.\n\n  Global Instance simrel_strong_extends_prf:\n    SimulationRelation simrel_strong_extends_ops.\n  Proof.\n    assert (Heqsub: forall A B, subrel (@eqrel A B) (@subrel A B)).\n    {\n      intros A B x y H.\n      repeat red in H.\n      tauto.\n    }\n    constructor; try now repeat constructor.\n\n    (** preorder *)\n    - constructor; typeclasses eauto.\n\n    (** [Genv.init_mem] *)\n    - intros F V p1 p2 Hp.\n      apply (simrel_init_mem (R := ext (D:=D))) in Hp.\n      inversion Hp; clear Hp; subst; try now constructor.\n      lazymatch goal with\n        K: _ x y |- _ =>\n        destruct K as [w Hm];\n          rename x into m1;\n          rename y into m2\n      end.\n      simpl in Hm.\n      apply strong_extends_intro in Hm.\n      destruct Hm as [ mm Hm ].\n      constructor.\n      exists mm.\n      assumption.\n\n    (** [Mem.alloc] *)\n    - intros p m1 m1' Hm1 lo hi.\n      destruct (Mem.alloc m1 _ _) eqn:Halloc1.\n      edestruct (Mem.alloc_extends m1) as (? & Halloc2 & Hm2); eauto; try reflexivity.\n      rewrite Halloc2.\n      destruct (strong_extends_le_intro p _ _ _ _ Hm1 Hm2) as [p' Hp'].\n      + eapply Mem.alloc_unchanged_on; eauto.\n      + eapply Mem.alloc_unchanged_on; eauto.\n      + eapply Mem.valid_block_alloc; eauto.\n      + intros; eapply Mem.perm_alloc_4; eauto.\n        intro ABSURD; subst.\n        edestruct (Mem.fresh_block_alloc m1); eauto.\n      + destruct Hp'.\n        reexists; repeat rstep.\n        reflexivity.\n\n    (** [Mem.free] *)\n    - intros p m1 m1' Hm1 [[b_ o_] ?] [[b o] ? ] Hb.\n      inversion Hb as [? ? ? ? sz]; clear Hb; subst.\n      match goal with\n          K: match_ptr _ _ _ _ |- _ =>\n          rewrite match_strong_extends_ptr in K;\n            inversion K; clear K; subst\n      end.\n      simpl.\n      destruct (Mem.free m1 _ _ _) eqn:Hfree1; try now solve_monotonic.\n      edestruct (Mem.free_parallel_extends m1) as (? & Hfree2 & Hm2); eauto.\n      rewrite Hfree2.\n      destruct (strong_extends_le_intro p _ _ _ _ Hm1 Hm2) as [p' Hp'].\n      + eapply Mem.free_unchanged_on; eauto.\n        intros i H.\n        unfold Events.loc_not_writable.\n        intro ABSURD. apply ABSURD; clear ABSURD.\n        apply Mem.perm_cur_max.\n        eapply Mem.perm_implies ; [ eapply Mem.free_range_perm; eauto | ].\n        constructor.\n      + eapply Mem.free_unchanged_on; eauto.\n        intros i H.\n        unfold Events.loc_out_of_bounds.\n        intro ABSURD. apply ABSURD; clear ABSURD.\n        apply Mem.perm_cur_max.\n        eapply Mem.perm_implies ; [ eapply Mem.free_range_perm; eauto | ].\n        constructor.\n      + eapply Mem.valid_block_free_1; eauto.\n      + intros b0 o0 p0 H H0. eapply Mem.perm_free_3; eauto.\n      + destruct Hp' . solve_monotonic.\n\n    (** [Mem.load] *)\n    - intro p.\n      rewrite match_strong_extends_val.\n      rewrite match_strong_extends_ptr.\n      simpl.\n      repeat red.\n      intros a x y H x0 y0 H0.\n      subst.\n      destruct y0.\n      simpl.\n      destruct (Mem.load _ x _ _) eqn:Hload; try constructor.\n      edestruct (Mem.load_extends a x) as (? & Hload2 & ?); eauto.\n      rewrite Hload2.\n      constructor; assumption.\n\n    (** [Mem.store] *)\n    - intro p.\n      rewrite match_strong_extends_val.\n      rewrite match_strong_extends_ptr.\n      simpl.\n      intros a x y H x0 y0 H0 x1 y1 H1.\n      subst.\n      destruct y0 as [b o].\n      simpl.\n      destruct (Mem.store a x b o x1) eqn:STORE1; try now solve_monotonic.\n      edestruct (Mem.store_within_extends a x) as (? & Hstore2 & Hm2); eauto.\n      rewrite Hstore2.\n      destruct (strong_extends_le_intro p _ _ _ _ H Hm2) as [p' Hp'].\n      + eapply Mem.store_unchanged_on; eauto.\n        intros i H0.\n        unfold Events.loc_not_writable.\n        intro ABSURD. apply ABSURD; clear ABSURD.\n        apply Mem.perm_cur_max.\n        eapply Mem.store_valid_access_3; eauto.\n      + eapply Mem.store_unchanged_on; eauto.\n        intros i H0.\n        unfold Events.loc_out_of_bounds.\n        intro ABSURD. apply ABSURD; clear ABSURD.\n        apply Mem.perm_cur_max.\n        eapply Mem.perm_implies; [ eapply Mem.store_valid_access_3; eauto | ].\n        constructor.\n      + eapply Mem.store_valid_block_1; eauto.\n      + intros b0 o0 p0 H0 H2; eapply Mem.perm_store_2; eauto.\n      + destruct Hp' ; solve_monotonic.\n\n    (** [Mem.loadbytes] *)\n    - intro p.\n      rewrite match_strong_extends_memval.\n      rewrite match_strong_extends_ptr.\n      intros x y H x0 y0 H0 a.\n      subst.\n      destruct y0.\n      simpl.\n      destruct (Mem.loadbytes x _ _ _) eqn:Hlb1; try constructor.\n      edestruct (Mem.loadbytes_extends x) as (? & Hlb2 & ?); eauto.\n      rewrite Hlb2.\n      constructor.\n      rewrite <- CompcertStructures.list_forall2_list_rel; assumption.\n\n    (** [Mem.storebytes] *)\n    - intro p.\n      rewrite match_strong_extends_memval.\n      rewrite match_strong_extends_ptr.\n      intros x y H x0 y0 H0 x1 y1 H1.\n      subst.\n      destruct y0.\n      simpl.\n      destruct (Mem.storebytes x _ _ _) eqn:Hsb1; try now solve_monotonic.\n      edestruct (Mem.storebytes_within_extends x) as (? & Hsb2 & Hm2); eauto.\n      { rewrite CompcertStructures.list_forall2_list_rel; eassumption. }\n      rewrite Hsb2.\n      destruct (strong_extends_le_intro p _ _ _ _ H Hm2) as [p' Hp'].\n      + eapply Mem.storebytes_unchanged_on; eauto.\n        intros i H0. unfold Events.loc_not_writable.\n        intro ABSURD. apply ABSURD. clear ABSURD.\n        apply Mem.perm_cur_max.\n        eapply Mem.storebytes_range_perm; eauto.\n      + eapply Mem.storebytes_unchanged_on; eauto.\n        assert (length y1 = length x1) as LEN by (symmetry; solve_monotonic).\n        rewrite LEN.\n        intros i H0. unfold Events.loc_out_of_bounds.\n        intro ABSURD. apply ABSURD. clear ABSURD.\n        apply Mem.perm_cur_max.\n        clear Hsb2.\n        eapply Mem.perm_implies; [ eapply Mem.storebytes_range_perm; eauto | ].\n        constructor.\n      + eapply Mem.storebytes_valid_block_1; eauto.\n      + intros; eapply Mem.perm_storebytes_2; eauto.\n      + destruct Hp' . solve_monotonic.\n\n    (** [Mem.perm] *)\n    - intros p.\n      rewrite match_strong_extends_ptr.\n      repeat red.\n      intros x y H x0 y0 H0 a a0 H1.\n      subst.\n      destruct y0.\n      simpl in *.\n      eapply Mem.perm_extends; eauto.\n\n    (** [Mem.valid_block] *)\n    - intros p.\n      rewrite match_strong_extends_block.\n      simpl.\n      intros m1 m2 Hm b1 b2 Hb; subst.\n      eapply Mem.valid_block_extends; eauto.\n\n    (** [Mem.different_pointers_inject] *)\n    - inversion 5; subst.\n      inversion 1; subst.\n      tauto.\n\n    (** [Mem.weak_valid_pointer_inject_val] *)\n    - intros p m1 m2 b1 ofs1 b2 ofs2 H H0 H1.\n      rewrite match_strong_extends_ptrbits in H1.\n      inversion H1; clear H1; subst.\n      eapply Mem.weak_valid_pointer_extends; eauto.\n\n    (** [Mem.weak_valid_pointer_address_inject_weak] *)\n    - intros p m1 m2 b1 b2 delta H H0.\n      inversion H0; clear H0; subst.\n      exists 0.\n      intros ofs1 H0.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    (** [Mem.address_inject *)\n    - simpl.\n      inversion 3; subst.\n      rewrite Ptrofs.add_zero.\n      omega.\n\n    (** [Mem.aligned_area_inject] *)\n    - simpl.\n      inversion 7; subst.\n      rewrite Z.add_0_r.\n      assumption.\n\n    (** [Mem.disjoint_or_equal_inject] *)\n    - simpl.\n      inversion 2; subst.\n      inversion 1; subst.\n      repeat rewrite Z.add_0_r.\n      tauto.\n  Qed.\n\n  Definition simrel_strong_extends :=\n    {|\n      simrel_ops := simrel_strong_extends_ops\n    |}.\nEnd STRONG_LESSDEF_SIMREL.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/liblayers/simrel/SimrelLessdef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.1880778424719084}}
{"text": "Require Import TestSuite.admit.\n(* File reduced by coq-bug-finder from original input, then from 8249 lines to 907 lines, then from 843 lines to 357 lines, then from 351 lines to 260 lines, then from 208 lines to 162 lines, then from 167 lines to 154 lines, then from 146 lines to 72 lines, then from 82 lines to 70 lines, then from 79 lines to 49 lines, then from 59 lines to 16 lines *)\n\nSet Universe Polymorphism.\nGeneralizable All Variables.\nRecord hSet := BuildhSet {setT:> Type}.\nAxiom minus1Trunc : Type -> Type.\nDefinition hexists {X} (P:X->Type):Type:= minus1Trunc (sigT  P).\nDefinition issurj {X Y} (f:X->Y) := forall y:Y, hexists (fun x => (f x) = y).\nLemma isepi_issurj {X Y} (f:X->Y): issurj f.\nProof.\n  intros y.\n  admit.\nDefined. (* Toplevel input, characters 15-23:\nError: Unsatisfied constraints:\nTop.38 <= Coq.Init.Specif.7\nTop.43 <= Top.38\nTop.43 <= Coq.Init.Specif.8\n (maybe a bugged tactic). *)\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_121.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.18807784012867443}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import compcertx.x86.AsmX.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.compcertx.ErrorMonad.\nRequire Export liblayers.logic.Layers.\nRequire Export liblayers.logic.PTreeLayers.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Export liblayers.compcertx.MemWithData.\nRequire Export liblayers.compat.CompatData.\nRequire Export liblayers.compat.CompatPrimSem.\nRequire Export liblayers.compat.CompatLayerDef.\n\nSection WITH_MEMORY_MODEL.\n  Context `{Hmem: Mem.MemoryModel} `{Hmem': !UseMemWithData mem}.\n\n  (** * Extra interface *)\n\n  Section POINTWISE.\n\n  Local Existing Instance ptree_layer_sim_op.\n  Local Existing Instance ptree_layer_ops.\n  Local Existing Instance ptree_layer_prf.\n\n  (** FIXME: those are theorems about [ptree_layer] *)\n  Lemma cl_layer_pointwise D1 D2 (R: path compatrel D1 D2) L1 L2:\n    sim R (cl_base_layer L1) (cl_base_layer L2) <->\n    (forall (i: ident),\n       res_le (option_le (compatsim R))\n         (get_layer_primitive i L1)\n         (get_layer_primitive i L2)) /\\\n     (forall (i: ident),\n        res_le (option_le eq)\n         (get_layer_globalvar i L1)\n         (get_layer_globalvar i L2)).\n  Proof.\n    simpl.\n    generalize (cl_base_layer L1) (cl_base_layer L2); clear L1 L2.\n    intros L1 L2.\n    split.\n    * intros H.\n      simpl.\n      split; intro; solve_monotonic.\n    * intros [Hfun Hvar].\n      destruct L1 as [L1p L1v], L2 as [L2p L2v].\n      Local Transparent ptree_layer_ops.\n      constructor; intro i;\n      specialize (Hfun i);\n      specialize (Hvar i);\n      simpl in *;\n      unfold ptree_layer_primitive, ptree_layer_globalvar in *; simpl in *.\n      Local Opaque ptree_layer_ops.\n      + destruct (Maps.PTree.get i L1p) as [[|]|];\n        destruct (Maps.PTree.get i L2p) as [[|]|];\n        simpl in *;\n        inversion Hfun as [x1 x2 Hx | ]; try inversion Hx; subst;\n        solve_monotonic.\n      + destruct (Maps.PTree.get i L1v) as [[|]|];\n        destruct (Maps.PTree.get i L2v) as [[|]|];\n        simpl in *;\n        inversion Hvar as [x1 x2 Hx | ]; try inversion Hx; subst;\n        solve_monotonic.\n  Qed.\n\n  (** FIXME: those are theorems about [ptree_layer] *)\n  Lemma cl_le_layer_pointwise D (L1 L2: compatlayer D):\n    sim id (cl_base_layer L1) (cl_base_layer L2) <->\n    (forall (i: ident),\n       res_le (option_le (compatsem_le D))\n         (get_layer_primitive i L1)\n         (get_layer_primitive i L2)) /\\\n     (forall (i: ident),\n        res_le (option_le eq)\n         (get_layer_globalvar i L1)\n         (get_layer_globalvar i L2)).\n  Proof.\n    apply cl_layer_pointwise.\n  Qed.\n\n  (** FIXME: those are theorems about [ptree_layer] *)\n  Lemma cl_sim_layer_pointwise D1 D2 (R: compatrel D1 D2) L1 L2:\n    sim (path_inj R) (cl_base_layer L1) (cl_base_layer L2) <->\n    (forall (i: ident),\n       res_le (option_le (compatsim (path_inj R)))\n         (get_layer_primitive i L1)\n         (get_layer_primitive i L2)) /\\\n     (forall (i: ident),\n        res_le (option_le eq)\n         (get_layer_globalvar i L1)\n         (get_layer_globalvar i L2)).\n  Proof.\n    apply cl_layer_pointwise.\n  Qed.\n\n  End POINTWISE.\n\n  (** * Properties of LayerOK *)\n\n  Lemma get_layer_primitive_mapsto_le_ok\n        {D}\n        (L: compatlayer D)\n        {HOK: LayerOK L}\n        i (\u03c3: compatsem D)\n        (Hle: (i \u21a6 \u03c3) \u2264 L):\n    exists \u03c3',\n      get_layer_primitive i L = OK (Some \u03c3') /\\\n      compatsem_le _ \u03c3 \u03c3'.\n  Proof.\n    generalize (get_layer_primitive_sim_monotonic _ _ _ i _ _ Hle).\n    rewrite get_layer_primitive_mapsto.\n    inversion 1; subst.\n    * inversion H2; subst.\n      eauto.\n    * exfalso. destruct (HOK i) as [[\u03c3' H\u03c3'] _ _].\n      simpl in *.\n      congruence.\n  Qed.\n\n  Lemma get_layer_globalvar_mapsto_le_ok\n        {D}\n        (L: compatlayer D)\n        {HOK: LayerOK L}\n        i (\u03c4: globvar (Ctypes.type))\n        (Hle: (i \u21a6 \u03c4) \u2264 L):\n    get_layer_globalvar i L = OK (Some \u03c4).\n  Proof.\n    generalize (get_layer_globalvar_sim_monotonic _ _ _ i _ _ Hle).\n    rewrite get_layer_globalvar_mapsto.\n    inversion 1; subst.\n    * inversion H2; subst.\n      symmetry; assumption.\n    * exfalso. destruct (HOK i) as [_ [\u03c4' H\u03c4'] _].\n      simpl in *.\n      congruence.\n  Qed.\n\n\n  (** * Matching initial states *)\n\n  Require Import MakeProgram.\n\n  Record cl_init_sim_mem D1 D2 (R: compatrel D1 D2) (m2: mem) :=\n    {\n      cl_init_sim_relate:\n        relate_AbData (Mem.flat_inj (Mem.nextblock m2)) empty_data empty_data;\n      cl_init_sim_match:\n        match_AbData empty_data m2 (Mem.flat_inj (Mem.nextblock m2))\n    }.\n\n  Section WITH_PROGRAM.\n\n    Context `{Hmkp: MakeProgram}.\n    Context `{Fm: Type}.\n    Context `{Fp: Type}.\n    Context `{Vp: Type}.\n    Context `{Hmodule: Modules AST.ident Fm (globvar Ctypes.type)}.\n    Context `{mkp_fmt_ops: !ProgramFormatOps Fm Ctypes.type Fp Vp}.\n    Context `{mkp_fmt: !ProgramFormat Fm Ctypes.type Fp Vp}.\n\n    Require Import InitMem.\n\n    Record cl_init_sim_def D1 D2 R (L1: compatlayer D1) (M: module) (L2: compatlayer D2) :=\n      {\n        cl_init_sim_init_mem:\n          forall (CTXT: module) (m2: mem),\n            (p <- make_program _ (CTXT \u2295 M, L2); ret (Genv.init_mem p) = OK (Some m2)) ->\n            cl_init_sim_mem D1 D2 R m2;\n\n        cl_init_sim_glbl:\n          forall i,\n            List.In i new_glbl ->\n            isOKNone (get_layer_globalvar i L1);\n\n        cl_init_sim_glbl_prim:\n          forall i,\n            List.In i new_glbl ->\n            isOKNone (get_layer_primitive i L1);\n\n        cl_init_sim_glbl_module:\n          forall i,\n            List.In i new_glbl ->\n            exists vi, get_module_variable i M = OK (Some vi);\n\n        cl_init_sim_M:\n          forall {F V} (ge: Genv.t F V) i vi,\n          get_module_variable i M = OK (Some vi) ->\n          Genv.init_data_list_valid ge 0 (gvar_init vi) = true;\n\n        cl_init_sim_low:\n          forall i,\n            isOKNone (get_layer_globalvar i L2)\n\n      }.\n\n    Inductive cl_init_sim D1: forall D2, path compatrel D1 D2 ->\n      compatlayer D1 -> module -> compatlayer D2 -> Prop :=\n      | cl_init_sim_inj D2 R L1 M L2:\n          cl_init_sim_def D1 D2 R L1 M L2 ->\n          cl_init_sim D1 D2 (path_inj R) L1 M L2\n      | cl_init_sim_cons D2 D3 R Rs L1 M L2 N L3:\n          cl_init_sim_def D1 D2 R L1 M L2 ->\n          cl_init_sim D2 D3 Rs L2 N L3 ->\n          cl_init_sim D1 D3 (path_cons R Rs) L1 (M \u2295 N) L3.\n\n    Lemma cl_init_sim_intro D1 D2 R (L1: compatlayer D1) (M: module) (L2: compatlayer D2):\n      (forall (CTXT: module) (m2: mem),\n         (p <- make_program _ (CTXT \u2295 M, L2); ret (Genv.init_mem p)) = OK (Some m2) ->\n         cl_init_sim_mem D1 D2 R m2) ->\n      (forall i,\n         List.In i new_glbl ->\n         isOKNone (get_layer_globalvar i L1)) ->\n      (forall i,\n         List.In i new_glbl ->\n         isOKNone (get_layer_primitive i L1)) ->\n      (forall i,\n         List.In i new_glbl ->\n         exists vi, get_module_variable i M = OK (Some vi)) ->\n      (forall {F V} (ge: Genv.t F V)  i vi,\n         get_module_variable i M = OK (Some vi) ->\n         Genv.init_data_list_valid ge 0 (gvar_init vi) = true) ->\n      (forall i,\n         isOKNone (get_layer_globalvar i L2)) ->\n      cl_init_sim D1 D2 (path_inj R) L1 M L2.\n    Proof.\n      intros Hinitmem HL1v HL1p HMglbl HMinitdata HMnonglbl.\n      constructor.\n      split.\n      * intros.\n        eauto.\n      * intros i Hi.\n        eauto.\n      * intros. eauto.\n      * intros. eauto.\n      * intros. eauto.\n      * intros. eauto.\n    Qed.\n\n  End  WITH_PROGRAM.\nEnd WITH_MEMORY_MODEL.\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/compat/CompatLayerFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.18807783778544016}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICTyping PCUICEquality PCUICAst PCUICAstUtils\n  PCUICWeakeningConv PCUICWeakeningTyp PCUICSubstitution PCUICGeneration PCUICArities\n  PCUICWcbvEval PCUICSR PCUICInversion\n  PCUICUnivSubstitutionConv PCUICUnivSubstitutionTyp\n  PCUICElimination PCUICSigmaCalculus PCUICContextConversion\n  PCUICUnivSubst PCUICWeakeningEnvConv PCUICWeakeningEnvTyp\n  PCUICCumulativity PCUICConfluence\n  PCUICInduction PCUICLiftSubst PCUICContexts PCUICSpine\n  PCUICConversion PCUICValidity PCUICInductives PCUICConversion\n  PCUICInductiveInversion PCUICNormal PCUICSafeLemmata\n  PCUICParallelReductionConfluence\n  PCUICWcbvEval PCUICClosed PCUICClosedTyp\n  PCUICReduction PCUICCSubst PCUICOnFreeVars PCUICWellScopedCumulativity\n  PCUICWcbvEval PCUICCanonicity PCUICSN PCUICNormalization.\n\nFrom Equations Require Import Equations.\n\nDefinition Prop_univ := Universe.of_levels (inl PropLevel.lProp).\n\nDefinition False_oib : one_inductive_body :=\n  {| ind_name := \"False\";\n     ind_indices := [];\n     ind_sort := Prop_univ;\n     ind_type := tSort Prop_univ;\n     ind_kelim := IntoAny;\n     ind_ctors := [];\n     ind_projs := [];\n     ind_relevance := Relevant |}.\n\nDefinition False_mib : mutual_inductive_body :=\n  {| ind_finite := BiFinite;\n     ind_npars := 0;\n     ind_params := [];\n     ind_bodies := [False_oib];\n     ind_universes := Monomorphic_ctx;\n     ind_variance := None |}.\n\nTheorem pcuic_consistent  {cf:checker_flags} {nor : normalizing_flags} \u03a3\n  {normalization_in: NormalizationIn \u03a3} t False_pcuic :\n  declared_inductive \u03a3 False_pcuic False_mib False_oib ->\n  wf_ext \u03a3 -> axiom_free \u03a3 ->\n  \u03a3 ;;; [] |- t : tInd False_pcuic []  -> False.\nProof.\n  intros Hdecl wf\u03a3 ax\u03a3 typ_false. pose proof (_ ; typ_false) as wt.\n  destruct Hdecl as [Hdecl Hidecl].\n  destruct False_pcuic as [kn n]. destruct n; cbn in *; [| now rewrite nth_error_nil in Hidecl].\n  eapply wh_normalization in wt ; eauto. destruct wt as [empty [Hnormal Hempty]].\n  pose proof (Hempty_ := Hempty).\n  eapply subject_reduction in typ_false; eauto.\n  eapply ind_whnf_canonicity with (indargs := []) in typ_false as ctor; auto.\n  - unfold isConstruct_app in ctor.\n    destruct decompose_app eqn:decomp.\n    apply decompose_app_inv in decomp.\n    rewrite decomp in typ_false.\n    destruct t0; try discriminate ctor.\n    apply PCUICValidity.inversion_mkApps in typ_false as H; auto.\n    destruct H as (?&typ_ctor&_).\n    apply inversion_Construct in typ_ctor as (?&?&?&?&?&?&?); auto.\n    eapply Construct_Ind_ind_eq with (args' := []) in typ_false; tea.\n    2: eauto.\n    destruct (on_declared_constructor d).\n    destruct p.\n    destruct s.\n    destruct p.\n    destruct typ_false as (((((->&_)&_)&_)&_)&_).\n    clear -Hdecl d wf\u03a3. destruct wf\u03a3.\n    cbn in *.\n    destruct d as ((?&?)&?).\n    unshelve eapply declared_minductive_to_gen in Hdecl; eauto.\n    unshelve eapply declared_minductive_to_gen in H; eauto.\n    red in H, Hdecl. cbn in *. rewrite Hdecl in H; noconf H.\n    cbn in H0. noconf H0.\n    cbn in H1. rewrite nth_error_nil in H1.\n    discriminate.\n  - unfold notCoInductive, check_recursivity_kind. destruct wf\u03a3.\n    unshelve eapply declared_minductive_to_gen in Hdecl; eauto.\n    red in Hdecl. cbn. rewrite Hdecl; cbn. auto.\nQed.", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICConsistency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.18807783643814138}}
{"text": "Require Import MetaCoq.Template.All.\n\nFrom MetaCoq.PCUIC Require Import \n     PCUICAst PCUICAstUtils PCUICInduction\n     PCUICLiftSubst PCUICEquality\n     PCUICUnivSubst PCUICTyping PCUICGeneration.\n\nFrom MetaCoq.PCUIC Require Import PCUICToTemplate.\nFrom MetaCoq.PCUIC Require Import TemplateToPCUIC.\n\nRequire Import List String.\nImport ListNotations MonadNotation Nat.\nRequire Import MetaCoq.Template.Pretty.\nRequire Import MetaCoq.PCUIC.PCUICPretty.\n\nRequire Import Modes.\n\nOpen Scope string_scope.\n\nDefinition nestedMode := \"Nested_Inductives\".\n\n\n\nClass registered {X} (ty:X) :=\n{\n  assumptionType: Type;\n  assumption: assumptionType;\n  proofType: Type;\n  proof: proofType\n}.\n\n\n\n\nFixpoint isAugmentable (isMain:bool) (t:term) : bool := \n  match t with\n  | tSort _ => negb isMain\n  | tProd _ t1 t2 => \n      orb \n      (isAugmentable false t1)\n      (isAugmentable isMain t2)\n  | _ => false\n  end.\n\nOpen Scope string_scope.\n\nDefinition errorMessage (name:string) : TemplateMonad unit :=\n  (* tmPrint tE;; *)\n  tmMsg (name ++ \" is not a registered container and won't generate nested inductive hypothesis.\");;\n  tmMsg (\"Use `MetaCoq Run Derive Container for \" ++ name ++ \"` to register \" ++ name ++ \" as container.\").\n  (* tmMsg \"was not found in the registered database and thus will be ignored.\";; *)\n\n\nDefinition createFunction (inds:list (kername * option nat * Instance.t)) : TemplateMonad( kername -> nat -> option (term\u00d7term) ) :=\n  monad_fold_left\n  (fun acc '(kname,no,u) =>\n    let object :=\n      match no with\n        None => Ast.tConst kname u\n      | Some n => Ast.tInd (mkInd kname n) u\n      end\n    in\n    tt <- tmUnquote object;;\n    let t := tt.(my_projT2) in\n    inst <- tmInferInstance None (registered t);;\n    tE <- tmEval lazy t;;\n    match inst with\n    | my_None => \n        match no with\n          None => (* TODO check augmentable constant *)\n            errorMessage kname;;\n            tmReturn acc\n        | Some n =>\n          mind <- tmQuoteInductive kname;;\n          match nth_error (Ast.ind_bodies mind) n with\n          | Some oind => \n              match isAugmentable true (trans (Ast.ind_type oind)) with\n              | true => \n                  errorMessage (Ast.ind_name oind);;\n                  tmReturn acc\n              | false => \n                  (* tmMsg \"not found and not augmentable\";; *)\n                  tmReturn acc\n              end\n          | None => tmReturn acc\n          end\n        end\n    | my_Some a => \n        (* tmMsg \"was found in the registered database.\";; *)\n        assumI <- tmQuote (@assumption _ _ a);;\n        proofI <- tmQuote (@proof _ _ a);;\n        assumE <- tmEval lazy assumI;;\n        proofE <- tmEval lazy proofI;;\n        tmReturn\n          (fun name i => \n            if name =? kname then (* TODO use i and no for mutual *)\n              Some (\n                TemplateToPCUIC.trans assumE,\n                TemplateToPCUIC.trans proofE\n              )\n            else\n              acc name i\n          )\n    end\n  )\n  inds\n  (fun _ _ => None).\n\n\nFixpoint findRec (k:nat) (u:term) :=\n  match u with\n  | tRel n => Nat.eqb n k\n  | tProd na A B => orb (findRec k A) (findRec (S k) B)\n  | tLambda na T M => orb (findRec k T) (findRec (S k) M)\n  | tLetIn na b ty b' => orb (orb (findRec k b) (findRec k ty)) (findRec (S k) b')\n  | tApp t1 t2 =>\n    orb (findRec k t1) (findRec k t2)\n  | _ => false\n  end.\n\n\nFixpoint findRecInd (rec:nat) (forceAdd:bool) (t:term) : list (kername * option nat * Instance.t) :=\n  match t with\n  | tProd _ t1 t2 => findRecInd rec false t1 ++\n      findRecInd (S rec) forceAdd t2\n  | tLambda _ t1 t2 => findRecInd rec false t1 ++\n      findRecInd (S rec) forceAdd t2\n  | tLetIn _ t1 t2 t3 => findRecInd rec false t1 ++\n      findRecInd rec false t2 ++\n      findRecInd (S rec) forceAdd t3\n  | tApp t1 t2 =>\n      findRecInd rec (orb forceAdd (findRec rec t2)) t1 ++\n      findRecInd rec forceAdd t2\n  | tInd (mkInd kname n) u => \n      if forceAdd then\n        [(kname, Some n, u)]\n      else\n        []\n  | tConst kname u => \n      if forceAdd then\n        [(kname, None, u)]\n      else\n        []\n  | _ => []\n  end.\n\n\nDefinition getInd (oind:one_inductive_body) : list (kername * option nat * Instance.t) :=\n  List.concat (map (fun '(n,t,i) => findRecInd 0 false t) oind.(ind_ctors)).\n\nDefinition getInds (oind:one_inductive_body) : TemplateMonad (list (kername * option nat * Instance.t)) :=\n        monad_fold_left \n        (fun acc '(n,t,i) =>\n          et <- tmEval all t;;\n          let inds := findRecInd 0 false et in\n          tmReturn (app acc inds)\n        )\n        oind.(ind_ctors)\n        [].\n\nDefinition extractFunction (mind:mutual_inductive_body) (n:nat) : TemplateMonad( kername -> nat -> option (term\u00d7term) )  :=\n  isNested <- getMode nestedMode;;\n  if isNested:bool then\n    match nth_error mind.(ind_bodies) n with\n      None => tmFail \"mutual inductive body was not found\"\n    | Some oind => \n        inds <- getInds oind;;\n        createFunction inds\n    end\n  else\n    tmMsg \"Nested recursion will be ignored.\";;\n    tmReturn (\n      fun _ _ => None\n    ).\n\n\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-nested-induction/helperGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3702254064929194, "lm_q1q2_score": 0.18800485387469568}}
{"text": "(* -------------------------------------------------------------------------- *\n *                     Vellvm - the Verified LLVM project                     *\n *                                                                            *\n *     Copyright (c) 2017 Steve Zdancewic <stevez@cis.upenn.edu>              *\n *                                                                            *\n *   This file is distributed under the terms of the GNU General Public       *\n *   License as published by the Free Software Foundation, either version     *\n *   3 of the License, or (at your option) any later version.                 *\n ---------------------------------------------------------------------------- *)\n\nRequire Import ZArith List String Omega.\nRequire Import Program.\nRequire Import Vellvm.Util.\nRequire Import Vellvm.LLVMAst Vellvm.AstLib Vellvm.CFG Vellvm.CFGProp.\nImport ListNotations.\nOpen Scope Z_scope.\nOpen Scope string_scope.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nRequire Import Vellvm.Handlers.Memory.\n\nDefinition optimization {T} := definition T (list (block T)) -> definition T (list (block T)).\n\nDefinition optimize {T} (m:modul T (list (block T))) (o:optimization) : modul T (list (block T)) :=\n {|\n  m_name := (m_name _ _ m);\n  m_target := (m_target _ _ m);\n  m_datalayout := (m_datalayout _ _ m);\n  m_type_defs := (m_type_defs _ _ m);\n  m_globals := (m_globals _ _ m);\n  m_declarations := (m_declarations _ _ m);\n  m_definitions := map o (m_definitions _ _ m);\n  |}.\n\n\n(*\n\nDefinition correct (P : modul (list block) -> Prop) (o:optimization) :=\n  forall (m:modul (list block)) m_semantic m_opt_semantic,\n    P m ->\n    mcfg_of_modul m = Some m_semantic ->\n    mcfg_of_modul (optimize m o) = Some m_opt_semantic ->\n    forall (s:state),\n      E.obs_error_free (sem m_semantic s) ->\n      E.obs_equiv (sem m_semantic s) (sem m_opt_semantic s).\n      \nClass RemoveInstr X := remove_instr : instr_id -> X -> X.\n\nDefinition remove_instr_block (id:instr_id) (b:block) : block :=\n  {| blk_id := blk_id b;\n     blk_instrs := List.filter (fun x => negb (if (fst x == id) then false else true)) (blk_instrs b);\n     blk_term := blk_term b;\n     blk_term_id := blk_term_id b;\n  |}.\nInstance rem_instr_block : RemoveInstr block := remove_instr_block.\n\nDefinition remove_instr_defn (id:instr_id) (d:definition (list block)) : definition (list block) :=\n  {|\n    df_prototype   := (df_prototype d);\n    df_args        := (df_args d);\n    df_instrs      := List.map (remove_instr id) (df_instrs d);\n  |}.\n\nInstance rem_instr_defn : RemoveInstr (definition (list block)) := remove_instr_defn.\n\nDefinition dead (g:cfg) (inst:instr_id) : Prop :=\n  match inst with\n  | IVoid _ => False\n  | IId id => forall pt, ~ (cmd_uses_local g pt id)\n  end.\n\nInductive remove_instr_applies (inst:instr_id) (d:definition (list block)) : Prop :=\n| remove_instr_applies_intro:\n    forall glbls g, cfg_of_definition glbls d = Some g ->\n               dead g inst ->\n               remove_instr_applies inst d.\n\nDefinition remove_instr_applies_module (instr:instr_id) (m:modul (list block)) : Prop :=\n  Forall (remove_instr_applies instr) (m_definitions m).\n\nRequire Import paco.\n\n(*\nLemma obs_error_free_inv :\n  forall (m:mcfg) (s:state), \n    E.obs_error_free (sem m s) ->\n    (exists dv, sem m s = E.Fin dv) \\/\n    (exists s', stepD m s = E.Ret s' /\\ E.obs_error_free (sem m s')).\nProof.\n  intros m s H.\n  punfold H. remember (upaco1 obs_error_free_step bot1). remember (sem m s) as d. induction H. \n  - left. exists v. reflexivity.\n  - rewrite sem_match_id in Heqd. unfold sem in Heqd.\n    unfold bind in Heqd. \n    destruct (stepD m s).\n    + right. exists s0. split; eauto. subst. inversion Heqd. pclearbot. punfold H. subst. pfold. apply H.\n    + inversion Heqd.\n    + inversion Heqd.\n    + \nAbort.    \n*)  \n    \n\nLemma remove_instr_correct:\n  forall (instr:instr_id), correct (remove_instr_applies_module instr) (remove_instr_defn instr).\nProof.\n  intros instr.\n  unfold correct.\n  intros m m_semantic m_opt_semantic Happlies H0 H1 s Herr. revert s Herr.\n  pcofix CIH.\n  intros s Herr.\n  \nAbort.\n  \n  \n*)\n", "meta": {"author": "amuppal18", "repo": "test", "sha": "4f6663f47786843480790e1b754ea117de435ff3", "save_path": "github-repos/coq/amuppal18-test", "path": "github-repos/coq/amuppal18-test/test-4f6663f47786843480790e1b754ea117de435ff3/src/coq/Transformations/DeadInstr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.18800485034608042}}
{"text": "Load \"preamble3D.v\".\n\n\n(* dans la couche 0 *)\nLemma LOoAB : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAB requis par la preuve de (?)OoAB pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAB requis par la preuve de (?)OoAB pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABm2 : rk(Oo :: A :: B :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABM2 : rk(Oo :: A :: B :: nil) <= 2).\n{\n\tassert(HOoABCMtmp : rk(Oo :: A :: B :: C :: nil) <= 2) by (solve_hyps_max HOoABCeq HOoABCM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: B :: nil) (Oo :: A :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: B :: nil) (Oo :: A :: B :: C :: nil) 2 2 HOoABCMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABM : rk(Oo :: A :: B ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoABeq HOoABM3).\nassert(HOoABm : rk(Oo :: A :: B ::  nil) >= 1) by (solve_hyps_min HOoABeq HOoABm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAC : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAC requis par la preuve de (?)OoAC pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAC requis par la preuve de (?)OoAC pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACm2 : rk(Oo :: A :: C :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACM2 : rk(Oo :: A :: C :: nil) <= 2).\n{\n\tassert(HOoABCMtmp : rk(Oo :: A :: B :: C :: nil) <= 2) by (solve_hyps_max HOoABCeq HOoABCM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: C :: nil) (Oo :: A :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: C :: nil) (Oo :: A :: B :: C :: nil) 2 2 HOoABCMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACM : rk(Oo :: A :: C ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoACeq HOoACM3).\nassert(HOoACm : rk(Oo :: A :: C ::  nil) >= 1) by (solve_hyps_min HOoACeq HOoACm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoBC : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: C ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoBC requis par la preuve de (?)OoBC pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoBC requis par la preuve de (?)OoBC pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCm2 : rk(Oo :: B :: C :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: C :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCM2 : rk(Oo :: B :: C :: nil) <= 2).\n{\n\tassert(HOoABCMtmp : rk(Oo :: A :: B :: C :: nil) <= 2) by (solve_hyps_max HOoABCeq HOoABCM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: C :: nil) (Oo :: A :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: B :: C :: nil) (Oo :: A :: B :: C :: nil) 2 2 HOoABCMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoBCM : rk(Oo :: B :: C ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoBCeq HOoBCM3).\nassert(HOoBCm : rk(Oo :: B :: C ::  nil) >= 1) by (solve_hyps_min HOoBCeq HOoBCm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABC : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: C ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABC requis par la preuve de (?)ABC pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABC requis par la preuve de (?)ABC pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCm2 : rk(A :: B :: C :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: C :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCM2 : rk(A :: B :: C :: nil) <= 2).\n{\n\tassert(HOoABCMtmp : rk(Oo :: A :: B :: C :: nil) <= 2) by (solve_hyps_max HOoABCeq HOoABCM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: C :: nil) (Oo :: A :: B :: C :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (A :: B :: C :: nil) (Oo :: A :: B :: C :: nil) 2 2 HOoABCMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HABCM : rk(A :: B :: C ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABCeq HABCM3).\nassert(HABCm : rk(A :: B :: C ::  nil) >= 1) by (solve_hyps_min HABCeq HABCm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AAp requis par la preuve de (?)AAp pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 2) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap ::  de rang :  3 et 3 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HAApm2 : rk(A :: Ap :: nil) >= 2).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: nil) (A :: Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: nil) (Oo :: A :: A :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: A :: Ap :: nil) ((Oo :: A :: nil) ++ (A :: Ap :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApmtmp;try rewrite HT2 in HOoAApmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (A :: Ap :: nil) (A :: nil) 3 1 2 HOoAApmtmp HAmtmp HOoAMtmp Hincl); apply HT.\n}\n\nassert(HAApM : rk(A :: Ap ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HAApeq HAApM2).\nassert(HAApm : rk(A :: Ap ::  nil) >= 1) by (solve_hyps_min HAApeq HAApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBAp *)\n(* dans constructLemma(), requis par LBApMQ *)\n(* dans la couche 0 *)\nLemma LOoBCApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBCApMQ requis par la preuve de (?)OoBCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCApMQ requis par la preuve de (?)OoBCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HOoBCApMQm3 : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: A :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: Oo :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Oo :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: nil) ++ (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: nil) 4 1 2 HOoABCApMQmtmp HOomtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: B ::  de rang :  2 et 2 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HOoBCApMQm4 : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hincl : incl (Oo :: B :: nil) (list_inter (Oo :: A :: B :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: Oo :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Oo :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: nil) 4 2 2 HOoABCApMQmtmp HOoBmtmp HOoABMtmp Hincl); apply HT.\n}\n\nassert(HOoBCApMQM : rk(Oo :: B :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoBCApMQm : rk(Oo :: B :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Ap :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BApMQ requis par la preuve de (?)BApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HBCApMQm2 : rk(B :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: nil) (B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: nil) ++ (B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (B :: C :: Ap :: M :: Q :: nil) (nil) 4 0 2 HOoABCApMQmtmp Hmtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : B ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HBCApMQm3 : rk(B :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (B :: C :: Ap :: M :: Q :: nil) (B :: nil) 4 1 2 HOoABCApMQmtmp HBmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BApMQ requis par la preuve de (?)BApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BApMQ requis par la preuve de (?)BApMQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBApMQM3 : rk(B :: Ap :: M :: Q :: nil) <= 3).\n{\n\tassert(HBMtmp : rk(B :: nil) <= 1) by (solve_hyps_max HBeq HBM1).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (B :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: M :: Q :: nil) ((B :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (B :: nil) (Ap :: M :: Q :: nil) (nil) 1 2 0 HBMtmp HApMQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -1 et -2*)\n(* ensembles concern\u00e9s AUB : B :: C :: Ap :: M :: Q ::  de rang :  3 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HBApMQm2 : rk(B :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HBCApMQmtmp : rk(B :: C :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBCApMQeq HBCApMQm3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: M :: Q :: nil) (C :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: B :: Ap :: M :: Q :: nil) ((C :: nil) ++ (B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApMQmtmp;try rewrite HT2 in HBCApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (B :: Ap :: M :: Q :: nil) (nil) 3 0 1 HBCApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : B ::  de rang :  1 et 1 \t A : Oo :: B :: C ::   de rang : 2 et 2 *)\nassert(HBApMQm3 : rk(B :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoBCeq : rk(Oo :: B :: C :: nil) = 2) by (apply LOoBC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCMtmp : rk(Oo :: B :: C :: nil) <= 2) by (solve_hyps_max HOoBCeq HOoBCM2).\n\tassert(HOoBCApMQeq : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMQmtmp : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm4).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: B :: C :: nil) (B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: C :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: B :: Ap :: M :: Q :: nil) ((Oo :: B :: C :: nil) ++ (B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApMQmtmp;try rewrite HT2 in HOoBCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: nil) (B :: Ap :: M :: Q :: nil) (B :: nil) 4 1 2 HOoBCApMQmtmp HBmtmp HOoBCMtmp Hincl); apply HT.\n}\n\nassert(HBApMQM : rk(B :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBApMQm : rk(B :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HBApMQeq HBApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Ap ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BAp requis par la preuve de (?)BAp pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBApm2 : rk(B :: Ap :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (B :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: Ap :: M :: Q :: nil) ((B :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 3 1 2 HBApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBApM : rk(B :: Ap ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBApeq HBApM2).\nassert(HBApm : rk(B :: Ap ::  nil) >= 1) by (solve_hyps_min HBApeq HBApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoBAp *)\n(* dans la couche 0 *)\nLemma LOoBApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBApMQ requis par la preuve de (?)OoBApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBApMQ requis par la preuve de (?)OoBApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBApMQ requis par la preuve de (?)OoBApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBApMQm2 : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: Ap :: M :: Q :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoBApMQm3 : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoBCApMQeq : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMQmtmp : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: M :: Q :: nil) (C :: Oo :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: B :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Oo :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApMQmtmp;try rewrite HT2 in HOoBCApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: B :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoBCApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: B ::  de rang :  2 et 2 \t A : Oo :: B :: C ::   de rang : 2 et 2 *)\nassert(HOoBApMQm4 : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoBCeq : rk(Oo :: B :: C :: nil) = 2) by (apply LOoBC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCMtmp : rk(Oo :: B :: C :: nil) <= 2) by (solve_hyps_max HOoBCeq HOoBCM2).\n\tassert(HOoBCApMQeq : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMQmtmp : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm4).\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hincl : incl (Oo :: B :: nil) (list_inter (Oo :: B :: C :: nil) (Oo :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: C :: Oo :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: Oo :: B :: Ap :: M :: Q :: nil) ((Oo :: B :: C :: nil) ++ (Oo :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApMQmtmp;try rewrite HT2 in HOoBCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: nil) (Oo :: B :: Ap :: M :: Q :: nil) (Oo :: B :: nil) 4 2 2 HOoBCApMQmtmp HOoBmtmp HOoBCMtmp Hincl); apply HT.\n}\n\nassert(HOoBApMQM : rk(Oo :: B :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoBApMQm : rk(Oo :: B :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoBApMQeq HOoBApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoBAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoBAp requis par la preuve de (?)OoBAp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoBAp requis par la preuve de (?)OoBAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBApm2 : rk(Oo :: B :: Ap :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: Ap :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoBApm3 : rk(Oo :: B :: Ap :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoBApMQeq : rk(Oo :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApMQmtmp : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBApMQeq HOoBApMQm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (Oo :: B :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: M :: Q :: nil) (Oo :: B :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: Ap :: Ap :: M :: Q :: nil) ((Oo :: B :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApMQmtmp;try rewrite HT2 in HOoBApMQmtmp.\n\tassert(HT := rule_2 (Oo :: B :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 4 1 2 HOoBApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HOoBApM : rk(Oo :: B :: Ap ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoBApeq HOoBApM3).\nassert(HOoBApm : rk(Oo :: B :: Ap ::  nil) >= 1) by (solve_hyps_min HOoBApeq HOoBApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LABAp *)\n(* dans constructLemma(), requis par LABApMQ *)\n(* dans la couche 0 *)\nLemma LABCApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCApMQ requis par la preuve de (?)ABCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCApMQ requis par la preuve de (?)ABCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HABCApMQm3 : rk(A :: B :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: nil) (A :: B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: A :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: A :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: nil) ++ (A :: B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (A :: B :: C :: Ap :: M :: Q :: nil) (A :: nil) 4 1 2 HOoABCApMQmtmp HAmtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A :: B ::  de rang :  2 et 2 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HABCApMQm4 : rk(A :: B :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hincl : incl (A :: B :: nil) (list_inter (Oo :: A :: B :: nil) (A :: B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: A :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (A :: B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: B :: C :: Ap :: M :: Q :: nil) (A :: B :: nil) 4 2 2 HOoABCApMQmtmp HABmtmp HOoABMtmp Hincl); apply HT.\n}\n\nassert(HABCApMQM : rk(A :: B :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCApMQm : rk(A :: B :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HABCApMQeq HABCApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABApMQ requis par la preuve de (?)ABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABApMQ requis par la preuve de (?)ABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABApMQ requis par la preuve de (?)ABApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABApMQm2 : rk(A :: B :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Ap :: M :: Q :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HABApMQm3 : rk(A :: B :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HABCApMQeq : rk(A :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LABCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCApMQmtmp : rk(A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HABCApMQeq HABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Ap :: M :: Q :: nil) (C :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: A :: B :: Ap :: M :: Q :: nil) ((C :: nil) ++ (A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCApMQmtmp;try rewrite HT2 in HABCApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (A :: B :: Ap :: M :: Q :: nil) (nil) 4 0 1 HABCApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A :: B ::  de rang :  2 et 2 \t A : A :: B :: C ::   de rang : 2 et 2 *)\nassert(HABApMQm4 : rk(A :: B :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HABCeq : rk(A :: B :: C :: nil) = 2) by (apply LABC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCMtmp : rk(A :: B :: C :: nil) <= 2) by (solve_hyps_max HABCeq HABCM2).\n\tassert(HABCApMQeq : rk(A :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LABCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCApMQmtmp : rk(A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HABCApMQeq HABCApMQm4).\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hincl : incl (A :: B :: nil) (list_inter (A :: B :: C :: nil) (A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Ap :: M :: Q :: nil) (A :: B :: C :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: A :: B :: Ap :: M :: Q :: nil) ((A :: B :: C :: nil) ++ (A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCApMQmtmp;try rewrite HT2 in HABCApMQmtmp.\n\tassert(HT := rule_4 (A :: B :: C :: nil) (A :: B :: Ap :: M :: Q :: nil) (A :: B :: nil) 4 2 2 HABCApMQmtmp HABmtmp HABCMtmp Hincl); apply HT.\n}\n\nassert(HABApMQM : rk(A :: B :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABApMQm : rk(A :: B :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HABApMQeq HABApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABAp requis par la preuve de (?)ABAp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABAp requis par la preuve de (?)ABAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABApm2 : rk(A :: B :: Ap :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Ap :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HABApm3 : rk(A :: B :: Ap :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HABApMQeq : rk(A :: B :: Ap :: M :: Q :: nil) = 4) by (apply LABApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApMQmtmp : rk(A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HABApMQeq HABApMQm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (A :: B :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Ap :: M :: Q :: nil) (A :: B :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: Ap :: Ap :: M :: Q :: nil) ((A :: B :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABApMQmtmp;try rewrite HT2 in HABApMQmtmp.\n\tassert(HT := rule_2 (A :: B :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 4 1 2 HABApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HABApM : rk(A :: B :: Ap ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABApeq HABApM3).\nassert(HABApm : rk(A :: B :: Ap ::  nil) >= 1) by (solve_hyps_min HABApeq HABApm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABAp requis par la preuve de (?)OoABAp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABAp requis par la preuve de (?)OoABAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABAp requis par la preuve de (?)OoABAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApm2 : rk(Oo :: A :: B :: Ap :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABApM3 : rk(Oo :: A :: B :: Ap :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: nil) (Oo :: A :: B :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: nil) ((Oo :: A :: B :: nil) ++ (Ap :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (Ap :: nil) (nil) 2 1 0 HOoABMtmp HApMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApm3 : rk(Oo :: A :: B :: Ap :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABApM : rk(Oo :: A :: B :: Ap ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApm : rk(Oo :: A :: B :: Ap ::  nil) >= 1) by (solve_hyps_min HOoABApeq HOoABApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCAp *)\n(* dans constructLemma(), requis par LCApMQ *)\n(* dans la couche 0 *)\nLemma LOoACApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApMQ requis par la preuve de (?)OoACApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApMQ requis par la preuve de (?)OoACApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApMQ requis par la preuve de (?)OoACApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApMQm2 : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : B ::   de rang : 1 et 1 *)\nassert(HOoACApMQm3 : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HBMtmp : rk(B :: nil) <= 1) by (solve_hyps_max HBeq HBM1).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (B :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (B :: Oo :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Oo :: A :: C :: Ap :: M :: Q :: nil) ((B :: nil) ++ (Oo :: A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (B :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoABCApMQmtmp Hmtmp HBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HOoACApMQm4 : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: B :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: Oo :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Oo :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (Oo :: A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: nil) 4 2 2 HOoABCApMQmtmp HOoAmtmp HOoABMtmp Hincl); apply HT.\n}\n\nassert(HOoACApMQM : rk(Oo :: A :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACApMQm : rk(Oo :: A :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoACApMQeq HOoACApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour CApMQ requis par la preuve de (?)CApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApMQ requis par la preuve de (?)CApMQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApMQ requis par la preuve de (?)CApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HCApMQm2 : rk(C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (C :: Ap :: M :: Q :: nil) (nil) 4 0 2 HOoABCApMQmtmp Hmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HCApMQM3 : rk(C :: Ap :: M :: Q :: nil) <= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: M :: Q :: nil) (C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (C :: nil) (Ap :: M :: Q :: nil) (nil) 1 2 0 HCMtmp HApMQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : C ::  de rang :  1 et 1 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HCApMQm3 : rk(C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HCmtmp : rk(C :: nil) >= 1) by (solve_hyps_min HCeq HCm1).\n\tassert(Hincl : incl (C :: nil) (list_inter (Oo :: A :: C :: nil) (C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (C :: Ap :: M :: Q :: nil) (C :: nil) 4 1 2 HOoACApMQmtmp HCmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HCApMQM : rk(C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApMQm : rk(C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HCApMQeq HCApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour CAp requis par la preuve de (?)CAp pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HCApm2 : rk(C :: Ap :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HCApMQeq : rk(C :: Ap :: M :: Q :: nil) = 3) by (apply LCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApMQmtmp : rk(C :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HCApMQeq HCApMQm3).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (C :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: M :: Q :: nil) (C :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Ap :: M :: Q :: nil) ((C :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApMQmtmp;try rewrite HT2 in HCApMQmtmp.\n\tassert(HT := rule_2 (C :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 3 1 2 HCApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HCApM : rk(C :: Ap ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HCApeq HCApM2).\nassert(HCApm : rk(C :: Ap ::  nil) >= 1) by (solve_hyps_min HCApeq HCApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoCAp *)\n(* dans la couche 0 *)\nLemma LOoCApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApMQ requis par la preuve de (?)OoCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApMQ requis par la preuve de (?)OoCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBCApMQ requis par la preuve de (?)OoCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCApMQ requis par la preuve de (?)OoBCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HOoBCApMQm3 : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: A :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: Oo :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Oo :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: nil) ++ (Oo :: B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: nil) 4 1 2 HOoABCApMQmtmp HOomtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApMQ requis par la preuve de (?)OoCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: M :: Q ::  de rang :  3 et 4 \t AiB : Oo ::  de rang :  1 et 1 \t A : Oo :: B ::   de rang : 2 et 2 *)\nassert(HOoCApMQm2 : rk(Oo :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoBMtmp : rk(Oo :: B :: nil) <= 2) by (solve_hyps_max HOoBeq HOoBM2).\n\tassert(HOoBCApMQmtmp : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm3).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: B :: nil) (Oo :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: Oo :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: Oo :: C :: Ap :: M :: Q :: nil) ((Oo :: B :: nil) ++ (Oo :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApMQmtmp;try rewrite HT2 in HOoBCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: nil) (Oo :: C :: Ap :: M :: Q :: nil) (Oo :: nil) 3 1 2 HOoBCApMQmtmp HOomtmp HOoBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HOoCApMQm3 : rk(Oo :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: A :: B :: nil) (Oo :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: Oo :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Oo :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (Oo :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (Oo :: C :: Ap :: M :: Q :: nil) (Oo :: nil) 4 1 2 HOoABCApMQmtmp HOomtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: C ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoCApMQm4 : rk(Oo :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hincl : incl (Oo :: C :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: Oo :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: C :: Ap :: M :: Q :: nil) (Oo :: C :: nil) 4 2 2 HOoACApMQmtmp HOoCmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HOoCApMQM : rk(Oo :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApMQm : rk(Oo :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoCApMQeq HOoCApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoCAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoCAp requis par la preuve de (?)OoCAp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoCAp requis par la preuve de (?)OoCAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApm2 : rk(Oo :: C :: Ap :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoCApm3 : rk(Oo :: C :: Ap :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoCApMQeq : rk(Oo :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApMQmtmp : rk(Oo :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoCApMQeq HOoCApMQm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (Oo :: C :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: M :: Q :: nil) (Oo :: C :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: C :: Ap :: Ap :: M :: Q :: nil) ((Oo :: C :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApMQmtmp;try rewrite HT2 in HOoCApMQmtmp.\n\tassert(HT := rule_2 (Oo :: C :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 4 1 2 HOoCApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HOoCApM : rk(Oo :: C :: Ap ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoCApeq HOoCApM3).\nassert(HOoCApm : rk(Oo :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HOoCApeq HOoCApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LACAp *)\n(* dans la couche 0 *)\nLemma LACApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACApMQ requis par la preuve de (?)ACApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACApMQ requis par la preuve de (?)ACApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACApMQ requis par la preuve de (?)ACApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: B ::   de rang : 2 et 2 *)\nassert(HACApMQm2 : rk(A :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoBMtmp : rk(Oo :: B :: nil) <= 2) by (solve_hyps_max HOoBeq HOoBM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: B :: nil) (A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: B :: nil) ++ (A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: nil) (A :: C :: Ap :: M :: Q :: nil) (nil) 4 0 2 HOoABCApMQmtmp Hmtmp HOoBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HACApMQm3 : rk(A :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: C :: Ap :: M :: Q :: nil) (A :: nil) 4 1 2 HOoABCApMQmtmp HAmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A :: C ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HACApMQm4 : rk(A :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hincl : incl (A :: C :: nil) (list_inter (Oo :: A :: C :: nil) (A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (A :: C :: Ap :: M :: Q :: nil) (A :: C :: nil) 4 2 2 HOoACApMQmtmp HACmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HACApMQM : rk(A :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HACApMQm : rk(A :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HACApMQeq HACApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ACAp requis par la preuve de (?)ACAp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ACAp requis par la preuve de (?)ACAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACApm2 : rk(A :: C :: Ap :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Ap :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HACApm3 : rk(A :: C :: Ap :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HACApMQeq : rk(A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACApMQmtmp : rk(A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HACApMQeq HACApMQm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (A :: C :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Ap :: M :: Q :: nil) (A :: C :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: C :: Ap :: Ap :: M :: Q :: nil) ((A :: C :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACApMQmtmp;try rewrite HT2 in HACApMQmtmp.\n\tassert(HT := rule_2 (A :: C :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 4 1 2 HACApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HACApM : rk(A :: C :: Ap ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HACApeq HACApM3).\nassert(HACApm : rk(A :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HACApeq HACApm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoACAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACAp requis par la preuve de (?)OoACAp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACAp requis par la preuve de (?)OoACAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACAp requis par la preuve de (?)OoACAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApm2 : rk(Oo :: A :: C :: Ap :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoACApM3 : rk(Oo :: A :: C :: Ap :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: C :: nil) (Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: nil) (Oo :: A :: C :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: nil) ((Oo :: A :: C :: nil) ++ (Ap :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Ap :: nil) (nil) 2 1 0 HOoACMtmp HApMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApm3 : rk(Oo :: A :: C :: Ap :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACApM : rk(Oo :: A :: C :: Ap ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACApm : rk(Oo :: A :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HOoACApeq HOoACApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBCAp *)\n(* dans la couche 0 *)\nLemma LBCApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: C :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BCApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BCApMQ requis par la preuve de (?)BCApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HBCApMQm2 : rk(B :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: nil) (B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: nil) ++ (B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (B :: C :: Ap :: M :: Q :: nil) (nil) 4 0 2 HOoABCApMQmtmp Hmtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : B ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HBCApMQm3 : rk(B :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (B :: C :: Ap :: M :: Q :: nil) (B :: nil) 4 1 2 HOoABCApMQmtmp HBmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : B :: C ::  de rang :  2 et 2 \t A : Oo :: B :: C ::   de rang : 2 et 2 *)\nassert(HBCApMQm4 : rk(B :: C :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoBCeq : rk(Oo :: B :: C :: nil) = 2) by (apply LOoBC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCMtmp : rk(Oo :: B :: C :: nil) <= 2) by (solve_hyps_max HOoBCeq HOoBCM2).\n\tassert(HOoBCApMQeq : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMQmtmp : rk(Oo :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBCApMQeq HOoBCApMQm4).\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hincl : incl (B :: C :: nil) (list_inter (Oo :: B :: C :: nil) (B :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: C :: B :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: B :: C :: Ap :: M :: Q :: nil) ((Oo :: B :: C :: nil) ++ (B :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApMQmtmp;try rewrite HT2 in HOoBCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: nil) (B :: C :: Ap :: M :: Q :: nil) (B :: C :: nil) 4 2 2 HOoBCApMQmtmp HBCmtmp HOoBCMtmp Hincl); apply HT.\n}\n\nassert(HBCApMQM : rk(B :: C :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBCApMQm : rk(B :: C :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HBCApMQeq HBCApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBCAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BCAp requis par la preuve de (?)BCAp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BCAp requis par la preuve de (?)BCAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HBCApm2 : rk(B :: C :: Ap :: nil) >= 2).\n{\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: C :: nil) (B :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: C :: nil) (B :: C :: Ap :: nil) 2 2 HBCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBCApm3 : rk(B :: C :: Ap :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBCApMQeq : rk(B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApMQmtmp : rk(B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HBCApMQeq HBCApMQm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (B :: C :: Ap :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: M :: Q :: nil) (B :: C :: Ap :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: C :: Ap :: Ap :: M :: Q :: nil) ((B :: C :: Ap :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApMQmtmp;try rewrite HT2 in HBCApMQmtmp.\n\tassert(HT := rule_2 (B :: C :: Ap :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 4 1 2 HBCApMQmtmp HApmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBCApM : rk(B :: C :: Ap ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HBCApeq HBCApM3).\nassert(HBCApm : rk(B :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HBCApeq HBCApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoBCAp *)\n(* dans la couche 0 *)\nLemma LOoABCAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABCAp requis par la preuve de (?)OoABCAp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABAp requis par la preuve de (?)OoABCAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABAp requis par la preuve de (?)OoABAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABAp requis par la preuve de (?)OoABAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApm2 : rk(Oo :: A :: B :: Ap :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABApM3 : rk(Oo :: A :: B :: Ap :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: nil) (Oo :: A :: B :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: nil) ((Oo :: A :: B :: nil) ++ (Ap :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (Ap :: nil) (nil) 2 1 0 HOoABMtmp HApMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCAp requis par la preuve de (?)OoABCAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCAp requis par la preuve de (?)OoABCAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApm2 : rk(Oo :: A :: B :: C :: Ap :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 5 et -4*)\nassert(HOoABCApM3 : rk(Oo :: A :: B :: C :: Ap :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: nil) (Oo :: A :: C :: Oo :: A :: B :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: Ap :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: Ap :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: nil) (Oo :: A :: nil) 2 3 2 HOoACMtmp HOoABApMtmp HOoAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApm3 : rk(Oo :: A :: B :: C :: Ap :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABCApM : rk(Oo :: A :: B :: C :: Ap ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABCApm : rk(Oo :: A :: B :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HOoABCApeq HOoABCApm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoBCAp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: C :: Ap ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoBCAp requis par la preuve de (?)OoBCAp pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBCAp requis par la preuve de (?)OoBCAp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCAp requis par la preuve de (?)OoBCAp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCApm2 : rk(Oo :: B :: C :: Ap :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: C :: Ap :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: C :: Ap :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoBCApM3 : rk(Oo :: B :: C :: Ap :: nil) <= 3).\n{\n\tassert(HOoBCeq : rk(Oo :: B :: C :: nil) = 2) by (apply LOoBC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCMtmp : rk(Oo :: B :: C :: nil) <= 2) by (solve_hyps_max HOoBCeq HOoBCM2).\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: B :: C :: nil) (Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: nil) (Oo :: B :: C :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: Ap :: nil) ((Oo :: B :: C :: nil) ++ (Ap :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: B :: C :: nil) (Ap :: nil) (nil) 2 1 0 HOoBCMtmp HApMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap ::  de rang :  3 et 3 \t AiB : Oo :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HOoBCApm3 : rk(Oo :: B :: C :: Ap :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApeq : rk(Oo :: A :: B :: C :: Ap :: nil) = 3) by (apply LOoABCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABCApmtmp : rk(Oo :: A :: B :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoABCApeq HOoABCApm3).\n\tassert(HOoBApeq : rk(Oo :: B :: Ap :: nil) = 3) by (apply LOoBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApmtmp : rk(Oo :: B :: Ap :: nil) >= 3) by (solve_hyps_min HOoBApeq HOoBApm3).\n\tassert(Hincl : incl (Oo :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: nil) (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (Oo :: B :: C :: Ap :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApmtmp;try rewrite HT2 in HOoABCApmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: nil) (Oo :: B :: Ap :: nil) 3 3 3 HOoABCApmtmp HOoBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\nassert(HOoBCApM : rk(Oo :: B :: C :: Ap ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoBCApm : rk(Oo :: B :: C :: Ap ::  nil) >= 1) by (solve_hyps_min HOoBCApeq HOoBCApm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LABp *)\n(* dans la couche 0 *)\nLemma LOoAApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Bp :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAApBpCp requis par la preuve de (?)OoAApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAApBpCp requis par la preuve de (?)OoAApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApBpCp requis par la preuve de (?)OoAApBpCp pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HOoAApBpCpM3 : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: nil) (A :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Oo :: Ap :: Bp :: Cp :: nil) ((A :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (nil) 1 2 0 HAMtmp HOoApBpCpMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpCpm2 : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: Cp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpCpm3 : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: Cp :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAApBpCpM : rk(Oo :: A :: Ap :: Bp :: Cp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApBpCpm : rk(Oo :: A :: Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoAApBpCpeq HOoAApBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Bp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour ABp requis par la preuve de (?)ABp pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HABpm2 : rk(A :: Bp :: nil) >= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoAApBpCpeq : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoAApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApBpCpmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoAApBpCpeq HOoAApBpCpm3).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (A :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: nil) (A :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((A :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpmtmp;try rewrite HT2 in HOoAApBpCpmtmp.\n\tassert(HT := rule_2 (A :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Bp :: nil) 3 1 2 HOoAApBpCpmtmp HBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HABpM : rk(A :: Bp ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HABpeq HABpM2).\nassert(HABpm : rk(A :: Bp ::  nil) >= 1) by (solve_hyps_min HABpeq HABpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABp requis par la preuve de (?)OoABp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoABp requis par la preuve de (?)OoABp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpm2 : rk(Oo :: A :: Bp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -4 et -4*)\nassert(HOoABpm3 : rk(Oo :: A :: Bp :: nil) >= 3).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoAApBpCpeq : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoAApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApBpCpmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoAApBpCpeq HOoAApBpCpm3).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: A :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: nil) (Oo :: A :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpmtmp;try rewrite HT2 in HOoAApBpCpmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: Bp :: nil) 3 2 2 HOoAApBpCpmtmp HOoBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HOoABpM : rk(Oo :: A :: Bp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoABpeq HOoABpM3).\nassert(HOoABpm : rk(Oo :: A :: Bp ::  nil) >= 1) by (solve_hyps_min HOoABpeq HOoABpm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBBp *)\n(* dans constructLemma(), requis par LOoBApBpCp *)\n(* dans la couche 0 *)\nLemma LOoABApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: Bp :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABApBpCp requis par la preuve de (?)OoABApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApBpCp requis par la preuve de (?)OoABApBpCp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApBpCp requis par la preuve de (?)OoABApBpCp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApBpCpm2 : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: Bp :: Cp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABApBpCpM3 : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: A :: B :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: Bp :: Cp :: nil) (Oo :: A :: B :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: B :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: nil) 2 2 1 HOoABMtmp HOoApBpCpMtmp HOomtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApBpCpm3 : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: Bp :: Cp :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABApBpCpM : rk(Oo :: A :: B :: Ap :: Bp :: Cp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApBpCpm : rk(Oo :: A :: B :: Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoABApBpCpeq HOoABApBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoBApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: Ap :: Bp :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoBApBpCp requis par la preuve de (?)OoBApBpCp pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoBApBpCp requis par la preuve de (?)OoBApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBApBpCp requis par la preuve de (?)OoBApBpCp pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HOoBApBpCpM3 : rk(Oo :: B :: Ap :: Bp :: Cp :: nil) <= 3).\n{\n\tassert(HBMtmp : rk(B :: nil) <= 1) by (solve_hyps_max HBeq HBM1).\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (B :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: Bp :: Cp :: nil) (B :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Oo :: Ap :: Bp :: Cp :: nil) ((B :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (B :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (nil) 1 2 0 HBMtmp HOoApBpCpMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBApBpCpm2 : rk(Oo :: B :: Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: Ap :: Bp :: Cp :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: Bp :: Cp ::  de rang :  3 et 3 \t AiB : Oo :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HOoBApBpCpm3 : rk(Oo :: B :: Ap :: Bp :: Cp :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABApBpCpeq : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoABApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApBpCpmtmp : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoABApBpCpeq HOoABApBpCpm3).\n\tassert(HOoBApeq : rk(Oo :: B :: Ap :: nil) = 3) by (apply LOoBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApmtmp : rk(Oo :: B :: Ap :: nil) >= 3) by (solve_hyps_min HOoBApeq HOoBApm3).\n\tassert(Hincl : incl (Oo :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (Oo :: B :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: Bp :: Cp :: nil) (Oo :: A :: B :: Ap :: Oo :: B :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: Oo :: B :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (Oo :: B :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApBpCpmtmp;try rewrite HT2 in HOoABApBpCpmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (Oo :: B :: Ap :: Bp :: Cp :: nil) (Oo :: B :: Ap :: nil) 3 3 3 HOoABApBpCpmtmp HOoBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\nassert(HOoBApBpCpM : rk(Oo :: B :: Ap :: Bp :: Cp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoBApBpCpm : rk(Oo :: B :: Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoBApBpCpeq HOoBApBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Bp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BBp requis par la preuve de (?)BBp pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBBpm2 : rk(B :: Bp :: nil) >= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoBApBpCpeq : rk(Oo :: B :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoBApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApBpCpmtmp : rk(Oo :: B :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoBApBpCpeq HOoBApBpCpm3).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (B :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: Bp :: Cp :: nil) (B :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((B :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApBpCpmtmp;try rewrite HT2 in HOoBApBpCpmtmp.\n\tassert(HT := rule_2 (B :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Bp :: nil) 3 1 2 HOoBApBpCpmtmp HBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HBBpM : rk(B :: Bp ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBBpeq HBBpM2).\nassert(HBBpm : rk(B :: Bp ::  nil) >= 1) by (solve_hyps_min HBBpeq HBBpm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LABBp *)\n(* dans constructLemma(), requis par LABBpNP *)\n(* dans la couche 0 *)\nLemma LABCBpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: C :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCBpNP requis par la preuve de (?)ABCBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCBpNP requis par la preuve de (?)ABCBpNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HABCBpNPm3 : rk(A :: B :: C :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: nil) (A :: B :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: A :: B :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: A :: B :: C :: Bp :: N :: P :: nil) ((Oo :: A :: nil) ++ (A :: B :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (A :: B :: C :: Bp :: N :: P :: nil) (A :: nil) 4 1 2 HOoABCBpNPmtmp HAmtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A :: B ::  de rang :  2 et 2 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HABCBpNPm4 : rk(A :: B :: C :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hincl : incl (A :: B :: nil) (list_inter (Oo :: A :: B :: nil) (A :: B :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: B :: A :: B :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: B :: C :: Bp :: N :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: B :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: B :: C :: Bp :: N :: P :: nil) (A :: B :: nil) 4 2 2 HOoABCBpNPmtmp HABmtmp HOoABMtmp Hincl); apply HT.\n}\n\nassert(HABCBpNPM : rk(A :: B :: C :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCBpNPm : rk(A :: B :: C :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HABCBpNPeq HABCBpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABBpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABBpNP requis par la preuve de (?)ABBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABBpNP requis par la preuve de (?)ABBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABBpNP requis par la preuve de (?)ABBpNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABBpNPm2 : rk(A :: B :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Bp :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Bp :: N :: P :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HABBpNPm3 : rk(A :: B :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HABCBpNPeq : rk(A :: B :: C :: Bp :: N :: P :: nil) = 4) by (apply LABCBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCBpNPmtmp : rk(A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HABCBpNPeq HABCBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (A :: B :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Bp :: N :: P :: nil) (C :: A :: B :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: A :: B :: Bp :: N :: P :: nil) ((C :: nil) ++ (A :: B :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCBpNPmtmp;try rewrite HT2 in HABCBpNPmtmp.\n\tassert(HT := rule_4 (C :: nil) (A :: B :: Bp :: N :: P :: nil) (nil) 4 0 1 HABCBpNPmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A :: B ::  de rang :  2 et 2 \t A : A :: B :: C ::   de rang : 2 et 2 *)\nassert(HABBpNPm4 : rk(A :: B :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HABCeq : rk(A :: B :: C :: nil) = 2) by (apply LABC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCMtmp : rk(A :: B :: C :: nil) <= 2) by (solve_hyps_max HABCeq HABCM2).\n\tassert(HABCBpNPeq : rk(A :: B :: C :: Bp :: N :: P :: nil) = 4) by (apply LABCBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCBpNPmtmp : rk(A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HABCBpNPeq HABCBpNPm4).\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hincl : incl (A :: B :: nil) (list_inter (A :: B :: C :: nil) (A :: B :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Bp :: N :: P :: nil) (A :: B :: C :: A :: B :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: A :: B :: Bp :: N :: P :: nil) ((A :: B :: C :: nil) ++ (A :: B :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCBpNPmtmp;try rewrite HT2 in HABCBpNPmtmp.\n\tassert(HT := rule_4 (A :: B :: C :: nil) (A :: B :: Bp :: N :: P :: nil) (A :: B :: nil) 4 2 2 HABCBpNPmtmp HABmtmp HABCMtmp Hincl); apply HT.\n}\n\nassert(HABBpNPM : rk(A :: B :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABBpNPm : rk(A :: B :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HABBpNPeq HABBpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Bp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABBp requis par la preuve de (?)ABBp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABBp requis par la preuve de (?)ABBp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABBpm2 : rk(A :: B :: Bp :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Bp :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HABBpm3 : rk(A :: B :: Bp :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABBpNPeq : rk(A :: B :: Bp :: N :: P :: nil) = 4) by (apply LABBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABBpNPmtmp : rk(A :: B :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HABBpNPeq HABBpNPm4).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (A :: B :: Bp :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Bp :: N :: P :: nil) (A :: B :: Bp :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: Bp :: Bp :: N :: P :: nil) ((A :: B :: Bp :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABBpNPmtmp;try rewrite HT2 in HABBpNPmtmp.\n\tassert(HT := rule_2 (A :: B :: Bp :: nil) (Bp :: N :: P :: nil) (Bp :: nil) 4 1 2 HABBpNPmtmp HBpmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HABBpM : rk(A :: B :: Bp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABBpeq HABBpM3).\nassert(HABBpm : rk(A :: B :: Bp ::  nil) >= 1) by (solve_hyps_min HABBpeq HABBpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Bp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABBp requis par la preuve de (?)OoABBp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBp requis par la preuve de (?)OoABBp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBp requis par la preuve de (?)OoABBp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpm2 : rk(Oo :: A :: B :: Bp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABBpM3 : rk(Oo :: A :: B :: Bp :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HBpMtmp : rk(Bp :: nil) <= 1) by (solve_hyps_max HBpeq HBpM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (Bp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: nil) (Oo :: A :: B :: Bp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: nil) ((Oo :: A :: B :: nil) ++ (Bp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (Bp :: nil) (nil) 2 1 0 HOoABMtmp HBpMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -4 et -4*)\nassert(HOoABBpm3 : rk(Oo :: A :: B :: Bp :: nil) >= 3).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoABApBpCpeq : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoABApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApBpCpmtmp : rk(Oo :: A :: B :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoABApBpCpeq HOoABApBpCpm3).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: A :: B :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: Bp :: Cp :: nil) (Oo :: A :: B :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: B :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApBpCpmtmp;try rewrite HT2 in HOoABApBpCpmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: Bp :: nil) 3 2 2 HOoABApBpCpmtmp HOoBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HOoABBpM : rk(Oo :: A :: B :: Bp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABBpm : rk(Oo :: A :: B :: Bp ::  nil) >= 1) by (solve_hyps_min HOoABBpeq HOoABBpm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCBp *)\n(* dans constructLemma(), requis par LOoCApBpCp *)\n(* dans la couche 0 *)\nLemma LOoACApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Ap :: Bp :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACApBpCp requis par la preuve de (?)OoACApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpCp requis par la preuve de (?)OoACApBpCp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpCp requis par la preuve de (?)OoACApBpCp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpCpm2 : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Cp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoACApBpCpM3 : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Cp :: nil) (Oo :: A :: C :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: nil) 2 2 1 HOoACMtmp HOoApBpCpMtmp HOomtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpCpm3 : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Cp :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACApBpCpM : rk(Oo :: A :: C :: Ap :: Bp :: Cp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACApBpCpm : rk(Oo :: A :: C :: Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoACApBpCpeq HOoACApBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoCApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: Bp :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoCApBpCp requis par la preuve de (?)OoCApBpCp pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoCApBpCp requis par la preuve de (?)OoCApBpCp pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpCp requis par la preuve de (?)OoCApBpCp pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HOoCApBpCpM3 : rk(Oo :: C :: Ap :: Bp :: Cp :: nil) <= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: Cp :: nil) (C :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: Ap :: Bp :: Cp :: nil) ((C :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (C :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (nil) 1 2 0 HCMtmp HOoApBpCpMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpCpm2 : rk(Oo :: C :: Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Cp :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Cp ::  de rang :  3 et 3 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpCpm3 : rk(Oo :: C :: Ap :: Bp :: Cp :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpCpeq : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoACApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApBpCpmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoACApBpCpeq HOoACApBpCpm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Cp :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpCpmtmp;try rewrite HT2 in HOoACApBpCpmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Cp :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpCpmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\nassert(HOoCApBpCpM : rk(Oo :: C :: Ap :: Bp :: Cp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApBpCpm : rk(Oo :: C :: Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoCApBpCpeq HOoCApBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Bp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour CBp requis par la preuve de (?)CBp pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HCBpm2 : rk(C :: Bp :: nil) >= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoCApBpCpeq : rk(Oo :: C :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoCApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApBpCpmtmp : rk(Oo :: C :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoCApBpCpeq HOoCApBpCpm3).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (C :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: Cp :: nil) (C :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((C :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpCpmtmp;try rewrite HT2 in HOoCApBpCpmtmp.\n\tassert(HT := rule_2 (C :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Bp :: nil) 3 1 2 HOoCApBpCpmtmp HBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HCBpM : rk(C :: Bp ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HCBpeq HCBpM2).\nassert(HCBpm : rk(C :: Bp ::  nil) >= 1) by (solve_hyps_min HCBpeq HCBpm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LACBp *)\n(* dans constructLemma(), requis par LACBpNP *)\n(* dans la couche 0 *)\nLemma LOoACBpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACBpNP requis par la preuve de (?)OoACBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACBpNP requis par la preuve de (?)OoACBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACBpNP requis par la preuve de (?)OoACBpNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACBpNPm2 : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : B ::   de rang : 1 et 1 *)\nassert(HOoACBpNPm3 : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HBMtmp : rk(B :: nil) <= 1) by (solve_hyps_max HBeq HBM1).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (B :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (B :: Oo :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Oo :: A :: C :: Bp :: N :: P :: nil) ((B :: nil) ++ (Oo :: A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (B :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil) (nil) 4 0 1 HOoABCBpNPmtmp Hmtmp HBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HOoACBpNPm4 : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: B :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: B :: Oo :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Oo :: A :: C :: Bp :: N :: P :: nil) ((Oo :: A :: B :: nil) ++ (Oo :: A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (Oo :: A :: C :: Bp :: N :: P :: nil) (Oo :: A :: nil) 4 2 2 HOoABCBpNPmtmp HOoAmtmp HOoABMtmp Hincl); apply HT.\n}\n\nassert(HOoACBpNPM : rk(Oo :: A :: C :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACBpNPm : rk(Oo :: A :: C :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoACBpNPeq HOoACBpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACBpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ACBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ACBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ACBpNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: B ::   de rang : 2 et 2 *)\nassert(HACBpNPm2 : rk(A :: C :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HOoBMtmp : rk(Oo :: B :: nil) <= 2) by (solve_hyps_max HOoBeq HOoBM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: B :: nil) (A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: B :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: A :: C :: Bp :: N :: P :: nil) ((Oo :: B :: nil) ++ (A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: B :: nil) (A :: C :: Bp :: N :: P :: nil) (nil) 4 0 2 HOoABCBpNPmtmp Hmtmp HOoBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HACBpNPm3 : rk(A :: C :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: B :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: C :: Bp :: N :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: C :: Bp :: N :: P :: nil) (A :: nil) 4 1 2 HOoABCBpNPmtmp HAmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A :: C ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HACBpNPm4 : rk(A :: C :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACBpNPeq : rk(Oo :: A :: C :: Bp :: N :: P :: nil) = 4) by (apply LOoACBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpNPmtmp : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoACBpNPeq HOoACBpNPm4).\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hincl : incl (A :: C :: nil) (list_inter (Oo :: A :: C :: nil) (A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: N :: P :: nil) (Oo :: A :: C :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: C :: Bp :: N :: P :: nil) ((Oo :: A :: C :: nil) ++ (A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpNPmtmp;try rewrite HT2 in HOoACBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (A :: C :: Bp :: N :: P :: nil) (A :: C :: nil) 4 2 2 HOoACBpNPmtmp HACmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HACBpNPM : rk(A :: C :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HACBpNPm : rk(A :: C :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HACBpNPeq HACBpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Bp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ACBp requis par la preuve de (?)ACBp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ACBp requis par la preuve de (?)ACBp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACBpm2 : rk(A :: C :: Bp :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Bp :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HACBpm3 : rk(A :: C :: Bp :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HACBpNPeq : rk(A :: C :: Bp :: N :: P :: nil) = 4) by (apply LACBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpNPmtmp : rk(A :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HACBpNPeq HACBpNPm4).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (A :: C :: Bp :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Bp :: N :: P :: nil) (A :: C :: Bp :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: C :: Bp :: Bp :: N :: P :: nil) ((A :: C :: Bp :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACBpNPmtmp;try rewrite HT2 in HACBpNPmtmp.\n\tassert(HT := rule_2 (A :: C :: Bp :: nil) (Bp :: N :: P :: nil) (Bp :: nil) 4 1 2 HACBpNPmtmp HBpmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HACBpM : rk(A :: C :: Bp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HACBpeq HACBpM3).\nassert(HACBpm : rk(A :: C :: Bp ::  nil) >= 1) by (solve_hyps_min HACBpeq HACBpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoACBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Bp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACBp requis par la preuve de (?)OoACBp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACBp requis par la preuve de (?)OoACBp pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACBp requis par la preuve de (?)OoACBp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACBpm2 : rk(Oo :: A :: C :: Bp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Bp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoACBpM3 : rk(Oo :: A :: C :: Bp :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HBpMtmp : rk(Bp :: nil) <= 1) by (solve_hyps_max HBpeq HBpM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: C :: nil) (Bp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: nil) (Oo :: A :: C :: Bp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Bp :: nil) ((Oo :: A :: C :: nil) ++ (Bp :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Bp :: nil) (nil) 2 1 0 HOoACMtmp HBpMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -4 et -4*)\nassert(HOoACBpm3 : rk(Oo :: A :: C :: Bp :: nil) >= 3).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoACApBpCpeq : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoACApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApBpCpmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoACApBpCpeq HOoACApBpCpm3).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: A :: C :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Cp :: nil) (Oo :: A :: C :: Bp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Bp :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: C :: Bp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpCpmtmp;try rewrite HT2 in HOoACApBpCpmtmp.\n\tassert(HT := rule_2 (Oo :: A :: C :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: Bp :: nil) 3 2 2 HOoACApBpCpmtmp HOoBpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HOoACBpM : rk(Oo :: A :: C :: Bp ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACBpm : rk(Oo :: A :: C :: Bp ::  nil) >= 1) by (solve_hyps_min HOoACBpeq HOoACBpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoApBp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: Ap :: Bp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoApBp requis par la preuve de (?)OoApBp pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoApBp requis par la preuve de (?)OoApBp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoApBpm2 : rk(Oo :: Ap :: Bp :: nil) >= 2).\n{\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (Oo :: Ap :: Bp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: Ap :: nil) (Oo :: Ap :: Bp :: nil) 2 2 HOoApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoApBpM2 : rk(Oo :: Ap :: Bp :: nil) <= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Ap :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: Ap :: Bp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) 2 2 HOoApBpCpMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoApBpM : rk(Oo :: Ap :: Bp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoApBpeq HOoApBpM3).\nassert(HOoApBpm : rk(Oo :: Ap :: Bp ::  nil) >= 1) by (solve_hyps_min HOoApBpeq HOoApBpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoACp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Cp ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACp requis par la preuve de (?)OoACp pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoACp requis par la preuve de (?)OoACp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACpm2 : rk(Oo :: A :: Cp :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Cp :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -4 et -4*)\nassert(HOoACpm3 : rk(Oo :: A :: Cp :: nil) >= 3).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(HOoAApBpCpeq : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) = 3) by (apply LOoAApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApBpCpmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HOoAApBpCpeq HOoAApBpCpm3).\n\tassert(HOoCpmtmp : rk(Oo :: Cp :: nil) >= 2) by (solve_hyps_min HOoCpeq HOoCpm2).\n\tassert(Hincl : incl (Oo :: Cp :: nil) (list_inter (Oo :: A :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: nil) (Oo :: A :: Cp :: Oo :: Ap :: Bp :: Cp :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Cp :: Oo :: Ap :: Bp :: Cp :: nil) ((Oo :: A :: Cp :: nil) ++ (Oo :: Ap :: Bp :: Cp :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpmtmp;try rewrite HT2 in HOoAApBpCpmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) (Oo :: Cp :: nil) 3 2 2 HOoAApBpCpmtmp HOoCpmtmp HOoApBpCpMtmp Hincl);apply HT.\n}\n\nassert(HOoACpM : rk(Oo :: A :: Cp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoACpeq HOoACpM3).\nassert(HOoACpm : rk(Oo :: A :: Cp ::  nil) >= 1) by (solve_hyps_min HOoACpeq HOoACpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoApCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: Ap :: Cp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoApCp requis par la preuve de (?)OoApCp pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoApCp requis par la preuve de (?)OoApCp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoApCpm2 : rk(Oo :: Ap :: Cp :: nil) >= 2).\n{\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (Oo :: Ap :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: Ap :: nil) (Oo :: Ap :: Cp :: nil) 2 2 HOoApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoApCpM2 : rk(Oo :: Ap :: Cp :: nil) <= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Ap :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: Ap :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) 2 2 HOoApBpCpMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoApCpM : rk(Oo :: Ap :: Cp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoApCpeq HOoApCpM3).\nassert(HOoApCpm : rk(Oo :: Ap :: Cp ::  nil) >= 1) by (solve_hyps_min HOoApCpeq HOoApCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: Bp :: Cp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoBpCp requis par la preuve de (?)OoBpCp pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoBpCp requis par la preuve de (?)OoBpCp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBpCpm2 : rk(Oo :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (Oo :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: Bp :: nil) (Oo :: Bp :: Cp :: nil) 2 2 HOoBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBpCpM2 : rk(Oo :: Bp :: Cp :: nil) <= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Bp :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: Bp :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) 2 2 HOoApBpCpMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoBpCpM : rk(Oo :: Bp :: Cp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoBpCpeq HOoBpCpM3).\nassert(HOoBpCpm : rk(Oo :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HOoBpCpeq HOoBpCpm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApBpCp : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: Cp ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ApBpCp requis par la preuve de (?)ApBpCp pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ApBpCp requis par la preuve de (?)ApBpCp pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HApBpCpm2 : rk(Ap :: Bp :: Cp :: nil) >= 2).\n{\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Ap :: Bp :: nil) (Ap :: Bp :: Cp :: nil) 2 2 HApBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HApBpCpM2 : rk(Ap :: Bp :: Cp :: nil) <= 2).\n{\n\tassert(HOoApBpCpMtmp : rk(Oo :: Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoApBpCpeq HOoApBpCpM2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Ap :: Bp :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Ap :: Bp :: Cp :: nil) (Oo :: Ap :: Bp :: Cp :: nil) 2 2 HOoApBpCpMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HApBpCpM : rk(Ap :: Bp :: Cp ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HApBpCpeq HApBpCpM3).\nassert(HApBpCpm : rk(Ap :: Bp :: Cp ::  nil) >= 1) by (solve_hyps_min HApBpCpeq HApBpCpm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAX *)\n(* dans constructLemma(), requis par LABApX *)\n(* dans la couche 0 *)\nLemma LOoABApX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABApX requis par la preuve de (?)OoABApX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApX requis par la preuve de (?)OoABApX pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApX requis par la preuve de (?)OoABApX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApXm2 : rk(Oo :: A :: B :: Ap :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABApXM3 : rk(Oo :: A :: B :: Ap :: X :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: Ap :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: X :: nil) (Oo :: A :: B :: B :: Ap :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: Ap :: X :: nil) ((Oo :: A :: B :: nil) ++ (B :: Ap :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (B :: Ap :: X :: nil) (B :: nil) 2 2 1 HOoABMtmp HBApXMtmp HBmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApXm3 : rk(Oo :: A :: B :: Ap :: X :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: X :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABApXM : rk(Oo :: A :: B :: Ap :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApXm : rk(Oo :: A :: B :: Ap :: X ::  nil) >= 1) by (solve_hyps_min HOoABApXeq HOoABApXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABApX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Ap :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABApX requis par la preuve de (?)ABApX pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABApX requis par la preuve de (?)ABApX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABApX requis par la preuve de (?)ABApX pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HABApXM3 : rk(A :: B :: Ap :: X :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (B :: Ap :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Ap :: X :: nil) (A :: B :: Ap :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: Ap :: X :: nil) ((A :: nil) ++ (B :: Ap :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (B :: Ap :: X :: nil) (nil) 1 2 0 HAMtmp HBApXMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABApXm2 : rk(A :: B :: Ap :: X :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Ap :: X :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: X ::  de rang :  3 et 3 \t AiB : A :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HABApXm3 : rk(A :: B :: Ap :: X :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABApXeq : rk(Oo :: A :: B :: Ap :: X :: nil) = 3) by (apply LOoABApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApXmtmp : rk(Oo :: A :: B :: Ap :: X :: nil) >= 3) by (solve_hyps_min HOoABApXeq HOoABApXm3).\n\tassert(HABApeq : rk(A :: B :: Ap :: nil) = 3) by (apply LABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApmtmp : rk(A :: B :: Ap :: nil) >= 3) by (solve_hyps_min HABApeq HABApm3).\n\tassert(Hincl : incl (A :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (A :: B :: Ap :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: X :: nil) (Oo :: A :: B :: Ap :: A :: B :: Ap :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: A :: B :: Ap :: X :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (A :: B :: Ap :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApXmtmp;try rewrite HT2 in HOoABApXmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (A :: B :: Ap :: X :: nil) (A :: B :: Ap :: nil) 3 3 3 HOoABApXmtmp HABApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\nassert(HABApXM : rk(A :: B :: Ap :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABApXm : rk(A :: B :: Ap :: X ::  nil) >= 1) by (solve_hyps_min HABApXeq HABApXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: X ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AX requis par la preuve de (?)AX pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HAXm2 : rk(A :: X :: nil) >= 2).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HABApXeq : rk(A :: B :: Ap :: X :: nil) = 3) by (apply LABApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApXmtmp : rk(A :: B :: Ap :: X :: nil) >= 3) by (solve_hyps_min HABApXeq HABApXm3).\n\tassert(HXmtmp : rk(X :: nil) >= 1) by (solve_hyps_min HXeq HXm1).\n\tassert(Hincl : incl (X :: nil) (list_inter (A :: X :: nil) (B :: Ap :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Ap :: X :: nil) (A :: X :: B :: Ap :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: X :: B :: Ap :: X :: nil) ((A :: X :: nil) ++ (B :: Ap :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABApXmtmp;try rewrite HT2 in HABApXmtmp.\n\tassert(HT := rule_2 (A :: X :: nil) (B :: Ap :: X :: nil) (X :: nil) 3 1 2 HABApXmtmp HXmtmp HBApXMtmp Hincl);apply HT.\n}\n\nassert(HAXM : rk(A :: X ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HAXeq HAXM2).\nassert(HAXm : rk(A :: X ::  nil) >= 1) by (solve_hyps_min HAXeq HAXm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoAX *)\n(* dans la couche 0 *)\nLemma LOoABpX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABpX requis par la preuve de (?)OoABpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoABpX requis par la preuve de (?)OoABpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABpX requis par la preuve de (?)OoABpX pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HOoABpXM3 : rk(Oo :: A :: Bp :: X :: nil) <= 3).\n{\n\tassert(HOoMtmp : rk(Oo :: nil) <= 1) by (solve_hyps_max HOoeq HOoM1).\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: X :: nil) (Oo :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Bp :: X :: nil) ((Oo :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: nil) (A :: Bp :: X :: nil) (nil) 1 2 0 HOoMtmp HABpXMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpXm2 : rk(Oo :: A :: Bp :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABpXm3 : rk(Oo :: A :: Bp :: X :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: X :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABpXM : rk(Oo :: A :: Bp :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABpXm : rk(Oo :: A :: Bp :: X ::  nil) >= 1) by (solve_hyps_min HOoABpXeq HOoABpXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAX requis par la preuve de (?)OoAX pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAX requis par la preuve de (?)OoAX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXm2 : rk(Oo :: A :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAXm3 : rk(Oo :: A :: X :: nil) >= 3).\n{\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HOoABpXeq : rk(Oo :: A :: Bp :: X :: nil) = 3) by (apply LOoABpX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpXmtmp : rk(Oo :: A :: Bp :: X :: nil) >= 3) by (solve_hyps_min HOoABpXeq HOoABpXm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: X :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: X :: nil) (Oo :: A :: X :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: X :: A :: Bp :: X :: nil) ((Oo :: A :: X :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpXmtmp;try rewrite HT2 in HOoABpXmtmp.\n\tassert(HT := rule_2 (Oo :: A :: X :: nil) (A :: Bp :: X :: nil) (A :: X :: nil) 3 2 2 HOoABpXmtmp HAXmtmp HABpXMtmp Hincl);apply HT.\n}\n\nassert(HOoAXM : rk(Oo :: A :: X ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoAXeq HOoAXM3).\nassert(HOoAXm : rk(Oo :: A :: X ::  nil) >= 1) by (solve_hyps_min HOoAXeq HOoAXm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBX *)\n(* dans constructLemma(), requis par LABBpX *)\n(* dans la couche 0 *)\nLemma LOoABBpX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Bp :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABBpX requis par la preuve de (?)OoABBpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBpX requis par la preuve de (?)OoABBpX pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBpX requis par la preuve de (?)OoABBpX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpXm2 : rk(Oo :: A :: B :: Bp :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABBpXM3 : rk(Oo :: A :: B :: Bp :: X :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: X :: nil) (Oo :: A :: B :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: Bp :: X :: nil) ((Oo :: A :: B :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (A :: Bp :: X :: nil) (A :: nil) 2 2 1 HOoABMtmp HABpXMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABBpXm3 : rk(Oo :: A :: B :: Bp :: X :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABBpXM : rk(Oo :: A :: B :: Bp :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABBpXm : rk(Oo :: A :: B :: Bp :: X ::  nil) >= 1) by (solve_hyps_min HOoABBpXeq HOoABBpXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABBpX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Bp :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABBpX requis par la preuve de (?)ABBpX pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABBpX requis par la preuve de (?)ABBpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABBpX requis par la preuve de (?)ABBpX pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HABBpXM3 : rk(A :: B :: Bp :: X :: nil) <= 3).\n{\n\tassert(HBMtmp : rk(B :: nil) <= 1) by (solve_hyps_max HBeq HBM1).\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (B :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Bp :: X :: nil) (B :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: A :: Bp :: X :: nil) ((B :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (B :: nil) (A :: Bp :: X :: nil) (nil) 1 2 0 HBMtmp HABpXMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABBpXm2 : rk(A :: B :: Bp :: X :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Bp :: X :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Bp :: X ::  de rang :  3 et 3 \t AiB : A :: B :: Bp ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Bp ::   de rang : 3 et 3 *)\nassert(HABBpXm3 : rk(A :: B :: Bp :: X :: nil) >= 3).\n{\n\tassert(HOoABBpeq : rk(Oo :: A :: B :: Bp :: nil) = 3) by (apply LOoABBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpMtmp : rk(Oo :: A :: B :: Bp :: nil) <= 3) by (solve_hyps_max HOoABBpeq HOoABBpM3).\n\tassert(HOoABBpXeq : rk(Oo :: A :: B :: Bp :: X :: nil) = 3) by (apply LOoABBpX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpXmtmp : rk(Oo :: A :: B :: Bp :: X :: nil) >= 3) by (solve_hyps_min HOoABBpXeq HOoABBpXm3).\n\tassert(HABBpeq : rk(A :: B :: Bp :: nil) = 3) by (apply LABBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABBpmtmp : rk(A :: B :: Bp :: nil) >= 3) by (solve_hyps_min HABBpeq HABBpm3).\n\tassert(Hincl : incl (A :: B :: Bp :: nil) (list_inter (Oo :: A :: B :: Bp :: nil) (A :: B :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: X :: nil) (Oo :: A :: B :: Bp :: A :: B :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: A :: B :: Bp :: X :: nil) ((Oo :: A :: B :: Bp :: nil) ++ (A :: B :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABBpXmtmp;try rewrite HT2 in HOoABBpXmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Bp :: nil) (A :: B :: Bp :: X :: nil) (A :: B :: Bp :: nil) 3 3 3 HOoABBpXmtmp HABBpmtmp HOoABBpMtmp Hincl); apply HT.\n}\n\nassert(HABBpXM : rk(A :: B :: Bp :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABBpXm : rk(A :: B :: Bp :: X ::  nil) >= 1) by (solve_hyps_min HABBpXeq HABBpXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: X ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BX requis par la preuve de (?)BX pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBXm2 : rk(B :: X :: nil) >= 2).\n{\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HABBpXeq : rk(A :: B :: Bp :: X :: nil) = 3) by (apply LABBpX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABBpXmtmp : rk(A :: B :: Bp :: X :: nil) >= 3) by (solve_hyps_min HABBpXeq HABBpXm3).\n\tassert(HXmtmp : rk(X :: nil) >= 1) by (solve_hyps_min HXeq HXm1).\n\tassert(Hincl : incl (X :: nil) (list_inter (B :: X :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Bp :: X :: nil) (B :: X :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: X :: A :: Bp :: X :: nil) ((B :: X :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABBpXmtmp;try rewrite HT2 in HABBpXmtmp.\n\tassert(HT := rule_2 (B :: X :: nil) (A :: Bp :: X :: nil) (X :: nil) 3 1 2 HABBpXmtmp HXmtmp HABpXMtmp Hincl);apply HT.\n}\n\nassert(HBXM : rk(B :: X ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBXeq HBXM2).\nassert(HBXm : rk(B :: X ::  nil) >= 1) by (solve_hyps_min HBXeq HBXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABX requis par la preuve de (?)OoABX pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABX requis par la preuve de (?)OoABX pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABX requis par la preuve de (?)OoABX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXm2 : rk(Oo :: A :: B :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABXM3 : rk(Oo :: A :: B :: X :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HXMtmp : rk(X :: nil) <= 1) by (solve_hyps_max HXeq HXM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: nil) (Oo :: A :: B :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: nil) ((Oo :: A :: B :: nil) ++ (X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (X :: nil) (nil) 2 1 0 HOoABMtmp HXMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoABXm3 : rk(Oo :: A :: B :: X :: nil) >= 3).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HOoABApXeq : rk(Oo :: A :: B :: Ap :: X :: nil) = 3) by (apply LOoABApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApXmtmp : rk(Oo :: A :: B :: Ap :: X :: nil) >= 3) by (solve_hyps_min HOoABApXeq HOoABApXm3).\n\tassert(HBXeq : rk(B :: X :: nil) = 2) by (apply LBX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBXmtmp : rk(B :: X :: nil) >= 2) by (solve_hyps_min HBXeq HBXm2).\n\tassert(Hincl : incl (B :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (B :: Ap :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: X :: nil) (Oo :: A :: B :: X :: B :: Ap :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: B :: Ap :: X :: nil) ((Oo :: A :: B :: X :: nil) ++ (B :: Ap :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApXmtmp;try rewrite HT2 in HOoABApXmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: X :: nil) (B :: Ap :: X :: nil) (B :: X :: nil) 3 2 2 HOoABApXmtmp HBXmtmp HBApXMtmp Hincl);apply HT.\n}\n\nassert(HOoABXM : rk(Oo :: A :: B :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABXm : rk(Oo :: A :: B :: X ::  nil) >= 1) by (solve_hyps_min HOoABXeq HOoABXm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LApX *)\n(* dans constructLemma(), requis par LAApBpX *)\n(* dans la couche 0 *)\nLemma LOoAApBpX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Bp :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApBpX requis par la preuve de (?)OoAApBpX pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApBpX requis par la preuve de (?)OoAApBpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApBpX requis par la preuve de (?)OoAApBpX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpXm2 : rk(Oo :: A :: Ap :: Bp :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpXm3 : rk(Oo :: A :: Ap :: Bp :: X :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: X :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoAApBpXM3 : rk(Oo :: A :: Ap :: Bp :: X :: nil) <= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: X :: nil) (Oo :: Ap :: Bp :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: A :: Bp :: X :: nil) ((Oo :: Ap :: Bp :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: Ap :: Bp :: nil) (A :: Bp :: X :: nil) (Bp :: nil) 2 2 1 HOoApBpMtmp HABpXMtmp HBpmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HOoAApBpXM : rk(Oo :: A :: Ap :: Bp :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApBpXm : rk(Oo :: A :: Ap :: Bp :: X ::  nil) >= 1) by (solve_hyps_min HOoAApBpXeq HOoAApBpXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAApBpX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap :: Bp :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AApBpX requis par la preuve de (?)AApBpX pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AApBpX requis par la preuve de (?)AApBpX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AApBpX requis par la preuve de (?)AApBpX pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HAApBpXM3 : rk(A :: Ap :: Bp :: X :: nil) <= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: Bp :: X :: nil) (Ap :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: A :: Bp :: X :: nil) ((Ap :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Ap :: nil) (A :: Bp :: X :: nil) (nil) 1 2 0 HApMtmp HABpXMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAApBpXm2 : rk(A :: Ap :: Bp :: X :: nil) >= 2).\n{\n\tassert(HAApeq : rk(A :: Ap :: nil) = 2) by (apply LAAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApmtmp : rk(A :: Ap :: nil) >= 2) by (solve_hyps_min HAApeq HAApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: Ap :: nil) (A :: Ap :: Bp :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: Ap :: nil) (A :: Ap :: Bp :: X :: nil) 2 2 HAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: X ::  de rang :  3 et 3 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HAApBpXm3 : rk(A :: Ap :: Bp :: X :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoAApBpXeq : rk(Oo :: A :: Ap :: Bp :: X :: nil) = 3) by (apply LOoAApBpX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApBpXmtmp : rk(Oo :: A :: Ap :: Bp :: X :: nil) >= 3) by (solve_hyps_min HOoAApBpXeq HOoAApBpXm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: X :: nil) (Oo :: Ap :: Bp :: A :: Ap :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: A :: Ap :: Bp :: X :: nil) ((Oo :: Ap :: Bp :: nil) ++ (A :: Ap :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpXmtmp;try rewrite HT2 in HOoAApBpXmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: X :: nil) (Ap :: Bp :: nil) 3 2 2 HOoAApBpXmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\nassert(HAApBpXM : rk(A :: Ap :: Bp :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAApBpXm : rk(A :: Ap :: Bp :: X ::  nil) >= 1) by (solve_hyps_min HAApBpXeq HAApBpXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: X ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour ApX requis par la preuve de (?)ApX pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HApXm2 : rk(Ap :: X :: nil) >= 2).\n{\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HAApBpXeq : rk(A :: Ap :: Bp :: X :: nil) = 3) by (apply LAApBpX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApBpXmtmp : rk(A :: Ap :: Bp :: X :: nil) >= 3) by (solve_hyps_min HAApBpXeq HAApBpXm3).\n\tassert(HXmtmp : rk(X :: nil) >= 1) by (solve_hyps_min HXeq HXm1).\n\tassert(Hincl : incl (X :: nil) (list_inter (Ap :: X :: nil) (A :: Bp :: X :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: Bp :: X :: nil) (Ap :: X :: A :: Bp :: X :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: X :: A :: Bp :: X :: nil) ((Ap :: X :: nil) ++ (A :: Bp :: X :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApBpXmtmp;try rewrite HT2 in HAApBpXmtmp.\n\tassert(HT := rule_2 (Ap :: X :: nil) (A :: Bp :: X :: nil) (X :: nil) 3 1 2 HAApBpXmtmp HXmtmp HABpXMtmp Hincl);apply HT.\n}\n\nassert(HApXM : rk(Ap :: X ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HApXeq HApXM2).\nassert(HApXm : rk(Ap :: X ::  nil) >= 1) by (solve_hyps_min HApXeq HApXm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAApX : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: X ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApX requis par la preuve de (?)OoAApX pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApX requis par la preuve de (?)OoAApX pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApX requis par la preuve de (?)OoAApX pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXm2 : rk(Oo :: A :: Ap :: X :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: X :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXm3 : rk(Oo :: A :: Ap :: X :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAApXM3 : rk(Oo :: A :: Ap :: X :: nil) <= 3).\n{\n\tassert(HOoABApXeq : rk(Oo :: A :: B :: Ap :: X :: nil) = 3) by (apply LOoABApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApXMtmp : rk(Oo :: A :: B :: Ap :: X :: nil) <= 3) by (solve_hyps_max HOoABApXeq HOoABApXM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: X :: nil) (Oo :: A :: B :: Ap :: X :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: Ap :: X :: nil) (Oo :: A :: B :: Ap :: X :: nil) 3 3 HOoABApXMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAApXM : rk(Oo :: A :: Ap :: X ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApXm : rk(Oo :: A :: Ap :: X ::  nil) >= 1) by (solve_hyps_min HOoAApXeq HOoAApXm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAY *)\n(* dans constructLemma(), requis par LACApY *)\n(* dans la couche 0 *)\nLemma LOoACApY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Ap :: Y ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACApY requis par la preuve de (?)OoACApY pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApY requis par la preuve de (?)OoACApY pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApY requis par la preuve de (?)OoACApY pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApYm2 : rk(Oo :: A :: C :: Ap :: Y :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Y :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoACApYM3 : rk(Oo :: A :: C :: Ap :: Y :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(HCmtmp : rk(C :: nil) >= 1) by (solve_hyps_min HCeq HCm1).\n\tassert(Hincl : incl (C :: nil) (list_inter (Oo :: A :: C :: nil) (C :: Ap :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Y :: nil) (Oo :: A :: C :: C :: Ap :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: C :: Ap :: Y :: nil) ((Oo :: A :: C :: nil) ++ (C :: Ap :: Y :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (C :: Ap :: Y :: nil) (C :: nil) 2 2 1 HOoACMtmp HCApYMtmp HCmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApYm3 : rk(Oo :: A :: C :: Ap :: Y :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Y :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACApYM : rk(Oo :: A :: C :: Ap :: Y ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACApYm : rk(Oo :: A :: C :: Ap :: Y ::  nil) >= 1) by (solve_hyps_min HOoACApYeq HOoACApYm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACApY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Ap :: Y ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ACApY requis par la preuve de (?)ACApY pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ACApY requis par la preuve de (?)ACApY pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACApY requis par la preuve de (?)ACApY pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HACApYM3 : rk(A :: C :: Ap :: Y :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (C :: Ap :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Ap :: Y :: nil) (A :: C :: Ap :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: C :: Ap :: Y :: nil) ((A :: nil) ++ (C :: Ap :: Y :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (C :: Ap :: Y :: nil) (nil) 1 2 0 HAMtmp HCApYMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACApYm2 : rk(A :: C :: Ap :: Y :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Ap :: Y :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Y ::  de rang :  3 et 3 \t AiB : A :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HACApYm3 : rk(A :: C :: Ap :: Y :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApYeq : rk(Oo :: A :: C :: Ap :: Y :: nil) = 3) by (apply LOoACApY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApYmtmp : rk(Oo :: A :: C :: Ap :: Y :: nil) >= 3) by (solve_hyps_min HOoACApYeq HOoACApYm3).\n\tassert(HACApeq : rk(A :: C :: Ap :: nil) = 3) by (apply LACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACApmtmp : rk(A :: C :: Ap :: nil) >= 3) by (solve_hyps_min HACApeq HACApm3).\n\tassert(Hincl : incl (A :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (A :: C :: Ap :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Y :: nil) (Oo :: A :: C :: Ap :: A :: C :: Ap :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: A :: C :: Ap :: Y :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (A :: C :: Ap :: Y :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApYmtmp;try rewrite HT2 in HOoACApYmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (A :: C :: Ap :: Y :: nil) (A :: C :: Ap :: nil) 3 3 3 HOoACApYmtmp HACApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\nassert(HACApYM : rk(A :: C :: Ap :: Y ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HACApYm : rk(A :: C :: Ap :: Y ::  nil) >= 1) by (solve_hyps_min HACApYeq HACApYm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Y ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AY requis par la preuve de (?)AY pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HAYm2 : rk(A :: Y :: nil) >= 2).\n{\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(HACApYeq : rk(A :: C :: Ap :: Y :: nil) = 3) by (apply LACApY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACApYmtmp : rk(A :: C :: Ap :: Y :: nil) >= 3) by (solve_hyps_min HACApYeq HACApYm3).\n\tassert(HYmtmp : rk(Y :: nil) >= 1) by (solve_hyps_min HYeq HYm1).\n\tassert(Hincl : incl (Y :: nil) (list_inter (A :: Y :: nil) (C :: Ap :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Ap :: Y :: nil) (A :: Y :: C :: Ap :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Y :: C :: Ap :: Y :: nil) ((A :: Y :: nil) ++ (C :: Ap :: Y :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACApYmtmp;try rewrite HT2 in HACApYmtmp.\n\tassert(HT := rule_2 (A :: Y :: nil) (C :: Ap :: Y :: nil) (Y :: nil) 3 1 2 HACApYmtmp HYmtmp HCApYMtmp Hincl);apply HT.\n}\n\nassert(HAYM : rk(A :: Y ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HAYeq HAYM2).\nassert(HAYm : rk(A :: Y ::  nil) >= 1) by (solve_hyps_min HAYeq HAYm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCY *)\n(* dans constructLemma(), requis par LOoACY *)\n(* dans la couche 0 *)\nLemma LOoACCpY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Cp :: Y ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACCpY requis par la preuve de (?)OoACCpY pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACCpY requis par la preuve de (?)OoACCpY pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACCpY requis par la preuve de (?)OoACCpY pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACCpYm2 : rk(Oo :: A :: C :: Cp :: Y :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Cp :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Cp :: Y :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoACCpYM3 : rk(Oo :: A :: C :: Cp :: Y :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HACpYMtmp : rk(A :: Cp :: Y :: nil) <= 2) by (solve_hyps_max HACpYeq HACpYM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: C :: nil) (A :: Cp :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Cp :: Y :: nil) (Oo :: A :: C :: A :: Cp :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: Cp :: Y :: nil) ((Oo :: A :: C :: nil) ++ (A :: Cp :: Y :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (A :: Cp :: Y :: nil) (A :: nil) 2 2 1 HOoACMtmp HACpYMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACCpYm3 : rk(Oo :: A :: C :: Cp :: Y :: nil) >= 3).\n{\n\tassert(HOoACpeq : rk(Oo :: A :: Cp :: nil) = 3) by (apply LOoACp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACpmtmp : rk(Oo :: A :: Cp :: nil) >= 3) by (solve_hyps_min HOoACpeq HOoACpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Cp :: nil) (Oo :: A :: C :: Cp :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Cp :: nil) (Oo :: A :: C :: Cp :: Y :: nil) 3 3 HOoACpmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACCpYM : rk(Oo :: A :: C :: Cp :: Y ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACCpYm : rk(Oo :: A :: C :: Cp :: Y ::  nil) >= 1) by (solve_hyps_min HOoACCpYeq HOoACCpYm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoACY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Y ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACY requis par la preuve de (?)OoACY pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACY requis par la preuve de (?)OoACY pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACY requis par la preuve de (?)OoACY pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACYm2 : rk(Oo :: A :: C :: Y :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Y :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoACYM3 : rk(Oo :: A :: C :: Y :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HYMtmp : rk(Y :: nil) <= 1) by (solve_hyps_max HYeq HYM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: C :: nil) (Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Y :: nil) (Oo :: A :: C :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Y :: nil) ((Oo :: A :: C :: nil) ++ (Y :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Y :: nil) (nil) 2 1 0 HOoACMtmp HYMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoACYm3 : rk(Oo :: A :: C :: Y :: nil) >= 3).\n{\n\tassert(HACpYMtmp : rk(A :: Cp :: Y :: nil) <= 2) by (solve_hyps_max HACpYeq HACpYM2).\n\tassert(HOoACCpYeq : rk(Oo :: A :: C :: Cp :: Y :: nil) = 3) by (apply LOoACCpY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACCpYmtmp : rk(Oo :: A :: C :: Cp :: Y :: nil) >= 3) by (solve_hyps_min HOoACCpYeq HOoACCpYm3).\n\tassert(HAYeq : rk(A :: Y :: nil) = 2) by (apply LAY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAYmtmp : rk(A :: Y :: nil) >= 2) by (solve_hyps_min HAYeq HAYm2).\n\tassert(Hincl : incl (A :: Y :: nil) (list_inter (Oo :: A :: C :: Y :: nil) (A :: Cp :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Cp :: Y :: nil) (Oo :: A :: C :: Y :: A :: Cp :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Y :: A :: Cp :: Y :: nil) ((Oo :: A :: C :: Y :: nil) ++ (A :: Cp :: Y :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACCpYmtmp;try rewrite HT2 in HOoACCpYmtmp.\n\tassert(HT := rule_2 (Oo :: A :: C :: Y :: nil) (A :: Cp :: Y :: nil) (A :: Y :: nil) 3 2 2 HOoACCpYmtmp HAYmtmp HACpYMtmp Hincl);apply HT.\n}\n\nassert(HOoACYM : rk(Oo :: A :: C :: Y ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACYm : rk(Oo :: A :: C :: Y ::  nil) >= 1) by (solve_hyps_min HOoACYeq HOoACYm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Y ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour CY requis par la preuve de (?)CY pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 2) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Y ::  de rang :  3 et 3 \t AiB : C ::  de rang :  1 et 1 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HCYm2 : rk(C :: Y :: nil) >= 2).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACYeq : rk(Oo :: A :: C :: Y :: nil) = 3) by (apply LOoACY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACYmtmp : rk(Oo :: A :: C :: Y :: nil) >= 3) by (solve_hyps_min HOoACYeq HOoACYm3).\n\tassert(HCmtmp : rk(C :: nil) >= 1) by (solve_hyps_min HCeq HCm1).\n\tassert(Hincl : incl (C :: nil) (list_inter (Oo :: A :: C :: nil) (C :: Y :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Y :: nil) (Oo :: A :: C :: C :: Y :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: C :: Y :: nil) ((Oo :: A :: C :: nil) ++ (C :: Y :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACYmtmp;try rewrite HT2 in HOoACYmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (C :: Y :: nil) (C :: nil) 3 1 2 HOoACYmtmp HCmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HCYM : rk(C :: Y ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HCYeq HCYM2).\nassert(HCYm : rk(C :: Y ::  nil) >= 1) by (solve_hyps_min HCYeq HCYm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAApY : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Y ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApY requis par la preuve de (?)OoAApY pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApY requis par la preuve de (?)OoAApY pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApY requis par la preuve de (?)OoAApY pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYm2 : rk(Oo :: A :: Ap :: Y :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYm3 : rk(Oo :: A :: Ap :: Y :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAApYM3 : rk(Oo :: A :: Ap :: Y :: nil) <= 3).\n{\n\tassert(HOoACApYeq : rk(Oo :: A :: C :: Ap :: Y :: nil) = 3) by (apply LOoACApY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApYMtmp : rk(Oo :: A :: C :: Ap :: Y :: nil) <= 3) by (solve_hyps_max HOoACApYeq HOoACApYM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: Y :: nil) (Oo :: A :: C :: Ap :: Y :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: Ap :: Y :: nil) (Oo :: A :: C :: Ap :: Y :: nil) 3 3 HOoACApYMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAApYM : rk(Oo :: A :: Ap :: Y ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApYm : rk(Oo :: A :: Ap :: Y ::  nil) >= 1) by (solve_hyps_min HOoAApYeq HOoAApYm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAM *)\n(* dans la couche 0 *)\nLemma LAApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AApMQ requis par la preuve de (?)AApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACApMQ requis par la preuve de (?)AApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACApMQ requis par la preuve de (?)ACApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACApMQ requis par la preuve de (?)ACApMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: B ::   de rang : 2 et 2 *)\nassert(HACApMQm2 : rk(A :: C :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoBMtmp : rk(Oo :: B :: nil) <= 2) by (solve_hyps_max HOoBeq HOoBM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: B :: nil) (A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: B :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: B :: nil) ++ (A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: B :: nil) (A :: C :: Ap :: M :: Q :: nil) (nil) 4 0 2 HOoABCApMQmtmp Hmtmp HOoBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HACApMQm3 : rk(A :: C :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: C :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: B :: A :: C :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: C :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: nil) ++ (A :: C :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: C :: Ap :: M :: Q :: nil) (A :: nil) 4 1 2 HOoABCApMQmtmp HAmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AApMQ requis par la preuve de (?)AApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AApMQ requis par la preuve de (?)AApMQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HAApMQM3 : rk(A :: Ap :: M :: Q :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: Q :: nil) (A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Ap :: M :: Q :: nil) ((A :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (Ap :: M :: Q :: nil) (nil) 1 2 0 HAMtmp HApMQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -1 et -2*)\n(* ensembles concern\u00e9s AUB : A :: C :: Ap :: M :: Q ::  de rang :  3 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HAApMQm2 : rk(A :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HACApMQmtmp : rk(A :: C :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HACApMQeq HACApMQm3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Ap :: M :: Q :: nil) (C :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: A :: Ap :: M :: Q :: nil) ((C :: nil) ++ (A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACApMQmtmp;try rewrite HT2 in HACApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (A :: Ap :: M :: Q :: nil) (nil) 3 0 1 HACApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HAApMQm3 : rk(A :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: C :: nil) (A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (A :: Ap :: M :: Q :: nil) (A :: nil) 4 1 2 HOoACApMQmtmp HAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HAApMQM : rk(A :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAApMQm : rk(A :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HAApMQeq HAApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: M ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AM requis par la preuve de (?)AM pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HAMm2 : rk(A :: M :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HAApMQeq : rk(A :: Ap :: M :: Q :: nil) = 3) by (apply LAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApMQmtmp : rk(A :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HAApMQeq HAApMQm3).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: Q :: nil) (A :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: Ap :: M :: Q :: nil) ((A :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApMQmtmp;try rewrite HT2 in HAApMQmtmp.\n\tassert(HT := rule_2 (A :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 3 1 2 HAApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HAMM : rk(A :: M ::  nil) <= 2) (* dim : 3 *) 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 LOoAM *)\n(* dans constructLemma(), requis par LOoAMP *)\n(* dans la couche 0 *)\nLemma LOoAApCpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Cp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApCpMP requis par la preuve de (?)OoAApCpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApCpMP requis par la preuve de (?)OoAApCpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApCpMP requis par la preuve de (?)OoAApCpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApCpMPm2 : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApCpMPm3 : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo :: Ap ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HOoAApCpMPm4 : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Oo :: Ap :: Bp :: Oo :: A :: Ap :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: Oo :: A :: Ap :: Cp :: M :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (Oo :: A :: Ap :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (Oo :: A :: Ap :: Cp :: M :: P :: nil) (Oo :: Ap :: nil) 4 2 2 HOoAApBpCpMPmtmp HOoApmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\nassert(HOoAApCpMPM : rk(Oo :: A :: Ap :: Cp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApCpMPm : rk(Oo :: A :: Ap :: Cp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoAApCpMPeq HOoAApCpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAMP requis par la preuve de (?)OoAMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAMP requis par la preuve de (?)OoAMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAMP requis par la preuve de (?)OoAMP pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HOoAMPM3 : rk(Oo :: A :: M :: P :: nil) <= 3).\n{\n\tassert(HOoMtmp : rk(Oo :: nil) <= 1) by (solve_hyps_max HOoeq HOoM1).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: M :: P :: nil) (Oo :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: M :: P :: nil) ((Oo :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: nil) (A :: M :: P :: nil) (nil) 1 2 0 HOoMtmp HAMPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAMPm2 : rk(Oo :: A :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo ::  de rang :  1 et 1 \t A : Oo :: Ap :: Cp ::   de rang : 2 et 2 *)\nassert(HOoAMPm3 : rk(Oo :: A :: M :: P :: nil) >= 3).\n{\n\tassert(HOoApCpeq : rk(Oo :: Ap :: Cp :: nil) = 2) by (apply LOoApCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApCpMtmp : rk(Oo :: Ap :: Cp :: nil) <= 2) by (solve_hyps_max HOoApCpeq HOoApCpM2).\n\tassert(HOoAApCpMPeq : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) = 4) by (apply LOoAApCpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApCpMPmtmp : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApCpMPeq HOoAApCpMPm4).\n\tassert(HOomtmp : rk(Oo :: nil) >= 1) by (solve_hyps_min HOoeq HOom1).\n\tassert(Hincl : incl (Oo :: nil) (list_inter (Oo :: Ap :: Cp :: nil) (Oo :: A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Cp :: M :: P :: nil) (Oo :: Ap :: Cp :: Oo :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Cp :: Oo :: A :: M :: P :: nil) ((Oo :: Ap :: Cp :: nil) ++ (Oo :: A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApCpMPmtmp;try rewrite HT2 in HOoAApCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Cp :: nil) (Oo :: A :: M :: P :: nil) (Oo :: nil) 4 1 2 HOoAApCpMPmtmp HOomtmp HOoApCpMtmp Hincl); apply HT.\n}\n\nassert(HOoAMPM : rk(Oo :: A :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAMPm : rk(Oo :: A :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoAMPeq HOoAMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAM requis par la preuve de (?)OoAM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAM requis par la preuve de (?)OoAM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAMm2 : rk(Oo :: A :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAMm3 : rk(Oo :: A :: M :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoAMPeq : rk(Oo :: A :: M :: P :: nil) = 3) by (apply LOoAMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMPmtmp : rk(Oo :: A :: M :: P :: nil) >= 3) by (solve_hyps_min HOoAMPeq HOoAMPm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: M :: P :: nil) (Oo :: A :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: M :: A :: M :: P :: nil) ((Oo :: A :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAMPmtmp;try rewrite HT2 in HOoAMPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: M :: nil) (A :: M :: P :: nil) (A :: M :: nil) 3 2 2 HOoAMPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoAMM : rk(Oo :: A :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoAMeq HOoAMM3).\nassert(HOoAMm : rk(Oo :: A :: M ::  nil) >= 1) by (solve_hyps_min HOoAMeq HOoAMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: M ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BM requis par la preuve de (?)BM pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBMm2 : rk(B :: M :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (B :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: M :: Ap :: M :: Q :: nil) ((B :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 3 1 2 HBApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBMM : rk(B :: M ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBMeq HBMM2).\nassert(HBMm : rk(B :: M ::  nil) >= 1) by (solve_hyps_min HBMeq HBMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABM requis par la preuve de (?)ABM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABM requis par la preuve de (?)ABM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABMm2 : rk(A :: B :: M :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: M :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HABMm3 : rk(A :: B :: M :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HABApMQeq : rk(A :: B :: Ap :: M :: Q :: nil) = 4) by (apply LABApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApMQmtmp : rk(A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HABApMQeq HABApMQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: B :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Ap :: M :: Q :: nil) (A :: B :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: M :: Ap :: M :: Q :: nil) ((A :: B :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABApMQmtmp;try rewrite HT2 in HABApMQmtmp.\n\tassert(HT := rule_2 (A :: B :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 4 1 2 HABApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HABMM : rk(A :: B :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABMeq HABMM3).\nassert(HABMm : rk(A :: B :: M ::  nil) >= 1) by (solve_hyps_min HABMeq HABMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoABM *)\n(* dans la couche 0 *)\nLemma LOoABMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMPm2 : rk(Oo :: A :: B :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABMPM3 : rk(Oo :: A :: B :: M :: P :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: B :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: M :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HOoABMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABMPm3 : rk(Oo :: A :: B :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: P :: nil) 3 3 HOoAMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABMPM : rk(Oo :: A :: B :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABMPm : rk(Oo :: A :: B :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoABMPeq HOoABMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABM requis par la preuve de (?)OoABM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABM requis par la preuve de (?)OoABM pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABM requis par la preuve de (?)OoABM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMm2 : rk(Oo :: A :: B :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABMM3 : rk(Oo :: A :: B :: M :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: nil) (Oo :: A :: B :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: nil) ((Oo :: A :: B :: nil) ++ (M :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (M :: nil) (nil) 2 1 0 HOoABMtmp HMMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoABMm3 : rk(Oo :: A :: B :: M :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoABMPeq : rk(Oo :: A :: B :: M :: P :: nil) = 3) by (apply LOoABMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMPmtmp : rk(Oo :: A :: B :: M :: P :: nil) >= 3) by (solve_hyps_min HOoABMPeq HOoABMPm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: B :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: B :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: A :: M :: P :: nil) ((Oo :: A :: B :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABMPmtmp;try rewrite HT2 in HOoABMPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: M :: nil) (A :: M :: P :: nil) (A :: M :: nil) 3 2 2 HOoABMPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoABMM : rk(Oo :: A :: B :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABMm : rk(Oo :: A :: B :: M ::  nil) >= 1) by (solve_hyps_min HOoABMeq HOoABMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoCM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoCM requis par la preuve de (?)OoCM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoCM requis par la preuve de (?)OoCM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCMm2 : rk(Oo :: C :: M :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: M :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoCMm3 : rk(Oo :: C :: M :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoCApMQeq : rk(Oo :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApMQmtmp : rk(Oo :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoCApMQeq HOoCApMQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (Oo :: C :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: M :: Q :: nil) (Oo :: C :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: C :: M :: Ap :: M :: Q :: nil) ((Oo :: C :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApMQmtmp;try rewrite HT2 in HOoCApMQmtmp.\n\tassert(HT := rule_2 (Oo :: C :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 4 1 2 HOoCApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HOoCMM : rk(Oo :: C :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoCMeq HOoCMM3).\nassert(HOoCMm : rk(Oo :: C :: M ::  nil) >= 1) by (solve_hyps_min HOoCMeq HOoCMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ACM requis par la preuve de (?)ACM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ACM requis par la preuve de (?)ACM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACMm2 : rk(A :: C :: M :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: M :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HACMm3 : rk(A :: C :: M :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HACApMQeq : rk(A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACApMQmtmp : rk(A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HACApMQeq HACApMQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: C :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Ap :: M :: Q :: nil) (A :: C :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: C :: M :: Ap :: M :: Q :: nil) ((A :: C :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACApMQmtmp;try rewrite HT2 in HACApMQmtmp.\n\tassert(HT := rule_2 (A :: C :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 4 1 2 HACApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HACMM : rk(A :: C :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HACMeq HACMM3).\nassert(HACMm : rk(A :: C :: M ::  nil) >= 1) by (solve_hyps_min HACMeq HACMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBCM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: C :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BCM requis par la preuve de (?)BCM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BCM requis par la preuve de (?)BCM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HBCMm2 : rk(B :: C :: M :: nil) >= 2).\n{\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: C :: nil) (B :: C :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: C :: nil) (B :: C :: M :: nil) 2 2 HBCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBCMm3 : rk(B :: C :: M :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBCApMQeq : rk(B :: C :: Ap :: M :: Q :: nil) = 4) by (apply LBCApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApMQmtmp : rk(B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HBCApMQeq HBCApMQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (B :: C :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: M :: Q :: nil) (B :: C :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: C :: M :: Ap :: M :: Q :: nil) ((B :: C :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApMQmtmp;try rewrite HT2 in HBCApMQmtmp.\n\tassert(HT := rule_2 (B :: C :: M :: nil) (Ap :: M :: Q :: nil) (M :: nil) 4 1 2 HBCApMQmtmp HMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBCMM : rk(B :: C :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HBCMeq HBCMM3).\nassert(HBCMm : rk(B :: C :: M ::  nil) >= 1) by (solve_hyps_min HBCMeq HBCMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LApM *)\n(* dans la couche 0 *)\nLemma LAApMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AApMP requis par la preuve de (?)AApMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AApMP requis par la preuve de (?)AApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AApMP requis par la preuve de (?)AApMP pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HAApMPM3 : rk(A :: Ap :: M :: P :: nil) <= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: P :: nil) (Ap :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: A :: M :: P :: nil) ((Ap :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Ap :: nil) (A :: M :: P :: nil) (nil) 1 2 0 HApMtmp HAMPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAApMPm2 : rk(A :: Ap :: M :: P :: nil) >= 2).\n{\n\tassert(HAApeq : rk(A :: Ap :: nil) = 2) by (apply LAAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApmtmp : rk(A :: Ap :: nil) >= 2) by (solve_hyps_min HAApeq HAApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: Ap :: nil) (A :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: Ap :: nil) (A :: Ap :: M :: P :: nil) 2 2 HAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Ap ::  de rang :  1 et 1 \t A : Oo :: Ap :: Cp ::   de rang : 2 et 2 *)\nassert(HAApMPm3 : rk(A :: Ap :: M :: P :: nil) >= 3).\n{\n\tassert(HOoApCpeq : rk(Oo :: Ap :: Cp :: nil) = 2) by (apply LOoApCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApCpMtmp : rk(Oo :: Ap :: Cp :: nil) <= 2) by (solve_hyps_max HOoApCpeq HOoApCpM2).\n\tassert(HOoAApCpMPeq : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) = 4) by (apply LOoAApCpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApCpMPmtmp : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApCpMPeq HOoAApCpMPm4).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (Oo :: Ap :: Cp :: nil) (A :: Ap :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Cp :: M :: P :: nil) (Oo :: Ap :: Cp :: A :: Ap :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Cp :: A :: Ap :: M :: P :: nil) ((Oo :: Ap :: Cp :: nil) ++ (A :: Ap :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApCpMPmtmp;try rewrite HT2 in HOoAApCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Cp :: nil) (A :: Ap :: M :: P :: nil) (Ap :: nil) 4 1 2 HOoAApCpMPmtmp HApmtmp HOoApCpMtmp Hincl); apply HT.\n}\n\nassert(HAApMPM : rk(A :: Ap :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAApMPm : rk(A :: Ap :: M :: P ::  nil) >= 1) by (solve_hyps_min HAApMPeq HAApMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: M ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour ApM requis par la preuve de (?)ApM pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HApMm2 : rk(Ap :: M :: nil) >= 2).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAApMPeq : rk(A :: Ap :: M :: P :: nil) = 3) by (apply LAApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApMPmtmp : rk(A :: Ap :: M :: P :: nil) >= 3) by (solve_hyps_min HAApMPeq HAApMPm3).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (Ap :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: P :: nil) (Ap :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: M :: A :: M :: P :: nil) ((Ap :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApMPmtmp;try rewrite HT2 in HAApMPmtmp.\n\tassert(HT := rule_2 (Ap :: M :: nil) (A :: M :: P :: nil) (M :: nil) 3 1 2 HAApMPmtmp HMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HApMM : rk(Ap :: M ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HApMeq HApMM2).\nassert(HApMm : rk(Ap :: M ::  nil) >= 1) by (solve_hyps_min HApMeq HApMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoAApM *)\n(* dans la couche 0 *)\nLemma LOoAApMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApMP requis par la preuve de (?)OoAApMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApMP requis par la preuve de (?)OoAApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApMP requis par la preuve de (?)OoAApMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMPm2 : rk(Oo :: A :: Ap :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMPm3 : rk(Oo :: A :: Ap :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo :: Ap ::  de rang :  2 et 2 \t A : Oo :: Ap :: Cp ::   de rang : 2 et 2 *)\nassert(HOoAApMPm4 : rk(Oo :: A :: Ap :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApCpeq : rk(Oo :: Ap :: Cp :: nil) = 2) by (apply LOoApCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApCpMtmp : rk(Oo :: Ap :: Cp :: nil) <= 2) by (solve_hyps_max HOoApCpeq HOoApCpM2).\n\tassert(HOoAApCpMPeq : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) = 4) by (apply LOoAApCpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApCpMPmtmp : rk(Oo :: A :: Ap :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApCpMPeq HOoAApCpMPm4).\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (list_inter (Oo :: Ap :: Cp :: nil) (Oo :: A :: Ap :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Cp :: M :: P :: nil) (Oo :: Ap :: Cp :: Oo :: A :: Ap :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Cp :: Oo :: A :: Ap :: M :: P :: nil) ((Oo :: Ap :: Cp :: nil) ++ (Oo :: A :: Ap :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApCpMPmtmp;try rewrite HT2 in HOoAApCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Cp :: nil) (Oo :: A :: Ap :: M :: P :: nil) (Oo :: Ap :: nil) 4 2 2 HOoAApCpMPmtmp HOoApmtmp HOoApCpMtmp Hincl); apply HT.\n}\n\nassert(HOoAApMPM : rk(Oo :: A :: Ap :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApMPm : rk(Oo :: A :: Ap :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoAApMPeq HOoAApMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApM requis par la preuve de (?)OoAApM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApM requis par la preuve de (?)OoAApM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApM requis par la preuve de (?)OoAApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMm2 : rk(Oo :: A :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMm3 : rk(Oo :: A :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAApMm4 : rk(Oo :: A :: Ap :: M :: nil) >= 4).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoAApMPeq : rk(Oo :: A :: Ap :: M :: P :: nil) = 4) by (apply LOoAApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMPmtmp : rk(Oo :: A :: Ap :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApMPeq HOoAApMPm4).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: Ap :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: P :: nil) (Oo :: A :: Ap :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: M :: A :: M :: P :: nil) ((Oo :: A :: Ap :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMPmtmp;try rewrite HT2 in HOoAApMPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Ap :: M :: nil) (A :: M :: P :: nil) (A :: M :: nil) 4 2 2 HOoAApMPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoAApMM : rk(Oo :: A :: Ap :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApMm : rk(Oo :: A :: Ap :: M ::  nil) >= 1) by (solve_hyps_min HOoAApMeq HOoAApMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBApM *)\n(* dans la couche 0 *)\nLemma LOoABApMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMP requis par la preuve de (?)OoABApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMP requis par la preuve de (?)OoABApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMP requis par la preuve de (?)OoABApMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMPm2 : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMPm3 : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABApMPm4 : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: P :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABApMPM : rk(Oo :: A :: B :: Ap :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApMPm : rk(Oo :: A :: B :: Ap :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoABApMPeq HOoABApMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Ap :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BApM requis par la preuve de (?)BApM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApM requis par la preuve de (?)BApM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm2 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm3 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BApM requis par la preuve de (?)BApM pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M ::  de rang :  3 et 4 \t AiB : B :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HBApMm2 : rk(B :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABApMmtmp : rk(Oo :: A :: B :: Ap :: M :: nil) >= 3) by (solve_hyps_min HOoABApMeq HOoABApMm3).\n\tassert(HBApeq : rk(B :: Ap :: nil) = 2) by (apply LBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApmtmp : rk(B :: Ap :: nil) >= 2) by (solve_hyps_min HBApeq HBApm2).\n\tassert(Hincl : incl (B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (B :: Ap :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: B :: Ap :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: B :: Ap :: M :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (B :: Ap :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMmtmp;try rewrite HT2 in HOoABApMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (B :: Ap :: M :: nil) (B :: Ap :: nil) 3 2 3 HOoABApMmtmp HBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HBApMm3 : rk(B :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoABMPeq : rk(Oo :: A :: B :: M :: P :: nil) = 3) by (apply LOoABMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMPMtmp : rk(Oo :: A :: B :: M :: P :: nil) <= 3) by (solve_hyps_max HOoABMPeq HOoABMPM3).\n\tassert(HOoABApMPeq : rk(Oo :: A :: B :: Ap :: M :: P :: nil) = 4) by (apply LOoABApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMPmtmp : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 4) by (solve_hyps_min HOoABApMPeq HOoABApMPm4).\n\tassert(HBMeq : rk(B :: M :: nil) = 2) by (apply LBM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMmtmp : rk(B :: M :: nil) >= 2) by (solve_hyps_min HBMeq HBMm2).\n\tassert(Hincl : incl (B :: M :: nil) (list_inter (B :: Ap :: M :: nil) (Oo :: A :: B :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: P :: nil) (B :: Ap :: M :: Oo :: A :: B :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: M :: Oo :: A :: B :: M :: P :: nil) ((B :: Ap :: M :: nil) ++ (Oo :: A :: B :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMPmtmp;try rewrite HT2 in HOoABApMPmtmp.\n\tassert(HT := rule_2 (B :: Ap :: M :: nil) (Oo :: A :: B :: M :: P :: nil) (B :: M :: nil) 4 2 3 HOoABApMPmtmp HBMmtmp HOoABMPMtmp Hincl);apply HT.\n}\n\nassert(HBApMM : rk(B :: Ap :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HBApMeq HBApMM3).\nassert(HBApMm : rk(B :: Ap :: M ::  nil) >= 1) by (solve_hyps_min HBApMeq HBApMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: Ap :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABApM requis par la preuve de (?)ABApM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApM requis par la preuve de (?)ABApM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm2 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm3 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABApM requis par la preuve de (?)ABApM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABApM requis par la preuve de (?)ABApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABApMm2 : rk(A :: B :: Ap :: M :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: Ap :: M :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M ::  de rang :  3 et 4 \t AiB : A :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HABApMm3 : rk(A :: B :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABApMmtmp : rk(Oo :: A :: B :: Ap :: M :: nil) >= 3) by (solve_hyps_min HOoABApMeq HOoABApMm3).\n\tassert(HABApeq : rk(A :: B :: Ap :: nil) = 3) by (apply LABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApmtmp : rk(A :: B :: Ap :: nil) >= 3) by (solve_hyps_min HABApeq HABApm3).\n\tassert(Hincl : incl (A :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (A :: B :: Ap :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: A :: B :: Ap :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: A :: B :: Ap :: M :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (A :: B :: Ap :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMmtmp;try rewrite HT2 in HOoABApMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (A :: B :: Ap :: M :: nil) (A :: B :: Ap :: nil) 3 3 3 HOoABApMmtmp HABApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HABApMm4 : rk(A :: B :: Ap :: M :: nil) >= 4).\n{\n\tassert(HOoABMPeq : rk(Oo :: A :: B :: M :: P :: nil) = 3) by (apply LOoABMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMPMtmp : rk(Oo :: A :: B :: M :: P :: nil) <= 3) by (solve_hyps_max HOoABMPeq HOoABMPM3).\n\tassert(HOoABApMPeq : rk(Oo :: A :: B :: Ap :: M :: P :: nil) = 4) by (apply LOoABApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMPmtmp : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 4) by (solve_hyps_min HOoABApMPeq HOoABApMPm4).\n\tassert(HABMeq : rk(A :: B :: M :: nil) = 3) by (apply LABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABMmtmp : rk(A :: B :: M :: nil) >= 3) by (solve_hyps_min HABMeq HABMm3).\n\tassert(Hincl : incl (A :: B :: M :: nil) (list_inter (A :: B :: Ap :: M :: nil) (Oo :: A :: B :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: P :: nil) (A :: B :: Ap :: M :: Oo :: A :: B :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: Ap :: M :: Oo :: A :: B :: M :: P :: nil) ((A :: B :: Ap :: M :: nil) ++ (Oo :: A :: B :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMPmtmp;try rewrite HT2 in HOoABApMPmtmp.\n\tassert(HT := rule_2 (A :: B :: Ap :: M :: nil) (Oo :: A :: B :: M :: P :: nil) (A :: B :: M :: nil) 4 3 3 HOoABApMPmtmp HABMmtmp HOoABMPMtmp Hincl);apply HT.\n}\n\nassert(HABApMM : rk(A :: B :: Ap :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABApMm : rk(A :: B :: Ap :: M ::  nil) >= 1) by (solve_hyps_min HABApMeq HABApMm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApM requis par la preuve de (?)OoABApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm2 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMm3 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoABApMm4 : rk(Oo :: A :: B :: Ap :: M :: nil) >= 4).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoABApMPeq : rk(Oo :: A :: B :: Ap :: M :: P :: nil) = 4) by (apply LOoABApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMPmtmp : rk(Oo :: A :: B :: Ap :: M :: P :: nil) >= 4) by (solve_hyps_min HOoABApMPeq HOoABApMPm4).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: B :: Ap :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: P :: nil) (Oo :: A :: B :: Ap :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: M :: A :: M :: P :: nil) ((Oo :: A :: B :: Ap :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMPmtmp;try rewrite HT2 in HOoABApMPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: Ap :: M :: nil) (A :: M :: P :: nil) (A :: M :: nil) 4 2 2 HOoABApMPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoABApMM : rk(Oo :: A :: B :: Ap :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApMm : rk(Oo :: A :: B :: Ap :: M ::  nil) >= 1) by (solve_hyps_min HOoABApMeq HOoABApMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoCApM *)\n(* dans la couche 0 *)\nLemma LOoACApMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Ap :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApMP requis par la preuve de (?)OoACApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApMP requis par la preuve de (?)OoACApMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApMP requis par la preuve de (?)OoACApMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApMPm2 : rk(Oo :: A :: C :: Ap :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApMPm3 : rk(Oo :: A :: C :: Ap :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACApMPm4 : rk(Oo :: A :: C :: Ap :: M :: P :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: C :: Ap :: M :: P :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACApMPM : rk(Oo :: A :: C :: Ap :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACApMPm : rk(Oo :: A :: C :: Ap :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoACApMPeq HOoACApMPm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoCApM *)\n(* dans la couche 0 *)\nLemma LOoACMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoACMP requis par la preuve de (?)OoACMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACMP requis par la preuve de (?)OoACMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACMP requis par la preuve de (?)OoACMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACMPm2 : rk(Oo :: A :: C :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoACMPM3 : rk(Oo :: A :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: C :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: M :: P :: nil) (Oo :: A :: C :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: M :: P :: nil) ((Oo :: A :: C :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HOoACMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACMPm3 : rk(Oo :: A :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: C :: M :: P :: nil) 3 3 HOoAMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACMPM : rk(Oo :: A :: C :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACMPm : rk(Oo :: A :: C :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoACMPeq HOoACMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoCApM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApM requis par la preuve de (?)OoCApM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApM requis par la preuve de (?)OoCApM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApM requis par la preuve de (?)OoACApM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApM requis par la preuve de (?)OoACApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApMm2 : rk(Oo :: A :: C :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApMm3 : rk(Oo :: A :: C :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApM requis par la preuve de (?)OoCApM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApM requis par la preuve de (?)OoCApM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApMm2 : rk(Oo :: C :: Ap :: M :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: M :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApMm3 : rk(Oo :: C :: Ap :: M :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApMmtmp : rk(Oo :: A :: C :: Ap :: M :: nil) >= 3) by (solve_hyps_min HOoACApMeq HOoACApMm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: M :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMmtmp;try rewrite HT2 in HOoACApMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApMmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HOoCApMm4 : rk(Oo :: C :: Ap :: M :: nil) >= 4).\n{\n\tassert(HOoACMPeq : rk(Oo :: A :: C :: M :: P :: nil) = 3) by (apply LOoACMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMPMtmp : rk(Oo :: A :: C :: M :: P :: nil) <= 3) by (solve_hyps_max HOoACMPeq HOoACMPM3).\n\tassert(HOoACApMPeq : rk(Oo :: A :: C :: Ap :: M :: P :: nil) = 4) by (apply LOoACApMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMPmtmp : rk(Oo :: A :: C :: Ap :: M :: P :: nil) >= 4) by (solve_hyps_min HOoACApMPeq HOoACApMPm4).\n\tassert(HOoCMeq : rk(Oo :: C :: M :: nil) = 3) by (apply LOoCM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCMmtmp : rk(Oo :: C :: M :: nil) >= 3) by (solve_hyps_min HOoCMeq HOoCMm3).\n\tassert(Hincl : incl (Oo :: C :: M :: nil) (list_inter (Oo :: C :: Ap :: M :: nil) (Oo :: A :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: P :: nil) (Oo :: C :: Ap :: M :: Oo :: A :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: C :: Ap :: M :: Oo :: A :: C :: M :: P :: nil) ((Oo :: C :: Ap :: M :: nil) ++ (Oo :: A :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMPmtmp;try rewrite HT2 in HOoACApMPmtmp.\n\tassert(HT := rule_2 (Oo :: C :: Ap :: M :: nil) (Oo :: A :: C :: M :: P :: nil) (Oo :: C :: M :: nil) 4 3 3 HOoACApMPmtmp HOoCMmtmp HOoACMPMtmp Hincl);apply HT.\n}\n\nassert(HOoCApMM : rk(Oo :: C :: Ap :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApMm : rk(Oo :: C :: Ap :: M ::  nil) >= 1) by (solve_hyps_min HOoCApMeq HOoCApMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoABpM *)\n(* dans constructLemma(), requis par LOoABpMP *)\n(* dans la couche 0 *)\nLemma LOoABpCpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp :: Cp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABpCpMP requis par la preuve de (?)OoABpCpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABpCpMP requis par la preuve de (?)OoABpCpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABpCpMP requis par la preuve de (?)OoABpCpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpCpMPm2 : rk(Oo :: A :: Bp :: Cp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoABpCpMPm3 : rk(Oo :: A :: Bp :: Cp :: M :: P :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Ap :: Oo :: A :: Bp :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: A :: Bp :: Cp :: M :: P :: nil) ((Ap :: nil) ++ (Oo :: A :: Bp :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil) (nil) 4 0 1 HOoAApBpCpMPmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HOoABpCpMPm4 : rk(Oo :: A :: Bp :: Cp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Oo :: Ap :: Bp :: Oo :: A :: Bp :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: Oo :: A :: Bp :: Cp :: M :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (Oo :: A :: Bp :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (Oo :: A :: Bp :: Cp :: M :: P :: nil) (Oo :: Bp :: nil) 4 2 2 HOoAApBpCpMPmtmp HOoBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\nassert(HOoABpCpMPM : rk(Oo :: A :: Bp :: Cp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABpCpMPm : rk(Oo :: A :: Bp :: Cp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoABpCpMPeq HOoABpCpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABpMP requis par la preuve de (?)OoABpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABpMP requis par la preuve de (?)OoABpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABpMP requis par la preuve de (?)OoABpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpMPm2 : rk(Oo :: A :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABpMPm3 : rk(Oo :: A :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: M :: P :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo :: Bp ::  de rang :  2 et 2 \t A : Oo :: Bp :: Cp ::   de rang : 2 et 2 *)\nassert(HOoABpMPm4 : rk(Oo :: A :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoBpCpeq : rk(Oo :: Bp :: Cp :: nil) = 2) by (apply LOoBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBpCpMtmp : rk(Oo :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoBpCpeq HOoBpCpM2).\n\tassert(HOoABpCpMPeq : rk(Oo :: A :: Bp :: Cp :: M :: P :: nil) = 4) by (apply LOoABpCpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpCpMPmtmp : rk(Oo :: A :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoABpCpMPeq HOoABpCpMPm4).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: Bp :: Cp :: nil) (Oo :: A :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: Cp :: M :: P :: nil) (Oo :: Bp :: Cp :: Oo :: A :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Bp :: Cp :: Oo :: A :: Bp :: M :: P :: nil) ((Oo :: Bp :: Cp :: nil) ++ (Oo :: A :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpCpMPmtmp;try rewrite HT2 in HOoABpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Bp :: Cp :: nil) (Oo :: A :: Bp :: M :: P :: nil) (Oo :: Bp :: nil) 4 2 2 HOoABpCpMPmtmp HOoBpmtmp HOoBpCpMtmp Hincl); apply HT.\n}\n\nassert(HOoABpMPM : rk(Oo :: A :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABpMPm : rk(Oo :: A :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoABpMPeq HOoABpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABpM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABpM requis par la preuve de (?)OoABpM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABpM requis par la preuve de (?)OoABpM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABpM requis par la preuve de (?)OoABpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpMm2 : rk(Oo :: A :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABpMm3 : rk(Oo :: A :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: Bp :: M :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoABpMm4 : rk(Oo :: A :: Bp :: M :: nil) >= 4).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoABpMPeq : rk(Oo :: A :: Bp :: M :: P :: nil) = 4) by (apply LOoABpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpMPmtmp : rk(Oo :: A :: Bp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoABpMPeq HOoABpMPm4).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: Bp :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: M :: P :: nil) (Oo :: A :: Bp :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Bp :: M :: A :: M :: P :: nil) ((Oo :: A :: Bp :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpMPmtmp;try rewrite HT2 in HOoABpMPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Bp :: M :: nil) (A :: M :: P :: nil) (A :: M :: nil) 4 2 2 HOoABpMPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoABpMM : rk(Oo :: A :: Bp :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABpMm : rk(Oo :: A :: Bp :: M ::  nil) >= 1) by (solve_hyps_min HOoABpMeq HOoABpMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LACBpM *)\n(* dans la couche 0 *)\nLemma LOoACBpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: C :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACBpMP requis par la preuve de (?)OoACBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACBpMP requis par la preuve de (?)OoACBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACBpMP requis par la preuve de (?)OoACBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACBpMPm2 : rk(Oo :: A :: C :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACBpMPm3 : rk(Oo :: A :: C :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACBpMPm4 : rk(Oo :: A :: C :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoABpMeq : rk(Oo :: A :: Bp :: M :: nil) = 4) by (apply LOoABpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpMmtmp : rk(Oo :: A :: Bp :: M :: nil) >= 4) by (solve_hyps_min HOoABpMeq HOoABpMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: M :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: M :: nil) (Oo :: A :: C :: Bp :: M :: P :: nil) 4 4 HOoABpMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoACBpMPM : rk(Oo :: A :: C :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoACBpMPm : rk(Oo :: A :: C :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoACBpMPeq HOoACBpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACBpM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Bp :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACBpM requis par la preuve de (?)ACBpM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACBpM requis par la preuve de (?)ACBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACBpM requis par la preuve de (?)OoACBpM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACBpM requis par la preuve de (?)OoACBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACBpMm2 : rk(Oo :: A :: C :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Bp :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACBpMm3 : rk(Oo :: A :: C :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: M :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACBpM requis par la preuve de (?)ACBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACBpM requis par la preuve de (?)ACBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACBpMm2 : rk(A :: C :: Bp :: M :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Bp :: M :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: M ::  de rang :  3 et 4 \t AiB : A :: C :: Bp ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Bp ::   de rang : 3 et 3 *)\nassert(HACBpMm3 : rk(A :: C :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoACBpeq : rk(Oo :: A :: C :: Bp :: nil) = 3) by (apply LOoACBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpMtmp : rk(Oo :: A :: C :: Bp :: nil) <= 3) by (solve_hyps_max HOoACBpeq HOoACBpM3).\n\tassert(HOoACBpMmtmp : rk(Oo :: A :: C :: Bp :: M :: nil) >= 3) by (solve_hyps_min HOoACBpMeq HOoACBpMm3).\n\tassert(HACBpeq : rk(A :: C :: Bp :: nil) = 3) by (apply LACBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpmtmp : rk(A :: C :: Bp :: nil) >= 3) by (solve_hyps_min HACBpeq HACBpm3).\n\tassert(Hincl : incl (A :: C :: Bp :: nil) (list_inter (Oo :: A :: C :: Bp :: nil) (A :: C :: Bp :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: M :: nil) (Oo :: A :: C :: Bp :: A :: C :: Bp :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Bp :: A :: C :: Bp :: M :: nil) ((Oo :: A :: C :: Bp :: nil) ++ (A :: C :: Bp :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpMmtmp;try rewrite HT2 in HOoACBpMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Bp :: nil) (A :: C :: Bp :: M :: nil) (A :: C :: Bp :: nil) 3 3 3 HOoACBpMmtmp HACBpmtmp HOoACBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HACBpMm4 : rk(A :: C :: Bp :: M :: nil) >= 4).\n{\n\tassert(HOoACMPeq : rk(Oo :: A :: C :: M :: P :: nil) = 3) by (apply LOoACMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMPMtmp : rk(Oo :: A :: C :: M :: P :: nil) <= 3) by (solve_hyps_max HOoACMPeq HOoACMPM3).\n\tassert(HOoACBpMPeq : rk(Oo :: A :: C :: Bp :: M :: P :: nil) = 4) by (apply LOoACBpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpMPmtmp : rk(Oo :: A :: C :: Bp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoACBpMPeq HOoACBpMPm4).\n\tassert(HACMeq : rk(A :: C :: M :: nil) = 3) by (apply LACM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACMmtmp : rk(A :: C :: M :: nil) >= 3) by (solve_hyps_min HACMeq HACMm3).\n\tassert(Hincl : incl (A :: C :: M :: nil) (list_inter (A :: C :: Bp :: M :: nil) (Oo :: A :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: M :: P :: nil) (A :: C :: Bp :: M :: Oo :: A :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: C :: Bp :: M :: Oo :: A :: C :: M :: P :: nil) ((A :: C :: Bp :: M :: nil) ++ (Oo :: A :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpMPmtmp;try rewrite HT2 in HOoACBpMPmtmp.\n\tassert(HT := rule_2 (A :: C :: Bp :: M :: nil) (Oo :: A :: C :: M :: P :: nil) (A :: C :: M :: nil) 4 3 3 HOoACBpMPmtmp HACMmtmp HOoACMPMtmp Hincl);apply HT.\n}\n\nassert(HACBpMM : rk(A :: C :: Bp :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HACBpMm : rk(A :: C :: Bp :: M ::  nil) >= 1) by (solve_hyps_min HACBpMeq HACBpMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LApBpM *)\n(* dans constructLemma(), requis par LAApBpMP *)\n(* dans la couche 0 *)\nLemma LAApBpCpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AApBpCpMP requis par la preuve de (?)AApBpCpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AApBpCpMP requis par la preuve de (?)AApBpCpMP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A ::   de rang : 2 et 2 *)\nassert(HAApBpCpMPm3 : rk(A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAMtmp : rk(Oo :: A :: nil) <= 2) by (solve_hyps_max HOoAeq HOoAM2).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: nil) (A :: Ap :: Bp :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Oo :: A :: A :: Ap :: Bp :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: A :: Ap :: Bp :: Cp :: M :: P :: nil) ((Oo :: A :: nil) ++ (A :: Ap :: Bp :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: nil) (A :: Ap :: Bp :: Cp :: M :: P :: nil) (A :: nil) 4 1 2 HOoAApBpCpMPmtmp HAmtmp HOoAMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HAApBpCpMPm4 : rk(A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Oo :: Ap :: Bp :: A :: Ap :: Bp :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: A :: Ap :: Bp :: Cp :: M :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (A :: Ap :: Bp :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: Cp :: M :: P :: nil) (Ap :: Bp :: nil) 4 2 2 HOoAApBpCpMPmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\nassert(HAApBpCpMPM : rk(A :: Ap :: Bp :: Cp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAApBpCpMPm : rk(A :: Ap :: Bp :: Cp :: M :: P ::  nil) >= 1) by (solve_hyps_min HAApBpCpMPeq HAApBpCpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAApBpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Ap :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AApBpMP requis par la preuve de (?)AApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)AApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)OoAApBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)OoAApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpMPm2 : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpMPm3 : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AApBpMP requis par la preuve de (?)AApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AApBpMP requis par la preuve de (?)AApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAApBpMPm2 : rk(A :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HAApeq : rk(A :: Ap :: nil) = 2) by (apply LAAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApmtmp : rk(A :: Ap :: nil) >= 2) by (solve_hyps_min HAApeq HAApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: Ap :: nil) (A :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: Ap :: nil) (A :: Ap :: Bp :: M :: P :: nil) 2 2 HAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: M :: P ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HAApBpMPm3 : rk(A :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoAApBpMPmtmp : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 3) by (solve_hyps_min HOoAApBpMPeq HOoAApBpMPm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: M :: P :: nil) (Oo :: Ap :: Bp :: A :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: A :: Ap :: Bp :: M :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (A :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpMPmtmp;try rewrite HT2 in HOoAApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (A :: Ap :: Bp :: M :: P :: nil) (Ap :: Bp :: nil) 3 2 2 HOoAApBpMPmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Ap :: Bp :: Cp ::   de rang : 2 et 2 *)\nassert(HAApBpMPm4 : rk(A :: Ap :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HApBpCpeq : rk(Ap :: Bp :: Cp :: nil) = 2) by (apply LApBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApBpCpMtmp : rk(Ap :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HApBpCpeq HApBpCpM2).\n\tassert(HAApBpCpMPeq : rk(A :: Ap :: Bp :: Cp :: M :: P :: nil) = 4) by (apply LAApBpCpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApBpCpMPmtmp : rk(A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HAApBpCpMPeq HAApBpCpMPm4).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Ap :: Bp :: Cp :: nil) (A :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: Bp :: Cp :: M :: P :: nil) (Ap :: Bp :: Cp :: A :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Bp :: Cp :: A :: Ap :: Bp :: M :: P :: nil) ((Ap :: Bp :: Cp :: nil) ++ (A :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApBpCpMPmtmp;try rewrite HT2 in HAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Ap :: Bp :: Cp :: nil) (A :: Ap :: Bp :: M :: P :: nil) (Ap :: Bp :: nil) 4 2 2 HAApBpCpMPmtmp HApBpmtmp HApBpCpMtmp Hincl); apply HT.\n}\n\nassert(HAApBpMPM : rk(A :: Ap :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAApBpMPm : rk(A :: Ap :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HAApBpMPeq HAApBpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApBpM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ApBpM requis par la preuve de (?)ApBpM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ApBpM requis par la preuve de (?)ApBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HApBpMm2 : rk(Ap :: Bp :: M :: nil) >= 2).\n{\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (Ap :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Ap :: Bp :: nil) (Ap :: Bp :: M :: nil) 2 2 HApBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HApBpMm3 : rk(Ap :: Bp :: M :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAApBpMPeq : rk(A :: Ap :: Bp :: M :: P :: nil) = 4) by (apply LAApBpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApBpMPmtmp : rk(A :: Ap :: Bp :: M :: P :: nil) >= 4) by (solve_hyps_min HAApBpMPeq HAApBpMPm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (Ap :: Bp :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: Bp :: M :: P :: nil) (Ap :: Bp :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Bp :: M :: A :: M :: P :: nil) ((Ap :: Bp :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApBpMPmtmp;try rewrite HT2 in HAApBpMPmtmp.\n\tassert(HT := rule_2 (Ap :: Bp :: M :: nil) (A :: M :: P :: nil) (M :: nil) 4 1 2 HAApBpMPmtmp HMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HApBpMM : rk(Ap :: Bp :: M ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HApBpMeq HApBpMM3).\nassert(HApBpMm : rk(Ap :: Bp :: M ::  nil) >= 1) by (solve_hyps_min HApBpMeq HApBpMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoApBpM *)\n(* dans la couche 0 *)\nLemma LOoAApBpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)OoAApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)OoAApBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApBpMP requis par la preuve de (?)OoAApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpMPm2 : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApBpMPm3 : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  de rang :  4 et 4 \t AiB : Oo :: Ap ::  de rang :  2 et 2 \t A : Oo :: Ap :: Cp ::   de rang : 2 et 2 *)\nassert(HOoAApBpMPm4 : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApCpeq : rk(Oo :: Ap :: Cp :: nil) = 2) by (apply LOoApCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApCpMtmp : rk(Oo :: Ap :: Cp :: nil) <= 2) by (solve_hyps_max HOoApCpeq HOoApCpM2).\n\tassert(HOoAApBpCpMPmtmp : rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpCpMPeq HOoAApBpCpMPm4).\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (list_inter (Oo :: Ap :: Cp :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: Cp :: M :: P :: nil) (Oo :: Ap :: Cp :: Oo :: A :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Cp :: Oo :: A :: Ap :: Bp :: M :: P :: nil) ((Oo :: Ap :: Cp :: nil) ++ (Oo :: A :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpCpMPmtmp;try rewrite HT2 in HOoAApBpCpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Cp :: nil) (Oo :: A :: Ap :: Bp :: M :: P :: nil) (Oo :: Ap :: nil) 4 2 2 HOoAApBpCpMPmtmp HOoApmtmp HOoApCpMtmp Hincl); apply HT.\n}\n\nassert(HOoAApBpMPM : rk(Oo :: A :: Ap :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApBpMPm : rk(Oo :: A :: Ap :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoAApBpMPeq HOoAApBpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoApBpM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: Ap :: Bp :: M ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoApBpM requis par la preuve de (?)OoApBpM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoApBpM requis par la preuve de (?)OoApBpM pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoApBpM requis par la preuve de (?)OoApBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoApBpMm2 : rk(Oo :: Ap :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoApmtmp : rk(Oo :: Ap :: nil) >= 2) by (solve_hyps_min HOoApeq HOoApm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: Ap :: nil) (Oo :: Ap :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: Ap :: nil) (Oo :: Ap :: Bp :: M :: nil) 2 2 HOoApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoApBpMM3 : rk(Oo :: Ap :: Bp :: M :: nil) <= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: Bp :: nil) (M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: Ap :: Bp :: M :: nil) (Oo :: Ap :: Bp :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: M :: nil) ((Oo :: Ap :: Bp :: nil) ++ (M :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: Ap :: Bp :: nil) (M :: nil) (nil) 2 1 0 HOoApBpMtmp HMMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoApBpMm3 : rk(Oo :: Ap :: Bp :: M :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoAApBpMPeq : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) = 4) by (apply LOoAApBpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApBpMPmtmp : rk(Oo :: A :: Ap :: Bp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoAApBpMPeq HOoAApBpMPm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (Oo :: Ap :: Bp :: M :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Bp :: M :: P :: nil) (Oo :: Ap :: Bp :: M :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: M :: A :: M :: P :: nil) ((Oo :: Ap :: Bp :: M :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApBpMPmtmp;try rewrite HT2 in HOoAApBpMPmtmp.\n\tassert(HT := rule_2 (Oo :: Ap :: Bp :: M :: nil) (A :: M :: P :: nil) (M :: nil) 4 1 2 HOoAApBpMPmtmp HMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoApBpMM : rk(Oo :: Ap :: Bp :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoApBpMm : rk(Oo :: Ap :: Bp :: M ::  nil) >= 1) by (solve_hyps_min HOoApBpMeq HOoApBpMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCApBpM *)\n(* dans constructLemma(), requis par LCApBpMQ *)\n(* dans la couche 0 *)\nLemma LOoCApBpMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: Bp :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)OoCApBpMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)OoCApBpMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)OoCApBpMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpMQm2 : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoCApBpMQm3 : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil) 3 3 HOoCApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoCApBpMQm4 : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoCApMeq : rk(Oo :: C :: Ap :: M :: nil) = 4) by (apply LOoCApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApMmtmp : rk(Oo :: C :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoCApMeq HOoCApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil) 4 4 HOoCApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoCApBpMQM : rk(Oo :: C :: Ap :: Bp :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApBpMQm : rk(Oo :: C :: Ap :: Bp :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoCApBpMQeq HOoCApBpMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApBpMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: Bp :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApBpMQ requis par la preuve de (?)CApBpMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)CApBpMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)OoCApBpMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpMQ requis par la preuve de (?)OoCApBpMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpMQm2 : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoCApBpMQm3 : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: Q :: nil) 3 3 HOoCApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApBpMQ requis par la preuve de (?)CApBpMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpMQ requis par la preuve de (?)CApBpMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpMQ requis par la preuve de (?)OoACApBpMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpMQ requis par la preuve de (?)OoACApBpMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMQm2 : rk(Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMQm3 : rk(Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApBpMQ requis par la preuve de (?)CApBpMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M :: Q ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApBpMQm2 : rk(C :: Ap :: Bp :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMQmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) >= 3) by (solve_hyps_min HOoACApBpMQeq HOoACApBpMQm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: Q :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: Q :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: Bp :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMQmtmp;try rewrite HT2 in HOoACApBpMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: Q :: nil) (C :: Ap :: nil) 3 2 3 HOoACApBpMQmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: M :: Q ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HCApBpMQm3 : rk(C :: Ap :: Bp :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoCApBpMQmtmp : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 3) by (solve_hyps_min HOoCApBpMQeq HOoCApBpMQm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: M :: Q :: nil) (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: Q :: nil) ((Oo :: Ap :: Bp :: nil) ++ (C :: Ap :: Bp :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpMQmtmp;try rewrite HT2 in HOoCApBpMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: Q :: nil) (Ap :: Bp :: nil) 3 2 2 HOoCApBpMQmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: M :: Q ::  de rang :  4 et 4 \t AiB : Ap :: Bp :: M ::  de rang :  3 et 3 \t A : Oo :: Ap :: Bp :: M ::   de rang : 3 et 3 *)\nassert(HCApBpMQm4 : rk(C :: Ap :: Bp :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoApBpMeq : rk(Oo :: Ap :: Bp :: M :: nil) = 3) by (apply LOoApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMMtmp : rk(Oo :: Ap :: Bp :: M :: nil) <= 3) by (solve_hyps_max HOoApBpMeq HOoApBpMM3).\n\tassert(HOoCApBpMQeq : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) = 4) by (apply LOoCApBpMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApBpMQmtmp : rk(Oo :: C :: Ap :: Bp :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoCApBpMQeq HOoCApBpMQm4).\n\tassert(HApBpMeq : rk(Ap :: Bp :: M :: nil) = 3) by (apply LApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApBpMmtmp : rk(Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HApBpMeq HApBpMm3).\n\tassert(Hincl : incl (Ap :: Bp :: M :: nil) (list_inter (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: M :: Q :: nil) (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: M :: Q :: nil) ((Oo :: Ap :: Bp :: M :: nil) ++ (C :: Ap :: Bp :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpMQmtmp;try rewrite HT2 in HOoCApBpMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: M :: Q :: nil) (Ap :: Bp :: M :: nil) 4 3 3 HOoCApBpMQmtmp HApBpMmtmp HOoApBpMMtmp Hincl); apply HT.\n}\n\nassert(HCApBpMQM : rk(C :: Ap :: Bp :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApBpMQm : rk(C :: Ap :: Bp :: M :: Q ::  nil) >= 1) by (solve_hyps_min HCApBpMQeq HCApBpMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApBpM : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: Bp :: M ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApBpM requis par la preuve de (?)CApBpM pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpM requis par la preuve de (?)CApBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpM requis par la preuve de (?)OoCApBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpM requis par la preuve de (?)OoACApBpM pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpM requis par la preuve de (?)OoACApBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMm2 : rk(Oo :: A :: C :: Ap :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMm3 : rk(Oo :: A :: C :: Ap :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpM requis par la preuve de (?)OoCApBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpM requis par la preuve de (?)OoCApBpM pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpMm2 : rk(Oo :: C :: Ap :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpMm3 : rk(Oo :: C :: Ap :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HOoACApBpMeq HOoACApBpMm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMmtmp;try rewrite HT2 in HOoACApBpMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpMmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApBpM requis par la preuve de (?)CApBpM pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApBpM requis par la preuve de (?)CApBpM pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApBpMm2 : rk(C :: Ap :: Bp :: M :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HOoACApBpMeq HOoACApBpMm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: Bp :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMmtmp;try rewrite HT2 in HOoACApBpMmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: nil) (C :: Ap :: nil) 3 2 3 HOoACApBpMmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: M ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HCApBpMm3 : rk(C :: Ap :: Bp :: M :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoCApBpMmtmp : rk(Oo :: C :: Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HOoCApBpMeq HOoCApBpMm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: M :: nil) (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: nil) ((Oo :: Ap :: Bp :: nil) ++ (C :: Ap :: Bp :: M :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpMmtmp;try rewrite HT2 in HOoCApBpMmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: nil) (Ap :: Bp :: nil) 3 2 2 HOoCApBpMmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HCApBpMm4 : rk(C :: Ap :: Bp :: M :: nil) >= 4).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HCApBpMQeq : rk(C :: Ap :: Bp :: M :: Q :: nil) = 4) by (apply LCApBpMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApBpMQmtmp : rk(C :: Ap :: Bp :: M :: Q :: nil) >= 4) by (solve_hyps_min HCApBpMQeq HCApBpMQm4).\n\tassert(HApMeq : rk(Ap :: M :: nil) = 2) by (apply LApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApMmtmp : rk(Ap :: M :: nil) >= 2) by (solve_hyps_min HApMeq HApMm2).\n\tassert(Hincl : incl (Ap :: M :: nil) (list_inter (C :: Ap :: Bp :: M :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: Bp :: M :: Q :: nil) (C :: Ap :: Bp :: M :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Bp :: M :: Ap :: M :: Q :: nil) ((C :: Ap :: Bp :: M :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApBpMQmtmp;try rewrite HT2 in HCApBpMQmtmp.\n\tassert(HT := rule_2 (C :: Ap :: Bp :: M :: nil) (Ap :: M :: Q :: nil) (Ap :: M :: nil) 4 2 2 HCApBpMQmtmp HApMmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HCApBpMM : rk(C :: Ap :: Bp :: M ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApBpMm : rk(C :: Ap :: Bp :: M ::  nil) >= 1) by (solve_hyps_min HCApBpMeq HCApBpMm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAN *)\n(* dans la couche 0 *)\nLemma LABpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Bp :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABpNP requis par la preuve de (?)ABpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ABpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ACBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACBpNP requis par la preuve de (?)ACBpNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: B ::   de rang : 2 et 2 *)\nassert(HACBpNPm2 : rk(A :: C :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HOoBMtmp : rk(Oo :: B :: nil) <= 2) by (solve_hyps_max HOoBeq HOoBM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: B :: nil) (A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: B :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: A :: C :: Bp :: N :: P :: nil) ((Oo :: B :: nil) ++ (A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: B :: nil) (A :: C :: Bp :: N :: P :: nil) (nil) 4 0 2 HOoABCBpNPmtmp Hmtmp HOoBMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: B ::   de rang : 2 et 2 *)\nassert(HACBpNPm3 : rk(A :: C :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: C :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: B :: A :: C :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: C :: Bp :: N :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: C :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: nil) (A :: C :: Bp :: N :: P :: nil) (A :: nil) 4 1 2 HOoABCBpNPmtmp HAmtmp HOoABMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABpNP requis par la preuve de (?)ABpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABpNP requis par la preuve de (?)ABpNP pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HABpNPM3 : rk(A :: Bp :: N :: P :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: N :: P :: nil) (A :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Bp :: N :: P :: nil) ((A :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (Bp :: N :: P :: nil) (nil) 1 2 0 HAMtmp HBpNPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -1 et -2*)\n(* ensembles concern\u00e9s AUB : A :: C :: Bp :: N :: P ::  de rang :  3 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HABpNPm2 : rk(A :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HACBpNPmtmp : rk(A :: C :: Bp :: N :: P :: nil) >= 3) by (solve_hyps_min HACBpNPeq HACBpNPm3).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (A :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Bp :: N :: P :: nil) (C :: A :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: A :: Bp :: N :: P :: nil) ((C :: nil) ++ (A :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACBpNPmtmp;try rewrite HT2 in HACBpNPmtmp.\n\tassert(HT := rule_4 (C :: nil) (A :: Bp :: N :: P :: nil) (nil) 3 0 1 HACBpNPmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : A ::  de rang :  1 et 1 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HABpNPm3 : rk(A :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACBpNPeq : rk(Oo :: A :: C :: Bp :: N :: P :: nil) = 4) by (apply LOoACBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpNPmtmp : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoACBpNPeq HOoACBpNPm4).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: C :: nil) (A :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: N :: P :: nil) (Oo :: A :: C :: A :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: A :: Bp :: N :: P :: nil) ((Oo :: A :: C :: nil) ++ (A :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpNPmtmp;try rewrite HT2 in HOoACBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (A :: Bp :: N :: P :: nil) (A :: nil) 4 1 2 HOoACBpNPmtmp HAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HABpNPM : rk(A :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABpNPm : rk(A :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HABpNPeq HABpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: N ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour AN requis par la preuve de (?)AN pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HANm2 : rk(A :: N :: nil) >= 2).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABpNPeq : rk(A :: Bp :: N :: P :: nil) = 3) by (apply LABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNPmtmp : rk(A :: Bp :: N :: P :: nil) >= 3) by (solve_hyps_min HABpNPeq HABpNPm3).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (A :: N :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: N :: P :: nil) (A :: N :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: N :: Bp :: N :: P :: nil) ((A :: N :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABpNPmtmp;try rewrite HT2 in HABpNPmtmp.\n\tassert(HT := rule_2 (A :: N :: nil) (Bp :: N :: P :: nil) (N :: nil) 3 1 2 HABpNPmtmp HNmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HANM : rk(A :: N ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HANeq HANM2).\nassert(HANm : rk(A :: N ::  nil) >= 1) by (solve_hyps_min HANeq HANm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoAN *)\n(* dans la couche 0 *)\nLemma LOoABpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABpNP requis par la preuve de (?)OoABpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABpNP requis par la preuve de (?)OoABpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABpNP requis par la preuve de (?)OoABpNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABpNPm2 : rk(Oo :: A :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Bp :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Bp :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoABpNPm3 : rk(Oo :: A :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoACBpNPeq : rk(Oo :: A :: C :: Bp :: N :: P :: nil) = 4) by (apply LOoACBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpNPmtmp : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoACBpNPeq HOoACBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: N :: P :: nil) (C :: Oo :: A :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: Bp :: N :: P :: nil) ((C :: nil) ++ (Oo :: A :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpNPmtmp;try rewrite HT2 in HOoACBpNPmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: Bp :: N :: P :: nil) (nil) 4 0 1 HOoACBpNPmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoABpNPm4 : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACBpNPeq : rk(Oo :: A :: C :: Bp :: N :: P :: nil) = 4) by (apply LOoACBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpNPmtmp : rk(Oo :: A :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoACBpNPeq HOoACBpNPm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: N :: P :: nil) (Oo :: A :: C :: Oo :: A :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: Bp :: N :: P :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpNPmtmp;try rewrite HT2 in HOoACBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: Bp :: N :: P :: nil) (Oo :: A :: nil) 4 2 2 HOoACBpNPmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HOoABpNPM : rk(Oo :: A :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABpNPm : rk(Oo :: A :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoABpNPeq HOoABpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoAN requis par la preuve de (?)OoAN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour OoAN requis par la preuve de (?)OoAN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoANm2 : rk(Oo :: A :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoANm3 : rk(Oo :: A :: N :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (Oo :: A :: N :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Oo :: A :: N :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: N :: Bp :: N :: P :: nil) ((Oo :: A :: N :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: N :: nil) (Bp :: N :: P :: nil) (N :: nil) 4 1 2 HOoABpNPmtmp HNmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HOoANM : rk(Oo :: A :: N ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HOoANeq HOoANM3).\nassert(HOoANm : rk(Oo :: A :: N ::  nil) >= 1) by (solve_hyps_min HOoANeq HOoANm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABN requis par la preuve de (?)ABN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABN requis par la preuve de (?)ABN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABNm2 : rk(A :: B :: N :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: N :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HABNm3 : rk(A :: B :: N :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABBpNPeq : rk(A :: B :: Bp :: N :: P :: nil) = 4) by (apply LABBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABBpNPmtmp : rk(A :: B :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HABBpNPeq HABBpNPm4).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (A :: B :: N :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: Bp :: N :: P :: nil) (A :: B :: N :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: N :: Bp :: N :: P :: nil) ((A :: B :: N :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABBpNPmtmp;try rewrite HT2 in HABBpNPmtmp.\n\tassert(HT := rule_2 (A :: B :: N :: nil) (Bp :: N :: P :: nil) (N :: nil) 4 1 2 HABBpNPmtmp HNmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HABNM : rk(A :: B :: N ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABNeq HABNM3).\nassert(HABNm : rk(A :: B :: N ::  nil) >= 1) by (solve_hyps_min HABNeq HABNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoABN *)\n(* dans la couche 0 *)\nLemma LOoABBpNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Bp :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABBpNP requis par la preuve de (?)OoABBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBpNP requis par la preuve de (?)OoABBpNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBpNP requis par la preuve de (?)OoABBpNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpNPm2 : rk(Oo :: A :: B :: Bp :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoABBpNPm3 : rk(Oo :: A :: B :: Bp :: N :: P :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (C :: Oo :: A :: B :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: B :: Bp :: N :: P :: nil) ((C :: nil) ++ (Oo :: A :: B :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil) (nil) 4 0 1 HOoABCBpNPmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoABBpNPm4 : rk(Oo :: A :: B :: Bp :: N :: P :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABCBpNPmtmp : rk(Oo :: A :: B :: C :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABCBpNPeq HOoABCBpNPm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Bp :: N :: P :: nil) (Oo :: A :: C :: Oo :: A :: B :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: Bp :: N :: P :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCBpNPmtmp;try rewrite HT2 in HOoABCBpNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: B :: Bp :: N :: P :: nil) (Oo :: A :: nil) 4 2 2 HOoABCBpNPmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HOoABBpNPM : rk(Oo :: A :: B :: Bp :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABBpNPm : rk(Oo :: A :: B :: Bp :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoABBpNPeq HOoABBpNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABN requis par la preuve de (?)OoABN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABN requis par la preuve de (?)OoABN pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABN requis par la preuve de (?)OoABN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABNm2 : rk(Oo :: A :: B :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -2 et 5*)\nassert(HOoABNM3 : rk(Oo :: A :: B :: N :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: A :: B :: nil) (N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: N :: nil) (Oo :: A :: B :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: N :: nil) ((Oo :: A :: B :: nil) ++ (N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (N :: nil) (nil) 2 1 0 HOoABMtmp HNMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HOoABNm3 : rk(Oo :: A :: B :: N :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HOoABBpNPeq : rk(Oo :: A :: B :: Bp :: N :: P :: nil) = 4) by (apply LOoABBpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpNPmtmp : rk(Oo :: A :: B :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABBpNPeq HOoABBpNPm4).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (Oo :: A :: B :: N :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: N :: P :: nil) (Oo :: A :: B :: N :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: N :: Bp :: N :: P :: nil) ((Oo :: A :: B :: N :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABBpNPmtmp;try rewrite HT2 in HOoABBpNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: N :: nil) (Bp :: N :: P :: nil) (N :: nil) 4 1 2 HOoABBpNPmtmp HNmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HOoABNM : rk(Oo :: A :: B :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABNm : rk(Oo :: A :: B :: N ::  nil) >= 1) by (solve_hyps_min HOoABNeq HOoABNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBpN *)\n(* dans constructLemma(), requis par LBBpNQ *)\n(* dans la couche 0 *)\nLemma LOoBBpCpNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: B :: Bp :: Cp :: N :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBBpCpNQ requis par la preuve de (?)OoBBpCpNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBBpCpNQ requis par la preuve de (?)OoBBpCpNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBBpCpNQ requis par la preuve de (?)OoBBpCpNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBBpCpNQm2 : rk(Oo :: B :: Bp :: Cp :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoBBpCpNQm3 : rk(Oo :: B :: Bp :: Cp :: N :: Q :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoBApBpCpNQmtmp : rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoBApBpCpNQeq HOoBApBpCpNQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: Bp :: Cp :: N :: Q :: nil) (Ap :: Oo :: B :: Bp :: Cp :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: B :: Bp :: Cp :: N :: Q :: nil) ((Ap :: nil) ++ (Oo :: B :: Bp :: Cp :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApBpCpNQmtmp;try rewrite HT2 in HOoBApBpCpNQmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil) (nil) 4 0 1 HOoBApBpCpNQmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  de rang :  4 et 4 \t AiB : Oo :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HOoBBpCpNQm4 : rk(Oo :: B :: Bp :: Cp :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoBApBpCpNQmtmp : rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoBApBpCpNQeq HOoBApBpCpNQm4).\n\tassert(HOoBpmtmp : rk(Oo :: Bp :: nil) >= 2) by (solve_hyps_min HOoBpeq HOoBpm2).\n\tassert(Hincl : incl (Oo :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: Bp :: Cp :: N :: Q :: nil) (Oo :: Ap :: Bp :: Oo :: B :: Bp :: Cp :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: Oo :: B :: Bp :: Cp :: N :: Q :: nil) ((Oo :: Ap :: Bp :: nil) ++ (Oo :: B :: Bp :: Cp :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApBpCpNQmtmp;try rewrite HT2 in HOoBApBpCpNQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (Oo :: B :: Bp :: Cp :: N :: Q :: nil) (Oo :: Bp :: nil) 4 2 2 HOoBApBpCpNQmtmp HOoBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\nassert(HOoBBpCpNQM : rk(Oo :: B :: Bp :: Cp :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoBBpCpNQm : rk(Oo :: B :: Bp :: Cp :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoBBpCpNQeq HOoBBpCpNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBBpNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Bp :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BBpNQ requis par la preuve de (?)BBpNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BBpNQ requis par la preuve de (?)BBpNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BBpNQ requis par la preuve de (?)BBpNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBBpNQM3 : rk(B :: Bp :: N :: Q :: nil) <= 3).\n{\n\tassert(HBpMtmp : rk(Bp :: nil) <= 1) by (solve_hyps_max HBpeq HBpM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Bp :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Bp :: N :: Q :: nil) (Bp :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: B :: N :: Q :: nil) ((Bp :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Bp :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HBpMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBBpNQm2 : rk(B :: Bp :: N :: Q :: nil) >= 2).\n{\n\tassert(HBBpeq : rk(B :: Bp :: nil) = 2) by (apply LBBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBBpmtmp : rk(B :: Bp :: nil) >= 2) by (solve_hyps_min HBBpeq HBBpm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: Bp :: nil) (B :: Bp :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: Bp :: nil) (B :: Bp :: N :: Q :: nil) 2 2 HBBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Bp :: Cp :: N :: Q ::  de rang :  4 et 4 \t AiB : Bp ::  de rang :  1 et 1 \t A : Oo :: Bp :: Cp ::   de rang : 2 et 2 *)\nassert(HBBpNQm3 : rk(B :: Bp :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoBpCpeq : rk(Oo :: Bp :: Cp :: nil) = 2) by (apply LOoBpCp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBpCpMtmp : rk(Oo :: Bp :: Cp :: nil) <= 2) by (solve_hyps_max HOoBpCpeq HOoBpCpM2).\n\tassert(HOoBBpCpNQeq : rk(Oo :: B :: Bp :: Cp :: N :: Q :: nil) = 4) by (apply LOoBBpCpNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBBpCpNQmtmp : rk(Oo :: B :: Bp :: Cp :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoBBpCpNQeq HOoBBpCpNQm4).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (Oo :: Bp :: Cp :: nil) (B :: Bp :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Bp :: Cp :: N :: Q :: nil) (Oo :: Bp :: Cp :: B :: Bp :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Bp :: Cp :: B :: Bp :: N :: Q :: nil) ((Oo :: Bp :: Cp :: nil) ++ (B :: Bp :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBBpCpNQmtmp;try rewrite HT2 in HOoBBpCpNQmtmp.\n\tassert(HT := rule_4 (Oo :: Bp :: Cp :: nil) (B :: Bp :: N :: Q :: nil) (Bp :: nil) 4 1 2 HOoBBpCpNQmtmp HBpmtmp HOoBpCpMtmp Hincl); apply HT.\n}\n\nassert(HBBpNQM : rk(B :: Bp :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBBpNQm : rk(B :: Bp :: N :: Q ::  nil) >= 1) by (solve_hyps_min HBBpNQeq HBBpNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBpN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Bp :: N ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BpN requis par la preuve de (?)BpN pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBpNm2 : rk(Bp :: N :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBBpNQeq : rk(B :: Bp :: N :: Q :: nil) = 3) by (apply LBBpNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBBpNQmtmp : rk(B :: Bp :: N :: Q :: nil) >= 3) by (solve_hyps_min HBBpNQeq HBBpNQm3).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (Bp :: N :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Bp :: N :: Q :: nil) (Bp :: N :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: N :: B :: N :: Q :: nil) ((Bp :: N :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBBpNQmtmp;try rewrite HT2 in HBBpNQmtmp.\n\tassert(HT := rule_2 (Bp :: N :: nil) (B :: N :: Q :: nil) (N :: nil) 3 1 2 HBBpNQmtmp HNmtmp HBNQMtmp Hincl);apply HT.\n}\n\nassert(HBpNM : rk(Bp :: N ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBpNeq HBpNM2).\nassert(HBpNm : rk(Bp :: N ::  nil) >= 1) by (solve_hyps_min HBpNeq HBpNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABpN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Bp :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABpN requis par la preuve de (?)ABpN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABBpN requis par la preuve de (?)ABpN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBpN requis par la preuve de (?)OoABBpN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBpN requis par la preuve de (?)OoABBpN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpNm2 : rk(Oo :: A :: B :: Bp :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABBpNm3 : rk(Oo :: A :: B :: Bp :: N :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: N :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABpN requis par la preuve de (?)ABpN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Bp :: N ::  de rang :  3 et 4 \t AiB : A :: Bp ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Bp ::   de rang : 3 et 3 *)\nassert(HABpNm2 : rk(A :: Bp :: N :: nil) >= 2).\n{\n\tassert(HOoABBpeq : rk(Oo :: A :: B :: Bp :: nil) = 3) by (apply LOoABBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpMtmp : rk(Oo :: A :: B :: Bp :: nil) <= 3) by (solve_hyps_max HOoABBpeq HOoABBpM3).\n\tassert(HOoABBpNmtmp : rk(Oo :: A :: B :: Bp :: N :: nil) >= 3) by (solve_hyps_min HOoABBpNeq HOoABBpNm3).\n\tassert(HABpeq : rk(A :: Bp :: nil) = 2) by (apply LABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpmtmp : rk(A :: Bp :: nil) >= 2) by (solve_hyps_min HABpeq HABpm2).\n\tassert(Hincl : incl (A :: Bp :: nil) (list_inter (Oo :: A :: B :: Bp :: nil) (A :: Bp :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: N :: nil) (Oo :: A :: B :: Bp :: A :: Bp :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: A :: Bp :: N :: nil) ((Oo :: A :: B :: Bp :: nil) ++ (A :: Bp :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABBpNmtmp;try rewrite HT2 in HOoABBpNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Bp :: nil) (A :: Bp :: N :: nil) (A :: Bp :: nil) 3 2 3 HOoABBpNmtmp HABpmtmp HOoABBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HABpNm3 : rk(A :: Bp :: N :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABpNPeq : rk(A :: Bp :: N :: P :: nil) = 3) by (apply LABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNPmtmp : rk(A :: Bp :: N :: P :: nil) >= 3) by (solve_hyps_min HABpNPeq HABpNPm3).\n\tassert(HBpNeq : rk(Bp :: N :: nil) = 2) by (apply LBpN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBpNmtmp : rk(Bp :: N :: nil) >= 2) by (solve_hyps_min HBpNeq HBpNm2).\n\tassert(Hincl : incl (Bp :: N :: nil) (list_inter (A :: Bp :: N :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: N :: P :: nil) (A :: Bp :: N :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Bp :: N :: Bp :: N :: P :: nil) ((A :: Bp :: N :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABpNPmtmp;try rewrite HT2 in HABpNPmtmp.\n\tassert(HT := rule_2 (A :: Bp :: N :: nil) (Bp :: N :: P :: nil) (Bp :: N :: nil) 3 2 2 HABpNPmtmp HBpNmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HABpNM : rk(A :: Bp :: N ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HABpNeq HABpNM3).\nassert(HABpNm : rk(A :: Bp :: N ::  nil) >= 1) by (solve_hyps_min HABpNeq HABpNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LXMN *)\n(* dans constructLemma(), requis par LAXMN *)\n(* dans constructLemma(), requis par LOoAApXMN *)\n(* dans la couche 0 *)\nLemma LOoAApXMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: X :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApXMNP requis par la preuve de (?)OoAApXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApXMNP requis par la preuve de (?)OoAApXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApXMNP requis par la preuve de (?)OoAApXMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXMNPm2 : rk(Oo :: A :: Ap :: X :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXMNPm3 : rk(Oo :: A :: Ap :: X :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAApXMNPm4 : rk(Oo :: A :: Ap :: X :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: Ap :: X :: M :: N :: P :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAApXMNPM : rk(Oo :: A :: Ap :: X :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApXMNPm : rk(Oo :: A :: Ap :: X :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoAApXMNPeq HOoAApXMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAApXMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: X :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApXMN requis par la preuve de (?)OoAApXMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApXMN requis par la preuve de (?)OoAApXMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApXMN requis par la preuve de (?)OoAApXMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXMNm2 : rk(Oo :: A :: Ap :: X :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: X :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: X :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApXMNm3 : rk(Oo :: A :: Ap :: X :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: X :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAApXMNm4 : rk(Oo :: A :: Ap :: X :: M :: N :: nil) >= 4).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoAApXMNPeq : rk(Oo :: A :: Ap :: X :: M :: N :: P :: nil) = 4) by (apply LOoAApXMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApXMNPmtmp : rk(Oo :: A :: Ap :: X :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HOoAApXMNPeq HOoAApXMNPm4).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: Ap :: X :: M :: N :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: X :: M :: N :: P :: nil) (Oo :: A :: Ap :: X :: M :: N :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: X :: M :: N :: A :: M :: P :: nil) ((Oo :: A :: Ap :: X :: M :: N :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApXMNPmtmp;try rewrite HT2 in HOoAApXMNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Ap :: X :: M :: N :: nil) (A :: M :: P :: nil) (A :: M :: nil) 4 2 2 HOoAApXMNPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoAApXMNM : rk(Oo :: A :: Ap :: X :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApXMNm : rk(Oo :: A :: Ap :: X :: M :: N ::  nil) >= 1) by (solve_hyps_min HOoAApXMNeq HOoAApXMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAXMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: X :: M :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AXMN requis par la preuve de (?)AXMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour AXMNP requis par la preuve de (?)AXMN pour la r\u00e8gle 3  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour AXNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour ABpXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)OoABBpXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)OoABBpXNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpXNPm2 : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABBpXNPm3 : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Bp :: X :: N :: P ::  de rang :  3 et 4 \t AiB : A :: Bp ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Bp ::   de rang : 3 et 3 *)\nassert(HABpXNPm2 : rk(A :: Bp :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABBpeq : rk(Oo :: A :: B :: Bp :: nil) = 3) by (apply LOoABBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpMtmp : rk(Oo :: A :: B :: Bp :: nil) <= 3) by (solve_hyps_max HOoABBpeq HOoABBpM3).\n\tassert(HOoABBpXNPmtmp : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABBpXNPeq HOoABBpXNPm3).\n\tassert(HABpeq : rk(A :: Bp :: nil) = 2) by (apply LABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpmtmp : rk(A :: Bp :: nil) >= 2) by (solve_hyps_min HABpeq HABpm2).\n\tassert(Hincl : incl (A :: Bp :: nil) (list_inter (Oo :: A :: B :: Bp :: nil) (A :: Bp :: X :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: X :: N :: P :: nil) (Oo :: A :: B :: Bp :: A :: Bp :: X :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: A :: Bp :: X :: N :: P :: nil) ((Oo :: A :: B :: Bp :: nil) ++ (A :: Bp :: X :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABBpXNPmtmp;try rewrite HT2 in HOoABBpXNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Bp :: nil) (A :: Bp :: X :: N :: P :: nil) (A :: Bp :: nil) 3 2 3 HOoABBpXNPmtmp HABpmtmp HOoABBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -4 -4 et -2*)\nassert(HABpXNPM3 : rk(A :: Bp :: X :: N :: P :: nil) <= 3).\n{\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (A :: Bp :: X :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: X :: N :: P :: nil) (A :: Bp :: X :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Bp :: X :: Bp :: N :: P :: nil) ((A :: Bp :: X :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: Bp :: X :: nil) (Bp :: N :: P :: nil) (Bp :: nil) 2 2 1 HABpXMtmp HBpNPMtmp HBpmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HABpXNPm3 : rk(A :: Bp :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HABpNeq : rk(A :: Bp :: N :: nil) = 3) by (apply LABpN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNmtmp : rk(A :: Bp :: N :: nil) >= 3) by (solve_hyps_min HABpNeq HABpNm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: Bp :: N :: nil) (A :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: Bp :: N :: nil) (A :: Bp :: X :: N :: P :: nil) 3 3 HABpNmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour ANP requis par la preuve de (?)AXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 2 pour NP requis par la preuve de (?)ANP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BNPQ requis par la preuve de (?)NP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : B ::  de rang :  1 et 1 \t A : A :: B :: M ::   de rang : 3 et 3 *)\nassert(HBNPQm2 : rk(B :: N :: P :: Q :: nil) >= 2).\n{\n\tassert(HABMeq : rk(A :: B :: M :: nil) = 3) by (apply LABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABMMtmp : rk(A :: B :: M :: nil) <= 3) by (solve_hyps_max HABMeq HABMM3).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (A :: B :: M :: nil) (B :: N :: P :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: B :: M :: B :: N :: P :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: M :: B :: N :: P :: Q :: nil) ((A :: B :: M :: nil) ++ (B :: N :: P :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: B :: M :: nil) (B :: N :: P :: Q :: nil) (B :: nil) 4 1 3 HABMNPQmtmp HBmtmp HABMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBNPQM3 : rk(B :: N :: P :: Q :: nil) <= 3).\n{\n\tassert(HPMtmp : rk(P :: nil) <= 1) by (solve_hyps_max HPeq HPM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: N :: P :: Q :: nil) (P :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P :: B :: N :: Q :: nil) ((P :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HPMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : P ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBNPQm3 : rk(B :: N :: P :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HPmtmp : rk(P :: nil) >= 1) by (solve_hyps_min HPeq HPm1).\n\tassert(Hincl : incl (P :: nil) (list_inter (A :: M :: P :: nil) (B :: N :: P :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: N :: P :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: N :: P :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: N :: P :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: N :: P :: Q :: nil) (P :: nil) 4 1 2 HABMNPQmtmp HPmtmp HAMPMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour NP requis par la preuve de (?)NP pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 -2 et -4*)\nassert(HNPm2 : rk(N :: P :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBNPQmtmp : rk(B :: N :: P :: Q :: nil) >= 3) by (solve_hyps_min HBNPQeq HBNPQm3).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (N :: P :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: N :: P :: Q :: nil) (N :: P :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: P :: B :: N :: Q :: nil) ((N :: P :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBNPQmtmp;try rewrite HT2 in HBNPQmtmp.\n\tassert(HT := rule_2 (N :: P :: nil) (B :: N :: Q :: nil) (N :: nil) 3 1 2 HBNPQmtmp HNmtmp HBNQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ANP requis par la preuve de (?)ANP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ANP requis par la preuve de (?)ANP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Bp ::   de rang : 2 et 2 *)\nassert(HANPm2 : rk(A :: N :: P :: nil) >= 2).\n{\n\tassert(HOoBpMtmp : rk(Oo :: Bp :: nil) <= 2) by (solve_hyps_max HOoBpeq HOoBpM2).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Bp :: nil) (A :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Oo :: Bp :: A :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Bp :: A :: N :: P :: nil) ((Oo :: Bp :: nil) ++ (A :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_4 (Oo :: Bp :: nil) (A :: N :: P :: nil) (nil) 4 0 2 HOoABpNPmtmp Hmtmp HOoBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 5 et -4*)\nassert(HANPm3 : rk(A :: N :: P :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABpNPeq : rk(A :: Bp :: N :: P :: nil) = 3) by (apply LABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNPmtmp : rk(A :: Bp :: N :: P :: nil) >= 3) by (solve_hyps_min HABpNPeq HABpNPm3).\n\tassert(HNPmtmp : rk(N :: P :: nil) >= 2) by (solve_hyps_min HNPeq HNPm2).\n\tassert(Hincl : incl (N :: P :: nil) (list_inter (A :: N :: P :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: N :: P :: nil) (A :: N :: P :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: N :: P :: Bp :: N :: P :: nil) ((A :: N :: P :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABpNPmtmp;try rewrite HT2 in HABpNPmtmp.\n\tassert(HT := rule_2 (A :: N :: P :: nil) (Bp :: N :: P :: nil) (N :: P :: nil) 3 2 2 HABpNPmtmp HNPmtmp HBpNPMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXNP requis par la preuve de (?)OoABXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXNP requis par la preuve de (?)OoABXNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXNPm2 : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXNPm3 : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: N :: P :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: N :: P ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXNPm2 : rk(A :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXNPmtmp : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABXNPeq HOoABXNPm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: N :: P :: nil) (Oo :: A :: B :: X :: A :: X :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: N :: P :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXNPmtmp;try rewrite HT2 in HOoABXNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: N :: P :: nil) (A :: X :: nil) 3 2 3 HOoABXNPmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HAXNPm3 : rk(A :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: X :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HAXNPM3 : rk(A :: X :: N :: P :: nil) <= 3).\n{\n\tassert(HABpXNPMtmp : rk(A :: Bp :: X :: N :: P :: nil) <= 3) by (solve_hyps_max HABpXNPeq HABpXNPM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: X :: N :: P :: nil) (A :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (A :: X :: N :: P :: nil) (A :: Bp :: X :: N :: P :: nil) 3 3 HABpXNPMtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour AMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMNP requis par la preuve de (?)OoABMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMNP requis par la preuve de (?)OoABMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMNPm2 : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABMNPm3 : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: N :: P :: nil) 3 3 HOoAMmtmp 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\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: M ::  de rang :  2 et 2 \t A : Oo :: A :: B :: M ::   de rang : 3 et 3 *)\nassert(HAMNPm2 : rk(A :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABMeq : rk(Oo :: A :: B :: M :: nil) = 3) by (apply LOoABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMMtmp : rk(Oo :: A :: B :: M :: nil) <= 3) by (solve_hyps_max HOoABMeq HOoABMM3).\n\tassert(HOoABMNPmtmp : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABMNPeq HOoABMNPm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: B :: M :: nil) (A :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: N :: P :: nil) (Oo :: A :: B :: M :: A :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: A :: M :: N :: P :: nil) ((Oo :: A :: B :: M :: nil) ++ (A :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABMNPmtmp;try rewrite HT2 in HOoABMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: M :: nil) (A :: M :: N :: P :: nil) (A :: M :: nil) 3 2 3 HOoABMNPmtmp HAMmtmp HOoABMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HAMNPM3 : rk(A :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (N :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: M :: N :: P :: nil) (N :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: A :: M :: P :: nil) ((N :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (N :: nil) (A :: M :: P :: nil) (nil) 1 2 0 HNMtmp HAMPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HAMNPm3 : rk(A :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: M :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)OoABXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)OoABXMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNPm2 : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNPm3 : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXMNPm2 : rk(A :: X :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMNPmtmp : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABXMNPeq HOoABXMNPm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: P :: nil) (Oo :: A :: B :: X :: A :: X :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: M :: N :: P :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNPmtmp;try rewrite HT2 in HOoABXMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: P :: nil) (A :: X :: nil) 3 2 3 HOoABXMNPmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HAXMNPm3 : rk(A :: X :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: X :: M :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 5 5 et 5*)\nassert(HAXMNPM3 : rk(A :: X :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HAXNPMtmp : rk(A :: X :: N :: P :: nil) <= 3) by (solve_hyps_max HAXNPeq HAXNPM3).\n\tassert(HAMNPMtmp : rk(A :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HAMNPeq HAMNPM3).\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hincl : incl (A :: N :: P :: nil) (list_inter (A :: X :: N :: P :: nil) (A :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: X :: M :: N :: P :: nil) (A :: X :: N :: P :: A :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: X :: N :: P :: A :: M :: N :: P :: nil) ((A :: X :: N :: P :: nil) ++ (A :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: X :: N :: P :: nil) (A :: M :: N :: P :: nil) (A :: N :: P :: nil) 3 3 3 HAXNPMtmp HAMNPMtmp HANPmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)AXMN pour la r\u00e8gle 3  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXMNQm2 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNQm3 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)AXMN pour la r\u00e8gle 3  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoANP requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoANPm2 : rk(Oo :: A :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Bp ::   de rang : 1 et 1 *)\nassert(HOoANPm3 : rk(Oo :: A :: N :: P :: nil) >= 3).\n{\n\tassert(HBpMtmp : rk(Bp :: nil) <= 1) by (solve_hyps_max HBpeq HBpM1).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Bp :: nil) (Oo :: A :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Bp :: Oo :: A :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: Oo :: A :: N :: P :: nil) ((Bp :: nil) ++ (Oo :: A :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_4 (Bp :: nil) (Oo :: A :: N :: P :: nil) (nil) 4 0 1 HOoABpNPmtmp Hmtmp HBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 5 et -4*)\nassert(HOoANPm4 : rk(Oo :: A :: N :: P :: nil) >= 4).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(HNPmtmp : rk(N :: P :: nil) >= 2) by (solve_hyps_min HNPeq HNPm2).\n\tassert(Hincl : incl (N :: P :: nil) (list_inter (Oo :: A :: N :: P :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Oo :: A :: N :: P :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: N :: P :: Bp :: N :: P :: nil) ((Oo :: A :: N :: P :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: N :: P :: nil) (Bp :: N :: P :: nil) (N :: P :: nil) 4 2 2 HOoABpNPmtmp HNPmtmp HBpNPMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXMNPQm2 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNPQm3 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HOoAXMNPQm4 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 4).\n{\n\tassert(HOoANPmtmp : rk(Oo :: A :: N :: P :: nil) >= 4) by (solve_hyps_min HOoANPeq HOoANPm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: P :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: P :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 4 4 HOoANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXMN requis par la preuve de (?)AXMN pour la r\u00e8gle 3  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMN requis par la preuve de (?)AXMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMN requis par la preuve de (?)OoABXMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMN requis par la preuve de (?)OoABXMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNm2 : rk(Oo :: A :: B :: X :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNm3 : rk(Oo :: A :: B :: X :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXMN requis par la preuve de (?)AXMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXMNm2 : rk(A :: X :: M :: N :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMNmtmp : rk(Oo :: A :: B :: X :: M :: N :: nil) >= 3) by (solve_hyps_min HOoABXMNeq HOoABXMNm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: nil) (Oo :: A :: B :: X :: A :: X :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: M :: N :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNmtmp;try rewrite HT2 in HOoABXMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: nil) (A :: X :: nil) 3 2 3 HOoABXMNmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 3 code (6 dans la th\u00e8se) *)\n(* marque des ant\u00e9c\u00e9dents A B AUB: 5 5 et 5*)\nassert(HAXMNM3 : rk(A :: X :: M :: N :: nil) <= 3).\n{\n\tassert(HAXMNPMtmp : rk(A :: X :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HAXMNPeq HAXMNPM3).\n\tassert(HOoAXMNQMtmp : rk(Oo :: A :: X :: M :: N :: Q :: nil) <= 4) by (solve_hyps_max HOoAXMNQeq HOoAXMNQM4).\n\tassert(HOoAXMNPQmtmp : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HOoAXMNPQeq HOoAXMNPQm4).\n\tassert(Hincl : incl (A :: X :: M :: N :: nil) (list_inter (A :: X :: M :: N :: P :: nil) (Oo :: A :: X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: X :: M :: N :: P :: Q :: nil) (A :: X :: M :: N :: P :: Oo :: A :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: X :: M :: N :: P :: Oo :: A :: X :: M :: N :: Q :: nil) ((A :: X :: M :: N :: P :: nil) ++ (Oo :: A :: X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAXMNPQmtmp;try rewrite HT2 in HOoAXMNPQmtmp.\n\tassert(HT := rule_3 (A :: X :: M :: N :: P :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) (A :: X :: M :: N :: nil) 3 4 4 HAXMNPMtmp HOoAXMNQMtmp HOoAXMNPQmtmp Hincl);apply HT.\n}\ntry clear HAXMNPM1. try clear HAXMNPM2. try clear HAXMNPM3. try clear HAXMNPm4. try clear HAXMNPm3. try clear HAXMNPm2. try clear HAXMNPm1. try clear HOoAXMNPQM1. try clear HOoAXMNPQM2. try clear HOoAXMNPQM3. try clear HOoAXMNPQm4. try clear HOoAXMNPQm3. try clear HOoAXMNPQm2. try clear HOoAXMNPQm1. \n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: X :: M :: N ::  de rang :  4 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: Ap :: X ::   de rang : 3 et 3 *)\nassert(HAXMNm3 : rk(A :: X :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApXeq : rk(Oo :: A :: Ap :: X :: nil) = 3) by (apply LOoAApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApXMtmp : rk(Oo :: A :: Ap :: X :: nil) <= 3) by (solve_hyps_max HOoAApXeq HOoAApXM3).\n\tassert(HOoAApXMNeq : rk(Oo :: A :: Ap :: X :: M :: N :: nil) = 4) by (apply LOoAApXMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApXMNmtmp : rk(Oo :: A :: Ap :: X :: M :: N :: nil) >= 4) by (solve_hyps_min HOoAApXMNeq HOoAApXMNm4).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: Ap :: X :: nil) (A :: X :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: X :: M :: N :: nil) (Oo :: A :: Ap :: X :: A :: X :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: X :: A :: X :: M :: N :: nil) ((Oo :: A :: Ap :: X :: nil) ++ (A :: X :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApXMNmtmp;try rewrite HT2 in HOoAApXMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: Ap :: X :: nil) (A :: X :: M :: N :: nil) (A :: X :: nil) 4 2 3 HOoAApXMNmtmp HAXmtmp HOoAApXMtmp Hincl); apply HT.\n}\n\nassert(HAXMNM : rk(A :: X :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAXMNm : rk(A :: X :: M :: N ::  nil) >= 1) by (solve_hyps_min HAXMNeq HAXMNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LXMN *)\n(* dans constructLemma(), requis par LXMNQ *)\n(* dans constructLemma(), requis par LBXMNQ *)\n(* dans constructLemma(), requis par LBXMQ *)\n(* dans la couche 0 *)\nLemma LBApXMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Ap :: X :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BApXMQ requis par la preuve de (?)BApXMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BApXMQ requis par la preuve de (?)BApXMQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApXMQ requis par la preuve de (?)BApXMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApXMQ requis par la preuve de (?)OoABApXMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApXMQ requis par la preuve de (?)OoABApXMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApXMQm2 : rk(Oo :: A :: B :: Ap :: X :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: X :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApXMQm3 : rk(Oo :: A :: B :: Ap :: X :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: X :: M :: Q :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BApXMQ requis par la preuve de (?)BApXMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: X :: M :: Q ::  de rang :  3 et 4 \t AiB : B :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HBApXMQm2 : rk(B :: Ap :: X :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABApXMQmtmp : rk(Oo :: A :: B :: Ap :: X :: M :: Q :: nil) >= 3) by (solve_hyps_min HOoABApXMQeq HOoABApXMQm3).\n\tassert(HBApeq : rk(B :: Ap :: nil) = 2) by (apply LBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApmtmp : rk(B :: Ap :: nil) >= 2) by (solve_hyps_min HBApeq HBApm2).\n\tassert(Hincl : incl (B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (B :: Ap :: X :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: X :: M :: Q :: nil) (Oo :: A :: B :: Ap :: B :: Ap :: X :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: B :: Ap :: X :: M :: Q :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (B :: Ap :: X :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApXMQmtmp;try rewrite HT2 in HOoABApXMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (B :: Ap :: X :: M :: Q :: nil) (B :: Ap :: nil) 3 2 3 HOoABApXMQmtmp HBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -4 -4 et -2*)\nassert(HBApXMQM3 : rk(B :: Ap :: X :: M :: Q :: nil) <= 3).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HApmtmp : rk(Ap :: nil) >= 1) by (solve_hyps_min HApeq HApm1).\n\tassert(Hincl : incl (Ap :: nil) (list_inter (B :: Ap :: X :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: X :: M :: Q :: nil) (B :: Ap :: X :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: X :: Ap :: M :: Q :: nil) ((B :: Ap :: X :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (B :: Ap :: X :: nil) (Ap :: M :: Q :: nil) (Ap :: nil) 2 2 1 HBApXMtmp HApMQMtmp HApmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBApXMQm3 : rk(B :: Ap :: X :: M :: Q :: nil) >= 3).\n{\n\tassert(HBApMeq : rk(B :: Ap :: M :: nil) = 3) by (apply LBApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMmtmp : rk(B :: Ap :: M :: nil) >= 3) by (solve_hyps_min HBApMeq HBApMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (B :: Ap :: M :: nil) (B :: Ap :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: Ap :: M :: nil) (B :: Ap :: X :: M :: Q :: nil) 3 3 HBApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HBApXMQM : rk(B :: Ap :: X :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBApXMQm : rk(B :: Ap :: X :: M :: Q ::  nil) >= 1) by (solve_hyps_min HBApXMQeq HBApXMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBXMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: X :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BXMQ requis par la preuve de (?)BXMQ pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BMQ requis par la preuve de (?)BXMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 2 pour MQ requis par la preuve de (?)BMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BMNQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBMNQM3 : rk(B :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: B :: N :: Q :: nil) ((M :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HMMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBMNQm2 : rk(B :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HBMeq : rk(B :: M :: nil) = 2) by (apply LBM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMmtmp : rk(B :: M :: nil) >= 2) by (solve_hyps_min HBMeq HBMm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: nil) (B :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: nil) (B :: M :: N :: Q :: nil) 2 2 HBMmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : M ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBMNQm3 : rk(B :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: P :: nil) (B :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: M :: N :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: M :: N :: Q :: nil) (M :: nil) 4 1 2 HABMNPQmtmp HMmtmp HAMPMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour MQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 -2 et -4*)\nassert(HMQm2 : rk(M :: Q :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBMNQmtmp : rk(B :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HBMNQeq HBMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (M :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: Q :: B :: N :: Q :: nil) ((M :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBMNQmtmp;try rewrite HT2 in HBMNQmtmp.\n\tassert(HT := rule_2 (M :: Q :: nil) (B :: N :: Q :: nil) (Q :: nil) 3 1 2 HBMNQmtmp HQmtmp HBNQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Ap ::   de rang : 2 et 2 *)\nassert(HBMQm2 : rk(B :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoApMtmp : rk(Oo :: Ap :: nil) <= 2) by (solve_hyps_max HOoApeq HOoApM2).\n\tassert(HOoBApMQeq : rk(Oo :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApMQmtmp : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBApMQeq HOoBApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: nil) (B :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: M :: Q :: nil) (Oo :: Ap :: B :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: B :: M :: Q :: nil) ((Oo :: Ap :: nil) ++ (B :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApMQmtmp;try rewrite HT2 in HOoBApMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: nil) (B :: M :: Q :: nil) (nil) 4 0 2 HOoBApMQmtmp Hmtmp HOoApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 5 et -4*)\nassert(HBMQm3 : rk(B :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (B :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: M :: Q :: Ap :: M :: Q :: nil) ((B :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 3 2 2 HBApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BXMQ requis par la preuve de (?)BXMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMQ requis par la preuve de (?)BXMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMQ requis par la preuve de (?)OoABXMQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMQ requis par la preuve de (?)OoABXMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMQm2 : rk(Oo :: A :: B :: X :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMQm3 : rk(Oo :: A :: B :: X :: M :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BXMQ requis par la preuve de (?)BXMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: Q ::  de rang :  3 et 4 \t AiB : B :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HBXMQm2 : rk(B :: X :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMQmtmp : rk(Oo :: A :: B :: X :: M :: Q :: nil) >= 3) by (solve_hyps_min HOoABXMQeq HOoABXMQm3).\n\tassert(HBXeq : rk(B :: X :: nil) = 2) by (apply LBX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBXmtmp : rk(B :: X :: nil) >= 2) by (solve_hyps_min HBXeq HBXm2).\n\tassert(Hincl : incl (B :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (B :: X :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: Q :: nil) (Oo :: A :: B :: X :: B :: X :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: B :: X :: M :: Q :: nil) ((Oo :: A :: B :: X :: nil) ++ (B :: X :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMQmtmp;try rewrite HT2 in HOoABXMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (B :: X :: M :: Q :: nil) (B :: X :: nil) 3 2 3 HOoABXMQmtmp HBXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HBXMQm3 : rk(B :: X :: M :: Q :: nil) >= 3).\n{\n\tassert(HBMQmtmp : rk(B :: M :: Q :: nil) >= 3) by (solve_hyps_min HBMQeq HBMQm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: Q :: nil) (B :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: Q :: nil) (B :: X :: M :: Q :: nil) 3 3 HBMQmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBXMQM3 : rk(B :: X :: M :: Q :: nil) <= 3).\n{\n\tassert(HBApXMQeq : rk(B :: Ap :: X :: M :: Q :: nil) = 3) by (apply LBApXMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApXMQMtmp : rk(B :: Ap :: X :: M :: Q :: nil) <= 3) by (solve_hyps_max HBApXMQeq HBApXMQM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (B :: X :: M :: Q :: nil) (B :: Ap :: X :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (B :: X :: M :: Q :: nil) (B :: Ap :: X :: M :: Q :: nil) 3 3 HBApXMQMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HBXMQM : rk(B :: X :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBXMQm : rk(B :: X :: M :: Q ::  nil) >= 1) by (solve_hyps_min HBXMQeq HBXMQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBXMNQ *)\n(* dans la couche 0 *)\nLemma LBQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: Q ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour BQ requis par la preuve de (?)BQ pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HBQm2 : rk(B :: Q :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (B :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Q :: Ap :: M :: Q :: nil) ((B :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: Q :: nil) (Ap :: M :: Q :: nil) (Q :: nil) 3 1 2 HBApMQmtmp HQmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBQM : rk(B :: Q ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HBQeq HBQM2).\nassert(HBQm : rk(B :: Q ::  nil) >= 1) by (solve_hyps_min HBQeq HBQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBXMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: X :: M :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BXMNQ requis par la preuve de (?)BXMNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BMQ requis par la preuve de (?)BXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 2 pour MQ requis par la preuve de (?)BMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BMNQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBMNQM3 : rk(B :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: B :: N :: Q :: nil) ((M :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HMMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBMNQm2 : rk(B :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HBMeq : rk(B :: M :: nil) = 2) by (apply LBM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMmtmp : rk(B :: M :: nil) >= 2) by (solve_hyps_min HBMeq HBMm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: nil) (B :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: nil) (B :: M :: N :: Q :: nil) 2 2 HBMmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : M ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBMNQm3 : rk(B :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: P :: nil) (B :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: M :: N :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: M :: N :: Q :: nil) (M :: nil) 4 1 2 HABMNPQmtmp HMmtmp HAMPMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour MQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 -2 et -4*)\nassert(HMQm2 : rk(M :: Q :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBMNQmtmp : rk(B :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HBMNQeq HBMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (M :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: Q :: B :: N :: Q :: nil) ((M :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBMNQmtmp;try rewrite HT2 in HBMNQmtmp.\n\tassert(HT := rule_2 (M :: Q :: nil) (B :: N :: Q :: nil) (Q :: nil) 3 1 2 HBMNQmtmp HQmtmp HBNQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Ap ::   de rang : 2 et 2 *)\nassert(HBMQm2 : rk(B :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoApMtmp : rk(Oo :: Ap :: nil) <= 2) by (solve_hyps_max HOoApeq HOoApM2).\n\tassert(HOoBApMQeq : rk(Oo :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApMQmtmp : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBApMQeq HOoBApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: nil) (B :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: M :: Q :: nil) (Oo :: Ap :: B :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: B :: M :: Q :: nil) ((Oo :: Ap :: nil) ++ (B :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApMQmtmp;try rewrite HT2 in HOoBApMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: nil) (B :: M :: Q :: nil) (nil) 4 0 2 HOoBApMQmtmp Hmtmp HOoApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 5 et -4*)\nassert(HBMQm3 : rk(B :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (B :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: M :: Q :: Ap :: M :: Q :: nil) ((B :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 3 2 2 HBApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BXMNQ requis par la preuve de (?)BXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)BXMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNQm2 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNQm3 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BXMNQ requis par la preuve de (?)BXMNQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N :: Q ::  de rang :  3 et 4 \t AiB : B :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HBXMNQm2 : rk(B :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMNQmtmp : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HOoABXMNQeq HOoABXMNQm3).\n\tassert(HBXeq : rk(B :: X :: nil) = 2) by (apply LBX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBXmtmp : rk(B :: X :: nil) >= 2) by (solve_hyps_min HBXeq HBXm2).\n\tassert(Hincl : incl (B :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (B :: X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: Q :: nil) (Oo :: A :: B :: X :: B :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: B :: X :: M :: N :: Q :: nil) ((Oo :: A :: B :: X :: nil) ++ (B :: X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNQmtmp;try rewrite HT2 in HOoABXMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (B :: X :: M :: N :: Q :: nil) (B :: X :: nil) 3 2 3 HOoABXMNQmtmp HBXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HBXMNQm3 : rk(B :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HBMQmtmp : rk(B :: M :: Q :: nil) >= 3) by (solve_hyps_min HBMQeq HBMQm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: Q :: nil) (B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: Q :: nil) (B :: X :: M :: N :: Q :: nil) 3 3 HBMQmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et 4*)\nassert(HBXMNQM3 : rk(B :: X :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HBXMQeq : rk(B :: X :: M :: Q :: nil) = 3) by (apply LBXMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBXMQMtmp : rk(B :: X :: M :: Q :: nil) <= 3) by (solve_hyps_max HBXMQeq HBXMQM3).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBQeq : rk(B :: Q :: nil) = 2) by (apply LBQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBQmtmp : rk(B :: Q :: nil) >= 2) by (solve_hyps_min HBQeq HBQm2).\n\tassert(Hincl : incl (B :: Q :: nil) (list_inter (B :: X :: M :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: X :: M :: N :: Q :: nil) (B :: X :: M :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: X :: M :: Q :: B :: N :: Q :: nil) ((B :: X :: M :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (B :: X :: M :: Q :: nil) (B :: N :: Q :: nil) (B :: Q :: nil) 3 2 2 HBXMQMtmp HBNQMtmp HBQmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HBXMNQM : rk(B :: X :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBXMNQm : rk(B :: X :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HBXMNQeq HBXMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LXMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(X :: M :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour XMNQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMQm2 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoAApMQm3 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (C :: Oo :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Oo :: A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoACApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoAApMQm4 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: Oo :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: A :: nil) 4 2 2 HOoACApMQmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 2 pour MQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour BMNQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBMNQM3 : rk(B :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: B :: N :: Q :: nil) ((M :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HMMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBMNQm2 : rk(B :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HBMeq : rk(B :: M :: nil) = 2) by (apply LBM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMmtmp : rk(B :: M :: nil) >= 2) by (solve_hyps_min HBMeq HBMm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: nil) (B :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: nil) (B :: M :: N :: Q :: nil) 2 2 HBMmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : M ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBMNQm3 : rk(B :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: P :: nil) (B :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: M :: N :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: M :: N :: Q :: nil) (M :: nil) 4 1 2 HABMNPQmtmp HMmtmp HAMPMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour MQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 -2 et -4*)\nassert(HMQm2 : rk(M :: Q :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBMNQmtmp : rk(B :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HBMNQeq HBMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (M :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: Q :: B :: N :: Q :: nil) ((M :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBMNQmtmp;try rewrite HT2 in HBMNQmtmp.\n\tassert(HT := rule_2 (M :: Q :: nil) (B :: N :: Q :: nil) (Q :: nil) 3 1 2 HBMNQmtmp HQmtmp HBNQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAMQm2 : rk(Oo :: A :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoAMQm3 : rk(Oo :: A :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: A :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Ap :: Oo :: A :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: A :: M :: Q :: nil) ((Ap :: nil) ++ (Oo :: A :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: A :: M :: Q :: nil) (nil) 4 0 1 HOoAApMQmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 5 et -4*)\nassert(HOoAMQm4 : rk(Oo :: A :: M :: Q :: nil) >= 4).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (Oo :: A :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: A :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: M :: Q :: Ap :: M :: Q :: nil) ((Oo :: A :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_2 (Oo :: A :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 4 2 2 HOoAApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXMNQm2 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNQm3 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HOoAXMNQm4 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAMQmtmp : rk(Oo :: A :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAMQeq HOoAMQm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: Q :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: Q :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 4 4 HOoAMQmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 2 pour NQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour ApMNQ requis par la preuve de (?)NQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm2 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm3 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABApMNQm4 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M :: N :: Q ::  de rang :  4 et 4 \t AiB : Ap :: M ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Ap :: M ::   de rang : 4 et 4 *)\nassert(HApMNQm2 : rk(Ap :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABApMeq : rk(Oo :: A :: B :: Ap :: M :: nil) = 4) by (apply LOoABApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMMtmp : rk(Oo :: A :: B :: Ap :: M :: nil) <= 4) by (solve_hyps_max HOoABApMeq HOoABApMM4).\n\tassert(HOoABApMNQmtmp : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMNQeq HOoABApMNQm4).\n\tassert(HApMeq : rk(Ap :: M :: nil) = 2) by (apply LApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApMmtmp : rk(Ap :: M :: nil) >= 2) by (solve_hyps_min HApMeq HApMm2).\n\tassert(Hincl : incl (Ap :: M :: nil) (list_inter (Oo :: A :: B :: Ap :: M :: nil) (Ap :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) (Oo :: A :: B :: Ap :: M :: Ap :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: M :: Ap :: M :: N :: Q :: nil) ((Oo :: A :: B :: Ap :: M :: nil) ++ (Ap :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMNQmtmp;try rewrite HT2 in HOoABApMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: M :: nil) (Ap :: M :: N :: Q :: nil) (Ap :: M :: nil) 4 2 4 HOoABApMNQmtmp HApMmtmp HOoABApMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HApMNQM3 : rk(Ap :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (N :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: M :: N :: Q :: nil) (N :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: Ap :: M :: Q :: nil) ((N :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (N :: nil) (Ap :: M :: Q :: nil) (nil) 1 2 0 HNMtmp HApMQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Ap :: Bp :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : N ::  de rang :  1 et 1 \t A : Bp :: N :: P ::   de rang : 2 et 2 *)\nassert(HApMNQm3 : rk(Ap :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HApBpMNPQmtmp : rk(Ap :: Bp :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HApBpMNPQeq HApBpMNPQm4).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (Bp :: N :: P :: nil) (Ap :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: Bp :: M :: N :: P :: Q :: nil) (Bp :: N :: P :: Ap :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: N :: P :: Ap :: M :: N :: Q :: nil) ((Bp :: N :: P :: nil) ++ (Ap :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HApBpMNPQmtmp;try rewrite HT2 in HApBpMNPQmtmp.\n\tassert(HT := rule_4 (Bp :: N :: P :: nil) (Ap :: M :: N :: Q :: nil) (N :: nil) 4 1 2 HApBpMNPQmtmp HNmtmp HBpNPMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour NQ requis par la preuve de (?)NQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 2) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Ap :: M :: N :: Q ::  de rang :  3 et 3 \t AiB : Q ::  de rang :  1 et 1 \t A : Ap :: M :: Q ::   de rang : 2 et 2 *)\nassert(HNQm2 : rk(N :: Q :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HApMNQmtmp : rk(Ap :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HApMNQeq HApMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (Ap :: M :: Q :: nil) (N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: M :: N :: Q :: nil) (Ap :: M :: Q :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: M :: Q :: N :: Q :: nil) ((Ap :: M :: Q :: nil) ++ (N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HApMNQmtmp;try rewrite HT2 in HApMNQmtmp.\n\tassert(HT := rule_4 (Ap :: M :: Q :: nil) (N :: Q :: nil) (Q :: nil) 3 1 2 HApMNQmtmp HQmtmp HApMQMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour OoANQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour OoABNQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABNQm2 : rk(Oo :: A :: B :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABNQM3 : rk(Oo :: A :: B :: N :: Q :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: N :: Q :: nil) (Oo :: A :: B :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: N :: Q :: nil) ((Oo :: A :: B :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (B :: N :: Q :: nil) (B :: nil) 2 2 1 HOoABMtmp HBNQMtmp HBmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABNQm3 : rk(Oo :: A :: B :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANeq : rk(Oo :: A :: N :: nil) = 3) by (apply LOoAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANmtmp : rk(Oo :: A :: N :: nil) >= 3) by (solve_hyps_min HOoANeq HOoANm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil) 3 3 HOoANmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoANQm2 : rk(Oo :: A :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoANQm3 : rk(Oo :: A :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANeq : rk(Oo :: A :: N :: nil) = 3) by (apply LOoAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANmtmp : rk(Oo :: A :: N :: nil) >= 3) by (solve_hyps_min HOoANeq HOoANm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: nil) (Oo :: A :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: nil) (Oo :: A :: N :: Q :: nil) 3 3 HOoANmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HOoANQM3 : rk(Oo :: A :: N :: Q :: nil) <= 3).\n{\n\tassert(HOoABNQMtmp : rk(Oo :: A :: B :: N :: Q :: nil) <= 3) by (solve_hyps_max HOoABNQeq HOoABNQM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: Q :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: N :: Q :: nil) (Oo :: A :: B :: N :: Q :: nil) 3 3 HOoABNQMtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour XMNQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNQm2 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNQm3 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HOoABXMNQm4 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAMQmtmp : rk(Oo :: A :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAMQeq HOoAMQm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: Q :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: Q :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 4 4 HOoAMQmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoABMQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMQm2 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoABApMQm3 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (C :: Oo :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: B :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoABCApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoABApMQm4 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: Oo :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) (Oo :: A :: nil) 4 2 2 HOoABCApMQmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMQm2 : rk(Oo :: A :: B :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoABMQm3 : rk(Oo :: A :: B :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoABApMQmtmp : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMQeq HOoABApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: A :: B :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: Q :: nil) (Ap :: Oo :: A :: B :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: A :: B :: M :: Q :: nil) ((Ap :: nil) ++ (Oo :: A :: B :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMQmtmp;try rewrite HT2 in HOoABApMQmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: A :: B :: M :: Q :: nil) (nil) 4 0 1 HOoABApMQmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 5 et -4*)\nassert(HOoABMQm4 : rk(Oo :: A :: B :: M :: Q :: nil) >= 4).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoABApMQmtmp : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMQeq HOoABApMQm4).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (Oo :: A :: B :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: Q :: nil) (Oo :: A :: B :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: Q :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMQmtmp;try rewrite HT2 in HOoABApMQmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 4 2 2 HOoABApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour XMNQ requis par la preuve de (?)XMNQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 5 et 5*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N :: Q ::  de rang :  4 et 4 \t AiB : M :: Q ::  de rang :  2 et 2 \t A : Oo :: A :: B :: M :: Q ::   de rang : 4 et 4 *)\nassert(HXMNQm2 : rk(X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABMQMtmp : rk(Oo :: A :: B :: M :: Q :: nil) <= 4) by (solve_hyps_max HOoABMQeq HOoABMQM4).\n\tassert(HOoABXMNQmtmp : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoABXMNQeq HOoABXMNQm4).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (Oo :: A :: B :: M :: Q :: nil) (X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: Q :: nil) (Oo :: A :: B :: M :: Q :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: Q :: X :: M :: N :: Q :: nil) ((Oo :: A :: B :: M :: Q :: nil) ++ (X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNQmtmp;try rewrite HT2 in HOoABXMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: M :: Q :: nil) (X :: M :: N :: Q :: nil) (M :: Q :: nil) 4 2 4 HOoABXMNQmtmp HMQmtmp HOoABMQMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 5 et 5*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: X :: M :: N :: Q ::  de rang :  4 et 4 \t AiB : N :: Q ::  de rang :  2 et 2 \t A : Oo :: A :: N :: Q ::   de rang : 3 et 3 *)\nassert(HXMNQm3 : rk(X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANQMtmp : rk(Oo :: A :: N :: Q :: nil) <= 3) by (solve_hyps_max HOoANQeq HOoANQM3).\n\tassert(HOoAXMNQmtmp : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoAXMNQeq HOoAXMNQm4).\n\tassert(HNQmtmp : rk(N :: Q :: nil) >= 2) by (solve_hyps_min HNQeq HNQm2).\n\tassert(Hincl : incl (N :: Q :: nil) (list_inter (Oo :: A :: N :: Q :: nil) (X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: X :: M :: N :: Q :: nil) (Oo :: A :: N :: Q :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: N :: Q :: X :: M :: N :: Q :: nil) ((Oo :: A :: N :: Q :: nil) ++ (X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAXMNQmtmp;try rewrite HT2 in HOoAXMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: N :: Q :: nil) (X :: M :: N :: Q :: nil) (N :: Q :: nil) 4 2 3 HOoAXMNQmtmp HNQmtmp HOoANQMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HXMNQM3 : rk(X :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HBXMNQeq : rk(B :: X :: M :: N :: Q :: nil) = 3) by (apply LBXMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBXMNQMtmp : rk(B :: X :: M :: N :: Q :: nil) <= 3) by (solve_hyps_max HBXMNQeq HBXMNQM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (X :: M :: N :: Q :: nil) (B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (X :: M :: N :: Q :: nil) (B :: X :: M :: N :: Q :: nil) 3 3 HBXMNQMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HXMNQM : rk(X :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HXMNQm : rk(X :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HXMNQeq HXMNQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LXMN *)\n(* dans constructLemma(), requis par LAXMNQ *)\n(* dans constructLemma(), requis par LOoAXMNQ *)\n(* dans constructLemma(), requis par LOoAMQ *)\n(* dans la couche 0 *)\nLemma LOoAApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApMQ requis par la preuve de (?)OoAApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApMQm2 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoAApMQm3 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (C :: Oo :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Oo :: A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoACApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoAApMQm4 : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoACApMQeq : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) = 4) by (apply LOoACApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMQmtmp : rk(Oo :: A :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoACApMQeq HOoACApMQm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: Oo :: A :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApMQmtmp;try rewrite HT2 in HOoACApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: A :: nil) 4 2 2 HOoACApMQmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HOoAApMQM : rk(Oo :: A :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApMQm : rk(Oo :: A :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoAApMQeq HOoAApMQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoAMQ *)\n(* dans constructLemma(), requis par LMQ *)\n(* dans la couche 0 *)\nLemma LBMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: M :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BMNQ requis par la preuve de (?)BMNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBMNQM3 : rk(B :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HMMtmp : rk(M :: nil) <= 1) by (solve_hyps_max HMeq HMM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (M :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: B :: N :: Q :: nil) ((M :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (M :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HMMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HBMNQm2 : rk(B :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HBMeq : rk(B :: M :: nil) = 2) by (apply LBM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMmtmp : rk(B :: M :: nil) >= 2) by (solve_hyps_min HBMeq HBMm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: M :: nil) (B :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: M :: nil) (B :: M :: N :: Q :: nil) 2 2 HBMmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : M ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBMNQm3 : rk(B :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (A :: M :: P :: nil) (B :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: M :: N :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: M :: N :: Q :: nil) (M :: nil) 4 1 2 HABMNPQmtmp HMmtmp HAMPMtmp Hincl); apply HT.\n}\n\nassert(HBMNQM : rk(B :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBMNQm : rk(B :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HBMNQeq HBMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(M :: Q ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour MQ requis par la preuve de (?)MQ pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HMQm2 : rk(M :: Q :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBMNQeq : rk(B :: M :: N :: Q :: nil) = 3) by (apply LBMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBMNQmtmp : rk(B :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HBMNQeq HBMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (M :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: M :: N :: Q :: nil) (M :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (M :: Q :: B :: N :: Q :: nil) ((M :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBMNQmtmp;try rewrite HT2 in HBMNQmtmp.\n\tassert(HT := rule_2 (M :: Q :: nil) (B :: N :: Q :: nil) (Q :: nil) 3 1 2 HBMNQmtmp HQmtmp HBNQMtmp Hincl);apply HT.\n}\n\nassert(HMQM : rk(M :: Q ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HMQeq HMQM2).\nassert(HMQm : rk(M :: Q ::  nil) >= 1) by (solve_hyps_min HMQeq HMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAMQ requis par la preuve de (?)OoAMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAMQm2 : rk(Oo :: A :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoAMQm3 : rk(Oo :: A :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoAApMQeq : rk(Oo :: A :: Ap :: M :: Q :: nil) = 4) by (apply LOoAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: A :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Ap :: Oo :: A :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: A :: M :: Q :: nil) ((Ap :: nil) ++ (Oo :: A :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: A :: M :: Q :: nil) (nil) 4 0 1 HOoAApMQmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAMQm4 : rk(Oo :: A :: M :: Q :: nil) >= 4).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoAApMQeq : rk(Oo :: A :: Ap :: M :: Q :: nil) = 4) by (apply LOoAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(HMQeq : rk(M :: Q :: nil) = 2) by (apply LMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (Oo :: A :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: A :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: M :: Q :: Ap :: M :: Q :: nil) ((Oo :: A :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_2 (Oo :: A :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 4 2 2 HOoAApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HOoAMQM : rk(Oo :: A :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAMQm : rk(Oo :: A :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoAMQeq HOoAMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAXMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: X :: M :: N :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAXMNQ requis par la preuve de (?)OoAXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXMNQm2 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNQm3 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNQm4 : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAMQeq : rk(Oo :: A :: M :: Q :: nil) = 4) by (apply LOoAMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMQmtmp : rk(Oo :: A :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAMQeq HOoAMQm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: Q :: nil) (Oo :: A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: Q :: nil) (Oo :: A :: X :: M :: N :: Q :: nil) 4 4 HOoAMQmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAXMNQM : rk(Oo :: A :: X :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAXMNQm : rk(Oo :: A :: X :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoAXMNQeq HOoAXMNQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAXMNQ *)\n(* dans constructLemma(), requis par LANQ *)\n(* dans la couche 0 *)\nLemma LABNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABNQ requis par la preuve de (?)ABNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ABNQ requis par la preuve de (?)ABNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABNQ requis par la preuve de (?)ABNQ pour la r\u00e8gle 1  *)\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HABNQM3 : rk(A :: B :: N :: Q :: nil) <= 3).\n{\n\tassert(HAMtmp : rk(A :: nil) <= 1) by (solve_hyps_max HAeq HAM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (A :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: N :: Q :: nil) (A :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: N :: Q :: nil) ((A :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HAMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABNQm2 : rk(A :: B :: N :: Q :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: N :: Q :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HABNQm3 : rk(A :: B :: N :: Q :: nil) >= 3).\n{\n\tassert(HABNeq : rk(A :: B :: N :: nil) = 3) by (apply LABN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABNmtmp : rk(A :: B :: N :: nil) >= 3) by (solve_hyps_min HABNeq HABNm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: N :: nil) (A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: N :: nil) (A :: B :: N :: Q :: nil) 3 3 HABNmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HABNQM : rk(A :: B :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABNQm : rk(A :: B :: N :: Q ::  nil) >= 1) by (solve_hyps_min HABNQeq HABNQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LANQ *)\n(* dans constructLemma(), requis par LNQ *)\n(* dans la couche 0 *)\nLemma LApMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: M :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm2 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm3 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABApMNQm4 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ApMNQ requis par la preuve de (?)ApMNQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M :: N :: Q ::  de rang :  4 et 4 \t AiB : Ap :: M ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Ap :: M ::   de rang : 4 et 4 *)\nassert(HApMNQm2 : rk(Ap :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABApMeq : rk(Oo :: A :: B :: Ap :: M :: nil) = 4) by (apply LOoABApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMMtmp : rk(Oo :: A :: B :: Ap :: M :: nil) <= 4) by (solve_hyps_max HOoABApMeq HOoABApMM4).\n\tassert(HOoABApMNQmtmp : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMNQeq HOoABApMNQm4).\n\tassert(HApMeq : rk(Ap :: M :: nil) = 2) by (apply LApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApMmtmp : rk(Ap :: M :: nil) >= 2) by (solve_hyps_min HApMeq HApMm2).\n\tassert(Hincl : incl (Ap :: M :: nil) (list_inter (Oo :: A :: B :: Ap :: M :: nil) (Ap :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) (Oo :: A :: B :: Ap :: M :: Ap :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: M :: Ap :: M :: N :: Q :: nil) ((Oo :: A :: B :: Ap :: M :: nil) ++ (Ap :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMNQmtmp;try rewrite HT2 in HOoABApMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: M :: nil) (Ap :: M :: N :: Q :: nil) (Ap :: M :: nil) 4 2 4 HOoABApMNQmtmp HApMmtmp HOoABApMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HApMNQM3 : rk(Ap :: M :: N :: Q :: nil) <= 3).\n{\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (N :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: M :: N :: Q :: nil) (N :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: Ap :: M :: Q :: nil) ((N :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (N :: nil) (Ap :: M :: Q :: nil) (nil) 1 2 0 HNMtmp HApMQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Ap :: Bp :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : N ::  de rang :  1 et 1 \t A : Bp :: N :: P ::   de rang : 2 et 2 *)\nassert(HApMNQm3 : rk(Ap :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HApBpMNPQmtmp : rk(Ap :: Bp :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HApBpMNPQeq HApBpMNPQm4).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (Bp :: N :: P :: nil) (Ap :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: Bp :: M :: N :: P :: Q :: nil) (Bp :: N :: P :: Ap :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: N :: P :: Ap :: M :: N :: Q :: nil) ((Bp :: N :: P :: nil) ++ (Ap :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HApBpMNPQmtmp;try rewrite HT2 in HApBpMNPQmtmp.\n\tassert(HT := rule_4 (Bp :: N :: P :: nil) (Ap :: M :: N :: Q :: nil) (N :: nil) 4 1 2 HApBpMNPQmtmp HNmtmp HBpNPMtmp Hincl); apply HT.\n}\n\nassert(HApMNQM : rk(Ap :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HApMNQm : rk(Ap :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HApMNQeq HApMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(N :: Q ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour NQ requis par la preuve de (?)NQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 2) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : Ap :: M :: N :: Q ::  de rang :  3 et 3 \t AiB : Q ::  de rang :  1 et 1 \t A : Ap :: M :: Q ::   de rang : 2 et 2 *)\nassert(HNQm2 : rk(N :: Q :: nil) >= 2).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HApMNQeq : rk(Ap :: M :: N :: Q :: nil) = 3) by (apply LApMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApMNQmtmp : rk(Ap :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HApMNQeq HApMNQm3).\n\tassert(HQmtmp : rk(Q :: nil) >= 1) by (solve_hyps_min HQeq HQm1).\n\tassert(Hincl : incl (Q :: nil) (list_inter (Ap :: M :: Q :: nil) (N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: M :: N :: Q :: nil) (Ap :: M :: Q :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: M :: Q :: N :: Q :: nil) ((Ap :: M :: Q :: nil) ++ (N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HApMNQmtmp;try rewrite HT2 in HApMNQmtmp.\n\tassert(HT := rule_4 (Ap :: M :: Q :: nil) (N :: Q :: nil) (Q :: nil) 3 1 2 HApMNQmtmp HQmtmp HApMQMtmp Hincl); apply HT.\n}\n\nassert(HNQM : rk(N :: Q ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HNQeq HNQM2).\nassert(HNQm : rk(N :: Q ::  nil) >= 1) by (solve_hyps_min HNQeq HNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LANQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ANQ requis par la preuve de (?)ANQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour OoABNQ requis par la preuve de (?)ANQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABNQm2 : rk(Oo :: A :: B :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABNQM3 : rk(Oo :: A :: B :: N :: Q :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: N :: Q :: nil) (Oo :: A :: B :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: N :: Q :: nil) ((Oo :: A :: B :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (B :: N :: Q :: nil) (B :: nil) 2 2 1 HOoABMtmp HBNQMtmp HBmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABNQm3 : rk(Oo :: A :: B :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANeq : rk(Oo :: A :: N :: nil) = 3) by (apply LOoAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANmtmp : rk(Oo :: A :: N :: nil) >= 3) by (solve_hyps_min HOoANeq HOoANm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil) 3 3 HOoANmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ANQ requis par la preuve de (?)ANQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: N :: Q ::  de rang :  3 et 3 \t AiB : A :: N ::  de rang :  2 et 2 \t A : Oo :: A :: B :: N ::   de rang : 3 et 3 *)\nassert(HANQm2 : rk(A :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABNeq : rk(Oo :: A :: B :: N :: nil) = 3) by (apply LOoABN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABNMtmp : rk(Oo :: A :: B :: N :: nil) <= 3) by (solve_hyps_max HOoABNeq HOoABNM3).\n\tassert(HOoABNQmtmp : rk(Oo :: A :: B :: N :: Q :: nil) >= 3) by (solve_hyps_min HOoABNQeq HOoABNQm3).\n\tassert(HANeq : rk(A :: N :: nil) = 2) by (apply LAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANmtmp : rk(A :: N :: nil) >= 2) by (solve_hyps_min HANeq HANm2).\n\tassert(Hincl : incl (A :: N :: nil) (list_inter (Oo :: A :: B :: N :: nil) (A :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: N :: Q :: nil) (Oo :: A :: B :: N :: A :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: N :: A :: N :: Q :: nil) ((Oo :: A :: B :: N :: nil) ++ (A :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABNQmtmp;try rewrite HT2 in HOoABNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: N :: nil) (A :: N :: Q :: nil) (A :: N :: nil) 3 2 3 HOoABNQmtmp HANmtmp HOoABNMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HANQm3 : rk(A :: N :: Q :: nil) >= 3).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HABNQeq : rk(A :: B :: N :: Q :: nil) = 3) by (apply LABNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABNQmtmp : rk(A :: B :: N :: Q :: nil) >= 3) by (solve_hyps_min HABNQeq HABNQm3).\n\tassert(HNQeq : rk(N :: Q :: nil) = 2) by (apply LNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HNQmtmp : rk(N :: Q :: nil) >= 2) by (solve_hyps_min HNQeq HNQm2).\n\tassert(Hincl : incl (N :: Q :: nil) (list_inter (A :: N :: Q :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: N :: Q :: nil) (A :: N :: Q :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: N :: Q :: B :: N :: Q :: nil) ((A :: N :: Q :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABNQmtmp;try rewrite HT2 in HABNQmtmp.\n\tassert(HT := rule_2 (A :: N :: Q :: nil) (B :: N :: Q :: nil) (N :: Q :: nil) 3 2 2 HABNQmtmp HNQmtmp HBNQMtmp Hincl);apply HT.\n}\n\nassert(HANQM : rk(A :: N :: Q ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HANQeq HANQM3).\nassert(HANQm : rk(A :: N :: Q ::  nil) >= 1) by (solve_hyps_min HANQeq HANQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAXMNQ *)\n(* dans constructLemma(), requis par LOoANQ *)\n(* dans la couche 0 *)\nLemma LOoABNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABNQ requis par la preuve de (?)OoABNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABNQm2 : rk(Oo :: A :: B :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABNQM3 : rk(Oo :: A :: B :: N :: Q :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (Oo :: A :: B :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: N :: Q :: nil) (Oo :: A :: B :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: B :: N :: Q :: nil) ((Oo :: A :: B :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (B :: N :: Q :: nil) (B :: nil) 2 2 1 HOoABMtmp HBNQMtmp HBmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABNQm3 : rk(Oo :: A :: B :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANeq : rk(Oo :: A :: N :: nil) = 3) by (apply LOoAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANmtmp : rk(Oo :: A :: N :: nil) >= 3) by (solve_hyps_min HOoANeq HOoANm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: nil) (Oo :: A :: B :: N :: Q :: nil) 3 3 HOoANmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABNQM : rk(Oo :: A :: B :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABNQm : rk(Oo :: A :: B :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoABNQeq HOoABNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoANQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: N :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoANQ requis par la preuve de (?)OoANQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoANQm2 : rk(Oo :: A :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoANQm3 : rk(Oo :: A :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoANeq : rk(Oo :: A :: N :: nil) = 3) by (apply LOoAN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANmtmp : rk(Oo :: A :: N :: nil) >= 3) by (solve_hyps_min HOoANeq HOoANm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: nil) (Oo :: A :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: nil) (Oo :: A :: N :: Q :: nil) 3 3 HOoANmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoANQM3 : rk(Oo :: A :: N :: Q :: nil) <= 3).\n{\n\tassert(HOoABNQeq : rk(Oo :: A :: B :: N :: Q :: nil) = 3) by (apply LOoABNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABNQMtmp : rk(Oo :: A :: B :: N :: Q :: nil) <= 3) by (solve_hyps_max HOoABNQeq HOoABNQM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: Q :: nil) (Oo :: A :: B :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Oo :: A :: N :: Q :: nil) (Oo :: A :: B :: N :: Q :: nil) 3 3 HOoABNQMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoANQM : rk(Oo :: A :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoANQm : rk(Oo :: A :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoANQeq HOoANQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAXMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: X :: M :: N :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AXMNQ requis par la preuve de (?)AXMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour AMQ requis par la preuve de (?)AXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AMQ requis par la preuve de (?)AMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AMQ requis par la preuve de (?)AMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Ap ::   de rang : 2 et 2 *)\nassert(HAMQm2 : rk(A :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoApMtmp : rk(Oo :: Ap :: nil) <= 2) by (solve_hyps_max HOoApeq HOoApM2).\n\tassert(HOoAApMQeq : rk(Oo :: A :: Ap :: M :: Q :: nil) = 4) by (apply LOoAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: nil) (A :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: Ap :: A :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: A :: M :: Q :: nil) ((Oo :: Ap :: nil) ++ (A :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: nil) (A :: M :: Q :: nil) (nil) 4 0 2 HOoAApMQmtmp Hmtmp HOoApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HAMQm3 : rk(A :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HAApMQeq : rk(A :: Ap :: M :: Q :: nil) = 3) by (apply LAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApMQmtmp : rk(A :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HAApMQeq HAApMQm3).\n\tassert(HMQeq : rk(M :: Q :: nil) = 2) by (apply LMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (A :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: Q :: nil) (A :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: Q :: Ap :: M :: Q :: nil) ((A :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApMQmtmp;try rewrite HT2 in HAApMQmtmp.\n\tassert(HT := rule_2 (A :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 3 2 2 HAApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXMNQ requis par la preuve de (?)AXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)AXMNQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNQm2 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNQm3 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXMNQ requis par la preuve de (?)AXMNQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N :: Q ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXMNQm2 : rk(A :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMNQmtmp : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3) by (solve_hyps_min HOoABXMNQeq HOoABXMNQm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: Q :: nil) (Oo :: A :: B :: X :: A :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: M :: N :: Q :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNQmtmp;try rewrite HT2 in HOoABXMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: Q :: nil) (A :: X :: nil) 3 2 3 HOoABXMNQmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 5 *)\nassert(HAXMNQm3 : rk(A :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HAMQmtmp : rk(A :: M :: Q :: nil) >= 3) by (solve_hyps_min HAMQeq HAMQm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: M :: Q :: nil) (A :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: M :: Q :: nil) (A :: X :: M :: N :: Q :: nil) 3 3 HAMQmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: X :: M :: N :: Q ::  de rang :  4 et 4 \t AiB : A :: N :: Q ::  de rang :  3 et 3 \t A : Oo :: A :: N :: Q ::   de rang : 3 et 3 *)\nassert(HAXMNQm4 : rk(A :: X :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoANQeq : rk(Oo :: A :: N :: Q :: nil) = 3) by (apply LOoANQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANQMtmp : rk(Oo :: A :: N :: Q :: nil) <= 3) by (solve_hyps_max HOoANQeq HOoANQM3).\n\tassert(HOoAXMNQeq : rk(Oo :: A :: X :: M :: N :: Q :: nil) = 4) by (apply LOoAXMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXMNQmtmp : rk(Oo :: A :: X :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HOoAXMNQeq HOoAXMNQm4).\n\tassert(HANQeq : rk(A :: N :: Q :: nil) = 3) by (apply LANQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANQmtmp : rk(A :: N :: Q :: nil) >= 3) by (solve_hyps_min HANQeq HANQm3).\n\tassert(Hincl : incl (A :: N :: Q :: nil) (list_inter (Oo :: A :: N :: Q :: nil) (A :: X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: X :: M :: N :: Q :: nil) (Oo :: A :: N :: Q :: A :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: N :: Q :: A :: X :: M :: N :: Q :: nil) ((Oo :: A :: N :: Q :: nil) ++ (A :: X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAXMNQmtmp;try rewrite HT2 in HOoAXMNQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: N :: Q :: nil) (A :: X :: M :: N :: Q :: nil) (A :: N :: Q :: nil) 4 3 3 HOoAXMNQmtmp HANQmtmp HOoANQMtmp Hincl); apply HT.\n}\n\nassert(HAXMNQM : rk(A :: X :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAXMNQm : rk(A :: X :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HAXMNQeq HAXMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LXMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(X :: M :: N ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour XMN requis par la preuve de (?)XMN pour la r\u00e8gle 3  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour XMN requis par la preuve de (?)XMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: X :: M :: N ::  de rang :  4 et 4 \t AiB : X ::  de rang :  1 et 1 \t A : Oo :: A :: Ap :: X ::   de rang : 3 et 3 *)\nassert(HXMNm2 : rk(X :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAApXeq : rk(Oo :: A :: Ap :: X :: nil) = 3) by (apply LOoAApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApXMtmp : rk(Oo :: A :: Ap :: X :: nil) <= 3) by (solve_hyps_max HOoAApXeq HOoAApXM3).\n\tassert(HOoAApXMNeq : rk(Oo :: A :: Ap :: X :: M :: N :: nil) = 4) by (apply LOoAApXMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApXMNmtmp : rk(Oo :: A :: Ap :: X :: M :: N :: nil) >= 4) by (solve_hyps_min HOoAApXMNeq HOoAApXMNm4).\n\tassert(HXmtmp : rk(X :: nil) >= 1) by (solve_hyps_min HXeq HXm1).\n\tassert(Hincl : incl (X :: nil) (list_inter (Oo :: A :: Ap :: X :: nil) (X :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: X :: M :: N :: nil) (Oo :: A :: Ap :: X :: X :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: X :: X :: M :: N :: nil) ((Oo :: A :: Ap :: X :: nil) ++ (X :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApXMNmtmp;try rewrite HT2 in HOoAApXMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: Ap :: X :: nil) (X :: M :: N :: nil) (X :: nil) 4 1 3 HOoAApXMNmtmp HXmtmp HOoAApXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 3 code (6 dans la th\u00e8se) *)\n(* marque des ant\u00e9c\u00e9dents A B AUB: 4 4 et 4*)\nassert(HXMNM2 : rk(X :: M :: N :: nil) <= 2).\n{\n\tassert(HAXMNeq : rk(A :: X :: M :: N :: nil) = 3) by (apply LAXMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXMNMtmp : rk(A :: X :: M :: N :: nil) <= 3) by (solve_hyps_max HAXMNeq HAXMNM3).\n\tassert(HXMNQeq : rk(X :: M :: N :: Q :: nil) = 3) by (apply LXMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HXMNQMtmp : rk(X :: M :: N :: Q :: nil) <= 3) by (solve_hyps_max HXMNQeq HXMNQM3).\n\tassert(HAXMNQeq : rk(A :: X :: M :: N :: Q :: nil) = 4) by (apply LAXMNQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXMNQmtmp : rk(A :: X :: M :: N :: Q :: nil) >= 4) by (solve_hyps_min HAXMNQeq HAXMNQm4).\n\tassert(Hincl : incl (X :: M :: N :: nil) (list_inter (A :: X :: M :: N :: nil) (X :: M :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: X :: M :: N :: Q :: nil) (A :: X :: M :: N :: X :: M :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: X :: M :: N :: X :: M :: N :: Q :: nil) ((A :: X :: M :: N :: nil) ++ (X :: M :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAXMNQmtmp;try rewrite HT2 in HAXMNQmtmp.\n\tassert(HT := rule_3 (A :: X :: M :: N :: nil) (X :: M :: N :: Q :: nil) (X :: M :: N :: nil) 3 3 4 HAXMNMtmp HXMNQMtmp HAXMNQmtmp Hincl);apply HT.\n}\n\n\nassert(HXMNM : rk(X :: M :: N ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HXMNeq HXMNM3).\nassert(HXMNm : rk(X :: M :: N ::  nil) >= 1) by (solve_hyps_min HXMNeq HXMNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoAApYZMN *)\n(* dans la couche 0 *)\nLemma LOoAApYZMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApYZMNP requis par la preuve de (?)OoAApYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApYZMNP requis par la preuve de (?)OoAApYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApYZMNP requis par la preuve de (?)OoAApYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYZMNPm2 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYZMNPm3 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAApYZMNPm4 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAApYZMNPM : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApYZMNPm : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoAApYZMNPeq HOoAApYZMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAApYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: Ap :: Y :: Z :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAApYZMN requis par la preuve de (?)OoAApYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAApYZMN requis par la preuve de (?)OoAApYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAApYZMN requis par la preuve de (?)OoAApYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYZMNm2 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAApYZMNm3 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoAApYZMNm4 : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HOoAApYZMNPeq : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) = 4) by (apply LOoAApYZMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApYZMNPmtmp : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HOoAApYZMNPeq HOoAApYZMNPm4).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: Ap :: Y :: Z :: M :: N :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: Y :: Z :: M :: N :: A :: M :: P :: nil) ((Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApYZMNPmtmp;try rewrite HT2 in HOoAApYZMNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) (A :: M :: P :: nil) (A :: M :: nil) 4 2 2 HOoAApYZMNPmtmp HAMmtmp HAMPMtmp Hincl);apply HT.\n}\n\nassert(HOoAApYZMNM : rk(Oo :: A :: Ap :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAApYZMNm : rk(Oo :: A :: Ap :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HOoAApYZMNeq HOoAApYZMNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCBpYZMN *)\n(* dans constructLemma(), requis par LCApBpYZMN *)\n(* dans constructLemma(), requis par LCApBpYZMNP *)\n(* dans la couche 0 *)\nLemma LOoCApBpYZMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoACApBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoACApBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNPm2 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNPm3 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpYZMNPm2 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpYZMNPm3 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpYZMNPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpYZMNPeq HOoACApBpYZMNPm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpYZMNPmtmp;try rewrite HT2 in HOoACApBpYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpYZMNPmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoCApBpYZMNPm4 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HOoCApMeq : rk(Oo :: C :: Ap :: M :: nil) = 4) by (apply LOoCApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApMmtmp : rk(Oo :: C :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoCApMeq HOoCApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 4 4 HOoCApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoCApBpYZMNPM : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApBpYZMNPm : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoCApBpYZMNPeq HOoCApBpYZMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApBpYZMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApBpYZMNP requis par la preuve de (?)CApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)CApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoACApBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpYZMNP requis par la preuve de (?)OoACApBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNPm2 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNPm3 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpYZMNP requis par la preuve de (?)OoCApBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpYZMNPm2 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpYZMNPm3 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpYZMNPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpYZMNPeq HOoACApBpYZMNPm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpYZMNPmtmp;try rewrite HT2 in HOoACApBpYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpYZMNPmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApBpYZMNP requis par la preuve de (?)CApBpYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApBpYZMNP requis par la preuve de (?)CApBpYZMNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApBpYZMNPm2 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpYZMNPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpYZMNPeq HOoACApBpYZMNPm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpYZMNPmtmp;try rewrite HT2 in HOoACApBpYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (C :: Ap :: nil) 3 2 3 HOoACApBpYZMNPmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HCApBpYZMNPm3 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoCApBpYZMNPmtmp : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoCApBpYZMNPeq HOoCApBpYZMNPm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: Ap :: Bp :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpYZMNPmtmp;try rewrite HT2 in HOoCApBpYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Ap :: Bp :: nil) 3 2 2 HOoCApBpYZMNPmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  de rang :  4 et 4 \t AiB : Ap :: Bp :: M ::  de rang :  3 et 3 \t A : Oo :: Ap :: Bp :: M ::   de rang : 3 et 3 *)\nassert(HCApBpYZMNPm4 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HOoApBpMeq : rk(Oo :: Ap :: Bp :: M :: nil) = 3) by (apply LOoApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMMtmp : rk(Oo :: Ap :: Bp :: M :: nil) <= 3) by (solve_hyps_max HOoApBpMeq HOoApBpMM3).\n\tassert(HOoCApBpYZMNPeq : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) = 4) by (apply LOoCApBpYZMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApBpYZMNPmtmp : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HOoCApBpYZMNPeq HOoCApBpYZMNPm4).\n\tassert(HApBpMeq : rk(Ap :: Bp :: M :: nil) = 3) by (apply LApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApBpMmtmp : rk(Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HApBpMeq HApBpMm3).\n\tassert(Hincl : incl (Ap :: Bp :: M :: nil) (list_inter (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) ((Oo :: Ap :: Bp :: M :: nil) ++ (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpYZMNPmtmp;try rewrite HT2 in HOoCApBpYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (Ap :: Bp :: M :: nil) 4 3 3 HOoCApBpYZMNPmtmp HApBpMmtmp HOoApBpMMtmp Hincl); apply HT.\n}\n\nassert(HCApBpYZMNPM : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApBpYZMNPm : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HCApBpYZMNPeq HCApBpYZMNPm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCApBpYZMN *)\n(* dans constructLemma(), requis par LCApBpMP *)\n(* dans la couche 0 *)\nLemma LOoCApBpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: C :: Ap :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoACApBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoACApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMPm2 : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMPm3 : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpMPm2 : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M :: P ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpMPm3 : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpMPeq HOoACApBpMPm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMPmtmp;try rewrite HT2 in HOoACApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpMPmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoCApBpMPm4 : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoCApMeq : rk(Oo :: C :: Ap :: M :: nil) = 4) by (apply LOoCApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApMmtmp : rk(Oo :: C :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoCApMeq HOoCApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: Ap :: M :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil) 4 4 HOoCApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoCApBpMPM : rk(Oo :: C :: Ap :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoCApBpMPm : rk(Oo :: C :: Ap :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoCApBpMPeq HOoCApBpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApBpMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: Bp :: M :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApBpMP requis par la preuve de (?)CApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)CApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoACApBpMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpMP requis par la preuve de (?)OoACApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMPm2 : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpMPm3 : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpMP requis par la preuve de (?)OoCApBpMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpMPm2 : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M :: P ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpMPm3 : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpMPeq HOoACApBpMPm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: M :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMPmtmp;try rewrite HT2 in HOoACApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpMPmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApBpMP requis par la preuve de (?)CApBpMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApBpMP requis par la preuve de (?)CApBpMP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: M :: P ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApBpMPm2 : rk(C :: Ap :: Bp :: M :: P :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpMPmtmp : rk(Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) >= 3) by (solve_hyps_min HOoACApBpMPeq HOoACApBpMPm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: M :: P :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpMPmtmp;try rewrite HT2 in HOoACApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: M :: P :: nil) (C :: Ap :: nil) 3 2 3 HOoACApBpMPmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: M :: P ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HCApBpMPm3 : rk(C :: Ap :: Bp :: M :: P :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoCApBpMPmtmp : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 3) by (solve_hyps_min HOoCApBpMPeq HOoCApBpMPm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: C :: Ap :: Bp :: M :: P :: nil) ((Oo :: Ap :: Bp :: nil) ++ (C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpMPmtmp;try rewrite HT2 in HOoCApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: M :: P :: nil) (Ap :: Bp :: nil) 3 2 2 HOoCApBpMPmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: M :: P ::  de rang :  4 et 4 \t AiB : Ap :: Bp :: M ::  de rang :  3 et 3 \t A : Oo :: Ap :: Bp :: M ::   de rang : 3 et 3 *)\nassert(HCApBpMPm4 : rk(C :: Ap :: Bp :: M :: P :: nil) >= 4).\n{\n\tassert(HOoApBpMeq : rk(Oo :: Ap :: Bp :: M :: nil) = 3) by (apply LOoApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMMtmp : rk(Oo :: Ap :: Bp :: M :: nil) <= 3) by (solve_hyps_max HOoApBpMeq HOoApBpMM3).\n\tassert(HOoCApBpMPeq : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) = 4) by (apply LOoCApBpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApBpMPmtmp : rk(Oo :: C :: Ap :: Bp :: M :: P :: nil) >= 4) by (solve_hyps_min HOoCApBpMPeq HOoCApBpMPm4).\n\tassert(HApBpMeq : rk(Ap :: Bp :: M :: nil) = 3) by (apply LApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApBpMmtmp : rk(Ap :: Bp :: M :: nil) >= 3) by (solve_hyps_min HApBpMeq HApBpMm3).\n\tassert(Hincl : incl (Ap :: Bp :: M :: nil) (list_inter (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: M :: P :: nil) (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: M :: C :: Ap :: Bp :: M :: P :: nil) ((Oo :: Ap :: Bp :: M :: nil) ++ (C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpMPmtmp;try rewrite HT2 in HOoCApBpMPmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: M :: nil) (C :: Ap :: Bp :: M :: P :: nil) (Ap :: Bp :: M :: nil) 4 3 3 HOoCApBpMPmtmp HApBpMmtmp HOoApBpMMtmp Hincl); apply HT.\n}\n\nassert(HCApBpMPM : rk(C :: Ap :: Bp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApBpMPm : rk(C :: Ap :: Bp :: M :: P ::  nil) >= 1) by (solve_hyps_min HCApBpMPeq HCApBpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApBpYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: Bp :: Y :: Z :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApBpYZMN requis par la preuve de (?)CApBpYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoCApBpYZMN requis par la preuve de (?)CApBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApBpYZMN requis par la preuve de (?)OoCApBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApBpYZMN requis par la preuve de (?)OoACApBpYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApBpYZMN requis par la preuve de (?)OoACApBpYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNm2 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApBpYZMNm3 : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoCApBpYZMN requis par la preuve de (?)OoCApBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoCApBpYZMN requis par la preuve de (?)OoCApBpYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoCApBpYZMNm2 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoCmtmp : rk(Oo :: C :: nil) >= 2) by (solve_hyps_min HOoCeq HOoCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: C :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) 2 2 HOoCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Oo :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HOoCApBpYZMNm3 : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpYZMNmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoACApBpYZMNeq HOoACApBpYZMNm3).\n\tassert(HOoCApeq : rk(Oo :: C :: Ap :: nil) = 3) by (apply LOoCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoCApmtmp : rk(Oo :: C :: Ap :: nil) >= 3) by (solve_hyps_min HOoCApeq HOoCApm3).\n\tassert(Hincl : incl (Oo :: C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpYZMNmtmp;try rewrite HT2 in HOoACApBpYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (Oo :: C :: Ap :: nil) 3 3 3 HOoACApBpYZMNmtmp HOoCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApBpYZMN requis par la preuve de (?)CApBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApBpYZMN requis par la preuve de (?)CApBpYZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApBpYZMNm2 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApBpYZMNmtmp : rk(Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoACApBpYZMNeq HOoACApBpYZMNm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApBpYZMNmtmp;try rewrite HT2 in HOoACApBpYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (C :: Ap :: nil) 3 2 3 HOoACApBpYZMNmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Ap :: Bp ::  de rang :  2 et 2 \t A : Oo :: Ap :: Bp ::   de rang : 2 et 2 *)\nassert(HCApBpYZMNm3 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoApBpeq : rk(Oo :: Ap :: Bp :: nil) = 2) by (apply LOoApBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoApBpMtmp : rk(Oo :: Ap :: Bp :: nil) <= 2) by (solve_hyps_max HOoApBpeq HOoApBpM2).\n\tassert(HOoCApBpYZMNmtmp : rk(Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoCApBpYZMNeq HOoCApBpYZMNm3).\n\tassert(HApBpmtmp : rk(Ap :: Bp :: nil) >= 2) by (solve_hyps_min HApBpeq HApBpm2).\n\tassert(Hincl : incl (Ap :: Bp :: nil) (list_inter (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (Oo :: Ap :: Bp :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: Bp :: C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) ((Oo :: Ap :: Bp :: nil) ++ (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoCApBpYZMNmtmp;try rewrite HT2 in HOoCApBpYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: Bp :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (Ap :: Bp :: nil) 3 2 2 HOoCApBpYZMNmtmp HApBpmtmp HOoApBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HCApBpYZMNm4 : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HCApBpMPeq : rk(C :: Ap :: Bp :: M :: P :: nil) = 4) by (apply LCApBpMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApBpMPMtmp : rk(C :: Ap :: Bp :: M :: P :: nil) <= 4) by (solve_hyps_max HCApBpMPeq HCApBpMPM4).\n\tassert(HCApBpYZMNPeq : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) = 4) by (apply LCApBpYZMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApBpYZMNPmtmp : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HCApBpYZMNPeq HCApBpYZMNPm4).\n\tassert(HCApBpMeq : rk(C :: Ap :: Bp :: M :: nil) = 4) by (apply LCApBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApBpMmtmp : rk(C :: Ap :: Bp :: M :: nil) >= 4) by (solve_hyps_min HCApBpMeq HCApBpMm4).\n\tassert(Hincl : incl (C :: Ap :: Bp :: M :: nil) (list_inter (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (C :: Ap :: Bp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: Bp :: Y :: Z :: M :: N :: P :: nil) (C :: Ap :: Bp :: Y :: Z :: M :: N :: C :: Ap :: Bp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Bp :: Y :: Z :: M :: N :: C :: Ap :: Bp :: M :: P :: nil) ((C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) ++ (C :: Ap :: Bp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApBpYZMNPmtmp;try rewrite HT2 in HCApBpYZMNPmtmp.\n\tassert(HT := rule_2 (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (C :: Ap :: Bp :: M :: P :: nil) (C :: Ap :: Bp :: M :: nil) 4 4 4 HCApBpYZMNPmtmp HCApBpMmtmp HCApBpMPMtmp Hincl);apply HT.\n}\n\nassert(HCApBpYZMNM : rk(C :: Ap :: Bp :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApBpYZMNm : rk(C :: Ap :: Bp :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HCApBpYZMNeq HCApBpYZMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCBpYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Bp :: Y :: Z :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CBpYZMN requis par la preuve de (?)CBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)CBpYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACBpYZMNPm2 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HACBpYZMNPm3 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HACBpeq : rk(A :: C :: Bp :: nil) = 3) by (apply LACBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpmtmp : rk(A :: C :: Bp :: nil) >= 3) by (solve_hyps_min HACBpeq HACBpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: Bp :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: Bp :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 3 3 HACBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HACBpYZMNPm4 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HACBpMeq : rk(A :: C :: Bp :: M :: nil) = 4) by (apply LACBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpMmtmp : rk(A :: C :: Bp :: M :: nil) >= 4) by (solve_hyps_min HACBpMeq HACBpMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: Bp :: M :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: Bp :: M :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 4 4 HACBpMmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CBpYZMN requis par la preuve de (?)CBpYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACBpYZMN requis par la preuve de (?)CBpYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACBpYZMN requis par la preuve de (?)OoACBpYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACBpYZMN requis par la preuve de (?)OoACBpYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACBpYZMNm2 : rk(Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoACBpYZMNm3 : rk(Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CBpYZMN requis par la preuve de (?)CBpYZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Bp :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : C :: Bp ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Bp ::   de rang : 3 et 3 *)\nassert(HCBpYZMNm2 : rk(C :: Bp :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoACBpeq : rk(Oo :: A :: C :: Bp :: nil) = 3) by (apply LOoACBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACBpMtmp : rk(Oo :: A :: C :: Bp :: nil) <= 3) by (solve_hyps_max HOoACBpeq HOoACBpM3).\n\tassert(HOoACBpYZMNmtmp : rk(Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoACBpYZMNeq HOoACBpYZMNm3).\n\tassert(HCBpeq : rk(C :: Bp :: nil) = 2) by (apply LCBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCBpmtmp : rk(C :: Bp :: nil) >= 2) by (solve_hyps_min HCBpeq HCBpm2).\n\tassert(Hincl : incl (C :: Bp :: nil) (list_inter (Oo :: A :: C :: Bp :: nil) (C :: Bp :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Bp :: Y :: Z :: M :: N :: nil) (Oo :: A :: C :: Bp :: C :: Bp :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Bp :: C :: Bp :: Y :: Z :: M :: N :: nil) ((Oo :: A :: C :: Bp :: nil) ++ (C :: Bp :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACBpYZMNmtmp;try rewrite HT2 in HOoACBpYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Bp :: nil) (C :: Bp :: Y :: Z :: M :: N :: nil) (C :: Bp :: nil) 3 2 3 HOoACBpYZMNmtmp HCBpmtmp HOoACBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 -2 et -4*)\nassert(HCBpYZMNm3 : rk(C :: Bp :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HACBpYZMNPmtmp : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HACBpYZMNPeq HACBpYZMNPm4).\n\tassert(HMmtmp : rk(M :: nil) >= 1) by (solve_hyps_min HMeq HMm1).\n\tassert(Hincl : incl (M :: nil) (list_inter (C :: Bp :: Y :: Z :: M :: N :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) (C :: Bp :: Y :: Z :: M :: N :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Bp :: Y :: Z :: M :: N :: A :: M :: P :: nil) ((C :: Bp :: Y :: Z :: M :: N :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HACBpYZMNPmtmp;try rewrite HT2 in HACBpYZMNPmtmp.\n\tassert(HT := rule_2 (C :: Bp :: Y :: Z :: M :: N :: nil) (A :: M :: P :: nil) (M :: nil) 4 1 2 HACBpYZMNPmtmp HMmtmp HAMPMtmp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et -4*)\n(* ensembles concern\u00e9s AUB : C :: Ap :: Bp :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : C :: Y ::  de rang :  2 et 2 \t A : C :: Ap :: Y ::   de rang : 2 et 2 *)\nassert(HCBpYZMNm4 : rk(C :: Bp :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(HCApBpYZMNeq : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) = 4) by (apply LCApBpYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApBpYZMNmtmp : rk(C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HCApBpYZMNeq HCApBpYZMNm4).\n\tassert(HCYeq : rk(C :: Y :: nil) = 2) by (apply LCY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCYmtmp : rk(C :: Y :: nil) >= 2) by (solve_hyps_min HCYeq HCYm2).\n\tassert(Hincl : incl (C :: Y :: nil) (list_inter (C :: Ap :: Y :: nil) (C :: Bp :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: Bp :: Y :: Z :: M :: N :: nil) (C :: Ap :: Y :: C :: Bp :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Y :: C :: Bp :: Y :: Z :: M :: N :: nil) ((C :: Ap :: Y :: nil) ++ (C :: Bp :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApBpYZMNmtmp;try rewrite HT2 in HCApBpYZMNmtmp.\n\tassert(HT := rule_4 (C :: Ap :: Y :: nil) (C :: Bp :: Y :: Z :: M :: N :: nil) (C :: Y :: nil) 4 2 2 HCApBpYZMNmtmp HCYmtmp HCApYMtmp Hincl); apply HT.\n}\n\nassert(HCBpYZMNM : rk(C :: Bp :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCBpYZMNm : rk(C :: Bp :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HCBpYZMNeq HCBpYZMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LXYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(X :: Y :: Z :: M :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour XYZMN requis par la preuve de (?)XYZMN pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)XYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 4 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)OoABCApXYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)OoABCApXYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNPm2 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNPm3 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCApXYZMNPm2 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HABCApXYZMNPm3 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApXYZMNPmtmp : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABCApXYZMNPeq HOoABCApXYZMNPm3).\n\tassert(HABApeq : rk(A :: B :: Ap :: nil) = 3) by (apply LABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApmtmp : rk(A :: B :: Ap :: nil) >= 3) by (solve_hyps_min HABApeq HABApm3).\n\tassert(Hincl : incl (A :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: B :: Ap :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApXYZMNPmtmp;try rewrite HT2 in HOoABCApXYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (A :: B :: Ap :: nil) 3 3 3 HOoABCApXYZMNPmtmp HABApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HABCApXYZMNPm4 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HABApMeq : rk(A :: B :: Ap :: M :: nil) = 4) by (apply LABApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApMmtmp : rk(A :: B :: Ap :: M :: nil) >= 4) by (solve_hyps_min HABApMeq HABApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: Ap :: M :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: Ap :: M :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 4 4 HABApMmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour ABCMP requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 3 pour OoABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMPm2 : rk(Oo :: A :: B :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABMPM3 : rk(Oo :: A :: B :: M :: P :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: B :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: M :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HOoABMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCMPm2 : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 5 et -4*)\nassert(HOoABCMPM3 : rk(Oo :: A :: B :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABMPMtmp : rk(Oo :: A :: B :: M :: P :: nil) <= 3) by (solve_hyps_max HOoABMPeq HOoABMPM3).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: M :: P :: nil) (Oo :: A :: C :: Oo :: A :: B :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: M :: P :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: nil) 2 3 2 HOoACMtmp HOoABMPMtmp HOoAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABCMPm3 : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: B :: C :: M :: P :: nil) 3 3 HOoAMmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCMPm2 : rk(A :: B :: C :: M :: P :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: C :: M :: P :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HABCMPM3 : rk(A :: B :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HABCeq : rk(A :: B :: C :: nil) = 2) by (apply LABC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCMtmp : rk(A :: B :: C :: nil) <= 2) by (solve_hyps_max HABCeq HABCM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (A :: B :: C :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: P :: nil) (A :: B :: C :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: A :: M :: P :: nil) ((A :: B :: C :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HABCMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: M :: P ::  de rang :  3 et 3 \t AiB : A :: B :: M ::  de rang :  3 et 3 \t A : Oo :: A :: B :: M ::   de rang : 3 et 3 *)\nassert(HABCMPm3 : rk(A :: B :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HOoABMeq : rk(Oo :: A :: B :: M :: nil) = 3) by (apply LOoABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMMtmp : rk(Oo :: A :: B :: M :: nil) <= 3) by (solve_hyps_max HOoABMeq HOoABMM3).\n\tassert(HOoABCMPmtmp : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 3) by (solve_hyps_min HOoABCMPeq HOoABCMPm3).\n\tassert(HABMeq : rk(A :: B :: M :: nil) = 3) by (apply LABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABMmtmp : rk(A :: B :: M :: nil) >= 3) by (solve_hyps_min HABMeq HABMm3).\n\tassert(Hincl : incl (A :: B :: M :: nil) (list_inter (Oo :: A :: B :: M :: nil) (A :: B :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: M :: P :: nil) (Oo :: A :: B :: M :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: A :: B :: C :: M :: P :: nil) ((Oo :: A :: B :: M :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCMPmtmp;try rewrite HT2 in HOoABCMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: M :: nil) (A :: B :: C :: M :: P :: nil) (A :: B :: M :: nil) 3 3 3 HOoABCMPmtmp HABMmtmp HOoABMMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm2 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm3 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCApXYZMNm2 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Oo :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HOoBCApXYZMNm3 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApXYZMNmtmp : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoABCApXYZMNeq HOoABCApXYZMNm3).\n\tassert(HOoBApeq : rk(Oo :: B :: Ap :: nil) = 3) by (apply LOoBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApmtmp : rk(Oo :: B :: Ap :: nil) >= 3) by (solve_hyps_min HOoBApeq HOoBApm3).\n\tassert(Hincl : incl (Oo :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApXYZMNmtmp;try rewrite HT2 in HOoABCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: Ap :: nil) 3 3 3 HOoABCApXYZMNmtmp HOoBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HBCApXYZMNm2 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HBCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : B :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: B :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HBCApXYZMNm3 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoBCApeq : rk(Oo :: B :: C :: Ap :: nil) = 3) by (apply LOoBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMtmp : rk(Oo :: B :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoBCApeq HOoBCApM3).\n\tassert(HOoBCApXYZMNmtmp : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoBCApXYZMNeq HOoBCApXYZMNm3).\n\tassert(HBCApeq : rk(B :: C :: Ap :: nil) = 3) by (apply LBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApmtmp : rk(B :: C :: Ap :: nil) >= 3) by (solve_hyps_min HBCApeq HBCApm3).\n\tassert(Hincl : incl (B :: C :: Ap :: nil) (list_inter (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: B :: C :: Ap :: nil) ++ (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApXYZMNmtmp;try rewrite HT2 in HOoBCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: C :: Ap :: nil) 3 3 3 HOoBCApXYZMNmtmp HBCApmtmp HOoBCApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 5 4 et 5*)\nassert(HBCApXYZMNm4 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HABCMPMtmp : rk(A :: B :: C :: M :: P :: nil) <= 3) by (solve_hyps_max HABCMPeq HABCMPM3).\n\tassert(HABCApXYZMNPmtmp : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HABCApXYZMNPeq HABCApXYZMNPm4).\n\tassert(HBCMeq : rk(B :: C :: M :: nil) = 3) by (apply LBCM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCMmtmp : rk(B :: C :: M :: nil) >= 3) by (solve_hyps_min HBCMeq HBCMm3).\n\tassert(Hincl : incl (B :: C :: M :: nil) (list_inter (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (A :: B :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: A :: B :: C :: M :: P :: nil) ((B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCApXYZMNPmtmp;try rewrite HT2 in HABCApXYZMNPmtmp.\n\tassert(HT := rule_2 (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (A :: B :: C :: M :: P :: nil) (B :: C :: M :: nil) 4 3 3 HABCApXYZMNPmtmp HBCMmtmp HABCMPMtmp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)OoACApXYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)OoACApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApXYZMNm2 : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApXYZMNm3 : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApXYZMNm2 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApXYZMNmtmp : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoACApXYZMNeq HOoACApXYZMNm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApXYZMNmtmp;try rewrite HT2 in HOoACApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (C :: Ap :: nil) 3 2 3 HOoACApXYZMNmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et -4*)\n(* ensembles concern\u00e9s AUB : B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Ap :: X ::  de rang :  2 et 2 \t A : B :: Ap :: X ::   de rang : 2 et 2 *)\nassert(HCApXYZMNm3 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HBCApXYZMNmtmp : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HBCApXYZMNeq HBCApXYZMNm3).\n\tassert(HApXeq : rk(Ap :: X :: nil) = 2) by (apply LApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApXmtmp : rk(Ap :: X :: nil) >= 2) by (solve_hyps_min HApXeq HApXm2).\n\tassert(Hincl : incl (Ap :: X :: nil) (list_inter (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((B :: Ap :: X :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApXYZMNmtmp;try rewrite HT2 in HBCApXYZMNmtmp.\n\tassert(HT := rule_4 (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Ap :: X :: nil) 3 2 2 HBCApXYZMNmtmp HApXmtmp HBApXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et -4*)\n(* ensembles concern\u00e9s AUB : B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : Ap :: X ::  de rang :  2 et 2 \t A : B :: Ap :: X ::   de rang : 2 et 2 *)\nassert(HCApXYZMNm4 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HBCApXYZMNmtmp : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HBCApXYZMNeq HBCApXYZMNm4).\n\tassert(HApXeq : rk(Ap :: X :: nil) = 2) by (apply LApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApXmtmp : rk(Ap :: X :: nil) >= 2) by (solve_hyps_min HApXeq HApXm2).\n\tassert(Hincl : incl (Ap :: X :: nil) (list_inter (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((B :: Ap :: X :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApXYZMNmtmp;try rewrite HT2 in HBCApXYZMNmtmp.\n\tassert(HT := rule_4 (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Ap :: X :: nil) 4 2 2 HBCApXYZMNmtmp HApXmtmp HBApXMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour XYZMN requis par la preuve de (?)XYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour XYZMN requis par la preuve de (?)XYZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -2 et -4*)\n(* ensembles concern\u00e9s AUB : C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Y ::  de rang :  1 et 1 \t A : C :: Ap :: Y ::   de rang : 2 et 2 *)\nassert(HXYZMNm2 : rk(X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(HCApXYZMNmtmp : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HCApXYZMNeq HCApXYZMNm3).\n\tassert(HYmtmp : rk(Y :: nil) >= 1) by (solve_hyps_min HYeq HYm1).\n\tassert(Hincl : incl (Y :: nil) (list_inter (C :: Ap :: Y :: nil) (X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (C :: Ap :: Y :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Y :: X :: Y :: Z :: M :: N :: nil) ((C :: Ap :: Y :: nil) ++ (X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApXYZMNmtmp;try rewrite HT2 in HCApXYZMNmtmp.\n\tassert(HT := rule_4 (C :: Ap :: Y :: nil) (X :: Y :: Z :: M :: N :: nil) (Y :: nil) 3 1 2 HCApXYZMNmtmp HYmtmp HCApYMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 -2 et -4*)\n(* ensembles concern\u00e9s AUB : C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : Y ::  de rang :  1 et 1 \t A : C :: Ap :: Y ::   de rang : 2 et 2 *)\nassert(HXYZMNm3 : rk(X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HCApYMtmp : rk(C :: Ap :: Y :: nil) <= 2) by (solve_hyps_max HCApYeq HCApYM2).\n\tassert(HCApXYZMNmtmp : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HCApXYZMNeq HCApXYZMNm4).\n\tassert(HYmtmp : rk(Y :: nil) >= 1) by (solve_hyps_min HYeq HYm1).\n\tassert(Hincl : incl (Y :: nil) (list_inter (C :: Ap :: Y :: nil) (X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (C :: Ap :: Y :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Ap :: Y :: X :: Y :: Z :: M :: N :: nil) ((C :: Ap :: Y :: nil) ++ (X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCApXYZMNmtmp;try rewrite HT2 in HCApXYZMNmtmp.\n\tassert(HT := rule_4 (C :: Ap :: Y :: nil) (X :: Y :: Z :: M :: N :: nil) (Y :: nil) 4 1 2 HCApXYZMNmtmp HYmtmp HCApYMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -4 4 et -2*)\nassert(HXYZMNM3 : rk(X :: Y :: Z :: M :: N :: nil) <= 3).\n{\n\tassert(HXYZMtmp : rk(X :: Y :: Z :: nil) <= 2) by (solve_hyps_max HXYZeq HXYZM2).\n\tassert(HXMNeq : rk(X :: M :: N :: nil) = 2) by (apply LXMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HXMNMtmp : rk(X :: M :: N :: nil) <= 2) by (solve_hyps_max HXMNeq HXMNM2).\n\tassert(HXmtmp : rk(X :: nil) >= 1) by (solve_hyps_min HXeq HXm1).\n\tassert(Hincl : incl (X :: nil) (list_inter (X :: Y :: Z :: nil) (X :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (X :: Y :: Z :: M :: N :: nil) (X :: Y :: Z :: X :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (X :: Y :: Z :: X :: M :: N :: nil) ((X :: Y :: Z :: nil) ++ (X :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (X :: Y :: Z :: nil) (X :: M :: N :: nil) (X :: nil) 2 2 1 HXYZMtmp HXMNMtmp HXmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HXYZMNM : rk(X :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HXYZMNm : rk(X :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HXYZMNeq HXYZMNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LCApXYZMN *)\n(* dans constructLemma(), requis par LBCApXYZMN *)\n(* dans la couche 0 *)\nLemma LABCApXYZMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)OoABCApXYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCApXYZMNP requis par la preuve de (?)OoABCApXYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNPm2 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNPm3 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCApXYZMNP requis par la preuve de (?)ABCApXYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCApXYZMNPm2 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HABCApXYZMNPm3 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApXYZMNPmtmp : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABCApXYZMNPeq HOoABCApXYZMNPm3).\n\tassert(HABApeq : rk(A :: B :: Ap :: nil) = 3) by (apply LABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApmtmp : rk(A :: B :: Ap :: nil) >= 3) by (solve_hyps_min HABApeq HABApm3).\n\tassert(Hincl : incl (A :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (Oo :: A :: B :: Ap :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApXYZMNPmtmp;try rewrite HT2 in HOoABCApXYZMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (A :: B :: Ap :: nil) 3 3 3 HOoABCApXYZMNPmtmp HABApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HABCApXYZMNPm4 : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HABApMeq : rk(A :: B :: Ap :: M :: nil) = 4) by (apply LABApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABApMmtmp : rk(A :: B :: Ap :: M :: nil) >= 4) by (solve_hyps_min HABApMeq HABApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: Ap :: M :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: Ap :: M :: nil) (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) 4 4 HABApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HABCApXYZMNPM : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCApXYZMNPm : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HABCApXYZMNPeq HABCApXYZMNPm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LBCApXYZMN *)\n(* dans constructLemma(), requis par LABCMP *)\n(* dans la couche 0 *)\nLemma LOoABCMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: C :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour OoABMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMP requis par la preuve de (?)OoABMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMPm2 : rk(Oo :: A :: B :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HOoABMPM3 : rk(Oo :: A :: B :: M :: P :: nil) <= 3).\n{\n\tassert(HOoABeq : rk(Oo :: A :: B :: nil) = 2) by (apply LOoAB with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMtmp : rk(Oo :: A :: B :: nil) <= 2) by (solve_hyps_max HOoABeq HOoABM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (Oo :: A :: B :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: B :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: A :: M :: P :: nil) ((Oo :: A :: B :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: B :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HOoABMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCMP requis par la preuve de (?)OoABCMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCMPm2 : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: M :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 5 et -4*)\nassert(HOoABCMPM3 : rk(Oo :: A :: B :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABMPMtmp : rk(Oo :: A :: B :: M :: P :: nil) <= 3) by (solve_hyps_max HOoABMPeq HOoABMPM3).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: M :: P :: nil) (Oo :: A :: C :: Oo :: A :: B :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: M :: P :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Oo :: A :: C :: nil) (Oo :: A :: B :: M :: P :: nil) (Oo :: A :: nil) 2 3 2 HOoACMtmp HOoABMPMtmp HOoAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABCMPm3 : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: B :: C :: M :: P :: nil) 3 3 HOoAMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABCMPM : rk(Oo :: A :: B :: C :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABCMPm : rk(Oo :: A :: B :: C :: M :: P ::  nil) >= 1) by (solve_hyps_min HOoABCMPeq HOoABCMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABCMP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: B :: C :: M :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HABCMPm2 : rk(A :: B :: C :: M :: P :: nil) >= 2).\n{\n\tassert(HABmtmp : rk(A :: B :: nil) >= 2) by (solve_hyps_min HABeq HABm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: nil) (A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: nil) (A :: B :: C :: M :: P :: nil) 2 2 HABmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 -4 et -2*)\nassert(HABCMPM3 : rk(A :: B :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HABCeq : rk(A :: B :: C :: nil) = 2) by (apply LABC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCMtmp : rk(A :: B :: C :: nil) <= 2) by (solve_hyps_max HABCeq HABCM2).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HAmtmp : rk(A :: nil) >= 1) by (solve_hyps_min HAeq HAm1).\n\tassert(Hincl : incl (A :: nil) (list_inter (A :: B :: C :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: P :: nil) (A :: B :: C :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: A :: M :: P :: nil) ((A :: B :: C :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: nil) (A :: M :: P :: nil) (A :: nil) 2 2 1 HABCMtmp HAMPMtmp HAmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: M :: P ::  de rang :  3 et 3 \t AiB : A :: B :: M ::  de rang :  3 et 3 \t A : Oo :: A :: B :: M ::   de rang : 3 et 3 *)\nassert(HABCMPm3 : rk(A :: B :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HOoABMeq : rk(Oo :: A :: B :: M :: nil) = 3) by (apply LOoABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMMtmp : rk(Oo :: A :: B :: M :: nil) <= 3) by (solve_hyps_max HOoABMeq HOoABMM3).\n\tassert(HOoABCMPeq : rk(Oo :: A :: B :: C :: M :: P :: nil) = 3) by (apply LOoABCMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABCMPmtmp : rk(Oo :: A :: B :: C :: M :: P :: nil) >= 3) by (solve_hyps_min HOoABCMPeq HOoABCMPm3).\n\tassert(HABMeq : rk(A :: B :: M :: nil) = 3) by (apply LABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABMmtmp : rk(A :: B :: M :: nil) >= 3) by (solve_hyps_min HABMeq HABMm3).\n\tassert(Hincl : incl (A :: B :: M :: nil) (list_inter (Oo :: A :: B :: M :: nil) (A :: B :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: M :: P :: nil) (Oo :: A :: B :: M :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: A :: B :: C :: M :: P :: nil) ((Oo :: A :: B :: M :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCMPmtmp;try rewrite HT2 in HOoABCMPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: M :: nil) (A :: B :: C :: M :: P :: nil) (A :: B :: M :: nil) 3 3 3 HOoABCMPmtmp HABMmtmp HOoABMMtmp Hincl); apply HT.\n}\n\nassert(HABCMPM : rk(A :: B :: C :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCMPm : rk(A :: B :: C :: M :: P ::  nil) >= 1) by (solve_hyps_min HABCMPeq HABCMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBCApXYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: C :: Ap :: X :: Y :: Z :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm2 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm3 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCApXYZMNm2 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Oo :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HOoBCApXYZMNm3 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApXYZMNmtmp : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoABCApXYZMNeq HOoABCApXYZMNm3).\n\tassert(HOoBApeq : rk(Oo :: B :: Ap :: nil) = 3) by (apply LOoBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApmtmp : rk(Oo :: B :: Ap :: nil) >= 3) by (solve_hyps_min HOoBApeq HOoBApm3).\n\tassert(Hincl : incl (Oo :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApXYZMNmtmp;try rewrite HT2 in HOoABCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: Ap :: nil) 3 3 3 HOoABCApXYZMNmtmp HOoBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HBCApXYZMNm2 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HBCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : B :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: B :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HBCApXYZMNm3 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoBCApeq : rk(Oo :: B :: C :: Ap :: nil) = 3) by (apply LOoBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMtmp : rk(Oo :: B :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoBCApeq HOoBCApM3).\n\tassert(HOoBCApXYZMNmtmp : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoBCApXYZMNeq HOoBCApXYZMNm3).\n\tassert(HBCApeq : rk(B :: C :: Ap :: nil) = 3) by (apply LBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApmtmp : rk(B :: C :: Ap :: nil) >= 3) by (solve_hyps_min HBCApeq HBCApm3).\n\tassert(Hincl : incl (B :: C :: Ap :: nil) (list_inter (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: B :: C :: Ap :: nil) ++ (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApXYZMNmtmp;try rewrite HT2 in HOoBCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: C :: Ap :: nil) 3 3 3 HOoBCApXYZMNmtmp HBCApmtmp HOoBCApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et 4*)\nassert(HBCApXYZMNm4 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HABCMPeq : rk(A :: B :: C :: M :: P :: nil) = 3) by (apply LABCMP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCMPMtmp : rk(A :: B :: C :: M :: P :: nil) <= 3) by (solve_hyps_max HABCMPeq HABCMPM3).\n\tassert(HABCApXYZMNPeq : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) = 4) by (apply LABCApXYZMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABCApXYZMNPmtmp : rk(A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HABCApXYZMNPeq HABCApXYZMNPm4).\n\tassert(HBCMeq : rk(B :: C :: M :: nil) = 3) by (apply LBCM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCMmtmp : rk(B :: C :: M :: nil) >= 3) by (solve_hyps_min HBCMeq HBCMm3).\n\tassert(Hincl : incl (B :: C :: M :: nil) (list_inter (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (A :: B :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: P :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: A :: B :: C :: M :: P :: nil) ((B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCApXYZMNPmtmp;try rewrite HT2 in HABCApXYZMNPmtmp.\n\tassert(HT := rule_2 (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (A :: B :: C :: M :: P :: nil) (B :: C :: M :: nil) 4 3 3 HABCApXYZMNPmtmp HBCMmtmp HABCMPMtmp Hincl);apply HT.\n}\n\nassert(HBCApXYZMNM : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBCApXYZMNm : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HBCApXYZMNeq HBCApXYZMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LCApXYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(C :: Ap :: X :: Y :: Z :: M :: N ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABCApXYZMN requis par la preuve de (?)OoABCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm2 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABCApXYZMNm3 : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoBCApXYZMN requis par la preuve de (?)OoBCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoBCApXYZMNm2 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoBmtmp : rk(Oo :: B :: nil) >= 2) by (solve_hyps_min HOoBeq HOoBm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: B :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoBmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Oo :: B :: Ap ::  de rang :  3 et 3 \t A : Oo :: A :: B :: Ap ::   de rang : 3 et 3 *)\nassert(HOoBCApXYZMNm3 : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoABApeq : rk(Oo :: A :: B :: Ap :: nil) = 3) by (apply LOoABAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMtmp : rk(Oo :: A :: B :: Ap :: nil) <= 3) by (solve_hyps_max HOoABApeq HOoABApM3).\n\tassert(HOoABCApXYZMNmtmp : rk(Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoABCApXYZMNeq HOoABCApXYZMNm3).\n\tassert(HOoBApeq : rk(Oo :: B :: Ap :: nil) = 3) by (apply LOoBAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApmtmp : rk(Oo :: B :: Ap :: nil) >= 3) by (solve_hyps_min HOoBApeq HOoBApm3).\n\tassert(Hincl : incl (Oo :: B :: Ap :: nil) (list_inter (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Ap :: Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: A :: B :: Ap :: nil) ++ (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApXYZMNmtmp;try rewrite HT2 in HOoABCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Ap :: nil) (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: Ap :: nil) 3 3 3 HOoABCApXYZMNmtmp HOoBApmtmp HOoABApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BCApXYZMN requis par la preuve de (?)BCApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HBCApXYZMNm2 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HBCmtmp : rk(B :: C :: nil) >= 2) by (solve_hyps_min HBCeq HBCm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (B :: C :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HBCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : B :: C :: Ap ::  de rang :  3 et 3 \t A : Oo :: B :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HBCApXYZMNm3 : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoBCApeq : rk(Oo :: B :: C :: Ap :: nil) = 3) by (apply LOoBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBCApMtmp : rk(Oo :: B :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoBCApeq HOoBCApM3).\n\tassert(HOoBCApXYZMNmtmp : rk(Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoBCApXYZMNeq HOoBCApXYZMNm3).\n\tassert(HBCApeq : rk(B :: C :: Ap :: nil) = 3) by (apply LBCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApmtmp : rk(B :: C :: Ap :: nil) >= 3) by (solve_hyps_min HBCApeq HBCApm3).\n\tassert(Hincl : incl (B :: C :: Ap :: nil) (list_inter (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: B :: C :: Ap :: B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: B :: C :: Ap :: nil) ++ (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBCApXYZMNmtmp;try rewrite HT2 in HOoBCApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: B :: C :: Ap :: nil) (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: C :: Ap :: nil) 3 3 3 HOoBCApXYZMNmtmp HBCApmtmp HOoBCApMtmp Hincl); apply HT.\n}\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)OoACApXYZMN pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoACApXYZMN requis par la preuve de (?)OoACApXYZMN pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApXYZMNm2 : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoACApXYZMNm3 : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour CApXYZMN requis par la preuve de (?)CApXYZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : C :: Ap ::  de rang :  2 et 2 \t A : Oo :: A :: C :: Ap ::   de rang : 3 et 3 *)\nassert(HCApXYZMNm2 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoACApeq : rk(Oo :: A :: C :: Ap :: nil) = 3) by (apply LOoACAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACApMtmp : rk(Oo :: A :: C :: Ap :: nil) <= 3) by (solve_hyps_max HOoACApeq HOoACApM3).\n\tassert(HOoACApXYZMNmtmp : rk(Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HOoACApXYZMNeq HOoACApXYZMNm3).\n\tassert(HCApeq : rk(C :: Ap :: nil) = 2) by (apply LCAp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCApmtmp : rk(C :: Ap :: nil) >= 2) by (solve_hyps_min HCApeq HCApm2).\n\tassert(Hincl : incl (C :: Ap :: nil) (list_inter (Oo :: A :: C :: Ap :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Oo :: A :: C :: Ap :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Ap :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((Oo :: A :: C :: Ap :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoACApXYZMNmtmp;try rewrite HT2 in HOoACApXYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: Ap :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (C :: Ap :: nil) 3 2 3 HOoACApXYZMNmtmp HCApmtmp HOoACApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et -4*)\n(* ensembles concern\u00e9s AUB : B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  3 et 4 \t AiB : Ap :: X ::  de rang :  2 et 2 \t A : B :: Ap :: X ::   de rang : 2 et 2 *)\nassert(HCApXYZMNm3 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HBCApXYZMNmtmp : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 3) by (solve_hyps_min HBCApXYZMNeq HBCApXYZMNm3).\n\tassert(HApXeq : rk(Ap :: X :: nil) = 2) by (apply LApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApXmtmp : rk(Ap :: X :: nil) >= 2) by (solve_hyps_min HApXeq HApXm2).\n\tassert(Hincl : incl (Ap :: X :: nil) (list_inter (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((B :: Ap :: X :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApXYZMNmtmp;try rewrite HT2 in HBCApXYZMNmtmp.\n\tassert(HT := rule_4 (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Ap :: X :: nil) 3 2 2 HBCApXYZMNmtmp HApXmtmp HBApXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 4 et -4*)\n(* ensembles concern\u00e9s AUB : B :: C :: Ap :: X :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : Ap :: X ::  de rang :  2 et 2 \t A : B :: Ap :: X ::   de rang : 2 et 2 *)\nassert(HCApXYZMNm4 : rk(C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4).\n{\n\tassert(HBApXMtmp : rk(B :: Ap :: X :: nil) <= 2) by (solve_hyps_max HBApXeq HBApXM2).\n\tassert(HBCApXYZMNeq : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) = 4) by (apply LBCApXYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBCApXYZMNmtmp : rk(B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HBCApXYZMNeq HBCApXYZMNm4).\n\tassert(HApXeq : rk(Ap :: X :: nil) = 2) by (apply LApX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HApXmtmp : rk(Ap :: X :: nil) >= 2) by (solve_hyps_min HApXeq HApXm2).\n\tassert(Hincl : incl (Ap :: X :: nil) (list_inter (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: Ap :: X :: C :: Ap :: X :: Y :: Z :: M :: N :: nil) ((B :: Ap :: X :: nil) ++ (C :: Ap :: X :: Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBCApXYZMNmtmp;try rewrite HT2 in HBCApXYZMNmtmp.\n\tassert(HT := rule_4 (B :: Ap :: X :: nil) (C :: Ap :: X :: Y :: Z :: M :: N :: nil) (Ap :: X :: nil) 4 2 2 HBCApXYZMNmtmp HApXmtmp HBApXMtmp Hincl); apply HT.\n}\n\nassert(HCApXYZMNM : rk(C :: Ap :: X :: Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HCApXYZMNm : rk(C :: Ap :: X :: Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HCApXYZMNeq HCApXYZMNm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LNP *)\n(* dans la couche 0 *)\nLemma LBNPQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: N :: P :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour BNPQ requis par la preuve de (?)BNPQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : B ::  de rang :  1 et 1 \t A : A :: B :: M ::   de rang : 3 et 3 *)\nassert(HBNPQm2 : rk(B :: N :: P :: Q :: nil) >= 2).\n{\n\tassert(HABMeq : rk(A :: B :: M :: nil) = 3) by (apply LABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABMMtmp : rk(A :: B :: M :: nil) <= 3) by (solve_hyps_max HABMeq HABMM3).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HBmtmp : rk(B :: nil) >= 1) by (solve_hyps_min HBeq HBm1).\n\tassert(Hincl : incl (B :: nil) (list_inter (A :: B :: M :: nil) (B :: N :: P :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: B :: M :: B :: N :: P :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: M :: B :: N :: P :: Q :: nil) ((A :: B :: M :: nil) ++ (B :: N :: P :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: B :: M :: nil) (B :: N :: P :: Q :: nil) (B :: nil) 4 1 3 HABMNPQmtmp HBmtmp HABMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HBNPQM3 : rk(B :: N :: P :: Q :: nil) <= 3).\n{\n\tassert(HPMtmp : rk(P :: nil) <= 1) by (solve_hyps_max HPeq HPM1).\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (P :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: N :: P :: Q :: nil) (P :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (P :: B :: N :: Q :: nil) ((P :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (P :: nil) (B :: N :: Q :: nil) (nil) 1 2 0 HPMtmp HBNQMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : A :: B :: M :: N :: P :: Q ::  de rang :  4 et 4 \t AiB : P ::  de rang :  1 et 1 \t A : A :: M :: P ::   de rang : 2 et 2 *)\nassert(HBNPQm3 : rk(B :: N :: P :: Q :: nil) >= 3).\n{\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(HABMNPQmtmp : rk(A :: B :: M :: N :: P :: Q :: nil) >= 4) by (solve_hyps_min HABMNPQeq HABMNPQm4).\n\tassert(HPmtmp : rk(P :: nil) >= 1) by (solve_hyps_min HPeq HPm1).\n\tassert(Hincl : incl (P :: nil) (list_inter (A :: M :: P :: nil) (B :: N :: P :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: M :: N :: P :: Q :: nil) (A :: M :: P :: B :: N :: P :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: P :: B :: N :: P :: Q :: nil) ((A :: M :: P :: nil) ++ (B :: N :: P :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABMNPQmtmp;try rewrite HT2 in HABMNPQmtmp.\n\tassert(HT := rule_4 (A :: M :: P :: nil) (B :: N :: P :: Q :: nil) (P :: nil) 4 1 2 HABMNPQmtmp HPmtmp HAMPMtmp Hincl); apply HT.\n}\n\nassert(HBNPQM : rk(B :: N :: P :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HBNPQm : rk(B :: N :: P :: Q ::  nil) >= 1) by (solve_hyps_min HBNPQeq HBNPQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(N :: P ::  nil) = 2.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 2 pour NP requis par la preuve de (?)NP pour la r\u00e8gle 2  *)\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 -2 et -4*)\nassert(HNPm2 : rk(N :: P :: nil) >= 2).\n{\n\tassert(HBNQMtmp : rk(B :: N :: Q :: nil) <= 2) by (solve_hyps_max HBNQeq HBNQM2).\n\tassert(HBNPQeq : rk(B :: N :: P :: Q :: nil) = 3) by (apply LBNPQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBNPQmtmp : rk(B :: N :: P :: Q :: nil) >= 3) by (solve_hyps_min HBNPQeq HBNPQm3).\n\tassert(HNmtmp : rk(N :: nil) >= 1) by (solve_hyps_min HNeq HNm1).\n\tassert(Hincl : incl (N :: nil) (list_inter (N :: P :: nil) (B :: N :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: N :: P :: Q :: nil) (N :: P :: B :: N :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: P :: B :: N :: Q :: nil) ((N :: P :: nil) ++ (B :: N :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBNPQmtmp;try rewrite HT2 in HBNPQmtmp.\n\tassert(HT := rule_2 (N :: P :: nil) (B :: N :: Q :: nil) (N :: nil) 3 1 2 HBNPQmtmp HNmtmp HBNQMtmp Hincl);apply HT.\n}\n\nassert(HNPM : rk(N :: P ::  nil) <= 2) (* dim : 3 *) by (solve_hyps_max HNPeq HNPM2).\nassert(HNPm : rk(N :: P ::  nil) >= 1) by (solve_hyps_min HNPeq HNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LANP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ANP requis par la preuve de (?)ANP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour ANP requis par la preuve de (?)ANP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Bp ::   de rang : 2 et 2 *)\nassert(HANPm2 : rk(A :: N :: P :: nil) >= 2).\n{\n\tassert(HOoBpMtmp : rk(Oo :: Bp :: nil) <= 2) by (solve_hyps_max HOoBpeq HOoBpM2).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Bp :: nil) (A :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Oo :: Bp :: A :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Bp :: A :: N :: P :: nil) ((Oo :: Bp :: nil) ++ (A :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_4 (Oo :: Bp :: nil) (A :: N :: P :: nil) (nil) 4 0 2 HOoABpNPmtmp Hmtmp HOoBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HANPm3 : rk(A :: N :: P :: nil) >= 3).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HABpNPeq : rk(A :: Bp :: N :: P :: nil) = 3) by (apply LABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNPmtmp : rk(A :: Bp :: N :: P :: nil) >= 3) by (solve_hyps_min HABpNPeq HABpNPm3).\n\tassert(HNPeq : rk(N :: P :: nil) = 2) by (apply LNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HNPmtmp : rk(N :: P :: nil) >= 2) by (solve_hyps_min HNPeq HNPm2).\n\tassert(Hincl : incl (N :: P :: nil) (list_inter (A :: N :: P :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: N :: P :: nil) (A :: N :: P :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: N :: P :: Bp :: N :: P :: nil) ((A :: N :: P :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABpNPmtmp;try rewrite HT2 in HABpNPmtmp.\n\tassert(HT := rule_2 (A :: N :: P :: nil) (Bp :: N :: P :: nil) (N :: P :: nil) 3 2 2 HABpNPmtmp HNPmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HANPM : rk(A :: N :: P ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HANPeq HANPM3).\nassert(HANPm : rk(A :: N :: P ::  nil) >= 1) by (solve_hyps_min HANPeq HANPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoANP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoANP requis par la preuve de (?)OoANP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoANPm2 : rk(Oo :: A :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Bp :: N :: P ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Bp ::   de rang : 1 et 1 *)\nassert(HOoANPm3 : rk(Oo :: A :: N :: P :: nil) >= 3).\n{\n\tassert(HBpMtmp : rk(Bp :: nil) <= 1) by (solve_hyps_max HBpeq HBpM1).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Bp :: nil) (Oo :: A :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Bp :: Oo :: A :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Bp :: Oo :: A :: N :: P :: nil) ((Bp :: nil) ++ (Oo :: A :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_4 (Bp :: nil) (Oo :: A :: N :: P :: nil) (nil) 4 0 1 HOoABpNPmtmp Hmtmp HBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoANPm4 : rk(Oo :: A :: N :: P :: nil) >= 4).\n{\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HOoABpNPeq : rk(Oo :: A :: Bp :: N :: P :: nil) = 4) by (apply LOoABpNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpNPmtmp : rk(Oo :: A :: Bp :: N :: P :: nil) >= 4) by (solve_hyps_min HOoABpNPeq HOoABpNPm4).\n\tassert(HNPeq : rk(N :: P :: nil) = 2) by (apply LNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HNPmtmp : rk(N :: P :: nil) >= 2) by (solve_hyps_min HNPeq HNPm2).\n\tassert(Hincl : incl (N :: P :: nil) (list_inter (Oo :: A :: N :: P :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Bp :: N :: P :: nil) (Oo :: A :: N :: P :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: N :: P :: Bp :: N :: P :: nil) ((Oo :: A :: N :: P :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABpNPmtmp;try rewrite HT2 in HOoABpNPmtmp.\n\tassert(HT := rule_2 (Oo :: A :: N :: P :: nil) (Bp :: N :: P :: nil) (N :: P :: nil) 4 2 2 HOoABpNPmtmp HNPmtmp HBpNPMtmp Hincl);apply HT.\n}\n\nassert(HOoANPM : rk(Oo :: A :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoANPm : rk(Oo :: A :: N :: P ::  nil) >= 1) by (solve_hyps_min HOoANPeq HOoANPm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LAXNP *)\n(* dans la couche 0 *)\nLemma LABpXNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: Bp :: X :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)OoABBpXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABBpXNP requis par la preuve de (?)OoABBpXNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABBpXNPm2 : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABBpXNPm3 : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HOoABpeq : rk(Oo :: A :: Bp :: nil) = 3) by (apply LOoABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABpmtmp : rk(Oo :: A :: Bp :: nil) >= 3) by (solve_hyps_min HOoABpeq HOoABpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Bp :: nil) (Oo :: A :: B :: Bp :: X :: N :: P :: nil) 3 3 HOoABpmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABpXNP requis par la preuve de (?)ABpXNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Bp :: X :: N :: P ::  de rang :  3 et 4 \t AiB : A :: Bp ::  de rang :  2 et 2 \t A : Oo :: A :: B :: Bp ::   de rang : 3 et 3 *)\nassert(HABpXNPm2 : rk(A :: Bp :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABBpeq : rk(Oo :: A :: B :: Bp :: nil) = 3) by (apply LOoABBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABBpMtmp : rk(Oo :: A :: B :: Bp :: nil) <= 3) by (solve_hyps_max HOoABBpeq HOoABBpM3).\n\tassert(HOoABBpXNPmtmp : rk(Oo :: A :: B :: Bp :: X :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABBpXNPeq HOoABBpXNPm3).\n\tassert(HABpeq : rk(A :: Bp :: nil) = 2) by (apply LABp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpmtmp : rk(A :: Bp :: nil) >= 2) by (solve_hyps_min HABpeq HABpm2).\n\tassert(Hincl : incl (A :: Bp :: nil) (list_inter (Oo :: A :: B :: Bp :: nil) (A :: Bp :: X :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Bp :: X :: N :: P :: nil) (Oo :: A :: B :: Bp :: A :: Bp :: X :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: Bp :: A :: Bp :: X :: N :: P :: nil) ((Oo :: A :: B :: Bp :: nil) ++ (A :: Bp :: X :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABBpXNPmtmp;try rewrite HT2 in HOoABBpXNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: Bp :: nil) (A :: Bp :: X :: N :: P :: nil) (A :: Bp :: nil) 3 2 3 HOoABBpXNPmtmp HABpmtmp HOoABBpMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -4 -4 et -2*)\nassert(HABpXNPM3 : rk(A :: Bp :: X :: N :: P :: nil) <= 3).\n{\n\tassert(HABpXMtmp : rk(A :: Bp :: X :: nil) <= 2) by (solve_hyps_max HABpXeq HABpXM2).\n\tassert(HBpNPMtmp : rk(Bp :: N :: P :: nil) <= 2) by (solve_hyps_max HBpNPeq HBpNPM2).\n\tassert(HBpmtmp : rk(Bp :: nil) >= 1) by (solve_hyps_min HBpeq HBpm1).\n\tassert(Hincl : incl (Bp :: nil) (list_inter (A :: Bp :: X :: nil) (Bp :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Bp :: X :: N :: P :: nil) (A :: Bp :: X :: Bp :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: Bp :: X :: Bp :: N :: P :: nil) ((A :: Bp :: X :: nil) ++ (Bp :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: Bp :: X :: nil) (Bp :: N :: P :: nil) (Bp :: nil) 2 2 1 HABpXMtmp HBpNPMtmp HBpmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HABpXNPm3 : rk(A :: Bp :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HABpNeq : rk(A :: Bp :: N :: nil) = 3) by (apply LABpN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpNmtmp : rk(A :: Bp :: N :: nil) >= 3) by (solve_hyps_min HABpNeq HABpNm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: Bp :: N :: nil) (A :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: Bp :: N :: nil) (A :: Bp :: X :: N :: P :: nil) 3 3 HABpNmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HABpXNPM : rk(A :: Bp :: X :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABpXNPm : rk(A :: Bp :: X :: N :: P ::  nil) >= 1) by (solve_hyps_min HABpXNPeq HABpXNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAXNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: X :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXNP requis par la preuve de (?)OoABXNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXNP requis par la preuve de (?)OoABXNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXNPm2 : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXNPm3 : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: N :: P :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXNP requis par la preuve de (?)AXNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: N :: P ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXNPm2 : rk(A :: X :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXNPmtmp : rk(Oo :: A :: B :: X :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABXNPeq HOoABXNPm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: N :: P :: nil) (Oo :: A :: B :: X :: A :: X :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: N :: P :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXNPmtmp;try rewrite HT2 in HOoABXNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: N :: P :: nil) (A :: X :: nil) 3 2 3 HOoABXNPmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAXNPm3 : rk(A :: X :: N :: P :: nil) >= 3).\n{\n\tassert(HANPeq : rk(A :: N :: P :: nil) = 3) by (apply LANP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: X :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAXNPM3 : rk(A :: X :: N :: P :: nil) <= 3).\n{\n\tassert(HABpXNPeq : rk(A :: Bp :: X :: N :: P :: nil) = 3) by (apply LABpXNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HABpXNPMtmp : rk(A :: Bp :: X :: N :: P :: nil) <= 3) by (solve_hyps_max HABpXNPeq HABpXNPM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: X :: N :: P :: nil) (A :: Bp :: X :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (A :: X :: N :: P :: nil) (A :: Bp :: X :: N :: P :: nil) 3 3 HABpXNPMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAXNPM : rk(A :: X :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAXNPm : rk(A :: X :: N :: P ::  nil) >= 1) by (solve_hyps_min HAXNPeq HAXNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABMNP requis par la preuve de (?)AMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMNP requis par la preuve de (?)OoABMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMNP requis par la preuve de (?)OoABMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMNPm2 : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABMNPm3 : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAMeq : rk(Oo :: A :: M :: nil) = 3) by (apply LOoAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMmtmp : rk(Oo :: A :: M :: nil) >= 3) by (solve_hyps_min HOoAMeq HOoAMm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: nil) (Oo :: A :: B :: M :: N :: P :: nil) 3 3 HOoAMmtmp 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\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: M ::  de rang :  2 et 2 \t A : Oo :: A :: B :: M ::   de rang : 3 et 3 *)\nassert(HAMNPm2 : rk(A :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABMeq : rk(Oo :: A :: B :: M :: nil) = 3) by (apply LOoABM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABMMtmp : rk(Oo :: A :: B :: M :: nil) <= 3) by (solve_hyps_max HOoABMeq HOoABMM3).\n\tassert(HOoABMNPmtmp : rk(Oo :: A :: B :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABMNPeq HOoABMNPm3).\n\tassert(HAMeq : rk(A :: M :: nil) = 2) by (apply LAM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMmtmp : rk(A :: M :: nil) >= 2) by (solve_hyps_min HAMeq HAMm2).\n\tassert(Hincl : incl (A :: M :: nil) (list_inter (Oo :: A :: B :: M :: nil) (A :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: M :: N :: P :: nil) (Oo :: A :: B :: M :: A :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: A :: M :: N :: P :: nil) ((Oo :: A :: B :: M :: nil) ++ (A :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABMNPmtmp;try rewrite HT2 in HOoABMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: M :: nil) (A :: M :: N :: P :: nil) (A :: M :: nil) 3 2 3 HOoABMNPmtmp HAMmtmp HOoABMMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : -2 -4 et 5*)\nassert(HAMNPM3 : rk(A :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HNMtmp : rk(N :: nil) <= 1) by (solve_hyps_max HNeq HNM1).\n\tassert(HAMPMtmp : rk(A :: M :: P :: nil) <= 2) by (solve_hyps_max HAMPeq HAMPM2).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (N :: nil) (A :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: M :: N :: P :: nil) (N :: A :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (N :: A :: M :: P :: nil) ((N :: nil) ++ (A :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (N :: nil) (A :: M :: P :: nil) (nil) 1 2 0 HNMtmp HAMPMtmp Hmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAMNPm3 : rk(A :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HANPeq : rk(A :: N :: P :: nil) = 3) by (apply LANP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: M :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HAMNPM : rk(A :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAMNPm : rk(A :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HAMNPeq HAMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAXMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: X :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 1  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)OoABXMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNP requis par la preuve de (?)OoABXMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNPm2 : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNPm3 : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: P :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour AXMNP requis par la preuve de (?)AXMNP pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 5 4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: X :: M :: N :: P ::  de rang :  3 et 4 \t AiB : A :: X ::  de rang :  2 et 2 \t A : Oo :: A :: B :: X ::   de rang : 3 et 3 *)\nassert(HAXMNPm2 : rk(A :: X :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HOoABXeq : rk(Oo :: A :: B :: X :: nil) = 3) by (apply LOoABX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABXMtmp : rk(Oo :: A :: B :: X :: nil) <= 3) by (solve_hyps_max HOoABXeq HOoABXM3).\n\tassert(HOoABXMNPmtmp : rk(Oo :: A :: B :: X :: M :: N :: P :: nil) >= 3) by (solve_hyps_min HOoABXMNPeq HOoABXMNPm3).\n\tassert(HAXeq : rk(A :: X :: nil) = 2) by (apply LAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXmtmp : rk(A :: X :: nil) >= 2) by (solve_hyps_min HAXeq HAXm2).\n\tassert(Hincl : incl (A :: X :: nil) (list_inter (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: X :: M :: N :: P :: nil) (Oo :: A :: B :: X :: A :: X :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: X :: A :: X :: M :: N :: P :: nil) ((Oo :: A :: B :: X :: nil) ++ (A :: X :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABXMNPmtmp;try rewrite HT2 in HOoABXMNPmtmp.\n\tassert(HT := rule_4 (Oo :: A :: B :: X :: nil) (A :: X :: M :: N :: P :: nil) (A :: X :: nil) 3 2 3 HOoABXMNPmtmp HAXmtmp HOoABXMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HAXMNPm3 : rk(A :: X :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HANPeq : rk(A :: N :: P :: nil) = 3) by (apply LANP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: N :: P :: nil) (A :: X :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: N :: P :: nil) (A :: X :: M :: N :: P :: nil) 3 3 HANPmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 1 code (5 dans la th\u00e8se) conclusion AUB *)\n(* marque des ant\u00e9c\u00e9dents A B AiB : 4 4 et 4*)\nassert(HAXMNPM3 : rk(A :: X :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HAXNPeq : rk(A :: X :: N :: P :: nil) = 3) by (apply LAXNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAXNPMtmp : rk(A :: X :: N :: P :: nil) <= 3) by (solve_hyps_max HAXNPeq HAXNPM3).\n\tassert(HAMNPeq : rk(A :: M :: N :: P :: nil) = 3) by (apply LAMNP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAMNPMtmp : rk(A :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HAMNPeq HAMNPM3).\n\tassert(HANPeq : rk(A :: N :: P :: nil) = 3) by (apply LANP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HANPmtmp : rk(A :: N :: P :: nil) >= 3) by (solve_hyps_min HANPeq HANPm3).\n\tassert(Hincl : incl (A :: N :: P :: nil) (list_inter (A :: X :: N :: P :: nil) (A :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: X :: M :: N :: P :: nil) (A :: X :: N :: P :: A :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: X :: N :: P :: A :: M :: N :: P :: nil) ((A :: X :: N :: P :: nil) ++ (A :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: X :: N :: P :: nil) (A :: M :: N :: P :: nil) (A :: N :: P :: nil) 3 3 3 HAXNPMtmp HAMNPMtmp HANPmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HAXMNPM : rk(A :: X :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HAXMNPm : rk(A :: X :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HAXMNPeq HAXMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LACBpYZMNP : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: C :: Bp :: Y :: Z :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ACBpYZMNP requis par la preuve de (?)ACBpYZMNP pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HACBpYZMNPm2 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 2).\n{\n\tassert(HACmtmp : rk(A :: C :: nil) >= 2) by (solve_hyps_min HACeq HACm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 2 2 HACmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HACBpYZMNPm3 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HACBpeq : rk(A :: C :: Bp :: nil) = 3) by (apply LACBp with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpmtmp : rk(A :: C :: Bp :: nil) >= 3) by (solve_hyps_min HACBpeq HACBpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: Bp :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: Bp :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 3 3 HACBpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HACBpYZMNPm4 : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HACBpMeq : rk(A :: C :: Bp :: M :: nil) = 4) by (apply LACBpM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HACBpMmtmp : rk(A :: C :: Bp :: M :: nil) >= 4) by (solve_hyps_min HACBpMeq HACBpMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (A :: C :: Bp :: M :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: C :: Bp :: M :: nil) (A :: C :: Bp :: Y :: Z :: M :: N :: P :: nil) 4 4 HACBpMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HACBpYZMNPM : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HACBpYZMNPm : rk(A :: C :: Bp :: Y :: Z :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HACBpYZMNPeq HACBpYZMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LAMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(A :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour AMQ requis par la preuve de (?)AMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour AMQ requis par la preuve de (?)AMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Ap ::   de rang : 2 et 2 *)\nassert(HAMQm2 : rk(A :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoApMtmp : rk(Oo :: Ap :: nil) <= 2) by (solve_hyps_max HOoApeq HOoApM2).\n\tassert(HOoAApMQeq : rk(Oo :: A :: Ap :: M :: Q :: nil) = 4) by (apply LOoAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMQmtmp : rk(Oo :: A :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAApMQeq HOoAApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: nil) (A :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: M :: Q :: nil) (Oo :: Ap :: A :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: A :: M :: Q :: nil) ((Oo :: Ap :: nil) ++ (A :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApMQmtmp;try rewrite HT2 in HOoAApMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: nil) (A :: M :: Q :: nil) (nil) 4 0 2 HOoAApMQmtmp Hmtmp HOoApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HAMQm3 : rk(A :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HAApMQeq : rk(A :: Ap :: M :: Q :: nil) = 3) by (apply LAApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HAApMQmtmp : rk(A :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HAApMQeq HAApMQm3).\n\tassert(HMQeq : rk(M :: Q :: nil) = 2) by (apply LMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (A :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: Ap :: M :: Q :: nil) (A :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: M :: Q :: Ap :: M :: Q :: nil) ((A :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HAApMQmtmp;try rewrite HT2 in HAApMQmtmp.\n\tassert(HT := rule_2 (A :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 3 2 2 HAApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HAMQM : rk(A :: M :: Q ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HAMQeq HAMQM3).\nassert(HAMQm : rk(A :: M :: Q ::  nil) >= 1) by (solve_hyps_min HAMQeq HAMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LBMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(B :: M :: Q ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour BMQ requis par la preuve de (?)BMQ pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 3) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -4*)\n(* ensembles concern\u00e9s AUB : Oo :: B :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Oo :: Ap ::   de rang : 2 et 2 *)\nassert(HBMQm2 : rk(B :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoApMtmp : rk(Oo :: Ap :: nil) <= 2) by (solve_hyps_max HOoApeq HOoApM2).\n\tassert(HOoBApMQeq : rk(Oo :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoBApMQmtmp : rk(Oo :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoBApMQeq HOoBApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Oo :: Ap :: nil) (B :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: B :: Ap :: M :: Q :: nil) (Oo :: Ap :: B :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: Ap :: B :: M :: Q :: nil) ((Oo :: Ap :: nil) ++ (B :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoBApMQmtmp;try rewrite HT2 in HOoBApMQmtmp.\n\tassert(HT := rule_4 (Oo :: Ap :: nil) (B :: M :: Q :: nil) (nil) 4 0 2 HOoBApMQmtmp Hmtmp HOoApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HBMQm3 : rk(B :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HBApMQeq : rk(B :: Ap :: M :: Q :: nil) = 3) by (apply LBApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HBApMQmtmp : rk(B :: Ap :: M :: Q :: nil) >= 3) by (solve_hyps_min HBApMQeq HBApMQm3).\n\tassert(HMQeq : rk(M :: Q :: nil) = 2) by (apply LMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (B :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (B :: Ap :: M :: Q :: nil) (B :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (B :: M :: Q :: Ap :: M :: Q :: nil) ((B :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HBApMQmtmp;try rewrite HT2 in HBApMQmtmp.\n\tassert(HT := rule_2 (B :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 3 2 2 HBApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HBMQM : rk(B :: M :: Q ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HBMQeq HBMQM3).\nassert(HBMQm : rk(B :: M :: Q ::  nil) >= 1) by (solve_hyps_min HBMQeq HBMQm1).\nintuition.\nQed.\n\n(* dans constructLemma(), requis par LOoABMQ *)\n(* dans la couche 0 *)\nLemma LOoABApMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMQ requis par la preuve de (?)OoABApMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMQm2 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : C ::   de rang : 1 et 1 *)\nassert(HOoABApMQm3 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 3).\n{\n\tassert(HCMtmp : rk(C :: nil) <= 1) by (solve_hyps_max HCeq HCM1).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (C :: Oo :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Oo :: A :: B :: Ap :: M :: Q :: nil) ((C :: nil) ++ (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) (nil) 4 0 1 HOoABCApMQmtmp Hmtmp HCMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 4 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: -4 -4 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: C :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB : Oo :: A ::  de rang :  2 et 2 \t A : Oo :: A :: C ::   de rang : 2 et 2 *)\nassert(HOoABApMQm4 : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4).\n{\n\tassert(HOoACeq : rk(Oo :: A :: C :: nil) = 2) by (apply LOoAC with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoACMtmp : rk(Oo :: A :: C :: nil) <= 2) by (solve_hyps_max HOoACeq HOoACM2).\n\tassert(HOoABCApMQmtmp : rk(Oo :: A :: B :: C :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABCApMQeq HOoABCApMQm4).\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hincl : incl (Oo :: A :: nil) (list_inter (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: C :: Ap :: M :: Q :: nil) (Oo :: A :: C :: Oo :: A :: B :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: C :: Oo :: A :: B :: Ap :: M :: Q :: nil) ((Oo :: A :: C :: nil) ++ (Oo :: A :: B :: Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABCApMQmtmp;try rewrite HT2 in HOoABCApMQmtmp.\n\tassert(HT := rule_4 (Oo :: A :: C :: nil) (Oo :: A :: B :: Ap :: M :: Q :: nil) (Oo :: A :: nil) 4 2 2 HOoABCApMQmtmp HOoAmtmp HOoACMtmp Hincl); apply HT.\n}\n\nassert(HOoABApMQM : rk(Oo :: A :: B :: Ap :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApMQm : rk(Oo :: A :: B :: Ap :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoABApMQeq HOoABApMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABMQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: M :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 2  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABMQ requis par la preuve de (?)OoABMQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABMQm2 : rk(Oo :: A :: B :: M :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: M :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: M :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -1 et -2*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: B :: Ap :: M :: Q ::  de rang :  4 et 4 \t AiB :  de rang :  0 et 0 \t A : Ap ::   de rang : 1 et 1 *)\nassert(HOoABMQm3 : rk(Oo :: A :: B :: M :: Q :: nil) >= 3).\n{\n\tassert(HApMtmp : rk(Ap :: nil) <= 1) by (solve_hyps_max HApeq HApM1).\n\tassert(HOoABApMQeq : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoABApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMQmtmp : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMQeq HOoABApMQm4).\n\tassert(Hmtmp : rk(nil) >= 0) by (solve_hyps_min Hnuleq Hm).\n\tassert(Hincl : incl (nil) (list_inter (Ap :: nil) (Oo :: A :: B :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: Q :: nil) (Ap :: Oo :: A :: B :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Oo :: A :: B :: M :: Q :: nil) ((Ap :: nil) ++ (Oo :: A :: B :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMQmtmp;try rewrite HT2 in HOoABApMQmtmp.\n\tassert(HT := rule_4 (Ap :: nil) (Oo :: A :: B :: M :: Q :: nil) (nil) 4 0 1 HOoABApMQmtmp Hmtmp HApMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 2 code (7 ou 8 dans la th\u00e8se) conclusion A*)\n(* marque des ant\u00e9c\u00e9dents AUB AiB B: 4 4 et -4*)\nassert(HOoABMQm4 : rk(Oo :: A :: B :: M :: Q :: nil) >= 4).\n{\n\tassert(HApMQMtmp : rk(Ap :: M :: Q :: nil) <= 2) by (solve_hyps_max HApMQeq HApMQM2).\n\tassert(HOoABApMQeq : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) = 4) by (apply LOoABApMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoABApMQmtmp : rk(Oo :: A :: B :: Ap :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoABApMQeq HOoABApMQm4).\n\tassert(HMQeq : rk(M :: Q :: nil) = 2) by (apply LMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HMQmtmp : rk(M :: Q :: nil) >= 2) by (solve_hyps_min HMQeq HMQm2).\n\tassert(Hincl : incl (M :: Q :: nil) (list_inter (Oo :: A :: B :: M :: Q :: nil) (Ap :: M :: Q :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: B :: Ap :: M :: Q :: nil) (Oo :: A :: B :: M :: Q :: Ap :: M :: Q :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: B :: M :: Q :: Ap :: M :: Q :: nil) ((Oo :: A :: B :: M :: Q :: nil) ++ (Ap :: M :: Q :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoABApMQmtmp;try rewrite HT2 in HOoABApMQmtmp.\n\tassert(HT := rule_2 (Oo :: A :: B :: M :: Q :: nil) (Ap :: M :: Q :: nil) (M :: Q :: nil) 4 2 2 HOoABApMQmtmp HMQmtmp HApMQMtmp Hincl);apply HT.\n}\n\nassert(HOoABMQM : rk(Oo :: A :: B :: M :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABMQm : rk(Oo :: A :: B :: M :: Q ::  nil) >= 1) by (solve_hyps_min HOoABMQeq HOoABMQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABApMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: Ap :: M :: N :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABApMNQ requis par la preuve de (?)OoABApMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm2 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABApMNQm3 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAApmtmp : rk(Oo :: A :: Ap :: nil) >= 3) by (solve_hyps_min HOoAApeq HOoAApm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 3 3 HOoAApmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABApMNQm4 : rk(Oo :: A :: B :: Ap :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAApMeq : rk(Oo :: A :: Ap :: M :: nil) = 4) by (apply LOoAApM with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApMmtmp : rk(Oo :: A :: Ap :: M :: nil) >= 4) by (solve_hyps_min HOoAApMeq HOoAApMm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: Ap :: M :: nil) (Oo :: A :: B :: Ap :: M :: N :: Q :: nil) 4 4 HOoAApMmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABApMNQM : rk(Oo :: A :: B :: Ap :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABApMNQm : rk(Oo :: A :: B :: Ap :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoABApMNQeq HOoABApMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoABXMNQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: B :: X :: M :: N :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoABXMNQ requis par la preuve de (?)OoABXMNQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoABXMNQm2 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNQm3 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoABXMNQm4 : rk(Oo :: A :: B :: X :: M :: N :: Q :: nil) >= 4).\n{\n\tassert(HOoAMQeq : rk(Oo :: A :: M :: Q :: nil) = 4) by (apply LOoAMQ with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAMQmtmp : rk(Oo :: A :: M :: Q :: nil) >= 4) by (solve_hyps_min HOoAMQeq HOoAMQm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: M :: Q :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: M :: Q :: nil) (Oo :: A :: B :: X :: M :: N :: Q :: nil) 4 4 HOoAMQmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoABXMNQM : rk(Oo :: A :: B :: X :: M :: N :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoABXMNQm : rk(Oo :: A :: B :: X :: M :: N :: Q ::  nil) >= 1) by (solve_hyps_min HOoABXMNQeq HOoABXMNQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LOoAXMNPQ : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Oo :: A :: X :: M :: N :: P :: Q ::  nil) = 4.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour OoAXMNPQ requis par la preuve de (?)OoAXMNPQ pour la r\u00e8gle 5  *)\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : -4 *)\nassert(HOoAXMNPQm2 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 2).\n{\n\tassert(HOoAmtmp : rk(Oo :: A :: nil) >= 2) by (solve_hyps_min HOoAeq HOoAm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 2 2 HOoAmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNPQm3 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 3).\n{\n\tassert(HOoAXeq : rk(Oo :: A :: X :: nil) = 3) by (apply LOoAX with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAXmtmp : rk(Oo :: A :: X :: nil) >= 3) by (solve_hyps_min HOoAXeq HOoAXm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: X :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 3 3 HOoAXmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la r\u00e8gle 5 code (1 ou 2 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HOoAXMNPQm4 : rk(Oo :: A :: X :: M :: N :: P :: Q :: nil) >= 4).\n{\n\tassert(HOoANPeq : rk(Oo :: A :: N :: P :: nil) = 4) by (apply LOoANP with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoANPmtmp : rk(Oo :: A :: N :: P :: nil) >= 4) by (solve_hyps_min HOoANPeq HOoANPm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (Oo :: A :: N :: P :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Oo :: A :: N :: P :: nil) (Oo :: A :: X :: M :: N :: P :: Q :: nil) 4 4 HOoANPmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HOoAXMNPQM : rk(Oo :: A :: X :: M :: N :: P :: Q ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HOoAXMNPQm : rk(Oo :: A :: X :: M :: N :: P :: Q ::  nil) >= 1) by (solve_hyps_min HOoAXMNPQeq HOoAXMNPQm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LYZMN : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> rk(Y :: Z :: M :: N ::  nil) = 3.\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour YZMN requis par la preuve de (?)YZMN pour la r\u00e8gle 6  *)\n(* dans constructProofaux(), preuve de 2 <= rg <= 4 pour YZMN requis par la preuve de (?)YZMN pour la r\u00e8gle 4  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour YZMN requis par la preuve de (?)YZMN pour la r\u00e8gle 4  *)\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 2 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et 4*)\n(* ensembles concern\u00e9s AUB : Oo :: A :: Ap :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : Y ::  de rang :  1 et 1 \t A : Oo :: A :: Ap :: Y ::   de rang : 3 et 3 *)\nassert(HYZMNm2 : rk(Y :: Z :: M :: N :: nil) >= 2).\n{\n\tassert(HOoAApYeq : rk(Oo :: A :: Ap :: Y :: nil) = 3) by (apply LOoAApY with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApYMtmp : rk(Oo :: A :: Ap :: Y :: nil) <= 3) by (solve_hyps_max HOoAApYeq HOoAApYM3).\n\tassert(HOoAApYZMNeq : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) = 4) by (apply LOoAApYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HOoAApYZMNmtmp : rk(Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HOoAApYZMNeq HOoAApYZMNm4).\n\tassert(HYmtmp : rk(Y :: nil) >= 1) by (solve_hyps_min HYeq HYm1).\n\tassert(Hincl : incl (Y :: nil) (list_inter (Oo :: A :: Ap :: Y :: nil) (Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Oo :: A :: Ap :: Y :: Z :: M :: N :: nil) (Oo :: A :: Ap :: Y :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Oo :: A :: Ap :: Y :: Y :: Z :: M :: N :: nil) ((Oo :: A :: Ap :: Y :: nil) ++ (Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HOoAApYZMNmtmp;try rewrite HT2 in HOoAApYZMNmtmp.\n\tassert(HT := rule_4 (Oo :: A :: Ap :: Y :: nil) (Y :: Z :: M :: N :: nil) (Y :: nil) 4 1 3 HOoAApYZMNmtmp HYmtmp HOoAApYMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 4 code (7 ou 8 dans la th\u00e8se) concerne B (rang 3 et 4) *)\n(* marque des ant\u00e9c\u00e9dents AUB AiB A: 4 -2 et -4*)\n(* ensembles concern\u00e9s AUB : C :: Bp :: Y :: Z :: M :: N ::  de rang :  4 et 4 \t AiB : Z ::  de rang :  1 et 1 \t A : C :: Bp :: Z ::   de rang : 2 et 2 *)\nassert(HYZMNm3 : rk(Y :: Z :: M :: N :: nil) >= 3).\n{\n\tassert(HCBpZMtmp : rk(C :: Bp :: Z :: nil) <= 2) by (solve_hyps_max HCBpZeq HCBpZM2).\n\tassert(HCBpYZMNeq : rk(C :: Bp :: Y :: Z :: M :: N :: nil) = 4) by (apply LCBpYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HCBpYZMNmtmp : rk(C :: Bp :: Y :: Z :: M :: N :: nil) >= 4) by (solve_hyps_min HCBpYZMNeq HCBpYZMNm4).\n\tassert(HZmtmp : rk(Z :: nil) >= 1) by (solve_hyps_min HZeq HZm1).\n\tassert(Hincl : incl (Z :: nil) (list_inter (C :: Bp :: Z :: nil) (Y :: Z :: M :: N :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (C :: Bp :: Y :: Z :: M :: N :: nil) (C :: Bp :: Z :: Y :: Z :: M :: N :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (C :: Bp :: Z :: Y :: Z :: M :: N :: nil) ((C :: Bp :: Z :: nil) ++ (Y :: Z :: M :: N :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HCBpYZMNmtmp;try rewrite HT2 in HCBpYZMNmtmp.\n\tassert(HT := rule_4 (C :: Bp :: Z :: nil) (Y :: Z :: M :: N :: nil) (Z :: nil) 4 1 2 HCBpYZMNmtmp HZmtmp HCBpZMtmp Hincl); apply HT.\n}\n\n(* Application de la r\u00e8gle 6 (code, 3 ou 4 dans la th\u00e8se) *)\n(* marque de l'ant\u00e9c\u00e9dent : 4 *)\nassert(HYZMNM3 : rk(Y :: Z :: M :: N :: nil) <= 3).\n{\n\tassert(HXYZMNeq : rk(X :: Y :: Z :: M :: N :: nil) = 3) by (apply LXYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption).\n\tassert(HXYZMNMtmp : rk(X :: Y :: Z :: M :: N :: nil) <= 3) by (solve_hyps_max HXYZMNeq HXYZMNM3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Y :: Z :: M :: N :: nil) (X :: Y :: Z :: M :: N :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_6 (Y :: Z :: M :: N :: nil) (X :: Y :: Z :: M :: N :: nil) 3 3 HXYZMNMtmp Hcomp Hincl);apply HT.\n}\n\nassert(HYZMNM : rk(Y :: Z :: M :: N ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HYZMNm : rk(Y :: Z :: M :: N ::  nil) >= 1) by (solve_hyps_min HYZMNeq HYZMNm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nTheorem def_Conclusion : forall Oo A B C Ap Bp Cp X Y Z M N P Q ,\nrk(Oo :: A ::  nil) = 2 -> rk(Oo :: B ::  nil) = 2 -> rk(A :: B ::  nil) = 2 ->\nrk(Oo :: C ::  nil) = 2 -> rk(A :: C ::  nil) = 2 -> rk(B :: C ::  nil) = 2 ->\nrk(Oo :: A :: B :: C ::  nil) = 2 -> rk(Oo :: Ap ::  nil) = 2 -> rk(Oo :: A :: Ap ::  nil) = 3 ->\nrk(Oo :: Bp ::  nil) = 2 -> rk(Ap :: Bp ::  nil) = 2 -> rk(Oo :: Cp ::  nil) = 2 ->\nrk(Ap :: Cp ::  nil) = 2 -> rk(Bp :: Cp ::  nil) = 2 -> rk(Oo :: Ap :: Bp :: Cp ::  nil) = 2 ->\nrk(B :: Ap :: X ::  nil) = 2 -> rk(A :: Bp :: X ::  nil) = 2 -> rk(C :: Ap :: Y ::  nil) = 2 ->\nrk(A :: Cp :: Y ::  nil) = 2 -> rk(C :: Bp :: Z ::  nil) = 2 -> rk(B :: Cp :: Z ::  nil) = 2 ->\nrk(X :: Y :: Z ::  nil) = 2 -> rk(A :: M :: P ::  nil) = 2 -> rk(Oo :: A :: Ap :: Bp :: Cp :: M :: P ::  nil) = 4 ->\nrk(Bp :: N :: P ::  nil) = 2 -> rk(Oo :: A :: B :: C :: Bp :: N :: P ::  nil) = 4 -> rk(Ap :: M :: Q ::  nil) = 2 ->\nrk(Oo :: A :: B :: C :: Ap :: M :: Q ::  nil) = 4 -> rk(B :: N :: Q ::  nil) = 2 -> rk(Oo :: B :: Ap :: Bp :: Cp :: N :: Q ::  nil) = 4 ->\nrk(A :: B :: M :: N :: P :: Q ::  nil) = 4 -> rk(Ap :: Bp :: M :: N :: P :: Q ::  nil) = 4 -> \n\t rk(Y :: Z :: M :: N ::  nil) = 3  .\nProof.\n\nintros Oo A B C Ap Bp Cp X Y Z M N P Q \nHOoAeq HOoBeq HABeq HOoCeq HACeq HBCeq HOoABCeq HOoApeq HOoAApeq HOoBpeq\nHApBpeq HOoCpeq HApCpeq HBpCpeq HOoApBpCpeq HBApXeq HABpXeq HCApYeq HACpYeq HCBpZeq\nHBCpZeq HXYZeq HAMPeq HOoAApBpCpMPeq HBpNPeq HOoABCBpNPeq HApMQeq HOoABCApMQeq HBNQeq HOoBApBpCpNQeq\nHABMNPQeq HApBpMNPQeq .\nrepeat split.\n\n\tapply LYZMN with (Oo := Oo) (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (X := X) (Y := Y) (Z := Z) (M := M) (N := N) (P := P) (Q := Q) ; assumption.\nQed .\n", "meta": {"author": "pascalschreck", "repo": "ADG2021", "sha": "09a5b93c80a0390aa645f53d9b64c15c2cb453e5", "save_path": "github-repos/coq/pascalschreck-ADG2021", "path": "github-repos/coq/pascalschreck-ADG2021/ADG2021-09a5b93c80a0390aa645f53d9b64c15c2cb453e5/Dandelin-Gallucci/Pappus2DG_R_exists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.18800484681746518}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines a number of data types and operations used in\n  the abstract syntax trees of many of the intermediate languages. *)\n\nRequire Import String.\nRequire Import Coqlib Maps Errors Integers Floats.\nRequire Archi.\n\nSet Implicit Arguments.\n\n(** * Syntactic elements *)\n\n(** Identifiers (names of local variables, of global symbols and functions,\n  etc) are represented by the type [positive] of positive integers. *)\n\nDefinition ident := positive.\n\nDefinition ident_eq := peq.\n\n(** The intermediate languages are weakly typed, using the following types: *)\n\nInductive typ : Type :=\n  | Tint                (**r 32-bit integers or pointers *)\n  | Tfloat              (**r 64-bit double-precision floats *)\n  | Tlong               (**r 64-bit integers *)\n  | Tsingle             (**r 32-bit single-precision floats *)\n  | Tany32              (**r any 32-bit value *)\n  | Tany64.             (**r any 64-bit value, i.e. any value *)\n\nLemma typ_eq: forall (t1 t2: typ), {t1=t2} + {t1<>t2}.\nProof. decide equality. Defined.\nGlobal Opaque typ_eq.\n\nDefinition opt_typ_eq: forall (t1 t2: option typ), {t1=t2} + {t1<>t2}\n                     := option_eq typ_eq.\n\nDefinition list_typ_eq: forall (l1 l2: list typ), {l1=l2} + {l1<>l2}\n                     := list_eq_dec typ_eq.\n\nDefinition Tptr : typ := if Archi.ptr64 then Tlong else Tint.\n\nDefinition typesize (ty: typ) : Z :=\n  match ty with\n  | Tint => 4\n  | Tfloat => 8\n  | Tlong => 8\n  | Tsingle => 4\n  | Tany32 => 4\n  | Tany64 => 8\n  end.\n\nLemma typesize_pos: forall ty, typesize ty > 0.\nProof. destruct ty; simpl; omega. Qed.\n\nLemma typesize_Tptr: typesize Tptr = if Archi.ptr64 then 8 else 4.\nProof. unfold Tptr; destruct Archi.ptr64; auto. Qed.\n\n(** All values of size 32 bits are also of type [Tany32].  All values\n  are of type [Tany64].  This corresponds to the following subtyping\n  relation over types. *)\n\nDefinition subtype (ty1 ty2: typ) : bool :=\n  match ty1, ty2 with\n  | Tint, Tint => true\n  | Tlong, Tlong => true\n  | Tfloat, Tfloat => true\n  | Tsingle, Tsingle => true\n  | (Tint | Tsingle | Tany32), Tany32 => true\n  | _, Tany64 => true\n  | _, _ => false\n  end.\n\nFixpoint subtype_list (tyl1 tyl2: list typ) : bool :=\n  match tyl1, tyl2 with\n  | nil, nil => true\n  | ty1::tys1, ty2::tys2 => subtype ty1 ty2 && subtype_list tys1 tys2\n  | _, _ => false\n  end.\n\n(** Additionally, function definitions and function calls are annotated\n  by function signatures indicating:\n- the number and types of arguments;\n- the type of the returned value, if any;\n- additional information on which calling convention to use.\n\nThese signatures are used in particular to determine appropriate\ncalling conventions for the function. *)\n\nRecord calling_convention : Type := mkcallconv {\n  cc_vararg: bool;                      (**r variable-arity function *)\n  cc_unproto: bool;                     (**r old-style unprototyped function *)\n  cc_structret: bool                    (**r function returning a struct  *)\n}.\n\nDefinition cc_default :=\n  {| cc_vararg := false; cc_unproto := false; cc_structret := false |}.\n\nDefinition calling_convention_eq (x y: calling_convention) : {x=y} + {x<>y}.\nProof.\n  decide equality; apply bool_dec.\nDefined.\nGlobal Opaque calling_convention_eq.\n\nRecord signature : Type := mksignature {\n  sig_args: list typ;\n  sig_res: option typ;\n  sig_cc: calling_convention\n}.\n\nDefinition proj_sig_res (s: signature) : typ :=\n  match s.(sig_res) with\n  | None => Tint\n  | Some t => t\n  end.\n\nDefinition signature_eq: forall (s1 s2: signature), {s1=s2} + {s1<>s2}.\nProof.\n  generalize opt_typ_eq, list_typ_eq, calling_convention_eq; decide equality.\nDefined.\nGlobal Opaque signature_eq.\n\nDefinition signature_main :=\n  {| sig_args := nil; sig_res := Some Tint; sig_cc := cc_default |}.\n\n(** Memory accesses (load and store instructions) are annotated by\n  a ``memory chunk'' indicating the type, size and signedness of the\n  chunk of memory being accessed. *)\n\nInductive memory_chunk : Type :=\n  | Mint8signed     (**r 8-bit signed integer *)\n  | Mint8unsigned   (**r 8-bit unsigned integer *)\n  | Mint16signed    (**r 16-bit signed integer *)\n  | Mint16unsigned  (**r 16-bit unsigned integer *)\n  | Mint32          (**r 32-bit integer, or pointer *)\n  | Mint64          (**r 64-bit integer *)\n  | Mfloat32        (**r 32-bit single-precision float *)\n  | Mfloat64        (**r 64-bit double-precision float *)\n  | Many32          (**r any value that fits in 32 bits *)\n  | Many64.         (**r any value *)\n\nDefinition chunk_eq: forall (c1 c2: memory_chunk), {c1=c2} + {c1<>c2}.\nProof. decide equality. Defined.\nGlobal Opaque chunk_eq.\n\nDefinition Mptr : memory_chunk := if Archi.ptr64 then Mint64 else Mint32.\n\n(** The type (integer/pointer or float) of a chunk. *)\n\nDefinition type_of_chunk (c: memory_chunk) : typ :=\n  match c with\n  | Mint8signed => Tint\n  | Mint8unsigned => Tint\n  | Mint16signed => Tint\n  | Mint16unsigned => Tint\n  | Mint32 => Tint\n  | Mint64 => Tlong\n  | Mfloat32 => Tsingle\n  | Mfloat64 => Tfloat\n  | Many32 => Tany32\n  | Many64 => Tany64\n  end.\n\nLemma type_of_Mptr: type_of_chunk Mptr = Tptr.\nProof. unfold Mptr, Tptr; destruct Archi.ptr64; auto. Qed.\n\n(** The chunk that is appropriate to store and reload a value of\n  the given type, without losing information. *)\n\nDefinition chunk_of_type (ty: typ) :=\n  match ty with\n  | Tint => Mint32\n  | Tfloat => Mfloat64\n  | Tlong => Mint64\n  | Tsingle => Mfloat32\n  | Tany32 => Many32\n  | Tany64 => Many64\n  end.\n\nLemma chunk_of_Tptr: chunk_of_type Tptr = Mptr.\nProof. unfold Mptr, Tptr; destruct Archi.ptr64; auto. Qed.\n\n(** Initialization data for global variables. *)\n\nInductive init_data: Type :=\n  | Init_int8: int -> init_data\n  | Init_int16: int -> init_data\n  | Init_int32: int -> init_data\n  | Init_int64: int64 -> init_data\n  | Init_float32: float32 -> init_data\n  | Init_float64: float -> init_data\n  | Init_space: Z -> init_data\n  | Init_addrof: ident -> ptrofs -> init_data.  (**r address of symbol + offset *)\n\nDefinition init_data_size (i: init_data) : Z :=\n  match i with\n  | Init_int8 _ => 1\n  | Init_int16 _ => 2\n  | Init_int32 _ => 4\n  | Init_int64 _ => 8\n  | Init_float32 _ => 4\n  | Init_float64 _ => 8\n  | Init_addrof _ _ => if Archi.ptr64 then 8 else 4\n  | Init_space n => Z.max n 0\n  end.\n\nFixpoint init_data_list_size (il: list init_data) {struct il} : Z :=\n  match il with\n  | nil => 0\n  | i :: il' => init_data_size i + init_data_list_size il'\n  end.\n\nLemma init_data_size_pos:\n  forall i, init_data_size i >= 0.\nProof.\n  destruct i; simpl; try xomega. destruct Archi.ptr64; omega.\nQed.\n\nLemma init_data_list_size_pos:\n  forall il, init_data_list_size il >= 0.\nProof.\n  induction il; simpl. omega. generalize (init_data_size_pos a); omega.\nQed.\n\n(** Information attached to global variables. *)\n\nRecord globvar (V: Type) : Type := mkglobvar {\n  gvar_info: V;                    (**r language-dependent info, e.g. a type *)\n  gvar_init: list init_data;       (**r initialization data *)\n  gvar_readonly: bool;             (**r read-only variable? (const) *)\n  gvar_volatile: bool              (**r volatile variable? *)\n}.\n\n(** Whole programs consist of:\n- a collection of global definitions (name and description);\n- a set of public names (the names that are visible outside\n  this compilation unit);\n- the name of the ``main'' function that serves as entry point in the program.\n\nA global definition is either a global function or a global variable.\nThe type of function descriptions and that of additional information\nfor variables vary among the various intermediate languages and are\ntaken as parameters to the [program] type.  The other parts of whole\nprograms are common to all languages. *)\n\nInductive globdef (F V: Type) : Type :=\n  | Gfun (f: F)\n  | Gvar (v: globvar V).\n\nArguments Gfun [F V].\nArguments Gvar [F V].\n\nRecord program (F V: Type) : Type := mkprogram {\n  prog_defs: list (ident * globdef F V);\n  prog_public: list ident;\n  prog_main: ident\n}.\n\nDefinition prog_defs_names (F V: Type) (p: program F V) : list ident :=\n  List.map fst p.(prog_defs).\n\n(** The \"definition map\" of a program maps names of globals to their definitions.\n  If several definitions have the same name, the one appearing last in [p.(prog_defs)] wins. *)\n\nDefinition prog_defmap (F V: Type) (p: program F V) : PTree.t (globdef F V) :=\n  PTree_Properties.of_list p.(prog_defs).\n\nSection DEFMAP.\n\nVariables F V: Type.\nVariable p: program F V.\n\nLemma in_prog_defmap:\n  forall id g, (prog_defmap p)!id = Some g -> In (id, g) (prog_defs p).\nProof.\n  apply PTree_Properties.in_of_list.\nQed.\n\nLemma prog_defmap_dom:\n  forall id, In id (prog_defs_names p) -> exists g, (prog_defmap p)!id = Some g.\nProof.\n  apply PTree_Properties.of_list_dom.\nQed.\n\nLemma prog_defmap_unique:\n  forall defs1 id g defs2,\n  prog_defs p = defs1 ++ (id, g) :: defs2 ->\n  ~In id (map fst defs2) ->\n  (prog_defmap p)!id = Some g.\nProof.\n  unfold prog_defmap; intros. rewrite H. apply PTree_Properties.of_list_unique; auto.\nQed.\n\nLemma prog_defmap_norepet:\n  forall id g,\n  list_norepet (prog_defs_names p) ->\n  In (id, g) (prog_defs p) ->\n  (prog_defmap p)!id = Some g.\nProof.\n  apply PTree_Properties.of_list_norepet.\nQed.\n\nEnd DEFMAP.\n\n(** * Generic transformations over programs *)\n\n(** We now define a general iterator over programs that applies a given\n  code transformation function to all function descriptions and leaves\n  the other parts of the program unchanged. *)\n\nSection TRANSF_PROGRAM.\n\nVariable A B V: Type.\nVariable transf: A -> B.\n\nDefinition transform_program_globdef (idg: ident * globdef A V) : ident * globdef B V :=\n  match idg with\n  | (id, Gfun f) => (id, Gfun (transf f))\n  | (id, Gvar v) => (id, Gvar v)\n  end.\n\nDefinition transform_program (p: program A V) : program B V :=\n  mkprogram\n    (List.map transform_program_globdef p.(prog_defs))\n    p.(prog_public)\n    p.(prog_main).\n\nEnd TRANSF_PROGRAM.\n\n(** The following is a more general presentation of [transform_program]:\n- Global variable information can be transformed, in addition to function\n  definitions.\n- The transformation functions can fail and return an error message.\n- The transformation for function definitions receives a global context\n  (derived from the compilation unit being transformed) as additiona\n  argument.\n- The transformation functions receive the name of the global as\n  additional argument. *)\n\nLocal Open Scope error_monad_scope.\n\nSection TRANSF_PROGRAM_GEN.\n\nVariables A B V W: Type.\nVariable transf_fun: ident -> A -> res B.\nVariable transf_var: ident -> V -> res W.\n\nDefinition transf_globvar (i: ident) (g: globvar V) : res (globvar W) :=\n  do info' <- transf_var i g.(gvar_info);\n  OK (mkglobvar info' g.(gvar_init) g.(gvar_readonly) g.(gvar_volatile)).\n\nFixpoint transf_globdefs (l: list (ident * globdef A V)) : res (list (ident * globdef B W)) :=\n  match l with\n  | nil => OK nil\n  | (id, Gfun f) :: l' =>\n    match transf_fun id f with\n      | Error msg => Error (MSG \"In function \" :: CTX id :: MSG \": \" :: msg)\n      | OK tf =>\n        do tl' <- transf_globdefs l'; OK ((id, Gfun tf) :: tl')\n    end\n  | (id, Gvar v) :: l' =>\n    match transf_globvar id v with\n      | Error msg => Error (MSG \"In variable \" :: CTX id :: MSG \": \" :: msg)\n      | OK tv =>\n        do tl' <- transf_globdefs l'; OK ((id, Gvar tv) :: tl')\n    end\n  end.\n\nDefinition transform_partial_program2 (p: program A V) : res (program B W) :=\n  do gl' <- transf_globdefs p.(prog_defs);\n  OK (mkprogram gl' p.(prog_public) p.(prog_main)).\n\nEnd TRANSF_PROGRAM_GEN.\n\n(** The following is a special case of [transform_partial_program2],\n  where only function definitions are transformed, but not variable definitions. *)\n\nSection TRANSF_PARTIAL_PROGRAM.\n\nVariable A B V: Type.\nVariable transf_fun: A -> res B.\n\nDefinition transform_partial_program (p: program A V) : res (program B V) :=\n  transform_partial_program2 (fun i f => transf_fun f) (fun i v => OK v) p.\n\nEnd TRANSF_PARTIAL_PROGRAM.\n\nLemma transform_program_partial_program:\n  forall (A B V: Type) (transf_fun: A -> B) (p: program A V),\n  transform_partial_program (fun f => OK (transf_fun f)) p = OK (transform_program transf_fun p).\nProof.\n  intros. unfold transform_partial_program, transform_partial_program2.\n  assert (EQ: forall l,\n              transf_globdefs (fun i f => OK (transf_fun f)) (fun i (v: V) => OK v) l =\n              OK (List.map (transform_program_globdef transf_fun) l)).\n  { induction l as [ | [id g] l]; simpl.\n  - auto.\n  - destruct g; simpl; rewrite IHl; simpl. auto. destruct v; auto.\n  }\n  rewrite EQ; simpl. auto.\nQed.\n\n(** * External functions *)\n\n(** For most languages, the functions composing the program are either\n  internal functions, defined within the language, or external functions,\n  defined outside.  External functions include system calls but also\n  compiler built-in functions.  We define a type for external functions\n  and associated operations. *)\n\nInductive external_function : Type :=\n  | EF_external (name: string) (sg: signature)\n     (** A system call or library function.  Produces an event\n         in the trace. *)\n  | EF_builtin (name: string) (sg: signature)\n     (** A compiler built-in function.  Behaves like an external, but\n         can be inlined by the compiler. *)\n  | EF_runtime (name: string) (sg: signature)\n     (** A function from the run-time library.  Behaves like an\n         external, but must not be redefined. *)\n  | EF_vload (chunk: memory_chunk)\n     (** A volatile read operation.  If the adress given as first argument\n         points within a volatile global variable, generate an\n         event and return the value found in this event.  Otherwise,\n         produce no event and behave like a regular memory load. *)\n  | EF_vstore (chunk: memory_chunk)\n     (** A volatile store operation.   If the adress given as first argument\n         points within a volatile global variable, generate an event.\n         Otherwise, produce no event and behave like a regular memory store. *)\n  | EF_malloc\n     (** Dynamic memory allocation.  Takes the requested size in bytes\n         as argument; returns a pointer to a fresh block of the given size.\n         Produces no observable event. *)\n  | EF_free\n     (** Dynamic memory deallocation.  Takes a pointer to a block\n         allocated by an [EF_malloc] external call and frees the\n         corresponding block.\n         Produces no observable event. *)\n  | EF_memcpy (sz: Z) (al: Z)\n     (** Block copy, of [sz] bytes, between addresses that are [al]-aligned. *)\n  | EF_annot (kind: positive) (text: string) (targs: list typ)\n     (** A programmer-supplied annotation.  Takes zero, one or several arguments,\n         produces an event carrying the text and the values of these arguments,\n         and returns no value. *)\n  | EF_annot_val (kind: positive) (text: string) (targ: typ)\n     (** Another form of annotation that takes one argument, produces\n         an event carrying the text and the value of this argument,\n         and returns the value of the argument. *)\n  | EF_inline_asm (text: string) (sg: signature) (clobbers: list string)\n     (** Inline [asm] statements.  Semantically, treated like an\n         annotation with no parameters ([EF_annot text nil]).  To be\n         used with caution, as it can invalidate the semantic\n         preservation theorem.  Generated only if [-finline-asm] is\n         given. *)\n  | EF_debug (kind: positive) (text: ident) (targs: list typ).\n     (** Transport debugging information from the front-end to the generated\n         assembly.  Takes zero, one or several arguments like [EF_annot].\n         Unlike [EF_annot], produces no observable event. *)\n\n(** The type signature of an external function. *)\n\nDefinition ef_sig (ef: external_function): signature :=\n  match ef with\n  | EF_external name sg => sg\n  | EF_builtin name sg => sg\n  | EF_runtime name sg => sg\n  | EF_vload chunk => mksignature (Tptr :: nil) (Some (type_of_chunk chunk)) cc_default\n  | EF_vstore chunk => mksignature (Tptr :: type_of_chunk chunk :: nil) None cc_default\n  | EF_malloc => mksignature (Tptr :: nil) (Some Tptr) cc_default\n  | EF_free => mksignature (Tptr :: nil) None cc_default\n  | EF_memcpy sz al => mksignature (Tptr :: Tptr :: nil) None cc_default\n  | EF_annot kind text targs => mksignature targs None cc_default\n  | EF_annot_val kind text targ => mksignature (targ :: nil) (Some targ) cc_default\n  | EF_inline_asm text sg clob => sg\n  | EF_debug kind text targs => mksignature targs None cc_default\n  end.\n\n(** Whether an external function should be inlined by the compiler. *)\n\nDefinition ef_inline (ef: external_function) : bool :=\n  match ef with\n  | EF_external name sg => false\n  | EF_builtin name sg => true\n  | EF_runtime name sg => false\n  | EF_vload chunk => true\n  | EF_vstore chunk => true\n  | EF_malloc => false\n  | EF_free => false\n  | EF_memcpy sz al => true\n  | EF_annot kind text targs => true\n  | EF_annot_val kind Text rg => true\n  | EF_inline_asm text sg clob => true\n  | EF_debug kind text targs => true\n  end.\n\n(** Whether an external function must reload its arguments. *)\n\nDefinition ef_reloads (ef: external_function) : bool :=\n  match ef with\n  | EF_annot kind text targs => false\n  | EF_debug kind text targs => false\n  | _ => true\n  end.\n\n(** Equality between external functions.  Used in module [Allocation]. *)\n\nDefinition external_function_eq: forall (ef1 ef2: external_function), {ef1=ef2} + {ef1<>ef2}.\nProof.\n  generalize ident_eq string_dec signature_eq chunk_eq typ_eq list_eq_dec zeq Int.eq_dec; intros.\n  decide equality.\nDefined.\nGlobal Opaque external_function_eq.\n\n(** Function definitions are the union of internal and external functions. *)\n\nInductive fundef (F: Type): Type :=\n  | Internal: F -> fundef F\n  | External: external_function -> fundef F.\n\nArguments External [F].\n\nSection TRANSF_FUNDEF.\n\nVariable A B: Type.\nVariable transf: A -> B.\n\nDefinition transf_fundef (fd: fundef A): fundef B :=\n  match fd with\n  | Internal f => Internal (transf f)\n  | External ef => External ef\n  end.\n\nEnd TRANSF_FUNDEF.\n\nSection TRANSF_PARTIAL_FUNDEF.\n\nVariable A B: Type.\nVariable transf_partial: A -> res B.\n\nDefinition transf_partial_fundef (fd: fundef A): res (fundef B) :=\n  match fd with\n  | Internal f => do f' <- transf_partial f; OK (Internal f')\n  | External ef => OK (External ef)\n  end.\n\nEnd TRANSF_PARTIAL_FUNDEF.\n\n(** * Register pairs *)\n\nSet Contextual Implicit.\n\n(** In some intermediate languages (LTL, Mach), 64-bit integers can be\n  split into two 32-bit halves and held in a pair of registers.\n  Syntactically, this is captured by the type [rpair] below. *)\n\nInductive rpair (A: Type) : Type :=\n  | One (r: A)\n  | Twolong (rhi rlo: A).\n\nDefinition typ_rpair (A: Type) (typ_of: A -> typ) (p: rpair A): typ :=\n  match p with\n  | One r => typ_of r\n  | Twolong rhi rlo => Tlong\n  end.\n\nDefinition map_rpair (A B: Type) (f: A -> B) (p: rpair A): rpair B :=\n  match p with\n  | One r => One (f r)\n  | Twolong rhi rlo => Twolong (f rhi) (f rlo)\n  end.\n\nDefinition regs_of_rpair (A: Type) (p: rpair A): list A :=\n  match p with\n  | One r => r :: nil\n  | Twolong rhi rlo => rhi :: rlo :: nil\n  end.\n\nFixpoint regs_of_rpairs (A: Type) (l: list (rpair A)): list A :=\n  match l with\n  | nil => nil\n  | p :: l => regs_of_rpair p ++ regs_of_rpairs l\n  end.\n\nLemma in_regs_of_rpairs:\n  forall (A: Type) (x: A) p, In x (regs_of_rpair p) -> forall l, In p l -> In x (regs_of_rpairs l).\nProof.\n  induction l; simpl; intros. auto. apply in_app. destruct H0; auto. subst a. auto.\nQed.\n\nLemma in_regs_of_rpairs_inv:\n  forall (A: Type) (x: A) l, In x (regs_of_rpairs l) -> exists p, In p l /\\ In x (regs_of_rpair p).\nProof.\n  induction l; simpl; intros. contradiction.\n  rewrite in_app_iff in H; destruct H.\n  exists a; auto.\n  apply IHl in H. firstorder auto.\nQed.\n\nDefinition forall_rpair (A: Type) (P: A -> Prop) (p: rpair A): Prop :=\n  match p with\n  | One r => P r\n  | Twolong rhi rlo => P rhi /\\ P rlo\n  end.\n\n(** * Arguments and results to builtin functions *)\n\nInductive builtin_arg (A: Type) : Type :=\n  | BA (x: A)\n  | BA_int (n: int)\n  | BA_long (n: int64)\n  | BA_float (f: float)\n  | BA_single (f: float32)\n  | BA_loadstack (chunk: memory_chunk) (ofs: ptrofs)\n  | BA_addrstack (ofs: ptrofs)\n  | BA_loadglobal (chunk: memory_chunk) (id: ident) (ofs: ptrofs)\n  | BA_addrglobal (id: ident) (ofs: ptrofs)\n  | BA_splitlong (hi lo: builtin_arg A)\n  | BA_addptr (a1 a2: builtin_arg A).\n\nInductive builtin_res (A: Type) : Type :=\n  | BR (x: A)\n  | BR_none\n  | BR_splitlong (hi lo: builtin_res A).\n\nFixpoint globals_of_builtin_arg (A: Type) (a: builtin_arg A) : list ident :=\n  match a with\n  | BA_loadglobal chunk id ofs => id :: nil\n  | BA_addrglobal id ofs => id :: nil\n  | BA_splitlong hi lo => globals_of_builtin_arg hi ++ globals_of_builtin_arg lo\n  | BA_addptr a1 a2 => globals_of_builtin_arg a1 ++ globals_of_builtin_arg a2\n  | _ => nil\n  end.\n\nDefinition globals_of_builtin_args (A: Type) (al: list (builtin_arg A)) : list ident :=\n  List.fold_right (fun a l => globals_of_builtin_arg a ++ l) nil al.\n\nFixpoint params_of_builtin_arg (A: Type) (a: builtin_arg A) : list A :=\n  match a with\n  | BA x => x :: nil\n  | BA_splitlong hi lo => params_of_builtin_arg hi ++ params_of_builtin_arg lo\n  | BA_addptr a1 a2 => params_of_builtin_arg a1 ++ params_of_builtin_arg a2\n  | _ => nil\n  end.\n\nDefinition params_of_builtin_args (A: Type) (al: list (builtin_arg A)) : list A :=\n  List.fold_right (fun a l => params_of_builtin_arg a ++ l) nil al.\n\nFixpoint params_of_builtin_res (A: Type) (a: builtin_res A) : list A :=\n  match a with\n  | BR x => x :: nil\n  | BR_none => nil\n  | BR_splitlong hi lo => params_of_builtin_res hi ++ params_of_builtin_res lo\n  end.\n\nFixpoint map_builtin_arg (A B: Type) (f: A -> B) (a: builtin_arg A) : builtin_arg B :=\n  match a with\n  | BA x => BA (f x)\n  | BA_int n => BA_int n\n  | BA_long n => BA_long n\n  | BA_float n => BA_float n\n  | BA_single n => BA_single n\n  | BA_loadstack chunk ofs => BA_loadstack chunk ofs\n  | BA_addrstack ofs => BA_addrstack ofs\n  | BA_loadglobal chunk id ofs => BA_loadglobal chunk id ofs\n  | BA_addrglobal id ofs => BA_addrglobal id ofs\n  | BA_splitlong hi lo =>\n      BA_splitlong (map_builtin_arg f hi) (map_builtin_arg f lo)\n  | BA_addptr a1 a2 =>\n      BA_addptr (map_builtin_arg f a1) (map_builtin_arg f a2)\n  end.\n\nFixpoint map_builtin_res (A B: Type) (f: A -> B) (a: builtin_res A) : builtin_res B :=\n  match a with\n  | BR x => BR (f x)\n  | BR_none => BR_none\n  | BR_splitlong hi lo =>\n      BR_splitlong (map_builtin_res f hi) (map_builtin_res f lo)\n  end.\n\n(** Which kinds of builtin arguments are supported by which external function. *)\n\nInductive builtin_arg_constraint : Type :=\n  | OK_default\n  | OK_const\n  | OK_addrstack\n  | OK_addressing\n  | OK_all.\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/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1880048397602349}}
{"text": "From PetitC Require Import Codegen Asm TypedTree Memory Output Semantics AsmSemantics SemanticsLemmas\n                           MemoryEquivalence Values Ids Monad Star Tactics Sublist.\nImport TypedTree. (* why do i have to import TypedTree? all the definitions are on top level there *)\n\nFrom Coq Require Import Lists.List Nat ZArith Program.Utils Wellfounded Nat Lia.\nImport ListNotations.\nOpen Scope nat.\n\nSection CodegenLemmas.\n\nVariables (funcs : list (func_id * func))\n          (func_labels : FuncIdMap.t label)\n          (func_depths : FuncIdMap.t nat)\n          (var_rbp_offsets : VarIdMap.t offset)\n          (var_depths : VarIdMap.t nat).\n\nDefinition toplevel_accessible_var_ids_opt (func_id : func_id) : option (list var_id) :=\n  assoc func_id funcs >>= fun func =>\n  Some ((f_local_var_ids func) ++ (f_arg_var_ids func)).\n\nFixpoint toplevel_accessible_var_ids_opt_of_list (func_ids : list func_id) :\n           option (list var_id) :=\n  match func_ids with\n  | id::ids => toplevel_accessible_var_ids_opt id >>= fun func_var_ids =>\n               toplevel_accessible_var_ids_opt_of_list ids >>= fun func_var_ids' =>\n               Some (func_var_ids ++ func_var_ids')\n  | []      => Some []\n  end.\n\nDefinition accessible_var_ids_opt (func_id : func_id) : option (list var_id) :=\n  assoc func_id funcs >>= fun func =>\n  toplevel_accessible_var_ids_opt func_id >>= fun var_ids =>\n  toplevel_accessible_var_ids_opt_of_list (f_parent_func_ids func) >>= fun parent_var_ids =>\n  Some (var_ids ++ parent_var_ids).\n\nDefinition accessible_var_ids (func_id : func_id) (var_ids : list var_id) :=\n  accessible_var_ids_opt func_id = Some var_ids.\n\nDefinition parent_rbp (stack : stack) (rbp : offset) (parent_rbp : offset) : Prop :=\n  OffsetMap.find (rbp + Z.of_nat word_size)%Z stack = Some (PtrValue (StackPtr parent_rbp)).\n\nInductive ancestor_rbp (stack : stack) : nat -> offset -> offset -> Prop :=\n  | ARZero (rbp : offset) :\n      ancestor_rbp stack 0%nat rbp rbp\n  | ARSucc (depth : nat) (rbp parent_rbp' ancestor_rbp' : offset) : (* primes to avoid name clashes *)\n        parent_rbp stack rbp parent_rbp' ->\n        ancestor_rbp stack depth parent_rbp' ancestor_rbp' ->\n      ancestor_rbp stack (S depth) rbp ancestor_rbp'.\n\nDefinition asm_var_ptr (stack : stack) (rbp : offset)\n                            (var_id : var_id) (ptr : ptr_value) : Prop :=\n  exists depth ancestor_rbp' rbp_offset,\n    VarIdMap.find var_id var_depths = Some depth /\\\n    VarIdMap.find var_id var_rbp_offsets = Some rbp_offset /\\\n    ancestor_rbp stack depth rbp ancestor_rbp' /\\\n    ptr = StackPtr (ancestor_rbp' + rbp_offset)%Z.\n\nDefinition asm_accessible_var_ptrs (stack : stack) (rbp : offset) (func_id : func_id)\n                                        (var_ptrs : VarIdMap.t ptr_value) : Prop :=\n  exists var_ids, accessible_var_ids func_id var_ids /\\\n                  (forall var_id, In var_id var_ids <-> VarIdMap.In var_id var_ptrs) /\\\n                  forall var_id ptr, VarIdMap.find var_id var_ptrs = Some ptr ->\n                                     asm_var_ptr stack rbp var_id ptr.\n\nDefinition VarIdMap_combine {X Y : Type}\n                            (m : VarIdMap.t X) (m' : VarIdMap.t Y) (l : list (X * Y)) : Prop :=\n  NoDup l /\\\n  (forall id, VarIdMap.In id m <-> VarIdMap.In id m') /\\\n  (forall x y, In (x, y) l <->\n                exists id, VarIdMap.find id m = Some x /\\ VarIdMap.find id m' = Some y).\n\nDefinition states_equivalent (rbp : offset) (func_id : func_id) (c_var_ptrs : VarIdMap.t ptr_value)\n                             (c_state asm_state : memory * output) : Prop :=\n  let '(c_mem, c_out) := c_state in\n  let '((asm_stack, asm_heap) as asm_mem, asm_out) := asm_state in\n  c_out = asm_out /\\\n  exists asm_var_ptrs,\n    asm_accessible_var_ptrs asm_stack rbp func_id asm_var_ptrs /\\\n    (forall var_id, VarIdMap.In var_id c_var_ptrs <-> VarIdMap.In var_id asm_var_ptrs) /\\\n    exists corresponding_ptrs,\n      VarIdMap_combine c_var_ptrs asm_var_ptrs corresponding_ptrs /\\\n      accessible_equivalent corresponding_ptrs c_mem asm_mem.\n\n(* Definition compile_cmd' (args : compile_args) (depth : nat) (cmd : cmd)\n                        (break_lbl continue_lbl : label) (label_counter : label_counter) :\n                        option asm :=\n  let compiled := compile_cmd (ca_func_depths args) depth (ca_var_rbp_offsets args)\n                              (ca_var_depths args) break_lbl continue_lbl cmd [] label_counter in\n  match compiled with\n  | (Some asm, _) => Some asm\n  | (None, _)     => None\n  end. *)\n\nLemma compile_cmd_eq_cons_tail_asm fd d vro vd bl cl lc lc' cmd tail_asm asm_app_tail :\n  compile_cmd fd d vro vd bl cl cmd tail_asm lc = (Some asm_app_tail, lc') ->\n  exists asm,\n    asm_app_tail = asm ++ tail_asm /\\\n    compile_cmd fd d vro vd bl cl cmd [] lc = (Some asm, lc').\nProof. Admitted.\n\nLemma compile_expr_eq_cons_tail_asm fd d vro vd lc lc' cmd tail_asm asm_app_tail :\n  compile_expr fd d vro vd cmd tail_asm lc = (Some asm_app_tail, lc') ->\n  exists asm,\n    asm_app_tail = asm ++ tail_asm /\\\n    compile_expr fd d vro vd cmd [] lc = (Some asm, lc').\nProof. Admitted.\n\nDefinition cmd_compiles_to fd vro vd (depth : nat) (cmd : cmd) (asm : asm) : Prop :=\n  exists  cl bl label_counter label_counter',\n    compile_cmd fd depth vro vd bl cl cmd [] label_counter = (Some asm, label_counter').\n\nDefinition expr_compiles_to fd vro vd (depth : nat) (expr : annotated_expr) (asm : asm) : Prop :=\n  exists  label_counter label_counter',\n    compile_expr fd depth vro vd expr [] label_counter = (Some asm, label_counter').\n\n(* Definition subprogram\n    (prog : prog) (func_id : func_id) (first_instr_index last_instr_index : nat) (asm : asm) :=\n  exists func_asm, FuncIdMap.find func_id prog = Some func_asm /\\\n                   sublist asm first_instr_index last_instr_index func_asm. *)\n\nDefinition backward_simulates\n    (nb_steps : nat) (funcs : list (func_id * func)) (prog : prog) (func_id : func_id)\n    (cmd : cmd) (asm : asm) (first_instr_index last_instr_index : nat) : Prop :=\n  forall c_var_ptrs c_var_ptrs' c_state c_state' asm_state regs rbp,\n    star_count (continued_step funcs) nb_steps (c_var_ptrs, c_state, ContinuedCmd cmd KStop)\n                                               (c_var_ptrs', c_state', ContinuedCmd Skip KStop) ->\n    r_rbp regs = PtrValue (StackPtr rbp) ->\n    states_equivalent rbp func_id c_var_ptrs c_state asm_state ->\n    exists regs' asm_state' rbp',\n      r_rbp regs' = PtrValue (StackPtr rbp') /\\\n      states_equivalent rbp' func_id c_var_ptrs' c_state' asm_state' /\\\n      star (instr_step prog) (asm_state, (func_id, first_instr_index), regs)\n                             (asm_state', (func_id, last_instr_index), regs').\n\n\nDefinition backward_simulates_expr\n    (nb_steps : nat) (funcs : list (func_id * func)) (prog : prog) (func_id : func_id)\n    (expr : annotated_expr) (asm : asm) (first_instr_index last_instr_index : nat) : Prop :=\n  forall c_var_ptrs c_var_ptrs' c_state c_state' asm_state regs rbp val ty,\n    star_count (continued_step funcs) nb_steps\n                  (c_var_ptrs, c_state, ContinuedExpr expr (KExpr KStop))\n                  (c_var_ptrs', c_state', ContinuedExpr (Const val <: ty) (KExpr KStop)) ->\n    r_rbp regs = PtrValue (StackPtr rbp) ->\n    states_equivalent rbp func_id c_var_ptrs c_state asm_state ->\n    exists regs' asm_state' rbp',\n      r_rbp regs' = PtrValue (StackPtr rbp') /\\\n      r_rax regs' = val /\\\n      states_equivalent rbp' func_id c_var_ptrs' c_state' asm_state' /\\\n      star (instr_step prog) (asm_state, (func_id, first_instr_index), regs)\n                             (asm_state', (func_id, last_instr_index), regs').\n\n\nLtac destruct_compile_cmd cmd :=\n  let a := fresh \"asm\" in\n  let lc := fresh \"label_counter\" in\n  let H := fresh \"Hcompile\" in\n  destruct (compile_cmd _ _ _ _ _ _ cmd _ _) as [[a | ] lc] eqn:H; try discriminate.\n\nLtac destruct_compile_expr expr :=\n  let a := fresh \"asm\" in\n  let lc := fresh \"label_counter\" in\n  let H := fresh \"Hcompile\" in\n  destruct (compile_expr _ _ _ _ expr _ _) as [[a | ] lc] eqn:H; try discriminate.\n\nLtac elim_tail_asm cmd :=\n  match goal with\n  | [ H : compile_cmd _ _ _ _ _ _ cmd _ _ = (Some _, _) |- _ ] =>\n      let asm := fresh \"asm\" in\n      let Hasm_app := fresh \"Hasm_app\" in\n      let Hcompile := fresh \"Hcompile\" in\n      apply compile_cmd_eq_cons_tail_asm in H;\n      destruct H as [asm [Hasm_app Hcompile]];\n      clear H; subst\n  end.\n\nLtac elim_tail_asm_expr expr :=\n  match goal with\n  | [ H : compile_expr _ _ _ _ expr _ _ = (Some _, _) |- _ ] =>\n      let asm := fresh \"asm\" in\n      let Hasm_app := fresh \"Hasm_app\" in\n      let Hcompile_expr := fresh \"Hcompile\" in\n      apply compile_expr_eq_cons_tail_asm in H;\n      destruct H as [asm [Hasm_app Hcompile_expr]];\n      clear H; subst\n  end.\n\nLtac separate_first cmd cont cmd' cont' :=\n  match goal with\n  | [ Hstar_continued_step : star_count (continued_step _) _\n                                (_, _, _ cmd cont)\n                                (_, _, _ cmd' cont') |- _] =>\n    let Hstar_continued_step' := fresh \"Hstar_continued_step\" in\n    let Hstar_continued_step'' := fresh \"Hstar_continued_step\" in\n    let Hcontinued_step := fresh \"continued_step\" in\n    let Hineq := fresh \"Hineq\" in\n    let nb_steps := fresh \"nb_steps\" in\n    let nb_steps' := fresh \"nb_steps\" in\n    let x := fresh \"x\" in\n    let y := fresh \"y\" in\n    inversion Hstar_continued_step\n      as [nb_steps x | nb_steps' x y z Hcontinued_step Hstar_continued_step']; subst;\n    inversion Hcontinued_step; subst;\n    destruct (star_from_middle_of_deterministic_of_final_count\n                  (continued_step_deterministic _) (Skip_KStop_final _ _ _)\n                  (StarCountCons Hcontinued_step StarCountRefl) Hstar_continued_step)\n        as [Hineq Hstar_continued_step'']\n  end.\n\nLtac separate_last expr :=\n  match goal with\n  | [ Hstar_continued_step : star_count (continued_step _) _\n                                          (_, _, ContinuedExpr expr (KExpr KStop))\n                                          (_, _, ContinuedCmd Skip KStop) |- _ ] =>\n  let val := fresh \"val\" in let ty := fresh \"ty\" in\n  let Hstar_continued_step' := fresh \"Hstar_continued_step\" in\n  destruct (continued_step_KExpr_of_continued_step_KStop _ _ _ _ _ _ _ Hstar_continued_step)\n    as [val [ty Hstar_continued_step']]\n  end.\n\nLtac from_middle cmd cont cmd' cont' :=\n  match goal with\n  | [ Hstar_continued_step : star_count (continued_step _) _ _ (_, _, _ cmd cont),\n      Hstar_continued_step' : star_count (continued_step _) _ _ (_, _, _ cmd' cont') |- _ ] =>\n    let Hstar_continued_step'' := fresh \"Hstar_continued_step\" in\n    let Hstar_continued_step''' := fresh \"Hstar_continued_step\" in\n    let Hineq := fresh \"Hineq\" in\n    destruct (star_from_middle_of_deterministic_of_final_count\n                (continued_step_deterministic _) (Skip_KStop_final _ _ _)\n                Hstar_continued_step Hstar_continued_step')\n      as [Hineq Hstar_continued_step''']\n  end.\n\nLtac fastest_same_cont_skip_full cmd cont :=\n  match goal with\n  | [ Hstar_continued_step : star_count (continued_step _) _\n                                (_, _, ContinuedCmd cmd cont)\n                                (_, _, ContinuedCmd Skip KStop) |- _ ] =>\n    let Hstar_continued_step' := fresh \"Hstar_continued_step\" in\n    let Hstar_continued_step'' := fresh \"Hstar_continued_step\" in\n    let nb_steps := fresh \"nb_steps\" in\n    let var_ptrs := fresh \"var_ptrs\" in\n    let Hineq := fresh \"Hineq\" in\n    let H := fresh \"H\" in  \n    assert (H := Hstar_continued_step);\n    apply continued_step_KStop_and_cont_of_continued_step_Skip_KStop in H;\n    destruct H as [nb_steps [var_ptrs [state [Hineq [Hstar_continued_step' Hstarcontinued_step'']]]]];\n    from_middle Skip cont Skip KStop\n  end.\n\nLtac fastest_same_cont_skip_full_expr expr cont :=\n  match goal with\n  | [ Hstar_continued_step : star_count (continued_step _) _\n                                (_, _, ContinuedExpr expr cont)\n                                (_, _, ContinuedCmd Skip KStop) |- _ ] =>\n    let Hstar_continued_step' := fresh \"Hstar_continued_step\" in\n    let Hstar_continued_step'' := fresh \"Hstar_continued_step\" in\n    let nb_steps := fresh \"nb_steps\" in\n    let var_ptrs := fresh \"var_ptrs\" in\n    let Hineq := fresh \"Hineq\" in\n    let val := fresh \"val\" in\n    let ty := fresh \"ty\" in\n    let H := fresh \"H\" in  \n    assert (H := Hstar_continued_step);\n    apply continued_step_KStop_and_cont_of_continued_step_Expr_const_KStop in H;\n    destruct H as [nb_steps [var_ptrs [state [val [ty [Hineq [Hstar_continued_step' Hstarcontinued_step'']]]]]]];\n    from_middle (Const val <: ty) cont Skip KStop\n  end.\n\nLtac simulate_cmd IH nb_steps cmd asm_state Hrbp Hstates_equivalent Hstar_continued_step :=\n  let Hsimulation := fresh \"Hsimulation\" in\n  let regs' := fresh \"regs\" in\n  let asm_state' := fresh \"asm_state\" in\n  let rbp' := fresh \"rbp\" in\n  let Hrbp' := fresh \"Hrbp\" in\n  let Hstates_equivalent' := fresh \"Hstates_equivalent\" in\n  let Hstar_instr_step' := fresh \"Hstar_instr_step\" in\n  eassert (Hsimulation : backward_simulates nb_steps _ _ _ cmd _ _ _);\n  try ( eapply IH; try (eexists; repeat eexists; eassumption); try eassumption; try lia;\n        (eapply sublist_of_app_sublist_left; eassumption) ||\n        (eapply sublist_of_app_sublist_right; eassumption) );\n  destruct (Hsimulation _ _ _ _ asm_state _ _ Hstar_continued_step Hrbp Hstates_equivalent)\n    as [regs' [asm_state' [rbp' [Hrbp' [Hstates_equivalent' Hstar_instr_step']]]]].\n\nLtac simulate_cmd' IH nb_steps cmd asm_state Hrbp Hstates_equivalent Hstar_continued_step :=\n  let Hsimulation := fresh \"Hsimulation\" in\n  let regs' := fresh \"regs\" in\n  let asm_state' := fresh \"asm_state\" in\n  let rbp' := fresh \"rbp\" in\n  let Hrbp' := fresh \"Hrbp\" in\n  let Hstates_equivalent' := fresh \"Hstates_equivalent\" in\n  let Hstar_instr_step' := fresh \"Hstar_instr_step\" in\n  eassert (Hsimulation : backward_simulates nb_steps _ _ _ cmd _ _ _) (* ;\n  try ( eapply IH; try (eexists; repeat eexists; eassumption); try eassumption; try lia;\n        (eapply sublist_of_app_sublist_left; eassumption) ||\n        (eapply sublist_of_app_sublist_right; eassumption) );\n  destruct (Hsimulation _ _ _ _ asm_state _ _ Hstar_continued_step Hrbp Hstates_equivalent)\n    as [regs' [asm_state' [rbp' [Hrbp' [Hstates_equivalent' Hstar_instr_step']]]]]. *).\n\nLtac simulate_expr IH nb_steps expr asm_state Hrbp Hstates_equivalent Hstar_continued_step :=\n  let Hsimulation := fresh \"Hsimulation\" in\n  let regs' := fresh \"regs\" in\n  let asm_state' := fresh \"asm_state\" in\n  let rbp' := fresh \"rbp\" in\n  let Hrbp' := fresh \"Hrbp\" in\n  let Hrax' := fresh \"Hrax\" in\n  let Hstates_equivalent' := fresh \"Hstates_equivalent\" in\n  let Hstar_instr_step' := fresh \"Hstar_instr_step\" in\n  eassert (Hsimulation : backward_simulates_expr nb_steps _ _ _ expr _ _ _);\n  try ( eapply IH; try (eexists; repeat eexists; eassumption); try eassumption; try lia;\n        (eapply sublist_of_app_sublist_left; eassumption) ||\n        (eapply sublist_of_app_sublist_right; eassumption) );\n  destruct (Hsimulation _ _ _ _ asm_state _ _ _ _  Hstar_continued_step Hrbp Hstates_equivalent)\n    as [regs' [asm_state' [rbp' [Hrbp' [Hrax' [Hstates_equivalent' Hstar_instr_step']]]]]].\n\nTheorem backward_simulation_aux nb_steps :\n  ( forall funcs prog func_id func func_asm fd vro vd cmd cmd_asm first_instr_index last_instr_index,\n      compile_file funcs = Some prog ->\n      In (func_id, func) funcs ->\n      FuncIdMap.find func_id prog = Some func_asm ->\n      cmd_compiles_to fd vro vd (depth func) cmd cmd_asm ->\n      sublist cmd_asm first_instr_index last_instr_index func_asm ->\n      backward_simulates nb_steps funcs prog func_id cmd\n                         cmd_asm first_instr_index last_instr_index ) /\\\n  ( forall funcs prog func_id func func_asm fd vro vd expr expr_asm first_instr_index last_instr_index,\n      compile_file funcs = Some prog ->\n      In (func_id, func) funcs ->\n      FuncIdMap.find func_id prog = Some func_asm ->\n      expr_compiles_to fd vro vd (depth func) expr expr_asm ->\n      backward_simulates_expr nb_steps funcs prog func_id expr\n                              expr_asm first_instr_index last_instr_index ).\nProof.\n  induction (lt_wf nb_steps) as [n _ IH].\n\n  assert (IHCmd := fun nb_steps Hnb_steps => proj1 (IH nb_steps Hnb_steps)).\n  assert (IHExpr := fun nb_steps Hnb_steps => proj2 (IH nb_steps Hnb_steps)).\n  clear IH.\n\n  split.\n\n  - (* Case : show that commands are compiled correctly *)\n    intros funcs0 prog func_id func func_asm fd vro vd cmd cmd_asm first_instr_index last_instr_index\n          Hcompile_file Hfunc_In Hfunc_asm [bl [cl [lc [lc' Hcompile]]]] Hsublist\n          c_var_ptrs c_var_ptrs' c_state c_state' asm_state regs rbp\n          Hstar_continued_step Hrbp Hstates_equivalent.\n\n    destruct cmd as [ | cmd1 cmd2 | expr | cond_expr then_cmd else_cmd | | | | | ];\n    simpl in Hcompile.\n\n    + (* Case : cmd = Skip *)\n      injection Hcompile as Hcompile. subst.\n      inv Hstar_continued_step.\n\n      * (* Zero C small steps. *)\n        (* Since there are zero c steps, we can show that the c states before and after are equal\n            and that the o compiled command is Skip.\n          Then, by executing no instructions the assembly program transitions to the same state\n            in zero steps. *)\n        exists regs. exists asm_state. exists rbp.\n        repeat split; try assumption.\n        apply nil_sublist in Hsublist. subst.\n        apply StarRefl.\n\n      * (* At least one C small step. *)\n        (* This is impossible: no step can be made from [ContinuedInstr Skip KStop] *)\n        inv H.\n\n    + (* Case: cmd = Seq cmd1 cmd2 *)\n      destruct_compile_cmd cmd2. destruct_compile_cmd cmd1.\n      injection Hcompile. intros. subst.\n      elim_tail_asm cmd1.\n\n      separate_first (Seq cmd1 cmd2) KStop Skip KStop.\n      fastest_same_cont_skip_full cmd1 (KSeq cmd2 KStop).\n      separate_first Skip (KSeq cmd2 KStop) Skip KStop.\n\n      simulate_cmd IHCmd nb_steps cmd1 asm_state Hrbp Hstates_equivalent Hstar_continued_step2.\n      simulate_cmd IHCmd (S nb_steps0-1-nb_steps-1) cmd2 asm_state0 Hrbp0 Hstates_equivalent0\n                     Hstar_continued_step5.\n      \n      exists regs1. exists asm_state1. exists rbp1.\n      repeat split; try assumption.\n      eapply star_trans; eassumption.\n\n    + (* Case : cmd = Expr expr *)\n      separate_first (Expr expr) KStop Skip KStop.\n      separate_last expr.\n\n      simulate_expr IHExpr (S nb_steps0-1-1) expr asm_state Hrbp Hstates_equivalent Hstar_continued_step2.\n      exists regs0. exists asm_state0. exists rbp0.\n      repeat split; eassumption.\n\n    + (* Case : cmd = If cond_expr then_cmd else_cmd *)\n      destruct_compile_cmd else_cmd. destruct_compile_cmd then_cmd.\n      destruct_compile_expr cond_expr.\n      elim_tail_asm_expr cond_expr. elim_tail_asm then_cmd. elim_tail_asm else_cmd.\n      injection Hcompile. intros. subst.\n\n      separate_first (If cond_expr then_cmd else_cmd) KStop Skip KStop.\n      fastest_same_cont_skip_full_expr cond_expr (KIf then_cmd else_cmd KStop).\n      separate_first (Const val <: ty) (KIf then_cmd else_cmd KStop) Skip KStop;\n      try (inv H6; discriminate);\n      try (inv continued_step0; inv H2; try discriminate; inv H10; discriminate).\n      \n      eassert (Hsublist1 : sublist asm1 (2 + first_instr_index + length asm2)\n                                   (2 + first_instr_index + length asm2 + length asm1) func_asm).\n      { admit. (* This is just a tideous manipulation on lists *) }\n\n      simulate_expr IHExpr nb_steps cond_expr asm_state Hrbp Hstates_equivalent Hstar_continued_step2.\n\n      destruct bool.\n      * (* The condition is true, the then branch is executed *)\nAbort.\n \n(* Theorem backward_simulation_aux nb_steps :\n  forall funcs prog func_id func func_asm fd vro vd cmd cmd_asm first_instr_index last_instr_index,\n    compile_file funcs = Some prog ->\n    In (func_id, func) funcs ->\n    FuncIdMap.find func_id prog = Some func_asm ->\n    cmd_compiles_to fd vro vd (depth func) cmd cmd_asm ->\n    sublist cmd_asm first_instr_index last_instr_index func_asm ->\n    backward_simulates nb_steps funcs prog func_id cmd cmd_asm first_instr_index last_instr_index.\nProof.\n  induction (lt_wf nb_steps) as [n _ IH].\n\n  intros funcs0 prog func_id func func_asm fd vro vd cmd cmd_asm first_instr_index last_instr_index\n         Hcompile_file Hfunc_In Hfunc_asm [bl [cl [lc [lc' Hcompile]]]] Hsublist\n         c_var_ptrs c_var_ptrs' c_state c_state' asm_state regs rbp\n         Hstar_continued_step Hrbp Hstates_equivalent.\n\n  destruct cmd;\n  simpl in Hcompile.\n\n  - (* Case : cmd = Skip *)\n    injection Hcompile as Hcompile. subst.\n\n    inv Hstar_continued_step.\n\n  + (* Zero C small steps. *)\n    (* Since there are zero c steps, we can show that the c states before and after are equal\n         and that the o compiled command is Skip.\n       Then, by executing no instructions the assembly program transitions to the same state\n         in zero steps. *)\n    exists regs. exists asm_state. exists rbp.\n    repeat split; try assumption.\n    apply nil_sublist in Hsublist. subst.\n    apply StarRefl.\n\n  + (* At least one C small step. *)\n    (* This is impossible: no step can be made from [ContinuedInstr Skip KStop] *)\n    inv H.\n\n\n  - (* Case: cmd = Seq cmd1 cmd2 *)\n    destruct_compile_cmd cmd2. destruct_compile_cmd cmd1.\n    injection Hcompile. intros. subst.\n    elim_tail_asm cmd1.\n\n    inversion Hstar_continued_step; subst. (* necessarily at least one step *)\n    inversion H. subst.\n    destruct (star_from_middle_of_deterministic_of_final_count\n                  (continued_step_deterministic _) (Skip_KStop_final _ _ _)\n                  (StarCountCons H StarCountRefl) Hstar_continued_step)\n        as [Hineq Hstar_continued_step'].\n\n    apply continued_step_same_continuation_of_continued_step_SKip_KStop in Hstar_continued_step'.\n    destruct Hstar_continued_step' as [n' [var_ptrs'' [state'' [Hineq' Hstar_continued_step']]]].\n    apply continued_step_KStop_of_continued_step_Skip_same_cont in Hstar_continued_step'.\n    destruct Hstar_continued_step' as [n'' [var_ptrs''' [state''' [Hineq'' Hstar_continued_step'']]]].\n\n    (* we state and show by induction hypothesis that the compiled cmd1 is emulated correctly *)\n    assert (Hemulation_cmd1 : exists regs' asm_state' rbp',\n      r_rbp regs' = PtrValue (StackPtr rbp') /\\\n      states_equivalent rbp' func_id var_ptrs''' state''' asm_state' /\\\n      star (instr_step prog)\n        (asm_state, (func_id, first_instr_index), regs)\n        (asm_state', (func_id, first_instr_index + length asm0), regs')).\n    { eapply IH with (cmd := cmd1) (c_var_ptrs' := var_ptrs''') (y := n''); try eassumption.\n      + lia.\n      + econstructor; repeat eexists. eassumption.\n      + eapply sublist_of_app_sublist_left; eassumption. }\n\n    destruct Hemulation_cmd1 as\n      [regs1 [asm_state1 [rbp1 [Hrbp1 [Hstates_equivalent1 Hstar_instr_step1]]]]].\n    \n    assert (Hstar_continued_step''' := H0).\n    apply continued_step_same_continuation_of_continued_step_SKip_KStop in H0.\n    destruct H0 as [nb_steps0 [var_ptrs' [state0 [Hineq0 Hstar_continued_step0]]]].\n    assert (Hcontinued_step0 : star_count (continued_step funcs0) (S nb_steps0)\n                                (c_var_ptrs, c_state, ContinuedCmd cmd1 (KSeq cmd2 KStop))\n                                (var_ptrs', c_state, ContinuedCmd cmd2 (KStop))).\n   {  assert (Harith : S nb_steps0 = nb_steps0 + 1). { lia. }\n      rewrite Harith.\n      eapply star_count_trans.\n     + eassumption. \n     + repeat econstructor. }\n    \n\n  assert (h := star_from_middle_of_deterministic_of_final_count\n    (continued_step_deterministic _) (Skip_KStop_final _ _ _) .......).\n    \n  \n\nTheorem backward_simulation_aux nb_steps :\n  forall fd vro vd funcs prog func_id func func_asm cmd cmd_asm first_instr_index last_instr_index\n         c_state c_state' c_var_ptrs c_var_ptrs' asm_state regs rbp,\n    compile_file funcs = Some prog ->\n    In (func_id, func) funcs ->\n    compile_func fd (depth func) vro vd (f_body func) = Some func_asm ->\n    cmd_compiles_to fd vro vd (depth func) cmd cmd_asm ->\n    sublist cmd_asm first_instr_index last_instr_index func_asm ->\n    r_rbp regs = PtrValue (StackPtr rbp) ->\n    states_equivalent rbp func_id c_var_ptrs c_state asm_state ->\n    star_count (continued_step funcs) nb_steps (c_var_ptrs, c_state, ContinuedCmd cmd KStop)\n                                               (c_var_ptrs', c_state', ContinuedCmd Skip KStop) ->\n    exists regs' asm_state' rbp',\n      r_rbp regs' = PtrValue (StackPtr rbp') /\\\n      states_equivalent rbp' func_id c_var_ptrs' c_state' asm_state' /\\\n      star (instr_step prog) (asm_state, (func_id, first_instr_index), regs)\n                             (asm_state', (func_id, last_instr_index), regs').\n\nProof.\n\n  induction (lt_wf nb_steps) as [n _ IH].\n\n  intros fd vro vd funcs0 prog func_id func func_asm cmd cmd_asm first_instr_index last_instr_index\n         c_state c_state' c_var_ptrs c_var_ptrs' asm_state regs rbp\n         Hcompile_file Hcompile_func Hfunc_In Hcompile Hsublist Hrbp Hstates_equivalent\n         Hstar_continued_step.\n  \n  destruct cmd;\n\n  (* simplify Hcompile *)\n  inv Hcompile; inv H; inv H0; inv H; simpl in H0; rename H0 into Hcompile;\n  rename x into break_lbl; rename x0 into continue_lbl;\n  rename x1 into label_counter; rename x2 into label_counter'.\n\n  - (* Case : cmd = Skip *)\n\n    injection Hcompile as Hcompile. subst.\n\n    inv Hstar_continued_step.\n\n    + (* Zero C small steps. *)\n      (* Since there are zero c steps, we can show that the c states before and after are equal\n           and that the o compiled command is Skip.\n         Then, by executing no instructions the assembly program transitions to the same state\n           in zero steps. *)\n      exists regs. exists asm_state. exists rbp.\n      repeat split; try assumption.\n      apply nil_sublist in Hsublist. subst.\n      apply StarRefl.\n\n    + (* At least one C small step. *)\n      (* This is impossible: no step can be made from [ContinuedInstr Skip KStop] *)\n      inv H.\n\n  - (* Case: cmd = Seq cmd1 cmd2 *)\n\n    destruct_compile_cmd cmd2. destruct_compile_cmd cmd1.\n    injection Hcompile. intros. subst.\n    elim_tail_asm cmd1.\n\n    inversion Hstar_continued_step; subst. (* necessarily at least one step *)\n    inversion H. subst.\n    destruct (star_from_middle_of_deterministic_of_final_count\n                  (continued_step_deterministic _) (Skip_KStop_final _ _ _)\n                  (StarCountCons H StarCountRefl) Hstar_continued_step)\n        as [Hineq Hstar_continued_step'].\n\n    apply continued_step_same_continuation_of_continued_step_SKip_KStop in Hstar_continued_step'.\n    destruct Hstar_continued_step' as [n' [var_ptrs'' [state'' [Hineq' Hstar_continued_step']]]].\n    apply continued_step_KStop_of_continued_step_Skip_same_cont in Hstar_continued_step'.\n    destruct Hstar_continued_step' as [n'' [var_ptrs''' [state''' [Hineq'' Hstar_continued_step'']]]].\n\n    (* we state and show by induction hypothesis that the compiled cmd1 is emulated correctly *)\n    assert (Hemulation_cmd1 : exists regs' asm_state' rbp',\n      r_rbp regs' = PtrValue (StackPtr rbp') /\\\n      states_equivalent rbp' func_id var_ptrs''' state''' asm_state' /\\\n      star (instr_step prog)\n        (asm_state, (func_id, first_instr_index), regs)\n        (asm_state', (func_id, first_instr_index + length asm0), regs')).\n    { eapply IH with (cmd := cmd1) (c_var_ptrs' := var_ptrs''') (y := n''); try eassumption.\n      + lia.\n      + econstructor; repeat eexists. eassumption.\n      + eapply sublist_of_app_sublist_left; eassumption. }\n\n    destruct Hemulation_cmd1 as\n      [regs1 [asm_state1 [rbp1 [Hrbp1 [Hstates_equivalent1 Hstar_instr_step1]]]]].\n\nQed.\n    *)\n\nEnd CodegenLemmas.", "meta": {"author": "astOwOlfo", "repo": "PetitC", "sha": "449bc594f698eaf476faac0943e65fb34e36a63f", "save_path": "github-repos/coq/astOwOlfo-PetitC", "path": "github-repos/coq/astOwOlfo-PetitC/PetitC-449bc594f698eaf476faac0943e65fb34e36a63f/CodegenLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.18797623652047382}}
{"text": "Require Import Framework File FileDiskLayer FileDiskNoninterference FileDiskRefinement.\nRequire Import FunctionalExtensionality Lia Language SameRetType.\nRequire Import TSCommon InodeTS TSAuthThenExec.\n\n\nOpaque Inode.get_inode DiskAllocator.alloc Inode.extend.\nLemma TS_extend_inner:\nforall o fm1 fm2 s1 s2 inum v v' ret1 u u' ex,\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 (extend_inner v inum) ret1 ->\nexists ret2, \nexec (TransactionalDiskLayer.TDLang FSParameters.data_length) u o s2 (extend_inner v' inum) ret2 /\\\n(extract_ret ret1 = None <-> extract_ret ret2 = None).\nProof.\nTransparent extend_inner.  \nunfold extend_inner; intros.\ninvert_step.\n{\n  eapply_fresh TS_alloc in H2; eauto.\n  cleanup.\n  destruct x2; simpl in *; try solve [intuition congruence]. \n  \n  eapply_fresh DiskAllocator.alloc_finished_oracle_eq in H2; eauto.\n  cleanup; destruct o; try solve [intuition congruence].\n  unfold refines, files_rep, files_inner_rep in *; cleanup.\n  eapply DiskAllocator.alloc_finished in H2; eauto.\n  cleanup; split_ors; cleanup.\n  eapply_fresh DiskAllocator.alloc_finished in H4; eauto.\n  cleanup; split_ors; cleanup.\n  \n  eapply_fresh TS_extend in H3; eauto.\n  cleanup.\n  destruct x8; simpl in *; try solve [intuition congruence].\n  eapply Inode.extend_finished_oracle_eq in H3; eauto; cleanup.\n\n  eexists; split.\n  econstructor.\n  simpl; eapply H4.\n  simpl; eauto.\n  simpl; intuition congruence.   \n\n  {\n    repeat cleanup_pairs; simpl in *.\n    unfold files_inner_rep; eexists; intuition eauto.\n\n    unfold Inode.inode_rep in *; cleanup.\n    eexists; split.\n    eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq with (s1:= t3); eauto.\n    intros; repeat solve_bounds.\n    eauto.\n    eexists; intuition eauto.\n    {\n      unfold file_map_rep in *; cleanup.\n      intuition eauto.\n      eapply H19 in H20; eauto.\n      unfold file_rep in *; cleanup.\n      intuition eauto.\n      eapply H23 in H24; cleanup.\n      eexists; intuition eauto.\n      rewrite Mem.upd_ne; eauto.\n      intros Hnot; subst; congruence.\n    }\n  }\n  {\n    repeat cleanup_pairs; simpl in *.\n    unfold files_inner_rep; eexists; intuition eauto.\n\n    unfold Inode.inode_rep in *; cleanup.\n    eexists; split.\n    eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; repeat solve_bounds.\n    eauto.\n    eexists; intuition eauto.\n    {\n      unfold file_map_rep in *; cleanup.\n      intuition eauto.\n      eapply H17 in H20; eauto.\n      unfold file_rep in *; cleanup.\n      intuition eauto.\n      eapply H23 in H24; cleanup.\n      eexists; intuition eauto.\n      rewrite Mem.upd_ne; eauto.\n      intros Hnot; subst; congruence.\n    }\n  }\n}\n{\n  eapply_fresh TS_alloc in H2; eauto.\n  cleanup.\n  destruct x0; simpl in *; try solve [intuition congruence]. \n  \n  eapply_fresh DiskAllocator.alloc_finished_oracle_eq in H2; eauto.\n  cleanup; destruct o; try solve [intuition congruence].\n\n  eexists; split.\n  econstructor.\n  simpl; eapply H3.\n  simpl; eauto.\n  repeat econstructor.\n  simpl; intuition congruence.   \n}\n{\n  repeat invert_step_crash.\n  {\n    eapply_fresh TS_alloc in H2; eauto.\n    cleanup.\n    destruct x; simpl in *; try solve [intuition congruence]. \n  \n    exists (Crashed s0); split.\n    repeat exec_step.\n    eapply ExecBindCrash; eauto.\n    simpl; intuition eauto.\n  }\n  {\n    eapply_fresh TS_alloc in H3; eauto.\n    logic_clean.\n    destruct x3; simpl in *; try solve [intuition congruence]. \n    \n    eapply_fresh DiskAllocator.alloc_finished_oracle_eq in H3; eauto.\n    logic_clean.\n    unfold refines, files_rep, files_inner_rep in *; logic_clean.\n    eapply DiskAllocator.alloc_finished in H3; eauto.\n    eapply_fresh DiskAllocator.alloc_finished in H2; eauto.\n    cleanup; repeat split_ors; cleanup; try solve [intuition congruence].\n    {\n      eapply_fresh TS_extend in H4; eauto.\n      cleanup.\n      destruct x8; simpl in *; try solve [intuition congruence].\n      exists (Crashed s3); split.\n      econstructor; simpl; eauto.\n      simpl; eauto.\n      simpl; intuition eauto.\n      {\n    repeat cleanup_pairs; simpl in *.\n    unfold files_inner_rep; eexists; intuition eauto.\n\n    unfold Inode.inode_rep in *; cleanup.\n    eexists; split.\n    eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq with (s1:= t3); eauto.\n    intros; repeat solve_bounds.\n    eauto.\n    eexists; intuition eauto.\n    {\n      unfold file_map_rep in *; cleanup.\n      intuition eauto.\n      eapply H19 in H20; eauto.\n      unfold file_rep in *; cleanup.\n      intuition eauto.\n      eapply H23 in H24; cleanup.\n      eexists; intuition eauto.\n      rewrite Mem.upd_ne; eauto.\n      intros Hnot; subst; congruence.\n    }\n  }\n  {\n    repeat cleanup_pairs; simpl in *.\n    unfold files_inner_rep; eexists; intuition eauto.\n\n    unfold Inode.inode_rep in *; cleanup.\n    eexists; split.\n    eapply Inode.InodeAllocator.block_allocator_rep_inbounds_eq; eauto.\n    intros; repeat solve_bounds.\n    eauto.\n    eexists; intuition eauto.\n    {\n      unfold file_map_rep in *; cleanup.\n      intuition eauto.\n      eapply H10 in H20; eauto.\n      unfold file_rep in *; cleanup.\n      intuition eauto.\n      eapply H23 in H24; cleanup.\n      eexists; intuition eauto.\n      rewrite Mem.upd_ne; eauto.\n      intros Hnot; subst; congruence.\n    }\n  }\n  }\n  {\n      invert_step; eexists; split.\n      repeat exec_step.\n      simpl; intuition congruence.\n  } \n}\n}\nUnshelve.\nall: eauto.\nQed.\nOpaque extend_inner.\n\n\nTheorem Termination_Sensitive_extend:\n  forall u u' m inum v1 ex,\n    Termination_Sensitive\n      u (extend inum v1) (extend inum v1) recover\n      AD_valid_state (AD_related_states u' ex)\n      (authenticated_disk_reboot_list m).\nProof.\n  Opaque extend_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  extend;\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_extend_inner in H7; eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.extend_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  }\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.extend_crashed in H14; eauto.\n    eapply_fresh FileSpecs.extend_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 extend_crashed_exfalso; eauto.\n   }\n   {\n     exfalso; eapply extend_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.upd_eq; eauto; intuition congruence\n         |repeat rewrite Mem.upd_ne; eauto; intuition congruence].\n         split; intros.\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.upd_eq in H5, H16; eauto; cleanup\n         |rewrite Mem.upd_ne in H5, H16; eauto; cleanup].\n         unfold extend_file in *; simpl in *.\n         eapply e in H19; eauto.\n         subst; eauto.\n         }\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.upd_eq in H5, H4; eauto; cleanup\n         |rewrite Mem.upd_ne in H5, H4; eauto; cleanup].\n         unfold extend_file in *; simpl in *.\n         eapply a0 in H7; eauto.\n         cleanup; intuition eauto.\n         repeat rewrite app_length; lia.\n         }\n       }\n     }\n   }\n  }\n  {\n     intros.\n     eapply_fresh TS_extend_inner in H7; eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.extend_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\n\nTheorem Termination_Sensitive_extend_input:\n  forall u u' m inum v1 v2,\n    Termination_Sensitive\n      u (extend inum v1) (extend inum v2) recover\n      AD_valid_state (AD_related_states u' (Some inum))\n      (authenticated_disk_reboot_list m).\nProof.\n  Opaque extend_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  extend;\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_extend_inner in H7; eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.extend_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  }\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.extend_crashed in H14; eauto.\n    eapply_fresh FileSpecs.extend_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:= Some inum).\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 extend_crashed_exfalso; eauto.\n   }\n   {\n     exfalso; eapply extend_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:= Some inum).\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.upd_eq; eauto; intuition congruence\n         |repeat rewrite Mem.upd_ne; eauto; intuition congruence].\n         split; intros.\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.upd_eq in H5, H16; eauto; cleanup\n         |rewrite Mem.upd_ne in H5, H16; eauto; cleanup].\n         intuition.\n         }\n         {\n          destruct (addr_dec inum0 inum);\n          [rewrite Mem.upd_eq in H5, H4; eauto; cleanup\n         |rewrite Mem.upd_ne in H5, H4; eauto; cleanup].\n         unfold extend_file in *; simpl in *.\n         eapply a0 in H7; eauto.\n         cleanup; intuition eauto.\n         repeat rewrite app_length; simpl; lia.\n         }\n       }\n     }\n   }\n  }\n  {\n     intros.\n     eapply_fresh TS_extend_inner in H7; eauto.\n     cleanup.\n     destruct ret1, x1; simpl in * ; try solve [intuition congruence].\n     {\n      eapply SameRetType.extend_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.", "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/TSExtend.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1879762214545204}}
{"text": "Require Import AutoSep Malloc.\n\n\nSection adt.\n  Variable P : 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 c,\n    PRE[V] P c (V \"self\") * mallocHeap 0\n    POST[_] mallocHeap 0.\n\n  Definition readS := SPEC(\"extra_stack\", \"self\") reserving res\n    Al c,\n    PRE[V] P c (V \"self\") * mallocHeap 0\n    POST[R] [| R = c |] * P c (V \"self\") * mallocHeap 0.\n\n  Definition writeS := SPEC(\"extra_stack\", \"self\", \"n\") reserving res\n    Al c,\n    PRE[V] P c (V \"self\") * mallocHeap 0\n    POST[_] P (V \"n\") (V \"self\") * mallocHeap 0.\nEnd adt.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/examples/Cell.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.18791387791938358}}
{"text": "From RecordUpdate Require Import RecordSet.\nFrom Perennial.Helpers Require Import ipm Map.\n\nFrom Goose.github_com.mit_pdos.perennial_examples Require Import async_mem_alloc_dir.\nFrom Perennial.program_proof Require Import async_disk_lib.\nFrom Perennial.program_proof Require Import async_disk_prelude.\nFrom Perennial.goose_lang.lib Require Import slice.crash_slice.\nFrom Perennial.program_proof.examples Require Import\n     alloc_addrset alloc_crash_proof async_mem_alloc_inode_proof.\nFrom Perennial.goose_lang.lib Require Import typed_slice. (* shadows things, should be last *)\n\nModule dir.\n  Record t :=\n    mk { inodes: gmap nat (list Block); }.\n  Global Instance _eta : Settable t := settable! mk <inodes>.\n  Global Instance _witness : Inhabited t := populate!.\nEnd dir.\n\n(* FIXME: port to [auth_map]; then these instances likely also can disappear. *)\nCanonical Structure listLO A := leibnizO (list A).\nCanonical Structure gset64O := leibnizO (gset u64).\n\nLocal Definition blocksR := authR $ gmapUR nat (exclR $ listLO Block).\nLocal Definition allocsR := authR $ gmapUR nat (exclR $ gset64O).\n\nSection goose.\n  Context `{!heapGS \u03a3}.\n  Context `{!allocG \u03a3}.\n  Context `{!stagedG \u03a3}.\n  Context `{!inG \u03a3 blocksR}.\n  Context `{!inG \u03a3 allocsR}.\n\n  (* The client picks our namespace *)\n  Context (N: namespace).\n  (* We use parts of it ourselves and assign the rest to sub-libraries. *)\n  Let dirN := N.@\"dir\".\n  Let allocN := N.@\"allocator\".\n  Let inodeN := N.@\"inode\".\n\n  Definition num_inodes: nat := 5.\n  Hint Unfold num_inodes : word.\n\n  Context (P: dir.t \u2192 iProp \u03a3).\n  Implicit Types (dir \u03c3: dir.t).\n\n  (** Per-inode statements and lemmas about them. *)\n  Local Definition inode_blocks \u03b3blocks (idx: nat) (blocks: list Block): iProp \u03a3 :=\n    own \u03b3blocks (\u25ef {[ idx := Excl blocks ]}: blocksR).\n  Local Definition inode_allblocks \u03b3blocks (allblocks: gmap nat (list Block)): iProp \u03a3 :=\n    own \u03b3blocks (\u25cf (Excl <$> allblocks): blocksR).\n  Local Definition inode_used \u03b3used (idx: nat) (used: gset u64): iProp \u03a3 :=\n    own \u03b3used (\u25ef {[ idx := Excl used ]}: allocsR).\n  Local Definition inode_allused \u03b3used (allused: gmap nat (gset u64)): iProp \u03a3 :=\n    own \u03b3used (\u25cf (Excl <$> allused): allocsR).\n\n  (* Twice the same proofs... really this should be abstracted, ideally into Iris. *)\n  Lemma inode_blocks_lookup \u03b3blocks (idx: nat) (blocks: list Block) (allblocks: gmap nat (list Block)):\n    inode_blocks \u03b3blocks idx blocks -\u2217\n    inode_allblocks \u03b3blocks allblocks -\u2217\n    \u231callblocks !! idx = Some blocks\u231d.\n  Proof.\n    iIntros \"Hblocks Hallblocks\".\n    iDestruct (own_valid_2 with \"Hallblocks Hblocks\") as\n        %[Hincl _]%auth_both_valid_discrete.\n    iPureIntro.\n    move: Hincl. rewrite singleton_included_l=> -[oblocks []].\n    rewrite lookup_fmap fmap_Some_equiv=> -[blocks' [-> ->]].\n    rewrite Excl_included leibniz_equiv_iff => -> //.\n  Qed.\n\n  Lemma inode_blocks_update {\u03b3blocks E} {idx: nat} (blocks1 blocks2: list Block) (allblocks: gmap nat (list Block)):\n    inode_blocks \u03b3blocks idx blocks1 -\u2217\n    inode_allblocks \u03b3blocks allblocks ={E}=\u2217\n    inode_blocks \u03b3blocks idx blocks2 \u2217 inode_allblocks \u03b3blocks (<[ idx := blocks2 ]> allblocks).\n  Proof.\n    iIntros \"Hblocks Hallblocks\".\n    iDestruct (inode_blocks_lookup with \"Hblocks Hallblocks\") as %Hallblocks.\n    iMod (own_update_2 with \"Hallblocks Hblocks\") as \"[Hallblocks $]\".\n    { apply: auth_update. apply: singleton_local_update.\n      { by rewrite lookup_fmap Hallblocks. }\n      apply: exclusive_local_update. done. }\n    rewrite -fmap_insert. done.\n  Qed.\n\n  Lemma inode_blocks_alloc E (allblocks: gmap nat (list Block)):\n    \u22a2 |={E}=> \u2203 \u03b3blocks, ([\u2217 map] idx \u21a6 blocks \u2208 allblocks, inode_blocks \u03b3blocks idx blocks) \u2217 inode_allblocks \u03b3blocks allblocks.\n  Proof.\n    set allblocksR: gmapUR nat (exclR $ listLO Block) := Excl <$> allblocks.\n    iMod (own_alloc (\u25cf allblocksR \u22c5 \u25ef allblocksR)) as (\u03b3) \"[Ha Hf]\".\n    { rewrite auth_both_valid_discrete. split; first done.\n      intros i. rewrite /allblocksR lookup_fmap. by destruct (allblocks !! i). }\n    iModIntro. iExists \u03b3. iFrame \"Ha\".\n    iInduction allblocks as [|i x m Hnew] \"IH\" using map_ind.\n    { rewrite big_sepM_empty. done. }\n    rewrite big_sepM_insert // /allblocksR fmap_insert.\n    rewrite (insert_singleton_op (Excl <$> m) i (Excl x: exclR $ listLO Block)); last first.\n    { rewrite lookup_fmap Hnew. done. }\n    rewrite auth_frag_op. iDestruct \"Hf\" as \"[$ Hf]\".\n    iApply \"IH\". done.\n  Qed.\n\n  Lemma inode_used_lookup \u03b3used (idx: nat) (used: gset u64) (allused: gmap nat (gset u64)):\n    inode_used \u03b3used idx used -\u2217\n    inode_allused \u03b3used allused -\u2217\n    \u231callused !! idx = Some used\u231d.\n  Proof.\n    iIntros \"Hused Hallused\".\n    iDestruct (own_valid_2 with \"Hallused Hused\") as\n        %[Hincl _]%auth_both_valid_discrete.\n    iPureIntro.\n    move: Hincl. rewrite singleton_included_l=> -[oused []].\n    rewrite lookup_fmap fmap_Some_equiv=> -[used' [-> ->]].\n    rewrite Excl_included leibniz_equiv_iff => -> //.\n  Qed.\n\n  Lemma inode_used_update {\u03b3used E} {idx: nat} (used1 used2: gset u64) (allused: gmap nat (gset u64)):\n    inode_used \u03b3used idx used1 -\u2217\n    inode_allused \u03b3used allused ={E}=\u2217\n    inode_used \u03b3used idx used2 \u2217 inode_allused \u03b3used (<[ idx := used2 ]> allused).\n  Proof.\n    iIntros \"Hused Hallused\".\n    iDestruct (inode_used_lookup with \"Hused Hallused\") as %Hallused.\n    iMod (own_update_2 with \"Hallused Hused\") as \"[Hallused $]\".\n    { apply: auth_update. apply: singleton_local_update.\n      { by rewrite lookup_fmap Hallused. }\n      apply: exclusive_local_update. done. }\n    rewrite -fmap_insert. done.\n  Qed.\n\n  Lemma inode_used_alloc E (allused: gmap nat (gset u64)):\n    \u22a2 |={E}=> \u2203 \u03b3used, ([\u2217 map] idx \u21a6 used \u2208 allused, inode_used \u03b3used idx used) \u2217 inode_allused \u03b3used allused.\n  Proof.\n    set allusedR: gmapUR nat (exclR $ gset64O) := Excl <$> allused.\n    iMod (own_alloc (\u25cf allusedR \u22c5 \u25ef allusedR)) as (\u03b3) \"[Ha Hf]\".\n    { rewrite auth_both_valid_discrete. split; first done.\n      intros i. rewrite /allusedR lookup_fmap. by destruct (allused !! i). }\n    iModIntro. iExists \u03b3. iFrame \"Ha\".\n    iInduction allused as [|i x m Hnew] \"IH\" using map_ind.\n    { rewrite big_sepM_empty. done. }\n    rewrite big_sepM_insert // /allusedR fmap_insert.\n    rewrite (insert_singleton_op (Excl <$> m) i (Excl x: exclR $ gset64O)); last first.\n    { rewrite lookup_fmap Hnew. done. }\n    rewrite auth_frag_op. iDestruct \"Hf\" as \"[$ Hf]\".\n    iApply \"IH\". done.\n  Qed.\n\n  (** Protocol invariant for inode library *)\n  Local Definition Pinode \u03b3blocks \u03b3used (ino: nat) (s: inode.t): iProp \u03a3 :=\n    \"Hownblocks\" \u2237 inode_blocks \u03b3blocks ino s.(inode.blocks) \u2217\n    \"Hused1\" \u2237 inode_used \u03b3used ino s.(inode.addrs).\n\n  (** Protocol invariant for alloc library *)\n  Local Definition Palloc \u03b3used (s: alloc.t): iProp \u03a3 :=\n    \u2203 allocs: gmap nat (gset u64), (* per-inode used blocks *)\n      \"%Halloc_size\" \u2237 \u231csize allocs = num_inodes\u231d \u2217\n      \"%Hused_global\" \u2237 \u231calloc.used s = \u22c3 (snd <$> map_to_list allocs)\u231d \u2217\n      \"Hused2\" \u2237 inode_allused \u03b3used allocs.\n\n  (** Our own invariant (added to this is [P dir]) *)\n  Definition dir_inv \u03b3blocks (dir: dir.t): iProp \u03a3 :=\n    \"%Hdom\" \u2237 \u231c \u2200 idx, idx < num_inodes \u2192 is_Some (dir.(dir.inodes) !! idx) \u231d \u2217\n    \"H\u03b3blocks\" \u2237 inode_allblocks \u03b3blocks dir.(dir.inodes).\n\n  (** In-memory state of the directory (persistent) *)\n  Definition dir_state (l alloc_l: loc) (inode_refs: list loc) : iProp \u03a3 :=\n    \u2203 d (inodes_s: Slice.t),\n      \"#d\" \u2237 readonly (l \u21a6[Dir :: \"d\"] (disk_val d)) \u2217\n      \"#allocator\" \u2237 readonly (l \u21a6[Dir :: \"allocator\"] #alloc_l) \u2217\n      \"#inodes\" \u2237 readonly (l \u21a6[Dir :: \"inodes\"] (slice_val inodes_s)) \u2217\n      \"#inodes_s\" \u2237 readonly (is_slice_small inodes_s ptrT 1 (inode_refs))\n  .\n\n  (** State of unallocated blocks *)\n  Local Definition alloc\u03a8 (a: u64): iProp \u03a3 := \u2203 bd b, int.Z a d\u21a6[bd] b.\n\n  Definition is_dir l (sz: Z) : iProp \u03a3 :=\n    \u2203 (alloc_ref: loc) (inode_refs: list loc) \u03b3alloc \u03b3used \u03b3blocks,\n      \"%Hlen\" \u2237 \u231clength inode_refs = num_inodes\u231d \u2217\n      \"Hro_state\" \u2237 dir_state l alloc_ref inode_refs \u2217\n      \"#Hinodes\" \u2237 ([\u2217 list] i \u21a6 inode_ref \u2208 inode_refs,\n        is_inode inodeN inode_ref (Pinode \u03b3blocks \u03b3used i) (U64 (Z.of_nat i))) \u2217\n      \"#Halloc\" \u2237 is_allocator (Palloc \u03b3used)\n        alloc\u03a8 allocN alloc_ref (rangeSet num_inodes (sz-num_inodes)) \u03b3alloc \u2217\n      \"#Hinv\" \u2237 ncinv dirN (\u2203 \u03c3, dir_inv \u03b3blocks \u03c3 \u2217 P \u03c3)\n  .\n\n  Definition dir_cinv sz \u03c3 (post_crash: bool) : iProp \u03a3 :=\n    \u2203 \u03b3blocks \u03b3used,\n    \"Hinodes\" \u2237 (\u2203 s_inodes,\n                    \"%Hinode_len\" \u2237 \u231clength s_inodes = num_inodes\u231d \u2217\n                    \"Hinodes\" \u2237 ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n                   \"Hinode_cinv\" \u2237 (if post_crash then inode_cinv_postcrash (U64 (Z.of_nat i)) s_inode\n                                   else inode_cinv_precrash (U64 (Z.of_nat i)) s_inode) \u2217\n                    \"HPinode\" \u2237 Pinode \u03b3blocks \u03b3used i s_inode)) \u2217\n    \"Halloc\" \u2237 alloc_crash_cond_no_later (Palloc \u03b3used) alloc\u03a8 (rangeSet num_inodes (sz-num_inodes)) post_crash \u2217\n    \"Hs_inode\" \u2237 dir_inv \u03b3blocks \u03c3\n  .\n\n  Lemma dir_cinv_post_crash sz \u03c3 :\n    dir_cinv sz \u03c3 true -\u2217 dir_cinv sz \u03c3 false.\n  Proof.\n    iNamed 1.\n    iExists _, _; iFrame.\n    iSplitR \"Halloc\"; last first.\n    { iApply alloc_crash_cond_no_later_from_post_crash; auto. }\n    iNamed \"Hinodes\". iExists _. iSplit; first eauto.\n    iApply (big_sepL_mono with \"Hinodes\").\n    iIntros (?? Hlook). iNamed 1.\n    iFrame. rewrite /inode_cinv_postcrash. iDestruct \"Hinode_cinv\" as (?) \"H\".\n    by iApply inode_durable_to_cinv.\n  Qed.\n\n  Definition pre_dir l (sz: Z) dir : iProp \u03a3 :=\n    \u2203 alloc_ref inode_refs \u03b3blocks \u03b3used,\n      \"%Hlen\" \u2237 \u231clength inode_refs = num_inodes\u231d \u2217\n      \"Hro_state\" \u2237 dir_state l alloc_ref inode_refs \u2217\n      \"Hd_inv\" \u2237 dir_inv \u03b3blocks dir \u2217\n      \"Hinodes\" \u2237 (\u2203 s_inodes,\n                      [\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n                     pre_inode inode_ref (U64 (Z.of_nat i)) s_inode \u2217\n                  Pinode \u03b3blocks \u03b3used i s_inode) \u2217\n      \"Halloc\" \u2237 (\u2203 s_alloc,\n                     \"Halloc_mem\" \u2237 is_allocator_mem_pre alloc_ref s_alloc \u2217\n                     \"%Halloc_dom\" \u2237 \u231calloc.domain s_alloc = rangeSet num_inodes (sz-num_inodes)\u231d \u2217\n                     \"Hunused\" \u2237 ([\u2217 set] k \u2208 alloc.unused s_alloc, alloc\u03a8 k) \u2217\n                     \"HPalloc\" \u2237 Palloc \u03b3used s_alloc)\n  .\n\n  Theorem big_sepM_const_seq {PROP:bi} {A} start sz (def: A) (\u03a6: nat \u2192 A \u2192 PROP) :\n    ([\u2217 map] i\u21a6x \u2208 gset_to_gmap def (set_seq start sz), \u03a6 i x) -\u2217\n    ([\u2217 list] i \u2208 seq start sz, \u03a6 i def).\n  Proof.\n    (iInduction sz as [|sz] \"IH\" forall (start)).\n    - rewrite gset_to_gmap_empty big_sepM_empty /=.\n      auto.\n    - simpl.\n      rewrite gset_to_gmap_union_singleton.\n      rewrite big_sepM_insert; last first.\n      { apply lookup_gset_to_gmap_None.\n        rewrite elem_of_set_seq.\n        lia. }\n      iIntros \"[$ Hm]\".\n      iApply (\"IH\" with \"Hm\").\n  Qed.\n\n  (* for compatibility with Coq v8.11 *)\n  Lemma seq_S : forall len start, seq start (S len) = seq start len ++ [start + len].\n  Proof.\n    intros len start.\n    change [start + len] with (seq (start + len) 1).\n    rewrite <- seq_app.\n    rewrite <- plus_n_Sm, <- plus_n_O; reflexivity.\n  Qed.\n\n  Theorem init_dir {E} (sz: Z) :\n    (num_inodes \u2264 sz < 2^64)%Z \u2192\n    ([\u2217 list] i \u2208 seqZ 0 sz, i d\u21a6[block0] block0) ={E}=\u2217\n    let \u03c30 := dir.mk $ gset_to_gmap [] $ set_seq 0 num_inodes in\n    dir_cinv sz \u03c30 true.\n  Proof.\n    (* Proof outline:\n       - split disk blocks into first num_inodes and [num_inodes,sz-num_inodes)\n       - create inode_cinv using init_inode for each of the first 5\n       - create allocator free blocks from remainder, prove something about\n         remainder's domain being same as [rangeSet num_inodes (sz -\n         num_inodes)]\n       - allocate ghost variables for each Pinode and Palloc\n     *)\n    iIntros (Hbound) \"Hd\".\n    replace (sz) with ((Z.of_nat num_inodes) + ((sz - Z.of_nat num_inodes)))%Z by lia.\n    rewrite -> seqZ_app by lia.\n    change (0 + Z.of_nat num_inodes)%Z with (Z.of_nat num_inodes).\n    rewrite big_sepL_app.\n    iDestruct \"Hd\" as \"[Hinodes Hfree]\".\n\n    iMod (inode_used_alloc _ (gset_to_gmap \u2205 $ set_seq 0 num_inodes)) as (\u03b3used) \"[Hinode_used Hallused]\".\n    iMod (inode_blocks_alloc _ (gset_to_gmap [] $ set_seq 0 num_inodes)) as (\u03b3blocks) \"[Hinode_blocks Hallblocks]\".\n    iModIntro.\n    iApply big_sepM_const_seq in \"Hinode_used\".\n    iApply big_sepM_const_seq in \"Hinode_blocks\".\n\n    iExists \u03b3blocks, \u03b3used; iFrame.\n    iSplitL \"Hinodes Hinode_blocks Hinode_used\".\n    {\n      iInduction num_inodes as [|n Sn] \"IH\".\n      + iExists []; auto.\n      + iAssert (\u231c(n <= sz)%Z \u2227 (sz < 2^64)%Z\u231d)%I as \"IHbound\"; [iPureIntro; word|].\n        rewrite !seq_S.\n        rewrite seqZ_S.\n        repeat change (0+n) with n.\n        change (0+n)%Z with (Z.of_nat n).\n        rewrite !big_sepL_app.\n        iDestruct \"Hinodes\" as \"[Hrest Hinode]\".\n        iDestruct \"Hinode_blocks\" as \"[Hrest_blocks Hinode_block]\".\n        iDestruct \"Hinode_used\" as \"[Hrest_used Hinode_used]\".\n        iSpecialize (\"IH\" with \"IHbound Hrest Hrest_blocks Hrest_used\").\n        iDestruct \"IH\" as (s_inodes) \"H\"; iNamed \"H\".\n\n        iExists (s_inodes ++ [(inode.mk \u2205 [])]).\n        iSplitR.\n        ++ iPureIntro. rewrite app_length; simpl. lia.\n        ++ rewrite big_sepL_app. iFrame \"Hinodes\".\n           repeat rewrite big_sepL_singleton.\n           replace (Z.of_nat n) with (int.Z (U64 n)) by word.\n           rewrite Hinode_len.\n           replace (n+0)%nat with n by word.\n           replace (Z.of_nat n) with (int.Z (U64 n)) by word.\n           iDestruct (init_inode with \"Hinode\") as \"Hinode\".\n           iFrame.\n    }\n    iSplitL \"Hfree Hallused\".\n    { pose proof (new_alloc_state_properties num_inodes (sz-num_inodes) \u2205 ltac:(set_solver))\n        as (Hdom&Hpost_crash&Hused&Hunused).\n      iExists (new_alloc_state num_inodes (sz-num_inodes) \u2205).\n      iSplitR; first eauto.\n      iSplitR.\n      { replace ((num_inodes + (sz - num_inodes) - Z.of_nat num_inodes)%Z) with ((sz - num_inodes)%Z) by word.\n        rewrite /alloc.domain in Hdom; eauto.\n      }\n      rewrite /Palloc Hused.\n      iSplitL \"Hallused\".\n      + iExists (gset_to_gmap \u2205 (set_seq 0 num_inodes)).\n        iFrame \"Hallused\".\n        iSplit; iPureIntro; set_unfold; lia.\n      + rewrite Hunused difference_empty_L.\n        rewrite /rangeSet.\n        rewrite big_sepS_list_to_set; last first.\n        { apply seq_U64_NoDup; word. }\n        rewrite big_sepL_fmap.\n        unfold alloc\u03a8.\n        iApply (big_sepL_mono with \"Hfree\").\n        iIntros (???) \"H\".\n        iExists _.\n        iExists _.\n        iExactEq \"H\".\n        f_equiv.\n        * apply lookup_seqZ in H. word.\n        * eauto.\n    }\n\n    iPureIntro.\n    intros idx Hidx.\n    exists [].\n    apply lookup_gset_to_gmap_Some; split; auto.\n    set_unfold. lia.\n  Qed.\n\n  Lemma pre_inodes_to_cinv inode_refs s_inodes :\n    ([\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n        pre_inode inode_ref i s_inode) -\u2217\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n        inode_cinv_precrash i s_inode).\n  Proof.\n    iIntros \"Hpre\".\n    iApply big_sepL2_to_sepL_2 in \"Hpre\".\n    iApply (big_sepL_mono with \"Hpre\").\n    iIntros (???) \"Hpre\".\n    iDestruct \"Hpre\" as (inode_ref) \"(?&Hpre)\".\n    iApply pre_inode_to_cinv; eauto.\n  Qed.\n\n  Lemma pre_inodes_to_cinv' inode_refs s_inodes :\n    ([\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n        pre_inode inode_ref i s_inode) -\u2217\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n        inode_cinv_postcrash i s_inode).\n  Proof.\n    iIntros \"Hpre\".\n    iApply big_sepL2_to_sepL_2 in \"Hpre\".\n    iApply (big_sepL_mono with \"Hpre\").\n    iIntros (???) \"Hpre\".\n    iDestruct \"Hpre\" as (inode_ref) \"(?&Hpre)\".\n    iApply pre_inode_to_cinv'; eauto.\n  Qed.\n\n  Lemma inodes_cinv_post_to_pre k s_inodes :\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n        inode_cinv_postcrash (k + i) s_inode) -\u2217\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n        inode_cinv_precrash (k + i) s_inode).\n  Proof.\n    iIntros \"Hpre\".\n    iApply (big_sepL_mono with \"Hpre\").\n    iIntros (???) \"Hpre\".\n    by iApply inode_cinv_post_to_pre.\n  Qed.\n\n  Lemma pre_dir_to_cinv l sz dir :\n    pre_dir l sz dir -\u2217 dir_cinv sz dir true.\n  Proof.\n    iNamed 1.\n    iDestruct \"Hinodes\" as (s_inodes) \"Hpre_inodes\".\n    iNamed \"Halloc\".\n    iExists _, _; iFrame.\n    iSplitL \"Hpre_inodes\".\n    - iDestruct (big_sepL2_length with \"Hpre_inodes\") as %Hlen'.\n      iExists s_inodes; iFrame.\n      iSplit.\n      { iPureIntro; congruence. }\n      iApply big_sepL2_flip in \"Hpre_inodes\".\n      iApply (big_sepL2_elim_big_sepL with \"[] Hpre_inodes\"); first auto.\n      iIntros \"!>\" (???????) \"[Hpre HP]\".\n      assert (x = z) by congruence; subst.\n      iFrame.\n      iApply pre_inode_to_cinv'; eauto.\n    - iDestruct (is_allocator_pre_post_crash with \"Halloc_mem\") as %?.\n      iExists _; iFrame \"\u2217 %\".\n  Qed.\n\n  Theorem is_dir_alloc l (sz: Z) \u03c3 :\n    (5 \u2264 sz < 2^64)%Z \u2192\n    \u25b7 P \u03c3 -\u2217\n    pre_dir l sz \u03c3 ={\u22a4}=\u2217\n    init_cancel (is_dir l sz)\n                (\u2203 \u03c3', dir_cinv sz \u03c3' false \u2217 \u25b7 P \u03c3').\n  Proof.\n    iIntros (?) \"HP\"; iNamed 1.\n    iNamed \"Hinodes\".\n    iNamed \"Halloc\".\n    iMod (is_allocator_alloc with \"Hunused HPalloc Halloc_mem\") as \"Halloc\".\n\n    (* allocate all the inodes into a list of is_inodes and a cfupd for all the\n    crash obligations *)\n    iDestruct (big_sepL2_length with \"Hinodes\") as %Hs_inodes_len.\n    iDestruct (big_sepL2_mono with \"Hinodes\") as \"inode_fupds\".\n    { iIntros (?????) \"[Hpre HP]\".\n      iDestruct (is_inode_alloc inodeN with \"HP Hpre\") as \"H\".\n      iDestruct (bupd_fupd with \"H\") as \"H\". iExact \"H\". }\n    cbv beta.\n    iMod (big_sepL2_fupd with \"inode_fupds\") as \"Hinodes\".\n    iDestruct (big_sepL2_init_cancel with \"Hinodes\") as \"Hinodes\".\n\n    iMod (ncinv_alloc dirN _ (\u2203 \u03c3, dir_inv \u03b3blocks \u03c3 \u2217 P \u03c3)\n         with \"[Hd_inv HP]\") as \"(#Hinv&Hinv_crash)\".\n    { iNext.\n      iExists _; iFrame. }\n    iMod (own_disc_fupd_elim with \"Hinv_crash\") as \"Hinv_crash\".\n    rewrite Halloc_dom.\n    iModIntro.\n    (* Combine then use init_cancel wand *)\n    iDestruct (init_cancel_sep with \"Halloc Hinodes\") as \"H\".\n\n    iApply (init_cancel_cfupd \u22a4).\n    iApply (init_cancel_fupd \u22a4).\n    iApply (init_cancel_wand with \"H [Hro_state] [Hinv_crash]\").\n    { iIntros \"H\". iDestruct \"H\" as \"(H1&Hinodes)\".\n      iDestruct \"H1\" as (\u03b3) \"Halloc\".\n      iModIntro. iExists _, _, _, _, _. iFrame.\n      iSplit; first eauto.\n      iFrame \"Hinv\".\n      iApply big_sepL2_to_sepL_1' in \"Hinodes\"; eauto.\n      iApply (big_sepL_mono with \"Hinodes\"); eauto.\n      iIntros (???) \"H\". iDestruct \"H\" as (s_inode) \"(_&$)\".\n    }\n    iIntros \"(Halloc&Hinodes)\".\n    iModIntro.\n    iMod (cfupd_weaken_mask with \"Hinv_crash\") as \"Hdir\"; auto.\n    iDestruct \"Hdir\" as (\u03c3') \"(>Hdir_inv&HP)\".\n    iIntros \"Hc\". iExists _. iFrame.\n    iMod (alloc_crash_cond_strip_later with \"Halloc\") as \"Halloc\".\n    iModIntro.\n    iExists _, _; iFrame.\n    (* here's a bit of gymnastics to maneuver the existential in the big_sepL: *)\n    iDestruct (big_sepL2_const_sepL_r with \"Hinodes\") as \"(_&Hinodes)\".\n    iDestruct (big_sepL_exists_list with \"Hinodes\") as (s_inodes') \"[%Hlen' Hinodes]\".\n    iApply big_sepL2_to_sepL_1' in \"Hinodes\"; auto.\n    iApply big_sepL2_to_sepL_2 in \"Hinodes\".\n    iExists s_inodes'. iSplit; first (iPureIntro; congruence).\n\n    iApply (big_sepL_mono with \"Hinodes\").\n    iIntros (???) \"H\".\n    iDestruct \"H\" as (s_inode) \"(_&H)\".\n    iFrame.\n  Qed.\n\n  (* TODO: use this to replace list_lookup_lt (it's much easier to remember) *)\n  Local Tactic Notation \"list_elem\" constr(l) constr(i) \"as\" simple_intropattern(x) :=\n    let H := fresh \"H\" x \"_lookup\" in\n    let i := lazymatch type of i with\n            | nat => i\n            | Z => constr:(Z.to_nat i)\n            | u64 => constr:(int.nat i)\n            end in\n    destruct (list_lookup_lt _ l i) as [x H];\n    [ try solve [ len ]\n    | ].\n\n  Lemma wpc_openInodes d s_inodes :\n    length s_inodes = num_inodes \u2192\n    {{{ ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n          inode_cinv_postcrash (U64 (Z.of_nat i)) s_inode)\n      }}}\n      openInodes (disk_val d) @ \u22a4\n    {{{ inode_s inode_refs, RET (slice_val inode_s);\n        is_slice_small inode_s ptrT 1 inode_refs \u2217\n        [\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n            pre_inode inode_ref (U64 (Z.of_nat i)) s_inode\n    }}}\n    {{{ ([\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n          inode_cinv_precrash (U64 (Z.of_nat i)) s_inode) }}}.\n  Proof.\n    iIntros (? \u03a6 \u03a6c) \"Hinode_cinvs H\u03a6\".\n    rewrite /openInodes; wpc_pures.\n    { crash_case. iApply (big_sepL_mono with \"[$]\"). iIntros. iApply (inode_cinv_post_to_pre); eauto. }\n    iCache with \"H\u03a6 Hinode_cinvs\".\n    { crash_case. iApply (big_sepL_mono with \"[$]\"). iIntros. iApply (inode_cinv_post_to_pre); eauto. }\n    wpc_frame_seq.\n    wp_apply wp_ref_of_zero.\n    { auto. }\n    iIntros (ino_l) \"Hinodes\". iNamed 1.\n    wpc_pures.\n    wpc_frame_seq.\n    wp_apply wp_ref_to.\n    { auto. }\n    iIntros (addr_ref) \"Haddr\". iNamed 1.\n    wpc_pures.\n    set (inodeT:=(struct.t async_mem_alloc_inode.Inode)).\n    wpc_apply (wpc_forUpto\n               (\u03bb n, \u2203 (inode_s: Slice.t) (inode_refs: list loc),\n                   \"Hinodes\" \u2237 ino_l \u21a6[slice.T ptrT] (slice_val inode_s) \u2217\n                   \"Hinode_slice\" \u2237 is_slice inode_s ptrT 1 inode_refs \u2217\n                   \"Hpre_inodes\" \u2237 ([\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;(take (int.nat n) s_inodes),\n                    pre_inode inode_ref i s_inode) \u2217\n                   \"Hinode_cinvs\" \u2237 ([\u2217 list] i\u21a6s_inode \u2208 (drop (int.nat n) s_inodes),\n                                     inode_cinv_postcrash (int.nat n+i) s_inode)\n               )%I\n              (\u03bb n,\n               \"Hpre_inodes\" \u2237 ([\u2217 list] i\u21a6s_inode \u2208 take (int.nat n) s_inodes,\n                                inode_cinv_precrash i s_inode) \u2217\n               \"Hinode_cinvs\" \u2237 ([\u2217 list] i\u21a6s_inode \u2208 drop (int.nat n) s_inodes,\n                      inode_cinv_precrash (int.nat n + i) s_inode)\n              )%I\n              with \"[] [Hinodes $Haddr Hinode_cinvs]\").\n    { word. }\n    { iIntros (i Hbound); iNamed 1. iFrame. iSplitL \"Hpre_inodes\".\n      - iApply pre_inodes_to_cinv. eauto.\n      - iApply inodes_cinv_post_to_pre. eauto.\n    }\n    { iIntros (n \u03a6' \u03a6c') \"!> (inv&Haddr&%Hbound) H\u03a6\".\n      iNamed \"inv\".\n      wpc_pures.\n      { crash_case. iLeft. iFrame. \n        iSplitL \"Hpre_inodes\".\n        - by iApply pre_inodes_to_cinv.\n        - iApply inodes_cinv_post_to_pre. eauto.\n      }\n      iCache with \"H\u03a6 Hpre_inodes Hinode_cinvs\".\n      { crash_case. iLeft. iFrame.\n        iSplitL \"Hpre_inodes\".\n        - by iApply pre_inodes_to_cinv.\n        - iApply inodes_cinv_post_to_pre. eauto.\n      }\n      wpc_bind (load_ty _ _). wpc_frame. wp_load. iModIntro. iNamed 1.\n      wpc_bind (async_mem_alloc_inode.Open _ _).\n      change (int.Z (U64 5)) with (Z.of_nat num_inodes) in Hbound.\n      list_elem s_inodes n as s_inode.\n      rewrite [drop (int.nat n) s_inodes](drop_S _ s_inode); last by auto.\n      iDestruct (big_sepL_cons with \"Hinode_cinvs\") as \"[Hs_inode Hinode_cinvs]\".\n      wpc_apply (async_mem_alloc_inode_proof.wpc_Open with \"[Hs_inode]\").\n      { replace (U64 $ int.nat n + 0) with n by word.\n        iFrame. }\n      iSplit.\n      { iLeft in \"H\u03a6\". iIntros \"Hs_inode\".\n        iApply \"H\u03a6\".\n        iLeft. iSplitL \"Hpre_inodes\".\n        { by iApply pre_inodes_to_cinv. }\n        iApply big_sepL_cons.\n        replace (U64 $ int.nat n + 0) with n by word.\n        iFrame. \n        setoid_rewrite <-(Nat.add_succ_comm).\n        by iApply inodes_cinv_post_to_pre. \n      }\n      iIntros \"!>\" (inode_ref) \"Hpre_inode\".\n      wpc_frame \"H\u03a6 Hpre_inode Hpre_inodes Hinode_cinvs\".\n      { crash_case. iLeft. iApply (pre_inodes_to_cinv) in \"Hpre_inodes\". iFrame.\n        simpl.\n        replace (U64 $ int.nat n + 0) with n by word.\n        iSplitL \"Hpre_inode\".\n        { by iApply pre_inode_to_cinv. }\n        iApply (big_sepL_mono with \"Hinode_cinvs\").\n        iIntros (???) \"H\". by iApply inode_cinv_post_to_pre.\n      }\n      wp_load.\n      wp_apply (wp_SliceAppend with \"Hinode_slice\").\n      iIntros (inode_s') \"Hinode_slice\".\n      wp_store. iModIntro.\n      iNamed 1.\n      iRight in \"H\u03a6\"; iApply \"H\u03a6\".\n      iFrame.\n      iExists _, _; iFrame.\n      iDestruct (big_sepL2_length with \"Hpre_inodes\") as %Hlens;\n          autorewrite with len in Hlens.\n      replace (int.nat (word.add n 1%Z)) with (S (int.nat n)); last first.\n      { unfold num_inodes in Hbound; word. }\n      iSplitR \"Hinode_cinvs\".\n      - erewrite take_S_r by eauto.\n        iApply (big_sepL2_app with \"Hpre_inodes\").\n        simpl. iSplitL; last done.\n        iExactEq \"Hpre_inode\".\n        f_equal.\n        word.\n      - iApply (big_sepL_mono with \"Hinode_cinvs\").\n        iIntros (?? ?) \"Hpre\".\n        iExactEq \"Hpre\".\n        repeat (f_equal; try word). }\n    { iExists Slice.nil, [].\n      iFrame.\n      rewrite big_sepL2_nil.\n      rewrite -is_slice_zero.\n      rewrite /named //. }\n    iSplit.\n    { (* loop crash condition implies overall crash condition *)\n      iLeft in \"H\u03a6\".\n      iIntros \"Hinv\".\n      iDestruct \"Hinv\" as (i) \"(Hpre&%Hbound')\".\n      iNamed \"Hpre\".\n      iApply \"H\u03a6\".\n      iEval (rewrite -[l in big_opL _ _ l](take_drop (int.nat i))).\n      rewrite big_sepL_app.\n      iSplitL \"Hpre_inodes\".\n      - iApply (big_sepL_mono with \"Hpre_inodes\").\n        iIntros (???) \"Hpre\".\n        iDestruct \"Hpre\" as (?) \"Hpre\".\n        iExists _. iFrame.\n      - iApply (big_sepL_mono with \"Hinode_cinvs\").\n        iIntros (???) \"Hpre\".\n        change (int.Z (U64 5)) with 5%Z in Hbound'.\n        iExactEq \"Hpre\".\n        f_equal; len.\n        rewrite H /num_inodes.\n        replace (int.nat i `min` 5)%nat with (int.nat i) by lia.\n        f_equal. }\n    iIntros \"!> (Hinv&Haddr)\". iNamed \"Hinv\".\n    change (int.Z (U64 5)) with 5%Z.\n    rewrite -> take_ge by word.\n    rewrite -> drop_ge by word.\n    wpc_frame_compl \"Hinodes\".\n    { crash_case. iApply pre_inodes_to_cinv. eauto. }\n    wp_load. iModIntro.\n    iNamed 1.\n    iRight in \"H\u03a6\"; iApply \"H\u03a6\".\n    iFrame.\n    iApply (is_slice_to_small with \"Hinode_slice\").\n  Qed.\n\n  Theorem wpc_inodeUsedBlocks inode_s inode_refs s_inodes :\n    {{{ \"Hinode_s\" \u2237 is_slice_small inode_s ptrT 1 inode_refs \u2217\n        \"Hpre_inodes\" \u2237 [\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n                    pre_inode inode_ref i s_inode }}}\n      inodeUsedBlocks (slice_val inode_s) @ \u22a4\n    {{{ (addrs_ref:loc) used, RET #addrs_ref;\n        \"Hused_set\" \u2237 is_addrset addrs_ref used \u2217\n        \"%Hused_eq\" \u2237 \u231cused = \u22c3 (inode.addrs <$> s_inodes)\u231d \u2217\n        \"Hinode_s\" \u2237 is_slice_small inode_s ptrT 1 inode_refs \u2217\n        \"Hpre_inodes\" \u2237 [\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n                  pre_inode inode_ref i s_inode }}}\n    {{{ [\u2217 list] i\u21a6s_inode \u2208 s_inodes,\n       inode_cinv_precrash i s_inode\n    }}}.\n  Proof.\n    iIntros (\u03a6 \u03a6c) \"Hpre H\u03a6\"; iNamed \"Hpre\".\n    rewrite /inodeUsedBlocks.\n    wpc_pures.\n    { iLeft in \"H\u03a6\". iApply \"H\u03a6\". by iApply pre_inodes_to_cinv. }\n    iCache with \"H\u03a6 Hpre_inodes\".\n    { crash_case. by iApply pre_inodes_to_cinv. }\n    wpc_frame_seq.\n    wp_apply (wp_NewMap unit (t:=struct.t alloc.unit)).\n    iIntros (addrs_ref) \"Hused_set\".\n    iApply is_addrset_from_empty in \"Hused_set\".\n    iNamed 1.\n    wpc_pures.\n    iDestruct (is_slice_small_sz with \"Hinode_s\") as %Hinode_ref_len.\n    wpc_apply (wpc_forSlice (V:=loc)\n                (\u03bb n, \"Hpre_inodes\" \u2237 ([\u2217 list] i\u21a6inode_ref;s_inode \u2208 inode_refs;s_inodes,\n                                  pre_inode inode_ref i s_inode) \u2217\n               \"Hused_set\" \u2237 is_addrset addrs_ref\n                  (\u22c3 (take (int.nat n) (inode.addrs <$> s_inodes))))%I\n                ([\u2217 list] i\u21a6s_inode \u2208 s_inodes, inode_cinv_precrash i s_inode)%I\n             with \"[] [] [$Hinode_s $Hpre_inodes $Hused_set]\").\n    { iIntros \"!>\" (x) \"Hpre\"; iNamed \"Hpre\". iApply pre_inodes_to_cinv. eauto. }\n    { iIntros (i inode_ref) \"!>\".\n      iIntros (\u03a6' \u03a6c') \"(Hpre&%Hbound&%Hlookup) H\u03a6\"; iNamed \"Hpre\".\n      wpc_pures.\n      { crash_case. by iApply pre_inodes_to_cinv. }\n      iDestruct (big_sepL2_lookup_1_some with \"Hpre_inodes\") as \"%Hs_inode_lookup\"; eauto.\n      destruct Hs_inode_lookup as [s_inode Hs_inode_lookup].\n      iDestruct (big_sepL2_lookup_acc_and _ (\u03bb i inode_ref s_inode, inode_cinv_precrash i s_inode) with \"Hpre_inodes\") as \"(Hinode&Hpre_inodes)\"; eauto.\n      { clear.\n        iIntros (k inode_ref s_inode ??) \"Hpre\".\n        iApply pre_inode_to_cinv; eauto. }\n      wpc_pures.\n      { iRight in \"Hpre_inodes\".\n        crash_case.\n        iApply pre_inode_to_cinv in \"Hinode\".\n        iSpecialize (\"Hpre_inodes\" with \"Hinode\").\n        iApply big_sepL2_to_sepL_2 in \"Hpre_inodes\".\n        iApply (big_sepL_mono with \"Hpre_inodes\").\n        iIntros (???) \"Hcinv\".\n        iDestruct \"Hcinv\" as (?) \"(_&$)\". }\n      wpc_apply (wpc_Inode__UsedBlocks with \"Hinode\").\n      iSplit.\n      { iRight in \"Hpre_inodes\".\n        crash_case. iLeft in \"H\u03a6\". iIntros. iApply \"H\u03a6\".\n        iSpecialize (\"Hpre_inodes\" with \"[$]\").\n        iApply big_sepL2_to_sepL_2 in \"Hpre_inodes\".\n        iApply (big_sepL_mono with \"Hpre_inodes\").\n        iIntros (???) \"Hcinv\".\n        iDestruct \"Hcinv\" as (?) \"(_&$)\". }\n      iIntros \"!>\" (addrs_s addrs) \"(Hused_addrs&%Haddrset&Hpre_inode)\".\n      wpc_frame \"H\u03a6 Hpre_inodes Hpre_inode\".\n      {\n        iRight in \"Hpre_inodes\".\n        iRight in \"Hpre_inode\".\n        crash_case. iSpecialize (\"Hpre_inodes\" with \"Hpre_inode\").\n        iFrame.\n        iApply big_sepL2_to_sepL_2 in \"Hpre_inodes\".\n        iApply (big_sepL_mono with \"Hpre_inodes\").\n        iIntros (???) \"Hcinv\".\n        iDestruct \"Hcinv\" as (?) \"(_&$)\". }\n      iDestruct (is_slice_small_acc with \"Hused_addrs\") as \"(Hused_addrs&Hused_cap)\".\n      wp_apply (wp_SetAdd with \"[$Hused_set $Hused_addrs]\").\n      iIntros \"(Hused_set&Hused_addrs)\".\n      iDestruct (\"Hused_cap\" with \"Hused_addrs\") as \"Hused_addrs\".\n      iNamed 1.\n      iApply \"H\u03a6\".\n      iSplitR \"Hused_set\".\n      { iLeft in \"Hpre_inodes\".\n        iApply (\"Hpre_inodes\" with \"(Hpre_inode Hused_addrs)\"). }\n      rewrite Haddrset.\n      iExactEq \"Hused_set\".\n      rewrite /named.\n      f_equal.\n      replace (int.nat (word.add i 1%Z)) with (S (int.nat i)) by word.\n      erewrite take_S_r; last first.\n      { rewrite list_lookup_fmap.\n        rewrite Hs_inode_lookup //. }\n      rewrite union_list_app_L /= right_id_L //. }\n    iSplit.\n    { iLeft in \"H\u03a6\". eauto. }\n    iIntros \"!> (Hinv&Hinode_s)\"; iNamed \"Hinv\".\n    wpc_pures.\n    iDestruct (big_sepL2_length with \"Hpre_inodes\") as %Hlens.\n    iApply \"H\u03a6\"; iFrame.\n    rewrite -> take_ge by len; eauto.\n  Qed.\n\n  Fixpoint delete_below `(m : gmap nat T) (off : nat) :=\n    match off with\n    | O => m\n    | S off' => delete off' (delete_below m off')\n    end.\n\n  Lemma delete_below_insert : forall (off : nat) (pos : nat) `(m : gmap nat T) v,\n    off <= pos ->\n    delete_below (<[pos:=v]> m) off = <[pos:=v]> (delete_below m off).\n  Proof.\n    induction off; intros; simpl; eauto.\n    rewrite IHoff; last by lia.\n    rewrite delete_insert_ne //. lia.\n  Qed.\n\n  Lemma delete_below_delete : forall (off : nat) (pos : nat) `(m : gmap nat T),\n    off <= pos ->\n    delete_below (delete pos m) off = delete pos (delete_below m off).\n  Proof.\n    induction off; intros; simpl; eauto.\n    rewrite IHoff; last by lia.\n    rewrite delete_commute //.\n  Qed.\n\n  Lemma unify_alloc_inodes_used_helper \u03b3used \u03b3blocks allocs s_inodes off :\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes, Pinode \u03b3blocks \u03b3used (off + i) s_inode) -\u2217\n    inode_allused \u03b3used allocs -\u2217\n    \u231clength s_inodes = length (map_to_list (delete_below allocs off)) ->\n     \u22c3 (map_to_list (delete_below allocs off)).*2 = \u22c3 (inode.addrs <$> s_inodes)\u231d.\n  Proof.\n    rewrite /Pinode.\n    iIntros \"Hinodes Hall\".\n    iInduction s_inodes as [|] \"IH\" forall (off).\n    { iPureIntro. intros.\n      generalize dependent (map_to_list (delete_below allocs off)). intros.\n      destruct l; simpl in *; congruence. }\n    iDestruct \"Hinodes\" as \"[Ha Hinodes]\". iNamed \"Ha\".\n    iDestruct (inode_used_lookup with \"Hused1 Hall\") as \"%\".\n    replace (allocs) with (<[off := a.(inode.addrs)]> (delete off allocs)) at 2 3.\n    2: { rewrite insert_delete //. replace (off) with (off + 0) by lia. done. }\n    rewrite delete_below_insert; last by lia.\n    rewrite map_to_list_insert.\n    2: { rewrite delete_below_delete; last by lia. rewrite lookup_delete //. }\n    rewrite ?fmap_cons ?union_list_cons /=.\n    iDestruct (\"IH\" $! (S off) with \"[Hinodes] Hall\") as \"%IH\".\n    { setoid_rewrite plus_n_Sm. iFrame. }\n    rewrite delete_below_delete; last by lia.\n    iPureIntro. intros.\n    rewrite -IH /=; last by lia. done.\n  Qed.\n\n  Lemma unify_alloc_inodes_used \u03b3used \u03b3blocks s_alloc s_inodes :\n    length s_inodes = num_inodes \u2192\n    ([\u2217 list] i\u21a6s_inode \u2208 s_inodes, Pinode \u03b3blocks \u03b3used i s_inode) -\u2217\n    Palloc \u03b3used s_alloc -\u2217\n    \u231calloc.used s_alloc = \u22c3 (inode.addrs <$> s_inodes)\u231d.\n  Proof.\n    rewrite /Palloc.\n    iIntros (Hlen) \"Hinodes\". iNamed 1. rewrite Hused_global.\n    iDestruct (unify_alloc_inodes_used_helper _ _ _ _ 0 with \"Hinodes Hused2\") as \"%Hhelper\".\n    iPureIntro. rewrite -Hhelper /=; eauto.\n    rewrite length_gmap_to_list.\n    congruence.\n  Qed.\n\n  Theorem wpc_Open d (sz: u64) \u03c30 :\n    (5 \u2264 int.Z sz)%Z \u2192\n    {{{ dir_cinv (int.Z sz) \u03c30 true }}}\n      Open (disk_val d) #sz @ \u22a4\n    {{{ l, RET #l; pre_dir l (int.Z sz) \u03c30 }}}\n    {{{ dir_cinv (int.Z sz) \u03c30 false }}}.\n  Proof using Type* - P.\n    iIntros (? \u03a6 \u03a6c) \"Hcinv H\u03a6\".\n    wpc_call.\n    { iApply dir_cinv_post_crash; auto. }\n    { iApply dir_cinv_post_crash; auto. }\n    iNamed \"Hcinv\".\n    iCache with \"H\u03a6 Hinodes Halloc Hs_inode\".\n    { crash_case.\n      iApply dir_cinv_post_crash.\n      iExists _, _; iFrame. }\n    wpc_pures.\n    iNamed \"Hinodes\".\n    iDestruct (big_sepL_sep with \"Hinodes\") as \"(Hinode_cinvs&HPinodes)\".\n    wpc_apply (wpc_openInodes with \"Hinode_cinvs\"); auto.\n    iSplit.\n    { iLeft in \"H\u03a6\". iIntros \"Hinode_cinvs\".\n      iApply \"H\u03a6\".\n      iExists _, _; iFrame.\n      iSplitR \"Halloc\"; last first.\n      { iApply alloc_crash_cond_no_later_from_post_crash; auto. }\n      iExists _. iSplit; first eauto.\n      iApply big_sepL_sep. iFrame.\n    }\n    iIntros \"!>\" (inode_s inode_refs) \"(Hinode_s & Hpre_inodes)\".\n    iCache with \"H\u03a6 Hpre_inodes HPinodes Halloc Hs_inode\".\n    { crash_case.\n      iExists _, _; iFrame.\n      iSplitR \"Halloc\"; last first.\n      { iApply alloc_crash_cond_no_later_from_post_crash; auto. }\n      iExists _. iSplit; first eauto.\n      iApply big_sepL_sep. iFrame.\n      iApply pre_inodes_to_cinv. eauto.\n    }\n    wpc_pures.\n    wpc_apply (wpc_inodeUsedBlocks with \"[$Hinode_s $Hpre_inodes]\").\n    iSplit.\n    { iLeft in \"H\u03a6\". iIntros \"Hinode_cinvs\".\n      iApply \"H\u03a6\".\n      iExists _, _; iFrame.\n      iSplitR \"Halloc\"; last first.\n      { iApply alloc_crash_cond_no_later_from_post_crash; auto. }\n      iExists _. iSplit; first eauto.\n      iApply big_sepL_sep. iFrame.\n    }\n    iIntros \"!>\" (addrs_ref used); iNamed 1.\n    iDestruct \"Halloc\" as (s_alloc) \"Halloc\"; iNamed \"Halloc\".\n    iDestruct (unify_alloc_inodes_used with \"HPinodes HPalloc\") as %Hused; auto.\n    wpc_frame \"H\u03a6 Hpre_inodes HPinodes HPalloc Hunused Hs_inode\".\n    { crash_case.\n      iExists _, _; iFrame.\n      iSplitL \"Hpre_inodes HPinodes\".\n      - iExists s_inodes; iFrame \"\u2217 %\".\n        iApply big_sepL_sep; iFrame.\n        iApply pre_inodes_to_cinv. eauto.\n      - iExists _; iFrame \"\u2217 %\". }\n    rewrite -wp_fupd.\n    wp_apply (wp_newAllocator s_alloc with \"Hused_set\").\n    { word. }\n    { word_cleanup.\n      rewrite /alloc.domain.\n      rewrite Halloc_dom.\n      f_equal; lia. }\n    { congruence. }\n    { auto. }\n    iIntros (alloc_ref) \"Halloc_mem\".\n    wp_apply wp_allocStruct; first val_ty.\n    iIntros (inode_ref) \"Hinode_fields\".\n    iDestruct (struct_fields_split with \"Hinode_fields\") as \"(d&allocator&inodes&_)\".\n    iMod (readonly_alloc_1 with \"d\") as \"#d\".\n    iMod (readonly_alloc_1 with \"allocator\") as \"#allocator\".\n    iMod (readonly_alloc_1 with \"inodes\") as \"#inodes\".\n    iMod (readonly_alloc_1 with \"Hinode_s\") as \"#inode_s\".\n    iModIntro.\n    iNamed 1.\n    iApply \"H\u03a6\".\n    iDestruct (big_sepL2_length with \"Hpre_inodes\") as %Hlens.\n    iExists alloc_ref, inode_refs, _, _; iFrame.\n    iSplit.\n    { iPureIntro; lia. }\n    iSplitR.\n    { iExists _, _; iFrame \"#\". }\n    iSplitL \"Hpre_inodes HPinodes\".\n    { iExists s_inodes; iFrame.\n      rewrite big_sepL2_sep; iFrame.\n      iAssert ([\u2217 list] k\u21a6v \u2208 inode_refs, emp)%I as \"Hinode_refs\".\n      { iApply big_sepL_emp. done. }\n      iDestruct (big_sepL2_sepL_2 with \"Hinode_refs HPinodes\") as \"Hmerge\"; eauto.\n      iApply (big_sepL2_mono with \"Hmerge\").\n      iIntros (?????) \"[_ H]\". iFrame.\n    }\n    iExists _; iFrame \"\u2217 %\".\n  Qed.\n\n  Theorem wpc_Dir__Read (Q: option Block \u2192 iProp \u03a3) l sz (idx: u64) (i: u64) :\n    int.nat idx < num_inodes \u2192\n    {{{ \"#Hdir\" \u2237 is_dir l sz \u2217\n        \"Hfupd\" \u2237 (\u2200 \u03c3 blocks mb,\n                      \u231c\u03c3.(dir.inodes) !! int.nat idx = Some blocks \u2227\n                       mb = blocks !! int.nat i\u231d -\u2217\n                      \u25b7 P \u03c3 ={\u22a4 \u2216 \u2191N}=\u2217 \u25b7 P \u03c3 \u2217 Q mb)\n    }}}\n      Dir__Read #l #idx #i @ \u22a4\n    {{{ (s:Slice.t) mb, RET (slice_val s);\n        match mb with\n        | None => \u231cs = Slice.nil\u231d\n        | Some b => is_block s 1 b\n        end \u2217 Q mb }}}\n    {{{ True }}}.\n  Proof.\n    iIntros (Hidx \u03a6 \u03a6c) \"Hpre H\u03a6\"; iNamed \"Hpre\".\n    wpc_call.\n    { crash_case; auto. }\n    { crash_case; auto. }\n    iCache with \"H\u03a6 Hfupd\".\n    { crash_case; auto. }\n    iNamed \"Hdir\". iNamed \"Hro_state\".\n    edestruct (lookup_lt_is_Some_2 inode_refs) as [inode_ref Hinode_ref].\n    { rewrite Hlen. done. }\n    iDestruct (big_sepL_lookup _ _ _ _ Hinode_ref with \"Hinodes\") as \"Hinode {Hinodes}\".\n    wpc_pures.\n    wpc_frame_seq.\n    wp_loadField.\n    iMod (readonly_load with \"inodes_s\") as (qinodes) \"{inodes_s} inodes_s\".\n    wp_apply (wp_SliceGet _ _ _ _ _ inode_refs with \"[$inodes_s //]\").\n    iIntros \"inodes_s Hrest\". iNamed \"Hrest\".\n    wpc_pures.\n    (* Now we get to the actual read operation. *)\n    iApply (wpc_step_strong_mono _ _ _ _ _\n         (\u03bb v, (\u2203 s mb, \u231c v = slice_val s \u231d \u2217\n                match mb with\n                | Some b => is_block s 1 b\n                | None => \u231cs = Slice.nil\u231d\n                end \u2217 Q mb))%I _ True with \"[-H\u03a6] [H\u03a6]\"); auto.\n    2: { iSplit.\n         * iNext. iIntros (?) \"H\". iDestruct \"H\" as (??) \"(%&?)\". subst.\n           iModIntro. iRight in \"H\u03a6\". by iApply \"H\u03a6\".\n         * iLeft in \"H\u03a6\". iIntros. iModIntro. by iApply \"H\u03a6\". }\n    iApply (wpc_Inode__Read with \"[Hinode]\"); first done.\n    iSplit; first eauto.\n    iIntros \"!>\" (\u03c3I mb) \"[%Hmb HPI]\". iNamed \"HPI\".\n    iInv dirN as (\u03c3D) \"[>Hdir HPD]\".\n    (* We need to learn that this inode exists in \u03c3D. *)\n    rewrite /dir_inv. iNamed \"Hdir\".\n    destruct (Hdom _ Hidx) as [\u03c3I' H\u03c3I'].\n    iDestruct (inode_blocks_lookup with \"Hownblocks H\u03b3blocks\") as %Hblock.\n    simplify_eq.\n    iMod fupd_mask_subseteq as \"HcloseM\"; (* adjust mask *)\n        last iMod (\"Hfupd\" with \"[] HPD\") as \"[HPD HQ]\".\n    { solve_ndisj. }\n    { iPureIntro. eauto. }\n    iMod \"HcloseM\" as \"_\". iModIntro. iSplitL \"H\u03b3blocks HPD\".\n    { (* re-establish dir_inv *) eauto 10 with iFrame. }\n    iModIntro. iSplitL \"Hownblocks Hused1\".\n    { (* re-establish inode invariant *) rewrite /Pinode. eauto 10 with iFrame. }\n    iSplit.\n    { eauto. }\n    iIntros (s) \"Hpost\".\n    iExists _, _; iSplit; first eauto; iFrame; eauto.\n  Qed.\n\n  Theorem wpc_Dir__Size (Q: u64 \u2192 iProp \u03a3) l sz (idx: u64):\n    int.nat idx < num_inodes \u2192\n    {{{ \"#Hdir\" \u2237 is_dir l sz \u2217\n        \"Hfupd\" \u2237 (\u2200 \u03c3 blocks sz,\n                      \u231c\u03c3.(dir.inodes) !! int.nat idx = Some blocks \u2227\n                       int.nat sz = length blocks\u231d -\u2217\n                      \u25b7 P \u03c3 ={\u22a4 \u2216 \u2191N}=\u2217 \u25b7 P \u03c3 \u2217 Q sz)\n    }}}\n      Dir__Size #l #idx @ \u22a4\n    {{{ sz, RET #sz; Q sz }}}\n    {{{ True }}}.\n  Proof.\n    iIntros (Hidx \u03a6 \u03a6c) \"Hpre H\u03a6\"; iNamed \"Hpre\".\n    wpc_call.\n    { crash_case; auto. }\n    { crash_case; auto. }\n    iCache with \"H\u03a6 Hfupd\".\n    { crash_case; auto. }\n    wpc_pures.\n    iNamed \"Hdir\". iNamed \"Hro_state\".\n    edestruct (lookup_lt_is_Some_2 inode_refs) as [inode_ref Hinode_ref].\n    { rewrite Hlen. done. }\n    iDestruct (big_sepL_lookup _ _ _ _ Hinode_ref with \"Hinodes\") as \"Hinode {Hinodes}\".\n    wpc_frame_seq.\n    wp_loadField.\n    iMod (readonly_load with \"inodes_s\") as (qinodes) \"{inodes_s} inodes_s\".\n    wp_apply (wp_SliceGet _ _ _ _ _ inode_refs with \"[$inodes_s //]\").\n    iIntros \"inodes_s Hrest\". iNamed \"Hrest\".\n    wpc_pures.\n    (* Now we get to the actual size operation. *)\n    iApply (wpc_step_strong_mono _ _ _ _ _\n           (\u03bb v, \u2203 (sz : u64), \u231c v = #sz \u231d \u2217 Q sz)%I _ _ with \"[-H\u03a6] [H\u03a6]\"); auto.\n    2: { iSplit.\n         * iNext. iIntros (?) \"H\". iDestruct \"H\" as (?) \"(%&?)\". subst.\n           iModIntro. iRight in \"H\u03a6\". by iApply \"H\u03a6\".\n         * iLeft in \"H\u03a6\". iIntros. iModIntro. by iApply \"H\u03a6\". }\n    iApply (wpc_Inode__Size with \"[$Hinode]\").\n    iSplit; first eauto.\n    iIntros \"!>\" (\u03c3I mb) \"[%Hmb HPI]\". iNamed \"HPI\".\n    iInv dirN as (\u03c3D) \"[>Hdir HPD]\".\n    (* We need to learn that this inode exists in \u03c3D. *)\n    rewrite /dir_inv. iNamed \"Hdir\".\n    destruct (Hdom _ Hidx) as [\u03c3I' H\u03c3I'].\n    iDestruct (inode_blocks_lookup with \"Hownblocks H\u03b3blocks\") as %Hblock.\n    simplify_eq.\n    iMod fupd_mask_subseteq as \"HcloseM\"; (* adjust mask *)\n        last iMod (\"Hfupd\" with \"[] HPD\") as \"[HPD HQ]\".\n    { solve_ndisj. }\n    { iPureIntro. eauto. }\n    iMod \"HcloseM\" as \"_\". iModIntro. iSplitL \"H\u03b3blocks HPD\".\n    { (* re-establish dir_inv *) eauto 10 with iFrame. }\n    iModIntro. iSplitL \"Hownblocks Hused1\".\n    { (* re-establish inode invariant *) rewrite /Pinode. eauto 10 with iFrame. }\n    iSplit.\n    - eauto.\n    - iIntros \"_\". eauto.\n  Qed.\n\n\n  (* these two fupds are easy to prove universally because the change they make\n  doesn't affect the free set, which is all that Palloc talks about *)\n\n  Lemma reserve_fupd_Palloc E \u03b3used :\n    \u22a2 reserve_fupd E (Palloc \u03b3used).\n  Proof.\n    iIntros (s s' ma Hma) \"HPalloc\".\n    destruct ma; intuition subst; auto.\n    iModIntro.\n    rewrite /Palloc /named.\n    rewrite alloc_used_reserve //.\n  Qed.\n\n  Lemma free_fupd_Palloc E \u03b3used :\n    \u22a2 \u2200 a, free_fupd E (Palloc \u03b3used) a.\n  Proof.\n    iIntros (a s s') \"HPalloc\".\n    iModIntro.\n    rewrite /Palloc /named.\n    rewrite alloc_free_reserved //.\n  Qed.\n\n  (*\n  Lemma dir_cinv_crash_true E sz \u03c3 :\n    dir_cinv sz \u03c3 false ={E}=\u2217 dir_cinv sz \u03c3 true.\n  Proof.\n    iNamed 1. rewrite /dir_cinv.\n    iMod (alloc_crash_cond_no_later_crash_true with \"[] Halloc\").\n    {\n      iIntros (\u03c30). rewrite /Palloc/named. rewrite used_revert_reserved.\n      iIntros \"H\". eauto.\n    }\n    iModIntro. iExists _, _. iFrame.\n  Qed.\n   *)\n\n  Lemma alloc_insert_dom idx (new_addrs old_addrs inode_addrs: gset u64)\n        (allocs: gmap nat (gset u64)) :\n    old_addrs = \u22c3 (snd <$> map_to_list allocs) \u2192\n    allocs !! idx = Some inode_addrs \u2192\n    new_addrs \u222a old_addrs =\n    \u22c3 (snd <$> map_to_list (<[idx:=new_addrs \u222a inode_addrs]> allocs)).\n  Proof.\n    intros -> Hidx.\n    revert idx Hidx; induction allocs using map_ind; intros idx Hidx.\n    { exfalso. rewrite lookup_empty in Hidx. done. }\n    destruct (decide (idx = i)) as [->|Hne].\n    - (* Induction reached the updated idx. We bottom out. *)\n      rewrite insert_insert. rewrite !map_to_list_insert //.\n      rewrite !fmap_cons !union_list_cons /=.\n      rewrite lookup_insert in Hidx. simplify_eq/=. set_solver+.\n    - (* The updated element is a different one. Recurse. *)\n      rewrite insert_commute //. rewrite map_to_list_insert //.\n      rewrite map_to_list_insert; last first.\n      { rewrite lookup_insert_ne //. }\n      rewrite !fmap_cons !union_list_cons /=.\n      rewrite -IHallocs; last first.\n      { rewrite -Hidx lookup_insert_ne //. }\n      set_solver+.\n  Qed.\n\n  (* FIXME: in case of failure, the resources put into \"Hfupd\" are lost! *)\n  Theorem wpc_Dir__Append (Q: iProp \u03a3) l sz b_s b0 (idx: u64) :\n    int.nat idx < num_inodes \u2192\n    {{{ \"#Hdir\" \u2237 is_dir l sz \u2217\n        \"Hb\" \u2237 is_block b_s 1 b0 \u2217\n        \"Hfupd\" \u2237 (\u2200 \u03c3 blocks,\n                      \u231c\u03c3.(dir.inodes) !! int.nat idx = Some blocks\u231d -\u2217\n                      \u25b7 P \u03c3 ={\u22a4 \u2216 \u2191N}=\u2217 \u25b7 P (dir.mk $ <[ int.nat idx := blocks ++ [b0] ]> \u03c3.(dir.inodes)) \u2217 Q)\n    }}}\n      Dir__Append #l #idx (slice_val b_s) @ \u22a4\n    {{{ (ok: bool), RET #ok; if ok then Q else emp }}}\n    {{{ True }}}.\n  Proof.\n    iIntros (Hidx \u03a6 \u03a6c) \"Hpre H\u03a6\"; iNamed \"Hpre\".\n    wpc_call.\n    { crash_case; auto. }\n    { crash_case; auto. }\n    iCache with \"H\u03a6 Hfupd\".\n    { crash_case; auto. }\n    wpc_pures.\n    iNamed \"Hdir\". iNamed \"Hro_state\".\n    edestruct (lookup_lt_is_Some_2 inode_refs) as [inode_ref Hinode_ref].\n    { rewrite Hlen. done. }\n    iDestruct (big_sepL_lookup _ _ _ _ Hinode_ref with \"Hinodes\") as \"Hinode {Hinodes}\".\n    wpc_frame_seq.\n    wp_loadField.\n    iMod (readonly_load with \"inodes_s\") as (qinodes) \"{inodes_s} inodes_s\".\n    wp_apply (wp_SliceGet _ _ _ _ _ inode_refs with \"[$inodes_s //]\").\n    iIntros \"inodes_s Hrest\". iNamed \"Hrest\".\n    wpc_pures.\n    wpc_loadField.\n    (* Now we get to the actual append operation. *)\n    iApply (wpc_step_strong_mono _ _ _ _ _\n           (\u03bb v, \u2203 (ok: bool), \u231c v = #ok \u231d \u2217 if ok then Q else emp)%I _ _ with \"[-H\u03a6] [H\u03a6]\"); auto.\n    2: { iSplit.\n         * iNext. iIntros (?) \"H\". iDestruct \"H\" as (?) \"(%&?)\". subst.\n           iModIntro. iRight in \"H\u03a6\". by iApply \"H\u03a6\".\n         * iLeft in \"H\u03a6\". iIntros. iModIntro. by iApply \"H\u03a6\". }\n    iApply (wpc_Inode__Append inodeN allocN);\n      [solve_ndisj|..].\n    iFrame \"Hinode Hb Halloc\".\n    iSplit; [ | iSplit; [ | iSplit ] ].\n    - iApply reserve_fupd_Palloc.\n    - iApply free_fupd_Palloc.\n    - eauto.\n    - iSplit.\n      { (* Failure case *) iNext. iExists _; iSplit; eauto. }\n      iIntros \"!>\" (\u03c3 \u03c3' addr' -> Hwf s Hreserved) \"(HPinode&>HPalloc)\".\n      iEval (rewrite /Palloc) in \"HPalloc\". iNamed \"HPalloc\".\n      iNamed \"HPinode\".\n      iDestruct (inode_used_lookup with \"Hused1 Hused2\") as %Heq.\n      iInv \"Hinv\" as ([\u03c30]) \"[>Hinner HP]\" \"Hclose\".\n      iNamed \"Hinner\".\n      iMod (inode_used_update _ (union {[addr']} \u03c3.(inode.addrs)) with \"Hused1 Hused2\") as\n          \"[H\u03b3used Hused]\".\n      iDestruct (inode_blocks_lookup with \"Hownblocks H\u03b3blocks\") as %Heq2.\n      simplify_eq/=.\n      iMod (inode_blocks_update  _ (\u03c3.(inode.blocks) ++ [b0]) with \"Hownblocks H\u03b3blocks\") as\n          \"[Hownblocks H\u03b3blocks]\".\n      iSpecialize (\"Hfupd\" $! {| dir.inodes := \u03c30 |}). rewrite Heq2.\n      iMod fupd_mask_subseteq as \"HcloseM\"; last (* adjust mask *)\n        iMod (\"Hfupd\" with \"[% //] [$HP]\") as \"[HP HQ]\".\n      { solve_ndisj. }\n      iMod \"HcloseM\" as \"_\".\n      simpl. iMod (\"Hclose\" with \"[H\u03b3blocks HP]\") as \"_\".\n      { iNext. iExists _. iFrame \"HP\". rewrite /dir_inv /=. iFrame.\n        (* Show that the first 5 inodes are still all allocated. *)\n        iPureIntro. intros idx' Hidx'. destruct (decide ((int.nat idx) = idx')) as [->|Hne].\n        - rewrite lookup_insert. eauto.\n        - rewrite lookup_insert_ne //. apply Hdom. done.\n      }\n      iModIntro.\n      iFrame.\n      rewrite /Palloc.\n      iSplitR \"HQ\".\n      { iNext. iExists _. iFrame \"Hused\".\n        (* Show that the domain bookeeping worked out. *)\n        iPureIntro. split.\n        - rewrite map_size_insert_Some //.\n        - rewrite alloc_used_insert.\n          apply alloc_insert_dom; auto.\n      }\n      iSplit; eauto.\n  Qed.\n\nEnd goose.\n\nFrom Perennial.goose_lang Require Import crash_modality recovery_lifting.\n\nSection crash_stable.\n  Context `{!heapGS \u03a3}.\n  Context `{!stagedG \u03a3}.\n  Context `{!inG \u03a3 blocksR}.\n  Context `{!inG \u03a3 allocsR}.\n\n  Instance alloc\u03a8_crash_stable k:\n    IntoCrash (alloc\u03a8 k) (\u03bb _, alloc\u03a8 k).\n  Proof.\n    rewrite /IntoCrash. iNamed 1.\n    iCrash. iExists _; eauto.\n  Qed.\n\n  Instance Palloc_crash_stable \u03b3 \u03c3:\n    IntoCrash (Palloc \u03b3 \u03c3) (\u03bb _, Palloc \u03b3 \u03c3).\n  Proof. rewrite /IntoCrash. iApply post_crash_nodep. Qed.\n\n  Instance Pinode_crash_stable \u03b3blocks \u03b3used i s_inode:\n    IntoCrash (Pinode \u03b3blocks \u03b3used i s_inode) (\u03bb _, Pinode \u03b3blocks \u03b3used i s_inode).\n  Proof. rewrite /IntoCrash. iApply post_crash_nodep. Qed.\n\n  Existing Instance inode_cinv_pre_post.\n\n  Global Instance dir_cinv_crash sz \u03c30 :\n    IntoCrash (dir_cinv sz \u03c30 false) (\u03bb _, (|={\u22a4}=> dir_cinv sz \u03c30 true)%I).\n  Proof.\n    rewrite /IntoCrash /dir_cinv.\n    iNamed 1.\n    iNamed \"Hinodes\".\n    rewrite (allocator_crash_cond_no_later_stable (\u03bb _, Palloc \u03b3used)).\n    rewrite /dir_inv.\n    iNamed \"Hs_inode\".\n    rewrite /inode_allblocks.\n    iPoseProof (post_crash_nodep with \"H\u03b3blocks\") as \"H\u03b3blocks\".\n    iCrash.\n    iExists _, _. \n    iMod (alloc_crash_cond_no_later_crash_true with \"[] Halloc\").\n    {\n      iIntros (\u03c30'). rewrite /Palloc/named. rewrite used_revert_reserved.\n      iIntros \"H\". eauto.\n    }\n    iModIntro.\n    iFrame.\n    iSplitL \"Hinodes\".\n    { iExists _. iSplit; first eauto. iFrame. }\n    eauto.\n  Qed.\n\nEnd crash_stable.\n\nSection recov.\n  Context `{!heapGS \u03a3}.\n  Context `{!allocG \u03a3}.\n  Context `{!stagedG \u03a3}.\n  Context `{!inG \u03a3 blocksR}.\n  Context `{!inG \u03a3 allocsR}.\n\n  Set Nested Proofs Allowed.\n\n  (* Just a simple example of using idempotence *)\n  Theorem wpr_Open (d: ()) (sz: u64) \u03c30:\n    (5 \u2264 int.Z sz)%Z \u2192\n    dir_cinv (int.Z sz) \u03c30 true -\u2217\n    wpr NotStuck \u22a4\n        (Open (disk_val d) #sz)\n        (Open (disk_val d) #sz)\n        (\u03bb _, True%I)\n        (\u03bb _, True%I)\n        (\u03bb _ _, True%I).\n  Proof using Type*.\n    iIntros (Hsz) \"Hstart\".\n    iApply (idempotence_wpr NotStuck \u22a4 _ _ (\u03bb _, True)%I (\u03bb _, True)%I (\u03bb _ _, True)%I (\u03bb _, \u2203 \u03c3', dir_cinv (int.Z sz) \u03c3' false)%I with \"[Hstart] []\").\n    { wpc_apply (wpc_Open with \"Hstart\"); auto 10. }\n    iModIntro. iIntros (????) \"H\".\n    iDestruct \"H\" as (\u03c3'') \"Hstart\".\n    (* TODO(Joe): why does iCrash not work after the iNext? *)\n    iNext. rewrite dir_cinv_crash. iRevert \"Hstart\".\n    iApply @post_crash_mono.\n    iIntros (?) \"Hstart _\".\n    iSplit; first done.\n    iMod \"Hstart\".\n    wpc_apply (wpc_Open with \"Hstart\").\n    { eauto. }\n    eauto 10.\n  Qed.\nEnd recov.\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/examples/async_mem_alloc_dir_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.18791387427162048}}
{"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 RealmSyncHandlerAux.Spec.\nRequire Import RealmSyncHandlerAux.Layer.\nRequire Import RealmSyncHandler.Code.handle_sysreg_access_trap.\n\nRequire Import RealmSyncHandler.LowSpecs.handle_sysreg_access_trap.\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    _assert_cond \u21a6 gensem assert_cond_spec\n      \u2295 _handle_id_sysreg_trap \u21a6 gensem handle_id_sysreg_trap_spec\n      \u2295 _handle_timer_sysreg_trap \u21a6 gensem handle_timer_sysreg_trap_spec\n      \u2295 _handle_icc_el1_sysreg_trap \u21a6 gensem handle_icc_el1_sysreg_trap_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_assert_cond: block.\n    Hypothesis h_assert_cond_s : Genv.find_symbol ge _assert_cond = Some b_assert_cond.\n    Hypothesis h_assert_cond_p : Genv.find_funct_ptr ge b_assert_cond\n                                 = Some (External (EF_external _assert_cond\n                                                  (signature_of_type (Tcons tuint Tnil) tvoid cc_default))\n                                        (Tcons tuint Tnil) tvoid cc_default).\n    Local Opaque assert_cond_spec.\n\n    Variable b_handle_id_sysreg_trap: block.\n    Hypothesis h_handle_id_sysreg_trap_s : Genv.find_symbol ge _handle_id_sysreg_trap = Some b_handle_id_sysreg_trap.\n    Hypothesis h_handle_id_sysreg_trap_p : Genv.find_funct_ptr ge b_handle_id_sysreg_trap\n                                           = Some (External (EF_external _handle_id_sysreg_trap\n                                                            (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default))\n                                                  (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default).\n    Local Opaque handle_id_sysreg_trap_spec.\n\n    Variable b_handle_timer_sysreg_trap: block.\n    Hypothesis h_handle_timer_sysreg_trap_s : Genv.find_symbol ge _handle_timer_sysreg_trap = Some b_handle_timer_sysreg_trap.\n    Hypothesis h_handle_timer_sysreg_trap_p : Genv.find_funct_ptr ge b_handle_timer_sysreg_trap\n                                              = Some (External (EF_external _handle_timer_sysreg_trap\n                                                               (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default))\n                                                     (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default).\n    Local Opaque handle_timer_sysreg_trap_spec.\n\n    Variable b_handle_icc_el1_sysreg_trap: block.\n    Hypothesis h_handle_icc_el1_sysreg_trap_s : Genv.find_symbol ge _handle_icc_el1_sysreg_trap = Some b_handle_icc_el1_sysreg_trap.\n    Hypothesis h_handle_icc_el1_sysreg_trap_p : Genv.find_funct_ptr ge b_handle_icc_el1_sysreg_trap\n                                                = Some (External (EF_external _handle_icc_el1_sysreg_trap\n                                                                 (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default))\n                                                       (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default).\n    Local Opaque handle_icc_el1_sysreg_trap_spec.\n\n    Lemma handle_sysreg_access_trap_body_correct:\n      forall m d d' env le rec_base rec_offset esr\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset)))\n             (HPTesr: PTree.get _esr le = Some (Vlong esr))\n             (Hspec: handle_sysreg_access_trap_spec0 (rec_base, rec_offset) (VZ64 (Int64.unsigned esr)) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) handle_sysreg_access_trap_body E0 le' (m, d') Out_normal).\n    Proof.\n      solve_code_proof Hspec handle_sysreg_access_trap_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmSyncHandler/CodeProof/handle_sysreg_access_trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.34864512856608565, "lm_q1q2_score": 0.1879138691079838}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.BinInt.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Utility.MkMachineWidth.\n\n\n(* Note: Register 0 is not considered valid because it cannot be written *)\nDefinition valid_register(r: Register): Prop := (0 < r < 32)%Z.\n\nSection Primitives.\n\n  Context {width: Z} {BW: Bitwidth width} {word: word width} {word_ok: word.ok word}.\n  Context {Registers: map.map Register word}.\n  Context {mem: map.map word byte}.\n\n  Context {M: Type -> Type}.\n  Context {MM: Monad M}.\n\n  Class PrimitivesParams(Machine: Type) := {\n    (* Abstract predicate specifying when a monadic computation satisfies a\n       postcondition when run on given initial machine *)\n    mcomp_sat: forall {A: Type}, M A -> Machine -> (A -> Machine -> Prop) -> Prop;\n\n    (* Tells whether the given value can be found in an uninitialized register.\n       On instances supporting non-determinism, it returns True for all values.\n       On instances without non-determinism, it only accepts a default value, eg 0 *)\n    is_initial_register_value: word -> Prop;\n\n    (* tells what happens if an n-byte read at a non-memory address is performed *)\n    nonmem_load : forall (n: nat), SourceType -> word -> RiscvMachine -> (HList.tuple byte n -> RiscvMachine -> Prop) -> Prop;\n\n    (* tells what happens if an n-byte write at a non-memory address is performed *)\n    nonmem_store: forall (n: nat), SourceType -> word -> HList.tuple byte n -> RiscvMachine -> (RiscvMachine -> Prop) -> Prop;\n\n    (* an invariant which is preserved by each primitive operation\n       TODO it might also be useful to have invariants which are only preserved by whole\n       instructions, such as eg the concrete nextPc = pc + 4 *)\n    valid_machine: Machine -> Prop;\n  }.\n\n  Class mcomp_sat_spec{Machine: Type}(p: PrimitivesParams Machine): Prop := {\n    spec_Bind{A B: Type}: forall (initialL: Machine) (post: B -> Machine -> Prop)\n                                 (m: M A) (f : A -> M B),\n        (exists mid: A -> Machine -> Prop,\n            mcomp_sat m initialL mid /\\\n            (forall a middle, mid a middle -> mcomp_sat (f a) middle post)) <->\n        mcomp_sat (Bind m f) initialL post;\n\n    spec_Return{A: Type}: forall (initialL: Machine)\n                                 (post: A -> Machine -> Prop) (a: A),\n        post a initialL <->\n        mcomp_sat (Return a) initialL post;\n  }.\n\n  (* monadic computations used for specifying the behavior of RiscvMachines should be \"sane\"\n     in the sense that we never step to the empty set (that's not absence of failure, since\n     failure is modeled as \"steps to no set at all\"), and that the trace of events is\n     append-only, and that valid_machine is preserved *)\n  Definition mcomp_sane{p: PrimitivesParams RiscvMachine}{A: Type}(comp: M A): Prop :=\n    forall (st: RiscvMachine) (post: A -> RiscvMachine -> Prop),\n      valid_machine st ->\n      mcomp_sat comp st post ->\n      (exists a st', post a st' /\\ valid_machine st') /\\\n      (mcomp_sat comp st (fun a st' =>\n         (post a st' /\\ exists diff, st'.(getLog) = diff ++ st.(getLog)) /\\ valid_machine st')).\n\n  Context {RVM: RiscvProgram M word}.\n  Context {RVS: @riscv.Spec.Machine.RiscvMachine M word _ _ RVM}.\n\n  Class PrimitivesSane(p: PrimitivesParams RiscvMachine): Prop := {\n    getRegister_sane: forall r, mcomp_sane (getRegister r);\n    setRegister_sane: forall r v, mcomp_sane (setRegister r v);\n    loadByte_sane: forall kind addr, mcomp_sane (loadByte kind addr);\n    loadHalf_sane: forall kind addr, mcomp_sane (loadHalf kind addr);\n    loadWord_sane: forall kind addr, mcomp_sane (loadWord kind addr);\n    loadDouble_sane: forall kind addr, mcomp_sane (loadDouble kind addr);\n    storeByte_sane: forall kind addr v, mcomp_sane (storeByte kind addr v);\n    storeHalf_sane: forall kind addr v, mcomp_sane (storeHalf kind addr v);\n    storeWord_sane: forall kind addr v, mcomp_sane (storeWord kind addr v);\n    storeDouble_sane: forall kind addr v, mcomp_sane (storeDouble kind addr v);\n    makeReservation_sane: forall addr, mcomp_sane (makeReservation addr);\n    clearReservation_sane: forall addr, mcomp_sane (clearReservation addr);\n    checkReservation_sane: forall addr, mcomp_sane (checkReservation addr);\n    getCSRField_sane: forall f, mcomp_sane (getCSRField f);\n    setCSRField_sane: forall f v, mcomp_sane (setCSRField f v);\n    getPrivMode_sane: mcomp_sane getPrivMode;\n    setPrivMode_sane: forall m, mcomp_sane (setPrivMode m);\n    fence_sane: forall a b, mcomp_sane (fence a b);\n    getPC_sane: mcomp_sane getPC;\n    setPC_sane: forall newPc, mcomp_sane (setPC newPc);\n    endCycleNormal_sane: mcomp_sane endCycleNormal;\n    endCycleEarly_sane: forall A, mcomp_sane (@endCycleEarly _ _ _ _ _ A);\n  }.\n\n  Definition spec_load{p: PrimitivesParams RiscvMachine}(n: nat)\n             (riscv_load: SourceType -> word -> M (HList.tuple byte n))\n             (mem_load: mem -> word -> option (HList.tuple byte n))\n    : Prop :=\n    forall initialL addr (kind: SourceType) (post: HList.tuple byte n -> RiscvMachine -> Prop),\n      (kind = Fetch -> isXAddr4 addr initialL.(getXAddrs)) /\\\n      ((exists v, mem_load initialL.(getMem) addr = Some v /\\\n                  post v initialL) \\/\n       (mem_load initialL.(getMem) addr = None /\\\n        nonmem_load n kind addr initialL post)) ->\n      mcomp_sat (riscv_load kind addr) initialL post.\n\n  (* After an address has been written, we make it non-executable, to make sure a processor\n     with an instruction cache won't execute a stale instruction. *)\n  Fixpoint invalidateWrittenXAddrs(nBytes: nat)(addr: word)(xAddrs: XAddrs): XAddrs :=\n    match nBytes with\n    | O => xAddrs\n    | S n => removeXAddr addr (invalidateWrittenXAddrs n (word.add addr (word.of_Z 1)) xAddrs)\n    end.\n\n  Definition spec_store{p: PrimitivesParams RiscvMachine}(n: nat)\n             (riscv_store: SourceType -> word -> HList.tuple byte n -> M unit)\n             (mem_store: mem -> word -> HList.tuple byte n -> option mem)\n             : Prop :=\n    forall initialL addr v (kind: SourceType) (post: unit -> RiscvMachine -> Prop),\n      (exists m', mem_store initialL.(getMem) addr v = Some m' /\\\n                  post tt (withXAddrs (invalidateWrittenXAddrs n addr initialL.(getXAddrs))\n                          (withMem m' initialL))) \\/\n      (mem_store initialL.(getMem) addr v = None /\\\n       nonmem_store n kind addr v initialL (post tt)) ->\n      mcomp_sat (riscv_store kind addr v) initialL post.\n\n  (* primitives_params is a paramater rather than a field because Primitives lives in Prop and\n     is opaque, but the fields of primitives_params need to be visible *)\n  Class Primitives(primitives_params: PrimitivesParams RiscvMachine): Prop := {\n    mcomp_sat_ok :> mcomp_sat_spec primitives_params;\n    primitives_sane :> PrimitivesSane primitives_params;\n\n    spec_getRegister: forall (initialL: RiscvMachine) (x: Register)\n                             (post: word -> RiscvMachine -> Prop),\n        (valid_register x /\\\n         match map.get initialL.(getRegs) x with\n         | Some v => post v initialL\n         | None => forall v, is_initial_register_value v -> post v initialL\n         end) \\/\n        (x = Register0 /\\ post (word.of_Z 0) initialL) ->\n        mcomp_sat (getRegister x) initialL post;\n\n    spec_setRegister: forall initialL x v (post: unit -> RiscvMachine -> Prop),\n      (valid_register x /\\ post tt (withRegs (map.put initialL.(getRegs) x v) initialL) \\/\n       x = Register0 /\\ post tt initialL) ->\n      mcomp_sat (setRegister x v) initialL post;\n\n    spec_loadByte: spec_load 1 (Machine.loadByte (RiscvProgram := RVM)) Memory.loadByte;\n    spec_loadHalf: spec_load 2 (Machine.loadHalf (RiscvProgram := RVM)) Memory.loadHalf;\n    spec_loadWord: spec_load 4 (Machine.loadWord (RiscvProgram := RVM)) Memory.loadWord;\n    spec_loadDouble: spec_load 8 (Machine.loadDouble (RiscvProgram := RVM)) Memory.loadDouble;\n\n    spec_storeByte: spec_store 1 (Machine.storeByte (RiscvProgram := RVM)) Memory.storeByte;\n    spec_storeHalf: spec_store 2 (Machine.storeHalf (RiscvProgram := RVM)) Memory.storeHalf;\n    spec_storeWord: spec_store 4 (Machine.storeWord (RiscvProgram := RVM)) Memory.storeWord;\n    spec_storeDouble: spec_store 8 (Machine.storeDouble (RiscvProgram := RVM)) Memory.storeDouble;\n\n    spec_getPC: forall initialL (post: word -> RiscvMachine -> Prop),\n        post initialL.(getPc) initialL ->\n        mcomp_sat getPC initialL post;\n\n    spec_setPC: forall initialL v (post: unit -> RiscvMachine -> Prop),\n        post tt (withNextPc v initialL) ->\n        mcomp_sat (setPC v) initialL post;\n\n    spec_endCycleNormal: forall initialL (post: unit -> RiscvMachine -> Prop),\n        post tt (withPc     initialL.(getNextPc)\n                (withNextPc (word.add initialL.(getNextPc) (word.of_Z 4))\n                            initialL)) ->\n        mcomp_sat endCycleNormal initialL post;\n  }.\n\nEnd Primitives.\n\nArguments PrimitivesParams {_ _ _ _ _} M Machine.\n", "meta": {"author": "mit-plv", "repo": "riscv-coq", "sha": "55c9cc88a6734550bdd913bfdf482d498c6354e6", "save_path": "github-repos/coq/mit-plv-riscv-coq", "path": "github-repos/coq/mit-plv-riscv-coq/riscv-coq-55c9cc88a6734550bdd913bfdf482d498c6354e6/src/riscv/Spec/Primitives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18791314697989492}}
{"text": "(* Hendra : trim the system to contain only Arithmetic *)\n  Import JVM_Dom JVM_Prog.\n\n  Open Scope type_scope.\n  Definition JVM_InitCallState :=  JVM_Method * (JVM_OperandStack.t * JVM_LocalVar.t).\n  Definition JVM_IntraNormalState := JVM_PC * (JVM_Heap.t * JVM_OperandStack.t * JVM_LocalVar.t).\n(* DEX  Definition JVM_IntraExceptionState := JVM_Heap.t * JVM_Location. *)\n  Definition JVM_ReturnState := JVM_Heap.t * JVM_ReturnVal.\n\n\n  Inductive JVM_NormalStep (p:JVM_Program) : JVM_Method -> JVM_IntraNormalState -> JVM_IntraNormalState  -> Prop :=\n(* DEX\n  | aconst_null : forall h m pc pc' s l,\n\n    instructionAt m pc = Some (JVM_Aconst_null) ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,s,l)) (pc',(h,(Null::s),l))\n\n  | arraylength : forall h m pc pc' s l loc length tp a, \n\n    instructionAt m pc = Some (JVM_Arraylength) ->\n    next m pc = Some pc' ->\n    JVM_Heap.typeof  h loc = Some (JVM_Heap.LocationArray length tp a) ->\n\n   JVM_NormalStep p m  (pc,(h,(Ref loc::s),l)) (pc',(h,(Num (I length)::s),l))\n*)\n(*\n | checkcast1 : forall h m pc pc' s l val t,\n\n    instructionAt m pc = Some (JVM_Checkcast t) ->\n    next m pc = Some pc' ->\n    assign_compatible p h val (JVM_ReferenceType t) ->\n\n   JVM_NormalStep p m (pc,(h,(val::s),l))  (pc',(h,(val::s),l))\n*)\n  | const : forall h m pc pc' s l t z,\n\n    instructionAt m pc = Some (JVM_Const t z) ->\n    next m pc = Some pc' ->\n    (   (t=JVM_BYTE /\\ -2^7 <= z < 2^7)%Z\n     \\/ (t=JVM_SHORT /\\ -2^15 <= z < 2^15)%Z\n     \\/ (t=JVM_INT /\\ -2^31 <= z < 2^31)%Z   ) ->\n\n   JVM_NormalStep p m (pc,(h,s,l)) (pc',(h,(Num (I (Int.const z))::s),l))\n\n  | dup : forall h m pc pc' s l v,\n\n    instructionAt m pc = Some (JVM_Dup) ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v::s),l))  (pc',(h,(v::v::s),l))\n\n  | dup_x1 : forall h m pc pc' s l v1 v2,\n\n    instructionAt m pc = Some JVM_Dup_x1 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::s),l)) (pc',(h,(v1::v2::v1::s),l))\n\n  | dup_x2 : forall h m pc pc' s l v1 v2 v3,\n\n    instructionAt m pc = Some JVM_Dup_x2 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p  m (pc,(h,(v1::v2::v3::s),l))  (pc',(h,(v1::v2::v3::v1::s),l))\n\n  | dup2 : forall h m pc pc' s l v1 v2,\n\n    instructionAt m pc = Some JVM_Dup2 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::s),l)) (pc',(h,(v1::v2::v1::v2::s),l))\n\n  | dup2_x1 : forall h m pc pc' s l v1 v2 v3,\n\n    instructionAt m pc = Some JVM_Dup2_x1 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::v3::s),l)) (pc',(h,(v1::v2::v3::v1::v2::s),l))\n\n  | dup2_x2 : forall h m pc pc' s l v1 v2 v3 v4,\n\n    instructionAt m pc = Some JVM_Dup2_x2 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::v3::v4::s),l)) (pc',(h,(v1::v2::v3::v4::v1::v2::s),l))\n(* DEX\n  | getfield : forall h m pc pc' s l loc f v cn,\n\n    instructionAt m pc = Some (JVM_Getfield f) ->\n    next m pc = Some pc' ->\n    JVM_Heap.typeof h loc = Some (JVM_Heap.LocationObject cn) -> \n    defined_field p cn f ->\n    JVM_Heap.get h (JVM_Heap.DynamicField loc f) = Some v ->    \n\n   JVM_NormalStep p m (pc,(h,(Ref loc::s),l)) (pc',(h,(v::s),l))\n*)\n\n  | goto : forall h m pc s l o,\n\n    instructionAt m pc = Some (JVM_Goto o) ->\n\n   JVM_NormalStep p m (pc,(h,s,l)) (JVM_OFFSET.jump pc o,(h,s,l))\n\n  | i2b : forall h m pc pc' s l i,\n\n    instructionAt m pc = Some JVM_I2b ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (pc',(h,(Num (I (b2i (i2b i)))::s),l))\n\n  | i2s : forall h m pc pc' s l i,\n\n    instructionAt m pc = Some JVM_I2s ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l))  (pc',(h,(Num (I (s2i (i2s i)))::s),l))\n\n  | ibinop : forall h m pc pc' s l op i1 i2,\n\n    instructionAt m pc = Some (JVM_Ibinop op) ->\n    next m pc = Some pc' ->\n    (* DEX (op = DivInt \\/ op = RemInt -> ~ Int.toZ i2 = 0%Z) -> *)\n\n   JVM_NormalStep p m (pc,(h,(Num (I i2)::Num (I i1)::s),l))\n                          (pc',(h,(Num (I (SemBinopInt op i1 i2))::s),l))\n\n(* DEX\n  | if_acmp_step_jump : forall h m pc s l val2 val1 o cmp,\n      instructionAt m pc = Some (JVM_If_acmp cmp o) ->\n      SemCompRef cmp val1 val2 ->\n  (******************************************************************)\n     JVM_NormalStep p m (pc,(h,(val2:: val1::s),l))\n                                   (JVM_OFFSET.jump pc o,(h,s,l))\n\n  | if_acmp_step_continue : forall h m pc pc' s l val2 val1 o cmp,\n      instructionAt m pc = Some (JVM_If_acmp cmp o) ->\n      next m pc = Some pc' ->\n      ~ SemCompRef cmp val1 val2 ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(val2::val1::s),l)) (pc',(h,s,l))\n*)\n\n  | if_icmp_step_jump : forall h m pc s l cmp i2 i1 o,\n      instructionAt m pc = Some (JVM_If_icmp cmp o) ->\n      SemCompInt cmp (Int.toZ i1) (Int.toZ i2) ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(Num(I i2)::Num(I i1)::s),l))\n                                  (JVM_OFFSET.jump pc o,(h,s,l))\n\n  | if_icmpeq_step_continue : forall h m pc pc' s l cmp i2 i1 o,\n      instructionAt m pc = Some (JVM_If_icmp cmp o) ->\n      next m pc = Some pc' ->\n      ~ SemCompInt cmp (Int.toZ i1) (Int.toZ i2) ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(Num(I i2)::Num(I i1)::s),l))\n                                  (pc',(h,s,l))\n\n  | ifeq_step_jump : forall h m pc s l cmp i o,\n      instructionAt m pc = Some (JVM_If0 cmp o) ->\n      SemCompInt cmp (Int.toZ i) 0 ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(Num(I i)::s),l))\n                                  (JVM_OFFSET.jump pc o,(h,s,l))\n\n  | ifeq_step_continue : forall h m pc pc' s l cmp i o,\n      instructionAt m pc = Some (JVM_If0 cmp o) ->\n      next m pc = Some pc' ->\n      ~ SemCompInt cmp (Int.toZ i) 0 ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(Num(I i)::s),l)) (pc',(h,s,l))\n(* DEX\n  | ifnull_step_jump : forall h m pc s l loc o cmp,\n      instructionAt m pc = Some (JVM_Ifnull cmp o) ->\n      SemCompRef cmp loc Null ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(loc::s),l))\n                                  (JVM_OFFSET.jump pc o,(h,s,l))\n\n  | ifnull_step_continue : forall h m pc pc' s l o loc cmp,\n    instructionAt m pc = Some (JVM_Ifnull cmp o) ->\n    next m pc = Some pc' ->\n    ~ SemCompRef cmp loc Null ->\n  (******************************************************************)\n    JVM_NormalStep p m (pc,(h,(loc::s),l)) (pc',(h,s,l))\n*)\n\n  | iinc_step : forall h m pc s l pc' x z i,\n    instructionAt m pc = Some (JVM_Iinc x z) ->\n\n    next m pc = Some pc' ->\n    (-2^7 <= z < 2^7)%Z ->\n    JVM_METHOD.valid_var m x ->\n    JVM_LocalVar.get l x = Some (Num (I i)) ->\n\n   JVM_NormalStep p m (pc,(h,s,l))\n                (pc',(h,s,(JVM_LocalVar.update l x (Num (I (Int.add i (Int.const z)))))))\n\n  | ineg_step : forall h m pc s l pc' i,\n    instructionAt m pc = Some JVM_Ineg ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (pc',(h,(Num (I (Int.neg i))::s),l))\n\n(* DEX\n  | instanceof1 : forall h m pc pc' s l loc t,\n\n    instructionAt m pc = Some (JVM_Instanceof t) ->\n    next m pc = Some pc' ->\n    assign_compatible p h (Ref loc) (JVM_ReferenceType t) ->\n\n   JVM_NormalStep p m (pc,(h,(Ref loc::s),l)) (pc',(h,(Num (I (Int.const 1))::s),l))\n\n\n  | instanceof2 : forall h m pc pc' s l t v,\n\n    instructionAt m pc = Some (JVM_Instanceof t) ->\n    next m pc = Some pc' ->\n    isReference v ->\n    (~ assign_compatible p h v (JVM_ReferenceType t) \\/ v=Null) ->\n\n   JVM_NormalStep p m (pc,(h,(v::s),l)) (pc',(h,(Num (I (Int.const 0))::s),l))\n*)\n\n  | lookupswitch1 : forall h m pc s l def listkey i i' o',\n\n    instructionAt m pc = Some (JVM_Lookupswitch def listkey) ->\n\n    List.In (pair i' o')listkey ->\n    i' = Int.toZ i ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (JVM_OFFSET.jump pc o',(h,s,l))\n\n  | lookupswitch2 : forall h m pc s l def listkey i,\n\n    instructionAt m pc = Some (JVM_Lookupswitch def listkey) ->\n    (forall i' o', List.In (pair i' o')listkey ->  i' <> Int.toZ i) ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (JVM_OFFSET.jump pc def,(h,s,l))\n(* DEX\n  | new : forall h m pc pc' s l c loc h',\n\n    instructionAt m pc = Some (JVM_New c) ->\n    next m pc = Some pc' ->\n    JVM_Heap.new h p (JVM_Heap.LocationObject c) = Some (pair loc h') ->\n\n   JVM_NormalStep p m (pc,(h,s,l))\n                      (pc',(h',(Ref loc::s),l))\n\n  | newarray : forall h m pc pc' s l t i loc h',\n\n    instructionAt m pc = Some (JVM_Newarray t) ->\n    next m pc = Some pc' ->\n    (0 <= Int.toZ i)%Z -> \n    JVM_Heap.new h p (JVM_Heap.LocationArray i t (m,pc)) = Some (pair loc h') ->\n\n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l))\n                            (pc',(h',(Ref loc::s),l))\n*)\n  | nop : forall h m pc pc' s l,\n\n    instructionAt m pc = Some JVM_Nop ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,s,l)) (pc',(h,s,l))\n\n  | pop : forall h m pc pc' s l v,\n\n    instructionAt m pc = Some JVM_Pop ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v::s),l)) (pc',(h,s,l))\n\n  | pop2 : forall h m pc pc' s l v1 v2,\n\n    instructionAt m pc = Some JVM_Pop2 ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::s),l)) (pc',(h,s,l))\n(* DEX\n  | putfield : forall h m pc pc' s l f loc cn v,\n\n    instructionAt m pc = Some (JVM_Putfield f) ->\n    next m pc = Some pc' ->\n    JVM_Heap.typeof h loc = Some (JVM_Heap.LocationObject cn) -> \n    defined_field p cn f ->\n    assign_compatible p h v (JVM_FIELDSIGNATURE.type (snd f)) ->\n\n   JVM_NormalStep p m(pc,(h,(v::(Ref loc)::s),l))\n                           (pc',(JVM_Heap.update h (JVM_Heap.DynamicField loc f) v,s,l))\n*)\n  | swap : forall h m pc pc' s l v1 v2,\n\n    instructionAt m pc = Some JVM_Swap ->\n    next m pc = Some pc' ->\n\n   JVM_NormalStep p m (pc,(h,(v1::v2::s),l)) (pc',(h,(v2::v1::s),l))\n\n  | tableswitch1 : forall h m pc s l i def low high list_offset,\n\n    instructionAt m pc = Some (JVM_Tableswitch def low high list_offset) ->\n    Z_of_nat (length list_offset) = (high - low + 1)%Z ->\n    (Int.toZ i < low \\/ high < Int.toZ i)%Z ->\n   \n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (JVM_OFFSET.jump pc def,(h,s,l))\n\n  | tableswitch2 : forall h m pc s l n o i def low high list_offset,\n\n    instructionAt m pc = Some (JVM_Tableswitch def low high list_offset) ->\n    Z_of_nat (length list_offset) = (high - low + 1)%Z ->\n    (low <= Int.toZ i <= high)%Z ->\n    (Z_of_nat n = (Int.toZ i) - low)%Z ->\n    nth_error list_offset n = Some o ->\n   \n   JVM_NormalStep p m (pc,(h,(Num (I i)::s),l)) (JVM_OFFSET.jump pc o,(h,s,l))\n(*\n  | vaload : forall h m pc pc' s l loc val i length t k a,\n\n    instructionAt m pc = Some (JVM_Vaload k) ->\n    next m pc = Some pc' ->\n    JVM_Heap.typeof h loc = Some (JVM_Heap.LocationArray length t a) ->\n    compat_ArrayKind_type k t ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    JVM_Heap.get h (JVM_Heap.ArrayElement loc (Int.toZ i)) = Some val ->\n    compat_ArrayKind_value k val ->\n\n    JVM_NormalStep p m \n          (pc,(h,((Num (I i))::(Ref loc)::s),l))\n          (pc',(h,(conv_for_stack val::s),l))\n\n  | vastore : forall h m pc pc' s l loc val i length t k a,\n\n    instructionAt m pc = Some (JVM_Vastore k) ->\n    next m pc = Some pc' ->\n    JVM_Heap.typeof h loc = Some (JVM_Heap.LocationArray length t a) ->\n    assign_compatible p h val t ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k t ->\n    compat_ArrayKind_value k val ->\n\n    JVM_NormalStep p m\n         (pc,(h,(val::(Num (I i))::(Ref loc)::s),l))\n         (pc',(JVM_Heap.update h (JVM_Heap.ArrayElement loc (Int.toZ i)) (conv_for_array val t),s,l))\n*)\n  | vload : forall h m pc pc' s l x val k,\n\n    instructionAt m pc = Some (JVM_Vload k x) ->\n    next m pc = Some pc' ->\n    JVM_METHOD.valid_var m x ->\n    JVM_LocalVar.get l x = Some val ->\n    compat_ValKind_value k val -> \n\n    JVM_NormalStep p m (pc,(h,s,l)) (pc',(h,(val::s),l))\n \n  | vstore : forall h m pc pc' s l l' x v k,\n\n    instructionAt m pc = Some (JVM_Vstore k x) ->\n    next m pc = Some pc' ->\n    JVM_METHOD.valid_var m x ->\n    l' = JVM_LocalVar.update l x v ->\n    compat_ValKind_value k v ->\n\n   JVM_NormalStep p m  (pc,(h,(v::s),l)) (pc',(h,s,l'))\n.\n\n(* DEX Exception\n  Inductive JVMExceptionStep  (p:Program) : Method -> IntraNormalState -> ShortClassName -> Prop :=\n  | arraylength_NullPointerException : forall h m pc s l,\n\n    instructionAt m pc = Some Arraylength ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l))  NullPointerException\n\n  | athrow_NullPointerException : forall h m pc s l,\n\n    instructionAt m pc = Some Athrow ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l)) NullPointerException\n\n  | checkcast_ClassCastException : forall h m pc s l loc t,\n\n    instructionAt m pc = Some (Checkcast t) ->\n    ~ assign_compatible p h (Ref loc) (ReferenceType t) ->\n\n    JVMExceptionStep p m (pc,(h,(Ref loc::s),l)) ClassCastException\n\n  | getfield_NullPointerException : forall h m pc s l f ,\n\n    instructionAt m pc = Some (Getfield f) ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l)) NullPointerException\n\n | ibinop_ArithmeticException : forall h m pc s l op i1 i2,\n\n    instructionAt m pc = Some (Ibinop op) ->\n    op = DivInt \\/ op = RemInt ->\n    Int.toZ i2 = 0%Z ->\n\n    JVMExceptionStep p m (pc,(h,(Num (I i2)::Num (I i1)::s),l)) ArithmeticException\n\n  | invokevirtual_NullPointerException : forall h m pc s l mid args,\n\n    instructionAt m pc = Some (Invokevirtual mid) ->\n    length args = length (METHODSIGNATURE.parameters (snd mid)) ->\n\n    JVMExceptionStep p m (pc,(h,(args++Null::s),l)) NullPointerException\n\n  | newarray_NegativeArraySizeException : forall h m pc s l t i,\n\n    instructionAt m pc = Some (Newarray t) ->\n    (~ 0 <= Int.toZ i)%Z ->\n\n    JVMExceptionStep p m (pc,(h,(Num (I i)::s),l)) NegativeArraySizeException\n\n  | putfield_NullPointerException : forall h m pc s l f v,\n\n    instructionAt m pc = Some (Putfield f) ->\n   \n    JVMExceptionStep p m (pc,(h,(v::Null::s),l)) NullPointerException\n\n  | vaload_NullPointerException : forall h m pc s l i k,\n\n    instructionAt m pc = Some (Vaload k) ->\n\n    JVMExceptionStep p m (pc,(h,((Num (I i))::Null::s),l)) NullPointerException\n\n  | vaload_ArrayIndexOutOfBoundsException : forall h m pc s l loc i length t k a,\n\n    instructionAt m pc = Some (Vaload k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    compat_ArrayKind_type k t ->\n    (~ 0 <= Int.toZ i < Int.toZ length)%Z ->\n\n    JVMExceptionStep p m (pc,(h,((Num (I i))::(Ref loc)::s),l)) ArrayIndexOutOfBoundsException\n\n  | vastore_NullPointerException : forall h m pc s l val i k,\n\n    instructionAt m pc = Some (Vastore k) ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::Null::s),l)) NullPointerException\n\n  | vastore_ArrayIndexOutOfBoundsException : forall h m pc s l loc val i t length k a,\n\n    instructionAt m pc = Some (Vastore k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    (~ 0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k t ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::(Ref loc)::s),l)) ArrayIndexOutOfBoundsException\n\n  | vastore_ArrayStoreException : forall h m pc s l loc val i t k length a,\n\n    instructionAt m pc = Some (Vastore k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    ~ assign_compatible p h val t ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k t ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::(Ref loc)::s),l)) ArrayStoreException\n.\n\n\n  Inductive ExceptionStep (p:Program) : Method -> IntraNormalState -> IntraExceptionState -> Prop :=\n  | athrow : forall h m pc s l loc cn,\n\n    instructionAt m pc = Some Athrow ->\n    Heap.typeof h loc = Some (Heap.LocationObject cn) ->\n    subclass_name p cn javaLangThrowable ->\n    ExceptionStep p m (pc,(h,(Ref loc::s),l)) (h,loc)\n\n  | jvm_exception : forall h m pc s l h' loc (e:ShortClassName),\n\n    JVMExceptionStep p m (pc,(h,s,l)) e ->\n    Heap.new h p (Heap.LocationObject (javaLang,e)) = Some (loc,h') ->\n\n    ExceptionStep p m (pc,(h,s,l)) (h',loc).\n*)\n\n(* DEX Method\n  Inductive JVM_CallStep (p:JVM_Program) : JVM_Method -> JVM_IntraNormalState -> JVM_InitCallState -> Prop :=\n  | invokestatic : forall h m pc s l mid M args bM,\n\n    instructionAt m pc = Some (JVM_Invokestatic mid) ->\n    findMethod p mid = Some M ->\n    JVM_METHOD.isNative M = false ->\n    length args = length (JVM_METHODSIGNATURE.parameters (snd mid)) ->\n    JVM_METHOD.body M = Some bM ->\n    JVM_METHOD.isStatic M = true ->\n    \n    JVM_CallStep p m (pc,(h,(args++s),l)) (M,(s,(stack2localvar (args++s) (length args))))\n\n  | invokevirtual : forall h m pc s l mid cn M args loc cl bM,\n\n    instructionAt m pc = Some (JVM_Invokevirtual (cn,mid)) ->\n    lookup p cn mid (pair cl M) ->\n    JVM_Heap.typeof h loc = Some (JVM_Heap.LocationObject cn) ->\n    length args = length (JVM_METHODSIGNATURE.parameters mid) ->\n    JVM_METHOD.body M = Some bM ->\n    JVM_METHOD.isStatic M = false ->\n \n    JVM_CallStep p m (pc,(h,(args++(Ref loc)::s),l)) (M,(s,stack2localvar (args++(Ref loc)::s)  (1+(length args)))).\n*)\n\n  Inductive JVM_ReturnStep (p:JVM_Program) : JVM_Method -> JVM_IntraNormalState -> JVM_ReturnState -> Prop :=\n  | void_return : forall h m pc s l,\n\n    instructionAt m pc = Some JVM_Return ->\n    JVM_METHODSIGNATURE.result (JVM_METHOD.signature m) = None ->\n\n    JVM_ReturnStep p m  (pc,(h,s,l)) (h, Normal None)\n  | vreturn : forall h m pc s l val t k,\n\n    instructionAt m pc = Some (JVM_Vreturn k) ->\n    JVM_METHODSIGNATURE.result (JVM_METHOD.signature m) = Some t ->\n    assign_compatible p h val t ->\n    compat_ValKind_value k val ->\n\n    JVM_ReturnStep p m (pc,(h,(val::s),l)) (h,Normal (Some val))\n.\n\n(* DEX Method\n  Inductive JVM_call_and_return : \n    JVM_Method -> JVM_IntraNormalState -> JVM_InitCallState -> JVM_IntraNormalState -> JVM_ReturnState -> JVM_IntraNormalState -> Prop :=\n  | call_and_return_void : forall m pc h s l m' l' bm' h'' s' pc',\n      next m pc = Some pc' -> \n      JVM_METHOD.body m' = Some bm' ->\n      JVM_call_and_return\n                 m\n                 (pc,(h,s,l))\n                 (m',(s',l'))\n                  (JVM_BYTECODEMETHOD.firstAddress bm',(h,JVM_OperandStack.empty,l'))\n                 (h'', Normal None) \n                 (pc',(h'',s',l))\n  | call_and_return_value : forall m pc h s l m' l' bm' h'' v s' pc',\n      next m pc = Some pc' -> \n      JVM_METHOD.body m' = Some bm' ->\n      JVM_call_and_return\n                 m\n                 (pc,(h,s,l))\n                 (m',(s',l') )\n                 (JVM_BYTECODEMETHOD.firstAddress bm',(h,JVM_OperandStack.empty,l'))\n                 (h'', Normal (Some v)) \n                 (pc',(h'',v::s',l)).\n*)\n\n(* DEX Exception\n  Inductive call_and_return_exception : Method -> IntraNormalState -> InitCallState -> IntraNormalState -> ReturnState -> IntraExceptionState -> Prop :=\n  | call_and_return_exception_def : forall m pc h s l m' l' bm' h'' s' loc,\n      METHOD.body m' = Some bm' ->\n      call_and_return_exception\n                 m\n                 (pc,(h,s,l))\n                 (m',(s',l'))\n                 (BYTECODEMETHOD.firstAddress bm',(h,OperandStack.empty,l'))\n                 (h'',Exception loc) \n                 (h'',loc).\n*)\n  Inductive JVM_exec_intra (p:JVM_Program) (m:JVM_Method) : JVM_IntraNormalState -> JVM_IntraNormalState -> Prop :=\n  | exec_intra_normal : forall s1 s2,\n     JVM_NormalStep p m s1 s2 ->\n     JVM_exec_intra p m s1 s2\n(* DEX Exception\n  | exec_exception : forall pc1 h1 h2 loc2 s1 l1 pc',\n   ExceptionStep p m (pc1,(h1,s1,l1)) (h2,loc2) ->\n   CaughtException p m (pc1,h2,loc2) pc' ->\n   exec_intra p m (pc1,(h1,s1,l1)) (pc',(h2,Ref loc2::OperandStack.empty,l1))*).\n\n  Inductive JVM_exec_return (p:JVM_Program) (m:JVM_Method) : JVM_IntraNormalState -> JVM_ReturnState -> Prop :=\n  | exec_return_normal : forall s h ov,\n     JVM_ReturnStep p m s (h,Normal ov) ->\n     JVM_exec_return p m s (h,Normal ov)\n(* DEX Exception\n | exec_return_exception : forall pc1 h1 h2 loc2 s1 l1,\n     ExceptionStep p m (pc1,(h1,s1,l1)) (h2,loc2) ->\n     UnCaughtException  p m (pc1,h2,loc2) ->\n     exec_return p m (pc1,(h1,s1,l1)) (h2,Exception loc2)\n*).\n\n(* Method\n  Inductive JVM_exec_call (p:JVM_Program) (m:JVM_Method) :\n   JVM_IntraNormalState -> JVM_ReturnState -> JVM_Method  -> JVM_IntraNormalState -> JVM_IntraNormalState+JVM_ReturnState -> Prop :=\n | exec_call_normal : forall m2 pc1 pc1' h1 s1 l1 os l2 h2 bm2 ov,\n     JVM_CallStep p m (pc1,(h1,s1,l1 )) (m2,(os,l2)) ->\n     JVM_METHOD.body m2 = Some bm2 ->\n     next m pc1 = Some pc1' ->\n     JVM_exec_call p m\n        (pc1,(h1,s1,l1))\n        (h2,Normal ov)\n        m2\n        (JVM_BYTECODEMETHOD.firstAddress bm2,(h1,JVM_OperandStack.empty,l2))\n        (inl _ (pc1',(h2,cons_option ov os,l1)))\n(* DEX Exception\n | exec_call_caught : forall m2 pc1 pc1' h1 s1 l1 os l2 h2 loc bm2,\n     CallStep p m (pc1,(h1,s1,l1 )) (m2,(os,l2)) ->\n     METHOD.body m2 = Some bm2 ->\n     CaughtException p m (pc1, h2, loc) pc1' ->\n     exec_call p m\n        (pc1,(h1,s1,l1))\n        (h2,Exception loc)\n        m2\n        (BYTECODEMETHOD.firstAddress bm2,(h1,OperandStack.empty,l2))\n        (inl _(pc1',(h2,Ref loc::nil,l1)))\n | exec_call_uncaught : forall m2 pc1 h1 s1 l1 os l2 h2 loc bm2,\n     CallStep p m (pc1,(h1,s1,l1 )) (m2,(os,l2)) ->\n     METHOD.body m2 = Some bm2 ->\n     UnCaughtException p m (pc1, h2, loc)  ->\n     exec_call p m\n       (pc1,(h1,s1,l1))\n       (h2,Exception loc)\n       m2\n       (BYTECODEMETHOD.firstAddress bm2,(h1,OperandStack.empty,l2))\n       (inr _ (h2,Exception loc))*) .\n*)\n\n Inductive JVM_IntraStep (p:JVM_Program) : \n    JVM_Method -> JVM_IntraNormalState -> JVM_IntraNormalState + JVM_ReturnState -> Prop :=\n  | IntraStep_res :forall m s ret,\n     JVM_exec_return p m s ret ->\n     JVM_IntraStep p m s (inr _ ret)\n  | IntraStep_intra_step:forall m s1 s2,\n     JVM_exec_intra p m s1 s2 ->\n     JVM_IntraStep p m s1 (inl _ s2) \n(* DEX Method\n  | IntraStep_call :forall m m' s1 s' ret' r,\n     JVM_exec_call p m s1 ret' m' s' r ->\n     TransStep_l (JVM_IntraStep p m') s' (inr _ ret') ->\n     JVM_IntraStep p m s1 r*).\n \n Definition JVM_IntraStepStar p m s r := TransStep_l (JVM_IntraStep p m) s r.\n\n Definition JVM_IntraStepStar_intra p m s s' := JVM_IntraStepStar p m s (inl _ s').\n\n Definition JVM_BigStep  p m s ret := JVM_IntraStepStar p m s (inr _ ret).\n\n Inductive JVM_ReachableStep (P:JVM_Program) : \n      (JVM_Method*JVM_IntraNormalState)->(JVM_Method*JVM_IntraNormalState) ->Prop :=\n   | ReachableIntra : forall M s s', \n       JVM_IntraStep P M s (inl _ s') ->\n       JVM_ReachableStep P (M,s) (M,s')\n(* DEX Method\n   | Reachable_invS : forall M pc h os l M' os' l' bm',\n       JVM_CallStep P M (pc,(h,os,l)) (M',(os',l')) ->\n       JVM_METHOD.body M' = Some bm' ->\n       JVM_ReachableStep P (M, (pc,(h,os,l)))\n         (M', (JVM_BYTECODEMETHOD.firstAddress bm',(h,JVM_OperandStack.empty,l')))*).\n\n Definition JVM_Reachable P M s s' := \n   exists M',  ClosReflTrans (JVM_ReachableStep P) (M,s) (M',s').\n", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/JVM_BigStepLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.18771291720497596}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Preamble *)\n\nRequire String BitTerminationProofs.\nImport String.StringSyntax.\n\n(* Converted imports: *)\n\nRequire Coq.Init.Peano.\nRequire Coq.NArith.BinNat.\nRequire Coq.Numbers.BinNums.\nRequire Data.Bits.\nRequire Data.Foldable.\nRequire Data.Maybe.\nRequire Data.Tuple.\nRequire GHC.Base.\nRequire GHC.Num.\nRequire HsToCoq.Err.\nRequire HsToCoq.Wf.\nRequire Utils.Containers.Internal.BitUtil.\nImport Data.Bits.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nDefinition Prefix :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Nat :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Mask :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Key :=\n  Coq.Numbers.BinNums.N%type.\n\nDefinition BitMap :=\n  Coq.Numbers.BinNums.N.\n\nInductive IntSet : Type :=\n  | Bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet\n  | Tip : Prefix -> BitMap -> IntSet\n  | Nil : IntSet.\n\nInductive Stack : Type :=\n  | Push : Prefix -> IntSet -> Stack -> Stack\n  | Nada : Stack.\n\nInstance Default__IntSet : HsToCoq.Err.Default IntSet :=\n  HsToCoq.Err.Build_Default _ Nil.\n\nInstance Default__Stack : HsToCoq.Err.Default Stack :=\n  HsToCoq.Err.Build_Default _ Nada.\n\n(* Midamble *)\n\n(** Additional definitions for termination proof *)\n\nFixpoint size_nat (t : IntSet) : nat :=\n  match t with\n  | Bin _ _ l r => S (size_nat l + size_nat r)%nat\n  | Tip _ bm => 0\n  | Nil => 0\n  end.\n\nRequire Omega.\nLtac termination_by_omega :=\n  Coq.Program.Tactics.program_simpl;\n  simpl;Omega.omega.\n\n\nRequire Import Coq.NArith.NArith.\n(* Z.ones 6 = 64-1 *)\n(* Definition suffixBitMask := Coq.NArith.BinNat.N.ones 6%N. *)\n\n(* Converted value declarations: *)\n\nDefinition branchMask : Prefix -> Prefix -> Mask :=\n  fun p1 p2 =>\n    Coq.NArith.BinNat.N.pow 2 (Coq.NArith.BinNat.N.log2 (Coq.NArith.BinNat.N.lxor p1\n                                                                                  p2)).\n\nDefinition maskW : Nat -> Nat -> Prefix :=\n  fun i m => Coq.NArith.BinNat.N.ldiff i (2 * m - 1 % N).\n\nDefinition mask : Coq.Numbers.BinNums.N -> Mask -> Prefix :=\n  fun i m => maskW (i) (m).\n\nDefinition zero : Coq.Numbers.BinNums.N -> Mask -> bool :=\n  fun i m => ((i) Data.Bits..&.(**) (m)) GHC.Base.== #0.\n\nDefinition link : Prefix -> IntSet -> Prefix -> IntSet -> IntSet :=\n  fun p1 t1 p2 t2 =>\n    let m := branchMask p1 p2 in\n    let p := mask p1 m in if zero p1 m : bool then Bin p m t1 t2 else Bin p m t2 t1.\n\nDefinition nomatch : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base./= p.\n\nFixpoint insertBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n  : IntSet\n  := match arg_0__, arg_1__, arg_2__ with\n     | kx, bm, (Bin p m l r as t) =>\n         if nomatch kx p m : bool then link kx (Tip kx bm) p t else\n         if zero kx m : bool then Bin p m (insertBM kx bm l) r else\n         Bin p m l (insertBM kx bm r)\n     | kx, bm, (Tip kx' bm' as t) =>\n         if kx' GHC.Base.== kx : bool then Tip kx' (bm Data.Bits..|.(**) bm') else\n         link kx (Tip kx bm) kx' t\n     | kx, bm, Nil => Tip kx bm\n     end.\n\nDefinition shorter : Mask -> Mask -> bool :=\n  fun m1 m2 => (m1) GHC.Base.> (m2).\n\nProgram Fixpoint union (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__ +\n                        size_nat arg_1__)} : IntSet\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n         let union2 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then link p1 t1 p2 t2 else\n           if Bool.Sumbool.sumbool_of_bool (zero p1 m2)\n           then Bin p2 m2 (union t1 l2) r2 else\n           Bin p2 m2 l2 (union t1 r2) in\n         let union1 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then link p1 t1 p2 t2 else\n           if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n           then Bin p1 m1 (union l1 t2) r1 else\n           Bin p1 m1 l1 (union r1 t2) in\n         if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then union1 else\n         if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then union2 else\n         if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n         then Bin p1 m1 (union l1 l2) (union r1 r2) else\n         link p1 t1 p2 t2\n     | (Bin _ _ _ _ as t), Tip kx bm => insertBM kx bm t\n     | (Bin _ _ _ _ as t), Nil => t\n     | Tip kx bm, t => insertBM kx bm t\n     | Nil, t => t\n     end.\nSolve Obligations with (termination_by_omega).\n\nLocal Definition Semigroup__IntSet_op_zlzlzgzg__ : IntSet -> IntSet -> IntSet :=\n  union.\n\nProgram Instance Semigroup__IntSet : GHC.Base.Semigroup IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__IntSet_op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__IntSet_mappend : IntSet -> IntSet -> IntSet :=\n  _GHC.Base.<<>>_.\n\nDefinition empty : IntSet :=\n  Nil.\n\nDefinition unions {f : Type -> Type} `{Data.Foldable.Foldable f}\n   : f IntSet -> IntSet :=\n  fun xs => Data.Foldable.foldl' union empty xs.\n\nLocal Definition Monoid__IntSet_mconcat : list IntSet -> IntSet :=\n  unions.\n\nLocal Definition Monoid__IntSet_mempty : IntSet :=\n  empty.\n\nProgram Instance Monoid__IntSet : GHC.Base.Monoid IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__IntSet_mappend ;\n           GHC.Base.mconcat__ := Monoid__IntSet_mconcat ;\n           GHC.Base.mempty__ := Monoid__IntSet_mempty |}.\n\n(* Skipping all instances of class `Data.Data.Data', including\n   `Data.IntSet.Internal.Data__IntSet' *)\n\n(* Skipping all instances of class `GHC.Exts.IsList', including\n   `Data.IntSet.Internal.IsList__IntSet' *)\n\nFixpoint equal (arg_0__ arg_1__ : IntSet) : bool\n  := match arg_0__, arg_1__ with\n     | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n         andb (m1 GHC.Base.== m2) (andb (p1 GHC.Base.== p2) (andb (equal l1 l2) (equal r1\n                                                                   r2)))\n     | Tip kx1 bm1, Tip kx2 bm2 => andb (kx1 GHC.Base.== kx2) (bm1 GHC.Base.== bm2)\n     | Nil, Nil => true\n     | _, _ => false\n     end.\n\nLocal Definition Eq___IntSet_op_zeze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => equal t1 t2.\n\nFixpoint nequal (arg_0__ arg_1__ : IntSet) : bool\n  := match arg_0__, arg_1__ with\n     | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n         orb (m1 GHC.Base./= m2) (orb (p1 GHC.Base./= p2) (orb (nequal l1 l2) (nequal r1\n                                                                r2)))\n     | Tip kx1 bm1, Tip kx2 bm2 => orb (kx1 GHC.Base./= kx2) (bm1 GHC.Base./= bm2)\n     | Nil, Nil => false\n     | _, _ => true\n     end.\n\nLocal Definition Eq___IntSet_op_zsze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => nequal t1 t2.\n\nProgram Instance Eq___IntSet : GHC.Base.Eq_ IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___IntSet_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___IntSet_op_zsze__ |}.\n\nDefinition indexOfTheOnlyBit :=\n  fun x => Coq.NArith.BinNat.N.log2 x.\n\nDefinition revNat : Nat -> Nat :=\n  fun x1 =>\n    let 'x2 := ((Utils.Containers.Internal.BitUtil.shiftRL x1 #1) Data.Bits..&.(**)\n                  #6148914691236517205) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x1 Data.Bits..&.(**)\n                                                             #6148914691236517205) #1) in\n    let 'x3 := ((Utils.Containers.Internal.BitUtil.shiftRL x2 #2) Data.Bits..&.(**)\n                  #3689348814741910323) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x2 Data.Bits..&.(**)\n                                                             #3689348814741910323) #2) in\n    let 'x4 := ((Utils.Containers.Internal.BitUtil.shiftRL x3 #4) Data.Bits..&.(**)\n                  #1085102592571150095) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x3 Data.Bits..&.(**)\n                                                             #1085102592571150095) #4) in\n    let 'x5 := ((Utils.Containers.Internal.BitUtil.shiftRL x4 #8) Data.Bits..&.(**)\n                  #71777214294589695) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x4 Data.Bits..&.(**)\n                                                             #71777214294589695) #8) in\n    let 'x6 := ((Utils.Containers.Internal.BitUtil.shiftRL x5 #16) Data.Bits..&.(**)\n                  #281470681808895) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x5 Data.Bits..&.(**)\n                                                             #281470681808895) #16) in\n    (Utils.Containers.Internal.BitUtil.shiftRL x6 #32) Data.Bits..|.(**)\n    (Utils.Containers.Internal.BitUtil.shiftLL x6 #32).\n\nDefinition revNatSafe n :=\n  Coq.NArith.BinNat.N.modulo (revNat n) (Coq.NArith.BinNat.N.pow 2 64).\n\nProgram Definition foldrBits {a}\n   : Coq.Numbers.BinNums.N ->\n     (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n  fun prefix f z bitmap =>\n    let go :=\n      HsToCoq.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                           Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                           match arg_0__, arg_1__ with\n                           | num_2__, acc =>\n                               if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                               match arg_0__, arg_1__ with\n                               | bm, acc =>\n                                   let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                   let bi := indexOfTheOnlyBit bitmask in\n                                   go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                      GHC.Num.-\n                                                                      bi)) acc)\n                               end\n                           end) in\n    go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldr {b : Type} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Nil => z'\n         | z', Tip kx bm => foldrBits kx f z' bm\n         | z', Bin _ _ l r => go (go z' r) l\n         end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nDefinition toAscList : IntSet -> list Key :=\n  foldr cons nil.\n\nLocal Definition Ord__IntSet_compare : IntSet -> IntSet -> comparison :=\n  fun s1 s2 => GHC.Base.compare (toAscList s1) (toAscList s2).\n\nLocal Definition Ord__IntSet_op_zl__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Lt.\n\nLocal Definition Ord__IntSet_op_zlze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Gt.\n\nLocal Definition Ord__IntSet_op_zg__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Gt.\n\nLocal Definition Ord__IntSet_op_zgze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Lt.\n\nLocal Definition Ord__IntSet_max : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__IntSet_min : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__IntSet : GHC.Base.Ord IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zl____ := Ord__IntSet_op_zl__ ;\n           GHC.Base.op_zlze____ := Ord__IntSet_op_zlze__ ;\n           GHC.Base.op_zg____ := Ord__IntSet_op_zg__ ;\n           GHC.Base.op_zgze____ := Ord__IntSet_op_zgze__ ;\n           GHC.Base.compare__ := Ord__IntSet_compare ;\n           GHC.Base.max__ := Ord__IntSet_max ;\n           GHC.Base.min__ := Ord__IntSet_min |}.\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Data.IntSet.Internal.Show__IntSet' *)\n\n(* Skipping all instances of class `GHC.Read.Read', including\n   `Data.IntSet.Internal.Read__IntSet' *)\n\n(* Skipping all instances of class `Control.DeepSeq.NFData', including\n   `Data.IntSet.Internal.NFData__IntSet' *)\n\n(* Skipping definition `Data.IntSet.Internal.natFromInt' *)\n\n(* Skipping definition `Data.IntSet.Internal.intFromNat' *)\n\nDefinition bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__, arg_1__, arg_2__, arg_3__ with\n    | _, _, l, Nil => l\n    | _, _, Nil, r => r\n    | p, m, l, r => Bin p m l r\n    end.\n\nDefinition tip : Prefix -> BitMap -> IntSet :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | _, num_2__ =>\n        if num_2__ GHC.Base.== #0 : bool then Nil else\n        match arg_0__, arg_1__ with\n        | kx, bm => Tip kx bm\n        end\n    end.\n\nFixpoint deleteBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n  : IntSet\n  := match arg_0__, arg_1__, arg_2__ with\n     | kx, bm, (Bin p m l r as t) =>\n         if nomatch kx p m : bool then t else\n         if zero kx m : bool then bin p m (deleteBM kx bm l) r else\n         bin p m l (deleteBM kx bm r)\n     | kx, bm, (Tip kx' bm' as t) =>\n         if kx' GHC.Base.== kx : bool\n         then tip kx (Data.Bits.xor bm' (bm' Data.Bits..&.(**) bm)) else\n         t\n     | _, _, Nil => Nil\n     end.\n\nProgram Fixpoint difference (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                             arg_0__ +\n                             size_nat arg_1__)} : IntSet\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n         let difference2 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then t1 else\n           if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then difference t1 l2 else\n           difference t1 r2 in\n         let difference1 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then t1 else\n           if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n           then bin p1 m1 (difference l1 t2) r1 else\n           bin p1 m1 l1 (difference r1 t2) in\n         if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then difference1 else\n         if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then difference2 else\n         if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n         then bin p1 m1 (difference l1 l2) (difference r1 r2) else\n         t1\n     | (Bin _ _ _ _ as t), Tip kx bm => deleteBM kx bm t\n     | (Bin _ _ _ _ as t), Nil => t\n     | (Tip kx bm as t1), t2 =>\n         let fix differenceTip arg_12__\n           := match arg_12__ with\n              | Bin p2 m2 l2 r2 =>\n                  if Bool.Sumbool.sumbool_of_bool (nomatch kx p2 m2) then t1 else\n                  if Bool.Sumbool.sumbool_of_bool (zero kx m2) then differenceTip l2 else\n                  differenceTip r2\n              | Tip kx2 bm2 =>\n                  if Bool.Sumbool.sumbool_of_bool (kx GHC.Base.== kx2)\n                  then tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**) bm2)) else\n                  t1\n              | Nil => t1\n              end in\n         differenceTip t2\n     | Nil, _ => Nil\n     end.\nSolve Obligations with (termination_by_omega).\n\nDefinition op_zrzr__ : IntSet -> IntSet -> IntSet :=\n  fun m1 m2 => difference m1 m2.\n\nNotation \"'_\\\\_'\" := (op_zrzr__).\n\nInfix \"\\\\\" := (_\\\\_) (at level 99).\n\n(* Skipping definition `Data.IntSet.Internal.fromListConstr' *)\n\n(* Skipping definition `Data.IntSet.Internal.intSetDataType' *)\n\nDefinition null : IntSet -> bool :=\n  fun arg_0__ => match arg_0__ with | Nil => true | _ => false end.\n\nDefinition size : IntSet -> Coq.Numbers.BinNums.N :=\n  let fix go arg_0__ arg_1__\n    := match arg_0__, arg_1__ with\n       | acc, Bin _ _ l r => go (go acc l) r\n       | acc, Tip _ bm =>\n           acc GHC.Num.+ Utils.Containers.Internal.BitUtil.bitcount #0 bm\n       | acc, Nil => acc\n       end in\n  go #0.\n\nDefinition bitmapOfSuffix : Coq.Numbers.BinNums.N -> BitMap :=\n  fun s => Utils.Containers.Internal.BitUtil.shiftLL #1 s.\n\nDefinition suffixBitMask :=\n  Coq.NArith.BinNat.N.ones 6.\n\nDefinition suffixOf : Coq.Numbers.BinNums.N -> Coq.Numbers.BinNums.N :=\n  fun x => x Data.Bits..&.(**) suffixBitMask.\n\nDefinition bitmapOf : Coq.Numbers.BinNums.N -> BitMap :=\n  fun x => bitmapOfSuffix (suffixOf x).\n\nDefinition prefixOf : Coq.Numbers.BinNums.N -> Prefix :=\n  fun x => Coq.NArith.BinNat.N.ldiff x suffixBitMask.\n\nDefinition member : Key -> IntSet -> bool :=\n  fun x =>\n    let fix go arg_0__\n      := match arg_0__ with\n         | Bin p m l r =>\n             if nomatch x p m : bool then false else\n             if zero x m : bool then go l else\n             go r\n         | Tip y bm =>\n             andb (prefixOf x GHC.Base.== y) ((bitmapOf x Data.Bits..&.(**) bm) GHC.Base./=\n                   #0)\n         | Nil => false\n         end in\n    go.\n\nDefinition notMember : Key -> IntSet -> bool :=\n  fun k => negb GHC.Base.\u2218 member k.\n\nDefinition highestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.highestBitMask x).\n\nFixpoint unsafeFindMax (arg_0__ : IntSet) : option Key\n  := match arg_0__ with\n     | Nil => None\n     | Tip kx bm => Some (kx GHC.Num.+ highestBitSet bm)\n     | Bin _ _ _ r => unsafeFindMax r\n     end.\n\nDefinition lookupLT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | def, Bin p m l r =>\n             if nomatch x p m : bool\n             then if x GHC.Base.< p : bool\n                  then unsafeFindMax def\n                  else unsafeFindMax r else\n             if zero x m : bool then go def l else\n             go l r\n         | def, Tip kx bm =>\n             let maskLT := (bitmapOf x GHC.Num.- #1) Data.Bits..&.(**) bm in\n             if prefixOf x GHC.Base.> kx : bool\n             then Some (kx GHC.Num.+ highestBitSet bm) else\n             if andb (prefixOf x GHC.Base.== kx) (maskLT GHC.Base./= #0) : bool\n             then Some (kx GHC.Num.+ highestBitSet maskLT) else\n             unsafeFindMax def\n         | def, Nil => unsafeFindMax def\n         end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\n(* Skipping definition `Utils.Containers.Internal.BitUtil.lowestBitMask' *)\n\nDefinition lowestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.lowestBitMask x).\n\nFixpoint unsafeFindMin (arg_0__ : IntSet) : option Key\n  := match arg_0__ with\n     | Nil => None\n     | Tip kx bm => Some (kx GHC.Num.+ lowestBitSet bm)\n     | Bin _ _ l _ => unsafeFindMin l\n     end.\n\nDefinition lookupGT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | def, Bin p m l r =>\n             if nomatch x p m : bool\n             then if x GHC.Base.< p : bool\n                  then unsafeFindMin l\n                  else unsafeFindMin def else\n             if zero x m : bool then go r l else\n             go def r\n         | def, Tip kx bm =>\n             let maskGT :=\n               (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                          (Coq.NArith.BinNat.N.pred (Utils.Containers.Internal.BitUtil.shiftLL (bitmapOf\n                                                                                                                x) #1)))\n               Data.Bits..&.(**)\n               bm in\n             if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n             if andb (prefixOf x GHC.Base.== kx) (maskGT GHC.Base./= #0) : bool\n             then Some (kx GHC.Num.+ lowestBitSet maskGT) else\n             unsafeFindMin def\n         | def, Nil => unsafeFindMin def\n         end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupLE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | def, Bin p m l r =>\n             if nomatch x p m : bool\n             then if x GHC.Base.< p : bool\n                  then unsafeFindMax def\n                  else unsafeFindMax r else\n             if zero x m : bool then go def l else\n             go l r\n         | def, Tip kx bm =>\n             let maskLE :=\n               ((Utils.Containers.Internal.BitUtil.shiftLL (bitmapOf x) #1) GHC.Num.- #1)\n               Data.Bits..&.(**)\n               bm in\n             if prefixOf x GHC.Base.> kx : bool\n             then Some (kx GHC.Num.+ highestBitSet bm) else\n             if andb (prefixOf x GHC.Base.== kx) (maskLE GHC.Base./= #0) : bool\n             then Some (kx GHC.Num.+ highestBitSet maskLE) else\n             unsafeFindMax def\n         | def, Nil => unsafeFindMax def\n         end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupGE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | def, Bin p m l r =>\n             if nomatch x p m : bool\n             then if x GHC.Base.< p : bool\n                  then unsafeFindMin l\n                  else unsafeFindMin def else\n             if zero x m : bool then go r l else\n             go def r\n         | def, Tip kx bm =>\n             let maskGE :=\n               (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                          (Coq.NArith.BinNat.N.pred (bitmapOf x))) Data.Bits..&.(**)\n               bm in\n             if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n             if andb (prefixOf x GHC.Base.== kx) (maskGE GHC.Base./= #0) : bool\n             then Some (kx GHC.Num.+ lowestBitSet maskGE) else\n             unsafeFindMin def\n         | def, Nil => unsafeFindMin def\n         end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition singleton : Key -> IntSet :=\n  fun x => Tip (prefixOf x) (bitmapOf x).\n\nDefinition insert : Key -> IntSet -> IntSet :=\n  fun x => insertBM (prefixOf x) (bitmapOf x).\n\nDefinition delete : Key -> IntSet -> IntSet :=\n  fun x => deleteBM (prefixOf x) (bitmapOf x).\n\nProgram Fixpoint intersection (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                               arg_0__ +\n                               size_nat arg_1__)} : IntSet\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n         let intersection2 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then Nil else\n           if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then intersection t1 l2 else\n           intersection t1 r2 in\n         let intersection1 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then Nil else\n           if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then intersection l1 t2 else\n           intersection r1 t2 in\n         if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then intersection1 else\n         if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then intersection2 else\n         if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n         then bin p1 m1 (intersection l1 l2) (intersection r1 r2) else\n         Nil\n     | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n         let fix intersectBM arg_11__\n           := match arg_11__ with\n              | Bin p1 m1 l1 r1 =>\n                  if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then Nil else\n                  if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then intersectBM l1 else\n                  intersectBM r1\n              | Tip kx1 bm1 =>\n                  if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                  then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                  Nil\n              | Nil => Nil\n              end in\n         intersectBM t1\n     | Bin _ _ _ _, Nil => Nil\n     | Tip kx1 bm1, t2 =>\n         let fix intersectBM arg_18__\n           := match arg_18__ with\n              | Bin p2 m2 l2 r2 =>\n                  if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then Nil else\n                  if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then intersectBM l2 else\n                  intersectBM r2\n              | Tip kx2 bm2 =>\n                  if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                  then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                  Nil\n              | Nil => Nil\n              end in\n         intersectBM t2\n     | Nil, _ => Nil\n     end.\nSolve Obligations with (termination_by_omega).\n\nFixpoint subsetCmp (arg_0__ arg_1__ : IntSet) : comparison\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n         let subsetCmpEq :=\n           match pair (subsetCmp l1 l2) (subsetCmp r1 r2) with\n           | pair Gt _ => Gt\n           | pair _ Gt => Gt\n           | pair Eq Eq => Eq\n           | _ => Lt\n           end in\n         let subsetCmpLt :=\n           if nomatch p1 p2 m2 : bool then Gt else\n           if zero p1 m2 : bool then subsetCmp t1 l2 else\n           subsetCmp t1 r2 in\n         if shorter m1 m2 : bool then Gt else\n         if shorter m2 m1 : bool\n         then match subsetCmpLt with\n              | Gt => Gt\n              | _ => Lt\n              end else\n         if p1 GHC.Base.== p2 : bool then subsetCmpEq else\n         Gt\n     | _, _ =>\n         match arg_0__, arg_1__ with\n         | Bin _ _ _ _, _ => Gt\n         | Tip kx1 bm1, Tip kx2 bm2 =>\n             if kx1 GHC.Base./= kx2 : bool then Gt else\n             if bm1 GHC.Base.== bm2 : bool then Eq else\n             if Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 : bool\n             then Lt else\n             Gt\n         | (Tip kx _ as t1), Bin p m l r =>\n             if nomatch kx p m : bool then Gt else\n             if zero kx m : bool then match subsetCmp t1 l with | Gt => Gt | _ => Lt end else\n             match subsetCmp t1 r with\n             | Gt => Gt\n             | _ => Lt\n             end\n         | Tip _ _, Nil => Gt\n         | Nil, Nil => Eq\n         | Nil, _ => Lt\n         end\n     end.\n\nDefinition isProperSubsetOf : IntSet -> IntSet -> bool :=\n  fun t1 t2 => match subsetCmp t1 t2 with | Lt => true | _ => false end.\n\nDefinition match_ : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base.== p.\n\nFixpoint isSubsetOf (arg_0__ arg_1__ : IntSet) : bool\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n         if shorter m1 m2 : bool then false else\n         if shorter m2 m1 : bool\n         then andb (match_ p1 p2 m2) (if zero p1 m2 : bool\n                    then isSubsetOf t1 l2\n                    else isSubsetOf t1 r2) else\n         andb (p1 GHC.Base.== p2) (andb (isSubsetOf l1 l2) (isSubsetOf r1 r2))\n     | _, _ =>\n         match arg_0__, arg_1__ with\n         | Bin _ _ _ _, _ => false\n         | Tip kx1 bm1, Tip kx2 bm2 =>\n             andb (kx1 GHC.Base.== kx2) (Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2)\n                   GHC.Base.==\n                   #0)\n         | (Tip kx _ as t1), Bin p m l r =>\n             if nomatch kx p m : bool then false else\n             if zero kx m : bool then isSubsetOf t1 l else\n             isSubsetOf t1 r\n         | Tip _ _, Nil => false\n         | Nil, _ => true\n         end\n     end.\n\nProgram Fixpoint disjoint (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__\n                           +\n                           size_nat arg_1__)} : bool\n  := match arg_0__, arg_1__ with\n     | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n         let disjoint2 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then true else\n           if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then disjoint t1 l2 else\n           disjoint t1 r2 in\n         let disjoint1 :=\n           if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then true else\n           if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then disjoint l1 t2 else\n           disjoint r1 t2 in\n         if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then disjoint1 else\n         if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then disjoint2 else\n         if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n         then andb (disjoint l1 l2) (disjoint r1 r2) else\n         true\n     | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n         let fix disjointBM arg_11__\n           := match arg_11__ with\n              | Bin p1 m1 l1 r1 =>\n                  if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then true else\n                  if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then disjointBM l1 else\n                  disjointBM r1\n              | Tip kx1 bm1 =>\n                  if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                  then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                  true\n              | Nil => true\n              end in\n         disjointBM t1\n     | Bin _ _ _ _, Nil => true\n     | Tip kx1 bm1, t2 =>\n         let fix disjointBM arg_18__\n           := match arg_18__ with\n              | Bin p2 m2 l2 r2 =>\n                  if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then true else\n                  if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then disjointBM l2 else\n                  disjointBM r2\n              | Tip kx2 bm2 =>\n                  if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                  then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                  true\n              | Nil => true\n              end in\n         disjointBM t2\n     | Nil, _ => true\n     end.\nSolve Obligations with (termination_by_omega).\n\nProgram Definition foldl'Bits {a}\n   : Coq.Numbers.BinNums.N ->\n     (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n  fun prefix f z bitmap =>\n    let go :=\n      HsToCoq.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                           Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                           match arg_0__, arg_1__ with\n                           | num_2__, acc =>\n                               if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                               match arg_0__, arg_1__ with\n                               | bm, acc =>\n                                   let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                   let bi := indexOfTheOnlyBit bitmask in\n                                   go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                               end\n                           end) in\n    go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nFixpoint filter (predicate : Key -> bool) (t : IntSet) : IntSet\n  := let bitPred :=\n       fun kx bm bi =>\n         if predicate (kx GHC.Num.+ bi) : bool\n         then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n         bm in\n     match t with\n     | Bin p m l r => bin p m (filter predicate l) (filter predicate r)\n     | Tip kx bm => tip kx (foldl'Bits #0 (bitPred kx) #0 bm)\n     | Nil => Nil\n     end.\n\nDefinition partition : (Key -> bool) -> IntSet -> (IntSet * IntSet)%type :=\n  fun predicate0 t0 =>\n    let fix go predicate t\n      := let bitPred :=\n           fun kx bm bi =>\n             if predicate (kx GHC.Num.+ bi) : bool\n             then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n             bm in\n         match t with\n         | Bin p m l r =>\n             let 'pair r1 r2 := go predicate r in\n             let 'pair l1 l2 := go predicate l in\n             pair (bin p m l1 r1) (bin p m l2 r2)\n         | Tip kx bm =>\n             let bm1 := foldl'Bits #0 (bitPred kx) #0 bm in\n             pair (tip kx bm1) (tip kx (Data.Bits.xor bm bm1))\n         | Nil => (pair Nil Nil)\n         end in\n    id (go predicate0 t0).\n\nDefinition split : Key -> IntSet -> (IntSet * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | x', (Bin p m l r as t') =>\n             if match_ x' p m : bool\n             then if zero x' m : bool\n                  then let 'pair lt gt := go x' l in\n                       pair lt (union gt r)\n                  else let 'pair lt gt := go x' r in\n                       pair (union lt l) gt else\n             if x' GHC.Base.< p : bool\n             then (pair Nil t')\n             else (pair t' Nil)\n         | x', (Tip kx' bm as t') =>\n             let lowerBitmap := bitmapOf x' GHC.Num.- #1 in\n             let higherBitmap :=\n               Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                          GHC.Num.+\n                                          bitmapOf x') in\n             if kx' GHC.Base.> x' : bool then (pair Nil t') else\n             if kx' GHC.Base.< prefixOf x' : bool then (pair t' Nil) else\n             pair (tip kx' (bm Data.Bits..&.(**) lowerBitmap)) (tip kx' (bm Data.Bits..&.(**)\n                                                                         higherBitmap))\n         | _, Nil => (pair Nil Nil)\n         end in\n    let j_21__ := let 'pair lt gt := go x t in pair lt gt in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair lt gt := go x l in\n                  let lt' := union lt r in pair lt' gt\n             else let 'pair lt gt := go x r in\n                  let gt' := union gt l in pair lt gt' else\n        j_21__\n    | _ => j_21__\n    end.\n\nDefinition splitMember : Key -> IntSet -> (IntSet * bool * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | x', (Bin p m l r as t') =>\n             if match_ x' p m : bool\n             then if zero x' m : bool\n                  then let 'pair (pair lt fnd) gt := go x' l in\n                       pair (pair lt fnd) (union gt r)\n                  else let 'pair (pair lt fnd) gt := go x' r in\n                       pair (pair (union lt l) fnd) gt else\n             if x' GHC.Base.< p : bool\n             then pair (pair Nil false) t'\n             else pair (pair t' false) Nil\n         | x', (Tip kx' bm as t') =>\n             let bitmapOfx' := bitmapOf x' in\n             let lowerBitmap := bitmapOfx' GHC.Num.- #1 in\n             let higherBitmap :=\n               Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                          GHC.Num.+\n                                          bitmapOfx') in\n             if kx' GHC.Base.> x' : bool then pair (pair Nil false) t' else\n             if kx' GHC.Base.< prefixOf x' : bool then pair (pair t' false) Nil else\n             let gt := tip kx' (bm Data.Bits..&.(**) higherBitmap) in\n             let found := (bm Data.Bits..&.(**) bitmapOfx') GHC.Base./= #0 in\n             let lt := tip kx' (bm Data.Bits..&.(**) lowerBitmap) in pair (pair lt found) gt\n         | _, Nil => pair (pair Nil false) Nil\n         end in\n    let j_22__ := go x t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair (pair lt fnd) gt := go x l in\n                  let lt' := union lt r in pair (pair lt' fnd) gt\n             else let 'pair (pair lt fnd) gt := go x r in\n                  let gt' := union gt l in pair (pair lt fnd) gt' else\n        j_22__\n    | _ => j_22__\n    end.\n\nDefinition maxView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n      := match arg_0__ with\n         | Bin p m l r => let 'pair result r' := go r in pair result (bin p m l r')\n         | Tip kx bm =>\n             let 'bi := highestBitSet bm in\n             pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                            bitmapOfSuffix bi)))\n         | Nil => pair (0 % N) Nil\n         end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result l' := go l in\n             Some (pair result (bin p m l' r)) else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition minView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n      := match arg_0__ with\n         | Bin p m l r => let 'pair result l' := go l in pair result (bin p m l' r)\n         | Tip kx bm =>\n             let 'bi := lowestBitSet bm in\n             pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                            bitmapOfSuffix bi)))\n         | Nil => pair (0 % N) Nil\n         end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result r' := go r in\n             Some (pair result (bin p m l r')) else\n        j_12__\n    | _ => j_12__\n    end.\n\n(* Skipping definition `Data.IntSet.Internal.deleteFindMin' *)\n\n(* Skipping definition `Data.IntSet.Internal.deleteFindMax' *)\n\n(* Skipping definition `Data.IntSet.Internal.findMin' *)\n\n(* Skipping definition `Data.IntSet.Internal.findMax' *)\n\nDefinition deleteMin : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.\u2218 minView.\n\nDefinition deleteMax : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.\u2218 maxView.\n\nDefinition fromList : list Key -> IntSet :=\n  fun xs => let ins := fun t x => insert x t in Data.Foldable.foldl' ins empty xs.\n\nDefinition toList : IntSet -> list Key :=\n  toAscList.\n\nDefinition map : (Key -> Key) -> IntSet -> IntSet :=\n  fun f => fromList GHC.Base.\u2218 (GHC.Base.map f GHC.Base.\u2218 toList).\n\nDefinition fold {b : Type} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nProgram Definition foldr'Bits {a}\n   : Coq.Numbers.BinNums.N ->\n     (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n  fun prefix f z bitmap =>\n    let go :=\n      HsToCoq.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                           Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                           match arg_0__, arg_1__ with\n                           | num_2__, acc =>\n                               if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                               match arg_0__, arg_1__ with\n                               | bm, acc =>\n                                   let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                   let bi := indexOfTheOnlyBit bitmask in\n                                   go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                      GHC.Num.-\n                                                                      bi)) acc)\n                               end\n                           end) in\n    go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldr' {b : Type} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Nil => z'\n         | z', Tip kx bm => foldr'Bits kx f z' bm\n         | z', Bin _ _ l r => go (go z' r) l\n         end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nProgram Definition foldlBits {a}\n   : Coq.Numbers.BinNums.N ->\n     (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n  fun prefix f z bitmap =>\n    let go :=\n      HsToCoq.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                           Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                           match arg_0__, arg_1__ with\n                           | num_2__, acc =>\n                               if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                               match arg_0__, arg_1__ with\n                               | bm, acc =>\n                                   let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                   let bi := indexOfTheOnlyBit bitmask in\n                                   go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                               end\n                           end) in\n    go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldl {a : Type} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Nil => z'\n         | z', Tip kx bm => foldlBits kx f z' bm\n         | z', Bin _ _ l r => go (go z' l) r\n         end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition foldl' {a : Type} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n      := match arg_0__, arg_1__ with\n         | z', Nil => z'\n         | z', Tip kx bm => foldl'Bits kx f z' bm\n         | z', Bin _ _ l r => go (go z' l) r\n         end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition elems : IntSet -> list Key :=\n  toAscList.\n\nDefinition toDescList : IntSet -> list Key :=\n  foldl (GHC.Base.flip cons) nil.\n\nDefinition foldrFB {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nDefinition foldlFB {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  foldl.\n\n(* Skipping definition `Data.IntSet.Internal.fromAscList' *)\n\n(* Skipping definition `Data.IntSet.Internal.fromDistinctAscList' *)\n\n(* Skipping definition `Data.IntSet.Internal.showTree' *)\n\n(* Skipping definition `Data.IntSet.Internal.showTreeWith' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsTree' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsTreeHang' *)\n\n(* Skipping definition `Data.IntSet.Internal.showBin' *)\n\n(* Skipping definition `Data.IntSet.Internal.showWide' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsBars' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsBitMap' *)\n\n(* Skipping definition `Data.IntSet.Internal.showBitMap' *)\n\n(* Skipping definition `Data.IntSet.Internal.node' *)\n\n(* Skipping definition `Data.IntSet.Internal.withBar' *)\n\n(* Skipping definition `Data.IntSet.Internal.withEmpty' *)\n\n(* Skipping definition `Data.IntSet.Internal.prefixBitMask' *)\n\nDefinition splitRoot : IntSet -> list IntSet :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Nil => nil\n    | (Tip _ _ as x) => cons x nil\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool then cons r (cons l nil) else\n        cons l (cons r nil)\n    end.\n\nModule Notations.\nNotation \"'_Data.IntSet.Internal.\\\\_'\" := (op_zrzr__).\nInfix \"Data.IntSet.Internal.\\\\\" := (_\\\\_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Bool.Sumbool.sumbool_of_bool Eq Gt Lt N None Some Type andb bool comparison cons\n     false id list negb nil op_zm__ op_zp__ op_zt__ op_zv__ option orb pair size_nat\n     true Coq.Init.Peano.lt Coq.NArith.BinNat.N.ldiff Coq.NArith.BinNat.N.log2\n     Coq.NArith.BinNat.N.lxor Coq.NArith.BinNat.N.modulo Coq.NArith.BinNat.N.ones\n     Coq.NArith.BinNat.N.pow Coq.NArith.BinNat.N.pred Coq.NArith.BinNat.N.to_nat\n     Coq.Numbers.BinNums.N Data.Bits.op_zizazi__ Data.Bits.op_zizbzi__ Data.Bits.xor\n     Data.Foldable.Foldable Data.Foldable.foldl' Data.Maybe.maybe Data.Tuple.snd\n     GHC.Base.Eq_ GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.compare\n     GHC.Base.compare__ GHC.Base.flip GHC.Base.map GHC.Base.mappend__ GHC.Base.max__\n     GHC.Base.mconcat__ GHC.Base.mempty__ GHC.Base.min__ GHC.Base.op_z2218U__\n     GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zg__ GHC.Base.op_zg____\n     GHC.Base.op_zgze__ GHC.Base.op_zgze____ GHC.Base.op_zl__ GHC.Base.op_zl____\n     GHC.Base.op_zlze____ GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____\n     GHC.Base.op_zsze__ GHC.Base.op_zsze____ GHC.Num.fromInteger GHC.Num.op_zm__\n     GHC.Num.op_zp__ HsToCoq.Err.Build_Default HsToCoq.Err.Default HsToCoq.Wf.wfFix2\n     Utils.Containers.Internal.BitUtil.bitcount\n     Utils.Containers.Internal.BitUtil.highestBitMask\n     Utils.Containers.Internal.BitUtil.lowestBitMask\n     Utils.Containers.Internal.BitUtil.shiftLL\n     Utils.Containers.Internal.BitUtil.shiftRL\n*)\n", "meta": {"author": "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/IntSet/Internal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.18771291720497596}}
{"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 \u03a3}.\nSet Default Proof Using \"Type\".\n\n\nDefinition tree_copy : val :=\nrec: \"tree_copy\" \"r\" :=\nlet: \"x2\" := ! (\"r\") in\n#();; \nif: \"x2\" = #null_loc\nthen (\n#()\n)\nelse (\nlet: \"vx22\" := ! (\"x2\") in\n#();; \nlet: \"lx22\" := ! (\"x2\" +\u2097 #1) in\n#();; \nlet: \"rx22\" := ! (\"x2\" +\u2097 #2) in\n#();; \n(\"r\") <- (\"lx22\");; \n\"tree_copy\" \"r\";; \nlet: \"y12\" := ! (\"r\") in\n#();; \n(\"r\") <- (\"rx22\");; \n\"tree_copy\" \"r\";; \nlet: \"y22\" := ! (\"r\") in\n#();; \nlet: \"y3\" := AllocN (#3) (#()) in\n#();; \n(\"r\") <- (\"y3\");; \n(\"y3\" +\u2097 #1) <- (\"y12\");; \n(\"y3\" +\u2097 #2) <- (\"y22\");; \n(\"y3\") <- (\"vx22\");; \n#()\n).\n\n\nLemma tree_copy_spec :\n\u2200 (r : loc) (x : loc) (s : (list Z)) (a : tree_card),\n{{{ r \u21a6 #x \u2217 (tree x s a) }}}\n  tree_copy #r\n{{{ RET #(); \u2203 (y : loc), r \u21a6 #y \u2217 (tree x s a) \u2217 (tree y s a) }}}.\nProof.\niIntros (r x s a \u03d5) \"(iH1 & iH2) Post\".\niRewriteHyp.\niL\u00f6b as \"tree_copy\" forall (r x s a \u03d5).\nssl_begin.\ntry rename x into x2.\nssl_load.\niRename select ((tree x2 s a))%I into \"iH3\".\nssl_if Cond_iH3.\n\niDestruct (tree_card_0_learn with \"iH3\") as \"[iH3 %iH3_eqn]\".\nrewrite iH3_eqn; last by safeDispatchPure.\ntac_except_post ltac:(rewrite tree_card_0_open).\niDestruct \"iH3\" as  \"(%iH4 & %iH5)\".\ntry wp_pures.\niFindApply.\niExists null_loc.\nssl_finish.\nssl_rewrite_first_heap tree_card_0_open.\nssl_finish.\nssl_rewrite_first_heap tree_card_0_open.\nssl_finish.\n\n\niDestruct (tree_card_2_learn with \"iH3\") as \"[iH3 %iH3_eqn]\".\n\nedestruct iH3_eqn as [_alpha_545x2 [_alpha_544x2 ->]]; first by safeDispatchPure.\ntac_except_post ltac:(rewrite tree_card_2_open).\niDestruct \"iH3\" as (vx2 s1x2 s2x2 lx2 rx2) \"((%iH6 & %iH7) & (iH8 & iH9 & iH10 & iH11 & iH12 & iH13))\".\ntry rename vx2 into vx22.\nssl_load.\ntry rename lx2 into lx22.\nssl_load.\ntry rename rx2 into rx22.\nssl_load.\nssl_store.\nwp_apply (\"tree_copy\" $! (r) (lx22) (s1x2) (_alpha_544x2) with \"[$] [$]\").\n\n\niIntros  \"iH17\".\niDestruct \"iH17\" as (y1) \"(iH14 & iH15 & iH16)\".\ntry wp_pures.\ntry rename y1 into y12.\nssl_load.\nssl_store.\nwp_apply (\"tree_copy\" $! (r) (rx22) (s2x2) (_alpha_545x2) with \"[$] [$]\").\n\n\niIntros  \"iH21\".\niDestruct \"iH21\" as (y2) \"(iH18 & iH19 & iH20)\".\ntry wp_pures.\ntry rename y2 into y22.\nssl_load.\nwp_alloc y3 as \"?\"; try by safeDispatchPure.\nwp_pures.\ndo 3 try rewrite array_cons. iSplitAllHyps. try rewrite array_nil.\ntry rewrite !loc_add_assoc !Z.add_1_r.\n\nmovePure.\nssl_store.\nssl_store.\nssl_store.\nssl_store.\ntry wp_pures.\niFindApply.\niExists y3.\nssl_finish.\nssl_rewrite_first_heap tree_card_2_open.\npull_out_exist.\niExists vx22.\npull_out_exist.\niExists s1x2.\npull_out_exist.\niExists s2x2.\npull_out_exist.\niExists lx22.\npull_out_exist.\niExists rx22.\nssl_finish.\nssl_rewrite_first_heap tree_card_2_open.\npull_out_exist.\niExists vx22.\npull_out_exist.\niExists s1x2.\npull_out_exist.\niExists s2x2.\npull_out_exist.\niExists y12.\npull_out_exist.\niExists y22.\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/tree/tree_copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18760597995334327}}
{"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_sendA_Nack_procR_typing :\n  forall i k r r' (xc:free_id) (xerr1:free_id) (x:free_id) (xin:free_id),\n    r --(MInp (TSingleton k))--> r'\n    ->\n    ~ In xc (\"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In x (xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In xin (x :: xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In xerr1 (xin :: x :: xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    (CTX.add(ValVariable (Var (Free xerr1)),\n        TChannel (SNack r k r' (token_of_bool i)))\n      (CTX.add(ValVariable (Var (Free xc)), TChannel SEpsilon)\n      (CTX.add(ValVariable (Var (Free xin)), TChannel (SToks (r')))\n      (CTX.add(ValVariable (Var (Free x)), TSingleton k) \n      (CTX.add(ValName (Nm (Free (String.append \"send_\" (string_of_bool i)))),\n        (TChannel (SFwd (SSend i))))\n      (CTX.add(ValName(CoNm (Free (String.append \"send_\" (string_of_bool i)))),\n        (TChannel (SDual (SFwd (SSend i)))))\n      (CTX.add(ValName (CoNm (Free (String.append \"send_\" \n        (string_of_bool (negb i))))),\n        (TChannel (SDual (SFwd (SSend (negb i))))))\n      CTX.empty)))))))\n    |-p Var (Free xerr1) ! Token (if i then \"true\" else \"false\");\n      (Var (Free xerr1) ! Var (Free x);\n      (New\n      (CoNm (Free (String.append \"send_\" (if i then \"true\" else \"false\")))\n        ! Nm (Bound 0);\n      (CoNm (Bound 0) ! Var (Free x);\n      (CoNm (Bound 0) ! Var (Free xin);\n      (CoNm (Bound 0) ! Var (Free xerr1);\n      Zero)))))).\nProof.\n  intros i k r r' xc xerr1 x xin Htrans Hxc_nin Hx_nin Hxin_nin Hxerr1_nin.\n  compute.\n  Case \"SNack - Sum Part 1\".\n    eapply TypPrefixOutput with (s:=SNack r k r' (token_of_bool i))\n        (rho:=TSingleton (token_of_bool i))\n        (t:=SNack1 r k r' (token_of_bool i));\n      [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    (* main event *)\n    eapply TypPrefixOutput with (s:=SNack1 r k r' (token_of_bool i))\n        (rho:=TSingleton k) (t:=SNack r k r' (token_of_bool i));\n      [constructor; assumption\n        | left; discriminate_w_list\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | right; split; [reflexivity | constructor]\n        | reflexivity | ].\n    (* main event *)\n    apply TypNew with (s:=SSend i)\n        (L:=xc :: xerr1 :: xin :: x :: \"send_true\" :: \"send_false\" :: nil);\n    intros d G' H_d_nin G'def; compute; subst G'.\n    eapply TypPrefixOutput with (s:=SDual (SFwd (SSend i)))\n        (rho:=TChannel (SSend i)) (t:=SDual (SFwd (SSend i)));\n      [apply trdual_w_mdual_involution; constructor\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    eapply TypPrefixOutput with (s:=SDual (SSend i))\n        (rho:=TSingleton k)\n        (t:=SDual (SSend1 i r' (SNack r k r' (token_of_bool i))));\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | right; split; [reflexivity | constructor]\n        | reflexivity | ].\n    eapply TypPrefixOutput with\n        (s:=SDual (SSend1 i r' (SNack r k r' (token_of_bool i))))\n        (rho:=TChannel (SToks r'))\n        (t:=SDual (SSend2 i (SNack r k r' (token_of_bool i))));\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    eapply TypPrefixOutput with\n        (s:=SDual (SSend2 i (SNack r k r' (token_of_bool i))))\n        (rho:=TChannel (SNack r k r' (token_of_bool i)))\n        (t:=SDual SEpsilon);\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    apply TypZero;\n      destruct i;\n      ctx_wf;\n      discriminate_w_list.\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/ExampleABPSendANack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18760597995334327}}
{"text": "From stdpp Require Import namespaces.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import excl.\nFrom Perennial.base_logic.lib Require Import invariants.\nFrom Perennial.program_logic Require Export weakestpre.\nFrom Perennial.Helpers Require Import Qextra.\n\nFrom Perennial.goose_lang Require Export lang typing.\nFrom Perennial.goose_lang Require Import proofmode wpc_proofmode notation crash_borrow.\nFrom Perennial.goose_lang Require Import persistent_readonly.\nFrom Perennial.goose_lang.lib Require Import typed_mem.\nFrom Perennial.goose_lang.lib Require Export rwlock.impl.\nFrom Perennial.goose_lang.lib Require Export rwlock.rwlock_noncrash.\nRequire Import Field.\nAdd Field Qcfield : Qcanon.Qcft.\nSet Default Proof Using \"Type\".\n\nSection goose_lang.\nContext `{ffi_sem: ffi_semantics}.\nContext `{!ffi_interp ffi}.\nContext {ext_tys: ext_types ext}.\n\nLocal Coercion Var' (s:string): expr := Var s.\n\nSection proof.\n  Context `{!heapGS \u03a3} (N : namespace).\n  Context `{!stagedG \u03a3}.\n\n  Definition rfrac: Qp :=\n    (Qp.inv (Qp_of_Z (2^64)))%Qp.\n\n  Definition is_crash_rwlock lk R Rc :=\n    is_rwlock N lk (\u03bb q, crash_borrow (R q) (Rc q)).\n\n  (** The main proofs. *)\n  Global Instance is_crash_rwlock_persistent l R Rc : Persistent (is_crash_rwlock l R Rc).\n  Proof. apply _. Qed.\n\n  Definition is_free_lock (l: loc): iProp \u03a3 := l \u21a6 #1 \u2217 later_tok \u2217 later_tok \u2217 later_tok \u2217 later_tok.\n\n  Theorem is_free_lock_ty lk :\n    is_free_lock lk -\u2217 \u231cval_ty #lk ptrT\u231d.\n  Proof.\n    iIntros \"Hlk\".\n    iPureIntro.\n    val_ty.\n  Qed.\n\n  Theorem alloc_lock E l R Rc :\n    \u25a1 (\u2200 q1 q2, R (q1 + q2)%Qp \u2217-\u2217 R q1 \u2217 R q2) -\u2217\n    \u25a1 (\u2200 q1 q2, Rc (q1 + q2)%Qp \u2217-\u2217 Rc q1 \u2217 Rc q2) -\u2217\n    \u25a1 (\u2200 q, R q -\u2217 Rc q) -\u2217\n    l \u21a6 #1 -\u2217 crash_borrow (R 1%Qp) (Rc 1%Qp) ={E}=\u2217 is_crash_rwlock #l R Rc.\n  Proof.\n    iIntros \"#H1 #H2 #H3 Hl HR\".\n    iMod (alloc_lock N E l (\u03bb q, (crash_borrow (R q) (Rc q))) with \"[] [] [$] [$]\").\n    { iModIntro. iIntros (q1 q2) \"H\".\n      iApply (crash_borrow_split_post with \"H\").\n      { iNext. iIntros \"HR\". iApply \"H1\"; eauto. }\n      { eauto. }\n      { eauto. }\n      { iNext. iIntros \"HR\". iApply \"H2\"; eauto. }\n    }\n    { iModIntro. iIntros (q1 q2) \"Hc1 Hc2\".\n      iApply (crash_borrow_combine_post with \"Hc1 Hc2\").\n      { iNext. eauto. }\n      { iNext. iIntros \"HR\". iApply \"H2\"; eauto. }\n      { iNext. iIntros \"HR\". iApply \"H1\"; eauto. }\n    }\n    eauto.\n  Qed.\n\n  Lemma wp_new_free_lock:\n    {{{ True }}} rwlock.new #() {{{ lk, RET #lk; is_free_lock lk }}}.\n  Proof.\n    iIntros (\u03a6) \"_ H\u03a6\".\n    wp_call.\n    iApply wp_crash_borrow_generate_pre; first auto.\n    wp_apply wp_alloc_untyped; auto.\n    iIntros (?) \"Hl Htoks\".\n    iApply \"H\u03a6\". iFrame.\n Qed.\n\n  Lemma alloc_rwlock \u03a6 \u03a6c e lk (R Rc : Qp \u2192 iProp \u03a3):\n    \u25a1 (\u2200 q1 q2, R (q1 + q2)%Qp \u2217-\u2217 R q1 \u2217 R q2) -\u2217\n    \u25a1 (\u2200 q1 q2, Rc (q1 + q2)%Qp \u2217-\u2217 Rc q1 \u2217 Rc q2) -\u2217\n    \u25a1 (\u2200 q, R q -\u2217 Rc q) -\u2217\n    R 1%Qp \u2217\n    is_free_lock lk \u2217\n    (is_crash_rwlock #lk R Rc -\u2217\n          WPC e @ \u22a4 {{ \u03a6 }} {{ Rc 1%Qp -\u2217 \u03a6c }}) -\u2217\n    WPC e @ \u22a4 {{ \u03a6 }} {{ \u03a6c }}.\n  Proof.\n    clear.\n    iIntros \"#Hwand1 #Hwand2 #Hwand3 (HR&Hfree&Hwp)\".\n    iDestruct \"Hfree\" as \"(Hfree1&Htoks)\".\n    iApply (wpc_crash_borrow_inits with \"[$] HR []\").\n    { iModIntro. iApply \"Hwand3\". }\n    iIntros \"Hborrow\".\n    iMod (alloc_lock with \"[] [] [] [$] Hborrow\") as \"H\"; try eauto.\n    iApply \"Hwp\". eauto.\n  Qed.\n\n\n  Lemma read_acquire_spec lk R Rc :\n    {{{ is_crash_rwlock lk R Rc }}} rwlock.read_acquire lk {{{ RET #(); crash_borrow (R rfrac) (Rc rfrac) }}}.\n  Proof.\n    iIntros (\u03a6) \"#Hl H\u03a6\".\n    wp_apply (read_acquire_spec with \"[$]\").\n    eauto.\n  Qed.\n\n  Lemma read_release_spec lk R Rc :\n    {{{ is_crash_rwlock lk R Rc \u2217 crash_borrow (R rfrac) (Rc rfrac) }}}\n      rwlock.read_release lk\n    {{{ RET #(); True }}}.\n  Proof.\n    iIntros (\u03a6) \"(Hlock&Hborrow) H\u03a6\".\n    wp_apply (read_release_spec with \"[$Hlock $Hborrow]\").\n    iApply \"H\u03a6\"; eauto.\n  Qed.\n\n  Lemma write_acquire_spec lk R Rc :\n    {{{ is_crash_rwlock lk R Rc }}}\n      rwlock.write_acquire lk\n    {{{ RET #(); wlocked lk \u2217 crash_borrow (R 1%Qp) (Rc 1%Qp) }}}.\n  Proof.\n    iIntros (\u03a6) \"Hlock H\u03a6\".\n    wp_apply (write_acquire_spec with \"[$Hlock]\").\n    iApply \"H\u03a6\"; eauto.\n  Qed.\n\n  Lemma release_spec lk R Rc :\n    {{{ is_crash_rwlock lk R Rc \u2217 wlocked lk \u2217 crash_borrow (R 1%Qp) (Rc 1%Qp) }}}\n      rwlock.write_release lk\n    {{{ RET #(); True }}}.\n  Proof.\n    iIntros (\u03a6) \"(Hlock&Hborrow) H\u03a6\".\n    wp_apply (release_spec with \"[$Hlock $Hborrow]\").\n    iApply \"H\u03a6\"; eauto.\n  Qed.\n\nEnd proof.\nEnd goose_lang.\n\nTypeclasses Opaque is_rwlock.\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/rwlock/rwlock_derived.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1876059727494972}}
{"text": "Require Import GhostSimulations.\nRequire Import InverseTraceRelations.\nRequire Import UpdateLemmas.\n\nRequire Import Raft.\nRequire Import CommonTheorems.\nRequire Import TraceUtil.\n\nRequire Import SpecLemmas.\n\nRequire Import InputBeforeOutputInterface.\nRequire Import AppliedImpliesInputInterface.\nRequire Import OutputImpliesAppliedInterface.\nRequire Import LastAppliedCommitIndexMatchingInterface.\nRequire Import SortedInterface.\nRequire Import LogMatchingInterface.\nRequire Import StateMachineSafetyInterface.\nRequire Import MaxIndexSanityInterface.\nRequire Import UniqueIndicesInterface.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSection InputBeforeOutput.\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 {si : sorted_interface}.\n  Context {lacimi : lastApplied_commitIndex_match_interface}.\n  Context {lmi : log_matching_interface}.\n  Context {smsi : state_machine_safety_interface}.\n  Context {misi : max_index_sanity_interface}.\n  Context {uii : unique_indices_interface}.\n\n  Section inner.\n  Variables client id : nat.\n\n  Fixpoint client_id_in l :=\n    match l with\n      | [] => false\n      | e :: l' =>\n        if (andb (eClient e =? client)\n                 (eId e =? id)) then\n          true\n        else\n          client_id_in l'\n    end.\n\n  Lemma client_id_in_true_in_applied_entries :\n    forall net,\n      client_id_in (applied_entries (nwState net)) = true ->\n      in_applied_entries client id net.\n  Proof using. \n    intros. unfold in_applied_entries.\n    induction (applied_entries (nwState net)); simpl in *; try congruence.\n    break_if; do_bool; intuition; do_bool; eauto;\n    break_exists_exists; intuition.\n  Qed.\n\n  Lemma client_id_in_false_not_in_applied_entries :\n    forall net,\n      client_id_in (applied_entries (nwState net)) = false ->\n      ~ in_applied_entries client id net.\n  Proof using. \n    intros. unfold in_applied_entries.\n    induction (applied_entries (nwState net)); simpl in *; try congruence; intuition.\n    - break_exists; intuition.\n    - break_if; try congruence.\n      do_bool.\n      break_exists; intuition; do_bool; subst; eauto.\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            (forall e, In e es -> exists h, In e (log (sigma h)) /\\ eIndex e <= commitIndex (sigma h)).\n  Proof using lacimi si. \n    intros.\n    unfold doGenericServer in *. break_let. find_inversion.\n    find_copy_apply_lem_hyp logs_sorted_invariant. unfold logs_sorted, logs_sorted_host in *.\n    intuition.\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;\n                exists nil; simpl in *; intuition].\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; [find_rewrite; exists nil; simpl in *; intuition|].\n    pose proof applied_entries_cases sigma.\n    intuition; repeat find_rewrite; eauto;\n    [eexists; intuition; eauto;\n     find_apply_lem_hyp in_rev;\n     find_copy_apply_lem_hyp removeAfterIndex_In_le; eauto;\n     find_apply_lem_hyp removeAfterIndex_in; eexists; intuition; 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    + match goal with\n        | h : name |- _ =>\n          pose proof removeAfterIndex_partition (removeAfterIndex (log (sigma h)) (commitIndex (sigma h))) (lastApplied (sigma h))\n      end.\n      find_apply_lem_hyp rev_exists.\n      break_exists_exists.\n      repeat find_rewrite.\n      rewrite <- removeAfterIndex_le by omega. intuition.\n      find_eapply_lem_hyp app_in_2; eauto.\n      find_apply_lem_hyp In_rev.\n      find_copy_apply_lem_hyp removeAfterIndex_in.\n      find_apply_lem_hyp removeAfterIndex_In_le; eauto.\n    + match goal with\n        | _ : ?h <> ?h' |- context [ removeAfterIndex ?l (commitIndex (?sigma ?h)) ] =>\n          pose proof removeAfterIndex_partition (removeAfterIndex l (commitIndex (sigma h)))\n               (lastApplied (sigma h'))\n      end.\n      find_apply_lem_hyp rev_exists.\n      break_exists_exists.\n      repeat match goal with | H : applied_entries _ = _ |- _ => clear H end.\n      find_rewrite.\n      erewrite <- removeAfterIndex_le; eauto.\n      intuition.\n      * f_equal. f_equal.\n        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      * find_eapply_lem_hyp app_in_2; eauto.\n        find_apply_lem_hyp In_rev.\n        find_copy_apply_lem_hyp removeAfterIndex_in.\n        find_apply_lem_hyp removeAfterIndex_In_le; eauto.\n  Qed.\n\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 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 uii misi smsi 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  Lemma handleMessage_log :\n    forall net h h' h'' e 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      In e (log (update (nwState net) h st' h'')) ->\n      applied_implies_input_state (eClient e) (eId e) (eInput e) net.\n  Proof using. \n    intros.\n    unfold handleMessage in *. break_match; repeat break_let; repeat find_inversion.\n    - find_apply_lem_hyp handleRequestVote_same_log.\n      update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n      unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n    - update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n      try find_rewrite_lem handleRequestVoteReply_same_log;\n      unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n    - update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n      try solve [unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto].\n      find_apply_lem_hyp handleAppendEntries_log. intuition.\n      + repeat find_rewrite. unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n      + subst.\n        unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n        right. repeat eexists; eauto. reflexivity.\n      + repeat find_rewrite. do_in_app. intuition.\n        * unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n          right. repeat eexists; eauto. reflexivity.\n        * find_apply_lem_hyp removeAfterIndex_in.\n          unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n    - find_apply_lem_hyp handleAppendEntriesReply_log.\n      update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n      unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\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_same, 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 handleInput_log :\n    forall net h inp os st' ms h' e,\n      raft_intermediate_reachable net ->\n      handleInput h inp (nwState net h) = (os, st', ms) ->\n      In e (log (update (nwState net) h st' h')) ->\n      (applied_implies_input_state (eClient e) (eId e) (eInput e) net \\/\n       inp = ClientRequest (eClient e) (eId e) (eInput e)).\n  Proof using. \n    intros.\n    unfold handleInput in *. break_match; repeat break_let; repeat find_inversion.\n    - left.\n      find_apply_lem_hyp handleTimeout_log_same.\n      update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n      unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n    - find_apply_lem_hyp handleClientRequest_log. intuition.\n      + left.\n        update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n        unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n      + break_exists. intuition.\n        update_destruct_hyp; subst; rewrite_update; repeat find_rewrite;\n        try solve [left; unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto].\n        simpl in *. intuition; subst; intuition.\n        left; unfold applied_implies_input_state, correct_entry; eexists; intuition; eauto.\n  Qed.\n  \n  Lemma in_applied_entries_step_applied_implies_input_state' :\n    forall (failed : list name) net failed' net' o,\n      raft_intermediate_reachable net ->\n      step_f (failed, net) (failed', net') o ->\n      ~ in_applied_entries client id 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      exists h o' inp,\n        o = (h, inl (ClientRequest client id inp)) :: o'.\n  Proof using uii misi smsi lmi lacimi si. \n    intros. match goal with H : step_f _ _ _ |- _ => invcs H end; intuition.\n    - left. unfold RaftNetHandler in *. repeat break_let. subst.\n      unfold in_applied_entries in *.\n      break_exists_exists. intuition.\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'') as H by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H in *; clear H\n      end.\n      find_copy_eapply_lem_hyp RIR_handleMessage; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.\n      simpl in *.\n      find_copy_apply_lem_hyp handleMessage_applied_entries; repeat find_rewrite; eauto;\n      try solve [destruct p; simpl in *; intuition].\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_eapply_lem_hyp doGenericServer_applied_entries; eauto.\n      break_exists. intuition.\n      unfold ghost_data in *. simpl in *.\n      repeat find_rewrite.\n      do_in_app. intuition.\n      + find_false. eexists; intuition; repeat find_rewrite; eauto.\n      + find_apply_hyp_hyp. break_exists. intuition.\n        eapply handleMessage_log with (h'' := x1); eauto;\n        [destruct p; simpl in *; repeat find_rewrite; intuition|].\n        update_destruct_hyp; subst; rewrite_update; eauto.\n        find_apply_lem_hyp doLeader_log. repeat find_rewrite. auto.\n    - unfold RaftInputHandler in *. repeat break_let. subst.\n      unfold in_applied_entries in *.\n      break_exists_exists. intuition.\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'') as H by (repeat rewrite update_overwrite; auto); unfold data in *; simpl in *; rewrite H in *; clear H\n      end.\n      find_copy_eapply_lem_hyp RIR_handleInput; eauto.\n      find_eapply_lem_hyp RIR_doLeader; simpl in *; eauto.\n      simpl in *.\n      find_copy_apply_lem_hyp handleInput_applied_entries; repeat find_rewrite; eauto;\n      try solve [destruct p; simpl in *; intuition].\n      find_copy_apply_lem_hyp doLeader_appliedEntries.\n      find_eapply_lem_hyp doGenericServer_applied_entries; eauto.\n      break_exists. intuition.\n      unfold ghost_data in *. simpl in *.\n      repeat find_rewrite.\n      match goal with\n        | H : In _ _ -> False |- _ => clear H\n      end.\n      do_in_app. intuition.\n      + find_false. eexists; intuition; repeat find_rewrite; eauto.\n      + find_apply_hyp_hyp. break_exists. intuition.\n        find_apply_lem_hyp doLeader_log.\n        match goal with\n          | H : _ |- _ =>\n            eapply handleInput_log with (h' := x1) in H\n        end; eauto;\n        [|update_destruct_hyp; subst; eauto; rewrite_update; repeat find_rewrite; eauto].\n        intuition; subst;\n        repeat find_rewrite; eauto.\n    - find_false.\n      unfold in_applied_entries in *.\n      break_exists_exists. intuition.\n      match goal with\n        | H : In _ (applied_entries _) |- In _ (applied_entries ?sig) =>\n          erewrite applied_entries_log_lastApplied_same with (sigma := sig) in H\n      end; auto;\n      intros; simpl in *; break_if; auto.\n  Qed.\n  \n  Lemma in_applied_entries_step_applied_implies_input_state :\n    forall (s : list name * network) s' tr o,\n      refl_trans_1n_trace step_f step_f_init s tr ->\n      ~ in_applied_entries client id (snd s) ->\n      step_f s s' o ->\n      in_applied_entries client id (snd s') ->\n      (exists e,\n        eClient e = client /\\\n        eId e = id /\\\n        applied_implies_input_state client id (eInput e) (snd s)) \\/\n      exists h o' inp,\n        o = (h, inl (ClientRequest client id inp)) :: o'.\n  Proof using uii misi smsi lmi lacimi si. \n    intros.\n    destruct s as (failed, net).\n    destruct s' as (failed', net'). simpl in *.\n    find_apply_lem_hyp step_f_star_raft_intermediate_reachable.\n    eauto using in_applied_entries_step_applied_implies_input_state'.\n  Qed.\n\n  Lemma in_input_not_in_output_input_before_output :\n    forall client id i tr,\n      in_input_trace client id i tr ->\n      ~ key_in_output_trace client id tr ->\n      input_before_output client id tr.\n  Proof using. \n    intros. induction tr; simpl in *; intuition.\n    - unfold in_input_trace in *. break_exists; simpl in *; intuition.\n    - unfold in_input_trace in *.\n      break_exists. simpl in *. intuition.\n      + subst. unfold input_before_output. simpl.\n        left. do_bool; intuition; do_bool; auto.\n      + unfold input_before_output. simpl. right. intuition.\n        * unfold key_in_output_trace in *. \n          apply Bool.not_true_iff_false. intuition.\n          find_false. unfold is_output_with_key in *.\n          break_match; subst. repeat break_match; try congruence.\n          exists l, n. intuition.\n        * conclude_using eauto.\n          conclude_using\n            ltac:(intros; find_false; unfold key_in_output_trace in *;\n                    break_exists_exists; intuition).\n          eauto.\n  Qed.\n\n  Lemma input_before_output_not_key_in_output_trace_snoc_key :\n    forall client id tr h inp tr',\n      ~ key_in_output_trace client id tr ->\n      input_before_output client id\n                          (tr ++ (h, inl (ClientRequest client id inp)) :: tr').\n  Proof using. \n    intros. induction tr; simpl in *.\n    -unfold input_before_output. simpl in *.\n     left. repeat (do_bool; intuition).\n    - unfold input_before_output. simpl. right. intuition.\n      + unfold key_in_output_trace in *.\n        apply Bool.not_true_iff_false. intuition.\n        find_false. unfold is_output_with_key in *.\n        break_match; subst. repeat break_match; try congruence.\n        exists l, n. intuition.\n      + conclude_using\n          ltac:(intros; find_false; unfold key_in_output_trace in *;\n                  break_exists_exists; intuition).\n        eauto.\n  Qed.\n\n  Instance TR : InverseTraceRelation step_f :=\n    {\n      init := step_f_init;\n      T := input_before_output client id;\n      R := fun s => in_applied_entries client id (snd s) \n    }.\n  Proof.\n    - intros.\n      destruct (client_id_in (applied_entries (nwState (snd s)))) eqn:?;\n      eauto using client_id_in_true_in_applied_entries, client_id_in_false_not_in_applied_entries.\n    - intros.\n      unfold input_before_output in *.\n      eauto using before_func_app.\n    - intuition. simpl in *.\n      unfold in_applied_entries, applied_entries in *. simpl in *.\n      break_match; simpl in *; break_exists; intuition.\n    - intros.\n      destruct s as (failed, net).\n      destruct s' as (failed', net'). simpl in *.\n      find_eapply_lem_hyp in_applied_entries_step_applied_implies_input_state; eauto.\n      break_or_hyp.\n      + break_exists. intuition.\n        find_eapply_lem_hyp applied_implies_input; eauto.\n        apply before_func_app.\n        destruct (key_in_output_trace_dec client id tr);\n          [find_eapply_lem_hyp output_implies_applied; eauto; intuition|].\n        fold (input_before_output client id tr).\n        subst. eauto using in_input_not_in_output_input_before_output.\n      + destruct (key_in_output_trace_dec client id tr);\n        [find_eapply_lem_hyp output_implies_applied; eauto; intuition|].\n        break_exists. subst.\n        eauto using input_before_output_not_key_in_output_trace_snoc_key.\n  Defined.\n\n  Theorem output_implies_input_before_output :\n    forall 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  Proof using uii misi smsi lmi lacimi si aiii oiai. \n    intros. pose proof (inverse_trace_relations_work (failed, net) tr).\n    concludes.\n    find_eapply_lem_hyp output_implies_applied; eauto.\n    intuition.\n  Qed.\n\n  End inner.\n\n  Instance iboi : input_before_output_interface.\n  Proof.\n    split.\n    intros.\n    eapply output_implies_input_before_output; eauto.\n  Qed.\nEnd InputBeforeOutput.", "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/InputBeforeOutputProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1876059727494972}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.omega.Omega\n        Coq.Strings.Ascii\n        Coq.Strings.String\n        Coq.Bool.Bool\n        Coq.Vectors.VectorDef\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.VectorDef.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 \u25cb [ \"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 \u25cb [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 \u25cb [o !! \"authority\" / t :: o].\n\n  (* combine with above? *)\n  Definition add_additional (p : packet) (t : resourceRecord) :=\n    p \u25cb [o !! \"additional\" / t :: o].\n\n  Definition updateRecords (p : packet) answers' authority' additional' :=\n    p \u25cb [\"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": "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/DNS/SimpleDNSPacket.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.18759005519017088}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX Protocols.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule WorldGetters.\nSection WorldGetters.\n\n(* It's okay to have duplicating nodes in this list *)\n\n(* World is a dependent partial map of protocols *)\n\nDefinition context := union_map Label protocol.\n\n(*\nThe hooks are dependencies between:\n\n1. a hook's unique id\n2. a core protocol\n3. a client protocol\n4. a send-transition (represented by its tag) of a client protocol\n\n*)\nDefinition hook_domain := [ordType of ((nat * Label) * (Label * nat))%type].\n\n(*\n\nA hook is a constraint from the local state wrt. core protocol (1st\nheap argument), relating the local state wrt. the client protocol (2ns\nheap argument), message to be sent, and the destination node id.\n\n*)\nDefinition hook_type := heap -> heap -> seq nat -> nid -> Prop.\n\nDefinition hooks := union_map hook_domain hook_type.\nDefinition world := (context * hooks)%type.\n\nDefinition getc (w: world) : context := fst w.\nCoercion getc : world >-> context.\n\nDefinition geth (w: world) : hooks := snd w.\nCoercion geth : world >-> hooks.\n\nVariable w : world.\n\nVariables (p : protocol).\n\n(* The function is, in fact, partially defined and returns Empty\n   Protocol for a non-present label. *)\nDefinition getProtocol i : protocol:=\n  match find i (getc w) with\n  | Some p => p\n  | None => EmptyProt i\n  end.\n\nEnd WorldGetters.\nEnd WorldGetters.\n\nExport WorldGetters.\n\n(* Defining coherence of a state with respect to the world *)\n\nModule Worlds.\n\nModule Core.\nSection Core.\n\n(* The following definition ties together worlds and states *)\n\nDefinition hooks_consistent (c : context) (h : hooks) : Prop :=\n  forall z lc ls t, ((z, lc), (ls, t)) \\in dom h ->\n  (lc \\in dom c) && (ls \\in dom c).\n\nDefinition hook_complete w := hooks_consistent (getc w) (geth w).\n\nLemma hook_complete0 c : hook_complete (c, Unit).\nProof. by move=>????; rewrite dom0. Qed.\n\nDefinition Coh (w : world) : Pred state := fun s =>\n  let: c := fst w in\n  let: h := snd w in\n  [/\\ valid w, valid s, hook_complete w,\n      dom c =i dom s &\n      forall l, coh (getProtocol w l) (getStatelet s l)].\n\nLemma cohW w s : Coh w s -> valid w.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohS w s : Coh w s -> valid s.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohH w s : Coh w s -> hook_complete w.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohD w s : Coh w s -> dom (getc w) =i dom s.\nProof. by case w=>[c h]; case. Qed.\n\nLemma coh_coh w s l : Coh w s -> coh (getProtocol w l) (getStatelet s l).\nProof. by case w=>[c h]; case. Qed.\n\n(* Now we need to establish a bunch of natural properties with respect\n   to coherence of worlds and states. *)\n\nLemma unit_coh w s :\n  Coh w s -> w = Unit <-> s = Unit.\nProof.\ncase: (w)=>[c h].\ncase=>V V' Hc E H; split.\ncase=>Z1 Z2; subst c h; rewrite dom0 in E; last by rewrite (dom0E V').\nmove=>Z; subst s; move/andP: V=>/=[V1 V2].\nhave Z: c = Unit by apply: (dom0E V1); move=>z; rewrite E dom0.\nsubst c; suff Z: (h = Unit) by subst h.\nsimpl in Hc; clear E H V1 V'.\napply: (dom0E V2); move=> x; case X: (x \\in dom h)=>//.\nby move: x X=>[[z lc] [ls t]]/Hc/andP[]; rewrite !dom0.\nQed.\n\nLemma Coh0 (w : world) (s : state) :\n  w = Unit -> s = Unit -> Coh w s.\nProof.\nmove=>->->{w s}; split; rewrite ?valid_unit ?dom0=>//=; last first.\n- by move=>l; rewrite /getProtocol /getStatelet !find0E.\nby move=>z lc ls t; rewrite dom0.\nQed.\n\nLemma CohUn (w1 w2 : world) (s1 s2 : state) :\n  Coh w1 s1 -> Coh w2 s2 ->\n  valid (w1 \\+ w2) -> Coh (w1 \\+ w2) (s1 \\+ s2).\nProof.\ncase: w1=>[c1 h1]; case: w2=>[c2 h2]; move=>C1 C2 V.\ncase: (C1)=>_ G1 K1 J1 H1; case: (C2)=>_ G2 K2 J2 H2.\ncase/andP: V=>V V'; simpl in V, V'.\nhave X: valid (s1 \\+ s2).\n- case: validUn=>//; [by rewrite G1|by rewrite G2|move=>l; rewrite -J1 -J2=>D1 D2].\n  by case: validUn V=>//=V1 V2; move/(_ _ D1); rewrite D2.\nhave Y: dom (c1 \\+ c2) =i dom (s1 \\+ s2).\n- by move=>z; rewrite !domUn !inE/=;rewrite V X/= J1 J2.\nhave Z1:  valid ((c1, h1) \\+ (c2, h2)) by rewrite /valid/= V V'.\nsplit=>//[|l]; last first.\n- rewrite /getProtocol /getStatelet.\n  case: (dom_find l (s1 \\+ s2))=>[|v]Z.\n  - by move/find_none: (Z); rewrite -Y; case: dom_find=>//->_; rewrite Z.\n  move/find_some: (Z)=>D; rewrite Z; rewrite -Y in D=> E.\n  case: dom_find D=>// p Z' _ _; rewrite Z'.\n  rewrite findUnL // in Z; rewrite findUnL // J1 in Z'.\n  by case: ifP Z Z'=>_ F1 F2; [move: (H1 l)|move: (H2 l)];\n     rewrite /getProtocol /getStatelet F1 F2.\nby move=>z lc ls t/=; rewrite domUn inE=>/andP[_]/orP[];[move/K1|move/K2];\n   move/andP=>[A1 A2]; rewrite !domUn !inE A1 A2 V -?(orbC true).\nQed.\n\n(* Coherence is trivially precise wrt. statelets *)\nLemma coh_prec w: precise (Coh w).\nProof.\nmove=>s1 s2 t1 t2 V C1 C2.\ncase: C1 => H1 G1 K1 D1 _.\ncase: C2 => H2 G2 K2 D2 _ H.\nby apply: (@dom_prec _ _ _ _ s1 s2 t1 t2) =>//z; rewrite -D1 -D2.\nQed.\n\nLemma locE i n k x y :\n  k \\in dom i -> valid i -> valid (dstate (getStatelet i k)) ->\n  getLocal n (getStatelet (upd k\n       {| dstate := upd n x (dstate (getStatelet i k));\n          dsoup := y |} i) k) = x.\nProof.\nmove=>D V; rewrite /getStatelet; case:dom_find (D) =>//d->_ _.\nby rewrite findU eqxx/= V /getLocal/= findU eqxx/==>->.\nQed.\n\nLemma locE' d n x y :\n  valid (dstate d) ->\n  getLocal n {| dstate := upd n x (dstate d);\n                dsoup := y |} = x.\nProof. by move=>V; rewrite /getLocal findU eqxx/= V. Qed.\n\nLemma locU n n' x st s :\n  n != n' ->\n  valid st ->\n  getLocal n {| dstate := upd n' x st; dsoup := s |} =\n  getLocal n {| dstate := st; dsoup := s |}.\nProof.\nby move=>/negbTE N V; rewrite /getLocal findU/= N.\nQed.\n\n\nSection MakeWorld.\n\nVariable p : protocol.\nNotation l := (plab p).\n\nDefinition mkWorld : world := (l \\\\-> p, Unit).\n\nLemma prEq : (getProtocol mkWorld l) = p.\nProof. by rewrite /getProtocol findPt. Qed.\n\n(*\n\nHere's an incomplete list of procedures and facts, which might be\nuseful eventually:\n\n- Define getters for particular transitions of worlds;\n\n *)\n\nEnd MakeWorld.\n\n(* TODO: try_recv should be restricted by a set of labels and a set of\n   protocols *)\nEnd Core.\nEnd Core.\n\nEnd Worlds.\n\nExport Worlds.Core.\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/Worlds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.18745718744489115}}
{"text": "(* Evaluation contexts of the L6 CPS language\n * Part of the CertiCoq project\n *)\n\nFrom Coq Require Import Arith.Arith NArith.BinNat Lists.List omega.Omega.\nFrom SFS Require Import cps tactics set_util.\n\nImport ListNotations.\n\n(** Expression evaluation contexts *)\nInductive exp_ctx : Type :=\n| Hole_c : exp_ctx\n| Econstr_c : var -> cTag -> list var -> exp_ctx -> exp_ctx\n| Eproj_c  : var -> cTag -> N -> var -> exp_ctx -> exp_ctx\n| Eprim_c : var -> prim -> list var -> exp_ctx -> exp_ctx   \n| Ecase_c : var -> list (cTag * exp) -> cTag ->\n            exp_ctx -> list (cTag * exp) -> exp_ctx  \n| Efun1_c : fundefs -> exp_ctx -> exp_ctx\n| Efun2_c : fundefs_ctx -> exp -> exp_ctx\nwith fundefs_ctx :=\n     | Fcons1_c:  var -> cTag -> list var -> exp_ctx -> fundefs -> fundefs_ctx\n     | Fcons2_c:  var -> cTag -> list var -> exp -> fundefs_ctx -> fundefs_ctx.\n\n(** Evaluation context application - Relational definition *)\nInductive app_ctx: exp_ctx -> exp -> exp -> Prop :=\n| Hole_ac: forall e, app_ctx Hole_c e e\n| Constr_ac : forall x t c ys e ce,\n                app_ctx c e ce ->        \n                app_ctx (Econstr_c x t ys c) e (Econstr x t ys ce)\n| Proj_ac : forall x t n y e c ce, \n              app_ctx c e ce ->        \n              app_ctx (Eproj_c x t n y c) e (Eproj x t n y ce)\n| Case_ac : forall x te t e te' c ce,\n              app_ctx c e ce ->\n              app_ctx (Ecase_c x te t c te') e\n                      (Ecase x (te ++ (t, ce) :: te')) \n| Prim_ac : forall x f ys e c ce, \n              app_ctx c e ce ->        \n              app_ctx (Eprim_c x f ys c) e (Eprim x f ys ce)\n| Fun1_ac : forall c e ce fds,\n              app_ctx c e ce ->\n              app_ctx (Efun1_c fds c) e (Efun fds ce)\n| Fun2_ac : forall e cfds cfdse e',\n              app_f_ctx cfds e cfdse ->          \n              app_ctx (Efun2_c cfds e') e (Efun cfdse e')\nwith app_f_ctx : fundefs_ctx -> exp -> fundefs -> Prop :=\n     | Fcons1_ac : forall c e ce f t ys fds,\n                     app_ctx c e ce -> \n                     app_f_ctx (Fcons1_c f t ys c fds) e (Fcons f t ys ce fds)\n     | Fcons2_ac: forall e cfdse f cfds ys e' t, \n                    app_f_ctx cfds e cfdse -> \n                    app_f_ctx (Fcons2_c f t ys e' cfds) e (Fcons f t ys e' cfdse).\n\nHint Constructors app_ctx app_f_ctx.\n\n(** Evaluation context application - Computational definition *)\nFixpoint app_ctx_f (c:exp_ctx) (e:exp) : exp :=\n  match c with\n    | Hole_c => e\n    | Econstr_c x t ys c => Econstr x t ys (app_ctx_f c e)\n    | Eproj_c x t n y c => Eproj x t n y (app_ctx_f c e)\n    | Ecase_c x te t c te' =>\n      Ecase x (te ++ (t, app_ctx_f c e) :: te')\n    | Eprim_c x f ys c => Eprim x f ys (app_ctx_f c e)\n    | Efun1_c fds c => Efun fds (app_ctx_f c e)\n    | Efun2_c cfds e' => Efun (app_f_ctx_f cfds e) e' \n  end\nwith app_f_ctx_f (c: fundefs_ctx) (e:exp) : fundefs :=\n       match c with\n         | Fcons1_c f t ys c fds => Fcons f t ys (app_ctx_f c e) fds\n         | Fcons2_c f t ys e' cfds => Fcons f t ys e' (app_f_ctx_f cfds e)\n       end.\n\n(** Composition of evaluation context - Relational definition *)\nInductive  comp_ctx: exp_ctx -> exp_ctx -> exp_ctx -> Prop :=\n| Hole_cc: forall e, comp_ctx Hole_c e e\n| Constr_cc : forall x t c ys e ce,\n                comp_ctx c e ce ->\n                comp_ctx (Econstr_c x t ys c) e (Econstr_c x t ys ce)\n| Proj_cc : forall x t n y e c ce,\n              comp_ctx c e ce ->\n              comp_ctx (Eproj_c x t n y c) e (Eproj_c x t n y ce)\n| Case_cc : forall x te t c te' c' cc,\n              comp_ctx c c' cc ->\n              comp_ctx (Ecase_c x te t c te') c' (Ecase_c x te t cc te')\n| Prim_cc : forall x f ys e c ce,\n              comp_ctx c e ce ->\n              comp_ctx (Eprim_c x f ys c) e (Eprim_c x f ys ce)\n| Fun1_cc : forall c e ce fds,\n              comp_ctx c e ce ->\n              comp_ctx (Efun1_c fds c) e (Efun1_c fds ce)\n| Fun2_cc : forall e cfds cfdse e',\n              comp_f_ctx cfds e cfdse ->\n              comp_ctx (Efun2_c cfds e') e (Efun2_c cfdse e')\nwith comp_f_ctx : fundefs_ctx -> exp_ctx -> fundefs_ctx -> Prop :=\n     | Fcons1_cc :\n         forall c e ce f t ys fds,\n           comp_ctx c e ce ->\n           comp_f_ctx (Fcons1_c f t ys c fds) e (Fcons1_c f t ys ce fds)\n     | Fcons2_cc:\n         forall e cfdse f cfds ys e' t,\n           comp_f_ctx cfds e cfdse ->\n           comp_f_ctx (Fcons2_c f t ys e' cfds) e (Fcons2_c f t ys e' cfdse).\n\n(** Composition of evaluation context - Computational definition *)\nFixpoint comp_ctx_f (c1:exp_ctx) (c2:exp_ctx) : exp_ctx :=\n  match c1 with\n    | Hole_c => c2\n    | Econstr_c x t ys c => Econstr_c x t ys (comp_ctx_f c c2)\n    | Eproj_c x t n y c => Eproj_c x t n y (comp_ctx_f c c2)\n    | Ecase_c x te t c te' => Ecase_c x te t (comp_ctx_f c c2) te'\n    | Eprim_c x f ys c => Eprim_c x f ys (comp_ctx_f c c2)\n    | Efun1_c fds c => Efun1_c fds (comp_ctx_f c c2)\n    | Efun2_c cfds e' => Efun2_c (comp_f_ctx_f cfds c2) e'\n  end\nwith comp_f_ctx_f (c: fundefs_ctx) (c2:exp_ctx) : fundefs_ctx :=\n       match c with\n         | Fcons1_c f t ys c fds =>\n           Fcons1_c f t ys (comp_ctx_f c c2) fds\n         | Fcons2_c f t ys e' cfds =>\n           Fcons2_c f t ys e' (comp_f_ctx_f cfds c2)\n       end.\n\nNotation \"c '|[' e ']|' \" := (app_ctx_f c e)  (at level 28, no associativity)\n                             : ctx_scope.\nNotation \"f '<[' e ']>'\" := (app_f_ctx_f f e)  (at level 28, no associativity)\n                            : ctx_scope.\nOpen Scope ctx_scope.\n\nScheme ctx_exp_mut := Induction for exp_ctx Sort Prop\nwith ctx_fundefs_mut := Induction for fundefs_ctx Sort Prop.\n\nScheme ctx_exp_mut' := Induction for exp_ctx Sort Type\nwith ctx_fundefs_mut' := Induction for fundefs_ctx Sort Type.\n\nLemma exp_fundefs_ctx_mutual_ind :\n  forall (P : exp_ctx -> Prop) (P0 : fundefs_ctx -> Prop),\n    P Hole_c ->\n    (forall (v : var) (t : cTag) (l : list var) (e : exp_ctx),\n       P e -> P (Econstr_c v t l e)) ->\n    (forall (v : var) (t : cTag) (n : N) (v0 : var) (e : exp_ctx),\n       P e -> P (Eproj_c v t n v0 e)) ->\n    (forall (v : var) (p : prim) (l : list var) (e : exp_ctx),\n       P e -> P (Eprim_c v p l e)) ->\n    (forall (v : var) (l : list (cTag * exp)) (t : cTag) (e : exp_ctx),\n       P e -> forall l0 : list (cTag * exp), P (Ecase_c v l t e l0)) ->\n    (forall (f4 : fundefs) (e : exp_ctx), P e -> P (Efun1_c f4 e)) ->\n    (forall f5 : fundefs_ctx, P0 f5 -> forall e : exp, P (Efun2_c f5 e)) ->\n    (forall (v : var) (t : fTag) (l : list var) (e : exp_ctx),\n       P e -> forall f6 : fundefs, P0 (Fcons1_c v t l e f6)) ->\n    (forall (v : var) (t : fTag) (l : list var) \n            (e : exp) (f7 : fundefs_ctx), P0 f7 -> P0 (Fcons2_c v t l e f7)) ->\n    (forall e : exp_ctx, P e) /\\ (forall f : fundefs_ctx, P0 f).\nProof.\n  intros. split.\n  apply (ctx_exp_mut P P0); assumption.\n  apply (ctx_fundefs_mut P P0); assumption.\nQed.\n\n(** Name the induction hypotheses only *)\nLtac exp_fundefs_ctx_induction IH1 IH2 :=\n  apply exp_fundefs_ctx_mutual_ind;\n  [ | intros ? ? ? ? IH1 \n    | intros ? ? ? ? ? IH1\n    | intros ? ? ? ? IH1\n    | intros ? ? ? ? IH1\n    | intros ? ? IH1\n    | intros ? IH2 ?\n    | intros ? ? ? ? IH1 ?\n    | intros ? ? ? ? ? IH2 ].\n\n(** Alternative definition of subterm relation *)\nDefinition subterm_e' (e':exp) (e:exp): Prop :=\n  exists c, Hole_c <> c /\\ app_ctx c e' e.\n\nDefinition subterm_or_eq' (e':exp) (e:exp) : Prop :=\n  exists c, app_ctx c e' e.\n\n(** Theorems about context application and composition *)\nLemma app_ctx_f_correct_mut:\n  (forall c e e',\n     c |[ e ]|  = e' <-> app_ctx c e e') /\\\n  (forall cf B B',\n     cf <[ B ]> = B' <-> app_f_ctx cf B B').\nProof. \n  exp_fundefs_ctx_induction IHe IHf; simpl; intros; split; intros H';\n  first\n    [ inversion H'; subst; constructor;\n      eapply IHe; congruence\n    | inversion H'; subst; repeat f_equal; eapply IHe;\n      eassumption\n    | inversion H'; subst; constructor;\n      eapply IHf; congruence\n    | inversion H'; subst; repeat f_equal; eapply IHf ];\n  inversion H'; subst; eassumption.\nQed.\n\nCorollary app_ctx_f_correct :\n  forall c e e',\n    c |[ e ]|  = e' <-> app_ctx c e e'.\nProof.\n  now apply app_ctx_f_correct_mut.\nQed.\n\nCorollary app_f_ctx_f_correct :\n  forall cf B B',\n    cf <[ B ]> = B' <-> app_f_ctx cf B B'.\nProof.\n  now apply app_ctx_f_correct_mut.\nQed.\n\nLemma comp_ctx_f_correct_mut:\n  (forall c c' cc',\n     comp_ctx_f c c'  = cc' <-> comp_ctx c c' cc') /\\\n  (forall cf cf' ccf',\n     comp_f_ctx_f cf cf' = ccf' <-> comp_f_ctx cf cf' ccf').\nProof. \n  exp_fundefs_ctx_induction IHe IHf; simpl; intros; split; intros H';\n  first\n    [ inversion H'; subst; constructor;\n      eapply IHe; congruence\n    | inversion H'; subst; repeat f_equal; eapply IHe;\n      eassumption\n    | inversion H'; subst; constructor;\n      eapply IHf; congruence\n    | inversion H'; subst; repeat f_equal; eapply IHf ];\n  inversion H'; subst; eassumption.\nQed.\n\nCorollary comp_ctx_f_correct :\n  forall c c' cc',\n    comp_ctx_f c c'  = cc' <-> comp_ctx c c' cc'.\nProof.\n  now apply comp_ctx_f_correct_mut.\nQed.\n\nCorollary comp_f_ctx_f_correct :\n  forall cf cf' ccf',\n   comp_f_ctx_f cf cf' = ccf' <-> comp_f_ctx cf cf' ccf'.\nProof.\n  now apply comp_ctx_f_correct_mut.\nQed.\n\nLemma app_ctx_f_fuse_mut :\n  (forall c c' e,\n     c |[ c' |[ e ]| ]| = (comp_ctx_f c c') |[ e ]|) /\\\n  (forall cf c e,\n     cf <[ c |[ e ]| ]> = (comp_f_ctx_f cf c) <[ e ]>).\nProof.\n  exp_fundefs_ctx_induction IHe IHf; simpl; intros;\n  try (rewrite IHe; reflexivity); try (rewrite IHf; reflexivity).\n  reflexivity.\nQed.\n\nCorollary app_ctx_f_fuse :\n  forall c c' e,\n    c |[ c' |[ e ]| ]| = (comp_ctx_f c c') |[ e ]|.\nProof.\n  now apply app_ctx_f_fuse_mut.\nQed.\n\nCorollary app_f_ctx_f_fuse :\n  forall cf c e,\n    cf <[ c |[ e ]| ]> = (comp_f_ctx_f cf c) <[ e ]>.\nProof.\n  now apply app_ctx_f_fuse_mut.\nQed.\n\nLemma app_ctx_fuse:\n  forall (c c' : exp_ctx) (e1 e2 e3 : exp),\n    app_ctx c e1 e2 ->\n    app_ctx c' e2 e3 ->\n    app_ctx (comp_ctx_f c' c) e1 e3.\nProof.\n  intros c c' e1 e2 e3 H1 H2. rewrite <- app_ctx_f_correct.\n  rewrite <- app_ctx_f_fuse.\n  rewrite <- app_ctx_f_correct in H1, H2. rewrite H1. eauto.\nQed.\n\nLemma comp_ctx_f_assoc_mut:\n  (forall c1 c2 c3,\n     comp_ctx_f (comp_ctx_f c1 c2) c3 = comp_ctx_f c1 (comp_ctx_f c2 c3)) /\\\n  (forall f c2 c3, comp_f_ctx_f (comp_f_ctx_f f c2) c3 =\n              comp_f_ctx_f f (comp_ctx_f c2 c3)).\nProof.\n  exp_fundefs_ctx_induction IHc1 IHf; intros; simpl; auto; try (rewrite IHc1; auto).\n  - rewrite IHf; auto.\n  - rewrite IHf; auto.\nQed.\n\nTheorem comp_ctx_f_assoc:\n  (forall c1 c2 c3,\n     comp_ctx_f (comp_ctx_f c1 c2) c3 = comp_ctx_f c1 (comp_ctx_f c2 c3)).\nProof.\n  intros; apply comp_ctx_f_assoc_mut; auto.\nQed.      \n\nTheorem comp_f_ctx_f_assoc:\n  (forall f c2 c3, comp_f_ctx_f (comp_f_ctx_f f c2) c3 =\n              comp_f_ctx_f f (comp_ctx_f c2 c3)).\nProof.\n  intros; apply comp_ctx_f_assoc_mut; auto.\nQed.\n\nTheorem comp_ctx_split_mut:\n  (forall c1 c2 c3 c4,\n     comp_ctx_f c1 c2 = comp_ctx_f c3 c4 ->\n     (exists c41 c42, c4 = comp_ctx_f c41 c42 /\\ c1 = comp_ctx_f c3 c41 /\\ c2 = c42) \\/ \n     (exists c31 c32, c3 = comp_ctx_f c31 c32 /\\ c1 = c31 /\\ c2 = comp_ctx_f c32 c4)) /\\\n  (forall f1 c2 f3 c4, comp_f_ctx_f f1 c2 = comp_f_ctx_f f3 c4 ->\n                  (exists c41 c42, c4 = comp_ctx_f c41 c42 /\\ f1 = comp_f_ctx_f f3 c41 /\\ c2 = c42) \\/\n                  (exists f31 c32, f3 = comp_f_ctx_f f31 c32 /\\ f1 = f31 /\\ c2 = comp_ctx_f c32 c4)).\nProof.\n  exp_fundefs_ctx_induction IHc1 IHf; intros.\n  - simpl in H.\n    right.          \n    exists Hole_c, c3.\n    auto.\n  - simpl in H. destruct c3; inv H.          \n    + simpl in H0.\n      left.\n      destruct c4; inv H0.\n      exists ( Econstr_c v0 c l0 e), c2.\n      auto.\n    + apply IHc1 in H4. destruct H4.\n      * left.\n        destructAll.\n        exists x, x0.\n        auto.\n      * right. destructAll.\n        exists (Econstr_c v0 c l0 x), x0.\n        auto.\n  - simpl in H. destruct c3; inv H.\n    + simpl in H0.\n      left.\n      destruct c4; inv H0.\n      exists ( Eproj_c v1 c n0 v2 e ),  c2; auto.\n    + apply IHc1 in H5. destruct H5.\n      * left.\n        destructAll.\n        exists x, x0.\n        auto.\n      * right. destructAll.\n        exists ( Eproj_c v1 c n0 v2 x), x0;\n          auto.\n  - simpl in H. destruct c3; inv H.\n    + simpl in H0.\n      left.\n      destruct c4; inv H0.\n      exists ( Eprim_c v0 p0 l0 e ),  c2; auto.\n    + apply IHc1 in H4. destruct H4.\n      * left.\n        destructAll.\n        exists x, x0.\n        auto.\n      * right. destructAll.\n        exists (Eprim_c v0 p0 l0 x ), x0;\n          auto.\n  - simpl in H. destruct c3; inv H.\n    + simpl in H0. left.\n      exists (Ecase_c v l t e l0), c2.\n      auto.\n    + apply IHc1 in H4.\n      destruct H4; destructAll.\n      * left.\n        exists x, x0; auto.\n      * right.\n        exists (Ecase_c v0 l1 c x l2), x0.\n        auto.\n  - simpl in H.\n    destruct c3; inv H.\n    + simpl in H0.\n      left.\n      exists (Efun1_c f4 e), c2.\n      auto.\n    + apply IHc1 in H2.\n      destruct H2; destructAll.\n      * left.\n        exists x, x0; auto.\n      * right.\n        exists (Efun1_c f x), x0.\n        auto.              \n  - simpl in H.\n    destruct c3; inv H.\n    + simpl in H0.\n      left.\n      exists (Efun2_c f5 e), c2.\n      auto.\n    + apply IHf in H1.\n      destruct H1.\n      * left.\n        destructAll.\n        simpl. exists x, x0.\n        auto.\n      * right.\n        destructAll.\n        exists ( Efun2_c x e0), x0.\n        auto.\n  - destruct f3; inv H.\n    apply IHc1 in H4.\n    destruct H4; destructAll.\n    * left.\n      simpl.\n      exists x, x0.\n      auto.\n    * right.\n      exists (Fcons1_c v0 c l0 x f), x0; auto.            \n  - simpl in H.\n    destruct f3; inv H.\n    apply IHf in H5.\n    destruct H5.\n    * left.\n      destructAll.\n      simpl. exists x, x0.\n      auto.\n    * right.\n      destructAll.\n      exists (Fcons2_c v0 c l0 e0 x), x0.\n      auto.              \nQed.\n\nTheorem comp_ctx_split:\n  (forall c1 c2 c3 c4,\n     comp_ctx_f c1 c2 = comp_ctx_f c3 c4 ->\n     (exists c41 c42, c4 = comp_ctx_f c41 c42 /\\ c1 = comp_ctx_f c3 c41 /\\ c2 = c42) \\/ \n     (exists c31 c32, c3 = comp_ctx_f c31 c32 /\\ c1 = c31 /\\ c2 = comp_ctx_f c32 c4)).\nProof.\n  apply comp_ctx_split_mut; auto.\nQed.\n\nTheorem comp_f_ctx_split:\n  (forall f1 c2 f3 c4, comp_f_ctx_f f1 c2 = comp_f_ctx_f f3 c4 ->\n                  (exists c41 c42, c4 = comp_ctx_f c41 c42 /\\ f1 = comp_f_ctx_f f3 c41 /\\ c2 = c42) \\/\n                  (exists f31 c32, f3 = comp_f_ctx_f f31 c32 /\\ f1 = f31 /\\ c2 = comp_ctx_f c32 c4)).\nProof.\n  apply comp_ctx_split_mut; auto.\nQed.              \n\n(* prefix a fundefs ctx with a fundefs *)\nFixpoint app_fundefs_ctx (f:fundefs) (fc:fundefs_ctx): fundefs_ctx:=\n  match f with\n    | Fnil => fc\n    | Fcons x t xs e f' =>\n      Fcons2_c x t xs e (app_fundefs_ctx f' fc)\n  end.\n\n\nLemma comp_ctx_f_Hole_c C :\n  comp_ctx_f C Hole_c = C\nwith comp_f_ctx_f_Hole_c f : \n       comp_f_ctx_f f Hole_c = f.\nProof.\n  - destruct C; simpl; eauto;\n    try (rewrite comp_ctx_f_Hole_c; reflexivity). \n    rewrite comp_f_ctx_f_Hole_c. reflexivity.\n  - destruct f; simpl; eauto.\n    rewrite comp_ctx_f_Hole_c; reflexivity.\n    rewrite comp_f_ctx_f_Hole_c. reflexivity.\nQed.\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/ctx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.18745378391780837}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import riscv.util.BitWidths.\nRequire Import riscv.Decode.\nRequire Import riscv.Memory.\nRequire Import riscv.Utility.\n\n\nClass RegisterFile{RF R V: Type} := mkRegisterFile {\n  getReg: RF -> R -> V;\n  setReg: RF -> R -> V -> RF;\n  initialRegs: RF;\n}.\n\nArguments RegisterFile: clear implicits.\n\nSection Riscv.\n\n  Context {mword: Set}.\n  Context {MW: MachineWidth mword}.\n  Context {Mem: Set}.\n  Context {MemIsMem: Memory Mem mword}.\n  Context {RF: Type}.\n  Context {RFI: RegisterFile RF Register mword}.\n  \n  Record RiscvMachineCore := mkRiscvMachineCore {\n    registers: RF;\n    pc: mword;\n    nextPC: mword;\n    exceptionHandlerAddr: MachineInt;\n  }.\n\n  Record RiscvMachine := mkRiscvMachine {\n    core: RiscvMachineCore;\n    machineMem: Mem;\n  }.\n\n  Definition with_registers r ma :=\n    mkRiscvMachine (mkRiscvMachineCore\n        r ma.(core).(pc) ma.(core).(nextPC) ma.(core).(exceptionHandlerAddr))\n        ma.(machineMem).\n  Definition with_pc p ma :=\n    mkRiscvMachine (mkRiscvMachineCore\n        ma.(core).(registers) p ma.(core).(nextPC) ma.(core).(exceptionHandlerAddr))\n        ma.(machineMem).\n  Definition with_nextPC npc ma :=\n    mkRiscvMachine (mkRiscvMachineCore\n        ma.(core).(registers) ma.(core).(pc) npc ma.(core).(exceptionHandlerAddr))\n        ma.(machineMem).\n  Definition with_exceptionHandlerAddr eh ma :=\n    mkRiscvMachine (mkRiscvMachineCore\n        ma.(core).(registers) ma.(core).(pc) ma.(core).(nextPC) eh)\n        ma.(machineMem).\n  Definition with_machineMem m ma :=\n    mkRiscvMachine ma.(core) m.\n\nEnd Riscv.\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/RiscvMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.1874537728241969}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Util.\nRequire Import Common.Memory.\nRequire Import Common.Linking.\nRequire Import Common.CompCertExtensions.\nRequire Import Common.RenamingOption.\nRequire Import Common.Reachability.\nRequire Import CompCert.Events.\nRequire Import CompCert.Smallstep.\nRequire Import CompCert.Behaviors.\nRequire Import Intermediate.Machine.\nRequire Import Intermediate.GlobalEnv.\nRequire Import Intermediate.CS.\nRequire Import Intermediate.CSInvariants.\nRequire Import Intermediate.RecompositionRelCommon.\n\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Setoids.Setoid.\n\nFrom mathcomp Require Import ssreflect ssrnat ssrint ssrfun ssrbool eqtype seq.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nImport Intermediate.\n\n(* Helpers, epsilon and lockstep versions of three-way simulation. *)\nSection ThreewayMultisem1.\n  Variables p c p' c' : program.\n  Variables n n'' : Component.id -> nat.\n  Let n' := fun cid =>\n              if cid \\in domm (prog_interface p)\n              then n   cid\n              else n'' cid.\n  Let ip := prog_interface p.\n  Let ic := prog_interface c.\n  Let prog   := program_link p  c.\n  Let prog'  := program_link p  c'.\n  Let prog'' := program_link p' c'.\n  Let sem   := CS.sem_non_inform prog.\n  Let sem'  := CS.sem_non_inform prog'.\n  Let sem'' := CS.sem_non_inform prog''.\n\n\n   (*[DynShare]\n\n     This lemma should intuitively continue to hold (under some weaker\n     definition of mergeable_states).\n\n     The current proof that is commented below relies on \"to_partial_memory_epsilon_star\",\n     the lemma that does not hold any more in the [DynShare] world.\n\n     We should be able to find a weaker version of \"to_partial_memory_epsilon_star\"\n     that will help us complete the proof of this lemma.\n\n    *)\n\n    (*;\n        try (pose proof to_partial_memory_epsilon_star Hmerge1 Hcomp Hstar12'' Hstep23'' as Hmem23'';\n             simpl in Hmem23''; rewrite Hmem23'');\n        reflexivity.\n  Qed.\n     *)\n\n  (* RB: NOTE: By itself, this lemma no longer says anything interesting, in\n     fact it is trivial because [s1'] and [s1''] are not really related. To add\n     significance to it, one may consider adding the mergeability relation, but\n     then we need to know what [s1] is doing. *)\n  Lemma context_epsilon_star_merge_states s1 s1' s1'' s2'' t t' t'' :\n    mergeable_internal_states p c p' c' n n'' s1 s1' s1'' t t' t'' ->\n    CS.is_program_component s1 ic ->\n    Star sem'' s1'' E0 s2'' ->\n  exists s2',\n    Star sem' s1' E0 s2' /\\\n    mergeable_internal_states p c p' c' n n'' s1 s2' s2'' t t' t''.\n  Admitted. (* RB: TODO: Currently not useful, maybe with tweaks later? *)\n  (* Proof. *)\n  (*   intros Hmerge1 Hcomp1 Hstar12''. *)\n  (*   remember E0 as t12'' eqn:Ht12''. *)\n  (*   revert s1 s1' Hmerge1 Hcomp1 Ht12''. *)\n  (*   induction Hstar12''; intros; subst. *)\n  (*   - exists s1'. now apply star_refl. *)\n  (*   - (* Fix some names quickly for now... *) *)\n  (*     rename s1 into s1''. rename s2 into s2''. rename s3 into s3''. rename s0 into s1. *)\n  (*     (* Back to the proof. *) *)\n  (*     apply Eapp_E0_inv in Ht12'' as [? ?]; subst. *)\n  (*     assert (Hmerge2 : mergeable_states p c p' c' s1 s1' s2''). *)\n  (*     { *)\n  (*       eapply merge_states_silent_star; try eassumption. *)\n  (*       eapply star_step; [eassumption | eapply star_refl | reflexivity]. *)\n  (*     } *)\n  (*     exact (IHHstar12'' _ _ Hmerge2 Hcomp1 eq_refl). *)\n  (* Qed. *)\n\n  (* RB: NOTE: This lemma no longer holds as currently stated: even if [p]\n     steps silently (no calls and returns), it can perform memory-altering\n     operations that will not be reflected in [s1']. It can be repaired by\n     adding a matching [Step] on [sem']. *)\n  Lemma threeway_multisem_mergeable_step_E0 s1 s2 s1' s1'' t t' t'' :\n    CS.is_program_component s1 ic ->\n    mergeable_internal_states p c p' c' n n'' s1 s1' s1'' t t' t'' ->\n    Step sem s1 E0 s2 ->\n  exists s2',\n    Step sem' s1' E0 s2' /\\\n    mergeable_internal_states p c p' c' n n'' s2 s2' s1'' t t' t''.\n  Abort. (* RB: TODO: Check repair, uses. Should be provable, but see\n            [threeway_multisem_step_E0]. *)\n  (* Proof. *)\n  (*   intros Hcomp1 Hmerge1 Hstep12. *)\n  (*   inversion Hmerge1 *)\n  (*     as [s0 s0' s0'' t t' t'' n n' n'' Hwfp Hwfc Hwfp' Hwfc' *)\n  (*         Hmergeable_ifaces Hifacep Hifacec Hprog_is_closed Hprog_is_closed' *)\n  (*         Hini Hini' Hini'' Hstar01 Hstar01' Hstar01'' Hrel' Hrel'']. *)\n  (*   apply mergeable_states_intro with s0 s0' s0'' t t' t'' n n' n''; *)\n  (*     try assumption. *)\n  (*   eapply (star_right _ _ Hstar01 Hstep12); try eassumption. now rewrite E0_right. *)\n  (* Qed. *)\n\n  (* RB: NOTE: The structure follows closely that of\n     threeway_multisem_star_program. *)\n  (* RB: NOTE: Expect the proof to hold, but the statement is in all likelihood\n     not sufficiently informative, as the sequence of steps taken by [s1'] will\n     be hidden by the existential. *)\n\n  (* AEK: This lemma is probably redundant.  *)\n  (*Lemma threeway_multisem_mergeable_program\n        s1 s1' s1'' t1 t1' t1'' t2 t2'' s2 s2'' :\n    CS.is_program_component s1 ic ->\n    mergeable_internal_states p c p' c' n n'' s1 s1' s1'' t1 t1' t1'' ->\n    Star sem   s1   t2   s2   ->\n    Star sem'' s1'' t2'' s2'' ->\n    behavior_rel_behavior_all_cids n n'' (FTbc t2) (FTbc t2'') ->\n    (*mem_rel2 n n'' (CS.state_mem s1, t2) (CS.state_mem s1'', t2'') p -> *)\n  exists s2' t2',\n    mergeable_internal_states p c p' c' n n'' s2 s2' s2''\n                     (t1 ++ t2) (t1' ++ t2') (t1'' ++ t2'').\n  Admitted.*) (* RB: TODO: Wait to see how this will be useful. *)\n  (* Proof. *)\n  (*   intros Hcomp1 Hmerge1 Hstar12 Hstar12'' Hrel''. *)\n  (*   inversion Hmerge1 *)\n  (*     as [s0 s0' s0'' t1 t1' t1'' ? n' ? Hwfp Hwfc Hwfp' Hwfc' *)\n  (*         Hmergeable_ifaces Hifacep Hifacec Hprog_is_closed Hprog_is_closed' *)\n  (*         Hini Hini' Hini'' Hstar01 Hstar01' Hstar01'' Hrel Hrel']. *)\n  (*   (* Assume that we can not only execute the star in the recombined context, *)\n  (*      but also establish the trace relation, here on partial traces. *) *)\n  (*   assert (exists t2' s2', *)\n  (*              Star sem' s1' t2' s2' /\\ *)\n  (*              behavior_rel_behavior_all_cids n n' (FTbc t2) (FTbc t2')) *)\n  (*     as [t2' [s2' [Hstar12' Hrel2']]] *)\n  (*     by admit. *)\n  (*   (* If we do so, we can begin to reconstruct the mergeability relation... *) *)\n  (*   exists s2'. *)\n  (*   eapply mergeable_states_intro; try assumption. *)\n  (*   eassumption. eassumption. eassumption. *)\n  (*   (* The various stars compose easily (and in the way the old proof was *)\n  (*      written). *) *)\n  (*   instantiate (1 := t1 ++ t2). eapply star_trans; try eassumption; reflexivity. *)\n  (*   instantiate (1 := t1' ++ t2'). eapply star_trans; try eassumption; reflexivity. *)\n  (*   instantiate (1 := t1'' ++ t2''). eapply star_trans; try eassumption; reflexivity. *)\n  (*   (* And it should be possible to compose the relations, possibly using some *)\n  (*      of the stars. *) *)\n  (*   instantiate (1 := n'). instantiate (1 := n). admit. *)\n  (*   instantiate (1 := n''). admit. *)\n  (* (* Qed. *) *)\n\n  (* Ltac t_threeway_multisem_step_E0 := *)\n  (*   CS.step_of_executing; *)\n  (*   try eassumption; try reflexivity; *)\n  (*   (* Solve side goals for CS step. *) *)\n  (*   match goal with *)\n  (*   | |- Memory.load _ _ = _ => *)\n  (*     eapply program_load_to_partialized_memory; *)\n  (*     try eassumption; [now rewrite Pointer.inc_preserves_component] *)\n  (*   | |- Memory.store _ _ _ = _ => *)\n  (*     eapply program_store_to_partialized_memory; eassumption *)\n  (*   | |- find_label_in_component _ _ _ = _ => *)\n  (*     eapply find_label_in_component_recombination; eassumption *)\n  (*   | |- find_label_in_procedure _ _ _ = _ => *)\n  (*     eapply find_label_in_procedure_recombination; eassumption *)\n  (*   | |- Memory.alloc _ _ _ = _ => *)\n  (*     eapply program_alloc_to_partialized_memory; eassumption *)\n  (*   | _ => idtac *)\n  (*   end; *)\n  (*   (* Apply linking invariance and solve side goals. *) *)\n  (*   eapply execution_invariant_to_linking; try eassumption; *)\n  (*   [ congruence *)\n  (*   | apply linkable_implies_linkable_mains; congruence *)\n  (*   | apply linkable_implies_linkable_mains; congruence *)\n  (*   | eapply is_program_component_in_domm; eassumption *)\n  (*   ]. *)\n\n  (* Ltac solve_executing_threeway_multisem_step_E0 Hlinkable pc1 := *)\n  (*   eapply execution_invariant_to_linking with (c1 := c); eauto; *)\n  (*   match goal with *)\n  (*   | Hcc' : prog_interface c = _ |- _ => *)\n  (*     match goal with *)\n  (*       Hcomp1 : is_true (CS.is_program_component (?gps2, ?mem2, ?regs2, pc1, ?addrs2) _) *)\n  (*       |- _ => *)\n  (*       match goal with *)\n  (*       | |- linkable _ _ => rewrite Hcc' in Hlinkable; exact Hlinkable *)\n  (*       | |- linkable_mains p c => eapply linkable_implies_linkable_mains; eauto *)\n  (*       | |- linkable_mains p c' => eapply linkable_implies_linkable_mains; eauto; *)\n  (*                                   rewrite Hcc' in Hlinkable; exact Hlinkable *)\n  (*       | |- _ => *)\n  (*         eapply is_program_component_pc_in_domm *)\n  (*           with (s := (gps2, mem2, regs2, pc1, addrs2)) *)\n  (*                (c := c); eauto *)\n  (*       end *)\n  (*     end *)\n  (*   end. *)\n\n  (* RB: NOTE: Another trivial lemma that needs to add the mergeability relation\n     to make up for the information lost by removing the computable state\n     merging functions and hiding the third execution in the relation. *)\n  Theorem threeway_multisem_step_E0 s1 s1' s1'' t1 t1' t1'' s2 :\n    CS.is_program_component s1 ic ->\n    mergeable_internal_states p c p' c' n n'' s1 s1' s1'' t1 t1' t1'' ->\n    Step sem  s1  E0 s2  ->\n  exists s2',\n    Step sem' s1' E0 s2' /\\\n    mergeable_internal_states p c p' c' n n'' s2 s2' s1'' t1 t1' t1''.\n  Proof.\n    intros Hcomp1 Hmerge1 Hstep12.\n    (* NOTE: Keep the context light for now, rewrite lemmas are no longer\n       directly applicable, as [s2'] is not computed explicitly. *)\n    (* inversion Hmerge1 as [_ _ _ _ _ _ _ _ _ _ _ _ _ Hmergeable_ifaces _ _ _ _ _ _ _ _ _ _ _ _]. *)\n    (* Derive some useful facts and begin to expose state structure. *)\n    (* inversion Hmergeable_ifaces as [Hlinkable _]. *)\n    (* rewrite (mergeable_states_merge_program Hcomp1 Hmerge1). *)\n    pose proof CS.silent_step_non_inform_preserves_program_component\n         _ _ _ _ Hcomp1 Hstep12 as Hcomp2.\n    (* pose proof threeway_multisem_mergeable_step_E0 Hcomp1 Hmerge1 Hstep12 *)\n      (* as Hmerge2. *)\n    (* rewrite (mergeable_states_merge_program Hcomp2 Hmerge2). *)\n    (* NOTE: As usual, we should proceed by cases on the step. *)\n    simpl in Hstep12.\n    inversion Hstep12 as [? t ? ? Hstep12' DUMMY Ht DUMMY'];\n      subst; rename Hstep12 into Hstep12_.\n    inversion Hstep12'; subst; rename Hstep12' into Hstep12'_.\n\n    - (* INop *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n          + unfold CS.is_program_component,\n            CS.is_context_component, turn_of, CS.state_turn in *.\n            unfold negb in Hcomp1.\n            pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n            assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        eexists. split.\n        * eapply CS.Step_non_inform; eauto. exact (CS.Nop _ _ _ _ _ Hex'). (* Make more implicit later. *)\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n                 by rewrite E0_right.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; eauto. by eapply CS.Nop.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n  \n    - (* ILabel *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n          + unfold CS.is_program_component,\n            CS.is_context_component, turn_of, CS.state_turn in *.\n            unfold negb in Hcomp1.\n            pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n            assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        eexists. split.\n        * eapply CS.Step_non_inform; eauto. exact (CS.Label _ _ _ _ _ _ Hex'). (* Make more implicit later. *)\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n                 by rewrite E0_right.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; eauto. eapply CS.Label; eauto.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IConst *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n          + unfold CS.is_program_component,\n            CS.is_context_component, turn_of, CS.state_turn in *.\n            unfold negb in Hcomp1.\n            pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n            assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        eexists. split.\n        * eapply CS.Step_non_inform; first eapply CS.Const.\n          -- exact Hex'.\n          -- reflexivity.\n          -- by simpl.\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n                 by rewrite E0_right.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; first eapply CS.Const; eauto.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n          -- inversion Hregsp as [Hregs]. simpl in *. constructor. intros reg.\n             unfold Register.set, Register.get in *.\n             destruct (Register.to_nat reg == Register.to_nat r) eqn:Hreg;\n               rewrite setmE Hreg; specialize (Hregs reg).\n             ++ rewrite setmE Hreg.\n                assert (well_formed_program prog) as Hwf.\n                  by eapply linking_well_formedness; eauto;\n                    unfold mergeable_interfaces in *; intuition.\n                  match goal with\n                  | Hexec: executing (prepare_global_env prog) _ _ |- _ =>\n                    specialize (CS.IConst_possible_values\n                                  _\n                                  Hwf pc v r Hexec)\n                      as Hv\n                  end.\n                  destruct Hv as [[i Hvi] |\n                                  [perm [cid [bid [off [? [? [? ?]]]\n                                             ]]]]].\n                ** left. by subst.\n                ** subst. simpl.\n                   unfold rename_addr_option, sigma_shifting_wrap_bid_in_addr.\n                   simpl.\n                   assert (Pointer.component pc \\in domm (prog_interface p))\n                     as Hpc_p.\n                   {\n                       by specialize\n                            (is_program_component_pc_in_domm Hcomp1 Hmerge1).\n                   }\n                   rewrite Hpc_p.\n                   destruct (sigma_shifting_lefttoright_option\n                               (n (Pointer.component pc))\n                               (n (Pointer.component pc)) Block.local) eqn:ebid.\n                   --- by\n                         left;\n                         apply\n                           sigma_shifting_lefttoright_option_n_n_id in ebid;\n                         subst.\n                   --- right. split; auto; split; auto.\n\n             ++ rewrite setmE Hreg. assumption.\n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IMov *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n          + unfold CS.is_program_component,\n            CS.is_context_component, turn_of, CS.state_turn in *.\n            unfold negb in Hcomp1.\n            pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n            assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        eexists. split.\n        * eapply CS.Step_non_inform; first eapply CS.Mov.\n          -- exact Hex'.\n          -- reflexivity.\n          -- by simpl.\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n                 by rewrite E0_right.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; first eapply CS.Mov; eauto.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n          -- (* regs_rel_of_executing_part *)\n            constructor.\n            match goal with\n            | H: regs_rel_of_executing_part _ _ _ _  |- _ => inversion H as [Hreg] end.\n            intros reg.\n            pose proof (Hreg rsrc)\n              as [Hget_shift | [Hshift_r1_None Heq1]];\n              pose proof (Hreg reg)\n              as [Hreg_shift | [Hshift_reg_None Heq2]];\n              destruct ((Register.to_nat reg == Register.to_nat rdest)) eqn:Hreg_r; simpl;\n                unfold Register.set, Register.get; rewrite !setmE Hreg_r.\n            ++ left. by simpl in *.\n            ++ left. eauto.\n            ++ left. by simpl in *.\n            ++ right. split; eauto.\n            ++ right. split.\n               ** by simpl in *.\n               ** by simpl in *.\n            ++ left. eauto.\n            ++ right. split; eauto.\n            ++ right. split; eauto.\n\n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IBinOp *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n          + unfold CS.is_program_component,\n            CS.is_context_component, turn_of, CS.state_turn in *.\n            unfold negb in Hcomp1.\n            pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n            assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        assert (Pointer.component pc \\in domm (prog_interface p)) as Hpc_p.\n        {\n            by specialize (is_program_component_pc_in_domm Hcomp1 Hmerge1).\n        }\n\n        eexists. split.\n        * eapply CS.Step_non_inform; first eapply CS.BinOp.\n          -- exact Hex'.\n          -- reflexivity.\n          -- by simpl.\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n                 by rewrite E0_right.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; first eapply CS.BinOp; eauto.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n          -- (* regs_rel_of_executing_part *)\n            constructor.\n            match goal with\n            | H: regs_rel_of_executing_part _ _ _ _ |- _ =>\n              inversion H as [Hreg] end.\n            intros reg. simpl in *.\n            destruct ((Register.to_nat reg == Register.to_nat r3)) eqn:Hreg_r; simpl.\n            ++ unfold Register.set, Register.get in *. rewrite !setmE Hreg_r.\n               unfold result, shift_value_option, rename_value_option,\n               rename_value_template_option, sigma_shifting_wrap_bid_in_addr,\n               rename_addr_option in *.\n\n               pose proof (Hreg r1) as rel_r1.\n               pose proof (Hreg r2) as rel_r2.\n               pose proof (Hreg r3) as rel_r3.\n\n               destruct op; simpl.\n               **\n                 (* Add *)\n                 destruct (regs (Register.to_nat r1)) \n                   as [[i1 | [[[perm1 cid1] bid1] off1] |]|] eqn:eregsr1;\n                    destruct (regs1' (Register.to_nat r1))\n                    as [[i1' | [[[perm1' cid1'] bid1'] off1'] |]|] eqn:eregs1'r1;\n                    destruct rel_r1 as [rel_r1_eq |\n                                         [rel_r1_eq\n                                            [rel_r1_eq2 rel_r1_eq'\n                                               (*[rel_r1_shr_t1 rel_r1_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    destruct (regs (Register.to_nat r2)) \n                      as [[i2 | [[[perm2 cid2] bid2] off2] |]|] eqn:eregsr2;\n                    destruct (regs1' (Register.to_nat r2))\n                      as [[i2' | [[[perm2' cid2'] bid2'] off2'] |]|] eqn:eregs1'r2;\n                    destruct rel_r2 as [rel_r2_eq |\n                                        [rel_r2_eq\n                                           [rel_r2_eq2 rel_r2_eq'\n                                              (*[rel_r2_shr_t1 rel_r2_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    try (by left);\n                    inversion rel_r1_eq as [Hrel_r1_eq];\n                    inversion rel_r2_eq as [Hrel_r2_eq];\n                    subst;\n                    try (by left);\n                    unfold Pointer.add;\n                    (* 15 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid2)\n                                        (if cid2 \\in domm (prog_interface p)\n                                         then n cid2 else n'' cid2)\n                                        bid2) as [bid2_shift|] eqn:ebid2_shift;\n                            rewrite ebid2_shift in Hrel_r2_eq; try discriminate\n                          );\n                    (* 9 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid1)\n                                        (if cid1 \\in domm (prog_interface p)\n                                         then n cid1 else n'' cid1)\n                                        bid1) as [bid1_shift|] eqn:ebid1_shift;\n                            rewrite ebid1_shift in Hrel_r1_eq; try discriminate\n                          ).\n\n                 (* 8 subgoals *)\n                  --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                      +++ \n                        destruct (sigma_shifting_lefttoright_option\n                                    (n cid2)\n                                    (if cid2 \\in domm (prog_interface p)\n                                     then n cid2 else n'' cid2)\n                                    bid2) as [bid2_shift|] eqn:ebid2_shift;\n                          rewrite ebid2_shift in Hrel_r2_eq; try discriminate;\n                            rewrite ebid2_shift.\n                        inversion Hrel_r2_eq; subst. by left.\n                      +++ \n                        inversion Hrel_r2_eq; subst. by left.\n                  --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid2)\n                                  (if cid2 \\in domm (prog_interface p)\n                                   then n cid2 else n'' cid2)\n                                  bid2) as [bid2_shift|] eqn:ebid2_shift;\n                        rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                      rewrite ebid2_shift.\n                      inversion rel_r2_eq'; subst.\n                      rewrite eperm2 in rel_r2_eq2. simpl in *.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (if cid2' \\in domm (prog_interface p)\n                                   then n cid2'\n                                   else n'' cid2') (n cid2') bid2') eqn:esigma2';\n                        rewrite esigma2' in rel_r2_eq2; try discriminate.\n                      rewrite eperm2 esigma2'. \n                      right. by intuition.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid1)\n                                  (if cid1 \\in domm (prog_interface p)\n                                   then n cid1 else n'' cid1)\n                                  bid1) as [bid1_shift|] eqn:ebid1_shift;\n                        rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid1)\n                                  (if cid1 \\in domm (prog_interface p)\n                                   then n cid1 else n'' cid1)\n                                  bid1) as [bid1_shift|] eqn:ebid1_shift;\n                        rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                      +++\n                        destruct (sigma_shifting_lefttoright_option\n                                    (n cid1)\n                                    (if cid1 \\in domm (prog_interface p)\n                                     then n cid1 else n'' cid1)\n                                    bid1) as [bid1_shift|] eqn:ebid1_shift;\n                          rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                        rewrite ebid1_shift.\n                        inversion Hrel_r1_eq. subst. by left.\n                      +++\n                        inversion Hrel_r1_eq. subst. by left.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid1)\n                                  (if cid1 \\in domm (prog_interface p)\n                                   then n cid1 else n'' cid1)\n                                  bid1) as [bid1_shift|] eqn:ebid1_shift;\n                        rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                      rewrite ebid1_shift. inversion rel_r1_eq'. subst.\n                      inversion Hrel_r1_eq.\n                      rewrite eperm1 in rel_r1_eq2. simpl in *.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (if cid1' \\in domm (prog_interface p)\n                                   then n cid1'\n                                   else n'' cid1') (n cid1') bid1') eqn:esigma1';\n                        rewrite esigma1' in rel_r1_eq2; try discriminate.\n                      rewrite eperm1 esigma1'.\n                      right; by intuition.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid1)\n                                  (if cid1 \\in domm (prog_interface p)\n                                   then n cid1 else n'' cid1)\n                                  bid1) as [bid1_shift|] eqn:ebid1_shift;\n                        rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                  --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                        try discriminate.\n                      destruct (sigma_shifting_lefttoright_option\n                                  (n cid1)\n                                  (if cid1 \\in domm (prog_interface p)\n                                   then n cid1 else n'' cid1)\n                                  bid1) as [bid1_shift|] eqn:ebid1_shift;\n                        rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n\n\n               **\n                 (* Minus *)\n                 destruct (regs (Register.to_nat r1)) \n                   as [[i1 | [[[perm1 cid1] bid1] off1] |]|] eqn:eregsr1;\n                    destruct (regs1' (Register.to_nat r1))\n                    as [[i1' | [[[perm1' cid1'] bid1'] off1'] |]|] eqn:eregs1'r1;\n                    destruct rel_r1 as [rel_r1_eq |\n                                         [rel_r1_eq\n                                            [rel_r1_eq2 rel_r1_eq'\n                                               (*[rel_r1_shr_t1 rel_r1_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    destruct (regs (Register.to_nat r2)) \n                      as [[i2 | [[[perm2 cid2] bid2] off2] |]|] eqn:eregsr2;\n                    destruct (regs1' (Register.to_nat r2))\n                      as [[i2' | [[[perm2' cid2'] bid2'] off2'] |]|] eqn:eregs1'r2;\n                    destruct rel_r2 as [rel_r2_eq |\n                                        [rel_r2_eq\n                                           [rel_r2_eq2 rel_r2_eq'\n                                              (*[rel_r2_shr_t1 rel_r2_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    try (by left);\n                    inversion rel_r1_eq as [Hrel_r1_eq];\n                    inversion rel_r2_eq as [Hrel_r2_eq];\n                    subst;\n                    try (by left);\n                    unfold Pointer.sub;\n                    (* 31 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid1)\n                                        (if cid1 \\in domm (prog_interface p)\n                                         then n cid1 else n'' cid1)\n                                        bid1) as [bid1_shift|] eqn:ebid1_shift;\n                            rewrite ebid1_shift in Hrel_r1_eq; try discriminate\n                          );\n                    (* 13 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid2)\n                                        (if cid2 \\in domm (prog_interface p)\n                                         then n cid2 else n'' cid2)\n                                        bid2) as [bid2_shift|] eqn:ebid2_shift;\n                            rewrite ebid2_shift in Hrel_r2_eq; try discriminate\n                          ).\n\n                 (* 10 subgoals *)\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                     +++\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n cid1)\n                                   (if cid1 \\in domm (prog_interface p)\n                                    then n cid1 else n'' cid1)\n                                   bid1) as [bid1_shift|] eqn:ebid1_shift;\n                         rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                       rewrite ebid1_shift.\n                       inversion Hrel_r1_eq. subst. by left.\n                     +++\n                       inversion Hrel_r1_eq. subst. by left.\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                     +++\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n cid1)\n                                   (if cid1 \\in domm (prog_interface p)\n                                    then n cid1 else n'' cid1)\n                                   bid1) as [bid1_shift|] eqn:ebid1_shift;\n                         rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                       inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2)\n                                     bid2) as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         destruct ((Permission.eqb perm1' perm2') &&\n                                   (cid1' =? cid2') &&\n                                   (bid1 =? bid2)) eqn:eandb.\n                         ----\n                           symmetry in eandb.\n                           apply andb_true_eq in eandb as [eandb1 eandb2].\n                           apply andb_true_eq in eandb1 as [eandb1 eandb3].\n                           rewrite <- eandb1, <- eandb3, !andTb.\n                           \n                           assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                           assert (bid1 = bid2). by apply beq_nat_true. subst.\n                           \n                           rewrite ebid1_shift in ebid2_shift. inversion ebid2_shift.\n                           subst.\n                           \n                           left. by rewrite <- beq_nat_refl.\n                         ----\n                           left.\n                           destruct (Permission.eqb perm1' perm2') eqn:eperm12.\n                           ++++\n                             destruct (cid1' =? cid2') eqn:ecid12.\n                             ****\n                               destruct (bid1 =? bid2) eqn:ebid12; try discriminate.\n                               assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                               assert (bid1' <> bid2') as Hneq.\n                               {\n                                 unfold not. intros. subst.\n                                 assert (bid1 = bid2).\n                                   by eapply\n                                        sigma_shifting_lefttoright_option_Some_inj;\n                                     eauto.\n                                   subst.\n                                     by rewrite <- beq_nat_refl in ebid12.\n                               }\n                               assert (bid1' =? bid2' = false) as G.\n                                 by rewrite Nat.eqb_neq.\n\n                                 by rewrite G !andbF.\n\n                             ****\n                               by rewrite !andFb.\n                           ++++\n                               by rewrite !andFb.\n                               \n                       ***\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm1' = Permission.data). by apply /Permission.eqP.\n                           subst.\n                           move : eperm2 => /Permission.eqP => eperm2.\n                           destruct (Permission.eqb Permission.data perm2')\n                                    eqn:econtra; auto.\n                           assert (Permission.data = perm2'). by apply /Permission.eqP.\n                           by subst.\n                         }\n                         left. by rewrite G !andFb.\n                     +++\n                       left. inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                           as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm2' = Permission.data). by apply /Permission.eqP.\n                           subst. assumption.\n                         }\n                           by rewrite G !andFb.\n                       ***\n                         inversion Hrel_r2_eq. subst.\n                           by destruct ((Permission.eqb perm1' perm2') &&\n                                        (cid1' =? cid2') &&\n                                        (bid1' =? bid2')).\n                           \n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       last discriminate.\n\n                     assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                       \n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2) bid2)\n                       as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                     inversion rel_r2_eq'. subst.\n                     destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                     +++\n                       assert (perm1 = Permission.data). by apply /Permission.eqP.\n                       subst.\n                       destruct (sigma_shifting_lefttoright_option\n                                     (n cid1)\n                                     (if cid1 \\in domm (prog_interface p)\n                                      then n cid1 else n'' cid1) bid1)\n                         as [bid1_shift|] eqn:ebid1_shift;\n                         rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                         inversion Hrel_r1_eq. subst.\n                         rewrite andTb.\n                         destruct (cid1' =? cid2') eqn:ecid12.\n                       ***\n                         assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                         rewrite andTb.\n                         destruct (bid1 =? bid2') eqn:ebid1_bid2'; auto.\n                         ----\n                           assert (bid1 = bid2'). by apply beq_nat_true. subst.\n                           by rewrite ebid1_shift in ebid2_shift.\n                         ----\n                           simpl in *. rewrite ebid2_shift.\n                           destruct (bid1' =? bid2') eqn:ebid1'2'.\n                           ****\n                             assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                             assert (CSInvariants.wf_ptr_wrt_cid_t\n                                       (Pointer.component pc)\n                                       t1'\n                                       (Permission.data, cid2', bid2', off2'))\n                                   as Hwf.\n                             {\n                               eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                                 last (by simpl);\n                                 last (unfold Register.get;\n                                         by erewrite eregs1'r2).\n                               eapply CSInvariants.wf_state_wf_reg\n                                 with (s := (gps1', mem1', regs1', pc)); eauto.\n                               eapply CSInvariants.is_prefix_wf_state_t;\n                                 last exact Hpref_t'.\n                               - eapply interface_preserves_closedness_r; eauto.\n                                 + by unfold mergeable_interfaces in *; intuition.\n                                 + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                                 + apply interface_implies_matching_mains; auto.\n                               - eapply linking_well_formedness; eauto.\n                                 unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                             }\n                             inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                             -----\n                               assert (Pointer.component pc \\in domm\n                                                                  (prog_interface p))\n                               as G. by eapply mergeable_states_program_component_domm;\n                                       eauto.\n                             rewrite G in ebid2_shift.\n                             rewrite G in ebid1_shift.\n                             apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid1_shift.\n                             by rewrite sigma_shifting_righttoleft_lefttoright\n                               ebid2_shift in ebid1_shift.\n                             -----\n                               inversion Hgood_t' as [? Hcontra]; subst.\n                             specialize (Hcontra _ Hshr) as contra.\n                             unfold left_addr_good_for_shifting in *.\n                             erewrite sigma_lefttoright_Some_spec in contra.\n                             (* TODO: The following destruct fails in some\n                                still-supported Coq versions, e.g. 8.9. Fix\n                                later or adjust dependencies. *)\n                             destruct contra as [? G].\n                               by erewrite G in rel_r2_eq2.\n                           ****\n                             by left.\n                       *** rewrite !andFb. by left.\n                     +++\n                       inversion Hrel_r1_eq. subst.\n                       rewrite eperm1 !andFb. by left.\n\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       last discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       last discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm2;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1)\n                                 bid1) as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     rewrite ebid1_shift. inversion rel_r1_eq'. subst.\n                     rewrite eperm2 in rel_r1_eq2. simpl in *.\n                     destruct (\n                         sigma_shifting_lefttoright_option\n                           (if cid1' \\in domm (prog_interface p)\n                            then n cid1'\n                            else n'' cid1') (n cid1') bid1'\n                       ) eqn:esigma1'; rewrite esigma1' in rel_r1_eq2;\n                       try discriminate.\n                     rewrite eperm2 esigma1'.\n                     by right; intuition.\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                       last discriminate.\n\n                     assert (perm1 = Permission.data). by apply /Permission.eqP. subst.\n                       \n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1) bid1)\n                       as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     inversion rel_r1_eq'. subst.\n                     destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                     +++\n                       assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                       destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                         as [bid2_shift|] eqn:ebid2_shift;\n                         rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         rewrite andTb.\n                         destruct (cid1' =? cid2') eqn:ecid21.\n                       ***\n                         assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                         rewrite andTb.\n                         destruct (bid1' =? bid2) eqn:ebid2_bid1'; auto.\n                         ----\n                           assert (bid1' = bid2). by apply beq_nat_true. subst.\n                           by rewrite ebid2_shift in ebid1_shift.\n                         ----\n                           simpl in *. rewrite ebid1_shift.\n                           destruct (bid1' =? bid2') eqn:ebid2'1'.\n                           ****\n                             assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                             assert (CSInvariants.wf_ptr_wrt_cid_t\n                                       (Pointer.component pc)\n                                       t1'\n                                       (Permission.data, cid2', bid2', off2'))\n                                   as Hwf.\n                             {\n                               eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                                 last (by simpl);\n                                 last (unfold Register.get;\n                                         by erewrite eregs1'r2).\n                               eapply CSInvariants.wf_state_wf_reg\n                                 with (s := (gps1', mem1', regs1', pc)); eauto.\n                               eapply CSInvariants.is_prefix_wf_state_t;\n                                 last exact Hpref_t'.\n                               - eapply interface_preserves_closedness_r; eauto.\n                                 + by unfold mergeable_interfaces in *; intuition.\n                                 + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                                 + apply interface_implies_matching_mains; auto.\n                               - eapply linking_well_formedness; eauto.\n                                 unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                             }\n                             inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                             -----\n                               assert (Pointer.component pc \\in domm\n                                                                  (prog_interface p))\n                               as G. by eapply mergeable_states_program_component_domm;\n                                       eauto.\n                             rewrite G in ebid1_shift.\n                             rewrite G in ebid2_shift.\n                             apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid2_shift.\n                             by rewrite sigma_shifting_righttoleft_lefttoright\n                               ebid1_shift in ebid2_shift.\n                             -----\n                               inversion Hgood_t' as [? Hcontra]; subst.\n                             specialize (Hcontra _ Hshr) as contra.\n                             unfold left_addr_good_for_shifting in *.\n                             erewrite sigma_lefttoright_Some_spec in contra.\n                             destruct contra as [? G].\n                               by erewrite G in rel_r1_eq2.\n                           ****\n                             by left.\n                       *** rewrite !andFb. by left.\n                     +++\n                       inversion Hrel_r2_eq. subst.\n                       destruct (Permission.eqb Permission.data perm2') eqn:perm2contra; auto.\n                       assert (Permission.data = perm2'). by apply /Permission.eqP.\n                       by subst.\n\n                 --- inversion rel_r1_eq'. subst.\n                     inversion rel_r2_eq'. subst.\n\n                     by destruct ((Permission.eqb perm1' perm2') &&\n                                  (cid1' =? cid2') &&\n                                  (bid1' =? bid2')); auto.\n\n               **\n                 (* Mul *)\n                 destruct (regs (Register.to_nat r1)) \n                   as [[i1 | [[[perm1 cid1] bid1] off1] |]|] eqn:eregsr1;\n                    destruct (regs1' (Register.to_nat r1))\n                    as [[i1' | [[[perm1' cid1'] bid1'] off1'] |]|] eqn:eregs1'r1;\n                    destruct rel_r1 as [rel_r1_eq |\n                                         [rel_r1_eq\n                                            [rel_r1_eq2 rel_r1_eq'\n                                               (*[rel_r1_shr_t1 rel_r1_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    destruct (regs (Register.to_nat r2)) \n                      as [[i2 | [[[perm2 cid2] bid2] off2] |]|] eqn:eregsr2;\n                    destruct (regs1' (Register.to_nat r2))\n                      as [[i2' | [[[perm2' cid2'] bid2'] off2'] |]|] eqn:eregs1'r2;\n                    destruct rel_r2 as [rel_r2_eq |\n                                        [rel_r2_eq\n                                           [rel_r2_eq2 rel_r2_eq'\n                                                       (*[rel_r2_shr_t1 rel_r2_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    try (by left);\n                    inversion rel_r1_eq as [Hrel_r1_eq];\n                    inversion rel_r2_eq as [Hrel_r2_eq];\n                    subst;\n                    try (by left).\n\n                 (* 3 subgoals *)\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1)\n                                 bid1) as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n\n                 --- destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                       try discriminate.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid2_shift|] eqn:ebid2_shift;\n                       rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n\n\n\n\n               **\n                 (* Eq *)\n                 destruct (regs (Register.to_nat r1)) \n                   as [[i1 | [[[perm1 cid1] bid1] off1] |]|] eqn:eregsr1;\n                    destruct (regs1' (Register.to_nat r1))\n                    as [[i1' | [[[perm1' cid1'] bid1'] off1'] |]|] eqn:eregs1'r1;\n                    destruct rel_r1 as [rel_r1_eq |\n                                         [rel_r1_eq\n                                            [rel_r1_eq2 rel_r1_eq'\n                                                        (*[rel_r1_shr_t1 rel_r1_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    destruct (regs (Register.to_nat r2)) \n                      as [[i2 | [[[perm2 cid2] bid2] off2] |]|] eqn:eregsr2;\n                    destruct (regs1' (Register.to_nat r2))\n                      as [[i2' | [[[perm2' cid2'] bid2'] off2'] |]|] eqn:eregs1'r2;\n                    destruct rel_r2 as [rel_r2_eq |\n                                        [rel_r2_eq\n                                           [rel_r2_eq2 rel_r2_eq'\n                                                       (*[rel_r2_shr_t1 rel_r2_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    try (by left);\n                    inversion rel_r1_eq as [Hrel_r1_eq];\n                    inversion rel_r2_eq as [Hrel_r2_eq];\n                    subst;\n                    try (by left);\n                    unfold Pointer.eq;\n                    (* 27 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid1)\n                                        (if cid1 \\in domm (prog_interface p)\n                                         then n cid1 else n'' cid1)\n                                        bid1) as [bid1_shift|] eqn:ebid1_shift;\n                            rewrite ebid1_shift in Hrel_r1_eq; try discriminate\n                          );\n                    (* 11 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid2)\n                                        (if cid2 \\in domm (prog_interface p)\n                                         then n cid2 else n'' cid2)\n                                        bid2) as [bid2_shift|] eqn:ebid2_shift;\n                            rewrite ebid2_shift in Hrel_r2_eq; try discriminate\n                          ).\n\n                 (* 8 subgoals *)\n                 --- \n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                     +++\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n cid1)\n                                   (if cid1 \\in domm (prog_interface p)\n                                    then n cid1 else n'' cid1)\n                                   bid1) as [bid1_shift|] eqn:ebid1_shift;\n                         rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                       inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2)\n                                     bid2) as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         destruct ((Permission.eqb perm1' perm2') &&\n                                   (cid1' =? cid2') &&\n                                   (bid1 =? bid2)) eqn:eandb.\n                         ----\n                           symmetry in eandb.\n                           apply andb_true_eq in eandb as [eandb1 eandb2].\n                           apply andb_true_eq in eandb1 as [eandb1 eandb3].\n                           rewrite <- eandb1, <- eandb3, !andTb.\n                           \n                           assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                           assert (bid1 = bid2). by apply beq_nat_true. subst.\n                           \n                           rewrite ebid1_shift in ebid2_shift. inversion ebid2_shift.\n                           subst.\n                           \n                           left. by rewrite <- beq_nat_refl.\n                         ----\n                           left.\n                           destruct (Permission.eqb perm1' perm2') eqn:eperm12.\n                           ++++\n                             destruct (cid1' =? cid2') eqn:ecid12.\n                             ****\n                               destruct (bid1 =? bid2) eqn:ebid12; try discriminate.\n                               assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                               assert (bid1' <> bid2') as Hneq.\n                               {\n                                 unfold not. intros. subst.\n                                 assert (bid1 = bid2).\n                                   by eapply\n                                        sigma_shifting_lefttoright_option_Some_inj;\n                                     eauto.\n                                   subst.\n                                     by rewrite <- beq_nat_refl in ebid12.\n                               }\n                               assert (bid1' =? bid2' = false) as G.\n                                 by rewrite Nat.eqb_neq.\n\n                                 by rewrite G !andbF.\n\n                             ****\n                               by rewrite !andFb.\n                           ++++\n                               by rewrite !andFb.\n                               \n                       ***\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm1' = Permission.data). by apply /Permission.eqP.\n                           subst.\n                           move : eperm2 => /Permission.eqP => eperm2.\n                           destruct (Permission.eqb Permission.data perm2')\n                                    eqn:econtra; auto.\n                           assert (Permission.data = perm2'). by apply /Permission.eqP.\n                           by subst.\n                         }\n                         left. by rewrite G !andFb.\n                     +++\n                       left. inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                           as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm2' = Permission.data). by apply /Permission.eqP.\n                           subst. assumption.\n                         }\n                           by rewrite G !andFb.\n                       ***\n                         inversion Hrel_r2_eq. subst.\n                           by destruct ((Permission.eqb perm1' perm2') &&\n                                        (cid1' =? cid2') &&\n                                        (bid1' =? bid2')).\n                 --- \n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate.\n\n                   assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                   \n                   destruct (sigma_shifting_lefttoright_option\n                               (n cid2)\n                               (if cid2 \\in domm (prog_interface p)\n                                then n cid2 else n'' cid2) bid2)\n                     as [bid2_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                   inversion rel_r2_eq'. subst.\n                   destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                   +++\n                     assert (perm1 = Permission.data). by apply /Permission.eqP. subst.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1) bid1)\n                       as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     inversion Hrel_r1_eq. subst.\n                     rewrite andTb.\n                     destruct (cid1' =? cid2') eqn:ecid12.\n                     ***\n                       assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                       rewrite andTb.\n                       destruct (bid1 =? bid2') eqn:ebid1_bid2'; auto.\n                       ----\n                         assert (bid1 = bid2'). by apply beq_nat_true. subst.\n                           by rewrite ebid1_shift in ebid2_shift.\n                       ----\n                         simpl in *. rewrite ebid2_shift.\n                         destruct (bid1' =? bid2') eqn:ebid1'2'.\n                         ****\n                           assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                           assert (CSInvariants.wf_ptr_wrt_cid_t\n                                     (Pointer.component pc)\n                                     t1'\n                                     (Permission.data, cid2', bid2', off2'))\n                             as Hwf.\n                           {\n                             eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                               last (by simpl);\n                               last (unfold Register.get;\n                                       by erewrite eregs1'r2).\n                             eapply CSInvariants.wf_state_wf_reg\n                               with (s := (gps1', mem1', regs1', pc)); eauto.\n                             eapply CSInvariants.is_prefix_wf_state_t;\n                                 last exact Hpref_t'.\n                             - eapply interface_preserves_closedness_r; eauto.\n                               + by unfold mergeable_interfaces in *; intuition.\n                               + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                               + apply interface_implies_matching_mains; auto.\n                             - eapply linking_well_formedness; eauto.\n                               unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                           }\n                           inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                           -----\n                             assert (Pointer.component pc \\in domm\n                                                                (prog_interface p))\n                             as G. by eapply mergeable_states_program_component_domm;\n                                     eauto.\n                           rewrite G in ebid2_shift.\n                           rewrite G in ebid1_shift.\n                           apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid1_shift.\n                             by rewrite sigma_shifting_righttoleft_lefttoright\n                               ebid2_shift in ebid1_shift.\n                             \n                             -----\n                               inversion Hgood_t' as [? Hcontra]; subst.\n                             specialize (Hcontra _ Hshr) as contra.\n                             unfold left_addr_good_for_shifting in *.\n                             erewrite sigma_lefttoright_Some_spec in contra.\n                             destruct contra as [? G].\n                               by erewrite G in rel_r2_eq2.\n                         ****\n                             by left.\n                     *** rewrite !andFb. by left.\n                   +++\n                     inversion Hrel_r1_eq. subst.\n                     rewrite eperm1 !andFb. by left.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                       try discriminate.\n\n                     assert (perm1 = Permission.data). by apply /Permission.eqP. subst.\n                       \n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1) bid1)\n                       as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     inversion rel_r1_eq'. subst.\n                     destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                     +++\n                       assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                       destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                         as [bid2_shift|] eqn:ebid2_shift;\n                         rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         rewrite andTb.\n                         destruct (cid1' =? cid2') eqn:ecid21.\n                       ***\n                         assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                         rewrite andTb.\n                         destruct (bid1' =? bid2) eqn:ebid2_bid1'; auto.\n                         ----\n                           assert (bid1' = bid2). by apply beq_nat_true. subst.\n                           by rewrite ebid2_shift in ebid1_shift.\n                         ----\n                           simpl in *. rewrite ebid1_shift.\n                           destruct (bid1' =? bid2') eqn:ebid2'1'.\n                           ****\n                             assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                             assert (CSInvariants.wf_ptr_wrt_cid_t\n                                       (Pointer.component pc)\n                                       t1'\n                                       (Permission.data, cid2', bid2', off2'))\n                                   as Hwf.\n                             {\n                               eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                                 last (by simpl);\n                                 last (unfold Register.get;\n                                         by erewrite eregs1'r2).\n                               eapply CSInvariants.wf_state_wf_reg\n                                 with (s := (gps1', mem1', regs1', pc)); eauto.\n                               eapply CSInvariants.is_prefix_wf_state_t;\n                                 last exact Hpref_t'.\n                               - eapply interface_preserves_closedness_r; eauto.\n                                 + by unfold mergeable_interfaces in *; intuition.\n                                 + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                                 + apply interface_implies_matching_mains; auto.\n                               - eapply linking_well_formedness; eauto.\n                                 unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                             }\n                             inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                             -----\n                               assert (Pointer.component pc \\in domm\n                                                                  (prog_interface p))\n                               as G. by eapply mergeable_states_program_component_domm;\n                                       eauto.\n                             rewrite G in ebid2_shift.\n                             rewrite G in ebid1_shift.\n                             apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid2_shift.\n                               by rewrite sigma_shifting_righttoleft_lefttoright\n                                          ebid1_shift in ebid2_shift.\n                           \n                             -----\n                               inversion Hgood_t' as [? Hcontra]; subst.\n                             specialize (Hcontra _ Hshr) as contra.\n                             unfold left_addr_good_for_shifting in *.\n                             erewrite sigma_lefttoright_Some_spec in contra.\n                             destruct contra as [? G].\n                               by erewrite G in rel_r1_eq2.\n                           ****\n                             by left.\n                       *** rewrite !andFb. by left.\n                     +++\n                       inversion Hrel_r2_eq. subst.\n                       destruct (Permission.eqb Permission.data perm2') eqn:perm2contra; auto.\n                       \n                 ---\n                   inversion rel_r1_eq'. inversion rel_r2_eq'. subst. by left. \n\n                 \n               ** \n                 (* Leq *)\n                 destruct (regs (Register.to_nat r1)) \n                   as [[i1 | [[[perm1 cid1] bid1] off1] |]|] eqn:eregsr1;\n                    destruct (regs1' (Register.to_nat r1))\n                    as [[i1' | [[[perm1' cid1'] bid1'] off1'] |]|] eqn:eregs1'r1;\n                    destruct rel_r1 as [rel_r1_eq |\n                                         [rel_r1_eq\n                                            [rel_r1_eq2 rel_r1_eq'\n                                                        (*[rel_r1_shr_t1 rel_r1_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    destruct (regs (Register.to_nat r2)) \n                      as [[i2 | [[[perm2 cid2] bid2] off2] |]|] eqn:eregsr2;\n                    destruct (regs1' (Register.to_nat r2))\n                      as [[i2' | [[[perm2' cid2'] bid2'] off2'] |]|] eqn:eregs1'r2;\n                    destruct rel_r2 as [rel_r2_eq |\n                                        [rel_r2_eq\n                                           [rel_r2_eq2 rel_r2_eq'\n                                                       (*[rel_r2_shr_t1 rel_r2_shr_t1']*)\n                                       ]]];\n                    try discriminate;\n                    try (by left);\n                    inversion rel_r1_eq as [Hrel_r1_eq];\n                    inversion rel_r2_eq as [Hrel_r2_eq];\n                    subst;\n                    try (by left);\n                    unfold Pointer.leq;\n                    (* 27 subgoals *)\n                    \n                    try by (\n                            destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid1)\n                                        (if cid1 \\in domm (prog_interface p)\n                                         then n cid1 else n'' cid1)\n                                        bid1) as [bid1_shift|] eqn:ebid1_shift;\n                            rewrite ebid1_shift in Hrel_r1_eq; try discriminate\n                          );\n                    (* 11 subgoals *)\n\n                    try by (\n                            destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                            try discriminate;\n                            destruct (sigma_shifting_lefttoright_option\n                                        (n cid2)\n                                        (if cid2 \\in domm (prog_interface p)\n                                         then n cid2 else n'' cid2)\n                                        bid2) as [bid2_shift|] eqn:ebid2_shift;\n                            rewrite ebid2_shift in Hrel_r2_eq; try discriminate\n                          ).\n\n\n                 (* 8 subgoals *)\n                 --- \n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                     +++\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n cid1)\n                                   (if cid1 \\in domm (prog_interface p)\n                                    then n cid1 else n'' cid1)\n                                   bid1) as [bid1_shift|] eqn:ebid1_shift;\n                         rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                       inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2)\n                                     bid2) as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         destruct ((Permission.eqb perm1' perm2') &&\n                                   (cid1' =? cid2') &&\n                                   (bid1 =? bid2)) eqn:eandb.\n                         ----\n                           symmetry in eandb.\n                           apply andb_true_eq in eandb as [eandb1 eandb2].\n                           apply andb_true_eq in eandb1 as [eandb1 eandb3].\n                           rewrite <- eandb1, <- eandb3, !andTb.\n                           \n                           assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                           assert (bid1 = bid2). by apply beq_nat_true. subst.\n                           \n                           rewrite ebid1_shift in ebid2_shift. inversion ebid2_shift.\n                           subst.\n                           \n                           left. by rewrite <- beq_nat_refl.\n                         ----\n                           left.\n                           destruct (Permission.eqb perm1' perm2') eqn:eperm12.\n                           ++++\n                             destruct (cid1' =? cid2') eqn:ecid12.\n                             ****\n                               destruct (bid1 =? bid2) eqn:ebid12; try discriminate.\n                               assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                               assert (bid1' <> bid2') as Hneq.\n                               {\n                                 unfold not. intros. subst.\n                                 assert (bid1 = bid2).\n                                   by eapply\n                                        sigma_shifting_lefttoright_option_Some_inj;\n                                     eauto.\n                                   subst.\n                                     by rewrite <- beq_nat_refl in ebid12.\n                               }\n                               assert (bid1' =? bid2' = false) as G.\n                                 by rewrite Nat.eqb_neq.\n\n                                 by rewrite G !andbF.\n\n                             ****\n                               by rewrite !andFb.\n                           ++++\n                               by rewrite !andFb.\n                               \n                       ***\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm1' = Permission.data). by apply /Permission.eqP.\n                           subst.\n                           move : eperm2 => /Permission.eqP => eperm2.\n                           destruct (Permission.eqb Permission.data perm2')\n                                    eqn:econtra; auto.\n                           assert (Permission.data = perm2'). by apply /Permission.eqP.\n                           by subst.\n                         }\n                         left. by rewrite G !andFb.\n                     +++\n                       left. inversion Hrel_r1_eq. subst.\n                       destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                       ***\n                         destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                           as [bid2_shift|] eqn:ebid2_shift;\n                           rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         assert (Permission.eqb perm1' perm2' = false) as G.\n                         {\n                           assert (perm2' = Permission.data). by apply /Permission.eqP.\n                           subst. assumption.\n                         }\n                           by rewrite G !andFb.\n                       ***\n                         inversion Hrel_r2_eq. subst.\n                           by destruct ((Permission.eqb perm1' perm2') &&\n                                        (cid1' =? cid2') &&\n                                        (bid1' =? bid2')).\n                 --- \n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     last discriminate.\n\n                   assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                   \n                   destruct (sigma_shifting_lefttoright_option\n                               (n cid2)\n                               (if cid2 \\in domm (prog_interface p)\n                                then n cid2 else n'' cid2) bid2)\n                     as [bid2_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                   inversion rel_r2_eq'. subst.\n                   destruct (Permission.eqb perm1 Permission.data) eqn:eperm1.\n                   +++\n                     assert (perm1 = Permission.data). by apply /Permission.eqP. subst.\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1) bid1)\n                       as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     inversion Hrel_r1_eq. subst.\n                     rewrite andTb.\n                     destruct (cid1' =? cid2') eqn:ecid12.\n                     ***\n                       assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                       rewrite andTb.\n                       destruct (bid1 =? bid2') eqn:ebid1_bid2'; auto.\n                       ----\n                         assert (bid1 = bid2'). by apply beq_nat_true. subst.\n                           by rewrite ebid1_shift in ebid2_shift.\n                       ----\n                         simpl in *. rewrite ebid2_shift.\n                         destruct (bid1' =? bid2') eqn:ebid1'2'.\n                         ****\n                           assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                           assert (CSInvariants.wf_ptr_wrt_cid_t\n                                     (Pointer.component pc)\n                                     t1'\n                                     (Permission.data, cid2', bid2', off2'))\n                             as Hwf.\n                           {\n                             eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                               last (by simpl);\n                               last (unfold Register.get;\n                                       by erewrite eregs1'r2).\n                             eapply CSInvariants.wf_state_wf_reg\n                               with (s := (gps1', mem1', regs1', pc)); eauto.\n                             eapply CSInvariants.is_prefix_wf_state_t;\n                               last exact Hpref_t'.\n                             - eapply interface_preserves_closedness_r; eauto.\n                               + by unfold mergeable_interfaces in *; intuition.\n                               + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                               + apply interface_implies_matching_mains; auto.\n                             - eapply linking_well_formedness; eauto.\n                               unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                           }\n                           inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                           -----\n                             assert (Pointer.component pc \\in domm\n                                                                (prog_interface p))\n                             as G. by eapply mergeable_states_program_component_domm;\n                                     eauto.\n                             rewrite G in ebid2_shift.\n                             rewrite G in ebid1_shift.\n                             apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid1_shift.\n                               by rewrite sigma_shifting_righttoleft_lefttoright\n                                          ebid2_shift in ebid1_shift.\n                           \n                               -----\n                                 inversion Hgood_t' as [? Hcontra]; subst.\n                               specialize (Hcontra _ Hshr) as contra.\n                               unfold left_addr_good_for_shifting in *.\n                               erewrite sigma_lefttoright_Some_spec in contra.\n                               destruct contra as [? G].\n                                 by erewrite G in rel_r2_eq2.\n                         ****\n                             by left.\n                     *** rewrite !andFb. by left.\n                   +++\n                     inversion Hrel_r1_eq. subst.\n                     rewrite eperm1 !andFb. by left.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 ---\n                   destruct (Permission.eqb perm2 Permission.data) eqn:eperm2;\n                     try discriminate;\n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid2)\n                                 (if cid2 \\in domm (prog_interface p)\n                                  then n cid2 else n'' cid2)\n                                 bid2) as [bid1_shift|] eqn:ebid2_shift;\n                     rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                 --- destruct (Permission.eqb perm1 Permission.data) eqn:eperm1;\n                       try discriminate.\n\n                     assert (perm1 = Permission.data). by apply /Permission.eqP. subst.\n                       \n                     destruct (sigma_shifting_lefttoright_option\n                                 (n cid1)\n                                 (if cid1 \\in domm (prog_interface p)\n                                  then n cid1 else n'' cid1) bid1)\n                       as [bid1_shift|] eqn:ebid1_shift;\n                       rewrite ebid1_shift in Hrel_r1_eq; try discriminate.\n                     inversion rel_r1_eq'. subst.\n                     destruct (Permission.eqb perm2 Permission.data) eqn:eperm2.\n                     +++\n                       assert (perm2 = Permission.data). by apply /Permission.eqP. subst.\n                       destruct (sigma_shifting_lefttoright_option\n                                     (n cid2)\n                                     (if cid2 \\in domm (prog_interface p)\n                                      then n cid2 else n'' cid2) bid2)\n                         as [bid2_shift|] eqn:ebid2_shift;\n                         rewrite ebid2_shift in Hrel_r2_eq; try discriminate.\n                         inversion Hrel_r2_eq. subst.\n                         rewrite andTb.\n                         destruct (cid1' =? cid2') eqn:ecid21.\n                       ***\n                         assert (cid1' = cid2'). by apply beq_nat_true. subst.\n                         rewrite andTb.\n                         destruct (bid1' =? bid2) eqn:ebid2_bid1'; auto.\n                         ----\n                           assert (bid1' = bid2). by apply beq_nat_true. subst.\n                           by rewrite ebid2_shift in ebid1_shift.\n                         ----\n                           simpl in *. rewrite ebid1_shift.\n                           destruct (bid1' =? bid2') eqn:ebid2'1'.\n                           ****\n                             assert (bid1' = bid2'). by apply beq_nat_true. subst.\n                             assert (CSInvariants.wf_ptr_wrt_cid_t\n                                       (Pointer.component pc)\n                                       t1'\n                                       (Permission.data, cid2', bid2', off2'))\n                                   as Hwf.\n                             {\n                               eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t;\n                                 last (by simpl);\n                                 last (unfold Register.get;\n                                         by erewrite eregs1'r2).\n                               eapply CSInvariants.wf_state_wf_reg\n                                 with (s := (gps1', mem1', regs1', pc)); eauto.\n                               eapply CSInvariants.is_prefix_wf_state_t;\n                                 last exact Hpref_t'.\n                               - eapply interface_preserves_closedness_r; eauto.\n                                 + by unfold mergeable_interfaces in *; intuition.\n                                 + eapply linkable_implies_linkable_mains; eauto.\n                                   by unfold mergeable_interfaces in *; intuition.\n                                 + apply interface_implies_matching_mains; auto.\n                               - eapply linking_well_formedness; eauto.\n                                 unfold mergeable_interfaces in *.\n                                 by rewrite <- Hifc_cc'; intuition.\n                             }\n                             inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                             -----\n                               assert (Pointer.component pc \\in domm\n                                                                  (prog_interface p))\n                               as G. by eapply mergeable_states_program_component_domm;\n                                       eauto.\n                               rewrite G in ebid2_shift.\n                               rewrite G in ebid1_shift.\n                               apply sigma_shifting_lefttoright_option_Some_sigma_shifting_righttoleft_option_Some in ebid2_shift.\n                             by rewrite sigma_shifting_righttoleft_lefttoright\n                                        ebid1_shift in ebid2_shift.\n                           \n                             -----\n                               inversion Hgood_t' as [? Hcontra]; subst.\n                             specialize (Hcontra _ Hshr) as contra.\n                             unfold left_addr_good_for_shifting in *.\n                             erewrite sigma_lefttoright_Some_spec in contra.\n                             destruct contra as [? G].\n                               by erewrite G in rel_r1_eq2.\n                           ****\n                             by left.\n                       *** rewrite !andFb. by left.\n                     +++\n                       inversion Hrel_r2_eq. subst.\n                       destruct (Permission.eqb Permission.data perm2') eqn:perm2contra; auto.\n                       assert (Permission.data = perm2'). by apply /Permission.eqP.\n                       by subst.\n\n                 ---\n                   inversion rel_r1_eq'. inversion rel_r2_eq'. subst. left. \n                     by destruct ((Permission.eqb perm1' perm2') &&\n                                  (cid1' =? cid2') &&\n                                  (bid1' =? bid2')).\n\n\n                     \n            ++ unfold Register.set, Register.get in *.\n               rewrite !setmE Hreg_r.\n               pose proof (Hreg reg)\n                 as [Hget_shift_reg | [HNone Heq]].\n              ** left. assumption. \n              ** right. split; eauto.\n\n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n            by rewrite H_c' in Hcomp1.\n    - (* IPtrOfLabel *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1',\n                      Register.set r (Ptr ptr) regs1',\n                      (Pointer.inc pc)\n                     )\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.PtrOfLabel.\n          -- exact Hex'.\n          -- unfold sem', prog'.\n             eapply find_label_in_component_mergeable_internal_states; auto.\n             ++ exact H_p.\n             ++ exact Hmerge1.\n             ++ reflexivity.\n             ++ eassumption.\n          -- reflexivity.\n          -- reflexivity.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem, Register.set r (Ptr ptr) regs, Pointer.inc pc)\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1', Register.set r (Ptr ptr) regs1', Pointer.inc pc)\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl. symmetry.\n             by rewrite Pointer.inc_preserves_component.\n        * by simpl.\n        * simpl. constructor. intros ?.\n          inversion Hregsp as [Hregs]. specialize (Hregs reg).\n          unfold Register.get, Register.set in *. simpl in Hregs. rewrite !setmE.\n          destruct (Register.to_nat reg == Register.to_nat r) eqn:ereg;\n            rewrite ereg; try assumption.\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n          destruct ptr as [[[perm cid] bid] ?]. simpl in *.\n          assert (perm = Permission.code).\n          {\n            unfold find_label_in_component in *.\n            destruct (genv_procedures (prepare_global_env prog)\n                                      (Pointer.component pc)); try discriminate.\n            \n            match goal with\n            | H: find_label_in_component_helper _ _ _ _ = _ |- _ =>\n              apply find_label_in_component_helper_guarantees in H as [? ?]\n            end.\n            simpl in *. subst.\n            match goal with\n            | H: executing _ pc _ |- _ =>\n              destruct H as [? [? ?]]; by intuition\n            end.\n          }\n          subst. by left.\n\n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n\n    - (* ILoad *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n\n        assert (Pointer.component pc \\in domm (prog_interface p)) as Hpc_in.\n        {\n          by eapply mergeable_states_program_component_domm; eauto.\n        }\n            \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n\n        (* ILoad-specific *)\n\n        match goal with\n        | H: Memory.load _ _ = Some _ |- _ =>\n          specialize (Memory.load_some_permission mem ptr _ H) as Hperml\n        end.\n        destruct ptr as [[[perml cidl] bidl] offl].\n        simpl in Hperml. subst.\n        \n        assert (CSInvariants.wf_ptr_wrt_cid_t\n                  (Pointer.component pc) t1\n                  (Permission.data, cidl, bidl, offl)\n               ) as cidl_bidl_invariant.\n        {\n          eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n          eapply CSInvariants.wf_state_wf_reg.\n          - eapply CSInvariants.is_prefix_wf_state_t with (p := prog); eauto.\n            eapply linking_well_formedness; auto.\n            unfold mergeable_interfaces in *.\n              by intuition.\n          - by simpl.\n          - by simpl.\n          - reflexivity.\n        }\n\n        unfold mem_of_part_executing_rel_original_and_recombined,\n        memory_shifts_memory_at_private_addr, memory_shifts_memory_at_shared_addr,\n        memory_renames_memory_at_private_addr, memory_renames_memory_at_shared_addr\n         in Hmemp.\n        simpl in Hmemp.\n        destruct Hmemp as [Hmem_own [Hmem_shared Hmem_next_block]].\n        \n        assert (\n            (cidl, bidl).1 \\in domm (prog_interface p) ->\n                               (\n                                 Memory.load mem1' (Permission.data,\n                                                    cidl, bidl, offl) =\n                                 match\n                                   rename_value_option\n                                     (rename_addr_option\n                                        (sigma_shifting_wrap_bid_in_addr\n                                           (sigma_shifting_lefttoright_addr_bid\n                                              n\n                                              (fun cid : nat =>\n                                                 if cid \\in domm (prog_interface p)\n                                                 then n cid else n'' cid)))) v\n                                 with\n                                 | Some v' => Some v'\n                                 | None => Some v\n                                 end)\n          ) as Hmem_own1.\n        {\n          intros Hcidl.\n          specialize (Hmem_own _ Hcidl) as [Hspec _].\n          \n          match goal with | H: Memory.load _ _ = _ |- _ => \n                            specialize (Hspec _ _ H)\n          end.\n          destruct (\n              rename_value_option\n                (sigma_shifting_wrap_bid_in_addr\n                   (sigma_shifting_lefttoright_addr_bid\n                      n\n                      (fun cid : nat =>\n                         if cid \\in domm (prog_interface p)\n                         then n cid else n'' cid)))\n                v\n            ) eqn:eshiftv; rewrite eshiftv; rewrite eshiftv in Hspec; auto.\n          intuition.\n        }\n        \n                \n        assert (CSInvariants.is_prefix\n                  (gps,\n                   mem,\n                   Register.set\n                     r2\n                     v\n                     regs,\n                   Pointer.inc pc\n                  )\n                  prog\n                    t1\n               ) as Hprefix_t1_E0.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n            by rewrite E0_right.\n        }\n\n\n\n        inversion Hregsp as [Hregs]. simpl in Hregs.\n        specialize (Hregs r1) as Hregsr1.\n\n        assert (exists ptr, Register.get r1 regs1' = Ptr ptr) as Hget_r1_ptr.\n        {\n          unfold shift_value_option, rename_value_option, rename_value_template_option,\n          rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n          sigma_shifting_lefttoright_addr_bid in *.\n\n          inversion Hregsr1 as [Hregs1'_r1 | [Hregs1'_r1 [Hregs1'_r1_2 Heq\n                                                                       (*[Hnotshr1 Hnotshr2]*)\n                               ]]].\n          - match goal with\n            | H: Register.get r1 regs = Ptr _ |- _ =>\n              rewrite H in Hregs1'_r1\n            end.\n            simpl in *.\n            destruct (sigma_shifting_lefttoright_option\n                        (n cidl)\n                        (if cidl \\in domm (prog_interface p)\n                         then n cidl else n'' cidl) bidl) eqn:eshift;\n              rewrite eshift in Hregs1'_r1;\n              try discriminate.\n            inversion Hregs1'_r1.\n              by eauto.\n          - setoid_rewrite <- Heq.\n            by eexists;\n              match goal with\n              | H: Register.get r1 regs = Ptr _ |- _ =>\n                erewrite H\n              end.\n        }\n\n        destruct Hget_r1_ptr as [ptr Hptr].\n\n        match goal with\n        | H: Register.get r1 regs = Ptr _ |- _ =>\n          rewrite H in Hregsr1\n        end.\n        rewrite Hptr in Hregsr1.\n\n\n        unfold shift_value_option, rename_value_option, rename_value_template_option,\n        rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n        sigma_shifting_lefttoright_addr_bid in *. simpl in *.\n        \n        assert (\n          exists v',\n            Memory.load mem1' ptr = Some v'\n          ) as [v' Hloadmem1'].\n        {\n          destruct (\n              sigma_shifting_lefttoright_option\n                (n cidl)\n                (if cidl \\in domm (prog_interface p) then n cidl else n'' cidl) bidl\n            ) as [bidl_shift|] eqn:ebidl_shift; rewrite ebidl_shift in Hregsr1. \n          - inversion Hregsr1 as [G | [? _]]; try discriminate.\n            inversion G. subst. clear G Hregsr1 Hregs.\n            inversion cidl_bidl_invariant as [| ? ? ? ?  Hshr]; subst.\n            + rewrite Hpc_in in ebidl_shift.\n              apply sigma_shifting_lefttoright_option_n_n_id in ebidl_shift.\n              rewrite Hpc_in in Hmem_own1.\n              inversion ebidl_shift. subst.\n              setoid_rewrite Hmem_own1; auto.\n              destruct v as [|[[[perm cid] bid] ?]|].\n              * eexists; eauto.\n              * destruct (Permission.eqb perm Permission.data).\n                -- destruct (sigma_shifting_lefttoright_option\n                               (n cid)\n                               (if cid \\in domm (prog_interface p)\n                                then n cid else n'' cid) bid) eqn:rewr;\n                     rewrite rewr; eexists; eauto.\n                -- eexists; eauto.\n              * eexists; eauto.\n            + specialize (Hmem_shared _ Hshr) as Hmem_shared_cid_bid.\n              setoid_rewrite ebidl_shift in Hmem_shared_cid_bid.\n              destruct Hmem_shared_cid_bid as [addr' [addr'eq [addr'load _]]].\n              inversion addr'eq. subst.\n              match goal with\n              | Hload: Memory.load mem _ = _ |- _ =>\n                specialize (addr'load _ _ Hload) as [v' [G _]]\n              end.\n              eexists. eassumption.\n          - inversion Hregsr1 as [| [contra1 [contra2 ptr_eq\n                                              (*[Hnotshrt1 Hnotshrt1']*)]]];\n              try discriminate.\n            inversion ptr_eq. subst. simpl in *.\n            clear Hregsr1 ptr_eq.\n            inversion cidl_bidl_invariant as [| ? ? ? ?  Hshr]; subst.\n            + destruct v as [| [[[perm cid] bid] off] |].\n              * eexists. erewrite Hmem_own1; auto.\n              * destruct (Permission.eqb perm Permission.data) eqn:eperm; eauto.\n                destruct (sigma_shifting_lefttoright_option\n                            (n cid)\n                            (if cid \\in domm (prog_interface p)\n                             then n cid else n'' cid) bid) eqn:esigma;\n                  eexists; erewrite Hmem_own1; auto;\n                    rewrite esigma; eauto.\n              * eexists. erewrite Hmem_own1; auto.\n            + inversion Hgood_t as [? Hcontra]; subst.\n              specialize (Hcontra _ Hshr).\n              unfold left_addr_good_for_shifting in *.\n              erewrite sigma_lefttoright_Some_spec in Hcontra.\n              destruct Hcontra as [? G].\n              by erewrite G in ebidl_shift.\n        }\n\n        \n        eexists. split.\n        * eapply CS.Step_non_inform; first eapply CS.Load.\n          -- exact Hex'.\n          -- exact Hptr.\n          -- exact Hloadmem1'. \n          -- reflexivity.\n          -- by simpl.\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ unfold CSInvariants.is_prefix in *.\n               eapply star_right; try eassumption.\n               ** eapply CS.Step_non_inform; first eapply CS.Load; eauto.\n               ** by rewrite E0_right.\n            ++ by simpl.\n            ++ by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n          -- (** regs_rel_of_executing_part *)\n            simpl. constructor. intros reg.\n            unfold Register.get, Register.set. rewrite setmE.\n            destruct (Register.to_nat reg == Register.to_nat r2) eqn:ereg;\n              rewrite ereg; rewrite setmE ereg.\n            ++ unfold shift_value_option, rename_value_option,\n               rename_value_template_option,\n               rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n               sigma_shifting_lefttoright_addr_bid in *. simpl in *.\n               destruct (\n                   sigma_shifting_lefttoright_option\n                     (n cidl)\n                     (if cidl \\in domm (prog_interface p)\n                      then n cidl else n'' cidl) bidl\n                 ) as [bidl_shift|] eqn:ebidl_shift;\n               rewrite !ebidl_shift in Hregsr1.\n               ** inversion Hregsr1 as [G | [? _]]; try discriminate.\n                  inversion G. subst. clear G Hregsr1 Hregs.\n\n                  (* Is this the right next step? *)\n                  inversion cidl_bidl_invariant as [|? ? ? ? Hshr]; subst.\n                  ---\n                    rewrite Hpc_in in ebidl_shift.\n                    apply sigma_shifting_lefttoright_option_n_n_id\n                      in ebidl_shift.\n                    subst.\n                    rewrite <- Hloadmem1'.\n                    rewrite Hmem_own1; auto.\n                    (* left. *)\n                    destruct v as [|[[[perm cid] b] o]|]; simpl; auto.\n                    destruct (Permission.eqb perm Permission.data) eqn:eperm; auto.\n                    destruct (sigma_shifting_lefttoright_option\n                                (n cid)\n                                (if cid \\in domm (prog_interface p)\n                                 then n cid else n'' cid) b) eqn:esigma;\n                      rewrite esigma; auto.\n                    assert (perm = Permission.data). by apply /Permission.eqP. subst.\n                    assert (CSInvariants.wf_load\n                              (Pointer.component pc)\n                              t1\n                              (Permission.data, Pointer.component pc, bidl, offl)\n                              (Permission.data, cid, b, o)\n                           ) as cid_b_invariant.\n                    {\n                      eapply CSInvariants.wf_mem_wrt_t_pc_wf_load; eauto.\n                      eapply CSInvariants.wf_state_wf_mem\n                        with (s := (gps, mem, regs, pc)); eauto.\n                      eapply CSInvariants.is_prefix_wf_state_t\n                        with (p := (program_link p c)); eauto.\n                      eapply linking_well_formedness; eauto.\n                      by unfold mergeable_interfaces in *; intuition.\n                    }\n\n                    inversion cid_b_invariant as [|? ? Hshr |]; simpl in *; subst; auto.\n                    +++ specialize (Hmem_own1 Hpc_in).\n                        rewrite Hloadmem1' in Hmem_own1.\n                        rewrite esigma in Hmem_own1. inversion Hmem_own1.\n                        simpl. rewrite Hpc_in in esigma. rewrite Hpc_in esigma.\n                        by right.\n                    +++ inversion Hgood_t as [? Hgood]; subst. apply Hgood in Hshr.\n                        unfold left_addr_good_for_shifting in *.\n                        eapply sigma_lefttoright_Some_spec in Hshr.\n                        destruct Hshr as [? rewr].\n                        by erewrite rewr in esigma.\n                    +++ specialize (Hmem_own1 Hpc_in).\n                        rewrite Hloadmem1' in Hmem_own1.\n                        rewrite esigma in Hmem_own1. inversion Hmem_own1.\n                        simpl. rewrite Hpc_in in esigma. rewrite Hpc_in esigma.\n                        by right.\n\n                  ---\n                    destruct (Hmem_shared (cidl, bidl) Hshr)\n                      as [? [Hcidlbidl [Hmem_shared1 _]]].\n                    rewrite ebidl_shift in Hcidlbidl. inversion Hcidlbidl. subst.\n                    simpl in *.\n                    match goal with\n                    | Hload: Memory.load mem _ = _ |- _ =>\n                      specialize (Hmem_shared1 _ _ Hload) as [v'exists [v'eq G]]\n                    end.\n                    rewrite Hloadmem1' in v'eq.\n                    inversion v'eq. subst. left. exact G.\n\n               **                     \n                 inversion cidl_bidl_invariant as [|? ? ? ? Hshr]; subst.\n                 ---\n                   destruct Hregsr1 as [| [none1 [none2 eptr\n                                                        (*[Hnotshr Hnotshr']*)\n                                       ]]];\n                     try discriminate.\n                   inversion eptr. subst. clear eptr.\n                   rewrite Hloadmem1' in Hmem_own1.\n                   specialize (Hmem_own1 Hpc_in).\n                   rewrite Hmem_own1.\n                   destruct v as [| [[[perm cid] bid] off]  |]; auto.\n                   destruct (Permission.eqb perm Permission.data) eqn:eperm; auto.\n                   destruct (sigma_shifting_lefttoright_option\n                               (n cid)\n                               (if cid \\in domm (prog_interface p)\n                                then n cid else n'' cid) bid) eqn:esigma;\n                     rewrite esigma; rewrite esigma in Hmem_own1; auto.\n                   inversion Hmem_own1.\n                   right; split; auto; split; auto.\n                   simpl in *. rewrite eperm.\n                   specialize (Hmem_own (_, bidl) Hpc_in) as [_ Hmem_own2].\n                   specialize (Hmem_own2 _ _ Hloadmem1') as [? [Hload Hrel]].\n                   simpl in *.\n                   match goal with\n                   | Hl: Memory.load mem _ = Some (Ptr _) |- _ =>\n                     rewrite Hload in Hl; inversion Hl; subst\n                   end.\n                   rewrite eperm esigma in Hrel.\n                   destruct (sigma_shifting_lefttoright_option\n                               (if cid \\in domm (prog_interface p)\n                                then n cid else n'' cid)\n                               (n cid)\n                               bid\n                            ) eqn:ebid; rewrite ebid; rewrite ebid in Hrel;\n                     destruct Hrel as [[? [? ?]]|]; try discriminate; auto.\n                   \n                   \n                 --- (*specialize (addr_shared_so_far_good_addr _ _ Hgood_t _ Hshr)\n                       as cidbgood.*)\n                   inversion Hgood_t as [? shared_good]. subst.\n                   specialize (shared_good _ Hshr) as cidbgood.\n                   \n                   unfold left_addr_good_for_shifting in *.\n                   erewrite sigma_lefttoright_Some_spec in cidbgood.\n                   destruct cidbgood as [? contra].\n                   by erewrite contra in ebidl_shift.\n                     \n            ++ by apply Hregs.\n\n          -- (* mem_of_part_executing_rel_original_and_recombined *)\n            by unfold mem_of_part_executing_rel_original_and_recombined; intuition.\n            \n      + simpl in *. subst.\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb, ic in Hcomp1.\n          rewrite Hpccomp_s'_s in H_c'.\n            by rewrite H_c' in Hcomp1.\n\n    - (* IStore *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n\n        assert (Pointer.component pc \\in domm (prog_interface p)) as Hpc_in.\n        {\n          by eapply mergeable_states_program_component_domm; eauto.\n        }\n            \n\n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n\n        (* IStore-specific *)\n\n        unfold mem_of_part_executing_rel_original_and_recombined,\n        memory_shifts_memory_at_private_addr, memory_shifts_memory_at_shared_addr,\n        memory_renames_memory_at_private_addr, memory_renames_memory_at_shared_addr\n         in Hmemp.\n        simpl in Hmemp.\n        destruct Hmemp as [Hmem_own [Hmem_shared Hmem_next_block]].\n        \n\n\n        assert (CSInvariants.is_prefix\n                  (gps,\n                   mem',\n                   regs,\n                   Pointer.inc pc\n                  )\n                  prog\n                    t1\n               ) as Hprefix_t1_E0.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n            by rewrite E0_right.\n        }\n\n\n\n        match goal with\n        | H: Memory.store _ _ _ = Some _ |- _ =>\n          specialize (Memory.store_some_permission mem ptr _ _ H) as Hperm_st\n        end.\n        destruct ptr as [[[perm_st cid_st] bid_st] off_st].\n        simpl in Hperm_st. subst.\n\n\n        inversion Hregsp as [Hregs]. simpl in Hregs.\n        specialize (Hregs r1) as Hregs1'r1.\n        match goal with\n        | H: Register.get r1 regs = Ptr _ |- _ =>\n          rewrite H in Hregs1'r1\n        end.\n        \n\n        assert (exists ptr, Register.get r1 regs1' = Ptr ptr) as Hget_r1_ptr.\n        {\n          unfold shift_value_option, rename_value_option, rename_value_template_option,\n          rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n          sigma_shifting_lefttoright_addr_bid in *.\n\n          \n          inversion Hregs1'r1 as [Hregs1'_r1 | [Hregs1'_r1 [Hregs1'_r1_2 Heq\n                                                                         (*[Hnotshr1 Hnotshr2]*)\n                                 ]]].\n          - simpl in *.\n            destruct (sigma_shifting_lefttoright_option\n                        (n cid_st)\n                        (if cid_st \\in domm (prog_interface p)\n                         then n cid_st else n'' cid_st) bid_st) eqn:eshift;\n              rewrite eshift in Hregs1'_r1;\n              try discriminate.\n            inversion Hregs1'_r1.\n              by eauto.\n          - setoid_rewrite <- Heq.\n            by eexists.\n        }\n\n        destruct Hget_r1_ptr as [ptr Hptr].\n\n\n        \n        \n        assert (CSInvariants.wf_ptr_wrt_cid_t\n                  (Pointer.component pc) t1\n                  (Permission.data, cid_st, bid_st, off_st)\n               ) as cidst_bidst_invariant.\n        {\n          eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n          eapply CSInvariants.wf_state_wf_reg.\n          - eapply CSInvariants.is_prefix_wf_state_t with (p := prog); eauto.\n            eapply linking_well_formedness; auto.\n            unfold mergeable_interfaces in *.\n              by intuition.\n          - by simpl.\n          - by simpl.\n          - by apply Pointer.inc_preserves_component.\n        }\n\n\n        assert (forall cidv bidv offv,\n                   Register.get r2 regs = Ptr (Permission.data, cidv, bidv, offv) ->\n                   CSInvariants.wf_ptr_wrt_cid_t\n                     (Pointer.component pc) t1\n                     (Permission.data, cidv, bidv, offv)\n               ) as get_r2_invariant.\n        {\n          intros ? ? ? Hget.\n          eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n          eapply CSInvariants.wf_state_wf_reg.\n          - eapply CSInvariants.is_prefix_wf_state_t with (p := prog); eauto.\n            eapply linking_well_formedness; auto.\n            unfold mergeable_interfaces in *.\n              by intuition.\n          - by simpl.\n          - by simpl.\n          - by apply Pointer.inc_preserves_component.\n        }\n\n\n        assert (forall cidv bidv offv,\n                   Register.get r2 regs1' = Ptr (Permission.data, cidv, bidv, offv) ->\n                   CSInvariants.wf_ptr_wrt_cid_t\n                     (Pointer.component pc) t1'\n                     (Permission.data, cidv, bidv, offv)\n               ) as get_r2_invariant'.\n        {\n          intros ? ? ? Hget.\n          eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n          eapply CSInvariants.wf_state_wf_reg.\n          - eapply CSInvariants.is_prefix_wf_state_t with (p := prog'); eauto.\n            + eapply interface_preserves_closedness_r; eauto.\n              * by unfold mergeable_interfaces in *; intuition.\n              * eapply linkable_implies_linkable_mains; eauto.\n                by unfold mergeable_interfaces in *; intuition.\n              * eapply interface_implies_matching_mains; eauto.\n            + eapply linking_well_formedness; auto.\n              rewrite <- Hifc_cc'. unfold mergeable_interfaces in *.\n              by intuition.\n          - by simpl.\n          - by simpl.\n          - reflexivity.\n        }\n\n        \n        assert (exists v,\n                   Memory.load mem (Permission.data, cid_st, bid_st, off_st) =\n                   Some v) as [vload Hload].\n        {\n          eapply Memory.store_some_load_some.\n          eexists. eassumption.\n        }\n\n        (*assert (good_memory\n                  (left_addr_good_for_shifting n)\n                  (CS.state_mem (gps, mem', regs, Pointer.inc pc)))\n          as Hgood_after_store.\n        {\n          eapply Hgood_prog; eassumption.\n        }*)\n\n        \n        \n        assert (\n          exists mem2',\n            Memory.store mem1' ptr (Register.get r2 regs1') = Some mem2'\n          ) as [mem2' Hstoremem1'].\n        {\n          rewrite <- Memory.store_some_load_some.\n\n\n\n          (* Consider refactoring the unfold and the assert out of \n             the enclosing assertion proof *)\n          unfold mem_of_part_executing_rel_original_and_recombined,\n          shift_value_option, rename_value_option,\n          rename_value_template_option,\n          rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n          sigma_shifting_lefttoright_addr_bid in *. simpl in *.\n          \n          assert (\n              (cid_st, bid_st).1 \\in domm (prog_interface p) ->\n                                     (\n                                       Memory.load mem1' (Permission.data,\n                                                          cid_st, bid_st, off_st) =\n                                       match\n                                         rename_value_option\n                                           (rename_addr_option\n                                              (sigma_shifting_wrap_bid_in_addr\n                                                 (sigma_shifting_lefttoright_addr_bid\n                                                    n\n                                                    (fun cid : nat =>\n                                                       if cid \\in domm (prog_interface p)\n                                                       then n cid else n'' cid)))) vload\n                                       with\n                                       | Some v' => Some v'\n                                       | None => Some vload\n                                       end)\n            ) as Hmem_own1.\n          {\n            intros Hcidl.\n            specialize (Hmem_own _ Hcidl) as [Hspec _].\n            \n            match goal with | H: Memory.load _ _ = _ |- _ => \n                              specialize (Hspec _ _ H)\n            end.\n            destruct (\n                rename_value_option\n                  (rename_addr_option\n                     (sigma_shifting_wrap_bid_in_addr\n                        (sigma_shifting_lefttoright_addr_bid\n                           n\n                           (fun cid : nat =>\n                              if cid \\in domm (prog_interface p)\n                              then n cid else n'' cid))))\n                  vload\n              ) eqn:evload;\n              unfold\n                rename_value_option,\n              rename_value_template_option,\n              rename_addr_option, sigma_shifting_wrap_bid_in_addr,\n              sigma_shifting_lefttoright_addr_bid in *; simpl in *;\n                rewrite evload in Hspec; auto.\n            intuition.\n          }\n\n\n          \n          destruct (\n              sigma_shifting_lefttoright_option\n                (n cid_st)\n                (if cid_st \\in domm (prog_interface p)\n                 then n cid_st else n'' cid_st) bid_st\n            ) as [bidst_shift|] eqn:ebidst_shift; rewrite ebidst_shift in Hregs1'r1. \n          - inversion Hregs1'r1 as [G | [? _]]; try discriminate.\n            rewrite Hptr in G. inversion G. subst. clear G Hregs1'r1 Hregs.\n            inversion cidst_bidst_invariant as [| ? ? ? ?  Hshr]; subst.\n            + rewrite Hpc_in in ebidst_shift.\n              apply sigma_shifting_lefttoright_option_n_n_id in ebidst_shift.\n              subst.\n              rewrite Hpc_in in Hmem_own1.\n              setoid_rewrite Hmem_own1; auto.\n              by destruct (\n                     rename_value_option\n                       (rename_addr_option\n                          (sigma_shifting_wrap_bid_in_addr\n                             (sigma_shifting_lefttoright_addr_bid\n                                n\n                                (fun cid : nat =>\n                                   if cid \\in domm (prog_interface p)\n                                   then n cid else n'' cid))))\n                       vload); eexists; auto.\n            + specialize (Hmem_shared _ Hshr) as Hmem_shared_cid_bid.\n              setoid_rewrite ebidst_shift in Hmem_shared_cid_bid.\n              destruct Hmem_shared_cid_bid as [addr' [addr'eq [addr'load _]]].\n              inversion addr'eq. subst.\n              match goal with\n              | Hload: Memory.load mem _ = _ |- _ =>\n                specialize (addr'load _ _ Hload) as [v' [G _]]\n              end.\n              eexists. eassumption.\n          - inversion Hregs1'r1 as [| [? [? ptr_eq\n                                            (*[Hnotshrt1 Hnotshrt1']*)\n                                   ]]];\n              try discriminate.\n            rewrite Hptr in ptr_eq.\n            inversion ptr_eq. subst. simpl in *.\n            clear Hregs1'r1 ptr_eq.\n            inversion cidst_bidst_invariant as [| ? ? ? ?  Hshr]; subst.\n            + rewrite Hmem_own1; auto.\n              by destruct (\n                     rename_value_option\n                       (rename_addr_option\n                          (sigma_shifting_wrap_bid_in_addr\n                             (sigma_shifting_lefttoright_addr_bid\n                                n\n                                (fun cid : nat =>\n                                   if cid \\in domm (prog_interface p)\n                                   then n cid else n'' cid))))\n                       vload) eqn:e; rewrite e; eexists; auto.\n            + inversion Hgood_t as [? Hcontra]; subst.\n              specialize (Hcontra _ Hshr).\n              unfold left_addr_good_for_shifting in *.\n              erewrite sigma_lefttoright_Some_spec in Hcontra.\n              destruct Hcontra as [? contra].\n                by erewrite contra in ebidst_shift.\n        }\n\n        assert (\n          Step (CS.sem_non_inform (program_link p c'))\n               (gps1', mem1', regs1', pc) \n               E0\n               (gps1', mem2', regs1', Pointer.inc pc)\n        ) as Hstep.\n        {\n          eapply CS.Step_non_inform; first eapply CS.Store.\n          -- exact Hex'.\n          -- exact Hptr.\n          -- exact Hstoremem1'. \n          -- reflexivity.\n        }\n        \n        assert (\n          CSInvariants.is_prefix\n            (gps1',\n             mem2',\n             regs1',\n             Pointer.inc pc\n            )\n            (program_link p c')\n            t1'\n        ) as Hprefix_t1'_E0.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n            by rewrite E0_right.\n        }\n\n        (* TODO: Refactor out *)\n        Ltac find_if_inside_hyp H :=\n          let e := fresh \"e\" in\n          let t := type of H in\n          match t with\n          |  context [if ?X then _ else _] => destruct X eqn:e\n          end.\n        Ltac find_if_inside_goal :=\n          let e := fresh \"e\" in\n          match goal with\n          | [ |- context[if ?X then _ else _] ] => destruct X eqn:e\n          end.\n\n        assert (Pointer.permission ptr = Permission.data) as Hptrperm.\n        {\n          simpl in *.\n          unfold rename_addr_option,\n          sigma_shifting_wrap_bid_in_addr,\n          sigma_shifting_lefttoright_addr_bid in *.\n          rewrite Hptr in Hregs1'r1.\n          inversion Hregs1'r1 as [Hregs1'r1a | Hregs1'r1a]; simpl in *;\n            destruct (sigma_shifting_lefttoright_option\n                        (n cid_st)\n                        (if cid_st \\in domm (prog_interface p)\n                         then n cid_st else n'' cid_st) bid_st) as [?|] eqn:esigma;\n            rewrite esigma in Hregs1'r1a; try discriminate.\n          - by inversion Hregs1'r1a.\n          - exfalso. by destruct Hregs1'r1a.\n          - destruct Hregs1'r1a as [_ [_ G]]. by inversion G.\n        }\n\n        assert (Pointer.component ptr = cid_st) as Hptrcomp.\n        {\n          simpl in *.\n          unfold rename_addr_option,\n          sigma_shifting_wrap_bid_in_addr,\n          sigma_shifting_lefttoright_addr_bid in *.\n          rewrite Hptr in Hregs1'r1.\n          inversion Hregs1'r1 as [Hregs1'r1a | Hregs1'r1a]; simpl in *;\n            destruct (sigma_shifting_lefttoright_option\n                        (n cid_st)\n                        (if cid_st \\in domm (prog_interface p)\n                         then n cid_st else n'' cid_st) bid_st) as [?|] eqn:esigma;\n            rewrite esigma in Hregs1'r1a; try discriminate.\n          - by inversion Hregs1'r1a.\n          - exfalso. by destruct Hregs1'r1a.\n          - destruct Hregs1'r1a as [_ [_ G]]. by inversion G.\n        }\n\n        rewrite Hptr in Hregs1'r1.\n\n        assert (\n            mem_of_part_executing_rel_original_and_recombined\n              p\n              mem'\n              mem2'\n              n\n              (fun cid : nat_ordType =>\n                 if cid \\in domm (prog_interface p) then n cid else n'' cid) t1\n          ) as Hmem'mem2'.\n        {\n          split; last split.\n          - unfold shift_value_option, memory_shifts_memory_at_private_addr,\n            memory_renames_memory_at_private_addr,\n            rename_value_option, rename_value_template_option,\n            rename_addr_option,\n            sigma_shifting_wrap_bid_in_addr,\n            sigma_shifting_lefttoright_addr_bid in *.\n            simpl in *.\n            intros ? Horiginal. split.\n            + intros ? ? Hloadmem'.\n              erewrite Memory.load_after_store in Hloadmem'; eauto.\n              erewrite Memory.load_after_store; eauto.\n              find_if_inside_hyp Hloadmem'.\n              * inversion Hloadmem'. subst.\n                assert ((Permission.data, original_addr.1, original_addr.2, offset) =\n                        (Permission.data, Pointer.component ptr, bid_st, off_st))\n                  as Heq.\n                  by apply/Pointer.eqP.\n                  inversion Heq as [[Hcid Hbid]]. subst.\n                  rewrite Hcid in Horiginal.\n                  rewrite Horiginal\n                    in Hregs1'r1.\n                  destruct Hregs1'r1 as [G| [G1 [G2 G3]]].\n                --\n                  destruct (sigma_shifting_lefttoright_option\n                              (n (Pointer.component ptr))\n                              (n (Pointer.component ptr))\n                              original_addr.2\n                           ) eqn:eoriginal; try discriminate.\n                  apply sigma_shifting_lefttoright_option_n_n_id in eoriginal.\n                  inversion G. subst. rewrite Hcid. simpl.\n                  rewrite <- !beq_nat_refl, Z.eqb_refl. simpl.\n                  specialize (Hregs r2) as Hgetr2.\n                  destruct Hgetr2 as [G'|G']; try by rewrite G'.\n                  destruct (Register.get r2 regs) as [|[[[perm cid] b] o]|] eqn:eget;\n                    destruct G' as [contra [G'' ?]]; try discriminate.\n                  destruct (Permission.eqb perm Permission.data) eqn:eperm; try discriminate.\n                  destruct (sigma_shifting_lefttoright_option\n                              (n cid)\n                              (if cid \\in domm (prog_interface p)\n                               then n cid else n'' cid) b) eqn:esigma;\n                    rewrite esigma in contra; try discriminate.\n                  match goal with\n                  | H: Ptr _ = Register.get r2 regs1' |- _ =>\n                    rewrite <- H, eperm in G'';\n                      rewrite esigma G'' H\n                  end.\n                    by auto.\n                -- destruct (sigma_shifting_lefttoright_option\n                               (n (Pointer.component ptr))\n                               (n (Pointer.component ptr))\n                               original_addr.2\n                            ) eqn:eoriginal; try discriminate.\n                   destruct ptr as [[[pptr cptr] bptr] optr].\n                   inversion G3. subst. inversion Heq. subst.\n                   simpl in G2. clear G1 G3. simpl in *.\n                   rewrite !Z.eqb_refl -!beq_nat_refl. simpl.\n                   specialize (Hregs r2) as Hgetr2.\n                   destruct Hgetr2 as [G'|G']; try by rewrite G'.\n                   destruct G' as [G'' [Hrewr1 Hrewr2]].\n                   rewrite Hrewr2 Hrewr1.\n                   rewrite Hrewr2 in G''.\n                   by rewrite G''.\n              * subst.\n                find_if_inside_goal.\n                --\n                  assert (ptr =\n                          (Permission.data, original_addr.1, original_addr.2, offset)).\n                  {\n                    symmetry. by apply/Pointer.eqP.\n                  }\n                  subst. simpl in *.\n                  rewrite Horiginal\n                    in Hregs1'r1.\n                  destruct Hregs1'r1 as [G | [G1 [G2 G3]]]; try discriminate.\n                  ++\n                    destruct (\n                      sigma_shifting_lefttoright_option\n                        (n original_addr.1)\n                        (n original_addr.1) bid_st\n                    ) eqn:ebidst; try discriminate.\n                    apply sigma_shifting_lefttoright_option_n_n_id in ebidst.\n                    inversion G. subst. simpl in e.\n                    rewrite -!beq_nat_refl Z.eqb_refl in e. by simpl in e.\n                  ++\n                    inversion G3. subst.\n                    rewrite -!beq_nat_refl Z.eqb_refl in e. by simpl in e.\n     \n                --\n                  specialize (Hmem_own _ Horiginal) as [G _].\n                    by eapply G; eauto.\n            + intros ? ? Hloadmem2'.\n              erewrite Memory.load_after_store in Hloadmem2'; eauto.\n              erewrite Memory.load_after_store; eauto.\n              find_if_inside_hyp Hloadmem2'.\n              * inversion Hloadmem2'. subst.\n                assert ((Permission.data, original_addr.1, original_addr.2, offset) =\n                        ptr)\n                  as Heq.\n                  by apply/Pointer.eqP.\n                  subst.\n                  simpl in *.\n                  rewrite Horiginal\n                    in Hregs1'r1.\n                  destruct (Hregs1'r1) as [Hrewr | [G1 [G2 G3]]];\n                    try discriminate.\n                --\n                  inversion Hrewr. subst. clear Hregs1'r1 Hrewr.\n                  destruct (\n                      sigma_shifting_lefttoright_option\n                        (n original_addr.1)\n                        (n original_addr.1) bid_st\n                    ) eqn:ebidst; try discriminate.\n                  apply sigma_shifting_lefttoright_option_n_n_id in ebidst.\n                  match goal with | H: Some _ = Some _ |- _ =>\n                                    inversion H; subst\n                  end.\n                  rewrite -!beq_nat_refl Z.eqb_refl. simpl.\n                  eexists; split; eauto.\n                  specialize (Hregs r2) as Hgetr2.\n                  destruct Hgetr2 as [G'|G']; try by right.\n                  left. by intuition.\n                --\n                  inversion G3. subst.\n                  rewrite -!beq_nat_refl Z.eqb_refl. simpl.\n                  eexists; split; eauto.\n                  specialize (Hregs r2) as Hgetr2.\n                  destruct Hgetr2 as [G'|G']; try by right.\n                  left. by intuition.\n              * subst. find_if_inside_goal.\n                --\n                  assert ((Permission.data, original_addr.1, original_addr.2, offset) =\n                          (Permission.data, Pointer.component ptr, bid_st, off_st))\n                    as contra.\n                  by apply/Pointer.eqP.\n                  destruct original_addr as [origc origb].\n                  inversion contra as [[Hcid Hbid]]. subst.\n                  simpl in *.\n                  rewrite Horiginal in Hregs1'r1.\n                  destruct Hregs1'r1 as [G | [G1 [G2 G3]]]; try discriminate.\n                  ++\n                    destruct (\n                        sigma_shifting_lefttoright_option\n                          (n (Pointer.component ptr))\n                          (n (Pointer.component ptr)) bid_st\n                      ) eqn:ebid_st; try discriminate.\n                    apply sigma_shifting_lefttoright_option_n_n_id in ebid_st.\n                    inversion G as [G']. subst.\n                      by rewrite <- G', <- !beq_nat_refl, Z.eqb_refl in e; simpl.\n                  ++\n                    inversion G3 as [G'].\n                    by rewrite <- G', <- !beq_nat_refl, Z.eqb_refl in e; simpl.\n                --\n                  specialize (Hmem_own _ Horiginal) as [_ G].\n                    by eapply G; eauto.\n          - unfold shift_value_option, memory_shifts_memory_at_shared_addr,\n            memory_renames_memory_at_shared_addr,\n            rename_value_option, rename_value_template_option,\n            rename_addr_option,\n            sigma_shifting_wrap_bid_in_addr,\n            sigma_shifting_lefttoright_addr_bid in *.\n            simpl in *.\n            intros ? Horiginal.\n            (*specialize (addr_shared_so_far_good_addr _ _ Hgood_t _ Horiginal)\n                as Hgood.*)\n            inversion Hgood_t as [? shared_good]. subst.\n            specialize (shared_good _ Horiginal) as Hgood.\n\n\n            unfold left_addr_good_for_shifting in *.\n            destruct original_addr as [cid_orig bid_orig].\n            erewrite sigma_lefttoright_Some_spec in Hgood.\n            destruct Hgood as [rbid Hrbid].\n            setoid_rewrite Hrbid.\n            eexists. split; auto; split; simpl in *; intros ? ?.\n            + intros Hloadmem'.\n              specialize (Hgood_prog _ _ Hprefix_t1_E0) as [_ Hgoodv].\n              assert (goodv : left_value_good_for_shifting n v).\n              {\n                eapply Hgoodv; eauto. simpl.\n                specialize (shared_good _ Horiginal).\n                by simpl in *.\n              }\n              unfold left_value_good_for_shifting, left_addr_good_for_shifting\n                in goodv.\n              \n              erewrite Memory.load_after_store in Hloadmem'; eauto.\n              erewrite Memory.load_after_store; eauto.\n              find_if_inside_hyp Hloadmem'.\n              * inversion Hloadmem'. subst. clear Hloadmem'.\n                assert ((Permission.data, cid_orig, bid_orig, offset) =\n                        (Permission.data, Pointer.component ptr, bid_st, off_st))\n                  as Heq.\n                  by apply/Pointer.eqP. \n                  inversion Heq. subst. clear Heq e.\n                  rewrite Hrbid in Hregs1'r1.\n                  destruct Hregs1'r1 as [Heq | [? _]]; try discriminate.\n                  inversion Heq. simpl in *.\n                  rewrite -!beq_nat_refl Z.eqb_refl; simpl.\n                  eexists. split; eauto.\n                  specialize (Hregs r2) as Hgetr2.\n                  destruct Hgetr2 as [G'|G']; auto.\n                  destruct (Register.get r2 regs)\n                    as [|[[[perm cid] b] o]|] eqn:eget;\n                    destruct G' as [contra [G''' G''\n                                                 (*[Hnotshr Hnotshr']*)\n                                   ]]; try discriminate.\n                  destruct (Permission.eqb perm Permission.data) eqn:eperm; try discriminate.\n                  assert (perm = Permission.data). by apply /Permission.eqP. subst.\n                  destruct (sigma_shifting_lefttoright_option\n                              (n cid)\n                              (if cid \\in domm (prog_interface p)\n                               then n cid else n'' cid) b) eqn:esigma;\n                    rewrite esigma in contra; try discriminate.\n                  erewrite sigma_lefttoright_Some_spec in goodv.\n                  destruct goodv as [? G].\n                  by erewrite G in esigma.\n\n              * subst.\n                find_if_inside_goal.\n                --\n                  assert ((Permission.data, cid_orig, rbid, offset) =\n                          ptr)\n                    as Heq.\n                    by apply/Pointer.eqP. \n                    subst.\n                    simpl in *.\n                    destruct (\n                        sigma_shifting_lefttoright_option\n                          (n cid_orig)\n                          (if cid_orig \\in domm (prog_interface p)\n                           then n cid_orig else n'' cid_orig)\n                          bid_st\n                      ) eqn:esigma; rewrite esigma in Hregs1'r1.\n                  ++\n                    destruct Hregs1'r1 as [contra | [? _]]; try discriminate.\n                    inversion contra. subst.\n                    assert (bid_orig = bid_st).\n                    by eapply sigma_shifting_lefttoright_option_Some_inj; eauto.\n                    subst.\n                    by rewrite -!beq_nat_refl Z.eqb_refl in e.\n                  ++\n                    destruct Hregs1'r1 as [contra | [? [contra ? (*[? contra]*)\n                                          ]]];\n                      try discriminate.\n                    apply sigma_shifting_lefttoright_Some_inv_Some in Hrbid.\n                    by rewrite Hrbid in contra.\n                --\n                  specialize (Hmem_shared _ Horiginal) as [? [esigma [G _]]].\n                  rewrite Hrbid in esigma. inversion esigma. subst.\n                  simpl in *. by eapply G; eauto.\n            + intros Hloadmem2'.\n              specialize (Hgood_prog _ _ Hprefix_t1_E0) as [_ Hgoodv].\n              specialize (Hgoodv\n                            mem'\n                            (Permission.data, cid_orig, bid_orig, offset)\n                            (cid_orig, bid_orig)\n                         ).\n              simpl in Hgoodv.\n              unfold left_value_good_for_shifting, left_addr_good_for_shifting\n                in Hgoodv.\n              \n              erewrite Memory.load_after_store in Hloadmem2'; eauto.\n              erewrite Memory.load_after_store in Hgoodv; eauto.\n              erewrite Memory.load_after_store; eauto.\n              find_if_inside_hyp Hloadmem2'.\n              * inversion Hloadmem2'. subst. clear Hloadmem2'.\n                assert ((Permission.data, cid_orig, rbid, offset) = ptr)\n                  as Heq.\n                  by apply/Pointer.eqP.\n                  subst. simpl in *.\n                  find_if_inside_goal.\n                --\n                  assert ((Permission.data, cid_orig, bid_orig, offset) =\n                          (Permission.data, cid_orig, bid_st, off_st)) as Heq.\n                    by apply/Pointer.eqP.\n                  inversion Heq. subst. clear Heq e0.\n                  eexists; split; eauto.\n                  specialize (Hregs r2) as Hgetr2.\n                  destruct Hgetr2 as [G'|G']; auto.\n                  destruct (Register.get r2 regs)\n                    as [|[[[perm cid] b] o]|] eqn:eget;\n                    destruct G' as [contra [? G'' (*[Hnotshr Hnotshr']*)]];\n                    try discriminate.\n                  destruct (Permission.eqb perm Permission.data) eqn:eperm; try discriminate.\n                  assert (perm = Permission.data). by apply /Permission.eqP. subst.\n                  destruct (sigma_shifting_lefttoright_option\n                              (n cid)\n                              (if cid \\in domm (prog_interface p)\n                               then n cid else n'' cid) b) eqn:esigma;\n                    rewrite esigma in contra; try discriminate.\n                  assert (left_block_id_good_for_shifting (n cid) b) as G.\n                  {\n                    specialize (Hgoodv (Ptr (Permission.data, cid, b, o))).\n                    eapply Hgoodv; eauto.\n                    by erewrite sigma_lefttoright_Some_spec; eauto.\n                  }\n                  erewrite sigma_lefttoright_Some_spec in G.\n                  destruct G as [? Gcontra].\n                  by erewrite Gcontra in esigma.\n\n                --\n                  destruct (\n                      sigma_shifting_lefttoright_option\n                        (n cid_orig)\n                        (if cid_orig \\in domm (prog_interface p)\n                         then n cid_orig else n'' cid_orig)\n                        bid_st\n                    ) eqn:esigma; rewrite esigma in Hregs1'r1.\n                  ++\n                    destruct Hregs1'r1 as [Hrewr|[? _]]; try discriminate.\n                    inversion Hrewr. subst. clear Hrewr.\n                    assert (bid_orig = bid_st).\n                      by eapply sigma_shifting_lefttoright_option_Some_inj; eauto.\n                    subst. by rewrite -!beq_nat_refl Z.eqb_refl in e0.\n                  ++\n                    destruct Hregs1'r1 as [?|[_ [contra Hinv (*[? Hcontra]*)\n                                          ]]]; try discriminate.\n                    inversion Hinv. subst.\n                    apply sigma_shifting_lefttoright_Some_inv_Some in Hrbid.\n                    by rewrite Hrbid in contra.\n\n              * find_if_inside_goal.\n                --\n                  assert ((Permission.data, cid_orig, bid_orig, offset) =\n                        (Permission.data, Pointer.component ptr, bid_st, off_st))\n                  as Heq.\n                  by apply/Pointer.eqP.\n                  inversion Heq. subst. clear Heq e0.\n                  rewrite Hrbid in Hregs1'r1.\n                  destruct Hregs1'r1 as [Hrewr|[? _]]; try discriminate.\n                  inversion Hrewr as [Hsubst].\n                  rewrite <- Hsubst in e. simpl in e.\n                  by rewrite -!beq_nat_refl Z.eqb_refl in e.\n                --\n                  specialize (Hmem_shared _ Horiginal) as [? [esigma [_ G]]].\n                  rewrite Hrbid in esigma. inversion esigma. subst.\n                  simpl in *. by eapply G; eauto.\n\n                    \n          - unfold Memory.store in *. simpl in *.\n            destruct (mem cid_st) as [memC|] eqn:ememC; try discriminate.\n            destruct (ComponentMemory.store memC bid_st off_st (Register.get r2 regs))\n              as [memC'|] eqn:ememC'; try discriminate.\n            match goal with | H: Some _ = Some _ |- _ => inversion H end. subst.\n            find_if_inside_hyp Hstoremem1'; try discriminate.\n            destruct (mem1' (Pointer.component ptr)) as [mem1'ptr|] eqn:emem1'ptr;\n              try discriminate.\n            destruct (ComponentMemory.store\n                        mem1'ptr\n                        (Pointer.block ptr) \n                        (Pointer.offset ptr)\n                        (Register.get r2 regs1')) as [mem1'ptrComp|]\n            eqn:compMemStore; try discriminate.\n            inversion Hstoremem1'. subst.\n            intros cid Hcid. rewrite !setmE.\n            destruct (cid == Pointer.component ptr) eqn:ecid; rewrite ecid.\n            + specialize (Hmem_next_block cid Hcid).\n              unfold omap, obind, oapp in *.\n              erewrite <- ComponentMemory.next_block_store_stable; last exact ememC'.\n              symmetry.\n              erewrite <- ComponentMemory.next_block_store_stable;\n                last exact compMemStore.\n              symmetry.\n              assert (cid = Pointer.component ptr). by apply/eqP. subst.\n              by rewrite ememC emem1'ptr in Hmem_next_block.\n            + by specialize (Hmem_next_block cid Hcid). \n        }\n\n\n        assert (\n          mem_of_part_not_executing_rel_original_and_recombined_at_internal\n            c'\n            (CS.state_mem s1'')\n            mem2'\n            n''\n            (fun cid : nat_ordType =>\n               if cid \\in domm (prog_interface p) then n cid else n'' cid)\n            t1''\n        ).\n        {\n          unfold\n            mem_of_part_not_executing_rel_original_and_recombined_at_internal,\n          memory_shifts_memory_at_private_addr,\n          memory_renames_memory_at_private_addr in *.\n          destruct Hmemc' as [Hprivrel Halloc].\n          split.\n          - intros ? Horiginal Hnotshr.\n\n            assert (original_addr.1 \\in domm (prog_interface p) -> False)\n              as Horiginal_not_p.\n            {\n              intros contra.\n              rewrite <- Hifc_cc' in Horiginal.\n              destruct Hmerge_ipic as [[_ Hcontra] _].\n                by specialize (fdisjoint_partition_notinboth\n                                 Hcontra Horiginal contra).\n            }\n            \n            split; intros ? ? Hload_c'.\n            + erewrite Memory.load_after_store; last exact Hstoremem1'.\n              find_if_inside_goal.\n              * assert ((Permission.data, original_addr.1,\n                         original_addr.2, offset) = ptr).\n                by apply/Pointer.eqP.\n                subst.\n                assert (CSInvariants.wf_ptr_wrt_cid_t\n                          (Pointer.component pc)\n                          t1'\n                          (Permission.data,\n                           original_addr.1,\n                           original_addr.2, offset)) as Hwf.\n                {\n                  eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n                  eapply CSInvariants.wf_state_wf_reg\n                      with (s := (gps1', mem1', regs1', pc)); eauto.\n                  eapply CSInvariants.is_prefix_wf_state_t\n                    with (p := (program_link p c')); eauto.\n                  - eapply interface_preserves_closedness_r; eauto.\n                    + by unfold mergeable_interfaces in *; intuition.\n                    + eapply linkable_implies_linkable_mains; eauto.\n                        by unfold mergeable_interfaces in *; intuition.\n                    + apply interface_implies_matching_mains; auto.\n                  - eapply linking_well_formedness; try assumption.\n                    rewrite <- Hifc_cc'.\n                    by unfold mergeable_interfaces in *;\n                      intuition.\n                }\n                \n\n                inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                ++\n                  match goal with\n                  | Hrewr: Pointer.component pc = _ |- _ =>\n                    rewrite Hrewr in Hpc_in\n                  end.\n                  by intuition. (* contradiction *)\n                ++\n                  inversion Hshift_t''t' as [? ? t''t'ren]. subst.\n                  inversion t''t'ren\n                    as [|? ? ? ? ? ? _ Hshr'_shr'' _ _ _ _ _]; subst.\n                  ** inversion Hshr; by find_nil_rcons.\n                  ** specialize (Hshr'_shr'' _ Hshr)\n                      as [[cid bid] [Hren [_ Hcontra]]].\n                     unfold rename_addr_option, sigma_shifting_wrap_bid_in_addr\n                       in *.\n                     simpl in *.\n                     destruct (cid \\in domm (prog_interface p)) eqn:ecid;\n                       rewrite ecid in Hren.\n                     ---\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n'' cid) (n cid) bid); try discriminate.\n                       inversion Hren. subst.\n                         by rewrite ecid in Horiginal_not_p; exfalso; auto.\n                     ---\n                       destruct\n                         (sigma_shifting_lefttoright_option\n                            (n'' cid) (n'' cid) bid) eqn:esigma;\n                         try discriminate.\n                       apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                       inversion Hren. subst.\n                         by destruct original_addr; simpl in *; intuition.\n                         (* contradiction Hcontra with Hnotshr *)\n                    \n              * specialize (Hprivrel _ Horiginal Hnotshr) as [Hprivrel' _].\n                  by eapply Hprivrel'.\n            + erewrite Memory.load_after_store in Hload_c';\n                last exact Hstoremem1'.\n              find_if_inside_hyp Hload_c'.\n              * assert ((Permission.data, original_addr.1,\n                         original_addr.2, offset) = ptr).\n                by apply/Pointer.eqP.\n                subst.\n                assert (CSInvariants.wf_ptr_wrt_cid_t\n                          (Pointer.component pc)\n                          t1'\n                          (Permission.data,\n                           original_addr.1,\n                           original_addr.2, offset)) as Hwf.\n                {\n                  eapply CSInvariants.wf_reg_wf_ptr_wrt_cid_t; eauto.\n                  eapply CSInvariants.wf_state_wf_reg\n                      with (s := (gps1', mem1', regs1', pc)); eauto.\n                  eapply CSInvariants.is_prefix_wf_state_t\n                    with (p := (program_link p c')); eauto.\n                  - eapply interface_preserves_closedness_r; eauto.\n                    + by unfold mergeable_interfaces in *; intuition.\n                    + eapply linkable_implies_linkable_mains; eauto.\n                        by unfold mergeable_interfaces in *; intuition.\n                    + apply interface_implies_matching_mains; auto.\n                  - eapply linking_well_formedness; try assumption.\n                    rewrite <- Hifc_cc'.\n                    by unfold mergeable_interfaces in *;\n                      intuition.\n                }\n                \n\n                inversion Hwf as [| ? ? ? ? Hshr]; subst.\n                ++\n                  match goal with\n                  | Hrewr: Pointer.component pc = _ |- _ =>\n                    rewrite Hrewr in Hpc_in\n                  end.\n                  by intuition. (* contradiction *)\n                ++\n                  inversion Hshift_t''t' as [? ? t''t'ren]. subst.\n                  inversion t''t'ren\n                    as [|? ? ? ? ? ? _ Hshr'_shr'' _ _ _ _ _]; subst.\n                  ** inversion Hshr; by find_nil_rcons.\n                  ** specialize (Hshr'_shr'' _ Hshr)\n                      as [[cid bid] [Hren [_ Hcontra]]].\n                     unfold rename_addr_option, sigma_shifting_wrap_bid_in_addr\n                       in *.\n                     simpl in *.\n                     destruct (cid \\in domm (prog_interface p)) eqn:ecid;\n                       rewrite ecid in Hren.\n                     ---\n                       destruct (sigma_shifting_lefttoright_option\n                                   (n'' cid) (n cid) bid); try discriminate.\n                       inversion Hren. subst.\n                         by rewrite ecid in Horiginal_not_p; exfalso; auto.\n                     ---\n                       destruct\n                         (sigma_shifting_lefttoright_option\n                            (n'' cid) (n'' cid) bid) eqn:esigma;\n                         try discriminate.\n                       apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                       inversion Hren. subst.\n                         by destruct original_addr; simpl in *; intuition.\n                         (* contradiction Hcontra with Hnotshr *)\n                \n              * specialize (Hprivrel _ Horiginal Hnotshr) as [_ Hprivrel'].\n                  by eapply Hprivrel'.\n\n          - intros ? Hcid.\n            assert (cid \\in domm (prog_interface p) -> False)\n              as Hcid_not_p.\n            {\n              intros contra.\n              rewrite <- Hifc_cc' in Hcid.\n              destruct Hmerge_ipic as [[_ Hcontra] _].\n                by specialize (fdisjoint_partition_notinboth\n                                 Hcontra Hcid contra).\n            }\n            \n            unfold Memory.store in *. simpl in *.\n            destruct (mem cid_st) as [memC|] eqn:ememC; try discriminate.\n            destruct (ComponentMemory.store memC bid_st off_st (Register.get r2 regs))\n              as [memC'|] eqn:ememC'; try discriminate.\n            match goal with | H: Some _ = Some _ |- _ => inversion H end. subst.\n            find_if_inside_hyp Hstoremem1'; try discriminate.\n            destruct (mem1' (Pointer.component ptr)) as [mem1'ptr|] eqn:emem1'ptr;\n              try discriminate.\n            destruct (ComponentMemory.store\n                        mem1'ptr\n                        (Pointer.block ptr) \n                        (Pointer.offset ptr)\n                        (Register.get r2 regs1')) as [mem1'ptrComp|]\n            eqn:compMemStore; try discriminate.\n            inversion Hstoremem1'. subst.\n            rewrite !setmE.\n            destruct (cid == Pointer.component ptr) eqn:ecid; rewrite ecid.\n            + specialize (Halloc cid Hcid).\n              unfold omap, obind, oapp in *.\n              erewrite <- ComponentMemory.next_block_store_stable;\n                last exact compMemStore.\n              rewrite Halloc.\n              assert (cid = Pointer.component ptr). by apply/eqP. subst.\n              by rewrite emem1'ptr.\n              \n            + by specialize (Halloc cid Hcid).\n        }\n        \n        \n        eexists. split.\n        * exact Hstep.\n\n        * econstructor; try eassumption.\n          -- (* mergeable_states_well_formed *)\n            eapply mergeable_states_well_formed_intro; try eassumption.\n            ++ by simpl.\n            ++ simpl. rewrite <- Hpccomp_s'_s''.\n                 by rewrite Pointer.inc_preserves_component.\n          -- by simpl.\n\n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n          \n\n\n    -  (* IJal *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1',\n                      Register.set R_RA (Ptr (Pointer.inc pc)) regs1',\n                      pc'\n                     )\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.Jal.\n          -- exact Hex'.\n          -- unfold sem', prog'.\n             eapply find_label_in_component_mergeable_internal_states; auto.\n             ++ exact H_p.\n             ++ exact Hmerge1.\n             ++ reflexivity.\n             ++ unfold sem, prog in *. assumption.\n          -- reflexivity.\n          -- reflexivity.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem,\n                   Register.set R_RA (Ptr (Pointer.inc pc)) regs, pc')\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1',\n                   Register.set R_RA (Ptr (Pointer.inc pc)) regs1',\n                   pc'\n                  )\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl. symmetry.\n             eapply find_label_in_component_1; eassumption.\n        * by simpl.\n        * simpl. constructor. intros ?.\n          inversion Hregsp as [Hregs]. specialize (Hregs reg).\n          unfold Register.get, Register.set in *. simpl in Hregs. rewrite !setmE.\n          destruct (Register.to_nat reg == Register.to_nat R_RA) eqn:ereg;\n            rewrite ereg; try assumption.\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n          assert (Pointer.permission pc = Permission.code).\n          {\n            match goal with\n            | H: executing _ pc _ |- _ =>\n              destruct H as [? [? ?]]; by intuition\n            end.\n          }\n          assert (Pointer.permission (Pointer.inc pc) = Permission.code) as Hcode.\n            by rewrite Pointer.inc_preserves_permission.\n            \n          destruct (Pointer.inc pc) as [[[perm cid] bid] off]. simpl in *. subst.\n          simpl. by left.\n\n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IJump *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Register.get r regs1' = Ptr pc') as Hregs1'_r.\n        {\n          inversion Hregsp as [Hregs].\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n\n          specialize (Hregs r) as [Hshift | Hshift];\n            simpl in Hshift;\n            match goal with\n            | Hr: Register.get r regs = _ |- _ => rewrite Hr in Hshift\n            end;\n            destruct pc' as [[[perm ?] ?] ?];\n            simpl in *;\n            subst;\n            simpl in *;\n            by inversion Hshift.\n        }\n\n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1', regs1', pc')\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.Jump.\n          -- exact Hex'.\n          -- assumption.\n          -- assumption.\n          -- assumption.\n          -- by simpl.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem, regs, pc')\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1', regs1', pc')\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl. assumption.\n        * by simpl.\n        \n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IJumpFunPtr *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Register.get r regs1' = Ptr pc') as Hregs1'_r.\n        {\n          inversion Hregsp as [Hregs].\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n\n          specialize (Hregs r) as [Hshift | Hshift];\n            simpl in Hshift;\n            match goal with\n            | Hr: Register.get r regs = _ |- _ => rewrite Hr in Hshift\n            end;\n            destruct pc' as [[[perm ?] ?] ?];\n            simpl in *;\n            subst;\n            simpl in *;\n            by inversion Hshift.\n        }\n\n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1', regs1', pc')\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.JumpFunPtr.\n          -- exact Hex'.\n          -- assumption.\n          -- assumption.\n          -- assumption.\n          -- assumption.\n          -- by simpl.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem, regs, pc')\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1', regs1', pc')\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl. assumption.\n        * by simpl.\n        \n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n\n\n    - (* IBnz, non-zero case *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Register.get r regs1' = Int val) as Hregs1'_r.\n        {\n\n          inversion Hregsp as [Hregs].\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n\n          specialize (Hregs r) as [Hshift | Hshift];\n            simpl in Hshift;\n            match goal with\n            | Hr: Register.get r regs = _ |- _ => rewrite Hr in Hshift\n            end;\n            simpl in *;\n            by inversion Hshift.\n\n        }\n\n        \n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1', regs1', pc')\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.BnzNZ.\n          -- exact Hex'.\n          -- eassumption.\n          -- assumption.\n          -- eapply find_label_in_procedure_mergeable_internal_states; auto.\n             ++ exact H_p.\n             ++ exact Hmerge1.\n             ++ reflexivity.\n             ++ unfold sem, prog in *. assumption.\n          -- by simpl.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem, regs, pc')\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1', regs1', pc')\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl.\n             symmetry.\n             eapply find_label_in_procedure_1; eassumption.\n        * by simpl.\n        \n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IBnz, zero case *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Register.get r regs1' = Int 0) as Hregs1'_r.\n        {\n          inversion Hregsp as [Hregs].\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n\n          specialize (Hregs r) as [Hshift | Hshift];\n            simpl in Hshift;\n            match goal with\n            | Hr: Register.get r regs = _ |- _ => rewrite Hr in Hshift\n            end;\n            simpl in *;\n            by inversion Hshift.\n        }\n\n        \n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem1', regs1', Pointer.inc pc)\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.BnzZ.\n          -- exact Hex'.\n          -- eassumption.\n          -- assumption.\n        }\n\n          assert (CSInvariants.is_prefix\n                  (gps, mem, regs, Pointer.inc pc)\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem1', regs1', Pointer.inc pc)\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl.\n             by rewrite Pointer.inc_preserves_component.\n        * by simpl.\n        \n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n    - (* IAlloc *)\n      destruct s1' as [[[gps1' mem1'] regs1'] pc1'].\n      find_and_invert_mergeable_internal_states;\n        find_and_invert_mergeable_states_well_formed.\n      + assert (pc1' = pc). by simpl in *.\n        subst pc1'. (* PC lockstep. *)\n        assert (Pointer.component pc \\in domm (prog_interface p)) as\n            Hpc_prog_interface_p.\n        {\n          unfold CS.is_program_component,\n          CS.is_context_component, turn_of, CS.state_turn in *.\n          unfold negb in Hcomp1.\n          pose proof @CS.star_pc_domm_non_inform p c\n                 Hwfp Hwfc Hmerge_ipic Hclosed_prog as Hor'.\n          assert (Pointer.component pc \\in domm (prog_interface p)\n                    \\/\n                    Pointer.component pc \\in domm (prog_interface c))\n              as [G | Hcontra]; auto.\n            {\n              unfold CSInvariants.is_prefix in Hpref_t.\n              eapply Hor'; eauto.\n              - by unfold CS.initial_state.\n            }\n            by (unfold ic in *; rewrite Hcontra in Hcomp1).\n        }\n        \n        match goal with\n        | H : executing (prepare_global_env prog) ?PC ?INSTR |- _ =>\n          assert (Hex' : executing (prepare_global_env prog') PC INSTR)\n        end.\n        {\n          eapply execution_invariant_to_linking with (c1 := c); eauto.\n          + unfold mergeable_interfaces in *. by intuition.\n          + rewrite <- Hifc_cc'. unfold mergeable_interfaces in *. by intuition.\n        }\n\n        assert (Register.get rsize regs1' = Int size) as Hregs1'_r.\n        {\n          inversion Hregsp as [Hregs].\n          unfold shift_value_option, rename_value_option,\n          rename_value_template_option in *.\n\n          specialize (Hregs rsize) as [Hshift | Hshift];\n            simpl in Hshift;\n            match goal with\n            | Hr: Register.get rsize regs = _ |- _ => rewrite Hr in Hshift\n            end;\n            simpl in *;\n            by inversion Hshift.\n        }\n\n        assert (\n          exists mem2',\n            Memory.alloc mem1' (Pointer.component pc) (Z.to_nat size) =\n            Some (mem2', ptr)\n        ) as [mem2' Halloc'].\n        {\n          destruct Hmemp as [_ [_ Hnextb_eq]].\n          specialize (Hnextb_eq (Pointer.component pc) Hpc_prog_interface_p).\n          simpl in Hnextb_eq.\n          unfold omap, obind, oapp in *.\n          unfold Memory.alloc in *.\n          destruct (mem (Pointer.component pc)) as [cMem|] eqn:ecMem; try discriminate.\n          destruct (mem1' (Pointer.component pc)) as [cMem1'|] eqn:ecMem1';\n            try discriminate.\n          destruct (ComponentMemory.alloc cMem1' (Z.to_nat size))\n            as [cMem1'_new b] eqn:ecMem1'_new.\n          eexists.\n          destruct (ComponentMemory.alloc cMem (Z.to_nat size))\n            as [cMem_new also_b] eqn:ecMem_new.\n          assert (also_b = b).\n          {\n            specialize (ComponentMemory.next_block_alloc _ _ _ _ ecMem1'_new) as [eb _].\n            specialize (ComponentMemory.next_block_alloc _ _ _ _ ecMem_new) as [eb' _].\n            subst.\n            by inversion Hnextb_eq.\n          }\n          subst.\n          repeat match goal with | H: Some _ = Some _ |- _ => inversion H; clear H end.\n          reflexivity.\n        }\n\n\n        assert (Pointer.component ptr \\in domm (prog_interface p)) as Hptr.\n        {\n          specialize (Memory.component_of_alloc_ptr _ _ _ _ _ Halloc').\n          intros H_. by rewrite H_.\n        }\n          \n        assert (mem_of_part_executing_rel_original_and_recombined\n                  p\n                  mem'\n                  mem2'\n                  n\n                  (fun cid : nat_ordType => if cid \\in domm (prog_interface p)\n                                            then n cid else n'' cid)\n                  t1\n               ) as [Hpriv [Hshared Hnextblock]].\n        {\n          destruct Hmemp as [Hpriv_given [Hshared_given Hnextblock_given]].\n\n          specialize (Memory.component_of_alloc_ptr _ _ _ _ _ Halloc')\n            as Hcompptr.\n          \n          split; last split.\n          - intros [cid_original bid_original] Horiginal.\n            unfold memory_shifts_memory_at_private_addr,\n            memory_renames_memory_at_private_addr,\n            rename_value_option,\n            rename_value_template_option in *.\n            \n            split.\n            + intros ? ? Hload. simpl in *.\n              \n              specialize (Hpriv_given (cid_original, bid_original) Horiginal).\n              destruct Hpriv_given as [Hpriv_given' _].\n              simpl in *.\n              specialize (Hpriv_given' offset v).\n\n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              simpl in *.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Heq.\n              simpl in *.\n              \n              match goal with\n              | H: Memory.alloc mem _ _ = _ |- _ =>\n                specialize (Memory.load_after_alloc\n                              _ _ _ _ _\n                              (Permission.data, cid_original, bid_original, offset)\n                              H\n                           ) as Hnoteq_p;\n                  simpl in Hnoteq_p;\n                  \n                  specialize (Memory.load_after_alloc_eq\n                                _ _ _ _ _\n                                (Permission.data, cid_original, bid_original, offset)\n                                H\n                             ) as Heq_p;\n                  simpl in Heq_p\n              end.\n              \n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by apply/eqP.\n                  inversion H_. subst. clear H_.\n                  rewrite Heq; auto.\n                  unfold Memory.load, Memory.alloc in *. simpl in *.\n                  destruct (mem1' (Pointer.component pc)) eqn:emem1'pc;\n                    try discriminate.\n                  destruct (mem (Pointer.component pc)) eqn:emempc;\n                    try discriminate.\n                  destruct (mem' (Pointer.component ptr)) eqn:emem'ptr;\n                    try discriminate.\n                  rewrite Hload in Heq_p.\n\n                  repeat match goal with\n                         | H: ?x = ?x -> ?y |- _ =>\n                           assert (y) by auto; clear H\n                         end.\n                  \n                  destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n                    destruct (Z.leb Z0 offset); auto; try discriminate.\n                    by destruct v; try discriminate.\n                    \n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  repeat match goal with\n                         | H: ?x <> ?z -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n\n                  rewrite assertion0.\n                  rewrite Hload in assertion.\n                  symmetry in assertion.\n                  by apply Hpriv_given'; auto.\n\n            + intros ? ? Hload. simpl in *.\n              \n              specialize (Hpriv_given (cid_original, bid_original) Horiginal).\n              destruct Hpriv_given as [_ Hpriv_given'].\n              simpl in *.\n              specialize (Hpriv_given' offset v').\n\n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              simpl in *.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Heq.\n              simpl in *.\n              \n              match goal with\n              | H: Memory.alloc mem _ _ = _ |- _ =>\n                specialize (Memory.load_after_alloc\n                              _ _ _ _ _\n                              (Permission.data, cid_original, bid_original, offset)\n                              H\n                           ) as Hnoteq_p;\n                  simpl in Hnoteq_p;\n                  \n                  specialize (Memory.load_after_alloc_eq\n                                _ _ _ _ _\n                                (Permission.data, cid_original, bid_original, offset)\n                                H\n                             ) as Heq_p;\n                  simpl in Heq_p\n              end.\n              \n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by apply/eqP.\n                  inversion H_. subst. clear H_.\n                  rewrite Heq_p; auto.\n                  unfold Memory.load, Memory.alloc in *. simpl in *.\n                  destruct (mem1' (Pointer.component pc)) eqn:emem1'pc;\n                    try discriminate.\n                  destruct (mem (Pointer.component pc)) eqn:emempc;\n                    try discriminate.\n                  destruct (mem2' (Pointer.component ptr)) eqn:emem2'ptr;\n                    try discriminate.\n                  rewrite Hload in Heq.\n\n                  repeat match goal with\n                         | H: ?x = ?x -> ?y |- _ =>\n                           assert (y) by auto; clear H\n                         end.\n\n                  destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n                    destruct (Z.leb Z0 offset); auto; try discriminate.\n                  by destruct v'; try discriminate; eexists; eauto.\n\n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  repeat match goal with\n                         | H: ?x <> ?z -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n\n                  rewrite assertion.\n                  rewrite Hload in assertion0.\n                  symmetry in assertion0.\n                    by apply Hpriv_given'; auto.\n\n          - intros [cid_original bid_original] Horiginal.\n            unfold memory_shifts_memory_at_shared_addr,\n            memory_renames_memory_at_shared_addr,\n            rename_value_option,\n            rename_value_template_option in *.\n\n            specialize (Hshared_given (cid_original, bid_original) Horiginal)\n              as [addr' [Haddr' [Hsharedmemmem1' Hsharedmem1'mem]]].\n            exists addr'; split; first assumption.\n            split.\n            + intros ? ? Hload. simpl in *.\n              \n              simpl in *.\n              specialize (Hsharedmemmem1' offset v).\n\n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, addr'.1, addr'.2, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              simpl in *.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, addr'.1, addr'.2, offset)\n                            Halloc'\n                         ) as Heq.\n              simpl in *.\n              \n              match goal with\n              | H: Memory.alloc mem _ _ = _ |- _ =>\n                specialize (Memory.load_after_alloc\n                              _ _ _ _ _\n                              (Permission.data, cid_original, bid_original, offset)\n                              H\n                           ) as Hnoteq_p;\n                  simpl in Hnoteq_p;\n                  \n                  specialize (Memory.load_after_alloc_eq\n                                _ _ _ _ _\n                                (Permission.data, cid_original, bid_original, offset)\n                                H\n                             ) as Heq_p;\n                  simpl in Heq_p\n              end.\n              \n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by apply/eqP.\n                  inversion H_. subst. clear H_.\n                  unfold rename_addr_option,\n                  sigma_shifting_wrap_bid_in_addr,\n                  sigma_shifting_lefttoright_addr_bid in Haddr'.\n                  rewrite Hptr in Haddr'.\n                  destruct (sigma_shifting_lefttoright_option\n                              (n (Pointer.component ptr))\n                              (n (Pointer.component ptr))\n                              (Pointer.block ptr)) eqn:esigma; try discriminate.\n                  apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                  destruct addr' as [cid' bid']. inversion Haddr'. subst.\n                  simpl in *.\n                  eexists; erewrite Heq; eauto.\n                  \n                  unfold Memory.load, Memory.alloc in *. simpl in *.\n                  destruct (mem1' (Pointer.component pc)) eqn:emem1'pc;\n                    try discriminate.\n                  destruct (mem (Pointer.component pc)) eqn:emempc;\n                    try discriminate.\n                  destruct (mem' (Pointer.component ptr)) eqn:emem'ptr;\n                    try discriminate.\n                  rewrite Hload in Heq_p.\n\n                  repeat match goal with\n                         | H: ?x = ?x -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n                  \n                  destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n                    destruct (Z.leb Z0 offset); auto; try discriminate.\n                    by destruct v; try discriminate.\n                    \n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  \n                  assert ((addr'.1, addr'.2) <>\n                          (Pointer.component ptr, Pointer.block ptr)).\n                  {\n                    destruct ptr as [[[? ?] ?] ?].\n                    unfold not. intros H'. inversion H'. subst.\n                    simpl in *.\n                    unfold rename_addr_option,\n                    sigma_shifting_wrap_bid_in_addr,\n                    sigma_shifting_lefttoright_addr_bid in Haddr'.\n                    destruct addr' as [addr'cid addr'bid].\n                    simpl in *.\n                    destruct (sigma_shifting_lefttoright_option\n                                (n cid_original)\n                                (if cid_original \\in domm (prog_interface p)\n                                 then n cid_original\n                                 else n'' cid_original) bid_original)\n                             eqn:esigma; rewrite esigma in Haddr';\n                      try discriminate.\n                    inversion Haddr'. subst.\n                    rewrite Hpc_prog_interface_p  in esigma.\n                    apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                    inversion esigma. subst.\n                    by rewrite eqxx in Hwhichaddr.\n                  }\n                  \n                  repeat match goal with\n                         | H: ?x <> ?z -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n\n\n                  rewrite assertion0.\n                  rewrite Hload in assertion.\n                  symmetry in assertion.\n                    by apply Hsharedmemmem1'; auto.\n\n            + intros ? ? Hload. simpl in *.\n              \n              simpl in *.\n              specialize (Hsharedmem1'mem offset v').\n\n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, addr'.1, addr'.2, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              simpl in *.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, addr'.1, addr'.2, offset)\n                            Halloc'\n                         ) as Heq.\n              simpl in *.\n              \n              match goal with\n              | H: Memory.alloc mem _ _ = _ |- _ =>\n                specialize (Memory.load_after_alloc\n                              _ _ _ _ _\n                              (Permission.data, cid_original, bid_original, offset)\n                              H\n                           ) as Hnoteq_p;\n                  simpl in Hnoteq_p;\n                  \n                  specialize (Memory.load_after_alloc_eq\n                                _ _ _ _ _\n                                (Permission.data, cid_original, bid_original, offset)\n                                H\n                             ) as Heq_p;\n                  simpl in Heq_p\n              end.\n              \n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by apply/eqP.\n                  inversion H_. subst. clear H_.\n                  unfold rename_addr_option,\n                  sigma_shifting_wrap_bid_in_addr,\n                  sigma_shifting_lefttoright_addr_bid in Haddr'.\n                  rewrite Hptr in Haddr'.\n                  destruct (sigma_shifting_lefttoright_option\n                              (n (Pointer.component ptr))\n                              (n (Pointer.component ptr))\n                              (Pointer.block ptr)) eqn:esigma; try discriminate.\n                  apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                  destruct addr' as [cid' bid']. inversion Haddr'. subst.\n                  simpl in *.\n                  eexists; erewrite Heq_p; eauto.\n                  \n                  unfold Memory.load, Memory.alloc in *. simpl in *.\n                  destruct (mem1' (Pointer.component pc)) eqn:emem1'pc;\n                    try discriminate.\n                  destruct (mem (Pointer.component pc)) eqn:emempc;\n                    try discriminate.\n                  destruct (mem2' (Pointer.component ptr)) eqn:emem'ptr;\n                    try discriminate.\n                  rewrite Hload in Heq.\n\n                  repeat match goal with\n                         | H: ?x = ?x -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n                  \n                  destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n                    destruct (Z.leb Z0 offset); auto; try discriminate.\n                    \n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  \n                  assert ((addr'.1, addr'.2) <>\n                          (Pointer.component ptr, Pointer.block ptr)).\n                  {\n                    destruct ptr as [[[? ?] ?] ?].\n                    unfold not. intros H'. inversion H'. subst.\n                    simpl in *.\n                    unfold rename_addr_option,\n                    sigma_shifting_wrap_bid_in_addr,\n                    sigma_shifting_lefttoright_addr_bid in Haddr'.\n                    destruct addr' as [addr'cid addr'bid].\n                    simpl in *.\n                    destruct (sigma_shifting_lefttoright_option\n                                (n cid_original)\n                                (if cid_original \\in domm (prog_interface p)\n                                 then n cid_original\n                                 else n'' cid_original) bid_original)\n                             eqn:esigma; rewrite esigma in Haddr';\n                      try discriminate.\n                    inversion Haddr'. subst.\n                    rewrite Hpc_prog_interface_p  in esigma.\n                    apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                    inversion esigma. subst.\n                    by rewrite eqxx in Hwhichaddr.\n                  }\n                  \n                  repeat match goal with\n                         | H: ?x <> ?z -> ?y |- _ =>\n                           let assertion := fresh \"assertion\" in\n                           assert (y) as assertion by auto; clear H\n                         end.\n\n\n                  rewrite assertion.\n                  rewrite Hload in assertion0.\n                  symmetry in assertion0.\n                    by apply Hsharedmem1'mem; auto.\n\n          - intros cid Hcid.\n            unfold Memory.alloc in *.\n            destruct (mem (Pointer.component pc)) as [memComp|] eqn:ememComp;\n              try discriminate.\n            destruct (mem1' (Pointer.component pc)) as [mem1'Comp|] eqn:emem1'Comp;\n              try discriminate.\n            destruct (ComponentMemory.alloc memComp (Z.to_nat size))\n              as [memComp' b] eqn:ememComp'.\n            destruct (ComponentMemory.alloc mem1'Comp (Z.to_nat size))\n              as [mem1'Comp' b'] eqn:emem1'Comp'.\n            match goal with\n            | H: Some _ = Some _, H2: Some _ = Some _ |- _ =>\n              inversion H; subst; clear H; inversion H2; subst; clear H2\n            end.\n            rewrite !setmE.\n            destruct (cid == Pointer.component pc) eqn:ecid.\n            + unfold omap, obind, oapp in *.\n              \n              specialize (ComponentMemory.next_block_alloc _ _ _ _ emem1'Comp')\n                as [_ G1].\n              rewrite G1.\n              specialize (ComponentMemory.next_block_alloc _ _ _ _ ememComp')\n                as [_ G2].\n              rewrite G2.\n\n              specialize (Hnextblock_given (Pointer.component pc) Hptr).\n              simpl in Hnextblock_given.\n              rewrite ememComp emem1'Comp in Hnextblock_given.\n              inversion Hnextblock_given as [Hrewr].\n              by rewrite Hrewr.\n\n            + specialize (Hnextblock_given cid Hcid).\n              simpl in Hnextblock_given.\n              inversion Hnextblock_given as [Hrewr].\n              by rewrite Hrewr.\n                \n        }\n\n\n        assert (mem_of_part_not_executing_rel_original_and_recombined_at_internal\n                  c' \n                  (CS.state_mem s1'')\n                  mem2'\n                  n''\n                  (fun cid : nat => if cid \\in domm (prog_interface p)\n                                    then n cid else n'' cid)\n                  t1''\n               ) as [Hpriv_not_exec Hnextblock_not_exec].\n        {\n          destruct Hmemc' as [Hpriv_given Hnextblock_given].\n          split.\n          - intros [cid_original bid_original] Horiginal1 Horiginal2.\n            unfold memory_shifts_memory_at_private_addr,\n            memory_renames_memory_at_private_addr in *.\n            split; intros ? ? Hload.\n            + \n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Heq.\n              \n              specialize (Hpriv_given\n                            (cid_original, bid_original) Horiginal1 Horiginal2)\n                as [Hpriv_given' _].\n              specialize (Hpriv_given' offset v).\n              simpl in *.\n\n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr))\n                  as H_. by apply/eqP.\n                inversion H_. subst. clear H_.\n                simpl in *.\n                rewrite <- Hifc_cc' in Horiginal1.\n                unfold mergeable_interfaces, linkable in *.\n                destruct Hmerge_ipic as [[_ Hcontra] _].\n                  by specialize (fdisjoint_partition_notinboth Hcontra Horiginal1 Hptr).\n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  rewrite Hnoteq; auto.\n                  eapply Hpriv_given'; eauto.\n\n            +\n              specialize (Memory.load_after_alloc\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Hnoteq.\n              \n              specialize (Memory.load_after_alloc_eq\n                            _ _ _ _ _\n                            (Permission.data, cid_original, bid_original, offset)\n                            Halloc'\n                         ) as Heq.\n              \n              specialize (Hpriv_given\n                            (cid_original, bid_original) Horiginal1 Horiginal2)\n                as [_ Hpriv_given'].\n              specialize (Hpriv_given' offset v').\n              simpl in *.\n\n              destruct ((cid_original, bid_original) ==\n                        (Pointer.component ptr, Pointer.block ptr))\n                       eqn:Hwhichaddr.\n              * assert ((cid_original, bid_original) =\n                        (Pointer.component ptr, Pointer.block ptr))\n                  as H_. by apply/eqP.\n                inversion H_. subst. clear H_.\n                simpl in *.\n                rewrite <- Hifc_cc' in Horiginal1.\n                unfold mergeable_interfaces, linkable in *.\n                destruct Hmerge_ipic as [[_ Hcontra] _].\n                  by specialize (fdisjoint_partition_notinboth Hcontra Horiginal1 Hptr).\n              * assert ((cid_original, bid_original) <>\n                        (Pointer.component ptr, Pointer.block ptr)) as H_.\n                  by intros H_; inversion H_; subst; rewrite eqxx in Hwhichaddr.\n\n                  rewrite Hnoteq in Hload; auto.\n\n          - intros cid Hcid.\n            unfold Memory.alloc in *.\n            destruct (mem (Pointer.component pc)) as [memComp|] eqn:ememComp;\n              try discriminate.\n            destruct (mem1' (Pointer.component pc)) as [mem1'Comp|] eqn:emem1'Comp;\n              try discriminate.\n            destruct (ComponentMemory.alloc memComp (Z.to_nat size))\n              as [memComp' b] eqn:ememComp'.\n            destruct (ComponentMemory.alloc mem1'Comp (Z.to_nat size))\n              as [mem1'Comp' b'] eqn:emem1'Comp'.\n            match goal with\n            | H: Some _ = Some _, H2: Some _ = Some _ |- _ =>\n              inversion H; subst; clear H; inversion H2; subst; clear H2\n            end.\n            rewrite !setmE.\n            destruct (cid == Pointer.component pc) eqn:ecid.\n            + assert (cid = Pointer.component pc). by apply/eqP. subst.\n              rewrite <- Hifc_cc' in Hcid.\n              unfold mergeable_interfaces, linkable in *.\n              destruct Hmerge_ipic as [[_ Hcontra] _].\n                by specialize (fdisjoint_partition_notinboth\n                                 Hcontra Hcid Hpc_prog_interface_p).\n\n            + specialize (Hnextblock_given cid Hcid).\n              simpl in Hnextblock_given.\n              inversion Hnextblock_given as [Hrewr].\n              by rewrite Hrewr.\n\n        }\n\n        \n        assert (\n          regs_rel_of_executing_part\n            (Register.set rptr (Ptr ptr) regs)\n            (Register.set rptr (Ptr ptr) regs1')\n            n\n            (fun cid : nat_ordType =>\n               if cid \\in domm (prog_interface p) then n cid else n'' cid)\n        ) as Hregs.\n        {\n          constructor. intros reg. unfold Register.get, Register.set.\n          rewrite !setmE.\n          destruct (Register.to_nat reg == Register.to_nat rptr) eqn:ereg;\n            rewrite ereg.\n          - destruct ptr as [[[perm cid] bid] off].\n            unfold shift_value_option, rename_value_option,\n            rename_value_template_option, rename_addr_option,\n            sigma_shifting_wrap_bid_in_addr,\n            sigma_shifting_lefttoright_addr_bid in *. simpl in *.\n            rewrite Hptr.\n            assert (perm = Permission.data).\n            {\n                by specialize (Memory.permission_of_alloc_ptr _ _ _ _ _ Halloc');\n                  simpl in *.\n            }\n            subst. simpl.\n            destruct (sigma_shifting_lefttoright_option (n cid) (n cid) bid)\n                     eqn:esigma.\n            + apply sigma_shifting_lefttoright_option_n_n_id in esigma.\n                by subst; left.\n            + by right; intuition.\n          - inversion Hregsp as [G]. by specialize (G reg).\n        }\n                \n        assert (Step sem'\n                     (gps1', mem1', regs1', pc)\n                     E0\n                     (gps1', mem2', Register.set rptr (Ptr ptr) regs1', Pointer.inc pc)\n               ) as Hstep12'.\n        {\n          eapply CS.Step_non_inform; first eapply CS.Alloc.\n          -- exact Hex'.\n          -- eassumption.\n          -- assumption.\n          -- eassumption.\n          -- reflexivity.\n          -- reflexivity.\n        }\n\n\n        assert (CSInvariants.is_prefix\n                  (gps, mem', Register.set rptr (Ptr ptr) regs, Pointer.inc pc)\n                  (program_link p c) t1)\n          as H_prefix_after_step.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n        \n\n        assert (CSInvariants.is_prefix\n                  (gps1', mem2', Register.set rptr (Ptr ptr) regs1', Pointer.inc pc)\n                  (program_link p c')\n                  t1'\n               )\n          as H_prefix_after_step'.\n        {\n          unfold CSInvariants.is_prefix in *.\n          eapply star_right; try eassumption.\n          ++ by rewrite E0_right.\n        }\n\n        (*\n        assert (good_memory (left_addr_good_for_shifting n) mem') as Hgood_memp_alloc.\n        {\n          unfold good_memory.\n          intros ? ? ? ? ? ? Hlgood Hloadptr.\n          match goal with | Halloc: Memory.alloc mem _ _ = _ |- _ =>\n                            specialize (Memory.load_after_alloc_eq\n                                          _ _ _ _ _\n                                          (Permission.data, cid, bid, offset)\n                                          Halloc\n                                       ) as Heq;\n                            specialize (Memory.load_after_alloc\n                                          _ _ _ _ _\n                                          (Permission.data, cid, bid, offset)\n                                          Halloc\n                                       ) as Hnoteq  \n          end.\n          simpl in Heq. simpl in Hnoteq.\n          destruct ((cid, bid) == (Pointer.component ptr, Pointer.block ptr))\n                   eqn:eptr.\n          - assert ((cid, bid) = (Pointer.component ptr, Pointer.block ptr)) as H_.\n              by apply/eqP.\n            inversion H_. subst. clear H_ eptr.\n            rewrite Heq in Hloadptr; auto.\n            destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n              destruct (Z.leb Z0 offset); discriminate.\n          - assert ((cid, bid) <> (Pointer.component ptr, Pointer.block ptr)) as H_.\n            { intros H_. inversion H_. subst. clear H_. by rewrite eqxx in eptr.  }\n            rewrite Hnoteq in Hloadptr; auto.\n            by eapply Hgood_mem; eauto.\n        }\n\n        assert (good_memory\n                  (left_addr_good_for_shifting\n                     (fun cid : nat => if cid \\in domm (prog_interface p)\n                                       then n cid else n'' cid))\n                  mem2') as Hgood_mem2'.\n        {\n          unfold good_memory.\n          intros ? ? ? ? ? ? Hlgood Hloadptr.\n          specialize (Memory.load_after_alloc_eq\n                        _ _ _ _ _\n                        (Permission.data, cid, bid, offset)\n                        Halloc'\n                     ) as Heq.\n          specialize (Memory.load_after_alloc\n                        _ _ _ _ _\n                        (Permission.data, cid, bid, offset)\n                        Halloc'\n                     ) as Hnoteq.\n          simpl in Heq. simpl in Hnoteq.\n          destruct ((cid, bid) == (Pointer.component ptr, Pointer.block ptr))\n                   eqn:eptr.\n          - assert ((cid, bid) = (Pointer.component ptr, Pointer.block ptr)) as H_.\n              by apply/eqP.\n            inversion H_. subst. clear H_ eptr.\n            rewrite Heq in Hloadptr; auto.\n            destruct (Z.ltb offset (Z.of_nat (Z.to_nat size)));\n              destruct (Z.leb Z0 offset); discriminate.\n          - assert ((cid, bid) <> (Pointer.component ptr, Pointer.block ptr)) as H_.\n            { intros H_. inversion H_. subst. clear H_. by rewrite eqxx in eptr.  }\n            rewrite Hnoteq in Hloadptr; auto.\n            by eapply Hgood_mem'; eauto.\n        }\n        *)\n        \n        eexists. split; eauto.\n        econstructor; try eassumption.\n        * (* mergeable_states_well_formed *)\n          eapply mergeable_states_well_formed_intro; try eassumption.\n          -- by simpl.\n          -- rewrite <- Hpccomp_s'_s''. simpl.\n             by rewrite Pointer.inc_preserves_component.\n        * by simpl.\n        * by unfold mem_of_part_executing_rel_original_and_recombined; intuition.\n        * by unfold\n               mem_of_part_not_executing_rel_original_and_recombined_at_internal;\n            intuition.\n        \n      + simpl in *. subst.\n        unfold CS.is_program_component,\n        CS.is_context_component, turn_of, CS.state_turn in *.\n        unfold negb, ic in Hcomp1.\n        rewrite Hpccomp_s'_s in H_c'.\n          by rewrite H_c' in Hcomp1.\n\n\n    - discriminate.\n    - discriminate.\n\n      \n  Qed.\n  \n\n  Theorem threeway_multisem_star_E0 s1 s1' s1'' t1 t1' t1'' s2 :\n    CS.is_program_component s1 ic ->\n    mergeable_internal_states p c p' c' n n'' s1 s1' s1'' t1 t1' t1'' ->\n    starR (CS.step_non_inform) (prepare_global_env prog) s1  E0 s2  ->\n    exists s2',\n      starR (CS.step_non_inform) (prepare_global_env prog') s1' E0 s2' /\\\n      mergeable_internal_states p c p' c' n n'' s2 s2' s1'' t1 t1' t1''.\n  Proof.\n    intros Hcomp Hmerge Hstar.\n    remember E0 as t.\n    induction Hstar as [| ]; subst.\n    - eexists; split; last exact Hmerge. constructor.\n    - assert (t0 = E0). by now destruct t0. subst.\n      assert (t2 = E0). by now destruct t2. subst.\n      pose proof (IHHstar Hcomp Hmerge Logic.eq_refl) as [s2' [Hs2' Hmerge2]].\n      assert (Hcomp2: CS.is_program_component s2 ic).\n      {\n        eapply CS.epsilon_star_non_inform_preserves_program_component; eauto.\n        erewrite star_iff_starR. simpl.\n        exact Hstar.\n      }\n      match goal with\n        | Hstep: CS.step_non_inform _ _ _ _ |- _ =>\n          pose proof threeway_multisem_step_E0 Hcomp2 Hmerge2 Hstep as G\n      end.\n      destruct G as [? [? ?]].\n\n      eexists; split; first eapply starR_step; first eassumption; eauto.\n  Qed.\n\n\nEnd ThreewayMultisem1.\n\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/RecompositionRelLockstepSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.18741991858342863}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Coqlib.\nFrom compcert Require Import\n     AST Memory Globalenvs Maps Values Linking\n     Ctypes Clight Clightdefs.\n\nRequire Import ZArith String Bool List Lia.\n\nRequire Import sflib.\nRequire Import StdlibExt IntegersExt.\nRequire Import DiscreteTimeModel IPModel.\n\nRequire Import SysSem.\nRequire Import NWSysModel.\nRequire Import OSModel OSNodes.\nRequire Import RTSysEnv.\nRequire Import CProgEventSem.\nRequire Import SyncSysModel.\nRequire Import ProgSem.\nRequire Import LinkLemmas.\nRequire Import MWITree.\n\nRequire Import config_prm main_prm SystemProgs.\nRequire Import VerifProgBase.\nRequire Import MWLinkInversion.\nRequire Import PALSSystem.\n\nRequire Import ctrl.\nRequire Import AcStSystem.\n\nLocal Opaque Z.to_nat Z.of_nat PTree.combine.\n\nImport ITreeNotations.\nImport ListNotations.\n\nImport ActiveStandby.\n\nSet Nested Proofs Allowed.\n\nLocal Open Scope Z.\n\n\n(* Definition MAX_TIMEOUT: nat := 5. *)\nDefinition MAX_TIMEOUT: Z := 5.\nDefinition QSIZE: Z := 4.\n\nModule CtrlState.\n\n  Inductive mode_t: Type :=\n  | Uninit | Active | Standby.\n\n  Definition mode_to_Z (md: mode_t): Z :=\n    match md with\n    | Uninit => 0\n    | Active => 1\n    | Standby => 2\n    end.\n\n  Definition mode_of_Z (md_z: Z): mode_t :=\n    if md_z =? 1 then Active\n    else if md_z =? 2 then Standby\n         else Uninit.\n\n  Definition default_mode (tid: Z): mode_t :=\n    if tid =? 1 then Active else Standby.\n\n  Record t: Type :=\n    mk { mode: mode_t ;\n         timeout: Z ;\n\n         queue_begin: Z ;\n         queue_end: Z ;\n         queue: list Z ;\n       }.\n\n  Inductive wf: t -> Prop :=\n    Wf md tout qb qe q\n       (RANGE_TOUT: IntRange.sintz8 tout)\n       (RANGE_QBGN: IntRange.sintz8 qb)\n       (RANGE_QEND: IntRange.sintz8 qe)\n       (RANGE_QUEUE: Forall IntRange.sintz8 q)\n       (QUEUE_LENGTH: length q = 4%nat)\n    : wf (mk md tout qb qe q).\n\n  Definition init: t :=\n    mk Uninit 0 0 0 [0; 0; 0; 0].\n\n  Lemma wf_init: wf init.\n  Proof.\n    econs; ss.\n    do 4 (econs; ss).\n  Qed.\n\n  Definition set_mode (md: mode_t) (st: t): t :=\n    let 'mk _ tout qb qe q := st in\n    mk md tout qb qe q.\n\n  Lemma wf_set_mode md st\n        (WF: wf st)\n    : wf (set_mode md st).\n  Proof.\n    inv WF. econs; ss.\n  Qed.\n\n  (* Definition copy_state_from_hb *)\n  (*            (st: t) (msg: list byte): t := *)\n  (*   (* let 'CtrlState md tout qb qe q := st in *) *)\n  (*   let tout_msg := Byte.signed (nth 1 msg Byte.zero) in *)\n  (*   let qb_msg := Byte.signed (nth 2 msg Byte.zero) in *)\n  (*   let qe_msg := Byte.signed (nth 3 msg Byte.zero) in *)\n  (*   let q1_msg := Byte.signed (nth 4 msg Byte.zero) in *)\n  (*   let q2_msg := Byte.signed (nth 5 msg Byte.zero) in *)\n  (*   let q3_msg := Byte.signed (nth 6 msg Byte.zero) in *)\n  (*   let q4_msg := Byte.signed (nth 7 msg Byte.zero) in *)\n  (*   mk (mode st) tout_msg qb_msg qe_msg *)\n  (*      [q1_msg; q2_msg; q3_msg; q4_msg]. *)\n\n  Definition of_bytes (msg: bytes): t :=\n    let md_msg := Byte.signed (nth 0 msg Byte.zero) in\n    let tout_msg := Byte.signed (nth 1 msg Byte.zero) in\n    let qb_msg := Byte.signed (nth 2 msg Byte.zero) in\n    let qe_msg := Byte.signed (nth 3 msg Byte.zero) in\n    let q1_msg := Byte.signed (nth 4 msg Byte.zero) in\n    let q2_msg := Byte.signed (nth 5 msg Byte.zero) in\n    let q3_msg := Byte.signed (nth 6 msg Byte.zero) in\n    let q4_msg := Byte.signed (nth 7 msg Byte.zero) in\n    mk (mode_of_Z md_msg) tout_msg qb_msg qe_msg\n       [q1_msg; q2_msg; q3_msg; q4_msg].\n\n  Lemma wf_of_bytes msg: wf (of_bytes msg).\n  Proof.\n    econs.\n    - apply Byte.signed_range.\n    - apply Byte.signed_range.\n    - apply Byte.signed_range.\n    - econs; [ apply Byte.signed_range |].\n      econs; [ apply Byte.signed_range |].\n      econs; [ apply Byte.signed_range |].\n      econs; [ apply Byte.signed_range |].\n      econs.\n    - ss.\n  Qed.\n\n  (* Definition copy_state_from_hb *)\n  (*            (st: t) (msg: list byte): t := *)\n  (*   set_mode (mode st) (of_bytes msg). *)\n\n  Definition copy_state_from_hb\n             (md: mode_t) (msg: list byte): t :=\n    set_mode md (of_bytes msg).\n\n  Lemma wf_copy_state_from_hb md msg\n    : wf (copy_state_from_hb md msg).\n  Proof.\n    unfold copy_state_from_hb.\n    apply wf_set_mode.\n    apply wf_of_bytes.\n  Qed.\n\n  Definition to_bytes (st: t): bytes :=\n    let 'mk md tout qb qe q := st in\n    map Byte.repr (mode_to_Z md :: tout :: qb :: qe :: q).\n\nEnd CtrlState.\n\n\nDefinition qrange_sanitize (i: Z): Z :=\n  if (andb (0 <=? i) (i <? QSIZE)) then i else 0.\n\nLemma range_qrange_sanitize i\n  : IntRange.sintz8 (qrange_sanitize i).\nProof.\n  unfold qrange_sanitize.\n  destruct (Z.leb_spec 0 i);\n    destruct (Z.ltb_spec i QSIZE); ss.\n  unfold QSIZE in *.\n  r.\n  pose proof int_consts_lts as X; desH X.\n  split.\n  - nia.\n  - etransitivity.\n    { instantiate (1:= 4). nia. }\n    { ss. }\nQed.\n\nDefinition adv_qidx (i: Z): Z :=\n  qrange_sanitize (i + 1).\n\nLemma range_adv_qidx i\n  : IntRange.sintz8 (adv_qidx i).\nProof.\n  apply range_qrange_sanitize.\nQed.\n\nDefinition check_dev_id (id: Z): bool :=\n  existsb (Z.eqb id) [Z.of_nat tid_dev1;\n                     Z.of_nat tid_dev2;\n                     Z.of_nat tid_dev3].\n\nImport CtrlState.\n\n(* Activate state in case of failure at other side *)\nDefinition activate_nhb (st: CtrlState.t)\n  : CtrlState.t :=\n  let 'CtrlState.mk _ tout qb qe q := st in\n  let tout' := if (tout =? MAX_TIMEOUT)%Z then 0 else tout in\n  CtrlState.mk Active tout' qb qe q.\n\nDefinition sync_istate (tid: Z) (st: CtrlState.t)\n           (inb: list bytes?)\n  : CtrlState.t :=\n  let other_tid: Z := 3 - tid in\n  let msg_con := nth 0 inb None in\n  let msg_hb := nth (Z.to_nat other_tid) inb None in\n\n  match st.(mode) with\n  | Uninit =>\n    match msg_hb with\n    | Some hb =>\n      copy_state_from_hb Standby hb\n    | None =>\n      set_mode (default_mode tid) st\n    end\n  | Active =>\n    match msg_hb, msg_con with\n    | Some _ , Some _ => set_mode Standby st\n    | _, _ => st\n    end\n  | Standby =>\n    match msg_hb with\n    | Some hb =>\n      let md' := if msg_con then Active else Standby in\n      copy_state_from_hb md' hb\n    | None =>\n      activate_nhb st\n    end\n  end.\n\nLemma wf_sync_istate\n      tid st inb\n      (WF_ST: wf st)\n  : wf (sync_istate tid st inb).\nProof.\n  inv WF_ST.\n  unfold sync_istate. ss.\n  desf.\n  - apply wf_copy_state_from_hb.\n  - apply wf_copy_state_from_hb.\n  - apply wf_copy_state_from_hb.\nQed.\n\n\nDefinition get_queue (csr: Z) (q: list Z): Z :=\n  nth (Z.to_nat csr) q 0.\n\nLemma range_get_queue\n      csr q\n      (RANGE_Q: Forall IntRange.sintz8 q)\n  : IntRange.sintz8 (get_queue csr q).\nProof.\n  unfold get_queue.\n  rewrite Forall_nth in RANGE_Q.\n\n  destruct (lt_ge_dec (Z.to_nat csr) (length q)).\n  - hexploit (nth_error_Some2 _ q (Z.to_nat csr)); eauto.\n    i. des.\n    erewrite nth_error_nth; eauto.\n    specialize (RANGE_Q (Z.to_nat csr)).\n    r in RANGE_Q. desf.\n  - rewrite nth_overflow by ss.\n    range_stac.\nQed.\n\nDefinition set_queue (csr: Z) (elem: Z) (q: list Z)\n  : list Z :=\n  replace_nth q (Z.to_nat csr) elem.\n\nLemma range_len_set_queue\n      csr elem q\n      (RANGE_Q: Forall IntRange.sintz8 q)\n      (RANGE_ELEM: IntRange.sintz8 elem)\n  : Forall IntRange.sintz8 (set_queue csr elem q) /\\\n    length (set_queue csr elem q) = length q.\nProof.\n  unfold set_queue.\n  generalize (Z.to_nat csr) as idx. clear csr. i.\n\n  generalize (replace_nth_spec _ q idx elem).\n  intros [ [LEN_OF REPL_EQ] | AUX ].\n  { rewrite REPL_EQ. ss. }\n\n  destruct AUX as (l1 & p & l2 & Q_EQ & LEN & REPL_EQ).\n  rewrite REPL_EQ. subst q.\n\n  apply Forall_app_inv in RANGE_Q. des.\n  apply Forall_app_inv in RANGE_Q0. des.\n  split.\n  2: { repeat rewrite app_length. ss. }\n  apply Forall_app; eauto.\n  apply Forall_app; eauto.\nQed.\n\n\nFixpoint try_add_queue_loop\n         (st: CtrlState.t) (* (qe: Z) *) (id_dev: Z)\n         (n: nat) (csr: Z)\n  : CtrlState.t :=\n  match n with\n  | O => st\n  | S n' =>\n    let 'mk md tout qb qe q := st in\n    if csr =? qe then\n      let q' := set_queue csr id_dev q in\n      let qe' := adv_qidx csr in\n      mk md tout qb qe' q'\n    else\n      if get_queue csr q =? id_dev then\n        st (* already in queue *)\n      else\n        try_add_queue_loop st id_dev n' (adv_qidx csr)\n  end.\n\nLemma wf_try_add_queue_loop\n      st id_dev\n      n csr\n      (WF_ST: wf st)\n      (RANGE_ID_DEV: IntRange.sintz8 id_dev)\n  : wf (try_add_queue_loop st id_dev n csr).\nProof.\n  depgen csr.\n  induction n as [| n' IH]; i; ss.\n\n  inv WF_ST.\n  destruct (Z.eqb_spec csr qe); eauto.\n  2: { desf. }\n\n  subst csr.\n  hexploit (range_len_set_queue qe id_dev); eauto. i. des.\n  econs; eauto.\n  - apply range_adv_qidx.\n  - congruence.\nQed.\n\n\nDefinition try_add_queue (st: CtrlState.t) (id_dev: Z)\n  : CtrlState.t :=\n  let qb := qrange_sanitize (queue_begin st) in\n  try_add_queue_loop st (* (queue_end st) *) id_dev 3 qb.\n\nLemma wf_try_add_queue\n      st id_dev\n      (WF_ST: wf st)\n      (RANGE_ID_DEV: IntRange.sintz8 id_dev)\n  : wf (try_add_queue st id_dev).\nProof.\n  apply wf_try_add_queue_loop; eauto.\nQed.\n\n\nDefinition try_release (st: CtrlState.t) (id_dev: Z)\n  : CtrlState.t :=\n  let 'mk md tout qb qe q := st in\n  if andb (andb (negb (qb =? qe))\n                (get_queue (qrange_sanitize qb) q =? id_dev))\n          (andb (0 <? tout) (tout <? MAX_TIMEOUT))\n  then\n    mk md 1 qb qe q\n  else st.\n\nLemma wf_try_release\n      st id_dev\n      (WF_ST: wf st)\n  : wf (try_release st id_dev).\nProof.\n  unfold try_release.\n  inv WF_ST.\n  desf.\nQed.\n\n\nDefinition apply_devmsg (st: CtrlState.t)\n           (id_dev: Z) (ment: bytes?)\n  : CtrlState.t :=\n  match ment with\n  | Some msg =>\n    let b: Z := Byte.signed (nth 0 msg Byte.zero) in\n    if (b =? 1) then\n      (* acquire *)\n      try_add_queue st id_dev\n    else\n      (* release *)\n      try_release st id_dev\n  | None => st\n  end.\n\nLemma wf_apply_devmsg\n      st id_dev ment\n      (WF_ST: wf st)\n      (RANGE_ID_DEV: IntRange.sintz8 id_dev)\n  : wf (apply_devmsg st id_dev ment).\nProof.\n  unfold apply_devmsg.\n  inv WF_ST.\n  destruct ment; ss.\n  desf.\n  apply wf_try_add_queue; eauto.\n  econs; eauto.\nQed.\n\n\nDefinition reduce_timeout (st: CtrlState.t)\n  : CtrlState.t :=\n  let 'mk md tout qb qe q := st in\n  if (tout =? 1) then\n    mk md 0 (adv_qidx qb) qe q\n  else\n    if (1 <? tout) then\n      mk md (tout - 1) qb qe q\n    else st.\n\nLemma wf_reduce_timeout\n      st\n      (WF_ST: wf st)\n  : wf (reduce_timeout st).\nProof.\n  inv WF_ST.\n  unfold reduce_timeout.\n  desf.\n  - econs; eauto.\n    + range_stac.\n    + apply range_adv_qidx.\n  - econs; eauto.\n    destruct (Z.ltb_spec 1 tout); ss.\n    range_stac.\nQed.\n\n\nFixpoint update_queue_loop (inb: list bytes?)\n         (id_devs: list Z)\n         (st: CtrlState.t)\n  : CtrlState.t :=\n  match id_devs with\n  | [] => st\n  | id_dev :: id_devs' =>\n    let devmsg: bytes? := nth (Z.to_nat id_dev) inb None in\n    let st' := apply_devmsg st id_dev devmsg in\n    update_queue_loop inb id_devs' st'\n  end.\n\nLemma wf_update_queue_loop\n      inb id_devs st\n      (WF_ST: wf st)\n      (RANGE_ID_DEVS: Forall IntRange.sintz8 id_devs)\n  : wf (update_queue_loop inb id_devs st).\nProof.\n  revert st WF_ST.\n  induction RANGE_ID_DEVS.\n  - i. ss.\n  - i. ss.\n    eapply IHRANGE_ID_DEVS.\n    apply wf_apply_devmsg; eauto.\nQed.\n\n\nDefinition update_queue (st: CtrlState.t) (inb: list bytes?)\n  : CtrlState.t :=\n  let st' := update_queue_loop inb [3; 4; 5] st in\n  reduce_timeout st'.\n\nLemma wf_update_queue\n      st inb\n      (WF_ST: wf st)\n  : wf (update_queue st inb).\nProof.\n  unfold update_queue.\n  apply wf_reduce_timeout.\n  apply wf_update_queue_loop; eauto.\n  do 3 (econs; ss).\nQed.\n\nDefinition update_istate (tid: Z)\n           (st: CtrlState.t) (inb: list bytes?)\n  : CtrlState.t :=\n  let st1 := sync_istate tid st inb in\n  update_queue st1 inb.\n\nLemma wf_update_istate\n      tid st inb\n      (WF_ST: wf st)\n  : wf (update_istate tid st inb).\nProof.\n  apply wf_update_queue.\n  apply wf_sync_istate. ss.\nQed.\n\nDefinition update_owner (st: CtrlState.t)\n  : CtrlState.t * Z :=\n  let 'mk md tout qb qe q := st in\n  let qhd := get_queue (qrange_sanitize qb) q in\n\n  if andb (tout =? 0) (negb (qb =? qe)) then\n    let st' := mk md MAX_TIMEOUT qb qe q in\n    let tid_gr: Z :=\n        match md with\n        | Active => qhd\n        | _ => Z_mone\n        end\n    in\n    (st', tid_gr)\n  else (st, Z_mone).\n(* match md with *)\n(* | Active => *)\n(*   if andb (tout =? 0) (* (0 <? qhd) *) (negb (qb =? qe)) then *)\n(*     (mk md MAX_TIMEOUT qb qe q, qhd) *)\n(*   else (st, Z_mone) *)\n(* | _ => (st, Z_mone) *)\n(* end. *)\n\nLemma wf_update_owner\n      st st' retz\n      (WF_ST: wf st)\n      (UPD_OWNER: update_owner st = (st', retz))\n  : <<WF_ST': wf st'>> /\\\n    <<RANGE_RETZ: IntRange.sintz8 retz>>.\nProof.\n  unfold update_owner in *.\n  inv WF_ST.\n\n  desf.\n  splits.\n  - econs; ss.\n  - apply range_get_queue. ss.\nQed.\n\n\nDefinition send_hb_itree (st: CtrlState.t) (tid: Z)\n  : itree appE unit :=\n  trigger (AbstSendEvent (Z.to_nat (3 - tid))\n                         (CtrlState.to_bytes st)).\n\nDefinition job_controller_itree\n           (tid: Z) (st: CtrlState.t)\n           (sytm: Z) (inb: list bytes?)\n  : itree appE CtrlState.t :=\n  let st1 := update_istate tid st inb in\n  let (st2, tid_owner) := update_owner st1 in\n\n  (if check_dev_id tid_owner then\n     trigger (AbstSendEvent (Z.to_nat tid_owner) grant_msg)\n   else Ret tt) ;;\n  send_hb_itree st2 tid ;;\n  (* trigger (WriteLog (CtrlState.mode_to_Z (CtrlState.mode st2))) ;; *)\n  Ret st2.\n\n\nDefinition ctrl_job (tid: Z) (sytm: Z)\n           (inb: list bytes?) (st: CtrlState.t)\n  : itree (obsE +' bsendE) CtrlState.t :=\n  job_controller_itree tid st sytm inb.\n\nDefinition ctrl_mod (tid: Z): @AppMod.t obsE bytes :=\n  {| AppMod.abst_state_t := CtrlState.t ;\n     AppMod.job_itree := ctrl_job tid ;\n     AppMod.init_abst_state := CtrlState.init |}.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/apps/active_standby/app_verif/SpecController.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.1874199174714427}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Logic.Eqdep_dec\n        Fiat.Computation\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.Sequence\n        Fiat.Narcissus.BaseFormats\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad.\n\nRequire Import\n        Coq.Vectors.Vector\n        Coq.ZArith.ZArith\n        Bedrock.Word.\n\nSection AlignWord.\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  Variable addD_addD_plus :\n    forall cd n m, addD (addD cd n) m = addD cd (n + m).\n\n  Lemma If_Opt_Then_Else_DecodeBindOpt {A ResultT ResultT'}\n    : forall (a_opt : option A)\n             (t : A -> option (ResultT * B * CacheDecode))\n             (e : option (ResultT * B * CacheDecode))\n             (k : _ -> _ -> _ -> option (ResultT' * B * CacheDecode)),\n      (`(w, b', cd') <- Ifopt a_opt as a Then t a Else e;\n         k w b' cd') =\n      (Ifopt a_opt as a Then\n                        (`(w, b', cd') <- t a; k w b' cd')\n                        Else (`(w, b', cd') <- e; k w b' cd')).\n  Proof.\n    destruct a_opt; simpl; intros; reflexivity.\n  Qed.\n\n  Fixpoint split1' (sz sz' : nat) : word (sz + sz') -> word sz :=\n    match sz return word (sz + sz') -> word sz with\n    | 0 => fun _ => WO\n    | S n' => fun w => SW_word (word_split_hd w)\n                               (split1' n' sz' (word_split_tl w))\n    end.\n\n  Fixpoint split2' (sz sz' : nat) : word (sz + sz') -> word sz' :=\n    match sz return word (sz + sz') -> word sz' with\n    | 0 => fun w => w\n    | S n' => fun w => split2' n' sz' (word_split_tl w)\n    end.\n\n  Definition trans_S_comm : forall n m : nat, S (n + m) = n + S m.\n  Proof.\n    fix trans_S_comm 1. destruct n.\n    - intro; reflexivity.\n    - simpl; intro; destruct (trans_S_comm n m); reflexivity.\n  Defined.\n\n  Lemma trans_plus_comm : forall n m, n + m = m + n.\n  Proof.\n    fix rec_n 1.\n    destruct n.\n    - fix rec_m 1.\n      destruct m.\n      + reflexivity.\n      + simpl.\n        destruct (rec_m m); reflexivity.\n    - simpl; intro; rewrite (rec_n n m).\n      apply trans_S_comm.\n  Defined.\n\n  Lemma wtl_eq_rect_S : forall sz sz' w eq_comm eq_comm',\n      wtl (eq_rect (S sz) word w (S sz') eq_comm) =\n      eq_rect sz word (wtl w) sz' eq_comm'.\n  Proof.\n    intros.\n    destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear.\n    revert w' eq_comm.\n    rewrite eq_comm'; clear eq_comm'; intros.\n    unfold eq_rect; simpl.\n    revert w'.\n    pattern eq_comm.\n    apply K_dec_set; eauto; decide equality.\n  Qed.\n\n  Lemma wtl_eq_rect_comm : forall sz sz' w eq_comm eq_comm',\n      wtl (eq_rect (S (sz + sz')) word w (S (sz' + sz)) eq_comm) =\n      eq_rect (sz + sz') word (wtl w) (sz' + sz) eq_comm'.\n  Proof.\n    intros.\n    eapply wtl_eq_rect_S.\n  Qed.\n\n  Lemma whd_eq_rect_comm : forall sz sz' w eq_comm,\n      whd (eq_rect (S (sz + sz')) word w (S (sz' + sz)) eq_comm) =\n      whd w.\n  Proof.\n    intros ? ?; rewrite trans_plus_comm; intros.\n    destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear.\n    unfold eq_rect; simpl.\n    pattern eq_comm.\n    apply K_dec_set; eauto; decide equality.\n  Qed.\n\n  Lemma eq_rect_WS : forall b sz sz' w e e',\n      eq_rect (S sz) _ (WS b w) (S sz') e = WS b (eq_rect sz _ w sz' e').\n  Proof.\n    simpl; intros.\n    revert e w.\n    rewrite e'; intro; pattern e.\n    apply K_dec_set; eauto; decide equality.\n  Qed.\n\n  Lemma eq_rect_split_tl\n    : forall (sz sz' : nat) (x0 : bool) (w'' : word (sz' + sz)) (e : sz' + sz = sz + sz') (e1 : sz + sz' = sz' + sz),\n      word_split_tl (WS x0 w'') =\n      eq_rect (sz + sz') word (word_split_tl (WS x0 (eq_rect (sz' + sz) word w'' (sz + sz') e))) (sz' + sz) e1.\n  Proof.\n    induction sz; simpl.\n    - intro; rewrite <- plus_n_O; intros.\n      pattern e1.\n      apply K_dec_set; eauto; try decide equality; clear e1.\n      pattern e.\n      apply K_dec_set; eauto; try decide equality; clear e.\n    - intro; rewrite <- (trans_S_comm sz' sz); intros.\n      intros; destruct (shatter_word_S w'') as (?, (w', H)); rewrite H in *; clear H.\n      simpl.\n      rewrite (IHsz sz' x w' (trans_plus_comm _ _) (trans_plus_comm _ _)); repeat f_equal.\n      erewrite !eq_rect_WS; reflexivity.\n  Qed.\n\n  Lemma split1'_eq : forall sz sz' w,\n      split1' sz sz' w = split2 sz' sz (eq_rect _ _ w _ (trans_plus_comm _ _)).\n  Proof.\n    induction sz; simpl; intros.\n    - induction sz'; simpl.\n      + shatter_word w; reflexivity.\n      + destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear H.\n        erewrite wtl_eq_rect_comm.\n        eapply IHsz'.\n    - intros; destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear H.\n      simpl; rewrite IHsz; clear.\n      generalize (eq_ind_r (fun n : nat => S n = sz' + S sz) (trans_S_comm sz' sz) (trans_plus_comm sz sz')).\n      generalize (trans_plus_comm sz sz').\n      fold (plus sz sz').\n      revert x sz w'; induction sz'; simpl.\n      + intros ? ?; rewrite <- (plus_n_O sz); simpl.\n        intros.\n        pattern e.\n        apply K_dec_set; eauto; try decide equality.\n        pattern e0.\n        apply K_dec_set; eauto; try decide equality.\n        unfold eq_rect; simpl.\n        rewrite <- word_split_SW; reflexivity.\n      + intros ? ?.\n        rewrite <- !trans_S_comm.\n        rewrite trans_plus_comm.\n        intros; pattern e.\n        apply K_dec_set; eauto; try decide equality; clear e.\n        intros; destruct (shatter_word_S w') as (?, (w'', H)); rewrite H in *; clear H.\n        rewrite (wtl_eq_rect_S _ _ _ e0 (trans_S_comm _ _)); simpl.\n        assert (S (sz + sz') = sz' + S sz) by omega.\n        replace (eq_rect (S (sz' + sz)) word (WS x0 w'') (sz' + S sz) (trans_S_comm sz' sz)) with\n            (eq_rect (S (sz + sz')) word (WS x0 (eq_rect _ _ w'' _ (trans_plus_comm _ _))) (sz' + S sz) H).\n        erewrite <- (IHsz' x0 sz _ (trans_plus_comm _ _)).\n        repeat f_equal.\n        { generalize (trans_plus_comm sz' sz); intros; clear.\n          revert sz' x0 w'' e; induction sz; simpl.\n          - intro; rewrite <- plus_n_O; intros.\n            destruct e; reflexivity.\n          - intro; rewrite <- (trans_S_comm sz' sz); intros.\n            intros; destruct (shatter_word_S w'') as (?, (w', H)); rewrite H in *; clear H.\n            simpl.\n            rewrite (IHsz sz' x w' (trans_plus_comm _ _)); repeat f_equal.\n            erewrite eq_rect_WS; eauto.\n        }\n        { eapply eq_rect_split_tl. }\n        revert H; clear. revert w''; generalize (trans_S_comm sz' sz).\n        rewrite (trans_plus_comm sz' sz); intros; simpl.\n        destruct e; simpl.\n        rewrite eq_rect_WS with (e' := eq_refl _); reflexivity.\n  Qed.\n\n  Lemma split2'_eq : forall sz sz' w,\n      split2' sz sz' w = split1 sz' sz (eq_rect _ _ w _ (trans_plus_comm _ _)).\n  Proof.\n    induction sz; simpl; intros.\n    - induction sz'; simpl.\n      + shatter_word w; reflexivity.\n      + destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear H.\n        rewrite whd_eq_rect_comm; simpl.\n        erewrite wtl_eq_rect_comm.\n        rewrite (IHsz' w') at 1; reflexivity.\n    - intros; destruct (shatter_word_S w) as (?, (w', H)); rewrite H in *; clear H.\n      simpl; rewrite IHsz; clear.\n      generalize (eq_ind_r (fun n : nat => S n = sz' + S sz) (trans_S_comm sz' sz) (trans_plus_comm sz sz')).\n      generalize (trans_plus_comm sz sz').\n      fold (plus sz sz').\n      revert x sz w'; induction sz'; simpl; eauto.\n      intros.\n      assert (sz + S sz' = sz' + S sz) by omega.\n      rewrite eq_rect_WS with (e' := H); simpl.\n      revert w' e0 H; rewrite e; intros.\n      destruct (shatter_word_S w') as (?, (w'', H')); rewrite H' in *; clear H'; simpl.\n      f_equal.\n      assert (S (sz + sz') = sz' + S sz) by omega.\n      replace (eq_rect (S (sz' + sz)) word (WS x0 w'') (sz' + S sz) H)\n        with (eq_rect (S (sz + sz')) word (WS x0 (eq_rect _ _ w'' _ (trans_plus_comm _ _))) (sz' + S sz) H0)\n        by (revert w'' H H0; clear;\n            rewrite (trans_plus_comm sz' sz); intros; simpl;\n            destruct H; simpl;\n            erewrite eq_rect_WS with (e' := eq_refl _); reflexivity).\n      rewrite <- IHsz' with (e := trans_plus_comm _ _);\n        f_equal; simpl.\n      eapply eq_rect_split_tl.\n  Qed.\n\n  Lemma CollapseWord {ResultT}\n    : forall sz sz' (b : B)\n             (cd : CacheDecode)\n             (k : _ -> _ -> _ -> _ -> option (ResultT * B * CacheDecode)),\n      (`(w, b', cd') <- decode_word (sz:=sz) b cd;\n         `(w', b', cd') <- decode_word (sz:=sz') b' cd';\n         k w w' b' cd') =\n      (`(w , b', cd') <- decode_word (sz:=sz + sz') b cd;\n         k (split1' sz sz' w)\n           (split2' sz sz' w) b' cd').\n  Proof.\n    unfold decode_word; repeat setoid_rewrite If_Opt_Then_Else_DecodeBindOpt; simpl.\n    induction sz; simpl; intros.\n    - rewrite !If_Opt_Then_Else_DecodeBindOpt; simpl.\n      rewrite addD_addD_plus; reflexivity.\n    - destruct (dequeue_opt b) as [ [? ?] | ]; simpl; eauto.\n      pose proof (IHsz sz' b1 (addD cd 1) (fun w => k (SW_word b0 w))).\n      destruct (decode_word' sz b1) as [ [? ?] | ]; simpl in *.\n      + rewrite !If_Opt_Then_Else_DecodeBindOpt;\n          rewrite !If_Opt_Then_Else_DecodeBindOpt in H; simpl in *;\n            rewrite !addD_addD_plus in H;\n            rewrite !addD_addD_plus; simpl in *.\n        rewrite H.\n        destruct (decode_word' (sz + sz') b1) as [ [? ?] | ]; simpl; eauto.\n        repeat f_equal; clear.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w0; simpl; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; eauto.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w0; simpl; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; f_equal; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; f_equal; eauto.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w0; simpl; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; f_equal; eauto.\n          pose proof (shatter_word_S w0); destruct_ex; subst;\n            simpl; f_equal; eauto.\n      + destruct (decode_word' (sz + sz') b1) as [ [? ?] | ]; simpl in *; eauto.\n        rewrite addD_addD_plus in H; simpl in *.\n        rewrite H; repeat f_equal; clear.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w; simpl; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; eauto.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w; simpl; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; f_equal; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; f_equal; eauto.\n        * induction sz; simpl in *.\n          induction sz'; simpl in *; try shatter_word w; simpl; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; f_equal; eauto.\n          pose proof (shatter_word_S w); destruct_ex; subst;\n            simpl; f_equal; eauto.\n  Qed.\n\n  Lemma CollapseWord' {ResultT}\n    : forall sz' sz (b : B)\n             (cd : CacheDecode)\n             (k : _ -> _ -> _ -> _ -> option (ResultT * B * CacheDecode)),\n      (`(w, b', cd') <- decode_word (sz:=sz) b cd;\n         `(w', b', cd') <- decode_word (sz:=sz') b' cd';\n         k w w' b' cd') =\n      (`(w , b', cd') <- decode_word (sz:=sz + sz') b cd;\n         k (split2 sz' sz (eq_rect _ _ w _ (trans_plus_comm sz sz')))\n           (split1 sz' sz (eq_rect _ _ w _ (trans_plus_comm sz sz'))) b' cd').\n  Proof.\n    intros; rewrite CollapseWord.\n    destruct (decode_word b cd) as [ [ [? ?] ?] | ]; simpl.\n    rewrite split2'_eq, split1'_eq; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma CollapseWord'' {ResultT}\n    : forall sz' sz (b : B)\n             (cd : CacheDecode)\n             (k : _ -> _ -> _ -> _ -> option (ResultT * B * CacheDecode)),\n      (`(w, b', cd') <- decode_word (sz:=sz) b cd;\n         `(w', b', cd') <- decode_word (sz:=sz') b' cd';\n         k w w' b' cd') =\n      (`(w , b', cd') <- decode_word (sz:=sz' + sz) b cd;\n         k (split2 sz' sz w)\n           (split1 sz' sz w) b' cd').\n  Proof.\n    intros; rewrite CollapseWord'.\n    replace (decode_word (sz:=sz' + sz) b cd) with (eq_rect _ (fun n => option (word n * B * _)) (decode_word (sz:=sz + sz') b cd) _ (trans_plus_comm _ _)).\n    - destruct (decode_word b cd) as [ [ [? ?] ?] | ]; simpl.\n      + revert w; rewrite (trans_plus_comm sz sz'); simpl; eauto.\n      + rewrite (trans_plus_comm sz sz'); simpl; eauto.\n    - rewrite (trans_plus_comm sz sz'); simpl; reflexivity.\n  Qed.\n\n  Lemma CollapseEnumWord {ResultT}\n    : forall sz' sz n (b : B) (tb : Vector.t (word sz) (S n))\n             (cd : CacheDecode)\n             (k : _ -> _ -> _ -> _ -> option (ResultT * B * CacheDecode)),\n      (`(w, b', cd') <- decode_enum (sz:=sz) tb b cd;\n         `(w', b', cd') <- decode_word (sz:=sz') b' cd';\n         k w w' b' cd') =\n      (`(w , b', cd') <- decode_word (sz:=sz' + sz) b cd;\n         Ifopt (word_indexed (split2 sz' sz w) tb) as idx Then\n                                                          k idx\n                                                          (split1 sz' sz w) b' cd'\n                                                          Else None).\n  Proof.\n    intros.\n    unfold decode_enum.\n    rewrite <- CollapseWord'' with\n        (b0 := b)\n        (cd0 := cd)\n        (k0 := fun w1 w2 b cd =>\n                Ifopt (word_indexed w1 tb) as idx Then k idx w2 b cd Else None).\n    unfold decode_word; repeat setoid_rewrite If_Opt_Then_Else_DecodeBindOpt; simpl.\n    destruct (decode_word' sz b) as [ [? ?] | ] eqn: ?; simpl; eauto.\n    destruct (word_indexed w tb) as [ ? | ] eqn: ?; simpl; eauto.\n    destruct (decode_word' sz' b0) as [ [? ?] | ] eqn: ?; simpl; eauto.\n  Qed.\n\n  Variable addE_addE_plus :\n    forall (ce : CacheFormat) (n m : nat), addE (addE ce n) m = addE ce (n + m).\n\n  Lemma format_word_S {n}\n    : forall (w : word (S n)) (bs : B),\n      encode_word' (S n) w bs =\n      encode_word' n (word_split_tl w) (enqueue_opt (word_split_hd w) bs).\n  Proof.\n    intros; pose proof (shatter_word_S w); destruct_ex; subst.\n    simpl.\n    clear; revert x; induction x0; simpl; intros.\n    - simpl; reflexivity.\n    - rewrite IHx0.\n      reflexivity.\n  Qed.\n\n  Lemma word_split_hd_SW_word {n}\n    : forall b (w : word n),\n      word_split_hd (SW_word b w) = b.\n  Proof.\n    induction w; simpl; intros; eauto.\n  Qed.\n\n  Lemma word_split_tl_SW_word {n}\n    : forall b (w : word n),\n      word_split_tl (SW_word b w) = w.\n  Proof.\n    induction w; simpl; intros; eauto.\n    f_equal; eauto.\n  Qed.\n\n  Lemma CollapseFormatWord\n    : forall {sz sz'} (w : word sz) (w' : word sz') k ce,\n      refine (((format_word w)\n                 ThenC (format_word w')\n                 ThenC k) ce)\n             (((format_word (combine w' w))\n                 ThenC k) ce).\n  Proof.\n    intros; unfold compose, format_word, Bind2.\n    autorewrite with monad laws.\n    simpl; rewrite addE_addE_plus.\n    rewrite Plus.plus_comm; f_equiv; intro.\n    rewrite mappend_assoc.\n    destruct a; simpl.\n    f_equiv; f_equiv; f_equiv.\n    revert sz' w'; induction w; simpl; intros.\n    - rewrite mempty_left.\n      generalize mempty; clear; induction w'; intros.\n      + reflexivity.\n      + simpl; rewrite IHw'; reflexivity.\n    - rewrite !enqueue_opt_format_word.\n      replace (encode_word' (sz' + S n) (combine w' (WS b0 w)) mempty)\n        with (encode_word' (S sz' + n) (combine (SW_word b0 w') w) mempty).\n      + rewrite <- IHw.\n        simpl; rewrite format_word_S.\n        rewrite <- mappend_assoc, word_split_tl_SW_word, word_split_hd_SW_word.\n        f_equal.\n        clear; induction w'.\n        * simpl; rewrite mempty_right; reflexivity.\n        * simpl; rewrite !enqueue_opt_format_word.\n          rewrite <- IHw'.\n          rewrite mappend_assoc; reflexivity.\n      + clear; revert n w; induction w'; intros.\n        * simpl; eauto.\n        * simpl; rewrite <- IHw'; reflexivity.\n  Qed.\n\n  Lemma CollapseFormatWord'\n    : forall {sz sz'} (w : word sz) (w' : word sz') k ce,\n      refine (((format_word (combine w' w))\n                 ThenC k) ce)\n             (((format_word w)\n                 ThenC (format_word w')\n                 ThenC k) ce).\n  Proof.\n    intros; unfold compose, format_word, Bind2.\n    autorewrite with monad laws.\n    simpl; rewrite addE_addE_plus.\n    f_equiv.\n    clear; rewrite Plus.plus_comm; reflexivity.\n    intro; rewrite mappend_assoc.\n    destruct a; simpl.\n    f_equiv; f_equiv; f_equiv.\n    revert sz' w'; induction w; simpl; intros.\n    - rewrite mempty_left.\n      generalize mempty; clear; induction w'; intros.\n      + reflexivity.\n      + simpl; rewrite IHw'; reflexivity.\n    - rewrite !enqueue_opt_format_word.\n      replace (encode_word' (sz' + S n) (combine w' (WS b0 w)) mempty)\n        with (encode_word' (S sz' + n) (combine (SW_word b0 w') w) mempty).\n      + rewrite IHw.\n        simpl; rewrite format_word_S.\n        rewrite <- mappend_assoc, word_split_tl_SW_word, word_split_hd_SW_word.\n        f_equal.\n        clear; induction w'.\n        * simpl; rewrite mempty_right; reflexivity.\n        * simpl; rewrite !enqueue_opt_format_word.\n          rewrite IHw'.\n          rewrite mappend_assoc; reflexivity.\n      + clear; revert n w; induction w'; intros.\n        * simpl; eauto.\n        * simpl; rewrite <- IHw'; reflexivity.\n  Qed.\n\n  Lemma format_SW_word {n}\n    : forall b (w : word n) ce,\n      refine (format_word (SW_word b w) ce)\n             (`(bs, ce') <- format_word w (addE ce 1);\n                ret (mappend (enqueue_opt b mempty) bs, ce')).\n  Proof.\n    induction n; simpl; intros.\n    - shatter_word w; simpl.\n      unfold format_word; simpl.\n      autorewrite with monad laws.\n      simpl; rewrite addE_addE_plus; rewrite mempty_right; reflexivity.\n    - pose proof (shatter_word_S w); destruct_ex; subst.\n      simpl.\n      unfold format_word; simpl.\n      autorewrite with monad laws; simpl.\n      assert (computes_to (`(bs, ce') <- ret (encode_word' n x0 mempty, addE (addE ce 1) n);\n                           ret (mappend (enqueue_opt b mempty) bs, ce'))\n                          (mappend (enqueue_opt b mempty) (encode_word' n x0 mempty), addE (addE ce 1) n)) by repeat computes_to_econstructor.\n      pose proof (IHn b x0 ce _ H).\n      unfold format_word in H0.\n      computes_to_inv; inversion H0; subst.\n      rewrite H2.\n      rewrite enqueue_mappend_opt.\n      rewrite addE_addE_plus.\n      reflexivity.\n  Qed.\n\n  Lemma If_Opt_Then_Else_DecodeBindOpt_swap {A C ResultT : Type}\n    : forall (a_opt : option A)\n             (b : B)\n             (cd : CacheDecode)\n             (dec_c : B -> CacheDecode -> option (C * B * CacheDecode))\n             (k : A -> C -> B -> CacheDecode -> option (ResultT * B * CacheDecode)),\n      (`(a, b', cd') <- Ifopt a_opt as a Then Some (a, b, cd) Else None;\n         `(c, b', cd') <- dec_c b' cd';\n         k a c b' cd') =\n      (`(c, b', cd') <- dec_c b cd;\n         `(a, b', cd') <- Ifopt a_opt as a Then Some (a, b', cd') Else None;\n         k a c b' cd').\n  Proof.\n    destruct a_opt; simpl; intros; eauto.\n    destruct (dec_c b cd) as [ [ [? ?] ? ] | ]; reflexivity.\n  Qed.\n\n  Lemma If_Then_Else_Bind {sz} {C ResultT : Type}\n    : forall (w w' : word sz)\n             (b : B)\n             (cd : CacheDecode)\n             (dec_c : B -> CacheDecode -> option (C * B * CacheDecode))\n             (k : C -> B -> CacheDecode -> option (ResultT * B * CacheDecode)),\n      (if weq w w' then\n         `(c, b', cd') <- dec_c b cd;\n           k c b' cd'\n       else\n         None) =\n      (`(c, b', cd') <- dec_c b cd;\n         if weq w w' then\n           k c b' cd'\n         else None).\n  Proof.\n    intros; find_if_inside; eauto.\n    destruct (dec_c b cd) as [ [ [? ?] ? ] | ]; reflexivity.\n  Qed.\n\nEnd AlignWord.\n\nRequire Import Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad.\n\nSection AlignEncodeWord.\n\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n\n  Variable addD_addD_plus :\n    forall cd n m, addD (addD cd n) m = addD cd (n + m).\n\n  Lemma aligned_format_char_eq\n    : forall (w : word 8) cd,\n      refine (format_word (monoidUnit := ByteString_QueueMonoidOpt) w cd)\n             (ret (build_aligned_ByteString (Vector.cons _ w _ (Vector.nil _)), addE cd 8)).\n  Proof.\n    intros; shatter_word w; simpl.\n    unfold format_word; simpl.\n    compute.\n    intros.\n    computes_to_inv; subst.\n    match goal with\n      |- computes_to (ret ?c) ?v => replace c with v\n    end.\n    computes_to_econstructor.\n    f_equal.\n    eapply ByteString_f_equal; simpl.\n    instantiate (1 := eq_refl _).\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    unfold ByteBuffer.t; erewrite eq_rect_Vector_cons; repeat f_equal.\n    instantiate (1 := eq_refl _); reflexivity.\n    Unshelve.\n    reflexivity.\n  Qed.\n\n  Local Open Scope AlignedDecodeM_scope.\n\n  Lemma AlignedDecodeChar {C}\n        {numBytes}\n    : forall (v : ByteBuffer.t (S numBytes))\n             (t : (word 8 * ByteString * CacheDecode) -> C)\n             (e : C)\n             cd,\n      Ifopt (decode_word\n               (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8) (build_aligned_ByteString v) cd)\n      as w Then t w Else e\n         =\n         LetIn (Vector.nth v Fin.F1)\n               (fun w => t (w, build_aligned_ByteString (snd (Vector_split 1 _ v)), addD cd 8)).\n  Proof.\n    unfold LetIn; intros.\n    unfold decode_word, WordOpt.decode_word.\n    rewrite aligned_decode_char_eq; simpl.\n    f_equal.\n    pattern numBytes, v; apply Vector.caseS; simpl; intros.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedDecodeCharM\n    : DecodeMEquivAlignedDecodeM\n        (decode_word (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8))\n        (fun numBytes => GetCurrentByte).\n  Proof.\n    unfold DecodeMEquivAlignedDecodeM, BindAlignedDecodeM, DecodeBindOpt2, BindOpt; intros;\n      unfold decode_word, WordOpt.decode_word.\n    split; [ | split ]; intros.\n    - pattern numBytes_hd, v; eapply Vector.caseS; simpl; intros.\n      unfold GetCurrentByte, nth_opt; simpl.\n      destruct (Vector_nth_opt t n); simpl; eauto.\n    - destruct (decode_word' 8 b) as [ [? ?] | ] eqn: ?; simpl in H; try discriminate.\n      eapply decode_word'_lt in Heqo; unfold le_B, bin_measure in Heqo; simpl in Heqo.\n      unfold lt_B in Heqo; simpl in Heqo.\n      injections; omega.\n    - destruct v.\n      + simpl; intuition; discriminate.\n      + rewrite aligned_decode_char_eq; simpl; intuition.\n        * discriminate.\n        * unfold GetCurrentByte in H; simpl in H; discriminate.\n        * unfold GetCurrentByte; injections; simpl.\n          clear; induction n; simpl; eauto.\n        * injections.\n          replace (match numBytes (build_aligned_ByteString v) with\n                   | 0 => S n\n                   | S l => n - l\n                   end) with 1 by\n              (unfold numBytes; simpl;\n               clear; induction n; omega).\n          setoid_rewrite <- build_aligned_ByteString_append.\n          eexists (Vector.cons _ c _ (@Vector.nil _)); reflexivity.\n  Qed.\n\n  Lemma SW_word_append :\n    forall b sz (w : word sz) sz' (w' : word sz'),\n      SW_word b (Core.append_word w w')\n      = eq_rect _ word (Core.append_word w (SW_word b w')) _ (sym_eq (plus_n_Sm _ _)).\n  Proof.\n    induction w; simpl; intros.\n    - apply Eqdep_dec.eq_rect_eq_dec; auto with arith.\n    - erewrite <- !WS_eq_rect_eq.\n      rewrite IHw; reflexivity.\n  Qed.\n\n  Lemma decode_word_plus':\n    forall (n m : nat) (v : ByteString),\n      decode_word' (n + m) v =\n      (`(w, v') <- decode_word' n v;\n         `(w', v'') <- decode_word' m v';\n         Some (eq_rect _ _ (Core.append_word w' w) _ (plus_comm_transparent _ _), v'')).\n  Proof.\n    induction n.\n    - simpl; intros.\n      destruct (decode_word' m v) as [ [? ?] | ]; simpl; repeat f_equal.\n      revert w; clear.\n      induction w; simpl; eauto.\n      rewrite IHw at 1.\n      rewrite Core.succ_eq_rect; f_equal.\n      apply Eqdep_dec.UIP_dec; auto with arith.\n    - simpl; intros.\n      simpl; rewrite !DecodeBindOpt_assoc;\n        destruct (ByteString_dequeue v) as [ [? ?] | ]; try reflexivity.\n      simpl; rewrite !DecodeBindOpt_assoc.\n      rewrite IHn.\n      simpl; rewrite !DecodeBindOpt_assoc.\n      destruct (decode_word' n b0)  as [ [? ?] | ]; try reflexivity.\n      simpl; rewrite !DecodeBindOpt_assoc.\n      destruct (decode_word' m b1)  as [ [? ?] | ]; try reflexivity.\n      simpl; f_equal; f_equal; clear.\n      revert b n w; induction w0; simpl; intros.\n      + apply SW_word_eq_rect_eq.\n      + erewrite !SW_word_eq_rect_eq; simpl.\n        erewrite <- !WS_eq_rect_eq.\n        f_equal.\n        rewrite SW_word_append.\n        rewrite <- Equality.transport_pp.\n        f_equal.\n        Unshelve.\n        omega.\n        omega.\n  Qed.\n\n  Lemma AlignedDecodeBindCharM {C : Type}\n        (t : word 8 -> DecodeM (C * ByteString) ByteString)\n        (t' : word 8 -> forall {numBytes}, AlignedDecodeM C numBytes)\n    : (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_word (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8) v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- GetCurrentByte; t' b).\n  Proof.\n    intro; eapply Bind_DecodeMEquivAlignedDecodeM.\n    apply AlignedDecodeCharM.\n    intros; eapply H.\n  Qed.\n\n\n  Lemma AlignedDecodeNCharM\n        (addD_O : forall cd, addD cd 0 = cd)\n        {m}\n    : DecodeMEquivAlignedDecodeM\n        (decode_word (sz := m * 8))\n        (fun numBytes => GetCurrentBytes m).\n  Proof.\n    induction m.\n    - unfold decode_word; simpl;\n        pose proof (Return_DecodeMEquivAlignedDecodeM WO).\n      eapply DecodeMEquivAlignedDecodeM_trans; intros; try rewrite addD_O; try higher_order_reflexivity.\n      eapply H.\n    - Local Arguments decode_word' : simpl never.\n      Local Arguments plus : simpl never.\n      unfold decode_word; simpl.\n      eapply DecodeMEquivAlignedDecodeM_trans;\n        intros; try eapply AlignedDecodeMEquiv_refl.\n      + eapply AlignedDecodeBindCharM; intros.\n        eapply Bind_DecodeMEquivAlignedDecodeM.\n        eassumption.\n        intros.\n        pose proof (@Return_DecodeMEquivAlignedDecodeM); eapply H.\n      + intros; unfold mult; simpl; rewrite decode_word_plus'; simpl; fold mult;\n        simpl.\n        unfold decode_word.\n        destruct (decode_word' 8 b) as [ [? ?] | ]; simpl; eauto.\n        destruct (decode_word' (m * 8) b0) as [ [? ?] | ]; simpl; eauto.\n        rewrite addD_addD_plus; eauto.\n  Qed.\n\n  Lemma AlignedDecodeBindCharM' {A C : Type}\n        (t : word 8 -> DecodeM (C * ByteString) ByteString)\n        (t' : word 8 -> forall {numBytes}, AlignedDecodeM C numBytes)\n        decode_w\n    : (forall v cd,\n          decode_word (monoidUnit := ByteString_QueueMonoidOpt) (sz := 8) v cd\n          = decode_w v cd)\n      -> (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_w v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- GetCurrentByte; t' b)%AlignedDecodeM.\n  Proof.\n    intros; eapply Bind_DecodeMEquivAlignedDecodeM; eauto.\n    eapply DecodeMEquivAlignedDecodeM_trans; eauto.\n    apply AlignedDecodeCharM.\n    simpl. intros; eapply AlignedDecodeMEquiv_refl.\n  Qed.\n\n  Lemma decode_unused_word_plus':\n    forall (n m : nat) (v : ByteString),\n      decode_unused_word' (n + m) v =\n      (`(w, v') <- decode_unused_word' n v;\n         `(w', v'') <- decode_unused_word' m v';\n         Some ((), v'')).\n  Proof.\n    induction n.\n    - unfold plus; simpl; intros.\n      destruct (decode_unused_word' m v) as [ [? ?] | ]; simpl; repeat f_equal.\n      destruct u; eauto.\n    - simpl; intros.\n      unfold decode_unused_word' in *; simpl.\n      fold plus.\n      destruct (ByteString_dequeue v) as [ [? ?] | ]; try reflexivity.\n      simpl.\n      pose proof (IHn m b0).\n      destruct (WordOpt.monoid_dequeue_word (n + m) b0) as [ [? ?] | ];\n        simpl in *; try congruence.\n      simpl in *.\n      destruct (WordOpt.monoid_dequeue_word n b0) as [ [? ?] | ];\n        simpl in *; try congruence.\n      destruct (WordOpt.monoid_dequeue_word n b0) as [ [? ?] | ];\n        simpl in *; try congruence.\n  Qed.\n\n  Lemma aligned_decode_unused_char_eq\n        {numBytes}\n    : forall (v : Vector.t _ (S numBytes)),\n      WordOpt.decode_unused_word' (monoidUnit := ByteString_QueueMonoidOpt) 8 (build_aligned_ByteString v)\n      = Some ((), build_aligned_ByteString (Vector.tl v)).\n  Proof.\n    unfold decode_unused_word'; simpl; intros.\n    etransitivity.\n    apply f_equal with (f := fun z => If_Opt_Then_Else z _ _ ).\n    eapply DecodeBindOpt_under_bind; intros; set_evars; rewrite !DecodeBindOpt_assoc.\n    repeat (unfold H; apply DecodeBindOpt_under_bind; intros; set_evars; rewrite !DecodeBindOpt_assoc).\n    unfold H5; higher_order_reflexivity.\n    simpl.\n    pattern numBytes, v; eapply Vector.caseS; intros; simpl; clear v numBytes.\n    replace (build_aligned_ByteString t) with (ByteString_enqueue_ByteString ByteString_id (build_aligned_ByteString t)).\n    unfold Core.char in h.\n    shatter_word h.\n    pose proof (@dequeue_mappend_opt _ _ _ ByteString_QueueMonoidOpt).\n    rewrite build_aligned_ByteString_cons; simpl.\n    simpl in H7.\n    erewrite H7 with (t := x6)\n                     (b' := {| front := WS x (WS x0 (WS x1 (WS x2 (WS x3 (WS x4 (WS x5 WO))))));\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x5)\n                     (b' := {| front := WS x (WS x0 (WS x1 (WS x2 (WS x3 (WS x4 WO)))));\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x4)\n                     (b' := {| front := WS x (WS x0 (WS x1 (WS x2 (WS x3 WO))));\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x3)\n                     (b' := {| front := WS x (WS x0 (WS x1 (WS x2 WO)));\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x2)\n                     (b' := {| front := WS x (WS x0 (WS x1 WO));\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x1)\n                     (b' := {| front := WS x (WS x0 WO);\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x0)\n                     (b' := {| front := WS x WO;\n                               byteString := Vector.nil _ |}); simpl.\n    erewrite H7 with (t := x)\n                     (b' := {| front := WO;\n                               byteString := Vector.nil _ |}); simpl.\n    reflexivity.\n    unfold dequeue_opt.\n    simpl.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    compute; repeat f_equal; apply Core.le_uniqueness_proof.\n    unfold build_aligned_ByteString.\n    unfold ByteString_dequeue; simpl.\n    repeat f_equal; apply Core.le_uniqueness_proof.\n    apply (@mempty_left _ ByteStringQueueMonoid).\n  Qed.\n\n  Lemma aligned_decode_unused_char_eq'\n        {numBytes}\n    : forall (v : Vector.t _ (S numBytes)) env,\n      WordOpt.decode_unused_word (sz := 8) (monoidUnit := ByteString_QueueMonoidOpt) (build_aligned_ByteString v) env\n      = Some ((), build_aligned_ByteString (Vector.tl v), addD env 8).\n  Proof.\n    unfold decode_unused_word; simpl; intros.\n    etransitivity.\n    unfold Compose_Decode, DecodeBindOpt.\n    unfold BindOpt.\n    eapply AlignedDecodeChar.\n    pattern numBytes, v.\n    eapply Vector.caseS; simpl; intros.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedDecodeUnusedCharM\n    : DecodeMEquivAlignedDecodeM\n        (decode_unused_word (sz := 8))\n        (fun numBytes => SkipCurrentByte).\n  Proof.\n    unfold DecodeMEquivAlignedDecodeM, BindAlignedDecodeM, DecodeBindOpt2, BindOpt, Compose_Decode; intros;\n      unfold WordOpt.decode_word, Compose_Decode.\n    split; [ | split ]; intros.\n    - pattern numBytes_hd, v; eapply Vector.caseS; simpl; intros.\n      unfold SkipCurrentByte, nth_opt; simpl.\n      destruct (Vector_nth_opt t n); simpl; eauto.\n    - unfold decode_unused_word, Compose_Decode, decode_word in H.\n      destruct (decode_word' 8 b) as [ [? ?] | ] eqn: ?; simpl in H; try discriminate.\n      injections.\n      eapply decode_word'_lt in Heqo; unfold le_B, bin_measure in Heqo; simpl in Heqo.\n      unfold lt_B in Heqo; simpl in Heqo.\n      injections; omega.\n    - destruct v.\n      + simpl; intuition; discriminate.\n      + rewrite aligned_decode_unused_char_eq'; simpl; intuition.\n        * discriminate.\n        * unfold GetCurrentByte in H; simpl in H; discriminate.\n        * unfold SkipCurrentByte; injections; simpl.\n          clear; induction n; simpl; eauto.\n        * injections.\n          replace (match numBytes (build_aligned_ByteString v) with\n                   | 0 => S n\n                   | S l => n - l\n                   end) with 1 by\n              (unfold numBytes; simpl;\n               clear; induction n; omega).\n          setoid_rewrite <- build_aligned_ByteString_append.\n          eexists (Vector.cons _ h _ (@Vector.nil _)); reflexivity.\n  Qed.\n\n  Lemma AlignedDecodeNUnusedCharM\n        (addD_O : forall cd, addD cd 0 = cd)\n        {m}\n    : DecodeMEquivAlignedDecodeM\n        (decode_unused_word (sz := m * 8))\n        (fun numBytes => SkipCurrentBytes m).\n  Proof.\n    induction m.\n    - unfold decode_unused_word; simpl;\n        pose proof (@Return_DecodeMEquivAlignedDecodeM).\n      eapply DecodeMEquivAlignedDecodeM_trans; intros; try rewrite addD_O.\n      eapply H.\n      unfold Compose_Decode, DecodeBindOpt, BindOpt.\n      simpl; rewrite addD_O; reflexivity.\n      simpl; reflexivity.\n    - Local Arguments decode_word' : simpl never.\n      Local Arguments plus : simpl never.\n      unfold decode_unused_word; simpl.\n      eapply DecodeMEquivAlignedDecodeM_trans;\n        intros; try eapply AlignedDecodeMEquiv_refl.\n      (*intros; unfold mult; simpl; rewrite decode_unused_word_plus'; simpl; fold mult. *)\n      Focus 2.\n      (*2: {*)\n      {\n      instantiate (1 := fun b cd => `(w, v', cd') <- decode_unused_word (sz := 8) b cd;\n                                    `(w', v'', cd') <- decode_unused_word (sz := m * 8) v' cd';\n                                    Some ((), v'', cd')); simpl.\n      unfold decode_unused_word, Compose_Decode, DecodeBindOpt, BindOpt.\n      unfold decode_word, decode_word'; simpl in *.\n      destruct (ByteString_dequeue b) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b1) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b3) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b5) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b7) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b9) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      rewrite !DecodeBindOpt_assoc.\n      destruct (ByteString_dequeue b11) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b13) as [ [? ?] | ]; simpl in *; try discriminate; eauto.\n      destruct (ByteString_dequeue b15) as [ [? ?] | ]; simpl in *; try discriminate; eauto;\n      intros; rewrite !DecodeBindOpt_assoc.\n      simpl;  match goal with\n                |- context [DecodeBindOpt ?z] => destruct z as [ [? ?] | ] eqn: ? ;\n                                                   simpl in *; try discriminate\n              end.\n      rewrite addD_addD_plus; reflexivity.\n      eauto.\n      simpl;  match goal with\n                |- context [DecodeBindOpt ?z] => destruct z as [ [? ?] | ] eqn: ? ;\n                                                   simpl in *; try discriminate\n              end.\n      rewrite addD_addD_plus; reflexivity.\n      eauto.\n      }\n      all: idtac.\n      repeat (intros; eapply Bind_DecodeMEquivAlignedDecodeM);\n        eauto using @Return_DecodeMEquivAlignedDecodeM.\n      eapply AlignedDecodeUnusedCharM.\n  Qed.\n\n  Lemma AlignedDecodeBindUnusedCharM {C : Type}\n        (t : unit -> DecodeM (C * ByteString) ByteString)\n        (t' : unit -> forall {numBytes}, AlignedDecodeM C numBytes)\n    : (DecodeMEquivAlignedDecodeM (t ()) (@t' ()))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_unused_word (sz := 8) (monoidUnit := ByteString_QueueMonoidOpt) v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- SkipCurrentByte; @t' b numBytes)%AlignedDecodeM.\n  Proof.\n    intro; eapply Bind_DecodeMEquivAlignedDecodeM; eauto using AlignedDecodeUnusedCharM.\n    intro; destruct a; eauto.\n  Qed.\n\n  Lemma AlignedFormatChar {numBytes}\n    : forall (w : word 8) ce ce' (c : _ -> Comp _) (v : Vector.t _ numBytes),\n      refine (c (addE ce 8)) (ret (build_aligned_ByteString v, ce'))\n      -> refine (((format_word (monoidUnit := ByteString_QueueMonoidOpt) w)\n                    ThenC c) ce)\n                (ret (build_aligned_ByteString (Vector.cons _ w _ v), ce')).\n  Proof.\n    unfold compose; intros.\n    unfold Bind2.\n    setoid_rewrite aligned_format_char_eq; simplify with monad laws.\n    simpl; rewrite H; simplify with monad laws.\n\n    simpl.\n    rewrite <- build_aligned_ByteString_append.\n    reflexivity.\n  Qed.\n\n  Lemma AlignedDecode2Char {C}\n        {numBytes}\n    : forall (v : ByteBuffer.t (S (S numBytes)))\n             (t : (word 16 * ByteString * CacheDecode) -> C)\n             (e : C)\n             cd,\n      (Ifopt (decode_word\n                (monoidUnit := ByteString_QueueMonoidOpt) (sz := 16) (build_aligned_ByteString v) cd) as w\n                                                                                                           Then t w\n                                                                                                           Else e)\n      = Let n := Core.append_word (Vector.nth v (Fin.FS Fin.F1)) (Vector.nth v Fin.F1) in\n        t (n, build_aligned_ByteString (snd (Vector_split 2 _ v)), addD cd 16).\n  Proof.\n    unfold LetIn; intros.\n    unfold decode_word, WordOpt.decode_word.\n    match goal with\n      |- context[Ifopt ?Z as _ Then _ Else _] => replace Z with\n        (let (v', v'') := Vector_split 2 numBytes v in Some (VectorByteToWord v', build_aligned_ByteString v'')) by (symmetry; apply (@aligned_decode_char_eq' _ 1 v))\n    end.\n    unfold Vector_split, If_Opt_Then_Else, If_Opt_Then_Else.\n    f_equal.\n    rewrite !Vector_nth_tl, !Vector_nth_hd.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    f_equal.\n    erewrite VectorByteToWord_cons.\n    rewrite <- !Eqdep_dec.eq_rect_eq_dec; eauto using Peano_dec.eq_nat_dec.\n    Unshelve.\n    omega.\n    omega.\n  Qed.\n\n  Lemma decode_word_aligned_ByteString_overflow\n        {sz'}\n    : forall (b : t (word 8) sz')\n             {sz : nat}\n             (cd : CacheDecode),\n      lt sz' sz\n      -> decode_word (sz := 8 * sz) (build_aligned_ByteString b) cd = None.\n  Proof.\n    induction b; intros.\n    - unfold build_aligned_ByteString; simpl.\n      inversion H; subst; reflexivity.\n    - destruct sz; try omega.\n      apply lt_S_n in H.\n      pose proof (IHb _ cd H).\n      unfold decode_word, WordOpt.decode_word.\n      rewrite <- mult_n_Sm, plus_comm.\n      rewrite decode_word_plus'.\n      rewrite (@aligned_decode_char_eq' _ 0).\n      simpl.\n      unfold build_aligned_ByteString, decode_word in *.\n      simpl in H0.\n      first [destruct (decode_word' (sz + (sz + (sz + (sz + (sz + (sz + (sz + (sz + 0))))))))\n                                    {|\n                                      padding := 0;\n                                      front := WO;\n                                      paddingOK := build_aligned_ByteString_subproof (*n b *);\n                                      numBytes := n;\n                                      byteString := b |}) as [ [? ?] | ]\n            | destruct (decode_word' (sz + (sz + (sz + (sz + (sz + (sz + (sz + (sz + 0))))))))\n                                     {|\n                                       padding := 0;\n                                       front := WO;\n                                       paddingOK := build_aligned_ByteString_subproof n b;\n                                       numBytes := n;\n                                       byteString := b |}) as [ [? ?] | ]]\n      ; simpl in *; try congruence.\n  Qed.\n\n  Lemma AlignedDecodeBind2CharM {C : Type}\n        (t : word 16 -> DecodeM (C * ByteString) ByteString)\n        (t' : word 16 -> forall {numBytes}, AlignedDecodeM C numBytes)\n    : (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n           (fun v cd => `(a, b0, cd') <- decode_word (monoidUnit := ByteString_QueueMonoidOpt) (sz := 16) v cd;\n                          t a b0 cd')\n           (fun numBytes => b <- GetCurrentByte; b' <- GetCurrentByte; w <- return (Core.append_word b' b); t' w).\n  Proof.\n    intros; eapply DecodeMEquivAlignedDecodeM_trans with\n                (bit_decoder1 :=\n                   (fun (v : ByteString) (cd : CacheDecode) => `(w1, bs, cd') <-  decode_word (sz := 8) v cd;\n                                                               `(w2, bs, cd') <-  decode_word (sz := 8) bs cd';\n                                                               t (Core.append_word w2 w1) bs cd')).\n    eapply AlignedDecodeBindCharM; intros.\n    eapply AlignedDecodeBindCharM; intros.\n    eapply DecodeMEquivAlignedDecodeM_trans.\n    eapply (H _).\n    intros; reflexivity.\n    intros; higher_order_reflexivity.\n    intros.\n    unfold decode_word.\n    rewrite (decode_word_plus' 8 8).\n    unfold DecodeBindOpt2, DecodeBindOpt, BindOpt, If_Opt_Then_Else.\n    destruct (decode_word' 8 b) as [ [? ?] | ]; eauto.\n    destruct (decode_word' 8 b0) as [ [? ?] | ]; eauto.\n    rewrite <- eq_rect_eq_dec; eauto using eq_nat_dec.\n    rewrite addD_addD_plus; reflexivity.\n    intros; reflexivity.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatChar_f\n        {S} (proj : S -> word 8)\n    : CorrectAlignedEncoder\n        (Projection_Format format_word proj)\n        (fun sz v idx s => SetCurrentByte v idx (proj s)).\n  Proof.\n    intros.\n    unfold CorrectAlignedEncoder. eexists (Compose_Encode  (fun c env => Some ((build_aligned_ByteString (cons (word 8) c 0 (nil (word 8))), addE env 8))) (fun s => Some (proj s))); split; [ | split].\n    - unfold Compose_Encode, Projection_Format, Compose_Format; intros.\n      split; intros.\n      + setoid_rewrite aligned_format_char_eq.\n        injections.\n        intros ? ?; apply unfold_computes; eexists; intuition eauto.\n      + simpl in H; discriminate.\n    - unfold Compose_Encode; simpl; intros.\n      injections; reflexivity.\n    - unfold Compose_Encode, EncodeMEquivAlignedEncodeM; intros; injections; intuition; simpl.\n      + injections; simpl; unfold SetCurrentByte.\n        unfold plus; fold plus.\n        destruct (Nat.ltb idx (idx + Datatypes.S m)) eqn: ? ; try omega.\n        * eexists (Vector.append v1 (Vector.cons _ (proj s) _ v2)); split.\n          { repeat f_equal; try omega.\n            clear; simpl in v.\n            revert v v2; induction v1; intros.\n            - replace v with (Vector.cons _ (Vector.hd v) _ (Vector.tl v)).\n              + generalize (Vector.tl v); apply Vector.case0; reflexivity.\n              + revert v; generalize 0; apply Vector.caseS; simpl;\n                  intros; reflexivity.\n            - simpl; rewrite IHv1; reflexivity.\n          }\n          { rewrite !ByteString_enqueue_ByteString_assoc.\n            rewrite <- !build_aligned_ByteString_append.\n            assert (idx + 1 + m = idx + Datatypes.S m) by omega.\n            pose proof (Vector_append_assoc _ _ _ H v1 (Vector.cons (word 8) (proj s) 0 (Vector.nil (word 8))) v2).\n            simpl in H1; unfold Core.char in *;             unfold plus in *; fold plus in *; rewrite H1.\n            generalize (append (append v1 (Vector.cons (word 8) (proj s) 0 (Vector.nil (word 8)))) v2).\n            rewrite H; reflexivity.\n          }\n        * destruct (le_lt_dec (idx + Datatypes.S m) idx); try omega.\n          apply Nat.ltb_lt in l; congruence.\n      + injections; simpl; unfold SetCurrentByte.\n        destruct (Nat.ltb idx numBytes') eqn: ?; eauto.\n        apply Nat.ltb_lt in Heqb.\n        unfold build_aligned_ByteString in H0.\n        unfold length_ByteString in H0; simpl padding in H0; simpl numBytes in H0.\n        omega.\n      + injections; simpl in *; omega.\n      + discriminate.\n  Defined.\n\n  Lemma CorrectAlignedEncoderForFormatChar\n    : CorrectAlignedEncoder\n        (format_word (monoidUnit := ByteString_QueueMonoidOpt))\n        (@SetCurrentByte _ _).\n  Proof.\n    replace (@SetCurrentByte _ _)\n      with (fun (sz : nat) v idx s => SetCurrentByte (n := sz) v idx (id s)).\n    eapply refine_CorrectAlignedEncoder.\n    2: eapply (CorrectAlignedEncoderForFormatChar_f id).\n    split; intros.\n    + unfold Projection_Format, Compose_Format.\n      intros v Comp_v; rewrite unfold_computes in Comp_v; destruct_ex; intuition.\n      subst; eauto.\n    + intro; apply (H v).\n      unfold Projection_Format, Compose_Format in *.\n      rewrite unfold_computes; eexists.\n      subst; eauto.\n    + eapply functional_extensionality_dep; intros.\n      repeat (eapply functional_extensionality; intros).\n      reflexivity.\n  Defined.\n\n  Lemma CorrectAlignedEncoderForFormatUnusedWord\n        {S}\n    : CorrectAlignedEncoder\n        (format_unused_word 8 (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun sz v idx (s : S) => SetCurrentByte v idx (wzero 8)).\n  Proof.\n    intros; eapply refine_CorrectAlignedEncoder;\n      eauto using (CorrectAlignedEncoderForFormatChar_f (fun _ => wzero 8)).\n    simpl; split; intros.\n    + unfold format_unused_word, Projection_Format, Compose_Format; simpl.\n      intros ? ?.\n      rewrite unfold_computes in *.\n      destruct_ex; split_and; subst.\n      eexists; split; eauto.\n      rewrite unfold_computes; eauto.\n    + unfold format_unused_word, Projection_Format, Compose_Format; simpl.\n      intros ?.\n      eapply (H _).\n      unfold format_unused_word, Projection_Format, Compose_Format; simpl.\n      destruct_ex; split_and; subst.\n      rewrite unfold_computes; eauto.\n      eexists _; split; eauto.\n      unfold format_word; eauto.\n  Defined.\n\n  Lemma CorrectAlignedEncoderForProjection_Format\n        {S S'}\n        (f : S -> S')\n        (format : FormatM S' ByteString)\n        (encoder : forall n, AlignedEncodeM n)\n    :\n      CorrectAlignedEncoder format encoder\n      -> CorrectAlignedEncoder (Projection_Format format f)\n                            (fun sz v idx (s : S) => encoder sz v idx (f s)).\n  Proof.\n    intros; eapply refine_CorrectAlignedEncoder.\n    split; intros.\n    - rewrite refine_Projection_Format at 1. higher_order_reflexivity.\n    - intro.\n      eapply H.\n      apply refine_Projection_Format in H0. eauto.\n    - destruct X; intuition.\n      eexists (fun s env => x (f s) env); intuition eauto.\n      eapply H; eauto.\n      eapply H; eauto.\n      unfold EncodeMEquivAlignedEncodeM in *; intros.\n      specialize (H2 env (f s) idx); intuition eauto.\n  Defined.\n\n  Lemma CollapseCorrectAlignedEncoderFormatWord\n        {S : Type}\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n    : forall {sz sz'} (f : S ->  word sz) (f' : S -> word sz') k encoder,\n      CorrectAlignedEncoder\n        (Projection_Format format_word (fun s => combine (f' s) (f s))\n                           ++ k)\n        encoder\n      -> CorrectAlignedEncoder\n           (Projection_Format format_word f\n                              ++ Projection_Format format_word f'\n                              ++ k)\n           encoder.\n  Proof.\n    intros; eapply refine_CorrectAlignedEncoder; eauto.\n    intros.\n    rewrite !refine_sequence_Format.\n    unfold compose, Bind2.\n    rewrite !refine_Projection_Format.\n    pose proof CollapseFormatWord.\n    unfold compose, Bind2 in H.\n    rewrite <- H; eauto.\n    split.\n    - f_equiv; intro.\n      rewrite !refine_sequence_Format.\n      simpl.\n      unfold compose, Bind2.\n      simplify with monad laws.\n      rewrite !refine_Projection_Format.\n      setoid_rewrite refineEquiv_bind_bind.\n      f_equiv; intro.\n      setoid_rewrite refineEquiv_bind_bind.\n      f_equiv; intro.\n      setoid_rewrite refineEquiv_bind_unit.\n      reflexivity.\n    - intros.\n      intro.\n      simpl.\n      apply refine_sequence_Format in H1.\n      unfold compose, Bind2 in H1.\n      computes_to_inv.\n      apply refine_Projection_Format in H1.\n      apply refine_sequence_Format in H1'.\n      unfold compose, Bind2 in H1'.\n      unfold format_word in *.\n      computes_to_inv; subst.\n      apply refine_Projection_Format in H1'.\n      computes_to_inv; subst.\n      simpl in *.\n      eapply H0.\n      unfold sequence_Format, compose, Bind2.\n      computes_to_econstructor.\n      apply refine_Projection_Format.\n      eauto.\n      computes_to_econstructor; eauto.\n      simpl.\n      rewrite addE_addE_plus in H1''0;\n      rewrite plus_comm; eauto.\n  Defined.\n\n  Lemma CollapseCorrectAlignedEncoderFormatWord'\n        {S : Type}\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n    : forall {sz sz'} (f : S ->  word sz) (f' : S -> word sz') k encoder,\n      CorrectAlignedEncoder\n        (Projection_Format format_word f\n                           ++ Projection_Format format_word f'\n                           ++ k)\n        encoder\n      -> CorrectAlignedEncoder\n           (Projection_Format format_word (fun s => combine (f' s) (f s))\n                              ++ k)\n           encoder.\n  Proof.\n    intros; eapply refine_CorrectAlignedEncoder; eauto.\n    intros.\n    rewrite !refine_sequence_Format.\n    unfold compose, Bind2.\n    rewrite !refine_Projection_Format.\n    pose proof CollapseFormatWord'.\n    unfold compose, Bind2 in H.\n    rewrite H; eauto.\n    split.\n    - f_equiv; intro.\n      rewrite !refine_sequence_Format.\n      simpl.\n      unfold compose, Bind2.\n      simplify with monad laws.\n      rewrite !refine_Projection_Format.\n      setoid_rewrite refineEquiv_bind_bind.\n      f_equiv; intro.\n      setoid_rewrite refineEquiv_bind_bind.\n      f_equiv; intro.\n      setoid_rewrite refineEquiv_bind_unit.\n      reflexivity.\n    - intros.\n      intro.\n      simpl.\n      apply refine_sequence_Format in H1.\n      unfold compose, Bind2 in H1.\n      computes_to_inv.\n      apply refine_Projection_Format in H1.\n      unfold format_word in *.\n      computes_to_inv; subst.\n      simpl in *.\n      eapply H0.\n      unfold sequence_Format, compose, Bind2.\n      computes_to_econstructor.\n      apply refine_Projection_Format.\n      eauto.\n      computes_to_econstructor; eauto.\n      simpl.\n      computes_to_econstructor; eauto.\n      apply refine_Projection_Format.\n      eauto.\n      computes_to_econstructor; eauto.\n      simpl.\n      rewrite addE_addE_plus;\n      rewrite plus_comm; eauto.\n  Defined.\n\n  Lemma refine_CollapseFormatWord\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n    : forall {sz sz'} (w : word sz) (w' : word sz') format_1 format_2 ce,\n      refine (format_1 ce) (format_word w ce)\n      -> (forall ce, refine (format_2 ce) (format_word w' ce))\n      -> refine ((format_1\n                    ThenC format_2) ce)\n                ((format_word (combine w' w)) ce).\n  Proof.\n    intros.\n    etransitivity.\n    instantiate (1 := ((format_word (combine w' w)) ThenC (fun ce => ret (ByteString_id, ce))) ce).\n    rewrite <- CollapseFormatWord; eauto.\n    unfold compose, Bind2; intros.\n    rewrite H; setoid_rewrite H0; setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit.\n    simpl.\n    pose proof mempty_right; simpl in *; rewrite H1; reflexivity.\n    unfold compose, Bind2; intros; eauto.\n    repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    pose proof mempty_right; simpl in *; rewrite H1; reflexivity.\n  Qed.\n\n  Lemma refine_CollapseFormatWord'\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n        {S}\n    : forall {sz sz'} (f : S -> word sz) (f' : S -> word sz')\n             (format_1 format_2 : FormatM S _),\n      (forall s env, refine (format_1 s env) (Projection_Format format_word f s env))\n      -> (forall s env, refine (format_2 s env) (Projection_Format format_word f' s env))\n      -> (forall s env, refine ((format_1 ++ format_2) s env)\n                               (Projection_Format format_word (fun s => combine (f' s) (f s)) s env)).\n  Proof.\n    intros.\n    unfold sequence_Format, compose, Projection_Format, Compose_Format, Bind2.\n    rewrite H; setoid_rewrite H0.\n    intros ? ?.\n    rewrite unfold_computes in H1.\n    destruct_ex; intuition; subst.\n    pose proof (CollapseFormatWord (sz' := sz') (sz := sz) addE_addE_plus (f s) (f' s)\n               (fun ce => ret (ByteString_id, ce)) env); eauto.\n    unfold compose in H1.\n    unfold Bind2 in H1.\n    repeat setoid_rewrite refineEquiv_bind_unit in H1.\n    simpl in H1.\n    unfold format_word in H2.\n    pose proof mempty_right.\n    simpl in H3.\n    rewrite !H3 in H1.\n    eapply H1 in H2.\n    computes_to_inv; subst.\n    computes_to_econstructor.\n    unfold Projection_Format, Compose_Format; apply unfold_computes; eexists; intuition eauto.\n    unfold format_word; computes_to_econstructor.\n    computes_to_econstructor.\n    unfold Projection_Format, Compose_Format; apply unfold_computes; eexists; intuition eauto.\n    unfold format_word; computes_to_econstructor.\n    simpl.\n    eauto.\n  Qed.\n\n  Lemma format_words' {n m}\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n    : forall (w : word (n + m)) ce,\n      refine (format_word (monoidUnit := ByteString_QueueMonoidOpt) w ce)\n             ((format_word (monoidUnit := ByteString_QueueMonoidOpt) (split1' _ _ w)\n                           ThenC (format_word (monoidUnit := ByteString_QueueMonoidOpt) (split2' _ _ w)))\n                ce).\n  Proof.\n    induction n.\n    - unfold compose; simpl; intros.\n      unfold format_word at 2; simpl.\n      autorewrite with monad laws.\n      simpl; rewrite addE_addE_plus.\n      pose proof mempty_left as H'; simpl in H'; rewrite H'.\n      reflexivity.\n    - unfold plus; fold plus; simpl; intros.\n      rewrite (word_split_SW w) at 1.\n      rewrite format_SW_word.\n      unfold compose, Bind2.\n      rewrite (IHn (word_split_tl w) (addE ce 1)).\n      unfold compose, Bind2.\n      unfold format_word; autorewrite with monad laws.\n      simpl.\n      rewrite format_word_S.\n      pose proof mappend_assoc as H'; simpl in H'.\n      rewrite !H'.\n      rewrite !addE_addE_plus; simpl.\n      f_equiv.\n      f_equiv.\n      f_equiv.\n      rewrite !word_split_hd_SW_word, !word_split_tl_SW_word.\n      fold plus.\n      clear;\n        generalize (split1' n m (word_split_tl w))\n                   (ByteString_enqueue (word_split_hd w) ByteString_id).\n      induction w0; simpl in *.\n      + intros; pose proof (mempty_right b) as H; simpl in H; rewrite H; eauto.\n      + intros.\n        rewrite <- (IHw0 (wtl w) b0).\n        pose proof enqueue_mappend_opt as H'''; simpl in H'''.\n        rewrite <- H'''; eauto.\n      + eauto.\n  Qed.\n\n  Lemma format_words {n m}\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n    : forall (w : word (n + m)) ce,\n      refine (format_word (monoidUnit := ByteString_QueueMonoidOpt) w ce)\n             ((format_word (monoidUnit := ByteString_QueueMonoidOpt) (split2 m n (eq_rect _ _ w _ (trans_plus_comm _ _)))\n                           ThenC (format_word (monoidUnit := ByteString_QueueMonoidOpt) (split1 m n (eq_rect _ _ w _ (trans_plus_comm _ _)))))\n                ce).\n  Proof.\n    intros; rewrite format_words'.\n    rewrite split1'_eq, split2'_eq; reflexivity.\n    eauto.\n  Qed.\n\n  Lemma CorrectAlignedEncoderForFormatNChar'\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n        {sz}\n    : forall encoder,\n      (CorrectAlignedEncoder\n            (format_word (monoidUnit := ByteString_QueueMonoidOpt))\n            (fun sz => encoder sz))\n      -> CorrectAlignedEncoder\n           (format_word (monoidUnit := ByteString_QueueMonoidOpt))\n           (fun sz' => AppendAlignedEncodeM (fun v idx w => @SetCurrentByte _ _ sz' v idx (split1' 8 sz w))\n                                            (fun v idx w => encoder sz' v idx (split2' 8 sz w))).\n  Proof.\n    intros; pose proof (format_words addE_addE_plus (n := 8) (m := sz)) as H';\n      eapply refine_CorrectAlignedEncoder.\n    split.\n    - unfold flip, pointwise_relation; eapply H'.\n    - intros; intro.\n      eapply H.\n      unfold compose, format_word; computes_to_econstructor; eauto.\n      unfold compose, format_word; computes_to_econstructor; eauto.\n    - eapply refine_CorrectAlignedEncoder.\n      split; intros.\n      rewrite <- split2'_eq, <- split1'_eq.\n      3: eapply CorrectAlignedEncoderForThenC.\n      (*3: intros; eapply (@CorrectAlignedEncoderForFormatChar_f (word (8 + sz))\n        (split1' 8 sz)).*)\n      instantiate (1 := Projection_Format format_word (split2' 8 sz)).\n      rewrite refine_sequence_Format.\n      instantiate (1 := Projection_Format format_word (split1' 8 sz)).\n      unfold compose, Bind2; rewrite refine_Projection_Format; f_equiv.\n      intro; rewrite refine_Projection_Format; f_equiv.\n      2: eapply CorrectAlignedEncoderForProjection_Format; eauto.\n      + intro.\n        eapply H.\n        rewrite <- split2'_eq, <- split1'_eq in H0.\n        unfold sequence_Format.\n        unfold compose, Bind2 in *; computes_to_inv; computes_to_econstructor.\n        apply refine_Projection_Format; eauto.\n        computes_to_econstructor.\n        apply refine_Projection_Format; eauto.\n        subst; eauto.\n      + intros.\n        instantiate (1 := (@CorrectAlignedEncoderForFormatChar_f (word (8 + sz)) (split1' 8 sz))).\n        destruct (projT1 (CorrectAlignedEncoderForFormatChar_f (split1' 8 sz)) s env) eqn: ?.\n        * eexists _, _; split; eauto.\n          apply refine_Projection_Format; eauto.\n          unfold format_word; eauto.\n        * generalize (proj2 (proj1 (projT2 (CorrectAlignedEncoderForFormatChar_f (split1' 8 sz))) s env));\n            intro.\n          eapply H1 in Heqo.\n          eapply Heqo in H; intuition eauto.\n  Defined.\n\n  Fixpoint SetCurrentBytes' (* Sets the bytes at the current index and increments the current index. *)\n           {n sz : nat}\n    : @AlignedEncodeM _ (word (sz * 8)) n :=\n    match sz return @AlignedEncodeM _ (word (sz * 8)) _ with\n    | 0 => AlignedEncode_Nil n\n    | S sz' => AppendAlignedEncodeM (fun v idx w => SetCurrentByte v idx (split1' 8 (sz' * 8) w))\n                                    (fun v idx w => SetCurrentBytes' v idx (split2' 8 (sz' * 8) w))\n    end.\n\n  Fixpoint SetCurrentBytes (* This version produces better code. *)\n           {n sz : nat} {struct sz}\n    : @AlignedEncodeM _ (word (sz * 8)) n :=\n    match sz as n0 return (AlignedEncodeM n) with\n    | 0 => AlignedEncode_Nil n\n    | S sz0 =>\n      fun v idx w =>\n        match sz0 return word (S sz0 * 8) -> _ with\n        | 0 => fun (w' : word 8) => SetCurrentByte v idx w'\n        | S sz1 => fun _  => (* ignored to get proper recursive call *)\n                    AppendAlignedEncodeM\n                      (fun (v : t Core.char n) (idx : nat) (w : word (S sz0 * 8)) =>\n                         SetCurrentByte v idx (split1' 8 (sz0 * 8) w))\n                      (fun (v : t Core.char n) (idx : nat) (w : word (S sz0 * 8)) =>\n                         SetCurrentBytes v idx (split2' 8 (sz0 * 8) w))\n                      v idx w\n        end w\n    end.\n\n  Local Arguments split1' : simpl never.\n  Local Arguments split2' : simpl never.\n\n  Lemma split1'_8_0 :\n    forall w, (split1' 8 0 w) = w.\n  Proof. intros; compute in (type of w); shatter_word w; reflexivity. Qed.\n\n  Lemma SetCurrentBytes_SetCurrentBytes' :\n    forall n sz v idx w c,\n      @SetCurrentBytes n sz v idx w c =\n      @SetCurrentBytes' n sz v idx w c.\n  Proof.\n    induction sz; simpl; intros.\n    - reflexivity.\n    - destruct sz;\n        unfold AppendAlignedEncodeM, SetCurrentByte;\n        destruct (_ <? _) eqn:?; unfold If_Opt_Then_Else.\n      + unfold SetCurrentBytes', AlignedEncode_Nil, ReturnAlignedEncodeM; simpl.\n        destruct (S _ <? S _) eqn:?; rewrite ?Nat.ltb_lt, ?Nat.ltb_ge, ?split1'_8_0 in *;\n          (reflexivity || omega).\n      + reflexivity.\n      + rewrite IHsz; reflexivity.\n      + reflexivity.\n  Qed.\n\n  Corollary CorrectAlignedEncoderForFormatNChar\n            (addE_addE_plus :\n               forall ce n m, addE (addE ce n) m = addE ce (n + m))\n            (addE_0 :\n               forall ce, addE ce 0 = ce)\n            {sz}\n    : CorrectAlignedEncoder\n        (format_word (monoidUnit := ByteString_QueueMonoidOpt))\n        (fun n => @SetCurrentBytes n sz).\n  Proof.\n    eapply CorrectAlignedEncoder_morphism with (encode := (fun n => @SetCurrentBytes' n sz)).\n    apply EquivFormat_reflexive.\n    auto using SetCurrentBytes_SetCurrentBytes'.\n    unfold CorrectAlignedEncoder.\n    induction sz; simpl; intros.\n    - eapply refine_CorrectAlignedEncoder; intros.\n      shatter_word s; unfold format_word; simpl.\n      split.\n      unfold format_word; rewrite addE_0; higher_order_reflexivity.\n      intros; intro.\n      eapply H.\n      eauto.\n      + eapply CorrectAlignedEncoderForDoneC.\n    - eapply (CorrectAlignedEncoderForFormatNChar'\n                addE_addE_plus\n                (fun sz' => @SetCurrentBytes' sz' sz));\n        eauto.\n  Defined.\n\n  Lemma CorrectAlignedEncoderForFormatMChar_f n\n        {S}\n        (addE_addE_plus :\n           forall ce n m, addE (addE ce n) m = addE ce (n + m))\n        (addE_0 :\n           forall ce, addE ce 0 = ce)\n        (proj : S -> word (n * 8))\n    : CorrectAlignedEncoder\n        (Projection_Format format_word proj)\n        (fun sz v idx s => SetCurrentBytes v idx (proj s)).\n  Proof.\n    eapply CorrectAlignedEncoderForProjection_Format with\n        (format := format_word)\n        (encoder := fun sz => @SetCurrentBytes sz n)\n        (f := proj).\n    eapply CorrectAlignedEncoderForFormatNChar; eauto.\n  Defined.\n\nEnd AlignEncodeWord.\n\nLtac collapse_word addD_addD_plus :=\n  match goal with\n  | |- DecodeBindOpt2\n         (decode_word (sz := ?sz) ?b ?cd)\n         (fun w b' cd' =>\n            DecodeBindOpt2 (decode_word (sz := ?sz') b' cd')\n                           (fun w' b'' cd'' => @?k w w' b'' cd'')) = _ =>\n    etransitivity;\n    [let H := fresh in\n     pose proof (@CollapseWord'' _ _ _ _ _ addD_addD_plus _ sz' sz b cd k);\n     apply H | ]\n  end.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/BinLib/AlignWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.18741990888733023}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Csyntax.\nRequire Import Csem.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr (Zpos id) ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nFixpoint constval (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval l\n  | Eunop op r1 ty =>\n      do v1 <- constval r1;\n      match sem_unary_operation op v1 (typeof r1) with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match sem_binary_operation op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ty1)))\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      do v3 <- constval r3;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval r1; constval r2\n  | Evar x ty =>\n      OK(Vptr (Zpos x) Int.zero)\n  | Ederef r ty =>\n      constval r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id fList _ =>\n          do delta <- field_offset f fList;\n          do v <- constval l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id fList _ =>\n          constval l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r ty =>\n      do v <- constval r; do_cast v (typeof r) ty\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_compound (il: initializer_list)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint I8 sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vfloat f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr (Zpos id) ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr (Zpos id) ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  Return the corresponding list of initialization data. *)\n\nDefinition padding (frm to: Z) : list init_data :=\n  let n := to - frm in\n  if zle n 0 then nil else Init_space n :: nil.\n\nFixpoint transl_init (ty: type) (i: initializer)\n                     {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ty a; OK (d :: nil)\n  | Init_compound il, Tarray tyelt sz _ =>\n      if zle sz 0\n      then OK (Init_space(sizeof tyelt) :: nil)\n      else transl_init_array tyelt il sz\n  | Init_compound il, Tstruct _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tstruct id fl _ =>\n      transl_init_struct id ty fl il 0\n  | Init_compound il, Tunion _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tunion id (Fcons _ ty1 _) _ =>\n      transl_init_union id ty ty1 il\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ty: type) (il: initializer_list) (sz: Z)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0\n      then OK nil\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do d1 <- transl_init ty i1;\n      do d2 <- transl_init_array ty il' (sz - 1);\n      OK (d1 ++ d2)\n  end\n\nwith transl_init_struct (id: ident) (ty: type)\n                        (fl: fieldlist) (il: initializer_list) (pos: Z)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, Fnil =>\n      OK (padding pos (sizeof ty))\n  | Init_cons i1 il', Fcons _ ty1 fl' =>\n      let pos1 := align pos (alignof ty1) in\n      do d1 <- transl_init (unroll_composite id ty ty1) i1;\n      do d2 <- transl_init_struct id ty fl' il' (pos1 + sizeof ty1);\n      OK (padding pos pos1 ++ d1 ++ d2)\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end\n\nwith transl_init_union (id: ident) (ty ty1: type) (il: initializer_list)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      Error (msg \"empty union initializer\")\n  | Init_cons i1 _ =>\n      do d <- transl_init (unroll_composite id ty ty1) i1;\n      OK (d ++ padding (sizeof ty1) (sizeof ty))\n  end.\n\n\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.1873449877452955}}
{"text": "(* Checking that the \"in\" clause takes the \"eqn\" clause into account *)\n\nDefinition test (x: nat): {y: nat | False }. Admitted.\n\nParameter x: nat.\nParameter z: nat.\n\nGoal\n  proj1_sig (test x) = z ->\n  False.\nProof.\n  intro H.\n  destruct (test x) eqn:Heqs in H.\n  change (test x = exist (fun _ : nat => False) x0 f) in Heqs. (* Check it has the expected statement *)\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/7779.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.18734497311935994}}
{"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.\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) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t) (lc2:Local.t): Prop :=\n    | read_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord Ordering.acqrel else ord)\n        (STEP: Local.read_step lc1 mem1 loc to val released ord' lc2)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released'\n                         (GET: Memory.get loc to' mem1 = Some (from', Message.concrete val' released')),\n            Time.le to' to)\n    .\n    Hint Constructors read_step: 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 Ordering.acqrel else ord)\n        (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord' lc2 sc2 mem2 kind)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released'\n                         (GET: Memory.get loc to' mem1 = Some (from', Message.concrete val' released')),\n            Time.lt to' to)\n    .\n    Hint Constructors write_step: 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        msgs kinds kind\n        (LOC: L loc = false)\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 kind\n        (LOC: L loc = true)\n        (STEP: Local.write_step lc1 sc1 mem1 loc from to val None released Ordering.acqrel 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 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: OrdLocal.racy_read_step L Ordering.acqrel 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: OrdLocal.racy_write_step L Ordering.acqrel 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. esplits; eauto. }\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. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n      - inv LOCAL2. inv STEP. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n      - 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  End SCLocal.\nEnd SCLocal.\n\n\nModule SCThread.\n  Section SCThread.\n    Variable lang: language.\n    Variable L: Loc.t -> bool.\n\n    Inductive program_step (e:ThreadEvent.t): forall (e1 e2:Thread.t lang), Prop :=\n    | program_step_intro\n        st1 lc1 sc1 mem1\n        st2 lc2 sc2 mem2\n        (STATE: (Language.step lang) (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: SCLocal.program_step L e lc1 sc1 mem1 lc2 sc2 mem2):\n        program_step e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)\n    .\n    Hint Constructors program_step: 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 SCLocal.program_step_future; eauto.\n    Qed.\n\n    Lemma step_future\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_future; eauto.\n      - eapply program_step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          e1 e2\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1. induction STEPS; i.\n      - esplits; eauto; refl.\n      - inv H. inv USTEP. exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des.\n        esplits; eauto; etrans; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_future\n          e1 e2\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_future; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n    Lemma opt_step_future\n          e e1 e2\n          (STEP: opt_step e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; try refl.\n      - eapply step_future; eauto.\n    Qed.\n\n    (* disjoint *)\n\n    Lemma step_disjoint\n          pf e e1 e2 lc\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_disjoint; eauto.\n      - inv STEP0. eapply SCLocal.program_step_disjoint; eauto.\n    Qed.\n\n    Lemma rtc_all_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1 DISJOINT1 WF.\n      induction STEPS; i; eauto.\n      inv H. inv USTEP.\n      exploit step_future; eauto. i. des.\n      exploit step_disjoint; eauto. i. des.\n      eauto.\n    Qed.\n\n    Lemma rtc_tau_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_disjoint; try exact DISJOINT1; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n\n    (* promise_consistent *)\n\n    Lemma step_promise_consistent\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      inv STEP; ss.\n      - inv STEP0. s.\n        eapply promise_step_promise_consistent; eauto.\n      - inv STEP0. inv LOCAL; ss.\n        + inv LOCAL0. eapply read_step_promise_consistent; eauto.\n        + inv LOCAL0. eapply write_step_promise_consistent; eauto.\n        + inv LOCAL1. inv LOCAL2.\n          exploit Local.read_step_future; eauto. i. des.\n          eapply read_step_promise_consistent; eauto.\n          eapply write_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n        + 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  End SCThread.\nEnd SCThread.\n\n\nModule SCConfiguration.\n  Section SCConfiguration.\n    Variable L: Loc.t -> bool.\n\n    Inductive step: forall (e: ThreadEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | step_intro\n        e tid c1 lang st1 lc1 e2 e3 st4 lc4 sc4 memory4\n        (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n        (CANCELS: rtc (@Thread.cancel_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n        (STEP: SCThread.opt_step L e e2 e3)\n        (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n        (CONSISTENT: ThreadEvent.get_machine_event e <> MachineEvent.failure ->\n                     SCThread.consistent L (Thread.mk _ st4 lc4 sc4 memory4)):\n        step e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n    .\n    Hint Constructors step: 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    Lemma step_future\n          e tid c1 c2\n          (STEP: step e tid c1 c2)\n          (WF1: Configuration.wf c1):\n      (<<WF2: Configuration.wf c2>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\n    Proof.\n      inv WF1. inv WF. inv STEP; s. exploit THREADS; ss; eauto. i.\n      assert (STEPS: rtc\n                       (@SCThread.all_step _ L)\n                       (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                       (Thread.mk _ st4 lc4 sc4 memory4)).\n      { etrans.\n        { eapply rtc_implies; try apply CANCELS. i.\n          inv H. inv STEP; [|inv STEP1; inv LOCAL].\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify. }\n        etrans.\n        { instantiate (1:=e3). inv STEP0; eauto.\n          econs; [|refl]; eauto. econs; eauto. econs; eauto. }\n        { eapply rtc_implies; try apply RESERVES. i.\n          inv H. inv STEP; [|inv STEP1; inv LOCAL].\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify. }\n      }\n      exploit SCThread.rtc_all_step_future; eauto. s. i. des.\n      splits; eauto. econs; ss. econs.\n      + i. Configuration.simplify.\n        * exploit THREADS; try apply TH1; eauto. i. des.\n          exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n          symmetry. auto.\n        * exploit THREADS; try apply TH2; eauto. i. des.\n          exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n          auto.\n        * eapply DISJOINT; [|eauto|eauto]. auto.\n      + i. Configuration.simplify.\n        exploit THREADS; try apply TH; eauto. i.\n        exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n    Qed.\n\n    Lemma all_steps_future\n          c1 c2\n          (STEPS: rtc all_step c1 c2)\n          (WF1: Configuration.wf c1):\n      (<<WF2: Configuration.wf c2>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\n    Proof.\n      ginduction STEPS; eauto.\n      - i. esplits; eauto; try refl.\n      - i. inv H. exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des. esplits; eauto. etrans; eauto.\n    Qed.\n  End SCConfiguration.\nEnd SCConfiguration.\n\n\nDefinition is_accessing (e:ProgramEvent.t): option Loc.t :=\n  match e with\n  | ProgramEvent.read loc _ _ => Some loc\n  | ProgramEvent.write loc _ _ => Some loc\n  | ProgramEvent.update loc _ _ _ _ => Some loc\n  | _ => None\n  end.\n\n\n(** L-SC race **)\nModule SCRace.\n  Section SCRace.\n    Variable L: Loc.t -> bool.\n\n    Definition race lang (th: Thread.t lang): Prop :=\n      exists e st' loc,\n        (<<STEP: Language.step _ e (Thread.state th) st'>>) /\\\n        (<<ACCESS: is_accessing e = (Some loc)>>) /\\\n        (<<LOC: L loc>>) /\\\n        (<<MAXIMAL: SCLocal.non_maximal (Thread.local th) (Thread.memory th) loc>>).\n\n    Definition race_steps (c: Configuration.t) (tid: Ident.t): Prop :=\n      exists lang st1 lc1 e2,\n        (<<TID: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st1, lc1)>>) /\\\n        (<<THREAD_STEPS: rtc (SCThread.all_step L)\n                             (Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) e2>>) /\\\n        (<<CONS: Local.promise_consistent (Thread.local e2)>>) /\\\n        (<<SCRACE: race e2>>).\n\n    Definition racefree (c: Configuration.t): Prop :=\n      forall tid c2\n             (STEPS: rtc (SCConfiguration.all_step L) c c2),\n        ~ race_steps c2 tid.\n\n    Definition racefree_syn (syn: Threads.syntax): Prop :=\n      racefree (Configuration.init syn).\n\n    Lemma step_racefree\n          e tid c1 c2\n          (RACEFREE: racefree c1)\n          (STEP: SCConfiguration.step L e tid c1 c2):\n      racefree c2.\n    Proof.\n      ii. eapply RACEFREE; cycle 1; eauto.\n      econs 2; eauto. econs; eauto.\n    Qed.\n  End SCRace.\nEnd SCRace.\n", "meta": {"author": "snu-sf", "repo": "promising-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/ldrfsc/SCStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.18725026247391321}}
{"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(** Corollaries of the main semantic preservation theorem. *)\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Behaviors.\nRequire Import Csyntax.\nRequire Import Csem.\nRequire Import Cstrategy.\nRequire Import Clight.\nRequire Import Cminor.\nRequire Import RTL.\nRequire Import Asm.\nRequire Import Compiler.\nRequire Import Errors.\n\n(** * Preservation of whole-program behaviors *)\n\n(** From the simulation diagrams proved in file [Compiler]. it follows that\n  whole-program observable behaviors are preserved in the following sense.\n  First, every behavior of the generated assembly code is matched by\n  a behavior of the source C code. *)\n\nTheorem transf_c_program_preservation:\n  forall p tp beh,\n  transf_c_program p = OK tp ->\n  program_behaves (AsmBits.semantics_bits tp) beh ->\n  exists beh', program_behaves (Csem.semantics p) beh' /\\ behavior_improves beh' beh.\nProof.\n  intros. eapply backward_simulation_behavior_improves; eauto. \n  apply transf_c_program_correct; auto.\nQed.\n\n(** As a corollary, if the source C code cannot go wrong, the behavior of the\n  generated assembly code is one of the possible behaviors of the source C code. *)\n\nTheorem transf_c_program_is_refinement:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall beh, program_behaves (Csem.semantics p) beh -> not_wrong beh) ->\n  (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> program_behaves (Csem.semantics p) beh).\nProof.\n  intros. eapply backward_simulation_same_safe_behavior; eauto.\n  apply transf_c_program_correct; auto.\nQed.\n\n(** If we consider the C evaluation strategy implemented by the compiler,\n  we get stronger preservation results. *)\n\nTheorem transf_cstrategy_program_preservation:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall beh, program_behaves (Cstrategy.semantics p) beh ->\n     exists beh', program_behaves (AsmBits.semantics_bits tp) beh' /\\ behavior_improves beh beh')\n/\\(forall beh, program_behaves (AsmBits.semantics_bits tp) beh ->\n     exists beh', program_behaves (Cstrategy.semantics p) beh' /\\ behavior_improves beh' beh)\n/\\(forall beh, not_wrong beh ->\n     program_behaves (Cstrategy.semantics p) beh -> program_behaves (AsmBits.semantics_bits tp) beh)\n/\\(forall beh,\n     (forall beh', program_behaves (Cstrategy.semantics p) beh' -> not_wrong beh') ->\n     program_behaves (AsmBits.semantics_bits tp) beh ->\n     program_behaves (Cstrategy.semantics p) beh).\nProof.\n  assert (WBT: forall p, well_behaved_traces (Cstrategy.semantics p)).\n    intros. eapply ssr_well_behaved. apply Cstrategy.semantics_strongly_receptive.\n  intros. intuition.\n  eapply forward_simulation_behavior_improves; eauto. \n    apply (fst (transf_cstrategy_program_correct _ _ H)).\n  exploit backward_simulation_behavior_improves.\n    apply (snd (transf_cstrategy_program_correct _ _ H)).\n    eauto.\n  intros [beh1 [A B]]. exists beh1; split; auto. rewrite atomic_behaviors; auto.\n  eapply forward_simulation_same_safe_behavior; eauto.\n    apply (fst (transf_cstrategy_program_correct _ _ H)).\n  exploit backward_simulation_same_safe_behavior.\n    apply (snd (transf_cstrategy_program_correct _ _ H)).\n    intros. rewrite <- atomic_behaviors in H2; eauto. eauto.\n    intros. rewrite atomic_behaviors; auto. \nQed.\n\n(** We can also use the alternate big-step semantics for [Cstrategy]\n  to establish behaviors of the generated assembly code. *)\n\nTheorem bigstep_cstrategy_preservation:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall t r,\n     Cstrategy.bigstep_program_terminates p t r ->\n     program_behaves (AsmBits.semantics_bits tp) (Terminates t r))\n/\\(forall T,\n     Cstrategy.bigstep_program_diverges p T ->\n       program_behaves (AsmBits.semantics_bits tp) (Reacts T)\n    \\/ exists t, program_behaves (AsmBits.semantics_bits tp) (Diverges t) /\\ traceinf_prefix t T).\nProof.\n  intuition.\n  apply transf_cstrategy_program_preservation with p; auto. red; auto.\n  apply behavior_bigstep_terminates with (Cstrategy.bigstep_semantics p); auto.\n  apply Cstrategy.bigstep_semantics_sound.\n  exploit (behavior_bigstep_diverges (Cstrategy.bigstep_semantics_sound p)). eassumption.\n  intros [A | [t [A B]]]. \n  left. apply transf_cstrategy_program_preservation with p; auto. red; auto.\n  right; exists t; split; auto. apply transf_cstrategy_program_preservation with p; auto. red; auto.\nQed.\n\n(** * Satisfaction of specifications *)\n\n(** The second additional results shows that if all executions\n  of the source C program satisfies a given specification\n  (a predicate on the observable behavior of the program),\n  then all executions of the produced Asm program satisfy\n  this specification as well.  \n\n  We first show this result for specifications that are stable\n  under the [behavior_improves] relation. *) \n\nSection SPECS_PRESERVED.\n\nVariable spec: program_behavior -> Prop.\n\nHypothesis spec_stable:\n  forall beh1 beh2, behavior_improves beh1 beh2 -> spec beh1 -> spec beh2.\n\nTheorem transf_c_program_preserves_spec:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall beh, program_behaves (Csem.semantics p) beh -> spec beh) ->\n  (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> spec beh).\nProof.\n  intros.\n  exploit transf_c_program_preservation; eauto. intros [beh' [A B]].\n  apply spec_stable with beh'; auto. \nQed.\n\nEnd SPECS_PRESERVED.\n\n(** As a corollary, we obtain preservation of safety specifications:\n  specifications that exclude \"going wrong\" behaviors. *)\n\nSection SAFETY_PRESERVED.\n\nVariable spec: program_behavior -> Prop.\n\nHypothesis spec_safety:\n  forall beh, spec beh -> not_wrong beh.\n\nTheorem transf_c_program_preserves_safety_spec:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall beh, program_behaves (Csem.semantics p) beh -> spec beh) ->\n  (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> spec beh).\nProof.\n  intros. eapply transf_c_program_preserves_spec; eauto. \n  intros. destruct H2. congruence. destruct H2 as [t [EQ1 EQ2]]. \n  subst beh1. elim (spec_safety _ H3). \nQed.\n\nEnd SAFETY_PRESERVED.\n\n(** We also have preservation of liveness specifications:\n  specifications that assert the existence of a prefix of the observable\n  trace satisfying some conditions. *)\n\nSection LIVENESS_PRESERVED.\n\nVariable spec: trace -> Prop.\n\nDefinition liveness_spec_satisfied (b: program_behavior) : Prop :=\n  exists t, behavior_prefix t b /\\ spec t.\n\nTheorem transf_c_program_preserves_liveness_spec:\n  forall p tp,\n  transf_c_program p = OK tp ->\n  (forall beh, program_behaves (Csem.semantics p) beh -> liveness_spec_satisfied beh) ->\n  (forall beh, program_behaves (AsmBits.semantics_bits tp) beh -> liveness_spec_satisfied beh).\nProof.\n  intros. eapply transf_c_program_preserves_spec; eauto.\n  intros. destruct H3 as [t1 [A B]]. destruct H2.\n  subst. exists t1; auto.\n  destruct H2 as [t [C D]]. subst.\n  destruct A as [b1 E]. destruct D as [b2 F].\n  destruct b1; simpl in E; inv E.\n  exists t1; split; auto. \n  exists (behavior_app t0 b2); apply behavior_app_assoc. \nQed.\n\nEnd LIVENESS_PRESERVED.\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/driver/Complements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18724443636969032}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Locations.\nRequire Import Stacklayout.\nRequire Import Conventions.\nRequire Import Memory.\nRequire Import Asm.\n\nRequire Import PeekLib.\nRequire Import PeekTactics.\nRequire Import FindInstrLib.\nRequire Import PregTactics.\nRequire Import ProgPropDec.\n\nRequire Import Zlen.\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\nRequire Import PtrEquiv.\nRequire Import PtrEquivMem.\nRequire Import PtrEquivMemInit.\n\n\nDefinition instr_of_prog (i : instruction) (p : program) :=\n  exists z c,\n    code_of_prog c p /\\ find_instr z c = Some i.\n\nFixpoint lookup_global {F V : Type} (id : ident) (l : list (ident * globdef F V)) : option (globdef F V) :=\n  match l with\n    | nil => None\n    | (id',gd) :: r => if peq id id' then Some gd else lookup_global id r\n  end.\n\nDefinition global_size (id : ident) (p : program) : Z :=\n  match lookup_global id (prog_defs p) with\n    | Some (Gfun (Internal f)) => zlen (fn_code f)\n    | Some (Gfun (External e)) => 1\n    | Some (Gvar v) => Genv.init_data_list_size (gvar_init v)\n    | None => 0\n  end.\n\n\n(* Fixpoint lookup_global {F V : Type} (id : ident) (l : list (ident * globdef F V)) : option (globdef F V) := *)\n(*   match l with *)\n(*     | nil => None *)\n(*     | (id',gd) :: r => if peq id id' then Some gd else lookup_global id r *)\n(*   end. *)\n\n(* Definition global_size (id : ident) (p : program) : Z := *)\n(*   match lookup_global id (prog_defs p) with *)\n(*     | Some (Gfun (Internal f)) => zlen (fn_code f) *)\n(*     | Some (Gfun (External e)) => 0 *)\n(*     | Some (Gvar v) => Genv.init_data_list_size (gvar_init v) *)\n(*     | None => 0 *)\n(*   end. *)\n\n\n\nLemma lookup_norepet :\n  forall {F V : Type} l (id : ident) (x : globdef F V),\n    list_norepet (map fst l) ->\n    In (id,x) l ->\n    lookup_global id l = Some x.\nProof.\n  induction l; intros.\n  simpl in H0. inv H0.\n  simpl in H0. break_or.\n  simpl. destruct (peq id id); congruence.\n  simpl in H. inv H.\n  app IHl H1.\n  simpl. rewrite H1.\n  destruct a. simpl in H3.\n  eapply in_map with (f := fst) in H. simpl in H.\n  break_match; auto. subst. congruence.\nQed.\n\nFixpoint well_formed_annot_arg {A : Type} (aa : annot_arg A) (p : program) : Prop :=\n  match aa with\n    | AA_addrglobal id ofs =>\n      In id (prog_defs_names p) ->\n      0 <= Int.unsigned ofs < global_size id p\n    | AA_longofwords hi lo => well_formed_annot_arg hi p /\\ well_formed_annot_arg lo p\n    | _ => True\n  end.\n\nDefinition well_formed_addrmode (a : addrmode) (p : program) : Prop :=\n  match a with\n    | Addrmode _ _ (inr (id,ofs)) =>\n      In id (prog_defs_names p) ->\n      0 <= Int.unsigned ofs <= global_size id p\n    | _ => True\n  end.\n\nDefinition all_lea_well_formed (p : program) : Prop :=\n  forall r a,\n    instr_of_prog (Plea r a) p ->\n    well_formed_addrmode a p.\n\nDefinition all_annot_well_formed (p : program) : Prop :=\n  forall e l,\n    instr_of_prog (Pannot e l) p ->\n    forall aa,\n      In aa l -> well_formed_annot_arg aa p.\n\nDefinition is_nonempty_fun (id : ident) (p : program) : Prop :=\n  forall x,\n    In (id,x) (prog_defs p) ->\n    exists fd,\n      x = Gfun fd /\\ match fd with\n                       | Internal f => (fn_code f <> nil)\n                       | External _ => True\n                     end.\n\n\nDefinition global_nonempty (gd : globdef fundef unit) : Prop :=\n  match gd with\n    | Gvar v => Genv.init_data_list_size (gvar_init v) > 0\n    | Gfun (Internal fd) => zlen (fn_code fd) > 0\n    | Gfun (External _) => True\n  end.\n\nDefinition globals_nonempty (p : program) : Prop :=\n  forall id gd,\n    In (id,gd) (prog_defs p) -> global_nonempty gd.\n\nSection FSIM.\n\n\n  Variable p : program.\n  Definition ge := Genv.globalenv p.\n  (* All of these are well formedness hypotheses that we will carry down from higher levels *)\n  Hypothesis palloc : all_allocframes_positive p.\n  Hypothesis norep : list_norepet (prog_defs_names p).\n  Hypothesis main_fn_is_fn : is_nonempty_fun (prog_main p) p.\n  (* Hypothesis all_addrmode_wf : all_lea_well_formed p. *)\n  Hypothesis all_annot_wf : all_annot_well_formed p.\n  Hypothesis no_PC : no_PC_overflow_prog p.\n  (* Hypothesis nonempty : globals_nonempty p. *)\n  (* Hypothesis all_defs_wf : wf_defs p (prog_defs p). *)\n\n\n  \n  Definition alloc_inj (t : allocator_metadata) : Prop :=\n    forall b,\n      allocated t b ->\n      pinj t b Int.zero <> None.\n\n  Definition reachable (s : state) : Prop :=\n    exists start_state tr,\n      initial_state p start_state /\\\n      star step ge start_state tr s.\n  \n  (* This is what we have to assume about the program *)\n  (* TODO: change allocated to be just about blocks *)\n  (* just say the first thing in the block injects *)\n  (* pinj_add takes care of the rest *)\n  Hypothesis prog_well_behaved :\n    forall rs m t,\n      reachable (State rs m) ->\n      match_metadata t m ->\n      alloc_inj t.\n\n  (* Hypothesis global_base_inj : *)\n  (*   forall rs m t b, *)\n  (*     reachable (State rs m) -> *)\n  (*     match_metadata t m -> *)\n  (*     is_global_block b -> *)\n  (*     pinj t b (Int.zero) <> None. *)\n  \n  Definition reachable_bits (s : state_bits) : Prop :=\n    exists start_state tr,\n      initial_state_bits p start_state /\\\n      star step_bits ge start_state tr s.\n\n  Definition globals_alloc (t : allocator_metadata) : Prop := \n    forall b,\n      is_global_block (Genv.globalenv p) b ->\n      allocated t b.\n\n  \n  Inductive match_states : state -> state_bits -> Prop :=\n  | internal :\n      forall t rs m rs' m',\n        ptr_equiv_rs t rs rs' ->\n        ptr_equiv_mem (Genv.globalenv p) t m m' ->\n        globals_alloc t ->\n        reachable (State rs m) ->\n        reachable_bits (State_bits rs' m' t) ->\n        match_states (State rs m) (State_bits rs' m' t).\n\n\n  (* Lemma within_global_size_in_range : *)\n  (*   forall id ofs b, *)\n  (*     Genv.find_symbol ge id = Some b -> *)\n  (*     0 <= Int.unsigned ofs < global_size id p -> *)\n  (*     (in_var_range ge b ofs \\/ in_code_range ge b ofs). *)\n  (* Proof. *)\n  (*   intros. app Genv.find_symbol_inversion H. *)\n  (*   unfold prog_defs_names in H. *)\n  (*   app list_in_map_inv H. repeat break_and. destruct x. *)\n  (*   simpl in H. subst i. *)\n  (*   destruct g. right. *)\n  (*   app Genv.find_funct_ptr_exists H4. break_and. *)\n  (*   unfold ge in H1. rewrite H1 in H4. inv H4. *)\n  (*   unfold in_code_range. unfold global_size in H3. *)\n  (*   app (@lookup_norepet fundef unit) H. rewrite H in H3. *)\n  (*   unfold ge. rewrite H5. *)\n  (*   break_match; simpl. *)\n    \n  (*   omega. *)\n\n  (*   omega. *)\n\n  (*   left. *)\n  (*   app (@lookup_norepet fundef unit) H4. *)\n  (*   unfold global_size in H3. rewrite H4 in H3. *)\n  (*   unfold in_var_range. app Genv.find_var_exists H. *)\n  (*   repeat break_and. unfold ge in *. rewrite H1 in H. *)\n  (*   inv H. rewrite H6. omega. *)\n  (* Qed. *)\n\n  (* Lemma inj_init_defs: *)\n  (*   forall rs m t, *)\n  (*     initial_state p (State rs m) -> *)\n  (*     match_metadata t m -> *)\n  (*     injectable_defs ge t (prog_defs p). *)\n  (* Proof. *)\n  (*   intros. *)\n  (*   unfold wf_defs in *. unfold wf_idg in *. *)\n  (*   unfold wf_globdef in *. unfold wf_gvar in *. *)\n  (*   unfold injectable_defs. unfold injectable_idg. *)\n  (*   unfold injectable_globdef. unfold injectable_gvar. *)\n  (*   intros. break_let. break_match; auto. *)\n  (*   intros. *)\n  (*   subst. *)\n  (*   app all_defs_wf H1. simpl. *)\n  (*   app H1 H2. *)\n  (*   unfold wf_init_data in H2. *)\n  (*   unfold injectable_init_data. *)\n  (*   break_match; auto. *)\n  (*   intros. *)\n  (*   eapply prog_well_behaved; eauto. *)\n  (*   unfold reachable.  *)\n  (*   exists (State rs m). exists E0. *)\n  (*   split; auto. *)\n  (*   eapply star_refl. *)\n\n  (*   inv H. *)\n  (*   app ptr_equiv_init H7. *)\n  (*   break_and. unfold ptr_equiv_mem in H8. *)\n  (*   repeat break_and. *)\n  (*   unfold PtrEquivMem.globals_allocated in H11. *)\n    \n  (*   eapply ptr_equiv_init_find_symbol. *)\n  (*   inv H. eauto. eauto. *)\n  (*   eapply within_global_size_in_range. eauto. *)\n  (*   eauto. *)\n    \n    \n  (* Qed. *)\n\n  Lemma goto_label_same_mem :\n    forall f l rs m rs' m',\n      goto_label f l rs m = Next rs' m' ->\n      m = m'.\n  Proof.\n    intros. unfold goto_label in H.\n    repeat break_match_hyp; congruence.\n  Qed.\n\n  (* Definition more_allocated (md md' : allocator_metadata) : Prop := *)\n  (*   forall b ofs, *)\n  (*     allocated md b ofs -> *)\n  (*     allocated md' b ofs. *)\n\n  (* This is the wrong approach *)\n  (* Probably not useful, as has existential in conclusion *)\n  (* Move this lemma to MemoryAxioms.v *)\n  (* Lemma step_match_metadata : *)\n  (*   forall ge rs m t rs' m' md, *)\n  (*     match_metadata md m -> *)\n  (*     step ge (State rs m) t (State rs' m') -> *)\n  (*     exists md', *)\n  (*       match_metadata md' m' /\\ more_allocated md md'. *)\n  (* Proof. *)\n  (*   intros. inv_step H0. *)\n  (*   subst. *)\n  (*   * destruct i; simpl_exec; *)\n  (*     simpl in H9; *)\n  (*     repeat break_match_hyp; *)\n  (*     inv H9; *)\n  (*     unfold exec_load in *; *)\n  (*     unfold exec_big_load in *; *)\n  (*     repeat (break_match_hyp; try congruence); *)\n  (*     try find_inversion; *)\n\n  (*     try solve [eexists; split; try eassumption; *)\n  (*                unfold more_allocated; intros; assumption]; *)\n      \n  (*     unfold exec_store in *; unfold Mem.storev in *; *)\n  (*     repeat (break_match_hyp; try congruence); *)\n  (*     try find_inversion; *)\n\n  (*     try solve [eexists; split; try eapply match_store; eauto; *)\n  (*                unfold more_allocated; intros; assumption]; *)\n      \n  (*     try solve [match goal with *)\n  (*                  | [ H : goto_label _ _ _ _ = Next _ _ |- _ ] => *)\n  (*                    app goto_label_same_mem H; *)\n  (*                      subst; *)\n  (*                      solve [eexists; split; try eassumption; *)\n  (*                             unfold more_allocated; intros; assumption] *)\n  (*                end]; *)\n            \n  (*     try solve [unfold exec_big_store in *; *)\n  (*                 unfold Mem.storev in *; *)\n  (*                 repeat (break_match_hyp; try congruence); *)\n  (*                 find_inversion; *)\n  (*                 eexists; split; try eapply match_store; *)\n  (*                 try eapply match_store; eauto; *)\n  (*                 unfold more_allocated; intros; assumption]. *)\n\n  (*     (* alloc frame *) *)\n  (*     eexists. split. *)\n  (*     eapply match_store. eapply match_store. *)\n  (*     eapply match_alloc. eassumption. *)\n  (*     eauto. eauto. eauto. *)\n  (*     econstructor; eauto. *)\n\n\n  (*     (* free frame *) *)\n  (*     eexists. split. eapply match_free; eauto. *)\n  (*     econstructor; eauto. *)\n      \n  (*   * subst. *)\n  (*     eexists. split. *)\n  (*     eapply match_ec'; eauto. *)\n  (*     econstructor; eauto. *)\n  (*   * subst. *)\n  (*     eexists. split. *)\n  (*     eapply match_ec; eauto. *)\n  (*     econstructor; eauto. *)\n  (*   * subst. *)\n  (*     eexists. split. *)\n  (*     eapply match_ec'; eauto. *)\n  (*     econstructor; eauto. *)\n  (* Qed. *)\n\n  (* Lemma star_step_match_metadata : *)\n  (*   forall st st' t, *)\n  (*     star step ge st t st' -> *)\n  (*     forall rs m, *)\n  (*       st = State rs m -> *)\n  (*       forall rs' m', *)\n  (*         st' = State rs' m' -> *)\n  (*         forall md, *)\n  (*           match_metadata md m -> *)\n  (*           exists md', *)\n  (*             match_metadata md' m' /\\ more_allocated md md'. *)\n  (* Proof. *)\n  (*   induction 1; intros. *)\n  (*   subst. inv H0. *)\n  (*   eexists. split. eauto. *)\n  (*   unfold more_allocated. intros. eauto. *)\n  (*   subst. destruct s2. *)\n  (*   specialize (IHstar _ _ eq_refl _ _ eq_refl). *)\n  (*   app step_match_metadata H. break_and. *)\n  (*   specialize (IHstar x H). *)\n  (*   break_exists. break_and. *)\n  (*   exists x0. split. auto. *)\n  (*   unfold more_allocated in *. *)\n  (*   intros. apply H5. *)\n  (*   apply H2. assumption. *)\n  (* Qed. *)\n  \n  (* Lemma reachable_injectable : *)\n  (*   forall rs m, *)\n  (*     reachable (State rs m) -> *)\n  (*     exists md, *)\n  (*       injectable_defs ge md (prog_defs p) /\\ *)\n  (*       match_metadata md m. *)\n  (* Proof. *)\n  (*   intros. unfold reachable in *. *)\n  (*   repeat break_exists. *)\n  (*   break_and. *)\n  (*   destruct x. *)\n  (*   app init_state_match_metadata H. *)\n\n  (*   app star_step_match_metadata H0. break_and. *)\n  (*   exists x1. split; auto. *)\n  (*   unfold injectable_defs. intros. *)\n  (*   unfold injectable_idg. break_let. *)\n  (*   unfold injectable_globdef. break_match; auto. *)\n  (*   unfold injectable_gvar. intros. *)\n  (*   unfold injectable_init_data. break_match; auto. intros. *)\n  (*   unfold alloc_inj in *. *)\n  (*   eapply prog_well_behaved; eauto. *)\n  (*   apply H3. *)\n\n  (*   eapply ptr_equiv_init_find_symbol; eauto. *)\n  (*   inv H1; auto. *)\n\n  (*   eapply within_global_size_in_range. eauto. *)\n  (*   unfold wf_defs in *. *)\n  (*   unfold wf_idg in *. *)\n  (*   subst. specialize (all_defs_wf (i, Gvar v) H4). *)\n  (*   break_let. inv Heqp0. *)\n  (*   unfold wf_globdef in *. *)\n  (*   unfold wf_gvar in *. *)\n  (*   specialize (all_defs_wf _ H5). *)\n  (*   unfold wf_init_data in *. auto. *)\n  (* Qed. *)\n  \n  Fixpoint injectable_annot_arg {A : Type} (t : allocator_metadata) (aa : annot_arg A) : Prop :=\n    match aa with\n      | AA_addrglobal id ofs =>\n        match Genv.find_symbol ge id with\n          | Some b => pinj t b ofs <> None\n          | None => True\n        end\n      | AA_longofwords hi lo => injectable_annot_arg t hi /\\ injectable_annot_arg t lo\n      | _ => True\n    end.\n  \n  Lemma well_formed_inj :\n    forall {A : Type} t rs m (aa : annot_arg A),\n      well_formed_annot_arg aa p ->\n      globals_alloc t ->\n      reachable (State rs m) ->\n      match_metadata t m ->\n      injectable_annot_arg t aa.\n  Proof.\n    induction aa; intros; simpl; auto.\n    unfold well_formed_annot_arg in H.\n    break_match; auto.\n    unfold globals_alloc in H0.\n    unfold alloc_inj in prog_well_behaved.\n    destruct (pinj t b ofs) eqn:?; try congruence.\n    exploit prog_well_behaved; try eapply H0; eauto.\n\n    app Genv.find_symbol_inversion Heqo.\n    unfold prog_defs_names in Heqo.\n    app list_in_map_inv Heqo.\n    destruct x. break_and. subst.\n    unfold is_global_block. eauto.\n\n    destruct (pinj t b Int.zero) eqn:?; try congruence.\n    eapply pinj_add in Heqo1.\n    instantiate (1 := ofs) in Heqo1.\n    rewrite Int.add_zero_l in Heqo1.\n    congruence.\n    \n    simpl in H. break_and.\n    eauto.\n\n  Qed.\n\n  Lemma all_annot_arg_injectable :\n    forall e l,\n      instr_of_prog (Pannot e l) p ->\n      forall aa t rs m,\n        In aa l ->\n        globals_alloc t ->\n        reachable (State rs m) ->\n        match_metadata t m ->\n        injectable_annot_arg t aa.\n  Proof.\n    intros.\n    unfold all_annot_well_formed in *.\n    app all_annot_wf H0.\n    eapply well_formed_inj; eauto.\n  Qed.\n\n(*   Lemma all_addrmode_injectable : *)\n(*     forall r a, *)\n(*       instr_of_prog (Plea r a) p -> *)\n(*       injectable_addrmode a. *)\n(*   Proof. *)\n(*     intros. unfold all_lea_well_formed in all_addrmode_wf. *)\n(*     app all_addrmode_wf H. *)\n(*     unfold well_formed_addrmode in H. *)\n(*     unfold injectable_addrmode. *)\n(*     destruct a; auto. destruct const; auto. *)\n(*     destruct p0. break_match; auto. *)\n(*     app Genv.find_symbol_inversion Heqo. *)\n(*     app H Heqo. *)\n(*     apply globals_valid. *)\n(*     unfold prog_defs_names in H2. *)\n(*     app list_in_map_inv H2. break_and. subst i. *)\n(*     destruct x. destruct g. *)\n(*     right. unfold in_code_range. *)\n(*     app Genv.find_funct_ptr_exists H4. repeat break_and. *)\n(*     unfold ge. simpl in H1. unfold ge in H1. *)\n(*     rewrite H1 in H4. inv H4. *)\n(*     rewrite H7. simpl in H6. *)\n(*     unfold global_size in H6. *)\n(*     app (@lookup_norepet fundef unit) H2. *)\n(*     rewrite H2 in H6. *)\n(*     break_match; try omega. *)\n(*     assert (Int.unsigned i0 = 0) by omega. *)\n(*     rewrite H8 in *. *)\n(*     destruct i0. simpl in H8. subst. unfold Int.zero. *)\n(*     symmetry. apply Int.eqm_repr_eq. simpl. *)\n(*     apply Int.eqm_refl. *)\n(*     left. unfold in_var_range. *)\n(*     app Genv.find_var_exists H4. repeat break_and. *)\n(*     unfold ge in *. simpl in H1. *)\n(*     rewrite H4 in H1. inv H1. *)\n(*     rewrite H7. simpl in H6. unfold global_size in H6. *)\n(*     app (@lookup_norepet fundef unit) H2. rewrite H2 in H6. *)\n(*     omega. *)\n(*   Qed. *)\n\n  \n(* Lemma pinj_main_exists : *)\n(*     match Genv.symbol_address (Genv.globalenv p) (prog_main p) Int.zero with *)\n(*       | Vptr b i => pinj b i <> None *)\n(*       | _ => True *)\n(*     end. *)\n(* Proof. *)\n(*   unfold Genv.symbol_address. break_match_sm; auto. *)\n(*   app Genv.find_symbol_inversion Heqo. *)\n(*   eapply globals_valid. right. unfold in_code_range. *)\n(*   unfold prog_defs_names in Heqo. *)\n(*   app list_in_map_inv Heqo. break_and. *)\n(*   destruct x. simpl in H1. subst i. *)\n(*   destruct g. *)\n(*   app Genv.find_funct_ptr_exists H2. break_and. rewrite H2 in H. inv H. *)\n(*   unfold ge. rewrite H3. rewrite Int.unsigned_zero. *)\n(*   break_match. *)\n(*   name (zlen_nonneg _ (fn_code f0)) zln. omega. reflexivity. *)\n(*   app main_fn_is_fn H2. specialize (H2 v). congruence. *)\n(* Qed. *)\n\n(* Lemma pinj_symbol_exists : *)\n(*   forall id, *)\n(*     match Genv.find_symbol (Genv.globalenv p) id with *)\n(*       | Some b => *)\n(*         pinj b Int.zero <> None *)\n(*       | None => True *)\n(*     end. *)\n(* Proof. *)\n(*   intros. break_match; auto. *)\n(*   eapply globals_valid; eauto. *)\n(*   app Genv.find_symbol_inversion Heqo. *)\n(*   unfold prog_defs_names in Heqo. app list_in_map_inv Heqo. *)\n(*   break_and. destruct x. simpl in H1. subst id. destruct g. *)\n(*   right. app Genv.find_funct_ptr_exists H2. break_and. *)\n(*   rewrite H in H2. inv H2. unfold in_code_range. *)\n(*   unfold ge. rewrite H3. break_match. *)\n(*   name (zlen_nonneg _ (fn_code f0)) zln. rewrite Int.unsigned_zero. omega. *)\n(*   reflexivity. *)\n(*   left. unfold in_var_range. app Genv.find_var_exists H2. break_and. *)\n(*   rewrite H2 in H. inv H. *)\n(*   unfold ge. find_rewrite. *)\n(*   rewrite Int.unsigned_zero. split; try omega. *)\n(*   name (Genv.init_data_list_size_pos (gvar_init v)) lsp. omega. *)\n(* Qed. *)\n  \n(* Lemma pinj_alloc_exists : *)\n(*   forall rs m', *)\n(*     reachable (State rs m') -> *)\n(*     forall lo hi m b, *)\n(*       lo < hi -> *)\n(*       Mem.alloc m lo hi = (m',b) -> *)\n(*       forall i, *)\n(*         lo <= Int.unsigned i -> *)\n(*         Int.unsigned i <= hi -> (* pointers to just after block are also valid *) *)\n(*         pinj b i <> None. *)\n(* Proof. *)\n(*   intros. *)\n(*   eapply reachable_ptr_valid; eauto. *)\n(*   rewrite orb_true_iff. *)\n(*   assert (Int.unsigned i < hi \\/ Int.unsigned i = hi) by omega. destruct H4. *)\n(*   left. *)\n(*   rewrite Mem.valid_pointer_nonempty_perm. *)\n(*   app Mem.perm_alloc_2 H1. *)\n(*   eapply Mem.perm_implies; eauto. econstructor. *)\n(*   right. *)\n(*   rewrite H4 in *. clear H4. *)\n(*   rewrite Mem.valid_pointer_nonempty_perm. *)\n(*   app Mem.perm_alloc_2 H1. *)\n(*   eapply Mem.perm_implies; eauto. econstructor. *)\n(*   split; try omega. *)\n(* Qed. *)\n\n  \n  \nLemma eval_addrmode_pres :\n  forall a rs rs' m m' t b i,\n    match_states (State rs m) (State_bits rs' m' t) ->\n    eval_addrmode ge a rs = Vptr b i ->\n    Mem.valid_pointer m b (Int.unsigned i) = true ->\n    eval_addrmode_bits ge t a rs' = Vptr b i.\nProof.\n\n  intros a rs rs' m m' t b i H Hev Hvp.\n  inversion H as [ x y c d e Hptr_rs Hptr_mem Hreach Hreach_bits ].\n  subst.\n  unfold eval_addrmode in *.\n  unfold eval_addrmode_bits.\n  unfold ptr_equiv_rs in *.\n  unfold ptr_equiv_val in *.\n  destruct a. \n  repeat break_match_hyp; subst;\n  try name (Hptr_rs i0) Hi0;\n    try name (Hptr_rs i1) Hi1;\n    try name (Hptr_rs i2) Hi2;\n    clear Hptr_rs;\n    repeat break_match_hyp;\n    repeat break_or;\n    repeat break_exists;\n    repeat break_and;\n    simpl;\n    try rewrite H0;\n    try rewrite H1;\n    try rewrite H2;\n    unfold Val.add in *;\n    unfold Val.mul in *;\n    simpl in *;\n    try congruence;\n    try rewrite <- Hi0;\n    try rewrite <- Hi1;\n    inversion Hev;\n    subst;\n    try rewrite Heqb0;\n    repeat (break_match_hyp; try congruence);\n\n    match goal with\n      | [ H : pinj t _ _ = Some ?X\n          |-\n          match psur t (Int.add ?X _ ) with\n              _ => _\n          end = _\n        ] => idtac\n      | [ |- _ ] => try rewrite Int.add_permut\n    end;\n  \n  \n  name (pinj_add _ _ _ _ H2) Hpinj;\n  match goal with\n    | [ |- match psur _ (Int.add _ ?X) with\n               _ => _ end = _ ] =>\n      specialize (Hpinj X)\n  end;\n\n  try find_inversion;\n  try find_inversion;\n  try inv Heqv1;\n  try inv Heqv0;\n  \n  try solve [\n        app Mem.valid_pointer_implies Hvp;\n        name (conj Hpinj Hvp) Hp;\n        erewrite <- weak_valid_pointer_sur in Hp;\n        try collapse_match; try f_equal; try ring;\n        eapply ptr_equiv_match_metadata_l; eauto];\n\n  try solve [\n        rewrite Int.add_assoc in Hvp;\n        match goal with\n          | [ H : Mem.valid_pointer _ _ (Int.unsigned (Int.add ?Z (Int.add ?X ?Y))) = true |- _ ] => \n            rewrite (Int.add_commut X Y) in H;\n              app Mem.valid_pointer_implies H\n        end;\n        try solve [  name (conj Hpinj Hvp) Hp;\n                    erewrite <- weak_valid_pointer_sur in Hp;\n                    try collapse_match; try f_equal; try ring;\n                    eapply ptr_equiv_match_metadata_l; eauto]].\n  \nQed.\n\n\n  Lemma ptr_equiv_rs_val :\n    forall t rs rs',\n      ptr_equiv_rs t rs rs' ->\n      forall reg v,\n        rs reg = v ->\n        exists v',\n          rs' reg = v' /\\ ptr_equiv_val t v v'.\n  Proof.\n    intros. unfold ptr_equiv_rs in H. specialize (H reg).\n    rewrite H0 in H. exists (rs' reg). eauto.\n  Qed.\n\n  \n  Definition injectable_addrmode (t : allocator_metadata) (a : addrmode) : Prop :=\n    match a with\n      | Addrmode _ _ (inr (id,ofs)) =>\n        match Genv.find_symbol ge id with\n          | Some b => pinj t b ofs <> None\n          | None => True\n        end\n      | _ => True\n    end.\n\n  \nLemma ptr_equiv_eval_addrmode :\n  forall t rs rs',\n    ptr_equiv_rs t rs rs' ->\n    forall a,\n      injectable_addrmode t a ->\n      ptr_equiv_val t (eval_addrmode ge a rs) (eval_addrmode_no_ptr ge t a rs').\nProof.\n  intros.\n  name ptr_equiv_add pea.\n  name ptr_equiv_mul pem.\n  unfold ptr_equiv_binop in *.\n  destruct a; destruct base; destruct ofs; destruct const; try destruct p0;\n  simpl; repeat apply pea;\n  try destruct p1;\n  unfold Genv.symbol_address;\n  match goal with\n    | [ |- context[Genv.find_symbol ?X ?Y ] ] => destruct (Genv.find_symbol X Y) eqn:?\n    | [ |- _ ] => idtac\n  end;\n    repeat match goal with\n             | [ |- context[Int.eq ?X ?Y] ] => destruct (Int.eq X Y) eqn:?\n           end;\n    repeat apply pem;\n    unfold injectable_addrmode in *;\n    repeat find_rewrite;\n  try solve [apply ptr_equiv_self; assumption];\n  try solve [apply ptr_equiv_nonpointers; (intros; discriminate)];\n  try solve [\n        try apply ptr_equiv_undef_int;\n        try apply ptr_equiv_bits;\n        try apply ptr_equiv_init_undef;\n        try apply psur_add; assumption];\n  try solve [\n        break_match_sm;\n        try congruence;\n        match goal with\n          | [ H : pinj _ _ = Some _ |- _ ] => app pinj_psur_inverse H\n          | [ |- _ ] => idtac\n        end;\n        try solve [apply ptr_equiv_self; assumption];\n        try solve [apply ptr_equiv_nonpointers; (intros; discriminate)];\n        try solve [\n              try apply ptr_equiv_undef_int;\n              try apply ptr_equiv_bits;\n              try apply ptr_equiv_init_undef;\n              try apply psur_add; assumption] ];\n  try solve [break_match_sm; try congruence; apply ptr_equiv_bits;\n             try eapply pinj_add; eauto;\n             symmetry; rewrite Int.add_commut; symmetry;\n             eapply pinj_add; eauto];\n  try reflexivity;\n  clear pea;\n  clear pem;\n  unfold Val.add;\n  unfold Val.mul;\n  break_match_sm;\n  \n  match goal with\n    | [ H : rs _ = _ |- _ ] => app ptr_equiv_rs_val H; repeat break_and\n    | [ |- _ ] => idtac\n  end;\n  match goal with\n    | [ H : ptr_equiv_val _ _ _ |- _ ] => unfold ptr_equiv_val in H\n    | [ |- _ ] => idtac\n  end;\n  try break_match_hyp;\n  repeat break_or;\n  repeat break_exists;\n  repeat break_and;\n  subst;\n  repeat collapse_match;\n  match goal with\n    | [ |- context[pinj ?T ?X ?Y] ] => destruct (pinj T X Y) eqn:?; try congruence\n    | [ |- _ ] => idtac\n  end;\n  \n  try solve [apply ptr_equiv_self; assumption];\n  try solve [apply ptr_equiv_nonpointers; (intros; discriminate)];\n  try solve [\n        try apply ptr_equiv_undef_int;\n        try apply ptr_equiv_bits;\n        try apply ptr_equiv_init_undef;\n        try apply psur_add; assumption];\n  try congruence;\n  apply ptr_equiv_bits;\n  repeat eapply pinj_add;\n  symmetry; rewrite Int.add_commut; symmetry;\n  repeat eapply pinj_add;\n  try (symmetry; rewrite Int.add_commut; symmetry;\n       repeat eapply pinj_add);\n  eauto.\nQed.\n\n\nLemma globals_inj_addrmode :\n  forall t a rs m,\n    globals_alloc t ->\n    reachable (State rs m) ->\n    match_metadata t m ->\n    injectable_addrmode t a.\nProof.\n  unfold injectable_addrmode.\n  unfold globals_alloc. intros.\n  repeat break_match; try solve [exact I].\n  subst.\n\n\n  destruct (pinj t b Int.zero) eqn:?.\n  intro.\n  eapply pinj_add in Heqo0.\n  instantiate (1 := i0) in Heqo0.\n  rewrite Int.add_commut in Heqo0.\n  erewrite Int.add_zero in Heqo0.\n  congruence.\n  intro.\n\n  exploit H. unfold is_global_block. eauto.\n  intros.\n  exploit prog_well_behaved; eauto.\nQed.\n\nLtac ptr_equiv :=\n  try apply ptr_equiv_nextinstr_nf;\n  try apply ptr_equiv_nextinstr;\n  try apply ptr_equiv_undef_regs;\n  try apply ptr_equiv_set_regs;\n  try apply ptr_equiv_map_args;\n  try apply ptr_equiv_compare_ints;\n  try apply ptr_equiv_compare_floats;\n  try apply ptr_equiv_compare_floats32;\n  repeat apply ptr_equiv_update;\n  ptr_equiv_ops;\n  try apply ptr_equiv_sext;\n  try apply ptr_equiv_zext;\n  try apply ptr_equiv_encode_long;\n  try apply ptr_equiv_decode_longs;\n  ptr_equiv_conversion;\n  try apply ptr_equiv_self;\n  try eapply ptr_equiv_undef_self;\n  try solve [apply ptr_equiv_nonpointers; (intros; discriminate)];\n  try apply ptr_equiv_undef_int;\n  try apply ptr_equiv_bits;\n  try apply ptr_equiv_init_undef;\n  try apply ptr_equiv_eval_addrmode;\n  try apply ptr_equiv_of_optbool;\n  ptr_equiv_ops;\n  try eapply globals_inj_addrmode;\n  try eapply ptr_equiv_match_metadata_l; \n  eassumption.\n\n\nLemma in_range_unsigned_repr :\n  forall x y,\n    0 <= x < y ->\n    0 <= Int.unsigned (Int.repr x) < y.\nProof.\n  intros. \n  name (Int.unsigned_range (Int.repr x)) H1.\n  split. omega.\n  assert (y < Int.modulus \\/ y >= Int.modulus) by omega.\n  destruct H0. assert (x < Int.modulus) by omega.\n  rewrite Int.unsigned_repr. omega.\n  unfold Int.max_unsigned.\n  omega.\n  omega.\nQed.\n\nLemma ints_can_add :\n  forall x y,\n  exists z, (Int.add x z) = y.\nProof.\n  intros. exists (Int.sub y x). ring.\nQed.\n\nLemma goto_label_pres :\n  forall t rs rs' m m',\n    match_states (State rs m) (State_bits rs' m' t) ->\n    forall b i,\n      rs PC = Vptr b i ->\n      forall f,\n        Genv.find_funct_ptr ge b = Some (Internal f) ->\n        forall l rs'' m'',\n          goto_label f l rs m = Next rs'' m'' ->\n          exists rs''' m''',\n            goto_label_bits t f l b rs' m' = Nxt rs''' m''' t  /\\\n            ptr_equiv_rs t rs'' rs''' /\\ ptr_equiv_mem (Genv.globalenv p) t m'' m'''.\nProof.\n  intros.\n  P inv match_states.\n  unfold goto_label in *. unfold goto_label_bits.\n  break_match_hyp; try congruence.\n  break_match_hyp; try congruence.\n  app ptr_equiv_PC Heqv. break_and.\n  match goal with\n    | [ H : Vptr _ _ = Vptr _ _ |- _ ] => inv H\n  end.\n\n  match goal with\n    | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n  end.\n  break_match.\n\n  eexists. eexists. split; try reflexivity.\n  split; ptr_equiv.\n\n  exfalso.\n  generalize Heqo0.\n  cut (pinj t b (Int.repr z) <> None). auto.\n  clear Heqo0.\n  \n  app label_pos_find_instr Heqo.\n  apex in_range_find_instr Heqo.\n\n  use pinj_add; try eapply H4.\n  use (ints_can_add i (Int.repr z)).\n  break_exists. rewrite <- H7.\n  intro. rewrite H5 in H13. congruence.\nQed.\n\nLemma valid_access_any_chunk :\n  forall m c b ofs p,\n    Mem.valid_access m c b ofs p ->\n    Mem.valid_access m Mint8unsigned b ofs p.\nProof.\n  intros.\n  unfold Mem.valid_access in *.\n\n  break_and.\n\n\n  destruct c; simpl in *; eauto;\n  split;\n\n  try solve [unfold Mem.range_perm in *;\n              intros; apply H; omega];\n\n  eapply Z.divide_1_l.\n  \nQed.\n\nLemma load_valid_pointer :\n  forall c m b ofs v,\n    Mem.load c m b ofs = Some v ->\n    Mem.valid_pointer m b ofs = true.\nProof.\n  intros.\n  app Mem.load_valid_access H.\n  eapply Mem.valid_pointer_valid_access.\n  eapply Mem.valid_access_implies;\n    try instantiate (1 := Readable);\n    try solve [econstructor].\n  eapply valid_access_any_chunk; eauto.\nQed.\n  \nLemma exec_load_pres :\n  forall rs rs' m m' t,\n    match_states (State rs m) (State_bits rs' m' t) ->\n    forall c a r rs'' m'',\n      exec_load ge c m a rs r = Next rs'' m'' ->\n      exists rs''' m''',\n        exec_load_bits ge t c m' a rs' r = Nxt rs''' m''' t /\\\n        ptr_equiv_rs t rs'' rs''' /\\\n        ptr_equiv_mem (Genv.globalenv p) t m'' m'''.\nProof.\n  intros. inversion H. unfold exec_load_bits in *.\n  unfold exec_load in *.\n  unfold Mem.loadv in *.\n  destruct (eval_addrmode ge a rs) eqn:?; P inv Next.\n  break_match_hyp; P inv Next.\n  NP _app load_valid_pointer Mem.load.\n  \n  NP _eapplyin eval_addrmode_pres eval_addrmode; eauto.\n\n\n  unfold ge in *. unfold ge.\n  collapse_match.\n  NP _app ptr_equiv_mem_load Mem.load.\n  break_and.\n  collapse_match.\n  eexists. eexists. split. reflexivity.\n  econstructor; eauto; subst; try ptr_equiv.\nQed.\n\n\nLemma store_valid_pointer :\n  forall c m b ofs d m',\n    Mem.store c m b ofs d = Some m' ->\n    Mem.valid_pointer m b ofs = true.\nProof.\n  intros.\n  app Mem.store_valid_access_3 H.\n  eapply Mem.valid_pointer_valid_access.\n  eapply Mem.valid_access_implies;\n    try instantiate (1 := Writable);\n    try solve [econstructor].\n  eapply valid_access_any_chunk; eauto.\nQed.\n\nLemma exec_store_pres :\n  forall rs rs' m m' t,\n    match_states (State rs m) (State_bits rs' m' t) ->\n    forall c a r rs'' m'' d,\n      exec_store ge c m a rs r d = Next rs'' m'' ->\n      exists rs''' m''',\n        exec_store_bits ge t c m' a rs' r d = Nxt rs''' m''' t /\\\n        ptr_equiv_rs t rs'' rs''' /\\\n        ptr_equiv_mem (Genv.globalenv p) t m'' m'''.\nProof.\n  intros. name H Hmatch.\n  inversion H. unfold exec_store_bits in *.\n  unfold exec_store in *.\n  unfold Mem.storev in *.\n  destruct (eval_addrmode ge a rs) eqn:?; P inv Next.\n  break_match_hyp; P inv Next.\n  NP _app store_valid_pointer Mem.store.\n  NP _eapplyin eval_addrmode_pres eval_addrmode; eauto.\n  unfold ge in *. unfold ge.\n  P _rewrite eval_addrmode_bits.\n  NP _app ptr_equiv_mem_store Mem.store. break_and.\n  eexists. eexists.\n  unfold storev_bits. collapse_match.\n  split. reflexivity.\n  econstructor; eauto.\n  ptr_equiv.\nQed.\n\n\n\nLemma eval_annot_arg_pres :\n  forall t rs rs' m m' sp sp',\n    ptr_equiv_rs t rs rs' ->\n    ptr_equiv_mem (Genv.globalenv p) t m m' ->\n    ptr_equiv_val t sp sp' ->\n    forall aa v,\n      injectable_annot_arg t aa ->\n      eval_annot_arg ge rs sp m aa v ->\n      exists v',\n        eval_annot_arg_bits t ge rs' sp' m' aa v' /\\ ptr_equiv_val t v v'.\nProof.\n  intros.\n  induction H3;\n  try solve [eexists; split; [ econstructor; eauto | ptr_equiv]].\n  * unfold Mem.loadv in H3. unfold Val.add in H3.\n    destruct sp; simpl in H3; inversion H3.\n    simpl in H1. break_exists. break_and.\n    app ptr_equiv_mem_load H3. break_and.\n    eexists; split; try econstructor; eauto.\n    instantiate (2 := b). instantiate (1 := i).\n    erewrite weak_valid_pointer_sur.\n    split. eapply pinj_add; eauto.\n    app load_valid_pointer H5.\n    eapply Mem.valid_pointer_implies; eauto.\n    eapply ptr_equiv_match_metadata_l; eauto.\n    simpl. eauto.\n  * unfold Mem.loadv in *.\n    break_match_hyp; try congruence.\n    app ptr_equiv_mem_load H3.\n    break_and.\n    eexists; split; try econstructor.\n    unfold Mem.loadv. collapse_match. eauto. assumption.\n  * remember (Senv.symbol_address ge id ofs) as se.\n    unfold Senv.symbol_address in Heqse.\n    break_match_hyp; subst.\n\n    \n    unfold injectable_annot_arg in H2. unfold Senv.find_symbol in Heqo.\n    unfold Genv.to_senv in Heqo. rewrite Heqo in H2.\n    destruct (pinj t b ofs) eqn:?; try congruence.\n    eexists; split. econstructor; eauto.\n    unfold Senv.symbol_address. unfold Senv.find_symbol.\n    unfold ge. simpl. unfold ge in Heqo. rewrite Heqo. reflexivity.\n    ptr_equiv. \n    \n    exists Vundef. split; try ptr_equiv.\n    eapply eval_AA_addrglobal_undef.\n    unfold Senv.symbol_address.\n    collapse_match. reflexivity.\n    \n  * repeat break_exists; repeat break_and.\n    simpl in H2. break_and.\n    app IHeval_annot_arg1 H2.\n    app IHeval_annot_arg2 H3.\n    repeat break_and.\n    eexists; split. econstructor; eauto.\n    ptr_equiv.\nQed.\n\nLemma eval_annot_args_pres :\n  forall t rs rs' m m' sp sp',\n    ptr_equiv_rs t rs rs' ->\n    ptr_equiv_mem (Genv.globalenv p) t m m' ->\n    ptr_equiv_val t sp sp' ->\n    forall args vargs,\n      (forall x, In x args -> injectable_annot_arg t x) ->\n      eval_annot_args ge rs sp m args vargs ->\n      exists vargs',\n        (eval_annot_args_bits t ge rs' sp' m' args vargs' /\\\n         ptr_equiv_list t vargs vargs').\nProof.\n  intros. unfold eval_annot_args in H3.\n  induction H3.\n  * eexists.\n    split; econstructor; eauto.\n  * destruct IHlist_forall2. intros.\n    apply H2. simpl.  right. assumption.\n    app eval_annot_arg_pres H3; try apply H2; simpl;\n    try left; try reflexivity;\n    repeat break_and.\n    eexists; split; econstructor; eauto.\n\nQed.\n\nLemma extcall_arg_pres :\n  forall t rs rs' m m',\n    ptr_equiv_rs t rs rs' ->\n    ptr_equiv_mem (Genv.globalenv p) t m m' ->\n    forall a b,\n      extcall_arg rs m a b ->\n      exists b',\n        extcall_arg_bits t rs' m' a b' /\\ ptr_equiv_val t b b'.\nProof.\n  intros. inv H1.\n  * eexists; split.\n    econstructor; eauto.\n    ptr_equiv.\n  * unfold Mem.loadv in H3.\n    break_match_hyp; try congruence.\n    app ptr_equiv_mem_load H3. break_and.\n    unfold Val.add in Heqv.\n    break_match_hyp; try solve [inv Heqv].\n    unfold ptr_equiv_rs in H.\n    specialize (H ESP). unfold ptr_equiv_val in H.\n    rewrite Heqv0 in H.\n    break_exists; break_and.\n    \n    eexists; split; try econstructor; try reflexivity; eauto.\n\n    rewrite H. reflexivity.\n\n    erewrite weak_valid_pointer_sur;\n      try solve [eapply ptr_equiv_match_metadata_l; eauto].\n    split. inv Heqv.\n    eapply pinj_add; eauto.\n\n    app load_valid_pointer H1.\n    eapply Mem.valid_pointer_implies; eauto.\nQed.  \n\nLemma extcall_arguments_pres :\n  forall t rs m sg args,\n    extcall_arguments rs m sg args ->\n    forall rs' m',\n      ptr_equiv_rs t rs rs' ->\n      ptr_equiv_mem (Genv.globalenv p) t m m' ->\n      exists args',\n        extcall_arguments_bits t rs' m' sg args' /\\\n        ptr_equiv_list t args args'.\nProof.\n  intros. unfold extcall_arguments in *.\n  unfold extcall_arguments_bits.\n  induction H.\n  * eexists. split; try econstructor; eauto.\n  * break_exists; break_and.\n    app extcall_arg_pres H. break_and.\n    eexists; split; econstructor; eauto.\nQed.\n\n(* We guarantee our simulation only when *)\n(* a valid pointer into the current memory implies pinj works *)\n(* for current memory reached from start state *)\n\n(* TODO: maybe build sample pinj-psur functions that satisfy these axioms *)\n\n\n(* We need an axiom for external calls *)\n(* We provide slightly different arguments to external calls *)\n(* Thus we need the fact that external calls play nicely with our conversion *)\n(* Thus this needs to be an axiom *)\nAxiom ext_call_pres :\n  forall md rs rs' m m',\n    ptr_equiv_rs md rs rs' ->\n    ptr_equiv_mem (Genv.globalenv p) md m m' ->\n    forall ef vargs t v m'0,\n      external_call ef ge vargs m t v m'0 ->\n      forall vargs',\n        ptr_equiv_list md vargs vargs' ->\n        exists m'' v',\n          (external_call ef ge vargs' m' t v' m'' /\\\n           ptr_equiv_val (md_ec md ef ge vargs' m' t v' m'') v v' /\\\n           ptr_equiv_mem (Genv.globalenv p) (md_ec md ef ge vargs' m' t v' m'') m'0 m'').\n\nAxiom ext_call'_pres :\n  forall md rs rs' m m',\n    ptr_equiv_rs md rs rs' ->\n    ptr_equiv_mem (Genv.globalenv p) md m m' ->\n    forall ef vargs t v m'0,\n      external_call' ef ge vargs m t v m'0 ->\n      forall vargs',\n        ptr_equiv_list md vargs vargs' ->\n        exists m'' v',\n          (external_call' ef ge vargs' m' t v' m'' /\\\n           ptr_equiv_list (md_ec' md ef ge vargs' m' t v' m'') v v' /\\\n           ptr_equiv_mem (Genv.globalenv p) (md_ec' md ef ge vargs' m' t v' m'') m'0 m'').\n(* Proof. *)\n(*   intros. inversion H1. *)\n(*   name H3 Hec; eapply ext_call_pres in Hec; *)\n(*   try apply ptr_equiv_decode_longs; *)\n(*   try apply H2. *)\n(*   repeat break_exists. repeat break_and. *)\n(*   do 2 eexists; split; *)\n(*   try eapply external_call'_intro. *)\n(*   eapply H5. reflexivity. split. *)\n(*   subst. ptr_equiv. eauto. *)\n(*   eassumption. assumption. *)\n(* Qed. *)\n\n(* Lemma global_size_nonzero : *)\n(*   forall id b, *)\n(*     Genv.find_symbol (Genv.globalenv p) id = Some b -> *)\n(*     global_size id p > 0. *)\n(* Proof. *)\n(*   intros. app Genv.find_symbol_inversion H. *)\n(*   unfold global_size. *)\n(*   unfold prog_defs_names in H. *)\n(*   app list_in_map_inv H. *)\n(*   break_and. destruct x. *)\n(*   subst. *)\n(*   erewrite lookup_norepet; eauto. *)\n(*   unfold globals_nonempty in nonempty. *)\n(*   app nonempty H2. *)\n(*   unfold global_nonempty in *. *)\n(*   destruct g; try destruct f; omega. *)\n(* Qed. *)\n\nLemma find_sym_pinj_exists :\n  forall rs m t id b,\n    reachable (State rs m) ->\n    match_metadata t m ->\n    globals_alloc t ->\n    Genv.find_symbol (Genv.globalenv p) id = Some b ->\n    exists bits,\n      pinj t b Int.zero = Some bits.\nProof.\n  intros.\n  destruct (pinj t b Int.zero) eqn:?; eauto.\n  unfold globals_alloc in *.\n  exploit prog_well_behaved; try eapply H1; eauto.\n  unfold is_global_block. eauto.\n  intros. inv_false.\nQed.\n\nLemma reachable_step :\n  forall s,\n    reachable s ->\n    forall t s',\n      step ge s t s' ->\n      reachable s'.\nProof.\n  intros. unfold reachable in H.\n  repeat break_exists.\n  repeat break_and.\n  unfold reachable.\n  exists x. eexists.\n  split. auto.\n  eapply star_right. eassumption.\n  eassumption. reflexivity.\nQed.\n\nLemma reachable_step_bits :\n  forall s,\n    reachable_bits s ->\n    forall t s',\n      step_bits ge s t s' ->\n      reachable_bits s'.\nProof.\n  intros. unfold reachable_bits in H.\n  repeat break_exists.\n  repeat break_and.\n  unfold reachable.\n  exists x. eexists.\n  split. auto.\n  eapply star_right. eassumption.\n  eassumption. reflexivity.\nQed.\n\nLemma no_pointer_no_ptr :\n  forall m,\n    (forall b ofs, no_pointer (Mem.mem_contents m) !! b ofs) ->\n    no_ptr_mem m.\nProof.\n  intros. unfold no_pointer in *.\n  unfold no_ptr_mem.\n  intros.\n  apply H.\nQed.\n\nLemma ptr_equiv_no_ptr_mem :\n  forall t m m',\n    ptr_equiv_mem (Genv.globalenv p) t m m' ->\n    no_ptr_mem m'.\nProof.\n  intros. unfold ptr_equiv_mem in *.\n  repeat break_and.\n  unfold mem_contents_equiv in H1.\n  unfold contents_equiv in *.\n  eapply no_pointer_no_ptr.\n  intros. repeat break_and.\n  specialize (H5 b ofs).\n  break_and; eauto.\nQed.\n\nLemma psur_valid_code :\n  forall t b ofs bits f i,\n    pinj t b ofs = Some bits ->\n    Genv.find_funct_ptr (Genv.globalenv p) b = Some (Internal f) ->\n    find_instr (Int.unsigned ofs) (fn_code f) = Some i ->\n    forall m m',\n      ptr_equiv_mem (Genv.globalenv p) t m m' ->\n      psur t bits = Some (b,ofs).\nProof.\n  intros.\n  name H2 Hptr_equiv.\n  unfold ptr_equiv_mem in H2.\n  repeat break_and.\n  app global_perms_valid_globals H6.\n  unfold valid_globals in *.\n  exploit (H6 b ofs); intros.\n  unfold is_global. left.\n  unfold in_code_range.\n  collapse_match.\n  apex in_range_find_instr H1. omega.\n\n  eapply valid_pointer_sur; eauto.\n  eapply ptr_equiv_match_metadata_r; eauto.\nQed.\n\n\nLemma store_valid_commute :\n  forall m m' c b ofs v,\n    Mem.store c m b ofs v = Some m' ->\n    forall b ofs,\n      Mem.valid_pointer m b ofs = Mem.valid_pointer m' b ofs.\nProof.\n  intros. app Mem.store_access H.\n  unfold Mem.valid_pointer.\n  unfold Mem.perm_dec.\n  unfold proj_sumbool.\n  repeat break_match; try congruence;\n  clear Heqs; clear Heqs0;\n  rewrite H in *;\n  congruence.\nQed.\n\n\n\nLemma ptr_equiv_rs_alloc :\n  forall t rs rs',\n    ptr_equiv_rs t rs rs' ->\n    forall lo hi b,\n      ptr_equiv_rs (md_alloc t lo hi b) rs rs'.\nProof.\n  intros. unfold ptr_equiv_rs in *.\n  intros. eapply ptr_equiv_md_alloc; eauto.\nQed.\n\nLemma globals_inj_alloc :\n  forall t,\n    globals_alloc t ->\n    forall lo hi b,\n      globals_alloc (md_alloc t lo hi b).\nProof.\n  intros. unfold globals_alloc in *.\n  intros. app H H0.\n  econstructor; eauto.\nQed.\n\n\n\nLemma ptr_equiv_rs_free :\n  forall t rs rs',\n    ptr_equiv_rs t rs rs' ->\n    forall lo hi b,\n      ptr_equiv_rs (md_free t lo hi b) rs rs'.\nProof.\n  intros. unfold ptr_equiv_rs in *.\n  intros. eapply ptr_equiv_md_free; eauto.\nQed.\n\n\nLemma globals_inj_free :\n  forall t,\n    globals_alloc t ->\n    forall lo hi b,\n      globals_alloc (md_free t lo hi b).\nProof.\n  intros. unfold globals_alloc in *.\n  intros. app H H0.\n  econstructor; eauto.\nQed.\n\n\nLemma ptr_equiv_md_ec' :\n  forall rs rs' md,\n    ptr_equiv_rs md rs rs' ->\n    forall ef ge args m t m' res,\n      ptr_equiv_rs (md_ec' md ef ge args m t m' res) rs rs'.\nProof.\n  intros.\n  unfold ptr_equiv_rs in *.\n  intros. specialize (H r).\n  unfold ptr_equiv_val in *.\n  break_match_hyp; try assumption.\n  repeat break_exists. break_and.\n  eexists; split; try eassumption.\n  eapply pinj_ec'; eauto.\nQed.\n\nLemma globals_inj_ec :\n  forall md,\n    globals_alloc md ->\n    forall ef ge args m t m' res,\n      globals_alloc (md_ec md ef ge args m t m' res).\nProof.\n  intros. unfold globals_alloc in *.\n  intros. app H H0.\n  econstructor; eauto.\nQed.\n\nLemma ptr_equiv_md_ec :\n  forall rs rs' md,\n    ptr_equiv_rs md rs rs' ->\n    forall ef ge args m t m' res,\n      ptr_equiv_rs (md_ec md ef ge args m t m' res) rs rs'.\nProof.\n  intros.\n  unfold ptr_equiv_rs in *.\n  intros. specialize (H r).\n  unfold ptr_equiv_val in *.\n  break_match_hyp; try assumption.\n  repeat break_exists. break_and.\n  eexists; split; try eassumption.\n  eapply pinj_ec; eauto.\nQed.\n\nLemma globals_inj_ec' :\n  forall md,\n    globals_alloc md ->\n    forall ef ge args m t m' res,\n      globals_alloc (md_ec' md ef ge args m t m' res).\nProof.\n  intros. unfold globals_alloc in *.\n  intros. app H H0.\n  econstructor; eauto.\nQed.\n\nLemma as_bits_fsim_step :\n  forall (s1 : state) (t : trace) (s1' : state),\n    step ge s1 t s1' ->\n    forall s2 : state_bits,\n      match_states s1 s2 ->\n      exists s2', step_bits ge s2 t s2' /\\ match_states s1' s2'.\nProof.\n  intros. inversion H0.\n  inversion H. subst.\n  inv H12.\n\n  * assert (Hiop : instr_of_prog i p). {\n      unfold instr_of_prog. eexists. eexists. split; try eauto.\n      unfold code_of_prog.\n      app Genv.find_funct_ptr_inversion H9.\n      exists x. exists (fn_sig f). destruct f. simpl. apply H7.\n    }\n\n                                       \n    destruct i eqn:Hinstr;\n      try solve [P _simpl exec_instr; P inv exec_instr];\n      P _simpl exec_instr;\n\n      match goal with\n        | [ H : exec_load _ _ _ _ _ _ = _ |- _ ] => app exec_load_pres H\n        | [ H : exec_store _ _ _ _ _ _ _ = _ |- _ ] => app exec_store_pres H\n        | [ H : goto_label _ _ _ _ = _ |- _ ] => app goto_label_pres H\n        | [ |- _ ] => idtac\n      end;\n    name (H1 PC) HPC;\n    rewrite H8 in HPC;\n    unfold ptr_equiv_val in HPC;\n    repeat break_exists; repeat break_and;\n    try unfold Genv.symbol_address in *;\n    try destruct (Genv.find_symbol ge id) eqn:Hfindsym;\n    try unfold Genv.symbol_address in *;\n    try rewrite Hfindsym;\n    repeat break_match_hyp;\n    try congruence;\n    match goal with\n      | [ H : Val.divu _ _ = Some _ |- _ ] => app ptr_equiv_divu_pres H\n      | [ H : Val.divs _ _ = Some _ |- _ ] => app ptr_equiv_divs_pres H\n      | [ |- _ ] => idtac\n    end;\n    match goal with\n      | [ H : Val.modu _ _ = Some _ |- _ ] => app ptr_equiv_modu_pres H\n      | [ H : Val.mods _ _ = Some _ |- _ ] => app ptr_equiv_mods_pres H\n      | [ |- _ ] => idtac\n    end;\n    repeat break_and;\n    repeat match goal with\n             | [ H : State _ _ = State _ _ |- _ ] => inv H\n             | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n    end;\n    match goal with\n      | [ |- ptr_equiv_val _ _ ] => try ptr_equiv\n      | [ |- _ ] => idtac\n    end;\n    (*try app all_addrmode_injectable Hiop; *)\n\n    try solve [\n\n    (* Normal cases *)\n          unfold Genv.symbol_address in *;\n          match goal with\n            | [ H : Genv.find_symbol _ _ = Some _ |- _ ] => app find_sym_pinj_exists H\n            | [ |- _ ] => idtac\n          end;\n          try (eexists; isplit; econstructor);\n          simpl;\n          match goal with\n            | [ |- find_instr _ _ = _ ] => eassumption\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => reflexivity\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => simpl; unfold Genv.symbol_address; repeat collapse_match; reflexivity\n            | [ |- _ ] => idtac\n          end;\n          eauto;\n          match goal with\n            | [ H : pinj _ _ = Some _ |- _ ] => app pinj_psur_inverse H\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ H : reachable _ |- _ ] => app reachable_ptr_valid H\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ |- ptr_equiv_val _ _ _ ] => ptr_equiv\n            | [ |- ptr_equiv_rs _ _ _ ] => ptr_equiv\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n            | [ |- reachable _ ] => eapply reachable_step; eauto\n            | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n            | [ |- _ ] => idtac\n          end;\n          instantiate;\n          try eapply ptr_equiv_no_ptr_mem; eauto;\n          try solve [eapply ptr_equiv_match_metadata_r; eauto];\n          try solve [eapply ptr_equiv_match_metadata_l; eauto];\n          try solve [eapply ptr_equiv_global_perms_r; eauto];\n          try solve [eapply psur_valid_code; eauto];\n          instantiate\n\n        | \n\n          (* cmov *)\n          match goal with\n            | [ H : eval_testcond _ _ = _ |- _ ] => app ptr_equiv_eval_testcond H\n            | [ |- _ ] => idtac\n          end;\n          eexists; isplit; econstructor;\n          match goal with\n            | [ |- find_instr _ _ = _ ] => eassumption\n            | [ |- _ ] => idtac\n          end;\n          simpl;\n          repeat match goal with\n                   | [ H : eval_testcond _ _ = _ |- _ ] => try rewrite H; clear H\n                 end;\n          match goal with\n            | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n            | [ |- _ ] => idtac\n          end;\n          try reflexivity;\n          eauto;\n          match goal with\n            | [ |- ptr_equiv_val _ _ _ ] => ptr_equiv\n            | [ |- ptr_equiv_rs _ _ _ ] => ptr_equiv\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n            | [ |- reachable _ ] => eapply reachable_step; eauto\n            | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n            | [ |- _ ] => idtac\n          end;\n          try eapply ptr_equiv_no_ptr_mem; eauto;\n          try solve [eapply ptr_equiv_match_metadata_r; eauto];\n          try solve [eapply ptr_equiv_match_metadata_l; eauto];\n          try solve [eapply ptr_equiv_global_perms_r; eauto];\n          try solve [eapply psur_valid_code; eauto]\n\n        |\n    \n          (* Conditional Jumps *)\n          match goal with\n            | [ H : _ = Some (Pjcc ?X _), H2 : eval_testcond ?X _ = _ |- _ ] => app ptr_equiv_eval_testcond H2\n            | [ H : _ = Some (Pjcc2 ?X ?Y _), H2 : eval_testcond ?X _ = _, H3 : eval_testcond ?Y _ = _ |- _ ] => app ptr_equiv_eval_testcond H2; app ptr_equiv_eval_testcond H3\n          end;\n          match goal with\n            | [ H : goto_label _ _ _ _ = _ |- _ ] => app goto_label_pres H\n            | [ |- _ ] => idtac\n          end;\n          repeat break_and;\n          eexists; isplit; econstructor;\n          simpl;\n          match goal with\n            | [ |- find_instr _ _ = _ ] => eassumption\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n            | [ |- _ ] => idtac\n          end;\n          try reflexivity;\n          try ptr_equiv;\n          try solve [eapply ptr_equiv_no_ptr; eassumption];\n          try solve [eapply reachable_step; eauto];\n          try solve [eapply reachable_step_bits; eauto];\n          simpl;\n          repeat match goal with\n                   | [ H : eval_testcond _ rs' = _ |- _ ] => rewrite H\n                 end;\n          try reflexivity;\n          eauto;\n          try eapply ptr_equiv_no_ptr_mem; eauto;\n          try solve [eapply ptr_equiv_match_metadata_r; eauto];\n          try solve [eapply ptr_equiv_match_metadata_l; eauto];\n          try solve [eapply ptr_equiv_global_perms_r; eauto];\n          try solve [eapply psur_valid_code; eauto]\n          \n          |\n\n          (* jump table *)\n          match goal with\n            | [ H : goto_label _ _ _ _ = Next _ _ |- _ ] => app goto_label_pres H\n          end; repeat break_and;\n          eexists; isplit; econstructor;\n          match goal with\n            | [ |- find_instr _ _ = _ ] => eassumption\n            | [ |- _ ] => idtac\n          end;\n          match goal with\n            | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n            | [ |- _ ] => idtac\n          end;\n          simpl;\n          match goal with\n            | [ H : rs _ = _ |- _ ] => app ptr_equiv_val_exists H\n            | [ |- _ ] => idtac\n          end;\n          repeat break_and;\n          simpl in *;\n          repeat collapse_match;\n          eauto;\n          match goal with\n            | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n            | [ |- reachable _ ] => eapply reachable_step; eauto\n            | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n            | [ |- _ ] => idtac\n          end;\n          try eapply ptr_equiv_no_ptr_mem; eauto;\n          try solve [eapply ptr_equiv_match_metadata_r; eauto];\n          try solve [eapply ptr_equiv_match_metadata_l; eauto];\n          try solve [eapply ptr_equiv_global_perms_r; eauto];\n          try solve [eapply psur_valid_code; eauto]\n          \n        ].\n\n    \n    (*mov_mi*)\n    unfold Mem.storev in Heqo.\n    break_match_hyp; try congruence.\n    app eval_addrmode_pres Heqv.\n    app ptr_equiv_mem_store Heqo.\n    eexists. isplit.\n    econstructor; eauto.\n    eapply psur_valid_code; eauto.\n    eapply ptr_equiv_no_ptr; eassumption.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    simpl.\n    unfold storev_bits.\n    break_and. collapse_match.\n    rewrite H13. reflexivity.\n    eapply ptr_equiv_match_metadata_r; eauto.\n    repeat break_and.\n    eapply ptr_equiv_global_perms_r; eauto.\n    econstructor; eauto.\n    ptr_equiv.\n    break_and. assumption.\n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n    ptr_equiv.\n    app store_valid_pointer Heqo.\n\n    (* Pmovups_rm *)\n    unfold exec_big_load in *.\n    repeat break_let;\n      repeat break_match_hyp; try congruence;\n      state_inv.\n    unfold Mem.loadv in *. repeat break_match_hyp; try congruence.\n    app ptr_equiv_mem_load Heqo.\n    app ptr_equiv_mem_load Heqo0.\n    repeat break_and.\n    app eval_addrmode_pres Heqv0.\n    app eval_addrmode_pres Heqv1.\n    eexists; isplit; econstructor.\n    Focus 6. eauto.\n    Focus 6.\n    simpl. unfold exec_big_load_bits.\n    collapse_match. find_rewrite. find_rewrite.\n    simpl. repeat collapse_match.\n    reflexivity.\n    eauto. eauto.\n    eapply psur_valid_code; eauto.\n    eapply ptr_equiv_no_ptr; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    eauto.\n    eapply ptr_equiv_match_metadata_r; eauto.\n    eapply ptr_equiv_global_perms_r; eauto.\n    ptr_equiv. eauto.\n    eauto.\n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n    eapply load_valid_pointer; eauto.\n    eapply load_valid_pointer; eauto.   \n\n    (* Pmovups_mr *)\n    unfold exec_big_store in *.\n    repeat break_match; try congruence; state_inv.\n    unfold Mem.storev in *.\n    repeat break_match; try congruence.\n    app eval_addrmode_pres Heqv0.\n    app eval_addrmode_pres Heqv.\n    app ptr_equiv_mem_store Heqo. break_and.\n    app ptr_equiv_mem_store Heqo0. break_and.\n    eexists; isplit; econstructor; try eapply H10;\n    simpl; unfold exec_big_store_bits; try collapse_match;\n    try find_rewrite; try find_rewrite; simpl;\n    repeat collapse_match; try reflexivity; eauto.\n    eapply psur_valid_code; eauto.\n    eapply ptr_equiv_no_ptr; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    eapply ptr_equiv_match_metadata_r; eauto.\n    eapply ptr_equiv_global_perms_r; eauto.\n    ptr_equiv.\n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n\n\n    app store_valid_commute Heqo.\n    rewrite Heqo.\n    \n    eapply store_valid_pointer; eauto.\n    eapply store_valid_pointer; eauto.\n\n\n    (* div *)\n    unfold Genv.symbol_address in *;\n      match goal with\n        | [ H : Genv.find_symbol _ _ = Some _ |- _ ] => app find_sym_pinj_exists H\n        | [ |- _ ] => idtac\n      end;\n      try (eexists; isplit; econstructor);\n      simpl;\n      match goal with\n        | [ |- find_instr _ _ = _ ] => eassumption\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => reflexivity\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => simpl; unfold Genv.symbol_address; repeat collapse_match; reflexivity\n        | [ |- _ ] => idtac\n      end;\n      eauto;\n      match goal with\n        | [ H : pinj _ _ = Some _ |- _ ] => app pinj_psur_inverse H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ H : reachable _ |- _ ] => app reachable_ptr_valid H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- ptr_equiv_val _ _ _ ] => ptr_equiv\n        | [ |- ptr_equiv_rs _ _ _ ] => ptr_equiv\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n        | [ |- reachable _ ] => eapply reachable_step; eauto\n        | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n        | [ |- _ ] => idtac\n      end;\n      try eapply ptr_equiv_no_ptr_mem; eauto;\n      try solve [eapply ptr_equiv_match_metadata_r; eauto];\n      try solve [eapply ptr_equiv_match_metadata_l; eauto];\n      try solve [eapply ptr_equiv_global_perms_r; eauto];\n      try solve [eapply psur_valid_code; eauto];\n      instantiate.\n\n    (* idiv *)\n    unfold Genv.symbol_address in *;\n      match goal with\n        | [ H : Genv.find_symbol _ _ = Some _ |- _ ] => app find_sym_pinj_exists H\n        | [ |- _ ] => idtac\n      end;\n      try (eexists; isplit; econstructor);\n      simpl;\n      match goal with\n        | [ |- find_instr _ _ = _ ] => eassumption\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => reflexivity\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => simpl; unfold Genv.symbol_address; repeat collapse_match; reflexivity\n        | [ |- _ ] => idtac\n      end;\n      eauto;\n      match goal with\n        | [ H : pinj _ _ = Some _ |- _ ] => app pinj_psur_inverse H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ H : reachable _ |- _ ] => app reachable_ptr_valid H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- ptr_equiv_val _ _ _ ] => ptr_equiv\n        | [ |- ptr_equiv_rs _ _ _ ] => ptr_equiv\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n        | [ |- reachable _ ] => eapply reachable_step; eauto\n        | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n        | [ |- _ ] => idtac\n      end;\n      try eapply ptr_equiv_no_ptr_mem; eauto;\n      try solve [eapply ptr_equiv_match_metadata_r; eauto];\n      try solve [eapply ptr_equiv_match_metadata_l; eauto];\n      try solve [eapply ptr_equiv_global_perms_r; eauto];\n      try solve [eapply psur_valid_code; eauto].\n\n    \n    (* cmov (left eval to None) *)\n    destruct (eval_testcond c rs') eqn:?;\n             try destruct b0;\n\n    unfold Genv.symbol_address in *;\n      match goal with\n        | [ H : Genv.find_symbol _ _ = Some _ |- _ ] => app find_sym_pinj_exists H\n        | [ |- _ ] => idtac\n      end;\n      try (eexists; isplit; econstructor);\n      simpl;\n      match goal with\n        | [ |- find_instr _ _ = _ ] => eassumption\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => reflexivity\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- exec_instr_bits _ _ _ _ _ _ _ = _ ] => simpl; unfold Genv.symbol_address; repeat collapse_match; reflexivity\n        | [ |- _ ] => idtac\n      end;\n      eauto;\n      match goal with\n        | [ H : pinj _ _ = Some _ |- _ ] => app pinj_psur_inverse H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ H : reachable _ |- _ ] => app reachable_ptr_valid H\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- ptr_equiv_val _ _ _ ] => ptr_equiv\n        | [ |- ptr_equiv_rs _ _ _ ] => ptr_equiv\n        | [ |- _ ] => idtac\n      end;\n      match goal with\n        | [ |- no_ptr_regs _ ] => eapply ptr_equiv_no_ptr; eassumption\n        | [ |- reachable _ ] => eapply reachable_step; eauto\n        | [ |- reachable_bits _ ] => eapply reachable_step_bits; eauto\n        | [ |- _ ] => idtac\n      end;\n      try eapply ptr_equiv_no_ptr_mem; eauto;\n      try solve [eapply ptr_equiv_match_metadata_r; eauto];\n      try solve [eapply ptr_equiv_match_metadata_l; eauto];\n      try solve [eapply ptr_equiv_global_perms_r; eauto];\n      try solve [eapply psur_valid_code; eauto].\n\n    eapply ptr_equiv_nextinstr.\n    unfold ptr_equiv_rs.\n    intros. preg_case.\n    ptr_equiv. ptr_equiv.\n    \n\n    (* allocframe *)\n    app ptr_equiv_mem_alloc Heqp0. repeat break_and.\n    destruct (pinj (md_alloc t0 0 sz b0) b0 Int.zero) eqn:Hpinj_zero.\n\n    app ptr_equiv_mem_store Heqo. repeat break_and.\n    app ptr_equiv_mem_store Heqo0. repeat break_and.\n    \n    eexists; isplit; econstructor;\n    try solve [eapply ptr_equiv_no_ptr; eassumption];\n    match goal with\n      | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n      | [ |- _ ] => idtac\n    end;\n    match goal with\n      | [ |- find_instr _ _ = _ ] => eassumption\n      | [ |- _ ] => idtac\n    end;\n    eauto.\n    eapply psur_valid_code; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    simpl.\n    break_let.\n    match goal with\n      | [ H : (_,_) = (_,_) |- _ ] => inv H\n    end.\n    repeat collapse_match.\n    rewrite H15. rewrite H18.\n    reflexivity.\n    eapply ptr_equiv_match_metadata_r; eauto.\n    eapply ptr_equiv_global_perms_r; eauto.\n\n\n    eapply ptr_equiv_update;\n      try solve [preg_simpl; find_rewrite; find_rewrite;\n                 eapply ptr_equiv_md_alloc; ptr_equiv];\n      eapply ptr_equiv_update;\n      try eapply ptr_equiv_update;\n      try solve [eapply ptr_equiv_rs_alloc; eauto];\n    ptr_equiv.\n\n    eapply globals_inj_alloc; eauto.\n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n\n    eapply ptr_equiv_md_alloc; ptr_equiv.\n    eapply ptr_equiv_md_alloc; ptr_equiv.\n    \n\n    assert (code_of_prog (fn_code f) p). {\n      unfold code_of_prog.\n      app Genv.find_funct_ptr_inversion H9.\n    exists x1. exists (fn_sig f). destruct f. simpl. auto.\n    }       \n      \n    NP _app palloc code_of_prog.\n\n    unfold all_allocframes_positive_code in *.\n    NP1 _app H14 find_instr.\n\n    assert (allocated (md_alloc t0 0 sz b0) b0). {\n      econstructor; eauto.\n    } \n    eapply prog_well_behaved in H17.\n    congruence.\n    instantiate (1 := m'0).\n    eapply reachable_step; eauto.\n    eapply match_store; try solve [eauto].\n    eapply match_store; try solve [eauto].\n    eapply ptr_equiv_match_metadata_l; eauto.\n                                                          \n    (* freeframe *)\n    unfold Mem.loadv in *. unfold Val.add in *.\n    app ptr_equiv_mem_load Heqo. break_and.\n    app ptr_equiv_mem_load Heqo0. break_and.\n    name (H1 ESP) HESP.\n    rewrite Heqv1 in HESP.\n    simpl in HESP. break_exists; break_and.\n    app ptr_equiv_mem_free Heqo1; break_and.\n    eexists; isplit; econstructor;\n    try solve [eapply ptr_equiv_no_ptr; eassumption];\n    match goal with\n      | [ H : Next _ _ = Next _ _ |- _ ] => inv H\n      | [ |- _ ] => idtac\n    end;\n    match goal with\n      | [ H : find_instr _ _ = _ |- _ ] => try apply H\n    end; eauto. simpl.\n    eapply psur_valid_code; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    simpl.\n    match goal with\n      | [ H : rs' _ = _ |- _ ] => rewrite H\n    end.\n\n    app load_valid_pointer H11.\n    app load_valid_pointer H14.\n    copy H18.\n    eapply pinj_add in H24. instantiate (1 := ofs_ra) in H24.\n    copy H18.\n    eapply pinj_add in H25. instantiate (1 := ofs_link) in H25.\n    app Mem.valid_pointer_implies H11.\n    app Mem.valid_pointer_implies H14.\n    name (conj H24 H11) Hora.\n    name (conj H25 H14) Holink.\n    erewrite <- weak_valid_pointer_sur in Hora.\n    erewrite <- weak_valid_pointer_sur in Holink.\n    repeat collapse_match.\n    reflexivity.\n    eapply ptr_equiv_match_metadata_l; eauto.\n    eapply ptr_equiv_match_metadata_l; eauto.\n    eapply ptr_equiv_match_metadata_r; eauto.\n\n    eapply ptr_equiv_global_perms_r; eauto.\n    \n    eapply ptr_equiv_rs_free; ptr_equiv.\n\n    eapply globals_inj_free; eauto.\n    \n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n    \n  *\n    \n\n    subst.\n    match goal with\n      | [ H : State _ _ = State _ _ |- _ ] => inv H\n    end.\n    \n    match goal with\n      | [ H : external_call' _ _ _ _ _ _ _ |- _ ] => app ext_call'_pres H\n    end; eauto.\n    match goal with\n      | [ H : rs PC = _ |- _ ] => app ptr_equiv_PC H\n    end.\n    repeat break_and.\n\n    Focus 2.\n    apply ptr_equiv_map_args.\n    apply H1.\n    \n    \n    assert (ptr_equiv_rs (md_ec' t0 ef ge (map rs' args) m' t x0 x) (nextinstr_nf\n              (set_regs res vl\n                 (undef_regs (map preg_of (destroyed_by_builtin ef)) rs)))\n                         (nextinstr_nf (set_regs res x0 (undef_regs (map preg_of (destroyed_by_builtin ef)) rs')))).\n    {\n      apply ptr_equiv_nextinstr_nf;\n      try apply ptr_equiv_set_regs;\n      try apply ptr_equiv_undef_regs;\n      try ptr_equiv;\n      try eapply ptr_equiv_md_ec';\n      eauto.\n    }\n\n    eexists; isplit; econstructor; eauto.\n\n    erewrite weak_valid_pointer_sur; try eapply ptr_equiv_match_metadata_r; eauto.\n    split; try assumption.\n    eapply ptr_equiv_valid_globals_r in H2; eauto.\n    unfold valid_globals in *.\n    eapply Mem.valid_pointer_implies.\n    eapply H2.\n    unfold is_global.\n    left.\n    unfold in_code_range.\n    unfold ge in *.\n    unfold fundef in *.\n    collapse_match.\n    apex in_range_find_instr H10.\n    omega.\n    \n    eapply ptr_equiv_no_ptr; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n\n    eapply ptr_equiv_match_metadata_r; eauto.\n    eapply ptr_equiv_global_perms_r; eauto.\n\n    eapply globals_inj_ec'; eauto.\n    \n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n          \n  * \n    subst.\n    match goal with\n      | [ H : State _ _ = State _ _ |- _ ] => inv H\n    end.\n    match goal with\n      | [ H : rs PC = _ |- _ ] => app ptr_equiv_PC H\n    end.\n    break_and.\n\n    match goal with\n      | [ H : eval_annot_args _ _ _ _ _ _ |- _ ] => app eval_annot_args_pres H; repeat break_and\n    end.\n    match goal with\n      | [ H : external_call _ _ _ _ _ _ _ |- _ ] => app ext_call_pres H; repeat break_and\n    end.\n\n    eexists; isplit.\n    try eapply exec_step_annot_bits;\n      try eassumption.\n\n    erewrite weak_valid_pointer_sur; try eapply ptr_equiv_match_metadata_r; eauto.\n    split; try assumption.\n    eapply ptr_equiv_valid_globals_r in H2; eauto.\n    unfold valid_globals in *.\n    eapply Mem.valid_pointer_implies.\n    eapply H2.\n    unfold is_global.\n    left.\n    unfold in_code_range.\n    unfold ge in *.\n    unfold fundef in *.\n    collapse_match.\n    apex in_range_find_instr H10.\n    omega.\n    \n    eapply ptr_equiv_no_ptr; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n    eapply ptr_equiv_no_ptr_mem; eauto.\n\n    eapply ptr_equiv_match_metadata_r; eauto.\n\n    eapply ptr_equiv_global_perms_r; eauto.\n\n    econstructor; try ptr_equiv.\n\n    eapply ptr_equiv_md_ec; ptr_equiv.\n    \n    eapply globals_inj_ec; eauto.\n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n    intros.\n    eapply all_annot_arg_injectable; eauto. \n    unfold instr_of_prog. destruct f.\n    match goal with\n      | [ H : Genv.find_funct_ptr _ _ = _ |- _ ] => app Genv.find_funct_ptr_inversion H\n    end.\n    repeat eexists; eauto.\n    eapply ptr_equiv_match_metadata_l; eauto.\n\n  * \n    subst.\n    match goal with\n      | [ H : State _ _ = State _ _ |- _ ] => inv H\n    end.\n\n    match goal with\n      | [ H : extcall_arguments _ _ _ _ |- _ ] => app extcall_arguments_pres H\n    end.\n    break_and.\n\n    match goal with\n      | [ H : external_call' _ _ _ _ _ _ _ |- _ ] => app ext_call'_pres H\n    end; eauto; repeat break_and.\n\n    match goal with\n      | [ H : rs PC = _ |- _ ] => app ptr_equiv_PC H\n    end; eauto; repeat break_and.\n\n    \n    \n    eexists; isplit;\n    try eapply exec_step_external_bits;\n    try eapply ptr_equiv_no_ptr;\n    eauto.\n    6: econstructor; eauto.\n\n    erewrite weak_valid_pointer_sur; try eapply ptr_equiv_match_metadata_r; eauto.\n    split; try assumption.\n    eapply ptr_equiv_valid_globals_r in H2; eauto.\n    unfold valid_globals in *.\n    eapply Mem.valid_pointer_implies.\n    eapply H2.\n    unfold is_global.\n    left.\n    unfold in_code_range.\n    unfold ge in *.\n    unfold fundef in *.\n    collapse_match.\n    rewrite Int.unsigned_zero.\n    omega.\n\n    eapply ptr_equiv_update. eapply ptr_equiv_set_regs.\n    2: eassumption. eapply ptr_equiv_md_ec'. eassumption.\n    assert (ptr_equiv_val t0 (rs RA) (rs' RA)).\n    eapply H1.\n    unfold ptr_equiv_val. unfold ptr_equiv_val in H17.\n    instantiate (1 := rs RA). break_match_hyp; try assumption.\n    break_exists. break_and. eexists; split; try eassumption.\n                             eapply pinj_ec'; eauto.\n\n    eapply ptr_equiv_no_ptr_mem; eauto.\n\n    eapply ptr_equiv_match_metadata_r; eauto.\n\n    eapply ptr_equiv_global_perms_r; eauto.\n    \n    eapply ptr_equiv_update; try eapply ptr_equiv_set_regs; try ptr_equiv.\n    eapply ptr_equiv_md_ec'; eauto.\n    eapply ptr_equiv_md_ec'; eauto.\n\n    eapply globals_inj_ec'; eauto.\n    \n    eapply reachable_step; eauto.\n    eapply reachable_step_bits; eauto.\n\n    Grab Existential Variables.\n    exact PC. exact PC.\n    exact PC. exact PC.\n    exact PC. exact PC.\n\nQed.\n\nLemma public_symbols_preserved :\n     forall id : ident,\n   Senv.public_symbol (symbolenv (semantics_bits p)) id =\n   Senv.public_symbol (symbolenv (semantics p)) id.\nProof.\n  intros. unfold Senv.public_symbol. simpl.\n  reflexivity.\nQed.\n\n\nLemma initial_states_match :\n  forall s1 : state,\n    initial_state p s1 ->\n    exists s2,\n      initial_state_bits p s2 /\\ match_states s1 s2.\nProof.\n\n  intros. inversion H. subst.\n  app ptr_equiv_init H0. repeat break_and.\n\n  destruct (Genv.find_symbol (Genv.globalenv p) (prog_main p)) eqn:?.\n  \n  Focus 2.\n  eexists; isplit; econstructor; eauto.\n  unfold Genv.symbol_address. rewrite Heqo.\n  reflexivity.\n  subst rs0. repeat eapply ptr_equiv_update; try ptr_equiv.\n  unfold Genv.symbol_address. unfold ge0. rewrite Heqo.\n  ptr_equiv. unfold globals_alloc. intros.\n  app globals_allocated_init H0.\n  unfold reachable. eexists; eexists; isplit.\n  eauto. eapply star_refl.\n  unfold reachable_bits. eexists. eexists.\n  isplit. eauto. eapply star_refl.\n\n  assert (pinj x0 b Int.zero <> None). {\n\n    unfold alloc_inj in *.\n    eapply prog_well_behaved; eauto.\n\n    unfold reachable.\n    eexists; eexists; split; try eapply star_refl; eauto.\n    eapply ptr_equiv_match_metadata_l; eauto.\n    unfold is_global_block.\n    app globals_allocated_init H0.\n    eapply H0.\n    unfold is_global_block. eauto.\n    \n  } idtac.\n  \n  destruct (pinj x0 b Int.zero) eqn:?; try congruence.\n\n  eexists; isplit; try econstructor; eauto.\n  unfold Genv.symbol_address. unfold fundef in *.\n  repeat collapse_match.\n  instantiate (1 := i). app ptr_equiv_match_metadata_r H2.\n  erewrite weak_valid_pointer_sur; eauto. split; auto.\n  eapply Mem.valid_pointer_implies.\n  app ptr_equiv_global_perms_r H4; eauto.\n  eapply global_perms_valid_globals in H4.\n  \n  eapply H4. app Genv.find_symbol_inversion Heqo.\n  unfold prog_defs_names in Heqo.\n  app list_in_map_inv Heqo. destruct x1.\n  break_and.\n  simpl in H8. subst i0.\n  app main_fn_is_fn H9.\n  destruct g.\n  * break_and.\n    \n    unfold is_global. left. unfold in_code_range.\n    inv H9.\n    app Genv.find_funct_ptr_exists H8.\n    repeat break_and. unfold fundef in *.\n    rewrite H8 in H6. inv H6.\n    collapse_match.\n    rewrite Int.unsigned_zero.\n    break_match; split; try omega.\n    destruct (fn_code f); try congruence.\n    rewrite zlen_cons. name (zlen_nonneg _ c) zlnc.\n    omega.\n    \n  * break_and. congruence.\n  * \n  subst rs0.\n  repeat eapply ptr_equiv_update; eauto.\n  unfold ptr_equiv_rs. intros. rewrite Pregmap.gi. simpl. left. reflexivity.\n  unfold Genv.symbol_address. unfold ge0. unfold fundef in *. collapse_match.\n  simpl. eauto. simpl. eauto. simpl. eauto.\n  * unfold globals_alloc. intros.\n    app globals_allocated_init H0.\n  * \n  unfold reachable. eexists; eexists; isplit.\n  eauto. eapply star_refl.\n  * unfold reachable_bits. eexists. eexists.\n  isplit. eauto. eapply star_refl.\n\nQed.  \n\nLemma final_states_match :\n  forall s1 s2 x,\n    match_states s1 s2 ->\n    final_state s1 x ->\n    final_state_bits s2 x.\nProof.\n  intros. inversion H0. subst.\n  inversion H. subst.\n  unfold ptr_equiv_rs in H5.\n  unfold ptr_equiv_val in H5.\n  econstructor.\n  specialize (H5 PC). rewrite H1 in H5. simpl in H5. auto.\n  specialize (H5 EAX). rewrite H2 in H5. auto.\nQed.\n\nLemma as_bits_fsim :\n  forward_simulation (semantics p) (semantics_bits p).\nProof.\n  intros.\n  eapply forward_simulation_step;\n    try eapply as_bits_fsim_step;\n    try eapply public_symbols_preserved;\n    try eapply initial_states_match;\n    try eapply final_states_match.\nQed.\n\nEnd FSIM.\n\nLemma eval_annot_arg_bits_determ:\n  forall (ge : Senv.t) (e : preg -> val)\n         (sp : val) (m : mem) (a : annot_arg preg) (v : val) md,\n    eval_annot_arg_bits md ge e sp m a v ->\n    forall v' : val, eval_annot_arg_bits md ge e sp m a v' -> v' = v.\nProof.\n  induction 1; intros v' EV; inv EV; try congruence.\n  f_equal; eauto.\n  inv H4. rewrite H0 in H5.\n  assert (Int.add o ofs = Int.add o0 ofs) by congruence.\n  rewrite H in *.\n  assert (o = o0). {\n    assert (Int.add (Int.add o ofs) (Int.neg ofs) = Int.add (Int.add o ofs) (Int.neg ofs)) by reflexivity.\n    rewrite H in H2 at 1. repeat rewrite Int.add_assoc in H2.\n    rewrite Int.add_neg_zero in H2.\n    repeat rewrite Int.add_zero in H2. congruence.\n  } idtac.\n  subst o.\n  assert (b = b0) by congruence.\n  subst b.\n  rewrite H1 in H7. congruence.\n  f_equal; eauto.\n  \nQed.\n\nLemma eval_annot_args_bits_determ:\n  forall (ge : Senv.t) (e : preg -> val)\n         (sp : val) (m : mem) (al : list (annot_arg preg))\n         (vl : list val) md,\n    eval_annot_args_bits md ge e sp m al vl ->\n    forall vl' : list val, eval_annot_args_bits md ge e sp m al vl' -> vl' = vl.\nProof.\n  induction 1; intros v' EV; inv EV; f_equal; eauto using eval_annot_arg_bits_determ.\nQed.\n\nRemark extcall_arguments_bits_determ:\n  forall rs md m sg args1 args2,\n    extcall_arguments_bits md rs m sg args1 ->\n    extcall_arguments_bits md rs m sg args2 ->\n    args1 = args2.\nProof.\n  intros until m.\n  \n  assert (forall ll vl1, list_forall2 (extcall_arg_bits md rs m) ll vl1 ->\n          forall vl2, list_forall2 (extcall_arg_bits md rs m) ll vl2 -> vl1 = vl2).\n    induction 1; intros vl2 EA; inv EA.\n    auto.\n    f_equal; auto.\n    inv H; inv H3; congruence.\n  intros. red in H0; red in H1. eauto.\nQed.\n\n\nLemma alloc_only_globals_bits_match :\n  forall l md ge m m' md' l',\n    alloc_only_globals_bits md ge m l = Some (m',md',l') ->\n    match_metadata md m ->\n    match_metadata md' m'.\nProof.\n  induction l; intros;\n  simpl in *; try congruence.\n  repeat break_match_hyp; try congruence.\n  subst. opt_inv. subst.\n  app IHl Heqo0.\n  destruct a; simpl in Heqo.\n  repeat break_match_hyp; try congruence;\n  opt_inv; subst;\n  try solve [\n  eapply match_drop_perm; try eapply match_alloc; eauto].\nQed.\n\nLemma store_zeros_bits_match :\n  forall l m b ofs m',\n    store_zeros_bits m b ofs l = Some m' ->\n    forall md,\n      match_metadata md m ->\n      match_metadata md m'.\nProof.\n  induction l using Z_nat_ind; eauto; intros;\n  rewrite store_zeros_bits_equation in *;\n  try break_match_hyp; try omega; try congruence.\n  break_match_hyp; try congruence.\n  rewrite store_zeros_bits_equation in *.\n  break_match_hyp; try omega. opt_inv. subst.\n  eapply match_store_bits; eauto.\n  break_match_hyp; try congruence.\n  replace (l + 1 - 1) with l in * by omega.\n  app IHl H0.\n  eapply match_store_bits; eauto.\nQed.\n\nLemma store_init_data_list_bits_match :\n  forall l md ge m b ofs m',\n    store_init_data_list_bits md ge m b ofs l = Some m' ->\n    match_metadata md m ->\n    match_metadata md m'.\nProof.\n  induction l; intros;\n  simpl in *. congruence.\n  repeat break_match_hyp; try congruence.\n  app IHl H.\n  unfold store_init_data_bits in Heqo.\n  repeat break_match_hyp; try congruence;\n  eapply match_store_bits; eauto.\nQed.\n\nLemma store_globals_bits_match :\n  forall l md m ge m' md',\n    store_globals_bits md ge m l = Some (m',md') ->\n    match_metadata md m ->\n    match_metadata md' m'.\nProof.\n  induction l; intros;\n  simpl in *; try congruence.\n  repeat break_let; repeat break_match_hyp; try congruence.\n  subst. app IHl H.\n  unfold store_global_bits in Heqo.\n  repeat break_match_hyp; try congruence;\n  opt_inv; subst.\n  eapply match_set_perm; eauto.\n  eapply match_set_perm; eauto.\n  eapply match_set_perm; try eapply Heqo2.\n  eapply store_init_data_list_bits_match;\n    try eapply store_zeros_bits_match;\n    eauto.\nQed.\n\nLemma init_mem_bits_match :\n  forall p m md,\n    init_mem_bits p = Some (m,md) ->\n    match_metadata md m.\nProof.\n  unfold init_mem_bits in *.\n  unfold alloc_globals_bits in *.\n  intros.\n  repeat break_match_hyp; try congruence.\n  subst.\n  app alloc_only_globals_bits_match Heqo;\n    try solve [econstructor].\n  eapply store_globals_bits_match; eauto.\nQed.\n\n\nLemma semantics_determinate:\n  forall p, determinate (semantics_bits p).\nProof.\n\nLtac Equalities :=\n  match goal with\n  | [ H1: ?a = ?b, H2: ?a = ?c |- _ ] =>\n      rewrite H1 in H2; inv H2; Equalities\n  | _ => idtac\n  end.\n  intros; constructor; simpl; intros.\n- (* determ *)\n  inv H; inv H0; Equalities.\n  + split. constructor. auto.\n  + discriminate.\n  + discriminate.\n  + discriminate.\n  + exploit external_call_determ'. eexact H5.\n    eexact H16. intros [A B].\n    split. auto. intros. destruct B; auto. subst. auto.\n  + discriminate.\n  + assert (vargs0 = vargs) by (eapply eval_annot_args_bits_determ; eauto). subst vargs0.\n    exploit external_call_determ.\n    eexact H8. eassumption.\n    intros [A B].\n    split. auto. intros. destruct B; auto. subst. auto.\n  + assert (args0 = args) by (eapply extcall_arguments_bits_determ; eauto). subst args0.\n    exploit external_call_determ'. eexact H5. eexact H16. intros [A B].\n    split. auto. intros. destruct B; auto. subst. auto.\n- (* trace length *)\n  red; intros; inv H; simpl.\n  omega.\n  inv H4. eapply external_call_trace_length; eauto.\n  eapply external_call_trace_length; eauto.\n  inv H4. eapply external_call_trace_length; eauto.\n- (* initial states *)\n  inv H; inv H0. f_equal.\n  + unfold rs0, rs1.\n    repeat break_match_hyp; subst_max; auto.\n    rewrite H1 in H. inv H.\n    app init_mem_bits_match H1.\n    erewrite weak_valid_pointer_sur in *; eauto.\n    repeat break_and.\n    unify_pinj. auto.\n  + congruence.\n  + congruence.\n- (* final no step *)\n  inv H. unfold Vzero in H0.\n  red; intros; red; intros.\n  inv H; replace bits with Int.zero in * by congruence.\n  + erewrite weak_valid_pointer_sur in *; eauto.\n    break_and. eapply null_always_invalid in H; eauto.\n    break_and. app Mem.weak_valid_pointer_spec H2.\n    break_or; try congruence.\n  + erewrite weak_valid_pointer_sur in *; eauto.\n    break_and. eapply null_always_invalid in H; eauto.\n    break_and. app Mem.weak_valid_pointer_spec H2.\n    break_or; try congruence.\n  + erewrite weak_valid_pointer_sur in *; eauto.\n    break_and. eapply null_always_invalid in H; eauto.\n    break_and. app Mem.weak_valid_pointer_spec H2.\n    break_or; try congruence.\n  + erewrite weak_valid_pointer_sur in *; eauto.\n    break_and. eapply null_always_invalid in H; eauto.\n    break_and. app Mem.weak_valid_pointer_spec H2.\n    break_or; try congruence.\n- (* final states *)\n  inv H; inv H0. congruence.\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/asmbits/Asm2Bits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18715415116007478}}
{"text": "Require Import ZArith String List Bool.\nRequire Import ExtLib.Core.ZDecidables.\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Data.Monads.StateMonad.\nRequire Import ExtLib.Structures.Folds.\nRequire Import ExtLib.Data.Strings.\nRequire Import ExtLib.Data.Char.\nRequire Import ExtLib.Data.Lists.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Tactics.Consider.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** Provides abstract syntax and \"ugly\" printer for LLVM assembly code.\n    I've tried to be relatively complete but there are a few missing\n    instructions, attributes, etc. that we are very unlikely to use\n    (e.g., things dealing with concurrency or intrinsics.)\n\n    The ugly printer has not been tested at all. \n\n    We probably want to provide some some convenience on top of this\n    for building abstract syntax that provides convenient defaults.\n*)\nModule LLVM.\n  Import MonadNotation String.\n  Local Open Scope string_scope.\n  Local Open Scope monad_scope.\n  Definition var := string.\n  Definition label := string.\n\n  Inductive cconv : Type := \n  | X86_fastcallcc | C_cc | Fast_cc | Cold_cc | CC10_cc | Num_cc : nat -> cconv.\n\n  Inductive linkage : Type := \n  | Private | Linker_private | Linker_private_weak | Linker_private_weak_def_auto \n  | Internal | Available_externally | Linkonce | Weak | Common | Appending | Extern_weak\n  | Linkonce_odr | Weak_odr | External | Dllimport | Dllexport. \n      \n  Inductive visibility : Type := | Default_v | Hidden_v | Protected_v.\n\n  Inductive param_attr : Type := \n  | Zeroext_pattr | Signext_pattr | Inreg_pattr | Byval_pattr | Sret_pattr | Noalias_pattr\n  | Nocapture_pattr | Nest_pattr.\n\n\n  Inductive fn_attr : Type := \n  | Address_safety | Align_stack : nat -> fn_attr | Alwaysinline | Nonlazybind | Inlinehint\n  | Naked | Noimplicitfloat | Noinline | Noredzone | Noreturn | Nounwind\n  | Optsize | Readnone | Readonly | Returns_twice | Ssp | Sspreq | Uwtable.\n\n\n  Inductive type : Type := \n  | I_t : nat -> type\n  | Half_t | Float_t | Double_t | X86_fp80_t | Fp128_t | Ppc_fp128_t \n  | Void_t | Label_t | X86mmx_t | Metadata_t \n  | Array_t : list nat -> type -> type\n  | Fn_t : forall (returntype: type) (arg_types : list type) (vararg : bool), type\n  | Struct_t : forall (packed:bool) (elts : list type), type\n  | Named_t : string -> type\n  | Opaque_t : type\n  | Pointer_t : forall (addrspace:nat), type -> type\n  | Vector_t : nat -> type -> type.\n\n  Inductive constant : Type := \n  | True_c\n  | False_c\n  | Int_c : Z -> constant\n  | Float_c : string -> constant\n  | Null_c : constant\n  | Global_c : var -> constant\n  | Undef_c : constant\n  | Zero_c : constant\n  | Struct_c : list constant -> constant\n  | Array_c : list constant -> constant\n  | Vector_c : list constant -> constant\n  | Metadata_c : list constant -> constant\n  | Metastring_c : string -> constant\n  | Ptrtoint_c : type -> constant -> type -> constant\n  | Inttoptr_c : type -> constant -> type -> constant\n  | Bitcast_c : type ->constant -> type -> constant.\n\n  Inductive value : Type := \n  | Local : var -> value\n  | Global : var -> value\n  | AnonLocal : nat -> value\n  | AnonGlobal : nat -> value\n  | Constant : constant -> value.\n\n  Inductive cond : Type := \n  | Eq | Ne | Ugt | Uge | Ult | Ule | Sgt | Sge | Slt | Sle.\n\n  Inductive fcond : Type := \n  | False_fc | Oeq_fc | Ogt_fc | Oge_fc | Olt_fc | Ole_fc | One_fc | Ord_fc | Ueq_fc\n  | Ugt_fc | Uge_fc | Ult_fc | Ule_fc | Une_fc | Uno_fc | True_fc.\n\n  Inductive exp : Type := \n  | Add_e : forall (nuw:bool) (nsw:bool) (ty:type) (op1:value) (op2:value), exp\n  | Fadd_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Sub_e : forall (nuw:bool) (nsw:bool) (ty:type) (op1:value) (op2:value), exp\n  | Fsub_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Mul_e : forall (nuw:bool) (nsw:bool) (ty:type) (op1:value) (op2:value), exp\n  | Fmul_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Udiv_e : forall (exact:bool) (ty:type) (op1 op2:value), exp\n  | Sdiv_e : forall (exact:bool) (ty:type) (op1 op2:value), exp\n  | Fdiv_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Urem_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Srem_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Frem_e : forall (ty:type) (op1:value) (op2:value), exp\n  | Shl_e : forall (nuw:bool) (nsw:bool) (ty:type) (op1:value) (op2:value), exp \n  | Lshr_e : forall (exact:bool) (ty:type) (op1 op2:value), exp\n  | Ashr_e : forall (exact:bool) (ty:type) (op1 op2:value), exp\n  | And_e : forall (ty:type) (op1 op2:value), exp\n  | Or_e : forall (ty:type) (op1 op2:value), exp\n  | Xor_e : forall (ty:type) (op1 op2:value), exp\n  | Extractvalue_e : type -> value -> nat -> list nat -> exp\n  | Insertvalue_e : type -> value -> type -> value -> nat -> list nat -> exp\n  | Alloca_e : type -> option (type * nat) -> option nat -> exp\n  | Load_e : forall (atomic:bool) (volatile:bool) (ty:type) (pointer:value) (align:option nat)\n                    (nontemporal:option nat) (invariant:option nat) (singlethread:bool), exp\n  | Getelementptr_e : forall (inbounds:bool)(pointer_ty:type) (pointerval: value), list (type * value) -> exp\n  | Trunc_e : type -> value -> type -> exp\n  | Zext_e : type -> value -> type -> exp\n  | Sext_e : type -> value -> type -> exp\n  | Fptrunc_e : type -> value -> type -> exp\n  | Fpext_e : type -> value -> type -> exp\n  | Fptoui_e : type -> value -> type -> exp\n  | Fptosi_e : type -> value -> type -> exp\n  | Uitofp_e : type -> value -> type -> exp\n  | Sitofp_e : type -> value -> type -> exp\n  | Ptrtoint_e : type -> value -> type -> exp\n  | Inttoptr_e : type -> value -> type -> exp\n  | Bitcast_e : type -> value -> type -> exp\n  | Icmp_e : cond -> type -> value -> value -> exp\n  | Fcmp_e : fcond -> type -> value -> value -> exp\n  | Phi_e : type -> list (value * label) -> exp\n  | Select_e : type -> value -> type -> value -> type -> value -> exp\n  | Call_e : forall (tail:bool) (convention: option cconv) (ret_attrs:list param_attr) (ty:type) \n                    (fnptrty: option type) (fnptr:value) \n                    (args : list (type * value * (list param_attr))) \n                    (fn_attrs: list fn_attr), exp.\n\n  Definition flag(b:bool)(s:string) : string := if b then s else \"\".\n  \n  Inductive instr : Type := \n  | Comment_i : string -> instr\n  | Ret_i : option (type * value) -> instr\n  | Br_cond_i : value -> label -> label -> instr\n  | Br_uncond_i : label -> instr\n  | Switch_i : type -> value -> label -> list (type * Z * label) -> instr\n  | Resume_i : type -> value -> instr\n  | Unreachable_i : instr\n  | Assign_i : (option value) -> exp -> instr\n  | Store_i : forall (atomic:bool) (volatile:bool) (ty:type) (v:value) (ptrty:type) (pointer:value) \n                     (align:option nat) (nontemporal:option nat) (singlethread:bool), instr.\n\n  Record fn_header : Type := {\n    linkage_fh : option linkage ; \n    visibility_fh : option visibility ; \n    cconv_fh : option cconv ; \n    unnamed_addr_fh : bool ; \n    return_type_fh : type ; \n    return_type_attrs_fh : list param_attr ; \n    name_fh : var ; \n    args_fh : list (type * var * list (param_attr)) ; \n    attrs_fh : list fn_attr ; \n    section_fh : option string ; \n    align_fh : option nat ; \n    gc_fh : option string\n  }.\n\n  Definition block := ((option label) * (list instr))%type.\n    \n  Inductive topdecl : Type := \n  | Global_d : forall (x:var) (addrspace:option nat) (l:option linkage) (unnamed_addr:bool) (const:bool) \n                      (t:type) (c:constant) (section:option string) (align:option nat), topdecl\n  | Define_d : fn_header -> list block -> topdecl\n  | Declare_d : fn_header -> topdecl\n  | Alias_d : forall (x:var) (l:option linkage) (v:option visibility) (t:type) (e:exp), topdecl\n  | Metadata_d : forall (x:var), list constant -> topdecl.\n\n  Definition module := list topdecl.\n\n  Fixpoint eq_type x y : bool :=\n    match x , y with\n      | I_t n , I_t n' => eq_dec n n'\n      | Half_t , Half_t => true\n      | Float_t , Float_t => true\n      | Double_t , Double_t => true\n      | X86_fp80_t , X86_fp80_t => true\n      | Fp128_t , Fp128_t => true\n      | Ppc_fp128_t , Ppc_fp128_t => true\n      | Void_t , Void_t => true\n      | Label_t , Label_t => true\n      | X86mmx_t , X86mmx_t => true\n      | Metadata_t , Metadata_t => true\n      | Array_t ns t , Array_t ns' t' =>\n        eq_dec ns ns' && eq_type t t'\n      | Fn_t r a b , Fn_t r' a' b' =>\n        eq_type r r' && eq_dec b b' &&\n        (fix recur l r :=\n          match l , r with\n            | nil , nil => true\n            | cons l ls , cons r rs =>\n              if eq_type l r then recur ls rs else false\n            | _ , _ => false\n          end) a a'\n      | Struct_t b e , Struct_t b' e' =>\n        eq_dec b b' &&\n        (fix recur l r :=\n          match l , r with\n            | nil , nil => true\n            | cons l ls , cons r rs =>\n              if eq_type l r then recur ls rs else false\n            | _ , _ => false\n          end) e e'\n      | Named_t n , Named_t n' =>\n        eq_dec n n'\n      | Pointer_t a t , Pointer_t a' t' =>\n        eq_dec a a' && eq_type t t'\n      | Vector_t n t , Vector_t n' t' =>\n        eq_dec n n' && eq_type t t'\n      | _ , _ => false\n  end.\n\n  Global Instance RelDec_eq_LLVMtype : RelDec (@eq LLVM.type) :=\n  { rel_dec := eq_type }.\n\n  Fixpoint eq_constant x y : bool :=\n    match x , y with\n      | True_c , True_c\n      | False_c , False_c\n      | Null_c , Null_c\n      | Undef_c , Undef_c \n      | Zero_c , Zero_c => true\n      | Int_c i1, Int_c i2 => eq_dec i1 i2\n      | Float_c c1, Float_c c2 => eq_dec c1 c2\n      | Global_c v , Global_c v' => eq_dec v v'\n      | Struct_c v , Struct_c v'\n      | Array_c v, Array_c v' \n      | Vector_c v , Vector_c v' \n      | Metadata_c v , Metadata_c v' => \n        (fix rec xs ys : bool :=\n          match xs , ys with\n            | nil , nil => true\n            | x :: xs , y :: ys => \n              eq_constant x y && rec xs ys\n            | _ , _ => false\n          end) v v'\n      | Metastring_c v , Metastring_c v' => eq_dec v v'\n      | Ptrtoint_c t1 c t2 , Ptrtoint_c t1' c' t2' =>\n        eq_constant c c' && eq_dec t1 t1' && eq_dec t2 t2'\n      | Inttoptr_c t1 c t2 , Inttoptr_c t1' c' t2' =>\n        eq_constant c c' && eq_dec t1 t1' && eq_dec t2 t2'\n      | Bitcast_c t1 c t2 , Bitcast_c t1' c' t2' =>\n        eq_constant c c' && eq_dec t1 t1' && eq_dec t2 t2'\n      | _ , _ => false\n    end.\n\n  Global Instance RelDec_eq_constant : RelDec (@eq LLVM.constant) :=\n  { rel_dec := eq_constant }.\n\n  Global Instance RelDec_eq_value : RelDec (@eq value) :=\n  { rel_dec := fun x y => \n    match x , y with\n      | Local v, Local v' => eq_dec v v'\n      | Global v , Global v' => eq_dec v v'\n      | AnonLocal v, AnonLocal v' => eq_dec v v'\n      | AnonGlobal v, AnonGlobal v' => eq_dec v v'\n      | Constant c, Constant c' => eq_dec c c'\n      | _ , _ => false\n    end }.\n\n\n  Section Printing.\n    Require Import ExtLib.Programming.Show.\n    Import ShowNotation.\n    Local Open Scope show_scope.\n\n    Global Instance Show_cconv : Show cconv :=\n      fun c => \n        match c with \n          | X86_fastcallcc => \"x86_fastcallcc\" \n          | C_cc => \"ccc\" | Fast_cc => \"fastcc\" | Cold_cc => \"coldcc\" | CC10_cc => \"cc 10\"\n          | Num_cc n => \"cc \" << show n \n        end.\n\n    Global Instance Show_linkage : Show linkage :=\n      fun l => \n        match l with \n          | Private => \"private\"\n          | Linker_private => \"linker_private\"\n          | Linker_private_weak => \"linker_private_weak\"\n          | Linker_private_weak_def_auto => \"linker_private_weak_def_auto\"\n          | Internal => \"internal\"\n          | Available_externally => \"available_externally\"\n          | Linkonce => \"linkonce\"\n          | Weak => \"weak\"\n          | Common => \"common\"\n          | Appending => \"appending\"\n          | Extern_weak => \"extern_weak\"\n          | Linkonce_odr => \"linkonce_odr\"\n          | Weak_odr => \"weak_odr\"\n          | External => \"external\"\n          | Dllimport => \"dllimport\"\n          | Dllexport => \"dllexport\"\n        end.\n\n    Global Instance Show_param_attr : Show param_attr :=\n      fun p => \n        match p with \n          | Zeroext_pattr => \"zeroext\" | Signext_pattr => \"signext\" | Inreg_pattr => \"inreg\" \n          | Byval_pattr => \"byval\" | Sret_pattr => \"sret\" | Noalias_pattr => \"noalias\"\n          | Nocapture_pattr => \"nocapture\" | Nest_pattr => \"nest\"\n        end.\n\n    Definition double_quote := Ascii.ascii_of_nat 34.\n    Definition quoted := wrap double_quote double_quote.\n\n    Global Instance Show_visibility : Show visibility :=\n      fun v => quoted \n        match v with \n          | Default_v => \"default\" | Hidden_v => \"hidden\" | Protected_v => \"protected\"\n        end.\n\n    Global Instance Show_fn_attr : Show fn_attr :=\n      fun f =>\n        match f with \n          | Address_safety => \"address_safety\" \n          | Align_stack n => \"alignstack(\" << show n << \")\" \n          | Alwaysinline => \"alwaysinline\" \n          | Nonlazybind => \"nonlazybind\"\n          | Inlinehint => \"inlinehint\"\n          | Naked => \"naked\"\n          | Noimplicitfloat => \"noimplicitfloat\"\n          | Noinline => \"noinline\" \n          | Noredzone => \"noredzone\"\n          | Noreturn => \"noreturn\"\n          | Nounwind => \"nounwind\"\n          | Optsize => \"optsize\"\n          | Readnone => \"readnone\"\n          | Readonly => \"readonly\" \n          | Returns_twice => \"returns_twice\"\n          | Ssp => \"ssp\"\n          | Sspreq => \"sspreq\"\n          | Uwtable => \"uwtable\"\n        end.\n\n    Global Instance Show_type : Show type :=\n      fix show_type (t : type) : showM :=\n        match t with \n          | I_t n => \"i\" << show n\n          | Half_t => \"half\"\n          | Float_t => \"float\"\n          | Double_t => \"double\"\n          | X86_fp80_t => \"x86_fp80\"\n          | Fp128_t => \"fp128\"\n          | Ppc_fp128_t => \"ppc_fp128\"\n          | Void_t => \"void\"\n          | Label_t => \"label\"\n          | X86mmx_t => \"x86mmx\"\n          | Metadata_t => \"metadata\"\n          | Array_t ns t => \n            List.fold_right (fun (i:nat) (t:showM) => \n                         \"[\" << show i << \" x \" << t << \"]\") (show_type t) ns\n          | Fn_t t ts vararg => \n            show_type t << \"(\" << sepBy \", \" (List.map show_type ts) << \n            (if vararg then \",...)\" else \")\")\n          | Struct_t packed elts => \n            let s := \"{\" << (sepBy \", \" (List.map show_type elts)) << \"}\" in \n            if packed then \"<\" << s << \">\" else s\n          | Named_t x => x\n          | Opaque_t => \"opaque\"\n          | Pointer_t 0 t => show_type t << \" *\"\n          | Pointer_t n t => show_type t << \"addrspace(\" << show n << \") *\"\n          | Vector_t n t => \"<\" << show n << \" x \" << show_type t << \">\"\n        end.\n    \n    Global Instance Show_constant : Show constant :=\n      fix show_constant c := \n        match c return showM with \n          | True_c => \"true\" \n          | False_c => \"false\" \n          | Int_c i => show i\n          | Float_c s => s\n          | Null_c =>  \"null\"\n          | Global_c v => v \n          | Undef_c => \"undef\"\n          | Zero_c => \"zeroinitializer\"\n          | Struct_c cs => \"{\" << sepBy \", \" (List.map show_constant cs) << \"}\"\n          | Array_c cs => \"[\" << sepBy \", \" (List.map show_constant cs) << \"]\"\n          | Vector_c cs => \"<\" << sepBy \", \" (List.map show_constant cs) << \">\"\n          | Metastring_c s => \"!\" << quoted s\n          | Metadata_c cs => \"!{\" << sepBy \", \" (List.map show_constant cs) << \"}\"\n          | Ptrtoint_c t1 c t2 => \"ptrtoint (\" << (show t1) << \" \" << (show_constant c) << \" to \" << (show t2) << \")\"\n          | Inttoptr_c t1 c t2 => \"inttoptr (\" << (show t1) << \" \" << (show_constant c) << \" to \" << (show t2) << \")\"\n          | Bitcast_c t1 c t2 => \"bitcast (\" << (show t1) << \" \" << (show_constant c) << \" to \" << (show t2) << \")\"\n        end.\n    \n    Global Instance Show_value : Show value :=\n      fun v =>\n        match v with \n          | Local x => \"%\" << x\n          | Global x => \"@\" << x\n          | AnonLocal n => \"%\" << show n\n          | AnonGlobal n => \"@\" << show n\n          | Constant c => show c\n        end.\n\n    Global Instance Show_cond : Show cond :=\n      fun c =>\n        match c with \n          | Eq => \"eq\" | Ne => \"ne\" | Ugt => \"ugt\" | Uge => \"uge\" | Ult => \"ult\" | Ule => \"ule\" \n          | Sgt => \"sgt\" | Sge => \"sge\" | Slt => \"slt\" | Sle => \"sle\"\n        end.\n\n    Global Instance Show_fcond : Show fcond :=\n      fun f =>\n        match f with \n          | False_fc => \"false\" | Oeq_fc => \"oeq\" | Ogt_fc => \"ogt\" | Oge_fc => \"oge\" | Olt_fc => \"olt\"\n          | Ole_fc => \"ole\" | One_fc => \"one\" | Ord_fc => \"ord\" | Ueq_fc => \"ueq\" | Ugt_fc => \"ugt\"\n          | Uge_fc => \"uge\" | Ult_fc => \"ult\" | Ule_fc => \"ule\" | Une_fc => \"une\" | Uno_fc => \"uno\"\n          | True_fc => \"true\"\n        end.\n\n    Definition option_show (T : Type) (f : T -> showM) (o : option T) : showM :=\n      match o with\n        | None => empty\n        | Some x => f x \n      end.\n    \n    Global Instance Show_option (T : Type) {S : Show T} : Show (option T) :=\n      fun x => option_show show x.\n\n    Definition show_fn_header (drop_vars:bool) (fh:fn_header) : showM :=\n      show (linkage_fh fh) << \" \" <<\n      show (visibility_fh fh) << \" \" <<\n      show (cconv_fh fh) << \" \" <<\n      (if (unnamed_addr_fh fh) then \"unnamed_addr \" else empty) <<\n      show (return_type_fh fh) << \" \" <<\n      iter_show (map (fun x => show x << \" \") (return_type_attrs_fh fh)) <<\n      \"@\" << name_fh fh << \"(\" <<\n      sepBy \", \"\n            (map (fun (p : type * var * list param_attr) => \n              let '(t, x, attrs) := p in\n              show t <<\n              (if drop_vars then empty else \" %\"%string << x) <<\n              iter_show (map (fun x => show x << \" \") attrs))\n              (args_fh fh)) <<\n      \") \" <<\n      iter_show (map (fun x => show x << \" \") (attrs_fh fh)) <<\n      option_show (fun s : string => \", section \" << quoted s << \" \") (section_fh fh) <<\n      option_show (fun n => \", align \" << show n << \" \") (align_fh fh) <<\n      option_show (fun s : string => \"gc \" << quoted s << \" \") (gc_fh fh).\n\n    Definition show_arith(opcode:string)(nuw nsw:bool)(ty:type)(op1 op2:value) : showM := \n      opcode << \" \" << flag nuw \"nuw \" << flag nsw \"nsw \" << show ty << \" \" <<\n      show op1 << \", \" << show op2.\n\n    Definition show_binop(opcode:string)(ty:type)(op1 op2:value) : showM := \n      show_arith opcode false false ty op1 op2.\n\n    Definition show_logical(opcode:string)(ex:bool)(ty:type)(op1 op2:value) : showM := \n      opcode << \" \" << flag ex \"exact \" << show ty << \" \" << show op1 << \", \" << show op2.\n    \n    Definition show_conv(opcode:string)(ty1:type)(op:value)(ty2:type) : showM := \n      opcode << \" \" << show ty1 << \" \" << show op << \" to \" << show ty2.\n\n    Definition show_alloca (ty : type) (opttynum : option (type * nat)) (optalign : option nat) : showM := \n      \"alloca \" << show ty <<\n      match opttynum return showM with \n        | None => \"\" \n        | Some (ty,n) => \", \" << show ty << \" \" << show n\n      end <<\n      match optalign return showM with\n        | None => \"\" \n        | Some n => \", align \" << show n\n      end.\n    \n    Definition show_call (tail : bool) (conv : option cconv) (ret_attrs : list param_attr)\n      (ty : type) (fnptrty : option type) (fnptr : value) (args : list (type * value * list param_attr)) (fnattrs : list fn_attr) : showM :=\n      flag tail \"tail \" << \"call \" << option_show show conv << \" \" <<\n      sepBy \" \" (List.map show ret_attrs) << \" \" <<\n      show ty << \" \" << option_show show fnptrty << \n      show fnptr << \"(\" <<\n      (sepBy \", \" (List.map (fun x => match x with | (t,v,a) => \n                                        (show t) << \" \" << (show v) << \n                                        (sepBy \" \" (List.map show a))\n                                      end) args)) \n      << \") \" << sepBy \" \" (List.map show fnattrs).\n\n\n    Global Instance Show_exp : Show exp :=\n    { show := fun e =>\n        match e with \n          | Add_e nuw nsw ty op1 op2 => show_arith \"add\" nuw nsw ty op1 op2\n          | Fadd_e ty op1 op2 => show_binop \"fadd\" ty op1 op2\n          | Sub_e nuw nsw ty op1 op2 => show_arith \"sub\" nuw nsw ty op1 op2\n          | Fsub_e ty op1 op2 => show_binop \"fsub\" ty op1 op2\n          | Mul_e nuw nsw ty op1 op2 => show_arith \"mul\" nuw nsw ty op1 op2\n          | Fmul_e ty op1 op2 => show_binop \"fmul\" ty op1 op2\n          | Udiv_e ex ty op1 op2 => show_logical \"udiv\" ex ty op1 op2\n          | Sdiv_e ex ty op1 op2 => show_logical \"sdiv\" ex ty op1 op2\n          | Fdiv_e ty op1 op2 => show_binop \"fdiv\" ty op1 op2\n          | Urem_e ty op1 op2 => show_binop \"urem\" ty op1 op2\n          | Srem_e ty op1 op2 => show_binop \"srem\" ty op1 op2\n          | Frem_e ty op1 op2 => show_binop \"frem\" ty op1 op2\n          | Shl_e nuw nsw ty op1 op2 => show_arith \"shl\" nuw nsw ty op1 op2\n          | Lshr_e ex ty op1 op2 => show_logical \"lshr\" ex ty op1 op2\n          | Ashr_e ex ty op1 op2 => show_logical \"ashr\" ex ty op1 op2\n          | And_e ty op1 op2 => show_binop \"and\" ty op1 op2\n          | Or_e ty op1 op2 => show_binop \"or\" ty op1 op2\n          | Xor_e ty op1 op2 => show_binop \"xor\" ty op1 op2\n          | Extractvalue_e ty op n ns => \n            \"extractvalue \" << show ty << \" \" << show op << \", \" <<\n            sepBy \", \" (List.map show (n::ns))\n          | Insertvalue_e ty1 op1 ty2 op2 n ns =>\n            \"insertvalue \" << show ty1 << \" \" << show op1 << \", \" <<\n            show ty2 << \" \" << show op2 << \", \" <<\n            sepBy \", \" (List.map show (n::ns))\n          | Alloca_e ty opttynum optalign => show_alloca ty opttynum optalign\n          | Load_e atomic volatile ty pointer align nontemporal invariant singlethread => \n            (* fixme: just doing the simple stuff here *)\n           \"load \" << flag atomic \"atomic \" << flag volatile \"volatile \" <<\n            show ty << \" \" << show pointer << \" \" << flag singlethread \"singlethread \" <<\n            match align return showM with\n              | None => \"\"\n              | Some n => \", align \" << show n\n            end\n          | Getelementptr_e inbounds ty v indexes =>\n            \"getelementptr \" << (flag inbounds \"inbounds \") << (show ty) << \" \" << \n            (sepBy \", \" ((show v)::\n              (List.map (fun p => (show (fst p)) << \" \" << (show (snd p))) indexes)))\n          | Trunc_e ty1 v ty2 => show_conv \"trunc\" ty1 v ty2 \n          | Zext_e ty1 v ty2 => show_conv \"zext\" ty1 v ty2 \n          | Sext_e ty1 v ty2 => show_conv \"sext\" ty1 v ty2 \n          | Fptrunc_e ty1 v ty2 => show_conv \"fptrunc\" ty1 v ty2 \n          | Fpext_e ty1 v ty2 => show_conv \"fpext\" ty1 v ty2 \n          | Fptoui_e ty1 v ty2 => show_conv \"fptoui\" ty1 v ty2 \n          | Fptosi_e ty1 v ty2 => show_conv \"fptosi\" ty1 v ty2 \n          | Uitofp_e ty1 v ty2 => show_conv \"uitofp\" ty1 v ty2 \n          | Sitofp_e ty1 v ty2 => show_conv \"sitofp\" ty1 v ty2 \n          | Ptrtoint_e ty1 v ty2 => show_conv \"ptrtoint\" ty1 v ty2 \n          | Inttoptr_e ty1 v ty2 => show_conv \"inttoptr\" ty1 v ty2 \n          | Bitcast_e ty1 v ty2 => show_conv \"bitcast\" ty1 v ty2 \n          | Icmp_e cond ty v1 v2 => \"icmp \" << (show cond) << \" \" << (show ty) <<\n            (show v1) << \", \" << (show v2)\n          | Fcmp_e cond ty v1 v2 => \"fcmp \" << (show cond) << \" \" << (show ty) <<\n            (show v1) << \", \" << (show v2)\n          | Phi_e ty vls => \n            \"phi \" << show ty << \" \" << \n            sepBy \", \" (List.map (fun p : (value * label) => \"[ \" << show (fst p) << \", %\" << (snd p) << \" ]\") vls)\n          | Select_e ty1 v1 ty2 v2 ty3 v3 => \n            \"select \" << (show ty1) << \" \" << (show v1) << \", \" << \n            (show ty2) << \" \" << (show v2) << \", \" << \n            (show ty3) << \" \" << (show v3)\n          | Call_e tail conv ret_attrs ty fnptrty fnptr args fnattrs =>\n            show_call tail conv ret_attrs ty fnptrty fnptr args fnattrs\n        end }.\n\n    Global Instance Show_instr : Show instr :=\n      fun i => \n        match i with \n          | Comment_i s => \"; \" << s\n          | Ret_i vopt => \n            \"ret \" << \n            option_show (fun p => show (fst p) << \" \" << show (snd p)) vopt\n          | Br_cond_i v l1 l2 => \n            \"br i1 \" << show v << \", label %\" << l1 << \", label %\" << l2\n          | Br_uncond_i l => \n            \"br label %\"<< l\n          | Switch_i t v def arms => \n            \"switch \" << show t << \" \" << show v << \", label %\" << def << \" [\" <<\n            sepBy \" \" (List.map (fun p : type * Z * label => \n              let '(t,i,l) := p in\n              show t << \" \" << show i << \", label %\" << l) arms) << \" ]\"\n          | Resume_i t v => \n            \"resume \" << show t << \" \" << show v\n          | Unreachable_i => \"unreachable\"\n          | Assign_i (Some x) e => show x << \" = \" << show e\n          | Assign_i None e => show e\n          | Store_i atomic volatile ty v ptrty pointer align nontemporal singlethread => \n            (* fix -- doesn't do nontemporal or ordering *)\n            \"store \" << flag atomic \"atomic \" << flag volatile \"volatile \" << show ty << \" \" <<\n            show v << \", \" << show ptrty << \" \" << show pointer << \" \" <<\n            flag singlethread \"singlethread \" << \n            option_show (fun n => \", align \" << show n << \" \") align\n        end.\n\n    Global Instance Show_block : Show block :=\n      fun b =>\n        match fst b with\n          | None => \"  \"\n          | Some l =>\n            l << \":\" << chr_newline << \"  \"\n        end \n        << indent \"  \" (sepBy Char.chr_newline (map show (snd b))).\n\n    Global Instance Show_topdecl : Show topdecl :=\n      fun t =>\n        match t return showM with \n          | Global_d x a l u c t v s al => \n            x << \" = \" <<\n            option_show (fun n => \"addrspace(\" << show n << \")\") a <<\n            option_show show l <<\n            (if u then \"unnamed_addr \" else empty) <<\n            (if c then \"constant \" else empty) <<\n            show t << \" \" << \n            show v << \" \" <<\n            option_show (fun s : string => \", section \" << quoted s << \" \") s <<\n            option_show (fun n => \", align \" << show n << \" \") al <<\n            chr_newline \n          | Define_d fh bs => \"define \" <<\n            show_fn_header false fh << \" {\" << indent \"  \" (chr_newline << sepBy Char.chr_newline (map show bs)) << chr_newline << \"}\" << chr_newline\n          | Declare_d fh => \"declare \" << show_fn_header true fh << chr_newline\n          | Alias_d x l v t e => \n            x << \" = alias \" << \n            show l <<\n            show v <<\n            show t << \" \" << \n            show e << chr_newline\n          | Metadata_d x cs => \n            x << \" = metadata !{\" << sepBy \", \" (List.map show cs) << \n            \"}\" << chr_newline\n        end.\n\n    Global Instance Show_module : Show module :=\n      fun m => sepBy Char.chr_newline (map show m).\n    \n    Definition string_of_module (m : module) : string := runShow (show m) \"\".\n    Definition string_of_topdecl (t : topdecl) : string := runShow (show t) \"\".\n    Definition string_of_fn_header (b : bool) (h : fn_header) : string := runShow (show_fn_header b h) \"\".\n\n  End Printing.\nEnd LLVM.\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/LLVM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.1871541476069538}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import common_predicates.\nRequire Import sll_append.\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 sll_append_spec :=\n  DECLARE _sll_append\n   WITH x1: val, r: val, x2: val, s2: (list Z), _alpha_526: sll_card, _alpha_525: sll_card, s1: (list Z)\n   PRE [ (tptr (Tunion _sslval noattr)), (tptr (Tunion _sslval noattr)) ]\n   PROP( is_pointer_or_null((x1 : val)); is_pointer_or_null((r : val)); is_pointer_or_null((x2 : val)) )\n   PARAMS(x1; r)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (x2 : val))] (r : val)); (sll (x1 : val) (s1 : list Z) (_alpha_525 : sll_card)); (sll (x2 : val) (s2 : list Z) (_alpha_526 : sll_card)))\n   POST[ tvoid ]\n   EX _alpha_527: sll_card,\n   EX y: val,\n   EX s: (list Z),\n   PROP( ((s : list Z) = ((s1 : list Z) ++ (s2 : list Z))); is_pointer_or_null((y : val)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (y : val))] (r : val)); (sll (y : val) (s : list Z) (_alpha_527 : sll_card))).\n\n\n\n\n\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [sll_append_spec]).\n\n\nLemma body_sll_append : semax_body Vprog Gprog f_sll_append sll_append_spec.\nProof.\n\nstart_function.\nssl_open_context.\nassert_PROP (isptr r). { entailer!. }\ntry rename x2 into x22.\nforward.\nforward_if.\n\n - {\nassert_PROP (_alpha_525 = sll_card_0) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card sll ssl_card_assert .\nassert_PROP (((x1 : val) = nullval)). { entailer!. }\nlet ssl_var := fresh in assert_PROP(s1 = ([] : list Z)) as ssl_var; try rewrite ssl_var in *. { entailer!. }\nforward; entailer!.\nExists (_alpha_526 : sll_card).\nExists (x22 : val).\nExists (([] : list Z) ++ (s2 : list Z)).\nssl_entailer.\n\n}\n - {\nassert_PROP (exists _alpha_524, _alpha_525 = sll_card_1 _alpha_524) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card sll ssl_card_assert _alpha_524x1.\nassert_PROP ((~ ((x1 : val) = nullval))). { entailer!. }\nIntros vx1 s1x1 nxtx1.\nlet ssl_var := fresh in assert_PROP(s1 = (([(vx1 : Z)] : list Z) ++ (s1x1 : list Z))) as ssl_var; try rewrite ssl_var in *. { entailer!. }\ntry rename vx1 into vx12.\nforward.\ntry rename nxtx1 into nxtx12.\nforward.\nassert_PROP(is_pointer_or_null((nxtx12 : val))). { entailer!. }\nassert_PROP(is_pointer_or_null((r : val))). { entailer!. }\nassert_PROP(is_pointer_or_null((x22 : val))). { entailer!. }\nforward_call ((nxtx12 : val), (r : val), (x22 : val), (s2 : list Z), (_alpha_526 : sll_card), (_alpha_524x1 : sll_card), (s1x1 : list Z)).\nlet ret := fresh vret in Intros ret; destruct ret as [[_alpha_5271 y1] s3].\nassert_PROP(is_pointer_or_null((y1 : val))). { entailer!. }\nlet ssl_var := fresh in assert_PROP(s3 = ((s1x1 : list Z) ++ (s2 : list Z))) as ssl_var; try rewrite ssl_var in *. { entailer!. }\ntry rename y1 into y12.\nforward.\nforward.\nforward.\nforward; entailer!.\nExists (sll_card_1 (_alpha_5271 : sll_card) : sll_card).\nExists (x1 : val).\nExists ((([(vx12 : Z)] : list Z) ++ (s1x1 : list Z)) ++ (s2 : list Z)).\nssl_entailer.\nrewrite (unfold_sll_card_1 (_alpha_5271 : sll_card)) at 1.\nExists (vx12 : Z).\nExists ((s1x1 : list Z) ++ (s2 : list Z)).\nExists (y12 : val).\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/sll/verif_sll_append.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.18715414405383277}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nRequire Import ZArith Lia.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import seq_ext.\nRequire Import machine_int.\nRequire Import mips_seplog mips_frame mips_tactics.\nImport MachineInt.\n\nLocal Open Scope heap_scope.\nImport mips_bipl.expr_m.\nLocal Open Scope mips_expr_scope.\nImport mips_bipl.assert_m.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope mips_hoare_scope.\n\nLemma dom_heap_invariant0 s c s' : s -- c ----> s' ->\n  forall st h st' h', s = Some (st, h) -> s' = Some (st', h') ->\n    heap.dom h = heap.dom h'.\nProof.\ncase=> //; clear s c s'.\n- (* nop *) move=> s st h st' h' -> [] _ <- //.\n- (* add *) move=> st h rd rs rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- (* addi *) move=> st h rd rs rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- (* addiu *) move=> st h rt rs imm st_ h_ st' h' [] _ <- [] _ <- //.\n- (* addu *) move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* cmd_and *) move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* andi *) move=> st h rt rs imm st_ h_ st' h' [] _ <- [] _ <- //.\n- (* lw *) move=> st h rt off base p z Hp Hz st_ h_ st' h' [] _ <- [] _ <- //.\n- (* lwxs *) move=> st h rt idx base p z Hp Hz st_ h_ st' h' [] _ <- [] _ <- //.\n- (* maddu *) move=> st h rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* mfhi *) move=> st h rd st_ h_ st' h' [] _ <- [] _ <- //.\n- (* mflhxu *) move=> st h rd st_ h_ st' h' [] _ <- [] _ <- //.\n- (* mflo *) move=> st h rd st_ h_ st' h' [] _ <- [] _ <- //.\n- (* movn *) move=> st h rd rs rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- move=> st h _ _ rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- (* movz *) move=> st h rd rs rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- move=> st h _ _ rt Hcond st_ h_ st' h' [] _ <- [] _ <- //.\n- (* msubu *) move=> st h rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* mthi *) move=> st h rs st_ h_ st' h' [] _ <- [] _ <- //.\n- (* mtlo *) move=> st h rs st_ h_ st' h' [] _ <- [] _ <- //.\n- (* multu *) move=> st h rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* nor *) move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* cmd_or *) move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <- //.\n- (* sll *) move=> st h rx ry sa st_ h_ st' h' [] _ <- [] _ <- //.\n- (* sllv *) move=> st h rd rt rs st_ h_ st' h' [] _ <- [] _ <- //.\n- (* sltu *) move=> st h rd rt rs st_ h_ st' h' st'_ h'_ [] _ <- [] _ <- //.\n- (* sra *) by move=> st h rd rt sa st_ h_ st' h' [] _ <- [] _ <-.\n- (* srl *) by move=> st h rd rt sa st_ h_ st' h' [] _ <- [] _ <-.\n- (* srlv *) by move=> st h rd rt rs st_ h_ st' h' [] _ <- [] _ <-.\n- (* subu *) by move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <-.\n- (* sw *) move=> st h rt off base p Hp [z Hz] st_ h_ st'_ h'_ [] _ <- [] _ <-.\n  by rewrite heap.dom_upd_invariant.\n- (* xor *) by move=> st h rd rs rt st_ h_ st' h' [] _ <- [] _ <-.\n- (* xori *) by move=> st h rt rs imm st_ h_ st' h' [] _ <- [] _ <-.\nQed.\n\nLemma dom_heap_invariant' s c s' : s -- c ---> s' ->\n  forall st h st' h', s = Some (st, h) -> s' = Some (st', h') ->\n    heap.dom h = heap.dom h'.\nProof.\nelim=> //; clear s c s'.\n- (* cmd0 *) move=> s c s' H st he st' he' Hs Hs'.\n  by eapply dom_heap_invariant0; eauto.\n- (* seq *) move=> s s' s'' c d Hc IHc Hd IHd /= st he st'' he'' Hs Hs''.\n  destruct s' as [[st' he']|]; last first.\n    move/semop_prop_m.from_none : Hd => Hd.\n    by subst.\n  eapply trans_eq.\n  by eapply IHc; eauto.\n  by eapply IHd; eauto.\n- (* while true *) move=> [st h] s' s'' t c Ht Hc IH1 Hwhile IH2 st_ h_ st'' h'' [] _ <- Hs''.\n  destruct s' as [[st' h']|].\n  apply trans_eq with (heap.dom h').\n  by apply (IH1 _ _ _ _ (refl_equal _) (refl_equal _)).\n  eapply IH2; eauto.\n  destruct s'' => //.\n  by move/semop_prop_m.from_none : Hwhile.\n- (* while false *)  by move=> [st h] t _ Ht st_ h_ st' h' [] _ <- [] _ <-.\nQed.\n\nLemma dom_heap_invariant s h c s' h' : Some (s, h) -- c ---> Some (s', h') ->\n  heap.dom h = heap.dom h'.\nProof. intros. eapply dom_heap_invariant'; eauto. Qed.\n\nLemma reg_unchanged0 : forall (c : cmd0) st h st' h',\n  Some (st, h) -- c ----> Some (st', h') ->\n  forall x, x \\notin (mips_frame.modified_regs c) ->\n    [x]_st = [x]_st'.\nProof.\nelim.\n- move=> st h st' h'.\n  case/exec0_nop_inv=> X Y; by subst.\n- move=> rt rs imm st h st' h'.\n  case/exec0_add_inv.\n  + case=> H1 [] Hst' Hh'; subst => x /=.\n    rewrite negb_and orbC /=.\n    move/eqP => X.\n    by rewrite store.get_upd.\n  + by case.\n- move=> rt rs imm st h st' h'.\n  case/exec0_addi_inv.\n  + case=> H1 [] Hst' Hh'; subst => x /=.\n    rewrite negb_and orbC /=.\n    move/eqP => X.\n    by rewrite store.get_upd.\n  + by case.\n- move=> rt rs imm st h st' h'.\n  case/exec0_addiu_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rs rt st h st' h'.\n  case/exec0_addu_inv => Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rs rt st h st' h'.\n  case/exec0_and_inv => Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rt rs imm st h st' h'.\n  case/exec0_andi_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rt off base st h st' h'.\n  case/exec0_lw_inv.\n  move=> [p [Hp [z [Hz]]]] [] Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n  by case.\n- (* lwxs *) move=> rt idx base st h st' h'.\n  case/exec0_lwxs_inv.\n  move=> [p [Hp [z [Hz]]]] [] Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n  by case.\n- move=> rs rt st h st' h'.\n  case/exec0_maddu_inv=> Hst' Hh'; subst => x /= _.\n  by rewrite store.get_maddu_op.\n- move=> rd st h st' h'.\n  case/exec0_mfhi_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd st h st' h'.\n  case/exec0_mflhxu_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  rewrite store.get_mflhxu_op.\n  by rewrite store.get_upd.\n- (* mflo *) move=> rd st h st' h'.\n  case/exec0_mflo_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- (* movn *) move=> rd rs rt st h st' h'.\n  case/exec0_movn_inv.\n  move=> [Hrt []] Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n  move=> [Hrt []] Hst' Hh'; by subst.\n- move=> rd rs rt st h st' h'.\n  case/exec0_movz_inv.\n  move=> [Hrt []] Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n  move=> [Hrt []] Hst' Hh'; by subst.\n- move=> rs rt st h st' h'.\n  case/exec0_msubu_inv=> Hst' Hh'; subst => x _.\n  by rewrite store.get_msubu_op.\n- move=> rs st h st' h'.\n  case/exec0_mthi_inv=> Hst' Hh'; subst => x _.\n  by rewrite store.get_mthi_op.\n- (* mtlo *) move=> rs st h st' h'.\n  case/exec0_mtlo_inv=> Hst' Hh'; subst => x _.\n  by rewrite store.get_mtlo_op.\n- move=> rs rt st h st' h'.\n  case/exec0_multu_inv=> Hst' Hh'; subst => x _.\n  by rewrite store.get_multu_op.\n- move=> rd rs rt st h st' h'.\n  case/exec0_nor_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rs rt st h st' h'.\n  case/exec0_or_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- (* sll *) move=> rx ry sa st h st' h'.\n  case/exec0_sll_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rt rs st h st' h'.\n  case/exec0_sllv_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rt rs st h st' h'.\n  case/exec0_sltu_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- (* sra *) move=> rd rt sa st h st' h'.\n  case/exec0_sra_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- (* srl *) move=> rd rt sa st h st' h'.\n  case/exec0_srl_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rt rs st h st' h'.\n  case/exec0_srlv_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rd rt rs st h st' h'.\n  case/exec0_subu_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rt off base st h st' h'.\n  case/exec0_sw_inv.\n  move=> [p [Hp [z [Hz]]]] [] Hst' Hh'; by subst.\n  by case.\n- (* xor *) move=> rd rs rt st h st' h'.\n  case/exec0_xor_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\n- move=> rt rs imm st h st' h'.\n  case/exec0_xori_inv=> Hst' Hh'; subst => x /=.\n  rewrite negb_and orbC /=.\n  move/eqP => X.\n  by rewrite store.get_upd.\nQed.\n\nLemma reg_unchanged' s c s' : (s -- c ---> s') ->\n  forall x st h st' h', ~ List.In x (modified_regs c) ->\n    s = Some (st, h) -> s' = Some (st', h') ->\n    store.get x st = store.get x st'.\nProof.\nelim => //; clear s c s'.\n- (* cmd0 *) move=> s c s' H x st h st' h' Hx Hs Hs'.\n  subst.\n  eapply reg_unchanged0.\n  apply H.\n  apply/negP.\n  by move/inP.\n- (* seq *) move=> s s' s'' c d Hc IHc Hd IHd x st h st'' h'' Hx Hs Hs''.\n  destruct s' as [[st' h']|]; last first.\n    move/semop_prop_m.from_none : Hd => Hd; by subst.\n  eapply trans_eq.\n  eapply IHc.\n  contradict Hx.\n  rewrite /=.\n  apply List.in_or_app; by left.\n  apply Hs.\n  reflexivity.\n  eapply IHd.\n  contradict Hx.\n  rewrite /=.\n  apply List.in_or_app; by right.\n  reflexivity.\n  by apply Hs''.\n- (* if true *) move=> [s h] s' t c d Ht Hc IH x st he st' he' Hx [] X Y Hs'; subst.\n  eapply IH.\n  contradict Hx.\n  rewrite /=.\n  apply List.in_or_app; by left.\n  reflexivity.\n  reflexivity.\n- (* if false *) move=> [s h] s' t c d Ht Hc IH x st he st' he' Hx [] X Y Hs'; subst.\n  eapply IH.\n  contradict Hx.\n  rewrite /=.\n  apply List.in_or_app; by right.\n  reflexivity.\n  reflexivity.\n- (* while true *) move=> [s h] s' s'' t c Ht Hc IHc Hwhile IHwhile x st he st'' he'' Hx [] X Y Hs''; subst.\n  destruct s' as [[st' he']|]; last first.\n    move/semop_prop_m.from_none : Hwhile => Hwhile; by subst.\n  eapply trans_eq.\n  eapply IHc.\n  done.\n  reflexivity.\n  reflexivity.\n  eapply IHwhile.\n  done.\n  reflexivity.\n  reflexivity.\n- (* while false *) move=> [s h] t c Ht x st he st' he' Hx [] X Y [] U V; subst.\n  by subst.\nQed.\n\nLemma reg_unchanged : forall st h c st' h',\n  Some (st, h) -- c ---> Some (st', h') ->\n  forall x, ~ List.In x (modified_regs c) ->\n    store.get x st = store.get x st'.\nProof. intros. eapply reg_unchanged'; eauto. Qed.\n\nLtac Reg_unchanged :=\n  match goal with\n    | Hid : (Some (?st1, ?h1) -- ?c ---> Some (?st2, ?h2))%mips_cmd \n     |- ( [ ?r1 ]_ ?st1 = [ ?r2 ]_ ?st2 )%mips_expr =>\n        apply reg_unchanged with h1 c h2; [exact Hid | idtac]\n    | Hid : WMIPS_Semop.exec (Some (?st1, ?h1)) ?c (Some (?st2, ?h2))\n      |- ( [ ?r1 ]_ ?st1 = [ ?r2 ]_ ?st2 )%mips_expr =>\n        apply reg_unchanged with h1 c h2; [exact Hid | idtac]\n  end.\n\nLemma triple_exec_proj0 (P : assert) c (Q : assert) :\n  (mips_seplog.hoare0 P c Q) ->\n    forall st h st' h' d,\n      P st (heap.proj h d) ->\n      (Some (st, h) -- c ----> Some (st', h')) ->\n      (Some (st, heap.proj h d) -- c ----> Some (st', heap.proj h' d)).\nProof.\nelim=> //; clear P c Q.\n- move=> P st h st' h' d _.\n  case/exec0_nop_inv => -> ->; by constructor.\n- move=> Q rs rt rd st h st' h' d _.\n  case/exec0_add_inv.\n  + case=> Hcond [] -> ->; by constructor.\n  + by case.\n- move=> Q rt rs imm st h st' h' d _.\n  case/exec0_addi_inv.\n  + case=> Hcond [] -> ->; by constructor.\n  + by case.\n- move=> Q rt rs imm st h st' h' d _.\n  case/exec0_addiu_inv=> -> ->; by constructor.\n- move=> Q rs rt rd st h st' h' d _.\n  case/exec0_addu_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_and_inv => -> ->; by constructor.\n- move=> Q rt rs imm st h st' h' d _.\n  case/exec0_andi_inv => -> ->; by constructor.\n- move=> Q rt off base st h st' h' d Hpre.\n  case/exec0_lw_inv.\n  + case=> p [] Hp [] z [] Hz [] -> ->.\n    apply exec0_lw with p => //.\n    rewrite heap.get_proj //.\n    rewrite /mips_seplog.wp_lw in Hpre.\n    case: Hpre => p' [] Hp' [] z' [] Hz' HQ.\n    have ? : p = p' by rewrite [u2Z _]/= in Hp'; lia.\n    subst p'.\n    apply/seq_ext.inP.\n    move/heap.get_Some_in_dom : Hz'; move/seq_ext.inP.\n    move: (heap.inc_dom_proj d h).\n    move/seq_ext.incP.\n    by apply.\n  + by case.\n- move=> rt idx base Q st h st' h' d Hpre.\n  case/exec0_lwxs_inv.\n  + case=> p [] Hp [] z [] Hz [] -> ->.\n    apply exec0_lwxs with p => //.\n    rewrite heap.get_proj //.\n    rewrite /mips_seplog.wp_lwxs in Hpre.\n    case: Hpre => p' [] Hp' [] z' [] Hz' HQ.\n    have ? : p = p' by rewrite [u2Z _]/= in Hp'; lia.\n    subst p'.\n    apply/seq_ext.inP.\n    move/heap.get_Some_in_dom : Hz'; move/seq_ext.inP.\n    move: (heap.inc_dom_proj d h).\n    move/seq_ext.incP.\n    by apply.\n  + by case.\n- move=> Q rs rt st h st' h' d _.\n  case/exec0_maddu_inv=> -> ->; by constructor.\n- move=> Q rd st h st' h' d _.\n  case/exec0_mfhi_inv=> -> ->; by constructor.\n- move=> rd Q st h st' h' d _.\n  case/exec0_mflhxu_inv=> -> ->; by constructor.\n- move=> Q rd st h st' h' d _.\n  case/exec0_mflo_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_movn_inv.\n  + case=> Htest [] -> ->; by apply exec0_movn_true.\n  + case=> Htest [] -> ->; by apply exec0_movn_false.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_movz_inv.\n  + case=> Htest [] -> ->; by apply exec0_movz_true.\n  + case=> Htest [] -> ->; by apply exec0_movz_false.\n- move=> Q rs rt st h st' h' d _.\n  case/exec0_msubu_inv=> -> ->; by constructor.\n- move=> Q rs st h st' h' d _.\n  case/exec0_mthi_inv=> -> ->; by constructor.\n- move=> Q rs st h st' h' d _.\n  case/exec0_mtlo_inv => -> ->; by constructor.\n- move=> Q rs rt st h st' h' d _.\n  case/exec0_multu_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_nor_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_or_inv=> -> ->; by constructor.\n- move=> Q rx ry sa st h st' h' d _.\n  case/exec0_sll_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_sllv_inv=> -> ->; by constructor.\n- move=> Q rd rs rt st h st' h' d _.\n  case/exec0_sltu_inv=> -> ->; by constructor.\n- (* sra *) move=> Q rd rt sa st h st' h' d _.\n  case/exec0_sra_inv=> -> ->; by constructor.\n- move=> Q rd rt sa st h st' h' d _.\n  case/exec0_srl_inv=> -> ->; by constructor.\n- move=> Q rd rt rs st h st' h' d _.\n  case/exec0_srlv_inv=> -> ->; by constructor.\n- move=> Q rs rt rd st h st' h' d _.\n  case/exec0_subu_inv=> -> ->; by constructor.\n- move=> rt off base Q st h st' h' d Hpre.\n  case/exec0_sw_inv.\n  + case=> p [] Hp [] z [] Hz [] -> ->.\n    rewrite heap.proj_upd.\n    apply exec0_sw => //.\n    exists z.\n    rewrite heap.get_proj //.\n    rewrite /mips_seplog.wp_sw in Hpre.\n    case: Hpre => p' [] Hp' [] [] z' Hz' HQ.\n    have ? : p = p' by rewrite [u2Z _]/= in Hp'; lia.\n    subst p'.\n    apply/seq_ext.inP.\n    move/heap.get_Some_in_dom : Hz'; move/seq_ext.inP.\n    move: (heap.inc_dom_proj d h).\n    move/seq_ext.incP.\n    by apply.\n  + by case.\n- move=> Q rd rs rt st h st' h' d Hpre.\n  case/exec0_xor_inv=> -> ->; by constructor.\n- move=> Q rt rs imm st h st' h' d Hpre.\n  case/exec0_xori_inv=> -> ->; by constructor.\nQed.\n\nLemma triple_exec_proj P c Q :\n  mips_seplog.WMIPS_Hoare.hoare P c Q ->\n  forall d st h st' h',\n    P st (heap.proj h d) ->\n    Some (st, h) -- c ---> Some (st', h') ->\n    Some (st, heap.proj h d) -- c ---> Some (st', heap.proj h' d).\nProof.\nelim=> //; clear P c Q.\n- move=> P Q c Htriple d st h st' h' HP Hc.\n  apply while.exec_cmd0.\n  eapply triple_exec_proj0; eauto.\n  by inversion Hc.\n- move=> P Q R c1 c2 Hc1 IHc1 Hc2 IHc2 d st h st' h' HP.\n  case/semop_prop_m.exec_seq_inv.\n  case.\n  + case=> st'' h'' [] Hc1' Hc2'.\n    apply while.exec_seq with (Some (st'', heap.proj h'' d)).\n    apply IHc1 => //.\n    apply IHc2 => //.\n    move/hoare_prop_m.soundness : Hc1 => Hc1.\n    rewrite /hoare_semantics in Hc1.\n    move/Hc1 : (HP) => HP'.\n    case: HP' => _ HP'.\n    apply HP' => //.\n    by apply IHc1.\n  + case=> _.\n    by move/semop_prop_m.from_none.\n- move=> P P' Q Q' c HQ'Q HPP' Hc IHc s st h st' h' HP Hexec_c.\n  apply IHc; last by [].\n  by apply HPP'.\n- move=> P t c Htriple_c IHc d st h st' h' HP.\n  move Hs : (Some (st, h)) => s.\n  move Hs' : (Some (st', h')) => s'.\n  move Hwhile : (while.while t c) => C.\n  move=> Hexec_C.\n  move: Hexec_C P t c Htriple_c IHc d st h st' h' HP Hs' Hs Hwhile.\n  elim=> //; clear s s' C.\n  + move=> [s h] s' s'' t c Ht H_exec_c IH_exec_c H_exec_while IH_exec_while P t_ c_ Hhoare_c_ IH d s_ h_ st'' h'' HP.\n    destruct s' as [[s' h']|].\n    * move=> Hs'' [] X Y.\n      subst s_ h_.\n      case=> X Y; subst t_ c_.\n      case/boolP : (eval_b t s) => X.\n      - apply while.exec_while_true with (Some (s', heap.proj h' d)) => //.\n        by apply IH.\n        apply: (IH_exec_while _ _ _ Hhoare_c_) => //.\n        move/hoare_prop_m.soundness in Hhoare_c_.\n        rewrite /hoare_semantics in Hhoare_c_.\n        apply: (proj2 (Hhoare_c_ _ _ (conj HP X))).\n        by apply IH.\n      - by rewrite Ht in X.\n    * move/semop_prop_m.from_none : H_exec_while.\n      by move=> ->.\n  + move=> [s h] t c Ht P t_ c_ Hhoare_c IH d st_ h_ st' h' HP.\n    case=> X Y; subst.\n    case=> X Y; subst.\n    case=> X Y; subst.\n    by apply while.exec_while_false.\n- move=> P Q t c1 c2.\n  move=> Hhoare_c1 IHc1 Hhoare_c2 IHc2 d st h st' h' HP.\n  case/boolP : (eval_b t st) => X.\n  + move/(semop_prop_m.exec_ifte_true_inv _ _ _ _ _ _ X) => Hc1.\n    apply while.exec_ifte_true => //; by apply IHc1.\n  + move/(semop_prop_m.exec_ifte_false_inv _ _ _ _ _ _ X) => Hc2.\n    apply while.exec_ifte_false => //; by apply IHc2.\nQed.\n\nLemma exec_deter_proj0 s (c : cmd0) s' : s -- c ----> s'  ->\n  forall st h st' h' d st'_proj h'_proj,\n    s = Some (st, h) -> s' = Some (st',h') ->\n    Some (st, heap.proj h d) -- c ----> Some (st'_proj, h'_proj) ->\n    st'_proj = st' /\\ h'_proj = heap.proj h' d /\\ h \\D\\ d = h' \\D\\ d.\nProof.\ncase=> //; clear s c s'.\n- move=> s st h st' h' d st'_proj h'_proj [] -> [] X Y.\n  subst st' h'; by case/exec0_nop_inv.\n- move=> st h rd rs rt Hcond st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  case/exec0_add_inv.\n  + by case=> _ [].\n  + tauto.\n- move=> st h rt rs imm Hcond st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  case/exec0_addi_inv.\n  + by case=> _ [].\n  + tauto.\n- move=> st h rt rs imm st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_addiu_inv.\n- move=> st h rt rs imm st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_addu_inv.\n- move=> st h rd rs rt st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_and_inv.\n- move=> st h rt rs imm st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_andi_inv.\n- move=> st h rt off base p z Hp Hz st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  case/exec0_lw_inv.\n  + case=> p_ [Hp_ [z_ [Hz_ []] ]] Heq.\n    split=> //.\n    have {Hp_}X : p = p_ by lia. subst p_.\n    move/heap.get_Some_in_dom : (Hz_); move/seq_ext.inP.\n    move/seq_ext.incP : (heap.inc_dom_proj d h) => X; move/X => p_d.\n    rewrite heap.get_proj // in Hz_; last by apply/seq_ext.inP.\n    rewrite Heq.\n    f_equal.\n    rewrite Hz in Hz_.\n    by case: Hz_.\n  + by case.\n- move=> st h rt ids base p z Hp Hz st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  case/exec0_lwxs_inv.\n  + case=> p_ [] Hp_ [] z_ [] Hz_ [] -> ->.\n    split=> //.\n    have Hpp_ : p = p_ by lia.\n    subst p_.\n    move/heap.get_Some_in_dom : (Hz_); move/seq_ext.inP.\n    move/seq_ext.incP : (heap.inc_dom_proj d h) => X; move/X => Hp_in_d.\n    rewrite heap.get_proj // in Hz_; last by apply/seq_ext.inP.\n    rewrite Hz in Hz_; by case : Hz_ => ->.\n  + by case.\n- move=> st h rs rt st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_maddu_inv=> -> ->.\n- move=> st h rd st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_mfhi_inv=> -> ->.\n- move=> st h rd st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_mflhxu_inv=> -> ->.\n- move=> st h rd st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_mflo_inv=> -> ->.\n- move=> st h rd rs rt Hcond st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  case/exec0_movn_inv.\n  + by case=> Hcond' [] -> ->.\n  + case; tauto.\n- move=> st h rd rs rt Hcond st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  case/exec0_movn_inv.\n  + case; tauto.\n  + by case=> Hcond' [] -> ->.\n- move=> st h rd rs rt Hcond st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  case/exec0_movz_inv.\n  + by case=> Hcond' [] -> ->.\n  + case; tauto.\n- move=> st h rd rs rt Hcond st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  case/exec0_movz_inv.\n  + case; tauto.\n  + by case=> Hcond' [] -> ->.\n- move=> st h rs rt st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_msubu_inv=> -> ->.\n- move=> st h rs st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_mthi_inv=> -> ->.\n- move=> st h rs st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_mtlo_inv=> -> ->.\n- move=> st h rs rt st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_multu_inv=> -> ->.\n- move=> st h rd rs rt st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_nor_inv=> -> ->.\n- move=> st h rd rs rt st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_or_inv=> -> ->.\n- move=> st h rx ry sa st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_sll_inv=> -> ->.\n- move=> st h rd rt rs st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_sllv_inv=> -> ->.\n- move=> st h rd rs rt st_ h_ st' h' st'_ h'_ d st'_proj h'_proj [] <- <- [] <- <-.\n  case/exec0_sltu_inv=> -> ->.\n  by rewrite -h_.\n- (* sra *) move=> st h rd rt sa st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_sra_inv=> -> ->.\n- (* srl *) move=> st h rd rt sa st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_srl_inv=> -> ->.\n- move=> st h rd rt rs st_ h_ st' h' d st'_proj h'_proj [] <- <- [] <- <-.\n  by case/exec0_srlv_inv=> -> ->.\n- move=> st h rt rs imm st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  by case/exec0_subu_inv.\n- (* sw *) move=> st h rt off base p HP [z Hz] st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'.\n  case/exec0_sw_inv.\n  (* no error *)\n  + case=> p_ [Hp_ [z_ [Hz_ []]]] Heq.\n    have {Hp_}X : p = p_ by lia. subst p_.\n    move/heap.get_Some_in_dom : (Hz_); move/seq_ext.inP.\n    move/seq_ext.incP : (heap.inc_dom_proj d h) => X; move/X => Hp_in_d.\n    rewrite heap.get_proj // in Hz_; last by apply/seq_ext.inP.\n    rewrite Hz in Hz_. case: Hz_ => ?; subst z_.\n    split; first by [].\n    split.\n    * by rewrite heap.proj_upd.\n    * rewrite heap.difs_upd //; by apply/seq_ext.inP.\n  + by case.\n- (* xor *) move=> st h rd rs rt st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_xor_inv.\n- (* xori *) move=> st h rt rs imm st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  case=> X Y; subst st' h'; by case/exec0_xori_inv.\nQed.\n\nLemma exec_deter_proj' s c s' : s -- c ---> s' ->\n  forall st h st' h' d st'_proj h'_proj,\n    s = Some (st, h) -> s' = Some (st', h') ->\n    Some (st, heap.proj h d) -- c ---> Some (st'_proj, h'_proj) ->\n    st' = st'_proj /\\ h'_proj = heap.proj h' d /\\ h \\D\\ d = h' \\D\\ d.\nProof.\nelim=> //; clear s c s'.\n- (* cmd0 *) move=> s c s' H st h st' h' d st'_proj h'_proj Hs Hs' Hc.\n  inversion Hc; subst.\n  move: (exec_deter_proj0 _ _ _ H st h st' h' d _ _ (refl_equal _) (refl_equal _) H2).\n  by case => H1 [h2 H3].\n- (* seq *) move=> s s'' s' c1 c2 Hc1 IHc1 Hc2 IHc2 st h st' h' d st'_proj h'_proj Hs Hs'.\n  subst s s'.\n  case/semop_prop_m.exec_seq_inv.\n  case.\n  + case=> st''_proj h''_proj [Hc1' Hc2'].\n    destruct s'' as [[st''_ h'']|].\n    - case : {IHc1}(IHc1 st h st''_ h'' d st''_proj h''_proj (refl_equal _) (refl_equal _) Hc1') => IHc1 [IHc1' IHc1''].\n      subst st''_ h''_proj.\n      case : {IHc2}(IHc2 st''_proj h'' st' h' d _ _ (refl_equal _) (refl_equal _) Hc2') => IHc2 [IHc2' IHc2''].\n      subst st'_proj h'_proj.\n      by rewrite IHc1'' IHc2''.\n    - by move/semop_prop_m.from_none : Hc2.\n  + case=> H1; by move/semop_prop_m.from_none.\n- (* if true *) move=> [st h] s' t c1 c2 Ht Hc IHc st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  move=> Hs'.\n  move=> H.\n  apply semop_prop_m.exec_ifte_true_inv in H; last by [].\n  by apply (IHc st h st' h' d _ _ (refl_equal _) Hs' H).\n- (* if false *) move=> [st h] s' t c1 c2 Ht Hc IHc st_ h_ st' h' d st'_proj h'_proj [] X Y; subst st_ h_.\n  move=> Hs'.\n  move=> H.\n  apply semop_prop_m.exec_ifte_false_inv in H; last by [].\n  by apply (IHc st h st' h' d _ _ (refl_equal _) Hs' H).\n- (* while true *) move=> [st h] s'' s' t c Ht Hc IHc Hwhile IHwhile st_ h_ st' h' d st'_proj h'_proj [] X Y.\n  subst st_ h_ => Hs' H.\n  apply semop_prop_m.exec_while_inv_true in H; last by [].\n  case : H => st''_proj [h''_proj [Hc' Hwhile']].\n  destruct s'' as [[st''_ h''_]|].\n  + move: {IHc}(IHc st h st''_ h''_ d st''_proj h''_proj (refl_equal _) (refl_equal _) Hc') => [IHc1 [IHc2 IHc3]].\n    subst st''_ h''_proj.\n    move: {IHwhile}(IHwhile st''_proj h''_ st' h' d _ _ (refl_equal _) Hs' Hwhile') => IHwhile.\n    split; first by tauto.\n    split; first by tauto.\n    rewrite IHc3; tauto.\n  + move/semop_prop_m.from_none in Hwhile; by subst.\n- (* while false *) move=> [st h] t c Ht st_ h_ st__ h__ d st'_proj h'_proj [] X Y.\n  subst st_ h_. move=> [] X Y.\n  subst st__ h__.\n  by case/semop_prop_m.exec_while_inv_false.\nQed.\n\nLemma exec_deter_proj : forall st h c st' h', Some (st, h) -- c ---> Some (st', h') ->\n  forall d st'_proj h'_proj,\n    Some (st, heap.proj h d) -- c ---> Some (st'_proj, h'_proj) ->\n    st' = st'_proj /\\ h'_proj = heap.proj h' d /\\ h \\D\\ d = h' \\D\\ d.\nProof.\nintros.\neapply exec_deter_proj'.\nby apply H.\nreflexivity.\nreflexivity.\nby apply H0.\nQed.\n\nDefinition is_sw (c : cmd0) : bool :=\n  match c with | sw _ _ _ => true | _ => false end.\n\n(* TODO: inelegant *)\nFixpoint contains_sw (c : @while.cmd cmd0 expr_b) : bool :=\n  match c with\n    | while.cmd_cmd0 c0 => is_sw c0\n    | c ; d => contains_sw c || contains_sw d\n    | while.ifte _ c d => contains_sw c || contains_sw d\n    | while.while _ c => contains_sw c\n  end.\n\nLemma no_sw_heap_invariant_cmd0 s (c : cmd0) s' :\n  (s -- c ----> s') ->\n  ~~ contains_sw c ->\n  forall st h st' h',\n    s = Some (st, h) -> s' = Some (st', h') ->\n    h = h'.\nProof.\nelim=> //; clear s c s'.\n- (* nop *) move=> s _ st he st' he' -> [] //.\n- (* add *) move=> s ha rd rs rt H _ st he st' he' [] X Y [] U V; by subst.\n- (* addi *) move=> s h rt rs imm H _ st he st' he' [] X Y [] U V; by subst.\n- (* addiu *) move=> s h rt rs imm _ st he st' he' [] X Y [] U V; by subst.\n- (* addu *) move=> s h rd rs rt _ st he st' he' [] X Y [] U V; by subst.\n- (* cmd_and *) move=> s h rd rs rt _ st he st' he' [] X Y [] U V; by subst.\n- (* andi *) move=> s h rd rs rt _ st he st' he' [] X Y [] U V; by subst.\n- (* lw *) move=> s h rt off base p z Hp Hz _ st he st' he' [] X Y [] U V; by subst.\n- (* lwxs *) move=> s h rt idx base p z Hp Hz _ st he st' he' [] X Y [] U V; by subst.\n- (* maddu *) move=> s h rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* mfhi *) move=> s h rd _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* mflhxu *) move=> s h rd _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* mflo *) move=> s h rd _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* movn *) move=> s h rd rs rt H _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* movn *) move=> s h rd rs rt H _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* movz *) move=> s h rd rs rt H _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* movz *) move=> s h rd rs rt H _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* msubu *) move=> s h rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* mthi *) move=> s h rs _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* mtlo *) move=> s h rs _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* multu *) move=> s h rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* nor *) move=> s h rd rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* or *) move=> s h rd rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* sll *) move=> s h rx ry sa _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* sllv *) move=> s h rd rt rs _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* sltu *) move=> s h rd rs rt flag H _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* sra *) by move=> s h rd rt sa _ s_ h_ st' h' [] _ <- [] _ <-.\n- (* srl *) by move=> s h rd rt sa _ s_ h_ st' h' [] _ <- [] _ <-.\n- (* srlv *) move=> s h rd rt rs _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* subu *) move=> s h rd rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* xor *) move=> s h rd rs rt _ s_ h_ st' h' [] _ <- [] _ <- //.\n- (* xori *) move=> s h rt rs imm _ s_ h_ st' h' [] _ <- [] _ <- //.\nQed.\n\nLemma no_sw_heap_invariant s c s' :\n  s -- c ---> s' -> ~~ contains_sw c ->\n  forall st h st' h', s = Some (st, h) -> s' = Some (st', h') ->\n    h = h'.\nProof.\nelim=> //; clear s c s'.\n- (* cmd0 *) move=> s c s' H Hcontains st he st' he' Hs Hs'.\n  eapply no_sw_heap_invariant_cmd0.\n  apply H.\n  done.\n  apply Hs.\n  apply Hs'.\n- (* seq *) move=> s s' s'' c d Hc IHc Hd IHd /= Hcontains st he st'' he'' Hs Hs''.\n  destruct s' as [[st' he']|]; last first.\n    move/semop_prop_m.from_none : Hd => Hd.\n    by subst.\n  eapply trans_eq.\n  eapply IHc.\n  apply/negP. move/orP : Hcontains. tauto.\n  apply Hs.\n  reflexivity.\n  eapply IHd.\n  apply/negP. move/orP : Hcontains. tauto.\n  reflexivity.\n  apply Hs''.\n- (* ifte true *) move=> [st h] s' t c1 c2 Ht Hc1 IHc1 Hcontains st_ h_ st' h' [] X Y.\n  subst st_ h_ => Hs'.\n  apply IHc1 with st st' => //.\n  move: Hcontains.\n  rewrite /= negb_or.\n  by case/andP.\n- (* ifte false *) move=> [st h] s' t c1 c2 Ht Hc2 IHc2 Hcontains st_ h_ st' h' [] X Y.\n  subst st_ h_ => Hs'.\n  apply IHc2 with st st' => //.\n  move: Hcontains.\n  rewrite /= negb_or.\n  by case/andP.\n- (* while true *) move=> [s h] s' s'' b c Hb Hc IHc Hwhile IHwhile Hcontains s_ h_ st'' h'' [] _ <- Hs''.\n  destruct s' as [[st' h']|].\n  eapply trans_eq.\n  eapply IHc => //.\n  eapply IHwhile => //.\n  apply Hs''.\n  subst s''.\n  by move/semop_prop_m.from_none : Hwhile.\n- (* while false *) move=> [s h] b c Hb Hcontains s_ h_ s__ h__.\n  case=> _ <-.\n  by case=> _ <-.\nQed.\n\nLemma safety_monotonicity0 (s : option state) (c : cmd0) (s' : option state) :\n   (s -- c ----> s') ->\n   forall (st : store.t) (h0 : heap.t) (st' : store.t)\n     (h' : heap.t),\n   Some (st, h0) = s ->\n   Some (st', h') = s' ->\n   forall h'' : heap.t,\n   heap.disj h0 h'' ->\n   (Some (st, heap.union h0 h'') -- c ----> Some (st', heap.union h' h'')) /\\\n   heap.disj h' h''.\nProof.\nelim=> //; clear s c s'.\n- (* skip *) move=> st st0 h st' h' [] X [] Y h'' Hdisj.\n  subst st.\n  case: Y => Y Z; subst.\n  split; [by constructor | assumption].\n- (* add *) move=> st h rd rs rt Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* addi *) move=> st h rt rs imm Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* addiu *) move=> st h rt rs imm st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* addu *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* cmd_and *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* andi *) move=> st h rt rs imm st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* lw *) move=> s h rt off base p z Hp Hz st he st' he' [] X Y [] Z U; subst.\n  move=> h'' Hdisj.\n  split=> //.\n  econstructor; eauto.\n  by apply heap.get_union_L.\n- (* lwxs *) move=> s h rt idx base p z Hp Hz st he st' he' [] X Y [] Z U; subst.\n  move=> h'' Hdisj.\n  split=> //.\n  econstructor; eauto.\n  by apply heap.get_union_L.\n- (* maddu *) move=> st h rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* mfhi *) move=> st h rd st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* mflhxu *) move=> st h rd st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* mflo *) move=> st h rd st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* movn true *) move=> st h rd rs rt Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* movn false *) move=> st h rd rs rt Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* movz true *) move=> st h rd rs rt Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* movz false *) move=> st h rd rs rt Hcond st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* msubu *) move=> st h rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* mthi *) move=> st h rd st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* mtlo *) move=> st h rd st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* multu *) move=> st h rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* nor *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* cmd_or *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* sll *) move=> st h rx ry sa st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* sllv *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* sltu *) move=> st h rd rs rt flag Hflas st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* sra *) move=> st h rd rt sa st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* srl *) move=> st h rd rt sa st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* srlv *) move=> st h rd rt sa st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* subu *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* sw *) move=> s h rt off base p Hp [z Hz] st he st' he' [] X Y [] Z U; subst.\n  move=> h'' Hdisj.\n  rewrite -(heap.upd_union_L _ _ _ _ _ z) //.\n  split.\n  + econstructor; eauto.\n    exists z.\n    by apply heap.get_union_L.\n  + by apply heap.disj_upd.\n- (* xor *) move=> st h rd rs rt st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\n- (* xori *) move=> st h rt rs imm st_ h_ st' h' [] -> -> [] -> -> h'' Hdisj.\n  split; [by constructor | assumption].\nQed.\n\nLemma safety_monotonicity c st h st' h' :\n    (Some (st, h) -- c ---> Some (st', h')) ->\n    forall h'',\n      heap.disj h h'' ->\n      (Some (st, heap.union h h'') -- c ---> Some (st', heap.union h' h'')) /\\\n      heap.disj h' h''.\nProof.\nmove Hs : (Some (st, h)) => s.\nmove Hs' : (Some (st', h')) => s'.\nmove=> Hexec.\nmove: Hexec st h st' h' Hs Hs'.\nelim=> //; clear c s s'.\n- move=> s c s' H st h0 st' h' X Y h'' Hdisj.\n  case: (safety_monotonicity0 _ _ _ H _ _ _ _ X Y h'' Hdisj) => H1 H2.\n  split => //.\n  by constructor.\n- move=> s s' s'' c1 c2 Hc1 IHc1 Hc2 IHc2 st h st'' h'' Hs Hs' h_disj Hdisj.\n  destruct s' as [[st' h']|].\n  - case: (IHc1 _ _ _ _ Hs (refl_equal _) _ Hdisj) => H1 H2.\n    case: (IHc2 _ _ _ _ (refl_equal _) Hs' _ H2) => H3 H4.\n    split => //.\n    apply while.exec_seq with (Some (st', heap.union h' h_disj)) => //.\n  - destruct s'' as [[st''_ h''_]|] => //.\n    by move/semop_prop_m.from_none : Hc2.\n- move=> [st h] s' b c1 c2 Hb Hc1 IHc1 st_ h_ st' h' [] -> -> Hs' h'' Hh''.\n  case: {IHc1}(IHc1 _ _ _ _ (refl_equal _) Hs' _ Hh'').\n  split=> //.\n  by apply while.exec_ifte_true.\n- move=> [st h] s' b c1 c2 Hb Hc1 IHc1 st_ h_ st' h' [] -> -> Hs' h'' Hh''.\n  case: {IHc1}(IHc1 _ _ _ _ (refl_equal _) Hs' _ Hh'').\n  split=> //.\n  by apply while.exec_ifte_false.\n- move=> [st h] s' s'' b c Hb Hc IHc Hwhile IHwhile st_ h_ st'' h'' [] -> -> Hs'' h2 Hh2.\n  destruct s' as [[st' h']|].\n  + case: (IHc _ _ _ _ (refl_equal _) (refl_equal _) _ Hh2) => Htmp Htmp'.\n    subst s''.\n     case: (IHwhile _ _ _ _ (refl_equal _) (refl_equal _) _ Htmp') => Htmp'' Htmp'''.\n     split=> //.\n     by apply while.exec_while_true with (Some (st', heap.union h' h2)).\n  + subst s''.\n    by move/semop_prop_m.from_none : Hwhile.\n- move=> [st h] b c Hb st_ h_ st' h' [] -> -> [] -> -> h2 Hh2.\n  split=> //.\n  by apply while.exec_while_false.\nQed.\n\nFrom mathcomp Require Import seq.\n\nLemma exec_termi_proj0 (s : option state) (c : cmd0) (s' : option state) :\n   s -- c ----> s' ->\n   forall (st : store.t) (h0 : heap.t) d,\n   Some (st, h0) = s ->\n   exists s'_ : option state, Some (st, heap.proj h0 d) -- c ---> s'_.\nProof.\ncase=> //; clear s c s'.\n- move=> s st h d [] Hs.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_nop.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_add.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_add_error.\n- move=> st h rt rs imm Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_addi.\n- move=> st h rt rs imm Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_addi_error.\n- move=> st h rt rs imm st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_addiu.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_addu.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_and.\n- move=> st h rt rs imm st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_andi.\n- move=> st h rt off base p z Hp Hz st_ h_ d [] -> ->.\n  case/boolP : (p \\in d) => X.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_lw with p => //.\n    rewrite heap.get_proj //.\n    by apply Hz.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_lw_error.\n    move=> [l [Hl [p_ Hp_]]].\n    rewrite Hp in Hl.\n    have {Hl}Y : p = l by lia.\n    subst l.\n    by rewrite heap.get_proj_None in Hp_.\n- move=> st h rt off base Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  apply exec0_lw_error.\n  contradict Hcond.\n  case: Hcond => l [Hl [z Hz]]; exists l; split=> //.\n  exists z.\n  case/boolP : (l \\in d) => X.\n  + by rewrite heap.get_proj in Hz.\n  + by rewrite heap.get_proj_None in Hz.\n- move=> st h rt idx base p z Hp Hz st_ h_ d [] -> ->.\n  case/boolP : (p \\in d) => X.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_lwxs with p => //.\n    rewrite heap.get_proj //.\n    by apply Hz.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_lwxs_error.\n    move=> [l [Hl [p_ Hp_]]].\n    rewrite Hp in Hl.\n    have {Hl}Y : p = l by lia.\n    subst l.\n    by rewrite heap.get_proj_None in Hp_.\n- move=> st h rt off base Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  apply exec0_lwxs_error.\n  contradict Hcond.\n  case: Hcond => l [Hl [z Hz]]; exists l; split=> //.\n  exists z.\n  case/boolP : (l \\in d) => X.\n  + by rewrite heap.get_proj in Hz.\n  + by rewrite heap.get_proj_None in Hz.\n- move=> st h rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_maddu.\n- move=> st h rd st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_mfhi.\n- move=> st h rd st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_mflhxu.\n- move=> st h rd st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_mflo.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_movn_true.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_movn_false.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_movz_true.\n- move=> st h rd rs rt Hcond st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_movz_false.\n- move=> st h rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_msubu.\n- move=> st h rd st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_mthi.\n- move=> st h rd st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_mtlo.\n- move=> st h rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_multu.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_nor.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_or.\n- move=> st h rx ry sa st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_sll.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_sllv.\n- move=> st h rd rs rt flag Hflag st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_sltu.\n- move=> st h rd rt sa st_ h_ d [] -> ->.\n  eapply ex_intro.\n  by apply while.exec_cmd0, exec0_sra.\n- move=> st h rd rt sa st_ h_ d [] -> ->.\n  eapply ex_intro.\n  by apply while.exec_cmd0, exec0_srl.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_srlv.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_subu.\n- move=> st h rt off base p Hp [z Hz] st_ h_ d [] -> ->.\n  case/boolP : (p \\in d) => X.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_sw.\n    apply Hp.\n    exists z.\n    by rewrite heap.get_proj.\n  + eapply ex_intro.\n    constructor.\n    apply exec0_sw_err.\n    move=> [l [Hl [z' Hz']]].\n    have X' : p = l by lia.\n    subst p.\n    by rewrite heap.get_proj_None in Hz'.\n- move=> st h rt off base H st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  apply exec0_sw_err.\n  contradict H.\n  case: H => [l [Hl [p Hp]]].\n  exists l; split => //.\n  exists p.\n  case/boolP : (l \\in d) => X.\n  rewrite heap.get_proj // in Hp.\n  by rewrite heap.get_proj_None in Hp.\n- move=> st h rd rs rt st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_xor.\n- move=> st h rt rs imm st_ h_ d [] -> ->.\n  eapply ex_intro.\n  constructor.\n  by apply exec0_xori.\nQed.\n\nModule semop_deter_prop_m := while.While_Semop_Deter_Prop WMIPS_Semop_Deter.\n\nLemma exec_termi_proj st h s' c d : Some (st, h) -- c ---> s' ->\n  exists s'_, Some (st, heap.proj h d) -- c ---> s'_.\nProof.\nmove Hs : (Some (st, h)) => s.\nmove=> Hexec.\nmove: Hexec st h d Hs.\nelim=> //; clear c s s'.\n- exact exec_termi_proj0.\n- move=> s s' s'' c1 c2 Hc1 IHc1 Hc2 IHc2 st h d Hs.\n  case: (IHc1 _ _ d Hs) => s1 Hs1.\n  destruct s' as [[st' h']|].\n  + subst s.\n    destruct s1 as [[st1 h1]|].\n    * move: (exec_deter_proj _ _ _ _ _ Hc1 _ _ _ Hs1) => Htmp.\n      case: Htmp => Hst1 [Hh1 Hd'].\n      subst st' h1.\n      case: {IHc2}(IHc2 _ _ d (refl_equal _)) => s''_ IHc2.\n      exists s''_.\n      by eapply while.exec_seq; eauto.\n    * exists None.\n      eapply while.exec_seq; eauto.\n      apply while.exec_none.\n  + destruct s''.\n    * by move/semop_prop_m.from_none : Hc2.\n    * destruct s1 as [[st1 h1]|].\n      - move: (safety_monotonicity _ _ _ _ _ Hs1 (heap.difs h d) (map_prop_m.proj_difs_disj_spec _ _)).\n        rewrite -heap.proj_difs.\n        case=> Hexec _.\n        subst s.\n        by move: (semop_deter_prop_m.exec_deter _ _ _ Hexec _ Hc1).\n      - exists None.\n        by eapply while.exec_seq; eauto.\n- move=> [st h] s' b c1 c2 Hb Hc1 IHc1 st_ h_ d.\n  case=> X Y; subst st_ h_.\n  case: (IHc1 _ _ d (refl_equal _)) => s1 Hs1.\n  exists s1.\n  by apply while.exec_ifte_true.\n- move=> [st h] s' b c1 c2 Hb Hc1 IHc1 st_ h_ d.\n  case=> X Y; subst st_ h_.\n  case: (IHc1 _ _ d (refl_equal _)) => s1 Hs1.\n  exists s1.\n  by apply while.exec_ifte_false.\n- (* while true *) move=> [st h] s' s'' b c Hb Hc IHc Hwhile IHwhile st_ h_ d [] X Y; subst st_ h_.\n  case: {IHc}(IHc _ _ d (refl_equal _)) => s1 IHc.\n  destruct s1 as [[st1 h1]|].\n  + destruct s' as [[st' h']|].\n    * move: (exec_deter_proj _ _ _ _ _ Hc _ _ _ IHc) => Htmp.\n      case: Htmp => Hst1 [Hh1 Hh'].\n      subst st1 h1.\n      case: {IHwhile}(IHwhile _ _ d (refl_equal _)) => s' IHwhile.\n      exists s'.\n      eapply while.exec_while_true => //.\n      apply IHc.\n      done.\n    * move: (safety_monotonicity _ _ _ _ _ IHc (heap.difs h d) (map_prop_m.proj_difs_disj_spec _ _)).\n      rewrite -heap.proj_difs.\n      case=> Hexec _.\n      by move: (semop_deter_prop_m.exec_deter _ _ _ Hexec _ Hc).\n  + exists None.\n    apply while.exec_while_true with None => //.\n    by apply while.exec_none.\n- move=> [st h] b c Hb st_ h_ d [] -> ->.\n  eapply ex_intro.\n  by apply while.exec_while_false.\nQed.\n\nRequire Import Epsilon.\n\nLemma triple_exec_precond c P Q : mips_seplog.WMIPS_Hoare.hoare P c Q ->\n  forall st h s', Some (st, h) -- c ---> s' ->\n    forall d, P st (heap.proj h d) ->\n      {s' | Some (st,h) -- c ---> Some s' }.\nProof.\nmove=> Hhoare st h s' Hexec d HP.\napply constructive_indefinite_description.\nmove/hoare_prop_m.soundness : Hhoare.\nrewrite /hoare_semantics.\nmove/(_ _ _ HP) => [Hno_err Hsome].\ndestruct s' as [p|].\nby exists p.\nmove: (exec_termi_proj _ _ _ _ d Hexec).\ncase => x Hx.\ndestruct x as [[st' h']|] => //.\nmove: (safety_monotonicity _ _ _ _ _ Hx (heap.difs h d) (map_prop_m.proj_difs_disj_spec _ _)).\nrewrite -heap.proj_difs.\ncase=> H1 H2.\nby move: (semop_deter_prop_m.exec_deter _ _ _ Hexec _ H1).\nQed.\n\n(* NB: inelegant *)\nDefinition is_while (c : @while.cmd cmd0 expr_b) : bool :=\n  match c with | while.while _ _ => true | _ => false end.\n\n(* NB: inelegant *)\nFixpoint contains_while (c : @while.cmd cmd0 expr_b) : bool :=\n  match c with\n    | while.cmd_cmd0 c0 => false\n    | c ; d => contains_while c || contains_while d\n    | while.ifte _ c d => contains_while c || contains_while d\n    | while.while _ c => true\n  end.\n\nLemma no_while_terminate : forall c, ~~ contains_while c ->\n  forall s, exists s', (s -- c ---> s').\nProof.\nelim=> //.\n- move=> c _ [s|].\n  + case: (mips_cmd.cmd0_terminate c s) => x Hx.\n    exists x. by apply while.exec_cmd0.\n  + exists None; by apply while.exec_none.\n- move=> c1 IHc1 c2 IHc2.\n  rewrite /= negb_or.\n  case/andP=> H1 H2 s.\n  case: {IHc1 H1}(IHc1 H1 s) => s1 H1.\n  case: {IHc2 H2}(IHc2 H2 s1) => s2 H2.\n  exists s2; by apply while.exec_seq with s1.\n- move=> b c1 IH1 c2 IH2.\n  rewrite /= negb_or.\n  case/andP=> H1 H2 s.\n  destruct s as [[s h]|].\n  + case/boolP : (eval_b b s) => Hb.\n    * case: {IH1 H1}(IH1 H1 (Some (s, h))) => s1 H1.\n      exists s1; by apply while.exec_ifte_true.\n    * case: {IH2 H2}(IH2 H2 (Some (s, h))) => s2 H2.\n      by exists s2; apply while.exec_ifte_false.\n  + exists None; by apply while.exec_none.\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/mips_syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1870928879427797}}
{"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(** Register allocation by external oracle and a posteriori validation. *)\n\nRequire Import FSets FSetAVLplus.\nRequire Import Coqlib Ordered Maps Errors Integers Floats.\nRequire Import AST Lattice Kildall Memdata.\nRequire Archi.\nRequire Import Op Registers RTL Locations Conventions RTLtyping LTL.\n\n(** The validation algorithm used here is described in\n  \"Validating register allocation and spilling\",\n  by Silvain Rideau and Xavier Leroy,\n  in Compiler Construction (CC 2010), LNCS 6011, Springer, 2010. *)\n\n(** * Structural checks *)\n\n(** As a first pass, we check the LTL code returned by the external oracle\n  against the original RTL code for structural conformance.\n  Each RTL instruction was transformed into a LTL basic block whose\n  shape must agree with the RTL instruction.  For example, if the RTL\n  instruction is [Istore(Mint32, addr, args, src, s)], the LTL basic block\n  must be of the following shape:\n- zero, one or several \"move\" instructions\n- a store instruction [Lstore(Mint32, addr, args', src')]\n- a [Lbranch s] instruction.\n\n  The [block_shape] type below describes all possible cases of structural\n  matching between an RTL instruction and an LTL basic block.\n*)\n\nInductive move: Type :=\n  | MV (src dst: loc)\n  | MVmakelong (src1 src2 dst: mreg)\n  | MVlowlong (src dst: mreg)\n  | MVhighlong (src dst: mreg).\n\nDefinition moves := list move.\n\nInductive block_shape: Type :=\n  | BSnop (mv: moves) (s: node)\n  | BSmove (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSmakelong (src1 src2: reg) (dst: reg) (mv: moves) (s: node)\n  | BSlowlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BShighlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSop (op: operation) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': mreg)\n         (mv2: moves) (s: node)\n  | BSopdead (op: operation) (args: list reg) (res: reg)\n         (mv: moves) (s: node)\n  | BSload (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSloaddead (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv: moves) (s: node)\n  | BSload2 (addr1 addr2: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args1': list mreg) (dst1': mreg)\n         (mv2: moves) (args2': list mreg) (dst2': mreg)\n         (mv3: moves) (s: node)\n  | BSload2_1 (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSload2_2 (addr addr': addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSstore (chunk: memory_chunk) (addr: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args': list mreg) (src': mreg)\n         (s: node)\n  | BSstore2 (addr1 addr2: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args1': list mreg) (src1': mreg)\n         (mv2: moves) (args2': list mreg) (src2': mreg)\n         (s: node)\n  | BScall (sg: signature) (ros: reg + ident) (args: list reg) (res: reg)\n         (mv1: moves) (ros': mreg + ident) (mv2: moves) (s: node)\n  | BStailcall (sg: signature) (ros: reg + ident) (args: list reg)\n         (mv1: moves) (ros': mreg + ident)\n  | BSbuiltin (ef: external_function)\n         (args: list (builtin_arg reg)) (res: builtin_res reg)\n         (mv1: moves) (args': list (builtin_arg loc)) (res': builtin_res mreg)\n         (mv2: moves) (s: node)\n  | BScond (cond: condition) (args: list reg)\n         (mv: moves) (args': list mreg) (s1 s2: node)\n  | BSjumptable (arg: reg)\n         (mv: moves) (arg': mreg) (tbl: list node)\n  | BSreturn (arg: option reg)\n         (mv: moves).\n\n(** Classify operations into moves, 64-bit split integer operations, and other\n  arithmetic/logical operations. *)\n\nInductive operation_kind {A: Type}: operation -> list A -> Type :=\n  | operation_Omove: forall arg, operation_kind Omove (arg :: nil)\n  | operation_Omakelong: forall arg1 arg2, operation_kind Omakelong (arg1 :: arg2 :: nil)\n  | operation_Olowlong: forall arg, operation_kind Olowlong (arg :: nil)\n  | operation_Ohighlong: forall arg, operation_kind Ohighlong (arg :: nil)\n  | operation_other: forall op args, operation_kind op args.\n\nDefinition classify_operation {A: Type} (op: operation) (args: list A) : operation_kind op args :=\n  match op, args with\n  | Omove, arg::nil => operation_Omove arg\n  | Omakelong, arg1::arg2::nil => operation_Omakelong arg1 arg2\n  | Olowlong, arg::nil => operation_Olowlong arg\n  | Ohighlong, arg::nil => operation_Ohighlong arg\n  | op, args => operation_other op args\n  end.\n\n(** Extract the move instructions at the beginning of block [b].\n  Return the list of moves and the suffix of [b] after the moves.\n  Two versions are provided: [extract_moves], which extracts only\n  \"true\" moves, and [extract_moves_ext], which also extracts\n  the [makelong], [lowlong] and [highlong] operations over 64-bit integers.\n*)\n\nFixpoint extract_moves (accu: moves) (b: bblock) {struct b} : moves * bblock :=\n  match b with\n  | Lgetstack sl ofs ty dst :: b' =>\n      extract_moves (MV (S sl ofs ty) (R dst) :: accu) b'\n  | Lsetstack src sl ofs ty :: b' =>\n      extract_moves (MV (R src) (S sl ofs ty) :: accu) b'\n  | Lop op args res :: b' =>\n      match is_move_operation op args with\n      | Some arg =>\n          extract_moves (MV (R arg) (R res) :: accu) b'\n      | None =>\n          (List.rev accu, b)\n      end\n  | _ =>\n      (List.rev accu, b)\n  end.\n\nFixpoint extract_moves_ext (accu: moves) (b: bblock) {struct b} : moves * bblock :=\n  match b with\n  | Lgetstack sl ofs ty dst :: b' =>\n      extract_moves_ext (MV (S sl ofs ty) (R dst) :: accu) b'\n  | Lsetstack src sl ofs ty :: b' =>\n      extract_moves_ext (MV (R src) (S sl ofs ty) :: accu) b'\n  | Lop op args res :: b' =>\n      match classify_operation op args with\n      | operation_Omove arg =>\n          extract_moves_ext (MV (R arg) (R res) :: accu) b'\n      | operation_Omakelong arg1 arg2 =>\n          extract_moves_ext (MVmakelong arg1 arg2 res :: accu) b'\n      | operation_Olowlong arg =>\n          extract_moves_ext (MVlowlong arg res :: accu) b'\n      | operation_Ohighlong arg =>\n          extract_moves_ext (MVhighlong arg res :: accu) b'\n      | operation_other _ _ =>\n          (List.rev accu, b)\n      end\n  | _ =>\n      (List.rev accu, b)\n  end.\n\nDefinition check_succ (s: node) (b: LTL.bblock) : bool :=\n  match b with\n  | Lbranch s' :: _ => peq s s'\n  | _ => false\n  end.\n\nDeclare Scope option_monad_scope.\n\nNotation \"'do' X <- A ; B\" := (match A with Some X => B | None => None end)\n         (at level 200, X ident, A at level 100, B at level 200)\n         : option_monad_scope.\n\nNotation \"'assertion' A ; B\" := (if A then B else None)\n         (at level 200, A at level 100, B at level 200)\n         : option_monad_scope.\n\nLocal Open Scope option_monad_scope.\n\n(** Check RTL instruction [i] against LTL basic block [b].\n  On success, return [Some] with a [block_shape] describing the correspondence.\n  On error, return [None]. *)\n\nDefinition pair_Iop_block (op: operation) (args: list reg) (res: reg) (s: node) (b: LTL.bblock) :=\n  let (mv1, b1) := extract_moves nil b in\n  match b1 with\n  | Lop op' args' res' :: b2 =>\n      let (mv2, b3) := extract_moves nil b2 in\n      assertion (eq_operation op op');\n      assertion (check_succ s b3);\n      Some(BSop op args res mv1 args' res' mv2 s)\n  | _ =>\n      assertion (check_succ s b1);\n      Some(BSopdead op args res mv1 s)\n  end.\n\nDefinition pair_instr_block\n               (i: RTL.instruction) (b: LTL.bblock) : option block_shape :=\n  match i with\n  | Inop s =>\n      let (mv, b1) := extract_moves nil b in\n      assertion (check_succ s b1); Some(BSnop mv s)\n  | Iop op args res s =>\n      match classify_operation op args with\n      | operation_Omove arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmove arg res mv s)\n      | operation_Omakelong arg1 arg2 =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BSmakelong arg1 arg2 res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_Olowlong arg =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BSlowlong arg res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_Ohighlong arg =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BShighlong arg res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_other _ _ =>\n          pair_Iop_block op args res s b\n      end\n  | Iload chunk addr args dst s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lload chunk' addr' args' dst' :: b2 =>\n          if chunk_eq chunk Mint64 && Archi.splitlong then\n            assertion (chunk_eq chunk' Mint32);\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lload chunk'' addr'' args'' dst'' :: b4 =>\n                let (mv3, b5) := extract_moves nil b4 in\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr''));\n                assertion (check_succ s b5);\n                Some(BSload2 addr addr'' args dst mv1 args' dst' mv2 args'' dst'' mv3 s)\n            | _ =>\n                assertion (check_succ s b3);\n                if (eq_addressing addr addr') then\n                  Some(BSload2_1 addr args dst mv1 args' dst' mv2 s)\n                else\n                 (assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr'));\n                  Some(BSload2_2 addr addr' args dst mv1 args' dst' mv2 s))\n            end\n          else (\n            let (mv2, b3) := extract_moves nil b2 in\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b3);\n            Some(BSload chunk addr args dst mv1 args' dst' mv2 s))\n      | _ =>\n          assertion (check_succ s b1);\n          Some(BSloaddead chunk addr args dst mv1 s)\n      end\n  | Istore chunk addr args src s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lstore chunk' addr' args' src' :: b2 =>\n          if chunk_eq chunk Mint64 && Archi.splitlong then\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lstore chunk'' addr'' args'' src'' :: b4 =>\n                assertion (chunk_eq chunk' Mint32);\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr''));\n                assertion (check_succ s b4);\n                Some(BSstore2 addr addr'' args src mv1 args' src' mv2 args'' src'' s)\n            | _ => None\n            end\n          else (\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b2);\n            Some(BSstore chunk addr args src mv1 args' src' s))\n      | _ => None\n      end\n  | Icall sg ros args res s =>\n      let (mv1, b1) := extract_moves_ext nil b in\n      match b1 with\n      | Lcall sg' ros' :: b2 =>\n          let (mv2, b3) := extract_moves_ext nil b2 in\n          assertion (signature_eq sg sg');\n          assertion (check_succ s b3);\n          Some(BScall sg ros args res mv1 ros' mv2 s)\n      | _ => None\n      end\n  | Itailcall sg ros args =>\n      let (mv1, b1) := extract_moves_ext nil b in\n      match b1 with\n      | Ltailcall sg' ros' :: b2 =>\n          assertion (signature_eq sg sg');\n          Some(BStailcall sg ros args mv1 ros')\n      | _ => None\n      end\n  | Ibuiltin ef args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lbuiltin ef' args' res' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (external_function_eq ef ef');\n          assertion (check_succ s b3);\n          Some(BSbuiltin ef args res mv1 args' res' mv2 s)\n      | _ => None\n      end\n  | Icond cond args s1 s2 =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcond cond' args' s1' s2' :: b2 =>\n          assertion (eq_condition cond cond');\n          assertion (peq s1 s1');\n          assertion (peq s2 s2');\n          Some(BScond cond args mv1 args' s1 s2)\n      | _ => None\n      end\n  | Ijumptable arg tbl =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ljumptable arg' tbl' :: b2 =>\n          assertion (list_eq_dec peq tbl tbl');\n          Some(BSjumptable arg mv1 arg' tbl)\n      | _ => None\n      end\n  | Ireturn arg =>\n      let (mv1, b1) := extract_moves_ext nil b in\n      match b1 with\n      | Lreturn :: b2 => Some(BSreturn arg mv1)\n      | _ => None\n      end\n  end.\n\n(** Check all instructions of the RTL function [f1] against the corresponding\n  basic blocks of LTL function [f2].  Return a map from CFG nodes to\n  [block_shape] info. *)\n\nDefinition pair_codes (f1: RTL.function) (f2: LTL.function) : PTree.t block_shape :=\n  PTree.combine\n    (fun opti optb => do i <- opti; do b <- optb; pair_instr_block i b)\n    (RTL.fn_code f1) (LTL.fn_code f2).\n\n(** Check the entry point code of the LTL function [f2].  It must be\n  a sequence of moves that branches to the same node as the entry point\n  of RTL function [f1]. *)\n\nDefinition pair_entrypoints (f1: RTL.function) (f2: LTL.function) : option moves :=\n  do b <- (LTL.fn_code f2)!(LTL.fn_entrypoint f2);\n  let (mv, b1) := extract_moves_ext nil b in\n  assertion (check_succ (RTL.fn_entrypoint f1) b1);\n  Some mv.\n\n(** * Representing sets of equations between RTL registers and LTL locations. *)\n\n(** The Rideau-Leroy validation algorithm manipulates sets of equations of\n  the form [pseudoreg = location [kind]], meaning:\n- if [kind = Full], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the value of [pseudoreg] in the original\n  RTL code;\n- if [kind = Low], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the low 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code;\n- if [kind = High], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the high 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code.\n*)\n\nInductive equation_kind : Type := Full | Low | High.\n\nRecord equation := Eq {\n  ekind: equation_kind;\n  ereg: reg;\n  eloc: loc\n}.\n\n(** We use AVL finite sets to represent sets of equations.  Therefore, we need\n  total orders over equations and their components. *)\n\nModule IndexedEqKind <: INDEXED_TYPE.\n  Definition t := equation_kind.\n  Definition index (x: t) :=\n    match x with Full => 1%positive | Low => 2%positive | High => 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 (x y: t) : {x=y} + {x<>y}.\n  Proof. decide equality. Defined.\nEnd IndexedEqKind.\n\nModule OrderedEqKind := OrderedIndexed(IndexedEqKind).\n\n(** This is an order over equations that is lexicographic on [ereg], then\n  [eloc], then [ekind]. *)\n\nModule OrderedEquation <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    (OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\n  Lemma eq_refl : forall x : t, eq x x.\n  Proof (@eq_refl t).\n  Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof (@eq_sym t).\n  Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof (@eq_trans t).\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n    unfold lt; intros.\n    destruct H.\n    destruct H0. left; eapply Plt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H.\n    destruct H0. auto.\n    destruct H0. right; split; auto.\n    intuition.\n    left; eapply OrderedLoc.lt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim Plt_strict; eauto.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedPositive.compare (ereg x) (ereg y)).\n  - apply LT. red; auto.\n  - destruct (OrderedLoc.compare (eloc x) (eloc y)).\n    + apply LT. red; auto.\n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red.\n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec (x y: t) : {x = y} + {x <> y}.\n  Proof.\n    intros. decide equality.\n    apply Loc.eq.\n    apply peq.\n    apply IndexedEqKind.eq.\n  Defined.\nEnd OrderedEquation.\n\n(** This is an alternate order over equations that is lexicgraphic on\n  [eloc], then [ereg], then [ekind]. *)\n\nModule OrderedEquation' <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    (Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\n  Lemma eq_refl : forall x : t, eq x x.\n  Proof (@eq_refl t).\n  Lemma eq_sym : forall x y : t, eq x y -> eq y x.\n  Proof (@eq_sym t).\n  Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\n  Proof (@eq_trans t).\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n    unfold lt; intros.\n    destruct H.\n    destruct H0. left; eapply OrderedLoc.lt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H.\n    destruct H0. auto.\n    destruct H0. right; split; auto.\n    intuition.\n    left; eapply Plt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim Plt_strict; eauto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedLoc.compare (eloc x) (eloc y)).\n  - apply LT. red; auto.\n  - destruct (OrderedPositive.compare (ereg x) (ereg y)).\n    + apply LT. red; auto.\n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red.\n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec: forall (x y: t), {x = y} + {x <> y} := OrderedEquation.eq_dec.\nEnd OrderedEquation'.\n\nModule EqSet := FSetAVLplus.Make(OrderedEquation).\nModule EqSet2 := FSetAVLplus.Make(OrderedEquation').\n\n(** We use a redundant representation for sets of equations, comprising\n  two AVL finite sets, containing the same elements, but ordered along\n  the two orders defined above.  Playing on properties of lexicographic\n  orders, this redundant representation enables us to quickly find\n  all equations involving a given RTL pseudoregister, or all equations\n  involving a given LTL location or overlapping location. *)\n\nRecord eqs := mkeqs {\n  eqs1 :> EqSet.t;\n  eqs2 : EqSet2.t;\n  eqs_same: forall q, EqSet2.In q eqs2 <-> EqSet.In q eqs1\n}.\n\n(** * Operations on sets of equations *)\n\n(** The empty set of equations. *)\n\nProgram Definition empty_eqs := mkeqs EqSet.empty EqSet2.empty _.\nNext Obligation.\n  split; intros. eelim EqSet2.empty_1; eauto. eelim EqSet.empty_1; eauto.\nQed.\n\n(** Adding or removing an equation from a set. *)\n\nProgram Definition add_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.add q (eqs1 e)) (EqSet2.add q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0).\n  apply EqSet.add_1; auto.\n  apply EqSet.add_2. apply (eqs_same e). apply EqSet2.add_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0).\n  apply EqSet2.add_1; auto.\n  apply EqSet2.add_2. apply (eqs_same e). apply EqSet.add_3 with q; auto.\nQed.\n\nProgram Definition remove_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.remove q (eqs1 e)) (EqSet2.remove q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0).\n  eelim EqSet2.remove_1; eauto.\n  apply EqSet.remove_2; auto. apply (eqs_same e). apply EqSet2.remove_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0).\n  eelim EqSet.remove_1; eauto.\n  apply EqSet2.remove_2; auto. apply (eqs_same e). apply EqSet.remove_3 with q; auto.\nQed.\n\n(** [reg_unconstrained r e] is true if [e] contains no equations involving\n  the RTL pseudoregister [r].  In other words, all equations [r' = l [kind]]\n  in [e] are such that [r' <> r]. *)\n\nDefinition select_reg_l (r: reg) (q: equation) := Pos.leb r (ereg q).\nDefinition select_reg_h (r: reg) (q: equation) := Pos.leb (ereg q) r.\n\nDefinition reg_unconstrained (r: reg) (e: eqs) : bool :=\n  negb (EqSet.mem_between (select_reg_l r) (select_reg_h r) (eqs1 e)).\n\n(** [loc_unconstrained l e] is true if [e] contains no equations involving\n  the LTL location [l] or a location that partially overlaps with [l].\n  In other words, all equations [r = l' [kind]] in [e] are such that\n  [Loc.diff l' l]. *)\n\nDefinition select_loc_l (l: loc) :=\n  let lb := OrderedLoc.diff_low_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lb with LT _ => false | _ => true end.\nDefinition select_loc_h (l: loc) :=\n  let lh := OrderedLoc.diff_high_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lh with GT _ => false | _ => true end.\n\nDefinition loc_unconstrained (l: loc) (e: eqs) : bool :=\n  negb (EqSet2.mem_between (select_loc_l l) (select_loc_h l) (eqs2 e)).\n\nDefinition reg_loc_unconstrained (r: reg) (l: loc) (e: eqs) : bool :=\n  reg_unconstrained r e && loc_unconstrained l e.\n\n(** [subst_reg r1 r2 e] simulates the effect of assigning [r2] to [r1] on [e].\n  All equations of the form [r1 = l [kind]] are replaced by [r2 = l [kind]].\n*)\n\nDefinition subst_reg (r1 r2: reg) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e => add_equation (Eq (ekind q) r2 (eloc q)) (remove_equation q e))\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_reg_kind r1 k1 r2 k2 e] simulates the effect of assigning\n  the [k2] part of [r2] to the [k1] part of [r1] on [e].\n  All equations of the form [r1 = l [k1]] are replaced by [r2 = l [k2]].\n*)\n\nDefinition subst_reg_kind (r1: reg) (k1: equation_kind) (r2: reg) (k2: equation_kind) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e =>\n      if IndexedEqKind.eq (ekind q) k1\n      then add_equation (Eq k2 r2 (eloc q)) (remove_equation q e)\n      else e)\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_loc l1 l2 e] simulates the effect of assigning [l2] to [l1] on [e].\n  All equations of the form [r = l1 [kind]] are replaced by [r = l2 [kind]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1].\n*)\n\nDefinition subst_loc (l1 l2: loc) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            Some (add_equation (Eq (ekind q) (ereg q) l2) (remove_equation q e))\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [subst_loc_part l1 l2 k e] simulates the effect of assigning\n  [l2] to the [k] part of [l1] on [e].\n  All equations of the form [r = l1 [k]] are replaced by [r = l2 [Full]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1], or an equation of the form [r = l1] with\n  a kind different from [k1].\n*)\n\nDefinition subst_loc_part (l1: loc) (l2: loc) (k: equation_kind) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            if IndexedEqKind.eq (ekind q) k\n            then Some (add_equation (Eq Full (ereg q) l2) (remove_equation q e))\n            else None\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [subst_loc_pair l1 l2 l2'] simulates the effect of assigning\n  [makelong l2 l2'] to [l1].  All equations of the form [r = l1 [Full]]\n  are replaced by the two equations [r = l2 [High], r = l2' [Low]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1], or an equation of the form [r = l1] with\n  a kind different from [Full]. *)\n\nDefinition subst_loc_pair (l1 l2 l2': loc) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            if IndexedEqKind.eq (ekind q) Full\n            then Some (add_equation (Eq High (ereg q) l2)\n                        (add_equation (Eq Low (ereg q) l2')\n                           (remove_equation q e)))\n            else None\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [loc_type_compat env l e] checks that for all equations [r = l] in [e],\n  the type [env r] of [r] is compatible with the type of [l]. *)\n\nDefinition sel_type (k: equation_kind) (ty: typ) : typ :=\n  match k with\n  | Full => ty\n  | Low | High => Tint\n  end.\n\nDefinition loc_type_compat (env: regenv) (l: loc) (e: eqs) : bool :=\n  EqSet2.for_all_between\n    (fun q => subtype (sel_type (ekind q) (env (ereg q))) (Loc.type l))\n    (select_loc_l l) (select_loc_h l) (eqs2 e).\n\n(** [long_type_compat env l e] checks that for all equations [r = l] in [e].\n  then type [env r] of [r] is compatible with the type [Tlong]. *)\n\nDefinition long_type_compat (env: regenv) (l: loc) (e: eqs) : bool :=\n  EqSet2.for_all_between\n    (fun q => subtype (env (ereg q)) Tlong)\n    (select_loc_l l) (select_loc_h l) (eqs2 e).\n\n(** [add_equations [r1...rN] [m1...mN] e] adds to [e] the [N] equations\n    [ri = R mi [Full]].  Return [None] if the two lists have different lengths.\n*)\n\nFixpoint add_equations (rl: list reg) (ml: list mreg) (e: eqs) : option eqs :=\n  match rl, ml with\n  | nil, nil => Some e\n  | r1 :: rl, m1 :: ml => add_equations rl ml (add_equation (Eq Full r1 (R m1)) e)\n  | _, _ => None\n  end.\n\n(** [add_equations_args] is similar but additionally handles the splitting\n  of pseudoregisters of type [Tlong] in two locations containing the\n  two 32-bit halves of the 64-bit integer. *)\n\nFunction add_equations_args (rl: list reg) (tyl: list typ) (ll: list (rpair loc)) (e: eqs) : option eqs :=\n  match rl, tyl, ll with\n  | nil, nil, nil => Some e\n  | r1 :: rl, ty :: tyl, One l1 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Full r1 l1) e)\n  | r1 :: rl, Tlong :: tyl, Twolong l1 l2 :: ll =>\n      if Archi.ptr64 then None else\n      add_equations_args rl tyl ll (add_equation (Eq Low r1 l2) (add_equation (Eq High r1 l1) e))\n  | _, _, _ => None\n  end.\n\n(** [add_equations_res] is similar but is specialized to the case where\n  there is only one pseudo-register. *)\n\nFunction add_equations_res (r: reg) (ty: typ) (p: rpair mreg) (e: eqs) : option eqs :=\n  match p, ty with\n  | One mr, _ =>\n      Some (add_equation (Eq Full r (R mr)) e)\n  | Twolong mr1 mr2, Tlong =>\n      if Archi.ptr64 then None else\n      Some (add_equation (Eq Low r (R mr2)) (add_equation (Eq High r (R mr1)) e))\n  | _, _ =>\n      None\n  end.\n\n(** [remove_equations_res] is similar to [add_equations_res] but removes\n  equations instead of adding them. *)\n\nFunction remove_equations_res (r: reg) (p: rpair mreg) (e: eqs) : option eqs :=\n  match p with\n  | One mr =>\n      Some (remove_equation (Eq Full r (R mr)) e)\n  | Twolong mr1 mr2 =>\n      if mreg_eq mr2 mr1\n      then None\n      else Some (remove_equation (Eq Low r (R mr2)) (remove_equation (Eq High r (R mr1)) e))\n  end.\n\n(** [add_equations_ros] adds an equation, if needed, between an optional\n  pseudoregister and an optional machine register.  It is used for the\n  function argument of the [Icall] and [Itailcall] instructions. *)\n\nDefinition add_equation_ros (ros: reg + ident) (ros': mreg + ident) (e: eqs) : option eqs :=\n  match ros, ros' with\n  | inl r, inl mr => Some(add_equation (Eq Full r (R mr)) e)\n  | inr id, inr id' => assertion (ident_eq id id'); Some e\n  | _, _ => None\n  end.\n\n(** [add_equations_builtin_arg] adds the needed equations for arguments\n    to builtin functions. *)\n\nFixpoint add_equations_builtin_arg\n     (env: regenv) (arg: builtin_arg reg) (arg': builtin_arg loc) (e: eqs) : option eqs :=\n  match arg, arg' with\n  | BA r, BA l =>\n      Some (add_equation (Eq Full r l) e)\n  | BA r, BA_splitlong (BA lhi) (BA llo) =>\n      assertion (typ_eq (env r) Tlong);\n      assertion (Archi.splitlong);\n      Some (add_equation (Eq Low r llo) (add_equation (Eq High r lhi) e))\n  | BA_int n, BA_int n' =>\n      assertion (Int.eq_dec n n'); Some e\n  | BA_long n, BA_long n' =>\n      assertion (Int64.eq_dec n n'); Some e\n  | BA_float f, BA_float f' =>\n      assertion (Float.eq_dec f f'); Some e\n  | BA_single f, BA_single f' =>\n      assertion (Float32.eq_dec f f'); Some e\n  | BA_loadstack chunk ofs, BA_loadstack chunk' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_addrstack ofs, BA_addrstack ofs' =>\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_loadglobal chunk id ofs, BA_loadglobal chunk' id' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (ident_eq id id');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_addrglobal id ofs, BA_addrglobal id' ofs' =>\n      assertion (ident_eq id id');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_splitlong hi lo, BA_splitlong hi' lo' =>\n      do e1 <- add_equations_builtin_arg env hi hi' e;\n      add_equations_builtin_arg env lo lo' e1\n  | BA_addptr a1 a2, BA_addptr a1' a2' =>\n      do e1 <- add_equations_builtin_arg env a1 a1' e;\n      add_equations_builtin_arg env a2 a2' e1\n  | _, _ =>\n      None\n  end.\n\nFixpoint add_equations_builtin_args\n   (env: regenv) (args: list (builtin_arg reg))\n   (args': list (builtin_arg loc)) (e: eqs) : option eqs :=\n  match args, args' with\n  | nil, nil => Some e\n  | a1 :: al, a1' :: al' =>\n      do e1 <- add_equations_builtin_arg env a1 a1' e;\n      add_equations_builtin_args env al al' e1\n  | _, _ => None\n  end.\n\n(** For [EF_debug] builtins, some arguments can be removed. *)\n\nFixpoint add_equations_debug_args\n   (env: regenv) (args: list (builtin_arg reg))\n   (args': list (builtin_arg loc)) (e: eqs) : option eqs :=\n  match args, args' with\n  | _, nil => Some e\n  | a1 :: al, a1' :: al' =>\n      match add_equations_builtin_arg env a1 a1' e with\n      | None => add_equations_debug_args env al args' e\n      | Some e1 => add_equations_debug_args env al al' e1\n      end\n  | _, _ => None\n  end.\n\n(** Checking of the result of a builtin *)\n\nDefinition remove_equations_builtin_res\n    (env: regenv) (res: builtin_res reg) (res': builtin_res mreg) (e: eqs) : option eqs :=\n  match res, res' with\n  | BR r, BR r' => Some (remove_equation (Eq Full r (R r')) e)\n  | BR r, BR_splitlong (BR rhi) (BR rlo) =>\n      assertion (typ_eq (env r) Tlong);\n      if mreg_eq rhi rlo then None else\n        Some (remove_equation (Eq Low r (R rlo))\n                (remove_equation (Eq High r (R rhi)) e))\n  | BR_none, BR_none => Some e\n  | _, _ => None\n  end.\n\n(** [can_undef ml] returns true if all machine registers in [ml] are\n  unconstrained and can harmlessly be undefined. *)\n\nFixpoint can_undef (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => loc_unconstrained (R m1) e && can_undef ml e\n  end.\n\nFixpoint can_undef_except (l: loc) (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml =>\n      (Loc.eq l (R m1) || loc_unconstrained (R m1) e) && can_undef_except l ml e\n  end.\n\n(** [no_caller_saves e] returns [e] if all caller-save locations are\n  unconstrained in [e].  In other words, [e] contains no equations\n  involving a caller-save register or [Outgoing] stack slot. *)\n\nDefinition no_caller_saves (e: eqs) : bool :=\n  EqSet.for_all\n   (fun eq =>\n     match eloc eq with\n       | R r => is_callee_save r\n       | S Outgoing _ _ => false\n       | S _ _ _ => true\n       end)\n    e.\n\n(** [compat_left r l e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l [Full]]. *)\n\nDefinition compat_left (r: reg) (l: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | Full => Loc.eq l (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [compat_left2 r l1 l2 e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l1 [High]] or [r = l2 [Low]]. *)\n\nDefinition compat_left2 (r: reg) (l1 l2: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | High => Loc.eq l1 (eloc q)\n        | Low => Loc.eq l2 (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [ros_compatible_tailcall ros] returns true if [ros] is a function\n  name or a caller-save register.  This is used to check [Itailcall]\n  instructions. *)\n\nDefinition ros_compatible_tailcall (ros: mreg + ident) : bool :=\n  match ros with\n  | inl r => negb (is_callee_save r)\n  | inr id => true\n  end.\n\n(** * The validator *)\n\nDefinition destroyed_by_move (src dst: loc) :=\n  match src, dst with\n  | S sl ofs ty, _ => destroyed_by_getstack sl\n  | _, S sl ofs ty => destroyed_by_setstack ty\n  | _, _ => destroyed_by_op Omove\n  end.\n\nDefinition well_typed_move (env: regenv) (dst: loc) (e: eqs) : bool :=\n  match dst with\n  | R r => true\n  | S sl ofs ty => loc_type_compat env dst e\n  end.\n\n(** Simulate the effect of a sequence of moves [mv] on a set of\n  equations [e].  The set [e] is the equations that must hold\n  after the sequence of moves.  Return the set of equations that\n  must hold before the sequence of moves.  Return [None] if the\n  set of equations [e] cannot hold after the sequence of moves. *)\n\nFixpoint track_moves (env: regenv) (mv: moves) (e: eqs) : option eqs :=\n  match mv with\n  | nil => Some e\n  | MV src dst :: mv =>\n      do e1 <- track_moves env mv e;\n      assertion (can_undef_except dst (destroyed_by_move src dst)) e1;\n      assertion (well_typed_move env dst e1);\n      subst_loc dst src e1\n  | MVmakelong src1 src2 dst :: mv =>\n      assertion (negb Archi.ptr64);\n      do e1 <- track_moves env mv e;\n      assertion (long_type_compat env (R dst) e1);\n      subst_loc_pair (R dst) (R src1) (R src2) e1\n  | MVlowlong src dst :: mv =>\n      assertion (negb Archi.ptr64);\n      do e1 <- track_moves env mv e;\n      subst_loc_part (R dst) (R src) Low e1\n  | MVhighlong src dst :: mv =>\n      assertion (negb Archi.ptr64);\n      do e1 <- track_moves env mv e;\n      subst_loc_part (R dst) (R src) High e1\n  end.\n\n(** [transfer_use_def args res args' res' undefs e] returns the set\n  of equations that must hold \"before\" in order for the equations [e]\n  to hold \"after\" the execution of RTL and LTL code of the following form:\n<<\n                RTL                            LTL\n         use pseudoregs args            use machine registers args'\n         define pseudoreg res           undefine machine registers undef\n                                        define machine register res'\n>>\n  As usual, [None] is returned if the equations [e] cannot hold after\n  this execution.\n*)\n\nDefinition transfer_use_def (args: list reg) (res: reg) (args': list mreg) (res': mreg)\n                            (undefs: list mreg) (e: eqs) : option eqs :=\n  let e1 := remove_equation (Eq Full res (R res')) e in\n  assertion (reg_loc_unconstrained res (R res') e1);\n  assertion (can_undef undefs e1);\n  add_equations args args' e1.\n\nDefinition kind_first_word := if Archi.big_endian then High else Low.\nDefinition kind_second_word := if Archi.big_endian then Low else High.\n\n(** The core transfer function.  It takes a set [e] of equations that must\n  hold \"after\" and a block shape [shape] representing a matching pair\n  of an RTL instruction and an LTL basic block.  It returns the set of\n  equations that must hold \"before\" these instructions, or [None] if\n  impossible. *)\n\nDefinition transfer_aux (f: RTL.function) (env: regenv)\n                        (shape: block_shape) (e: eqs) : option eqs :=\n  match shape with\n  | BSnop mv s =>\n      track_moves env mv e\n  | BSmove src dst mv s =>\n      track_moves env mv (subst_reg dst src e)\n  | BSmakelong src1 src2 dst mv s =>\n      let e1 := subst_reg_kind dst High src1 Full e in\n      let e2 := subst_reg_kind dst Low src2 Full e1 in\n      assertion (reg_unconstrained dst e2);\n      track_moves env mv e2\n  | BSlowlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src Low e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BShighlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src High e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BSop op args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args res args' res' (destroyed_by_op op) e1;\n      track_moves env mv1 e2\n  | BSopdead op args res mv s =>\n      assertion (reg_unconstrained res e);\n      track_moves env mv e\n  | BSload chunk addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args dst args' dst' (destroyed_by_load chunk addr) e1;\n      track_moves env mv1 e2\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s =>\n      do e1 <- track_moves env mv3 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst2')) e1 in\n      assertion (loc_unconstrained (R dst2') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args2' e2;\n      do e4 <- track_moves env mv2 e3;\n      let e5 := remove_equation (Eq kind_first_word dst (R dst1')) e4 in\n      assertion (loc_unconstrained (R dst1') e5);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e5);\n      assertion (reg_unconstrained dst e5);\n      do e6 <- add_equations args args1' e5;\n      track_moves env mv1 e6\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_first_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSloaddead chunk addr args dst mv s =>\n      assertion (reg_unconstrained dst e);\n      track_moves env mv e\n  | BSstore chunk addr args src mv args' src' s =>\n      assertion (can_undef (destroyed_by_store chunk addr) e);\n      do e1 <- add_equations (src :: args) (src' :: args') e;\n      track_moves env mv e1\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s =>\n      assertion (can_undef (destroyed_by_store Mint32 addr') e);\n      do e1 <- add_equations args args2'\n                  (add_equation (Eq kind_second_word src (R src2')) e);\n      do e2 <- track_moves env mv2 e1;\n      assertion (can_undef (destroyed_by_store Mint32 addr) e2);\n      do e3 <- add_equations args args1'\n                  (add_equation (Eq kind_first_word src (R src1')) e2);\n      track_moves env mv1 e3\n  | BScall sg ros args res mv1 ros' mv2 s =>\n      let args' := loc_arguments sg in\n      let res' := loc_result sg in\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_res res res' e1;\n      assertion (forallb (fun l => reg_loc_unconstrained res l e2)\n                         (map R (regs_of_rpair res')));\n      assertion (no_caller_saves e2);\n      do e3 <- add_equation_ros ros ros' e2;\n      do e4 <- add_equations_args args (sig_args sg) args' e3;\n      track_moves env mv1 e4\n  | BStailcall sg ros args mv1 ros' =>\n      let args' := loc_arguments sg in\n      assertion (tailcall_is_possible sg);\n      assertion (rettype_eq sg.(sig_res) f.(RTL.fn_sig).(sig_res));\n      assertion (ros_compatible_tailcall ros');\n      do e1 <- add_equation_ros ros ros' empty_eqs;\n      do e2 <- add_equations_args args (sig_args sg) args' e1;\n      track_moves env mv1 e2\n  | BSbuiltin ef args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_builtin_res env res res' e1;\n      assertion (forallb (fun r => reg_unconstrained r e2)\n                         (params_of_builtin_res res));\n      assertion (forallb (fun mr => loc_unconstrained (R mr) e2)\n                         (params_of_builtin_res res'));\n      assertion (can_undef (destroyed_by_builtin ef) e2);\n      do e3 <-\n        match ef with\n        | EF_debug _ _ _ => add_equations_debug_args env args args' e2\n        | _              => add_equations_builtin_args env args args' e2\n        end;\n      track_moves env mv1 e3\n  | BScond cond args mv args' s1 s2 =>\n      assertion (can_undef (destroyed_by_cond cond) e);\n      do e1 <- add_equations args args' e;\n      track_moves env mv e1\n  | BSjumptable arg mv arg' tbl =>\n      assertion (can_undef destroyed_by_jumptable e);\n      track_moves env mv (add_equation (Eq Full arg (R arg')) e)\n  | BSreturn None mv =>\n      track_moves env mv empty_eqs\n  | BSreturn (Some arg) mv =>\n      let arg' := loc_result (RTL.fn_sig f) in\n      do e1 <- add_equations_res arg (proj_sig_res (RTL.fn_sig f)) arg' empty_eqs;\n      track_moves env mv e1\n  end.\n\n(** The main transfer function for the dataflow analysis.  Like [transfer_aux],\n  it infers the equations that must hold \"before\" as a function of the\n  equations that must hold \"after\".  It also handles error propagation\n  and reporting. *)\n\nDefinition transfer (f: RTL.function) (env: regenv) (shapes: PTree.t block_shape)\n                    (pc: node) (after: res eqs) : res eqs :=\n  match after with\n  | Error _ => after\n  | OK e =>\n      match shapes!pc with\n      | None => Error(MSG \"At PC \" :: POS pc :: MSG \": unmatched block\" :: nil)\n      | Some shape =>\n          match transfer_aux f env shape e with\n          | None => Error(MSG \"At PC \" :: POS pc :: MSG \": invalid register allocation\" :: nil)\n          | Some e' => OK e'\n          end\n      end\n  end.\n\n(** The semilattice for dataflow analysis.  Operates on analysis results\n  of type [res eqs], that is, either a set of equations or an error\n  message.  Errors correspond to [Top].  Sets of equations are ordered\n  by inclusion. *)\n\nModule LEq <: SEMILATTICE.\n\n  Definition t := res eqs.\n\n  Definition eq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Equal a b\n    | Error _, Error _ => True\n    | _, _ => False\n    end.\n\n  Lemma eq_refl: forall x, eq x x.\n  Proof.\n    intros; destruct x; simpl; auto. red; tauto.\n  Qed.\n\n  Lemma eq_sym: forall x y, eq x y -> eq y x.\n  Proof.\n    unfold eq; intros; destruct x; destruct y; auto.\n    red in H; red; intros. rewrite H; tauto.\n  Qed.\n\n  Lemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    unfold eq; intros. destruct x; destruct y; try contradiction; destruct z; auto.\n    red in H; red in H0; red; intros. rewrite H. auto.\n  Qed.\n\n  Definition beq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.equal a b\n    | Error _, Error _ => true\n    | _, _ => false\n    end.\n\n  Lemma beq_correct: forall x y, beq x y = true -> eq x y.\n  Proof.\n    unfold beq, eq; intros. destruct x; destruct y.\n    apply EqSet.equal_2. auto.\n    discriminate.\n    discriminate.\n    auto.\n  Qed.\n\n  Definition ge (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Subset b a\n    | Error _, _ => True\n    | _, Error _ => False\n    end.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge, EqSet.Equal, EqSet.Subset; intros.\n    destruct x; destruct y; auto. intros; rewrite H; auto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge, EqSet.Subset; intros.\n    destruct x; auto; destruct y; try contradiction.\n    destruct z; eauto.\n  Qed.\n\n  Definition bot: t := OK empty_eqs.\n\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot, EqSet.Subset; simpl; intros.\n    destruct x; auto. intros. elim (EqSet.empty_1 H).\n  Qed.\n\n  Program Definition lub (x y: t) : t :=\n    match x, y return _ with\n    | OK a, OK b =>\n        OK (mkeqs (EqSet.union (eqs1 a) (eqs1 b))\n                  (EqSet2.union (eqs2 a) (eqs2 b)) _)\n    | OK _, Error _ => y\n    | Error _, _ => x\n    end.\n  Next Obligation.\n    split; intros.\n    apply EqSet2.union_1 in H. destruct H; rewrite eqs_same in H.\n    apply EqSet.union_2; auto. apply EqSet.union_3; auto.\n    apply EqSet.union_1 in H. destruct H; rewrite <- eqs_same in H.\n    apply EqSet2.union_2; auto. apply EqSet2.union_3; auto.\n  Qed.\n\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub, ge, EqSet.Subset; intros.\n    destruct x; destruct y; auto.\n    intros; apply EqSet.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, EqSet.Subset; intros.\n    destruct x; destruct y; auto.\n    intros; apply EqSet.union_3; auto.\n  Qed.\n\nEnd LEq.\n\n(** The backward dataflow solver is an instantiation of Kildall's algorithm. *)\n\nModule DS := Backward_Dataflow_Solver(LEq)(NodeSetBackward).\n\n(** The control-flow graph that the solver operates on is the CFG of\n  block shapes built by the structural check phase.  Here is its notion\n  of successors. *)\n\nDefinition successors_block_shape (bsh: block_shape) : list node :=\n  match bsh with\n  | BSnop mv s => s :: nil\n  | BSmove src dst mv s => s :: nil\n  | BSmakelong src1 src2 dst mv s => s :: nil\n  | BSlowlong src dst mv s => s :: nil\n  | BShighlong src dst mv s => s :: nil\n  | BSop op args res mv1 args' res' mv2 s => s :: nil\n  | BSopdead op args res mv s => s :: nil\n  | BSload chunk addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s => s :: nil\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s => s :: nil\n  | BSloaddead chunk addr args dst mv s => s :: nil\n  | BSstore chunk addr args src mv1 args' src' s => s :: nil\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s => s :: nil\n  | BScall sg ros args res mv1 ros' mv2 s => s :: nil\n  | BStailcall sg ros args mv1 ros' => nil\n  | BSbuiltin ef args res mv1 args' res' mv2 s => s :: nil\n  | BScond cond args mv args' s1 s2 => s1 :: s2 :: nil\n  | BSjumptable arg mv arg' tbl => tbl\n  | BSreturn optarg mv => nil\n  end.\n\nDefinition analyze (f: RTL.function) (env: regenv) (bsh: PTree.t block_shape) :=\n  DS.fixpoint_allnodes bsh successors_block_shape (transfer f env bsh).\n\n(** * Validating and translating functions and programs *)\n\n(** Checking equations at function entry point.  The RTL function receives\n  its arguments in the list [rparams] of pseudoregisters.  The LTL function\n  receives them in the list [lparams] of locations dictated by the\n  calling conventions, with arguments of type [Tlong] being split in\n  two 32-bit halves.  We check that the equations [e] that must hold\n  at the beginning of the functions are compatible with these calling\n  conventions, in the sense that all equations involving a pseudoreg\n  [r] from [rparams] is of the form [r = l [Full]] or [r = l [Low]]\n  or [r = l [High]], where [l] is the corresponding element of [lparams].\n\n  Note that [e] can contain additional equations [r' = l [kind]]\n  involving pseudoregs [r'] not in [rparams]: these equations are\n  automatically satisfied since the initial value of [r'] is [Vundef]. *)\n\nFunction compat_entry (rparams: list reg) (lparams: list (rpair loc)) (e: eqs)\n                      {struct rparams} : bool :=\n  match rparams, lparams with\n  | nil, nil => true\n  | r1 :: rl,  One l1 :: ll =>\n      compat_left r1 l1 e && compat_entry rl ll e\n  | r1 :: rl, Twolong l1 l2 :: ll =>\n      compat_left2 r1 l1 l2 e && compat_entry rl ll e\n  | _, _ => false\n  end.\n\n(** Checking the satisfiability of equations inferred at function entry\n  point.  We also check that the RTL and LTL functions agree in signature\n  and stack size. *)\n\nDefinition check_entrypoints_aux (rtl: RTL.function) (ltl: LTL.function)\n                                 (env: regenv) (e1: eqs) : option unit :=\n  do mv <- pair_entrypoints rtl ltl;\n  do e2 <- track_moves env mv e1;\n  assertion (compat_entry (RTL.fn_params rtl)\n                          (loc_parameters (RTL.fn_sig rtl)) e2);\n  assertion (can_undef destroyed_at_function_entry e2);\n  assertion (zeq (RTL.fn_stacksize rtl) (LTL.fn_stacksize ltl));\n  assertion (signature_eq (RTL.fn_sig rtl) (LTL.fn_sig ltl));\n  Some tt.\n\nLocal Close Scope option_monad_scope.\nLocal Open Scope error_monad_scope.\n\nDefinition check_entrypoints (rtl: RTL.function) (ltl: LTL.function)\n                             (env: regenv) (bsh: PTree.t block_shape)\n                             (a: PMap.t LEq.t): res unit :=\n  do e1 <- transfer rtl env bsh (RTL.fn_entrypoint rtl) a!!(RTL.fn_entrypoint rtl);\n  match check_entrypoints_aux rtl ltl env e1 with\n  | None => Error (msg \"invalid register allocation at entry point\")\n  | Some _ => OK tt\n  end.\n\n(** Putting it all together, this is the validation function for\n  a source RTL function and an LTL function generated by the external\n  register allocator. *)\n\nDefinition check_function (rtl: RTL.function) (ltl: LTL.function) (env: regenv): res unit :=\n  let bsh := pair_codes rtl ltl in\n  match analyze rtl env bsh with\n  | None => Error (msg \"allocation analysis diverges\")\n  | Some a => check_entrypoints rtl ltl env bsh a\n  end.\n\n(** [regalloc] is the external register allocator.  It is written in OCaml\n  in file [backend/Regalloc.ml]. *)\n\nParameter regalloc: RTL.function -> res LTL.function.\n\n(** Register allocation followed by validation. *)\n\nDefinition transf_function (f: RTL.function) : res LTL.function :=\n  match type_function f with\n  | Error m => Error m\n  | OK env =>\n      match regalloc f with\n      | Error m => Error m\n      | OK tf => do x <- check_function f tf env; OK tf\n      end\n  end.\n\nDefinition transf_fundef (fd: RTL.fundef) : res LTL.fundef :=\n  AST.transf_partial_fundef transf_function fd.\n\nDefinition transf_program (p: RTL.program) : res LTL.program :=\n  transform_partial_program transf_fundef p.\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/Allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.1870928843307848}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Tactics.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import 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 Dots.\n\nRequire Import ValidationUtil.\nRequire Import Dynamic.\nRequire MuIndExtract.\n\n\nLemma muForm_valid : muForm_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a ext1 ext0 Ha Hpos.\nrewrite -> def_istp in Ha.\nrewrite -> def_positive in Hpos.\nrewrite -> def_istp.\nunfold Defs.triv.\nrewrite -> def_mu.\napply tr_mu_formation.\n  {\n  eapply tr_eqtype_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma muEq_valid : muEq_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a b ext2 ext1 ext0 Ha Hposa Hposb.\nrewrite -> def_eqtp in Ha.\nrewrite -> def_positive in Hposa, Hposb.\nrewrite -> def_eqtp.\nunfold Defs.triv.\nrewrite -> !def_mu.\napply tr_mu_formation.\n  {\n  eapply tr_eqtype_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma muFormUniv_valid : muFormUniv_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a i ext2 ext1 ext0 Hi Ha Hpos.\nrewrite -> def_of in Hi, Ha |- *.\nrewrite -> def_positive in Hpos.\nunfold Defs.triv.\nrewrite -> !def_univ.\nrewrite -> !def_univ in Ha.\nunfold Defs.level in Hi.\nrewrite -> def_mu.\napply tr_equal_intro.\napply tr_mu_formation_univ.\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma muEqUniv_valid : muEqUniv_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a b i ext3 ext2 ext1 ext0 Hi Hab Hposa Hposb.\nrewrite -> def_eq in Hab |- *.\nrewrite -> def_of in Hi.\nrewrite -> def_positive in Hposa, Hposb.\nunfold Defs.triv.\nrewrite -> !def_univ.\nrewrite -> !def_univ in Hab.\nunfold Defs.level in Hi.\nrewrite -> !def_mu.\napply tr_equal_intro.\napply tr_mu_formation_univ.\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma def_eeqtp :\n  forall a b,\n    equiv (app (app Defs.eeqtp a) b) (prod (subtype a b) (subtype b a)).\nProof.\nintros a b.\nunfold Defs.eeqtp.\napply steps_equiv.\neapply star_step.\n  {\n  apply step_app1.\n  apply step_app2.\n  }\nsimpsub.\neapply star_step.\n  {\n  apply step_app2.\n  }\nsimpsub.\napply star_refl.\nQed.\n\n\n\nHint Rewrite def_eeqtp def_mu def_positive : prepare.\n\n\nLemma tr_prod_intro :\n  forall G a b m m' n n',\n    tr G (deq m m' a)\n    -> tr G (deq n n' b)\n    -> tr G (deq (ppair m n) (ppair m' n') (prod a b)).\nProof.\nintros G a b m m' n n' Hm Hn.\napply (tr_eqtype_convert _#3 (sigma a (subst sh1 b))).\n  {\n  apply tr_eqtype_symmetry.\n  apply tr_prod_sigma_equal.\n    {\n    eapply tr_inhabitation_formation; eauto.\n    }\n\n    {\n    eapply tr_inhabitation_formation; eauto.\n    }\n  }\napply tr_sigma_intro; auto.\n  {\n  simpsub.\n  auto.\n  }\n\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length unlift].\n    auto.\n    }\n    \n    {\n    cbn [length unlift].\n    simpsub.\n    auto.\n    }\n  cbn [length unlift].\n  simpsub.\n  cbn [List.app].\n  eapply tr_inhabitation_formation; eauto.\n  }\nQed.\n\n\nLemma muUnroll_valid : muUnroll_obligation.\nProof.\nprepare.\nintros G a ext1 ext0 Ha Hpos.\napply tr_prod_intro.\n  {\n  apply tr_mu_unroll; auto.\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  apply tr_mu_roll; auto.\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma muUnrollUniv_valid : muUnrollUniv_obligation.\nProof.\nprepare.\nintros G a i ext2 ext1 ext0 Hlv Ha Hpos.\napply tr_prod_intro.\n  {\n  eapply tr_mu_unroll_univ; eauto.\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  eapply tr_mu_roll_univ; eauto.\n  eapply tr_positive_eta2; eauto.\n  }\nQed.\n\n\nLemma muInd_valid : muInd_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a b m ext2 ext1 n ext0 Hhide Ha Hpos Hb Hm.\nunfold Defs.theta.\nunfold Defs.triv.\nrewrite -> def_istp in Ha.\nrewrite -> def_of in Hm.\nrewrite -> def_pi in Hb.\nrewrite -> def_subtype in Hb.\nrewrite -> def_mu in Hb, Hm.\nrewrite -> def_positive in Hpos.\nreplace (subst (dot (var 1) (dot triv (dot (var 0) (dot triv (sh 2))))) n)\n  with  (subst (dot (var 1) (dot triv (dot (var 0) (sh 2))))\n           (subst (under 3 (dot triv id)) n)).\n2:{\n  simpsub.\n  auto.\n  }\neapply MuIndExtract.tr_mu_ind_extract.\n  {\n  eapply tr_eqtype_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  rewrite <- (subst_into_absent_single _ _ _ triv Hhide) in Hb.\n  simpsubin Hb.\n  cbn [Nat.add] in Hb.\n  exact Hb.\n  }\n\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\nQed.\n\n\nLemma muIndUniv_valid : muIndUniv_obligation.\nProof.\nunfoldtop.\nunfold Defs.dof.\nintros G a b i m ext3 ext2 ext1 n ext0 Hhide Hi Ha Hpos Hb Hm.\nunfold Defs.theta.\nunfold Defs.triv.\nunfold Defs.level in Hi.\nrewrite -> !def_univ in Ha, Hb.\nrewrite -> def_of in Hm, Ha, Hi, Hb.\nrewrite -> def_pi in Hb.\nrewrite -> def_subtype in Hb.\nrewrite -> def_mu in Hb, Hm.\nrewrite -> def_positive in Hpos.\nrewrite -> def_prod in Hb.\nreplace (ppi1 (subst (dot (var 1) (dot triv (dot (var 0) (dot triv (sh 2))))) n))\n  with  (subst (dot (var 1) (dot triv (dot (var 0) (sh 2))))\n           (subst (under 3 (dot triv id)) (ppi1 n))).\n2:{\n  simpsub.\n  auto.\n  }\neapply (MuIndExtract.tr_mu_ind_univ_extract _ i a).\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\n\n  {\n  eapply tr_positive_eta2; eauto.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  rewrite <- (subst_into_absent_single _ _ _ triv Hhide) in Hb.\n  simpsubin Hb.\n  cbn [Nat.add] in Hb.\n  apply tr_equal_elim.\n  apply (tr_equal_eta2 _#4 (ppi2 (subst (dot (var 0) (dot (var 1) (dot (var 2) (dot triv (sh 4))))) n)) (ppi2 (subst (dot (var 0) (dot (var 1) (dot (var 2) (dot triv (sh 4))))) n))).\n  eapply tr_prod_elim2.\n  exact Hb.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  rewrite <- (subst_into_absent_single _ _ _ triv Hhide) in Hb.\n  simpsubin Hb.\n  cbn [Nat.add] in Hb.\n  eapply tr_prod_elim1.\n  exact Hb.\n  }\n\n  {\n  apply tr_equal_elim.\n  eapply tr_equal_eta2; eauto.\n  }\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ValidationMu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18692887840277242}}
{"text": "\nFrom Undecidability.FOL Require Import Syntax.Facts Syntax.Asimpl Deduction.FragmentNDFacts Deduction.FragmentNDConsistency Syntax.Theories Semantics.Tarski.FragmentFacts Semantics.Tarski.FragmentSoundness.\nFrom Undecidability.Synthetic Require Import Definitions DecidabilityFacts MPFacts 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.\nFrom Undecidability.FOL.Completeness Require Export TarskiConstructions EnumerationUtils.\n(* ** Completeness *)\n\n(* ** Standard Models **)\n\nSection Completeness.\n  Context {\u03a3f : funcs_signature} {\u03a3p : preds_signature}.\n  Context {HdF : eq_dec \u03a3f} {HdP : eq_dec \u03a3p}.\n  Variable eF : nat -> option \u03a3f.\n  Context {HeF : enumerator__T eF \u03a3f}.\n  Variable eP : nat -> option \u03a3p.\n  Context {HeP : enumerator__T eP \u03a3p}.\n\n  #[local] Hint Constructors bounded : core.\n\n  Section BotModel.\n    #[local] Existing Instance falsity_on | 0.\n    Variable T : theory.\n    Hypothesis T_closed : closed_T T.\n\n    Definition input_bot : ConstructionInputs :=\n      {|\n        NBot := \u22a5 ;\n        NBot_closed := bounded_falsity 0;\n\n        variant := falsity_on ;\n\n        In_T := T ;\n        In_T_closed := T_closed ;\n        TarskiConstructions.enum := form_enum_with_default \u22a5;\n        TarskiConstructions.enum_enum := form_default_is_enum _;\n        TarskiConstructions.enum_bounded := form_default_is_bounded (bounded_falsity _)\n      |}.\n\n    Definition output_bot := construct_construction input_bot.\n\n    Instance model_bot : interp term :=\n      {| i_func := func; i_atom := fun P v => atom P v \u2208 Out_T output_bot|}.\n\n    Lemma eval_ident rho (t : term) :\n      eval rho t = subst_term rho t.\n    Proof.\n      induction t in rho|-*.\n      - easy.\n      - cbn. easy.\n    Qed.\n    Hypothesis Hcon : consistent class T.\n\n    Lemma model_bot_correct phi rho :\n      (phi[rho] \u2208 Out_T output_bot <-> rho \u22a8 phi).\n    Proof.\n      revert rho. induction phi using form_ind_falsity; intros rho. 1,2,3: cbn.\n      - split; try tauto. intros H. apply Hcon.\n        apply Out_T_econsistent with output_bot. exists [\u22a5].\n        split; try apply Ctx. 2: now left. intros a [<-|[]]; easy.\n      - erewrite (Vector.map_ext_in _ _ _ (eval rho)). 1:easy.\n        easy.\n      - destruct b0. rewrite <- IHphi1. rewrite <- IHphi2. apply Out_T_impl.\n      - destruct q. cbn. setoid_rewrite <- IHphi. setoid_rewrite Out_T_all.\n        split; intros H t; asimpl; specialize (H t); now asimpl in H.\n    Qed. \n\n    Lemma model_bot_classical :\n      classical model_bot.\n    Proof.\n      intros rho phi psi. apply model_bot_correct, Out_T_prv.\n      use_theory (nil : list form). apply Pc.\n    Qed.\n\n    Lemma valid_T_model_bot phi :\n      phi \u2208 T -> var \u22a8 phi.\n    Proof.\n      intros H % (Out_T_sub output_bot). apply model_bot_correct. now rewrite subst_id.\n    Qed.\n  End BotModel.\n\n  Section StandardCompleteness.\n    Variables (T : @theory _ _ _ falsity_on) (phi : @form _ _ _ falsity_on).\n    Hypothesis (HT : closed_T T) (Hphi : closed phi).\n\n    Lemma semi_completeness_standard_classical_model :\n      valid_theory_C (classical (ff:=falsity_on)) T phi -> ~ ~ T \u22a2TC phi.\n    Proof.\n      intros Hval Hcons. rewrite refutation_prv in Hcons. \n      assert (Hcl : closed_T (T \u22c4 (\u00ac phi))) by (apply closed_T_extend; try econstructor; eauto).\n      unshelve eapply (model_bot_correct (T_closed := Hcl) Hcons (\u00ac phi) var).\n      - apply Out_T_sub. cbn. right. now asimpl.\n      - apply Hval. 1: apply model_bot_classical, Hcons. intros ? ?. apply valid_T_model_bot; intuition.\n    Qed.\n\n    Lemma semi_completeness_standard :\n      valid_theory T phi -> ~ ~ T \u22a2TC phi.\n    Proof.\n      intros H. apply semi_completeness_standard_classical_model.\n      intros D I rho _. apply (H D I rho).\n    Qed.\n\n    Definition stable P := ~~P -> P.\n\n    Lemma completeness_standard_stability :\n      stable (T \u22a2TC phi) -> valid_theory T phi -> T \u22a2TC phi.\n    Proof.\n      intros Hstab Hsem. now apply Hstab, semi_completeness_standard.\n    Qed.\n\n    Lemma completeness_classical_stability :\n      stable (T \u22a2TC phi) -> valid_theory_C (classical (ff := falsity_on)) T phi -> T \u22a2TC phi.\n    Proof.\n      intros Hstab Hsem. now apply Hstab, semi_completeness_standard_classical_model.\n    Qed.\n\n    Lemma completeness_standard_stability' :\n      (valid_theory_C (classical (ff := falsity_on)) T phi -> T \u22a2TC phi) -> stable (T \u22a2TC phi).\n    Proof.\n      intros Hcomp Hdn. apply Hcomp.\n      intros D I rho Hclass Hsat. unfold classical in Hclass. cbn in Hclass.\n      eapply (Hclass _ _ \u22a5). intros Hsat2. exfalso. apply Hdn. intros [A [HA Hc]]. apply Hsat2.\n      eapply sound_for_classical_model.\n      - easy.\n      - exact Hc.\n      - intros a Ha. apply Hsat. apply HA, Ha.\n    Qed.\n  End StandardCompleteness.\n\n  Section ExplodingCompletenessConstr.\n    Variables (T : @theory _ _ _ falsity_on).\n    Hypothesis (HT : closed_T T).\n\n    Definition expl_interp := (model_bot HT).\n    Existing Instance expl_interp.\n\n    Lemma model_expl_correct phi rho :\n      (phi[rho] \u2208 Out_T (output_bot HT) <-> sat_bot (falsity \u2208 Out_T (output_bot HT)) rho phi).\n    Proof.\n      revert rho. induction phi using form_ind_falsity; intros rho. 1,2,3: cbn.\n      - easy.\n      - erewrite (Vector.map_ext_in _ _ _ (eval rho)). 1:easy.\n        easy.\n      - destruct b0. unfold sat_bot in *. rewrite <- IHphi1. rewrite <- IHphi2. apply Out_T_impl.\n      - destruct q. cbn. unfold sat_bot in *. setoid_rewrite <- IHphi. setoid_rewrite Out_T_all.\n        split; intros H t; asimpl; specialize (H t); now asimpl in H.\n    Qed.\n\n    Lemma model_bot_exploding :\n      FragmentFacts.exploding (model_bot HT) (falsity \u2208 Out_T (output_bot HT)).\n    Proof.\n      intros rho phi. cbn. intros H. apply model_expl_correct.\n      apply (Out_T_impl (output_bot HT) \u22a5 (phi[rho])). 2: easy.\n      apply Out_T_prv. exists []. split.\n      - intros ? [].\n      - apply II. apply FragmentND.Exp. apply Ctx. now left.\n    Qed.\n\n    Lemma valid_T_model_exploding phi :\n      phi \u2208 T -> sat_bot (falsity \u2208 Out_T (output_bot HT)) var phi.\n    Proof.\n      intros H % (Out_T_sub (output_bot HT)). apply model_expl_correct. now rewrite subst_id.\n    Qed.\n  End ExplodingCompletenessConstr.\n  Section ExplodingCompleteness.\n\n    #[local] Existing Instance falsity_on | 0.\n    Lemma semi_completeness_exploding T phi :\n      closed_T T -> closed phi -> valid_exploding_theory T phi -> T \u22a2TC phi.\n    Proof.\n      intros HT Hphi Hval.\n      assert (Hcl : closed_T (T \u22c4 (\u00ac phi))).\n      1: { intros ? ?; subst; eauto. destruct H as [Hl| ->].\n           + apply HT, Hl.\n           + repeat econstructor. apply Hphi. }\n      apply refutation_prv.\n      apply (@Out_T_econsistent _ _ _ (output_bot Hcl)).\n      use_theory [\u22a5]. 2: { apply Ctx. now left. }\n      intros ? [<-|[]].\n      specialize (Hval term (model_bot Hcl) (falsity \u2208 Out_T (output_bot Hcl)) var (@model_bot_exploding _ Hcl)).\n      rewrite <- (@subst_id _ _ _ _ \u22a5 var). 2: easy.\n      apply (@model_expl_correct _ Hcl (\u00ac phi) var).\n      - apply Out_T_sub. cbn. rewrite subst_id. 2:easy. now right.\n      - apply Hval. intros psi Hpsi. apply model_expl_correct. rewrite subst_id; [|easy].\n        apply Out_T_sub. left. apply Hpsi.\n    Qed.\n\n  End ExplodingCompleteness.\n\n\n  Section FragmentCompleteness.\n    #[local] Existing Instance falsity_off | 0.\n  End FragmentCompleteness.\n \n\n  Section MPStrongCompleteness.\n    Hypothesis mp : MP.\n    Variables (T : @theory _ _ _ falsity_on) (phi : @form _ _ _ falsity_on).\n    Hypothesis (HT : closed_T T) (Hphi : closed phi).\n    Hypothesis (He : list_enumerable T).\n\n    Lemma mp_tprv_stability :\n      ~ ~ T \u22a2TC phi -> T \u22a2TC phi.\n    Proof.\n      apply (MP_stable_enumerable mp). 2: apply dec_form; eauto.\n      apply list_enumerable_enumerable. destruct He as [L HL]. eexists. apply enum_tprv. apply HL.\n    Qed.\n\n    Lemma mp_standard_completeness :\n      valid_theory T phi -> T \u22a2TC phi.\n    Proof.\n      apply completeness_standard_stability; eauto. unfold stable.\n      apply mp_tprv_stability.\n    Qed.\n  End MPStrongCompleteness.\n\n(* *** Minimal Models **)\n\n  Section FragmentModel.\n    #[local] Existing Instance falsity_off | 0.\n    Variable T : theory.\n    Hypothesis T_closed : closed_T T.\n\n    Variable GBot : form.\n    Hypothesis GBot_closed : closed GBot.\n\n    Definition input_fragment :=\n      {|\n        NBot := GBot ;\n        NBot_closed := GBot_closed ;\n\n        variant := falsity_off ;\n\n        In_T := T ;\n        In_T_closed := T_closed ;\n\n        TarskiConstructions.enum := form_enum_with_default GBot;\n        TarskiConstructions.enum_enum := form_default_is_enum _;\n        TarskiConstructions.enum_bounded := form_default_is_bounded (GBot_closed)\n      |}.\n\n    Definition output_fragment := construct_construction input_fragment.\n\n    Instance model_fragment : interp term :=\n      {| i_func := func; i_atom := fun P v => atom P v \u2208 Out_T output_fragment|}.\n\n    Lemma model_fragment_correct phi rho :\n      (phi[rho] \u2208 Out_T output_fragment <-> rho \u22a8 phi).\n    Proof.\n      revert rho. unfold model_fragment, output_fragment, input_fragment in *; cbn in *.\n      remember falsity_off as ff eqn:Hff.\n      induction phi; intros rho. 1,2,3: cbn.\n      - split; try tauto. discriminate Hff.\n      - erewrite (Vector.map_ext_in _ _ _ (eval rho)). 1:easy.\n        easy.\n      - destruct b0. rewrite <- IHphi1. rewrite <- IHphi2. apply Out_T_impl. 1-2:congruence.\n      - destruct q. cbn. setoid_rewrite <- IHphi. setoid_rewrite Out_T_all. 2:congruence.\n        split; intros H t; asimpl; specialize (H t); now asimpl in H.\n    Qed.\n\n    Lemma model_fragment_classical :\n      classical model_fragment.\n    Proof.\n      intros rho phi psi. apply model_fragment_correct, Out_T_prv.\n      use_theory (nil : list form). apply Pc.\n    Qed.\n\n    Lemma valid_T_fragment phi :\n      phi \u2208 T -> var \u22a8 phi.\n    Proof.\n      intros H % (Out_T_sub output_fragment). apply model_fragment_correct. rewrite subst_id. 1:easy. easy.\n    Qed.\n  End FragmentModel.\n\n  Section FragmentCompleteness.\n    #[local] Existing Instance falsity_off | 0.\n    Lemma semi_completeness_fragment T phi :\n      closed_T T -> closed phi -> valid_theory T phi -> T \u22a2TC phi.\n    Proof.\n      intros HT Hphi Hval.\n      apply (@Out_T_econsistent _ _ _ (@output_fragment T HT phi Hphi)).\n      use_theory [phi[var]]. 2: apply Ctx; left; now rewrite subst_id.\n      intros ? [<- | []].\n      apply (@model_fragment_correct T HT phi Hphi phi var).\n      apply Hval. intros psi Hpsi.\n      apply valid_T_fragment, Hpsi.\n    Qed.\n  End FragmentCompleteness.\n\n  Section LEM_Equivalence.\n    Definition completeness_arbitrary := \n      forall (T : @theory _ _ _ falsity_on) (phi : @form _ _ _ falsity_on),\n             closed_T T -> closed phi ->\n             valid_theory_C (classical (ff := falsity_on)) T phi -> T \u22a2TC phi.\n    Definition LEM := forall (P:Prop), P \\/ ~ P.\n\n    Lemma bot_valid_stable (T : @theory _ _ _ falsity_on) : closed_T T -> stable (valid_theory_C (classical (ff := falsity_on)) T \u22a5).\n    Proof.\n      intros Hclosed HH D I rho Hclass H.\n      apply HH. intros Hc. apply (Hc D I rho Hclass H).\n    Qed.\n    Lemma bot_deriv_stable (T : @theory _ _ _ falsity_on) : completeness_arbitrary -> closed_T T -> stable (@tprv _ _ _ class T \u22a5).\n    Proof.\n      intros Hcomp Hclosed Hc. apply (Hcomp T \u22a5). 1: eauto. 1: econstructor.\n      apply bot_valid_stable. 1:easy. intros Hd. apply Hc. intros [L [HT HL]]. apply Hd.\n      intros D I rho Hclass Harg.\n      eapply sound_for_classical_model; try easy. 1: exact HL.\n      intros l Hl. apply Harg. now apply HT.\n    Qed.\n    Existing Instance falsity_on.\n    Lemma arbitrary_completeness_is_LEM : completeness_arbitrary -> LEM.\n    Proof.\n      intros HC P.\n      pose (fun x : form => closed x /\\ (P \\/ ~P)) as T.\n      assert (closed_T T) as Hclosed by (intros k; cbv; tauto).\n      pose proof (@bot_deriv_stable T HC Hclosed).\n      enough (T \u22a2TC \u22a5) as [[|lx lr] [HL HL']].\n      - exfalso. eapply consistent_ND. apply HL'.\n      - eapply HL. now left.\n      - enough (~~ (P \\/ ~P)).\n        + apply H. intros Hc. apply H0. intros Hc2. apply Hc. exists [\u22a5]. split; try (apply Ctx; now left).\n          intros ? [<- | []]. cbv. split; try apply Hc2. econstructor.\n        + tauto.\n    Qed.\n\n    Lemma LEM_is_arbitrary_completeness : LEM -> completeness_arbitrary.\n    Proof.\n      intros Hlem T phi HT Hphi Hvalid.\n      apply completeness_classical_stability; eauto.\n      intros H. destruct (Hlem (T \u22a2TC phi)); tauto.\n    Qed.\n  End LEM_Equivalence.\n\n  Section MP_Equivalence.\n    Definition completeness_enumerable := \n      forall (T : @theory _ _ _ falsity_on) (phi : @form _ _ _ falsity_on),\n             closed_T T -> closed phi -> enumerable T ->\n             valid_theory_C (classical (ff := falsity_on)) T phi -> T \u22a2TC phi.\n\n    Lemma bot_deriv_stable_enum (T : @theory _ _ _ falsity_on) : completeness_enumerable -> closed_T T -> enumerable T ->\n      stable (@tprv _ _ _ class T \u22a5).\n    Proof.\n      intros Hcomp Hclosed Henum Hc. apply (Hcomp T \u22a5). 1: eauto. 1: econstructor. 1: apply Henum.\n      apply bot_valid_stable. 1:easy. intros Hd. apply Hc. intros [L [HT HL]]. apply Hd.\n      intros D I rho Hclass Harg.\n      eapply sound_for_classical_model; try easy. 1: exact HL.\n      intros l Hl. apply Harg. now apply HT.\n    Qed.\n    Existing Instance falsity_on.\n\n    Lemma MP_is_enumerable_completeness : MP -> completeness_enumerable.\n    Proof.\n      intros Hmp T phi HT Hphi Henum Hvalid.\n      apply completeness_classical_stability; eauto. unfold stable.\n      eapply mp_tprv_stability; try tauto. now eapply enumerable_list_enumerable.\n    Qed.\n\n    Lemma enumerable_completeness_is_MP : completeness_enumerable -> MP.\n    Proof.\n      intros HC f Hf.\n      pose (fun x : form => exists n, x = \u22a5 /\\ f n = true) as T.\n      assert (closed_T T) as Hclosed by now intros k [n [-> Hn]].\n      assert (enumerable T) as Henum.\n      { exists (fun n => if f n then Some (\u22a5) else None). intros phi; split; intros H.\n        + destruct H as (n & Heq & Hfn). exists n. rewrite Hfn. now rewrite Heq.\n        + destruct H as (n & Hn). unfold T. exists n. destruct (f n); try congruence.\n          split; try easy. congruence.\n       }\n      pose proof (@bot_deriv_stable_enum T HC Hclosed Henum).\n      enough (T \u22a2TC \u22a5) as [[|lx lr] [HL HL']].\n      - exfalso. eapply consistent_ND. apply HL'.\n      - destruct (HL lx) as (n & Heq & Hfn). 1:now left. now exists n.\n      - apply H. intros Hc. apply Hf. intros [n Hn]. apply Hc. exists [\u22a5]. split.\n        + intros ? [<- | []]. unfold T. exists n. split; try easy.\n        + apply Ctx; now left.\n    Qed.\n\n  End MP_Equivalence.\n\nEnd Completeness.\n\n(* ** Extending the Completeness Results *)\n(*\nSection FiniteCompleteness.\n  Context {Sigma : Signature}.\n  Context {HdF : eq_dec Funcs} {HdP : eq_dec Preds}.\n  Context {HeF : enumT Funcs} {HeP : enumT Preds}.\n\n  Lemma list_completeness_standard A phi :\n    ST__f -> valid_L SM A phi -> A \u22a2CE phi.\n  Proof.\n    intros stf Hval % valid_L_to_single. apply prv_from_single.\n    apply con_T_correct. apply completeness_standard_stability.\n    1: intros ? ? []. 1: apply close_closed. 2: now apply valid_L_valid_T in Hval.\n    apply stf, fin_T_con_T.\n    - intros ? ? [].\n    - eapply close_closed.\n  Qed.\n\n  Lemma list_completeness_expl A phi :\n    valid_L EM A phi -> A \u22a2CE phi.\n  Proof.\n    intros Hval % valid_L_to_single. apply prv_from_single.\n    apply tprv_list_T. apply completeness_expl. 1: intros ? ? [].\n    1: apply close_closed. now apply valid_L_valid_T in Hval.\n  Qed.\n\n  Lemma list_completeness_fragment A phi :\n    valid_L BLM A phi -> A \u22a2CL phi.\n  Proof.\n    intros Hval % valid_L_to_single. apply prv_from_single.\n    apply tprv_list_T. apply semi_completeness_fragment. 1: intros ? ? [].\n    1: apply close_closed. now apply valid_L_valid_T in Hval.\n  Qed.\nEnd FiniteCompleteness.\n\nSection StrongCompleteness.\n  Context {Sigma : Signature}.\n  Context {HdF : eq_dec Funcs} {HdP : eq_dec Preds}.\n  Context {HeF : enumT Funcs} {HeP : enumT Preds}.\n\n  Lemma dn_inherit (P Q : Prop) :\n    (P -> Q) -> ~ ~ P -> ~ ~ Q.\n  Proof. tauto. Qed.\n\n  Lemma strong_completeness_standard (S : stab_class) T phi :\n    (forall (T : theory) (phi : form), S Sigma T -> stable (tmap (fun psi : form => (sig_lift psi)[ext_c]) T \u22a2TC phi)) -> @map_closed S Sigma (sig_ext Sigma) (fun phi => (sig_lift phi)[ext_c]) -> S Sigma T -> T \u22abS phi -> T \u22a2TC phi.\n  Proof.\n    intros sts cls HT Hval. apply sig_lift_out_T. apply completeness_standard_stability.\n    1: apply lift_ext_c_closes_T. 1: apply lift_ext_c_closes. 2: apply (sig_lift_subst_valid droppable_S Hval).\n    now apply sts.\n  Qed.\n\n  Lemma strong_completeness_expl T phi :\n    T \u22abE phi -> T \u22a2TC phi.\n  Proof.\n    intros Hval. apply sig_lift_out_T, completeness_expl.\n    1: apply lift_ext_c_closes_T. 1: apply lift_ext_c_closes.\n    apply (sig_lift_subst_valid droppable_E Hval).\n  Qed.\n\n  Lemma strong_completeness_fragment T phi :\n    T \u22abM phi -> T \u22a9CL phi.\n  Proof.\n    intros Hval. apply sig_lift_out_T, semi_completeness_fragment.\n    1: apply lift_ext_c_closes_T. 1: apply lift_ext_c_closes.\n    apply (sig_lift_subst_valid droppable_BL Hval).\n  Qed.\n\nEnd StrongCompleteness.\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/Completeness/TarskiCompleteness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1869288776248054}}
{"text": "(* En este archivo se demuestra la correcci\u00f3n de la acci\u00f3n receiveIntent *)\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.\nRequire Export Coq.Arith.PeanoNat.\nImport PeanoNat.Nat.\n\nSection VerifyOldApp.\n\nLemma verifyOldAppCorrect : forall (s:System) (a:idApp) (sValid: validstate s),\n    (pre (verifyOldApp a) s) -> post_verifyOldApp a s (verifyOldApp_post a s).\nProof.\n    simpl.\n    unfold pre_verifyOldApp, post_verifyOldApp.\n    intros.\n    destruct_conj H.\n    unfold verifyOldApp_post.\n    repeat split; auto; simpl.\n  - intros a' lPerm' H3.\n    elim (classic (a=a')); intros.\n    rewrite H1 in H3.\n    rewrite <- addAndApply in H3.\n    inversion H3.\n    destructVS sValid.\n    destructSC statesConsistencyVS a'.\n    clear certSC defPermsSC grantedPermGroupsSC.\n\n    assert (In a' (apps (state s)) \\/\n          (exists sysapp : SysImgApp,\n             In sysapp (systemImage (environment s)) /\\ idSI sysapp = a')).\n    rewrite <- H1. auto.\n    apply permsSC in H4.\n    destruct H4 as [lPerm H4].\n    exists lPerm. split; auto.\n    intros. inversion H6.\n\n    rewrite overrideNotEq in H3; auto.\n    exists lPerm'. auto.\n  - intros a' lPerm H3.\n    elim (classic (a=a')); intros.\n    exists nil. rewrite H1.\n    split. rewrite <- addAndApply. auto.\n    intros; auto.\n\n    exists lPerm.\n    rewrite overrideNotEq.\n    split. auto.\n    intros. contradiction. auto.\n\n  - rewrite <- addAndApply. auto.\n\n  - apply addPreservesCorrectness.\n    apply permsCorrect;auto.\n\n  - intros a' lGroup' H3.\n    elim (classic (a=a')); intros.\n    rewrite H1 in H3.\n    rewrite <- addAndApply in H3.\n    inversion H3.\n    destructVS sValid.\n    destructSC statesConsistencyVS a'.\n    clear mfstSC certSC defPermsSC permsSC.\n\n    assert (In a' (apps (state s)) \\/\n          (exists sysapp : SysImgApp,\n             In sysapp (systemImage (environment s)) /\\ idSI sysapp = a')).\n    rewrite <- H1. auto.\n    apply grantedPermGroupsSC in H4.\n    destruct H4 as [lPerm H4].\n    exists lPerm. split; auto.\n    intros. inversion H6.\n\n    rewrite overrideNotEq in H3; auto.\n    exists lGroup'. auto.\n\n  - intros a' lGroup H3.\n    elim (classic (a=a')); intros.\n    exists nil. rewrite H1.\n    split. rewrite <- addAndApply. auto.\n    intros; auto. \n\n    exists lGroup.\n    rewrite overrideNotEq.\n    split. auto.\n    intros. contradiction. auto.\n\n  - rewrite <- addAndApply. auto.\n\n  - apply addPreservesCorrectness.\n    apply grantedPermGroupsCorrect;auto.\n\n  - intros a' H1. right. auto.\n\n  - intros. destruct H1; auto.\n\n  - auto.\nQed.\n\nLemma notPreVerifyThenError : forall (s : System) (a : idApp),\n  ~ pre (verifyOldApp a) s -> validstate s ->\n    exists ec : ErrorCode,\n      response (step s (verifyOldApp a)) = error ec /\\\n      ErrorMsg s (verifyOldApp a) ec /\\ s = system (step s (verifyOldApp a)).\nProof.\n    intros. simpl in H.\n    simpl. unfold verifyOldApp_safe, verifyOldApp_pre.\n    case_eq (negb (isAppInstalledBool a s)); intros; simpl.\n\n    exists no_such_app.\n    split; auto. split; auto.\n    unfold not. intros.\n    rewrite negb_true_iff in H1.\n    apply isAppInstalled_iff in H2.\n    rewrite H1 in H2. inversion H2.\n\n    case_eq (InBool idApp idApp_eq a (alreadyVerified (state s))); intros; simpl.\n\n    exists already_verified.\n    repeat split;auto.\n    unfold InBool in H2.\n    rewrite existsb_exists in H2.\n    destruct H2 as [a' [H2 H3]].\n    destruct (idApp_eq a a').\n    rewrite e. auto.\n    inversion H3.\n\n    case_eq (negb (isOldAppBool a s)); intros; simpl.\n\n    exists no_verification_needed.\n    repeat split;auto.\n    unfold not. intros.\n    rewrite negb_true_iff in H3.\n    apply isOld_isOldBool in H4.\n    rewrite H3 in H4. inversion H4.\n    auto.\n\n    destruct H.\n    unfold pre_verifyOldApp.\n    rewrite negb_false_iff in H1.\n    split.\n  - rewrite isAppInstalled_iff. auto.\n  - split.\n -- unfold not. intros.\n    apply (In_InBool idApp idApp_eq) in H.\n    rewrite H2 in H. inversion H.\n -- rewrite negb_false_iff in H3.\n    apply isOldBool_isOld.\n    auto. auto.\nQed.\n\nLemma verifyOldAppIsSound : forall (s:System) (a:idApp),\n        validstate s -> exec s (verifyOldApp a) (system (step s (verifyOldApp a))) (response (step s (verifyOldApp a))).\nProof.\n    intros s a vs.\n    unfold exec.\n    split; auto.\n    elim (classic (pre (verifyOldApp a) s));intro.\n  - left. assert (verifyOldApp_pre a s = None).\n    unfold verifyOldApp_pre.\n    destruct H. destruct H0.\n    rewrite isAppInstalled_iff in H.\n    rewrite <- negb_false_iff in H.\n    rewrite H.\n    case_eq (InBool idApp idApp_eq a (alreadyVerified (state s))); intros.\n    unfold InBool in H2.\n    apply existsb_exists in H2. destruct H2 as [a' [H2 H3]].\n    destruct (idApp_eq a a').\n    rewrite <- e in H2. contradiction.\n    inversion H3.\n    clear H2.\n    apply isOld_isOldBool in H1.\n    rewrite <- negb_false_iff in H1.\n    rewrite H1. auto. auto.\n\n    simpl.\n    unfold verifyOldApp_safe;simpl.\n    rewrite H0. simpl.\n    split; auto.\n    split; auto.\n    apply verifyOldAppCorrect;auto.\n  - right. apply notPreVerifyThenError; auto.\nQed.\n\nEnd VerifyOldApp.", "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/VerifyOldAppIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1869288776248054}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Ltac2 Require Import Ltac2.\n\nFrom Coq Require Import Ensembles Bool.\nFrom Coq.Logic Require Import FunctionalExtensionality Eqdep_dec.\nFrom Equations Require Import Equations.\n\nRequire Import Coq.Program.Tactics.\n\nFrom MatchingLogic Require Import\n    Syntax\n    DerivedOperators_Syntax\n    ProofSystem\n    IndexManipulation\n    wftactics\n    ProofInfo\n    BasicProofSystemLemmas\n.\nFrom MatchingLogic.ProofMode Require Import Basics\n                                            Propositional\n                                            Firstorder.\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.Substitution.Notations\n  MatchingLogic.DerivedOperators_Syntax.Notations\n  MatchingLogic.ProofInfo.Notations\n.\n\nSet Default Proof Mode \"Classic\".\n\nOpen Scope ml_scope.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\n\nLemma Knaster_tarski {\u03a3 : Signature}\n  (\u0393 : Theory) (\u03d5 \u03c8 : Pattern)  (i : ProofInfo)\n  {pile : ProofInfoLe (\n        {| pi_generalized_evars := \u2205;\n           pi_substituted_svars := \u2205;\n           pi_uses_kt := true ;\n           pi_uses_advanced_kt := has_bound_variable_under_mu \u03d5 ; (* TODO depends on \u03d5*)\n        |}) i} :\n  well_formed (mu, \u03d5) ->\n  \u0393 \u22a2i (instantiate (mu, \u03d5) \u03c8) ---> \u03c8 using i ->\n  \u0393 \u22a2i (mu, \u03d5) ---> \u03c8 using i.\nProof.\n  intros Hfev [pf Hpf].\n  unshelve (eexists).\n  {\n    apply ProofSystem.Knaster_tarski.\n    { exact Hfev. }\n    { exact pf. }\n  }\n  {\n    simpl.\n    constructor; simpl.\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      apply Hpf2.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      apply Hpf3.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      unfold is_true in Hpf4.\n      rewrite implb_true_iff in Hpf4.\n      destruct i. cbn in *.\n      destruct pile as [Hpile1 [Hpile2 [Hpile3 Hpile4 ] ] ]. cbn in *.\n      exact Hpile3.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      unfold is_true in Hpf4.\n      rewrite implb_true_iff in Hpf4.\n      destruct i. cbn in *.\n      destruct pile as [Hpile1 [Hpile2 [Hpile3 Hpile4 ] ] ]. cbn in *.\n      unfold is_true.\n      rewrite implb_true_iff. intros H1.\n      rewrite andb_true_r.\n      rewrite orb_true_iff in H1.\n      destruct H1 as [H1|H1].\n      {\n        rewrite H1 in Hpile4. simpl in Hpile4.\n        exact Hpile4.\n      }\n      {\n        rewrite H1 in Hpf5. simpl in Hpf5.\n        destruct_and!. assumption.\n      }\n    }\n  }\nDefined.\n\nLemma Svar_subst {\u03a3 : Signature}\n  (\u0393 : Theory) (\u03d5 \u03c8 : Pattern) (X : svar)  (i : ProofInfo)\n  {pile : ProofInfoLe (\n        {| pi_generalized_evars := \u2205;\n           pi_substituted_svars := {[X]};\n           pi_uses_kt := false ;\n           pi_uses_advanced_kt := false ;\n        |}) i} :\n  well_formed \u03c8 ->\n  \u0393 \u22a2i \u03d5 using i ->\n  \u0393 \u22a2i (\u03d5^[[svar: X \u21a6 \u03c8]]) using i.\nProof.\n  intros wf\u03c8 [pf Hpf].\n  unshelve (eexists).\n  {\n   apply ProofSystem.Svar_subst.\n   { pose proof (Hwf := proved_impl_wf _ _ pf). exact Hwf. }\n   { exact wf\u03c8. }\n   { exact pf. }\n  }\n  {\n    simpl.\n    constructor; simpl.\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      apply Hpf2.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      pose proof (Hpile := pile_impl_allows_svsubst_X _ _ _ _ pile).\n      clear -Hpile Hpf3.\n      set_solver.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      exact Hpf4.\n    }\n    {\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      exact Hpf5.\n    }\n  }\nDefined.\n\nLemma Pre_fixp {\u03a3 : Signature}\n  (\u0393 : Theory) (\u03d5 : Pattern) :\n  well_formed (patt_mu \u03d5) ->\n  \u0393 \u22a2i (instantiate (patt_mu \u03d5) (patt_mu \u03d5) ---> (patt_mu \u03d5))\n  using BasicReasoning.\nProof.\n  intros wf\u03d5.\n  unshelve (eexists).\n  {\n    apply ProofSystem.Pre_fixp.\n    { exact wf\u03d5. }\n  }\n  {\n    simpl.\n    abstract(solve_pim_simple).\n  }\nDefined.\n\nLemma mu_monotone {\u03a3 : Signature} \u0393 \u03d5\u2081 \u03d5\u2082 X (i : ProofInfo):\n  ProofInfoLe ( (ExGen := \u2205, SVSubst := {[X]}, KT := true, AKT := has_bound_variable_under_mu \u03d5\u2081^{{svar:X\u21a60}})) i ->\n  svar_has_negative_occurrence X \u03d5\u2081 = false ->\n  svar_has_negative_occurrence X \u03d5\u2082 = false ->\n  \u0393 \u22a2i \u03d5\u2081 ---> \u03d5\u2082 using i->\n  \u0393 \u22a2i (patt_mu (\u03d5\u2081^{{svar: X \u21a6 0}})) ---> (patt_mu (\u03d5\u2082^{{svar: X \u21a6 0}}))\n  using i.\nProof.\n  intros pile noneg\u03d5\u2081 noneg\u03d5\u2082 Himp.\n  pose proof (wf\u03d512 := proved_impl_wf _ _ (proj1_sig Himp)).\n  assert(wf\u03d5\u2081 : well_formed \u03d5\u2081) by wf_auto2.\n  assert(wf\u03d5\u2082 : well_formed \u03d5\u2082) by wf_auto2.\n\n  apply Knaster_tarski.\n  { try_solve_pile. }\n  { \n    wf_auto2.\n  }\n\n  pose proof (Htmp := @Svar_subst \u03a3 \u0393 (\u03d5\u2081 ---> \u03d5\u2082) (mu, \u03d5\u2082^{{svar: X \u21a6 0}}) X i).\n  feed specialize Htmp.\n  { try_solve_pile. }\n  { wf_auto2. }\n  { exact Himp. }\n  unfold free_svar_subst in Htmp.\n  simpl in Htmp.\n  fold free_svar_subst in Htmp.\n\n  pose proof (Hpf := Pre_fixp \u0393 (\u03d5\u2082^{{svar: X \u21a6 0}})).\n  simpl in Hpf.\n\n  unshelve (eapply (cast_proof' \u0393 _ _) in Hpf).\n  3: { \n  erewrite bound_to_free_set_variable_subst.\n    5: { apply svar_quantify_not_free. }\n    4: {\n     apply svar_quantify_closed_mu.\n     unfold well_formed, well_formed_closed in *. destruct_and!. auto.\n    }\n    3: {\n       apply svar_quantify_closed_mu.\n       unfold well_formed, well_formed_closed in *. destruct_and!. auto.\n    }\n    2: lia.\n    reflexivity.\n  }\n\n  2: abstract (wf_auto2).\n\n  eapply (cast_proof' \u0393) in Hpf.\n  2: {\n    rewrite svar_open_svar_quantify.\n    { unfold well_formed, well_formed_closed in *. destruct_and!. auto. }\n    reflexivity.\n  }\n\n\n  assert(well_formed_positive (\u03d5\u2082^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?.\n    apply wfp_free_svar_subst; auto.\n    { apply svar_quantify_closed_mu. auto. }\n    { simpl. split_and!.\n      2: apply well_formed_positive_svar_quantify; assumption.\n      apply no_negative_occurrence_svar_quantify; auto.\n    }\n  }\n\n  assert(well_formed_closed_mu_aux (\u03d5\u2082^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) 0 = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?; auto.\n    replace 0 with (0 + 0) at 3 by lia.\n    apply wfc_mu_free_svar_subst; auto.\n    simpl.\n    apply svar_quantify_closed_mu. assumption.\n  }\n\n  assert(well_formed_closed_ex_aux (\u03d5\u2082^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) 0 = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?; auto.\n    replace 0 with (0 + 0) at 3 by lia.\n    apply wfc_ex_free_svar_subst; auto.\n    simpl.\n    apply svar_quantify_closed_ex. assumption.\n  }\n\n  assert(well_formed_positive (\u03d5\u2081^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?.\n    apply wfp_free_svar_subst; auto.\n    { apply svar_quantify_closed_mu. auto. }\n    { simpl. split_and!.\n      2: apply well_formed_positive_svar_quantify; assumption.\n      apply no_negative_occurrence_svar_quantify; auto.\n    }\n  }\n\n  assert(well_formed_closed_mu_aux (\u03d5\u2081^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) 0 = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?; auto.\n    replace 0 with (0 + 0) at 3 by lia.\n    apply wfc_mu_free_svar_subst; auto.\n    simpl.\n    apply svar_quantify_closed_mu. assumption.\n  }\n\n  assert(well_formed_closed_ex_aux (\u03d5\u2081^[[svar: X \u21a6 mu , \u03d5\u2082^{{svar: X \u21a6 0}}]]) 0 = true).\n  {\n    unfold well_formed, well_formed_closed in *. destruct_and!. simpl; split_and?; auto.\n    replace 0 with (0 + 0) at 3 by lia.\n    apply wfc_ex_free_svar_subst; auto.\n    simpl.\n    apply svar_quantify_closed_ex. assumption.\n  }\n\n  apply useBasicReasoning with (i := i) in Hpf.\n  epose proof (Hsi := syllogism_meta _ _ _ Htmp Hpf).\n  simpl.\n\n  eapply (@cast_proof' \u03a3 \u0393).\n  1: {\n    erewrite bound_to_free_set_variable_subst with (X := X).\n    5: { apply svar_quantify_not_free. }\n    4: {\n         apply svar_quantify_closed_mu.\n         unfold well_formed, well_formed_closed in *. destruct_and!. auto.\n    }\n    3: {\n         apply svar_quantify_closed_mu.\n         unfold well_formed, well_formed_closed in *. destruct_and!. auto.\n    }\n    2: lia.\n    reflexivity.\n  }\n\n  eapply (cast_proof' \u0393).\n  1: {\n    rewrite svar_open_svar_quantify.\n    { unfold well_formed, well_formed_closed in *. destruct_and!. auto. }\n    reflexivity.\n  }\n  apply Hsi.\n  Unshelve.\n  all: abstract(wf_auto2).\nDefined.\n\nClose Scope ml_scope.\nClose Scope string_scope.\nClose Scope list_scope.\n", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/ProofMode/FixPoint.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3345894346180164, "lm_q1q2_score": 0.18681031336664933}}
{"text": "Require Import id_and_loc augmented mmemory mimperative language mlattice bridge types bijection Coq.Program.Tactics Arith Omega tactics low_equivalence nibridge_helper decision preservation List.\nRequire Import LibTactics InductionPrinciple Coq.Program.Equality Coq.Program.Basics.\nImport FunctionalExtensionality.\nSet Implicit Arguments.\n\nModule NIBridge (L : Lattice) (M: Memory L).\n  Module NIBridgeHelper := NIBridgeHelper L M.\n  Import NIBridgeHelper Preserve LowEq B Aug Imp TDefs M T MemProp LatProp Lang L.\n  \nTheorem ni_bridge_num:\n  forall n \u2113, ni_bridge n \u2113.\nProof.\n  intros.\n  induction n using strongind.\n  {\n    (* n = 0 *)\n    unfold ni_bridge.\n    intros.\n    revert \u03a31 \u03a32 \u03a31' \u03a33 \u03a33' H H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10.\n    revert pc pc1' pc2'' pc_end.\n    revert \u03c6 \u03a6.\n    revert c' c2 c2' H11 H12.\n    revert m1 m2 s1 s2'' s1' w1' h1 h2 w1 w2''.\n    revert t t' t2 g2''.\n    revert ev1 ev2.\n    revert n2.\n    induction c; intros; subst.\n    (* Skip *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step.\n        + invert_low_event.\n        + invert_low_event.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        invert_event_step.\n        + super_destruct; subst.\n          * invert_sem_step.            \n            invert_taint_eq.\n            invert_taint_eq_cmd.\n            exists EmptyEvent 0 \u03c6 \u03a6 s1 w1; exists \u03a32.\n            _apply skip_bridge_properties in *.\n            super_destruct; subst.            \n            splits*.\n            { unfolds.\n              splits*. }\n            { splits; eauto 2.\n              - unfolds.\n                intros.\n                splits.\n                + intros.\n                  eapply low_gc_trans_preserves_high; eauto 2.\n                  eapply H2; eauto.\n                + intros.\n                  assert (high \u2113 s2'' w1' loc).\n                  {\n                    eapply high_iff; reflexivity || eauto 2.\n                  }\n                  eapply H2; eauto.\n              - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H22).\n                rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_trans with (m' := s2'') (h' := w1').\n                + repeat invert_wf_aux; eauto 2.\n                + unfolds.\n                  splits*.\n                + unfold taint_eq in *; super_destruct'; subst.\n                  splits*.\n            }\n    }\n    \n    (* Stop *)\n    {\n      invert_bridge_step_with_steps 0.\n      - exfalso; eauto 2.\n      - unfold high_event_step in *.\n        super_destruct;\n          subst;\n          invert_event_step; exfalso; eauto using stop_takes_no_step.\n    }\n\n    (* Assign *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step.\n        + assert (wellformed_aux \u0393 \u03a31' \u27e8 Stop, pc1', m2, h2, t2 \u27e9 pc_end).\n          {\n            eapply preservation; eauto.\n          }\n          assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n          invert_taint_eq.\n          invert_taint_eq_cmd.\n          _apply assign_bridge_properties in *.\n          super_destruct; subst.\n          assert (wellformed_aux \u0393 \u03a33' \u27e8i ::= e, pc2'', s1', w2'', g2'' - 1\u27e9 pc_end) by eauto 2.\n          invert_sem_step.\n          rewrite_inj.\n          repeat invert_wf_aux.\n          assert ((i ::= e) <> Stop) by congruence.\n          assert ((i ::= e) <> TimeOut) by congruence.\n          do 4 specialize_gen.\n          do 2 invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          invert_bridge_step_with_steps 0.\n          * invert_low_event_step.\n            invert_event_step.\n            invert_sem_step.\n            rewrite_inj.\n            match goal with\n              [H: S (?X - 1) = ?X |- _] => clear H\n            end.\n           \n            destruct_prod_join_flowsto.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            invert_low_event.\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2 using taint_eq_mem_sym.\n            assert (exists v2, eval s1 e = Some v2 /\\ val_taint_eq (inverse \u03a6) (SecType \u03c4 (\u2113', \u03b9')) v1 v2) by eauto 2.\n            super_destruct; subst.\n            rename v2 into u.\n            destruct_prod_join_flowsto.\n            assert (val_low_eq \u2113 (SecType \u03c4 (\u21131, \u03b90)) v0 u \u03c6)\n              by (invert_state_low_eq; eauto 3).            \n            remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' (extend_memory i v0 m1) h2) (low_dec \u2113 \u0393 \u03a31' (extend_memory i v0 m1) h2) \u03c6).\n            remember_simple (filter_bijection\n                               (high \u2113 (extend_memory i u s1) w1)\n                               (high_dec \u2113 (extend_memory i u s1) w1) \u03a6).\n            super_destruct; subst.\n            rename \u03c8 into \u03a8.\n            rename \u03c80 into \u03c8.\n            exists (AssignEvent \u21131 i u).\n            exists 0.\n            exists \u03c8.\n            exists \u03a8.\n            exists (extend_memory i u s1).\n            exists w1.\n            exists \u03a32.\n            assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 v0]) h2\n                                 (s1 [i \u2192 u]) w1 \u0393 \u03a31' \u03a32).\n            {\n              eapply state_low_eq_extend_memory; intros; subst; eauto 2.\n              - intros; subst.\n                assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intros.\n                eapply eval_low_implies_low_reach; eauto 3.\n              - intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intros.\n                eapply eval_low_implies_low_reach; eauto.\n              - subst; eauto 2.\n              - subst; eauto 2.\n              - eapply wf_tenv_extend.\n                + eauto.\n                + eauto.\n                + intros; subst.\n                  eauto 2.\n                + intros; subst.\n                  eauto 2.\n            }\n            assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 v0]) h2).\n            {\n              invert_low_event.\n              destruct \u03b50 as [\u2113_e \u03b9_e].            \n              eapply wf_bijection_extend_mem1; eauto 2.\n              - intros; subst; eauto 2.\n              - intros; subst.\n                assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intros.\n                assert (wf_type bot (SecType (Array \u03c40 \u2113'0) (\u2113', \u03b9'))) by eauto 2.\n                invert_wf_type.\n                assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e = Var x)\n                  by eauto 2.\n                super_destruct; subst.\n                rewrite_inj.\n                do 2 invert_var_typing.\n                rewrite_inj.\n                assert (\u2113_e \u2291 \u21131) by eauto 2.\n                eauto 3.\n            }\n            splits~.\n            {\n              eapply bridge_low_num.\n              splits~.\n              eauto.\n            }\n            { invert_low_event.\n              constructor.\n              - splits*.\n              - intros _.\n                constructor.\n                repeat destruct_prod_join_flowsto.\n                repeat invert_state_low_eq.\n                invert_val_low_eq.\n                + exfalso; eauto.\n                + exfalso; eauto.\n                + eauto.\n                + assert (wf_type bot (SecType (Array \u03c40 \u2113_p) (\u21131, \u03b90))) by eauto 2.\n                  invert_wf_type.\n                  assert (low \u2113 \u0393 \u03a31' (m1 [i \u2192 ValLoc l1]) h2 l1).\n                  {\n                    eapply LowReachable.\n                    eauto 3.\n                  }\n                  eauto 3.\n            }\n            {\n              eapply TaintEqEventAssign.\n              - eauto.\n              - invert_val_taint_eq; eauto 3.\n                assert (left \u03a6 loc' = Some loc) by (destruct \u03a6; eauto).\n                assert (high \u2113 (s1 [i \u2192 ValLoc loc'])\n                             w1 loc') by eauto 3.\n                assert (left \u03a8 loc' = Some loc) by eauto 2.\n                eauto.\n            }\n            \n            assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop (s1 [i \u2192 u]) w1\n                             (s1' [i \u2192 v1]) w2'').\n            {\n              assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a33' \u03a33' (i ::= e) (i ::= e) s1' w1' s1' w2'').\n              {\n                eauto 3 using low_gc_trans_preserves_taint_eq.\n              }\n              unfold taint_eq in *; super_destruct'; subst.\n              splits~.\n              - eapply taint_eq_mem_extend; eauto 4.\n              - eapply taint_eq_reach_extend_mem; eauto 2.\n                + assert (taint_eq_reach (identity_bijection loc) s1' w1' s1' w2'')\n                    by eauto 2.\n                  rewrite <- (compose_id_right \u03a6).\n                  eapply taint_eq_reach_trans; eauto.\n                + rewrite <- (compose_id_right \u03a6).\n                  eapply taint_eq_heap_trans; eauto 2.\n                + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto.\n                + eauto 4.\n                + intros; subst; eauto 2.\n                + intros; subst; eauto 2.\n              - eapply taint_eq_heap_extend_mem.\n                + eapply taint_eq_heap_trans; eauto 2.\n                + eauto.\n                + intros; subst; eauto 2.\n                + intros; subst; eauto 2.\n                + intros; subst.\n                  assert (exists loc, u = ValLoc loc) by eauto 2.\n                  super_destruct; subst.\n                  exists loc.\n                  splits; eauto 3.\n                + intros; subst.\n                  assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                  super_destruct; subst.\n                  exists loc.\n                  splits; eauto 3.\n                + rewrite -> compose_id_right.\n                  eauto.\n                + rewrite -> compose_id_right.\n                  eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n                + rewrite -> compose_id_right.\n                  eauto.\n              - eapply taint_eq_heap_size_trans; eauto 2.\n              - repeat invert_wf_aux.\n                eapply taint_eq_heap_domain_eq_extend_mem with (\u03a6 := bijection.bijection_compose \u03a6 (identity_bijection loc)); eauto 2.\n                + eapply taint_eq_heap_domain_eq_trans; eauto 2.\n                + rewrite -> compose_id_right.\n                  eauto.\n                + rewrite -> compose_id_right.\n                  eapply low_gc_trans_preserves_wf_taint_bijection\n                  with (pc := pc_end); eauto.\n                + eapply taint_eq_mem_trans; eauto 2.\n                + eapply taint_eq_heap_trans; eauto 2.\n                + eapply taint_eq_reach_trans; eauto 2.\n                + rewrite -> compose_id_right.\n                  eauto.\n                + rewrite -> compose_id_right.\n                  eauto.\n                + rewrite -> compose_id_right.\n                  eauto.\n                + rewrite -> compose_id_right.\n                  eapply low_gc_trans_preserves_wf_taint_bijection\n                  with (pc := pc_end); eauto.\n                + intros; subst.\n                  assert (exists loc, u = ValLoc loc) by eauto 2.\n                  super_destruct; subst.\n                  exists loc.\n                  splits; eauto 3.\n                + intros; subst; eauto 3.\n                + intros; subst.\n                  assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                  super_destruct; subst.\n                  exists loc.\n                  splits; eauto 3.\n                + intros; subst; eauto 3.\n                + rewrite -> compose_id_right.\n                  eauto.\n              - eapply taint_eq_stenv_extend_mem; eauto 2.\n            }\n            splits.\n            {\n              eapply wf_bijection_extend_mem2; eauto 3.\n              - intros; subst.\n                eauto 2.\n              - intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                destruct \u03b50 as [\u2113_e \u03b9_e].\n                intros.\n                assert (wf_type bot (SecType (Array \u03c40 \u2113'0) (\u2113', \u03b9'))) by eauto 2.\n                invert_wf_type.\n                assert (exists x, memory_lookup s1 x = Some (ValLoc loc) /\\ e = Var x)\n                  by eauto 2.\n                super_destruct; subst.\n                rewrite_inj.\n                do 2 invert_var_typing.\n                rewrite_inj.\n                assert (\u2113_e \u2291 \u21131) by eauto 2.\n                eauto 3.\n            }\n            {\n              eapply wf_taint_bijection_extend_mem1; intros; subst; eauto 2.\n            }\n            {\n              invert_taint_eq.\n              eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans.\n                + eauto.\n                + eapply gc_trans_preserves_taint_eq_reach; eauto.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans.\n                + eapply gc_trans_preserves_taint_eq_reach; eauto 2.\n                + eauto.\n                + eauto.\n                + eauto.\n                + eapply low_gc_trans_preserves_taint_eq_heap; eauto 2.\n                + eapply low_gc_trans_preserves_taint_eq_heap_domain_eq with (pc := pc_end); eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              - eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n              - intros; subst; eauto 3.\n              - intros; subst; eauto 3.\n              - eauto 4.\n              - intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                eexists; splits; eauto 2.\n            }\n            { eauto. }\n          * invert_high_event_step.\n            invert_event_step.\n            rewrite_inj.\n            invert_low_event.\n            assert (~ \u21131 \u2291 \u2113) by eauto.\n            contradiction.\n        + invert_low_event.\n      - invert_high_event_step.\n        unfold is_stop_config, cmd_of in *; subst.\n        invert_event_step.\n        + assert (wellformed_aux \u0393 \u03a31' \u27e8 Stop, pc1', m2, h2, t2 \u27e9 pc_end).\n          {\n            eapply preservation; eauto.\n          }\n          assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n          invert_taint_eq.\n          invert_taint_eq_cmd.\n          _apply assign_bridge_properties in *.\n          super_destruct; subst.\n          assert (wellformed_aux \u0393 \u03a33' \u27e8i ::= e, pc2'', s1', w2'', g2'' - 1\u27e9 pc_end) by eauto 2.\n          invert_sem_step.\n          rewrite_inj.\n          repeat invert_wf_aux.\n          assert ((i ::= e) <> Stop) by congruence.\n          assert ((i ::= e) <> TimeOut) by congruence.\n          do 4 specialize_gen.\n          do 2 invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          invert_bridge_step_with_steps 0.\n          * invert_low_event_step.\n            invert_event_step.\n            rewrite_inj.\n            invert_low_event.\n            assert (~ \u21131 \u2291 \u2113) by eauto.\n            contradiction.\n          * invert_high_event_step.\n            invert_event_step.\n            rewrite_inj.\n            assert (~ \u21131 \u2291 \u2113) by eauto.\n            invert_sem_step.\n            rewrite_inj.\n            match goal with\n              [H: S (?X - 1) = ?X |- _] => clear H\n            end.\n           \n            destruct_prod_join_flowsto.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2 using taint_eq_mem_sym.\n            assert (exists v2, eval s1 e = Some v2 /\\ val_taint_eq (inverse \u03a6) (SecType \u03c4 (\u2113', \u03b9')) v1 v2) by eauto 2.\n            super_destruct; subst.\n            rename v2 into u.\n            destruct_prod_join_flowsto.\n            assert (val_low_eq \u2113 (SecType \u03c4 (\u21131, \u03b90)) v0 u \u03c6)\n              by (invert_state_low_eq; eauto 3).            \n            remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' (extend_memory i v0 m1) h2) (low_dec \u2113 \u0393 \u03a31' (extend_memory i v0 m1) h2) \u03c6).\n            remember_simple (filter_bijection\n                               (high \u2113 (extend_memory i u s1) w1)\n                               (high_dec \u2113 (extend_memory i u s1) w1) \u03a6).\n            super_destruct; subst.\n            rename \u03c8 into \u03a8.\n            rename \u03c80 into \u03c8.\n            exists (AssignEvent \u21131 i u).\n            exists 0.\n            exists \u03c8.\n            exists \u03a8.\n            exists (extend_memory i u s1).\n            exists w1.\n            exists \u03a32.\n            assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 v0]) h2\n                                 (s1 [i \u2192 u]) w1 \u0393 \u03a31' \u03a32).\n            {\n              eapply state_low_eq_extend_memory; eauto 2.\n              - intros; subst.\n                assert (exists loc, v0 = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intros.\n                assert (~ \u21131 \u2291 \u2113) by eauto.\n                contradiction.\n              - intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intros.\n                assert (~ \u21131 \u2291 \u2113) by eauto.\n                contradiction.\n              - intros; subst; eauto 2.\n              - intros; subst; eauto 2.\n              - eapply wf_tenv_extend.\n                + eauto.\n                + eauto.\n                + intros; subst.\n                  eauto 2.\n                + intros; subst.\n                  eauto 2.\n            }\n            assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 v0]) h2).\n            {\n              eapply wf_bijection_extend_mem1; eauto 2.\n              - intros; subst; eauto 2.\n              - intros; subst.\n                assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intro.\n                exfalso; eauto 3.\n            }\n            splits~.\n            {\n              eapply bridge_stop_num; eauto.\n              constructor.\n              - eapply EventSemStep; eauto.\n              - unfolds.\n                intro.\n                invert_low_event.\n                eauto.\n            }\n            { unfolds.\n              splits~.\n              - invert_high_event.\n                splits; intros; invert_low_event; exfalso; eauto.\n              - intros; invert_low_event; exfalso; eauto.\n            }\n            {\n              eapply TaintEqEventAssign.\n              - eauto.\n              - invert_val_taint_eq; eauto 3.\n                assert (left \u03a6 loc' = Some loc) by (destruct \u03a6; eauto).\n                assert (high \u2113 (s1 [i \u2192 ValLoc loc'])\n                              w1 loc') by eauto 3.\n                assert (left \u03a8 loc' = Some loc) by eauto 2.\n                eauto.\n            }\n            {\n              \n              assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop (s1 [i \u2192 u]) w1\n                               (s1' [i \u2192 v1]) w2'').\n              {\n                assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a33' \u03a33' (i ::= e) (i ::= e) s1' w1' s1' w2'').\n                {\n                  eauto 3 using low_gc_trans_preserves_taint_eq.\n                }\n                unfold taint_eq in *; super_destruct'; subst.\n                splits~.\n                - eapply taint_eq_mem_extend; eauto 4.\n                - eapply taint_eq_reach_extend_mem; eauto 2.\n                  + assert (taint_eq_reach (identity_bijection loc) s1' w1' s1' w2'')\n                      by eauto 2.\n                    rewrite <- (compose_id_right \u03a6).\n                    eapply taint_eq_reach_trans; eauto.\n                  + rewrite <- (compose_id_right \u03a6).\n                    eapply taint_eq_heap_trans; eauto 2.\n                  + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto.\n                  + eauto 4.\n                  + intros; subst; eauto 2.\n                  + intros; subst; eauto 2.\n                - eapply taint_eq_heap_extend_mem.\n                  + eapply taint_eq_heap_trans; eauto 2.\n                  + eauto.\n                  + intros; subst; eauto 2.\n                  + intros; subst; eauto 2.\n                  + intros; subst.\n                    assert (exists loc, u = ValLoc loc) by eauto 2.\n                    super_destruct; subst.\n                    exists loc.\n                    splits; eauto 3.\n                  + intros; subst.\n                    assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                    super_destruct; subst.\n                    exists loc.\n                    splits; eauto 3.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                  + rewrite -> compose_id_right.\n                    eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                - eapply taint_eq_heap_size_trans; eauto 2.\n                - repeat invert_wf_aux.\n                  eapply taint_eq_heap_domain_eq_extend_mem with (\u03a6 := bijection.bijection_compose \u03a6 (identity_bijection loc)); eauto 2.\n                  + eapply taint_eq_heap_domain_eq_trans; eauto 2.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                  + rewrite -> compose_id_right.\n                    eapply low_gc_trans_preserves_wf_taint_bijection\n                    with (pc := pc_end); eauto.\n                  + eapply taint_eq_mem_trans; eauto 2.\n                  + eapply taint_eq_heap_trans; eauto 2.\n                  + eapply taint_eq_reach_trans; eauto 2.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                  + rewrite -> compose_id_right.\n                    eapply low_gc_trans_preserves_wf_taint_bijection\n                    with (pc := pc_end); eauto.\n                  + intros; subst.\n                    assert (exists loc, u = ValLoc loc) by eauto 2.\n                    super_destruct; subst.\n                    exists loc.\n                    splits; eauto 3.\n                  + intros; subst; eauto 3.\n                  + intros; subst.\n                    assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                    super_destruct; subst.\n                    exists loc.\n                    splits; eauto 3.\n                  + intros; subst; eauto 3.\n                  + rewrite -> compose_id_right.\n                    eauto.\n                - eapply taint_eq_stenv_extend_mem; eauto 2.\n              }\n              splits.\n              {\n                eapply wf_bijection_extend_mem2; eauto 3.\n              - intros; subst; eauto 2.\n              - intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto 2.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                intro; exfalso; eauto 3.\n              }\n              {\n                eapply wf_taint_bijection_extend_mem1; intros; subst; eauto 2.\n              }\n              {\n                invert_taint_eq.\n                eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n                - rewrite <- (compose_id_right \u03a6).\n                  eapply taint_eq_reach_trans.\n                  + eauto.\n                  + eapply gc_trans_preserves_taint_eq_reach; eauto.\n                - rewrite <- (compose_id_right \u03a6).\n                  eapply taint_eq_heap_trans.\n                  + eapply gc_trans_preserves_taint_eq_reach; eauto 2.\n                  + eauto.\n                  + eauto.\n                  + eauto.\n                  + eapply low_gc_trans_preserves_taint_eq_heap; eauto 2.\n                  + eapply low_gc_trans_preserves_taint_eq_heap_domain_eq with (pc := pc_end); eauto 2.\n                - rewrite <- (compose_id_right \u03a6).\n                  eapply taint_eq_heap_domain_eq_trans; eauto 2.\n                - eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n                - intros; subst; eauto 3.\n                - intros; subst; eauto 3.\n                - eauto 4.\n                - intros; subst.\n                  assert (exists loc, v1 = ValLoc loc) by eauto 3.\n                  super_destruct'; subst.\n                  eexists; splits; eauto 2.\n              }\n              { eauto. }\n            }\n    }\n    (* If *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step; invert_low_event.\n      - invert_high_event_step.\n        exfalso.\n        eauto 2.\n    }\n    (* While *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step; invert_low_event.\n      - invert_high_event_step.\n        unfold is_stop_config, cmd_of in *; subst.\n        invert_event_step.\n        * super_destruct; try invert_ends_with_backat.\n          subst.\n          invert_sem_step.\n          exists EmptyEvent 0 \u03c6 \u03a6 s1 w1; exists \u03a32.\n          assert (eval s1 e = Some (ValNum 0)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            assert (\u21130 \u2291 \u2113) by eauto 2.\n            assert (exists u, onvals (left \u03c6) (ValNum 0) = Some u /\\ eval s1 e = Some u)\n              by eauto 2.\n            super_destruct'; subst.\n            unfold onvals in *.\n            injects.\n            eauto.\n          }\n          invert_taint_eq.\n          invert_taint_eq_cmd.\n          assert (eval s1' e = Some (ValNum 0)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            assert (exists v2,\n                       eval s1' e = Some v2 /\\ val_taint_eq \u03a6 (SecType Int (\u21130, \u2218)) (ValNum 0) v2) by eauto 2.\n            super_destruct'; subst.\n            invert_val_taint_eq.\n            eauto.\n          }\n          splits; eauto 2.\n          {\n            _apply while_bridge_properties in *.\n            super_destruct; subst.\n            - eauto.\n            - congruence.\n          }\n          {\n            _apply while_bridge_properties in *.\n            super_destruct; subst.\n            - eauto.\n            - congruence.\n          }\n          {\n            splits*.\n          }\n          {\n            _apply while_bridge_properties in *.\n            super_destruct; subst.\n            - eauto.\n            - congruence.\n          }\n          splits; eauto 2.\n          {\n            _apply while_bridge_properties in *.\n            super_destruct; subst.\n            - eapply low_gc_trans_preserves_wf_taint_bijection; eauto.\n            - congruence.\n          }\n          {\n            _apply while_bridge_properties in *.\n            super_destruct; subst.\n            - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n              unfold taint_eq in *; super_destruct.\n              splits.\n              + eauto.\n              + eauto.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto.\n                * repeat invert_wf_aux; eauto.\n              + eapply taint_eq_heap_size_trans; eauto.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_stenv_trans; eauto. \n            - congruence.\n          }\n    }\n    (* Sequential composition *)\n    {\n      assert (H8' := H8).\n      match goal with\n        [H: context[bridge_step_num] |- _] => assert (H' := H); eapply about_seq_bridge_step in H; eauto 2\n      end.\n      match goal with\n        [H: (exists _, _ ) \\/ (exists _, _ ) |- _] =>\n        destruct H; super_destruct'; try omega\n      end.\n      subst.\n      assert (c1 <> Stop).\n      {\n        intro; subst.\n        invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        match goal with\n          [H: wt_aux _ _ Stop _ |- _] =>\n          inverts H\n        end.\n      }\n      assert (c2 <> Stop).\n      {\n        intro; subst.\n        invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        match goal with\n          [H: wt_aux _ _ Stop _ |- _] =>\n          inverts H\n        end.\n      }\n      invert_taint_eq.\n      invert_taint_eq_cmd.\n      assert (exists pc'',\n                 wellformed_aux \u0393 \u03a31 \u27e8 c1, pc, m1, h1, t \u27e9 pc'') by eauto 2.\n      assert (exists pc'',\n                 wellformed_aux \u0393 \u03a32 \u27e8 c1, pc, s1, w1, t \u27e9 pc'') by eauto 2.\n      assert (exists pc'',\n                 wellformed_aux \u0393 \u03a33 \u27e8 c1'0, pc, s1', w1', t' \u27e9 pc'') by eauto 2.\n      super_destruct'; subst.\n      assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1'0 s1 w1 s1' w1').\n      {\n        unfolds.\n        splits*.\n      }\n      assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n      match goal with\n        [H: context[bridge_step_num] |- _] =>\n        eapply about_seq_bridge_step in H; eauto 2\n      end.\n      \n      super_destruct; subst.\n      - assert (c1 <> TimeOut).\n        {\n          intro; subst.\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          match goal with\n            [H: wt_aux _ _ (TimeOut ;; _) _ |- _] =>\n            inverts H\n          end.\n          invert_wt_timeout.\n        }\n        assert (pc''1 = pc''0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eapply deterministic_typing; eauto 2.\n        }\n        subst.\n        assert (c1' <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (c1'0 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n        assert (c1'0 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (c1'1 <> TimeOut).\n        {\n          intro; subst.\n          assert (TimeOut <> Stop) by congruence.\n          specialize_gen.\n          subst.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (pc'' = pc''0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H27 H50).\n          eauto 2.\n        }\n        subst.\n        remember_simple (IHc1 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H35 H38 _ _ _ _ _ _ _ _ _ _ _ H H0 H1 H2 H18 H25 H26 H6 H7 H28 H9 H10).\n        super_destruct'; rewrite_inj; subst.\n        exists ev1' n1' \u03c8 \u03a8 s2' w2'; exists \u03a32'.\n        splits~.\n        + destruct (eq_cmd_dec c1' Stop).\n          * subst.\n            match goal with\n              [H: _ = _ -> _ |- _] =>\n              specialize (H eq_refl); subst\n            end.\n            eapply bridge_step_seq_low_event_in_left_stop; eauto 2.\n          * match goal with\n              [H1: ?P -> _, H2: ?P |- _] =>\n              specialize (H1 H2); subst\n            end.\n            destruct (eq_cmd_dec c1' TimeOut).\n            {\n              subst.\n              assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2\u27e9 pc_end).\n              {\n                eauto 2.\n              }\n              invert_wf_aux.\n              repeat specialize_gen.\n              invert_wt_cmd.\n              invert_wt_timeout.\n            }\n            {\n              eapply bridge_step_seq_low_event_in_left_nonstop; eauto 2.\n            }\n        + splits; eauto 2.\n          invert_taint_eq.\n          unfolds.\n          splits; eauto 2.\n          destruct (eq_cmd_dec c1' Stop).\n          * subst.\n            repeat specialize_gen.\n            subst.\n            assert (c1'1 = Stop).\n            {\n              invert_taint_eq_cmd; eauto 2.\n            }\n            subst.\n            repeat specialize_gen.\n            subst.\n            eauto 2.\n          * assert (c1'1 <> Stop).\n            {\n              intro; subst.\n              invert_taint_eq_cmd.\n              eauto 2.\n            }\n            repeat specialize_gen.\n            subst.\n            eauto 2.\n      - assert (pc''2 = pc'') by (eapply wt_aux_soundness_bridge; eauto 2).\n        subst.\n        assert (c1 <> TimeOut).\n        {\n          intro; subst.\n          inverts H3.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (pc''1 = pc''0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eauto 2.\n        }\n        subst.\n        assert (c1'0 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd.\n          invert_wt_stop.\n        }\n        assert (c1'0 <> TIMEOUT).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (c1'0 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc'' = pc''0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H27 H50).\n          eauto 2.\n        }\n        subst.\n        assert (c1' <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (Stop <> TimeOut) by congruence.\n        remember_simple (IHc1 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H39 H40 _ _ _ _ _ _ _ _ _ _ _ H H0 H1 H2 H18 H25 H26 H6 H7 H28 H9 H33).\n        super_destruct'; rewrite_inj; subst.\n        assert (low_event \u2113 ev1') by eauto 2.\n        assert (low_event \u2113 ev').\n        {\n          eapply taint_eq_event_low_implies_low.\n          - eapply taint_eq_events_sym.\n            eauto.\n          - eauto.\n        }\n        contradiction.\n    }\n    (* At *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step; invert_low_event.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        invert_event_step.\n        + invert_sem_step.\n    }\n    (* Back at *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      assert (\u03a33 = \u03a33' /\\\n              (exists t'', ev2 = RestoreEvent l t'') /\\\n              taint_eq_mem (identity_bijection loc) \u0393 s1' s2'' /\\\n              taint_eq_heap \u2113 (identity_bijection loc) \u03a33 \u03a33' s1' w1' s2'' w2'' /\\\n              taint_eq_reach (identity_bijection loc) s1' w1' s2'' w2'' /\\\n              taint_eq_heap_size \u2113 w1' w2'' /\\\n              taint_eq_heap_domain_eq \u2113 (identity_bijection loc) s1' s2'' w1' w2'' /\\\n              wf_taint_bijection \u2113 (inverse \u03a6) s2'' w2'').\n      {\n        remember_simple (backat_bridge_properties H5 H10).\n        super_destruct; subst.\n        - congruence.\n        - splits*.\n          + repeat invert_wf_aux.\n            eapply taint_eq_mem_refl; eauto.\n          + remember_simple (low_gc_or_inc_many_preserves_taint_eq H5 H7 H8).\n            unfold taint_eq in *; super_destruct'; subst.\n            eauto.\n          + remember_simple (low_gc_or_inc_many_preserves_taint_eq H5 H7 H8).\n            unfold taint_eq in *; super_destruct'; subst.\n            eauto.\n          + remember_simple (low_gc_or_inc_many_preserves_taint_eq H5 H7 H8).\n            unfold taint_eq in *; super_destruct'; subst.\n            eauto.\n          + remember_simple (low_gc_or_inc_many_preserves_taint_eq H5 H7 H8).\n            unfold taint_eq in *; super_destruct'; subst.\n            eauto.\n      }\n      super_destruct'; subst.\n      subst.\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step.\n        + invert_low_event.\n        + invert_sem_step.\n          * omega.\n          * invert_low_event.\n            do 7 eexists.\n            splits.\n            { constructor.\n              splits*. }\n            { eauto. }\n            { remember_simple (backat_bridge_properties H5 H10).\n              super_destruct; congruence. }\n            { eapply H6; eauto 2. }\n            { splits*. }\n            { eauto. }\n            { eauto 2. }\n            splits.\n            { eauto. }\n            { eauto. }\n            { eauto 2. }\n            { unfolds.\n              splits.\n              - remember_simple (backat_bridge_properties H5 H10).\n                super_destruct; try congruence.\n                subst.\n                eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_mem_trans; eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eauto 2 using taint_eq_reach_trans.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans.\n                + eauto.\n                + eauto.\n                + repeat invert_wf_aux.\n                  eauto.\n                + eauto.\n                + eauto.\n                + eauto.\n              - eauto 2 using taint_eq_heap_size_trans.\n              - rewrite <- (compose_id_right \u03a6).\n                eauto 2 using taint_eq_heap_domain_eq_trans.\n              - eauto 2 using taint_eq_stenv_trans.\n            }\n          * omega.\n        + invert_sem_step.\n          * omega.\n          * omega.\n          * congruence.\n        + invert_low_event.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        invert_event_step.\n        + invert_sem_step.\n          omega.\n        + invert_sem_step.\n          assert (~ pc1' \u2291 \u2113) by eauto.\n          invert_wf_aux.\n          do 2 specialize_gen.\n          invert_wt_cmd.\n          exfalso; eauto 3.\n        + invert_sem_step.\n          assert (~ pc1' \u2291 \u2113) by eauto.\n          invert_wf_aux.\n          do 2 specialize_gen.\n          invert_wt_cmd.\n          exfalso; eauto 3.\n    }\n  \n    (* New *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8c2, pc1', m2, h2, t2\u27e9\n                               pc_end) by eauto 2 using preservation_event_step.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end).\n        {\n          eauto 2 using preservation_bridge_step.\n        }\n        invert_event_step.\n        + super_destruct; subst; try invert_ends_with_backat.\n          invert_sem_step.\n          rewrite_inj.\n          _apply same_extend_implies_same_loc in *; subst.\n          invert_low_event.\n          assert (wf_type bot (SecType (Array \u03c40 l) (\u21130, \u03b9))).\n          {\n            repeat invert_wf_aux.\n            eauto.\n          }\n          _apply new_bridge_properties in *.\n          super_destruct'; subst.\n          invert_bridge_step; try solve[invert_high_event_step; invert_event_step; rewrite_inj; assert (~ \u21131 \u2291 \u2113) by eauto; contradiction].\n          invert_low_event_step.\n          invert_event_step.\n          rewrite_inj.\n          invert_sem_step.\n          match goal with\n            [H: S (_ - 1) = _ |- _] =>\n            clear H\n          end.\n          _apply same_extend_implies_same_loc in *; subst.\n          rewrite_inj.\n          inverts H4.\n          do 2 specialize_gen.\n          invert_wt_cmd.\n          rewrite_inj.\n          assert (exists v2,\n                     eval s1 e = Some v2 /\\ val_taint_eq \u03a6 (SecType Int (\u2113_size, \u2218)) v2 (ValNum n0)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            repeat destruct_join_flowsto.\n            assert (exists v2,\n                       eval s1 e = Some v2 /\\ val_taint_eq (inverse \u03a6) (SecType Int (\u2113_size, \u2218))  (ValNum n0) v2).\n            {\n              assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by (eapply taint_eq_mem_sym; eauto 2).\n              eapply eval_taint_eq_possibilistic with (m1 := s1') (m2 := s1); eauto 2.\n            }\n            super_destruct'; subst.\n            eauto 4.\n          }\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          assert (n = n0).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            repeat destruct_join_flowsto.\n            assert (val_low_eq \u2113 (SecType Int (\u2113_size, \u2218)) (ValNum n) (ValNum n0) \u03c6).\n            {\n              invert_state_low_eq.\n              eauto 2 using eval_low_eq.\n            }\n            rewrite_inj.\n            invert_val_low_eq.\n            - exfalso; eauto.\n            - reflexivity.\n          }\n          subst.\n          assert (size l w1 + n0 <= maxsize l w1).\n          {\n            destruct (flowsto_dec l \u2113).\n            - assert (size l h1 = size l w1).\n              {\n                invert_state_low_eq.\n                eauto.\n              }\n              subst.\n              match goal with\n                [H: size _ _ = size _ _ |- _] =>\n                rewrite <- H\n              end.\n              erewrite -> constant_maxsize; eauto.\n            - assert (l <> pc_end).\n              {\n                intro; subst.\n                contradiction.\n              }\n              assert (size l w1' = size l h')\n                by eauto using gc_trans_preserves_heap_size_neq_pc.\n              assert (size l w1 = size l w1') by eauto 2.\n              rewrite <- (constant_maxsize h' w1 l).\n              congruence.\n          }\n          \n          match goal with\n            [H: size _ _ + _ <= maxsize _ _ |- _] =>\n            remember_simple (fresh_location w1 l n0 v H)\n          end.\n          super_destruct; subst.\n          \n          assert (left \u03c6 l1 = None).\n          {\n            destruct (left \u03c6 l1) eqn:H_l1; try reflexivity.\n            assert (exists \u2113 \u03bc, heap_lookup l1 h1 = Some (\u2113, \u03bc)).\n            {\n              repeat invert_wf_aux.\n              eapply bijection_implies_in_heap; eauto 2.\n            }\n            super_destruct'; subst.\n            congruence.\n          }\n          assert (right \u03c6 loc = None).\n          {\n            destruct (right \u03c6 loc) eqn:H_loc; try reflexivity.\n            assert (exists \u2113 \u03bc, heap_lookup loc w1 = Some (\u2113, \u03bc)).\n            {\n              repeat invert_wf_aux.\n              eapply bijection_implies_in_heap; destruct \u03c6; eauto 2.\n            }\n            super_destruct'; subst.\n            congruence.\n          }            \n          \n          remember_simple (filter_bijection\n                             (low \u2113 \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                                  (m1 [i \u2192 ValLoc l1])\n                                  (extend_heap v l1 l n0 h1 H9 H21))\n                             (low_dec \u2113 \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                                      (m1 [i \u2192 ValLoc l1])\n                                      (extend_heap v l1 l n0 h1 H9 H21)) \u03c6).\n          super_destruct; subst.\n          assert (left \u03c8 l1 = None) by eauto 2.\n          assert (right \u03c8 loc = None).\n          {\n            destruct (right \u03c8 loc) eqn:H_loc; try reflexivity.\n            rename l0 into loc'.\n            assert (left \u03c8 loc' = Some loc) by (destruct \u03c8; eauto 2).\n            assert (low \u2113 \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                        (m1 [i \u2192 ValLoc l1])\n                        (extend_heap v l1 l n0 h1 H9 H21) loc').\n            {\n              eapply filtered_bijection_some_implies_predicate; eauto 2.\n            }\n            destruct_low.\n            - destruct (decide (loc0 = l1)); subst.\n              + congruence.\n              + assert (low_reach \u2113_adv \u0393 \u03a31 m1 h1 loc0).\n                {\n                  inverts H3.\n                  assert (NewArr i l e e0 <> Stop) as H' by congruence.\n                  assert (NewArr i l e e0 <> TimeOut) as H'' by congruence.\n                  do 2 specialize_gen.\n                  clear H' H''.\n                  invert_wt_cmd.\n                  rewrite_inj.\n                  destruct \u03c4 as [\u03c4 [\u2113 \u03b9]].\n                  eapply low_reach_extend_implies_low_reach_if\n                  with (\u03c3 := \u03c4) (v := v) (\u2113 := \u2113).\n                  - intros; subst.\n                    assert (exists loc, v = ValLoc loc) by eauto 2.\n                    super_destruct; subst.\n                    exists loc1.\n                    splits~.\n                    intros.\n                    assert (exists x, memory_lookup m1 x = Some (ValLoc loc1) /\\ e0 = Var x) by eauto 2.\n                    super_destruct; subst.\n                    assert (\u03b9 = \u2218).\n                    {\n                      assert_wf_type.\n                      do 2 invert_wf_type.\n                      reflexivity.\n                    }\n                    subst.\n                    invert_var_typing.\n                    eauto 2.\n                  - intros; subst.\n                    eauto 2.\n                  - eauto.\n                  - eauto.\n                }\n                assert (low_reach \u2113_adv \u0393 \u03a32 s1 w1 loc).\n                {\n                  invert_state_low_eq.\n                  match goal with\n                    [H: context[low_reach_NI] |- _] =>\n                    solve[eapply H; eauto]\n                  end.\n                }\n                repeat invert_wf_aux.\n                assert (exists \u2113 \u03bc, heap_lookup loc w1 = Some (\u2113, \u03bc)) by eauto 3.\n                super_destruct.\n                congruence.\n            - destruct (decide (loc0 = l1)); subst.\n              + congruence.\n              + rewrite -> heap_lookup_extend_neq in * by solve[eauto 2].\n                assert (low \u2113_adv \u0393 \u03a31 m1 h1 loc0) by eauto 2.\n                assert (exists \u03bd, heap_lookup loc w1 = Some (\u2113, \u03bd)).\n                {\n                  invert_state_low_eq.\n                  match goal with\n                    [H: context[low_heap_domain_eq] |- _] =>\n                    solve[eapply H; eauto]\n                  end.\n                }\n                super_destruct; subst.\n                congruence.\n          }\n\n          exists (NewEvent \u2113_x i loc).\n          exists 0.\n          match goal with\n            [H1: left \u03c8 ?loc1 = None,\n                 H2: right \u03c8 ?loc2 = None |- _] =>\n            exists (extend_bijection \u03c8 loc1 loc2 H1 H2)\n          end.\n\n          assert (exists v2, eval s1 e0 = Some v2 /\\ val_taint_eq \u03a6 \u03c40 v2 v1).\n          {\n            destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n            repeat invert_wf_aux.\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            assert (exists v2,\n                       eval s1 e0 = Some v2 /\\\n                       val_taint_eq (inverse \u03a6) (SecType \u03c3 (\u2113', \u03b9')) v1 v2) by eauto 2.\n            super_destruct'; subst.\n            eauto 4.\n          }\n          super_destruct'; subst.\n          \n          remember_simple (filter_bijection\n                             (high \u2113 (s1 [i \u2192 ValLoc loc])\n                                    (extend_heap v2 loc l n0 w1 H30 H28))\n                             (high_dec \u2113 (s1 [i \u2192 ValLoc loc])\n                                        (extend_heap v2 loc l n0 w1 H30 H28)) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          assert (left \u03a8 loc = None).\n          {\n            assert (left \u03a6 loc = None).\n            {\n              destruct (left \u03a6 loc) eqn:H_loc; try reflexivity.\n              rename l0 into loc'.\n              assert (high \u2113 s1 w1 loc).\n              {\n                eapply H1; eauto.\n              }\n              assert (exists \u2113 \u03bc, heap_lookup loc w1 = Some (\u2113, \u03bc)).\n              {\n                destruct_high; eauto 3.\n              }\n              super_destruct'; subst.\n              congruence.\n            }\n            eapply filtered_bijection_is_subset_transpose_left.\n            - eapply high_dec.\n            - eauto.\n            - eauto.\n          }\n          assert (right \u03a8 l2 = None).\n          {\n            destruct (right \u03a8 l2) eqn:H_loc; try reflexivity.\n            rename l0 into l2'.\n            assert (left \u03a8 l2' = Some l2) by (destruct \u03a8; eauto 2).\n            assert (high \u2113 (s1 [i \u2192 ValLoc loc])\n                          (extend_heap v2 loc l n0 w1 H30 H28) l2').\n            {\n              eapply filtered_bijection_some_implies_predicate.\n              - eapply high_dec; eauto.\n              - eauto.\n              - eauto.\n            }\n            destruct (decide (loc = l2')); subst.\n            + congruence.\n            + assert (high \u2113 s1 w1 l2').\n              {\n                destruct_high.\n                - eapply HighReachable.\n                  eapply reach_extend_implies_reach_if with (v := v2).\n                  + intros; subst.\n                    eauto 3.\n                  + eauto.\n                  + eauto.\n                - rewrite -> heap_lookup_extend_neq in * by solve[eauto 2].\n                  eauto 3.\n              }\n              assert (left \u03a6 l2' = Some l2).\n              {\n                eapply filtered_bijection_is_subset.\n                - eapply high_dec.\n                - eauto.\n                - eauto.\n              }\n              assert (high \u2113 s1' w1' l2).\n              {\n                rewrite <- high_iff; eauto 2.\n              }\n              assert (high \u2113 s1' h' l2).\n              {\n                eapply low_gc_trans_preserves_high; eauto 2.\n              }\n              assert (wellformed_aux \u0393 \u03a33 \u27e8NewArr i l e e0, pc_end, s1', h', g2'' - 1 \u27e9 pc_end) by eauto 2.\n              repeat invert_wf_aux.\n              assert (exists \u2113 \u03bc, heap_lookup l2 h' = Some (\u2113, \u03bc)).\n              {\n                destruct_high; eauto 3.\n              }\n              super_destruct'.\n              congruence.\n          }\n          match goal with\n            [H1: left \u03a8 ?loc1 = None,\n                 H2: right \u03a8 ?loc2 = None |- _] =>\n            exists (extend_bijection \u03a8 loc1 loc2 H1 H2)\n          end.\n          exists (s1 [i \u2192 ValLoc loc]).\n          exists (extend_heap v2 loc l n0 w1 H30 H28).\n          exists (extend_stenv loc \u03c40 \u03a32).\n          \n          assert (state_low_eq \u2113 (extend_bijection \u03c8 l1 loc H46 H48)\n                               (m1 [i \u2192 ValLoc l1]) \n                               (extend_heap v l1 l n0 h1 H9 H21)\n                               (s1 [i \u2192 ValLoc loc])\n                               (extend_heap v2 loc l n0 w1 H30 H28) \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                               (extend_stenv loc \u03c40 \u03a32)).\n          {\n            destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            repeat invert_wt_cmd.\n            rewrite_inj.\n            eapply state_low_eq_extend_EVERYTHING; try solve[intros; subst; eauto 3].\n            - intros; subst.\n              assert (exists loc, v = ValLoc loc) by eauto 2.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto 2.\n              super_destruct; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto 3.\n              super_destruct; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - intros.\n              assert (val_low_eq \u2113 (SecType \u03c3 (\u2113', \u03b9')) v v2 \u03c6).\n              {\n                invert_state_low_eq.\n                eauto 3 using eval_low_eq.\n              }\n              invert_val_low_eq; contradiction || eauto.\n          }\n\n          assert (wf_bijection \u2113 (extend_bijection \u03c8 l1 loc H46 H48) \u0393\n                               (extend_stenv l1 \u03c40 \u03a31)\n                               (m1 [i \u2192 ValLoc l1])\n                               (extend_heap v l1 l n0 h1 H9 H21)).\n          {\n            destruct \u03c40 as [\u03c40 [\u2113' \u03b9']].\n            eapply wf_bijection_extend_mem_and_heap1; eauto 3.\n            - repeat invert_wf_aux; eauto.\n            - intros; subst.\n              repeat invert_wf_aux.\n              assert (exists loc, v = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              splits~.\n              intros.\n              assert (NewArr i l e e0 <> Stop) by congruence.\n              assert (NewArr i l e e0 <> TimeOut) by congruence.\n              do 2 specialize_gen.\n              invert_wt_cmd.\n              rewrite_inj.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto 2.\n              super_destruct; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              eauto 2.\n            - intros; subst.\n              repeat invert_wf_aux.\n              eauto 3.\n          }\n\n          assert (wellformed_aux \u0393 \u03a33 \u27e8NewArr i l e e0, pc_end, s1', h', g2'' - 1\u27e9 pc_end) by eauto 2.\n          splits~.\n          { eapply bridge_low_num.\n            splits*.\n          }\n          { unfolds.\n            splits*.\n          }\n          \n          assert (wf_taint_bijection \u2113 (extend_bijection \u03a8 loc l2 H52 H53)\n                                     (s1 [i \u2192 ValLoc loc]) (extend_heap v2 loc l n0 w1 H30 H28)).\n          {\n            eapply wf_taint_bijection_extend_mem_and_heap1; eauto 2.\n            intros; subst; eauto 2.\n          }\n          splits.\n          {\n            repeat invert_wf_aux.\n            assert (NewArr i l e e0 <> Stop) as H' by congruence.\n            repeat match goal with\n                     [H: _ <> _ -> _ |- _] =>\n                     specialize (H H')\n                   end.\n            clear H'.\n            repeat invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03c40 as [\u03c4 [\u2113' \u03b9]].\n            eapply wf_bijection_extend_mem_and_heap2; eauto 3.\n            - intros; subst; eauto 3.\n            - intros; subst; eauto 3.\n            - intros; subst.\n              assert (exists loc, v = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              invert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              invert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - repeat invert_state_low_eq.\n              assert (val_low_eq \u2113 (SecType \u03c4 (\u2113', \u03b9)) v v2 \u03c6) by eauto 3.\n              invert_val_low_eq; contradiction || eauto 3.\n          }\n          {\n            eauto 2.\n          }\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n            unfold taint_eq in *; super_destruct'; subst.\n            destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n            repeat invert_wf_aux.\n            eapply wf_taint_bijection_extend_mem_and_heap2 with (\u03a6 := \u03a6) (m1 := s1) (h1 := w1) (v1 := v2); intros; subst; eauto 3.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans; eauto.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto.\n            - eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto.\n            - subst; eauto 2.\n            - subst; eauto 2.\n            - subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 3.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - subst.\n              assert (exists loc, v1 = ValLoc loc) by eauto 3.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n          }\n          {\n            unfolds.\n            splits.\n            - eauto 2.\n            - eapply taint_eq_mem_extend_mem_and_bijection; eauto.\n            - destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n              unfold taint_eq in *; super_destruct'; subst.\n              eapply taint_eq_reach_extend_mem_and_heap;\n                (intros; subst; eauto 3) || (try solve [repeat invert_wf_aux; eauto 2]).\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n                repeat invert_wf_aux; eauto 2.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + intros; subst.\n                repeat invert_wf_aux.\n                assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + subst; eauto 2.\n              + subst.\n                repeat invert_wf_aux; eauto 3.                \n            - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n              unfold taint_eq in *; super_destruct'; subst.\n              eapply taint_eq_heap_extend_mem_and_heap with (\u03a6 := \u03a6).\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans.\n                * eauto.\n                * eauto.\n                * repeat invert_wf_aux; eauto 2.\n                * eauto.\n                * eauto.\n                * eauto.\n              + eauto.\n              + intros; subst; eauto 2.\n              + intros; subst; repeat invert_wf_aux; eauto 2.\n              + eauto.\n            - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n              unfold taint_eq in *; super_destruct'; subst.\n              unfolds.\n              intros.\n              destruct (T_dec l0 l); subst.\n              + repeat rewrite -> size_extend_heap_eq_level by solve[eauto 2].\n                assert (size l w1' = size l h') by eauto 2.\n                assert (size l w1 = size l w1') by eauto 2.\n                omega.\n              + repeat rewrite -> size_extend_heap_neq_level by solve[eauto 2].\n                assert (size l0 w1' = size l0 h') by eauto 2.\n                assert (size l0 w1 = size l0 w1') by eauto 2.\n                omega.\n            - destruct \u03c40 as [\u03c3 \u03b5].\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H26).\n              unfold taint_eq in *; super_destruct'; subst.\n              repeat invert_wf_aux.\n              eapply taint_eq_heap_domain_eq_extend_mem_and_heap with (\u03a6 := \u03a6); eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto.\n              + intros; subst; eauto 3.\n              + intros; subst; eauto 3.\n            - unfolds.\n              intros.\n              destruct (decide (loc = loc1)); subst.\n              + _rewrite -> left_extend_bijection_eq in *.\n                rewrite_inj.\n                repeat rewrite -> extend_stenv_lookup_eq.\n                splits*.\n              + _rewrite -> left_extend_bijection_neq in * by solve[eauto 2].\n                assert (l2 <> loc2).\n                {\n                  intro; subst.\n                  assert (right \u03a8 loc2 = Some loc1) by (destruct \u03a8; eauto 2).\n                  congruence.\n                }\n                repeat rewrite -> extend_stenv_lookup_neq by solve[eauto 2].\n                assert (left \u03a6 loc1 = Some loc2).\n                {\n                  eapply filtered_bijection_is_subset.\n                  - eapply high_dec.\n                  - eauto 2.\n                  - eauto 2.\n                }\n                eapply H18; eauto 2.\n          }\n        + invert_low_event.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8Stop, pc1', m2, h2, t2\u27e9\n                               pc_end) by eauto 2 using preservation_event_step.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end).\n        {\n          eauto 2 using preservation_bridge_step.\n        }\n        invert_event_step.\n        invert_sem_step.\n        assert (~ \u21130 \u2291 \u2113) by eauto.\n        rewrite_inj.\n        _apply same_extend_implies_same_loc in *; subst.\n        assert (wf_type bot (SecType (Array \u03c40 l) (\u21130, \u03b9))).\n        {\n          repeat invert_wf_aux.\n          eauto.\n        }\n        _apply new_bridge_properties in *.\n        super_destruct'; subst.\n        invert_bridge_step; try solve[invert_low_event_step; invert_event_step; invert_low_event; rewrite_inj; contradiction].\n        invert_high_event_step.\n        invert_event_step.\n        rewrite_inj.\n        invert_sem_step.\n        match goal with\n          [H: S (_ - 1) = _ |- _] =>\n          clear H\n        end.\n        _apply same_extend_implies_same_loc in *; subst.\n        rewrite_inj.\n        inverts H4.\n        do 2 specialize_gen.\n        invert_wt_cmd.\n        rewrite_inj.\n        assert (exists v2,\n                   eval s1 e = Some v2 /\\ val_taint_eq \u03a6 (SecType Int (\u2113_size, \u2218)) v2 (ValNum n0)).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          repeat destruct_join_flowsto.\n          assert (exists v2,\n                       eval s1 e = Some v2 /\\ val_taint_eq (inverse \u03a6) (SecType Int (\u2113_size, \u2218))  (ValNum n0) v2).\n            {\n              assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by (eapply taint_eq_mem_sym; eauto 2).\n              eapply eval_taint_eq_possibilistic with (m1 := s1') (m2 := s1); eauto 2.\n            }\n            super_destruct'; subst.\n            eauto 4.\n          }\n          super_destruct'; subst.\n        invert_val_taint_eq.\n        assert (wf_type bot (SecType (Array \u03c40 l) (\u2113_x, \u2218))) by eauto.\n        invert_wf_type.\n        assert (~ l \u2291 \u2113) by eauto.\n        assert (size l w1' = size l h').\n        {\n          eapply gc_trans_preserves_heap_size_neq_pc.\n          - eauto 2.\n          - intro; subst.\n            eauto 3.\n        }\n        assert (size l w1 = size l w1').\n        {\n          eapply H16; eauto 3.\n        }\n        let H' := fresh in\n        assert (size l w1 + n0 <= maxsize l w1) as H' by\n              (rewrite <- (constant_maxsize h' w1 l); omega);\n          remember_simple (fresh_location w1 l n0 v H').\n        super_destruct; subst.        \n        \n        assert (left \u03c6 l1 = None).\n        {\n          destruct (left \u03c6 l1) eqn:H_l1; try reflexivity.\n          assert (exists \u2113 \u03bc, heap_lookup l1 h1 = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            eapply bijection_implies_in_heap; eauto 2.\n          }\n          super_destruct'; subst.\n          congruence.\n        }\n        assert (right \u03c6 loc = None).\n        {\n          destruct (right \u03c6 loc) eqn:H_loc; try reflexivity.\n          assert (exists \u2113 \u03bc, heap_lookup loc w1 = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            eapply bijection_implies_in_heap; destruct \u03c6; eauto 2.\n          }\n          super_destruct'; subst.\n          congruence.\n        }            \n        \n        remember_simple (filter_bijection\n                           (low \u2113 \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                                (m1 [i \u2192 ValLoc l1])\n                                (extend_heap v l1 l n h1 H9 H21))\n                           (low_dec \u2113 \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                                    (m1 [i \u2192 ValLoc l1])\n                                    (extend_heap v l1 l n h1 H9 H21)) \u03c6).\n          super_destruct; subst.\n          exists (NewEvent \u2113_x i loc).\n          exists 0.\n          exists \u03c8.\n\n          assert (exists v2, eval s1 e0 = Some v2 /\\ val_taint_eq \u03a6 \u03c40 v2 v1).\n          {\n            destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n            repeat invert_wf_aux.\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            assert (exists v2,\n                       eval s1 e0 = Some v2 /\\\n                       val_taint_eq (inverse \u03a6) (SecType \u03c3 (\u2113', \u03b9')) v1 v2) by eauto 2.\n            super_destruct'; subst.\n            eauto 4.\n          }\n          super_destruct'; subst.\n          \n          remember_simple (filter_bijection\n                             (high \u2113 (s1 [i \u2192 ValLoc loc])\n                                    (extend_heap v2 loc l n0 w1 H50 H33))\n                             (high_dec \u2113 (s1 [i \u2192 ValLoc loc])\n                                        (extend_heap v2 loc l n0 w1 H50 H33)) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          assert (left \u03a8 loc = None).\n          {\n            assert (left \u03a6 loc = None).\n            {\n              destruct (left \u03a6 loc) eqn:H_loc; try reflexivity.\n              rename l0 into loc'.\n              assert (high \u2113 s1 w1 loc).\n              {\n                eapply H1; eauto.\n              }\n              assert (exists \u2113 \u03bc, heap_lookup loc w1 = Some (\u2113, \u03bc)).\n              {\n                destruct_high; eauto 3.\n              }\n              super_destruct'; subst.\n              congruence.\n            }\n            eapply filtered_bijection_is_subset_transpose_left.\n            - eapply high_dec.\n            - eauto.\n            - eauto.\n          }\n          assert (right \u03a8 l2 = None).\n          {\n            destruct (right \u03a8 l2) eqn:H_loc; try reflexivity.\n            rename l0 into l2'.\n            assert (left \u03a8 l2' = Some l2) by (destruct \u03a8; eauto 2).\n            assert (high \u2113 (s1 [i \u2192 ValLoc loc])\n                          (extend_heap v2 loc l n0 w1 H50 H33) l2').\n            {\n              eapply filtered_bijection_some_implies_predicate.\n              - eapply high_dec; eauto.\n              - eauto.\n              - eauto.\n            }\n            destruct (decide (loc = l2')); subst.\n            + congruence.\n            + assert (high \u2113 s1 w1 l2').\n              {\n                destruct_high.\n                - eapply HighReachable.\n                  eapply reach_extend_implies_reach_if with (v := v2).\n                  + intros; subst.\n                    eauto 3.\n                  + eauto.\n                  + eauto.\n                - rewrite -> heap_lookup_extend_neq in * by solve[eauto 2].\n                  eapply HighHeapLevel; eauto 3.\n              }\n              assert (left \u03a6 l2' = Some l2).\n              {\n                eapply filtered_bijection_is_subset.\n                - eapply high_dec.\n                - eauto.\n                - eauto.\n              }\n              assert (high \u2113 s1' w1' l2).\n              {\n                rewrite -> high_iff; eauto 2.\n                destruct \u03a6; eauto 2.\n              }\n              assert (high \u2113 s1' h' l2).\n              {\n                eapply low_gc_trans_preserves_high; eauto 2.\n              }\n              assert (wellformed_aux \u0393 \u03a33 \u27e8NewArr i l e e0, pc_end, s1', h', g2'' - 1 \u27e9 pc_end) by eauto 2.\n              repeat invert_wf_aux.\n              assert (exists \u2113 \u03bc, heap_lookup l2 h' = Some (\u2113, \u03bc)).\n              {\n                destruct_high; eauto 3.\n              }\n              super_destruct'.\n              congruence.\n          }\n          match goal with\n            [H1: left \u03a8 ?loc1 = None,\n                 H2: right \u03a8 ?loc2 = None |- _] =>\n            exists (extend_bijection \u03a8 loc1 loc2 H1 H2)\n          end.\n          exists (s1 [i \u2192 ValLoc loc]).\n          exists (extend_heap v2 loc l n0 w1 H50 H33).\n          exists (extend_stenv loc \u03c40 \u03a32).\n          \n          assert (state_low_eq \u2113 \u03c8\n                               (m1 [i \u2192 ValLoc l1]) \n                               (extend_heap v l1 l n h1 H9 H21)\n                               (s1 [i \u2192 ValLoc loc])\n                               (extend_heap v2 loc l n0 w1 H50 H33) \u0393 (extend_stenv l1 \u03c40 \u03a31)\n                               (extend_stenv loc \u03c40 \u03a32)).\n          {\n            destruct \u03c40 as [\u03c4 [\u2113' \u03b9']].\n            eapply state_low_eq_extend_EVERYTHING_high; try solve[intros; subst; eauto 3].\n            - repeat invert_wf_aux; eauto 2.\n            - repeat invert_wf_aux; eauto 2.\n            - repeat invert_wf_aux; eauto 2.\n            - repeat invert_wf_aux; eauto 2.\n            - intros; subst; repeat invert_wf_aux; eauto 2.\n            - intros; subst.\n              repeat invert_wf_aux.\n              assert (exists loc, v = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto 2.\n              super_destruct; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - intros; subst.\n              repeat invert_wf_aux.\n              assert (exists loc, v2 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc0.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc0) /\\ e0 = Var x) by eauto 2.\n              super_destruct; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              splits~.\n              + intros; eauto 3.\n              + intros; eauto 3.\n            - intros; contradiction.\n          }\n          assert (wf_bijection \u2113 \u03c8 \u0393\n                               (extend_stenv l1 \u03c40 \u03a31)\n                               (m1 [i \u2192 ValLoc l1])\n                               (extend_heap v l1 l n h1 H9 H21)).\n          {\n            destruct \u03c40 as [\u03c40 [\u2113' \u03b9']].\n            eapply wf_bijection_extend_mem_and_heap_high1; eauto 3.\n            - repeat invert_wf_aux; eauto.\n            - repeat invert_wf_aux; eauto.\n          }\n\n          assert (wellformed_aux \u0393 \u03a33 \u27e8NewArr i l e e0, pc_end, s1', h', g2'' - 1\u27e9 pc_end) by eauto 2.\n          splits~.\n          { eapply bridge_stop_num.\n            splits; eauto 2.\n            - constructor.\n              constructors; eauto 2.\n            - intro.\n              invert_low_event; contradiction.\n            - reflexivity.\n          }\n          { unfolds.\n            splits.\n            - splits; intros; invert_low_event; contradiction.\n            - intros; invert_low_event; contradiction.\n          }\n\n          assert (wf_taint_bijection \u2113 (extend_bijection \u03a8 loc l2 H58 H59)\n                                     (s1 [i \u2192 ValLoc loc]) (extend_heap v2 loc l n0 w1 H50 H33)).\n          {\n            eapply wf_taint_bijection_extend_mem_and_heap1; eauto 2.\n            intros; subst; eauto 2.\n          }\n          splits.\n          {\n            eapply wf_bijection_extend_mem_and_heap_high2; eauto 2.\n          }\n          {\n            eauto 2.\n          }\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H27).\n            unfold taint_eq in *; super_destruct'; subst.\n            destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n            repeat invert_wf_aux.\n            eapply wf_taint_bijection_extend_mem_and_heap2 with (\u03a6 := \u03a6) (m1 := s1) (h1 := w1) (v1 := v2); intros; subst; eauto 3.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans; eauto.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto.\n            - eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto.\n            - subst; eauto 2.\n            - subst; eauto 2.\n            - subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 3.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - subst.\n              assert (exists loc, v1 = ValLoc loc) by eauto 3.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n          }\n          {\n            unfolds.\n            splits.\n            - eauto 2.\n            - eapply taint_eq_mem_extend_mem_and_bijection; eauto.\n            - destruct \u03c40 as [\u03c3 [\u2113' \u03b9']].\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H27).\n              unfold taint_eq in *; super_destruct'; subst.\n              eapply taint_eq_reach_extend_mem_and_heap;\n                (intros; subst; eauto 3) || (try solve [repeat invert_wf_aux; eauto 2]).\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n                repeat invert_wf_aux; eauto 2.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + intros; subst.\n                repeat invert_wf_aux.\n                assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + subst.\n                repeat invert_wf_aux; eauto 3.\n              + subst.\n                repeat invert_wf_aux; eauto 3.                \n            - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H27).\n              unfold taint_eq in *; super_destruct'; subst.\n              eapply taint_eq_heap_extend_mem_and_heap with (\u03a6 := \u03a6).\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans.\n                * eauto.\n                * eauto.\n                * repeat invert_wf_aux; eauto 2.\n                * eauto.\n                * eauto.\n                * eauto.\n              + eauto.\n              + intros; subst; eauto 2.\n              + intros; subst; repeat invert_wf_aux; eauto 2.\n              + eauto.\n            - remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H27).\n              unfold taint_eq in *; super_destruct'; subst.\n              unfolds.\n              intros.\n              destruct (T_dec l0 l); subst.\n              + repeat rewrite -> size_extend_heap_eq_level by solve[eauto 2].\n                assert (size l w1' = size l h') by eauto 2.\n                assert (size l w1 = size l w1') by eauto 2.\n                omega.\n              + repeat rewrite -> size_extend_heap_neq_level by solve[eauto 2].\n                assert (size l0 w1' = size l0 h') by eauto 2.\n                assert (size l0 w1 = size l0 w1') by eauto 2.\n                omega.\n            - destruct \u03c40 as [\u03c3 \u03b5].\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H27).\n              unfold taint_eq in *; super_destruct'; subst.\n              repeat invert_wf_aux.\n              eapply taint_eq_heap_domain_eq_extend_mem_and_heap with (\u03a6 := \u03a6); eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eexists; splits; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto.\n              + intros; subst; eauto 3.\n              + intros; subst; eauto 3.\n            - unfolds.\n              intros.\n              destruct (decide (loc = loc1)); subst.\n              + _rewrite -> left_extend_bijection_eq in *.\n                rewrite_inj.\n                repeat rewrite -> extend_stenv_lookup_eq.\n                splits*.\n              + _rewrite -> left_extend_bijection_neq in * by solve[eauto 2].\n                assert (l2 <> loc2).\n                {\n                  intro; subst.\n                  assert (right \u03a8 loc2 = Some loc1) by (destruct \u03a8; eauto 2).\n                  congruence.\n                }\n                repeat rewrite -> extend_stenv_lookup_neq by solve[eauto 2].\n                assert (left \u03a6 loc1 = Some loc2).\n                {\n                  eapply filtered_bijection_is_subset.\n                  - eapply high_dec.\n                  - eauto 2.\n                  - eauto 2.\n                }\n                eapply H18; eauto 2.\n          }\n    }\n    (* Set *)\n    {\n      invert_bridge_step_with_steps 0.\n      + invert_low_event_step.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        invert_taint_eq; invert_taint_eq_cmd.\n        invert_event_step; try solve[invert_low_event].\n        assert (lookup_in_bounds m2 h2).\n        {\n          repeat invert_wf_aux; eauto.\n        }\n        invert_sem_step.\n        invert_low_event.\n        _apply set_bridge_properties in *.\n        super_destruct'; subst.\n        invert_bridge_step.\n        * invert_low_event_step.\n          invert_event_step; invert_low_event.\n          invert_sem_step.\n          rewrite_inj.\n          clear H40.\n          \n          assert (eval s1 e = Some (ValNum n0)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            repeat invert_lifted.\n            rewrite_inj.\n            destruct \u03b5_idx as [\u2113_idx \u03b9_idx].\n            rewrite -> ProdL.join_is_pairwise in *.\n            assert (\u2113_idx \u2294 pc_end \u2291 \u2113_x0) by eauto 2.\n            destruct_join_flowsto.\n            assert (\u2113_idx \u2291 \u2113) by eauto 2.\n            assert (exists u, onvals (left \u03c6) (ValNum n0) = Some u /\\ eval s1 e = Some u) by eauto 2 using eval_low_eq_possibilistic.\n            super_destruct'; subst.\n            unfold onvals in *.\n            rewrite_inj.\n            eauto.\n          }\n          assert (n0 = n3).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            repeat invert_lifted.\n            rewrite_inj.\n            destruct \u03b5_idx as [\u2113_idx \u03b9_idx].\n            assert_wf_type.\n            invert_wf_type.\n            repeat rewrite -> ProdL.join_is_pairwise in *.\n            assert (LH.flowsto (LH.join \u03b9_idx \u2218) \u2218) by eauto 2.\n            assert (val_taint_eq \u03a6 (SecType Int (\u2113_idx, \u03b9_idx)) (ValNum n0) (ValNum n3))\n              by eauto 2.\n            invert_val_taint_eq.\n            - reflexivity.\n            - inverts H3.\n          }\n          subst.\n          assert (exists u, onvals (left \u03c6) v0 = Some u /\\ eval s1 e0 = Some u).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            repeat invert_lifted.\n            rewrite_inj.\n            assert (\u2113_x0 \u2294 \u2113' \u2291 \u21131) by eauto 2.\n            destruct_join_flowsto.\n            assert_wf_type.\n            invert_wf_type.\n            assert (\u2113' \u2291 \u2113) by eauto 2.\n            eauto 2 using eval_low_eq_possibilistic.\n          }\n          super_destruct'; subst.\n          rewrite_inj.\n          exists (SetEvent \u21131 \u2113_x0 i n3 u) 0.\n\n          remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' m2 (update_heap l1 n3 v0 h1))\n                                            (low_dec \u2113 \u0393 \u03a31' m2 (update_heap l1 n3 v0 h1)) \u03c6).\n          super_destruct; subst.          \n          exists \u03c8.\n          assert (eval m2 (Var i) = Some (ValLoc l1)) by eauto 2.\n          assert (exists u, onvals (left \u03c6) (ValLoc l1) = Some u /\\ eval s1 (Var i) = Some u).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i) (SecType (Array (SecType \u03c40 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0))) by eauto 2.\n            eauto 2 using eval_low_eq_possibilistic.\n          }\n          super_destruct'; subst; unfold onvals in *.\n          break_match; try discriminate.\n          rewrite_inj.\n          remember_simple (filter_bijection (high \u2113 s1 (update_heap l n3 u w1)) (high_dec \u2113 s1 (update_heap l n3 u w1)) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8 s1 (update_heap l n3 u w1) \u03a32.\n\n          assert (left \u03a6 l = Some l3).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i) (SecType (Array (SecType \u03c3 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0))) by eauto 2.\n            assert (eval s2'' (Var i) = Some (ValLoc l3)) by eauto 2.\n            assert (val_taint_eq \u03a6 (SecType (Array (SecType \u03c3 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0)) (ValLoc l) (ValLoc l3)) by eauto 2 using eval_taint_eq.\n            invert_val_taint_eq; eauto 2.\n            assert_wf_type.\n            invert_wf_type.\n          }\n          assert (wellformed_aux \u0393 \u03a33' \u27e8SetArr i e e0, pc2'', s2'', h', g2'' - 1\u27e9 pc_end).\n          {\n            eauto 2 using gc_trans_preservation.\n          }\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a33' \u03a33' (SetArr i e e0) (SetArr i e e0) s2'' w1' s2'' h').\n          {\n            eauto 2.\n          }\n          unfold taint_eq in *; super_destruct'.\n          assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s2'' h').\n          {\n            rewrite <- (compose_id_right \u03a6).\n            repeat invert_wf_aux.\n            eapply taint_eq_heap_trans; eauto 2.\n          }\n          assert (high \u2113 s1 w1 l) by eauto 3.\n          assert (exists \u2113 \u03bc, heap_lookup l w1 = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            destruct_high; eauto 3.\n          }\n          assert (high \u2113 s2'' h' l3) by eauto 3.\n          assert (exists \u2113 \u03bc, heap_lookup l3 h' = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            destruct_high; eauto 3.\n          }\n          super_destruct'; subst.\n          assert (exists s, \u03a32 l = Some s) by (repeat invert_wf_aux; eauto 2).\n          super_destruct'; subst.\n          assert (\u03a33' l3 = Some s).\n          {\n            eapply H20; eauto 2.\n          }\n          assert (\u21132 = \u21130 /\\\n                  length_of l w1 = length_of l3 h' /\\\n                  (forall n,\n                      (exists v, lookup \u03bc0 n = Some v) <-> (exists v, lookup \u03bc n = Some v)) /\\\n                  (forall n v1 v2,\n                      reach s1 w1 l ->\n                      reach s2'' h' l3 ->\n                      lookup \u03bc0 n = Some v1 -> lookup \u03bc n = Some v2 -> val_taint_eq \u03a6 s v1 v2)).\n          {\n            eapply H46; eauto.\n          }\n          super_destruct'; subst.\n          assert (state_low_eq \u2113 \u03c8 m2 (update_heap l1 n3 v0 h1) s1 (update_heap l n3 u w1) \u0393 \u03a31' \u03a32).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply state_low_eq_update_heap with (length1 := length) (length2 := length0); try solve[intros; subst; eauto 3].\n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              assert (exists x, memory_lookup m2 x = Some (ValLoc loc) /\\ e0 = Var x)\n                by eauto 2.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              assert (wf_type bot (SecType (Array (SecType (Array s0 \u21133) (\u21131, \u03b90)) \u21132) (\u2113_x0, \u03b9_x0))) by eauto 2.\n              do 2 invert_wf_type.\n              splits~; eauto 3.\n              intros.\n              assert (wf_type bot (SecType (Array s0 \u21133) \u03b5)) by eauto 2.\n              invert_wf_type.\n              destruct_prod_join_flowsto.\n              assert (l_ref \u2291 \u21131) by eauto 2.\n              eauto 3.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc) /\\ e0 = Var x)\n                by eauto 2.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              assert (wf_type bot (SecType (Array (SecType (Array s0 \u21133) (\u21131, \u03b90)) \u21132) (\u2113_x0, \u03b9_x0))) by eauto 2.\n              do 2 invert_wf_type.\n              splits~; eauto 3.\n              intros.\n              assert (wf_type bot (SecType (Array s0 \u21133) \u03b5)) by eauto 2.\n              invert_wf_type.\n              destruct_prod_join_flowsto.\n              assert (l_ref \u2291 \u21131) by eauto 2.\n              eauto 3.\n            - destruct \u03b5 as [\u2113' \u03b9'].\n              destruct_prod_join_flowsto.\n              assert (\u2113' \u2291 \u21131) by eauto 2.\n              assert (\u2113' \u2291 \u2113) by eauto 2.\n              eapply val_low_eq_mon.\n              + invert_state_low_eq.\n                eapply eval_low_eq with (m1 := m2); eauto 3.\n              + eauto 2.\n            - congruence.\n          }\n          \n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' m2 (update_heap l1 n3 v0 h1)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert_wf_type.\n            invert_wf_type.\n            eapply wf_bijection_update_heap1.\n            - eauto 3.\n            - eauto.\n            - intros; subst.\n              destruct \u03c3.\n              + assert (exists n, ValLoc loc' = ValNum n) by eauto 2.\n                super_destruct; discriminate.\n              + assert (exists x, memory_lookup m2 x = Some (ValLoc loc') /\\ e0 = Var x)\n                  by eauto 2.\n                super_destruct; subst.\n                destruct \u03b5 as [\u2113' \u03b9'].\n                destruct_prod_join_flowsto.\n                assert (\u2113' \u2291 \u21131) by eauto 2.\n                assert (\u2113' \u2291 \u2113) by eauto 2.\n                invert_var_typing.\n                assert_wf_type.\n                invert_wf_type.\n                eauto 3.\n            - eauto.\n          }\n          \n          splits.\n          {\n            constructor.\n            splits; eauto 2.\n            constructor.\n            eapply event_sem_step_set; eauto 2.\n            eapply step_set with (length := length0); eauto 2.\n            congruence.\n          }\n          {\n            eauto 2.\n          }\n          {\n            eauto 2.\n          }\n          {\n            eauto 2.\n          }\n          {\n            splits*.\n            intros.\n            constructor.\n            break_match; rewrite_inj.\n            - eauto 2.\n            - break_match; try discriminate.\n              subst.\n              rewrite_inj.\n              assert (low \u2113 \u0393 \u03a31' m2 (update_heap l1 n3 (ValLoc l0) h1) l0).\n              {\n                assert (low \u2113 \u0393 \u03a31' m2 h1 l0) by eauto 2.\n                destruct_low.\n                - repeat invert_wf_aux.\n                  assert_wf_type.\n                  invert_wf_type.\n                  repeat specialize_gen.\n                  invert_wt_cmd.\n                  invert_lifted.\n                  rewrite_inj.\n                  assert (exists \u03c4 \u2113, \u03c3 = Array \u03c4 \u2113).\n                  {\n                    destruct \u03c3.\n                    - assert (exists n, ValLoc loc = ValNum n) by eauto 3.\n                      super_destruct'; congruence.\n                    - do 2 eexists; reflexivity.\n                  }\n                  super_destruct'; subst.\n                  rewrite_inj.\n                  invert_wf_type.\n                  assert (reach m h l1) by eauto 2.\n                  assert (exists \u2113 \u03bc, heap_lookup l1 h = Some (\u2113, \u03bc)) by eauto 2.\n                  super_destruct'.\n                  eapply LowReachable.\n                  eapply LowReachHeap.\n                  + eapply LowReachMem.\n                    * eauto 2.\n                    * eauto.\n                    * eauto.\n                  + eauto 3.\n                  + eapply heap_lookup_update_eq; eauto 2.\n                  + eauto 2.\n                  + eauto 2.\n                - destruct (decide (l1 = loc)); subst.\n                  + eapply LowHeapLevel.\n                    * eapply heap_lookup_update_eq; eauto 2.\n                    * eauto 2.\n                  + eapply LowHeapLevel.\n                    * rewrite -> heap_lookup_update_neq by solve[eauto 2].\n                      eauto 2.\n                    * eauto 2.\n              }\n              assert (left \u03c8 l0 = Some l2) by eauto 2.\n              eauto 2.\n          }\n          {\n            repeat invert_wf_aux.\n            assert_wf_type.\n            invert_wf_type.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply TaintEqEventSet.\n            - eauto 2.\n            - destruct \u03b5 as [\u2113' \u03b9'].\n              destruct_prod_join_flowsto.\n              eapply val_taint_eq_mon with (\u21131 := \u2113') (\u03b91 := \u03b9'); eauto 2.\n              assert (val_taint_eq \u03a6 (SecType \u03c3 (\u2113', \u03b9')) u v2) by eauto 2 using eval_taint_eq.\n              invert_val_taint_eq; eauto 2.\n              assert (left \u03a8 loc = Some loc').\n              {\n                assert (high \u2113 s1 (update_heap l n3 (ValLoc loc) w1) loc).\n                {\n                  eauto 3.\n                }\n                eapply filter_true; eauto 2.\n              }\n              eauto 2.\n          }\n          {\n            eauto 2.\n          }\n\n          assert (wf_taint_bijection \u2113 \u03a8 s1 (update_heap l n3 u w1)).\n          {\n            eapply taint_eq_update_bijection1; eauto 2.\n            intros; subst.\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            eapply eval_implies_reach; eauto 2.\n          }\n\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          assert (val_taint_eq \u03a6 (SecType \u03c3 (\u21131, \u03b90)) u v2).\n          {\n            destruct \u03b5 as [\u2113'' \u03b9''].\n            destruct_prod_join_flowsto.\n            eapply val_taint_eq_mon; eauto.\n            eapply LHLatProp.flowsto_refl.\n          }\n\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          splits~.\n\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply wf_bijection_update_heap2; try solve[intros; subst; eauto 3].\n            - eapply val_low_eq_mon.\n              + repeat invert_state_low_eq.\n                eauto 3.\n              + repeat destruct_prod_join_flowsto.\n                eauto.                \n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits~.\n              intros.\n              destruct \u03b5 as [\u2113'' \u03b9''].\n              repeat destruct_join_flowsto.\n              assert (\u2113_x0 \u2294 \u2113'' \u2291 \u21131) by eauto 2.\n              destruct_join_flowsto.\n              assert (\u2113'' \u2291 \u2113) by eauto 3.\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (exists x, memory_lookup m2 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto 2.\n              super_destruct'; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits~.\n              intros.\n              destruct \u03b5 as [\u2113'' \u03b9''].\n              repeat destruct_join_flowsto.\n              assert (\u2113_x0 \u2294 \u2113'' \u2291 \u21131) by eauto 2.\n              destruct_join_flowsto.\n              assert (\u2113'' \u2291 \u2113) by eauto 3.\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto 2.\n              super_destruct'; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              eauto 2.\n          }\n          \n          {\n            eapply wf_taint_bijection_update_heap2 with (\u03a6 := \u03a6) (m1 := s1) (m2 := s2'')\n            ; eauto 2.\n            - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              eauto 2.\n            - intros; subst.\n              eauto 2.\n          }\n          { eapply taint_eq_mem_update_heap; eauto 2. }\n          { eapply taint_eq_reach_update_heap; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              eauto 2.\n            - intros; subst.\n              eauto 2.\n            - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n          }\n          { assert (\u03a32 l = Some (SecType \u03c30 (\u21131, \u03b90))) by eauto 2.\n            rewrite_inj.\n            eapply taint_eq_heap_update_heap; eauto 2.\n            + intros; subst.\n              eauto 2.\n            + intros; subst.\n              eauto 2. }\n          { splits.\n            - unfolds.\n              intros.\n              repeat rewrite -> size_update_heap.\n              rewrite -> H18 by eauto 2.\n              eauto 2.\n            - repeat invert_wf_aux.\n              eapply taint_eq_heap_update_domain_eq_update_heap with (\u03a6 := \u03a6) (\u03a31 := \u03a32) (\u03a32 := \u03a33'); eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                eexists; eauto 3.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                eexists; eauto 3.\n              + intros; subst; eauto 2.\n              + intros; subst; eauto 3.\n            - unfolds.\n              intros.\n              assert (left \u03a6 loc1 = Some loc2).\n              {\n                eapply filtered_bijection_is_subset.\n                - eapply high_dec.\n                - eauto 2.\n                - eauto 2.\n              }\n              eauto. }\n        * unfold is_stop_config, cmd_of in *; subst.\n          invert_high_event_step.\n          invert_event_step.\n          invert_sem_step.\n          rewrite_inj.\n          assert (low_event \u2113 (SetEvent \u21131 \u2113_x0 i n3 v2)) by eauto 2.\n          contradiction.\n      + invert_high_event_step.\n        unfold is_stop_config, cmd_of in *; subst.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8Stop, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        invert_taint_eq; invert_taint_eq_cmd.\n        invert_event_step; try solve[invert_low_event].\n        assert (lookup_in_bounds m2 h2).\n        {\n          repeat invert_wf_aux; eauto.\n        }\n        invert_sem_step.\n        invert_high_event.\n        _apply set_bridge_properties in *.\n        super_destruct'; subst.\n        invert_bridge_step.\n        * invert_low_event_step.\n          invert_event_step; try solve[invert_low_event].\n          rewrite_inj.\n          invert_low_event.\n          assert (low_event \u2113 (SetEvent \u21131 \u2113_x0 i n0 v0)) by eauto 2.\n          contradiction.\n        * invert_high_event_step.\n          invert_event_step.\n          invert_sem_step.\n          rewrite_inj.\n          clear H31.\n          \n         assert (eval s1 e = Some (ValNum n3)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            repeat invert_lifted.\n            rewrite_inj.\n            destruct \u03b5_idx as [\u2113_idx \u03b9_idx].\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s2'' s1) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H9 H27 H24 H3 H50).\n            super_destruct'; subst.\n            invert_val_taint_eq.\n            - eauto.\n            - assert_wf_type.\n              invert_wf_type.\n              assert (LH.flowsto (LH.join \u2022 \u2218) \u2218) as H' by eauto 2.\n              inverts H'.\n          }\n   \n          assert (exists u,\n                     eval s1 e0 = Some u /\\ val_taint_eq \u03a6 (SecType \u03c40 (\u21131, \u03b90)) u v2).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            repeat invert_lifted.\n            rewrite_inj.\n            assert_wf_type.\n            invert_wf_type.\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s2'' s1) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H21 H28 H25 H3 H51).\n            super_destruct'; subst.\n            exists v1.\n            splits*.\n          }\n          super_destruct'; subst.\n          rewrite_inj.\n          exists (SetEvent \u21131 \u2113_x0 i n3 u) 0.\n\n          remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' m2 (update_heap l1 n0 v0 h1))\n                                            (low_dec \u2113 \u0393 \u03a31' m2 (update_heap l1 n0 v0 h1)) \u03c6).\n          super_destruct; subst.          \n          exists \u03c8.\n          assert (eval m2 (Var i) = Some (ValLoc l1)) by eauto 2.\n          assert (exists l, right \u03a6 l3 = Some l /\\ eval s1 (Var i) = Some (ValLoc l)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i) (SecType (Array (SecType \u03c40 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0))) by eauto 2.\n            invert_lifted.\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s2'' s1) by eauto 2.\n            assert (eval s2'' (Var i) = Some (ValLoc l3)) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H3 H32 H29 H4 H28).\n            super_destruct'; subst.\n            invert_val_taint_eq.\n            - destruct \u03a6; eexists; splits*.\n            - assert_wf_type.\n              invert_wf_type.\n          }\n          super_destruct'; subst; unfold onvals in *.\n          remember_simple (filter_bijection (high \u2113 s1 (update_heap l n3 u w1))\n                                            (high_dec \u2113 s1 (update_heap l n3 u w1)) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8 s1 (update_heap l n3 u w1) \u03a32.\n\n          assert (left \u03a6 l = Some l3).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i) (SecType (Array (SecType \u03c3 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0))) by eauto 2.\n            assert (eval s2'' (Var i) = Some (ValLoc l3)) by eauto 2.\n            assert (val_taint_eq \u03a6 (SecType (Array (SecType \u03c3 (\u21131, \u03b90)) \u21130) (\u2113_x0, \u03b9_x0)) (ValLoc l) (ValLoc l3)) by eauto 2 using eval_taint_eq.\n            invert_val_taint_eq; eauto 2.\n            assert_wf_type.\n            invert_wf_type.\n          }\n          assert (wellformed_aux \u0393 \u03a33' \u27e8SetArr i e e0, pc2'', s2'', h', g2'' - 1\u27e9 pc_end).\n          {\n            eauto 2 using gc_trans_preservation.\n          }\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a33' \u03a33' (SetArr i e e0) (SetArr i e e0) s2'' w1' s2'' h').\n          {\n            eauto 2.\n          }\n          unfold taint_eq in *; super_destruct'.\n          assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s2'' h').\n          {\n            rewrite <- (compose_id_right \u03a6).\n            repeat invert_wf_aux.\n            eapply taint_eq_heap_trans; eauto 2.\n          }\n          assert (high \u2113 s1 w1 l) by eauto 3.\n          assert (exists \u2113 \u03bc, heap_lookup l w1 = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            destruct_high; eauto 3.\n          }\n          assert (high \u2113 s2'' h' l3) by eauto 3.\n          assert (exists \u2113 \u03bc, heap_lookup l3 h' = Some (\u2113, \u03bc)).\n          {\n            repeat invert_wf_aux.\n            destruct_high; eauto 3.\n          }\n          super_destruct'; subst.\n          assert (exists s, \u03a32 l = Some s) by (repeat invert_wf_aux; eauto 2).\n          super_destruct'; subst.\n          assert (\u03a33' l3 = Some s).\n          {\n            eapply H20; eauto 2.\n          }\n          assert (\u21132 = \u21130 /\\\n                  length_of l w1 = length_of l3 h' /\\\n                  (forall n,\n                      (exists v, lookup \u03bc0 n = Some v) <-> (exists v, lookup \u03bc n = Some v)) /\\\n                  (forall n v1 v2,\n                      reach s1 w1 l ->\n                      reach s2'' h' l3 ->\n                      lookup \u03bc0 n = Some v1 -> lookup \u03bc n = Some v2 -> val_taint_eq \u03a6 s v1 v2)).\n          {\n            eapply H49; eauto.\n          }\n          super_destruct'; subst.\n          assert (~ \u21131 \u2291 \u2113).\n          {\n            intro.\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert_wf_type.\n            invert_wf_type.\n            destruct \u03b5 as [\u2113' \u03b9'].\n            assert (\u2113_x0 \u2294 \u2113' \u2291 \u21131) by eauto 2.\n            destruct_join_flowsto.\n            assert (\u2113_x0 \u2291 \u2113) by eauto.\n            assert (low_event \u2113 (SetEvent \u21131 \u2113_x0 i n3 v2)) by eauto 2.\n            contradiction.\n          }\n          assert (state_low_eq \u2113 \u03c8 m2 (update_heap l1 n0 v0 h1) s1 (update_heap l n3 u w1) \u0393 \u03a31' \u03a32).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply state_low_eq_update_heap with (length1 := length) (length2 := length0); try solve[intros; subst; eauto 3].\n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              assert (exists x, memory_lookup m2 x = Some (ValLoc loc) /\\ e0 = Var x)\n                by eauto 2.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              assert (wf_type bot (SecType (Array (SecType (Array s0 \u21133) (\u21131, \u03b90)) \u21132) (\u2113_x0, \u03b9_x0))) by eauto 2.\n              do 2 invert_wf_type.\n              splits~; eauto 3.\n              intros.\n              assert (wf_type bot (SecType (Array s0 \u21133) \u03b5)) by eauto 2.\n              invert_wf_type.\n              destruct_prod_join_flowsto.\n              assert (l_ref \u2291 \u21131) by eauto 2.\n              eauto 3.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc) /\\ e0 = Var x)\n                by eauto 2.\n              super_destruct; subst.\n              rewrite_inj.\n              invert_var_typing.\n              assert (wf_type bot (SecType (Array (SecType (Array s0 \u21133) (\u21131, \u03b90)) \u21132) (\u2113_x0, \u03b9_x0))) by eauto 2.\n              do 2 invert_wf_type.\n              splits~; eauto 3.\n              intros.\n              assert (wf_type bot (SecType (Array s0 \u21133) \u03b5)) by eauto 2.\n              invert_wf_type.\n              destruct_prod_join_flowsto.\n              assert (l_ref \u2291 \u21131) by eauto 2.\n              eauto 3.\n            - destruct \u03c3.\n              + assert (exists n, v0 = ValNum n) by eauto 2.\n                assert (exists n, u = ValNum n) by eauto 2.\n                super_destruct'; subst; eauto 2.\n              + assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                assert (exists loc, u = ValLoc loc) by eauto 2.\n                super_destruct'; subst; eauto 2.\n            - intros; contradiction.\n            - congruence.\n          }\n\n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' m2 (update_heap l1 n0 v0 h1)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert_wf_type.\n            invert_wf_type.\n            eapply wf_bijection_update_heap1.\n            - eauto 3.\n            - eauto.\n            - intros; subst.\n              destruct \u03c3.\n              + assert (exists n, ValLoc loc' = ValNum n) by eauto 2.\n                super_destruct; discriminate.\n              + assert (exists x, memory_lookup m2 x = Some (ValLoc loc') /\\ e0 = Var x)\n                  by eauto 2.\n                super_destruct; subst.\n                destruct \u03b5 as [\u2113' \u03b9'].\n                destruct_prod_join_flowsto.\n                assert (\u2113' \u2291 \u21131) by eauto 2.\n                assert (\u2113' \u2291 \u2113) by eauto 2.\n                invert_var_typing.\n                assert_wf_type.\n                invert_wf_type.\n                eauto 3.\n            - eauto.\n          }\n          \n          splits.\n          {\n            eapply bridge_stop_num.\n            - splits; eauto 2.\n              + constructor.\n                eapply event_sem_step_set; eauto 2.\n                eapply step_set; eauto 2.\n                congruence.\n              + intro.\n                invert_low_event.\n                contradiction.\n            - reflexivity.\n          }\n          {\n            eauto 2.\n          }\n          {\n            eauto 2.\n          }\n          {\n            eauto 2.\n          }\n          {\n            splits.\n            - splits; intro; invert_low_event; contradiction.\n            - intro; invert_low_event; contradiction.\n          }\n          {\n            repeat invert_wf_aux.\n            assert_wf_type.\n            invert_wf_type.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply TaintEqEventSet.\n            - eauto 2.\n            - destruct \u03b5 as [\u2113' \u03b9'].\n              destruct_prod_join_flowsto.\n              eapply val_taint_eq_mon with (\u21131 := \u2113') (\u03b91 := \u03b9'); eauto 2.\n              assert (val_taint_eq \u03a6 (SecType \u03c3 (\u2113', \u03b9')) u v2) by eauto 2 using eval_taint_eq.\n              invert_val_taint_eq; eauto 2.\n              assert (left \u03a8 loc = Some loc').\n              {\n                assert (high \u2113 s1 (update_heap l n3 (ValLoc loc) w1) loc).\n                {\n                  eauto 3.\n                }\n                eapply filter_true; eauto 2.\n              }\n              eauto 2.\n          }\n          {\n            eauto 2.\n          }\n\n          assert (wf_taint_bijection \u2113 \u03a8 s1 (update_heap l n3 u w1)).\n          {\n            eapply taint_eq_update_bijection1; eauto 2.\n            intros; subst.\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            eapply eval_implies_reach; eauto 2.\n          }\n\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          assert (val_taint_eq \u03a6 (SecType \u03c3 (\u21131, \u03b90)) u v2).\n          {\n            destruct \u03b5 as [\u2113'' \u03b9''].\n            destruct_prod_join_flowsto.\n            eapply val_taint_eq_mon; eauto.\n            eapply LHLatProp.flowsto_refl.\n          }\n\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          splits~.\n\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            eapply wf_bijection_update_heap2; try solve[intros; subst; eauto 3].\n            - intros; contradiction.\n            - eapply val_low_eq_mon.\n              + repeat invert_state_low_eq.\n                eauto 3.\n              + repeat destruct_prod_join_flowsto.\n                eauto.\n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits~.\n              intros.\n              destruct \u03b5 as [\u2113'' \u03b9''].\n              repeat destruct_join_flowsto.\n              assert (\u2113_x0 \u2294 \u2113'' \u2291 \u21131) by eauto 2.\n              destruct_join_flowsto.\n              assert (\u2113'' \u2291 \u2113) by eauto 3.\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (exists x, memory_lookup m2 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto 2.\n              super_destruct'; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits~.\n              intros.\n              destruct \u03b5 as [\u2113'' \u03b9''].\n              repeat destruct_join_flowsto.\n              assert (\u2113_x0 \u2294 \u2113'' \u2291 \u21131) by eauto 2.\n              destruct_join_flowsto.\n              assert (\u2113'' \u2291 \u2113) by eauto 3.\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (exists x, memory_lookup s1 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto 2.\n              super_destruct'; subst.\n              invert_var_typing.\n              assert_wf_type.\n              invert_wf_type.\n              eauto 2.\n          }\n          {\n            eapply wf_taint_bijection_update_heap2 with (\u03a6 := \u03a6) (m1 := s1) (m2 := s2'')\n            ; eauto 2.\n            - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              eauto 2.\n            - intros; subst.\n              eauto 2.\n          }\n          { eapply taint_eq_mem_update_heap; eauto 2. }\n          { eapply taint_eq_reach_update_heap; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_domain_eq_trans; eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              assert (exists loc, v2 = ValLoc loc) by eauto 2.\n              super_destruct'; subst.\n              eexists; splits; eauto 2.\n            - intros; subst.\n              eauto 2.\n            - intros; subst.\n              eauto 2.\n            - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n            - rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n          }\n          { assert (\u03a32 l = Some (SecType \u03c30 (\u21131, \u03b90))) by eauto 2.\n            rewrite_inj.\n            eapply taint_eq_heap_update_heap; eauto 2.\n            + intros; subst.\n              eauto 2.\n            + intros; subst.\n              eauto 2. }\n          { splits.\n            - unfolds.\n              intros.\n              repeat rewrite -> size_update_heap.\n              rewrite -> H18 by eauto 2.\n              eauto 2.\n            - repeat invert_wf_aux.\n              eapply taint_eq_heap_update_domain_eq_update_heap with (\u03a6 := \u03a6) (\u03a31 := \u03a32) (\u03a32 := \u03a33'); eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                eexists; eauto 3.\n              + intros; subst.\n                assert (exists loc, v2 = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                eexists; eauto 3.\n              + intros; subst; eauto 2.\n              + intros; subst; eauto 3.\n            - unfolds.\n              intros.\n              assert (left \u03a6 loc1 = Some loc2).\n              {\n                eapply filtered_bijection_is_subset.\n                - eapply high_dec.\n                - eauto 2.\n                - eauto 2.\n              }\n              eauto. }\n          }\n    (* Get *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n        invert_event_step; try solve[invert_low_event].\n        invert_low_event.\n        invert_sem_step.\n        rewrite_inj.\n        _apply get_bridge_properties in *.\n        super_destruct'; subst.\n        invert_bridge_step_with_steps 0.\n        + invert_low_event_step.\n          invert_event_step; try solve[invert_low_event].\n          invert_sem_step.\n          rewrite_inj.\n          clear H29.\n          rewrite_inj.\n          assert (wellformed_aux \u0393 \u03a33' \u27e8GetArr i i0 e, pc2'', s1', w2'', g2'' - 1\u27e9 pc_end) by eauto 2.\n          assert (exists l3, right \u03a6 l2 = Some l3 /\\ memory_lookup s1 i0 = Some (ValLoc l3)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i0) (SecType (Array (SecType \u03c3 \u03b5) \u21132) \u03b5_y)) by eauto 2.\n            destruct \u03b5_y as [\u2113_y \u03b9_y].\n            assert (\u2113_y \u2291 \u2113_x0).\n            {\n              destruct \u03b5.\n              destruct_prod_join_flowsto.\n              eauto 2.\n            }\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            assert (eval s1' (Var i0) = Some (ValLoc l2)) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H3 H27 H20 H5 H66).\n            super_destruct'; subst.\n            invert_val_taint_eq.\n            - destruct \u03a6; eexists; splits*.\n            - assert_wf_type.\n              invert_wf_type.\n          }\n          super_destruct'; subst.\n          assert (eval s1 e = Some (ValNum n1)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            destruct \u03b5_idx as [\u2113_idx \u03b9_idx].\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H8 H29 H24 H3 H49).\n            super_destruct'; subst.\n            invert_val_taint_eq; eauto 2.\n            assert_wf_type.\n            invert_wf_type.\n            destruct_prod_join_flowsto.\n            assert (LH.flowsto \u2022 \u2218) as H' by eauto 2.\n            inverts H'.\n          }\n          invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n          invert_lifted; rewrite_inj.\n          assert (exists u \u2113 \u03bc, heap_lookup l3 w1 = Some (\u2113, \u03bc) /\\ lookup \u03bc n1 = Some u /\\ val_taint_eq \u03a6 (SecType \u03c3 (\u2113_x0, \u03b90)) u v1 /\\ length_of l3 w1 = Some length0).\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            unfold taint_eq; super_destruct'; subst.\n            assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans.\n              - eapply gc_trans_preserves_taint_eq_reach; eauto 2.\n              - eauto 2.\n              - repeat invert_wf_aux; eauto 2.\n              - eauto 2.\n              - eapply low_gc_trans_preserves_taint_eq_heap; eauto 2.\n              - eapply low_gc_trans_preserves_taint_eq_heap_domain_eq; eauto 2.\n            }\n            assert (left \u03a6 l3 = Some l2) by (destruct \u03a6; eauto 2).\n            assert (high \u2113 s1 w1 l3) by eauto 3.\n            assert (exists \u2113 \u03bc, heap_lookup l3 w1 = Some (\u2113, \u03bc)).\n            {\n              repeat invert_wf_aux.\n              destruct_high; eauto 3.\n            }\n            assert (high \u2113 s1' w2'' l2) by eauto 3.\n            super_destruct'; subst.\n            assert (\u03a33' l2 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n            assert (\u03a32 l3 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n            remember_simple (H25 l3 l2 _ _ _ _ _ H26 H32 H46 H33 H54 H56 H47).\n            super_destruct'; subst.\n            assert (exists v1, lookup \u03bc1 n1 = Some v1) by firstorder 2.\n            super_destruct'; subst.\n            exists v2.\n            assert (val_taint_eq \u03a6 (SecType \u03c3 \u03b5) v2 v1) by eauto 4.\n            exists \u21131 \u03bc1.\n            splits*.\n            - destruct \u03b5, \u03b5_y; destruct_prod_join_flowsto.\n              eapply val_taint_eq_mon with (\u21131 := t0) (\u03b91 := t1); eauto 2.\n            - congruence.\n          }\n          super_destruct'; subst.\n          exists (GetEvent \u2113_x0 i i0 u) 0.\n          \n          remember_simple (filter_bijection\n                             (low \u2113 \u0393 \u03a31' (m1 [i \u2192 v0]) h2)\n                             (low_dec \u2113 \u0393 \u03a31' (m1 [i \u2192 v0]) h2) \u03c6).\n          super_destruct'; subst.\n          exists \u03c8.\n          remember_simple (filter_bijection\n                             (high \u2113 (extend_memory i u s1) w1)\n                             (high_dec \u2113 (extend_memory i u s1)\n                                        w1) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8.\n          exists (extend_memory i u s1).\n          exists w1 \u03a32.\n          \n          assert (n0 = n1).\n          {\n            invert_state_low_eq.\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert (val_low_eq \u2113 (SecType Int \u03b5_idx) (ValNum n0) (ValNum n1) \u03c6)\n              by eauto 2.\n            invert_val_low_eq.\n            - destruct_prod_join_flowsto.\n              destruct \u03b5_y0 as [\u2113' \u03b9'].\n              assert (\u21132 \u2291 \u2113') by eauto 2.\n              assert (~ \u2113' \u2291 \u2113) by eauto 2.\n              destruct_prod_join_flowsto.\n              destruct \u03b50 as [\u2113'' \u03b9''].\n              assert (\u2113' \u2291 \u2113_x0) by eauto 2.\n              assert (~ \u2113_x0 \u2291 \u2113) by eauto 2.\n              contradiction.\n            - reflexivity.\n          }\n          subst.\n          assert (val_low_eq \u2113 (SecType \u03c3 \u03b5) v0 u \u03c6).\n          {\n            assert (val_low_eq \u2113 (SecType (Array (SecType \u03c3 \u03b5) \u21132) \u03b5_y) (ValLoc l1)\n                               (ValLoc l3) \u03c6).\n            {\n              invert_state_low_eq; eauto 2.\n            }\n            invert_val_low_eq.\n            + destruct \u03b5; destruct_prod_join_flowsto.\n              assert (\u21134 \u2291 \u2113_x0) by eauto 2.\n              assert (\u21134 \u2291 \u2113) by eauto 2.\n              contradiction.\n            + assert (\u03a31' l1 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n              assert (\u03a32 l3 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n              assert (low \u2113 \u0393 \u03a31' m1 h2 l1) by eauto 2.\n              assert (low \u2113 \u0393 \u03a32 s1 w1 l3).\n              {\n                eapply low_iff; destruct \u03c6; eauto 2.\n              }\n              invert_state_low_eq.\n              assert (heapval_low_eq \u2113 (SecType \u03c3 \u03b5) l1 l3 m1 s1 h2 w1 \u03c6) by eauto 2.\n              invert_heapval_low_eq.\n              assert (reach m1 h2 l1) by eauto 2.\n              assert (reach s1 w1 l3) by eauto 2.\n              rewrite_inj.\n              eauto 2.\n          }\n          \n          assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 v0]) h2\n                               (s1 [i \u2192 u]) w1 \u0393 \u03a31' \u03a32).\n          {\n            repeat destruct_prod_join_flowsto.\n            repeat invert_wf_aux.\n            eapply state_low_eq_extend_memory; eauto 2.\n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              destruct \u03b5_y as [\u2113_y \u03b9_y].\n              assert (\u2113_y \u2291 \u2113_x0) by eauto 2.\n              assert (\u2113_y \u2291 \u2113) by eauto 2.\n              destruct \u03b5 as [\u2113' \u03b9'].\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (\u2113' \u2291 \u2113_x0) by eauto 2.\n              assert (\u2113' \u2291 \u2113) by eauto 2.\n              eapply LowReachHeap; eauto 2.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              destruct \u03b5_y as [\u2113_y \u03b9_y].\n              assert (\u2113_y \u2291 \u2113_x0) by eauto 2.\n              assert (\u2113_y \u2291 \u2113) by eauto 2.\n              destruct \u03b5 as [\u2113' \u03b9'].\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (\u2113' \u2291 \u2113_x0) by eauto 2.\n              assert (\u2113' \u2291 \u2113) by eauto 2.\n              eapply LowReachHeap; eauto 2.\n            - intros; subst; eauto 3.\n            - intros; subst; eauto 3.\n            - eapply wf_tenv_extend.\n              + eauto.\n              + eauto.\n              + intros; subst; eauto.\n              + intros; subst; eauto.\n          }\n\n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 v0]) h2).\n          {\n            repeat invert_wf_aux.\n            eapply wf_bijection_extend_mem1; intros; subst; eauto 3.\n            - subst.\n              eauto 3.\n            - subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              assert_wf_type.\n              invert_wf_type.\n              invert_wf_type.\n              assert (l_ref0 \u2294 l_ref \u2291 \u2113_x0) by eauto 2.\n              destruct_join_flowsto.\n              assert (l_ref \u2291 \u2113) by eauto 2.\n              assert (low_reach \u2113 \u0393 \u03a31' m1 h2 l1) by eauto 2.\n              eapply LowReachHeap; eauto 2.\n          }\n\n          assert (wf_taint_bijection \u2113 \u03a8 (s1 [i \u2192 u]) w1).\n          {\n            eapply wf_taint_bijection_extend_mem1; eauto 2.\n            intros; subst.\n            eapply reach_heap with (loc0 := l3); eauto 2.\n          }\n\n          assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop\n                           (s1 [i \u2192 u]) w1\n                           (s1' [i \u2192 v1]) w2'').\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            unfold taint_eq in *; super_destruct'.\n            repeat invert_wf_aux.\n            splits~.\n            - eapply taint_eq_mem_extend; eauto 2.\n            - eapply taint_eq_reach_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + intros; subst.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n            - eapply taint_eq_heap_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              + intros; subst; eauto.\n              + intros; subst; eauto.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n            - eapply taint_eq_heap_size_trans; eauto 2.\n            - eapply taint_eq_heap_domain_eq_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst; eauto 3.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst; eauto 3.\n            - eapply taint_eq_stenv_extend_mem; eauto 2.\n          }\n          \n          splits~.\n          * constructor.\n            splits; eauto 2.\n            constructor.\n            eapply event_sem_step_get; eauto 2.\n          * unfolds.\n            splits~.\n            { splits*. }\n            { intros.\n              invert_low_event.\n              destruct \u03b5 as [\u2113_arr \u03b9_arr].\n              destruct \u03b5_y as [\u2113_y \u03b9_y].\n              assert (\u2113_arr \u2294 \u2113_y \u2291 \u2113_x0) by eauto 2.\n              destruct_join_flowsto.\n              assert (\u2113_arr \u2291 \u2113) by eauto 2.\n              constructor; eauto 2.\n              invert_val_low_eq; contradiction || eauto 2.\n              assert (low \u2113 \u0393 \u03a31' (m1 [i \u2192 ValLoc l0]) h2 l0).\n              {\n                eauto 2.\n                assert (wf_type bot (SecType (Array \u03c4 \u2113_p) (\u2113_x0, \u03b90))) as H' by eauto 2.\n                invert_wf_type.\n                eapply LowReachable.\n                eauto 3.\n              }\n              eauto 3. }\n          * eapply TaintEqEventGet; eauto 2.\n            invert_val_taint_eq; eauto 2.\n            assert (high \u2113 (s1 [i \u2192 ValLoc loc]) w1 loc) by eauto 3.\n            assert (left \u03a8 loc = Some loc') by eauto 2.\n            eauto 2.\n          * splits~.\n            {\n              repeat invert_wf_aux.\n              repeat destruct_prod_join_flowsto.\n              eapply wf_bijection_extend_mem2; try solve[intros; subst; eauto 3].\n              intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              assert_wf_type.\n              do 2 invert_wf_type.\n              assert (l_ref \u2291 \u2113_x0) by eauto 2.\n              assert (l_ref \u2291 \u2113) by eauto 2.\n              assert (l_ref0 \u2291 \u2113_x0) by eauto 2.\n              assert (l_ref0 \u2291 \u2113) by eauto 2.\n              rewrite_inj.\n              eapply LowReachHeap; eauto 2.\n            }\n            {\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n              repeat invert_wf_aux.\n              unfold taint_eq in *; super_destruct'.\n              eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans.\n                + eauto.\n                + eapply gc_trans_preserves_taint_eq_reach; eauto.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              - intros; subst.\n                eauto.\n              - intros; subst.\n                eauto.\n              - intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                exists loc.\n                splits~.\n                eapply reach_heap; eauto 2.\n            }\n        + invert_high_event_step.\n          invert_event_step.\n          invert_sem_step; rewrite_inj.\n          assert (low_event \u2113 (GetEvent \u2113_x0 i i0 v1)) by eauto 2.\n          contradiction.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8Stop, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8c2', pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n        invert_event_step.\n        assert (~ \u2113_x \u2291 \u2113).\n        {\n          intro.\n          assert (low_event \u2113 (GetEvent \u2113_x i i0 v)) by eauto 2.\n          contradiction.\n        }\n        invert_sem_step.\n        rewrite_inj.\n        _apply get_bridge_properties in *.\n        super_destruct'; subst.\n        invert_bridge_step_with_steps 0.\n        + invert_low_event_step.\n          invert_event_step; invert_low_event.\n          rewrite_inj.\n          contradiction.\n        + invert_high_event_step.\n          invert_event_step.\n          invert_sem_step.\n          rewrite_inj.\n          clear H31.\n          rewrite_inj.\n          assert (wellformed_aux \u0393 \u03a33' \u27e8GetArr i i0 e, pc2'', s1', w2'', g2'' - 1\u27e9 pc_end) by eauto 2.\n          assert (exists l3, right \u03a6 l2 = Some l3 /\\ memory_lookup s1 i0 = Some (ValLoc l3)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            assert (expr_has_type \u0393 (Var i0) (SecType (Array (SecType \u03c3 \u03b5) \u21132) \u03b5_y)) by eauto 2.\n            destruct \u03b5_y as [\u2113_y \u03b9_y].\n            assert (\u2113_y \u2291 \u2113_x0).\n            {\n              destruct \u03b5.\n              destruct_prod_join_flowsto.\n              eauto 2.\n            }\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            assert (eval s1' (Var i0) = Some (ValLoc l2)) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H3 H29 H22 H5 H68).\n            super_destruct'; subst.\n            invert_val_taint_eq.\n            - destruct \u03a6; eexists; splits*.\n            - assert_wf_type.\n              invert_wf_type.\n          }\n          super_destruct'; subst.\n          assert (eval s1 e = Some (ValNum n1)).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            invert_lifted.\n            rewrite_inj.\n            destruct \u03b5_idx as [\u2113_idx \u03b9_idx].\n            assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n            remember_simple (eval_taint_eq_possibilistic H8 H31 H26 H3 H51).\n            super_destruct'; subst.\n            invert_val_taint_eq; eauto 2.\n            assert_wf_type.\n            invert_wf_type.\n            destruct_prod_join_flowsto.\n            assert (LH.flowsto \u2022 \u2218) as H' by eauto 2.\n            inverts H'.\n          }\n          invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n          invert_lifted; rewrite_inj.\n          assert (exists u \u2113 \u03bc, heap_lookup l3 w1 = Some (\u2113, \u03bc) /\\ lookup \u03bc n1 = Some u /\\ val_taint_eq \u03a6 (SecType \u03c3 (\u2113_x0, \u03b90)) u v1 /\\ length_of l3 w1 = Some length0).\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H21).\n            unfold taint_eq; super_destruct'; subst.\n            assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans.\n              - eapply gc_trans_preserves_taint_eq_reach; eauto 2.\n              - eauto 2.\n              - repeat invert_wf_aux; eauto 2.\n              - eauto 2.\n              - eapply low_gc_trans_preserves_taint_eq_heap; eauto 2.\n              - eapply low_gc_trans_preserves_taint_eq_heap_domain_eq; eauto 2.\n            }\n            assert (left \u03a6 l3 = Some l2) by (destruct \u03a6; eauto 2).\n            assert (high \u2113 s1 w1 l3) by eauto 3.\n            assert (exists \u2113 \u03bc, heap_lookup l3 w1 = Some (\u2113, \u03bc)).\n            {\n              repeat invert_wf_aux.\n              destruct_high; eauto 3.\n            }\n            assert (high \u2113 s1' w2'' l2) by eauto 3.\n            super_destruct'; subst.\n            assert (\u03a33' l2 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n            assert (\u03a32 l3 = Some (SecType \u03c3 \u03b5)) by (repeat invert_wf_aux; eauto 2).\n            remember_simple (H27 l3 l2 _ _ _ _ _ H28 H34 H48 H40 H56 H58 H49).\n            super_destruct'; subst.\n            assert (exists v1, lookup \u03bc1 n1 = Some v1) by firstorder 2.\n            super_destruct'; subst.\n            exists v2.\n            exists \u21131 \u03bc1.\n            assert (val_taint_eq \u03a6 (SecType \u03c3 \u03b5) v2 v1) by eauto 4.\n            splits*.\n            - destruct \u03b5, \u03b5_y; destruct_prod_join_flowsto.\n              eapply val_taint_eq_mon; eauto 2.\n            - congruence.\n          }\n          super_destruct'; subst.\n          exists (GetEvent \u2113_x0 i i0 u) 0.\n          \n          remember_simple (filter_bijection\n                             (low \u2113 \u0393 \u03a31' (m1 [i \u2192 v0]) h2)\n                             (low_dec \u2113 \u0393 \u03a31' (m1 [i \u2192 v0]) h2) \u03c6).\n          super_destruct'; subst.\n          exists \u03c8.\n          remember_simple (filter_bijection\n                             (high \u2113 (extend_memory i u s1) w1)\n                             (high_dec \u2113 (extend_memory i u s1)\n                                        w1) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8.\n          exists (extend_memory i u s1).\n          exists w1 \u03a32.\n\n          assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 v0]) h2\n                               (s1 [i \u2192 u]) w1 \u0393 \u03a31' \u03a32).\n          {\n            repeat destruct_prod_join_flowsto.\n            repeat invert_wf_aux.\n            eapply state_low_eq_extend_memory; eauto 2.\n            - destruct \u03c3.\n              + assert (exists n, v0 = ValNum n) by eauto 2.\n                assert (exists n, u = ValNum n) by eauto.\n                super_destruct; subst; eauto 2.\n              + assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst; eauto 2.\n            - intros; subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              contradiction.\n            - intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              contradiction.\n            - intros; subst; eauto 3.\n            - intros; subst; eauto 3.\n            - eapply wf_tenv_extend.\n              + eauto.\n              + eauto.\n              + intros; subst; eauto.\n              + intros; subst; eauto.\n          }\n\n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 v0]) h2).\n          {\n            repeat invert_wf_aux.\n            eapply wf_bijection_extend_mem1; intros; subst; eauto 3.\n            - subst; eauto 2.\n            - subst.\n              assert (exists loc, v0 = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              contradiction.\n          }\n          \n          assert (wf_taint_bijection \u2113 \u03a8 (s1 [i \u2192 u]) w1).\n          {\n            rewrite_inj.\n            eapply wf_taint_bijection_extend_mem1; eauto 2.\n            intros; subst.\n            eapply reach_heap with (loc0 := l3); eauto 2.\n          }\n\n          assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop\n                           (s1 [i \u2192 u]) w1\n                           (s1' [i \u2192 v1]) w2'').\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H21).\n            repeat invert_wf_aux.\n            assert (taint_eq_heap \u2113 (bijection_compose \u03a6 (identity_bijection loc)) \u03a32 \u03a33' s1 w1 s1' w2'').\n            {\n              unfold taint_eq in *; super_destruct'.\n              eapply taint_eq_heap_trans; eauto 2.\n            }\n            splits~.\n            - eapply taint_eq_mem_extend; eauto 2.\n            - eapply taint_eq_reach_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + rewrite <- (compose_id_right \u03a6); eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + intros; subst.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n            - eapply taint_eq_heap_extend_mem; eauto 2.\n              + intros; subst; eauto.\n              + intros; subst; eauto.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + rewrite -> (compose_id_right \u03a6).\n                eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite -> (compose_id_right \u03a6).\n                eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite -> (compose_id_right \u03a6); eauto 2.\n            - unfold taint_eq in *; super_destruct'.\n              eapply taint_eq_heap_size_trans; eauto 2.\n            - eapply taint_eq_heap_domain_eq_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans; eauto 2.\n              + eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              + intros; subst.\n                assert (exists loc, u = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst; eauto 3.\n              + intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto.\n                super_destruct; subst.\n                exists loc.\n                splits~.\n                rewrite_inj.\n                eapply reach_heap; eauto 2.\n              + intros; subst; eauto 3.\n            - eapply taint_eq_stenv_extend_mem; eauto 2.\n          }\n          \n          splits~.\n          * eapply bridge_stop_num.\n            { splits~.\n              - constructor.\n                constructors; eauto 2.\n              - intro; invert_low_event; contradiction.\n            }\n            { reflexivity. }\n          * unfolds.\n            splits.\n            { splits; intro; invert_low_event; contradiction. }\n            { intro; invert_low_event; contradiction. }\n          * eapply TaintEqEventGet; eauto 2.\n            invert_val_taint_eq; eauto 2.\n            assert (high \u2113 (s1 [i \u2192 ValLoc loc])\n                         w1 loc) by eauto 3.\n            assert (left \u03a8 loc = Some loc') by eauto 2.\n            eauto 2.\n          * splits~.\n            {\n              - repeat invert_wf_aux.\n                repeat destruct_prod_join_flowsto.\n                eapply wf_bijection_extend_mem2; try solve[intros; subst; eauto 3].\n                {\n                  destruct \u03c3.\n                  - assert (exists n, v0 = ValNum n) by eauto 2.\n                    assert (exists n, u = ValNum n) by eauto.\n                    super_destruct'; subst; eauto 2.\n                  - assert (exists loc, v0 = ValLoc loc) by eauto 2.\n                    assert (exists loc, u = ValLoc loc) by eauto.\n                    super_destruct'; subst; eauto 2.\n                }\n            {\n              intros; subst.\n              assert (exists loc, u = ValLoc loc) by eauto 3.\n              super_destruct; subst.\n              exists loc.\n              splits~.\n              intros.\n              contradiction. }\n            }\n            {\n              remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H21).\n              repeat invert_wf_aux.\n              eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_reach_trans.\n                + eauto.\n                + eapply gc_trans_preserves_taint_eq_reach; eauto.\n              - rewrite <- (compose_id_right \u03a6).\n                unfold taint_eq in *; super_destruct'.\n                eapply taint_eq_heap_trans.\n                + eapply H5.\n                + eauto 2.\n                + eauto 2.\n                + eauto 2.\n                + eauto 2.\n                + eauto 2.\n              - rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              - unfold taint_eq in *; super_destruct'; eauto 2.\n              - idtac.\n                unfold taint_eq in *; super_destruct'; eauto 2.\n              - eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n              - intros; subst.\n                eauto.\n              - intros; subst.\n                eauto.\n              - intros; subst.\n                assert (exists loc, v1 = ValLoc loc) by eauto 3.\n                super_destruct'; subst.\n                exists loc.\n                splits~.\n                eapply reach_heap; eauto 2.\n            }\n    }\n    (* Time *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        _apply time_bridge_properties in *.\n        super_destruct'; subst.\n        assert (wellformed_aux \u0393 \u03a33 \u27e8TIME (i), pc, s1', h', g2'' - 1\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8Stop, pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        invert_event_step; invert_low_event.\n        invert_bridge_step.\n        + invert_low_event_step.\n          invert_event_step; invert_low_event.\n          do 2 invert_sem_step; rewrite_inj.\n          clear H29.\n          exists (TimeEvent \u21131 i t).\n          exists 0.\n          remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' (extend_memory i (ValNum t) m1) h2) (low_dec \u2113 \u0393 \u03a31' (extend_memory i (ValNum t) m1) h2) \u03c6).\n          super_destruct'; subst.\n          exists \u03c8.\n\n          remember_simple (filter_bijection\n                             (high \u2113 (extend_memory i (ValNum t) s1) w1)\n                             (high_dec \u2113 (extend_memory i (ValNum t) s1) w1) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8.\n          exists (extend_memory i (ValNum t) s1).\n          exists w1.\n          exists \u03a32.\n\n          assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 ValNum t]) h2\n                               (s1 [i \u2192 ValNum t]) w1 \u0393 \u03a31' \u03a32).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            eapply state_low_eq_extend_memory; eauto 2.\n            - intros; discriminate.\n            - intros; discriminate.\n            - eapply wf_tenv_extend; eauto 2.\n              intros; discriminate.\n          }\n\n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 ValNum t]) h2).\n          {\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.\n            eapply wf_bijection_extend_mem1; eauto 2.\n            intros; discriminate.\n          }\n\n          assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop\n                           (s1 [i \u2192 ValNum t]) w1\n                           (s1' [i \u2192 ValNum (S (g2'' - 1) - 1)]) w2'').\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            unfold taint_eq in *; super_destruct'.\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd;\n              rewrite_inj.\n            assert (taint_eq_reach \u03a6 s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            }\n            assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans with (h' := w1'); eauto 2.\n            }\n            assert (wf_taint_bijection \u2113 (inverse \u03a6) s1' w2'').\n            {\n              eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n            }\n            splits~.\n            - eapply taint_eq_mem_extend; eauto 2.\n            - eapply taint_eq_reach_extend_mem; eauto 2.\n              + eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_heap_extend_mem; eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_heap_size_trans; eauto 2.\n            - eapply taint_eq_heap_domain_eq_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_stenv_extend_mem; eauto 2.\n          }\n\n          assert (wf_taint_bijection \u2113 \u03a8 (s1 [i \u2192 ValNum t]) w1).\n          {\n            eapply wf_taint_bijection_extend_mem1; eauto 2.\n            intros; discriminate.\n          }\n          \n          splits~.\n          * constructor.\n            splits~.\n            constructor.\n            eapply event_sem_step_time; eauto 2.\n          * splits*.\n          * repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.\n            eapply TaintEqEventTime; eauto 2.\n          * splits~.\n            {\n              repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n              rewrite_inj.\n              eapply wf_bijection_extend_mem2; eauto 2.\n              intros; discriminate.\n            }\n            {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.            \n            unfold taint_eq in *; super_destruct'.\n            eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n            { rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans.\n              + eauto.\n              + eapply gc_trans_preserves_taint_eq_reach; eauto. }\n              { rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2. }\n              { rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2. }\n              { eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end);\n                  eauto 2. }\n              { intros; discriminate. }\n            }\n        + invert_high_event_step.\n          invert_event_step.\n          do 2 invert_sem_step; rewrite_inj.\n          assert (low_event \u2113 (TimeEvent \u21131 i (g2'' - 1))).\n          {\n            constructor.\n            eauto 2.\n          }\n          contradiction.\n      - unfold is_stop_config, cmd_of in *; subst.\n        invert_high_event_step.\n        _apply time_bridge_properties in *.\n        super_destruct'; subst.\n        assert (wellformed_aux \u0393 \u03a33 \u27e8TIME (i), pc, s1', h', g2'' - 1\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33' \u27e8Stop, pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a31' \u27e8Stop, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n        invert_event_step.\n        invert_bridge_step.\n        + invert_low_event_step.\n          invert_event_step.\n          rewrite_inj.\n          invert_low_event.\n          assert (low_event \u2113 (TimeEvent \u21131 i t)) by eauto 2.\n          contradiction.\n        + invert_high_event_step.\n          invert_event_step.\n          do 2 invert_sem_step; rewrite_inj.\n          clear H30.\n          assert (~ \u21131 \u2291 \u2113).\n          {\n            intro.\n            assert (low_event \u2113 (TimeEvent \u21131 i t)) by eauto 2.\n            contradiction.\n          }\n          exists (TimeEvent \u21131 i t).\n          exists 0.\n          remember_simple (filter_bijection (low \u2113 \u0393 \u03a31' (extend_memory i (ValNum t) m1) h2) (low_dec \u2113 \u0393 \u03a31' (extend_memory i (ValNum t) m1) h2) \u03c6).\n          super_destruct'; subst.\n          exists \u03c8.\n\n          remember_simple (filter_bijection\n                             (high \u2113 (extend_memory i (ValNum t) s1) w1)\n                             (high_dec \u2113 (extend_memory i (ValNum t) s1) w1) \u03a6).\n          super_destruct'; subst.\n          rename \u03c80 into \u03a8.\n          exists \u03a8.\n          exists (extend_memory i (ValNum t) s1).\n          exists w1.\n          exists \u03a32.\n\n          assert (state_low_eq \u2113 \u03c8 (m1 [i \u2192 ValNum t]) h2\n                               (s1 [i \u2192 ValNum t]) w1 \u0393 \u03a31' \u03a32).\n          {\n            repeat invert_wf_aux.\n            repeat specialize_gen.\n            invert_wt_cmd.\n            rewrite_inj.\n            eapply state_low_eq_extend_memory; eauto 2.\n            - intros; discriminate.\n            - intros; discriminate.\n            - eapply wf_tenv_extend; eauto 2.\n              intros; discriminate.\n          }\n\n          assert (wf_bijection \u2113 \u03c8 \u0393 \u03a31' (m1 [i \u2192 ValNum t]) h2).\n          {\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.\n            eapply wf_bijection_extend_mem1; eauto 2.\n            intros; discriminate.\n          }\n\n          assert (taint_eq \u2113 \u03a8 \u0393 \u03a32 \u03a33' Stop Stop\n                           (s1 [i \u2192 ValNum t]) w1\n                           (s1' [i \u2192 ValNum (S (g2'' - 1) - 1)])w2'').\n          {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            unfold taint_eq in *; super_destruct'.\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd;\n              rewrite_inj.\n            assert (taint_eq_reach \u03a6 s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans; eauto 2.\n            }\n            assert (taint_eq_heap \u2113 \u03a6 \u03a32 \u03a33' s1 w1 s1' w2'').\n            {\n              rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_heap_trans with (h' := w1'); eauto 2.\n            }\n            assert (wf_taint_bijection \u2113 (inverse \u03a6) s1' w2'').\n            {\n              eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end); eauto 2.\n            }\n            splits~.\n            - eapply taint_eq_mem_extend; eauto 2.\n            - eapply taint_eq_reach_extend_mem; eauto 2.\n              + eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_heap_extend_mem; eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_heap_size_trans; eauto 2.\n            - eapply taint_eq_heap_domain_eq_extend_mem; eauto 2.\n              + rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2.\n              + intros; discriminate.\n              + intros; discriminate.\n            - eapply taint_eq_stenv_extend_mem; eauto 2.\n          }\n\n          assert (wf_taint_bijection \u2113 \u03a8 (s1 [i \u2192 ValNum t]) w1).\n          {\n            eapply wf_taint_bijection_extend_mem1; eauto 2.\n            intros; discriminate.\n          }\n          \n          splits~.\n          * eapply bridge_stop_num; eauto 2.\n            splits*.\n          * splits*.\n          * repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.\n            eapply TaintEqEventTime; eauto 2.\n          * splits~.\n            {\n              repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n              rewrite_inj.\n              eapply wf_bijection_extend_mem2; eauto 2.\n              intros; discriminate.\n            }\n            {\n            remember_simple (low_gc_trans_preserves_taint_eq H5 H7 H10).\n            repeat invert_wf_aux; repeat specialize_gen; invert_wt_cmd.\n            rewrite_inj.            \n            unfold taint_eq in *; super_destruct'.\n            eapply wf_taint_bijection_extend_mem2 with (m := s1) (h := w1) (\u03a6 := \u03a6); eauto 2.\n            { rewrite <- (compose_id_right \u03a6).\n              eapply taint_eq_reach_trans.\n              + eauto.\n              + eapply gc_trans_preserves_taint_eq_reach; eauto. }\n              { rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_trans; eauto 2. }\n              { rewrite <- (compose_id_right \u03a6).\n                eapply taint_eq_heap_domain_eq_trans; eauto 2. }\n              { eapply low_gc_trans_preserves_wf_taint_bijection with (pc := pc_end);\n                  eauto 2. }\n              { intros; discriminate. }\n            }\n    }\n    (* TimeOut *)\n    {\n      invert_bridge_step_with_steps 0.\n      - invert_low_event_step.\n        invert_event_step; try solve[invert_low_event].\n      - invert_high_event_step.\n        unfold is_stop_config, cmd_of in *; subst.\n        invert_event_step.\n    }\n  }\n  (* Inductive case *)\n  {\n    unfolds.\n    intros.\n    unfold ni_bridge.\n    revert m1 m2 s1 s1' s2'' H0 H1 H2 H3 H4 H5 H6 H7 H9 H10 H11.\n    revert h1 h2 w1 w1' w2''.\n    revert \u03a31 \u03a32 \u03a33 \u03a31' \u03a33'.\n    revert t t' t2 g2'' ev1 ev2.\n    revert pc_end.\n    revert n n2 \u03c6 \u03a6 H.\n    revert c' c2 c2' H12 H13.\n    revert pc pc1' pc2'' H8.\n\n    induction c; intros; subst.\n    (* Skip *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8Skip, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred Skip Skip pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8Skip, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8Skip, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8Skip, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 Skip Skip m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' Skip Skip m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' Skip Skip m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* Stop *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_high_event_step.\n      invert_event_step.\n      exfalso; eauto 2.\n    }\n    (* Assign *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8i ::= e, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred (i ::= e) (i ::= e) pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8i ::= e, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8i ::= e, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8i ::= e, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 (i ::= e) (i ::= e) m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (i ::= e) (i ::= e) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (i ::= e) (i ::= e) m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* If *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      remember_simple (if_bridge_properties H4 H10).\n      remember_simple (if_bridge_properties H6 H11).\n      super_destruct; subst.\n      - replace (S n - 1) with n in * by omega.\n        assert (wellformed_aux \u0393 \u03a31 \u27e8c1, pc, m1, h1, S t\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33 \u27e8c1', pc, s1', w1', S t'\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a32 \u27e8c1, pc, s1, w1, S t\u27e9 pc_end) by eauto 2.\n        assert (n <= n) by omega.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1' s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c8 \u03a8 s2' w2'; exists \u03a32'.\n        splits*.\n        eapply bridge_trans_num.\n        + splits*.\n          constructor.\n          eapply event_sem_step_if; eauto 2.\n          eapply step_if_true; eauto 2.\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          rewrite_inj.\n          invert_state_low_eq.\n          remember_simple (eval_taint_eq_possibilistic H29 H49 H50 H36 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        + intro; unfold is_stop_config, cmd_of in *; subst.\n          invert_bridge_step.\n          * invert_low_event_step.\n            invert_event_step; invert_low_event.\n          * invert_high_event_step.\n            invert_event_step; eauto 2.\n          * invert_high_event_step.\n            invert_event_step; exfalso; eauto 2.\n        + intro; unfold is_timeout_config, cmd_of in *; subst.\n          invert_bridge_step.\n          * invert_low_event_step.\n            invert_event_step; invert_low_event.\n          * invert_high_event_step.\n            invert_event_step; eauto 2.\n          * invert_high_event_step.\n            invert_event_step; exfalso; eauto 2.\n        + eauto 2.\n      - repeat invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        rewrite_inj.\n        invert_state_low_eq.\n        assert (eval s1 e = Some (ValNum p)).\n        {\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          remember_simple (eval_taint_eq_possibilistic H28 H33 H32 H7 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        }\n        assert (val_low_eq \u2113 (SecType Int (\u21130, \u2218)) (ValNum 0) (ValNum p) \u03c6) by eauto 2.\n        invert_val_low_eq.\n        + assert (\u21130 \u2291 \u2113) by eauto 2.\n          contradiction.\n        + congruence.\n      - repeat invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        rewrite_inj.\n        invert_state_low_eq.\n        assert (eval s1 e = Some (ValNum 0)).\n        {\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          remember_simple (eval_taint_eq_possibilistic H28 H33 H32 H7 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        }\n        assert (val_low_eq \u2113 (SecType Int (\u21130, \u2218)) (ValNum p) (ValNum 0) \u03c6) by eauto 2.\n        invert_val_low_eq.\n        + assert (\u21130 \u2291 \u2113) by eauto 2.\n          contradiction.\n        + congruence.\n      - replace (S n - 1) with n in * by omega.\n        assert (wellformed_aux \u0393 \u03a31 \u27e8c2, pc, m1, h1, S t\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a33 \u27e8c2'0, pc, s1', w1', S t'\u27e9 pc_end) by eauto 2.\n        assert (wellformed_aux \u0393 \u03a32 \u27e8c2, pc, s1, w1, S t\u27e9 pc_end) by eauto 2.\n        assert (n <= n) by omega.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c2 c2'0 s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        idtac.\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c8 \u03a8 s2' w2'; exists \u03a32'.\n        splits*.\n        eapply bridge_trans_num.\n        + splits*.\n          constructor.\n          eapply event_sem_step_if; eauto 2.\n          eapply step_if_false; eauto 2.\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          rewrite_inj.\n          invert_state_low_eq.\n          remember_simple (eval_taint_eq_possibilistic H27 H47 H48 H34 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        + intro; unfold is_stop_config, cmd_of in *; subst.\n          invert_bridge_step.\n          * invert_low_event_step.\n            invert_event_step; invert_low_event.\n          * invert_high_event_step.\n            invert_event_step; eauto 2.\n          * invert_high_event_step.\n            invert_event_step; exfalso; eauto 2.\n        + intro; unfold is_timeout_config, cmd_of in *; subst.\n          invert_bridge_step.\n          * invert_low_event_step.\n            invert_event_step; invert_low_event.\n          * invert_high_event_step.\n            invert_event_step; eauto 2.\n          * invert_high_event_step.\n            invert_event_step; exfalso; eauto 2.\n        + eauto 2.\n    }\n    (* While *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      remember_simple (while_bridge_properties H10).\n      remember_simple (while_bridge_properties H11).\n      super_destruct; subst.\n      - construct_many_gc_run.\n        super_destruct'; subst.\n        exists EmptyEvent (S n) \u03c8 \u03a6 m2' h2'; exists \u03a32'.\n        splits.\n        + assert (\u27e8WHILE e DO c END, pc2'', m2', h2', t''0\u27e9\n                    \u21d2 [EmptyEvent, \u0393, \u03a32', \u03a32']\n                  \u27e8Stop, pc2'', m2', h2', S t''0\u27e9).\n          {\n            constructor.\n            constructor.\n            eapply step_while_false; eauto 2.\n            assert (eval s1 e = Some (ValNum 0)).\n            {\n              repeat invert_wf_aux.\n              repeat specialize_gen.\n              invert_wt_cmd.\n              assert (taint_eq_mem (inverse \u03a6) \u0393 s2'' s1) by eauto 2.\n              remember_simple (eval_taint_eq_possibilistic H6 H32 H31 H4 H20).\n              super_destruct'; subst.\n              invert_val_taint_eq.\n              eauto.\n            }\n            eapply gc_trans_preserves_eval2; eauto 2.\n          }\n          eapply gc_run_and_stop_implies_bridge; eauto 2.\n        + eauto 2.\n        + eauto 2.\n        + eauto 2.\n        + splits*.\n        + eauto 2.\n        + eauto 2.\n        + splits.\n          * eauto 2.\n          * eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n          * eapply low_gc_trans_preserves_wf_taint_bijection; eauto 2.\n          * remember_simple (low_gc_trans_preserves_taint_eq H5 H8 H21).\n            remember_simple (low_gc_trans_preserves_taint_eq H6 H8 H26).\n            rewrite <- inverse_identity_is_identity in H22.\n            eapply taint_eq_symmetry in H22.\n            rewrite <- inverse_is_involutive in H22.\n            assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 Stop Stop m2' h2' s2'' w1').\n            {\n              rewrite <- (compose_id_left \u03a6).\n              eapply taint_eq_trans with (m' := s1) (h' := w1).\n              - repeat invert_wf_aux; eauto 2.\n              - unfold taint_eq in *; super_destruct'; splits*.\n              - unfold taint_eq in *; super_destruct'; splits*.\n            }\n            \n            rewrite <- (compose_id_right \u03a6).\n            eapply taint_eq_trans with (m' := s2'') (h' := w1').\n            { repeat invert_wf_aux; eauto 2. }\n            { eauto. }\n            { unfold taint_eq in *; super_destruct'; splits*. }\n      - repeat invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        assert (eval s1 e = Some (ValNum 0)).\n        {\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s2'' s1) by eauto 2.\n          remember_simple (eval_taint_eq_possibilistic H6 H32 H27 H4 H20).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        }\n        invert_state_low_eq.\n        assert (val_low_eq \u2113 (SecType Int (\u21130, \u2218)) (ValNum k) (ValNum 0) \u03c6) by eauto 2.\n        invert_val_low_eq.\n        + assert (\u21130 \u2291 \u2113) by eauto 2.\n          contradiction.\n        + congruence.\n      - repeat invert_wf_aux.\n        repeat specialize_gen.\n        invert_wt_cmd.\n        assert (eval s1 e = Some (ValNum k)).\n        {\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          remember_simple (eval_taint_eq_possibilistic H6 H30 H28 H4 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        }\n        invert_state_low_eq.\n        assert (val_low_eq \u2113 (SecType Int (\u21130, \u2218)) (ValNum 0) (ValNum k) \u03c6) by eauto 2.\n        invert_val_low_eq.\n        + assert (\u21130 \u2291 \u2113) by eauto 2.\n          contradiction.\n        + congruence.\n      - replace (S n - 1) with n in * by omega.\n        assert (wellformed_aux \u0393 \u03a31 \u27e8c ;; WHILE e DO c END, pc, m1, h1, S t \u27e9 pc_end).\n        {\n          repeat invert_wf_aux; constructor; eauto 2.\n          intros.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          constructors; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8c'0;; WHILE e DO c'0 END, pc, s1', w1', S t'\u27e9 pc_end).\n        {\n          repeat invert_wf_aux; constructor; eauto 2.\n          intros.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          constructors; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32 \u27e8c ;; WHILE e DO c END, pc, s1, w1, S t\u27e9 pc_end).\n        {\n          repeat invert_wf_aux; constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 (c;; WHILE e DO c END) (c'0;; WHILE e DO c'0 END) s1 w1 s1' w1').\n        {\n          unfolds.\n          splits*.\n        }\n        assert (n <= n) by omega.\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c8 \u03a8 s2' w2'; exists \u03a32'.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits*.\n          constructor.\n          eapply event_sem_step_while; eauto 2.\n          eapply step_while_true; eauto 2.\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          assert (taint_eq_mem (inverse \u03a6) \u0393 s1' s1) by eauto 2.\n          remember_simple (eval_taint_eq_possibilistic H6 H47 H44 H4 H21).\n          super_destruct'; subst.\n          invert_val_taint_eq.\n          eauto.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* Sequential composition *)\n    {\n      invert_taint_eq; invert_taint_eq_cmd.\n      remember_simple (about_seq_bridge_step H4 H10).\n      remember_simple (about_seq_bridge_step H6 H11).\n      super_destruct; subst.\n      - assert (exists pc', wellformed_aux \u0393 \u03a31 \u27e8c1, pc, m1, h1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a32 \u27e8c1, pc, s1, w1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a33 \u27e8c1', pc, s1', w1', t'\u27e9 pc') by eauto 2.\n        super_destruct'; subst.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1' s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        assert (c1 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n        assert (c1 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc'1 = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eauto 2.\n        }\n        subst.\n        assert (c1' <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n\n        assert (c1' <> TIMEOUT).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc' = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H22 H48).\n          eauto 2.\n        }\n        subst.\n        assert (c1'1 <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2 \u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (c1'0 <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          assert (wellformed_aux \u0393 \u03a33' \u27e8TIMEOUT;; c2'0, pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        remember_simple (IHc1 _ _ _ H8 _ _ _ H37 H38 _ _ _ _ H\n                              _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                              H0 H1 H2 H3 H29 H30 H31 H7 H32 H9 H20).\n        super_destruct'; subst.\n        exists ev1' n1' \u03c8 \u03a8 s2' w2'; exists \u03a32'.\n        splits; eauto 2.\n        + destruct (eq_cmd_dec c1'1 Stop).\n          * subst.\n            specialize (H27 eq_refl).\n            subst.\n            eapply bridge_step_seq_low_event_in_left_stop.\n            { eauto. }\n            { eauto. }\n            { intro; subst.\n              invert_wf_aux.\n              repeat specialize_gen.\n              invert_wt_cmd.\n              invert_wt_stop. }\n          * specialize (H26 n0).\n            subst.\n            eapply bridge_step_seq_low_event_in_left_nonstop.\n            { eauto. }\n            { eauto 2. }\n            { eauto 2. }\n            { intro; subst.\n              assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2\u27e9 pc_end).\n              {\n                eauto 2.\n              }\n              invert_wf_aux.\n              repeat specialize_gen.\n              invert_wt_cmd.\n              invert_wt_timeout. }\n        + splits~.\n          unfold taint_eq in *; super_destruct'.\n          splits~.\n          destruct (eq_cmd_dec c1'1 Stop); subst.\n          * assert (c0 = c2) by eauto 2.\n            subst.\n            invert_taint_eq_cmd.\n            assert (c2' = c2'0) by eauto 2.\n            subst.\n            eauto 2.\n          * assert (c0 = (c1'1;; c2)) by eauto 2.\n            subst.\n            assert (c1'0 <> Stop).\n            {\n              intro; subst.\n              invert_taint_eq_cmd; eauto 2.\n            }\n            repeat specialize_gen.\n            subst.\n            eauto 2. \n      - assert (exists pc', wellformed_aux \u0393 \u03a31 \u27e8c1, pc, m1, h1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a32 \u27e8c1, pc, s1, w1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a33 \u27e8c1', pc, s1', w1', t'\u27e9 pc') by eauto 2.\n        super_destruct'; subst.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1' s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        assert (c1 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n        assert (c1 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc'1 = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eauto 2.\n        }\n        subst.\n        assert (c1' <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n\n        assert (c1' <> TIMEOUT).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc' = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H22 H61).\n          eauto 2.\n        }\n        subst.\n        assert (Stop <> TimeOut) by congruence.\n        assert (c1'0 <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          \n          assert (wellformed_aux \u0393 \u03a33' \u27e8 TIMEOUT;; c2'0, pc2'', s2'', w2'', g2''\u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        assert (k <= n) by omega.\n        apply_IH.\n        super_destruct'.\n        assert (low_event \u2113 ev1') by eauto 2.\n        assert (low_event \u2113 ev').\n        {\n          unfold event_low_eq in *.\n          super_destruct'.\n          firstorder 2.\n        }\n        contradiction.\n      - assert (exists pc', wellformed_aux \u0393 \u03a31 \u27e8c1, pc, m1, h1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a32 \u27e8c1, pc, s1, w1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a33 \u27e8c1', pc, s1', w1', t'\u27e9 pc') by eauto 2.\n        super_destruct'; subst.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1' s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        assert (c1 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n        assert (c1 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc'1 = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eauto 2.\n        }\n        subst.\n        assert (c1' <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n\n        assert (c1' <> TIMEOUT).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc' = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H22 H61).\n          eauto 2.\n        }\n        subst.\n        assert (Stop <> TimeOut) by congruence.\n        assert (c1'0 <> TimeOut).\n        {\n          intro; subst.\n          repeat specialize_gen.\n          subst.\n          \n          assert (wellformed_aux \u0393 \u03a31' \u27e8TIMEOUT;; c2, pc1', m2, h2, t2\u27e9 pc_end) by eauto 2.\n          invert_wf_aux.\n          repeat specialize_gen.\n          invert_wt_cmd.\n          invert_wt_timeout.\n        }\n        remember_simple (IHc1 _ _ _ H8 _ _ _ H39 H38 _ _ _ _ H\n                              _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                              H0 H1 H2 H3 H30 H31 H32 H7 H33 H9 H25).\n        super_destruct'; subst.\n        assert (low_event \u2113 ev1') by eauto 2.\n        assert (low_event \u2113 ev').\n        {\n          unfold event_low_eq in *.\n          super_destruct'.\n          eauto 2.\n        }\n        contradiction.\n      - replace (S n - k0 - 1) with (n - k0) in * by omega.\n        assert (exists pc', wellformed_aux \u0393 \u03a31 \u27e8c1, pc, m1, h1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a32 \u27e8c1, pc, s1, w1, t\u27e9 pc') by eauto 2.\n        assert (exists pc', wellformed_aux \u0393 \u03a33 \u27e8c1', pc, s1', w1', t'\u27e9 pc') by eauto 2.\n        super_destruct'; subst.\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32 \u03a33 c1 c1' s1 w1 s1' w1').\n        {\n          unfolds; splits*.\n        }\n        assert (c1 <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n        assert (c1 <> TimeOut).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc'1 = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          eauto 2.\n        }\n        subst.\n        assert (c1' <> Stop).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_stop.\n        }\n\n        assert (c1' <> TIMEOUT).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          intro; subst.\n          invert_wt_cmd; invert_wt_timeout.\n        }\n        assert (pc' = pc'0).\n        {\n          repeat invert_wf_aux.\n          repeat specialize_gen.\n          remember_simple (taint_eq_cmd_implies_same_type H22 H50).\n          eauto 2.\n        }\n        subst.\n        assert (Stop <> TimeOut) by congruence.\n        assert (Stop <> TimeOut) by congruence.\n        assert (k0 <= n) by omega.\n        apply_IH.\n        super_destruct'.\n        assert (n - k0 <= n) by omega.\n        remember_simple (wf_seq_half_step_implies_wf_bridge_step H4 H29).\n        remember_simple (wf_seq_half_step_implies_wf_bridge_step H5 H42).\n        remember_simple (wf_seq_half_step_implies_wf_bridge_step H6 H25).\n        assert (pc''0 = pc'0).\n        {\n          eauto 2 using wt_aux_soundness_bridge.\n        }\n        subst.\n\n        clear H7.\n        assert (taint_eq \u2113 \u03a8 \u0393 \u03a32' \u03a3' c2 c2'0 s2' w2' m'' h'').\n        {\n          unfold taint_eq in *; super_destruct'; splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1'0 (S (n1' + n1'0)) \u03c80 \u03a80 s2'0 w2'0; exists \u03a32'0.\n        splits; eauto 2.\n        + eapply concat_bridge_step_seq.\n          * eauto 2.\n          * eauto 2.\n          * intro.\n            assert (low_event \u2113 ev') by eauto 2.\n            contradiction.\n          * eauto 2.\n        + splits*.\n    }\n    (* At *)\n    {\n      eauto 2 using ni_bridge_num_at_case.\n    }\n    {\n      eauto 2 using ni_bridge_num_backat_case.\n    }\n    (* New *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8NewArr i l e e0, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred (NewArr i l e e0) (NewArr i l e e0) pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8NewArr i l e e0, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8NewArr i l e e0, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8NewArr i l e e0, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 (NewArr i l e e0) (NewArr i l e e0) m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (NewArr i l e e0) (NewArr i l e e0) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (NewArr i l e e0) (NewArr i l e e0) m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* Set *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8SetArr i e e0, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred (SetArr i e e0) (SetArr i e e0) pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8SetArr i e e0, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8SetArr i e e0, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8SetArr i e e0, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 (SetArr i e e0) (SetArr i e e0) m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (SetArr i e e0) (SetArr i e e0) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (SetArr i e e0) (SetArr i e e0) m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* Get  *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8GetArr i i0 e, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred (GetArr i i0 e) (GetArr i i0 e) pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8GetArr i i0 e, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8GetArr i i0 e, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8GetArr i i0 e, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 (GetArr i i0 e) (GetArr i i0 e) m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (GetArr i i0 e) (GetArr i i0 e) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (GetArr i i0 e) (GetArr i i0 e) m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* Time *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_taint_eq; invert_taint_eq_cmd.\n      invert_high_event_step.\n      invert_event_step.\n      - exfalso; eauto 2.\n      - assert (wellformed_aux \u0393 \u03a3' \u27e8Time i, pc', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          eapply gc_preserves_wf; eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        repeat invert_wf_aux.\n        assert (gc_occurred (Time i) (Time i) pc' pc' m' m'\n                            ([[h1_pc \u228e h1_not_pc, H15] \u228e h3, H9])\n                            ([h1_pc \u228e h1_not_pc, H15]) t (t + \u03b4) \u03a3' \u03a3') as H'.\n        {\n          unfolds.\n          splits*.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n          erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n        }\n        construct_gc_run.\n        super_destruct'; subst.\n        assert (\u03b40 = \u03b4).\n        {\n          unfold gc_occurred_no_ex in H'.\n          super_destruct'; omega.\n        }\n        subst.\n        clear H'.\n        unfold gc_occurred_no_ex in *; super_destruct'; subst.\n        assert (n <= n) by omega.\n        assert (wf_taint_bijection \u2113 \u03a6 m2' ([h2_pc \u228e h2_not_pc, H2'])).\n        {\n          eapply low_gc_preserves_wf_taint_bijection; eauto 2.\n          unfolds.\n          splits; reflexivity || eauto 2.\n          do 7 eexists.\n          splits; reflexivity || eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a3' \u27e8Time i, pc2', m', [h1_pc \u228e h1_not_pc, H15], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a32' \u27e8Time i, pc2', m2', [h2_pc \u228e h2_not_pc, H2'], t + \u03b4\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n          eapply lookup_in_bounds_subset; eauto 2.\n        }\n        assert (wellformed_aux \u0393 \u03a33 \u27e8Time i, pc2', s1', w1', t'\u27e9 pc_end).\n        {\n          constructor; eauto 2.\n        }\n        assert (taint_eq \u2113 \u03a6 \u0393 \u03a32' \u03a33 (Time i) (Time i) m2' ([h2_pc \u228e h2_not_pc, H2']) s1' w1').\n        {\n          assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (Time i) (Time i) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1']) m2' ([h2_pc \u228e h2_not_pc, H2'])).\n          {\n            eapply low_gc_preserves_taint_eq; eauto 2.\n            unfolds.\n            splits; reflexivity || eauto 2.\n            do 7 eexists.\n            splits; reflexivity || eauto 2.\n          }\n          rewrite <- (compose_id_left \u03a6).\n          eapply taint_eq_trans\n          with (m' := m2') (h' := ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n          - eauto 2.\n          - assert (taint_eq \u2113 (identity_bijection loc) \u0393 \u03a32' \u03a32' (Time i) (Time i) m2' ([h2_pc \u228e h2_not_pc, H2']) m2' ([[h2_pc \u228e h2_not_pc, H2'] \u228e h2_gc, H1'])).\n            {\n              rewrite <- inverse_identity_is_identity.\n              eapply taint_eq_symmetry; eauto 2.\n            }\n            eauto 2.\n          - unfolds.\n            splits*.\n        }\n        apply_IH.\n        super_destruct'; subst.\n        exists ev1' (S n1') \u03c80 \u03a8 s2' w2'; exists \u03a32'0.\n        splits*.\n        eapply bridge_trans_num.\n        + unfolds.\n          splits.\n          * eapply EventGCStep.\n            eapply step_gc; reflexivity || eauto 2.\n          * intro; invert_low_event.\n        + intro; discriminate.\n        + intro; discriminate.\n        + eauto 2.\n    }\n    (* TimeOut *)\n    {\n      invert_bridge_step_with_steps (S n).\n      invert_high_event_step.\n      exfalso.\n      invert_event_step; eauto 2.\n    }\n\n    Unshelve.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - constructor; eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n    - eauto 2.\n  }\nQed.\nEnd NIBridge.", "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/nibridge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.18672265853576683}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import NoMix.\nRequire Import DelayedSimulation.\nRequire Import DelayedStep.\nRequire Import DelayedAdequacy.\nRequire Import SeqLiftSim.\nRequire Import Sequential.\nRequire Import SequentialBehavior.\nRequire Import SequentialRefinement.\nRequire Import Program.\n\n\nSet Implicit Arguments.\n\n\nSection ADEQUACY.\n  Variable loc_na: Loc.t -> Prop.\n  Variable loc_at: Loc.t -> Prop.\n  Hypothesis LOCDISJOINT: forall loc (NA: loc_na loc) (AT: loc_at loc), False.\n\n  Theorem sequential_adequacy (progs_src progs_tgt: Threads.syntax)\n          (SIM: forall tid,\n              option_rel\n                (fun '(existT _ lang_src prog_src) '(existT _ lang_tgt prog_tgt) =>\n                   exists sim_ret, @sim_seq_all\n                                     _ _ sim_ret\n                                     (lang_src.(Language.init) prog_src)\n                                     (lang_tgt.(Language.init) prog_tgt))\n                (IdentMap.find tid progs_src)\n                (IdentMap.find tid progs_tgt))\n          (NOMIX_SRC:\n             forall tid lang syn\n                    (FIND: IdentMap.find tid progs_src = Some (existT _ lang syn)),\n               nomix loc_na loc_at lang (lang.(Language.init) syn))\n          (NOMIX_TGT:\n             forall tid lang syn\n                    (FIND: IdentMap.find tid progs_tgt = Some (existT _ lang syn)),\n               nomix loc_na loc_at lang (lang.(Language.init) syn))\n    :\n      behaviors\n        Configuration.step\n        (Configuration.init progs_tgt)\n      <2=\n      behaviors\n        Configuration.step\n        (Configuration.init progs_src).\n  Proof.\n    i. eapply DelayedAdequacy.sim_init.\n    { eapply SeqLiftSim.world_messages_le_PreOrder. }\n    { eapply SeqLiftSim.world_messages_le_mon. }\n    { eapply SeqLiftSim.world_messages_le_frame. }\n    { i. specialize (SIM tid). unfold option_rel in *. des_ifs.\n      { rewrite Heq1 in Heq0. dependent destruction Heq0.\n        des. eapply SeqLiftSim.sim_lift_init; eauto.\n      }\n      { clarify. }\n      { clarify. }\n    }\n    { eapply SeqLiftSim.initial_sim_memory_lift. }\n    eapply DConfiguration.delayed_refinement; eauto.\n  Qed.\n\n  Theorem sequential_adequacy_concurrent_context\n          (ctx: Threads.syntax) (tid: Ident.t)\n          (lang_src: language) (prog_src: lang_src.(Language.syntax))\n          (lang_tgt: language) (prog_tgt: lang_tgt.(Language.syntax))\n          (SIM: exists sim_ret, @sim_seq_all\n                                  _ _ sim_ret\n                                  (lang_src.(Language.init) prog_src)\n                                  (lang_tgt.(Language.init) prog_tgt))\n          (NOMIX_SRC: nomix loc_na loc_at _ (lang_src.(Language.init) prog_src))\n          (NOMIX_TGT: nomix loc_na loc_at _ (lang_tgt.(Language.init) prog_tgt))\n          (NOMIX_CTX:\n             forall tid lang syn\n                    (FIND: IdentMap.find tid ctx = Some (existT _ lang syn)),\n               nomix loc_na loc_at lang (lang.(Language.init) syn))\n    :\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ lang_tgt prog_tgt) ctx))\n      <2=\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ lang_src prog_src) ctx)).\n  Proof.\n    eapply sequential_adequacy.\n    { i. rewrite ! IdentMap.gsspec. des_ifs; ss.\n      destruct (IdentMap.find tid0 ctx) as [[lang prog]|]; ss.\n      esplits. eapply sim_seq_all_refl.\n    }\n    { ii. rewrite IdentMap.gsspec in FIND. des_ifs; eauto.\n      dependent destruction H0. auto.\n    }\n    { ii. rewrite IdentMap.gsspec in FIND. des_ifs; eauto.\n      dependent destruction H0. auto.\n    }\n  Qed.\n\n  Theorem sequential_refinement_adequacy_concurrent_context\n          (ctx: Threads.syntax) (tid: Ident.t)\n          (lang_src: language) (prog_src: lang_src.(Language.syntax))\n          (lang_tgt: language) (prog_tgt: lang_tgt.(Language.syntax))\n          (REFINE: SeqBehavior.refine _ _ (lang_tgt.(Language.init) prog_tgt) (lang_src.(Language.init) prog_src))\n          (DETERM: deterministic _ (lang_src.(Language.init) prog_src))\n          (RECEPTIVE: receptive _ (lang_tgt.(Language.init) prog_tgt))\n          (MONOTONE: monotone_read_state lang_src (lang_src.(Language.init) prog_src))\n          (NOMIX_SRC: nomix loc_na loc_at _ (lang_src.(Language.init) prog_src))\n          (NOMIX_TGT: nomix loc_na loc_at _ (lang_tgt.(Language.init) prog_tgt))\n          (NOMIX_CTX:\n             forall tid lang syn\n                    (FIND: IdentMap.find tid ctx = Some (existT _ lang syn)),\n               nomix loc_na loc_at lang (lang.(Language.init) syn))\n    :\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ lang_tgt prog_tgt) ctx))\n      <2=\n      behaviors\n        Configuration.step\n        (Configuration.init (IdentMap.add tid (existT _ lang_src prog_src) ctx)).\n  Proof.\n    eapply sequential_adequacy_concurrent_context; eauto.\n    esplits. eapply refinement_implies_simulation; eauto.\n  Qed.\nEnd ADEQUACY.\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/SequentialAdequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18669733575575997}}
{"text": "Require Import ucos_include.\nRequire Import os_ucos_h.\nRequire Import sep_lemmas_ext.\nRequire Import linv_solver.\nRequire Import taskcreate_pure.\nRequire Import protect.\nLocal Open Scope code_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope int_scope.\n\nTheorem TaskCreateProof:\n  forall  vl p r tid, \n    Some p =\n    BuildPreA' os_api OSTaskCreate taskcreapi vl  OSLInv tid init_lg ->\n    Some r =\n    BuildRetA' os_api OSTaskCreate taskcreapi vl  OSLInv tid init_lg ->\n    exists t d1 d2 s,\n      os_api OSTaskCreate = 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  hoare forward.\n  math simpls.\n  destruct ( Int.ltu ($ OS_LOWEST_PRIO) i); simpl; intro; tryfalse.\n  hoare unfold.\n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply absimp_taskcre_prio_invalid.\n  go.\n  unfold OS_LOWEST_PRIO in *.\n  int auto.\n  \n  hoare forward.\n  hoare forward.\n  hoare unfold.\n  hoare forward prim.\n  hoare normal pre.\n  hoare unfold.\n  assert (Int.unsigned i < 64).\n  clear -H.\n\n  unfold OS_LOWEST_PRIO in *.\n  int auto.\n  destruct H; simpl in H; tryfalse.\n  clear H.\n  assert (   rule_type_val_match OS_TCB \u2217 (nth_val' (Z.to_nat (Int.unsigned i)) v'5) = true).\n  apply symbolic_lemmas.array_type_vallist_match_imp_rule_type_val_match.\n  rewrite H8.\n  clear -H9; mauto.\n  auto.\n\n  hoare forward.\n  math simpls.\n  auto.\n  unfolds in H.\n  destruct ( nth_val' (Z.to_nat (Int.unsigned i)) v'5 ); tryfalse.\n  simpl.\n  intro; tryfalse.\n\n  simpl.\n  destruct a.\n  intro; tryfalse.\n  instantiate (1 := Afalse).\n  Focus 2.\n  (* error path *)\n  hoare forward.\n  hoare unfold.\n  hoare abscsq.\n  apply noabs_oslinv.\n\n  eapply absimp_taskcre_prio_already_exists.\n  go.\n  hoare forward prim.\n  unfold AOSTCBPrioTbl.\n  sep pauto.\n  go.\n  hoare forward.\n\n  (* right path *) \n\n  \n\n  hoare unfold.\n  hoare_assert_pure (   array_type_vallist_match Int8u v'11/\\ length v'11 = \u2218 OS_RDY_TBL_SIZE ) .\n  unfold AOSRdyTblGrp in H13.\n  unfold AOSRdyTbl in H13.\n  sep normal in H13.\n  sep split in H13.\n  auto.\n  hoare_split_pure_all.\n  rename H13 into somehyp.\n  protect somehyp.\n  \n  assert ((nth_val' (Z.to_nat (Int.unsigned i)) v'5) = Vnull).\n  remember (nth_val' (Z.to_nat (Int.unsigned i)) v'5).\n\n  destruct H.\n\n  auto.\n  simpljoin.\n  rewrite H in *.\n  simpl in *.\n  destruct x; simpl in *.\n  tryfalse.\n  clear H10 H11 H12.\n  hoare unfold.\n  unfold AOSTCBList.\n  hoare unfold.\n  hoare forward.\n  math simpls.\n  sep cancel Aie.\n  sep cancel Ais.\n  sep cancel Aisr.\n  sep cancel Acs.\n  sep cancel AOSTCBFreeList.\n  sep cancel Aop.\n  sep cancel AOSRdyTblGrp.\n  sep cancel 9%nat 1%nat.\n  sep cancel 3%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  eauto.\n  eauto.\n\n  go.\n  go.\n  math simpl.\n  clear -H9 l.\n  unfold OS_LOWEST_PRIO in l.\n  int auto.\n  go.\n  apply retpost_tcbinitpost.\n\n  math simpl.\n  clear -H1 H15.\n  change Byte.max_unsigned with 255 in H15.\n  omega.\n\n\n  repeat intro.\n\n  sep normal in H15.\n  sep destruct H15.\n  sep lift 6%nat in H15.\n\n  disj_asrt_destruct H15.\n  sep normal in H15.\n  sep destruct H15.\n  sep eexists.\n  sep cancel p_local.\n  simpl; auto.\n\n  sep normal in H15.\n  sep destruct H15.\n  sep eexists.\n  sep cancel p_local.\n  simpl; auto.\n\n  linv_solver.\n  \n  hoare unfold.\n  hoare lift 6%nat pre.\n  eapply backward_rule1.\n  intro.\n  intros.\n  eapply disj_star_elim_disj in H15.\n  eauto.\n  hoare forward.\n  hoare unfold.\n  inverts H18.\n\n  (* no more tcb *)\n  hoare forward.\n  hoare unfold.\n  false.\n  change (Int.eq ($ OS_NO_MORE_TCB) ($ OS_NO_ERR)) with false in *.\n  simpl in *.\n  apply H18; auto.\n  hoare unfold.\n  \n  hoare abscsq.\n  apply noabs_oslinv.\n\n  eapply absimp_taskcre_no_more_tcb.\n  go.\n  \n  \n  instantiate (1 :=    <|| END Some (V$ OS_NO_MORE_TCB) ||>  **\n                               Aisr empisr **\n                               Aie true **\n                               Ais nil ** Acs nil ** p_local OSLInv tid init_lg **\n                               A_dom_lenv\n                               ((prio, Int8u)\n                                  :: (os_code_defs.pdata, (Void) \u2217)\n                                  :: (task, (Void) \u2217) :: (err, Int8u) :: nil) **\n                               LV err @ Int8u |-> (V$ OS_NO_MORE_TCB)  ** LV prio @ Int8u |-> Vint32 i **\n                               LV os_code_defs.pdata @ (Void) \u2217 |-> x0 ** LV task @ (Void) \u2217 |-> x1\n              ).\n  \n  hoare forward prim.\n  sep cancel tcbdllflag.\n  \n  sep cancel A_dom_lenv.\n  sep pauto.\n  unfold AOSTCBPrioTbl.\n  unfold AOSTCBList.\n  sep pauto.\n  sep cancel 3%nat 1%nat.\n  \n  sep cancel 3%nat 1%nat.\n  sep cancel 2%nat 1%nat.\n  \n  assumption.\n  go.\n  go.\n  go.\n  go.\n  go.\n  go.\n\n  hoare forward.\n  hoare_split_pure_all.\n  false.\n  clear -H18.\n  simpljoin.\n  change (Int.eq ($ OS_NO_MORE_TCB) ($ OS_NO_ERR)) with false in *.\n  simpl in *.\n  apply H; auto.\n\n  (* right path *)\n  hoare forward.\n\n  hoare unfold.\n  inverts H19.\n\n  hoare forward.\n  \n  hoare unfold.\n  Focus 2.\n  hoare unfold.\n  false.\n  clear -H17.\n  change (Int.eq ($ OS_NO_ERR) ($ OS_NO_ERR)) with true in H17.\n  simpl in H17; destruct H17; tryfalse.\n\n  \n  \n\n  hoare abscsq.\n  apply noabs_oslinv.\n  apply absimp_taskcre_succ.\n  go.\n\n  \n  hoare_assert_pure (GoodLInvAsrt OSLInv).\n  unfold p_local in H21.\n  unfold LINV in H21.\n  sep normal in H21.\n  sep split in H21.\n  auto.\n  instantiate (1 :=\n                 EX x, (\n                   POST [OS_SchedPost, nil, x,\n                         logic_code (END Some (V$ NO_ERR)) :: nil, tid] **\n                        LV err @ Int8u |-> (V$ OS_NO_ERR) **\n                        LV prio @ Int8u |-> Vint32 v'42 **\n                        LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n                        LV task @ (Void) \u2217 |-> x1 **\n                        A_dom_lenv\n                        ((prio, Int8u)\n                           :: (os_code_defs.pdata, (Void) \u2217)\n                           :: (task, (Void) \u2217) :: (err, Int8u) :: nil)\n                 )).\n\n\n  hoare_assert_pure(exists new_tcbmod, TcbJoin v'34 (v'42, rdy, Vnull) v'14 new_tcbmod).\n  \n    unfold TcbJoin.\n    eexists.\n    eapply map_join_comm.\n    \n    unfold join; simpl.\n    eapply TcbMod.join_sig_set.\n    auto.\n    intro.\n    eapply (join_in_or H11) in H24.\n    destruct H23.\n    simpljoin.\n    unfolds in H27.\n    inverts H27.\n    destruct H24.\n    gen H23.\n    eapply sometcblist_lemma.\n    instantiate ( 8:= s0).\n    sep cancel 13%nat 1%nat.\n    sep cancel 14%nat 1%nat.\n    eauto.\n    eauto.\n\n    gen H23.\n    eapply sometcblist_lemma.\n    instantiate ( 8:= s0).\n    sep cancel 13%nat 1%nat.\n    sep cancel 16%nat 1%nat.\n    eauto.\n    eapply  tcblist_p_hold_for_upd_1.\n    eauto.\n\n\n\n    simpljoin.\n    unfolds in H26.\n    inverts H26.\n\n    destruct v'35.\n    inverts H28.\n    inverts H28.\n\n    destruct H24.\n    gen H24.\n    eapply sometcblist_lemma.\n    instantiate ( 8:= s0).\n    sep cancel 13%nat 1%nat.\n    sep cancel 14%nat 1%nat.\n    eauto.\n    eapply  tcblist_p_hold_for_upd_1.\n    eauto.\n\n    gen H24.\n    eapply sometcblist_lemma.\n    instantiate ( 8:= s0).\n    sep cancel 13%nat 1%nat.\n    sep cancel 16%nat 1%nat.\n    eauto.\n    eauto.\n  hoare_split_pure_all.\n  simpljoin.\n\n\n  eapply backward_rule1.\n  intro.\n  Set Printing Depth 999.\n  intros.\n \n  instantiate (1 :=\n    (<||\n       scrt (x1 :: x0 :: Vint32 v'42 :: nil);;\n       isched;; END Some (V$ NO_ERR) \n       ||>  ** \n       (\n       HECBList v'13 **\n       HTime v'15 **\n       AOSTCBFreeList v'24 v'25 **\n       AOSMapTbl **\n       GAarray OSTCBPrioTbl (Tarray OS_TCB \u2217 64)\n       (update_nth_val (Z.to_nat (Int.unsigned v'42)) v'28 (Vptr v'34)) **\n       G& OSPlaceHolder @ Int8u == v'43 **\n       PV v'43 @ Int8u |-> v'45 **\n       GV OSTCBList @ OS_TCB \u2217 |-> Vptr v'34 **\n       node (Vptr v'34) v'39 OS_TCB_flag **\n       PV get_off_addr v'34 ($ 24) @ Int8u |-r-> (V$ 1) **\n       tcbdllseg v'30 (Vptr v'34) v'32 (Vptr tid) v'36 **\n       GV OSTCBCur @ OS_TCB \u2217 |-r-> Vptr tid **\n       tcbdllseg (Vptr tid) v'32 v'33 Vnull v'38 **\n       AOSRdyTblGrp\n       (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n                       (val_inj\n                          (or\n                             (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                             (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7)))\n                                       OSMapVallist)))) v'41 **\n       p_local OSLInv tid init_lg **\n       \n       LV err @ Int8u |-> (V$ OS_NO_ERR) **\n       AOSEventFreeList v'0 **\n       AOSQFreeList v'1 **\n       AOSQFreeBlk v'2 **\n       AECBList v'4 v'3 v'13 v'14 **\n       AOSUnMapTbl **\n       AOSIntNesting **\n       AOSTime (Vint32 v'15) **\n       AGVars **\n       tcbdllflag v'30 (v'35 ++ v'9 :: v'10) **\n       atoy_inv' **\n       LV prio @ Int8u |-> Vint32 v'42 **\n       LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n       LV task @ (Void) \u2217 |-> x1 **\n       A_dom_lenv\n       ((prio, Int8u)\n          :: (os_code_defs.pdata, (Void) \u2217)\n          :: (task, (Void) \u2217) :: (err, Int8u) :: nil)\n       ) **\n       OSLInv v'34 init_lg **\n       HTCBList v'14  **\n       HCurTCB tid ** \n       OS [ empisr, false, nil, (true::nil)]  \n    )).\n  remember (\n       HECBList v'13 **\n       HTime v'15 **\n       AOSTCBFreeList v'24 v'25 **\n       AOSMapTbl **\n       GAarray OSTCBPrioTbl (Tarray OS_TCB \u2217 64)\n         (update_nth_val (Z.to_nat (Int.unsigned v'42)) v'28 (Vptr v'34)) **\n       G& OSPlaceHolder @ Int8u == v'43 **\n       PV v'43 @ Int8u |-> v'45 **\n       GV OSTCBList @ OS_TCB \u2217 |-> Vptr v'34 **\n       node (Vptr v'34) v'39 OS_TCB_flag **\n       PV get_off_addr v'34 ($ 24) @ Int8u |-r-> (V$ 1) **\n       tcbdllseg v'30 (Vptr v'34) v'32 (Vptr tid) v'36 **\n       GV OSTCBCur @ OS_TCB \u2217 |-r-> Vptr tid **\n       tcbdllseg (Vptr tid) v'32 v'33 Vnull v'38 **\n       AOSRdyTblGrp\n         (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n            (val_inj\n               (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                  (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7)))\n                     OSMapVallist)))) v'41 **\n       p_local OSLInv tid init_lg **\n       LV err @ Int8u |-> (V$ OS_NO_ERR) **\n       AOSEventFreeList v'0 **\n       AOSQFreeList v'1 **\n       AOSQFreeBlk v'2 **\n       AECBList v'4 v'3 v'13 v'14 **\n       AOSUnMapTbl **\n       AOSIntNesting **\n       AOSTime (Vint32 v'15) **\n       AGVars **\n       tcbdllflag v'30 (v'35 ++ v'9 :: v'10) **\n       atoy_inv' **\n       LV prio @ Int8u |-> Vint32 v'42 **\n       LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n       LV task @ (Void) \u2217 |-> x1 **\n       A_dom_lenv\n         ((prio, Int8u)\n          :: (os_code_defs.pdata, (Void) \u2217)\n          :: (task, (Void) \u2217) :: (err, Int8u) :: nil)).\n\n  sep lifts (6::8:: nil)%nat.\n  eapply elim_a_isr_is_prop.\n\n  sep pauto.\n  sep cancel Aisr.\n  sep cancel Aie.\n  sep cancel Ais.\n  sep cancel Acs.\n  sep cancel A_isr_is_prop.\n  sep cancel 1%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  repeat sep cancel 2%nat 1%nat.\n  repeat sep cancel 5%nat 3%nat.\n  repeat sep cancel 4%nat 1%nat.\n  unfold OSLInv.\n  sep pauto.\n  unfold init_lg.\n  go.\n  unfolds.\n  left; auto.\n  unfold scrt.\n  \n  eapply seq_rule.\n  \n  \n   \n  eapply cre_rule.\n  assumption.\n  go.\n  unfold p_local.\n  go.\n  unfold CurTid.\n  go.\n  unfold LINV.\n  go.\n  unfold OSLInv.\n  go.\n  exact H21.\n  clear -H4.\n  unfolds in H4.\n  simpljoin.\n  unfolds.\n  eauto.\n  intro.\n  intros.\n  split.\n  sep get rv.\n  clear -H3.\n  pauto.\n  split.\n  sep get rv.\n  clear -H2.\n  pauto.\n  split.\n  sep get rv.\n  math simpls.\n  apply len_lt_update_get_eq.\n  rewrite H8.\n  bsimplr.\n  assumption.\n  unfold CurLINV.\n  unfold p_local in H26.\n  sep pauto.\n  sep cancel LINV.\n  simpl; auto.\n  eapply backward_rule1.\n  intro; intros.\nremember (\n       HECBList v'13 **\n       HTime v'15 **\n       AOSTCBFreeList v'24 v'25 **\n       AOSMapTbl **\n       GAarray OSTCBPrioTbl (Tarray OS_TCB \u2217 64)\n         (update_nth_val (Z.to_nat (Int.unsigned v'42)) v'28 (Vptr v'34)) **\n       G& OSPlaceHolder @ Int8u == v'43 **\n       PV v'43 @ Int8u |-> v'45 **\n       GV OSTCBList @ OS_TCB \u2217 |-> Vptr v'34 **\n       node (Vptr v'34) v'39 OS_TCB_flag **\n       PV get_off_addr v'34 ($ 24) @ Int8u |-r-> (V$ 1) **\n       tcbdllseg v'30 (Vptr v'34) v'32 (Vptr tid) v'36 **\n       GV OSTCBCur @ OS_TCB \u2217 |-r-> Vptr tid **\n       tcbdllseg (Vptr tid) v'32 v'33 Vnull v'38 **\n       AOSRdyTblGrp\n         (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n            (val_inj\n               (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                  (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7)))\n                     OSMapVallist)))) v'41 **\n       p_local OSLInv tid init_lg **\n       LV err @ Int8u |-> (V$ OS_NO_ERR) **\n       AOSEventFreeList v'0 **\n       AOSQFreeList v'1 **\n       AOSQFreeBlk v'2 **\n       AECBList v'4 v'3 v'13 v'14 **\n       AOSUnMapTbl **\n       AOSIntNesting **\n       AOSTime (Vint32 v'15) **\n       AGVars **\n       tcbdllflag v'30 (v'35 ++ v'9 :: v'10) **\n       atoy_inv' **\n       LV prio @ Int8u |-> Vint32 v'42 **\n       LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n       LV task @ (Void) \u2217 |-> x1 **\n       A_dom_lenv\n         ((prio, Int8u)\n          :: (os_code_defs.pdata, (Void) \u2217)\n          :: (task, (Void) \u2217) :: (err, Int8u) :: nil)).\n\n\n  sep lifts (5::7::nil)%nat in H26.\n  \n  eapply add_a_isr_is_prop in H26.\n  subst a.\n  eauto.\n  \n\n  (***** two part ******)\n    destruct H23.\n      simpljoin.\n\n      unfold tcbls_change_prev_ptr in H27.\n      inverts H27.\n\n      \n      hoare forward prim.\n      unfold AOSTCBPrioTbl.\n      unfold AOSTCBList.\n      sep pauto.\n      sep cancel 1%nat 5%nat.\n      sep cancel 1%nat 3%nat.\n      instantiate (1 :=  (LV err @ Int8u |-> (V$ OS_NO_ERR) **\n                                  LV prio @ Int8u |-> Vint32 v'42 **\n                                  LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n                                  LV task @ (Void) \u2217 |-> x1 **\n                                  A_dom_lenv\n                                  ((prio, Int8u)\n                                     :: (os_code_defs.pdata, (Void) \u2217)\n                                     :: (task, (Void) \u2217) :: (err, Int8u) :: nil))).\n      sep pauto.\n      sep cancel A_dom_lenv.\n      Focus 10.\n      hoare forward.\n      unfold init_lg in H23.\n      sep cancel p_local.\n      sep cancel Aie.\n      sep cancel Ais.\n      sep cancel Aisr.\n      sep cancel Acs.\n      sep cancel Aop.\n      eauto.\n      unfolds; auto.\n      go.\n      linv_solver.\n      linv_solver.\n      \n      unfold AECBList in *.\n      sep pauto.\n      sep cancel 1%nat 1%nat.\n      sep cancel 4%nat 2%nat.\n      instantiate (1 := (v'39 ::nil ) ++ nil).\n      eapply inv_prop.tcbdllseg_compose.\n      sep cancel 3%nat 2%nat.\n      change (  (((v'39 :: nil) ++ nil) ++ update_nth_val 1 v'9 (Vptr v'34) :: v'10) ) with (v'39 :: update_nth_val 1 v'9 (Vptr v'34) :: v'10) .\n      unfold tcbdllseg.\n      unfold dllseg.\n      sep pauto.\n      unfold tcbdllflag.\n      remember ( update_nth_val 1 v'9 (Vptr v'34) :: v'10).\n      unfold1 dllsegflag.\n      sep pauto.\n      sep cancel 1%nat 1%nat.\n      change (nil ++ v'9 :: v'10) with (v'9 :: v'10) in H23.\n      unfold tcbdllflag in H23.\n      unfold dllsegflag in *.\n      sep destruct H23.\n      \n      sep pauto.\n      unfolds.\n      eapply nth_upd_neqrev.\n      omega.\n      auto.\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n      \n\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n      eapply ecblist_hold_for_add_tcb; eauto.\n\n      \n\n      assert (v'43 <> v'34).\n      \n        unfold node in H23.\n        sep normal in H23.\n        sep destruct H23.\n        sep split in H23.\n        simpljoin.\n        inverts H27.\n        intro.\n        eapply struct_pv_overlap.\n(* ** ac:         Show. *)\n(* ** ac:         Show. *)\n        rewrite H27 in H23.\n        sep lift 4%nat in H23.\n        sep lift 2%nat in H23.\n        exact H23.\n          \n\n        \n      \n\n      \n      eapply r_priotbl_p_hold_for_add_tcb; eauto.\n      assumption.\n(* ** ac:       Print TCBList_P. *)\n      instantiate (1:= v'23).\n      eapply tcblist_p_hold_for_add_tcb.\n      clear -H9.\n      int auto.\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n      \n      assumption.\n      \n      \n        clear -H7 H13 H11.\n        unfolds in H7.\n        simpljoin.\n        intro.\n        simpljoin.\n        assert (get v'14 x = Some (v'42, x0, x1)).\n        unfold get,join in *; simpl in *.\n        go.\n        \n        lets bb: H0 H3.\n        simpljoin.\n        eapply nth_val_nth_val'_some_eq in H4.\n        unfold nat_of_Z in H4.\n        rewrite H4 in H13.\n        inverts H13.\n\n      \n     \n      \n    \n   \n\n      \n  \n\n      instantiate (1:= (sig v'34 (v'42, rdy, Vnull))).\n      eapply tcblist_p_hold_for_add_tcb''.\n      clear -H9.\n      int auto.\n      clear -somehyp .\n      unprotect somehyp.\n      tauto.\n      clear -somehyp .\n      unprotect somehyp.\n      tauto.\n        instantiate (1 := v'22).\n        intro.\n        simpljoin.\n        assert (get v'14 x = Some (v'42, x2, x3)).\n        unfold get,join,sig in *; simpl in *.\n        go.\n        eapply not_in_priotbl_no_priotcb; eauto.\n      eauto.\n      auto.\n\n      eapply TCBList_P_nil_empty in H12.\n      subst v'22.\n      clear.\n      join auto.\n      simpl in H12.\n      subst v'22.\n      assert (v'23 = v'14).\n      clear -H11.\n      join auto.\n      subst v'14.\n      assumption.\n      unfolds.\n      unfolds in H4.\n      simpljoin.\n      clear -H4 H21.\n      do 3 eexists.\n      unfold get in *; simpl in *.\n      eapply TcbMod.join_get_get_r.\n      exact H21.\n      eauto.\n\n      eapply rh_t_e_p_hold_for_add_tcb.\n      eauto.\n      eauto.\n      go.\n      assert (exists t, join (sig v'34 (v'42, rdy, Vnull)) v'22 t ).\n      clear -H21 H11.\n      unfold TcbJoin in H21.\n      join auto.\n      simpljoin.\n\n      unfold tcbls_change_prev_ptr in H27.\n      destruct v'35.\n      clear -H23; tryfalse.\n      inverts H27.\n      \n      hoare forward prim.\n      unfold AOSTCBPrioTbl.\n      unfold AOSTCBList.\n      sep pauto.\n      sep cancel 1%nat 5%nat.\n      sep cancel 1%nat 3%nat.\n      instantiate (1 :=  (LV err @ Int8u |-> (V$ OS_NO_ERR) **\n                                  LV prio @ Int8u |-> Vint32 v'42 **\n                                  LV os_code_defs.pdata @ (Void) \u2217 |-> x0 **\n                                  LV task @ (Void) \u2217 |-> x1 **\n                                  A_dom_lenv\n                                  ((prio, Int8u)\n                                     :: (os_code_defs.pdata, (Void) \u2217)\n                                     :: (task, (Void) \u2217) :: (err, Int8u) :: nil))).\n      sep pauto.\n      sep cancel A_dom_lenv.\n      Focus 10.\n      hoare forward.\n      unfold init_lg in H27.\n      sep cancel p_local.\n      sep cancel Aie.\n      sep cancel Ais.\n      sep cancel Aisr.\n      sep cancel Acs.\n      sep cancel Aop.\n      eauto.\n      unfolds; auto.\n      go.\n      linv_solver.\n      linv_solver.\n      \n      unfold AECBList in *.\n      sep pauto.\n      sep cancel 1%nat 1%nat.\n      sep cancel 4%nat 2%nat.\n      instantiate (1 := (v'39 ::nil ) ++ ( (update_nth_val 1 v (Vptr v'34) :: v'35))).\n      eapply inv_prop.tcbdllseg_compose.\n      sep cancel 3%nat 2%nat.\n      unfold tcbdllseg.\n      unfold dllseg.\n      sep pauto.\n      unfold tcbdllflag.\n      change ((v'39 :: nil) ++ update_nth_val 1 v (Vptr v'34) :: v'35) with (v'39 :: update_nth_val 1 v (Vptr v'34) :: v'35) .\n      change (((v'39 :: update_nth_val 1 v (Vptr v'34) :: v'35) ++ v'9 :: v'10)) with (v'39 :: ((update_nth_val 1 v (Vptr v'34) :: v'35) ++ v'9 :: v'10)). \n      remember ((update_nth_val 1 v (Vptr v'34) :: v'35) ++ v'9 :: v'10).\n\n      unfold1 dllsegflag.\n      sep pauto.\n      sep cancel 1%nat 1%nat.\n      change  ((update_nth_val 1 v (Vptr v'34) :: v'35) ++ v'9 :: v'10) with  (update_nth_val 1 v (Vptr v'34) :: v'35 ++ v'9::v'10).\n      change ((v :: v'35) ++ v'9 :: v'10) with (v :: v'35 ++ v'9 :: v'10) in H27.\n      unfold tcbdllflag in H27.\n      unfold dllsegflag in *.\n      sep destruct H27.\n      \n      sep pauto.\n      unfolds.\n      eapply nth_upd_neqrev.\n      omega.\n      auto.\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n\n      clear -H18.\n      unfolds in H18.\n      simpljoin; auto.\n\n      \n      eapply ecblist_hold_for_add_tcb; eauto.\n      \n      eapply r_priotbl_p_hold_for_add_tcb; eauto.\n        unfold node in H27.\n        sep normal in H27.\n        sep destruct H27.\n        sep split in H27.\n        simpljoin.\n        inverts H29.\n        intro.\n        eapply struct_pv_overlap.\n        rewrite H29 in H27.\n        sep lift 4%nat in H27.\n        sep lift 2%nat in H27.\n        exact H27.\n      assumption.\n      instantiate (1:= v'23).\n      \n      assert (exists x, nth_val 1 v'9 = Some x).\n      clear -H14.\n      unfold1 TCBList_P in H14.\n      simpljoin.\n      unfolds in H2.\n      destruct x2; destruct p.\n      simpljoin.\n      unfolds in H2.\n      destruct v'9.\n      inverts H2.\n      destruct v'9.\n      inverts H2.\n      eexists.\n      simpl.\n      eauto.\n      simpljoin.\n      erewrite (update_eq v'9).\n      \n      eapply tcblist_p_hold_for_add_tcb.\n      clear -H9.\n      int auto.\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n      assumption.\n        clear -H7 H13 H11.\n        unfolds in H7.\n        simpljoin.\n        intro.\n        simpljoin.\n        assert (get v'14 x = Some (v'42, x0, x1)).\n        unfold get,join in *; simpl in *.\n        go.\n        \n        lets bb: H0 H3.\n        simpljoin.\n        eapply nth_val_nth_val'_some_eq in H4.\n        unfold nat_of_Z in H4.\n        rewrite H4 in H13.\n        inverts H13.\n\n      eauto.\n      \n      \n\n      \n      instantiate (1 := x). \n      eapply tcblist_p_hold_for_add_tcb''.\n      clear -H9.\n      int auto.\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n      clear -somehyp.\n      unprotect somehyp.\n      tauto.\n        instantiate (1 := v'22).\n        intro.\n        simpljoin.\n        assert (get v'14 x2 = Some (v'42, x3, x4)).\n        unfold get,join,sig in *; simpl in *.\n        go.\n        eapply not_in_priotbl_no_priotcb; eauto.\n \n      eapply tcblist_p_hold_for_upd_1.\n      eauto.\n      eauto.\n      go.\n      clear -H21 H26 H11.\n      unfold TcbJoin in H21.\n      join auto.\n      unfolds.\n      unfolds in H4.\n      simpljoin.\n      clear -H4 H21.\n      do 3 eexists.\n      unfold get in *; simpl in *.\n      eapply TcbMod.join_get_get_r.\n      exact H21.\n      eauto.\n\n\n      \n\n      eapply rh_t_e_p_hold_for_add_tcb.\n      eauto.\n      eauto.\n      go.\n      \n\n\n  hoare forward.\n  hoare unfold.\n  unfold OS_SchedPost .\n  unfold OS_SchedPost'.\n  unfold getasrt.\n  hoare unfold.\n  hoare forward.\n  inverts H21.\n  reflexivity.\n  hoare_split_pure_all.\n  false.\n  clear -H17.\n  int auto.\n  destruct H17; tryfalse.\n\n  Grab Existential Variables.\n  exact (Afalse).\n  exact (Afalse).\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/task/taskcreate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594692351241}}
{"text": "Require Import Raft.\nRequire Import SpecLemmas.\n\nRequire Import NoAppendEntriesToSelfInterface.\n\nSection NoAppendEntriesToSelf.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Lemma doLeader_no_messages_to_self :\n    forall st h os st' ms m,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      fst m <> h.\n  Proof using. \n    intros.\n    unfold doLeader in *.\n    repeat break_match; try solve [find_inversion; simpl in *; congruence].\n    find_inversion.\n    do_in_map.\n    subst. simpl in *.\n    find_apply_lem_hyp filter_In.\n    intuition. subst.\n    break_match; congruence.\n  Qed.\n\n  Lemma no_append_entries_to_self_do_leader :\n    raft_net_invariant_do_leader no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map.\n    subst. simpl in *.\n    find_eapply_lem_hyp doLeader_no_messages_to_self; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_do_generic_server :\n    raft_net_invariant_do_generic_server no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map.\n    subst. simpl in *.\n    find_eapply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma no_append_entries_to_self_append_entries :\n    raft_net_invariant_append_entries no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    subst. simpl in *. subst.\n    find_apply_lem_hyp handleAppendEntries_not_append_entries.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n  \n  Lemma no_append_entries_to_self_append_entries_reply :\n    raft_net_invariant_append_entries_reply no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_apply_lem_hyp handleAppendEntriesReply_packets.\n    subst. intuition.\n  Qed.\n  \n  Lemma no_append_entries_to_self_request_vote :\n    raft_net_invariant_request_vote no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    subst. simpl in *. subst.\n    find_apply_lem_hyp handleRequestVote_no_append_entries.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_request_vote_reply :\n    raft_net_invariant_request_vote_reply no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_client_request :\n    raft_net_invariant_client_request no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_eapply_lem_hyp handleClientRequest_no_append_entries; eauto.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_timeout :\n    raft_net_invariant_timeout no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_eapply_lem_hyp handleTimeout_not_is_append_entries; eauto.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_reboot :\n    raft_net_invariant_reboot no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_reverse_rewrite. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_init :\n    raft_net_invariant_init no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *. intuition.\n  Qed.\n\n\n  Theorem no_append_entries_to_self_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      no_append_entries_to_self net.\n  Proof using. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply no_append_entries_to_self_init.\n    - apply no_append_entries_to_self_client_request.\n    - apply no_append_entries_to_self_timeout.\n    - apply no_append_entries_to_self_append_entries.\n    - apply no_append_entries_to_self_append_entries_reply.\n    - apply no_append_entries_to_self_request_vote.\n    - apply no_append_entries_to_self_request_vote_reply.\n    - apply no_append_entries_to_self_do_leader.\n    - apply no_append_entries_to_self_do_generic_server.\n    - apply no_append_entries_to_self_state_same_packet_subset.\n    - apply no_append_entries_to_self_reboot.\n  Qed.    \n  \n  Instance noaetsi : no_append_entries_to_self_interface.\n  split. exact no_append_entries_to_self_invariant.\n  Qed.\n\nEnd NoAppendEntriesToSelf.", "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/NoAppendEntriesToSelfProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.18655946768697806}}
{"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.\n  (* of and *)\n  exploit get_sound; eauto. unfold equation_holds; simpl. \n  destruct args; try discriminate. destruct args; try discriminate. simpl. \n  intros EQ; inv EQ. destruct (valu v); simpl; auto. \nQed.\n\nLemma combine_compimm_eq_0_sound:\n  forall x cond args,\n  combine_compimm_eq_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_eq_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  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.\n  (* of and *)\n  exploit get_sound; eauto. unfold equation_holds; simpl. \n  destruct args; try discriminate. destruct args; try discriminate. simpl. \n  intros EQ; inv EQ. destruct (valu v); simpl; 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  exploit get_sound; eauto. unfold equation_holds; simpl; intro EQ.\n  assert (forall vl,\n         eval_addressing ge sp (SelectOp.offset_addressing a n) vl =\n         option_map (fun v => Val.add v (Vint n)) (eval_addressing ge sp a vl)).\n    intros. destruct a; simpl; repeat (destruct vl; auto); simpl. \n    rewrite Val.add_assoc. auto. \n    repeat rewrite Val.add_assoc. auto.\n    rewrite Val.add_assoc. auto.\n    repeat rewrite Val.add_assoc. auto.\n    unfold symbol_address. destruct (Globalenvs.Genv.find_symbol ge i); auto. \n    unfold symbol_address. destruct (Globalenvs.Genv.find_symbol ge i); auto.\n      repeat rewrite <- (Val.add_commut v). rewrite Val.add_assoc. auto. \n    unfold symbol_address. destruct (Globalenvs.Genv.find_symbol ge i0); auto.\n      repeat rewrite <- (Val.add_commut (Val.mul v (Vint i))). rewrite Val.add_assoc. auto.\n    rewrite Val.add_assoc; auto.\n  rewrite H0. rewrite EQ. auto. \nQed.\n\nTheorem combine_op_sound:\n  forall op args op' args',\n  combine_op get op args = Some(op', args') ->\n  eval_operation ge sp op' (map valu args') m = eval_operation ge sp op (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n(* lea *)\n  simpl. eapply combine_addr_sound; eauto. \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/ia32/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.18655946768697804}}
{"text": "Require Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.semantics_lemmas.\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.veric.Clight_base.\nRequire Import VST.veric.Clight_core.\n\nLemma alloc_variables_mem_step: forall cenv vars m e e2 m'\n      (M: alloc_variables cenv e m vars e2 m'), mem_step m m'.\nProof. intros.\n  induction M.\n  apply mem_step_refl.\n  eapply semantics.mem_step_trans.\n    eapply semantics.mem_step_alloc; eassumption. eassumption.\nQed.\n\nLemma assign_loc_mem_step g t m b z v m' (A:assign_loc g t m b z v m'):\n    mem_step m m'.\nProof.\n  inv A.\n  { simpl in H0. eapply mem_step_storebytes. eapply Mem.store_storebytes; eauto. }\n  { eapply mem_step_storebytes; eauto. }\nQed.\n\nLemma bind_parameters_mem_step: forall cenv e m pars vargs m'\n      (M: bind_parameters cenv e m pars vargs m'), semantics.mem_step m m'.\nProof. intros.\n  induction M.\n  apply mem_step_refl.\n  inv H0.\n+ eapply semantics.mem_step_trans; try eassumption. simpl in H2.\n  eapply mem_step_store; eassumption.\n+ eapply semantics.mem_step_trans; try eassumption.\n  eapply semantics.mem_step_storebytes; eassumption.\nQed.\n\nLemma inline_assembly_memstep: forall text sg g vargs m t vres m' (IA:Events.inline_assembly_sem text sg g vargs m t vres m'),\n    mem_step m m'.\nAdmitted. (*Maybe include mem_step in Events.extcall_properties.?*)\n\nLemma extcall_sem_mem_step: forall name sg g vargs m t vres m' (E:Events.external_functions_sem name sg g vargs m t vres m'),\n  mem_step m m'.\nAdmitted. (*Maybe include mem_step in Events.extcall_properties.?*)\n\nLemma extcall_mem_step g: forall ef vargs m t vres m' (E:Events.external_call ef g vargs m t vres m'),\n  mem_step m m'.\nProof.\n  destruct ef; simpl; intros; try solve [inv E; apply mem_step_refl].\n  { eapply extcall_sem_mem_step; eassumption. }\n  { eapply extcall_sem_mem_step; eassumption. }\n  { eapply extcall_sem_mem_step; eassumption. }\n  { inv E. inv H. eapply mem_step_refl.\n    apply Mem.store_storebytes in H1. eapply mem_step_storebytes. eassumption. }\n  { inv E. apply Mem.store_storebytes in H0.\n    eapply mem_step_trans. eapply mem_step_alloc; eassumption.\n    eapply mem_step_storebytes; eassumption. }\n  { inv E. eapply mem_step_free; eassumption. }\n  { inv E. eapply mem_step_storebytes. eassumption. }\n  { eapply inline_assembly_memstep; eassumption. }\nQed.\n  \nLemma CLC_corestep_mem:\n  forall (g : genv) c (m : mem) c'  (m' : mem),\n    semantics.corestep (cl_core_sem g) c m c' m' ->\n    semantics.mem_step m m'.\nProof. simpl; intros. inv H; simpl in *;\n  try apply mem_step_refl.\n   eapply assign_loc_mem_step; eauto.\n   eapply mem_step_freelist; eauto.\n   eapply mem_step_freelist; eauto.\n   eapply mem_step_freelist; eauto.\n   inv H0.\n   eapply alloc_variables_mem_step; eauto.\n   apply extcall_mem_step in H1; auto.\nQed. \n\nProgram Definition CLC_memsem  (ge : Clight.genv) :\n  @MemSem state.\napply Build_MemSem with (csem := cl_core_sem ge).\neapply CLC_corestep_mem.\nDefined.\n\n\n(*\nLemma assign_loc_forward:\n      forall cenv t m b ofs v m'\n      (A: assign_loc cenv t m b ofs v m'),\n      mem_forward m m'.\nProof.\nintros.\ninduction A.\n unfold Mem.storev in H0.\n eapply store_forward; eassumption.\n eapply storebytes_forward; eassumption.\nQed.\n\nLemma alloc_variables_forward: forall cenv vars m e e2 m'\n      (M: alloc_variables cenv e m vars e2 m'),\n      mem_forward m m'.\nProof. intros.\n  induction M.\n  apply mem_forward_refl.\n  apply alloc_forward in H.\n  eapply mem_forward_trans; eassumption.\nQed.\n\nLemma cln_forward: forall (g : genv) (c : corestate)\n  (m : mem) (c' : corestate) (m' : mem),\n  corestep cl_core_sem g c m c' m' -> mem_forward m m'.\nProof.\nintros.\ninduction H; try apply mem_forward_refl; trivial.\n  eapply assign_loc_forward; eassumption.\n  eapply alloc_variables_forward; eassumption.\n  eapply freelist_forward; eassumption.\nQed.\nProgram Definition CLN_coop_sem :\n  CoopCoreSem Clight.genv (*(Genv.t fundef type)*) corestate.\napply Build_CoopCoreSem with (coopsem := cl_core_sem).\napply cln_forward.\nadmit. (*This is the new readonly condition which should be easy to prove.*)\nAdmitted.\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/Clightcore_coop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1865594588958893}}
{"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.\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\nRequire Import MemoryReorder.\nRequire Import PromiseConsistent.\nRequire Import FulfillStep.\n\nSet Implicit Arguments.\n\n\nLemma reorder_promise_read\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1 kind1\n      loc2 to2 val2 released2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.read_step lc1 mem1 loc2 to2 val2 released2 ord2 lc2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (LOCTS: (loc1, to1) <> (loc2, to2)):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 msg1 lc2 mem1 kind1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit MemoryFacts.promise_get_inv_diff; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_promise_promise_lower_None\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 (Message.concrete val2 None) lc2 mem2 kind2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (KIND2: Memory.op_kind_is_lower kind2 = true):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ Message.le (Message.concrete val2 None) msg1 /\\ kind2 = Memory.op_kind_lower msg1 /\\\n   exists kind1', <<STEP: Local.promise_step lc0 mem0 loc1 from1 to1 (Message.concrete val2 None) lc2 mem2 kind1'>>) \\/\n  (exists lc1' mem1' from2' kind1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2' to2 (Message.concrete val2 None) lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 msg1 lc2 mem2 kind1'>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE0; inv KIND2. des. subst.\n  inv PROMISE; ss.\n  - exploit MemoryReorder.add_lower; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n    + subst.\n      exploit MemoryReorder.add_lower; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n      left. esplits; ss.\n      * inv MEM. inv LOWER. ss.\n      * econs; eauto. econs; eauto.\n        i. inv MEM. inv LOWER. inv MSG_LE; ss; eauto.\n        eapply ATTACH; eauto. ss.\n    + exploit MemoryReorder.add_lower; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n      right. esplits; eauto; econs; eauto.\n      * econs; eauto.\n        i. revert GET.\n        erewrite Memory.lower_o; eauto. condtac; ss.\n        { i. des. subst. inv GET.\n          exploit Memory.lower_get0; try exact MEM. i. des.\n          revert GET. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          des. subst. inv MEM. inv LOWER. timetac. }\n        { i. exploit Memory.lower_get1; try exact GET; eauto. }\n      * eapply Memory.lower_closed_message; eauto.\n  - des. subst.\n    destruct (classic ((loc1, ts3) = (loc2, to2))).\n    { inv H.\n      exploit MemoryReorder.split_lower_same; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n      exploit MemoryReorder.split_lower_same; try exact MEM1; try exact MEM; eauto. i. des.\n      subst. right. esplits; eauto; econs; eauto.\n      eapply Memory.lower_closed_message; eauto.\n    }\n    { exploit MemoryReorder.split_lower_diff; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n      - subst.\n        exploit MemoryReorder.split_lower_diff; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n        left. esplits; eauto. inv MEM. inv LOWER. ss.\n      - exploit MemoryReorder.split_lower_diff; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n        right. esplits; eauto; econs; eauto.\n        eapply Memory.lower_closed_message; eauto.\n    }\n  - des. subst.\n    exploit MemoryReorder.lower_lower; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n    + subst.\n      exploit MemoryReorder.lower_lower; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n      left. esplits; eauto. inv MEM. inv LOWER. ss.\n    + exploit MemoryReorder.lower_lower; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n      right. esplits; eauto; econs; eauto.\n      eapply Memory.lower_closed_message; cycle 1; eauto.\nQed.\n\nLemma reorder_promise_promise_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2)\n      (KIND2: Memory.op_kind_is_cancel kind2 = true):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = Message.reserve /\\ kind1 = Memory.op_kind_add /\\\n   lc0 = lc2 /\\ mem0 = mem2) \\/\n  (exists lc1' mem1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 msg1 lc2 mem2 kind1>>).\nProof.\n  inv STEP1. inv STEP2. ss. destruct kind2; ss.\n  exploit MemoryReorder.promise_cancel; try exact PROMISE; eauto. i. des.\n  - left. splits; auto. destruct lc0; ss. subst. ss.\n  - right. esplits.\n    + econs; eauto.\n      inv CANCEL1. eapply Memory.cancel_closed_message; eauto.\n    + econs; eauto.\n      inv PROMISE0. eapply Memory.cancel_closed_message; eauto.\nQed.\n\nLemma reorder_promise_promise\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2)\n      (REL_CLOSED: forall promises1' mem1' kind1'\n                     (PROMISE1: Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 msg2 promises1' mem1' kind1'),\n          Memory.closed_message msg2 mem1')\n      (LOCAL0: Local.wf lc0 mem0)\n      (CLOSED0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (MSG2: msg2 <> Message.reserve)\n      (LOCTS1: forall to1' msg1'\n                (LOC: loc1 = loc2)\n                (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2 /\\\n          (forall msg2', kind2 <> Memory.op_kind_split to1' msg2'))\n      (LOCTS2: forall (LOC: loc1 = loc2)\n                 (KIND1: kind1 = Memory.op_kind_add)\n                 (KIND2: kind2 = Memory.op_kind_add)\n                 (MSG1: msg1 <> Message.reserve),\n               Time.lt to2 to1):\n  exists lc1' mem1' kind2',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2'>> /\\\n    <<STEP2: __guard__\n               ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                (exists from1' kind1',\n                    (loc1, to1) <> (loc2, to2) /\\\n                    (forall to1' msg1'\n                       (LOC: loc1 = loc2)\n                       (KIND: kind1' = Memory.op_kind_split to1' msg1'),\n                        to1' <> to2 /\\\n                        (forall msg2', kind2 <> Memory.op_kind_split to1' msg2')) /\\\n                    Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1' /\\\n                    Memory.op_kind_is_cancel kind1' = false /\\\n                    (Memory.op_kind_is_lower kind1 = false -> Memory.op_kind_is_lower kind1' = false))\n               )>> /\\\n    <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE; ss.\n  { inv PROMISE0; ss.\n    - (* add/add *)\n      exploit MemoryReorder.add_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.add_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 msg2\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.add_get1; try exact MEM; eauto.\n      + right. esplits; eauto. econs; eauto.\n        * econs; eauto. i. revert GET.\n          erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          i. des. inv GET.\n          exploit LOCTS2; eauto. intros x.\n          inv ADD0. inv ADD. rewrite x in TO. timetac.\n        * eapply Memory.add_closed_message; cycle 1; eauto.\n      + auto.\n    - (* add/split *)\n      exploit MemoryReorder.add_split; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst.\n        exploit MemoryReorder.add_split; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 msg2\n                              mem1' mem1'0 Memory.op_kind_add).\n          { i. econs; eauto. }\n          econs; eauto; try congr.\n          i. exploit Memory.add_get1; try exact GET; try exact MEM. i.\n          exploit Memory.add_get0; try exact MEM. i. des.\n          clear GET GET0.\n          exploit Memory.get_ts; try exact x4. i. des.\n          { subst. inv ADD0. inv ADD. inv TO. }\n          exploit Memory.get_ts; try exact GET1. i. des.\n          { subst. inv ADD3. inv ADD. inv TO. }\n          exploit Memory.get_disjoint; [exact x4|exact GET1|..]. i. des.\n          { subst. inv ADD0. inv ADD. timetac. }\n          destruct (TimeFacts.le_lt_dec to' ts3).\n          { apply (x7 to'); econs; ss; try refl.\n            inv ADD0. inv ADD. etrans; eauto. }\n          { apply (x7 ts3); econs; ss; try refl.\n            - inv ADD3. inv ADD. ss.\n            - econs. ss. }\n        * right. esplits; eauto.\n          { ii. inv H. inv ADD3. inv ADD. timetac. }\n          { econs.\n            - econs; eauto.\n              i. revert GET.\n              erewrite Memory.add_o; eauto. condtac; ss; eauto. i. des. inv GET.\n              inv ADD0. inv ADD. inv ADD3. inv ADD. rewrite TO in TO0. timetac.\n            - eapply Memory.split_closed_message; eauto.\n            - auto. }\n        * auto.\n      + exploit MemoryReorder.add_split; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.split_get0; try exact MEM0; eauto. i. des.\n            revert GET. erewrite Memory.add_o; eauto. condtac; ss. des; congr. }\n          { econs; eauto.\n            - econs; eauto.\n              i. revert GET.\n              erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n              + i. des. inv GET.\n                exploit Memory.split_get0; try exact MEM0. i. des.\n                revert GET0. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n                i. des. inv GET0.\n                inv MEM0. inv SPLIT. rewrite TS12 in TS23. timetac.\n              + guardH o. i. des. inv GET.\n                exploit Memory.split_get0; try exact SPLIT0. i. des.\n                exploit Memory.add_get0; try exact ADD0. i. des.\n                exploit Memory.add_get1; try exact GET1; eauto. i.\n                clear GET GET0 GET1 GET2 GET3.\n                exploit Memory.get_ts; try exact GET4. i. des.\n                { subst. inv SPLIT0. inv SPLIT. inv TS12. }\n                exploit Memory.get_ts; try exact x0. i. des.\n                { subst. inv ADD0. inv ADD. inv TO. }\n                exploit Memory.get_disjoint; [exact GET4|exact x0|..]. i. des.\n                { subst. exploit Memory.split_get0; try exact SPLIT0. i. des.\n                  inv ADD0. inv ADD.\n                  hexploit DISJOINT; try eapply GET1. i.\n                  apply (H to1); econs; ss; try refl. }\n                apply (x3 to1); econs; ss; try refl.\n            - eapply Memory.split_closed_message; eauto. }\n        * auto.\n    - (* add/lower *)\n      des. subst.\n      exploit MemoryReorder.add_lower; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst.\n        exploit MemoryReorder.add_lower; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * econs; eauto. econs; eauto.\n          i. inv MEM0. inv LOWER. inv MSG_LE; ss; eauto.\n          eapply ATTACH; eauto. ss.\n        * left. auto.\n        * auto.\n      + exploit MemoryReorder.add_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs; eauto.\n        * right. esplits; eauto. econs; eauto.\n          { econs; eauto.\n            i. revert GET.\n            erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n            i. des. inv GET.\n            exploit Memory.lower_get0; try exact LOWER0. i. des. eauto. }\n          { eapply Memory.lower_closed_message; eauto. }\n        * auto.\n  }\n\n  { des. subst. inv PROMISE0; ss.\n    - (* split/add *)\n      exploit MemoryReorder.split_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.split_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 msg2\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.split_get1; try exact GET; eauto. i. des.\n        dup GET2. revert GET2.\n        erewrite Memory.split_o; eauto. repeat condtac; ss.\n        * i. des. inv GET2.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          rewrite GET in *. ss.\n        * guardH o. i. des. inv GET2.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          rewrite GET in *. inv GET2. eauto.\n        * i. rewrite GET in *. inv GET2. eauto.\n      + right. esplits; eauto. econs; eauto.\n        eapply Memory.add_closed_message; eauto.\n      + auto.\n    - (* split/split *)\n      des.\n      exploit MemoryReorder.split_split; try exact PROMISES; try exact PROMISES0; eauto.\n      { ii. inv H. eapply LOCTS1; eauto. }\n      i. des.\n      + subst. exploit MemoryReorder.split_split; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. inv SPLIT2. inv SPLIT. timetac. }\n        i. des; [|congr].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. inv SPLIT2. inv SPLIT. timetac. }\n          { econs; eauto.\n            eapply Memory.split_closed_message; cycle 1; eauto. }\n        * congr.\n      + exploit MemoryReorder.split_split; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. eapply LOCTS1; eauto. }\n        i. des; [congr|].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.split_get0; try exact MEM1; eauto. i. des.\n            revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n            guardH o0. des; congr. }\n          { econs; eauto.\n            eapply Memory.split_closed_message; cycle 1; eauto. }\n        * auto.\n    - (* split/lower *)\n      des. subst.\n      exploit MemoryReorder.split_lower_diff; try exact PROMISES; try exact PROMISES0; eauto.\n      { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n      i. des.\n      + subst.\n        exploit MemoryReorder.split_lower_diff; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n        i. des; [|congr].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * left. auto.\n        * congr.\n      + subst. exploit MemoryReorder.split_lower_diff; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n        i. des; [congr|].\n        esplits.\n        * econs; eauto.\n        * right. esplits; eauto. econs; eauto.\n          eapply Memory.lower_closed_message; eauto.\n        * congr.\n  }\n\n  { des. subst. inv PROMISE0; ss.\n    - (* lower/add *)\n      exploit MemoryReorder.lower_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.lower_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 msg2\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.lower_get1; try exact GET; eauto. i. des. eauto.\n      + right. esplits; eauto. econs; eauto.\n        eapply Memory.add_closed_message; eauto.\n      + auto.\n    - (* lower/split *)\n      des.\n      exploit MemoryReorder.lower_split; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.lower_split; try exact MEM; try exact MEM0; eauto. i. des.\n      unguardH FROM1. des.\n      + inv FROM1. unguardH FROM0. des; [|congr]. inv FROM0.\n        esplits.\n        * econs.\n          { econs 2; eauto. inv LOWER0. inv LOWER. inv MSG_LE; ss. }\n          { eapply REL_CLOSED. econs 2; eauto.\n            inv LOWER0. inv LOWER. inv MSG_LE; ss. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. inv SPLIT1. inv SPLIT. timetac. }\n          { econs; eauto. eapply Memory.split_closed_message; eauto. }\n        * congr.\n      + inv FROM2. unguardH FROM0. des; [congr|]. inv FROM2.\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.lower_get0; try exact MEM; eauto.\n            exploit Memory.split_get0; try exact SPLIT0; eauto. i. des. congr. }\n          { econs; eauto. eapply Memory.split_closed_message; eauto. }\n        * auto.\n    - (* lower/lower *)\n      des. subst.\n      exploit MemoryReorder.lower_lower; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst.\n        exploit MemoryReorder.lower_lower; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * econs; eauto.\n        * left. auto.\n        * congr.\n      + exploit MemoryReorder.lower_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs; eauto.\n        * right. esplits; eauto. econs; eauto.\n          eapply Memory.lower_closed_message; cycle 1; eauto.\n        * auto.\n  }\nQed.\n\nLemma reorder_promise_fulfill\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: fulfill_step lc1 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (LOCTS1: (loc1, to1) <> (loc2, to2))\n      (LOCTS2: forall to1' msg1'\n                 (LOC: loc1 = loc2)\n                 (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2):\n  exists lc1',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2>> /\\\n    <<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 msg1 lc2 mem1 kind1>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE; ss.\n  - exploit MemoryReorder.add_remove; try exact REMOVE; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss.\n  - exploit MemoryReorder.split_remove; try exact PROMISES; try exact REMOVE; eauto.\n    { ii. inv H. eapply LOCTS2; eauto. }\n    i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss; eauto.\n  - des. subst.\n    exploit MemoryReorder.lower_remove; try exact REMOVE; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; eauto.\n  - exploit MemoryReorder.remove_remove; try exact PROMISES; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss.\nQed.\n\nLemma promise_step_nonsynch_loc_inv\n      lc1 mem1 loc from to msg lc2 mem2 kind l\n      (WF1: Local.wf lc1 mem1)\n      (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n      (NONPF: Memory.op_kind_is_lower kind = false \\/ ~ Message.is_released_none msg)\n      (NONSYNCH: Memory.nonsynch_loc l lc2.(Local.promises)):\n  Memory.nonsynch_loc l lc1.(Local.promises).\nProof.\n  guardH NONPF.\n  ii. inv STEP. inv PROMISE; ss.\n  - exploit Memory.add_get1; try exact GET; eauto. i. des.\n    exploit NONSYNCH; eauto.\n  - exploit Memory.split_get1; try exact GET; eauto. i. des.\n    exploit NONSYNCH; eauto.\n  - exploit Memory.lower_o; try exact PROMISES; eauto.\n    instantiate (1 := t). instantiate (1 := l). condtac; ss.\n    + i. des. subst. exploit NONSYNCH; eauto.\n      destruct msg; destruct msg0; ss.\n      * i. subst. unguard. des; ss.\n      * exploit Memory.lower_get0; try exact PROMISES. i. des.\n        rewrite GET0 in *. inv GET. inv MSG_LE.\n    + rewrite GET. i. exploit NONSYNCH; eauto.\n  - exploit Memory.remove_get1; try exact GET; eauto. i. des.\n    + subst. exploit Memory.remove_get0; try exact PROMISES. i. des.\n      rewrite GET0 in GET. inv GET. ss.\n    + exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_promise_write_aux\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2)\n      (NONPF: Memory.op_kind_is_lower kind1 = false \\/ ~ Message.is_released_none msg1)\n      (REL_WF: View.opt_wf releasedm2)\n      (REL_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (LOCAL0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (LOCTS1: forall to1' msg1'\n                (LOC: loc1 = loc2)\n                (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2 /\\\n          (forall msg2', kind2 <> Memory.op_kind_split to1' msg2'))\n      (LOCTS2: forall (LOC: loc1 = loc2)\n                 (KIND1: kind1 = Memory.op_kind_add)\n                 (KIND2: kind2 = Memory.op_kind_add)\n                 (MSG1: msg1 <> Message.reserve),\n               Time.lt to2 to1):\n  exists kind2' lc1' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2'>> /\\\n    <<STEP2: __guard__\n               ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                ((loc1, to1) <> (loc2, to2) /\\\n                 exists from1' kind1',\n                   <<STEP2: Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'>>))>> /\\\n    <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>.\nProof.\n  guardH NONPF.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto; try by viewtac. i. des.\n  exploit reorder_promise_promise; try exact STEP1; eauto; ss.\n  { i. subst.\n    exploit Memory.promise_op; eauto. i.\n    econs. eapply TViewFacts.op_closed_released; try exact x0; eauto.\n    inv STEP1. apply LOCAL0.\n  }\n  i. des.\n  unguardH STEP5. des.\n  - inv STEP5.\n    exploit promise_fulfill_write; try exact STEP4; eauto.\n    { i. hexploit ORD; eauto. i.\n      eapply promise_step_nonsynch_loc_inv; try exact STEP1; eauto.\n    }\n    { inv STEP1. ss. }\n    i. esplits; eauto. left; eauto.\n  - exploit Local.promise_step_future; try exact STEP4; eauto. i. des.\n    exploit reorder_promise_fulfill; try exact STEP6; eauto.\n    { i. eapply STEP6; eauto. }\n    i. des.\n    exploit fulfill_step_future; try exact STEP7; try exact WF0; eauto; try by viewtac. i. des.\n    exploit promise_fulfill_write; try exact STEP4; eauto; try by viewtac.\n    { i. hexploit ORD; eauto. i.\n      eapply promise_step_nonsynch_loc_inv; try exact STEP1; eauto.\n    }\n    { subst. inv STEP1. ss. }\n    i. esplits; eauto. right. esplits; eauto.\nQed.\n\nLemma reorder_promise_write\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2)\n      (NONPF: Memory.op_kind_is_lower kind1 = false \\/ ~ Message.is_released_none msg1)\n      (REL_WF: View.opt_wf releasedm2)\n      (REL_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (LOCAL0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (CONS: Local.promise_consistent lc2):\n  (exists kind2' lc1' mem1',\n     <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2'>> /\\\n     <<STEP2: __guard__\n                ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                 ((loc1, to1) <> (loc2, to2) /\\\n                  exists from1' kind1', <<STEP2: Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'>>))>> /\\\n     <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>).\nProof.\n  guardH NONPF. eapply reorder_promise_write_aux; eauto.\n  { i. subst. split.\n    - ii. subst. ss. inv STEP1.\n      exploit Memory.promise_get2; eauto. i. des. inv PROMISE.\n      exploit promise_consistent_promise_write; eauto; try by destruct msg1. i.\n      inv MEM. inv SPLIT. timetac.\n    - ii. subst. ss. inv STEP1.\n      exploit Memory.promise_get2; eauto. i. des. inv PROMISE.\n      exploit promise_consistent_promise_write; eauto. i.\n      exploit Memory.split_get0; try exact PROMISES. i. des.\n      inv STEP2. ss. inv WRITE. inv PROMISE.\n      exploit Memory.split_get0; try exact PROMISES0. i. des.\n      rewrite GET2 in *. inv GET4.\n      inv MEM1. inv SPLIT. timetac. }\n  { i. subst. inv STEP1. inv PROMISE.\n    exploit Memory.add_get0; try exact PROMISES. i. des.\n    exploit promise_consistent_promise_write; try exact GET0; eauto; ss. i.\n    inv x0; ss. inv H.\n    inv STEP2. inv WRITE. inv PROMISE. ss.\n    exploit Memory.add_get0; try exact MEM. i. des.\n    exploit Memory.add_get0; try exact MEM1. i. des. congr. }\nQed.\n\nLemma reorder_promise_write_memory\n      promises0 mem0\n      promises1 mem1\n      promises2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 msg2 kind2\n      (PROMISE: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1)\n      (WRITE: Memory.write promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 kind2)\n      (NONPF: Memory.op_kind_is_cancel kind1 = false)\n      (CONS: forall f t m\n               (GET: Memory.get loc2 t promises2 = Some (f, m))\n               (RESERVE: m <> Message.reserve),\n          Time.lt to2 t):\n  exists kind2' promises1' mem1',\n    (<<WRITE: Memory.write promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' kind2'>>) /\\\n    (<<PROMISE: __guard__\n                  ((promises2, mem2, loc1) = (promises1', mem1', loc2) \\/\n                   (exists from1' kind1',\n                       Memory.promise promises1' mem1' loc1 from1' to1 msg1 promises2 mem2 kind1' /\\\n                       Memory.op_kind_is_cancel kind1' = false))>>).\nProof.\n  exploit Memory.write_not_cancel; eauto. intro KIND2.\n  inv WRITE. inv PROMISE; inv PROMISE0; ss.\n  { (* add-add *)\n    exploit MemoryReorder.add_add; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.add_add; try exact MEM; eauto. i. des.\n    exploit MemoryReorder.add_remove; try exact ADD2; eauto. i. des.\n    esplits.\n    - econs; eauto. econs 1; eauto. i.\n      exploit Memory.add_get1; try exact MEM; eauto.\n    - right. esplits.\n      + econs 1; eauto. i.\n        revert GET. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        i. des. inv GET.\n        exploit Memory.add_get0; try exact ADD4. i. des.\n        exploit CONS; eauto. intros x.\n        inv MEM0. inv ADD. rewrite x in TO. timetac.\n      + ss.\n  }\n\n  { (* add-split *)\n    exploit MemoryReorder.add_split; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.add_split; try exact MEM; eauto. i.\n    des; subst; ss.\n    { clear x1 x2 x3 x4.\n      exploit MemoryReorder.add_remove; try exact ADD3; eauto.\n      { ii. inv H. inv ADD3. inv ADD. timetac. }\n      i. des. esplits.\n      - econs; eauto. econs 1; eauto. i.\n        exploit Memory.split_get0; try exact MEM0. i. des.\n        exploit Memory.add_get1; try exact MEM; eauto. i.\n        exploit Memory.get_disjoint; [exact GET1|exact x0|]. i. des.\n        + subst. inv ADD0. inv ADD. timetac.\n        + inv MEM0. inv SPLIT.\n          destruct (TimeFacts.le_lt_dec ts3 to').\n          * apply (x1 ts3); econs; ss; try refl. etrans; eauto.\n          * apply (x1 to'); econs; ss; try refl.\n            { exploit Memory.get_ts; try exact x0. i. des.\n              - subst. timetac.\n              - etrans; eauto.\n            }\n            { econs. ss. }\n            { exploit Memory.get_ts; try exact x0. i. des; ss.\n              subst. inv TS12.\n            }\n      - right. esplits.\n        + econs 1; eauto. i.\n          exploit Memory.add_get1; try exact GET; eauto.\n          erewrite Memory.split_o; eauto. repeat (condtac; ss).\n          { i. des. inv x0.\n            inv MEM0. inv SPLIT. rewrite TS12 in TS23. timetac. }\n          { guardH o. i. des. inv x0.\n            inv MEM0. inv SPLIT. timetac. }\n          guardH o. guardH o0.\n          erewrite Memory.add_o; eauto. condtac; ss; eauto.\n        + ss.\n    }\n    { exploit MemoryReorder.add_remove; try exact ADD0; try exact REMOVE; eauto.\n      { ii. inv H.\n        exploit Memory.add_get0; try exact PROMISES. i. des.\n        exploit Memory.split_get0; try exact PROMISES0. i. des.\n        exploit Memory.get_disjoint; [exact GET0|exact GET2|]. i. des.\n        { subst. inv MEM0. inv SPLIT. timetac. }\n        inv MEM0. inv SPLIT. apply (x0 to2); econs; ss; try refl.\n        - inv MEM. inv ADD. ss.\n        - econs. ss.\n      }\n      i. des. esplits; eauto.\n      right. esplits.\n      - econs 1; eauto. i. revert GET.\n        erewrite Memory.split_o; eauto. repeat (condtac; ss); eauto.\n        + i. des. inv GET.\n          exploit Memory.split_get0; try exact MEM0. i. des. revert GET0.\n          erewrite Memory.add_o; eauto. condtac; ss; eauto.\n          i. des. inv GET0. inv MEM. inv ADD. timetac.\n        + guardH o. i. des. inv GET.\n          exploit Memory.add_get0; try exact MEM. i. des.\n          exploit Memory.split_get0; try exact MEM0. i. des. congr.\n      - ss.\n    }\n  }\n\n  { (* add-lower *)\n    exploit MemoryReorder.add_lower; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.add_lower; try exact MEM; eauto. i.\n    des; subst; ss.\n    { clear x1 x2 x3 x4.\n      exploit Memory.add_get0; try exact x9. intros x. des.\n      exploit Memory.remove_exists; try exact GET0. i. des.\n      esplits.\n      - econs; try exact x0. econs 1; eauto. i.\n        eapply ATTACH; eauto. ii. subst.\n        inv MEM0. inv LOWER. inv MSG_LE. ss.\n      - left. f_equal. f_equal.\n        apply Memory.ext. i.\n        erewrite (@Memory.remove_o promises2); eauto.\n        erewrite (@Memory.remove_o mem3); eauto.\n    }\n    { exploit MemoryReorder.add_remove; try exact ADD0; eauto. i. des.\n      esplits; eauto. right. esplits.\n      - econs 1; eauto. i. revert GET.\n        erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n        i. des. inv GET.\n        exploit Memory.add_get0; try exact PROMISES. i. des.\n        exploit Memory.lower_get1; try exact GET0; eauto. i. des.\n        exploit Memory.remove_get1; try exact GET2; eauto. i. des; subst; ss.\n        exploit CONS; try exact GET1; eauto.\n        { ii. subst. inv MSG_LE. ss. }\n        intros x. inv PROMISES0. inv LOWER. rewrite TS1 in x. timetac.\n      - ss.\n    }\n  }\n\n  { (* split-add *)\n    exploit MemoryReorder.split_add; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.split_add; try exact MEM; eauto. i. des.\n    exploit MemoryReorder.split_remove; try exact SPLIT2; eauto. i. des.\n    esplits.\n    - econs; eauto. econs 1; eauto. i.\n      destruct (Memory.get loc2 to' mem1) as [[]|] eqn:GET'; cycle 1.\n      { revert GET'. erewrite Memory.split_o; eauto.\n        repeat condtac; ss. congr.\n      }\n      exploit Memory.split_get0; try exact MEM. i. des.\n      dup GET'. revert GET'. erewrite Memory.split_o; eauto.\n      repeat (condtac; ss).\n      + i. des. inv GET'. congr.\n      + guardH o. i. des. inv GET'.\n        rewrite GET in *. inv GET1. eauto.\n      + i. rewrite GET in *. inv GET'. eauto.\n    - right. esplits; eauto.\n  }\n\n  { (* split-split *)\n    assert (LOCTS: (loc1, ts3) <> (loc2, ts0)).\n    { ii. inv H.\n      exploit Memory.split_get0; try exact PROMISES. intros x. des.\n      exploit Memory.split_get0; try exact PROMISES0. intros x. des.\n      rewrite GET2 in *. inv GET4.\n      destruct (Memory.get loc2 from2 promises2) as [[]|] eqn:GET'.\n      { exploit CONS; try exact GET'.\n        - ii. subst. revert GET'.\n          erewrite Memory.remove_o; eauto. condtac; ss. guardH o.\n          erewrite Memory.split_o; eauto. repeat (condtac; ss); eauto.\n          + guardH o0. i. des. inv GET'. ss.\n          + guardH o0. guardH o1. i. rewrite GET' in *. inv GET1. ss.\n        - intros x. inv PROMISES0. inv SPLIT. rewrite x in TS12. timetac.\n      }\n      { revert GET'. erewrite Memory.remove_o; eauto. condtac; ss.\n        - des. subst. inv MEM0. inv SPLIT. timetac.\n        - erewrite Memory.split_o; eauto. repeat (condtac; ss); eauto. congr.\n      }\n    }\n    exploit MemoryReorder.split_split; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.split_split; try exact MEM; eauto. i.\n    des; subst; ss.\n    - exploit MemoryReorder.split_remove; try exact SPLIT3; try exact REMOVE; eauto.\n      { ii. inv H. inv MEM0. inv SPLIT. timetac. }\n      { ii. inv H. inv MEM. inv SPLIT. inv MEM0. inv SPLIT.\n        rewrite TS23 in TS2. timetac. }\n      i. des. esplits; eauto.\n      right. esplits; eauto.\n    - exploit MemoryReorder.split_remove; try exact SPLIT3; try exact REMOVE; eauto.\n      { ii. inv H.\n        exploit Memory.split_get0; try exact MEM. i. des.\n        exploit Memory.split_get0; try exact MEM0. i. des. congr. }\n      { ii. inv H.\n        exploit Memory.split_get0; try exact MEM. i. des.\n        exploit Memory.split_get0; try exact MEM0. i. des. congr. }\n      i. des. esplits; eauto.\n      right. esplits; eauto.\n  }\n\n  { (* split-lower *)\n    destruct (classic ((loc1, ts3) = (loc2, to2))).\n    { inv H. exfalso.\n      exploit Memory.split_get0; try exact PROMISES. i. des.\n      destruct (Memory.get loc2 to1 promises2) as [[]|] eqn:GET'.\n      { dup GET'. revert GET'.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        erewrite Memory.lower_o; eauto. condtac; ss.\n        i. rewrite GET' in *. inv GET1.\n        exploit CONS; try exact GET'0; eauto. intros x.\n        inv MEM. inv SPLIT. rewrite x in TS23. timetac.\n      }\n      { revert GET'.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        - des. subst. inv MEM. inv SPLIT. timetac.\n        - erewrite Memory.lower_o; eauto. condtac; ss. congr.\n      }\n    }\n    exploit MemoryReorder.split_lower_diff; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.split_lower_diff; try exact MEM; eauto. i.\n    des; subst; ss.\n    - clear x1 x2 x3 x4. esplits; eauto. left. ss.\n    - exploit MemoryReorder.split_remove; try exact SPLIT0; eauto. i. des.\n      esplits; eauto.\n      right. esplits; eauto.\n  }\n\n  { (* lower-add *)\n    exploit MemoryReorder.lower_add; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.lower_add; try exact MEM; eauto. i. des.\n    exploit MemoryReorder.lower_remove; try exact LOWER2; eauto. i. des.\n    esplits.\n    - econs; eauto. econs 1; eauto. i.\n      exploit Memory.lower_get1; try exact GET; eauto. i. des.\n      eapply ATTACH; try exact GET2; eauto.\n    - right. esplits; eauto.\n  }\n\n  { (* lower-split *)\n    exploit MemoryReorder.lower_split; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.lower_split; try exact MEM; eauto. i.\n    unguardH x0. unguardH x1. des; try inv FROM0; try inv FROM1; ss.\n    { exploit MemoryReorder.lower_remove; try exact LOWER0; eauto.\n      { ii. inv H. inv SPLIT0. inv SPLIT. timetac. }\n      i. des. esplits.\n      - econs; eauto. econs 2; eauto. ii. subst.\n        inv MEM. inv LOWER. inv MSG_LE. ss.\n      - right. esplits; eauto.\n    }\n    { inv FROM3. inv FROM2.\n      exploit MemoryReorder.lower_remove; try exact LOWER0; try exact REMOVE; eauto.\n      { ii. inv H.\n        exploit Memory.lower_get0; try exact MEM. i. des.\n        exploit Memory.split_get0; try exact MEM0. i. des. congr.\n      }\n      i. des. esplits; eauto. right. eauto.\n    }\n  }\n\n  { (* lower-lower *)\n    exploit MemoryReorder.lower_lower; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.lower_lower; try exact MEM; eauto. i.\n    des; subst; ss.\n    { esplits; eauto. left. ss. }\n    { exploit MemoryReorder.lower_remove; try exact LOWER3; eauto. i. des.\n      esplits; eauto. right. eauto.\n    }\n  }\nQed.\n\nLemma write_promise_consistent\n      ts\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (CONS: forall f t m\n               (GET: Memory.get loc t promises2 = Some (f, m))\n               (RESERVE: m <> Message.reserve),\n          Time.lt to t)\n      (TS: Time.lt ts to):\n  forall f t m\n    (GET: Memory.get loc t promises1 = Some (f, m))\n    (RESERVE: m <> Message.reserve),\n    Time.lt ts t.\nProof.\n  exploit Memory.write_not_cancel; eauto. i.\n  inv WRITE. inv PROMISE; ss; i.\n  - exploit Memory.add_get1; try exact GET; eauto. i.\n    exploit Memory.remove_get1; try exact x1; eauto. i. des.\n    { subst. exploit Memory.add_get0; try exact PROMISES. i. des. congr. }\n    exploit CONS; try exact GET2; eauto.\n  - exploit Memory.split_get1; try exact GET; eauto. i. des.\n    exploit Memory.remove_get1; try exact GET2; eauto. i. des.\n    { subst. exploit Memory.split_get0; try exact PROMISES. i. des. congr. }\n    exploit CONS; try exact GET0; eauto.\n  - exploit Memory.lower_get1; try exact GET; eauto. i. des.\n    exploit Memory.remove_get1; try exact GET2; eauto. i. des.\n    { subst. exploit Memory.lower_get0; try exact PROMISES. i. des. congr. }\n    exploit CONS; try exact GET0; eauto.\n    { ii. subst. inv MSG_LE. ss. }\nQed.\n\nLemma write_na_promise_consistent\n      ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n      (WRITE: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind)\n      (CONS: forall f t m\n               (GET: Memory.get loc t promises2 = Some (f, m))\n               (RESERVE: m <> Message.reserve),\n          Time.lt to t):\n  forall f t m\n    (GET: Memory.get loc t promises1 = Some (f, m))\n    (RESERVE: m <> Message.reserve),\n    Time.lt ts t.\nProof.\n  induction WRITE; eauto using write_promise_consistent.\nQed.\n\nLemma reorder_promise_write_na_memory\n      promises0 mem0\n      promises1 mem1\n      promises2 mem2\n      loc1 from1 to1 msg1 kind1\n      ts loc2 from2 to2 val2 msgs2 kinds2 kind2\n      (PROMISE: Memory.promise promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1)\n      (WRITE: Memory.write_na ts promises1 mem1 loc2 from2 to2 val2 promises2 mem2 msgs2 kinds2 kind2)\n      (NONPF: Memory.op_kind_is_cancel kind1 = false)\n      (CONS: forall f t m\n               (GET: Memory.get loc2 t promises2 = Some (f, m))\n               (RESERVE: m <> Message.reserve),\n          Time.lt to2 t):\n  exists kinds2' kind2' promises1' mem1',\n    <<WRITE: Memory.write_na ts promises0 mem0 loc2 from2 to2 val2 promises1' mem1' msgs2 kinds2' kind2'>> /\\\n    (<<PROMISE: __guard__\n                  ((promises2, mem2, loc1) = (promises1', mem1', loc2) \\/\n                   (exists from1' kind1',\n                       Memory.promise promises1' mem1' loc1 from1' to1 msg1 promises2 mem2 kind1'))>>).\nProof.\n  revert promises0 mem0 loc1 from1 to1 msg1 kind1 PROMISE NONPF.\n  induction WRITE; i.\n  { exploit reorder_promise_write_memory; eauto. i. des.\n    esplits; eauto.\n    unguardH PROMISE0. des; [left|right]; eauto.\n    }\n  exploit reorder_promise_write_memory; try exact PROMISE; eauto.\n  { eapply write_na_promise_consistent; eauto. }\n  i. unguardH x0. des.\n  { inv PROMISE0. esplits; eauto. left. ss. }\n  exploit IHWRITE; try exact PROMISE0; eauto.\n  intros x. unguardH x. des.\n  - inv PROMISE1. esplits; eauto. left. ss.\n  - esplits; eauto. right. esplits; eauto.\nQed.\n\nLemma reorder_promise_write_na\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 ord2 msgs2 kinds2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.write_na_step lc1 sc0 mem1 loc2 from2 to2 val2 ord2 lc2 sc2 mem2 msgs2 kinds2 kind2)\n      (NONPF: Memory.op_kind_is_cancel kind1 = false)\n      (LOCAL0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (CONS: Local.promise_consistent lc2):\n  (exists kinds2' kind2' lc1' mem1',\n     <<STEP1: Local.write_na_step lc0 sc0 mem0 loc2 from2 to2 val2 ord2 lc1' sc2 mem1' msgs2 kinds2' kind2'>> /\\\n     <<STEP2: __guard__\n                ((lc2, mem2, loc1) = (lc1', mem1', loc2) \\/\n                 (exists from1' kind1',\n                     <<STEP2: Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'>>))>>).\nProof.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit Local.write_na_step_future; eauto. i. des.\n  inv STEP1. inv STEP2. ss.\n  exploit reorder_promise_write_na_memory; eauto.\n  { i. exploit CONS; eauto. s. i.\n    eapply TimeFacts.le_lt_lt; eauto.\n    unfold TimeMap.join, TimeMap.singleton, Loc.LocFun.add, Loc.LocFun.find.\n    condtac; ss. apply Time.join_r.\n  }\n  i. des. esplits; eauto.\n  unguardH PROMISE0. des.\n  - inv PROMISE0. left. ss.\n  - right. esplits. econs; eauto.\n    eapply Memory.future_closed_message; eauto.\nQed.\n\n\n#[export] Hint Constructors Thread.program_step: core.\n#[export] Hint Constructors Thread.step: core.\n\nLemma reorder_nonpf_program\n      lang\n      e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang false e1 th0 th1)\n      (STEP2: Thread.program_step e2 th1 th2)\n      (CONS2: Local.promise_consistent (Thread.local th2))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n      (MEMORY: Memory.closed (Thread.memory th0)):\n  exists th1',\n     <<STEP1: Thread.program_step e2 th0 th1'>> /\\\n     <<STEP2: __guard__ (th2 = th1' \\/ exists pf2' e2', Thread.promise_step pf2' e2' th1' th2)>>.\nProof.\n  exploit Thread.step_future; eauto. i. des.\n  inv STEP1. inv STEP. ss. inv STEP2. inv LOCAL1; ss.\n  - (* silent *)\n    esplits; eauto.\n    right. esplits. econs; eauto.\n  - (* read *)\n    exploit reorder_promise_read; try exact LOCAL0; eauto; try by viewtac.\n    { ii. inv H.\n      inv LOCAL0. exploit Memory.promise_get2; eauto.\n      { destruct kind, msg; ss. }\n      i. des.\n      dup LOCAL2. inv LOCAL0. ss.\n      rewrite GET in *. inv GET_MEM.\n      hexploit promise_consistent_promise_read; eauto. i. timetac.\n    }\n    i. des. esplits.\n    + econs; eauto.\n    + right. esplits. econs; eauto.\n  - (* write *)\n    exploit reorder_promise_write; try exact LOCAL0; eauto.\n    { destruct kind, msg; ss; eauto. repeat condtac; ss; eauto. }\n    { destruct kind, msg; ss. }\n    i. des. esplits.\n    + econs; eauto.\n    + unguardH STEP2. des.\n      * inv STEP2. left. auto.\n      * right. esplits. econs; eauto.\n  - (* update *)\n    exploit reorder_promise_read; try exact LOCAL1; eauto; try by viewtac.\n    { ii. inv H.\n      inv LOCAL0. exploit Memory.promise_get2; eauto.\n      { destruct kind, msg; ss. }\n      i. des.\n      dup LOCAL2. inv LOCAL0. ss.\n      rewrite GET in *. inv GET_MEM.\n      exploit promise_consistent_promise_read; eauto.\n      { eapply write_step_promise_consistent; eauto. }\n      i. eapply Time.lt_strorder. eauto.\n    }\n    i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit reorder_promise_write; try exact LOCAL2; eauto; try by viewtac.\n    { destruct kind, msg; ss; eauto. repeat condtac; ss; eauto. }\n    { destruct kind, msg; ss. }\n    i. des. esplits.\n    + econs; eauto.\n    + unguardH STEP3. des.\n      * inv STEP3. left. auto.\n      * right. esplits. econs; eauto.\n  - (* fence *)\n    inv LOCAL0. inv LOCAL2.\n    esplits; eauto.\n    + econs; eauto. econs 5; eauto. econs; eauto; cycle 1.\n      { i. subst. ss. erewrite PROMISES in *; eauto.\n        eapply Memory.ext. i. erewrite Memory.bot_get.\n        destruct (Memory.get loc0 ts (Local.promises lc1)) as [[from0 msg0]|] eqn:GET; auto.\n        eapply Memory.promise_get1_promise in GET; try apply PROMISE.\n        { des. erewrite Memory.bot_get in *. ss. }\n        { destruct kind; ss. }\n      }\n      ss. intros ORDW l. eapply promise_step_nonsynch_loc_inv; eauto.\n      * destruct msg, kind; ss; eauto. repeat condtac; ss; eauto.\n      * apply RELEASE. ss.\n    + right. esplits. econs; eauto.\n  - (* syscall *)\n    inv LOCAL0. inv LOCAL2.\n    esplits; eauto.\n    + econs; eauto. econs 6; eauto. econs; eauto; cycle 1.\n      { i. subst. ss. erewrite PROMISES in *; eauto.\n        eapply Memory.ext. i. erewrite Memory.bot_get.\n        destruct (Memory.get loc0 ts (Local.promises lc1)) as [[from0 msg0]|] eqn:GET; auto.\n        eapply Memory.promise_get1_promise in GET; try apply PROMISE.\n        { des. erewrite Memory.bot_get in *. ss. }\n        { destruct kind; ss. }\n      }\n      intros ORDW l. eapply promise_step_nonsynch_loc_inv; eauto.\n      * destruct msg, kind; ss; eauto. repeat condtac; ss; eauto.\n      * apply RELEASE. ss.\n    + right. esplits. econs; eauto.\n  - (* failure *)\n    inv LOCAL2.\n    hexploit promise_step_promise_consistent; eauto. i.\n    esplits; eauto.\n    right. esplits. econs; eauto.\n  - (* na write *)\n    exploit reorder_promise_write_na; try exact LOCAL0; eauto.\n    { destruct kind, msg; ss. }\n    i. des. esplits.\n    + econs; eauto.\n    + unguardH STEP2. des.\n      * inv STEP2. left. auto.\n      * right. esplits. econs; eauto.\n  - (* racy read *)\n    inv LOCAL0. inv LOCAL2. inv RACE. ss.\n    exploit MemoryFacts.promise_get_inv_diff; try exact PROMISE; eauto.\n    { ii. inv H.\n      exploit Memory.promise_get2; try exact PROMISE; try by (destruct kind; ss). i. des. congr. }\n    i. des.\n    destruct (Memory.get loc0 to0 lc1.(Local.promises)) as [[]|] eqn:GETP1.\n    { exploit Memory.promise_get1_promise; eauto; try by (destruct kind; ss). i. des. congr. }\n    esplits; eauto. right. esplits. econs; eauto.\n  - (* racy write *)\n    inv LOCAL0. inv LOCAL2. inv RACE. ss.\n    hexploit promise_step_promise_consistent; eauto. i.\n    exploit MemoryFacts.promise_get_inv_diff; try exact PROMISE; eauto.\n    { ii. inv H0.\n      exploit Memory.promise_get2; try exact PROMISE; try by (destruct kind; ss). i. des. congr. }\n    i. des.\n    destruct (Memory.get loc0 to0 lc1.(Local.promises)) as [[]|] eqn:GETP1.\n    { exploit Memory.promise_get1_promise; eauto; try by (destruct kind; ss). i. des. congr. }\n    esplits; eauto. right. esplits. econs; eauto.\n  - (* racy update *)\n    hexploit promise_step_promise_consistent; eauto. i.\n    inv LOCAL0. inv LOCAL2; ss.\n    { esplits; eauto. right. esplits. econs; eauto. }\n    { esplits; eauto. right. esplits. econs; eauto. }\n    inv RACE. ss.\n    exploit MemoryFacts.promise_get_inv_diff; try exact PROMISE; eauto.\n    { ii. inv H0.\n      exploit Memory.promise_get2; try exact PROMISE; try by (destruct kind; ss). i. des. congr. }\n    i. des.\n    destruct (Memory.get loc0 to0 lc1.(Local.promises)) as [[]|] eqn:GETP1.\n    { exploit Memory.promise_get1_promise; eauto; try by (destruct kind; ss). i. des. congr. }\n    esplits; eauto.\n    right. esplits. econs; eauto.\nQed.\n\nLemma reorder_nonpf_pf\n      lang\n      e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang false e1 th0 th1)\n      (STEP2: Thread.step true e2 th1 th2)\n      (CONS2: Local.promise_consistent (Thread.local th2))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n      (MEMORY: Memory.closed (Thread.memory th0)):\n  (th0 = th2) \\/\n  (exists pf2' e2',\n      <<STEP: Thread.step pf2' e2' th0 th2>> /\\\n      <<EVENT: __guard__ (e2' = e2 \\/ (ThreadEvent.is_promising e2' /\\ ThreadEvent.is_promising e2))>>) \\/\n  (exists e2' pf1' e1' th1',\n      <<STEP1: Thread.step true e2' th0 th1'>> /\\\n      <<STEP2: Thread.promise_step pf1' e1' th1' th2>> /\\\n      <<EVENT: __guard__ (e2' = e2 \\/ (ThreadEvent.is_promising e2' /\\ ThreadEvent.is_promising e2))>>).\nProof.\n  inv STEP2; ss.\n  - inv STEP. ss.\n    inv STEP1. inv STEP. ss.\n    destruct kind; ss.\n    + destruct msg1, msg; ss; cycle 1.\n      { inv LOCAL0. inv PROMISE. inv MEM. inv LOWER. inv MSG_LE. }\n      { inv LOCAL0. inv PROMISE. inv MEM. inv LOWER. inv MSG_LE. }\n      destruct released0; ss.\n      exploit reorder_promise_promise_lower_None; eauto.\n      { destruct kind0; ss. }\n      i. des; subst.\n      * right. left. esplits.\n        { econs 1. econs; eauto. }\n        { right. ss. }\n      * right. right. esplits.\n        { econs 1. econs; eauto. }\n        { econs; eauto. }\n        { right. ss. }\n    + exploit reorder_promise_promise_cancel; eauto.\n      i. des; subst; eauto.\n      right. right. esplits.\n      { econs 1. econs; eauto. }\n      { econs; eauto. }\n      { right. ss. }\n  - exploit reorder_nonpf_program; eauto. i. des.\n    unguardH STEP2. des.\n    + subst. right. left. esplits; eauto. left. ss.\n    + right. right. esplits; eauto. left. ss.\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/ReorderPromise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.18655886681841916}}
{"text": "Require Export sem_common.\nRequire Export OSQPostPure.\n\nOpen Scope code_scope.\n\nLemma sempost_ltu_trans:\n  forall n,\n    Int.ltu n ($ 65535) = true ->\n    Int.ltu (n+\u1d62$ 1) ($ 65536) = true.\nProof.\n  int auto.\n  int auto.\nQed.  \n\nLemma sempost_inc_cnt_prop:\n  forall s P a msgq mq a' msgq' mq' n i x2 x3 x4 qid b tcbls,\n    s |= AEventData a msgq ** P ->\n    RLH_ECBData_P msgq mq ->\n    R_ECB_ETbl_P qid (a,b) tcbls ->\n    a = (V$OS_EVENT_TYPE_SEM :: Vint32 i :: Vint32 n :: x2 :: x3 :: x4 :: nil) ->\n    msgq = DSem n ->\n    mq = (abssem n, nil) ->\n    a' = (V$OS_EVENT_TYPE_SEM :: Vint32 i :: Vint32 (n+\u1d62$ 1)  :: x2 :: x3 :: x4 :: nil) ->\n    msgq' = DSem (n+\u1d62$ 1) ->\n    mq' = (abssem (n+\u1d62$ 1), nil) ->\n    Int.ltu n ($ 65535) = true ->\n    s |= AEventData a' msgq' **\n         [| RLH_ECBData_P msgq' mq' |] ** \n         [| R_ECB_ETbl_P qid (a',b) tcbls |] ** P. \nProof.\n  intros.\n  sep pauto.\n  unfold AEventData in *.\n  sep pauto.\n\n\n  apply sempost_ltu_trans; auto.\n  unfold RLH_ECBData_P in *.\n  destruct H0.\n  split.\n  auto.  \n  unfold RH_ECB_P in *.\n  destruct H2.\n  split.\n  intros.\n  auto.\n  intros.\n  tryfalse.\nQed.\n\nLemma something_in_not_nil : forall (T:Type) (y: @list T), y<>nil -> exists x, In x y.\nProof.\n  intros T y.\n  elim y.\n  intro; tryfalse.\n  intros.\n  exists a.\n  simpl.\n  left; auto.\nQed.\n\nLemma rg1 :  forall x2 x6 ,  0 <= Int.unsigned x2 < 64->\n                             x6 = $ Int.unsigned x2&\u1d62$ 7 ->\n                             0<= Int.unsigned x6 < 8.\nProof.\n  intros.\n  subst x6.\n\n  mauto.\nQed.\n\nLemma rg2 :  forall x2 x7 ,  0 <= Int.unsigned x2 < 64->\n                             x7 = Int.shru ($ Int.unsigned x2) ($ 3) ->\n                             0<= Int.unsigned x7 < 8.\nProof.\n  intros.\n  subst x7.\n  mauto.\nQed.\n\nLemma sempost_grp_wls_nil:\n  forall (v'36 v'13 : vallist) (v'12 : int32) \n         (v'32 : block) (v'15 : int32) (v'24 : val) \n         (v'35 v'0 : val) (v'8 : tid) (v'9 v'11 : EcbMod.map)\n         x  (x1 : waitset)\n         (v'6 v'10 : EcbMod.map) (v'38 v'69 v'39 : int32) \n         (v'58 : block) (a : priority)\n         (c : msg) (v'62 v'7 : TcbMod.map) \n         (vhold : addrval),\n    v'12 = Int.zero ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_SEM\n                   :: Vint32 v'12\n                   :: Vint32 x :: v'24 :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig (v'32, Int.zero) (abssem x , x1) v'6 v'10 ->\n    x1 = nil.\nProof.\n  intros.\n  unfolds in H2.\n  destruct H2 as (H2 & H2' & _).\n  destruct H2 as (_ & H2 & _ & _).\n  destruct H2' as (_ & H2' & _ & _).\n  unfolds in H2.\n  unfolds in H2'.\n  \n\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  destruct H3 as (_ & H3 & _ & _).\n  unfolds in H3.\n  destruct H3 as (H3 & H3').\n\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  assert ( x1 = nil \\/ x1 <> nil) by tauto.\n  destruct H4; intros; auto.\n\n  idtac.\n  apply something_in_not_nil in H4.\n  inversion H4.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (abssem x, x1) /\\ In x0 x1) by tauto.\n  lets aadf : H3 H6.\n  mytac.\n  lets bbdf : H2' H10.\n  destruct bbdf.\n  unfolds in H.\n  do 3 destruct H.\n  destruct H as (Ha & Hb & Hc & Hd& He).\n  cut ( 0<=(\u2218(Int.unsigned x7)) <8)%nat.\n  intro.\n  assert (V$0 = V$0) by auto.\n  lets adfafd : H1 H Hd H12.\n  destruct adfafd.\n  destruct H13.\n  destruct H14.\n  cut ( $ 0&\u1d62($ 1<<\u1d62$ Z.of_nat \u2218(Int.unsigned x7)) = $ 0).\n  intro.\n  apply H13 in H17.\n  subst x8.\n\n  lets rg : rg1 Ha Hb.\n  clear -He rg.\n  false.\n  gen He.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\nQed.\n\nLemma post_exwt_succ_pre_sem\n     : forall (v'36 v'13 : vallist) (v'12 : int32) \n         (v'32 : block) (v'24 : block) \n         (v'35 v'0 : val) (v'8 : tid) (v'9 v'11 : EcbMod.map)\n         x (x1 : waitset)\n         (v'6 v'10 : EcbMod.map) (v'38 v'69 v'39 : int32) \n         (v'58 : block) (a : priority) (b : taskstatus) \n         (c :msg) (v'62 v'7 : TcbMod.map) \n         (vhold : addrval),\n       v'12 <> Int.zero ->\n       R_PrioTbl_P v'36 v'7 vhold ->\n       RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n       R_ECB_ETbl_P (v'32, Int.zero)\n         (V$OS_EVENT_TYPE_SEM\n          :: Vint32 v'12\n             :: Vint32 x :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n         v'13) v'7 ->\n       RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n       EcbMod.join v'9 v'10 v'11 ->\n       EcbMod.joinsig (v'32, Int.zero) (abssem x , x1) v'6 v'10 ->\n       Int.unsigned v'12 <= 255 ->\n       array_type_vallist_match Int8u v'13 ->\n       length v'13 = \u2218OS_EVENT_TBL_SIZE ->\n       nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n       Int.unsigned v'38 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n       Int.unsigned v'69 <= 255 ->\n       nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n       Int.unsigned v'39 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39))) v'36 =\n       Vptr (v'58, Int.zero) ->\n       TcbJoin (v'58, Int.zero) (a, b, c) v'62 v'7 ->\n       x1 <> nil /\\\n       GetHWait v'7 x1 (v'58, Int.zero) /\\\n       TcbMod.get v'7 (v'58, Int.zero) = Some (a, b, c) /\\ a = ((v'38<<\u1d62$ 3)+\u1d62v'39).\nProof.\n  intros.\n  lets Hs :  tcbjoin_get_a  H16.\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  unfolds in H2.\n  destruct H2.\n  destruct H17 as (H17&Htype).\n  unfolds in H2.\n  unfolds in H17.\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  clear H16.\n  assert ( Int.unsigned v'38 < 8) as Hx by omega.\n  assert (Int.unsigned v'39 < 8) as Hy by omega.\n  clear H10 H12.\n  lets Hrs : math_xy_prio_cons Hx Hy.\n  unfold nat_of_Z in H0.\n  destruct H0 as (Hpr1 & Hpr2).\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  destruct Hpr2.\n  apply H0 in Hs.\n  destruct Hs;auto.\n  lets Hnth : nth_val'_imp_nth_val_vptr H15.\n  lets Hsd : Hpr1 Hrs Hnth.\n  destruct Hsd as (st & m & Hst);auto.\n  unfold get in Hst; simpl in Hst.\n  rewrite Hs in Hst.\n  inverts Hst.\n  assert (Int.shru ((v'38<<\u1d62$ 3)+\u1d62v'39) ($ 3)= v'38).\n  eapply math_shrl_3_eq; eauto.\n  eapply nat_8_range_conver; eauto.\n  assert ( (Z.to_nat (Int.unsigned v'38))  < length v'13)%nat.\n  rewrite H8.\n  simpl.\n  unfold Pos.to_nat; simpl.\n  clear - Hx.\n  mauto.\n  lets Has : array_int8u_nth_lt_len H7 H4.\n  destruct Has as (i & Hnthz & Hinsa).\n  rewrite H11 in Hnthz.\n  inverts Hnthz.\n  assert ((((v'38<<\u1d62$ 3)+\u1d62v'39)&\u1d62$ 7) = v'39).\n  eapply math_8range_eqy; eauto.\n  eapply  nat_8_range_conver; eauto.\n  apply nth_val'_imp_nth_val_int in H11.\n  assert ( Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 H11 H10.\n  eapply  nat_8_range_conver; eauto.\n  destruct Hzs.\n  lets Has : math_8_255_eq H6 H9 H.\n  assert (i <> $ 0).\n  assert ($ 1<<\u1d62$ Z.of_nat \u2218(Int.unsigned v'38) = $ 1<<\u1d62v'38).\n  clear -Hx.\n  mauto.\n  rewrite H18 in H16.\n  apply H16 in Has.\n  apply ltu_eq_false in Has.\n  pose (Int.eq_spec i ($0)).\n  rewrite Has in y.\n  auto.\n  assert (PrioWaitInQ (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39)) v'13).\n  unfolds.\n  rewrite Int.repr_unsigned in *.\n  exists ( ((v'38<<\u1d62$ 3)+\u1d62v'39)&\u1d62$ 7 ).\n  exists (Int.shru ((v'38<<\u1d62$ 3)+\u1d62v'39) ($ 3) ).\n  rewrite H0 in *.\n  exists i.\n  splits; eauto.\n  rewrite H5.\n  eapply math_8_255_eq; eauto.\n  destruct H2 as (H2'&H2&H2''&Hres).\n  lets Hes : H2 H19.\n  unfold V_OSEventType in Hes.\n  simpl nth_val in Hes.\n  assert (Some (V$OS_EVENT_TYPE_SEM) = Some (V$OS_EVENT_TYPE_SEM)) by auto.\n  apply Hes in H20.\n  clear Hes.\n  rename H20 into Hes.\n  destruct Hes as (td & nn &mm & Hge).\n  destruct Hpr2 as (Hpr2 & Hpr3).\n  unfolds in Hpr3.\n  assert (td = (v'58, Int.zero)  \\/ td <> (v'58, Int.zero) ) by tauto.\n  destruct H20.\n  Focus 2.\n  lets Hass : Hpr3 H20 Hge Hs.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  rewrite Int.repr_unsigned in *.\n  subst td.\n  unfold get in Hge; simpl in Hge.\n  rewrite Hs in Hge.\n  inverts Hge.\n  destruct H3 as (H3'&H3&H3''&Hres').\n  destruct H3 as (Heg1 & Heg2).\n  lets Hrgs : Heg2 Hs.\n  destruct Hrgs as (xz &  qw & Hem & Hin).\n  unfold get in Hem; simpl in Hem.\n  rewrite Hg in Hem.\n  inverts Hem.\n\n\n  assert (qw = nil \\/ qw <> nil) by tauto.\n  destruct H3.\n  subst qw.\n  simpl in Hin; tryfalse.\n  splits; auto.\n  unfolds.\n  splits; auto.\n  do 3 eexists; splits; eauto.\n  intros.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (abssem xz, qw) /\\ In t' qw) .\n  splits; auto.\n  lets Habs : Heg1 H22.\n  destruct Habs as (prio' & m' & n' & Hbs).\n  do 3 eexists; splits; eauto.\n  destruct H17 as (H17'&H17&H17''&Hres'').\n  lets Hpro : H17 Hbs.\n  destruct Hpro as (Hpro&Hss).\n  clear Hss.\n  unfolds in Hpro.\n  destruct Hpro as (xa & xb & zz & Hran & Hxx & Hyy & Hnths & Hzz).\n  subst xa xb.\n  rewrite Int.repr_unsigned in *.\n  lets Hat : math_highest_prio_select H13 H9 H11 Hnths  Hzz;\n    try eapply int_usigned_tcb_range; try omega;\n    eauto.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 Hnths H23.\n  eapply nat_8_range_conver; eauto.\n  try eapply int_usigned_tcb_range; eauto.  \n  destruct Hzs.\n  assert (zz = $ 0 \\/ zz <> $ 0) by tauto.\n  destruct H26.\n  subst zz.\n  rewrite Int.and_commut in Hzz.\n  rewrite Int.and_zero in Hzz.\n  unfold Int.one in *.\n  unfold Int.zero in *.\n  assert ($ 1<<\u1d62(prio'&\u1d62$ 7) <> $ 0 ).\n  eapply math_prop_neq_zero2; eauto.\n  tryfalse.\n  assert (Int.ltu ($ 0) zz = true).\n  clear - H26.\n  int auto.\n  assert (0<=Int.unsigned zz ).\n  int auto.\n  assert (Int.unsigned zz = 0).\n  omega.\n  rewrite <- H0 in H26.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  apply H25 in H27.\n  assert ($ Z.of_nat \u2218(Int.unsigned (Int.shru prio' ($ 3))) = (Int.shru prio' ($ 3))).\n  clear -Hran.\n  mauto.\n  rewrite H28 in *.\n  auto.\n  lets Hasss : Hpr3 H20 Hs Hbs; eauto.\n  unfolds.\n  rewrite zlt_true; auto.\n  assert (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) < Int.unsigned prio' \\/\n          Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) = Int.unsigned prio').\n  omega.\n  destruct H23; auto; tryfalse.\n  false.\n  apply Hasss.\n  apply unsigned_inj; eauto.\nQed.\n\n\nLemma sem_post_get_tcb_stat\n: forall (p : int32) (etbl : vallist) (ptbl : list val) \n         (tid : addrval) (tcbls : TcbMod.map) (abstcb : abstcb.B)\n         (tcbls' : TcbMod.map) (vl rtbl : vallist) \n         (qid : addrval) (vle : list val) (vhold : addrval),\n    0 <= Int.unsigned p < 64 ->\n    array_type_vallist_match Int8u etbl ->\n    length etbl = \u2218OS_EVENT_TBL_SIZE ->\n    prio_in_tbl p etbl ->\n    nth_val' (Z.to_nat (Int.unsigned p)) ptbl = Vptr tid ->\n    R_PrioTbl_P ptbl tcbls vhold ->\n    TcbJoin tid abstcb tcbls' tcbls ->\n    TCBNode_P vl rtbl abstcb ->\n    R_ECB_ETbl_P qid (V$OS_EVENT_TYPE_SEM :: vle, etbl) tcbls ->\n    V_OSTCBStat vl = Some (V$OS_STAT_SEM).\nProof.\n  introv Hran Harr Hlen Hpri Hnth Hr Htj Htn Hre.\n  unfolds in Hre.\n  destruct Hre as (Hre1 & Hre2 & Hre3).\n  unfolds in Hre2.\n  destruct Hre1 as (Hre1'&Hre1&Hre1''& _).\n  unfolds in Hre1.\n  unfolds in Htn.\n  destruct abstcb.\n  destruct p0.\n  destruct Htn as (Hv1 & Hv2 &  Hrl & Hrc).\n  funfold Hrl.\n  rewrite H8 in H4.\n  inverts H4.\n  unfolds in Hrc.\n  destruct Hrc as (_&_&_&Hrc).\n  unfolds in Hrc.\n  destruct Hrc as (_&Hrc&_&_&_).\n  unfolds in Hrc.\n  unfolds in Hpri.\n  lets Hges : tcbjoin_get_a Htj.\n  unfolds in Hr.\n  destruct Hr.\n  apply nth_val'_imp_nth_val_vptr in Hnth.\n  lets Hs : H Hnth; eauto.\n  assert (tid <> vhold) as Hnvhold.\n  apply H4 in Hges;destruct Hges;auto.\n  destruct Hs as (st & mm & Hgs);auto.\n  unfold get in Hgs; simpl in Hgs.\n  rewrite Hges in Hgs.\n  inverts Hgs.\n  assert (PrioWaitInQ (Int.unsigned p) etbl).\n  unfolds.\n  rewrite Int.repr_unsigned.\n  remember (Int.shru p ($3)) as py.\n  remember ( p&\u1d62$ 7) as px.\n  lets Hrs : n07_arr_len_ex \u2218(Int.unsigned py)  Harr Hlen.\n  subst py.\n  clear - H17.\n  mauto.\n  destruct Hrs as (vx & Hntht & Hin).\n  do 3 eexists; splits; eauto.\n  assert ( V_OSEventType (V$OS_EVENT_TYPE_SEM :: vle) = Some (V$OS_EVENT_TYPE_SEM)).\n  unfolds.\n  simpl; auto.\n  lets Hsd : Hre1 H15 H20.\n  mytac.\n  rewrite Int.repr_unsigned in H22.\n  assert (x = tid \\/ x <> tid) by tauto.\n  destruct H23.\n  subst x.\n  unfold get in H22; simpl in H22.\n  rewrite Hges in H22.\n  inverts H22.\n  eapply Hrc; eauto.\n  unfolds in H21.\n  lets Hfs : H21 H23 H22 Hges.\n  tryfalse.\nQed. \n\n\nLemma le7_le7_range64:  forall v'57 v'59, Int.unsigned v'57 <= 7 -> Int.unsigned v'59 <= 7 ->  0 <= Int.unsigned ((v'57<<\u1d62$ 3)+\u1d62v'59) < 64.\n  intros.\n  mauto.\nQed.\n\nLemma TCBList_P_post_sem: (*tcblist_P_post_mbox *)\n forall (v'42 : val) (v'48 : list vallist) (v'47 : TcbMod.map)\n         (v'60 : val) (v'50 : list vallist) (v'37 : vallist)\n         (v'59 v'49 v'44 : TcbMod.map) (v'63 v'64 v'65 : val)\n         (v'51 v'52 v'53 v'54 v'55 v'56 : int32) (x00 : addrval)\n         (v'58 : block) (v'40 v'38 : int32) (prio : priority)\n         (st : taskstatus) (msg0 msg1:msg)\n         (v'7 v'62 v'43 : TcbMod.map) (v'36 : vallist) \n         (v'39 : int32) (v'13 : vallist) (vhold : addrval),\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    prio_in_tbl ((v'38<<\u1d62$ 3)+\u1d62v'39) v'13 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = \u2218OS_RDY_TBL_SIZE ->\n    TcbMod.join v'44 v'43 v'7 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'62 v'7 ->\n    get_last_tcb_ptr v'48 v'42 = Some (Vptr (v'58, Int.zero)) ->\n    TCBList_P v'42 v'48 v'37 v'47 ->\n    TCBList_P v'60 v'50 v'37 v'59 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'59 v'49 ->\n    TcbMod.join v'47 v'49 v'44 ->\n    TCBNode_P\n      (v'60\n         :: v'63\n         :: v'64\n         :: v'65\n         :: Vint32 v'51\n         :: V$OS_STAT_SEM\n         :: Vint32 v'52\n         :: Vint32 v'53\n         :: Vint32 v'54\n         :: Vint32 v'55 :: Vint32 v'56 :: nil) v'37\n      (prio, st, msg0) ->\n    TCBList_P v'42\n              (v'48 ++\n                    (v'60\n                       :: v'63\n                       :: Vnull\n                       :: msg1\n                       :: V$0\n                       :: V$0\n                       :: Vint32 v'52\n                       :: Vint32 v'53\n                       :: Vint32 v'54\n                       :: Vint32 v'55 :: Vint32 v'56 :: nil)\n                    :: v'50)\n              (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37)\n                                     (Vint32 v'40))))\n              (TcbMod.set v'44 (v'58, Int.zero) (prio, rdy, msg1)).\nProof.\n  intros.\n  unfolds in H5.\n  destruct H5 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) < 64).\n  clear -H H0.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H4.\n  lets Hps : Ha1 H5 H4.\n  \n  lets Hgs : tcbjoin_get_a H9.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in Hgs.\n  destruct Hgs;auto.\n  apply Hps in Hnvhold.\n  clear Hps.\n  mytac.\n  unfold get in H17; simpl in H17.\n  rewrite H17 in Hgs.\n  inverts Hgs.\n  remember ((v'38<<\u1d62$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+\u1d62py) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  lets Hps : tcbjoin_set_ex (prio,st,msg0) (prio,rdy,msg1)  H14;eauto.\n  destruct Hps as (b&Htx & Hty).\n  remember (val_inj\n              (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))) as Hv.\n  assert (0<= Z.to_nat (Int.unsigned v'38) <8)%nat.\n  clear -H.\n  mauto.\n  lets Hsx : n07_arr_len_ex H6 H7; eauto.\n  destruct Hsx as (vx & Hnth & Hi).\n  lets Hns :  nth_val_nth_val'_some_eq  Hnth.\n  rewrite Hns in HeqHv.\n  simpl in HeqHv.\n  subst Hv.\n  assert (v'38 = Int.shru prio ($ 3)).\n  subst.\n  clear - H H0.\n  mauto.\n  rewrite H19.\n  assert (v'40 = ($ 1<<\u1d62(prio &\u1d62$ 7))).  \n  rewrite Heqprio.\n  rewrite Heqpx.\n  assert ((((v'38<<\u1d62$ 3)+\u1d62py)&\u1d62$ 7) = py).\n  clear -H H0.\n  mauto.\n  rewrite H20.\n  clear -H0 H1.\n  unfold OSMapVallist in H1.\n  (* ** ac: SearchAbout OSMapVallist. *)\n  eapply math_mapval_core_prop; eauto.\n  mauto.\n  \n  rewrite H20.\n  eapply TCBList_P_Combine; eauto.\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  unfolds in Ha3.\n  lets Hsx : tcbjoin_join_get_neq H13 H14 H21.\n  destruct Hsx.\n  eapply Ha3; eauto.\n  lets Hacb  :  TcbMod.join_get_l H8 H23; eauto.\n  simpl.\n  do 4 eexists; splits; eauto.\n  unfolds; simpl; eauto.\n  unfold TcbJoin in *.\n  unfold join in *; simpl in *.\n  eauto.\n  unfolds in H15.\n  unfolds.\n  fsimpl.\n  usimpl H15.\n  usimpl H22.\n  splits.\n  unfolds; simpl; auto.\n  unfolds; simpl; auto.\n  funfold H23.\n  unfolds.\n  do 6 eexists; splits; try solve [unfolds; simpl;auto].\n  omega.\n  splits; eauto.\n  eexists.\n  split.\n  unfolds;simpl; eauto.\n  auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  splits; try solve [unfolds; simpl;auto].\n  eexists; eauto.\n  unfolds.\n  intros.\n  inverts H15.\n  splits; try solve [unfolds; simpl;auto].\n  unfolds.\n  splits; try solve [unfolds; simpl;auto].\n  apply prio_in_tbl_orself ; auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  false.\n  rewrite H26 in H19.\n  rewrite H19 in Hnth.\n  rewrite H26 in *.\n  (* ** ac: Check prio_notin_tbl_orself. *)\n  lets Hfs :  prio_notin_tbl_orself  H16 Hnth.\n  tryfalse.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  \n  unfolds.\n  splits; try solve [\n                unfolds;\n                introv Hf; inverts Hf].\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  lets Hnas : tcbjoin_tid_neq H13 H21.\n  unfolds in Ha3.\n  eapply Ha3; eauto.\n  lets Haxc  : TcbMod.join_get_r H13 H21.\n  lets Haa : TcbMod.join_get_r H14 Haxc.\n  lets Ad :  TcbMod.join_get_l H8 Haa; eauto.\nQed.\n\n\nLemma tcb_inrtbl_not_vhold: forall v'42 v'62 v'93 v'57 v'81, RL_RTbl_PrioTbl_P v'42 v'62 v'93 ->  prio_in_tbl ((v'57)) v'42 -> nth_val' (Z.to_nat (Int.unsigned ((v'57)))) v'62 =  Vptr (v'81, Int.zero) ->   0 <= Int.unsigned v'57 < 64 -> (v'81, Int.zero) <> v'93.\nProof.\n  introv H H0 H1 asdfasfd.\n  unfolds in H.\n  lets adaf: H H0.\n  auto.\n  mytac.\n  (* ** ac: Check nth_val_nth_val'_some_eq. *)\n  apply nth_val_nth_val'_some_eq in H4.\n  rewrite H1 in H4.\n  inverts H4.\n  auto.\nQed.\n\nLemma ECBList_P_Set_Rdy_hold_sem\n: forall (a : list EventCtr) (tcbls : TcbMod.map) \n         (tid : tidspec.A) (prio : priority) (msg0 msg' : msg) \n         (x y : val) (b : list EventData) (c : EcbMod.map) \n         (eid : ecbid) (nl : int32),\n    TcbMod.get tcbls tid = Some (prio, wait (os_stat_sem eid) nl, msg0) ->\n    EcbMod.get c eid = None ->\n    ECBList_P x y a b c tcbls ->\n    ECBList_P x y a b c (TcbMod.set tcbls tid (prio, rdy, msg')).\nProof.\n  inductions a; intros.\n  simpl in *; auto.\n  simpl in H1.\n  mytac.\n  destruct b; tryfalse.\n  destruct a.\n  mytac.\n  simpl.\n  eexists.\n  splits; eauto.\n  unfolds.\n  unfolds in H2.\n\n  splits.\n  \n  destructs H2.\n  unfolds in H2.\n  mytac.\n  unfolds.\n  splits; unfolds;intros.\n\n  apply H2 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  \n  \n  apply H8 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H9 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H10 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n\n\n  \n  unfolds.\n  destructs H2;unfolds in H6;destructs H6.\n  splits;intros prio' mg ng x3 Hti;\n  assert (tid = x3\n          \\/ tid <> x3) by tauto.\n  destruct H11.\n  subst tid.\n  unfold get in *; simpl in *.\n  unfold get in *; simpl in *.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.eq_beq_true in Hti; auto.\n  inverts Hti.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H6; eauto.\n\n  destruct H11.\n  subst tid.\n  unfold get in *; simpl in *.\n  unfold get in *; simpl in *.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.eq_beq_true in Hti; auto.\n  inverts Hti.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H8; eauto.\n  \n  destruct H11.\n  subst tid.\n  unfold get in *; simpl in *.\n  unfold get in *; simpl in *.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.eq_beq_true in Hti; auto.\n  inverts Hti.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H9; eauto.\n\n  destruct H11.\n  subst tid.\n  unfold get in *; simpl in *.\n  unfold get in *; simpl in *.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.eq_beq_true in Hti; auto.\n  inverts Hti.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H10; eauto.\n\n  mytac;auto.\n\n  do 3 eexists; splits; eauto.\n  eapply IHa; eauto.\n  eapply ecbmod_joinsig_get_none; eauto.\nQed.\n\nLemma ecblist_p_post_exwt_hold_sem (* ecblist_p_post_exwt_hold_mbox *)\n: forall (v'36 : vallist) (v'12 : int32) (v'13 : vallist)\n         (v'38 v'69 v'39 : int32) (v'58 : block) (v'40 : int32)\n         (v'32 : block) (v'15 : int32) (v'24 : val)\n         (v'35 : val) (x1 : waitset) \n         (v'0 : val) (v'1 : list EventCtr) (v'5 : list EventData)\n         (v'6 : EcbMod.map) (v'7 : TcbMod.map) \n         (v'11 : EcbMod.map) (v'31 : list EventData) \n         (v'30 : list EventCtr) (v'29 : val) (v'10 v'9 : EcbMod.map)\n         (prio : priority) (v'62 : TcbMod.map) (st : taskstatus)\n         (msg0 msg1: msg) (y : int32) (vhold : addrval),\n    Int.unsigned v'15 <= 65535 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold ->\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = \u2218OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_SEM\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: v'24 :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RLH_ECBData_P\n      (DSem v'15) (abssem v'15, x1) ->\n    ECBList_P v'0 Vnull v'1 v'5 v'6 v'7 ->\n    ECBList_P v'29 (Vptr (v'32, Int.zero)) v'30 v'31 v'9 v'7 ->\n    EcbMod.joinsig (v'32, Int.zero) (abssem v'15, x1) v'6 v'10 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'62 v'7 ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    x1 <> nil ->\n    ECBList_P v'29 Vnull\n              (v'30 ++\n                    ((V$OS_EVENT_TYPE_SEM\n                       :: Vint32 y\n                       :: Vint32 v'15 :: v'24 :: v'35 :: v'0 :: nil,\n                      update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                                     (Vint32 (v'69&\u1d62Int.not v'40))) :: nil) ++ v'1)\n              (v'31 ++\n                    (DSem v'15 ::nil)\n                    ++ v'5)\n              (EcbMod.set v'11 (v'32, Int.zero)\n                          (abssem v'15, remove_tid (v'58, Int.zero) x1))\n              (TcbMod.set v'7 (v'58, Int.zero) (prio, rdy, msg1))\n.\nProof.\n  introv Hcnt.\n  intros.\n  unfolds in H21.\n  destruct H21 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) < 64).\n  clear -H5 H9.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H10.\n  lets Hps : Ha1 H21 H10.\n  apply tcbjoin_get_a in H20.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in H20.\n  destruct H20;auto.\n  destruct Hps as (sts & mg & Hget);auto.\n  unfold get in *; simpl in *.\n  rewrite Hget in H20.\n  inverts H20.\n  remember ((v'38<<\u1d62$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+\u1d62py) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  unfolds in H14.\n  destruct H14 as (Ha & Hb & Hc).\n  destruct Ha as (Ha''&Ha&Ha'&Ha''').\n  destruct Hb as (Hb''&Hb&Hb'&Hb''').\n  lets Hz : math_unmap_get_y H1 H4.\n  lets Heq1 :  math_mapval_core_prop H11; eauto.\n  omega.\n  subst v'40.\n  assert (v'38 = Int.shru prio ($3)).\n  subst.\n  clear -Hz H9.\n  mauto.\n  assert (py = prio &\u1d62 $ 7).\n  subst prio. \n  rewrite Heqpx.\n  clear -Hz H9.\n  mauto.\n  rewrite H14 in H6.\n  assert (PrioWaitInQ (Int.unsigned prio) v'13) as Hcp.\n  unfolds.\n  do 3 eexists; splits; eauto.\n  rewrite Int.repr_unsigned.\n  eapply nth_val'_imp_nth_val_int; eauto.\n  rewrite Int.repr_unsigned.\n  rewrite <- H20.\n  unfold Int.one.\n  eapply math_8_255_eq; eauto.\n  \n  unfold Int.zero in H0.\n  rewrite <-H14 in *.\n  lets Hneq :  rl_tbl_grp_neq_zero H1 H0  H4 H6 H13.\n  omega.\n  auto.\n  lets Hecp : Ha Hcp.\n  unfold V_OSEventType in Hecp.\n  simpl nth_val in Hecp.\n  assert (Some (V$OS_EVENT_TYPE_SEM) = Some (V$OS_EVENT_TYPE_SEM)) by auto.\n  apply Hecp in H23.\n  clear Hecp.\n  rename H23 into Hecp.\n  destruct Hecp as (ct & nl & mg & Hcg).\n  assert (ct = tid) as Hed.\n  assert (ct = tid \\/ ct <> tid)  by tauto.\n  destruct H23; auto.\n  lets Heqs : Ha3 H23 Hcg Hget.\n  rewrite Int.repr_unsigned in Heqs.\n  tryfalse.\n  subst ct.\n  unfold get in Hcg; simpl in Hcg.\n  rewrite Hget in Hcg.\n  inversion Hcg.\n  subst mg st .\n  clear Hcg.\n  \n  lets Hsds : ecb_set_join_join  (abssem v'15, remove_tid tid x1)  H18  H19.\n  destruct Hsds as ( vv & Hsj1 & Hsj2).\n\n  eapply semacc_compose_EcbList_P.\n  instantiate (1:= (v'32, Int.zero)).\n  unfolds.\n  splits.\n  unfolds.\n  splits;unfolds.\n  Focus 2.\n  \n  introv Hprs Hxx.\n  clear Hxx.\n  apply prio_wt_inq_convert in Hprs.\n  destruct Hprs as (Hprs1 & Hprs2).\n  rewrite H14 in Hprs1.\n  rewrite H20 in Hprs1.\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (Hrs & _).\n  apply Hrs in Hprs1.\n  destruct Hprs1 as (Hpq & Hneq).\n  unfolds in Ha.\n  lets Hxs : Ha Hpq.\n  rewrite Int.repr_unsigned in Hxs.\n  destruct Hxs as (tid' & nn & mm & Htg).\n  unfolds;simpl;auto.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  unfold get in Htg; simpl in Htg.\n  rewrite Hget in Htg.\n  inversion Htg.\n  tryfalse.\n  exists tid' nn mm.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false;eauto.\n\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  \n  3:eauto.\n\n  unfolds.\n  splits;\n    intros prio' mm nn tid'.\n  Focus 2.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb.\n  lets Hga : Hb Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (_ & Hrs).\n  apply Hrs in H25.\n  rewrite H20.\n  rewrite H14.\n  auto.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb''.\n  lets Hga : Hb'' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'.\n  lets Hga : Hb' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'''.\n  lets Hga : Hb''' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  simpl fst in Hc;simpl;auto.\n\n  5:eauto.\n  4:eauto.\n  unfolds.\n  splits; auto.\n  unfolds.\n  split.\n  intros.\n  destruct H15 as (Ht1 & Ht2 & Ht3).\n  apply Ht2 in H23.\n  subst x1.\n  tryfalse.\n  intros.\n  destruct H15 as (Ht1 & Ht2 & Ht3).\n  apply Ht3 in H22.\n  auto.\n  \n  eapply ECBList_P_Set_Rdy_hold_sem;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply joinsig_join_getnone; eauto.\n  eapply ECBList_P_Set_Rdy_hold_sem;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply  joinsig_get_none; eauto.\nQed.\n\n\nLemma rh_tcblist_ecblist_p_post_exwt_aux_sem \n: forall (v'8 tid0 : tid) (v'11 : EcbMod.map) \n         (v'7 : TcbMod.map) (v'9 v'10 : EcbMod.map) \n         (eid : tidspec.A) x \n         (x0 : maxlen) (x1 : waitset) (v'6 : EcbMod.map) \n         (prio : priority) (msg0 : msg) \n         (st : taskstatus),\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (abssem x, x1) v'6 v'10 ->\n    In tid0 x1 ->\n    TcbMod.get v'7 tid0 = Some (prio, st, msg0) ->\n    exists xl, st = wait (os_stat_sem eid) xl\n.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (Hexaa & Hex & Hexa & Hexaaa).\n  lets Hget : EcbMod.join_joinsig_get H0 H1.\n  assert (EcbMod.get v'11 eid = Some (abssem x, x1) /\\ In tid0 x1).\n  split; auto.\n  apply Hex in H.\n  mytac.\n  unfold get in H; simpl in H.\n  rewrite H3 in H.\n  inverts H.\n  eauto.\nQed.\n\n\nLemma rh_tcblist_ecblist_p_post_exwt_sem\n: forall (v'8 tid : tid) (v'11 : EcbMod.map) \n         (v'7 : TcbMod.map) (v'9 v'10 : EcbMod.map) \n         (eid : tidspec.A) x \n         (x0 : maxlen) (x1 : waitset) (v'6 : EcbMod.map) \n         (prio : priority) (msg0 msg1: msg) \n         (x00 : addrval) (xl : int32),\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (abssem x , x1) v'6 v'10 ->\n    In tid x1 ->\n    TcbMod.get v'7 tid = Some (prio, wait (os_stat_sem eid) xl, msg0) ->\n    RH_TCBList_ECBList_P\n      (EcbMod.set v'11 eid (abssem x, remove_tid tid x1))\n      (TcbMod.set v'7 tid (prio, rdy, msg1)) v'8\n.\nProof.\n  intros.\n  unfolds.\n  splits.\n  Focus 2.\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hy&H&Hx&Hz).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H7.\n  subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (EcbMod.get v'11 eid = Some (abssem x, x1)/\\ In tid0 x1 ).\n  splits; auto.\n  lets Hsa : H H7.\n  mytac.\n  unfold get in H9; simpl in H9.\n  rewrite H3 in H9.\n  inverts H9.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H9.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  (* ** ac: Check in_wtset_rm_notin. *)\n  apply in_wtset_rm_notin in H8.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (abssem n, wls) /\\ In tid0 wls ).\n\n  splits; auto.\n  lets Hsc : H H10.\n  mytac.\n  unfold get in *; simpl in *.\n  rewrite H3 in H12.\n  inverts H12.\n  tryfalse.\n  rewrite TcbMod.set_sem .\n  rewrite tidspec.neq_beq_false; auto.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  (* ** ac: Check tidneq_inwt_in. *)\n  lets Hbss :tidneq_inwt_in x1 H7.\n  destruct Hbss as (Hbss & _).\n  lets Hbssc : Hbss H5.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert ( EcbMod.get v'11 eid0 = Some (abssem n, x1) /\\ In tid0 x1 ).\n  splits; auto.\n  apply H in H4.\n  mytac.\n  do 3 eexists; eauto.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert ( EcbMod.get v'11 eid0 = Some (abssem n, wls)/\\ In tid0 wls ).\n  splits; auto.\n  apply H in H9.\n  mytac.\n  do 3 eexists; eauto .\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H5.\n  subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  \n  unfolds in H.\n  destruct H as (H6 & H & H7 & H8).\n  destruct H.\n  apply H9 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H11.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget.\n  inverts Hget.\n  lets Hbss :tidneq_inwt_in  x1 H5.\n  destruct Hbss as (_ & Hbss).\n  lets Hbssc : Hbss H10.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  do 2 eexists; splits; eauto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\n\n\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (H&_).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmsgq x2 y, qwaitset) /\\ In tid0 qwaitset).\n  split;auto.\n  apply H in H8.\n  mytac.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (H&_).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists;split;eauto.\n\n  \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&Hr&H&_).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmbox n, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  mytac.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&Hr&H&_).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists;split;eauto.\n\n  \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&Hhh&Hx&H).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmutexsem n1 n2, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  mytac.\n  assert (Htmp:tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct Htmp;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&Hx&Hhh&H).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  mytac.\n  assert (Htmp:eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct Htmp;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists;split;eauto.\n\n\n  apply Mutex_owner_hold_for_set_tcb.\n  eapply Mutex_owner_set; eauto.\n  intro; mytac.\n  inverts H4.\n  unfolds in H.\n  mytac.\n  unfolds in H6; mytac.\nQed.\n\n\nLemma sempost_grp_wls_nil':\n  forall v'36 v'6 vhold v'7 v'13 v'12 v'32 x v'24 v'35 v'0 v'11 v'8 v'9 v'10 x1,\n    v'12 = Int.zero ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_SEM\n                   :: Vint32 v'12\n                   :: Vint32 x :: v'24 :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig (v'32, Int.zero) (abssem x , x1) v'6 v'10 ->\n    x1 = nil.\nProof.\n  intros.\n  unfolds in H2.\n  destruct H2 as (H2 & H2' & _).\n  destruct H2 as (_ & H2 & _ & _).\n  destruct H2' as (_ & H2' & _ & _).\n  unfolds in H2.\n  unfolds in H2'.\n  \n\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  destruct H3 as (_ & H3 & _ & _).\n  unfolds in H3.\n  destruct H3 as (H3 & H3').\n\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  assert ( x1 = nil \\/ x1 <> nil) by tauto.\n  destruct H4; intros; auto.\n\n  idtac.\n  apply something_in_not_nil in H4.\n  inversion H4.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (abssem x, x1) /\\ In x0 x1) by tauto.\n  lets aadf : H3 H6.\n  mytac.\n  lets bbdf : H2' H10.\n  destruct bbdf.\n  unfolds in H.\n  do 3 destruct H.\n  destruct H as (Ha & Hb & Hc & Hd& He).\n  cut ( 0<=(\u2218(Int.unsigned x7)) <8)%nat.\n  intro.\n  assert (V$0 = V$0) by auto.\n  lets adfafd : H1 H Hd H12.\n  destruct adfafd.\n  destruct H13.\n  destruct H14.\n  cut ( $ 0&\u1d62($ 1<<\u1d62$ Z.of_nat \u2218(Int.unsigned x7)) = $ 0).\n  intro.\n  apply H13 in H17.\n  subst x8.\n\n  lets rg : rg1 Ha Hb.\n  clear -He rg.\n  false.\n  gen He.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\nQed.\n\nLemma sempost_inc_RH_TCBList_ECBList_P_hold:\n  forall mqls tcbls ct a n wl,\n    RH_TCBList_ECBList_P mqls tcbls ct ->\n    EcbMod.get mqls a = Some (abssem n, wl) ->\n    Int.ltu n ($ 65535) = true ->\n    RH_TCBList_ECBList_P \n      (EcbMod.set mqls a (abssem (Int.add n Int.one), wl)) tcbls ct.\nProof.\n  intros.\n  unfold RH_TCBList_ECBList_P in *.\n  destruct H as [Hq [Hsem [Hmbox Hmutex]]] .\n  intuition.\n\n\n(***************** Q begin ************)\n\n  unfold RH_TCBList_ECBList_Q_P in *.\n  destruct Hq as [F1 F2].\n  intuition.\n  destruct (tidspec.beq a eid) eqn:Feq.\n  (* ** ac: Check tidspec.beq_true_eq. *)\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  match goal with\n    | H: EcbMod.get (EcbMod.set _ _ _) _ = _ |- _ =>\n        rewrite EcbMod.set_a_get_a in H; tryfalse; auto\n  end.\n\n  apply CltEnvMod.beq_refl.\n  eapply F1.\n  split; \n    [ rewrite EcbMod.set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  match goal with\n    | H: TcbMod.get _ _ = _ |- _ =>\n        apply F2 in H; mytac; tryfalse\n  end.\n      \n  rewrite EcbMod.set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n(**************** Q end ************)  \n\n  unfold RH_TCBList_ECBList_SEM_P in *.\n  destruct Hsem as [F1 F2].\n  intuition.\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  rewrite EcbMod.set_a_get_a in H2; eauto.\n  inverts H2.\n  eapply F1.\n  split; eauto.\n\n  apply CltEnvMod.beq_refl.\n  \n  eapply F1.\n  split;\n    [ rewrite EcbMod.set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  apply F2 in H; mytac.\n  rewrite H in H0.\n  inverts H0.\n  exists (Int.add n Int.one) wl.\n  rewrite EcbMod.set_a_get_a; eauto.\n\n  apply CltEnvMod.beq_refl.\n\n  rewrite EcbMod.set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n\n  unfold RH_TCBList_ECBList_MBOX_P in *.\n  destruct Hmbox as [F1 F2].\n  intuition.\n  destruct (tidspec.beq a eid) eqn:Feq.\n\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  match goal with\n    | H: EcbMod.get (EcbMod.set _ _ _) _ = _ |- _ =>\n        rewrite EcbMod.set_a_get_a in H; tryfalse; auto\n  end.\n\n  apply CltEnvMod.beq_refl.\n  \n  eapply F1.\n  split; \n    [ rewrite EcbMod.set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n  match goal with\n    | H: TcbMod.get _ _ = _ |- _ =>\n        apply F2 in H; mytac; tryfalse\n  end.\n      \n  rewrite EcbMod.set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n\n\n  unfold RH_TCBList_ECBList_MUTEX_P in *.\n  destruct Hmutex as [F1 F2].\n  intuition.\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n\n  match goal with\n    | H: EcbMod.get (EcbMod.set _ _ _) _ = _ |- _ =>\n        rewrite EcbMod.set_a_get_a in H; tryfalse; auto\n  end.\n\n  apply CltEnvMod.beq_refl.\n\n  eapply F1.\n  split; \n    [ rewrite EcbMod.set_a_get_a' in H4; eauto\n    | eauto].\n\n  destruct (tidspec.beq a eid) eqn:Feq.\n  apply tidspec.beq_true_eq in Feq; substs.\n  unfold get in *; simpl in *.\n\n  match goal with\n    | Hget: TcbMod.get _ _ = _ |- _ =>\n        apply H in Hget; mytac; tryfalse\n  end.\n      \n  rewrite EcbMod.set_a_get_a'; \n    [ eapply H; eauto\n    | auto].\n\n  eapply Mutex_owner_set.\n  unfolds.\n  intros.\n  mytac.\n  inverts H3.\n  auto.\nQed.\n\nLemma node_fold':\n  forall s P vl t b,\n    s |= Astruct (b, Int.zero) t vl ** P ->\n    struct_type_vallist_match t vl ->\n    s |= node (Vptr (b, Int.zero)) vl t ** P.\n  intros.\n  unfold node.\n  sep pauto.\nQed.\n\nLemma sempost_vallist_match_assert1:\n  forall x,\n    Int.ltu x ($ 65535) = true ->\n    Int.unsigned (Int.add x Int.one) <= 65535.\nProof.\n  intros.\n  int auto.\n  destruct (zlt (Int.unsigned x) 65535).\n  int auto.\n  tryfalse.\nQed.  \n\nLemma sempost_struct_type_vallist_match_sem:\n  forall i1 x2 x3 v'44,\n    isptr v'44 ->\n    isptr x2 ->\n    Int.ltu i1 ($ 65535) = true ->\n    struct_type_vallist_match OS_EVENT\n                              (V$OS_EVENT_TYPE_SEM\n                                :: V$0 :: Vint32 (i1+\u1d62$ 1) :: x2 :: x3 :: v'44 :: nil).\nProof.\n  intros.\n  apply sempost_vallist_match_assert1 in H1.\n  pauto.\nQed.\n\nLemma rl_etbl_ptbl_p:\n  forall l egrp v'33 i4 x6 v'22 etbl tcbls ptbl etype av,\n    array_type_vallist_match Int8u etbl ->\n    length etbl = \u2218OS_RDY_TBL_SIZE ->\n    R_ECB_ETbl_P l\n                 (etype\n                   :: Vint32 egrp\n                   :: Vint32 i4 :: v'33 \n                   :: x6 :: v'22 :: nil,\n                  etbl) tcbls ->\n    RL_Tbl_Grp_P etbl (Vint32 egrp) ->\n    R_PrioTbl_P ptbl tcbls av->\n    RL_RTbl_PrioTbl_P etbl ptbl av.\nProof.\n  introv Ha Hl.\n  intros.\n  unfolds in H.\n  unfolds in H0.\n  unfolds in H1.\n  unfolds.\n  intros.\n  unfolds in H3.\n  destruct H1.\n  destruct H4.\n  destruct H.\n  destruct H6 as (H6&Htype).\n  unfolds in H6.\n  unfolds in H.\n  assert ( PrioWaitInQ (Int.unsigned p) etbl).\n  unfolds.\n  remember (Int.shru p ($3)) as px.\n  remember (p &\u1d62 $ 7) as py.\n  lets Hxx : n07_arr_len_ex   \u2218(Int.unsigned px ) Ha Hl.\n  clear - Heqpx H2.\n  subst px.\n  mauto.\n  destruct Hxx as (vx & Hth & Hvr).\n  lets Has : H3 Hth; eauto.\n  do 3 eexists; eauto; splits; eauto.\n  rewrite Int.repr_unsigned.\n  rewrite <- Heqpx.\n  eauto.\n  rewrite Int.repr_unsigned.\n  unfold Int.one.\n  subst py.\n  eauto.\n  destructs H.\n  unfolds in Htype.\n  destruct Htype.\n  apply H in H7.\n  unfold V_OSEventType in H7.\n  simpl in H7.\n  unfolds in H11;simpl in H11;inverts H11.\n  assert (Some (V$OS_EVENT_TYPE_Q) = Some (V$OS_EVENT_TYPE_Q)) by auto.\n  apply H7 in H11.\n  \n  mytac.\n  rewrite Int.repr_unsigned in *.\n  apply H4 in H11.\n  eexists; eauto.\n \n  destruct H11.\n  unfolds in H11;simpl in H11;inverts H11.\n  apply H8 in H7.\n  assert (Some (V$OS_EVENT_TYPE_SEM) = Some (V$OS_EVENT_TYPE_SEM)) by auto.\n  apply H7 in H11.\n  mytac.\n  rewrite Int.repr_unsigned in *.\n  apply H4 in H11.\n  eexists; eauto.\n  \n  destruct H11.\n  unfolds in H11;simpl in H11;inverts H11.\n  apply H9 in H7.\n  assert (Some (V$OS_EVENT_TYPE_MBOX) = Some (V$OS_EVENT_TYPE_MBOX)) by auto.\n  apply H7 in H11.\n  mytac.\n  rewrite Int.repr_unsigned in *.\n  apply H4 in H11.\n  eexists; eauto.\n\n  unfolds in H11;simpl in H11;inverts H11.\n  apply H10 in H7.\n  assert (Some (V$OS_EVENT_TYPE_MUTEX) = Some (V$OS_EVENT_TYPE_MUTEX)) by auto.\n  apply H7 in H11.\n  mytac.\n  rewrite Int.repr_unsigned in *.\n  apply H4 in H11.\n  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/ucos_lib/sempost_pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253925955867, "lm_q1q2_score": 0.18655885981546746}}
{"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\nInductive program_behavior: Type :=\n  | Terminates: trace -> int -> program_behavior\n  | Diverges: trace -> program_behavior\n  | Reacts: traceinf -> program_behavior\n  | Goes_wrong: trace -> program_behavior.\n\n(** Operations and relations on behaviors *)\n\nDefinition not_wrong (beh: program_behavior) : Prop :=\n  match beh with\n  | Terminates _ _ => True\n  | Diverges _ => True\n  | Reacts _ => True\n  | Goes_wrong _ => False\n  end.\n\nDefinition behavior_app (t: trace) (beh: program_behavior): program_behavior :=\n  match beh with\n  | Terminates t1 r => Terminates (t ** t1) r\n  | Diverges t1 => Diverges (t ** t1)\n  | Reacts T => Reacts (t *** T)\n  | Goes_wrong t1 => Goes_wrong (t ** t1)\n  end.\n\nLemma behavior_app_assoc:\n  forall t1 t2 beh,\n  behavior_app (t1 ** t2) beh = behavior_app t1 (behavior_app t2 beh).\nProof.\n  intros. destruct beh; simpl; f_equal; traceEq.\nQed.\n\nLemma behavior_app_E0:\n  forall beh, behavior_app E0 beh = beh.\nProof.\n  destruct beh; auto.\nQed.\n\nDefinition behavior_prefix (t: trace) (beh: program_behavior) : Prop :=\n  exists beh', beh = behavior_app t beh'.\n\nDefinition behavior_improves (beh1 beh2: program_behavior) : Prop :=\n  beh1 = beh2 \\/ exists t, beh1 = Goes_wrong t /\\ behavior_prefix t beh2.\n\nLemma behavior_improves_refl:\n  forall beh, behavior_improves beh beh.\nProof.\n  intros; red; auto.\nQed.\n\nLemma behavior_improves_trans:\n  forall beh1 beh2 beh3,\n  behavior_improves beh1 beh2 -> behavior_improves beh2 beh3 ->\n  behavior_improves beh1 beh3.\nProof.\n  intros. red. destruct H; destruct H0; subst; auto.\n  destruct H as [t1 [EQ1 [beh2' EQ1']]].\n  destruct H0 as [t2 [EQ2 [beh3' EQ2']]].\n  subst. destruct beh2'; simpl in EQ2; try discriminate. inv EQ2.\n  right. exists t1; split; auto. exists (behavior_app t beh3'). apply behavior_app_assoc.\nQed.\n\nLemma behavior_improves_bot:\n  forall beh, behavior_improves (Goes_wrong E0) beh.\nProof.\n  intros. right. exists E0; split; auto. exists beh. rewrite behavior_app_E0; auto.\nQed.\n\nLemma behavior_improves_app:\n  forall t beh1 beh2,\n  behavior_improves beh1 beh2 ->\n  behavior_improves (behavior_app t beh1) (behavior_app t beh2).\nProof.\n  intros. red; destruct H. left; congruence.\n  destruct H as [t' [A [beh' B]]]. subst.\n  right; exists (t ** t'); split; auto. exists beh'. rewrite behavior_app_assoc; auto.\nQed.\n\n(** Associating behaviors to programs. *)\n\nSection PROGRAM_BEHAVIORS.\n\nVariable L: semantics.\n\nInductive state_behaves (s: state L): program_behavior -> Prop :=\n  | state_terminates: forall t s' r,\n      Star L s t s' ->\n      final_state L s' r ->\n      state_behaves s (Terminates t r)\n  | state_diverges: forall t s',\n      Star L s t s' -> Forever_silent L s' ->\n      state_behaves s (Diverges t)\n  | state_reacts: forall T,\n      Forever_reactive L s T ->\n      state_behaves s (Reacts T)\n  | state_goes_wrong: forall t s',\n      Star L s t s' ->\n      Nostep L s' ->\n      (forall r, ~final_state L s' r) ->\n      state_behaves s (Goes_wrong t).\n\nInductive program_behaves: program_behavior -> Prop :=\n  | program_runs: forall s beh,\n      initial_state L s -> state_behaves s beh ->\n      program_behaves beh\n  | program_goes_initially_wrong:\n      (forall s, ~initial_state L s) ->\n      program_behaves (Goes_wrong E0).\n\nLemma state_behaves_app:\n  forall s1 t s2 beh,\n  Star L s1 t s2 -> state_behaves s2 beh -> state_behaves s1 (behavior_app t beh).\nProof.\n  intros. inv H0; simpl; econstructor; eauto; try (eapply star_trans; eauto).\n  eapply star_forever_reactive; eauto.\nQed.\n\n(** * Existence of behaviors *)\n\n(** We now show that any program admits at least one behavior.\n  The proof requires classical logic: the axiom of excluded middle\n  and an axiom of description. *)\n\n(** The most difficult part of the proof is to show the existence\n  of an infinite trace in the case of reactive divergence. *)\n\nSection TRACEINF_REACTS.\n\nVariable s0: state L.\n\nHypothesis reacts:\n  forall s1 t1, Star L s0 t1 s1 ->\n  exists s2, exists t2, Star L s1 t2 s2 /\\ t2 <> E0.\n\nLemma reacts':\n  forall s1 t1, Star L s0 t1 s1 ->\n  { s2 : state L & { t2 : trace | Star L s1 t2 s2 /\\ t2 <> E0 } }.\nProof.\n  intros.\n  destruct (constructive_indefinite_description _ (reacts H)) as [s2 A].\n  destruct (constructive_indefinite_description _ A) as [t2 [B C]].\n  exists s2; exists t2; auto.\nQed.\n\nCoFixpoint build_traceinf' (s1: state L) (t1: trace) (ST: Star L s0 t1 s1) : traceinf' :=\n  match reacts' ST with\n  | existT _ s2 (exist _ t2 (conj A B)) =>\n      Econsinf' t2\n                (build_traceinf' (star_trans ST A (refl_equal _)))\n                B\n  end.\n\nLemma reacts_forever_reactive_rec:\n  forall s1 t1 (ST: Star L s0 t1 s1),\n  Forever_reactive L s1 (traceinf_of_traceinf' (build_traceinf' ST)).\nProof.\n  cofix COINDHYP; intros.\n  rewrite (unroll_traceinf' (build_traceinf' ST)). simpl.\n  destruct (reacts' ST) as [s2 [t2 [A B]]].\n  rewrite traceinf_traceinf'_app.\n  econstructor. eexact A. auto. apply COINDHYP.\nQed.\n\nLemma reacts_forever_reactive:\n  exists T, Forever_reactive L s0 T.\nProof.\n  exists (traceinf_of_traceinf' (build_traceinf' (star_refl (step L) (globalenv L) s0))).\n  apply reacts_forever_reactive_rec.\nQed.\n\nEnd TRACEINF_REACTS.\n\nLemma diverges_forever_silent:\n  forall s0,\n  (forall s1 t1, Star L s0 t1 s1 -> exists s2, Step L s1 E0 s2) ->\n  Forever_silent L s0.\nProof.\n  cofix COINDHYP; intros.\n  destruct (H s0 E0) as [s1 ST]. constructor.\n  econstructor. eexact ST. apply COINDHYP.\n  intros. eapply H. eapply star_left; eauto.\nQed.\n\nLemma state_behaves_exists:\n  forall s, exists beh, state_behaves s beh.\nProof.\n  intros s0.\n  destruct (classic (forall s1 t1, Star L s0 t1 s1 -> exists s2, exists t2, Step L s1 t2 s2)).\n(* 1 Divergence (silent or reactive) *)\n  destruct (classic (exists s1, exists t1, Star L s0 t1 s1 /\\\n                       (forall s2 t2, Star L s1 t2 s2 ->\n                        exists s3, Step L s2 E0 s3))).\n(* 1.1 Silent divergence *)\n  destruct H0 as [s1 [t1 [A B]]].\n  exists (Diverges t1); econstructor; eauto.\n  apply diverges_forever_silent; auto.\n(* 1.2 Reactive divergence *)\n  destruct (@reacts_forever_reactive s0) as [T FR].\n  intros.\n  generalize (not_ex_all_not _ _ H0 s1). intro A; clear H0.\n  generalize (not_ex_all_not _ _ A t1). intro B; clear A.\n  destruct (not_and_or _ _ B). contradiction.\n  destruct (not_all_ex_not _ _ H0) as [s2 C]; clear H0.\n  destruct (not_all_ex_not _ _ C) as [t2 D]; clear C.\n  destruct (imply_to_and _ _ D) as [E F]; clear D.\n  destruct (H s2 (t1 ** t2)) as [s3 [t3 G]]. eapply star_trans; eauto.\n  exists s3; exists (t2 ** t3); split.\n  eapply star_right; eauto.\n  red; intros. destruct (app_eq_nil t2 t3 H0). subst. elim F. exists s3; auto.\n  exists (Reacts T); econstructor; eauto.\n(* 2 Termination (normal or by going wrong) *)\n  destruct (not_all_ex_not _ _ H) as [s1 A]; clear H.\n  destruct (not_all_ex_not _ _ A) as [t1 B]; clear A.\n  destruct (imply_to_and _ _ B) as [C D]; clear B.\n  destruct (classic (exists r, final_state L s1 r)) as [[r FINAL] | NOTFINAL].\n(* 2.1 Normal termination *)\n  exists (Terminates t1 r); econstructor; eauto.\n(* 2.2 Going wrong *)\n  exists (Goes_wrong t1); econstructor; eauto. red. intros.\n  generalize (not_ex_all_not _ _ D s'); intros.\n  generalize (not_ex_all_not _ _ H t); intros.\n  auto.\nQed.\n\nTheorem program_behaves_exists:\n  exists beh, program_behaves beh.\nProof.\n  destruct (classic (exists s, initial_state L s)) as [[s0 INIT] | NOTINIT].\n(* 1. Initial state is defined. *)\n  destruct (state_behaves_exists s0) as [beh SB].\n  exists beh; econstructor; eauto.\n(* 2. Initial state is undefined *)\n  exists (Goes_wrong E0). apply program_goes_initially_wrong.\n  intros. eapply not_ex_all_not; eauto.\nQed.\n\nEnd PROGRAM_BEHAVIORS.\n\n(** * Forward simulations and program behaviors *)\n\nSection FORWARD_SIMULATIONS.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable S: forward_simulation L1 L2.\n\nLemma forward_simulation_state_behaves:\n  forall i s1 s2 beh1,\n  S i s1 s2 -> state_behaves L1 s1 beh1 ->\n  exists beh2, state_behaves L2 s2 beh2 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H0.\n(* termination *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  exists (Terminates t r); split.\n  econstructor; eauto. eapply fsim_match_final_states; eauto.\n  apply behavior_improves_refl.\n(* silent divergence *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  exists (Diverges t); split.\n  econstructor; eauto. eapply simulation_forever_silent; eauto.\n  apply behavior_improves_refl.\n(* reactive divergence *)\n  exists (Reacts T); split.\n  econstructor. eapply simulation_forever_reactive; eauto.\n  apply behavior_improves_refl.\n(* going wrong *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  destruct (state_behaves_exists L2 s2') as [beh' SB].\n  exists (behavior_app t beh'); split.\n  eapply state_behaves_app; eauto.\n  replace (Goes_wrong t) with (behavior_app t (Goes_wrong E0)).\n  apply behavior_improves_app. apply behavior_improves_bot.\n  simpl. decEq. traceEq.\nQed.\n\nTheorem forward_simulation_behavior_improves:\n  forall beh1, program_behaves L1 beh1 ->\n  exists beh2, program_behaves L2 beh2 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H.\n(* initial state defined *)\n  exploit (fsim_match_initial_states S); eauto. intros [i [s' [INIT MATCH]]].\n  exploit forward_simulation_state_behaves; eauto. intros [beh2 [A B]].\n  exists beh2; split; auto. econstructor; eauto.\n(* initial state undefined *)\n  destruct (classic (exists s', initial_state L2 s')).\n  destruct H as [s' INIT].\n  destruct (state_behaves_exists L2 s') as [beh' SB].\n  exists beh'; split. econstructor; eauto. apply behavior_improves_bot.\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros. elim H; exists s; auto.\n  apply behavior_improves_refl.\nQed.\n\nCorollary forward_simulation_same_safe_behavior:\n  forall beh,\n  program_behaves L1 beh -> not_wrong beh ->\n  program_behaves L2 beh.\nProof.\n  intros. exploit forward_simulation_behavior_improves; eauto.\n  intros [beh' [A B]]. destruct B.\n  congruence.\n  destruct H1 as [t [C D]]. subst. contradiction.\nQed.\n\nEnd FORWARD_SIMULATIONS.\n\n(** * Backward simulations and program behaviors *)\n\nSection BACKWARD_SIMULATIONS.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable S: backward_simulation L1 L2.\n\nDefinition safe_along_behavior (s: state L1) (b: program_behavior) : Prop :=\n  forall t1 s' b2, Star L1 s t1 s' -> b = behavior_app t1 b2 ->\n     (exists r, final_state L1 s' r)\n  \\/ (exists t2, exists s'', Step L1 s' t2 s'').\n\nRemark safe_along_safe:\n  forall s b, safe_along_behavior s b -> safe L1 s.\nProof.\n  intros; red; intros. eapply H; eauto. symmetry; apply behavior_app_E0.\nQed.\n\nRemark star_safe_along:\n  forall s b t1 s' b2,\n  safe_along_behavior s b ->\n  Star L1 s t1 s' -> b = behavior_app t1 b2 ->\n  safe_along_behavior s' b2.\nProof.\n  intros; red; intros. eapply H. eapply star_trans; eauto.\n  subst. rewrite behavior_app_assoc. eauto.\nQed.\n\nRemark not_safe_along_behavior:\n  forall s b,\n  ~ safe_along_behavior s b ->\n  exists t, exists s',\n     behavior_prefix t b\n  /\\ Star L1 s t s'\n  /\\ Nostep L1 s'\n  /\\ (forall r, ~(final_state L1 s' r)).\nProof.\n  intros.\n  destruct (not_all_ex_not _ _ H) as [t1 A]; clear H.\n  destruct (not_all_ex_not _ _ A) as [s' B]; clear A.\n  destruct (not_all_ex_not _ _ B) as [b2 C]; clear B.\n  destruct (imply_to_and _ _ C) as [D E]; clear C.\n  destruct (imply_to_and _ _ E) as [F G]; clear E.\n  destruct (not_or_and _ _ G) as [P Q]; clear G.\n  exists t1; exists s'.\n  split. exists b2; auto.\n  split. auto.\n  split. red; intros; red; intros. elim Q. exists t; exists s'0; auto.\n  intros; red; intros. elim P. exists r; auto.\nQed.\n\nLemma backward_simulation_star:\n  forall s2 t s2', Star L2 s2 t s2' ->\n  forall i s1 b, S i s1 s2 -> safe_along_behavior s1 (behavior_app t b) ->\n  exists i', exists s1', Star L1 s1 t s1' /\\ S i' s1' s2'.\nProof.\n  induction 1; intros.\n  exists i; exists s1; split; auto. apply star_refl.\n  exploit (bsim_simulation S); eauto. eapply safe_along_safe; eauto.\n  intros [i' [s1' [A B]]].\n  assert (Star L1 s0 t1 s1'). intuition. apply plus_star; auto.\n  exploit IHstar; eauto. eapply star_safe_along; eauto.\n  subst t; apply behavior_app_assoc.\n  intros [i'' [s2'' [C D]]].\n  exists i''; exists s2''; split; auto. eapply star_trans; eauto.\nQed.\n\nLemma backward_simulation_forever_silent:\n  forall i s1 s2,\n  Forever_silent L2 s2 -> S i s1 s2 -> safe L1 s1 ->\n  Forever_silent L1 s1.\nProof.\n  assert (forall i s1 s2,\n         Forever_silent L2 s2 -> S i s1 s2 -> safe L1 s1 ->\n         forever_silent_N (step L1) (bsim_order S) (globalenv L1) i s1).\n    cofix COINDHYP; intros.\n    inv H.  destruct (bsim_simulation S _ _ _ H2 _ H0 H1) as [i' [s2' [A B]]].\n    destruct A as [C | [C D]].\n    eapply forever_silent_N_plus; eauto. eapply COINDHYP; eauto.\n      eapply star_safe; eauto. apply plus_star; auto.\n    eapply forever_silent_N_star; eauto. eapply COINDHYP; eauto.\n      eapply star_safe; eauto.\n  intros. eapply forever_silent_N_forever; eauto. apply bsim_order_wf.\nQed.\n\nLemma backward_simulation_forever_reactive:\n  forall i s1 s2 T,\n  Forever_reactive L2 s2 T -> S i s1 s2 -> safe_along_behavior s1 (Reacts T) ->\n  Forever_reactive L1 s1 T.\nProof.\n  cofix COINDHYP; intros. inv H.\n  destruct (backward_simulation_star H2 _ (Reacts T0) H0) as [i' [s1' [A B]]]; eauto.\n  econstructor; eauto. eapply COINDHYP; eauto. eapply star_safe_along; eauto.\nQed.\n\nLemma backward_simulation_state_behaves:\n  forall i s1 s2 beh2,\n  S i s1 s2 -> state_behaves L2 s2 beh2 ->\n  exists beh1, state_behaves L1 s1 beh1 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. destruct (classic (safe_along_behavior s1 beh2)).\n(* 1. Safe along *)\n  exists beh2; split; [idtac|apply behavior_improves_refl].\n  inv H0.\n(* termination *)\n  assert (Terminates t r = behavior_app t (Terminates E0 r)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  exploit (bsim_match_final_states S); eauto.\n    eapply safe_along_safe. eapply star_safe_along; eauto.\n  intros [s1'' [C D]].\n  econstructor. eapply star_trans; eauto. traceEq. auto.\n(* silent divergence *)\n  assert (Diverges t = behavior_app t (Diverges E0)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  econstructor. eauto. eapply backward_simulation_forever_silent; eauto.\n  eapply safe_along_safe. eapply star_safe_along; eauto.\n(* reactive divergence *)\n  econstructor. eapply backward_simulation_forever_reactive; eauto.\n(* goes wrong *)\n  assert (Goes_wrong t = behavior_app t (Goes_wrong E0)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  exploit (bsim_progress S); eauto. eapply safe_along_safe. eapply star_safe_along; eauto.\n  intros [[r FIN] | [t' [s2' STEP2]]].\n  elim (H4 _ FIN).\n  elim (H3 _ _ STEP2).\n\n(* 2. Not safe along *)\n  exploit not_safe_along_behavior; eauto.\n  intros [t [s1' [PREF [STEPS [NOSTEP NOFIN]]]]].\n  exists (Goes_wrong t); split.\n  econstructor; eauto.\n  right. exists t; auto.\nQed.\n\nTheorem backward_simulation_behavior_improves:\n  forall beh2, program_behaves L2 beh2 ->\n  exists beh1, program_behaves L1 beh1 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H.\n(* L2's initial state is defined. *)\n  destruct (classic (exists s1, initial_state L1 s1)) as [[s1 INIT] | NOINIT].\n(* L1's initial state is defined too. *)\n  exploit (bsim_match_initial_states S); eauto. intros [i [s1' [INIT1' MATCH]]].\n  exploit backward_simulation_state_behaves; eauto. intros [beh1 [A B]].\n  exists beh1; split; auto. econstructor; eauto.\n(* L1 has no initial state *)\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros. elim NOINIT; exists s0; auto.\n  apply behavior_improves_bot.\n(* L2 has no initial state *)\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros.\n  exploit (bsim_initial_states_exist S); eauto. intros [s2 INIT2].\n  elim (H0 s2); auto.\n  apply behavior_improves_refl.\nQed.\n\nCorollary backward_simulation_same_safe_behavior:\n  (forall beh, program_behaves L1 beh -> not_wrong beh) ->\n  (forall beh, program_behaves L2 beh -> program_behaves L1 beh).\nProof.\n  intros. exploit backward_simulation_behavior_improves; eauto.\n  intros [beh' [A B]]. destruct B.\n  congruence.\n  destruct H1 as [t [C D]]. subst. elim (H (Goes_wrong t)). auto.\nQed.\n\nEnd BACKWARD_SIMULATIONS.\n\n(** * Program behaviors for the \"atomic\" construction *)\n\nSection ATOMIC.\n\nVariable L: semantics.\nHypothesis Lwb: well_behaved_traces L.\n\nRemark atomic_finish: forall s t, output_trace t -> Star (atomic L) (t, s) t (E0, s).\nProof.\n  induction t; intros.\n  apply star_refl.\n  simpl in H; destruct H. eapply star_left; eauto.\n  simpl. apply atomic_step_continue; auto. simpl; auto. auto.\nQed.\n\nLemma step_atomic_plus:\n  forall s1 t s2, Step L s1 t s2 -> 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 B: bigstep_semantics.\nVariable L: semantics.\nHypothesis sound: bigstep_sound B L.\n\nLemma behavior_bigstep_terminates:\n  forall t r,\n  bigstep_terminates B t r -> program_behaves L (Terminates t r).\nProof.\n  intros. exploit (bigstep_terminates_sound sound); eauto.\n  intros [s1 [s2 [P [Q R]]]].\n  econstructor; eauto. econstructor; eauto.\nQed.\n\nLemma behavior_bigstep_diverges:\n  forall T,\n  bigstep_diverges B T ->\n  program_behaves L (Reacts T)\n  \\/ exists t, program_behaves L (Diverges t) /\\ traceinf_prefix t T.\nProof.\n  intros. exploit (bigstep_diverges_sound sound); eauto. intros [s1 [P Q]].\n  exploit forever_silent_or_reactive; eauto. intros [X | [t [s' [T' [X [Y Z]]]]]].\n  left. econstructor; eauto. constructor; auto.\n  right. exists t; split. econstructor; eauto. econstructor; eauto. exists T'; auto.\nQed.\n\nEnd BIGSTEP_BEHAVIORS.\n", "meta": {"author": "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/common/Behaviors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.18655885981546744}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import RData.\nRequire Import CalLock.\nRequire Import Constants.\nRequire Import LockOpsQ.Spec.\nRequire Import HypsecCommLib.\nRequire Import LockOpsQ.Layer.\n\nLocal Open Scope Z_scope.\n\nSection LockOpsHSpec.\n\n  Definition wait_hlock_spec (lk: Z) (adt: RData) : option RData :=\n    match ZMap.get lk adt.(log), ZMap.get lk adt.(lock) with\n    | l, LockFalse =>\n      let wl := WAIT_LOCK (Z.to_nat lock_bound) in\n      let to := ZMap.get lk adt.(oracle) in\n      let l' := TEVENT adt.(curid) (TTICKET wl) ::\n                to adt.(curid) l ++ l in\n      match H_CalLock l' with\n      | Some _ => Some adt {log: ZMap.set lk (l') adt.(log)}\n                           {lock: ZMap.set lk (LockOwn false) adt.(lock)}\n      | _ => None\n      end\n    | _, _ => None\n    end\n  .\n\n  Definition pass_hlock_spec (lk: Z) (adt: RData) : option RData :=\n    match ZMap.get lk (log adt), ZMap.get lk adt.(lock) with\n      | l, LockOwn false =>\n        let l' := TEVENT adt.(curid) (TTICKET REL_LOCK) :: l in\n        match H_CalLock l' with\n          | Some _ => Some adt {log: ZMap.set lk (l') adt.(log)}\n                               {lock: ZMap.set lk LockFalse adt.(lock)}\n          | _ => None\n        end\n      | _,_ => None\n    end\n  .\n\nEnd LockOpsHSpec.\n\nSection LockOpsHSpecLow.\n\n  Context `{real_params: RealParams}.\n\n  Notation LDATA := RData.\n\n  Notation LDATAOps := (cdata (cdata_ops := LockOpsQ_ops) LDATA).\n\n  Definition wait_hlock_spec0 (lk: Z) (adt: RData) : option RData :=\n    wait_qlock_spec lk adt.\n\n  Definition pass_hlock_spec0 (lk: Z) (adt: RData) : option RData :=\n    pass_qlock_spec lk adt.\n\n  Inductive wait_hlock_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | wait_hlock_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' lk\n      (Hinv: high_level_invariant labd)\n      (Hspec: wait_hlock_spec0 (Int.unsigned lk) labd = Some labd'):\n      wait_hlock_spec_low_step s WB ((Vint lk)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive pass_hlock_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | pass_hlock_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' lk\n      (Hinv: high_level_invariant labd)\n      (Hspec: pass_hlock_spec0 (Int.unsigned lk) labd = Some labd'):\n      pass_hlock_spec_low_step s WB ((Vint lk)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModelX}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Definition wait_hlock_spec_low: compatsem LDATAOps :=\n      csem wait_hlock_spec_low_step (type_of_list_type (Tint32::nil)) Tvoid.\n\n    Definition pass_hlock_spec_low: compatsem LDATAOps :=\n      csem pass_hlock_spec_low_step (type_of_list_type (Tint32::nil)) Tvoid.\n\n  End WITHMEM.\n\nEnd LockOpsHSpecLow.\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/sekvm/LockOpsH/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1865588563139916}}
{"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 x86proved.x86.macros.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nOpen Scope instr_scope.\nOpen Scope string_scope.\n\nDefinition call_cdecl2 f arg1 arg2 :=\n  PUSH arg2;; PUSH arg1;; CALL f;; ADD ESP, 8.\n\n(*=main *)\nExample main :=\n  IMPORTDLL \"MSVCRT.DLL\";\n  IMPORT \"printf\" as printf;\n  IMPORTDLL \"exporter.dll\";\n  IMPORT \"add\" as add;\n  SECTION CODE\nLOCAL greeting;\nLOCAL answer;\n  MOV EDI, printf;; PUSH greeting;; CALL [EDI];; ADD ESP, 4;;\n  MOV EDI, add;;\n  MOV EAX, 19;;\n  MOV EBX, 23;;\n  CALL [EDI];;\n  MOV EDI, printf;;\n  call_cdecl2 ([EDI]%ms) answer EAX;;\n  RET 0;;\ngreeting:;;\n  ds \"Hello!\";; db #10;; db #0;;\nanswer:;;\n  ds \"The answer is %d.\";; db #10;; db #0.\n(*=End *)\n\n(*=mainBytes *)\nCompute makeEXE #x\"00AB0000\" \"importer.exe\" main.\n(*=End *)\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/importer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1865588563139916}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Linearization of the control-flow graph: translation from LTL to Linear *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Ordered.\nRequire Import FSets.\nRequire FSetAVL.\nRequire Import AST.\nRequire Import Errors.\nRequire Import Op.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import Linear.\nRequire Import Kildall.\nRequire Import Lattice.\n\nOpen Scope error_monad_scope.\n\n(** To translate from LTL to Linear, we must lay out the nodes\n  of the LTL control-flow graph in some linear order, and insert\n  explicit branches and conditional branches to make sure that\n  each node jumps to its successors as prescribed by the\n  LTL control-flow graph.  However, branches are not necessary\n  if the fall-through behaviour of LTLin instructions already\n  implements the desired flow of control.  For instance,\n  consider the two LTL blocks\n<<\n    L1: Lop op args res; Lbranch L2\n    L2: ...\n>>\n  If the instructions [L1] and [L2] are laid out consecutively in the LTLin\n  code, we can generate the following Linear code:\n<<\n    L1: Lop op args res\n    L2: ...\n>>\n  However, if this is not possible, an explicit [Lgoto] is needed:\n<<\n    L1: Lop op args res\n        Lgoto L2\n        ...\n    L2: ...\n>>\n  The main challenge in code linearization is therefore to pick a\n  ``good'' order for the nodes that exploits well the\n  fall-through behavior.  Many clever trace picking heuristics\n  have been developed for this purpose.  \n\n  In this file, we present linearization in a way that clearly\n  separates the heuristic part (choosing an order for the basic blocks)\n  from the actual code transformation parts.  We proceed in two passes:\n- Choosing an order for the nodes.  This returns an enumeration of CFG\n  nodes stating that they must be laid out in the order shown in the\n  list.\n- Generate Linear code where each node branches explicitly to its\n  successors, except if one of these successors is the immediately\n  following instruction.\n\n  The beauty of this approach is that correct code is generated\n  under surprisingly weak hypotheses on the enumeration of\n  CFG nodes: it suffices that every reachable instruction occurs\n  exactly once in the enumeration.  We therefore follow an approach\n  based on validation a posteriori: a piece of untrusted Caml code\n  implements the node enumeration heuristics, and the resulting\n  enumeration is checked for correctness by Coq functions that are\n  proved to be sound.\n*)\n\n(** * Determination of the order of basic blocks *)\n\n(** We first compute a mapping from CFG nodes to booleans,\n  indicating whether a CFG instruction is reachable or not.\n  This computation is a trivial forward dataflow analysis\n  where the transfer function is the identity: the successors\n  of a reachable instruction are reachable, by the very\n  definition of reachability. *)\n\nModule DS := Dataflow_Solver(LBoolean)(NodeSetForward).\n\nDefinition reachable_aux (f: LTL.function) : option (PMap.t bool) :=\n  DS.fixpoint\n    (LTL.fn_code f) successors_block\n    (fun pc r => r)\n    f.(fn_entrypoint) true.\n\nDefinition reachable (f: LTL.function) : PMap.t bool :=\n  match reachable_aux f with  \n  | None => PMap.init true\n  | Some rs => rs\n  end.\n\n(** We then enumerate the nodes of reachable blocks.\n  This task is performed by external, untrusted Caml code. *)\n\nParameter enumerate_aux: LTL.function -> PMap.t bool -> list node.\n\n(** Now comes the a posteriori validation of a node enumeration. *)\n\nModule Nodeset := FSetAVL.Make(OrderedPositive).\n\n(** Build a [Nodeset.t] from a list of nodes, checking that the list\n  contains no duplicates. *)\n\nFixpoint nodeset_of_list (l: list node) (s: Nodeset.t)\n                         {struct l}: res Nodeset.t :=\n  match l with\n  | nil => OK s\n  | hd :: tl =>\n      if Nodeset.mem hd s \n      then Error (msg \"Linearize: duplicates in enumeration\")\n      else nodeset_of_list tl (Nodeset.add hd s)\n  end.\n\nDefinition check_reachable_aux\n     (reach: PMap.t bool) (s: Nodeset.t)\n     (ok: bool) (pc: node) (bb: LTL.bblock) : bool :=\n  if reach!!pc then ok && Nodeset.mem pc s else ok.\n\nDefinition check_reachable\n     (f: LTL.function) (reach: PMap.t bool) (s: Nodeset.t) : bool :=\n  PTree.fold (check_reachable_aux reach s) f.(LTL.fn_code) true.\n\nDefinition enumerate (f: LTL.function) : res (list node) :=\n  let reach := reachable f in\n  let enum := enumerate_aux f reach in\n  do s <- nodeset_of_list enum Nodeset.empty;\n  if check_reachable f reach s\n  then OK enum\n  else Error (msg \"Linearize: wrong enumeration\").\n\n(** * Translation from LTL to Linear *)\n\n(** We now flatten the structure of the CFG graph, laying out\n  LTL blocks consecutively in the order computed by [enumerate],\n  and inserting branches to the labels of sucessors if necessary.\n  Whether to insert a branch or not is determined by\n  the [starts_with] function below.\n\n  For LTL conditional branches [Lcond cond args s1 s2],\n  we have two possible translations:\n<<\n      Lcond cond args s1;       or     Lcond (not cond) args s2;\n      Lgoto s2                         Lgoto s1\n>>\n  We favour the first translation if [s2] is the label of the\n  next instruction, and the second if [s1] is the label of the\n  next instruction, thus avoiding the insertion of a redundant [Lgoto]\n  instruction. *)\n\nFixpoint starts_with (lbl: label) (k: code) {struct k} : bool :=\n  match k with\n  | Llabel lbl' :: k' => if peq lbl lbl' then true else starts_with lbl k'\n  | _ => false\n  end.\n\nDefinition add_branch (s: label) (k: code) : code :=\n  if starts_with s k then k else Lgoto s :: k.\n\nFixpoint linearize_block (b: LTL.bblock) (k: code) : code :=\n  match b with\n  | nil => k\n  | LTL.Lop op args res :: b' =>\n      Lop op args res :: linearize_block b' k\n  | LTL.Lload chunk addr args dst :: b' =>\n      Lload chunk addr args dst :: linearize_block b' k\n  | LTL.Lgetstack sl ofs ty dst :: b' =>\n      Lgetstack sl ofs ty dst :: linearize_block b' k\n  | LTL.Lsetstack src sl ofs ty :: b' =>\n      Lsetstack src sl ofs ty :: linearize_block b' k\n  | LTL.Lstore chunk addr args src :: b' =>\n      Lstore chunk addr args src :: linearize_block b' k\n  | LTL.Lcall sig ros :: b' =>\n      Lcall sig ros :: linearize_block b' k\n  | LTL.Ltailcall sig ros :: b' =>\n      Ltailcall sig ros :: k\n  | LTL.Lbuiltin ef args res :: b' =>\n      Lbuiltin ef args res :: linearize_block b' k\n  | LTL.Lannot ef args :: b' =>\n      Lannot ef args :: linearize_block b' k\n  | LTL.Lbranch s :: b' =>\n      add_branch s k\n  | LTL.Lcond cond args s1 s2 :: b' =>\n      if starts_with s1 k then\n        Lcond (negate_condition cond) args s2 :: add_branch s1 k\n      else\n        Lcond cond args s1 :: add_branch s2 k\n  | LTL.Ljumptable arg tbl :: b' =>\n      Ljumptable arg tbl :: k\n  | LTL.Lreturn :: b' =>\n      Lreturn :: k\n  end.\n\n(** Linearize a function body according to an enumeration of its nodes.  *)\n\nDefinition linearize_node (f: LTL.function) (pc: node) (k: code) : code :=\n  match f.(LTL.fn_code)!pc with\n  | None => k\n  | Some b => Llabel pc :: linearize_block b k\n  end.\n\nDefinition linearize_body (f: LTL.function) (enum: list node) : code :=\n  list_fold_right (linearize_node f) enum nil.\n\n(** * Entry points for code linearization *)\n\nDefinition transf_function (f: LTL.function) : res Linear.function :=\n  do enum <- enumerate f;\n  OK (mkfunction\n       (LTL.fn_sig f)\n       (LTL.fn_stacksize f)\n       (add_branch (LTL.fn_entrypoint f) (linearize_body f enum))).\n\nDefinition transf_fundef (f: LTL.fundef) : res Linear.fundef :=\n  AST.transf_partial_fundef transf_function f.\n\nDefinition transf_program (p: LTL.program) : res Linear.program :=\n  transform_partial_program transf_fundef p.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Linearize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.1865588563139916}}
{"text": "(*! Frontend | Typechecking errors and error-reporting functions !*)\nRequire Import Koika.Common Koika.Types.\n\nSection TypeErrors.\n  Context {pos_t var_t fn_name_t: Type}.\n\n  Inductive basic_error_message :=\n  | OutOfBounds (pos: nat) (sig: array_sig)\n  | UnboundField (f: string) (sig: struct_sig)\n  | TypeMismatch (actual: type) (expected: type)\n  | KindMismatch (actual: type_kind) (expected: type_kind).\n\n  Inductive error_message :=\n  | ExplicitErrorInAst\n  | SugaredConstructorInAst\n  | UnboundVariable (var: var_t)\n  | UnboundEnumMember (f: string) (sig: enum_sig)\n  | BasicError (msg: basic_error_message)\n  | TooManyArguments (fn_name: fn_name_t) (nexpected: nat) (nextra: nat)\n  | TooFewArguments (fn_name: fn_name_t) (nexpected: nat) (nmissing: nat).\n\n  (* FIXME add ability to report error on meta arguments *)\n  (* FIXME and use this to fix the location of unbound field errors *)\n  Inductive fn_tc_error_loc := Arg1 | Arg2.\n  Definition fn_tc_error : Type := fn_tc_error_loc * basic_error_message.\n\n  Definition assert_kind (kind: type_kind) arg (tau: type)\n    : result (match kind with\n              | kind_bits => nat\n              | kind_enum sig => enum_sig\n              | kind_struct sig => struct_sig\n              | kind_array sig => array_sig\n              end) fn_tc_error :=\n    match kind, tau with\n    | kind_bits, bits_t sz => Success sz\n    | kind_enum _, enum_t sg => Success sg\n    | kind_struct _, struct_t sg => Success sg\n    | kind_array _, array_t sg => Success sg\n    | _, _ => Failure (arg, KindMismatch (kind_of_type tau) kind)\n    end.\n\n  (* Error sources live in prop, because they are only useful in interactive\n     mode: LV only cares about positions. *)\n  Inductive ErrorSource : Prop :=\n  | ErrSrc {T: Type} (t: T).\n\n  Record error :=\n    { epos: pos_t;\n      emsg: error_message;\n      esource: ErrorSource }.\nEnd TypeErrors.\n\nArguments basic_error_message : clear implicits.\nArguments fn_tc_error : clear implicits.\nArguments error_message : clear implicits.\nArguments error : clear implicits.\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/ErrorReporting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.1865588528125158}}
{"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 AMapping.\n\nSet Implicit Arguments.\n\n\nDefinition map_ident_in_memory (f: Loc.t -> Time.t -> Time.t -> Prop)\n           (mem: Memory.t): Prop :=\n  forall loc to\n         (TS: Time.le to (Memory.max_ts loc mem)),\n    f loc to to.\n\nDefinition map_ident_in_memory_bot\n           f mem\n           (MAP: map_ident_in_memory f mem)\n  :\n    mapping_map_bot f.\nProof.\n  ii. eapply MAP. eapply Time.bot_spec.\nQed.\n\nLemma map_ident_in_memory_closed_timemap\n      f mem tm\n      (MAP: map_ident_in_memory f mem)\n      (CLOSED: Memory.closed_timemap tm mem)\n  :\n    timemap_map f tm tm.\nProof.\n  ii. eapply MAP; eauto.\n  exploit CLOSED; eauto. intro x. des.\n  eapply Memory.max_ts_spec in x. des. eauto.\nQed.\n\nLemma map_ident_in_memory_closed_view\n      f mem vw\n      (MAP: map_ident_in_memory f mem)\n      (CLOSED: Memory.closed_view vw mem)\n  :\n    view_map f vw vw.\nProof.\n  inv CLOSED. econs.\n  - eapply map_ident_in_memory_closed_timemap; eauto.\n  - eapply map_ident_in_memory_closed_timemap; eauto.\nQed.\n\nLemma map_ident_in_memory_closed_tview\n      f mem tvw\n      (MAP: map_ident_in_memory f mem)\n      (CLOSED: TView.closed tvw mem)\n  :\n    tview_map f tvw tvw.\nProof.\n  inv CLOSED. econs.\n  - i. eapply map_ident_in_memory_closed_view; eauto.\n  - eapply map_ident_in_memory_closed_view; eauto.\n  - eapply map_ident_in_memory_closed_view; eauto.\nQed.\n\nLemma map_ident_in_memory_closed_opt_view\n      f mem vw\n      (MAP: map_ident_in_memory f mem)\n      (CLOSED: Memory.closed_opt_view vw mem)\n  :\n    opt_view_map f vw vw.\nProof.\n  inv CLOSED; econs.\n  eapply map_ident_in_memory_closed_view; eauto.\nQed.\n\nLemma map_ident_in_memory_closed_message\n      f mem msg\n      (MAP: map_ident_in_memory f mem)\n      (CLOSED: Memory.closed_message msg mem)\n  :\n    msg_map f msg msg.\nProof.\n  inv CLOSED; econs.\n  eapply map_ident_in_memory_closed_opt_view; eauto.\nQed.\n\nLemma map_ident_in_memory_promises\n      f mem0 mem\n      (MAP: map_ident_in_memory f mem)\n      (MAPLT: mapping_map_lt f)\n      (CLOSED: Memory.closed mem)\n      (MLE: Memory.le mem0 mem)\n  :\n    promises_map f mem0 mem0.\nProof.\n  inv CLOSED. econs.\n  - i. esplits; eauto.\n    + eapply mapping_map_lt_non_collapsable; auto.\n    + eapply MLE in GET. eapply Memory.max_ts_spec in GET. des.\n      eapply MAP; eauto.\n    + eapply MLE in GET. eapply CLOSED0 in GET. des.\n      eapply map_ident_in_memory_closed_message; eauto.\n  - i. esplits; eauto.\n    + eapply MLE in GET. eapply Memory.max_ts_spec in GET. des.\n      eapply MAP; eauto.\n    + eapply MLE in GET. eapply MAP. etrans.\n      * eapply memory_get_ts_le; eauto.\n      * eapply Memory.max_ts_spec in GET. des. auto.\nQed.\n\nLemma map_ident_in_memory_memory\n      f mem\n      (MAP: map_ident_in_memory f mem)\n      (MAPLT: mapping_map_lt f)\n      (CLOSED: Memory.closed mem)\n  :\n    memory_map f mem mem.\nProof.\n  eapply promises_map_memory_map.\n  eapply map_ident_in_memory_promises; eauto. refl.\nQed.\n\nLemma map_ident_in_memory_local\n      f mem lc\n      (MAP: map_ident_in_memory f mem)\n      (MAPLT: mapping_map_lt f)\n      (LOCAL: Local.wf lc mem)\n      (CLOSED: Memory.closed mem)\n  :\n    local_map f lc lc.\nProof.\n  inv LOCAL. econs.\n  - refl.\n  - eapply map_ident_in_memory_closed_tview; eauto.\n  - eapply map_ident_in_memory_promises; eauto.\nQed.\n\nLemma update_map_lt (f: Time.t -> Time.t -> Prop) to fto\n      (MAPLT: mapping_map_lt_loc f)\n      (NOMAPPED: forall fts (MAPPED: f to fts), False)\n      (LEFT: forall ts fts (TS: Time.lt ts to) (MAPPED: f ts fts),\n          Time.lt fts fto)\n      (RIGHT: forall ts fts (TS: Time.lt to ts) (MAPPED: f ts fts),\n          Time.lt fto fts)\n  :\n    mapping_map_lt_loc (fun ts fts => <<ORIG: f ts fts>> \\/ <<NEW: to = ts /\\ fto = fts>>).\nProof.\n  ii. des; clarify.\n  - eapply MAPLT; eauto.\n  - split; i.\n    + eapply RIGHT; eauto.\n    + destruct (Time.le_lt_dec t1 t0); auto. destruct l.\n      * eapply LEFT in H0; eauto.\n        exfalso. eapply Time.lt_strorder. etrans; eauto.\n      * inv H0. exfalso. eapply NOMAPPED; eauto.\n  - split; i.\n    + eapply LEFT; eauto.\n    + destruct (Time.le_lt_dec t1 t0); auto. destruct l.\n      * eapply RIGHT in H0; eauto.\n        exfalso. eapply Time.lt_strorder. etrans; eauto.\n      * inv H0. exfalso. eapply NOMAPPED; eauto.\n  - split; i.\n    + exfalso. eapply Time.lt_strorder; eauto.\n    + exfalso. eapply Time.lt_strorder; eauto.\nQed.\n\nFixpoint compressing_map (ts0 ts1: Time.t) (T: list Time.t) :=\n  match T with\n  | [] => bot2\n  | hd :: tl => (fun ts fts => ts = hd /\\ fts = Time.middle ts0 ts1)\n                  \\2/ compressing_map (Time.middle ts0 ts1) ts1 tl\n  end.\n\nLemma compressing_map_spec ts0 ts1 T\n      (TS: Time.lt ts0 ts1)\n      (SORTED: times_sorted T)\n  :\n    (<<MAPLT: mapping_map_lt_loc (compressing_map ts0 ts1 T)>>) /\\\n    (<<COMPLETE: forall to (IN: List.In to T), exists fto, (<<MAPPED: (compressing_map ts0 ts1 T) to fto>>)>>) /\\\n    (<<BOUND: forall to fto (MAPPED: (compressing_map ts0 ts1 T) to fto),\n        (<<IN: List.In to T>>) /\\ (<<TS0: Time.lt ts0 fto>>) /\\ (<<TS1: Time.lt fto ts1>>)>>).\nProof.\n  i. ginduction T.\n  - i. ss. splits.\n    + ii. clarify.\n    + i. clarify.\n    + i. clarify.\n  - i. ss. inv SORTED. exploit IHT.\n    { instantiate (1:=ts1). instantiate (1:=Time.middle ts0 ts1).\n      eapply Time.middle_spec; eauto. }\n    { eauto. }\n    i. des. clear IHT. splits.\n    + ii. des; clarify.\n      * split; i.\n        { exfalso. eapply Time.lt_strorder; eauto. }\n        { exfalso. eapply Time.lt_strorder; eauto. }\n      * eapply BOUND in MAP0. des.\n        eapply List.Forall_forall in HD; eauto. split; i.\n        { exfalso. eapply Time.lt_strorder; eauto. }\n        { exfalso. eapply Time.lt_strorder; eauto. }\n      * eapply BOUND in MAP1. des. split; i; auto.\n        eapply List.Forall_forall in HD; eauto.\n      * eapply MAPLT; eauto.\n    + i. des; clarify.\n      * esplits; eauto.\n      * eapply COMPLETE in IN. des. esplits; eauto.\n    + i. des; clarify.\n      * split; auto. eapply Time.middle_spec; auto.\n      * eapply BOUND in MAPPED. des. splits; auto.\n        etrans.\n        { eapply Time.middle_spec; eauto. }\n        { eauto. }\nQed.\n\nLemma shift_map_exists max ts0 ts1 (T: list Time.t)\n      (MAX: Time.le max ts0)\n      (TS: Time.lt ts0 ts1)\n  :\n    exists (f: Time.t -> Time.t -> Prop),\n      (<<COMPLETE: forall to (IN: List.In to T), exists fto, (<<MAPPED: f to fto>>)>>) /\\\n      (<<SAME: forall ts (TS: Time.le ts max), f ts ts>>) /\\\n      (<<BOUND: forall to fto (MAPPED: f to fto) (TS: Time.lt max to),\n          (Time.lt ts0 fto /\\ Time.lt fto ts1)>>) /\\\n      (<<MAPLT: mapping_map_lt_loc f>>)\n.\nProof.\n  hexploit (list_filter_exists (fun ts => Time.lt max ts) T). i. des.\n  hexploit (sorting_sorted l'). i. des.\n  hexploit (@compressing_map_spec ts0 ts1 (sorting l')); eauto. i. des.\n  exists ((fun ts fts => Time.le ts max /\\ ts = fts) \\2/ (compressing_map ts0 ts1 (sorting l'))).\n  splits.\n\n  - i. destruct (Time.le_lt_dec to max).\n    + esplits; eauto.\n    + hexploit (proj1 (COMPLETE to)).\n      { split; auto. } intros IN'. des.\n      eapply COMPLETE0 in IN'.\n      eapply COMPLETE1 in IN'. des. esplits; eauto.\n  - i. eauto.\n  - i. apply or_strengthen in MAPPED. des; clarify; eauto.\n    + exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; eauto.\n    + eapply BOUND in SAT. des. auto.\n\n  - ii. des; clarify.\n    + apply BOUND in MAP0. des.\n      eapply COMPLETE0 in IN. eapply COMPLETE in IN. des.\n      split; i.\n      * exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply H. } etrans.\n        { eapply MAP1. }\n        { left. auto. }\n      * exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply H. } etrans.\n        { eapply MAP1. } etrans.\n        { eapply MAX. }\n        { left. auto. }\n\n    + apply BOUND in MAP1. des.\n      apply COMPLETE0 in IN. eapply COMPLETE in IN. des.\n      split; i.\n      * eapply TimeFacts.le_lt_lt.\n        { eapply MAP0. }\n        eapply TimeFacts.le_lt_lt; eauto.\n      * eapply TimeFacts.le_lt_lt; eauto.\n\n    + eapply MAPLT; eauto.\nQed.\n\n\nDefinition pf_consistent_drf_shift lang (e0:Thread.t lang)\n           (spaces: Loc.t -> Time.t -> Prop)\n           (promises: Loc.t -> Time.t -> Prop)\n           (max: TimeMap.t)\n           (U AU: Loc.t -> Prop): Prop :=\n  (<<UPDATESMAX: forall loc (UPDATES: (U \\1/ AU) loc), max loc = Memory.max_ts loc (Thread.memory e0)>>) /\\\n  (<<CONSISTENT:\n     forall (gap newmax: TimeMap.t)\n            (GAP: forall loc (UPDATES: U loc \\/ AU loc),\n                Time.lt (max loc) (gap loc))\n            (NEWMAX: TimeMap.le max newmax),\n     exists e2 tr,\n       (<<STEPS: traced_step tr e0 e2>>) /\\\n\n       (<<TRACE: List.Forall (fun em => (no_sc /1\\ no_promise /1\\ (fun e => ThreadEvent.get_machine_event e = MachineEvent.silent)/1\\ (write_in (spaces \\2/ (fun loc to => (__guard__(U loc \\/ AU loc) /\\ Time.lt (max loc) to /\\ Time.lt to (gap loc))) \\2/                 (fun loc to => ~ U loc /\\ ~ AU loc /\\ Time.lt (newmax loc) to)))) (fst em)) tr>>) /\\\n\n       (<<COMPLETEU:\n          forall loc (SAT: U loc),\n          exists to from valr valw releasedr releasedw ordr ordw mem,\n            <<IN: List.In (ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw, mem) tr>> /\\ <<ORDR: Ordering.le ordr Ordering.strong_relaxed>> >>) /\\\n\n       (<<COMPLETEAU:\n          forall loc (SAT: AU loc),\n          exists to from valr valw releasedr releasedw ordr ordw mem,\n            <<IN: List.In (ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw, mem) tr>> >>) /\\\n\n       (<<COMPLETEW: forall loc to (PROMISED: promises loc to),\n           exists e m,\n             (<<IN: List.In (e, m) tr>>) /\\\n             (<<WRITETO: rlx_write_loc loc e>>)>>)\n         >>)\n.\n\nDefinition wf_time_evt (P: Loc.t -> Time.t -> Prop) (e: ThreadEvent.t) : Prop :=\n  match e with\n  | ThreadEvent.promise loc from to msg kind =>\n    (<<FROM: P loc from>>) /\\ (<<TO: P loc to>>)\n  | ThreadEvent.write loc from to val released ordw =>\n    (<<FROM: P loc from>>) /\\ (<<TO: P loc to>>)\n  | ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw =>\n    (<<FROM: P loc from>>) /\\ (<<TO: P loc to>>)\n  | _ => True\n  end.\n\nLemma wf_time_evt_mon P0 P1\n      (LE: P0 <2= P1)\n  :\n    wf_time_evt P0 <1= wf_time_evt P1.\nProof.\n  ii. unfold wf_time_evt in *. des_ifs; des; splits; eauto.\nQed.\n\nLemma step_times_list_exists lang (th0 th1: Thread.t lang) e\n      (STEP: AThread.step_allpf e th0 th1)\n  :\n    exists (times: Loc.t -> list Time.t),\n      (<<WFTIME: wf_time_evt (fun loc to => List.In to (times loc)) e>>).\nProof.\n  destruct e.\n  - exists (fun l => if Loc.eq_dec l loc then\n                       [from; to] else []).\n    econs; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n  - exists (fun _ => []). econs; eauto.\n  - exists (fun _ => []). econs; eauto.\n  - exists (fun l => if Loc.eq_dec l loc then\n                       [from; to] else []).\n    econs; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n  - exists (fun l => if Loc.eq_dec l loc then\n                       [tsr; tsw] else []).\n    econs; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n    + ss. splits; auto; des_ifs; ss; eauto.\n  - exists (fun _ => []). econs; eauto.\n  - exists (fun _ => []). econs; eauto.\n  - exists (fun _ => []). econs; eauto.\nQed.\n\nLemma traced_times_list_exists lang (th0 th1: Thread.t lang) tr\n      (STEPS: traced_step tr th0 th1)\n  :\n    exists (times: Loc.t -> list Time.t),\n      (<<WFTIME: List.Forall (fun em => wf_time_evt (fun loc to => List.In to (times loc)) (fst em)) tr>>).\nProof.\n  ginduction STEPS.\n  - exists (fun _ => []). econs.\n  - des. eapply step_times_list_exists in HD. des.\n    exists (fun loc => (times0 loc ++ times loc)). econs.\n    + eapply wf_time_evt_mon; eauto.\n      i. ss. eapply List.in_or_app; eauto.\n    + eapply List.Forall_impl; eauto.\n      i. ss. eapply wf_time_evt_mon; eauto.\n      i. ss. eapply List.in_or_app; eauto.\nQed.\n\nLemma wf_time_mapped_mappable (tr: list (ThreadEvent.t * Memory.t)) times f\n      (WFTIME: List.Forall (fun em => wf_time_evt (fun loc to => List.In to (times loc)) (fst em)) tr)\n      (COMPLETE: forall loc to (IN: List.In to (times loc)),\n          exists fto, (<<MAPPED: f loc to fto>>))\n  :\n    List.Forall (fun em => mappable_evt f (fst em)) tr.\nProof.\n  eapply List.Forall_impl; eauto. i. ss. destruct a. destruct t; ss.\n  - des. split.\n    + apply COMPLETE in FROM. des. esplit. eauto.\n    + apply COMPLETE in TO. des. esplit. eauto.\n  - des. split.\n    + apply COMPLETE in FROM. des. esplit. eauto.\n    + apply COMPLETE in TO. des. esplit. eauto.\n  - des. split.\n    + apply COMPLETE in FROM. des. esplit. eauto.\n    + apply COMPLETE in TO. des. esplit. eauto.\nQed.\n\nLemma step_wf_event lang (th0 th1: Thread.t lang) e\n      (INHABITED: Memory.inhabited (Thread.memory th0))\n      (STEP: AThread.step_allpf e th0 th1)\n  :\n    wf_event e.\nProof.\n  inv STEP. inv STEP0.\n  - inv STEP. inv LOCAL. ss.\n    eapply promise_wf_event; eauto.\n  - inv STEP. inv LOCAL; ss.\n    + inv LOCAL0. eapply write_wf_event; eauto.\n    + inv LOCAL1. inv LOCAL2. eapply write_wf_event; eauto.\nQed.\n\nLemma traced_step_wf_event lang (th0 th1: Thread.t lang) tr\n      (INHABITED: Memory.inhabited (Thread.memory th0))\n      (STEPS: traced_step tr th0 th1)\n  :\n    List.Forall (fun em => wf_event (fst em)) tr.\nProof.\n  ginduction STEPS; i.\n  - econs.\n  - econs.\n    + eapply step_wf_event; eauto.\n    + eapply IHSTEPS. inv HD. eapply AThread.step_inhabited; eauto.\nQed.\n\n\nLemma pf_consistent_drf_src_shift lang (e0: Thread.t lang) spaces promises max U AU\n      (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n      (SC: Memory.closed_timemap (Thread.sc e0) (Thread.memory e0))\n      (CLOSED: Memory.closed (Thread.memory e0))\n      (CONSISTENT: pf_consistent_drf_src e0 spaces promises max U AU)\n  :\n    pf_consistent_drf_shift e0 spaces promises max U AU.\nProof.\n  ii. unfold pf_consistent_drf_src in CONSISTENT. des.\n  split.\n  { auto. } red.\n  exploit (choice\n             (fun loc to =>\n                forall (SAT: MU loc),\n                  (<<NOTUPDATES: ~ U loc /\\ ~ AU loc>>) /\\\n                  (<<TS0: Time.le (Memory.max_ts loc (Thread.memory e0)) to>>) /\\\n                  (<<TS1: Time.lt to (max loc)>>) /\\\n                  (<<BLANK: Interval.mem (to, (max loc)) <1= spaces loc>>))).\n  { intros loc. destruct (classic (MU loc)).\n    - eapply MYUPDATES in H. des. exists to. esplits; eauto.\n    - exists Time.bot. i. clarify. }\n  i. clear MYUPDATES. destruct x0 as [mu MYUPDATES].\n\n  exploit traced_times_list_exists; eauto. i. des.\n  exploit (choice\n             (fun loc (floc: Time.t -> Time.t -> Prop) =>\n                (<<COMPLETE: forall to (IN: List.In to (times loc)),\n                    exists fto, (<<MAPPED: floc to fto>>)>>) /\\\n                (<<NUS: forall (SAT: ~ U loc /\\ ~ AU loc /\\ ~ MU loc),\n                    (<<SAME: forall ts (TS: Time.le ts (max loc)), floc ts ts>>) /\\\n                    (<<MAPGAP: exists fts, <<MAPPED: floc (max' loc) fts>> /\\ Time.lt (newmax loc) fts>>) /\\\n                    (<<RANGE: forall ts fts (MAPPED: floc ts fts) (TS: Time.lt (max loc) ts),\n                        Time.lt (newmax loc) fts>>)>>) /\\\n                (<<UAUS: forall (SAT: __guard__(U loc \\/ AU loc)),\n                    (<<SAME: forall ts (TS: Time.le ts (max loc)), floc ts ts>>) /\\\n                    (<<RANGE: forall ts fts (MAPPED: floc ts fts) (TS: Time.lt (max loc) ts),\n                        Time.lt (max loc) fts /\\ Time.lt fts (gap loc)>>)>>) /\\\n                (<<MUS: forall (SAT: MU loc),\n                    (<<SAME: forall ts (TS: Time.le ts (mu loc)), floc ts ts>>) /\\\n                    (<<RANGE: forall ts fts (MAPPED: floc ts fts) (TS: Time.lt (mu loc) ts),\n                        Time.lt (mu loc) fts /\\ Time.lt fts (max loc)>>)>>) /\\\n                (<<MAPLT: mapping_map_lt_loc floc>>)\n          )).\n  { intros loc. destruct (classic (MU loc)).\n    { exploit MYUPDATES; eauto. i. des.\n      exploit (@shift_map_exists (mu loc) (mu loc) (max loc)); auto.\n      { refl. }\n      i. des. esplits; eauto; i; des; clarify.\n      exfalso. unguard. des; clarify.\n    }\n    destruct (classic (__guard__(U loc \\/ AU loc))).\n    { exploit (@shift_map_exists (max loc) (max loc) (gap loc)); auto.\n      { refl. }\n      i. des. esplits; eauto; i.\n      - clarify. unguard. exfalso. des; eauto.\n      - exploit MYUPDATES; eauto. i. des. unguard. des; clarify. }\n    { exploit (@shift_map_exists (max loc) (newmax loc) (Time.incr (newmax loc)) ((max' loc)::(times loc))); auto.\n      { apply Time.incr_spec. }\n      i. des. esplits; eauto; i; clarify.\n      { eapply COMPLETE; eauto. ss. auto. } splits; auto.\n      { ss. exploit COMPLETE; eauto. i. des. esplits; eauto.\n        exploit BOUND; eauto. i. des. auto. }\n      i. exploit BOUND; eauto. i. des; auto.\n    }\n  }\n  intros [f FSPEC].\n\n  assert (MAPLT: mapping_map_lt f).\n  { eapply mapping_map_lt_locwise. i. specialize (FSPEC loc). des. auto. }\n  assert (IDENTINMAP: map_ident_in_memory f (Thread.memory e0)).\n  { ii. specialize (FSPEC loc). des.\n    destruct (classic (MU loc)).\n    { exploit MUS; eauto. i. des.\n      exploit MYUPDATES; eauto. i. des.\n      eapply SAME. etrans; eauto. }\n    destruct (classic (__guard__(U loc \\/ AU loc))).\n    { exploit UAUS; eauto. i. des.\n      eapply SAME. etrans; eauto. }\n    { exploit NUS; eauto.\n      { unguard. apply not_or_and in H0. des. split; auto. }\n      i. des.\n      eapply SAME. etrans; eauto. }\n  }\n  assert (MAPEQ: mapping_map_eq f).\n  { eapply mapping_map_lt_map_eq; eauto. }\n  assert (MAPLE: mapping_map_le f).\n  { eapply mapping_map_lt_map_le; eauto. }\n\n  assert (MAPPABLE: List.Forall (fun em => mappable_evt f (fst em)) tr).\n  { eapply wf_time_mapped_mappable; eauto. i.\n    specialize (FSPEC loc). des.\n    destruct (classic (MU loc)).\n    { exploit MUS; eauto. }\n    destruct (classic (__guard__(U loc \\/ AU loc))).\n    { exploit UAUS; eauto. }\n    { exploit NUS; eauto.\n      unguard. apply not_or_and in H0. des. split; auto. }\n  }\n\n  exploit traced_step_wf_event; eauto.\n  { inv CLOSED. auto. } intros WFEVT.\n\n  destruct e0 as [st0 lc0 sc0 mem0].\n  destruct e2 as [st1 lc1 sc1 mem1]. ss.\n  hexploit traced_steps_map; try apply STEPS; eauto.\n  { eapply map_ident_in_memory_bot; eauto. }\n  { eapply map_ident_in_memory_local; eauto. }\n  { eapply map_ident_in_memory_memory; eauto. }\n  { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n  { eapply map_ident_in_memory_closed_timemap; eauto. }\n  { refl. }\n  i. des. esplits; eauto.\n\n  - eapply List.Forall_forall. i.\n    eapply list_Forall2_in in H; eauto. des. destruct a, x. ss.\n    eapply List.Forall_forall in TRACE; eauto. ss. des.\n    eapply List.Forall_forall in WFEVT; eauto. ss.\n    inv EVENT; ss.\n\n    + splits; auto.\n      specialize (FSPEC loc). des.\n      destruct (classic (MU loc)).\n      { exploit MUS; eauto. i. des.\n        exploit MYUPDATES; eauto. i. des. unguard. des.\n        - left. left. eapply BLANK. inv IN0. ss.\n          assert (TS: Time.le (mu loc) from).\n          { destruct (Time.le_lt_dec (mu loc) from); auto. exfalso.\n            exploit (TRACE1 (Time.meet (mu loc) to)).\n            - unfold Time.meet. des_ifs; econs; ss. refl.\n            - unfold later_times. i. eapply Time.lt_strorder.\n              eapply TimeFacts.lt_le_lt.\n              { eapply x0. } etrans.\n              { eapply Time.meet_l. } etrans.\n              { left. eauto. }\n              eauto.\n          }\n          econs; ss.\n          + eapply TimeFacts.le_lt_lt; [|eapply FROM0].\n            eapply MAPLE.\n            * eapply SAME; eauto. refl.\n            * eauto.\n            * eauto.\n          + etrans; eauto.\n            left. eapply RANGE.\n            * eauto.\n            * eapply TimeFacts.le_lt_lt; eauto.\n        - ss. inv IN0. destruct (Time.le_lt_dec t (mu loc)).\n          + dup l. eapply SAME in l; eauto.\n            exploit (TRACE1 t).\n            { econs; ss.\n              - eapply MAPLT; eauto.\n              - destruct (Time.le_lt_dec t to); auto.\n                erewrite (MAPLT loc) in l1; try eassumption.\n                exfalso. eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n                { eapply TO0. }\n                { auto. }\n            }\n            i. des. auto.\n          + dup l. left. left. eapply BLANK. econs; ss.\n            exploit RANGE.\n            * eapply TO.\n            * eapply MAPLT.\n              { eapply SAME. refl. }\n              { eauto. }\n              eapply TimeFacts.lt_le_lt; eauto.\n            * i. des. etrans.\n              { eapply TO0. }\n              { left. auto. }\n      }\n      destruct (classic (__guard__(U loc \\/ AU loc))).\n      { exploit UAUS; eauto. i. des. unguard. guardH H0. des.\n        - left. right. split; auto. ss.\n          assert (TS: Time.le (max loc) from).\n          { destruct (Time.le_lt_dec (max loc) from); eauto. exfalso.\n            exploit (TRACE1 (Time.meet to (max loc))).\n            { unfold Time.meet. des_ifs; econs; ss.\n              - refl.\n              - left. auto. }\n            unfold later_times. i.\n            eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply x0. } etrans.\n            { eapply Time.meet_r. }\n            eauto. }\n          exploit RANGE; try apply TO.\n          { eapply TimeFacts.le_lt_lt.\n            - eapply TS.\n            - eauto. } i. des. inv IN0. split.\n          + eapply TimeFacts.le_lt_lt; [|eapply FROM0]. ss.\n            eapply MAPLE.\n            * eapply SAME. refl.\n            * eauto.\n            * eauto.\n          + eapply TimeFacts.le_lt_lt; eauto.\n        - left. left. ss. exploit (TRACE1 to).\n          { econs; ss. refl. } i. des.\n          exploit (SAME to); eauto. i.\n          hexploit (MAPEQ _ _ _ _ x2 TO). i. subst.\n          exploit (SAME from); eauto.\n          { etrans; eauto. left. auto. } i.\n          hexploit (MAPEQ _ _ _ _ x3 FROM). i. subst.\n          eapply TRACE1; eauto. }\n      { exploit NUS; eauto.\n        { unguard. guardH TRACE1. apply not_or_and in H0. des. split; auto. }\n        i. des. unguard. apply not_or_and in H0. des.\n        - right. splits; auto. inv IN0. ss.\n          transitivity ffrom; auto. eapply RANGE; eauto.\n          destruct (Time.le_lt_dec from (max loc)); auto. exfalso.\n          exploit (TRACE1 (Time.middle (max loc) (max' loc))).\n          { econs; ss.\n            - eapply TimeFacts.le_lt_lt; eauto.\n              eapply Time.middle_spec; eauto.\n            - etrans.\n              + left. eapply Time.middle_spec; eauto.\n              + left. eapply TRACE1; eauto. econs; ss. refl. }\n          unfold later_times. i.\n          eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply x0. }\n          { left. eapply Time.middle_spec; eauto. }\n        - left. left. ss. exploit (TRACE1 to).\n          { econs; ss. refl. } i. des.\n          exploit (SAME to); eauto. i.\n          hexploit (MAPEQ _ _ _ _ x2 TO). i. subst.\n          exploit (SAME from); eauto.\n          { etrans; eauto. left. auto. } i.\n          hexploit (MAPEQ _ _ _ _ x3 FROM). i. subst.\n          eapply TRACE1; eauto. }\n\n\n    + splits; auto.\n      specialize (FSPEC loc). des.\n      destruct (classic (MU loc)).\n      { exploit MUS; eauto. i. des.\n        exploit MYUPDATES; eauto. i. des. unguard. des.\n        - left. left. eapply BLANK. inv IN0. ss.\n          assert (TS: Time.le (mu loc) from).\n          { destruct (Time.le_lt_dec (mu loc) from); auto. exfalso.\n            exploit (TRACE1 (Time.meet (mu loc) to)).\n            - unfold Time.meet. des_ifs; econs; ss. refl.\n            - unfold later_times. i. eapply Time.lt_strorder.\n              eapply TimeFacts.lt_le_lt.\n              { eapply x0. } etrans.\n              { eapply Time.meet_l. } etrans.\n              { left. eauto. }\n              eauto.\n          }\n          econs; ss.\n          + eapply TimeFacts.le_lt_lt; [|eapply FROM0].\n            eapply MAPLE.\n            * eapply SAME; eauto. refl.\n            * eauto.\n            * eauto.\n          + etrans; eauto.\n            left. eapply RANGE.\n            * eauto.\n            * eapply TimeFacts.le_lt_lt; eauto.\n        - ss. inv IN0. destruct (Time.le_lt_dec t (mu loc)).\n          + dup l. eapply SAME in l; eauto.\n            exploit (TRACE1 t).\n            { econs; ss.\n              - eapply MAPLT; eauto.\n              - destruct (Time.le_lt_dec t to); auto.\n                erewrite (MAPLT loc) in l1; try eassumption.\n                exfalso. eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt.\n                { eapply TO0. }\n                { auto. }\n            }\n            i. des. auto.\n          + dup l. left. left. eapply BLANK. econs; ss.\n            exploit RANGE.\n            * eapply TO.\n            * eapply MAPLT.\n              { eapply SAME. refl. }\n              { eauto. }\n              eapply TimeFacts.lt_le_lt; eauto.\n            * i. des. etrans.\n              { eapply TO0. }\n              { left. auto. }\n      }\n      destruct (classic (__guard__(U loc \\/ AU loc))).\n      { exploit UAUS; eauto. i. des. unguard. guardH H0. des.\n        - left. right. split; auto. ss.\n          assert (TS: Time.le (max loc) from).\n          { destruct (Time.le_lt_dec (max loc) from); eauto. exfalso.\n            exploit (TRACE1 (Time.meet to (max loc))).\n            { unfold Time.meet. des_ifs; econs; ss.\n              - refl.\n              - left. auto. }\n            unfold later_times. i.\n            eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply x0. } etrans.\n            { eapply Time.meet_r. }\n            eauto. }\n          exploit RANGE; try apply TO.\n          { eapply TimeFacts.le_lt_lt.\n            - eapply TS.\n            - eauto. } i. des. inv IN0. split.\n          + eapply TimeFacts.le_lt_lt; [|eapply FROM0]. ss.\n            eapply MAPLE.\n            * eapply SAME. refl.\n            * eauto.\n            * eauto.\n          + eapply TimeFacts.le_lt_lt; eauto.\n        - left. left. ss. exploit (TRACE1 to).\n          { econs; ss. refl. } i. des.\n          exploit (SAME to); eauto. i.\n          hexploit (MAPEQ _ _ _ _ x2 TO). i. subst.\n          exploit (SAME from); eauto.\n          { etrans; eauto. left. auto. } i.\n          hexploit (MAPEQ _ _ _ _ x3 FROM). i. subst.\n          eapply TRACE1; eauto. }\n      { exploit NUS; eauto.\n        { unguard. guardH TRACE1. apply not_or_and in H0. des. split; auto. }\n        i. des. unguard. apply not_or_and in H0. des.\n        - right. splits; auto. inv IN0. ss.\n          transitivity ffrom; auto. eapply RANGE; eauto.\n          destruct (Time.le_lt_dec from (max loc)); auto. exfalso.\n          exploit (TRACE1 (Time.middle (max loc) (max' loc))).\n          { econs; ss.\n            - eapply TimeFacts.le_lt_lt; eauto.\n              eapply Time.middle_spec; eauto.\n            - etrans.\n              + left. eapply Time.middle_spec; eauto.\n              + left. eapply TRACE1; eauto. econs; ss. refl. }\n          unfold later_times. i.\n          eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply x0. }\n          { left. eapply Time.middle_spec; eauto. }\n        - left. left. ss. exploit (TRACE1 to).\n          { econs; ss. refl. } i. des.\n          exploit (SAME to); eauto. i.\n          hexploit (MAPEQ _ _ _ _ x2 TO). i. subst.\n          exploit (SAME from); eauto.\n          { etrans; eauto. left. auto. } i.\n          hexploit (MAPEQ _ _ _ _ x3 FROM). i. subst.\n          eapply TRACE1; eauto. }\n\n  - i. eapply COMPLETEU in SAT. des.\n    eapply list_Forall2_in2 in IN; eauto. des. ss. destruct b. ss.\n    inv EVENT. esplits; eauto.\n\n  - i. eapply COMPLETEAU in SAT. des.\n    eapply list_Forall2_in2 in IN; eauto. des. ss. destruct b. ss.\n    inv EVENT. esplits; eauto.\n\n  - i. eapply COMPLETEW in PROMISED. des.\n    eapply list_Forall2_in2 in IN; eauto. des. ss. destruct b. ss.\n    inv EVENT; ss.\n    + esplits; eauto.\n    + esplits; eauto.\n\nQed.\n\n\n\nDefinition pf_consistent_drf_future lang (e0:Thread.t lang)\n           (spaces: Loc.t -> Time.t -> Prop)\n           (promises: Loc.t -> Time.t -> Prop)\n           (U AU: Loc.t -> Prop): Prop :=\n  forall mem_future sc_future\n         (UNCH: unchanged_on spaces (Thread.memory e0) mem_future)\n         (ATTATCH: not_attatched (fun loc to => (<<UPDATES: (U \\1/ AU) loc>>) /\\ (<<MAX: Memory.max_ts loc (Thread.memory e0) = to>>)) mem_future),\n  exists e2 tr,\n    (<<STEPS: traced_step tr (Thread.mk _ (Thread.state e0) (Thread.local e0) sc_future mem_future) e2>>) /\\\n\n    (<<TRACE: List.Forall (fun em => no_promise (fst em) /\\ ThreadEvent.get_machine_event (fst em) = MachineEvent.silent) tr>>) /\\\n\n    (<<COMPLETEU:\n       forall loc (SAT: U loc),\n       exists to from valr valw releasedr releasedw ordr ordw mem,\n         <<IN: List.In (ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw, mem) tr>> /\\ <<ORDR: Ordering.le ordr Ordering.strong_relaxed>> >>) /\\\n\n    (<<COMPLETEAU:\n       forall loc (SAT: AU loc),\n       exists to from valr valw releasedr releasedw ordr ordw mem,\n         <<IN: List.In (ThreadEvent.update loc from to valr valw releasedr releasedw ordr ordw, mem) tr>> >>) /\\\n\n    (<<COMPLETEW: forall loc to (PROMISED: promises loc to),\n        exists e m,\n          (<<IN: List.In (e, m) tr>>) /\\\n          (<<WRITETO: rlx_write_loc loc e>>)>>)\n.\n\n\nLemma unchanged_on_traced_step\n      L lang th_src th_tgt th_tgt' st st' v v' prom' sc sc'\n      mem_src mem_tgt mem_tgt' tr_tgt\n      (PRED: List.Forall (fun em => (write_in L /1\\ no_promise) (fst em)) tr_tgt)\n      (STEPS: traced_step tr_tgt th_tgt th_tgt')\n      (TH_SRC: th_src = Thread.mk lang st (Local.mk v Memory.bot) sc mem_src)\n      (TH_TGT0: th_tgt = Thread.mk lang st (Local.mk v Memory.bot) sc mem_tgt)\n      (TH_TGT1: th_tgt' = Thread.mk lang st' (Local.mk v' prom') sc' mem_tgt')\n      (MEM: unchanged_on L mem_tgt mem_src)\n  :\n    exists tr_src mem_src',\n      (<<STEP: traced_step\n                 tr_src\n                 th_src\n                 (Thread.mk lang st' (Local.mk v' Memory.bot) sc' mem_src')>>) /\\\n      (<<TRACE: List.map fst tr_src = List.map fst tr_tgt>>) /\\\n      (<<MEM: unchanged_on L mem_tgt' mem_src'>>).\nProof.\n  ginduction STEPS; i; clarify.\n  - esplits.\n    + econs 1.\n    + ss.\n    + auto.\n  - inv PRED. destruct th1. destruct local.\n    exploit unchanged_on_step; eauto.\n    { instantiate (1:=write_in L /1\\ no_promise). ss. }\n    { econs; eauto. } i. des. inv STEP.\n    exploit IHSTEPS; ss.\n    + eauto.\n    + f_equal. f_equal.\n      exploit promise_bot_no_promise.\n      * econs.\n        { eapply HD. }\n        { apply SAT. }\n      * i. auto.\n      * ss.\n      * ss.\n    + eauto.\n    + i. des. esplits; eauto.\n      * econs; eauto.\n      * ss. f_equal. auto.\nQed.\n\n\nLemma pf_consistent_shift_future lang (e0: Thread.t lang)\n      spaces promises max U AU\n      (CONSISTENT: pf_consistent_drf_shift e0 spaces promises max U AU)\n      (BOT: (Local.promises (Thread.local e0)) = Memory.bot)\n  :\n    pf_consistent_drf_future e0 spaces promises U AU.\nProof.\n  ii.\n  unfold pf_consistent_drf_shift in CONSISTENT. des.\n  exploit (choice (fun loc ts =>\n                     forall (UPDATES: U loc \\/ AU loc),\n                       (<<TS: Time.lt (max loc) ts>>) /\\\n                       (<<NCOVER: forall to (TS0: Time.lt (max loc) to) (TS1: Time.le to ts),\n                           ~ covered loc to mem_future>>))).\n  { intros loc. destruct (classic (__guard__(U loc \\/ AU loc))).\n    - exploit ATTATCH.\n      { splits; eauto. } i. des.\n      exists to'. i. rewrite UPDATESMAX in *; auto. splits; auto.\n      i. eapply EMPTY. econs; ss.\n    - exists Time.bot. i. clarify. }\n  intros [gap GAP].\n\n  set (newmax := TimeMap.join (Memory.max_timemap mem_future) max).\n  set (L := (spaces \\2/ (fun loc to => (__guard__(U loc \\/ AU loc) /\\ Time.lt (max loc) to /\\ Time.lt to (gap loc))) \\2/                 (fun loc to => ~ U loc /\\ ~ AU loc /\\ Time.lt (newmax loc) to))).\n  assert (NEWMAX: TimeMap.le (Memory.max_timemap mem_future) newmax).\n  { unfold newmax. eapply TimeMap.join_l. }\n\n  hexploit (CONSISTENT0 gap newmax).\n  { i. eapply GAP in UPDATES. des. auto. }\n  { unfold newmax. eapply TimeMap.join_r. }\n  i. des.\n  destruct e0, e2. destruct local, local0. ss. clarify.\n  hexploit (@unchanged_on_traced_step L); try apply STEPS; eauto.\n  { eapply List.Forall_impl; eauto. i. ss. des. auto. }\n  { instantiate (1:=mem_future). inv UNCH. econs; eauto. unfold L. i. des.\n    - eauto.\n    - exploit GAP; eauto. i. des.\n      exfalso. eapply NCOVER in COV; eauto. left. auto.\n    - inv COV. eapply Memory.max_ts_spec in GET. des. inv ITV. ss.\n      exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n      { eapply IN1. } etrans.\n      { eapply TO. } etrans.\n      { eapply MAX. }\n      { eapply NEWMAX. }\n  }\n  i. des. eapply no_sc_any_sc_traced in STEP; eauto; cycle 1.\n  { i. eapply List.in_map in IN; eauto.\n    erewrite TRACE0 in IN.\n    eapply List.in_map_iff in IN; eauto. des. destruct x, e. ss. clarify.\n    eapply List.Forall_forall in IN0; eauto. ss. des; auto. }\n  des. esplits; eauto.\n  - eapply List.Forall_forall. i.\n    eapply List.in_map in H; eauto.\n    erewrite TRACE0 in H.\n    eapply List.in_map_iff in H; eauto. des. destruct x0, x. ss. clarify.\n    eapply List.Forall_forall in H0; eauto. ss. des; auto.\n  - i. eapply COMPLETEU in SAT. des.\n    eapply List.in_map in IN. erewrite <- TRACE0 in IN.\n    eapply List.in_map_iff in IN; eauto. des. destruct x. ss. subst.\n    esplits; eauto.\n  - i. eapply COMPLETEAU in SAT. des.\n    eapply List.in_map in IN. erewrite <- TRACE0 in IN.\n    eapply List.in_map_iff in IN; eauto. des. destruct x. ss. subst.\n    esplits; eauto.\n  - i. eapply COMPLETEW in PROMISED. des.\n    eapply List.in_map in IN. erewrite <- TRACE0 in IN.\n    eapply List.in_map_iff in IN; eauto. des. destruct x. ss. subst.\n    esplits; eauto.\nQed.\n\nLemma sim_pf_impl tids0 tids1 mlast spaces updates aupdates c_src c_tgt\n      (SIM: sim_pf tids1 mlast spaces updates aupdates c_src c_tgt)\n      (IMPL: tids0 <1= tids1)\n  :\n    sim_pf tids0 mlast spaces updates aupdates c_src c_tgt.\nProof.\n  inv SIM. econs; eauto.\nQed.\n\nLemma sim_pf_minus_plus_one\n      tid mlast spaces updates aupdates c_src c_tgt\n      (SIM: sim_pf_minus_one tid mlast spaces updates aupdates c_src c_tgt)\n      mlast_one spaces_one updates_one aupdates_one\n      (ONE: sim_pf_one tid mlast_one spaces_one updates_one aupdates_one c_src c_tgt)\n  :\n    sim_pf\n      (fun _ => True)\n      (fun tid' => if Ident.eq_dec tid tid' then mlast_one else mlast tid')\n      (fun tid' => if Ident.eq_dec tid tid' then spaces_one else spaces tid')\n      (fun tid' => if Ident.eq_dec tid tid' then updates_one else updates tid')\n      (fun tid' => if Ident.eq_dec tid tid' then aupdates_one else aupdates tid')\n      c_src c_tgt.\nProof.\n  inv SIM. econs; eauto. i. des_ifs. eapply THREADS; eauto.\nQed.\n\n\nLemma no_promise_traces_step_program_step lang (th0 th1: Thread.t lang) tr\n      (STEPS: traced_step tr th0 th1)\n      (NOPROMISE: List.Forall (fun em => no_promise (fst em) /\\ ThreadEvent.get_machine_event (fst em) = MachineEvent.silent) tr)\n  :\n    rtc (tau (@AThread.program_step lang)) th0 th1.\nProof.\n  ginduction STEPS; auto. i. inv NOPROMISE. inv HD. des. inv STEP.\n  { inv STEP0; ss. }\n  econs.\n  - econs; eauto.\n  - eapply IHSTEPS; eauto.\nQed.\n\nLemma sim_pf_step\n      c_src0 c_tgt0 c_tgt1 tid e\n      (SIM: sim_pf_all c_src0 c_tgt0)\n      (STEP: Configuration.step e tid c_tgt0 c_tgt1)\n  :\n    exists c_src1,\n      (<<STEP: APFConfiguration.opt_step e tid c_src0 c_src1>>) /\\\n      ((<<FAIL: e = MachineEvent.failure>>) \\/\n       (exists c_src2,\n           (<<FAIL: APFConfiguration.step MachineEvent.failure tid c_src1 c_src2>>)) \\/\n       (<<SIM: sim_pf_all c_src1 c_tgt1>>)).\nProof.\n  inv SIM.\n  eapply sim_pf_impl with (tids0 := fun tid0 => tid <> tid0) in SIM0; ss.\n  exploit sim_pf_step_minus_full; eauto. i. des.\n  unguard. des; cycle 1.\n  { exists c_src1. esplits; eauto. }\n  exploit sim_pf_step_pf_consistent; eauto. i. des; cycle 1.\n  { esplits; eauto. }\n  dup SIM. inv SIM1. inv WFSRC. inv WF. exploit THREADS0; eauto. intros LCWF.\n  exploit pf_consistent_drf_src_shift; eauto; ss.\n  intros CONSISTENTSHIFT.\n  hexploit pf_consistent_shift_future; eauto.\n  { inv FORGET. specialize (THS tid).\n    rewrite FIND in *. rewrite FIND0 in *. inv THS. ss. }\n  intros CONSISTENTFUTURE.\n\n  esplits; eauto. right. right. econs.\n  eapply sim_pf_minus_plus_one; [eauto|].\n\n  instantiate (1:=fun loc to => (<<UPDATES: AU loc>>) /\\ (<<MAX: Memory.max_ts loc (Configuration.memory c_src1) = to>>)).\n  instantiate (1:=fun loc to => (<<UPDATES: U loc>>) /\\ (<<MAX: Memory.max_ts loc (Configuration.memory c_src1) = to>>)).\n  instantiate (1:=concrete_covered (Local.promises lc_tgt) (Configuration.memory c_tgt1)).\n  instantiate (1:=Configuration.memory c_src1). econs.\n\n  - refl.\n  - ii. assert (MAXTS: to = Memory.max_ts loc (Configuration.memory c_src1)).\n    { des; auto. } clear SAT. clarify. split.\n    + inv MEM. specialize (INHABITED loc).\n      eapply Memory.max_ts_spec in INHABITED. des. destruct msg.\n      * econs; eauto.\n      * exfalso. eapply sim_pf_src_no_reserve; eauto.\n    + esplits.\n      * eapply Time.incr_spec.\n      * ii. inv H. inv ITV. inv ITV0. ss.\n        eapply Memory.max_ts_spec in GET. des.\n        eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply FROM. } etrans; eauto.\n  - i. clarify. dependent destruction H0. dependent destruction H1. econs; eauto.\n    + i. des. dup UPDATES. eapply AUPDATES in UPDATES.\n      unfold Memory.latest_reserve in UPDATES.\n      des_ifs. inv WFTGT. inv WF. exploit THREADS1; eauto. intros LCWFTGT.\n      inv LCWFTGT. dup Heq. eapply PROMISES in Heq0.\n      exploit max_full_ts_max_ts; eauto.\n      { inv MEM0. auto. }\n      i. des.\n      * destruct (MAX loc). des. unfold Memory.get in Heq0.\n        rewrite FULL in GET. clarify .\n      * clarify. unfold pf_consistent_drf_shift in *. des.\n        exploit UPDATESMAX; eauto. intro x. ss. rewrite x in *. esplits; eauto.\n\n    + i. hexploit (CONSISTENTFUTURE m sc); eauto.\n      { eapply not_attatched_mon; eauto. i. des; ss; auto. }\n      i. des. ss.\n      exploit COMPLETEW; eauto. i. des.\n      exploit traced_step_in; eauto. i. des. clarify.\n      eapply no_promise_traces_step_program_step in STEPS0.\n      * destruct th'. destruct local. ss. esplits; eauto.\n        clear - STEP1 WRITETO. inv STEP1. inv STEP; inv STEP0; ss.\n        unfold is_writing. inv LOCAL; ss; des; subst.\n        { esplits; eauto.\n          - econs; eauto.\n          - ss. }\n        { esplits; eauto.\n          - econs; eauto.\n          - ss. }\n      * eapply Forall_app_inv in TRACE. des. auto.\n\n    + i. hexploit (CONSISTENTFUTURE m sc); eauto.\n      { eapply not_attatched_mon; eauto. i. des; ss; auto. }\n      i. des. ss.\n      exploit COMPLETEU; eauto. i. des.\n      exploit traced_step_in; eauto. i. des. subst.\n      eapply no_promise_traces_step_program_step in STEPS0.\n      * destruct th'. destruct local. ss. esplits; eauto.\n        clear - STEP1 ORDR. inv STEP1. inv STEP; inv STEP0; ss.\n        unfold is_updating. inv LOCAL; ss; des; subst.\n        esplits; eauto.\n        { econs; eauto. }\n        { ss. }\n      * eapply Forall_app_inv in TRACE. des. auto.\n\n    + i. hexploit (CONSISTENTFUTURE m sc); eauto.\n      { eapply not_attatched_mon; eauto. i. des; ss; auto. }\n      i. des. ss.\n      exploit COMPLETEAU; eauto. i. des.\n      exploit traced_step_in; eauto. i. des. subst.\n      eapply no_promise_traces_step_program_step in STEPS0.\n      * destruct th'. destruct local. ss. esplits; eauto.\n        clear - STEP1. inv STEP1. inv STEP; inv STEP0; ss.\n        unfold is_updating. inv LOCAL; ss; des; subst.\n        esplits; eauto.\n        { econs; eauto. }\n        { instantiate (1:=ordr). destruct ordr; ss. }\n        { ss. }\n      * eapply Forall_app_inv in TRACE. des. auto.\n\n  - i. clarify.\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_PF5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.18649441748872558}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import monad.\nRequire Import Metatheory.\nRequire Import alist.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nRequire Import Memory.\nRequire Import Values.\nRequire Import Integers.\nRequire Import AST.\nRequire Import targetdata.\nRequire Import ZArith.\nRequire Import Floats.\nRequire Import vellvm_tactics.\nRequire Import util.\nRequire Import Coqlib.\nLocal Open Scope nat_scope.\n\n(* The file defines generic values that represent values at runtime. *)\nModule LLVMgv.\n\nImport LLVMsyntax.\nImport LLVMinfra.\nImport LLVMtd.\n\n(******************************************************************************)\n(* We first define a generic value that is a list of memory values with memory \n   chunks. *)\nDefinition moffset := Int.int 31.\nDefinition mem := Mem.mem.\nDefinition GenericValue := list (val*memory_chunk).\nDefinition GVMap := list (id*GenericValue).\n\nDefinition mblock := Values.block.\nDefinition mptr := GenericValue.\nDefinition null : GenericValue := (Vint 31 (Int.repr 31 0), Mint 31):: nil.\n\n(******************************************************************************)\n(* Predicate of generic values. *)\n\n(* One generic value is less defined than the other in terms of Val.lessdef. *)\nDefinition gv_lessdef (gv1 gv2:GenericValue) : Prop :=\nList.Forall2 (fun vm1 vm2 =>\n              let '(v1, cm1) := vm1 in\n              let '(v2, cm2) := vm2 in\n              Val.lessdef v1 v2 /\\ cm1 = cm2) gv1 gv2.\n\nDefinition gv_lessdef_list (gvs1 gvs2:list GenericValue) : Prop :=\nList.Forall2 gv_lessdef gvs1 gvs2.\n\n(* Check if memory values in a gv match their corresponding chunks. *)\nDefinition gv_has_chunk (gv:GenericValue): Prop :=\nList.Forall (fun vm => \n             let '(v, mc) := vm in\n             Val.has_chunk v mc) gv.\n\n(* A computable version of gv_has_chunk. *)\nFixpoint gv_has_chunkb (gv : GenericValue) : bool := \nmatch gv with\n| nil => true\n| (v,m)::gv' => Val.has_chunkb v m && gv_has_chunkb gv'\nend.\n\n(* Equivalence of gvs. *)\nFixpoint eq_gv (gv1 gv2:GenericValue) : bool :=\nmatch gv1, gv2 with\n| nil, nil => true\n| (v1,c1)::gv1', (v2,c2)::gv2' => if Val.eq v1 v2\n                                  then memory_chunk_eq c1 c2 &&\n                                    eq_gv gv1' gv2'\n                                  else false\n| _, _ => false\nend.\n\n(* a list of undefined memory chunks with size n. *)\nDefinition uninitMCs (n:nat) : list memory_chunk :=\n  Coqlib.list_repeat n (Mint 7).\n\n(* a list of repeated memory chunks. *)\nFixpoint repeatMC (mcs:list memory_chunk) (n:nat) : list memory_chunk :=\nmatch n with\n| O => nil\n| S n' => mcs ++ repeatMC mcs n'\nend.\n\n(* Return the size of a list of memory chunks. *)\nFixpoint sizeMC (mc:list memory_chunk) : nat :=\nmatch mc with\n| nil => 0%nat\n| c::mc' => (size_chunk_nat c + sizeMC mc')%nat\nend.\n\n(* Compute the list of memory chunks that represents a type. *)\nDefinition flatten_typs_aux_\n  (flatten_typ_aux :\n    TargetData -> list (id * option (list memory_chunk)) ->\n    typ -> option (list memory_chunk)) :=\nfix flatten_typs_aux (TD:TargetData) acc (lt:list typ)\n  : option (list memory_chunk) :=\nmatch lt with\n| nil => Some nil\n| t :: lt' =>\n  match (flatten_typs_aux TD acc lt', flatten_typ_aux TD acc t) with\n  | (Some mc, Some mc0) =>\n       match getTypeAllocSize TD t with\n       | Some asz => Some (mc0++uninitMCs (asz - sizeMC mc0)++mc)\n       | _ => None\n       end\n  | _ => None\n  end\nend.\n\nFixpoint flatten_typ_aux (TD:TargetData)\n  (acc:list (id*option (list memory_chunk))) (t:typ)\n  : option (list memory_chunk) :=\nmatch t with\n| typ_int sz => Some (Mint (Size.to_nat sz - 1) :: nil)\n| typ_floatpoint fp =>\n  match fp with\n  | fp_float => Some (Mfloat32 :: nil)\n  | fp_double => Some (Mfloat64 :: nil)\n  | _ => None (* FIXME: not supported 80 and 128 yet. *)\n  end\n| typ_void => None\n| typ_label => None\n| typ_metadata => None\n| typ_array sz t =>\n  match sz with\n  | O => Some (uninitMCs 1)\n  | _ =>\n    match flatten_typ_aux TD acc t with\n    | Some mc0 =>\n      match getTypeAllocSize TD t with\n      | Some asz =>\n         Some (repeatMC (mc0++uninitMCs (Size.to_nat asz - sizeMC mc0))\n                 (Size.to_nat sz))\n      | _ => None\n      end\n    | _ => None\n    end\n  end\n| typ_struct ts =>\n  match flatten_typs_aux_ flatten_typ_aux TD acc ts with\n  | Some nil => Some (uninitMCs 1)\n  | Some gv0 => Some gv0\n  | None => None\n  end\n| typ_pointer t' => Some (Mint 31::nil)\n| typ_function _ _ _ => None\n| typ_namedt nid => \n  match lookupAL _ acc nid with\n  | Some re => re\n  | _ => None\n  end\nend.\n\nDefinition flatten_typs_aux :=\n  flatten_typs_aux_ flatten_typ_aux.\n\nFixpoint flatten_typ_for_namedts TD (los:layouts) (nts:namedts) \n  : list (id*option (list memory_chunk)) :=\nmatch nts with\n| nil => nil \n| (id0, ts0)::nts' =>\n  let results := flatten_typ_for_namedts TD los nts' in\n  (id0, flatten_typ_aux TD results (typ_struct ts0))::results\nend.\n\nDefinition flatten_typ (TD:TargetData) (t:typ) : option (list memory_chunk) :=\nlet '(los, nts) := TD in\nflatten_typ_aux TD (flatten_typ_for_namedts TD los nts) t.\n\nDefinition flatten_typs (TD:TargetData) (lt:list typ)\n  : option (list memory_chunk) :=\nlet '(los, nts) := TD in\nflatten_typs_aux TD (flatten_typ_for_namedts TD los nts) lt.\n\n(* Check if gv has type t. *)\nDefinition gv_has_type (TD:LLVMtd.TargetData) (gv:GenericValue) \n  (t:typ) : Prop :=\nmatch flatten_typ TD t with\n| None => False\n| Some ts =>\n    List.Forall2 (fun v mc => Val.has_type v (AST.type_of_chunk mc)) \n                 (fst (List.split gv)) ts\nend.\n\n(* Check if gv contains undefined memory values. *)\nFixpoint isGVUndef (gv:GenericValue) : Prop :=\nmatch gv with\n| nil => False\n| (Vundef,_)::gv' => True\n| _::gv' => isGVUndef gv'\nend.\n\n(* Check if a generic value matches its memory chunks. *)\nDefinition vm_matches_typ :=\n  fun (vm:val*memory_chunk) (mc:memory_chunk) => \n    snd vm = mc /\\ Val.has_chunk (fst vm) (snd vm).\n\nDefinition gv_chunks_match_typ (TD:TargetData) (gv:GenericValue) (t:typ) \n  : Prop :=\nmatch flatten_typ TD t with\n| None => False\n| Some ts => List.Forall2 vm_matches_typ gv ts\nend.\n\nDefinition gv_chunks_match_list_typ (TD:TargetData) (gv:GenericValue)\n  (ts:list typ) : Prop :=\nmatch flatten_typs TD ts with\n| None => False\n| Some mcs => List.Forall2 vm_matches_typ gv mcs\nend.\n\n(******************************************************************************)\n(* Operations of generic values. *)\n\n(* a list of undefined memory values with size n. *)\nDefinition uninits (n:nat) : GenericValue :=\n   Coqlib.list_repeat n (Vundef, Mint 7).\n\n(* Generate an undefined generic values in terms of memory chunks. *)\nDefinition mc2undefs (mc:list memory_chunk) : GenericValue :=\nList.fold_right \n  (fun c acc => (Vundef, c) :: acc) nil mc.\n\n(* Generate an undefined generic values in terms of type. *)\nDefinition gundef (TD:TargetData) (t:typ) : option GenericValue :=\nmatch (flatten_typ TD t) with\n| Some mc => Some (mc2undefs mc)\n| None => None\nend.\n\n(* Convert between generic values and basic memory values. *)\nDefinition GV2val (TD:TargetData) (gv:GenericValue) : option val :=\nmatch gv with\n| (v,c)::nil => Some v\n| _ => Some Vundef\nend.\n\nDefinition GV2int (TD: TargetData) (bsz: sz) (gv: GenericValue) :=\n  match gv with\n  | ((Values.Vint wz i, (AST.Mint sz))) :: nil =>\n    if Nat.eq_dec (wz + 1) (Size.to_nat bsz)\n    then if (Nat.eq_dec wz sz)\n         then Some (Int.signed wz i)\n         else None\n    else None\n  | _ => None\n  end\n.\nDefinition GV2ptr (TD:TargetData) (bsz:sz) (gv:GenericValue) : option val :=\nmatch gv with\n| (Vptr a b,c)::nil => Some (Vptr a b)\n| _ => None\nend.\nDefinition val2GV (TD:TargetData) (v:val) (c:memory_chunk) : GenericValue :=\n(v,c)::nil.\nDefinition ptr2GV (TD:TargetData) (ptr:val) : GenericValue :=\nval2GV TD ptr (Mint (Size.mul Size.Eight (getPointerSize TD)-1)).\nDefinition blk2GV (TD:TargetData) (b:mblock) : GenericValue :=\nptr2GV TD (Vptr b (Int.repr 31 0)).\nDefinition isGVZero (TD:TargetData) (gv:GenericValue) : bool :=\nmatch (GV2int TD Size.One gv) with\n| Some z => if Coqlib.zeq z 0 then true else false\n| _ => false\nend.\n\n(* Internal operations of generic values that Vellvm provides *)\nDefinition mgep (TD:TargetData) (t:typ) (ma:val) (idxs:list Z) : option val :=\nmatch ma with\n| Vptr b ofs =>\n  match idxs with\n  | nil => None\n  | _ =>\n    match (mgetoffset TD (typ_array 0%nat t) idxs) with\n    | Some (offset, _) => Some (Vptr b (Int.add 31 ofs (Int.repr 31 offset)))\n    | _ => None\n    end\n  end\n| _ => None\nend.\n\nFixpoint sizeGenericValue (gv:GenericValue) : nat :=\nmatch gv with\n| nil => 0%nat\n| (v,c)::gv' => (size_chunk_nat c + sizeGenericValue gv')%nat\nend.\n\nFixpoint splitGenericValue (gv:GenericValue) (pos:Z):\n  option (GenericValue*GenericValue) :=\nif (Coqlib.zeq pos 0) then Some (nil, gv)\nelse\n  if (Coqlib.zlt pos 0) then None\n  else\n    match gv with\n    | nil => None\n    | (v,c)::gv' =>\n        match splitGenericValue gv' (pos - size_chunk c) with\n        | Some (gvl', gvr') => Some ((v,c)::gvl', gvr')\n        | None => None\n        end\n    end.\n\nFixpoint gv_chunks_match_typb_aux (gv:GenericValue) (mcs:list memory_chunk)\n  : bool :=\nmatch gv, mcs with\n| nil, nil => true\n| (v1, mc1)::gv', mc2::mcs' => \n    AST.memory_chunk_eq mc1 mc2 && Val.has_chunkb v1 mc1 &&\n      gv_chunks_match_typb_aux gv' mcs'\n| _, _ => false\nend.\n\nDefinition gv_chunks_match_typb (TD:TargetData) (gv:GenericValue) (t:typ) \n  : bool :=\nmatch flatten_typ TD t with\n| None => false\n| Some mcs => gv_chunks_match_typb_aux gv mcs\nend.\n\nDefinition mget (TD:TargetData) (gv:GenericValue) (o:Z) (t:typ)\n  : option GenericValue :=\ndo s <- getTypeStoreSize TD t;\n  match (splitGenericValue gv o) with\n  | Some (gvl, gvr) =>\n      match (splitGenericValue gvr (Z_of_nat s)) with\n      | Some (gvrl, gvrr) => \n          if gv_chunks_match_typb TD gvrl t then Some gvrl else None\n      | None => None\n      end\n  | None => None\n  end.\n\nDefinition mset (TD:TargetData) (gv:GenericValue) (o:Z) (t0:typ)\n  (gv0:GenericValue) : option GenericValue :=\nlet n := Coqlib.nat_of_Z o in\ndo s <- getTypeStoreSize TD t0;\n  if (beq_nat s (length gv0)) then\n    match (splitGenericValue gv o) with\n    | Some (gvl, gvr) =>\n       match (splitGenericValue gvr (Z_of_nat s)) with\n       | Some (gvrl, gvrr) => \n          if gv_chunks_match_typb TD gvrl t0 \n          then Some (gvl++gv0++gvrr) else None\n       | None => None\n       end\n    | None => None\n    end\n  else None.\n\nFixpoint GVs2Nats (TD:TargetData) (lgv:list GenericValue) : option (list Z):=\nmatch lgv with\n| nil => Some nil\n| gv::lgv' =>\n    match (GV2int TD Size.ThirtyTwo gv) with\n    | Some z =>\n        match (GVs2Nats TD lgv') with\n        | Some ns => Some (z::ns)\n        | None => None\n        end\n    | _ => None\n    end\nend.\n\n(* FIXME : bounds check *)\nDefinition extractGenericValue (TD:TargetData) (t:typ) (gv : GenericValue)\n  (cidxs : list const) : option GenericValue :=\nmatch (intConsts2Nats TD cidxs) with\n| None => None\n| Some idxs =>\n  match (mgetoffset TD t idxs) with\n  | Some (o, t') => match mget TD gv o t' with\n                    | Some gv' => Some gv'\n                    | None => gundef TD t'\n                    end\n  | None => None\n  end\nend.\n\nDefinition insertGenericValue (TD:TargetData) (t:typ) (gv:GenericValue)\n  (cidxs:list const) (t0:typ) (gv0:GenericValue) : option GenericValue :=\nmatch (intConsts2Nats TD cidxs) with\n| None => None\n| Some idxs =>\n  match (mgetoffset TD t idxs) with\n  | Some (o, _) => match (mset TD gv o t0 gv0) with\n                   | Some gv' => Some gv'\n                   | None => gundef TD t\n                   end\n  | None => None\n  end\nend.\n\nDefinition mtrunc (TD:TargetData) (op:truncop) (t1:typ) (t2:typ)\n  (gv1:GenericValue) : option GenericValue :=\nmatch GV2val TD gv1 with\n| Some (Vint wz1 i1) =>\n    match (t1, t2) with\n    | (typ_int sz1, typ_int sz2) =>\n        Some (val2GV TD (Val.trunc (Vint wz1 i1) (sz2-1)) (Mint (sz2-1)))\n    | _ => gundef TD t2\n    end\n| Some (Vfloat f) =>\n    match (t1, t2) with\n    | (typ_floatpoint fp1, typ_floatpoint fp2) =>\n        if floating_point_order fp2 fp1\n        then\n          match fp1 with\n          | fp_double => \n               Some (val2GV TD (Vsingle (Float.to_single f)) Mfloat32)\n          | _ => gundef TD t2 (* FIXME: not supported 80 and 128 yet. *)\n          end\n        else gundef TD t2\n    | _ => gundef TD t2\n    end\n| Some (Vsingle f) =>\n    match (t1, t2) with\n    | (typ_floatpoint _, typ_floatpoint _) => gundef TD t2\n    | _ => gundef TD t2\n    end\n| _ => gundef TD t2\nend.\n\nDefinition mbop (TD:TargetData) (op:bop) (bsz:sz) (gv1 gv2:GenericValue)\n  : option GenericValue :=\nlet bsz' := (Size.to_nat bsz) in\nmatch (GV2val TD gv1, GV2val TD gv2) with\n| (Some (Vint wz1 i1), Some (Vint wz2 i2)) =>\n  if eq_nat_dec (wz1+1) bsz'\n  then\n     match op with\n     | bop_add =>\n         Some (val2GV TD (Val.add (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_sub =>\n         Some (val2GV TD (Val.sub (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_mul =>\n         Some (val2GV TD (Val.mul (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_udiv =>\n         match Val.divu (Vint wz1 i1) (Vint wz2 i2) with\n         | Some vresult => Some (val2GV TD vresult (Mint (bsz'-1)))\n         | None => gundef TD (typ_int bsz')\n         end\n     | bop_sdiv =>\n         match Val.divs (Vint wz1 i1) (Vint wz2 i2) with\n         | Some vresult => Some (val2GV TD vresult (Mint (bsz'-1)))\n         | None => gundef TD (typ_int bsz')\n         end\n     | bop_urem =>\n         match Val.modu (Vint wz1 i1) (Vint wz2 i2) with\n         | Some vresult => Some (val2GV TD vresult (Mint (bsz'-1)))\n         | None => gundef TD (typ_int bsz')\n         end\n     | bop_srem =>\n         match Val.mods (Vint wz1 i1) (Vint wz2 i2) with\n         | Some vresult => Some (val2GV TD vresult (Mint (bsz'-1)))\n         | None => gundef TD (typ_int bsz')\n         end\n     | bop_shl =>\n         Some (val2GV TD (Val.shl (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_lshr =>\n         match Val.shrx (Vint wz1 i1) (Vint wz2 i2) with\n         | Some vresult => Some (val2GV TD vresult (Mint (bsz'-1)))\n         | None => gundef TD (typ_int bsz')\n         end\n     | bop_ashr =>\n         Some (val2GV TD (Val.shr (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_and =>\n         Some (val2GV TD (Val.and (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_or =>\n         Some (val2GV TD (Val.or (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     | bop_xor =>\n         Some (val2GV TD (Val.xor (Vint wz1 i1) (Vint wz2 i2)) (Mint (bsz'-1)))\n     end\n  else gundef TD (typ_int bsz')\n| _ => gundef TD (typ_int bsz')\nend.\n\nDefinition mfbop (TD:TargetData) (op:fbop) (fp:floating_point)\n  (gv1 gv2:GenericValue) : option GenericValue :=\nmatch (GV2val TD gv1, GV2val TD gv2) with\n| (Some (Vfloat f1), Some (Vfloat f2)) =>\n  let v :=\n     match op with\n     | fbop_fadd => Val.addf (Vfloat f1) (Vfloat f2)\n     | fbop_fsub => Val.subf (Vfloat f1) (Vfloat f2)\n     | fbop_fmul => Val.mulf (Vfloat f1) (Vfloat f2)\n     | fbop_fdiv => Val.divf (Vfloat f1) (Vfloat f2)\n     | fbop_frem => Val.modf (Vfloat f1) (Vfloat f2)\n     end in\n  match fp with\n  | fp_double => Some (val2GV TD v Mfloat64)\n  | fp_float => gundef TD (typ_floatpoint fp)\n  | _ => gundef TD (typ_floatpoint fp)\n  end\n| (Some (Vsingle f1), Some (Vsingle f2)) =>\n  let v :=\n     match op with\n     | fbop_fadd => Val.addfs (Vsingle f1) (Vsingle f2)\n     | fbop_fsub => Val.subfs (Vsingle f1) (Vsingle f2)\n     | fbop_fmul => Val.mulfs (Vsingle f1) (Vsingle f2)\n     | fbop_fdiv => Val.divfs (Vsingle f1) (Vsingle f2)\n     | fbop_frem => Val.modfs (Vsingle f1) (Vsingle f2)\n     end in\n  match fp with\n  | fp_float => Some (val2GV TD v Mfloat32)\n  | fp_double => gundef TD (typ_floatpoint fp)\n  | _ => gundef TD (typ_floatpoint fp)\n  end\n| _ => gundef TD (typ_floatpoint fp)\nend.\n\n(*\nDefinition mptrtoint (TD:TargetData) (M:mem) (gv1:GenericValue) (sz2:nat)\n : option GenericValue :=\n    match GV2val TD gv1 with\n    | Some (Vptr b1 ofs1) =>\n        match Mem.ptr2int M b1 0 with\n        | Some z =>\n            Some (val2GV TD\n                   (Vint sz2 (Int.repr sz2 (z + Int.signed 31 ofs1)))\n                   (Mint (sz2-1)))\n        | None => Some (val2GV TD (Vint sz2 (Int.zero sz2)) (Mint (sz2-1)))\n        end\n    | Some (Vinttoptr i) =>\n        Some (val2GV TD (Vint sz2 (Int.repr sz2 (Int.unsigned 31 i)))\n               (Mint (sz2-1)))\n    | _ => gundef TD (typ_int sz2)\n    end.\n*)\n\nDefinition mbitcast (t1:typ) (gv1:GenericValue)(t2:typ) : option GenericValue :=\nmatch (t1, t2) with\n| (typ_int sz1, typ_int sz2) => Some gv1\n| (typ_pointer _, typ_pointer _) => Some gv1\n| _ => None\nend.\n\n(*\nDefinition minttoptr (TD:TargetData) (M:mem) (gv1:GenericValue)\n  : option GenericValue :=\n  match GV2val TD gv1 with\n  | Some (Vint wz1 i1) =>\n      match Mem.int2ptr M (Int.signed wz1 i1) with\n      | Some (b,ofs) => Some (ptr2GV TD (Vptr b (Int.repr 31 ofs)))\n      | None =>\n          Some (ptr2GV TD (Vinttoptr (Int.repr 31 (Int.unsigned wz1 i1))))\n      end\n  | _ => gundef TD (typ_pointer typ_void)\n  end.\n*)\n\n(* Here is another idea to support inttoptr and ptrtoint. We should\n   distinguish two kinds of ptr: at global spaces, and at heap or stack. The\n   first kind of ptr has an known address at compile time, and at runtime\n   their addresses cannot be reused; the second kind of ptr has no such\n   properties.\n\n   So, we can support i2p and p2i for the first ptr w/o parameterizing Mem\n   everywhere (at const2GV and getOperandValue), because we can maintain a\n   fixed mapping that is created at program initialization.\n\n   For p2i, it is total. i2p can be undef if the int value is not in the map.\n\n   This makes values in registers hold the substitution properities. If const2GV\n   is with Mem, that means its result can be affected by memory state, so we can-\n   not substitute it arbitrarily.\n\n   Having Mem  everywhere, and not distinguishing the two kinds of\n   ptr, complicates proofs, because we need to argue that\n   1) memory model does not reuse addresses for globals, this is true for our\n      corrent memory model, because it has inifite memory, and never reuses,\n      but needs more work if we support finite memory later.\n\n   2) It is hard to define simulation relations between the pointers or\n      intergers casted from two programs, because related pointers can be in\n      different memory addresses.\n\n   This also indicates that the 2nd kind of ptr should eval to undef by i2p or\n   p2i, because what their values are depends on runtime and platform.\n\n   For the time being, we simply consider both of the kinds of ptrs fomr i2p\n   to be undef, and integers from p2i to be undef, too.\n\n*)\nDefinition mcast (TD:TargetData) (op:castop) (t1:typ) (t2:typ) (gv1:GenericValue)\n : option GenericValue :=\nmatch op with\n| castop_inttoptr => gundef TD t2\n| castop_ptrtoint => gundef TD t2\n| castop_bitcase => mbitcast t1 gv1 t2\nend.\n\nDefinition mext (TD:TargetData) (op:extop) (t1:typ) (t2:typ) (gv1:GenericValue)\n  : option GenericValue :=\nmatch (t1, t2) with\n| (typ_int sz1, typ_int sz2) =>\n   match (GV2val TD gv1) with\n   | Some (Vint wz1 i1) =>\n     match op with\n     | extop_z => Some (val2GV TD (Val.zero_ext' (sz2-1) (Vint wz1 i1))\n                        (Mint (sz2-1)))\n     | extop_s => Some (val2GV TD (Val.sign_ext' (sz2-1) (Vint wz1 i1))\n                        (Mint (sz2-1)))\n     | _ => gundef TD t2\n     end\n   | _ => gundef TD t2\n   end\n| (typ_floatpoint fp1, typ_floatpoint fp2) =>\n  if floating_point_order fp1 fp2\n  then\n    match (GV2val TD gv1) with\n    | Some (Vfloat f1) =>\n      match op with\n      | extop_fp =>\n         match fp2 with\n         | fp_double => Some (val2GV TD (Vfloat f1) Mfloat64)\n         | _ => gundef TD t2 (* FIXME: not supported 80 and 128 yet. *)\n         end\n      | _ => gundef TD t2\n      end\n    | _ => gundef TD t2\n    end\n  else gundef TD t2\n| (_, _) => gundef TD t2\nend.\n\nDefinition micmp_int TD c gv1 gv2 : option GenericValue :=\n  match (GV2val TD gv1, GV2val TD gv2) with\n  | (Some (Vint wz1 i1), Some (Vint wz2 i2)) =>\n     match c with\n     | cond_eq =>\n         Some (val2GV TD (Val.cmp Ceq (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_ne =>\n         Some (val2GV TD (Val.cmp Cne (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_ugt =>\n         Some (val2GV TD (Val.cmpu_int Cgt (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_uge =>\n         Some (val2GV TD (Val.cmpu_int Cge (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_ult =>\n         Some (val2GV TD (Val.cmpu_int Clt (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_ule =>\n         Some (val2GV TD (Val.cmpu_int Cle (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_sgt =>\n         Some (val2GV TD (Val.cmp Cgt (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_sge =>\n         Some (val2GV TD (Val.cmp Cge (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_slt =>\n         Some (val2GV TD (Val.cmp Clt (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     | cond_sle =>\n         Some (val2GV TD (Val.cmp Cle (Vint wz1 i1) (Vint wz2 i2)) (Mint 0))\n     end\n  | _ => gundef TD (typ_int 1%nat)\n  end.\n\nDefinition micmp (TD:TargetData) (c:cond) (t:typ) (gv1 gv2:GenericValue)\n  : option GenericValue :=\nmatch t with\n| typ_int sz => micmp_int TD c gv1 gv2\n| typ_pointer _ => gundef TD (typ_int 1%nat)\n| _ => gundef TD (typ_int 1%nat)\nend.\n\n(* TODO: issue. Single vs Float. *)\nDefinition mfcmp (TD:TargetData) (c:fcond) (fp:floating_point)\n  (gv1 gv2:GenericValue) : option GenericValue :=\nmatch (GV2val TD gv1, GV2val TD gv2) with\n| (Some (Vfloat f1), Some (Vfloat f2)) =>\n   let ov :=\n     match c with\n     | fcond_false => Some (val2GV TD Vfalse (Mint 0))\n     | fcond_oeq =>\n         Some (val2GV TD (Val.cmpf Ceq (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ogt =>\n         Some (val2GV TD (Val.cmpf Cgt (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_oge =>\n         Some (val2GV TD (Val.cmpf Cge (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_olt =>\n         Some (val2GV TD (Val.cmpf Clt (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ole =>\n         Some (val2GV TD (Val.cmpf Cle (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_one =>\n         Some (val2GV TD (Val.cmpf Cne (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ord => gundef TD (typ_int 1%nat) (*FIXME: not supported yet. *)\n     | fcond_ueq =>\n         Some (val2GV TD (Val.cmpf Ceq (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ugt =>\n         Some (val2GV TD (Val.cmpf Cgt (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_uge =>\n         Some (val2GV TD (Val.cmpf Cge (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ult =>\n         Some (val2GV TD (Val.cmpf Clt (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_ule =>\n         Some (val2GV TD (Val.cmpf Cle (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_une =>\n         Some (val2GV TD (Val.cmpf Cne (Vfloat f1) (Vfloat f2)) (Mint 0))\n     | fcond_uno => gundef TD (typ_int 1%nat) (*FIXME: not supported yet. *)\n     | fcond_true => Some (val2GV TD Vtrue (Mint 0))\n     end in\n   match fp with\n   | fp_float => ov\n   | fp_double => ov\n   | _ => gundef TD (typ_int 1%nat) (*FIXME: not supported 80 and 128 yet. *)\n   end\n| _ => gundef TD (typ_int 1%nat)\nend.\n\n(* chunks_match_or_undef *)\n(* why not fit_gv? (-- harsher than needed, opsem_wf harder ++ already defined function) *)\n(* Actually, for --, see \"wf_GVs\" and \"getOperandValue__wf_gvs\", fit_gv is ok too. *)\n(* I just follow convention (like insertGenericValue-mset's case) here. *)\n(* fit_gv haven't used in defining mbop, blah. *)\nDefinition fit_chunk_gv (TD: TargetData) (ty: typ) (gv: GenericValue): option GenericValue :=\n  if (gv_chunks_match_typb TD gv ty)\n  then Some gv\n  else gundef TD ty\n.\n\nDefinition mselect (TD: TargetData) (ty: typ) (gv0 gv1 gv2: GenericValue): option GenericValue :=\n  match (GV2int TD Size.One gv0) with\n  | Some z =>\n    if (negb (Coqlib.zeq z 0))\n    then fit_chunk_gv TD ty gv1\n    else fit_chunk_gv TD ty gv2\n  | None => gundef TD ty\n  end\n.\n\n(* Convert constants to generic values *)\nFixpoint repeatGV (gv:GenericValue) (n:nat) : GenericValue :=\nmatch n with\n| O => nil\n| S n' => gv++repeatGV gv n'\nend.\n\nDefinition zeroconsts2GV_aux_\n  (zeroconst2GV_aux :\n    TargetData -> list (id * option GenericValue) ->\n    typ -> option GenericValue) :=\nfix zeroconsts2GV_aux (TD:TargetData) acc (lt:list typ) : option GenericValue :=\nmatch lt with\n| nil => Some nil\n| t :: lt' =>\n  match (zeroconsts2GV_aux TD acc lt', zeroconst2GV_aux TD acc t) with\n  | (Some gv, Some gv0) =>\n       match getTypeAllocSize TD t with\n       | Some asz => Some (gv0++uninits (asz - sizeGenericValue gv0)++gv)\n       | _ => None\n       end\n  | _ => None\n  end\nend.\n\nFixpoint zeroconst2GV_aux (TD:TargetData) (acc:list (id*option GenericValue))\n  (t:typ) : option GenericValue :=\nmatch t with\n| typ_int sz =>\n  let wz := ((Size.to_nat sz) - 1)%nat in\n  Some (val2GV TD (Vint wz (Int.repr wz 0)) (Mint wz))\n| typ_floatpoint fp =>\n  match fp with\n  | fp_float => Some (val2GV TD (Vsingle Float32.zero) Mfloat32)\n  | fp_double => Some (val2GV TD (Vfloat Float.zero) Mfloat64)\n  | _ => None (* FIXME: not supported 80 and 128 yet. *)\n  end\n| typ_void => None\n| typ_label => None\n| typ_metadata => None\n| typ_array sz t =>\n  match sz with\n  | O => Some (uninits 1)\n  | _ =>\n    match zeroconst2GV_aux TD acc t with\n    | Some gv0 =>\n      match getTypeAllocSize TD t with\n      | Some asz =>\n         Some (repeatGV (gv0++uninits (Size.to_nat asz - sizeGenericValue gv0))\n                 (Size.to_nat sz))\n      | _ => None\n      end\n    | _ => None\n    end\n  end\n| typ_struct ts =>\n  match zeroconsts2GV_aux_ zeroconst2GV_aux TD acc ts with\n  | Some nil => Some (uninits 1)\n  | Some gv0 => Some gv0\n  | None => None\n  end\n| typ_pointer t' => Some null\n| typ_function _ _ _ => None\n| typ_namedt nid => \n  match lookupAL _ acc nid with\n  | Some re => re\n  | _ => None\n  end\nend.\n\nDefinition zeroconsts2GV_aux :=\n  zeroconsts2GV_aux_ zeroconst2GV_aux.\n\nFixpoint zeroconst2GV_for_namedts TD (los:layouts) (nts:namedts) \n  : list (id*option GenericValue) :=\nmatch nts with\n| nil => nil \n| (id0, ts0)::nts' =>\n  let results := zeroconst2GV_for_namedts TD los nts' in\n  (id0, zeroconst2GV_aux TD results (typ_struct ts0))::results\nend.\n\nDefinition zeroconst2GV (TD:TargetData) (t:typ) : option GenericValue :=\nlet '(los, nts) := TD in\nzeroconst2GV_aux TD (zeroconst2GV_for_namedts TD los nts) t.\n\nDefinition zeroconsts2GV (TD:TargetData) (lt:list typ)\n  : option GenericValue :=\nlet '(los, nts) := TD in\nzeroconsts2GV_aux TD (zeroconst2GV_for_namedts TD los nts) lt.\n\nDefinition _list_const_arr2GV_\n  (_const2GV : TargetData -> GVMap ->\n    const -> option (GenericValue * typ)) :=\nfix _list_const_arr2GV (TD:TargetData) (gl:GVMap) (t:typ) (cs:list const)\n  : option GenericValue :=\nmatch cs with\n| nil => Some nil\n| c :: lc' =>\n  match (_list_const_arr2GV TD gl t lc', _const2GV TD gl c) with\n  | (Some gv, Some (gv0, t0)) =>\n      if typ_dec t t0 then\n             match getTypeAllocSize TD t0 with\n             | Some asz0 =>\n                 Some (gv0++uninits (asz0 - sizeGenericValue gv0) ++ gv)\n             | _ => None\n             end\n      else None\n  | _ => None\n  end\nend.\n\nDefinition _list_const_struct2GV_\n  (_const2GV : TargetData -> GVMap ->\n    const -> option (GenericValue * typ)) :=\nfix _list_const_struct2GV (TD:TargetData) (gl:GVMap) (cs:list const)\n  : option (GenericValue * list typ) :=\nmatch cs with\n| nil => Some (nil, nil)\n| c :: lc' =>\n  match (_list_const_struct2GV TD gl lc', _const2GV TD gl c) with\n  | (Some (gv, ts), Some (gv0,t0)) =>\n       match getTypeAllocSize TD t0 with\n       | Some asz =>\n            Some (gv0++uninits (asz - sizeGenericValue gv0)++gv,\n                  t0 :: ts)\n       | _ => None\n       end\n  | _ => None\n  end\nend.\n\nFixpoint _const2GV (TD:TargetData) (gl:GVMap) (c:const)\n  : option (GenericValue*typ) :=\nmatch c with\n| const_zeroinitializer t =>\n  match zeroconst2GV TD t with\n  | Some gv => Some (gv, t)\n  | None => None\n  end\n| const_int sz n =>\n         let wz := (Size.to_nat sz - 1)%nat in\n         Some (val2GV TD (Vint wz (Int.repr wz (INTEGER.to_Z n))) (Mint wz),\n               typ_int sz)\n| const_floatpoint fp f =>\n         match fp with\n         | fp_float => Some (val2GV TD (Vsingle (Float.to_single f)) Mfloat32, \n                             typ_floatpoint fp)\n         | fp_double => Some (val2GV TD (Vfloat f) Mfloat64, typ_floatpoint fp)\n         | _ => None (* FIXME: not supported 80 and 128 yet. *)\n         end\n| const_undef t =>\n         match (gundef TD t) with\n         | Some gv => Some (gv, t)\n         | None => None\n         end\n| const_null t =>\n         Some (null, typ_pointer t)\n| const_arr t lc =>\n         match _list_const_arr2GV_ _const2GV TD gl t lc with\n         | Some gv =>\n             match length lc with\n             | O => Some (uninits 1,\n                            typ_array (length lc) t)\n             | _ => Some (gv,\n                            typ_array (length lc) t)\n             end\n         | _ => None\n         end\n| const_struct t lc =>\n         match (_list_const_struct2GV_ _const2GV TD gl lc) with\n         | None => None\n         | Some (gv0, ts) =>\n             let '(_, nts) := TD in\n             if typ_eq_list_typ nts t ts then\n               match gv0 with\n               | nil => Some (uninits 1, t)\n               | gv => Some (gv, t)\n               end\n             else None\n         end\n| const_gid t id =>\n         match (lookupAL _ gl id) with\n         | Some gv => Some (gv, typ_pointer t)\n         | None => None\n         end\n| const_truncop op c1 t2 =>\n         match _const2GV TD gl c1 with\n         | Some (gv1, t1) =>\n           match mtrunc TD op t1 t2 gv1 with\n           | Some gv2 => Some (gv2, t2)\n           | _ => None\n           end\n         | _ => None\n         end\n| const_extop op c1 t2 =>\n         match _const2GV TD gl c1 with\n         | Some (gv1, t1) =>\n           match mext TD op t1 t2 gv1 with\n           | Some gv2 => Some (gv2, t2)\n           | _ => None\n           end\n         | _ => None\n         end\n| const_castop op c1 t2 =>\n         match _const2GV TD gl c1 with\n         | Some (gv1, t1) =>\n           match mcast TD op t1 t2 gv1 with\n           | Some gv2 => Some (gv2, t2)\n           | _ => None\n           end\n         | _ => None\n         end\n| const_gep ib c1 cs2 =>\n       match _const2GV TD gl c1 with\n       | Some (gv1, typ_pointer t1) =>\n         match getConstGEPTyp cs2 (typ_pointer t1) with\n         | Some t2 =>\n           match GV2ptr TD (getPointerSize TD) gv1 with\n           | Some ptr =>\n             match intConsts2Nats TD cs2 with\n             | None => match gundef TD t2 with\n                       | Some gv => Some (gv, t2)\n                       | None => None\n                       end\n             | Some idxs =>\n               match (mgep TD t1 ptr idxs) with\n               | Some ptr0 => Some (ptr2GV TD ptr0, t2)\n               | None => match gundef TD t2 with\n                         | Some gv => Some (gv, t2)\n                         | None => None\n                         end\n               end\n             end\n           | None => match gundef TD t2 with\n                     | Some gv => Some (gv, t2)\n                     | None => None\n                     end\n           end\n         | _ => None\n         end\n       | _ => None\n       end\n| const_select c0 c1 c2 =>\n  match _const2GV TD gl c0, _const2GV TD gl c1, _const2GV TD gl c2 with\n  | Some (gv0, t0), Some gvt1, Some gvt2 => if isGVZero TD gv0\n                                            then Some gvt2\n                                            else Some gvt1\n  | _, _, _ => None\n  end\n| const_icmp cond c1 c2 =>\n         match _const2GV TD gl c1, _const2GV TD gl c2 with\n         | Some (gv1, t1), Some (gv2, _) =>\n             match micmp TD cond t1 gv1 gv2 with\n             | Some gv2 => Some (gv2, typ_int Size.One)\n             | _ => None\n             end\n         | _, _ => None\n         end\n| const_fcmp cond c1 c2 =>\n         match _const2GV TD gl c1, _const2GV TD gl c2 with\n         | Some (gv1, typ_floatpoint fp1), Some (gv2, _) =>\n           match mfcmp TD cond fp1 gv1 gv2 with\n           | Some gv2 => Some (gv2, typ_int Size.One)\n           | _ => None\n           end\n         | _, _ => None\n         end\n| const_extractvalue c1 cs2 =>\n       match _const2GV TD gl c1 with\n       | Some (gv1, t1) =>\n         match getSubTypFromConstIdxs cs2 t1 with\n         | Some t2 =>\n           match extractGenericValue TD t1 gv1 cs2 with\n           | Some gv2 => Some (gv2, t2)\n           | _ => None\n           end\n         | _ => None\n         end\n       | _ => None\n       end\n| const_insertvalue c1 c2 cs3 =>\n         match _const2GV TD gl c1, _const2GV TD gl c2 with\n         | Some (gv1, t1), Some (gv2, t2) =>\n           match insertGenericValue TD t1 gv1 cs3 t2 gv2 with\n           | Some gv3 => Some (gv3, t1)\n           | _ => None\n           end\n         | _, _ => None\n         end\n| const_bop op c1 c2 =>\n         match _const2GV TD gl c1, _const2GV TD gl c2 with\n         | Some (gv1, typ_int sz1), Some (gv2, _) =>\n           match mbop TD op sz1 gv1 gv2 with\n           | Some gv3 => Some (gv3, typ_int sz1)\n           | _ => None\n           end\n         | _, _ => None\n         end\n| const_fbop op c1 c2 =>\n         match _const2GV TD gl c1, _const2GV TD gl c2 with\n         | Some (gv1, typ_floatpoint fp1), Some (gv2, _) =>\n           match mfbop TD op fp1 gv1 gv2 with\n           | Some gv3 => Some (gv3, typ_floatpoint fp1)\n           | _ => None\n           end\n         | _, _ => None\n         end\nend.\n\nDefinition _list_const_struct2GV :=\n  _list_const_struct2GV_ _const2GV.\n\nDefinition _list_const_arr2GV :=\n  _list_const_arr2GV_ _const2GV.\n\nDefinition cundef_gv gv t : GenericValue :=\nmatch t with\n| typ_int sz => (Vint (sz-1) (Int.zero (sz-1)), Mint (sz -1))::nil\n| typ_floatpoint fp_float => (Vsingle Float32.zero, Mfloat32)::nil\n| typ_floatpoint fp_double => (Vfloat Float.zero, Mfloat64)::nil\n| typ_pointer _ => null\n| _ => gv\nend.\n\nDefinition cgv2gv (gv:GenericValue) (t:typ) : GenericValue := gv.\n\nNotation \"? gv # t ?\" := (cgv2gv gv t) (at level 41).\n\nDefinition const2GV (TD:TargetData) (gl:GVMap) (c:const) : option GenericValue :=\nmatch (_const2GV TD gl c) with\n| None => None\n| Some (gv, t) => Some (? gv # t ?)\nend.\n\n(* Compute the generic value of a program value. *)\nDefinition getOperandValue (TD:TargetData) (v:value) (locals:GVMap)\n  (globals:GVMap) : option GenericValue :=\nmatch v with\n| value_id id => lookupAL _ locals id\n| value_const c => const2GV TD globals c\nend.\n\nDefinition getOperandInt (TD:TargetData) (bsz:sz) (v:value) (locals:GVMap)\n  (globals:GVMap) : option Z :=\nmatch (getOperandValue TD v locals globals) with\n| Some gi => GV2int TD bsz gi\n| None => None\nend.\n\nDefinition getOperandPtr (TD:TargetData) (v:value) (locals:GVMap)\n  (globals:GVMap) : option val :=\nmatch (getOperandValue TD v locals globals) with\n| Some gi => GV2ptr TD (getPointerSize TD) gi\n| None => None\nend.\n\nDefinition getOperandPtrInBits (TD:TargetData) (s:sz) (v:value) (locals:GVMap)\n  (globals:GVMap) : option val :=\nmatch (getOperandValue TD v locals globals) with\n| Some gi => GV2ptr TD s gi\n| None => None\nend.\n\n(* Check if the runtime of a program value is undefined. *)\nDefinition isOperandUndef (TD:TargetData) (t:typ) (v:value) (locals:GVMap)\n  (globals:GVMap) : Prop  :=\nmatch (getOperandValue TD v locals globals) with\n| Some gi => isGVUndef gi\n| None => False\nend.\n\n(* convert parameters and values to generic values *)\nFixpoint params2GVs (TD:TargetData) (lp:params) (locals:GVMap)\n  (globals:GVMap) : option (list GenericValue) :=\nmatch lp with\n| nil => Some nil\n| (_, v)::lp' =>\n    match (getOperandValue TD v locals globals,\n          params2GVs TD lp' locals globals) with\n    | (Some gv, Some gvs) => Some (gv::gvs)\n    | _ => None\n    end\nend.\n\nFixpoint values2GVs (TD:TargetData) (lv:list (sz * value)) (locals:GVMap)\n  (globals:GVMap) : option (list GenericValue):=\nmatch lv with\n| nil => Some nil\n| (_, v) :: lv' =>\n  match (getOperandValue TD v locals globals) with\n  | Some GV =>\n    match (values2GVs TD lv' locals globals) with\n    | Some GVs => Some (GV::GVs)\n    | None => None\n    end\n  | None => None\n  end\nend.\n\nFixpoint intValues2Nats (TD:TargetData) (lv:list (sz * value)) (locals:GVMap)\n  (globals:GVMap) : option (list Z):=\nmatch lv with\n| nil => Some nil\n| (_, v) :: lv' =>\n  match (getOperandValue TD v locals globals) with\n  | Some GV =>\n    match (GV2int TD Size.ThirtyTwo GV) with\n    | Some z =>\n        match (intValues2Nats TD lv' locals globals) with\n        | Some ns => Some (z::ns)\n        | None => None\n        end\n    | _ => None\n    end\n  | None => None\n  end\nend.\n\n(* Initialize locals of funtions *)\nDefinition fit_gv TD (t:typ) (gv:GenericValue) : option GenericValue :=\nmatch (getTypeSizeInBits TD t) with\n| Some sz =>\n    if beq_nat (sizeGenericValue gv)\n               (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) &&\n       gv_chunks_match_typb TD gv t\n    then Some gv\n    else gundef TD t\n| None => None\nend.\n\nFixpoint _initializeFrameValues TD (la:args) (lg:list GenericValue)\n  (locals:GVMap) : option GVMap :=\nmatch (la, lg) with\n| (((t, _), id)::la', g::lg') =>\n  match _initializeFrameValues TD la' lg' locals, fit_gv TD t g with\n  | Some lc', Some gv => Some (updateAddAL _ lc' id (? gv # t ?))\n  | _, _ => None\n  end\n| (((t, _), id)::la', nil) =>\n  (* FIXME: We should initalize them w.r.t their type size. *)\n  match _initializeFrameValues TD la' nil locals, gundef TD t with\n  | Some lc', Some gv => Some (updateAddAL _ lc' id (? gv # t ?))\n  | _, _ => None\n  end\n| _ => Some locals\nend.\n\nDefinition initLocals TD (la:args) (lg:list GenericValue): option GVMap :=\n_initializeFrameValues TD la lg nil.\n\n(* Operations of generic values used by Vellvm's operational semantics *)\nDefinition BOP (TD:TargetData) (lc gl:GVMap) (op:bop) (bsz:sz)\n  (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gv1, Some gv2) => mbop TD op bsz gv1 gv2\n| _ => None\nend.\n\nDefinition FBOP (TD:TargetData) (lc gl:GVMap) (op:fbop)\n  (fp:floating_point) (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gv1, Some gv2) => mfbop TD op fp gv1 gv2\n| _ => None\nend\n.\n\nDefinition TRUNC (TD:TargetData) (lc gl:GVMap) (op:truncop) (t1:typ)\n  (v1:value) (t2:typ) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gv1) => mtrunc TD op t1 t2 gv1\n| _ => None\nend\n.\n\nDefinition CAST (TD:TargetData) (lc gl:GVMap) (op:castop) (t1:typ)\n  (v1:value) (t2:typ) : option GenericValue:=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gv1) => mcast TD op t1 t2 gv1\n| _ => None\nend\n.\n\nDefinition EXT (TD:TargetData) (lc gl:GVMap) (op:extop) (t1:typ)\n  (v1:value) (t2:typ) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gv1) => mext TD op t1 t2 gv1\n| _ => None\nend\n.\n\nDefinition ICMP (TD:TargetData) (lc gl:GVMap) (c:cond) (t:typ)\n  (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gv1, Some gv2) => micmp TD c t gv1 gv2\n| _ => None\nend.\n\nDefinition FCMP (TD:TargetData) (lc gl:GVMap) (c:fcond)\n  (fp:floating_point) (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gv1, Some gv2) => mfcmp TD c fp gv1 gv2\n| _ => None\nend.\n\nDefinition SELECT (TD:TargetData) (lc gl:GVMap) (v0 v1 v2:value) (t: typ): option GenericValue :=\n  match (getOperandValue TD v0 lc gl, getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n  | (Some gv0, Some gv1, Some gv2) => mselect TD t gv0 gv1 gv2\n  | _ => gundef TD t\n  end\n.\n\n(* t' is from getGEPtyp that always returns Some t'* or None *)\nDefinition GEP (TD:TargetData) (t:typ) (ma:GenericValue)\n  (vidxs:list GenericValue) (inbounds:bool) (t':typ) : option GenericValue :=\nmatch GV2ptr TD (getPointerSize TD) ma with\n| Some ptr =>\n  match GVs2Nats TD vidxs with\n  | None => gundef TD (typ_pointer t')\n  | Some idxs =>\n    match (mgep TD t ptr idxs) with\n    | Some ptr0 => Some (ptr2GV TD ptr0)\n    | None => gundef TD (typ_pointer t')\n    end\n  end\n| None => gundef TD (typ_pointer t')\nend.\n\nDefinition malloc (TD:TargetData) (M:mem) (bsz:sz) (gn:GenericValue) (al:align)\n  : option (mem * mblock)%type :=\n  Some (Mem.alloc M 0\n          match GV2int TD Size.ThirtyTwo gn with\n            | Some n => (Size.to_Z bsz) * n\n            | None => 0\n          end).\n\nDefinition alloca (TD:TargetData) (M:mem) (bsz:sz) (gn:GenericValue) (al:align)\n  : option (mem * mblock)%type :=\n  match GV2int TD Size.ThirtyTwo gn with\n  | Some n =>\n    let hi := (Size.to_Z bsz * n)%Z in\n    let (M', nb) := (Mem.alloc M 0 hi) in\n    option_map ((flip pair) nb) (Mem.drop_perm M' nb 0 hi Writable)\n  | None => None\n  end\n.\n\nDefinition malloc_one (TD:TargetData) (M:mem) (bsz:sz) (al:align)\n  : option (mem * mblock)%type :=\n  Some (Mem.alloc M 0 (Size.to_Z bsz)).\n\nDefinition free (TD:TargetData) (M:mem) (ptr:mptr) : option mem :=\nmatch GV2ptr TD (getPointerSize TD) ptr with\n| Some (Vptr b i) =>\n  if Coqlib.zeq (Int.signed 31 i) 0\n  then\n    match (Mem.bounds M b) with\n    | (l, h) => Mem.free M b l h\n    end\n  else None\n| _ => None\nend.\n\nFixpoint free_allocas (TD:TargetData) (Mem:mem) (allocas:list mblock)\n  : option mem :=\nmatch allocas with\n| nil => Some Mem\n| alloca::allocas' =>\n  let (lo, hi) := Mem.bounds Mem alloca in\n  free_allocas TD (Mem.unchecked_free Mem alloca lo hi) allocas'\nend.\n\nFixpoint mload_aux M (mc:list memory_chunk) b ofs : option GenericValue :=\nmatch mc with\n| nil => Some nil\n| c::mc' =>\n    match (Mem.load c M b ofs, mload_aux M mc' b (ofs+size_chunk c)%Z) with\n    | (Some v, Some gv) => Some ((v,c) :: gv)\n    | _ => None\n    end\nend.\n\nDefinition mload (TD:TargetData) (M:mem) (ptr:mptr) (t:typ) (a:align)\n  : option GenericValue :=\nmatch GV2ptr TD (getPointerSize TD) ptr with\n| Some (Vptr b ofs) =>\n  match flatten_typ TD t with\n  | Some mc => mload_aux M mc b (Int.signed 31 ofs)\n  | _ => None\n  end\n| _ => None\nend.\n\nDefinition has_chunk_eq (v : val) (chk : AST.memory_chunk) : bool :=\n  match v, chk with\n    | Vundef, _ => true\n    | Vint wz i0, AST.Mint wz' =>\n      beq_nat wz wz'\n    | Vsingle f, AST.Mfloat32 =>\n      true\n    | Vfloat f, AST.Mfloat64 =>\n      true\n    | Vptr _ _, AST.Mint wz =>\n      beq_nat wz 31%nat\n    | Vinttoptr _, AST.Mint wz =>\n      beq_nat wz 31%nat\n    | _, _ =>\n      false\n  end.\n\nLemma has_chunk_eq_prop v chk (H: has_chunk_eq v chk) :\n  Val.has_chunk v chk.\nProof.\n  destruct v, chk; simpl in *; auto;\n    repeat\n      match goal with\n        | [H: is_true false |- _] =>\n          unfold is_true in H; inversion H\n        | [H: is_true (beq_nat ?a ?b) |- _] =>\n          apply beq_nat_true in H; subst\n        | [H: context[Floats.Float.eq_dec ?a ?b] |- _] =>\n          destruct (Floats.Float.eq_dec a b); try inversion H\n      end;\n    auto.\n  split; [auto|].\n  apply Int.unsigned_range.\nQed.\n\nLemma memory_chunk_eq_prop a b\n  (H: AST.memory_chunk_eq a b) : a = b.\nProof.\n  destruct a, b; unfold AST.memory_chunk_eq in H; simpl in *; auto;\n    try match goal with\n          | [H: is_true false |- _] =>\n            unfold is_true in H; inversion H\n        end.\n  apply beq_nat_true in H; subst; auto.\nQed.\n\nFixpoint mstore_aux M (mc:list memory_chunk) (gv:GenericValue) b ofs : option mem :=\n  match mc, gv with\n    | nil, nil => Some M\n    | c'::mc', (v,c)::gv' =>\n      if memory_chunk_eq c' c && has_chunk_eq v c\n      then\n        match (Mem.store c M b ofs v) with\n          | Some M' => mstore_aux M' mc' gv' b (ofs+size_chunk c)%Z\n          | _ => None\n        end\n      else None\n    | _, _ => None\n  end.\n\nDefinition mstore (TD:TargetData) (M:mem) (ptr:mptr) (t:typ) (gv:GenericValue)\n           (a:align) : option mem :=\n  match GV2ptr TD (getPointerSize TD) ptr with\n    | Some (Vptr b ofs) =>\n      match flatten_typ TD t with\n        | Some mc => mstore_aux M mc gv b (Int.signed 31 ofs)\n        | None => None\n      end\n    | _ => None\n  end.\n\nDefinition gep (TD:TargetData) (ty:typ) (vidxs:list GenericValue) (inbounds:bool)\n  (ty':typ) (ma:GenericValue) : option GenericValue :=\nLLVMgv.GEP TD ty ma vidxs inbounds ty'.\n\nDefinition mget' TD o t' gv: option GenericValue :=\nmatch mget TD gv o t' with\n| Some gv' => Some gv'\n| None => gundef TD t'\nend.\n\nDefinition mset' TD o t t0 gv gv0 : option GenericValue :=\nmatch (mset TD gv o t0 gv0) with\n| Some gv' => Some gv'\n| None => gundef TD t\nend.\n\nLtac inv H := inversion H; subst; clear H.\n\n(********** Properties of sizeGenericValue *******************)\nLemma sizeGenericValue__app : forall gv1 gv2,\n  sizeGenericValue (gv1 ++ gv2) = sizeGenericValue gv1 + sizeGenericValue gv2.\nProof.\n  induction gv1; intros; simpl; auto.\n    destruct a. rewrite IHgv1. omega.\nQed.\n\nLemma sizeGenericValue__repeatGV : forall gv n,\n  sizeGenericValue (repeatGV gv n) = n * sizeGenericValue gv.\nProof.\n  induction n; simpl; auto.\n    rewrite sizeGenericValue__app. rewrite IHn. auto.\nQed.\n\nLemma sizeGenericValue__uninits : forall n, sizeGenericValue (uninits n) = n.\nProof.\n  induction n; simpl; auto.\nQed.\n\nLemma sizeGenericValue_cons_pos : forall p gv0,\n  (sizeGenericValue (p :: gv0) > 0)%nat.\nProof.\n  intros. destruct p. simpl.\n  assert (J:=@size_chunk_nat_pos' m).\n  omega.\nQed.\n\nLemma sizeGenericValue_mc2undefs__sizeMC : forall mc, \n  sizeGenericValue (mc2undefs mc) = sizeMC mc.\nProof.\n  induction mc; simpl; auto.\nQed.\n\n(********** Properties of memory chunk *******************)\nLemma memory_chuck_dec : forall (mc1 mc2:AST.memory_chunk), \n  mc1 = mc2 \\/ mc1 <> mc2.\nProof.\n  destruct mc1; destruct mc2; try solve [auto | right; congruence].\n    destruct (eq_nat_dec n n0); auto.\n      right. intros J. inv J. auto.\nQed.\n\n(********** Properties of getSubTypFromConstIdxs *******************)\nDefinition wf_global TD system5 gl := forall id5 typ5,\n  lookupTypViaGIDFromSystem system5 id5 = ret typ5 ->\n  exists gv, exists sz,\n    lookupAL GenericValue gl id5 = Some gv /\\\n    getTypeSizeInBits TD typ5 = Some sz /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv /\\\n    gv_chunks_match_typ TD gv typ5.\n\nLemma getSubTypFromConstIdxs__mgetoffset_aux : forall TD const_list idxs o t'\n    t1 typ' o0\n  (HeqR1 : ret idxs = intConsts2Nats TD const_list)\n  (HeqR2 : ret (o, t') = mgetoffset_aux TD t1 idxs o0)\n  (e0 : getSubTypFromConstIdxs const_list t1 = ret typ'),\n  t' = typ'.\nProof.\n  induction const_list; simpl; intros.\n    inv HeqR1. simpl in HeqR2. inv HeqR2. inv e0; auto.\n\n    destruct_const a; tinv HeqR1.\n    destruct (Size.dec sz5 Size.ThirtyTwo); tinv HeqR1.\n    remember (intConsts2Nats TD const_list) as R3.\n    destruct R3; inv HeqR1.\n    destruct t1; tinv e0.\n      simpl in HeqR2.\n      destruct (getTypeAllocSize TD t1); inv HeqR2; eauto.\n\n      simpl in HeqR2.\n      destruct (_getStructElementOffset TD l1 (Coqlib.nat_of_Z\n        (INTEGER.to_Z Int5)) 0); inv HeqR2; eauto.\n      unfold INTEGER.to_nat in e0.\n      unfold INTEGER.to_Z in H0.\n      destruct (nth_error l1 (Coqlib.nat_of_Z Int5)); inv e0.\n      simpl in H0. eauto.\nQed.\n\nLemma getSubTypFromConstIdxs__mgetoffset : forall TD const_list idxs o t' t1\n    typ'\n  (HeqR1 : ret idxs = intConsts2Nats TD const_list)\n  (HeqR2 : ret (o, t') = mgetoffset TD t1 idxs)\n  (e0 : getSubTypFromConstIdxs const_list t1 = ret typ'),\n  t' = typ'.\nProof.\n  unfold mgetoffset. intros.\n  eapply getSubTypFromConstIdxs__mgetoffset_aux; eauto.\nQed.\n\n(********** Properties of splitGenericValue *******************)\nLemma splitGenericValue_spec0 : forall gv pos gv1 gv2,\n  splitGenericValue gv pos = Some (gv1, gv2) -> (pos >= 0)%Z.\nProof.\n  induction gv; simpl; intros.\n    destruct (Coqlib.zeq pos 0); subst.\n      auto with zarith.\n      destruct (Coqlib.zlt pos 0); inv H.\n\n    destruct (Coqlib.zeq pos 0); subst.\n      auto with zarith.\n\n      destruct (Coqlib.zlt pos 0); tinv H; auto.\nQed.\n\nLemma splitGenericValue_spec : forall gv pos gv1 gv2,\n  splitGenericValue gv pos = Some (gv1, gv2) ->\n  sizeGenericValue gv1 = Coqlib.nat_of_Z pos /\\\n  (sizeGenericValue gv1 + sizeGenericValue gv2 = sizeGenericValue gv)%nat.\nProof.\n  induction gv; simpl; intros.\n    destruct (Coqlib.zeq pos 0); subst.\n      inv H. auto.\n      destruct (Coqlib.zlt pos 0); inv H.\n\n    destruct a.\n    destruct (Coqlib.zeq pos 0); subst.\n      inv H. auto.\n\n      destruct (Coqlib.zlt pos 0); tinv H.\n      remember (splitGenericValue gv (pos - size_chunk m)) as R.\n      destruct R as [[]|]; inv H.\n      simpl.\n      symmetry in HeqR.\n      assert (J:=HeqR). apply splitGenericValue_spec0 in J.\n      eapply IHgv in HeqR; eauto.\n      destruct HeqR as [J1 J2].\n      rewrite <- J2. rewrite J1.\n      assert ((size_chunk_nat m + Coqlib.nat_of_Z (pos - size_chunk m))%nat =\n        Coqlib.nat_of_Z pos) as J3.\n        unfold size_chunk_nat.\n        assert (J0:=@size_chunk_pos m).\n        rewrite <- Coqlib.nat_of_Z_plus; auto.\n          assert (size_chunk m + (pos - size_chunk m) = pos)%Z as EQ.\n            ring.\n          rewrite EQ. auto.\n\n          auto with zarith.\n      rewrite J3. rewrite <- plus_assoc_reverse. rewrite J3.\n      split; auto.\nQed.\n\nLemma splitGenericValue_spec1: forall gv o gv1 gv2, \n  splitGenericValue gv o = Some (gv1, gv2) ->\n  gv = gv1 ++ gv2 /\\ sizeGenericValue gv1 = Coqlib.nat_of_Z o.\nProof.\n  induction gv as [|[]]; simpl; intros.\n    repeat (destruct_if; auto).\n\n    repeat (destruct_if; auto).\n    inv_mbind. uniq_result. symmetry_ctx.\n    assert (J:=HeqR1). apply splitGenericValue_spec0 in J.\n    apply IHgv in HeqR1. \n    destruct HeqR1 as [J1 J2]; subst.\n    split; simpl; auto.\n      rewrite J2.\n      unfold size_chunk_nat.\n      assert (J0:=@size_chunk_pos m).\n      rewrite <- Coqlib.nat_of_Z_plus; auto.\n        assert (size_chunk m + (o - size_chunk m) = o)%Z as EQ.\n          ring.\n        rewrite EQ. auto.\n\n        auto with zarith.\nQed.\n\n(********** Properties of gv_chunks_match_typ *******************)\nLemma gv_chunks_match_typb_aux__gv_chunks_match_typ: forall mcs gv,\n  gv_chunks_match_typb_aux gv mcs = true ->\n  Forall2 vm_matches_typ gv mcs.\nProof.\n  induction mcs; simpl; intros.\n    destruct gv as [|[]]; auto.\n      inv H.\n    destruct gv as [|[]].\n      inv H.\n\n      simpl in H.\n      apply andb_true_iff in H.\n      destruct H as [H1 H2].\n      apply andb_true_iff in H1.\n      destruct H1 as [H1 H3].\n      constructor; eauto.\n        unfold vm_matches_typ. simpl.\n        split; auto using Val.has_chunkb__has_chunk.\n        destruct m, a; tinv H1; auto.\n          apply neq_inv in H1. congruence.\nQed.\n\nLemma gv_chunks_match_typb__gv_chunks_match_typ: forall td gv ty,\n  gv_chunks_match_typb td gv ty = true ->\n  gv_chunks_match_typ td gv ty.\nProof.\n  unfold gv_chunks_match_typb, gv_chunks_match_typ.\n  intros.\n  inv_mbind.\n  apply gv_chunks_match_typb_aux__gv_chunks_match_typ; auto.\nQed.\n\n(********** Properties of vm_matches_typ *******************)\nLemma match_chunks_app: forall gv2 mcs2 (H2: Forall2 vm_matches_typ gv2 mcs2)\n  gv1 mcs1 (H1: Forall2 vm_matches_typ gv1 mcs1),\n    Forall2 vm_matches_typ (gv1++gv2) (mcs1++mcs2).\nProof.\n  induction 2; simpl; auto.\nQed.\n\nLemma match_chunks_repeat: forall gv mcs (H1: Forall2 vm_matches_typ gv mcs) \n  n, Forall2 vm_matches_typ (repeatGV gv n) (repeatMC mcs n).\nProof.\n  induction n; simpl; auto.\n    apply match_chunks_app; auto.\nQed.\n\nLemma match_chunks_eq_size: forall gv mcs,\n  Forall2 vm_matches_typ gv mcs ->\n  sizeGenericValue gv = sizeMC mcs.\nProof.\n  induction 1 as [|[]]; simpl; auto.\n    inv H. simpl. congruence.\nQed.\n\nLemma match_chunks_app_inv: forall gv2 mcs2 gv1 mcs1 \n  (H:Forall2 vm_matches_typ (gv1++gv2) (mcs1++mcs2))\n  (EQ1: sizeGenericValue gv1 = sizeMC mcs1),\n  Forall2 vm_matches_typ gv1 mcs1 /\\ Forall2 vm_matches_typ gv2 mcs2.\nProof.\n  induction gv1 as [|[]]; destruct mcs1; simpl; intros; auto.\n    assert (J:=@size_chunk_nat_pos m).\n    destruct J as [n J].\n    rewrite J in EQ1.\n    inv EQ1.\n\n    assert (J:=@size_chunk_nat_pos m).\n    destruct J as [n J].\n    rewrite J in EQ1.\n    inv EQ1.\n\n    inv H. \n    apply IHgv1 in H5.\n      destruct H5 as [H5 H6].\n      split; auto.\n\n      inv H3. simpl in *. clear - EQ1. omega.\nQed.\n\nLemma match_chunks_split_right: forall gv2 gv1 mcs\n  (H:Forall2 vm_matches_typ (gv1++gv2) mcs),\n  exists mcs1, exists mcs2,\n    mcs = mcs1 ++ mcs2 /\\\n    Forall2 vm_matches_typ gv1 mcs1 /\\ \n    Forall2 vm_matches_typ gv2 mcs2.\nProof.\n  induction gv1; simpl; intros.\n    exists nil. exists mcs.\n    split; auto.\n\n    inv H.\n    apply IHgv1 in H4.\n    destruct H4 as [mcs1 [mcs2 [J1 [J2 J3]]]]; subst.\n    exists (y::mcs1). exists mcs2.\n    split; auto.\nQed.\n\nLemma match_chunks_det: forall gv mcs1 \n  (H1: Forall2 vm_matches_typ gv mcs1)\n  mcs2 (H2: Forall2 vm_matches_typ gv mcs2),\n  mcs1 = mcs2.\nProof.\n  induction 1; simpl; intros; inv H2; auto.\n    inv H. inv H4.\n    erewrite IHForall2; eauto.\nQed.\n\nLemma uninits_match_uninitMCs: forall n,\n  Forall2 vm_matches_typ (uninits n) (uninitMCs n).\nProof.\n  unfold uninits, uninitMCs, vm_matches_typ.\n  induction n; simpl; auto.\n    constructor; simpl; auto.\nQed.\n\nLemma mset_matches_chunks : forall td gv1 o t2 gv2 gv t1 \n  (J1: gv_chunks_match_typ td gv1 t1) (J2: gv_chunks_match_typ td gv2 t2)\n  (HeqR4 : ret gv = mset td gv1 o t2 gv2),\n  gv_chunks_match_typ td gv t1.\nProof.\n  intros.\n  unfold mset in HeqR4.\n  remember (getTypeStoreSize td t2) as R.\n  destruct R; tinv HeqR4.\n  simpl in HeqR4.\n  destruct (n =n= length gv2); tinv HeqR4.\n  remember (splitGenericValue gv1 o) as R1.\n  destruct R1 as [[? gvr]|]; tinv HeqR4.\n  remember (splitGenericValue gvr (Z_of_nat n)) as R2.\n  destruct R2 as [[gvrl ?]|]; inv HeqR4.\n  destruct_if.\n  unfold gv_chunks_match_typ in *.\n  inv_mbind. symmetry_ctx.\n  apply splitGenericValue_spec1 in HeqR1.\n  apply splitGenericValue_spec1 in HeqR2.\n  destruct HeqR1 as [HeqR11 HeqR12]; subst.\n  destruct HeqR2 as [HeqR21 HeqR22]; subst.\n  apply match_chunks_split_right in J1.\n  destruct J1 as [mcs1 [mcs2 [EQ [J1 J3]]]]; subst.\n  apply match_chunks_split_right in J3.\n  destruct J3 as [mcs3 [mcs4 [EQ [J3 J4]]]]; subst.\n  repeat (apply match_chunks_app; auto).\n  symmetry in HeqR0.\n  apply gv_chunks_match_typb__gv_chunks_match_typ in HeqR0; auto.\n  unfold gv_chunks_match_typ in HeqR0.\n  rewrite HeqR3 in HeqR0.\n  eapply match_chunks_det with (mcs2:=l0) in J3; eauto.\n  subst. auto.\nQed.\n\nLemma mget_matches_chunks : forall td gv1 o typ' gv'\n  (HeqR4 : ret gv' = mget td gv1 o typ'),\n  gv_chunks_match_typ td gv' typ'.\nProof.\n  intros.\n  unfold mget in HeqR4.\n  remember (getTypeStoreSize td typ') as R.\n  destruct R; tinv HeqR4.\n  simpl in HeqR4.\n  remember (splitGenericValue gv1 o) as R1.\n  destruct R1 as [[? gvr]|]; tinv HeqR4.\n  remember (splitGenericValue gvr (Z_of_nat n)) as R2.\n  destruct R2 as [[gvrl ?]|]; inv HeqR4.\n  remember (gv_chunks_match_typb td gvrl typ') as R.\n  destruct R; inv H0.\n  apply gv_chunks_match_typb__gv_chunks_match_typ; auto.\nQed.\n\nLemma mcmp_matches_chunks_helper : forall TD gv,\n  gundef TD (typ_int 1%nat) = ret gv ->\n  gv_chunks_match_typ TD gv (typ_int 1%nat).\nProof.\n  intros. destruct TD.\n  unfold gundef in H. simpl in H. inv H. \n  unfold gv_chunks_match_typ, vm_matches_typ. \n  simpl. constructor; simpl; auto.\nQed.\n\nLemma micmp_matches_chunks : forall TD cond5 t1 gv1 gv2 gv,\n  micmp TD cond5 t1 gv1 gv2 = Some gv ->\n  gv_chunks_match_typ TD gv (typ_int 1%nat).\nProof.\n  intros. unfold micmp in H.\n  destruct t1;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  unfold micmp_int, GV2val in H.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct TD.\n  Local Opaque Val.cmp Val.cmpu Val.cmpu_int.\n  destruct cond5; inv H; unfold gv_chunks_match_typ, vm_matches_typ, val2GV;\n    simpl; constructor; try solve [\n      auto |\n      split; try solve [auto | apply Val.cmp_has_Mint0 | \n                        apply Val.cmpu_has_Mint0 |\n                        apply Val.cmpu_int_has_Mint0]\n    ].\n  Transparent Val.cmp Val.cmpu Val.cmpu_int.\nQed.\n\nLemma mfcmp_matches_chunks : forall TD fcond5 fp gv1 gv2 gv,\n  mfcmp TD fcond5 fp gv1 gv2 = Some gv ->\n  gv_chunks_match_typ TD gv (typ_int 1%nat).\nProof.\n  intros. unfold mfcmp, GV2val in H.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_matches_chunks_helper; eauto].\n  destruct TD.\n  Local Opaque Val.cmpf.\n  destruct fp; try solve [\n    inv H | \n    destruct fcond5; inv H; unfold gv_chunks_match_typ, vm_matches_typ, val2GV;\n      try solve [\n      auto |\n      simpl; constructor; try solve [\n        auto |\n        simpl; split; try solve [auto | apply Val.cmpf_has_Mint0 |\n                                 simpl; split; try solve [\n                                   auto |\n                                   unfold Int.modulus, two_power_nat, shift_nat; simpl; omega\n                                ]\n                      ]\n        ]\n      ]\n    ].\n  Transparent Val.cmpf.\nQed.\n\nLemma vm_matches_typ__eq__snd: forall gv1 mc \n  (Hmatch : Forall2 vm_matches_typ gv1 mc), snd (split gv1) = mc.\nProof.\n  induction 1; simpl; subst; auto.\n    destruct x. inv H.\n    destruct (split l0). auto.\nQed.\n\nLemma vm_matches_typ__gv_has_chunk: forall gv1 mc \n  (Hmatch : Forall2 vm_matches_typ gv1 mc), gv_has_chunk gv1.\nProof.\n  unfold gv_has_chunk.\n  induction 1; simpl; subst; auto.\n    destruct x. inv H. constructor; auto.\nQed.\n\nLemma vm_matches_typ__sizeMC_eq_sizeGenericValue: forall gvs mcs \n  (Hmatch : Forall2 vm_matches_typ gvs mcs), \n  sizeMC mcs = sizeGenericValue gvs.\nProof.\n  induction 1; simpl; subst; auto.\n    destruct x. inv H.\n    simpl. congruence.\nQed.\n\n(* Inversion *)\nLemma BOP_inversion : forall TD lc gl b s v1 v2 gv,\n  BOP TD lc gl b s v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    mbop TD b s gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl b s v1 v2 gv HBOP.\n  unfold BOP in HBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HBOP].\n    remember (getOperandValue TD v2 lc gl) as ogv2.\n    destruct ogv2; try solve [inversion HBOP].\n      remember (mbop TD b s g g0) as R.\n      destruct R; inversion HBOP; subst.\n        exists g. exists g0. auto.\nQed.\n\nLemma FBOP_inversion : forall TD lc gl b fp v1 v2 gv,\n  FBOP TD lc gl b fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    mfbop TD b fp gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl b fp v1 v2 gv HFBOP.\n  unfold FBOP in HFBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFBOP].\n    remember (getOperandValue TD v2 lc gl) as ogv2.\n    destruct ogv2; try solve [inversion HFBOP].\n      remember (mfbop TD b fp g g0) as R.\n      destruct R; inversion HFBOP; subst.\n        exists g. exists g0. auto.\nQed.\n\nLemma getOperandPtr_inversion : forall TD lc gl v mptr,\n  getOperandPtr TD v lc gl = Some mptr ->\n  exists gv,\n    getOperandValue TD v lc gl = Some gv /\\\n    GV2ptr TD (getPointerSize TD) gv = Some mptr.\nProof.\n  intros TD lc gl v mptr HgetOperandPtr.\n  unfold getOperandPtr in HgetOperandPtr.\n  remember (getOperandValue TD v lc gl) as ogv.\n  destruct ogv; try solve [inversion HgetOperandPtr].\n    exists g. auto.\nQed.\n\nLemma getOperandInt_inversion : forall TD sz lc gl v n,\n  getOperandInt TD sz v lc gl = Some n ->\n  exists gv,\n    getOperandValue TD v lc gl = Some gv /\\\n    GV2int TD sz gv = Some n.\nProof.\n  intros TD sz0 lc gl v mptr HgetOperandInt.\n  unfold getOperandInt in HgetOperandInt.\n  remember (getOperandValue TD v lc gl) as ogv.\n  destruct ogv; try solve [inversion HgetOperandInt].\n    exists g. auto.\nQed.\n\nLemma CAST_inversion : forall TD lc gl op t1 v1 t2 gv,\n  CAST TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    mcast TD op t1 t2 gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HCAST.\n  unfold CAST in HCAST.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HCAST].\n    remember (mcast TD op t1 t2 g) as R.\n    destruct R; inversion HCAST; subst.\n      exists g. auto.\nQed.\n\nLemma TRUNC_inversion : forall TD lc gl op t1 v1 t2 gv,\n  TRUNC TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    mtrunc TD op t1 t2 gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HTRUNC.\n  unfold TRUNC in HTRUNC.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HTRUNC].\n    remember (mtrunc TD op t1 t2 g) as R.\n    destruct R; inversion HTRUNC; subst.\n      exists g. auto.\nQed.\n\nLemma EXT_inversion : forall TD lc gl op t1 v1 t2 gv,\n  EXT TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    mext TD op t1 t2 gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HEXT.\n  unfold EXT in HEXT.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HEXT].\n    remember (mext TD op t1 t2 g) as R.\n    destruct R; inversion HEXT; subst.\n      exists g. auto.\nQed.\n\nLemma ICMP_inversion : forall TD lc gl cond t v1 v2 gv,\n  ICMP TD lc gl cond t v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    micmp TD cond t gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl cond0 t v1 v2 gv HICMP.\n  unfold ICMP in HICMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HICMP].\n    remember (getOperandValue TD v2 lc gl) as ogv2.\n    destruct ogv2; try solve [inversion HICMP].\n      remember (micmp TD cond0 t g g0) as R.\n      destruct R; inversion HICMP; subst.\n        exists g. exists g0. auto.\nQed.\n\nLemma FCMP_inversion : forall TD lc gl cond fp v1 v2 gv,\n  FCMP TD lc gl cond fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    mfcmp TD cond fp gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl cond0 fp v1 v2 gv HFCMP.\n  unfold FCMP in HFCMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFCMP].\n    remember (getOperandValue TD v2 lc gl) as ogv2.\n    destruct ogv2; try solve [inversion HFCMP].\n      remember (mfcmp TD cond0 fp g g0) as R.\n      destruct R; inversion HFCMP; subst.\n        exists g. exists g0. auto.\nQed.\n\nLemma intValues2Nats_inversion : forall l0 lc gl TD ns0,\n  intValues2Nats TD l0 lc gl = Some ns0 ->\n  exists gvs0,\n    values2GVs TD l0 lc gl = Some gvs0 /\\\n    GVs2Nats TD gvs0 = Some ns0.\nProof.\n  induction l0; intros; simpl in *.\n    inversion H. exists nil. auto.\n\n    destruct a as [s v].\n    remember (getOperandValue TD v lc gl) as ogv.\n    destruct ogv; try solve [inversion H].\n    remember (GV2int TD Size.ThirtyTwo g) as on.\n    destruct on; try solve [inversion H].\n    remember (intValues2Nats TD l0 lc gl) as ons.\n    destruct ons; inversion H; subst.\n    symmetry in Heqons.\n    apply IHl0 in Heqons.\n    destruct Heqons as [gvs [J1 J2]].\n    exists (g::gvs).\n    rewrite J1.\n    split; auto.\n      simpl. rewrite J2. rewrite <- Heqon. auto.\nQed.\n\nLemma values2GVs_GVs2Nats__intValues2Nats : forall l0 lc gl TD gvs0,\n  values2GVs TD l0 lc gl = Some gvs0 ->\n  GVs2Nats TD gvs0 = intValues2Nats TD l0 lc gl.\nProof.\n  induction l0; intros lc gl TD gvs0 H; simpl in *.\n    inversion H. auto.\n\n    destruct a as [s v].\n    destruct (getOperandValue TD v lc gl); try solve [inversion H].\n      remember (values2GVs TD l0 lc gl)as ogv.\n      destruct ogv; inversion H; subst.\n        rewrite <- IHl0 with (gvs0:=l1); auto.\nQed.\n\n(* Properties of eqAL *)\nLemma const2GV_eqAL_aux :\n  (forall c gl1 gl2 TD, eqAL _ gl1 gl2 ->\n     _const2GV TD gl1 c = _const2GV TD gl2 c) /\\\n  (forall cs gl1 gl2 TD, eqAL _ gl1 gl2 ->\n    (forall t, _list_const_arr2GV TD gl1 t cs = _list_const_arr2GV TD gl2 t cs)\n    /\\\n    _list_const_struct2GV TD gl1 cs = _list_const_struct2GV TD gl2 cs).\nProof.\n  apply const_mutind; intros; simpl;\n  try solve [\n    auto |\n\n    apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H0;\n      destruct H0; auto |\n\n    apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H0;\n    destruct H0;\n    unfold _list_const_arr2GV in H0; rewrite H0; auto |\n\n    rewrite H; auto |\n\n    assert (J:=H1);\n    apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H1;\n    rewrite H1;\n    assert (J':=J);\n    apply H0 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J;\n    rewrite J; auto\n  ];\n  fold _list_const_struct2GV.\n\n  apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H0.\n  rewrite (proj2 H0). auto.\n\n  assert (J:=H1).\n  apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H1.\n  rewrite H1.\n  assert (J':=J). trivial.\n\n  assert (J:=H2).\n  apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H2.\n  rewrite H2.\n  assert (J':=J).\n  apply H0 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J.\n  rewrite J.\n  apply H1 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J'.\n  rewrite J'. auto.\n\n  assert (J:=H1).\n  apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H1.\n  rewrite H1. auto.\n\n  assert (J:=H2).\n  apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H2.\n  rewrite H2.\n  assert (J':=J).\n  apply H0 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J.\n  rewrite J. auto.\n\n  split.\n    intros.\n    assert (J:=H1);\n    apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H1;\n    rewrite H1;\n    assert (J':=J);\n    apply H0 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J.\n    destruct J. rewrite H2; auto.\n\n    assert (J:=H1);\n    apply H with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in H1;\n    rewrite H1;\n    assert (J':=J);\n    apply H0 with (TD:=TD)(gl1:=gl1)(gl2:=gl2) in J.\n    destruct J. rewrite H3; auto.\nQed.\n\nLemma const2GV_eqAL : forall c gl1 gl2 TD,\n  eqAL _ gl1 gl2 ->\n  const2GV TD gl1 c = const2GV TD gl2 c.\nProof.\n  intros. unfold const2GV.\n  destruct const2GV_eqAL_aux.\n  erewrite H0; eauto.\nQed.\n\nLemma getOperandValue_eqAL : forall lc1 gl lc2 v TD,\n  eqAL _ lc1 lc2 ->\n  getOperandValue TD v lc1 gl = getOperandValue TD v lc2 gl.\nProof.\n  intros lc1 gl lc2 v TD HeqAL.\n  unfold getOperandValue in *.\n  destruct v; auto.\nQed.\n\nLemma BOP_eqAL : forall lc1 gl lc2 bop0 sz0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  BOP TD lc1 gl bop0 sz0 v1 v2 = BOP TD lc2 gl bop0 sz0 v1 v2.\nProof.\n  intros lc1 gl lc2 bop0 sz0 v1 v2 TD HeqEnv.\n  unfold BOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FBOP_eqAL : forall lc1 gl lc2 fbop0 fp0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  FBOP TD lc1 gl fbop0 fp0 v1 v2 = FBOP TD lc2 gl fbop0 fp0 v1 v2.\nProof.\n  intros lc1 gl lc2 fbop0 fp0 v1 v2 TD HeqEnv.\n  unfold FBOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma getOperandPtr_eqAL : forall lc1 gl lc2 v TD,\n  eqAL _ lc1 lc2 ->\n  getOperandPtr TD v lc1 gl = getOperandPtr TD v lc2 gl.\nProof.\n  intros lc1 gl lc2 v TD HeqEnv.\n  unfold getOperandPtr in *.\n  erewrite getOperandValue_eqAL; eauto.\nQed.\n\nLemma getOperandInt_eqAL : forall lc1 gl lc2 sz v TD,\n  eqAL _ lc1 lc2 ->\n  getOperandInt TD sz v lc1 gl = getOperandInt TD sz v lc2 gl.\nProof.\n  intros lc1 gl lc2 sz0 v TD HeqAL.\n  unfold getOperandInt in *.\n  erewrite getOperandValue_eqAL; eauto.\nQed.\n\nLemma getOperandPtrInBits_eqAL : forall lc1 gl lc2 sz v TD,\n  eqAL _ lc1 lc2 ->\n  getOperandPtrInBits TD sz v lc1 gl = getOperandPtrInBits TD sz v lc2 gl.\nProof.\n  intros lc1 gl lc2 sz0 v TD HeqAL.\n  unfold getOperandPtrInBits in *.\n  erewrite getOperandValue_eqAL; eauto.\nQed.\n\nLemma CAST_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  CAST TD lc1 gl op t1 v1 t2 = CAST TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold CAST in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma TRUNC_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  TRUNC TD lc1 gl op t1 v1 t2 = TRUNC TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold TRUNC in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma EXT_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  EXT TD lc1 gl op t1 v1 t2 = EXT TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold EXT in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma ICMP_eqAL : forall lc1 gl lc2 cond t v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  ICMP TD lc1 gl cond t v1 v2 = ICMP TD lc2 gl cond t v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 t v1 v2 TD HeqAL.\n  unfold ICMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FCMP_eqAL : forall lc1 gl lc2 cond fp v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  FCMP TD lc1 gl cond fp v1 v2 = FCMP TD lc2 gl cond fp v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 fp v1 v2 TD HeqAL.\n  unfold FCMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma intValues2Nats_eqAL : forall l0 lc1 gl lc2 TD,\n  eqAL _ lc1 lc2 ->\n  intValues2Nats TD l0 lc1 gl = intValues2Nats TD l0 lc2 gl.\nProof.\n  induction l0; intros lc1 gl lc2 TD HeqAL; simpl; auto.\n    destruct a.\n    rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v); auto.\n    erewrite IHl0; eauto.\nQed.\n\nLemma values2GVs_eqAL : forall l0 lc1 gl lc2 TD,\n  eqAL _ lc1 lc2 ->\n  values2GVs TD l0 lc1 gl = values2GVs TD l0 lc2 gl.\nProof.\n  induction l0; intros lc1 gl lc2 TD HeqAL; simpl; auto.\n    destruct a.\n    rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v); auto.\n    erewrite IHl0; eauto.\nQed.\n\nLemma mload_aux__sizeGenericValue : forall M b mc ofs gv,\n  mload_aux M mc b ofs = Some gv ->\n  sizeMC mc = sizeGenericValue gv.\nProof.\n  induction mc; simpl; intros.\n    inv H. auto.\n\n    destruct (Mem.load a M b ofs); tinv H.\n    remember (mload_aux M mc b (ofs + size_chunk a)) as R.\n    destruct R; inv H.\n    simpl.\n    erewrite IHmc; eauto.\nQed.\n\nLemma mload_inv : forall Mem2 t align0 TD gvp2\n  (gv2 : GenericValue)\n  (H21 : mload TD Mem2 gvp2 t align0 = ret gv2),\n  exists b, exists ofs, exists m, exists mc,\n    gvp2 = (Vptr b ofs,m)::nil /\\ flatten_typ TD t = Some mc /\\\n    mload_aux Mem2 mc b (Int.signed 31 ofs) = Some gv2.\nProof.\n  intros.\n  unfold mload in H21.\n  remember (GV2ptr TD (getPointerSize TD) gvp2) as R.\n  destruct R; try solve [inversion H21].\n  destruct v; try solve [inversion H21].\n  unfold GV2ptr in HeqR.\n  destruct gvp2; try solve [inversion HeqR].\n  destruct p.\n  destruct v; try solve [inversion HeqR].\n  destruct gvp2; inv HeqR.\n  exists b0. exists i1. exists m.\n  destruct (flatten_typ TD t); inv H21.\n  eauto.\nQed.\n\nLemma free_inv : forall TD Mem0 gv Mem',\n  free TD Mem0 gv = ret Mem' ->\n  exists blk, exists ofs, exists hi, exists lo,\n    GV2ptr TD (getPointerSize TD) gv = Some (Vptr blk ofs) /\\\n    Int.signed 31 ofs = 0%Z /\\\n    (lo, hi) = Mem.bounds Mem0 blk /\\\n    Mem.free Mem0 blk lo hi = Some Mem'.\nProof.\n  intros TD Mem0 gv Mem' H0.\n  unfold free in H0.\n  destruct (GV2ptr TD (getPointerSize TD) gv); try solve [inversion H0; subst].\n  destruct v; try solve [inversion H0; subst].\n  destruct (Coqlib.zeq (Int.signed 31 i0) 0); try solve [inversion H0; subst].\n  remember (Mem.bounds Mem0 b) as R.\n  destruct R as [l h].\n  exists b. exists i0. rewrite e. rewrite <- HeqR. exists h. exists l.\n  repeat (split; auto).\nQed.\n\nLemma malloc_inv : forall TD Mem0 tsz gn align0 Mem' mb,\n  malloc TD Mem0 tsz gn align0 = ret (Mem', mb) ->\n  Mem.alloc Mem0 0\n        match GV2int TD Size.ThirtyTwo gn with\n          | Some n => (Size.to_Z tsz) * n\n          | None => 0\n        end = (Mem', mb).\nProof.\n  intros. inv H. auto.\nQed.\n\nLemma alloca_inv : forall TD Mem0 tsz gn align0 Mem' mb,\n  alloca TD Mem0 tsz gn align0 = ret (Mem', mb) ->\n  exists z, (GV2int TD Size.ThirtyTwo gn) = Some z /\\\n            let hi := (Size.to_Z tsz * z)%Z in\n            let (M', nb) := Mem.alloc Mem0 0 hi in\n            option_map (flip pair nb) (Mem.drop_perm M' nb 0 hi Writable) = ret (Mem', mb)\n.\nProof.\n  intros. unfold alloca in *.\n  destruct (GV2int TD Size.ThirtyTwo gn) eqn:T; simpl in *; subst; eauto.\n  inv H.\nQed.\n\nLemma store_inv : forall TD Mem0 gvp t gv align Mem',\n  mstore TD Mem0 gvp t gv align = Some Mem' ->\n  exists b, exists ofs, exists mc,\n    GV2ptr TD (getPointerSize TD) gvp = Some (Vptr b ofs) /\\\n    flatten_typ TD t = Some mc /\\\n    mstore_aux Mem0 mc gv b (Int.signed 31 ofs) = Some Mem'.\nProof.\n  intros TD Mem0 gvp t gv align Mem' H.\n  unfold mstore in H.\n  destruct (GV2ptr TD (getPointerSize TD) gvp); try solve [inversion H; subst].\n  destruct v; try solve [inversion H; subst].\n  exists b. exists i0.\n  destruct (flatten_typ TD t); inv H.\n  exists l0. split; auto.\nQed.\n\n Lemma mstore_inversion : forall Mem2 t align0 TD gvp2 Mem2'\n   (gv2 : GenericValue)\n   (H21 : mstore TD Mem2 gvp2 t gv2 align0 = ret Mem2'),\n  exists b, exists ofs, exists cm, exists mc,\n    gvp2 = (Vptr b ofs,cm)::nil /\\\n    flatten_typ TD t = Some mc /\\\n    mstore_aux Mem2 mc gv2 b (Int.signed 31 ofs) = ret Mem2'.\n Proof.\n  intros.\n  unfold mstore in H21.\n  remember (GV2ptr TD (getPointerSize TD) gvp2) as R.\n  destruct R; try solve [inversion H21].\n  destruct v; try solve [inversion H21].\n  unfold GV2ptr in HeqR.\n  destruct gvp2; try solve [inversion HeqR].\n  destruct p.\n  destruct v; try solve [inversion HeqR].\n  destruct gvp2; inv HeqR.\n  exists b0. exists i1. exists m.\n  destruct (flatten_typ TD t); inv H21.\n  exists l0. eauto.\nQed.\n\n(* Properties of sizeMC *)\nLemma sizeMC__app : forall mc1 mc2,\n  sizeMC (mc1 ++ mc2) = (sizeMC mc1 + sizeMC mc2)%nat.\nProof.\n  induction mc1; intros; simpl; auto.\n    rewrite IHmc1. omega.\nQed.\n\nLemma sizeMC__repeatMC : forall mc n,\n  sizeMC (repeatMC mc n) = (n * sizeMC mc)%nat.\nProof.\n  induction n; simpl; auto.\n    rewrite sizeMC__app. rewrite IHn. auto.\nQed.\n\nLemma sizeMC__uninitMCs : forall n, sizeMC (uninitMCs n) = n.\nProof.\n  induction n; simpl; auto.\nQed.\n\n(* Properties of initLocals *)\nLemma initLocals_spec : forall TD la gvs id1 lc,\n  In id1 (getArgsIDs la) ->\n  initLocals TD la gvs = Some lc ->\n  exists gv, lookupAL _ lc id1 = Some gv.\nProof.\n  unfold initLocals.\n  induction la; intros; simpl in *.\n    inversion H.\n\n    destruct a as [[t c] id0].\n    simpl in H.\n    destruct H as [H | H]; subst; simpl.\n      destruct gvs.\n        remember (_initializeFrameValues TD la nil nil) as R1.\n        destruct R1; tinv H0.\n        remember (gundef TD t) as R2.\n        destruct R2; inv H0.\n        exists (? g0 # t ?). apply lookupAL_updateAddAL_eq; auto.\n\n        remember (_initializeFrameValues TD la gvs nil) as R1.\n        destruct R1; tinv H0.\n        remember (fit_gv TD t g) as R2.\n        destruct R2; inv H0.\n        exists (? g1 # t ?). apply lookupAL_updateAddAL_eq; auto.\n\n      destruct (eq_atom_dec id0 id1); subst.\n        destruct gvs.\n          remember (_initializeFrameValues TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          exists (? g0 # t ?). apply lookupAL_updateAddAL_eq; auto.\n\n          remember (_initializeFrameValues TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          remember (fit_gv TD t g) as R2.\n          destruct R2; inv H0.\n          exists (? g1 # t ?). apply lookupAL_updateAddAL_eq; auto.\n\n        destruct gvs.\n          remember (_initializeFrameValues TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          exists gv. rewrite <- lookupAL_updateAddAL_neq; auto.\n\n          remember (_initializeFrameValues TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          remember (fit_gv TD t g) as R2.\n          destruct R2; inv H0.\n          exists gv. rewrite <- lookupAL_updateAddAL_neq; auto.\nQed.\n\n(* Properties of gundef *)\nLemma gundef_p1__total : forall TD, exists mp', gundef TD (typ_pointer (typ_int 1%nat)) = ret mp'.\nProof.\n  intros. unfold gundef. destruct TD. simpl. eauto.\nQed.\n\nLemma gundef_i1__total : forall TD, exists mp', gundef TD (typ_int 1%nat) = ret mp'.\nProof.\n  intros. unfold gundef. destruct TD. simpl. eauto.\nQed.\n\n(* Properties of typesize *)\nLemma mget_typsize : forall los nts gv1 o typ' gv'\n  (HeqR4 : ret gv' = mget (los, nts) gv1 o typ'),\n   exists sz1 : nat,\n     exists al0 : nat,\n       _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true typ' = ret (sz1, al0) /\\\n       Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz1) 8) = sizeGenericValue gv'.\nProof.\n  intros.\n  unfold mget in HeqR4.\n  remember (getTypeStoreSize (los, nts) typ') as R.\n  destruct R; tinv HeqR4.\n  simpl in HeqR4.\n  remember (splitGenericValue gv1 o) as R1.\n  destruct R1 as [[? gvr]|]; tinv HeqR4.\n  remember (splitGenericValue gvr (Z_of_nat n)) as R2.\n  destruct R2 as [[gvrl ?]|]; inv HeqR4.\n  destruct (gv_chunks_match_typb (los, nts) gvrl typ'); inv H0.\n  unfold getTypeStoreSize, getTypeSizeInBits, getTypeSizeInBits_and_Alignment,\n    getTypeSizeInBits_and_Alignment_for_namedts in HeqR.\n  remember (_getTypeSizeInBits_and_Alignment los\n               (_getTypeSizeInBits_and_Alignment_for_namedts los\n                  nts true) true typ') as R3.\n  destruct R3 as [[sz ?]|]; tinv HeqR.\n  exists sz. exists n0.\n  split; auto. inv HeqR.\n    symmetry in HeqR2.\n    apply splitGenericValue_spec in HeqR2.\n    destruct HeqR2 as [J1 J2].\n    rewrite J1.\n    erewrite Coqlib.Z_of_nat_eq; eauto.\nQed.\n\nLemma mset_typsize : forall los nts gv1 o t2 gv2 gv sz2 al2\n  (J3 : _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t2 = ret (sz2, al2))\n  (J4 : Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8) = sizeGenericValue gv2)\n  (HeqR4 : ret gv = mset (los, nts) gv1 o t2 gv2),\n  sizeGenericValue gv1 = sizeGenericValue gv.\nProof.\n  intros.\n  unfold mset in HeqR4.\n  remember (getTypeStoreSize (los, nts) t2) as R.\n  destruct R; tinv HeqR4.\n  simpl in HeqR4.\n  destruct (n =n= length gv2); tinv HeqR4.\n  remember (splitGenericValue gv1 o) as R1.\n  destruct R1 as [[? gvr]|]; tinv HeqR4.\n  remember (splitGenericValue gvr (Z_of_nat n)) as R2.\n  destruct R2 as [[gvrl ?]|]; inv HeqR4.\n  symmetry in HeqR2.\n  apply splitGenericValue_spec in HeqR2.\n  destruct HeqR2 as [J1 J2].\n  symmetry in HeqR1.\n  apply splitGenericValue_spec in HeqR1.\n  destruct HeqR1 as [J3' J4'].\n  rewrite <- J4'. rewrite <- J2.\n  destruct_if.\n  rewrite sizeGenericValue__app.\n  rewrite sizeGenericValue__app.\n  unfold getTypeStoreSize, getTypeSizeInBits, getTypeSizeInBits_and_Alignment,\n    getTypeSizeInBits_and_Alignment_for_namedts in HeqR.\n  rewrite J3 in HeqR.\n  inv HeqR.\n  rewrite Coqlib.Z_of_nat_eq in J1.\n  rewrite <- J1 in J4. rewrite J4. auto.\nQed.\n\nLemma feasible_typ_inv'' : forall TD t,\n  LLVMtd.feasible_typ TD t ->\n  exists ssz, exists asz,\n    getTypeStoreSize TD t = Some ssz /\\ getTypeAllocSize TD t = Some asz.\nProof.\n  intros TD t Hs.\n  apply feasible_typ_inv' in Hs.\n  destruct Hs as [sz [al [J1 J2]]].\n  unfold getTypeAllocSize, getTypeStoreSize, getTypeSizeInBits,\n    getABITypeAlignment, getAlignment.\n  rewrite J1. eauto.\nQed.\n\nLemma mcmp_typsize_helper : forall TD gv,\n  gundef TD (typ_int 1%nat) = ret gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat Size.One) 8) = sizeGenericValue gv.\nProof.\n  intros. destruct TD.\n  unfold gundef in H. simpl in H. inv H. simpl. auto.\nQed.\n\nLemma micmp_typsize : forall los nts cond5 t1 gv1 gv2 gv,\n  micmp (los,nts) cond5 t1 gv1 gv2 = Some gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat Size.One) 8) = sizeGenericValue gv.\nProof.\n  intros. unfold micmp in H.\n  destruct t1;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  unfold micmp_int, GV2val in H.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct p.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct p.\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct cond5; inv H; auto.\nQed.\n\nLemma mfcmp_typsize : forall los nts fcond5 fp gv1 gv2 gv,\n  mfcmp (los,nts) fcond5 fp gv1 gv2 = Some gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat Size.One) 8) = sizeGenericValue gv.\nProof.\n  intros. unfold mfcmp, GV2val in H.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct p.\n  destruct gv1;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct p.\n  destruct gv2;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct v;\n    try solve [inversion H | eapply mcmp_typsize_helper; eauto].\n  destruct fp; try solve [inv H | destruct fcond5; inv H; auto].\nQed.\n\n(* Properties of gv_lessdef *)\nLemma gv_lessdef_ref: forall gv, gv_lessdef gv gv.\nProof.\n  unfold gv_lessdef.\n  induction gv as [|[]]; auto.\nQed.\n    \n(* Properties of gv_has_chunk *)\nLemma gv_has_chunkb__gv_has_chunk: forall gv (Hchk: gv_has_chunkb gv), \n  gv_has_chunk gv.\nProof.\n  unfold gv_has_chunk.\n  induction gv as [|[]]; simpl; intros; auto.\n    apply andb_true_iff in Hchk.\n    destruct Hchk as [J1 J2].\n    constructor; auto using Val.has_chunkb__has_chunk.\nQed.\n\nEnd LLVMgv.", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/genericvalues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18649441371387307}}
{"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 Configuration.\nRequire Import Trace.\nRequire Import Behavior.\nRequire Import Single.\nRequire Import Mapping.\n\nSet Implicit Arguments.\n\nModule SemiReachable.\n  Section REACHABLE.\n\n    Variable (c0: Configuration.t).\n\n    Hypothesis CONFIG_CONSISTENT: forall tid lang st lc\n                                         (TID: IdentMap.find tid (Configuration.threads c0) = Some (existT _ lang st, lc)),\n        Local.promise_consistent lc.\n    Hypothesis CONFIG_WF: Configuration.wf c0.\n\n    Section TID.\n\n      Variable (tid: Ident.t).\n\n      Inductive semi_reachable lang (th: Thread.t lang): Prop :=\n      | semi_reachable_intro\n          c1 st1 lc1\n          (STEPS: rtc SConfiguration.all_machine_step c0 c1)\n          (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n          (TSTEPS: rtc (@Thread.all_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) th)\n          (CONSISTENT: Local.promise_consistent (Thread.local th))\n      .\n      Hint Constructors semi_reachable.\n\n      Inductive semi_reachable_state\n                (lang: language) (st: @Language.state _ lang): Prop :=\n      | semi_reachable_stateintro\n          lc sc mem\n          (REACHABLE: semi_reachable (Thread.mk _ st lc sc mem))\n        :\n          semi_reachable_state _ st\n      .\n      Hint Constructors semi_reachable_state.\n\n      Inductive step lang: forall (pf: bool) (e: ThreadEvent.t) (th0 th1: Thread.t lang), Prop :=\n      | step_intro\n          pf e th0 th1\n          (STEP: Thread.step pf e th0 th1)\n          (REACHABLE: semi_reachable_state lang (Thread.state th1))\n        :\n          step pf e th0 th1\n      .\n      Hint Constructors step.\n\n      Inductive opt_step lang: forall (e:ThreadEvent.t) (e1 e2:Thread.t lang), Prop :=\n      | step_none\n          e:\n          opt_step ThreadEvent.silent e e\n      | step_some\n          pf e e1 e2\n          (STEP: step pf e e1 e2):\n          opt_step e e1 e2\n      .\n      Hint Constructors opt_step.\n\n      Inductive step_allpf lang (e:ThreadEvent.t) (e1 e2:Thread.t lang): Prop :=\n      | step_nopf_intro\n          pf\n          (STEP: step pf e e1 e2)\n      .\n      Hint Constructors step_allpf.\n\n      Definition tau_step lang := tau (@step_allpf lang).\n\n      Inductive reserve_step lang (e1 e2:Thread.t lang): Prop :=\n      | reserve_step_intro\n          pf loc from to\n          (STEP: step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) e1 e2)\n      .\n      Hint Constructors reserve_step.\n\n      Inductive cancel_step lang (e1 e2:Thread.t lang): Prop :=\n      | cancel_step_intro\n          pf loc from to\n          (STEP: step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel) e1 e2)\n      .\n      Hint Constructors cancel_step.\n\n      Lemma step_reachable lang pf e (th0 th1: Thread.t lang)\n            (STEP: Thread.step pf e th0 th1)\n            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable th0)\n        :\n          (<<STEP: step pf e th0 th1>>) /\\\n          (<<REACHABLE: semi_reachable th1>>).\n      Proof.\n        inv REACHABLE.\n        assert (REACHABLE0: semi_reachable th1).\n        { econs; eauto. etrans; eauto. econs 2; [|refl]. econs; eauto. econs; eauto. }\n        splits; auto. econs; eauto. destruct th1. econs; eauto.\n      Qed.\n\n      Lemma opt_step_reachable lang e (th0 th1: Thread.t lang)\n            (STEP: Thread.opt_step e th0 th1)\n            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable th0)\n        :\n          (<<STEP: opt_step e th0 th1>>) /\\\n          (<<REACHABLE: semi_reachable th1>>).\n      Proof.\n        inv STEP.\n        - splits; auto.\n        - eapply step_reachable in STEP0; eauto. des. splits; eauto.\n      Qed.\n\n      Lemma tau_steps_reachable lang (th0 th1: Thread.t lang)\n            (STEPS: rtc (@Thread.tau_step _) th0 th1)\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            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable th0)\n        :\n          (<<STEP: rtc (@tau_step _) th0 th1>>) /\\\n          (<<REACHABLE: semi_reachable th1>>).\n      Proof.\n        revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.\n        inv H. inv TSTEP. exploit Thread.step_future; eauto. i. des.\n        hexploit PromiseConsistent.rtc_tau_step_promise_consistent; eauto. i.\n        hexploit step_reachable; eauto. i. des.\n        hexploit IHSTEPS; eauto. i. des. splits; eauto.\n        econs; eauto. econs; eauto.\n      Qed.\n\n      Lemma reserve_steps_reachable lang (th0 th1: Thread.t lang)\n            (STEPS: rtc (@Thread.reserve_step _) th0 th1)\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            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable th0)\n        :\n          (<<STEP: rtc (@reserve_step _) th0 th1>>) /\\\n          (<<REACHABLE: semi_reachable th1>>).\n      Proof.\n        revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.\n        inv H. exploit Thread.step_future; eauto. i. des.\n        hexploit PromiseConsistent.rtc_reserve_step_promise_consistent; eauto. i.\n        hexploit step_reachable; eauto. i. des.\n        hexploit IHSTEPS; eauto. i. des. splits; eauto.\n      Qed.\n\n      Lemma cancel_steps_reachable lang (th0 th1: Thread.t lang)\n            (STEPS: rtc (@Thread.cancel_step _) th0 th1)\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            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable th0)\n        :\n          (<<STEP: rtc (@cancel_step _) th0 th1>>) /\\\n          (<<REACHABLE: semi_reachable th1>>).\n      Proof.\n        revert LOCAL MEMORY SC CONSISTENT REACHABLE. induction STEPS; eauto. i.\n        inv H. exploit Thread.step_future; eauto. i. des.\n        hexploit PromiseConsistent.rtc_cancel_step_promise_consistent; eauto. i.\n        hexploit step_reachable; eauto. i. des.\n        hexploit IHSTEPS; eauto. i. des. splits; eauto.\n      Qed.\n\n      Definition consistent lang (e1:Thread.t lang): Prop :=\n        forall mem1 sc1\n               (CAP: Memory.cap (Thread.memory e1) mem1)\n               (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n          (exists e2 e3,\n              (<<STEPS: rtc (@tau_step lang) (Thread.mk _ (Thread.state e1) (Thread.local e1) sc1 mem1) e2>>) /\\\n              (<<FAILURE: step true ThreadEvent.failure e2 e3 >>)) \\/\n          (exists e2,\n              (<<STEPS: rtc (@tau_step lang) (Thread.mk _ (Thread.state e1) (Thread.local e1) sc1 mem1) e2>>) /\\\n              (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>))\n      .\n\n      Inductive configuration_step:\n        forall (e:ThreadEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n      | configuration_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 (@cancel_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n          (STEP: opt_step e e2 e3)\n          (RESERVES: rtc (@reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n          (CONSISTENT: e <> ThreadEvent.failure -> consistent (Thread.mk _ st4 lc4 sc4 memory4)):\n          configuration_step e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n      .\n      Hint Constructors configuration_step.\n\n      Lemma step_map_reachable lang pf e (th0 th1 fth0: Thread.t lang)\n            (STEP: Thread.step pf e th0 th1)\n            (THREAD: thread_map ident_map th0 fth0)\n            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable fth0)\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            (FLOCAL: Local.wf (Thread.local fth0) (Thread.memory fth0))\n            (FMEMORY: Memory.closed (Thread.memory fth0))\n            (FSC: Memory.closed_timemap (Thread.sc fth0) (Thread.memory fth0))\n        :\n          exists fpf fe fth1,\n            (<<STEP: Thread.step fpf fe fth0 fth1>>) /\\\n            (<<EVENT: tevent_map ident_map fe e>>) /\\\n            (<<THREAD: thread_map ident_map th1 fth1>>) /\\\n            (<<REACHABLE: semi_reachable fth1>>) /\\\n            (<<STEP: step pf e th0 th1>>)\n      .\n      Proof.\n        splits; auto.\n        inv THREAD. destruct th1. ss. hexploit step_map; ss.\n        { eapply ident_map_le. }\n        { eapply ident_map_bot. }\n        { eapply ident_map_eq. }\n        { instantiate (1:=fun _ => True). i. eapply ident_map_mappable_evt. }\n        { econs; eauto. econs; eauto. }\n        { ss. }\n        { eauto. }\n        { ss. }\n        { ss. }\n        { ss. }\n        { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n        { ss. }\n        i. des. inv STEP0.\n        assert (RECHABLE0: semi_reachable (Thread.mk _ state flc1 fsc1 fmem1)).\n        { inv REACHABLE.\n          econs; eauto. etrans; eauto. econs 2; [|refl]. econs; eauto. econs; eauto.\n          ss. inv LOCAL1. hexploit promise_consistent_map.\n          { eapply ident_map_le. }\n          { eapply ident_map_eq. }\n          { eapply TVIEW. }\n          { eapply PROMISES. }\n          { ss. }\n          i. eapply promise_consistent_mon; eauto. refl.\n        }\n        esplits; eauto. econs; eauto.\n        { eapply mapping_map_lt_collapsable_unwritable; eauto. eapply ident_map_lt. }\n      Qed.\n\n      Lemma tau_steps_map_reachable lang (th0 th1 fth0: Thread.t lang)\n            (STEPS: rtc (@Thread.tau_step _) th0 th1)\n            (THREAD: thread_map ident_map th0 fth0)\n            (CONSISTENT: Local.promise_consistent (Thread.local th1))\n            (REACHABLE: semi_reachable fth0)\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            (FLOCAL: Local.wf (Thread.local fth0) (Thread.memory fth0))\n            (FMEMORY: Memory.closed (Thread.memory fth0))\n            (FSC: Memory.closed_timemap (Thread.sc fth0) (Thread.memory fth0))\n        :\n          exists fth1,\n            (<<STEPS: rtc (@Thread.tau_step _) fth0 fth1>>) /\\\n            (<<THREAD: thread_map ident_map th1 fth1>>) /\\\n            (<<REACHABLE: semi_reachable fth1>>) /\\\n            (<<STEPS: rtc (@tau_step _) th0 th1>>)\n      .\n      Proof.\n        revert_until STEPS. revert fth0. induction STEPS; eauto.\n        { i. esplits; eauto. }\n        i. inv H. inv TSTEP. exploit Thread.step_future; eauto. i. des.\n        hexploit PromiseConsistent.rtc_tau_step_promise_consistent; eauto. i.\n        hexploit step_map_reachable; eauto. i. des.\n        exploit Thread.step_future; try apply STEP0; eauto. i. des.\n        hexploit IHSTEPS; eauto. i. des. exists fth2. splits; auto.\n        { eapply tevent_map_same_machine_event in EVENT0.\n          rewrite <- EVENT0 in EVENT.\n          econs 2; eauto. econs; eauto. econs; eauto.\n        }\n        { econs 2; eauto. econs; eauto. }\n      Qed.\n\n      Lemma consistent_reachable lang (th0: Thread.t lang)\n            (CONSISTENT: Thread.consistent th0)\n            (REACHABLE: semi_reachable th0)\n            (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n            (MEMORY: Memory.closed (Thread.memory th0))\n            (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n        :\n          consistent th0.\n      Proof.\n        ii.\n        assert (THREAD: thread_map ident_map (Thread.mk _ (Thread.state th0) (Thread.local th0) sc1 mem1) th0).\n        { destruct th0. ss. econs; eauto.\n          - eapply ident_map_local.\n          - econs.\n            + i. eapply Memory.cap_inv in GET; eauto. des; eauto.\n              right. exists to, from, msg, msg. splits; ss.\n              * eapply ident_map_message.\n              * refl.\n            + i. eapply Memory.cap_le in GET; eauto; [|refl].\n              left. exists fto, ffrom, fto, ffrom. splits; ss; try refl. i. econs; eauto.\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        assert (FLOCAL: Local.wf (Thread.local th0) mem1).\n        { eapply Local.cap_wf; eauto. }\n        assert (FMEMORY: Memory.closed mem1).\n        { eapply Memory.cap_closed; eauto. }\n        assert (FSC: Memory.closed_timemap sc1 mem1).\n        { eapply Memory.max_concrete_timemap_closed; eauto. }\n        exploit CONSISTENT; eauto. i. des.\n        { left. unfold Thread.steps_failure in *. des.\n          exploit Thread.rtc_tau_step_future; eauto. i. des. ss.\n          eapply tau_steps_map_reachable in STEPS; eauto.\n          { des. exploit Thread.rtc_tau_step_future; eauto. i. des.\n            eapply step_map_reachable in FAILURE0; eauto.\n            { des. esplits; eauto. }\n            { inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss. }\n          }\n          { inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss. }\n        }\n        { right. eapply tau_steps_map_reachable in STEPS; eauto.\n          { des. esplits; eauto. }\n          { eapply Local.bot_promise_consistent; eauto. }\n        }\n      Qed.\n\n      Lemma configuration_step_reachable c1 c2 e\n            (STEP: SConfiguration.step e tid c1 c2)\n            (REACHABLE: rtc SConfiguration.all_machine_step c0 c1)\n            (WF: Configuration.wf c1)\n        :\n          configuration_step e tid c1 c2.\n      Proof.\n        inv STEP.\n        exploit Thread.rtc_cancel_step_future; eauto; try eapply WF; eauto. i. des. ss.\n        exploit Thread.opt_step_future; eauto. i. des.\n        exploit Thread.rtc_reserve_step_future; eauto. i. des. ss.\n        assert ((<<CONSISTENT4: Local.promise_consistent lc4>>) /\\\n                (<<CONSISTENT3: Local.promise_consistent (Thread.local e3)>>)).\n        { destruct (classic (e = ThreadEvent.failure)).\n          - subst. inv STEP0. inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n            splits; eauto.\n            eapply PromiseConsistent.rtc_reserve_step_promise_consistent2 in RESERVES; eauto.\n          - specialize (CONSISTENT H).\n            eapply PromiseConsistent.consistent_promise_consistent in CONSISTENT; eauto.\n            splits; eauto.\n            eapply PromiseConsistent.rtc_reserve_step_promise_consistent; eauto.\n        }\n        des.\n        assert (CONSISTENT2: Local.promise_consistent (Thread.local e2)).\n        { inv STEP0; eauto.\n          eapply PromiseConsistent.step_promise_consistent; eauto. }\n        assert (CONSISTENT1: Local.promise_consistent lc1).\n        { eapply PromiseConsistent.rtc_cancel_step_promise_consistent in CANCELS; eauto. }\n        eapply cancel_steps_reachable in CANCELS; eauto; try eapply WF; eauto. des.\n        eapply opt_step_reachable in STEP0; eauto. des.\n        eapply reserve_steps_reachable in RESERVES; eauto. des.\n        econs; eauto. i.\n        eapply consistent_reachable; eauto.\n      Qed.\n\n    End TID.\n\n    Section SIMCONFIG.\n\n      Inductive sim_state_rel\n                (tid: Ident.t)\n                (lang_src lang_tgt: language)\n                (r: Language.state lang_src -> Language.state lang_tgt -> Prop) :=\n      | sim_state_rel_intro\n          (STEP: forall st_src0 st_tgt0 st_tgt1 e\n                        (REL: r st_src0 st_tgt0)\n                        (REACHABLE: semi_reachable_state tid lang_tgt st_tgt1)\n                        (STEP: Language.step lang_tgt e st_tgt0 st_tgt1),\n              exists st_src1,\n                (<<STEP: Language.step lang_src e st_src0 st_src1>>) /\\\n                (<<REL: r st_src1 st_tgt1>>))\n          (TERMINAL: forall st_src st_tgt\n                            (REL: r st_src st_tgt)\n                            (REACHABLE: semi_reachable_state tid lang_tgt st_tgt)\n                            (TERMINAL: Language.is_terminal lang_tgt st_tgt),\n              Language.is_terminal lang_src st_src)\n      .\n      Hint Constructors sim_state_rel.\n\n      Lemma eq_sim_state_rel tid lang\n        :\n          sim_state_rel tid lang lang eq.\n      Proof.\n        econs; i; clarify. eauto.\n      Qed.\n\n      Variable (r: forall (tid: Ident.t) (lang_src lang_tgt: language),\n                   Language.state lang_src -> Language.state lang_tgt -> Prop).\n      Hypothesis (REL: forall tid lang_src lang_tgt, sim_state_rel tid lang_src lang_tgt (r tid lang_src lang_tgt)).\n\n      Inductive sim_statelocal tid:\n        forall (lcst_src lcst_tgt: (sigT (@Language.state _)) * Local.t), Prop :=\n      | sim_statelocal_intro\n          lang_src lang_tgt st_src st_tgt lc\n          (REL: r tid lang_src lang_tgt st_src st_tgt)\n        :\n          sim_statelocal tid (existT _ lang_src st_src, lc) (existT _ lang_tgt st_tgt, lc)\n      .\n      Hint Constructors sim_statelocal.\n\n      Inductive sim_thread tid lang_src lang_tgt: forall (th_src: Thread.t lang_src) (th_tgt: Thread.t lang_tgt), Prop :=\n      | sim_thread_intro\n          st_src st_tgt lc sc mem\n          (REL: r tid lang_src lang_tgt st_src st_tgt)\n        :\n          sim_thread tid (Thread.mk _ st_src lc sc mem) (Thread.mk _ st_tgt lc sc mem)\n      .\n      Hint Constructors sim_thread.\n\n      Inductive sim_configuration:\n        forall (c_src c_tgt: Configuration.t), Prop :=\n      | sim_configuration_intro\n          ths_src ths_tgt sc mem\n          (THS: forall tid,\n              option_rel\n                (sim_statelocal tid)\n                (IdentMap.find tid ths_src)\n                (IdentMap.find tid ths_tgt))\n        :\n          sim_configuration (Configuration.mk ths_src sc mem) (Configuration.mk ths_tgt sc mem)\n      .\n      Hint Constructors sim_configuration.\n\n      Lemma sim_thread_step tid lang_src lang_tgt\n            (th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt) pf e\n            (STEP: step tid pf e th_tgt0 th_tgt1)\n            (SIM: sim_thread tid th_src0 th_tgt0)\n        :\n          exists th_src1,\n            (<<STEP: Thread.step pf e th_src0 th_src1>>) /\\\n            (<<SIM: sim_thread tid th_src1 th_tgt1>>).\n      Proof.\n        inv SIM. inv STEP; ss. inv STEP0.\n        { inv STEP. ss. esplits; eauto. econs 1; eauto. econs; eauto. }\n        inv STEP. specialize (REL tid lang_src lang_tgt). inv REL.\n        exploit STEP; eauto. i. des.\n        esplits; eauto.\n      Qed.\n\n      Lemma sim_thread_opt_step tid lang_src lang_tgt\n            (th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt) e\n            (STEP: opt_step tid e th_tgt0 th_tgt1)\n            (SIM: sim_thread tid th_src0 th_tgt0)\n        :\n          exists th_src1,\n            (<<STEP: Thread.opt_step e th_src0 th_src1>>) /\\\n            (<<SIM: sim_thread tid th_src1 th_tgt1>>).\n      Proof.\n        inv STEP.\n        - esplits; eauto. econs 1.\n        - eapply sim_thread_step in SIM; eauto. des. esplits; eauto. econs 2; eauto.\n      Qed.\n\n      Lemma sim_thread_reserve_steps tid lang_src lang_tgt\n            (th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)\n            (STEPS: rtc (@reserve_step tid _) th_tgt0 th_tgt1)\n            (SIM: sim_thread tid th_src0 th_tgt0)\n        :\n          exists th_src1,\n            (<<STEPS: rtc (@Thread.reserve_step _) th_src0 th_src1>>) /\\\n            (<<SIM: sim_thread tid th_src1 th_tgt1>>).\n      Proof.\n        ginduction STEPS; eauto. i. inv H.\n        eapply sim_thread_step in STEP; eauto. des.\n        exploit IHSTEPS; eauto. i. des.\n        exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto.\n      Qed.\n\n      Lemma sim_thread_cancel_steps tid lang_src lang_tgt\n            (th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)\n            (STEPS: rtc (@cancel_step tid _) th_tgt0 th_tgt1)\n            (SIM: sim_thread tid th_src0 th_tgt0)\n        :\n          exists th_src1,\n            (<<STEPS: rtc (@Thread.cancel_step _) th_src0 th_src1>>) /\\\n            (<<SIM: sim_thread tid th_src1 th_tgt1>>).\n      Proof.\n        ginduction STEPS; eauto. i. inv H.\n        eapply sim_thread_step in STEP; eauto. des.\n        exploit IHSTEPS; eauto. i. des.\n        exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto.\n      Qed.\n\n      Lemma sim_thread_tau_steps tid lang_src lang_tgt\n            (th_src0: Thread.t lang_src) (th_tgt0 th_tgt1: Thread.t lang_tgt)\n            (STEPS: rtc (@tau_step tid _) th_tgt0 th_tgt1)\n            (SIM: sim_thread tid th_src0 th_tgt0)\n        :\n          exists th_src1,\n            (<<STEPS: rtc (@Thread.tau_step _) th_src0 th_src1>>) /\\\n            (<<SIM: sim_thread tid th_src1 th_tgt1>>).\n      Proof.\n        ginduction STEPS; eauto. i. inv H. inv TSTEP.\n        eapply sim_thread_step in STEP; eauto. des.\n        exploit IHSTEPS; eauto. i. des.\n        exists th_src2; eauto. esplits; eauto. econs; eauto. econs; eauto. econs; eauto.\n      Qed.\n\n      Lemma sim_thread_consistent tid lang_src lang_tgt\n            (th_src: Thread.t lang_src) (th_tgt: Thread.t lang_tgt)\n            (CONSISTENT: consistent tid th_tgt)\n            (SIM: sim_thread tid th_src th_tgt)\n        :\n          Thread.consistent th_src.\n      Proof.\n        inv SIM. ii; ss.\n        assert (SIM: sim_thread tid (Thread.mk _ st_src lc sc1 mem1) (Thread.mk _ st_tgt lc sc1 mem1)).\n        { econs; eauto. }\n        exploit CONSISTENT; eauto. i; ss. des.\n        - left. eapply sim_thread_tau_steps in STEPS; eauto. des.\n          eapply sim_thread_step in FAILURE; eauto. des.\n          unfold Thread.steps_failure. esplits; eauto.\n        - right. eapply sim_thread_tau_steps in STEPS; eauto. des.\n          esplits; eauto. inv SIM0. ss.\n      Qed.\n\n      Lemma sim_configuration_step c_src0 c_tgt0 c_tgt1 e tid\n            (WF: Configuration.wf c_tgt0)\n            (STEP: SConfiguration.step e tid c_tgt0 c_tgt1)\n            (SIM: sim_configuration c_src0 c_tgt0)\n            (REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt0)\n        :\n          exists c_src1,\n            (<<STEP: SConfiguration.step e tid c_src0 c_src1>>) /\\\n            (<<SIM: sim_configuration c_src1 c_tgt1>>).\n      Proof.\n        eapply configuration_step_reachable in STEP; eauto.\n        inv STEP. inv SIM. ss.\n        dup THS. specialize (THS0 tid). setoid_rewrite TID in THS0.\n        unfold option_rel in THS0. des_ifs. destruct p as [[lang_src st_src] lc_tgt].\n        inv THS0. eapply inj_pair2 in H4. clarify. eapply inj_pair2 in H0. clarify.\n        assert (SIM: sim_thread tid (Thread.mk _ st_src lc1 sc mem) (Thread.mk _ st1 lc1 sc mem)) by eauto.\n        eapply sim_thread_cancel_steps in CANCELS; eauto. des.\n        eapply sim_thread_opt_step in STEP0; eauto. des.\n        eapply sim_thread_reserve_steps in RESERVES; eauto. des. destruct th_src2.\n        esplits.\n        { econs; s.\n          - eauto.\n          - eapply STEPS.\n          - eapply STEP.\n          - eapply STEPS0.\n          - i. eapply sim_thread_consistent; eauto.\n        }\n        { inv SIM2. ss. econs; eauto. i.\n          repeat erewrite IdentMap.gsspec. des_ifs.\n        }\n      Qed.\n\n      Lemma steps_configuration_local_consistent c1\n            (REACHABLE: rtc SConfiguration.all_machine_step c0 c1)\n            tid lang st lc\n            (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st, lc))\n        :\n          Local.promise_consistent lc.\n      Proof.\n        eapply Operators_Properties.clos_rt_rt1n_iff in REACHABLE.\n        eapply Operators_Properties.clos_rt_rtn1_iff in REACHABLE.\n        revert tid lang st lc TID. induction REACHABLE; eauto.\n        i. inv H. inv STEP. assert (WF0: Configuration.wf y).\n        { eapply Operators_Properties.clos_rt_rtn1_iff in REACHABLE.\n          eapply Operators_Properties.clos_rt_rt1n_iff in REACHABLE.\n          eapply SConfiguration.all_machine_steps_future; eauto. }\n        exploit SConfiguration.step_future; eauto. i. des.\n        inv STEP0. ss.\n        erewrite IdentMap.gsspec in TID. des_ifs.\n        { eapply inj_pair2 in H0. clarify.\n          destruct (classic (e0 = ThreadEvent.failure)).\n          { inv STEP; ss. inv STEP0; inv STEP. inv LOCAL. inv LOCAL0.\n            eapply PromiseConsistent.rtc_reserve_step_promise_consistent2 in RESERVES; eauto.\n          }\n          { hexploit PromiseConsistent.consistent_promise_consistent; eauto; try apply WF2; eauto.\n            ss. inv WF2. ss. eapply WF; eauto.\n            erewrite IdentMap.gss. eauto.\n          }\n        }\n        { eapply IHREACHABLE; eauto. }\n      Qed.\n\n      Lemma sim_configuration_terminal c_src c_tgt\n            (TERMINAL: Configuration.is_terminal c_tgt)\n            (SIM: sim_configuration c_src c_tgt)\n            (REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt)\n        :\n          Configuration.is_terminal c_src.\n      Proof.\n        ii. inv SIM. ss.\n        specialize (THS tid). setoid_rewrite FIND in THS.\n        unfold option_rel in THS. des_ifs. destruct p as [[lang_tgt st_tgt] lc_tgt].\n        inv THS. eapply inj_pair2 in H4. clarify. eapply inj_pair2 in H0. clarify.\n        exploit TERMINAL; eauto. i. des.\n        specialize (REL tid lang lang_tgt). inv REL.\n        exploit TERMINAL0; eauto.\n        econs; eauto. econs; eauto. ss.\n        hexploit steps_configuration_local_consistent.\n        { eapply REACHABLE. }\n        { ss. eauto. }\n        { eauto. }\n      Qed.\n\n      Lemma sim_configuration_behavior c_src c_tgt\n            (WF: Configuration.wf c_tgt)\n            (SIM: sim_configuration c_src c_tgt)\n            (REACHABLE: rtc SConfiguration.all_machine_step c0 c_tgt)\n        :\n          behaviors SConfiguration.machine_step c_tgt <1= behaviors SConfiguration.machine_step c_src.\n      Proof.\n        intros beh BEH. ginduction BEH; eauto.\n        - i. econs 1. eapply sim_configuration_terminal; eauto.\n        - i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.\n          eapply sim_configuration_step in STEP1; eauto. des. econs 2.\n          + rewrite <- H0. econs; eauto.\n          + eapply IHBEH; eauto. etrans; eauto.\n        - i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.\n          eapply sim_configuration_step in STEP1; eauto. des. econs 3.\n          + rewrite <- H0. econs; eauto.\n        - i. dup STEP. inv STEP0. exploit SConfiguration.step_future; eauto. i. des.\n          eapply sim_configuration_step in STEP1; eauto. des. econs 4.\n          + rewrite <- H0. econs; eauto.\n          + eapply IHBEH; eauto. etrans; eauto.\n      Qed.\n    End SIMCONFIG.\n  End REACHABLE.\n\n  Theorem unreachable_code_transformation syn_src syn_tgt\n          (r: forall (tid: Ident.t) (lang_src lang_tgt: language),\n              Language.state lang_src -> Language.state lang_tgt -> Prop)\n          (REL: forall tid lang_src lang_tgt, sim_state_rel (Configuration.init syn_tgt) tid lang_src lang_tgt (r tid lang_src lang_tgt))\n          (INIT: sim_configuration r (Configuration.init syn_src) (Configuration.init syn_tgt))\n    :\n      behaviors SConfiguration.machine_step (Configuration.init syn_tgt)\n      <1=\n      behaviors SConfiguration.machine_step (Configuration.init syn_src).\n  Proof.\n    eapply sim_configuration_behavior; eauto.\n    - i. ss. unfold Threads.init in *. rewrite IdentMap.Facts.map_o in TID.\n      unfold option_map in *. des_ifs. ii. ss. erewrite Memory.bot_get in *. ss.\n    - eapply Configuration.init_wf.\n    - eapply Configuration.init_wf.\n  Qed.\nEnd SemiReachable.\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/SemiReachable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.18635878294358035}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromises.\nRequire Import Mapping.\nRequire Import Pred.\nRequire Import Trace.\n\nSet Implicit Arguments.\n\n\nDefinition pf_consistent lang (e:Thread.t lang): Prop :=\n  forall mem1 (CAP: Memory.cap (Thread.memory e) mem1),\n  exists e2,\n    (<<STEPS: rtc (tau (Thread.step true)) (Thread.mk _ (Thread.state e) (Thread.local e) (Thread.sc e) mem1) e2>>) /\\\n    (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>).\n\nDefinition pf_consistent_or_failure lang (e:Thread.t lang): Prop :=\n  forall mem1 (CAP: Memory.cap (Thread.memory e) mem1),\n  exists e2,\n    (<<STEPS: rtc (tau (Thread.step true)) (Thread.mk _ (Thread.state e) (Thread.local e) (Thread.sc e) mem1) e2>>) /\\\n    ((exists e e3,\n         (<<STEP_FAILURE: Thread.step true e e2 e3 >>) /\\\n         (<<EVENT_FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure>>)) \\/\n     (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>)).\n\nLemma promise_step_is_racy\n      lc1 mem1 loc from to msg lc2 mem2 kind\n      loc' to' ord\n      (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n      (RACE: Local.is_racy lc2 mem2 loc' to' ord):\n  Local.is_racy lc1 mem1 loc' to' ord.\nProof.\n  destruct lc1 as [tview1 promises1]. inv STEP. ss.\n  inv RACE. ss. inv PROMISE; ss.\n  { revert GET. erewrite Memory.add_o; eauto.\n    revert GETP. erewrite Memory.add_o; eauto.\n    condtac; ss; eauto.\n  }\n  { revert GET. erewrite Memory.split_o; eauto.\n    revert GETP. erewrite Memory.split_o; eauto.\n    repeat (condtac; ss); eauto.\n  }\n  { revert GET. erewrite Memory.lower_o; eauto.\n    revert GETP. erewrite Memory.lower_o; eauto.\n    condtac; ss; eauto.\n  }\n  { revert GET. erewrite Memory.remove_o; eauto.\n    revert GETP. erewrite Memory.remove_o; eauto.\n    condtac; ss; eauto.\n  }\nQed.\n\nLemma rtc_union_step_nonpf_failure\n      lang e1 e e2 e2'\n      (STEP: rtc (union (@Thread.step lang false)) e1 e2)\n      (FAILURE: Thread.step true e e2 e2')\n      (EVENT: ThreadEvent.get_machine_event e = MachineEvent.failure)\n  :\n    exists e1',\n      Thread.step true e e1 e1'.\nProof.\n  ginduction STEP; eauto.\n  i. exploit IHSTEP; eauto. intros x0. des.\n  exists (Thread.mk _ (Thread.state e1') (Thread.local x) (Thread.sc x) (Thread.memory x)).\n  econs 2; eauto.\n    inv H. inv USTEP. inv STEP0. ss.\n  inv x0; inv STEP0; ss. inv LOCAL0; ss.\n  - inv LOCAL1; ss.\n    econs; eauto. econs; eauto. econs; eauto; ss.\n    eapply promise_step_promise_consistent; eauto.\n  - inv LOCAL1; ss.\n    econs; eauto. econs; eauto. econs; eauto; ss.\n    + eapply promise_step_is_racy; eauto.\n    + eapply promise_step_promise_consistent; eauto.\n  - econs; eauto. econs; eauto.\n    inv LOCAL1; ss; eauto using promise_step_is_racy, promise_step_promise_consistent.\nQed.\n\nLemma consistent_pf_consistent lang (e:Thread.t lang)\n      (WF: Local.wf (Thread.local e) (Thread.memory e))\n      (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n      (MEM: Memory.closed (Thread.memory e))\n      (CONSISTENT: Thread.consistent e)\n  :\n    (<<CONSISTENT: pf_consistent e>>) \\/ (<<FAILURE: Thread.steps_failure e>>).\nProof.\n  destruct (classic (Thread.steps_failure e)) as [|NFAILURE]; auto.\n  left. ii. exploit CONSISTENT; eauto. i. des.\n  - exfalso. red in FAILURE. des.\n    exploit cap_failure_current_steps; eauto.\n    red. esplits; eauto.\n  - exploit tau_steps_pf_tau_steps; eauto; ss.\n    { ii. rewrite PROMISES, Memory.bot_get in *.  congr. }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.cap_closed_timemap; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    i. des.\n    exploit rtc_union_step_nonpf_bot; [|eauto|].\n    { eapply rtc_implies; [|eauto]. apply tau_union. }\n    i. subst. esplits; eauto.\nQed.\n\nLemma consistent_pf_consistent_or_failure lang (e:Thread.t lang)\n      (WF: Local.wf (Thread.local e) (Thread.memory e))\n      (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n      (MEM: Memory.closed (Thread.memory e))\n      (CONSISTENT: Thread.consistent e)\n  :\n    pf_consistent_or_failure e.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des.\n  - inv FAILURE. des.\n    hexploit tau_steps_pf_tau_steps; eauto; ss.\n    { inv STEP_FAILURE; inv STEP; ss.\n      inv LOCAL; ss; inv LOCAL0; ss.\n    }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.cap_closed_timemap; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    i. des.\n    exploit rtc_union_step_nonpf_failure.\n    { eapply rtc_implies; [|eauto]. apply tau_union. }\n    { eauto. }\n    { eauto. }\n    i. des.\n    esplits; eauto.\n  - exploit tau_steps_pf_tau_steps; eauto; ss.\n    { ii. rewrite PROMISES, Memory.bot_get in *.  congr. }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.cap_closed_timemap; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    i. des.\n    exploit rtc_union_step_nonpf_bot; [|eauto|].\n    { eapply rtc_implies; [|eauto]. apply tau_union. }\n    i. subst. esplits; eauto.\nQed.\n\nDefinition no_sc_consistent lang (e:Thread.t lang): Prop :=\n  forall mem1 (CAP: Memory.cap (Thread.memory e) mem1),\n  exists e2,\n    (<<STEPS: rtc (tau (@pred_step no_sc _)) (Thread.mk _ (Thread.state e) (Thread.local e) (Thread.sc e) mem1) e2>>) /\\\n    __guard__((exists e e3,\n                  (<<STEP_FAILURE: Thread.step true e e2 e3 >>) /\\\n                  (<<EVENT_FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure>>)) \\/\n              (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>)).\n\nLemma consistent_no_sc_consistent lang (e:Thread.t lang)\n      (WF: Local.wf (Thread.local e) (Thread.memory e))\n      (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n      (MEM: Memory.closed (Thread.memory e))\n      (CONSISTENT: Thread.consistent e)\n  :\n  no_sc_consistent e.\nProof.\n  eapply consistent_pf_consistent_or_failure in CONSISTENT; eauto.\n  ii. exploit CONSISTENT; eauto. intros [e2 [STEPS FINAL]].\n  guardH FINAL. des.\n  eapply rtc_implies in STEPS; cycle 1.\n  { instantiate (1:= tau (@pred_step (fun _ => True)  _)).\n    i. inv H. econs; eauto. econs; eauto. econs; eauto.\n  }\n  eapply (@hold_or_not _ no_sc) in STEPS. des.\n  { esplits.\n    { eapply rtc_implies; [|eapply HOLD].\n      i. inv H. inv TSTEP. des. econs; eauto. econs; eauto.\n    }\n    { eauto. }\n  }\n  { esplits.\n    { eapply rtc_implies; [|eapply STEPS0].\n      i. inv H. inv TSTEP. des. econs; eauto. econs; eauto.\n    }\n    right. inv STEP. inv STEP0; inv STEP; ss. inv LOCAL; ss.\n    { inv LOCAL0. eapply PROMISES.\n      eapply NNPP in BREAKQ. destruct ordw; ss.\n    }\n    { inv LOCAL0. eapply PROMISES. auto. }\n  }\nQed.\n\nDefinition no_sc_trace_consistent lang (e:Thread.t lang): Prop :=\n  forall mem1 (CAP: Memory.cap (Thread.memory e) mem1),\n  exists tr0 tr1 e2,\n    (<<STEPS: Trace.steps (tr0++tr1) (Thread.mk _ (Thread.state e) (Thread.local e) (Thread.sc e) mem1) e2>>) /\\\n    (<<NOSC: List.Forall (fun '(_, e) => no_sc e) (tr0++tr1)>>) /\\\n    (<<SILENT: List.Forall (fun '(_, e) => ThreadEvent.get_machine_event e = MachineEvent.silent) tr0>>) /\\\n    (<<TRACE: __guard__(((<<NIL: tr1 = []>>) /\\ (<<PROMISES: Local.promises (Thread.local e2) = Memory.bot>>)) \\/ (exists lc e, (<<EVENT: tr1 = [(lc, e)]>>) /\\ (<<FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure>>)))>>).\n\nLemma consistent_no_sc_trace_consistent lang (e:Thread.t lang)\n      (WF: Local.wf (Thread.local e) (Thread.memory e))\n      (SC: Memory.closed_timemap (Thread.sc e) (Thread.memory e))\n      (MEM: Memory.closed (Thread.memory e))\n      (CONSISTENT: Thread.consistent e)\n  :\n  no_sc_trace_consistent e.\nProof.\n  eapply consistent_no_sc_consistent in CONSISTENT; eauto.\n  ii. exploit CONSISTENT; eauto. intros x. des.\n  eapply pred_steps_trace_steps in STEPS. des. red in x0. des.\n  { exists tr, [(Thread.local e2, e0)]. esplits; eauto.\n    { eapply Trace.plus_step_steps; eauto. }\n    { eapply List.Forall_app. split.\n      { eapply List.Forall_impl; eauto. i.\n        destruct a. ss. des. auto.\n      }\n      { econs; eauto. destruct e0; ss. }\n    }\n    { eapply List.Forall_impl; eauto. i.\n      destruct a. ss. des. auto.\n    }\n    { right. esplits; eauto. }\n  }\n  { eexists tr, []. rewrite List.app_nil_r. esplits; eauto.\n    { eapply List.Forall_impl; eauto. i.\n      destruct a. ss. des. auto.\n    }\n    { eapply List.Forall_impl; eauto. i.\n      destruct a. ss. des. auto.\n    }\n    { left. esplits; eauto. }\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/PFConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.18621982605630719}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.IL Bedrock.Memory Coq.Strings.String Bedrock.sep.Locals Coq.Lists.List.\n\nDefinition upd_option vs x value :=\n  match x with\n    | None => vs\n    | Some s => Locals.upd vs s value\n  end.\n\nRequire Import Platform.Cito.FuncCore.\nExport FuncCore.\nRecord InternalFuncSpec :=\n  {\n    Fun : FuncCore;\n    NoDupArgVars : NoDup (ArgVars Fun)\n  }.\n\nCoercion Fun : InternalFuncSpec >-> FuncCore.\n\nRequire Import Platform.Cito.Syntax Platform.Cito.SemanticsExpr.\nRequire Import Platform.Cito.GLabel.\nRequire Import Platform.Cito.WordMap.\nRequire Import Platform.Cito.AxSpec.\nExport AxSpec.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Definition Heap := WordMap.t ADTValue.\n\n  Definition State := (vals * Heap)%type.\n\n  Notation Value := (@Value ADTValue).\n  Notation AxiomaticSpec := (@AxiomaticSpec ADTValue).\n  Arguments SCA {ADTValue} _.\n  Arguments ADT {ADTValue} _.\n\n  Inductive Callee := \n  | Foreign : AxiomaticSpec -> Callee\n  | Internal : InternalFuncSpec -> Callee.\n\n  Definition word_adt_match (heap : Heap) (p : W * Value) :=\n    let word := fst p in\n    let in_ := snd p in\n    match in_ with\n      | SCA w => word = w\n      | ADT a => WordMap.find word heap = Some a\n    end.\n\n  Definition disjoint_ptrs (pairs : list (W * Value)) := \n    let pairs := filter (fun p => is_adt (snd p)) pairs in\n    NoDup (List.map fst pairs).\n\n  Definition good_inputs heap pairs :=\n    Forall (word_adt_match heap) pairs /\\\n    disjoint_ptrs pairs.\n\n  Record ArgTriple :=\n    {\n      Word : W;\n      ADTIn : Value;\n      ADTOut : option ADTValue\n    }.\n\n  Definition store_out (heap : Heap) t :=\n    match ADTIn t, ADTOut t with \n      | SCA _, _ => heap\n      | ADT _, None => WordMap.remove (Word t) heap\n      | ADT _, Some a => WordMap.add (Word t) a heap\n    end.\n\n  Definition decide_ret addr (ret : Value) :=\n    match ret with\n      | SCA w => (w, None)\n      | ADT a => (addr, Some a)\n    end.\n\n  Definition separated heap ret_w (ret_a : option ADTValue) :=\n    ret_a = None \\/ ~ @WordMap.In ADTValue ret_w heap.\n\n  Definition heap_upd_option m k (v : option ADTValue) :=\n    match v with\n      | Some x => WordMap.add k x m\n      | None => m\n    end.\n\n  (* Semantics *)\n\n  Section Env.\n\n    Variable env : (glabel -> option W) * (W -> option Callee).\n\n    Inductive RunsTo : Stmt -> State -> State -> Prop :=\n    | RunsToSkip : forall v, RunsTo Syntax.Skip v v\n    | RunsToSeq :\n        forall a b v v' v'',\n          RunsTo a v v' ->\n          RunsTo b v' v'' ->\n          RunsTo (Syntax.Seq a b) v v''\n    | RunsToIfTrue :\n        forall cond t f v v',\n          wneb (eval (fst v) cond) $0 = true ->\n          RunsTo t v v' ->\n          RunsTo (Syntax.If cond t f) v v'\n    | RunsToIfFalse :\n        forall cond t f v v',\n          wneb (eval (fst v) cond) $0 = false ->\n          RunsTo f v v' ->\n          RunsTo (Syntax.If cond t f) v v'\n    | RunsToWhileTrue :\n        forall cond body v v' v'',\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = true ->\n          RunsTo body v v' ->\n          RunsTo loop v' v'' ->\n          RunsTo loop v v''\n    | RunsToWhileFalse :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = false ->\n          RunsTo loop v v\n    | RunsToCallInternal :\n        forall var f args v spec vs_callee vs_callee' heap',\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Internal spec) ->\n          map (Locals.sel vs_callee) (ArgVars spec) = map (eval vs) args ->\n          RunsTo (Body spec) (vs_callee, heap) (vs_callee', heap') ->\n          let vs := upd_option vs var (Locals.sel vs_callee' (RetVar spec)) in\n          let heap := heap' in\n          RunsTo (Syntax.Call var f args) v (vs, heap)\n    | RunsToCallForeign :\n        forall var f args v spec triples addr ret heap',\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Foreign spec) ->\n          map (eval vs) args = map Word triples ->\n          good_inputs heap (map (fun x => (Word x, ADTIn x)) triples) ->\n          PreCond spec (map ADTIn triples) ->\n          PostCond spec (map (fun x => (ADTIn x, ADTOut x)) triples) ret ->\n          let heap := fold_left store_out triples heap in\n          let t := decide_ret addr ret in\n          let ret_w := fst t in\n          let ret_a := snd t in\n          separated heap ret_w ret_a ->\n          let heap := heap_upd_option heap ret_w ret_a in\n          let vs := upd_option vs var ret_w in\n          WordMap.Equal heap' heap ->\n          RunsTo (Syntax.Call var f args) v (vs, heap')\n    | RunsToLabel :\n        forall x lbl v w,\n          fst env lbl = Some w ->\n          RunsTo (Syntax.Label x lbl) v (Locals.upd (fst v) x w, snd v)\n    | RunsToAssign :\n        forall x e v,\n          let vs := fst v in\n          RunsTo (Syntax.Assign x e) v (Locals.upd vs x (eval vs e), snd v).\n\n    CoInductive Safe : Stmt -> State -> Prop :=\n    | SafeSkip :\n        forall v, Safe Syntax.Skip v\n    | SafeSeq :\n        forall a b v,\n          Safe a v ->\n          (forall v', RunsTo a v v' -> Safe b v') ->\n          Safe (Syntax.Seq a b) v\n    | SafeIf :\n        forall cond t f v,\n          let b := wneb (eval (fst v) cond) $0 in\n          b = true /\\ Safe t v \\/ b = false /\\ Safe f v ->\n          Safe (Syntax.If cond t f) v\n    | SafeWhileTrue :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = true ->\n          Safe body v ->\n          (forall v', RunsTo body v v' -> Safe loop v') ->\n          Safe loop v\n    | SafeWhileFalse :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = false ->\n          Safe loop v\n    | SafeCallInternal :\n        forall var f args v spec,\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Internal spec) ->\n          length (ArgVars spec) = length args ->\n          (forall vs_arg,\n             map (Locals.sel vs_arg) (ArgVars spec) = map (eval vs) args\n             -> Safe (Body spec) (vs_arg, heap)) ->\n          Safe (Syntax.Call var f args) v\n    | SafeCallForeign :\n        forall var f args v spec pairs,\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Foreign spec) ->\n          map (eval vs) args = map fst pairs ->\n          good_inputs heap pairs ->\n          PreCond spec (map snd pairs) ->\n          Safe (Syntax.Call var f args) v\n    | SafeLabel :\n        forall x lbl v,\n          fst env lbl <> None ->\n          Safe (Syntax.Label x lbl) v\n    | SafeAssign :\n        forall x e v,\n          Safe (Syntax.Assign x e) v.\n\n    Section Safe_coind.\n      Variable R : Stmt -> State -> Prop.\n\n      Hypothesis SeqCase : forall a b v, R (Syntax.Seq a b) v -> R a v /\\ forall v', RunsTo a v v' -> R b v'.\n\n      Hypothesis IfCase : forall cond t f v, R (Syntax.If cond t f) v -> (wneb (eval (fst v) cond) $0 = true /\\ R t v) \\/ (wneb (eval (fst v) cond) $0 = false /\\ R f v).\n\n      Hypothesis WhileCase :\n        forall cond body v,\n          let loop := Syntax.While cond body in\n          R loop v ->\n          (wneb (eval (fst v) cond) $0 = true /\\ R body v /\\ (forall v', RunsTo body v v' -> R loop v')) \\/\n          (wneb (eval (fst v) cond) $0 = false).\n\n      Hypothesis CallCase : forall var f args v,\n        R (Syntax.Call var f args) v\n        -> (exists spec, let vs := fst v in\n          let heap := snd v in\n            let fs := snd env in\n              fs (eval vs f) = Some (Internal spec) /\\\n              length (ArgVars spec) = length args /\\\n              (forall vs_arg,\n                map (Locals.sel vs_arg) (ArgVars spec) = map (eval vs) args\n                -> R (Body spec) (vs_arg, heap)))\n        \\/ (exists spec, exists pairs, let vs := fst v in\n          let heap := snd v in\n            let fs := snd env in\n              fs (eval vs f) = Some (Foreign spec) /\\\n              map (eval vs) args = map fst pairs /\\\n              good_inputs heap pairs /\\\n              PreCond spec (map snd pairs)).\n\n      Hypothesis LabelCase : forall x lbl v,\n        R (Syntax.Label x lbl) v\n        -> fst env lbl <> None.\n\n      Hint Constructors Safe.\n\n      Ltac openhyp :=\n        repeat match goal with\n                 | H : _ /\\ _ |- _  => destruct H\n                 | H : _ \\/ _ |- _ => destruct H\n                 | H : exists x, _ |- _ => destruct H\n               end.\n\n      Ltac break_pair :=\n        match goal with\n          V : (_ * _)%type |- _ => destruct V\n        end.\n\n      Theorem Safe_coind : forall c v, R c v -> Safe c v.\n        cofix; unfold State; intros; break_pair; destruct c.\n\n        eauto.\n\n        eapply SeqCase in H; openhyp; eauto.\n\n        eapply IfCase in H; openhyp; eauto.\n\n        eapply WhileCase in H; openhyp; eauto.\n\n        eapply CallCase in H; openhyp; simpl in *; intuition eauto.\n\n        eapply LabelCase in H; openhyp; eauto.\n\n        eauto.\n      Qed.\n\n    End Safe_coind.\n\n  End Env.\n\nEnd ADTValue.\n\nRequire Import Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Definition RunsTo := @RunsTo ADTValue.\n\n  Definition Safe := @Safe ADTValue.\n\n  Definition Heap := @Heap ADTValue.\n\n  Definition State := @State ADTValue.\n\n  Definition ArgIn := @Value ADTValue.\n\n  Definition ArgOut := option ADTValue.\n\n  Definition Ret := @Value ADTValue.\n\n  Definition ForeignFuncSpec := @AxiomaticSpec ADTValue.\n\n  Definition Callee := @Callee ADTValue.\n\n  Definition ArgTriple := @ArgTriple ADTValue.\n\n  Definition word_adt_match := @word_adt_match ADTValue.\n\n  Definition is_adt := @is_adt ADTValue.\n\n  Definition disjoint_ptrs := @disjoint_ptrs ADTValue.\n\n  Definition good_inputs := @good_inputs ADTValue.\n\n  Definition store_out := @store_out ADTValue.\n\n  Definition decide_ret := @decide_ret ADTValue.\n\n  Definition separated := @separated ADTValue.\n\n  Definition heap_upd_option := @heap_upd_option ADTValue.\n\n  Definition Foreign := @Foreign ADTValue.\n\n  Definition Internal := @Internal ADTValue.\n\n  (* some shorthands for heap operations *)\n  Require Import Coq.FSets.FMapFacts.\n  Module Import P := Properties WordMap.\n  Import F WordMap.\n\n  Definition elt := ADTValue.\n\n  Implicit Types m h : Heap.\n  Implicit Types x y z k p w : key.\n  Implicit Types e v a : elt.\n  Implicit Types ls : list (key * elt).\n\n  Definition heap_sel h p := find p h.\n\n  Definition heap_mem := @In elt.\n\n  Definition heap_upd h p v := add p v h.\n\n  Definition heap_remove h p := remove p h.\n\n  Definition heap_empty := @empty elt.\n\n  Definition heap_merge := @update elt.\n\n  Definition heap_elements := @elements elt.\n\n  Definition heap_diff := @diff elt.\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/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.1862198117550688}}
{"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.reptype_lemmas.\nRequire Import floyd.aggregate_type.\nRequire Import floyd.sublist.\n\nSection PROJ_REPTYPE.\n\nContext {cs: compspecs}.\n\nDefinition proj_gfield_reptype (t: type) (gf: gfield) (v: reptype t): reptype (gfield_type t gf) :=\n  match t, gf return (REPTYPE t -> reptype (gfield_type t gf))\n  with\n  | Tarray t0 hi a, ArraySubsc i => fun v => Znth i v (default_val _)\n  | Tstruct id _, StructField i => fun v => proj_struct i (co_members (get_co id)) v (default_val _)\n  | Tunion id _, UnionField i => fun v => proj_union i (co_members (get_co id)) v (default_val _)\n  | _, _ => fun _ => default_val _\n  end (unfold_reptype v).\n\nFixpoint proj_reptype (t: type) (gfs: list gfield) (v: reptype t) : reptype (nested_field_type t gfs) :=\n  let res :=\n  match gfs as gfs'\n    return reptype (match gfs' with\n                    | nil => t\n                    | gf :: gfs0 => gfield_type (nested_field_type t gfs0) gf\n                    end)\n  with\n  | nil => v\n  | gf :: gfs0 => proj_gfield_reptype _ gf (proj_reptype t gfs0 v)\n  end\n  in eq_rect_r reptype res (nested_field_type_ind t gfs).\n\nEnd PROJ_REPTYPE.\n\n", "meta": {"author": "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/proj_reptype_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.18615862445564657}}
{"text": "(******************************************************************************)\n(** * Compilation correctness from the S_IMM memory model to the ARMv8.3 model *)\n(******************************************************************************)\n\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import Arm.\nRequire Import imm_bob.\nRequire Import imm_s_ppo.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import imm_ppo.\nRequire Import imm_hb.\nRequire Import imm.\nRequire Import immToARMhelper.\nRequire Import imm_s_hb_hb.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection immToARM.\n\nVariable G : execution.\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\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 \"'deps'\" := G.(deps).\nNotation \"'rmw_dep'\" := G.(rmw_dep).\n\nNotation \"'fre'\" := G.(fre).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'coe'\" := G.(coe).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'fri'\" := G.(fri).\nNotation \"'coi'\" := G.(coi).\nNotation \"'fr'\" := G.(fr).\nNotation \"'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 \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex \u2229\u2081 (fun a => is_true (is_xacq lab a))).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\n\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\nNotation \"'detour'\" := G.(detour).\nNotation \"'bob'\" := G.(bob).\n\n(* imm_s *)\nNotation \"'s_sw'\" := G.(imm_s_hb.sw).\nNotation \"'s_release'\" := G.(imm_s_hb.release).\nNotation \"'s_rs'\" := G.(imm_s_hb.rs).\nNotation \"'s_hb'\" := G.(imm_s_hb.hb).\nNotation \"'s_ppo'\" := G.(imm_s_ppo.ppo).\nNotation \"'s_psc_f'\" := G.(imm_s.psc_f).\nNotation \"'s_psc_base'\" := G.(imm_s.psc_base).\nNotation \"'s_ar_int'\" := G.(imm_s_ppo.ar_int).\n\n(* imm *)\nNotation \"'sw'\" := G.(imm_hb.sw).\nNotation \"'release'\" := G.(imm_hb.release).\nNotation \"'rs'\" := G.(imm_hb.rs).\nNotation \"'hb'\" := G.(imm_hb.hb).\nNotation \"'ppo'\" := G.(imm_ppo.ppo).\nNotation \"'psc'\" := G.(imm.psc).\nNotation \"'psc_f'\" := G.(imm.psc_f).\nNotation \"'psc_base'\" := G.(imm.psc_base).\nNotation \"'ar_int'\" := G.(imm_ppo.ar_int).\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\n(* arm *)\nNotation \"'obs'\" := G.(obs).\nNotation \"'obs''\" := G.(obs').\nNotation \"'aob'\" := G.(aob).\nNotation \"'boba'\" := G.(Arm.bob).\nNotation \"'boba''\" := G.(bob').\nNotation \"'dob'\" := G.(dob).\n\nNotation \"'L'\" := (W \u2229\u2081 (fun a => is_true (is_rel lab a))).\nNotation \"'Q'\" := (R \u2229\u2081 (fun a => is_true (is_acq lab a))).\nNotation \"'A'\" := (R \u2229\u2081 (fun a => is_true (is_sc  lab a))).\n\nNotation \"'F^ld'\" := (F \u2229\u2081 (fun a => is_true (is_acq lab a))).\nNotation \"'F^sy'\" := (F \u2229\u2081 (fun a => is_true (is_rel lab a))).\n\nHypothesis RMW_DEPS : rmw \u2286 ctrl \u222a data.\nHypothesis W_EX_ACQ_SB : \u2997W_ex_acq\u2998 \u2a3e sb \u2286 sb \u2a3e \u2997F^ld\u2998 \u2a3e  sb^?.\nHypothesis DEPS_RMW_SB : rmw_dep \u2a3e sb \u2286 ctrl.\nHypothesis REX_IN_RMW_CTRL : <|R_ex|> ;; sb \u2286 ctrl.\n\nHypothesis CON: ArmConsistent G.\n\nLemma WF : Wf G.\nProof using CON. apply CON. Qed.\nLemma COMP : complete G.\nProof using CON. apply CON. Qed.\nLemma SC_PER_LOC : sc_per_loc G.\nProof using CON. apply CON. Qed.\n\nLemma RMW_COI : rmw \u2a3e coi \u2286 obs' \u222a dob \u222a aob \u222a boba.\nProof using CON.\n  cdes CON. rewrite rmw_in_fri; auto.\n  rewrite fri_coi; auto. rewrite fri_in_fr. \n  unfold Arm.obs'. eauto with hahn.\nQed.\n\nLemma R_ex_fail_sb_in_ctrl : \u2997R_ex \\\u2081 dom_rel rmw\u2998 \u2a3e sb \u2286 ctrl.\nProof using REX_IN_RMW_CTRL.\n  rewrite <- REX_IN_RMW_CTRL.\n  basic_solver.\nQed.\n\nLemma s_ppo_in_dob : s_ppo \u2286 dob\u207a.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n  unfold imm_s_ppo.ppo.\n  rewrite REX_IN_RMW_CTRL.\n  arewrite (data \u222a ctrl \u222a addr \u2a3e sb^? \u222a rfi \u222a rmw \u222a rmw_dep \u2a3e sb^? \u222a ctrl \u2286\n            data \u222a ctrl \u222a addr \u2a3e sb^? \u222a rfi \u222a rmw_dep \u2a3e sb^?).\n  { rewrite RMW_DEPS. unionL; eauto with hahn. }\n  rewrite path_union, !seq_union_l, !seq_union_r. unionL.\n  { apply ppo_in_dob_helper; auto. }\n  assert ((data \u222a ctrl \u222a addr \u2a3e sb^? \u222a rfi)\uff0a \u2286 sb^?) as AA.\n  { rewrite WF.(data_in_sb), WF.(ctrl_in_sb), WF.(addr_in_sb).\n    arewrite (rfi \u2286 sb).\n    generalize (@sb_trans G). ins. relsf. }\n  rewrite AA at 2.\n  rewrite ct_begin, !seqA.\n  rewrite AA at 2.\n  arewrite (sb^? \u2a3e (sb^? \u2a3e rmw_dep \u2a3e sb^?)\uff0a \u2a3e sb^? \u2286 sb^?).\n  { rewrite WF.(rmw_dep_in_sb). generalize (@sb_trans G). ins. relsf. }\n  arewrite (rmw_dep \u2a3e sb^? \u2a3e \u2997W\u2998 \u2286 rmw_dep \u2a3e sb \u2a3e \u2997W\u2998).\n  { rewrite (dom_r WF.(wf_rmw_depD)) at 1. rewrite R_ex_in_R. type_solver. }\n  sin_rewrite DEPS_RMW_SB.\n  arewrite (ctrl \u2286 data \u222a ctrl \u222a addr \u2a3e sb^? \u222a rfi) at 2.\n  seq_rewrite <- ct_end.\n  apply ppo_in_dob_helper; auto.\nQed.\n\nLemma s_ppo_in_ord : s_ppo \u2286 (obs\u207a \u2229 sb \u222a dob \u222a aob \u222a boba' \u222a sb \u2a3e \u2997F^ld\u2998)\u207a.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n  rewrite s_ppo_in_dob. apply clos_trans_mori. eauto with hahn. \nQed.\n\nLemma s_ar_int_in_ord : \u2997R\u2998 \u2a3e s_ar_int\u207a \u2a3e \u2997W\u2998 \u2286 (obs \u222a dob \u222a aob \u222a boba')\u207a.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n  unfold imm_s_ppo.ar_int.\n  transitivity (\u2997R\u2998 \u2a3e  ((obs\u207a\u2229 sb) \u222a dob \u222a aob \u222a boba' \u222a sb \u2a3e \u2997F^ld\u2998)\u207a \u2a3e \u2997W\u2998).\n  2: { rewrite path_union.\n       relsf; unionL.\n       { arewrite_id \u2997R\u2998; arewrite_id \u2997W\u2998.\n         rels.\n         arewrite (obs\u207a \u2229 sb \u2286 obs\u207a).\n         apply inclusion_t_t2.\n         apply_unionL_once.\n         apply_unionL_once.\n         apply_unionL_once.\n         { apply inclusion_t_t. basic_solver. }\n         all: rewrite <- ct_step; basic_solver. }\n       rewrite (dob_in_sb WF) at 1 2.\n       rewrite (aob_in_sb WF) at 1 2.\n       rewrite (bob'_in_sb WF) at 1 2.\n       arewrite (obs\u207a \u2229 sb \u2286 sb).\n       rewrite ct_begin.\n       arewrite_id \u2997F^ld\u2998 at 2.\n       generalize (@sb_trans G); ins; relsf.\n       arewrite (\u2997F^ld\u2998 \u2a3e sb^? \u2a3e \u2997W\u2998 \u2286 \u2997F^ld\u2998 \u2a3e sb) by type_solver.\n       unfold Arm.bob', Arm.bob.\n       rewrite <- ct_step. basic_solver 21. }\n  arewrite (detour \u2286 detour \u2229 sb).\n  rewrite W_ex_acq_sb_in_boba1; auto.\n  rewrite bob_in_boba; auto.\n  rewrite detour_in_obs; auto.\n  hahn_frame.\n  apply inclusion_t_t2.\n  apply_unionL_once.\n  2: { rewrite <- ct_step. unfold Arm.aob. basic_solver 12. }\n  apply_unionL_once.\n  2: { apply inclusion_t_t; basic_solver 12. }\n  apply_unionL_once.\n  2: by unfolder; ins; econs; eauto.\n  apply_unionL_once.\n  { rewrite <- ct_step; rewrite <- ct_step; unfold Arm.obs; ie_unfolder; basic_solver 12. }\n  apply s_ppo_in_ord.\nQed.\n\nLemma C_EXT_helper: imm_s.acyc_ext G (\u2997F\u2229\u2081Sc\u2998 \u2a3e s_hb \u2a3e eco \u2a3e s_hb \u2a3e \u2997F\u2229\u2081Sc\u2998).\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n  apply (s_acyc_ext_psc_helper WF).\n  rewrite s_ar_int_in_ord.\n  arewrite (rfe \u2286 (obs \u222a dob \u222a aob \u222a boba')\u207a ).\n  { unfold Arm.obs; rewrite <- ct_step; basic_solver 12. }\n  arewrite (imm_s.psc G \u2286 imm.psc G).\n  { unfold imm_s.psc, imm.psc. by rewrite s_hb_in_hb. }\n  rewrite psc_in_ord; auto.\n  relsf; red; relsf.\n  apply (external_alt_bob' WF CON).\nQed.\n\nLemma C_SC : acyclic (imm_s.psc_f G \u222a imm_s.psc_base G).\nProof using CON RMW_DEPS W_EX_ACQ_SB.\n  unfold imm_s.psc_f, imm_s.psc_base, imm_s.scb.\n  rewrite s_hb_in_hb. \n  apply immToARMhelper.C_SC; auto.\nQed.\n\nLemma IMM_s_psc_consistent : exists sc, imm_psc_consistent G sc.\nProof using CON DEPS_RMW_SB REX_IN_RMW_CTRL RMW_DEPS W_EX_ACQ_SB.\n  edestruct (imm_s.s_acyc_ext_helper WF C_EXT_helper) as [sc HH]. desc.\n  exists sc. red. splits; eauto.\n  2: by apply C_SC.\n  red. splits; eauto; try apply CON.\n  red.\n  rewrite crE, seq_union_r, seq_id_r.\n  rewrite s_hb_in_hb. \n  apply irreflexive_union. split.\n  2: { apply COH; auto. } \n  rewrite hb_in_ord; auto. \n  apply irreflexive_union. split.\n  { by apply (@sb_irr G). }\n  apply (external_alt_bob' WF CON).\nQed.\n\nEnd immToARM.\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/hardware/imm_sToARM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.186158617427378}}
{"text": "Require Import List.\nRequire Import ListSet.\nRequire Import Coqlib.\nRequire Import Metatheory.\nRequire Import Maps.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import Iteration.\nRequire Import cfg.\nRequire Import dom_decl.\nRequire Import reach.\nRequire Import Dipaths.\nRequire Import dom_tree.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nImport LLVMsyntax.\nImport LLVMinfra.\n\n(* The file defines the specification of computing dominators. *)\n\nNotation \"x {+} y\" := (x :: y) (at level 0): dom.\nNotation \"x {<=} y\" := (incl x y) (at level 0): dom.\nNotation \"{}\" := nil (at level 0): dom.\nNotation \"x `in` y\" := (In x y) (at level 70): dom.\nLocal Open Scope dom.\n\n(* ALGDOM gives an abstract specification of algorithms that compute dominators. \n   First of all, sdom defines the signature of a dominance analysis algorithm: \n   given a function f and a label l1, (sdom f l1) returns the set of strict \n   dominators of l1 in f ; dom defines the set of dominators of l1 by adding l1 \n   into l1\u2019s strict dominators.\n\n   To make the interface simple, ALGDOM only requires the basic properties that \n   ensure that sdom is correct: it must be both sound and complete in terms of \n   the declarative definitions (Definition 2). Given the correctness of sdom, \n   the AlgDom_Properties module can \u2018lift\u2019 properties (conversion, transitivity, \n   acyclicity, ordering, etc.) from the declarative definitions to the \n   implementations of sdom and dom. \n\n   ALGDOM requires completeness directly. Soundness can be proven by two more \n   basic properties: entry_sound requires that the entry has no strict \n   dominators; successors_sound requires that if l1 is a successor of l2, then \n   l2\u2019s dominators must include l1\u2019s strict dominators. Given an algorithm that \n   establishes the two properties, AlgDom_Properties proves that the algorithm \n   is sound by induction over any path from the entry to l2. *)\nModule Type ALGDOM.\n\nParameter sdom : fdef -> atom -> set atom.\n\nAxiom dom_entrypoint : forall f l0 s0\n  (Hentry : getEntryBlock f = Some (l0, s0)),\n  sdom f l0 = {}.\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\nAxiom sdom_in_bound: forall fh bs l5, \n  (sdom (fdef_intro fh bs) l5) {<=} (bound_blocks bs).\n\nAxiom dom_successors : forall\n  (l3 : l) (l' : l) f\n  (contents3 contents': ListSet.set atom)\n  (Hinscs : l' `in` (successors f) !!! l3)\n  (Heqdefs3 : contents3 = sdom f l3)\n  (Heqdefs' : contents' = sdom f l'),\n  contents' {<=} (l3 {+} contents3).\n\nAxiom sdom_is_complete: forall (f:fdef)\n  (Hbinf: branchs_in_fdef f) \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: f |= l' >> l3),\n  l' `in` (sdom f l3).\n\nAxiom dom_unreachable: forall (f:fdef)\n  (Hbinf: branchs_in_fdef f) \n  (Hhasentry: getEntryBlock f <> None)\n  (l3 : l) s3\n  (HuniqF: uniqFdef f)\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hunreach: ~ f ~>* l3),\n  sdom f l3 = bound_fdef f.\n\nAxiom pres_sdom: forall \n  (ftrans: fdef -> fdef) \n  (btrans: block -> block)\n  (ftrans_spec: forall fh bs, \n    ftrans (fdef_intro fh bs) = fdef_intro fh (List.map btrans bs))\n  (btrans_eq_label: forall b, getBlockLabel b = getBlockLabel (btrans b))\n  (btrans_eq_tmn: forall b, \n    terminator_match (getTerminator b) (getTerminator (btrans b)))\n  (f : fdef) (l5 l0 : l),\n  ListSet.set_In l5 (sdom f l0) <->\n  ListSet.set_In l5 (sdom (ftrans f) l0).\n\nEnd ALGDOM.\n\nModule AlgDom_Properties(adom: ALGDOM).\n\nLemma entry_doms_others: forall (f:fdef) \n  (Hbinf: adom.branchs_in_fdef f) (Huniq: uniqFdef f) entry\n  (H: getEntryLabel f = Some entry),\n  (forall b (H0: b <> entry /\\ reachable f b),\n     entry `in` (adom.sdom f b)).\nProof.\n  intros.\n  assert (Hsdom: strict_domination f entry b).\n    apply DecDom.entry_doms_others; auto.\n  destruct H0 as [Hneq Hreach].\n  apply reachable__in_bound in Hreach; auto.\n  apply In_bound_fdef__blockInFdefB in Hreach.\n  destruct Hreach as [s HBinF].\n  apply getEntryLabel__getEntryBlock in H.\n  destruct H as [be [Hentry EQ]]; subst.\n  apply entryBlockInFdef in Hentry.\n  destruct be; simpl in *.\n  eapply adom.sdom_is_complete; eauto.\nQed.\n\nLemma in_bound_dom__in_bound_fdef: forall l' f l1\n  (Hin: l' `in` (adom.sdom f l1)),\n  l' `in` (bound_fdef f).\nProof.\n  intros. destruct f. eapply adom.sdom_in_bound; eauto.\nQed.\n\nSection sound.\n\nVariable f : fdef.\nHypothesis Hhasentry: getEntryBlock f <> None.\n\nLemma dom_is_sound : forall\n  (l3 : l) (l' : l) s3\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hin : l' `in` (l3 {+} (adom.sdom f l3))),\n  f |= l' >>= l3.\nProof.\n  unfold domination. autounfold with cfg.\n  intros. destruct f as [fh bs].\n  remember (getEntryBlock (fdef_intro fh bs)) as R.\n  destruct R; try congruence. clear Hhasentry.\n  destruct b as [l5 s5].\n  intros vl al Hreach.\n  generalize dependent s3.\n  remember (ACfg.vertexes (successors (fdef_intro fh bs))) as Vs.\n  remember (ACfg.arcs (successors (fdef_intro fh bs))) as As.\n  unfold ATree.elt, l in *.\n  remember (index l3) as v0.\n  remember (index l5) as v1.\n  generalize dependent bs.\n  generalize dependent l3.\n  generalize dependent l5.\n  induction Hreach; intros; subst.\n    inv Heqv0. symmetry in HeqR.\n    apply adom.dom_entrypoint in HeqR.\n    rewrite HeqR in Hin.\n    simpl in Hin. destruct Hin as [Hin | Hin]; tinv Hin; auto.\n\n    destruct y as [a0].\n    assert (exists ps0, exists cs0, exists tmn0,\n      blockInFdefB (a0, stmts_intro ps0 cs0 tmn0) (fdef_intro fh bs) /\\\n      In l3 (successors_terminator tmn0)) as J.\n      eapply successors__blockInFdefB; eauto.\n    destruct J as [ps0 [cs0 [tmn0 [HBinF'' Hinsucc]]]].\n    destruct (id_dec l' l3); subst; auto.\n    left.\n    assert (In l'\n      (a0 :: (adom.sdom (fdef_intro fh bs) a0))) as J.\n      assert (incl (adom.sdom (fdef_intro fh bs) l3)\n                   (a0 :: (adom.sdom (fdef_intro fh bs) a0))) as Hinc.\n        eapply adom.dom_successors; eauto.\n      simpl in Hin. destruct Hin; try congruence.\n      apply Hinc; auto.\n    eapply IHHreach in J; eauto 1.\n    simpl.\n    destruct J as [J | J]; subst; eauto.\nQed.\n\nLemma sdom_is_sound : forall\n  (l3 : l) (l' : l) s3\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hin : l' `in` (adom.sdom f l3)),\n  f |= l' >> l3.\nProof. \n  intros.\n  eapply dom_is_sound with (l':=l') in HBinF; simpl; eauto.\n  unfold strict_domination, domination in *.\n  remember (getEntryBlock f) as R.\n  destruct R; try congruence.\n  destruct b as [l0 ? ? ?].\n  intros vl al Hreach.\n  assert (Hw':=Hreach).\n  apply DWalk_to_dpath in Hreach; auto.\n  destruct Hreach as [vl0 [al0 Hp]].\n  destruct (id_dec l' l3); subst.\n  Case \"l'=l3\".\n    destruct (id_dec l3 l0); subst.\n    SCase \"l3=l0\".\n      symmetry in HeqR.\n      apply adom.dom_entrypoint in HeqR.\n      rewrite HeqR in Hin. inv Hin.\n    SCase \"l3<>l0\".   \n      inv Hp; try congruence.\n      destruct y as [a0].\n      assert (exists ps0, exists cs0, exists tmn0,\n        blockInFdefB (a0, stmts_intro ps0 cs0 tmn0) f /\\\n        In l3 (successors_terminator tmn0)) as J.\n        eapply successors__blockInFdefB; eauto.\n      destruct J as [ps0 [cs0 [tmn0 [HBinF' Hinsucc]]]].\n      assert (In l3 (a0 :: (adom.sdom f a0))) as J.\n        assert (incl (adom.sdom f l3) (a0 :: (adom.sdom f a0))) as Hinc.\n          destruct f. eapply adom.dom_successors; eauto.\n        simpl in Hin.\n        apply Hinc; auto.\n      eapply dom_is_sound in J; try solve [eauto 1 | congruence].\n      unfold domination in J.\n      rewrite <- HeqR in J.\n      assert (Hw:=H).\n      apply D_path_isa_walk in Hw.\n      apply J in Hw.\n      destruct Hw as [Hw | Hw]; subst; auto.\n        apply H4 in Hw. inv Hw; try congruence.\n        elimtype False. auto.\n  Case \"l'<>l3\".\n    apply HBinF in Hw'.\n    split; auto. destruct Hw'; subst; auto. congruence.\nQed. \n\nEnd sound.\n\nLemma sdom_isnt_refl : forall\n  f (l3 : l) (l' : l) s3\n  (Hreach : reachable f l3)\n  (HBinF : blockInFdefB (l3, s3) f = true)\n  (Hin : In l' (adom.sdom f l3)),\n  l' <> l3.\nProof. \n  intros.\n  eapply sdom_is_sound in Hin; eauto using reachable_has_entry.\n  unfold strict_domination, reachable in *.\n  autounfold with cfg in *.\n  destruct (getEntryBlock f) as [[]|]; try congruence.\n  destruct Hreach as [vl [al Hreach]].\n  apply Hin in Hreach. tauto.\nQed. \n\nDefinition getEntryBlock_inv f := forall\n  (l3 : l)\n  (l' : l)\n  (ps : phinodes)\n  (cs : cmds)\n  (tmn : terminator)\n  (HBinF : blockInFdefB (l3, stmts_intro ps cs tmn) f = true)\n  (Hsucc : In l' (successors_terminator tmn)) a s0\n  (H : getEntryBlock f = Some (a, s0)),\n  l' <> a.\n\nLemma sdom_acyclic: forall f\n  (HgetEntryBlock_inv : getEntryBlock_inv f)\n  l1 l2 s1 s2,\n  reachable f l2 ->\n  blockInFdefB (l1, s1) f = true ->\n  blockInFdefB (l2, s2) f = true ->\n  l1 `in` (adom.sdom f l2) ->\n  l2 `in` (adom.sdom f l1) ->\n  l1 <> l2 ->\n  False.\nProof.\n  intros.\n  assert (strict_domination f l1 l2) as Hdom12.\n    eapply sdom_is_sound; eauto using reachable_has_entry.\n  assert (strict_domination f l2 l1) as Hdom21.\n    eapply sdom_is_sound; eauto using reachable_has_entry.\n  eapply DecDom.dom_acyclic in Hdom12; eauto 1.\n  apply Hdom12. apply DecDom.sdom_dom; auto.\nQed.\n\nEnd AlgDom_Properties.\n\n(* The analysis that create trees must ensure that generated trees are\n   well-formed. *)\nModule Type ALGDOM_WITH_TREE.\n\nInclude Type ALGDOM.\n\nParameter create_dom_tree : fdef -> option (@DTree l).\n\nAxiom dtree_edge_iff_idom: forall (f:fdef)\n  (dt: @DTree l)\n  (Hcreate: create_dom_tree f = Some dt)\n  (le:l) (Hentry: getEntryLabel f = Some le)\n  (Hnopreds: (XATree.make_predecessors (successors f)) !!! le = nil)\n  (Hwfcfg: branchs_in_fdef f)\n  (Huniq: uniqFdef f),\n  forall p0 ch0,\n    is_dtree_edge eq_atom_dec dt p0 ch0 = true <-> \n      (imm_domination f p0 ch0 /\\ reachable f ch0).\n\nAxiom create_dom_tree__wf_dtree: forall (f:fdef)\n  (dt: @DTree l)\n  (Hcreate: create_dom_tree f = Some dt)\n  (le:l) (Hentry: getEntryLabel f = Some le)\n  (Hnopreds: (XATree.make_predecessors (successors f)) !!! le = nil)\n  (Hwfcfg: branchs_in_fdef f)\n  (Huniq: uniqFdef f),\n  ADProps.wf_dtree (successors f) le eq_atom_dec dt.\n\nEnd ALGDOM_WITH_TREE.\n\n", "meta": {"author": "vellvm", "repo": "vellvm-legacy", "sha": "e4c22d795974ba7c768c18b74fa098b0be2f86f7", "save_path": "github-repos/coq/vellvm-vellvm-legacy", "path": "github-repos/coq/vellvm-vellvm-legacy/vellvm-legacy-e4c22d795974ba7c768c18b74fa098b0be2f86f7/src/Vellvm/Dominators/dom_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.186158617427378}}
{"text": "(*! Language | Compilation from typed ASTs to lowered ASTs !*)\nRequire Import Koika.Syntax Koika.TypedSyntaxFunctions Koika.SyntaxMacros.\nRequire Export Koika.Common Koika.Environments.\nRequire Koika.SyntaxMacros Koika.TypedSyntax Koika.LoweredSyntax.\n\nImport PrimTyped CircuitSignatures.\n\nSection Lowering.\n  Context {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t: Type}.\n\n  Context {R: reg_t -> type}.\n  Context {Sigma: ext_fn_t -> ExternalSignature}.\n  Context {REnv: Env reg_t}.\n\n  Definition lower_R idx :=\n    type_sz (R idx).\n  Notation lR := lower_R.\n\n  Definition lower_Sigma fn :=\n    CSig_of_Sig (Sigma fn).\n  Notation lSigma := lower_Sigma.\n\n  Definition lower_r (r: REnv.(env_t) R)\n    : REnv.(env_t) (fun idx => bits (lR idx)) :=\n    map REnv (fun idx v => bits_of_value v) r.\n\n  Definition lower_sigma (sigma: forall f, Sig_denote (Sigma f))\n    : forall f, CSig_denote (lSigma f) :=\n    fun f => fun bs => bits_of_value (sigma f (value_of_bits bs)).\n\n  Notation typed_action := (TypedSyntax.action pos_t var_t fn_name_t R Sigma).\n  Notation low_action := (LoweredSyntax.action pos_t var_t lR lSigma).\n\n  Section Action.\n    Definition lower_unop {sig} (fn: fn1)\n               (a: low_action sig (type_sz (PrimSignatures.Sigma1 fn).(arg1Sig))):\n      low_action sig (type_sz (PrimSignatures.Sigma1 fn).(retSig)) :=\n      let lArg1 fn := low_action sig (type_sz (PrimSignatures.Sigma1 fn).(arg1Sig)) in\n      let lRet fn := low_action sig (type_sz (PrimSignatures.Sigma1 fn).(retSig)) in\n      match fn return lArg1 fn -> lRet fn with\n      | Display fn => fun a => LoweredSyntax.Unop (Lowered (DisplayBits fn)) a\n      | Conv tau fn => fun a =>\n        match fn return lArg1 (Conv tau fn) -> lRet (Conv tau fn) with\n        | Pack => fun a => a\n        | Unpack => fun a => a\n        | Ignore => fun a => LoweredSyntax.Unop (Lowered (IgnoreBits _)) a\n        end a\n      | Bits1 fn => fun a => LoweredSyntax.Unop fn a\n      | Struct1 fn sig f => fun a =>\n        match fn return lArg1 (Struct1 fn sig f) -> lRet (Struct1 fn sig f) with\n        | GetField => fun a =>\n          LoweredSyntax.Unop (GetFieldBits sig f) a\n        end a\n      | Array1 fn sig idx => fun a =>\n        match fn return lArg1 (Array1 fn sig idx) -> lRet (Array1 fn sig idx) with\n        | GetElement => fun a =>\n          LoweredSyntax.Unop (GetElementBits sig idx) a\n        end a\n      end a.\n\n    Definition lower_binop {sig} (fn: fn2)\n               (a1: low_action sig (type_sz (PrimSignatures.Sigma2 fn).(arg1Sig)))\n               (a2: low_action sig (type_sz (PrimSignatures.Sigma2 fn).(arg2Sig))):\n      low_action sig (type_sz (PrimSignatures.Sigma2 fn).(retSig)) :=\n      let lArg1 fn := low_action sig (type_sz (PrimSignatures.Sigma2 fn).(arg1Sig)) in\n      let lArg2 fn := low_action sig (type_sz (PrimSignatures.Sigma2 fn).(arg2Sig)) in\n      let lRet fn := low_action sig (type_sz (PrimSignatures.Sigma2 fn).(retSig)) in\n      match fn return lArg1 fn -> lArg2 fn -> lRet fn with\n      | Eq tau negate => fun a1 a2 => LoweredSyntax.Binop (EqBits (type_sz tau) negate) a1 a2\n      | Bits2 fn => fun a1 a2 => LoweredSyntax.Binop fn a1 a2\n      | Struct2 fn sig f => fun a1 a2 =>\n        match fn return lArg1 (Struct2 fn sig f) -> lArg2 (Struct2 fn sig f) -> lRet (Struct2 fn sig f) with\n        | SubstField => fun a1 a2 =>\n          LoweredSyntax.Binop (SubstFieldBits sig f) a1 a2\n        end a1 a2\n      | Array2 fn sig idx => fun a1 a2 =>\n        match fn return lArg1 (Array2 fn sig idx) -> lArg2 (Array2 fn sig idx) -> lRet (Array2 fn sig idx) with\n        | SubstElement => fun a1 a2 =>\n          LoweredSyntax.Binop (SubstElementBits sig idx) a1 a2\n        end a1 a2\n      end a1 a2.\n\n    Definition lower_member\n               {k: var_t} {tau: type} {sig}\n               (m: member (k, tau) sig) :\n      member (type_sz tau) (lsig_of_tsig sig) :=\n      member_map _ m.\n\n    Section Args.\n      Context (lower_action:\n                 forall {sig: tsig var_t} {tau}\n                   (a: typed_action sig tau),\n                   low_action (lsig_of_tsig sig) (type_sz tau)).\n\n      Definition lower_args' {sig argspec}\n                 (args: context (fun k_tau => typed_action sig (snd k_tau)) argspec) :=\n        cmap (V' := fun sz => (var_t * low_action _ sz)%type)\n             (fun k_tau => type_sz (snd k_tau))\n             (fun k_tau a => ((fst k_tau), lower_action _ _ a))\n             args.\n    End Args.\n\n    Fixpoint lower_action\n             {sig: tsig var_t} {tau}\n             (a: typed_action sig tau):\n      low_action (lsig_of_tsig sig) (type_sz tau) :=\n      let l {sig tau} a := @lower_action sig tau a in\n      match a with\n      | TypedSyntax.Fail tau =>\n        LoweredSyntax.Fail (type_sz tau)\n      | @TypedSyntax.Var _ _ _ _ _ _ _ _ k _ m =>\n        LoweredSyntax.Var k (lower_member m)\n      | TypedSyntax.Const cst =>\n        LoweredSyntax.Const (bits_of_value cst)\n      | TypedSyntax.Seq r1 r2 =>\n        LoweredSyntax.Seq (l r1) (l r2)\n      | @TypedSyntax.Assign _ _ _ _ _ _ _ _ k _ m ex =>\n        LoweredSyntax.Assign k (lower_member m) (l ex)\n      | TypedSyntax.Bind var ex body =>\n        LoweredSyntax.Bind var (l ex) (l body)\n      | TypedSyntax.If cond tbranch fbranch =>\n        LoweredSyntax.If (l cond) (l tbranch) (l fbranch)\n      | TypedSyntax.Read p idx =>\n        LoweredSyntax.Read p idx\n      | TypedSyntax.Write p idx val =>\n        LoweredSyntax.Write p idx (l val)\n      | TypedSyntax.Unop fn a =>\n        lower_unop fn (l a)\n      | TypedSyntax.Binop fn a1 a2 =>\n        lower_binop fn (l a1) (l a2)\n      | TypedSyntax.ExternalCall fn a =>\n        LoweredSyntax.ExternalCall fn (l a)\n      | TypedSyntax.InternalCall fn args body =>\n        SyntaxMacros.InternalCall\n          (lower_args' (@lower_action) args)\n          (l body)\n      | TypedSyntax.APos p a =>\n        LoweredSyntax.APos p (l a)\n      end.\n  End Action.\nEnd Lowering.\n\nNotation lower_args args := (lower_args' (@lower_action _ _ _ _ _ _ _) args).\n\nArguments lower_R {reg_t} R idx : assert.\nArguments lower_Sigma {ext_fn_t} Sigma fn : assert.\nArguments lower_r {reg_t} {R} {REnv} r : assert.\nArguments lower_sigma {ext_fn_t} {Sigma} sigma f a : 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/Lowering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18615861391324373}}
{"text": "Require Import Raft.\n\nRequire Import LastAppliedLeCommitIndexInterface.\nRequire Import UpdateLemmas.\nRequire Import SpecLemmas.\nRequire Import CommonTheorems.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\n\nSection LastAppliedLeCommitIndex.\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  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  Lemma lastApplied_le_commitIndex_appendEntries :\n    raft_net_invariant_append_entries lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleAppendEntries_same_lastApplied.\n    repeat find_rewrite.\n    find_apply_lem_hyp handleAppendEntries_log_detailed.\n    intuition; repeat find_rewrite; eauto;\n    eapply le_trans; eauto; eauto using Max.le_max_l.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_appendEntriesReply :\n    raft_net_invariant_append_entries_reply lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_same_lastApplied.\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_same_commitIndex.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  \n  Lemma lastApplied_le_commitIndex_requestVote :\n    raft_net_invariant_request_vote lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleRequestVote_same_lastApplied.\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleRequestVote_same_commitIndex.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_requestVoteReply :\n    raft_net_invariant_request_vote_reply lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    rewrite handleRequestVoteReply_same_lastApplied.\n    rewrite handleRequestVoteReply_same_commitIndex. eauto.\n  Qed.\n\n\n  Lemma doLeader_same_lastApplied:\n    forall st (os : list raft_output) (d' : raft_data)\n      (ms : list (name * msg)) (h0 : name),\n      doLeader st h0 = (os, d', ms) ->\n      lastApplied d' = lastApplied st.\n  Proof using. \n    intros.\n    unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; simpl in *; find_inversion; auto.\n  Qed.\n\n  Lemma fold_left_max :\n    forall l y z,\n      (forall x, In x l ->\n            y <= x) ->\n      y <= z ->\n      y <= fold_left max l z.\n  Proof using. \n    induction l; simpl in *; auto.\n    intros.\n    specialize (IHl y (max z a)).\n    forward IHl; eauto. concludes.\n    forward IHl; [eapply le_trans; eauto; eauto using Max.le_max_l|].\n    concludes. auto.\n  Qed.\n  \n  Lemma advanceCommitIndex_commitIndex :\n    forall st h,\n      commitIndex st <= commitIndex (advanceCommitIndex st h).\n  Proof using. \n    intros. unfold advanceCommitIndex. simpl in *.\n    apply fold_left_max; auto.\n    intros.\n    do_in_map. subst.\n    find_apply_lem_hyp filter_In.\n    repeat (intuition; do_bool).\n  Qed.\n  \n  Lemma doLeader_same_commitIndex :\n    forall st (os : list raft_output) (d' : raft_data)\n      (ms : list (name * msg)) (h0 : name),\n      doLeader st h0 = (os, d', ms) ->\n      commitIndex st <= commitIndex d'.\n  Proof using. \n    intros.\n    unfold doLeader in *.\n    repeat break_match; tuple_inversion; auto; eauto using advanceCommitIndex_commitIndex.\n    eapply le_trans; [eapply advanceCommitIndex_commitIndex with (h := h0)|]; eauto.\n  Qed.\n  \n  Lemma lastApplied_le_commitIndex_doLeader :\n    raft_net_invariant_do_leader lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp doLeader_same_lastApplied.\n    find_copy_apply_lem_hyp doLeader_same_commitIndex.\n    repeat find_rewrite. eapply le_trans; [|eauto]; eauto.\n  Qed.\n  \n  Lemma doGenericServer_lastApplied:\n    forall (h : name) \n      (st : raft_data) (out : list raft_output) (st' : raft_data)\n      (ms : list (name * msg)),\n      doGenericServer h st = (out, st', ms) ->\n      lastApplied st' <= max (lastApplied st) (commitIndex st).\n  Proof using. \n    intros. unfold doGenericServer in *. break_let. find_inversion.\n    simpl in *.\n    break_if; simpl in *; do_bool; auto.\n    - use_applyEntries_spec. subst. simpl in *.\n      eauto using Max.le_max_r.\n    - use_applyEntries_spec. subst. simpl in *.\n      eauto using Max.le_max_l.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_doGenericServer :\n    raft_net_invariant_do_generic_server lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp doGenericServer_commitIndex.\n    find_copy_apply_lem_hyp doGenericServer_lastApplied.\n    repeat find_rewrite.\n    erewrite Max.max_r in *; eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_clientRequest :\n    raft_net_invariant_client_request lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleClientRequest_commitIndex.\n    find_copy_apply_lem_hyp handleClientRequest_lastApplied.\n    repeat find_rewrite. eauto.\n  Qed.\n  \n\n  Lemma lastApplied_le_commitIndex_timeout :\n    raft_net_invariant_timeout lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleTimeout_commitIndex.\n    find_copy_apply_lem_hyp handleTimeout_lastApplied.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_reboot :\n    raft_net_invariant_reboot lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_reverse_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_init :\n    raft_net_invariant_init lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. auto.\n  Qed.\n\n  Theorem lastApplied_le_commitIndex_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      lastApplied_le_commitIndex net.\n  Proof using. \n    intros. apply raft_net_invariant; auto.\n    - apply lastApplied_le_commitIndex_init.\n    - apply lastApplied_le_commitIndex_clientRequest.\n    - apply lastApplied_le_commitIndex_timeout.\n    - apply lastApplied_le_commitIndex_appendEntries.\n    - apply lastApplied_le_commitIndex_appendEntriesReply.\n    - apply lastApplied_le_commitIndex_requestVote.\n    - apply lastApplied_le_commitIndex_requestVoteReply.\n    - apply lastApplied_le_commitIndex_doLeader.\n    - apply lastApplied_le_commitIndex_doGenericServer.\n    - apply lastApplied_le_commitIndex_state_same_packet_subset.\n    - apply lastApplied_le_commitIndex_reboot.\n  Qed.\n  \n  Instance lalcii : lastApplied_le_commitIndex_interface.\n  split. auto using lastApplied_le_commitIndex_invariant.\n  Qed.\n\nEnd LastAppliedLeCommitIndex.", "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/LastAppliedLeCommitIndexProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.1861477570340455}}
{"text": "Require Import Charge.Open.Subst.\nRequire Import Charge.Open.Open.\nRequire Import Charge.Open.Stack.\nRequire Import Charge.Logics.BILogic.\n\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.String.\nRequire Import ExtLib.Data.Sum.\nRequire Import ExtLib.Tactics.Consider.\n\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.Lemma.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.syms.SymEnv.\nRequire Import MirrorCore.syms.SymSum.\nRequire Import MirrorCore.Subst.FMapSubst.\n\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Language.Lang.\nRequire Import Java.Language.Program.\nRequire Import Java.Semantics.OperationalSemantics.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Bool.Bool.\n\nRequire Import MirrorCharge.Java.JavaType.\nRequire Import MirrorCharge.ModularFunc.ILogicFunc.\nRequire Import MirrorCharge.ModularFunc.BILogicFunc.\nRequire Import MirrorCharge.ModularFunc.LaterFunc.\nRequire Import MirrorCharge.ModularFunc.BaseFunc.\nRequire Import MirrorCharge.ModularFunc.ListFunc.\nRequire Import MirrorCharge.ModularFunc.OpenFunc.\nRequire Import MirrorCharge.ModularFunc.EmbedFunc.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n\tInductive java_func :=\n\t| pVal (_ : val)\n\t| pVarList (_ : list var) \n\t| pProg (_ : Program)\n\t| pCmd (_ : cmd)\n\t| pDExpr (_ : dexpr)\n\t| pFields (_ : list field)\n\t\n\t| pMethodSpec\n\t| pProgEq\n\t| pTriple\n\t| pTypeOf\n\t| pFieldLookup\n\t\n\t| pPointsto\n\t| pNull\n\t\n\t| pPlus\n\t| pMinus\n\t| pTimes\n\t| pAnd\n\t| pOr\n\t| pNot\n\t| pLt\n\t| pValEq.\n\n\tFixpoint beq_list {A} (f : A -> A -> bool) (xs ys : list A) :=\n\t\tmatch xs, ys with\n\t\t\t| nil, nil => true\n\t\t\t| x::xs, y :: ys => andb (f x y) (beq_list f xs ys)\n\t\t\t| _, _ => false\n\t\tend.\n\n\tDefinition typeof_java_func bf :=\n\t\tmatch bf with\n\t\t    | pVal _ => Some tyVal\n\t\t    | pVarList _ => Some tyVarList\n\t\t    | pProg _ => Some tyProg\n\t\t    | pCmd _ => Some tyCmd\n\t\t    | pDExpr _ => Some tyDExpr\n\t\t    | pFields _ => Some tyFields\n\t\t\n\t\t    | pMethodSpec => Some (tyArr tyString (tyArr tyString (tyArr tyVarList\n\t\t    \t (tyArr tyString (tyArr tySasn (tyArr tySasn tySpec))))))\n\t\t    | pProgEq => Some (tyArr tyProg tySpec)\n\t\t    | pTriple => Some (tyArr tySasn (tyArr tySasn (tyArr tyCmd tySpec)))\n\t\t    \n\t\t    | pTypeOf => Some (tyArr tyString (tyArr tyVal tyProp))\n\t\t    \n\t\t    | pFieldLookup => Some (tyArr tyProg (tyArr tyString (tyArr tyFields tyProp)))\n\t\t    \n\t\t    | pPointsto => Some (tyArr tyVal (tyArr tyString (tyArr tyVal tyAsn)))\n\t\t    \n\t\t    | pNull => Some tyVal\n\t\t    \n\t\t    | pPlus => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pMinus => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pTimes => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pAnd => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pOr => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pNot => Some (tyArr tyVal tyVal)\n\t\t    | pLt => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\t    | pValEq => Some (tyArr tyVal (tyArr tyVal tyVal))\n\t\tend.\n\n\tDefinition java_func_eq (a b : java_func) : option bool :=\n\t  match a , b with\n\t\t| pVal a, pVal b => Some (a ?[ eq ] b)\n\t    | pVarList a, pVarList b => Some (a ?[ eq ] b)\n\t    | pProg a, pProg b => Some (a ?[ eq ] b)\n\t    | pCmd a, pCmd b => Some (a ?[ eq ] b)\n\t    | pDExpr e1, pDExpr e2 => Some (e1 ?[ eq ] e2)\n\t    | pFields a, pFields b => Some (a ?[ eq ] b)\n\t        \n\t    | pMethodSpec, pMethodSpec => Some true\n\t    | pProgEq, pProgEq => Some true\n\t\t| pTriple, pTriple => Some true\n\t\n\t    | pTypeOf, pTypeOf => Some true\n\t\n\t    | pPointsto, pPointsto => Some true\n\t    | pFieldLookup, pFieldLookup => Some true\n\t\n\t    | pNull, pNull => Some true\n\t    | pPlus, pPlus => Some true\n\t    | pMinus, pMinus => Some true\n\t    | pTimes, pTimes => Some true\n\t    | pAnd, pAnd => Some true\n\t    | pOr, pOr => Some true\n\t    | pNot, pNot => Some true\n\t    | pLt, pLt => Some true\n\t    | pValEq, pValEq => Some true\n\t    | _, _ => None\n\t  end.\n\n    Global Instance RelDec_java_func : RelDec (@eq java_func) := {\n      rel_dec a b := match java_func_eq a b with \n    \t  \t\t       | Some b => b \n    \t\t \t       | None => false \n    \t\t\t     end\n    }.\n\n    Global Instance RelDec_Correct_ilfunc : RelDec_Correct RelDec_java_func.\n    Proof.\n      constructor.\n      destruct x; destruct y; simpl;\n      try solve [ try rewrite Bool.andb_true_iff ;\n                  repeat rewrite rel_dec_correct; intuition congruence ].                  \t\n    Qed.\n\nDefinition set_fold_fun (x : String.string) (f : field) (P : sasn) :=\n\t(`pointsto) (x/V) `f `null ** P.\n  \n  \t Definition java_func_symD bf :=\n\t\tmatch bf as bf return match typeof_java_func bf with\n\t\t\t\t\t\t\t\t| Some t => typD t\n\t\t\t\t\t\t\t\t| None => unit\n\t\t\t\t\t\t\t  end with\n              | pProg p => p\n              | pVal v => v\n              | pVarList vs => vs\n              | pCmd c => c\n              | pDExpr e => e\n              | pFields fs => fs\n\n              | pMethodSpec => method_spec\n              | pProgEq => prog_eq\n              | pTriple => triple\n              \n              | pTypeOf => typeof\n                            \n              | pFieldLookup => field_lookup\n              \n              | pPointsto => pointsto\n              \n              | pNull => null\n              \n              | pPlus => eplus\n              | pMinus => eminus\n              | pTimes => etimes\n              | pAnd => eand\n              | pOr => eor\n              | pNot => enot\n              | pLt => elt\n              | pValEq => eeq\n\tend.\n\n\tGlobal Instance RSym_JavaFunc : SymI.RSym java_func := {\n\t  typeof_sym := typeof_java_func;\n\t  symD := java_func_symD;\n\t  sym_eqb := java_func_eq\n\t}.\n\n\tGlobal Instance RSymOk_JavaFunc : SymI.RSymOk RSym_JavaFunc.\n\tProof.\n\t\tsplit; intros.\n\t\tdestruct a, b; simpl; try apply I; try reflexivity.\n\t\t+ consider (v ?[ eq ] v0); intuition congruence.\n\t\t+ consider (l ?[ eq ] l0); intuition congruence.\n\t\t+ consider (p ?[ eq ] p0); intuition congruence. \n\t\t+ consider (c ?[ eq ] c0); intuition congruence. \n\t\t+ consider (d ?[ eq ] d0); intuition congruence. \n\t\t+ consider (l ?[ eq ] l0); intuition congruence. \n\tQed.\t\t\n\n\nDefinition func := (SymEnv.func + @ilfunc typ + @bilfunc typ + \n                    @base_func typ + @list_func typ + @open_func typ _ _ + \n                    @embed_func typ + @later_func typ + java_func)%type.\n\nSection MakeJavaFunc.\n\tDefinition mkVal v : expr typ func := Inj (inr (pVal v)).\n\tDefinition mkVarList vs : expr typ func := Inj (inr (pVarList vs)).\n\tDefinition mkProg P : expr typ func := Inj (inr (pProg P)).\n\tDefinition mkCmd c : expr typ func := Inj (inr (pCmd c)).\n\tDefinition mkDExpr e : expr typ func := Inj (inr (pDExpr e)).\n\tDefinition mkFields fs : expr typ func := Inj (inr (pFields fs)).\n\n\tDefinition fMethodSpec : expr typ func := Inj (inr pMethodSpec).\n\tDefinition fProgEq : expr typ func := Inj (inr pProgEq).\n\tDefinition fTriple : expr typ func := Inj (inr pTriple).\n\tDefinition fTypeOf : expr typ func := Inj (inr pTypeOf).\n\tDefinition fFieldLookup : expr typ func := Inj (inr pFieldLookup).\n\tDefinition fPointsto : expr typ func := Inj (inr pPointsto).\n\tDefinition mkNull : expr typ func := Inj (inr pNull).\n\n\tDefinition fPlus : expr typ func := Inj (inr pPlus).\n\tDefinition fMinus : expr typ func := Inj (inr pMinus).\n\tDefinition fTimes : expr typ func := Inj (inr pTimes).\n\tDefinition fAnd : expr typ func := Inj (inr pAnd).\n\tDefinition fOr : expr typ func := Inj (inr pOr).\n\tDefinition fNot : expr typ func := Inj (inr pNot).\n\tDefinition fLt : expr typ func := Inj (inr pLt).\n\tDefinition fValEq : expr typ func := Inj (inr pValEq).\n\n\tDefinition mkTriple P c Q : expr typ func := App (App (App fTriple P) Q) c.\n\tDefinition mkFieldLookup P C f : expr typ func := App (App (App fFieldLookup P) C) f.\n\tDefinition mkTypeOf C x : expr typ func := App (App fTypeOf C) x.\n\tDefinition mkProgEq P := App fProgEq P.\n\t\n\tDefinition mkExprList es :=\n\t\t(fold_right (fun (e : dexpr) (acc : expr typ func) => \n\t\t\tmkCons tyExpr (mkDExpr e) acc) (mkNil tyExpr) es).\n\t\n\tFixpoint evalDExpr (e : dexpr) : expr typ func :=\n\t\tmatch e with\n\t\t\t| E_val v => mkConst tyVal (mkVal v)\n\t\t\t| E_var x => App (fStackGet (func := expr typ func)) (mkString (func := func) x)\n\t\t\t| E_plus e1 e2 => mkAps fPlus ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_minus e1 e2 => mkAps fMinus ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_times e1 e2 => mkAps fTimes ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_and e1 e2 => mkAps fAnd ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_or e1 e2 => mkAps fOr ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_not e => mkAps fNot ((evalDExpr e, tyVal)::nil) tyVal\n\t\t\t| E_lt e1 e2 => mkAps fLt ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\t\t| E_eq e1 e2 => mkAps fValEq ((evalDExpr e2, tyVal)::(evalDExpr e1, tyVal)::nil) tyVal\n\t\tend.\n\n\nEnd MakeJavaFunc.\n\nRequire Import Java.Examples.ListModel.\n\n\nClass Environment := { java_env :> @SymEnv.functions typ _}.\n\nSection JavaFunc.\n\n  Context {fs : Environment}.\n\n(* This needs to be parametric. It shouldn't be here \nDefinition fs : @SymEnv.functions typ _ :=\n  SymEnv.from_list\n  \t(@SymEnv.F typ _ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) List::\n  \t @SymEnv.F typ _ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) NodeList::nil). \n\n*)\nCheck RSym.\n\n  Global Instance RSym_ilfunc : RSym (@ilfunc typ) := \n\t  RSym_ilfunc ilops.\n  Global Instance RSym_bilfunc : RSym (@bilfunc typ) := \n\t  RSym_bilfunc _ bilops.\n  Global Instance RSym_embed_func : RSym (@embed_func typ) :=\n\t  RSym_embed_func _ eops.\n  Global Instance RSym_later_func : RSym (@later_func typ) :=\n\t  RSym_later_func _ lops.\n\n  Global Instance RSym_open_func : RSym (@open_func typ _ _) :=\n\t  @RSym_OpenFunc _ _ _ RType_typ _ _ _ _ _ _ _ _.\n\n  Global Existing Instance RSym_sum.\n  Global Existing Instance RSymOk_sum.\n\n  Global Instance RSym_func : RSym func.\n    repeat (apply RSym_sum; [|apply _]).\n    apply (RSym_func java_env).\n  Defined.\n\n  Global Instance RelDec_expr : RelDec (@eq func) := _.\n\n  Global Instance Expr_expr : ExprI.Expr _ (expr typ func) := @Expr_expr typ func _ _ _.\n  Global Instance Expr_ok : @ExprI.ExprOk typ RType_typ (expr typ func) Expr_expr := ExprOk_expr.\n\n  Require Import MirrorCore.VariablesI.\n  Require Import MirrorCore.Lambda.ExprVariables.\n\n  Global Instance ExprVar_expr : ExprVar (expr typ func) := _.\n  Global Instance ExprVarOk_expr : ExprVarOk ExprVar_expr := _.\n\n  Global Instance ExprUVar_expr : ExprUVar (expr typ func) := _.\n  Global Instance ExprUVarOk_expr : ExprUVarOk ExprUVar_expr := _.\n\n  Definition subst : Type :=\n    FMapSubst.SUBST.raw (expr typ func).\n  Global Instance SS : SubstI.Subst subst (expr typ func) :=\n    @FMapSubst.SUBST.Subst_subst _.\n  Global Instance SU : SubstI.SubstUpdate subst (expr typ func) :=\n    @FMapSubst.SUBST.SubstUpdate_subst _ _. \n  Global Instance SO : SubstI.SubstOk SS := \n    @FMapSubst.SUBST.SubstOk_subst typ RType_typ (expr typ func) _ _.\n  Global Instance SUO :SubstI.SubstUpdateOk SU SO :=  @FMapSubst.SUBST.SubstUpdateOk_subst typ RType_typ (expr typ func) _ _ _.\n\n  Global Instance MA : MentionsAny (expr typ func) := {\n    mentionsAny := ExprCore.mentionsAny\n  }.\n\n  Global Instance MAOk : MentionsAnyOk MA _ _.\n  Proof.\n    admit.\n  Qed.\n\n  Lemma evalDexpr_wt (e : dexpr) : \n\t  typeof_expr nil nil (evalDExpr e) = Some tyExpr.\n  Proof.\n    induction e.\n    + simpl; reflexivity.\n    + simpl; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n    + simpl; rewrite IHe1, IHe2; reflexivity.\n  Qed.\n\n  Definition is_pure (e : expr typ func) : bool :=\n\tmatch e with\n\t  | App f P => match embedS f with\n\t\t\t\t     | Some (eilf_embed tyPure tySasn) => true\n\t\t\t\t\t | Some (eilf_embed tyProp tySasn) => true\n\t\t\t\t\t | _ => false\n\t\t\t\t   end\n\t\t\t\n \t  | e =>\n \t\tmatch ilogicS e with\n \t\t  | Some (ilf_true _) => true\n \t\t  | Some (ilf_false _) => true\n \t\t  | _ => false\n \t\tend\n   end.\n\n  Definition mkPointstoVar x f e : 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                      (App fStackGet (mkString x)))\n                (mkConst tyString (mkString f)))\n          e.\n\n  Definition test_lemma :=\n    @lemmaD typ (expr typ func) RType_typ Expr_expr (expr typ func)\n            (fun tus tvs e => exprD' tus tvs tyProp e)\n            _\n            nil nil.\nEnd JavaFunc.", "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/JavaFunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.1861477510038583}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.algebra Require Import reservation_map agree frac.\nFrom iris.algebra Require Export dfrac.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export own.\nFrom iris.base_logic.lib Require Import ghost_map.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n(** This file provides a generic mechanism for a language-level point-to\nconnective [l \u21a6{dq} v] reflecting the physical heap.  This library is designed to\nbe used as a singleton (i.e., with only a single instance existing in any\nproof), with the [gen_heapG] typeclass providing the ghost names of that unique\ninstance.  That way, [mapsto] does not need an explicit [gname] parameter.\nThis mechanism can be plugged into a language and related to the physical heap\nby using [gen_heap_interp \u03c3] in the state interpretation of the weakest\nprecondition. See heap-lang for an example.\n\nIf you are looking for a library providing \"ghost heaps\" independent of the\nphysical state, you will likely want explicit ghost names to disambiguate\nmultiple heaps and are thus better off using [ghost_map], or (if you need more\nflexibility), directly using the underlying [algebra.lib.gmap_view].\n\nThis library is generic in the types [L] for locations and [V] for values and\nsupports fractional permissions.  Next to the point-to connective [l \u21a6{dq} v],\nwhich keeps track of the value [v] of a location [l], this library also provides\na way to attach \"meta\" or \"ghost\" data to locations. This is done as follows:\n\n- When one allocates a location, in addition to the point-to connective [l \u21a6 v],\n  one also obtains the token [meta_token l \u22a4]. This token is an exclusive\n  resource that denotes that no meta data has been associated with the\n  namespaces in the mask [\u22a4] for the location [l].\n- Meta data tokens can be split w.r.t. namespace masks, i.e.\n  [meta_token l (E1 \u222a E2) \u22a3\u22a2 meta_token l E1 \u2217 meta_token l E2] if [E1 ## E2].\n- Meta data can be set using the update [meta_token l E ==\u2217 meta l N x] provided\n  [\u2191N \u2286 E], and [x : A] for any countable [A]. The [meta l N x] connective is\n  persistent and denotes the knowledge that the meta data [x] has been\n  associated with namespace [N] to the location [l].\n\nTo make the mechanism as flexible as possible, the [x : A] in [meta l N x] can\nbe of any countable type [A]. This means that you can associate e.g. single\nghost names, but also tuples of ghost names, etc.\n\nTo further increase flexibility, the [meta l N x] and [meta_token l E]\nconnectives are annotated with a namespace [N] and mask [E]. That way, one can\nassign a map of meta information to a location. This is particularly useful when\nbuilding abstractions, then one can gradually assign more ghost information to a\nlocation instead of having to do all of this at once. We use namespaces so that\nthese can be matched up with the invariant namespaces. *)\n\n(** To implement this mechanism, we use three resource algebras:\n\n- A [gmap_view L V], which keeps track of the values of locations.\n- A [gmap_view L gname], which keeps track of the meta information of\n  locations. More specifically, this RA introduces an indirection: it keeps\n  track of a ghost name for each location.\n- The ghost names in the aforementioned authoritative RA refer to namespace maps\n  [reservation_map (agree positive)], which store the actual meta information.\n  This indirection is needed because we cannot perform frame preserving updates\n  in an authoritative fragment without owning the full authoritative element\n  (in other words, without the indirection [meta_set] would need [gen_heap_interp]\n  as a premise).\n *)\n\n(** The CMRAs we need, and the global ghost names we are using. *)\n\nClass gen_heapPreG (L V : Type) (\u03a3 : gFunctors) `{Countable L} := {\n  gen_heap_preG_inG :> ghost_mapG \u03a3 L V;\n  gen_meta_preG_inG :> ghost_mapG \u03a3 L gname;\n  gen_meta_data_preG_inG :> inG \u03a3 (reservation_mapR (agreeR positiveO));\n}.\n\nClass gen_heapG (L V : Type) (\u03a3 : gFunctors) `{Countable L} := GenHeapG {\n  gen_heap_inG :> gen_heapPreG L V \u03a3;\n  gen_heap_name : gname;\n  gen_meta_name : gname\n}.\nGlobal Arguments GenHeapG L V \u03a3 {_ _ _} _ _.\nGlobal Arguments gen_heap_name {L V \u03a3 _ _} _ : assert.\nGlobal Arguments gen_meta_name {L V \u03a3 _ _} _ : assert.\n\nDefinition gen_heap\u03a3 (L V : Type) `{Countable L} : gFunctors := #[\n  ghost_map\u03a3 L V;\n  ghost_map\u03a3 L gname;\n  GFunctor (reservation_mapR (agreeR positiveO))\n].\n\nGlobal Instance subG_gen_heapPreG {\u03a3 L V} `{Countable L} :\n  subG (gen_heap\u03a3 L V) \u03a3 \u2192 gen_heapPreG L V \u03a3.\nProof. solve_inG. Qed.\n\nSection definitions.\n  Context `{Countable L, hG : !gen_heapG L V \u03a3}.\n\n  Definition gen_heap_interp (\u03c3 : gmap L V) : iProp \u03a3 := \u2203 m : gmap L gname,\n    (* The [\u2286] is used to avoid assigning ghost information to the locations in\n    the initial heap (see [gen_heap_init]). *)\n    \u231c dom _ m \u2286 dom (gset L) \u03c3 \u231d \u2217\n    ghost_map_auth (gen_heap_name hG) 1 \u03c3 \u2217\n    ghost_map_auth (gen_meta_name hG) 1 m.\n\n  Definition mapsto_def (l : L) (dq : dfrac) (v: V) : iProp \u03a3 :=\n    l \u21aa[gen_heap_name hG]{dq} v.\n  Definition mapsto_aux : seal (@mapsto_def). Proof. by eexists. Qed.\n  Definition mapsto := mapsto_aux.(unseal).\n  Definition mapsto_eq : @mapsto = @mapsto_def := mapsto_aux.(seal_eq).\n\n  Definition meta_token_def (l : L) (E : coPset) : iProp \u03a3 :=\n    \u2203 \u03b3m, l \u21aa[gen_meta_name hG]\u25a1 \u03b3m \u2217 own \u03b3m (reservation_map_token E).\n  Definition meta_token_aux : seal (@meta_token_def). Proof. by eexists. Qed.\n  Definition meta_token := meta_token_aux.(unseal).\n  Definition meta_token_eq : @meta_token = @meta_token_def := meta_token_aux.(seal_eq).\n\n  (** TODO: The use of [positives_flatten] violates the namespace abstraction\n  (see the proof of [meta_set]. *)\n  Definition meta_def `{Countable A} (l : L) (N : namespace) (x : A) : iProp \u03a3 :=\n    \u2203 \u03b3m, l \u21aa[gen_meta_name hG]\u25a1 \u03b3m \u2217\n          own \u03b3m (reservation_map_data (positives_flatten N) (to_agree (encode x))).\n  Definition meta_aux : seal (@meta_def). Proof. by eexists. Qed.\n  Definition meta := meta_aux.(unseal).\n  Definition meta_eq : @meta = @meta_def := meta_aux.(seal_eq).\nEnd definitions.\nGlobal Arguments meta {L _ _ V \u03a3 _ A _ _} l N x.\n\n(** FIXME: Refactor these notations using custom entries once Coq bug #13654\nhas been fixed. *)\nLocal Notation \"l \u21a6{ dq } v\" := (mapsto l dq v)\n  (at level 20, format \"l  \u21a6{ dq }  v\") : bi_scope.\nLocal Notation \"l \u21a6\u25a1 v\" := (mapsto l DfracDiscarded v)\n  (at level 20, format \"l  \u21a6\u25a1  v\") : bi_scope.\nLocal Notation \"l \u21a6{# q } v\" := (mapsto l (DfracOwn q) v)\n  (at level 20, format \"l  \u21a6{# q }  v\") : bi_scope.\nLocal Notation \"l \u21a6 v\" := (mapsto l (DfracOwn 1) v)\n  (at level 20, format \"l  \u21a6  v\") : bi_scope.\n\nSection gen_heap.\n  Context {L V} `{Countable L, !gen_heapG L V \u03a3}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03a6 : V \u2192 iProp \u03a3.\n  Implicit Types \u03c3 : gmap L V.\n  Implicit Types m : gmap L gname.\n  Implicit Types l : L.\n  Implicit Types v : V.\n\n  (** General properties of mapsto *)\n  Global Instance mapsto_timeless l dq v : Timeless (l \u21a6{dq} v).\n  Proof. rewrite mapsto_eq. apply _. Qed.\n  Global Instance mapsto_fractional l v : Fractional (\u03bb q, l \u21a6{#q} v)%I.\n  Proof. rewrite mapsto_eq. apply _. Qed.\n  Global Instance mapsto_as_fractional l q v :\n    AsFractional (l \u21a6{#q} v) (\u03bb q, l \u21a6{#q} v)%I q.\n  Proof. rewrite mapsto_eq. apply _. Qed.\n  Global Instance mapsto_persistent l v : Persistent (l \u21a6\u25a1 v).\n  Proof. rewrite mapsto_eq. apply _. Qed.\n\n  Lemma mapsto_valid l dq v : l \u21a6{dq} v -\u2217 \u231c\u2713 dq\u231d%Qp.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_valid. Qed.\n  Lemma mapsto_valid_2 l dq1 dq2 v1 v2 : l \u21a6{dq1} v1 -\u2217 l \u21a6{dq2} v2 -\u2217 \u231c\u2713 (dq1 \u22c5 dq2) \u2227 v1 = v2\u231d.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_valid_2. Qed.\n  (** Almost all the time, this is all you really need. *)\n  Lemma mapsto_agree l dq1 dq2 v1 v2 : l \u21a6{dq1} v1 -\u2217 l \u21a6{dq2} v2 -\u2217 \u231cv1 = v2\u231d.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_agree. Qed.\n\n  Lemma mapsto_combine l dq1 dq2 v1 v2 :\n    l \u21a6{dq1} v1 -\u2217 l \u21a6{dq2} v2 -\u2217 l \u21a6{dq1 \u22c5 dq2} v1 \u2217 \u231cv1 = v2\u231d.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_combine. Qed.\n\n  Lemma mapsto_frac_ne l1 l2 dq1 dq2 v1 v2 :\n    \u00ac \u2713(dq1 \u22c5 dq2) \u2192 l1 \u21a6{dq1} v1 -\u2217 l2 \u21a6{dq2} v2 -\u2217 \u231cl1 \u2260 l2\u231d.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_frac_ne. Qed.\n  Lemma mapsto_ne l1 l2 dq2 v1 v2 : l1 \u21a6 v1 -\u2217 l2 \u21a6{dq2} v2 -\u2217 \u231cl1 \u2260 l2\u231d.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_ne. Qed.\n\n  (** Permanently turn any points-to predicate into a persistent\n      points-to predicate. *)\n  Lemma mapsto_persist l dq v : l \u21a6{dq} v ==\u2217 l \u21a6\u25a1 v.\n  Proof. rewrite mapsto_eq. apply ghost_map_elem_persist. Qed.\n\n  (** General properties of [meta] and [meta_token] *)\n  Global Instance meta_token_timeless l N : Timeless (meta_token l N).\n  Proof. rewrite meta_token_eq. apply _. Qed.\n  Global Instance meta_timeless `{Countable A} l N (x : A) : Timeless (meta l N x).\n  Proof. rewrite meta_eq. apply _. Qed.\n  Global Instance meta_persistent `{Countable A} l N (x : A) : Persistent (meta l N x).\n  Proof. rewrite meta_eq. apply _. Qed.\n\n  Lemma meta_token_union_1 l E1 E2 :\n    E1 ## E2 \u2192 meta_token l (E1 \u222a E2) -\u2217 meta_token l E1 \u2217 meta_token l E2.\n  Proof.\n    rewrite meta_token_eq /meta_token_def. intros ?. iDestruct 1 as (\u03b3m1) \"[#H\u03b3m Hm]\".\n    rewrite reservation_map_token_union //. iDestruct \"Hm\" as \"[Hm1 Hm2]\".\n    iSplitL \"Hm1\"; eauto.\n  Qed.\n  Lemma meta_token_union_2 l E1 E2 :\n    meta_token l E1 -\u2217 meta_token l E2 -\u2217 meta_token l (E1 \u222a E2).\n  Proof.\n    rewrite meta_token_eq /meta_token_def.\n    iDestruct 1 as (\u03b3m1) \"[#H\u03b3m1 Hm1]\". iDestruct 1 as (\u03b3m2) \"[#H\u03b3m2 Hm2]\".\n    iDestruct (ghost_map_elem_valid_2 with \"H\u03b3m1 H\u03b3m2\") as %[_ ->].\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %?%reservation_map_token_valid_op.\n    iExists \u03b3m2. iFrame \"H\u03b3m2\". rewrite reservation_map_token_union //. by iSplitL \"Hm1\".\n  Qed.\n  Lemma meta_token_union l E1 E2 :\n    E1 ## E2 \u2192 meta_token l (E1 \u222a E2) \u22a3\u22a2 meta_token l E1 \u2217 meta_token l E2.\n  Proof.\n    intros; iSplit; first by iApply meta_token_union_1.\n    iIntros \"[Hm1 Hm2]\". by iApply (meta_token_union_2 with \"Hm1 Hm2\").\n  Qed.\n\n  Lemma meta_token_difference l E1 E2 :\n    E1 \u2286 E2 \u2192 meta_token l E2 \u22a3\u22a2 meta_token l E1 \u2217 meta_token l (E2 \u2216 E1).\n  Proof.\n    intros. rewrite {1}(union_difference_L E1 E2) //.\n    by rewrite meta_token_union; last set_solver.\n  Qed.\n\n  Lemma meta_agree `{Countable A} l i (x1 x2 : A) :\n    meta l i x1 -\u2217 meta l i x2 -\u2217 \u231cx1 = x2\u231d.\n  Proof.\n    rewrite meta_eq /meta_def.\n    iDestruct 1 as (\u03b3m1) \"[H\u03b3m1 Hm1]\"; iDestruct 1 as (\u03b3m2) \"[H\u03b3m2 Hm2]\".\n    iDestruct (ghost_map_elem_valid_2 with \"H\u03b3m1 H\u03b3m2\") as %[_ ->].\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %H\u03b3; iPureIntro.\n    move: H\u03b3. rewrite -reservation_map_data_op reservation_map_data_valid.\n    move=> /to_agree_op_inv_L. naive_solver.\n  Qed.\n  Lemma meta_set `{Countable A} E l (x : A) N :\n    \u2191 N \u2286 E \u2192 meta_token l E ==\u2217 meta l N x.\n  Proof.\n    rewrite meta_token_eq meta_eq /meta_token_def /meta_def.\n    iDestruct 1 as (\u03b3m) \"[H\u03b3m Hm]\". iExists \u03b3m. iFrame \"H\u03b3m\".\n    iApply (own_update with \"Hm\").\n    apply reservation_map_alloc; last done.\n    cut (positives_flatten N \u2208@{coPset} \u2191N); first by set_solver.\n    rewrite nclose_eq. apply elem_coPset_suffixes.\n    exists 1%positive. by rewrite left_id_L.\n  Qed.\n\n  (** Update lemmas *)\n  Lemma gen_heap_alloc \u03c3 l v :\n    \u03c3 !! l = None \u2192\n    gen_heap_interp \u03c3 ==\u2217 gen_heap_interp (<[l:=v]>\u03c3) \u2217 l \u21a6 v \u2217 meta_token l \u22a4.\n  Proof.\n    iIntros (H\u03c3l). rewrite /gen_heap_interp mapsto_eq /mapsto_def meta_token_eq /meta_token_def /=.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 Hm]\".\n    iMod (ghost_map_insert l with \"H\u03c3\") as \"[H\u03c3 Hl]\"; first done.\n    iMod (own_alloc (reservation_map_token \u22a4)) as (\u03b3m) \"H\u03b3m\".\n    { apply reservation_map_token_valid. }\n    iMod (ghost_map_insert_persist l with \"Hm\") as \"[Hm Hlm]\".\n    { move: H\u03c3l. rewrite -!(not_elem_of_dom (D:=gset L)). set_solver. }\n    iModIntro. iFrame \"Hl\". iSplitL \"H\u03c3 Hm\"; last by eauto with iFrame.\n    iExists (<[l:=\u03b3m]> m). iFrame. iPureIntro.\n    rewrite !dom_insert_L. set_solver.\n  Qed.\n\n  Lemma gen_heap_alloc_big \u03c3 \u03c3' :\n    \u03c3' ##\u2098 \u03c3 \u2192\n    gen_heap_interp \u03c3 ==\u2217\n    gen_heap_interp (\u03c3' \u222a \u03c3) \u2217 ([\u2217 map] l \u21a6 v \u2208 \u03c3', l \u21a6 v) \u2217 ([\u2217 map] l \u21a6 _ \u2208 \u03c3', meta_token l \u22a4).\n  Proof.\n    revert \u03c3; induction \u03c3' as [| l v \u03c3' Hl IH] using map_ind; iIntros (\u03c3 Hdisj) \"H\u03c3\".\n    { rewrite left_id_L. auto. }\n    iMod (IH with \"H\u03c3\") as \"[H\u03c3'\u03c3 H\u03c3']\"; first by eapply map_disjoint_insert_l.\n    decompose_map_disjoint.\n    rewrite !big_opM_insert // -insert_union_l //.\n    by iMod (gen_heap_alloc with \"H\u03c3'\u03c3\") as \"($ & $ & $)\";\n      first by apply lookup_union_None.\n  Qed.\n\n  Lemma gen_heap_valid \u03c3 l dq v : gen_heap_interp \u03c3 -\u2217 l \u21a6{dq} v -\u2217 \u231c\u03c3 !! l = Some v\u231d.\n  Proof.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 _]\". iIntros \"Hl\".\n    rewrite /gen_heap_interp mapsto_eq.\n    by iDestruct (ghost_map_lookup with \"H\u03c3 Hl\") as %?.\n  Qed.\n\n  Lemma gen_heap_update \u03c3 l v1 v2 :\n    gen_heap_interp \u03c3 -\u2217 l \u21a6 v1 ==\u2217 gen_heap_interp (<[l:=v2]>\u03c3) \u2217 l \u21a6 v2.\n  Proof.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 Hm]\".\n    iIntros \"Hl\". rewrite /gen_heap_interp mapsto_eq /mapsto_def.\n    iDestruct (ghost_map_lookup with \"H\u03c3 Hl\") as %Hl.\n    iMod (ghost_map_update with \"H\u03c3 Hl\") as \"[H\u03c3 Hl]\".\n    iModIntro. iFrame \"Hl\". iExists m. iFrame.\n    iPureIntro. apply (elem_of_dom_2 (D:=gset L)) in Hl.\n    rewrite dom_insert_L. set_solver.\n  Qed.\nEnd gen_heap.\n\n(** This variant of [gen_heap_init] should only be used when absolutely needed.\nThe key difference to [gen_heap_init] is that the [inG] instances in the new\n[gen_heapG] instance are related to the original [gen_heapPreG] instance,\nwhereas [gen_heap_init] forgets about that relation. *)\nLemma gen_heap_init_names `{Countable L, !gen_heapPreG L V \u03a3} \u03c3 :\n  \u22a2 |==> \u2203 \u03b3h \u03b3m : gname,\n    let hG := GenHeapG L V \u03a3 \u03b3h \u03b3m in\n    gen_heap_interp \u03c3 \u2217 ([\u2217 map] l \u21a6 v \u2208 \u03c3, l \u21a6 v) \u2217 ([\u2217 map] l \u21a6 _ \u2208 \u03c3, meta_token l \u22a4).\nProof.\n  iMod (ghost_map_alloc_empty (K:=L) (V:=V)) as (\u03b3h) \"Hh\".\n  iMod (ghost_map_alloc_empty (K:=L) (V:=gname)) as (\u03b3m) \"Hm\".\n  iExists \u03b3h, \u03b3m.\n  iAssert (gen_heap_interp (hG:=GenHeapG _ _ _ \u03b3h \u03b3m) \u2205) with \"[Hh Hm]\" as \"Hinterp\".\n  { iExists \u2205; simpl. iFrame \"Hh Hm\". by rewrite dom_empty_L. }\n  iMod (gen_heap_alloc_big with \"Hinterp\") as \"(Hinterp & $ & $)\".\n  { apply map_disjoint_empty_r. }\n  rewrite right_id_L. done.\nQed.\n\nLemma gen_heap_init `{Countable L, !gen_heapPreG L V \u03a3} \u03c3 :\n  \u22a2 |==> \u2203 _ : gen_heapG L V \u03a3,\n    gen_heap_interp \u03c3 \u2217 ([\u2217 map] l \u21a6 v \u2208 \u03c3, l \u21a6 v) \u2217 ([\u2217 map] l \u21a6 _ \u2208 \u03c3, meta_token l \u22a4).\nProof.\n  iMod (gen_heap_init_names \u03c3) as (\u03b3h \u03b3m) \"Hinit\".\n  iExists (GenHeapG _ _ _ \u03b3h \u03b3m).\n  done.\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/gen_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.18614773659884293}}
{"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 list.\n(* Not using iris but importing their ssreflect dependencies *)\nFrom iris.proofmode Require Import tactics.\nFrom shack Require Import lang progdef.\n\n(* Abstract definition of the SDT constraints at the class level. *)\nClass SDTClassConstraints := {\n  \u0394sdt : tag \u2192 list constraint;\n  \u0394sdt_m : tag \u2192 string \u2192 list constraint;\n}.\n\nSection Subtype.\n  (* assume a given set of class definitions *)\n  Context `{PDC: ProgDefContext}.\n  (* That are not cyclic *)\n  Context `{PDA: ProgDefAcc}.\n  (* assume some SDT constraints *)\n  Context `{SDTCC: SDTClassConstraints}.\n\n  Inductive subtype_kind := Aware | Plain.\n\n  (* Type well-formdness is mostly introduced to be able to define\n   * subtyping rule correctly, like unions.\n   *)\n  Inductive subtype (\u0394 : list constraint) : subtype_kind \u2192 lang_ty \u2192 lang_ty \u2192 Prop :=\n    | SubMixed: \u2200 kd ty, subtype \u0394 kd ty MixedT\n    | SubNothing: \u2200 kd ty, wf_ty ty \u2192 subtype \u0394 kd NothingT ty\n    | SubClass: \u2200 kd A \u03c3A B \u03c3B adef,\n        pdefs !! A = Some adef \u2192\n        length \u03c3A = length adef.(generics) \u2192\n        extends_using A B \u03c3B \u2192\n        subtype \u0394 kd (ClassT false A \u03c3A) (ClassT false B (subst_ty \u03c3A <$> \u03c3B))\n    | SubExact: \u2200 kd A \u03c3A adef,\n        pdefs !! A = Some adef \u2192\n        length \u03c3A = length adef.(generics) \u2192\n        subtype \u0394 kd (ClassT true A \u03c3A) (ClassT false A \u03c3A)\n    | SubVariance: \u2200 kd A adef \u03c30 \u03c31,\n        pdefs !! A = Some adef \u2192\n        Forall wf_ty \u03c31 \u2192\n        subtype_targs \u0394 kd adef.(generics) \u03c30 \u03c31 \u2192\n        subtype \u0394 kd (ClassT false A \u03c30) (ClassT false A \u03c31)\n    | SubExactVariance: \u2200 kd A adef \u03c30 \u03c31,\n        pdefs !! A = Some adef \u2192\n        Forall wf_ty \u03c31 \u2192\n        subtype_targs \u0394 kd ((\u03bb _, Invariant) <$> adef.(generics)) \u03c30 \u03c31 \u2192\n        subtype \u0394 kd (ClassT true A \u03c30) (ClassT true A \u03c31)\n    | SubMixed2 kd: subtype \u0394 kd MixedT (UnionT NonNullT NullT)\n    | SubIntNonNull kd: subtype \u0394 kd IntT NonNullT\n    | SubBoolNonNull kd: subtype \u0394 kd BoolT NonNullT\n    | SubIntBoolDisj kd: subtype \u0394 kd (InterT IntT BoolT) NothingT\n    | SubClassNonNull: \u2200 kd exact A targs, subtype \u0394 kd (ClassT exact A targs) NonNullT\n    | SubUnionUpper1: \u2200 kd s t, wf_ty t \u2192 subtype \u0394 kd s (UnionT s t)\n    | SubUnionUpper2: \u2200 kd s t, wf_ty s \u2192 subtype \u0394 kd t (UnionT s t)\n    | SubUnionLower : \u2200 kd s t u, subtype \u0394 kd s u \u2192 subtype \u0394 kd t u \u2192 subtype \u0394 kd (UnionT s t) u\n    | SubInterLower1: \u2200 kd s t, subtype \u0394 kd (InterT s t) s\n    | SubInterLower2: \u2200 kd s t, subtype \u0394 kd (InterT s t) t\n    | SubInterUpper: \u2200 kd s t u, subtype \u0394 kd u s \u2192 subtype \u0394 kd u t \u2192 subtype \u0394 kd u (InterT s t)\n    | SubRefl: \u2200 kd s, subtype \u0394 kd s s\n    | SubTrans: \u2200 kd s t u, subtype \u0394 kd s t \u2192 subtype \u0394 kd t u \u2192 subtype \u0394 kd s u\n    | SubConstraint: \u2200 kd s t, (s, t) \u2208 \u0394 \u2192 subtype \u0394 kd s t\n    | SubClassDyn: \u2200 kd exact A adef \u03c3A,\n        pdefs !! A = Some adef \u2192\n        wf_ty (ClassT exact A \u03c3A) \u2192\n        (* \u0394 => \u0394sdt,A[\u03c3A] *)\n        (\u2200 k s t, (subst_constraints \u03c3A (\u0394sdt A)) !! k = Some (s, t) \u2192 subtype \u0394 kd s t) \u2192\n        (* \u0394 => \u0394A[\u03c3A] *)\n        (\u2200 k s t, adef.(constraints) !! k = Some (s, t) \u2192 subtype \u0394 kd (subst_ty \u03c3A s) (subst_ty \u03c3A t)) \u2192\n        subtype \u0394 kd (ClassT exact A \u03c3A) SupportDynT\n    | SubIntDyn kd: subtype \u0394 kd IntT SupportDynT\n    | SubBoolDyn kd: subtype \u0394 kd BoolT SupportDynT\n    | SubNullDyn kd: subtype \u0394 kd NullT SupportDynT\n    | SubSupDyn: subtype \u0394 Aware SupportDynT DynamicT\n    | SubDynPrim kd : subtype \u0394 kd DynamicT SupportDynT\n    | SubFalse kd : \u2200 A B,\n        wf_ty B \u2192\n        subtype \u0394 kd IntT BoolT \u2192\n        subtype \u0394 kd A B\n  with subtype_targs (\u0394: list constraint) : subtype_kind \u2192 list variance \u2192 list lang_ty \u2192 list lang_ty \u2192 Prop :=\n    | subtype_targs_nil kd: subtype_targs \u0394 kd [] [] []\n    | subtype_targs_invariant: \u2200 kd ty0 ty1 vs ty0s ty1s,\n        subtype \u0394 kd ty0 ty1 \u2192\n        subtype \u0394 kd ty1 ty0 \u2192\n        subtype_targs \u0394 kd vs ty0s ty1s \u2192\n        subtype_targs \u0394 kd (Invariant :: vs) (ty0 :: ty0s) ( ty1 :: ty1s)\n    | subtype_targs_covariant: \u2200 kd ty0 ty1 vs ty0s ty1s,\n        subtype \u0394 kd ty0 ty1 \u2192\n        subtype_targs \u0394 kd vs ty0s ty1s \u2192\n        subtype_targs \u0394 kd (Covariant :: vs) (ty0 :: ty0s) ( ty1 :: ty1s)\n    | subtype_targs_contravariant: \u2200 kd ty0 ty1 vs ty0s ty1s,\n        subtype \u0394 kd ty1 ty0 \u2192\n        subtype_targs \u0394 kd vs ty0s ty1s \u2192\n        subtype_targs \u0394 kd (Contravariant :: vs) (ty0 :: ty0s) (ty1 :: ty1s)\n  .\n\n  Definition \u0394entails kd (\u03940 \u03941: list constraint) :=\n    \u2200 i c, \u03941 !! i = Some c \u2192 subtype \u03940 kd c.1 c.2.\n\n  (* Properties of \u0394sdt *)\n  Class SDTClassSpec `{PDA : ProgDefAcc} := {\n    (* \u0394sdt preserves the wf_ty of \u03c3 *)\n    \u0394sdt_wf: \u2200 A k c, \u0394sdt A !! k = Some c -> wf_constraint c;\n    \u0394sdt_m_wf: \u2200 A m k c, \u0394sdt_m A m !! k = Some c -> wf_constraint c;\n    (* \u0394sdt is bounded by the generics of its class *)\n    \u0394sdt_bounded: \u2200 A adef k c,\n      pdefs !! A = Some adef \u2192\n      \u0394sdt A !! k = Some c \u2192\n      bounded_constraint (length adef.(generics)) c;\n    \u0394sdt_m_bounded: \u2200 A m adef k c,\n      pdefs !! A = Some adef \u2192\n      \u0394sdt_m A m !! k = Some c \u2192\n      bounded_constraint (length adef.(generics)) c;\n    (* Like normal constraints, \u0394sdt can't use the `this` type *)\n    \u0394sdt_no_this: \u2200 A k c, \u0394sdt A !! k = Some c -> no_this_constraint c;\n    \u0394sdt_m_no_this: \u2200 A m k c,\n      \u0394sdt_m A m !! k = Some c \u2192\n      no_this_constraint c;\n  }.\nEnd Subtype.\n\nSection SubtypeFacts.\n  (* assume a given set of class definitions and\n   * their SDT annotations.\n   *)\n  Context `{SDTCS: SDTClassSpec}.\n\n  Corollary length_subtype_targs_v0 \u0394 kd: \u2200 vs ty0s ty1s,\n    subtype_targs \u0394 kd vs ty0s ty1s \u2192 length vs = length ty0s.\n  Proof.\n    induction 1 as [ | ???????? h hi | ??????? h hi | ??????? h hi] => //=; by rewrite hi.\n  Qed.\n\n  Corollary length_subtype_targs_v1 \u0394 kd: \u2200 vs ty0s ty1s,\n    subtype_targs \u0394 kd vs ty0s ty1s \u2192 length vs = length ty1s.\n  Proof.\n    induction 1 as [ | ???????? h hi | ??????? h hi | ??????? h hi] => //=; by rewrite hi.\n  Qed.\n\n  Hint Constructors subtype : core.\n  Hint Constructors subtype_targs : core.\n\n  Notation \"\u0394 \u22a2 s <: t\" := (subtype \u0394 Plain s t) (at level 70, s at next level, no associativity).\n  Notation \"\u0394 \u22a2 s <D: t\" := (subtype \u0394 Aware s t) (at level 70, s at next level, no associativity).\n  Notation \"\u0394 \u22a2 lts <: vs :> rts\" := (subtype_targs \u0394 Plain vs lts rts) (at level 70, lts, vs at next level).\n\n  Lemma subtype_to_Aware \u0394 kd s t : subtype \u0394 kd s t \u2192 subtype \u0394 Aware s t\n  with subtype_targs_to_Aware \u0394 kd lhs vs rhs :\n     subtype_targs \u0394 kd vs lhs rhs \u2192 subtype_targs \u0394 Aware vs lhs rhs.\n  Proof.\n    - destruct 1 as [ kd ty | kd ty hwf | kd A \u03c3A B \u03c3B adef hadef hL hext\n      | kd A \u03c3A adef hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | | | | | kd A targs\n      | kd s t ht | kd s t hs | kd s t u hs ht | kd s t | kd s t | kd s t u hs ht\n      | kd s | kd s t u hs ht | kd s t hin | kd ? A adef \u03c3A hpdefs hwfA hf0 hf1\n      | | | | | | kd A B hwf h]; try by econstructor.\n      + econstructor => //; by eapply subtype_targs_to_Aware.\n      + econstructor => //; by eapply subtype_targs_to_Aware.\n      + econstructor; by eapply subtype_to_Aware.\n      + econstructor; by eapply subtype_to_Aware.\n      + econstructor; by eapply subtype_to_Aware.\n      + eapply SubClassDyn => //.\n        * move => k s t hst.\n          eapply subtype_to_Aware.\n          by eapply hf0.\n        * move => k s t hc.\n          eapply subtype_to_Aware.\n          by eapply hf1.\n      + eapply SubFalse => //.\n        by eapply subtype_to_Aware.\n    - destruct 1 as [ | ???????? h | ??????? h | ??????? h ].\n      + by constructor.\n      + econstructor; [ by eapply subtype_to_Aware | by eapply subtype_to_Aware | ].\n        by eapply subtype_targs_to_Aware.\n      + econstructor; [ by eapply subtype_to_Aware | ].\n        by eapply subtype_targs_to_Aware.\n      + econstructor; [ by eapply subtype_to_Aware | ].\n        by eapply subtype_targs_to_Aware.\n  Qed.\n\n  Lemma subtype_weaken \u0394 kd s t: subtype \u0394 kd s t \u2192 \u2200 \u0394', \u0394 \u2286 \u0394' \u2192 subtype \u0394' kd s t\n   with subtype_targs_weaken \u0394 kd lhs vs rhs:\n     subtype_targs \u0394 kd vs lhs rhs \u2192 \u2200 \u0394', \u0394 \u2286 \u0394' \u2192 subtype_targs \u0394' kd vs lhs rhs.\n  Proof.\n    - destruct 1 as [ kd ty | kd ty hwf | kd A \u03c3A B \u03c3B adef hadef hL hext\n      | kd A adef \u03c3A hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | | | | | kd A targs\n      | kd s t ht | kd s t hs | kd s t u hs ht | kd s t | kd s t | kd s t u hs ht\n      | kd s | kd s t u hs ht | kd s t hin | kd ? A adef \u03c3A hpdefs hwfA hf0 hf1\n      | | | | | | kd A B hwf h] => \u0394' h\u0394; try by econstructor.\n      + econstructor; [ done | done | ].\n        by eapply subtype_targs_weaken.\n      + econstructor; [ done | done | ].\n        by eapply subtype_targs_weaken.\n      + econstructor; by eapply subtype_weaken.\n      + econstructor; by eapply subtype_weaken.\n      + econstructor; by eapply subtype_weaken.\n      + apply SubConstraint.\n        by set_solver.\n      + eapply SubClassDyn => // k s t hst.\n        * eapply subtype_weaken; last done.\n          by eapply hf0.\n        * eapply subtype_weaken; last done.\n          by eapply hf1.\n      + eapply SubFalse => //.\n        by eapply subtype_weaken.\n    - destruct 1 as [ | ???????? h | ??????? h | ??????? h ] => \u0394' h\u0394.\n      + by constructor.\n      + econstructor; [ by eapply subtype_weaken | by eapply subtype_weaken | ].\n        by eapply subtype_targs_weaken.\n      + econstructor; [ by eapply subtype_weaken | ].\n        by eapply subtype_targs_weaken.\n      + econstructor; [ by eapply subtype_weaken | ].\n        by eapply subtype_targs_weaken.\n  Qed.\n\n  Lemma subtype_constraint_elim_ G kd S T:\n    subtype G kd S T \u2192\n    \u2200 \u0394 \u0394', G = \u0394 ++ \u0394' \u2192\n    (\u2200 i c, \u0394' !! i = Some c \u2192 subtype \u0394 kd c.1 c.2) \u2192\n    subtype \u0394 kd S T\n  with subtype_targs_constraint_elim_ G kd lhs vs rhs:\n    subtype_targs G kd vs lhs rhs \u2192\n    \u2200 \u0394 \u0394', G = \u0394 ++ \u0394' \u2192\n    (\u2200 i c, \u0394' !! i = Some c \u2192 subtype \u0394 kd c.1 c.2) \u2192\n    subtype_targs \u0394 kd vs lhs rhs.\n  Proof.\n    - destruct 1 as [ kd ty | kd ty hwf | kd A \u03c3A B \u03c3B adef hadef hL hext\n      | kd A adef \u03c3A hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | kd | kd | kd | kd |  kd A targs\n      | kd s t ht | kd s t hs | kd s t u hs ht | kd s t | kd s t | kd s t u hs ht | kd s\n      | kd s t u hs ht | kd s t hin | kd ? A adef \u03c3A hpdefs hwfA hf0 hf1\n      | | | | | | kd A B hwf h ]\n      => \u0394 \u0394' heq h\u0394; subst; try by econstructor.\n      + econstructor; [done | done | ].\n        by eapply subtype_targs_constraint_elim_.\n      + econstructor; [done | done | ].\n        by eapply subtype_targs_constraint_elim_.\n      + econstructor; by eapply subtype_constraint_elim_.\n      + econstructor; by eapply subtype_constraint_elim_.\n      + econstructor; by eapply subtype_constraint_elim_.\n      + apply elem_of_app in hin as [hin | hin].\n        { by apply SubConstraint. }\n        apply elem_of_list_lookup_1 in hin as [i hin].\n        by apply h\u0394 in hin.\n      + eapply SubClassDyn => // k s t hst.\n        * eapply subtype_constraint_elim_; by eauto.\n        * eapply subtype_constraint_elim_; by eauto.\n      + eapply SubFalse => //.\n        eapply subtype_constraint_elim_; by eauto.\n    - destruct 1 as [ | ???????? h | ??????? h | ??????? h ] => \u0394 \u0394' heq h\u0394; subst.\n      + by constructor.\n      + econstructor; [ by eapply subtype_constraint_elim_ | by eapply subtype_constraint_elim_ | ].\n        by eapply subtype_targs_constraint_elim_.\n      + econstructor; [ by eapply subtype_constraint_elim_ | ].\n        by eapply subtype_targs_constraint_elim_.\n      + econstructor; [ by eapply subtype_constraint_elim_ | ].\n        by eapply subtype_targs_constraint_elim_.\n  Qed.\n\n  Lemma subtype_constraint_elim kd \u0394 \u0394' S T:\n    subtype (\u0394 ++ \u0394') kd  S T \u2192\n    (\u2200 i c, \u0394' !! i = Some c \u2192 subtype \u0394 kd c.1 c.2) \u2192\n    subtype \u0394 kd S T.\n  Proof. intros; by eapply subtype_constraint_elim_. Qed.\n\n  Lemma subtype_constraint_trans \u0394 kd s t:\n    subtype \u0394 kd s t \u2192\n    \u2200 \u0394', (\u2200 i c, \u0394 !! i = Some c \u2192 subtype \u0394' kd c.1 c.2) \u2192\n    subtype \u0394' kd s t\n  with subtype_targs_constraint_trans \u0394 kd lhs vs rhs:\n    subtype_targs \u0394 kd vs lhs rhs \u2192\n    \u2200 \u0394', (\u2200 i c, \u0394 !! i = Some c \u2192 subtype \u0394' kd c.1 c.2) \u2192\n    subtype_targs \u0394' kd vs lhs rhs.\n  Proof.\n    - destruct 1 as [ kd ty | kd ty hwf | kd A \u03c3A B \u03c3B adef hadef hL hext\n      | kd A \u03c3A adef hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | kd A adef \u03c30 \u03c31 hadef hwf h\u03c3\n      | | | | | kd A targs\n      | kd s t ht | kd s t hs | kd s t u hs ht | kd s t | kd s t | kd s t u hs ht\n      | kd s | kd s t u hs ht | kd s t hin | kd ? A adef \u03c3A hpdefs hwfA hf0 hf1\n      | | | | | | kd A B hwf h] => \u0394' h\u0394; try by econstructor.\n      + eapply SubVariance; [exact hadef | assumption | ].\n        eapply subtype_targs_constraint_trans.\n        * by apply h\u03c3.\n        * exact h\u0394.\n      + eapply SubExactVariance; [exact hadef | assumption | ].\n        eapply subtype_targs_constraint_trans.\n        * by apply h\u03c3.\n        * exact h\u0394.\n      + econstructor; by eapply subtype_constraint_trans.\n      + econstructor; by eapply subtype_constraint_trans.\n      + apply SubTrans with t; by eapply subtype_constraint_trans.\n      + apply elem_of_list_lookup in hin as [i hin].\n        by apply h\u0394 in hin.\n      + eapply SubClassDyn => // k s t hst.\n        * eapply subtype_constraint_trans; by eauto.\n        * eapply subtype_constraint_trans; by eauto.\n      + eapply SubFalse => //.\n        eapply subtype_constraint_trans; by eauto.\n    - destruct 1 as [ | ???????? h | ??????? h | ??????? h ] => \u0394' h\u0394.\n      + by constructor.\n      + econstructor; [ by eapply subtype_constraint_trans | by eapply subtype_constraint_trans | ].\n        by eapply subtype_targs_constraint_trans.\n      + econstructor; [ by eapply subtype_constraint_trans | ].\n        by eapply subtype_targs_constraint_trans.\n      + econstructor; [ by eapply subtype_constraint_trans | ].\n        by eapply subtype_targs_constraint_trans.\n  Qed.\n\n  (* See Andrew Kennedy's paper:\n     Variance and Generalized Constraints for C\u266f Generics\n  *)\n  Inductive mono (vs: list variance) : lang_ty \u2192 Prop :=\n    | MonoInt : mono vs IntT\n    | MonoBool : mono vs BoolT\n    | MonoNothing : mono vs NothingT\n    | MonoMixed : mono vs MixedT\n    | MonoNull : mono vs NullT\n    | MonoNonNull : mono vs NonNullT\n    | MonoUnion s t : mono vs s \u2192 mono vs t \u2192 mono vs (UnionT s t)\n    | MonoInter s t : mono vs s \u2192 mono vs t \u2192 mono vs (InterT s t)\n    | MonoVInvGen n: vs !! n = Some Invariant \u2192 mono vs (GenT n)\n    | MonoVCoGen n: vs !! n = Some Covariant \u2192 mono vs (GenT n)\n    | MonoClass (exact:bool) cname cdef targs:\n        pdefs !! cname = Some cdef \u2192\n        (\u2200 i wi ti, cdef.(generics) !! i = Some wi \u2192\n                    targs !! i = Some ti \u2192\n                    not_contra wi \u2228 exact = true \u2192\n                    mono vs ti) \u2192\n        (\u2200 i wi ti, cdef.(generics) !! i = Some wi \u2192\n                    targs !! i = Some ti \u2192\n                    not_cov wi \u2228 exact = true \u2192\n                    mono (neg_variance <$> vs) ti) \u2192\n        mono vs (ClassT exact cname targs)\n    | MonoDynamic : mono vs DynamicT\n    | MonoSupportDyn : mono vs SupportDynT\n    | MonoThis : mono vs ThisT\n  .\n\n  Lemma monoI vs ty:\n    mono vs ty \u2192\n    match ty with\n    | ClassT exact t \u03c3 =>\n        \u2203 def, pdefs !! t = Some def \u2227\n        (\u2200 i wi ti, def.(generics) !! i = Some wi \u2192\n                    \u03c3 !! i = Some ti \u2192\n                    not_contra wi \u2228 exact = true \u2192\n                    mono vs ti) \u2227\n        (\u2200 i wi ti, def.(generics) !! i = Some wi \u2192\n                    \u03c3 !! i = Some ti \u2192\n                    not_cov wi \u2228 exact = true \u2192\n                    mono (neg_variance <$> vs) ti)\n    | UnionT A B\n    | InterT A B => mono vs A \u2227 mono vs B\n    | GenT n =>\n        match vs !! n with\n        | Some Invariant\n        | Some Covariant => True\n        | _ => False\n        end\n    | _ => True\n    end.\n  Proof.\n    move => h; inv h; simplify_eq; try by eauto.\n    - by rewrite H.\n    - by rewrite H.\n  Qed.\n\n  Definition wf_cdef_mono cdef : Prop :=\n    match cdef.(superclass) with\n    | None => True\n    | Some (parent, \u03c3) =>\n        mono cdef.(generics) (ClassT false parent \u03c3)\n    end\n  .\n\n  Definition wf_mdef_mono vs mdef : Prop :=\n    match mdef.(methodvisibility) with\n    | Private => True\n    | Public =>\n        map_Forall (\u03bb _argname, mono (neg_variance <$> vs)) mdef.(methodargs) \u2227\n        mono vs mdef.(methodrettype)\n    end.\n\n  Definition wf_cdef_methods_mono cdef : Prop :=\n   map_Forall (\u03bb _mname, wf_mdef_mono cdef.(generics)) cdef.(classmethods)\n  .\n\n  Definition invariant vs ty :=\n    mono vs ty \u2227 mono (neg_variance <$> vs) ty.\n\n  Definition field_mono vs (vfty: visibility * lang_ty) :=\n    let (vis, fty) := vfty in\n    match vis with\n    | Public => invariant vs fty\n    | Private => True\n    end.\n\n  Definition wf_field_mono cdef :=\n    map_Forall (\u03bb _fname, field_mono cdef.(generics)) cdef.(classfields).\n\n  Lemma mono_subst vs ty:\n    mono vs ty \u2192\n    bounded (length vs) ty \u2192\n    \u2200 ws \u03c3,\n    length vs = length \u03c3 \u2192\n    (\u2200 i vi ti, vs !! i = Some vi \u2192 \u03c3 !! i = Some ti \u2192\n      not_cov vi \u2192 mono (neg_variance <$> ws) ti) \u2192\n    (\u2200 i vi ti, vs !! i = Some vi \u2192 \u03c3 !! i = Some ti \u2192\n      not_contra vi \u2192 mono ws ti) \u2192\n    mono ws (subst_ty \u03c3 ty).\n  Proof.\n    induction 1 as [ | | | | | | vs s t hs his ht hit\n      | vs s t hs his ht hit | vs n hinv | vs n hco\n      | vs exact_ cname cdef targs hpdefs hcov hicov hcontra hicontra | | | ]\n      => hb ws \u03c3 hlen h0 h1 //=; try by constructor.\n    - apply boundedI in hb as [??].\n      constructor.\n      + eapply his; by eauto.\n      + eapply hit; by eauto.\n    - apply boundedI in hb as [??].\n      constructor.\n      + eapply his; by eauto.\n      + eapply hit; by eauto.\n    - destruct (\u03c3 !! n) as [ty | ] eqn:hty => //=.\n      + by eapply h1.\n      + apply lookup_lt_Some in hinv.\n        rewrite hlen in hinv.\n        apply lookup_lt_is_Some_2 in hinv.\n        rewrite hty in hinv.\n        by elim hinv.\n    - destruct (\u03c3 !! n) as [ty | ] eqn:hty => //=.\n      + by eapply h1.\n      + apply lookup_lt_Some in hco.\n        rewrite hlen in hco.\n        apply lookup_lt_is_Some_2 in hco.\n        rewrite hty in hco.\n        by elim hco.\n    - apply boundedI in hb as hb.\n      rewrite Forall_lookup in hb.\n      econstructor; first done.\n      + move => i ci ti hci hi hc.\n        apply list_lookup_fmap_inv in hi as [ty [-> hi]].\n        eapply hicov => //.\n        by apply hb in hi.\n      + move => i ci ti hci hi hc.\n        apply list_lookup_fmap_inv in hi as [ty [-> hi]].\n        eapply hicontra => //.\n        * rewrite map_length.\n          by apply hb in hi.\n        * by rewrite map_length.\n        * move => j vj tj hj htj hcj.\n          apply list_lookup_fmap_inv in hj as [vj' [-> hj]].\n          rewrite neg_variance_fmap_idem.\n          eapply h1 => //.\n          by destruct vj'.\n        * move => j vj tj hj htj hcj.\n          apply list_lookup_fmap_inv in hj as [vj' [-> hj]].\n          eapply h0 => //.\n          by destruct vj'.\n  Qed.\n\n  Lemma extends_using_mono A B \u03c3 :\n    map_Forall (\u03bb _cname, wf_cdef_mono) pdefs \u2192\n    extends_using A B \u03c3 \u2192\n    \u2200 def, pdefs !! A = Some def \u2192\n    mono def.(generics) (ClassT false B \u03c3).\n  Proof.\n    move => hmono h def hdef.\n    destruct h as [A B adef \u03c3 hadef hsuper]; simplify_eq.\n    apply hmono in hadef.\n    by rewrite /wf_cdef_mono hsuper in hadef.\n  Qed.\n\n  Derive Inversion_clear mono_classI with\n    (\u2200 vs ex t \u03c3, mono vs (ClassT ex t \u03c3)) Sort Prop.\n\n  Lemma inherits_using_mono A B \u03c3 :\n    map_Forall (\u03bb _ : string, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _cname, wf_cdef_mono) pdefs \u2192\n    inherits_using A B \u03c3 \u2192\n    \u2200 def, pdefs !! A = Some def \u2192\n    mono def.(generics) (ClassT false B \u03c3).\n  Proof.\n    move => ? hmono.\n    induction 1 as [A adef h | A B \u03c3 C \u03c3C hext h hi ] => def hdef.\n    - simplify_eq.\n      econstructor => //.\n      + move => i wi ti hgi /lookup_gen_targs -> hc.\n        case: hc => // hc.\n        destruct wi; by constructor.\n      + move => i wi ti hgi /lookup_gen_targs -> hc.\n        case: hc => // hc.\n        destruct wi => //.\n        * apply MonoVInvGen.\n          by rewrite list_lookup_fmap hgi.\n        * apply MonoVCoGen.\n          by rewrite list_lookup_fmap hgi.\n    - apply inherits_using_wf in h => //.\n      destruct h as (bdef & hbdef & hF & hwf).\n      assert (hbdef' := hbdef).\n      assert (hext' := hext).\n      apply hi in hbdef.\n      apply extends_using_mono with (def := def) in hext' => //.\n      elim/mono_classI : hext'.\n      move => ?? hnotcontra hnotcov; simplify_eq.\n      change (ClassT false C (subst_ty \u03c3 <$> \u03c3C)) with (subst_ty \u03c3 (ClassT false C \u03c3C)).\n      apply mono_subst with (generics bdef) => //.\n      + by constructor.\n      + apply extends_using_wf in hext => //.\n        destruct hext as (? & ? & ? & hwfB & _).\n        apply wf_tyI in hwfB as (? & ? & hlen & ?); simplify_eq.\n        by rewrite hlen.\n      + intros; by firstorder.\n      + intros; by firstorder.\n  Qed.\n\n  Lemma has_field_mono f t vis ty orig:\n    map_Forall (\u03bb _cname, wf_field_mono) pdefs \u2192\n    map_Forall (\u03bb _cname, wf_cdef_mono) pdefs \u2192\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _cname, wf_cdef_fields_bounded) pdefs \u2192\n    has_field f t vis ty orig \u2192\n    \u2203 def, pdefs !! t = Some def \u2227\n    match vis with\n    | Public => invariant def.(generics) ty\n    | Private => True\n    end.\n  Proof.\n    move => hwfpdefs hmono hp hfb.\n    induction 1 as [ tag tdef [vis typ] htdef hf\n      | tag targs parent tdef vis typ orig htdef hf hs h hi ].\n      - exists tdef; split => //.\n        apply hwfpdefs in htdef.\n        by apply htdef in hf.\n      - destruct hi as [def [hdef hvis]].\n        exists tdef; split => //.\n        destruct vis; last done.\n        destruct hvis as [h0 h1].\n        assert (htag := htdef).\n        apply hp in htag.\n        rewrite /wf_cdef_parent hs in htag.\n        destruct htag as (hwf & hf0); simplify_eq.\n        apply wf_tyI in hwf as (def' & hdef' & ? & ?); simplify_eq.\n        apply has_field_bounded in h => //.\n        destruct h as (pdef & ? & hbt).\n        assert (htag := htdef).\n        apply hmono in htag.\n        rewrite /wf_cdef_mono hs in htag.\n        elim/mono_classI: htag.\n        move => ?? hnotcontra hnotcov; simplify_eq.\n        split.\n        + apply mono_subst with (generics pdef) => //.\n          * intros; by firstorder.\n          * intros; by firstorder.\n        + apply mono_subst with (neg_variance <$> generics pdef) => //.\n          * by rewrite map_length.\n          * by rewrite map_length.\n          * rewrite !neg_variance_fmap_idem.\n            move => i vi ti hvi hti hc.\n            apply list_lookup_fmap_inv in hvi.\n            destruct hvi as [wi [-> hwi]].\n            eapply hnotcontra => //.\n            left.\n            by destruct wi.\n          * move => i vi ti hvi hti hc.\n            apply list_lookup_fmap_inv in hvi.\n            destruct hvi as [wi [-> hwi]].\n            eapply hnotcov => //.\n            left.\n            by destruct wi.\n  Qed.\n\n  Lemma subtype_wf \u0394 kd A B:\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    Forall wf_constraint \u0394 \u2192\n    wf_ty A \u2192 subtype \u0394 kd A B \u2192 wf_ty B.\n  Proof.\n    move => hp h\u0394 hwf.\n    induction 1 as [ kd ty | kd ty h | kd A \u03c3A B \u03c3B adef hadef hA hext\n      | kd A \u03c3A adef hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf\u03c3 h\u03c3\n      | kd A adef \u03c30 \u03c31 hadef hwf\u03c3 h\u03c3\n      | | | | | kd A args | kd s t h\n      | kd s t h | kd s t u hs his ht hit | kd s t | kd s t | kd s t u hs his ht hit | kd s\n      | kd s t u hst hist htu hitu | kd s t hin | kd ? A adef \u03c3A hwfA hadef hf hi\n      | | | | | | kd A B ? h hi ]\n      => //=; try (by constructor).\n    - destruct hext as [A B adef' \u03c3B hadef' hsuper]; simplify_eq.\n      rewrite /map_Forall_lookup in hp.\n      apply hp in hadef.\n      rewrite /wf_cdef_parent hsuper in hadef.\n      destruct hadef as (hwfB & hF).\n      apply wf_tyI in hwfB as (? & ? & ? & hwfB).\n      econstructor; first done.\n      + by rewrite map_length.\n      + rewrite Forall_lookup => k ty.\n        rewrite list_lookup_fmap.\n        destruct (\u03c3B !! k) as [ tyk | ] eqn:hty => //=.\n        case => <-.\n        apply wf_ty_subst; first by apply wf_ty_classI in hwf.\n        rewrite Forall_lookup in hwfB.\n        by eauto.\n    - apply wf_tyI in hwf as [? [? [??]]]; simplify_eq; by econstructor.\n    - apply length_subtype_targs_v1 in h\u03c3.\n      apply wf_tyI in hwf as [? [hadef' [? hwf0]]]; simplify_eq; econstructor.\n      + exact hadef'.\n      + by rewrite h\u03c3.\n      + rewrite Forall_lookup => k ty hty.\n        rewrite !Forall_lookup in hwf\u03c3, hwf0.\n        by eauto.\n    - apply length_subtype_targs_v1 in h\u03c3.\n      apply wf_tyI in hwf as [? [hadef' [? hwf0]]]; simplify_eq; econstructor.\n      + exact hadef'.\n      + by rewrite -h\u03c3 fmap_length.\n      + rewrite Forall_lookup => k ty hty.\n        rewrite !Forall_lookup in hwf\u03c3, hwf0.\n        by eauto.\n    - apply wf_tyI in hwf as [??]; by eauto.\n    - apply wf_tyI in hwf as [??]; by eauto.\n    - apply wf_tyI in hwf as [??]; by eauto.\n    - constructor; by eauto.\n    - by eauto.\n    - rewrite Forall_forall in h\u0394.\n      by apply h\u0394 in hin as [].\n  Qed.\n\n  Lemma subtype_subst \u0394 kd A B:\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _, wf_cdef_constraints_bounded) pdefs \u2192\n    subtype \u0394 kd A B \u2192 \u2200 \u03c3,\n    Forall wf_ty \u03c3 \u2192\n    subtype (subst_constraints \u03c3 \u0394) kd (subst_ty \u03c3 A) (subst_ty \u03c3 B)\n  with subtype_targs_subst \u0394 kd vs As Bs:\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _, wf_cdef_constraints_bounded) pdefs \u2192\n    subtype_targs \u0394 kd vs As Bs \u2192 \u2200 \u03c3,\n    Forall wf_ty \u03c3 \u2192\n    subtype_targs (subst_constraints \u03c3 \u0394) kd vs (subst_ty \u03c3 <$> As) (subst_ty \u03c3 <$> Bs).\n  Proof.\n    - move => hp hb.\n      destruct 1 as [ kd ty | kd ty h | kd A \u03c3A B \u03c3B adef hadef hA hext\n      | kd A \u03c3A adef hadef hL\n      | kd A adef \u03c30 \u03c31 hadef hwf\u03c3 h\u03c301\n      | kd A adef \u03c30 \u03c31 hadef hwf\u03c3 h\u03c301\n      | | | | | kd A args\n      | kd s t h | kd s t h | kd s t u hs ht | kd s t | kd s t | kd s t u hs ht | kd s\n      | kd s t u hst htu | kd s t hin | kd ? A adef \u03c3A hadef hwfA hf0 hf1\n      | | | | | | kd A B hwf h ]\n      => \u03c3 h\u03c3 => /=; try (by constructor).\n      + constructor.\n        by apply wf_ty_subst.\n      + rewrite map_subst_ty_subst.\n        * econstructor; [exact hadef | | by assumption].\n          by rewrite map_length.\n        * apply extends_using_wf in hext; last done.\n          destruct hext as (? & hadef' & hF & hwfB & _).\n          apply wf_tyI in hwfB as [? [? [??]]]; simplify_eq.\n          by rewrite hA.\n      + eapply SubExact => //.\n        by rewrite fmap_length.\n      + eapply SubVariance.\n        * exact hadef.\n        * rewrite Forall_forall => ty /elem_of_list_fmap [ty' [-> hin]].\n          apply wf_ty_subst => //.\n          rewrite Forall_forall in hwf\u03c3; by apply hwf\u03c3 in hin.\n        * apply subtype_targs_subst; by assumption.\n      + eapply SubExactVariance.\n        * exact hadef.\n        * rewrite Forall_forall => ty /elem_of_list_fmap [ty' [-> hin]].\n          apply wf_ty_subst => //.\n          rewrite Forall_forall in hwf\u03c3; by apply hwf\u03c3 in hin.\n        * apply subtype_targs_subst; by assumption.\n      + constructor.\n        by apply wf_ty_subst.\n      + constructor.\n        by apply wf_ty_subst.\n      + constructor; by apply subtype_subst.\n      + constructor; by apply subtype_subst.\n      + econstructor; by apply subtype_subst.\n      + apply SubConstraint.\n        apply elem_of_list_lookup_1 in hin as [i hin].\n        apply elem_of_list_lookup; exists i.\n        by rewrite /subst_constraints list_lookup_fmap hin.\n      + eapply SubClassDyn => //.\n        * apply wf_tyI in hwfA as [? [? [? hwf]]]; simplify_eq.\n          rewrite Forall_lookup in hwf.\n          econstructor => //.\n          { by rewrite fmap_length. }\n          rewrite Forall_lookup  => k ty h.\n          apply list_lookup_fmap_inv in h as [? [-> h]].\n          apply wf_ty_subst => //.\n          by eauto.\n        * move => k s t hst.\n          apply list_lookup_fmap_inv in hst as [[u v] [[= -> ->] h]].\n          assert (hbst: bounded_constraint (length \u03c3A) (u, v)).\n          { apply wf_tyI in hwfA as [? [? [hlen ?]]]; simplify_eq.\n            rewrite hlen; by eapply \u0394sdt_bounded in h.\n          }\n          destruct hbst as [].\n          rewrite -!subst_ty_subst //.\n          eapply subtype_subst; [done | done | | done].\n          apply hf0 with k.\n          by rewrite /subst_constraints list_lookup_fmap h.\n        * move => k s t hst.\n          assert (hbst: bounded_constraint (length \u03c3A) (s, t)).\n          { apply wf_tyI in hwfA as [? [? [hlen ?]]]; simplify_eq.\n            apply hb in hadef.\n            rewrite /wf_cdef_constraints_bounded Forall_lookup in hadef.\n            apply hadef in hst.\n            by rewrite hlen.\n          }\n          destruct hbst as [].\n          rewrite -!subst_ty_subst //.\n          eapply subtype_subst; [done | done | | done].\n          by eapply hf1.\n      + eapply SubFalse.\n        * by apply wf_ty_subst.\n        * change IntT with (subst_ty \u03c3 IntT).\n          change BoolT with (subst_ty \u03c3 BoolT).\n          by eapply subtype_subst.\n    - move => hp hb.\n      destruct 1 as [ | ?????? h0 h1 h | ?????? h0 h | ?????? h0 h] => \u03c3 h\u03c3 /=.\n      + by constructor.\n      + constructor.\n        * by apply subtype_subst.\n        * by apply subtype_subst.\n        * by apply subtype_targs_subst.\n      + constructor.\n        * by apply subtype_subst.\n        * by apply subtype_targs_subst.\n      + constructor.\n        * by apply subtype_subst.\n        * by apply subtype_targs_subst.\n  Qed.\n\n  (* Sanity checks: Some derived rules *)\n  Lemma subtype_union_comm \u0394: \u2200 A B,\n    wf_ty A \u2192 wf_ty B \u2192\n    \u0394 \u22a2 (UnionT A B) <: (UnionT B A).\n  Proof. by auto. Qed.\n\n  Lemma subtype_inter_comm \u0394 : \u2200 A B,\n    wf_ty A \u2192 wf_ty B \u2192\n    \u0394 \u22a2 (InterT A B) <: (InterT B A).\n  Proof. by auto. Qed.\n\n  Lemma subtype_union_assoc \u0394:\n    \u2200 A B C,\n    wf_ty A \u2192 wf_ty B \u2192 wf_ty C \u2192\n    \u0394 \u22a2 (UnionT (UnionT A B) C) <: (UnionT A (UnionT B C)).\n  Proof.\n    move => A B C wfA wfB wfC.\n    apply SubUnionLower; last by eauto.\n    apply SubUnionLower; last by eauto.\n    apply SubUnionUpper1.\n    constructor; by eauto.\n  Qed.\n\n  Lemma subtype_inter_assoc \u0394:\n    \u2200 A B C,\n    wf_ty A \u2192 wf_ty B \u2192 wf_ty C \u2192\n    \u0394 \u22a2 (InterT (InterT A B) C) <: (InterT A (InterT B C)).\n  Proof. by eauto. Qed.\n\n  Lemma \u0394entails_app kd \u03940 \u03941:\n    \u0394entails kd \u03940 \u03941 \u2192 \u2200 \u0394, \u0394entails kd (\u0394 ++ \u03940) (\u0394 ++ \u03941).\n  Proof.\n    move => h\u039401 \u0394 k [s t] /=.\n    rewrite lookup_app.\n    destruct (\u0394 !! k) as [[s0 t0] | ] eqn:h0; rewrite h0 /=.\n    - case => <- <-.\n      eapply SubConstraint.\n      apply elem_of_list_lookup_2 in h0.\n      by set_solver.\n    - move => h1.\n      apply h\u039401 in h1.\n      eapply subtype_weaken with \u03940 => //.\n      by set_solver.\n  Qed.\n\n  (* Typing contexts *)\n  Definition local_tys := stringmap lang_ty.\n\n  (* Subtype / Inclusion of typing contexts *)\n  Definition lty_sub \u0394 kd (\u03930 \u03931: local_tys) :=\n    \u2200 k A, \u03931 !! k = Some A \u2192 \u2203 B, \u03930 !! k = Some B \u2227 subtype \u0394 kd B A.\n\n  Notation \"\u0394 \u22a2 \u03930 <:< \u03931\" := (lty_sub \u0394 Plain \u03930 \u03931) (\u03930 at next level, at level 70, no associativity).\n\n  Definition wf_lty (\u0393: local_tys) := map_Forall (\u03bb _, wf_ty) \u0393.\n\n  Lemma insert_wf_lty x ty \u0393 :\n    wf_ty ty \u2192 wf_lty \u0393 \u2192 wf_lty (<[x := ty]>\u0393).\n  Proof.\n    rewrite /wf_lty /= => h hl.\n    rewrite map_Forall_lookup => k tk.\n    rewrite lookup_insert_Some.\n    case => [[? <-] | [? hk]]; first done.\n    by apply hl in hk.\n  Qed.\n\n  Lemma lty_sub_constraint_trans \u0394 kd \u03930 \u03931:\n    lty_sub \u0394 kd \u03930 \u03931 \u2192\n    \u2200 \u0394', \u0394entails kd \u0394' \u0394 \u2192\n    lty_sub \u0394' kd \u03930 \u03931.\n  Proof.\n    move => h\u0393 \u0394' h\u0394 k A hA.\n    apply h\u0393 in hA as (B & hB & h).\n    exists B; split => //.\n    by eapply subtype_constraint_trans.\n  Qed.\n\n  Definition bounded_lty n (\u0393: local_tys) := map_Forall (\u03bb _, bounded n) \u0393.\n\n  Lemma insert_bounded_lty n x ty \u0393 :\n    bounded n ty \u2192 bounded_lty n \u0393 \u2192 bounded_lty n (<[x := ty]>\u0393).\n  Proof.\n    rewrite /bounded_lty /= => h hl.\n    rewrite map_Forall_lookup => k tk.\n    rewrite lookup_insert_Some.\n    case => [[? <-] | [? hk]]; first done.\n    by apply hl in hk.\n  Qed.\n\n  Lemma bounded_lty_ge \u0393 n m:\n    bounded_lty n \u0393 \u2192 m \u2265 n \u2192 bounded_lty m \u0393.\n  Proof.\n    move => /map_Forall_lookup h1 hge k ty h.\n    apply h1 in h.\n    by eapply bounded_ge.\n  Qed.\n\n  (* We allow method override: children can redeclare a method if types\n   * are compatible:\n   * - return type must be a subtype\n   * - argument types must be a supertype\n   *)\n  Definition mdef_incl (\u0394: list constraint) (sub super: methodDef) :=\n    dom sub.(methodargs) = dom super.(methodargs) \u2227\n    (\u2200 k A B, sub.(methodargs) !! k = Some A \u2192\n    super.(methodargs) !! k = Some B \u2192 \u0394 \u22a2 B <D: A) \u2227\n    \u0394 \u22a2 sub.(methodrettype) <D: super.(methodrettype).\n\n  Lemma mdef_incl_reflexive \u0394: reflexive _ (mdef_incl \u0394).\n  Proof.\n    move => mdef; split; first done.\n    split; last done.\n    by move => k A B -> [] ->.\n  Qed.\n\n  Lemma mdef_incl_subst \u0394 mdef0 mdef1 \u03c3 :\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _, wf_cdef_constraints_bounded) pdefs \u2192\n    Forall wf_ty \u03c3 \u2192\n    mdef_incl \u0394 mdef0 mdef1 \u2192\n    mdef_incl (subst_constraints \u03c3 \u0394) (subst_mdef \u03c3 mdef0) (subst_mdef \u03c3 mdef1).\n  Proof.\n    move => hp hb h\u03c3.\n    rewrite /mdef_incl /subst_mdef /=.\n    case => [hdom [hargs hret]]; split; first by rewrite !dom_fmap_L.\n    split; last by apply subtype_subst.\n    move => k A B.\n    rewrite !lookup_fmap_Some.\n    case => tyA [<- hA].\n    case => tyB [<- hB].\n    apply subtype_subst => //.\n    by eapply hargs.\n  Qed.\n\n  (* Any redeclared public method must correctly override its parent methods.\n   * Also, if a parent method is public, it can't be overrided with a private\n   * method.\n   *\n   *\n   * Also, a class cannot redeclare a _private_ method if it is already\n   *  present in any of its parents definition.\n   *\n   * This is a restriction we aim to lift later on. This first version\n   * is here to enable desugaring a private field into a private getter/setter\n   * pair of methods.\n   *\n   * TODO: remove this restriction and allow private methods to\n   * be redefined in sub classes.\n   *)\n  Definition wf_method_override :=\n    \u2200 A B adef bdef m \u03c3 mA mB,\n    pdefs !! A = Some adef \u2192\n    pdefs !! B = Some bdef \u2192\n    inherits_using A B \u03c3 \u2192\n    adef.(classmethods) !! m = Some mA \u2192\n    bdef.(classmethods) !! m = Some mB \u2192\n    match mB.(methodvisibility), mA.(methodvisibility) with\n    | Public, Public => mdef_incl adef.(constraints) mA (subst_mdef \u03c3 mB)\n    | Public, Private => False\n    | Private, _ => False (* TODO : lift this *)\n    end.\n\n  (* Key lemma for soundness of method call:\n   * if A <: B and they both have a method m (from resp. origA, origB) which\n   * is public in B, then the origins must be ordered in the same way,\n   * meaning origA <: origB.\n   * This implies some relations on all the inheritance substitution.\n   *)\n  Lemma has_method_ordered A B \u03c3AB m origA mdefA origB mdefB:\n    wf_method_override \u2192\n    map_Forall (\u03bb _cname, wf_cdef_parent) pdefs \u2192\n    map_Forall (\u03bb _, wf_cdef_constraints_bounded) pdefs \u2192\n    map_Forall (\u03bb _cname, cdef_methods_bounded) pdefs \u2192\n    inherits_using A B \u03c3AB \u2192\n    has_method m A origA mdefA \u2192\n    has_method m B origB mdefB \u2192\n    (* mdefB.(methodvisibility) = Public \u2192 *)\n    \u2203 oA oB \u03c3A \u03c3B mA mB,\n      pdefs !! origA = Some oA \u2227\n      pdefs !! origB = Some oB \u2227\n      oA.(classmethods) !! m = Some mA \u2227\n      oB.(classmethods) !! m = Some mB \u2227\n      inherits_using A origA \u03c3A \u2227\n      inherits_using B origB \u03c3B \u2227\n      mdefA = subst_mdef \u03c3A mA \u2227\n      mdefB = subst_mdef \u03c3B mB \u2227\n      (* mA.(methodvisibility) = Public \u2227 *)\n      mdef_incl (subst_constraints \u03c3A oA.(constraints)) mdefA (subst_mdef \u03c3AB mdefB) \u2227\n      (* A <: B <: orig A = orig B *)\n      ((inherits_using B origA \u03c3B \u2227\n          origA = origB \u2227\n          mA = mB \u2227\n          subst_ty \u03c3AB <$> \u03c3B = \u03c3A) \u2228\n      (* A <: origA <: B <: origB *)\n       (\u2203 \u03c3, inherits_using origA B \u03c3 \u2227\n             subst_ty \u03c3A <$> \u03c3 = \u03c3AB \u2227\n             mdef_incl oA.(constraints) mA (subst_mdef \u03c3 (subst_mdef \u03c3B mB)))).\n  Proof.\n    move => ho hp hb hm hin hA hB (* hvB *).\n    assert (hhA := hA).\n    assert (hhB := hB).\n    apply has_method_from_def in hA => //.\n    apply has_method_from_def in hB => //.\n    destruct hA as (oadef & oaorig & hoA & hmA & hmoA & [\u03c3A [hiA ->]]).\n    destruct hB as (obdef & oborig & hoB & hmB & hmoB & [\u03c3B [hiB ->]]).\n    exists oadef, obdef, \u03c3A, \u03c3B, oaorig, oborig.\n    do 8 split => //.\n    destruct (inherits_using_chain _ _ _ hp hin _ _ hiA) as [\u03c3'' [ [<- h] | [<- h]]].\n    - destruct (has_method_below_orig _ _ _ _ hp hm hhA _ _ _ hin h) as\n        (? & ? & mbdef & ? & ? & hbm & ->); simplify_eq.\n      destruct (has_method_fun _ _ _ _ _ _ hhB hbm) as [-> ->].\n      simplify_eq.\n      (* split; first done. *)\n      assert (mdef_bounded (length \u03c3'') oaorig).\n      { assert (hoA' := hoA).\n        apply hm in hoA.\n        apply hoA in hmA.\n        apply inherits_using_wf in h => //.\n        destruct h as (? & ? & ? & h & _).\n        apply wf_tyI in h as [? [? [hlen ?]]]; simplify_eq.\n        by rewrite hlen.\n      }\n      split.\n      { rewrite subst_mdef_mdef //.\n        by apply mdef_incl_reflexive.\n      }\n      left.\n      repeat split => //.\n      assert (hh : inherits_using A origA (subst_ty \u03c3AB <$> \u03c3B))\n        by by eapply inherits_using_trans.\n      by rewrite (inherits_using_fun _ _ _ hp hiA _ hh).\n    - assert (mdef_bounded (length \u03c3B) oborig).\n      { assert (hoB' := hoB).\n        apply hm in hoB.\n        apply hoB in hmB.\n        apply inherits_using_wf in hiB => //.\n        destruct hiB as (? & ? & ? & hiB & _).\n        apply wf_tyI in hiB as [? [? [hlen ?]]]; simplify_eq.\n        by rewrite hlen.\n      }\n      assert (mdef_bounded (length \u03c3'') (subst_mdef \u03c3B oborig)).\n      { apply mdef_bounded_subst with (n := length \u03c3B) => //.\n        apply inherits_using_wf in hiB => //.\n        destruct hiB as (bdef & ? & ? & ? & _).\n        apply inherits_using_wf in h => //.\n        destruct h as (? & ? & ? & h & _).\n        apply wf_tyI in h as [? [? [hlen ?]]]; simplify_eq.\n        by rewrite hlen.\n      }\n      assert (hh: oaorig.(methodvisibility) = Public \u2227\n        mdef_incl (constraints oadef) oaorig (subst_mdef \u03c3'' (subst_mdef \u03c3B oborig))).\n      { rewrite subst_mdef_mdef //.\n        assert (hino: inherits_using origA origB (subst_ty \u03c3'' <$> \u03c3B))\n          by by eapply inherits_using_trans.\n        move: (ho _ _ _ _ _ _ _ _ hoA hoB hino hmA hmB).\n        (* rewrite hvB. *)\n        (* by destruct oaorig.(methodvisibility). *)\n        (**)\n        destruct oborig.(methodvisibility); last done.\n        destruct oaorig.(methodvisibility); last done.\n        done.\n        (**)\n      }\n      destruct hh as [? ?].\n      (* split; first done. *)\n      split.\n      { rewrite -subst_mdef_mdef //.\n        apply mdef_incl_subst => //.\n        apply inherits_using_wf in hiA => //.\n        destruct hiA as (? & ? & ? & hiA & _).\n        by apply wf_ty_classI in hiA.\n      }\n      right.\n      exists \u03c3''.\n      by repeat split => //.\n  Qed.\nEnd SubtypeFacts.\n\n(* Hints and notations are local to the section. Re-exporting them *)\nGlobal Hint Constructors subtype : core.\nGlobal Hint Constructors subtype_targs : core.\n", "meta": {"author": "facebookresearch", "repo": "shack", "sha": "e51cfcd3e72a0941feb337f9e152f6c429f3af63", "save_path": "github-repos/coq/facebookresearch-shack", "path": "github-repos/coq/facebookresearch-shack/shack-e51cfcd3e72a0941feb337f9e152f6c429f3af63/theories/subtype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.18609547978380675}}
{"text": "(*! Language | Semantics of Lowered K\u00f4ika programs !*)\nRequire Export Koika.Common Koika.Environments Koika.Syntax Koika.TypedSemantics Koika.LoweredSyntax.\n\nSection Interp.\n  Context {pos_t var_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 -> nat}.\n  Context {Sigma: ext_fn_t -> CExternalSignature}.\n\n  Context {REnv: Env reg_t}.\n\n  Notation Log := (CLog R REnv).\n\n  Notation rule := (rule pos_t var_t R Sigma).\n  Notation action := (action pos_t var_t R Sigma).\n  Notation scheduler := (scheduler pos_t rule_name_t).\n\n  Definition lcontext (sig: lsig) :=\n    context Bits.bits sig.\n\n  Section Action.\n    Context (r: REnv.(env_t) (fun idx => bits (R idx))).\n    Context (sigma: forall f, CSig_denote (Sigma f)).\n\n    Fixpoint interp_action\n             {sig: lsig}\n             {sz}\n             (Gamma: lcontext sig)\n             (sched_log: Log)\n             (action_log: Log)\n             (a: action sig sz)\n    : option (Log * bits sz * (lcontext sig)) :=\n      match a in LoweredSyntax.action _ _ _ _ ts sz return (lcontext ts -> option (Log * bits sz * (lcontext ts)))  with\n      | Fail sz => fun _ =>\n        None\n      | Var k m => fun Gamma =>\n        Some (action_log, cassoc m Gamma, Gamma)\n      | Const cst => fun Gamma =>\n        Some (action_log, cst, Gamma)\n      | Seq r1 r2 => fun Gamma =>\n        let/opt3 action_log, _, Gamma := interp_action Gamma sched_log action_log r1 in\n        interp_action Gamma sched_log action_log r2\n      | Assign k m ex => fun Gamma =>\n        let/opt3 action_log, v, Gamma := interp_action Gamma sched_log action_log ex in\n        Some (action_log, Ob, creplace m v Gamma)\n      | @Bind _ _ _ _ _ _ sig _ sz sz' ex body => fun (Gamma : lcontext sig) =>\n        let/opt3 action_log1, v, Gamma := interp_action Gamma sched_log action_log ex in\n        let/opt3 action_log2, v, Gamma := interp_action (CtxCons sz v Gamma) sched_log action_log1 body in\n        Some (action_log2, v, ctl Gamma)\n      | If cond tbranch fbranch => fun Gamma =>\n        let/opt3 action_log, cond, Gamma := interp_action Gamma sched_log action_log cond in\n        if Bits.single cond then\n          interp_action Gamma sched_log action_log tbranch\n        else\n          interp_action Gamma sched_log action_log fbranch\n      | Read prt idx => fun Gamma =>\n        if may_read sched_log prt idx then\n          Some (log_cons idx (LE LogRead prt tt) action_log,\n                match prt with\n                | P0 => REnv.(getenv) r idx\n                | P1 => match latest_write0 (log_app action_log sched_log) idx with\n                       | Some v => v\n                       | None => REnv.(getenv) r idx\n                       end\n                end,\n                Gamma)\n        else None\n      | Write prt idx val => fun Gamma =>\n        let/opt3 action_log, val, Gamma_new := interp_action Gamma sched_log action_log val in\n        if may_write sched_log action_log prt idx then\n          Some (log_cons idx (LE LogWrite prt val) action_log, Bits.nil, Gamma_new)\n        else None\n      | Unop fn arg1 => fun Gamma =>\n        let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n        Some (action_log, (CircuitPrimSpecs.sigma1 fn) arg1, Gamma)\n      | Binop fn arg1 arg2 => fun Gamma =>\n        let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n        let/opt3 action_log, arg2, Gamma := interp_action Gamma sched_log action_log arg2 in\n        Some (action_log, (CircuitPrimSpecs.sigma2 fn) arg1 arg2, Gamma)\n      | ExternalCall fn arg1 => fun Gamma =>\n        let/opt3 action_log, arg1, Gamma := interp_action Gamma sched_log action_log arg1 in\n        Some (action_log, sigma fn arg1, Gamma)\n      | APos _ a => fun Gamma =>\n        interp_action Gamma sched_log action_log a\n      end Gamma.\n\n    Definition interp_rule (sched_log: Log) (rl: rule) : option Log :=\n      match interp_action CtxEmpty sched_log log_empty rl with\n      | Some (l, _, _) => Some l\n      | None => None\n      end.\n  End Action.\n\n  Section Scheduler.\n    Context (r: REnv.(env_t) (fun idx => bits (R idx))).\n    Context (sigma: forall f, CSig_denote (Sigma f)).\n    Context (rules: rule_name_t -> rule).\n\n    Fixpoint interp_scheduler'\n             (sched_log: Log)\n             (s: scheduler)\n             {struct s} :=\n      let interp_try rl s1 s2 :=\n          match interp_rule r sigma sched_log (rules rl) with\n          | Some l => interp_scheduler' (log_app l sched_log) s1\n          | None => interp_scheduler' sched_log s2\n          end in\n      match s with\n      | Done => sched_log\n      | Cons r s => interp_try r s s\n      | Try r s1 s2 => interp_try r s1 s2\n      | SPos _ s => interp_scheduler' sched_log s\n      end.\n\n    Definition interp_scheduler (s: scheduler) :=\n      interp_scheduler' log_empty s.\n  End Scheduler.\n\n  Definition interp_cycle (sigma: forall f, CSig_denote (Sigma f)) (rules: rule_name_t -> rule)\n             (s: scheduler) (r: REnv.(env_t) (fun idx => bits (R idx))) :=\n      commit_update r (interp_scheduler r sigma rules s).\nEnd Interp.\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/LoweredSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.18600595915872903}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.ADT.\nRequire Import Platform.Cito.RepInv.\n\nModule Make (Import E : ADT) (Import M : RepInv E).\n\n  Require Import Platform.Cito.VerifCondOkNonCall.\n  Module Import VerifCondOkNonCallMake := Make E M.\n  Require Import Platform.Cito.VerifCondOkNonCall2.\n  Module Import VerifCondOkNonCall2Make := Make E M.\n  Require Import Platform.Cito.VerifCondOkCall.\n  Module Import VerifCondOkCallMake := Make E M.\n  Import CompileStmtSpecMake.\n  Import InvMake.\n  Import Semantics.\n  Import SemanticsMake.\n  Import InvMake2.\n\n  Section TopSection.\n\n    Require Import Platform.AutoSep.\n\n    Variable vars : list string.\n\n    Variable temp_size : nat.\n\n    Variable imports : LabelMap.t assert.\n\n    Variable imports_global : importsGlobal imports.\n\n    Variable modName : string.\n\n    Variable rv_postcond : W -> vals -> Prop.\n\n    Notation do_compile := (CompileStmtImplMake.compile vars temp_size rv_postcond imports_global modName).\n\n    Lemma verifCond_ok :\n      forall s k (pre : assert),\n        vcs (verifCond vars temp_size s k rv_postcond pre) ->\n        vcs\n          (VerifCond (do_compile s k pre)).\n    Proof.\n\n      unfold verifCond, imply; induction s.\n\n      eapply verifCond_ok_skip; eauto.\n      eapply verifCond_ok_seq; eauto.\n      eapply verifCond_ok_if; eauto.\n      eapply verifCond_ok_while; eauto.\n\n      eapply verifCond_ok; eauto.\n\n      eapply verifCond_ok_label; eauto.\n      eapply verifCond_ok_assign; eauto.\n\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/VerifCondOk.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18600595041716997}}
{"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(** Architecture-dependent parameters for ARM *)\n\nRequire Import ZArith.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\n\nDefinition big_endian := false.\n\nNotation align_int64 := 8%Z (only parsing).\nNotation align_float64 := 8%Z (only parsing).\n\nProgram Definition default_pl : bool * nan_pl 53 := (false, nat_iter 51 xO xH).\n\nDefinition choose_binop_pl (s1: bool) (pl1: nan_pl 53) (s2: bool) (pl2: nan_pl 53) :=\n  (** Choose second NaN if pl2 is sNaN but pl1 is qNan.\n      In all other cases, choose first NaN *)\n  (Pos.testbit (proj1_sig pl1) 51 &&\n   negb (Pos.testbit (proj1_sig pl2) 51))%bool.\n\nGlobal Opaque big_endian default_pl choose_binop_pl.\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/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.18600594893631}}
{"text": "Require Import Coq.Strings.String.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype.\nFrom deriving Require Import deriving.\nFrom extructures Require Import ord fset fmap ffun fperm.\n\nFrom CoqUtils Require Import nominal.\n\nFrom memsafe Require Import basic structured.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Separation.\n\nLocal Open Scope fset_scope.\nLocal Open Scope state_scope.\n\nLocal Notation locals := {fmap string -> value}.\nLocal Notation heap := {fmap ptr -> value}.\nLocal Notation state := (locals * heap)%type.\n\nImplicit Type (e : expr) (c : com) (ls : locals) (h : heap)\n              (s : state) (\u03c0 : {fperm name}) (v : value)\n              (P Q R : state -> Prop).\n\nDefinition triple P c Q :=\n  forall s k, fsubset (vars_c c) (domm s.1) ->\n              P s ->\n              match eval_com c s k with\n              | Done rs' => pbindr fset0 Q rs'\n              | Error    => False\n              | NotYet   => True\n              end.\n\nDefinition separating_conjunction P Q s :=\n  exists ls h1 h2,\n    [/\\ s = (ls, unionm h1 h2),\n        P (ls, h1),\n        Q (ls, h2) &\n        fdisjoint (names (domm h1)) (names (domm h2)) ].\n\nLocal Infix \"*\" := separating_conjunction.\n\nDefinition ind_vars (xs : {fset string}) P :=\n  forall s s', P s ->\n               (forall x, x \\notin xs -> s.1 x = s'.1 x) ->\n               s.2 = s'.2 ->\n               P s'.\n\nLemma sc_lift P Q A ls h1 h2 :\n  pbindr fset0 P (hide A (Restr (ls, h1))) ->\n  pbindr fset0 Q (hide A (Restr (ls, h2))) ->\n  fdisjoint (names (domm h1)) (names (domm h2)) ->\n  pbindr fset0 (P * Q) (hide A (Restr (ls, unionm h1 h2))).\nProof.\nmove=> Ph1 Qh2 dis A12 /= s /restr_eqP /= [\u03c0 ids_\u03c0 [eA es]] _.\nmove: ids_\u03c0.\nrewrite fsetDUl /= namesm_union_disjoint ?fdisjoint_names_domm //.\nrewrite (fsetDUl (names h1)) -[names ls :\\: A]fsetUid -fsetUA.\nrewrite [in X in _ :|: X]fsetUC 2!fsetUA -fsetUA (fsetUC (names h2 :\\: A)).\nrewrite -2!fsetDUl -(namespE (ls, h1)) -(namespE (ls, h2)) fdisjointUr.\ncase/andP=> [dis_\u03c01 dis_\u03c02].\nexists (rename \u03c0 ls), (rename \u03c0 h1), (rename \u03c0 h2).\nrewrite -es pair_eqvar unionm_eqvar; split=> //.\n- apply: (Ph1 (rename \u03c0 A)); last exact: fdisjoint0s.\n  rewrite -[LHS](@renameJ _ \u03c0) ?names_hider ?namesrE //.\n  by rewrite hide_eqvar Restr_eqvar pair_eqvar.\n- apply: (Qh2 (rename \u03c0 A)); last exact: fdisjoint0s.\n  rewrite -[LHS](@renameJ _ \u03c0) ?names_hider ?namesrE //.\n  by rewrite hide_eqvar Restr_eqvar pair_eqvar.\nby rewrite -![domm (rename _ _)]domm_eqvar -fdisjoint_eqvar renameT.\nQed.\n\nLemma frame_rule P Q R c :\n  triple P c Q ->\n  ind_vars (mod_vars_c c) R ->\n  triple (P * R) c (Q * R).\nProof.\nmove=> t ind s k sub [ls [h1 [h2 [e ph1 ph2 dis]]]].\nrewrite {}e {s} in sub *.\nmove/(_ (ls, h1) k sub ph1): t.\nrewrite -{2}[ls]unionm0.\ncase ev: (eval_com c (ls, h1) k)=> [rs'| |] //=; first last.\n  by rewrite (@frame_loop _ (ls, h1) (emptym, h2)).\nmove=> Q_rs'; rewrite (@frame_ok _ (ls, h1) (emptym, h2) _ _ sub dis ev).\ncase: rs' / (restrP (names (ls, h1) :|: names ((emptym, h2) : state)) rs')\n          Q_rs' ev => /= A [ls' h1'] dis'' sub' Q_rs' ev.\nmove: dis''; rewrite fdisjointUl=> /andP [dis1 dis2].\nrewrite maprE // /stateu unionm0.\nrewrite namespE /= namesm_empty fset0U in dis2.\napply: sc_lift=> //.\n  move=> /= A' s2' /restr_eqP [\u03c0].\n  rewrite namespE fsetDUl /= (fsetDidPl dis2) fdisjointUr.\n  case/andP=> dis_ls' dis_h2.\n  rewrite pair_eqvar /= (renameJ dis_h2) => - [eA <-] _.\n  apply/ind; eauto=> /= x nin_x.\n  move: (mod_vars_cP ev nin_x); rewrite maprE ?fdisjoint0s //=.\n  move/(congr1 (@oexpose _)); rewrite oexposeE oexposeE0.\n  case: ifP=> // dis''' [<-].\n  rewrite renamemE renameT renameJ // fdisjointC.\n  rewrite fdisjointC in dis_ls'.\n  apply/fdisjoint_trans; eauto.\n  apply/fsubsetP=> /= i in_i; apply/fsetDP; split.\n    case e: getm in_i=> [v|]; try by rewrite in_fset0.\n    move=> in_i; apply/namesmP/@PMFreeNamesVal; eauto.\n  by move: i in_i; apply/fdisjointP; rewrite fdisjointC.\nhave := @eval_com_blocks _ (ls, h1) c k dis.\nrewrite ev pbind_resE /=.\nhave: fdisjoint (names (domm h2)) A.\n  by apply: fdisjoint_trans dis2; eapply nom_finsuppP; finsupp.\nmove: (names (domm h2)) => A' disA'.\nby rewrite pbindrE //= namesfsnE.\nQed.\n\nDefinition weak_triple P c Q :=\n  forall s k,\n    fsubset (vars_c c) (domm s.1) ->\n    P s ->\n    if eval_com c s k is Done rs' then\n      pbindr fset0 Q rs'\n    else True.\n\nDefinition strong_separating_conjunction P Q s :=\n  exists ls h1 h2,\n    [/\\ s = (ls, unionm h1 h2),\n        P (ls, h1),\n        Q (ls, h2) &\n        fdisjoint (names (ls, h1)) (names (domm h2)) ].\n\nLocal Infix \"*>\" := strong_separating_conjunction (at level 20).\n\nLemma ssc_lift P Q A ls h1 h2 :\n  pbindr fset0 P (hide A (Restr (ls, h1))) ->\n  pbindr fset0 Q (hide A (Restr (ls, h2))) ->\n  fdisjoint (names (ls, h1)) (names (domm h2)) ->\n  pbindr fset0 (P *> Q) (hide A (Restr (ls, unionm h1 h2))).\nProof.\nmove=> Ph1 Qh2 dis A12 /= s /restr_eqP /= [\u03c0 ids_\u03c0 [eA es]] _.\nmove: ids_\u03c0.\nrewrite fsetDUl /= namesm_union_disjoint ?fdisjoint_names_domm //; last first.\n  suffices h : fsubset (names (domm h1)) (names (ls, h1)).\n    by apply: fdisjoint_trans; eauto.\n  by rewrite fsubsetU //= [_ _ (names h1)]fsubsetU ?orbT ?fsubsetxx.\nrewrite (fsetDUl (names h1)) -[names ls :\\: A]fsetUid -fsetUA.\nrewrite [in X in _ :|: X]fsetUC 2!fsetUA -fsetUA (fsetUC (names h2 :\\: A)).\nrewrite -2!fsetDUl -(namespE (ls, h1)) -(namespE (ls, h2)) fdisjointUr.\ncase/andP=> [dis_\u03c01 dis_\u03c02].\nexists (rename \u03c0 ls), (rename \u03c0 h1), (rename \u03c0 h2).\nrewrite -es pair_eqvar unionm_eqvar; split=> //.\n- apply: (Ph1 (rename \u03c0 A)); last exact: fdisjoint0s.\n  rewrite -[LHS](@renameJ _ \u03c0) ?names_hider ?namesrE //.\n  by rewrite hide_eqvar Restr_eqvar pair_eqvar.\n- apply: (Qh2 (rename \u03c0 A)); last exact: fdisjoint0s.\n  rewrite -[LHS](@renameJ _ \u03c0) ?names_hider ?namesrE //.\n  by rewrite hide_eqvar Restr_eqvar pair_eqvar.\nby rewrite -![domm (rename _ _)]domm_eqvar -fdisjoint_eqvar renameT.\nQed.\n\nLemma weak_frame_rule P Q R c :\n  weak_triple P c Q ->\n  ind_vars (mod_vars_c c) R ->\n  weak_triple (P *> R) c (Q *> R).\nProof.\nmove=> t ind s k sub [ls [h1 [h2 [e ph1 ph2 dis]]]].\nrewrite {}e {s} in sub *.\nmove/(_ (ls, h1) k sub ph1): t.\nrewrite -{2}[ls]unionm0.\nhave dis': fdisjoint (names (domm h1)) (names (domm h2)).\n  move: dis; rewrite fdisjointUl=> /andP [_] /=.\n  by rewrite fdisjointUl=> /andP [].\ncase ev: (eval_com c (ls, h1) k)=> [rs'| |] //=; first last.\n- by rewrite (@frame_loop _ (ls, h1) (emptym, h2)).\n- by rewrite (@frame_error _ (ls, h1) (emptym, h2)).\nmove=> Q_rs'; rewrite (@frame_ok _ (ls, h1) (emptym, h2) _ _ sub dis' ev).\ncase: rs' / (restrP (names (ls, h1) :|: names ((emptym, h2) : state)) rs')\n          Q_rs' ev => /= A [ls' h1'] dis'' sub' Q_rs' ev.\nmove: dis''; rewrite fdisjointUl=> /andP [dis1 dis2].\nrewrite maprE // /stateu unionm0.\nrewrite namespE /= namesm_empty fset0U in dis2.\napply: ssc_lift=> //.\n  move=> /= A' s2' /restr_eqP [\u03c0].\n  rewrite namespE fsetDUl /= (fsetDidPl dis2) fdisjointUr.\n  case/andP=> dis_ls' dis_h2.\n  rewrite pair_eqvar /= (renameJ dis_h2) => - [eA <-] _.\n  apply/ind; eauto=> /= x nin_x.\n  move: (mod_vars_cP ev nin_x); rewrite maprE ?fdisjoint0s //=.\n  move/(congr1 (@oexpose _)); rewrite oexposeE oexposeE0.\n  case: ifP=> // dis''' [<-].\n  rewrite renamemE renameT renameJ // fdisjointC.\n  rewrite fdisjointC in dis_ls'.\n  apply/fdisjoint_trans; eauto.\n  apply/fsubsetP=> /= i in_i; apply/fsetDP; split.\n    case e: getm in_i=> [v|]; try by rewrite in_fset0.\n    move=> in_i; apply/namesmP/@PMFreeNamesVal; eauto.\n  by move: i in_i; apply/fdisjointP; rewrite fdisjointC.\nhave: fsubset (names (eval_com c (ls, h1) k)) (names (ls, h1)).\n  eapply nom_finsuppP; finsupp.\nrewrite ev namesresE names_hider namesrE fsubDset fsetUC => ?.\napply: fdisjoint_trans; first eauto.\nrewrite fdisjointUl dis fdisjointC.\napply: fdisjoint_trans; eauto.\nby eapply nom_finsuppP; finsupp.\nQed.\n\nEnd Separation.\n", "meta": {"author": "arthuraa", "repo": "memory-safe-language", "sha": "1a32e879b93b5e9d6fc97100464c8432faece72d", "save_path": "github-repos/coq/arthuraa-memory-safe-language", "path": "github-repos/coq/arthuraa-memory-safe-language/memory-safe-language-1a32e879b93b5e9d6fc97100464c8432faece72d/separation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18600594530596057}}
{"text": "(* begin hide *)\nFrom ITree Require Import\n     Eq.Eqit\n     ITree\n     FailFacts\n     Events.Exception.\n\nFrom Vellvm Require Import \n     Utils.PostConditions\n     Utils.PropT\n     Utils.TFor\n     Utils.Tactics.\n\nFrom Paco Require Import paco.\n\nFrom ExtLib Require Import\n     Structures.Monad.\n\nFrom Coq Require Import\n     Morphisms Lia.\n\nImport ITreeNotations.\nLocal Open Scope itree.\n(* end hide *)\n\n(** * Reasoning about successful computations\n\n  Compilers are typically only required to preserve the behavior of valid programs.\n  Correctness statements are therefore phrased in terms \"for any program c, if c\n  has a well defined semantics, then ...\".\n  Having a well defined semantics when manipulating an operational semantics is \n  typically expressed as never reaching a blocking state, or an error state.\n  In this file, we develop the necessary machinery to express and reason about \n  this same fact in an itree-based semantics.\n\n  We choose here to assume that failure is represented using the [exceptT] domain of\n  events, and to interpret this failure into a trivial option monad. \n  The property of \"well definedness\" of a computation is then expressed after interpretation\n  using the [has_post] unary logic developed in [./Utils/PostConditions.v]: it simply asserts\n  that the computation does not fail (see [no_failure]).\n\n  Interestingly, this requires to process [eutt]-based equations forward as opposed to \n  backward: we know for an hypothesis an evidence of the form [has_post (x <- c;; k) P]\n  and need to deduce information about [c] and [k]. It so happens that one needs to be\n  a little bit more careful when processing monadic equivalences forward than backward:\n  we use to this end notably [eutt_clo_bind_returns].\n\n  This approach is heavily used in the Helix development.\n\n*)\n\n(* For some reason the new definition of [ecofix] in itrees loops here.\n  We redefine the old one for now.\n*)\nRequire Import Paco.pacotac_internal.\n\n Tactic Notation \"ecofix\" ident(CIH) \"with\" ident(gL) ident(gH) :=\n   repeat red;\n   paco_pre2;\n   eapply euttG_cofix;\n   paco_post2 CIH with gL;\n   paco_post2 CIH with gH.\n\n Tactic Notation \"ecofix\" ident(CIH) := ecofix CIH with gL gH.\n\nSection ITreeUtilities.\n\n(* TODO: move to itree *)\nLemma interp_state_iter :\n  forall {A R S : Type} (E F : Type -> Type) (s0 : S) (a0 : A) (h : E ~> Monads.stateT S (itree F)) f,\n    State.interp_state (E := E) (T := R) h (ITree.iter f a0) s0 \u2248\n                 @Basics.iter _ MonadIter_stateT0 _ _ (fun a s => State.interp_state h (f a) s) a0 s0.\nProof.\n  unfold iter, CategoryKleisli.Iter_Kleisli, Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree in *; cbn.\n  einit. ecofix CIH; intros.\n  rewrite 2 unfold_iter; cbn.\n  rewrite !Eqit.bind_bind.\n  setoid_rewrite bind_ret_l.\n  rewrite StateFacts.interp_state_bind.\n  ebind; econstructor; eauto.\n  - reflexivity.\n  - intros [s' []] _ []; cbn.\n    + rewrite StateFacts.interp_state_tau.\n      estep.\n    + rewrite StateFacts.interp_state_ret; apply reflexivity.\nQed.\n\nLemma interp_fail_iter :\n  forall {A R : Type} (E F : Type -> Type) (a0 : A) (h : E ~> failT (itree F)) f,\n    interp_fail (E := E) (T := R) h (ITree.iter f a0) \u2248\n                @Basics.iter _ failT_iter _ _ (fun a => interp_fail h (f a)) a0.\nProof.\n  unfold Basics.iter, failT_iter, Basics.iter, MonadIter_itree in *; cbn.\n  einit. ecofix CIH; intros *.\n  rewrite 2 unfold_iter; cbn.\n  rewrite !Eqit.bind_bind.\n  rewrite interp_fail_bind.\n  ebind; econstructor; eauto.\n  reflexivity.\n  intros [[a1|r1]|] [[a2|r2]|] EQ; inv EQ.\n  - rewrite bind_ret_l.\n    rewrite interp_fail_tau.\n    estep.\n  - rewrite bind_ret_l, interp_fail_ret.\n    eret.\n  - rewrite bind_ret_l.\n    eret.\nQed.\n\nLemma translate_iter :\n  forall {A R : Type} (E F : Type -> Type) (a0 : A) (h : E ~> F) f,\n    translate (E := E) (F := F) (T := R) h (ITree.iter f a0) \u2248\n              ITree.iter (fun a => translate h (f a)) a0.\nProof.\n  intros; revert a0.\n  einit; ecofix CIH; intros.\n  rewrite 2 unfold_iter; cbn.\n  rewrite TranslateFacts.translate_bind.\n  ebind; econstructor; eauto.\n  - reflexivity.\n  - intros [|] [] EQ; inv EQ.\n    + rewrite TranslateFacts.translate_tau; estep.\n    + rewrite TranslateFacts.translate_ret; apply reflexivity.\nQed.\n\nEnd ITreeUtilities.\n\n(* We don't care in this context about having an informative failure, \n  we just dive into the option monad.\n   *)\nSection Handle_Fail.\n\n  Definition h_fail {T E} : exceptE T ~> failT (itree E) :=\n    fun _ _ => Ret None.\n\n  Definition trigger_fail {E} : E ~> failT (itree E)\n    := fun _ e => Vis e (fun x => Ret (Some x)).\n\n  (* TODO: Use [over], or possibly [exceptE -< E] *)\n  Definition run_fail {E T}\n    : itree (exceptE T +' E) ~> failT (itree E)\n    := interp_fail (case_ h_fail trigger_fail).\n\nEnd Handle_Fail.\n\nLemma post_returns : forall {E X} (t : itree E X), t \u2933 fun a => Returns a t.\nProof.\n  intros; eapply eqit_mon; eauto.\n  2: eapply PropT.eutt_Returns.\n  intros ? ? [<- ?]; auto.\nQed.\n\nLemma eutt_clo_bind_returns {E R1 R2 RR U1 U2 UU}\n      (t1 : itree E U1) (t2 : itree E U2)\n      (k1 : U1 -> itree E R1) (k2 : U2 -> itree E R2)\n      (EQT: @eutt E U1 U2 UU t1 t2)\n      (EQK: forall u1 u2, UU u1 u2 -> Returns u1 t1 -> Returns u2 t2 -> eutt RR (k1 u1) (k2 u2)):\n  eutt RR (x <- t1;; k1 x) (x <- t2;; k2 x).\nProof.\n  intros; eapply eutt_post_bind_gen; eauto using post_returns.\nQed.\n\nSection No_Failure.\n\n  (* We are often interested in assuming that a computation does not fail.\n     This file develop ways to assert and reason about such a fact assuming that\n     the tree has been interpreted into the [failT (itree E)] monad.\n     Note: nothing in this file is specific to Vellvm, it should eventually be\n     moved to the itree library.\n   *)\n\n  Definition no_failure {E X} (t : itree E (option X)) : Prop :=\n    t \u2933 fun x => ~ x = None.\n\n  Global Instance no_failure_eutt {E X} : Proper (eutt eq ==> iff) (@no_failure E X).\n  Proof.\n    intros t s EQ; unfold no_failure; split; intros ?; [rewrite <- EQ | rewrite EQ]; auto.\n  Qed.\n\n  (* This is a non-trivial proof, not a direct consequence of an inversion lemma.\n     This states essentially that if `no_failure` holds at the end of the execution,\n     then it is an invariant of the execution.\n   *)\n  Lemma no_failure_bind_prefix : forall {E X Y} (t : itree E (option X)) (k : X -> itree E (option Y)),\n      no_failure (bind (m := failT (itree E)) t k) ->\n      no_failure t.\n  Proof.\n    unfold no_failure,has_post; intros E X Y.\n    einit; ecofix CIH.\n    intros * NOFAIL.\n    cbn in NOFAIL. rewrite unfold_bind in NOFAIL.\n    rewrite itree_eta.\n    destruct (observe t) eqn:EQt.\n    - eret.\n      cbn in *.\n      destruct r; [intros abs; inv abs | exfalso]. \n      apply eutt_Ret in NOFAIL; apply NOFAIL; auto.\n    - estep.\n      cbn in *.\n      ebase; right; eapply CIH.\n      rewrite <- tau_eutt; eauto.\n    - estep.\n      cbn in *.\n      intros ?; ebase.\n      right; eapply CIH0.\n      eapply eqit_inv_Vis in NOFAIL; eauto.\n  Qed.\n\n  Lemma no_failure_bind_cont : forall {E X Y} (t : _ X) (k : X -> _ Y),\n      no_failure (bind (m := failT (itree E)) t k) ->\n      forall u, Returns (E := E) (Some u) t -> \n              no_failure (k u).\n  Proof.\n    intros * NOFAIL * ISRET.\n    unfold no_failure in *.\n    cbn in *.\n    eapply PropT.eqit_bind_Returns_inv in NOFAIL; eauto. \n    apply NOFAIL.\n  Qed.\n\n  Lemma no_failure_Ret :\n    forall E T X x, @no_failure E X (@run_fail E T X (Ret x)).\n  Proof.\n    intros.\n    unfold run_fail, no_failure.\n    cbn.\n    rewrite interp_fail_Ret.\n    apply eutt_Ret; intros abs; inv abs.\n  Qed.\n\n  Lemma failure_throw : forall E Err X (s: Err),\n      ~ no_failure (E := E) (X := X) (@run_fail E Err X (throw (E := _ +' E) s)).\n  Proof.\n    intros * abs.\n    unfold no_failure, throw, run_fail in *.\n    rewrite interp_fail_vis in abs.\n    cbn in *.\n    unfold h_fail in *; rewrite  !bind_ret_l in abs.\n    eapply eutt_Ret in abs.\n    apply abs; auto.\n  Qed.\n\n  (* The following lemmas reason about [tfor] in the specific case where the body goes \n   into the failure monad.\n   They are quite a bit ugly as intrinsically [tfor] unfolds using the itree [bind] while\n   [no_failure] relies on the failT [bind]. Improving the situation will require to \n   develop better general monadic reasoning principles rather than re-internalize things\n   into the [itree E] monad forcibly.\n   *)\n  Lemma tfor_fail_None : forall {E A} i j (body : nat -> A -> itree E (option A)),\n      (i <= j)%nat ->\n      tfor (fun k x => match x with\n                    | Some a0 => body k a0\n                    | None => Ret None\n                    end) i j None \u2248 Ret None.\n  Proof.\n    intros E A i j body; remember (j - i)%nat as k; revert i Heqk; induction k as [| k IH].\n    - intros i EQ INEQ; replace j with i by lia; rewrite tfor_0; reflexivity. \n    - intros i EQ INEQ.\n      rewrite tfor_unroll; [|lia].\n      rewrite bind_ret_l, IH; [reflexivity | lia | lia].\n  Qed.\n\n  (* One step unrolling of the combinator *)\n  Lemma tfor_unroll_fail: forall {E A} i j (body : nat -> A -> itree E (option A)) a0,\n      (i < j)%nat ->\n      tfor (fun k x => match x with\n                    | Some a0 => body k a0\n                    | None => Ret None\n                    end) i j a0 \u2248\n           bind (m := failT (itree E))\n           (match a0 with\n            | Some a0 => body i a0\n            | None => Ret None\n            end) (fun a =>\n                    tfor (fun k x =>\n                            match x with\n                            | Some a0 => body k a0\n                            | None => Ret None\n                            end) (S i) j (Some a)).\n  Proof.\n    intros *.\n    remember (j - i)%nat as k.\n    revert i Heqk a0.\n    induction k as [| k IH].\n    - lia.\n    - intros i EQ a0 INEQ.\n      rewrite tfor_unroll; auto.\n      cbn.\n      destruct a0 as [a0 |]; cycle 1.\n      + rewrite !bind_ret_l.\n        rewrite tfor_fail_None; [reflexivity | lia].\n      + apply eutt_eq_bind.\n        intros [a1|]; cycle 1.\n        * rewrite tfor_fail_None; [reflexivity | lia].\n        * destruct (PeanoNat.Nat.eq_dec (S i) j).\n          {\n            subst.\n            rewrite tfor_0; reflexivity.\n          }\n          destruct k; [lia |].\n          rewrite (IH (S i)); [| lia | lia].\n          reflexivity.\n  Qed.\n\n  Lemma no_failure_tfor : forall {E A} (body : nat -> A -> itree E (option A)) n m a0,\n      no_failure (tfor (fun k x => match x with\n                                | Some a => body k a\n                                | None => Ret None\n                                end) n m a0) ->\n      forall k a,\n        (n <= k < m)%nat ->\n        Returns (Some a) (tfor (fun k x => match x with\n                                        | Some a => body k a\n                                        | None => Ret None\n                                        end) n k a0) ->\n        no_failure (body k a).\n  Proof.\n    intros E A body n m.\n    remember (m - n)%nat as j.\n    revert n Heqj.\n    induction j as [| j IH].\n    - intros n EQ a0 NOFAIL k a [INEQ1 INEQ2] RET.\n      assert (n = m) by lia; subst.\n      lia.\n    - intros n EQ a0 NOFAIL k a [INEQ1 INEQ2] RET.\n      destruct (PeanoNat.Nat.eq_dec k n). \n      + subst.\n        clear INEQ1.\n        rewrite tfor_unroll_fail in NOFAIL; [| auto].\n        rewrite tfor_0 in RET.\n        apply Returns_Ret in RET.\n        subst.\n        apply no_failure_bind_prefix in NOFAIL; auto.\n      + specialize (IH (S n)).\n        forward IH; [lia |].\n        rewrite tfor_unroll_fail in NOFAIL; [| lia].\n        rewrite tfor_unroll_fail in RET; [| lia].\n        cbn in RET.\n        apply Returns_bind_inversion in RET.\n        destruct RET as (a1 & RET1 & RET2).\n        destruct a0 as [a0|]; cycle 1.\n        { cbn in *.\n          rewrite bind_ret_l in NOFAIL.\n          apply eutt_Ret in NOFAIL; contradiction NOFAIL; auto.\n        }\n        cbn in *.\n        destruct a1 as [a1|]; cycle 1.\n        {\n          apply Returns_Ret in RET2.\n          inv RET2.\n        }\n        apply no_failure_bind_cont with (u := a1) in NOFAIL; auto.\n        eapply IH; eauto.\n        lia.\n  Qed.\n\nEnd No_Failure.\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/NoFailure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1857373694606667}}
{"text": "Require Import Lia.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic Language.\nFrom imm Require Import\n     AuxDef\n     Events Execution\n     Traversal TraversalConfig SimTraversal SimTraversalProperties\n     Prog ProgToExecution ProgToExecutionProperties Receptiveness\n     imm_common imm_s imm_s_hb SimState PromiseLTS\n     CertExecution2\n     SubExecution CombRelations.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import LblStep.\nRequire Import CertRf.\nRequire Import ImmProperties.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Classical_Prop.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection CertGraph.\n  Variable prog : Prog.t.\n  Variable G  : execution.\n  Variable GPROG : program_execution prog G.\n  Variable sc : relation actid.\n  Variable TC : trav_config.\n  Variable TC': trav_config.\n  Variable thread : thread_id.\n  Variable state : state.\n\n  Notation \"'certG'\" := state.(ProgToExecution.G).\n\n  Notation \"'certE'\" := certG.(acts_set).\n\n  Definition certLab : actid -> label :=\n    restr_fun certE certG.(lab) G.(lab).\n\n  Notation \"'certRmw'\" := (certG.(rmw)).\n\n  Notation \"'cert_rf'\" := (cert_rf G sc TC').\n\n  Notation \"'E'\" := G.(acts_set).\n\n  Notation \"'Tid' t\" := (fun x => tid x = t) (at level 1).\n  Notation \"'NTid' t\" := (fun x => tid x <> t) (at level 1).\n\n  Notation \"'R'\" := (fun a => is_true (is_r G.(lab) a)).\n  Notation \"'W'\" := (fun a => is_true (is_w G.(lab) a)).\n  Notation \"'F'\" := (fun a => is_true (is_f G.(lab) a)).\n\n  Notation \"'Rel'\" := (fun a => is_true (is_rel G.(lab) a)).\n\n  Notation \"'R_ex'\" := (fun a => R_ex G.(lab) a).\n\n  Notation \"'sb'\" := (G.(sb)).\n  Notation \"'rmw'\" := G.(rmw).\n  Notation \"'addr'\" := G.(addr).\n  Notation \"'data'\" := G.(data).\n  Notation \"'ctrl'\" := G.(ctrl).\n  Notation \"'rmw_dep'\" := G.(rmw_dep).\n  Notation \"'rf'\" := (G.(rf)).\n  Notation \"'co'\" := (G.(co)).\n\n  Notation \"'ppo'\" := (G.(ppo)).\n  Notation \"'hb'\" := (G.(imm_s_hb.hb)).\n  Notation \"'vf'\" := (furr G sc).\n\n  Notation \"'C'\"  := (covered TC).\n  Notation \"'I'\"  := (issued TC).\n  Notation \"'C''\"  := (covered TC').\n  Notation \"'I''\"  := (issued TC').\n\n  Notation \"'E0'\" := (Tid_ thread \u2229\u2081 CsbI G TC').\n\n  Definition cert_dom st :=\n    (C \u222a\u2081 (dom_rel (sb^? \u2a3e \u2997 I \u2998) \u2229\u2081 NTid thread) \u222a\u2081 acts_set st.(ProgToExecution.G)).\n\n  Lemma cert_dom_alt st\n    (STCOV : C \u2229\u2081 Tid thread \u2286\u2081 acts_set st.(ProgToExecution.G)) :\n      cert_dom st \u2261\u2081\n               (C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997 I \u2998)) \u2229\u2081 NTid thread \u222a\u2081\n               acts_set st.(ProgToExecution.G).\n  Proof.\n    unfold cert_dom.\n    split; [|basic_solver 10].\n    arewrite (C \u2261\u2081 C \u2229\u2081 Tid thread \u222a\u2081 C \u2229\u2081 NTid thread) at 1.\n    { rewrite <- set_inter_union_r.\n      rewrite tid_set_dec.\n      basic_solver. }\n    rewrite STCOV. basic_solver 10.\n  Qed.\n\n  Record cert_graph :=\n    { cslab : eq_dom (D G TC') certLab G.(lab);\n      cuplab_cert : same_lab_u2v_dom certE certG.(lab) G.(lab);\n\n      dcertE : certE \u2261\u2081 E0;\n      dcertRMW : certRmw \u2261 \u2997 certE \u2998 \u2a3e rmw;\n\n      cert_rfv_clab : cert_rf \u2a3e \u2997 Tid_ thread \u2998 \u2286 same_val certLab;\n    }.\n\n  Section CertGraphProperties.\n    Variable WF : Wf G.\n    Variable Wf_sc : wf_sc G sc.\n    Variable IMMC : imm_consistent G sc.\n    Variable TCCOH : tc_coherent G sc TC.\n    Variable TSTEP : isim_trav_step G sc thread TC TC'.\n\n    Lemma isim_trav_step_coherence : tc_coherent G sc TC'.\n    Proof. eapply sim_trav_step_coherence; eauto. red. eauto. Qed.\n\n    Hint Resolve isim_trav_step_coherence.\n\n    Lemma trstep_thread_prog : IdentMap.In thread prog.\n    Proof.\n      apply sim_trav_step_to_step in TSTEP.\n      destruct TSTEP as [e [T'' ITSTEP]]. desf.\n      assert (E e) as EE.\n      { cdes ITSTEP. desf.\n        { apply COV. }\n        apply ISS. }\n      set (BB := EE).\n      apply GPROG in BB.\n      desf. exfalso.\n      cdes ITSTEP. desf.\n      { apply NEXT. by eapply init_covered; eauto. }\n      apply NISS. by eapply init_issued; eauto.\n    Qed.\n\n    (******************************************************************************)\n    (** ** E0 propeties *)\n    (******************************************************************************)\n\n    Lemma E0_in_thread_execE st\n          (TEH : thread_restricted_execution G thread st.(ProgToExecution.G)) :\n      E0 \u2286\u2081 acts_set st.(ProgToExecution.G).\n    Proof.\n      rewrite tr_acts_set; eauto.\n      rewrite set_interC.\n      rewrite CsbI_in_E; eauto.\n    Qed.\n\n    Lemma E0_sb_prcl :\n      dom_rel (\u2997Tid_ thread \u2998 \u2a3e sb \u2a3e \u2997E0\u2998) \u2286\u2081 E0.\n    Proof.\n      rewrite seq_eqv_lr.\n      intros x [y [TIDx [SB E0y]]].\n      split; auto.\n      eapply CsbI_sb_prcl; eauto.\n      exists y.\n      apply seq_eqv_r.\n      split; auto.\n      apply E0y.\n    Qed.\n\n    Lemma E0_rmw_fwcl\n          (RMWCLOS : forall r w (RMW : rmw r w), C' r <-> C' w)\n          (IRELCOV : W \u2229\u2081 Rel \u2229\u2081 I' \u2286\u2081 C') :\n      \u2997E0\u2998 \u2a3e rmw \u2261 \u2997E0\u2998 \u2a3e rmw \u2a3e \u2997E0\u2998.\n    Proof.\n      split; [|basic_solver].\n      rewrite seq_eqv_l, seq_eqv_lr.\n      unfolder. ins. desc.\n      splits; auto.\n      { subst thread. symmetry.\n        by apply WF.(wf_rmwt). }\n      assert ((\u2997CsbI G TC'\u2998 \u2a3e rmw) x y) as HH.\n      { basic_solver. }\n      eapply CsbI_rmw_fwcl in HH; eauto.\n      by destruct_seq HH as [AA BB].\n    Qed.\n\n    Lemma E0_eindex_weak e (CTE : E0 e) (NINITT : thread <> tid_init) :\n      exists index : nat,\n        \u27ea EREP : e = ThreadEvent thread index \u27eb.\n    Proof.\n      ins. destruct CTE as [AA BB].\n      destruct e; simpls; rewrite <- AA in *; desf.\n      eauto.\n    Qed.\n\n    Lemma E0_eindex st\n          (NINITT : thread <> tid_init)\n          (GPC : wf_thread_state thread st)\n          (TEH : thread_restricted_execution G thread st.(ProgToExecution.G)) :\n      exists ctindex,\n        \u27ea CCLOS :forall index (LT : index < ctindex),\n            E0 (ThreadEvent thread index) \u27eb /\\\n        \u27ea CREP : forall e (CTE : E0 e),\n            exists index : nat,\n              \u27ea EREP : e = ThreadEvent thread index \u27eb /\\\n              \u27ea ILT : index < ctindex \u27eb \u27eb.\n    Proof.\n      assert (E0 \u2286\u2081 E) as E0_in_E.\n      { rewrite CsbI_in_E; eauto. basic_solver. }\n      destruct (classic (exists e, E0 e)) as [|NCT].\n      2: { exists 0. splits.\n           { ins. inv LT. }\n           ins. exfalso. apply NCT. eauto. }\n      desc.\n      assert (acyclic (sb \u2a3e \u2997 E0 \u2998)) as AC.\n      { arewrite (sb \u2a3e \u2997E0\u2998 \u2286 sb). apply sb_acyclic. }\n      set (doml := filterP E0 G.(acts)).\n      assert (forall c, (sb \u2a3e \u2997E0\u2998)\uff0a e c -> In c doml) as UU.\n      { intros c SCC. apply rtE in SCC. destruct SCC as [SCC|SCC].\n        { red in SCC. desf. apply in_filterP_iff.\n          split; auto. eapply E0_in_E. eauto. }\n        apply inclusion_ct_seq_eqv_r in SCC. apply seq_eqv_r in SCC.\n        apply in_filterP_iff. split; auto; [apply E0_in_E|]; desf. }\n      edestruct (last_exists doml AC UU) as [max [MM1 MM2]].\n      assert (E0 max) as CTMAX.\n      { apply rtE in MM1. destruct MM1 as [MM1|MM1].\n        { red in MM1. desf. }\n        apply inclusion_ct_seq_eqv_r in MM1. apply seq_eqv_r in MM1. desf. }\n      assert (Tid thread max) as CTTID by apply CTMAX.\n      destruct max as [l|mthread mindex].\n      { simpls. rewrite <- CTTID in *. desf. }\n      simpls. rewrite CTTID in *.\n      assert (acts_set G (ThreadEvent thread mindex)) as EEM.\n      { by apply E0_in_E. }\n      exists (1 + mindex). splits.\n      { ins. destruct CTMAX as [_ CTMAX].\n        split; [by ins|].\n        apply le_lt_or_eq in LT. destruct LT as [LT|LT].\n        2: { inv LT. }\n        assert (acts_set (st.(ProgToExecution.G)) (ThreadEvent thread mindex)) as PP.\n        { apply TEH.(tr_acts_set). by split. }\n        assert (E (ThreadEvent thread index)) as EEE.\n        { apply TEH.(tr_acts_set). eapply acts_rep in PP; eauto. desc.\n          eapply GPC.(acts_clos). inv REP. lia. }\n        assert (sb (ThreadEvent thread index) (ThreadEvent thread mindex)) as QQQ.\n        { red.\n          apply seq_eqv_l. split; auto.\n          apply seq_eqv_r. split; auto.\n          red. split; auto. lia. }\n        destruct CTMAX as [AA|[z AA]]; [left|right].\n        { apply isim_trav_step_coherence in AA. apply AA. eexists.\n          apply seq_eqv_r. split; eauto. }\n        exists z. apply seq_eqv_r in AA. destruct AA as [AA1 AA2].\n        apply seq_eqv_r. split; auto.\n        apply rewrite_trans_seq_cr_cr.\n        { apply sb_trans. }\n        eexists; split; [|by eauto].\n          by apply r_step. }\n      ins. set (CTE' := CTE).\n      apply E0_eindex_weak in CTE'; auto; desc.\n      eexists. splits; eauto.\n      destruct (le_gt_dec index mindex) as [LL|LL].\n      { by apply le_lt_n_Sm. }\n      exfalso.\n      eapply MM2. apply seq_eqv_r. split; [|by apply CTE].\n      red.\n      apply seq_eqv_l. split; auto.\n      apply seq_eqv_r. split; auto.\n      red. rewrite EREP.\n      split; auto.\n    Qed.\n\n    (******************************************************************************)\n    (** ** certLab propeties *)\n    (******************************************************************************)\n\n    Lemma cuplab (SCG : cert_graph) :\n      same_lab_u2v certLab G.(lab).\n    Proof.\n      red. red. ins.\n      unfold certLab.\n      unfold restr_fun.\n      desf.\n      { by apply SCG. }\n      red. desf.\n    Qed.\n\n    (******************************************************************************)\n    (** ** cert_rf propeties *)\n    (******************************************************************************)\n\n    Lemma cert_rfl_clab (CERTG : cert_graph) :\n      cert_rf \u2286 same_loc certLab.\n    Proof.\n      erewrite same_lab_u2v_same_loc.\n      { eapply cert_rfl. }\n      apply cuplab; auto.\n    Qed.\n\n    Lemma cert_rf_ntid_old_iss_sb\n          (SCG : cert_graph)\n          (NINITT : thread <> tid_init)\n          (IRELCOV : W \u2229\u2081 Rel \u2229\u2081 I \u2286\u2081 C) :\n      cert_rf \u2a3e \u2997 Tid_ thread \u2998 \u2286\n        \u2997 NTid thread \u2229\u2081 I \u2998 \u2a3e cert_rf \u222a sb \u2229 same_tid.\n    Proof.\n      assert (IRELCOV' : W \u2229\u2081 Rel \u2229\u2081 I' \u2286\u2081 C').\n      { eapply sim_trav_step_rel_covered; eauto; red; eauto. }\n      erewrite cert_rf_ntid_iss_sb; eauto.\n      rewrite isim_trav_step_new_issued_tid; eauto.\n      basic_solver.\n    Qed.\n\n    Lemma cert_rf_cert_dom st\n          (SCG : cert_graph)\n          (NINITT : thread <> tid_init)\n          (IRELCOV : W \u2229\u2081 Rel \u2229\u2081 I \u2286\u2081 C)\n          (WFST : wf_thread_state thread st) :\n      dom_rel (cert_rf \u2a3e \u2997 eq (ThreadEvent thread st.(eindex)) \u2998) \u2286\u2081 cert_dom st.\n    Proof.\n      unfold cert_dom.\n      rewrite <- seq_eqvK.\n      arewrite\n        (eq (ThreadEvent thread (eindex st)) \u2286\u2081 Tid_ thread)\n        at 1.\n      { basic_solver. }\n      rewrite <- seq_eqvK\n        with (dom := Tid thread).\n      do 2 rewrite <- seqA.\n      erewrite cert_rf_ntid_old_iss_sb; eauto.\n      rewrite !seq_union_l, dom_union.\n      apply set_subset_union_l. split.\n      { basic_solver 10. }\n\n      arewrite (sb \u2229 same_tid \u2a3e \u2997Tid thread\u2998 \u2261 \u2997Tid thread\u2998 \u2a3e sb).\n      { unfolder; splits; ins; splits; desf; auto.\n        { unfold same_tid.\n          edestruct sb_tid_init as [STID | INITx]; eauto.\n          exfalso. apply NINITT.\n            by apply is_init_tid in INITx. }\n        edestruct sb_tid_init as [STID | INITx]; eauto.\n        exfalso. apply NINITT.\n          by apply is_init_tid in INITx. }\n      intros x [y HH]. right.\n      apply seq_eqv_lr in HH.\n      destruct HH as [TIDx [SB EQy]].\n      destruct x; [intuition|].\n      unfold tid in TIDx. subst.\n      apply acts_clos; auto.\n      unfold Execution.sb, ext_sb in SB.\n      apply seq_eqv_lr in SB; desf.\n    Qed.\n\n    (******************************************************************************)\n    (** ** deps propeties *)\n    (******************************************************************************)\n\n    Lemma dom_addrE_in_D : dom_rel (addr \u2a3e \u2997 E0 \u2998) \u2286\u2081 D G TC'.\n    Proof.\n      unfold CsbI.\n      rewrite set_inter_union_r.\n      rewrite id_union; relsf; unionL; splits.\n      { rewrite (addr_in_sb WF).\n        generalize (dom_sb_covered isim_trav_step_coherence).\n        unfold D; basic_solver 21. }\n      arewrite (Tid thread \u2229\u2081 dom_rel (sb^? \u2a3e \u2997I'\u2998) \u2286\u2081\n                      dom_rel (sb^? \u2a3e \u2997I'\u2998)) by basic_solver.\n      rewrite dom_rel_eqv_dom_rel.\n      arewrite (\u2997I'\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997I'\u2998).\n      { generalize (issuedW isim_trav_step_coherence); basic_solver. }\n      rewrite (dom_l (wf_addrD WF)), !seqA.\n      arewrite (\u2997R\u2998 \u2a3e addr \u2a3e sb^? \u2a3e \u2997W\u2998 \u2286 ppo).\n      { unfold imm_common.ppo; rewrite <- ct_step; basic_solver 12. }\n      unfold D; basic_solver 21.\n    Qed.\n\n    Lemma dom_ctrlE_in_D : dom_rel (ctrl \u2a3e \u2997 E0 \u2998) \u2286\u2081 D G TC'.\n    Proof.\n      unfold CsbI.\n      rewrite set_inter_union_r.\n      rewrite id_union; relsf; unionL; splits.\n      { rewrite (ctrl_in_sb WF).\n        generalize (dom_sb_covered isim_trav_step_coherence).\n        unfold D; basic_solver 21. }\n      arewrite (Tid thread \u2229\u2081 dom_rel (sb^? \u2a3e \u2997I'\u2998) \u2286\u2081\n                      dom_rel (sb^? \u2a3e \u2997I'\u2998)) by basic_solver.\n      rewrite dom_rel_eqv_dom_rel.\n      arewrite (ctrl \u2a3e sb^? \u2286 ctrl).\n      { generalize (ctrl_sb WF); basic_solver 21. }\n      arewrite (\u2997I'\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997I'\u2998).\n      { generalize (issuedW isim_trav_step_coherence); basic_solver. }\n      rewrite (wf_ctrlD WF), !seqA.\n      arewrite (\u2997R\u2998 \u2a3e ctrl \u2a3e \u2997W\u2998 \u2286 ppo).\n      { unfold imm_common.ppo; rewrite <- ct_step; basic_solver 12. }\n      unfold D; basic_solver 21.\n    Qed.\n\n    Lemma dom_rmw_depE_in_D : dom_rel (rmw_dep \u2a3e \u2997 E0 \u2998) \u2286\u2081 D G TC'.\n    Proof.\n      unfold CsbI.\n      rewrite set_inter_union_r.\n      rewrite id_union; relsf; unionL; splits.\n      { rewrite (rmw_dep_in_sb WF).\n        generalize (dom_sb_covered isim_trav_step_coherence).\n        unfold D; basic_solver 21. }\n      arewrite (Tid thread \u2229\u2081 dom_rel (sb^? \u2a3e \u2997I'\u2998) \u2286\u2081\n                      dom_rel (sb^? \u2a3e \u2997I'\u2998)) by basic_solver.\n      rewrite dom_rel_eqv_dom_rel.\n      rewrite (wf_rmw_depD WF), !seqA.\n      arewrite (\u2997I'\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997I'\u2998).\n      { generalize (issuedW isim_trav_step_coherence); basic_solver. }\n      arewrite (\u2997R\u2998 \u2a3e rmw_dep \u2a3e \u2997R_ex\u2998 \u2a3e sb^? \u2a3e \u2997W\u2998 \u2286 ppo).\n      2: unfold D; basic_solver 21.\n      unfold imm_common.ppo; hahn_frame.\n      case_refl _.\n      { by rewrite <- ct_step; basic_solver 12. }\n      rewrite ct_begin; rewrite <- inclusion_t_rt, <- ct_step; basic_solver 12.\n    Qed.\n\n    Lemma dom_rmwE_in_D : dom_rel (rmw \u2a3e \u2997 E0 \u2998) \u2286\u2081 D G TC'.\n    Proof.\n      unfold CsbI.\n      rewrite set_inter_union_r.\n      rewrite id_union; relsf; unionL; splits.\n      { rewrite (rmw_in_sb WF).\n        generalize (dom_sb_covered isim_trav_step_coherence).\n        unfold D; basic_solver 21. }\n      arewrite (Tid thread \u2229\u2081 dom_rel (sb^? \u2a3e \u2997I'\u2998) \u2286\u2081\n                      dom_rel (sb^? \u2a3e \u2997I'\u2998)) by basic_solver.\n      rewrite dom_rel_eqv_dom_rel.\n      arewrite (\u2997I'\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997I'\u2998).\n      { generalize (issuedW isim_trav_step_coherence); basic_solver. }\n      generalize (rmw_in_ppo WF) (rmw_sb_W_in_ppo WF).\n      unfold D; basic_solver 21.\n    Qed.\n\n    Lemma dom_dataD_in_D : dom_rel (data \u2a3e \u2997D G TC'\u2998) \u2286\u2081 D G TC'.\n    Proof.\n      unfold CsbI.\n      unfold D.\n      rewrite !id_union; relsf; unionL; splits.\n      { rewrite (data_in_sb WF).\n        generalize dom_sb_covered. basic_solver 21. }\n      { rewrite (data_in_ppo WF).\n        basic_solver 12. }\n      { rewrite dom_rel_eqv_dom_rel.\n        rewrite crE at 1; relsf; unionL; splits.\n        { rewrite (dom_r (wf_dataD WF)), (dom_l (@wf_ppoD G)). type_solver. }\n        rewrite (data_in_ppo WF).\n        sin_rewrite ppo_rfi_ppo. basic_solver 21. }\n      { rewrite (dom_r (wf_dataD WF)), (dom_r (wf_rfiD WF)). type_solver. }\n      rewrite (dom_r (wf_dataD WF)), (dom_r (wf_rfeD WF)). type_solver.\n    Qed.\n\n  End CertGraphProperties.\nEnd CertGraph.\n\nSection CertGraphLemmas.\n\nVariable prog : Prog.t.\nVariable G  : execution.\nVariable GPROG : program_execution prog G.\nVariable sc : relation actid.\nVariable TC : trav_config.\nVariable TC': trav_config.\nVariable thread : thread_id.\n\nNotation \"'E'\" := G.(acts_set).\n\nNotation \"'R'\" := (fun a => is_true (is_r G.(lab) a)).\nNotation \"'W'\" := (fun a => is_true (is_w G.(lab) a)).\nNotation \"'F'\" := (fun a => is_true (is_f G.(lab) a)).\n\nNotation \"'Rel'\" := (fun a => is_true (is_rel G.(lab) a)).\n\nNotation \"'R_ex'\" := (fun a => R_ex G.(lab) a).\n\nNotation \"'sb'\" := (G.(sb)).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'addr'\" := G.(addr).\nNotation \"'data'\" := G.(data).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'rmw_dep'\" := G.(rmw_dep).\nNotation \"'rf'\" := (G.(rf)).\nNotation \"'co'\" := (G.(co)).\n\nNotation \"'ppo'\" := (G.(ppo)).\nNotation \"'hb'\" := (G.(imm_s_hb.hb)).\nNotation \"'vf'\" := (furr G sc).\n\nNotation \"'C'\"  := (covered TC).\nNotation \"'I'\"  := (issued TC).\nNotation \"'C''\"  := (covered TC').\nNotation \"'I''\"  := (issued TC').\n\nNotation \"'E0'\" := (Tid_ thread \u2229\u2081 CsbI G TC').\n(* Notation \"'D'\" := (D G TC' thread). *)\n\nNotation \"'Tid' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'NTid' t\" := (fun x => tid x <> t) (at level 1).\n\nVariable WF : Wf G.\nVariable Wf_sc : wf_sc G sc.\nVariable IMMC : imm_consistent G sc.\nVariable TCCOH : tc_coherent G sc TC.\nVariable TSTEP : isim_trav_step G sc thread TC TC'.\n\nHint Resolve isim_trav_step_coherence.\n\n(******************************************************************************)\n(** ** cert_graph start lemma *)\n(******************************************************************************)\n\nLemma cert_graph_start\n      (state : Language.state (PromiseLTS.thread_lts thread))\n      (NINITT : thread <> tid_init)\n      (GPC : wf_thread_state thread state)\n      (PROGST : stable_lprog (instrs state))\n      (REACHABLE : (step thread)\uff0a (init (instrs state)) state)\n      (SSTATE : sim_state G sim_normal C state)\n      (STATECOV : acts_set state.(ProgToExecution.G) \u2286\u2081 C)\n      (RMWCLOS : forall r w (RMW : rmw r w), C r <-> C w)\n      (IRELCOV : W \u2229\u2081 Rel \u2229\u2081 I \u2286\u2081 C) :\n  exists state',\n    \u27ea CERTG : cert_graph G sc TC' thread state' \u27eb /\\\n    \u27ea CST_STABLE : stable_state state' \u27eb /\\\n    \u27ea CST_REACHABLE : (step thread)\uff0a state state' \u27eb.\nProof.\n    cdes SSTATE. cdes SSTATE1.\n\n    assert (wf_thread_state thread state') as GPC'.\n    { eapply wf_thread_state_steps; eauto. }\n\n    assert (forall r w, rmw r w -> covered TC' r <-> covered TC' w) as RMWCOV.\n    { eapply sim_trav_step_rmw_covered; eauto.\n      red. eauto. }\n\n    edestruct E0_eindex; eauto; desf.\n    edestruct steps_middle_set with\n      (thread := thread)\n      (state0 := state) (state':=state') as [state''].\n    3: { eapply E0_in_thread_execE; eauto. }\n    all: eauto.\n    { apply set_subset_inter_r. split.\n      { etransitivity.\n        { eapply steps_preserve_E; eauto. }\n        etransitivity.\n        { eapply TEH.(tr_acts_set). }\n        basic_solver. }\n      unionR left.\n      etransitivity; eauto.\n      eapply sim_trav_step_covered_le. red. eauto. }\n    { ins.\n      eapply rmw_in_thread_restricted_rmw in RMW; eauto.\n      split; intros [TT XX]; split.\n      1,3: by apply WF.(wf_rmwt) in RMW; rewrite <- TT; red in RMW; desf.\n      all: destruct XX as [XX|XX]; [by left; eapply RMWCOV with (r:=r); eauto|right].\n      all: destruct XX as [e XX].\n      all: apply seq_eqv_r in XX; destruct XX as [SB II].\n      all: exists e; apply seq_eqv_r; split; auto.\n      2: { apply (wf_rmwi WF) in RMW.\n           generalize SB RMW (@sb_trans G). basic_solver. }\n      assert (R r) as RR.\n      { apply WF.(wf_rmwD) in RMW. destruct_seq RMW as [AAA BBB].\n        type_solver. }\n      apply (wf_rmwi WF) in RMW.\n      destruct SB as [|SB]; subst.\n      { eapply issuedW in II; eauto. type_solver. }\n      destruct (classic (w = e)) as [|NEQ]; [by left|].\n      assert (~ is_init r) as NINIT.\n      { intros GG. eapply WF.(init_w) in GG.\n        type_solver. }\n      edestruct sb_semi_total_l with (y:=w) (z:=e); eauto.\n      { apply RMW. }\n      exfalso. eapply RMW; eauto. }\n    desf.\n\n    assert (wf_thread_state thread state'') as GPC''.\n    { eapply wf_thread_state_steps. apply GPC. auto. }\n\n    set (new_rf := cert_rf G sc TC' \u2a3e \u2997 E0 \\\u2081 D G TC' \u2998).\n    set (new_rfi := \u2997 Tid thread \u2998 \u2a3e new_rf \u2a3e \u2997 Tid thread \u2998).\n    set (new_rfe := \u2997 NTid thread \u2998 \u2a3e new_rf \u2a3e \u2997 Tid thread \u2998).\n    set (new_rfe_ex := new_rfe \u222a \u2997 set_compl (codom_rel new_rfe) \u2998).\n\n    assert (new_rfi \u2286 \u2997 Tid_ thread \u2998 \u2a3e cert_rf G sc TC' \u2a3e \u2997 Tid_ thread \u2998)\n      as NEWRFI_IN_CERT.\n    { unfold new_rfi, new_rf. basic_solver. }\n\n    assert (new_rff : functional new_rf\u207b\u00b9).\n    { arewrite (new_rf \u2286 cert_rf G sc TC').\n      apply cert_rff; auto. }\n    assert (new_rfif : functional new_rfi\u207b\u00b9).\n    { arewrite (new_rfi \u2286 new_rf); auto.\n      unfold new_rfi; basic_solver. }\n    assert (new_rfef : functional new_rfe\u207b\u00b9).\n    { arewrite (new_rfe \u2286 new_rf); auto.\n      unfold new_rfe; basic_solver. }\n\n    assert (tc_coherent G sc TC') as TCCOH'.\n    { eapply isim_trav_step_coherence; [ eapply TCCOH | apply TSTEP]. }\n    assert (W \u2229\u2081 Rel \u2229\u2081 I' \u2286\u2081 C') as RELCOV'.\n    { eapply sim_trav_step_rel_covered; eauto. red. eauto. }\n\n    assert (new_rfi \u2261 \u2997 E0 \u2998 \u2a3e new_rfi \u2a3e \u2997 E0 \u2998) as NEW_RFIE.\n    { split; [|basic_solver].\n      etransitivity.\n      2: apply doma_helper.\n      { unfold new_rfi, new_rf. basic_solver 10. }\n      arewrite (new_rfi \u2286 \u2997Tid thread\u2998 \u2a3e sb).\n      { etransitivity.\n        { apply NEWRFI_IN_CERT. }\n        rewrite <- seq_eqvK at 1.\n        rewrite !seqA.\n        by rewrite cert_rf_tid_in_sb; auto. }\n      unfold doma. ins.\n      eapply E0_sb_prcl; [|eauto|]; eauto.\n      basic_solver. }\n\n    assert (forall r, exists ! w, new_rfe_ex\u207b\u00b9 r w) as new_rfe_unique.\n    { ins.\n      destruct (classic ((codom_rel new_rfe) r)) as [X|X].\n      { unfolder in X.\n        destruct X as [w RFE].\n        exists w; red; splits.\n        unfold new_rfe_ex; basic_solver 12.\n        unfold new_rfe_ex; unfolder; ins; desf.\n        eapply new_rfef; basic_solver.\n        exfalso; eauto. }\n      exists r; red; splits.\n      unfold new_rfe_ex; basic_solver 12.\n      unfold new_rfe_ex; unfolder; ins; desf.\n      unfolder in X; exfalso; eauto. }\n\n    assert (exists new_value, forall x, (new_rfe_ex)\u207b\u00b9 x (new_value x)) as HH; desc.\n    { apply (unique_choice (new_rfe_ex)\u207b\u00b9 (new_rfe_unique)). }\n\n    set (get_val (v: option value) :=  match v with | Some v => v | _ => 0 end).\n    set (new_val := fun r => get_val (val G.(lab) (new_value r))).\n\n    assert (forall e (IN: acts_set (ProgToExecution.G state'') e),\n               lab (ProgToExecution.G state'') e = G.(lab) e) as LST2.\n    { ins.\n      assert (tid e = thread) as ETT.\n      { eapply acts_rep in IN.\n        2: by eapply wf_thread_state_steps; [|by eauto]; eauto.\n        desf. }\n      erewrite <- steps_preserve_lab; try rewrite ETT; eauto.\n      eapply tr_lab; eauto.\n      eapply steps_preserve_E; eauto. }\n\n    edestruct steps_old_restrict with (state0:=state'') (state':=state') as [ORMW]; eauto.\n    desc. unnw.\n    edestruct receptiveness_full with\n        (tid:=thread)\n        (s_init:=state) (s:=state'')\n        (new_val:=new_val)\n        (new_rfi:=new_rfi)\n        (MOD:=E0 \\\u2081 D G TC') as [pre_cert_state]; eauto.\n    { rewrite CACTS. apply NEW_RFIE. }\n    { split; [|basic_solver].\n      rewrite NEW_RFIE at 1.\n      unfolder. intros w r [EEX [RFXY EEY]].\n      set (AA := RFXY).\n      unfold new_rfi in AA.\n      destruct_seq AA as [TX TY].\n      unfold new_rf in AA. apply seq_eqv_r in AA. destruct AA as [AA _].\n      apply cert_rfD in AA; auto. destruct_seq AA as [WX RY].\n      splits; auto; unfold is_w, is_r.\n      all: erewrite <- steps_preserve_lab with (state0:=state'') (state':=state'); eauto;\n        [ erewrite tr_lab; eauto; eapply E0_in_thread_execE with (TC:=TC); eauto\n        | | | by apply CACTS].\n      1-2: rewrite TX; auto.\n      all: rewrite TY; auto. }\n    { rewrite NEWRFI_IN_CERT.\n      rewrite cert_rf_tid_in_sb; auto.\n      unfold Execution.sb. basic_solver. }\n    { unfold new_rfi, new_rf. basic_solver. }\n    { rewrite <- CACTS. basic_solver. }\n    { rewrite STATECOV.\n      sin_rewrite sim_trav_step_covered_le.\n      2: by red; eauto.\n      rewrite C_in_D; eauto.\n      basic_solver. }\n\n    Ltac _ltt thread EE0 TCCOH OC CC CACTS CCD :=\n      rewrite OC; rewrite CC;\n      rewrite CACTS;\n      arewrite_id \u2997Tid thread\u2998; arewrite_id \u2997E0\u2998 at 1;\n      rewrite !seq_id_l;\n      (*unfold EE0, thread;*)\n      rewrite CCD; [| |apply TCCOH|]; auto;\n      basic_solver.\n\n    { _ltt thread E0 TCCOH OFAILDEP TEH.(tr_rmw_dep) CACTS dom_rmw_depE_in_D. }\n    { _ltt thread E0 TCCOH OADDR TEH.(tr_addr) CACTS dom_addrE_in_D. }\n    2: { _ltt thread E0 TCCOH OCTRL TEH.(tr_ctrl) CACTS dom_ctrlE_in_D. }\n\n    { rewrite CACTS.\n      arewrite ((E0 \\\u2081 D G TC') \u2229\u2081 E0 \u2286\u2081 E0 \\\u2081 D G TC') by basic_solver.\n      intros e [[EE DE] RE]. red.\n      apply DE.\n      set (EE':=EE).\n      destruct EE' as [TT [AA|AA]].\n      { by apply C_in_D. }\n      unfolder in AA.\n      destruct AA as [y [z [[EQx | SB] [EQ Iz]]]].\n      { rewrite EQx. by apply I_in_D. }\n      subst. red. do 2 left. right.\n      eexists. eexists. split.\n      { by left. }\n      apply seq_eqv_r. split; eauto.\n      assert (R_ex e) as UU.\n      { unfold Events.R_ex. rewrite <- LST2; auto. by apply CACTS. }\n      red. apply seq_eqv_l. split.\n      { by apply R_ex_in_R. }\n      apply seq_eqv_r. split.\n      2: by eapply issuedW; eauto.\n      apply ct_step. left. right.\n      apply seq_eqv_l. split; auto. }\n\n    { rewrite ODATA, CACTS.\n      arewrite_id \u2997E0\u2998 at 1. rewrite seq_id_l.\n      rewrite <- id_inter.\n      arewrite (E0 \u2229\u2081 set_compl (E0 \\\u2081 D G TC') \u2286\u2081 D G TC').\n      { unfolder. intros a [AA BB].\n        destruct (classic (D G TC' a)); auto.\n        exfalso. apply BB. desf. }\n      rewrite TEH.(tr_data), !seqA.\n      arewrite_id \u2997Tid thread\u2998. rewrite !seq_id_l.\n      generalize (dom_dataD_in_D). basic_solver 10. }\n\n    desf.\n\n    assert (instrs pre_cert_state = instrs state) as INSTRSS.\n    { eapply steps_same_instrs; eauto. }\n\n    edestruct get_stable with (state0:=pre_cert_state) (thread:=thread)\n      as [cert_state [CC _]].\n    { by rewrite INSTRSS. }\n    { eapply transitive_rt; [|by eauto]. by rewrite INSTRSS. }\n    desc.\n\n    assert (ProgToExecution.G cert_state = ProgToExecution.G pre_cert_state) as SCC.\n    { eapply eps_steps_same_G; eauto. }\n\n    assert (acts_set (ProgToExecution.G pre_cert_state) =\n            acts_set (ProgToExecution.G state'')) as SS.\n    { unfold acts_set. by rewrite RACTS. }\n\n    exists cert_state.\n    splits; auto.\n    2 : { eapply transitive_rt; eauto. by apply eps_steps_in_steps. }\n\n    assert (eq_dom (D G TC') (certLab G cert_state) (lab G))\n      as CERTLABD.\n    { intros e DE. unfold certLab.\n      unfold restr_fun.\n      destruct (excluded_middle_informative\n                  (acts_set (ProgToExecution.G cert_state) e))\n               as [CEE|]; auto.\n      rewrite SCC in *. rewrite SS in CEE.\n      rewrite <- LST2; auto.\n      apply same_label_u2v_val; auto.\n      apply OLD_VAL. intros [_ ND]. desf. }\n\n    constructor; auto.\n    all: try rewrite SCC.\n    { intros e DD.\n      eapply same_label_u2v_trans.\n      { by apply SAME. }\n      rewrite LST2; [by red; desf|].\n      red. by rewrite RACTS. }\n    { unfold acts_set. by rewrite <- RACTS. }\n    { rewrite <- RRMW, SS. rewrite ORMW, !CACTS.\n      rewrite TEH.(tr_rmw), !seqA.\n      rewrite seq_eqvC. seq_rewrite <- !id_inter.\n      arewrite (E0 \u2229\u2081 Tid thread \u2261\u2081 E0).\n      { rewrite set_interC. unfold CsbI. rewrite <- !set_interA.\n          by rewrite set_interK. }\n      symmetry. eapply E0_rmw_fwcl.\n      3 : eauto.\n      all: eauto. }\n\n    rewrite seq_eqv_r.\n    intros w r [RF TIDy].\n    apply cert_rf_codom in RF.\n    destruct_seq_r RF as EER.\n    unfold same_val, val.\n\n    destruct (classic (D G TC' r)) as [DR|NDR].\n    { rewrite CERTLABD with (x:=r); auto.\n      assert (rf w r) as RFWR.\n      { intros. eapply cert_rf_D_in_rf with (TC:=TC'); eauto.\n        apply seq_eqv_r. do 2 (split; eauto). }\n      assert (D G TC' w).\n      2: { rewrite CERTLABD; auto. apply wf_rfv; auto. }\n      eapply rf_D_CsbI_in_D; eauto.\n      basic_solver 10. }\n\n    unfold certLab at 2.\n    set (STE := EER).\n    assert (E0 r) as E0r.\n    { basic_solver. }\n    apply CACTS in E0r.\n    unfold restr_fun.\n    destruct (excluded_middle_informative (acts_set (ProgToExecution.G cert_state) r))\n      as [VV|VV].\n    2: { exfalso. apply VV. rewrite SCC. red. by rewrite <- RACTS. }\n    rewrite SCC.\n\n    set (LL := RF).\n    apply cert_rfE in LL; auto. destruct_seq LL as [RE RW].\n    apply cert_rfD in LL; auto. destruct_seq LL as [RR WW].\n\n    assert (Tid thread w -> sb w r) as SBWR.\n    { intros TTW.\n      edestruct same_thread with (x:=r) (y:=w) as [[SB|SB]|SB]; eauto.\n      { intros II. eapply init_w in II; eauto.\n        clear -WW II. type_solver. }\n      { desf. }\n      { subst. clear -RR WW. type_solver. }\n      exfalso. eapply cert_rf_hb_irr; eauto.\n      eexists; split; eauto. by apply sb_in_hb. }\n\n    assert (Tid thread w -> acts_set (ProgToExecution.G cert_state) w) as PP.\n    { intros TT. set (AA := TT).\n      apply SBWR in AA. rewrite SCC. red.\n      rewrite <- RACTS. apply CACTS.\n      eapply E0_sb_prcl; [|eauto|]; eauto.\n      basic_solver 10. }\n\n    destruct (classic (codom_rel new_rfi r)) as [DD|DD].\n    { set (TT:=DD). destruct TT as [w' TT].\n      set (OO := TT). destruct_seq OO as [TTW TTR].\n      assert (w' = w); subst.\n      { destruct_seq_r OO as QQ. eapply cert_rff; eauto. }\n      unfold certLab. unfold restr_fun.\n      set (OO' := OO). destruct_seq_r OO' as OOK.\n      assert (tid w = tid r) as EQT by congruence.\n      specialize (PP EQT).\n      destruct (excluded_middle_informative (acts_set (ProgToExecution.G cert_state) w));\n        [|done].\n      rewrite SCC.\n      symmetry. apply NEW_VAL1. red.\n      apply seq_eqv_l. split; auto.\n      apply seq_eqv_r. split; auto. }\n\n    destruct (classic (Tid thread w)) as [TTW|NTTW].\n    { exfalso. apply DD. exists w.\n      apply seq_eqv_l. split; auto.\n      apply seq_eqv_r. split; auto.\n      apply seq_eqv_r. do 2 (split; auto).\n      basic_solver. }\n\n    rewrite CERTLABD.\n    2: { apply cert_rf_iss_sb in LL; auto.\n         destruct LL as [LL | [SB STID]];\n           auto; [|congruence].\n         destruct_seq_l LL as Iw.\n           by apply I_in_D. }\n\n    etransitivity.\n    2: { symmetry. apply NEW_VAL2; auto.\n         2: by split.\n         eapply same_lab_u2v_is_r; eauto. unfold is_r. by rewrite LST2. }\n    unfold new_val, get_val, val.\n    assert (new_value r = w) as FF.\n    2: { rewrite FF; desf. clear -Heq RR. type_solver. }\n    assert (new_rfe w r) as RFE.\n    { apply seq_eqv_l. split; auto.\n      apply seq_eqv_r. split; auto.\n      apply seq_eqv_r. repeat (split; auto). }\n    specialize (HH r). destruct HH as [HH|HH].\n    { eapply new_rfef; eauto. }\n    clear -HH RFE. red in HH. desf.\n    exfalso. apply HH0. rewrite HH.\n    eexists. eauto.\nQed.\n\n(******************************************************************************)\n(** ** ilbl_step lemmas *)\n(******************************************************************************)\n\nLemma ilbl_step_E0_eindex lbls\n        (st st' st'' : Language.state (PromiseLTS.thread_lts thread))\n        (WFT : wf_thread_state thread st)\n        (CG : cert_graph G sc TC' thread st'')\n        (ILBL_STEP : ilbl_step thread lbls st st')\n        (CST_REACHABLE : (lbl_step thread)\uff0a st' st'') :\n  E0 (ThreadEvent thread st.(eindex)).\nProof.\n  eapply dcertE; [apply CG|].\n  eapply preserve_event.\n  { eapply lbl_steps_in_steps; eauto. }\n  edestruct ilbl_step_cases as [l [l' HH]]; eauto.\n  desf; apply ACTS; basic_solver.\nQed.\n\nLemma ilbl_step_E0_eindex' lbls lbl lbl'\n        (st st' st'' : Language.state (PromiseLTS.thread_lts thread))\n        (WFT : wf_thread_state thread st)\n        (CG : cert_graph G sc TC' thread st'')\n        (ILBL_STEP : ilbl_step thread lbls st st')\n        (LBLS_EQ : lbls = opt_to_list lbl' ++ [lbl])\n        (LBL' : lbl' <> None)\n        (CST_REACHABLE : (lbl_step thread)\uff0a st' st'') :\n  E0 (ThreadEvent thread (1 + st.(eindex))).\nProof.\n  eapply dcertE; [apply CG|].\n  eapply preserve_event.\n  { eapply lbl_steps_in_steps; eauto. }\n  edestruct ilbl_step_cases as [l [l' HH]]; eauto.\n  desf.\n  1-4 : apply opt_to_list_app_singl in LBLS; intuition.\n  desf; apply ACTS; basic_solver.\nQed.\n\n(* Lemma ilbl_step_cert_dom_eindex lbls *)\n(*         (st st' st'' : Language.state (Promise.thread_lts thread)) *)\n(*         (WFT : wf_thread_state thread st)  *)\n(*         (CG : cert_graph G sc TC TC' thread st'') *)\n(*         (ILBL_STEP : ilbl_step thread lbls st st') *)\n(*         (CST_REACHABLE : (lbl_step thread)\uff0a st' st'') :  *)\n(*   cert_dom st' \u2261\u2081 cert_dom st \u222a  *)\n(*            eq (ThreadEvent thread st.(eindex)) \u222a\u2081 eq (ThreadEvent thread (1 + st.(eindex))) *)\n(*   E0 (ThreadEvent thread st.(eindex)). *)\n\nEnd CertGraphLemmas.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/CertGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.18572646599867337}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.derive.Derive.\nRequire Import bedrock2.Syntax.\nRequire Import compiler.FlatToRiscvDef.\nRequire Import compiler.Pipeline.\nRequire Import compiler.RiscvWordProperties.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Map.Z_keyed_SortedListMap.\nRequire Import Bedrock2Experiments.WordProperties.\nRequire Import Bedrock2Experiments.IncrementWait.Constants.\nRequire Import Bedrock2Experiments.IncrementWait.IncrementWait.\nRequire Import Bedrock2Experiments.StateMachineMMIO.\nRequire Import Bedrock2Experiments.RiscvMachineWithCavaDevice.Bedrock2ToCava.\nRequire Import Bedrock2Experiments.IncrementWait.IncrementWaitSemantics.\nRequire coqutil.Word.Naive.\nRequire coqutil.Map.SortedListWord.\nRequire riscv.Utility.InstructionNotations.\nImport Syntax.Coercions.\nLocal Open Scope string_scope.\n\nInstance word: word.word 32 := Naive.word 32.\nInstance mem: map.map word Byte.byte := SortedListWord.map _ _.\nExisting Instance SortedListString.map.\nExisting Instance SortedListString.ok.\n\n(* TODO: we actually need a different word implementation than Naive here; in\n   corner cases such as a shift argument greater than the width of the word,\n   the naive implementation violates the riscv_ok requirements *)\nInstance naive_riscv_ok : word.riscv_ok word. Admitted.\n\nDefinition heap_start: word := word.of_Z (4*2^10).\n\n(* dummy base address -- just past end of stack *)\nDefinition base_addr : Z := 16 * 2^10.\n\nInstance circuit_spec : circuit_behavior :=\n  {| ncycles_processing := 15%nat |}.\n\nDefinition funcs := [put_wait_get].\n\nDefinition put_wait_get_compile_result_o :=\n  Eval vm_compute in compile compile_ext_call (map.of_list funcs).\n\nDefinition put_wait_get_compile_result:\n  list Decode.Instruction * (SortedListString.map (nat * nat * Z)) * Z.\n  let r := eval unfold put_wait_get_compile_result_o in put_wait_get_compile_result_o in\n      match r with\n      | Some ?x => exact x\n      end.\nDefined.\n\nLemma put_wait_get_compile_result_eq:\n  compile compile_ext_call (map.of_list funcs) = Some put_wait_get_compile_result.\nProof. reflexivity. Qed.\n\nDefinition put_wait_get_asm := Eval compute in fst (fst put_wait_get_compile_result).\n\nModule PrintAssembly.\n  Import riscv.Utility.InstructionNotations.\n  Redirect \"put_wait_get.s\" Print put_wait_get_asm.\n  (*\n    put_wait_get:\n     addi    x2, x2, -84   // decrease stack pointer\n     sw      x2, x1, 52    // save ra\n     sw      x2, x5, 0     // save registers that will be used for temporaries\n     sw      x2, x14, 4\n     sw      x2, x15, 8\n     sw      x2, x16, 12\n     sw      x2, x17, 16\n     sw      x2, x13, 20\n     sw      x2, x12, 24\n     sw      x2, x6, 28    // save registers that will be used for arguments\n     sw      x2, x7, 32\n     sw      x2, x8, 36\n     sw      x2, x9, 40\n     sw      x2, x10, 44\n     sw      x2, x11, 48\n     lw      x6, x2, 60    // load arguments\n     lw      x7, x2, 64\n     lw      x8, x2, 68\n     lw      x9, x2, 72\n     lw      x10, x2, 76\n     lw      x11, x2, 80\n     addi    x5, x2, 0     // save stack pointer in register?\n     sw      x6, x11, 0    // MMIO write : write value\n     addi    x13, x0, 0    // x13 = 0\n     addi    x14, x0, 1    // loop start\n     sll     x15, x14, x10 // 1 << STATUS_DONE\n     and     x16, x13, x15 // x13 & (1 << STATUS_DONE)\n     addi    x17, x0, 0\n     bne     x16, x17, 12  // if x16 != 0 then break loop\n     lw      x13, x7, 0    // MMIO read : read status\n     jal     x0, -24       // jump back to loop start\n     lw      x12, x6, 0    // MMIO read : read value\n     sw      x2, x12, 56   // store return value\n     lw      x5, x2, 0     // restore values of temporary registers\n     lw      x14, x2, 4\n     lw      x15, x2, 8\n     lw      x16, x2, 12\n     lw      x17, x2, 16\n     lw      x13, x2, 20\n     lw      x12, x2, 24\n     lw      x6, x2, 28    // restore values of argument registers\n     lw      x7, x2, 32\n     lw      x8, x2, 36\n     lw      x9, x2, 40\n     lw      x10, x2, 44\n     lw      x11, x2, 48\n     lw      x1, x2, 52    // load ra\n     addi    x2, x2, 84    // increase stack pointer\n     jalr    x0, x1, 0     // return\n\n\n    main:\n     addi    x2, x2, -48   // decrease stack pointer\n     sw      x2, x1, 44    // save ra\n     sw      x2, x5, 4     // save registers that will be used for temporaries\n     sw      x2, x7, 8\n     sw      x2, x8, 12\n     sw      x2, x9, 16\n     sw      x2, x10, 20\n     sw      x2, x11, 24\n     sw      x2, x12, 28\n     sw      x2, x13, 32\n     sw      x2, x6, 36\n     sw      x2, x14, 40\n     addi    x5, x2, 4     // save stack pointer+4 in register x5\n     addi    x6, x2, 0     // save stack pointer in register x6\n     lui     x7, 16384     // compute global constants\n     xori    x7, x7, 0\n     lui     x8, 16384\n     xori    x8, x8, 4\n     addi    x9, x0, 1\n     addi    x10, x0, 2\n     addi    x11, x0, 3\n     lui     x12, 16384    // compute input ptr\n     xori    x12, x12, 8\n     lw      x13, x12, 0   // load input\n     sw      x2, x7, -24   // put arguments on stack\n     sw      x2, x8, -20\n     sw      x2, x9, -16\n     sw      x2, x10, -12\n     sw      x2, x11, -8\n     sw      x2, x13, -4\n     jal     x1, -316      // call put_wait_get\n     lw      x6, x2, -28   // fetch return value\n     lui     x14, 16384    // compute output ptr\n     xori    x14, x14, 12\n     sw      x14, x6, 0    // store output\n     lw      x5, x2, 4     // restore values of temporary registers\n     lw      x7, x2, 8\n     lw      x8, x2, 12\n     lw      x9, x2, 16\n     lw      x10, x2, 20\n     lw      x11, x2, 24\n     lw      x12, x2, 28\n     lw      x13, x2, 32\n     lw      x6, x2, 36\n     lw      x14, x2, 40\n     lw      x1, x2, 44    // load ra\n     addi    x2, x2, 48    // increase stack pointer\n     jalr    x0, x1, 0     // return\n   *)\nEnd PrintAssembly.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/firmware/IncrementWait/IncrementWaitToRiscV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18572181923758124}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paco.\nFrom Paco Require Import paconotation_internal paco_internal pacotac_internal.\nFrom Paco Require Export paconotation.\nFrom Fairness Require Import pind_internal.\nSet Implicit Arguments.\n\nSection PIND9.\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.\n\n(** ** Predicates of Arity 9\n*)\n\nDefinition pind9(gf : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8)(r: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 :=\n  @curry9 T0 T1 T2 T3 T4 T5 T6 T7 T8 (pind (fun R0 => @uncurry9 T0 T1 T2 T3 T4 T5 T6 T7 T8 (gf (@curry9 T0 T1 T2 T3 T4 T5 T6 T7 T8 R0))) (@uncurry9 T0 T1 T2 T3 T4 T5 T6 T7 T8 r)).\n\nDefinition upind9(gf : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8)(r: rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) := pind9 gf r /9\\ r.\nArguments pind9 : clear implicits.\nArguments upind9 : clear implicits.\n#[local] Hint Unfold upind9 : core.\n\nLemma monotone9_inter (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8)\n      (MON1: monotone9 gf)\n      (MON2: monotone9 gf'):\n  monotone9 (gf /10\\ gf').\nProof.\n  red; intros. destruct IN. split; eauto.\nQed.\n\nLemma _pind9_mon_gen (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r r'\n    (LEgf: gf <10= gf')\n    (LEr: r <9= r'):\n  pind9 gf r <9== pind9 gf' r'.\nProof.\n  apply curry_map9. red; intros. eapply pind_mon_gen. apply PR.\n  - intros. apply LEgf, PR0.\n  - intros. apply LEr, PR0.\nQed.\n\nLemma pind9_mon_gen (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: pind9 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf')\n    (LEr: r <9= r'):\n  pind9 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  eapply _pind9_mon_gen; [apply LEgf | apply LEr | apply REL].\nQed.\n\nLemma pind9_mon_bot (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r' x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: pind9 gf bot9 x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf'):\n  pind9 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  eapply pind9_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nDefinition top9 { T0 T1 T2 T3 T4 T5 T6 T7 T8} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3) (x5: T5 x0 x1 x2 x3 x4) (x6: T6 x0 x1 x2 x3 x4 x5) (x7: T7 x0 x1 x2 x3 x4 x5 x6) (x8: T8 x0 x1 x2 x3 x4 x5 x6 x7) := True.\n\nLemma pind9_mon_top (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: pind9 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf'):\n  pind9 gf' top9 x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  eapply pind9_mon_gen; eauto. red. auto.\nQed.\n\nLemma upind9_mon_gen (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: upind9 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf')\n    (LEr: r <9= r'):\n  upind9 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  destruct REL. split; eauto.\n  eapply pind9_mon_gen; [apply H | apply LEgf | apply LEr].\nQed.\n\nLemma upind9_mon_bot (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r' x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: upind9 gf bot9 x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf'):\n  upind9 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  eapply upind9_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nLemma upind9mon_top (gf gf': rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8) r x0 x1 x2 x3 x4 x5 x6 x7 x8\n    (REL: upind9 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8)\n    (LEgf: gf <10= gf'):\n  upind9 gf' top9 x0 x1 x2 x3 x4 x5 x6 x7 x8.\nProof.\n  eapply upind9_mon_gen; eauto. red. auto.\nQed.\n\nSection Arg9.\n\nVariable gf : rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8 -> rel9 T0 T1 T2 T3 T4 T5 T6 T7 T8.\nArguments gf : clear implicits.\n\nTheorem _pind9_mon: _monotone9 (pind9 gf).\nProof.\n  red; intros. eapply curry_map9, _pind_mon; apply uncurry_map9; assumption.\nQed.\n\nTheorem _pind9_acc: forall\n  l r (OBG: forall rr (DEC: rr <9== r) (IH: rr <9== l), pind9 gf rr <9== l),\n  pind9 gf r <9== l.\nProof.\n  intros. apply curry_adjoint2_9.\n  eapply _pind_acc. intros.\n  apply curry_adjoint2_9 in DEC. apply curry_adjoint2_9 in IH.\n  apply curry_adjoint1_9.\n  eapply le9_trans. 2: eapply (OBG _ DEC IH).\n  apply curry_map9.\n  apply _pind_mon; try apply le1_refl; apply curry_bij2_9.\nQed.\n\nTheorem _pind9_mult_strong: forall r,\n  pind9 gf r <9== pind9 gf (upind9 gf r).\nProof.\n  intros. apply curry_map9.\n  eapply le1_trans; [eapply _pind_mult_strong |].\n  apply _pind_mon; intros [] H. apply H.\nQed.\n\nTheorem _pind9_fold: forall r,\n  gf (upind9 gf r) <9== pind9 gf r.\nProof.\n  intros. apply uncurry_adjoint1_9.\n  eapply le1_trans; [| apply _pind_fold]. apply le1_refl.\nQed.\n\nTheorem _pind9_unfold: forall (MON: _monotone9 gf) r,\n  pind9 gf r <9== gf (upind9 gf r).\nProof.\n  intros. apply curry_adjoint2_9.\n  eapply _pind_unfold; apply monotone9_map; assumption.\nQed.\n\nTheorem pind9_acc: forall\n  l r (OBG: forall rr (DEC: rr <9= r) (IH: rr <9= l), pind9 gf rr <9= l),\n  pind9 gf r <9= l.\nProof.\n  apply _pind9_acc.\nQed.\n\nTheorem pind9_mon: monotone9 (pind9 gf).\nProof.\n  apply monotone9_eq.\n  apply _pind9_mon.\nQed.\n\nTheorem upind9_mon: monotone9 (upind9 gf).\nProof.\n  red; intros.\n  destruct IN. split; eauto.\n  eapply pind9_mon. apply H. apply LE.\nQed.\n\nTheorem pind9_mult_strong: forall r,\n  pind9 gf r <9= pind9 gf (upind9 gf r).\nProof.\n  apply _pind9_mult_strong.\nQed.\n\nCorollary pind9_mult: forall r,\n  pind9 gf r <9= pind9 gf (pind9 gf r).\nProof. intros; eapply pind9_mult_strong in PR. eapply pind9_mon; eauto. intros. destruct PR0. eauto. Qed.\n\nTheorem pind9_fold: forall r,\n  gf (upind9 gf r) <9= pind9 gf r.\nProof.\n  apply _pind9_fold.\nQed.\n\nTheorem pind9_unfold: forall (MON: monotone9 gf) r,\n  pind9 gf r <9= gf (upind9 gf r).\nProof.\n  intro. eapply _pind9_unfold; apply monotone9_eq; assumption.\nQed.\n\nEnd Arg9.\n\nArguments pind9_acc : clear implicits.\nArguments pind9_mon : clear implicits.\nArguments upind9_mon : clear implicits.\nArguments pind9_mult_strong : clear implicits.\nArguments pind9_mult : clear implicits.\nArguments pind9_fold : clear implicits.\nArguments pind9_unfold : clear implicits.\n\nEnd PIND9.\n\nGlobal Opaque pind9.\n\n#[export] Hint Unfold upind9 : core.\n#[export] Hint Resolve pind9_fold : core.\n#[export] Hint Unfold monotone9 : core.\n\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/pico/pind9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18572181923758121}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom cap_machine Require Import rules_base addr_reg_sample map_simpl.\n\nSection test.\n  Context `{memG \u03a3, regG \u03a3}.\n\n  Lemma foo rmap:\n    ([\u2217 map] k\u21a6y \u2208 <[r_t3:=WInt 0%Z]>\n     (<[r_t2:=WInt 0%Z]>\n      (<[r_t4:=WInt 0%Z]>\n       (<[r_t5:=WInt 0%Z]> (delete r_t5 (<[r_t2:=WInt 0%Z]> (delete r_t3 (delete r_t1 rmap))))))),\n     k \u21a6\u1d63 y) -\u2217 \u231cTrue\u231d.\n  Proof.\n    iIntros \"H\".\n    map_simpl \"H\".\n  Abort.\n\n  Lemma foo (w1 w2 w3: Word) :\n    ([\u2217 map] k\u21a6y \u2208 delete r_t2 (<[r_t1:=w1]> (<[r_t2:=w2]> (<[r_t1:=w3]> \u2205))), k \u21a6\u1d63 y) -\u2217\n    r_t1 \u21a6\u1d63 w1 \u2217 r_t2 \u21a6\u1d63 w2.\n  Proof.\n    iIntros \"H\".\n    map_simpl \"H\".\n  Abort.\n\n  Lemma expressions_allowed pc_p pc_b pc_e a_first:\n    ([\u2217 map] k\u21a6y \u2208  (<[r_t8:= WCap pc_p pc_b pc_e (a_first ^+ 0)%a]>\n                       (<[r_t8 := WInt 0]> \u2205)),\n            k \u21a6\u1d63 y) -\u2217 \u231c True \u231d.\n  Proof. iIntros \"Ht\".\n         map_simpl \"Ht\".\n  Abort.\nEnd 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_test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.1855199704205148}}
{"text": "Require Import RelationClasses.\nRequire Import List.\nRequire Import Basics.\nRequire Import Coqlib.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import DenseOrder.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\n\nRequire Import Memory.\nRequire Import Cell.\nRequire Import Time.\nRequire Import Thread.\nRequire Import Local.\nRequire Import CompAuxDef.\n\nRequire Import Kildall.\nRequire Import AveAnalysis.\nRequire Import CorrectOpt.\nRequire Import MsgMapping.\nRequire Import CSE.\nRequire Import LocalSim.\nRequire Import LibTactics.\nRequire Import Event.\nRequire Import View.\nRequire Import TView.\n\nRequire Import CSEProofAux.\nRequire Import CSEProofMState.\nRequire Import CSEProofStep.\n\n(** * Correctness Proof of Common subexpression elimination *)\n\n(** Top level proofs for Common Subexpression Elimination's correctness *)\n\n(** the top lemma organizes individual transition's correctness *)\nTheorem cse_match_state_implies_sim:\n  forall inj lo e_tgt e_src b,\n  cse_match_state inj lo e_tgt e_src b\n  -> @local_sim_state nat lt rtl_lang cse_invariant lo inj DelaySet.dset_init b e_tgt e_src.\nProof.\n  cofix COFIX.\n  intros.\n  destruct e_tgt as (st_tgt, lc_tgt, sc_tgt, mem_tgt) eqn:EqETgt.\n  destruct e_src as (st_src, lc_src, sc_src, mem_src) eqn:EqESrc.\n\n  pose proof (classic (Local.promise_consistent lc_tgt)).\n  destruct H0 as [CsstTgt|NotCsstTgt].\n  2: {\n    eapply local_sim_state_tgt_not_prm_consistent_intro; eauto.\n  }\n\n  pose proof (classic (Thread.is_abort e_tgt lo)).\n  destruct H0 as [|NotAbort]. \n  { \n    eapply local_sim_state_abort_intro; eauto.\n    eapply cse_match_state_implies_abort_preserving. splits; eauto.\n    rewrite EqETgt in H0; eauto.\n  } \n\n  eapply local_sim_state_step_intro; eauto.\n  eapply cse_match_state_implies_si; eauto.\n  4: { (** case: abort step -> sim. proved. *)\n    intro. rewrite EqETgt in NotAbort. contradiction.\n  }\n  3: { (** case: done step -> sim *)\n    pose proof (classic (Thread.is_done e_tgt)).\n\n    destruct H0 as [Done|NotDone].\n    2: {\n      intros. rewrite <- EqETgt in DONE. contradiction.\n    }\n    (** case: done. straightforward. *)\n    intros. clear DONE.\n    inversion H. simpls.\n    exists e_src; exists inj'.\n    splits; eauto.\n    { (** na_steps *)\n      rewrite <- EqESrc.\n      eapply rtc_refl.\n      econs.\n    }\n    2: { (** trivial incr_inj *)\n      destruct PREEMPT as [(_&EQ_INJ) | (_&INCR_INJ)].\n      apply eq_inj_implies_incr; trivial.\n      trivial.\n    }\n    2: { (** trivial invariant *)\n      rewrite EqESrc; simpls.\n      trivial.\n    }\n    { (** tgt done -> src done *)\n      unfolds Thread.is_done.\n      destruct Done as (IsTermTgt & NoPrmTgt).\n      splits.\n      2: { (** src promise free *)\n        rewrite EqESrc. rewrite EqETgt in NoPrmTgt. simpls.\n        inv H. inv MATCH_LOCAL. simpls.\n        rewrite <- PROMISES_EQ. trivial. \n      }\n      { (** src done *)\n        unfolds Language.is_terminal; simpls.\n        unfolds State.is_terminal.\n        destruct IsTermTgt as (RetTgt & ContDoneTgt).\n        inv H.\n        inv MATCH_LOCAL. \n        inv MATCH_RTL_STATE. simpls.\n        splits.\n        inv MATCH_FRAME.\n        remember (AveAI.br_from_i analysis !! l i) as ai. \n        rewrite RetTgt in TRANSF_BLK.\n        eapply ret_transformed_by_ret; eauto.\n\n        inv MATCH_CONT.  \n        destruct DONE; trivial.\n        rewrite ContDoneTgt in CONT_T; discriminate.\n      }\n    }\n  }\n  2: { (** case: rely step -> sim *)\n    intro.\n    splits.\n    { (** I still holds *)\n      inv H; simpls. \n      destruct PREEMPT as [(_&EQ_INJ) | (B&INCR_INJ)].\n      2: { discriminate. }\n      eapply eq_inj_implies_invariant; eauto.\n      eapply eq_inj_sym.\n      trivial. \n    }\n    intros.\n    rewrite OUT_ATMBLK in H.\n    eapply cse_match_state_preserving_rely in H; eauto.\n  }\n  (** case: thread step -> sim *)\n  intros. splits.\n  { (** case: at step -> sim *)\n    intros.\n    destruct e_tgt' as (st_tgt', lc_tgt', sc_tgt', mem_tgt') eqn:EqETgt'.\n    eapply cse_match_state_preserving_at \n      with (st_tgt' := st_tgt') (lc_tgt' := lc_tgt') \n           (sc_tgt' := sc_tgt') (mem_tgt' := mem_tgt')\n      in H; eauto. \n    2: {\n          { \n            inversion STEP.\n            {\n              (** at is not prc *)\n              inv STEP0.\n              unfolds ThreadEvent.is_at_or_out_step. contradiction.\n            }\n            trivial.\n          } \n      }\n      {\n        destruct H as (st_src' & lc_src' & sc_src' & mem_src' & inj' & H & H1 & H2).\n        remember {|\n                Thread.state := st_src';\n                Thread.local := lc_src';\n                Thread.sc := sc_src';\n                Thread.memory := mem_src'\n              |} as e_src'.\n        \n        exists e_src. exists e_src'. exists inj'. exists te.\n        rewrite <- EqESrc.\n        splits; eauto.\n        rewrite EqESrc.\n        trivial.\n        eapply thrdevt_eq_refl.\n      }\n  }\n  { (** case: na step -> sim *)\n    intros.\n    destruct e_tgt' as (st_tgt', lc_tgt', sc_tgt', mem_tgt') eqn:EqETgt'.\n    pose proof classic (ThreadEvent.is_na_access te).\n    destruct H0 as [IS_NA_ACCESS | NOT_NA_ACCESS].\n    { (** is na access *)\n      eapply cse_match_state_preserving_na_access \n      with (st_tgt' := st_tgt') (lc_tgt' := lc_tgt') \n          (sc_tgt' := sc_tgt') (mem_tgt' := mem_tgt')\n      in H; eauto. \n      destruct H as (st_src' & lc_src' & sc_src' & mem_src' & H1 & H2).\n      2: {\n          { \n            inversion STEP.\n            {\n              inv STEP0.\n              unfolds ThreadEvent.is_at_or_out_step. contradiction.\n            }\n            trivial.\n          } \n        }\n        remember {|\n        Thread.state := st_src';\n        Thread.local := lc_src';\n        Thread.sc := sc_src';\n        Thread.memory := mem_src'\n      |} as e_src'.\n      pose proof classic (ThreadEvent.is_na_write te).\n      destruct H as [IS_NA_WRITE | NOT_NA_WRITE].\n      2: { (** na read *)\n        exists e_src'. \n        do 3 exists (@DelaySet.dset_init nat).\n        unfolds ThreadEvent.is_na_write; unfolds ThreadEvent.is_na_access.\n        inversion H1.\n        simpls.\n        destruct te; simpls; try contradiction; eauto.\n        destruct ord; simpls; try contradiction; eauto.\n        splits; eauto.\n        - eapply DelaySet.dset_become_na_read; eauto.\n        - eapply DelaySet.na_steps_dset_read with (dset:=DelaySet.dset_init) in H1; eauto.\n          {\n            eapply Operators_Properties.clos_rt1n_step in H1.\n            rewrite <- H6 in H1.\n            rewrite H1.\n            eapply rtc_refl. econs.\n          }\n          {\n            simpls. intros.\n            rewrite DelaySet.dset_gempty in H.\n            discriminate.\n          }           \n        - eapply DelaySet.dset_reduce_init; eauto.\n        - rewrite <- H6 in H2. auto.\n      }\n      (** is na write *)\n      unfolds ThreadEvent.is_na_write. \n      destruct te; try contradiction; eauto.\n      destruct ord; try contradiction; eauto.\n      exists e_src'. \n      exists (DelaySet.dset_add loc to 0 DelaySet.dset_init).\n      do 2 exists (@DelaySet.dset_init nat).\n      splits; eauto. \n      - eapply DelaySet.dset_become_na_write; eauto. \n      - eapply DelaySet.na_steps_dset_write in H1; eauto.\n        right. exists to.\n        rewrite DelaySet.dset_remove_add. trivial.\n      - eapply DelaySet.dset_reduce_init.\n    }\n    { (** is na silent *)\n      unfolds ThreadEvent.is_na_access.\n      unfolds ThreadEvent.is_na_step.\n      destruct te eqn:EqTe; simpls; eauto; try contradiction.\n      clear NA_STEP; clear NOT_NA_ACCESS.\n      eapply cse_match_state_preserving_na_silent\n      with (st_tgt' := st_tgt') (lc_tgt' := lc_tgt') \n          (sc_tgt' := sc_tgt') (mem_tgt' := mem_tgt')\n      in H; eauto.\n      2: {\n        inversion STEP. inversion STEP0.   auto.\n      } \n      destruct H as (st_src' & lc_src' & sc_src' & mem_src' & te' & SILENT & SRCSTEP & MATCH_STATE).\n      remember {|\n        Thread.state := st_src';\n        Thread.local := lc_src';\n        Thread.sc := sc_src';\n        Thread.memory := mem_src'\n      |} as e_src'.\n      exists e_src'.\n      do 3 exists (@DelaySet.dset_init nat).\n      splits; eauto.\n      - eapply DelaySet.dset_become_na_read; eauto.\n      - destruct SILENT; eauto. \n        { \n          rewrite H in SRCSTEP.\n          eapply DelaySet.na_steps_dset_tau in SRCSTEP; eauto. \n        }\n        { \n          unfold ThreadEvent.is_na_read in H.\n          destruct te'; try discriminate; try contradiction; eauto.\n          destruct ord; try contradiction; eauto.\n          eapply DelaySet.na_steps_dset_read in SRCSTEP; eauto.\n          simpls.\n          intros.\n          rewrite DelaySet.dset_gempty in H0; discriminate.\n        }\n      - eapply DelaySet.dset_reduce_init; eauto.\n    }\n  }\n  { (** case: promise step -> sim *)\n    intros.\n    destruct e_tgt' as (st_tgt', lc_tgt', sc_tgt', mem_tgt') eqn:EqETgt'.\n    eapply cse_match_state_preserving_prm \n      with (st_tgt' := st_tgt') (lc_tgt' := lc_tgt') \n          (sc_tgt' := sc_tgt') (mem_tgt' := mem_tgt')\n          (te := te)\n      in H; eauto.\n    2: {\n      rewrite PROMISE in STEP.\n      destruct PRM_STEP as (loc & t & PRM_STEP).\n      unfolds ThreadEvent.is_promising.\n      destruct te; try discriminate; eauto. \n      inv PRM_STEP.\n      inv STEP.\n      trivial.\n    }\n    destruct H as (st_src' & lc_src' & sc_src' & mem_src' & inj' & H & H1 & H2).\n    remember {|\n        Thread.state := st_src';\n        Thread.local := lc_src';\n        Thread.sc := sc_src';\n        Thread.memory := mem_src'\n      |} as e_src'.\n    exists e_src'. exists inj'. \n    splits; eauto.\n    eapply rtc_n1 with (b:=e_src).\n    - rewrite EqESrc. eapply rtc_refl. trivial.\n    - rewrite EqESrc.  \n      rewrite PROMISE in STEP.\n      destruct PRM_STEP as (loc & t & PRM_STEP).\n      unfolds ThreadEvent.is_promising.\n      destruct te; try discriminate; eauto.\n      inv PRM_STEP. \n      eapply Thread.prc_step_intro; eauto.\n  }\n  { (** case: promise-free step -> sim *)\n    intros.\n    destruct e_tgt' as (st_tgt', lc_tgt', sc_tgt', mem_tgt') eqn:EqETgt'.\n    eapply cse_match_state_preserving_pf_prm \n      with (st_tgt' := st_tgt') (lc_tgt' := lc_tgt') \n           (sc_tgt' := sc_tgt') (mem_tgt' := mem_tgt')\n      in H; eauto.\n    2: {\n        eapply Thread.pf_promise_step_intro with (e:=te).\n        rewrite PF in STEP.\n        destruct PRM_STEP as (loc & t & PRM_STEP).\n        unfolds ThreadEvent.is_promising.\n        destruct te; try discriminate; eauto. \n        inv PRM_STEP. simpls.\n        inv STEP; eauto.\n        inversion STEP0.\n        inv LOCAL; try discriminate; eauto. \n    } \n    destruct H as (st_src' & lc_src' & sc_src' & mem_src' & H & H1).\n    remember {|\n        Thread.state := st_src';\n        Thread.local := lc_src';\n        Thread.sc := sc_src';\n        Thread.memory := mem_src'\n      |} as e_src'.\n    exists e_src'.\n    splits; eauto.\n  }\nQed.\n\n(** ** Correctness of the Common subexpression elimination *)\n(** proof for initial match state *)\nTheorem verif_cse:\n  forall code_s code_t lo,\n      cse_optimizer lo code_s = Some code_t \n      ->\n      @local_sim nat lt rtl_lang cse_invariant lo code_t code_s.\nProof.\n  intros.\n  constructor.\n  - apply nat_lt_is_well_founded.\n  - apply wf_cse_invariant.\n  - apply cse_invariant_init.\n  - intros.\n    inv INIT_STATE.\n    unfolds State.init; simpls. \n    destruct (code_t ! fid) eqn:CodetFunc; try discriminate.\n    destruct f eqn:FunctCdhp. destruct (c ! f0) eqn:CdhptBlk; try discriminate.\n    inversion H1. clear H1. rewrite H2.\n    pose proof H as OPT.\n    unfold cse_optimizer in H. inversion H. clear H.\n    unfolds transform_prog.\n    pose proof CodetFunc.\n    rewrite <- H1 in H.\n\n    rewrite PTree.gmap in H.\n    unfolds Coqlib.option_map.\n    destruct (code_s ! fid) eqn:CodeSFunc; try discriminate.\n    inversion H. clear H.\n    destruct f1 eqn:FuncS.\n    rename f1 into func_s, c0 into cdhp_s, f2 into fentry_s.\n    rename f into func_t, c into cdhp_t, f0 into fentry_t, t into blk_t.\n    (** \n      code_t -> func_t -> (cdhp_t, fentry_t) -> blk_t\n      code_s -> func_s -> chdp_s [] -> [] \n    *)\n    unfolds transform_func.\n    remember (AveDS.analyze_program code_s succ AveLat.top Ave_B.transf_blk) ! fid as AFunc.\n    assert (fentry_s = fentry_t). {\n      destruct AFunc; inv H3; auto. \n    } \n    remember (cdhp_s ! fentry_s) as opt_blk_s.\n    destruct opt_blk_s eqn:BlkS.\n    2: {  (** blk_t exists implies blk_s exists  *)\n      destruct AFunc eqn:AFuncEq. \n      2: { (** AFunc = None => blk_t = blk_s *)\n        inversion H3. rewrite H4 in Heqopt_blk_s. rewrite H5 in Heqopt_blk_s. rewrite <- Heqopt_blk_s in CdhptBlk. discriminate.\n      } (** AFunc = Some res => blk_t becomes from blk_s *)\n      inversion H3.\n      pose proof CdhptBlk.\n      unfolds transform_cdhp.\n      rewrite <- H4 in H0.\n      rewrite PTree.gmap in H0.\n      unfolds Coqlib.option_map.  \n      destruct (cdhp_s ! fentry_t) eqn:BlkSS; try discriminate. \n      rename t into blk_s. rewrite <- H5 in BlkSS. rewrite BlkSS in Heqopt_blk_s. discriminate.\n    }\n    rename t into blk_s.\n    clear BlkS opt_blk_s.\n    (** Some prepare clean-up finished.*)\n    (** Now we have:  \n        fid & AFunc\n        code_t -> func_t -> (cdhp_t, fentry_t) -> blk_t\n          SS       SS          SS       ||         SS\n        code_s -> func_s -> (chdp_s, fentry_t) -> blk_s \n    *)\n    (** Let prove match_state_init *)\n    remember (State.mk RegFile.init blk_s cdhp_s Continuation.done code_s) as st_src.\n    exists st_src.\n    splits.\n    { (** Init(code_s, fid) = st_src*)\n        unfolds State.init. rewrite CodeSFunc. rewrite <- Heqopt_blk_s. eapply f_equal. eauto.\n    }\n    (** let's prove local simulation *)  \n    (** 1. we have match_state on initial states *)\n    pose proof (cse_invariant_init lo).\n  assert (cse_match_state inj_init lo \n    (Thread.mk rtl_lang st_tgt Local.init TimeMap.bot Memory.init) \n    (Thread.mk rtl_lang st_src Local.init TimeMap.bot Memory.init) true). {\n      eapply cse_match_state_intro with (inj' := inj_init); simpls; eauto.\n      2: { (** inj = inj' = init_inj *)\n        left. splits; eauto.\n        unfolds eq_inj. intros; eauto.\n      }\n      2: {\n        eapply Local.wf_init.\n      }\n      2: {\n        eapply Memory.closed_timemap_bot.\n        unfolds Memory.inhabited; intros; eauto.\n      }\n      2: {\n        eapply Memory.init_closed.\n      }\n      (** match local state *)\n      eapply cse_match_local_state_intro; eauto.\n      2: {\n        unfolds Local.init; simpl; eauto. unfolds TView.eq; eauto.\n      }\n      destruct AFunc eqn:AFunc_is_None.\n      (** match rtl state *)\n      eapply cse_match_rtl_state_intro; eauto.\n      { (** transform code_s aprog = code_t *) \n        rewrite Heqst_src; simpls. \n        rewrite <- H2; simpls. auto.\n      }\n      2: { (* match_cont *)\n      rewrite Heqst_src; rewrite <- H2; simpls. \n      eapply cse_match_cont_base; auto. \n      }\n      { (* cse_match_frame *)\n        rename a into acdhp.\n        eapply cse_match_frame_intro with (i := 0) (l := fentry_s) (enode := fentry_s) (blk := blk_s) (analysis:= acdhp); \n        try rewrite Heqst_src; try rewrite <- H2; simpls; eauto.\n        2: { inv H3; trivial. }\n        3: { (** match abstract interp *)\n          unfolds match_abstract_interp; unfolds AveAI.br_from_i; simpls.\n          assert (AveAI.ge (AveAI.getFirst (acdhp !! fentry_s)) AveLat.top).\n          {\n            eapply AveDS.analyze_func_entry; eauto.\n            eapply Ave_B.wf_transf_blk.\n          }\n          remember (AveAI.getFirst acdhp!!fentry_s) as aentry.\n          - destruct aentry; eauto. \n            simpls.\n            intros.\n            pose proof W.empty_1. unfolds W.Empty. unfolds W.Subset.\n            eapply H4 in H5. eapply H6 in H5. contradiction.\n        }\n        2: {  (** transform blk_s analysis fentry_s => blk_t *)\n            unfolds AveAI.br_from_i; simpls.\n            inversion H3; clear H6.\n            unfold transform_cdhp in H5.\n            pose proof CdhptBlk.\n            rewrite <- H5 in H4.\n            rewrite PTree.gmap in H4; unfolds Coqlib.option_map; simpls.\n            rewrite <- H in H4; rewrite <- Heqopt_blk_s in H4.\n            inversion H4.\n            unfold transform_blk'. rewrite H; auto.\n        }\n        {\n            pose proof HeqAFunc.\n            unfold AveDS.analyze_program in H4.\n            rewrite PTree.gmap1 in H4.\n            unfolds Coqlib.option_map.\n            rewrite CodeSFunc in H4. simpls.\n            inversion H4. \n            remember (AveDS.fixpoint_blk cdhp_s succ fentry_s AveLat.top\n                (fun (n : positive) (ai : AveDS.AI.t) =>\n                match cdhp_s ! n with\n                | Some b => Ave_B.transf_blk ai b\n                | None => AveDS.AI.Atom ai\n                end)) as acdhp_partial.\n            destruct acdhp_partial eqn:acdhp_partial_eq.\n             - left.  trivial.\n             - right. trivial.  \n        }\n        { (** link *)\n          unfolds AveAI.br_from_i; simpls.\n          intros.\n          eapply AveDS.analyze_func_solution; eauto.\n          eapply Ave_B.wf_transf_blk.\n          eapply Ave_B.wf_transf_blk2.\n        }\n        {\n          unfolds AveAI.br_from_i; simpls.\n          assert (AveAI.ge (AveAI.getFirst (acdhp !! fentry_s)) AveLat.top).\n          {\n            eapply AveDS.analyze_func_entry; eauto.\n            eapply Ave_B.wf_transf_blk.\n          }\n          unfold AveAI.ge in H4. unfold AveDS.L.ge in H4.\n          destruct (AveAI.getFirst acdhp !! fentry_s) eqn:EqEntry; unfolds AveLat.top; try contradiction; eauto.\n          assert (W.Empty tuples). {\n            unfolds W.Subset.\n            pose proof (classic (exists a, W.In a tuples)). destruct H5; trivial.\n            2: {\n              unfold W.Empty.\n              eapply not_ex_all_not. trivial.\n            }\n            destruct H5.\n            specialize (H4 x H5).\n            pose proof W.empty_1. unfolds W.Empty. \n            specialize (H6 x). contradiction.\n          }\n          unfolds loc_fact_valid.\n          intros. \n          unfolds W.Empty. \n          specialize (H5 (AveTuple.AVar r loc)). \n          contradiction.\n        }\n      }\n      {\n          rewrite <- H2.\n          rewrite Heqst_src.\n          simpls.\n          eapply AveDS.wf_analyze_func with (eval := AveLat.top) (transfb := Ave_B.transf_blk) in CodeSFunc; eauto.\n          destruct CodeSFunc as (acdhp & ACdhp).\n          rewrite ACdhp in HeqAFunc. discriminate.\n      }\n      {\n        unfold mem_injected.\n        intros.\n        unfold Local.init in MSG; simpls. \n        rewrite Memory.bot_get in MSG. discriminate.\n      }\n    }\n    apply cse_match_state_implies_sim in H4; simpls; auto.\nQed.\n \n(** Common subexpression elimination optimizer is correct. *)\nTheorem correct_cse:\n  Correct cse_optimizer.\nProof.\n  eapply Verif_implies_Correctness.\n  unfolds Verif. intros. exists cse_invariant nat lt. \n  eapply verif_cse; eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/CSEProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.18551996674150922}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\nRequire Import Coq.Strings.String.\n\nRequire Import lib.utils.\nRequire Import common.types.\nRequire Import concrete.concrete.\nRequire Import concrete.exec.\nRequire Import symbolic.symbolic.\nRequire Import symbolic.exec.\nRequire Import symbolic.rules.\nRequire Import symbolic.refinement_common.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nHint Constructors restricted_exec.\nHint Unfold exec.\nHint Resolve restricted_exec_trans.\n\nSection Refinement.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {opss : machine_ops_spec ops}\n        {sp : Symbolic.params}\n        {e : encodable mt Symbolic.ttypes}\n        {mi : monitor_invariant}\n        {table : Symbolic.syscall_table mt}\n        {mcc : monitor_code_bwd_correctness mi table}.\n\nHint Unfold Symbolic.next_state.\nHint Unfold Symbolic.next_state_reg_and_pc.\nHint Unfold Symbolic.next_state_pc.\nHint Unfold Symbolic.next_state_reg.\n\nHint Resolve monitor_invariant_upd_mem.\nHint Resolve monitor_invariant_upd_reg.\nHint Resolve monitor_invariant_store_mvec.\n\nLocal Open Scope string_scope.\n\nLtac check_conv t1 t2 :=\n  let e := constr:(erefl t1 : t1 = t2) in idtac.\n\nLtac contradict_in_user :=\n  match goal with\n  | INUSER : is_true (in_user ?st),\n    ISMONITOR : ?t = Concrete.TMonitor |- _ =>\n    check_conv (Concrete.pct st) t;\n    first [ rewrite ISMONITOR /in_user /= decode_monitor_tag in INUSER; done |\n            failwith \"contradict_in_user\" ]\n  end.\n\nLtac destruct_hseq :=\n  repeat match goal with\n  | x : hseq _ _ |- _ => simpl in x\n  | x : hseq_nil |- _ => destruct x\n  | x : hseq_cons _ _ |- _ => destruct x\n  end.\n\nLtac analyze_cache :=\n  match goal with\n  | LOOKUP : Concrete.cache_lookup ?cache _ ?mvec = Some ?rvec,\n    PC     : getm _ ?pc = Some ?i@_,\n    INST   : decode_instr ?i = Some _,\n    INUSER : is_true (in_user (Concrete.State _ _ _ ?pc@_ _)),\n    CACHE  : cache_correct ?cache ?cmem |- _ =>\n    first [\n        assert (CACHEHIT := analyze_cache CACHE LOOKUP INUSER);\n        simpl in CACHEHIT;\n        repeat match type of CACHEHIT with\n        | exists _, _ => destruct CACHEHIT as [? CACHEHIT]\n        | _ /\\ _ => destruct CACHEHIT as [? CACHEHIT]\n        | _ \\/ _ => destruct CACHEHIT as [CACHEHIT | CACHEHIT]\n        | and3 _ _ _ => destruct CACHEHIT\n        | and4 _ _ _ _ => destruct CACHEHIT\n        | False => destruct CACHEHIT\n        end;\n        try contradict_in_user; destruct_hseq; match_inv; simpl in *\n      | failwith \"analyze_cache hit\" ]\n  | INUSER : is_true (in_user (Concrete.miss_state ?st ?mvec)) |- _ =>\n    first [ destruct (negP (miss_state_not_user st mvec) INUSER) |\n            failwith \"analyze_cache miss\" ]\n  end.\n\nLtac relate_register_get :=\n  match goal with\n  | REFR : refine_registers ?areg ?creg ?cmem,\n    GET : getm ?creg ?r = Some _@?t,\n    DEC : decode Symbolic.R ?cmem ?t = Some _ |- _ =>\n    match goal with\n    | GET' : getm areg r = Some _ |- _ => fail 1\n    | |- _ => first [ pose proof (proj1 REFR _ _ _ _ DEC GET) |\n                      failwith \"relate_register_get\" ]\n    end\n  end.\n\nLtac relate_memory_get :=\n  match goal with\n  | MEM : getm ?cmem ?addr = Some _@?t,\n    REFM : refine_memory ?smem ?cmem,\n    DEC : decode Symbolic.M ?cmem ?t = Some (User _) |- _ =>\n    match goal with\n    | _ : getm smem addr = Some _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    first [ pose proof (proj1 REFM _ _ _ _ DEC MEM) |\n            failwith \"relate_memory_get\" ]\n  end.\n\nLtac relate_register_upd :=\n  match goal with\n  | GET : getm ?reg ?r = Some _@?t,\n    DEC : decode Symbolic.R ?cmem ?t = Some _,\n    UPD : updm ?reg ?r ?v@?t' = Some ?reg',\n    DEC' : decode Symbolic.R ?cmem ?t' = Some _,\n    REFR : refine_registers _ ?reg ?cmem,\n    MINV : monitor_invariant_statement ?mi ?cmem _ _ _ |- _ =>\n    first [ destruct (refine_registers_upd REFR GET DEC UPD DEC') as [? ? ?];\n            pose proof (monitor_invariant_upd_reg MINV GET DEC UPD DEC')\n          | failwith \"relate_register_upd\" ]\n  end.\n\nLtac relate_memory_upd :=\n  match goal with\n  | GET : getm ?cmem ?addr = Some _@?t,\n    DEC : decode Symbolic.M ?cmem ?t = Some (User _),\n    UPD : updm ?cmem ?addr _@?t' = Some _,\n    DEC' : decode Symbolic.M ?cmem ?t' = Some (User _),\n    CACHE : cache_correct _ ?cmem,\n    REFR : refine_registers _ _ ?cmem,\n    REFM : refine_memory _ ?cmem,\n    WFENTRYPOINTS : wf_entry_points _ ?cmem,\n    MVEC : mvec_in_monitor ?cmem |- _ =>\n    first [ destruct (refine_memory_upd CACHE REFR REFM GET DEC UPD DEC') as [? [? ? ?]];\n            pose proof (wf_entry_points_user_upd WFENTRYPOINTS GET DEC UPD DEC');\n            pose proof (mvec_in_monitor_user_upd MVEC GET DEC UPD DEC')\n          | failwith \"relate_memory_upd\" ]\n  end.\n\nLtac update_decodings :=\n  match goal with\n  | DEC : decode ?k ?cmem ?ct = Some ?ut,\n    UPD : updm ?cmem _ _ = Some ?cmem' |-\n    decode ?k ?cmem' ?ct = Some ?ut =>\n    first [ solve [ rewrite /= -DEC (updm_set UPD);\n                    erewrite decode_monotonic; eauto ] |\n            failwith \"update_decodings\" ]\n  end.\n\nLtac find_and_rewrite :=\n  match goal with\n  | H : ?x = _ |- context[?x] =>\n    rewrite H; clear H; simpl\n  end.\n\nLtac simplify_eqs :=\n  match goal with\n  | E1 : ?x = ?y1,\n    E2 : ?x = ?y2 |- _ =>\n    rewrite E1 in E2;\n    inversion E2; subst; clear E2\n  end.\n\nLtac solve_step :=\n  solve [\n      s_econstructor (\n          solve [eauto;\n                 repeat autounfold;\n                 repeat simplify_eqs;\n                 repeat (find_and_rewrite; simpl);\n                 reflexivity])\n    | failwith \"solve_step\" ].\n\nLtac solve_refine_state :=\n  solve [ econstructor; eauto; try update_decodings\n        | failwith \"solve_refine_state\" ].\n\nLemma refine_ivec_inv sst cst cmvec ivec :\n  refine_state mi table sst cst ->\n  build_cmvec cst = Some cmvec ->\n  decode_ivec e (Concrete.mem cst) cmvec = Some ivec ->\n  build_ivec table sst = Some ivec.\nProof.\n  move=> Href Hbuild /decode_ivec_inv /=.\n  case: ivec => [[op|] tpc ti ts]; last first.\n    case=> [Hop Hdec_tpc Hdec_ti].\n    rewrite (build_cmvec_ctpc Hbuild) in Hdec_tpc.\n    have [i [instr [Hget Hdec_i Hop']]] := build_cmvec_cop_cti Hbuild.\n    move: Hop. rewrite -{}Hop'.\n    case: instr Hdec_i => // /is_nopP Hdec_i _.\n    have [sc Hget_sc Hsct] := wf_entry_points_only_if (rs_entry_points Href)\n                                                      Hget Hdec_ti Hdec_i.\n    rewrite /build_ivec (rs_pc Href).\n    case Hget': (getm _ _) => [[i' ti']|] //=.\n      have [cti] := proj2 (rs_refm Href) _ _ _ Hget'.\n      rewrite Hget => Hdec_ti' [? ?]. subst i' cti.\n      by rewrite Hdec_ti' in Hdec_ti.\n    rewrite (rs_pct Href) in Hdec_tpc.\n    case: Hdec_tpc => ->. rewrite Hget_sc Hsct.\n    by rewrite [in RHS]hseq0.\n  case=> [Hop Hpriv Hdec_tpc Hdec_ti Hdec_ts].\n  move: ti ts Hdec_ti Hdec_ts; rewrite {}Hop => ti ts Hdec_ti Hdec_ts.\n  rewrite (build_cmvec_ctpc Hbuild) (rs_pct Href) in Hdec_tpc.\n  case: Hdec_tpc => ?. subst tpc.\n  have [i [instr [Hget_i Hdec_i Hop']]] := build_cmvec_cop_cti Hbuild.\n  move: ts Hdec_ts; rewrite -{}Hop'=> ts Hdec_ts.\n  move: Hbuild.\n  rewrite /build_cmvec /build_ivec (rs_pc Href) Hget_i Hdec_i.\n  rewrite (proj1 (rs_refm Href) _ _ _ _ Hdec_ti Hget_i) Hdec_i /=.\n  destruct Href, instr, cmvec; move=> Hbuild; simpl in *; match_inv;\n  repeat match goal with\n  | x : hseq_nil |- _ => destruct x\n  | x : hseq_cons _ _ |- _ => destruct x\n  | x : atom _ _ |- _ => destruct x\n  | H : Some _ = Some _ |- _ => inv H\n  end; simpl in *; match_inv;\n  repeat relate_register_get;\n  repeat relate_memory_get;\n  trivial; repeat find_and_rewrite; by trivial.\nQed.\n\nLemma cache_hit_simulation sst cst cst' :\n  refine_state mi table sst cst ->\n  hit_step cst cst' ->\n  exists2 sst',\n    Symbolic.step table sst sst' &\n    refine_state mi table sst' cst'.\nProof.\n  case: sst => smem sregs [pc atpc] int.\n  move => [/= PC DEC REFM REFR CACHE MVEC WFENTRYPOINTS MINV] [INUSER INUSER' STEP].\n  rewrite /Symbolic.pcv /= in PC. subst pc.\n  inv STEP; subst mv;\n  unfold Concrete.next_state_reg, Concrete.next_state_reg_and_pc,\n         Concrete.next_state_pc, Concrete.next_state in *;\n  simpl in *;\n  try rewrite KER in NEXT; simpl in *;\n\n  match_inv;\n\n  analyze_cache;\n\n  repeat relate_register_get;\n\n  repeat relate_memory_get;\n\n  try relate_register_upd;\n\n  try relate_memory_upd;\n\n  (eexists; [ solve_step | solve_refine_state ]).\n\nQed.\n\nLemma initial_handler_state cst kst cmvec :\n  forall (CMVEC : build_cmvec cst = Some cmvec)\n         (MISS : Concrete.cache_lookup (Concrete.cache cst) masks cmvec = None)\n         (STEP : Concrete.step _ masks cst kst),\n      kst = Concrete.State (Concrete.store_mvec (Concrete.mem cst) cmvec)\n                             (Concrete.regs cst)\n                             (Concrete.cache cst)\n                             (Concrete.fault_handler_start mt)@Concrete.TMonitor\n                             (Concrete.pc cst).\nProof.\n  move=> BUILD LOOKUP /step_lookup_success_or_fault.\n  rewrite BUILD.\n  case=> [cmvec' [[<-]]] {cmvec'}.\n  by rewrite LOOKUP.\nQed.\n\nLemma monitor_user_exec_determ k s1 s2 :\n  monitor_user_exec k s1 ->\n  monitor_user_exec k s2 ->\n  s1 = s2.\nProof.\n  unfold monitor_user_exec. intros EXEC1 EXEC2.\n  eapply exec_until_determ; eauto.\n  - clear. intros s s1 s2.\n    do 2 rewrite <- concrete.exec.stepP in *. congruence.\n  - clear. by move=> s /= ->.\n  - clear. by move=> s /= ->.\nQed.\n\nLemma user_monitor_user_step_determ s s1 s2 :\n  user_monitor_user_step s s1 ->\n  user_monitor_user_step s s2 ->\n  s1 = s2.\nProof.\n  move => [s' USER1 STEP1 EXEC1] [s'' USER2 STEP2 EXEC2].\n  have E: (s' = s'') by rewrite <- concrete.exec.stepP in *; congruence. subst s''.\n  eauto using monitor_user_exec_determ.\nQed.\n\nLemma build_cmvec_cache_lookup_pc cst cst' cmvec crvec :\n  Concrete.step _ masks cst cst' ->\n  build_cmvec cst = Some cmvec ->\n  Concrete.cache_lookup (Concrete.cache cst) masks cmvec = Some crvec ->\n  taga (Concrete.pc cst') = Concrete.ctrpc crvec.\nProof.\n  move=> STEP BUILD LOOKUP.\n  move/step_lookup_success_or_fault: STEP.\n  rewrite BUILD.\n  case=> cmvec' [[<-]] {cmvec'}.\n  by rewrite LOOKUP.\nQed.\n\nLemma monitor_cache_lookup_fail (cst cst' : Concrete.state mt) cmvec :\n  in_user cst ->\n  in_monitor cst' ->\n  Concrete.step _ masks cst cst' ->\n  ~~ cache_allows_syscall table cst ->\n  wf_entry_points table (Concrete.mem cst) ->\n  cache_correct (Concrete.cache cst) (Concrete.mem cst) ->\n  build_cmvec cst = Some cmvec ->\n  Concrete.cache_lookup (Concrete.cache cst) masks cmvec = None.\nProof.\n  move=> INUSER INMONITOR STEP NOTALLOWED WFENTRYPOINTS CACHECORRECT BUILD.\n  move/step_lookup_success_or_fault: STEP NOTALLOWED.\n  rewrite /cache_allows_syscall BUILD.\n  case=> cmvec' [[<-]] {cmvec'}.\n  case LOOKUP: (Concrete.cache_lookup _ _ _) => [[ctrpc ctr]|] //= E. subst ctrpc.\n  case GETSC: (getm table _) => [sc|] //=.\n  move: INMONITOR LOOKUP.\n  rewrite /in_monitor /Concrete.is_monitor_tag => /eqP -> LOOKUP _.\n  rewrite /in_user /= -(build_cmvec_ctpc BUILD) in INUSER.\n  case/(_ cmvec _ LOOKUP INUSER): CACHECORRECT => ivec [ovec [/decode_ivec_inv DECi DECo _]].\n  case: ivec DECi ovec DECo => [[op|] tpc ti ts] /= => [[E Hpriv _ _ _]|[DECop _ DECti]].\n    by rewrite {}E /decode_ovec /= decode_monitor_tag /= => ovec.\n  suff : false by done.\n  move: (build_cmvec_cop_cti BUILD) DECop => [i [instr [GETPC DECi <-]]] DECop.\n  have {DECi} ISNOP : is_nop i by rewrite /is_nop {}DECi; case: instr DECop.\n  move: (wf_entry_points_only_if WFENTRYPOINTS GETPC DECti ISNOP).\n  by rewrite GETSC; case.\nQed.\n\nLemma cache_miss_simulation sst cst cst' :\n  refine_state mi table sst cst ->\n  ~~ cache_allows_syscall table cst ->\n  user_monitor_user_step cst cst' ->\n  refine_state mi table sst cst'.\nProof.\n  case: sst => smem sregs [pc tpc] int.\n  case: cst => cmem cregs cache [pc' ctpc] epc.\n  move => REF NOTALLOWED [kst ISUSER STEP KEXEC].\n  have KER : in_monitor kst = true.\n  { destruct KEXEC as [? EXEC]. exact (restricted_exec_fst EXEC). }\n  case: REF=> [//= PC DEC REFM REFR CACHECORRECT MVEC WFENTRYPOINTS MINV].\n  rewrite /Concrete.pcv /= in PC. subst pc'.\n  have ISUSER' : ~~ in_monitor cst' by case: KEXEC.\n  have [cmvec Hcmvec] := step_build_cmvec STEP.\n  have LOOKUP := monitor_cache_lookup_fail ISUSER KER STEP NOTALLOWED WFENTRYPOINTS CACHECORRECT Hcmvec.\n  have H := initial_handler_state Hcmvec LOOKUP STEP.\n  have EXEC : exec (Concrete.step _ masks) kst cst'.\n    case: KEXEC => kst' EXEC _ STEP'.\n    apply restricted_exec_weaken in EXEC.\n    by apply restricted_exec_trans with kst'; eauto.\n  subst kst. rewrite /= in STEP KEXEC EXEC KER LOOKUP.\n  destruct (handler_correct_allowed_case_bwd MINV CACHECORRECT KEXEC)\n      as (ivec & ovec & DECivec & TRANS & CACHE' & MVEC' &\n          HPCT & HMEM & HREGS & HPC & WFENTRYPOINTS' & MINV').\n  case: cst' {KEXEC EXEC} HPC CACHE'\n             ISUSER' MVEC' HPCT HMEM HREGS WFENTRYPOINTS' MINV' =>\n        cmem'' cregs'' cache' pc' ? /= -> {pc'} CACHE' ISUSER' MVEC' HPCT HMEM HREGS WFENTRYPOINTS' MINV'.\n  econstructor; eauto.\n  - by apply/HPCT.\n  - split.\n    + move=> w x ctg atg {DECivec DEC} /HPCT DEC GET.\n      move: (HMEM w x ctg _ DEC) GET => H /H {H} ?.\n      by eapply (proj1 REFM); eauto.\n    + move=> w x atg /(proj2 REFM) {DEC} [ctg DEC GET].\n      move: DEC (HMEM w x ctg _ DEC) GET => /HPCT DEC H /H {H} ? /=.\n      by eauto.\n  - split.\n    + move=> r x ctg atg {DECivec DEC} /HPCT DEC GET.\n      move: (HREGS r x ctg _ DEC) GET => H /H {H} ?.\n      by eapply (proj1 REFR); eauto.\n    + move=> r x atg /(proj2 REFR) {DEC} [ctg DEC GET].\n      move: DEC (HREGS r x ctg _ DEC) GET => /HPCT DEC H /H {H} ? /=.\n      by eauto.\nQed.\n\nLemma syscall_simulation sst cst cst' :\n  refine_state mi table sst cst ->\n  cache_allows_syscall table cst ->\n  user_monitor_user_step cst cst' ->\n  exists2 sst', Symbolic.step table sst sst' &\n                refine_state mi table sst' cst'.\nProof.\n  case: sst=> smem sregs [pc tpc] int.\n  case: cst=> cmem cregs cache [pc' ctpc] epc.\n  intros REF ALLOWED STEP.\n  case: REF=> [//= PC DEC REFM REFR CACHE MVEC WFENTRYPOINTS MINV].\n  rewrite /Concrete.pcv /= in PC. subst pc'.\n  have [sc GETCALL]: (exists sc, table pc = Some sc).\n  { rewrite /cache_allows_syscall in ALLOWED.\n    case GETCALL: (table pc) ALLOWED => [sc|//] ALLOWED.\n    by eauto. }\n  destruct cst' as [cmem' creg' cache' [cpc' ctpc'] epc'].\n  have := syscalls_correct_allowed_case_bwd MINV REFM REFR CACHE MVEC GETCALL\n                                            DEC ALLOWED STEP.\n  move/(_ mcc).\n  intros (smem' & sregs' & stpc' & sint' & RUNSC &\n          HPCT & REFM' & REFR' & CACHE' & MVEC' & WFENTRYPOINTS' & MINV').\n  exists (Symbolic.State smem' sregs' cpc'@stpc' sint').\n  - eapply Symbolic.step_syscall; eauto.\n    eapply wf_entry_points_if in GETCALL; last by exact WFENTRYPOINTS.\n    move: GETCALL => [i [ti [GETPC DECti ISNOP]]].\n    case GET': (getm smem pc) => [[? ?]|] //.\n    move: (proj2 REFM _ _ _ GET') => {GET' DEC} [ctg' DEC GET'].\n    rewrite GETPC in GET'.\n    move: GET' => [? H]. subst i ti.\n    by rewrite DEC in DECti.\n  - by econstructor; eauto.\nQed.\n\nLemma user_into_monitor sst cst cst' :\n  refine_state mi table sst cst ->\n  Concrete.step _ masks cst cst' ->\n  ~~ in_user cst'->\n  in_monitor cst'.\nProof.\n  move=> REF STEP NUSER.\n  move: (refine_state_in_user REF) => INUSER.\n  case: REF => [? ? ? ? CACHE ? ? ?]. subst.\n  move : (valid_pcs STEP CACHE INUSER) NUSER.\n  rewrite /in_monitor /Concrete.is_monitor_tag /in_user.\n  move => [[t ->]|->] //=.\nQed.\n\nDefinition refine_state_weak sst cst :=\n  refine_state mi table sst cst \\/\n  exists cst0 kst,\n    refine_state mi table sst cst0 /\\\n    Concrete.step _ masks cst0 kst /\\\n    monitor_exec kst cst.\n\nLemma backwards_simulation sst cst cst' :\n  refine_state_weak sst cst ->\n  Concrete.step _ masks cst cst' ->\n  refine_state_weak sst cst' \\/\n  exists2 sst',\n    Symbolic.step table sst sst' &\n    refine_state mi table sst' cst'.\nProof.\n  intros [REF | (cst0 & kst & REF & KSTEP & EXEC)] STEP.\n  - have USER : in_user cst by eapply refine_state_in_user; eauto.\n    have [USER'|USER'] := boolP (in_user cst').\n    + right.\n      eapply cache_hit_simulation; eauto.\n      by constructor; auto.\n    + left. right. do 2 eexists. do 2 (split; eauto).\n      constructor.\n      by eapply user_into_monitor; eauto.\n  - have USER : in_user cst0 by eapply refine_state_in_user; eauto.\n    have [KER'|KER'] := boolP (in_monitor cst').\n    + left. right.\n      do 2 eexists. do 2 (split; eauto).\n      eapply restricted_exec_trans; eauto.\n      have KER : in_monitor cst by eapply restricted_exec_snd in EXEC.\n      eapply re_step; by eauto using user_into_monitor.\n    + assert (EXEC' : user_monitor_user_step cst0 cst').\n      { econstructor; eauto.\n        econstructor; eauto using in_user_in_monitor. }\n      case: (boolP (cache_allows_syscall table cst0)) => [ALLOWED | NOTALLOWED].\n      * right. by eapply syscall_simulation; eauto.\n      * left. left. by eapply cache_miss_simulation; eauto.\nQed.\n\nLemma monitor_step cst cst' ast kst cst0 :\n  refine_state mi table ast cst0 ->\n  Concrete.step ops rules.masks cst0 kst ->\n  monitor_exec kst cst ->\n  Concrete.step _ masks cst cst' ->\n  in_monitor cst ->\n  ~~ in_user cst' ->\n  in_monitor cst'.\nProof.\n  intros REF STEP EXEC STEP' INMONITOR INUSER.\n  assert (REFW: refine_state_weak ast cst).\n  { right. eauto. }\n  generalize (backwards_simulation REFW STEP').\n  intros [[REF' | (? & ? & ? & ? & KEXEC')] | [? _ REF']].\n  - apply @refine_state_in_user in REF'. by rewrite REF' in INUSER.\n  - by apply restricted_exec_snd in KEXEC'.\n  - apply @refine_state_in_user in REF'. by rewrite REF' in INUSER.\nQed.\n\nTheorem backwards_refinement sst cst cst' :\n  refine_state mi table sst cst ->\n  exec (Concrete.step _ masks) cst cst' ->\n  in_user cst' ->\n  exists2 sst',\n    exec (Symbolic.step table) sst sst' &\n    refine_state mi table sst' cst'.\nProof.\n  intros REF EXEC USER'.\n  have {REF} REF: refine_state_weak sst cst by left.\n  move: sst REF.\n  induction EXEC as [cst _|cst cst'' cst' _ STEP EXEC IH].\n  - move => sst [? | REF]; first by eauto.\n    destruct REF as (? & ? & ? & ? & EXEC).\n    apply restricted_exec_snd in EXEC.\n    apply in_user_in_monitor in USER'.\n    by rewrite EXEC in USER'.\n  - move => sst REF.\n    have [REF' | [sst' SSTEP REF']] := backwards_simulation REF STEP;\n      first by auto.\n    have {REF'} REF': refine_state_weak sst' cst'' by left.\n    move: (IH USER' _ REF') => {IH USER' REF'} [sst'' EXEC' REF'].\n    eexists; last by eauto.\n    eapply re_step; trivial; eauto.\nQed.\n\nEnd Refinement.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/symbolic/backward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.566018549837479, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.18546634389064648}}
{"text": "Require Import Classical List Relations Peano_dec.\nRequire Import Hahn.\nRequire Import Basic RC11_Events RC11_Model RC11_Threads.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection WriteBefore.\n\nVariable G : execution.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'mo'\" := G.(mo).\nNotation \"'sw'\" := G.(sw).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'rb'\" := G.(rb).\nNotation \"'hb'\" := G.(hb).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'deps'\" := G.(deps).\nNotation \"'eco'\" := G.(eco).\nNotation \"'same_loc'\" := G.(same_loc).\nNotation \"rel |loc\" := (rel \u2229 same_loc) (at level 1).\nNotation \"'psc'\" := G.(psc).\nNotation \"'psc_base'\" := G.(psc_base). \nNotation \"'psc_f'\" := G.(psc_f).\nNotation \"'scb'\" := G.(scb).\n\nNotation \"'E'\" := G.(E).\nNotation \"'R'\" := (R lab).\nNotation \"'W'\" := (W lab).\nNotation \"'F'\" := (F lab).\nNotation \"'RMW'\" := (RMW lab).\nNotation \"'RW'\" := (RW lab).\nNotation \"'FR'\" := (FR lab).\nNotation \"'FW'\" := (FW lab).\nNotation \"'Na'\" := (Only_Na lab).\nNotation \"'Rlx'\" := (Rlx lab).\nNotation \"'Rel'\" := (Rel lab).\nNotation \"'Acq'\" := (Acq lab).\nNotation \"'Acqrel'\" := (Acqrel lab).\nNotation \"'Sc'\" := (Sc lab).\nNotation \"type ~ mode\" := (type \u2229\u2081 mode) (at level 1).\n\nHypothesis NRMW: NO_RMW_EVENTS G.\n\nDefinition wb0 := \n  \u2997W\u2998 \u2a3e (rmw\u207b\u00b9 \u2a3e rf\u207b\u00b9)\uff0a \u2a3e (rf^? \u2a3e hb|loc \u2a3e rf\u207b\u00b9^? \\  (rf \u2a3e rmw)\uff0a ) \u2a3e \u2997W\u2998.\nDefinition wb :=  rf \u2a3e rmw \u222a wb0.\n\nDefinition consistent_wb :=\n  << WF   : Wf G >> /\\\n  << WB  : acyclic wb >> /\\\n  << AT   : functional (rf \u2a3e rmw)  >> /\\\n  << SC   : acyclic psc >> /\\\n  << SBRF : acyclic (sb \u222a rf) >>.\n\nLemma con_wb_wf  (CON: consistent_wb) : Wf G.\nProof. cdes CON; done. Qed.\n\nHint Resolve con_wb_wf.\n\n\nLemma wb0_acta (WF: Wf G) : doma wb0 E.\nProof.\ncdes WF; unfold wb0.\nclear_equivs \u2997W\u2998.\nrewrite rtE at 1; relsf.\napply union_doma; [| by eauto 12 using rmw_actb with rel].\napply minus_doma.\nrewrite inter_inclusion, crE; relsf.\neauto 12 using hb_acta, rf_acta, rmw_actb with rel.\nQed.\n\nLemma wb_acta (WF: Wf G) : (doma wb (fun x => In x acts)).\nProof.\ncdes WF; unfold wb.\napply union_doma.\nby eauto 12 using hb_acta, rf_acta, rmw_actb with rel.\nby apply wb0_acta.\nQed.\n\nLemma wb0_actb (WF: Wf G) : (domb wb0 (fun x => In x acts)).\nProof.\ncdes WF; unfold wb0.\narewrite_id (\u2997W\u2998); rels.\napply seq_domb.\napply minus_domb.\nrewrite (crE rf\u207b\u00b9), inter_inclusion; relsf.\neauto 12 using hb_actb, rf_acta with rel.\nQed.\n\nLemma wb_actb (WF: Wf G) : (domb wb (fun x => In x acts)).\nProof.\ncdes WF; unfold wb.\napply union_domb.\nby eauto using rmw_actb with rel.\nby apply wb0_actb.\nQed.\n\nLemma wb0_act (WF: Wf G) : \n  wb0 \u2286 <| fun x => In x acts |> \u2a3e wb0 \u2a3e <| fun x => In x acts |>. \nProof.\neapply act_helper; split; [apply wb0_acta| apply wb0_actb]; done.\nQed.\n\nLemma wb_act (WF: Wf G) : \n  wb \u2286 <| fun x => In x acts |> \u2a3e wb \u2a3e <| fun x => In x acts |>. \nProof.\neapply act_helper; split; [apply wb_acta| apply wb_actb]; done.\nQed.\n\nLemma rmw_functional (WF: Wf  G) :\n   functional rmw.\nProof.\ncdes WF; cdes WF_RMW; cdes WF_SB.\nunfold functional; intros x y z H0 H1.\nassert (Ix: I x) by eby eapply no_rmw_from_init.\nhahn_rewrite RMW_IMM in H0.\nhahn_rewrite RMW_IMM in H1.\napply sb_immediate_adjacent in H0; try done.\napply sb_immediate_adjacent in H1; try done.\ndesf.\neapply adjacent_uniqe1 with (r:=sb); try edone.\nby apply trans_irr_acyclic.\nQed.\n\nLemma transp_rmw_functional (WF: Wf  G) :\n   functional rmw\u207b\u00b9.\nProof.\ncdes WF; cdes WF_RMW; cdes WF_SB.\nunfold functional; intros x y z H0 H1.\nunfold transp in *.\nassert (Iy: I y) by eby eapply no_rmw_from_init.\nassert (Iz: I z) by eby eapply no_rmw_from_init.\nhahn_rewrite RMW_IMM in H0.\nhahn_rewrite RMW_IMM in H1.\napply sb_immediate_adjacent in H0; try done.\napply sb_immediate_adjacent in H1; try done.\ndesf.\neapply adjacent_uniqe2 with (r:=sb); try edone.\nby apply trans_irr_acyclic.\nQed.\n\nLemma rf_rmw_wb (WF: Wf G) (FUN: functional (rf \u2a3e rmw)) :\n  rmw\u207b\u00b9 \u2a3e rf\u207b\u00b9 \u2a3e wb \u2286 wb^?.\nProof.\nunfold wb; relsf.\napply inclusion_union_l; rels.\n- rewrite <- !seqA with (r1 := rmw\u207b\u00b9).\n rewrite <- transp_seq.\napply functional_alt in FUN; rewrite FUN; basic_solver.\n- unfold wb0 at 1.\narewrite_id (\u2997W\u2998) at 1; rels.\ncdes WF; cdes WF_RMW; rewrite RMW_DOM at 1.\nclear_equivs \u2997R\u2998; rels.\nrewrite transp_seq; rels; rewrite !seqA.\nrewrite <- !seqA with (r1 := rmw\u207b\u00b9).\nrels.\narewrite ((rmw\u207b\u00b9\u2a3e rf\u207b\u00b9) ^+ \u2286 (rmw\u207b\u00b9\u2a3e rf\u207b\u00b9) \uff0a).\nunfold wb0; eauto with rel.\nQed.\n\nLemma rfU_successor (WF: Wf G) (FUN: functional (rf \u2a3e rmw)) :\n    Successor wb^+ (rf \u2a3e rmw).\nProof.\nred; splits; auto.\n- rewrite transp_seq.\n  apply functional_seq; [apply transp_rmw_functional; auto | apply WF].\n- rewrite transp_seq; rewrite seqA, ct_begin.\n  sin_rewrite rf_rmw_wb; [rels| auto| auto].\n- unfold wb; eauto with rel.\nQed.\n\nLemma wb_base:\n\u2997W\u2998 \u2a3e rf^? \u2a3e hb|loc \u2a3e (rf\u207b\u00b9)^? \u2a3e \u2997W\u2998\n\u2286\nwb\uff0a.\nProof.\narewrite (\u2997W\u2998\u2a3e rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9)^?\u2a3e \u2997W\u2998 \u2286\n (\u2997W\u2998\u2a3e rf^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9)^?\u2a3e \u2997W\u2998 \\(rf\u2a3ermw)\uff0a) \u222a (rf\u2a3ermw)\uff0a).\nby eapply inclusion_union_minus.\nunfold wb, wb0.\napply inclusion_union_l; [|eauto with rel].\narewrite (\u2997W\u2998\u2a3e rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9)^?\u2a3e \u2997W\u2998 \\(rf\u2a3e rmw) \uff0a \u2286\n  \u2997W\u2998\u2a3e (rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9)^? \\ (rf\u2a3e rmw) \uff0a) \u2a3e \u2997W\u2998).\nby rewrite minus_eqv_rel_helper, !seqA.\narewrite (\u2997W\u2998 \u2286 \u2997W\u2998\u2a3e (rmw\u207b\u00b9\u2a3e rf\u207b\u00b9) \uff0a) at 1.\nrewrite rtE; relsf.\nQed.\n\nLemma mo_wb_coh (WF: Wf G) (SBRF : acyclic (sb \u222a rf))\n  (WB: wb \u2286 mo) :\n  irreflexive (hb \u2a3e eco^?).\nProof.\nrewrite eco_alt2; auto.\nrewrite crE; relsf.\nrewrite !irreflexive_union; splits.\n- rewrite hb_in_sb_rf; auto.\n- rewrite hb_in_sb_rf; [ |auto].\n  arewrite (rf \u2286 (sb \u222a rf)) at 2; rels.\n  arewrite ((sb \u222a rf)^+ \u2286 (sb \u222a rf)\uff0a); rels.\n- cdes WF; cdes WF_RF; cdes WF_MO.\n  eapply funeq_irreflexive.\n  by ins; eauto 10 with rel.\n  rewrite MO_DOM.\n  rewrite <- !seqA, irreflexive_seqC, <- !seqA, irreflexive_seqC, !seqA.\n  rewrite <- !seqA with (r3 := mo).\n  arewrite (\u2997W\u2998 \u2a3e rf^? \u2286 \u2997W\u2998 \u2a3e rf^? ;; \u2997RW\u2998).\n  by rewrite RF_DOM at 1; solve_type_mismatch 10.\n  arewrite ( (rf\u207b\u00b9)^? \u2a3e \u2997W\u2998 \u2286 \u2997RW\u2998 ;;  (rf\u207b\u00b9)^? \u2a3e \u2997W\u2998).\n  by rewrite RF_DOM at 1; unfold RC11_Events.RW; basic_solver 42.\n  seq_rewrite restr_eq_rel_same_loc.\n  sin_rewrite wb_base.\n  rewrite WB; relsf. \nQed.\n\nLemma mo_wb_at (WF: Wf G)\n  (SUC: Successor mo (rf \u2a3e rmw)) :\n  irreflexive (rb \u2a3e mo \u2a3e rmw\u207b\u00b9).\nProof.\nrewrite NRMW_implies_original_rb; auto.\nred in SUC; desc.\nrewrite <- irreflexive_seqC, !seqA.\nrewrite transp_seq, !seqA in SUC.\nrewrite SUC.\ncdes WF; cdes WF_MO.\nrelsf.\nQed.\n\nLemma two_rmws (WF: Wf G) (COH: irreflexive (hb \u2a3e clos_refl eco))\n  (AT: irreflexive (rb \u2a3e mo \u2a3e rmw\u207b\u00b9)) :\n    functional (rf \u2a3e rmw).\nProof.\nred; unfold seq, transp; ins; desf; splits; auto.\nassert (LOCz: exists l, loc z = Some l).\n  eapply rw_has_location.\n  eapply rmw_domb in H1; cdes WF; cdes WF_RMW; eauto.\n  solve_type_mismatch.\ndesc.\ncdes WF; cdes WF_RF; cdes WF_RMW.\nassert (LOCy: loc y = Some l).\n  apply RF_LOC in H; try done.\n  apply RF_LOC in H0; try done.\n  apply RMW_LOC in H1; try done.\n  apply RMW_LOC in H2; try done.\n  by congruence.\ndestruct (classic (y=z)) as [X|NEQ]; [eauto| exfalso].\ncdes WF; cdes WF_MO; eapply MO_TOT in NEQ; eauto.\n- desf; rewrite NRMW_implies_original_rb in AT; auto.\n  * apply AT with (x:=z0).\n    exists y; splits.\n    repeat eexists; eauto.\n    eapply rf_rmw_mo; eauto.\n    exists z1; eauto.\n    repeat eexists; eauto.\n  * apply AT with (x:=z1).\n    exists z; splits.\n    repeat eexists; eauto.\n    eapply rf_rmw_mo; eauto.\n    exists z0; eauto.\n    repeat eexists; eauto.\n- unfolder; splits; eauto.\n  eapply rmw_actb; eauto.\n  eapply rmw_domb; eauto.\n- unfolder; splits; eauto.\n  eapply rmw_actb; eauto.\n  eapply rmw_domb; eauto.\nQed.\n\nLemma mo_tot_helper (r: relation event)\n  (WF: Wf G)\n  (IRR: irreflexive r)\n  (ACTS: r \u2286 \u2997E\u2998 \u2a3e (fun _ _ => True) \u2a3e \u2997E\u2998)\n  (WW: r \u2286 \u2997W\u2998\u2a3e (fun _ _ => True) \u2a3e \u2997W\u2998)\n  (LOC: funeq loc r)\n  (MO: irreflexive (r \u2a3e mo)):\n r \u2286 mo.\nProof.\nred; ins.\nassert (exists l, loc x = Some l).\nby eapply rw_has_location; apply WW in H; generalize H; solve_type_mismatch.\ndesc.\neapply tot_ex.\neapply WF.\nunfolder; splits; eauto.\napply ACTS in H; generalize H; basic_solver.\napply WW in H; generalize H; basic_solver.\neby apply LOC in H;  rewrite <- H.\nunfolder; splits; eauto.\napply ACTS in H; generalize H; basic_solver.\napply WW in H; generalize H; basic_solver.\ngeneralize MO; basic_solver 10.\nintro; subst; eapply IRR; eauto.\nQed.\n\nLemma transp_rmw_rf_mo (CON: consistent G) :\n(rmw\u207b\u00b9\u2a3e rf\u207b\u00b9)\u2a3e mo \u2286 mo^? .\nProof.\nrewrite crE.\napply inclusion_minus_l.\napply mo_tot_helper; auto.\nbasic_solver 10.\nall: arewrite(fun __ => __ \\ \u2997fun _ : event => True\u2998 \u2286 __).\n- cdes CON; cdes WF; cdes WF_SB; cdes WF_MO.\n  rewrite rmw_in_sb; auto.\n  rewrite SB_ACT, MO_ACT.\n  basic_solver.\n- cdes CON; cdes WF; cdes WF_RMW; cdes WF_MO.\n  rewrite RMW_DOM, MO_DOM.\n  basic_solver.\n- cdes CON; cdes CON; cdes WF; cdes WF_RMW; cdes WF_RF; cdes WF_MO.\n  eauto with rel.\n- arewrite (rf\u207b\u00b9 \u2a3e mo \u2286 rb).\n    by cdes CON; apply NRMW_implies_original_rb.\n  rotate 2.\n  by cdes CON.\nQed.\n\nLemma transp_rmw_rf_mo1 (CON: consistent G) :\n(rmw\u207b\u00b9\u2a3e rf\u207b\u00b9)\u2a3e (mo \\ (rf\u2a3e rmw) \uff0a) \u2286 mo \\ (rf\u2a3e rmw) \uff0a.\nProof.\nrewrite fun_seq_minus_helper.\n2: apply functional_seq; [apply transp_rmw_functional; auto | apply CON].\nred; unfold minus_rel; ins;desc.\nassert (MO: mo^? x y).\napply transp_rmw_rf_mo; eauto.\ndestruct MO.\n* exfalso; subst; unfold seq in *; desf.\n  apply H0; eauto.\n  eexists; splits; eauto.\n  econs; unfold transp in *; desf; eauto.\n* splits; eauto.\n  intro.\n  apply H0.\n  destruct H; desf.\n  eexists; splits; eauto.\n   unfold transp, seq in H; desf; eauto.\n  eapply clos_trans_in_rt, t_step_rt.\n  eexists; unfold seq; eauto.\nQed.\n\nLemma wb0_in_mo (CON: consistent G) : wb0 \u2286 mo \\ (rf\u2a3e rmw) \uff0a.\nProof.\neapply rt_ind_left with (P:= fun __ => \u2997W\u2998\u2a3e __\u2a3e \n  (rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9) ^? \\ (rf\u2a3e rmw) \uff0a)\u2a3e \u2997W\u2998).\n- eauto with rel.\n- rels.\narewrite ((rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9) ^?) \\ (rf\u2a3e rmw) \uff0a \u2286\n(rf ^?\u2a3e hb|loc \u2a3e (rf\u207b\u00b9) ^?) \\ (rf\u2a3e rmw) \uff0a \\ (rf\u2a3e rmw) \uff0a).\nrewrite minus_eqv_rel_helper.\napply inclusion_minus_mon; try done.\n eapply mo_tot_helper; eauto.\n  * arewrite_id (\u2997W\u2998); rels.\n     basic_solver.\n  * transitivity wb0.\n    unfold wb0.\n    rewrite rtE with (r:=rmw\u207b\u00b9\u2a3e rf\u207b\u00b9); relsf.\n    etransitivity; [eapply wb0_act; eauto| basic_solver].\n  * basic_solver 10.\n  * cdes CON; cdes WF; cdes WF_RF; cdes WF_RMW.\n    eauto 10 using loceq_hb_loc with rel.\n  * arewrite (fun __ => __\\ (rf\u2a3e rmw) \uff0a \u2286 __).\n    arewrite_id !(\u2997W\u2998).\n    rels.\n    apply irreflexive_seqC.\n    rewrite !crE; relsf.\n    arewrite (rf\u207b\u00b9 \u2a3e mo \u2286 rb) by cdes CON; apply NRMW_implies_original_rb.\n    rewrite rb_in_eco, mo_in_eco, rf_in_eco; eauto.\n    assert (transitive eco).\n      by apply eco_trans; eauto.\n    relsf.\n    arewrite (eco \u2286 eco^?).\n    rewrite inter_inclusion.\n    by cdes CON.\n- ins. rewrite !seqA.\n arewrite (rf\u207b\u00b9  \u2286 rf\u207b\u00b9 \u2a3e \u2997W\u2998) at 1.\n      by cdes CON; cdes WF; generalize (rf_doma WF_RF); basic_solver 10.\n    rewrite H.\n    arewrite_id (\u2997W\u2998) at 1.\n    rels.  \n  rewrite <- !seqA with (r1 := rmw\u207b\u00b9).\nby apply transp_rmw_rf_mo1.\nQed.\n\nLemma wb_in_mo (CON: consistent G) : wb \u2286 mo.\nProof.\napply inclusion_union_l.\napply rf_rmw_mo; eauto; apply CON.\netransitivity; [apply wb0_in_mo; eauto | basic_solver].\nQed.\n\nLemma wb_consistency : consistent G -> consistent_wb.\nProof.\nunfold consistent_wb.\nintro CON.\n cdes CON; ins; desf; splits; eauto.\nrewrite wb_in_mo; try done.\nred; cdes WF; cdes WF_MO; relsf.\napply two_rmws; eauto.\nQed.\n\nEnd WriteBefore.", "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/WriteBefore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18543260944917916}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom lrust.lang.lib Require Import memcpy.\nFrom lrust.typing Require Export type.\nFrom lrust.typing Require Import util uninit type_context programs.\nFrom iris.prelude Require Import options.\n\nSection own.\n  Context `{!typeGS \u03a3}.\n\n  Definition freeable_sz (n : nat) (sz : nat) (l : loc) : iProp \u03a3 :=\n    match sz, n return _ with\n    | 0%nat, _ => True\n    | _, 0%nat => False\n    | sz, n => \u2020{pos_to_Qp (Pos.of_nat sz) / pos_to_Qp (Pos.of_nat n)}l\u2026sz\n    end%I.\n  Global Arguments freeable_sz : simpl never.\n\n  Global Instance freeable_sz_timeless n sz l : Timeless (freeable_sz n sz l).\n  Proof. destruct sz, n; apply _. Qed.\n\n  Lemma freeable_sz_full n l : freeable_sz n n l \u22a3\u22a2 \u2020{1}l\u2026n \u2228 \u231cZ.of_nat n = 0\u231d.\n  Proof.\n    destruct n as [|n].\n    - iSplit; iIntros \"H /=\"; auto.\n    - assert (Z.of_nat (S n) = 0 \u2194 False) as -> by done. rewrite right_id.\n      by rewrite /freeable_sz Qp_div_diag.\n  Qed.\n\n  Lemma freeable_sz_full_S n l : freeable_sz (S n) (S n) l \u22a3\u22a2 \u2020{1}l\u2026(S n).\n  Proof. rewrite freeable_sz_full. iSplit; auto. iIntros \"[$|%]\"; done. Qed.\n\n  Lemma freeable_sz_split n sz1 sz2 l :\n    freeable_sz n sz1 l \u2217 freeable_sz n sz2 (l +\u2097 sz1) \u22a3\u22a2\n                freeable_sz n (sz1 + sz2) l.\n  Proof.\n    destruct sz1; [|destruct sz2;[|rewrite /freeable_sz plus_Sn_m; destruct n]].\n    - by rewrite left_id shift_loc_0.\n    - by rewrite right_id Nat.add_0_r.\n    - iSplit.\n      + by iIntros \"[[]?]\".\n      + by iIntros \"[]\".\n    - rewrite heap_freeable_op_eq. f_equiv; [|done..].\n      by rewrite -Qp_div_add_distr pos_to_Qp_add -Nat2Pos.inj_add.\n  Qed.\n\n  (* Make sure 'simpl' doesn't unfold. *)\n  Global Opaque freeable_sz.\n\n  Program Definition own_ptr (n : nat) (ty : type) :=\n    {| ty_size := 1;\n       ty_own tid vl :=\n         match vl return _ with\n         | [ #(LitLoc l) ] =>\n         (* We put a later in front of the \u2020{q}, because we cannot use\n            [ty_size_eq] on [ty] at step index 0, which would in turn\n            prevent us to prove [subtype_own].\n\n            Since this assertion is timeless, this should not cause\n            problems. *)\n           \u25b7 (l \u21a6\u2217: ty.(ty_own) tid \u2217 freeable_sz n ty.(ty_size) l)\n         | _ => False\n         end%I;\n       ty_shr \u03ba tid l :=\n         (\u2203 l':loc, &frac{\u03ba}(\u03bb q', l \u21a6{q'} #l') \u2217\n            \u25a1 (\u2200 F q, \u231c\u2191shrN \u222a \u2191lftN \u2286 F\u231d -\u2217 q.[\u03ba] ={F}[F\u2216\u2191shrN]\u25b7=\u2217\n                            ty.(ty_shr) \u03ba tid l' \u2217 q.[\u03ba]))%I |}.\n  Next Obligation. by iIntros (q ty tid [|[[]|][]]) \"H\". Qed.\n  Next Obligation.\n    move=>n ty N \u03ba l tid ?? /=. iIntros \"#LFT Hshr Htok\".\n    iMod (bor_exists with \"LFT Hshr\") as (vl) \"Hb\"; first solve_ndisj.\n    iMod (bor_sep with \"LFT Hb\") as \"[Hb1 Hb2]\"; first solve_ndisj.\n    destruct vl as [|[[|l'|]|][]];\n      try (iMod (bor_persistent with \"LFT Hb2 Htok\") as \"[>[]_]\"; solve_ndisj).\n    iFrame. iExists l'. rewrite heap_mapsto_vec_singleton.\n    rewrite bi.later_sep.\n    iMod (bor_sep with \"LFT Hb2\") as \"[Hb2 _]\"; first solve_ndisj.\n    iMod (bor_fracture (\u03bb q, l \u21a6{q} #l')%I with \"LFT Hb1\") as \"$\"; first solve_ndisj.\n    iApply delay_sharing_later; done.\n  Qed.\n  Next Obligation.\n    intros _ ty \u03ba \u03ba' tid l. iIntros \"#H\u03ba #H\".\n    iDestruct \"H\" as (l') \"[Hfb #Hvs]\".\n    iExists l'. iSplit; first by iApply (frac_bor_shorten with \"[]\"). iIntros \"!> %F %q % Htok\".\n    iApply (step_fupd_mask_mono F _ (F\u2216\u2191shrN)); [solve_ndisj..|].\n    iMod (lft_incl_acc with \"H\u03ba 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.(ty_shr_mono) with \"H\u03ba\").\n  Qed.\n\n  Global Instance own_ptr_wf n ty `{!TyWf ty} : TyWf (own_ptr n ty) :=\n    { ty_lfts := ty_lfts ty; ty_wf_E := ty_wf_E ty }.\n\n  Lemma own_type_incl n m ty1 ty2 :\n    \u25b7 \u231cn = m\u231d -\u2217 \u25b7 type_incl ty1 ty2 -\u2217 type_incl (own_ptr n ty1) (own_ptr m ty2).\n  Proof.\n    iIntros \"#Heq (#Hsz & #Ho & #Hs)\". iSplit; first done. iSplit; iModIntro.\n    - iIntros (?[|[[| |]|][]]) \"H\"; try done. simpl.\n      iDestruct \"H\" as \"[Hmt H\u2020]\". iNext. iDestruct (\"Hsz\") as %<-.\n      iDestruct \"Heq\" as %->. iFrame. iApply (heap_mapsto_pred_wand with \"Hmt\").\n      iApply \"Ho\".\n    - iIntros (???) \"H\". iDestruct \"H\" as (l') \"[Hfb #Hvs]\".\n      iExists l'. iFrame. iIntros \"!>\". iIntros (F' q) \"% Htok\".\n      iMod (\"Hvs\" with \"[%] Htok\") as \"Hvs'\"; first done. iModIntro. iNext.\n      iMod \"Hvs'\" as \"[Hshr $]\". iApply (\"Hs\" with \"Hshr\").\n  Qed.\n\n  Global Instance own_mono E L n :\n    Proper (subtype E L ==> subtype E L) (own_ptr n).\n  Proof.\n    intros ty1 ty2 Hincl. iIntros (qmax qL) \"HL\".\n    iDestruct (Hincl with \"HL\") as \"#Hincl\".\n    iClear \"\u2217\". iIntros \"!> #HE\".\n    iApply own_type_incl; first by auto. iApply \"Hincl\"; auto.\n  Qed.\n  Lemma own_mono' E L n1 n2 ty1 ty2 :\n    n1 = n2 \u2192 subtype E L ty1 ty2 \u2192 subtype E L (own_ptr n1 ty1) (own_ptr n2 ty2).\n  Proof. intros -> *. by apply own_mono. Qed.\n  Global Instance own_proper E L n :\n    Proper (eqtype E L ==> eqtype E L) (own_ptr n).\n  Proof. intros ??[]; split; by apply own_mono. Qed.\n  Lemma own_proper' E L n1 n2 ty1 ty2 :\n    n1 = n2 \u2192 eqtype E L ty1 ty2 \u2192 eqtype E L (own_ptr n1 ty1) (own_ptr n2 ty2).\n  Proof. intros -> *. by apply own_proper. Qed.\n\n  Global Instance own_type_contractive n : TypeContractive (own_ptr n).\n  Proof. solve_type_proper. Qed.\n\n  Global Instance own_ne n : NonExpansive (own_ptr n).\n  Proof. apply type_contractive_ne, _. Qed.\n\n  Global Instance own_send n ty :\n    Send ty \u2192 Send (own_ptr n ty).\n  Proof.\n    iIntros (Hsend tid1 tid2 [|[[| |]|][]]) \"H\"; try done.\n    iDestruct \"H\" as \"[Hm $]\". iNext. iApply (heap_mapsto_pred_wand with \"Hm\").\n    iIntros (vl) \"?\". by iApply Hsend.\n  Qed.\n\n  Global Instance own_sync n ty :\n    Sync ty \u2192 Sync (own_ptr n ty).\n  Proof.\n    iIntros (Hsync \u03ba tid1 tid2 l) \"H\". iDestruct \"H\" as (l') \"[Hm #Hshr]\".\n    iExists _. iFrame \"Hm\". iModIntro. iIntros (F q) \"% Htok\".\n    iMod (\"Hshr\" with \"[] Htok\") as \"Hfin\"; first done. iModIntro. iNext.\n    iMod \"Hfin\" as \"{Hshr} [Hshr $]\". by iApply Hsync.\n  Qed.\nEnd own.\n\nSection box.\n  Context `{!typeGS \u03a3}.\n\n  Definition box ty := own_ptr ty.(ty_size) ty.\n\n  Lemma box_type_incl ty1 ty2 :\n    \u25b7 type_incl ty1 ty2 -\u2217 type_incl (box ty1) (box ty2).\n  Proof.\n    iIntros \"#Hincl\". iApply own_type_incl; last done.\n    iDestruct \"Hincl\" as \"(? & _ & _)\". done.\n  Qed.\n\n  Global Instance box_mono E L :\n    Proper (subtype E L ==> subtype E L) box.\n  Proof.\n    intros ty1 ty2 Hincl. iIntros (qmax qL) \"HL\".\n    iDestruct (Hincl with \"HL\") as \"#Hincl\".\n    iClear \"\u2217\". iIntros \"!> #HE\".\n    iApply box_type_incl. iApply \"Hincl\"; auto.\n  Qed.\n  Lemma box_mono' E L ty1 ty2 :\n    subtype E L ty1 ty2 \u2192 subtype E L (box ty1) (box ty2).\n  Proof. intros. by apply box_mono. Qed.\n  Global Instance box_proper E L :\n    Proper (eqtype E L ==> eqtype E L) box.\n  Proof. intros ??[]; split; by apply box_mono. Qed.\n  Lemma box_proper' E L ty1 ty2 :\n    eqtype E L ty1 ty2 \u2192 eqtype E L (box ty1) (box ty2).\n  Proof. intros. by apply box_proper. Qed.\n\n  Global Instance box_type_contractive : TypeContractive box.\n  Proof. solve_type_proper. Qed.\n\n  Global Instance box_ne : NonExpansive box.\n  Proof. apply type_contractive_ne, _. Qed.\nEnd box.\n\nSection util.\n  Context `{!typeGS \u03a3}.\n\n  Lemma ownptr_own n ty tid v :\n    (own_ptr n ty).(ty_own) tid [v] \u22a3\u22a2\n       \u2203 (l : loc) (vl : vec val ty.(ty_size)),\n         \u231cv = #l\u231d \u2217 \u25b7 l \u21a6\u2217 vl \u2217 \u25b7 ty.(ty_own) tid vl \u2217 \u25b7 freeable_sz n ty.(ty_size) l.\n  Proof.\n    iSplit.\n    - iIntros \"Hown\". destruct v as [[|l|]|]; try done.\n      iExists l. iDestruct \"Hown\" as \"[Hown $]\". rewrite heap_mapsto_ty_own.\n      iDestruct \"Hown\" as (vl) \"[??]\". eauto with iFrame.\n    - iIntros \"Hown\". iDestruct \"Hown\" as (l vl) \"(% & ? & ? & ?)\". subst v.\n      iFrame. iExists _. iFrame.\n  Qed.\n\n  Lemma ownptr_uninit_own n m tid v :\n    (own_ptr n (uninit m)).(ty_own) tid [v] \u22a3\u22a2\n         \u2203 (l : loc) (vl' : vec val m), \u231cv = #l\u231d \u2217 \u25b7 l \u21a6\u2217 vl' \u2217 \u25b7 freeable_sz n m l.\n  Proof.\n    rewrite ownptr_own. apply bi.exist_proper=>l. iSplit.\n    (* FIXME: The goals here look rather confusing:  One cannot tell that we are looking at\n       a statement in Iris; the top-level \u2192 could just as well be a Coq implication. *)\n    - iIntros \"H\". iDestruct \"H\" as (vl) \"(% & Hl & _ & $)\". subst v.\n      iExists vl. iSplit; done.\n    - iIntros \"H\". iDestruct \"H\" as (vl) \"(% & Hl & $)\". subst v.\n      iExists vl. rewrite /= vec_to_list_length.\n      eauto with iFrame.\n  Qed.\nEnd util.\n\nSection typing.\n  Context `{!typeGS \u03a3}.\n\n  (** Typing *)\n  Lemma write_own {E L} ty ty' n :\n    ty.(ty_size) = ty'.(ty_size) \u2192 \u22a2 typed_write E L (own_ptr n ty') ty (own_ptr n ty).\n  Proof.\n    rewrite typed_write_eq. iIntros (Hsz) \"!>\".\n    iIntros ([[]|] tid F qmax qL ?) \"_ _ $ Hown\"; try done.\n    rewrite /= Hsz. iDestruct \"Hown\" as \"[H\u21a6 $]\". iDestruct \"H\u21a6\" as (vl) \"[>H\u21a6 Hown]\".\n    iDestruct (ty_size_eq with \"Hown\") as \"#>%\". iExists _, _. iFrame \"H\u21a6\". auto.\n  Qed.\n\n  Lemma read_own_copy E L ty n :\n    Copy ty \u2192 \u22a2 typed_read E L (own_ptr n ty) ty (own_ptr n ty).\n  Proof.\n    rewrite typed_read_eq. iIntros (Hsz) \"!>\".\n    iIntros ([[|l|]|] tid F qmax qL ?) \"_ _ $ $ Hown\"; try done.\n    iDestruct \"Hown\" as \"[H\u21a6 H\u2020]\". iDestruct \"H\u21a6\" as (vl) \"[>H\u21a6 #Hown]\".\n    iExists l, _, _. iFrame \"\u2217#\". iSplitR; first done. iIntros \"!> Hl !>\".\n    iExists _. auto.\n  Qed.\n\n  Lemma read_own_move E L ty n :\n    \u22a2 typed_read E L (own_ptr n ty) ty (own_ptr n $ uninit ty.(ty_size)).\n  Proof.\n    rewrite typed_read_eq. iModIntro.\n    iIntros ([[|l|]|] tid F qmax qL ?) \"_ _ $ $ Hown\"; try done.\n    iDestruct \"Hown\" as \"[H\u21a6 H\u2020]\". iDestruct \"H\u21a6\" as (vl) \"[>H\u21a6 Hown]\".\n    iDestruct (ty_size_eq with \"Hown\") as \"#>%\".\n    iExists l, vl, _. iFrame \"\u2217#\". iSplitR; first done. iIntros \"!> Hl !> !>\".\n    iExists _. iFrame. done.\n  Qed.\n\n  Lemma type_new_instr {E L} (n : Z) :\n    0 \u2264 n \u2192\n    \u22a2 let n' := Z.to_nat n in\n      typed_instruction_ty E L [] (new [ #n ]%E) (own_ptr n' (uninit n')).\n  Proof.\n    iIntros (? tid qmax) \"#LFT #HE $ $ _\".\n    iApply wp_new; try done. iModIntro.\n    iIntros (l) \"(H\u2020 & Hlft)\". rewrite tctx_interp_singleton tctx_hasty_val.\n    iNext. rewrite freeable_sz_full Z2Nat.id //. iFrame.\n    iExists (repeat #\u2620 (Z.to_nat n)). iFrame. by rewrite /= repeat_length.\n  Qed.\n\n  Lemma type_new {E L C T} (n' : nat) x (n : Z) e :\n    Closed (x :b: []) e \u2192\n    0 \u2264 n \u2192\n    n' = Z.to_nat n \u2192\n    (\u2200 (v : val),\n        typed_body E L C ((v \u25c1 own_ptr n' (uninit n')) :: T) (subst' x v e)) -\u2217\n    typed_body E L C T (let: x := new [ #n ] in e).\n  Proof. iIntros. subst. iApply type_let; [by apply type_new_instr|solve_typing..]. Qed.\n\n  Lemma type_new_subtype ty E L C T x (n : Z) e :\n    Closed (x :b: []) e \u2192\n    0 \u2264 n \u2192\n    let n' := Z.to_nat n in\n    subtype E L (uninit n') ty \u2192\n    (\u2200 (v : val), typed_body E L C ((v \u25c1 own_ptr n' ty) :: T) (subst' x v e)) -\u2217\n    typed_body E L C T (let: x := new [ #n ] in e).\n  Proof.\n    iIntros (????) \"Htyp\". iApply type_let; [by apply type_new_instr|solve_typing|].\n    iIntros (v). iApply typed_body_mono; last iApply \"Htyp\"; try done.\n    by apply (tctx_incl_frame_r _ [_] [_]), subtype_tctx_incl, own_mono.\n  Qed.\n\n  Lemma type_delete_instr {E L} ty (n : Z) p :\n    Z.of_nat (ty.(ty_size)) = n \u2192\n    \u22a2 typed_instruction E L [p \u25c1 own_ptr ty.(ty_size) ty] (delete [ #n; p])%E (\u03bb _, []).\n  Proof.\n    iIntros (<- tid qmax) \"#LFT #HE $ $ Hp\". rewrite tctx_interp_singleton.\n    wp_bind p. iApply (wp_hasty with \"Hp\"). iIntros ([[]|]) \"_ Hown\"; try done.\n    iDestruct \"Hown\" as \"[H\u21a6: >H\u2020]\". iDestruct \"H\u21a6:\" as (vl) \"[>H\u21a6 Hown]\".\n    iDestruct (ty_size_eq with \"Hown\") as \"#>EQ\".\n    iDestruct \"EQ\" as %<-. iApply (wp_delete with \"[-]\"); auto.\n    - iFrame \"H\u21a6\". by iApply freeable_sz_full.\n    - rewrite /tctx_interp /=; auto.\n  Qed.\n\n  Lemma type_delete {E L} ty C T T' (n' : nat) (n : Z)  p e :\n    Closed [] e \u2192\n    tctx_extract_hasty E L p (own_ptr n' ty) T T' \u2192\n    n = n' \u2192 Z.of_nat (ty.(ty_size)) = n \u2192\n    typed_body E L C T' e -\u2217\n    typed_body E L C T (delete [ #n; p ] ;; e).\n  Proof.\n    iIntros (?? -> Hlen) \"?\". iApply type_seq; [by apply type_delete_instr| |done].\n    by rewrite (inj _ _ _ Hlen).\n  Qed.\n\n  Lemma type_letalloc_1 {E L} ty C T T' (x : string) p e :\n    Closed [] p \u2192 Closed (x :b: []) e \u2192\n    tctx_extract_hasty E L p ty T T' \u2192\n    ty.(ty_size) = 1%nat \u2192\n    (\u2200 (v : val), typed_body E L C ((v \u25c1 own_ptr 1 ty)::T') (subst x v e)) -\u2217\n    typed_body E L C T (letalloc: x <- p in e).\n  Proof.\n    iIntros (??? Hsz) \"**\". iApply type_new.\n    - rewrite /Closed /=. rewrite !andb_True.\n      eauto 10 using is_closed_weaken with set_solver.\n    - done.\n    - solve_typing.\n    - iIntros (xv) \"/=\". rewrite -Hsz.\n      assert (subst x xv (x <- p ;; e)%E = (xv <- p ;; subst x xv e)%E) as ->.\n      { (* TODO : simpl_subst should be able to do this. *)\n        unfold subst=>/=. repeat f_equal.\n        - by rewrite bool_decide_true.\n        - eapply is_closed_subst; first done. set_solver. }\n      iApply type_assign; [|solve_typing|by eapply write_own|solve_typing].\n      apply subst_is_closed; last done. apply is_closed_of_val.\n  Qed.\n\n  Lemma type_letalloc_n {E L} ty ty1 ty2 C T T' (x : string) p e :\n    Closed [] p \u2192 Closed (x :b: []) e \u2192\n    tctx_extract_hasty E L p ty1 T T' \u2192\n    (\u22a2 typed_read E L ty1 ty ty2) \u2192\n    (\u2200 (v : val),\n        typed_body E L C ((v \u25c1 own_ptr (ty.(ty_size)) ty)::(p \u25c1 ty2)::T') (subst x v e)) -\u2217\n    typed_body E L C T (letalloc: x <-{ty.(ty_size)} !p in e).\n  Proof.\n    iIntros. iApply type_new.\n    - rewrite /Closed /=. rewrite !andb_True.\n      eauto 10 using is_closed_of_val, is_closed_weaken with set_solver.\n    - lia.\n    - done.\n    - iIntros (xv) \"/=\".\n      assert (subst x xv (x <-{ty.(ty_size)} !p ;; e)%E =\n              (xv <-{ty.(ty_size)} !p ;; subst x xv e)%E) as ->.\n      { (* TODO : simpl_subst should be able to do this. *)\n        unfold subst=>/=. repeat f_equal.\n        - eapply (is_closed_subst []); last set_solver. apply is_closed_of_val.\n        - by rewrite bool_decide_true.\n        - eapply is_closed_subst; first done. set_solver. }\n      rewrite Nat2Z.id. iApply type_memcpy.\n      + apply subst_is_closed; last done. apply is_closed_of_val.\n      + solve_typing.\n      + (* TODO: Doing \"eassumption\" here shows that unification takes *forever* to fail.\n           I guess that's caused by it trying to unify typed_read and typed_write,\n           but considering that the Iris connectives are all sealed, why does\n           that take so long? *)\n        by eapply (write_own ty (uninit _)).\n      + solve_typing.\n      + done.\n      + done.\n  Qed.\nEnd typing.\n\nGlobal Hint Resolve own_mono' own_proper' box_mono' box_proper'\n             write_own read_own_copy : lrust_typing.\n(* By setting the priority high, we make sure copying is tried before\n   moving. *)\nGlobal Hint Resolve read_own_move | 100 : 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/own.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.1853084323141777}}
{"text": "Require Import UFO.Rel.Definitions_closed.\nRequire Import UFO.Lang.Static.\n\nSet Implicit Arguments.\n\nImplicit Types EV LV V L : Set.\n\nNotation subst_ef \u03b4 \u03c1 \u03b5 := (\n  EV_bind_ef \u03b4 (LV_bind_ef \u03c1 \u03b5)\n).\n\nNotation subst_eff \u03b4 \u03c1 E := (\n  EV_bind_eff \u03b4 (LV_bind_eff \u03c1 E)\n).\n\nNotation subst_ty \u03b4 \u03c1 T := (\n  EV_bind_ty \u03b4 (LV_bind_ty \u03c1 T)\n).\n\nNotation subst_md \u03b4 \u03c1 \u03b3 t := (\n  V_bind_md \u03b3 (EV_bind_md \u03b4 (LV_bind_md \u03c1 t))\n).\n\nNotation subst_ktx \u03b4 \u03c1 \u03b3 K := (\n  V_bind_ktx \u03b3 (EV_bind_ktx \u03b4 (LV_bind_ktx \u03c1 K))\n).\n\nNotation subst_val \u03b4 \u03c1 \u03b3 t := (\n  V_bind_val \u03b3 (EV_bind_val \u03b4 (LV_bind_val \u03c1 t))\n).\n\nNotation subst_tm \u03b4 \u03c1 \u03b3 t := (\n  V_bind_tm \u03b3 (EV_bind_tm \u03b4 (LV_bind_tm \u03c1 t))\n).\n\nSection section_\ud835\udf29\ud835\udc77\ud835\udf1e.\nContext (EV LV V : Set).\nImplicit Type (\u039e : XEnv EV LV).\nImplicit Type (\u0393 : V \u2192 ty \u2205 EV LV \u2205).\nImplicit Type (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig).\nImplicit Type (\u03c1\u2081 \u03c1\u2082 : LV \u2192 lbl0) (\u03c1 : LV \u2192 IRel \ud835\udce3_Sig).\nImplicit Type (\u03b3\u2081 \u03b3\u2082 : V \u2192 val0).\n\nDefinition \ud835\udf1e \u039e \u0393 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 :=\n\u2200\u1d62 x, \ud835\udce5\u27e6 \u039e \u22a2 \u0393 x \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 (\u03b3\u2081 x) (\u03b3\u2082 x).\n\nDefinition \ud835\udf29 \u039e \u03be\u2081 \u03be\u2082 := dom \u039e \\c from_list \u03be\u2081 \u2227 dom \u039e \\c from_list \u03be\u2082.\n\nDefinition \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 : IProp := \u2200\u1d62 \u03b1, \ud835\udce4_is_closed \u03be\u2081 \u03be\u2082 (\u03b4 \u03b1).\n\nDefinition \u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082 : Prop :=\n\u2200 \u03b1 X,\n(\u03c1\u2081 \u03b1 = lbl_id (lid_f X) \u2192 X \u2208 from_list \u03be\u2081) \u2227\n(\u03c1\u2082 \u03b1 = lbl_id (lid_f X) \u2192 X \u2208 from_list \u03be\u2082).\n\nEnd section_\ud835\udf29\ud835\udc77\ud835\udf1e.\n\nNotation \"'\ud835\udf1e\u27e6' \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\" := (\ud835\udf1e \u039e \u0393 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1)\n(at level 25, \u039e at level 0, \u0393 at level 0,\n\u03b4\u2081 at level 0, \u03b4\u2082 at level 0, \u03b4 at level 0,\n\u03c1\u2081 at level 0, \u03c1\u2082 at level 0, \u03c1 at level 0).\n\n\nSection section_EV_LV_V_open.\nContext (EV LV V : Set).\nContext (\u039e : XEnv EV LV).\nContext (\u0393 : V \u2192 ty \u2205 EV LV \u2205).\n\nDefinition \ud835\udce3_EV_LV_V_open (T : ty \u2205 EV LV \u2205) (E : eff \u2205 EV LV \u2205) (t\u2081 t\u2082 : tm EV LV V \u2205) : IProp :=\n  \u2200\u1d62 \u03be\u2081 \u03be\u2082 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03b3\u2081 \u03b3\u2082,\n  (\ud835\udf29 \u039e \u03be\u2081 \u03be\u2082)\u1d62 \u21d2\n  \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 \u21d2\n  (\u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082)\u1d62 \u21d2\n  \ud835\udf1e\u27e6 \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 \u21d2\n  \ud835\udce3\u27e6 \u039e \u22a2 T # E \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    \u03be\u2081 \u03be\u2082\n    (subst_tm \u03b4\u2081 \u03c1\u2081 \u03b3\u2081 t\u2081)\n    (subst_tm \u03b4\u2082 \u03c1\u2082 \u03b3\u2082 t\u2082).\n\nDefinition \ud835\udce5_EV_LV_V_open (T : ty \u2205 EV LV \u2205) v\u2081 v\u2082 : IProp :=\n  \u2200\u1d62 \u03be\u2081 \u03be\u2082 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03b3\u2081 \u03b3\u2082,\n  (\ud835\udf29 \u039e \u03be\u2081 \u03be\u2082)\u1d62 \u21d2\n  \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 \u21d2\n  (\u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082)\u1d62 \u21d2\n  \ud835\udf1e\u27e6 \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 \u21d2\n  \ud835\udce5\u27e6 \u039e \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    \u03be\u2081 \u03be\u2082\n    (subst_val \u03b4\u2081 \u03c1\u2081 \u03b3\u2081 v\u2081)\n    (subst_val \u03b4\u2082 \u03c1\u2082 \u03b3\u2082 v\u2082).\n\nDefinition \ud835\udcdc_EV_LV_V_open (\u03c3 : ms \u2205 EV LV \u2205) (\u2113 : lbl LV \u2205) m\u2081 m\u2082 : IProp :=\n  \u2200\u1d62 \u03be\u2081 \u03be\u2082 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03b3\u2081 \u03b3\u2082,\n  (\ud835\udf29 \u039e \u03be\u2081 \u03be\u2082)\u1d62 \u21d2\n  \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 \u21d2\n  (\u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082)\u1d62 \u21d2\n  \ud835\udf1e\u27e6 \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 \u21d2\n  \ud835\udcdc\u27e6 \u039e \u22a2 \u03c3 ^ \u2113 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    \u03be\u2081 \u03be\u2082\n    (subst_md \u03b4\u2081 \u03c1\u2081 \u03b3\u2081 m\u2081)\n    (subst_md \u03b4\u2082 \u03c1\u2082 \u03b3\u2082 m\u2082).\n\nDefinition \ud835\udcda_EV_LV_V_open (Ta Tb : ty \u2205 EV LV \u2205) (Ea Eb : eff \u2205 EV LV \u2205) K\u2081 K\u2082 : IProp :=\n  \u2200\u1d62 \u03be\u2081 \u03be\u2082 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03b3\u2081 \u03b3\u2082,\n  (\ud835\udf29 \u039e \u03be\u2081 \u03be\u2082)\u1d62 \u21d2\n  \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 \u21d2\n  (\u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082)\u1d62 \u21d2\n  \ud835\udf1e\u27e6 \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 \u21d2\n  \ud835\udcda\u27e6 \u039e \u22a2 Ta # Ea \u21e2 Tb # Eb \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    \u03be\u2081 \u03be\u2082\n    (subst_ktx \u03b4\u2081 \u03c1\u2081 \u03b3\u2081 K\u2081)\n    (subst_ktx \u03b4\u2082 \u03c1\u2082 \u03b3\u2082 K\u2082).\n\nDefinition \ud835\udcd7_EV_LV_V_open (Ta Tb : ty \u2205 EV LV \u2205) (Ea Eb : eff \u2205 EV LV \u2205) r\u2081 r\u2082 : IProp :=\n  \u2200\u1d62 \u03be\u2081 \u03be\u2082 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03b3\u2081 \u03b3\u2082,\n  (\ud835\udf29 \u039e \u03be\u2081 \u03be\u2082)\u1d62 \u21d2\n  \u03b4_is_closed \u03be\u2081 \u03be\u2082 \u03b4 \u21d2\n  (\u03c1\u2081\u03c1\u2082_are_closed \u03be\u2081 \u03be\u2082 \u03c1\u2081 \u03c1\u2082)\u1d62 \u21d2\n  \ud835\udf1e\u27e6 \u039e \u22a2 \u0393 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 \u03b3\u2081 \u03b3\u2082 \u21d2\n  \ud835\udcd7\u27e6 \u039e \u22a2 Ta # Ea \u21e2 Tb # Eb \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1\n    \u03be\u2081 \u03be\u2082\n    (subst_tm \u03b4\u2081 \u03c1\u2081 (V_shift_val \u2218 \u03b3\u2081) r\u2081)\n    (subst_tm \u03b4\u2082 \u03c1\u2082 (V_shift_val \u2218 \u03b3\u2082) r\u2082).\n\nEnd section_EV_LV_V_open.\n\nNotation \"\u27e6 \u039e \u0393 \u22a2 t\u2081 '\u227c\u02e1\u1d52\u1d4d' t\u2082 : T # E \u27e7\" := (\ud835\udce3_EV_LV_V_open \u039e \u0393 T E t\u2081 t\u2082)\n  (at level 1, \u039e at level 0, \u0393 at level 0, t\u2081 at level 0, t\u2082 at level 0, T at level 0).\n\nNotation \"\u27e6 \u039e \u0393 \u22a2 v\u2081 '\u227c\u02e1\u1d52\u1d4d\u1d65' v\u2082 : T \u27e7\" := (\ud835\udce5_EV_LV_V_open \u039e \u0393 T v\u2081 v\u2082)\n  (at level 1, \u039e at level 0, \u0393 at level 0, v\u2081 at level 0, v\u2082 at level 0).\n\nNotation \"\u27e6 \u039e \u0393 \u22a2 m\u2081 '\u227c\u02e1\u1d52\u1d4d\u2098' m\u2082 : \u03c3 ^ \u2113 \u27e7\" := (\ud835\udcdc_EV_LV_V_open \u039e \u0393 \u03c3 \u2113 m\u2081 m\u2082)\n  (at level 1, \u039e at level 0, \u0393 at level 0, m\u2081 at level 0, m\u2082 at level 0, \u03c3 at level 0).\n\nNotation \"\u27e6 \u039e \u0393 \u22a2 K\u2081 '\u227c\u02e1\u1d52\u1d4d' K\u2082 : Ta # Ea \u21e2 Tb # Eb \u27e7\" :=\n  (\ud835\udcda_EV_LV_V_open \u039e \u0393 Ta Tb Ea Eb K\u2081 K\u2082)\n  (at level 1, \u039e at level 0, \u0393 at level 0, K\u2081 at level 0, K\u2082 at level 0, Ta at level 0, Tb at level 0).\n\nDefinition \ud835\udce3_eq_EV_LV_V_open\n(EV LV V : Set) (\u039e : XEnv EV LV) (\u0393 : V \u2192 ty \u2205 EV LV \u2205)\n(T : ty \u2205 EV LV \u2205) (E : eff \u2205 EV LV \u2205) (t\u2081 t\u2082 : tm EV LV V \u2205) : IProp :=\n\u27e6 \u039e \u0393 \u22a2 t\u2081 \u227c\u02e1\u1d52\u1d4d t\u2082 : T # E \u27e7 \u2227\u1d62 \u27e6 \u039e \u0393 \u22a2 t\u2082 \u227c\u02e1\u1d52\u1d4d t\u2081 : T # E \u27e7.\n\nNotation \"\u27e6 \u039e \u0393 \u22a2 t\u2081 '\u2248\u02e1\u1d52\u1d4d' t\u2082 : T # E \u27e7\" := (\ud835\udce3_eq_EV_LV_V_open \u039e \u0393 T E t\u2081 t\u2082)\n  (at level 1, \u039e at level 0, \u0393 at level 0, t\u2081 at level 0, t\u2082 at level 0, T at level 0).\n\n\nSection section_EV_LV_V_L_open.\nContext (EV LV V L : Set).\nContext (\u03a0 : LEnv EV LV L).\nContext (\u0393 : V \u2192 ty \u2205 EV LV L).\n\nDefinition \ud835\udce3_EV_LV_V_L_open T E t\u2081 t\u2082 : IProp :=\n\u2200\u1d62 \u039e f,\n(XLEnv \u039e \u03a0 f)\u1d62 \u21d2\n\u27e6 \u039e (L_bind_ty f \u2218 \u0393) \u22a2 (L_bind_tm f t\u2081) \u227c\u02e1\u1d52\u1d4d (L_bind_tm f t\u2082) :\n  (L_bind_ty f T) # (L_bind_eff f E) \u27e7.\n\nDefinition \ud835\udce5_EV_LV_V_L_open T v\u2081 v\u2082 : IProp :=\n\u2200\u1d62 \u039e f,\n(XLEnv \u039e \u03a0 f)\u1d62 \u21d2\n\u27e6 \u039e (L_bind_ty f \u2218 \u0393) \u22a2 (L_bind_val f v\u2081) \u227c\u02e1\u1d52\u1d4d\u1d65 (L_bind_val f v\u2082) :\n  (L_bind_ty f T) \u27e7.\n\nDefinition \ud835\udcdc_EV_LV_V_L_open \u03c3 \u2113 m\u2081 m\u2082 : IProp :=\n\u2200\u1d62 \u039e f,\n(XLEnv \u039e \u03a0 f)\u1d62 \u21d2\n\u27e6 \u039e (L_bind_ty f \u2218 \u0393) \u22a2 (L_bind_md f m\u2081) \u227c\u02e1\u1d52\u1d4d\u2098 (L_bind_md f m\u2082) :\n  (L_bind_ms f \u03c3) ^ (L_bind_lbl f \u2113) \u27e7.\n\nDefinition \ud835\udcda_EV_LV_V_L_open Ta Tb Ea Eb K\u2081 K\u2082 : IProp :=\n\u2200\u1d62 \u039e f,\n(XLEnv \u039e \u03a0 f)\u1d62 \u21d2\n\u27e6 \u039e (L_bind_ty f \u2218 \u0393) \u22a2 (L_bind_ktx f K\u2081) \u227c\u02e1\u1d52\u1d4d (L_bind_ktx f K\u2082) :\n  (L_bind_ty f Ta) # (L_bind_eff f Ea) \u21e2 (L_bind_ty f Tb) # (L_bind_eff f Eb) \u27e7.\n\nEnd section_EV_LV_V_L_open.\n\nNotation \"\u3010 \u03a0 \u0393 \u22a2 t\u2081 '\u227c\u02e1\u1d52\u1d4d' t\u2082 : T # E \u3011\" := (\ud835\udce3_EV_LV_V_L_open \u03a0 \u0393 T E t\u2081 t\u2082)\n  (\u03a0 at level 0, \u0393 at level 0, t\u2081 at level 0, t\u2082 at level 0, T at level 0).\n\nNotation \"\u3010 \u03a0 \u0393 \u22a2 v\u2081 '\u227c\u02e1\u1d52\u1d4d\u1d65' v\u2082 : T \u3011\" := (\ud835\udce5_EV_LV_V_L_open \u03a0 \u0393 T v\u2081 v\u2082)\n  (\u03a0 at level 0, \u0393 at level 0, v\u2081 at level 0, v\u2082 at level 0).\n\nNotation \"\u3010 \u03a0 \u0393 \u22a2 m\u2081 '\u227c\u02e1\u1d52\u1d4d\u2098' m\u2082 : \u03c3 ^ \u2113 \u3011\" := (\ud835\udcdc_EV_LV_V_L_open \u03a0 \u0393 \u03c3 \u2113 m\u2081 m\u2082)\n  (\u03a0 at level 0, \u0393 at level 0, m\u2081 at level 0, m\u2082 at level 0, \u03c3 at level 0).\n\nNotation \"\u3010 \u03a0 \u0393 \u22a2 K\u2081 '\u227c\u02e1\u1d52\u1d4d' K\u2082 : Ta # Ea \u21e2 Tb # Eb \u3011\" :=\n  (\ud835\udcda_EV_LV_V_L_open \u03a0 \u0393 Ta Tb Ea Eb K\u2081 K\u2082)\n  (\u03a0 at level 0, \u0393 at level 0, K\u2081 at level 0, K\u2082 at level 0, Ta at level 0, Tb at level 0).\n\nDefinition \ud835\udce3_eq_EV_LV_V_L_open\n(EV LV V L : Set) (\u03a0 : LEnv EV LV L) (\u0393 : V \u2192 ty \u2205 EV LV L) T E t\u2081 t\u2082 : IProp :=\n\u3010 \u03a0 \u0393 \u22a2 t\u2081 \u227c\u02e1\u1d52\u1d4d t\u2082 : T # E \u3011 \u2227\u1d62 \u3010 \u03a0 \u0393 \u22a2 t\u2082 \u227c\u02e1\u1d52\u1d4d t\u2081 : T # E \u3011.\n\nNotation \"\u3010 \u03a0 \u0393 \u22a2 t\u2081 '\u2248\u02e1\u1d52\u1d4d' t\u2082 : T # E \u3011\" := (\ud835\udce3_eq_EV_LV_V_L_open \u03a0 \u0393 T E t\u2081 t\u2082)\n  (\u03a0 at level 0, \u0393 at level 0, t\u2081 at level 0, t\u2082 at level 0, T at level 0).\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/Definitions_open.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.18529531912878133}}
{"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 rec_destroy_ops_spec (g_rec: Pointer) (adt: RData) : option RData :=\n    rely (peq (base g_rec) ginfo_loc);\n    let rec_gidx := (offset g_rec) in\n    rely is_gidx rec_gidx;\n    let gn := (gs (share adt)) @ rec_gidx in\n    rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n    rely (gtype gn =? GRANULE_STATE_REC);\n    rely prop_dec (glock gn = Some CPU_ID);\n    rely prop_dec (gref gn = None);\n    rely (g_inited (gro gn));\n    rely prop_dec ((buffer (priv adt)) @ SLOT_REC = None);\n    rely prop_dec ((buffer (priv adt)) @ SLOT_REC_LIST = None);\n    let rd_gidx := g_rd (ginfo gn) in\n    let rec_list_gidx := g_rec_rec_list (grec gn) in\n    let rec_idx := g_rec_idx (gro gn) in\n    rely is_int64 rec_idx; rely is_gidx rd_gidx; rely is_gidx rec_list_gidx;\n    let gn_recl := (gs (share adt)) @ rec_list_gidx in\n    let gn_rd := (gs (share adt)) @ rd_gidx in\n    rely (gtype gn_recl =? GRANULE_STATE_REC_LIST);\n    rely (gtype gn_rd =? GRANULE_STATE_RD);\n    rely (gcnt gn_rd >? 0);\n    let gn_recl' := gn_recl {gnorm: (gnorm gn_recl) {g_data: (g_data (gnorm gn_recl)) # rec_idx == 0}} in\n    let gn_rec' := gn {ginfo: (ginfo gn) {g_rd: 0} {g_tag: GRANULE_STATE_DELEGATED}}\n                      {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec} in\n    let gn_rd' := gn_rd {gcnt: (gcnt gn_rd) - 1} in\n    let e := EVT CPU_ID (RECL rec_list_gidx rec_idx UNSET_RECL) in\n    let e' := EVT CPU_ID (REL rec_gidx gn_rec') in\n    let e'' := EVT CPU_ID (DEC_RD_GCNT rd_gidx) in\n    Some adt {log: e'' :: e' :: e :: log adt}\n             {share: (share adt) {gs: (gs (share adt)) # rec_list_gidx == gn_recl'\n                                                       # rec_gidx == (gn_rec' {glock: None} {gtype: GRANULE_STATE_DELEGATED})\n                                                       # rd_gidx == gn_rd'}}.\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/rec_destroy_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.18529531377906422}}
{"text": "Require Import RelationClasses.\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.\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 MemoryDomain.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\n\nSet Implicit Arguments.\n\n\nInductive sim_local (pview:SimPromises.t) (lc_src lc_tgt:Local.t): Prop :=\n| sim_local_intro\n    (TVIEW: TView.le (Local.tview lc_src) (Local.tview lc_tgt))\n    (PROMISES: SimPromises.sem pview SimPromises.bot (Local.promises lc_src) (Local.promises lc_tgt))\n.\n\nGlobal Program Instance sim_local_PreOrder: PreOrder (sim_local SimPromises.bot).\nNext Obligation.\n  econs; try refl. apply SimPromises.sem_bot.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. econs; try etrans; eauto.\n  apply SimPromises.sem_bot_inv in PROMISES; auto.\n  apply SimPromises.sem_bot_inv in PROMISES0; auto.\n  rewrite PROMISES, PROMISES0. apply SimPromises.sem_bot.\nQed.\n\nLemma sim_local_nonsynch_loc\n      pview loc lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch_loc loc (Local.promises lc_tgt)):\n  Memory.nonsynch_loc loc (Local.promises lc_src).\nProof.\n  inv SIM. inv PROMISES.\n  ii. destruct msg; ss.\n  destruct (Memory.get loc t (Local.promises lc_tgt)) as [[? []]|] eqn:GET_TGT.\n  - exploit NONSYNCH; eauto. ss. i. subst.\n    exploit LE; eauto. intro X. rewrite GET in X. inv X.\n    unfold SimPromises.none_if, SimPromises.none_if_released. condtac; ss.\n  - exploit LE; eauto. s. i. congr.\n  - exploit LE; eauto. s. i. congr.\n  - exploit COMPLETE; eauto. rewrite SimPromises.bot_spec. ss.\nQed.\n\nLemma sim_local_nonsynch\n      pview lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch (Local.promises lc_tgt)):\n  Memory.nonsynch (Local.promises lc_src).\nProof.\n  ii. eapply sim_local_nonsynch_loc; eauto.\nQed.\n\nLemma sim_local_memory_bot\n      pview lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (BOT: (Local.promises lc_tgt) = Memory.bot):\n  (Local.promises lc_src) = Memory.bot.\nProof.\n  inv SIM. inv PROMISES. rewrite BOT in *.\n  apply Memory.ext. i. rewrite Memory.bot_get.\n  destruct (Memory.get loc ts (Local.promises lc_src)) eqn:GET_SRC; ss.\n  destruct p.\n  exploit COMPLETE; eauto.\n  - apply Memory.bot_get.\n  - rewrite SimPromises.bot_spec. ss.\nQed.\n\nLemma sim_local_promise\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to (SimPromises.none_if loc to pview msg) lc2_src mem2_src (SimPromises.kind_transf loc to pview kind)>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit sim_memory_closed_message; eauto. i.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { unfold SimPromises.none_if, SimPromises.none_if_released.\n    destruct msg; try condtac; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto. SimPromises.none_if_tac. eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_promise_bot\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit sim_local_promise; eauto.\n  rewrite SimPromises.none_if_bot.\n  rewrite SimPromises.kind_transf_bot. ss.\nQed.\n\nLemma sim_local_read\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt ord_tgt lc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; eauto. i. des.\n  inv MSG. esplits; eauto.\n  - econs; eauto; (try etrans; eauto).\n    eapply TViewFacts.readable_mon; eauto. apply TVIEW.\n  - econs; eauto. s. apply TViewFacts.read_tview_mon; auto.\n    + apply WF1_TGT.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des. inv MSG_WF. auto.\nQed.\n\nLemma sim_local_fulfill\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (PVIEW: SimPromises.mem loc to pview = false \\/ Ordering.le ord_tgt Ordering.plain)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src (SimPromises.none_if_released loc to pview released) ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local (SimPromises.unset loc to pview) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  guardH PVIEW.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { apply TViewFacts.write_released_mon; ss.\n    - apply LOCAL1.\n    - apply WF1_TGT.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  i. des. esplits.\n  - econs; eauto.\n    + SimPromises.none_if_tac.\n      * unguardH PVIEW. des; ss. unfold TView.write_released. condtac; [|refl].\n        destruct ord_src, ord_tgt; inv ORD; inv PVIEW; inv COND0.\n      * etrans; eauto.\n    + SimPromises.none_if_tac; viewtac.\n    + eapply TViewFacts.writable_mon; try exact WRITABLE; eauto. apply LOCAL1.\n  - econs; eauto. s. apply TViewFacts.write_tview_mon; auto.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n  - ss.\nQed.\n\nLemma sim_local_fulfill_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  exploit sim_local_fulfill; eauto.\n  { rewrite SimPromises.bot_spec. intuition. }\n  i. des. esplits; eauto.\n  rewrite SimPromises.unset_bot in *; ss.\nQed.\n\nLemma sim_local_promise_not_lower\n      pview\n      lc1_src\n      lc1_tgt mem1_tgt loc from to msg_tgt lc1 mem2_tgt kind\n      (LOCAL: sim_local pview lc1_src lc1_tgt)\n      (STEP: Local.promise_step lc1_tgt mem1_tgt loc from to msg_tgt lc1 mem2_tgt kind)\n      (KIND: negb (Memory.op_kind_is_lower kind)):\n  SimPromises.mem loc to pview = false.\nProof.\n  destruct (SimPromises.mem loc to pview) eqn:X; ss.\n  inv LOCAL. inv PROMISES. exploit PVIEW; eauto. i. des.\n  inv STEP. inv PROMISE; ss.\n  - exploit Memory.add_get0; try exact PROMISES; eauto. i. des. congr.\n  - exploit Memory.split_get0; try exact PROMISES; eauto. i. des. congr.\n  - exploit Memory.remove_get0; try exact PROMISES; eauto. i. des. congr.\nQed.\n\nLemma sim_local_write\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (PVIEW: SimPromises.mem loc to pview = false \\/\n              Ordering.le ord_tgt Ordering.plain \\/\n              Ordering.le Ordering.strong_relaxed ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src\n                                 released_src\n                                 ord_src lc2_src sc2_src mem2_src\n                                 (SimPromises.kind_transf loc to pview kind)>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local (SimPromises.unset loc to pview) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  guardH PVIEW.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_fulfill; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { unguardH PVIEW. des; intuition.\n    exploit Local.write_step_strong_relaxed; eauto. i.\n    left. eapply sim_local_promise_not_lower; try exact STEP1; eauto.\n  }\n  i. des.\n  exploit promise_fulfill_write_sim_memory; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. subst. esplits; eauto.\n  - apply TViewFacts.write_released_mon; ss;\n      try apply LOCAL1; try apply WF1_TGT.\n  - etrans; eauto.\nQed.\n\nLemma sim_local_write_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src\n                                 released_src\n                                 ord_src lc2_src sc2_src mem2_src\n                                 kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  hexploit sim_local_write; eauto.\n  { rewrite SimPromises.bot_spec. intuition. }\n  i. des. esplits; eauto.\n  - rewrite SimPromises.kind_transf_bot in *. eauto.\n  - rewrite SimPromises.unset_bot in *; ss.\nQed.\n\nLemma sim_local_write_na\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 ord_src ord_tgt msgs kinds kind\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.write_na_step lc1_tgt sc1_tgt mem1_tgt loc from to val ord_tgt lc2_tgt sc2_tgt mem2_tgt msgs kinds kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_na_step lc1_src sc1_src mem1_src loc from to val ord_src lc2_src sc2_src mem2_src msgs kinds kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv STEP_TGT.\n  exploit SimPromises.write_na;\n    try apply WRITE; try apply LOCAL1; try apply WF1_SRC; try apply WF1_TGT; eauto.\n  i. des.\n  esplits; eauto. econs; s; eauto.\n  apply TViewFacts.write_tview_mon; try apply LOCAL1; eauto. apply WF1_TGT.\nQed.\n\nLemma sim_local_update\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (PVIEW: SimPromises.mem loc to2 pview = false \\/\n              Ordering.le ord2_tgt Ordering.plain \\/\n              Ordering.le Ordering.strong_relaxed ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src\n                                  (SimPromises.kind_transf loc to2 pview kind)>> /\\\n    <<LOCAL3: sim_local (SimPromises.unset loc to2 pview) lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  guardH PVIEW.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_update_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src kind>> /\\\n    <<LOCAL3: sim_local SimPromises.bot lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write_bot; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_fence\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt sc1_tgt ordr_tgt ordw_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: Local.fence_step lc1_src sc1_src ordr_src ordw_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT. esplits; eauto.\n  - econs; eauto. i. eapply sim_local_nonsynch; eauto.\n    i. eapply sim_local_memory_bot; eauto. eapply PROMISES.\n    subst. destruct ordw_tgt; ss.\n  - econs; try apply LOCAL1. s.\n    apply TViewFacts.write_fence_tview_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n    + eapply TViewFacts.read_fence_future; apply WF1_SRC.\n  - apply TViewFacts.write_fence_sc_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\nQed.\n\nLemma sim_local_promise_consistent\n      pview\n      lc_src lc_tgt\n      (LOCAL: sim_local pview lc_src lc_tgt)\n      (CONS_TGT: Local.promise_consistent lc_tgt):\n  <<CONS_SRC: Local.promise_consistent lc_src>>.\nProof.\n  inv LOCAL. inv PROMISES. ii.\n  destruct (Memory.get loc ts (Local.promises lc_tgt)) as [[]|] eqn:GETP.\n  - exploit LE; eauto. intros x. rewrite PROMISE in x. inv x.\n    destruct (classic (t0 = Message.reserve)); subst; ss.\n    exploit CONS_TGT; eauto; ss. i.\n    eapply TimeFacts.le_lt_lt; eauto.\n    inv TVIEW. inv CUR. eauto.\n  - exploit COMPLETE; eauto. intros x.\n    rewrite MemoryDomain.bot_spec in x. ss.\nQed.\n\nLemma sim_local_failure\n      pview\n      lc1_src lc1_tgt\n      (STEP_TGT: Local.failure_step lc1_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt):\n  <<STEP_SRC: Local.failure_step lc1_src>>.\nProof.\n  inv STEP_TGT.\n  hexploit sim_local_promise_consistent; eauto.\nQed.\n\nLemma sim_local_is_racy\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to ord_src ord_tgt\n      (RACE_TGT: Local.is_racy lc1_tgt mem1_tgt loc to ord_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<RACE_SRC: Local.is_racy lc1_src mem1_src loc to ord_src>>.\nProof.\n  inv RACE_TGT.\n  exploit sim_memory_get; eauto. i. des.\n  exploit SimPromises.get_None; [apply LOCAL1|..]; eauto. i. des.\n  econs; eauto.\n  - eapply TViewFacts.racy_view_mon; eauto. apply LOCAL1.\n  - inv MSG; ss.\n  - i. exploit MSG2; try by destruct ord_src, ord_tgt; inv ORD.\n    i. subst. inv MSG. ss.\nQed.\n\nLemma sim_local_racy_read\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to val ord_src ord_tgt\n      (STEP_TGT: Local.racy_read_step lc1_tgt mem1_tgt loc to val ord_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<STEP_SRC: Local.racy_read_step lc1_src mem1_src loc to val ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy; eauto.\nQed.\n\nLemma sim_local_racy_write\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to ord_src ord_tgt\n      (STEP_TGT: Local.racy_write_step lc1_tgt mem1_tgt loc to ord_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<STEP_SRC: Local.racy_write_step lc1_src mem1_src loc to ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy; eauto. i. des.\n  hexploit sim_local_promise_consistent; eauto.\nQed.\n\nLemma sim_local_racy_update\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to ordr_src ordw_src ordr_tgt ordw_tgt\n      (STEP_TGT: Local.racy_update_step lc1_tgt mem1_tgt loc to ordr_tgt ordw_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src mem1_src loc to ordr_src ordw_src>>.\nProof.\n  inv STEP_TGT; try by hexploit sim_local_promise_consistent; eauto.\n  exploit sim_local_is_racy; eauto. i. des.\n  hexploit sim_local_promise_consistent; eauto.\nQed.\n\nLemma sim_local_program_step\n      lang\n      th1_src\n      th1_tgt th2_tgt e_tgt\n      (STEP_TGT: @Thread.program_step lang e_tgt th1_tgt th2_tgt)\n      (WF1_SRC: Local.wf (Thread.local th1_src) (Thread.memory th1_src))\n      (WF1_TGT: Local.wf (Thread.local th1_tgt) (Thread.memory th1_tgt))\n      (SC1_SRC: Memory.closed_timemap (Thread.sc th1_src) (Thread.memory th1_src))\n      (SC1_TGT: Memory.closed_timemap (Thread.sc th1_tgt) (Thread.memory th1_tgt))\n      (MEM1_SRC: Memory.closed (Thread.memory th1_src))\n      (MEM1_TGT: Memory.closed (Thread.memory th1_tgt))\n      (STATE: (Thread.state th1_src) = (Thread.state th1_tgt))\n      (LOCAL: sim_local SimPromises.bot (Thread.local th1_src) (Thread.local th1_tgt))\n      (SC: TimeMap.le (Thread.sc th1_src) (Thread.sc th1_tgt))\n      (MEM: sim_memory (Thread.memory th1_src) (Thread.memory th1_tgt)):\n  exists e_src th2_src,\n    <<STEP_SRC: @Thread.program_step lang e_src th1_src th2_src>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<STATE: (Thread.state th2_src) = (Thread.state th2_tgt)>> /\\\n    <<LOCAL: sim_local SimPromises.bot (Thread.local th2_src) (Thread.local th2_tgt)>> /\\\n    <<SC: TimeMap.le (Thread.sc th2_src) (Thread.sc th2_tgt)>> /\\\n    <<MEM: sim_memory (Thread.memory th2_src) (Thread.memory th2_tgt)>>.\nProof.\n  destruct th1_src. ss. subst. inv STEP_TGT; ss.\n  inv LOCAL0; ss.\n  - esplits; (try by econs; [|econs 1]; eauto); ss.\n  - exploit sim_local_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 2]; eauto); ss.\n  - hexploit sim_local_write_bot; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 3]; eauto); ss.\n  - exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read; eauto; try refl. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    hexploit sim_local_write_bot; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 4]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 5]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 6]; eauto); ss.\n  - exploit sim_local_failure; eauto. i. des.\n    esplits; (try by econs; [|econs 7]; eauto); ss.\n  - exploit sim_local_write_na; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 8]; eauto); ss.\n  - exploit sim_local_racy_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 9]; eauto); ss.\n  - exploit sim_local_racy_write; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 10]; eauto); ss.\n  - exploit sim_local_racy_update; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 11]; eauto); ss.\nQed.\n\nLemma sim_local_lower_src\n      pview1\n      lc1_src sc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_src mem2_src\n      loc from to val released\n      (LOCAL1: sim_local pview1 lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (STEP_SRC: Local.promise_step lc1_src mem1_src loc from to (Message.concrete val None) lc2_src mem2_src (Memory.op_kind_lower (Message.concrete val released))):\n  <<LOCAL2: exists pview2, sim_local pview2 lc2_src lc1_tgt>> /\\\n  <<MEM2: sim_memory mem2_src mem1_tgt>> /\\\n  <<WF2_SRC: Local.wf lc2_src mem2_src>>.\nProof.\n  splits.\n  - inv STEP_SRC. inv PROMISE.\n    exists (match Memory.get loc to (Local.promises lc1_tgt) with\n       | Some _ => SimPromises.set loc to pview1\n       | None => pview1\n       end).\n    inv LOCAL1. econs; ss. inv PROMISES0. econs; ss.\n    + ii.\n      exploit LE; eauto. intros x.\n      exploit Memory.lower_get0; try exact PROMISES; eauto. i.\n      erewrite Memory.lower_o; eauto.\n      unfold SimPromises.none_if, SimPromises.none_if_released.\n      destruct (Memory.get loc to (Local.promises lc1_tgt)) eqn:TGT.\n      * rewrite SimPromises.set_o. condtac; ss.\n        { des. subst. condtac; ss; cycle 1.\n          { revert COND0. condtac; ss. des; congr. }\n          rewrite GET in x. inv x. destruct msg; ss. inv H1; ss.\n        }\n        { guardH o. condtac.\n          { revert COND0. condtac; ss.\n            { des. subst. unguardH o. des; congr. }\n            guardH o0. i.\n            rewrite x. repeat f_equal. SimPromises.none_if_tac.\n          }\n          rewrite x. repeat f_equal. SimPromises.none_if_tac.\n          revert COND0. condtac; ss.\n        }\n      * condtac; ss. des. subst. congr.\n    + i. revert MEM0. condtac; ss; cycle 1.\n      { eapply PVIEW. }\n      rewrite SimPromises.set_o. condtac; ss; cycle 1.\n      { eapply PVIEW. }\n      i. des. subst. destruct p.\n      exploit LE; eauto. ss. i.\n      exploit Memory.lower_get0; try exact PROMISES; eauto. i. des.\n      destruct t0; ss; try congr; eauto.\n    + i. revert SRC. erewrite Memory.lower_o; eauto. condtac; ss.\n      * i. des. inv SRC. eapply COMPLETE; eauto.\n        hexploit Memory.lower_get0; try exact PROMISES; eauto. i. des. eauto.\n      * i. eapply COMPLETE; eauto.\n  - etrans; [|eauto]. inv STEP_SRC. inv PROMISE. eapply lower_sim_memory; eauto.\n  - eapply Local.promise_step_future; eauto.\nQed.\n\nLemma sim_local_nonsynch_src\n      pview\n      lang st sc\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (LOCAL1_SRC: Local.wf lc1_src mem1_src)\n      (LOCAL2_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists pview2 lc2_src mem2_src,\n    <<STEP_SRC: rtc (@Thread.tau_step lang)\n                    (Thread.mk lang st lc1_src sc mem1_src)\n                    (Thread.mk lang st lc2_src sc mem2_src)>> /\\\n    <<NONSYNCH2: Memory.nonsynch (Local.promises lc2_src)>> /\\\n    <<LOCAL2: sim_local pview2 lc2_src lc1_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem1_tgt>>.\nProof.\n  inversion LOCAL1_SRC.\n  destruct FINITE. rename x into dom.\n  assert (FINITE' : forall (loc : Loc.t) (from to : Time.t) (msg : Message.t),\n             Memory.get loc to (Local.promises lc1_src) = Some (from, msg) ->\n             (match msg with\n              | Message.concrete _ (Some _) => True\n              | _ => False\n              end) ->\n             In (loc, to) dom).\n  { ii. eapply H. eauto. }\n  clear H. move dom after lc1_src. revert_until dom. revert pview.\n  induction dom.\n  { esplits; eauto. ii. destruct msg; ss. destruct released; ss.\n    exfalso. eapply FINITE'; eauto. ss.\n  }\n  destruct a as [loc to]. i.\n  destruct (Memory.get loc to (Local.promises lc1_src)) as [[? []]|] eqn:X; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intros x. inv x; ss.\n    inv H1. rewrite X in H. inv H. inv H0. }\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intros x. inv x; ss.\n    inv H1. rewrite X in H. inv H. inv H0. }\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intros x. inv x; ss.\n    inv H1. congr. }\n  destruct released; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intros x. inv x; ss.\n    inv H1. rewrite H in X. inv X. ss. }\n  exploit MemoryFacts.promise_exists_None; eauto.\n  { eapply MemoryFacts.released_time_lt; [by apply MEM1_SRC|]. apply LOCAL1_SRC. eauto. }\n  i. des.\n  exploit Memory.promise_future; try exact x0; try apply LOCAL1_SRC; eauto. i. des.\n  exploit sim_local_lower_src; eauto. i. des.\n  exploit IHdom; eauto.\n  { eapply Memory.future_closed_timemap; eauto. }\n  { eapply TView.future_closed; eauto. }\n  { s. i. inv x0. revert H.\n    erewrite Memory.lower_o; eauto. condtac; ss.\n    - i. des. inv H. ss.\n    - guardH o. i. exploit FINITE'; eauto. intros x. des; ss. inv x.\n      unguardH o. des; congr.\n  }\n  i. des. esplits; try exact NONSYNCH2; eauto.\n  econs 2; eauto. econs.\n  - econs. econs 1. econs; eauto.\n  - ss.\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/SimLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.18527281519473698}}
{"text": "Require Import erasure. \nRequire Import IndependenceCommon. \n\nTheorem newFastForward : forall H T H' T' TID x M' E s2 d s1' p M,\n         heap_lookup x H = None -> decompose M' E new ->\n         spec_multistep H (tUnion T (tSingleton(TID,unlocked nil,s2,M'))) H' \n                        (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,M))) ->\n         exists H'' T'',\n           spec_multistep H (tUnion T (tSingleton(TID,unlocked nil,s2,M'))) H''\n                         (tUnion T'' (tSingleton(TID,unlocked [nAct M' E d x],s2,fill E (ret (fvar x))))) /\\\n           spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked [nAct M' E d x],s2,fill E (ret (fvar x)))))\n                          H' (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,M)))  /\\\n           spec_multistep (Heap.extend x (sempty COMMIT) H p) T \n                          (replace x (sempty COMMIT) H'') T'' /\\ \n           heap_lookup x H'' = Some(sempty SPEC).\nProof.\n  intros. dependent induction H2. \n  {apply UnionEqTID in x. invertHyp. inv H2. invertListNeq. }\n  {startIndCase. destructThread x1. exMid TID H9. \n   {apply UnionEqTID in H5. invertHyp. econstructor. exists T. split. econstructor. \n    eapply SNew with (x:=x0)(p:=p). eauto. simpl. constructor.\n    split. inv H3;try solve[falseDecomp]. \n    {inv H14; falseDecomp. }\n    {simpl in *. copy H2. firstActTac H2. inv H2. proofsEq d d0. proofsEq p p0. eassumption. }\n    split. erewrite replaceExtendOverwrite. constructor. rewrite lookupExtend. auto. \n   }\n   {apply UnionNeqTID in x. invertHyp. copy H3. eapply specStepNoneIVar in H3; eauto. \n    Focus 3. solveSet. Focus 2. rewrite H4. solveSet. left. invUnion. right. simpl; auto. \n    Focus 2. auto. eapply IHspec_multistep with(p:=H3)in H1. Focus 2. eassumption. \n    Focus 2. auto. Focus 3. auto. invertHyp. exists x. exists x1. split. rewrite H11. \n    unfoldTac. rewrite UnionSwap. econstructor. eapply specStepChangeUnused. eauto. \n    unfoldTac. rewrite <- UnionSwap. eassumption. split. eassumption. split.\n    rewrite H11. clear H11 H4. inv H12. \n    {econstructor. eapply SBasicStep; eauto. proofsEq p H3. eassumption. }\n    {econstructor. eapply SFork. auto. proofsEq p H3. eauto. }\n    {destruct (beq_nat x2 x0) eqn:eq. apply beq_nat_true in eq. subst. rewrite H0 in H23.\n     inv H23. apply beq_nat_false in eq. econstructor. eapply SGet with(x:=x2); auto. \n     erewrite lookupExtendNeq; eauto. erewrite <- extendReplaceSwitch; eauto. }\n    {destruct (beq_nat x2 x0) eqn:eq. apply beq_nat_true in eq. subst.\n     rewrite H0 in H23. inv H23. apply beq_nat_false in eq. econstructor. eapply SPut with(x:=x2). \n     erewrite lookupExtendNeq; eauto. auto. erewrite <- extendReplaceSwitch; eauto. }\n    {destruct (beq_nat x2 x0)eqn:eq. apply beq_nat_true in eq. subst. \n     copy H3. erewrite lookupExtend in H4. inv H4. apply beq_nat_false in eq. \n     econstructor. eapply SNew with(x:=x2). auto. erewrite extendExtendSwitch. eassumption. }\n    {econstructor. eapply SSpec; eauto. proofsEq p H3. eassumption. }\n    auto. rewrite H4. rewrite UnionSubtract. unfoldTac. rewrite UnionSwap; eauto. \n   }\n  }\n  Grab Existential Variables. eapply lookupExtendNeq; eauto.  \nQed. \n\nTheorem stepReplaceEmpty : forall H T t H' t' x,\n                             heap_lookup x H = Some(sempty SPEC) -> \n                             heap_lookup x H' = Some(sempty SPEC) ->\n                             spec_step H T t H' T t' -> \n                             spec_step (replace x (sempty COMMIT) H) T t \n                                       (replace x (sempty COMMIT) H') T t'. \nProof.\n  intros. inv H2; auto.\n  {destruct (beq_nat x0 x) eqn:eq. \n   {apply beq_nat_true in eq. subst. rewrite H3 in H0. inv H0. }\n   {eapply SGet with(x:=x0). apply beq_nat_false in eq. rewrite lookupReplaceNeq; eauto. \n    rewrite lookupReplaceSwitch. auto. apply beq_nat_false in eq. auto. }\n  }\n  {destruct (beq_nat x0 x) eqn:eq. \n   {apply beq_nat_true in eq. subst. erewrite HeapLookupReplace in H1; eauto. inv H1. }\n   {apply beq_nat_false in eq. eapply SPut. erewrite lookupReplaceNeq; eauto. \n    erewrite lookupReplaceSwitch; eauto. }\n  }\n  {destruct (beq_nat x0 x) eqn:eq. \n   {apply beq_nat_true in eq. subst. copy p. rewrite H2 in H0. inv H0. }\n   {apply beq_nat_false in eq. eapply SNew; eauto. erewrite extendReplaceSwitch; eauto. }\n  }\n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto. \nQed. \n\nTheorem smultiReplaceEmpty : forall H T T' H' x,\n                             heap_lookup x H = Some(sempty SPEC) -> \n                             heap_lookup x H' = Some(sempty SPEC) ->\n                             spec_multistep H T H' T' -> \n                             spec_multistep (replace x (sempty COMMIT) H) T \n                                       (replace x (sempty COMMIT) H') T'. \nProof.\n  intros. induction H2. \n  {constructor. }\n  {copy H. apply specStepSingleton in H3. invertHyp. copy H. \n   eapply specStepEmptyIVar' in H; eauto. eapply stepReplaceEmpty in H3; eauto. \n   econstructor. eauto. auto. }\nQed. \n\nTheorem newSimPureStepsEmpty : forall H T H' T' TID x M' E d N N' N'' s2 s1',\n       eraseTrm s1' N' N'' -> \n       heap_lookup x H = Some(sempty SPEC) ->       \n       heap_lookup x H' = Some(sempty SPEC)-> \n       spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) ->\n       exists H'' T'',\n         spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) \n                        H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) /\\\n         spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) \n                        H' (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) /\\\n         spec_multistep (replace x (sempty COMMIT) H) T \n                        (replace x (sempty COMMIT)H'') T'' /\\\n         heap_lookup x H'' = Some(sempty SPEC).\nProof.\n  intros. dependent induction H3. \n  {apply UnionEqTID in x. invertHyp. inv H. destruct s1'; inv H5; try invertListNeq. \n   inv H0; try invertListNeq. repeat econstructor. eauto. }\n  {startIndCase. destructThread x1. exMid H10 TID.\n   {apply UnionEqTID in x. invertHyp. inversion H4; subst. \n    {eapply IHspec_multistep in H1;[idtac|eauto|idtac|auto|auto|auto|auto]; auto. \n     invertHyp. econstructor. econstructor. split. econstructor. eapply SBasicStep; eauto.\n     eassumption. split; auto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. \n     do 4 econstructor. simpl in *. econstructor. eapply SFork; eauto. eassumption. \n     split. constructor. auto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. \n     do 4 econstructor. simpl in *. destruct (beq_nat x x0) eqn:eq. apply beq_nat_true in eq.\n     subst. rewrite H15 in H1. inv H1. apply beq_nat_false in eq. econstructor. \n     eapply SGet with(x:=x); eauto. simpl in *. eassumption. split. constructor. auto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. \n     do 4 econstructor. simpl in *. destruct (beq_nat x x0) eqn:eq. apply beq_nat_true in eq.\n     subst. eapply smultiEmptyFull in H5. Focus 3. eauto. Focus 2. rewrite H15 in H1.\n     inv H1. erewrite HeapLookupReplace; eauto. contradiction. \n     apply beq_nat_false in eq. econstructor. eapply SPut with(x:=x); eauto. simpl in *. \n     eassumption. split. constructor. auto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. \n     do 4 econstructor. simpl in *. destruct (beq_nat x x0) eqn:eq. apply beq_nat_true in eq.\n     subst. copy p. rewrite H0 in H1. inv H1. apply beq_nat_false in eq. econstructor. \n     eapply SNew with(x:=x); eauto. simpl in *. eassumption. split. constructor. auto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. \n     do 4 econstructor. econstructor. eapply SSpec; eauto. simpl in *. eassumption. \n     split. constructor. auto. }\n   }\n   {apply UnionNeqTID in x; auto. invertHyp. copy H4. eapply specStepEmptyIVar' in H4; eauto. copy H4. \n    eapply IHspec_multistep in H4;[idtac|eauto|idtac|auto|idtac|auto|auto].\n    Focus 2. auto. invertHyp. econstructor. econstructor. split. rewrite H12. \n    unfoldTac. rewrite UnionSwap. econstructor. eapply specStepChangeUnused; eauto.\n    unfoldTac. rewrite UnionSwap. eauto. split; auto. split. rewrite H12. \n    econstructor. eapply stepReplaceEmpty. eauto. eapply H14.  eapply specStepChangeUnused; eauto. \n    eauto. eauto. rewrite H5. rewrite UnionSubtract. unfoldTac. rewrite UnionSwap; eauto. }\n  }\nQed. \n\nTheorem newSimActionStepsEmpty : forall H T H' T' TID x M' E d N N' H'' T'' N'' s2 s1 s1' a,\n       eraseTrm (s1'++[a]) N' N'' ->\n       heap_lookup x H = Some(sempty SPEC) ->       \n       heap_lookup x H' = Some(sempty SPEC) -> \n       spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked [nAct M' E d x],s2,N'')))\n                      H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) ->\n       spec_multistep H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[a]++[nAct M' E d x]),s2,N'))) ->\n       spec_multistep (replace x (sempty COMMIT) H)\n                      (tUnion T (tSingleton(TID,unlocked s1,nAct M' E d x::s2,N))) \n                      (replace x (sempty COMMIT) H')\n                      (tUnion T' (tSingleton(TID,unlocked (s1'++[a]), nAct M' E d x::s2,N'))).\nProof.\n  intros. dependent induction H4; intros. \n  {apply UnionEqTID in x. invertHyp. inv H.\n   replace[a;nAct M' E d x0] with ([a]++[nAct M' E d x0]) in H6; auto. \n   rewrite app_assoc in H6. apply app_inj_tail in H6. invertHyp. rewrite H2 in H1. \n   inv H1. constructor. }\n  {startIndCase. destructThread x1. exMid H11 TID. \n   {apply UnionEqTID in x. invertHyp. inv H7. copy H5. eapply specStepEmptyIVar' in H5; eauto.  \n    inversion H6; subst. \n    {copy H3. eapply stackNonNil in H3; eauto. destruct s1. exfalso. apply H3. auto. \n     econstructor. eapply SBasicStep; eauto. constructor. eapply IHspec_multistep; eauto. \n     eapply spec_multi_trans. eauto. econstructor. eapply SBasicStep; eauto. constructor.\n     intros c. subst. apply eraseTrmApp in H0. inv H0; inv H16; falseDecomp. }\n    {econstructor. eapply SFork; eauto. simpl. unfoldTac. rewrite coupleUnion. \n     rewrite Union_associative. rewrite UnionSwap. eapply IHspec_multistep; eauto. \n     Focus 2. rewrite <- Union_associative. rewrite <- coupleUnion. rewrite couple_swap. \n     unfold numForks. simpl. simpl. eauto. rewrite numForksDistribute. simpl. rewrite <- plus_assoc. \n     rewrite <- plus_comm. simpl. rewrite plus_comm. reflexivity. eapply spec_multi_trans. \n     eassumption. econstructor. eapply SFork; eauto. rewrite <- Union_associative. rewrite <- coupleUnion. \n     rewrite couple_swap. simpl. rewrite numForksDistribute. simpl. rewrite <- plus_assoc. \n     rewrite plus_comm. simpl. rewrite plus_comm. constructor. }\n    {destruct(beq_nat x x0) eqn:eq. \n     {apply beq_nat_true in eq. subst. heapsDisagree. }\n     {apply beq_nat_false in eq. apply neqSym in eq. lookupTac.\n      eapply IHspec_multistep in H7;[idtac|eauto|idtac|auto|auto|auto|auto|auto]; auto.\n      econstructor. eapply SGet with(x:=x); auto. rewrite lookupReplaceNeq; eauto. \n      rewrite lookupReplaceSwitch; auto. eassumption. eapply spec_multi_trans. eassumption. \n      econstructor. eapply SGet with(x:=x); eauto. constructor. simpl. eauto. }\n    }\n    {destruct (beq_nat x x0) eqn:eq. apply beq_nat_true in eq. subst. rewrite H16 in H1. \n     inv H1. eapply smultiEmptyFull in H4; eauto. contradiction. erewrite HeapLookupReplace; eauto. \n     apply beq_nat_false in eq. apply neqSym in eq. lookupTac.\n     eapply IHspec_multistep in H7;[idtac|eauto|idtac|auto|auto|auto|auto|auto]; auto.\n     econstructor. eapply SPut with(x:=x). \n     rewrite lookupReplaceNeq; eauto. auto. rewrite lookupReplaceSwitch; auto. simpl. \n     eassumption. eapply spec_multi_trans. eassumption. econstructor. eapply SPut with(x:=x). \n     eauto. auto. constructor. simpl. reflexivity. }\n    {destruct (beq_nat x x0) eqn:eq. apply beq_nat_true in eq. subst. copy p. rewrite H7 in H1. \n     inv H1. apply beq_nat_false in eq. apply neqSym in eq. lookupTac.\n     eapply IHspec_multistep in H7;[idtac|eauto|idtac|auto|auto|auto|auto|auto]; auto.\n     econstructor. eapply SNew with(x:=x). \n     auto. erewrite extendReplaceSwitch; eauto. eapply spec_multi_trans. eassumption. \n     econstructor. eapply SNew with(x:=x); eauto. constructor. simpl. auto. }\n    {econstructor. eapply SSpec; eauto. unfoldTac. rewrite coupleUnion. rewrite Union_associative. \n     rewrite <- UnionSwap. eapply IHspec_multistep; eauto. Focus 2. rewrite <- Union_associative. \n     rewrite <- coupleUnion.  rewrite couple_swap. reflexivity. eapply spec_multi_trans. \n     eassumption. econstructor. eapply SSpec; eauto. rewrite <- Union_associative. rewrite <- coupleUnion. \n     rewrite couple_swap. constructor. }\n   }\n   {apply UnionNeqTID in x; auto. invertHyp.  copy H5. eapply specStepEmptyIVar' in H5; eauto. \n    copy H5. eapply IHspec_multistep in H5;[idtac|eauto|idtac|auto|auto|auto|auto|auto]; auto.\n    rewrite H13. unfoldTac. rewrite UnionSwap. econstructor. eapply stepReplaceEmpty. eauto. \n    eapply H15. eapply specStepChangeUnused; eauto. unfoldTac. rewrite UnionSwap; eauto. \n    eapply spec_multi_trans. eassumption. rewrite H13. unfoldTac. rewrite UnionSwap. \n    econstructor. eapply specStepChangeUnused; eauto. unfoldTac. rewrite UnionSwap. constructor. \n    rewrite H6. rewrite UnionSubtract. unfoldTac. rewrite UnionSwap; eauto. }\n  }\n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto. \nQed. \n\nTheorem smultiFullIVar : forall T' x H H' ds tid M T S sc,\n         spec_multistep H T H' T' ->\n         heap_lookup x H = Some(sfull sc ds S tid M) ->\n         exists ds', heap_lookup x H' = \n                     Some(sfull sc ds' S tid M). \nProof.\n  intros. genDeps{sc; ds; S; tid; M}. induction H0; intros.  \n  {eauto. }\n  {eapply specStepFullIVar in H; eauto. invertHyp. eauto. }\nQed. \n\nTheorem specStepEmptyIVarOr : forall x H H' H'' T T' t t' s s' ds M t0,\n                              heap_lookup x H = Some(sempty s) -> \n                              spec_step H T (tSingleton t) H' T t' ->\n                              spec_multistep H' (tUnion T t') H'' T' ->\n                              heap_lookup x H'' = Some(sfull s ds s' t0 M) ->\n                              (heap_lookup x H' = Some(sempty s) \\/\n                               exists ds', heap_lookup x H' = Some(sfull s ds' s' t0 M)). \nProof. \n  intros. inversion H1; subst; eauto. \n  {destruct (beq_nat x x0)eqn:eq. \n   {apply beq_nat_true in eq. subst. rewrite H5 in H0. inv H0. }\n   {apply beq_nat_false in eq. rewrite lookupReplaceNeq; eauto. }\n  }\n  {destruct (beq_nat x x0)eqn:eq. \n   {apply beq_nat_true in eq. subst. rewrite H5 in H0. inv H0.\n    eapply smultiFullIVar in H2; eauto. Focus 2. erewrite HeapLookupReplace; eauto. \n    invertHyp. rewrite H3 in H0. inv H0. right. exists nil. erewrite HeapLookupReplace; eauto. }\n   {apply beq_nat_false in eq. rewrite lookupReplaceNeq; eauto. }\n  }\n  { destruct (beq_nat x x0)eqn:eq. \n   {apply beq_nat_true in eq. subst. copy p. rewrite H4 in H0. inv H0. }\n   {apply beq_nat_false in eq. left. apply lookupExtendNeq; auto. }\n  }\nQed. \n\n\n\nTheorem stepReplaceSpecFull : forall H T H' t t' ds ds' x M' TID,\n                   heap_lookup x H = Some(sfull SPEC ds SPEC TID M') ->\n                   heap_lookup x H' = Some(sfull SPEC ds' SPEC TID M') ->\n                   spec_step H T t H' T t' ->\n                   spec_step (replace x (sfull COMMIT ds SPEC TID M') H) T t\n                                  (replace x (sfull COMMIT ds' SPEC TID M') H') T t'. \nProof. \n  intros. inv H2. \n  {rewrite H0 in H1. inv H1. eauto. }\n  {rewrite H0 in H1. inv H1; eauto. }\n  {varsEq x x0. rewrite H0 in H3. inv H3. erewrite HeapLookupReplace in H1; eauto. inv H1.\n   eapply SGet; eauto. erewrite HeapLookupReplace; eauto. repeat rewrite replaceOverwrite. \n   auto. eapply SGet; eauto. rewrite lookupReplaceNeq; eauto. rewrite lookupReplaceSwitch; eauto. \n   erewrite lookupReplaceNeq in H1; eauto. rewrite H0 in H1. inv H1. auto. }\n  {varsEq x x0. heapsDisagree. rewrite lookupReplaceNeq in H1; eauto. rewrite H1 in H0. \n   inv H0. eapply SPut; eauto. rewrite lookupReplaceNeq; eauto.\n   rewrite lookupReplaceSwitch; eauto. }\n  {varsEq x x0. heapsDisagree. eapply SNew; eauto. erewrite extendReplaceSwitch; eauto. \n   erewrite lookupExtendNeq in H1; eauto. inv H1. auto. }\n  {rewrite H0 in H1; inv H1; eauto. }\n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto.\nQed. \n\nTheorem smultiReplaceSpecFull : forall H T H' T' ds ds' x M' TID,\n                   heap_lookup x H = Some(sfull SPEC ds SPEC TID M') ->\n                   heap_lookup x H' = Some(sfull SPEC ds' SPEC TID M') ->\n                   spec_multistep H T H' T' ->\n                   spec_multistep (replace x (sfull COMMIT ds SPEC TID M') H) T\n                                  (replace x (sfull COMMIT ds' SPEC TID M') H') T'. \nProof.\n  intros. genDeps{ds; ds'}. induction H2; intros. \n  {rewrite H1 in H0. inv H0. constructor. }\n  {copy H. eapply specStepFullIVar in H; eauto. invertHyp. \n   eapply stepReplaceSpecFull in H3; eauto. econstructor. eassumption.\n   eapply IHspec_multistep; eauto. }\nQed. \n\nTheorem subtractSingle' : forall (A:Type) (x:A) T,\n                            In A T x ->\n                            Union A (Subtract A T x) (Single A x) = T. \nProof.\n  induction T; intros. \n  {inversion H. }\n  {inversion H; subst.\n   {simpl. destruct (classicT(x=x)). \n    {rewrite Union_commutative. simpl. auto. }\n    {simpl. rewrite IHT; eauto. inversion H. contradiction. auto. }\n   }\n   {simpl. destruct (classicT(a=x)). \n    {subst. rewrite Union_commutative. simpl. auto. }\n    {simpl. rewrite IHT; eauto. }\n   }\n  }\nQed. \n\nTheorem newSimPureStepsFull' : forall H T H' T' TID x M' E d M'' t0 ds ds' N N' N'' s2 s1',\n       eraseTrm s1' N' N'' -> \n       heap_lookup x H = Some(sfull SPEC ds SPEC t0 M'') ->\n       heap_lookup x H' = Some(sfull SPEC ds' SPEC t0 M'')-> \n       spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) ->\n       exists H'' T'',\n         spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) \n                        H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) /\\\n         spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) \n                        H' (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) /\\\n         exists ds'',\n         spec_multistep (replace x (sfull COMMIT ds SPEC t0 M'') H) T \n                        (replace x (sfull COMMIT ds'' SPEC t0 M'')H'') T'' /\\\n          heap_lookup x H'' = Some(sfull SPEC ds'' SPEC t0 M''). \nProof.\n  intros. genDeps{ds; ds'}. dependent induction H3; intros. \n  {apply UnionEqTID in x. invertHyp. inv H. destruct s1'; inv H5; try invertListNeq. \n   inv H0; try invertListNeq. rewrite H1 in H2. inv H2. do 6 econstructor. constructor. \n   eauto. }\n  {startIndCase. destructThread x1. exMid TID H10. \n   {apply UnionEqTID in x. invertHyp. inversion H1; subst. \n    {eapply IHspec_multistep in H4;[idtac|eauto|idtac|eauto|eauto|eauto|eauto]. Focus 2. auto.\n     invertHyp. econstructor. econstructor. split. econstructor. eapply SBasicStep; eauto. \n     eauto. split; auto. econstructor. split. eauto. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     econstructor. eapply SFork; eauto. eassumption. econstructor. split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     econstructor. eapply SGet; eauto. eassumption. econstructor. split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     econstructor. eapply SPut; eauto. eassumption. econstructor. split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     econstructor. eapply SNew; eauto. eassumption. econstructor. split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     econstructor. eapply SSpec; eauto. eassumption. econstructor. split. constructor. eauto. }\n   }\n   {copy H4. copy H1. eapply specStepFullIVar in H1; eauto. invertHyp.  \n    apply UnionNeqTID in x. invertHyp. copy H13. eapply IHspec_multistep in H13; eauto. \n    invertHyp. econstructor. econstructor. split. takeTStep. eauto. split; auto. \n    econstructor. split. Focus 2. eauto. rewrite H14. econstructor.\n    eapply stepReplaceSpecFull. eauto. eapply H15. eapply specStepChangeUnused; eauto. \n    eauto. rewrite H1. rewrite UnionSubtract. unfoldTac; rewrite UnionSwap; eauto. auto. }\n  }\nQed. \n\nTheorem newSimPureStepsFull : forall H T H' T' TID x M' E d M'' t0 ds' N N' N'' s2 s1',\n       eraseTrm s1' N' N'' -> \n       heap_lookup x H = Some(sempty SPEC) ->\n       heap_lookup x H' = Some(sfull SPEC ds' SPEC t0 M'')-> \n       spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) ->\n       (exists H'' T'',\n         spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) \n                        H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) /\\\n         spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) \n                        H' (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) /\\\n         spec_multistep (replace x (sempty COMMIT) H) T \n                        (replace x (sempty COMMIT)H'') T'' /\\\n          heap_lookup x H'' = Some(sempty SPEC)) \\/\n       (exists H'' T'' ds'',\n         spec_multistep H (tUnion T (tSingleton(TID,unlocked[nAct M' E d x],s2,N))) \n                        H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) /\\\n         spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked[nAct M' E d x],s2,N''))) \n                        H' (tUnion T' (tSingleton(TID,unlocked(s1'++[nAct M' E d x]),s2,N'))) /\\\n         spec_multistep (replace x (sempty COMMIT) H) T \n                        (replace x (sfull COMMIT ds'' SPEC t0 M'')H'') T'' /\\\n          heap_lookup x H'' = Some(sfull SPEC ds'' SPEC t0 M'')). \nProof.\n  intros. dependent induction H3. \n  {rewrite H1 in H2. inv H2. }\n  {startIndCase. destructThread x1. exMid H10 TID. \n   {apply UnionEqTID in x. invertHyp. inversion H4; subst.\n    {eapply IHspec_multistep in H1;[idtac|eauto|idtac|auto|auto|auto|auto]. Focus 2. auto. \n     inv H1. \n     {invertHyp. left. econstructor. econstructor. split. econstructor. eapply SBasicStep; eauto. \n      eassumption. split; auto. }\n     {right. invertHyp. econstructor. econstructor. econstructor. split. econstructor.\n      eapply SBasicStep; eauto. eauto. eauto. }\n    }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     constructor. split. simpl in *. econstructor. eapply SFork; eauto. eassumption. \n     split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     constructor. split. simpl in *. econstructor. eapply SGet; eauto. eassumption. \n     split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     constructor. split. simpl in *. econstructor. eapply SPut; eauto. eassumption. \n     split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     constructor. split. simpl in *. econstructor. eapply SNew; eauto. eassumption. \n     split. constructor. eauto. }\n    {copy H3. nonEmptyStackTac H3. invertHyp. apply eraseTrmApp in H0. inv H0. do 4 econstructor. \n     constructor. split. simpl in *. econstructor. eapply SSpec; eauto. eassumption. \n     split. constructor. eauto. }\n   }\n   {copy H4. eapply specStepEmptyIVarOr in H4; eauto. inv H4. \n    {copy H12. eapply IHspec_multistep in H12; eauto. inv H12. \n     {apply UnionNeqTID in x. invertHyp. left. econstructor. econstructor. \n      split. takeTStep. eassumption. split. assumption. split. rewrite H17. econstructor. \n      eapply stepReplaceEmpty. auto. eapply H4. eapply specStepChangeUnused. eauto.\n      eauto. eauto. eauto. }\n     {apply UnionNeqTID in x; auto. invertHyp. right. econstructor. econstructor. econstructor. \n      split. takeTStep. eauto. split; eauto. split. Focus 2. eauto. rewrite H17. clear H15 H17.\n      inversion H5; subst.\n      {econstructor. eapply SBasicStep; eauto. auto. }\n      {econstructor. eapply SFork; eauto. eauto. }\n      {varsEq x x0. heapsDisagree. econstructor. eapply SGet; eauto. \n       rewrite lookupReplaceNeq; eauto. rewrite lookupReplaceSwitch; eauto. }\n      {varsEq x x0. erewrite HeapLookupReplace in H4; eauto. inv H4. econstructor. \n       eapply SPut; eauto. rewrite lookupReplaceNeq; eauto. rewrite lookupReplaceSwitch; eauto. }\n      {varsEq x x0. heapsDisagree. econstructor. eapply SNew; eauto.\n       erewrite extendReplaceSwitch; eauto. }\n      {econstructor. eapply SSpec; eauto. eauto. }\n     }\n     {proveUnionEq x. rewrite UnionSubtract. rewrite UnionSwap; auto. \n      apply UnionNeqTID in x. invertHyp. rewrite H14. solveSet. auto. }\n    }\n    {invertHyp. apply UnionNeqTID in x. invertHyp. rewrite H12 in H3. unfoldTac. \n     rewrite UnionSwap in H3. eapply newSimPureStepsFull' in H3. invertHyp. \n     right. econstructor. econstructor. econstructor. split. takeTStep.\n     rewrite UnionSwap. rewrite subtractSingle'. rewrite H12.\n     rewrite UnionSwap. eassumption. rewrite H12. solveSet. split; auto. \n     split. Focus 2. eassumption. rewrite H13. clear H12 H13.\n     inv H5; try solve[heapsDisagree].  \n     {varsEq x4 x0. heapsDisagree. erewrite lookupReplaceNeq in H4; eauto. \n      heapsDisagree. }\n     {varsEq x4 x0. erewrite HeapLookupReplace in H4; eauto. inv H4. \n      econstructor. eapply SPut; eauto. erewrite HeapLookupReplace; eauto. \n      rewrite replaceOverwrite. rewrite replaceOverwrite in H16.\n      apply UnionNeqTID in H6; auto. invertHyp. rewrite H4. \n      rewrite UnionSubtract. eauto. rewrite lookupReplaceNeq in H4; auto. \n      heapsDisagree. }\n     {varsEq x4 x0. heapsDisagree. erewrite lookupExtendNeq in H4; eauto. inv H4. }\n     {eauto. }\n     {eauto. }\n     {eauto. }\n     {auto. }\n    }\n   }\n  }\n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto. \nQed. \n\nTheorem smultiReplaceEmptyFull : forall H T H' T' ds' x M' TID,\n                   heap_lookup x H = Some(sempty SPEC) ->\n                   heap_lookup x H' = Some(sfull SPEC ds' SPEC TID M') ->\n                   spec_multistep H T H' T' ->\n                   spec_multistep (replace x (sempty COMMIT) H) T\n                                  (replace x (sfull COMMIT ds' SPEC TID M') H') T'. \nProof.\n  intros. genDeps{ds'}. induction H2; intros.  \n  {rewrite H1 in H0. inv H0. }\n  {copy H. apply specStepSingleton in H. invertHyp. copy H3. \n   eapply specStepEmptyIVarOr in H3; eauto. inv H3. \n   {econstructor. eapply stepReplaceEmpty; eauto. eauto. }\n   {invertHyp. inversion H; subst; try solve[heapsDisagree]. \n    {varsEq x2 x. heapsDisagree. rewrite lookupReplaceNeq in H3; eauto. \n     heapsDisagree. } \n    {varsEq x2 x. rewrite H5 in H0. inv H0. econstructor. eapply SPut with(d:=d);eauto. \n     erewrite HeapLookupReplace; eauto. rewrite replaceOverwrite. \n     copy H2. eapply smultiFullIVar in H2. Focus 2. erewrite HeapLookupReplace; eauto. \n     invertHyp. rewrite H4 in H1. inv H1. lookupTac. eapply smultiReplaceSpecFull in H0. \n     Focus 2. eassumption. Focus 2. eassumption. rewrite replaceOverwrite in H0.\n     eassumption. rewrite lookupReplaceNeq in H3; eauto. heapsDisagree. }\n    {varsEq x2 x. heapsDisagree. erewrite lookupExtendNeq in H3; eauto. inv H3. }\n   }\n  }\nQed. \n\nTheorem newSimActionStepsFullFull : forall H T H' T' TID x ds ds' t0 M'' M' E d N N' H'' T'' N'' s2 s1 s1' a,\n       eraseTrm (s1'++[a]) N' N'' ->\n       heap_lookup x H = Some(sfull SPEC ds SPEC t0 M'') ->       \n       heap_lookup x H' = Some(sfull SPEC ds' SPEC t0 M'') -> \n       spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked [nAct M' E d x],s2,N'')))\n                      H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) ->\n       spec_multistep H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[a]++[nAct M' E d x]),s2,N'))) ->\n       spec_multistep (replace x (sfull COMMIT ds SPEC t0 M'') H)\n                      (tUnion T (tSingleton(TID,unlocked s1,nAct M' E d x::s2,N))) \n                      (replace x (sfull COMMIT ds' SPEC t0 M'') H')\n                      (tUnion T' (tSingleton(TID,unlocked (s1'++[a]), nAct M' E d x::s2,N'))).\nProof.\n  intros. genDeps{ds; ds'}. dependent induction H4; intros. \n  {apply UnionEqTID in x. invertHyp. inv H. \n   replace [a; nAct M' E d x0] with ([a]++[nAct M' E d x0]) in H6; auto. \n   rewrite app_assoc in H6. apply app_inj_tail in H6. invertHyp. inv H5. rewrite H1 in H2. \n   inv H2. constructor. }\n  {startIndCase. destructThread x1. exMid TID H11. \n   {apply UnionEqTID in x. invertHyp. inversion H1; subst. \n    {copy H3. eapply stackNonNil in H3. destruct s1. exfalso. apply H3. auto. \n     econstructor. eapply SBasicStep; eauto. constructor. \n     eapply IHspec_multistep; eauto.  eapply spec_multi_trans. eassumption. \n     econstructor. eapply SBasicStep; eauto. constructor. eauto. intros c. subst. \n     apply eraseTrmApp in H0. inv H0; inv H17; falseDecomp. }\n    {econstructor. eapply SFork; eauto. simpl. unfoldTac. rewrite coupleUnion. \n     rewrite Union_associative. rewrite UnionSwap. eapply IHspec_multistep; eauto. \n     Focus 2. rewrite <- Union_associative. rewrite <- coupleUnion. \n     rewrite couple_swap. unfold numForks. simpl. simpl. eauto. \n     rewrite numForksDistribute. simpl. rewrite <- plus_assoc. \n     rewrite <- plus_comm. simpl. rewrite plus_comm. reflexivity. \n     eapply spec_multi_trans. eassumption. econstructor. eapply SFork; eauto. \n     rewrite <- Union_associative. rewrite <- coupleUnion. rewrite couple_swap. \n     simpl. rewrite numForksDistribute. simpl. rewrite <- plus_assoc. \n     rewrite plus_comm. simpl. rewrite plus_comm. constructor. }\n    {varsEq x0 x. \n     {rewrite H17 in H5. inv H5. econstructor. eapply SGet; eauto. \n      erewrite HeapLookupReplace; eauto. rewrite replaceOverwrite. lookupTac.\n      eapply IHspec_multistep in H5; eauto. rewrite replaceOverwrite in H5. eauto. \n      eapply spec_multi_trans. eauto. econstructor. eapply SGet; eauto. constructor.\n      simpl. auto. }\n     {lookupTac. eapply IHspec_multistep in H8; eauto. econstructor. \n      eapply SGet; eauto. rewrite lookupReplaceNeq; eauto. \n      rewrite lookupReplaceSwitch. eassumption. auto. eapply spec_multi_trans. \n      eassumption. econstructor. eapply SGet; eauto. simpl. constructor. simpl.\n      auto. }\n    }\n    {varsEq x0 x. heapsDisagree. lookupTac. eapply IHspec_multistep in H8; eauto. \n     econstructor. eapply SPut; eauto. rewrite lookupReplaceNeq; eauto. \n     rewrite lookupReplaceSwitch; eauto. eapply spec_multi_trans. eassumption. \n     econstructor. eapply SPut; eauto. constructor. simpl. auto. }\n    {varsEq x0 x. heapsDisagree. lookupTac. eapply IHspec_multistep in H8; eauto. \n     econstructor. eapply SNew; eauto. erewrite extendReplaceSwitch; eauto.\n     eapply spec_multi_trans. eassumption. econstructor. eapply SNew; eauto. \n     constructor. simpl; auto. }\n    {econstructor. eapply SSpec; eauto. unfoldTac. rewrite coupleUnion. \n     rewrite Union_associative. rewrite <-UnionSwap. eapply IHspec_multistep; eauto. \n     Focus 2. rewrite <- Union_associative. rewrite <- coupleUnion.  \n     rewrite couple_swap. reflexivity. eapply spec_multi_trans. eassumption. \n     econstructor. eapply SSpec; eauto. rewrite <- Union_associative. \n     rewrite <- coupleUnion. rewrite couple_swap. constructor. }\n   }\n   {apply UnionNeqTID in H7; auto. invertHyp. copy H1. copy H7. \n    eapply specStepFullIVar in H7; eauto. invertHyp.\n    eapply stepReplaceSpecFull in H1; eauto. takeTStep.  \n    eapply IHspec_multistep; eauto. eapply spec_multi_trans. eassumption. rewrite H13.\n    rewrite UnionSwap. econstructor. eapply specStepChangeUnused. eauto. unfoldTac. \n    rewrite UnionSwap. constructor. proveUnionEq x. rewrite UnionSubtract. \n    unfoldTac. rewrite UnionSwap. auto. rewrite H13. solveSet. }\n  } \n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto.\nQed. \n\nTheorem newSimActionStepsEmptyFull : forall H T H' T' TID x ds' t0 M'' M' E d N N' H'' T'' N'' s2 s1 s1' a,\n       eraseTrm (s1'++[a]) N' N'' ->\n       heap_lookup x H = Some(sempty SPEC) ->       \n       heap_lookup x H' = Some(sfull SPEC ds' SPEC t0 M'') -> \n       spec_multistep H'' (tUnion T'' (tSingleton(TID,unlocked [nAct M' E d x],s2,N'')))\n                      H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) ->\n       spec_multistep H (tUnion T (tSingleton(TID,unlocked(s1++[nAct M' E d x]),s2,N))) H'\n                      (tUnion T' (tSingleton(TID,unlocked(s1'++[a]++[nAct M' E d x]),s2,N'))) ->\n       spec_multistep (replace x (sempty COMMIT) H)\n                      (tUnion T (tSingleton(TID,unlocked s1,nAct M' E d x::s2,N))) \n                      (replace x (sfull COMMIT ds' SPEC t0 M'') H')\n                      (tUnion T' (tSingleton(TID,unlocked (s1'++[a]), nAct M' E d x::s2,N'))).\nProof.\n  intros. genDeps{ds'}. dependent induction H4; intros. \n  {rewrite H1 in H2. inv H2. }\n  {startIndCase. destructThread x1. exMid TID H11. \n   {apply UnionEqTID in x. invertHyp. copy H1. copy H2. \n    eapply specStepEmptyIVarOr in H8; eauto. inv H8.\n    {inversion H2; subst.\n     {copy H3. eapply stackNonNil in H3. destruct s1. exfalso. apply H3. auto. \n      econstructor. eapply SBasicStep; eauto. constructor. \n      eapply IHspec_multistep; eauto. eapply spec_multi_trans. eassumption. \n      econstructor. eapply SBasicStep; eauto. constructor. eauto. intros c. subst. \n      apply eraseTrmApp in H0. inv H0; inv H19; falseDecomp. }\n     {econstructor. eapply SFork; eauto. simpl. unfoldTac. rewrite coupleUnion. \n      rewrite Union_associative. rewrite UnionSwap. eapply IHspec_multistep; eauto. \n      Focus 2. rewrite <- Union_associative. rewrite <- coupleUnion. \n      rewrite couple_swap. unfold numForks. simpl. simpl. eauto. \n      rewrite numForksDistribute. simpl. rewrite <- plus_assoc. rewrite <- plus_comm. \n      simpl. rewrite plus_comm. reflexivity. eapply spec_multi_trans. \n      eassumption. econstructor. eapply SFork; eauto. rewrite <- Union_associative. \n      rewrite <- coupleUnion. rewrite couple_swap. simpl. rewrite numForksDistribute. \n      simpl. rewrite <- plus_assoc. rewrite plus_comm. simpl. rewrite plus_comm. \n      constructor. }\n     {varsEq x0 x. heapsDisagree. econstructor. eapply SGet; eauto. \n      rewrite lookupReplaceNeq; eauto. lookupTac.\n      eapply IHspec_multistep in H10; eauto. rewrite lookupReplaceSwitch; auto. \n      eassumption. eapply spec_multi_trans. eassumption. econstructor.\n      eapply SGet; eauto. simpl. constructor. reflexivity. } \n     {varsEq x0 x. erewrite HeapLookupReplace in H9; eauto. inv H9. econstructor. \n      eapply SPut; eauto. rewrite lookupReplaceNeq; eauto. lookupTac.\n      eapply IHspec_multistep in H10; eauto. rewrite lookupReplaceSwitch; auto. \n      eassumption. eapply spec_multi_trans. eassumption. econstructor. \n      eapply SPut; eauto. simpl. constructor. reflexivity. }\n     {varsEq x0 x. heapsDisagree. econstructor. eapply SNew; eauto. lookupTac.\n      eapply IHspec_multistep in H10; eauto. erewrite extendReplaceSwitch; eauto. \n      eapply spec_multi_trans. eassumption. econstructor. eapply SNew; eauto. simpl. \n      constructor. reflexivity. }\n    {econstructor. eapply SSpec; eauto. unfoldTac. rewrite coupleUnion. \n     rewrite Union_associative. rewrite <- UnionSwap. eapply IHspec_multistep; eauto. \n     Focus 2. rewrite <- Union_associative. rewrite <- coupleUnion.  \n     rewrite couple_swap. reflexivity. eapply spec_multi_trans. eassumption. \n     econstructor. eapply SSpec; eauto. rewrite <- Union_associative. \n     rewrite <- coupleUnion. rewrite couple_swap. constructor. }\n    }\n    {invertHyp. inversion H2; subst; try solve[heapsDisagree]. \n     {varsEq x1 x0. erewrite HeapLookupReplace in H8; eauto. inv H8. heapsDisagree. \n      rewrite lookupReplaceNeq in H8; eauto. heapsDisagree. }\n     {varsEq x1 x0. erewrite HeapLookupReplace in H8; eauto. inv H8. simpl in *. \n      rewrite app_comm_cons in H4. eapply newSimActionStepsFullFull in H4; eauto. \n      econstructor. eapply SPut; eauto. erewrite HeapLookupReplace; eauto. \n      rewrite replaceOverwrite. rewrite replaceOverwrite in H4. eassumption. \n      erewrite HeapLookupReplace; eauto. eapply spec_multi_trans. eassumption. \n      econstructor. eapply SPut; eauto. constructor. \n      rewrite lookupReplaceNeq in H8; eauto. heapsDisagree. }\n     {varsEq x1 x0. heapsDisagree. erewrite lookupExtendNeq in H8; eauto. inv H8. }\n    }\n   }\n   {apply UnionNeqTID in x; auto. copy H1. copy H2.\n    eapply specStepEmptyIVarOr in H2; eauto. inv H2. \n    {copy H14.  eapply IHspec_multistep in H14; eauto. invertHyp. takeTStep.\n     econstructor. eapply specStepChangeUnused. eapply stepReplaceEmpty. \n     eauto. eapply H2. eauto. unfoldTac. rewrite UnionSwap. eassumption. \n     eapply spec_multi_trans. eassumption. invertHyp. takeTStep. constructor. \n     invertHyp. rewrite H15. rewrite UnionSubtract. unfoldTac. rewrite UnionSwap. \n     auto. }\n    {inversion H13; subst; try solve[invertHyp; heapsDisagree]. \n     {varsEq x1 x0; invertHyp. heapsDisagree. rewrite lookupReplaceNeq in H15; auto. \n      heapsDisagree. }\n     {varsEq x1 x0. inv H14. erewrite HeapLookupReplace in H2; eauto. inv H2. \n      invertHyp. takeTStep. rewrite H2 in H4. rewrite UnionSwap in H4.\n      eapply newSimActionStepsFullFull in H4; eauto. Focus 2.  \n      erewrite HeapLookupReplace; eauto. Focus 2. eapply spec_multi_trans.\n      eassumption. rewrite H11. rewrite UnionSwap. econstructor. eapply SPut; eauto. \n      rewrite UnionSubtract. unfoldTac. rewrite UnionSwap. constructor. \n      econstructor. eapply SPut; eauto. erewrite HeapLookupReplace; eauto. \n      rewrite replaceOverwrite. rewrite replaceOverwrite in H4. rewrite H2. \n      rewrite UnionSubtract. unfoldTac. rewrite UnionSwap. eassumption. \n      invertHyp. rewrite lookupReplaceNeq in H15; eauto. heapsDisagree. }\n     {varsEq x1 x0. heapsDisagree. invertHyp. erewrite lookupExtendNeq in H15; eauto. \n      inv H15. }\n    }\n   }\n  }\n  Grab Existential Variables. rewrite lookupReplaceNeq; eauto. \nQed. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/newest/newIndependence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.18520357106085533}}
{"text": "From refinedc.typing Require Import typing.\nFrom refinedc.project.learning.src.solswitch Require Import generated_code.\nFrom refinedc.project.learning.src.solswitch Require Import generated_spec.\nSet Default Proof Using \"Type\".\n\n(* Generated from [src/solswitch.c]. *)\nSection proof_SML_isSafetyVoltageCondExists.\n  Context `{!typeG \u03a3} `{!globalG \u03a3}.\n\n  (* Typing proof for [SML_isSafetyVoltageCondExists]. *)\n  Lemma type_SML_isSafetyVoltageCondExists (global_curTime : loc) :\n    global_locs !! \"curTime\" = Some global_curTime \u2192\n    global_initialized_types !! \"curTime\" = Some (GT nat (\u03bb 'global_time, (global_time @ (int (u16))) : type)%I) \u2192\n    \u22a2 typed_function (impl_SML_isSafetyVoltageCondExists global_curTime) type_of_SML_isSafetyVoltageCondExists.\n  Proof.\n    Open Scope printing_sugar.\n    start_function \"SML_isSafetyVoltageCondExists\" ([[[[[state msg] conversionEnded] voltage] p] global_time]) => arg_solenoidSwitchingParams_ptr arg_isConversionEnded local_uniqueSafetyVoltage.\n    prepare_parameters (state msg conversionEnded voltage p global_time).\n    split_blocks ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)) ((\n      \u2205\n    )%I : gmap label (iProp \u03a3)).\n    - repeat liRStep; liShow.\n      all: print_typesystem_goal \"SML_isSafetyVoltageCondExists\" \"#0\".\n    Unshelve. all: li_unshelve_sidecond; sidecond_hook; prepare_sideconditions; normalize_and_simpl_goal; try solve_goal; unsolved_sidecond_hook.\n    all: try destruct state; tauto.\n    all: print_sidecondition_goal \"SML_isSafetyVoltageCondExists\".\n    Unshelve. all: try done; try apply: inhabitant; print_remaining_shelved_goal \"SML_isSafetyVoltageCondExists\".\n  Qed.\nEnd proof_SML_isSafetyVoltageCondExists.\n", "meta": {"author": "afifit", "repo": "circuit_verif", "sha": "5427a1223c5ea7e4a52f909489c45f8e51c4be54", "save_path": "github-repos/coq/afifit-circuit_verif", "path": "github-repos/coq/afifit-circuit_verif/circuit_verif-5427a1223c5ea7e4a52f909489c45f8e51c4be54/src/proofs/solswitch/generated_proof_SML_isSafetyVoltageCondExists.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.18520356229072824}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import XOmega.\n\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import Conventions.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\n\nRequire Import AbstractDataType.\nRequire Import TSysCall.\nRequire Import I64Layer.\nRequire Import LoadStoreSem2.\nRequire Import MakeProgram.\n\nRequire Import SecurityCommon.\nRequire Import ProofIrrelevance.\n\n(* This file proves that some new state invariants are preserved by each step \n   of the tsyscall layer. Note that we do not specify whether these invariants hold\n   on the initial state here, we only prove that they are preserved. The invariants are:\n   1.) we are in host mode (this version of mCertiKOS does not support virtualization)\n   2.) the return address pseudoregister RA in each process's saved register context\n       always points to the code entry point of the proc_start_user primitive\n   3.) the usermode predicate, which consists of three interdependent properties that\n       essentially say that we are always in user mode. The only exceptions to being\n       in user mode are when the special kernel process 0 is executing (initialization\n       setup only), or when we just called yield and are about to re-enter user mode in\n       a single step. The three properties are:\n       a.) if we are in kernel mode, then the instruction pointer register must be \n           pointing to the code entry point of the proc_start_user primitive\n       b.) the currently-running process is not process 0\n       c.) the ready queue is nonempty, and process 0 is never on the ready queue\n   Paper Reference: Section 5 *)\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Local Instance : ExternalCallsOps (mwd (cdata RData)) := \n    CompatExternalCalls.compatlayer_extcall_ops tsyscall_layer.\n  Local Instance : LayerConfigurationOps := compatlayer_configuration_ops tsyscall_layer.\n\n  Section IHOST_INV.\n\n    Lemma exec_loadex_ihost_inv {F V} :\n      forall ge chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd,\n        exec_loadex(F:=F)(V:=V) ge chunk (m,d) a rs rd = Next rs' (m',d') ->\n        ihost d = true -> ihost d' = true.\n    Proof.\n      unfold exec_loadex, exec_loadex2; intros; subdestruct; rename H into Hexec.\n      - unfold Asm.exec_load in Hexec; subdestruct; inv Hexec; auto.\n      - unfold HostAccess2.exec_host_load2 in Hexec; subdestruct; inv Hexec; auto.\n        unfold PageFault.exec_pagefault in *; subdestruct; inv H1; auto.\n      - unfold Asm.exec_load in Hexec; subdestruct; inv Hexec; auto.\n      - simpl in *; rewrites.\n      - simpl in *; rewrites.\n    Qed.\n\n    Lemma exec_storeex_ihost_inv {F V} :\n      forall ge chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd rds,\n        exec_storeex(F:=F)(V:=V) ge chunk (m,d) a rs rd rds = Next rs' (m',d') ->\n        ihost d = true -> ihost d' = true.\n    Proof.\n      unfold exec_storeex, exec_storeex2; intros; subdestruct; rename H into Hexec.\n      - unfold Asm.exec_store in Hexec; subdestruct; inv Hexec.\n        unfold Mem.storev in *; unfold_lift; subdestruct; inv Hdestruct3; auto.\n      - unfold HostAccess2.exec_host_store2 in Hexec; subdestruct.\n        unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in Hexec; subdestruct; inv Hexec; auto.\n        unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in Hexec; subdestruct; inv Hexec; auto.\n        unfold PageFault.exec_pagefault in Hexec; subdestruct; inv Hexec; auto.\n      - unfold Asm.exec_store in Hexec; subdestruct; inv Hexec.\n        unfold Mem.storev in *; unfold_lift; subdestruct; inv Hdestruct3; auto.\n      - simpl in *; rewrites.\n      - simpl in *; rewrites.\n    Qed.\n\n    Lemma proc_start_user_host_inv:\n      forall d d' rs,\n        proc_start_user_spec d = Some (d', rs) ->\n        ihost d' = true.\n    Proof.\n      unfold proc_start_user_spec. intros. subdestruct.\n      inv H. trivial.\n    Qed.\n\n    Lemma ihost_inv :\n      forall ge rs rs' (m m' : mem) (d d' : cdata RData) t,\n        LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) ->         \n        ihost d = true -> ihost d' = true.\n    Proof.\n      intros.\n      eapply (step_P (fun d d' : cdata RData => \n                        ihost d = true -> ihost d' = true)) in H; eauto.\n      - simpl; intros; eapply exec_loadex_ihost_inv; eauto.\n      - simpl; intros; eapply exec_storeex_ihost_inv; eauto.\n      - (* Case 2: EF_external *)\n        intros. inv H1.\n        destruct H3 as [\u03c3 [Hl [s [\u03c3' [Hmatch [Hsem [? [? ?]]]]]]]]; subst.\n        inv_layer Hl; inv Hsem; try assumption; gensem_simpl.\n        (*+ functional inversion H3. trivial.*)\n        + unfold proc_init_spec, ret in *; subdestruct; inv_somes; auto.\n      - (* Case 3: prim_call step *)\n        intros. destruct H1 as [x [sg [\u03c3 [Hef [Hl Hsem]]]]]; subst.\n        inv_layer Hl; inv Hsem; simpl in *.\n        {\n          (* dispatch *)\n          inv H4. inv H9.\n          eapply proc_start_user_host_inv.\n          eapply H4.\n        }\n        {\n          (* pagefault *)\n          inv H4. inv H10.\n          eapply proc_start_user_host_inv.\n          eapply H4.\n        }\n        {\n          (* yield *)\n          inv H4.\n          inv_spec; inv_somes; auto.\n        }\n        {\n          (* proc_start_user *)\n          inv H4.\n          eapply proc_start_user_host_inv; eauto.\n        }\n    Qed.\n\n  End IHOST_INV.\n\n  Ltac fun_inv_spec :=\n    match goal with\n      | H: _ = Some ?a |- context[?a] =>\n        try (functional inversion H; clear H)\n    end.\n\n  Section WITHIMPL.\n\n    Context `{make_program_ops: !MakeProgramOps function Ctypes.type fundef unit}.\n    Context `{make_program_prf: !MakeProgram function Ctypes.type fundef unit}.\n\n    Variables (b : block).\n\n    Definition RA_startuser d :=\n      forall id,\n        id <> 0 -> cused (ZMap.get id (AC d)) = true ->\n        ZMap.get id (kctxt d) RA = Vptr b Int.zero.\n\n    Lemma exec_loadex_RA_startuser_inv :\n      forall {F V} ge chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd,\n        exec_loadex (F:=F) (V:=V) ge chunk (m,d) a rs rd = Next rs' (m',d') ->\n        ihost d = true -> RA_startuser d -> RA_startuser d'.\n    Proof.\n      unfold exec_loadex, exec_loadex2; intros; subdestruct; rename H into Hexec.\n      - unfold Asm.exec_load in Hexec; subdestruct; inv Hexec; auto.\n      - unfold HostAccess2.exec_host_load2 in Hexec; subdestruct; inv Hexec; auto.\n        unfold PageFault.exec_pagefault in *; subdestruct; inv H2; auto.\n      - unfold Asm.exec_load in Hexec; subdestruct; inv Hexec; auto.\n      - simpl in *; rewrites.\n      - simpl in *; rewrites.\n    Qed.\n\n    Lemma exec_storeex_RA_startuser_inv:\n      forall {F V} ge chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd rds,\n        exec_storeex(F:=F)(V:=V) ge chunk (m,d) a rs rd rds = Next rs' (m',d') ->\n        ihost d = true -> RA_startuser d -> RA_startuser d'.\n    Proof.\n      unfold exec_storeex, exec_storeex2; intros; subdestruct; rename H into Hexec.\n      - unfold Asm.exec_store in Hexec; subdestruct; inv Hexec.\n        unfold Mem.storev in *; unfold_lift; subdestruct; inv Hdestruct3; auto.\n      - unfold HostAccess2.exec_host_store2 in Hexec; subdestruct.\n        unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in Hexec; subdestruct; inv Hexec; auto.\n        unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in Hexec; subdestruct; inv Hexec; auto.\n        unfold PageFault.exec_pagefault in Hexec; subdestruct; inv Hexec; auto.\n      - unfold Asm.exec_store in Hexec; subdestruct; inv Hexec.\n        unfold Mem.storev in *; unfold_lift; subdestruct; inv Hdestruct3; auto.\n      - simpl in *; rewrites.\n      - simpl in *; rewrites.\n    Qed.\n\n    Variables (s : stencil) (M : module) (ge : genv).\n\n    Hypothesis (Hmake : make_globalenv s M tsyscall_layer = OK ge).\n    Hypothesis (Hpsu : Genv.find_symbol ge proc_start_user = Some b).\n\n    (* needed so that the inv_spec tactic doesn't interpret find_symbol as a spec *)\n    Opaque Genv.find_symbol find_symbol.\n\n    Let local_stencil_matches : stencil_matches s ge.\n    Proof.\n      eapply make_globalenv_stencil_matches; eauto.\n    Qed.\n\n    Let local_find_symbol : find_symbol s proc_start_user = Some b.\n    Proof.\n      erewrite <- stencil_matches_symbols; eauto.\n    Qed.\n\n    Section YIELD_RA_INV.\n    \n      Lemma trap_into_kernel_RA_startuser_inv :\n      forall id s' m' rs d d' vargs sg0 b0 v0\n             v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16,\n        trap_into_kernel_spec id s' m' rs d d' vargs sg0 b0 v0\n          v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 -> \n        RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros until v16; intro Hspec; inv Hspec.\n        decompose [and] H0; inv_spec; inv_somes; auto.\n      Qed.\n\n      Lemma ptInsertPTE0_RA_startuser_inv:\n        forall i vadr padr pm d d',\n          ptInsertPTE0_spec i vadr padr pm d = Some d' ->\n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros; inv_spec; inv_somes; simpl; auto. \n      Qed.\n\n      Lemma ptAllocPDE0_RA_startuser_inv:\n        forall i1 i2 n d d',\n          ptAllocPDE0_spec i1 i2 d = Some (d', n) ->\n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros. functional inversion H; subst; auto; simpl;clear H.\n        unfold RA_startuser in *; simpl in *. intros.\n        destruct (zeq id i1); subst.\n        - rewrite ZMap.gss in H1. subst cur c. simpl in *.\n          eapply H0; eauto.\n        - rewrite ZMap.gso in H1; eauto.\n      Qed.\n\n      Lemma ptInsert0_RA_startuser_inv:\n        forall i1 i2 b i3 d d' v,\n          ptInsert0_spec i1 i2 b i3 d = Some (d', v) ->\n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros; inv_spec; inv_somes; clear Hdestruct4.\n        - eapply ptInsertPTE0_RA_startuser_inv; eauto.\n        - eapply ptAllocPDE0_RA_startuser_inv; eauto.\n        - eapply ptInsertPTE0_RA_startuser_inv; eauto.\n          eapply ptAllocPDE0_RA_startuser_inv; eauto.\n      Qed.\n\n      Lemma palloc_RA_startuser_inv:\n        forall i r d d',\n          alloc_spec i d = Some (d', r) ->\n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros; inv_spec; inv_somes; auto; simpl.\n        unfold RA_startuser in *; simpl in *. intros.\n        destruct (zeq id i); subst.\n        - rewrite ZMap.gss in H1. simpl in *.\n          eapply H0; eauto.\n        - rewrite ZMap.gso in H1; eauto.\n      Qed.\n\n      Lemma ptResv2_RA_startuser_inv :\n        forall i2 i3 i5 i6 n d d',\n          ptResv2_spec 1 i2 i3 2 i5 i6 d = Some (d', n) ->\n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros. functional inversion H; subst; clear H; trivial.\n        - eapply ptInsert0_RA_startuser_inv; eauto.\n          eapply palloc_RA_startuser_inv; eauto.\n        - eapply ptInsert0_RA_startuser_inv; eauto.\n          eapply ptInsert0_RA_startuser_inv; eauto.\n          eapply palloc_RA_startuser_inv; eauto.\n      Qed.\n\n      Lemma sys_dispatch_RA_startuser_inv :\n        forall s m d d',\n          stencil_matches s ge ->\n          sys_dispatch_c_spec s m d = Some d' -> \n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros; inv_spec; fun_inv_spec;\n        inv_somes; auto.       \n        - repeat inv_spec;\n          inv_somes; simpl in *; auto;\n          unfold RA_startuser in *; simpl in *.\n          intros id Hn0 Hused; zmap_solve.\n          + rewrite Pregmap.gss.\n            rewrite (stencil_matches_unique _ _ _ H local_stencil_matches) in Hdestruct14. \n            rewrites; reflexivity.\n          + unfold update_cchildren, update_cusage in Hused; simpl in Hused.\n            zmap_solve; subst; auto.\n\n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n        - unfold RA_startuser in *.\n          functional inversion H2; subst. clear H2.\n          subst uctx uctx'. simpl.\n          functional inversion H7; subst; simpl in *. clear H7.\n          subst uctx uctx'.\n          functional inversion H6; subst; simpl in *; auto; clear H6.\n          eapply ptResv2_RA_startuser_inv; eauto.\n          eapply ptResv2_RA_startuser_inv; eauto.\n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n      Qed.\n\n      Lemma ptfault_resv_RA_startuser_inv :\n        forall v d d',\n          ptfault_resv_spec v d = Some d' -> \n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros v d d' Hspec.\n        inv_spec; inv_somes; auto.\n        inv_spec; inv_somes; simpl; eauto.\n        intros.\n        unfold RA_startuser in *; simpl in *.\n        eapply ptInsert0_RA_startuser_inv; eauto.\n        eapply palloc_RA_startuser_inv; eauto.\n      Qed.\n\n      Lemma proc_start_user_RA_startuser_inv :\n        forall rs d d',\n          proc_start_user_spec d = Some (d', rs) -> \n          RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros; inv_spec; inv_somes; auto.\n      Qed.\n\n      Ltac solve_RA_startuser_inv :=\n        repeat match goal with\n        | [ H : appcontext [syscall_spec] |- _ ] => inv H\n        | [ H : proc_start_user_spec _ = _ /\\ _ |- _ ] => destruct H\n        | [ H : appcontext [trap_into_kernel_spec _ _ _ _ _ ?d] |- RA_startuser ?d ] => \n          eapply trap_into_kernel_RA_startuser_inv; eauto\n        | [ H : appcontext [proc_start_user_spec _ = Some (?d,_)] |- RA_startuser ?d ] => \n          eapply proc_start_user_RA_startuser_inv; eauto\n        | [ H : appcontext [sys_dispatch_c_spec _ _ _ = Some ?d] |- RA_startuser ?d ] => \n          eapply sys_dispatch_RA_startuser_inv; eauto\n        | [ H : appcontext [ptfault_resv_spec _ _ = Some ?d] |- RA_startuser ?d ] => \n          eapply ptfault_resv_RA_startuser_inv; eauto      \n        end.\n\n      Lemma RA_startuser_inv :\n        forall rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) ->         \n          ihost d = true -> RA_startuser d -> RA_startuser d'.\n      Proof.\n        intros.\n        eapply (step_P (fun d d' : cdata RData => \n                          ihost d = true -> RA_startuser d -> RA_startuser d')) in H; eauto.\n        - simpl; intros; eapply exec_loadex_RA_startuser_inv; eauto.\n        - simpl; intros; eapply exec_storeex_RA_startuser_inv; eauto.\n        - (* Case 2: EF_external *)\n          intros. inv H2.\n          destruct H5 as [\u03c3 [Hl [s' [\u03c3' [Hmatch [Hsem [? [? ?]]]]]]]]; subst.\n          inv_layer Hl; inv Hsem; try assumption; gensem_simpl.\n          (*+ functional inversion H5. trivial.*)\n          + unfold proc_init_spec, ret in *; subdestruct; inv_somes.\n            unfold RA_startuser; simpl; intros id Hn0 Hused.\n            unfold real_AC in Hused; zmap_solve; inv Hused.\n        - (* Case 3: prim_call step *) \n          intros. destruct H2 as [x [sg [\u03c3 [Hef [Hl Hsem]]]]]; subst.\n          inv_layer Hl; inv Hsem; simpl in *; inv H6; solve_RA_startuser_inv.\n          unfold thread_yield_spec in *; subdestruct; inv_somes; unfold RA_startuser; simpl; intros; zmap_solve.\n          {\n            rewrite Pregmap.gss; f_equal.\n            assert (Heq:= stencil_matches_unique _ _ _ local_stencil_matches H5); congruence.\n          }\n          {\n            eapply trap_into_kernel_RA_startuser_inv in H6; eauto.\n          }\n          {\n            rewrite Pregmap.gss; f_equal.\n            assert (Heq:= stencil_matches_unique _ _ _ local_stencil_matches H5); congruence.\n          }\n          {\n            eapply trap_into_kernel_RA_startuser_inv in H6; eauto.\n          }\n      Qed.\n\n    End YIELD_RA_INV.\n\n    Section USERMODE_INV.\n\n      Notation abq_inv d := (forall l,\n                              ZMap.get num_id (abq d) = AbQValid l ->\n                              l <> nil /\\ forall id, In id l -> 0 < id).\n\n      Record usermode (rs : regset) (d : cdata RData) := \n        {\n          usermode_ikern: ikern d = true -> rs PC = Vptr b Int.zero;\n          usermode_cid: 0 < cid d;\n          usermode_abq: abq_inv d\n        }.\n\n      Lemma startuser_step :\n        forall rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) -> \n          rs PC = Vptr b Int.zero ->\n          primcall_startuser_sem proc_start_user_spec s rs (m,d) rs' (m',d') /\\ t = E0.\n      Proof.        \n        intros rs rs' m m' d d' t Hstep Hpc.\n        assert (Hmake': make_globalenv s M tsyscall_layer = ret ge) by auto.\n        clear Hmake; rename Hmake' into Hmake; unfold tsyscall_layer in Hmake; inv_make_globalenv Hmake.\n        unfold tsyscall, tsyscall_passthrough in HLge0; inv_make_globalenv HLge0.\n        assert (b1 = b).\n        {\n          inv HLge0le.\n          specialize (genv_le_find_symbol proc_start_user).\n          rewrite Hb1fs, Hpsu in genv_le_find_symbol; inv genv_le_find_symbol; auto.\n        }\n        subst.\n        assert (Genv.find_funct_ptr ge b = Some (External (EF_external proc_start_user null_signature))).\n        {\n          inv HLge0le.\n          specialize (genv_le_find_funct_ptr b).\n          rewrite Hb1fp in genv_le_find_funct_ptr; inv genv_le_find_funct_ptr; auto.\n        }\n        assert (Heq: get_layer_primitive proc_start_user tsyscall_layer \n                     = OK (Some (primcall_start_user_compatsem proc_start_user_spec))) by reflexivity.\n        rename H into Hbfp; inv Hstep; rewrites.\n        - inv H7.\n          inv H.\n          destruct H0 as [Hl Hsem].\n          inv Hsem.\n          destruct H as [\u03c3' [Hmatch' [Hsem [Hcon _]]]]; subst.\n          unfold ident in *.\n          rewrite Heq in Hl. inv Hl.\n        - inv H6.\n          destruct H as [sg [\u03c3 [Hext [Hl Hsem]]]]; inv Hext.\n          unfold ident in *.\n          rewrite Heq in Hl. inv Hl.\n          inv Hsem; simpl in *.\n          rewrite (stencil_matches_unique _ _ _ local_stencil_matches H0); auto.\n      Qed.\n\n      Lemma startuser_step_d :\n        forall rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) -> \n          rs PC = Vptr b Int.zero ->\n          d' = d {ikern: false} {ipt: false} {PT: cid d}.\n      Proof.\n        intros rs rs' m m' d d' t Hstep Hpc.\n        destruct (startuser_step _ _ _ _ _ _ _ Hstep Hpc) as [Hsem ?]; inv Hsem.\n        inv_spec; inv_rewrite.\n      Qed.\n\n      Lemma exec_loadex_usermode_inv :\n        forall chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd,\n          exec_loadex ge chunk (m,d) a rs rd = Next rs' (m',d') ->\n          ikern d = false -> ihost d = true -> usermode rs d -> usermode rs' d'.\n      Proof.\n        unfold exec_loadex, exec_loadex2; intros; subdestruct; rename H into Hexec.\n        - destruct H2.\n          unfold HostAccess2.exec_host_load2 in Hexec; subdestruct;\n            try solve [inv Hexec; constructor; intros; rewrites; eauto].\n          unfold PageFault.exec_pagefault in *; subdestruct; inv Hexec.\n          constructor; simpl; auto; intros; rewrites.\n        - simpl in *; rewrites.\n      Qed.\n\n      Lemma exec_storeex_usermode_inv :\n        forall chunk rs rs' (m m' : mem) (d d' : cdata RData) a rd rds,\n          exec_storeex ge chunk (m,d) a rs rd rds = Next rs' (m',d') ->\n          ikern d = false -> ihost d = true -> usermode rs d -> usermode rs' d'.\n      Proof.\n        unfold exec_storeex, exec_storeex2; intros; subdestruct; rename H into Hexec.\n        - destruct H2.\n          unfold HostAccess2.exec_host_store2 in Hexec; subdestruct;\n            try solve [unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in Hexec; \n                       subdestruct; inv Hexec; constructor; simpl; eauto; intros; rewrites].\n          unfold PageFault.exec_pagefault in Hexec; subdestruct; inv Hexec.\n          constructor; simpl; auto; intros; rewrites.\n        - simpl in *; rewrites.\n      Qed.\n\n      Lemma trap_into_kernel_usermode_cid :\n        forall id s' m' rs d d' vargs sg0 b0 v0\n             v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16,\n          trap_into_kernel_spec id s' m' rs d d' vargs sg0 b0 v0\n            v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 -> \n          cid d = cid d'.\n      Proof.\n        intros until v16; intro Hspec; inv Hspec.\n        decompose [and] H0; inv_spec; inv_somes; auto.\n      Qed.\n\n      Lemma trap_into_kernel_usermode_abq :\n        forall id s' m' rs d d' vargs sg0 b0 v0\n             v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16,\n          trap_into_kernel_spec id s' m' rs d d' vargs sg0 b0 v0\n            v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 -> \n          abq d = abq d'.\n      Proof.\n        intros until v16; intro Hspec; inv Hspec.\n        decompose [and] H0; inv_spec; inv_somes; auto.\n      Qed.\n\n      Lemma ptInsertPTE0_cid:\n        forall i1 vadr padr pm d d',\n          ptInsertPTE0_spec i1 vadr padr pm d = Some d' ->\n          cid d = cid d'\n          /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n      Proof.\n        intros; inv_spec; inv_somes; simpl; auto. \n      Qed.\n\n      Lemma ptAllocPDE0_cid:\n        forall i1 i2 n d d',\n          ptAllocPDE0_spec i1 i2 d = Some (d', n) ->\n          cid d = cid d'\n          /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n      Proof.\n        intros. functional inversion H; subst; auto; simpl;clear H.\n      Qed.\n\n      Definition Q d d' :=\n        cid d = cid d'\n        /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n\n      Lemma Q_trans:\n        forall d1 d2 d3,\n          Q d1 d2 ->\n          Q d2 d3 ->\n          Q d1 d3.\n      Proof.\n        unfold Q. intros d1 d2 d3.\n        intros (He & Hi) (He' & Hi').\n        split. congruence. \n        intros Hle Habq.\n        eapply Hi'. rewrite <- He; trivial.\n        eapply Hi; assumption.\n      Qed.\n          \n      Lemma ptInsert0_cid:\n        forall i1 i2 b i3 d d' v,\n          ptInsert0_spec i1 i2 b i3 d = Some (d', v) ->\n          cid d = cid d'\n          /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n      Proof.\n        intros; inv_spec; inv_somes; clear Hdestruct4.\n        - eapply ptInsertPTE0_cid; eauto.\n        - eapply ptAllocPDE0_cid; eauto. \n        - exploit ptInsertPTE0_cid; eauto.\n          exploit ptAllocPDE0_cid; eauto. intros.\n          eapply Q_trans; eauto.\n      Qed.\n\n      Lemma alloc_cid:\n        forall i1 d d' b,\n          alloc_spec i1 d = Some (d', b) ->\n          Q d d'.\n      Proof.\n        intros. unfold Q.\n        functional inversion H; auto.\n      Qed.\n\n      Lemma ptResv2_cid :\n        forall i1 i4 i2 i3 i5 i6 n d d',\n          ptResv2_spec i1 i2 i3 i4 i5 i6 d = Some (d', n) ->\n          cid d = cid d'\n          /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n      Proof.\n        intros. functional inversion H; subst; clear H.\n        - auto.\n        - exploit ptInsert0_cid; eauto; intros.\n          eapply Q_trans; eauto.\n          eapply alloc_cid; eauto.\n        - exploit ptInsert0_cid; eauto; intros.\n          eapply Q_trans; eauto.\n          clear H0.\n          exploit ptInsert0_cid; eauto; intros.\n          eapply Q_trans; eauto.\n          eapply alloc_cid; eauto.\n      Qed.\n\n      Lemma sys_dispatch_usermode :\n        forall s m d d',\n          sys_dispatch_c_spec s m d = Some d' -> \n          cid d = cid d'\n          /\\ (0 < cid d -> abq_inv d -> abq_inv d').\n      Proof.\n        intros; inv_spec; fun_inv_spec;\n        inv_somes; auto.      \n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.\n          rewrite ZMap.gss. split; trivial.\n          intros. destruct (H0 l1); inv H1; auto. split; [discriminate|].\n          intro id; specialize (H3 id); simpl; intuition.\n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n\n        - functional inversion H0; subst. clear H0.\n          subst uctx uctx'. simpl.\n          functional inversion H5; subst; simpl in *. clear H5.\n          subst uctx uctx'.\n          functional inversion H4; subst; simpl in *; auto; clear H4.\n          eapply ptResv2_cid; eauto.\n          eapply ptResv2_cid; eauto.\n\n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n        - repeat inv_spec;\n          inv_somes; simpl in *; auto.      \n      Qed.\n\n      Lemma ptfault_resv_usermode:\n        forall v d d',\n          ptfault_resv_spec v d = Some d' -> \n          Q d d'.\n      Proof.\n        intros v d d' Hspec.\n        inv_spec; inv_somes.\n        inv_spec; inv_somes; simpl; auto; unfold Q; simpl; eauto.\n        exploit alloc_cid; eauto. intros.\n        eapply Q_trans; eauto.\n        eapply ptInsert0_cid; eauto.\n        unfold Q; auto.\n      Qed.\n\n      Lemma thread_yield_usermode_ikern :\n        forall rs rs' d d',\n          thread_yield_spec d rs = Some (d', rs') -> \n          high_level_invariant d -> RA_startuser d -> abq_inv d -> \n          rs' RA = Vptr b Int.zero.\n      Proof.\n        unfold RA_startuser; intros rs rs' d d' Hspec Hinv Hra Habq.\n        repeat inv_spec; inv_somes; simpl.\n        assert (Hin: In (last l num_id) l) by (apply last_correct; auto); apply Hra.\n        assert (0 < last l 64) by (eapply Habq; eauto); omega.\n        destruct (cused (ZMap.get (last l num_id) (AC d))) eqn:Hused; auto.\n        assert (0 <= last l num_id < num_id).\n        {\n          destruct (valid_TDQ _ Hinv Hdestruct num_id) as [l' [? Hrange]]; try omega.\n          apply Hrange; rewrites; auto.\n        }\n        eapply (valid_inQ _ Hinv) in Hdestruct3; eauto; try omega.\n        destruct (Hdestruct3 Hin) as [st Htcb].\n        apply (valid_notinQ _ Hinv) in Htcb; auto; try omega.\n      Qed.\n\n      Lemma thread_yield_usermode_cid :\n        forall rs rs' d d',\n          thread_yield_spec d rs = Some (d', rs') -> \n          abq_inv d -> 0 < cid d'. \n      Proof.\n        intros; repeat inv_spec; inv_somes; simpl.\n        apply (H0 l); auto.\n        apply last_correct; auto.\n      Qed.\n\n      Lemma thread_yield_usermode_abq :\n        forall rs rs' d d',\n          high_level_invariant d ->\n          thread_yield_spec d rs = Some (d', rs') -> \n          0 < cid d -> abq_inv d -> abq_inv d'.\n      Proof.\n        intros rs rs' d d' Hinv; intros; repeat inv_spec; inv_somes; simpl in *.\n        zmap_simpl; inv H2.\n        destruct (zeq (last l0 num_id) (cid d)).\n        - (* show by contradiction that cid cannot be in the ready queue *)\n          edestruct (valid_inQ _ Hinv); eauto; try omega.\n          eapply valid_curid; eauto.\n          rewrite <- e; apply last_correct; auto.\n          edestruct (valid_TCB _ Hinv) as [? [? [? [? _]]]]; eauto.\n          eapply valid_curid; eauto.\n          edestruct (correct_curid _ Hinv); eauto; rewrites.\n        - split; [discriminate|].\n          destruct (H1 l0); subst; auto.\n          simpl; intros ? [?|?]; try congruence.\n          eapply INVLemmaThread.remove_property; eauto.\n      Qed.\n\n      Lemma proc_start_user_usermode_ikern :\n        forall rs d d',\n          proc_start_user_spec d = Some (d', rs) -> \n          ikern d' = false.\n      Proof.\n        intros; inv_spec; inv_somes; auto.\n      Qed.\n\n      Lemma proc_start_user_usermode_cid :\n        forall rs d d',\n          proc_start_user_spec d = Some (d', rs) -> \n          cid d = cid d'.\n      Proof.\n        intros; inv_spec; inv_somes; auto.\n      Qed.\n\n      Lemma proc_start_user_usermode_abq :\n        forall rs d d',\n          proc_start_user_spec d = Some (d', rs) -> \n          abq d = abq d'.\n      Proof.\n        intros; inv_spec; inv_somes; auto.\n      Qed.\n\n      Ltac solve_usermode_inv :=\n        repeat match goal with\n        | [ H : appcontext [syscall_spec] |- _ ] => inv H\n        | [ H : proc_start_user_spec _ = _ /\\ _ |- _ ] => destruct H\n(*\n        | [ H : appcontext [trap_into_kernel_spec] |- _ ] => \n          apply trap_into_kernel_usermode_inv in H\n        | [ H : appcontext [proc_start_user_spec] |- _ ] => \n          apply proc_start_user_usermode_inv in H\n        | [ H : appcontext [sys_dispatch_c_spec] |- _ ] => \n          apply sys_dispatch_usermode_inv in H\n        | [ H : appcontext [ptfault_resv_spec] |- _ ] => \n          apply ptfault_resv_usermode_inv in H     *)   \n        end(*; try congruence*).\n\n      Ltac sapply H :=\n        match goal with\n          | [H' : _ |- _] => apply H in H'\n        end.\n\n      Ltac seapply H :=\n        match goal with\n          | [H' : _ |- _] => eapply H in H'\n        end.\n\n      Lemma abq_inv_trans:\n        forall d d',\n          abq_inv d ->\n          abq d = abq d' ->\n          abq_inv d'.\n      Proof.\n        intros. rewrite <- H0 in H1.\n        exploit H; eauto.\n      Qed.\n\n      Lemma usermode_inv :\n        forall rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) ->         \n          high_level_invariant d -> ihost d = true -> RA_startuser d -> \n          usermode rs d -> usermode rs' d'.\n      Proof.\n        intros rs rs' m m' d d' t Hstep Hinv Hhost Hra Huser.\n        destruct (ikern d) eqn:Hkern.\n        destruct Huser; erewrite startuser_step_d; eauto.\n        constructor; auto; discriminate.\n        inv Hstep; try solve [simpl in *; destruct EXT_ALLOWED; rewrites].\n        {\n          (* Case 1: internal step (assembly command) *)\n          rename H7 into Hexec.\n          destruct Huser; destruct i; simpl in *;\n          try solve [inv Hexec; constructor; auto; rewrite Hkern; discriminate |\n                     eapply exec_loadex_usermode_inv; eauto; constructor; auto |\n                     eapply exec_storeex_usermode_inv; eauto; constructor; auto].\n          destruct i; simpl in *; \n          try solve [inv Hexec; constructor; auto; rewrite Hkern; discriminate |\n                     eapply exec_loadex_usermode_inv; eauto; constructor; auto |\n                     eapply exec_storeex_usermode_inv; eauto; constructor; auto |                      \n                     unfold goto_label in *; subdestruct; inv Hexec; \n                       constructor; auto; rewrite Hkern; discriminate |\n                     unfold lift in *; simpl in *; subdestruct; inv Hexec; \n                       constructor; auto; rewrite Hkern; discriminate].\n        }\n        {\n          (* Case 2: prim_call step *)\n          destruct H6 as [x [sg [\u03c3 [Hef [Hl Hsem]]]]]; subst.\n          inv_layer Hl; inv Hsem; simpl in *; inv H1; solve_usermode_inv.\n          - (* dispatch *)\n            destruct Huser; constructor.\n            + sapply proc_start_user_usermode_ikern; congruence.\n            + sapply trap_into_kernel_usermode_cid.\n              sapply proc_start_user_usermode_cid.\n              sapply sys_dispatch_usermode. destruct H10 as (HP & _ ). congruence.            \n            + assert (0 < cid labd0) by (sapply trap_into_kernel_usermode_cid; congruence).\n              sapply trap_into_kernel_usermode_abq.\n              sapply proc_start_user_usermode_abq.\n              sapply sys_dispatch_usermode; destruct H10 as [? Habq].\n              rewrite <- H1; apply Habq; auto.\n              rewrite <- H; auto.\n          - (* pagefault *)\n            destruct Huser; constructor.\n            + sapply proc_start_user_usermode_ikern; congruence.\n            + sapply trap_into_kernel_usermode_cid.\n              sapply proc_start_user_usermode_cid.\n              sapply ptfault_resv_usermode. destruct H11 as (HP & _). congruence.            \n            + exploit trap_into_kernel_usermode_cid; eauto. intros Heq.\n              sapply trap_into_kernel_usermode_abq.\n              sapply proc_start_user_usermode_abq.\n              sapply ptfault_resv_usermode. destruct H11 as (HP1 & HP2).\n              eapply abq_inv_trans; [|eassumption].\n              eapply HP2; eauto.\n              {\n                rewrite <- Heq. trivial.\n              }\n              eapply abq_inv_trans; eauto.\n\n          - (* yield *)\n            destruct Huser; constructor.\n            + rewrite Pregmap.gss.\n              intro; eapply thread_yield_usermode_ikern; eauto.\n              eapply trap_into_kernel_high_inv; eauto.\n              eapply trap_into_kernel_RA_startuser_inv; eauto.\n              sapply trap_into_kernel_usermode_abq.\n              intros l'; intros; apply (usermode_abq0 l'); congruence.              \n            + eapply thread_yield_usermode_cid; eauto.\n              sapply trap_into_kernel_usermode_abq.\n              intros l'; intros; apply (usermode_abq0 l'); congruence.\n            + eapply thread_yield_usermode_abq; [|eauto|..].\n              eapply trap_into_kernel_high_inv; eauto.\n              sapply trap_into_kernel_usermode_cid; congruence.\n              sapply trap_into_kernel_usermode_abq.\n              intros l'; intros; apply (usermode_abq0 l'); congruence.\n          - (* proc_start_user *)\n            destruct Huser; constructor.\n            + sapply proc_start_user_usermode_ikern; congruence.\n            + sapply proc_start_user_usermode_cid; congruence.       \n            + sapply proc_start_user_usermode_abq.\n              intros l'; intros; apply (usermode_abq0 l'); congruence.\n        }\n      Qed.\n\n    End USERMODE_INV.\n\n  End WITHIMPL.\n\nEnd WITHMEM.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/security/SecurityInv2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.18494095548702838}}
{"text": "Require Import Term ConcreteEvidence StMonad_Coq.\n\nRequire Import Example_Phrases_Demo.\n\nRequire Import Appraisal_Defs Appraisal_IO_Stubs AM_Monad AM_St.\n\nRequire Import IO_Stubs privPolicy Cvm_Run.\n\nRequire Import List.\nImport ListNotations.\n\n\n\nDefinition peel_bs_am (ls:RawEv) : AM (BS * RawEv) :=\n  match ls with\n  | bs :: ls' => ret (bs, ls')\n  | _ => failm\n  end.\n\nFixpoint gen_appraise_AM (et:Evidence) (ls:RawEv) : AM AppResultC :=\n  match et with\n  | mt => ret mtc_app\n  | nn nid =>\n    v <- (peel_bs_am ls) ;;\n    match v with\n      (bs, _) =>\n      res <- checkNonce' nid bs ;;\n      ret (nnc_app nid res)\n    end\n\n  | uu p fwd params et' =>\n    match fwd with\n    | COMP => ret mtc_app (* TODO hash check *)\n    | ENCR =>\n      v <- peel_bs_am ls ;;\n      match v with\n        (bs, ls') => \n        decrypted_ls <- decrypt_bs_to_rawev' bs params ;;\n        rest <- gen_appraise_AM et' decrypted_ls ;;\n        ret (eec_app p params passed_bs rest)\n      (* TODO: consider encoding success/failure  of decryption for bs param \n         (instead of default_bs)  *)\n      end\n\n    | EXTD =>\n      v <- peel_bs_am ls ;;\n      match v with\n        (bs, ls') => \n        v <- check_asp_EXTD' params p bs ls' ;;\n        rest <- gen_appraise_AM et' ls' ;;\n        ret (ggc_app p params v rest)\n      end\n    | KILL => ret mtc_app (* Do we ever reach this case? *)\n    | KEEP => gen_appraise_AM et' ls (* Do we ever reach this case? *)\n    end\n  | ss et1 et2 => \n      x <- gen_appraise_AM et1 (firstn (et_size et1) ls) ;;\n      y <- gen_appraise_AM et2 (skipn (et_size et1) ls) ;;\n      ret (ssc_app x y)\n    end.\n\n\n\n\n(*\nDefinition gen_appraise_am_comp (t:Term) (p:Plc) (et:Evidence) (ls:RawEv) : AM AppResultC :=\n  gen_appraise_AM (eval t p et) ls.\n*)\n\n(*\nDefinition run_gen_appraise_am (t:Term) (p:Plc) (et:Evidence) (ls:RawEv) : AppResultC := \n  let am_appr_comp := gen_appraise_AM (eval t p et) ls in\n  (run_am_app_comp am_appr_comp mtc_app).\n*)\n\n\n\n\n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n(*\n\nDefinition checkASP (i:ASP_ID) (args:list Arg) (tpl:Plc) (tid:Plc) (bs:BS) : BS.\nAdmitted.\n\nDefinition checkSig (ls:EvBits) (p:Plc) (sig:BS) : BS.\nAdmitted.\n\nDefinition checkHash (e:Evidence) (p:Plc) (hash:BS) : BS.\nAdmitted.\n\n\nDefinition peel_bs (ls:EvBits) : option (BS * EvBits) :=\n  match ls with\n  | bs :: ls' => Some (bs, ls')\n  | _ => None\n  end.\n *)\n\n\n\n(*\nDefinition checkASP_fwd (p:Plc) (f:FWD) (params:ASP_PARAMS)\n           (et:Evidence) (bs:BS) (ls:RawEv) : Opt EvidenceC :=\n  match f with\n  | COMP => res <- checkHH params bs ;;\n           ret (hhc p params res et)\n  | ENCR => res <- checkEE params bs ;;\n           ret (eec p params res et)\n  | _ => res <- checkASP params bs ;;\n        \n        ret (ggc p params bs mtc)\n  end.\n *)\n\n\n(*\n\nFixpoint build_app_comp_evC (et:Evidence) (ls:RawEv) (nonceGolden:BS) : Opt AppResultC :=\n  match et with\n  | mt => ret mtc_app\n  | nn nid =>\n    '(bs, _) <- peel_bs ls ;;\n    res <- checkNonce nonceGolden bs ;;  (* TODO: proper nonce check *)\n    ret (nnc_app nid res)\n  | uu p fwd params et' =>\n    match fwd with\n    | COMP => ret mtc_app (* TODO hash check *)\n      (*\n      v <- checkHH params bs et' ;;\n      ret (hhc p params v et') *)\n    | ENCR =>\n      '(bs, ls') <- peel_bs ls ;;\n      decrypted_ls <- decrypt_bs_to_rawev bs params ;;\n      rest <- build_app_comp_evC et' decrypted_ls nonceGolden ;;\n      ret (eec_app p params passed_bs rest)\n    (* TODO: consider encoding success/failure  of decryption for bs param \n       (instead of default_bs)  *)\n    | EXTD =>\n      '(bs, ls') <- peel_bs ls ;;\n      v <- checkGG params p bs ls' ;;\n      rest <- build_app_comp_evC et' ls' nonceGolden ;;\n      ret (ggc_app p params v rest)\n    | KILL => ret mtc_app (* Do we ever reach this case? *)\n    | KEEP => build_app_comp_evC et' ls nonceGolden  (* ret mtc_app *) (* Do we ever reach this case? *)\n    end\n  | ss et1 et2 => \n      x <- build_app_comp_evC et1 (firstn (et_size et1) ls) nonceGolden ;;\n      y <- build_app_comp_evC et2 (skipn (et_size et1) ls) nonceGolden  ;;\n      ret (ssc_app x y)\n  end.\n\nDefinition run_gen_appraise (t:Term) (p:Plc) (et:Evidence) (nonceGolden:BS) (ls:RawEv) :=\n  fromSome mtc_app (build_app_comp_evC (eval t p et) ls nonceGolden).\n\nDefinition run_gen_appraise_w_nonce (t:Term) (p:Plc) (nonceIn:BS) (ls:RawEv) :=\n  run_gen_appraise t p (nn 0) nonceIn ls.\n\n*)\n\n\n\n\n\n\n\n\n\n(*\nFixpoint build_app_comp_evC (et:Evidence) (ls:RawEv) : Opt EvidenceC :=\n  match et with\n  | mt => ret mtc\n              \n  | uu params p et' =>\n    '(bs, ls') <- peel_bs ls ;;\n    x <- build_app_comp_evC et' ls' ;;\n    res <- checkASP params bs ;;\n    ret (uuc params p res x)\n    \n  | gg p et' =>\n    '(bs, ls') <- peel_bs ls ;;\n    x <- build_app_comp_evC et' ls' ;;\n    res <- checkSigBits ls' p bs ;;\n    ret (ggc p res x)\n         \n  | hh p et =>\n    '(bs, _) <- peel_bs ls ;;\n    res <- checkHash et p bs ;;\n    ret (hhc p res et)\n  | nn nid =>\n    '(bs, _) <- peel_bs ls ;;\n    res <- checkNonce nid bs ;;\n    ret (nnc nid res)\n\n  | ss et1 et2 =>\n    x <- build_app_comp_evC et1 (firstn (et_size et1) ls) ;;\n    y <- build_app_comp_evC et2 (skipn (et_size et1) ls) ;;\n    ret (ssc x y)\n  | pp et1 et2 =>\n    x <- build_app_comp_evC et1 (firstn (et_size et1) ls) ;;\n    y <- build_app_comp_evC et2 (skipn (et_size et1) ls) ;;\n    ret (ppc x y)\n  end.\n*)\n\n(*\n(* *** Extra AM Monad defs *** *)\n\nDefinition am_add_trace (tr':list Ev) : AM_St -> AM_St :=\n  fun '{| am_nonceMap := nm;\n        am_nonceId := ni;\n        st_aspmap := amap;\n        st_sigmap := smap;\n        st_hshmap := hmap;\n        am_st_trace := tr;\n        checked := cs |} =>\n    mkAM_St nm ni amap smap hmap (tr ++ tr') cs.\n\nDefinition am_add_tracem (tr:list Ev) : AM unit :=\n  modify (am_add_trace tr).\n\nDefinition am_run_cvm (annt:AnnoTerm) (e:EvidenceC) (et:Evidence) : AM EvidenceC :=\n  let start_st := (mk_st e et [] 0) in\n  let end_st := (run_cvm annt start_st) in\n  am_add_tracem (st_trace end_st) ;;\n  ret (st_ev end_st).\n\nDefinition am_run_cvm_comp{A:Type} (comp:CVM A) : AM A :=\n  let '(cvm_res, vmst') := (runSt comp empty_vmst) in\n  match cvm_res with\n  | Some v =>\n    am_add_tracem (st_trace vmst') ;;\n    ret v\n  | _ => failm\n  end.\n\nRequire Import Maps.\n\nDefinition am_get_hsh_gv (p:Plc) (i:ASP_ID) : AM BS :=\n  m <- gets st_hshmap ;;\n  let maybeId := map_get m (p,i) in\n  match maybeId with\n  | Some i' => ret i'\n  | None => failm\n  end.\n\n\nDefinition am_get_hsh_golden_val (p:Plc) (et:Evidence): AM BS :=\n  (*\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   *)\n  ret 0.\n\nDefinition am_check_hsh_eq (gv:BS) (actual:BS) : AM BS :=\n  ret 1.\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/Impl_appraisal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.18494095320847714}}
{"text": "Require Import Lia.\nRequire Import Program.Basics.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic Language.\nFrom imm Require Import Events Execution TraversalConfig Traversal\n     Prog ProgToExecution ProgToExecutionProperties imm_s imm_s_hb\n     CombRelations SimTraversal.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import ImmProperties.\nRequire Import EventStructure.\nRequire Import Consistency.\nRequire Import Execution.\nRequire Import EventToAction.\nRequire Import LblStep.\nRequire Import SimRelCont.\nRequire Import SimRelEventToAction.\nRequire Import ProgES.\nRequire Import SimRel.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection SimRelInit.\n\n  Variable prog : stable_prog_type.\n  Variable S : ES.t.\n  Variable G : execution.\n  Variable sc : relation actid.\n  Variable TC : trav_config.\n  Variable X : actid -> eventid.\n\n  Notation \"'SE'\" := ES.acts_set.\n  Notation \"'SEinit'\" := ES.acts_init_set.\n  Notation \"'SEninit'\" := ES.acts_ninit_set.\n  Notation \"'Stid'\" := ES.tid.\n  Notation \"'Slab'\" := ES.lab.\n  Notation \"'Sloc' S\" := (loc S.(ES.lab)) (at level 1).\n  Notation \"'K'\" := ES.cont_set.\n\n  Notation \"'STid' S t\" := (fun x => Stid S x = t) (at level 1).\n\n  Notation \"'SR'\" := (fun a => is_true (is_r Slab a)).\n  Notation \"'SW'\" := (fun a => is_true (is_w Slab a)).\n  Notation \"'SF'\" := (fun a => is_true (is_f Slab a)).\n  Notation \"'SRel'\" := (fun a => is_true (is_rel Slab a)).\n\n  Notation \"'Ssb'\" := ES.sb.\n  Notation \"'Scf'\" := ES.cf.\n  Notation \"'Srmw'\" := ES.rmw.\n  Notation \"'Sjf'\" := ES.jf.\n  Notation \"'Sjfi'\" := ES.jfi.\n  Notation \"'Sjfe'\" := ES.jfe.\n  Notation \"'Srf'\" := ES.rf.\n  Notation \"'Srfi'\" := ES.rfi.\n  Notation \"'Srfe'\" := ES.rfe.\n  Notation \"'Sco'\" := ES.co.\n  Notation \"'Sew'\" := ES.ew.\n\n  Notation \"'Srs'\" := Consistency.rs.\n  Notation \"'Srelease'\" := Consistency.release.\n  Notation \"'Ssw'\" := Consistency.sw.\n  Notation \"'Shb'\" := Consistency.hb.\n\n  Notation \"'thread_syntax' tid\"  :=\n    (Language.syntax (thread_lts tid)) (at level 10, only parsing).\n\n  Notation \"'thread_st' tid\" :=\n    (Language.state (thread_lts tid)) (at level 10, only parsing).\n\n  Notation \"'thread_init_st' tid\" :=\n    (Language.init (thread_lts tid)) (at level 10, only parsing).\n\n  Notation \"'thread_cont_st' tid\" :=\n    (fun st => existT _ (thread_lts tid) st) (at level 10, only parsing).\n\n  Notation \"'GE'\" := G.(acts_set).\n  Notation \"'GEinit'\" := (is_init \u2229\u2081 GE).\n  Notation \"'GEninit'\" := ((set_compl is_init) \u2229\u2081 GE).\n\n  Notation \"'Glab'\" := (Execution.lab G).\n  Notation \"'Gloc'\" := (Events.loc (lab G)).\n  Notation \"'Gtid'\" := (Events.tid).\n\n  Notation \"'GTid' t\" := (fun x => Gtid x = t) (at level 1).\n  Notation \"'GNTid' t\" := (fun x => Gtid x <> t) (at level 1).\n\n  Notation \"'GR'\" := (fun a => is_true (is_r Glab a)).\n  Notation \"'GW'\" := (fun a => is_true (is_w Glab a)).\n  Notation \"'GF'\" := (fun a => is_true (is_f Glab a)).\n\n  Notation \"'GRel'\" := (fun a => is_true (is_rel Glab a)).\n  Notation \"'GAcq'\" := (fun a => is_true (is_acq Glab a)).\n\n  Notation \"'Gsb'\" := (Execution.sb G).\n  Notation \"'Grmw'\" := (Execution.rmw G).\n  Notation \"'Grf'\" := (Execution.rf G).\n  Notation \"'Gco'\" := (Execution.co G).\n\n  Notation \"'Grs'\" := (imm_s_hb.rs G).\n  Notation \"'Grelease'\" := (imm_s_hb.release G).\n  Notation \"'Gsw'\" := (imm_s_hb.sw G).\n  Notation \"'Ghb'\" := (imm_s_hb.hb G).\n\n  Notation \"'Gfurr'\" := (furr G sc).\n\n  Notation \"'C'\"  := (covered TC).\n  Notation \"'I'\"  := (issued TC).\n\n  Notation \"'Gfurr'\" := (furr G sc).\n\n  Lemma simrel_init\n        (nInitProg : ~ IdentMap.In tid_init prog)\n        (PExec : program_execution (stable_prog_to_prog prog) G)\n        (WF : Execution.Wf G)\n        (CONS : imm_consistent G sc)\n        (nLocsEmpty : g_locs G <> [])\n        (GCLOS : forall tid m n (LT : m < n) (NE : GE (ThreadEvent tid n)),\n            GE (ThreadEvent tid m)) :\n    let Sinit := prog_g_es_init prog G in\n    simrel_consistent prog Sinit G sc\n                      (init_trav G)\n                      (ES.acts_set Sinit)\n                      (fun t => IdentMap.In t prog).\n  Proof.\n    clear S TC X.\n    assert (simrel_e2a (prog_g_es_init prog G) G sc) as HH.\n    { by apply simrel_e2a_init. }\n    simpls.\n    red. splits.\n    2: by apply prog_g_es_init_consistent.\n    constructor; auto.\n    { apply prog_g_es_init_wf; auto. }\n    { apply init_trav_coherent; auto. }\n    { constructor; eauto.\n      2: basic_solver.\n      simpls. ins.\n      split.\n      { apply rmw_from_non_init in RMW; auto.\n        generalize RMW. basic_solver. }\n      apply WF.(rmw_in_sb) in RMW.\n      apply no_sb_to_init in RMW.\n      generalize RMW. basic_solver. }\n    { constructor.\n      all: unfold ES.cf_free, vis, cc, ES.acts_init_set.\n      all: autorewrite with prog_g_es_init_db; auto.\n      all: try basic_solver.\n      { rewrite prog_g_es_init_w at 1. type_solver. }\n      unfolder. ins. splits; auto.\n      unfold cc.\n      ins. desf.\n      exfalso.\n      eapply prog_g_es_init_cf; eauto. }\n    { constructor.\n      all: try by (ins;\n                   match goal with\n                   | H : ES.cont_set _ _ |- _ =>\n                     apply prog_g_es_init_K in H; desf\n                   end).\n      5: { ins. apply prog_g_es_init_K in INKi; desf.\n           erewrite steps_same_eindex; eauto.\n           { by unfold init. }\n           apply wf_thread_state_init. }\n      { ins. red in INK.\n        rewrite prog_g_es_init_alt in *.\n        unfold ES.init, prog_init_K, ES.cont_thread in *.\n        simpls.\n        apply in_map_iff in INK. desf. }\n      { ins. apply prog_g_es_init_K in INK. desf.\n        eapply wf_thread_state_steps.\n        2: { simpls. apply eps_steps_in_steps. eauto. }\n        apply wf_thread_state_init. }\n      { ins.\n        assert (exists xst,\n                   IdentMap.find thread prog = Some xst /\\\n                   lprog = projT1 xst) as [xst [XST]];\n          subst.\n        { unfold stable_prog_to_prog in *.\n          rewrite IdentMap.Facts.map_o in INPROG.\n          unfold option_map in *. desf.\n          eauto. }\n        unfold prog_g_es_init, ES.init, prog_init_K, ES.cont_thread,\n        ES.cont_set in *.\n        simpls.\n        eexists. splits.\n        { apply in_map_iff.\n          exists (thread, xst). splits. simpls.\n            by apply IdentMap.elements_correct. }\n        destruct xst as [lprog BB]. simpls.\n        pose (AA :=\n                @proj2_sig\n                  _ _\n                  (get_stable thread (init lprog) BB\n                              (rt_refl state (step thread) (init lprog)))).\n        red in AA. desf. }\n      ins.\n      apply eps_steps_in_steps.\n      unfold prog_g_es_init, ES.init, prog_init_K, ES.cont_thread,\n      ES.cont_set in *.\n      simpls.\n      apply in_map_iff in INK.\n      destruct INK as [xst [INK REP]].\n      apply pair_inj in INK. destruct INK as [AA INK].\n      rewrite <- AA in *.\n      inv INK.\n      destruct xst as [thread [xprog BB]]. simpls.\n      assert (xprog = lprog); subst.\n      { clear -REP INPROG.\n        apply IdentMap.elements_complete in REP.\n        unfold stable_prog_to_prog in *.\n        rewrite IdentMap.Facts.map_o in INPROG.\n        unfold option_map in *. desf. }\n      pose (AA :=\n              @proj2_sig\n                _ _\n                (get_stable thread (init lprog) BB\n                            (rt_refl state (step thread) (init lprog)))).\n      red in AA. desf. }\n    { unfold contsimstate.\n      ins.\n      unfold stable_prog_to_prog in INPROG.\n      rewrite IdentMap.Facts.map_o in INPROG.\n      unfold option_map in *. desf.\n      match goal with\n      | H : IdentMap.find _ _ = Some _ |- _ => rename H into INP\n      end.\n      destruct s as [lprog BB].\n      pose (AA :=\n              @proj2_sig\n                _ _\n                (get_stable thread (init lprog) BB\n                            (rt_refl state (step thread) (init lprog)))).\n      assert\n        (K (prog_g_es_init prog G)\n           (CInit thread,\n            existT _\n              (thread_lts thread)\n              (proj1_sig\n                 (get_stable thread (init lprog) BB\n                             (rt_refl state (step thread) (init lprog))))))\n          as INK.\n      { unfold prog_g_es_init, ES.init, prog_init_K, ES.cont_thread,\n        ES.cont_set in *.\n        simpls.\n        apply in_map_iff.\n        eexists. splits.\n        2: { apply IdentMap.elements_correct; eauto. }\n        done. }\n\n      exists (CInit thread). eexists.\n      splits; eauto.\n      { arewrite\n          ((fun _ : eventid =>\n              tid_init = ES.cont_thread (prog_g_es_init prog G)\n                                        (CInit thread)) \u2261\u2081 \u2205).\n        2: basic_solver.\n        split; [|basic_solver].\n        unfolder. ins. apply nInitProg.\n        apply IdentMap.Facts.in_find_iff. desf.\n        destruct (IdentMap.find tid_init prog); desf. }\n      red in AA. desf.\n      red. splits; ins.\n      { erewrite steps_same_eindex; eauto.\n        2: by eapply wf_thread_state_init.\n        simpls.\n        split; [|lia].\n        unfold is_init. basic_solver. }\n\n      unfold prog_g_es_init, ES.init, prog_init_K, ES.cont_thread,\n      ES.cont_set in *. simpls.\n      apply in_map_iff in INK.\n      destruct INK as [[tid [lprog' BB']] [INK REP]].\n      apply pair_inj in INK. destruct INK as [AA INK].\n      assert (tid = thread) as TT by inv AA.\n      rewrite TT in *.\n      inv INK. desf.\n      apply RegMap.elements_complete in REP.\n      cdes PExec.\n      edestruct (PExec1 thread lprog) as [pe [CC DD]].\n      { unfold stable_prog_to_prog.\n        rewrite IdentMap.Facts.map_o. unfold option_map.\n        desf. }\n      cdes CC.\n      exists s.\n      red. splits.\n      2,3: by desf.\n      eapply steps_to_eps_steps_steps; eauto.\n        by apply terminal_stable. }\n    { simpls.\n      arewrite (GEinit \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997GEinit\u2998) \u2261\u2081 GEinit).\n      { rewrite (no_sb_to_init G). basic_solver. }\n      split.\n      2: { rewrite prog_g_es_init_init. apply HH. }\n      apply set_subset_inter_r. splits.\n      2: by apply HH.\n      unfold e2a. unfolder. ins. desf. }\n    { unfold prog_g_es_init, prog_l_es_init, ES.init. basic_solver. }\n    { eapply eq_dom_mori; eauto.\n      2: by apply prog_g_es_init_same_lab.\n      red. basic_solver. }\n    { simpls. rewrite WF.(rmw_in_sb). rewrite no_sb_to_init.\n      basic_solver. }\n    { unfold prog_g_es_init, ES.init. basic_solver. }\n    { unfold prog_g_es_init, ES.init. basic_solver. }\n    { unfold prog_g_es_init, ES.init. basic_solver. }\n    { unfold prog_g_es_init, ES.init. basic_solver. }\n    { unfold ES.jfe, prog_g_es_init, ES.init. basic_solver. }\n    { rewrite prog_g_es_init_alt. unfold ES.init. basic_solver. }\n    unfold release.\n    arewrite (is_rel (ES.lab (prog_g_es_init prog G)) \u2286\u2081 \u2205).\n    2: basic_solver 20.\n    unfolder. ins.\n    pose proof (prog_g_es_init_lab prog G x) as AA.\n    unfold prog_g_es_init, ES.init, is_rel, Events.mod, mode_le in *. simpls.\n    desf.\n  Qed.\n\nEnd SimRelInit.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/SimRelInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1849409524573894}}
{"text": "From Coq Require Import Bool List ListSet.\nImport ListNotations.\n\nFrom CasperCBC\n  Require Import\n    Lib.Preamble\n    Lib.ListExtras\n    Lib.ListSetExtras\n    Lib.Measurable\n    VLSM.Common\n    VLSM.Decisions\n    VLSM.CBC.FullNode.Validator.State\n    VLSM.CBC.FullNode.Validator.Equivocation\n    VLSM.Equivocation\n    VLSM.ObservableEquivocation\n    VLSM.CBC.FullNode.Client\n    .\n\n(** * VLSM Full Node Composite Validator *)\n\nSection CompositeValidator.\n\n  Context\n    {C V : Type}\n    {about_C : StrictlyComparable C}\n    {about_V : StrictlyComparable V}\n    {Hmeasurable : Measurable V}\n    {Hrt : ReachableThreshold V}\n    {Hestimator : Estimator (state C V) C}\n    (eq_V := @strictly_comparable_eq_dec _ about_V)\n    (message := State.message C V)\n    (message_preceeds_dec := validator_message_preceeds_dec C V)\n    .\n  Existing Instance eq_V.\n  Existing Instance message_preceeds_dec.\n\n  Definition full_node_validator_observable_messages_fn\n    (s : state C V)\n    (v : V)\n    : set message\n    :=\n    filter (fun m => bool_decide (sender m = v)) (get_message_set s).\n\n    Definition full_node_validator_state_validators\n    (s : state C V)\n    : set V\n    :=\n    full_node_client_state_validators (get_message_set s).\n\n  Instance full_node_validator_observable_messages\n    : observable_events (state C V) message\n    :=\n    state_observable_events_instance (state C V) V message _\n      full_node_validator_observable_messages_fn full_node_validator_state_validators.\n\n  Lemma full_node_validator_has_been_observed_iff\n    (s : state C V)\n    (m : message)\n    : has_been_observed s m <-> In m (get_message_set s).\n  Proof.\n    simpl.\n    unfold observable_events_has_been_observed.\n    unfold state_observable_events_fn.\n    split; intro H.\n    - apply union_fold in H.\n      destruct H as [needle [Hm Hneedle]] .\n      apply in_map_iff in Hneedle.\n      destruct Hneedle as [v0 [Hneedle Hv0]].\n      subst needle.\n      apply filter_In in Hm.\n      destruct Hm as [Hm Hv0eq].\n      assumption.\n    - apply union_fold.\n      exists (full_node_validator_observable_messages_fn s (sender m)).\n      split.\n      * apply filter_In.\n        split; [assumption|].\n        apply bool_decide_eq_true. reflexivity.\n      * apply in_map_iff.\n        exists (sender m). split; [intuition|].\n        apply set_map_exists.\n        exists m. split; [assumption|reflexivity].\n  Qed.\n\n  Instance full_node_validator_observation_based_equivocation_evidence\n    : observation_based_equivocation_evidence (state C V) V message _ decide_eq _ message_preceeds_dec full_node_message_subject_of_observation\n    :=\n    observable_events_equivocation_evidence _ _ _ _\n      full_node_validator_observable_messages_fn full_node_validator_state_validators\n      _ message_preceeds_dec full_node_message_subject_of_observation.\n\n  Instance full_node_validator_observation_based_equivocation_evidence_dec\n    : RelDecision (@equivocation_evidence _ _ _ _ _ _ _ _ full_node_validator_observation_based_equivocation_evidence)\n    :=\n    observable_events_equivocation_evidence_dec _ _ _ _\n      full_node_validator_observable_messages_fn full_node_validator_state_validators\n      _ _ message_preceeds_dec full_node_message_subject_of_observation.\n\n  Lemma full_node_validator_state_validators_nodup\n    (s : state C V)\n    : NoDup (full_node_validator_state_validators s).\n  Proof.\n    apply set_map_nodup.\n  Qed.\n\n  Definition validator_basic_equivocation\n    : basic_equivocation (state C V) V\n    := @basic_observable_equivocation (state C V) V message\n        message_eq _ (validator_message_preceeds_dec C V) full_node_validator_observable_messages full_node_message_subject_of_observation full_node_validator_observation_based_equivocation_evidence _ _ _  full_node_validator_state_validators full_node_validator_state_validators_nodup.\n\n  (** ** Full-node validator VLSM instance\n\n  Here we define a VLSM for a full-node validator identifying itself as\n  <<v>> when sending messages.\n\n  The validator and incorporates messages (sent by other validators), and\n  creates and sends new messages proposing consensus values estimated based\n  on its current state, signing them with its name and current state.\n\n  Unlike the client, no equivocation check is done within the validator upon\n  receiving a new message.\n  *)\n  Definition labelv : Type := option C.\n\n  Definition vtransitionv\n    (v : V)\n    (l : labelv)\n    (som : state C V * option message)\n    : state C V * option message\n    :=\n    let (s, om) := som in\n    let (msgs, final) := s in\n    match l with\n    | None => match om with\n             | None => som\n             | Some msg => pair (pair (set_add decide_eq msg msgs) final) None\n           end\n    | Some c =>\n      let msg := Msg c v (make_justification s) in\n      pair (pair (set_add decide_eq msg msgs) (Some msg)) (Some msg)\n    end.\n\n  Lemma vtransitionv_inv_out\n    (v : V)\n    (l : labelv)\n    (s s' : state C V)\n    (om : option message)\n    (m' : message)\n    (Ht : vtransitionv v l (s, om) = pair s' (Some m'))\n    : s' = pair (set_add decide_eq m' (get_message_set s)) (Some m')\n    /\\ get_justification m' = make_justification s\n    /\\ sender m' = v\n    /\\ exists (c : C), l = Some c.\n  Proof.\n    unfold vtransitionv in Ht. destruct s as (msgs, final).\n    destruct l as [c|].\n    - inversion Ht. repeat split; try reflexivity. exists c. reflexivity.\n    - destruct om as [msg|]; inversion Ht.\n  Qed.\n\n  Definition valid_validator\n    (l : labelv)\n    (som : state C V * option message)\n    : Prop\n    :=\n    let (s, om) := som in\n    match l, om with\n    | None, None => True\n    | None, Some msg =>\n      ~In msg (get_message_set s)\n      /\\\n      incl (get_message_set (unmake_justification (get_justification msg))) (get_message_set s)\n    | Some c, None =>\n      @estimator (state C V) C Hestimator s c\n    | _,_ => False\n    end.\n\n  Instance VLSM_type_full_validator : VLSM_type message :=\n    { state := state C V\n    ; label := labelv\n    }.\n\n  Definition initial_state_prop\n    (s : state C V)\n    : Prop\n    :=\n    s = pair [] None.\n\n  Definition state0 : {s | initial_state_prop s} :=\n    exist _ (pair [] None) eq_refl.\n\n  Definition initial_message_prop (m : message) : Prop := False.\n\n  Instance LSM_full_validator : VLSM_sign VLSM_type_full_validator :=\n    { initial_state_prop := initial_state_prop\n    ; initial_message_prop := initial_message_prop\n    ; s0 := state0\n    ; m0 := State.message0\n    ; l0 := None\n    }.\n\n  Definition VLSM_full_validator_machine (v : V) : VLSM_class LSM_full_validator :=\n    {| transition := vtransitionv v\n     ; valid := valid_validator\n    |}.\n\n  Definition VLSM_full_validator (v : V) : VLSM message :=\n    mk_vlsm (VLSM_full_validator_machine v).\n\n  Existing Instance observable_messages.\n\n  Definition full_node_validator_vlsm_observable_messages\n    (v : V)\n    : vlsm_observable_events (VLSM_full_validator v) full_node_message_subject_of_observation.\n  Proof.\n    split; intros.\n    - replace s with (@nil message, @None message) in He by assumption.\n      inversion He.\n    - inversion His.\n    - destruct som as (s, om). destruct s as (msgs, final).\n      destruct l as [c|]; [|destruct om as [msg|]]; inversion Ht.\n      subst. clear Ht.\n      match type of H with\n      | context[Msg _ _ ?s] => remember s as j\n      end.\n      apply full_node_validator_has_been_observed_iff.\n      simpl.\n      apply set_add_iff.\n      destruct H as [Hmsg | Hj]; intuition.\n      right.\n      apply in_unmake_justification in Hj.\n      apply in_make_message_set.\n      subst.\n      destruct final; assumption.\n  Qed.\n\nSection proper_sent_received.\n  Context\n    (v : V)\n    (vlsm := VLSM_full_validator v)\n    (bvlsm := pre_loaded_with_all_messages_vlsm vlsm)\n    .\n\n  Lemma validator_protocol_state_nodup\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    : NoDup (get_message_set s).\n  Proof.\n    induction Hs using protocol_state_prop_ind.\n    - inversion Hs. constructor.\n    - destruct Ht as [_ Ht].\n      simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s as (msgs, final).\n      destruct l as [c|].\n      + apply pair_equal_spec in Ht. destruct Ht as [Hs' _].\n        subst s'. apply set_add_nodup. assumption.\n      + destruct om as [msg|]; inversion Ht.\n        * apply set_add_nodup. assumption.\n        * assumption.\n  Qed.\n\n  Lemma vtransition_inv_out\n    (l : label)\n    (s s' : state C V)\n    (om : option message)\n    (m' : message)\n    (Ht : vtransition bvlsm l (s, om) = pair s' (Some m'))\n    : s' = pair (set_add decide_eq m' (get_message_set s)) (Some m')\n    /\\ get_justification m' = make_justification s\n    /\\ sender m' = v\n    /\\ exists (c : C), l = Some c.\n  Proof.\n    apply vtransitionv_inv_out in Ht. assumption.\n  Qed.\n\n  Lemma protocol_transition_inv_out\n    (l : label)\n    (s s' : state C V)\n    (om : option message)\n    (m' : message)\n    (Ht : protocol_transition bvlsm l (s, om) (s', Some m'))\n    : s' = pair (set_add decide_eq m' (get_message_set s)) (Some m')\n    /\\ get_justification m' = make_justification s\n    /\\ sender m' = v\n    /\\ exists (c : C), l = Some c.\n  Proof.\n    destruct Ht as [_ Ht]. apply vtransition_inv_out in Ht. assumption.\n  Qed.\n\n  Lemma protocol_transition_inv_in\n    (l : label)\n    (s s' : state C V)\n    (m : message)\n    (om' : option message)\n    (Ht : protocol_transition bvlsm l (s, Some m) (s', om'))\n    : s' = pair (set_add decide_eq m (get_message_set s)) (last_sent s)\n    /\\ om' = None\n    /\\ ~In m (get_message_set s)\n    /\\ incl\n        (unmake_message_set (justification_message_set (get_justification m)))\n        (get_message_set s)\n    /\\ protocol_state_prop bvlsm s\n    /\\ protocol_message_prop bvlsm m\n    /\\ protocol_state_prop bvlsm s'.\n  Proof.\n    pose Ht as Hs'.\n    apply protocol_transition_destination in Hs'.\n    destruct Ht as [[Hs [Hm Hv]] Ht].\n    simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n    simpl in Hv. unfold vvalid in Hv. simpl in Hv.\n    destruct l as [c|]; try inversion Hv.\n    destruct s as (msgs, final).\n    inversion Ht. subst. simpl.\n    repeat split; try reflexivity; assumption.\n  Qed.\n\n  Lemma last_sent_in_messages\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    (lst : message)\n    (Hlst : last_sent s = Some lst)\n    : In lst (get_message_set s).\n  Proof.\n    induction Hs using protocol_state_prop_ind.\n    - inversion Hs. subst s. inversion Hlst.\n    - destruct Ht as [_ Ht]. simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s as (msgs, final).\n      destruct l as [c|].\n      + inversion Ht; subst. destruct final as [m|]; simpl in *\n        ; inversion Hlst; apply set_add_iff; left; reflexivity.\n      + destruct om as [msg|]; inversion Ht; subst\n        ; simpl in Hlst; subst final\n        ; specialize (IHHs eq_refl); simpl; [|assumption].\n        apply set_add_iff. right. assumption.\n  Qed.\n\n  Lemma last_sent_justification_protocol\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    (lst : message)\n    (Hlst : last_sent s = Some lst)\n    (j := get_justification lst)\n    : exists sj : state C V, protocol_state_prop bvlsm sj /\\ make_justification sj = j.\n  Proof.\n    subst j.\n    induction Hs using protocol_state_prop_ind.\n    - inversion Hs. subst s. inversion Hlst.\n    - destruct Ht as [[Hps [Hom Hv]] Ht].\n       simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s as (msgs, final).\n      destruct l as [c|].\n      + inversion Ht; subst.\n        exists (msgs, final).\n        destruct final as [m|]; simpl in *; inversion Hlst; simpl\n        ; split; try assumption; reflexivity.\n      + destruct om as [msg|]; inversion Ht; subst\n        ; simpl in Hlst; subst final\n        ; specialize (IHHs eq_refl); simpl; assumption.\n  Qed.\n\n  Lemma in_protocol_state\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    (m : message)\n    (Hm : In m (get_message_set s))\n    : incl (unmake_message_set (justification_message_set (get_justification m))) (get_message_set s).\n  Proof.\n    induction Hs using protocol_state_prop_ind.\n    - inversion Hs. subst s. inversion Hm.\n    - destruct Ht as [[Hps [Hom Hv]] Ht].\n      simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      simpl in Hv. unfold vvalid in Hv. simpl in Hv.\n      destruct s as (msgs, final).\n      destruct l as [c|].\n      + inversion Ht; subst s' om';clear Ht;simpl in * |- *.\n        apply set_add_iff in Hm.\n        intros msg Hmsg; apply set_add_iff; right.\n        destruct Hm;[|apply IHHs;assumption].\n        subst m; clear -Hmsg;simpl in Hmsg.\n        apply make_unmake_message_set_eq.\n        destruct final;assumption.\n      + destruct om as [msg|]; inversion Ht; subst; clear Ht\n        ; simpl in IHHs; simpl in Hv; simpl\n        ; [|apply IHHs; assumption].\n        destruct Hv as [Hnmsg Hv].\n        apply set_add_iff in Hm.\n        destruct Hm as [Heqm | Hm].\n        * subst m.\n          apply incl_tran with msgs; try assumption.\n          intros x Hx; apply set_add_iff. right. assumption.\n        * specialize (IHHs Hm).\n          apply incl_tran with msgs; try assumption.\n          intros x Hx; apply set_add_iff. right. assumption.\n  Qed.\n\n  Lemma has_been_sent_in_futures\n    (s1 s2 : state C V)\n    (Hs : in_futures bvlsm s1 s2)\n    : incl (State.sent_messages s1) (State.sent_messages s2).\n  Proof.\n    unfold in_futures in Hs. destruct Hs as [tr Htr].\n    induction Htr; intros.\n    - apply incl_refl.\n    - revert IHHtr. apply incl_tran.\n      clear -H.\n      destruct H as [_ Ht]. simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s' as (msgs, final).\n      destruct l as [c|].\n      + inversion Ht; subst; clear Ht. unfold State.sent_messages. simpl.\n        destruct final as [m|]; subst; simpl in *; try apply incl_nil_l.\n        destruct m as (c0, v0, j0). intros m Hm.\n        apply set_add_iff. right. assumption.\n      + destruct iom as [msg|]; inversion Ht; apply incl_refl.\n  Qed.\n\n  Lemma get_messages_in_futures\n    (s1 s2 : state C V)\n    (Hs : in_futures bvlsm s1 s2)\n    : incl (get_message_set s1) (get_message_set s2).\n  Proof.\n    unfold in_futures in Hs. destruct Hs as [tr Htr].\n    induction Htr; intros.\n    - apply incl_refl.\n    - revert IHHtr. apply incl_tran. \n      clear -H.\n      destruct H as [_ Ht]. simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s' as (msgs, final).\n      destruct l as [c|].\n      + inversion Ht; subst; clear Ht. unfold get_message_set. simpl.\n        intros m Hm. apply set_add_iff. right. assumption.\n      + destruct iom as [msg|]; inversion Ht; try apply incl_refl.\n        simpl. intros m Hm. apply set_add_iff. right. assumption.\n  Qed.\n\n  Lemma has_been_sent_protocol_transition\n    (l : vlabel bvlsm)\n    (s1 s2 : state C V)\n    (iom oom : option message)\n    (Hpt : protocol_transition bvlsm l (s1, iom) (s2, oom))\n    (m : message)\n    (Hs1 : ~ In m (State.sent_messages s1))\n    : In m (State.sent_messages s2) <-> oom = Some m.\n  Proof.\n    destruct Hpt as [_ Ht]. simpl in Ht.\n    unfold vtransition in Ht. simpl in Ht.\n    destruct s1 as (msgs, final).\n    destruct l as [c|]; inversion Ht; subst.\n    + unfold State.sent_messages. simpl.  split; intro H.\n      * apply set_add_iff in H.\n        destruct H as [Heq | H]; subst; try reflexivity.\n        elim Hs1. unfold State.sent_messages. simpl.\n        destruct final; simpl in *; assumption.\n      * inversion H; subst.\n        apply set_add_iff. left. reflexivity.\n    + destruct iom as [msg|]; inversion H0; subst; split; intro H\n      ; try discriminate H\n      ; elim Hs1\n      ; assumption.\n  Qed.\n\n  Lemma has_been_sent_in_trace\n    (s : state C V)\n    (m: message)\n    (is : state C V)\n    (tr: list transition_item)\n    (Htr: finite_protocol_trace_init_to bvlsm is s tr)\n    (item: transition_item)\n    (Hitem: In item tr)\n    (Hm: output item = Some m)\n    : In m (State.sent_messages s).\n  Proof.\n    apply in_split in Hitem.\n    destruct Hitem as [l1 [l2 Hitem]]. subst tr.\n    destruct Htr as [Htr Hinit].\n    apply finite_protocol_trace_from_to_app_split in Htr.\n    destruct Htr as [_ Htr].\n    inversion Htr. subst. simpl in Hm. subst oom.\n    assert (Hm0 : In m (State.sent_messages s0)).\n    { clear -H4. destruct H4 as [_ Ht].\n      simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      change (state C V) with Common.state in is.\n      destruct\n        (finite_trace_last (is:Common.state) l1)\n        as (msgs, final) in Ht.\n      destruct l as [c|].\n      - inversion Ht; subst; clear Ht.\n        unfold State.sent_messages. simpl.\n        apply set_add_iff. left. reflexivity.\n      - destruct iom as [msg|]; inversion Ht.\n    }\n    assert (Hs0 : in_futures bvlsm s0 s).\n    { exists l2. inversion Htr. assumption. }\n    apply has_been_sent_in_futures with s0; assumption.\n  Qed.\n\n  Lemma has_been_sent_witness\n    (s: state C V)\n    (m: message)\n    (Horacle: In m (State.sent_messages s))\n    (start: Common.state)\n    (Hstart: ~In m (State.sent_messages start))\n    (prefix: list transition_item)\n    (Hprefix: finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm vlsm) start s prefix)\n    : exists item : transition_item, In item prefix /\\ output item = Some m.\n  Proof.\n    induction Hprefix.\n    + elim Hstart. assumption.\n    + simpl in *.\n      specialize (IHHprefix Horacle).\n      destruct oom as [om|]; try destruct (decide (om = m)); try subst om.\n      * eexists. split;[left;reflexivity|reflexivity]. \n      * assert (Hs0 : ~In m (State.sent_messages s)).\n        { intro Hbs.\n          apply (has_been_sent_protocol_transition _ _ _ _ _ H _ Hstart) in Hbs.\n          congruence.\n        }\n        specialize (IHHprefix Hs0) as [x [Hx Hm]].\n        exists x. tauto.\n      * assert (Hs0 : ~In m (State.sent_messages s)).\n        { intro Hbs.\n          apply (has_been_sent_protocol_transition _ _ _ _ _ H _ Hstart) in Hbs.\n          discriminate Hbs.\n        }\n        specialize (IHHprefix Hs0) as [x [Hx Hm]].\n        exists x. tauto.\n  Qed.\n\n  Lemma has_been_sent_in_trace_rev\n    (s: state C V)\n    (m: message)\n    (Horacle: In m (State.sent_messages s))\n    (is : state C V)\n    (tr: list transition_item)\n    (Htr: finite_protocol_trace_init_to bvlsm is s tr)\n    : exists item : transition_item, In item tr /\\ output item = Some m.\n  Proof.\n    destruct Htr as [Htr Hinit].\n    apply has_been_sent_witness with s is; try assumption.\n    inversion Hinit. intro. contradiction H0.\n  Qed.\n\n  Lemma has_been_received_in_futures\n    (s1 s2 : state C V)\n    (Hs : in_futures bvlsm s1 s2)\n    : incl (State.received_messages s1) (State.received_messages s2).\n  Proof.\n    unfold State.received_messages.\n    intros m Hm. apply set_diff_iff in Hm. apply set_diff_iff.\n    destruct Hm as [Hm Hnm].\n    specialize (get_messages_in_futures s1 s2 Hs _ Hm) as Hm1.\n    split; try assumption.\n    intro Hsm; elim Hnm.\n    destruct Hs as [tr Htr].\n    destruct\n      (has_been_sent_witness s2 m Hsm s1 Hnm tr Htr)\n      as [item [Hitem Hm']].\n    apply in_split in Hitem. destruct Hitem as [l1 [l2 Hitem]].\n    subst tr.\n    apply finite_protocol_trace_from_to_app_split in Htr as [Hl1 Hl2].\n    change Common.state in s1.\n    remember\n      (@finite_trace_last _ (@type _ bvlsm) s1 l1)\n      as s1'.\n    assert (Hs1' : in_futures bvlsm s1 s1')\n      by (exists l1; assumption).\n    assert (Hm1' : In m (get_message_set s1'))\n      by (apply (get_messages_in_futures s1 s1' Hs1'); assumption).\n    inversion Hl2. subst s' tl item.\n    simpl in Hm'. subst oom.\n    clear - Hm1' H4.\n    destruct H4 as [_ Ht].\n    simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n    destruct s1' as (msgs, final). simpl in *.\n    destruct l as [c|].\n    - inversion Ht; subst. destruct final as [m|]; clear Ht.\n      + elim\n        (in_justification_recursive'\n          (Msg c v (LastSent (make_message_set msgs) m))\n          msgs\n          eq_refl\n        ).\n        assumption.\n      + elim\n        (in_justification_recursive'\n          (Msg c v (NoSent (make_message_set msgs)))\n          msgs\n          eq_refl\n        ).\n        assumption.\n    - destruct iom as [msg|]; inversion Ht.\n  Qed.\n\n  Lemma last_state_empty_segment\n    (start: Common.state)\n    (prefix: list transition_item)\n    (Hprefix: finite_protocol_trace_from_to bvlsm start ([],None) prefix)\n    (item : transition_item)\n    (Hitem : In item prefix)\n    : input item = None /\\ output item = None /\\ destination item = pair [] None /\\ l item = None.\n  Proof.\n    remember ([],None) as sf in Hprefix.\n    induction Hprefix using @finite_protocol_trace_from_to_rev_ind.\n    - inversion Hitem.\n    - apply in_app_iff in Hitem.\n      subst sf. destruct H as [_ Ht].\n      simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct s as [msgs final].\n      destruct l as [c|];[discriminate Ht|].\n      destruct iom as [msg|]; inversion Ht; subst; clear Ht.\n      + contradict H0. apply set_add_not_empty.\n      + destruct Hitem as [Hin|[<- |[]]];auto.\n  Qed.\n\n  Lemma last_state_empty_trace\n    (is : state C V)\n    (tr: list transition_item)\n    (Htr: finite_protocol_trace_init_to bvlsm is ([], None) tr)\n    (item : transition_item)\n    (Hitem : In item tr)\n    : input item = None /\\ output item = None /\\ destination item = pair [] None /\\ l item = None.\n  Proof.\n    destruct Htr as [Htr _].\n    specialize (last_state_empty_segment is tr Htr item Hitem) as H.\n    assumption.\n  Qed.\n\n  Lemma sent_messages_prop\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    (m : message)\n    : In m (State.sent_messages s) <->\n    exists (sm : sent_messages vlsm s), proj1_sig sm = m.\n  Proof.\n    destruct Hs as [_om Hs].\n    pose (protocol_is_trace bvlsm s _om Hs) as Htr.\n    destruct Htr as [His | [is [tr [Htr _]]]];\n      [inversion His; subst s|];split;intros.\n    - inversion H.\n    - destruct H as [[m0 Hm0] _].\n      destruct Hm0 as [is [tr [Htr Hex]]];simpl in *.\n      apply Exists_exists in Hex.\n      destruct Hex as [item [Hitem Hout]].\n      specialize (last_state_empty_trace is tr Htr item Hitem).\n      intros [_ [Hnout _]].\n      simpl in Hout.\n      rewrite Hnout in Hout. discriminate Hout.\n    - assert (Hm : selected_message_exists_in_some_preloaded_traces vlsm (field_selector output) s m).\n      { exists is. exists tr. exists Htr.\n        apply Exists_exists.\n        apply (has_been_sent_in_trace_rev s m H is tr Htr).\n      }\n      exists (exist _ m Hm). reflexivity.\n    - destruct H as [[m0 Hm] Heq].\n      simpl in Heq. subst m0.\n      destruct Hm as [ism [trm [Htrm Hexistm]]].\n      apply Exists_exists in Hexistm.\n      destruct Hexistm as [item [Hin Hout]].\n      apply (has_been_sent_in_trace s m ism trm Htrm item Hin Hout).\n  Qed.\n\n  Lemma VLSM_full_validator_sent_consistency\n    (s : vstate vlsm)\n    (Hs : protocol_state_prop bvlsm s)\n    (m : message)\n    : selected_message_exists_in_some_preloaded_traces vlsm (field_selector output) s m <->\n    selected_message_exists_in_all_preloaded_traces vlsm (field_selector output) s m.\n  Proof.\n    specialize (sent_messages_prop s Hs m) as Hin.\n    split; intros.\n    - intro is; intros.\n      apply proj2 in Hin.\n      spec Hin; try (exists (exist _ m H); reflexivity).\n      specialize (has_been_sent_in_trace_rev s m Hin is tr Htr) as Hex.\n      apply Exists_exists. assumption.\n    - destruct Hs as [_om Hs].\n      pose (protocol_is_trace bvlsm s _om Hs) as Htr.\n      destruct Htr as [Hinit | [is [tr [Htr _]]]].\n      + specialize (selected_message_exists_in_all_traces_initial_state vlsm s Hinit (field_selector output) m) as Hsm.\n        elim Hsm. assumption.\n      + exists is. exists tr. exists Htr.\n        specialize (H is tr Htr). assumption.\n  Qed.\n\n  Definition VLSM_full_validator_send_oracle\n    (s : vstate vlsm)\n    (m : message) :\n    Prop :=\n    In m (State.sent_messages s).\n\n  Global Instance VLSM_full_validator_send_oracle_dec : RelDecision VLSM_full_validator_send_oracle.\n  Proof.\n    unfold RelDecision; intros s m.\n    unfold VLSM_full_validator_send_oracle.\n    destruct (inb decide_eq m (State.sent_messages s)) eqn : eq_inb.\n    - apply in_correct in eq_inb. left. intuition.\n    - apply in_correct' in eq_inb. right. intuition.\n  Qed.\n\n  Global Instance VLSM_full_validator_has_been_sent : has_been_sent_capability vlsm.\n  Proof.\n    apply (@has_been_sent_capability_from_stepwise _ vlsm VLSM_full_validator_send_oracle _).\n    split.\n    - intros.\n      simpl in H. unfold initial_state_prop in H.\n      subst s. unfold VLSM_full_validator_send_oracle. intuition.\n    - intros.\n      unfold VLSM_full_validator_send_oracle in *.\n      destruct H as [Hprotocol Htrans].\n      unfold transition in Htrans. simpl in Htrans.\n      unfold vtransition in Htrans. unfold transition in Htrans.\n      unfold protocol_valid in Hprotocol.\n      unfold valid in Hprotocol. simpl in Hprotocol.\n      unfold vvalid in Hprotocol. unfold valid in Hprotocol.\n      simpl in *.\n      split; intros H.\n      + unfold State.sent_messages in *. simpl in *.\n        destruct s as [s_set s_pointer].\n        destruct l eqn : eq_label.\n        * simpl in *.\n          destruct s_pointer eqn : eq_pointer.\n          -- inversion Htrans.\n             rewrite <- H1 in H.\n             rewrite H2 in H.\n             destruct om.\n             ++ destruct m0 as [c0 v0 j] eqn : eq_m0.\n                apply set_add_elim in H.\n                rewrite H2.\n                destruct H.\n                ** left. f_equal. intuition.\n                ** right. destruct m as [c1 v1 j0].\n                   inversion H2.\n                   subst j. simpl in *.\n                   intuition.\n             ++ simpl in H. intuition.\n          -- simpl in *.\n             inversion Htrans.\n             rewrite <- H1 in H.\n             simpl in H.\n             destruct H;[|intuition].\n             left. f_equal. intuition.\n        * simpl in *.\n          unfold State.sent_messages in *.\n          destruct im eqn : eq_im.\n          -- inversion Htrans.\n             rewrite <- H1 in H.\n             destruct s_pointer eqn : eq_pointer; simpl in *.\n             ++ destruct m0 as [c0 v0 j] eqn : eq_m0.\n                right. intuition.\n             ++ simpl in H. intuition.\n          -- inversion Htrans.\n             rewrite <- H1 in H.\n             destruct s_pointer eqn : eq_pointer; simpl in *.\n             ++ destruct m as [c v0 j].\n                right. intuition.\n             ++ intuition.\n      + destruct s as [s_set s_pointer].\n        unfold State.sent_messages in *.\n        destruct l eqn : eq_label.\n        * simpl in *.\n          destruct s_pointer eqn : eq_pointer; simpl in *.\n          -- destruct m as [c0 v0 j] eqn : eq_m.\n             inversion Htrans. subst om. simpl in *.\n             apply set_add_iff.\n             destruct H.\n             ++ left. inversion H. intuition.\n             ++ right. intuition.\n          -- inversion Htrans. subst om. simpl in *.\n             destruct H;[|intuition].\n             left. inversion H. intuition.\n        * destruct im eqn : eq_im.\n          -- inversion Htrans.\n             destruct s_pointer eqn : eq_pointer; simpl in *.\n             ++ destruct m0 as [c0 v0 j] eqn : eq_m0.\n                destruct H;[intuition congruence|intuition].\n             ++ destruct H;[intuition congruence|intuition].\n          -- inversion Htrans.\n             destruct s_pointer eqn : eq_pointer; simpl in *.\n             ++ destruct m as [c0 v0 j] eqn : eq_m.\n                destruct H;[intuition congruence|intuition].\n             ++ destruct H;[intuition congruence|intuition].\n  Qed.\n\n  Lemma get_sent_messages\n    (s : state C V)\n    (Hs : protocol_state_prop bvlsm s)\n    : incl (State.sent_messages s) (get_message_set s).\n  Proof.\n    intros m Hm.\n    apply sent_messages_prop in Hm; try assumption.\n    destruct Hm as [[m0 Hm] Heq]. simpl in Heq. subst m0.\n    apply VLSM_full_validator_sent_consistency in Hm; try assumption.\n    destruct Hs as [_om Hs].\n    pose (protocol_is_trace bvlsm s _om Hs) as Htr.\n    destruct Htr as [Hinit | [is [tr [Htr _]]]].\n    + elim (selected_message_exists_in_all_traces_initial_state vlsm s Hinit (field_selector output) m).\n      assumption.\n    + specialize (Hm is tr Htr).\n      apply Exists_exists in Hm. destruct Hm as [item [Hitem Hm]].\n      apply in_split in Hitem.\n      destruct Hitem as [l1 [l2 Hitem]]. subst tr.\n      destruct Htr as [Htr Hinit].\n      apply finite_protocol_trace_from_to_app_split in Htr as [Hl1 Hl2].\n      inversion Hl2. subst item tl.\n      rewrite <- H1 in *.\n      simpl in Hm. subst oom.\n      apply protocol_transition_inv_out in H4.\n      destruct H4 as [Hs0 [c Hc]].\n      assert (Hfutures : in_futures bvlsm s0 s)\n        by (exists l2;assumption).\n      apply (get_messages_in_futures s0 s Hfutures).\n      subst s0. simpl. apply set_add_iff. left. reflexivity.\n  Qed.\n\n  Definition VLSM_full_validator_receive_oracle\n    (s : vstate vlsm)\n    (m : message) :\n    Prop :=\n    In m (State.received_messages s).\n\n  Global Instance VLSM_full_validator_receive_oracle_dec : RelDecision VLSM_full_validator_receive_oracle.\n  Proof.\n    unfold RelDecision; intros s m.\n    unfold VLSM_full_validator_receive_oracle.\n    destruct (inb decide_eq m (State.received_messages s)) eqn : eq_inb.\n    - apply in_correct in eq_inb. left. intuition.\n    - apply in_correct' in eq_inb. right. intuition.\n  Qed.\n\n  Global Instance VLSM_full_validator_has_been_received : has_been_received_capability vlsm.\n  Proof.\n    apply (@has_been_received_capability_from_stepwise _ vlsm VLSM_full_validator_receive_oracle _).\n    split.\n    - intros s H m.\n      simpl in H. unfold initial_state_prop in H. subst s.\n      unfold VLSM_full_validator_receive_oracle. simpl. intuition.\n    - intros.\n      unfold VLSM_full_validator_receive_oracle in *.\n      destruct H as [Hprotocol Htrans].\n      unfold transition in Htrans. simpl in Htrans.\n      unfold vtransition in Htrans. unfold transition in Htrans.\n      unfold protocol_valid in Hprotocol.\n      unfold valid in Hprotocol. simpl in Hprotocol.\n      unfold vvalid in Hprotocol. unfold valid in Hprotocol.\n      simpl in *.\n      split; intros H; unfold State.received_messages in *.\n      + destruct s as [s_set s_pointer].\n        destruct l eqn : eq_l; simpl in *.\n        * destruct im;[intuition|].\n          destruct s_pointer eqn : eq_pointer; simpl in *.\n          -- inversion Htrans. subst s'. subst om.\n             right. simpl in *.\n             unfold State.sent_messages in *. simpl in *.\n             destruct m as [c0 v0 j]; simpl in *.\n             apply set_diff_iff in H; simpl in *.\n             destruct H as [Hin Hnin].\n             apply set_add_iff in Hin.\n             destruct Hin.\n             ++ subst msg.\n                contradict Hnin.\n                apply set_add_iff.\n                left. intuition.\n             ++ apply set_diff_iff.\n                split;[intuition|].\n                intros contra.\n                contradict Hnin.\n                apply set_add_iff.\n                right. intuition.\n          -- inversion Htrans. subst s'. subst om.\n             right. simpl in *.\n             unfold State.sent_messages in *. simpl in *.\n             apply set_diff_iff in H; simpl in *.\n             destruct H as [Hin Hnin].\n             apply set_add_iff in Hin.\n             destruct Hin.\n             ++ subst msg.\n                contradict Hnin; intuition.\n             ++ apply set_diff_iff.\n                split;[intuition|].\n                intuition.\n        * destruct im eqn : eq_im.\n          -- inversion Htrans. subst s'. subst om.\n             apply set_diff_iff in H.\n             destruct H as [Hin Hnin]; simpl in *.\n             apply set_add_iff in Hin.\n             destruct Hin.\n             ++ left. f_equal. intuition.\n             ++ right. apply set_diff_iff.\n                intuition.\n          -- inversion Htrans. subst s'. subst om.\n             apply set_diff_iff in H.\n             destruct H as [Hin Hnin]; simpl in *.\n             right. apply set_diff_iff.\n             intuition.\n       + destruct s as [s_set s_pointer] eqn : eq_s.\n         destruct l eqn : eq_l; simpl in *.\n         * destruct im;[intuition|].\n           destruct s_pointer eqn : eq_pointer; simpl in *.\n           -- inversion Htrans. subst s'. subst om.\n              destruct H;[intuition congruence|].\n              apply set_diff_iff in H.\n              destruct H as [Hin Hnin].\n              apply set_diff_iff.\n              split.\n              ++ apply set_add_iff. right. intuition.\n              ++ intros contra.\n                 unfold State.sent_messages in *; simpl in *.\n                 destruct m as [c0 v0 j]; simpl in *.\n                 apply set_add_iff in contra.\n                 destruct contra.\n                 ** specialize (in_justification_recursive' msg s_set) as Hjucrec.\n                     spec Hjucrec. {\n                      subst msg. simpl; intuition.\n                    }\n                    intuition.\n                 ** intuition.\n           -- destruct H;[intuition congruence|].\n              inversion Htrans. subst s'. subst om.\n              apply set_diff_iff in H. simpl in *.\n              destruct H as [H _].\n              apply set_diff_iff.\n              split.\n              ++ apply set_add_iff. right. intuition.\n              ++ intros contra.\n                 unfold State.sent_messages in contra. simpl in contra.\n                 destruct contra;[|intuition].\n                 specialize (in_justification_recursive' msg s_set) as Hjucrec.\n                     spec Hjucrec. {\n                      subst msg. simpl; intuition.\n                    }\n                  intuition.\n         * unfold State.sent_messages in H.\n           destruct im eqn : eq_im; simpl in *.\n           -- destruct s_pointer eqn : eq_pointer; simpl in *.\n              ++ destruct m0 as [c v0 j] eqn : eq_m0.\n                 inversion Htrans.\n                 subst s'. subst om. simpl.\n                 destruct H.\n                 ** inversion H.\n                    subst msg.\n                    apply set_diff_iff.\n                    split.\n                    --- apply set_add_iff. left. intuition.\n                    --- intros contra.\n                        apply set_add_iff in contra.\n                        assert (Hpr : protocol_state_prop bvlsm s). {\n                          destruct Hprotocol.\n                          subst s. intuition.\n                        }\n                        assert (Hinm0 :In m0 s_set). {\n                          specialize (last_sent_in_messages s Hpr m0).\n                          subst s. subst m0. simpl. intuition.\n                        }\n                        destruct contra.\n                        +++ subst m. subst m0. intuition.\n                        +++ specialize (in_protocol_state s Hpr m0) as Hin_pr.\n                            spec Hin_pr. {\n                              subst s. simpl. intuition.\n                            }\n                            unfold incl in Hin_pr.\n                            specialize (Hin_pr m).\n                            subst m0. simpl in *.\n                            specialize (get_sent_messages s Hpr) as Hincl.\n                            unfold State.sent_messages in Hincl.\n                            subst s. simpl in *.\n                            unfold incl in Hincl.\n                            specialize (Hincl m).\n                            spec Hincl. {\n                              apply set_add_iff. right.\n                              intuition.\n                            }\n                            intuition.\n                ** apply set_diff_iff in H.\n                   apply set_diff_iff.\n                   destruct H;split; [apply set_add_iff; right; intuition|intuition].\n              ++ inversion Htrans. subst s'. subst om. simpl in *.\n                 destruct H.\n                 ** apply set_diff_iff.\n                    split.\n                    --- apply set_add_iff. inversion H. intuition.\n                    --- intuition.\n                 ** apply set_diff_iff.\n                    apply set_diff_iff in H.\n                    destruct H as [H _].\n                    split;[apply set_add_iff;right;intuition|intuition].\n           -- inversion Htrans. subst s'. subst om.\n              destruct s_pointer eqn : eq_pointer; simpl in *.\n              ++ destruct m as [c v0 j]. simpl in *.\n                 destruct H;[intuition congruence|intuition].\n              ++ destruct H;[intuition congruence|intuition].\n  Qed.\n\n  Lemma VLSM_full_validator_sent_messages_comparable'\n    (s : vstate vlsm)\n    (tr : list transition_item)\n    (Htr : finite_protocol_trace bvlsm s tr)\n    (prefix middle suffix : list transition_item)\n    (item1 item2 : transition_item)\n    (Htreq: tr = prefix ++ cons item1 middle ++ item2 :: suffix)\n    (m1 m2 : message)\n    (Hm1 : output item1 = Some m1)\n    (Hm2 : output item2 = Some m2)\n    : validator_message_preceeds _ _ m1 m2.\n  Proof.\n    rewrite app_assoc in Htreq.\n    subst tr.\n    destruct Htr as [Htr Hinit].\n    apply finite_protocol_trace_from_app_iff in Htr.\n    destruct Htr as [Htr1 Htr2].\n    apply ptrace_add_default_last in Htr1 as Htr1'.\n    specialize\n      (has_been_sent_in_trace (finite_trace_last s (prefix ++ item1 :: middle))\n        m1 s (prefix ++ item1 :: middle)\n        (conj Htr1' Hinit)\n        item1\n      ) as Hm1'.\n    spec Hm1'.\n    { apply in_app_iff. right. left. reflexivity. }\n    specialize (Hm1' Hm1).\n    inversion Htr2. subst. simpl in Hm2. subst oom.\n    apply protocol_transition_inv_out in H3.\n    destruct H3 as [_ [Hjust _]].\n    unfold validator_message_preceeds.\n    unfold validator_message_preceeds_fn.\n    destruct m2. simpl in Hjust.\n    subst j. simpl.\n    apply in_correct.\n    apply in_unmake_message_set.\n    apply in_make_justification.\n    apply get_sent_messages; try assumption.\n    apply finite_ptrace_last_pstate. assumption.\n  Qed.\n\n  Lemma VLSM_full_validator_sent_messages_comparable\n    (s : vstate vlsm)\n    (tr : list transition_item)\n    (Htr : finite_protocol_trace bvlsm s tr)\n    (m1 m2 : message)\n    (Hm1 : trace_has_message(field_selector output) m1 tr)\n    (Hm2 : trace_has_message (field_selector output) m2 tr)\n    : m1 = m2 \\/ validator_message_preceeds _ _ m1 m2 \\/ validator_message_preceeds _ _ m2 m1.\n  Proof.\n    unfold trace_has_message in *.\n    apply Exists_exists in Hm1. destruct Hm1 as [item1 [Hitem1 Hm1]].\n    apply Exists_exists in Hm2. destruct Hm2 as [item2 [Hitem2 Hm2]].\n    apply in_split in Hitem1.\n    destruct Hitem1 as [prefix1 [suffix1 Hitem1]].\n    rewrite Hitem1 in Hitem2.\n    apply in_app_iff in Hitem2.\n    destruct Hitem2 as [Hitem2 | [Heq | Hitem2]]\n    ; try\n      (apply in_split in Hitem2; destruct Hitem2 as [prefix2 [suffix2 Hitem2]]\n      ; rewrite Hitem2 in Hitem1; clear Hitem2\n      ).\n    - right. right.\n      rewrite <- app_assoc in Hitem1.\n      apply\n        (VLSM_full_validator_sent_messages_comparable'\n          s tr Htr prefix2 suffix2 suffix1 item2 item1 Hitem1\n          m2 m1 Hm2 Hm1\n        ).\n    - left. subst. simpl in Hm1, Hm2. rewrite Hm1 in Hm2. inversion Hm2. reflexivity.\n    - right. left.\n      apply\n        (VLSM_full_validator_sent_messages_comparable'\n          s tr Htr prefix1 prefix2 suffix2 item1 item2 Hitem1\n          m1 m2 Hm1 Hm2\n        ).\n  Qed.\n\nEnd proper_sent_received.\n\nEnd CompositeValidator.\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/CBC/FullNode/Validator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.1849409517063015}}
{"text": "Require Import Bedrock.Prover Bedrock.Env.\nRequire Import Bedrock.ILEnv.\nRequire Bedrock.provers.AssumptionProver.\nRequire Bedrock.provers.ReflexivityProver.\nRequire Bedrock.provers.WordProver.\nRequire Bedrock.provers.ArrayBoundProver.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** * The Combo Prover **)\n\nDefinition comboTypes := repr_combine bedrock_types_r sep.Array.types_r.\nDefinition comboFuncs types' := repr_combine (bedrock_funcs_r (repr comboTypes types'))\n  (Array.funcs_r (repr comboTypes types')).\n\nDefinition ComboProver : ProverPackage :=\n{| ProverTypes := comboTypes\n ; ProverFuncs := comboFuncs\n ; Prover_correct := fun ts fs => composite_ProverT_correct\n   (composite_ProverT_correct (provers.AssumptionProver.assumptionProver_correct _)\n     (provers.ReflexivityProver.reflexivityProver_correct _))\n   (composite_ProverT_correct\n     (provers.WordProver.wordProver_correct (types' := repr comboTypes ts) (repr (comboFuncs ts) fs))\n     (provers.ArrayBoundProver.boundProver_correct (types' := repr comboTypes ts) (repr (comboFuncs ts) fs)))\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.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.18483965843974481}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.algebra Require Import gmap cmra dfrac_agree.\nFrom iris.algebra Require Import mono_list.\nFrom iris.base_logic Require Import mono_nat.\nFrom iris.proofmode Require Import proofmode.\n\nSection ghost_proof.\n\n(* A configuration is known by its write quorums *)\nRecord ConfigC :=\n{\n  is_quorum : (gset chan) \u2192 Prop\n}.\n\nRecord LogEntry :=\n{\n  config:ConfigC ;\n  val:list u8 ;\n}.\n\nClass reconfG \u03a3 :=\n{\n  acc_inG:> inG \u03a3 (gmapR (u64 * u64) (mono_listR (leibnizO LogEntry)));\n  commit_inG:> inG \u03a3 (mono_listR (leibnizO LogEntry));\n  proposal_inG:> inG \u03a3 (gmapR u64 (mono_listR (leibnizO LogEntry)));\n}.\n\nRecord reconf_names :=\n{\n  acc_gn:gname ;\n  commit_gn:gname ;\n  prop_gn:gname ;\n}.\n\nImplicit Type \u03b3:reconf_names.\nImplicit Type srv:u64.\n\nContext `{!heapGS \u03a3}.\nContext `{!reconfG \u03a3}.\n\nDefinition conf_eq (config1 config2:ConfigC) :=\n  \u2200 W, config1.(is_quorum) W \u2194 config2.(is_quorum) W.\n\nImplicit Type mval : (list (leibnizO LogEntry)).\n\nDefinition mval_le mval mval' := prefix mval mval'.\n\nDefinition mval_lt mval mval' := prefix mval mval' \u2227 mval \u2260 mval'.\n\nImplicit Type term:u64.\n\n(* This is just ownership of raw ghost resources. *)\n\nDefinition def_config : ConfigC.\nAdmitted.\n\nDefinition get_config mval : ConfigC :=\n  match (last mval) with\n  | Some e => e.(config)\n  | _ => def_config\nend\n.\n\nDefinition accepted \u03b3 srv term mval : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ (term,srv) := \u25cfML mval ]}.\n\nDefinition accepted_ro \u03b3 srv term mval : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ (term,srv) := \u25cfML\u25a1 mval ]}.\n\nDefinition accepted_ro_none \u03b3 srv term : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ (term,srv) := \u25cfML\u25a1 [] ]}. (* XXX: not sure if empty list is good enough here*)\n\nDefinition accepted_lb \u03b3 srv term mval : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ (term,srv) := \u25efML mval ]}.\n\nDefinition commit \u03b3 mval : iProp \u03a3 :=\n  own \u03b3.(commit_gn) (\u25cfML mval).\n\nDefinition commit_lb \u03b3 mval : iProp \u03a3 :=\n  own \u03b3.(commit_gn) (\u25efML mval).\n\nDefinition proposed \u03b3 term mval : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ term := \u25cfML mval ]}.\n\nDefinition proposed_lb \u03b3 term mval : iProp \u03a3 :=\n  own \u03b3.(acc_gn) {[ term := \u25efML mval ]}.\n\n\n(* This is more complicated stuff, beyond raw ghost resource ownership. *)\n\nDefinition committed_at_term \u03b3 term mval: iProp \u03a3 :=\n  \u2203 W, \u231c(get_config mval).(is_quorum) W\u231d \u2217\n  ([\u2217 set] srv \u2208 W, accepted_lb \u03b3 srv term mval)\n.\n\nDefinition overlapping_quorums (config1 config2:ConfigC) :=\n  \u2200 W1 W2, (config1.(is_quorum) W1) \u2192 (config2.(is_quorum) W2) \u2192 W1 \u2229 W2 \u2260 \u2205.\n\n(* Maybe this should say\n   either the config of mval' intersects with the config of mval OR\n   every quorum in mval' contains a server that accepted something bigger than\n   mval'.\n*)\n(*\n  FIXME: should we take term'' = term here?\n  If we do, then it's not clear how to prove (old_conf_max \u03b3 term mval -\u2217\n  old_conf_max \u03b3 (term + 1) mval) anymore.\n  If we don't, then when we want to use old_conf_max, it's possible that term''\n  < term, in which case we would want to use old_term_max, but we can't use\n  old_term_max, because it requires old_conf_max.\n\n  There isn't a real circularity, it's just that we want to recursive invoke\n  old_conf and old_term. But, that'll result in later problems.\n *)\nFrom iris.bi.lib Require Import fixpoint.\n\nDefinition old_conf_max_pre (\u03a6:(reconf_names -d> u64 -d> (list (leibnizO LogEntry)) -d> iPropO \u03a3)): (reconf_names -d> u64 -d> (list (leibnizO LogEntry)) -d> iPropO \u03a3) :=\n  \u03bb \u03b3 term mval,\n    (\u2200 mval', \u231cmval_lt mval' mval\u231d \u2192 \u25a1(\n        (\u231coverlapping_quorums (get_config mval') (get_config mval)\u231d \u2228\n         (\u2203 mval'' term'',\n             \u231cmval_lt mval' mval''\u231d \u2217\n             \u231cmval_le mval'' mval\u231d \u2217\n             \u231cint.nat term'' \u2264 int.nat term\u231d \u2217\n             committed_at_term \u03b3 term'' mval'' \u2217\n             \u03a6 \u03b3 term mval'' \u2217\n             \u231coverlapping_quorums (get_config mval') (get_config mval'')\u231d\n         )\n        )\n     ))%I\n.\n\nDefinition old_conf_max_pre_least \u03b3 \u03a6 (p:leibnizO(u64 * list (leibnizO LogEntry))): iProp \u03a3 :=\n  \u2200 mval', \u231cmval_lt mval' p.2\u231d \u2192 \u25a1(\n        (\u231coverlapping_quorums (get_config mval') (get_config p.2)\u231d \u2228\n         (\u2203 mval'' term'',\n             \u231cmval_lt p.2 mval''\u231d \u2217\n             \u231cint.nat term'' \u2264 int.nat p.1\u231d \u2217\n             committed_at_term \u03b3 term'' mval'' \u2217\n             \u03a6 ((term'', mval''):leibnizO _) \u2217\n             \u231coverlapping_quorums (get_config mval') (get_config mval'')\u231d\n         )\n        )\n     )\n.\n\n(* Definition old_conf_max \u03b3 term mval : iProp \u03a3 := (bi_least_fixpoint (old_conf_max_pre_least \u03b3) (term, mval)).\n\nInstance old_conf_max_pre_contr : Contractive old_conf_max_pre.\nAdmitted.\n\nProgram Definition old_conf_max_2 \u03b3 term mval : iProp \u03a3 := \u25a1 (fixpoint (old_conf_max_pre) \u03b3 term mval). *)\n\nDefinition old_conf_max_orig \u03b3 term mval: iProp \u03a3 :=\n  \u2200 mval', \u231cmval_lt mval' mval\u231d \u2192 \u25a1(\n        (\u231coverlapping_quorums (get_config mval') (get_config mval)\u231d \u2228\n         (\u2203 mval'' term'',\n             \u231cmval_lt mval' mval''\u231d \u2217\n             \u231cint.nat term'' \u2264 int.nat term\u231d \u2217\n             committed_at_term \u03b3 term'' mval'' \u2217\n             (* FIXME: want to be able to put another old_conf_max here *)\n             \u231coverlapping_quorums (get_config mval') (get_config mval'')\u231d\n         )\n        )\n     )\n.\n\n(* This says:\n   If mval gets committed in this term, then all smaller mval' will be \"sealed\".\n *)\nDefinition old_conf_max_single \u03b3 mval: iProp \u03a3 :=\n  \u2200 term mval', committed_at_term \u03b3 term mval -\u2217 \u231cmval_lt mval' mval\u231d \u2192\n      \u25a1(\u2203 mval'' term'',\n           \u231cmval_lt mval' mval''\u231d \u2217\n           \u231cint.nat term'' \u2264 int.nat term\u231d \u2217\n           committed_at_term \u03b3 term'' mval'' \u2217\n           \u231coverlapping_quorums (get_config mval') (get_config mval'')\u231d\n      )\n.\n\nDefinition old_conf_max \u03b3 mval : iProp \u03a3 :=\n  \u25a1(\u2200 mval_pfx, \u231cmval_le mval_pfx mval\u231d -\u2217 old_conf_max_single \u03b3 mval).\n\nDefinition old_term_max \u03b3 term mval : iProp \u03a3 :=\n  \u2200 term' mval', \u25a1(\u231cint.nat term' < int.nat term\u231d \u2192\n  proposed_lb \u03b3 term' mval' -\u2217\n  committed_at_term \u03b3 term' mval' -\u2217\n  old_conf_max \u03b3 mval' -\u2217\n  \u231cmval_le mval' mval\u231d\n  )\n.\n\nDefinition sysN := nroot .@ \"sys\".\n\nDefinition sys_inv \u03b3 : iProp \u03a3 :=\n  inv sysN (\n        \u2203 term mval,\n          commit \u03b3 mval \u2217\n          (committed_at_term \u03b3 term mval) \u2217\n          proposed_lb \u03b3 term mval \u2217\n          old_term_max \u03b3 term mval \u2217 (* XXX: could make a accepted_lb_fancy, and put this\n                              in there, and add requirement that quorum is\n                              non-empty. *)\n          old_conf_max \u03b3 mval\n  ).\n\nDefinition no_concurrent_reconfigs_and_overlapping_quorums \u03b3 term mval : iProp \u03a3 :=\n  \u2203 mval',\n    commit_lb \u03b3 mval' \u2217 \u25a1(\n      \u2200 mval'', \u231cmval_lt mval'' mval\u231d \u2192\n                \u231cmval_le mval' mval''\u231d \u2192\n                proposed_lb \u03b3 term mval'' \u2192\n                \u231cconf_eq (get_config mval') (get_config mval'')\u231d\n    ) \u2217\n    \u231coverlapping_quorums (get_config mval) (get_config mval')\u231d\n.\n\nLemma mono_list_included': \u2200 (A : ofe) (dq : dfrac) (l l': list A),\n    l `prefix_of` l' \u2192\n    \u25efML l \u227c \u25cfML{dq} l'.\nProof.\n  intros.\n  assert (\u25efML l' \u227c \u25cfML{dq} l').\n  { apply mono_list_included. }\n  assert (\u25efML l \u227c \u25efML l').\n  { apply mono_list_lb_mono. done. }\n  apply (transitivity H1 H0).\nQed.\n\nLemma ghost_commit \u03b3 term mval :\n  sys_inv \u03b3 -\u2217\n  committed_at_term \u03b3 term mval -\u2217\n  proposed_lb \u03b3 term mval -\u2217\n  old_term_max \u03b3 term mval -\u2217 (* XXX: could make a accepted_lb_fancy, and put this\n                              in there, and add requirement that quorum is\n                              non-empty. *)\n  old_conf_max \u03b3 mval -\u2217\n  |={\u2191sysN,\u2205}=> \u25b7 |={\u2205,\u2191sysN}=>\n  commit_lb \u03b3 mval\n.\nProof.\n  iIntros \"#Hinv #HcommitAt #Hproposed #Hold #Hconf\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iDestruct \"Hi\" as (commitTerm commitVal) \"Hi\".\n  iEval (unfold old_conf_max) in \"Hi\".\n  iDestruct \"Hi\" as \"(>Hcommit & #>HcommitAcc & #>HproposedCommit & #>HoldCommit & #HconfCommit)\".\n  replace (_ \u2216 _) with (\u2205: coPset); last first.\n  { set_solver. }\n  iModIntro.\n  iModIntro.\n  iAssert (\u231cmval_le mval commitVal \u2228 mval_le commitVal mval\u231d)%I as \"%Hcomparable\".\n  {\n    destruct (decide (int.nat term < int.nat commitTerm)).\n    { (* case: term < commitTerm *)\n      iDestruct (\"HoldCommit\" with \"[] Hproposed HcommitAt Hconf\") as \"%HvalLe\".\n      { done. }\n      eauto.\n    }\n    destruct (decide (int.nat term = int.nat commitTerm)).\n    { (* case: term == commitTerm *)\n      replace (commitTerm) with (term) by word.\n      iDestruct (own_valid_2 with \"Hproposed HproposedCommit\") as %Hvalid.\n      rewrite singleton_op in Hvalid.\n      apply singleton_valid in Hvalid.\n      apply mono_list_lb_op_valid_1_L in Hvalid.\n      done.\n    }\n    (* case: term > commitTerm *)\n    assert (int.nat term > int.nat commitTerm) by word.\n    iDestruct (\"Hold\" with \"[] HproposedCommit HcommitAcc HconfCommit\") as \"%HvalLe\".\n    { done. }\n    eauto.\n  }\n\n  destruct Hcomparable.\n  { (* committed value is bigger than mval *)\n    iDestruct (own_mono _ _ (\u25efML mval) with \"Hcommit\") as \"#HH\".\n    {\n      by apply mono_list_included'.\n    }\n    iFrame \"#\".\n    iMod (\"Hclose\" with \"[Hcommit]\").\n    {\n      iNext.\n      iExists _, _; iFrame.\n      iFrame \"#\".\n    }\n    done.\n  }\n  { (* mval is bigger than committed value; in this case, we commit something new *)\n    iMod (own_update with \"Hcommit\") as \"Hcommit\".\n    {\n      apply mono_list_update.\n      exact H.\n    }\n    iDestruct (own_mono _ _ (\u25efML mval) with \"Hcommit\") as \"#HH\".\n    {\n      apply mono_list_included.\n    }\n    iFrame \"#\".\n    iMod (\"Hclose\" with \"[Hcommit]\").\n    {\n      iNext.\n      iExists _, _; iFrame.\n      iFrame \"HcommitAt #\".\n    }\n    done.\n  }\nQed.\n\nLemma become_leader \u03b3 term highestVal highestTerm W:\n    int.nat highestTerm < int.nat term \u2192\n    (get_config highestVal).(is_quorum) W \u2192\n    sys_inv \u03b3 -\u2217\n    proposed_lb \u03b3 highestTerm highestVal -\u2217\n    old_term_max \u03b3 highestTerm highestVal -\u2217\n    old_conf_max \u03b3 highestVal -\u2217\n    \u25a1(\n      [\u2217 set] srv \u2208 W,\n        (\u2203 srvVal, \u231cmval_le srvVal highestVal\u231d \u2217 accepted_ro \u03b3 srv highestTerm srvVal) \u2217\n        (\u2200 term', \u231cint.nat highestTerm < int.nat term'\u231d \u2192 \u231cint.nat term' < int.nat term\u231d \u2192 accepted_ro_none \u03b3 srv term')\n    ) -\u2217\n    old_term_max \u03b3 term highestVal.\nProof.\n  intros HtermIneq Hquorum.\n  iIntros \"#Hsys #Hproposed #Hold #Hconf #HoldInfo\".\n  iIntros (term' mval').\n  iModIntro.\n  iIntros \"%Hterm'Ineq\".\n  iIntros \"#Hproposed'\".\n  iIntros \"#Hcommit' #Hconf'\".\n  destruct (decide (int.nat term' < int.nat highestTerm)).\n  { (* term' < highestTerm, so we can just use the old_term_max of (highestTerm,highestVal) *)\n    iApply \"Hold\"; try done.\n  }\n  destruct (decide (int.nat term' = int.nat highestTerm)).\n  { (* for term' == highestTerm, we have the first part of \"oldInfo\" *)\n    replace (term') with (highestTerm); last first.\n    { (* FIXME: why doesn't word work? *)\n      clear -e.\n      rewrite Z2Nat.inj_iff in e; first last.\n      { word. }\n      { word. }\n      {\n        apply word.unsigned_inj in e.\n        done.\n      }\n    }\n    iDestruct (own_valid_2 with \"Hproposed' Hproposed\") as %Hvalid.\n    rewrite singleton_op in Hvalid.\n    rewrite singleton_valid in Hvalid.\n    apply mono_list_lb_op_valid_1_L in Hvalid.\n    destruct Hvalid as [Hdone|HlogLe].\n    { done. }\n    destruct (decide (length mval' = length highestVal)).\n    { (* If the two are equal, then no problem *)\n      assert (mval' = highestVal).\n      {\n        symmetry.\n        apply list_prefix_eq.\n        {\n          done.\n        }\n        word.\n      }\n      rewrite H.\n      done.\n    }\n    (* case: mval_lt highestVal mval'. Here, we're gonna derive a contradiction. *)\n    iExFalso.\n    (* now, apply old_conf_max highestTerm mval'' *)\n    iDestruct (\"Hconf'\" $! mval' with \"[% //]\") as \"Hconf2\".\n    iDestruct (\"Hconf2\" $! _ highestVal with \"Hcommit' [%]\") as \"#Hconf3\".\n    {\n      enough (mval' \u2260 highestVal) by done.\n      admit. (* TODO: pure fact that if lists have different lengths, they are not equal *)\n    }\n    (* In this case, some highest value mval'' was committed, and has\n         overlapping quorums with highestVal. *)\n\n    iDestruct \"Hconf3\" as (mval'' term'') \"(%Hmval''lt & %Hterm''Ineq & #Hcommit'' & %Hoverlap)\".\n      (* if term'' < highestTerm, then (old_term_max highestTerm highestVal) takes care of it *)\n      destruct (decide (int.nat term'' < int.nat highestTerm)).\n      { (* if term'' < highestTerm, we use old_term_max *)\n        unfold old_term_max.\n        iDestruct (\"Hold\" $! term'' mval'' with \"[] [] Hcommit'' [Hconf'']\") as \"%HlogLe2\".\n        { done. }\n        { admit. } (* TODO: add this to old_conf_max. *)\n        {\n          rewrite /old_conf_max.\n          iFrame \"#\".\n        }\n        (* XXX: we need old_conf_max to finish instantiating the old_term_max.\n           So, going to use old_conf_max for the term'' and mval'' that we\n           destructed from the old_conf_max for mval'.\n         *)\n        iPureIntro.\n        simpl in Hmval''lt.\n        (* pure proof: mval'' \u2264 highestVal \u2264 mval' < mval''. Contradiction *)\n        assert (prefix mval'' mval').\n        {\n          transitivity (highestVal); done.\n        }\n        clear -H Hmval''lt.\n        destruct Hmval''lt as [H1 H2].\n        assert (mval'' = mval').\n        {\n          apply (anti_symm prefix); done.\n        }\n        done.\n      }\n      (* if term'' = highestTerm, we use overlapping quorum with highestVal to get contradiction *)\n      simpl in Hterm''Ineq.\n      assert (term'' = highestTerm) as -> by word.\n\n      iDestruct (\"Hcommit''\") as (W2) \"[%Hw2quorum #Hcommit'']\".\n      specialize (Hoverlap W W2).\n      assert (exists srv, srv \u2208 W \u2229 W2) as [srv HsrvIn].\n      {\n        apply set_choose.\n        rewrite leibniz_equiv_iff.\n        apply Hoverlap; done.\n      }\n\n      iDestruct (big_sepS_elem_of_acc _ _ srv with \"Hcommit''\") as \"[Hacc'' _]\".\n      { set_solver. }\n      iDestruct (big_sepS_elem_of_acc _ _ srv with \"HoldInfo\") as \"[Hacc _]\".\n      { set_solver. }\n      iDestruct \"Hacc\" as \"[Hacc _]\".\n      iDestruct \"Hacc\" as (?) \"[%HsrvValLe Hacc]\".\n      iDestruct (own_valid_2 with \"Hacc Hacc''\") as %Hvalid.\n      rewrite singleton_op in Hvalid.\n      rewrite singleton_valid in Hvalid.\n      apply mono_list_both_dfrac_valid_L in Hvalid.\n      destruct Hvalid as [_ HsrvValLe2].\n      simpl in Hmval''lt.\n      exfalso.\n      (* pure proof: mval' < mval'' \u2264 srvVal \u2264 highestVal \u2264 mval'. Contradiction *)\n      admit.\n    }\n  }\n  {\n    exfalso.\n    admit.\n  }\n\n\nEnd ghost_proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/reconf/ghost_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.184832646544243}}
{"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 *\n *\n * Some of the following code is derived from code original to the\n * Iris project. That original code is\n *\n *\tCopyright Iris developers and contributors\n *\n * and used according to the following license.\n *\n *\tSPDX-License-Identifier: BSD-3-Clause\n *\n * Original Code:\n * https://gitlab.mpi-sws.org/iris/iris/-/blob/5bb93f57729a8cc7d0ffeaab769cd24728e51a38/iris/bi/lib/atomic.v\n *\n * Original Iris License:\n * https://gitlab.mpi-sws.org/iris/iris/-/blob/5bb93f57729a8cc7d0ffeaab769cd24728e51a38/LICENSE-CODE\n *)\n\nFrom stdpp Require Import coPset namespaces.\nFrom iris.bi.lib Require Import fixpoint.\nFrom iris.proofmode Require Import coq_tactics proofmode reduction.\nFrom iris.prelude Require Import options.\nFrom iris.bi.lib Require Import atomic.\n\nRequire Export bedrock.lang.bi.laterable.\nRequire Import bedrock.lang.bi.telescopes.\n\n(** Conveniently split a conjunction on both assumption and conclusion. *)\nLocal Tactic Notation \"iSplitWith\" constr(H) :=\n  iApply (bi.and_parallel with H); iSplit; iIntros H.\n\nSection definition.\n  Context `{BiFUpd PROP} {TA TB : tele}.\n  Implicit Types\n    (Eo Ei : coPset) (* outer/inner masks *)\n    (\u03b1 : TA \u2192 PROP) (* atomic pre-condition *)\n    (P : PROP) (* abortion condition *)\n    (\u03b2 : TA \u2192 TB \u2192 PROP) (* atomic post-condition *)\n    (\u03a6 : TA \u2192 TB \u2192 PROP) (* post-condition *)\n  .\n\n  (** atomic1_acc as the \"introduction form\" of atomic updates: An accessor\n      that can be aborted back to [P]. *)\n  (** Main extension compared to [atomic_acc]:\n    This one can make a step---having a later---for the COMMIT case,i.e.\n      \u25b7 (\u2200.. y, \u03b2 x y ={Ei, Eo}=\u2217 \u03a6 x y)\n\n    This means that the client of this spec can make a step before applying the\n    closing COMMIT [fupd], and the prover the spec needs to take an actual step\n    when COMMITing.\n    Consider the example of an AU1 (atomic update) that takes a step.\n    - As a client of an AU spec, which has the form `AU1 \u22a2 wp`, the client\n      applies the spec and has to prove the `AU1`. In proving those, the client\n      has a later in the goal of the COMMIT [fupd], which allows them to strip\n      later from resources in the context, including resources that were\n      obtained by opening the invariants around the AU.\n      This stripping of laters is done before actually COMMITing.\n    - As the prover of the same AU spec `AU1 \u22a2 wp`, the prover assumes the\n      AU1 and proves the `wp`. Then the prover needs to apply the COMMIT [fupd]\n      to finish. But the COMMIT [fupd] is under a later, so the prover needs to\n      have the `wp` takes an actual step to strip that later before COMMITing.\n      This also demonstrates one you cannot prove an AU1 spec for a `wp` that\n      does not take a step.\n\n    Note that we can also add a later to the ABORT case:\n      \u25b7 (\u03b1 x ={Ei, Eo}=\u2217 P)\n\n    But that means the the prover has to show the implementation takes at least\n    a step every time the abort is used. While this is not unreasonable, it\n    restricts the set of implementations that can be proven with this spec. We\n    therefore choose not to support it here. *)\n  Definition atomic1_acc Eo Ei \u03b1 P \u03b2 \u03a6 : PROP :=\n    (|={Eo, Ei}=> \u2203.. x, \u03b1 x \u2217\n          ((\u03b1 x ={Ei, Eo}=\u2217 P) \u2227 \u25b7 (\u2200.. y, \u03b2 x y ={Ei, Eo}=\u2217 \u03a6 x y))\n    )%I.\n\n  (* atomic1_acc is more restricted than atomic_acc : ACCC \u22a2 ACCC1.\n    The direction of implication may look perplexing, but this really gives us\n    what we want: a AU1 spec implies a AU spec, that is\n      (AU1 -\u2217 wp) \u22a2 (AU -\u2217 wp)\n  *)\n  Lemma atomic_acc_atomic1_acc Eo Ei \u03b1 P \u03b2 \u03a6 :\n    atomic_acc Eo Ei \u03b1 P \u03b2 \u03a6 -\u2217 atomic1_acc Eo Ei \u03b1 P \u03b2 \u03a6.\n  Proof.\n    rewrite /atomic1_acc /atomic_acc.\n    iIntros \"AS\". iMod \"AS\" as (x) \"[H\u03b1 Hclose]\".\n    iModIntro. iExists x. iFrame \"H\u03b1\". iSplit.\n    - iIntros \"H\u03b1\". iDestruct \"Hclose\" as \"[Hclose _]\".\n      iApply \"Hclose\". done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iDestruct \"Hclose\" as \"[_ Hclose]\".\n      iApply \"Hclose\". done.\n  Qed.\n\n  Lemma atomic1_acc_wand Eo Ei \u03b1 P1 P2 \u03b2 \u03a61 \u03a62 :\n    ((P1 -\u2217 P2) \u2227 \u25b7 (\u2200.. x y, \u03a61 x y -\u2217 \u03a62 x y)) -\u2217\n    (atomic1_acc Eo Ei \u03b1 P1 \u03b2 \u03a61 -\u2217 atomic1_acc Eo Ei \u03b1 P2 \u03b2 \u03a62).\n  Proof.\n    iIntros \"HP12 AS\". iMod \"AS\" as (x) \"[H\u03b1 Hclose]\".\n    iModIntro. iExists x. iFrame \"H\u03b1\". iSplit.\n    - iIntros \"H\u03b1\". iDestruct \"Hclose\" as \"[Hclose _]\".\n      iApply \"HP12\". iApply \"Hclose\". done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iDestruct \"Hclose\" as \"[_ Hclose]\".\n      iApply \"HP12\". iApply \"Hclose\". done.\n  Qed.\n\n  Lemma atomic1_acc_mask Eo Ed \u03b1 P \u03b2 \u03a6 :\n    atomic1_acc Eo (Eo\u2216Ed) \u03b1 P \u03b2 \u03a6 \u22a3\u22a2 \u2200 E, \u231cEo \u2286 E\u231d \u2192 atomic1_acc E (E\u2216Ed) \u03b1 P \u03b2 \u03a6.\n  Proof.\n    iSplit; last first.\n    { iIntros \"Hstep\". iApply (\"Hstep\" with \"[% //]\"). }\n    iIntros \"Hstep\" (E HE).\n    iApply (fupd_mask_frame_acc with \"Hstep\"); first done.\n    iIntros \"Hstep\". iDestruct \"Hstep\" as (x) \"[H\u03b1 Hclose]\".\n    iIntros \"!> Hclose'\".\n    iExists x. iFrame. iSplitWith \"Hclose\".\n    - iIntros \"H\u03b1\". iApply \"Hclose'\". iApply \"Hclose\". done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iApply \"Hclose'\". iApply \"Hclose\". done.\n  Qed.\n\n  Lemma atomic1_acc_mask_weaken Eo1 Eo2 Ei \u03b1 P \u03b2 \u03a6 :\n    Eo1 \u2286 Eo2 \u2192\n    atomic1_acc Eo1 Ei \u03b1 P \u03b2 \u03a6 -\u2217 atomic1_acc Eo2 Ei \u03b1 P \u03b2 \u03a6.\n  Proof.\n    iIntros (HE) \"Hstep\".\n    iMod fupd_mask_subseteq as \"Hclose1\"; first done.\n    iMod \"Hstep\" as (x) \"[H\u03b1 Hclose2]\". iIntros \"!>\". iExists x.\n    iFrame. iSplitWith \"Hclose2\".\n    - iIntros \"H\u03b1\". iMod (\"Hclose2\" with \"H\u03b1\") as \"$\". done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iMod (\"Hclose2\" with \"H\u03b2\") as \"$\". done.\n  Qed.\n\n  (** atomic1_update as a fixed-point of the equation\n   AU = atomic1_acc \u03b1 AU \u03b2 Q\n  *)\n  Context Eo Ei \u03b1 \u03b2 \u03a6.\n\n  Definition atomic1_update_pre (\u03a8 : () \u2192 PROP) (_ : ()) : PROP :=\n    atomic1_acc Eo Ei \u03b1 (\u03a8 ()) \u03b2 \u03a6.\n\n  Local Instance atomic1_update_pre_mono : BiMonoPred atomic1_update_pre.\n  Proof.\n    constructor.\n    - iIntros (P1 P2 ??) \"#HP12\". iIntros ([]) \"AU\".\n      iApply (atomic1_acc_wand with \"[HP12] AU\").\n      iSplit; last by eauto. iApply \"HP12\".\n    - intros ??. solve_proper.\n  Qed.\n\n  Definition atomic1_update_def :=\n    bi_greatest_fixpoint atomic1_update_pre ().\n\nEnd definition.\n\n(** Seal it *)\nDefinition atomic1_update_aux : seal (@atomic1_update_def). Proof. by eexists. Qed.\nDefinition atomic1_update := atomic1_update_aux.(unseal).\nGlobal Arguments atomic1_update {PROP _ TA TB}.\nDefinition atomic1_update_eq : @atomic1_update = _ := atomic1_update_aux.(seal_eq).\n\nGlobal Arguments atomic1_acc {PROP _ TA TB} Eo Ei _ _ _ _ : simpl never.\nGlobal Arguments atomic1_update {PROP _ TA TB} Eo Ei _ _ _ : simpl never.\n\n(** Notation: Atomic updates *)\nNotation \"'AU1' '<<' \u2200 x1 .. xn , \u03b1 '>>' @ Eo , Ei '<<' \u2203 y1 .. yn , \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_update (TA:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. ))\n                 (TB:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                 Eo Ei\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn, \u03b1%I) ..)\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn,\n                         tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                         (\u03bb y1, .. (\u03bb yn, \u03b2%I) .. )\n                        ) .. )\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn,\n                         tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                         (\u03bb y1, .. (\u03bb yn, \u03a6%I) .. )\n                        ) .. )\n  )\n  (at level 20, Eo, Ei, \u03b1, \u03b2, \u03a6 at level 200, x1 binder, xn binder, y1 binder, yn binder,\n   format \"'[   ' 'AU1'  '<<'  \u2200  x1  ..  xn ,  \u03b1  '>>'  '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u2203  y1  ..  yn ,  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AU1' '<<' \u2200 x1 .. xn , \u03b1 '>>' @ Eo , Ei '<<' \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_update (TA:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. ))\n                 (TB:=TeleO)\n                 Eo Ei\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn, \u03b1%I) ..)\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn, tele_app (TT:=TeleO) \u03b2%I) .. )\n                 (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                       \u03bb x1, .. (\u03bb xn, tele_app (TT:=TeleO) \u03a6%I) .. )\n  )\n  (at level 20, Eo, Ei, \u03b1, \u03b2, \u03a6 at level 200, x1 binder, xn binder,\n   format \"'[   ' 'AU1'  '<<'  \u2200  x1  ..  xn ,  \u03b1  '>>'  '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AU1' '<<' \u03b1 '>>' @ Eo , Ei '<<' \u2203 y1 .. yn , \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_update (TA:=TeleO)\n                 (TB:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                 Eo Ei\n                 (tele_app (TT:=TeleO) \u03b1%I)\n                 (tele_app (TT:=TeleO) $\n                       tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                                (\u03bb y1, .. (\u03bb yn, \u03b2%I) ..))\n                 (tele_app (TT:=TeleO) $\n                       tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                                (\u03bb y1, .. (\u03bb yn, \u03a6%I) ..))\n  )\n  (at level 20, Eo, Ei, \u03b1, \u03b2, \u03a6 at level 200, y1 binder, yn binder,\n   format \"'[   ' 'AU1'  '<<'  \u03b1  '>>'  '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u2203  y1  ..  yn ,  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AU1' '<<' \u03b1 '>>' @ Eo , Ei '<<' \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_update (TA:=TeleO) (TB:=TeleO) Eo Ei\n                 (tele_app (TT:=TeleO) \u03b1%I)\n                 (tele_app (TT:=TeleO) $ tele_app (TT:=TeleO) \u03b2%I)\n                 (tele_app (TT:=TeleO) $ tele_app (TT:=TeleO) \u03a6%I)\n  )\n  (at level 20, Eo, Ei, \u03b1, \u03b2, \u03a6 at level 200,\n   format \"'[   ' 'AU1'  '<<'  \u03b1  '>>'  '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\n(** Notation: Atomic accessors *)\nNotation \"'AACC1' '<<' \u2200 x1 .. xn , \u03b1 'ABORT' P '>>' @ Eo , Ei '<<' \u2203 y1 .. yn , \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_acc (TA:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. ))\n              (TB:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n              Eo Ei\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                    \u03bb x1, .. (\u03bb xn, \u03b1%I) ..)\n              P%I\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                    \u03bb x1, .. (\u03bb xn,\n                      tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                      (\u03bb y1, .. (\u03bb yn, \u03b2%I) .. )\n                     ) .. )\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                    \u03bb x1, .. (\u03bb xn,\n                      tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                      (\u03bb y1, .. (\u03bb yn, \u03a6%I) .. )\n                     ) .. )\n  )\n  (at level 20, Eo, Ei, \u03b1, P, \u03b2, \u03a6 at level 200, x1 binder, xn binder, y1 binder, yn binder,\n   format \"'[     ' 'AACC1'  '[   ' '<<'  \u2200  x1  ..  xn ,  \u03b1  '/' ABORT  P  '>>'  ']' '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u2203  y1  ..  yn ,  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AACC1' '<<' \u2200 x1 .. xn , \u03b1 'ABORT' P '>>' @ Eo , Ei '<<' \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_acc (TA:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. ))\n              (TB:=TeleO)\n              Eo Ei\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                        \u03bb x1, .. (\u03bb xn, \u03b1%I) ..)\n              P%I\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                        \u03bb x1, .. (\u03bb xn, tele_app (TT:=TeleO) \u03b2%I) .. )\n              (tele_app (TT:=TeleS (\u03bb x1, .. (TeleS (\u03bb xn, TeleO)) .. )) $\n                        \u03bb x1, .. (\u03bb xn, tele_app (TT:=TeleO) \u03a6%I) .. )\n  )\n  (at level 20, Eo, Ei, \u03b1, P, \u03b2, \u03a6 at level 200, x1 binder, xn binder,\n   format \"'[     ' 'AACC1'  '[   ' '<<'  \u2200  x1  ..  xn ,  \u03b1  '/' ABORT  P  '>>'  ']' '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AACC1' '<<' \u03b1 'ABORT' P '>>' @ Eo , Ei '<<' \u2203 y1 .. yn , \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_acc (TA:=TeleO)\n              (TB:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n              Eo Ei\n              (tele_app (TT:=TeleO) \u03b1%I)\n              P%I\n              (tele_app (TT:=TeleO) $\n                        tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                        (\u03bb y1, .. (\u03bb yn, \u03b2%I) ..))\n              (tele_app (TT:=TeleO) $\n                        tele_app (TT:=TeleS (\u03bb y1, .. (TeleS (\u03bb yn, TeleO)) .. ))\n                        (\u03bb y1, .. (\u03bb yn, \u03a6%I) ..))\n  )\n  (at level 20, Eo, Ei, \u03b1, P, \u03b2, \u03a6 at level 200, y1 binder, yn binder,\n   format \"'[     ' 'AACC1'  '[   ' '<<'  \u03b1  '/' ABORT  P  '>>'  ']' '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u2203  y1  ..  yn ,  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\nNotation \"'AACC1' '<<' \u03b1 'ABORT' P '>>' @ Eo , Ei '<<' \u03b2 , 'COMM' \u03a6 '>>'\" :=\n  (atomic1_acc (TA:=TeleO)\n              (TB:=TeleO)\n              Eo Ei\n              (tele_app (TT:=TeleO) \u03b1%I)\n              P%I\n                 (tele_app (TT:=TeleO) $ tele_app (TT:=TeleO) \u03b2%I)\n                 (tele_app (TT:=TeleO) $ tele_app (TT:=TeleO) \u03a6%I)\n  )\n  (at level 20, Eo, Ei, \u03b1, P, \u03b2, \u03a6 at level 200,\n   format \"'[     ' 'AACC1'  '[   ' '<<'  \u03b1  '/' ABORT  P  '>>'  ']' '/' @  Eo ,  Ei  '/' '[   ' '<<'  \u03b2 ,  '/' COMM  \u03a6  '>>' ']' ']'\") : bi_scope.\n\n(** Lemmas about AU *)\nSection lemmas.\n  Context `{BiFUpd PROP} {TA TB : tele}.\n  Implicit Types (\u03b1 : TA \u2192 PROP) (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP) (P : PROP).\n\n  Local Existing Instances atomic1_update_pre_mono atomic_update_pre_mono.\n\n  (* Can't be in the section above as that fixes the parameters *)\n  Global Instance atomic1_acc_ne Eo Ei n :\n    Proper (\n        pointwise_relation TA (dist n) ==>\n        dist n ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        dist n\n    ) (atomic1_acc (PROP:=PROP) Eo Ei).\n  Proof. solve_proper. Qed.\n\n  Global Instance atomic1_update_ne Eo Ei n :\n    Proper (\n        pointwise_relation TA (dist n) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        dist n\n    ) (atomic1_update (PROP:=PROP) Eo Ei).\n  Proof.\n    rewrite atomic1_update_eq /atomic1_update_def /atomic1_update_pre. solve_proper.\n  Qed.\n\n  (* AU implies AU1 *)\n  Lemma atomic_update_atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 :\n    atomic_update Eo Ei \u03b1 \u03b2 \u03a6 -\u2217 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6.\n  Proof.\n    rewrite atomic.atomic_update_unseal atomic1_update_eq /atomic1_update_def /=.\n    iIntros \"HAU\".\n    iApply (greatest_fixpoint_coiter _ (\u03bb _, atomic.atomic_update_def Eo Ei \u03b1 \u03b2 \u03a6)); last done.\n    iIntros \"!> *\". rewrite {1}/atomic.atomic_update_def /= greatest_fixpoint_unfold.\n    by iApply atomic_acc_atomic1_acc.\n  Qed.\n\n  Lemma atomic1_update_mask_weaken Eo1 Eo2 Ei \u03b1 \u03b2 \u03a6 :\n    Eo1 \u2286 Eo2 \u2192\n    atomic1_update Eo1 Ei \u03b1 \u03b2 \u03a6 -\u2217 atomic1_update Eo2 Ei \u03b1 \u03b2 \u03a6.\n  Proof.\n    rewrite atomic1_update_eq {2}/atomic1_update_def /=.\n    iIntros (Heo) \"HAU\".\n    iApply (greatest_fixpoint_coiter _ (\u03bb _, atomic1_update_def Eo1 Ei \u03b1 \u03b2 \u03a6)); last done.\n    iIntros \"!> *\". rewrite {1}/atomic1_update_def /= greatest_fixpoint_unfold.\n    iApply atomic1_acc_mask_weaken. done.\n  Qed.\n\n  (** The elimination form: an atomic accessor *)\n  Lemma aupd1_aacc Eo Ei \u03b1 \u03b2 \u03a6 :\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 -\u2217\n    atomic1_acc Eo Ei \u03b1 (atomic1_update Eo Ei \u03b1 \u03b2 \u03a6) \u03b2 \u03a6.\n  Proof using Type*.\n    rewrite atomic1_update_eq {1}/atomic1_update_def /=. iIntros \"HUpd\".\n    iPoseProof (greatest_fixpoint_unfold_1 with \"HUpd\") as \"HUpd\". done.\n  Qed.\n\n  (* This lets you eliminate atomic updates with iMod. *)\n  Global Instance elim_mod_aupd1 \u03c6 Eo Ei E \u03b1 \u03b2 \u03a6 Q Q' :\n    (\u2200 R, ElimModal \u03c6 false false (|={E,Ei}=> R) R Q Q') \u2192\n    ElimModal (\u03c6 \u2227 Eo \u2286 E) false false\n              (atomic1_update Eo Ei \u03b1 \u03b2 \u03a6)\n              (\u2203.. x, \u03b1 x \u2217\n                       (\u03b1 x ={Ei,E}=\u2217 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6) \u2227\n                       \u25b7 (\u2200.. y, \u03b2 x y ={Ei,E}=\u2217 \u03a6 x y))\n              Q Q'.\n  Proof.\n    intros ?. rewrite /ElimModal /= =>-[??]. iIntros \"[AU Hcont]\".\n    iPoseProof (aupd1_aacc with \"AU\") as \"AC\".\n    iMod (atomic1_acc_mask_weaken with \"AC\"); first done.\n    iApply \"Hcont\". done.\n  Qed.\n\n  Lemma aupd1_intro P Q \u03b1 \u03b2 Eo Ei \u03a6 :\n    Affine P \u2192 Persistent P \u2192\n    (P \u2217 Q -\u2217 atomic1_acc Eo Ei \u03b1 Q \u03b2 \u03a6) \u2192\n    P \u2217 Q -\u2217 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6.\n  Proof.\n    rewrite atomic1_update_eq {1}/atomic1_update_def /=.\n    iIntros (?? HAU) \"[#HP HQ]\".\n    iApply (greatest_fixpoint_coiter _ (\u03bb _, Q)); last done. iIntros \"!>\" ([]) \"HQ\".\n    iApply HAU. by iFrame.\n  Qed.\n\n  Lemma aacc1_intro Eo Ei \u03b1 P \u03b2 \u03a6 :\n    Ei \u2286 Eo \u2192 \u22a2 (\u2200.. x, \u03b1 x -\u2217\n    ((\u03b1 x ={Eo}=\u2217 P) \u2227 \u25b7 (\u2200.. y, \u03b2 x y ={Eo}=\u2217 \u03a6 x y)) -\u2217\n    atomic1_acc Eo Ei \u03b1 P \u03b2 \u03a6).\n  Proof.\n    iIntros (? x) \"H\u03b1 Hclose\".\n    iMod fupd_mask_subseteq as \"Hclose'\"; last iModIntro; first set_solver.\n    iExists x. iFrame. iSplitWith \"Hclose\".\n    - iIntros \"H\u03b1\". iMod \"Hclose'\" as \"_\". iApply \"Hclose\". done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iMod \"Hclose'\" as \"_\". iApply \"Hclose\". done.\n  Qed.\n\n  (* This lets you open invariants etc. when the goal is an atomic accessor. *)\n  Global Instance elim_acc_aacc1 {X} E1 E2 Ei (\u03b1' \u03b2' : X \u2192 PROP) \u03b3' \u03b1 \u03b2 Pas \u03a6 :\n    ElimAcc (X:=X) True (fupd E1 E2) (fupd E2 E1) \u03b1' \u03b2' \u03b3'\n            (atomic1_acc E1 Ei \u03b1 Pas \u03b2 \u03a6)\n            (\u03bb x', atomic1_acc E2 Ei \u03b1 (\u03b2' x' \u2217 (\u03b3' x' -\u2217? Pas))%I \u03b2\n                (\u03bb.. x y, \u03b2' x' \u2217 (\u03b3' x' -\u2217? \u03a6 x y))\n            )%I.\n  Proof.\n    (* FIXME: Is there any way to prevent maybe_wand from unfolding?\n       It gets unfolded by env_cbv in the proofmode, ideally we'd like that\n       to happen only if one argument is a constructor. *)\n    iIntros (_) \"Hinner >Hacc\". iDestruct \"Hacc\" as (x') \"[H\u03b1' Hclose]\".\n    iMod (\"Hinner\" with \"H\u03b1'\") as (x) \"[H\u03b1 Hclose']\".\n    iMod (fupd_mask_subseteq) as \"Hclose''\"; last iModIntro; first done.\n    iExists x. iFrame. iSplitWith \"Hclose'\".\n    - iIntros \"H\u03b1\". iMod \"Hclose''\" as \"_\".\n      iMod (\"Hclose'\" with \"H\u03b1\") as \"[H\u03b2' HPas]\".\n      iMod (\"Hclose\" with \"H\u03b2'\") as \"H\u03b3'\".\n      iModIntro. destruct (\u03b3' x'); iApply \"HPas\"; done.\n    - iIntros \"!>\" (y) \"H\u03b2\". iMod \"Hclose''\" as \"_\".\n      iMod (\"Hclose'\" with \"H\u03b2\") as \"H\u03b2'\".\n      (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n      rewrite ->!tele_app_bind. iDestruct \"H\u03b2'\" as \"[H\u03b2' H\u03a6]\".\n      iMod (\"Hclose\" with \"H\u03b2'\") as \"H\u03b3'\".\n      iModIntro. destruct (\u03b3' x'); iApply \"H\u03a6\"; done.\n  Qed.\n\n  (* Everything that fancy updates can eliminate without changing, atomic\n  accessors can eliminate as well.  This is a forwarding instance needed becuase\n  atomic1_acc is becoming opaque. *)\n  Global Instance elim_modal_acc p q \u03c6 P P' Eo Ei \u03b1 Pas \u03b2 \u03a6 :\n    (\u2200 Q, ElimModal \u03c6 p q P P' (|={Eo,Ei}=> Q) (|={Eo,Ei}=> Q)) \u2192\n    ElimModal \u03c6 p q P P'\n              (atomic1_acc Eo Ei \u03b1 Pas \u03b2 \u03a6)\n              (atomic1_acc Eo Ei \u03b1 Pas \u03b2 \u03a6).\n  Proof. intros Helim. apply Helim. Qed.\n\n  Lemma aacc1_aacc {TA' TB' : tele} E1 E1' E2 E3\n        \u03b1 P \u03b2 \u03a6\n        (\u03b1' : TA' \u2192 PROP) P' (\u03b2' \u03a6' : TA' \u2192 TB' \u2192 PROP) :\n    E1' \u2286 E1 \u2192\n    atomic1_acc E1' E2 \u03b1 P \u03b2 \u03a6 -\u2217\n    (\u2200.. x, \u03b1 x -\u2217 atomic1_acc E2 E3 \u03b1' (\u03b1 x \u2217 (P ={E1}=\u2217 P')) \u03b2'\n            (\u03bb.. x' y', (\u03b1 x \u2217 (P ={E1}=\u2217 \u03a6' x' y'))\n                    \u2228 \u2203.. y, \u03b2 x y \u2217 (\u03a6 x y ={E1}=\u2217 \u03a6' x' y'))) -\u2217\n    atomic1_acc E1 E3 \u03b1' P' \u03b2' \u03a6'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\".\n    iMod (atomic1_acc_mask_weaken with \"Hupd\") as (x) \"[H\u03b1 Hclose]\"; first done.\n    iMod (\"Hstep\" with \"H\u03b1\") as (x') \"[H\u03b1' Hclose']\".\n    iModIntro. iExists x'. iFrame \"H\u03b1'\". iSplit.\n    - iIntros \"H\u03b1'\". iDestruct \"Hclose'\" as \"[Hclose' _]\".\n      iMod (\"Hclose'\" with \"H\u03b1'\") as \"[H\u03b1 Hupd]\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"H\u03b1\"). iApply \"Hupd\". auto.\n    - iIntros \"!>\" (y') \"H\u03b2'\". iDestruct \"Hclose'\" as \"[_ Hclose']\".\n      iMod (\"Hclose'\" with \"H\u03b2'\") as \"Hres\".\n      (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n      rewrite ->!tele_app_bind. iDestruct \"Hres\" as \"[[H\u03b1 H\u03a6']|Hcont]\".\n      + (* Abort the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[Hclose _]\".\n        iMod (\"Hclose\" with \"H\u03b1\") as \"HP\".\n        iApply \"H\u03a6'\". done.\n      + (* Complete the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[_ Hclose]\".\n        iDestruct \"Hcont\" as (y) \"[H\u03b2 H\u03a6']\".\n        iMod (\"Hclose\" with \"H\u03b2\") as \"H\u03a6\".\n        iApply \"H\u03a6'\". done.\n  Qed.\n\n  Lemma aacc1_aupd {TA' TB' : tele} E1 E1' E2 E3\n        \u03b1 \u03b2 \u03a6\n        (\u03b1' : TA' \u2192 PROP) P' (\u03b2' \u03a6' : TA' \u2192 TB' \u2192 PROP) :\n    E1' \u2286 E1 \u2192\n    atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 -\u2217\n    (\u2200.. x, \u03b1 x -\u2217 atomic1_acc E2 E3 \u03b1' (\u03b1 x \u2217 (atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 ={E1}=\u2217 P')) \u03b2'\n            (\u03bb.. x' y', (\u03b1 x \u2217 (atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 ={E1}=\u2217 \u03a6' x' y'))\n                    \u2228 \u2203.. y, \u03b2 x y \u2217 (\u03a6 x y ={E1}=\u2217 \u03a6' x' y'))) -\u2217\n    atomic1_acc E1 E3 \u03b1' P' \u03b2' \u03a6'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc1_aacc with \"[Hupd] Hstep\"); first done.\n    iApply aupd1_aacc; done.\n  Qed.\n\n  Lemma aacc1_aupd_commit {TA' TB' : tele} E1 E1' E2 E3\n        \u03b1 \u03b2 \u03a6\n        (\u03b1' : TA' \u2192 PROP) P' (\u03b2' \u03a6' : TA' \u2192 TB' \u2192 PROP) :\n    E1' \u2286 E1 \u2192\n    atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 -\u2217\n    (\u2200.. x, \u03b1 x -\u2217 atomic1_acc E2 E3 \u03b1' (\u03b1 x \u2217 (atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 ={E1}=\u2217 P')) \u03b2'\n            (\u03bb.. x' y', \u2203.. y, \u03b2 x y \u2217 (\u03a6 x y ={E1}=\u2217 \u03a6' x' y'))) -\u2217\n    atomic1_acc E1 E3 \u03b1' P' \u03b2' \u03a6'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc1_aupd with \"Hupd\"); first done.\n    iIntros (x) \"H\u03b1\". iApply atomic1_acc_wand; last first.\n    { iApply \"Hstep\". done. }\n    (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n    iSplit; first by eauto. iIntros \"!>\" (??) \"?\". rewrite ->!tele_app_bind. by iRight.\n  Qed.\n\n  Lemma aacc1_aupd_abort {TA' TB' : tele} E1 E1' E2 E3\n        \u03b1 \u03b2 \u03a6\n        (\u03b1' : TA' \u2192 PROP) P' (\u03b2' \u03a6' : TA' \u2192 TB' \u2192 PROP) :\n    E1' \u2286 E1 \u2192\n    atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 -\u2217\n    (\u2200.. x, \u03b1 x -\u2217 atomic1_acc E2 E3 \u03b1' (\u03b1 x \u2217 (atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 ={E1}=\u2217 P')) \u03b2'\n            (\u03bb.. x' y', \u03b1 x \u2217 (atomic1_update E1' E2 \u03b1 \u03b2 \u03a6 ={E1}=\u2217 \u03a6' x' y'))) -\u2217\n    atomic1_acc E1 E3 \u03b1' P' \u03b2' \u03a6'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc1_aupd with \"Hupd\"); first done.\n    iIntros (x) \"H\u03b1\". iApply atomic1_acc_wand; last first.\n    { iApply \"Hstep\". done. }\n    (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n    iSplit; first by eauto. iIntros \"!>\" (??) \"?\". rewrite ->!tele_app_bind. by iLeft.\n  Qed.\n\nEnd lemmas.\n\n(** This adds a few TC instances that are not automatically inferred. *)\n  Section atomic.\n  Context `{BiFUpd PROP} {TA TB : tele}.\n  Implicit Types (\u03b1 : TA \u2192 PROP).\n  Implicit Types (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP).\n\n  Global Instance aacc1_proper Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      (\u2261) ==>\n      pointwise_relation TA (pointwise_relation TB (\u2261)) ==>\n      pointwise_relation TA (pointwise_relation TB (\u2261)) ==>\n      (\u2261)\n    ) (atomic1_acc (PROP:=PROP) Eo Ei).\n  Proof. solve_proper. Qed.\n\n  Global Instance aacc1_mono' Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      (\u22a2) ==>\n      pointwise_relation TA (pointwise_relation TB (flip (\u22a2))) ==>\n      pointwise_relation TA (pointwise_relation TB (\u22a2)) ==>\n      (\u22a2)\n    ) (atomic1_acc (PROP:=PROP) Eo Ei).\n  Proof.\n    intros \u03b11 \u03b12 H\u03b1 P1 P2 HP \u03b21 \u03b22 H\u03b2 \u03a61 \u03a62 H\u03a6. rewrite/atomic1_acc.\n    repeat f_equiv; by rewrite ?H\u03b1 ?HP.\n  Qed.\n\n  Global Instance aacc1_flip_mono' Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      flip (\u22a2) ==>\n      pointwise_relation TA (pointwise_relation TB (\u22a2)) ==>\n      pointwise_relation TA (pointwise_relation TB (flip (\u22a2))) ==>\n      flip (\u22a2)\n    ) (atomic1_acc (PROP:=PROP) Eo Ei).\n  Proof. repeat intro. by rewrite -aacc1_mono'. Qed.\n\n  Global Instance aupd1_proper Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      pointwise_relation TA (pointwise_relation TB (\u2261)) ==>\n      pointwise_relation TA (pointwise_relation TB (\u2261)) ==>\n      (\u2261)\n    ) (atomic1_update (PROP:=PROP) Eo Ei).\n  Proof.\n    rewrite atomic1_update_eq /atomic1_update_def /atomic1_update_pre.\n    solve_proper.\n  Qed.\n\n  Global Instance aupd1_mono' Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      pointwise_relation TA (pointwise_relation TB (flip (\u22a2))) ==>\n      pointwise_relation TA (pointwise_relation TB (\u22a2)) ==>\n      (\u22a2)\n    ) (atomic1_update (PROP:=PROP) Eo Ei).\n  Proof.\n    rewrite atomic1_update_eq /atomic1_update_def /atomic1_update_pre.\n    solve_proper.\n  Qed.\n\n  Global Instance aupd1_flip_mono' Eo Ei :\n    Proper (\n      pointwise_relation TA (\u2261) ==>\n      pointwise_relation TA (pointwise_relation TB (\u22a2)) ==>\n      pointwise_relation TA (pointwise_relation TB (flip (\u22a2))) ==>\n      flip (\u22a2)\n    ) (atomic1_update (PROP:=PROP) Eo Ei).\n  Proof. repeat intro. by rewrite -aupd1_mono'. Qed.\n\n  (* TODO: this is duplicated from bedrock.lib.aupd. This should be cleaned up\n    once we unify AU/AC with AU1/AC1. *)\n  (** Learn from an atomic precondition. (To use the bound variables\n    [x], pick [P := \u2203 x, P' x].) *)\n  Lemma aupd1_obs_fupd P Eo Ei \u03b1 \u03b2 \u03a6 :\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u22a2\n    (\u2200.. x, \u03b1 x ={Ei}=\u2217 \u03b1 x \u2217 P) ={Eo}=\u2217 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u2217 P.\n  Proof.\n    iIntros \"AU Obs\". iMod \"AU\" as (x) \"[H\u03b1 Close]\".\n    iMod (\"Obs\" with \"H\u03b1\") as \"[H\u03b1 $]\". by iMod (\"Close\" with \"H\u03b1\") as \"$\".\n  Qed.\n  Lemma aupd1_obs_wand P Eo Ei \u03b1 \u03b2 \u03a6 :\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u22a2\n    (\u2200.. x, \u03b1 x -\u2217 \u03b1 x \u2217 P) ={Eo}=\u2217 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u2217 P.\n  Proof.\n    iIntros \"AU Obs\". iApply (aupd1_obs_fupd with \"AU [Obs]\").\n    iIntros (x) \"H\u03b1 !>\". by iApply \"Obs\".\n  Qed.\n  Lemma aupd1_obs P Eo Ei \u03b1 \u03b2 \u03a6 :\n    (\u2200.. x, \u03b1 x \u22a2 \u03b1 x \u2217 P) \u2192\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u22a2 |={Eo}=> atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u2217 P.\n  Proof.\n    rewrite tforall_forall. iIntros (Hobs) \"AU\".\n    iMod (aupd1_obs_wand P with \"AU []\") as \"$\"; auto.\n    iIntros (x). iApply Hobs.\n  Qed.\nEnd atomic.\n\nTheorem of_envs_alt' {PROP : bi} (\u0394 : envs PROP) :\n  of_envs \u0394 \u22a3\u22a2 (\u231cenvs_wf \u0394\u231d \u2227 \u25a1 [\u2227] env_intuitionistic \u0394) \u2217 [\u2217] env_spatial \u0394.\nProof.\n  rewrite of_envs_alt. iSplit; [iIntros \"[$[$$]]\" | iIntros \"[[$$]$]\"].\nQed.\n\n(** The tactic [iAuIntro1] applies lemma [aupd1_aacc] to change an Iris\n    proof mode goal [P := atomic1_update Eo Ei \u03b1 \u03b2 \u03a6] into [atomic1_acc Eo\n    Ei \u03b1 P \u03b2 \u03a6]. *)\nSection coq_tactic.\n  Import coq_tactics.\n  Context `{BiFUpd PROP} {TA TB : tele}.\n  Implicit Types (\u03b1 : TA \u2192 PROP).\n  Implicit Types (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP).\n\n  Lemma tac_aupd1_intro \u0393p \u0393s n \u03b1 \u03b2 Eo Ei \u03a6 P :\n    P = env_to_prop \u0393s \u2192\n    envs_entails (Envs \u0393p \u0393s n) (atomic1_acc Eo Ei \u03b1 P \u03b2 \u03a6) \u2192\n    envs_entails (Envs \u0393p \u0393s n) (atomic1_update Eo Ei \u03b1 \u03b2 \u03a6).\n  Proof.\n    intros ->. rewrite envs_entails_unseal of_envs_eq /=.\n    setoid_rewrite env_to_prop_sound =>HAU.\n    iIntros \"[#P [#Q R]]\". iStopProof. apply: aupd1_intro.\n    iIntros \"[#P Q]\". iApply HAU.\n    iSplit; first iDestruct \"P\" as \"[$ _]\".\n    iSplit; last done.\n    iDestruct \"P\" as \"[_ $]\".\n  Qed.\nEnd coq_tactic.\n\nLemma test_before `{BiFUpd PROP} {TA TB : tele} Eo Ei \u03b1 (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP) :\n  atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u22a2 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6.\nProof. iIntros \"AU\". Fail iAuIntro. Abort.\n\nTactic Notation \"iAuIntro1\" :=\n  iStartProof; eapply tac_aupd1_intro; [\n    (* P = ...: make the P pretty *) reduction.pm_reflexivity\n  | (* the new proof mode goal *) ].\nLemma test_after `{BiFUpd PROP} {TA TB : tele} Eo Ei \u03b1 (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP) :\n  atomic1_update Eo Ei \u03b1 \u03b2 \u03a6 \u22a2 atomic1_update Eo Ei \u03b1 \u03b2 \u03a6.\nProof. iIntros \"AU\". iAuIntro1. Abort.\n\nTactic Notation \"iAaccIntro1\" \"with\" constr(sel) :=\n  iStartProof; lazymatch goal with\n  | |- environments.envs_entails _ (@atomic1_acc ?PROP ?H ?TA ?TB ?Eo ?Ei ?\u03b1 ?P ?\u03b2 ?\u03a6) =>\n    iApply (@aacc1_intro PROP H TA TB Eo Ei \u03b1 P \u03b2 \u03a6 with sel);\n    first try solve_ndisj; last iSplit\n  | _ => fail \"iAaccIntro1: Goal is not an atomic accessor\"\n  end.\n\n(* From here on, prevent TC search from implicitly unfolding these. *)\n#[global] Typeclasses Opaque atomic1_acc atomic1_update.\n\nSection derived.\n  Context `{BiFUpd PROP} {TA TB : tele}.\n  Implicit Types (\u03b1 : TA \u2192 PROP) (\u03b2 \u03a6 : TA \u2192 TB \u2192 PROP).\n\n  Lemma atomic_update1_ppost_wand Eo Ei \u03b1 \u03b2 \u03a61 \u03a62 :\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a61 \u22a2\n    \u25b7 (\u2200.. x y, \u03a61 x y -\u2217 \u03a62 x y) -\u2217\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a62.\n  Proof.\n    iIntros \"AU1 W\". iAuIntro1; rewrite /atomic1_acc.\n    iMod \"AU1\" as (x) \"[A Cl]\"; iExists _; iFrame \"A\"; iIntros \"!>\".\n    iSplit. { iFrame \"W\". iIntros \"A\". iDestruct \"Cl\" as \"[H _]\". iApply (\"H\" with \"A\"). }\n    iIntros \"!> % B\". iApply (\"W\" with \"(Cl B)\").\n  Qed.\n\n  (* Strictly weaker, but proven for consistency. *)\n  Lemma atomic_update1_weak_ppost_wand Eo Ei \u03b1 \u03b2 \u03a61 \u03a62 :\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a61 \u22a2\n    (\u2200.. x y, \u03a61 x y -\u2217 \u03a62 x y) -\u2217\n    atomic1_update Eo Ei \u03b1 \u03b2 \u03a62.\n  Proof. iIntros \"AU1 W\". iApply (atomic_update1_ppost_wand with \"AU1 W\"). Qed.\nEnd derived.\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/atomic1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18483264299556634}}
{"text": "Require Import Hoare.\nRequire Import Prog ProgMonad.\nRequire Import Pred PredCrash.\nRequire Import SepAuto.\nRequire Import AsyncDisk.\nRequire Import Hashmap.\n\nLemma step_hashmap_subset : forall T m vm hm p m' vm' hm' (v: T),\n    step m vm hm p m' vm' hm' v ->\n    exists l, hashmap_subset l hm hm'.\nProof.\n  inversion 1; eauto.\nQed.\n\nHint Resolve step_hashmap_subset.\n\nLemma hashmap_subset_some_list_trans : forall hm hm' hm'',\n    (exists l, hashmap_subset l hm hm') ->\n    (exists l, hashmap_subset l hm' hm'') ->\n    exists l, hashmap_subset l hm hm''.\nProof.\n  eauto.\nQed.\n\nLemma finished_val_eq : forall T m vm hm (v:T),\n    exists v', Finished m vm hm v = Finished m vm hm v'.\nProof. eauto. Qed.\n\nHint Resolve finished_val_eq.\n\nLemma exec_crashed_hashmap_subset' : forall T m m' vm vm' hm hm' p out,\n  exec m vm hm p out\n  -> (out = Crashed T m' hm' \\/ exists v, out = Finished m' vm' hm' v)\n  -> exists l, hashmap_subset l hm hm'.\nProof.\n  intros.\n  generalize dependent vm'.\n  generalize dependent hm'.\n  generalize dependent m'.\n  induction H; subst; intuition; repeat deex; try congruence;\n    try match goal with\n        | [ H: @eq (outcome _) _ _ |- _ ] =>\n          inversion H; subst\n        end;\n    eauto.\n\n  eauto 7 using hashmap_subset_some_list_trans.\n  eauto 7 using hashmap_subset_some_list_trans.\n\nUnshelve.\n  all: eauto.\nQed.\n\nLemma exec_crashed_hashmap_subset : forall T m m' vm hm hm' p out,\n  exec m vm hm p out\n  -> out = Crashed T m' hm'\n  -> exists l, hashmap_subset l hm hm'.\nProof.\n  intros.\n  eapply exec_crashed_hashmap_subset'; eauto.\n\nUnshelve.\n  all: eauto.\nQed.\n\nLtac solve_hashmap_subset' :=\n  match goal with\n  | [ H: exec _ _ _ _ (Crashed _ _ _), Hpre: forall (_ : hashmap), _ =p=> ?pre _ _ _\n      |- forall (_ : hashmap), _ =p=> ?pre _ _ _ ]\n    => eapply exec_crashed_hashmap_subset in H as H'; eauto;\n        intros;\n        eapply pimpl_trans; try apply Hpre;\n        autorewrite with crash_xform; cancel\n  | [ |- context[hashmap_subset] ]\n        => pred_apply; cancel\n  end; try solve [\n    repeat match goal with\n    | [ H: forall (_ : hashmap), _ =p=> _ |- _ ] => clear H\n    end; solve_hashmap_subset\n  ].\n\nLemma corr3_from_corr2_failed:\n  forall (TF TR: Type) m mr vmr hmr (p: prog TF) (r: prog TR) out\n         (crash: hashmap -> pred) ppre rpre crashdone_p crashdone_r,\n  exec_recover mr vmr hmr p r out\n  -> TF = TR\n  -> possible_crash m mr\n  -> crash hmr m\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> ppre vmr hm' crashdone_p crash)\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> rpre Mem.empty_mem hm' crashdone_r crash)\n  -> {{ ppre }} p\n  -> {{ rpre }} r\n  -> out <> RFailed TF TR.\nProof.\n  intros.\n  generalize dependent m.\n  induction H; intros; try congruence.\n  - edestruct H5; eauto.\n    apply H3. eapply crash_xform_apply; eauto.\n    pred_apply; cancel.\n    repeat (destruct H7; try congruence).\n    repeat (destruct H7; try congruence).\n  - rewrite H0. eapply IHexec_recover; eauto.\n    + eapply exec_crashed_hashmap_subset with (hm':=hm') in H as H'.\n      intros.\n      eapply pimpl_trans; try apply H4.\n      autorewrite with crash_xform; cancel.\n      eauto.\n    + solve_hashmap_subset'.\n    + edestruct H5; eauto.\n      apply H3. eapply crash_xform_apply; eauto.\n      solve_hashmap_subset'.\n      repeat (destruct H9; try congruence).\n      repeat (destruct H9; try congruence).\nQed.\n\nLemma corr3_from_corr2_finished:\n  forall (TF TR: Type) m mr vmr hmr (p: prog TF) (r: prog TR) out\n         (crash: hashmap -> pred) ppre rpre crashdone_p crashdone_r m' vm' hm' v,\n  exec_recover mr vmr hmr p r out\n  -> TF = TR\n  -> possible_crash m mr\n  -> crash hmr m\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> ppre vmr hm' crashdone_p crash)\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> rpre Mem.empty_mem hm' crashdone_r crash)\n  -> {{ ppre }} p\n  -> {{ rpre }} r\n  -> out = RFinished TR m' vm' hm' v\n  -> crashdone_p vm' hm' v m'.\nProof.\n  intros.\n  induction H; try congruence.\n  edestruct H5; eauto.\n  - apply H3. eapply crash_xform_apply; eauto.\n    pred_apply; cancel.\n  - destruct H8. destruct H8. destruct H8. destruct H8.\n    inversion H8. congruence.\n  - repeat (destruct H8; try congruence).\nQed.\n\nLemma corr3_from_corr2_recovered:\n  forall (TF TR: Type) m mr vmr hmr (p: prog TF) (r: prog TR) out\n         (crash: hashmap -> pred) ppre rpre crashdone_p crashdone_r m' vm' hm' v,\n  exec_recover mr vmr hmr p r out\n  -> TF = TR\n  -> possible_crash m mr\n  -> crash hmr m\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> ppre vmr hm' crashdone_p crash)\n  -> (forall hm', crash_xform (crash hm'\n      * [[ exists l, hashmap_subset l hmr hm' ]])\n      =p=> rpre Mem.empty_mem hm' crashdone_r crash)\n  -> {{ ppre }} p\n  -> {{ rpre }} r\n  -> out = RRecovered TF m' vm' hm' v\n  -> crashdone_r vm' hm' v m'.\nProof.\n  intros.\n  generalize dependent m.\n  induction H; intros; try congruence.\n  - eapply corr3_from_corr2_finished; eauto.\n    clear IHexec_recover H2.\n    edestruct H5; eauto.\n    + apply H3. eapply crash_xform_apply; eauto.\n      pred_apply; cancel.\n    + repeat (destruct H2; try congruence).\n    + destruct H2. destruct H2. destruct H2.\n      inversion H2. eauto.\n    + solve_hashmap_subset'.\n    + solve_hashmap_subset'.\n    + congruence.\n  - eapply IHexec_recover; eauto; clear IHexec_recover H2.\n    + solve_hashmap_subset'.\n    + solve_hashmap_subset'.\n    + inversion H7. auto.\n    + edestruct H5; eauto.\n      * apply H3. eapply crash_xform_apply; eauto.\n        solve_hashmap_subset'.\n      * repeat (destruct H2; try congruence).\n      * repeat (destruct H2; try congruence).\nQed.\n\nTheorem corr3_from_corr2: forall TF TR (p: prog TF) (r: prog TR) ppre rpre, {{ ppre }} p\n  -> {{ rpre }} r\n  -> {{ fun vm hm done crashdone => exists crash,\n        ppre vm hm done crash\n        * [[ forall hm',\n          crash_xform (crash hm'\n          * [[ exists l, hashmap_subset l hm hm' ]])\n          =p=> rpre Mem.empty_mem hm' crashdone crash ]] }} p >> r.\nProof.\n  unfold corr3; intros.\n  destruct H1 as [crash H1].\n  destruct_lift H1.\n  inversion H2; subst.\n  - exfalso.\n    edestruct H; eauto; repeat deex; try congruence.\n  - left.\n    repeat eexists.\n    edestruct H; eauto; repeat deex; try congruence.\n  - exfalso.\n    edestruct H; eauto; repeat deex; try congruence.\n    inversion H8; clear H8; subst.\n    eapply corr3_from_corr2_failed; eauto.\n    solve_hashmap_subset'.\n    solve_hashmap_subset'.\n  - edestruct H; eauto; repeat deex; try congruence.\n    inversion H8; clear H8; subst.\n    clear H H1 H2 ppre.\n    right. repeat eexists.\n    eapply corr3_from_corr2_finished; eauto.\n    solve_hashmap_subset'.\n    solve_hashmap_subset'.\n  - edestruct H; eauto; repeat deex; try congruence.\n    inversion H8; clear H8; subst.\n    clear H H1 H2 ppre.\n    right. repeat eexists.\n    eapply corr3_from_corr2_recovered; eauto.\n    solve_hashmap_subset'.\n    solve_hashmap_subset'.\nQed.\n\nTheorem corr3_from_corr2_rx :\n  forall TF TR RF RR (p: prog TF) (r:  prog TR)\n         (rxp : TF -> prog RF) (rxr : TR -> prog RR)\n         ppre rpre,\n  {{ ppre }} Bind p rxp\n  -> {{ rpre }} Bind r rxr\n  -> {{ fun vm hm done crashdone => exists crash,\n        ppre vm hm done crash\n        * [[ forall hm',\n          crash_xform (crash hm'\n          * [[ exists l, hashmap_subset l hm hm' ]])\n          =p=> rpre Mem.empty_mem hm' crashdone crash ]] }} Bind p rxp >> Bind r rxr.\nProof.\n  intros.\n  apply corr3_from_corr2; eauto.\nQed.\n\nLtac eassign_idempred :=\n  match goal with\n  | [ H : crash_xform ?realcrash =p=> crash_xform ?body |- ?realcrash =p=> (_ ?hm') ] =>\n    let t := eval pattern hm' in body in\n    match eval pattern hm' in body with\n    | ?bodyf hm' =>\n      instantiate (1 := (fun hm => (exists p, p * [[ crash_xform p =p=> crash_xform (bodyf hm) ]])%pred))\n    end\n  | [ |- ?body =p=> (_ ?hm) ] =>\n    let t := eval pattern hm in body in\n    match eval pattern hm in body with\n    | ?bodyf hm =>\n      instantiate (1 := (fun hm' => (exists p, p * [[ crash_xform p =p=> crash_xform (bodyf hm') ]])%pred));\n      try (cancel; xform_norm; cancel)\n    end\n  end.\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/Idempotent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18483264299556634}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv While.\nFrom DiSeL\nRequire Import CalculatorProtocol CalculatorInvariant.\nFrom DiSeL\nRequire Import SeqLib.\n\nSection CalculatorRecieve.\n\nVariable l : Label.\n\nVariable f : input -> option nat.\nVariable prec : input -> bool.\n\nVariable cs: seq nid.\nVariable cls : seq nid.\n(* All nodes *)\nNotation nodes := (cs ++ cls).\n(* All nodes are unique *)\nHypothesis Huniq : uniq nodes.\n\n(* Protocol and its transitions *)\n\nNotation cal := (cal_with_inv l f prec cs cls).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\n\nNotation W := (mkWorld cal).\n\n(* Variable d : dstatelet. *)\n(* Hypothesis C : coh cal d. *)\n(* Check proj2 C. *)\n(* Check cal_inv_resp _ _ _ _ _ _ _ _ _ _ _ _ (proj1 C)(proj2 C). *)\n\nVariable cl : nid.\nHypothesis  Hc : cl \\in cls.\n\nProgram Definition tryrecv_resp_act := act (@tryrecv_action_wrapper W cl\n      (fun k _ t b => (k == l) && (t == resp)) _).\nNext Obligation. by case/andP:H=>/eqP->; rewrite domPt inE/=. Qed.\n\nNotation loc i := (getLocal cl (getStatelet i l)).\nNotation st := (ptr_nat 1).\n\nExport CalculatorProtocol.\n\n(* The following spec relates outstanding requests in\n   pre/postconditions and also ensures that we've got the right\n   answer. *)\nProgram Definition tryrecv_resp :\n  {rs : reqs}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (r : option perm) m =>\n     match r with\n     | Some (from, _, ms) =>\n       let v := head 0 ms in\n       let args := behead ms in\n       exists rs' : reqs,\n       [/\\ loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = Some v]\n     | None => loc m = st :-> rs\n     end) \n  := Do tryrecv_resp_act.    \nNext Obligation.\napply: ghC=>i1 rs L1 C.\napply: act_rule=>i2 R1/=; split; first by case: (rely_coh R1).\nmove=>r i3 i4[Sf]S R3/=; rewrite -(rely_loc' l R1) in L1.\ncase: Sf=>_ _ _ _ /(_ l); clear C=>C.\ncase: S=>C2[|[l'][mid][tms][from][rt][pf][][E]Hin E1 Hw/=].\n- by case=>?->Z; subst i3; rewrite (rely_loc' _ R3).\ncase/andP=>/eqP Z G; subst l'; set d := (getStatelet i2 l) in C E pf Hw *.\nmove=>Z->{r}; subst i3.\nmove: rt pf (coh_s l C2) Hin E1 Hw R3 C G.\nrewrite prEq=>rt pf cohs Hin E1 Hw R3 C G.\ncase: Hin=>/=Z; do?[subst rt|case: Z]=>//Z; subst rt.\nsimpl in E1, Hw, R3; clear G.\nrewrite /cr_wf/= in Hw.\ncase: tms E E1 R3 Hw=>t tms/= E E1 R3 Hw; subst t.\nhave A1: exists s', dsoup d = mid \\\\-> (Msg (TMsg resp tms) from cl true) \\+ s'.\n+ by move/esym/um_eta2: E=>->; exists (free mid (dsoup d)). \ncase: A1=>s' Es.\n\n(* Some auxiliary facts *)\nhave Y : tms = head 0 tms :: behead tms.\n- suff M: exists x xs, tms = x::xs by case:M=>x [xs]E'; subst tms. \n  by case/andP: Hw=>_; case: (tms)=>//x xs _; exists x, xs.\nhave Y' : from \\in cs.\n- case: (proj1 C)=>Cs _ _ _. case: Cs=>Vs/(_ mid)Cs.\n  rewrite Es in Vs Cs; move: (findPtUn Vs)=>Ez.\n  by move: (Cs _ Ez)=>/=; rewrite/cohMsg/==>H; case: H.\n\n(* Using the invariant *)\nmove: ((proj2 C) (proj1 C) cl from (head 0 tms) (behead tms) mid s' Hc Y')=>//=.\nrewrite -!Y; move/(_ Es)=>F.\nrewrite Y in Hw.\n\n(* Proving the change in permissions *)\nhave X: (cl, from, (behead tms)) \\in rs.\n- by case/andP: Hw; rewrite (getStK (proj1 cohs) L1). \nhave P1: valid (dstate d) by apply: (cohVl C).\nhave P2: valid i2 by apply: (cohS (proj2 (rely_coh R1))).\nhave P3: l \\in dom i2 by rewrite -(cohD(proj2(rely_coh R1)))domPt inE/=. \nrewrite (rely_loc' _ R3)/= locE// /cr_step (getStK (proj1 cohs) L1)/=.\nclear R3 Hw P1 P2 P3; exists (remove_elem rs (cl, from, (behead tms))). \nmove: (remove_elem_in rs (cl, from, (behead tms))); rewrite X.\nby rewrite perm_eq_sym=>H.\nQed.\n\n\nDefinition receive_loop_cond (res : option nat) := res == None .\n\nDefinition receive_loop_inv (rs : reqs) :=\n  fun r i =>\n    match r with\n     | Some v =>\n       exists (rs' : reqs) from args ,\n       [/\\ loc i = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = r]\n     | None => loc i = st :-> rs\n    end.\n\nProgram Definition receive_loop' :\n  {(rs : reqs)}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (res : option nat) m => \n     exists (rs' : reqs) v from args ,\n       [/\\ res = Some v, loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = res]) :=\n  Do _ (@while cl W _ _ receive_loop_cond receive_loop_inv _\n        (fun r => Do _ (\n           r <-- tryrecv_resp;\n           match r with\n           | Some (_, _, msg) => ret _ _ (Some (head 0 msg))\n           | None => ret _ _ None\n           end)) None).\n\nNext Obligation. by apply: with_spec x. Defined.\nNext Obligation.\nby move:H; rewrite /receive_loop_inv (rely_loc' _ H0).\nQed.\nNext Obligation.\napply:ghC=>i1 rs[];rewrite /receive_loop_cond.\nmove/eqP=>->/=E1 C1; apply: step; apply: (gh_ex (g:=rs)).\napply: call_rule=>//={r}res i2; case: res; last first.\n- move=>E2 C; apply:ret_rule=>i3 R2.\n  by rewrite /receive_loop_inv (rely_loc' _ R2).\ncase; case=>from v msg[rs'][E2]P F C2.\napply:ret_rule=>i3 R2; rewrite /receive_loop_inv (rely_loc' _ R2).\nby exists rs', from, (behead msg).\nQed.\n\nNext Obligation.\napply: ghC=>i rs E1 C1; apply: (gh_ex (g:=rs)).\napply: call_rule=>//res m[].\nrewrite /receive_loop_cond; case: res=>//=v _.\nmove=>[rs'][from][args][E2]Hp F C2.\nby exists rs', v, from, args. \nQed.\n\n(* Blocking receive-loop that always returns a result (but may not\n   terminate) *)\nProgram Definition blocking_receive_resp :\n  {(rs : reqs)}, DHT [cl, W]\n  (fun i => loc i = st :-> rs,\n   fun (res :  nat) m => \n     exists (rs': reqs) from args ,\n       [/\\ loc m = st :-> rs',\n        perm_eq rs ((cl, from, args) :: rs') &\n        f args = Some res]) :=\n  Do _ (r <-- receive_loop';\n        match r with\n        | Some res => ret _ _ res\n        | None => ret _ _ 0\n        end).\nNext Obligation.\napply: ghC=>i rs E1 C1; apply: step; apply: (gh_ex (g:=rs)).\napply: call_rule=>//res i2[rs'][v][from][args][Z]E2 H1 H2.\nsubst res=>C2; apply: ret_rule=>i3 R2.\nby exists rs', from, args; rewrite (rely_loc' _ R2).\nQed.\n\n(* Simple send_transition *)\n\nDefinition client_send_trans :=\n  ProtocolWithInvariant.snd_transI (s2 l f prec cs cls).\n\nProgram Definition send_request server args :=\n  act (@send_action_wrapper W cal cl l (prEq cal) client_send_trans _\n                            args server).\nNext Obligation. by rewrite InE; right; rewrite InE. Qed.\n\n\nProgram Definition compute_f (server : nid) (args: seq nat) : \n  DHT [cl, W]\n  (fun i =>\n     [/\\ loc i = st :-> ([::] : reqs),\n      prec args & server \\in cs],\n   fun (res : nat) m => loc m = st :-> ([::] : reqs) /\\\n                        f args = Some res) :=\n  Do _ (send_request server args;;\n        blocking_receive_resp).\nNext Obligation.\nmove=>i1/=[E1 H2 H3]. \napply: step; apply: act_rule=>i2 R1.\ncase: (rely_coh R1)=>_ C2.\nhave C': coh cal (getStatelet i2 l) by case: C2=>_ _ _ _/(_ l);rewrite prEq.\nsplit=>//=.\n- split=>//=.\n  + by split=>//; case: C'. \n  + rewrite/Actions.can_send -(cohD C2)/=domPt inE/= eqxx.\n    by rewrite mem_cat Hc orbC.\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.\nmove=>y i3 i4[S]/=;case=>Z[b]/=[F]E3 R3; subst y.\ncase: F=>/=F; subst b i3=>/=.\nrewrite -(rely_loc' _ R1) in E1.\nrewrite (getStK _ E1) in R3.\napply: (gh_ex (g:=[:: (cl, server, args)])).\napply: call_rule=>//.\n- move=>C4; rewrite (rely_loc' _ R3) locE//; last by apply: (cohVl C').\n  + by rewrite -(cohD C2) domPt inE/=.\n  by apply: (cohS C2).\nclear R3=>v i5[rs'][from][args'][E5]P5 R C.  \nsuff X: args = args' /\\ rs' = [::] by case: X=>Z X; subst args' rs'.  \nsuff X': rs' = [::].\n- subst rs'; split=>//; move/perm_eq_mem: P5=>P5. \n  move/P5: (cl, server, args).\n  by rewrite inE eqxx inE/==>/esym/eqP; case=>_->.\nby case/perm_eq_size: P5=>/esym/size0nil. \nQed.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n5 person-hours\n\n*)\n(**************************************************)\n\n\n(* More elaborated client program, compting a list of values *)\n\nDefinition compute_list_spec server ys :=\n  forall (xs_acc : (seq input) * (seq (input * nat))),\n  DHT [cl, W]\n   (fun i =>\n     let: (xs, acc) := xs_acc in         \n     [/\\ loc i = st :-> ([::] : reqs),\n      all prec xs,\n      all (fun e => f e.1 == Some e.2) acc,\n      ys = map fst acc ++ xs &\n      server \\in cs],\n   fun (res : seq (input * nat)) m =>\n     [/\\ loc m = st :-> ([::] : reqs),\n      all (fun e => f e.1 == Some e.2) res &\n      ys = map fst res]).\n\nProgram Definition compute_list_f server (xs : seq input) :\n  DHT [cl, W]\n   (fun i =>\n     [/\\ loc i = st :-> ([::] : reqs),\n      all prec xs &\n      server \\in cs],\n   fun (res : seq (input * nat)) m =>\n     [/\\ loc m = st :-> ([::] : reqs),\n      all (fun e => f e.1 == Some e.2) res &\n      xs = map fst res])\n  :=\n  Do (ffix (fun (rec : compute_list_spec server xs) xsa =>\n    Do _ (let: (xs, acc) := xsa in         \n          if xs is x :: xs' \n          then r <-- compute_f server x;\n               let: acc' := rcons acc (x, r) in\n               rec (xs', acc') \n          else ret _ _ acc)) (xs, [::])). \n\nNext Obligation.\nmove=>i1/=[L1]; move:l0 l4=>zs acc H1 H2 H3 H4.\ncase: zs H1 H3=>//=[_|z zs/andP[H1]H5] H3. \n- by rewrite cats0 in H3;\n  apply: ret_rule=>i2 R1; split=>//; rewrite ?(rely_loc' _ R1)//.\napply: step; apply: call_rule=>//r i2[L2]F C2.\napply: call_rule=>//_; split=>//; first by rewrite all_rcons/= F eqxx.\nby rewrite map_rcons/= -cats1 -catA cat_cons/=.\nQed.\n\nNext Obligation.\nby move=>i1/=[L1]??; apply: call_rule=>//; rewrite cats0.\nQed.\n\nEnd CalculatorRecieve.\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/CalculatorClientLib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.1847664065288079}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.RefinementCommonDefinitions.\n\nRequire Import VerdiRaft.PrevLogCandidateEntriesTermInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\n\nRequire Import VerdiRaft.PrevLogLeaderSublogInterface.\n\n#[global]\nHint Extern 4 (@BaseParams) => apply base_params : typeclass_instances.\n#[global]\nHint Extern 4 (@MultiParams _) => apply multi_params : typeclass_instances.\n#[global]\nHint Extern 4 (@FailureParams _ _) => apply failure_params : typeclass_instances.\n\n\nSection PrevLogLeaderSublogProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Context {lsi : leader_sublog_interface}.\n\n  Context {plceti : prevLog_candidateEntriesTerm_interface}.\n\n  Lemma prevLog_leader_sublog_init :\n   raft_net_invariant_init prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_init, prevLog_leader_sublog.\n    simpl. intuition.\n  Qed.\n\n  Lemma handleClientRequest_log_In :\n    forall h st client id c out st' ps e,\n      handleClientRequest h st client id c = (out, st', ps) ->\n      In e (log st) -> In e (log st').\n  Proof using. \n    intros.\n    find_apply_lem_hyp handleClientRequest_log.\n    intuition.\n    - find_rewrite. auto.\n    - break_exists. intuition. find_rewrite. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_client_request :\n    raft_net_invariant_client_request prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_client_request, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp handleClientRequest_type. break_and.\n      repeat find_rewrite.\n      eapply_prop_hyp In In; eauto.\n      break_exists_exists. intuition.\n      eauto using handleClientRequest_log_In.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. eapply handleClientRequest_no_append_entries; eauto.\n      subst. simpl in *. find_rewrite. eauto 10.\n  Qed.\n\n  Lemma prevLog_leader_sublog_timeout :\n    raft_net_invariant_timeout prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_timeout, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp handleTimeout_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eapply_prop_hyp In In; eauto.\n      break_exists_exists. intuition.\n      erewrite handleTimeout_log_same by eauto.\n      eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. subst. simpl in *.\n      eapply handleTimeout_packets; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntries_type_log :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      type st' = Follower \\/ (type st' = type st /\\ log st' = log st /\\ currentTerm st' = currentTerm st).\n  Proof using. \n    unfold handleAppendEntries.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_append_entries :\n    raft_net_invariant_append_entries prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_append_entries, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleAppendEntries_type_log.\n      intuition.\n      + congruence.\n      + repeat find_rewrite.\n        eapply_prop_hyp In In; eauto.\n    - find_apply_lem_hyp handleAppendEntries_not_append_entries.\n      simpl in *. subst. exfalso. eauto 10.\n  Qed.\n\n  Lemma prevLog_leader_sublog_append_entries_reply :\n    raft_net_invariant_append_entries_reply prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_append_entries_reply, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleAppendEntriesReply_log.\n      find_rewrite.\n      find_copy_apply_lem_hyp handleAppendEntriesReply_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. subst. simpl in *.\n      find_apply_lem_hyp handleAppendEntriesReply_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_request_vote :\n    raft_net_invariant_request_vote prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_request_vote, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleRequestVote_log.\n      find_copy_apply_lem_hyp handleRequestVote_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eauto.\n    - find_apply_lem_hyp handleRequestVote_no_append_entries.\n      simpl in *. subst. exfalso. eauto 10.\n  Qed.\n\n\n  Definition candidateEntriesTerm_lowered (net : network) t p : Prop :=\n    In p (nwPackets net) ->\n    pBody p = RequestVoteReply t true ->\n    currentTerm (nwState net (pDst p)) = t ->\n    wonElection (dedup name_eq_dec (pSrc p :: votesReceived (nwState net (pDst p)))) = true ->\n    type (nwState net (pDst p)) <> Candidate.\n\n  Lemma deghost_packet_exists :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    unfold deghost.\n    simpl.\n    intros.\n    do_in_map.\n    eauto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_lowered' :\n    forall net,\n      prevLog_candidateEntriesTerm net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p p' t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n        In p (nwPackets (deghost net)) ->\n        pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                entries leaderCommit ->\n        0 < prevLogTerm ->\n        candidateEntriesTerm_lowered (deghost net) prevLogTerm p'.\n  Proof using rri. \n    unfold candidateEntriesTerm_lowered,\n           cronies_correct, votes_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n    eapply_prop_hyp votes_nw pBody. concludes.\n    eapply_prop_hyp prevLog_candidateEntriesTerm pBody; auto.\n\n    concludes.\n    unfold candidateEntriesTerm in *. break_exists. break_and.\n\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n\n    simpl in *.\n    break_or_hyp.\n    - apply_prop_hyp cronies_votes In.\n      assert (pDst x = x1) by (eapply_prop one_vote_per_term; eauto).\n      subst. auto.\n    - intro.\n      assert (pDst x = x1).\n      { eapply_prop one_vote_per_term;\n        eapply_prop cronies_votes.\n        - eapply_prop votes_received_cronies; eauto.\n        - repeat find_reverse_rewrite. auto.\n      }\n      subst.\n      concludes. contradiction.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_lowered :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p p' t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n        In p (nwPackets net) ->\n        pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                entries leaderCommit ->\n        0 < prevLogTerm ->\n        candidateEntriesTerm_lowered net prevLogTerm p'.\n  Proof using plceti cci vci rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n\n    eapply prevLog_candidateEntriesTerm_lowered';\n      eauto using prevLog_candidateEntriesTerm_invariant, votes_correct_invariant,\n      cronies_correct_invariant.\n  Qed.\n\n  Lemma handleRequestVoteReply_type_term_won :\n    forall h st src t v st',\n      handleRequestVoteReply h st src t v = st' ->\n      type st' = type st \\/\n      type st' = Follower \\/\n      (v = true /\\\n       wonElection (dedup name_eq_dec (src :: votesReceived st)) = true /\\\n       currentTerm st' = t).\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; subst; simpl in *; auto; do_bool; intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_request_vote_reply :\n    raft_net_invariant_request_vote_reply prevLog_leader_sublog.\n  Proof using plceti cci vci rri. \n    unfold raft_net_invariant_request_vote_reply, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp.\n    find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n    find_rewrite. break_if; eauto.\n    find_copy_apply_lem_hyp handleRequestVoteReply_type.\n    find_copy_apply_lem_hyp handleRequestVoteReply_log.\n    intuition; repeat find_rewrite.\n    - eauto.\n    - discriminate.\n    - exfalso.\n      find_apply_lem_hyp handleRequestVoteReply_type_term_won.\n      intuition; try congruence.\n      eapply prevLog_candidateEntriesTerm_lowered with (p := p0) ; eauto.\n      + congruence.\n      + congruence.\n  Qed.\n\n  Lemma prevLog_leader_sublog_do_leader :\n    raft_net_invariant_do_leader prevLog_leader_sublog.\n  Proof using lsi. \n    unfold raft_net_invariant_do_leader, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp doLeader_type. break_and.\n      find_copy_apply_lem_hyp doLeader_log.\n      repeat find_rewrite. eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and. subst.\n      simpl in *.\n      find_copy_eapply_lem_hyp doLeader_messages; eauto.\n      intuition.\n      + lia.\n      + break_exists. break_and. subst.\n        exists x0. find_apply_lem_hyp findAtIndex_elim. intuition.\n        break_if.\n        * congruence.\n        * pose proof (leader_sublog_invariant_invariant _ ltac:(eauto)).\n          unfold leader_sublog_invariant, leader_sublog_host_invariant in *. break_and.\n          eauto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_do_generic_server :\n    raft_net_invariant_do_generic_server prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_eapply_lem_hyp doGenericServer_type. break_and.\n      find_copy_eapply_lem_hyp doGenericServer_log.\n      repeat find_rewrite.\n      eauto.\n    - find_copy_eapply_lem_hyp doGenericServer_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset, prevLog_leader_sublog.\n    intros.\n    find_apply_hyp_hyp.\n    repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_reboot :\n    raft_net_invariant_reboot prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_reboot, prevLog_leader_sublog, reboot.\n    intros.  subst. simpl in *.\n    repeat find_reverse_higher_order_rewrite.\n\n    match goal with\n    | [ H : context [In _ _], H' : In _ _ |- _ ] =>\n      eapply (H leader) in H'; eauto\n    end.\n    - break_exists_exists. intuition.\n      repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n    - repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n      discriminate.\n    - repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      prevLog_leader_sublog net.\n  Proof using plceti lsi cci vci rri. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply prevLog_leader_sublog_init.\n    - apply prevLog_leader_sublog_client_request.\n    - apply prevLog_leader_sublog_timeout.\n    - apply prevLog_leader_sublog_append_entries.\n    - apply prevLog_leader_sublog_append_entries_reply.\n    - apply prevLog_leader_sublog_request_vote.\n    - apply prevLog_leader_sublog_request_vote_reply.\n    - apply prevLog_leader_sublog_do_leader.\n    - apply prevLog_leader_sublog_do_generic_server.\n    - apply prevLog_leader_sublog_state_same_packet_subset.\n    - apply prevLog_leader_sublog_reboot.\n  Qed.\n\n  Instance pllsi : prevLog_leader_sublog_interface.\n  Proof.\n    constructor.\n    apply prevLog_leader_sublog_invariant.\n  Qed.\nEnd PrevLogLeaderSublogProof.\n", "meta": {"author": "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/PrevLogLeaderSublogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18476640551269896}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq fintype finfun.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\nFrom MicroPolicies\nRequire Import lib.utils common.types symbolic.symbolic symbolic.exec\nifc.labels ifc.common.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport DoNotation.\n\nSection Dev.\n\nLocal Open Scope label_scope.\n\nVariable L : labType.\nVariable mt : machine_types.\nVariable mops : machine_ops mt.\nContext {sregs : syscall_regs mt}.\nContext {addrs : ifc_addrs mt}.\n\nInductive mem_tag :=\n| MemInstr\n| MemData of L.\n\nDefinition option_of_mem_tag t :=\n  match t with\n  | MemInstr => None\n  | MemData l => Some l\n  end.\n\nDefinition mem_tag_of_option t :=\n  match t with\n  | None => MemInstr\n  | Some l => MemData l\n  end.\n\nLemma option_of_mem_tagK : cancel option_of_mem_tag mem_tag_of_option.\nProof. by case. Qed.\n\nDefinition mem_tag_eqMixin := CanEqMixin option_of_mem_tagK.\nCanonical mem_tag_eqType := EqType mem_tag mem_tag_eqMixin.\n\nImport Symbolic.\n\nDefinition ifc_tags := {|\n  pc_tag_type    := [eqType of L];\n  reg_tag_type   := [eqType of L];\n  mem_tag_type   := mem_tag_eqType;\n  entry_tag_type := unit_eqType\n|}.\n\n(** Tag propagation rules. *)\n\nDefinition instr_rules\n  (op : opcode) (tpc : L) (ts : hseq (tag_type ifc_tags) (inputs op)) :\n  option (ovec ifc_tags op) :=\n  let ret := fun rtpc (rt : type_of_result ifc_tags (outputs op)) => Some (@OVec ifc_tags op rtpc rt) in\n  match op, ts, ret with\n  | NOP, _, ret                             => ret tpc tt\n  | CONST, [hseq lold], ret                 => ret tpc \u22a5\n  | MOV, [hseq l; lold], ret                => ret tpc l\n  | BINOP b, [hseq l1; l2; lold], ret       => ret tpc (l1 \u2294 l2)\n  | LOAD, [hseq l1; MemData l2; lold], ret  => ret tpc (l1 \u2294 l2)\n  | STORE, [hseq l1; l2; MemData lold], ret => if l1 \u2294 tpc \u2291 lold then\n                                                 ret tpc (MemData (l1 \u2294 l2 \u2294 tpc))\n                                               else None\n  | JUMP, [hseq l], ret                     => ret (l \u2294 tpc) tt\n  | BNZ, [hseq l], ret                      => ret (l \u2294 tpc) tt\n  | JAL, [hseq l1; lold], ret               => ret (l1 \u2294 tpc) \u22a5\n  | _, _, _                                 => None\n  end.\n\nDefinition transfer (iv : ivec ifc_tags) : option (vovec ifc_tags (op iv)) :=\n  match iv with\n  | IVec (OP op) tpc ti ts =>\n    match ti with\n    | MemInstr => @instr_rules op tpc ts\n    | MemData _ => None\n    end\n  | IVec SERVICE tpc _ _ => Some tt\n  end.\n\n(** The internal state for the IFC policy is simply a sequence of atoms that has\n    been output during execution. *)\n\nRecord int_ifc := IntIFC {\n  outputs : seq (atom (mword mt) L);\n  call_stack : seq (call_frame mt L)\n}.\n\nDefinition tuple_of_int_ifc x :=\n  (outputs x, call_stack x).\n\nDefinition int_ifc_of_tuple x :=\n  IntIFC x.1 x.2.\n\nLemma tuple_of_int_ifcK : cancel tuple_of_int_ifc int_ifc_of_tuple.\nProof. by case. Qed.\n\nDefinition int_ifc_eqMixin := CanEqMixin tuple_of_int_ifcK.\nCanonical int_ifc_eqType := Eval hnf in EqType int_ifc int_ifc_eqMixin.\n\nGlobal Instance sym_ifc : params := {\n  ttypes := ifc_tags;\n\n  transfer := transfer;\n\n  internal_state := int_ifc_eqType\n}.\n\nLocal Notation state := (@Symbolic.state mt sym_ifc).\n\nImplicit Types st : state.\n\n(* Note that we often need to adjust the tag on the caller pc because it may be\n   lower than the one on the current pc; for example, if we jump to the service\n   via BNZ instead of JAL. *)\n\nDefinition return_fun st : option state :=\n  if call_stack (internal st) is cf :: stk then\n    do! retv <- regs st syscall_ret;\n    do! rs' <- updm (cf_regs cf) syscall_ret (vala retv)@(taga (pc st) \u2294 taga retv);\n    Some (State (mem st) rs' (cf_pc cf)\n                {| outputs := outputs (internal st);\n                   call_stack := stk |})\n  else None.\n\nDefinition call_fun st : option state :=\n  do! caller_pc <- regs st ra;\n  let caller_pc := (vala caller_pc)@(taga caller_pc \u2294 taga (pc st)) in\n  do! called_pc <- regs st syscall_arg1;\n  Some (State (mem st) (regs st)\n              (vala called_pc)@(taga called_pc \u2294 taga caller_pc)\n              {| outputs := outputs (internal st);\n                 call_stack :=\n                   CallFrame caller_pc (regs st)\n                   :: call_stack (internal st)\n              |}).\n\nDefinition output_fun st : option state :=\n  do! raddr <- regs st ra;\n  let r_pc  := taga raddr \u2294 taga (pc st) in\n  let raddr := (vala raddr)@r_pc in\n  do! out   <- regs st syscall_arg1;\n  let r_out := taga out in\n  Some (State (mem st) (regs st) raddr\n              {| outputs := rcons (outputs (internal st))\n                                  (vala out)@(taga (pc st) \u2294 r_out);\n                 call_stack := call_stack (internal st)\n              |}).\n\nDefinition ifc_syscalls : syscall_table mt :=\n  [fmap\n     (return_addr, (Syscall tt return_fun));\n     (call_addr, (Syscall tt call_fun));\n     (output_addr, (Syscall tt output_fun))\n  ].\n\nDefinition trace n st :=\n  let st' := iter n (fun st' => odflt st' (stepf ifc_syscalls st')) st in\n  drop (size (outputs (internal st))) (outputs (internal st')).\n\nLocal Notation step  := (@Symbolic.step mt mops sym_ifc ifc_syscalls).\nLocal Notation ratom := (atom (mword mt) (tag_type ifc_tags R)).\nLocal Notation matom := (atom (mword mt) (tag_type ifc_tags M)).\n\nHint Unfold stepf.\nHint Unfold next_state_pc.\nHint Unfold next_state_reg.\nHint Unfold next_state_reg_and_pc.\nHint Unfold next_state.\n\nLtac step_event_cat :=\n  simpl in *; repeat autounfold;\n  intros; subst; simpl in *;\n  repeat match goal with\n  | t : (_ * _)%type |- _ => destruct t; simpl in *\n  end;\n  match_inv; simpl; exists [::]; rewrite cats0.\n\nLemma step_event_cat s s' :\n  step s s' ->\n  exists t, outputs (internal s') = outputs (internal s) ++ t.\nProof.\n  case; try by step_event_cat.\n  move=> /= m rs pc sc rl [t stk] -> {s} _.\n  rewrite /ifc_syscalls /run_syscall mkfmapE //=.\n  case: ifP=> [_ [<-] {sc}|_] /=.\n    rewrite /return_fun /= => e; match_inv=> /=.\n    by exists [::]; rewrite cats0.\n  case: ifP=> [_ [<-] {sc}|_] /=.\n    rewrite /call_fun /= => e; match_inv=> /=.\n    by exists [::]; rewrite cats0.\n  case: ifP=> [_ [<-] {sc}|_] //=.\n  rewrite /output_fun /= => e; match_inv=> /=.\n  by rewrite -cats1; eexists; eauto.\nQed.\n\nEnd Dev.\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/ifc/symbolic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.1847663980705468}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base base_extra reg mem pagetable mailbox.\nFrom HypVeri Require Import machine_extra lifting rules.rules_base.\nFrom HypVeri.lang Require Import lang_extra reg_extra.\n\nSection nop.\n\nContext `{hypparams: HypervisorParameters}.\nContext `{vmG: !gen_VMG \u03a3}.\n\nLemma nop {E i w1 q s p_tx} a :\n  decode_instruction w1 = Some Nop ->\n  (tpa a) \u2208 s ->\n  (tpa a) \u2260 p_tx ->\n  {SS{{ \u25b7 (PC @@ i ->r a)\n        \u2217 \u25b7 (a ->a w1)\n        \u2217 \u25b7 (i -@{ q }A> s)\n        \u2217 \u25b7 (TX@ i := p_tx)}}}\n    ExecI @ i ; E\n  {{{ RET (false, ExecI); PC @@ i ->r (a ^+ 1)%f\n                  \u2217 a ->a w1\n                  \u2217 i -@{ q }A> s\n                  \u2217 TX@ i := p_tx}}}.\nProof.\n  iIntros (Hdecode Hin Hnottx \u03d5) \"(>Hpc & >Hapc & >Hacc & >tx) H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  iDestruct \"H\u03c3\" as \"(H1 & Hmem & Hreg & Hmb & ? & ? & Haccess & H2)\".\n  pose proof (decode_instruction_valid w1 _ Hdecode) as Hvalidinstr.\n  inversion Hvalidinstr as [| | | | | | | | | | |].\n  (* valid regs *)\n  iDestruct ((gen_reg_valid1 PC i a Hcur) with \"Hreg Hpc\") as \"%HPC\".\n  (* valid pt *)\n  iDestruct (access_agree_check_true with \"Haccess Hacc\") as %Hacc;first exact Hin.\n  iDestruct (mb_valid_tx with \"Hmb tx\") as %Htx.\n  subst p_tx.\n  (* valid mem *)\n  iDestruct (gen_mem_valid a w1 with \"Hmem Hapc\") as \"%Hmem\".\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    eapply (reducible_normal i _ a w1); eauto.\n  - (* step *)\n    iModIntro.\n    iIntros (m2 \u03c32) \"[%P PAuth] %HstepP\".\n    eapply (step_ExecI_normal i _ a w1) in HstepP;eauto.\n    remember (exec _ \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec /nop /update_incr_PC in Heqc2.\n    destruct HstepP; subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    rewrite p_upd_pc_mem.\n    all: try rewrite p_upd_pc_pgt //.\n    all: try rewrite p_upd_pc_trans //.\n    all: try rewrite p_upd_pc_mb //.\n    iFrame.\n    (* updated part *)\n    rewrite -> (u_upd_pc_regs _ i a 1); eauto.\n    + iDestruct ((gen_reg_update1_global PC i a (a ^+ 1)%f) with \"Hreg Hpc\") as \">[H\u03c3 Hreg]\"; eauto.\n      iModIntro.\n      iFrame \"H\u03c3\".\n      iSplitL \"PAuth\".\n      * by iExists P.\n      * iSplitL \"\".\n        rewrite /just_scheduled_vms /just_scheduled.\n        assert (filter\n                  (\u03bb id : vmid,\n                          base.negb (scheduled \u03c31 id) &&\n                          scheduled (update_offset_PC \u03c31 1) id = true)\n                  (seq 0 n) = []) as ->.\n        {\n          rewrite /scheduled /machine.scheduler //= /scheduler Hcur.\n          rewrite p_upd_pc_current_vm.\n          rewrite Hcur.\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        assert ((scheduled (update_offset_PC \u03c31 1) i) = true) as ->.\n        {\n          rewrite /scheduled /machine.scheduler //= /scheduler.\n          rewrite p_upd_pc_current_vm.\n          rewrite Hcur.\n          by case_bool_decide.\n        }\n        simpl.\n        iApply \"H\u03d5\".\n        iFrame.\n    + solve_reg_lookup.\nQed.\n\nEnd nop.\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/nop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.18475492797147394}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Map.\nFrom IntMap Require Import Allmaps.\nRequire Import List.\nRequire Import Wf_nat.\n\nRequire Import misc.\nRequire Import bool_fun.\nRequire Import myMap.\nRequire Import config.\nRequire Import alloc.\n\nSection BDD_make.\n\nVariable gc : BDDconfig -> list ad -> BDDconfig.\nHypothesis gc_is_OK : gc_OK gc.\n\n(* The arguments for the make function *)\nVariable cfg : BDDconfig.\nVariable x : BDDvar.\nVariable l r : ad.\nVariable ul : list ad.\n\n(* Conditions on the arguments for the make function *)\nHypothesis cfg_OK : BDDconfig_OK cfg.\nHypothesis ul_OK : used_list_OK cfg ul.\nHypothesis l_used' : used_node' cfg ul l.\nHypothesis r_used' : used_node' cfg ul r.\nHypothesis\n  xl_lt_x :\n    forall (xl : BDDvar) (ll rl : ad),\n    MapGet _ (bs_of_cfg cfg) l = Some (xl, (ll, rl)) ->\n    BDDcompare xl x = Datatypes.Lt.\nHypothesis\n  xr_lt_x :\n    forall (xr : BDDvar) (lr rr : ad),\n    MapGet _ (bs_of_cfg cfg) r = Some (xr, (lr, rr)) ->\n    BDDcompare xr x = Datatypes.Lt.\n\nLemma no_dup :\n MapGet3 ad (fst (snd cfg)) l r x = None ->\n forall (x' : BDDvar) (l' r' a : ad),\n MapGet (BDDvar * (ad * ad)) (bs_of_cfg cfg) a =\n Some (x', (l', r')) -> (x, (l, r)) <> (x', (l', r')).\nProof.\n  unfold not in |- *.  intros.  injection H1.  intros.  rewrite <- H2 in H0.\n  rewrite <- H3 in H0.  rewrite <- H4 in H0.\n  rewrite (proj2 (proj1 (proj2 cfg_OK) x l r a) H0) in H.\n  discriminate.\nQed.\n\nDefinition BDDmake :=\n  if Neqb l r\n  then (cfg, l)\n  else\n   match MapGet3 _ (fst (snd cfg)) l r x with\n   | Some y => (cfg, y)\n   | None => BDDalloc gc cfg x l r ul\n   end.\n\nLemma BDDmake_keeps_config_OK : BDDconfig_OK (fst BDDmake).\nProof.\n  unfold BDDmake in |- *.  elim (sumbool_of_bool (Neqb l r)).  intro y.  rewrite y.\n  assumption.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet3 ad (fst (snd cfg)) l r x)).  intro y0.  elim y0.\n  clear y0.  intros node y0.  rewrite y0.  assumption.  intro y0.  rewrite y0.\n  apply BDDalloc_keeps_config_OK.  assumption.  assumption.  assumption.  \n  assumption.  assumption.  assumption.  assumption.  assumption.  intros.\n  apply no_dup with (a := a).  assumption.  assumption.\nQed.\n\nLemma BDDmake_preserves_used_nodes :\n used_nodes_preserved cfg (fst BDDmake) ul.\nProof.\n  unfold BDDmake in |- *.  elim (sumbool_of_bool (Neqb l r)).  intro y.  rewrite y.\n  apply used_nodes_preserved_refl.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet3 ad (fst (snd cfg)) l r x)).  intro y0.  elim y0.\n  clear y0.  intros node y0.  rewrite y0.  apply used_nodes_preserved_refl.  intro y0.\n  rewrite y0.  apply BDDalloc_preserves_used_nodes.  assumption.  assumption.\n  assumption.\nQed.\n\nLemma BDDmake_node_OK : config_node_OK (fst BDDmake) (snd BDDmake).\nProof.\n  unfold BDDmake in |- *.  elim (sumbool_of_bool (Neqb l r)).  intro y.  rewrite y.\n  unfold config_node_OK in |- *.  apply used_node'_OK_bs with (ul := ul).\n  exact (proj1 cfg_OK).  assumption.  assumption.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet3 ad (fst (snd cfg)) l r x)).  intro y0.  elim y0.\n  clear y0.  intros x0 y0.  rewrite y0.  right.  right.  unfold in_dom in |- *.  simpl in |- *.\n  rewrite (proj1 (proj1 (proj2 cfg_OK) x l r x0) y0).  reflexivity.\n  intro y0.  rewrite y0.  apply BDDalloc_node_OK.  assumption.  assumption.  \n  assumption.  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDmake_bool_fun :\n bool_fun_eq (bool_fun_of_BDD (fst BDDmake) (snd BDDmake))\n   (bool_fun_if x (bool_fun_of_BDD cfg r) (bool_fun_of_BDD cfg l)).\nProof.\n  unfold BDDmake in |- *.  elim (sumbool_of_bool (Neqb l r)).  intro y.  rewrite y.\n  simpl in |- *.  apply bool_fun_eq_sym.  apply bool_fun_if_eq_2.\n  rewrite (Neqb_complete _ _ y).  apply bool_fun_eq_refl.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet3 ad (fst (snd cfg)) l r x)).  intro y0.  elim y0.\n  clear y0.  intros x0 y0.  rewrite y0.  unfold bool_fun_of_BDD in |- *.  simpl in |- *.\n  apply bool_fun_of_BDD_bs_int.  exact (proj1 cfg_OK).  \n  exact (proj1 (proj1 (proj2 cfg_OK) x l r x0) y0).  intro y0.\n  rewrite y0.  unfold bool_fun_of_BDD in |- *.  simpl in |- *.\n  apply\n   bool_fun_eq_trans\n    with\n      (bool_fun_if x\n         (bool_fun_of_BDD_bs (fst (fst (BDDalloc gc cfg x l r ul))) r)\n         (bool_fun_of_BDD_bs (fst (fst (BDDalloc gc cfg x l r ul))) l)).\n  apply bool_fun_of_BDD_bs_int.  apply BDDalloc_keeps_state_OK.  assumption.\n  assumption.  assumption.  assumption.  assumption.  assumption.  assumption.\n  assumption.  apply BDDallocGet.  apply bool_fun_if_preserves_eq.\n  apply used_nodes_preserved'_bs_bool_fun with (ul := ul).  exact (proj1 cfg_OK).\n  apply BDDalloc_keeps_state_OK.  assumption.  assumption.  assumption.  \n  assumption.  assumption.  assumption.  assumption.  assumption.\n  fold (used_nodes_preserved cfg (fst (BDDalloc gc cfg x l r ul)) ul) in |- *.\n  apply BDDalloc_preserves_used_nodes.  assumption.  assumption.  assumption.\n  assumption.  assumption.  apply used_nodes_preserved'_bs_bool_fun with (ul := ul). \n  exact (proj1 cfg_OK).  apply BDDalloc_keeps_state_OK.  assumption.\n  assumption.  assumption.  assumption.  assumption.  assumption.  assumption.  \n  assumption.\n  fold (used_nodes_preserved cfg (fst (BDDalloc gc cfg x l r ul)) ul) in |- *.\n  apply BDDalloc_preserves_used_nodes.  assumption.  assumption.  assumption.\n  assumption.  assumption.\nQed.\n\nLemma BDDmake_node_height_eq :\n Neqb l r = false ->\n Neqb (node_height (fst BDDmake) (snd BDDmake)) (ad_S x) = true.\nProof.\n  intro.  unfold BDDmake in |- *.  rewrite H.\n  elim (option_sum _ (MapGet3 ad (fst (snd cfg)) l r x)).  intro y.  elim y.\n  clear y.  intros x0 y.  rewrite y.  simpl in |- *.  unfold node_height in |- *.  unfold bs_node_height in |- *.\n  rewrite (proj1 (proj1 (proj2 cfg_OK) x l r x0) y).\n  apply Neqb_correct.  intro y.  rewrite y.  unfold node_height in |- *.  unfold bs_node_height in |- *.\n  rewrite (BDDallocGet gc cfg x l r ul).  apply Neqb_correct.\nQed.\n\nLemma BDDmake_node_height_eq_1 :\n Neqb l r = true ->\n Neqb (node_height (fst BDDmake) (snd BDDmake)) (node_height cfg l) = true.\nProof.\n  intro.  unfold BDDmake in |- *.  rewrite H.  apply Neqb_correct.\nQed.\n\nLemma BDDmake_node_height_le :\n Nleb (node_height (fst BDDmake) (snd BDDmake)) (ad_S x) = true.\nProof.\n  elim (sumbool_of_bool (Neqb l r)).  intro y.\n  rewrite\n   (Neqb_complete (node_height (fst BDDmake) (snd BDDmake))\n      (node_height cfg l)).\n  unfold node_height in |- *.  unfold bs_node_height in |- *.  elim (option_sum _ (MapGet _ (fst cfg) l)).\n  intro y0.  elim y0.  intro x0.  elim x0.  intro y1.  intro y2.  elim y2.  intros y3 y4 y5.\n  rewrite y5.  unfold Nleb in |- *.  apply leb_correct.  apply lt_le_weak.\n  apply BDDcompare_lt.  rewrite <- (ad_S_compare y1 x).\n  apply xl_lt_x with (ll := y3) (rl := y4).  assumption.  intro y0.  rewrite y0.\n  reflexivity.  apply BDDmake_node_height_eq_1.  assumption.  intro y.\n  rewrite (Neqb_complete _ _ (BDDmake_node_height_eq y)).  apply Nleb_refl.\nQed.\n\nEnd BDD_make.\n", "meta": {"author": "coq-contribs", "repo": "smc", "sha": "e175520faa82eda0f014d300705612892fc7e778", "save_path": "github-repos/coq/coq-contribs-smc", "path": "github-repos/coq/coq-contribs-smc/smc-e175520faa82eda0f014d300705612892fc7e778/make.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.18472683367247122}}
{"text": "Require Import TestSuite.admit.\nClass Foo.\nDefinition bar `{Foo} (x : Set) := Set.\nInstance: Foo.\nDefinition bar1 := bar nat.\nDefinition bar2 := bar ltac:(admit).\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/3682.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18472682669825868}}
{"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\nRequire Import Crypto.Util.ZRange.\n\nFrom Crypto Require Import IR Stringification.Language AbstractInterpretation.ZRange.\n\nImport ListNotations.\n\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 Zig.\n  Definition comment_module_header_block := List.map (fun line => \"// \" ++ line)%string.\n  Definition comment_block := List.map (fun line => \"// \" ++ line)%string.\n\n  Definition header\n             {language_naming_conventions : language_naming_conventions_opt}\n             {package_namev : package_name_opt}\n             {class_namev : class_name_opt}\n             (machine_wordsize : Z) (internal_private : bool) (private : bool) (prefix : string) (infos : ToString.ident_infos)\n    : list string\n    := ([\"\";\n         \"const std = @import(\"\"std\"\");\";\n         \"const cast = std.meta.cast;\";\n         \"const mode = std.builtin.mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels\"]%string)%list.\n\n  (* Zig natively supports any integer size between 0 and 4096 bits.\n     So, we never need to define our own types. *)\n  Definition int_type_to_string {language_naming_conventions : language_naming_conventions_opt} (t : ToString.int.type) : string :=\n    (if int.is_unsigned t then \"u\" else \"i\") ++ Decimal.Z.to_string(ToString.int.bitwidth_of t).\n\n  Definition primitive_type_to_string {language_naming_conventions : language_naming_conventions_opt} (private : bool) (prefix : 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 => \"\u2124\"\n           end.\n\n  (* Integer literal to string *)\n  Definition int_literal_to_string (prefix : string) (t : IR.type.primitive) (v : BinInt.Z) : string :=\n    match t with\n    | IR.type.Z => HexString.of_Z v (* Zig can automatically figure out the size of integer literals *)\n    | IR.type.Zptr => \"@compilerError(\"\"literal address \" ++ HexString.of_Z v ++ \"\"\");\"\n    end.\n\n  Import IR.Notations.\n\n  Fixpoint arith_to_string\n           {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)\n           (prefix : string) {t} (e : IR.arith_expr t) : string\n    := let special_name_ty name ty := ToString.format_special_function_name_ty internal_private prefix name ty in\n       let special_name name bw := ToString.format_special_function_name internal_private prefix name false(*unsigned*) bw in\n       match e with\n       (* integer literals *)\n       | (IR.literal v @@@ _) => int_literal_to_string prefix IR.type.Z v\n       (* array dereference *)\n       | (IR.List_nth n @@@ IR.Var _ v) => \"(\" ++ v ++ \"[\" ++ Decimal.Z.to_string (Z.of_nat n) ++ \"])\"\n       (* (de)referencing *)\n       | (IR.Addr @@@ IR.Var _ v) => \"&\" ++ v\n       | (IR.Dereference @@@ e) => \"( \" ++ arith_to_string internal_private prefix e ++ \".* )\"\n       (* bitwise operations *)\n       | (IR.Z_shiftr offset @@@ e) =>\n         \"(\" ++ arith_to_string internal_private prefix e ++ \" >> \" ++ Decimal.Z.to_string offset ++ \")\"\n       | (IR.Z_shiftl offset @@@ e) =>\n         \"(\" ++ arith_to_string internal_private prefix e ++ \" << \" ++ Decimal.Z.to_string offset ++ \")\"\n       | (IR.Z_land @@@ (e1, e2)) =>\n         \"(\" ++ arith_to_string internal_private prefix e1 ++ \" & \" ++ arith_to_string internal_private prefix e2 ++ \")\"\n       | (IR.Z_lor @@@ (e1, e2)) =>\n         \"(\" ++ arith_to_string internal_private prefix e1 ++ \" | \" ++ arith_to_string internal_private prefix e2 ++ \")\"\n       | (IR.Z_lxor @@@ (e1, e2)) =>\n         \"(\" ++ arith_to_string internal_private prefix e1 ++ \" ^ \" ++ arith_to_string internal_private prefix e2 ++ \")\"\n       | (IR.Z_lnot _ @@@ e) => \"(~\" ++ arith_to_string internal_private prefix e ++ \")\"\n       (* arithmetic operations *)\n       | (IR.Z_add @@@ (x1, x2)) =>\n         \"(\" ++ arith_to_string internal_private prefix x1 ++ \" + \" ++ arith_to_string internal_private prefix x2 ++ \")\"\n       | (IR.Z_mul @@@ (x1, x2)) =>\n         \"(\" ++ arith_to_string internal_private prefix x1 ++ \" * \" ++ arith_to_string internal_private prefix x2 ++ \")\"\n       | (IR.Z_sub @@@ (x1, x2)) =>\n         \"(\" ++ arith_to_string internal_private prefix x1 ++ \" - \" ++ arith_to_string internal_private prefix x2 ++ \")\"\n       | (IR.Z_bneg @@@ e) => \"(~\" ++ arith_to_string internal_private prefix e ++ \")\"\n       | (IR.Z_mul_split lg2s @@@ args) =>\n         special_name \"mulx\" lg2s ++ \"(\" ++ arith_to_string internal_private prefix args ++ \")\"\n       | (IR.Z_add_with_get_carry lg2s @@@ args) =>\n         special_name \"addcarryx\" lg2s ++ \"(\" ++ arith_to_string internal_private prefix args ++ \")\"\n       | (IR.Z_sub_with_get_borrow lg2s @@@ args) =>\n         special_name \"subborrowx\" lg2s ++ \"(\" ++ arith_to_string internal_private prefix args ++ \")\"\n       | (IR.Z_zselect ty @@@ args) =>\n         special_name_ty \"cmovznz\" ty ++ \"(\" ++ arith_to_string internal_private prefix args ++ \")\"\n       | (IR.Z_value_barrier ty @@@ args) =>\n         special_name_ty \"value_barrier\" ty ++ \"(\" ++ arith_to_string internal_private prefix args ++ \")\"\n       | (IR.Z_static_cast int_t @@@ e) =>\n         \"cast(\" ++ primitive_type_to_string internal_private prefix IR.type.Z (Some int_t) ++ \", \" ++ arith_to_string internal_private prefix e ++ \")\"\n       | IR.Var _ v => v\n       | IR.Pair A B a b => arith_to_string internal_private prefix a ++ \", \" ++ arith_to_string internal_private prefix b\n       | (IR.Z_add_modulo @@@ (x1, x2, x3)) => \"@compilerError(\"\"addmodulo\"\");\"\n       | (IR.List_nth _ @@@ _)\n       | (IR.Addr @@@ _)\n       | (IR.Z_add @@@ _)\n       | (IR.Z_mul @@@ _)\n       | (IR.Z_sub @@@ _)\n       | (IR.Z_land @@@ _)\n       | (IR.Z_lor @@@ _)\n       | (IR.Z_lxor @@@ _)\n       | (IR.Z_add_modulo @@@ _) => \"@compilerError(\"\"bad_arg\"\");\"\n       | IR.TT => \"@compilerError(\"\"tt\"\");\"\n       end%string%Cexpr.\n\n  Definition stmt_to_string\n             {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool)\n             (prefix : string) (e : IR.stmt) : string :=\n    match e with\n    | IR.Call val => arith_to_string internal_private prefix val ++ \";\"\n    | IR.Assign true t sz name val =>\n      (* local non-mutable declaration with initialization *)\n      \"const \" ++ name ++ \" = \" ++ arith_to_string internal_private prefix val ++ \";\"\n    | IR.Assign false _ sz name val =>\n    (* code : name ++ \" = \" ++ arith_to_string internal_private prefix val ++ \";\" *)\n      \"@compilerError(\"\"trying to assign value to non-mutable variable\"\");\"\n    | IR.AssignZPtr name sz val =>\n      name ++ \".* = \" ++ arith_to_string internal_private prefix val ++ \";\"\n    | IR.DeclareVar t sz name =>\n      \"var \" ++ name ++ \": \" ++ primitive_type_to_string internal_private prefix t sz ++ \" = undefined;\"\n    | IR.Comment lines _ =>\n      String.concat String.NewLine (comment_block (ToString.preprocess_comment_block lines))\n    | IR.AssignNth name n val =>\n      name ++ \"[\" ++ Decimal.Z.to_string (Z.of_nat n) ++ \"] = \" ++ arith_to_string internal_private prefix val ++ \";\"\n    end.\n\n  Definition to_strings {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) (e : IR.expr) : list string :=\n    List.map (stmt_to_string internal_private prefix) e.\n\n  Import Rewriter.Language.Language.Compilers Crypto.Language.API.Compilers IR.OfPHOAS.\n  Local Notation tZ := (base.type.type_base base.type.Z).\n\n  Inductive Mode := In | Out.\n\n  Fixpoint to_base_arg_list {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) (mode : Mode) {t} : ToString.OfPHOAS.base_var_data t -> list string :=\n    match t return base_var_data t -> _ with\n    | tZ =>\n      let typ := match mode with In => IR.type.Z | Out => IR.type.Zptr end in\n      fun '(n, is_ptr, r) => [n ++ \": \" ++ primitive_type_to_string internal_private prefix typ r]\n    | base.type.prod A B =>\n      fun '(va, vb) => (to_base_arg_list internal_private prefix mode va ++ to_base_arg_list internal_private prefix mode vb)%list\n    | base.type.list tZ =>\n      fun '(n, r, len) =>\n        match mode with\n        | In => (* arrays for inputs are immutable *)\n          [ n ++ \": \" ++\n              \"[\" ++ Decimal.Z.to_string (Z.of_nat len) ++ \"]\" ++ primitive_type_to_string internal_private prefix IR.type.Z r ]\n        | Out => (* arrays for outputs are mutable *)\n          [ n ++ \": \" ++\n              \"*[\" ++ Decimal.Z.to_string (Z.of_nat len) ++ \"]\" ++ primitive_type_to_string internal_private prefix IR.type.Z r ]\n        end\n    | base.type.list _ => fun _ => [\"@compilerError(\"\"complex list\"\");\"]\n    | base.type.option _ => fun _ => [\"@compilerError(\"\"option\"\");\"]\n    | base.type.unit => fun _ => [\"@compilerError(\"\"unit\"\");\"]\n    | base.type.type_base t => fun _ => [\"@compilerError(\"\"\" ++ show false t ++ \"\"\");\"]%string\n    end%string.\n\n  Definition to_arg_list {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) (mode : Mode) {t} : var_data t -> list string :=\n    match t return var_data t -> _ with\n    | type.base t => to_base_arg_list internal_private prefix mode\n    | type.arrow _ _ => fun _ => [\"@compilerError(\"\"arrow\"\");\"]\n    end%string.\n\n  Fixpoint to_arg_list_for_each_lhs_of_arrow {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (prefix : string) {t} : type.for_each_lhs_of_arrow var_data t -> list string\n    := match t return type.for_each_lhs_of_arrow var_data t -> _ with\n       | type.base t => fun _ => nil\n       | type.arrow s d\n         => fun '(x, xs)\n            => to_arg_list internal_private prefix In x ++ to_arg_list_for_each_lhs_of_arrow internal_private prefix xs\n       end%list.\n\n  (** * Language-specific numeric conversions to be passed to the PHOAS -> IR translation *)\n\n  Definition Zig_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  Definition Zig_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               let desired_type' := Some (ToString.int.union ct desired_type) in\n               (Some 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 Zig_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            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            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            => (\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            => (\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 ZigLanguageCasts : LanguageCasts :=\n    {| bin_op_natural_output := Zig_bin_op_natural_output\n       ; bin_op_casts := Zig_bin_op_casts\n       ; un_op_casts := Zig_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 {language_naming_conventions : language_naming_conventions_opt} (internal_private : bool) (private : bool) (prefix : string) (name : string)\n             {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    ((if private then \"fn \" else \"pub fn \") ++ name ++\n      \"(\" ++ String.concat \", \" (to_arg_list internal_private prefix Out rets ++ to_arg_list_for_each_lhs_of_arrow internal_private prefix args) ++\n      \")\" ++ (if private then \" callconv(.Inline) \" else \" \") ++ \"void {\")%string :: ([\"    @setRuntimeSafety(mode == .Debug);\"; \"\"]%string)%list ++ (List.map (fun s => \"    \" ++ s)%string (to_strings internal_private prefix body)) ++ [\"}\"%string]%list.\n\n  (** In Zig, there is no munging of return arguments (they remain\n      passed by pointers), so all variables are live *)\n  Local Instance : consider_retargs_live_opt := fun _ _ _ => true.\n  Local Instance : rename_dead_opt := fun s => 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_private : bool) (private : 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 (((List.map (fun s => if (String.length s =? 0)%nat then \"///\" else (\"/// \" ++ s))%string (comment indata outdata))\n              ++ [\"/// Input Bounds:\"%string]\n              ++ List.map (fun v => \"///   \"%string ++ v)%string (input_bounds_to_string indata inbounds)\n              ++ [\"/// Output Bounds:\"%string]\n              ++ List.map (fun v => \"///   \"%string ++ v)%string (bound_to_string outdata outbounds)\n              ++ to_function_lines internal_private private prefix name (indata, outdata, f))%list,\n           IR.ident_infos.collect_infos f)\n    | inr nil =>\n      inr (\"Unknown internal error in converting \" ++ name ++ \" to Zig\")%string\n    | inr [err] =>\n      inr (\"Error in converting \" ++ name ++ \" to Zig:\" ++ String.NewLine ++ err)%string\n    | inr errs =>\n      inr (\"Errors in converting \" ++ name ++ \" to Zig:\" ++ String.NewLine ++ String.concat String.NewLine errs)%string\n    end.\n\n  Definition OutputZigAPI : ToString.OutputLanguageAPI :=\n    {| ToString.comment_block := comment_block;\n       ToString.comment_file_header_block := comment_module_header_block;\n       ToString.ToFunctionLines := @ToFunctionLines;\n       ToString.header := @header;\n       ToString.footer := fun _ _ _ _ _ _ _ _ => [];\n       ToString.strip_special_infos machine_wordsize infos := infos |}.\n\nEnd Zig.\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/Zig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.18472682669825868}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import LemmaNat Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\n\n\n(**\nCheck get_offset.\nget_offset\n     : int64 -> M int\n\n *)\n\nOpen Scope Z_scope.\n\nSection Get_offset.\n  Context {S: special_blocks}.\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(int64:Type)].\n  Definition res : Type := (int:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := get_offset.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_offset.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (fun x => StateLess _ (int64_correct x))\n                    (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x  => StateLess _ (sint32_correct x).\n\n  Instance correct_function_bpf_verifier_get_offset : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f. unfold get_offset.\n    correct_forward.\n\n    get_invariant _i.\n\n    unfold eval_inv, int64_correct in c0.\n    subst.\n\n    eexists.\n\n    split_and; auto.\n    {\n      unfold exec_expr. repeat\n      match goal with\n      | H: ?X = _ |- context [match ?X with _ => _ end] =>\n        rewrite H\n      end. simpl.\n      unfold Cop.sem_shl, Cop.sem_shift; simpl.\n      change Int64.iwordsize with (Int64.repr 64).\n      change (Int64.ltu (Int64.repr 32) (Int64.repr 64)) with true; simpl.\n      unfold Cop.sem_shr; simpl.\n      unfold Cop.sem_shift; simpl.\n      change Int64.iwordsize with (Int64.repr 64).\n      change (Int64.ltu (Int64.repr 48) (Int64.repr 64)) with true; simpl.\n      unfold Cop.sem_cast; simpl.\n      reflexivity.\n    }\n    {\n      unfold match_res, sint32_correct, BinrBPF.get_offset; simpl.\n      split; [reflexivity | apply Int.signed_range].\n    }\n    unfold Cop.sem_cast; simpl.\n    reflexivity.\n  Qed.\n\nEnd Get_offset.\nClose Scope Z_scope.\n\nExisting Instance correct_function_bpf_verifier_get_offset.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_bpf_verifier_get_offset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.18466528459613524}}
{"text": "Require Import compcert.lib.Axioms.\n\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.semantics_lemmas.\n\nRequire Import concurrency.pos.\nRequire Import concurrency.scheduler.\nRequire Import concurrency.concurrent_machine.\nRequire Import concurrency.addressFiniteMap. (*The finite maps*)\nRequire Import concurrency.threads_lemmas.\nRequire Import concurrency.rmap_locking.\nRequire Import concurrency.lksize.\nRequire Import concurrency.semantics.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n  after Ssreflect eqtype.*)\nRequire Import compcert.common.AST.     (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.lib.Integers.\n\nRequire Import Coq.ZArith.ZArith.\n\n(*From msl get the juice! *)\nRequire Import veric.compcert_rmaps.\nRequire Import veric.juicy_mem.\nRequire Import veric.juicy_mem_lemmas.\nRequire Import veric.juicy_extspec.\nRequire Import veric.jstep.\nRequire Import veric.res_predicates.\n\n\n(**)\nRequire Import veric.res_predicates. (*For the precondition of lock make and free*)\n\n(*  This shoul be replaced by global:\n    Require Import concurrency.lksize.  *)\n\nRequire Import (*compcert_linking*) concurrency.permissions concurrency.threadPool.\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(* given n <= m, returns the list [n-1,...,0] with proofs of < m *)\n    Program Fixpoint enum_from n m (pr : le n m) : list (ordinal m) :=\n      match n with\n        O => nil\n      | S n => (@Ordinal m n ltac:(rewrite <-Heq_n in *; apply (introT leP pr)))\n                :: @enum_from n m ltac:(rewrite <-Heq_n in *; apply le_Sn_le, pr)\n      end.\n\n    Definition enum n := Coq.Lists.List.rev (@enum_from n n (le_refl n)).\n\nAxiom ord_enum_enum:\n  forall n : nat, @eq (list (ordinal n)) (ord_enum n) (enum 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/enums_equality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.18466528459613524}}
{"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 ProD3.examples.cms.verif_Win1.\nRequire Import ProD3.examples.cms.verif_Win2.\nRequire Import ProD3.examples.cms.verif_Win3.\nRequire Import ProD3.examples.cms.verif_CMS_1.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_4_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_5_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_index_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_window_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_3_body) : func_specs.\n\nDefinition P4_bf2_win_md_t_insert (f cf if' : Z) (new_clear_index : Sval) (is : list Sval) :=\n  if f=? cf then\n    P4_bf2_win_md_t (P4Bit 8 CLEAR) (Zrepeat new_clear_index 5)\n  else if f=? if' then\n    P4_bf2_win_md_t (P4Bit 8 INSERT) is\n  else\n    P4_bf2_win_md_t (P4Bit 8 NOOP) is.\n\nDefinition tbl_set_win_insert_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_2\"; \"api_2\"];\n               [\"act_set_clear_win_2\"; \"api_3\"];\n               [\"act_set_clear_win_3\"; \"api_1\"];\n               [\"act_set_clear_win_3\"; \"api_2\"];\n               [\"act_set_clear_win_3\"; \"api_3\"];\n               [\"act_set_clear_win_4\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_2\"];\n               [\"act_set_clear_win_4\"; \"api_3\"];\n               [\"act_set_clear_win_5\"; \"api_1\"];\n               [\"act_set_clear_win_5\"; \"api_2\"];\n               [\"act_set_clear_win_5\"; \"api_3\"]]) []\n    WITH (timer : Z * bool) (clear_index_1 hash_index_1 hash_index_2 hash_index_3 hash_index_4 hash_index_5 : Sval)\n      (H_timer : 0 <= fst timer < frame_tick_tocks * num_frames),\n      PRE\n        (ARG []\n        (MEM [([\"api\"], P4Bit 8 INSERT);\n              ([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"hash_index_4\", hash_index_4);\n                  (\"hash_index_5\", hash_index_5);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (let cf := get_clear_frame timer in\n        let if' := get_insert_frame cf in\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"hash_index_4\", hash_index_4);\n                  (\"hash_index_5\", hash_index_5);\n                  (\"win_1\", P4_bf2_win_md_t_insert 0 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5]);\n                  (\"win_2\", P4_bf2_win_md_t_insert 1 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5]);\n                  (\"win_3\", P4_bf2_win_md_t_insert 2 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5])])]\n        (EXT [])))))%arg_ret_assr.\n\nLemma tbl_set_win_insert_body :\n  func_sound ge tbl_set_win_fd nil tbl_set_win_insert_spec.\nProof.\n  start_function; elim_trivial_cases.\n  - replace (get_clear_frame timer) with 0. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_1_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 1. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_2_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 2. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_3_body.\n    { entailer. }\n    { entailer. }\n  - lia.\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_set_win_insert_body) : func_specs.\n\nDefinition cms_insert := @cms_insert num_frames num_rows num_slots H_num_frames H_num_rows H_num_slots\n  frame_tick_tocks.\n\nDefinition CMS_insert_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (key : Val) (tstamp : Z) (cf : cms num_frames num_rows num_slots),\n      PRE\n        (ARG [eval_val_to_sval key; P4Bit 8 INSERT; P4Bit 48 tstamp; P4Bit_ value_w]\n        (MEM []\n        (EXT [cms_repr p index_w panes rows cf])))\n      POST\n        (ARG_RET [P4Bit_ value_w] ValBaseNull\n        (MEM []\n        (EXT [cms_repr p index_w panes rows (cms_insert cf (Z.odd (tstamp/tick_time)) (hashes key))]))).\n\nLemma CMS_insert_body :\n  func_sound ge CMS_fd nil CMS_insert_spec.\nProof.\n  Time start_function.\n  destruct cf as [[ps ?H] ? ?].\n  unfold cms_repr.\n  cbn [proj1_sig] in *.\n  destruct_list ps.\n  normalize_EXT.\n  Time step.\n  Time step_call tbl_hash_index_1_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_2_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_hash_index_3_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_hash_index_4_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_hash_index_5_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  set (is := (exist _ [hash1 key; hash2 key; hash3 key; hash4 key; hash5 key] eq_refl : listn Z num_rows)).\n  set (clear_is := (exist _ (Zrepeat cms_clear_index num_rows) eq_refl : listn Z num_rows)).\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`is)). {\n    repeat first [apply Forall_cons | apply Forall_nil].\n    all : apply Z.mod_pos_bound; lia.\n  }\n  P4assert (0 <= cms_clear_index < num_slots). {\n    unfold fil_clear_index_repr.\n    Intros i'.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    subst.\n    apply Z.mod_pos_bound.\n    lia.\n  }\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`clear_is)). {\n    repeat first [\n      assumption\n    | constructor\n    ].\n  }\n  step_call tbl_clear_index_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_clear_window_body.\n  { entailer. }\n  Intros _.\n  set (new_timer := update_timer cms_timer (Z.odd (tstamp / tick_time))).\n  P4assert (0 <= fst new_timer < num_frames * frame_tick_tocks).\n  { unfold timer_repr.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    auto.\n  }\n  step_call tbl_set_win_insert_body.\n  { entailer. }\n  { auto. }\n  Intros _.\n  (* unfold and fold in the post condition *)\n  unfold cms_insert, ConModel.cms_insert.\n  unfold proj1_sig.\n  fold new_timer.\n  replace (exist (fun i : list Z => Zlength i = num_rows) (Zrepeat cms_clear_index num_rows) _) with clear_is. 2 : {\n    apply subset_eq_compat. auto.\n  }\n  assert (0 <= get_clear_frame new_timer < num_frames). {\n    unfold ConModel.get_clear_frame.\n    split.\n    - apply Z.div_le_lower_bound; lia.\n    - apply Z.div_lt_upper_bound; lia.\n  }\n  destruct (get_clear_frame new_timer =? 0) eqn:?.\n  { replace (get_clear_frame new_timer) with 0 by lia.\n    step_call verif_Win1.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 1) eqn:?.\n  { replace (get_clear_frame new_timer) with 1 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 2) eqn:?.\n  { replace (get_clear_frame new_timer) with 2 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 3) eqn:?.\n  { replace (get_clear_frame new_timer) with 3 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  lia.\nTime Qed.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/cms/verif_CMS_insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.18466528308318927}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import Relations.\nRequire Import EquivDec.\nRequire Import Equality.\nRequire Import List.\nRequire Import Bool.\nRequire Import Lia.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\n\nRequire Import PromisingArch.promising.Promising.\n\nRequire Import PromisingArch.mapping.RMWLang.\nRequire Import PromisingArch.mapping.RMWPromising.\n\nSet Implicit Arguments.\n\n\nSection SIM_EU.\n  Variable tid: Id.t.\n\n  Definition SIM_EU: Type := RMWExecUnit.t (A:=unit) -> ExecUnit.t (A:=unit) -> Prop.\n\n  Definition _sim_eu (sim_eu: SIM_EU)\n             (eu1_src: RMWExecUnit.t (A:=unit)) (eu1_tgt: ExecUnit.t (A:=unit)): Prop :=\n    (<<TERMINAL:\n      forall (TERMINAL_TGT: ExecUnit.is_terminal eu1_tgt),\n      exists eu2_src,\n        (<<STEPS_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n        (<<TERMINAL_SRC: RMWExecUnit.is_terminal eu2_src>>) /\\\n        (<<MEMORY2: RMWExecUnit.mem eu2_src = ExecUnit.mem eu1_tgt>>)>>) /\\\n    (<<STEP:\n      forall eu2_tgt\n        (STEP_TGT: ExecUnit.state_step tid eu1_tgt eu2_tgt),\n      exists eu2_src,\n        (<<STEP_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n        (<<SIM: sim_eu eu2_src eu2_tgt>>)>>)\n  .\n  #[local] Hint Unfold _sim_eu: paco.\n\n  Lemma sim_eu_monotone: monotone2 _sim_eu.\n  Proof.\n    ii. red in IN. des.\n    red. esplits; eauto. i.\n    exploit STEP; eauto. i. des.\n    esplits; eauto.\n  Qed.\n  #[local] Hint Resolve sim_eu_monotone: paco.\n\n  Definition sim_eu := paco2 _sim_eu bot2.\nEnd SIM_EU.\nArguments sim_eu [_] _ _.\n#[export] Hint Resolve sim_eu_monotone: paco.\n\n\nLemma sim_eu_state_step\n      tid eu1_src eu1_tgt eu2_tgt\n      (SIM: @sim_eu tid eu1_src eu1_tgt)\n      (STEP_TGT: ExecUnit.state_step tid eu1_tgt eu2_tgt):\n  exists eu2_src,\n    (<<STEP_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n    (<<SIM: @sim_eu tid eu2_src eu2_tgt>>).\nProof.\n  punfold SIM. r in SIM. des.\n  exploit STEP; eauto. i. des.\n  esplits; eauto.\n  inv SIM; ss.\nQed.\n\nLemma sim_eu_rtc_state_step\n      tid eu1_src eu1_tgt eu2_tgt\n      (SIM: @sim_eu tid eu1_src eu1_tgt)\n      (STEPS_TGT: rtc (ExecUnit.state_step tid) eu1_tgt eu2_tgt):\n  exists eu2_src,\n    (<<STEP_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n    (<<SIM: @sim_eu tid eu2_src eu2_tgt>>).\nProof.\n  revert eu1_src SIM.\n  induction STEPS_TGT; i; eauto.\n  exploit sim_eu_state_step; try exact H; eauto. i. des.\n  exploit IHSTEPS_TGT; eauto. i. des.\n  esplits; [|eauto]. etrans; eauto.\nQed.\n\nLemma sim_eu_terminal\n      tid eu1_src eu1_tgt\n      (SIM: @sim_eu tid eu1_src eu1_tgt)\n      (TERMINAL_TGT: ExecUnit.is_terminal eu1_tgt):\n  exists eu2_src,\n    (<<STEP_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n    (<<TERMINAL_SRC: RMWExecUnit.is_terminal eu2_src>>).\nProof.\n  punfold SIM. r in SIM. des.\n  exploit TERMINAL; eauto. i. des. eauto.\nQed.\n\n\nFixpoint rmw_to_llsc_stmt (tmp1 tmp2: Id.t) (stmt: rmw_stmtT): list stmtT :=\n  match stmt with\n  | rmw_stmt_instr rmw_instr_skip =>\n      [stmt_instr instr_skip]\n  | rmw_stmt_instr (rmw_instr_assign lhs rhs) =>\n      [stmt_instr (instr_assign lhs rhs)]\n  | rmw_stmt_instr (rmw_instr_load ord res eloc) =>\n      [stmt_instr (instr_load false ord res eloc)]\n  | rmw_stmt_instr (rmw_instr_store ord eloc eval) =>\n      [stmt_instr (instr_store false ord tmp1 eloc eval)]\n  | rmw_stmt_instr (rmw_instr_fadd ordr ordw res eloc eadd) =>\n      [stmt_dowhile\n         [stmt_instr (instr_load true ordr tmp1 eloc);\n          stmt_instr (instr_store true ordw tmp2 eloc (expr_op2 op_add (expr_reg tmp1) eadd))]\n         (expr_reg tmp2);\n       stmt_if (expr_reg tmp1) [] [];\n       stmt_instr (instr_assign res (expr_reg tmp1))]\n  | rmw_stmt_instr (rmw_instr_dmb rr rw wr ww) =>\n      [stmt_instr (instr_barrier (Barrier.dmb rr rw wr ww))]\n  | rmw_stmt_if cond s1 s2 =>\n      [stmt_if cond\n               (List.fold_right (@List.app _) [] (List.map (rmw_to_llsc_stmt tmp1 tmp2) s1))\n               (List.fold_right (@List.app _) [] (List.map (rmw_to_llsc_stmt tmp1 tmp2) s2))]\n  | rmw_stmt_dowhile s cond =>\n      [stmt_dowhile\n         (List.fold_right (@List.app _) [] (List.map (rmw_to_llsc_stmt tmp1 tmp2) s)) cond]\n  end.\n\nDefinition rmw_to_llsc_stmts (tmp1 tmp2: Id.t) (stmts: list rmw_stmtT): list stmtT :=\n  List.fold_right (@List.app _) [] (List.map (rmw_to_llsc_stmt tmp1 tmp2) stmts).\n\nInductive fresh (regs: IdSet.t): forall (stmt: rmw_stmtT), Prop :=\n| fresh_instr\n    i\n    (FRESH: IdSet.disjoint regs (regs_of_rmw_instr i)):\n  fresh regs (rmw_stmt_instr i)\n| fresh_if\n    cond s1 s2\n    (FRESH_COND: IdSet.disjoint regs (regs_of_expr cond))\n    (FRESH_STMT1: List.Forall (fresh regs) s1)\n    (FRESH_STMT2: List.Forall (fresh regs) s2):\n  fresh regs (rmw_stmt_if cond s1 s2)\n| fresh_dowhile\n    s cond\n    (FRESH_STMT: List.Forall (fresh regs) s)\n    (FRESH_COND: IdSet.disjoint regs (regs_of_expr cond)):\n  fresh regs (rmw_stmt_dowhile s cond)\n.\n\nDefinition rmw_to_llsc_program (p_src: rmw_program) (p_tgt: program): Prop :=\n  forall tid, exists tmp1 tmp2,\n    option_rel\n      (fun stmts_src stmts_tgt =>\n         (<<TMP: ~ (tmp1 = tmp2)>>) /\\\n         (<<FRESH: List.Forall (fresh (IdSet.add tmp2 (IdSet.singleton tmp1))) stmts_src>>) /\\\n         (<<STMTS: stmts_tgt = rmw_to_llsc_stmts tmp1 tmp2 stmts_src>>))\n      (IdMap.find tid p_src) (IdMap.find tid p_tgt).\n\n\nVariant sim_val (v_src v_tgt: ValA.t (A:=View.t (A:=unit))): Prop :=\n| sim_val_intro\n    (VAL: ValA.val v_src = ValA.val v_tgt)\n    (ANNOT: le (ValA.annot v_src) (ValA.annot v_tgt))\n.\n#[export] Hint Constructors sim_val: core.\n\n#[export] Program Instance sim_val_PreOrder: PreOrder sim_val.\nNext Obligation.\n  ii. destruct x. econs; ss. refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0.\n  destruct x, y, z. ss.\n  econs; ss; try congr.\n  etrans; eauto.\nQed.\n\nLemma sim_val_sem_op2\n      op2 v1_src v2_src v1_tgt v2_tgt\n      (SIM1: sim_val v1_src v1_tgt)\n      (SIM2: sim_val v2_src v2_tgt):\n  sim_val (sem_op2 op2 v1_src v2_src) (sem_op2 op2 v1_tgt v2_tgt).\nProof.\n  inv SIM1. inv SIM2.\n  unfold sem_op2. econs; s; try congr.\n  eapply join_le; try eapply View.order; ss.\nQed.\n\nDefinition sim_rmap (regs: IdSet.t) (rmap_src rmap_tgt: RMap.t (A:=View.t (A:=unit))): Prop :=\n  forall r (NEQ: ~ IdSet.In r regs),\n    sim_val (RMap.find r rmap_src) (RMap.find r rmap_tgt).\n\n#[export] Program Instance sim_rmap_PreOrder regs: PreOrder (sim_rmap regs).\nNext Obligation.\n  ii. refl.\nQed.\nNext Obligation.\n  ii. etrans; eauto.\nQed.\n\nLemma sim_rmap_sem_expr\n      regs rmap_src rmap_tgt\n      expr\n      (SIM: sim_rmap regs rmap_src rmap_tgt)\n      (EXPR: IdSet.disjoint regs (regs_of_expr expr)):\n  sim_val (sem_expr rmap_src expr) (sem_expr rmap_tgt expr).\nProof.\n  revert EXPR.\n  induction expr; i; ss.\n  - refl.\n  - apply SIM. ii.\n    eapply EXPR; eauto.\n    eapply IdSet.singleton_2. ss.\n  - apply IHexpr in EXPR. inv EXPR.\n    unfold sem_op1. econs; s; congr.\n  - exploit IHexpr1; ii.\n    { eauto using IdSet.union_2. }\n    exploit IHexpr2; ii.\n    { eauto using IdSet.union_3. }\n    inv x0. inv x1.\n    unfold sem_op2. econs; s; try congr.\n    eapply join_le; try eapply View.order; ss.\nQed.\n\nLemma sim_rmap_add\n      regs rmap_src rmap_tgt\n      r v_src v_tgt\n      (RMAP: sim_rmap regs rmap_src rmap_tgt)\n      (VAL: sim_val v_src v_tgt):\n  sim_rmap regs (RMap.add r v_src rmap_src) (RMap.add r v_tgt rmap_tgt).\nProof.\n  ii. do 2 rewrite RMap.add_o.\n  condtac; ss; eauto.\nQed.\n\nLemma sim_rmap_add_l\n      regs rmap_src rmap_tgt\n      r v\n      (RMAP: sim_rmap regs rmap_src rmap_tgt)\n      (IN: IdSet.In r regs):\n  sim_rmap regs (RMap.add r v rmap_src) rmap_tgt.\nProof.\n  ii. rewrite RMap.add_o.\n  condtac; ss; eauto. inversion e. congr.\nQed.\n\nLemma sim_rmap_add_r\n      regs rmap_src rmap_tgt\n      r v\n      (RMAP: sim_rmap regs rmap_src rmap_tgt)\n      (IN: IdSet.In r regs):\n  sim_rmap regs rmap_src (RMap.add r v rmap_tgt).\nProof.\n  ii. rewrite RMap.add_o.\n  condtac; ss; eauto. inversion e. congr.\nQed.\n\nVariant sim_fwditem (fwd_src fwd_tgt: FwdItem.t (A:=unit)): Prop :=\n| sim_fwditem_intro\n    (TS: FwdItem.ts fwd_src = FwdItem.ts fwd_tgt)\n    (VIEW: le (FwdItem.view fwd_src) (FwdItem.view fwd_tgt))\n    (EX: FwdItem.ex fwd_src = FwdItem.ex fwd_tgt)\n.\n#[export] Hint Constructors sim_fwditem: core.\n\n#[export] Program Instance sim_fwditem_PreOrder: PreOrder sim_fwditem.\nNext Obligation.\n  ii. destruct x. econs; ss. refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0.\n  destruct x, y, z. ss.\n  econs; ss; try congr.\n  etrans; eauto.\nQed.\n\nVariant sim_exbank (ex_src ex_tgt: Exbank.t (A:=unit)): Prop :=\n| sim_exbank_intro\n    (LOC: Exbank.loc ex_src = Exbank.loc ex_tgt)\n    (TS: Exbank.ts ex_src = Exbank.ts ex_tgt)\n    (VIEW: le (Exbank.view ex_src) (Exbank.view ex_tgt))\n.\n#[export] Hint Constructors sim_exbank: core.\n\n#[export] Program Instance sim_exbank_PreOrder: PreOrder sim_exbank.\nNext Obligation.\n  ii. destruct x. econs; ss. refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0.\n  destruct x, y, z. ss.\n  econs; ss; try congr.\n  etrans; eauto.\nQed.\n\nLemma sim_fwditem_read_view\n      fwd_src fwd_tgt\n      (SIM: sim_fwditem fwd_src fwd_tgt):\n  forall ts ord,\n    le (FwdItem.read_view fwd_src ts ord) (FwdItem.read_view fwd_tgt ts ord).\nProof.\n  inv SIM. i. unfold FwdItem.read_view.\n  rewrite TS, EX. condtac; ss. refl.\nQed.\n\nVariant sim_local (lc_src lc_tgt: Local.t (A:=unit)): Prop :=\n| sim_local_intro\n    (COH: le lc_src.(Local.coh) lc_tgt.(Local.coh))\n    (VRN: le lc_src.(Local.vrn) lc_tgt.(Local.vrn))\n    (VWN: le lc_src.(Local.vwn) lc_tgt.(Local.vwn))\n    (VRO: le lc_src.(Local.vro) lc_tgt.(Local.vro))\n    (VWO: le lc_src.(Local.vwo) lc_tgt.(Local.vwo))\n    (VCAP: le lc_src.(Local.vcap) lc_tgt.(Local.vcap))\n    (VREL: le lc_src.(Local.vrel) lc_tgt.(Local.vrel))\n    (FWDBANK: forall loc, sim_fwditem (lc_src.(Local.fwdbank) loc) (lc_tgt.(Local.fwdbank) loc))\n    (PROMISES: Local.promises lc_src = Local.promises lc_tgt)\n.\n#[export] Hint Constructors sim_local: core.\n\n#[export] Program Instance sim_local_PreOrder: PreOrder sim_local.\nNext Obligation.\n  ii. destruct x. econs; refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0.\n  destruct x, y, z; ss.\n  econs; ss; try refl; etrans; eauto.\nQed.\n\nLemma le_latest\n      loc ts view_src view_tgt mem\n      (LE: view_src <= view_tgt)\n      (LATEST: Memory.latest loc ts view_tgt mem):\n  Memory.latest loc ts view_src mem.\nProof.\n  unfold Memory.latest, Memory.no_msgs in *. i.\n  eapply LATEST; eauto. etrans; eauto.\nQed.\n\nLtac sim_viewtac :=\n  repeat\n    (try match goal with\n         | [|- orderC _ _] => (try apply View.order); (try apply Time.order)\n         | [|- le ?v ?v] => refl\n         | [|- View._le ?v ?v] => refl\n         | [|- le (join _ _) (join _ _)] => eapply join_le\n         | [|- le (View._join _ _) (View._join _ _)] => eapply join_le\n         | [|- View._le (join _ _) (join _ _)] => eapply join_le\n         | [|- View._le (View._join _ _) (View._join _ _)] => eapply join_le\n         | [|- (join _ _) <= (join _ _)] => eapply join_le\n         | [|- le (ifc ?c _) (ifc ?c _)] =>\n             let cond := fresh \"COND\" in destruct c eqn:cond; ss\n         | [|- View._le (ifc ?c _) (ifc ?c _)] =>\n             let cond := fresh \"COND\" in destruct c eqn:cond; ss\n         | [|- le (fun_add _ _ _) (fun_add _ _ _)] => ii; unfold fun_add\n         | [|- ?rel (if ?c then _ else _) (if ?c then _ else _)] =>\n             let cond := fresh \"COND\" in destruct c eqn:cond; ss\n         | [|- le (FwdItem.read_view _ _ _) (FwdItem.read_view _ _ _)] => eapply sim_fwditem_read_view\n         | [|- View._le (FwdItem.read_view _ _ _) (FwdItem.read_view _ _ _)] => eapply sim_fwditem_read_view\n         | [|- View.ts ?a <= View.ts ?b] =>\n             cut (le a b);\n             try (let h := fresh \"X\" in intro h; apply h)\n         | [H: (le ?a ?b) |- le (?a ?loc) (?b ?loc)] => apply H\n         | [|- sim_fwditem (fun_add _ _ _ _) (fun_add _ _ _ _)] => unfold fun_add\n         | [|- sim_fwditem (FwdItem.mk _ _ _) (FwdItem.mk _ _ _)] => econs\n         end;\n     ss; eauto; i).\n\nLemma sim_local_read\n      ex ord vloc_tgt res_tgt ts lc1_tgt mem_tgt lc2_tgt\n      vloc_src mem_src lc1_src\n      (LOCAL: sim_local lc1_src lc1_tgt)\n      (MEMORY: mem_src = mem_tgt)\n      (VLOC: sim_val vloc_src vloc_tgt)\n      (STEP_TGT: Local.read ex ord vloc_tgt res_tgt ts lc1_tgt mem_tgt lc2_tgt):\n  exists res_src lc2_src,\n    (<<STEP_SRC: Local.read ex ord vloc_src res_src ts lc1_src mem_src lc2_src>>) /\\\n    (<<RES: sim_val res_src res_tgt>>) /\\\n    (<<LOCAL2: sim_local lc2_src lc2_tgt>>) /\\\n    (<<EX_TRUE: ex = true -> option_rel sim_exbank lc2_src.(Local.exbank) lc2_tgt.(Local.exbank)>>) /\\\n    (<<EX_FALSE: ex = false -> lc1_src.(Local.exbank) = lc2_src.(Local.exbank)>>).\nProof.\n  destruct lc1_src, lc1_tgt. inv LOCAL. ss.\n  destruct vloc_src, vloc_tgt. inv VLOC. ss. subst.\n  inv STEP_TGT. ss.\n  esplits.\n  - econs; eauto; ss.\n    + eapply le_latest; try exact COH0. sim_viewtac.\n    + eapply le_latest; try exact LATEST. sim_viewtac.\n  - ss. econs; ss. sim_viewtac.\n  - s. econs; ss; sim_viewtac.\n  - s. i. subst. econs; ss. sim_viewtac.\n  - s. i. subst. ss.\nQed.\n\nLemma sim_local_fulfill\n      ex ord vloc_tgt vval_tgt res ts tid view_pre_tgt lc1_tgt mem_tgt lc2_tgt\n      vloc_src vval_src mem_src lc1_src\n      (LOCAL: sim_local lc1_src lc1_tgt)\n      (MEMORY: mem_src = mem_tgt)\n      (VLOC: sim_val vloc_src vloc_tgt)\n      (VVAL: sim_val vval_src vval_tgt)\n      (EXBANK: ex = true -> option_rel sim_exbank (Local.exbank lc1_src) (Local.exbank lc1_tgt))\n      (STEP_TGT: Local.fulfill ex ord vloc_tgt vval_tgt res ts tid view_pre_tgt lc1_tgt mem_tgt lc2_tgt):\n  exists view_pre_src lc2_src,\n    (<<STEP_SRC: Local.fulfill ex ord vloc_src vval_src res ts tid view_pre_src lc1_src mem_src lc2_src>>) /\\\n    (<<VIEW_PRE_SRC: le view_pre_src view_pre_tgt>>) /\\\n    (<<LOCAL2: sim_local lc2_src lc2_tgt>>) /\\\n    (<<EXBANK: ex = false -> lc1_src.(Local.exbank) = lc2_src.(Local.exbank)>>).\nProof.\n  destruct lc1_src, lc1_tgt. inv LOCAL. ss.\n  destruct vloc_src, vloc_tgt. inv VLOC. ss. subst.\n  destruct vval_src, vval_tgt. inv VVAL. ss. subst.\n  inv STEP_TGT. ss.\n  inv WRITABLE. ss.\n  esplits.\n  - econs; eauto; ss.\n    + econs; eauto; ss.\n      * eapply Nat.le_lt_trans; try exact COH0. sim_viewtac.\n      * eapply Nat.le_lt_trans; try exact EXT. sim_viewtac.\n        destruct ex; ss.\n        destruct exbank, exbank0; ss; try refl.\n        apply EXBANK. ss.\n      * destruct ex; ss. i.\n        exploit EX; eauto. i. des. subst.\n        exploit EXBANK; eauto. i. destruct exbank; ss.\n        esplits; eauto.\n        inv x0. rewrite LOC, TS. ss.\n    + ss.\n  - s. sim_viewtac.\n    destruct ex; ss.\n    destruct exbank, exbank0; ss; try refl.\n    apply EXBANK. ss.\n  - s. econs; ss; sim_viewtac.\n  - s. i. subst. ss.\nQed.\n\nLemma sim_local_isb\n      lc1_tgt lc2_tgt\n      lc1_src\n      (LOCAL: sim_local lc1_src lc1_tgt)\n      (STEP_TGT: Local.isb lc1_tgt lc2_tgt):\n  exists lc2_src,\n    (<<STEP_SRC: Local.isb lc1_src lc2_src>>) /\\\n    (<<LOCAL2: sim_local lc2_src lc2_tgt>>) /\\\n    (<<EXBANK: lc1_src.(Local.exbank) = lc2_src.(Local.exbank)>>).\nProof.\n  destruct lc1_src, lc1_tgt. inv LOCAL. ss.\n  inv STEP_TGT. ss.\n  esplits.\n  - econs; ss.\n  - econs; ss; sim_viewtac.\n  - ss.\nQed.\n\nLemma sim_local_dmb\n      rr rw wr ww lc1_tgt lc2_tgt\n      lc1_src\n      (LOCAL: sim_local lc1_src lc1_tgt)\n      (STEP_TGT: Local.dmb rr rw wr ww lc1_tgt lc2_tgt):\n  exists lc2_src,\n    (<<STEP_SRC: Local.dmb rr rw wr ww lc1_src lc2_src>>) /\\\n    (<<LOCAL2: sim_local lc2_src lc2_tgt>>) /\\\n    (<<EXBANK: lc1_src.(Local.exbank) = lc2_src.(Local.exbank)>>).\nProof.\n  destruct lc1_src, lc1_tgt. inv LOCAL. ss.\n  inv STEP_TGT. ss.\n  esplits.\n  - econs; ss.\n  - econs; ss; sim_viewtac.\n  - ss.\nQed.\n\nLemma sim_local_control\n      (ctrl_tgt: View.t (A:=unit)) lc1_tgt lc2_tgt\n      ctrl_src lc1_src\n      (LOCAL: sim_local lc1_src lc1_tgt)\n      (CTRL: le ctrl_src ctrl_tgt)\n      (STEP_TGT: Local.control ctrl_tgt lc1_tgt lc2_tgt):\n  exists lc2_src,\n    (<<STEP_SRC: Local.control ctrl_src lc1_src lc2_src>>) /\\\n    (<<LOCAL2: sim_local lc2_src lc2_tgt>>) /\\\n    (<<EXBANK: lc1_src.(Local.exbank) = lc2_src.(Local.exbank)>>).\nProof.\n  destruct lc1_src, lc1_tgt. inv LOCAL. ss.\n  inv STEP_TGT. ss.\n  esplits.\n  - econs; ss.\n  - econs; ss; sim_viewtac.\n  - ss.\nQed.\n\nLemma read_sim_local\n      ex ord vloc res ts lc1 mem (lc2: Local.t (A:=unit))\n      (READ: Local.read ex ord vloc res ts lc1 mem lc2):\n  sim_local lc1 lc2.\nProof.\n  inv READ. econs; ss;\n    try apply join_l; try refl.\n  ii. unfold fun_add. condtac; try refl.\n  inversion e. subst. apply join_l.\nQed.\n\nLemma unfold_rmw_to_llsc_stmts\n      tmp1 tmp2 s stmts:\n  rmw_to_llsc_stmts tmp1 tmp2 (s :: stmts) =\n  (rmw_to_llsc_stmt tmp1 tmp2 s) ++ rmw_to_llsc_stmts tmp1 tmp2 stmts.\nProof.\n   ss.\nQed.\n\nLemma fold_right_app\n      A (l1 l2: list (list A)):\n  fold_right (@List.app _) [] l1 ++ fold_right (@List.app _) [] l2 =\n  fold_right (@List.app _) [] (l1 ++ l2).\nProof.\n  induction l1; ss.\n  rewrite <- app_assoc.\n  rewrite IHl1. ss.\nQed.\n\nSection RMWtoLLSC.\n  Hypothesis ARCH: arch = armv8.\n\n  Lemma rmw_to_llsc_sim_eu\n        tid tmp1 tmp2\n        stmts_src rmap_src lc_src mem_src\n        stmts_tgt rmap_tgt lc_tgt mem_tgt\n        (TMP: tmp1 <> tmp2)\n        (FRESH: List.Forall (fresh (IdSet.add tmp2 (IdSet.singleton tmp1))) stmts_src)\n        (STMTS: stmts_tgt = rmw_to_llsc_stmts tmp1 tmp2 stmts_src)\n        (RMAP: sim_rmap (IdSet.add tmp2 (IdSet.singleton tmp1)) rmap_src rmap_tgt)\n        (LOCAL: sim_local lc_src lc_tgt)\n        (EXBANK: lc_src.(Local.exbank) = None)\n        (MEMORY: mem_src = mem_tgt):\n    @sim_eu tid\n            (RMWExecUnit.mk (RMWState.mk stmts_src rmap_src) lc_src mem_src)\n            (ExecUnit.mk (State.mk stmts_tgt rmap_tgt) lc_tgt mem_tgt).\n  Proof.\n    revert_until tmp2.\n    pcofix CIH. i.\n    pfold. red. ss. subst. splits.\n    { (* terminal *)\n      i. red in TERMINAL_TGT. ss. des.\n      esplits; try refl. red. ss. split.\n      - red in TERMINAL_TGT. red. ss.\n        destruct stmts_src; ss.\n        destruct r0; ss. destruct i; ss.\n      - inv LOCAL. congr.\n    }\n\n    i. inv STEP_TGT. inv STEP. ss.\n    destruct stmts_src; try by inv STATE.\n    destruct eu2_tgt as [[stmts2_tgt rmap2_tgt] lc2_tgt mem2_tgt]. ss. subst.\n    destruct r0; cycle 1.\n    { (* if *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      inv FRESH. inv H1.\n      exploit sim_rmap_sem_expr; try exact FRESH_COND; eauto. i. inv x0.\n      exploit sim_local_control; try exact LOCAL; eauto. i. des.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs; ss.\n        - econs 6; eauto.\n      }\n      rewrite VAL. condtac; ss.\n      - right. eapply CIH; eauto.\n        + rewrite List.Forall_app. split; ss.\n        + rewrite fold_right_app.\n          rewrite <- map_app. ss.\n        + congr.\n      - right. eapply CIH; eauto.\n        + rewrite List.Forall_app. split; ss.\n        + rewrite fold_right_app.\n          rewrite <- map_app. ss.\n        + congr.\n    }\n\n    { (* while *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs. ss.\n        - econs 1; eauto.\n      }\n      right. eapply CIH; eauto.\n      - inv FRESH. inv H1.\n        rewrite List.Forall_app. split; ss.\n        repeat (econs; ss).\n      - unfold rmw_to_llsc_stmts.\n        rewrite map_app.\n        rewrite <- fold_right_app. ss.\n    }\n\n    inv FRESH.\n    rewrite unfold_rmw_to_llsc_stmts in STATE.\n    destruct i; ss.\n    { (* skip *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs.\n        - econs 1; eauto.\n      }\n      right. eapply CIH; eauto.\n    }\n\n    { (* assign *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs. ss.\n        - econs 1; ss.\n      }\n      right. eapply CIH; eauto.\n      apply sim_rmap_add; auto.\n      eapply sim_rmap_sem_expr; eauto.\n      inv H1. ii. ss.\n      eapply FRESH; eauto.\n      apply IdSet.add_2. ss.\n    }\n\n    { (* load *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      exploit sim_local_read; try exact LOCAL; eauto.\n      { eapply sim_rmap_sem_expr; eauto.\n        inv H1. ss. ii. eapply FRESH; eauto.\n        apply IdSet.add_2. ss.\n      }\n      i. des.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs; eauto.\n        - econs 2; eauto.\n      }\n      right. eapply CIH; eauto.\n      - apply sim_rmap_add; ss.\n      - rewrite <- EX_FALSE; ss.\n    }\n\n    { (* store *)\n      inv STATE. inv LOCAL0; inv EVENT; cycle 1.\n      { inv STEP. ss. }\n      exploit sim_local_fulfill; try exact LOCAL; eauto.\n      { eapply sim_rmap_sem_expr; eauto.\n        inv H1. ss. ii. eapply FRESH; eauto.\n        apply IdSet.union_2. ss.\n      }\n      { eapply sim_rmap_sem_expr; eauto.\n        inv H1. ss. ii. eapply FRESH; eauto.\n        apply IdSet.union_3. ss.\n      }\n      { i. subst. ss. }\n      i. des.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs; ss.\n        - econs 3; eauto.\n      }\n      right. eapply CIH; eauto.\n      - apply sim_rmap_add_r; ss.\n        apply IdSet.add_2, IdSet.singleton_2. ss.\n      - rewrite <- EXBANK0; ss.\n    }\n\n    { (* fadd *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      esplits; [refl|]. left.\n      rename rmap2_tgt into rmap_tgt.\n      revert rmap_tgt lc_tgt RMAP LOCAL.\n      pcofix CIH_LOOP. i.\n      pfold. red. s. splits.\n      { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n      (* exclusive load *)\n      i. destruct eu2_tgt as [[]].\n      inv STEP_TGT. inv STEP. ss. subst.\n      inv STATE. inv LOCAL0; inv EVENT.\n      esplits; [refl|]. left.\n      pfold. red. s. splits.\n      { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n      (* exclusive store *)\n      i. destruct eu2_tgt as [[]].\n      inv STEP_TGT. inv STEP0. ss. subst.\n      inv STATE. inv LOCAL0; inv EVENT.\n\n      { (* exclusive store - succeed *)\n        clear CIH_LOOP.\n        esplits; [refl|]. left.\n        pfold. red. s. splits.\n        { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n        (* if *)\n        i. destruct eu2_tgt as [[]].\n        inv STEP_TGT. inv STEP1. ss. subst.\n        inv STATE. inv LOCAL0; inv EVENT.\n        condtac; ss.\n        { exfalso. apply c.\n          rewrite RMap.add_o. condtac; try congr.\n          inv STEP0. ss.\n        }\n        clear e X.\n        replace local1 with local0 in *; cycle 1.\n        { destruct local0, local1.\n          inv LC; ss. inv LC2. f_equal.\n          rewrite RMap.add_o. condtac; try congr.\n          inv STEP0. ss. rewrite ARCH. ss.\n          rewrite bot_join; ss.\n          destruct view_pre. destruct annot. ss.\n          apply View.order.\n        }\n        clear local1 LC.\n        esplits; [refl|].\n        left. pfold. red. s. splits.\n        { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n        (* fake branch on read value *)\n        i. destruct eu2_tgt as [[]].\n        inv STEP_TGT. inv STEP1. ss. subst.\n        inv STATE. inv LOCAL0; inv EVENT.\n\n        exploit sim_local_read; try exact STEP; eauto.\n        { eapply sim_rmap_sem_expr; eauto.\n          inv H1. ss. ii. eapply FRESH; eauto.\n          apply IdSet.add_2, IdSet.union_2. ss.\n        }\n        i. des.\n        exploit sim_local_fulfill; try exact STEP0; eauto.\n        { eapply sim_rmap_sem_expr.\n          - eapply sim_rmap_add_r; eauto.\n            apply IdSet.add_2, IdSet.singleton_2. ss.\n          - inv H1. ss. ii.\n            eapply FRESH; eauto.\n            apply IdSet.add_2, IdSet.union_2. ss.\n        }\n        { apply sim_val_sem_op2.\n          - rewrite RMap.add_o. condtac; try congr. eauto.\n          - eapply sim_rmap_sem_expr.\n            + eapply sim_rmap_add_r; eauto.\n              apply IdSet.add_2, IdSet.singleton_2. ss.\n            + inv H1. ss. ii.\n              eapply FRESH; eauto.\n              apply IdSet.add_2, IdSet.union_3. ss.\n        }\n        i. des.\n        exploit sim_local_control; try exact LC; eauto.\n        { rewrite RMap.add_o. condtac; try congr. clear c X.\n          rewrite RMap.add_o. condtac; try congr. clear e X.\n          apply RES.\n        }\n        i. des.\n\n        eexists (RMWExecUnit.mk _ _ _). splits.\n        { econs 2; try refl. econs. econs; s.\n          - econs; eauto.\n          - econs 4; eauto.\n          - ss.\n        }\n        match goal with\n        | [|-context[if ?c then ?s else ?s]] =>\n            replace (if c then s else s) with s by (condtac; ss); s\n        end.\n        left. pfold. red. s. splits.\n        { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n        (* assign *)\n        i. destruct eu2_tgt as [[]].\n        inv STEP_TGT. inv STEP1. ss. subst.\n        inv STATE. inv LOCAL3; inv EVENT.\n        esplits; [refl|].\n        right. eapply CIH; eauto.\n        - rewrite List.app_nil_r. ss.\n        - apply sim_rmap_add.\n          + apply sim_rmap_add_r; cycle 1.\n            { apply IdSet.add_1. ss. }\n            apply sim_rmap_add_r; ss.\n            apply IdSet.add_2. apply IdSet.singleton_2. ss.\n          + unfold sem_expr.\n            rewrite RMap.add_o. condtac; ss.\n            rewrite RMap.add_o. condtac; try congr.\n        - inv STEP_SRC0. ss.\n      }\n\n      { (* exclusive store - fail *)\n        inv STEP0. clear CIH EX.\n        esplits; try refl. left.\n        pfold. red. s. splits.\n        { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n        (* if *)\n        i. destruct eu2_tgt as [[]].\n        inv STEP_TGT. inv STEP0. ss. subst.\n        inv STATE. inv LOCAL0; inv EVENT. inv LC. ss.\n        repeat rewrite RMap.add_eq; ss.\n        replace (join (Local.vcap local) bot) with (Local.vcap local); cycle 1.\n        { rewrite bot_join; ss. apply View.order. }\n        esplits; try refl. left.\n        pfold. red. ss. splits.\n        { i. repeat (red in TERMINAL_TGT; des; ss). }\n\n        (* dowhile *)\n        i. destruct eu2_tgt as [[]].\n        inv STEP_TGT. inv STEP0. ss. subst.\n        inv STATE. inv LOCAL0; inv EVENT. ss.\n        esplits; [refl|]. right.\n        repeat rewrite List.app_nil_r.\n        eapply CIH_LOOP.\n        - apply sim_rmap_add_r; cycle 1.\n          { apply IdSet.add_1. ss. }\n          apply sim_rmap_add_r; ss.\n          apply IdSet.add_2. apply IdSet.singleton_2. ss.\n        - exploit read_sim_local; try exact STEP. i.\n          etrans; eauto. etrans; eauto.\n          destruct local. ss.\n          econs; s; refl.\n      }\n    }\n\n    { (* barrier *)\n      inv STATE. inv LOCAL0; inv EVENT.\n      exploit sim_local_dmb; eauto. i. des.\n      eexists (RMWExecUnit.mk _ _ _). splits.\n      { econs 2; try refl. econs. econs; ss.\n        - econs; ss.\n        - econs 5; eauto.\n      }\n      right. eapply CIH; eauto. congr.\n    }\n  Qed.\n\n\n  Variant sim_sl (tmp1 tmp2: Id.t):\n    forall (sl_src: RMWState.t (A:=View.t (A:=unit)) * Local.t (A:=unit))\n           (sl_tgt: State.t (A:=View.t (A:=unit)) * Local.t (A:=unit)), Prop :=\n    | sim_sl_intro\n        st_src lc_src\n        st_tgt lc_tgt\n        (TMP: tmp1 <> tmp2)\n        (FRESH: List.Forall (fresh (IdSet.add tmp2 (IdSet.singleton tmp1))) st_src.(RMWState.stmts))\n        (STMTS: st_tgt.(State.stmts) = rmw_to_llsc_stmts tmp1 tmp2 st_src.(RMWState.stmts))\n        (RMAP: sim_rmap (IdSet.add tmp2 (IdSet.singleton tmp1)) st_src.(RMWState.rmap) st_tgt.(State.rmap))\n        (LOCAL: sim_local lc_src lc_tgt)\n        (EXBANK: lc_src.(Local.exbank) = None):\n      sim_sl tmp1 tmp2 (st_src, lc_src) (st_tgt, lc_tgt)\n  .\n\n  Variant sim (m_src: RMWMachine.t) (m_tgt: Machine.t): Prop :=\n    | sim_machine_intro\n        (TPOOL: forall tid, exists tmp1 tmp2,\n            opt_rel (sim_sl tmp1 tmp2)\n              (IdMap.find tid (RMWMachine.tpool m_src))\n              (IdMap.find tid (Machine.tpool m_tgt)))\n        (MEMORY: RMWMachine.mem m_src = Machine.mem m_tgt)\n  .\n\n  Lemma sim_sl_sim_eu\n        tid tmp1 tmp2\n        sl_src sl_tgt\n        mem_src mem_tgt\n        (SIM: sim_sl tmp1 tmp2 sl_src sl_tgt)\n        (MEM: mem_src = mem_tgt):\n    @sim_eu tid\n            (RMWExecUnit.mk (fst sl_src) (snd sl_src) mem_src)\n            (ExecUnit.mk (fst sl_tgt) (snd sl_tgt) mem_tgt).\n  Proof.\n    inv SIM. s.\n    destruct st_src, st_tgt. ss.\n    eapply rmw_to_llsc_sim_eu; eauto.\n  Qed.\n\n  Lemma init_sim\n        prog_src prog_tgt\n        (COMPILE: rmw_to_llsc_program prog_src prog_tgt):\n    sim (RMWMachine.init prog_src) (Machine.init prog_tgt).\n  Proof.\n    econs; ss. i.\n    specialize (COMPILE tid). des.\n    exists tmp1, tmp2.\n    do 2 rewrite IdMap.map_spec.\n    destruct (IdMap.find tid prog_src) eqn:FIND_SRC,\n        (IdMap.find tid prog_tgt) eqn:FIND_TGT; ss. des.\n    econs. econs; ss; try refl.\n  Qed.\n\n  Lemma sim_local_promise\n        lc1_src mem1_src\n        lc1_tgt mem1_tgt\n        loc val ts tid\n        lc2_tgt mem2_tgt\n        (SIM1: sim_local lc1_src lc1_tgt)\n        (MEM1: mem1_src = mem1_tgt)\n        (STEP_TGT: Local.promise loc val ts tid lc1_tgt mem1_tgt lc2_tgt mem2_tgt):\n    exists lc2_src mem2_src,\n      (<<STEP_SRC: Local.promise loc val ts tid lc1_src mem1_src lc2_src mem2_src>>) /\\\n      (<<SIM2: sim_local lc2_src lc2_tgt>>) /\\\n      (<<MEM2: mem2_src = mem2_tgt>>).\n  Proof.\n    destruct lc1_src, lc1_tgt. inv SIM1. ss. subst.\n    inv STEP_TGT. ss.\n    esplits.\n    - econs; eauto.\n    - ss.\n    - ss.\n  Qed.\n\n  Lemma sim_sl_promise_step\n        tmp1 tmp2 tid\n        st1_src lc1_src mem1_src\n        st1_tgt lc1_tgt mem1_tgt\n        st2_tgt lc2_tgt mem2_tgt\n        (SIM1: sim_sl tmp1 tmp2 (st1_src, lc1_src) (st1_tgt, lc1_tgt))\n        (MEM1: mem1_src = mem1_tgt)\n        (STEP_TGT: ExecUnit.promise_step tid\n                     (ExecUnit.mk st1_tgt lc1_tgt mem1_tgt)\n                     (ExecUnit.mk st2_tgt lc2_tgt mem2_tgt)):\n    exists st2_src lc2_src mem2_src,\n      (<<STEP_SRC: RMWExecUnit.promise_step tid\n                     (RMWExecUnit.mk st1_src lc1_src mem1_src)\n                     (RMWExecUnit.mk st2_src lc2_src mem2_src)>>) /\\\n      (<<SIM2: sim_sl tmp1 tmp2 (st2_src, lc2_src) (st2_tgt, lc2_tgt)>>) /\\\n      (<<MEM2: mem2_src = mem2_tgt>>).\n  Proof.\n    inv SIM1. inv STEP_TGT. ss. subst.\n    exploit sim_local_promise; eauto. i. des. subst.\n    esplits.\n    - econs; s; eauto.\n    - econs; ss. inv STEP_SRC. ss.\n    - ss.\n  Qed.\n\n  Lemma sim_promise_step\n        m1_src m1_tgt m2_tgt\n        (SIM1: sim m1_src m1_tgt)\n        (STEP_TGT: Machine.step ExecUnit.promise_step m1_tgt m2_tgt):\n    exists m2_src,\n      (<<STEP_SRC: RMWMachine.step RMWExecUnit.promise_step m1_src m2_src>>) /\\\n      (<<SIM2: sim m2_src m2_tgt>>).\n  Proof.\n    destruct m1_src as [tpool1_src mem1_src],\n        m1_tgt as [tpool1_tgt mem1_tgt].\n    inv SIM1. inv STEP_TGT. ss.\n    exploit TPOOL. i. des.\n    rewrite FIND in x0. inv x0.\n    destruct a as [st1_src lc1_src].\n    symmetry in H0. rename H0 into FIND_SRC.\n    exploit sim_sl_promise_step; eauto. i. des.\n    eexists (RMWMachine.mk _ _).\n    esplits.\n    - econs; s; eauto.\n    - econs; ss. i.\n      rewrite TPOOL0.\n      do 2 rewrite IdMap.add_spec.\n      condtac; eauto.\n  Qed.\n\n  Lemma sim_rtc_promise_step\n        m1_src m1_tgt m2_tgt\n        (SIM1: sim m1_src m1_tgt)\n        (STEP_TGT: rtc (Machine.step ExecUnit.promise_step) m1_tgt m2_tgt):\n    exists m2_src,\n      (<<STEP_SRC: rtc (RMWMachine.step RMWExecUnit.promise_step) m1_src m2_src>>) /\\\n      (<<SIM2: sim m2_src m2_tgt>>).\n  Proof.\n    revert m1_src SIM1.\n    induction STEP_TGT; i; eauto.\n    exploit sim_promise_step; eauto. i. des.\n    exploit IHSTEP_TGT; eauto. i. des.\n    esplits; [|eauto]. etrans; eauto.\n  Qed.\n\n  Lemma sim_eu_exec\n        tid eu1_src eu1_tgt eu2_tgt\n        (SIM: @sim_eu tid eu1_src eu1_tgt)\n        (STEPS_TGT: rtc (ExecUnit.state_step tid) eu1_tgt eu2_tgt)\n        (TERMINAL_ST: State.is_terminal eu2_tgt.(ExecUnit.state))\n        (TERMINAL_LC: eu2_tgt.(ExecUnit.local).(Local.promises) = bot):\n    exists eu2_src,\n      (<<STEPS_SRC: rtc (RMWExecUnit.state_step None tid) eu1_src eu2_src>>) /\\\n      (<<TERMINAL_ST: RMWState.is_terminal eu2_src.(RMWExecUnit.state)>>) /\\\n      (<<TERMINAL_LC: eu2_src.(RMWExecUnit.local).(Local.promises) = bot>>).\n  Proof.\n    exploit sim_eu_rtc_state_step; eauto. i. des.\n    punfold SIM0. inv SIM0. des.\n    exploit H; [econs; ss|]. i. des.\n    esplits; try apply TERMINAL_SRC.\n    etrans; eauto.\n  Qed.\n\n  Lemma sim_state_exec\n        m1_src m1_tgt m_tgt\n        (SIM: sim m1_src m1_tgt)\n        (EXEC_TGT: Machine.state_exec m1_tgt m_tgt)\n        (TERMINAL_TGT: Machine.is_terminal m_tgt):\n    exists m_src,\n      (<<EXEC_SRC: RMWMachine.state_exec m1_src m_src>>) /\\\n      (<<TERMINAL_TGT: RMWMachine.is_terminal m_src>>) /\\\n      (<<MEMORY: RMWMachine.mem m_src = Machine.mem m_tgt>>).\n  Proof.\n    inv SIM. inv EXEC_TGT.\n    assert (exists tids,\n               (<<IN: forall tid (IN: List.In tid tids),\n                   (<<SIM:\n                     exists tid1 tid2,\n                       opt_rel\n                         (sim_sl tid1 tid2)\n                         (IdMap.find tid m1_src.(RMWMachine.tpool))\n                         (IdMap.find tid m1_tgt.(Machine.tpool))>>) /\\\n                   (<<EXEC_TGT:\n                     opt_rel\n                       (fun sl1 sl2 =>\n                          rtc (ExecUnit.state_step tid)\n                            (ExecUnit.mk (fst sl1) (snd sl1) m1_tgt.(Machine.mem))\n                            (ExecUnit.mk (fst sl2) (snd sl2) m1_tgt.(Machine.mem)))\n                       (IdMap.find tid m1_tgt.(Machine.tpool))\n                       (IdMap.find tid m_tgt.(Machine.tpool))>>)>>) /\\\n               (<<OUT: forall tid (OUT: ~ List.In tid tids),\n                   (<<TERMINAL: forall st_src lc_src\n                                  (FIND: IdMap.find tid m1_src.(RMWMachine.tpool) = Some (st_src, lc_src)),\n                       (<<TERMINAL_ST: RMWState.is_terminal st_src>>) /\\\n                       (<<TERMINAL_LC: lc_src.(Local.promises) = bot>>)>>)>>) /\\\n               (<<NODUP: List.NoDup tids>>)).\n    { exists (List.map fst (IdMap.elements m1_src.(RMWMachine.tpool))).\n      splits; ss.\n      - ii. exfalso. apply OUT.\n        setoid_rewrite IdMap.elements_spec in FIND.\n        revert FIND. clear.\n        generalize (IdMap.elements m1_src.(RMWMachine.tpool)). i.\n        induction l; ss.\n        destruct a. des_ifs; auto.\n      - specialize (IdMap.elements_3w m1_src.(RMWMachine.tpool)). clear.\n        generalize (IdMap.elements m1_src.(RMWMachine.tpool)). i.\n        induction l; ss.\n        inv H. econs; eauto.\n        clear - H2. ii.\n        induction l; ss. des; eauto.\n        destruct a0, a; ss. subst.\n        apply H2. left. ss.\n    }\n    des.\n    clear TPOOL TPOOL0.\n    revert m1_src m1_tgt IN OUT NODUP MEMORY MEM.\n\n    induction tids; i.\n    { exists m1_src. splits.\n      - econs; ss. ii.\n        destruct (IdMap.find id (RMWMachine.tpool m1_src)); ss.\n        econs. refl.\n      - econs. i. eapply OUT; eauto.\n      - congr.\n    }\n    exploit IN; [left; refl|]. i. des.\n    inv SIM.\n    { eapply IHtids; eauto; ii.\n      - eapply IN. right. ss.\n      - destruct (Id.eq_dec tid a).\n        + subst. congr.\n        + eapply OUT; eauto. ii. inv H1; ss.\n      - inv NODUP. ss.\n    }\n    destruct a0 as [st1_src lc1_src], b as [st1_tgt lc1_tgt].\n    exploit sim_sl_sim_eu; try exact REL; try exact MEMORY. s. intro SIM_EU.\n    rewrite <- H in *. inv EXEC_TGT.\n    destruct b as [st2_tgt lc2_tgt]. ss.\n    inv TERMINAL_TGT. exploit TERMINAL; eauto. i. des.\n    exploit sim_eu_exec; try exact REL0; eauto. i. des.\n    destruct eu2_src as [st2_src lc2_src mem2_src].\n    exploit (RMWExecUnit.rtc_state_step_memory (A:=unit)); try exact STEPS_SRC. s. i. subst.\n    destruct m1_src as [tpool1_src mem1_src],\n        m1_tgt as [tpool1_tgt mem1_tgt]. ss.\n    exploit (IHtids\n              (RMWMachine.mk (IdMap.add a (st2_src, lc2_src) tpool1_src) mem1_src)\n              (Machine.mk (IdMap.add a (st2_tgt, lc2_tgt) tpool1_tgt) mem1_tgt)); ss.\n    { clear IHtids. i.\n      repeat rewrite IdMap.add_spec.\n      condtac; ss; eauto.\n      r in e. subst. inv NODUP. ss.\n    }\n    { clear IHtids. ii. revert FIND.\n      rewrite IdMap.add_spec. condtac; i.\n      - r in e. inv FIND. auto.\n      - eapply OUT; eauto. ii. des; ss. congr.\n    }\n    { inv NODUP. ss. }\n    i. des. esplits; eauto.\n    inv EXEC_SRC. econs; ss.\n    ii. specialize (TPOOL id). inv TPOOL.\n    - revert H2. rewrite IdMap.add_spec. condtac; ss. i.\n      rewrite <- H2. ss.\n    - revert H2. rewrite IdMap.add_spec. condtac; ss; i.\n      + r in e. subst. inv H2.\n        rewrite <- H0. econs. ss. etrans; eauto.\n      + rewrite <- H2. econs. ss.\n  Qed.\n\n  Theorem rmw_to_llsc\n          prog_src prog_tgt m_tgt\n          (COMPILE: rmw_to_llsc_program prog_src prog_tgt)\n          (EXEC_TGT: Machine.pf_exec prog_tgt m_tgt)\n          (TERMINAL_TGT: Machine.is_terminal m_tgt):\n    exists m_src,\n      (<<EXEC_SRC: RMWMachine.pf_exec prog_src m_src>>) /\\\n      (<<TERMINAL_TGT: RMWMachine.is_terminal m_src>>) /\\\n      (<<MEMORY: RMWMachine.mem m_src = Machine.mem m_tgt>>).\n  Proof.\n    inv EXEC_TGT.\n    exploit init_sim; eauto. intro SIM.\n    exploit sim_rtc_promise_step; eauto. i. des.\n    exploit sim_state_exec; eauto. i. des.\n    esplits.\n    - econs; eauto. inv TERMINAL_TGT0.\n      econs. i. eapply TERMINAL; eauto.\n    - ss.\n    - ss.\n  Qed.\nEnd RMWtoLLSC.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-to-promising-arm", "sha": "1e16f948ec5549a55cde3497036feade3946e1f2", "save_path": "github-repos/coq/snu-sf-promising-ir-to-promising-arm", "path": "github-repos/coq/snu-sf-promising-ir-to-promising-arm/promising-ir-to-promising-arm-1e16f948ec5549a55cde3497036feade3946e1f2/src/mapping/RMWtoLLSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.18452086838641962}}
{"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 configure_realm_stage2_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 (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n    rely (ref_accessible gn CPU_ID);\n    let comm := g_regs (grec gn) in\n    rely (regs_is_int64_dec comm);\n    Some adt {priv: (priv adt) {cpu_regs: (cpu_regs (priv adt)) {r_vtcr_el2: (r_vtcr_el2 comm)}\n                                                                {r_vttbr_el2: (r_vttbr_el2 comm)}}}.\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/CtxtSwitch/Specs/configure_realm_stage2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3522017820478897, "lm_q1q2_score": 0.18434957965550158}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Facade.Facade.\n\nRequire Import Bedrock.Platform.Cito.StringMapFacts.\nRequire Import Coq.Lists.List.\nRequire Import Bedrock.Platform.Cito.ListFacts4.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Notation RunsTo := (@RunsTo ADTValue).\n  Notation State := (@State ADTValue).\n  Notation Env := (@Env ADTValue).\n  Notation Sca := (@SCA ADTValue).\n\n  Section Safe_coind.\n\n    Variable env : Env.\n\n    Variable R : Stmt -> State -> Prop.\n\n    Hypothesis SeqCase : forall a b st, R (Seq a b) st -> R a st /\\ forall st', RunsTo env a st st' -> R b st'.\n\n    Hypothesis IfCase : forall cond t f st, R (If cond t f) st -> (is_true st cond /\\ R t st) \\/ (is_false st cond /\\ R f st).\n\n    Hypothesis WhileCase :\n      forall cond body st,\n        let loop := While cond body in\n        R loop st ->\n        (is_true st cond /\\ R body st /\\ (forall st', RunsTo env body st st' -> R loop st')) \\/\n        (is_false st cond).\n\n    Hypothesis AssignCase :\n      forall x e st,\n        R (Facade.Assign x e) st ->\n        not_mapsto_adt x st = true /\\\n        exists w, eval st e = Some (Sca w).\n\n    Hypothesis LabelCase :\n      forall x lbl st,\n        R (Label x lbl) st ->\n        not_mapsto_adt x st = true /\\\n        exists w, Label2Word env lbl = Some w.\n\n    Hypothesis CallCase :\n      forall x f args st,\n        R (Call x f args) st ->\n        NoDup args /\\\n        not_mapsto_adt x st = true /\\\n        exists f_w input,\n          eval st f = Some (Sca f_w) /\\\n          mapM (sel st) args = Some input /\\\n          ((exists spec,\n              Word2Spec env f_w = Some (Axiomatic spec) /\\\n              PreCond spec input) \\/\n           (exists spec,\n              Word2Spec env f_w = Some (Operational _ spec) /\\\n              length args = length (ArgVars spec) /\\\n              let callee_st := make_map (ArgVars spec) input in\n              R (Body spec) callee_st /\\\n              (forall callee_st',\n                 RunsTo env (Body spec) callee_st callee_st' ->\n                 sel callee_st' (RetVar spec) <> None /\\\n                 no_adt_leak input (ArgVars spec) (RetVar spec) callee_st'))).\n\n    Hint Constructors Safe.\n\n    Require Import Bedrock.Platform.Cito.GeneralTactics.\n\n    Theorem Safe_coind : forall c st, R c st -> Safe env c st.\n      cofix; intros; destruct c.\n      - eauto.\n      - eapply SeqCase in H; openhyp; eapply SafeSeq; eauto.\n      - eapply IfCase in H; openhyp; eauto.\n      - eapply WhileCase in H; openhyp; eauto.\n      - eapply CallCase in H; openhyp; simpl in *; intuition eauto.\n      - eapply LabelCase in H; openhyp; eauto.\n      - eapply AssignCase in H; openhyp; eauto.\n    Qed.\n\n  End Safe_coind.\n\nEnd ADTValue.\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/SafeCoind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.35220178884745895, "lm_q1q2_score": 0.1843495779778337}}
{"text": "From RecordUpdate Require Import RecordSet.\n\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.program_proof Require Import wal.invariant.\n\nSection goose_lang.\nContext `{!heapGS \u03a3}.\nContext `{!walG \u03a3}.\n\nImplicit Types (\u03b3: wal_names).\n\nContext (P: log_state.t -> iProp \u03a3).\n\nHint Unfold slidingM.wf : word.\nHint Unfold slidingM.numMutable : word.\n\nLemma logIndex_set_mutable f \u03c3 pos :\n  slidingM.logIndex (set slidingM.mutable f \u03c3) pos = slidingM.logIndex \u03c3 pos.\nProof.\n  rewrite /slidingM.logIndex //=.\nQed.\n\nLemma stable_alloc_end \u03b3 txns mutable nextDiskEnd_txn_id endpos :\n  ( memLog_linv_nextDiskEnd_txn_id \u03b3 mutable nextDiskEnd_txn_id \u2217\n    nextDiskEnd_inv \u03b3 txns \u2217\n    txns_ctx \u03b3 txns \u2217\n    txn_pos \u03b3 (length txns - 1) endpos\n  )\n  ==\u2217\n  (\n    memLog_linv_nextDiskEnd_txn_id \u03b3 endpos (length txns - 1) \u2217\n    nextDiskEnd_inv \u03b3 txns \u2217\n    txns_ctx \u03b3 txns \u2217\n    (length txns - 1)%nat [[\u03b3.(stable_txn_ids_name)]]\u21a6ro tt\n  ).\nProof.\n  iIntros \"(H0 & H1 & Htxns_ctx & #Hend)\".\n  iNamed \"H1\".\n  iNamed \"H0\".\n  iDestruct (txn_pos_valid_general with \"Htxns_ctx HnextDiskEnd_txn\") as \"%HnextDiskEnd_txn\".\n  eapply is_txn_bound in HnextDiskEnd_txn as HnextDiskEnd_bound.\n  iDestruct (map_ctx_agree with \"HownStableSet Hstablectx\") as %->.\n  iCombine \"HownStableSet Hstablectx\" as \"Hstablectx\".\n  destruct (stable_txns !! (length txns - 1)%nat) eqn:He.\n  {\n    iDestruct (big_sepM_lookup with \"Hstablero\") as \"#Hstable\"; eauto.\n    iModIntro.\n    iDestruct \"Hstablectx\" as \"[Hstablectx HownStableSet]\".\n    iFrame \"Htxns_ctx Hstable\".\n    iSplitL \"HownStableSet\".\n    { iExists _. iFrame. iFrame \"# %\".\n      iPureIntro. intros. eapply HnextDiskEnd_max_stable. lia. }\n    iExists _. iFrame. iFrame \"%\".\n  }\n\n  iMod (map_alloc_ro with \"Hstablectx\") as \"[Hstablectx #Hstable]\"; eauto.\n  iDestruct (big_sepM_insert with \"[$Hstablero $Hstable]\") as \"Hstablero\"; eauto.\n  iModIntro.\n  iDestruct \"Hstablectx\" as \"[Hstablectx HownStableSet]\".\n  iFrame \"Htxns_ctx Hstable\".\n  iSplitL \"HownStableSet\".\n  { iExists _. iFrame. iFrame \"# %\".\n    iPureIntro. intros. rewrite lookup_insert_ne; try lia. eapply HnextDiskEnd_max_stable. lia. }\n  iExists _. iFrame.\n  iPureIntro. rewrite /stable_sound. intros.\n  destruct (decide (txn_id = (length txns - 1)%nat)); subst.\n  { eapply is_txn_bound in H2. lia. }\n  rewrite lookup_insert_ne in H0; eauto.\nQed.\n\nTheorem wp_sliding__clearMutable_wal l st \u03b3 dinit \u03c3 :\n  {{{ is_wal P l \u03b3 dinit \u2217 wal_linv_core st \u03b3 \u03c3 }}}\n    sliding__clearMutable (struct.loadF WalogState \"memLog\" #st)\n  {{{ \u03c3', RET #();\n    wal_linv_core st \u03b3 \u03c3' \u2217\n    \u231clength \u03c3.(memLog).(slidingM.log) = length \u03c3'.(memLog).(slidingM.log)\u231d\n  }}}.\nProof.\n  iIntros (\u03a6) \"(#Hwal & Hlkinv) H\u03a6\".\n  iNamed \"Hlkinv\".\n  iNamed \"Hfields\".\n  iNamed \"Hfield_ptsto\".\n  rewrite -wp_ncfupd.\n  iDestruct (is_sliding_wf with \"His_memLog\") as %Hsliding_wf.\n  wp_loadField.\n  wp_apply (wp_sliding__clearMutable with \"His_memLog\").\n  iIntros \"His_memLog\".\n\n  wp_pures. iApply (\"H\u03a6\" $! (set memLog (\u03bb _,\n    (set slidingM.mutable (\u03bb _ : u64, slidingM.endPos \u03c3.(memLog))\n    \u03c3.(memLog))) \u03c3\n  )).\n  iNamed \"HmemLog_linv\".\n  iNamed \"Hlinv_pers\".\n  iDestruct \"HmemStart_txn\" as \"#HmemStart_txn\".\n  iDestruct \"HmemEnd_txn\" as \"#HmemEnd_txn\".\n  iMod (txn_pos_valid_locked with \"Hwal HmemEnd_txn Howntxns\") as \"(%HmemEnd_is_txn & Howntxns)\".\n\n  iAssert (txn_pos \u03b3 nextDiskEnd_txn_id \u03c3.(memLog).(slidingM.mutable)) as \"#HnextDiskEnd_txn0\".\n  { iNamed \"HnextDiskEnd\". iFrame \"#\". }\n  iMod (txn_pos_valid_locked with \"Hwal HnextDiskEnd_txn0 Howntxns\") as \"(%HnextDiskEnd_is_txn0 & Howntxns)\".\n\n  iDestruct \"Hwal\" as \"[Hinv Hcirc]\".\n  iInv \"Hinv\" as (\u03c3s) \"[Hinner Hp]\" \"Hclose\".\n  iDestruct \"Hinner\" as \"(>%Hwf & Hmem & >Htxns_ctx & >\u03b3txns & >HnextDiskEnd_inv & >Hdisk)\".\n  iDestruct (ghost_var_agree with \"Howntxns \u03b3txns\") as %->.\n  iMod (stable_alloc_end with \"[$HnextDiskEnd $HnextDiskEnd_inv $Htxns_ctx $HmemEnd_txn]\") as \"H\".\n  iDestruct \"H\" as \"(HnextDiskEnd & HnextDiskEnd_inv & Htxns_ctx & #Hstable)\".\n  iMod (\"Hclose\" with \"[\u03b3txns Hmem HnextDiskEnd_inv Hdisk Htxns_ctx Hp]\").\n  { iModIntro.\n    iExists _. iFrame. done. }\n\n  iModIntro.\n  iDestruct (is_sliding_wf with \"His_memLog\") as %Hsliding_wf'.\n  simpl.\n  iSplitL; last by trivial.\n  iFrame \"# \u2217\".\n  iSplitR \"Howntxns HownLoggerPos_linv HownLoggerTxn_linv HnextDiskEnd HownInstallerPosMem_linv HownInstallerTxnMem_linv HownInstalledTxnMem_linv\".\n  { iExists _; iFrame.\n    iPureIntro.\n    split_and!; simpl; auto; try word.\n    rewrite /slidingM.endPos.\n    unfold locked_wf, slidingM.wf in Hlocked_wf.\n    word.\n  }\n  eapply is_txn_bound in HdiskEnd_txn as HdiskEnd_txn_bound.\n  eapply is_txn_bound in HnextDiskEnd_is_txn0 as HnextDiskEnd_txn0_bound.\n  destruct (decide (int.Z \u03c3.(memLog).(slidingM.mutable) \u2264 int.Z (slidingM.endPos \u03c3.(memLog)))).\n  2: {\n    epose proof (wal_wf_txns_mono_pos Hwf HmemEnd_is_txn HnextDiskEnd_is_txn0). lia.\n  }\n\n  iExists installed_txn_id_mem, (length \u03c3s.(log_state.txns) - 1)%nat, \u03c3s.(log_state.txns), _, _, _, _; simpl.\n  iFrame \"Howntxns HownLoggerPos_linv HownLoggerTxn_linv\".\n  iFrame \"HmemStart_txn HmemEnd_txn\".\n  iFrame \"HownInstallerPosMem_linv HownInstallerTxnMem_linv HownInstalledTxnMem_linv\".\n  iFrame \"% HinstalledTxn_lb\".\n  iSplit.\n  2: {\n    iNamed \"HnextDiskEnd\". iExists _. iFrame. iFrame \"#\". iFrame \"%\".\n  }\n  iSplit.\n  { iPureIntro. lia. }\n  iSplit.\n  { iPureIntro. lia. }\n  iSplit.\n  2: {\n    iPureIntro.\n    rewrite /slidingM.endPos.\n    word.\n  }\n  iPureIntro.\n  rewrite /memLog_linv_txns !logIndex_set_mutable /slidingM.endPos\n    /mwrb.logend /slidingM.logIndex /=.\n  rewrite /memLog_linv_txns /mwrb.logend /slidingM.logIndex in Htxns.\n  replace (S (_ - 1))%nat with (length \u03c3s.(log_state.txns)); last by lia.\n  eapply (is_memLog_boundaries_move _ _ _ mwrb_us) in Htxns;\n    last by reflexivity.\n  simpl in Htxns.\n  replace (int.nat (word.add _ _) - int.nat _)%nat\n    with (length \u03c3.(memLog).(slidingM.log)) by word.\n  assumption.\nQed.\n\nTheorem wp_endGroupTxn st \u03b3 :\n  {{{ wal_linv st \u03b3 }}}\n    WalogState__endGroupTxn #st\n  {{{ RET #(); wal_linv st \u03b3 }}}.\nProof.\n  iIntros (\u03a6) \"Hlkinv H\u03a6\".\n  iNamed \"Hlkinv\".\n  iNamed \"Hfields\".\n  iNamed \"Hfield_ptsto\".\n  iNamed \"His_memLog\".\n  iNamed \"Hinv\".\n  iNamed \"needFlush\".\n  wp_call.\n  wp_loadField.\n  wp_storeField.\n\n  iApply \"H\u03a6\".\n  iModIntro.\n  iExists _.\n  iFrame.\n  iExists _.\n  iFrame (Hlocked_wf Hwf) \"\u2217\".\n  iExists _, _.\n  iFrame \"\u2217 #\".\n  iExists _.\n  iFrame.\nQed.\n\nLemma is_txn_mid \u03c3 (a b c : nat) pos :\n  wal_wf \u03c3 ->\n  is_txn \u03c3.(log_state.txns) a pos ->\n  is_txn \u03c3.(log_state.txns) c pos ->\n  a \u2264 b \u2264 c ->\n  is_txn \u03c3.(log_state.txns) b pos.\nProof.\n  rewrite /is_txn /wal_wf; intros Hwf Ha Hc Hle.\n  destruct Hwf as [_ [Hwf _]].\n  destruct (decide (a < b)).\n  2: { assert (a = b) by lia; subst; eauto. }\n  destruct (decide (b < c)).\n  2: { assert (b = c) by lia; subst; eauto. }\n  assert (is_Some (\u03c3.(log_state.txns) !! b)).\n  { eapply lookup_lt_is_Some_2. etransitivity.\n    2: {\n      eapply lookup_lt_is_Some_1.\n      eapply fmap_is_Some. eauto.\n    }\n    lia.\n  }\n\n  destruct H as [tb Hb'].\n  assert (fst <$> \u03c3.(log_state.txns) !! b = Some (fst tb)) as Hb.\n  { rewrite Hb'. reflexivity. }\n\n  rewrite -list_lookup_fmap in Ha.\n  rewrite -list_lookup_fmap in Hb.\n  rewrite -list_lookup_fmap in Hc.\n  rewrite -list_lookup_fmap.\n\n  eapply Hwf in Ha as Hab'.\n  1: eapply Hab' in Hb as Hab. 2: lia.\n  eapply Hwf in Hb as Hbc'.\n  1: eapply Hbc' in Hc as Hbc. 2: lia.\n  rewrite Hb. f_equal. word.\nQed.\n\nLemma subslice_stable_nils \u03b3 \u03c3 (txn_id txn_id' : nat) pos :\n  wal_wf \u03c3 ->\n  txn_id \u2264 txn_id' ->\n  is_txn \u03c3.(log_state.txns) txn_id pos ->\n  is_txn \u03c3.(log_state.txns) txn_id' pos ->\n  ( nextDiskEnd_inv \u03b3 \u03c3.(log_state.txns) \u2217\n    txn_id [[\u03b3.(stable_txn_ids_name)]]\u21a6ro () ) -\u2217\n  \u231cForall (\u03bb x, snd x = nil) (subslice (S txn_id) (S txn_id') \u03c3.(log_state.txns))\u231d.\nProof.\n  intros.\n  iIntros \"[Hinv Hstable]\".\n  iNamed \"Hinv\".\n  iDestruct (map_ro_valid with \"Hstablectx Hstable\") as \"%Hvalid\".\n  iPureIntro.\n  apply Forall_lookup_2; intros.\n  apply subslice_lookup_some in H3 as H3'.\n  assert (snd <$> \u03c3.(log_state.txns) !! (S txn_id + i)%nat = Some x.2).\n  { rewrite H3'. eauto. }\n  erewrite HafterNextDiskEnd in H4; simplify_eq/=; eauto.\n  { lia. }\n  eapply is_txn_mid; [ done | apply H1 | apply H2 |].\n  apply subslice_lookup_bound' in H3.\n  lia.\nQed.\n\nLemma subslice_stable_nils2 \u03b3 \u03c3 (txn_id txn_id' : nat) pos :\n  wal_wf \u03c3 ->\n  is_txn \u03c3.(log_state.txns) txn_id pos ->\n  is_txn \u03c3.(log_state.txns) txn_id' pos ->\n  ( nextDiskEnd_inv \u03b3 \u03c3.(log_state.txns) \u2217\n    txn_id [[\u03b3.(stable_txn_ids_name)]]\u21a6ro () ) -\u2217\n  \u231cForall (\u03bb x, snd x = nil) (subslice (S txn_id) (S txn_id') \u03c3.(log_state.txns))\u231d.\nProof.\n  intros.\n  iIntros \"[Hinv Hstable]\".\n  destruct (decide (txn_id \u2264 txn_id')).\n  { iApply subslice_stable_nils; eauto. }\n\n  iPureIntro.\n  rewrite /subslice.\n  rewrite drop_ge; eauto.\n  etransitivity; first by apply firstn_le_length.\n  lia.\nQed.\n\nLemma stable_sound_alloc txns stable_txns (txn_id txn_id' : nat) (pos : u64) :\n  stable_txns !! txn_id = Some () ->\n  txn_id \u2264 txn_id' ->\n  is_txn txns txn_id pos ->\n  is_txn txns txn_id' pos ->\n  stable_sound txns stable_txns ->\n  stable_sound txns (<[txn_id':=()]> stable_txns).\nProof.\n  rewrite /stable_sound.\n  intros.\n\n  destruct (decide (txn_id' = txn_id0)).\n  { subst.\n    eapply (H3 txn_id txn_id'0 pos); try eassumption.\n    1: lia.\n    pose proof (is_txn_pos_unique _ _ _ _ H2 H6); subst.\n    eauto.\n  }\n  eapply H3; try eassumption.\n  rewrite lookup_insert_ne in H5; eauto.\nQed.\n\nLemma stable_sound_nils \u03c3 stable_txns txn_id txn_id' pos :\n  wal_wf \u03c3 ->\n  stable_txns !! txn_id = Some () ->\n  is_txn \u03c3.(log_state.txns) txn_id pos ->\n  is_txn \u03c3.(log_state.txns) txn_id' pos ->\n  stable_sound \u03c3.(log_state.txns) stable_txns ->\n  Forall (\u03bb x, x.2 = []) (subslice (S txn_id) (S txn_id') \u03c3.(log_state.txns)).\nProof.\n  intros.\n  apply Forall_lookup_2; intros.\n  apply subslice_lookup_some in H4 as H4'.\n  assert (snd <$> \u03c3.(log_state.txns) !! (S txn_id + i)%nat = Some x.2).\n  { rewrite H4'. eauto. }\n  erewrite H3 in H5; simplify_eq/=; eauto.\n  { lia. }\n  eapply is_txn_mid; [ done | apply H1 | apply H2 | ].\n  eapply subslice_lookup_bound' in H4 as Hbound.\n  lia.\nQed.\n\nTheorem stable_txn_id_advance \u03b3 mutable txn_id txn_id' pos nextDiskEnd_txn_id \u03c3 :\n  wal_wf \u03c3 ->\n  is_txn \u03c3.(log_state.txns) txn_id pos ->\n  is_txn \u03c3.(log_state.txns) txn_id' pos ->\n  txn_id \u2264 txn_id' ->\n  memLog_linv_nextDiskEnd_txn_id \u03b3 mutable nextDiskEnd_txn_id -\u2217\n  nextDiskEnd_inv \u03b3 \u03c3.(log_state.txns) -\u2217\n  txn_id [[\u03b3.(stable_txn_ids_name)]]\u21a6ro () -\u2217\n  txns_ctx \u03b3 \u03c3.(log_state.txns)\n  ==\u2217 (\n    txn_id' [[\u03b3.(stable_txn_ids_name)]]\u21a6ro () \u2217\n    nextDiskEnd_inv \u03b3 \u03c3.(log_state.txns) \u2217\n    txns_ctx \u03b3 \u03c3.(log_state.txns) \u2217\n    \u2203 nextDiskEnd_txn_id',\n      memLog_linv_nextDiskEnd_txn_id \u03b3 mutable nextDiskEnd_txn_id' \u2217\n      \u231cnextDiskEnd_txn_id \u2264 nextDiskEnd_txn_id' < length \u03c3.(log_state.txns)\u231d \u2217\n      \u231cForall (\u03bb x, x.2 = []) (subslice (S nextDiskEnd_txn_id) (S nextDiskEnd_txn_id') \u03c3.(log_state.txns))\u231d\n  ).\nProof.\n  clear P.\n\n  iIntros (Hwf Histxn Histxn' Hle) \"H0 H1 #Hstable Htxns_ctx\".\n  iNamed \"H0\".\n  iNamed \"H1\".\n  iDestruct (map_ctx_agree with \"HownStableSet Hstablectx\") as \"%Heq\". subst.\n  iDestruct (map_valid with \"HownStableSet Hstable\") as \"%Hstable\".\n\n  iDestruct (map_valid with \"Hstablectx HnextDiskEnd_stable\") as \"%HnextDiskEnd_stable\".\n  iDestruct (txn_pos_valid_general with \"Htxns_ctx HnextDiskEnd_txn\") as \"%HnextDiskEnd_txn\".\n\n  destruct (stable_txns0 !! txn_id') eqn:He.\n  {\n    iDestruct (big_sepM_lookup with \"Hstablero\") as \"#Hstable'\"; eauto.\n    iModIntro.\n    iFrame \"Hstable' Htxns_ctx\".\n    iSplitL \"Hstablectx Hstablero\".\n    { iExists _. iFrame. iFrame \"%\". }\n    iExists nextDiskEnd_txn_id.\n    iSplitL \"HownStableSet\".\n    { iExists _. iFrame. iFrame \"#\". iFrame \"%\". }\n    rewrite subslice_zero_length.\n    eapply is_txn_bound in HnextDiskEnd_txn.\n    iPureIntro. intuition eauto; lia.\n  }\n\n  iCombine \"HownStableSet Hstablectx\" as \"Hctx\".\n  iMod (map_alloc_ro with \"Hctx\") as \"[Hctx #Hstable']\"; eauto.\n  iDestruct (big_sepM_insert with \"[$Hstablero Hstable']\") as \"Hstablero\"; eauto.\n  iFrame \"Hstable'\".\n\n  iModIntro.\n  iDestruct \"Hctx\" as \"[HownStableSet Hstablectx]\".\n  iSplitL \"Hstablectx Hstablero\".\n  { iExists _. iFrame \"Hstablectx\". iFrame.\n    iPureIntro. eapply stable_sound_alloc. 1: apply Hstable. all: eauto. }\n\n  destruct (decide (txn_id' \u2264 nextDiskEnd_txn_id)).\n  {\n    iFrame \"Htxns_ctx\".\n    iExists nextDiskEnd_txn_id.\n    iSplitL \"HownStableSet\".\n    { iExists _. iFrame. iFrame \"#\".\n      iPureIntro. intros.\n      destruct (decide (txn_id0 = txn_id')); try lia.\n      rewrite lookup_insert_ne; eauto. }\n    iPureIntro.\n    rewrite subslice_zero_length.\n    eapply is_txn_bound in HnextDiskEnd_txn.\n    intuition eauto; lia.\n  }\n\n  destruct (decide (nextDiskEnd_txn_id < txn_id)).\n  {\n    rewrite HnextDiskEnd_max_stable in Hstable; try lia. congruence.\n  }\n\n  assert (is_txn \u03c3.(log_state.txns) nextDiskEnd_txn_id pos) as Hnextpos.\n  {\n    eapply (is_txn_mid _ txn_id _ txn_id'); eauto.\n    word.\n  }\n\n  pose proof (is_txn_pos_unique _ _ _ _ HnextDiskEnd_txn Hnextpos); subst.\n\n  iDestruct (txns_ctx_txn_pos _ _ txn_id' with \"Htxns_ctx\") as \"#Htxn_id'_pos\"; eauto.\n  iFrame.\n  iExists txn_id'.\n  iSplit.\n  { iExists _. iFrame. iFrame \"Hstable'\". iFrame \"Htxn_id'_pos\".\n    iPureIntro. intros. rewrite lookup_insert_ne; last by lia.\n    eapply HnextDiskEnd_max_stable. lia. }\n  eapply is_txn_bound in Histxn' as Histxn'_bound.\n  iPureIntro. intuition try lia.\n  eapply stable_sound_nils; eauto.\nQed.\n\nEnd goose_lang.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/wal/common_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18434957253743572}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import CtxtSwitchAux.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import CtxtSwitchAux.Layer.\nRequire Import CtxtSwitch.Code.save_realm_state.\n\nRequire Import CtxtSwitch.LowSpecs.save_realm_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    _save_sysreg_state \u21a6 gensem save_sysreg_state_spec\n      \u2295 _sysreg_read \u21a6 gensem sysreg_read_spec\n      \u2295 _set_rec_pc \u21a6 gensem set_rec_pc_spec\n      \u2295 _set_rec_pstate \u21a6 gensem set_rec_pstate_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_save_sysreg_state: block.\n    Hypothesis h_save_sysreg_state_s : Genv.find_symbol ge _save_sysreg_state = Some b_save_sysreg_state.\n    Hypothesis h_save_sysreg_state_p : Genv.find_funct_ptr ge b_save_sysreg_state\n                                       = Some (External (EF_external _save_sysreg_state\n                                                        (signature_of_type (Tcons Tptr Tnil) tvoid cc_default))\n                                              (Tcons Tptr Tnil) tvoid cc_default).\n    Local Opaque save_sysreg_state_spec.\n\n    Variable b_sysreg_read: block.\n    Hypothesis h_sysreg_read_s : Genv.find_symbol ge _sysreg_read = Some b_sysreg_read.\n    Hypothesis h_sysreg_read_p : Genv.find_funct_ptr ge b_sysreg_read\n                                 = Some (External (EF_external _sysreg_read\n                                                  (signature_of_type (Tcons tuint Tnil) tulong cc_default))\n                                        (Tcons tuint Tnil) tulong cc_default).\n    Local Opaque sysreg_read_spec.\n\n    Variable b_set_rec_pc: block.\n    Hypothesis h_set_rec_pc_s : Genv.find_symbol ge _set_rec_pc = Some b_set_rec_pc.\n    Hypothesis h_set_rec_pc_p : Genv.find_funct_ptr ge b_set_rec_pc\n                                = Some (External (EF_external _set_rec_pc\n                                                 (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default))\n                                       (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default).\n    Local Opaque set_rec_pc_spec.\n\n    Variable b_set_rec_pstate: block.\n    Hypothesis h_set_rec_pstate_s : Genv.find_symbol ge _set_rec_pstate = Some b_set_rec_pstate.\n    Hypothesis h_set_rec_pstate_p : Genv.find_funct_ptr ge b_set_rec_pstate\n                                    = Some (External (EF_external _set_rec_pstate\n                                                     (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default))\n                                           (Tcons Tptr (Tcons tulong Tnil)) tvoid cc_default).\n    Local Opaque set_rec_pstate_spec.\n\n    Lemma save_realm_state_body_correct:\n      forall m d d' env le rec_base rec_offset\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset)))\n             (Hspec: save_realm_state_spec0 (rec_base, rec_offset) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) save_realm_state_body E0 le' (m, d') Out_normal).\n    Proof.\n      solve_code_proof Hspec save_realm_state_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/CtxtSwitch/CodeProof/save_realm_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.18432007592949032}}
{"text": "(*TODO: These imports should be pared down*)\nRequire Import FSets.\nRequire FSetAVL.\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Ordered.\nRequire Import AST.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Clight.\nRequire Import SimplLocals.\n\nRequire Import mem_lemmas.\nRequire Import semantics.\nRequire Import semantics_lemmas.\nRequire Import reach.\nRequire Import effect_semantics.\nRequire Import structured_injections.\nRequire Import simulations.\nRequire Import effect_properties.\nRequire Import simulations_lemmas.\n\nRequire Export Axioms.\n\n(** Properties of values obtained by casting to a given type. *)\n\nInductive val_casted: val -> type -> Prop :=\n  | val_casted_int: forall sz si attr n,\n      cast_int_int sz si n = n ->\n      val_casted (Vint n) (Tint sz si attr)\n  | val_casted_float: forall sz attr n,\n      cast_float_float sz n = n ->\n      val_casted (Vfloat n) (Tfloat sz attr)\n  | val_casted_long: forall si attr n,\n      val_casted (Vlong n) (Tlong si attr)\n  | val_casted_ptr_ptr: forall b ofs ty attr,\n      val_casted (Vptr b ofs) (Tpointer ty attr)\n  | val_casted_int_ptr: forall n ty attr,\n      val_casted (Vint n) (Tpointer ty attr)\n  | val_casted_ptr_int: forall b ofs si attr,\n      val_casted (Vptr b ofs) (Tint I32 si attr)\n  | val_casted_ptr_cptr: forall b ofs id attr,\n      val_casted (Vptr b ofs) (Tcomp_ptr id attr)\n  | val_casted_int_cptr: forall n id attr,\n      val_casted (Vint n) (Tcomp_ptr id attr)\n  | val_casted_struct: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tstruct id fld attr)\n  | val_casted_union: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tunion id fld attr)\n  | val_casted_void: forall v,\n      val_casted v Tvoid.\n\nDefinition val_casted_func (v : val) (t : type) : bool :=\n  match v, t with\n    | Vint n, Tint sz si attr => \n      if Int.eq_dec (cast_int_int sz si n) n then true\n      else false\n    | Vfloat n, Tfloat sz attr => \n      if Float.eq_dec (cast_float_float sz n) n then true\n      else false\n    | Vlong n, Tlong si attr => true\n    | Vptr b ofs, Tpointer ty attr => true\n    | Vint n, Tpointer ty attr => true\n    | Vptr b ofs, Tint I32 si attr => true\n    | Vptr b ofs, Tcomp_ptr id attr => true\n    | Vint n, Tcomp_ptr id attr => true\n    | Vptr b ofs, Tstruct id flt attr => true\n    | Vptr b ofs, Tunion id flt attr => true\n    | _, Tvoid => true \n    | _, _ => false\n  end.\n\nLemma val_casted_funcI v t : \n  val_casted v t -> \n  val_casted_func v t=true.\nProof.\ndestruct 1; simpl; auto.\nrewrite H. case_eq (Int.eq_dec n n); auto.\nrewrite H. case_eq (Float.eq_dec n n); auto.\ndestruct v; auto.\nQed.\n\nLemma val_casted_funcE v t : \n  val_casted_func v t=true ->\n  val_casted v t.\nProof.\ndestruct v; destruct t; simpl; try solve[inversion 1;econstructor; eauto].\ncase_eq (Int.eq_dec (cast_int_int i0 s i) i). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ncase_eq (Float.eq_dec (cast_float_float f0 f) f). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ndestruct i0; try inversion 1. constructor.\nQed.\n\nLemma val_casted_funcP v t : \n  val_casted_func v t=true <-> val_casted v t.\nProof.\nsplit; [apply val_casted_funcE|apply val_casted_funcI].\nQed.\n\nRemark cast_int_int_idem:\n  forall sz sg i, cast_int_int sz sg (cast_int_int sz sg i) = cast_int_int sz sg i.\nProof.\n  intros. destruct sz; simpl; auto. \n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct (Int.eq i Int.zero); auto.\nQed.\n\nRemark cast_float_float_idem:\n  forall sz f, cast_float_float sz (cast_float_float sz f) = cast_float_float sz f.\nProof.\n  intros; destruct sz; simpl.\n  apply Float.singleoffloat_idem; auto.\n  auto.\nQed.\n\nLemma cast_val_is_casted:\n  forall v ty ty' v', sem_cast v ty ty' = Some v' -> val_casted v' ty'.\nProof.\n  unfold sem_cast; intros. destruct ty'; simpl in *.\n(* void *)\n  constructor.\n(* int *)\n  destruct i; destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. apply (cast_int_int_idem I8 s).\n  constructor. apply (cast_int_int_idem I8 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I8 s). \n  constructor. apply (cast_int_int_idem I16 s).\n  constructor. apply (cast_int_int_idem I16 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I16 s). \n  constructor. auto.\n  constructor.\n  constructor. auto. \n  destruct (cast_float_int s f0); inv H1. constructor. auto.\n  constructor. auto.\n  constructor.\n  constructor; auto.\n  constructor.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor. simpl. destruct (Int64.eq i Int64.zero); auto.\n  constructor. simpl. destruct (Float.cmp Ceq f0 Float.zero); auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor; auto.\n(* long *)\n  destruct ty; try discriminate.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; try discriminate. destruct (cast_float_long s f0); inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n(* float *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. unfold cast_float_float, cast_int_float.\n  destruct f; destruct s; auto.\n  rewrite Float.singleofint_floatofint. apply Float.singleoffloat_idem.\n  rewrite Float.singleofintu_floatofintu. apply Float.singleoffloat_idem.\n  constructor. unfold cast_float_float, cast_long_float.\n  destruct f; destruct s; auto. apply Float.singleoflong_idem. apply Float.singleoflongu_idem.\n  constructor. apply cast_float_float_idem.\n(* pointer *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; try constructor.\n(* impossible cases *)\n  discriminate.\n  discriminate.\n(* structs *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* unions *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* comp_ptr *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; constructor.\nQed.\n\nLemma val_casted_load_result:\n  forall v ty chunk,\n  val_casted v ty -> access_mode ty = By_value chunk ->\n  Val.load_result chunk v = v.\nProof.\n  intros. inversion H; clear H; subst v ty; simpl in H0.\n  destruct sz.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  clear H1. inv H0. auto.\n  inversion H0; clear H0; subst chunk. simpl in *. \n  destruct (Int.eq n Int.zero); subst n; reflexivity.\n  destruct sz; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\nQed.\n\nLemma cast_val_casted:\n  forall v ty, val_casted v ty -> sem_cast v ty ty = Some v.\nProof.\n  intros. inversion H; clear H; subst v ty; unfold sem_cast; simpl; auto.\n  destruct sz; congruence.\n  congruence.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\nQed.\n\nLemma val_casted_inject:\n  forall f v v' ty,\n  val_inject f v v' -> val_casted v ty -> val_casted v' ty.\nProof.\n  intros. inv H; auto.\n  inv H0; constructor.\n  inv H0; constructor.\nQed.\n\nInductive val_casted_list: list val -> typelist -> Prop :=\n  | vcl_nil:\n      val_casted_list nil Tnil\n  | vcl_cons: forall v1 vl ty1 tyl,\n      val_casted v1 ty1 -> val_casted_list vl tyl ->\n      val_casted_list (v1 :: vl) (Tcons  ty1 tyl).\n\nLemma val_casted_list_params:\n  forall params vl,\n  val_casted_list vl (type_of_params params) ->\n  list_forall2 val_casted vl (map snd params).\nProof.\n  induction params; simpl; intros. \n  inv H. constructor.\n  destruct a as [id ty]. inv H. constructor; auto. \nQed.\n\nFixpoint val_casted_list_func (vs : list val) (ts : typelist) : bool :=\n  match vs, ts with\n    | nil, Tnil => true\n    | v1 :: vl, Tcons ty1 tyl => \n      val_casted_func v1 ty1 && val_casted_list_func vl tyl\n    | _, _ => false\n  end.\n\nLemma val_casted_list_funcP vs ts : \n  val_casted_list_func vs ts=true <-> val_casted_list vs ts.\nProof.\nrevert ts; induction vs. destruct ts; simpl; auto.\nsplit; auto. intros _. constructor.\nsplit; auto. inversion 1. inversion 1.\nsplit; auto. destruct ts; simpl; auto.\ninversion 1. rewrite andb_true_iff. intros [H1 H2]. constructor.\napply val_casted_funcE in H1; auto. rewrite <-IHvs; auto.\ninversion 1; subst. simpl. rewrite andb_true_iff; split.\napply val_casted_funcI; auto. rewrite IHvs; auto.\nQed.\n\nLemma val_casted_inj (j : meminj) v1 v2 tv : \n  val_inject j v1 v2 -> \n  val_casted v1 tv -> \n  val_casted v2 tv.\nProof.\ninversion 1; subst; auto.\ninversion 1; subst; auto; try solve[constructor; auto].\ninversion 1; constructor.\nQed.\n\nLemma val_casted_list_inj (j : meminj) vs1 vs2 ts :\n  val_list_inject j vs1 vs2 ->\n  val_casted_list vs1 ts ->\n  val_casted_list vs2 ts.\nProof.\nintros H1; revert vs1 vs2 H1; induction ts; simpl; intros vs1 vs2 H1 H2.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\neapply val_casted_inj; eauto.\neapply IHts; eauto.\nQed.\n\nDefinition val_has_type_func (v : val) (t : typ) : bool :=\n  match v with\n    | Vundef => true\n    | Vint _ => match t with\n                  | AST.Tint => true\n                  | _ => false\n                end\n    | Vlong _ => match t with \n                 | AST.Tlong => true\n                 | _ => false\n               end\n    | Vfloat f => match t with \n                    | AST.Tfloat => true\n                    | Tsingle => if Float.is_single_dec f then true else false\n                    | _ => false\n                  end\n    | Vptr _ _ => match t with\n                    | AST.Tint => true\n                    | _ => false\n                  end\n  end.\n\nLemma val_has_type_funcP v t : \n  Val.has_type v t <-> (val_has_type_func v t=true).\nProof.\nsplit.\ninduction v; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto. destruct (Float.is_single_dec f); auto.\nsimpl. destruct t; auto.\ninduction v; simpl; auto.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try solve[inversion 1].\ndestruct (Float.is_single_dec f); try solve[inversion 1|auto].\ndestruct t; auto. inversion 1. inversion 1. inversion 1.\nQed.\n\nFixpoint val_has_type_list_func (vl : list val) (tyl : list typ) : bool :=\n  match vl, tyl with\n    | nil, nil => true\n    | v :: vl', ty :: tyl' => val_has_type_func v ty \n                              && val_has_type_list_func vl' tyl' \n    | nil, _ :: _ => false\n    | _ :: _, nil => false\n  end.\n\nLemma val_has_type_list_func_charact vl tyl : \n  Val.has_type_list vl tyl <-> (val_has_type_list_func vl tyl=true).\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl. split; auto. simpl. split; auto. inversion 1.\nintros. destruct tyl. simpl. split; auto. inversion 1.\nsimpl. split. intros [H H2]. \n+ rewrite andb_true_iff. split. \n  rewrite <-val_has_type_funcP; auto.\n  rewrite <-IHvl; auto.\n+ rewrite andb_true_iff. intros [H H2]. split.\n  rewrite val_has_type_funcP; auto.\n  rewrite IHvl; auto.\nQed.\n\nFixpoint tys_nonvoid (tyl : typelist) :=\n  match tyl with\n    | Tnil => true\n    | Tcons Tvoid tyl' => false\n    | Tcons _ tyl' => tys_nonvoid tyl'\n  end.\n\nFixpoint vals_defined (vl : list val) :=\n  match vl with\n    | nil => true\n    | Vundef :: _ => false\n    | _ :: vl' => vals_defined vl'\n  end.\n\nLemma vals_inject_defined (vl1 vl2 : list val) (j : meminj) :\n  val_list_inject j vl1 vl2 -> \n  vals_defined vl1=true -> \n  vals_defined vl2=true.\nProof.\nrevert vl2; induction vl1; simpl. destruct vl2; try solve[inversion 1|auto].\nintros vl2; inversion 1; subst. destruct a; try solve[inversion 1].\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\nQed.\n\nLemma valinject_hastype':\n  forall (j : meminj) (v v' : val),\n    val_inject j v v' -> \n    v <> Vundef -> \n    forall T : typ, Val.has_type v T -> Val.has_type v' T.\nProof.\n  intros.\n  induction H; auto.\n  elim H0; auto.\nQed.\n\nLemma val_list_inject_hastype j vl1 vl2 tys :\n  val_list_inject j vl1 vl2 -> \n  vals_defined vl1=true -> \n  val_has_type_list_func vl1 tys=true ->\n  val_has_type_list_func vl2 tys=true.\nProof.\nrevert vl2 tys. induction vl1. inversion 1. solve[destruct tys; simpl; auto].\nintros H tys H1 H2 H3. inv H1. \nassert (def: vals_defined vl1=true). \n{ inv H2. revert H0. destruct a; auto. congruence. }\nsimpl. destruct tys. simpl in H3; congruence. \nrewrite andb_true_iff. split. \nrewrite <-val_has_type_funcP. eapply valinject_hastype'; eauto.\nsimpl in H2. intros contra. rewrite contra in H2. congruence.\ninv H3. rewrite andb_true_iff in H0. \n  destruct H0 as [H0 _]. solve[rewrite val_has_type_funcP; auto].\neapply (IHvl1 vl'); eauto.\ninv H3. rewrite H0. rewrite andb_true_iff in H0. \n  solve[destruct H0 as [_ ->]; auto].\nQed.\n\nLemma val_list_inject_defined j vl1 vl2 : \n  val_list_inject j vl1 vl2 -> \n  vals_defined vl1=true -> \n  vals_defined vl2=true.\nProof.\nrevert vl2. induction vl1; simpl. \n+ intros vl2; inversion 1; auto.\n+ intros vl2; inversion 1; subst. inv H. \nsimpl. intros H8.\nassert (def1: vals_defined vl1=true).\n{ destruct a; try solve[congruence]. }\nrevert H2 H8. inversion 1; auto. subst. congruence.\nQed.\n\n(*TODO: put these in Events.v*)\nFixpoint encode_longs (tyl : list typ) (vl : list val) :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' => \n      match vl with \n        | nil => nil\n        | Vlong n :: vl' => Vint (Int64.hiword n) :: Vint (Int64.loword n) \n                            :: encode_longs tyl' vl'\n        | Vundef :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n        | _ :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n      end\n    | t :: tyl' => \n      match vl with\n        | nil => nil\n        | v :: vl' => v :: encode_longs tyl' vl'\n      end\n  end.\n\nFixpoint encode_typs (tyl : list typ) : list typ :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' => AST.Tint :: AST.Tint :: encode_typs tyl'\n    | t :: tyl' => t :: encode_typs tyl'\n  end.\n\nLemma encode_longs_has_type tyl vl :  \n  Val.has_type_list vl tyl -> \n  Val.has_type_list (encode_longs tyl vl) (encode_typs tyl).\nProof.\nrevert vl; induction tyl. simpl; auto. \ndestruct vl. intros; contradiction. intros [H H2]. simpl.\ndestruct a; try solve[split; auto].\ndestruct v; simpl; auto.\nQed.\n\nLemma decode_encode_longs tyl vl : \n  Val.has_type_list vl tyl -> \n  decode_longs tyl (encode_longs tyl vl) = vl.\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl; auto.\ndestruct t; simpl; auto.\ndestruct tyl. simpl. inversion 1. inversion 1; subst. clear H.\nsimpl. destruct t; auto; try rewrite IHvl; auto.\ndestruct a; simpl; try solve[inv H0].\nrewrite IHvl; auto.\nrewrite IHvl; auto. f_equal. \nrewrite Int64.ofwords_recompose; auto.\nQed.\n\nLemma encode_longs_inject:\n  forall (f : meminj) (tyl : list typ) (vl1 vl2 : list val),\n  val_list_inject f vl1 vl2 ->\n  val_list_inject f (encode_longs tyl vl1) (encode_longs tyl vl2).\nProof.\nintros until vl2; intros H; revert tyl; induction H; simpl.\ndestruct tyl; simpl; [solve[constructor]|]. solve[destruct t; auto].\ndestruct tyl; simpl; [solve[constructor]|]. destruct t.\nsolve[constructor; auto]. \nsolve[constructor; auto].\ninv H. solve[auto]. constructor; auto. solve[auto]. solve[auto].\ndestruct v'; solve[auto|constructor; auto].\nsolve[constructor; auto].\nQed.\n\nFixpoint getBlocks' (vl : list val) (b0 : block) := \n  match vl with\n    | nil => false\n    | Vptr b _ :: vl' => eq_block b b0 || getBlocks' vl' b0\n    | _ :: vl' => getBlocks' vl' b0\n  end.\n\nLemma getBlocks_getBlocks' vl b0 : getBlocks vl b0 = getBlocks' vl b0.\nProof.\ninduction vl; simpl; auto.\ndestruct a; auto. unfold getBlocks. simpl. \ndestruct (eq_block b b0); simpl; auto.\nrewrite <-IHvl. unfold getBlocks. \ndestruct (\n     in_dec eq_block b0\n       (fold_right\n          (fun (v : val) (L : list block) =>\n           match v with\n           | Vundef => L\n           | Vint _ => L\n           | Vlong _ => L\n           | Vfloat _ => L\n           | Vptr b' _ => b' :: L\n           end) nil vl)\n); auto.\nQed.\n\nLemma getBlocks_encode_longs tys vals b : \n  getBlocks (encode_longs tys vals) b=true ->\n  getBlocks vals b=true.\nProof.\n  rewrite !getBlocks_getBlocks'.\n  revert tys; induction vals; simpl; auto. destruct tys. simpl; auto. \n  solve[destruct t; simpl; auto].\n  destruct tys. simpl; congruence.\n  simpl. destruct t; destruct a; simpl; intros; try solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto. \n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto. \n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto. \n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\nQed.\n\nLemma val_casted_has_type a t :\n  tys_nonvoid (Tcons t Tnil) = true -> \n  val_casted_func a t = true -> \n  val_has_type_func a (typ_of_type t) = true.\nProof.\nintros H0 H.\napply val_casted_funcE in H.\ninduction H; try solve[auto].\ndestruct H. destruct sz. simpl. \ngeneralize (Float.singleoffloat_is_single n0).\ndestruct (Float.is_single_dec (Float.singleoffloat n0)); auto. auto.\nsimpl in H0. congruence.\nQed.\n\nLemma val_casted_has_type_list vals tys : \n  tys_nonvoid tys = true ->\n  val_casted_list_func vals tys = true -> \n  val_has_type_list_func vals (typlist_of_typelist tys) = true.\nProof.\nrevert vals; induction tys. simpl. intros vals.\ndestruct vals. simpl; auto. simpl. solve[inversion 2].\nsimpl; intros vals; revert tys IHtys; induction vals. simpl. \n  intros; congruence.\nsimpl; intros. rewrite andb_true_iff in H0; destruct H0 as [H0 H2].\nassert (H3: tys_nonvoid tys = true).\n{ destruct t; solve[congruence|auto]. }\nrewrite andb_true_iff. split; auto.\napply val_casted_has_type; auto. destruct t; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/core/val_casted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.1843200759294903}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Typing rules and a type inference algorithm for RTL. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Unityping.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import Globalenvs.\nRequire Import Values.\nRequire Import Integers.\nRequire Import Memory.\nRequire Import Events.\nRequire Import RTL.\nRequire Import Conventions.\n\n(** * The type system *)\n\n(** Like Cminor and all intermediate languages, RTL can be equipped with\n  a simple type system that statically guarantees that operations\n  and addressing modes are applied to the right number of arguments\n  and that the arguments are of the correct types.   The type algebra\n  is very simple, consisting of the four types [Tint] (for integers\n  and pointers), [Tfloat] (for double-precision floats), [Tlong]\n  (for 64-bit integers) and [Tsingle] (for single-precision floats).\n  At the RTL level, we simplify things further by equating [Tsingle]\n  with [Tfloat].\n\n  Additionally, we impose that each pseudo-register has the same type\n  throughout the function.  This requirement helps with register allocation,\n  enabling each pseudo-register to be mapped to a single hardware register\n  or stack location of the correct type.\n\n  Finally, we also check that the successors of instructions\n  are valid, i.e. refer to non-empty nodes in the CFG.\n\n  The typing judgement for instructions is of the form [wt_instr f env\n  instr], where [f] is the current function (used to type-check\n  [Ireturn] instructions) and [env] is a typing environment\n  associating types to pseudo-registers.  Since pseudo-registers have\n  unique types throughout the function, the typing environment does\n  not change during type-checking of individual instructions.  One\n  point to note is that we have one polymorphic operator, [Omove],\n  which can work over both integers and floats.\n*)\n\nDefinition normalize (ty: typ) : typ :=\n  match ty with Tsingle => Tfloat | _ => ty end.\n\nDefinition normalize_list (tyl: list typ) : list typ := map normalize tyl.\n\nDefinition regenv := reg -> typ.\n\nSection WT_INSTR.\n\nVariable funct: function.\nVariable env: regenv.\n\nDefinition valid_successor (s: node) : Prop :=\n  exists i, funct.(fn_code)!s = Some i.\n\nInductive wt_instr : instruction -> Prop :=\n  | wt_Inop:\n      forall s,\n      valid_successor s ->\n      wt_instr (Inop s)\n  | wt_Iopmove:\n      forall r1 r s,\n      env r = env r1 ->\n      valid_successor s ->\n      wt_instr (Iop Omove (r1 :: nil) r s)\n  | wt_Iop:\n      forall op args res s,\n      op <> Omove ->\n      map env args = fst (type_of_operation op) ->\n      env res = normalize (snd (type_of_operation op)) ->\n      valid_successor s ->\n      wt_instr (Iop op args res s)\n  | wt_Iload:\n      forall chunk addr args dst s,\n      map env args = type_of_addressing addr ->\n      env dst = normalize (type_of_chunk chunk) ->\n      valid_successor s ->\n      wt_instr (Iload chunk addr args dst s)\n  | wt_Istore:\n      forall chunk addr args src s,\n      map env args = type_of_addressing addr ->\n      env src = type_of_chunk_use chunk ->\n      valid_successor s ->\n      wt_instr (Istore chunk addr args src s)\n  | wt_Icall:\n      forall sig ros args res s,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      map env args = normalize_list sig.(sig_args) ->\n      env res = normalize (proj_sig_res sig) ->\n      valid_successor s ->\n      wt_instr (Icall sig ros args res s)\n  | wt_Itailcall:\n      forall sig ros args,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      map env args = normalize_list sig.(sig_args) ->\n      sig.(sig_res) = funct.(fn_sig).(sig_res) ->\n      tailcall_possible sig ->\n      wt_instr (Itailcall sig ros args)\n  | wt_Ibuiltin:\n      forall ef args res s,\n      map env args = normalize_list (ef_sig ef).(sig_args) ->\n      env res = normalize (proj_sig_res (ef_sig ef)) ->\n      valid_successor s ->\n      wt_instr (Ibuiltin ef args res s)\n  | wt_Icond:\n      forall cond args s1 s2,\n      map env args = type_of_condition cond ->\n      valid_successor s1 ->\n      valid_successor s2 ->\n      wt_instr (Icond cond args s1 s2)\n  | wt_Ijumptable:\n      forall arg tbl,\n      env arg = Tint ->\n      (forall s, In s tbl -> valid_successor s) ->\n      list_length_z tbl * 4 <= Int.max_unsigned ->\n      wt_instr (Ijumptable arg tbl)\n  | wt_Ireturn_none:\n      funct.(fn_sig).(sig_res) = None ->\n      wt_instr (Ireturn None)\n  | wt_Ireturn_some:\n      forall arg ty,\n      funct.(fn_sig).(sig_res) = Some ty ->\n      env arg = normalize ty ->\n      wt_instr (Ireturn (Some arg)).\n\nEnd WT_INSTR.\n\n(** A function [f] is well-typed w.r.t. a typing environment [env],\n   written [wt_function env f], if all instructions are well-typed,\n   parameters agree in types with the function signature, and\n   parameters are pairwise distinct. *)\n\nRecord wt_function (f: function) (env: regenv): Prop :=\n  mk_wt_function {\n    wt_params:\n      map env f.(fn_params) = normalize_list f.(fn_sig).(sig_args);\n    wt_norepet:\n      list_norepet f.(fn_params);\n    wt_instrs:\n      forall pc instr, \n      f.(fn_code)!pc = Some instr -> wt_instr f env instr;\n    wt_entrypoint:\n      valid_successor f f.(fn_entrypoint)\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef)\n  | wt_function_internal: forall f env,\n      wt_function f env ->\n      wt_fundef (Internal f).\n\n(** [CompCertX:test-compcert-void-symbols] We now allow a symbol to be\nassociated to no variable or function. *)\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, Some (Gfun f)) (prog_defs p) -> wt_fundef f.\n\n(** * Type inference *)\n\n(** Type inference reuses the generic solver for unification constraints\n  defined in module [Unityping]. *)\n\nModule RTLtypes <: TYPE_ALGEBRA.\n\nDefinition t := typ.\nDefinition eq := typ_eq.\nDefinition default := Tint.\n\nEnd RTLtypes.\n\nModule S := UniSolver(RTLtypes).\n\nSection INFERENCE.\n\nLocal Open Scope error_monad_scope.\n\nVariable f: function.\n\n(** Checking the validity of successor nodes. *)\n\nDefinition check_successor (s: node): res unit :=\n  match f.(fn_code)!s with\n  | None => Error (MSG \"bad successor \" :: POS s :: nil)\n  | Some i => OK tt\n  end.\n\nFixpoint check_successors (sl: list node): res unit :=\n  match sl with\n  | nil => OK tt\n  | s1 :: sl' => do x <- check_successor s1; check_successors sl'\n  end.\n\n(** Check structural constraints and process / record all type constraints. *)\n\nDefinition type_ros (e: S.typenv) (ros: reg + ident) : res S.typenv :=\n  match ros with\n  | inl r => S.set e r Tint\n  | inr s => OK e\n  end.\n\nDefinition is_move (op: operation) : bool :=\n  match op with Omove => true | _ => false end.\n\nDefinition type_instr (e: S.typenv) (i: instruction) : res S.typenv :=\n  match i with\n  | Inop s =>\n      do x <- check_successor s; OK e\n  | Iop op args res s =>\n      do x <- check_successor s;\n      if is_move op then\n        match args with\n        | arg :: nil => do (changed, e') <- S.move e res arg; OK e'\n        | _ => Error (msg \"ill-formed move\")\n        end\n      else\n       (let (targs, tres) := type_of_operation op in\n        do e1 <- S.set_list e args targs; S.set e1 res (normalize tres))\n  | Iload chunk addr args dst s =>\n      do x <- check_successor s;\n      do e1 <- S.set_list e args (type_of_addressing addr);\n      S.set e1 dst (normalize (type_of_chunk chunk))\n  | Istore chunk addr args src s =>\n      do x <- check_successor s;\n      do e1 <- S.set_list e args (type_of_addressing addr);\n      S.set e1 src (type_of_chunk_use chunk)\n  | Icall sig ros args res s =>\n      do x <- check_successor s;\n      do e1 <- type_ros e ros;\n      do e2 <- S.set_list e1 args (normalize_list sig.(sig_args));\n      S.set e2 res (normalize (proj_sig_res sig))\n  | Itailcall sig ros args =>\n      do e1 <- type_ros e ros;\n      do e2 <- S.set_list e1 args (normalize_list sig.(sig_args));\n      if opt_typ_eq sig.(sig_res) f.(fn_sig).(sig_res) then\n        if tailcall_is_possible sig\n        then OK e2\n        else Error(msg \"tailcall not possible\")\n      else Error(msg \"bad return type in tailcall\")\n  | Ibuiltin ef args res s =>\n      let sig := ef_sig ef in\n      do x <- check_successor s;\n      do e1 <- S.set_list e args (normalize_list sig.(sig_args));\n      S.set e1 res (normalize (proj_sig_res sig))\n | Icond cond args s1 s2 =>\n      do x1 <- check_successor s1;\n      do x2 <- check_successor s2;\n      S.set_list e args (type_of_condition cond)\n | Ijumptable arg tbl =>\n      do x <- check_successors tbl;\n      do e1 <- S.set e arg Tint;\n      if zle (list_length_z tbl * 4) Int.max_unsigned\n      then OK e1\n      else Error(msg \"jumptable too big\")\n  | Ireturn optres =>\n      match optres, f.(fn_sig).(sig_res) with\n      | None, None => OK e\n      | Some r, Some t => S.set e r (normalize t)\n      | _, _ => Error(msg \"bad return\")\n      end\n  end.\n\nDefinition type_code (e: S.typenv): res S.typenv :=\n  PTree.fold (fun re pc i =>\n    match re with\n    | Error _ => re\n    | OK e =>\n        match type_instr e i with\n        | Error msg => Error(MSG \"At PC \" :: POS pc :: MSG \": \" :: msg)\n        | OK e' => OK e'\n        end\n    end)\n  f.(fn_code) (OK e).\n\n(** Solve remaining constraints *)\n\nDefinition check_params_norepet (params: list reg): res unit := \n  if list_norepet_dec Reg.eq params\n  then OK tt\n  else Error(msg \"duplicate parameters\").\n\nDefinition type_function : res regenv :=\n  do e1 <- type_code S.initial;\n  do e2 <- S.set_list e1 f.(fn_params) (normalize_list f.(fn_sig).(sig_args));\n  do te <- S.solve e2;\n  do x1 <- check_params_norepet f.(fn_params);\n  do x2 <- check_successor f.(fn_entrypoint);\n  OK te.\n\n(** ** Soundness proof *)\n\nRemark type_ros_incr:\n  forall e ros e' te, type_ros e ros = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  unfold type_ros; intros. destruct ros. eauto with ty. inv H; auto with ty.\nQed.\n\nHint Resolve type_ros_incr: ty.\n\nLemma type_ros_sound:\n  forall e ros e' te, type_ros e ros = OK e' -> S.satisf te e' ->\n  match ros with inl r => te r = Tint | inr s => True end.\nProof.\n  unfold type_ros; intros. destruct ros. \n  eapply S.set_sound; eauto.\n  auto.\nQed.\n\nLemma check_successor_sound:\n  forall s x, check_successor s = OK x -> valid_successor f s.\nProof.\n  unfold check_successor, valid_successor; intros. \n  destruct (fn_code f)!s; inv H. exists i; auto.\nQed.\n\nHint Resolve check_successor_sound: ty.\n\nLemma check_successors_sound:\n  forall sl x, check_successors sl = OK x -> forall s, In s sl -> valid_successor f s.\nProof.\n  induction sl; simpl; intros. \n  contradiction.\n  monadInv H. destruct H0. subst a; eauto with ty. eauto. \nQed.\n\nLemma type_instr_incr:\n  forall e i e' te,\n  type_instr e i = OK e' -> S.satisf te e' -> S.satisf te e.\nProof.\n  intros; destruct i; try (monadInv H); eauto with ty.\n- (* op *)\n  destruct (is_move o) eqn:ISMOVE.\n  destruct l; try discriminate. destruct l; monadInv EQ0. eauto with ty.\n  destruct (type_of_operation o) as [targs tres] eqn:TYOP. monadInv EQ0. eauto with ty.\n- (* tailcall *)\n  destruct (opt_typ_eq (sig_res s) (sig_res (fn_sig f))); try discriminate.\n  destruct (tailcall_is_possible s) eqn:TCIP; inv EQ2.\n  eauto with ty.\n- (* jumptable *)\n  destruct (zle (list_length_z l * 4) Int.max_unsigned); inv EQ2.\n  eauto with ty.\n- (* return *)\n  simpl in H. destruct o as [r|] eqn: RET; destruct (sig_res (fn_sig f)) as [t|] eqn: RES; try discriminate.\n  eauto with ty.\n  inv H; auto with ty.\nQed.\n\nLemma type_instr_sound:\n  forall e i e' te,\n  type_instr e i = OK e' -> S.satisf te e' -> wt_instr f te i.\nProof.\n  intros; destruct i; try (monadInv H); simpl.\n- (* nop *)\n  constructor; eauto with ty.\n- (* op *)\n  destruct (is_move o) eqn:ISMOVE.\n  (* move *)\n  + assert (o = Omove) by (unfold is_move in ISMOVE; destruct o; congruence).\n    subst o.\n    destruct l; try discriminate. destruct l; monadInv EQ0.\n    constructor. eapply S.move_sound; eauto. eauto with ty.\n  + destruct (type_of_operation o) as [targs tres] eqn:TYOP. monadInv EQ0.\n    apply wt_Iop. \n    unfold is_move in ISMOVE; destruct o; congruence.\n    rewrite TYOP. eapply S.set_list_sound; eauto with ty.\n    rewrite TYOP. eapply S.set_sound; eauto with ty.\n    eauto with ty.\n- (* load *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* store *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* call *)\n  constructor. \n  eapply type_ros_sound; eauto with ty.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* tailcall *)\n  destruct (opt_typ_eq (sig_res s) (sig_res (fn_sig f))); try discriminate.\n  destruct (tailcall_is_possible s) eqn:TCIP; inv EQ2.\n  constructor.\n  eapply type_ros_sound; eauto with ty. \n  eapply S.set_list_sound; eauto with ty.\n  auto.\n  apply tailcall_is_possible_correct; auto.\n- (* builtin *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eapply S.set_sound; eauto with ty.\n  eauto with ty.\n- (* cond *)\n  constructor.\n  eapply S.set_list_sound; eauto with ty.\n  eauto with ty.\n  eauto with ty.\n- (* jumptable *)\n  destruct (zle (list_length_z l * 4) Int.max_unsigned); inv EQ2.\n  constructor.\n  eapply S.set_sound; eauto.\n  eapply check_successors_sound; eauto. \n  auto.\n- (* return *)\n  simpl in H. destruct o as [r|] eqn: RET; destruct (sig_res (fn_sig f)) as [t|] eqn: RES; try discriminate.\n  econstructor. eauto. eapply S.set_sound; eauto with ty.\n  inv H. constructor. auto. \nQed.\n\nLemma type_code_sound:\n  forall pc i e e' te,\n  type_code e = OK e' ->\n  f.(fn_code)!pc = Some i -> S.satisf te e' -> wt_instr f te i.\nProof.\n  intros pc i e0 e1 te TCODE.\n  set (P := fun c opte =>\n         match opte with\n         | Error _ => True\n         | OK e' => c!pc = Some i -> S.satisf te e' -> wt_instr f te i\n         end).\n  change (P f.(fn_code) (OK e1)).\n  rewrite <- TCODE. unfold type_code. apply PTree_Properties.fold_rec; unfold P; intros. \n  - (* extensionality *)\n    destruct a; auto; intros. rewrite <- H in H1. eapply H0; eauto. \n  - (* base case *)\n    rewrite PTree.gempty in H; discriminate.\n  - (* inductive case *)\n    destruct a as [e|?]; auto. \n    destruct (type_instr e v) as [e'|?] eqn:TYINSTR; auto.\n    intros. rewrite PTree.gsspec in H2. destruct (peq pc k). \n    inv H2. eapply type_instr_sound; eauto. \n    eapply H1; eauto. eapply type_instr_incr; eauto.\nQed.\n\nTheorem type_function_correct:\n  forall env, type_function = OK env -> wt_function f env.\nProof.\n  unfold type_function; intros. monadInv H.\n  assert (SAT0: S.satisf env x0) by (eapply S.solve_sound; eauto).\n  assert (SAT1: S.satisf env x) by (eauto with ty).\n  constructor.\n- (* type of parameters *)\n  eapply S.set_list_sound; eauto.\n- (* parameters are unique *)\n  unfold check_params_norepet in EQ2. \n  destruct (list_norepet_dec Reg.eq (fn_params f)); inv EQ2; auto. \n- (* instructions are well typed *)\n  intros. eapply type_code_sound; eauto. \n- (* entry point is valid *)\n  eauto with ty. \nQed.\n\n(** ** Completeness proof *)\n\nLemma type_ros_complete:\n  forall te ros e,\n  S.satisf te e ->\n  match ros with inl r => te r = Tint | inr s => True end ->\n  exists e', type_ros e ros = OK e' /\\ S.satisf te e'.\nProof.\n  intros; destruct ros; simpl. \n  eapply S.set_complete; eauto.\n  exists e; auto.\nQed.\n\nLemma check_successor_complete:\n  forall s, valid_successor f s -> check_successor s = OK tt.\nProof.\n  unfold valid_successor, check_successor; intros. \n  destruct H as [i EQ]; rewrite EQ; auto.\nQed.\n\nLemma type_instr_complete:\n  forall te e i,\n  S.satisf te e ->\n  wt_instr f te i ->\n  exists e', type_instr e i = OK e' /\\ S.satisf te e'.\nProof.\n  induction 2; simpl.\n- (* nop *)\n  econstructor; split. rewrite check_successor_complete; simpl; eauto. auto.\n- (* move *)\n  exploit S.move_complete; eauto. intros (changed & e' & A & B).\n  exists e'; split. rewrite check_successor_complete by auto; simpl. rewrite A; auto. auto.\n- (* other op *)\n  destruct (type_of_operation op) as [targ tres]. simpl in *.\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl. \n  replace (is_move op) with false. rewrite A; simpl; rewrite C; auto.\n  destruct op; reflexivity || congruence.\n- (* load *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl. \n  rewrite A; simpl; rewrite C; auto.\n- (* store *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl. \n  rewrite A; simpl; rewrite C; auto.\n- (* call *)\n  exploit type_ros_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_list_complete. eauto. eauto. intros [e2 [C D]].\n  exploit S.set_complete. eexact D. eauto. intros [e3 [E F]].\n  exists e3; split; auto. \n  rewrite check_successor_complete by auto; simpl. \n  rewrite A; simpl; rewrite C; simpl; rewrite E; auto.\n- (* tailcall *)\n  exploit type_ros_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_list_complete. eauto. eauto. intros [e2 [C D]].\n  exists e2; split; auto. \n  rewrite A; simpl; rewrite C; simpl. \n  rewrite H2; rewrite dec_eq_true. \n  replace (tailcall_is_possible sig) with true; auto. \n  revert H3. unfold tailcall_possible, tailcall_is_possible. generalize (loc_arguments sig). \n  induction l; simpl; intros. auto.\n  exploit (H3 a); auto. intros. destruct a; try contradiction. apply IHl.\n  intros; apply H3; auto. \n- (* builtin *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exploit S.set_complete. eexact B. eauto. intros [e2 [C D]].\n  exists e2; split; auto.\n  rewrite check_successor_complete by auto; simpl. \n  rewrite A; simpl; rewrite C; auto.\n- (* cond *)\n  exploit S.set_list_complete. eauto. eauto. intros [e1 [A B]].\n  exists e1; split; auto.\n  rewrite check_successor_complete by auto; simpl. \n  rewrite check_successor_complete by auto; simpl.\n  auto.\n- (* jumptbl *)\n  exploit S.set_complete. eauto. eauto. intros [e1 [A B]].\n  exists e1; split; auto.\n  replace (check_successors tbl) with (OK tt). simpl. \n  rewrite A; simpl. apply zle_true; auto. \n  revert H1. generalize tbl. induction tbl0; simpl; intros. auto. \n  rewrite check_successor_complete by auto; simpl.\n  apply IHtbl0; intros; auto.\n- (* return none *)\n  rewrite H0. exists e; auto.\n- (* return some *)\n  rewrite H0. apply S.set_complete; auto.\nQed.\n\nLemma type_code_complete:\n  forall te e,\n  (forall pc instr, f.(fn_code)!pc = Some instr -> wt_instr f te instr) ->\n  S.satisf te e ->\n  exists e', type_code e = OK e' /\\ S.satisf te e'.\nProof.\n  intros te e0 WTC SAT0.\n  set (P := fun c res =>\n        (forall pc i, c!pc = Some i -> wt_instr f te i) ->\n        exists e', res = OK e' /\\ S.satisf te e').\n  assert (P f.(fn_code) (type_code e0)).\n  {\n    unfold type_code. apply PTree_Properties.fold_rec; unfold P; intros.\n    - apply H0. intros. apply H1 with pc. rewrite <- H; auto. \n    - exists e0; auto. \n    - destruct H1 as [e [A B]]. \n      intros. apply H2 with pc. rewrite PTree.gso; auto. congruence.\n      subst a. \n      destruct (type_instr_complete te e v) as [e' [C D]].\n      auto. apply H2 with k. apply PTree.gss. \n      exists e'; split; auto. rewrite C; auto. \n  }\n  apply H; auto.\nQed.\n\nTheorem type_function_complete:\n  forall te, wt_function f te -> exists te, type_function = OK te.\nProof.\n  intros. destruct H. \n  destruct (type_code_complete te S.initial) as (e1 & A & B).\n  auto. apply S.satisf_initial. \n  destruct (S.set_list_complete te f.(fn_params) (normalize_list f.(fn_sig).(sig_args)) e1) as (e2 & C & D); auto.\n  destruct (S.solve_complete te e2) as (te' & E); auto.\n  exists te'; unfold type_function.\n  rewrite A; simpl. rewrite C; simpl. rewrite E; simpl. \n  unfold check_params_norepet. rewrite pred_dec_true; auto. simpl. \n  rewrite check_successor_complete by auto. auto. \nQed.\n\nEnd INFERENCE.\n\n(** * Type preservation during evaluation *)\n\n(** The type system for RTL is not sound in that it does not guarantee\n  progress: well-typed instructions such as [Icall] can fail because\n  of run-time type tests (such as the equality between callee and caller's\n  signatures).  However, the type system guarantees a type preservation\n  property: if the execution does not fail because of a failed run-time\n  test, the result values and register states match the static\n  typing assumptions.  This preservation property will be useful\n  later for the proof of semantic equivalence between [Linear] and [Mach].\n  Even though we do not need it for [RTL], we show preservation for [RTL]\n  here, as a warm-up exercise and because some of the lemmas will be\n  useful later. *)\n\nDefinition wt_regset (env: regenv) (rs: regset) : Prop :=\n  forall r, Val.has_type (rs#r) (env r).\n\nLemma wt_regset_assign:\n  forall env rs v r,\n  wt_regset env rs ->\n  Val.has_type v (env r) ->\n  wt_regset env (rs#r <- v).\nProof.\n  intros; red; intros. \n  rewrite Regmap.gsspec.\n  case (peq r0 r); intro.\n  subst r0. assumption.\n  apply H.\nQed.\n\nLemma normalize_subtype:\n  forall ty, subtype ty (normalize ty) = true.\nProof.\n  intros. destruct ty; reflexivity.\nQed.\n\nLemma wt_regset_assign2:\n  forall env rs v r ty,\n  wt_regset env rs ->\n  Val.has_type v ty ->\n  env r = normalize ty ->\n  wt_regset env (rs#r <- v).\nProof.\n  intros. eapply wt_regset_assign; eauto.\n  rewrite H1. eapply Val.has_subtype; eauto. apply normalize_subtype.\nQed.\n\nLemma wt_regset_list:\n  forall env rs,\n  wt_regset env rs ->\n  forall rl, Val.has_type_list (rs##rl) (List.map env rl).\nProof.\n  induction rl; simpl.\n  auto.\n  split. apply H. apply IHrl.\nQed.  \n\nLemma wt_init_regs:\n  forall env rl args,\n  Val.has_type_list args (List.map env rl) ->\n  wt_regset env (init_regs args rl).\nProof.\n  induction rl; destruct args; simpl; intuition.\n  red; intros. rewrite Regmap.gi. simpl; auto. \n  apply wt_regset_assign; auto.\nQed.\n\n(** [CompCertX:test-compcert-param-memory] We create section [WITHMEM] and associated\n contexts to parameterize the proof over the memory model. *)\n(** [CompCertX:test-compcert-param-extcall] Actually, we also need to parameterize\n    over external functions. To this end, we created a [CompilerConfiguration] class\n    (cf. [Events]) which is designed to be the single class on which the whole CompCert is to be\n    parameterized. It includes all operations and properties on which CompCert depends:\n    memory model, semantics of external functions and their preservation through\n    compilation. *)\nSection WITHCONFIG.\nContext `{compiler_config: CompilerConfiguration}.\n\nLemma wt_exec_Iop:\n  forall (ge: genv) env f sp op args res s rs m v,\n  wt_instr f env (Iop op args res s) ->\n  eval_operation ge sp op rs##args m = Some v ->\n  wt_regset env rs ->\n  wt_regset env (rs#res <- v).\nProof.\n  intros. inv H. \n  simpl in H0. inv H0. apply wt_regset_assign; auto.\n  rewrite H4; auto.\n  eapply wt_regset_assign2; auto.\n  eapply type_of_operation_sound; eauto.\n  auto.\nQed.\n\nLemma wt_exec_Iload:\n  forall env f chunk addr args dst s m a v rs,\n  wt_instr f env (Iload chunk addr args dst s) ->\n  Mem.loadv chunk m a = Some v ->\n  wt_regset env rs ->\n  wt_regset env (rs#dst <- v).\nProof.\n  intros. destruct a; simpl in H0; try discriminate. inv H.\n  eapply wt_regset_assign2; eauto.\n  eapply Mem.load_type; eauto.\nQed.\n\nLemma wt_exec_Ibuiltin:\n  forall WB: _ -> Prop,\n  forall env f ef (ge: genv) args res s vargs m t vres m' rs,\n  wt_instr f env (Ibuiltin ef args res s) ->\n  external_call ef WB ge vargs m t vres m' ->\n  wt_regset env rs ->\n  wt_regset env (rs#res <- vres).\nProof.\n  intros. inv H. \n  eapply wt_regset_assign2; eauto. \n  eapply external_call_well_typed; eauto.\nQed.\n\nLemma wt_instr_at:\n  forall f env pc i,\n  wt_function f env -> f.(fn_code)!pc = Some i -> wt_instr f env i.\nProof.\n  intros. inv H. eauto. \nQed.\n\n(** [CompCertX:test-compcert-per-function] We must not assume that\nmain will return Tint. So, we parameterize over its return type,\n[rettyp]. *)\n\nSection WITHRETTYP.\nVariable rettyp: option typ.\n\nInductive wt_stackframes: list stackframe -> signature -> Prop :=\n  | wt_stackframes_nil: forall sg,\n      sg.(sig_res) = rettyp ->\n      wt_stackframes nil sg\n  | wt_stackframes_cons:\n      forall s res f sp pc rs env sg,\n      wt_function f env ->\n      wt_regset env rs ->\n      env res = normalize (proj_sig_res sg) ->\n      wt_stackframes s (fn_sig f) ->\n      wt_stackframes (Stackframe res f sp pc rs :: s) sg.\n\nInductive wt_state: state -> Prop :=\n  | wt_state_intro:\n      forall s f sp pc rs m env\n        (WT_STK: wt_stackframes s (fn_sig f))\n        (WT_FN: wt_function f env)\n        (WT_RS: wt_regset env rs),\n      wt_state (State s f sp pc rs m)\n  | wt_state_call:\n      forall s f args m,\n      wt_stackframes s (funsig f) ->\n      wt_fundef f ->\n      Val.has_type_list args (normalize_list (sig_args (funsig f))) ->\n      wt_state (Callstate s f args m)\n  | wt_state_return:\n      forall s v m sg,\n      wt_stackframes s sg ->\n      Val.has_type v (normalize (proj_sig_res sg)) ->\n      wt_state (Returnstate s v m).\n\nEnd WITHRETTYP.\n\nRemark wt_stackframes_change_sig:\n  forall rettyp,\n  forall s sg1 sg2,\n  sg1.(sig_res) = sg2.(sig_res) -> wt_stackframes rettyp s sg1 -> wt_stackframes rettyp s sg2.\nProof.\n  intros. inv H0. \n- constructor; congruence.\n- econstructor; eauto. rewrite H3. unfold proj_sig_res. rewrite H. auto. \nQed.\n\nSection SUBJECT_REDUCTION.\n\nVariable p: program.\n\nHypothesis wt_p: wt_program p.\n\nLet ge := Genv.globalenv p.\n\nSection WITHWRITABLEBLOCK.\n(** [CompCertX:test-compcert-protect-stack-arg] We also parameterize over a way to mark blocks writable. *)\nContext `{writable_block_ops: WritableBlockOps}.\n\nLemma subject_reduction:\n  forall rettyp,\n  forall st1 t st2, step ge st1 t st2 ->\n  forall (WT: wt_state rettyp st1), wt_state rettyp st2.\nProof.\n  induction 1; intros; inv WT;\n  try (generalize (wt_instrs _ _ WT_FN pc _ H); intros WTI).\n  (* Inop *)\n  econstructor; eauto.\n  (* Iop *)\n  econstructor; eauto. eapply wt_exec_Iop; eauto.\n  (* Iload *)\n  econstructor; eauto. eapply wt_exec_Iload; eauto.\n  (* Istore *)\n  econstructor; eauto.\n  (* Icall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  econstructor; eauto. inv WTI; auto. \n  inv WTI. rewrite <- H8. apply wt_regset_list. auto.\n  (* Itailcall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  inv WTI. apply wt_stackframes_change_sig with (fn_sig f); auto.\n  inv WTI. rewrite <- H7. apply wt_regset_list. auto.\n  (* Ibuiltin *)\n  econstructor; eauto. eapply wt_exec_Ibuiltin; eauto.\n  (* Icond *)\n  econstructor; eauto.\n  (* Ijumptable *)\n  econstructor; eauto.\n  (* Ireturn *)\n  econstructor; eauto. \n  inv WTI; simpl. auto. unfold proj_sig_res; rewrite H2. rewrite <- H3. auto. \n  (* internal function *)\n  simpl in *. inv H5.\n  econstructor; eauto.\n  inv H1. apply wt_init_regs; auto. rewrite wt_params0. auto. \n  (* external function *)\n  econstructor; eauto. simpl.  \n  change (Val.has_type res (normalize (proj_sig_res (ef_sig ef)))).\n  eapply Val.has_subtype. apply normalize_subtype. \n  eapply external_call_well_typed; eauto.\n  (* return *)\n  inv H1. econstructor; eauto.\n  apply wt_regset_assign; auto. rewrite H10; auto. \nQed.\n\nEnd WITHWRITABLEBLOCK.\n\n(** [CompCertX:test-compcert-per-function] For whole programs, main will indeed return Tint. *)\n\nLemma wt_initial_state:\n  forall S, initial_state p S -> wt_state (Some Tint) S.\nProof.\n  intros. inv H. constructor. constructor. rewrite H3; auto. \n  pattern f. apply Genv.find_funct_ptr_prop with fundef unit p b.\n  exact wt_p. exact H2.\n  rewrite H3. constructor.\nQed.\n\nLemma wt_instr_inv:\n  forall rettyp,\n  forall s f sp pc rs m i,\n  wt_state rettyp (State s f sp pc rs m) ->\n  f.(fn_code)!pc = Some i ->\n  exists env, wt_instr f env i /\\ wt_regset env rs.\nProof.\n  intros. inv H. exists env; split; auto. \n  inv WT_FN. eauto. \nQed.\n\nEnd SUBJECT_REDUCTION.\n\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/compcert/backend/RTLtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.1843200689308583}}
{"text": "Require Import Bedrock.Platform.AutoSep Bedrock.Platform.Malloc Bedrock.Platform.Bootstrap Bedrock.Platform.Cito.examples.FactorialRecur.\n\n\nModule Type S.\n  Parameter heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($ (size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "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/FactorialRecurDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.18432006352351596}}
{"text": "Add Search Blacklist \"Private_\" \"_subproof\".\nSet Printing Depth 50.\nRemove Search Blacklist \"Private_\" \"_subproof\".\nAdd Search Blacklist \"Private_\" \"_subproof\".\nAdd LoadPath \"../..\".\nRequire Import BetaJulia.BasicPLDefs.Identifier.\nRequire Import BetaJulia.Sub0280a.BaseDefs.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nOpen Scope btjt.\nLemma cname_eq__decidable : forall n1 n2 : cname, Decidable.decidable (n1 = n2).\nProof.\n(intros n1 n2; destruct n1; destruct n2; (left; reflexivity) || (right; intros H; inversion H)).\nQed.\nLemma fresh_union__inv : forall (X : id) (fvs1 fvs2 : id_set), fresh X (IdSet.union fvs1 fvs2) -> fresh X fvs1 /\\ fresh X fvs2.\nProof.\n(intros X fvs1 fvs2 H).\n(unfold fresh in *).\n(split; intros Hcontra).\nSearch -IdSet.union.\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/7/user-7-session-115.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.1842274180910714}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import LeadersHaveLeaderLogsInterface.\n\nSection LeadersHaveLeaderLogs.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Lemma handleRequestVoteReply_spec :\n    forall h st h' t r st',\n      st' = handleRequestVoteReply h st h' t r ->\n      log st' = log st /\\\n      ((currentTerm st' = currentTerm st /\\ type st' = type st) \\/\n       type st' = Follower \\/ (type st = Candidate /\\ type st' = Leader)).\n  Proof using. \n    intros.\n    unfold handleRequestVoteReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition.\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  Ltac start :=\n    red; unfold leaders_have_leaderLogs; intros;\n    subst; simpl in *; find_higher_order_rewrite;\n    update_destruct_hyp; subst; rewrite_update; eauto; simpl in *.\n\n  Lemma leaders_have_leaderLogs_appendEntries :\n    refined_raft_net_invariant_append_entries leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp handleAppendEntries_type. intuition; try congruence.\n    rewrite update_elections_data_appendEntries_leaderLogs.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_appendEntriesReply :\n    refined_raft_net_invariant_append_entries_reply leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp handleAppendEntriesReply_type. intuition; try congruence.\n    repeat find_rewrite. eauto.\n  Qed.\n\n\n  Lemma leaders_have_leaderLogs_requestVote :\n    refined_raft_net_invariant_request_vote leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp handleRequestVote_type. intuition; try congruence.\n    rewrite leaderLogs_update_elections_data_requestVote.\n    repeat find_rewrite. eauto.\n  Qed.\n  \n  \n  Lemma leaders_have_leaderLogs_requestVoteReply :\n    refined_raft_net_invariant_request_vote_reply leaders_have_leaderLogs.\n  Proof using. \n    start.\n    unfold update_elections_data_requestVoteReply.\n    break_match; unfold raft_data in *;\n    try solve [repeat find_rewrite; congruence].\n    simpl in *.\n    match goal with\n      | |- context [ handleRequestVoteReply ?h ?st ?s ?t ?v ] =>\n        pose proof handleRequestVoteReply_spec h st s t v (handleRequestVoteReply h st s t v)\n    end. intuition; break_if; intuition; simpl in *; repeat find_rewrite; eauto; congruence.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_clientRequest :\n    refined_raft_net_invariant_client_request leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp handleClientRequest_type. intuition; try congruence.\n    rewrite update_elections_data_client_request_leaderLogs.\n    repeat find_rewrite. eauto.\n  Qed.\n\n\n  Lemma leaders_have_leaderLogs_timeout :\n    refined_raft_net_invariant_timeout leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp handleTimeout_type. intuition; try congruence.\n    rewrite update_elections_data_timeout_leaderLogs.\n    repeat find_rewrite. eauto.\n  Qed.\n\n\n  Lemma leaders_have_leaderLogs_doGenericServer :\n    refined_raft_net_invariant_do_generic_server leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp doGenericServer_type. intuition; try congruence.\n    match goal with\n      | [ H : forall _, _ -> exists _, _, h : name |- _ ] =>\n        specialize (H h)\n    end.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_doLeader :\n    refined_raft_net_invariant_do_leader leaders_have_leaderLogs.\n  Proof using. \n    start.\n    find_apply_lem_hyp doLeader_type. intuition; try congruence.\n    match goal with\n      | [ H : forall _, _ -> exists _, _, h : name |- _ ] =>\n        specialize (H h)\n    end.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_init :\n    refined_raft_net_invariant_init leaders_have_leaderLogs.\n  Proof using. \n    red. unfold leaders_have_leaderLogs, step_m_init.\n    intros. simpl in *. congruence.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_state_same_packets_subset :\n    refined_raft_net_invariant_state_same_packet_subset leaders_have_leaderLogs.\n  Proof using. \n    red. unfold leaders_have_leaderLogs. intros.\n    repeat find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma leaders_have_leaderLogs_reboot :\n    refined_raft_net_invariant_reboot leaders_have_leaderLogs.\n  Proof using. \n    start. congruence.\n  Qed.\n  \n  Instance lhlli : leaders_have_leaderLogs_interface.\n  Proof.\n    split.\n    intros. eapply refined_raft_net_invariant; eauto.\n    - apply leaders_have_leaderLogs_init.\n    - apply leaders_have_leaderLogs_clientRequest.\n    - apply leaders_have_leaderLogs_timeout.\n    - apply leaders_have_leaderLogs_appendEntries.\n    - apply leaders_have_leaderLogs_appendEntriesReply.\n    - apply leaders_have_leaderLogs_requestVote.\n    - apply leaders_have_leaderLogs_requestVoteReply.\n    - apply leaders_have_leaderLogs_doLeader.\n    - apply leaders_have_leaderLogs_doGenericServer.\n    - apply leaders_have_leaderLogs_state_same_packets_subset.\n    - apply leaders_have_leaderLogs_reboot.\n  Qed.\nEnd LeadersHaveLeaderLogs.", "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/LeadersHaveLeaderLogsProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.18422741443769808}}
{"text": "From stdpp Require Import finite.\nFrom iris.algebra Require Export cmra updates.\nFrom iris.bi Require Import notation.\nFrom iris.prelude Require Import options.\n\nLocal Hint Extern 1 (_ \u227c _) => etrans; [eassumption|] : core.\nLocal Hint Extern 1 (_ \u227c _) => etrans; [|eassumption] : core.\nLocal Hint Extern 10 (_ \u2264 _) => lia : core.\n\n(** The basic definition of the uPred type, its metric and functor laws.\n    You probably do not want to import this file. Instead, import\n    base_logic.base_logic; that will also give you all the primitive\n    and many derived laws for the logic. *)\n\n(** A good way of understanding this definition of the uPred OFE is to\n   consider the OFE uPred0 of monotonous SProp predicates. That is,\n   uPred0 is the OFE of non-expansive functions from M to SProp that\n   are monotonous with respect to CMRA inclusion. This notion of\n   monotonicity has to be stated in the SProp logic. Together with the\n   usual closedness property of SProp, this gives exactly uPred_mono.\n\n   Then, we quotient uPred0 *in the sProp logic* with respect to\n   equivalence on valid elements of M. That is, we quotient with\n   respect to the following *sProp* equivalence relation:\n     P1 \u2261 P2 := \u2200 x, \u2713 x \u2192 (P1(x) \u2194 P2(x))       (1)\n   When seen from the ambiant logic, obtaining this quotient requires\n   definig both a custom Equiv and Dist.\n\n\n   It is worth noting that this equivalence relation admits canonical\n   representatives. More precisely, one can show that every\n   equivalence class contains exactly one element P0 such that:\n     \u2200 x, (\u2713 x \u2192 P0(x)) \u2192 P0(x)                 (2)\n   (Again, this assertion has to be understood in sProp). Intuitively,\n   this says that P0 trivially holds whenever the resource is invalid.\n   Starting from any element P, one can find this canonical\n   representative by choosing:\n     P0(x) := \u2713 x \u2192 P(x)                        (3)\n\n   Hence, as an alternative definition of uPred, we could use the set\n   of canonical representatives (i.e., the subtype of monotonous\n   sProp predicates that verify (2)). This alternative definition would\n   save us from using a quotient. However, the definitions of the various\n   connectives would get more complicated, because we have to make sure\n   they all verify (2), which sometimes requires some adjustments. We\n   would moreover need to prove one more property for every logical\n   connective.\n *)\n\n(** Note that, somewhat curiously, [uPred M] is *not* in general a Camera,\n   at least not if all propositions are considered \"valid\" Camera elements.\n   It fails to satisfy the extension axiom. Here is the counterexample:\n\nWe use [M := (option Ex {A,B})^2] -- so we have pairs\nwhose components are \u03b5, A or B.\n\nLet\n[[\n  P r n := (ownM (A,A) \u2227 \u25b7 False) \u2228 ownM (A,B) \u2228 ownM (B,A) \u2228 ownM (B,B)\n         \u2194 r = (A,A) \u2227 n = 0 \u2228\n           r = (A,B) \u2228\n           r = (B,A) \u2228\n           r = (B,B)\n Q1 r n := ownM (A, \u03b5) \u2228 ownM (B, \u03b5)\n         \u2194 (A, \u03b5) \u227c r \u2228 (B, \u03b5) \u227c r\n           (\"Left component is not \u03b5\")\n Q2 r n := ownM (\u03b5, A) \u2228 ownM (\u03b5, B)\n         \u2194 (\u03b5, A) \u227c r \u2228 (\u03b5, B) \u227c r\n           (\"Right component is not \u03b5\")\n]]\nThese are all sufficiently closed and non-expansive and whatnot.\nWe have [P \u2261{0}\u2261 Q1 * Q2]. So assume extension holds, then we get Q1', Q2'\nsuch that\n[[\n  P \u2261 Q1' \u2217 Q2'\n Q1 \u2261{0}\u2261 Q1'\n Q2 \u2261{0}\u2261 Q2'\n]]\nNow comes the contradiction:\nWe know that [P (A,A) 1] does *not* hold, but I am going to show that\n[(Q1' \u2217 Q2') (A,A) 1] holds, which would be a contraction.\nTo this end, I will show (a) [Q1' (A,\u03b5) 1] and (b) [Q2' (\u03b5,A) 1].\nThe result [(Q1' \u2217 Q2') (A,A)] follows from [(A,\u03b5) \u22c5 (\u03b5,A) = (A,A)].\n\n(a) Proof of [Q1' (A,\u03b5) 1].\n    We have [P (A,B) 1], and thus [Q1' r1 1] and [Q2' r2 1] for some\n    [r1 \u22c5 r2 = (A,B)]. There are four possible decompositions [r1 \u22c5 r2]:\n    - [(\u03b5,\u03b5) \u22c5 (A,B)]: This would give us [Q1' (\u03b5,\u03b5) 1], from which we\n      obtain (through down-closure and the equality [Q1 \u2261{0}\u2261 Q1'] above) that\n      [Q1 (\u03b5,\u03b5) 0]. However, we know that's false.\n    - [(A,B) \u22c5 (\u03b5,\u03b5)]: Can be excluded for similar reasons\n      (the second resource must not be \u03b5 in the 2nd component).\n    - [(\u03b5,B) \u22c5 (A,\u03b5)]: Can be excluded for similar reasons\n      (the first resource must not be \u03b5 in the 1st component).\n    - [(A,\u03b5) \u22c5 (\u03b5,B)]: This gives us the desired [Q1' (A,\u03b5) 1].\n\n(b) Proof of [Q2' (\u03b5,A) 1].\n    We have [P (B,A) 1], and thus [Q1' r1 1] and [Q2' r2 1] for some\n    [r1 \u22c5 r2 = (B,A)]. There are again four possible decompositions,\n    and like above we can exclude three of them. This leaves us with\n    [(B,\u03b5) \u22c5 (\u03b5,A)] and thus [Q2' (\u03b5,A) 1].\n\nThis completes the proof.\n\n*)\n\nRecord uPred (M : ucmra) : Type := UPred {\n  uPred_holds : nat \u2192 M \u2192 Prop;\n\n  uPred_mono n1 n2 x1 x2 :\n    uPred_holds n1 x1 \u2192 x1 \u227c{n2} x2 \u2192 n2 \u2264 n1 \u2192 uPred_holds n2 x2\n}.\n(** When working in the model, it is convenient to be able to treat [uPred] as\n[nat \u2192 M \u2192 Prop].  But we only want to locally break the [uPred] abstraction\nthis way. *)\nLocal Coercion uPred_holds : uPred >-> Funclass.\nBind Scope bi_scope with uPred.\nGlobal Arguments uPred_holds {_} _%I _ _ : simpl never.\nAdd Printing Constructor uPred.\nGlobal Instance: Params (@uPred_holds) 3 := {}.\n\nSection cofe.\n  Context {M : ucmra}.\n\n  Inductive uPred_equiv' (P Q : uPred M) : Prop :=\n    { uPred_in_equiv : \u2200 n x, \u2713{n} x \u2192 P n x \u2194 Q n x }.\n  Local Instance uPred_equiv : Equiv (uPred M) := uPred_equiv'.\n  Inductive uPred_dist' (n : nat) (P Q : uPred M) : Prop :=\n    { uPred_in_dist : \u2200 n' x, n' \u2264 n \u2192 \u2713{n'} x \u2192 P n' x \u2194 Q n' x }.\n  Local Instance uPred_dist : Dist (uPred M) := uPred_dist'.\n  Definition uPred_ofe_mixin : OfeMixin (uPred M).\n  Proof.\n    split.\n    - intros P Q; split.\n      + by intros HPQ n; split=> i x ??; apply HPQ.\n      + intros HPQ; split=> n x ?; apply HPQ with n; auto.\n    - intros n; split.\n      + by intros P; split=> x i.\n      + by intros P Q HPQ; split=> x i ??; symmetry; apply HPQ.\n      + intros P Q Q' HP HQ; split=> i x ??.\n        by trans (Q i x);[apply HP|apply HQ].\n    - intros n P Q HPQ; split=> i x ??; apply HPQ; auto.\n  Qed.\n  Canonical Structure uPredO : ofe := Ofe (uPred M) uPred_ofe_mixin.\n\n  Program Definition uPred_compl : Compl uPredO := \u03bb c,\n    {| uPred_holds n x := \u2200 n', n' \u2264 n \u2192 \u2713{n'} x \u2192 c n' n' x |}.\n  Next Obligation.\n    move=> /= c n1 n2 x1 x2 HP Hx12 Hn12 n3 Hn23 Hv. eapply uPred_mono.\n    - eapply HP, cmra_validN_includedN, cmra_includedN_le=>//; lia.\n    - eapply cmra_includedN_le=>//; lia.\n    - done.\n  Qed.\n  Global Program Instance uPred_cofe : Cofe uPredO := {| compl := uPred_compl |}.\n  Next Obligation.\n    intros n c; split=>i x Hin Hv.\n    etrans; [|by symmetry; apply (chain_cauchy c i n)]. split=>H; [by apply H|].\n    repeat intro. apply (chain_cauchy c _ i)=>//. by eapply uPred_mono.\n  Qed.\nEnd cofe.\nGlobal Arguments uPredO : clear implicits.\n\nGlobal Instance uPred_ne {M} (P : uPred M) n : Proper (dist n ==> iff) (P n).\nProof.\n  intros x1 x2 Hx; split=> ?; eapply uPred_mono; eauto; by rewrite Hx.\nQed.\nGlobal Instance uPred_proper {M} (P : uPred M) n : Proper ((\u2261) ==> iff) (P n).\nProof. by intros x1 x2 Hx; apply uPred_ne, equiv_dist. Qed.\n\nLemma uPred_holds_ne {M} (P Q : uPred M) n1 n2 x :\n  P \u2261{n2}\u2261 Q \u2192 n2 \u2264 n1 \u2192 \u2713{n2} x \u2192 Q n1 x \u2192 P n2 x.\nProof.\n  intros [Hne] ???. eapply Hne; try done. eauto using uPred_mono, cmra_validN_le.\nQed.\n\n(* Equivalence to the definition of uPred in the appendix. *)\nLemma uPred_alt {M : ucmra} (P: nat \u2192 M \u2192 Prop) :\n  (\u2200 n1 n2 x1 x2, P n1 x1 \u2192 x1 \u227c{n1} x2 \u2192 n2 \u2264 n1 \u2192 P n2 x2) \u2194\n  ( (\u2200 x n1 n2, n2 \u2264 n1 \u2192 P n1 x \u2192 P n2 x) (* Pointwise down-closed *)\n  \u2227 (\u2200 n x1 x2, x1 \u2261{n}\u2261 x2 \u2192 \u2200 m, m \u2264 n \u2192 P m x1 \u2194 P m x2) (* Non-expansive *)\n  \u2227 (\u2200 n x1 x2, x1 \u227c{n} x2 \u2192 \u2200 m, m \u2264 n \u2192 P m x1 \u2192 P m x2) (* Monotonicity *)\n  ).\nProof.\n  (* Provide this lemma to eauto. *)\n  assert (\u2200 n1 n2 (x1 x2 : M), n2 \u2264 n1 \u2192 x1 \u2261{n1}\u2261 x2 \u2192 x1 \u227c{n2} x2).\n  { intros ????? H. eapply cmra_includedN_le; last done. by rewrite H. }\n  (* Now go ahead. *)\n  split.\n  - intros Hupred. repeat split; eauto using cmra_includedN_le.\n  - intros (Hdown & _ & Hmono) **. eapply Hmono; [done..|]. eapply Hdown; done.\nQed.\n\n(** functor *)\nProgram Definition uPred_map {M1 M2 : ucmra} (f : M2 -n> M1)\n  `{!CmraMorphism f} (P : uPred M1) :\n  uPred M2 := {| uPred_holds n x := P n (f x) |}.\nNext Obligation. naive_solver eauto using uPred_mono, cmra_morphism_monotoneN. Qed.\n\nGlobal Instance uPred_map_ne {M1 M2 : ucmra} (f : M2 -n> M1)\n  `{!CmraMorphism f} n : Proper (dist n ==> dist n) (uPred_map f).\nProof.\n  intros x1 x2 Hx; split=> n' y ??.\n  split; apply Hx; auto using cmra_morphism_validN.\nQed.\nLemma uPred_map_id {M : ucmra} (P : uPred M): uPred_map cid P \u2261 P.\nProof. by split=> n x ?. Qed.\nLemma uPred_map_compose {M1 M2 M3 : ucmra} (f : M1 -n> M2) (g : M2 -n> M3)\n    `{!CmraMorphism f, !CmraMorphism g} (P : uPred M3):\n  uPred_map (g \u25ce f) P \u2261 uPred_map f (uPred_map g P).\nProof. by split=> n x Hx. Qed.\nLemma uPred_map_ext {M1 M2 : ucmra} (f g : M1 -n> M2)\n      `{!CmraMorphism f} `{!CmraMorphism g}:\n  (\u2200 x, f x \u2261 g x) \u2192 \u2200 x, uPred_map f x \u2261 uPred_map g x.\nProof. intros Hf P; split=> n x Hx /=; by rewrite /uPred_holds /= Hf. Qed.\nDefinition uPredO_map {M1 M2 : ucmra} (f : M2 -n> M1) `{!CmraMorphism f} :\n  uPredO M1 -n> uPredO M2 := OfeMor (uPred_map f : uPredO M1 \u2192 uPredO M2).\nLemma uPredO_map_ne {M1 M2 : ucmra} (f g : M2 -n> M1)\n    `{!CmraMorphism f, !CmraMorphism g} n :\n  f \u2261{n}\u2261 g \u2192 uPredO_map f \u2261{n}\u2261 uPredO_map g.\nProof.\n  by intros Hfg P; split=> n' y ??;\n    rewrite /uPred_holds /= (dist_le _ _ _ _(Hfg y)); last lia.\nQed.\n\nProgram Definition uPredOF (F : urFunctor) : oFunctor := {|\n  oFunctor_car A _ B _ := uPredO (urFunctor_car F B A);\n  oFunctor_map A1 _ A2 _ B1 _ B2 _ fg := uPredO_map (urFunctor_map F (fg.2, fg.1))\n|}.\nNext Obligation.\n  intros F A1 ? A2 ? B1 ? B2 ? n P Q HPQ.\n  apply uPredO_map_ne, urFunctor_map_ne; split; by apply HPQ.\nQed.\nNext Obligation.\n  intros F A ? B ? P; simpl. rewrite -{2}(uPred_map_id P).\n  apply uPred_map_ext=>y. by rewrite urFunctor_map_id.\nQed.\nNext Obligation.\n  intros F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' P; simpl. rewrite -uPred_map_compose.\n  apply uPred_map_ext=>y; apply urFunctor_map_compose.\nQed.\n\nGlobal Instance uPredOF_contractive F :\n  urFunctorContractive F \u2192 oFunctorContractive (uPredOF F).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n P Q HPQ.\n  apply uPredO_map_ne, urFunctor_map_contractive. destruct n; split; by apply HPQ.\nQed.\n\n(** logical entailement *)\nInductive uPred_entails {M} (P Q : uPred M) : Prop :=\n  { uPred_in_entails : \u2200 n x, \u2713{n} x \u2192 P n x \u2192 Q n x }.\nGlobal Hint Resolve uPred_mono : uPred_def.\n\n(** logical connectives *)\nProgram Definition uPred_pure_def {M} (\u03c6 : Prop) : uPred M :=\n  {| uPred_holds n x := \u03c6 |}.\nSolve Obligations with done.\nDefinition uPred_pure_aux : seal (@uPred_pure_def). Proof. by eexists. Qed.\nDefinition uPred_pure := uPred_pure_aux.(unseal).\nGlobal Arguments 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 n x := P n x \u2227 Q n x |}.\nSolve Obligations with naive_solver eauto 2 with uPred_def.\nDefinition uPred_and_aux : seal (@uPred_and_def). Proof. by eexists. Qed.\nDefinition uPred_and := uPred_and_aux.(unseal).\nGlobal Arguments 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 n x := P n x \u2228 Q n x |}.\nSolve Obligations with naive_solver eauto 2 with uPred_def.\nDefinition uPred_or_aux : seal (@uPred_or_def). Proof. by eexists. Qed.\nDefinition uPred_or := uPred_or_aux.(unseal).\nGlobal Arguments 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 n x := \u2200 n' x',\n       x \u227c x' \u2192 n' \u2264 n \u2192 \u2713{n'} x' \u2192 P n' x' \u2192 Q n' x' |}.\nNext Obligation.\n  intros M P Q n1 n1' x1 x1' HPQ [x2 Hx1'] Hn1 n2 x3 [x4 Hx3] ?; simpl in *.\n  rewrite Hx3 (dist_le _ _ _ _ Hx1'); auto. intros ??.\n  eapply HPQ; auto. exists (x2 \u22c5 x4); by rewrite assoc.\nQed.\nDefinition uPred_impl_aux : seal (@uPred_impl_def). Proof. by eexists. Qed.\nDefinition uPred_impl := uPred_impl_aux.(unseal).\nGlobal Arguments 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} (\u03a8 : A \u2192 uPred M) : uPred M :=\n  {| uPred_holds n x := \u2200 a, \u03a8 a n x |}.\nSolve Obligations with naive_solver eauto 2 with uPred_def.\nDefinition uPred_forall_aux : seal (@uPred_forall_def). Proof. by eexists. Qed.\nDefinition uPred_forall := uPred_forall_aux.(unseal).\nGlobal Arguments 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} (\u03a8 : A \u2192 uPred M) : uPred M :=\n  {| uPred_holds n x := \u2203 a, \u03a8 a n x |}.\nSolve Obligations with naive_solver eauto 2 with uPred_def.\nDefinition uPred_exist_aux : seal (@uPred_exist_def). Proof. by eexists. Qed.\nDefinition uPred_exist := uPred_exist_aux.(unseal).\nGlobal Arguments uPred_exist {M A}.\nDefinition uPred_exist_eq: @uPred_exist = @uPred_exist_def := uPred_exist_aux.(seal_eq).\n\nProgram Definition uPred_internal_eq_def {M} {A : ofe} (a1 a2 : A) : uPred M :=\n  {| uPred_holds n x := a1 \u2261{n}\u2261 a2 |}.\nSolve Obligations with naive_solver eauto 2 using dist_le.\nDefinition uPred_internal_eq_aux : seal (@uPred_internal_eq_def). Proof. by eexists. Qed.\nDefinition uPred_internal_eq := uPred_internal_eq_aux.(unseal).\nGlobal Arguments uPred_internal_eq {M A}.\nDefinition uPred_internal_eq_eq:\n  @uPred_internal_eq = @uPred_internal_eq_def := uPred_internal_eq_aux.(seal_eq).\n\nProgram Definition uPred_sep_def {M} (P Q : uPred M) : uPred M :=\n  {| uPred_holds n x := \u2203 x1 x2, x \u2261{n}\u2261 x1 \u22c5 x2 \u2227 P n x1 \u2227 Q n x2 |}.\nNext Obligation.\n  intros M P Q n1 n2 x y (x1&x2&Hx&?&?) [z Hy] Hn.\n  exists x1, (x2 \u22c5 z); split_and?; eauto using uPred_mono, cmra_includedN_l.\n  rewrite Hy. eapply dist_le, Hn. by rewrite Hx assoc.\nQed.\nDefinition uPred_sep_aux : seal (@uPred_sep_def). Proof. by eexists. Qed.\nDefinition uPred_sep := uPred_sep_aux.(unseal).\nGlobal Arguments 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 n x := \u2200 n' x',\n       n' \u2264 n \u2192 \u2713{n'} (x \u22c5 x') \u2192 P n' x' \u2192 Q n' (x \u22c5 x') |}.\nNext Obligation.\n  intros M P Q n1 n1' x1 x1' HPQ ? Hn n3 x3 ???; simpl in *.\n  eapply uPred_mono with n3 (x1 \u22c5 x3);\n    eauto using cmra_validN_includedN, cmra_monoN_r, cmra_includedN_le.\nQed.\nDefinition uPred_wand_aux : seal (@uPred_wand_def). Proof. by eexists. Qed.\nDefinition uPred_wand := uPred_wand_aux.(unseal).\nGlobal Arguments uPred_wand {M}.\nDefinition uPred_wand_eq :\n  @uPred_wand = @uPred_wand_def := uPred_wand_aux.(seal_eq).\n\n(* Equivalently, this could be `\u2200 y, P n y`.  That's closer to the intuition\n   of \"embedding the step-indexed logic in Iris\", but the two are equivalent\n   because Iris is afine.  The following is easier to work with. *)\nProgram Definition uPred_plainly_def {M} (P : uPred M) : uPred M :=\n  {| uPred_holds n x := P n \u03b5 |}.\nSolve Obligations with naive_solver eauto using uPred_mono, ucmra_unit_validN.\nDefinition uPred_plainly_aux : seal (@uPred_plainly_def). Proof. by eexists. Qed.\nDefinition uPred_plainly := uPred_plainly_aux.(unseal).\nGlobal Arguments uPred_plainly {M}.\nDefinition uPred_plainly_eq :\n  @uPred_plainly = @uPred_plainly_def := uPred_plainly_aux.(seal_eq).\n\nProgram Definition uPred_persistently_def {M} (P : uPred M) : uPred M :=\n  {| uPred_holds n x := P n (core x) |}.\nSolve Obligations with naive_solver eauto using uPred_mono, cmra_core_monoN.\nDefinition uPred_persistently_aux : seal (@uPred_persistently_def). Proof. by eexists. Qed.\nDefinition uPred_persistently := uPred_persistently_aux.(unseal).\nGlobal Arguments uPred_persistently {M}.\nDefinition uPred_persistently_eq :\n  @uPred_persistently = @uPred_persistently_def := uPred_persistently_aux.(seal_eq).\n\nProgram Definition uPred_later_def {M} (P : uPred M) : uPred M :=\n  {| uPred_holds n x := match n return _ with 0 => True | S n' => P n' x end |}.\nNext Obligation.\n  intros M P [|n1] [|n2] x1 x2; eauto using uPred_mono, cmra_includedN_S with lia.\nQed.\nDefinition uPred_later_aux : seal (@uPred_later_def). Proof. by eexists. Qed.\nDefinition uPred_later := uPred_later_aux.(unseal).\nGlobal Arguments uPred_later {M}.\nDefinition uPred_later_eq :\n  @uPred_later = @uPred_later_def := uPred_later_aux.(seal_eq).\n\nProgram Definition uPred_ownM_def {M : ucmra} (a : M) : uPred M :=\n  {| uPred_holds n x := a \u227c{n} x |}.\nNext Obligation.\n  intros M a n1 n2 x1 x [a' Hx1] [x2 Hx] Hn.\n  exists (a' \u22c5 x2). rewrite Hx. eapply dist_le, Hn. rewrite (assoc op) -Hx1 //.\nQed.\nDefinition uPred_ownM_aux : seal (@uPred_ownM_def). Proof. by eexists. Qed.\nDefinition uPred_ownM := uPred_ownM_aux.(unseal).\nGlobal Arguments uPred_ownM {M}.\nDefinition uPred_ownM_eq :\n  @uPred_ownM = @uPred_ownM_def := uPred_ownM_aux.(seal_eq).\n\nProgram Definition uPred_cmra_valid_def {M} {A : cmra} (a : A) : uPred M :=\n  {| uPred_holds n x := \u2713{n} a |}.\nSolve Obligations with naive_solver eauto 2 using cmra_validN_le.\nDefinition uPred_cmra_valid_aux : seal (@uPred_cmra_valid_def). Proof. by eexists. Qed.\nDefinition uPred_cmra_valid := uPred_cmra_valid_aux.(unseal).\nGlobal Arguments uPred_cmra_valid {M A}.\nDefinition uPred_cmra_valid_eq :\n  @uPred_cmra_valid = @uPred_cmra_valid_def := uPred_cmra_valid_aux.(seal_eq).\n\nProgram Definition uPred_bupd_def {M} (Q : uPred M) : uPred M :=\n  {| uPred_holds n x := \u2200 k yf,\n      k \u2264 n \u2192 \u2713{k} (x \u22c5 yf) \u2192 \u2203 x', \u2713{k} (x' \u22c5 yf) \u2227 Q k x' |}.\nNext Obligation.\n  intros M Q n1 n2 x1 x2 HQ [x3 Hx] Hn k yf Hk.\n  rewrite (dist_le _ _ _ _ Hx); last lia. intros Hxy.\n  destruct (HQ k (x3 \u22c5 yf)) as (x'&?&?); [auto|by rewrite assoc|].\n  exists (x' \u22c5 x3); split; first by rewrite -assoc.\n  eauto using uPred_mono, cmra_includedN_l.\nQed.\nDefinition uPred_bupd_aux : seal (@uPred_bupd_def). Proof. by eexists. Qed.\nDefinition uPred_bupd := uPred_bupd_aux.(unseal).\nGlobal Arguments uPred_bupd {M}.\nDefinition uPred_bupd_eq :\n  @uPred_bupd = @uPred_bupd_def := uPred_bupd_aux.(seal_eq).\n\n(** Global uPred-specific Notation *)\nNotation \"\u2713 x\" := (uPred_cmra_valid x) (at level 20) : bi_scope.\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_pure_eq, uPred_and_eq, uPred_or_eq, uPred_impl_eq, uPred_forall_eq,\n  uPred_exist_eq, uPred_internal_eq_eq, uPred_sep_eq, uPred_wand_eq,\n  uPred_plainly_eq, uPred_persistently_eq, uPred_later_eq, uPred_ownM_eq,\n  uPred_cmra_valid_eq, @uPred_bupd_eq).\nLtac unseal :=\n  rewrite !unseal_eqs /=.\n\nSection primitive.\nContext {M : ucmra}.\nImplicit Types \u03c6 : Prop.\nImplicit Types P Q : uPred M.\nImplicit Types A : Type.\nLocal Arguments uPred_holds {_} !_ _ _ /.\nLocal Hint Immediate uPred_in_entails : core.\n\nNotation \"P \u22a2 Q\" := (@uPred_entails M P%I Q%I) : stdpp_scope.\nNotation \"(\u22a2)\" := (@uPred_entails M) (only parsing) : stdpp_scope.\nNotation \"P \u22a3\u22a2 Q\" := (@uPred_equiv M P%I Q%I) : stdpp_scope.\nNotation \"(\u22a3\u22a2)\" := (@uPred_equiv M) (only parsing) : stdpp_scope.\n\nNotation \"'True'\" := (uPred_pure True) : bi_scope.\nNotation \"'False'\" := (uPred_pure False) : bi_scope.\nNotation \"'\u231c' \u03c6 '\u231d'\" := (uPred_pure \u03c6%type%stdpp) : bi_scope.\nInfix \"\u2227\" := uPred_and : bi_scope.\nInfix \"\u2228\" := uPred_or : bi_scope.\nInfix \"\u2192\" := uPred_impl : bi_scope.\nNotation \"\u2200 x .. y , P\" :=\n  (uPred_forall (\u03bb x, .. (uPred_forall (\u03bb y, P)) ..)) : bi_scope.\nNotation \"\u2203 x .. y , P\" :=\n  (uPred_exist (\u03bb x, .. (uPred_exist (\u03bb y, P)) ..)) : bi_scope.\nInfix \"\u2217\" := uPred_sep : bi_scope.\nInfix \"-\u2217\" := uPred_wand : bi_scope.\nNotation \"\u25a1 P\" := (uPred_persistently P) : bi_scope.\nNotation \"\u25a0 P\" := (uPred_plainly P) : bi_scope.\nNotation \"x \u2261 y\" := (uPred_internal_eq x y) : bi_scope.\nNotation \"\u25b7 P\" := (uPred_later P) : bi_scope.\nNotation \"|==> P\" := (uPred_bupd P) : bi_scope.\n\n(** Entailment *)\nLemma entails_po : PreOrder (\u22a2).\nProof.\n  split.\n  - by intros P; split=> x i.\n  - by intros P Q Q' HP HQ; split=> x i ??; apply HQ, HP.\nQed.\nLemma entails_anti_sym : AntiSymm (\u22a3\u22a2) (\u22a2).\nProof. intros P Q HPQ HQP; split=> x n; by split; [apply HPQ|apply HQP]. Qed.\nLemma equiv_entails P Q : (P \u22a3\u22a2 Q) \u2194 (P \u22a2 Q) \u2227 (Q \u22a2 P).\nProof.\n  split.\n  - intros HPQ; split; split=> x i; apply HPQ.\n  - intros [??]. exact: entails_anti_sym.\nQed.\nLemma entails_lim (cP cQ : chain (uPredO M)) :\n  (\u2200 n, cP n \u22a2 cQ n) \u2192 compl cP \u22a2 compl cQ.\nProof.\n  intros Hlim; split=> n m ? HP.\n  eapply uPred_holds_ne, Hlim, HP; rewrite ?conv_compl; eauto.\nQed.\n\n(** Non-expansiveness and setoid morphisms *)\nLemma pure_ne n : Proper (iff ==> dist n) (@uPred_pure M).\nProof. intros \u03c61 \u03c62 H\u03c6. by unseal; split=> -[|m] ?; try apply H\u03c6. Qed.\n\nLemma and_ne : NonExpansive2 (@uPred_and M).\nProof.\n  intros n P P' HP Q Q' HQ; unseal; split=> x n' ??.\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' ??.\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' ??.\n  unseal; split; intros HPQ x' n'' ????; apply HQ, HPQ, HP; auto.\nQed.\n\nLemma sep_ne : NonExpansive2 (@uPred_sep M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> n' x ??.\n  unseal; split; intros (x1&x2&?&?&?); ofe_subst x;\n    exists x1, x2; split_and!; try (apply HP || apply HQ);\n    eauto using cmra_validN_op_l, cmra_validN_op_r.\nQed.\n\nLemma wand_ne :\n  NonExpansive2 (@uPred_wand M).\nProof.\n  intros n P P' HP Q Q' HQ; split=> n' x ??; unseal; split; intros HPQ x' n'' ???;\n    apply HQ, HPQ, HP; eauto using cmra_validN_op_r.\nQed.\n\nLemma internal_eq_ne (A : ofe) :\n  NonExpansive2 (@uPred_internal_eq M A).\nProof.\n  intros n x x' Hx y y' Hy; split=> n' z; unseal; split; intros; simpl in *.\n  - by rewrite -(dist_le _ _ _ _ Hx) -?(dist_le _ _ _ _ Hy); auto.\n  - by rewrite (dist_le _ _ _ _ Hx) ?(dist_le _ _ _ _ Hy); auto.\nQed.\n\nLemma forall_ne A n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (@uPred_forall M A).\nProof.\n  by intros \u03a81 \u03a82 H\u03a8; unseal; split=> n' x; split; intros HP a; apply H\u03a8.\nQed.\n\nLemma exist_ne A n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (@uPred_exist M A).\nProof.\n  intros \u03a81 \u03a82 H\u03a8.\n  unseal; split=> n' x ??; split; intros [a ?]; exists a; by apply H\u03a8.\nQed.\n\nLemma later_contractive : Contractive (@uPred_later M).\nProof.\n  unseal; intros [|n] P Q HPQ; split=> -[|n'] x ?? //=; try lia.\n  apply HPQ; eauto using cmra_validN_S.\nQed.\n\nLemma plainly_ne : NonExpansive (@uPred_plainly M).\nProof.\n  intros n P1 P2 HP.\n  unseal; split=> n' x; split; apply HP; eauto using ucmra_unit_validN.\nQed.\n\nLemma persistently_ne : NonExpansive (@uPred_persistently M).\nProof.\n  intros n P1 P2 HP.\n  unseal; split=> n' x; split; apply HP; eauto using cmra_core_validN.\nQed.\n\nLemma ownM_ne : NonExpansive (@uPred_ownM M).\nProof.\n  intros n a b Ha.\n  unseal; split=> n' x ? /=. by rewrite (dist_le _ _ _ _ Ha); last lia.\nQed.\n\nLemma cmra_valid_ne {A : cmra} :\n  NonExpansive (@uPred_cmra_valid M A).\nProof.\n  intros n a b Ha; unseal; split=> n' x ? /=.\n  by rewrite (dist_le _ _ _ _ Ha); last lia.\nQed.\n\nLemma bupd_ne : NonExpansive (@uPred_bupd M).\nProof.\n  intros n P Q HPQ.\n  unseal; split=> n' x; split; intros HP k yf ??;\n    destruct (HP k yf) as (x'&?&?); auto;\n    exists x'; split; auto; apply HPQ; eauto using cmra_validN_op_l.\nQed.\n\n(** Introduction and elimination rules *)\nLemma pure_intro \u03c6 P : \u03c6 \u2192 P \u22a2 \u231c\u03c6\u231d.\nProof. by intros ?; unseal; split. Qed.\nLemma pure_elim' \u03c6 P : (\u03c6 \u2192 True \u22a2 P) \u2192 \u231c\u03c6\u231d \u22a2 P.\nProof. unseal; intros HP; split=> n x ??. by apply HP. Qed.\nLemma pure_forall_2 {A} (\u03c6 : A \u2192 Prop) : (\u2200 x : A, \u231c\u03c6 x\u231d) \u22a2 \u231c\u2200 x : A, \u03c6 x\u231d.\nProof. by unseal. Qed.\n\nLemma and_elim_l P Q : P \u2227 Q \u22a2 P.\nProof. by unseal; split=> n x ? [??]. Qed.\nLemma and_elim_r P Q : P \u2227 Q \u22a2 Q.\nProof. by unseal; split=> n x ? [??]. Qed.\nLemma and_intro P Q R : (P \u22a2 Q) \u2192 (P \u22a2 R) \u2192 P \u22a2 Q \u2227 R.\nProof. intros HQ HR; unseal; split=> n x ??; by split; [apply HQ|apply HR]. Qed.\n\nLemma or_intro_l P Q : P \u22a2 P \u2228 Q.\nProof. unseal; split=> n x ??; left; auto. Qed.\nLemma or_intro_r P Q : Q \u22a2 P \u2228 Q.\nProof. unseal; split=> n x ??; right; auto. Qed.\nLemma or_elim P Q R : (P \u22a2 R) \u2192 (Q \u22a2 R) \u2192 P \u2228 Q \u22a2 R.\nProof.\n  intros HP HQ; unseal; split=> n x ? [?|?].\n  - by apply HP.\n  - by apply HQ.\nQed.\n\nLemma impl_intro_r P Q R : (P \u2227 Q \u22a2 R) \u2192 P \u22a2 Q \u2192 R.\nProof.\n  unseal; intros HQ; split=> n x ?? n' x' ????. apply HQ;\n    naive_solver eauto using uPred_mono, cmra_included_includedN.\nQed.\nLemma impl_elim_l' P Q R : (P \u22a2 Q \u2192 R) \u2192 P \u2227 Q \u22a2 R.\nProof. unseal; intros HP ; split=> n x ? [??]; apply HP with n x; auto. Qed.\n\nLemma forall_intro {A} P (\u03a8 : A \u2192 uPred M): (\u2200 a, P \u22a2 \u03a8 a) \u2192 P \u22a2 \u2200 a, \u03a8 a.\nProof. unseal; intros HP\u03a8; split=> n x ?? a; by apply HP\u03a8. Qed.\nLemma forall_elim {A} {\u03a8 : A \u2192 uPred M} a : (\u2200 a, \u03a8 a) \u22a2 \u03a8 a.\nProof. unseal; split=> n x ? HP; apply HP. Qed.\n\nLemma exist_intro {A} {\u03a8 : A \u2192 uPred M} a : \u03a8 a \u22a2 \u2203 a, \u03a8 a.\nProof. unseal; split=> n x ??; by exists a. Qed.\nLemma exist_elim {A} (\u03a6 : A \u2192 uPred M) Q : (\u2200 a, \u03a6 a \u22a2 Q) \u2192 (\u2203 a, \u03a6 a) \u22a2 Q.\nProof. unseal; intros H\u03a6\u03a8; split=> n x ? [a ?]; by apply H\u03a6\u03a8 with a. Qed.\n\n(** BI connectives *)\nLemma sep_mono P P' Q Q' : (P \u22a2 Q) \u2192 (P' \u22a2 Q') \u2192 P \u2217 P' \u22a2 Q \u2217 Q'.\nProof.\n  intros HQ HQ'; unseal.\n  split; intros n' x ? (x1&x2&?&?&?); exists x1,x2; ofe_subst x;\n    eauto 7 using cmra_validN_op_l, cmra_validN_op_r, uPred_in_entails.\nQed.\nLemma True_sep_1 P : P \u22a2 True \u2217 P.\nProof.\n  unseal; split; intros n x ??. exists (core x), x. by rewrite cmra_core_l.\nQed.\nLemma True_sep_2 P : True \u2217 P \u22a2 P.\nProof.\n  unseal; split; intros n x ? (x1&x2&?&_&?); ofe_subst;\n    eauto using uPred_mono, cmra_includedN_r.\nQed.\nLemma sep_comm' P Q : P \u2217 Q \u22a2 Q \u2217 P.\nProof.\n  unseal; split; intros n x ? (x1&x2&?&?&?); exists x2, x1; by rewrite (comm op).\nQed.\nLemma sep_assoc' P Q R : (P \u2217 Q) \u2217 R \u22a2 P \u2217 (Q \u2217 R).\nProof.\n  unseal; split; intros n x ? (x1&x2&Hx&(y1&y2&Hy&?&?)&?).\n  exists y1, (y2 \u22c5 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 \u2217 Q \u22a2 R) \u2192 P \u22a2 Q -\u2217 R.\nProof.\n  unseal=> HPQR; split=> n x ?? n' x' ???; apply HPQR; auto.\n  exists x, x'; split_and?; auto.\n  eapply uPred_mono with n x; eauto using cmra_validN_op_l.\nQed.\nLemma wand_elim_l' P Q R : (P \u22a2 Q -\u2217 R) \u2192 P \u2217 Q \u22a2 R.\nProof.\n  unseal =>HPQR. split; intros n x ? (?&?&?&?&?). ofe_subst.\n  eapply HPQR; eauto using cmra_validN_op_l.\nQed.\n\n(** Persistently *)\nLemma persistently_mono P Q : (P \u22a2 Q) \u2192 \u25a1 P \u22a2 \u25a1 Q.\nProof. intros HP; unseal; split=> n x ? /=. by apply HP, cmra_core_validN. Qed.\nLemma persistently_elim P : \u25a1 P \u22a2 P.\nProof.\n  unseal; split=> n x ? /=.\n  eauto using uPred_mono, cmra_included_core, cmra_included_includedN.\nQed.\nLemma persistently_idemp_2 P : \u25a1 P \u22a2 \u25a1 \u25a1 P.\nProof. unseal; split=> n x ?? /=. by rewrite cmra_core_idemp. Qed.\n\nLemma persistently_forall_2 {A} (\u03a8 : A \u2192 uPred M) : (\u2200 a, \u25a1 \u03a8 a) \u22a2 (\u25a1 \u2200 a, \u03a8 a).\nProof. by unseal. Qed.\nLemma persistently_exist_1 {A} (\u03a8 : A \u2192 uPred M) : (\u25a1 \u2203 a, \u03a8 a) \u22a2 (\u2203 a, \u25a1 \u03a8 a).\nProof. by unseal. Qed.\n\nLemma persistently_and_sep_l_1 P Q : \u25a1 P \u2227 Q \u22a2 P \u2217 Q.\nProof.\n  unseal; split=> n x ? [??]; exists (core x), x; simpl in *.\n  by rewrite cmra_core_l.\nQed.\n\n(** Plainly *)\nLemma plainly_mono P Q : (P \u22a2 Q) \u2192 \u25a0 P \u22a2 \u25a0 Q.\nProof. intros HP; unseal; split=> n x ? /=. apply HP, ucmra_unit_validN. Qed.\nLemma plainly_elim_persistently P : \u25a0 P \u22a2 \u25a1 P.\nProof. unseal; split; simpl; eauto using uPred_mono, ucmra_unit_leastN. Qed.\nLemma plainly_idemp_2 P : \u25a0 P \u22a2 \u25a0 \u25a0 P.\nProof. unseal; split=> n x ?? //. Qed.\n\nLemma plainly_forall_2 {A} (\u03a8 : A \u2192 uPred M) : (\u2200 a, \u25a0 \u03a8 a) \u22a2 (\u25a0 \u2200 a, \u03a8 a).\nProof. by unseal. Qed.\nLemma plainly_exist_1 {A} (\u03a8 : A \u2192 uPred M) : (\u25a0 \u2203 a, \u03a8 a) \u22a2 (\u2203 a, \u25a0 \u03a8 a).\nProof. by unseal. Qed.\n\nLemma prop_ext_2 P Q : \u25a0 ((P -\u2217 Q) \u2227 (Q -\u2217 P)) \u22a2 P \u2261 Q.\nProof.\n  unseal; split=> n x ? /=. setoid_rewrite (left_id \u03b5 op). split; naive_solver.\nQed.\n\n(* The following two laws are very similar, and indeed they hold not just for \u25a1\n   and \u25a0, but for any modality defined as `M P n x := \u2200 y, R x y \u2192 P n y`. *)\nLemma persistently_impl_plainly P Q : (\u25a0 P \u2192 \u25a1 Q) \u22a2 \u25a1 (\u25a0 P \u2192 Q).\nProof.\n  unseal; split=> /= n x ? HPQ n' x' ????.\n  eapply uPred_mono with n' (core x)=>//; [|by apply cmra_included_includedN].\n  apply (HPQ n' x); eauto using cmra_validN_le.\nQed.\n\nLemma plainly_impl_plainly P Q : (\u25a0 P \u2192 \u25a0 Q) \u22a2 \u25a0 (\u25a0 P \u2192 Q).\nProof.\n  unseal; split=> /= n x ? HPQ n' x' ????.\n  eapply uPred_mono with n' \u03b5=>//; [|by apply cmra_included_includedN].\n  apply (HPQ n' x); eauto using cmra_validN_le.\nQed.\n\n(** Later *)\nLemma later_mono P Q : (P \u22a2 Q) \u2192 \u25b7 P \u22a2 \u25b7 Q.\nProof.\n  unseal=> HP; split=>-[|n] x ??; [done|apply HP; eauto using cmra_validN_S].\nQed.\nLemma later_intro P : P \u22a2 \u25b7 P.\nProof.\n  unseal; split=> -[|n] /= x ? HP; first done.\n  apply uPred_mono with (S n) x; eauto using cmra_validN_S.\nQed.\nLemma later_forall_2 {A} (\u03a6 : A \u2192 uPred M) : (\u2200 a, \u25b7 \u03a6 a) \u22a2 \u25b7 \u2200 a, \u03a6 a.\nProof. unseal; by split=> -[|n] x. Qed.\nLemma later_exist_false {A} (\u03a6 : A \u2192 uPred M) :\n  (\u25b7 \u2203 a, \u03a6 a) \u22a2 \u25b7 False \u2228 (\u2203 a, \u25b7 \u03a6 a).\nProof. unseal; split=> -[|[|n]] x /=; eauto. Qed.\nLemma later_sep_1 P Q : \u25b7 (P \u2217 Q) \u22a2 \u25b7 P \u2217 \u25b7 Q.\nProof.\n  unseal; split=> n x ?.\n  destruct n as [|n]; simpl.\n  { by exists x, (core x); rewrite cmra_core_r. }\n  intros (x1&x2&Hx&?&?); destruct (cmra_extend n x x1 x2)\n    as (y1&y2&Hx'&Hy1&Hy2); eauto using cmra_validN_S; simpl in *.\n  exists y1, y2; split; [by rewrite Hx'|by rewrite Hy1 Hy2].\nQed.\nLemma later_sep_2 P Q : \u25b7 P \u2217 \u25b7 Q \u22a2 \u25b7 (P \u2217 Q).\nProof.\n  unseal; split=> n x ?.\n  destruct n as [|n]; simpl; [done|intros (x1&x2&Hx&?&?)].\n  exists x1, x2; eauto using dist_S.\nQed.\n\nLemma later_false_em P : \u25b7 P \u22a2 \u25b7 False \u2228 (\u25b7 False \u2192 P).\nProof.\n  unseal; split=> -[|n] x ? /= HP; [by left|right].\n  intros [|n'] x' ????; eauto using uPred_mono, cmra_included_includedN.\nQed.\n\nLemma later_persistently_1 P : \u25b7 \u25a1 P \u22a2 \u25a1 \u25b7 P.\nProof. by unseal. Qed.\nLemma later_persistently_2 P : \u25a1 \u25b7 P \u22a2 \u25b7 \u25a1 P.\nProof. by unseal. Qed.\nLemma later_plainly_1 P : \u25b7 \u25a0 P \u22a2 \u25a0 \u25b7 P.\nProof. by unseal. Qed.\nLemma later_plainly_2 P : \u25a0 \u25b7 P \u22a2 \u25b7 \u25a0 P.\nProof. by unseal. Qed.\n\n(** Internal equality *)\nLemma internal_eq_refl {A : ofe} P (a : A) : P \u22a2 (a \u2261 a).\nProof. unseal; by split=> n x ??; simpl. Qed.\nLemma internal_eq_rewrite {A : ofe} a b (\u03a8 : A \u2192 uPred M) :\n  NonExpansive \u03a8 \u2192 a \u2261 b \u22a2 \u03a8 a \u2192 \u03a8 b.\nProof. intros H\u03a8. unseal; split=> n x ?? n' x' ??? Ha. by apply H\u03a8 with n a. Qed.\n\nLemma fun_ext {A} {B : A \u2192 ofe} (g1 g2 : discrete_fun B) :\n  (\u2200 i, g1 i \u2261 g2 i) \u22a2 g1 \u2261 g2.\nProof. by unseal. Qed.\nLemma sig_eq {A : ofe} (P : A \u2192 Prop) (x y : sigO P) :\n  proj1_sig x \u2261 proj1_sig y \u22a2 x \u2261 y.\nProof. by unseal. Qed.\n\nLemma later_eq_1 {A : ofe} (x y : A) : Next x \u2261 Next y \u22a2 \u25b7 (x \u2261 y).\nProof. by unseal. Qed.\nLemma later_eq_2 {A : ofe} (x y : A) : \u25b7 (x \u2261 y) \u22a2 Next x \u2261 Next y.\nProof. by unseal. Qed.\n\nLemma discrete_eq_1 {A : ofe} (a b : A) : Discrete a \u2192 a \u2261 b \u22a2 \u231ca \u2261 b\u231d.\nProof.\n  unseal=> ?. split=> n x ?. by apply (discrete_iff n).\nQed.\n\n(** This is really just a special case of an entailment\nbetween two [siProp], but we do not have the infrastructure\nto express the more general case. This temporary proof rule will\nbe replaced by the proper one eventually. *)\nLemma internal_eq_entails {A B : ofe} (a1 a2 : A) (b1 b2 : B) :\n  (\u2200 n, a1 \u2261{n}\u2261 a2 \u2192 b1 \u2261{n}\u2261 b2) \u2192 a1 \u2261 a2 \u22a2 b1 \u2261 b2.\nProof. unseal=>Hsi. split=>n x ?. apply Hsi. Qed.\n\n(** Basic update modality *)\nLemma bupd_intro P : P \u22a2 |==> P.\nProof.\n  unseal. split=> n x ? HP k yf ?; exists x; split; first done.\n  apply uPred_mono with n x; eauto using cmra_validN_op_l.\nQed.\nLemma bupd_mono P Q : (P \u22a2 Q) \u2192 (|==> P) \u22a2 |==> Q.\nProof.\n  unseal. intros HPQ; split=> n x ? HP k yf ??.\n  destruct (HP k yf) as (x'&?&?); eauto.\n  exists x'; split; eauto using uPred_in_entails, cmra_validN_op_l.\nQed.\nLemma bupd_trans P : (|==> |==> P) \u22a2 |==> P.\nProof. unseal; split; naive_solver. Qed.\nLemma bupd_frame_r P R : (|==> P) \u2217 R \u22a2 |==> P \u2217 R.\nProof.\n  unseal; split; intros n x ? (x1&x2&Hx&HP&?) k yf ??.\n  destruct (HP k (x2 \u22c5 yf)) as (x'&?&?); eauto.\n  { by rewrite assoc -(dist_le _ _ _ _ Hx); last lia. }\n  exists (x' \u22c5 x2); split; first by rewrite -assoc.\n  exists x', x2. eauto using uPred_mono, cmra_validN_op_l, cmra_validN_op_r.\nQed.\nLemma bupd_plainly P : (|==> \u25a0 P) \u22a2 P.\nProof.\n  unseal; split => n x Hnx /= Hng.\n  destruct (Hng n \u03b5) as [? [_ Hng']]; try rewrite right_id; auto.\n  eapply uPred_mono; eauto using ucmra_unit_leastN.\nQed.\n\n(** Own *)\nLemma ownM_op (a1 a2 : M) :\n  uPred_ownM (a1 \u22c5 a2) \u22a3\u22a2 uPred_ownM a1 \u2217 uPred_ownM a2.\nProof.\n  unseal; split=> n x ?; split.\n  - intros [z ?]; exists a1, (a2 \u22c5 z); split; [by rewrite (assoc op)|].\n    split.\n    + by exists (core a1); rewrite cmra_core_r.\n    + by exists z.\n  - intros (y1&y2&Hx&[z1 Hy1]&[z2 Hy2]); exists (z1 \u22c5 z2).\n    by rewrite (assoc op _ z1) -(comm op z1) (assoc op z1)\n      -(assoc op _ a2) (comm op z1) -Hy1 -Hy2.\nQed.\nLemma persistently_ownM_core (a : M) : uPred_ownM a \u22a2 \u25a1 uPred_ownM (core a).\nProof.\n  split=> n x /=; unseal; intros Hx. simpl. by apply cmra_core_monoN.\nQed.\nLemma ownM_unit P : P \u22a2 (uPred_ownM \u03b5).\nProof. unseal; split=> n x ??; by  exists x; rewrite left_id. Qed.\nLemma later_ownM a : \u25b7 uPred_ownM a \u22a2 \u2203 b, uPred_ownM b \u2227 \u25b7 (a \u2261 b).\nProof.\n  unseal; split=> -[|n] x /= ? Hax; first by eauto using ucmra_unit_leastN.\n  destruct Hax as [y ?].\n  destruct (cmra_extend n x a y) as (a'&y'&Hx&?&?); auto using cmra_validN_S.\n  exists a'. rewrite Hx. eauto using cmra_includedN_l.\nQed.\n\nLemma bupd_ownM_updateP x (\u03a6 : M \u2192 Prop) :\n  x ~~>: \u03a6 \u2192 uPred_ownM x \u22a2 |==> \u2203 y, \u231c\u03a6 y\u231d \u2227 uPred_ownM y.\nProof.\n  unseal=> Hup; split=> n x2 ? [x3 Hx] k yf ??.\n  destruct (Hup k (Some (x3 \u22c5 yf))) as (y&?&?); simpl in *.\n  { rewrite /= assoc -(dist_le _ _ _ _ Hx); auto. }\n  exists (y \u22c5 x3); split; first by rewrite -assoc.\n  exists y; eauto using cmra_includedN_l.\nQed.\n\n(** Valid *)\nLemma ownM_valid (a : M) : uPred_ownM a \u22a2 \u2713 a.\nProof.\n  unseal; split=> n x Hv [a' ?]; ofe_subst; eauto using cmra_validN_op_l.\nQed.\nLemma cmra_valid_intro {A : cmra} P (a : A) : \u2713 a \u2192 P \u22a2 (\u2713 a).\nProof. unseal=> ?; split=> n x ? _ /=; by apply cmra_valid_validN. Qed.\nLemma cmra_valid_elim {A : cmra} (a : A) : \u00ac \u2713{0} a \u2192 \u2713 a \u22a2 False.\nProof. unseal=> Ha; split=> n x ??; apply Ha, cmra_validN_le with n; auto. Qed.\nLemma plainly_cmra_valid_1 {A : cmra} (a : A) : \u2713 a \u22a2 \u25a0 \u2713 a.\nProof. by unseal. Qed.\nLemma cmra_valid_weaken {A : cmra} (a b : A) : \u2713 (a \u22c5 b) \u22a2 \u2713 a.\nProof. unseal; split=> n x _; apply cmra_validN_op_l. Qed.\n\nLemma discrete_valid {A : cmra} `{!CmraDiscrete A} (a : A) : \u2713 a \u22a3\u22a2 \u231c\u2713 a\u231d.\nProof. unseal; split=> n x _. by rewrite /= -cmra_discrete_valid_iff. Qed.\n\n(** This is really just a special case of an entailment\nbetween two [siProp], but we do not have the infrastructure\nto express the more general case. This temporary proof rule will\nbe replaced by the proper one eventually. *)\nLemma valid_entails {A B : cmra} (a : A) (b : B) :\n  (\u2200 n, \u2713{n} a \u2192 \u2713{n} b) \u2192 \u2713 a \u22a2 \u2713 b.\nProof. unseal=> Hval. split=>n x ?. apply Hval. Qed.\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 \u03c6 : (True \u22a2 \u231c \u03c6 \u231d) \u2192 \u03c6.\nProof. unseal=> -[H]. by apply (H 0 \u03b5); eauto using ucmra_unit_validN. Qed.\n\nLemma internal_eq_soundness {A : ofe} (x y : A) : (True \u22a2 x \u2261 y) \u2192 x \u2261 y.\nProof.\n  unseal=> -[H]. apply equiv_dist=> n.\n  by apply (H n \u03b5); eauto using ucmra_unit_validN.\nQed.\n\nLemma later_soundness P : (True \u22a2 \u25b7 P) \u2192 (True \u22a2 P).\nProof.\n  unseal=> -[HP]; split=> n x Hx _.\n  apply uPred_mono with n \u03b5; eauto using ucmra_unit_leastN.\n  by apply (HP (S n)); eauto using ucmra_unit_validN.\nQed.\nEnd primitive.\nEnd uPred_primitive.\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/upred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.1842274058496299}}
{"text": "\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.ProofEnvironment. \nRequire Import depoolContract.DePoolClass.\n\n\nModule DePoolSpec (xt: XTypesSig) (sm: StateMonadSig).\nModule LedgerClass := LedgerClass xt sm .\nImport LedgerClass.\nImport SolidityNotations.\n\nModule Type DePoolSpecSig.\nImport xt. Import sm.\n\nParameter ProxyBase_\u0424__recoverStake : XAddress -> XInteger64 -> XAddress -> LedgerT True .\nParameter ProxyBase_\u0424__sendElectionRequest : XAddress -> XInteger64 -> XInteger64 -> DePoolLib_\u03b9_Request -> XAddress -> LedgerT True .\nParameter ConfigParamsBase_\u0424_getCurValidatorData : LedgerT ( XErrorValue ( XInteger256 # XInteger32 # XInteger32 )%sol XInteger ) .\nParameter ConfigParamsBase_\u0424_getPrevValidatorHash : LedgerT ( XErrorValue XInteger XInteger ) .\nParameter ConfigParamsBase_\u0424_roundTimeParams : LedgerT ( XErrorValue ( XInteger32 # XInteger32 # XInteger32 # XInteger32 )%sol XInteger ) .\nParameter ConfigParamsBase_\u0424_getMaxStakeFactor : LedgerT ( XErrorValue XInteger32 XInteger ) .\nParameter ConfigParamsBase_\u0424_getElector : LedgerT ( XErrorValue XAddress XInteger ) .\nParameter ParticipantBase_\u0424__setOrDeleteParticipant : XAddress -> DePoolLib_\u03b9_Participant -> LedgerT True .\nParameter ParticipantBase_\u0424_getOrCreateParticipant  : XAddress -> LedgerT DePoolLib_\u03b9_Participant .\nParameter DePoolProxyContract_\u0424_constructor5 : LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolProxyContract_\u0424_process_new_stake : XInteger64 -> XInteger256 -> XInteger32 -> XInteger32 -> XInteger256 -> XList XInteger8 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolProxyContract_\u0424_onStakeAccept : XInteger64 -> XInteger32 -> LedgerT True .\nParameter DePoolProxyContract_\u0424_onStakeReject : XInteger64 -> XInteger32 -> LedgerT True .\nParameter DePoolProxyContract_\u0424_recover_stake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolProxyContract_\u0424_onSuccessToRecoverStake : XInteger64 -> LedgerT True .\nParameter DePoolProxyContract_\u0424_getProxyInfo : LedgerT ( XAddress # XInteger64 )%sol .\nParameter RoundsBase_\u0424__addStakes : RoundsBase_\u03b9_Round -> DePoolLib_\u03b9_Participant -> XAddress -> XInteger64 -> XMaybe RoundsBase_\u03b9_InvestParams -> XMaybe RoundsBase_\u03b9_InvestParams -> LedgerT ( RoundsBase_\u03b9_Round # DePoolLib_\u03b9_Participant )%sol .\nParameter RoundsBase_\u0424_stakeSum : RoundsBase_\u03b9_StakeValue -> LedgerT XInteger64 .\nParameter RoundsBase_\u0424_transferStakeInOneRound : RoundsBase_\u03b9_Round -> DePoolLib_\u03b9_Participant -> DePoolLib_\u03b9_Participant -> XAddress -> XAddress -> XInteger64 -> XInteger64 -> LedgerT ( RoundsBase_\u03b9_Round # XInteger64 # XInteger64 # DePoolLib_\u03b9_Participant # DePoolLib_\u03b9_Participant )%sol .\nParameter RoundsBase_\u0424_isRoundPre0 : XInteger64 -> LedgerT XBool .\nParameter RoundsBase_\u0424_isRound0 : XInteger64 -> LedgerT XBool .\nParameter RoundsBase_\u0424_isRound1 : XInteger64 -> LedgerT XBool .\nParameter RoundsBase_\u0424_isRound2 : XInteger64 -> LedgerT XBool .\nParameter RoundsBase_\u0424_roundAt : XInteger64 -> LedgerT RoundsBase_\u03b9_Round .\nParameter RoundsBase_\u0424_getRoundPre0 : LedgerT RoundsBase_\u03b9_Round .\nParameter RoundsBase_\u0424_getRound0 : LedgerT RoundsBase_\u03b9_Round .\nParameter RoundsBase_\u0424_getRound1 : LedgerT RoundsBase_\u03b9_Round .\nParameter RoundsBase_\u0424_getRound2 : LedgerT RoundsBase_\u03b9_Round .\nParameter RoundsBase_\u0424_setRound : XInteger -> RoundsBase_\u03b9_Round -> LedgerT True .\nParameter RoundsBase_\u0424_setRoundPre0 : RoundsBase_\u03b9_Round -> LedgerT True .\nParameter RoundsBase_\u0424_setRound0 : RoundsBase_\u03b9_Round -> LedgerT True .\nParameter RoundsBase_\u0424_setRound1 : RoundsBase_\u03b9_Round -> LedgerT True .\nParameter RoundsBase_\u0424_setRound2 : RoundsBase_\u03b9_Round -> LedgerT True .\nParameter RoundsBase_\u0424_fetchRound : XInteger64 -> LedgerT (XMaybe RoundsBase_\u03b9_Round)  .\nParameter ParticipantBase_\u0424_fetchParticipant : XAddress -> LedgerT (XMaybe ( DePoolLib_\u03b9_Participant) ) .\nParameter RoundsBase_\u0424_minRound : LedgerT (XMaybe (XInteger64 # RoundsBase_\u03b9_Round)%sol) .\nParameter RoundsBase_\u0424_nextRound : XInteger64 -> LedgerT (XMaybe (XInteger64 # RoundsBase_\u03b9_Round)%sol) .\nParameter RoundsBase_\u0424_withdrawStakeInPoolingRound : DePoolLib_\u03b9_Participant -> XAddress -> XInteger64 -> XInteger64 -> LedgerT ( XInteger64 # DePoolLib_\u03b9_Participant )%sol .\nParameter RoundsBase_\u0424_toTruncatedRound : RoundsBase_\u03b9_Round -> LedgerT RoundsBase_\u03b9_TruncatedRound .\nParameter RoundsBase_\u0424_getRounds : LedgerT (XHMap XInteger64 RoundsBase_\u03b9_TruncatedRound) .\nParameter DePoolContract_\u0424_generateRound : LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_Constructor6 : XInteger64 -> XInteger64 -> TvmCell -> XAddress -> XInteger8 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_setLastRoundInfo : RoundsBase_\u03b9_Round -> LedgerT True .\nParameter DePoolContract_\u0424__returnChange : LedgerT True .\nParameter DePoolContract_\u0424__sendError : XInteger32 -> XInteger64 -> LedgerT True .\nParameter DePoolContract_\u0424_startRoundCompleting : RoundsBase_\u03b9_Round -> RoundsBase_\u03b9_CompletionReason -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_cutWithdrawalValue : RoundsBase_\u03b9_InvestParams -> XBool -> XInteger32 -> LedgerT ( (XMaybe RoundsBase_\u03b9_InvestParams) # XInteger64 # XInteger64 )%sol .\nParameter DePoolContract_\u0424__returnOrReinvestForParticipant : RoundsBase_\u03b9_Round -> RoundsBase_\u03b9_Round -> XAddress -> RoundsBase_\u03b9_StakeValue -> XBool -> XInteger32 -> LedgerT ( XErrorValue ( RoundsBase_\u03b9_Round # RoundsBase_\u03b9_Round )%sol XInteger ) .\nParameter DePoolContract_\u0424__returnOrReinvest : RoundsBase_\u03b9_Round -> XInteger8 -> LedgerT ( XErrorValue RoundsBase_\u03b9_Round XInteger ) .\nParameter DePoolContract_\u0424_sendAcceptAndReturnChange128 : XInteger64 -> LedgerT True .\nParameter DePoolContract_\u0424_sendAcceptAndReturnChange : LedgerT True .\nParameter DePoolContract_\u0424_addOrdinaryStake : XInteger64 -> LedgerT ( XErrorValue  True XInteger ) .\nParameter DePoolContract_\u0424_addVestingOrLock : XInteger64 -> XAddress -> XInteger32 -> XInteger32 -> XBool -> LedgerT True .\nParameter DePoolContract_\u0424_addVestingStake : XInteger64 -> XAddress -> XInteger32 -> XInteger32 -> LedgerT True .\nParameter DePoolContract_\u0424_addLockStake : XInteger64 -> XAddress -> XInteger32 -> XInteger32 -> LedgerT True .\nParameter DePoolContract_\u0424_withdrawPart : XInteger64 -> LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_withdrawAll : LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_cancelWithdrawal : LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_transferStake : XAddress -> XInteger64 -> LedgerT ( XErrorValue  True XInteger ) .\nParameter DePoolContract_\u0424_totalParticipantFunds : XInteger64 -> LedgerT XInteger64 .\nParameter DePoolContract_\u0424_checkPureDePoolBalance : LedgerT XBool .\nParameter DePoolContract_\u0424_participateInElections : XInteger64 -> XInteger256 -> XInteger32 -> XInteger32 -> XInteger256 -> XList XInteger8 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_updateRound2 : RoundsBase_\u03b9_Round -> XInteger256 -> XInteger256 -> XInteger32 -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_isEmptyRound : RoundsBase_\u03b9_Round -> LedgerT XBool .\nParameter DePoolContract_\u0424_updateRounds : LedgerT (XErrorValue (XValueValue True) XInteger) .\nParameter DePoolContract_\u0424_ticktock : LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_acceptRewardAndStartRoundCompleting : RoundsBase_\u03b9_Round -> XInteger64 -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_onSuccessToRecoverStake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onFailToRecoverStake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_terminator : LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onBounce : TvmSlice -> LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_completeRoundWithChunk : XInteger64 -> XInteger8 -> LedgerT (XErrorValue ( XValueValue True ) XInteger ) .\nParameter DePoolContract_\u0424_completeRound : XInteger64 -> XInteger32 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onStakeAccept : XInteger64 -> XInteger32 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onStakeReject : XInteger64 -> XInteger32 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_receiveFunds : LedgerT True .\nParameter DePool_\u0424_getParticipantInfo : XAddress -> LedgerT (XErrorValue ( XInteger64 # XInteger64 # XBool # XInteger64 # (XHMap XInteger64 XInteger64) # (XHMap XInteger64 RoundsBase_\u03b9_InvestParams) # (XHMap XInteger64 RoundsBase_\u03b9_InvestParams) ) XInteger)%sol.\nParameter DePoolContract_\u0424_setValidatorRewardFraction :  XInteger8 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePool_\u0424_getParticipants : LedgerT (XArray XAddress) .\nParameter DePoolContract_\u0424_withdrawFromPoolingRound : XInteger64 -> LedgerT (XErrorValue True XInteger) .\n\nEnd DePoolSpecSig.\n\nEnd DePoolSpec.\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/DePoolSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.18420741880658406}}
{"text": "Require Import SegmentQueue.lib.thread_queue.thread_queue.\nFrom SegmentQueue.lib.concurrent_linked_list.infinite_array\n     Require Import array_spec iterator.iterator_impl.\nFrom SegmentQueue.lib.blocking_pool Require Import outer_storage_interfaces.\nRequire Import SegmentQueue.lib.util.future.\nFrom iris.heap_lang Require Import notation.\n\nSection impl.\n\nVariable array_interface: infiniteArrayInterface.\n\nVariable storage_interface: outerStorageInterface.\n\nDefinition newPool: val :=\n  \u03bb: <>, ((ref #0, newStorage storage_interface #()),\n           newThreadQueue array_interface #()).\n\nDefinition takePool: val :=\n  rec: \"loop\" \"pool\" :=\n    let: \"availablePermits\" := Fst (Fst (\"pool\")) in\n    let: \"storage\" := Snd (Fst (\"pool\")) in\n    let: \"e\" := Fst (Snd (\"pool\")) in\n    let: \"p\" := FAA \"availablePermits\" #(-1) in\n    if: #0 < \"p\" then\n      match: tryRetrieve storage_interface \"storage\" with\n        NONE => \"loop\" \"pool\"\n      | SOME \"v\" => fillThreadQueueFuture \"v\"\n      end\n    else match: suspend array_interface \"e\" with\n           InjR \"v\" => \"v\"\n         | InjL \"x\" => \"undefined\"\n         end.\n\nDefinition resumePool: val :=\n  \u03bb: \"d\", resume array_interface #(Z.of_nat 300) #true #false #false \"d\".\n\nDefinition putPool: val :=\n  rec: \"loop\" \"pool\" \"value\" :=\n    let: \"availablePermits\" := Fst (Fst (\"pool\")) in\n    let: \"storage\" := Snd (Fst (\"pool\")) in\n    let: \"d\" := Snd (Snd (\"pool\")) in\n    let: \"p\" := FAA \"availablePermits\" #1 in\n    let: \"completeRefused\" :=\n       \u03bb: \"value'\", if: tryInsert storage_interface \"storage\" \"value'\"\n                    then #()\n                    else \"loop\" \"pool\" \"value\"\n    in if: #0 \u2264 \"p\" then\n         if: tryInsert storage_interface \"storage\" \"value\"\n         then #()\n         else \"loop\" \"pool\" \"value\"\n       else resumePool \"d\" \"completeRefused\" \"value\" ;; #().\n\nDefinition cancelPoolFuture : val :=\n  \u03bb: \"pool\" \"f\",\n  let: \"availablePermits\" := Fst (Fst (\"pool\")) in\n  let: \"storage\" := Snd (Fst (\"pool\")) in\n  let: \"d\" := Snd (Snd (\"pool\")) in\n  tryCancelThreadQueueFuture'\n    array_interface\n    #false\n    #(Z.of_nat 300)\n    #false\n    #false\n    \"d\"\n    (\u03bb: <>, FAA \"availablePermits\" #1 < #0)\n    (\u03bb: \"value'\", if: tryInsert storage_interface \"storage\" \"value'\"\n                  then #()\n                  else putPool \"pool\" \"value'\")\n    (\u03bb: <>, putPool \"pool\" \"value'\")\n    \"f\".\n\nEnd impl.\n\nFrom SegmentQueue.util Require Import everything big_opL.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.algebra Require Import auth numbers list gset excl csum.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Import proofmode.\n\nFrom SegmentQueue.lib.blocking_pool Require Import outer_storage_spec.\n\nSection proof.\n\nContext `{heapG \u03a3} `{iteratorG \u03a3} `{threadQueueG \u03a3} `{futureG \u03a3}.\n\nNotation algebra := (authUR (prodUR natUR natUR)).\n\nClass iPoolG \u03a3 := IPoolG { iPool_inG :> inG \u03a3 algebra }.\nDefinition iPool\u03a3 : gFunctors := #[GFunctor algebra].\nInstance subG_iPool\u03a3 : subG iPool\u03a3 \u03a3 \u2192 iPoolG \u03a3.\nProof. solve_inG. Qed.\nContext `{iPoolG \u03a3}.\n\nVariable (N NFuture: namespace).\nVariable (HNDisj: N ## NFuture).\nLet NPool := N .@ \"Pool\".\nLet NStorage := N .@ \"Storage\".\nLet NTq := N .@ \"Tq\".\nNotation iProp := (iProp \u03a3).\n\nDefinition insertion_permit \u03b3inner := own \u03b3inner (\u25ef (1, 0)).\n\nDefinition retrieval_permit \u03b3inner := own \u03b3inner (\u25ef (0, 1)).\n\nVariable array_interface: infiniteArrayInterface.\nVariable array_spec: infiniteArraySpec _ array_interface.\n\nVariable storage_interface: outerStorageInterface.\nVariable storage_spec: outerStorageSpec _ storage_interface.\n\nDefinition pool_inv (U: base_lit -> iProp)\n           (\u03b3inner \u03b3st \u03b3tq: gname) (p: loc) : iProp :=\n  \u2203 (elems: list base_lit) (failures: nat) (ki kr: nat),\n    \u231cfailures + kr \u2264 length elems + ki\u231d \u2227\n    (([\u2217 list] e \u2208 elems, U e \u2227 \u231clit_is_unboxed e\u231d \u2227 \u231cLaterable (U e)\u231d) \u2217\n     outer_storage_contents _ _ storage_spec \u03b3st\n       (OuterStorageState failures (list_to_set_disj (LitV <$> elems)))\n    ) \u2217 own \u03b3inner (\u25cf (ki, kr)) \u2217\n    \u2203 enqueuedThreads, thread_queue_state \u03b3tq enqueuedThreads \u2217\n    p \u21a6 #((length elems - failures)%Z - enqueuedThreads + ki - kr) \u2217\n    \u231c(length elems + ki = failures + kr)%nat \u2228 enqueuedThreads = 0\u231d.\n\nLet tqParams \u03b3 U :=\n  @ThreadQueueParameters\n    \u03a3\n    false\n    True\n    True\n    (insertion_permit \u03b3)\n    (fun x => U x \u2227 \u231clit_is_unboxed x\u231d \u2227 \u231cLaterable (U x)\u231d)%I\n    False.\n\nLet isThreadQueue \u03b3 U :=\n  is_thread_queue NTq NFuture (tqParams \u03b3 U) _ array_spec.\n\nDefinition is_pool_future \u03b3 U :=\n  is_thread_queue_future NTq NFuture (tqParams \u03b3 U) _ array_spec.\n\nDefinition is_pool U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d (pool: val): iProp :=\n  \u2203 e d s (p: loc), \u231cpool = ((#p, s), (e, d))%V\u231d \u2227\n  is_outer_storage _ _ storage_spec NStorage \u03b3st s \u2217\n  inv NPool (pool_inv U \u03b3 \u03b3st \u03b3tq p) \u2217 isThreadQueue \u03b3 U \u03b3a \u03b3tq \u03b3e \u03b3d e d.\n\nTheorem putPool_spec U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool (x: base_lit):\n  Laterable (U x) -> lit_is_unboxed x ->\n  {{{ is_pool U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool \u2217 U x }}}\n    putPool array_interface storage_interface pool #x\n  {{{ RET #(); True }}}.\nProof.\n  iIntros (xLaterable xUnboxed \u03a6) \"[#HIsPool HU] H\u03a6\". wp_lam. wp_pures.\n  iSpecialize (\"H\u03a6\" with \"[$]\").\n  iDestruct \"HIsPool\" as (e d s p ->) \"(HSt & HInv & HTq)\".\n  wp_pures.\n  iL\u00f6b as \"IH\" forall (\u03a6).\n  wp_bind (FAA _ _).\n  iInv \"HInv\" as (elements1 failures1 ki1 kr1)\n                   \"(>% & HElems & H\u25cf & HOpen)\" \"HClose\".\n  iDestruct \"HOpen\" as (enqueuedThreads1) \"(HState & Hp & >HPures)\".\n  iDestruct \"HPures\" as %HPures1.\n  destruct (decide (0 \u2264 length elements1 - failures1 - enqueuedThreads1 + ki1 - kr1)%Z)\n    as [HGe|HLt].\n  - assert (enqueuedThreads1 = 0) as -> by lia. rewrite Z.sub_0_r.\n    wp_faa.\n    iAssert (|==> own \u03b3 (\u25cf (S ki1, kr1)) \u2217 insertion_permit \u03b3)%I\n      with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_alloc, prod_local_update_1, nat_local_update.\n      rewrite Nat.add_0_r. lia.\n    }\n    iMod (\"HClose\" with \"[-H\u03a6 H\u25ef HU]\") as \"_\".\n    { iExists elements1, failures1, _, _.\n      iFrame \"HElems H\u25cf\". iSplitR.\n      by iPureIntro; lia.\n      iExists 0.\n      iFrame \"HState\". iSplitL; last by iPureIntro; lia.\n      rewrite Z.sub_0_r.\n      replace (_ + ki1 - kr1 + 1)%Z\n        with (length elements1 - failures1 + S ki1 - kr1)%Z by lia.\n      iFrame. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    awp_apply (tryInsert_spec with \"HSt\") without \"IH HTq H\u03a6\".\n    iInv \"HInv\" as (elements2 failures2 ki2 kr2)\n                    \"(>% & [HElems HContents] & >H\u25cf & HOpen)\".\n    iAaccIntro with \"HContents\".\n    {\n      iIntros \"HContents !>\". iFrame \"H\u25ef HU\".\n      iExists _, _, _, _. by iFrame.\n    }\n    iIntros (b) \"HContents\". destruct b.\n    + iSplitL.\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. by iApply \"H\u03a6\". }\n      simpl.\n      rewrite -list_to_set_disj_cons.\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      iExists (x::elements2), failures2, ki2', kr2.\n      iSplitR. by iPureIntro; simpl; lia.\n      simpl.\n      iFrame.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iSplitR; first by iPureIntro.\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - failures2 - enq + S ki2' - kr2)%Z\n              with (S (length elements2) - failures2 - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n    + iSplitR \"HU\".\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. wp_lam. wp_pures.\n           iApply (\"IH\" $! \u03a6 with \"[$] [$]\"). }\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      destruct failures2 as [|failures2']; simpl.\n      by iDestruct \"HContents\" as %[].\n      iExists elements2, failures2', ki2', kr2. iFrame.\n      iSplitR; first by iPureIntro; lia.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - S failures2' - enq + S ki2' - kr2)%Z\n              with (length elements2 - failures2' - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n  - iMod (thread_queue_register_for_dequeue' with \"HTq [] HState\")\n      as \"[HState HAwak]\"; [by solve_ndisj|lia|by iFrame|].\n    wp_faa. iMod (\"HClose\" with \"[-H\u03a6 HAwak HU]\") as \"_\".\n    { iExists elements1, failures1, ki1, kr1.\n      iFrame \"HElems H\u25cf\". iSplitR; first by iPureIntro.\n      iExists (enqueuedThreads1 - 1).\n      iFrame \"HState\". iSplitL; last by iPureIntro; lia.\n      by replace\n           (length elements1 - failures1 - enqueuedThreads1 + ki1 - kr1 + 1)%Z\n        with\n          (length elements1 - failures1 - (enqueuedThreads1 - 1)%nat + ki1 - kr1)%Z\n        by lia. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last lia. wp_pures.\n    wp_lam. wp_pures.\n    wp_apply (resume_spec with \"[] [HAwak HU]\").\n    5: { iFrame \"HTq HAwak HU\". iPureIntro; done. }\n    by solve_ndisj. done. done.\n    { simpl. iIntros (\u03a8) \"!> [H\u25ef HU] H\u03a8\". wp_pures.\n      iSpecialize (\"H\u03a8\" with \"[%]\"). done.\n    iDestruct \"HU\" as \"[HU _]\".\n    awp_apply (tryInsert_spec with \"HSt\") without \"IH HTq H\u03a8\".\n    iInv \"HInv\" as (elements2 failures2 ki2 kr2)\n                    \"(>% & [HElems HContents] & >H\u25cf & HOpen)\".\n    iAaccIntro with \"HContents\".\n    {\n      iIntros \"HContents !>\". iFrame \"H\u25ef HU\".\n      iExists _, _, _, _. by iFrame.\n    }\n    iIntros (b) \"HContents\". destruct b.\n    + iSplitL.\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. by iApply \"H\u03a6\". }\n      simpl.\n      rewrite -list_to_set_disj_cons.\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      iExists (x::elements2), failures2, ki2', kr2.\n      iSplitR. by iPureIntro; simpl; lia.\n      simpl.\n      iFrame.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iSplitR; first by iPureIntro.\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - failures2 - enq + S ki2' - kr2)%Z\n              with (S (length elements2) - failures2 - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n    + iSplitR \"HU\".\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. wp_lam. wp_pures.\n           iApply (\"IH\" $! \u03a8 with \"[$] [$]\"). }\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      destruct failures2 as [|failures2']; simpl.\n      by iDestruct \"HContents\" as %[].\n      iExists elements2, failures2', ki2', kr2. iFrame.\n      iSplitR; first by iPureIntro; lia.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - S failures2' - enq + S ki2' - kr2)%Z\n              with (length elements2 - failures2' - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n    }\n    iIntros (b) \"Hr\". simpl. wp_pures. by iApply \"H\u03a6\".\nQed.\n\nTheorem newPool_spec (n: nat) U:\n  {{{ inv_heap_inv }}}\n    newPool array_interface storage_interface #()\n  {{{ \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d s, RET s; is_pool U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d s }}}.\nProof.\n  iIntros (\u03a6) \"#HHeap H\u03a6\". iApply fupd_wp.\n  iMod (own_alloc (\u25cf (\u03b5, \u03b5))) as (\u03b3) \"H\u25cf\".\n  { apply auth_auth_valid. apply pair_valid. split; done. }\n  iModIntro.\n  wp_lam. wp_bind (newThreadQueue _ _).\n  iApply (newThreadQueue_spec with \"HHeap\").\n  iIntros (\u03b3a \u03b3tq \u03b3e \u03b3d e d) \"!> [#HTq HThreadState]\".\n  rewrite -wp_fupd.\n  wp_bind (newStorage _ _).\n  iApply (newStorage_spec with \"[$]\").\n  iIntros (\u03b3st st) \"!> [#HStorage HContents]\".\n  wp_alloc p as \"Hp\". wp_pures.\n  iMod (inv_alloc NPool _ (pool_inv U \u03b3 \u03b3st \u03b3tq p) with \"[-H\u03a6]\") as \"#HInv\".\n  { iExists [], 0, 0, 0. simpl. iFrame. iSplitR; first done.\n    iExists 0. iFrame. by iLeft. }\n  iApply \"H\u03a6\". iExists _, _, _, _. iSplitR; first done. by iFrame \"HInv HTq\".\nQed.\n\nSection XX.\nContext `{Countable A}.\nImplicit Types x y : A.\nImplicit Types X Y : gmultiset A.\nLemma gmultiset_difference_disj_union X Y : Y = (X \u228e Y) \u2216 X.\nProof.\n  apply gmultiset_eq. move=> x.\n  rewrite multiplicity_difference multiplicity_disj_union. lia.\nQed.\n\nLemma gmultiset_difference_disj_singleton' X Y B:\n  X \u2229 B = \u2205 -> X \u228e (Y \u2216 B) = (X \u228e Y) \u2216 B.\nProof.\n  move=> xintb. apply gmultiset_eq. move=> x.\n  rewrite multiplicity_difference multiplicity_disj_union.\n  rewrite multiplicity_difference multiplicity_disj_union.\n  destruct (decide (x \u2208 B)) as [XinB|XnotInB].\n  2: { move: XnotInB. rewrite elem_of_multiplicity=> e. lia. }\n  assert (not (x \u2208 X)) as XnotInX.\n  {\n    assert (multiplicity x (X \u2229 B) = 0) as XnotInXB.\n    by rewrite xintb multiplicity_empty.\n    move: XnotInXB. rewrite multiplicity_intersection.\n    move: XinB xintb. rewrite !elem_of_multiplicity. lia.\n  }\n  move: XnotInX. rewrite elem_of_multiplicity=> e. lia.\nQed.\nEnd XX.\n\nLemma XX {A} `{Countable A} x (xs: list A):\n  x \u2208 xs ->\n  \u2203 n,\n  list_to_set_disj xs \u2216 ({[x]}: gmultiset A) =\n  list_to_set_disj (take n xs ++ drop (S n) xs) \u2227 xs !! n = Some x.\nProof.\n  move=> xInXs.\n  induction xs.\n  - exfalso. inversion xInXs.\n  - simpl.\n    destruct (decide (a = x)) as [eq|neq].\n    * subst.\n      rewrite -gmultiset_difference_disj_union.\n      exists 0. simpl. rewrite drop_0. done.\n    * inversion xInXs; first done. subst.\n      rewrite -gmultiset_difference_disj_singleton'.\n      2: {\n        apply gmultiset_eq. move=> y.\n        rewrite multiplicity_empty multiplicity_intersection.\n        rewrite !multiplicity_singleton'.\n        destruct (decide (y = a)) as [eq'|neq']; simpl; last done.\n        destruct (decide (y = x)) as [eq''|neq']; simpl; last done.\n        subst. done.\n      }\n      destruct IHxs as [m Hm]; first done.\n      move: Hm. case=> -> HOk.\n      exists (S m). simpl. by split.\nQed.\n\nTheorem takePool_spec U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool:\n  {{{ is_pool U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool }}}\n    takePool array_interface storage_interface pool\n  {{{ \u03b3f v, RET v; is_pool_future \u03b3 U \u03b3tq \u03b3a \u03b3f v \u2217\n                   thread_queue_future_cancellation_permit \u03b3f }}}.\nProof.\n  iIntros (\u03a6) \"#HIsPool H\u03a6\". wp_lam. wp_pures.\n  iDestruct \"HIsPool\" as (e d s p ->) \"(HSt & HInv & HTq)\".\n  wp_pures.\n  iL\u00f6b as \"IH\".\n  wp_bind (FAA _ _).\n  iInv \"HInv\" as (elements1 failures1 ki1 kr1)\n                   \"(>% & HElems & H\u25cf & HOpen)\" \"HClose\".\n  iDestruct \"HOpen\" as (enqueuedThreads1) \"(HState & Hp & >HPures)\".\n  iDestruct \"HPures\" as %HPures1.\n  destruct (decide (0 < length elements1 - failures1 - enqueuedThreads1 + ki1 - kr1)%Z)\n    as [HGe|HLt].\n  - assert (enqueuedThreads1 = 0) as -> by lia. rewrite Z.sub_0_r.\n    wp_faa.\n    iAssert (|==> own \u03b3 (\u25cf (ki1, S kr1)) \u2217 retrieval_permit \u03b3)%I\n      with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_alloc, prod_local_update_2, nat_local_update.\n      rewrite Nat.add_0_r. lia. }\n    iMod (\"HClose\" with \"[-H\u03a6 H\u25ef]\") as \"_\".\n    { iExists elements1, failures1, ki1, (S kr1).\n      iFrame \"HElems H\u25cf\". iSplitR.\n      by iPureIntro; lia.\n      iExists 0.\n      iFrame \"HState\". iSplitL; last by iPureIntro; lia.\n      rewrite Z.sub_0_r.\n      replace (_ - kr1 + -1)%Z\n        with (length elements1 - failures1 + ki1 - S kr1)%Z by lia.\n      iFrame. }\n    iModIntro. wp_pures.\n    rewrite bool_decide_true; last lia. wp_pures.\n    awp_apply (tryRetrieve_spec with \"HSt\") without \"IH HTq H\u03a6\".\n    iInv \"HInv\" as (elements2 failures2 ki2 kr2)\n                    \"(>% & [HElems HContents] & >H\u25cf & HOpen)\".\n    iAaccIntro with \"HContents\".\n    {\n      iIntros \"HContents !>\". iFrame \"H\u25ef\".\n      iExists _, _, _, _. by iFrame.\n    }\n    iIntros (v) \"HContents\". destruct v as [v|]; simpl.\n    + destruct (multiplicity _ _) as [|m] eqn:E; first done.\n      assert (\u2203 (b: base_lit), v = #b) as [b eq].\n      {\n        move: E. clear.\n        induction elements2; first done.\n        simpl. rewrite multiplicity_disj_union.\n        destruct (decide (v = #a)) as [->|neq].\n        - move=> _. exists a. done.\n        - rewrite multiplicity_singleton' decide_False; last done.\n          simpl.\n          apply IHelements2.\n      }\n      subst.\n      destruct (XX (#b) (LitV <$> elements2)) as [n [-> HElem]].\n      { move: E. clear.\n        induction elements2; first done.\n        simpl. rewrite multiplicity_disj_union.\n        destruct (decide (b = a)) as [->|neq].\n        - move=> _. constructor.\n        - rewrite multiplicity_singleton' decide_False; last by by case.\n          simpl.\n          move=> HH. move: (IHelements2 HH). by constructor.\n      }\n      rewrite -fmap_take -fmap_drop -fmap_app.\n      assert (elements2 !! n = Some b) as HElem'.\n      {\n        rewrite list_lookup_fmap in HElem.\n        destruct (elements2 !! n); last done.\n        simpl in *.\n        move: HElem. case=> -> //.\n      }\n      rewrite big_opL_take_drop_middle; last done.\n      iDestruct \"HElems\" as \"(HElems1 & HU & HElems2)\".\n      iSplitR \"HU\".\n      2: {\n        iModIntro. iIntros \"H\u03a6\". wp_pures.\n        wp_apply (fillThreadQueueFuture_spec with \"[HU]\").\n        2: { iIntros (\u03b3f v') \"(HFuture & HCancPermit & _)\".\n             iApply \"H\u03a6\". iFrame. }\n        rewrite /V'. simpl. iExists b. iFrame. iPureIntro.\n        by repeat split.\n      }\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[_ HValid%nat_included]%prod_included _]%auth_both_valid.\n      simpl in *. destruct kr2 as [|kr2']; first lia.\n      assert (n < length elements2). by eapply lookup_lt_Some.\n      iExists (take n elements2 ++ drop (S n) elements2), failures2, ki2, kr2'.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_2, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      rewrite big_sepL_app.\n      rewrite app_length take_length_le; last lia.\n      rewrite drop_length.\n      iSplitR.\n      by iPureIntro; lia.\n      iFrame \"HElems1 HElems2 HContents\".\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame. iSplitL.\n      2: by iPureIntro; lia.\n      replace (length elements2 - failures2 - enq + ki2 - S kr2')%Z\n              with ((n + (length elements2 - S n))%nat -\n                                     failures2 - enq + ki2 - kr2')%Z by lia.\n      by iFrame.\n    + iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[_ HValid%nat_included]%prod_included _]%auth_both_valid.\n      simpl in *. destruct kr2 as [|kr2']; first lia.\n      iSplitL.\n      2: {\n        iModIntro. iIntros \"H\u03a6\". wp_pures. wp_lam. wp_pures.\n        by iApply (\"IH\" with \"H\u03a6\").\n      }\n      iExists elements2, (S failures2), ki2, kr2'.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_2, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iSplitR; first by iPureIntro; lia.\n      iFrame.\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame. iSplitL; last by iPureIntro; lia.\n      iModIntro.\n      replace (length elements2 - failures2 - enq + ki2 - S kr2')%Z\n              with (length elements2 - S failures2 - enq + ki2 - kr2')%Z by lia.\n      by iFrame.\n  - iMod (thread_queue_append' with \"HTq [] HState\")\n      as \"[HState HSus]\"=> /=; [by solve_ndisj|done|].\n    wp_faa. iMod (\"HClose\" with \"[-H\u03a6 HSus]\") as \"_\".\n    { iExists _, _, _, _. iFrame \"HElems H\u25cf\". iSplitR; first done.\n      iExists (S enqueuedThreads1).\n      iFrame \"HState\". iSplitL; last by iPureIntro; lia.\n      replace (_ - enqueuedThreads1 + ki1 - kr1 + -1)%Z with\n          (length elements1 - failures1 - S enqueuedThreads1 + ki1 - kr1)%Z\n          by lia.\n      done. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last lia. wp_pures.\n    wp_apply (suspend_spec with \"[$]\")=> /=. iIntros (v) \"[(_ & _ & %)|Hv]\".\n    done.\n    iDestruct \"Hv\" as (\u03b3f v') \"(-> & HFuture & HCancPermit)\". wp_pures.\n    iApply \"H\u03a6\". iFrame.\nQed.\n\nTheorem cancelPoolFuture_spec U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool \u03b3f f:\n  is_pool U \u03b3 \u03b3st \u03b3a \u03b3tq \u03b3e \u03b3d pool -\u2217\n  is_pool_future \u03b3 U \u03b3tq \u03b3a \u03b3f f -\u2217\n  <<< \u25b7 thread_queue_future_cancellation_permit \u03b3f >>>\n    cancelPoolFuture array_interface storage_interface pool f @ \u22a4 \u2216 \u2191NFuture \u2216 \u2191N\n  <<< \u2203 (r: bool),\n      if r then future_is_cancelled \u03b3f\n      else (\u2203 v, \u25b7 future_is_completed \u03b3f v) \u2217\n           thread_queue_future_cancellation_permit \u03b3f, RET #r >>>.\nProof.\n  iIntros \"#HIsPool #HFuture\" (\u03a6) \"AU\".\n  iDestruct \"HIsPool\" as (e d s p ->) \"(HSt & HInv & HTq)\".\n  wp_lam. wp_pures. wp_lam.\n  wp_pures. awp_apply (try_cancel_thread_queue_future with \"HTq HFuture\");\n              first by solve_ndisj.\n  iApply (aacc_aupd_commit with \"AU\"). by solve_ndisj.\n  iIntros \"HCancPermit\". iAaccIntro with \"HCancPermit\". by iIntros \"$ !> $ !>\".\n  iIntros (r) \"Hr\". iExists r. destruct r.\n  2: { iDestruct \"Hr\" as \"[$ $]\". iIntros \"!> H\u03a6 !>\". by wp_pures. }\n  iDestruct \"Hr\" as \"[#HFutureCancelled Hr]\". iFrame \"HFutureCancelled\".\n  rewrite /is_pool_future /is_thread_queue_future.\n  iDestruct \"Hr\" as (i f' s' ->) \"Hr\"=> /=.\n  iDestruct \"Hr\" as \"(#H\u21a6~ & #HTh & HToken)\". iIntros \"!> H\u03a6 !>\". wp_pures.\n  wp_lam. wp_pures. wp_apply derefCellPointer_spec.\n  by iDestruct \"HTq\" as \"(_ & $ & _)\". iIntros (\u2113) \"#H\u21a6\". wp_pures.\n  wp_bind (FAA _ _).\n  iInv \"HInv\" as (elements1 failures1 ki1 kr1)\n                   \"(>% & HElems & H\u25cf & HOpen)\" \"HClose\".\n  iDestruct \"HOpen\" as (enqueuedThreads1) \"(>HState & Hp & >HPures)\".\n  iDestruct \"HPures\" as %HPures.\n  iMod (register_cancellation with \"HTq HToken HState\")\n       as \"[HCancToken HState]\"; first by solve_ndisj.\n  destruct (decide (length elements1 - failures1 - enqueuedThreads1 + ki1 - kr1 < 0)%Z)\n    as [HLt|HGe].\n  - assert (length elements1 - failures1 + ki1 - kr1 = 0)%Z as HPerms by lia.\n    destruct enqueuedThreads1 as [|enqueuedThreads1']=>/=; first lia.\n    iDestruct \"HState\" as \"(HState & HCancHandle & #HInhabited)\".\n    wp_faa.\n    iMod (\"HClose\" with \"[-H\u03a6 HCancToken HCancHandle]\") as \"_\".\n    { iExists elements1, failures1, ki1, kr1.\n      iSplitR; simpl; first done. iFrame. iExists enqueuedThreads1'.\n      rewrite Nat.sub_0_r. iFrame \"HState\".\n      iSplitL; last by iLeft; iPureIntro; lia.\n      replace (_ - S enqueuedThreads1' + ki1 - kr1 + 1)%Z with\n          (length elements1 - failures1 - enqueuedThreads1' + ki1 - kr1)%Z;\n        last lia.\n      iFrame.\n    }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    wp_bind (getAndSet.getAndSet _ _).\n    awp_apply (markCancelled_spec with \"HTq HInhabited H\u21a6 HCancToken HTh\")\n              without \"H\u03a6 HCancHandle\".\n    iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n    iIntros \"!> [H\u03a6 HCancHandle]\". wp_pures.\n    iAssert (\u25b7 cell_cancellation_handle _ _ _ _ _ _)%I\n            with \"[HCancHandle]\" as \"HCancHandle\"; first done.\n    awp_apply (onCancelledCell_spec with \"[] H\u21a6~\") without \"Hv H\u03a6\".\n    by iDestruct \"HTq\" as \"(_ & $ & _)\".\n    iAaccIntro with \"HCancHandle\". by iIntros \"$\".\n    iIntros \"#HCancelled !> [Hv H\u03a6]\". wp_pures.\n    iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n    iDestruct \"Hv\" as (x ->) \"(#HInhabited' & HAwak & HU)\"; simplify_eq.\n    wp_pures.\n    iDestruct \"HU\" as \"[HU [% %]]\".\n    wp_apply (resume_spec with \"[] [HAwak HU]\").\n    5: { iFrame \"HTq HAwak HU\". by iPureIntro. }\n    by solve_ndisj. done. done.\n    2: {\n      iIntros (b) \"HContents\". destruct b. by wp_pures.\n      wp_pures. simpl. iDestruct \"HContents\" as \"[[[]|[]] _]\".\n    }\n    simpl. iIntros (\u03a8) \"!> [H\u25ef HU] H\u03a8\". wp_pures.\n    iSpecialize (\"H\u03a8\" with \"[%]\"). done.\n    iDestruct \"HU\" as \"[HU [% %]]\".\n    wp_bind (tryInsert _ _ _).\n    awp_apply (tryInsert_spec with \"HSt\") without \"H\u03a8\".\n    iInv \"HInv\" as (elements2 failures2 ki2 kr2)\n                    \"(>% & [HElems HContents] & >H\u25cf & HOpen)\".\n    iAaccIntro with \"HContents\".\n    {\n      iIntros \"HContents !>\". iFrame \"H\u25ef HU\".\n      iExists _, _, _, _. by iFrame.\n    }\n    iIntros (b) \"HContents\". destruct b.\n    + iSplitL.\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. by iApply \"H\u03a6\". }\n      simpl.\n      rewrite -list_to_set_disj_cons.\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      iExists (x::elements2), failures2, ki2', kr2.\n      iSplitR. by iPureIntro; simpl; lia.\n      simpl.\n      iFrame.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iSplitR; first by iPureIntro.\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - failures2 - enq + S ki2' - kr2)%Z\n              with (S (length elements2) - failures2 - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n    + iSplitR \"HU\".\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures.\n           iApply (putPool_spec with \"[HU]\"); try done.\n           { iFrame \"HU\". iExists _, _, _, _. iFrame \"HSt HInv HTq\".\n             done. }\n           by iIntros \"!> _\".\n      }\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      destruct failures2 as [|failures2']; simpl.\n      by iDestruct \"HContents\" as %[].\n      iExists elements2, failures2', ki2', kr2. iFrame.\n      iSplitR; first by iPureIntro; lia.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - S failures2' - enq + S ki2' - kr2)%Z\n              with (length elements2 - failures2' - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n  - rewrite bool_decide_true; last lia.\n    assert (enqueuedThreads1 = 0) as -> by lia.\n    simpl. iDestruct \"HState\" as \"(HState & HR & #HInhabited)\".\n    wp_faa.\n    iAssert (|==> own \u03b3 (\u25cf (S ki1, kr1)) \u2217 insertion_permit \u03b3)%I\n      with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_alloc, prod_local_update_1, nat_local_update.\n      rewrite Nat.add_0_r. lia. }\n    iMod (\"HClose\" with \"[-H\u03a6 HCancToken H\u25ef]\") as \"_\".\n    { iExists elements1, failures1, (S ki1), kr1.\n      iFrame \"H\u25cf\". iSplitR; first by iPureIntro; lia.\n      iFrame. iExists 0.\n      iFrame \"HState\". iSplitL; last by iRight.\n      by replace (_ + ki1 - kr1 + 1)%Z\n        with (length elements1 - failures1 - 0%nat + S ki1 - kr1)%Z by lia. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last lia. wp_pures.\n    wp_bind (getAndSet.getAndSet _ _).\n    awp_apply (markRefused_spec with \"HTq HInhabited H\u21a6 HCancToken HTh H\u25ef\")\n              without \"H\u03a6\".\n    iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n    iIntros \"!> H\u03a6\". iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n    iDestruct \"Hv\" as (? ->) \"[>H\u25ef [HU >[% %]]]\". simplify_eq. wp_pures.\n    awp_apply (tryInsert_spec with \"HSt\") without \"HTq H\u03a6\".\n    iInv \"HInv\" as (elements2 failures2 ki2 kr2)\n                    \"(>% & [HElems HContents] & >H\u25cf & HOpen)\".\n    iAaccIntro with \"HContents\".\n    {\n      iIntros \"HContents !>\". iFrame \"H\u25ef HU\".\n      iExists _, _, _, _. by iFrame.\n    }\n    iIntros (b) \"HContents\". destruct b.\n    + iSplitL.\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures. by iApply \"H\u03a6\". }\n      simpl.\n      rewrite -list_to_set_disj_cons.\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      iExists (v'::elements2), failures2, ki2', kr2.\n      iSplitR. by iPureIntro; simpl; lia.\n      simpl.\n      iFrame.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iSplitR; first by iPureIntro.\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - failures2 - enq + S ki2' - kr2)%Z\n              with (S (length elements2) - failures2 - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\n    + iSplitR \"HU\".\n      2: { iModIntro. iIntros \"H\u03a6\". wp_pures.\n           wp_apply (putPool_spec with \"[HU]\"); try done.\n           { iFrame. iExists _, _, _, _. iFrame \"HSt HInv HTq\". done. }\n           iIntros \"_\". by wp_pures. }\n      iDestruct (own_valid_2 with \"H\u25cf H\u25ef\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      simpl in *. destruct ki2 as [|ki2']; first lia.\n      destruct failures2 as [|failures2']; simpl.\n      by iDestruct \"HContents\" as %[].\n      iExists elements2, failures2', ki2', kr2. iFrame.\n      iSplitR; first by iPureIntro; lia.\n      iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\".\n      { apply auth_update_dealloc, prod_local_update_1, nat_local_update.\n        rewrite Nat.add_0_r. lia. }\n      iDestruct \"HOpen\" as (enq) \"(HTq' & Hp & >%)\".\n      iExists enq. iFrame \"HTq'\". iSplitL; last by iPureIntro; lia.\n      replace (length elements2 - S failures2' - enq + S ki2' - kr2)%Z\n              with (length elements2 - failures2' - enq + ki2' - kr2)%Z\n                   by lia.\n      by iFrame.\nQed.\n\nEnd proof.\n", "meta": {"author": "anonymousPldiSubmitterCQS", "repo": "proofs", "sha": "7dc09221303978c5918b5064ba787bc2268fa0bb", "save_path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs", "path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs/proofs-7dc09221303978c5918b5064ba787bc2268fa0bb/theories/lib/blocking_pool/pool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.18413817994186268}}
{"text": "Require Import os_code_defs.\nRequire Import code_notations.\nRequire Import os_ucos_h.\n\n(*os_q.c*)\nOpen Scope code_scope.\n\nDefinition OSQAccept_impl := \n Void \u2217 \u00b7OSQAccept\u00b7(\u231epevent @ OS_EVENT\u2217\u231f)\u00b7\u00b7{\n        \u231e \n          message @ Void \u2217;\n          pq @ OS_Q \u2217 ;\n          legal @ Int8u\n        \u231f; \n               \n          If(pevent\u2032 ==\u2091 NULL){\n              RETURN \u2329Void \u2217\u232a NULL \n          };\u209b\n          ENTER_CRITICAL;\u209b\n          legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n          If (legal\u2032 ==\u2091 \u20320){\n              EXIT_CRITICAL;\u209b\n              RETURN \u2329Void \u2217\u232a NULL \n          };\u209b\n          If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_Q){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2329Void \u2217\u232a NULL \n          };\u209b\n          pq\u2032 =\u2091 pevent\u2032\u2192OSEventPtr;\u209b\n          IF (pq\u2032\u2192OSQEntries >\u2091 \u20320){\n              message\u2032 =\u2091 \u2217(pq\u2032\u2192 OSQOut);\u209b\n              pq\u2032 \u2192 OSQOut =\u2091 pq\u2032\u2192OSQOut +\u2091 \u20321 ;\u209b\n              \u2212\u2212 pq\u2032\u2192OSQEntries;\u209b\n             If (pq\u2032\u2192OSQOut ==\u2091 pq\u2032\u2192OSQEnd){\n                 pq\u2032\u2192OSQOut =\u2091 pq\u2032\u2192OSQStart\n             }\n          }ELSE{\n              message\u2032 =\u2091 NULL\n          };\u209b\n          EXIT_CRITICAL;\u209b\n          RETURN  message\u2032 \n }\u00b7 .\n\n\n\nDefinition OSQCreate_impl :=\n OS_EVENT \u2217 \u00b7OSQCreate\u00b7(\u231esize @ Int16u\u231f)\u00b7\u00b7{\n        \u231e \n          pevent @ OS_EVENT \u2217;\n          pq @ OS_Q \u2217;\n          pqblk @ OS_Q_FREEBLK \u2217;\n          start @ Void \u2217\u2217\n        \u231f; \n\n          If ((size\u2032 >\u2091 \u2032OS_MAX_Q_SIZE ) ||\u2091 (size\u2032 ==\u2091 \u20320)){\n              RETURN \u2329OS_EVENT \u2217\u232a NULL\n          };\u209b\n          ENTER_CRITICAL;\u209b\n          pevent\u2032 =\u2091 OSEventFreeList\u2032;\u209b\n          If (OSEventFreeList\u2032 !=\u2091 NULL){\n              OSEventFreeList\u2032 =\u2091  \u2329OS_EVENT \u2217\u232a OSEventFreeList\u2032\u2192OSEventListPtr\n          };\u209b\n          EXIT_CRITICAL;\u209b\n          If (pevent\u2032 !=\u2091 NULL) {\n              ENTER_CRITICAL;\u209b\n              pq\u2032 =\u2091 OSQFreeList\u2032;\u209b\n              pqblk\u2032 =\u2091 OSQFreeBlk\u2032;\u209b\n              IF (pq\u2032 !=\u2091 NULL &&\u2091  pqblk\u2032 !=\u2091 NULL){\n                  OSQFreeList\u2032 =\u2091 OSQFreeList\u2032\u2192OSQPtr;\u209b \n                  OSQFreeBlk\u2032 =\u2091 OSQFreeBlk\u2032\u2192nextblk;\u209b\n                  pq\u2032\u2192qfreeblk =\u2091 pqblk\u2032;\u209b\n                  start\u2032 =\u2091 pqblk\u2032\u2192msgqueuetbl;\u209b\n                  pq\u2032\u2192OSQStart =\u2091 start\u2032;\u209b\n                  pq\u2032\u2192OSQEnd =\u2091 &\u2090start\u2032[size\u2032];\u209b\n                  pq\u2032\u2192OSQIn =\u2091 start\u2032;\u209b \n                  pq\u2032\u2192OSQOut =\u2091 start\u2032;\u209b\n                  pq\u2032\u2192OSQSize =\u2091 size\u2032;\u209b\n                  pq\u2032\u2192OSQEntries =\u2091 \u20320;\u209b\n                  OS_EventWaitListInit(\u00adpevent\u2032\u00ad);\u209b\n                  pevent\u2032\u2192OSEventType =\u2091 \u2032OS_EVENT_TYPE_Q;\u209b\n                  pevent\u2032\u2192OSEventCnt =\u2091 \u20320;\u209b\n                  pevent\u2032\u2192OSEventPtr =\u2091 pq\u2032;\u209b\n                  pevent\u2032\u2192OSEventListPtr =\u2091 OSEventList\u2032;\u209b\n                  OSEventList\u2032 =\u2091 pevent\u2032;\u209b\n                  EXIT_CRITICAL\n              }ELSE{\n                  pevent\u2032\u2192OSEventListPtr =\u2091 \u2329Void\u2217\u232a OSEventFreeList\u2032;\u209b\n                  OSEventFreeList\u2032 =\u2091  pevent\u2032;\u209b\n                  EXIT_CRITICAL;\u209b\n                  pevent\u2032 =\u2091 NULL\n              }\n          };\u209b\n          RETURN pevent\u2032\n }\u00b7 .\n\nDefinition OSQDel_impl := \n Int8u \u00b7OSQDel\u00b7(\u231e pevent @ OS_EVENT \u2217\u231f)\u00b7\u00b7{\n        \u231e \n         tasks_waiting @ Int8u;\n         pq @ OS_Q \u2217;\n         x @ OS_Q_FREEBLK \u2217;\n         legal @ Int8u\n        \u231f; \n         \n        If (pevent\u2032 ==\u2091  NULL){\n             RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b \n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_Q){\n            EXIT_CRITICAL;\u209b\n             RETURN \u2032OS_ERR_EVENT_TYPE\n        };\u209b  \n        IF (pevent\u2032\u2192OSEventGrp !=\u2091 \u20320){\n            tasks_waiting\u2032 =\u2091 \u20321\n        }ELSE{\n            tasks_waiting\u2032 =\u2091 \u20320\n        };\u209b\n        IF (tasks_waiting\u2032 ==\u2091 \u20320){\n            OS_EventRemove(\u00adpevent\u2032\u00ad);\u209b\n            pq\u2032 =\u2091 pevent\u2032\u2192OSEventPtr;\u209b\n            x\u2032 =\u2091 pq\u2032\u2192qfreeblk;\u209b\n            x\u2032\u2192nextblk =\u2091 OSQFreeBlk\u2032;\u209b\n            OSQFreeBlk\u2032 =\u2091 pq\u2032\u2192qfreeblk;\u209b\n            pq\u2032\u2192OSQPtr =\u2091 OSQFreeList\u2032;\u209b\n            OSQFreeList\u2032 =\u2091 pq\u2032;\u209b\n            pevent\u2032\u2192OSEventType =\u2091 \u2032OS_EVENT_TYPE_UNUSED;\u209b\n            pevent\u2032\u2192OSEventListPtr =\u2091 OSEventFreeList\u2032;\u209b\n            OSEventFreeList\u2032 =\u2091 pevent\u2032;\u209b\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_NO_ERR\n        }ELSE{\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_TASK_WAITING\n        }    \n }\u00b7 . \n\n \nDefinition OSQPend_impl :=\n Int8u \u00b7OSQPend\u00b7(\u231e pevent @ OS_EVENT \u2217; timeout @ Int16u \u231f)\u00b7\u00b7{\n         \u231e \n         message @ Void\u2217;\n         pq @ OS_Q \u2217;\n         legal @ Int8u\n        \u231f; \n\n        If (pevent\u2032 ==\u2091  NULL){\n             RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b \n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_Q){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        If (OSTCBCur\u2032\u2192OSTCBPrio ==\u2091 \u2032OS_IDLE_PRIO){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        If ( (OSTCBCur\u2032\u2192OSTCBStat  !=\u2091 \u2032OS_STAT_RDY) ||\u2091 (OSTCBCur\u2032\u2192OSTCBDly  !=\u2091 \u20320)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b     \n        OSTCBCur\u2032\u2192OSTCBMsg =\u2091 NULL;\u209b\n        pq\u2032 =\u2091 pevent\u2032\u2192OSEventPtr;\u209b\n        If (pq\u2032\u2192OSQEntries >\u2091 \u20320) {\n            message\u2032 =\u2091 \u2217(pq\u2032\u2192OSQOut);\u209b\n            pq\u2032\u2192 OSQOut =\u2091 pq\u2032\u2192OSQOut +\u2091 \u20321;\u209b\n            \u2212\u2212 pq\u2032\u2192OSQEntries;\u209b\n            If (pq\u2032\u2192OSQOut ==\u2091 pq\u2032\u2192OSQEnd){\n                pq\u2032\u2192OSQOut =\u2091 pq\u2032\u2192OSQStart\n            };\u209b\n            OSTCBCur\u2032\u2192OSTCBMsg =\u2091 message\u2032;\u209b\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_NO_ERR \n        };\u209b\n        OSTCBCur\u2032\u2192OSTCBStat =\u2091 \u2032OS_STAT_Q;\u209b\n        OSTCBCur\u2032\u2192OSTCBDly =\u2091 timeout\u2032;\u209b\n        OS_EventTaskWait(\u00adpevent\u2032\u00ad);\u209b\n        EXIT_CRITICAL;\u209b\n        OS_Sched(\u00ad);\u209b\n        ENTER_CRITICAL;\u209b\n        message\u2032 =\u2091 OSTCBCur\u2032\u2192OSTCBMsg;\u209b                                 \n        If (message\u2032 !=\u2091 NULL){\n          \n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_NO_ERR\n        };\u209b\n        EXIT_CRITICAL;\u209b\n        RETURN \u2032OS_TIMEOUT\n  }\u00b7 .\n\n\n \nDefinition OSQGetMsg_impl := \n Void\u2217 \u00b7OSQGetMsg\u00b7(\u231e \u231f)\u00b7\u00b7{\n         \u231e\n           message @ Void\u2217\n         \u231f;\n\n         ENTER_CRITICAL;\u209b\n         message\u2032 =\u2091  OSTCBCur\u2032\u2192OSTCBMsg;\u209b\n         OSTCBCur\u2032\u2192OSTCBMsg =\u2091 NULL;\u209b\n         EXIT_CRITICAL;\u209b\n         RETURN message\u2032 \n }\u00b7 . \n\n\nDefinition OSQPost_impl :=\n Int8u \u00b7OSQPost\u00b7(\u231epevent @ OS_EVENT\u2217 ;  message @ Void\u2217\u231f)\u00b7\u00b7{\n        \u231e\n         pq @ OS_Q\u2217;\n         legal @ Int8u;\n         x  @ Int8u\n        \u231f;\n        \n        If (pevent\u2032 ==\u2091 NULL){\n           RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        If (message\u2032 ==\u2091 NULL){\n          RETURN  \u2032OS_ERR_POST_NULL_PTR\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN  \u2032OS_ERR_PEVENT_NULL\n          };\u209b\n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_Q){\n            EXIT_CRITICAL;\u209b\n            RETURN  \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        If (pevent\u2032\u2192OSEventGrp !=\u2091 \u20320) {\n            x\u2032 =\u2091 \u2032OS_STAT_Q;\u209b \n            OS_EventTaskRdy(\u00adpevent\u2032, message\u2032, x\u2032\u00ad);\u209b\n            EXIT_CRITICAL;\u209b\n            OS_Sched(\u00ad);\u209b\n            RETURN \u2032OS_NO_ERR \n        };\u209b\n        pq\u2032 =\u2091 pevent\u2032\u2192OSEventPtr;\u209b\n        If (pq\u2032\u2192OSQEntries \u2265 pq\u2032\u2192OSQSize) {\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_Q_FULL\n        };\u209b\n        \u2217(pq\u2032\u2192OSQIn) =\u2091 message\u2032;\u209b\n        ++ (pq\u2032\u2192OSQIn);\u209b\n        ++ (pq\u2032\u2192OSQEntries);\u209b\n        If (pq\u2032\u2192OSQIn ==\u2091 pq\u2032\u2192OSQEnd) {\n            pq\u2032\u2192OSQIn =\u2091 pq\u2032\u2192OSQStart\n        };\u209b\n        EXIT_CRITICAL;\u209b\n        RETURN \u2032OS_NO_ERR \n }\u00b7 . \n\nClose Scope code_scope.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/code/os_q.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.341582512843634, "lm_q1q2_score": 0.18410724290305408}}
{"text": "Require 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 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.\n(* Require Import MemoryFacts. *)\nRequire Import TView.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Local.\nRequire Import Global.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import Cover.\nRequire Import MemoryProps.\nRequire Import LowerMemory.\n(* Require Import FulfillStep. *)\n(* Require Import ReorderStepPromise. *)\n(* Require Import Pred. *)\n(* Require Import Trace. *)\n\nRequire Import LowerMemory.\n\nRequire Import Delayed.\nRequire Import LowerStep.\nRequire Import Owned.\n\nSet Implicit Arguments.\n\n\nSection DStep.\n  Variable lang: language.\n\n  (** delayed steps *)\n\n  Variant dstep (e: ThreadEvent.t) (e1 e4: Thread.t lang): Prop :=\n  | dstep_intro\n      e2 e3\n      (PROMISES: rtc (@Thread.internal_step _) e1 e2)\n      (LOWERS: rtc (tau lower_step) e2 e3)\n      (STEP_RELEASE: Thread.step e e3 e4)\n      (EVENT_RELEASE: release_event e)\n  .\n\n  Variant dsteps: forall (e: MachineEvent.t) (e1 e2: Thread.t lang), Prop :=\n  | dsteps_promises\n      e1 e2 e3\n      (DSTEPS: rtc (tau dstep) e1 e2)\n      (PROMISES: rtc (@Thread.internal_step _) e2 e3):\n    dsteps MachineEvent.silent e1 e3\n  | dsteps_step\n      e te e1 e2 e3\n      (DSTEPS: rtc (tau dstep) e1 e2)\n      (DSTEP: dstep te e2 e3)\n      (EVENT: e = ThreadEvent.get_machine_event te):\n    dsteps e e1 e3\n  .\n\n  Definition delayed_consistent (e1: Thread.t lang): Prop :=\n    exists e e2,\n      (<<DSTEPS: dsteps\n                   e (Thread.mk _ (Thread.state e1) (Thread.local e1) (Global.cap_of (Thread.global e1))) e2>>) /\\\n      ((<<FAILURE: e = MachineEvent.failure>>) \\/\n       (exists e3,\n           (<<SILENT: e = MachineEvent.silent>>) /\\\n           (<<STEPS: rtc (tau lower_step) e2 e3>>) /\\\n           (<<PROMISES: Local.promises (Thread.local e3) = BoolMap.bot>>))).\n\n  Lemma dstep_future\n        e e1 e2\n        (STEP: dstep e e1 e2)\n        (LC_WF1: Local.wf e1.(Thread.local) e1.(Thread.global))\n        (GL_WF1: Global.wf e1.(Thread.global)):\n    (<<LC_WF2: Local.wf e2.(Thread.local) e2.(Thread.global)>>) /\\\n      (<<GL_WF2: Global.wf e2.(Thread.global)>>) /\\\n      (<<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>>) /\\\n      (<<GL_FUTURE: Global.future e1.(Thread.global) e2.(Thread.global)>>).\n  Proof.\n    inv STEP.\n    hexploit Thread.rtc_internal_step_future; eauto. i. des.\n    hexploit lower_steps_future; eauto. i. des.\n    hexploit Thread.step_future; eauto. i. des. splits; auto.\n    { etrans; eauto. etrans; eauto. }\n    { etrans; eauto. etrans; eauto. }\n  Qed.\n\n  Lemma rtc_dstep_future\n        e1 e2\n        (STEPS: rtc (tau dstep) e1 e2)\n        (LC_WF1: Local.wf e1.(Thread.local) e1.(Thread.global))\n        (GL_WF1: Global.wf e1.(Thread.global)):\n    (<<LC_WF2: Local.wf e2.(Thread.local) e2.(Thread.global)>>) /\\\n      (<<GL_WF2: Global.wf e2.(Thread.global)>>) /\\\n      (<<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>>) /\\\n      (<<GL_FUTURE: Global.future e1.(Thread.global) e2.(Thread.global)>>).\n  Proof.\n    induction STEPS.\n    { splits; auto; try by refl. }\n    { inv H. hexploit dstep_future; eauto. i. des.\n      hexploit IHSTEPS; eauto. i. des. splits; auto; try by (etrans; eauto). }\n  Qed.\n\n  Lemma dsteps_future\n        e e1 e2\n        (STEPS: dsteps e e1 e2)\n        (LC_WF1: Local.wf e1.(Thread.local) e1.(Thread.global))\n        (GL_WF1: Global.wf e1.(Thread.global)):\n    (<<LC_WF2: Local.wf e2.(Thread.local) e2.(Thread.global)>>) /\\\n      (<<GL_WF2: Global.wf e2.(Thread.global)>>) /\\\n      (<<TVIEW_FUTURE: TView.le e1.(Thread.local).(Local.tview) e2.(Thread.local).(Local.tview)>>) /\\\n      (<<GL_FUTURE: Global.future e1.(Thread.global) e2.(Thread.global)>>).\n  Proof.\n    inv STEPS.\n    { hexploit rtc_dstep_future; eauto. i. des.\n      hexploit Thread.rtc_internal_step_future; eauto. i. des.\n      esplits; eauto; try by (etrans; eauto).\n    }\n    { hexploit rtc_dstep_future; eauto. i. des.\n      hexploit dstep_future; eauto. i. des.\n      esplits; eauto; try by (etrans; eauto).\n    }\n  Qed.\n\n  Lemma dstep_rtc_all_step\n        e e1 e2\n        (STEP: dstep e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    etrans.\n    { eapply rtc_implies; try eapply PROMISES.\n      i. inv H. econs; eauto.\n    }\n    etrans.\n    { instantiate (1:=e3). clear - LOWERS. induction LOWERS; auto.\n      transitivity y; auto.\n      inv H. eapply lower_step_step; eauto.\n    }\n    econs 2; eauto. econs; eauto.\n  Qed.\n\n  Lemma dstep_rtc_tau_step\n        e e1 e2\n        (STEP: dstep e e1 e2)\n        (SILENT: ThreadEvent.get_machine_event e = MachineEvent.silent):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    etrans.\n    { eapply rtc_implies; try eapply PROMISES.\n      i. inv H. econs; eauto. inv LOCAL; ss.\n    }\n    etrans.\n    { instantiate (1:=e3). clear - LOWERS. induction LOWERS; auto.\n      transitivity y; auto.\n      eapply tau_lower_step_tau_step; eauto.\n    }\n    econs 2; eauto. econs; eauto.\n  Qed.\n\n  Lemma rtc_dstep_rtc_tau_step\n        e1 e2\n        (STEP: rtc (tau dstep) e1 e2):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    induction STEP; eauto. inv H.\n    exploit dstep_rtc_tau_step; eauto. i.\n    etrans; eauto.\n  Qed.\n\n  Lemma dsteps_rtc_all_step\n        e e1 e2\n        (STEP: dsteps e e1 e2):\n    rtc (@Thread.all_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      etrans.\n      + eapply rtc_implies; try eapply x0.\n        i. inv H. econs. eauto.\n      + eapply rtc_implies; try eapply PROMISES.\n        i. inv H. econs; eauto.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit dstep_rtc_all_step; eauto. i.\n      etrans; [|eauto].\n      eapply rtc_implies; try eapply x0.\n      i. inv H. econs. eauto.\n  Qed.\n\n  Lemma dsteps_rtc_tau_step\n        e e1 e2\n        (STEP: dsteps e e1 e2)\n        (SILENT: e = MachineEvent.silent):\n    rtc (@Thread.tau_step lang) e1 e2.\n  Proof.\n    inv STEP.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      etrans; eauto.\n      eapply rtc_implies; try eapply PROMISES.\n      i. inv H0. econs; eauto. inv LOCAL; ss.\n    - exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit dstep_rtc_tau_step; eauto. i.\n      etrans; eauto.\n  Qed.\n\n  Lemma dsteps_plus_step\n        e e1 e3\n        (STEP: dsteps e e1 e3):\n    e = MachineEvent.silent /\\ e1 = e3 \\/\n    exists e2 te,\n      (<<STEPS: rtc (@Thread.tau_step lang) e1 e2>>) /\\\n      (<<STEP: Thread.step te e2 e3>>) /\\\n      (<<EVENT: ThreadEvent.get_machine_event te = e>>).\n  Proof.\n    inv STEP.\n    { exploit rtc_dstep_rtc_tau_step; eauto. i.\n      exploit rtc_implies; try eapply PROMISES.\n      { i. instantiate (1 := @Thread.tau_step lang).\n        inv H. econs; eauto. inv LOCAL; ss.\n      }\n      i. rewrite x1 in x0. clear e2 DSTEPS PROMISES x1.\n      exploit rtc_tail; try exact x0. i. des; eauto.\n      right. inv x2. esplits; eauto.\n    }\n    { exploit rtc_dstep_rtc_tau_step; eauto. i.\n      inv DSTEP.\n      exploit rtc_implies; try eapply PROMISES; i.\n      { i. instantiate (1 := @Thread.tau_step lang).\n        inv H. econs; eauto. inv LOCAL; ss.\n      }\n      exploit rtc_implies; try eapply LOWERS; i.\n      { i. instantiate (1 := rtc (@Thread.tau_step lang)).\n        eapply tau_lower_step_tau_step; eauto.\n      }\n      eapply rtc_join in x2.\n      rewrite x2 in x1. rewrite x1 in x0.\n      clear x1 x2 DSTEPS PROMISES LOWERS.\n      right. esplits; eauto.\n    }\n  Qed.\n\n  Lemma interal_steps_lower_steps_dstep_dstep th0 th1 th2 th3 e\n        (INTERNALS: rtc (@Thread.internal_step _) th0 th1)\n        (LOWERS: rtc (tau lower_step) th1 th2)\n        (STEP: dstep e th2 th3)\n        (LOCAL: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (GLOBAL: Global.wf th0.(Thread.global))\n    :\n    dstep e th0 th3.\n  Proof.\n    hexploit Thread.rtc_internal_step_future; eauto. i. des.\n    inv STEP. hexploit reorder_lower_steps_internal_steps; eauto.\n    i. des. econs.\n    { etrans; eauto. }\n    { etrans; eauto. }\n    { eauto. }\n    { eauto. }\n  Qed.\n\n  Lemma interal_steps_lower_steps_dsteps_dsteps th0 th1 th2 th3 e\n        (INTERNALS: rtc (@Thread.internal_step _) th0 th1)\n        (LOWERS: rtc (tau lower_step) th1 th2)\n        (STEP: dsteps e th2 th3)\n        (LOCAL: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (GLOBAL: Global.wf th0.(Thread.global))\n        (EVENT: e <> MachineEvent.silent)\n    :\n    dsteps e th0 th3.\n  Proof.\n    inv STEP; ss. inv DSTEPS.\n    { econs 2.\n      { refl. }\n      { eapply interal_steps_lower_steps_dstep_dstep; eauto. }\n      { auto. }\n    }\n    { econs 2.\n      { econs 2; [|eauto]. inv H. econs; [|eauto].\n        eapply interal_steps_lower_steps_dstep_dstep; eauto.\n      }\n      { eauto. }\n      { auto. }\n    }\n  Qed.\n\n  Lemma failure_dfailure th0\n        (FAILURE: Thread.steps_failure th0)\n        (LOCAL: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (GLOBAL: Global.wf th0.(Thread.global))\n    :\n    exists th1, (<<FAILURE: dsteps MachineEvent.failure th0 th1>>).\n  Proof.\n    inv FAILURE. revert e th3 STEP_FAILURE EVENT_FAILURE LOCAL GLOBAL.\n    induction STEPS; i.\n    { esplits. econs.\n      { refl. }\n      { econs.\n        { refl. }\n        { refl. }\n        { eauto. }\n        destruct e; ss.\n      }\n      { auto. }\n    }\n    inv H. hexploit Thread.step_future; eauto. i. des.\n    hexploit IHSTEPS; eauto. i. des.\n    destruct (classic (release_event e0)).\n    { esplits. inv FAILURE; ss. econs; [|eauto|eauto].\n      econs 2; [|eauto]. econs; [|eapply EVENT]. econs.\n      { refl. }\n      { refl. }\n      { eauto. }\n      { eauto. }\n    }\n    hexploit split_step; eauto. i. des.\n    { esplits. eapply interal_steps_lower_steps_dsteps_dsteps; eauto. ss. }\n    { esplits. econs 2.\n      { refl. }\n      econs.\n      { refl. }\n      { refl. }\n      { eauto. }\n      { destruct e_race; ss. }\n      { eauto. }\n    }\n  Qed.\n\n  Lemma tau_dsteps_dsteps_dsteps th0 th1 th2 e\n        (STEP0: dsteps MachineEvent.silent th0 th1)\n        (STEP1: dsteps e th1 th2)\n    :\n    dsteps e th0 th2.\n  Proof.\n    inv STEP0; inv STEP1.\n    { inv DSTEPS0.\n      { econs 1; [eauto|]. etrans; eauto. }\n      { inv H. inv TSTEP. econs 1; [|eauto].\n        etrans; eauto. econs 2; [|eauto].\n        econs; [|eauto]. econs.\n        { etrans; eauto. }\n        { eauto. }\n        { eauto. }\n        { eauto. }\n      }\n    }\n    { inv DSTEPS0.\n      { inv DSTEP. econs 2; [eauto| |eauto].\n        econs; [|eauto|eauto|eauto]. etrans; eauto.\n      }\n      { inv H. inv TSTEP. econs 2; [|eauto|eauto].\n        etrans; eauto. econs 2; [|eauto].\n        econs; eauto. econs; [|eauto|eauto|eauto]. etrans; eauto.\n      }\n    }\n    { econs 1; [|eapply PROMISES]. etrans; eauto. }\n    { econs 2; [|eapply DSTEP0|]; auto. etrans; eauto. }\n  Qed.\n\n  Lemma rtc_tau_dstep_dsteps_dsteps th0 th1 th2 e\n        (STEP0: rtc (tau dstep) th0 th1)\n        (STEP1: dsteps e th1 th2)\n    :\n    dsteps e th0 th2.\n  Proof.\n    eapply tau_dsteps_dsteps_dsteps; [|eauto].\n    econs 1; eauto.\n  Qed.\n\n\n  (** steps to delayed steps *)\n\n  Variant delayed_thread (th_delayed th: Thread.t lang): Prop :=\n  | delayed_thread_intro\n      (DELAYED: delayed\n                  _\n                  (Thread.state th_delayed) (Thread.state th)\n                  (Thread.local th_delayed) (Thread.local th)\n                  (Thread.global th_delayed) (Thread.global th))\n  .\n\n\n  Lemma internal_step_strong_le\n        th1 th2\n        (STEP: @Thread.internal_step lang th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    Global.strong_le (Thread.global th1) (Thread.global th2).\n  Proof.\n    inv STEP. hexploit Local.internal_step_strong_le; eauto.\n    i. des. splits; auto.\n  Qed.\n\n  Lemma rtc_internal_step_strong_le\n        th1 th2\n        (STEPS: rtc (@Thread.internal_step lang) th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    Global.strong_le (Thread.global th1) (Thread.global th2).\n  Proof.\n    revert LC_WF1 GL_WF1. induction STEPS; i.\n    { refl. }\n    hexploit internal_step_strong_le; eauto. i.\n    hexploit Thread.internal_step_future; eauto. i. des.\n    etrans; eauto.\n  Qed.\n\n  Lemma lower_step_strong_le\n        e th1 th2\n        (STEP: lower_step e th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    (<<LE: Global.strong_le (Thread.global th1) (Thread.global th2)>>) \\/\n      exists e_race th2',\n        (<<STEP: @Thread.step lang e_race th1 th2'>>) /\\\n          (<<RELEASE: release_event e_race>>) /\\\n          (<<EVENT: ThreadEvent.get_program_event e_race = ThreadEvent.get_program_event e>>) /\\\n          (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>).\n  Proof.\n    inv STEP. des; subst.\n    { inv STEP0. hexploit Local.program_step_strong_le; eauto. i. des; auto.\n      right. esplits.\n      { econs 2; [|eauto]; eauto. rewrite EVENT. eauto. }\n      { destruct e_race; ss. }\n      { eauto. }\n      { auto. }\n    }\n    { inv STEP; [|inv LOCAL].\n      hexploit Local.internal_step_strong_le; eauto.\n      i. des. splits; auto.\n      inv STEP0. hexploit Local.program_step_strong_le; eauto. i. des.\n      { left. etrans; eauto. }\n      right. inv LOCAL. inv LOCAL1. ss. inv CANCEL.\n      inv STEP; ss. inv LOCAL. clarify. esplits.\n      { econs 2; cycle 1.\n        { eapply Local.program_step_racy_write. econs; eauto.\n          instantiate (1:=Ordering.na). instantiate (1:=to0). instantiate (1:=loc).\n          inv RACE0.\n          { econs 1; eauto. }\n          { econs 2; eauto. erewrite Memory.remove_o in GET; eauto.\n            des_ifs. eauto.\n          }\n        }\n        { eauto. }\n      }\n      { ss. }\n      { eauto. }\n      { eauto. }\n    }\n  Qed.\n\n  Lemma rtc_tau_lower_step_strong_le\n        th1 th2\n        (STEPS: rtc (tau (@lower_step lang)) th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    (<<LE: Global.strong_le (Thread.global th1) (Thread.global th2)>>) \\/\n      exists e_race th1' th2',\n        (<<STEPS: rtc (tau (@lower_step lang)) th1 th1'>>) /\\\n          (<<STEP: @Thread.step lang e_race th1' th2'>>) /\\\n          (<<RELEASE: release_event e_race>>) /\\\n          (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>).\n  Proof.\n    revert LC_WF1 GL_WF1. induction STEPS; i.\n    { left. r. refl. }\n    { inv H. hexploit lower_step_strong_le; eauto. i. des.\n      2:{ right. esplits; eauto. }\n      hexploit lower_step_future; eauto. i. des.\n      hexploit IHSTEPS; eauto. i. des.\n      { left. r. etrans; eauto. }\n      { right. esplits.\n        { econs 2; eauto. }\n        { eauto. }\n        { eauto. }\n        { eauto. }\n      }\n    }\n  Qed.\n\n  Lemma dstep_strong_le\n        th1 th2 e\n        (STEP: dstep e th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    (<<LE: Global.strong_le (Thread.global th1) (Thread.global th2)>>) \\/\n      exists e_race th2',\n        (<<STEP: dstep e_race th1 th2'>>) /\\\n          (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>).\n  Proof.\n    inv STEP.\n    hexploit rtc_internal_step_strong_le; eauto. i. des.\n    hexploit Thread.rtc_internal_step_future; eauto. i. des.\n    hexploit rtc_tau_lower_step_strong_le; eauto. i. des; cycle 1.\n    { right. esplits; [..|eauto]. econs; eauto. }\n    hexploit lower_steps_future; eauto. i. des.\n    hexploit Thread.step_strong_le; eauto. i. des.\n    { left. r. etrans; eauto. etrans; eauto. }\n    { right. esplits; eauto. econs; eauto. destruct e_race; ss. }\n  Qed.\n\n  Lemma rtc_tau_dstep_strong_le\n        th1 th2\n        (STEPS: rtc (tau dstep) th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    (<<LE: Global.strong_le (Thread.global th1) (Thread.global th2)>>) \\/\n      exists e_race th1' th2',\n        (<<STEPS: rtc (tau dstep) th1 th1'>>) /\\\n          (<<STEP: dstep e_race th1' th2'>>) /\\\n          (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>).\n  Proof.\n    revert LC_WF1 GL_WF1. induction STEPS; i.\n    { left. r. refl. }\n    inv H. hexploit dstep_strong_le; eauto. i. des; cycle 1.\n    { right. esplits; eauto. }\n    hexploit dstep_future; eauto. i. des.\n    hexploit IHSTEPS; eauto. i. des.\n    { left. r. etrans; eauto. }\n    { right. esplits; [..|eauto|eauto]. econs 2; eauto. }\n  Qed.\n\n  Lemma dsteps_strong_le\n        th1 th2 e\n        (STEPS: dsteps e th1 th2)\n        (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n        (GL_WF1: Global.wf (Thread.global th1)):\n    (<<LE: Global.strong_le (Thread.global th1) (Thread.global th2)>>) \\/\n      exists th2',\n          (<<STEPS: dsteps MachineEvent.failure th1 th2'>>).\n  Proof.\n    inv STEPS.\n    { hexploit rtc_tau_dstep_strong_le; eauto. i. des.\n      { hexploit rtc_dstep_future; eauto. i. des.\n        hexploit rtc_internal_step_strong_le; eauto.\n        i. left. r. etrans; eauto.\n      }\n      { right. esplits. eapply rtc_tau_dstep_dsteps_dsteps.\n        { eauto. }\n        { econs 2; eauto. }\n      }\n    }\n    { hexploit rtc_tau_dstep_strong_le; eauto. i. des.\n      { hexploit rtc_dstep_future; eauto. i. des.\n        hexploit dstep_strong_le; eauto.\n        i. des.\n        { left. r. etrans; eauto. }\n        { right. esplits. econs 2; eauto. }\n      }\n      { right. esplits. econs 2; eauto. }\n    }\n  Qed.\n\n  Lemma dsteps_promises_minus\n        e th1 th2\n        (STEP: dsteps 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    eapply Thread.rtc_all_step_promises_minus.\n    eapply dsteps_rtc_all_step; eauto.\n  Qed.\n\n  Lemma delayed_thread_delayed_global th_src0 th_tgt0\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (LOCALSRC0: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT0: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC0: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT0: Global.wf th_tgt0.(Thread.global))\n    :\n    delayed_global_private th_src0.(Thread.local) th_tgt0.(Thread.local) th_src0.(Thread.global) th_tgt0.(Thread.global).\n  Proof.\n    inv DELAYED. hexploit delayed_sync; eauto. i. des.\n    eapply lower_steps_delayed_preserve; eauto.\n  Qed.\n\n  Lemma delayed_thread_step th_src0 th_tgt0 th_tgt1 e\n        (STEP: Thread.step e th_tgt0 th_tgt1)\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (CONSISTENT: ThreadEvent.get_machine_event e <> MachineEvent.failure -> rtc_consistent th_tgt1)\n    :\n    exists th_src1,\n      ((<<STEP: dsteps (ThreadEvent.get_machine_event e) th_src0 th_src1>>) /\\\n         (<<DELAYED: delayed_thread th_src1 th_tgt1>>) /\\\n         (<<GLOBAL: delayed_global_public th_src1.(Thread.global) th_tgt1.(Thread.global)>>) /\\\n         (<<FUTURESRC: owned_future_global_promises\n                         (BoolMap.minus th_src0.(Thread.global).(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         th_src0.(Thread.global) th_src1.(Thread.global)>>) /\\\n         (<<FUTURETGT: owned_future_global_promises\n                         (BoolMap.minus th_src0.(Thread.global).(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         th_tgt0.(Thread.global) th_tgt1.(Thread.global)>>)) \\/\n        (<<FAILURE: dsteps MachineEvent.failure th_src0 th_src1>>)\n  .\n  Proof.\n    inv DELAYED. destruct th_src0, th_tgt0, th_tgt1; ss.\n    destruct (classic (release_event e)).\n    { hexploit delayed_step_release; eauto. i. des.\n      { esplits. left. esplits.\n        { econs 2; [refl|..|].\n          { econs; eauto. }\n          { auto. }\n        }\n        { econs; eauto. }\n        { eapply delayed_global_private_to_public; eauto. }\n        { eauto. }\n        { eauto. }\n      }\n      { hexploit failure_dfailure; eauto. i. des.\n        esplits. right. eauto.\n      }\n    }\n    { hexploit delayed_step_non_release; eauto. i. des.\n      { esplits. left. esplits.\n        { rewrite SILENT. econs 1; [refl|..]. eauto. }\n        { econs; eauto. }\n        { eapply delayed_global_private_to_public; eauto. }\n        { eauto. }\n        { eauto. }\n      }\n      { hexploit failure_dfailure; eauto. i. des.\n        esplits. right. eauto.\n      }\n    }\n  Qed.\n\n  Lemma delayed_thread_bot th_src0 th_tgt0\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (TERMINAL: Local.promises th_tgt0.(Thread.local) = BoolMap.bot)\n    :\n    exists th_src1,\n      ((<<STEPS: rtc (tau lower_step) th_src0 th_src1>>) /\\\n         (<<GLOBAL: delayed_global_public th_src1.(Thread.global) th_tgt0.(Thread.global)>>) /\\\n         (<<FUTURESRC: owned_future_global_promises\n                         (BoolMap.minus th_src0.(Thread.global).(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         th_src0.(Thread.global) th_src1.(Thread.global)>>) /\\\n         (<<STATE: th_src1.(Thread.state) = th_tgt0.(Thread.state)>>) /\\\n         (<<TERMINAL: Local.promises th_src1.(Thread.local) = BoolMap.bot>>)) \\/\n        (<<FAILURE: dsteps MachineEvent.failure th_src0 th_src1>>)\n  .\n  Proof.\n    inv DELAYED. destruct th_src0, th_tgt0; ss.\n    hexploit delayed_sync; eauto. i. des.\n    esplits. left. esplits; eauto.\n    { eapply delayed_global_private_to_public; eauto. }\n    { eapply SimLocal.sim_local_is_terminal; eauto. }\n  Qed.\n\n  Lemma delayed_thread_steps th_src0 th_tgt0 th_tgt1\n        (STEPS: rtc (@Thread.tau_step _) th_tgt0 th_tgt1)\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (CONSISTENT: rtc_consistent th_tgt1)\n      :\n    exists th_src1,\n      ((<<STEP: dsteps MachineEvent.silent th_src0 th_src1>>) /\\\n         (<<DELAYED: delayed_thread th_src1 th_tgt1>>) /\\\n         (<<GLOBAL: delayed_global_public th_src1.(Thread.global) th_tgt1.(Thread.global)>>) /\\\n         (<<FUTURESRC: owned_future_global_promises\n                         (BoolMap.minus th_src0.(Thread.global).(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         th_src0.(Thread.global) th_src1.(Thread.global)>>) /\\\n         (<<FUTURETGT: owned_future_global_promises\n                         (BoolMap.minus th_src0.(Thread.global).(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         th_tgt0.(Thread.global) th_tgt1.(Thread.global)>>)) \\/\n        (<<FAILURE: dsteps MachineEvent.failure th_src0 th_src1>>)\n  .\n  Proof.\n    revert th_src0 DELAYED LOCALSRC LOCALTGT GLOBALSRC GLOBALTGT CONSISTENT.\n    induction STEPS; i.\n    { esplits. left. esplits; eauto.\n      { econs 1; eauto. }\n      { eapply delayed_global_private_to_public; eauto.\n        eapply delayed_thread_delayed_global; eauto. }\n      { refl. }\n      { refl. }\n    }\n    inv H. hexploit Thread.step_future; eauto. i. des.\n    hexploit Thread.step_promises_minus; eauto. i.\n    hexploit delayed_thread_step; eauto.\n    { i. eapply tau_steps_rtc_consistent; eauto. }\n    i. des; cycle 1.\n    { esplits. right. esplits; eauto. }\n    hexploit dsteps_future; eauto. i. des.\n    hexploit dsteps_promises_minus; eauto. i.\n    rewrite EVENT in *.\n    hexploit IHSTEPS; eauto. i. des; cycle 1.\n    { esplits. right. eapply tau_dsteps_dsteps_dsteps; eauto. }\n    esplits. left. esplits.\n    { eapply tau_dsteps_dsteps_dsteps; eauto. }\n    { eauto. }\n    { eauto. }\n    { etrans; eauto. rewrite H0. auto. }\n    { etrans; eauto. rewrite H0. auto. }\n  Qed.\n\n  Lemma delayed_thread_future th_src0 th_tgt0 gl_src1 gl_tgt1\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (GLOBAL: delayed_global_public gl_src1 gl_tgt1)\n        (LOCALSRC0: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT0: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC0: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT0: Global.wf th_tgt0.(Thread.global))\n        (LOCALSRC1: Local.wf th_src0.(Thread.local) gl_src1)\n        (LOCALTGT1: Local.wf th_tgt0.(Thread.local) gl_tgt1)\n        (GLOBALSRC1: Global.wf gl_src1)\n        (GLOBALTGT1: Global.wf gl_tgt1)\n        (FUTURESRC: Global.strong_le th_src0.(Thread.global) gl_src1)\n        (FUTURETGT: Global.le th_tgt0.(Thread.global) gl_tgt1)\n        (OWNEDSRC: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_src0.(Thread.global) gl_src1)\n        (OWNEDTGT: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_tgt0.(Thread.global) gl_tgt1)\n    :\n    (<<DELAYED: delayed_thread (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) (Thread.mk _ th_tgt0.(Thread.state) th_tgt0.(Thread.local) gl_tgt1)>>) \\/\n      exists th_src1, (<<FAILURE: dsteps MachineEvent.failure (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) th_src1>>).\n  Proof.\n    hexploit delayed_thread_delayed_global; eauto. i.\n    inv DELAYED. hexploit delayed_future; eauto. i. des; cycle 1.\n    { hexploit failure_dfailure; eauto. }\n    left. r. econs; eauto.\n  Qed.\n\n  Lemma delayed_thread_consistent th_src0 th_tgt0\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (CONSISTENT: Thread.consistent th_tgt0)\n    :\n    delayed_consistent th_src0.\n  Proof.\n    hexploit delayed_global_public_cap; eauto.\n    { eapply delayed_global_private_to_public.\n      eapply delayed_thread_delayed_global; eauto.\n    }\n    intros CAP.\n    pose proof (Local.cap_wf LOCALSRC) as LOCALSRC1.\n    pose proof (Local.cap_wf LOCALTGT) as LOCALTGT1.\n    pose proof (Global.cap_wf GLOBALSRC) as GLOBALSRC1.\n    pose proof (Global.cap_wf GLOBALTGT) as GLOBALTGT1.\n    hexploit delayed_thread_future; eauto.\n    { eapply Global.cap_strong_le; eauto. }\n    { eapply Global.cap_le; eauto. }\n    { eapply cap_owned_future_global_promises; eauto. }\n    { eapply cap_owned_future_global_promises; eauto. }\n    i. des; cycle 1.\n    { r. esplits; eauto. }\n    inv CONSISTENT.\n    { inv FAILURE.\n      hexploit Thread.rtc_tau_step_future; eauto. i. des.\n      hexploit delayed_thread_steps; eauto.\n      { eapply failure_rtc_consistent. econs; eauto. }\n      i. des; ss; cycle 1.\n      { r. esplits; eauto. }\n      hexploit dsteps_future; eauto. i. des; s.\n      hexploit delayed_thread_step; eauto.\n      { i. ss. }\n      i. des.\n      { r. esplits.\n        { eapply tau_dsteps_dsteps_dsteps; eauto. }\n        { eauto. }\n      }\n      { r. esplits.\n        { eapply tau_dsteps_dsteps_dsteps; eauto. }\n        { eauto. }\n      }\n    }\n    hexploit Thread.rtc_tau_step_future; eauto. i. des.\n    hexploit delayed_thread_steps; eauto.\n    { eapply bot_rtc_consistent; eauto. }\n    i. des; cycle 1; ss.\n    { r. esplits; eauto. }\n    hexploit dsteps_future; eauto. i. des; ss.\n    hexploit delayed_thread_bot; eauto. i. des.\n    { r. esplits.\n      { eauto. }\n      { right. esplit; eauto. }\n    }\n    { r. esplits.\n      { eapply tau_dsteps_dsteps_dsteps; eauto. }\n      { eauto. }\n    }\n  Qed.\n\n  Lemma delayed_thread_steps_full th_src0 th_tgt0\n        gl_src1 gl_tgt1 th_tgt1 th_tgt2 e_tgt\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (STEPS: rtc (@Thread.tau_step _) (Thread.mk _ th_tgt0.(Thread.state) th_tgt0.(Thread.local) gl_tgt1) th_tgt1)\n        (STEP1: Thread.step e_tgt th_tgt1 th_tgt2)\n        (GLOBAL: delayed_global_public gl_src1 gl_tgt1)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (LOCALSRC1: Local.wf th_src0.(Thread.local) gl_src1)\n        (LOCALTGT1: Local.wf th_tgt0.(Thread.local) gl_tgt1)\n        (GLOBALSRC1: Global.wf gl_src1)\n        (GLOBALTGT1: Global.wf gl_tgt1)\n        (FUTURESRC: Global.strong_le th_src0.(Thread.global) gl_src1)\n        (FUTURETGT: Global.le th_tgt0.(Thread.global) gl_tgt1)\n        (OWNEDSRC: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_src0.(Thread.global) gl_src1)\n        (OWNEDTGT: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_tgt0.(Thread.global) gl_tgt1)\n        (CONSISTENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure -> Thread.consistent th_tgt2)\n      :\n    exists th_src1,\n      ((<<STEP: dsteps (ThreadEvent.get_machine_event e_tgt) (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) th_src1>>) /\\\n         (<<DELAYED: delayed_thread th_src1 th_tgt2>>) /\\\n         (<<GLOBAL: delayed_global_public th_src1.(Thread.global) th_tgt2.(Thread.global)>>) /\\\n         (<<CONSISTENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure -> delayed_consistent th_src1>>) /\\\n         (<<FUTURESRC: owned_future_global_promises\n                         (BoolMap.minus gl_src1.(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         gl_src1 th_src1.(Thread.global)>>) /\\\n         (<<FUTURETGT: owned_future_global_promises\n                         (BoolMap.minus gl_src1.(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         gl_tgt1 th_tgt2.(Thread.global)>>)) \\/\n        (<<FAILURE: dsteps MachineEvent.failure (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) th_src1>>)\n  .\n  Proof.\n    hexploit delayed_thread_future; eauto. i. des; cycle 1.\n    { esplits; eauto. }\n    hexploit Thread.rtc_tau_step_future; eauto. i. des.\n    hexploit Thread.step_future; eauto. i. des.\n    hexploit delayed_thread_steps; eauto.\n    { eapply tau_steps_rtc_consistent; eauto.\n      eapply step_rtc_consistent; eauto.\n      i. eapply consistent_rtc_consistent. eapply CONSISTENT.\n      rewrite H. ss.\n    }\n    i. des; eauto. hexploit dsteps_future; eauto. i. des.\n    hexploit dsteps_promises_minus; eauto. i. ss.\n    hexploit delayed_thread_step; eauto.\n    { i. eapply consistent_rtc_consistent. eapply CONSISTENT; auto. }\n    i. des; cycle 1.\n    { esplits. right. eapply tau_dsteps_dsteps_dsteps; eauto. }\n    { hexploit dsteps_future; eauto. i. des.\n      esplits. left. esplits.\n      { eapply tau_dsteps_dsteps_dsteps; eauto. }\n      { eauto. }\n      { eauto. }\n      { i. eapply delayed_thread_consistent; eauto. }\n      { etrans; eauto. rewrite H. auto. }\n      { etrans; eauto. rewrite H. auto. }\n    }\n  Qed.\n\n  Lemma delayed_thread_steps_terminal th_src0 th_tgt0\n        gl_src1 gl_tgt1\n        (DELAYED: delayed_thread th_src0 th_tgt0)\n        (TERMINAL: Local.is_terminal th_tgt0.(Thread.local))\n        (LANG: Language.is_terminal _ th_tgt0.(Thread.state))\n        (GLOBAL: delayed_global_public gl_src1 gl_tgt1)\n        (LOCALSRC: Local.wf th_src0.(Thread.local) th_src0.(Thread.global))\n        (LOCALTGT: Local.wf th_tgt0.(Thread.local) th_tgt0.(Thread.global))\n        (GLOBALSRC: Global.wf th_src0.(Thread.global))\n        (GLOBALTGT: Global.wf th_tgt0.(Thread.global))\n        (LOCALSRC1: Local.wf th_src0.(Thread.local) gl_src1)\n        (LOCALTGT1: Local.wf th_tgt0.(Thread.local) gl_tgt1)\n        (GLOBALSRC1: Global.wf gl_src1)\n        (GLOBALTGT1: Global.wf gl_tgt1)\n        (FUTURESRC: Global.strong_le th_src0.(Thread.global) gl_src1)\n        (FUTURETGT: Global.le th_tgt0.(Thread.global) gl_tgt1)\n        (OWNEDSRC: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_src0.(Thread.global) gl_src1)\n        (OWNEDTGT: owned_future_global_promises th_src0.(Thread.local).(Local.promises) th_tgt0.(Thread.global) gl_tgt1)\n    :\n    exists th_src1,\n      ((<<STEPS: rtc (tau lower_step) (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) th_src1>>) /\\\n         (<<GLOBAL: delayed_global_public th_src1.(Thread.global) gl_tgt1>>) /\\\n         (<<FUTURESRC: owned_future_global_promises\n                         (BoolMap.minus gl_src1.(Global.promises) th_src0.(Thread.local).(Local.promises))\n                         gl_src1 th_src1.(Thread.global)>>) /\\\n        (<<TERMINAL: Local.is_terminal th_src1.(Thread.local)>>) /\\\n        (<<LANG: Language.is_terminal _ th_src1.(Thread.state)>>)) \\/\n        (<<FAILURE: dsteps MachineEvent.failure (Thread.mk _ th_src0.(Thread.state) th_src0.(Thread.local) gl_src1) th_src1>>).\n  Proof.\n    hexploit delayed_thread_future; eauto. i. des; cycle 1.\n    { esplits; eauto. }\n    hexploit delayed_thread_bot; eauto.\n    { eapply TERMINAL. }\n    i. des; cycle 1.\n    { esplits; eauto. }\n    esplits. left. esplits; eauto.\n    { rewrite STATE. auto. }\n  Qed.\n\n  Lemma delayed_thread_init st:\n    delayed_thread (Thread.mk _ st Local.init Global.init) (Thread.mk _ st Local.init Global.init).\n  Proof.\n    econs; ss. r. esplits.\n    { refl. }\n    { refl. }\n    econs.\n    { refl. }\n    { refl. }\n    { ii. erewrite ! Memory.bot_get.\n      destruct (Memory.get loc to Memory.init) as [[]|]; econs. refl.\n    }\n  Qed.\n\n  Lemma delayed_global_public_init\n    :\n    delayed_global_public Global.init Global.init.\n  Proof.\n    econs.\n    { refl. }\n    { refl. }\n    { ii. destruct (Memory.get loc to Memory.init) as [[]|]; econs. refl. }\n  Qed.\n\n  Variant past_delayed_thread: Thread.t lang -> Thread.t lang -> Prop :=\n  | past_delayed_thread_intro\n      st_src lc_src st_tgt lc_tgt gl_src gl_tgt\n      gl_src0 gl_tgt0\n      (DELAYED:\n        delayed_thread (Thread.mk lang st_src lc_src gl_src0)\n                       (Thread.mk lang st_tgt lc_tgt gl_tgt0))\n      (FUTURESRC: Global.strong_le gl_src0 gl_src)\n      (FUTURETGT: Global.le gl_tgt0 gl_tgt)\n      (OWNEDSRC: owned_future_global_promises lc_src.(Local.promises) gl_src0 gl_src)\n      (OWNEDTGT: owned_future_global_promises lc_src.(Local.promises) gl_tgt0 gl_tgt)\n      (LOCALSRC: Local.wf lc_src gl_src0)\n      (LOCALTGT: Local.wf lc_tgt gl_tgt0)\n      (GLOBALSRC: Global.wf gl_src0)\n      (GLOBALTGT: Global.wf gl_tgt0)\n    :\n    past_delayed_thread (Thread.mk lang st_src lc_src gl_src)\n                        (Thread.mk lang st_tgt lc_tgt gl_tgt)\n  .\n\n  Lemma delayed_consistent_consistent\n        e\n        (CONSISTENT: delayed_consistent e):\n    (<<CONSISTENT: Thread.consistent e>>).\n  Proof.\n    rr in CONSISTENT. des.\n    { left.\n      exploit dsteps_plus_step; eauto. i. des; subst; ss.\n      econs; eauto.\n    }\n    { exploit dsteps_rtc_tau_step; eauto. i.\n      esplits; try exact PROMISES. econs 2; [|eauto].\n      etrans; eauto. eapply rtc_join.\n      eapply rtc_implies; try exact STEPS.\n      eapply tau_lower_step_tau_step.\n    }\n  Qed.\n\nEnd DStep.\n\n\nModule DConfiguration.\n  Variant step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n  | step_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      (DSTEPS: dsteps e (Thread.mk _ st1 lc1 (Configuration.global c1))\n                      (Thread.mk _ st2 lc2 gl2))\n      (CONSISTENT: e <> MachineEvent.failure ->\n                   delayed_consistent (Thread.mk _ st2 lc2 gl2)):\n      step e tid c1\n           (Configuration.mk (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1)) gl2)\n  .\n\n  Variant terminal_step: forall (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n  | terminal_step_intro\n      tid c1 lang st1 lc1 st2 lc2 gl2\n      (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n      (STEPS: rtc (tau lower_step)\n                  (Thread.mk _ st1 lc1 (Configuration.global c1))\n                  (Thread.mk _ st2 lc2 gl2))\n      (TERMINAL: Language.is_terminal _ st2)\n      (PROMISES: Local.is_terminal lc2):\n      terminal_step tid c1\n                    (Configuration.mk\n                       (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1))\n                       gl2)\n  .\n\n  Inductive terminal_steps: forall (tids: list Ident.t) (c1 c2: Configuration.t), Prop :=\n  | terminal_steps_nil\n      c\n      (TERMINAL: Configuration.is_terminal c):\n      terminal_steps [] c c\n  | terminal_steps_failure\n      tid c1 c2 tids c3\n      (NOTIN: ~ List.In tid tids)\n      (STEP: step MachineEvent.failure tid c1 c2):\n      terminal_steps (tid :: tids) c1 c3\n  | terminal_steps_cons\n      tid c1 c2 tids c3\n      (NOTIN: ~ List.In tid tids)\n      (STEP: terminal_step tid c1 c2)\n      (STEPS: terminal_steps tids c2 c3):\n      terminal_steps (tid :: tids) c1 c3\n  .\n\n  Lemma step_step\n        e tid c1 c2\n        (STEP: step e tid c1 c2):\n    Configuration.opt_step e tid c1 c2.\n  Proof.\n    inv STEP.\n    exploit dsteps_plus_step; eauto. i. des.\n    - inv x1. destruct c1 as [threads mem]. ss.\n      rewrite IdentMap.gsident; eauto.\n    - subst. econs 2. econs; eauto. i.\n      hexploit CONSISTENT; eauto. i.\n      eapply delayed_consistent_consistent; eauto.\n  Qed.\n\n  Lemma terminal_step_step\n        tid c1 c2\n        (STEP: terminal_step tid c1 c2):\n    Configuration.opt_step MachineEvent.silent tid c1 c2.\n  Proof.\n    inv STEP.\n    exploit rtc_tail; eauto. i. des.\n    - inv x1. inv TSTEP. destruct a2. ss.\n      rewrite <- EVENT. des; clarify.\n      { econs 2. econs; [eauto|..].\n        + eapply rtc_join.\n          eapply rtc_implies; try apply x0.\n          eapply tau_lower_step_tau_step; eauto.\n        + inv STEP. econs 2; eauto.\n        + ii. econs 2; eauto. ss. inv PROMISES. auto.\n      }\n      { econs 2. econs; [eauto|..].\n        + etrans.\n          { eapply rtc_join.\n            eapply rtc_implies; try apply x0.\n            eapply tau_lower_step_tau_step; eauto.\n          }\n          { econs 2; [|refl]. econs; eauto. }\n        + inv STEP. econs 2; eauto.\n        + ii. econs 2; eauto. ss. inv PROMISES. auto.\n      }\n    - inv x0. destruct c1 as [threads mem]. ss.\n      rewrite IdentMap.gsident; eauto.\n  Qed.\n\n  Lemma step_future c0 c1 e tid\n        (STEP: step e tid c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<WF2: Configuration.wf c1>>) /\\\n      (<<MEM_FUTURE: Global.future (Configuration.global c0) (Configuration.global c1)>>).\n  Proof.\n    inv WF. inv WF0. inv STEP; s.\n    exploit THREADS; ss; eauto. i.\n    hexploit dsteps_future; eauto. s. i. des.\n    eapply dsteps_rtc_all_step in DSTEPS.\n    splits; eauto. econs; ss. econs.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH1; eauto. i.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des. ss.\n        symmetry. auto.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH2; eauto. i. des.\n        exploit Thread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n      + eapply DISJOINT; [|eauto|eauto]. auto.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      exploit THREADS; try apply TH; eauto. i.\n      exploit Thread.rtc_all_step_disjoint; eauto. 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 Thread.rtc_all_step_promises_minus; try exact DSTEPS. 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 c0) 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 terminal_step_future c0 c1 tid\n        (STEP: terminal_step tid c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<WF2: Configuration.wf c1>>) /\\\n      (<<MEM_FUTURE: Global.future (Configuration.global c0) (Configuration.global c1)>>).\n  Proof.\n    inv WF. inv WF0. inv STEP; s.\n    exploit THREADS; ss; eauto. i.\n    exploit rtc_join.\n    { eapply rtc_implies; [|apply STEPS].\n      apply tau_lower_step_tau_step.\n    }\n    i. exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n    splits; eauto. econs; ss. econs.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH1; eauto. i.\n        exploit Thread.rtc_tau_step_disjoint; eauto. i. des. ss.\n        symmetry. auto.\n      + eapply inj_pair2 in H0. subst.\n        exploit THREADS; try apply TH2; eauto. i. des.\n        exploit Thread.rtc_tau_step_disjoint; eauto. i. des.\n        auto.\n      + eapply DISJOINT; [|eauto|eauto]. auto.\n    - i. erewrite IdentMap.gsspec in *. des_ifs.\n      exploit THREADS; try apply TH; eauto. i.\n      exploit Thread.rtc_tau_step_disjoint; eauto. 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 Thread.rtc_tau_step_promises_minus; try exact x1. s. i.\n        eapply equal_f in x2.\n        revert x2. unfold BoolMap.minus. rewrite GET, LGET. s. i.\n        destruct (Global.promises (Configuration.global c0) 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  Variant delayed_sl (gl_src gl_tgt: Global.t):\n    forall (sl_src sl_tgt: {lang: language & Language.state lang} * Local.t), Prop :=\n  | delayed_sl_intro\n      lang st_src lc_src st_tgt lc_tgt\n      (DELAYED:\n        past_delayed_thread (Thread.mk lang st_src lc_src gl_src)\n                       (Thread.mk lang st_tgt lc_tgt gl_tgt))\n    :\n    delayed_sl gl_src gl_tgt\n          (existT _ lang st_src, lc_src)\n          (existT _ lang st_tgt, lc_tgt)\n  .\n\n  Lemma delayed_sl_init lang st\n    :\n    delayed_sl Global.init Global.init (existT _ lang st, Local.init) (existT _ lang st, Local.init).\n  Proof.\n    econs.\n    { econs.\n      { eapply delayed_thread_init. }\n      { refl. }\n      { refl. }\n      { refl. }\n      { refl. }\n      { eapply Local.init_wf. }\n      { eapply Local.init_wf. }\n      { eapply Global.init_wf. }\n      { eapply Global.init_wf. }\n    }\n  Qed.\n\n  Variant delayed_conf: forall (c_src c_tgt: Configuration.t), Prop :=\n  | delayed_conf_intro\n      ths_src gl_src\n      ths_tgt gl_tgt\n      (THS: forall tid,\n          option_rel\n            (delayed_sl gl_src gl_tgt)\n            (IdentMap.find tid ths_src)\n            (IdentMap.find tid ths_tgt))\n      (GLOBAL: delayed_global_public gl_src gl_tgt)\n    :\n    delayed_conf (Configuration.mk ths_src gl_src)\n                 (Configuration.mk ths_tgt gl_tgt)\n  .\n\n  Lemma delayed_conf_init s:\n    delayed_conf (Configuration.init s) (Configuration.init s).\n  Proof.\n    econs.\n    { i. unfold Threads.init.\n      rewrite IdentMap.Facts.map_o. unfold option_map. des_ifs.\n      ss. eapply delayed_sl_init.\n    }\n    { eapply delayed_global_public_init. }\n  Qed.\n\n  Lemma delayed_conf_step\n        c1_src c1_tgt\n        e tid c2_tgt\n        (SIM: delayed_conf c1_src c1_tgt)\n        (WF1_SRC: Configuration.wf c1_src)\n        (WF1_TGT: Configuration.wf c1_tgt)\n        (STEP: Configuration.step e tid c1_tgt c2_tgt):\n    (exists c2_src,\n        (<<STEP_SRC: step e tid c1_src c2_src>>) /\\\n          (<<SIM: delayed_conf c2_src c2_tgt>>)) \\/\n    (exists c2_src,\n        (<<STEP_SRC: step MachineEvent.failure tid c1_src c2_src>>)).\n  Proof.\n    destruct c1_src as [ths1_src gl1_src],\n             c1_tgt as [ths1_tgt gl1_tgt].\n    inv SIM. inv STEP. ss.\n    dup THS. specialize (THS tid). rewrite TID in THS.\n    destruct (IdentMap.find tid ths1_src) as [[[lang_src st1_src] lc1_src]|] eqn:FIND_SRC; ss.\n    inv THS. Configuration.simplify.\n    dup WF1_SRC. inv WF1_SRC. ss.\n    inv WF. exploit THREADS; eauto. intro WF1_SRC.\n    clear DISJOINT THREADS.\n    inv WF1_TGT. ss.\n    inv WF. exploit THREADS; eauto. intro WF1_TGT.\n    clear DISJOINT THREADS.\n    inv DELAYED.\n    hexploit Thread.rtc_tau_step_future; eauto. i. des.\n    hexploit Thread.step_future; eauto. i. des.\n    hexploit delayed_thread_steps_full; eauto. i. des; cycle 1.\n    { destruct th_src1. right. esplits. econs; eauto. ss. }\n    hexploit dsteps_future; eauto. i. des. ss.\n    destruct th_src1.\n    hexploit dsteps_strong_le; eauto. i. des; ss; cycle 1.\n    { destruct th2'. right. esplits. econs; eauto. ss. }\n    left. esplits.\n    { econs; eauto. }\n    { econs; eauto. i. rewrite ! IdentMap.gsspec. des_ifs.\n      { econs; eauto. econs; eauto.\n        { refl. }\n        { refl. }\n        { refl. }\n        { refl. }\n      }\n      { specialize (THS0 tid0). ss. unfold option_rel in THS0. des_ifs.\n        des. ss. inv THS0; ss. destruct lc1_src, lc_src.\n        inv DELAYED1; ss. econs. econs; eauto.\n        { etrans; eauto. }\n        { etrans; eauto. eapply Global.future_le. etrans; eauto. }\n        { etrans; eauto.\n          eapply owned_future_global_promises_mon; eauto.\n          eapply other_promise_included; eauto.\n        }\n        { etrans; eauto.\n          eapply owned_future_global_promises_mon; eauto.\n          eapply other_promise_included; eauto.\n        }\n      }\n    }\n  Qed.\n\n  Lemma delayed_conf_terminal\n        c_src c_tgt\n        (LD: delayed_conf c_src c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (WF_TGT: Configuration.wf c_tgt)\n        (TERMINAL: Configuration.is_terminal c_tgt):\n    exists c1_src,\n      (<<STEP: terminal_steps\n                 (IdentSet.elements (Threads.tids (Configuration.threads c_src)))\n                 c_src c1_src>>).\n  Proof.\n    destruct c_src as [ths_src gl_src],\n             c_tgt as [ths_tgt gl_tgt]. ss.\n    remember (Threads.tids ths_src) as tids eqn:TIDS_SRC.\n    assert (NOTIN: forall tid lang_src st_src lc_src\n                     (FIND: IdentMap.find tid ths_src = Some (existT _ lang_src st_src, lc_src))\n                     (TID: ~ List.In tid (IdentSet.elements tids)),\n               Language.is_terminal _ st_src /\\ Local.is_terminal lc_src).\n    { i. destruct (IdentSet.mem tid tids) eqn:MEM.\n      - exfalso. apply TID. rewrite IdentSet.mem_spec in MEM.\n        rewrite <- IdentSet.elements_spec1 in MEM.\n        clear - MEM. induction MEM; [econs 1|econs 2]; auto.\n      - rewrite TIDS_SRC in MEM. rewrite Threads.tids_o in MEM.\n        destruct (IdentMap.find tid ths_src) eqn:IFIND; [inv MEM|]. ss.\n    }\n    assert (IN: forall tid (TID: List.In tid (IdentSet.elements tids)),\n               exists lang st_src lc_src st_tgt lc_tgt,\n                 (<<FIND_SRC: IdentMap.find tid ths_src = Some (existT _ lang st_src, lc_src)>>) /\\\n                 (<<FIND_TGT: IdentMap.find tid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)>>) /\\\n                 (<<LD_THREAD: past_delayed_thread\n                                 (Thread.mk _ st_src lc_src gl_src)\n                                 (Thread.mk _ st_tgt lc_tgt gl_tgt)>>)).\n    { i. destruct (IdentSet.mem tid tids) eqn:MEM.\n      - subst. dup MEM. rewrite Threads.tids_o in MEM0.\n        inv LD. specialize (THS tid).\n        destruct (IdentMap.find tid ths_src) as [[[lang_src st_src] lc_src]|] eqn:FIND_SRC; ss.\n        destruct (IdentMap.find tid ths_tgt) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:FIND_TGT; ss.\n        inv THS. Configuration.simplify.\n        esplits; eauto.\n      - exfalso. subst.\n        assert (SetoidList.InA eq tid (IdentSet.elements (Threads.tids ths_src))).\n        { clear - TID. induction (IdentSet.elements (Threads.tids ths_src)); eauto. }\n        rewrite IdentSet.elements_spec1 in H.\n        rewrite <- IdentSet.mem_spec in H. congr.\n    }\n    assert (TIDS_MEM: forall tid, List.In tid (IdentSet.elements tids) -> IdentSet.mem tid tids = true).\n    { i. rewrite IdentSet.mem_spec.\n      rewrite <- IdentSet.elements_spec1.\n      eapply SetoidList.In_InA; auto.\n    }\n    assert (NODUP: List.NoDup (IdentSet.elements tids)).\n    { specialize (IdentSet.elements_spec2w tids). i.\n      clear - H. induction H; econs; eauto.\n    }\n    assert (GLOBAL: delayed_global_public gl_src gl_tgt).\n    { inv LD. eauto. }\n    clear LD.\n    revert NOTIN IN TIDS_MEM NODUP GLOBAL.\n    revert ths_src gl_src WF_SRC TIDS_SRC WF_TGT.\n    induction (IdentSet.elements tids); i.\n    { esplits; [econs 1|..]. ii. eauto. }\n    exploit (IN a); try by econs 1. i. des.\n    exploit TERMINAL; eauto. i. des. inv THREAD.\n    inv LD_THREAD.\n    exploit delayed_thread_steps_terminal; try exact DELAYED; eauto; s.\n    { eapply WF_SRC; eauto. }\n    { eapply WF_TGT; eauto. }\n    { eapply WF_SRC; eauto. }\n    { eapply WF_TGT; eauto. }\n    i. des; cycle 1.\n    { destruct th_src1. esplits. econs 2; eauto.\n      { inv NODUP. auto. }\n      { econs; eauto. ss. }\n    }\n    hexploit lower_steps_future; eauto.\n    { eapply WF_SRC; eauto. }\n    { eapply WF_SRC; eauto. }\n    i. des. ss.\n    destruct th_src1 as [st1 lc1 gl1]. ss.\n    hexploit rtc_tau_lower_step_strong_le; eauto.\n    { eapply WF_SRC; eauto. }\n    { eapply WF_SRC; eauto. }\n    i. des; cycle 1.\n    { destruct th1', th2'. esplits. econs 2; eauto.\n      { inv NODUP. auto. }\n      { econs; eauto.\n        { econs; eauto. econs; eauto. }\n        { ss. }\n      }\n    }\n    assert (STEP_SRC: terminal_step\n                        a\n                        (Configuration.mk ths_src gl_src)\n                        (Configuration.mk\n                           (IdentMap.add a (existT _ _ st1, lc1) ths_src) gl1)).\n    { econs; eauto. }\n    exploit terminal_step_future; eauto. s. i. des.\n    exploit IHl; try exact WF2; ss; eauto; i.\n    { rewrite Threads.tids_add. rewrite IdentSet.add_mem; eauto. }\n    { rewrite IdentMap.gsspec in FIND. revert FIND. condtac; ss; i.\n      - subst. Configuration.simplify.\n      - eapply NOTIN; eauto. ii. des; ss. subst. ss.\n    }\n    { exploit IN; eauto. i. des. inv NODUP.\n      rewrite IdentMap.gso; try by (ii; subst; ss).\n      esplits; eauto.\n      inv LD_THREAD. destruct lc_src0, lc_src. ss. econs; eauto.\n      { etrans; eauto. }\n      { etrans; eauto.\n        eapply owned_future_global_promises_mon; eauto.\n        eapply other_promise_included; eauto.\n        ii. subst. ss.\n      }\n    }\n    { inv NODUP. ss. }\n    des. esplits.\n    econs 3; eauto. inv NODUP. ss.\n    Unshelve. all: ss.\n  Qed.\n\n  Inductive delayed_behaviors:\n    forall (conf:Configuration.t) (b:list Event.t) (f: bool), Prop :=\n  | delayed_behaviors_nil\n      c1 c2\n      (STEP: terminal_steps\n               (IdentSet.elements (Threads.tids (Configuration.threads c1)))\n               c1 c2):\n      delayed_behaviors c1 nil true\n  | delayed_behaviors_syscall\n      e1 e2 tid c1 c2 beh f\n      (STEP: step (MachineEvent.syscall e2) tid c1 c2)\n      (NEXT: delayed_behaviors c2 beh f)\n      (EVENT: Event.le e1 e2):\n      delayed_behaviors c1 (e1::beh) f\n  | delayed_behaviors_failure\n      tid c1 c2 beh f\n      (STEP: step MachineEvent.failure tid c1 c2):\n      delayed_behaviors c1 beh f\n  | delayed_behaviors_tau\n      tid c1 c2 beh f\n      (STEP: step MachineEvent.silent tid c1 c2)\n      (NEXT: delayed_behaviors c2 beh f):\n      delayed_behaviors c1 beh f\n  | delayed_behaviors_partial_term\n      c:\n      delayed_behaviors c [] false\n  .\n\n  Lemma delayed_conf_behavior\n        c_src c_tgt\n        (LD: delayed_conf c_src c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (WF_tgt: Configuration.wf c_tgt):\n    behaviors Configuration.step c_tgt <2= delayed_behaviors c_src.\n  Proof.\n    i. revert c_src LD WF_SRC. induction PR; i.\n    - exploit delayed_conf_terminal; eauto. i. des.\n      econs 1; eauto.\n    - exploit delayed_conf_step; eauto. i. des; cycle 1.\n      { eapply delayed_behaviors_failure; eauto. }\n      exploit step_future; eauto. i. des.\n      exploit Configuration.step_future; try exact STEP; eauto. i. des.\n      econs 2; eauto.\n    - exploit delayed_conf_step; eauto. i. des; cycle 1.\n      { eapply delayed_behaviors_failure; eauto. }\n      econs 3; eauto.\n    - exploit delayed_conf_step; eauto. i. des; cycle 1.\n      { eapply delayed_behaviors_failure; eauto. }\n      exploit step_future; eauto. i. des.\n      exploit Configuration.step_future; try exact STEP_SRC; eauto. i. des.\n      econs 4; eauto.\n    - econs 5.\n  Qed.\n\n  Lemma delayed_refinement\n        s\n    :\n    behaviors Configuration.step (Configuration.init s) <2= delayed_behaviors (Configuration.init s).\n  Proof.\n    exploit delayed_conf_init; eauto. i.\n    eapply delayed_conf_behavior; eauto.\n    { eapply Configuration.init_wf. }\n    { eapply Configuration.init_wf. }\n  Qed.\nEnd DConfiguration.\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/DelayedStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.18410723712422772}}
{"text": "Require Import Relations.\nRequire Import EquivDec.\nRequire Import Equality.\nRequire Import List.\nRequire Import Bool.\nRequire Import Lia.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import sflib.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\nRequire Import PromisingArch.promising.TsoPromising.\nRequire Import PromisingArch.promising.CommonPromising.\nRequire Import PromisingArch.promising.TsoStateExecFacts.\n\nSet Implicit Arguments.\n\n\nLemma reorder_state_step_promise_step\n      m1 m2 m3\n      (WF: Machine.wf m1)\n      (STEP1: Machine.step ExecUnit.state_step m1 m2)\n      (STEP2: Machine.step ExecUnit.promise_step m2 m3):\n  exists m2',\n    <<STEP: Machine.step ExecUnit.promise_step m1 m2'>> /\\\n    <<STEP: Machine.step ExecUnit.state_step m2' m3>>.\nProof.\n  destruct m1 as [tpool1 mem1].\n  destruct m2 as [tpool2 mem2].\n  destruct m3 as [tpool3 mem3].\n  inv STEP1. inv STEP2. ss. subst.\n  revert FIND0. rewrite IdMap.add_spec. condtac.\n  - (* same thread *)\n    inversion e. i. inv FIND0.\n    inv STEP. inv STEP0. inv STEP1. inv LOCAL. inv MEM2. ss. subst.\n    eexists (Machine.mk _ _). esplits.\n    + econs; eauto; ss. econs; ss.\n    + econs; ss.\n      * rewrite IdMap.add_spec. instantiate (3 := tid). condtac; [|congr]. eauto.\n      * econs. econs; eauto; ss.\n        instantiate (1 :=\n                       Local.mk\n                         lc0.(Local.coh)\n                         lc0.(Local.vrn)\n                         lc0.(Local.vpr)\n                         lc0.(Local.vpa)\n                         lc0.(Local.vpc)\n                         (Promises.set (S (length mem1)) lc0.(Local.promises))).\n        inv LOCAL0.\n        { econs 1; eauto. }\n        { econs 2; eauto. instantiate (1 := ts). inv STEP. ss.\n          exploit Memory.read_wf; try exact MSG. i.\n          econs; eauto; ss.\n          - ii. eapply LATEST; eauto.\n            rewrite nth_error_app1 in MSG0; ss.\n            eapply lt_le_trans; eauto.\n            inv WF. exploit WF0; eauto. i. inv x. ss. inv LOCAL.\n            repeat apply join_spec; viewtac.\n          - apply Memory.read_mon. ss.\n        }\n        { econs 3; eauto. instantiate (1 := ts).\n          inv STEP. inv WRITABLE. ss.\n          exploit Memory.get_msg_wf; try exact MSG. i.\n          econs; eauto; ss.\n          - inv COHMAX. econs; eauto.\n          - rewrite <- MSG. unfold Memory.get_msg. destruct ts; ss.\n            rewrite nth_error_app1; [|lia]. ss.\n          - rewrite Promises.set_o. condtac; ss. inversion e0. subst. ss.\n          - f_equal. apply Promises.set_unset.\n            ii. subst. lia.\n        }\n        { econs 4; eauto. instantiate (1 := ts). instantiate (1 := old_ts).\n          inv STEP.\n          exploit Memory.read_wf; try exact OLD_MSG. i.\n          inv WRITABLE. ss.\n          exploit Memory.get_msg_wf; try exact MSG. i.\n          econs; try exact OLD_RANGE; ss.\n          - ii. eapply EX; eauto.\n            rewrite nth_error_app1 in MSG0; ss.\n            eapply lt_le_trans; eauto.\n          - apply Memory.read_mon. ss.\n          - inv COHMAX. econs; eauto.\n          - rewrite <- MSG. unfold Memory.get_msg. destruct ts; ss.\n            rewrite nth_error_app1; [|lia]. ss.\n          - rewrite Promises.set_o. condtac; ss. inversion e0. subst. ss.\n          - f_equal. apply Promises.set_unset.\n            ii. subst. lia.\n        }\n        { econs 5; eauto. instantiate (1 := old_ts). instantiate (1 := vold). inv STEP. ss.\n          exploit Memory.read_wf; try exact OLD_MSG. i.\n          econs; eauto; ss.\n          - ii. eapply LATEST; eauto.\n            rewrite nth_error_app1 in MSG; ss.\n            eapply lt_le_trans; eauto.\n            inv WF. exploit WF0; eauto. i. inv x. ss. inv LOCAL.\n            repeat apply join_spec; viewtac.\n          - apply Memory.read_mon. ss.\n        }\n        { econs 6; eauto. inv STEP. inv COHMAX. econs; ss. econs; eauto. }\n        { econs 7; eauto. inv STEP. inv COHMAX. econs; ss. econs; eauto. }\n        { econs 8; eauto. inv STEP. inv COHMAX. econs; ss. econs; eauto. }\n        { econs 9; eauto. inv STEP. inv COHMAX_CL. econs; ss. econs; ss. }\n      * rewrite ? IdMap.add_add. eauto.\n  - (* diff thread *)\n    inv STEP. inv STEP1. inv STEP0. inv LOCAL0. inv MEM2. ss. subst.\n    eexists (Machine.mk _ _). esplits.\n    + econs; eauto; ss. econs; ss.\n    + econs; ss.\n      * rewrite IdMap.add_spec. instantiate (3 := tid). condtac; [|by eauto].\n        inversion e0. subst. congr.\n      * econs. econs; eauto; ss.\n        instantiate (1 := lc2). inv LOCAL.\n        { econs 1; eauto. }\n        { econs 2; eauto. inv STEP. econs; eauto.\n          - ii. eapply LATEST; eauto.\n            destruct (lt_dec ts0 (length mem1)).\n            { rewrite nth_error_app1 in MSG0; ss. }\n            contradict n.\n            eapply Time.lt_le_trans; [apply TS2|].\n            inv WF. exploit WF0; try exact FIND; eauto. i. inv x. inv LOCAL. ss.\n          - apply Memory.read_mon. ss.\n        }\n        { econs 3; eauto. inv STEP. inv WRITABLE. econs; eauto.\n          - econs; eauto.\n          - apply Memory.get_msg_mon. ss.\n        }\n        { econs 4; eauto. instantiate (1 := ts).\n          inv STEP. inv WRITABLE. econs; try exact OLD_RANGE; eauto.\n          - ii. eapply EX; eauto.\n            destruct (lt_dec ts0 (length mem1)).\n            { rewrite nth_error_app1 in MSG0; ss. }\n            contradict n.\n            eapply Time.lt_le_trans; [apply TS2|].\n            inv WF. exploit WF0; try exact FIND; eauto. i. inv x. inv LOCAL. ss.\n            etrans. instantiate (1 := ts).\n            + lia.\n            + viewtac.\n          - apply Memory.read_mon. ss.\n          - econs; eauto.\n          - apply Memory.get_msg_mon. ss.\n        }\n        { econs 5; eauto. instantiate (1 := old_ts). instantiate (1 := vold).\n          inv STEP. econs; eauto.\n          - ii. eapply LATEST; eauto.\n            destruct (lt_dec ts (length mem1)).\n            { rewrite nth_error_app1 in MSG; ss. }\n            contradict n.\n            eapply Time.lt_le_trans; [apply TS2|].\n            inv WF. exploit WF0; try exact FIND; eauto. i. inv x. inv LOCAL. ss.\n          - apply Memory.read_mon. ss.\n        }\n        { econs 6; eauto. }\n        { econs 7; eauto. }\n        { econs 8; eauto. }\n        { econs 9; eauto. }\n      * apply IdMap.add_add_diff. ss.\nQed.\n\nLemma reorder_state_step_rtc_promise_step\n      m1 m2 m3\n      (WF: Machine.wf m1)\n      (STEP1: Machine.step ExecUnit.state_step m1 m2)\n      (STEP2: rtc (Machine.step ExecUnit.promise_step) m2 m3):\n  exists m2',\n    <<STEP: rtc (Machine.step ExecUnit.promise_step) m1 m2'>> /\\\n    <<STEP: Machine.step ExecUnit.state_step m2' m3>>.\nProof.\n  revert m1 WF STEP1. induction STEP2; eauto.\n  i. exploit reorder_state_step_promise_step; eauto. i. des.\n  exploit Machine.step_promise_step_wf; eauto. i.\n  exploit IHSTEP2; eauto. i. des.\n  esplits; cycle 1; eauto.\nQed.\n\nLemma split_rtc_step\n      m1 m3\n      (WF: Machine.wf m1)\n      (STEP: rtc (Machine.step ExecUnit.step) m1 m3):\n  exists m2,\n    <<STEP: rtc (Machine.step ExecUnit.promise_step) m1 m2>> /\\\n    <<STEP: rtc (Machine.step ExecUnit.state_step) m2 m3>>.\nProof.\n  revert WF. induction STEP; eauto. i.\n  exploit Machine.step_step_wf; eauto. i.\n  exploit IHSTEP; eauto. i. des.\n  inv H. inv STEP2.\n  - exploit reorder_state_step_rtc_promise_step; try exact WF; eauto. i. des.\n    esplits; eauto.\n  - esplits; cycle 1; eauto.\nQed.\n\nTheorem promising_to_promising_pf\n        p m\n        (EXEC: Machine.exec p m):\n  Machine.pf_exec p m.\nProof.\n  inv EXEC. generalize (Machine.init_wf p). intro WF.\n  exploit split_rtc_step; eauto. i. des.\n  exploit Machine.rtc_step_promise_step_wf; eauto. i.\n  exploit rtc_state_step_state_exec; eauto.\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/equiv/TsoPtoPF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.18389260372469998}}
{"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\n     PCUICLiftSubst PCUICTyping PCUICSigmaCalculus\n     PCUICClosed PCUICClosedConv PCUICClosedTyp PCUICWeakeningEnv PCUICWeakeningEnvTyp\n     PCUICWeakeningConv PCUICWeakeningTyp PCUICInversion\n     PCUICSubstitution PCUICReduction PCUICCumulativity PCUICGeneration\n     PCUICUnivSubst PCUICUnivSubstitutionConv PCUICUnivSubstitutionTyp PCUICConfluence\n     PCUICConversion PCUICContexts\n     PCUICArities PCUICSpine PCUICInductives\n     PCUICWellScopedCumulativity PCUICContexts PCUICWfUniverses.\n\nFrom Equations Require Import Equations.\nRequire Import Equations.Prop.DepElim.\nRequire Import ssreflect ssrbool.\n\nDerive Signature for typing.\n\nImplicit Types (cf : checker_flags) (\u03a3 : global_env_ext).\n\nArguments Nat.sub : simpl never.\n\nSection Validity.\n  Context `{cf : config.checker_flags}.\n\n  Lemma isType_weaken_full : weaken_env_prop_full cumulSpec0 (lift_typing typing) (fun \u03a3 \u0393 t T => isType \u03a3 \u0393 T).\n  Proof using Type.\n    red. intros.\n    apply infer_typing_sort_impl with id X2; intros Hs.\n    unshelve eapply (weaken_env_prop_typing _ _ _ _ _ X1 _ _ (Typ (tSort _))); eauto with pcuic.\n    red. simpl. destruct \u03a3. eapply Hs.\n  Qed.\n\n  Hint Resolve isType_weaken_full : pcuic.\n\n  Lemma isType_weaken :\n    weaken_env_prop cumulSpec0 (lift_typing typing)\n      (lift_typing (fun \u03a3 \u0393 (_ T : term) => isType \u03a3 \u0393 T)).\n  Proof using Type.\n    red. intros.\n    apply lift_typing_impl with (1 := X2); intros ? Hs.\n    now eapply (isType_weaken_full (\u03a3, _)).\n  Qed.\n  Hint Resolve isType_weaken : pcuic.\n\n  Lemma isType_extends (\u03a3 : global_env) (\u03a3' : global_env) (\u03c6 : universes_decl) :\n    wf \u03a3 -> wf \u03a3' ->\n    extends \u03a3 \u03a3' ->\n    forall \u0393 : context,\n    forall t0 : term,\n    isType (\u03a3, \u03c6) \u0393 t0 -> isType (\u03a3', \u03c6) \u0393 t0.\n  Proof using Type.\n    intros wf\u03a3 wf\u03a3' ext \u0393 t Hty.\n    apply infer_typing_sort_impl with id Hty; intros Hs.\n    eapply (env_prop_typing weakening_env (\u03a3, \u03c6)); auto.\n  Qed.\n\n  Lemma weaken_env_prop_isType :\n    weaken_env_prop cumulSpec0 (lift_typing typing)\n    (lift_typing\n        (fun (\u03a30 : PCUICEnvironment.global_env_ext)\n          (\u03930 : PCUICEnvironment.context) (_ T : term) =>\n        isType \u03a30 \u03930 T)).\n  Proof using Type.\n    red. intros \u03a3 \u03a3' \u03d5 wf\u03a3 wf\u03a3' ext * Hty.\n    apply lift_typing_impl with (1 := Hty); intros ? Hs.\n    now eapply isType_extends with \u03a3.\n  Qed.\n\n  Lemma isType_Sort_inv {\u03a3 : global_env_ext} {\u0393 s} : wf \u03a3 -> isType \u03a3 \u0393 (tSort s) -> wf_universe \u03a3 s.\n  Proof using Type.\n    intros wf\u03a3 [u Hu].\n    now eapply inversion_Sort in Hu as [? [? ?]].\n  Qed.\n\n  Lemma isType_subst_instance_decl {\u03a3 \u0393 T c decl u} :\n    wf \u03a3.1 ->\n    lookup_env \u03a3.1 c = Some decl ->\n    isType (\u03a3.1, universes_decl_of_decl decl) \u0393 T ->\n    consistent_instance_ext \u03a3 (universes_decl_of_decl decl) u ->\n    isType \u03a3 (subst_instance u \u0393) (subst_instance u T).\n  Proof using Type.\n    destruct \u03a3 as [\u03a3 \u03c6]. intros X X0 Hty X1.\n    eapply infer_typing_sort_impl with _ Hty; intros Hs.\n    eapply (typing_subst_instance_decl _ _ _ (tSort _)); eauto.\n  Qed.\n\n  Lemma isWfArity_subst_instance_decl {\u03a3 \u0393 T c decl u} :\n    wf \u03a3.1 ->\n    lookup_env \u03a3.1 c = Some decl ->\n    isWfArity (\u03a3.1, universes_decl_of_decl decl) \u0393 T ->\n    consistent_instance_ext \u03a3 (universes_decl_of_decl decl) u ->\n    isWfArity \u03a3 (subst_instance u \u0393) (subst_instance u T).\n  Proof using Type.\n    destruct \u03a3 as [\u03a3 \u03c6]. intros X X0 [isTy [ctx [s eq]]] X1.\n    split. eapply isType_subst_instance_decl; eauto.\n    exists (subst_instance u ctx), (subst_instance_univ u s).\n    rewrite (subst_instance_destArity []) eq. intuition auto.\n  Qed.\n\n  Lemma isType_weakening {\u03a3 \u0393 T} :\n    wf \u03a3.1 ->\n    wf_local \u03a3 \u0393 ->\n    isType \u03a3 [] T ->\n    isType \u03a3 \u0393 T.\n  Proof using Type.\n    intros wf\u03a3 wf\u0393 HT.\n    apply infer_typing_sort_impl with id HT; intros Hs.\n    eapply (weaken_ctx (\u0393:=[])); eauto.\n  Qed.\n\n  Lemma nth_error_All_local_env {P : context -> term -> typ_or_sort -> Type} {\u0393 n d} :\n    nth_error \u0393 n = Some d ->\n    All_local_env P \u0393 ->\n    on_local_decl P (skipn (S n) \u0393) d.\n  Proof using Type.\n    intros heq h\u0393.\n    epose proof (nth_error_Some_length heq).\n    eapply (nth_error_All_local_env) in H; tea.\n    now rewrite heq in H.\n  Qed.\n\n  Notation type_ctx := (type_local_ctx (lift_typing typing)).\n  Lemma type_ctx_wf_univ \u03a3 \u0393 \u0394 s : type_ctx \u03a3 \u0393 \u0394 s -> wf_universe \u03a3 s.\n  Proof using Type.\n    induction \u0394 as [|[na [b|] ty]]; simpl; auto with pcuic.\n  Qed.\n  Hint Resolve type_ctx_wf_univ : pcuic.\n\n  Notation liat := ltac:(lia) (only parsing).\n\n  Lemma eq_binder_annots_eq_ctx (\u03a3 : global_env_ext) (\u0394 : context) (nas : list aname) :\n    All2 (fun x y => eq_binder_annot x y.(decl_name)) nas \u0394 ->\n    PCUICEquality.eq_context_gen (PCUICEquality.eq_term \u03a3 \u03a3) (PCUICEquality.eq_term \u03a3 \u03a3)\n      (map2 set_binder_name nas \u0394) \u0394.\n  Proof using Type.\n    induction \u0394 in nas |- * using PCUICInduction.ctx_length_rev_ind; simpl; intros hlen.\n    - depelim hlen. simpl. reflexivity.\n    - destruct nas as [|nas na] using rev_case => //;\n      pose proof (All2_length hlen) as hlen';len in hlen'; simpl in hlen'; try lia.\n      eapply All2_app_inv_l in hlen as (l1'&l2'&heq&alnas&allna).\n      depelim allna. depelim allna.\n      rewrite map2_app => /= //; try lia. unfold aname.\n      eapply app_inj_tail in heq as [<- <-].\n      simpl. eapply All2_fold_app; auto.\n      constructor. constructor.\n      destruct d as [na' [d|] ty]; constructor; cbn in *; auto;\n      try reflexivity.\n  Qed.\n\n  Lemma eq_term_set_binder_name (\u03a3 : global_env_ext) (\u0394 : context) T U (nas : list aname) :\n    All2 (fun x y => eq_binder_annot x y.(decl_name)) nas \u0394 ->\n    PCUICEquality.eq_term \u03a3 \u03a3 T U ->\n    PCUICEquality.eq_term \u03a3 \u03a3 (it_mkProd_or_LetIn (map2 set_binder_name nas \u0394) T) (it_mkProd_or_LetIn \u0394 U) .\n  Proof using Type.\n    intros a; unshelve eapply eq_binder_annots_eq_ctx in a; tea.\n    eapply All2_fold_All2 in a.\n    induction a in T, U |- *.\n    - auto.\n    - rewrite /= /mkProd_or_LetIn.\n      destruct r => /=; intros; eapply IHa;\n      constructor; auto.\n  Qed.\n\n  Lemma All2_eq_binder_subst_context_inst l s k i \u0394 \u0393 :\n    All2\n      (fun (x : binder_annot name) (y : context_decl) =>\n        eq_binder_annot x (decl_name y)) l \u0393 ->\n    All2\n      (fun (x : binder_annot name) (y : context_decl) =>\n      eq_binder_annot x (decl_name y)) l\n        (subst_context s k\n          (subst_instance i\n              (expand_lets_ctx \u0394 \u0393))).\n  Proof using Type.\n    intros. eapply All2_map_right in X.\n    depind X.\n    * destruct \u0393 => //. constructor.\n    * destruct \u0393 => //.\n      rewrite /expand_lets_ctx /expand_lets_k_ctx /=\n        !lift_context_snoc; simpl.\n      rewrite subst_context_snoc /= lift_context_length /=\n        subst_instance_cons subst_context_snoc subst_instance_length\n        subst_context_length lift_context_length.\n        constructor. simpl. simpl in H. now noconf H.\n        eapply IHX. simpl in H. now noconf H.\n  Qed.\n\n  Lemma wf_pre_case_predicate_context_gen {ci mdecl idecl} {p} :\n    wf_predicate mdecl idecl p ->\n    All2 (fun (x : binder_annot name) (y : context_decl) => eq_binder_annot x (decl_name y))\n      (forget_types (pcontext p))\n      (pre_case_predicate_context_gen ci mdecl idecl (pparams p) (puinst p)).\n  Proof using Type.\n    move=> [] hlen /Forall2_All2.\n    rewrite /pre_case_predicate_context_gen /ind_predicate_context.\n    intros a; depelim a.\n    destruct (pcontext p); noconf H.\n    cbn.\n    rewrite /inst_case_context /= subst_instance_cons subst_context_snoc Nat.add_0_r /subst_decl /map_decl /=.\n    constructor. cbn. apply e.\n    now eapply All2_eq_binder_subst_context_inst.\n  Qed.\n\n  Lemma validity_wf_local {\u03a3} \u0393 \u0394:\n    All_local_env\n      (fun (\u03930 : context) (t : term) (T : typ_or_sort) =>\n      match T with\n      | Typ T0 => isType \u03a3 (\u0393,,, \u03930) T0 \u00d7 \u03a3 ;;; (\u0393 ,,, \u03930) |- t : T0\n      | Sort => isType \u03a3 (\u0393,,, \u03930) t\n      end) \u0394 ->\n    \u2211 xs, sorts_local_ctx (lift_typing typing) \u03a3 \u0393 \u0394 xs.\n  Proof using Type.\n    induction 1.\n    - exists []; cbn; auto. exact tt.\n    - destruct IHX as [xs Hxs].\n      destruct t0 as [s Hs].\n      exists (s :: xs). cbn. split; auto.\n    - destruct IHX as [xs Hxs]. destruct t0 as [s Hs].\n      exists xs; cbn. split; auto.\n  Qed.\n\n  Import PCUICOnFreeVars.\n\n  Theorem validity_env :\n    env_prop (fun \u03a3 \u0393 t T => isType \u03a3 \u0393 T)\n      (fun \u03a3 \u0393 => wf_local \u03a3 \u0393 \u00d7 All_local_env\n        (fun \u0393 t T => match T with Typ T => (isType \u03a3 \u0393 T \u00d7 \u03a3 ;;; \u0393 |- t : T) | Sort => isType \u03a3 \u0393 t end) \u0393).\n  Proof using Type.\n    apply typing_ind_env; intros; rename_all_hyps.\n\n    - split => //. induction X; constructor; auto.\n\n    - destruct X as [_ X].\n      have hd := (nth_error_All_local_env heq_nth_error X).\n      destruct decl as [na [b|] ty]; cbn -[skipn] in *; destruct hd.\n      + eapply isType_lift; eauto.\n        now apply nth_error_Some_length in heq_nth_error.\n      + eapply isType_lift; eauto.\n        now apply nth_error_Some_length in heq_nth_error.\n        now exists x.\n\n    - (* Universe *)\n       exists (Universe.super (Universe.super u)).\n       constructor; auto.\n       now apply wf_universe_super.\n\n    - (* Product *)\n      eexists.\n      eapply isType_Sort_inv in X1; eapply isType_Sort_inv in X3; auto.\n      econstructor; eauto.\n      now apply wf_universe_product.\n\n    - (* Lambda *)\n      destruct X3 as [bs tybs].\n      eapply isType_Sort_inv in X1; auto.\n      exists (Universe.sort_of_product s1 bs).\n      constructor; auto.\n\n    - (* Let *)\n      apply infer_typing_sort_impl with id X5; unfold id in *; intros Hs.\n      eapply type_Cumul.\n      eapply type_LetIn; eauto.  econstructor; pcuic.\n      eapply convSpec_cumulSpec, red1_cumulSpec; constructor.\n\n    - (* Application *)\n      apply infer_typing_sort_impl with id X3; unfold id in *; intros Hs'.\n      move: (typing_wf_universe wf Hs') => wfs.\n      eapply (substitution0 (n := na) (T := tSort _)); eauto.\n      apply inversion_Prod in Hs' as [na' [s1 [s2 Hs]]]; tas. intuition.\n      eapply (weakening_ws_cumul_pb (pb:=Cumul) (\u0393' := []) (\u0393'' := [vass na A])) in b0; pcuic.\n      simpl in b0.\n      eapply (type_ws_cumul_pb (pb:=Cumul)); eauto. pcuic.\n      etransitivity; tea.\n      eapply into_ws_cumul_pb => //.\n      all:eauto with fvs.\n      do 2 constructor.\n      apply leq_universe_product.\n\n    - destruct decl as [ty [b|] univs]; simpl in *.\n      * eapply declared_constant_inv in X; eauto.\n        red in X. simpl in X.\n        eapply isType_weakening; eauto.\n        eapply (isType_subst_instance_decl (\u0393:=[])); eauto. simpl.\n        eapply weaken_env_prop_isType.\n      * have ond := on_declared_constant wf H.\n        do 2 red in ond. simpl in ond.\n        simpl in ond.\n        eapply isType_weakening; eauto.\n        eapply (isType_subst_instance_decl (\u0393:=[])); eauto.\n\n     - (* Inductive type *)\n      destruct (on_declared_inductive isdecl); pcuic.\n      destruct isdecl.\n      apply onArity in o0.\n      eapply isType_weakening; eauto.\n      eapply (isType_subst_instance_decl (\u0393:=[])); eauto.\n\n    - (* Constructor type *)\n      destruct (on_declared_constructor isdecl) as [[oni oib] [cs [declc onc]]].\n      unfold type_of_constructor.\n      eapply infer_typing_sort_impl with _ (on_ctype onc); intros Hs.\n      eapply instantiate_minductive in Hs; eauto.\n      2:(destruct isdecl as [[] ?]; eauto).\n      simpl in Hs.\n      eapply (weaken_ctx (\u0393:=[]) \u0393); eauto.\n      eapply (substitution (\u0393 := []) (s := inds _ _ _) (\u0394 := []) (T := tSort _)); eauto.\n      eapply subslet_inds; eauto. destruct isdecl; eauto.\n      now rewrite app_context_nil_l.\n\n    - (* Case predicate application *)\n      assert (cu : consistent_instance_ext \u03a3 (ind_universes mdecl) (puinst p)).\n      { eapply (isType_mkApps_Ind_inv wf isdecl) in X7 as [parsubst [argsubst Hind]];\n        repeat intuition auto. }\n      eassert (ctx_inst \u03a3 \u0393 _ (List.rev _)).\n      { eapply ctx_inst_impl with (1 := X5); now intros t T [Hty _]. }\n      clear X5; rename X6 into X5.\n      unshelve epose proof (ctx_inst_spine_subst _ X5); tea.\n      eapply weaken_wf_local; tea.\n      now apply (on_minductive_wf_params_indices_inst isdecl _ cu).\n      eapply spine_subst_smash in X6; tea.\n      destruct X4.\n      destruct (on_declared_inductive isdecl) as [onmind oib].\n      rewrite /ptm. exists ps.\n      eapply type_mkApps; eauto.\n      eapply type_it_mkLambda_or_LetIn; tea.\n      have typred : isType \u03a3 \u0393 (it_mkProd_or_LetIn predctx (tSort ps)).\n      { eapply All_local_env_app_inv in a0 as [_ onp].\n        eapply validity_wf_local in onp as [xs Hs].\n        eexists _.\n        eapply type_it_mkProd_or_LetIn_sorts; tea.\n        exact X3.\u03c02. }\n      have wfps : wf_universe \u03a3 ps.\n      { pcuic. }\n      eapply typing_spine_strengthen; tea.\n      2:{ rewrite /predctx /case_predicate_context /case_predicate_context_gen.\n          eapply ws_cumul_pb_compare. 1-2:eauto with fvs.\n          2:{ red.\n              instantiate (1 :=\n                it_mkProd_or_LetIn (pre_case_predicate_context_gen ci mdecl idecl (pparams p) (puinst p))\n                    (tSort ps)).\n            eapply PCUICEquality.eq_term_leq_term.\n            eapply eq_term_set_binder_name. 2:reflexivity.\n            now eapply wf_pre_case_predicate_context_gen. }\n          rewrite subst_instance_app_ctx in X6.\n          eapply spine_subst_smash_app_inv in X6 as [sppars spidx].\n          epose proof (isType_case_predicate (puinst p) _ _ wf\u0393 isdecl cu wfps sppars).\n          eauto with fvs. len.\n          rewrite (wf_predicate_length_pars H0).\n          now rewrite onmind.(onNpars). }\n      eapply wf_arity_spine_typing_spine; auto.\n      rewrite subst_instance_app_ctx in X6.\n      eapply spine_subst_smash_app_inv in X6 as [sppars spidx].\n      split; auto.\n      apply (isType_case_predicate (puinst p) _ _ wf\u0393 isdecl cu wfps sppars).\n      2:{ rewrite (wf_predicate_length_pars H0).\n          rewrite context_assumptions_map.\n          now rewrite onmind.(onNpars). }\n      eapply arity_spine_case_predicate; tea.\n\n    - (* Proj *)\n      pose proof isdecl as isdecl'.\n      eapply declared_projection_type in isdecl'; eauto.\n      unshelve eapply isType_mkApps_Ind_inv in X2 as [parsubst [argsubst [sppar sparg\n        lenpars lenargs cu]]]; eauto.\n      2:eapply isdecl.p1.\n      eapply infer_typing_sort_impl with _ isdecl'; intros Hs.\n      eapply (typing_subst_instance_decl _ _ _ _ _ _ _ wf isdecl.p1.p1.p1) in Hs; eauto.\n      simpl in Hs.\n      eapply (weaken_ctx \u0393) in Hs; eauto.\n      rewrite -heq_length in sppar. rewrite firstn_all in sppar.\n      rewrite subst_instance_cons in Hs.\n      rewrite subst_instance_smash in Hs. simpl in Hs.\n      eapply spine_subst_smash in sppar => //.\n      eapply (substitution (\u0394 := [_]) sppar) in Hs.\n      simpl in Hs.\n      eapply (substitution (\u0393' := [_]) (s := [c]) (\u0394 := [])) in Hs.\n      simpl in Hs. rewrite (subst_app_simpl [_]) /=. eassumption.\n      constructor. constructor.\n      simpl. rewrite subst_empty.\n      rewrite subst_instance_mkApps subst_mkApps /=.\n      rewrite [subst_instance_instance _ _](subst_instance_id_mdecl \u03a3 u _ cu); auto.\n      rewrite subst_instance_to_extended_list.\n      rewrite subst_instance_smash.\n      rewrite (spine_subst_subst_to_extended_list_k sppar).\n      assumption.\n\n    - (* Fix *)\n      eapply nth_error_all in X0 as [s Hs]; eauto.\n      pcuic.\n\n    - (* CoFix *)\n      eapply nth_error_all in X0 as [s Hs]; pcuic.\n\n    - (* Primitive *)\n      destruct X0 as [s [hty hbod huniv]].\n      exists s@[[]].\n      change (tSort s@[[]]) with (tSort s)@[[]].\n      rewrite -hty.\n      refine (type_Const _ _ _ [] _ wf\u0393 H0 _).\n      rewrite huniv //.\n\n    - (* Conv *)\n      now exists s.\n  Qed.\n\nEnd Validity.\n\nCorollary validity {cf:checker_flags} {\u03a3} {wf\u03a3 : wf \u03a3} {\u0393 t T} :\n  \u03a3 ;;; \u0393 |- t : T -> isType \u03a3 \u0393 T.\nProof.\n  intros. eapply validity_env; try eassumption.\nDefined.\n\nLemma wf_local_validity `{cf : checker_flags} {\u03a3} {wf\u03a3 : wf \u03a3} \u0393 \u0394 :\n  wf_local \u03a3 (\u0393 ,,, \u0394) ->\n  \u2211 us, sorts_local_ctx (lift_typing typing) \u03a3 \u0393 \u0394 us.\nProof.\n  move=> wf\u0393\u0394.\n  apply: validity_wf_local.\n  enough (h : wf_local_rel \u03a3 \u0393 \u0394).\n  apply: All_local_env_impl; first exact h.\n  1: move=> ?? [?|] //= ?; split=> //; apply: validity; eassumption.\n  by apply: (wf_local_app_inv _).2.\nQed.\n\n\n\n(* To deprecate *)\nNotation validity_term wf Ht := (validity (wf\u03a3:=wf) Ht).\n\n(* This corollary relies strongly on validity to ensure\n   every type in the derivation is well-typed.\n   It should be used instead of the weaker [invert_type_mkApps],\n   which is only used as a stepping stone to validity.\n *)\nLemma inversion_mkApps {cf} {\u03a3} {wf\u03a3 :  wf \u03a3.1} {\u0393 f u T} :\n  \u03a3 ;;; \u0393 |- mkApps f u : T ->\n  \u2211 A, \u03a3 ;;; \u0393 |- f : A \u00d7 typing_spine \u03a3 \u0393 A u T.\nProof.\n  induction u in f, T |- *. simpl. intros.\n  { exists T. intuition pcuic. eapply typing_spine_refl.\n    now eapply validity in X. }\n  intros Hf. simpl in Hf.\n  destruct u. simpl in Hf.\n  - pose proof (validity Hf).\n    eapply inversion_App in Hf as [na' [A' [B' [Hf' [Ha HA''']]]]]; tea.\n    eexists _; intuition eauto.\n    eapply validity in Hf'.\n    econstructor; eauto with pcuic.\n    constructor. all:eauto with pcuic.\n    now eapply isType_apply in Hf'.\n  - specialize (IHu (tApp f a) T).\n    specialize (IHu Hf) as [T' [H' H'']].\n    eapply inversion_App in H' as [na' [A' [B' [Hf' [Ha HA''']]]]]. 2:{ eassumption. }\n    exists (tProd na' A' B'). intuition; eauto.\n    eapply validity in Hf'.\n    econstructor; eauto with wf.\n    now eapply isType_ws_cumul_pb_refl.\n    eapply isType_apply in Hf'; tea.\n    eapply typing_spine_strengthen; tea.\nQed.\n\n(** \"Economical\" typing rule for applications, not requiring to check the product type *)\nLemma type_App' {cf:checker_flags} {\u03a3 : global_env_ext} {wf\u03a3 : wf \u03a3} {\u0393 t na A B u} :\n  \u03a3;;; \u0393 |- t : tProd na A B ->\n  \u03a3;;; \u0393 |- u : A -> \u03a3;;; \u0393 |- tApp t u : B {0 := u}.\nProof.\n  intros Ht Hu.\n  have [s Hs] := validity Ht.\n  eapply type_App; eauto.\nQed.\n\n(** This principle is useful when the type [tty] is an arity (of the form [it_mkProd_or_LetIn _ (tSort _)]),\n    as it avoids having to give intermediate well-typing and cumulativity proofs. *)\nLemma type_mkApps_arity {cf} {\u03a3 : global_env_ext} {wf\u03a3 : wf \u03a3} {\u0393 t u tty T} :\n  \u03a3;;; \u0393 |- t : tty ->\n  arity_spine \u03a3 \u0393 tty u T ->\n  \u03a3;;; \u0393 |- mkApps t u : T.\nProof.\n  intros Ht Hty.\n  pose proof (validity Ht).\n  eapply type_mkApps; tea.\n  eapply wf_arity_spine_typing_spine; tea.\n  constructor; tas.\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/PCUICValidity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18389260021374215}}
{"text": "(* En este archivo se demuestra que si el sistema parte de un estado inicial v\u00e1lido en el que existe\n * una aplicaci\u00f3n A que es considerada vieja y no ha sido verificada, y luego de una serie de operaciones\n * dicha aplicaci\u00f3n est\u00e1 en condiciones de ser ejecutada; es porque alguna de todas esas operaciones fue\n * la que verific\u00f3 a la aplicaci\u00f3n A. *)\n\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.\nRequire Import RuntimePermissions.\nRequire Import EqTheorems.\nRequire Import Trace.\nRequire Import PropertiesAuxFuns.\n\nRequire Import TraceRelatedLemmas.\nRequire Import Coq.Arith.Lt.\n\nSection IfOldAppRunThenVerified.\n\nLemma inductMe : forall\n(initState : System)\n(initStateValid : validstate initState)\n(a : idApp)\n(l : list Action)\n(aIsTheSame : ~ In (uninstall a) l)\n(notVerified : ~ In (verifyOldApp a) l)\n(couldntRun : ~canRun a initState)\n(aInstalled: \n  In a (apps (state initState)) \\/\n  (exists x0, In x0 (systemImage (environment initState)) /\\ idSI x0 = a)),\nvalidstate ((last (trace initState l)) initState) /\\\n(In a (apps (state ((last (trace initState l)) initState))) \\/ (exists x0, In x0 (systemImage (environment ((last (trace initState l)) initState))) /\\ idSI x0 = a)) /\\\n(~canRun a ((last (trace initState l)) initState)).\nProof.\n    intros.\n    induction l using rev_ind.\n  - simpl. split; auto.\n  - assert (~In (uninstall a) l).\n    unfold not;intros.\n    apply aIsTheSame.\n    rewrite in_app_iff.\n    left;auto.\n    assert (~In (verifyOldApp a) l).\n    unfold not;intros.\n    apply notVerified.\n    rewrite in_app_iff.\n    left;auto.\n    specialize (IHl H H0).\n    destruct IHl.\n    split.\n    rewrite (lastTraceApp initState l x initState).\n    apply stepIsInvariant. auto.\n\n    rewrite lastTraceApp.\n    remember (last (trace initState l) initState) as lastSys.\n    destruct H2.\n\n    assert (x<>uninstall a) as xNotUninstallA.\n    unfold not;intros.\n    apply aIsTheSame.\n    rewrite in_app_iff.\n    right.\n    rewrite H4.\n    apply in_eq.\n\n    assert (x<>verifyOldApp a) as xNotVerifyA.\n    unfold not; intros.\n    apply notVerified.\n    rewrite in_app_iff.\n    right.\n    rewrite H4.\n    apply in_eq.\n\n\n    split.\n    destruct H2.\n    left.\n\n    apply aInAppsAndNotUninstalled;auto.\n    right.\n    destruct H2.\n    exists x0.\n    destruct H2.\n    split;auto.\n\n    assert (systemImage (environment (system (step lastSys x))) = systemImage (environment lastSys)).\n    destruct x;simpl.\n    unfold install_safe; case_eq (install_pre i m c l0 lastSys);intros;simpl;auto.\n    unfold uninstall_safe; case_eq (uninstall_pre i lastSys);intros;simpl;auto.\n    unfold grant_safe; case_eq (grant_pre p i lastSys);intros;simpl;auto.\n    unfold grantAuto_safe; case_eq (grantAuto_pre p i lastSys);intros;simpl;auto.\n    unfold revoke_safe; case_eq (revoke_pre p i lastSys);intros;simpl;auto.\n    unfold revokegroup_safe; case_eq (revokegroup_pre i i0 lastSys);intros;simpl;auto.\n    auto.\n    unfold read_safe; case_eq (read_pre i c u lastSys);intros;simpl;auto.\n    unfold write_safe; case_eq (write_pre i c u v lastSys);intros;simpl;auto.\n    unfold startActivity_safe; case_eq (startActivity_pre i i0 lastSys);intros;simpl;auto.\n    unfold startActivity_safe; case_eq (startActivity_pre i i0 lastSys);intros;simpl;auto.\n    unfold startService_safe; case_eq (startService_pre i i0 lastSys);intros;simpl;auto.\n    unfold sendBroadcast_safe; case_eq (sendBroadcast_pre i i0 o lastSys);intros;simpl;auto.\n    unfold sendBroadcast_safe; case_eq (sendBroadcast_pre i i0 o lastSys);intros;simpl;auto.\n    unfold sendStickyBroadcast_safe; case_eq (sendStickyBroadcast_pre i i0 lastSys);intros;simpl;auto.\n    unfold resolveIntent_safe; case_eq (resolveIntent_pre i i0 lastSys);intros;simpl;auto.\n    unfold receiveIntent_safe; case_eq (receiveIntent_pre i i0 i1 lastSys);intros;simpl;auto.\n    unfold receiveIntent_post.\n    destruct (maybeIntentForAppCmp i i1 i0 lastSys);auto. \n    unfold stop_safe; case_eq (stop_pre i lastSys);intros;simpl;auto.\n    unfold grantP_safe; case_eq (grantP_pre i c i0 u p lastSys);intros;simpl;auto.\n    unfold revokeDel_safe; case_eq (revokeDel_pre i c u p lastSys);intros;simpl;auto.\n    unfold call_safe; case_eq (call_pre i s lastSys);intros;simpl;auto.\n    unfold verifyOldApp_safe; case_eq (verifyOldApp_pre i lastSys);intros;simpl;auto.\n    rewrite H5;auto.\n\n    assert (x <> verifyOldApp a) as xNotVerifyOldApp.\n    unfold not;intros.\n    apply notVerified.\n    rewrite in_app_iff.\n    right.\n    rewrite H4.\n    apply in_eq.\n\n    unfold not; intros.\n    apply H3.\n    unfold canRun in H4.\n    unfold canRun.\n    destruct H4. left.\n (* Caso alreadyVerifiedIsTheSame*)\n -- apply (alreadyVerifiedSame x a); auto.\n (* Caso manifestIsTheSame *)\n -- destruct H4 as [m [n [H4 [H5 H6]]]].\n    right. exists m, n.\n    split; auto.\n    unfold isManifestOfApp.\n    destruct H4.\n\n    left. apply (manifestsSame x); auto.\n\n    right. clear H5 H6.\n    destruct H4 as [sysapp [H4 [H5 H6]]].\n    exists sysapp.\n    split; auto.\n    apply (sysImgSame x lastSys H1 sysapp);auto.\nQed.\n\nTheorem ifOldAppRunThenWasVerifiedProof :\n  forall\n    (initState lastState: System)\n    (a: idApp)\n    (l: list Action)\n    (aInstalled:In a (apps (state initState)) \\/ (exists x0, In x0 (systemImage (environment initState)) /\\ idSI x0 = a))\n    (vsInit: validstate initState)\n    (oldApp: isOldApp a initState)\n    (notVerified: ~(In a (alreadyVerified (state initState))))\n    (canRunLastState: canRun a lastState)\n    (aIsTheSame : ~ In (uninstall a) l)\n    (fromInitToLast: last (trace initState l) initState  = lastState),\n    In (verifyOldApp a) l.\nProof.\n    intros.\n    apply NNPP.\n    unfold not;intros.\n    assert (validstate (last (trace initState l) initState) /\\ (In a (apps (state (last (trace initState l) initState))) \\/ (exists x0, In x0 (systemImage (environment (last (trace initState l) initState))) /\\ idSI x0 = a)) /\\ ~ (canRun a (last (trace initState l) initState))).\n    apply inductMe;auto.\n    unfold canRun. unfold not.\n    intros. destruct H0.\n    contradiction.\n    unfold isOldApp in oldApp.\n    destruct oldApp as [m [n [H1 [H2 nLTVulnerableSdk]]]].\n    destruct H0 as [m' [n' [H3 [H4 nGTVulnerableSdk]]]].\n\n    assert (m=m').\n    apply (sameAppSameManifest initState vsInit a); auto.\n\n    rewrite <- H0 in H4.\n    rewrite H2 in H4.\n    inversion H4.\n    rewrite <- H6 in nGTVulnerableSdk.\n    assert (n<n).\n    apply (lt_trans n vulnerableSdk); auto.\n    apply lt_irrefl in H5; auto.\n\n    destruct H0.\n    destruct H1.\n    rewrite fromInitToLast in H2.\n    contradiction.\nQed.\n\nEnd IfOldAppRunThenVerified.", "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/IfOldAppRunThenVerified.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.1838925985438291}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.LogMatchingInterface.\nRequire Import VerdiRaft.LeaderLogsTermSanityInterface.\nRequire Import VerdiRaft.LeaderLogsSortedInterface.\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.LeaderLogsSublogInterface.\nRequire Import VerdiRaft.LeaderLogsContiguousInterface.\nRequire Import VerdiRaft.TermsAndIndicesFromOneInterface.\n\nRequire Import VerdiRaft.LeaderLogsLogMatchingInterface.\n\nSection LeaderLogsLogMatching.\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  Context {lltsi : leaderLogs_term_sanity_interface}.\n  Context {llsi : leaderLogs_sorted_interface}.\n  Context {si : sorted_interface}.\n  Context {llsli : leaderLogs_sublog_interface}.\n  Context {llci : leaderLogs_contiguous_interface}.\n  Context {taifoi : terms_and_indices_from_one_interface}.\n\n  Definition leaderLogs_entries_match_nw (net : network) : Prop :=\n    forall h llt ll p t src pli plt es ci,\n      In (llt, ll) (leaderLogs (fst (nwState net h))) ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t src pli plt es ci ->\n      (forall e1 e2,\n         eIndex e1 = eIndex e2 ->\n         eTerm e1 = eTerm e2 ->\n         In e1 es ->\n         In e2 ll ->\n         (forall e3,\n            eIndex e3 <= eIndex e1 ->\n            In e3 es ->\n            In e3 ll) /\\\n         (pli <> 0 ->\n          exists e4,\n            eIndex e4 = pli /\\\n            eTerm e4 = plt /\\\n            In e4 ll)).\n\n  Definition leaderLogs_entries_match (net : network) : Prop :=\n    leaderLogs_entries_match_host net /\\\n    leaderLogs_entries_match_nw net.\n\n  Lemma leaderLogs_entries_match_init :\n    refined_raft_net_invariant_init leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_init, leaderLogs_entries_match,\n           leaderLogs_entries_match_host, leaderLogs_entries_match_nw.\n    simpl.\n    intuition.\n  Qed.\n\n  Lemma entries_match_cons_gt_maxTerm :\n    forall x xs ys,\n      sorted xs ->\n      sorted ys ->\n      eIndex x > maxIndex xs ->\n      eTerm x > maxTerm ys ->\n      entries_match xs ys ->\n      entries_match (x :: xs) ys.\n  Proof using. \n    unfold entries_match.\n    intuition; simpl in *; intuition; subst; subst;\n    try match goal with\n        | [ H : In _ _ |- _ ] => apply maxTerm_is_max in H; [| solve[auto]]; lia\n        | [ H : In _ _ |- _ ] => apply maxIndex_is_max in H; [| solve[auto]]; lia\n      end.\n    - match goal with\n        | [ H : _ |- _ ] => solve [eapply H; eauto]\n      end.\n    - right. match goal with\n        | [ H : _ |- _ ] => solve [eapply H; eauto]\n      end.\n  Qed.\n\n  Lemma entries_match_cons_sublog :\n    forall x xs ys,\n      sorted xs ->\n      sorted ys ->\n      eIndex x > maxIndex xs ->\n      entries_match xs ys ->\n      (forall y, In y ys -> eTerm x = eTerm y -> In y xs) ->\n      entries_match (x :: xs) ys.\n  Proof using. \n    unfold entries_match.\n    intuition; simpl in *; intuition; subst; subst;\n    try solve [\n         exfalso; try find_apply_hyp_hyp;\n          match goal with\n            | [ H : In _ _ |- _ ] => apply maxIndex_is_max in H; [| solve[auto]]; lia\n          end].\n    - match goal with\n        | [ H : _ |- _ ] => solve [eapply H; eauto]\n      end.\n    - right. match goal with\n        | [ H : _ |- _ ] => solve [eapply H; eauto]\n      end.\n  Qed.\n\n  Lemma entries_match_nil :\n    forall l,\n      entries_match l [].\n  Proof using. \n    red.\n    simpl.\n    intuition.\n  Qed.\n\n  Lemma lifted_logs_sorted_nw :\n    forall net p t n plt plti es ci,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n plt plti es ci ->\n      sorted es.\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    find_insterU. conclude_using eauto.\n    unfold logs_sorted in *. break_and.\n    unfold logs_sorted_nw in *.\n    eapply H3.\n    - unfold deghost. simpl.\n      apply in_map_iff. eauto.\n    - simpl. eauto.\n  Qed.\n\n  Lemma lifted_logs_sorted_host :\n    forall net h ,\n      refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    find_insterU. conclude_using eauto.\n    unfold logs_sorted in *. break_and.\n    unfold logs_sorted_host in *.\n    find_insterU.\n    find_rewrite_lem deghost_spec.\n    eauto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_nw_packet_set :\n    forall net net',\n      leaderLogs_entries_match_nw net ->\n      (forall p, In p (nwPackets net') ->\n                 is_append_entries (pBody p) ->\n                 In p (nwPackets net)) ->\n      (forall h, leaderLogs (fst (nwState net' h)) = leaderLogs (fst (nwState net h))) ->\n      leaderLogs_entries_match_nw net'.\n  Proof using. \n    unfold leaderLogs_entries_match_nw.\n    intros.\n    eapply_prop_hyp In nwPackets; [|eauto 10].\n    match goal with\n      | [ H : _ |- _ ] =>\n        solve [eapply H; eauto;\n               repeat find_higher_order_rewrite;\n               eauto]\n    end.\n  Qed.\n\n  Lemma leaderLogs_entries_match_host_state_same :\n    forall net net',\n      leaderLogs_entries_match_host net ->\n      (forall h, leaderLogs (fst (nwState net' h)) = leaderLogs (fst (nwState net h))) ->\n      (forall h, log (snd (nwState net' h)) = log (snd (nwState net h))) ->\n      leaderLogs_entries_match_host net'.\n  Proof using. \n    unfold leaderLogs_entries_match_host.\n    intuition.\n    repeat find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma handleClientRequest_no_send :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      ms = [].\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_client_request :\n    refined_raft_net_invariant_client_request leaderLogs_entries_match.\n  Proof using llsli si llsi lltsi rri. \n    unfold refined_raft_net_invariant_client_request, leaderLogs_entries_match.\n    intros.\n    split.\n    - { unfold leaderLogs_entries_match_host.\n        simpl. intuition. subst. repeat find_higher_order_rewrite.\n        repeat update_destruct_simplify.\n        - find_rewrite_lem update_elections_data_client_request_leaderLogs.\n          destruct (log d) using (handleClientRequest_log_ind ltac:(eauto)).\n          + eauto.\n          + destruct ll.\n            * apply entries_match_nil.\n            * { apply entries_match_cons_gt_maxTerm; eauto.\n                - eauto using lifted_logs_sorted_host.\n                - eapply leaderLogs_sorted_invariant; eauto.\n                - lia.\n                - find_copy_apply_lem_hyp leaderLogs_currentTerm_invariant; auto.\n                  find_copy_apply_lem_hyp leaderLogs_term_sanity_invariant.\n                  unfold leaderLogs_term_sanity in *.\n                  eapply_prop_hyp In In; simpl; eauto. repeat find_rewrite.\n                  simpl in *. lia.\n              }\n        - destruct (log d) using (handleClientRequest_log_ind ltac:(eauto)).\n          + eauto.\n          + apply entries_match_cons_sublog; eauto.\n            * eauto using lifted_logs_sorted_host.\n            * eapply leaderLogs_sorted_invariant; eauto.\n            * lia.\n            * intros.\n              eapply leaderLogs_sublog_invariant; eauto.\n              simpl in *. congruence.\n        - find_rewrite_lem update_elections_data_client_request_leaderLogs.\n          eauto.\n        - eauto.\n      }\n    - eapply leaderLogs_entries_match_nw_packet_set with (net:=net); intuition.\n      + find_apply_hyp_hyp. intuition eauto.\n        erewrite handleClientRequest_no_send with (ms := l) in * by eauto.\n        simpl in *. intuition.\n      + simpl. subst. find_higher_order_rewrite.\n        rewrite update_fun_comm. simpl.\n        rewrite update_fun_comm. simpl.\n        rewrite update_elections_data_client_request_leaderLogs.\n        now rewrite update_nop_ext' by auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_timeout :\n    refined_raft_net_invariant_timeout leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto;\n      simpl; intros; subst; find_higher_order_rewrite;\n      repeat update_destruct_simplify; rewrite_update; auto;\n      try rewrite update_elections_data_timeout_leaderLogs;\n      try erewrite handleTimeout_log_same by eauto; eauto.\n    - eapply leaderLogs_entries_match_nw_packet_set with (net:=net); intuition.\n      + simpl in *. find_apply_hyp_hyp.  intuition.\n        do_in_map. subst. simpl in *.\n        exfalso. eapply handleTimeout_not_is_append_entries; eauto 10.\n      + simpl. repeat find_higher_order_rewrite.\n        rewrite update_fun_comm. simpl.\n        rewrite update_fun_comm. simpl.\n        rewrite update_elections_data_timeout_leaderLogs.\n        rewrite update_nop_ext'; auto.\n  Qed.\n\n  Lemma lifted_log_matching :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      log_matching (deghost net).\n  Proof using lmi rri. \n    intros.\n    pose proof (lift_prop _ log_matching_invariant).\n    find_insterU. conclude_using eauto.\n    auto.\n  Qed.\n\n  Lemma lifted_log_matching_host :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      (forall h h',\n         entries_match (log (snd (nwState net h))) (log (snd (nwState net h')))) /\\\n      (forall h i,\n         1 <= i <= maxIndex (log (snd (nwState net h))) ->\n         exists e, eIndex e = i /\\ In e (log (snd (nwState net h)))) /\\\n      (forall h e,\n         In e (log (snd (nwState net h))) -> eIndex e > 0).\n  Proof using lmi rri. \n    intros.\n    find_apply_lem_hyp lifted_log_matching.\n    unfold log_matching, log_matching_hosts in *.\n    rename net into net0.\n    intuition; repeat rewrite <- deghost_spec with (net := net0).\n    - auto.\n    - match goal with\n        | [ H : _ |- _ ] => solve [apply H; rewrite deghost_spec; auto]\n      end.\n    - match goal with\n        | [ H : _ |- _ ] => solve [eapply H; rewrite deghost_spec; eauto]\n      end.\n  Qed.\n\n  Lemma lifted_log_matching_nw :\n    forall net,\n      refined_raft_intermediate_reachable net ->\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        (forall h e1 e2,\n           In e1 entries ->\n           In e2 (log (snd (nwState net h))) ->\n           eIndex e1 = eIndex e2 ->\n           eTerm e1 = eTerm e2 ->\n           (forall e3,\n              eIndex e3 <= eIndex e1 ->\n              In e3 entries ->\n              In e3 (log (snd (nwState net h)))) /\\\n           (prevLogIndex <> 0 ->\n            exists e4,\n              eIndex e4 = prevLogIndex /\\\n              eTerm e4 = prevLogTerm /\\\n              In e4 (log (snd (nwState net h))))) /\\\n        (forall i,\n           prevLogIndex < i <= maxIndex entries ->\n           exists e,\n             eIndex e = i /\\\n             In e entries) /\\\n        (forall e,\n           In e entries ->\n           prevLogIndex < eIndex e).\n  Proof using lmi rri. \n    intros.\n    find_apply_lem_hyp lifted_log_matching.\n    unfold log_matching, log_matching_nw in *.\n    break_and.\n    match goal with\n      | [ H : forall _ : packet , _ |- _ ] =>\n        do 7 insterU H;\n          conclude H ltac:(unfold deghost; simpl; eapply in_map_iff; eexists; eauto);\n          conclude H ltac:(simpl; eauto)\n    end.\n    rename net into net0.\n    intuition.\n    - rewrite <- deghost_spec with (net := net0).\n      eapply H3 with (e1:=e1)(e2:=e2); eauto.\n      rewrite deghost_spec.  auto.\n    - rewrite <- deghost_spec with (net := net0).\n      eapply H3 with (e1:=e1)(e2:=e2); eauto.\n      rewrite deghost_spec.  auto.\n  Qed.\n\n  Ltac use_log_matching_nw :=\n    pose proof (lifted_log_matching_nw _ ltac:(eauto));\n    match goal with\n      | [ H : _  |- _ ] =>\n        eapply H; [|eauto];\n        repeat find_rewrite; intuition\n    end.\n\n  Lemma handleAppendEntries_doesn't_send_AE :\n    forall n st t i l t' l' l'' st' m,\n      handleAppendEntries n st t i l t' l' l'' = (st', m) ->\n      ~ is_append_entries m.\n  Proof using. \n    unfold handleAppendEntries.\n    intros.\n    repeat break_match; find_inversion; intro; break_exists; discriminate.\n  Qed.\n\n  Lemma leaderLogs_entries_match_append_entries :\n    refined_raft_net_invariant_append_entries leaderLogs_entries_match.\n  Proof using taifoi si llsi lmi rri. \n    unfold refined_raft_net_invariant_append_entries, leaderLogs_entries_match.\n    intuition.\n    - unfold leaderLogs_entries_match_host in *. intros.\n      {\n        intros. simpl in *. repeat find_higher_order_rewrite.\n        find_rewrite_lem update_fun_comm. simpl in *.\n        find_rewrite_lem update_fun_comm.\n        find_rewrite_lem update_elections_data_appendEntries_leaderLogs.\n        find_erewrite_lem update_nop_ext'.\n        update_destruct_simplify; rewrite_update;\n        try rewrite update_elections_data_appendEntries_leaderLogs in *; eauto.\n        destruct (log d) using (handleAppendEntries_log_ind ltac:(eauto)); eauto.\n        + subst. eapply @entries_match_scratch with (plt := plt).\n          * eauto using lifted_logs_sorted_nw.\n          * apply sorted_uniqueIndices.\n            eapply leaderLogs_sorted_invariant; eauto.\n          * eapply_prop leaderLogs_entries_match_nw; eauto.\n          * use_log_matching_nw.\n          * use_log_matching_nw.\n          * match goal with\n              | [ H : In _ (leaderLogs _) |- _ ] =>\n                eapply terms_and_indices_from_one_invariant in H; [|solve[auto]]\n            end.\n            unfold terms_and_indices_from_one in *. intros.\n            find_apply_hyp_hyp. intuition.\n        + eapply entries_match_append; eauto.\n          * eauto using lifted_logs_sorted_host.\n          * eapply leaderLogs_sorted_invariant; eauto.\n          * eauto using lifted_logs_sorted_nw.\n          * use_log_matching_nw.\n          * use_log_matching_nw.\n          * eapply findAtIndex_intro; eauto using lifted_logs_sorted_host, sorted_uniqueIndices.\n      }\n    - (* nw *)\n      unfold leaderLogs_entries_match_nw in *.\n      intros. simpl in *. repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      find_rewrite_lem update_fun_comm.\n      find_rewrite_lem update_elections_data_appendEntries_leaderLogs.\n      find_erewrite_lem update_nop_ext'.\n      find_apply_hyp_hyp. break_or_hyp.\n      + intuition; match goal with\n            | [ H : _ |- _ ] => solve [eapply (H _ _ _ p0); eauto with *]\n          end.\n      + simpl in *.\n        find_copy_apply_lem_hyp handleAppendEntries_doesn't_send_AE.\n        exfalso. eauto 10.\n  Qed.\n\n  Lemma leaderLogs_entries_match_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; simpl; intros;\n      repeat find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto.\n      erewrite handleAppendEntriesReply_same_log by eauto. auto.\n    - eapply leaderLogs_entries_match_nw_packet_set; eauto; simpl.\n      + intros. find_apply_hyp_hyp. repeat find_rewrite. intuition; [eauto with *|].\n        find_apply_lem_hyp handleAppendEntriesReply_packets. subst. simpl in *. intuition.\n      + intros. repeat find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto; find_rewrite; auto.\n  Qed.\n\n  Lemma handleRequestVote_packets :\n    forall h st t candidate lli llt st' m,\n      handleRequestVote h st t candidate lli llt = (st', m) ->\n      ~ is_append_entries m.\n  Proof using. \n    intros. unfold handleRequestVote, advanceCurrentTerm in *.\n    repeat break_match; find_inversion;\n    subst; intuition; break_exists; congruence.\n  Qed.\n\n  Lemma leaderLogs_entries_match_request_vote :\n    refined_raft_net_invariant_request_vote leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; simpl; intros;\n      repeat find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto.\n      + now rewrite leaderLogs_update_elections_data_requestVote.\n      + erewrite handleRequestVote_log; eauto.\n    - eapply leaderLogs_entries_match_nw_packet_set; eauto; simpl.\n      + intros. find_apply_hyp_hyp. repeat find_rewrite. intuition; [eauto with *|].\n        find_apply_lem_hyp handleRequestVote_packets. subst. simpl in *. intuition.\n      + intros. repeat find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto.\n        now rewrite leaderLogs_update_elections_data_requestVote.\n  Qed.\n\n  Lemma leaderLogs_entries_match_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply leaderLogs_entries_match.\n  Proof using lmi rri. \n    unfold refined_raft_net_invariant_request_vote_reply, leaderLogs_entries_match.\n    intuition.\n    - unfold leaderLogs_entries_match_host in *.\n      intros. simpl in *. subst.\n      repeat find_higher_order_rewrite.\n      rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      rewrite update_nop_ext' by now rewrite handleRequestVoteReply_same_log.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      update_destruct_simplify; rewrite_update; eauto.\n      find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n      intuition eauto.\n      subst.\n      rewrite handleRequestVoteReply_same_log.\n      apply lifted_log_matching_host. auto.\n    - unfold leaderLogs_entries_match_nw in *.\n      intros. simpl in *. subst.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      find_rewrite_lem update_fun_comm.\n      update_destruct_simplify; rewrite_update.\n      + find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n        break_or_hyp.\n        * repeat find_reverse_rewrite. eauto.\n        * break_and. subst.\n          rewrite handleRequestVoteReply_same_log.\n          find_rewrite_lem handleRequestVoteReply_same_log.\n          pose proof (lifted_log_matching_nw _ ltac:(eauto)).\n          repeat find_reverse_rewrite.\n          match goal with\n            | [ H : _, pkt : packet  |- _ ] =>\n              solve [eapply H with (p := pkt); eauto]\n          end.\n      + repeat find_reverse_rewrite. eauto.\n  Qed.\n\n  Lemma doLeader_messages :\n    forall st h os st' ms,\n      doLeader st h = (os, st', ms) ->\n      ms = [] \\/\n      ms = map (replicaMessage st' h)\n               (filter (fun h' : name => if name_eq_dec h h' then false else true)\n                       nodes).\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_do_leader :\n    refined_raft_net_invariant_do_leader leaderLogs_entries_match.\n  Proof using llci si llsi rri. \n    unfold refined_raft_net_invariant_do_leader, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; simpl; intros;\n      find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto.\n      + find_rewrite. auto.\n      + erewrite doLeader_same_log by eauto. find_rewrite. auto.\n    - unfold leaderLogs_entries_match_nw in *. intros. simpl in *.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      match goal with\n        | [ H : _ |- _ ] =>\n          rewrite update_nop_ext' in H by (find_rewrite; auto)\n      end.\n      find_apply_hyp_hyp. break_or_hyp.\n      + find_reverse_rewrite. eauto.\n      + do_in_map. subst. simpl in *.\n        find_copy_apply_lem_hyp doLeader_messages.\n        break_or_hyp.\n        * simpl in *. intuition.\n        * do_in_map. find_apply_lem_hyp filter_In.\n          break_and. break_if; try discriminate.\n          unfold replicaMessage in *. subst. simpl in *. find_inversion.\n          { intuition.\n            - repeat find_erewrite_lem doLeader_same_log.\n              eapply_prop leaderLogs_entries_match_host; eauto.\n              + match goal with\n                  | [ H : _ |- _ ] => rewrite H\n                end. simpl.\n                eauto using findGtIndex_in.\n              + auto with *.\n              + find_rewrite. simpl. eauto using findGtIndex_in.\n            - find_copy_apply_lem_hyp leaderLogs_contiguous_invariant; auto.\n              unfold contiguous_range_exact_lo in *. break_and.\n              match goal with\n                | [ H : forall _, _ < _ <= _ -> _ |- context [eIndex _ = ?x]] =>\n                  remember (x) as index;\n                  specialize (H index); forward H\n              end.\n              + intuition; auto using Nat.neq_0_lt_0.\n                find_apply_lem_hyp findGtIndex_necessary. break_and.\n                eapply Nat.le_trans.\n                * apply Nat.lt_le_incl. eauto.\n                * repeat find_rewrite. eapply maxIndex_is_max; auto.\n                  eapply leaderLogs_sorted_invariant; eauto.\n              + concludes. break_exists_exists. intuition.\n                match goal with\n                  | [ H : context [leaderLogs_entries_match_host],\n                     H' : context [leaderLogs] |- _ ] =>\n                    eapply H with (h := src)(e := e1)(e' := e2)(e'' := x) in H'; auto\n                end.\n                * pose proof lifted_logs_sorted_host net src ltac:(auto).\n                  repeat find_rewrite. simpl in *.\n                  repeat find_erewrite_lem doLeader_same_log.\n                  erewrite doLeader_same_log by eauto.\n                  erewrite findAtIndex_intro; eauto using sorted_uniqueIndices.\n                * find_apply_lem_hyp findGtIndex_necessary. break_and.\n                  repeat find_erewrite_lem doLeader_same_log.\n                  repeat find_rewrite. simpl in *.\n                  auto.\n                * find_apply_lem_hyp findGtIndex_necessary. break_and.\n                  lia.\n          }\n  Qed.\n\n  Lemma doGenericServer_packets :\n    forall h st os st' ps,\n      doGenericServer h st = (os, st', ps) ->\n      ps = [].\n  Proof using. \n    intros. unfold doGenericServer in *.\n    repeat break_match; find_inversion; subst; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_do_generic_server :\n    refined_raft_net_invariant_do_generic_server leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; simpl; intros;\n      find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto.\n      + find_rewrite. auto.\n      + erewrite doGenericServer_log by eauto. find_rewrite. auto.\n    - eapply leaderLogs_entries_match_nw_packet_set; eauto; simpl.\n      + intros. find_apply_hyp_hyp. intuition.\n        find_apply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n      + intros. find_higher_order_rewrite; update_destruct_simplify; rewrite_update; auto; find_rewrite; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, leaderLogs_entries_match.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; intros; find_higher_order_rewrite; auto.\n    - eapply leaderLogs_entries_match_nw_packet_set; eauto; intros; find_higher_order_rewrite; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_reboot :\n    refined_raft_net_invariant_reboot leaderLogs_entries_match.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, leaderLogs_entries_match, reboot.\n    intuition.\n    - eapply leaderLogs_entries_match_host_state_same; eauto; intros; find_higher_order_rewrite;\n      update_destruct_simplify; rewrite_update; auto; find_rewrite; auto.\n    - eapply leaderLogs_entries_match_nw_packet_set; eauto; try find_rewrite; intuition.\n      find_higher_order_rewrite; update_destruct_simplify; rewrite_update; try find_rewrite; auto.\n  Qed.\n\n  Lemma leaderLogs_entries_match_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leaderLogs_entries_match net.\n  Proof using taifoi llci llsli si llsi lltsi lmi rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply leaderLogs_entries_match_init.\n    - apply leaderLogs_entries_match_client_request.\n    - apply leaderLogs_entries_match_timeout.\n    - apply leaderLogs_entries_match_append_entries.\n    - apply leaderLogs_entries_match_append_entries_reply.\n    - apply leaderLogs_entries_match_request_vote.\n    - apply leaderLogs_entries_match_request_vote_reply.\n    - apply leaderLogs_entries_match_do_leader.\n    - apply leaderLogs_entries_match_do_generic_server.\n    - apply leaderLogs_entries_match_state_same_packet_subset.\n    - apply leaderLogs_entries_match_reboot.\n  Qed.\n\n  Instance lllmi : leaderLogs_entries_match_interface : Prop.\n  Proof.\n    split.\n    apply leaderLogs_entries_match_invariant.\n  Qed.\nEnd LeaderLogsLogMatching.\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/LeaderLogsLogMatchingProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.18384634422629947}}
{"text": "Require Import VST.veric.rmaps.\nRequire Import VST.concurrency.conclib.\nRequire Import VST.floyd.library.\nImport FashNotation.\n\n(* lock invariants should be exclusive *)\nClass lock_impl := { t_lock : type; lock_handle : Type; ptr_of : lock_handle -> val;\n  lock_inv : share -> lock_handle -> mpred -> mpred;\n  lock_inv_nonexpansive : forall sh h, nonexpansive (lock_inv sh h);\n  lock_inv_share_join : forall sh1 sh2 sh3 h R, sh1 <> Share.bot -> sh2 <> Share.bot ->\n    sepalg.join sh1 sh2 sh3 -> lock_inv sh1 h R * lock_inv sh2 h R = lock_inv sh3 h R;\n  lock_inv_exclusive : forall sh h R, exclusive_mpred (lock_inv sh h R);\n  lock_inv_isptr : forall sh h R, lock_inv sh h R |-- !! isptr (ptr_of h) }.\n\nSection lock_specs.\n\n  Context {LI : lock_impl}.\n\n  Lemma lock_inv_nonexpansive2 : forall {A} (P Q : A -> mpred) sh p x, (ALL x : _, |> (P x <=> Q x) |--\n    |> lock_inv sh p (P x) <=> |> lock_inv sh p (Q x))%logic.\n  Proof.\n    intros.\n    apply allp_left with x.\n    eapply derives_trans, eqp_later1; apply later_derives.\n    apply nonexpansive_entail; apply lock_inv_nonexpansive.\n  Qed.\n\n  Lemma lock_inv_super_non_expansive : forall sh h R n,\n    compcert_rmaps.RML.R.approx n (lock_inv sh h R) = compcert_rmaps.RML.R.approx n (lock_inv sh h (compcert_rmaps.RML.R.approx n R)).\n  Proof.\n    intros; apply nonexpansive_super_non_expansive, lock_inv_nonexpansive.\n  Qed.\n\n  Notation InvType := Mpred.\n\n  (* R should be able to take the lock_handle as an argument, with subspecs for plain and selflock *)\n  Program Definition makelock_spec :=\n    TYPE (ProdType (ConstType globals) (ArrowType (ConstType lock_handle) InvType)) WITH gv: _, R : _\n    PRE [ ]\n       PROP ()\n       PARAMS () GLOBALS (gv)\n       SEP (mem_mgr gv)\n    POST [ tptr t_lock ] EX h,\n       PROP ()\n       RETURN (ptr_of h)\n       SEP (mem_mgr gv; lock_inv Tsh h (R h)).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x; simpl.\n    reflexivity.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x; simpl.\n    rewrite !approx_exp; f_equal; extensionality.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal; apply lock_inv_super_non_expansive.\n  Qed.\n\n  Program Definition freelock_spec :=\n    TYPE (ProdType (ProdType (ConstType _) InvType) Mpred)\n    WITH h : _, R : _, P : _\n    PRE [ tptr t_lock ]\n     PROP ()\n     PARAMS (ptr_of h)\n     SEP (lock_inv Tsh h R; P; (P * lock_inv Tsh h R * R -* FF) && emp)\n   POST[ tvoid ]\n     PROP ()\n     LOCAL ()\n     SEP (P).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 3 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal.\n    { apply lock_inv_super_non_expansive. }\n    f_equal.\n    rewrite !approx_andp; f_equal.\n    setoid_rewrite wand_nonexpansive; rewrite !approx_sepcon; do 2 f_equal; rewrite !approx_idem; auto.\n    do 2 f_equal; apply lock_inv_super_non_expansive.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    reflexivity.\n  Qed.\n\n  Program Definition freelock_spec_simple :=\n    TYPE (ProdType (ConstType _) InvType)\n    WITH h : _, R : _\n    PRE [ tptr t_lock ]\n     PROP ()\n     PARAMS (ptr_of h)\n     SEP (weak_exclusive_mpred R && emp; lock_inv Tsh h R; R)\n   POST[ tvoid ]\n     PROP ()\n     LOCAL ()\n     SEP (R).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x; simpl.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 3 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal.\n    { rewrite !approx_andp; f_equal.\n      apply exclusive_mpred_super_non_expansive. }\n    f_equal. apply lock_inv_super_non_expansive.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x; simpl.\n    unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    reflexivity.\n  Qed.\n\n  Lemma freelock_simple : funspec_sub freelock_spec freelock_spec_simple.\n  Proof.\n    unfold funspec_sub; simpl.\n    split; auto; intros ? (h, R) ?; Intros.\n    eapply derives_trans, fupd_intro.\n    Exists (nil : list Type) (h, R, R) emp; entailer!.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; entailer!.\n    apply andp_right, andp_left2; auto.\n    rewrite <- wand_sepcon_adjoint; sep_apply weak_exclusive_conflict; auto.\n    rewrite FF_sepcon; auto.\n  Qed.\n\n  Program Definition acquire_spec :=\n    TYPE (ProdType (ConstType _) InvType)\n    WITH sh : _, h : _, R : _\n    PRE [ tptr t_lock ]\n       PROP (sh <> Share.bot)\n       PARAMS (ptr_of h)\n       SEP (lock_inv sh h R)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (lock_inv sh h R; R).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 3 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    apply lock_inv_super_non_expansive.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal. apply lock_inv_super_non_expansive.\n  Qed.\n\n  Program Definition release_spec :=\n    TYPE (ProdType (ProdType (ProdType (ConstType _) InvType) Mpred) Mpred)\n    WITH sh : _, h : _, R : _, P : _, Q : _\n    PRE [ tptr t_lock ]\n       PROP (sh <> Share.bot)\n       PARAMS (ptr_of h)\n       SEP (weak_exclusive_mpred R && emp; |> lock_inv sh h R; P; lock_inv sh h R * P -* Q * R)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (Q).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((((?, ?), ?), ?), ?); simpl.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 3 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal.\n    { rewrite !approx_andp; f_equal.\n      apply exclusive_mpred_super_non_expansive. }\n    f_equal.\n    { setoid_rewrite later_nonexpansive; do 2 f_equal.\n      apply lock_inv_super_non_expansive. }\n    f_equal.\n    setoid_rewrite wand_nonexpansive; rewrite !approx_sepcon; do 2 f_equal; rewrite !approx_idem; f_equal.\n    apply lock_inv_super_non_expansive.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((((?, ?), ?), ?), ?); simpl.\n    unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    reflexivity.\n  Qed.\n\n  Program Definition release_spec_simple :=\n    TYPE (ProdType (ConstType _) InvType)\n    WITH sh : _, h : _, R : _\n    PRE [ tptr t_lock ]\n       PROP (sh <> Share.bot)\n       PARAMS (ptr_of h)\n       SEP (weak_exclusive_mpred R && emp; lock_inv sh h R; R)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (lock_inv sh h R).\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; rewrite !approx_andp; do 3 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    f_equal.\n    { rewrite !approx_andp; f_equal.\n      apply exclusive_mpred_super_non_expansive. }\n    f_equal.\n    apply lock_inv_super_non_expansive.\n  Qed.\n  Next Obligation.\n  Proof.\n    repeat intro.\n    destruct x as ((?, ?), ?); simpl.\n    unfold PROPx, LOCALx, SEPx; simpl; rewrite !approx_andp; do 2 f_equal;\n      rewrite -> !sepcon_emp, ?approx_sepcon, ?approx_idem.\n    apply lock_inv_super_non_expansive.\n  Qed.\n\n  Lemma release_simple : funspec_sub release_spec release_spec_simple.\n  Proof.\n    unfold funspec_sub; simpl.\n    split; auto; intros ? ((sh, h), R) ?; Intros.\n    eapply derives_trans, fupd_intro.\n    Exists (nil : list Type) (sh, h, R, R, lock_inv sh h R) emp; entailer!.\n    unfold PROPx, PARAMSx, GLOBALSx, LOCALx, SEPx, argsassert2assert; simpl; entailer!.\n    apply wand_refl_cancel_right.\n  Qed.\n\nEnd lock_specs.\n\n#[export] Hint Resolve lock_inv_isptr : saturate_local.\n#[export] Hint Resolve lock_inv_exclusive data_at_exclusive data_at__exclusive field_at_exclusive field_at__exclusive : core.\n\nLtac lock_props := match goal with |-context[weak_exclusive_mpred ?P && emp] => sep_apply (exclusive_weak_exclusive P); [auto with share | try timeout 20 cancel] end.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/lock_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.304041668660366, "lm_q1q2_score": 0.1836204424831551}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.logic.PTrees.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.PTreeLayers.\nRequire Import liblayers.logic.PTreeSemantics.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Export liblayers.compat.CompatLayerDef.\nRequire Import liblayers.compcertx.Observation.\n\n(** * Semantics of languages *)\n\nSection COMPAT_SEMANTICS.\n  Context `{Hobs: Observation}.\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel} `{Hmem': !UseMemWithData mem}.\n  Context {F: Type}.\n  Local Existing Instance ptree_module_ops.\n  Local Existing Instance ptree_module_prf.\n  Context `{fsem_ops: !FunctionSemanticsOps _ _ _ _ (ptree_module F _) compatlayer}.\n  Context `{Hfsem: !FunctionSemantics _ _ _ _ (ptree_module F _) compatlayer}.\n\n  Section COMPAT_SEMANTICS_DEF.\n  Local Existing Instance ptree_layer_sim_op.\n  Local Existing Instance ptree_layer_ops.\n  Local Existing Instance ptree_layer_prf.\n  Local Existing Instance ptree_semof.\n  Local Existing Instance ptree_semantics_ops.\n  Local Existing Instance ptree_semantics_prf.\n\n  (** In order to use the theorems about [ptree_layer]s, we need to\n    come up with a corresponding version of the [FunctionSemantics]\n    instance. *)\n\n  Local Instance compat_ptree_fsem_ops:\n    FunctionSemanticsOps _ F compatsem (globvar type)\n      (ptree_module _ _)\n      (ptree_layer _ _) :=\n    {\n      semof_fundef D M L i \u03ba :=\n        semof_fundef D M (cl_inj L) i \u03ba\n    }.\n\n  Local Instance compat_ptree_fsem_prf:\n    FunctionSemantics _ F compatsem (globvar type)\n      (ptree_module _ _)\n      (ptree_layer _ _).\n  Proof.\n    split.\n    * intros D1 D2 R M1 M2 HM L1 L2 HL i \u03ba.\n      simpl semof_fundef.\n      apply semof_fundef_sim_monotonic; eauto.\n      split; simpl.\n      - assumption.\n      - repeat constructor.\n      - repeat constructor.\n    (*\n    * intros.\n      destruct Hfsem.\n      specialize (semof_fundef_vcomp D M (cl_inj L) i \u03bai \u03c3i j \u03baj).\n      apply semof_fundef_vcomp; simpl; assumption.\n    *)\n  Qed.\n\n  (** ** [Semantics] *)\n\n  Local Instance compat_semof: Semof (ptree_module _ _) compatlayer compatlayer :=\n    {\n      semof D M L := cl_inj (\u301aM\u301b L)\n    }.\n\n  Local Instance compat_semantics_ops:\n    SemanticsOps ident F compatsem _ (ptree_module _ _) compatlayer := {}.\n\n  (** FIXME: the following is heavily copy-and-pasted from\n    PTreeSemantics.v, we should figure out a way to avoid this. *)\n\n  Local Existing Instance ptree_module_prf.\n  Local Existing Instance ptree_layer_prf.\n  Local Existing Instance ptree_semof.\n  Local Transparent ptree_layer_ops.\n  Local Transparent ptree_module ptree_module_ops.\n  Local Transparent ptree_layer ptree_layer_ops.\n  Local Opaque PTree.combine.\n\n  Lemma compat_semantics_monotonic:\n    Proper (\u2200 -, (\u2264) ++> (\u2264) ++> - ==> - ==> res_le (\u2264)) semof_fundef ->\n    Proper (\u2200 -, (\u2264) ++> (\u2264) ++> (\u2264)) semof.\n  Proof.\n    intros H D M1 M2 HM L1 L2 HL.\n    simpl.\n    solve_monotonic.\n  Qed.\n\n  Lemma compat_semantics_sim_monotonic:\n    Proper (\u2200 R, (\u2264) ++> sim R ++> - ==> - ==> res_le (sim R)) semof_fundef ->\n    Proper (\u2200 R, (\u2264) ++> sim R ++> sim R) semof.\n  Proof.\n    intros H D1 D2 R M1 M2 HM L1 L2 HL.\n    simpl.\n    apply cl_inj_sim_monotonic.\n    apply ptree_semantics_mapdef_sim_monotonic; eauto.\n  Qed.\n\n  (*\n  Lemma compat_semantics_vcomp D M N (L: compatlayer D):\n    (forall i (\u03bai : F) (\u03c3i : compatsem D) j (\u03baj : F),\n       get_layer_primitive i L = OK None ->\n       get_layer_globalvar i L = OK None ->\n       semof_fundef D M L i \u03bai = OK \u03c3i ->\n       (res_le (\u2264))\n         (semof_fundef D M (L \u2295 i \u21a6 \u03c3i) j \u03baj)\n         (semof_fundef D (M \u2295 i \u21a6 \u03bai) L j \u03baj)) ->\n    \u301aM\u301b (\u301aN\u301b L \u2295 L) \u2295 \u301aN\u301b L \u2264 \u301aM \u2295 N\u301b L.\n  *)\n\n  Lemma compat_semantics_hcomp D M N (L : compatlayer D):\n    \u301aM \u301b L \u2295 \u301aN \u301b L \u2264 \u301aM \u2295 N \u301b L.\n  Proof.\n    destruct M as [Mf Mv], N as [Nf Nv].\n    simpl.\n    constructor; simpl.\n    * constructor; simpl.\n      + intros i.\n        rewrite !PTree.gcombine by reflexivity.\n        rewrite !PTree.gmap.\n        rewrite !PTree.gcombine by reflexivity.\n        simpl.\n        destruct (Mf!i) as [[|]|], (Nf!i) as [[|]|];\n        simpl; monad_norm; simpl; repeat constructor.\n        - apply upper_bound.\n        - apply upper_bound.\n        - transitivity (Some (semof_fundef D (Mf, Mv) L i f)).\n          destruct (semof_fundef _ _ _ _ _); reflexivity.\n          monotonicity.\n          pose proof (semof_fundef_sim_monotonic D D id) as H;\n            simpl in H; apply H; clear H.\n          transitivity ((Mf, Mv) \u2295 (Nf, Nv)).\n          pose proof (left_upper_bound (Mf, Mv) (Nf, Nv)) as H;\n            simpl in H; apply H; clear H.\n          reflexivity.\n          change (sim id L L).\n          reflexivity.\n        - pose proof (semof_fundef_sim_monotonic D D id) as H;\n            simpl in H; apply H; clear H.\n          transitivity ((Mf, Mv) \u2295 (Nf, Nv)).\n          pose proof (right_upper_bound (Mf, Mv) (Nf, Nv)) as H;\n            simpl in H; apply H; clear H.\n          reflexivity.\n          change (sim id L L).\n          reflexivity.\n      + reflexivity.\n    * reflexivity.\n    * reflexivity.\n  Qed.\n\n  Lemma compat_get_semof_primitive {D} i (M: ptree_module F (globvar type)) (L: compatlayer D):\n    get_layer_primitive (layer := compatlayer) i (\u301aM\u301b L) = \n    semof_function M L i (get_module_function i M).\n  Proof.\n    apply ptree_get_semof_primitive.\n  Qed.\n\n  Local Instance compat_semantics_prf:\n    Semantics ident F compatsem _ (ptree_module _ _) compatlayer.\n  Proof.\n    split.\n    * apply compat_semantics_sim_monotonic.\n      apply semof_fundef_sim_monotonic.\n    * reflexivity.\n    * intros; apply compat_get_semof_primitive.\n    (*\n    * intros.\n      apply compat_semantics_vcomp.\n      (** For some reason that does not unify on its own *)\n      apply (semof_fundef_vcomp (FunctionSemantics := Hfsem)).\n    *)\n    * apply compat_semantics_hcomp.\n  Qed.\n\n  End COMPAT_SEMANTICS_DEF.\n\n  Local Existing Instance compat_semof.\n  Local Existing Instance compat_semantics_ops.\n  Local Existing Instance compat_semantics_prf.\n  Local Existing Instance compat_ptree_fsem_ops.\n  Local Existing Instance compat_ptree_fsem_prf.\n\n  (** Quick test of the decision procedure. *)\n  Goal\n    forall D,\n      module_layer_disjoint (D:=D) (F:=F)\n        (1%positive \u21a6 {| gvar_info := Tvoid;\n                          gvar_init := nil;\n                          gvar_readonly := false;\n                          gvar_volatile := false |})\n        (2%positive \u21a6 {| gvar_info := Tvoid;\n                         gvar_init := nil;\n                         gvar_readonly := false;\n                         gvar_volatile := false |}).\n  Proof.\n    intros D.\n    decision.\n  Qed.\n\n  (** Versions of [compat_semantics_spec_xxx] with [module_layer_disjoint]. *)\n\n  Lemma compat_semantics_spec_some_disj {D} M L i f:\n    get_module_function i M = OK (Some f) ->\n    get_layer_primitive i (\u301aM\u301b L) = fmap Some (semof_fundef D M L i f).\n  Proof.\n    intros HMi.\n    rewrite compat_get_semof_primitive.\n    rewrite HMi.\n    reflexivity.\n  Qed.\n\n  (** ** Instantiate the module system *)\n\n  Global Instance compat_ll_ops:\n    LayerLogicOps ident _ compatsem _ (ptree_module _ _) compatlayer :=\n      logic_impl_ops.\n\n  Global Instance compat_ll_prf:\n    LayerLogic ident _ compatsem _ (ptree_module _ _) compatlayer :=\n      logic_impl.\n\nEnd COMPAT_SEMANTICS.\n\n(** Fake [SimulationPaths] *)\n\nNotation path_inj R := R (only parsing).\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/liblayers/compat/CompatSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1835961159896625}}
{"text": "Require Import GhostSimulations.\nRequire Import Raft.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import RaftRefinementInterface.\nRequire Import CommonTheorems.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import LogsLeaderLogsInterface.\nRequire Import AppendEntriesRequestLeaderLogsInterface.\nRequire Import RefinedLogMatchingLemmasInterface.\nRequire Import AllEntriesLeaderLogsTermInterface.\nRequire Import LeaderLogsContiguousInterface.\nRequire Import OneLeaderLogPerTermInterface.\nRequire Import LeaderLogsSortedInterface.\nRequire Import TermSanityInterface.\nRequire Import AllEntriesTermSanityInterface.\n\nRequire Import AllEntriesLogInterface.\n\nSection AllEntriesLog.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {llli : logs_leaderLogs_interface}.\n  Context {aerlli : append_entries_leaderLogs_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {aellti : allEntries_leaderLogs_term_interface}.\n  Context {llci : leaderLogs_contiguous_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n  Context {llsi : leaderLogs_sorted_interface}.\n  Context {tsi : term_sanity_interface}.\n  Context {rri : raft_refinement_interface}.\n  Context {aetsi : allEntries_term_sanity_interface}.\n  \n\n  (* strategy : prove allEntries_log as inductive invariant, then\n     prove allEntries_leaderLogs inductive from that *)\n\n\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  Definition no_entries_past_current_term_host_lifted net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma no_entries_past_current_term_host_lifted_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      no_entries_past_current_term_host_lifted net.\n  Proof using rri tsi. \n    unfold no_entries_past_current_term_host_lifted.\n    pose proof deghost_spec.\n    do 4 intro.\n    repeat find_reverse_higher_order_rewrite.\n    eapply lift_prop; eauto.\n    intros.\n    find_apply_lem_hyp no_entries_past_current_term_invariant; eauto.\n  Qed.\n  \n(** Succeed iff [x] is in the list [ls], represented with left-associated nested tuples. *)\nLtac inList x ls :=\n  match ls with\n    | x => idtac\n    | (_, x) => idtac\n    | (?LS, _) => inList x LS\n  end.\n\n(** Try calling tactic function [f] on every element of tupled list [ls], keeping the first call not to fail. *)\nLtac app f ls :=\n  match ls with\n    | (?LS, ?X) => f X || app f LS || fail 1\n    | _ => f ls\n  end.\n\n(** Run [f] on every element of [ls], not just the first that doesn't fail. *)\nLtac all f ls :=\n  match ls with\n    | (?LS, ?X) => f X; all f LS\n    | (_, _) => fail 1\n    | _ => f ls\n  end.\n\n\n  Lemma appendEntries_haveNewEntries_false :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      haveNewEntries (snd (nwState net h)) es = false ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using rlmli. \n    intros.\n    unfold haveNewEntries in *. do_bool. intuition;\n      [unfold not_empty in *; break_match; subst; simpl in *; intuition; congruence|].\n    break_match; try congruence.\n    do_bool. find_apply_lem_hyp findAtIndex_elim. intuition.\n    assert (es <> nil) by (destruct es; subst; simpl in *; intuition; congruence).\n    find_eapply_lem_hyp maxIndex_non_empty.\n    break_exists. intuition.\n    find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n    match goal with\n      | H : In e es |- _ => copy_eapply maxIndex_is_max H; eauto\n    end.\n    repeat find_rewrite.\n    find_eapply_lem_hyp entries_match_nw_host_invariant; eauto.\n  Qed.\n  \n  Lemma maxIndex_le :\n    forall l1 l2,\n      sorted l1 ->\n      contiguous_range_exact_lo l1 0 ->\n      findAtIndex l1 (maxIndex l2) = None ->\n      l2 = nil\n      \\/ (exists e, In e l2 /\\ eIndex e = 0)\n      \\/ maxIndex l1 <= maxIndex l2.\n  Proof using. \n    intros. destruct l2; intuition.\n    simpl in *. right.\n    destruct l1; intuition.\n    find_copy_eapply_lem_hyp findAtIndex_None; simpl in *; eauto.\n    unfold contiguous_range_exact_lo in *.\n    simpl in *. intuition.\n    destruct (lt_eq_lt_dec 0 (eIndex e)); intuition; eauto.\n    destruct (lt_eq_lt_dec (eIndex e0) (eIndex e)); intuition.\n    exfalso. repeat break_if; do_bool; intuition.\n    match goal with\n      | H : forall _, _ < _ <= _ -> _ |- _ =>\n        specialize (H (eIndex e))\n    end; conclude_using omega.\n    simpl in *. break_exists. intuition; subst; intuition.\n    eapply findAtIndex_None; eauto.\n  Qed.\n\n  Lemma maxIndex_le' :\n    forall l1 l2 i,\n      sorted l1 ->\n      contiguous_range_exact_lo l1 0 ->\n      l2 <> nil ->\n      contiguous_range_exact_lo l2 i ->\n      findAtIndex l1 (maxIndex l2) = None ->\n      maxIndex l1 <= maxIndex l2.\n  Proof using. \n    intros. find_eapply_lem_hyp maxIndex_le; intuition; eauto.\n    break_exists. intuition.\n    unfold contiguous_range_exact_lo in *.\n    intuition.\n    find_insterU. conclude_using eauto. omega.\n  Qed.\n                                 \n  Lemma sorted_app_in_in :\n    forall l1 l2 e e',\n      sorted (l1 ++ l2) ->\n      In e l1 ->\n      In e' l2 ->\n      eIndex e' < eIndex e.\n  Proof using. \n    induction l1; intros; simpl in *; intuition; eauto.\n    subst. find_insterU. conclude_using ltac:(apply in_app_iff; intuition eauto).\n    intuition.\n  Qed.\n  \n  Lemma sorted_app_sorted_app_in1_in2 :\n    forall l1 l2 l3 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l3) ->\n      In e l1 ->\n      In e' (l2 ++ l3) ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  omega.\n  Qed.\n\n  Lemma sorted_app_sorted_app_in1_in2_prefix :\n    forall l1 l2 l3 l4 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l4) ->\n      Prefix l4 l3 ->\n      In e l1 ->\n      In e' (l2 ++ l4) ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    find_eapply_lem_hyp Prefix_In; [|eauto].\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto. omega.\n  Qed.\n  \n  Lemma sorted_app_in2_in2 :\n    forall l1 l2 e e',\n      sorted (l1 ++ l2) ->\n      In e' (l1 ++ l2) ->\n      In e l2 ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  omega.\n  Qed.\n\n  \n(*  Lemma sorted_app_in3_in4_prefix :\n    forall l1 l2 l3 l4 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l4) ->\n      Prefix l4 l3 ->\n      In e l3 ->\n      In e' (l2 ++ l4) ->\n      eIndex e' = eIndex e ->\n      In e' l4.\n  Proof.\n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  omega.\n  Qed.\n  *)\n  Lemma sorted_term_index_le :\n    forall l e e',\n      sorted l ->\n      In e l ->\n      In e' l ->\n      eTerm e' < eTerm e ->\n      eIndex e' <= eIndex e.\n  Proof using. \n    induction l; intros; simpl in *; intuition; subst_max; intuition.\n    - find_apply_hyp_hyp. intuition.\n    - find_apply_hyp_hyp. intuition.\n  Qed.\n  Lemma term_ne_in_l2 :\n    forall l e e' l1 l2,\n      sorted l ->\n      In e l ->\n      (forall e', In e' l -> eTerm e' <= eTerm e) ->\n      removeAfterIndex l (eIndex e) = l1 ++ l2 ->\n      (forall e', In e' l1 -> eTerm e' = eTerm e) ->\n      In e' l ->\n      eTerm e' <> eTerm e ->\n      In e' l2.\n  Proof using. \n    intros.\n    assert (eIndex e' <= eIndex e) by\n        (eapply sorted_term_index_le; eauto;\n         find_apply_hyp_hyp;\n         destruct (lt_eq_lt_dec (eTerm e') (eTerm e)); intuition).\n    find_eapply_lem_hyp removeAfterIndex_le_In; eauto.\n    repeat find_rewrite.\n    do_in_app. intuition.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma Prefix_maxIndex_eq :\n    forall l l',\n      Prefix l l' ->\n      l <> nil ->\n      maxIndex l = maxIndex l'.\n  Proof using. \n    intros.\n    induction l; simpl in *; intuition.\n    break_match; intuition. subst. simpl. auto.\n  Qed.\n\n  Lemma sorted_gt_maxIndex :\n    forall e l1 l2,\n      sorted (e :: l1 ++ l2) ->\n      l2 <> nil ->\n      maxIndex l2 < eIndex e.\n  Proof using. \n    intros; induction l1; simpl in *; intuition.\n    - destruct l2; simpl in *; intuition.\n      match goal with\n        | H : forall _, ?e = _ \\/ _ -> _ |- _ =>\n          specialize (H e)\n      end; intuition.\n  Qed.\n  \n  Lemma allEntries_log_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_log.\n  Proof using aetsi rri tsi llsi ollpti llci aellti rlmli aerlli llli. \n    red. unfold allEntries_log in *. simpl in *. intros.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    [|find_apply_hyp_hyp; intuition;\n      right; break_exists_exists; intuition;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *;\n      eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto].\n    find_eapply_lem_hyp update_elections_data_appendEntries_allEntries_detailed; eauto.\n    intuition;\n      [|repeat find_rewrite;\n         find_eapply_lem_hyp appendEntries_haveNewEntries_false; eauto].\n    find_copy_apply_hyp_hyp. intuition;\n      [|right; break_exists_exists; intuition;\n        repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n        try rewrite update_elections_data_appendEntries_leaderLogs; eauto; subst;\n        find_apply_lem_hyp handleAppendEntries_currentTerm_leaderId; intuition;\n        repeat find_rewrite; auto].\n    destruct (in_dec entry_eq_dec e (log d)); intuition.\n    right.\n    find_copy_apply_lem_hyp handleAppendEntries_log_detailed.\n    intuition; repeat find_rewrite; intuition.\n    - subst.\n      find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 (currentTerm d)); intuition; unfold ghost_data in *; simpl in *; try omega.\n      + find_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n        break_exists. break_and.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [repeat find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n          subst. repeat find_rewrite. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * subst. exfalso.\n          find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n          find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n          subst. clean.\n          repeat find_rewrite.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          find_copy_eapply_lem_hyp entries_sorted_invariant; eauto.\n          unfold entries_sorted in *.\n          repeat find_rewrite.\n          match goal with\n            | _ : removeAfterIndex ?l (eIndex ?e) = _ |- _ =>\n              assert (In e (removeAfterIndex l (eIndex e))) by\n                  (eapply removeAfterIndex_le_In; eauto)\n          end.\n          repeat find_rewrite.\n          do_in_app; intuition.\n          assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n              (eapply entries_contiguous_nw_invariant; eauto;\n               intuition; [eapply entries_contiguous_invariant; eauto|];\n               eapply le_trans; [eapply maxIndex_is_max; eauto|];\n               eapply maxIndex_le'; eauto;\n               [eapply entries_contiguous_invariant; eauto|\n                eapply entries_contiguous_nw_invariant; eauto]).\n          break_exists. intuition.\n          find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. Focus 5. eauto. Focus 4. eauto.\n          all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n          all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n          find_apply_hyp_hyp.\n          find_eapply_lem_hyp entries_match_nw_host_invariant; eauto; repeat conclude_using eauto.\n          match goal with\n            | H : eIndex _ = eIndex _ |- _ =>\n              eapply uniqueIndices_elim_eq in H\n          end; eauto using sorted_uniqueIndices.\n          subst. auto.\n        * exfalso.\n          find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n          subst. clean.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          repeat find_rewrite. apply in_app_iff; intuition.\n    - subst.\n      find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 (currentTerm d)); intuition; unfold ghost_data in *; simpl in *; try omega.\n      + find_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n        break_exists. break_and.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end. find_higher_order_rewrite.\n        split;\n          [subst; find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto.\n        intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n        subst. repeat find_rewrite. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists; intuition;\n            [break_exists; intuition;\n             find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n            subst. clean.\n            repeat find_rewrite.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_eapply_lem_hyp entries_sorted_invariant; eauto.\n            unfold entries_sorted in *.\n            repeat find_rewrite.\n            match goal with\n              | _ : removeAfterIndex ?l (eIndex ?e) = _ |- _ =>\n                assert (In e (removeAfterIndex l (eIndex e))) by\n                    (eapply removeAfterIndex_le_In; eauto)\n            end.\n            repeat find_rewrite.\n            do_in_app; intuition.\n            find_apply_lem_hyp findAtIndex_elim. intuition.\n            find_copy_apply_lem_hyp maxIndex_non_empty.\n            break_exists.\n            intuition.\n            match goal with\n              | _ : In ?e' (log _), _ : maxIndex ?l = eIndex ?e' |- _ =>\n                destruct (le_lt_dec (eIndex e) (maxIndex l))\n            end.\n            - assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n                  (eapply entries_contiguous_nw_invariant; eauto; intuition;\n                   eapply entries_gt_0_invariant; eauto).\n              break_exists. intuition.\n              find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. Focus 5. eauto. Focus 4. eauto.\n              all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n              all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n              find_apply_hyp_hyp.\n              find_eapply_lem_hyp entries_match_nw_host_invariant; eauto; repeat conclude_using eauto.\n              match goal with\n                | H : eIndex _ = eIndex _ |- _ =>\n                  eapply uniqueIndices_elim_eq in H\n              end; eauto using sorted_uniqueIndices.\n              subst. auto.\n            - exfalso.\n              repeat find_rewrite.\n              match goal with\n                | _ : eIndex ?e' = eIndex ?x,\n                  _ : eIndex ?x < ?i,\n                  _ : context [removeAfterIndex ?l ?i] |- _ =>\n                  assert (In e' (removeAfterIndex l i)) by\n                      (eapply removeAfterIndex_le_In; auto; omega)\n              end.\n              repeat find_rewrite.\n              do_in_app. intuition.\n              + find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. Focus 4. eauto.\n                all:eauto.\n                all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n                all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n                repeat find_apply_hyp_hyp. repeat find_rewrite. intuition.\n              + find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                find_copy_eapply_lem_hyp sorted_app_in2_in2. Focus 3. eauto.\n                all:eauto.\n                all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n                match goal with\n                  | H : eIndex ?e1 = eIndex ?e2, _ : In ?e1 ?ll, _ : In ?e2 ?ll |- _ =>\n                    eapply uniqueIndices_elim_eq with (xs0 := ll) in H\n                end; eauto using sorted_uniqueIndices.\n                subst. intuition.\n          }\n        * exfalso.\n          find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; omega|].\n          subst. clean.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          repeat find_rewrite. apply in_app_iff; intuition.\n    - find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 t); intuition; unfold ghost_data in *; simpl in *; try omega.\n      + match goal with\n          | H : context [pBody] |- _ =>\n            copy_eapply append_entries_leaderLogs_invariant H\n        end; eauto.\n        break_exists. break_and. subst.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto. intuition; subst.\n        * find_false.\n          apply in_app_iff. right. eapply removeAfterIndex_le_In; eauto.\n          find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n          eapply le_trans; [eapply maxIndex_is_max; eauto|]. omega.\n        * {\n            break_exists. intuition. unfold Prefix_sane in *. intuition.\n            - destruct (le_lt_dec (eIndex e) (eIndex x3)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                apply in_app_iff. right.\n                find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                eapply prefix_contiguous; eauto.\n                find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                eapply contiguous_app; eauto.\n                eapply entries_contiguous_nw_invariant; eauto.\n            - find_false.\n              repeat find_rewrite.\n              apply in_app_iff. right.\n              find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n              apply removeAfterIndex_le_In; auto.\n              eapply maxIndex_is_max; eauto.\n          }\n        * find_false. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists. break_and.\n            repeat find_rewrite.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto.\n            conclude_using eauto. subst. intuition.\n            - repeat find_rewrite.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                find_eapply_lem_hyp maxIndex_le'; eauto;\n                [|eapply entries_contiguous_invariant; eauto|eapply entries_contiguous_nw_invariant; eauto].\n                find_copy_eapply_lem_hyp entries_contiguous_nw_invariant; eauto.\n                unfold contiguous_range_exact_lo in *.\n                break_and.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                match goal with\n                  | H : forall _, _ < _ <= _ -> _ |- _ =>\n                    specialize (H (eIndex e));\n                      conclude_using ltac:(intuition; eapply le_trans; [eapply maxIndex_is_max; eauto|]; eauto)\n                end.\n                break_exists. break_and.\n                match goal with\n                  | H : eIndex ?x = eIndex e |- _ =>\n                    copy_eapply entries_match_nw_host_invariant H\n                end; eauto.\n                find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                conclude_using\n                  ltac:(match goal with\n                          | H : _ |- _ => apply H\n                        end; do_in_app; intuition;\n                        match goal with\n                          | H : In ?x _ |- In ?x _ =>\n                            copy_eapply Prefix_maxIndex H\n                        end; [|idtac|eauto]; eauto; omega).\n                conclude_using eauto. conclude_using auto.\n                match goal with\n                  | H : _ = _ |- _ =>\n                    eapply uniqueIndices_elim_eq in H\n                end; eauto; eauto using sorted_uniqueIndices.\n                subst. auto.\n            - break_exists. break_and.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | _ : removeAfterIndex _ (eIndex ?e) = ?l |- _ =>\n                    assert (In e l) by (repeat find_reverse_rewrite;\n                                        eapply removeAfterIndex_le_In; auto)\n                end.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x2)) by\n                      (eapply entries_contiguous_nw_invariant; eauto;\n                       intuition;\n                       eapply le_trans; [eapply maxIndex_is_max; eauto|];\n                       eapply maxIndex_le'; eauto;\n                       [eapply entries_contiguous_invariant; eauto|\n                        eapply entries_contiguous_nw_invariant; eauto]).\n                do_in_app. intuition.\n                * break_exists. break_and.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply sorted_app_sorted_app_in1_in2_prefix H\n                  end; eauto.\n                  all:try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted].\n                  all:try solve [eapply entries_sorted_nw_invariant; eauto].\n                  find_apply_hyp_hyp.\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end.\n                  apply in_app_iff. left.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply entries_match_nw_host_invariant H\n                  end; eauto. concludes. repeat conclude_using eauto.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply uniqueIndices_elim_eq H\n                  end; eauto using sorted_uniqueIndices. subst. auto.\n                * find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                  unfold Prefix_sane in *.\n                  intuition; [|find_eapply_lem_hyp maxIndex_is_max; eauto; omega].\n                  find_eapply_lem_hyp prefix_contiguous. Focus 2. eauto.\n                  all:eauto.\n                  all:try solve [eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n                                 eapply entries_sorted_nw_invariant; eauto].\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end. intuition.\n            - subst.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | _ : removeAfterIndex _ (eIndex ?e) = ?l |- _ =>\n                    assert (In e l) by (repeat find_reverse_rewrite;\n                                        eapply removeAfterIndex_le_In; auto)\n                end.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n                      (eapply entries_contiguous_nw_invariant; eauto;\n                       intuition;\n                       eapply le_trans; [eapply maxIndex_is_max; eauto|];\n                       eapply maxIndex_le'; eauto;\n                       [eapply entries_contiguous_invariant; eauto|\n                        eapply entries_contiguous_nw_invariant; eauto]).\n                do_in_app. intuition.\n                * break_exists. break_and.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply sorted_app_sorted_app_in1_in2 H\n                  end; eauto.\n                  all:try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted].\n                  all:try solve [eapply entries_sorted_nw_invariant; eauto].\n                  find_apply_hyp_hyp.\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end.\n                  apply in_app_iff. left.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply entries_match_nw_host_invariant H\n                  end; eauto. concludes. repeat conclude_using eauto.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply uniqueIndices_elim_eq H\n                  end; eauto using sorted_uniqueIndices. subst. auto.\n                * match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end. intuition.\n          }\n        * { exfalso.\n            find_copy_apply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists; intuition.\n            copy_eapply_prop_hyp append_entries_leaderLogs pBody; eauto.\n            break_exists; break_and.\n            subst. \n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_apply_lem_hyp leaderLogs_sorted_invariant; auto.\n            find_copy_apply_lem_hyp maxIndex_is_max; auto. \n            destruct (le_lt_dec (eIndex e) (eIndex x1));\n              [apply in_app_iff; right; eapply removeAfterIndex_le_In; eauto|].\n            repeat find_rewrite. apply in_app_iff; intuition.\n            - omega.\n            - break_exists; break_and.\n              unfold Prefix_sane in *. break_or_hyp; try omega.\n              left; apply in_app_iff; right.\n              eapply prefix_contiguous; eauto.\n              eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n              eapply entries_sorted_nw_invariant; eauto.\n            - subst. intuition.\n          }\n    - find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 t); intuition; unfold ghost_data in *; simpl in *; try omega.\n      + match goal with\n          | H : context [pBody] |- _ =>\n            copy_eapply append_entries_leaderLogs_invariant H\n        end; eauto.\n        break_exists. break_and. subst.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto. intuition; subst.\n        * find_false.\n          apply in_app_iff. right. eapply removeAfterIndex_le_In; eauto.\n          find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n          eapply le_trans; [eapply maxIndex_is_max; eauto|]. omega.\n        * {\n            break_exists. intuition. unfold Prefix_sane in *. intuition.\n            - destruct (le_lt_dec (eIndex e) (eIndex x4)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                apply in_app_iff. right.\n                find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                eapply prefix_contiguous; eauto.\n                find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                eapply contiguous_app; eauto.\n                eapply entries_contiguous_nw_invariant; eauto.\n            - find_false.\n              repeat find_rewrite.\n              apply in_app_iff. right.\n              find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n              apply removeAfterIndex_le_In; auto.\n              eapply maxIndex_is_max; eauto.\n          }\n        * find_false. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            find_copy_eapply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists. break_and.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto.\n            repeat find_rewrite.\n            conclude_using eauto. subst.\n            find_eapply_lem_hyp le_antisym; eauto.\n            destruct x1.\n            - simpl in *. destruct x2; simpl in *; auto.\n              break_match; auto.\n              match goal with\n                | H : _ \\/ (exists _, _) \\/ _ |- _ =>\n                  clear H\n              end.\n              break_and. subst.\n              cut (e1 = x6); intros; subst; auto.\n              find_apply_lem_hyp findAtIndex_elim.\n              break_and.\n              find_copy_apply_lem_hyp entries_sorted_invariant.\n              eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices.\n              eapply removeAfterIndex_in with (i := (eIndex e)).\n              unfold raft_data, ghost_data in *; simpl in *.\n              unfold raft_data, ghost_data in *; simpl in *.\n              repeat find_rewrite. intuition.\n            - simpl in *.\n              match goal with\n                | H : forall _, ?e = _ \\/ _ -> _ |- _ =>\n                  specialize (H e)\n              end. conclude_using auto.\n              repeat find_rewrite.\n              find_apply_lem_hyp findAtIndex_elim. break_and.\n              find_eapply_lem_hyp term_ne_in_l2. Focus 7. eauto. all:eauto.\n              all:try solve [eapply entries_sorted_invariant; eauto].\n              all:try solve [intros; find_eapply_lem_hyp no_entries_past_current_term_host_lifted_invariant; unfold ghost_data, raft_data in *; simpl in *;\n                             unfold ghost_data, raft_data in *; simpl in *;\n                             repeat find_rewrite; eauto].\n              assert (eIndex e0 <= maxIndex x4) by \n                  (repeat find_rewrite;\n                   eapply maxIndex_is_max; eauto;\n                   eapply leaderLogs_sorted_invariant; eauto).\n              assert (eIndex x7 < eIndex e0) by\n                  (eapply entries_contiguous_nw_invariant; eauto; intuition).\n              intuition.\n              + break_exists. break_and.\n                unfold Prefix_sane in *. intuition.\n                find_copy_eapply_lem_hyp Prefix_maxIndex_eq; eauto.\n                find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                find_eapply_lem_hyp sorted_gt_maxIndex; eauto; omega.\n              + subst.\n                find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                find_eapply_lem_hyp sorted_gt_maxIndex; eauto; try omega.\n                destruct x4; simpl in *; congruence.\n          }\n        * { exfalso.\n            find_copy_apply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists; intuition. subst.\n            copy_eapply_prop_hyp append_entries_leaderLogs pBody; eauto.\n            break_exists; break_and.\n            subst. \n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_apply_lem_hyp leaderLogs_sorted_invariant; auto.\n            find_copy_apply_lem_hyp maxIndex_is_max; auto. \n            destruct (le_lt_dec (eIndex e) (eIndex x2));\n              [apply in_app_iff; right; eapply removeAfterIndex_le_In; eauto|].\n            repeat find_rewrite. apply in_app_iff; intuition.\n            - omega.\n            - break_exists; break_and.\n              unfold Prefix_sane in *. break_or_hyp; try omega.\n              left; apply in_app_iff; right.\n              eapply prefix_contiguous; eauto.\n              eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n              eapply entries_sorted_nw_invariant; eauto.\n            - subst. intuition.\n          }\n  Qed.\n\n  Lemma handleAppendEntriesReply_currentTerm_leaderId :\n    forall h st h' t es res st' m,\n      handleAppendEntriesReply h st h' t es res = (st', m) ->\n      currentTerm st < currentTerm st' \\/\n      (currentTerm st = currentTerm st' /\\ leaderId st' = leaderId st).\n  Proof using. \n    intros. unfold handleAppendEntriesReply, advanceCurrentTerm in *.\n    repeat (break_match; try find_inversion; simpl in *; auto).\n  Qed.\n\n  Lemma allEntries_log_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log.\n    find_apply_lem_hyp handleAppendEntriesReply_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; repeat find_rewrite; intuition;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma update_elections_data_requestVote_leaderLogs :\n    forall h h' t lli llt st,\n      leaderLogs (update_elections_data_requestVote h h' t h' lli llt st) =\n      leaderLogs (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma update_elections_data_requestVoteReply_leaderLogs :\n    forall h h' t  st t' ll' r,\n      In (t', ll') (leaderLogs (fst st)) ->\n      In (t', ll') (leaderLogs (update_elections_data_requestVoteReply h h' t r st)).\n  Proof using. \n    unfold update_elections_data_requestVoteReply.\n    intros.\n    repeat break_match; auto.\n    simpl in *. intuition.\n  Qed.\n\n  Lemma allEntries_log_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp handleRequestVote_log.\n    find_apply_lem_hyp handleRequestVote_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto;\n    try find_rewrite_lem update_elections_data_requestVote_allEntries;\n    find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_requestVote_leaderLogs; auto.\n  Qed.\n\n  Lemma handleRequestVoteReply_log' :\n    forall h st h' t r,\n      log (handleRequestVoteReply h st h' t r) = log st.\n  Proof using. \n    eauto using handleRequestVoteReply_log.\n  Qed.\n\n  Lemma allEntries_log_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    find_copy_apply_lem_hyp handleRequestVoteReply_currentTerm_leaderId.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite handleRequestVoteReply_log';\n    try find_rewrite_lem update_elections_data_requestVoteReply_allEntries;\n    find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; repeat find_rewrite; intuition;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    apply update_elections_data_requestVoteReply_leaderLogs; auto.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries' :\n    forall h st client id c out st' ms t e,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      In (t, e) (allEntries (update_elections_data_client_request h st client id c)) ->\n      In (t, e) (allEntries (fst st)) \\/\n      In e (log st').\n  Proof using. \n    intros.\n    unfold update_elections_data_client_request in *.\n    repeat break_match; repeat find_inversion; auto.\n    simpl in *. intuition.\n    find_inversion. repeat find_rewrite. intuition.\n  Qed.\n\n  Lemma handleClientRequest_currentTerm_leaderId :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    subst.\n    break_match; try find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_client_request :\n    refined_raft_net_invariant_client_request allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    try (find_eapply_lem_hyp update_elections_data_client_request_allEntries'; eauto; [idtac]);\n    intuition;\n    find_copy_apply_lem_hyp handleClientRequest_log;\n    find_apply_lem_hyp handleClientRequest_currentTerm_leaderId;\n    intuition;\n    try break_exists; intuition; repeat find_rewrite; intuition; simpl in *;\n    find_apply_hyp_hyp; intuition; repeat right;\n    break_exists_exists; intuition;\n    repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_client_request_leaderLogs; auto.\n  Qed.\n\n  Lemma handleTimeout_currentTerm_leaderId :\n    forall h st out st' ms,\n      handleTimeout h st = (out, st', ms) ->\n      currentTerm st < currentTerm st' \\/\n      currentTerm st' = currentTerm st /\\ leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold handleTimeout, tryToBecomeLeader in *.\n    subst.\n    break_match; try find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_timeout :\n    refined_raft_net_invariant_timeout allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    try find_rewrite_lem update_elections_data_timeout_allEntries;\n    find_copy_apply_lem_hyp handleTimeout_log_same;\n    find_apply_lem_hyp handleTimeout_currentTerm_leaderId;\n    repeat find_rewrite;\n    find_apply_hyp_hyp; intuition;\n    right; break_exists_exists; intuition;\n    repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_timeout_leaderLogs; auto.\n  Qed.\n\n  Lemma doLeader_currentTerm_leaderId :\n    forall st h out st' m,\n      doLeader st h = (out, st', m) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp doLeader_log.\n    find_apply_lem_hyp doLeader_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n\n  Lemma doGenericServer_currentTerm_leaderId :\n    forall st h out st' m,\n      doGenericServer h st = (out, st', m) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold doGenericServer in *.\n    repeat break_match; find_inversion;\n    use_applyEntries_spec; subst; simpl in *;\n    auto.\n  Qed.\n  \n  Lemma allEntries_log_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp doGenericServer_log.\n    find_apply_lem_hyp doGenericServer_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_log_init :\n    refined_raft_net_invariant_init allEntries_log.\n  Proof using. \n    red. unfold allEntries_log. intros. simpl in *. intuition.\n  Qed.\n\n  Lemma allEntries_log_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros.\n    repeat find_reverse_higher_order_rewrite.\n    find_apply_hyp_hyp. intuition. right.\n    break_exists_exists. repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma allEntries_log_reboot :\n    refined_raft_net_invariant_reboot allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    subst. unfold reboot in *.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_log_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      allEntries_log net.\n  Proof using aetsi rri tsi llsi ollpti llci aellti rlmli aerlli llli. \n    intros. apply refined_raft_net_invariant; auto.\n    - exact allEntries_log_init.\n    - exact allEntries_log_client_request.\n    - exact allEntries_log_timeout.\n    - exact allEntries_log_append_entries.\n    - exact allEntries_log_append_entries_reply.\n    - exact allEntries_log_request_vote.\n    - exact allEntries_log_request_vote_reply.\n    - exact allEntries_log_do_leader.\n    - exact allEntries_log_do_generic_server.\n    - exact allEntries_log_state_same_packet_subset.\n    - exact allEntries_log_reboot.\n  Qed.\n\n  Instance aeli : allEntries_log_interface.\n  split. eauto using allEntries_log_invariant.\n  Defined.\nEnd AllEntriesLog.", "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/AllEntriesLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33807712415000574, "lm_q1q2_score": 0.18352965758159076}}
{"text": "Require Import List DepList.\nRequire Import Heaps.\nRequire Import Expr SepExpr SymEval.\n\nModule EvaluatorTests (B : Heap) (ST : SepTheoryX.SepTheoryXType B).\n  Module Import SE := Evaluator B ST.\n\n  Section Tests.\n    Variable a b : Type.\n\n    Variable ptsto32 : B.addr -> W -> ST.hprop a b nil.\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 addr_type : Expr.type :=\n      {| Expr.Impl := B.addr \n       ; Expr.Eq := fun x y => match B.addr_dec x y with\n                                 | left pf => Some pf\n                                 | right _ => None\n                               end\n       |} .\n\n    Definition W_type : Expr.type :=\n      {| Expr.Impl := W\n       ; Expr.Eq := fun x y => match equiv_dec x y with\n                                 | left pf => Some pf\n                                 | right _ => None\n                               end\n       |}.\n\n    Definition a_type : Expr.type :=\n      {| Expr.Impl := a \n       ; Eq := fun _ _ => None\n       |}.   \n    Definition b_type : Expr.type :=\n      {| Expr.Impl := b\n       ; Eq := fun _ _ => None\n       |}.\n\n    Require Import Word.\n\n    Definition pre_types : list Expr.type := \n      a_type :: b_type :: addr_type :: W_type :: nil.\n\n    (** I need to universally quantify SymEval_word over the functions list\n     **\n     **)\n\n    Definition funcs : functions (wtypes pre_types 2 3) := nil.\n\n    Definition sfuncs : list (SEP.ssignature (wtypes pre_types 2 3) (tvType 0) (tvType 1)) :=\n      {| SDomain := tvType 2 :: tvType 3 :: nil\n       ; SDenotation := ptsto32 : functionTypeD\n         (map (tvarD (wtypes pre_types 2 3)) (tvType 2 :: tvType 3 :: nil))\n         (ST.hprop (tvarD (wtypes pre_types 2 3) (tvType 0))\n           (tvarD (wtypes pre_types 2 3) (tvType 1)) nil)\n       |} :: nil.\n    \n    Definition Satisfies cs stn (P : ST.hprop a b nil) m : Prop :=\n      exists sm, \n          ST.satisfies cs P stn sm\n       /\\ ST.HT.satisfies sm m.\n\n    Theorem addr_not_state : 3 <> 2.\n      clear; auto.\n    Qed.\n\n    Definition known : list nat := 0 :: nil.\n\n    Definition evaluators : DepList.hlist (fun n : nat => match nth_error sfuncs n with\n                                                            | None => Empty_set \n                                                            | Some ss => \n                                                              SymEval_word pre_types addr_not_state\n                                                                funcs\n                                                                (pcIndex := 0) (stateIndex := 1) ss\n                                                          end) known.\n      refine (DepList.HCons _ DepList.HNil); simpl.\n      refine (\n        {| sym_read_word := fun _ args p => \n           match args with\n             | p' :: v :: nil => \n               if seq_dec p p' then Some v else None\n             | _ => None\n           end\n         ; sym_write_word := fun _ args p v =>\n           match args with\n             | p' :: v' :: nil => \n               if seq_dec p p' then Some (p' :: v :: nil) else None\n             | _ => None\n           end\n         ; sym_read_word_correct := _\n         ; sym_write_word_correct := _\n         |}).\n      admit.\n      admit.\n    Defined.\n\n    Ltac lift_evaluator_w e nt nf :=\n      let r := eval simpl sym_read_word in (sym_read_word e) in\n      let w := eval simpl sym_write_word in (sym_write_word e) in\n      let rc := eval simpl sym_read_word_correct in (sym_read_word_correct e) in\n      let wc := eval simpl sym_write_word_correct in (sym_write_word_correct e) in\n      match type of e with\n        | SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ ?s =>\n          match SE.SEP.lift_ssignatures (s :: nil) nt with\n            | ?s' :: nil =>\n              constr:(@Build_SymEval_word nt stI pcI ptrI wI pf nf s' r w rc wc)\n          end\n      end.\n\n    Ltac lift_evaluators_w es nt nf ns :=\n      let rec lift es :=\n        match es with\n          | @DepList.HNil _ (fun n : nat => \n            match nth_error _ n with\n              | None => Empty_set\n              | Some ss => @SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ _ \n            end) =>\n            let k := \n              constr:(@DepList.HNil nat (fun n : nat =>\n                match nth_error ns n with\n                  | None => Empty_set\n                  | Some ss => @SymEval_word nt stI pcI ptrI wI pf nf ss\n                end))\n            in k \n          | @DepList.HCons _ (fun n : nat => \n            match nth_error _ n with\n              | None => Empty_set\n              | Some ss => @SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ _ \n            end) ?f ?ls ?e ?es =>\n          idtac \"ok\" ;\n            let es := lift es in\n              idtac \"here\" e ;\n            let e := lift_evaluator_w e nt nf in\n              idtac \"got here \" ;\n            constr:(@DepList.HCons _ (fun n : nat =>\n                match nth_error ns n with\n                  | None => Empty_set\n                  | Some ss => @SymEval_word nt stI pcI ptrI wI pf nf ss\n                end) f ls e es)\n        end\n      in\n      lift es.\n\n    Goal True.\n      Set Printing Implicit.\n      match goal with\n        | [ |- _ ] => \n          let z := eval unfold evaluators in evaluators in\n            idtac \"foo\" z ;\n          let r := lift_evaluators_w z pre_types funcs sfuncs in\n            idtac \"here\" ;\n            idtac r\n      end.\n\n            constr:(@DepList.HNil nat (fun n : nat => \n              match nth_error sfuncs n with\n                | None => Empty_set \n                | Some ss => \n                  SymEval_word nt addr_not_state\n                  funcs\n                  (pcIndex := 0) (stateIndex := 1) ss\n              end) nil)\n(*\n    Goal forall p1 p2 p3 v1 v2 v3 cs stn m,\n      Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v2) (ptsto32 p3 v3))) m\n      -> mem_get_word B.addr B.mem B.footprint_w B.mem_get (IL.implode stn) p1 m = Some v1.\n    Proof.\n      intros.\n      match goal with\n        | [ H : Satisfies ?CS ?STN ?P ?M\n          |- context [ mem_get_word B.addr B.mem B.footprint_w B.mem_get (IL.implode stn) ?PTR ?M ] ] =>\n        let Ts := constr:(@nil Type) in\n        let Ts := SEP.collectAllTypes_sexpr ltac:(isConst) Ts (P :: nil) in\n        let Ts := SEP.collectAllTypes_expr ltac:(isConst) Ts (PTR, tt) in\n        let types := eval unfold pre_types in pre_types in\n        let types := SEP.extend_all_types Ts types in\n        let sexprs := constr:(P :: nil) in\n        match SEP.reify_sexprs a b ltac:(isConst) types tt tt sexprs with\n          | (?types, ?pcType, ?stateType, ?funcs, ?sfuncs, ?P :: nil) =>\n            match SEP.reify_exprs ltac:(isConst) types funcs (PTR, tt) with\n              | (?types, ?funcs, ?PTR :: nil) => \n                let hyps := constr:(@nil (expr types)) in\n                let s := eval simpl in (SEP.hash P) in\n                generalize (@symeval_read_word_correct types 1 0 2 3 addr_not_state funcs sfuncs known)\n                  ; pose hyps\n(*\n                  hyps PTR (snd s) _ (refl_equal _) CS STN nil nil M I H)\n*)\n            end\n        end\n      end.\n      intros.\n      pose evaluators.\n\n        \n\n      specialize (H0 evaluators).\n      (** TODO : the known list needs to be parameterized appropriately... **)\n\n      simpl. auto.\n    Qed.\n\n    Goal forall p1 p2 p3 v1 v2 v3 cs stn m,\n      Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v2) (ptsto32 p3 v3))) m\n      -> Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v3) (ptsto32 p3 v3))) \n           (mem_set_word B.addr B.mem B.footprint_w B.mem_set (IL.explode stn) p2 v3 m).\n    Proof.\n      intros.\n      match goal with\n        | [ H : Satisfies ?CS ?STN ?P ?M\n          |- context [ mem_set_word B.addr B.mem B.footprint_w B.mem_set (IL.explode stn) ?PTR ?VAL ?M ] ] =>\n        let Ts := constr:(@nil Type) in\n        let Ts := SEP.collectAllTypes_sexpr ltac:(isConst) Ts (P :: nil) in\n        let Ts := SEP.collectAllTypes_expr ltac:(isConst) Ts (PTR, (VAL, tt)) in\n        let types := eval unfold pre_types in pre_types in\n        let types := SEP.extend_all_types Ts types in\n        let sexprs := constr:(P :: nil) in\n        match SEP.reify_sexprs a b ltac:(isConst) types tt tt sexprs with\n          | (?types, ?pcType, ?stateType, ?funcs, ?sfuncs, ?P :: nil) =>\n             match SEP.reify_exprs ltac:(isConst) types funcs (PTR, (VAL, tt)) with\n              | (?types, ?funcs, ?PTR :: ?VAL :: nil) => \n                 let hyps := constr:(@nil (expr pre_types)) in\n                let s := eval simpl in (SEP.hash P) in\n                generalize (@symeval_write_word_correct types 1 0 2 3 addr_not_state sfuncs known evaluators \n                  hyps PTR VAL (snd s) _ (refl_equal _) CS STN funcs nil nil M _ I (refl_equal _) H)\n            end\n        end\n      end.\n      simpl; auto.\n    Qed.\n*)\n\n  End Tests.\nEnd EvaluatorTests.\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/SymEvalTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.1835296503406709}}
{"text": "\nLoad \"Pi2\".\n(******************************Protocol Pi2'' :**************************************************************************)\n\n\n\nDefinition t30 := msg (G (N 0)).\nDefinition t31 := msg (g (N 0)).\nDefinition phi30 := [t30; t31].\nDefinition mphi30 := (conv_mylist_listm phi30).\nDefinition msgt30 := (ostomsg t30).\nDefinition msgt31 := (ostomsg t31).\nDefinition grn31 := (exp msgt30 msgt31 (r (N 1))).\nDefinition qc0000:= (if_then_else_M (EQ_M (reveal (f mphi30)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi30)) (i 2) ) O (if_then_else_M ((EQ_M (to (f mphi30)) (i 1)) & (EQ_M (act (f mphi30)) new)) grn31 (if_then_else_M (EQ_M (to (f mphi30)) (i 1)) grn31 (if_then_else_M ((EQ_M (to (f mphi30)) (i 2)) & (EQ_M (act (f mphi30)) new)) grn31 (if_then_else_M (EQ_M (to (f mphi30)) (i 2)) grn31 O) ) )))).\nDefinition t32:= msg qc0000.\n\nDefinition phi31 := phi30 ++ [ t32 ].\n\n (***********************************************************)\nDefinition msgt32:= (ostomsg t32).\nDefinition mphi31 := (conv_mylist_listm phi31).\nDefinition mx31rn1 := (exp msgt30 (m (f mphi30 )) (r (N 1))).\nDefinition mx31rn2 := (exp msgt30 (m (f mphi30 )) (r (N 2))).\nDefinition grn32:= (exp msgt30 msgt31 (r (N 2))).\n\n(**********qc0000 -> qc1000, qc0010, qc0100, qc0001*************************************************)\n\nDefinition qc1000 := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) acc (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) grn32 (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) grn32 O))))).\n\nDefinition qc0010:= (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) mx31rn1 (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) grn32 (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) grn32 O) ) ) ).\n\nDefinition qc0100 := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) acc (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) grn31 (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) grn31 O))))).\n\nDefinition qc0001 :=(if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) mx31rn1 (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) grn32 (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) grn32 O) ) ) ).\n\nDefinition t33 := msg (if_then_else_M (EQ_M (reveal (f mphi30)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi30)) (i 2) ) O (if_then_else_M ((EQ_M (to (f mphi30)) (i 1)) & (EQ_M (act (f mphi30)) new)) qc1000 (if_then_else_M (EQ_M (to (f mphi30)) (i 1)) qc0010 (if_then_else_M ((EQ_M (to (f mphi30)) (i 2)) & (EQ_M (act (f mphi30)) new)) qc0100 (if_then_else_M (EQ_M (to (f mphi30)) (i 2)) qc0001 O) ) )))).\nDefinition phi32:= phi31 ++ [t33].\n\n\n(***************************************************************************)\nDefinition msgt33:= (ostomsg t33).\nDefinition mphi32 := (conv_mylist_listm phi32).\n\nDefinition mx32rn1 := (exp msgt30 (m (f mphi31 )) (r (N 1))).\nDefinition mx32rn2 := (exp msgt30 (m (f mphi31 )) (r (N 2))).\nDefinition grn33:= (exp msgt30 msgt31 (r (N 3))).\n\n\n\n(************* qc1000 -> qc2000, qc1100, qc1001*******************************************************)\n\nDefinition qc2000 :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) & (EQ_M (act (f mphi32)) new)) grn33 (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) grn33 O) ) ) ).\n\n\nDefinition qc1100 := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) acc (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) ) acc O) ))).\nDefinition qc1001 := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi30)) (i 2)))  mx31rn1 (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2))) mx32rn2  (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) acc O)))).\n(************qc0010 -> qc0020, qc0110, qc0011*********************************************************)\n\nDefinition qc0110 := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1)))  mx31rn1 (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1))) mx32rn2  (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) acc O)))).\n\n(*****************qc0100 -> qc0200, qc1100, qc0110****************************************************)\n\nDefinition qc0200 :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 (if_then_else_M ((EQ_M (to (f mphi32)) (i 1)) & (EQ_M (act (f mphi32)) new)) grn33 (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) grn33 O) ) ) ).\n\n(******************qc0001 -> qc0002, qc1001, qc0011****************************************************)\n\n(*****************************************************************************************************)\n\nDefinition qc1000_s := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc2000 (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc1100 (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc1001 O))))).\n\nDefinition qc0010_s := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc0110 (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) O O) ) ) ).\n\nDefinition qc0100_s := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc0200 (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1100 (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc0110 O))))).\n\nDefinition qc0001_s := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1001 (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) O O) ) ) ).\n\nDefinition t34 := msg (if_then_else_M (EQ_M (reveal (f mphi30)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi30)) (i 2) ) O (if_then_else_M ((EQ_M (to (f mphi30)) (i 1)) & (EQ_M (act (f mphi30)) new)) qc1000_s (if_then_else_M (EQ_M (to (f mphi30)) (i 1)) qc0010_s (if_then_else_M ((EQ_M (to (f mphi30)) (i 2)) & (EQ_M (act (f mphi30)) new)) qc0100_s (if_then_else_M (EQ_M (to (f mphi30)) (i 2)) qc0001_s O) ) )))).\n\nDefinition phi33:= phi32 ++ [t34].\n(***********************************************************************************************)\nDefinition mx33rn2 := (exp msgt30 (m (f mphi32 )) (r (N 2))).\nDefinition mx33rn1 := (exp msgt30 (m (f mphi32 )) (r (N 1))).\nDefinition mphi33 := (conv_mylist_listm phi33).\n\n(********************qc2000 -> qc3000, qc2100, qc2001****************************************************)\nDefinition qc2100 := (if_then_else_M (EQ_M (reveal (f mphi33)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 (if_then_else_M (EQ_M (to (f mphi33)) (i 2)) acc O ) )).\n(**************************qc1100 -> qc2100, qc1200 *****************************************************)\nDefinition qc1200 := (if_then_else_M (EQ_M (reveal (f mphi33)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi31)) new))   mx33rn2 (if_then_else_M (EQ_M (to (f mphi33)) (i 1)) acc O)) ) ).\n(**********Changes to the states qc2001, qc0210 in protocol2**************************************************)\n(**Definition grn34:= (exp msgt30 msgt31 (r (N 4))).**)\nDefinition qc2001 := (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 2))&(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn12))   mx32rn2 (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 2))&(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn12))   mx33rn1 (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi31)) new))   mx33rn2 O ))).\n \nDefinition qc0210 :=  (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 1))&(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn12))   mx32rn2 (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 1))&(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn12))  mx33rn1 (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 O ))).\n\n(********************************************************************************************************)\nDefinition qc0120 := (if_then_else_M (EQ_M (reveal (f mphi33)) (i 1) ) O ( if_then_else_M (EQ_M (to (f mphi31)) (i 2)) grn33 O)).\n\n\n(*****************************qc1001 -> qc1002, qc2001***************************************************)\n\nDefinition qc2000_s :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new)) O (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) & (EQ_M (act (f mphi32)) new)) qc2100 (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) qc2001 O) ) ) ).\n\n\nDefinition qc1100_s := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc2100 (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) ) qc1200 O) ))).\nDefinition qc1001_s := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi30)) (i 2)))  O (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc2001 O))).\n\nDefinition qc0110_s := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1)))  qc0120 (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1))) qc0120  (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) qc0210 O)))).\n\nDefinition qc0200_s :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   O (if_then_else_M ((EQ_M (to (f mphi32)) (i 1)) & (EQ_M (act (f mphi32)) new)) qc1200 (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc0210 O) ) ) ).\n(***********************************************************************************************************)\n\n\nDefinition qc1000_ss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc2000_s (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc1100_s (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc1001_s O))))).\n\nDefinition qc0010_ss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc0110_s (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) O O) ) ) ).\n\nDefinition qc0100_ss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc0200_s (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1100_s (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc0110_s O))))).\n\nDefinition qc0001_ss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1001_s (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) O O) ) ) ).\n\nDefinition t35 := msg (if_then_else_M (EQ_M (reveal (f mphi30)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi30)) (i 2) ) O (if_then_else_M ((EQ_M (to (f mphi30)) (i 1)) & (EQ_M (act (f mphi30)) new)) qc1000_ss (if_then_else_M (EQ_M (to (f mphi30)) (i 1)) qc0010_ss (if_then_else_M ((EQ_M (to (f mphi30)) (i 2)) & (EQ_M (act (f mphi30)) new)) qc0100_ss (if_then_else_M (EQ_M (to (f mphi30)) (i 2)) qc0001_ss O) ) )))).\n\nDefinition phi34 :=  phi33 ++ [ t35 ]. \n\n(***********************************************************************************************************)\nDefinition mx34rn3 := (exp msgt30 (m (f mphi33 )) (r (N 3))).\nDefinition mphi34 := (conv_mylist_listm phi34).\n\n(********************qc2100 -> qc2200, qc3100************************************)\n\nDefinition qc2200 := (if_then_else_M ((EQ_M (reveal (f mphi34)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   mx32rn1 (if_then_else_M ((EQ_M (reveal (f mphi34)) (i 2) ) & (EQ_M (to (f mphi33)) (i 2)) &(EQ_M (to (f mphi32)) (i 2)) & (notb (EQ_M ( act(f mphi33)) new)) &(EQ_M (act (f mphi32)) new))   mx34rn3 O)).\n\nDefinition qc2100_s := (if_then_else_M (EQ_M (reveal (f mphi33)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   O (if_then_else_M (EQ_M (to (f mphi33)) (i 2)) qc2200 O ) )).\n\nDefinition qc1200_s := (if_then_else_M (EQ_M (reveal (f mphi33)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))  O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi31)) new))  O (if_then_else_M (EQ_M (to (f mphi33)) (i 1)) qc2200 O)) ) ).\nDefinition qc2001_s :=  (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi31)) new))   O O )).\n(*****************************Changes in protocol2********************************)\nDefinition qc0210_s :=  (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 2))&(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn33))   O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 1)) &(EQ_M (to (f mphi31)) (i 2))&(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn33))   O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))  O O ))).\nDefinition qc0120_s := (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 1) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 1))&(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn33))   O (if_then_else_M ((EQ_M (reveal (f mphi33)) (i 2) ) & (EQ_M (to (f mphi32)) (i 2)) &(EQ_M (to (f mphi31)) (i 1))&(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi32)) new)) &(EQ_M (act (f mphi30)) new) &(EQ_M (m (f mphi31)) grn31) &(EQ_M (m (f mphi32)) grn33))   O (if_then_else_M (EQ_M (reveal (f mphi33)) (i 1) ) O ( if_then_else_M (EQ_M (to (f mphi31)) (i 2)) O O)))).\n(********************************************************************************)\nDefinition qc2000_ss :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1)) &(EQ_M (to (f mphi30)) (i 1)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new)) O (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) & (EQ_M (act (f mphi32)) new)) qc2100 (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) qc2001 O) ) ) ).\n\n\nDefinition qc1100_ss := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc2100_s (if_then_else_M ((EQ_M (to (f mphi32)) (i 2)) ) qc1200_s O) ))).\nDefinition qc1001_ss := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi30)) (i 2)))  O (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc2001_s O))).\n\nDefinition qc0110_ss := (if_then_else_M (EQ_M (reveal (f mphi32)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1)))  qc0120 (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 1) ) & (EQ_M (to (f mphi31)) (i 1))) qc0120_s  (if_then_else_M (EQ_M (to (f mphi32)) (i 2)) qc0210_s O)))).\n\nDefinition qc0200_ss :=  (if_then_else_M (EQ_M (reveal (f mphi32)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi32)) (i 2) ) & (EQ_M (to (f mphi31)) (i 2)) &(EQ_M (to (f mphi30)) (i 2)) & (notb (EQ_M ( act(f mphi31)) new)) &(EQ_M (act (f mphi30)) new))   O (if_then_else_M ((EQ_M (to (f mphi32)) (i 1)) & (EQ_M (act (f mphi32)) new)) qc1200_s (if_then_else_M (EQ_M (to (f mphi32)) (i 1)) qc0210_s O) ) ) ).\n(**********************************************************************************************)\n\nDefinition qc1000_sss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc2000_ss (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc1100_ss (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc1001_ss O))))).\n\nDefinition qc0010_sss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 2)) & (EQ_M (act (f mphi31)) new)) qc0110_ss (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) O O) ) ) ).\n\nDefinition qc0100_sss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi31)) (i 2) ) O (if_then_else_M (EQ_M (to (f mphi31)) (i 2)) qc0200_ss (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1100_ss (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) qc0110_ss O))))).\n\nDefinition qc0001_sss := (if_then_else_M (EQ_M (reveal (f mphi31)) (i 1) ) O (if_then_else_M ((EQ_M (reveal (f mphi31)) (i 1) ) & (EQ_M (to (f mphi30)) (i 1))) O (if_then_else_M ((EQ_M (to (f mphi31)) (i 1)) & (EQ_M (act (f mphi31)) new)) qc1001_ss (if_then_else_M (EQ_M (to (f mphi31)) (i 1)) O O) ) ) ).\n\nDefinition t36 := msg (if_then_else_M (EQ_M (reveal (f mphi30)) (i 1) ) O (if_then_else_M (EQ_M (reveal (f mphi30)) (i 2) ) O (if_then_else_M ((EQ_M (to (f mphi30)) (i 1)) & (EQ_M (act (f mphi30)) new)) qc1000_sss (if_then_else_M (EQ_M (to (f mphi30)) (i 1)) qc0010_sss (if_then_else_M ((EQ_M (to (f mphi30)) (i 2)) & (EQ_M (act (f mphi30)) new)) qc0100_sss (if_then_else_M (EQ_M (to (f mphi30)) (i 2)) qc0001_sss O) ) )))).\n\nDefinition phi35  := phi34 ++ [ t36].\n\n(**************************************************************************************************)\n(***************************************************************************************************)\n\nTheorem RRS1: phi11 ~ phi31.\nProof. reflexivity. Qed.\n\nTheorem RRS2: phi12 ~ phi32.\nProof. reflexivity. Qed.\n\nTheorem RRS3: phi13 ~ phi33.\nProof. reflexivity. Qed.\nTheorem RRS4: t15 ### t35.\nProof.  repeat try unfold phi35, phi15, phi34, phi14, phi33, phi13, phi32, phi12 ,phi31, phi11, phi30, phi10.\nrepeat try unfold t30, t10, t31,t32, t11,t12, t33, t13, t34, t14, t35, t15, t36, t16.\n \nrepeat try unfold qa0000, qa1000 , qa0010,qa0100,qa0001 ,qa2000,qa1100 ,qa1001 ,qa0110,qa0200,qa1000_s,qa0010_s,qa0100_s,qa0001_s,qa2100,qa1200,qa2001,qa0210,\n qa0120,qa2000_s, qa1100_s, qa1001_s, qa0110_s,qa0200_s,qa1000_ss,qa0010_ss, qa0100_ss,qa0001_ss,qa2200,qa2100_s,qa1200_s,qa2001_s,qa0210_s,qa0120_s,qa2000_ss,qa1100_ss ,qa1001_ss,qa0110_ss,qa0200_ss,\n qa1000_sss,qa0010_sss,qa0100_sss,qa0001_sss.\nsimpl.\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\nqc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s.\n\ntry unfold qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\nqc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\nrewrite IFSAME_M with (b:= (EQ_M (to (f mphi11)) (i 1))) (x:= O) .\nrewrite IFSAME_M with (b:= (EQ_M (to (f mphi31)) (i 1))) (x:= O) .\nrepeat try unfold qa0000, qa1000 , qa0010,qa0100,qa0001 ,qa2000,qa1100 ,qa1001 ,qa0110,qa0200,qa1000_s,qa0010_s,qa0100_s,qa0001_s,qa2100,qa1200,qa2001,qa0210,\n qa0120,qa2000_s, qa1100_s, qa1001_s, qa0110_s,qa0200_s,qa1000_ss,qa0010_ss, qa0100_ss,qa0001_ss,qa2200,qa2100_s,qa1200_s,qa2001_s,qa0210_s,qa0120_s,qa2000_ss,qa1100_ss ,qa1001_ss,qa0110_ss,qa0200_ss,\n qa1000_sss,qa0010_sss,qa0100_sss,qa0001_sss.\nsimpl.\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\nqc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s.\n\ntry unfold qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\nqc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\n\nAdmitted.\n\n\nTheorem RRS5: phi14 ~ phi34.\nProof.  repeat try unfold phi35, phi15, phi34, phi14, phi33, phi13, phi32, phi12 ,phi31, phi11, phi30, phi10.\nrepeat try unfold t30, t10, t31,t32, t11,t12, t33, t13, t34, t14, t35, t15, t36, t16.\n \nrepeat try unfold qa0000, qa1000 , qa0010,qa0100,qa0001 ,qa2000,qa1100 ,qa1001 ,qa0110,qa0200,qa1000_s,qa0010_s,qa0100_s,qa0001_s,qa2100,qa1200,qa2001,qa0210,\n qa0120,qa2000_s, qa1100_s, qa1001_s, qa0110_s,qa0200_s,qa1000_ss,qa0010_ss, qa0100_ss,qa0001_ss,qa2200,qa2100_s,qa1200_s,qa2001_s,qa0210_s,qa0120_s,qa2000_ss,qa1100_ss ,qa1001_ss,qa0110_ss,qa0200_ss,\n qa1000_sss,qa0010_sss,qa0100_sss,qa0001_sss.\nsimpl.\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\nqc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s.\n\ntry unfold qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\nqc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\n\npose proof(IFSAME_M).\nrewrite IFSAME_M with (b:= (EQ_M (to (f mphi11)) (i 1))) (x:= O) .\nrewrite IFSAME_M with (b:= (EQ_M (to (f mphi31)) (i 1))) (x:= O) .\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\nqc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s.\n\ntry unfold qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\nqc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\n\ntry unfold mphi25 , mphi24 , mphi23 , mphi22. try unfold mphi21, mphi20.\n try unfold mphi35 , mphi34 , mphi33 , mphi32. try unfold mphi31, mphi30. simpl.\n\n repeat try unfold phi35, phi15, phi34, phi14, phi33, phi13, phi32, phi12 ,phi31, phi11, phi30, phi10 .\nrepeat try unfold t30, t10, t31,t32, t11,t12, t33, t13, t34, t14, t35, t15, t36, t16.\n try unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10.\n try unfold mphi35 , mphi34 , mphi33 , mphi32. try unfold mphi31, mphi30. simpl.\n\nrepeat try unfold qa0000, qa1000 , qa0010,qa0100,qa0001 ,qa2000,qa1100 ,qa1001 ,qa0110,qa0200,qa1000_s,qa0010_s,qa0100_s,qa0001_s,qa2100,qa1200,qa2001,qa0210,\n qa0120,qa2000_s, qa1100_s, qa1001_s, qa0110_s,qa0200_s,qa1000_ss,qa0010_ss, qa0100_ss,qa0001_ss,qa2200,qa2100_s,qa1200_s,qa2001_s,qa0210_s,qa0120_s,qa2000_ss,qa1100_ss ,qa1001_ss,qa0110_ss,qa0200_ss,\n qa1000_sss,qa0010_sss,qa0100_sss,qa0001_sss.\n\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\n qc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s,qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\n qc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\n\n repeat try unfold phi35, phi15, phi34, phi14, phi33, phi13, phi32, phi12 ,phi31, phi11, phi30, phi10 .\nAdmitted.\n\nTheorem RRS7: [t14] ~ [t34]. \nProof. repeat try unfold t30, t10, t31,t32, t11,t12, t33, t13, t34, t14, t35, t15, t36, t16.\nrepeat try unfold qa0000, qa1000 , qa0010,qa0100,qa0001 ,qa2000,qa1100 ,qa1001 ,qa0110,qa0200,qa1000_s,qa0010_s,qa0100_s,qa0001_s,qa2100,qa1200,qa2001,qa0210,\n qa0120,qa2000_s, qa1100_s, qa1001_s, qa0110_s,qa0200_s,qa1000_ss,qa0010_ss, qa0100_ss,qa0001_ss,qa2200,qa2100_s,qa1200_s,qa2001_s,qa0210_s,qa0120_s,qa2000_ss,qa1100_ss ,qa1001_ss,qa0110_ss,qa0200_ss,\n qa1000_sss,qa0010_sss,qa0100_sss,qa0001_sss.\n\nrepeat try unfold qc0000, qc1000 , qc0010,qc0100,qc0001 ,qc2000,qc1100 ,qc1001 ,qc0110,qc0200,qc1000_s,qc0010_s,qc0100_s,qc0001_s,qc2100,qc1200,qc2001,qc0210,\n qc0120,qc2000_s, qc1100_s, qc1001_s, qc0110_s,qc0200_s,qc1000_ss,qc0010_ss, qc0100_ss,qc0001_ss,qc2200,qc2100_s,qc1200_s,qc2001_s,qc0210_s,qc0120_s,qc2000_ss,qc1100_ss ,qc1001_ss,qc0110_ss,qc0200_ss,\n qc1000_sss,qc0010_sss,qc0100_sss,qc0001_sss.\ntry unfold mphi15 , mphi14 , mphi13.  try unfold mphi12, mphi11, mphi10.\n try unfold mphi35 , mphi34 , mphi33 , mphi32. try unfold mphi31, mphi30. simpl.\ntry unfold mphi15 , mphi14 , mphi13 , mphi12. try unfold mphi11, mphi10.\n try unfold mphi35 , mphi34 , mphi33 , mphi32. try unfold mphi31, mphi30. simpl.\nAdmitted.\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/Pi3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.18352324928596195}}
{"text": "(** * Implementation of Section 4.8 *)\nRequire Import RL.Utilities.Rpos.\nRequire Import RL.Utilities.polynomials.\nRequire Import RL.Utilities.riesz_logic_Nat_more.\nRequire Import riesz_logic_List_more.\nRequire Import RL.hr.hr.\nRequire Import RL.hr.term.\nRequire Import RL.hr.semantic.\nRequire Import RL.hr.hseq.\nRequire Import RL.hr.p_hseq.\nRequire Import RL.hr.lambda_prop_tools.\nRequire Import RL.hr.invertibility.\nRequire Import RL.hr.can_elim.\nRequire Import RL.hr.M_elim.\nRequire Import RL.hr.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 hrr_fuse :\n  forall G T A r1 r2,\n    HR_T_M (((r1, A) :: (r2 , A) :: T) :: G) ->\n    HR_T_M (((plus_pos r1 r2, A) :: T) :: G).\nProof.\n  intros G T A r1 r2 pi.\n  apply hrr_can_elim.\n  unfold HR_full.\n  change hr_frag_full with (hr_frag_add_CAN hr_frag_full).\n  apply hrr_can_fuse.\n  apply HR_le_frag with hr_frag_T_M; try assumption.\n  repeat split.\nQed.\n\nLemma hrr_unfuse :\n  forall G T A r1 r2,\n    HR_T_M (((plus_pos r1 r2, A) :: T) :: G) ->\n    HR_T_M (((r1, A) :: (r2 , A) :: T) :: G).\nProof.\n  intros G T A r1 r2 pi.\n  apply hrr_can_elim.\n  unfold HR_full.\n  change hr_frag_full with (hr_frag_add_CAN hr_frag_full).\n  apply hrr_can_unfuse.\n  apply HR_le_frag with hr_frag_T_M; try assumption.\n  repeat split.\nQed.\n\nLemma hrr_unfuse_gen :\n  forall G T D r1 r2,\n    HR_T_M ((hseq.seq_mul (plus_pos r1 r2) D ++ T) :: G) ->\n    HR_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 hrr_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 hrr_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 hrr_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 hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\nQed.\n\nLemma hrr_fuse_gen :\n  forall G T D r1 r2,\n    HR_T_M ((hseq.seq_mul r1 D ++ hseq.seq_mul r2 D ++ T) :: G) ->\n    HR_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 hrr_fuse.\n    apply hrr_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 hrr_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    HR_T_M ((concat_with_coeff_mul G L1 ++ concat_with_coeff_mul G L2 ++ T) :: H) ->\n    HR_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 hrr_fuse_gen.\n    apply hrr_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 hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hrr_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 hrr_ex_seq ; [ | apply pi].\n    Permutation_Type_solve.\n  - apply hrr_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 hrr_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_atomic G ->\n    HR_T_M G ->\n    { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> None) L) *\n            (forall n, sum_weight_var_with_coeff n G L = 0))}.\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  - inversion Ha; subst.\n    destruct (IHpi X0) as [L [Hlen [Hex Hsum]]].\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]]].\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  - inversion Ha; inversion X0; subst.\n    destruct IHpi as [L [Hlen [Hex Hsum]]].\n    { apply Forall_inf_cons; try assumption.\n      apply seq_atomic_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_var_seq_app in Hsum.\n      nra.\n  - inversion Ha; subst.\n    destruct IHpi1 as [L1 [Hlen1 [Hex1 Hsum1]]].\n    { apply Forall_inf_cons ; [ apply seq_atomic_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]]].\n    { apply Forall_inf_cons ; [ apply seq_atomic_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_var_seq_app.\n      rewrite sum_weight_var_with_coeff_oadd_Rpos_list ; [ | simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia].\n      rewrite 2 sum_weight_var_with_coeff_omul_Rpos_list.\n      destruct r; destruct r0; simpl in *; nra.\n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [Hex Hsum]]].\n    { apply Forall_inf_cons; try assumption.\n      apply seq_atomic_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_var_seq_mul in Hsum; simpl in *.\n      nra.\n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [Hex Hsum]]].\n    { apply Forall_inf_cons; try assumption.\n      eapply seq_atomic_app_inv_r; eapply seq_atomic_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 (hr.term.V_eq n0 n); intros H.\n      * subst.\n        rewrite ? sum_weight_var_seq_app.\n        rewrite sum_weight_var_seq_vec_covar_eq;rewrite sum_weight_var_seq_vec_var_eq.\n        simpl in Hsum.\n        destruct o; nra.\n      * rewrite ? sum_weight_var_seq_app.\n        rewrite ? sum_weight_var_seq_vec_neq; try (intros H'; inversion H'; contradiction).\n        destruct o; simpl in Hsum; auto.\n        nra.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi Ha) as [L [Hlen [Hex Hsum]]].\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]]].\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]]].\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]]].\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 r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi1 Ha) as [L [Hlen [Hex Hsum]]].\n    split with L.\n    repeat split; try assumption.\n  - destruct IHpi as [L [Hlen [Hex Hsum]]].\n    { inversion Ha; subst.\n      apply Forall_inf_cons; try assumption.\n      apply seq_atomic_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_var_seq_perm _ _ _ p); apply Hsum.\n  - destruct IHpi as [L [Hlen [Hex Hsum]]].\n    { apply hseq_atomic_perm with H; try assumption.\n      symmetry; apply p. }\n    destruct (sum_weight_var_with_coeff_perm_r G H L p Hlen) as [L' [Hperm' Hsum']].\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  - inversion f.\nQed.\n\nLemma lambda_prop_inv :\n  forall G,\n    hseq_is_atomic G ->\n    { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> None) L) *\n            (forall n, sum_weight_var_with_coeff n G L = 0))} ->\n    HR_T_M G.\nProof.\n  enough (forall G H,\n             hseq_is_atomic G ->\n             hseq_is_atomic 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_var_with_coeff n G L = 0))} + HR_T_M H ->\n             HR_T_M (H ++  G)).\n  { intros G Hat [L [Hlen [Hex Hsum]]].\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  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]]] | 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_var_with_coeff_perm_l G _ _ Hperm) as [G' [HpermG Hsum']].\n    { lia. }\n    destruct G' as [ | T G'].\n    { symmetry in HpermG; apply Permutation_Type_nil in HpermG.\n      subst; inversion Heqn. }\n    apply hrr_ex_hseq with (T :: H ++ G') ; [ Permutation_Type_solve | ].\n    destruct r ; [ | exfalso; apply Hp; reflexivity].\n    apply hrr_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_atomic (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_atomic_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 atomic_proof_all_eq.\n        -- apply seq_atomic_mul.\n           apply hseq_atomic_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_var_with_coeff_all_0 _ (La ++ Lb)) in Hsum'; try assumption.\n           rewrite sum_weight_var_seq_mul; simpl.\n           nra.\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_var_seq_mul; simpl.\n           nra.\n  - eapply hrr_ex_hseq; [ apply Permutation_Type_app_comm | ].\n    apply hrr_W_gen.\n    apply pi.\nQed.\n\n(** ** Decidablity *)\n(* begin hide *)\n(* Preliminary work necessary for the decidability result *)\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 (eval_Poly 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 <= eval_Poly (upd_val_vec val (seq i (length L)) (map oRpos_to_R L)) x) (map Poly_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 eval_Poly_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 Poly_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 eval_Poly_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\nFixpoint p_sum_weight_var_with_coeff n G L :=\n  match G, L with\n  | _, nil => Poly_cst 0\n  | nil, _ => Poly_cst 0\n  | T :: G , r :: L => (r *R sum_weight_var_p_seq 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    eval_Poly 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_var_p_seq_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    eval_Poly val (p_sum_weight_var_with_coeff n (G1 ++ G2) (L1 ++ L2)) = eval_Poly val (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\nLemma eval_to_oRpos_to_R_eq : forall L val i,\n    Forall_inf (fun x => 0 <= eval_Poly (upd_val_vec val (seq i (length L)) (map oRpos_to_R L)) x) (map Poly_var (seq i (length L))) ->\n    map (eval_to_oRpos (upd_val_vec val (seq i (length L)) (map oRpos_to_R L))) (map Poly_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 eval_Poly_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 eval_Poly_eval_p_sequent : forall val n T,\n    eval_Poly val (sum_weight_var_p_seq n T) = sum_weight_var_seq n (eval_p_sequent val T).\nProof.\n  intros val n; induction T; simpl; try lra.\n  destruct a as [a A].\n  case_eq (R_order_dec (eval_Poly val a)); intros e He; simpl;\n    destruct A; simpl; try case (hr.term.V_eq n v); simpl; try rewrite IHT; try lra.\nQed.\n\nLemma eval_Poly_eval_p_hseq : forall val n G L,\n    Forall_inf (fun x => 0 <= eval_Poly val x) L ->\n    eval_Poly val (p_sum_weight_var_with_coeff n G L) = sum_weight_var_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  case_eq (R_order_dec (eval_Poly val x)); intros e' He'; simpl ; [ | exfalso; clear - r e'; apply R_blt_lt in e' |  ]; try lra.\n  - rewrite IHG; rewrite eval_Poly_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 eval_Poly_upd_val_vec_lt : forall val a vx vr,\n    Forall_inf (fun x => max_var_Poly a < x)%nat vx ->\n    eval_Poly (upd_val_vec val vx vr) a = eval_Poly 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_max_var ; [ | 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_var_with_coeff_eval_eq : forall val n G L,\n    sum_weight_var_with_coeff n (map (eval_p_sequent val) G) L = eval_Poly (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 Poly_var (seq (S (max_var_weight_p_hseq G)) (length L)))).\nProof.\n  intros val n G L.\n  rewrite eval_Poly_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\n(* Put non atomic formula first, i.e., G in the form H | |- T, r.A with A non atomic. *)\n\nFixpoint p_seq_fst_non_atomic_term (T : p_sequent) : (Poly * term) :=\n  match T with\n  | nil => (Poly_cst 0, RS_zero)\n  | (a, A) :: T => if (0 <? RS_outer_complexity_term A)%nat\n                   then (a , A)\n                   else (p_seq_fst_non_atomic_term T)\n  end.\n\nLemma p_seq_fst_non_atomic_term_correct :\n  forall T,\n    (p_seq_is_atomic T -> False) ->\n    (is_atom (snd (p_seq_fst_non_atomic_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 <? RS_outer_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_atom_outer_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_atom_outer_complexity_0_inv.\n    lia.\nQed.\n\nLemma p_seq_fst_non_atomic_term_well_defined :\n  forall val T,\n    (0 < HR_outer_complexity_p_seq T)%nat ->\n    p_seq_well_defined val T ->\n    0 <= eval_Poly val (fst (p_seq_fst_non_atomic_term T)).\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 <? RS_outer_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_atomic_term (T : p_sequent) : p_sequent :=\n  match T with\n  | nil => nil\n  | (a, A) :: T => if (0 <? RS_outer_complexity_term A)%nat\n                   then T\n                   else (a , A) :: (p_seq_without_fst_non_atomic_term T)\n  end.\n\nLemma p_seq_put_non_atomic_fst : forall T,\n    (p_seq_is_atomic T -> False) ->\n    Permutation_Type T (p_seq_fst_non_atomic_term T :: p_seq_without_fst_non_atomic_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 <? RS_outer_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_atomic T -> False).\n  { intros H; apply Hnb; apply Forall_inf_cons; auto.\n    apply is_atom_outer_complexity_0_inv.\n    lia. }\n  specialize (IHT H).\n  transitivity ((a , A) :: p_seq_fst_non_atomic_term T :: p_seq_without_fst_non_atomic_term T);\n    Permutation_Type_solve.\nQed.\n\nLemma p_seq_without_fst_non_atomic_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_atomic_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 <? RS_outer_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 (HR_outer_complexity_p_hseq G) <=? HR_outer_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 (HR_outer_complexity_p_hseq G) <=? HR_outer_complexity_p_seq a); auto.\nQed.\n\nLemma p_hseq_p_seq_max_complexity_correct :\n  forall G,\n    HR_outer_complexity_p_seq (p_hseq_p_seq_max_complexity G) = fst (HR_outer_complexity_p_hseq G).\nProof.\n  induction G; auto.\n  simpl.\n  case_eq (fst (HR_outer_complexity_p_hseq G) <=? HR_outer_complexity_p_seq a); intros H1;\n    case_eq (HR_outer_complexity_p_seq a =? fst (HR_outer_complexity_p_hseq G)); intros H2;\n      case_eq (HR_outer_complexity_p_seq a <? fst (HR_outer_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 (HR_outer_complexity_p_hseq G) <=? HR_outer_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 (HR_outer_complexity_p_hseq G) <=? HR_outer_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 (HR_outer_complexity_p_hseq G) <=? HR_outer_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_atomic_fst G :=\n  ((p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)) :: p_hseq_without_max_complexity G).\n\nLemma p_hseq_put_non_atomic_fst_HR_complexity :\n  forall G,\n    (p_hseq_is_atomic G -> False) ->\n    HR_outer_complexity_p_hseq (p_hseq_put_non_atomic_fst G) = HR_outer_complexity_p_hseq G.\nProof.\n  intros G Hnb.\n  unfold p_hseq_put_non_atomic_fst.\n  rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_atomic_fst.\n      intros H.\n      apply Hnb.\n      apply p_hseq_is_atomic_outer_complexity_0_inv.\n      rewrite <- p_hseq_p_seq_max_complexity_correct.\n      apply p_seq_is_atomic_complexity_0.\n      apply H. }\n  rewrite outer_complexity_p_hseq_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_atomic_fst_correct :\n  forall G a A T H,\n    (p_hseq_is_atomic G -> False) ->\n    p_hseq_put_non_atomic_fst G = ((a, A) :: T) :: H ->\n    is_atom A -> False.\nProof.\n  intros G a A T H Hnb Heq Hb.\n  unfold p_hseq_put_non_atomic_fst in Heq.\n  inversion Heq; subst.\n  apply p_seq_fst_non_atomic_term_correct with (p_hseq_p_seq_max_complexity G).\n  - intros Hb'.\n    apply Hnb.\n    apply p_hseq_is_atomic_outer_complexity_0_inv.\n    apply p_seq_is_atomic_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_atomic_fst_well_defined :\n  forall val G,\n    (0 < fst (HR_outer_complexity_p_hseq G))%nat ->\n    p_hseq_well_defined val G ->\n    p_hseq_well_defined val (p_hseq_put_non_atomic_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_atomic_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_atomic_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\nLemma p_hseq_put_non_atomic_fst_HR :\n  forall val G,\n    (p_hseq_is_atomic G -> False) ->\n    HR_T_M (map (eval_p_sequent val) (p_hseq_put_non_atomic_fst G)) ->\n    HR_T_M (map (eval_p_sequent val) G).\nProof.\n  intros val G Hnatomic Hpi.\n  apply hrr_ex_hseq with (map (eval_p_sequent val) (p_hseq_p_seq_max_complexity G :: p_hseq_without_max_complexity G)).\n  { apply Permutation_Type_map.\n    symmetry; apply p_hseq_put_max_complexity_fst.\n    intros Hnil.\n    subst.\n    apply Hnatomic; apply Forall_inf_nil. }\n  simpl.\n  apply hrr_ex_seq with (eval_p_sequent val (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G))).\n  { apply Permutation_Type_eval_p_sequent.\n    symmetry; apply p_seq_put_non_atomic_fst.\n    intros H.\n    apply p_seq_is_atomic_complexity_0 in H.\n    rewrite p_hseq_p_seq_max_complexity_correct in H.\n    apply Hnatomic.\n    apply p_hseq_is_atomic_outer_complexity_0_inv.\n    apply H. }\n  apply Hpi.\nQed.\n\nLemma p_hseq_put_non_atomic_fst_HR_inv :\n  forall val G,\n    (p_hseq_is_atomic G -> False) ->\n    HR_T_M (map (eval_p_sequent val) G) ->\n    HR_T_M (map (eval_p_sequent val) (p_hseq_put_non_atomic_fst G)).\nProof.\n  intros val G Hnatomic Hpi.\n  unfold p_hseq_put_non_atomic_fst.\n  unfold map.\n  apply hrr_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_atomic_fst.\n    intros H.\n    apply p_seq_is_atomic_complexity_0 in H.\n    rewrite p_hseq_p_seq_max_complexity_correct in H.\n    apply Hnatomic.\n    apply p_hseq_is_atomic_outer_complexity_0_inv.\n    apply H. }\n  eapply hrr_ex_hseq; [ | apply Hpi].\n  transitivity (map (eval_p_sequent val) (p_hseq_p_seq_max_complexity G :: p_hseq_without_max_complexity G)); [ | reflexivity ].\n  apply Permutation_Type_map.\n  apply p_hseq_put_max_complexity_fst.\n  intros Hnil.\n  subst.\n  apply Hnatomic; apply Forall_inf_nil.\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 (((Poly_cst (projT1 r0) *R a, A) :: T) :: G)\n                               | RS_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  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_HR :\n  forall val G G1,\n    apply_logical_rule_on_p_hypersequent G = inl G1 ->\n    p_hseq_well_defined val G ->\n    HR_T_M (map (eval_p_sequent val) G) ->\n    HR_T_M (map (eval_p_sequent val) G1).\nProof.\n  intros val G G1 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HR_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    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n      rewrite He in pi; simpl.\n    2:{ apply pi. }\n    apply hrr_Z_inv with ((existT _ (eval_Poly val a) e) :: nil).\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n      rewrite He in pi.\n    2:{ apply pi. }\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_plus_inv.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n      case (R_order_dec (projT1 r * eval_Poly 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        try (exfalso; rewrite e in e'; apply R_blt_lt in e'; lra);\n        rewrite He in pi.\n    + replace ((existT (fun x : R => (0 <? x) = true) (projT1 r * eval_Poly val a) e', A)\n                 :: eval_p_sequent val l) with\n          (hseq.vec (hseq.mul_vec r ((existT (fun x => (0 <? x) = true) (eval_Poly 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) (eval_Poly val a) e))\n            with (existT (fun x : R => (0 <? x) = true) (projT1 r * eval_Poly val a) e') by (destruct r; apply Rpos_eq; clear; simpl; nra); auto. }\n      apply hrr_mul_inv.\n      apply pi.\n    + apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n      rewrite He in pi.\n    2:{ apply hrr_W; apply pi. }\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_max_inv.\n    apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inl_HR_inv :\n  forall val G G1,\n    apply_logical_rule_on_p_hypersequent G = inl G1 ->\n    p_hseq_well_defined val G ->\n    HR_T_M (map (eval_p_sequent val) G1) ->\n    HR_T_M (map (eval_p_sequent val) G).\nProof.\n  intros val G G1 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HR_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    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra).\n    2:{ apply pi. }\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly val a) e)); intros pi.\n    change ((r, RS_zero) :: eval_p_sequent val l) with\n        (hseq.vec (r :: nil) RS_zero ++ eval_p_sequent val l).\n    apply hrr_Z.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra).\n    2:{ rewrite He in pi; apply pi. }\n    rewrite He in pi.\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_plus.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n    case_eq (R_order_dec (projT1 r * eval_Poly 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      try (exfalso; clear - e e'; rewrite e in e'; apply R_blt_lt in e'; lra);\n      rewrite He' in pi.\n    2:{ apply pi. }\n    replace ((existT (fun x : R => (0 <? x) = true) (projT1 r * eval_Poly val a) e', A)\n              :: eval_p_sequent val l) with\n        (hseq.vec (hseq.mul_vec r ((existT (fun x => (0 <? x) = true) (eval_Poly 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) (eval_Poly val a) e))\n          with (existT (fun x : R => (0 <? x) = true) (projT1 r * eval_Poly 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) (eval_Poly 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 hrr_mul.\n    apply pi.\n  - inversion Hwd; inversion X; subst.\n    simpl in pi |- *.\n    case_eq (R_order_dec (eval_Poly val a)); intros e He;\n      try (exfalso; clear - e H2;\n           try (apply R_blt_lt in e); simpl in *; lra);\n      rewrite He in pi.\n    2:{ apply hrr_C.\n        apply pi. }\n    revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_max.\n    apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_l_HR :\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    HR_T_M (map (eval_p_sequent val) G) ->\n    HR_T_M (map (eval_p_sequent val) G1).\nProof.\n  intros val G G1 G2 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HR_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  case_eq (R_order_dec (eval_Poly val a)); intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); simpl in *; lra);\n    rewrite He in pi.\n  2:{ apply pi. }\n  revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_min_inv_l with A2.\n  apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_r_HR :\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    HR_T_M (map (eval_p_sequent val) G) ->\n    HR_T_M (map (eval_p_sequent val) G2).\nProof.\n  intros val G G1 G2 Heq Hwd pi.\n  destruct G; [ exfalso; apply (HR_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  case_eq (R_order_dec (eval_Poly val a)); intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); simpl in *; lra);\n    rewrite He in pi.\n  2:{ apply pi. }\n  revert pi;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_min_inv_r with A1.\n  apply pi.\nQed.\n\nLemma apply_logical_rule_on_p_hypersequent_inr_HR_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    HR_T_M (map (eval_p_sequent val) G1) ->\n    HR_T_M (map (eval_p_sequent val) G2) ->\n    HR_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  case_eq (R_order_dec (eval_Poly val a)); intros e He;\n    try (exfalso; clear - e H2;\n         try (apply R_blt_lt in e); simpl in *; lra);\n    rewrite He in pi1; rewrite He in pi2.\n  2:{ apply pi1. }\n  revert pi1 pi2;set (r := (existT (fun x : R => (0 <? x) = true) (eval_Poly 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 hrr_min; auto.\nQed.\n    \nLemma apply_logical_rule_on_p_hypersequent_correct_inl :\n  forall G G1 n,\n    fst (HR_outer_complexity_p_hseq G) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_atomic_fst G) = inl G1 ->\n    HR_outer_complexity_p_hseq G1 <2 HR_outer_complexity_p_hseq G.\nProof.\n  intros G G1 n H1 H2.\n  simpl in H1.\n  remember (p_hseq_put_non_atomic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_atomic_fst_HR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    simpl in H1.\n    apply p_hseq_is_atomic_outer_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_atomic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_atom A -> False).\n  { apply p_hseq_put_non_atomic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_atomic_outer_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_atomic_fst_HR_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_atomic_outer_complexity_0 in Hnb; lia. }\n    rewrite <- HeqH.\n    change ((a, RS_zero) :: l) with (vec (a :: nil) RS_zero ++ l).\n    apply hrr_Z_decrease_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_atomic_fst in *.\n    rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_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_atomic_fst_HR_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_atomic_outer_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 hrr_plus_decrease_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_atomic_fst in *.\n    rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_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_atomic_fst_HR_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_atomic_outer_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 ((Poly_cst (projT1 r) *R a, A) :: l) with (vec (mul_vec (Poly_cst (projT1 r)) (a :: nil)) A ++ l).\n    apply hrr_mul_decrease_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_atomic_fst in *.\n    rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_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_atomic_fst_HR_complexity G).\n    2:{ intros Hnb.\n        apply p_hseq_is_atomic_outer_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 hrr_max_decrease_complexity ; [ intros H'; inversion H' | ].\n    simpl vec; simpl app.\n    rewrite HeqH.\n    unfold p_hseq_put_non_atomic_fst in *.\n    rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n    2:{ symmetry; apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_complexity_0 in Hb.\n        rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n    rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n    2:{ apply p_seq_put_non_atomic_fst.\n        intros Hb.\n        apply p_seq_is_atomic_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    fst (HR_outer_complexity_p_hseq G) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_atomic_fst G) = inr (G1 , G2) ->\n    HR_outer_complexity_p_hseq G1 <2 HR_outer_complexity_p_hseq G.\nProof.\n  intros G G1 G2 n H1 H2.\n  simpl in H1.\n  remember (p_hseq_put_non_atomic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_atomic_fst_HR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    apply p_hseq_is_atomic_outer_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_atomic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_atom A -> False).\n  { apply p_hseq_put_non_atomic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_atomic_outer_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_atomic_fst_HR_complexity G).\n  2:{ intros Hnb.\n      apply p_hseq_is_atomic_outer_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 hrr_min_r_decrease_complexity ; [ intros H'; inversion H' | ].\n  simpl vec; simpl app.\n  rewrite HeqH.\n  unfold p_hseq_put_non_atomic_fst in *.\n  rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_atomic_fst.\n      intros Hb.\n      apply p_seq_is_atomic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n  2:{ apply p_seq_put_non_atomic_fst.\n      intros Hb.\n      apply p_seq_is_atomic_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    fst (HR_outer_complexity_p_hseq G) = S n ->\n    apply_logical_rule_on_p_hypersequent (p_hseq_put_non_atomic_fst G) = inr (G1 , G2) ->\n    HR_outer_complexity_p_hseq G2 <2 HR_outer_complexity_p_hseq G.\nProof.\n  intros G G1 G2 n H1 H2.\n  simpl in H1.\n  remember (p_hseq_put_non_atomic_fst G) as H.\n  destruct H.\n  { exfalso.\n    rewrite <- p_hseq_put_non_atomic_fst_HR_complexity in H1 ; [ rewrite <- HeqH in H1; inversion H1 |].\n    intros Hnb.\n    apply p_hseq_is_atomic_outer_complexity_0 in Hnb; lia. }\n  destruct l.\n  { unfold p_hseq_put_non_atomic_fst in HeqH.\n    inversion HeqH. }\n  destruct p as [a A].\n  assert (is_atom A -> False).\n  { apply p_hseq_put_non_atomic_fst_correct with G a l H; auto.\n    intros Hb.\n    apply p_hseq_is_atomic_outer_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_atomic_fst_HR_complexity G).\n  2:{ intros Hnb.\n      apply p_hseq_is_atomic_outer_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 hrr_min_l_decrease_complexity ; [ intros H'; inversion H' | ].\n  simpl vec; simpl app.\n  rewrite HeqH.\n  unfold p_hseq_put_non_atomic_fst in *.\n  rewrite HR_outer_complexity_perm_fst_seq with _ _ (p_hseq_p_seq_max_complexity G).\n  2:{ symmetry; apply p_seq_put_non_atomic_fst.\n      intros Hb.\n      apply p_seq_is_atomic_complexity_0 in Hb.\n      rewrite p_hseq_p_seq_max_complexity_correct in Hb; lia. }\n  rewrite outer_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 outer_complexity_p_seq_perm with (p_hseq_p_seq_max_complexity G) (p_seq_fst_non_atomic_term (p_hseq_p_seq_max_complexity G) :: p_seq_without_fst_non_atomic_term (p_hseq_p_seq_max_complexity G)).\n  2:{ apply p_seq_put_non_atomic_fst.\n      intros Hb.\n      apply p_seq_is_atomic_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", "meta": {"author": "clucas26e4", "repo": "ramics_archimedean", "sha": "27074ea90fcb3c1b7e857b8f789f223a10f3c4dd", "save_path": "github-repos/coq/clucas26e4-ramics_archimedean", "path": "github-repos/coq/clucas26e4-ramics_archimedean/ramics_archimedean-27074ea90fcb3c1b7e857b8f789f223a10f3c4dd/hr/apply_logical_rule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.18352324189388253}}
{"text": "From Mtac2 Require Import Mtac2.\nRequire Import Bool.Bool.\n\nExample hyp_well_formed : True.\nMProof.\n  (\\nu x := I,\n   l <- M.hyps;\n   oeq <- M.unify l [m: ahyp x (mSome I)] UniCoq;\n   match oeq with\n   | mNone => M.raise exception\n   | _ => M.ret I\n   end)%MC.\nQed.\n\nExample env_well_formed : True.\nMProof.\n  (\\nu x := I,\n   oeq <- M.unify x I UniCoq;\n   match oeq with\n   | mNone => M.raise exception\n   | _ => M.ret I\n   end)%MC.\nQed.\n\nExample fail_returning_var : True.\nMProof.\n  (mtry\n    (\\nu x := I, M.ret x);; M.raise exception\n  with VarAppearsInValue => M.ret I\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/nu_let.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3557749071749626, "lm_q1q2_score": 0.1834446276539179}}
{"text": "(* * Jasmin semantics with \u201cpartial values\u201d. *)\n\n(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nRequire Import ZArith Psatz.\nRequire Export utils syscall wsize word type low_memory sem_type values.\nImport Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope Z_scope.\n\nSection Section.\n\nContext {pd: PointerData} {syscall_state : Type} {sc_sem : syscall_sem syscall_state}.\n\nDefinition exec_getrandom_s_core (scs : syscall_state_t) (m : mem) (p:pointer) (len:pointer) : exec (syscall_state_t * mem * pointer) := \n  let len := wunsigned len in\n  let sd := syscall.get_random scs len in\n  Let m := fill_mem m p sd.2 in\n  ok (sd.1, m, p).\n\nLemma exec_getrandom_s_core_stable scs m p len rscs rm rp : \n  exec_getrandom_s_core scs m p len = ok (rscs, rm, rp) \u2192\n  stack_stable m rm.\nProof. by rewrite /exec_getrandom_s_core; t_xrbindP => rm' /fill_mem_stack_stable hf ? <- ?. Qed.\n\nLemma exec_getrandom_s_core_validw scs m p len rscs rm rp : \n  exec_getrandom_s_core scs m p len = ok (rscs, rm, rp) \u2192\n  validw m =2 validw rm.\nProof. by rewrite /exec_getrandom_s_core; t_xrbindP => rm' /fill_mem_validw_eq hf ? <- ?. Qed.\n\nDefinition sem_syscall (o:syscall_t) : \n     syscall_state_t -> mem -> sem_prod (syscall_sig_s o).(scs_tin) (exec (syscall_state_t * mem * sem_tuple (syscall_sig_s o).(scs_tout))) := \n  match o with\n  | RandomBytes _ => exec_getrandom_s_core\n  end.\n\nDefinition exec_syscall_s (scs : syscall_state_t) (m : mem) (o:syscall_t) vs : exec (syscall_state_t * mem * values) :=\n  let semi := sem_syscall o in\n  Let: (scs', m', t) := app_sopn _ (semi scs m) vs in\n  ok (scs', m', list_ltuple t).\n  \nLemma syscall_sig_s_noarr o : all is_not_sarr (syscall_sig_s o).(scs_tin).\nProof. by case: o. Qed.\n\nLemma exec_syscallPs_eq scs m o vargs vargs' rscs rm vres :\n  exec_syscall_s scs m o vargs = ok (rscs, rm, vres) \u2192 \n  List.Forall2 value_uincl vargs vargs' \u2192 \n  exec_syscall_s scs m o vargs' = ok (rscs, rm, vres).\nProof.\n  rewrite /exec_syscall_s; t_xrbindP => -[[scs' m'] t] happ [<- <- <-] hu.\n  by have -> := vuincl_sopn (syscall_sig_s_noarr o ) hu happ.\nQed.\n \nLemma exec_syscallPs scs m o vargs vargs' rscs rm vres :\n  exec_syscall_s scs m o vargs = ok (rscs, rm, vres) \u2192 \n  List.Forall2 value_uincl vargs vargs' \u2192 \n  exists2 vres' : values,\n    exec_syscall_s scs m o vargs' = ok (rscs, rm, vres') & List.Forall2 value_uincl vres vres'.\nProof.\n  move=> h1 h2; rewrite (exec_syscallPs_eq h1 h2).\n  by exists vres=> //; apply List_Forall2_refl.\nQed.\n\nDefinition mem_equiv m1 m2 := stack_stable m1 m2 /\\ validw m1 =2 validw m2.\n\nLemma sem_syscall_equiv o scs m : \n  mk_forall (fun (rm: (syscall_state_t * mem * _)) => mem_equiv m rm.1.2)\n            (sem_syscall o scs m).\nProof.\n  case: o => _len /= p len [[scs' rm] t] /= hex; split.\n  + by apply: exec_getrandom_s_core_stable hex. \n  by apply: exec_getrandom_s_core_validw hex.\nQed.\n\nLemma exec_syscallSs scs m o vargs rscs rm vres :\n  exec_syscall_s scs m o vargs = ok (rscs, rm, vres) \u2192 \n  mem_equiv m rm.\nProof.\n  rewrite /exec_syscall_s; t_xrbindP => -[[scs' m'] t] happ [_ <- _].\n  apply (mk_forallP (sem_syscall_equiv o scs m) happ).\nQed.\n\nEnd Section.\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/syscall_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.18344462413189044}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import msl.base.\nOpen Local Scope nat_scope.\n\nRequire Import msl.ageable.\nRequire Import msl.functors.\nRequire Import msl.sepalg.\nRequire Import msl.sepalg_functors.\nRequire Import msl.sepalg_generators.\nRequire Import msl.predicates_hered.\nRequire Import msl.knot_hered.\nRequire Import msl.knot_lemmas.\nRequire Import msl.age_sepalg.\n\nModule Type TY_FUNCTOR_SA_PROP.\n  Declare Module TF:TY_FUNCTOR_PROP.\n  Import TF.\n\n  Parameter Join_F: forall A, Join (F A). Existing Instance Join_F.\n(*   Parameter Perm_F: forall A, Perm_alg (F A). EXisting Instance Perm_F. *)\n  Parameter paf_F : pafunctor f_F.        Existing Instance paf_F.\n  Parameter Perm_F: Perm_paf f_F Join_F.\n  Parameter Sep_F: Sep_paf f_F Join_F.\n  Parameter Canc_F: Canc_paf f_F Join_F.\n  Parameter Disj_F: Disj_paf f_F Join_F.\nEnd TY_FUNCTOR_SA_PROP.\n\nModule Type KNOT_HERED_SA.\n  Declare Module TFSA:TY_FUNCTOR_SA_PROP.\n  Declare Module K:KNOT_HERED with Module TF:=TFSA.TF.\n\n  Import TFSA.TF.\n  Import TFSA.\n  Import K.\n\n  Parameter Join_knot: Join knot.  Existing Instance Join_knot.\n  Parameter Perm_knot : Perm_alg knot.  Existing Instance Perm_knot.\n  Parameter Sep_knot : (forall A, Sep_alg (F A)) -> Sep_alg knot.  Existing Instance Sep_knot.\n  Parameter Canc_knot : (forall A, Canc_alg (F A)) -> Canc_alg knot.  Existing Instance Canc_knot.\n  Parameter Disj_knot : (forall A, Disj_alg (F A)) -> Disj_alg knot.  Existing Instance Disj_knot.\n\n  Instance Join_nat_F: Join (nat * F predicate) := \n       Join_prod nat  (Join_equiv nat) (F predicate) _.\n\n Instance Perm_nat_F : Perm_alg (nat * F predicate) :=\n    @Perm_prod nat _ _ _ (Perm_equiv _) (Perm_F predicate _ (Perm_equiv _)).\n Instance Sep_nat_F (Sep_F: forall A, Sep_alg (F A)): Sep_alg (nat * F predicate) :=\n    @Sep_prod nat _ _ _ (Sep_equiv _) (Sep_F predicate).\n Instance Canc_nat_F (Canc_F: forall A, Canc_alg (F A)): Canc_alg (nat * F predicate) :=\n    @Canc_prod nat _ _ _ (Canc_equiv _) (Canc_F predicate).\n Instance Disj_nat_F (Disj_F: forall A, Disj_alg (F A)): Disj_alg (nat * F predicate) :=\n    @Disj_prod nat _ _ _ (Disj_equiv _) (Disj_F predicate).\n\n  Axiom join_unsquash : forall x1 x2 x3 : knot,\n    join x1 x2 x3 = join (unsquash x1) (unsquash x2) (unsquash x3).\n\n  Axiom asa_knot : Age_alg knot.\n\nEnd KNOT_HERED_SA.\n\nModule KnotHeredSa (TFSA':TY_FUNCTOR_SA_PROP) (K':KNOT_HERED with Module TF:=TFSA'.TF)\n  : KNOT_HERED_SA with Module TFSA:=TFSA' with Module K:=K'.\n\n  Module TFSA:=TFSA'.\n  Module K:=K'.\n\n  Module KL := KnotHered_Lemmas(K).\n\n  Import TFSA.TF.\n  Import TFSA.\n  Import K.\n  Import KL.\n\n  Instance Join_nat_F: Join (nat * F predicate) := \n       Join_prod nat  (Join_equiv nat) (F predicate) _.\n\n Instance Perm_nat_F : Perm_alg (nat * F predicate) :=\n    @Perm_prod nat _ _ _ (Perm_equiv _) (Perm_F predicate _ (Perm_equiv _)).\n Instance Sep_nat_F (Sep_F: forall A, Sep_alg (F A)): Sep_alg (nat * F predicate) :=\n    @Sep_prod nat _ _ _ (Sep_equiv _) (Sep_F predicate).\n Instance Canc_nat_F (Canc_F: forall A, Canc_alg (F A)): Canc_alg (nat * F predicate) :=\n    @Canc_prod nat _ _ _ (Canc_equiv _) (Canc_F predicate).\n Instance Disj_nat_F (Disj_F: forall A, Disj_alg (F A)): Disj_alg (nat * F predicate) :=\n    @Disj_prod nat _ _ _ (Disj_equiv _) (Disj_F predicate).\n\n  Lemma unsquash_squash_join_hom : join_hom (unsquash oo squash).\n  Proof.\n    unfold compose.\n    intros [x1 x2] [y1 y2] [z1 z2] ?.\n    do 3 rewrite (unsquash_squash).\n    firstorder.\n    simpl in *.\n    subst y1.\n    subst z1.\n    apply paf_join_hom. auto.\n  Qed.\n\n  Instance Join_knot : Join knot := \n           Join_preimage knot (nat * F predicate) Join_nat_F unsquash.\n\n  Instance Perm_knot : Perm_alg knot := \n    Perm_preimage _ _ _ _ unsquash squash squash_unsquash unsquash_squash_join_hom.\n\n  Instance Sep_knot(Sep_F: forall A, Sep_alg (F A)) : Sep_alg knot := \n    Sep_preimage _ _ _  unsquash squash squash_unsquash unsquash_squash_join_hom.\n\n  Lemma join_unsquash : forall x1 x2 x3,\n    join x1 x2 x3 =\n    join (unsquash x1) (unsquash x2) (unsquash x3).\n  Proof.\n    intuition.\n  Qed.\n\n  Instance Canc_knot(Canc_F: forall A, Canc_alg (F A)) : Canc_alg knot.\n  Proof. repeat intro. \n            do 3 red in H, H0.\n            apply unsquash_inj.\n            apply (join_canc H H0).\n  Qed.\n\n  Instance Disj_knot(Disj_F: forall A, Disj_alg (F A)) : Disj_alg knot.\n  Proof.\n   repeat intro.\n   do 3 red in H.\n   apply join_self in H.\n   apply unsquash_inj; auto.\n  Qed.\n  \n  Lemma age_join1 :\n    forall x y z x' : K'.knot,\n      join x y z ->\n      age x x' ->\n      exists y' : K'.knot,\n        exists z' : K'.knot, join x' y' z' /\\ age y y' /\\ age z z'.\n  Proof.\n    intros.\n    unfold age in *; simpl in *.\n    rewrite knot_age1 in H0.\n    repeat rewrite knot_age1.\n    do 3 red in H.\n    destruct (unsquash x).\n    destruct (unsquash y).\n    destruct (unsquash z).\n    destruct n; try discriminate.\n    inv H0.\n   simpl in H; destruct H.\n    simpl in H; destruct H.\n    subst n0 n1.\n    exists (squash (n,f0)).\n    exists (squash (n,f1)).\n    simpl in H0.\n    split; intuition. do 3  red.\n    repeat rewrite unsquash_squash.\n    split; auto. simpl snd.\n    apply paf_join_hom; auto.\n  Qed.\n  Lemma age_join2 :\n    forall x y z z' : K'.knot,\n      join x y z ->\n      age z z' ->\n      exists x' : K'.knot,\n        exists y' : K'.knot, join x' y' z' /\\ age x x' /\\ age y y'.\n  Proof.\n    intros.\n    unfold age in *; simpl in *.\n    rewrite knot_age1 in H0.\n    repeat rewrite knot_age1.\n    do 3 red in H.\n    destruct (unsquash x).\n    destruct (unsquash y).\n    destruct (unsquash z).\n    destruct n1; try discriminate.\n    inv H0.\n    destruct H; simpl in *.\n    destruct H; subst.\n    exists (squash (n1,f)).\n    exists (squash (n1,f0)).\n    split; intuition. do 3  red.\n    repeat rewrite unsquash_squash.\n    split; auto. simpl snd.\n    apply paf_join_hom; auto.\n  Qed.\n\n  Lemma unage_join1 : forall x x' y' z', join x' y' z' -> age x x' ->\n    exists y, exists z, join x y z /\\ age y y' /\\ age z z'.\n  Proof.\n    intros.\n    unfold join, Join_knot, Join_preimage, age in *; simpl in *.\n    revert H0; rewrite knot_age1; case_eq (unsquash x); intros.\n    destruct n; inv H1.\n    hnf in H. rewrite unsquash_squash in H. simpl in H.\n    revert H.\n    case_eq (unsquash y');\n    case_eq (unsquash z'); intros.\n    destruct H2; simpl in *.\n    destruct H2; subst.\n    rename n0 into n.\n    destruct (paf_preserves_unmap_right (approx n) f f1 f0)\n      as [q [w [? [? ?]]]].\n    rewrite <- (unsquash_approx H1); auto.\n    exists (squash (S n,q)).\n    exists (squash (S n,w)). split. hnf.\n    repeat rewrite unsquash_squash.\n    split; simpl; auto.\n    generalize (paf_join_hom (approx (S n)) _ _ _ H2).\n    rewrite <- (unsquash_approx H0); auto.\n\n    split; hnf.\n    rewrite knot_age1.\n    rewrite unsquash_squash. f_equal.\n    replace y' with (squash (n,fmap (approx (S n)) q)); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H1.\n    apply injective_projections; simpl; auto.\n    rewrite (unsquash_approx H1).\n    rewrite <- H4.\n    rewrite fmap_app.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality a.\n    replace (S n) with (1 + n)%nat by trivial.\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n\n    rewrite knot_age1.\n    rewrite unsquash_squash. f_equal.\n    replace z' with  (squash (n,fmap (approx (S n)) w)); auto.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H.\n    apply injective_projections; simpl; auto.\n    rewrite <- H5.\n    rewrite fmap_app.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality a.\n    replace (S n) with (1 + n)%nat by trivial.\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n  Qed.\n\n  Lemma unage_join2 :\n    forall z x' y' z', join x' y' z' -> age z z' ->\n      exists x, exists y, join x y z /\\ age x x' /\\ age y y'.\n  Proof.\n    intros.\n    rewrite join_unsquash in H. \n    revert H H0.\n    unfold join, Join_knot, Join_preimage, age in *; simpl in *.\n    repeat rewrite knot_age1.\n\n    case_eq (unsquash x');\n    case_eq (unsquash y');\n    case_eq (unsquash z');\n    case_eq (unsquash z); intros.\n    destruct n;  inv H4.\n    destruct H3. hnf in H3. simpl in *. destruct H3; subst.\n    rewrite unsquash_squash in H0.\n    inv H0.\n    rename n0 into n.\n\n    destruct (paf_preserves_unmap_left\n      (approx n) f2 f1 f)\n      as [wx [wy [? [? ?]]]]; auto.\n    rewrite <- (unsquash_approx H1); auto.\n    exists (squash (S n, wx)).\n    exists (squash (S n, wy)).\n    split. unfold join, Join_nat_F, Join_prod; simpl.\n    (* unfold Join_knot; simpl. unfold Join_preimage; simpl. *)\n    repeat rewrite unsquash_squash.  simpl.  split; auto. \n\n    rewrite (unsquash_approx H).\n    apply paf_join_hom; auto.\n    split; rewrite knot_age1; rewrite unsquash_squash; f_equal; hnf.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H2.\n    apply injective_projections; simpl; auto.\n    rewrite fmap_app.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    extensionality x.\n    unfold compose.\n    change (approx n (approx (S n) x)) with ((approx n oo approx (1 + n)) x).\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n    apply unsquash_inj.\n    rewrite unsquash_squash, H1.\n    apply injective_projections; simpl; auto.\n    rewrite fmap_app.\n    replace (approx n oo approx (S n)) with (approx n); auto.\n    rewrite H5.\n    rewrite <- (unsquash_approx H1); auto.\n    extensionality x.\n    unfold compose.\n    change (approx n (approx (S n) x)) with ((approx n oo approx (1 + n)) x).\n    rewrite <- (approx_approx1 1 n).\n    trivial.\n  Qed.\n\n  Theorem asa_knot : @Age_alg knot _ K.ag_knot.\n  Proof.\n    constructor.\n    exact age_join1.\n    exact age_join2.\n    exact unage_join1.\n    exact unage_join2.\n  Qed.\n\nEnd KnotHeredSa.\n", "meta": {"author": "lexuanbach", "repo": "certified-permission-procedure", "sha": "f0ac470d8096b106ea03c22e95950bae684bcc86", "save_path": "github-repos/coq/lexuanbach-certified-permission-procedure", "path": "github-repos/coq/lexuanbach-certified-permission-procedure/certified-permission-procedure-f0ac470d8096b106ea03c22e95950bae684bcc86/msl/knot_hered_sa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18344462060986297}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext uniq_tac machine_int multi_int.\nImport MachineInt.\nRequire Import mips_seplog mips_frame mips_contrib mips_tactics mips_mint.\nImport expr_m.\nImport assert_m.\nRequire Import multi_add_s_u_prg pick_sign_prg copy_u_u_prg multi_add_u_u_prg.\nRequire Import multi_lt_prg multi_sub_u_u_prg multi_negate_prg multi_is_zero_u_prg.\nRequire Import pick_sign_triple multi_add_u_u_triple.\nRequire Import multi_lt_triple multi_sub_u_u_R_triple.\nRequire Import multi_sub_u_u_L_triple multi_negate_triple.\nRequire Import multi_is_zero_u_triple copy_u_u_triple.\n\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope multi_int_scope.\n\nLemma multi_add_s_u'_triple rk rx ry a0 a1 a2 a3 a4 a5 rX :\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, a5, rX, r0) ->\n  forall k vx vy ptr, k <> O -> Z_of_nat k < 2 ^^ 31 ->\n    u2Z ptr + 4 * Z_of_nat k < \\B^1 ->\n  forall X Y, size X = k -> size Y = k -> 0 < \\S_{ k } Y ->\n  forall slen, s2Z slen = sgZ (s2Z slen) * Z_of_nat k ->\n{{ fun s h => [ rx ]_s = vx /\\ [ ry ]_s = vy /\\ u2Z [ rk ]_s = Z_of_nat k /\\\n   ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) ** var_e ry |--> Y) s h }}\n multi_add_s_u0 rk rx ry a0 a1 a2 a3 a4 a5 rX\n{{ fun s h => exists X' slen', size X' = k /\\\n  [ rx ]_s = vx /\\ [ ry ]_s = vy /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat k /\\\n  sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ k } X + \\S_{ k } Y) /\\\n  ((var_e rx |--> slen' :: ptr :: nil ** int_e ptr |--> X') ** var_e ry |--> Y) s h /\\\n  u2Z ([a3]_ s) <= 1 /\\\n  sgZ (s2Z slen') * (\\S_{ k } X' + u2Z ([a3]_ s) * \\B^k) =\n  sgZ (s2Z slen) * \\S_{ k } X + \\S_{ k } Y }}.\nProof.\nmove=> Hregs nk va vb ptr Hnk Hnk' ptr_fit A B len_A len_B nk_B slen slen_no_weird.\nrewrite /multi_add_s_u0.\n\n(** lw rX four16 rx *)\n\napply hoare_lw_back_alt'' with (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\\n  u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [ rX ]_s = ptr /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h).\n\nrewrite /while.entails => s h [r_a [r_b [r_k Hmem]]].\nexists ptr; split.\n- rewrite conCE !conAE conCE !conAE\n    conCE !conAE in Hmem.\n  move: Hmem; apply monotony => // h'; apply mapsto_ext => //; by rewrite sext_Z2u.\n- rewrite /update_store_lw.\n  repeat Reg_upd; repeat (split => //).\n  by Assert_upd.\n\n(** pick_sign rx a0 a1 *)\n\napply while.hoare_seq with (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\\n  u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [ rX ]_s = ptr /\\ [a0]_s = slen /\\\n  sgZ (s2Z [a1]_s) = sgZ (s2Z slen) /\\ (s2Z [a1]_s = 0 \\/ s2Z [a1]_s = 1 \\/ s2Z [a1]_s = -1 ) /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h).\n\neapply while.hoare_conseq; last first.\napply (pick_sign_triple\n  (fun s h => [ ry ]_ s = vb /\\ u2Z [ rk ]_ s = Z_of_nat nk /\\ [ rX ]_ s = ptr)\n  (((var_e rx \\+ int_e four32 |~> int_e ptr ** (fun st h0 =>\n    u2Z (([ rx ]_ st `+ four32) `+ four32) mod 4 = 0 /\\\n    emp st h0)) ** int_e ptr |--> A) ** var_e ry |--> B) va slen).\n\nby Uniq_uniq r0.\nInde.\nmove=> s h x v /= [].\nmove=> ?; subst a1; by Reg_upd.\ncase=> // ?; subst a0; by Reg_upd.\nby Inde.\nmove=> s h /= [Ha [Hb [Hk [HX Hmem]]]].\nby rewrite !conAE in Hmem *.\nmove=> s h /= [Ha [Ha0 [Ha1 [Ha1' [Hmem [Hb [Hk HX]]]]]]].\nby rewrite !conAE in Hmem *.\n\n(** If_bgez a1 Then *)\n\napply while.hoare_ifte.\n\n(** If_beq a1, r0 Then *)\n\napply while.hoare_ifte.\n\napply while.hoare_seq with (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\\n  u2Z [ rk ]_ s = Z_of_nat nk /\\ [ rX ]_ s = ptr /\\ [a0 ]_ s = slen /\\\n  sgZ (s2Z slen) = 0 /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> B) ** var_e ry |--> B) s h).\n\n(** copy_u_u rk rX ry a2 a3 a4 *)\n\napply (before_frame\n  (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ [a0 ]_ s = slen /\\\n    sgZ (s2Z slen) = 0 /\\ (var_e rx |--> slen :: ptr :: nil) s h)\n  (fun s h => [ rX ]_s = ptr /\\ u2Z [ rk ]_s = Z_of_nat nk /\\\n    (var_e ry |--> B ** var_e rX |--> A) s h)\n  (fun s h => [ rX ]_s = ptr /\\ u2Z [ rk ]_s = Z_of_nat nk /\\\n    (var_e ry |--> B ** var_e rX |--> B) s h)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\n\napply copy_u_u_triple => //; by Uniq_uniq r0.\nmove=> s h [ [[Ha [Hb [Hk [HX [Ha0 [a1_slen [Ha1' mem]]]]]]] _] Ha1].\nrewrite conAE in mem.\ncase: mem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nrepeat (split => //).\nrewrite conCE.\nmove: Hh2; apply monotony => // h'; exact: mapstos_ext.\nrewrite /= in Ha1.\nmove/eqP/u2Z_inj in Ha1.\nrewrite store.get_r0 in Ha1.\nby rewrite -a1_slen Ha1 s2Z_u2Z_pos' // Z2uK.\n\nmove=> s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh2 => [Ha [Hb [Ha0 [Ha1' Hh2]]]].\ncase: Hh1 => Hx [Hk Hh1].\nrepeat (split => //).\nrewrite conAE.\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nrepeat (split => //).\nrewrite conCE.\nmove: Hh1; apply monotony => h' //; exact: mapstos_ext.\n\n(** addiu a3 r0 zero16 *)\n\napply hoare_addiu with (fun s h =>\n  [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z [ rk ]_ s = Z_of_nat nk /\\\n  [ rX ]_ s = ptr /\\ [a0 ]_ s = slen /\\ [a3]_s = zero32 /\\\n  sgZ (s2Z slen) = 0 /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> B) ** var_e ry |--> B) s h).\n\nmove=> s h [Ha [Hb [Hk [HX [Ha0 [Ha1 mem]]]]]].\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split => //).\nby rewrite add0i sext_Z2u.\nby Assert_upd.\n\n(** sw rk zero16 a *)\n\napply hoare_sw_back'.\nmove=> s h [Ha [Hb [Hk [HX [Ha0 [Ha3 [Hslen mem]]]]]]].\nexists (int_e slen).\nrewrite !conAE /= in mem.\nmove: mem; apply monotony => // h'.\napply mapsto_ext => //; by rewrite /= sext_Z2u // addi0.\napply currying => h'' Hh''.\nexists B, (Z2s 32 (Z_of_nat nk)).\nrepeat (split => //).\n\nrewrite Z2sK //; last lia.\nrewrite (proj2 (Zsgn_pos (Z_of_nat nk))); lia.\n\nrewrite Z2sK //; last lia.\nrewrite Hslen /= (proj2 (Zsgn_pos (Z_of_nat nk))); last lia.\nby rewrite (proj2 (Zsgn_pos (\\S_{ nk } B))).\n\nrewrite conCE in Hh''.\nrewrite /= !conAE.\nmove: Hh''; apply monotony => // h'''.\napply mapsto_ext => /=.\nby rewrite sext_Z2u // addi0.\napply u2Z_inj.\nrewrite Hk u2Z_Z2s_pos //.\nsplit; by [lia | apply: @ltZ_leZ_trans; [exact: Hnk' | ]].\nby rewrite Ha3 Z2uK.\nrewrite Z2sK //; last lia.\nrewrite (proj2 (Zsgn_pos (Z_of_nat nk))); last lia.\nby rewrite mul1Z Hslen /= Ha3 Z2uK // mul0Z addZ0.\n\n(** addiu a3 r0 one16; *)\n\napply hoare_addiu with (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z [ rk ]_ s = Z_of_nat nk /\\\n  [ rX ]_ s = ptr /\\ [a0 ]_ s = slen /\\ sgZ (s2Z [a1 ]_ s) = sgZ (s2Z slen) /\\\n  s2Z [a1]_s = 1 /\\ [a3]_s = one32 /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h).\n\nrewrite /wp_addiu => s h [[[Ha [Hb [Hk [HX [Ha0 [Ha1 [Ha1'' mem]]]]]]] Ha1'''] Ha1'].\nrepeat Reg_upd.\nrewrite /= in Ha1' Ha1'''.\nmove/leZP in Ha1'''.\nrewrite store.get_r0 Z2uK // in Ha1'.\nmove/eqP in Ha1'.\nrepeat (split => //).\ncase: Ha1'' => [Ha1'' | [ // | Ha1'']].\nrewrite (_ : 0 = s2Z zero32) in Ha1''; last by rewrite s2Z_u2Z_pos' Z2uK.\nmove/s2Z_inj in Ha1''.\nby rewrite Ha1'' Z2uK in Ha1'.\nlia.\nby rewrite add0i sext_Z2u.\nby Assert_upd.\n\n(** multi_add_u_u rk a3 ry rX rX a0 a1 a2 *)\n\napply while.hoare_seq with (fun s h => exists A' slen', size A' = nk /\\\n  [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat nk /\\\n  ((var_e rx |--> slen' :: ptr :: nil ** int_e ptr |--> A') ** var_e ry |--> B) s h /\\\n  u2Z (store.lo s) <= 1 /\\\n  sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ nk } A + \\S_{ nk } B) /\\\n  sgZ (s2Z slen') * (\\S_{ nk } A' + u2Z (store.lo s) * \\B^nk) =\n  sgZ (s2Z slen) * \\S_{ nk } A + \\S_{ nk } B).\n\nhave : uniq(rk, a3, ry, rX, a0, a1, a2, r0) by Uniq_uniq r0.\nmove/multi_add_u_u_triple.\nmove/(_ nk vb ptr ptr_fit _ _ len_B len_A) => Htmp.\n\napply (before_frame\n  (fun s h => sgZ (s2Z slen) = 1 /\\ [ rx ]_ s = va /\\ (var_e rx |--> slen :: ptr :: nil) s h)\n  (fun s h =>\n    ([a3]_s = one32 /\\ [ ry ]_ s = vb /\\ [ rX ]_ s = ptr /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\\n      (var_e rX |--> A ** var_e ry |--> B) s h) /\\\n    [ rx ]_ s = va /\\ [a0 ]_ s = slen /\\ 0 <= sgZ (s2Z slen) /\\ eval_b (bgez a1) s)\n  (fun s h => exists A',\n    size A' = nk /\\ [ ry ]_s = vb /\\ [ rX ]_ s = ptr /\\ (var_e ry |--> B ** var_e rX |--> A') s h /\\\n    u2Z (store.lo s) <= 1 /\\ \\S_{ nk } A' + u2Z (store.lo s) * \\B^nk = \\S_{ nk } A + \\S_{ nk } B)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\neapply while.hoare_conseq; last exact: Htmp.\nby rewrite addZC.\n\nrewrite /while.entails => s h [[Hone [Hb [HX [Hk Hmem]]]] [Ha [Ha0 [HZsgn Ha1]]]].\nmove/leZP in Ha1.\nby rewrite conCE in Hmem.\n\nrewrite /while.entails => s h [Ha [Hb [Hk [HX [Ha0 [Hsgn [Hsgn' [Ha3 Hmem]]]]]]]].\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nrepeat (split => //).\nmove: Hh2; apply monotony => h' //; exact: mapstos_ext.\nrewrite -Hsgn; by rewrite Hsgn'.\nrewrite /=; apply/leZP; lia.\nby rewrite -Hsgn Hsgn'.\n\nrewrite /while.entails => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [[A' [A'_nk [r_b [HX [Hh1 [Hlo Hsum]]]]]] [Hsgn [r_a Hh2]]]]]]].\nexists A', slen.\nrepeat (split => //).\nrewrite conAE.\nexists h2, h1.\nsplit; first by heap_tac_m.Disj.\nsplit; first by heap_tac_m.Equal.\nsplit; first by [].\nrewrite conCE.\nmove: Hh1; apply monotony => h' //; exact: mapstos_ext.\nrewrite Hsgn mul1Z (proj2 (Zsgn_pos (\\S_{ nk } A + \\S_{ nk } B))) //.\nmove: (min_lSum nk A) => ?; lia.\nby rewrite Hsgn 2!mul1Z.\n\n(** mflo a3 *)\n\napply hoare_mflo'.\n\nrewrite /while.entails => s h [A' [slen' [len_A' [r_a [r_b [slen'_nk [Hmem [Hlo [Hsgn Hsum]]]]]]]]].\nrewrite /wp_mflo.\nexists A', slen'.\nrepeat Reg_upd; repeat (split => //).\nmove: Hmem; apply inde_upd_store; by Inde.\n\n(** multi_lt rk ry rX a0 a1 a5 a2 a3 a4 ; *)\n\napply while.hoare_seq with (fun s h =>\n  ([ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\\n    [ rX ]_ s = ptr /\\ sgZ (s2Z slen) = -1 /\\\n    ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h) /\\\n  ((\\S_{ nk } B < \\S_{ nk } A /\\ [a5]_s = one32 /\\ [a2]_s = zero32 ) \\/\n   (\\S_{ nk } B > \\S_{ nk } A /\\ [a5]_s = zero32 /\\ [a2]_s = one32 ) \\/\n   (\\S_{ nk } B = \\S_{ nk } A /\\ [a5]_s = zero32 /\\ [a2]_s = zero32))).\n\napply (before_frame\n  (fun s h => [ rx ]_ s = va /\\ sgZ (s2Z slen) = -1 /\\ (var_e rx |--> slen :: ptr :: nil) s h)\n  (fun s h => u2Z [ rk ]_s = Z_of_nat nk /\\\n    [ ry ]_s = vb /\\ [ rX ]_s = ptr /\\ (var_e ry |--> B ** var_e rX |--> A) s h)\n  (fun s h => u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [ ry ]_ s = vb /\\ [ rX ]_ s = ptr /\\\n    ((\\S_{ nk } B < \\S_{ nk } A /\\ ([a5 ]_ s) = one32 /\\ [a2]_s = zero32) \\/\n      (\\S_{ nk } B > \\S_{ nk } A /\\ ([a5 ]_ s) = zero32 /\\ [a2]_s = one32) \\/\n      (\\S_{ nk } B = \\S_{ nk } A /\\ ([a5 ]_ s) = zero32 /\\ [a2]_s = zero32)) /\\\n    (var_e ry |--> B ** var_e rX |--> A) s h)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\napply multi_lt_triple => //; by Uniq_uniq r0.\n\nrewrite /while.entails => s h [[Ha [Hb [Hk [HX [Ha0 [HZgn [Hsgn' Hmem]]]]]]] Ha1].\nrewrite conAE in Hmem.\ncase : Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1.\nrepeat (split => //).\nrewrite conCE.\nmove: Hh2; apply monotony => // h'; exact: mapstos_ext.\nrepeat (split => //).\nrewrite /= in Ha1.\nmove/leZP in Ha1.\ncase: Hsgn' => Hsgn'; first lia.\ncase: Hsgn' => Hsgn'; first lia.\nby rewrite -HZgn Hsgn'.\n\nrewrite /while.entails => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\ncase: Hh1 => Hk [Hb [hX [Hsum Hh1]]].\ncase: Hh2 => Ha [Hsgn Hh2].\nsplit.\n- repeat (split => //).\n  rewrite conAE.\n  Compose_sepcon h2 h1 => //.\n  rewrite conCE.\n  move: Hh1; apply monotony => // h'; exact: mapstos_ext.\n- case: Hsum => Hsum.\n  left; tauto.\n  by right.\n\n(** If_beq a5,r0 Then *)\n\napply while.hoare_ifte.\n\n(** If_beq a2,r0 Then *)\n\napply while.hoare_ifte.\n\n(** addiu a3 r0 zero16 ; *)\n\napply hoare_addiu with (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\\n  u2Z [ rk ]_ s = Z_of_nat nk /\\ [ rX ]_ s = ptr /\\ [a3]_s = zero32 /\\\n  sgZ (s2Z slen) = -1 /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h  /\\\n  \\S_{ nk } B = \\S_{ nk } A).\n\nmove=> s h [ [[ [Ha [Hb [Hk [HX [Hslen mem]]] ]] Hsum] Ha5] Ha2].\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split => //).\nby rewrite add0i sext_Z2u.\nby Assert_upd.\nrewrite /= in Ha5 Ha2.\nmove/eqP/u2Z_inj in Ha5.\nmove/eqP/u2Z_inj in Ha2.\ncase: Hsum => Hsum.\n- rewrite Ha5 store.get_r0 in Hsum.\n  case: Hsum => _ [Hsum _].\n  by apply Z2u_dis in Hsum.\n- case: Hsum => Hsum; last tauto.\n  case: Hsum => _ [_ Hsum].\n  rewrite Ha2 store.get_r0 in Hsum.\n  by apply Z2u_dis in Hsum.\n\n(** sw r0 zero16 rx *)\n\napply hoare_sw_back'.\nmove=> s h [Ha [Hb [Hk [HX [Ha3 [Hslen [mem Hsum]]]]]]].\nexists (int_e slen).\nrewrite !conAE /= in mem.\nmove: mem; apply monotony => // h'.\napply mapsto_ext => //=; by rewrite sext_Z2u // addi0.\napply currying => h'' Hh''.\nexists A (*NB: whatever*), (Z2s 32 0).\nrepeat (split => //).\nby rewrite Z2sK.\n\nby rewrite Z2sK //= Hslen Hsum addZC mulN1Z addZN.\nrewrite conCE in Hh''.\nrewrite !conAE /=.\nmove: Hh''; apply monotony => // h'''.\napply mapsto_ext => /=.\nby rewrite sext_Z2u // addi0.\nrewrite store.get_r0.\napply u2Z_inj.\nby rewrite Z2uK // u2Z_Z2s_pos.\nby rewrite Ha3 Z2uK.\nrewrite Z2sK //= Hslen Hsum; ring.\n\n(** multi_sub_u_u rk ry rX rX a0 a1 a2 a3 a4 a5 ; *)\n\napply hoare_prop_m.hoare_stren with (fun s h => \\S_{ nk } B > \\S_{ nk } A /\\\n  (([ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\\n    [ rX ]_ s = ptr /\\ sgZ (s2Z slen) = -1 /\\\n    ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h))).\n\nrewrite /while.entails => s h [[[[Ha [Hb [Hk [HX [Hsgn Hmem]]]]] Hsum] Ha5] Ha2].\nrepeat (split => //).\nrewrite /= store.get_r0 Z2uK // in Ha5.\nmove/eqP in Ha5.\ncase: Hsum => Hsum.\n- case: Hsum => _ [Hsum _].\n  by rewrite Hsum Z2uK in Ha5.\n- rewrite /= in Ha2.\n  move/eqP in Ha2.\n  case: Hsum => Hsum; first by tauto.\n  case: Hsum => _ [_ Hsum].\n  by rewrite Hsum Z2uK // store.get_r0 // Z2uK in Ha2.\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => HAB.\n\napply while.hoare_seq with (fun s h => exists A', size A' = nk /\\\n  [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ s2Z slen = sgZ (s2Z slen) * Z_of_nat nk /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A') ** var_e ry |--> B) s h /\\\n  [a3]_s = zero32 /\\ sgZ (s2Z slen) = -1 /\\\n  - sgZ (s2Z slen) * (\\S_{ nk } A' - u2Z ([a3 ]_ s) * \\B^nk) =\n  sgZ (s2Z slen) * \\S_{ nk } A + \\S_{ nk } B).\n\napply (before_frame\n  (fun s h => [ rx ]_ s = va /\\ sgZ (s2Z slen) = -1 /\\ (var_e rx |--> slen :: ptr :: nil) s h)\n  (fun s h => [ ry ]_s = vb /\\ [ rX ]_ s = ptr /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\\n    (var_e ry |--> B ** var_e rX |--> A) s h)\n  (fun s h => exists A', size A' = nk /\\\n    [ ry ]_s = vb /\\ [ rX ]_ s = ptr /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [a3]_s = zero32 /\\\n    (var_e ry |--> B ** var_e rX |--> A') s h /\\ \\S_{ nk } A' = \\S_{ nk } B - \\S_{ nk } A)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\n\napply multi_sub_u_u_R_triple_B_le_A => //.\nby Uniq_uniq r0.\nlia.\n\nrewrite /while.entails => s h [Ha [Hb [Hk [HX [Hsgn Hmem]]]]].\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1; last by [].\nrepeat (split => //).\nrewrite conCE.\nmove: Hh2; apply monotony => h' //; exact: mapstos_ext.\n\nrewrite /while.entails => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 [Hva [Hsgn Hh2]]]]]]].\ncase: Hh1 => A' [len_A' [Hb [HX [Hk [Ha3 [Hh1 Hsum]]]]]].\nexists A'.\nrepeat (split => //).\nrewrite conAE.\nCompose_sepcon h2 h1 => //.\nrewrite conCE.\nmove: Hh1; apply monotony => // h'; exact: mapstos_ext.\nrewrite Hsgn mulNZ mulN1Z oppZK Hsum Ha3 Z2uK // mul0Z subZ0; ring.\n\napply (hoare_prop_m.extract_exists extract_exists0) => A'.\n\n(** multi_negate rx a0 *)\n\napply (before_frame (fun s h => size A' = nk /\\ [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\\n  s2Z slen = sgZ (s2Z slen) * Z_of_nat nk /\\\n  (var_e ry |--> B) s h /\\ [a3 ]_ s = zero32 /\\ sgZ (s2Z slen) = -1 /\\\n  - sgZ (s2Z slen) * (\\S_{ nk } A' - u2Z [a3 ]_ s * \\B^nk) = sgZ (s2Z slen) * \\S_{ nk } A + \\S_{ nk } B)\n(var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A')\n(var_e rx |--> cplt2 slen :: ptr :: nil ** int_e ptr |--> A')).\n\napply frame_rule_R.\n- apply multi_negate_triple; by Uniq_uniq r0.\n- Inde_frame.\n  rewrite /inde => s h x v /= [] // ?; subst x; by Reg_upd.\n- move=> ?; by Inde_mult.\n\nrewrite /while.entails => s h [lenA' [r_a [r_b [slen'_nk [Hmem [Ha3 [Hsgn HSum]]]]]]].\nmove: Hmem; exact: monotony.\n\nrewrite /while.entails => s h Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\ncase: Hh2 => A'_nk [slen_nk_ [r_a [r_b [Hh2 [Ha3 [HZsgn HSum]]]]]].\nexists (cplt2 slen).\nrewrite s2Z_cplt2; last first.\n  rewrite weirdE2 slen_no_weird HZsgn; lia.\nrewrite Ha3 Z2uK // mul0Z subZ0 in HSum.\nrewrite Ha3 Z2uK // mul0Z addZ0 Zsgn_Zopp.\nrepeat (split => //).\n\nhave Htmp : - sgZ (s2Z slen) = 1 by rewrite HZsgn.\nrewrite !Htmp HZsgn in HSum *.\nrewrite r_b HZsgn; ring.\n\nhave Htmp : - sgZ (s2Z slen) = 1 by rewrite HZsgn.\nrewrite !Htmp HZsgn in HSum *.\nrewrite mul1Z in HSum.\nrewrite -HSum (proj2 (Zsgn_pos (\\S_{ nk } A'))) //.\nmove: (min_lSum nk A) => ?.\nrewrite HSum mulN1Z; lia.\nby Compose_sepcon h1 h2.\n\n(** multi_sub_u_u k rX b rX a0 a1 a5 a3 a2 a4 *)\n\napply hoare_prop_m.hoare_stren with (fun s h => \\S_{ nk } B < \\S_{ nk } A /\\\n  ([ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [ rX ]_ s = ptr /\\\n    sgZ (s2Z slen) = -1 /\\\n    ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h)).\n\nrewrite /while.entails => s h [[[Ha [Hb [Hk [HX [Hslen Hmem]]]]] Hsum] Ha5].\ncase: Hsum => Hsum; first by tauto.\nrewrite /= in Ha5.\nmove/eqP in Ha5.\nrewrite store.get_r0 in Ha5.\ncase: Hsum.\ncase=> _ [Hsum _].\nby rewrite Hsum Z2uK in Ha5.\ncase=> _ [Hsum _].\nby rewrite Hsum Z2uK in Ha5.\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => HAB.\n\napply (before_frame\n  (fun s h => [ rx ]_ s = va /\\ sgZ (s2Z slen) = -1 /\\ (var_e rx |--> slen :: ptr :: nil) s h)\n  (fun s h => [ rX ]_s = ptr /\\\n  [ ry ]_s = vb /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\ (var_e rX |--> A ** var_e ry |--> B) s h)\n  (fun s h => exists A', size A' = nk /\\\n    [ rX ]_s = ptr /\\ [ ry ]_s = vb /\\ u2Z ([ rk ]_ s) = Z_of_nat nk /\\ [a3]_s = zero32 /\\\n    (var_e rX |--> A' ** var_e ry |--> B) s h /\\ \\S_{ nk } A' = \\S_{ nk } A - \\S_{ nk } B)).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\n\napply multi_sub_u_u_L_triple_B_le_A => //.\nby Uniq_uniq r0.\nexact/ltZW.\n\nrewrite /while.entails => s h [Ha [Hb [Hk [HX [Hslen Hmem]]]]].\nrewrite conAE in Hmem.\ncase: Hmem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1; last by [].\nrepeat (split => //).\nmove: Hh2; apply monotony => // h'; exact: mapstos_ext.\n\nrewrite /while.entails => s h Hmem.\ncase: Hmem =>  h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\ncase: Hh1 => A' [len_A' [HX [Hb [Hk [Ha3 [Hh1 Hsum]]]]]].\ncase: Hh2 => Ha [Hsgn Hh2].\nexists A', slen.\nrepeat (split => //).\nrewrite Hsgn (proj2 (Zsgn_neg (-1 * \\S_{ nk } A + \\S_{ nk } B))) // addZC mulN1Z addZNE; lia.\nrewrite conAE.\nCompose_sepcon h2 h1; first by [].\nmove: Hh1; apply monotony => // h'.\nexact: mapstos_ext.\nby rewrite Ha3 Z2uK.\nrewrite Hsgn 2!mulN1Z Hsum Ha3 Z2uK // mul0Z; ring.\nQed.\n\nLemma multi_add_s_u_triple_gen rk rx ry a0 a1 a2 a3 a4 a5 rX :\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, a5, rX, r0) ->\n  forall k va vb ptr, k <> O -> Z_of_nat k < 2 ^^ 31 ->\n    u2Z ptr + 4 * Z_of_nat k < \\B^1 -> u2Z vb + 4 * Z_of_nat k < \\B^1 ->\n  forall X Y, size X = k -> size Y = k ->\n  forall slen, s2Z slen = sgZ (s2Z slen) * Z_of_nat k ->\n    sgZ (s2Z slen) = sgZ (sgZ (s2Z slen) * \\S_{ k } X) ->\n{{ fun s h => [ rx ]_s = va /\\ [ ry ]_s = vb /\\\n    u2Z [ rk ]_s = Z_of_nat k /\\\n    ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) ** var_e ry |--> Y) s h }}\n multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX\n {{ fun s h => exists X' slen', size X' = k /\\\n   [ rx ]_s = va /\\ [ ry ]_s = vb /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat k /\\\n   sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ k } X + \\S_{ k } Y) /\\\n   ((var_e rx |--> slen' :: ptr :: nil ** int_e ptr |--> X') ** var_e ry |--> Y) s h /\\\n   u2Z ([a3]_ s) <= 1 /\\\n   sgZ (s2Z slen') * (\\S_{ k } X' + u2Z ([a3]_ s) * \\B^k) =\n   sgZ (s2Z slen) * \\S_{ k } X + \\S_{ k } Y }}.\nProof.\nmove=> Hregs nk va vb ptr Hnk Hnk' ptr_fit vb_fit A B\n  len_A len_B slen slen_no_weird slen_A.\nrewrite /multi_add_s_u.\n\n(** multi_is_zero_u rk ry a0 a1 a2 ; *)\n\napply while.hoare_seq with (fun s h => [ rx ]_s = va /\\ [ ry ]_s = vb /\\\n  u2Z [ rk ]_s = Z_of_nat nk /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h /\\\n  ((0 = \\S_{ nk } B -> [a2]_s = one32) /\\ (0 < \\S_{ nk } B -> [a2]_s = zero32))).\n\napply (before_frame(fun s h => [ rx ]_ s = va /\\\n  (var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) s h)\n  (fun s h => u2Z [ rk ]_s = Z_of_nat nk /\\ [ ry ]_s = vb /\\ (var_e ry |--> B) s h)\n  (fun s h => u2Z [ rk ]_s = Z_of_nat nk /\\ [ ry ]_s = vb /\\ (var_e ry |--> B) s h  /\\\n    ((0 = \\S_{ nk } B -> [a2]_s = one32) /\\   (0 < \\S_{ nk } B -> [a2]_s = zero32)))).\n\napply frame_rule_R; last 2 first.\n  by Inde_frame.\n  move=> ?; by Inde_mult.\n  apply multi_is_zero_u_triple => //.\n  by Uniq_uniq r0.\n\nmove=> s h [Ha [Hb [Hk mem]]].\ncase: mem => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\nCompose_sepcon h2 h1.\nby repeat (split => //).\nby repeat (split => //).\nmove => s h [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]].\nrepeat (split; first by tauto).\nsplit; last by tauto.\nCompose_sepcon h2 h1; tauto.\n\n(** If_bne a2,r0 Then *)\n\napply while.hoare_ifte.\n\n(** addiu a3 r0 zero16 *)\n\napply hoare_addiu'.\nmove=> s h [ [Ha [Hb [Hk [mem Ha5]]]] Ha2].\nrewrite /= in Ha2.\nmove/eqP in Ha2.\nmove: (min_lSum nk B).\ncase/Z_le_lt_eq_dec => Hsum.\napply (proj2 Ha5) in Hsum.\nby rewrite Hsum Z2uK // store.get_r0 Z2uK in Ha2.\nexists A, slen.\nrepeat Reg_upd; repeat (split => //).\nrewrite -Hsum addZ0; exact slen_A.\nby Assert_upd.\nby rewrite sext_Z2u // addi0 Z2uK.\nrewrite sext_Z2u // addi0 Z2uK // mul0Z addZ0 -Hsum; ring.\n\n(** multi_add_s_u0 rk rx ry a0 a1 a2 a3 a4 a5 rX *)\n\napply hoare_prop_m.hoare_stren with\n  (!(fun s => 0 < \\S_{ nk } B) **\n    (fun s h => [ rx ]_ s = va /\\ [ ry ]_ s = vb /\\ u2Z [ rk ]_ s = Z_of_nat nk /\\\n      ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> A) ** var_e ry |--> B) s h)).\n\nmove=> s h [[Ha [Hb [Hk [mem Ha2']]]] Ha2].\nrewrite /= negbK in Ha2.\nmove/eqP/u2Z_inj in Ha2.\nmove: (min_lSum nk B).\ncase/Z_le_lt_eq_dec => Hsum; last first.\n   apply (proj1 Ha2') in Hsum.\n   rewrite Hsum store.get_r0 in Ha2.\n   by apply Z2u_dis in Ha2.\nby Compose_sepcon heap.emp h.\n\napply pull_out_bang => nk_B.\nexact: multi_add_s_u'_triple.\nQed.\n\nLemma multi_add_s_u_triple rk rx ry a0 a1 a2 a3 a4 a5 rX :\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, a5, rX, r0) ->\n  forall k, 0 < Z_of_nat k < 2 ^^ 31 -> (* not the weird number *)\n  forall vx vy X Y,\n{{ fun s h => [rx]_s = vx /\\ [ry]_s = vy /\\\n    u2Z [rk]_s = Z_of_nat k /\\\n    (var_signed k rx X ** var_unsign k ry Y) s h }}\n multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX\n {{ fun s h => exists X' l' ptr, size X' = k /\\\n   [rx]_s = vx /\\ [ry]_s = vy /\\ s2Z l' = sgZ (s2Z l') * Z_of_nat k /\\\n   sgZ (s2Z l') = sgZ (X + Y) /\\\n   ((var_e rx |--> l' :: ptr :: List.nil ** int_e ptr |--> X') **\n     var_unsign k ry Y) s h /\\\n   u2Z ([a3]_ s) <= 1 /\\\n   sgZ (s2Z l') * (\\S_{ k } X' + u2Z ([a3]_ s) * \\B^k) = X + Y }}.\nProof.\nmove=> Hvars nk nk_0_max va vb A B.\napply hoare_prop_m.hoare_stren with (fun s h => exists slen ptr A0,\n      u2Z va + 4 * 2 < \\B^1 /\\\n      0 <= B < \\B^nk /\\\n      sgZ (s2Z slen) = sgZ A /\\\n      u2Z ptr + 4 * Z_of_nat nk < \\B^1 /\\\n      u2Z vb + 4 * Z_of_nat nk < \\B^1 /\\\n      s2Z slen = sgZ (s2Z slen) * Z_of_nat nk /\\\n      A = sgZ (s2Z slen) * \\S_{ nk } A0 /\\\n      size A0 = nk /\\\n      [rx]_s = va /\\ [ry]_s = vb /\\\n      u2Z [rk ]_ s = Z_of_nat nk /\\\n      ((fun st h0 =>\n        ((var_e rx |--> slen :: (ptr :: Datatypes.nil)%list **\n          int_e ptr |--> A0) st h0)) **\n       (fun st h0 =>\n        (var_e ry |--> Z2ints 32 nk B) st h0))\n        s h).\n  move=> s h H.\n  case: H => k_nk [a_va [b_vb [h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]]]]].\n  case: Hh1 => slen ptr A0 a_fit encodingA ptr_fit Hmem.\n  case: Hh2 => b_fit B_over G_mem.\n  exists slen, ptr, A0; repeat (split => //).\n  by subst va.\n  by case: encodingA => *.\n  by subst vb.\n  by case: encodingA => *.\n  by case: encodingA => *.\n  by case: encodingA => *.\n  by exists h1, h2.\napply mips_contrib.pull_out_exists => slen.\napply mips_contrib.pull_out_exists => ptr.\napply mips_contrib.pull_out_exists => A0.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => ?.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => ?.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => slen_A.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => ptr_fit.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => vb_fit.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => slen_nk.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => A_A0.\napply (hoare_prop_m.pull_out_conjunction' mips_contrib.hoare0_false) => A0_nk.\napply while.hoare_conseq with\n  (P' := fun s h => [rx]_s = va /\\ [ry]_s = vb /\\ u2Z [rk]_s = Z_of_nat nk /\\\n    ((var_e rx |--> slen :: ptr :: List.nil **\n      int_e ptr |--> A0) ** var_e ry |--> Z2ints 32 nk B) s h)\n  (Q':= fun s h => exists A' slen', size A' = nk /\\\n    [rx]_s = va /\\ [ry]_s = vb /\\ s2Z slen' = sgZ (s2Z slen') * Z_of_nat nk /\\\n    sgZ (s2Z slen') = sgZ (sgZ (s2Z slen) * \\S_{ nk } A0 + \\S_{ nk } (Z2ints 32 nk B)) /\\\n    ((var_e rx |--> slen' :: ptr :: List.nil ** int_e ptr |--> A') **\n      var_e ry |--> Z2ints 32 nk B) s h /\\\n    u2Z ([a3]_ s) <= 1 /\\\n   sgZ (s2Z slen') * (\\S_{ nk } A' + u2Z ([a3]_ s) * \\B^nk) =\n   sgZ (s2Z slen) * \\S_{ nk } A0 + \\S_{ nk } (Z2ints 32 nk B)).\n- move=> s h H.\n  case: H => A' [slen' [A'_nk [a_va [b_vb [slen'_nk [slen'_A_B [Hmem [Ha3 HA']]]]]]]].\n  exists A', slen', ptr.\n  repeat (split => //).\n  + rewrite slen'_A_B.\n    rewrite lSum_Z2ints; last by rewrite Z.abs_eq; tauto.\n    rewrite A_A0.\n    rewrite Z.abs_eq; tauto.\n  + move: Hmem; apply assert_m.monotony => // h' Hh'.\n    apply mkVarUnsign => //.\n    congruence.\n  + rewrite lSum_Z2ints in HA'; last by rewrite Z.abs_eq; tauto.\n    rewrite HA' -A_A0 Z.abs_eq; tauto.\n- move=> s h [a_va [b_vb [k_nk H]]].\n  case: H => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\n  repeat (split; first by []).\n  by exists h1, h2.\n- apply multi_add_s_u_triple_gen => //.\n  lia.\n  by case: nk_0_max.\n  by rewrite size_Z2ints.\n  by rewrite -A_A0.\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_add_s_u_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18344462060986297}}
{"text": "Require compcert.backend.Cminor.\nRequire SmallstepX.\nRequire EventsX.\n\nImport AST.\nImport Values.\nImport Memory.\nImport Globalenvs.\nImport EventsX.\nImport SmallstepX.\nExport Cminor.\n\nSection WITHCONFIG.\nContext `{external_calls_prf: ExternalCalls}.\n\n(** Execution of Cminor functions with C-style arguments (long long 64-bit integers allowed) *)\n\nInductive initial_state (p: Cminor.program) (i: ident) (m: mem) (sg: signature) (args: list val): 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    (** We need to keep the signature because it is required for lower-level languages *)\n    (Hsig: sg = funsig f)\n  :\n      initial_state p i m sg args (Callstate f args Kstop m)\n.\n\nInductive final_state (sg: signature): state -> (val * mem) -> Prop :=\n| final_state_intro\n    v\n    m :\n    final_state sg (Returnstate v Kstop m) (v, m)\n.\n\n(** We define the per-module semantics of RTL as adaptable to both C-style and Asm-style;\n    by default it is C-style. *)\n\nDefinition semantics\n           (p: Cminor.program) (i: ident) (m: mem)\n           (sg: signature) (args: list val) :=\n  Semantics Cminor.step (initial_state p i m sg args) (final_state 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/CminorX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.18344461356580813}}
{"text": "Require compcert.cfrontend.Cminorgenproof.\nRequire SelectLongproofX.\nRequire CminorX.\nRequire CsharpminorX.\nRequire SmallstepX.\nRequire EventsX.\n\nImport Coqlib.\nImport Errors.\nImport Values.\nImport Globalenvs.\nImport EventsX.\nImport SmallstepX.\nImport Cminorgen.\nExport Cminorgenproof.\n\nSection WITHCONFIG.\nContext `{compiler_config: CompilerConfiguration}.\n\nVariable prog: Csharpminor.program.\nVariable tprog: Cminor.program.\nHypothesis TRANSL: transl_program prog = OK tprog.\nLet ge : Csharpminor.genv := Genv.globalenv prog.\nLet tge: Cminor.genv := Genv.globalenv tprog.\n\nVariable init_m: mem.\nHypothesis init_m_inject_neutral: Mem.inject_neutral (Mem.nextblock init_m) init_m.\nHypothesis genv_next_init_m: Ple (Genv.genv_next ge) (Mem.nextblock init_m).\n\nVariable args: list val.\nHypothesis args_inj: val_list_inject (Mem.flat_inj (Mem.nextblock init_m)) args args.\n\nLemma transl_initial_states:\n  forall i sg,\n  forall S, CsharpminorX.initial_state prog i init_m sg args S ->\n  exists R, CminorX.initial_state tprog i init_m sg args R /\\ match_states prog init_m S R.\nProof.\n  intros.\n  inv H.\n  exploit function_ptr_translated; eauto.\n  destruct 1 as [? [? ?]].\n  esplit.\n  split.\n  econstructor; eauto.\n  erewrite symbols_preserved; eauto.\n  symmetry. eapply sig_preserved; eauto.\n  econstructor; eauto.\n  eapply Mem.neutral_inject; eauto.\n  econstructor.\n  econstructor.\n  apply Ple_refl.\n  intros. unfold Mem.flat_inj. destruct (plt b0 (Mem.nextblock init_m)); try contradiction. reflexivity.\n  unfold Mem.flat_inj. intros. destruct (plt b1 (Mem.nextblock init_m)); congruence.\n  intros. exploit Genv.genv_symb_range; eauto. unfold ge in *; xomega.\n  intros. exploit Genv.genv_funs_range; eauto. unfold ge in *; xomega.\n  intros. exploit Genv.genv_vars_range; eauto. unfold ge in *; xomega.\n  apply Ple_refl.\n  apply Ple_refl.\n  econstructor.\n  constructor.\n  Grab Existential Variables. constructor.\nQed.\n\nLemma transl_final_states:\n  forall sg,\n  forall S R r,\n  match_states prog init_m S R -> CsharpminorX.final_state sg S r -> final_state_with_inject (CminorX.final_state sg) init_m R r.\nProof.\n  inversion 2; subst. inv H. inv MK. inv MCS.\n  econstructor.\n  econstructor.\n  eapply match_globalenvs_inject_incr; eassumption.\n  eapply match_globalenvs_inject_separated; eassumption.\n  assumption.\n  assumption.\nQed. \n\nTheorem transl_program_correct:\n  forall i sg,\n  forward_simulation\n    (semantics_as_c (CsharpminorX.csemantics prog i init_m) sg args)\n    (semantics_with_inject (semantics_as_c (CminorX.csemantics tprog i init_m) sg args) init_m).\nProof.\n  intros.\n  eapply forward_simulation_star; eauto.\n  apply symbols_preserved; auto.\n  apply transl_initial_states.\n  apply transl_final_states.\n  instantiate (1 := measure).\n  intros. exploit transl_step_correct; eauto.\nQed.\n\n(** We also need to prove that I64 helpers present in Clight are correctly translated to Csharpminor. *)\n\nTheorem genv_contains_helpers_correct:\n  forall h,\n    SelectLongproofX.genv_contains_helpers h ge ->\n    SelectLongproofX.genv_contains_helpers h tge.\nProof.\n  intro.\n  apply SelectLongproofX.genv_contains_helpers_preserved.\n  eapply symbols_preserved; eauto.\n  intros. exploit function_ptr_translated; eauto. destruct 1 as [? [? INJ]].\n  simpl in INJ. inv INJ. eauto.\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/cfrontend/CminorgenproofX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.18332316188948863}}
{"text": "Require Import RelationClasses.\nRequire Import List.\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 PromiseConsistent.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import JoinedView.\n\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\nRequire SimMemory.\n\nRequire Import PFStep.\nRequire Import LocalPFThread.\nRequire Import TimeTraced.\nRequire Import PFConsistentStrong.\nRequire Import Mapping.\nRequire Import GoodFuture.\nRequire Import CapMap.\nRequire Import CapFlex.\nRequire Import Pred.\n\nSet Implicit Arguments.\n\n\n\nLemma reserving_trace_sim_trace_none L tr\n      (TRACE: sim_trace L tr None)\n  :\n    reserving_trace tr.\nProof.\n  ginduction tr.\n  { i. ss. }\n  { i. inv TRACE. econs; eauto. eapply IHtr; eauto. }\nQed.\n\nLemma reserving_trace_sim_trace_reserving L tr lc e\n      (TRACE: sim_trace L tr (Some (lc, e)))\n      (RESERVING: ThreadEvent.is_reservation_event e)\n  :\n    reserving_trace tr.\nProof.\n  remember (Some (lc, e)). ginduction TRACE; eauto; i; clarify.\n  { econs; eauto.\n    { ss. unfold ThreadEvent.is_reservation_event in RESERVING. des_ifs.\n      inv EVENT. des. rewrite RESERVE0; ss. }\n    { eapply reserving_trace_sim_trace_none; eauto. }\n  }\n  { eapply reserving_trace_sim_trace_none; eauto. }\n  { econs; eauto. eapply IHTRACE; eauto. }\nQed.\n\nLemma reserving_trace_sim_traces_reserving L tr_src tr_tgt\n      (TRACE: sim_traces L tr_src tr_tgt)\n      (RESERVING: reserving_trace tr_tgt)\n  :\n    reserving_trace tr_src.\nProof.\n  ginduction TRACE; eauto.\n  { i. inv RESERVING. eapply Forall_app.\n    { eapply reserving_trace_sim_trace_reserving; eauto. }\n    { eapply IHTRACE; eauto. }\n  }\n  { i. eapply Forall_app.\n    { eapply reserving_trace_sim_trace_none; eauto. }\n    { eapply IHTRACE; eauto. }\n  }\nQed.\n\nLemma sim_trace_relaxed_writing_event L tr lc ploc pts val we_tgt\n      (WRITING : relaxed_writing_event ploc pts val we_tgt)\n      (TRACE : sim_trace L tr (Some (lc, we_tgt)))\n  :\n    exists we_src : ThreadEvent.t,\n      (<<FINAL: final_event_trace we_src tr>>) /\\\n      (<<WRITING: PFRace.writing_event ploc pts we_src>>).\nProof.\n  remember (Some (lc, we_tgt)). ginduction TRACE; eauto; i; clarify.\n  { inv WRITING; inv EVENT.\n    { esplits; eauto.\n      { econs; eauto. eapply reserving_trace_sim_trace_none; eauto. }\n      { econs; eauto. }\n    }\n    { esplits; eauto.\n      { econs; eauto. eapply reserving_trace_sim_trace_none; eauto. }\n      { econs; eauto. }\n    }\n  }\n  { inv WRITING; ss. }\n  { exploit IHTRACE; eauto. i. des. esplits; eauto. econs; eauto. }\nQed.\n\nLemma final_event_trace_post_reserve e tr0 tr1\n      (FINAL: final_event_trace e tr0)\n      (RESERVING: reserving_trace tr1)\n  :\n    final_event_trace e (tr0 ++ tr1).\nProof.\n  ginduction FINAL; eauto.\n  { i. ss. erewrite List.app_comm_cons. ss. econs; eauto.\n    eapply Forall_app; eauto.\n  }\n  { i. eapply IHFINAL in RESERVING. ss. econs; eauto. }\nQed.\n\nLemma sim_traces_relaxed_writing_event L tr_src tr_tgt ploc pts val we_tgt\n      (WRITING : relaxed_writing_event ploc pts val we_tgt)\n      (TRACE : sim_traces L tr_src tr_tgt)\n      (FINAL: final_event_trace we_tgt tr_tgt)\n  :\n    exists we_src : ThreadEvent.t,\n      (<<FINAL: final_event_trace we_src tr_src>>) /\\\n      (<<WRITING: PFRace.writing_event ploc pts we_src>>).\nProof.\n  ginduction TRACE; eauto.\n  { i. inv FINAL. }\n  { i. inv FINAL.\n    { exploit sim_trace_relaxed_writing_event; eauto. i. des. esplits; eauto.\n      eapply final_event_trace_post_reserve; eauto.\n      eapply reserving_trace_sim_traces_reserving; eauto. }\n    { exploit IHTRACE; eauto. i. des. esplits; eauto.\n      eapply final_event_trace_post; eauto. }\n  }\n  { i. exploit IHTRACE; eauto. i. des. esplits; eauto.\n    eapply final_event_trace_post; eauto.\n  }\nQed.\n\nInductive all_promises\n          (tids: Ident.t -> Prop)\n          (proms: Ident.t -> Loc.t -> Time.t -> Prop): Loc.t -> Time.t -> Prop :=\n| all_promises_intro\n    tid loc ts\n    (TID: tids tid)\n    (PROMS: proms tid loc ts)\n  :\n    all_promises tids proms loc ts\n.\nHint Constructors all_promises.\n\nInductive all_extra\n          (tids: Ident.t -> Prop)\n          (extra: Ident.t -> Loc.t -> Time.t -> Time.t -> Prop)\n  : Loc.t -> Time.t -> Time.t -> Prop :=\n| all_extra_intro\n    tid loc ts from\n    (TID: tids tid)\n    (EXTRA: extra tid loc ts from)\n  :\n    all_extra tids extra loc ts from\n.\nHint Constructors all_extra.\n\nLemma jsim_event_sim_event\n  :\n    JSim.sim_event <2= sim_event.\nProof. ii. inv PR; econs. inv MSG; ss. Qed.\n\nLemma promise_writing_event_racy\n      loc from ts val released e\n      (WRITING : promise_writing_event loc from ts val released e)\n  :\n    PFRace.writing_event loc ts e.\nProof.\n  inv WRITING; econs; eauto.\nQed.\n\nLemma jsim_memory_concrete_promised mem_src mem_tgt\n      (MEM: SimMemory.sim_memory mem_src mem_tgt)\n  :\n    concrete_promised mem_tgt <2= concrete_promised mem_src.\nProof.\n  ii. inv PR. eapply MEM in GET.  des. inv MSG. econs; eauto.\nQed.\n\nLemma sim_memory_concrete_promised_later mem_src mem_tgt loc ts\n      (MEM: SimMemory.sim_memory mem_src mem_tgt)\n      (CLOSED: Memory.closed mem_tgt)\n      (PROMISED: concrete_promised mem_src loc ts)\n  :\n    exists ts_tgt,\n      (<<PROMISED: concrete_promised mem_tgt loc ts_tgt>>) /\\\n      (<<TS: Time.le ts ts_tgt>>).\nProof.\n  inv PROMISED. dup GET. apply memory_get_ts_strong in GET. des; subst.\n  { exists Time.bot. splits.\n    { econs. eapply CLOSED. }\n    { refl. }\n  }\n  inv MEM. exploit (proj1 (COVER loc ts)).\n  { econs; eauto. econs; ss. refl. }\n  i. inv x0. destruct msg.\n  { inv ITV. ss. exists to. splits; auto. econs; eauto. }\n  { eapply RESERVE in GET. exploit Memory.get_disjoint.\n    { eapply GET. }\n    { eapply GET0. }\n    i. des; clarify. exfalso. eapply x0; eauto. econs; ss. refl.\n  }\nQed.\n\nLemma jsim_joined_promises_covered prom_src prom_tgt view\n      (SIM: JSim.sim_joined_promises view prom_src prom_tgt)\n  :\n    forall loc ts, covered loc ts prom_src <-> covered loc ts prom_tgt.\nProof.\n  split; i.\n  { inv H. specialize (SIM loc to). rewrite GET in *. inv SIM; ss.\n    { econs; eauto. }\n    { econs; eauto. }\n  }\n  { inv H. specialize (SIM loc to). rewrite GET in *. inv SIM; ss.\n    { econs; eauto. }\n    { econs; eauto. }\n  }\nQed.\n\nLemma cap_flex_sim_memory mem_src mem_tgt cap_src cap_tgt tm\n      (TMSRC: forall loc : Loc.t, Time.lt (Memory.max_ts loc mem_src) (tm loc))\n      (MEM: SimMemory.sim_memory mem_src mem_tgt)\n      (CAPSRC: cap_flex mem_src cap_src tm)\n      (CAPTGT: cap_flex mem_tgt cap_tgt tm)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n  :\n    SimMemory.sim_memory cap_src cap_tgt.\nProof.\n  assert (TMTGT: forall loc : Loc.t, Time.lt (Memory.max_ts loc mem_tgt) (tm loc)).\n  { i. erewrite <- SimMemory.sim_memory_max_ts; eauto. }\n  dup MEM. inv MEM.\n  econs.\n  { i. erewrite <- (@cap_flex_covered mem_src cap_src); eauto.\n    erewrite <- (@cap_flex_covered mem_tgt cap_tgt); eauto. }\n  { i. eapply cap_flex_inv in GET; eauto. des; subst.\n    { exploit MSG; eauto. i. des.\n      eapply CAPSRC in GET0. esplits; eauto. }\n    { exploit SimMemory.sim_memory_adjacent_tgt; eauto. i. des.\n      eapply CAPSRC in x0; eauto. }\n    { esplits; eauto.\n      erewrite (cap_flex_back CAPSRC); eauto. }\n  }\n  { i. split; intros GET.\n    { eapply (@cap_flex_inv mem_src cap_src) in GET; eauto. des; subst.\n      { erewrite RESERVE in GET; eauto.\n        eapply (cap_flex_le CAPTGT); eauto. }\n      { exploit SimMemory.sim_memory_adjacent_src; eauto. i. des.\n        eapply CAPTGT in x0; eauto. }\n      { erewrite SimMemory.sim_memory_max_ts; eauto.\n        eapply (cap_flex_back CAPTGT). }\n    }\n    { eapply (@cap_flex_inv mem_tgt cap_tgt) in GET; eauto. des; subst.\n      { erewrite <- RESERVE in GET; eauto.\n        eapply (cap_flex_le CAPSRC); eauto. }\n      { exploit SimMemory.sim_memory_adjacent_tgt; eauto. i. des.\n        eapply CAPSRC in x0; eauto. }\n      { erewrite <- SimMemory.sim_memory_max_ts; eauto.\n        eapply (cap_flex_back CAPSRC). }\n    }\n  }\nQed.\n\nLemma joined_memory_cap_flex views mem cap tm\n      (JOINED: joined_memory views mem)\n      (TM: forall loc, Time.lt (Memory.max_ts loc mem) (tm loc))\n      (CAP: cap_flex mem cap tm)\n      (CLOSED: Memory.closed mem)\n  :\n    joined_memory views cap.\nProof.\n  inv JOINED. econs.\n  - i. eapply cap_flex_inv in GET; eauto. des; eauto; clarify.\n  - i. exploit ONLY; eauto. i. des.\n    eapply CAP in GET; eauto.\n  - i. eapply List.Forall_impl; try apply CLOSED0; eauto.\n    i. ss. eapply Memory.future_weak_closed_view; eauto.\n    eapply cap_flex_future_weak; eauto.\nQed.\n\nLemma sim_memory_concrete_promise_max_timemap mem_src mem_tgt\n      views prom_src prom_tgt max\n      (MAX: concrete_promise_max_timemap mem_src prom_src max)\n      (MEM: SimMemory.sim_memory mem_src mem_tgt)\n      (PROM: JSim.sim_joined_promises views prom_src prom_tgt)\n      (PROMSRC: Memory.le prom_src mem_src)\n      (PROMTGT: Memory.le prom_tgt mem_tgt)\n      (MEMSRC: Memory.closed mem_src)\n      (MEMTGT: Memory.closed mem_tgt)\n  :\n    concrete_promise_max_timemap mem_tgt prom_tgt max.\nProof.\n  ii. specialize (MAX loc). inv MAX. guardH EXISTS. econs.\n  { unguard. des.\n    { left. exploit sim_memory_concrete_promised_later; eauto.\n      { econs; eauto. }\n      i. des. inv PROMISED. inv TS.\n      { exfalso. eapply MEM in GET0. des. inv MSG.\n        eapply CONCRETE in GET1. timetac. }\n      { inv H. esplits; eauto.  }\n    }\n    { specialize (PROM loc (max loc)). rewrite GET in *. inv PROM; eauto. }\n  }\n  { i. eapply MEM in GET. des; eauto. inv MSG. eauto. }\n  { i. specialize (PROM loc to). rewrite GET in *. inv PROM; eauto. }\nQed.\n\nLemma jsim_event_write_not_in e_src e_tgt (P_src P_tgt: Loc.t -> Time.t -> Prop)\n      (WRITE: write_not_in P_tgt e_tgt)\n      (EVENT: JSim.sim_event e_src e_tgt)\n      (IMPL: forall loc ts (SAT: P_src loc ts), P_tgt loc ts)\n  :\n    write_not_in P_src e_src.\nProof.\n  inv EVENT; ss.\n  { des_ifs.\n    { inv KIND; ss. }\n    ii. eapply WRITE; eauto.\n  }\n  { ii. eapply WRITE; eauto. }\n  { ii. eapply WRITE; eauto. }\nQed.\n\nLemma tevent_ident_map f e fe\n      (MAP: tevent_map f fe e)\n      (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n  :\n    sim_event e fe.\nProof.\n  inv MAP; try econs; eauto.\n  { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. inv MSG; ss. }\n  { eapply IDENT in TO. subst. econs; eauto. }\n  { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. }\n  { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. }\nQed.\n\nLemma readable_not_exist_racy lc mem loc ts released ord\n      (READABLE: TView.readable (TView.cur (Local.tview lc)) loc ts released ord)\n      (CLOSED: TView.closed (Local.tview lc) mem)\n      (NOTEXIST: ~ concrete_promised mem loc ts)\n  :\n    Time.lt\n      (if Ordering.le Ordering.relaxed ord\n       then View.rlx (TView.cur (Local.tview lc)) loc\n       else View.pln (TView.cur (Local.tview lc)) loc) ts.\nProof.\n  inv READABLE. des_ifs.\n  { specialize (RLX eq_refl). destruct RLX; auto. inv H.\n    inv CLOSED. inv CUR. specialize (RLX loc).\n    des. exfalso. eapply NOTEXIST. econs; eauto. }\n  { destruct PLN; auto. inv H.\n    inv CLOSED. inv CUR. specialize (PLN loc).\n    des. exfalso. eapply NOTEXIST. econs; eauto. }\nQed.\n\nLemma racy_read_mon loc ts lc0 lc1 e0 e1\n      (RACY: PFRace.racy_read loc ts lc1 e1)\n      (LOCAL: TView.le (Local.tview lc0) (Local.tview lc1))\n      (EVENT: sim_event e0 e1)\n  :\n    PFRace.racy_read loc ts lc0 e0.\nProof.\n  inv RACY; inv EVENT; econs; eauto.\n  { des_ifs.\n    { eapply TimeFacts.le_lt_lt; eauto. eapply LOCAL. }\n    { eapply TimeFacts.le_lt_lt; eauto. eapply LOCAL. }\n  }\n  { des_ifs.\n    { eapply TimeFacts.le_lt_lt; eauto. eapply LOCAL. }\n    { eapply TimeFacts.le_lt_lt; eauto. eapply LOCAL. }\n  }\nQed.\n\n\nSection SIM.\n\n  Variable L: Loc.t -> bool.\n  Variable times: Loc.t -> Time.t -> Prop.\n  Hypothesis WO: forall loc, well_ordered (times loc).\n  Hypothesis INCR: forall nat loc, times loc (incr_time_seq nat).\n\n  Lemma later_timemap_exists (tm: TimeMap.t)\n    :\n      exists max,\n        (<<LT: forall loc, Time.lt (tm loc) (max loc)>>) /\\\n        (<<IN: forall loc, times loc (max loc)>>).\n  Proof.\n    hexploit (@choice\n                Loc.t Time.t\n                (fun loc ts =>\n                   (<<LT: Time.lt (tm loc) ts>>) /\\\n                   (<<IN: times loc ts>>))).\n    { i. hexploit (incr_time_seq_diverge (tm x)). i. des. esplits; eauto. }\n    intros [max SPEC]. des. exists max. splits; auto.\n    { eapply SPEC; eauto. }\n    { eapply SPEC; eauto. }\n  Qed.\n\n  Record pi_consistent\n         (self: Loc.t -> Time.t -> Prop)\n         (pl: list (Loc.t * Time.t))\n         (mem_src: Memory.t)\n         lang (e0:Thread.t lang)\n    : Prop :=\n    {\n      pi_consistent_promises:\n        forall loc ts (PROM: self loc ts),\n          List.In (loc, ts) pl;\n      pi_consistent_certify:\n        forall mem1 tm sc\n               (pl0 pl1: list (Loc.t * Time.t))\n               (ploc: Loc.t) (pts: Time.t)\n               (FUTURE: Memory.future_weak (Thread.memory e0) mem1)\n               (CLOSED: Memory.closed mem1)\n               (MWF: memory_times_wf times mem1)\n               (LOCAL: Local.wf (Thread.local e0) mem1)\n               (PLIST: pl = pl0 ++ (ploc, pts) :: pl1)\n        ,\n        exists ftr e1,\n          (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e1>>) /\\\n          (<<EVENTS: List.Forall (fun em => <<SAT: (no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised mem_src loc ts \\/ Time.lt (tm loc) ts))\n                                                                 /1\\ wf_time_evt times\n                                                   ) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n\n          (<<PROMCONSISTENT: Local.promise_consistent (Thread.local e1)>>) /\\\n          (<<GOOD: good_future tm mem1 (Thread.memory e1)>>) /\\\n          (<<SC: (Thread.sc e1) = sc>>) /\\\n\n          __guard__((exists val we ftr_cert,\n                        (<<CONSISTENT: pf_consistent_super_strong e1 ftr_cert times>>) /\\\n                        (<<EVENTSCERT: List.Forall (fun em => <<SAT: (no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised mem_src loc ts \\/ Time.lt (tm loc) ts))) (snd em)>>) ftr_cert>>) /\\\n                        (<<FINAL: final_event_trace we ftr>>) /\\\n                        (<<WRITING: relaxed_writing_event ploc pts 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 ++ [(ploc, pts)])),\n                            Memory.get loc0 to0 (Local.promises (Thread.local e1)) = None>>)) \\/\n                    (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  Definition past_consistent\n             (mem_src: Memory.t)\n             lang (e0:Thread.t lang)\n    : Prop :=\n    forall mem1 tm sc\n           (FUTURE: Memory.future_weak (Thread.memory e0) mem1)\n           (CLOSED: Memory.closed mem1)\n           (MWF: memory_times_wf times mem1)\n           (LOCAL: Local.wf (Thread.local e0) mem1)\n    ,\n    exists ftr e1,\n      (<<STEPS: Trace.steps ftr (Thread.mk _ (Thread.state e0) (Thread.local e0) sc mem1) e1>>) /\\\n      (<<EVENTS: List.Forall (fun em => <<SAT: (no_read_msgs (fun loc ts => ~ (covered loc ts (Local.promises (Thread.local e0)) \\/ concrete_promised mem_src loc ts \\/ Time.lt (tm loc) ts))\n                                                             /1\\ wf_time_evt times\n                                               ) (snd em)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd em) = MachineEvent.silent>>) ftr >>) /\\\n      (<<FINAL:__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  Lemma pi_consistent_mon self0 self1 pl mem_src0 mem_src1 lang\n        st lc sc0 mem0 sc1 mem1\n        (CONSISTENT: pi_consistent self0 pl mem_src0 (Thread.mk lang st lc sc0 mem0))\n        (SELFLE: self1 <2= self0)\n        (FUTURETGT: Memory.future_weak mem0 mem1)\n        (FUTURESRC: Memory.future_weak mem_src0 mem_src1)\n    :\n      pi_consistent self1 pl mem_src1 (Thread.mk lang st lc sc1 mem1).\n  Proof.\n    inv CONSISTENT. ss. econs; eauto.\n    { ii. ss. exploit pi_consistent_certify0.\n      { transitivity mem1; eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      { eauto. }\n      i. unguard. des.\n      { ss. esplits; eauto.\n        { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n          eapply no_read_msgs_mon; eauto. ii. des; eauto.\n          eapply memory_future_concrete_promised in H; eauto. }\n        { left. unguard. esplits; eauto.\n          eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n          eapply no_read_msgs_mon; eauto. ii. des; eauto.\n          eapply memory_future_concrete_promised in H0; eauto. }\n      }\n      { ss. esplits; eauto.\n        { eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n          eapply no_read_msgs_mon; eauto. ii. des; eauto.\n          eapply memory_future_concrete_promised in H; eauto. }\n      }\n    }\n  Qed.\n\n  Lemma past_consistent_mon mem_src0 mem_src1 lang\n        st lc sc0 mem0 sc1 mem1\n        (CONSISTENT: past_consistent mem_src0 (Thread.mk lang st lc sc0 mem0))\n        (FUTURETGT: Memory.future_weak mem0 mem1)\n        (FUTURESRC: Memory.future_weak mem_src0 mem_src1)\n    :\n      past_consistent mem_src1 (Thread.mk lang st lc sc1 mem1).\n  Proof.\n    ii. exploit (CONSISTENT mem2 tm sc); eauto.\n    { etrans; eauto. }\n    i. des. esplits; eauto.\n    eapply List.Forall_impl; eauto. i. ss. des. splits; auto.\n    eapply no_read_msgs_mon; eauto. ii. des; eauto.\n    eapply memory_future_concrete_promised in H; eauto.\n  Qed.\n\n  Inductive sim_configuration\n            (tids: Ident.t -> Prop)\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom: Ident.t -> Loc.t -> Time.t -> Prop)\n            (extra: Ident.t -> Loc.t -> Time.t -> Time.t -> Prop)\n            (proml: Ident.t -> list (Loc.t * Time.t))\n    :\n      forall (c_src c_mid c_tgt: Configuration.t), Prop :=\n  | sim_configuration_intro\n      ths_src sc_src mem_src\n      ths_mid mem_mid\n      ths_tgt sc_tgt mem_tgt\n      (THSPF: forall tid,\n          option_rel\n            (sim_statelocal L times (prom tid) (extra tid))\n            (IdentMap.find tid ths_src)\n            (IdentMap.find tid ths_mid))\n      (THSJOIN: forall tid,\n          option_rel\n            (JSim.sim_statelocal views)\n            (IdentMap.find tid ths_mid)\n            (IdentMap.find tid ths_tgt))\n      (BOT: forall tid (NONE: IdentMap.find tid ths_src = None),\n          (<<PROM: forall loc ts, ~ prom tid loc ts>>) /\\\n          (<<EXTRA: forall loc ts from, ~ extra tid loc ts from>>) /\\\n          (<<PLS: proml tid = []>>))\n      (MEMPF: sim_memory L times (all_promises (fun _ => True) prom) (all_extra (fun _ => True) extra) mem_src mem_mid)\n      (SCPF: TimeMap.le sc_src sc_tgt)\n\n      (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (MEMWF: memory_times_wf times mem_mid)\n      (MEMWFTGT: memory_times_wf times mem_tgt)\n      (CONSISTENT: forall tid lang st lc\n                          (IN: tids tid)\n                          (GET: IdentMap.find tid ths_tgt = Some (existT _ lang st, lc)),\n          pi_consistent (prom tid) (proml tid) mem_src (Thread.mk lang st lc sc_tgt mem_tgt))\n      (PAST: forall tid lang st lc\n                    (GET: IdentMap.find tid ths_tgt = Some (existT _ lang st, lc)),\n          (<<CONSISTENT: past_consistent mem_src (Thread.mk lang st lc sc_tgt mem_tgt)>>) \\/\n          ((<<PROM: forall loc ts, ~ prom tid loc ts>>) /\\\n           (<<EXTRA: forall loc ts from, ~ extra tid loc ts from>>) /\\\n           (<<EQ: IdentMap.find tid ths_src = IdentMap.find tid ths_mid>>)))\n    :\n      sim_configuration\n        tids views prom extra proml\n        (Configuration.mk ths_src sc_src mem_src)\n        (Configuration.mk ths_mid sc_src mem_mid)\n        (Configuration.mk ths_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_configuration.\n\n  Inductive sim_thread\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom_self prom_others: Loc.t -> Time.t -> Prop)\n            (extra_self extra_others: Loc.t -> Time.t -> Time.t -> Prop):\n    forall lang (th_src th_mid th_tgt: Thread.t lang), Prop :=\n  | sim_thread_intro\n      lang st lc_src lc_mid lc_tgt\n      mem_src mem_mid mem_tgt sc_src sc_tgt\n      (LOCALPF: sim_local L times prom_self extra_self lc_src lc_mid)\n      (LOCALJOIN: JSim.sim_local views lc_mid lc_tgt)\n      (MEMPF: sim_memory L times (prom_others \\\\2// prom_self) (extra_others \\\\3// extra_self) mem_src mem_mid)\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n    :\n      sim_thread\n        views prom_self prom_others extra_self extra_others\n        (Thread.mk lang st lc_src sc_src mem_src)\n        (Thread.mk lang st lc_mid sc_src mem_mid)\n        (Thread.mk lang st lc_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_thread.\n\n  Inductive sim_thread_strong\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom_self prom_others: Loc.t -> Time.t -> Prop)\n            (extra_self extra_others: Loc.t -> Time.t -> Time.t -> Prop):\n    forall lang (th_src th_mid th_tgt: Thread.t lang), Prop :=\n  | sim_thread_strong_intro\n      lang st lc_src lc_mid lc_tgt\n      mem_src mem_mid mem_tgt sc_src sc_tgt\n      (LOCALPF: sim_local_strong L times prom_self extra_self (extra_others \\\\3// extra_self) lc_src lc_mid)\n      (LOCALJOIN: JSim.sim_local views lc_mid lc_tgt)\n      (MEMPF: sim_memory L times (prom_others \\\\2// prom_self) (extra_others \\\\3// extra_self) mem_src mem_mid)\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n    :\n      sim_thread_strong\n        views prom_self prom_others extra_self extra_others\n        (Thread.mk lang st lc_src sc_src mem_src)\n        (Thread.mk lang st lc_mid sc_src mem_mid)\n        (Thread.mk lang st lc_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_thread_strong.\n\n  Lemma sim_thread_strong_sim_thread\n    :\n      sim_thread_strong <9= sim_thread.\n  Proof.\n    ii. dep_inv PR. econs; eauto.\n    eapply sim_local_strong_sim_local; eauto.\n  Qed.\n\n  Lemma sim_thread_jsim_thread\n        views prom_self prom_others extra_self extra_others\n        lang th_src th_mid th_tgt\n        (THREAD: @sim_thread\n                   views prom_self prom_others extra_self extra_others\n                   lang th_src th_mid th_tgt)\n    :\n      JSim.sim_thread views th_mid th_tgt.\n  Proof.\n    dep_inv THREAD.\n  Qed.\n\n  Lemma sim_thread_step_silent\n        views0 prom_self0 prom_others extra_self0 extra_others\n        lang th_src0 th_mid0 th_tgt0 th_tgt1 pf_tgt e_tgt\n        (STEPTGT: Thread.step pf_tgt e_tgt th_tgt0 th_tgt1)\n        (THREAD: @sim_thread\n                   views0 prom_self0 prom_others extra_self0 extra_others\n                   lang th_src0 th_mid0 th_tgt0)\n        (WFTIME: wf_time_evt times e_tgt)\n        (NOREAD: no_read_msgs prom_others e_tgt)\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src0) (Thread.memory th_src0))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid0) (Thread.memory th_mid0))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt0) (Thread.memory th_tgt0))\n        (MEMSRC: Memory.closed (Thread.memory th_src0))\n        (MEMMID: Memory.closed (Thread.memory th_mid0))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt0))\n        (LOCALSRC: Local.wf (Thread.local th_src0) (Thread.memory th_src0))\n        (LOCALMID: Local.wf (Thread.local th_mid0) (Thread.memory th_mid0))\n        (LOCALTGT: Local.wf (Thread.local th_tgt0) (Thread.memory th_tgt0))\n\n        (MEMWF: memory_times_wf times (Thread.memory th_mid0))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt0))\n        (CONSISTENT: Local.promise_consistent (Thread.local th_tgt1))\n\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src0) loc ts) (views0 loc ts))\n\n        (REL: joined_released\n                views0 (Local.promises (Thread.local th_mid0)) (Local.tview (Thread.local th_mid0)).(TView.rel))\n        (JOINEDMEM: joined_memory views0 (Thread.memory th_mid0))\n        (VIEWS: wf_views views0)\n    :\n      exists th_mid1 th_src1 views1 prom_self1 extra_self1 pf_mid e_mid tr,\n        (<<STEPMID: JThread.step pf_mid e_mid th_mid0 th_mid1 views0 views1>>) /\\\n        (<<STEPSRC: Trace.steps tr th_src0 th_src1>>) /\\\n        (<<THREAD: sim_thread_strong\n                     views1 prom_self1 prom_others extra_self1 extra_others\n                     th_src1 th_mid1 th_tgt1>>) /\\\n        (<<EVENTJOIN: JSim.sim_event e_mid e_tgt>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src1) loc ts) (views1 loc ts)>>) /\\\n        (<<TRACE: sim_trace L tr (Some ((Thread.local th_tgt0), e_tgt))>>) /\\\n        (<<MEMWF: memory_times_wf times (Thread.memory th_mid1)>>) /\\\n        (<<MEMWFTGT: memory_times_wf times (Thread.memory th_tgt1)>>)\n  .\n  Proof.\n    hexploit sim_thread_jsim_thread; eauto. intros JTHREAD.\n    exploit JSim.sim_thread_step; eauto. i. des.\n    dep_inv THREAD. destruct th1_src. ss.\n    hexploit sim_thread_step_silent; try apply STEP; eauto.\n    { inv EVENT0; ss. }\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. inv EVENT0; ss. }\n    { dep_inv SIM. eapply JSim.sim_local_promise_consistent; eauto. }\n    { inv EVENT0; ss. }\n    i. des. dep_inv SIM. esplits; eauto.\n    { eapply sim_trace_sim_event_sim_trace; eauto.\n      { dep_inv JTHREAD. inv LOCAL0. ss. }\n      { eapply jsim_event_sim_event; eauto. }\n    }\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. inv EVENT0; ss. }\n    { hexploit step_memory_times_wf; try apply STEPTGT; eauto. }\n  Qed.\n\n  Lemma sim_thread_step_event\n        views0 prom_self0 prom_others extra_self0 extra_others\n        lang th_src0 th_mid0 th_tgt0 th_tgt1 pf_tgt e_tgt\n        (STEPTGT: Thread.step pf_tgt e_tgt th_tgt0 th_tgt1)\n        (THREAD: @sim_thread_strong\n                   views0 prom_self0 prom_others extra_self0 extra_others\n                   lang th_src0 th_mid0 th_tgt0)\n        (WFTIME: wf_time_evt times e_tgt)\n        (NOREAD: no_read_msgs prom_others e_tgt)\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent)\n\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src0) (Thread.memory th_src0))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid0) (Thread.memory th_mid0))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt0) (Thread.memory th_tgt0))\n        (MEMSRC: Memory.closed (Thread.memory th_src0))\n        (MEMMID: Memory.closed (Thread.memory th_mid0))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt0))\n        (LOCALSRC: Local.wf (Thread.local th_src0) (Thread.memory th_src0))\n        (LOCALMID: Local.wf (Thread.local th_mid0) (Thread.memory th_mid0))\n        (LOCALTGT: Local.wf (Thread.local th_tgt0) (Thread.memory th_tgt0))\n\n        (MEMWF: memory_times_wf times (Thread.memory th_mid0))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt0))\n        (CONSISTENT: Local.promise_consistent (Thread.local th_tgt1))\n\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src0) loc ts) (views0 loc ts))\n\n        (REL: joined_released\n                views0 (Local.promises (Thread.local th_mid0)) (Local.tview (Thread.local th_mid0)).(TView.rel))\n        (JOINEDMEM: joined_memory views0 (Thread.memory th_mid0))\n        (VIEWS: wf_views views0)\n    :\n      exists th_mid1 th_src1 views1 prom_self1 extra_self1 pf_mid pf_src,\n        (<<STEPMID: JThread.step pf_mid e_tgt th_mid0 th_mid1 views0 views1>>) /\\\n        (<<STEPSRC: Thread.step pf_src e_tgt th_src0 th_src1>>) /\\\n        (<<THREAD: sim_thread_strong\n                     views1 prom_self1 prom_others extra_self1 extra_others\n                     th_src1 th_mid1 th_tgt1>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src1) loc ts) (views1 loc ts)>>) /\\\n        (<<MEMWF: memory_times_wf times (Thread.memory th_mid1)>>) /\\\n        (<<MEMWFTGT: memory_times_wf times (Thread.memory th_tgt1)>>)\n  .\n  Proof.\n    hexploit sim_thread_jsim_thread; eauto.\n    { eapply sim_thread_strong_sim_thread; eauto. }\n    intros JTHREAD.\n    exploit JSim.sim_thread_step; eauto. i. des.\n    dep_inv THREAD. destruct th1_src. ss.\n    hexploit sim_thread_step_event_strong; try apply STEP; eauto.\n    { inv EVENT0; ss. }\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. inv EVENT0; ss. }\n    { dep_inv SIM. eapply JSim.sim_local_promise_consistent; eauto. }\n    { inv EVENT0; ss. }\n    assert (e_src = e_tgt).\n    { inv EVENT0; ss. } subst.\n    i. des. dep_inv SIM. esplits; eauto.\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. }\n    { hexploit step_memory_times_wf; try apply STEPTGT; eauto. }\n  Qed.\n\n  Lemma sim_thread_steps_silent\n        views0 prom_self0 prom_others extra_self0 extra_others\n        lang th_src0 th_mid0 th_tgt0 th_tgt1 tr_tgt\n        (STEPTGT: Trace.steps tr_tgt th_tgt0 th_tgt1)\n        (THREAD: @sim_thread\n                   views0 prom_self0 prom_others extra_self0 extra_others\n                   lang th_src0 th_mid0 th_tgt0)\n\n        (EVENTS: List.Forall (fun the => <<SAT: (wf_time_evt times /1\\ no_read_msgs prom_others) (snd the)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd the) = MachineEvent.silent>>) tr_tgt)\n\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src0) (Thread.memory th_src0))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid0) (Thread.memory th_mid0))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt0) (Thread.memory th_tgt0))\n        (MEMSRC: Memory.closed (Thread.memory th_src0))\n        (MEMMID: Memory.closed (Thread.memory th_mid0))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt0))\n        (LOCALSRC: Local.wf (Thread.local th_src0) (Thread.memory th_src0))\n        (LOCALMID: Local.wf (Thread.local th_mid0) (Thread.memory th_mid0))\n        (LOCALTGT: Local.wf (Thread.local th_tgt0) (Thread.memory th_tgt0))\n\n        (MEMWF: memory_times_wf times (Thread.memory th_mid0))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt0))\n        (CONSISTENT: Local.promise_consistent (Thread.local th_tgt1))\n\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src0) loc ts) (views0 loc ts))\n\n        (REL: joined_released\n                views0 (Local.promises (Thread.local th_mid0)) (Local.tview (Thread.local th_mid0)).(TView.rel))\n        (JOINEDMEM: joined_memory views0 (Thread.memory th_mid0))\n        (VIEWS: wf_views views0)\n    :\n      exists th_mid1 th_src1 views1 prom_self1 extra_self1 tr_src,\n        (<<STEPMID: JThread.rtc_tau th_mid0 th_mid1 views0 views1>>) /\\\n        (<<STEPSRC: Trace.steps tr_src th_src0 th_src1>>) /\\\n        (<<THREAD: sim_thread_strong\n                     views1 prom_self1 prom_others extra_self1 extra_others\n                     th_src1 th_mid1 th_tgt1>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src1) loc ts) (views1 loc ts)>>) /\\\n        (<<TRACE: sim_traces L tr_src tr_tgt>>) /\\\n        (<<MEMWF: memory_times_wf times (Thread.memory th_mid1)>>) /\\\n        (<<MEMWFTGT: memory_times_wf times (Thread.memory th_tgt1)>>)\n  .\n  Proof.\n    ginduction STEPTGT.\n    { i. dep_inv THREAD. inv LOCALPF. exploit sim_promise_weak_strengthen; eauto.\n      { eapply LOCALMID. }\n      { eapply LOCALSRC. }\n      { eapply LOCALSRC. }\n      { eapply LOCALSRC. }\n      i. des. exploit reserve_future_memory_steps; eauto. i. des. ss. esplits; eauto.\n      { econs; eauto. econs; eauto. }\n      { i. ss. eapply List.Forall_impl; eauto.\n        ii. ss. eapply semi_closed_view_future; eauto.\n        eapply Memory.future_future_weak. eapply reserve_future_future; eauto. }\n      { replace tr with (tr ++ []); auto.\n        { econs 3.\n          { econs. }\n          { eapply reserving_r_sim_trace with (tr_src:=[]); eauto. econs. }\n        }\n        { eapply List.app_nil_r. }\n      }\n    }\n    i. subst. inv EVENTS. ss. des.\n    hexploit Thread.step_future; try apply STEP; eauto. i. des.\n    hexploit sim_thread_step_silent; eauto.\n    { eapply Trace.steps_promise_consistent; eauto. } i. des.\n    hexploit JThread.step_future; try apply STEPMID; eauto. i. des.\n    hexploit Trace.steps_future; try apply STEPSRC; eauto. i. des.\n    eapply sim_thread_strong_sim_thread in THREAD0. exploit IHSTEPTGT; eauto.\n    { i. eapply EXCLUSIVE in OTHER. des.\n      eapply unchangable_trace_steps_increase in UNCH; eauto. }\n    { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n      eapply unchangable_trace_steps_increase in OTHER; eauto. }\n    i. des. esplits; try apply THREAD1; eauto.\n    { econs; eauto. inv EVENTJOIN; ss. }\n    { eapply Trace.steps_trans; eauto. }\n    { econs 2; eauto. }\n  Qed.\n\n  Lemma sim_configuration_sim_thread tids views prom extra proml\n        (c_src c_mid c_tgt: Configuration.t)\n        tid lang st lc_tgt\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (TIDTGT: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st, lc_tgt))\n    :\n      exists lc_src lc_mid,\n        (<<TIDSRC: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<TIDMID: IdentMap.find tid (Configuration.threads c_mid) = Some (existT _ lang st, lc_mid)>>) /\\\n        (<<SIM: sim_thread\n                  views\n                  (prom tid)\n                  (all_promises (fun tid' => tid <> tid') prom)\n                  (extra tid)\n                  (all_extra (fun tid' => tid <> tid') extra)\n                  (Thread.mk _ st lc_src (Configuration.sc c_src) (Configuration.memory c_src))\n                  (Thread.mk _ st lc_mid (Configuration.sc c_mid) (Configuration.memory c_mid))\n                  (Thread.mk _ st lc_tgt (Configuration.sc c_tgt) (Configuration.memory c_tgt))>>).\n  Proof.\n    inv SIM. ss.\n    specialize (THSJOIN tid). specialize (THSPF tid).\n    setoid_rewrite TIDTGT in THSJOIN. unfold option_rel in THSJOIN. des_ifs.\n    unfold option_rel in THSPF. des_ifs.\n    destruct p as [[lang_mid st_mid] lc_mid]. destruct p0 as [[lang_src st_src] lc_src].\n    dup THSPF. dup THSJOIN.\n    dep_inv THSPF0. dep_inv THSJOIN0. esplits; eauto. econs; eauto.\n    replace (all_promises (fun tid' => tid <> tid') prom \\\\2// prom tid) with\n        (all_promises (fun _ => True) prom); cycle 1.\n    { extensionality loc. extensionality ts.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n      { inv H. destruct (Ident.eq_dec tid tid0).\n        { subst. right. auto. }\n        { left. econs; eauto. }\n      }\n      { destruct H.\n        { inv H. econs; eauto. }\n        { econs; eauto. }\n      }\n    }\n    replace (all_extra (fun tid' => tid <> tid') extra \\\\3// extra tid) with\n        (all_extra (fun _ => True) extra); cycle 1.\n    { extensionality loc. extensionality ts. extensionality from.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n      { inv H. destruct (Ident.eq_dec tid tid0).\n        { subst. right. auto. }\n        { left. econs; eauto. }\n      }\n      { destruct H.\n        { inv H. econs; eauto. }\n        { econs; eauto. }\n      }\n    }\n    auto.\n  Qed.\n\n  Lemma sim_configuration_forget_promise_exist\n        tids views prom extra proml c_src c_mid c_tgt\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        tid loc ts\n        (PROM: prom tid loc ts)\n    :\n      exists lang st lc_src from msg,\n        (<<TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<PROMISE: Memory.get loc ts (Local.promises lc_src) = Some (from, msg)>>)\n  .\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_src)) as\n        [[[lang st] lc_src]|] eqn:TID.\n    { inv SIM. specialize (THSPF tid). setoid_rewrite TID in THSPF. ss. des_ifs.\n      inv THSPF. inv LOCAL. set (CNT:=(sim_promise_contents PROMS) loc ts).\n      inv CNT; ss. esplits; eauto. }\n    { exfalso. inv SIM. eapply BOT in TID. des. eapply PROM0; eauto. }\n  Qed.\n\n  Lemma sim_configuration_extra_promise_exist\n        tids views prom extra proml c_src c_mid c_tgt\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        tid loc ts from\n        (PROM: extra tid loc ts from)\n    :\n      exists lang st lc_src,\n        (<<TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<PROMISE: Memory.get loc ts (Local.promises lc_src) = Some (from, Message.reserve)>>)\n  .\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_src)) as\n        [[[lang st] lc_src]|] eqn:TID.\n    { inv SIM. specialize (THSPF tid). setoid_rewrite TID in THSPF. ss. des_ifs.\n      inv THSPF. inv LOCAL. set (CNT:=(sim_promise_contents PROMS) loc ts).\n      inv CNT; try by (exfalso; eapply NEXTRA; eauto).\n      exploit ((sim_memory_wf MEMPF) loc from ts); eauto. i. des.\n      exploit (UNIQUE from0); eauto. i. subst. esplits; eauto. }\n    { exfalso. inv SIM. eapply BOT in TID. des. eapply EXTRA; eauto. }\n  Qed.\n\n  Lemma sim_configuration_forget_exclusive\n        tids views prom extra proml c_src c_mid c_tgt\n        tid lang st lc_src\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src))\n    :\n      forall loc ts\n             (PROM: all_promises (fun tid' => tid <> tid') prom loc ts),\n      exists (from : Time.t) (msg : Message.t),\n        (<<UNCH: unchangable (Configuration.memory c_src) (Local.promises lc_src) loc ts from msg>>).\n  Proof.\n    ii. dup WF_SRC. inv WF_SRC.\n    inv PROM. exploit sim_configuration_forget_promise_exist; eauto. i. des.\n    dup TID1. eapply WF in TID1. inv TID1. esplits. econs.\n    { eapply PROMISES. eauto. }\n    { inv WF. exploit DISJOINT; eauto. intros DISJ. inv DISJ.\n      destruct (Memory.get loc ts (Local.promises lc_src)) as [[from' msg']|] eqn:GET; auto.\n      exfalso. inv DISJOINT0. exploit DISJOINT1; eauto. i. des.\n      eapply memory_get_ts_strong in GET. des; subst; ss.\n      eapply memory_get_ts_strong in  PROMISE. des; subst; ss.\n      eapply x; eauto.\n      { econs; [|refl]. auto. }\n      { econs; ss. refl. }\n    }\n  Qed.\n\n  Lemma sim_configuration_extra_exclusive\n        tids views prom extra proml c_src c_mid c_tgt\n        tid lang st lc_src\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src))\n    :\n      forall loc ts from\n             (EXTRA: all_extra (fun tid' => tid <> tid') extra loc ts from),\n        (<<UNCH: unchangable (Configuration.memory c_src) (Local.promises lc_src) loc ts from Message.reserve>>).\n  Proof.\n    ii. dup WF_SRC. inv WF_SRC.\n    inv EXTRA. exploit sim_configuration_extra_promise_exist; eauto. i. des.\n    dup TID1. eapply WF in TID1. inv TID1. esplits. econs.\n    { eapply PROMISES. eauto. }\n    { inv WF. exploit DISJOINT; eauto. intros DISJ. inv DISJ.\n      destruct (Memory.get loc ts (Local.promises lc_src)) as [[from' msg']|] eqn:GET; auto.\n      exfalso. inv DISJOINT0. exploit DISJOINT1; eauto. i. des.\n      eapply memory_get_ts_strong in GET. des; subst; ss.\n      eapply memory_get_ts_strong in  PROMISE. des; subst; ss.\n      eapply x; eauto.\n      { econs; [|refl]. auto. }\n      { econs; ss. refl. }\n    }\n  Qed.\n\n  Lemma pf_consistent_pi_consistent\n        (prom_others prom_self: Time.t -> Time.t -> Prop)\n        lang (st_src st_mid st_tgt: Language.state lang)\n        lc_tgt mem_src mem_tgt sc_tgt\n        tr_cert ths_tgt pl\n        (CONFIGTGT: Configuration.wf (Configuration.mk ths_tgt sc_tgt mem_tgt))\n        (CONSISTENT: pf_consistent_super_strong_promises_list\n                       (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt)\n                       tr_cert\n                       times pl)\n        (PROMOTHERS: forall loc ts (PROM: (prom_others \\\\2// prom_self) loc ts),\n            exists from to val released,\n              (<<GET: Memory.get loc to mem_tgt = Some (from, Message.concrete val released)>>) /\\\n              (<<TS: Time.le ts to>>))\n        (PROMSELF: forall loc ts (PROM: prom_self loc ts),\n            exists from val released,\n              (<<GET: Memory.get loc ts (Local.promises lc_tgt) = Some (from, Message.concrete val released)>>))\n        (FORGET: forall loc ts\n                        (PROMISED: concrete_promised mem_tgt loc ts),\n            (<<PROMISED: concrete_promised mem_src loc ts>>) \\/\n            <<FORGET: (prom_others \\\\2// prom_self) loc ts>>)\n        (NOREAD: List.Forall\n                   (fun the => no_read_msgs\n                                 prom_others\n                                 (snd the)) tr_cert)\n    :\n      pi_consistent\n        prom_self pl mem_src\n        (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt).\n  Proof.\n    unfold pf_consistent_super_strong_promises_list in *. des. ss. econs.\n    { i. eapply PROMSELF in PROM. des. eapply COMPLETE; eauto. }\n    { exploit (@concrete_promise_max_timemap_exists mem_tgt (Local.promises lc_tgt)).\n      { eapply CONFIGTGT. } intros [max MAX].\n      ii. exploit CONSISTENT0; eauto. i. ss. des.\n      { exists (ftr0 ++ ftr_reserve), e1.\n        assert (NOREADTGT:\n                  Forall\n                    (fun em =>\n                       (no_read_msgs\n                          (fun (loc : Loc.t) (ts : Time.t) =>\n                             ~\n                               (covered loc ts (Local.promises lc_tgt) \\/\n                                concrete_promised mem_tgt loc ts \\/ Time.lt (tm loc) ts)) (snd em)))\n                    (ftr0 ++ ftr1)).\n        { eapply Forall_app.\n          { eapply Forall_app_inv in EVENTS. des.\n            eapply List.Forall_impl; try apply FORALL1; eauto. i. ss. des; eauto. }\n          { eapply Forall_app_inv in EVENTSCERT. des.\n            eapply List.Forall_impl; try apply FORALL2; eauto. i. ss. des; eauto. }\n        }\n        assert (NOREADSRC:\n                  Forall\n                    (fun em =>\n                       (no_read_msgs\n                          (fun (loc : Loc.t) (ts : Time.t) =>\n                             ~\n                               (covered loc ts (Local.promises lc_tgt) \\/\n                                concrete_promised mem_src loc ts \\/ Time.lt (tm loc) ts)) (snd em)))\n                    (ftr0 ++ ftr1)).\n        { eapply List.Forall_forall. i. dup H.\n          eapply List.Forall_forall in H0; try apply NOREADTGT; eauto. ss.\n          eapply list_Forall2_in in H; eauto. des.\n          eapply List.Forall_forall in IN; eauto. ss.\n          destruct x, a. ss. inv SAT; ss.\n          { ii. eapply H0. ii. eapply H. des; auto.\n            eapply FORGET in H1. des; ss; auto. destruct FORGET0; ss.\n            { replace fto with to in *; ss.\n              eapply MAPIDENT; eauto.\n              exploit PROMOTHERS.\n              { left. eauto. } i. des.\n              eapply MAX in GET; eauto.\n            }\n            { eapply PROMSELF in H1. des. left. econs; eauto. econs; ss; [|refl].\n              dup GET. apply memory_get_ts_strong in GET0. des; auto.\n              subst. inv LOCAL. erewrite BOT in GET. ss. }\n          }\n          { ii. eapply H0. ii. eapply H. des; auto.\n            eapply FORGET in H1. des; ss; auto. destruct FORGET0; ss.\n            { replace ffrom with from in *; ss.\n              eapply MAPIDENT; eauto.\n              exploit PROMOTHERS.\n              { left. eauto. } i. des.\n              eapply MAX in GET; eauto.\n            }\n            { eapply PROMSELF in H1. des. left. econs; eauto. econs; ss; [|refl].\n              dup GET. apply memory_get_ts_strong in GET0. des; auto.\n              subst. inv LOCAL. erewrite BOT in GET. ss. }\n          }\n        }\n        splits; eauto.\n        { eapply Forall_app_inv in NOREADSRC. des. eapply list_Forall_sum.\n          { instantiate (1:=fun em => wf_time_evt times (snd em) /\\ ThreadEvent.get_machine_event (snd em) = MachineEvent.silent).\n            eapply List.Forall_impl; eauto. i. ss. des; auto. }\n          { eapply Forall_app; try apply FORALL1. eapply List.Forall_impl; eauto.\n            i. ss. des. destruct a. ss. destruct t0; ss. }\n          { i. ss. des. splits; auto. }\n        }\n        { left. exists val, we, (ftr_cancel ++ ftr1). splits; auto.\n          eapply Forall_app_inv in NOREADSRC. des. eapply list_Forall_sum.\n          { instantiate (1:=fun em => wf_time_evt times (snd em) /\\ ThreadEvent.get_machine_event (snd em) = MachineEvent.silent).\n            eapply List.Forall_impl; eauto. i. ss. des; auto. }\n          { eapply Forall_app; try apply FORALL2. eapply List.Forall_impl; eauto.\n            i. ss. des. destruct a. ss. destruct t0; ss. }\n          { i. ss. }\n        }\n      }\n      { unguard. exists ftr, e1. splits; auto.\n        eapply List.Forall_forall. i. dup H.\n        eapply List.Forall_forall in H0; try apply EVENTS; eauto. ss.\n        eapply list_Forall2_in in H; eauto. des.\n        eapply List.Forall_forall in IN; eauto. ss.\n        destruct x, a. ss. splits; auto. inv SAT; ss.\n        { ii. eapply SAT3. ii. eapply H. des; auto.\n          eapply FORGET in H0. des; ss; auto.\n          { replace fto with to in *; ss.\n            eapply MAPIDENT; eauto.\n            exploit PROMOTHERS.\n            { left. eauto. } i. des.\n            eapply MAX in GET; eauto.\n          }\n          { eapply PROMSELF in FORGET0. des. left. econs; eauto. econs; ss; [|refl].\n            dup GET. apply memory_get_ts_strong in GET0. des; auto.\n            subst. inv LOCAL. erewrite BOT in GET. ss. }\n        }\n        { ii. eapply SAT3. ii. eapply H. des; auto.\n          eapply FORGET in H0. des; ss; auto.\n          { replace ffrom with from in *; ss.\n            eapply MAPIDENT; eauto.\n            exploit PROMOTHERS.\n            { left. eauto. } i. des.\n            eapply MAX in GET; eauto.\n          }\n          { eapply PROMSELF in FORGET0. des. left. econs; eauto. econs; ss; [|refl].\n            dup GET. apply memory_get_ts_strong in GET0. des; auto.\n            subst. inv LOCAL. erewrite BOT in GET. ss. }\n        }\n      }\n    }\n  Qed.\n\n  Lemma pf_consistent_past_consistent\n        (prom_others prom_self: Time.t -> Time.t -> Prop)\n        lang (st_src st_mid st_tgt: Language.state lang)\n        lc_tgt mem_src mem_tgt sc_tgt\n        tr_cert ths_tgt\n        (CONFIGTGT: Configuration.wf (Configuration.mk ths_tgt sc_tgt mem_tgt))\n        (CONSISTENTS: pf_consistent_super_strong\n                       (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt)\n                       tr_cert\n                       times)\n        (PROMOTHERS: forall loc ts (PROM: (prom_others \\\\2// prom_self) loc ts),\n            exists from to val released,\n              (<<GET: Memory.get loc to mem_tgt = Some (from, Message.concrete val released)>>) /\\\n              (<<TS: Time.le ts to>>))\n        (PROMSELF: forall loc ts (PROM: prom_self loc ts),\n            exists from val released,\n              (<<GET: Memory.get loc ts (Local.promises lc_tgt) = Some (from, Message.concrete val released)>>))\n        (FORGET: forall loc ts\n                        (PROMISED: concrete_promised mem_tgt loc ts),\n            (<<PROMISED: concrete_promised mem_src loc ts>>) \\/\n            <<FORGET: (prom_others \\\\2// prom_self) loc ts>>)\n        (NOREAD: List.Forall\n                   (fun the => no_read_msgs\n                                 prom_others\n                                 (snd the)) tr_cert)\n    :\n      past_consistent\n        mem_src\n        (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt).\n  Proof.\n    exploit (@concrete_promise_max_timemap_exists mem_tgt (Local.promises lc_tgt)).\n    { eapply CONFIGTGT. } intros [max MAX].\n    ii. exploit CONSISTENTS; eauto. i. ss. des.\n    exists ftr, e1. esplits; eauto.\n    { eapply List.Forall_forall. i. dup H.\n      eapply List.Forall_forall in H0; try apply NOREADTGT; eauto. ss.\n      eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in IN; eauto. ss.\n      destruct x, a. ss. splits; auto. inv SAT; ss.\n      { ii. eapply SAT3. ii. eapply H. des; eauto.\n        eapply FORGET in H0. des; ss; auto. destruct FORGET0; ss.\n        { replace fto with to in *; ss.\n          eapply MAPIDENT; eauto.\n          exploit PROMOTHERS.\n          { left. eauto. } i. des.\n          eapply MAX in GET; eauto.\n        }\n        { eapply PROMSELF in H0. des. left. econs; eauto. econs; ss; [|refl].\n          dup GET. apply memory_get_ts_strong in GET0. des; auto.\n          subst. inv LOCAL. erewrite BOT in GET. ss. }\n      }\n      { ii. eapply SAT3. ii. eapply H. des; eauto.\n        eapply FORGET in H0. des; ss; auto. destruct FORGET0; ss.\n        { replace ffrom with from in *; ss.\n          eapply MAPIDENT; eauto.\n          exploit PROMOTHERS.\n          { left. eauto. } i. des.\n          eapply MAX in GET; eauto.\n        }\n        { eapply PROMSELF in H0. des. left. econs; eauto. econs; ss; [|refl].\n          dup GET. apply memory_get_ts_strong in GET0. des; auto.\n          subst. inv LOCAL. erewrite BOT in GET. ss. }\n      }\n    }\n    { unguard. des; eauto. }\n  Qed.\n\n  Lemma sim_thread_sim_configuration\n        (consistent: bool)\n        tids views0 prom extra proml\n        (c_src c_mid c_tgt: Configuration.t)\n        tid lang (st_src st_mid st_tgt: Language.state lang)\n        lc_src lc_mid lc_tgt mem_src mem_mid mem_tgt sc_src sc_mid sc_tgt\n        (CONFIG: sim_configuration tids views0 prom extra proml c_src c_mid c_tgt)\n        views1 prom_self extra_self tr_cert ths_src ths_mid ths_tgt pl\n        (VIEWSLE: views_le views0 views1)\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views1 loc ts))\n        (MEMWF: memory_times_wf times mem_mid)\n        (MEMWFTGT: memory_times_wf times mem_tgt)\n        (FUTURESRC: Memory.future_weak (Configuration.memory c_src) mem_src)\n        (FUTUREMID: Memory.future_weak (Configuration.memory c_mid) mem_mid)\n        (FUTURETGT: Memory.future_weak (Configuration.memory c_tgt) mem_tgt)\n        (CONFIGTGT: Configuration.wf (Configuration.mk ths_tgt sc_tgt mem_tgt))\n        (CONFIGMID: JConfiguration.wf views1 (Configuration.mk ths_mid sc_mid mem_mid))\n        (CONSISTENT: ternary consistent (pf_consistent_super_strong_promises_list\n                                           (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt)\n                                           tr_cert\n                                           times pl) True)\n        (CONSISTENTS: pf_consistent_super_strong\n                        (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt)\n                        tr_cert\n                        times)\n        (NOREAD: List.Forall\n                   (fun the => no_read_msgs\n                                 (all_promises (fun tid' => tid <> tid') prom)\n                                 (snd the)) tr_cert)\n        (THREAD:\n           sim_thread\n             views1\n             prom_self\n             (all_promises (fun tid' => tid <> tid') prom)\n             extra_self\n             (all_extra (fun tid' => tid <> tid') extra)\n             (Thread.mk _ st_src lc_src sc_src mem_src)\n             (Thread.mk _ st_mid lc_mid sc_mid mem_mid)\n             (Thread.mk _ st_tgt lc_tgt sc_tgt mem_tgt))\n        (THSSRC:\n           forall tid',\n             IdentMap.find tid' ths_src =\n             if (Ident.eq_dec tid' tid)\n             then Some (existT _ lang st_src, lc_src)\n             else IdentMap.find tid' (Configuration.threads c_src))\n        (THSMID:\n           forall tid',\n             IdentMap.find tid' ths_mid =\n             if (Ident.eq_dec tid' tid)\n             then Some (existT _ lang st_mid, lc_mid)\n             else IdentMap.find tid' (Configuration.threads c_mid))\n        (THSTGT:\n           forall tid',\n             IdentMap.find tid' ths_tgt =\n             if (Ident.eq_dec tid' tid)\n             then Some (existT _ lang st_tgt, lc_tgt)\n             else IdentMap.find tid' (Configuration.threads c_tgt))\n    :\n      sim_configuration\n        (ternary consistent tids (fun tid' => tids tid' /\\ tid' <> tid))\n        views1\n        (fun tid' => if (Ident.eq_dec tid' tid) then prom_self else (prom tid'))\n        (fun tid' => if (Ident.eq_dec tid' tid) then extra_self else (extra tid'))\n        (fun tid' => if (Ident.eq_dec tid' tid) then pl else (proml tid'))\n        (Configuration.mk ths_src sc_src mem_src)\n        (Configuration.mk ths_mid sc_mid mem_mid)\n        (Configuration.mk ths_tgt sc_tgt mem_tgt)\n  .\n  Proof.\n    dep_inv THREAD. dep_inv CONFIG. econs; auto.\n    { i. erewrite THSSRC. erewrite THSMID. des_ifs. }\n    { i. erewrite THSMID. erewrite THSTGT. des_ifs.\n      eapply option_rel_mon; try apply THSJOIN.\n      i. eapply JSim.sim_statelocal_le; eauto. }\n    { ii. erewrite THSSRC in NONE. des_ifs. eauto. }\n    { replace (all_promises\n                 (fun _ => True)\n                 (fun tid' => if LocSet.Facts.eq_dec tid' tid then prom_self else prom tid'))\n        with\n          (all_promises (fun tid' => tid <> tid') prom \\\\2// prom_self); cycle 1.\n      { extensionality loc. extensionality ts.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n        { destruct H.\n          { inv H. eapply all_promises_intro with (tid:=tid0); ss. des_ifs. }\n          { eapply all_promises_intro with (tid:=tid); ss. des_ifs. }\n        }\n        { inv H. unguard. des_ifs; auto. econs; eauto. }\n      }\n      replace (all_extra\n                 (fun _ => True)\n                 (fun tid' => if LocSet.Facts.eq_dec tid' tid then extra_self else extra tid'))\n        with\n          (all_extra (fun tid' => tid <> tid') extra \\\\3// extra_self); cycle 1.\n      { extensionality loc. extensionality ts. extensionality from.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n        { destruct H.\n          { inv H. eapply all_extra_intro with (tid:=tid0); ss. des_ifs. }\n          { eapply all_extra_intro with (tid:=tid); ss. des_ifs. }\n        }\n        { inv H. unguard. des_ifs; auto. econs; eauto. }\n      }\n      auto.\n    }\n    { i. erewrite THSTGT in GET. unfold ternary in IN. des_ifs.\n      { dep_clarify.\n        eapply pf_consistent_pi_consistent; eauto.\n        { i. exploit sim_memory_forget_concrete_promised.\n          { eapply MEMPF. }\n          { eapply PROM. }\n          i. eapply sim_memory_concrete_promised_later in x0; eauto; cycle 1.\n          { eapply CONFIGTGT. }\n          des. inv PROMISED. esplits; eauto.\n        }\n        { i. inv LOCALPF. inv LOCALJOIN.\n          set (CNT:=(sim_promise_contents PROMS) loc ts). inv CNT; ss.\n          specialize (PROMISES loc ts).  rewrite <- H in *. inv PROMISES. eauto. }\n        { i. eapply jsim_memory_concrete_promised in PROMISED; cycle 1; eauto.\n          apply NNPP. ii. apply not_or_and in H. des. eapply H.\n          eapply sim_memory_concrete_promised; eauto. }\n      }\n      { dep_clarify. unguard. des; ss. }\n      { eapply pi_consistent_mon; eauto. }\n      { unguard. des. eapply pi_consistent_mon; eauto. }\n    }\n    { i. rewrite THSTGT in GET. des_ifs.\n      { dep_clarify. left.\n        eapply pf_consistent_past_consistent; try apply CONSISTENTS; eauto.\n        { i. exploit sim_memory_forget_concrete_promised.\n          { eapply MEMPF. }\n          { eapply PROM. }\n          i. eapply sim_memory_concrete_promised_later in x0; eauto; cycle 1.\n          { eapply CONFIGTGT. }\n          des. inv PROMISED. esplits; eauto.\n        }\n        { i. inv LOCALPF. inv LOCALJOIN.\n          set (CNT:=(sim_promise_contents PROMS) loc ts). inv CNT; ss.\n          specialize (PROMISES loc ts).  rewrite <- H in *. inv PROMISES. eauto. }\n        { i. eapply jsim_memory_concrete_promised in PROMISED; cycle 1; eauto.\n          apply NNPP. ii. apply not_or_and in H. des. eapply H.\n          eapply sim_memory_concrete_promised; eauto. }\n      }\n      { exploit PAST; eauto. i. des.\n        { left. eapply past_consistent_mon; eauto. }\n        { right. splits; auto. rewrite THSSRC. rewrite THSMID. des_ifs. }\n      }\n    }\n  Qed.\n\n  Lemma sim_configuration_forget_src_not_concrete tids c_src c_mid c_tgt prom extra views pls\n        (SIM: sim_configuration tids views prom extra pls c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (WF_MID: JConfiguration.wf views c_mid)\n        (WF_TGT: Configuration.wf c_tgt)\n        tid lang st lc_tgt\n        (TID: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st, lc_tgt))\n    :\n      forall loc ts\n             (PROMISE: all_promises (fun tid': Ident.t => tid <> tid') prom loc ts),\n        ~ ((covered loc ts (Local.promises lc_tgt)) \\/\n           concrete_promised (Configuration.memory c_src) loc ts \\/ Time.lt (Memory.max_ts loc (Configuration.memory c_tgt)) ts).\n  Proof.\n    inv SIM. ss. ii. inv PROMISE.\n    assert (PROMISE: all_promises (fun _ => True) prom loc ts).\n    { econs; eauto. }\n    des.\n    { exploit sim_configuration_forget_promise_exist; eauto. i. des. ss.\n      dup THSJOIN. specialize (THSJOIN0 tid).\n      specialize (THSPF tid0). specialize (THSJOIN tid0).\n      unfold option_rel in *. unfold language in *. des_ifs.\n      inv THSPF. inv LOCAL.\n      set (CNT:=(sim_promise_contents PROMS0) loc ts). inv CNT; ss.\n      dep_inv THSJOIN. inv LOCAL.\n      specialize (PROMISES loc ts). rewrite <- H2 in *. inv PROMISES.\n      inv H. dep_inv THSJOIN0.\n      assert (exists msg_tgt, <<GET: Memory.get loc to (Local.promises lc_src) = Some (from0, msg_tgt)>>).\n      { inv LOCAL. specialize (PROMISES loc to). ss.\n        rewrite GET in PROMISES. inv PROMISES; eauto. } clear NIL. des.\n      inv WF_MID. inv WF. ss. inv WF0.\n      hexploit DISJOINT; eauto. i. inv H. ss. inv DISJOINT0.\n      hexploit DISJOINT1; eauto. i. des.\n      { eapply H; eauto. econs; ss; [|refl].\n        symmetry in H6. apply memory_get_ts_strong in H6. des; auto. subst.\n        inv ITV. ss. clear - FROM. exfalso.\n        eapply Time.lt_strorder. eapply TimeFacts.le_lt_lt; eauto. eapply Time.bot_spec. }\n    }\n    { erewrite sim_memory_concrete_promised in H; eauto. des. ss. }\n    { erewrite <- SimMemory.sim_memory_max_ts in H; eauto.\n      { set (CNT:=(sim_memory_contents MEMPF) loc ts). inv CNT; ss.\n        symmetry in H2. eapply Memory.max_ts_spec in H2. des. timetac. }\n      { eapply WF_MID. }\n      { eapply WF_TGT. }\n    }\n  Qed.\n\n  Lemma sim_thread_consistent\n        views prom_self prom_others extra_self extra_others\n        lang th_src th_mid th_tgt tr\n        (CONSISTENTTGT: pf_consistent_super_strong th_tgt tr times)\n        (THREAD: @sim_thread_strong\n                   views prom_self prom_others extra_self extra_others\n                   lang th_src th_mid th_tgt)\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src) (Thread.memory th_src))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid) (Thread.memory th_mid))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt) (Thread.memory th_tgt))\n        (MEMSRC: Memory.closed (Thread.memory th_src))\n        (MEMMID: Memory.closed (Thread.memory th_mid))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt))\n        (LOCALSRC: Local.wf (Thread.local th_src) (Thread.memory th_src))\n        (LOCALMID: Local.wf (Thread.local th_mid) (Thread.memory th_mid))\n        (LOCALTGT: Local.wf (Thread.local th_tgt) (Thread.memory th_tgt))\n        (MEMWF: memory_times_wf times (Thread.memory th_mid))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt))\n        (NOREAD: List.Forall (fun the => no_read_msgs prom_others (snd the)) tr)\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src) (Local.promises (Thread.local th_src)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src) (Local.promises (Thread.local th_src)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src) loc ts) (views loc ts))\n\n        (REL: joined_released\n                views (Local.promises (Thread.local th_mid)) (Local.tview (Thread.local th_mid)).(TView.rel))\n        (JOINEDMEM: joined_memory views (Thread.memory th_mid))\n        (VIEWS: wf_views views)\n    :\n      PF.pf_consistent L th_src.\n  Proof.\n    dup THREAD. dep_inv THREAD.\n    hexploit sim_memory_strong_exists; eauto. i. des.\n    assert (MEMSRCSTRONG: Memory.closed mem_src').\n    { eapply sim_memory_same_closed; eauto.\n      eapply sim_memory_strong_sim_memory; eauto. }\n\n    hexploit (later_timemap_exists\n                (TimeMap.join\n                   (Memory.max_timemap mem_src')\n                   (TimeMap.join\n                      (Memory.max_timemap mem_src)\n                      (TimeMap.join\n                         (Memory.max_timemap mem_mid)\n                         (Memory.max_timemap mem_tgt))))). intros [tm ?]. des.\n\n    assert (TM0': forall loc,\n               Time.lt (Memory.max_ts loc mem_src') (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM0: forall loc,\n               Time.lt (Memory.max_ts loc mem_src) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM1: forall loc,\n               Time.lt (Memory.max_ts loc mem_mid) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM2: forall loc,\n               Time.lt (Memory.max_ts loc mem_tgt) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). refl. }\n\n    hexploit (@cap_flex_exists mem_src' tm); eauto.\n    intros [cap_src' CAPSRCSTRONG].\n    hexploit (@cap_flex_exists mem_mid tm); eauto.\n    intros [cap_mid CAPMID].\n    hexploit (@cap_flex_exists mem_tgt tm); eauto.\n    intros [cap_tgt CAPTGT].\n    hexploit (@Memory.max_concrete_timemap_exists mem_src); try apply MEMSRC.\n    intros [max MAX].\n\n    hexploit (@Memory.cap_exists mem_src); eauto. intros [mem1 CAP]. des.\n    hexploit (@Memory.max_concrete_timemap_exists mem1); eauto.\n    { eapply Memory.cap_closed in MEMSRC; eauto. eapply MEMSRC. } intros [sc1 SC_MAX].\n    assert (SCSRC0: Memory.closed_timemap sc1 mem_src).\n    { eapply concrete_promised_le_closed_timemap.\n      { eapply concrete_messages_le_concrete_promised_le.\n        eapply cap_flex_concrete_messages_le.\n        { eapply cap_cap_flex; eauto. }\n        { eauto. }\n        { i. ss. eapply Time.incr_spec. }\n      }\n      eapply Memory.max_concrete_timemap_closed; eauto.\n    }\n    assert (SCSRC1: Memory.closed_timemap sc1 mem_src').\n    { eapply concrete_promised_le_closed_timemap; eauto.\n      eapply concrete_messages_le_concrete_promised_le.\n      eapply sim_memory_same_concrete_messages_le; eauto.\n      eapply sim_memory_strong_sim_memory; eauto. }\n    assert (SCMID0: Memory.closed_timemap sc1 mem_mid).\n    { eapply concrete_promised_le_closed_timemap; try apply SCSRC0; eauto.\n      eapply concrete_messages_le_concrete_promised_le.\n      eapply sim_memory_concrete_messages_le; eauto. }\n    exploit (@Memory.max_concrete_timemap_exists mem_tgt).\n    { eapply MEMTGT. } intros [sctgt MAXTGT]. des.\n\n    hexploit (@concrete_promise_max_timemap_exists mem_tgt (Local.promises lc_tgt)).\n    { eapply MEMTGT. } intros [maxconcete MAXCONCRETE].\n\n    exploit (CONSISTENTTGT cap_tgt (Memory.max_timemap mem_src) sctgt); simpl.\n    { ss. eapply cap_flex_future_weak; eauto. }\n    { eapply cap_flex_closed; eauto. }\n    { eapply cap_flex_wf; eauto. }\n    { eauto. }\n    i. des. ss.\n\n    hexploit sim_thread_steps_silent; simpl.\n    { eapply STEPS. }\n    { econs.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { eauto. }\n      { eapply sim_memory_strong_cap; eauto. }\n      { eapply (@cap_flex_sim_memory mem_mid mem_tgt); eauto. }\n      { instantiate (1:=sc1).\n        eapply Memory.max_concrete_timemap_spec.\n        { instantiate (1:=mem_mid).\n          exploit (@Memory.max_concrete_timemap_exists mem_mid); eauto.\n          { eapply MEMMID. } i. des.\n          exploit (@SimMemory.sim_memory_max_concrete_timemap mem_mid mem_tgt); eauto.\n          i. subst. auto.\n        }\n        auto.\n      }\n    }\n    { eapply List.Forall_forall. i.\n      cut (no_read_msgs prom_others (snd x)).\n      { eapply List.Forall_forall in EVENTS; eauto. i. des. splits; auto. }\n      destruct x. dup H. eapply list_Forall2_in in H; eauto. des. destruct a. ss.\n      eapply List.Forall_forall in IN0; eauto. ss.\n      eapply List.Forall_forall in H0; eauto. ss. des. inv SAT; auto; s.\n      { intros PROM. replace fto with to in PROM; ss. eapply MAPIDENT; eauto.\n        exploit sim_memory_forget_concrete_promised.\n        { eapply MEMPF. }\n        { left. eauto. }\n        i. eapply sim_memory_concrete_promised_later in x0; eauto. des.\n        inv PROMISED. etrans; eauto. eapply MAXCONCRETE in GET. auto.\n      }\n      { intros PROM. replace ffrom with from in PROM; ss. eapply MAPIDENT; eauto.\n        exploit sim_memory_forget_concrete_promised.\n        { eapply MEMPF. }\n        { left. eauto. }\n        i. eapply sim_memory_concrete_promised_later in x0; eauto. des.\n        inv PROMISED. etrans; eauto. eapply MAXCONCRETE in GET. auto.\n      }\n    }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. } eauto. }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. } eauto. }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. }\n      eapply Memory.max_concrete_timemap_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_wf; eauto.\n      eapply sim_memory_strong_sim_local; eauto.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { inv LOCALPF. ss. }\n    }\n    { ss. eapply cap_flex_wf; eauto. }\n    { ss. eapply cap_flex_wf; eauto. }\n    { ss. eapply cap_flex_memory_times_wf; cycle 1; eauto. }\n    { ss. eapply cap_flex_memory_times_wf; cycle 1; eauto. }\n    { destruct x1.\n      { des. inv LOCAL. auto. }\n      { des. ii. erewrite PROMISES in *. erewrite Memory.bot_get in *. ss. }\n    }\n    { ss. ii. exploit EXCLUSIVE; eauto. i. des. inv UNCH.\n      set (CNT:=(sim_memory_strong_contents MEM) loc ts).\n      inv CNT; ss; try by (exfalso; eapply NPROM0; left; auto).\n      symmetry in H0. eapply CAPSRCSTRONG in H0. esplits. econs; eauto. }\n    { ss. ii. exploit EXCLUSIVEEXTRA; eauto. i. des. inv x.\n      set (CNT:=(sim_memory_strong_contents MEM) loc ts).\n      exploit ((sim_memory_strong_wf MEM) loc from ts).\n      { left. auto. } i. des.\n      inv CNT; ss; try by (exfalso; eapply NEXTRA; left; eauto).\n      eapply UNIQUE in EXTRA. subst.\n      symmetry in H0. eapply CAPSRCSTRONG in H0. esplits. econs; eauto. }\n    { ss. i. eapply List.Forall_impl; eauto. i. ss.\n      eapply semi_closed_view_future.\n      2: { eapply cap_flex_future_weak; eauto. }\n      { eapply concrete_promised_le_semi_closed_view; eauto.\n        eapply concrete_messages_le_concrete_promised_le.\n        eapply sim_memory_same_concrete_messages_le; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n    }\n    { ss. }\n    { ss. eapply joined_memory_cap_flex; eauto. }\n    { ss. }\n\n    i. des. hexploit (trace_times_list_exists tr_src). i. des.\n\n    hexploit (@cap_flex_map_exists\n                (Memory.max_timemap mem_src')\n                tm\n                (fun loc : Loc.t => Time.incr (Memory.max_ts loc mem_src))\n                times0); auto.\n    { i. erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src'); eauto.\n      { apply Time.incr_spec. }\n      { eapply sim_memory_strong_sim_memory; eauto. }\n    } i. des.\n\n    exploit (@Memory.max_concrete_timemap_exists mem_src').\n    { eapply MEMSRCSTRONG. } i. des.\n    hexploit concrete_messages_le_cap_flex_memory_map; try apply MAP.\n    { eapply sim_memory_same_concrete_messages_le.\n      { eapply sim_memory_strong_sim_memory; eauto. }\n      { eapply MEMPF. }\n    }\n    { eauto. }\n    { ii. ss. eapply max_concrete_ts_le_max_ts; eauto. }\n    { auto. }\n    { i. ss. eapply Time.incr_spec. }\n    { eauto. }\n    { eapply cap_cap_flex; eauto. }\n    { eauto. }\n    { eauto. }\n    intros MEMORYMAP. destruct th_src1. ss.\n    hexploit trace_steps_map; try apply MEMORYMAP.\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; eauto.\n      i. ss. eapply MAP in IN0. eauto. }\n    { eauto. }\n    { ss. }\n    { ss. }\n    { ss. }\n    { eapply cap_flex_wf; eauto.\n      eapply sim_memory_strong_sim_local; eauto.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { inv LOCALPF. ss. }\n    }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    { eapply cap_flex_closed; eauto. }\n    { eapply Memory.max_concrete_timemap_closed; eauto. }\n    { eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. }\n      { eauto. }\n    }\n    { eapply map_ident_in_memory_local; eauto.\n      { ii. eapply MAP; auto.\n        erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src') in TS; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n      { eapply MAP. }\n    }\n    { eapply mapping_map_lt_collapsable_unwritable. eapply MAP. }\n    { eapply map_ident_in_memory_closed_timemap.\n      { ii. eapply MAP; auto.\n        erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src') in TS; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n      { eauto. }\n    }\n    { refl. }\n\n    i. des.\n    assert (SILENT: List.Forall\n                      (fun the =>\n                         ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) ftr0).\n    { eapply List.Forall_forall. i.\n      eapply list_Forall2_in in H; eauto. i. des.\n      eapply sim_traces_silent in TRACE0; eauto.\n      { eapply tevent_map_same_machine_event in EVENT. erewrite EVENT.\n        eapply List.Forall_forall in TRACE0; eauto. }\n      { eapply List.Forall_impl; eauto. i. ss. des. auto. }\n    }\n\n    exists ftr0. dep_inv THREAD. esplits.\n    { ii. ss. eapply Memory.cap_inj in CAP; eauto. subst.\n      eapply Memory.max_concrete_timemap_inj in SC_MAX; eauto. subst.\n      esplits. eauto. eauto.\n      esplits; eauto. ss. unguard. des.\n      { left. esplits. econs 2. econs; eauto. econs.\n        eapply failure_step_map; eauto.\n        { eapply mapping_map_lt_map_le. eapply MAP. }\n        { eapply mapping_map_lt_map_eq. eapply MAP. }\n        eapply sim_failure_step; cycle 1.\n        { eapply sim_local_strong_sim_local; eauto. }\n        eapply JSim.sim_local_failure; eauto.\n      }\n      { right. esplits; eauto. ss. inv LOCAL.\n      cut ((Local.promises local) = Memory.bot).\n      { i. eapply bot_promises_map; eauto. erewrite <- H. eauto. }\n      eapply JSim.sim_local_memory_bot in LOCALJOIN0; auto.\n      inv LOCALPF0. ss.\n      eapply sim_promise_bot; eauto. eapply sim_promise_strong_sim_promise; eauto.\n      }\n    }\n    { eapply sim_traces_pf in TRACE0; eauto.\n      eapply List.Forall_forall. i.\n      eapply list_Forall2_in in H; eauto. des. destruct a, x; ss.\n      eapply List.Forall_forall in IN0; try apply TRACE0; eauto.\n      inv EVENT; ss. ii. ss. clarify. destruct msg; ss.\n      - exploit IN0; ss.\n      - inv MSG; ss. }\n  Qed.\n\n\n  Lemma configuration_step_not_consistent_future\n        c1 tid tr lang st1 lc1 th2\n        (TID: IdentMap.find tid (Configuration.threads c1) =\n              Some (existT _ lang st1, lc1))\n        (WF: Configuration.wf c1)\n        (STEPS: Trace.steps\n                  tr\n                  (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                  th2)\n    :\n      Configuration.wf\n        (Configuration.mk\n           (IdentMap.add\n              tid\n              (existT _ lang (Thread.state th2), (Thread.local th2))\n              (Configuration.threads c1))\n           (Thread.sc th2) (Thread.memory th2))\n  .\n  Proof.\n    inv WF. inv WF0.\n    exploit THREADS; ss; eauto. i.\n    exploit Trace.steps_future; eauto. s. i. des.\n    econs; ss. econs; i.\n    { erewrite IdentMap.gsspec in TH1.\n      erewrite IdentMap.gsspec in TH2. des_ifs; dep_clarify.\n      { symmetry. eapply Trace.steps_disjoint; eauto. }\n      { eapply Trace.steps_disjoint; eauto. }\n      { eapply DISJOINT; [|eauto|eauto]. auto. }\n    }\n    { erewrite IdentMap.gsspec in TH. des_ifs; dep_clarify.\n      eapply Trace.steps_disjoint; eauto.\n    }\n  Qed.\n\n  Lemma step_sim_configuration tids views0 prom0 extra0 proml0\n        c_src0 c_mid0 c_tgt0 c_tgt1 e tid tr_tgt tr_cert\n        (STEPTGT: @times_configuration_step times tr_tgt tr_cert e tid c_tgt0 c_tgt1)\n        (SIM: sim_configuration tids views0 prom0 extra0 proml0 c_src0 c_mid0 c_tgt0)\n        (NOREAD: List.Forall\n                   (fun the => no_read_msgs\n                                 (all_promises (fun tid' => tid <> tid') prom0)\n                                 (snd the)) tr_tgt)\n        (NOREADCERT: List.Forall\n                       (fun the => no_read_msgs\n                                     (all_promises (fun tid' => tid <> tid') prom0)\n                                     (snd the)) tr_cert)\n        (WF_SRC: Configuration.wf c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n    :\n      exists tr_src c_src1 c_mid1 views1 prom1 extra1 proml1,\n        (<<STEPMID: JConfiguration.step e tid c_mid0 c_mid1 views0 views1>>) /\\\n        (<<STEPSRC: PFConfiguration.opt_step_trace L tr_src e tid c_src0 c_src1>>) /\\\n        (<<TRACE: sim_traces L tr_src tr_tgt>>) /\\\n        __guard__(e = MachineEvent.failure \\/\n                  (<<SIM: sim_configuration tids views1 prom1 extra1 proml1 c_src1 c_mid1 c_tgt1>>) /\\\n                  (<<PROM: forall tid' (NEQ: tid <> tid'), prom1 tid' = prom0 tid'>>) /\\\n                  (<<EXTRA: forall tid' (NEQ: tid <> tid'), extra1 tid' = extra0 tid'>>) /\\\n                  (<<PROML: forall tid' (NEQ: tid <> tid'), proml1 tid' = proml0 tid'>>))\n  .\n  Proof.\n    hexploit times_configuration_step_future; eauto. i. des.\n    dep_inv STEPTGT.\n    assert (CONSISTENTLIST: exists pl,\n               forall (EQ: e0 <> ThreadEvent.failure),\n                 pf_consistent_super_strong_promises_list\n                   (Thread.mk _ st3 lc3 sc3 memory3) tr_cert times pl).\n    { destruct (classic (e0 = ThreadEvent.failure)).\n      { exists []. ii. ss. }\n      { hexploit CONSISTENT; eauto. i.\n        eapply pf_consistent_super_strong_promises_list_exists in H0; eauto.\n        { des. eauto. }\n        { ss. eapply WF2. }\n        { ss. eapply WF2; eauto. ss. erewrite IdentMap.gss. ss. }\n      }\n    }\n    hexploit sim_configuration_sim_thread; eauto. i. des.\n    generalize (sim_configuration_forget_exclusive SIM WF_SRC TIDSRC).\n    intros EXCLUSIVE.\n    generalize (sim_configuration_extra_exclusive SIM WF_SRC TIDSRC).\n    intros EXCLUSIVEEXTRA.\n    dup SIM. dup WF_MID. dup WF_SRC. inv WF_SRC. inv WF_MID. inv WF_TGT. inv SIM.\n    eapply Forall_app_inv in NOREAD. des.\n    eapply Forall_app_inv in TIMES. des.\n    exploit Trace.steps_future; eauto.\n    { ss. eapply WF1; eauto. } i. des.\n    exploit Thread.step_future; eauto. i. des. ss.\n    assert (CONSISTENT1: Local.promise_consistent lc3).\n    { destruct (classic (e0 = ThreadEvent.failure)) as [EQ|NEQ].\n      { subst. inv STEP; inv STEP0. ss. inv LOCAL. inv LOCAL0. auto. }\n      specialize (CONSISTENT NEQ).\n      eapply pf_consistent_super_strong_consistent in CONSISTENT; eauto.\n      eapply consistent_promise_consistent in CONSISTENT; eauto. }\n    assert (CONSTSIENT0: Local.promise_consistent (Thread.local e2)).\n    { eapply step_promise_consistent in STEP; eauto. }\n    exploit sim_thread_steps_silent; eauto; ss.\n    { eapply list_Forall_sum.\n      { eapply list_Forall_sum.\n        { eapply FORALL0. }\n        { eapply SILENT. }\n        { i. eapply (conj SAT0 SAT1). }\n      }\n      { eapply FORALL1. }\n      { i. ss. des. splits; auto. }\n    }\n    { eapply WF0. }\n    { eapply WF0. }\n    { eapply WF; eauto. }\n    { eapply WF0; eauto. }\n    { eapply WF1; eauto. }\n    i. des.\n    exploit JThread.tau_steps_future; eauto; ss.\n    { eapply WF0; eauto. }\n    { eapply WF0. }\n    { eapply WF0. }\n    i. des.\n    exploit Trace.steps_future; eauto; ss.\n    { eapply WF; eauto. }\n    i. des.\n    destruct (classic (ThreadEvent.get_machine_event e0 = MachineEvent.silent)) as [EQ|NEQ].\n    { eapply sim_thread_strong_sim_thread in THREAD.\n      hexploit sim_thread_step_silent; eauto.\n      { inv FORALL3. auto. }\n      { inv FORALL2. auto. }\n      { i. eapply EXCLUSIVE in OTHER. des. esplits.\n        eapply unchangable_trace_steps_increase; eauto. }\n      { i. eapply EXCLUSIVEEXTRA in OTHER. des. esplits.\n        eapply unchangable_trace_steps_increase; eauto. }\n      i. des. exists (tr_src ++ tr).\n      hexploit JThread.step_future; eauto. i. des.\n      hexploit Trace.steps_future; eauto. i. des.\n      assert (SIMTRACE: sim_traces L (tr_src++tr) (tr' ++ [((Thread.local e2), e0)])).\n      { eapply sim_traces_trans; eauto. replace tr with (tr++[]).\n        { econs; eauto. econs. }\n        { apply List.app_nil_r. }\n      }\n      assert (JSTEP: JConfiguration.step\n                       (ThreadEvent.get_machine_event e0) tid\n                       (Configuration.mk ths_mid sc_src mem_mid)\n                       (Configuration.mk\n                          (IdentMap.add\n                             tid\n                             (existT _ _ (Thread.state th_mid0), (Thread.local th_mid0)) ths_mid)\n                          (Thread.sc th_mid0) (Thread.memory th_mid0)) views0 views2).\n      { erewrite <- JSim.sim_event_machine_event; eauto. econs; eauto.\n        { destruct th_mid0. eauto. }\n        { i. dep_inv THREAD0. eapply JSim.sim_thread_consistent; eauto; ss.\n          eapply pf_consistent_super_strong_consistent; eauto.\n          eapply CONSISTENT. ii. subst. ss. }\n      }\n      hexploit (list_match_rev (tr_src++tr)). i. des.\n      { assert (tr_src = [] /\\ tr = []).\n        { split.\n          { destruct tr_src; auto. ss. }\n          { destruct tr; auto. destruct tr_src; ss. }\n        } des. subst. inv STEPSRC; ss. inv STEPSRC0; ss.\n        destruct th_mid0. esplits.\n        { eauto. }\n        { rewrite EQ. econs 2; eauto. }\n        { exploit sim_traces_trans; eauto. }\n        { right. splits.\n          { eapply (@sim_thread_sim_configuration true) with (tr_cert := tr_cert); eauto.\n            { etrans; eauto. }\n            { refl. }\n            {ss. eapply Memory.future_future_weak. etrans; eauto. }\n            { ss. eapply Memory.future_future_weak. etrans; eauto. }\n            { ss. eapply JConfiguration.step_future; eauto. }\n            { i. eapply CONSISTENTLIST. ii. subst. ss. }\n            { i. eapply CONSISTENT. ii. subst. ss. }\n            { eapply sim_thread_strong_sim_thread. eauto. }\n            { i. des_ifs. }\n            { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n            { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n          }\n          { i. ss. des_ifs. }\n          { i. ss. des_ifs. }\n          { i. ss. des_ifs. }\n        }\n      }\n      { hexploit Trace.steps_trans.\n        { eapply STEPSRC. }\n        { eapply STEPSRC0. } intros ALLSTEPS. rewrite H in ALLSTEPS. dup ALLSTEPS.\n        eapply Trace.steps_separate in ALLSTEPS. des. inv STEPS1; clarify.\n        inv STEPS2; ss. destruct th_src0, th_mid0. ss.\n        assert (ALLSILENT: List.Forall\n                             (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent)\n                             (tl_rev ++ [((Thread.local th1), e)])).\n        { rewrite <- H. eapply Forall_app.\n          { eapply sim_traces_silent; eauto. }\n          { eapply sim_trace_silent; eauto. i. clarify. }\n        }\n        eapply Forall_app_inv in ALLSILENT. des. inv FORALL5; ss.\n        assert (VSTEP: PFConfiguration.step_trace\n                         L\n                         (tr_src ++ tr)\n                         (ThreadEvent.get_machine_event e0) tid\n                         (Configuration.mk ths_src sc_src mem_src)\n                         (Configuration.mk\n                            (IdentMap.add\n                               tid\n                               (existT _ _ state, local) ths_src)\n                            sc memory)).\n        { rewrite EQ.\n          replace MachineEvent.silent with (ThreadEvent.get_machine_event e); auto.\n          exploit sim_thread_consistent; eauto.\n          { eapply CONSISTENT. ii. subst. clarify. }\n          { i. ss. eapply EXCLUSIVE in OTHER. des.\n            eapply unchangable_trace_steps_increase in ALLSTEPS0; eauto. }\n          { i. ss. eapply EXCLUSIVEEXTRA in OTHER. des.\n            eapply unchangable_trace_steps_increase in ALLSTEPS0; eauto. }\n          i. des. econs; try apply STEP0; eauto.\n          ii.\n          eapply sim_traces_pf; eauto.\n        }\n        (* exploit pf_step_trace_future; try apply VSTEP; eauto. i. des. ss. *)\n        esplits.\n        { eauto. }\n        { econs 1; eauto. }\n        { ss. }\n        { right. splits.\n          { eapply (@sim_thread_sim_configuration true); eauto.\n            { etrans; eauto. }\n            { ss. eapply Memory.future_future_weak. etrans; eauto. }\n            { ss. eapply Memory.future_future_weak. etrans; eauto. }\n            { ss. eapply Memory.future_future_weak. etrans; eauto. }\n            { eapply JConfiguration.step_future; eauto. }\n            { ss. eapply CONSISTENTLIST. ii. subst. ss. }\n            { ss. eapply CONSISTENT. ii. subst. ss. }\n            { dup THREAD0. eapply sim_thread_strong_sim_thread. eauto. }\n            { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n            { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n            { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n          }\n          { i. ss. des_ifs. }\n          { i. ss. des_ifs. }\n          { i. ss. des_ifs. }\n        }\n      }\n    }\n    { hexploit sim_thread_step_event; eauto.\n      { inv FORALL3. auto. }\n      { inv FORALL2. auto. }\n      { i. eapply EXCLUSIVE in OTHER. des. esplits.\n        eapply unchangable_trace_steps_increase; eauto. }\n      { i. eapply EXCLUSIVEEXTRA in OTHER. des. esplits.\n        eapply unchangable_trace_steps_increase; eauto. }\n      i. des. hexploit JThread.step_future; eauto. i. des.\n      hexploit Thread.step_future; eauto. i. des.\n      assert (JSTEP: JConfiguration.step\n                       (ThreadEvent.get_machine_event e0) tid\n                       (Configuration.mk ths_mid sc_src mem_mid)\n                       (Configuration.mk\n                          (IdentMap.add\n                             tid\n                             (existT _ _ (Thread.state th_mid0), (Thread.local th_mid0)) ths_mid)\n                          (Thread.sc th_mid0) (Thread.memory th_mid0)) views0 views2).\n      { econs; eauto.\n        { destruct th_mid0. eauto. }\n        { i. dep_inv THREAD0. eapply JSim.sim_thread_consistent; eauto; ss.\n          eapply pf_consistent_super_strong_consistent; eauto. }\n      }\n      assert (VSTEP: PFConfiguration.step_trace\n                       L\n                       (tr_src ++ [((Thread.local th_src1), e0)])\n                       (ThreadEvent.get_machine_event e0) tid\n                       (Configuration.mk ths_src sc_src mem_src)\n                       (Configuration.mk\n                          (IdentMap.add\n                             tid\n                             (existT _ _ (Thread.state th_src0), (Thread.local th_src0)) ths_src)\n                          (Thread.sc th_src0) (Thread.memory th_src0))).\n      { ss. econs; eauto.\n        { eapply sim_traces_silent; eauto. }\n        { destruct th_src0. eauto. }\n        { i. destruct th_src0. ss. eapply sim_thread_consistent; eauto.\n          { i. ss. eapply EXCLUSIVE in OTHER. des.\n            eapply unchangable_trace_steps_increase in STEPSRC; eauto.\n            eapply unchangable_increase in STEPSRC0; eauto. }\n          { i. ss. eapply EXCLUSIVEEXTRA in OTHER. des.\n            eapply unchangable_trace_steps_increase in STEPSRC; eauto.\n            eapply unchangable_increase in STEPSRC0; eauto. }\n        }\n        { eapply Forall_app.\n          { eapply sim_traces_pf; eauto. }\n          { econs; ss. eapply non_silent_pf in NEQ; eauto. }\n        }\n      }\n\n      destruct th_src0, th_mid0. ss. esplits.\n      { eauto. }\n      { ss.\n        { econs 1; eauto. }\n      }\n      { eapply sim_traces_trans; eauto.\n        replace [((Thread.local th_src1), e0)] with ([((Thread.local th_src1), e0)]++[]); auto. econs 2; auto.\n        { econs. }\n        { econs 2.\n          { eapply non_silent_pf; eauto. }\n          { econs. }\n          { refl. }\n          { dep_inv THREAD. inv LOCALJOIN. inv LOCALPF. eauto. }\n        }\n      }\n      { unguard. destruct (classic (e0 = ThreadEvent.failure)); subst; auto.\n        right. splits.\n        { eapply (sim_thread_sim_configuration true); eauto.\n          { etrans; eauto. }\n          { ss. eapply Memory.future_future_weak. etrans; eauto. }\n          { ss. eapply Memory.future_future_weak. etrans; eauto. }\n          { ss. eapply Memory.future_future_weak. etrans; eauto. }\n          { eapply JConfiguration.step_future; eauto. }\n          { ss. dup THREAD0. eauto. }\n          { eapply sim_thread_strong_sim_thread. eauto. }\n          { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n          { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n          { i. erewrite IdentMap.gsspec. des_ifs; eauto. }\n        }\n        { i. ss. des_ifs. }\n        { i. ss. des_ifs. }\n        { i. ss. des_ifs. }\n      }\n    }\n  Qed.\n\n\n  Lemma sim_configuration_no_promises_prom_extra_bot\n        tids views prom extra proml\n        c_src c_mid c_tgt tid lang st lc_tgt\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        (TIDTGT: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st, lc_tgt))\n        (PROMISE: (Local.promises lc_tgt) = Memory.bot)\n    :\n      (<<PROM: prom tid = bot2>>) /\\\n      (<<EXTRA: extra tid = bot3>>).\n  Proof.\n    inv SIM. ss. specialize (THSPF tid). specialize (THSJOIN tid).\n    unfold option_rel in *. des_ifs. inv THSPF. dep_inv THSJOIN. inv LOCAL. inv LOCAL0.\n    split.\n    { red. extensionality loc. extensionality ts.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n      set (CNT:=(sim_promise_contents PROMS) loc ts). inv CNT; ss.\n      specialize (PROMISES loc ts). rewrite <- H2 in *. inv PROMISES; ss.\n      erewrite Memory.bot_get in *. clarify. }\n    { red. extensionality loc. extensionality ts. extensionality from.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n      eapply (sim_promise_wf PROMS) in H. des.\n      set (CNT:=(sim_promise_contents PROMS) loc from). inv CNT; ss.\n      specialize (PROMISES loc from). rewrite <- H in *. inv PROMISES; ss.\n      erewrite Memory.bot_get in *. clarify. }\n  Qed.\n\n  Lemma sim_thread_forget\n        views prom_self prom_others extra_self extra_others\n        lang th_src th_mid th_tgt\n        (THREAD: @sim_thread\n                   views prom_self prom_others extra_self extra_others\n                   lang th_src th_mid th_tgt)\n        (LOCAL: Local.wf (Thread.local th_src) (Thread.memory th_src))\n        loc ts\n    :\n      prom_self loc ts <->\n      (<<MEMSRC: ~ concrete_promised (Thread.memory th_src) loc ts>>) /\\\n      (<<PROMTGT: concrete_promised (Local.promises (Thread.local th_tgt)) loc ts>>).\n  Proof.\n    dep_inv THREAD. inv LOCALPF. inv LOCALJOIN. split; i.\n    { split.\n      { set (CNT0:=(sim_memory_contents MEMPF) loc ts).\n        inv CNT0; ss; try by (exfalso; try apply NPROM; right; eauto).\n        ii. inv H0. rewrite GET in *. ss. }\n      { set (CNT0:=(sim_promise_contents PROMS) loc ts).\n        set (CNT1:=PROMISES loc ts).\n        inv CNT0; ss. rewrite <- H2 in *. inv CNT1. econs; eauto. }\n    }\n    { des. ss. inv PROMTGT.\n      set (CNT0:=(sim_promise_contents PROMS) loc ts).\n      set (CNT1:=PROMISES loc ts).\n      erewrite GET in *. inv CNT1.\n      rewrite <- H0 in *. inv CNT0; ss.\n      eapply LOCAL in H2. exfalso. eapply MEMSRC. econs; eauto.\n    }\n  Qed.\n\n  Lemma sim_configuration_certify_partial tids tid ploc pts pl0 pl1\n        views0 prom extra proml\n        c_src0 c_mid0 c_tgt0 tm\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (WF_SRC: Configuration.wf c_src0)\n        (PFSRC: PF.pf_configuration L c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n        (TIDS: tids tid)\n        (EQ: proml tid = pl0 ++ (ploc, pts) :: pl1)\n    :\n      exists tr_src tr_tgt tr_cert c_src1 c_mid1 c_tgt1\n             views1 e prom_self extra1 proml1 we,\n        (<<STEPSRC: PFConfiguration.opt_step_trace L tr_src e tid c_src0 c_src1>>) /\\\n        (<<STEPMID: JConfiguration.opt_step e tid c_mid0 c_mid1 views0 views1>>) /\\\n        (<<STEPTGT: @times_configuration_opt_step times tr_tgt tr_cert e tid c_tgt0 c_tgt1>>) /\\\n        (<<TRACE: sim_traces L tr_src tr_tgt>>) /\\\n        __guard__((e = MachineEvent.failure) \\/\n                  (e = MachineEvent.silent /\\\n                   (<<FUTURE: good_future tm (Configuration.memory c_tgt0) (Configuration.memory c_tgt1)>>) /\\\n                   (<<SC: (Configuration.sc c_tgt1) = (Configuration.sc c_tgt0)>>) /\\\n                   (<<SIM: sim_configuration\n                             tids views1\n                             (fun tid' => if (Ident.eq_dec tid' tid) then prom_self else (prom tid'))\n                             extra1\n                             proml1\n                             c_src1 c_mid1 c_tgt1>>) /\\\n                   (<<WRITE: PFRace.writing_event ploc pts we>>) /\\\n                   (<<FINAL: final_event_trace we tr_src>>) /\\\n                   (<<DECR: prom_self <2= prom tid>>) /\\\n                   (<<WRITTEN: forall loc ts (IN: List.In (loc, ts) (pl0 ++ [(ploc, pts)])),\n                       ~ prom_self loc ts>>) /\\\n                   (<<PROML: forall tid' (NEQ: tid <> tid'), proml1 tid' = proml tid'>>)))\n  .\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_tgt0)) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:TIDTGT.\n    { dup SIM. inv SIM. ss. hexploit CONSISTENT; eauto.\n      intros CONSISTENT0. exploit (pi_consistent_certify CONSISTENT0).\n      { refl. }\n      { eapply WF_TGT. }\n      { auto. }\n      { eapply WF_TGT; eauto. }\n      { erewrite EQ. eauto. }\n      instantiate (3:=TimeMap.join tm (fun loc => Time.incr (Memory.max_ts loc mem_tgt))).\n      i. des. ss.\n      assert (NOREAD: List.Forall\n                        (fun the => no_read_msgs\n                                      (all_promises (fun tid' => tid <> tid') prom)\n                                      (snd the)) ftr).\n      { eapply List.Forall_impl; eauto. i. ss. des. eapply no_read_msgs_mon; eauto.\n        i. ss.\n        hexploit sim_configuration_forget_src_not_concrete; eauto. i. ss.\n        ii. eapply H. des; auto. right. right. eapply TimeFacts.le_lt_lt; eauto. etrans.\n        { left. eapply Time.incr_spec. }\n        { eapply Time.join_r. }\n      }\n      destruct x1; des; cycle 1.\n      { destruct e1. ss.\n        assert (STEPTGT: @times_configuration_step\n                           times\n                           (ftr++[(local, ThreadEvent.failure)])\n                           []\n                           MachineEvent.failure\n                           tid\n                           (Configuration.mk ths_tgt sc_tgt mem_tgt)\n                           (Configuration.mk\n                              (IdentMap.add tid (existT _ lang_tgt st', local) ths_tgt)\n                              sc\n                              memory)).\n        { ss. replace MachineEvent.failure with\n                  (ThreadEvent.get_machine_event ThreadEvent.failure); auto.\n          econs; eauto; ss.\n          { eapply List.Forall_impl in EVENTS; eauto. i. ss. des. auto. }\n          { eapply Forall_app.\n            { eapply List.Forall_impl in EVENTS; eauto. i. ss. des. auto. }\n            { econs; ss. }\n          }\n        }\n        exploit (step_sim_configuration); eauto.\n        { eapply Forall_app.\n          { eapply List.Forall_impl in NOREAD; eauto. }\n          { econs; ss. }\n        }\n        i. des. esplits; eauto.\n        { econs 1. eauto. }\n        { left. ss. }\n        Unshelve.\n        { eapply (prom1 tid). }\n        { eapply extra1. }\n        { eapply proml1. }\n        { eapply ThreadEvent.failure. }\n      }\n      { destruct e1; ss.\n        assert (STEPTGT: @times_configuration_step\n                           times\n                           ftr\n                           ftr_cert\n                           MachineEvent.silent\n                           tid\n                           (Configuration.mk ths_tgt sc_tgt mem_tgt)\n                           (Configuration.mk\n                              (IdentMap.add tid (existT _ lang_tgt state, local) ths_tgt)\n                              sc\n                              memory)).\n        { hexploit (list_match_rev ftr). i. des; subst.\n          { exfalso. inv FINAL; ss. }\n          destruct hd_rev as [th e].\n          eapply Trace.steps_separate in STEPS. des.\n          inv STEPS1; ss; clarify. inv STEPS; clarify.\n          dup EVENTS. eapply Forall_app_inv in EVENTS. des.\n          replace MachineEvent.silent with (ThreadEvent.get_machine_event e0); cycle 1.\n          { inv FORALL2. ss. des. auto. }\n          econs; eauto.\n          { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n          { ii. exfalso. inv FORALL2. ss. des; clarify. }\n          { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n        }\n        exploit (step_sim_configuration); eauto.\n        { ss. eapply List.Forall_impl; eauto. i. ss. des; auto.\n          eapply no_read_msgs_mon; eauto.\n          i. ss.\n          hexploit sim_configuration_forget_src_not_concrete; eauto. i. ss.\n          ii. eapply H0. des; auto. right. right. eapply TimeFacts.le_lt_lt; eauto. etrans.\n          { left. eapply Time.incr_spec. }\n          { eapply Time.join_r. }\n        }\n        i. des.\n        exploit sim_traces_relaxed_writing_event; eauto. i. des.\n        eexists _, _, _, _, _, _, views1, _. esplits; eauto.\n        { econs 1. eauto. }\n        { unguard. des; ss. right. splits; auto.\n          { ss. eapply good_future_mon; eauto. eapply TimeMap.join_l. }\n          { instantiate (1:=extra1).\n            instantiate (1:=prom1 tid).\n            replace (fun tid' : Ident.t => if LocSet.Facts.eq_dec tid' tid then prom1 tid else prom tid')\n              with prom1; cycle 1.\n            { extensionality tid'. des_ifs; auto. }\n            eauto.\n          }\n          { eauto. }\n          { eauto. }\n          { exploit PFConfiguration.opt_step_trace_future; try apply STEPSRC; eauto. i. des.\n            exploit sim_configuration_sim_thread; try apply SIM0; eauto.\n            ss. i. des.\n            exploit sim_configuration_sim_thread; try apply SIM; eauto.\n            { ss. erewrite IdentMap.gss. ss. }\n            ss. i. des. eapply sim_thread_forget in PR; try apply SIM2; cycle 1.\n            { eapply WF2; eauto. }\n            ss. eapply sim_thread_forget; try apply SIM1.\n            { eapply WF_SRC; eauto. }\n            ss. des. split.\n            { ii. eapply MEMSRC. eapply memory_future_concrete_promised; eauto.\n              eapply Memory.future_future_weak; eauto. }\n            { inv PROMTGT. eapply SOUND in GET. des. econs; eauto. }\n          }\n          { exploit PFConfiguration.opt_step_trace_future; try apply STEPSRC; eauto. i. des.\n            exploit sim_configuration_sim_thread; try apply SIM; eauto.\n            { ss. erewrite IdentMap.gss. ss. }\n            ss. i. des. ii. eapply sim_thread_forget in H; try apply SIM1; cycle 1.\n            { eapply WF2; eauto. }\n            ss. des. eapply WRITTEN in IN. inv PROMTGT. clarify. }\n        }\n      }\n    }\n    { exfalso. dup SIM. inv SIM. ss. specialize (THSPF tid). specialize (THSJOIN tid).\n      rewrite TIDTGT in *. unfold option_rel in *. des_ifs.\n      specialize (BOT _ Heq0). des. rewrite PLS in *. destruct pl0; ss.\n    }\n  Qed.\n\n  Lemma sim_configuration_promises_forget_bot tids tid\n        views0 prom extra proml\n        c_src0 c_mid0 c_tgt0\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (TIDS: tids tid)\n        (PROMBOT: forall loc ts, ~ prom tid loc ts)\n    :\n      extra tid = bot3.\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_tgt0)) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:TIDTGT; cycle 1.\n    { dup SIM. inv SIM. exploit BOT.\n      { specialize (THSPF tid). specialize (THSJOIN tid). ss.\n        rewrite TIDTGT in *. unfold option_rel in *. des_ifs. eauto. }\n      i. des. esplits; eauto.\n      extensionality loc. extensionality ts. extensionality from.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality.\n      split; i; ss. eapply EXTRA; eauto.\n    }\n    { extensionality loc. extensionality ts. extensionality from.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n      inv SIM. specialize (THSPF tid). specialize (THSJOIN tid). ss.\n      rewrite TIDTGT in *. unfold option_rel in *. des_ifs. inv THSPF.\n      inv LOCAL. eapply PROMS in H. des. eapply PROMBOT in FORGET. ss. }\n  Qed.\n\n  Lemma sim_configuration_promises_list_nil tids tid\n        views0 prom extra proml\n        c_src0 c_mid0 c_tgt0\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (TIDS: tids tid)\n        (NIL: proml tid = [])\n    :\n      (<<PROM: prom tid = bot2>>) /\\\n      (<<EXTRA:extra tid = bot3>>).\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_tgt0)) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:TIDTGT; cycle 1.\n    { dup SIM. inv SIM. exploit BOT.\n      { specialize (THSPF tid). specialize (THSJOIN tid). ss.\n        rewrite TIDTGT in *. unfold option_rel in *. des_ifs. eauto. }\n      i. des. esplits; eauto.\n      { extensionality loc. extensionality ts.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality.\n        split; i; ss. eapply PROM; eauto. }\n      { extensionality loc. extensionality ts. extensionality from.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality.\n        split; i; ss. eapply EXTRA; eauto. }\n    }\n    { assert (PROM: prom tid = bot2).\n      { inv SIM. dup TIDTGT. eapply CONSISTENT in TIDTGT; eauto.\n        extensionality loc. extensionality ts.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n        eapply CONSISTENT in H; eauto. rewrite NIL in *. ss. }\n      splits; auto.\n      eapply sim_configuration_promises_forget_bot; eauto.\n      erewrite PROM. ss.\n    }\n  Qed.\n\n  Lemma sim_configuration_certify tids views0 prom extra proml\n        c_src0 c_mid0 c_tgt0 tid tm\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (WF_SRC: Configuration.wf c_src0)\n        (PFSRC: PF.pf_configuration L c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n        (TIDS: tids tid)\n    :\n      exists tr_src tr_tgt tr_cert c_src1 c_mid1 c_tgt1 views1 e extra1 proml1,\n        (<<STEPSRC: PFConfiguration.opt_step_trace L tr_src e tid c_src0 c_src1>>) /\\\n        (<<STEPMID: JConfiguration.opt_step e tid c_mid0 c_mid1 views0 views1>>) /\\\n        (<<STEPTGT: @times_configuration_opt_step times tr_tgt tr_cert e tid c_tgt0 c_tgt1>>) /\\\n        (<<TRACE: sim_traces L tr_src tr_tgt>>) /\\\n        __guard__((e = MachineEvent.failure) \\/\n                  (e = MachineEvent.silent /\\\n                   (<<FUTURE: good_future tm (Configuration.memory c_tgt0) (Configuration.memory c_tgt1)>>) /\\\n                   (<<SC: (Configuration.sc c_tgt1) = (Configuration.sc c_tgt0)>>) /\\\n                   (<<SIM: sim_configuration\n                             tids views1\n                             (fun tid' => if (Ident.eq_dec tid' tid) then bot2 else (prom tid'))\n                             extra1\n                             proml1\n                             c_src1 c_mid1 c_tgt1>>) /\\\n                   (<<PROML: forall tid' (NEQ: tid <> tid'), proml1 tid' = proml tid'>>)))\n  .\n  Proof.\n    hexploit (list_match_rev (proml tid)). i. des.\n    { esplits; eauto.\n      { econs 2; eauto. }\n      { econs 2; eauto. }\n      { econs; eauto. }\n      right. splits; auto.\n      { refl. }\n      hexploit sim_configuration_promises_list_nil; try apply H; eauto. i. des.\n      replace (fun tid' : Ident.t => if LocSet.Facts.eq_dec tid' tid then bot2 else prom tid')\n        with prom; cycle 1.\n      { extensionality tid'. des_ifs. }\n      eauto.\n    }\n    { destruct hd_rev as [ploc pts].\n      hexploit (@sim_configuration_certify_partial\n                  tids tid ploc pts tl_rev []); eauto.\n      i. des. unguard. des.\n      { esplits; eauto. }\n      destruct (IdentMap.find tid (Configuration.threads c_tgt0)) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:TIDTGT.\n      { assert (PROMBOT: prom_self = bot2).\n        { extensionality loc. extensionality ts.\n          apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n          exploit DECR; eauto. i.\n          inv SIM. hexploit CONSISTENT; eauto. i.\n          hexploit (pi_consistent_promises H0); eauto. i.\n          rewrite H in *. eapply WRITTEN; eauto. } subst.\n        esplits; eauto. right. splits; eauto.\n      }\n      { assert (PROMBOT: prom_self = bot2).\n        { inv STEPTGT; ss.\n          { dep_inv STEP; ss. }\n          { inv SIM0. specialize (THSPF tid). specialize (THSJOIN tid). ss.\n            rewrite TIDTGT in *. unfold option_rel in *. des_ifs.\n            eapply BOT in Heq0. des.\n            extensionality loc. extensionality ts.\n            apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n            eapply PROM. des_ifs; eauto.\n          }\n        }\n        subst. esplits; eauto.\n        right. splits; eauto.\n      }\n    }\n    Unshelve.\n    { eapply extra1. }\n    { eapply proml1. }\n  Qed.\n\n  Lemma sim_configuration_certify_list\n        (tidl: list Ident.t)\n        tids views0 prom extra proml\n        c_src0 c_mid0 c_tgt0 tm\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (WF_SRC: Configuration.wf c_src0)\n        (PFSRC: PF.pf_configuration L c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n        (ALL: List.Forall tids tidl)\n    :\n      exists trs c_src1 c_mid1 c_tgt1 views1 extra1 proml1,\n        (<<WF_SRC: Configuration.wf c_src1>>) /\\\n        (<<PFSRC: PF.pf_configuration L c_src1>>) /\\\n        (<<WF_MID: JConfiguration.wf views1 c_mid1>>) /\\\n        (<<WF_TGT: Configuration.wf c_tgt1>>) /\\\n        (<<STEPSRC: PFConfiguration.silent_steps_trace L c_src0 c_src1 trs>>) /\\\n        (<<THS: forall tid (TID: ~ List.In tid tidl),\n            IdentMap.find tid (Configuration.threads c_tgt0) =\n            IdentMap.find tid (Configuration.threads c_tgt1)>>) /\\\n        __guard__((<<FAIL: exists tid c_src2,\n                      (<<TID: List.In tid tidl>>) /\\\n                      (<<STEP: PFConfiguration.multi_step L MachineEvent.failure tid c_src1 c_src2>>)>>) \\/\n                  ((<<FUTURE: good_future tm (Configuration.memory c_tgt0) (Configuration.memory c_tgt1)>>) /\\\n                   (<<SC: (Configuration.sc c_tgt1) = (Configuration.sc c_tgt0)>>) /\\\n                   (<<SIM: sim_configuration\n                             tids views1\n                             (fun tid' => if (List.in_dec Ident.eq_dec tid' tidl) then bot2 else (prom tid'))\n                             extra1 proml1\n                             c_src1 c_mid1 c_tgt1>>) /\\\n                   (<<PROML: forall tid (TID: ~ List.In tid tidl),\n                       proml tid = proml1 tid>>)))\n  .\n  Proof.\n    Local Opaque List.in_dec.\n    ginduction tidl.\n    { i. eexists _, c_src0, c_mid0, c_tgt0, views0. esplits; auto.\n      { econs. }\n      right.\n      replace (fun tid':Ident.t => if (List.in_dec Ident.eq_dec tid' (@nil Ident.t)) then bot2 else (prom tid')) with prom; cycle 1.\n      { extensionality tid. des_ifs. }\n      splits; auto.\n      { refl. }\n      { eauto. }\n    }\n    { i. inv ALL. exploit sim_configuration_certify; eauto.\n      i. des. destruct x0; des; subst.\n      { subst. dep_inv STEPSRC.\n        eexists _, c_src0, c_mid0, c_tgt0, views0. esplits; auto.\n        { econs. }\n        left. esplits.\n        { ss. left. auto. }\n        { econs. esplits; eauto. }\n      }\n      exploit IHtidl; eauto.\n      { eapply PFConfiguration.opt_step_trace_future; eauto. }\n      { eapply PFConfiguration.opt_step_trace_future; eauto. }\n      { eapply JConfiguration.opt_step_future; eauto. }\n      { eapply times_configuration_opt_step_future; eauto. }\n      { i. des. dep_inv STEPSRC.\n        { eexists _, c_src2, c_mid2, c_tgt2, views2. esplits; eauto.\n          { econs 2; eauto. }\n          { i. erewrite <- THS; eauto. dep_inv STEPTGT.\n            dep_inv STEP0. erewrite IdentMap.gsspec. des_ifs.\n            exfalso. eapply TID; auto. }\n          unguard. des.\n          { left. esplits; eauto. }\n          { right. instantiate (1:=proml0). esplits; eauto.\n            { etrans; eauto. }\n            { etrans; eauto. }\n            { match goal with\n              | H:sim_configuration ?tids ?v ?f0 ?g0 ?h0 ?c0 ?c1 ?c2\n                |- sim_configuration tids ?v ?f1 ?g1 ?h1 ?c ?c1 ?c2 =>\n                (replace f1 with f0); eauto\n              end.\n              { extensionality tid. des_ifs; ss; des; exfalso; eauto. }\n            }\n            { i. apply not_or_and in TID. des. erewrite <- PROML; eauto. }\n          }\n        }\n        { eexists _, c_src2, c_mid2, c_tgt2, views2. esplits; auto.\n          { eauto. }\n          { i. erewrite <- THS; eauto. dep_inv STEPTGT.\n            dep_inv STEP. erewrite IdentMap.gsspec. des_ifs.\n            exfalso. eapply TID; auto. }\n          unguard. des.\n          { left. esplits; eauto. }\n          { right. instantiate (1:=proml0). esplits; auto.\n            { etrans; eauto. }\n            { etrans; eauto. }\n            { match goal with\n              | H:sim_configuration ?tids ?v ?f0 ?g0 ?h0 ?c0 ?c1 ?c2\n                |- sim_configuration ?tids ?v ?f1 ?g1 ?h1 ?c ?c1 ?c2 =>\n                (replace f1 with f0); eauto\n              end.\n              { extensionality tid. des_ifs; ss; des; exfalso; eauto. }\n            }\n            { i. apply not_or_and in TID. des. erewrite <- PROML; eauto. }\n          }\n        }\n      }\n    }\n    Unshelve.\n    { eapply extra1. }\n    { eapply proml1. }\n  Qed.\n\n  Lemma sim_configuration_certify_all\n        (ctids: Ident.t -> Prop) (ctids_dec: forall tid, { ctids tid } + { ~ ctids tid})\n        (tids: Ident.t -> Prop) views0 prom extra proml\n        (CTIDS: forall tid (CTID: ctids tid), tids tid)\n        c_src0 c_mid0 c_tgt0 tm\n        (SIM: sim_configuration tids views0 prom extra proml c_src0 c_mid0 c_tgt0)\n        (WF_SRC: Configuration.wf c_src0)\n        (PFSRC: PF.pf_configuration L c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n    :\n      exists trs c_src1 c_mid1 c_tgt1 views1 extra1 proml1,\n        (<<WF_SRC: Configuration.wf c_src1>>) /\\\n        (<<PFSRC: PF.pf_configuration L c_src1>>) /\\\n        (<<WF_MID: JConfiguration.wf views1 c_mid1>>) /\\\n        (<<WF_TGT: Configuration.wf c_tgt1>>) /\\\n        (<<STEPSRC: PFConfiguration.silent_steps_trace L c_src0 c_src1 trs>>) /\\\n        (<<THS: forall tid (TID: ~ ctids tid),\n            IdentMap.find tid (Configuration.threads c_tgt0) =\n            IdentMap.find tid (Configuration.threads c_tgt1)>>) /\\\n        __guard__((<<FAIL: exists tid c_src2,\n                      (<<TID: ctids tid>>) /\\\n                      (<<STEP: PFConfiguration.multi_step L MachineEvent.failure tid c_src1 c_src2>>)>>) \\/\n                  ((<<FUTURE: good_future tm (Configuration.memory c_tgt0) (Configuration.memory c_tgt1)>>) /\\\n                   (<<SC: (Configuration.sc c_tgt1) = (Configuration.sc c_tgt0)>>) /\\\n                   (<<SIM: sim_configuration\n                             tids\n                             views1\n                             (fun tid' => if (ctids_dec tid') then bot2 else (prom tid'))\n                             extra1 proml1\n                             c_src1 c_mid1 c_tgt1>>) /\\\n                    (<<PROML: forall tid (TID: ~ ctids tid),\n                       proml tid = proml1 tid>>))).\n  Proof.\n    hexploit (@sim_configuration_certify_list\n                (List.filter\n                   (fun tid => if ctids_dec tid then true else false)\n                   (List.map fst (IdentMap.elements (Configuration.threads c_src0))))); eauto.\n    { eapply List.Forall_forall. i.\n      eapply List.filter_In in H. des. des_ifs.\n      eapply List.in_map_iff in H; eauto. }\n    i. des. esplits; try apply STEPSRC; eauto.\n    { i. eapply THS. ii. eapply List.filter_In in H. des. des_ifs. }\n    unguard. des.\n    { left. esplits; eauto.\n      eapply List.filter_In in TID. des. des_ifs. }\n    { right. instantiate (1:=proml1). esplits; eauto.\n      { match goal with\n        | H:sim_configuration ?tids ?v ?f0 ?g0 ?h0 ?c0 ?c1 ?c2\n          |- sim_configuration ?tids ?v ?f1 ?g1 ?h1 ?c ?c1 ?c2 =>\n          (replace f1 with f0); eauto\n        end.\n        { extensionality tid. des_ifs.\n          { erewrite List.filter_In in i. des. des_ifs. }\n          { erewrite List.filter_In in n. apply not_and_or in n. des_ifs. des; ss.\n            extensionality loc. extensionality ts.\n            apply Coq.Logic.PropExtensionality.propositional_extensionality.\n            split; i; ss. eapply n.\n            eapply sim_configuration_forget_promise_exist in H; eauto. des.\n            eapply IdentMap.elements_correct in TID.\n            eapply List.in_map with (f:=fst) in TID. auto. }\n        }\n      }\n      { ii. eapply PROML. ii. eapply List.filter_In in H. des. des_ifs. }\n    }\n  Qed.\n\n  Lemma tevent_ident_map_weak f e fe\n        (MAP: tevent_map_weak f fe e)\n        (IDENT: forall loc to fto (MAP: f loc to fto), to = fto)\n    :\n      sim_event e fe.\n  Proof.\n    inv MAP; try econs; eauto.\n    { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. }\n    { eapply IDENT in TO. subst. econs; eauto. }\n    { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. }\n    { eapply IDENT in FROM. eapply IDENT in TO. subst. econs; eauto. }\n  Qed.\n\n  Lemma good_future_configuration_step_aux c0 c1 c0' e tid (tr0 tr_cert0: Trace.t) tm\n        lang st lc0 lc1 sc_tmp\n        (STEP: times_configuration_step times tr0 tr_cert0 e tid c0 c0')\n        (WF0: Configuration.wf c0)\n        (WF1: Configuration.wf c1)\n        (MWFTGT: memory_times_wf times (Configuration.memory c1))\n        (TID0: IdentMap.find tid (Configuration.threads c0) =\n               Some (existT _ lang st, lc0))\n        (TID1: IdentMap.find tid (Configuration.threads c1) =\n               Some (existT _ lang st, lc1))\n        (LOCAL: local_map\n                  (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                  lc0\n                  lc1)\n        (MEM: memory_map\n                (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                (Configuration.memory c0) (Configuration.memory c1))\n        (TM: forall loc, Time.lt (Memory.max_ts loc (Configuration.memory c0)) (tm loc))\n        (SCMAP: timemap_map\n                  (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                  (Configuration.sc c0) sc_tmp)\n        (SCLE: TimeMap.le (Configuration.sc c1) sc_tmp)\n        (TIME: List.Forall (fun the => wf_time_evt (fun loc ts => Time.lt ts (tm loc)) (snd the)) (tr0 ++ tr_cert0))\n    :\n      exists (tr1: Trace.t) tr_cert1 c1' f_good,\n        (<<STEP: times_configuration_step times tr1 tr_cert1 e tid c1 c1'>>) /\\\n        (<<TRACE: List.Forall2\n                    (fun the0 the1 =>\n                       (<<EVT: sim_event (snd the0) (snd the1)>>) /\\\n                       (<<TVIEW: TView.le (Local.tview (fst the1)) (Local.tview (fst the0))>>)) tr0 tr1>>) /\\\n        (<<TRACECERT: List.Forall2\n                    (fun the0 the1 =>\n                       (<<EVT: tevent_map_weak f_good (snd the1) (snd the0)>>)) tr_cert0 tr_cert1>>) /\\\n        (<<GOOD:\n           __guard__(exists st' lc0' lc1' sc_tmp',\n                        (<<TID0: IdentMap.find tid (Configuration.threads c0') =\n                                 Some (existT _ lang st', lc0')>>) /\\\n                        (<<TID1: IdentMap.find tid (Configuration.threads c1') =\n                                 Some (existT _ lang st', lc1')>>) /\\\n                        (<<LOCAL: local_map\n                                    (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                                    lc0'\n                                    lc1'>>) /\\\n                        (<<MEM: memory_map\n                                  (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                                  (Configuration.memory c0') (Configuration.memory c1')>>) /\\\n                        (<<SCMAP: timemap_map\n                                    (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                                    (Configuration.sc c0') sc_tmp'>>) /\\\n                        (<<SCLE: TimeMap.le (Configuration.sc c1') sc_tmp'>>))>>).\n  Proof.\n    dep_inv STEP. dep_clarify.\n    assert (IDENT:\n              map_ident_in_memory\n                (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))\n                (Configuration.memory c0)).\n    { ii. split; auto. eapply TimeFacts.le_lt_lt; eauto. }\n    assert (MAPLT: mapping_map_lt (fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))).\n    { ii. des. subst. auto. }\n    eapply wf_time_mapped_mappable in TIME; cycle 1.\n    { instantiate (1:=(fun loc ts fts => ts = fts /\\ Time.lt ts (tm loc))).\n      i. esplits; eauto. }\n    eapply Forall_app_inv in TIME. des.\n    eapply Forall_app_inv in FORALL1. des.\n    destruct e2. ss. hexploit trace_steps_map; try apply STEPS; 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 WF0; eauto. }\n    { eapply WF1; eauto. }\n    { eapply WF1. }\n    { eapply WF0. }\n    { eapply WF1. }\n    { eapply WF0. }\n    { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n    i. des.\n    hexploit Trace.steps_future; try apply STEPS; ss; eauto.\n    { eapply WF0; eauto. }\n    { eapply WF0. }\n    { eapply WF0. } i. des.\n    hexploit Trace.steps_future; try apply STEPS0; ss; eauto.\n    { eapply WF1; eauto. }\n    { eapply WF1. }\n    { eapply WF1. } i. des.\n    hexploit step_map; try apply MEM0; 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    { inv FORALL3. econs; eauto. econs. eauto. }\n    { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n    i. des. inv STEP. ss.\n    assert (EVENT: ThreadEvent.get_machine_event fe = ThreadEvent.get_machine_event e0).\n    { eapply tevent_map_same_machine_event; eauto. }\n    hexploit Thread.step_future; try apply STEP0; eauto. ss. i. des.\n    hexploit Thread.step_future; try apply STEP1; eauto. ss. i. des.\n\n    assert (CONSISTENT1:\n              exists tr_cert1 f_good,\n                (<<NORMAL:\n                   forall (NEQ: ThreadEvent.get_machine_event fe <> MachineEvent.failure),\n                     pf_consistent_super_strong\n                       (Thread.mk _ st3 flc0 fsc0 fmem0)\n                       tr_cert1 times>>) /\\\n                (<<SYSCALL: (exists se, ThreadEvent.get_machine_event fe = MachineEvent.syscall se) -> tr_cert1 = []>>) /\\\n                (<<FAILURE:\n                   forall (EQ: ThreadEvent.get_machine_event fe = MachineEvent.failure),\n                     tr_cert1 = []>>) /\\\n                (<<TRACECERT: List.Forall2\n                                (fun the0 the1 =>\n                                   (<<EVT: tevent_map_weak f_good (snd the1) (snd the0)>>)) tr_cert0 tr_cert1>>)).\n    { hexploit (@concrete_promise_max_timemap_exists memory3 (Local.promises lc3)); eauto.\n      { eapply CLOSED1. } intros [max MAX]. des.\n      destruct (classic (e0 = ThreadEvent.failure)).\n      { exists [], ident_map. splits; ss.\n        { ii. subst. ss. }\n        { exploit CERTBOT; eauto. i. subst. econs. }\n      }\n      { specialize (CONSISTENT H).\n        hexploit good_future_consistent; eauto.\n        { i. ss. des. auto. }\n        { eapply map_ident_in_memory_bot; eauto. }\n        { eapply Forall_app_inv in TIMES. des. inv FORALL4; ss.\n          eapply memory_times_wf_traced in STEPS0; eauto; cycle 1.\n          { eapply List.Forall_forall. i.\n            eapply list_Forall2_in in H0; eauto. des.\n            eapply List.Forall_forall in IN; try apply FORALL1; eauto. ss.\n            destruct a, x. ss. inv EVENT0; ss; des; subst; auto. }\n          { eapply step_memory_times_wf in STEP1; eauto.\n            inv EVT; ss; des; subst; auto. }\n        }\n        i. des. esplits; eauto.\n        { i. des. destruct fe; ss. destruct e0; ss. clarify.\n          exploit CERTBOT; eauto. i. subst. inv TRACE0. auto. }\n        { i. rewrite EQ in *. clarify. destruct e0; ss. }\n      }\n    } des.\n\n    eexists _, tr_cert1. esplits.\n    { erewrite <- EVENT. econs.\n      { erewrite TID1. eauto. }\n      { eauto. }\n      { eapply List.Forall_forall. i.\n        eapply list_Forall2_in in H; eauto. des.\n        destruct a, x. ss.\n        eapply List.Forall_forall in IN; try apply SILENT. ss. inv EVENT0; auto. }\n      { eauto. }\n      { ss. }\n      { i. eapply NORMAL. ii. destruct fe; ss. }\n      { i. subst. des; clarify; eauto. ss. eapply SYSCALL; eauto. }\n      { eapply list_Forall_app. splits.\n        { eapply List.Forall_forall. i.\n          eapply list_Forall2_in in H; eauto. des.\n          eapply wf_time_evt_map in EVENT0; cycle 1.\n          { eapply List.Forall_forall in TIMES; eauto.\n            eapply List.in_or_app. left. eauto. }\n          eapply wf_time_evt_mon; cycle 1; eauto.\n          i. ss. des. subst. auto. }\n        { econs; ss; eauto.\n          eapply wf_time_evt_map in EVT; cycle 1.\n          { eapply List.Forall_forall in TIMES; cycle 1.\n            { eapply List.in_or_app. right. econs. ss. }\n            { ss. eauto. }\n          }\n          { eapply wf_time_evt_mon; cycle 1; eauto.\n            i. ss. des. subst. auto. }\n        }\n      }\n    }\n    { eapply list_Forall2_app.\n      { eapply list_Forall2_impl; eauto. i. destruct a, b. ss. des. split; auto.\n        { eapply tevent_ident_map; eauto. i. ss. des; auto. }\n        { inv LOCAL2. eapply tview_ident_map in TVIEW; subst; eauto.\n          ii. ss. des. auto. }\n      }\n      { econs; ss; eauto. split; auto.\n        { eapply tevent_ident_map; eauto. i. ss. des; auto. }\n        { inv LOCAL0. eapply tview_ident_map in TVIEW; subst; eauto.\n          ii. ss. des. auto. }\n      }\n    }\n    { eauto. }\n    { unguard. exists st3, lc3, flc0, fsc1'0. splits; eauto.\n      { erewrite IdentMap.gss; eauto. }\n      { ss. erewrite IdentMap.gss; eauto. }\n    }\n  Qed.\n\n  Lemma configuration_step_certify c0 c1 e tid (tr tr_cert: Trace.t)\n        (WF: Configuration.wf c0)\n        (STEP: times_configuration_step_strong times tr tr_cert e tid c0 c1)\n    :\n      exists c2 tr_cert' f e',\n        (<<STEP: times_configuration_step times (tr ++ tr_cert') [] e' tid c0 c2>>) /\\\n        (<<MAPLT: mapping_map_lt f>>) /\\\n        (<<MAPIDENT:\n           forall loc ts fts to\n                  (CONCRETE: concrete_promised (Configuration.memory c1) loc to)\n                  (TS: Time.le ts to)\n                  (MAP: f loc ts fts),\n             ts = fts>>) /\\\n        __guard__((<<TRACE: List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) tr_cert tr_cert'>>) \\/\n                  (<<TRACE: exists lc, List.Forall2 (fun em fem => tevent_map_weak f (snd fem) (snd em)) (tr_cert++[(lc, ThreadEvent.failure)]) tr_cert'>>)) /\\\n        __guard__(e' = MachineEvent.failure \\/\n                  ((<<NEQ: e' <> MachineEvent.failure>>) /\\\n                   (<<BOT: forall lang st lc\n                                  (TID: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st, lc)),\n                       (Local.promises lc) = Memory.bot>>)))\n  .\n  Proof.\n    dup STEP. rename STEP0 into STEPWEAK.\n    eapply times_configuration_step_strong_step in STEPWEAK.\n    exploit times_configuration_step_future; eauto. i. des.\n    dup STEP. dep_inv STEP.\n    destruct (ThreadEvent.get_machine_event e0) eqn:EVENT.\n    { exploit (@concrete_promise_max_timemap_exists memory3 (Local.promises lc3)).\n      { eapply WF2. } i. des.\n      exploit CONSISTENT.\n      { ii. subst. ss. }\n      { refl. }\n      { eapply WF2. }\n      { eapply WF2; eauto. ss. erewrite IdentMap.gss; eauto. }\n      { eauto. }\n      i. des. ss. instantiate (1:=fun loc => Time.incr (Memory.max_ts loc memory3)) in GOOD.\n      destruct e1. ss. unguard. des.\n      { esplits.\n        { econs.\n          { eauto. }\n          { eapply Trace.steps_app.\n            { eapply STEPS. }\n            { econs 2.\n              { eauto. }\n              { eapply STEPS0. }\n              { ss. }\n            }\n          }\n          { eapply Forall_app; eauto. econs; eauto.\n            eapply List.Forall_impl; eauto. i. ss. des. auto. }\n          { econs 2. econs; cycle 1.\n            { eapply Local.step_failure; eauto. }\n            { eauto. }\n          }\n          { repeat erewrite <- List.app_assoc. ss. }\n          { i. ss. }\n          { i. ss. }\n          { eapply Forall_app; eauto.\n            eapply Forall_app; eauto.\n            { eapply List.Forall_impl; eauto. i. ss. des; auto. }\n            { econs; ss; eauto. }\n          }\n        }\n        { eauto. }\n        { ii. destruct (Time.le_lt_dec fts (tm loc)).\n          { eapply MAPIDENT; eauto. }\n          { dup l. eapply BOUND in l; eauto. des.\n            inv CONCRETE. eapply MAX in GET.\n            exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply l. } etrans.\n            { eapply TS. }\n            eauto.\n          }\n        }\n        { right. exists local. esplits. eapply List.Forall2_app; eauto.\n          econs; eauto. ss. econs. }\n        { left. auto. }\n      }\n      { hexploit (list_match_rev ftr). i. des; subst.\n        { inv TRACE. inv STEPS0; ss.\n          eexists _, [], ident_map, MachineEvent.silent.\n          erewrite List.app_nil_r. splits; eauto.\n          { eapply ident_map_lt. }\n          right. splits; ss.\n          i. erewrite IdentMap.gss in TID0. dep_clarify.\n        }\n        { eapply Trace.steps_separate in STEPS0. des.\n          inv STEPS2; ss. inv TR. inv STEPS0; ss.\n          eapply Forall_app_inv in TIMES.\n          eapply Forall_app_inv in EVENTS. des. inv FORALL2. ss. des.\n          esplits.\n          { econs.\n            { eauto. }\n            { eapply Trace.steps_app.\n              { eapply STEPS. }\n              { econs 2.\n                { eauto. }\n                { eapply STEPS1. }\n                { ss. }\n              }\n            }\n            { eapply Forall_app; eauto. econs; eauto.\n              eapply List.Forall_impl; eauto. i. ss. des. auto. }\n            { eauto. }\n            { repeat erewrite <- List.app_assoc. ss. }\n            { i. ss. eapply promises_bot_certify_nil; eauto. }\n            { i. subst. ss. }\n            { eapply Forall_app; eauto.\n              { eapply Forall_app; eauto. }\n              { eapply Forall_app; eauto.\n                eapply List.Forall_impl; eauto. i. ss. des; auto. }\n            }\n          }\n          { eauto. }\n          { ii. destruct (Time.le_lt_dec fts (tm loc)).\n            { eapply MAPIDENT; eauto. }\n            { dup l. eapply BOUND in l; eauto. des.\n              inv CONCRETE. eapply MAX in GET.\n              exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n              { eapply l. } etrans.\n              { eapply TS. }\n              eauto.\n            }\n          }\n          { ii. auto. }\n          { right. splits; auto.\n            { ii. erewrite H in *. ss. }\n            { i. ss. erewrite IdentMap.gss in TID0. dep_clarify. }\n          }\n        }\n      }\n    }\n    { assert (BOT: Local.promises lc3 = Memory.bot).\n      { destruct e0; ss. inv STEP1; inv STEP; ss. inv LOCAL.\n        inv LOCAL0; ss. eauto. }\n      hexploit CERTBOTNIL; auto. i. subst.\n      eexists _, [], ident_map. erewrite List.app_nil_r. esplits; eauto.\n      { eapply ident_map_lt. }\n      { left. auto. }\n      { right. splits; ss.\n        i. ss. erewrite IdentMap.gss in TID0. dep_clarify. }\n    }\n    { hexploit CERTBOT.\n      { destruct e0; ss. auto. } i. subst.\n      eexists _, [], ident_map. erewrite List.app_nil_r. esplits; eauto.\n      { eapply ident_map_lt. }\n      { left. auto. }\n      { left. auto. }\n    }\n  Qed.\n\n  Lemma list_final_exists A (P: A -> Prop) (l: list A)\n    :\n      (<<ALL: List.Forall P l>>) \\/\n      (exists l0 a l1,\n          (<<EQ: l = l0 ++ a :: l1>>) /\\\n          (<<SAT: ~ P a>>) /\\\n          (<<TL: List.Forall P l1>>)).\n  Proof.\n    induction l.\n    { left. econs. }\n    { des.\n      { destruct (classic (P a)).\n        { left. econs; eauto. }\n        { right. exists [], a, l. splits; auto. }\n      }\n      { subst. right. exists (a :: l0), a0, l1. splits; auto. }\n    }\n  Qed.\n\n  Lemma sim_configuration_forget_tgt_concrete\n        tids views prom extra proml c_src c_mid c_tgt\n        (SIM: sim_configuration tids views prom extra proml c_src c_mid c_tgt)\n        tid loc ts\n        (PROM: prom tid loc ts)\n        (TID: tids tid)\n        (WF: Configuration.wf c_tgt)\n    :\n      (<<CONCRETE: concrete_promised (Configuration.memory c_tgt) loc ts>>)\n      /\\ (<<LOC: L loc>>).\n  Proof.\n    inv SIM. specialize (THSJOIN tid). specialize (THSPF tid).\n    unfold option_rel in THSJOIN. unfold option_rel in THSPF. des_ifs.\n    { dep_inv THSPF. dep_inv THSJOIN. dep_inv LOCAL. dep_inv LOCAL0.\n      set (CNT0:=(sim_promise_contents PROMS) loc ts).\n      set (CNT1:=PROMISES loc ts).\n      inv CNT0; ss. rewrite <- H in *. inv CNT1; ss.\n      inv WF. ss. eapply WF0 in Heq0.\n      symmetry in H5. eapply Heq0 in H5. splits; auto. econs; eauto.\n    }\n    { eapply BOT in Heq1. des. exfalso. eapply PROM0; eauto. }\n  Qed.\n\n  Lemma promise_read_race views0 prom0 extra0 proml0\n        c_src0 c_mid0 c_tgt0 c_tgt1 e tid tr_tgt tr_cert\n        (STEPTGT: @times_configuration_step_strong times tr_tgt tr_cert e tid c_tgt0 c_tgt1)\n        (SIM: sim_configuration (fun _ => True) views0 prom0 extra0 proml0 c_src0 c_mid0 c_tgt0)\n        (READ: ~ List.Forall\n                 (fun the => no_read_msgs\n                               (all_promises (fun tid' => tid <> tid') prom0)\n                               (snd the)) (tr_tgt ++ tr_cert))\n        (WF_SRC: Configuration.wf c_src0)\n        (PFSRC: PF.pf_configuration L c_src0)\n        (WF_MID: JConfiguration.wf views0 c_mid0)\n        (WF_TGT: Configuration.wf c_tgt0)\n        (RACEFREE: PFRace.multi_racefree L c_src0)\n    :\n      (<<BEH: forall beh, behaviors (PFConfiguration.multi_step L) c_src0 beh>>) \\/\n      (exists s, (<<EVENT: e = MachineEvent.syscall s>>) /\\\n                 (<<BEH: forall beh,\n                     behaviors (PFConfiguration.multi_step L) c_src0 (s :: beh)>>)).\n  Proof.\n    exploit times_configuration_step_future; eauto.\n    { eapply times_configuration_step_strong_step; eauto. } i. des.\n    exploit (@Memory.max_concrete_timemap_exists (Configuration.memory c_tgt1)); eauto.\n    { eapply WF2. } intros [max MAX].\n    eapply configuration_step_certify in STEPTGT; eauto. des.\n    hexploit (@trace_times_list_exists (tr_tgt ++ tr_cert')). i. des.\n    assert (exists (maxmap: TimeMap.t),\n               (<<TIMES: forall loc' ts (IN: List.In ts (times0 loc')), Time.lt ts (maxmap loc')>>) /\\\n               (<<MAX: forall loc', Time.lt (Memory.max_ts loc' (Configuration.memory c_tgt0)) (maxmap loc')>>)).\n    { hexploit (@choice\n                  Loc.t\n                  Time.t\n                  (fun loc' max =>\n                     (<<TIMES: forall ts (IN: List.In ts (times0 loc')), Time.lt ts (max)>>) /\\\n                     (<<MAX: Time.lt (Memory.max_ts loc' (Configuration.memory c_tgt0)) (max)>>))).\n      { i. hexploit (finite_greatest (fun _ => True) (times0 x)). i. des.\n        { exists (Time.incr (Time.join\n                               (Memory.max_ts x (Configuration.memory c_tgt0))\n                               to)).\n          splits.\n          { i. eapply GREATEST in IN0; 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          { eapply TimeFacts.le_lt_lt.\n            { eapply Time.join_l. }\n            { eapply  Time.incr_spec. }\n          }\n        }\n        { exists (Time.incr (Memory.max_ts x (Configuration.memory c_tgt0))). splits.\n          { i. eapply EMPTY in IN. ss. }\n          { eapply Time.incr_spec. }\n        }\n      }\n      i. des. exists f0. split.\n      { ii. specialize (H loc'). des. auto. }\n      { ii. specialize (H loc'). des. auto. }\n    } i. des.\n    assert (exists tid0 ploc pts rlc re pl0 pl1,\n               (<<READING: PFRace.reading_event ploc pts re>>) /\\\n               (<<IN: List.In (rlc, re) (tr_tgt ++ tr_cert')>>) /\\\n               (<<PROMISED: prom0 tid0 ploc pts>>) /\\\n               (<<NEQ: tid0 <> tid>>) /\\\n               (<<PROML: proml0 tid0 = pl0 ++ (ploc, pts) :: pl1>>) /\\\n               (<<NOREAD:\n                  List.Forall\n                    (fun the =>\n                       no_read_msgs (fun loc ts => List.In (loc, ts) pl1 /\\ prom0 tid0 loc ts) (snd the)) (tr_tgt ++ tr_cert')>>)).\n    { assert (exists tid0 loc ts rlc0 re0,\n                 (<<READING0: PFRace.reading_event loc ts re0>>) /\\\n                 (<<IN0: List.In (rlc0, re0) (tr_tgt ++ tr_cert)>>) /\\\n                 (<<PROMISED: prom0 tid0 loc ts>>) /\\\n                 (<<NEQ: tid0 <> tid>>)).\n      { apply NNPP. ii. eapply READ. eapply List.Forall_forall. i.\n        eapply NNPP. ii. eapply H. unfold no_read_msgs in *. des_ifs.\n        { apply NNPP in H1. inv H1. destruct x. ss. subst.\n          esplits; eauto. econs; eauto. }\n        { apply NNPP in H1. inv H1. destruct x. ss. subst.\n          esplits; eauto. econs; eauto. }\n      } des.\n      assert (CONCRETE: concrete_promised (Configuration.memory c_tgt1) loc ts).\n      { eapply memory_future_concrete_promised.\n        { eapply Memory.future_future_weak; eauto. }\n        eapply sim_configuration_forget_tgt_concrete; eauto; ss.\n      }\n      assert (exists rlc re,\n                 (<<READING0: PFRace.reading_event loc ts re>>) /\\\n                 (<<IN0: List.In (rlc, re) (tr_tgt ++ tr_cert')>>)).\n      { eapply List.in_app_or in IN0. des.\n        { esplits; eauto. eapply List.in_or_app. eauto. }\n        { destruct STEPTGT0.\n          { des. eapply list_Forall2_in2 in IN0; eauto. des. ss.\n            destruct b. exists t, t0. ss. splits.\n            { inv READING0; inv SAT; eauto.\n              { eapply MAPIDENT in TO; eauto.\n                { subst. econs; eauto. }\n                { refl. }\n              }\n              { eapply MAPIDENT in FROM; eauto.\n                { subst. econs; eauto. }\n                { refl. }\n              }\n            }\n            { eapply List.in_or_app; eauto. }\n          }\n          { des. exploit list_Forall2_in2.\n            { eapply H. }\n            { eapply List.in_or_app. eauto. }\n            i. des. ss.\n            destruct b. exists t, t0. ss. splits.\n            { inv READING0; inv SAT; eauto.\n              { eapply MAPIDENT in TO; eauto.\n                { subst. econs; eauto. }\n                { refl. }\n              }\n              { eapply MAPIDENT in FROM; eauto.\n                { subst. econs; eauto. }\n                { refl. }\n              }\n            }\n            { eapply List.in_or_app; eauto. }\n          }\n        }\n      }\n      des.\n      assert (LIN: List.In (loc, ts) (proml0 tid0)).\n      { destruct (IdentMap.find tid0 (Configuration.threads c_tgt0)) as [[[lang_tgt st_tgt] lc_tgt]|] eqn:TIDTGT.\n        { inv SIM. eapply CONSISTENT in TIDTGT; eauto.\n          eapply (pi_consistent_promises TIDTGT) in PROMISED. auto. }\n        { inv SIM. ss. specialize (THSJOIN tid0). specialize (THSPF tid0).\n          unfold option_rel in THSJOIN.\n          unfold option_rel in THSPF. des_ifs.\n          eapply BOT in Heq1. des. exfalso. eapply PROM; eauto. }\n      }\n      hexploit (list_final_exists\n                  (fun locts =>\n                     ~ prom0 tid0 (fst locts) (snd locts) \\/\n                     List.Forall (fun the =>\n                                    no_read_msgs (fun loc0 ts0 => (loc0, ts0) = locts /\\ prom0 tid0 loc0 ts0) (snd the)) (tr_tgt ++ tr_cert'))\n                  (proml0 tid0)).\n      i. des.\n      { exfalso. eapply List.Forall_forall in ALL; eauto. des; ss.\n        eapply List.Forall_forall in ALL; eauto. ss.\n        unfold no_read_msgs in ALL. inv READING1; ss.\n        { eapply ALL. splits; auto. }\n        { eapply ALL. splits; auto. }\n      }\n      { apply not_or_and in SAT. des. apply NNPP in SAT. destruct a. ss.\n        assert (exists rlc' re',\n                   (<<READING: PFRace.reading_event t t0 re'>>) /\\\n                   (<<IN: List.In (rlc', re') (tr_tgt ++ tr_cert')>>)).\n        { apply NNPP. ii. eapply SAT0. eapply List.Forall_forall.\n          i. destruct x. ss. unfold no_read_msgs. des_ifs.\n          { ii. des; clarify. eapply H. esplits; eauto. econs; eauto. }\n          { ii. des; clarify. eapply H. esplits; eauto. econs; eauto. }\n        }\n        des. esplits; eauto. apply List.Forall_forall. i.\n        destruct x. ss. unfold no_read_msgs. des_ifs.\n        { ii. des. eapply List.Forall_forall in H0; eauto. ss. des; ss.\n          eapply List.Forall_forall in H0; eauto. ss. eapply H0; eauto. }\n        { ii. des. eapply List.Forall_forall in H0; eauto. ss. des; ss.\n          eapply List.Forall_forall in H0; eauto. ss. eapply H0; eauto. }\n      }\n    }\n    des.\n\n    exploit sim_configuration_forget_tgt_concrete.\n    { eapply SIM. }\n    { eapply PROMISED. }\n    { ss. }\n    { auto. }\n    i. des.\n\n    assert (DEC: forall (tid'': Ident.t), { (fun tid' => tid <> tid' /\\ tid0 <> tid') tid'' } + { ~ (fun tid' => tid <> tid' /\\ tid0 <> tid') tid''}).\n    { i. destruct (Ident.eq_dec tid tid''), (Ident.eq_dec tid0 tid''); subst; ss.\n      { right. ii. des; ss. }\n      { right. ii. des; ss. }\n      { left. split; auto. }\n    }\n\n    exploit (@sim_configuration_certify_all _ DEC); eauto; ss.\n    i. des. destruct x0; des.\n    { left. ii. eapply PFConfiguration.silent_multi_steps_trace_behaviors; eauto.\n      econs 3; eauto. }\n\n    exploit (@sim_configuration_certify_partial\n               (fun _ => True) tid0 ploc pts pl0 pl1); eauto.\n    { erewrite <- PROML0; eauto. ii. des; ss. }\n    i. des. destruct x0; des.\n    { left. ii. eapply PFConfiguration.silent_multi_steps_trace_behaviors; eauto.\n      inv STEPSRC0; ss. econs 3; eauto. econs; eauto. }\n\n    hexploit times_configuration_opt_step_future; try apply STEPTGT; eauto. i. des.\n    hexploit JConfiguration.opt_step_future; try apply STEPMID; eauto. i. des.\n    hexploit PFConfiguration.opt_step_trace_future; try apply STEPSRC0; eauto. i. des.\n\n    assert (IDENT: map_ident_in_memory (fun loc ts fts => ts = fts /\\ Time.lt ts (maxmap loc))\n                                       (Configuration.memory c_tgt0)).\n    { ii. splits; auto. eapply TimeFacts.le_lt_lt; eauto. }\n    assert (MAPLT0: mapping_map_lt (fun loc ts fts => ts = fts /\\ Time.lt ts (maxmap loc))).\n    { ii. des. subst. auto. }\n\n    dup STEP. dep_inv STEP.\n    exploit good_future_configuration_step_aux.\n    { eapply STEP0. }\n    { eauto. }\n    { eapply WF0. }\n    { inv SIM1. auto. }\n    { eauto. }\n    { erewrite <- TID. erewrite THS; eauto.\n      { inv STEPTGT; auto. inv STEP; auto.\n        ss. erewrite IdentMap.gso; eauto. }\n      { ii. des; ss. }\n    }\n    { eapply map_ident_in_memory_local; eauto.\n      { eapply WF_TGT; eauto. }\n      { eapply WF_TGT; eauto. }\n    }\n    { eapply max_good_future_map; eauto. etrans; eauto. eapply WF_TGT. }\n    { eauto. }\n    { eapply map_ident_in_memory_closed_timemap; eauto. eapply WF_TGT. }\n    { erewrite SC0. erewrite SC. refl. }\n    { erewrite app_nil_r.\n      eapply List.Forall_impl; try apply WFTIME; eauto. i. ss.\n      eapply wf_time_evt_mon; eauto. i. ss. eauto. }\n    i. des. ss.\n\n    exploit (@step_sim_configuration); eauto.\n    { eapply List.Forall_forall. i.\n      eapply list_Forall2_in in H; eauto. des.\n      eapply List.Forall_forall in NOREAD; eauto.\n      destruct x, a. ss.\n      assert (NOREAD0: no_read_msgs\n                         (fun loc ts => In (loc, ts) pl1 /\\ prom0 tid0 loc ts) t0).\n      { inv EVT; ss. }\n      eapply no_read_msgs_mon; eauto. i. ss. inv PR.\n      clear - SIM DECR WRITTEN TID0 PROMS NEQ TID PROML. des_ifs; ss.\n      { eapply DECR in PROMS. ss. }\n      { split; auto. dup PROMS. eapply DECR in PROMS.\n        destruct (IdentMap.find tid0 (Configuration.threads c_tgt0)) as [[[lang_tgt' st_tgt'] lc_tgt']|] eqn:TIDTGT.\n        { dep_inv SIM. eapply CONSISTENT in TIDTGT; ss.\n          eapply (pi_consistent_promises TIDTGT) in PROMS.\n          rewrite PROML in *.\n          clear - PROMS WRITTEN PROMS0.\n          eapply List.in_app_or in PROMS. des; ss.\n          { exfalso. eapply WRITTEN; eauto. eapply List.in_or_app. eauto. }\n          { des; ss. exfalso. eapply WRITTEN; eauto. eapply List.in_or_app.\n            ss. eauto. }\n        }\n        { inv SIM. specialize (THSJOIN tid0). specialize (THSPF tid0).\n          setoid_rewrite TIDTGT in THSJOIN. unfold option_rel in *. des_ifs.\n          eapply BOT in Heq0. des. exfalso. eapply PROM; eauto. }\n      }\n      { apply not_and_or in n0. des; ss. }\n      { apply not_and_or in n0. des; ss. exfalso. eapply n0. eauto. }\n    }\n    { ss. inv TRACECERT. ss. }\n    i. des. ss.\n\n    assert (exists rlc' re',\n               (<<IN: In (rlc', re') (tr_src0)>>) /\\\n               (<<READING: PFRace.reading_event ploc pts re'>>)).\n    { eapply list_Forall2_in2 in IN; eauto. des. ss.\n      destruct b. ss. exploit sim_traces_sim_event_exists; eauto.\n      { inv READING; inv EVT; ss. }\n      { inv READING; inv EVT; ss. }\n      i. des. esplits; eauto.\n      clear - READING EVT EVENT.\n      inv READING; inv EVT; inv EVENT; ss; econs. }\n    des.\n\n    exfalso. eapply RACEFREE.\n    { eapply PFConfiguration.silent_steps_trace_steps_trace; eauto. }\n    { eauto. }\n    { eapply NEQ. }\n    { inv STEPSRC0; eauto. inv FINAL. }\n    { eauto. }\n    { eauto. }\n    { inv STEPSRC1; eauto. ss. }\n    { eauto. }\n    { eauto. }\n  Qed.\n\nEnd SIM.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfpf/LocalPFSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.1833231583115002}}
{"text": "From Perennial.program_logic Require Export language.\n\nSection ctx.\nContext {\u039b: language}.\n\nInstance id_ctx : LanguageCtx (\u039b := \u039b) (fun x => x).\nProof.\n  split; intuition eauto.\n  rewrite to_of_val; eauto.\nQed.\n\nInstance comp_ctx K K':\n  LanguageCtx (\u039b := \u039b) K \u2192\n  LanguageCtx (\u039b := \u039b) K' \u2192\n  LanguageCtx (\u039b := \u039b) (\u03bb x, K' (K x)).\nProof.\n  intros Hctx Hctx'.\n  split; intros.\n  - by do 2 apply fill_not_val.\n  - destruct (to_val (K (of_val v))) as [Kv|] eqn:Heq; last first.\n    { apply (@fill_not_val _ K' _ _) in Heq.\n      eapply eq_None_not_Some in Heq; intuition. }\n    assert (is_Some (to_val (K (of_val v')))) as Hsome'.\n    { eapply fill_val_inv; eauto. }\n    destruct Hsome' as (Kv'&Heq').\n    apply of_to_val in Heq.\n    match goal with\n    | [ H: context[ K (of_val v)] |- _ ] => rewrite -Heq in H\n    end.\n    apply of_to_val in Heq'.\n    rewrite -Heq'.\n    eapply fill_val_inv. eauto.\n  - by do 2 apply fill_step.\n  - edestruct (@fill_step_inv _ _ Hctx' (K e1')); eauto; intuition.\n    { apply fill_not_val; auto. }\n    subst.\n    edestruct (@fill_step_inv _ _ Hctx); eauto; intuition.\n    subst.\n    eauto.\nQed.\n\nEnd ctx.\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/language_ctx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.1829763389359238}}
{"text": "From Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics Seqs.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBExport.\nFrom BitBlasting Require Import AdhereConform.\nFrom BBCache Require Import BitBlastingInit.\nFrom BBCache Require Import BitBlastingCCacheExport BitBlastingCacheExport.\nFrom BBCache Require Import CacheFlatten BitBlastingCCacheFlatten BitBlastingCacheFlatten.\nFrom BBCache Require Import CacheHash QFBVHash BitBlastingCCacheHash.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(* ==== bit_blast_exp_hcache and bit_blast_bexp_hcache ==== *)\n\nFixpoint bit_blast_exp_hcache E m c g (e : hexp) : vm * cache * generator * seq cnf * word :=\n  (* = bit_blast_exp_nocet = *)\n  let bit_blast_exp_nocet E m c g (e : hexp) : vm * cache * generator * seq cnf * word :=\n      match e with\n      | epair (HEvar v) _ =>\n        match find_het e c with\n        | Some (cs, ls) => (m, c, g, cs, ls)\n        | None => match SSAVM.find v m with\n                  | None => let '(g', cs, rs) := bit_blast_var E g v in\n                            (SSAVM.add v rs m, add_het e [:: cs] rs c, g', [:: cs], rs)\n                  | Some rs => (m, add_het e [::] rs c, g, [::], rs)\n                  end\n        end\n      | epair (HEconst bs) _ =>\n        match find_het e c with\n        | Some (cs, ls) => (m, c, g, cs, ls)\n        | None => let '(g', cs, rs) := bit_blast_const g bs in\n                  (m, add_het e [:: cs] rs c, g', [:: cs], rs)\n        end\n      | epair (HEunop op e1) _ =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_hcache E m c g e1 in\n        match find_het e c1 with\n        | Some (csop, lsop) => (m1, c1, g1, catrev cs1 csop, lsop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_eunop op g1 ls1 in\n          (m1, add_het e [:: csop] lsop c1, gop,\n           catrev cs1 [:: csop], lsop)\n        end\n      | epair (HEbinop op e1 e2) _ =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_hcache E m c g e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_hcache E m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lsop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_ebinop op g2 ls1 ls2 in\n          (m2, add_het e [:: csop] lsop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lsop)\n        end\n      | epair (HEite b e1 e2) _ =>\n        let '(mb, cb, gb, csb, lb) := bit_blast_bexp_hcache E m c g b in\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_hcache E mb cb gb e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_hcache E m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) =>\n          (m2, c2, g2, catrev csb (catrev cs1 (catrev cs2 csop)), lsop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_ite g2 lb ls1 ls2 in\n          (m2, add_het e [:: csop] lsop c2, gop,\n           catrev csb (catrev cs1 (catrev cs2 [:: csop])), lsop)\n        end\n      end\n  (* = = *)\n  in\n  match find_cet e c with\n  | Some ls => (m, c, g, [::], ls)\n  | None => let '(m', c', g', cs, lrs) := bit_blast_exp_nocet E m c g e in\n            (m', add_cet e lrs c', g', cs, lrs)\n  end\nwith\nbit_blast_bexp_hcache E m c g (e : hbexp) : vm * cache * generator * seq cnf * literal :=\n  (* = bit_blast_bexp_nocbt = *)\n  let bit_blast_bexp_nocbt E m c g (e : hbexp) : vm * cache * generator * seq cnf * literal :=\n      match e with\n      | bpair HBfalse _ =>\n        match find_hbt e c with\n        | Some (cs, l) => (m, c, g, cs, l)\n        | None => (m, add_hbt e [::] lit_ff c, g, [::], lit_ff)\n        end\n      | bpair HBtrue _ =>\n        match find_hbt e c with\n        | Some (cs, l) => (m, c, g, cs, l)\n        | None => (m, add_hbt e [::] lit_tt c, g, [::], lit_tt)\n        end\n      | bpair (HBbinop op e1 e2) _ =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_hcache E m c g e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_hcache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop)\n        | None =>\n          let '(gop, csop, lop) := bit_blast_bbinop op g2 ls1 ls2 in\n          (m2, add_hbt e [:: csop] lop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lop)\n        end\n      | bpair (HBlneg e1) _ =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_hcache E m c g e1 in\n        match find_hbt e c1 with\n        | Some (csop, lop) => (m1, c1, g1, catrev cs1 csop, lop)\n        | None => let '(gop, csop, lop) := bit_blast_lneg g1 l1 in\n                  (m1, add_hbt e [:: csop] lop c1, gop,\n                   catrev cs1 [:: csop], lop)\n        end\n      | bpair (HBconj e1 e2) _ =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_hcache E m c g e1 in\n        let '(m2, c2, g2, cs2, l2) := bit_blast_bexp_hcache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop)\n        | None => let '(gop, csop, lop) := bit_blast_conj g2 l1 l2 in\n                  (m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop)\n        end\n      | bpair (HBdisj e1 e2) _ =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_hcache E m c g e1 in\n        let '(m2, c2, g2, cs2, l2) := bit_blast_bexp_hcache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop)\n        | None => let '(gop, csop, lop) := bit_blast_disj g2 l1 l2 in\n                  (m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop)\n        end\n      end\n  (* = = *)\n  in\n  match find_cbt e c with\n  | Some l => (m, c, g, [::], l)\n  | None => let '(m', c', g', cs, lr) := bit_blast_bexp_nocbt E m c g e in\n            (m', add_cbt e lr c', g', cs, lr)\n  end.\n\n\n(* ==== relation between bit_blast_exp_hcache and bit_blast_exp_fcache ==== *)\n\nSection WellFormedCache.\n\n  Import QFBV.\n\n  Definition well_formed_cache (hc : CacheHash.cache) : Prop :=\n    well_formed_st (CacheHash.ct hc) /\\ well_formed_ct (CacheHash.ht hc).\n\n  Lemma well_formed_cache_find_cet hc e r :\n    well_formed_cache hc -> CacheHash.find_cet e hc = Some r ->\n    well_formed_hexp e.\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hf. exact: (H1 _ _ Hf).\n  Qed.\n\n  Lemma well_formed_cache_find_cbt hc e r :\n    well_formed_cache hc -> CacheHash.find_cbt e hc = Some r ->\n    well_formed_hbexp e.\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hf. exact: (H2 _ _ Hf).\n  Qed.\n\n  Lemma well_formed_cache_find_het hc e r :\n    well_formed_cache hc -> CacheHash.find_het e hc = Some r ->\n    well_formed_hexp e.\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hf. exact: (H3 _ _ Hf).\n  Qed.\n\n  Lemma well_formed_cache_find_hbt hc e r :\n    well_formed_cache hc -> CacheHash.find_hbt e hc = Some r ->\n    well_formed_hbexp e.\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hf. exact: (H4 _ _ Hf).\n  Qed.\n\n  Lemma well_formed_cache_add_cet hc (e : hexp) ls :\n    well_formed_cache hc -> well_formed_hexp e ->\n    well_formed_cache (CacheHash.add_cet e ls hc).\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hwfe. repeat split.\n    - rewrite /add_cet /=. move=> f fls. case Hfe: (f == e).\n      + rewrite (eqP Hfe). move=> _. assumption.\n      + move/negP: Hfe => Hfe. rewrite (SimpTableHash.find_et_add_et_neq _ _ Hfe).\n        exact: (H1 f).\n    - rewrite /add_cet /=. move=> f fls. rewrite SimpTableHash.find_bt_add_et.\n      exact: (H2 f).\n    - rewrite /add_cet /=. move=> f fls. exact: (H3 f).\n    - rewrite /add_cet /=. move=> f fls. exact: (H4 f).\n  Qed.\n\n  Lemma well_formed_cache_add_cbt hc (e : hbexp) ls :\n    well_formed_cache hc -> well_formed_hbexp e ->\n    well_formed_cache (CacheHash.add_cbt e ls hc).\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hwfe. repeat split.\n    - rewrite /add_cbt /=. move=> f fls. exact: (H1 f).\n    - rewrite /add_cbt /=. move=> f fls. case Hfe: (f == e).\n      + rewrite (eqP Hfe). move=> _. assumption.\n      + move/negP: Hfe => Hfe. rewrite (SimpTableHash.find_bt_add_bt_neq _ _ Hfe).\n        exact: (H2 f).\n    - rewrite /add_cbt /=. move=> f fls. exact: (H3 f).\n    - rewrite /add_cbt /=. move=> f fls. exact: (H4 f).\n  Qed.\n\n  Lemma well_formed_cache_add_het hc (e : hexp) cs ls :\n    well_formed_cache hc -> well_formed_hexp e ->\n    well_formed_cache (CacheHash.add_het e cs ls hc).\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hwfe. repeat split.\n    - rewrite /add_het /=. move=> f fls. exact: (H1 f).\n    - rewrite /add_het /=. move=> f fls. exact: (H2 f).\n    - rewrite /add_het /=. move=> f fls. case Hfe: (f == e).\n      + rewrite (eqP Hfe). move=> _; assumption.\n      + move/negP: Hfe=> Hfe. rewrite (CompTableHash.find_et_add_et_neq _ _ _ Hfe).\n        exact: (H3 f).\n    - rewrite /add_het /=. move=> f fls. exact: (H4 f).\n  Qed.\n\n  Lemma well_formed_cache_add_hbt hc (e : hbexp) cs ls :\n    well_formed_cache hc -> well_formed_hbexp e ->\n    well_formed_cache (CacheHash.add_hbt e cs ls hc).\n  Proof.\n    move=> [[H1 H2] [H3 H4]] Hwfe. repeat split.\n    - rewrite /add_hbt /=. move=> f fls. exact: (H1 f).\n    - rewrite /add_hbt /=. move=> f fls. exact: (H2 f).\n    - rewrite /add_hbt /=. move=> f fls. exact: (H3 f).\n    - rewrite /add_hbt /=. move=> f fls. case Hfe: (f == e).\n      + rewrite (eqP Hfe). move=> _; assumption.\n      + move/negP: Hfe=> Hfe. rewrite (CompTableHash.find_bt_add_bt_neq _ _ _ Hfe).\n        exact: (H4 f).\n  Qed.\n\n  Lemma well_formed_cache_reset_ct c :\n    well_formed_cache c -> well_formed_cache (reset_ct c).\n  Proof.\n    rewrite /reset_ct. move=>[[H1 H2] [H3 H4]]. by repeat split.\n  Qed.\n\nEnd WellFormedCache.\n\n\nLtac t_auto_hook ::=\n  match goal with\n  | |- ?e = ?e => reflexivity\n  | |- _ /\\ _ => split\n  | |- well_formed_cache (add_cet (hash_exp _) _ _) =>\n    apply: well_formed_cache_add_cet\n  | |- well_formed_cache (add_cbt (hash_bexp _) _ _) =>\n    apply: well_formed_cache_add_cbt\n  | |- well_formed_cache (add_het (hash_exp _) _ _ _) =>\n    apply: well_formed_cache_add_het\n  | |- well_formed_cache (add_hbt (hash_bexp _) _ _ _) =>\n    apply: well_formed_cache_add_hbt\n  | |- well_formed_cache (add_cet ?he _ _) =>\n    replace he with (hash_exp (unhash_hexp he))\n      by (rewrite /=; try rewrite !unhash_hash_exp; try rewrite !unhash_hash_bexp;\n          try rewrite !ehval_hash_exp; try rewrite !bhval_hash_bexp; reflexivity);\n    apply: well_formed_cache_add_cet\n  | |- well_formed_cache (add_cbt ?he _ _) =>\n    replace he with (hash_bexp (unhash_hbexp he))\n      by (rewrite /=; try rewrite !unhash_hash_exp; try rewrite !unhash_hash_bexp;\n          try rewrite !ehval_hash_exp; try rewrite !bhval_hash_bexp; reflexivity);\n    apply: well_formed_cache_add_cbt\n  | |- cache_compatible (add_cet _ ?rs _) (CacheFlatten.add_cet _ ?rs _) =>\n    apply: cache_compatible_add_cet\n  | |- cache_compatible (add_cbt _ ?rs _) (CacheFlatten.add_cbt _ ?rs _) =>\n    apply: cache_compatible_add_cbt\n  | |- cache_compatible (add_het _ ?cs ?rs _) (CacheFlatten.add_het _ ?cs ?rs _) =>\n    apply: cache_compatible_add_het\n  | |- cache_compatible (add_hbt _ ?cs ?rs _) (CacheFlatten.add_hbt _ ?cs ?rs _) =>\n    apply: cache_compatible_add_hbt\n  | |- context f [unhash_hexp (hash_exp ?e)] =>\n    rewrite (unhash_hash_exp e) /=\n  | |- context f [unhash_hbexp (hash_bexp ?e)] =>\n    rewrite (unhash_hash_bexp e) /=\n  | |- context f [ehval (hash_exp ?e)] =>\n    rewrite (ehval_hash_exp e)\n  | |- context f [bhval (hash_bexp ?e)] =>\n    rewrite (bhval_hash_bexp e)\n  | |- context f [well_formed_hexp (hash_exp ?e)] =>\n    rewrite (hash_exp_well_formed e)\n  | |- context f [well_formed_hbexp (hash_bexp ?e)] =>\n    rewrite (hash_bexp_well_formed e)\n\n  | |- context f [CacheHash.add_cet (epair ?he ?hh) _ _] =>\n    match goal with\n    | |- context g [CacheFlatten.add_cet ?e _ _] =>\n      replace (epair he hh) with (hash_exp e)\n    end\n  | |- hash_exp _ = epair _ _ => rewrite /=\n  end.\n\nLemma bit_blast_exp_hcache_well_formed_cache\n      E (e : QFBV.exp) m ihc g hm ohc hg hcs hlrs :\n  well_formed_cache ihc ->\n  bit_blast_exp_hcache E m ihc g (hash_exp e) =  (hm, ohc, hg, hcs, hlrs) ->\n  well_formed_cache ohc\nwith bit_blast_bexp_hcache_well_formed_cache\n       E (e : QFBV.bexp) m ihc g hm ohc hg hcs hlr :\n       well_formed_cache ihc ->\n       bit_blast_bexp_hcache E m ihc g (hash_bexp e) =  (hm, ohc, hg, hcs, hlr) ->\n       well_formed_cache ohc.\nProof.\n  (* bit_blast_exp_hcache_fcache_well_formed_cache *)\n  - case: e => /=.\n    + move=> v Hwf.\n      replace (epair (HEvar v) 1) with (hash_exp (QFBV.Evar v)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Evar v)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. assumption.\n      * case: (find_het (hash_exp (QFBV.Evar v)) ihc).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. by t_auto.\n        -- case Hvm: (SSAVM.find v m).\n           ++ move=> [] ? ? ? ? ?; subst. by t_auto.\n           ++ dcase (bit_blast_var E g v) => [[[g1 cs1] rs1] Hbbv].\n              move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> bs Hf.\n      replace (epair (HEconst bs) 1) with (hash_exp (QFBV.Econst bs)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Econst bs)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. assumption.\n      * case: (find_het (hash_exp (QFBV.Econst bs)) ihc).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> op e Hwf.\n      replace (epair (HEunop op (hash_exp e)) (ehval (hash_exp e) + 1))\n        with (hash_exp (QFBV.Eunop op e)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Eunop op e)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb].\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb) => Hwf_hc1.\n        case: (find_het (hash_exp (QFBV.Eunop op e)) hc1).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. by t_auto.\n        -- dcase (bit_blast_eunop op hg1 hls1) => [[[g1 cs1] ls1] Hbb].\n           move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> op e1 e2 Hwf.\n      replace (epair (HEbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1))\n        with (hash_exp (QFBV.Ebinop op e1 e2)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Ebinop op e1 e2)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf1 Hhbb2) => Hwf2.\n        case: (find_het (hash_exp (QFBV.Ebinop op e1 e2)) hc2).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. by t_auto.\n        -- dcase (bit_blast_ebinop op hg2 hls1 hls2) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> e1 e2 e3 Hwf.\n      replace (epair (HEite (hash_bexp e1) (hash_exp e2) (hash_exp e3))\n                     (bhval (hash_bexp e1) +\n                      ehval (hash_exp e2) + ehval (hash_exp e3) + 1)) with\n          (hash_exp (QFBV.Eite e1 e2 e3)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Eite e1 e2 e3)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        dcase (bit_blast_exp_hcache E hm2 hc2 hg2 (hash_exp e3)) =>\n        [[[[[hm3 hc3] hg3] hcs3] hls3] Hhbb3].\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf1 Hhbb2) => Hwf2.\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf2 Hhbb3) => Hwf3.\n        case: (find_het (hash_exp (QFBV.Eite e1 e2 e3)) hc3).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. by t_auto.\n        -- dcase (bit_blast_ite hg3 hls1 hls2 hls3) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. by t_auto.\n  (* bit_blast_bexp_hcache_fcache_well_formed_cache *)\n  - case: e => /=.\n    + move=> Hwf.\n      replace (bpair HBfalse 1) with (hash_bexp QFBV.Bfalse) by reflexivity.\n      case: (find_cbt (hash_bexp QFBV.Bfalse) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. assumption.\n      * case: (find_hbt (hash_bexp QFBV.Bfalse) ihc).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> Hwf.\n      replace (bpair HBtrue 1) with (hash_bexp QFBV.Btrue) by reflexivity.\n      case: (find_cbt (hash_bexp QFBV.Btrue) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. assumption.\n        case: (find_hbt (hash_bexp QFBV.Btrue) ihc).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> op e1 e2 Hwf.\n      replace (bpair (HBbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1)) with\n          (hash_bexp (QFBV.Bbinop op e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bbinop op e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        move: (bit_blast_exp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf1 Hhbb2) => Hwf2.\n        case: (find_hbt (hash_bexp (QFBV.Bbinop op e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- dcase (bit_blast_bbinop op hg2 hlr1 hlr2) => [[[gop csop] lop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> e Hwf.\n      replace (bpair (HBlneg (hash_bexp e)) (bhval (hash_bexp e) + 1)) with\n          (hash_bexp (QFBV.Blneg e)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Blneg e)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        case: (find_hbt (hash_bexp (QFBV.Blneg e)) hc1).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> e1 e2 Hwf.\n      replace (bpair (HBconj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bconj e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bconj e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf1 Hhbb2) => Hwf2.\n        case: (find_hbt (hash_bexp (QFBV.Bconj e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\n    + move=> e1 e2 Hwf.\n      replace (bpair (HBdisj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bdisj e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bdisj e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf Hhbb1) => Hwf1.\n        move: (bit_blast_bexp_hcache_well_formed_cache\n                 _ _ _ _ _ _ _ _ _ _ Hwf1 Hhbb2) => Hwf2.\n        case: (find_hbt (hash_bexp (QFBV.Bdisj e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. by t_auto.\nQed.\n\nLtac t_exists :=\n  match goal with\n  | H : cache_compatible ?ohc ?ifc\n    |- exists ofc : CacheFlatten.cache, cache_compatible ?ohc ofc =>\n    exists ifc\n  | H : cache_compatible ?ihc ?ifc\n    |- exists ofc : CacheFlatten.cache,\n      cache_compatible (add_cet ?he ?hlrs ?ihc) ofc =>\n    exists (CacheFlatten.add_cet (unhash_hexp he) hlrs ifc)\n  | H : cache_compatible ?ihc ?ifc\n    |- exists ofc : CacheFlatten.cache,\n      cache_compatible (add_cbt ?he ?hlr ?ihc) ofc =>\n    exists (CacheFlatten.add_cbt (unhash_hbexp he) hlr ifc)\n  | H : cache_compatible ?ihc ?ifc\n    |- exists ofc : CacheFlatten.cache,\n      cache_compatible\n        (add_cet ?he1 ?hlrs1\n                 (add_het ?he2 ?hcs2 ?hlrs2 ?ihc)) ofc =>\n    exists (CacheFlatten.add_cet\n              (unhash_hexp he1) hlrs1\n              (CacheFlatten.add_het (unhash_hexp he2) hcs2 hlrs2 ifc))\n  | H : cache_compatible ?ihc ?ifc\n    |- exists ofc : CacheFlatten.cache,\n      cache_compatible\n        (add_cbt ?he1 ?hlr1\n                 (add_hbt ?he2 ?hcs2 ?hlr2 ?ihc)) ofc =>\n    exists (CacheFlatten.add_cbt\n              (unhash_hbexp he1) hlr1\n              (CacheFlatten.add_hbt (unhash_hbexp he2) hcs2 hlr2 ifc))\n  end; rewrite /=.\n\nLemma bit_blast_exp_hcache_cache_compatible\n      E (e : QFBV.exp) m ihc ifc g hm ohc hg hcs hlrs :\n  cache_compatible ihc ifc ->\n  bit_blast_exp_hcache E m ihc g (hash_exp e) =  (hm, ohc, hg, hcs, hlrs) ->\n  exists ofc, cache_compatible ohc ofc\nwith bit_blast_bexp_hcache_cache_compatible\n       E (e : QFBV.bexp) m ihc ifc g hm ohc hg hcs hlr :\n       cache_compatible ihc ifc ->\n       bit_blast_bexp_hcache E m ihc g (hash_bexp e) =  (hm, ohc, hg, hcs, hlr) ->\n       exists ofc, cache_compatible ohc ofc.\nProof.\n  (* bit_blast_exp_hcache_fcache_cache_compatible *)\n  - case: e => /=.\n    + move=> v Hcc.\n      replace (epair (HEvar v) 1) with (hash_exp (QFBV.Evar v)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Evar v)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. t_exists. assumption.\n      * case: (find_het (hash_exp (QFBV.Evar v)) ihc).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- case Hvm: (SSAVM.find v m).\n           ++ move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n           ++ dcase (bit_blast_var E g v) => [[[g1 cs1] rs1] Hbbv].\n              move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> bs Hcc.\n      replace (epair (HEconst bs) 1) with (hash_exp (QFBV.Econst bs)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Econst bs)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. t_exists. assumption.\n      * case: (find_het (hash_exp (QFBV.Econst bs)) ihc).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> op e Hcc.\n      replace (epair (HEunop op (hash_exp e)) (ehval (hash_exp e) + 1))\n        with (hash_exp (QFBV.Eunop op e)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Eunop op e)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb) => [fc1 Hcc1].\n        case: (find_het (hash_exp (QFBV.Eunop op e)) hc1).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- dcase (bit_blast_eunop op hg1 hls1) => [[[g1 cs1] ls1] Hbb].\n           move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> op e1 e2 Hcc.\n      replace (epair (HEbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1))\n        with (hash_exp (QFBV.Ebinop op e1 e2)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Ebinop op e1 e2)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hhbb2) => [fc2 Hcc2].\n        case: (find_het (hash_exp (QFBV.Ebinop op e1 e2)) hc2).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- dcase (bit_blast_ebinop op hg2 hls1 hls2) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> e1 e2 e3 Hcc.\n      replace (epair (HEite (hash_bexp e1) (hash_exp e2) (hash_exp e3))\n                     (bhval (hash_bexp e1) +\n                      ehval (hash_exp e2) + ehval (hash_exp e3) + 1)) with\n          (hash_exp (QFBV.Eite e1 e2 e3)) by reflexivity.\n      case: (find_cet (hash_exp (QFBV.Eite e1 e2 e3)) ihc).\n      * move=> ls [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        dcase (bit_blast_exp_hcache E hm2 hc2 hg2 (hash_exp e3)) =>\n        [[[[[hm3 hc3] hg3] hcs3] hls3] Hhbb3].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hhbb2) => [fc2 Hcc2].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc2 Hhbb3) => [fc3 Hcc3].\n        case: (find_het (hash_exp (QFBV.Eite e1 e2 e3)) hc3).\n        -- move=> [cs ls] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- dcase (bit_blast_ite hg3 hls1 hls2 hls3) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n  (* bit_blast_bexp_hcache_fcache_cache_compatible *)\n  - case: e => /=.\n    + move=> Hcc.\n      replace (bpair HBfalse 1) with (hash_bexp QFBV.Bfalse) by reflexivity.\n      case: (find_cbt (hash_bexp QFBV.Bfalse) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * case: (find_hbt (hash_bexp QFBV.Bfalse) ihc).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> Hcc.\n      replace (bpair HBtrue 1) with (hash_bexp QFBV.Btrue) by reflexivity.\n      case: (find_cbt (hash_bexp QFBV.Btrue) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * case: (find_hbt (hash_bexp QFBV.Btrue) ihc).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> op e1 e2 Hcc.\n      replace (bpair (HBbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1)) with\n          (hash_bexp (QFBV.Bbinop op e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bbinop op e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        move: (bit_blast_exp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hhbb2) => [fc2 Hcc2].\n        case: (find_hbt (hash_bexp (QFBV.Bbinop op e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- dcase (bit_blast_bbinop op hg2 hlr1 hlr2) => [[[gop csop] lop] Hbbop].\n           move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> e Hcc.\n      replace (bpair (HBlneg (hash_bexp e)) (bhval (hash_bexp e) + 1)) with\n          (hash_bexp (QFBV.Blneg e)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Blneg e)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        case: (find_hbt (hash_bexp (QFBV.Blneg e)) hc1).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> e1 e2 Hcc.\n      replace (bpair (HBconj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bconj e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bconj e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hhbb2) => [fc2 Hcc2].\n        case: (find_hbt (hash_bexp (QFBV.Bconj e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\n    + move=> e1 e2 Hcc.\n      replace (bpair (HBdisj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bdisj e1 e2)) by reflexivity.\n      case: (find_cbt (hash_bexp (QFBV.Bdisj e1 e2)) ihc).\n      * move=> lr [] ? ? ? ? ?; subst. t_exists. assumption.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc Hhbb1) => [fc1 Hcc1].\n        move: (bit_blast_bexp_hcache_cache_compatible\n                 _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hhbb2) => [fc2 Hcc2].\n        case: (find_hbt (hash_bexp (QFBV.Bdisj e1 e2)) hc2).\n        -- move=> [cs lr] [] ? ? ? ? ?; subst. t_exists. by t_auto.\n        -- move=> [] ? ? ? ? ?; subst. t_exists. by t_auto.\nQed.\n\nLemma bit_blast_exp_hcache_fcache\n      E (e : QFBV.exp) m ihc ifc g hm fm\n      ohc ofc hg fg hcs fcs hlrs flrs :\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  bit_blast_exp_hcache E m ihc g (hash_exp e) =  (hm, ohc, hg, hcs, hlrs) ->\n  bit_blast_exp_fcache E m ifc g e =  (fm, ofc, fg, fcs, flrs) ->\n  hm = fm\n  /\\ well_formed_cache ohc\n  /\\ cache_compatible ohc ofc\n  /\\ hg = fg\n  /\\ hcs = fcs\n  /\\ hlrs = flrs\nwith bit_blast_bexp_hcache_fcache\n       E (e : QFBV.bexp) m ihc ifc g hm fm\n       ohc ofc hg fg hcs fcs hlr flr :\n       well_formed_cache ihc ->\n       cache_compatible ihc ifc ->\n       bit_blast_bexp_hcache E m ihc g (hash_bexp e) =  (hm, ohc, hg, hcs, hlr) ->\n       bit_blast_bexp_fcache E m ifc g e =  (fm, ofc, fg, fcs, flr) ->\n       hm = fm\n       /\\ well_formed_cache ohc\n       /\\ cache_compatible ohc ofc\n       /\\ hg = fg\n       /\\ hcs = fcs\n       /\\ hlr = flr.\nProof.\n  (* bit_blast_exp_hcache_fcache *)\n  - case: e => /=.\n    + move=> v Hwf Hcc.\n      replace (epair (HEvar v) 1) with (hash_exp (QFBV.Evar v)) by reflexivity.\n      rewrite (cache_compatible_find_cet _ Hcc).\n      rewrite (cache_compatible_find_het _ Hcc).\n      case: (CacheFlatten.find_cet (QFBV.Evar v) ifc).\n      * move=> ls [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * case: (CacheFlatten.find_het (QFBV.Evar v) ifc).\n        -- move=> [cs ls] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- case Hvm: (SSAVM.find v m).\n           ++ move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n                by t_auto.\n           ++ dcase (bit_blast_var E g v) => [[[g1 cs1] rs1] Hbbv].\n              move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n                by t_auto.\n    + move=> bs Hf Hcc.\n      replace (epair (HEconst bs) 1) with (hash_exp (QFBV.Econst bs)) by reflexivity.\n      rewrite (cache_compatible_find_cet _ Hcc).\n      rewrite (cache_compatible_find_het _ Hcc).\n      case: (CacheFlatten.find_cet (QFBV.Econst bs) ifc).\n      * move=> ls [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * case: (CacheFlatten.find_het (QFBV.Econst bs) ifc).\n        -- move=> [cs ls] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> op e Hwf Hcc.\n      replace (epair (HEunop op (hash_exp e)) (ehval (hash_exp e) + 1))\n        with (hash_exp (QFBV.Eunop op e)) by reflexivity.\n      rewrite (cache_compatible_find_cet _ Hcc).\n      case: (CacheFlatten.find_cet (QFBV.Eunop op e) ifc).\n      * move=> ls [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb].\n        dcase (bit_blast_exp_fcache E m ifc g e) =>\n        [[[[[fm1 fc1] fg1] fcs1] fls1] Hfbb].\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf Hcc Hhbb Hfbb).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_het _ Hcc1).\n        case: (CacheFlatten.find_het (QFBV.Eunop op e) fc1).\n        -- move=> [cs ls] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- dcase (bit_blast_eunop op fg1 fls1) => [[[g1 cs1] ls1] Hbb].\n           move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> op e1 e2 Hwf Hcc.\n      replace (epair (HEbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1))\n        with (hash_exp (QFBV.Ebinop op e1 e2)) by reflexivity.\n      rewrite (cache_compatible_find_cet _ Hcc).\n      case: (CacheFlatten.find_cet (QFBV.Ebinop op e1 e2) ifc).\n      * move=> ls [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        dcase (bit_blast_exp_fcache E m ifc g e1) =>\n        [[[[[fm1 fc1] fg1] fcs1] fls1] Hfbb1].\n        dcase (bit_blast_exp_fcache E fm1 fc1 fg1 e2) =>\n        [[[[[fm2 fc2] fg2] fcs2] fls2] Hfbb2].\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf1 Hcc1 Hhbb2 Hfbb2).\n        move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_het _ Hcc2).\n        case: (CacheFlatten.find_het (QFBV.Ebinop op e1 e2) fc2).\n        -- move=> [cs ls] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- dcase (bit_blast_ebinop op fg2 fls1 fls2) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> e1 e2 e3 Hwf Hcc.\n      replace (epair (HEite (hash_bexp e1) (hash_exp e2) (hash_exp e3))\n                     (bhval (hash_bexp e1) +\n                      ehval (hash_exp e2) + ehval (hash_exp e3) + 1)) with\n          (hash_exp (QFBV.Eite e1 e2 e3)) by reflexivity.\n      rewrite (cache_compatible_find_cet _ Hcc).\n      case: (CacheFlatten.find_cet (QFBV.Eite e1 e2 e3) ifc).\n      * move=> ls [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hls1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hls2] Hhbb2].\n        dcase (bit_blast_exp_hcache E hm2 hc2 hg2 (hash_exp e3)) =>\n        [[[[[hm3 hc3] hg3] hcs3] hls3] Hhbb3].\n        dcase (bit_blast_bexp_fcache E m ifc g e1) =>\n        [[[[[fm1 fc1] fg1] fcs1] fls1] Hfbb1].\n        dcase (bit_blast_exp_fcache E fm1 fc1 fg1 e2) =>\n        [[[[[fm2 fc2] fg2] fcs2] fls2] Hfbb2].\n        dcase (bit_blast_exp_fcache E fm2 fc2 fg2 e3) =>\n        [[[[[fm3 fc3] fg3] fcs3] fls3] Hfbb3].\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf1 Hcc1 Hhbb2 Hfbb2).\n        move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst.\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf2 Hcc2 Hhbb3 Hfbb3).\n        move=> [? [Hwf3 [Hcc3 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_het _ Hcc3).\n        case: (CacheFlatten.find_het (QFBV.Eite e1 e2 e3) fc3).\n        -- move=> [cs ls] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- dcase (bit_blast_ite fg3 fls1 fls2 fls3) => [[[gop csop] lsop] Hbbop].\n           move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n  (* bit_blast_bexp_hcache_fcache *)\n  - case: e => /=.\n    + move=> Hwf Hcc.\n      replace (bpair HBfalse 1) with (hash_bexp QFBV.Bfalse) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt QFBV.Bfalse ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * rewrite (cache_compatible_find_hbt _ Hcc).\n        case: (CacheFlatten.find_hbt QFBV.Bfalse ifc).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> Hwf Hcc.\n      replace (bpair HBtrue 1) with (hash_bexp QFBV.Btrue) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt QFBV.Btrue ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * rewrite (cache_compatible_find_hbt _ Hcc).\n        case: (CacheFlatten.find_hbt QFBV.Btrue ifc).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> op e1 e2 Hwf Hcc.\n      replace (bpair (HBbinop op (hash_exp e1) (hash_exp e2))\n                     (ehval (hash_exp e1) + ehval (hash_exp e2) + 1)) with\n          (hash_bexp (QFBV.Bbinop op e1 e2)) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt (QFBV.Bbinop op e1 e2) ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_exp_hcache E m ihc g (hash_exp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_exp_hcache E hm1 hc1 hg1 (hash_exp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        dcase (bit_blast_exp_fcache E m ifc g e1) =>\n        [[[[[fm1 fc1] fg1] fcs1] flr1] Hfbb1].\n        dcase (bit_blast_exp_fcache E fm1 fc1 fg1 e2) =>\n        [[[[[fm2 fc2] fg2] fcs2] flr2] Hfbb2].\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        move: (bit_blast_exp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                           Hwf1 Hcc1 Hhbb2 Hfbb2).\n        move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_hbt _ Hcc2).\n        case: (CacheFlatten.find_hbt (QFBV.Bbinop op e1 e2) fc2).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- dcase (bit_blast_bbinop op fg2 flr1 flr2) => [[[gop csop] lop] Hbbop].\n           move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> e Hwf Hcc.\n      replace (bpair (HBlneg (hash_bexp e)) (bhval (hash_bexp e) + 1)) with\n          (hash_bexp (QFBV.Blneg e)) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt (QFBV.Blneg e) ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_fcache E m ifc g e) =>\n        [[[[[fm1 fc1] fg1] fcs1] flr1] Hfbb1].\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                            Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_hbt _ Hcc1).\n        case: (CacheFlatten.find_hbt (QFBV.Blneg e) fc1).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> e1 e2 Hwf Hcc.\n      replace (bpair (HBconj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bconj e1 e2)) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt (QFBV.Bconj e1 e2) ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        dcase (bit_blast_bexp_fcache E m ifc g e1) =>\n        [[[[[fm1 fc1] fg1] fcs1] flr1] Hfbb1].\n        dcase (bit_blast_bexp_fcache E fm1 fc1 fg1 e2) =>\n        [[[[[fm2 fc2] fg2] fcs2] flr2] Hfbb2].\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                            Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                            Hwf1 Hcc1 Hhbb2 Hfbb2).\n        move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_hbt _ Hcc2).\n        case: (CacheFlatten.find_hbt (QFBV.Bconj e1 e2) fc2).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n    + move=> e1 e2 Hwf Hcc.\n      replace (bpair (HBdisj (hash_bexp e1) (hash_bexp e2))\n                     (bhval (hash_bexp e1) + bhval (hash_bexp e2) + 1)) with\n          (hash_bexp (QFBV.Bdisj e1 e2)) by reflexivity.\n      rewrite (cache_compatible_find_cbt _ Hcc).\n      case: (CacheFlatten.find_cbt (QFBV.Bdisj e1 e2) ifc).\n      * move=> lr [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n      * dcase (bit_blast_bexp_hcache E m ihc g (hash_bexp e1)) =>\n        [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n        dcase (bit_blast_bexp_hcache E hm1 hc1 hg1 (hash_bexp e2)) =>\n        [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n        dcase (bit_blast_bexp_fcache E m ifc g e1) =>\n        [[[[[fm1 fc1] fg1] fcs1] flr1] Hfbb1].\n        dcase (bit_blast_bexp_fcache E fm1 fc1 fg1 e2) =>\n        [[[[[fm2 fc2] fg2] fcs2] flr2] Hfbb2].\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                            Hwf Hcc Hhbb1 Hfbb1).\n        move=> [? [Hwf1 [Hcc1 [? [? ?]]]]]; subst.\n        move: (bit_blast_bexp_hcache_fcache _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                            Hwf1 Hcc1 Hhbb2 Hfbb2).\n        move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst.\n        rewrite (cache_compatible_find_hbt _ Hcc2).\n        case: (CacheFlatten.find_hbt (QFBV.Bdisj e1 e2) fc2).\n        -- move=> [cs lr] [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\n        -- move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst.\n             by t_auto.\nQed.\n\n\nLemma bit_blast_bexp_hcache_preserve\n      TE e ihm ihc ihg ohm ohc ohg ohcs ohlr ifc ic icc :\n  bit_blast_bexp_hcache TE ihm ihc ihg (hash_bexp e) =  (ohm, ohc, ohg, ohcs, ohlr) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  vm_preserve ihm ohm.\nProof.\n  move=> Hhbb Hwfihc Hccihc Hccifc Hccic.\n  dcase (bit_blast_bexp_fcache TE ihm ifc ihg e) =>\n  [[[[[ofm ofc] ofg] ofcs] oflr] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache Hwfihc Hccihc Hhbb Hfbb) =>\n  [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n  dcase (bit_blast_bexp_cache TE ihm ic ihg e) =>\n  [[[[[om oc] og] ocs] olr] Hbb].\n  move: (bit_blast_bexp_fcache_valid Hccifc Hfbb Hbb) =>\n  [? [Hccofc [? [Heqs ?]]]]; subst.\n  move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccic Hbb)\n  => [cicc [Hcbb Hccoc]].\n  exact: (bit_blast_bexp_ccache_preserve Hcbb).\nQed.\n\nLemma bit_blast_bexp_hcache_bound\n      TE e ihm ihc ihg ohm ohc ohg ohcs ohlr ifc ic icc :\n  bit_blast_bexp_hcache TE ihm ihc ihg (hash_bexp e) =  (ohm, ohc, ohg, ohcs, ohlr) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  bound_bexp e ohm.\nProof.\n  move=> Hhbb Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc.\n  dcase (bit_blast_bexp_fcache TE ihm ifc ihg e) =>\n  [[[[[ofm ofc] ofg] ofcs] oflr] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache Hwfihc Hccihc Hhbb Hfbb) =>\n  [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n  dcase (bit_blast_bexp_cache TE ihm ic ihg e) =>\n  [[[[[om oc] og] ocs] olr] Hbb].\n  move: (bit_blast_bexp_fcache_valid Hccifc Hfbb Hbb) =>\n  [? [Hccofc [? [Heqs ?]]]]; subst.\n  move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccic Hbb)\n  => [cicc [Hcbb Hccoc]].\n  exact: (proj1 (bit_blast_bexp_ccache_bound_cache Hcbb Hwficc Hboundicc)).\nQed.\n\nLemma bit_blast_bexp_hcache_adhere\n      TE e ihm ihc ihg ohm ohc ohg ohcs ohlr ifc ic icc :\n  bit_blast_bexp_hcache TE ihm ihc ihg (hash_bexp e) =  (ohm, ohc, ohg, ohcs, ohlr) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  adhere ihm TE ->\n  adhere ohm TE.\nProof.\n  move=> Hhbb Hwfihc Hccihc Hccifc Hccic Hadihm.\n  dcase (bit_blast_bexp_fcache TE ihm ifc ihg e) =>\n  [[[[[ofm ofc] ofg] ofcs] oflr] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache Hwfihc Hccihc Hhbb Hfbb) =>\n  [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n  dcase (bit_blast_bexp_cache TE ihm ic ihg e) =>\n  [[[[[om oc] og] ocs] olr] Hbb].\n  move: (bit_blast_bexp_fcache_valid Hccifc Hfbb Hbb) =>\n  [? [Hccofc [? [Heqs ?]]]]; subst.\n  move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccic Hbb)\n  => [cicc [Hcbb Hccoc]].\n  exact: (bit_blast_bexp_ccache_adhere Hadihm Hcbb).\nQed.\n\n\n\n(* ==== basic case ==== *)\n\n(* = bit-blasting only one bexp = *)\n\nDefinition init_hcache : cache := CacheHash.empty.\n\nLemma init_hcache_well_formed : well_formed_cache init_hcache.\nProof. done. Qed.\n\nLemma init_hcache_fcache_compatible : cache_compatible init_hcache init_fcache.\nProof. done. Qed.\n\nTheorem bit_blast_bexp_hcache_sound E (e : QFBV.bexp) m c g cs lr :\n  bit_blast_bexp_hcache\n    E init_vm init_hcache init_gen (hash_bexp e) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  ~ (sat (add_prelude ([::neg_lit lr]::(tflatten cs)))) ->\n  (forall s, AdhereConform.conform_bexp e s E ->\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hhbb Hwf Hsat.\n  dcase (bit_blast_bexp_fcache E init_vm init_fcache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache init_hcache_well_formed\n                                      init_hcache_fcache_compatible\n                                      Hhbb Hfbb).\n  move=> [? [Hwf' [Hcc' [? [? ?]]]]]; subst.\n  exact: (bit_blast_bexp_fcache_sound Hfbb Hwf Hsat).\nQed.\n\nTheorem bit_blast_bexp_hcache_complete E (e : QFBV.bexp) m c g cs lr :\n  bit_blast_bexp_hcache\n    E init_vm init_hcache init_gen (hash_bexp e) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (forall s, AdhereConform.conform_bexp e s E ->\n             QFBV.eval_bexp e s) ->\n  ~ (sat (add_prelude ([::neg_lit lr]::(tflatten cs)))).\nProof.\n  move=> Hhbb Hwf Hev.\n  dcase (bit_blast_bexp_fcache E init_vm init_fcache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache init_hcache_well_formed\n                                      init_hcache_fcache_compatible\n                                      Hhbb Hfbb).\n  move=> [? [Hwf' [Hcc' [? [? ?]]]]]; subst.\n  exact: (bit_blast_bexp_fcache_complete Hfbb Hwf Hev).\nQed.\n\nTheorem bit_blast_bexp_hcache_sat_sound E (e : QFBV.bexp) m c g cs lr :\n  bit_blast_bexp_hcache\n    E init_vm init_hcache init_gen (hash_bexp e) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (sat (add_prelude ([:: lr]::(tflatten cs)))) ->\n  (exists s, AdhereConform.conform_bexp e s E /\\\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hhbb Hwf Hsat.\n  dcase (bit_blast_bexp_fcache E init_vm init_fcache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache init_hcache_well_formed\n                                      init_hcache_fcache_compatible\n                                      Hhbb Hfbb).\n  move=> [? [Hwf' [Hcc' [? [? ?]]]]]; subst.\n  exact: (bit_blast_bexp_fcache_sat_sound Hfbb Hwf Hsat).\nQed.\n\nTheorem bit_blast_bexp_hcache_sat_complete E (e : QFBV.bexp) m c g cs lr :\n  bit_blast_bexp_hcache\n    E init_vm init_hcache init_gen (hash_bexp e) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (exists s, AdhereConform.conform_bexp e s E /\\\n             QFBV.eval_bexp e s) ->\n  (sat (add_prelude ([:: lr]::(tflatten cs)))).\nProof.\n  move=> Hhbb Hwf Hev.\n  dcase (bit_blast_bexp_fcache E init_vm init_fcache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexp_hcache_fcache init_hcache_well_formed\n                                      init_hcache_fcache_compatible\n                                      Hhbb Hfbb).\n  move=> [? [Hwf' [Hcc' [? [? ?]]]]]; subst.\n  exact: (bit_blast_bexp_fcache_sat_complete Hfbb Hwf Hev).\nQed.\n\nCorollary bit_blast_bexp_hcache_sat_sound_and_complete E (e : QFBV.bexp) m c g cs lr :\n  bit_blast_bexp_hcache\n    E init_vm init_hcache init_gen (hash_bexp e) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  ((exists s, AdhereConform.conform_bexp e s E /\\ QFBV.eval_bexp e s)\n   <->\n   (exists (E : env), interp_cnf E (add_prelude ([:: lr]::(tflatten cs))))).\nProof.\n  move=> Hbb Hwf. split.\n  - exact: (bit_blast_bexp_hcache_sat_complete Hbb).\n  - exact: (bit_blast_bexp_hcache_sat_sound Hbb).\nQed.\n\n\n(* ==== general case ==== *)\n\n(* = bit-blasting multiple bexps = *)\n\nDefinition bit_blast_bexp_hcache_tflatten E m c g e :=\n  let '(m', c', g', css', lr') := bit_blast_bexp_hcache E m c g e in\n  (m', c', g', tflatten css', lr').\n\nFixpoint bit_blast_hbexps_hcache E (es : seq hbexp) :=\n  match es with\n  | [::] => (init_vm, init_hcache, init_gen, add_prelude [::], lit_tt)\n  | e :: es' =>\n    let '(m, c, g, cs, lr) := bit_blast_hbexps_hcache E es' in\n    bit_blast_bexp_hcache_tflatten E m (CacheHash.reset_ct c) g e\n  end.\n\nDefinition bit_blast_bexps_hcache E (es : seq QFBV.bexp) :=\n  bit_blast_hbexps_hcache E (map hash_bexp es).\n\nLemma bit_blast_bexps_hcache_valid E es hm hc hg hcs hlr fm fc fg fcs flr :\n  bit_blast_bexps_hcache E es = (hm, hc, hg, hcs, hlr) ->\n  bit_blast_bexps_fcache E es = (fm, fc, fg, fcs, flr) ->\n  hm = fm\n  /\\ well_formed_cache hc\n  /\\ cache_compatible hc fc\n  /\\ hg = fg\n  /\\ hcs = fcs\n  /\\ hlr = flr.\nProof.\n  elim: es hm hc hg hcs hlr fm fc fg fcs flr =>\n  [| e es IH]  hm hc hg hcs hlr fm fc fg fcs flr /=.\n  - move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n  - rewrite /bit_blast_bexps_hcache /=.\n    dcase (bit_blast_hbexps_hcache E [seq hash_bexp i | i <- es]) =>\n    [[[[[hm1 hc1] hg1] hcs1] hlr1] Hhbb1].\n    rewrite Hhbb1. rewrite /bit_blast_bexp_hcache_tflatten.\n    dcase (bit_blast_bexp_hcache E hm1 (reset_ct hc1) hg1 (hash_bexp e)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlr2] Hhbb2].\n    case=> ? ? ? ? ?; subst.\n    dcase (bit_blast_bexps_fcache E es) => [[[[[fm1 fc1] fg1] fcs1] flr1] Hfbb1].\n    rewrite /bit_blast_bexp_fcache_tflatten.\n    dcase (bit_blast_bexp_fcache E fm1 (CacheFlatten.reset_ct fc1) fg1 e) =>\n    [[[[[fm2 fc2] fg2] fcs2] flr2] Hfbb2].\n    case=> ? ? ? ? ?; subst.\n    move: (IH _ _ _ _ _ _ _ _ _ _ Hhbb1 Hfbb1).\n    move=> [Hm [Hwf1 [Hcc1 [Hg [Hcs Hlr]]]]]; subst.\n    move: (bit_blast_bexp_hcache_fcache (well_formed_cache_reset_ct Hwf1)\n                                        (cache_compatible_reset_ct Hcc1)\n                                        Hhbb2 Hfbb2).\n    move=> [? [Hwf2 [Hcc2 [? [? ?]]]]]; subst. by repeat split => //=.\nQed.\n\nTheorem bit_blast_bexps_hcache_sound e es E m c g cs lr :\n  bit_blast_bexps_hcache E (e::es) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexps (e::es) E ->\n  ~ (sat (add_prelude ([::neg_lit lr]::cs))) ->\n  (forall s, AdhereConform.conform_bexps (e::es) s E ->\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hhbb Hwf Hsat.\n  dcase (bit_blast_bexps_fcache E (e::es)) => [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexps_hcache_valid Hhbb Hfbb).\n  move=> [Hm [Hwfc [Hcc [Hg [Hcs Hlr]]]]]; subst.\n  exact: (bit_blast_bexps_fcache_sound Hfbb Hwf Hsat).\nQed.\n\nTheorem bit_blast_bexps_hcache_complete e es E m c g cs lr :\n  bit_blast_bexps_hcache E (e::es) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexps (e::es) E ->\n  (forall s, AdhereConform.conform_bexps (e::es) s E ->\n             QFBV.eval_bexp e s) ->\n  ~ (sat (add_prelude ([::neg_lit lr]::cs))).\nProof.\n  move=> Hhbb Hwf Hev Hsat.\n  dcase (bit_blast_bexps_fcache E (e::es)) => [[[[[m' c'] g'] cs'] lr'] Hfbb].\n  move: (bit_blast_bexps_hcache_valid Hhbb Hfbb).\n  move=> [Hm [Hwfc [Hcc [Hg [Heqs Hlr]]]]]; subst.\n  exact: (bit_blast_bexps_fcache_complete Hfbb Hwf Hev).\nQed.\n\nDefinition bexp_to_cnf_hcache E m c g e :=\n  let '(m', c', g', cs, lr) := bit_blast_bexp_hcache_tflatten E m c g e in\n  (m', c', g', add_prelude ([::neg_lit lr]::cs)).\n\n\n\n(* Bit-blasting a sequence of QFBV bexps as a conjunction *)\n\nFixpoint bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs es : vm * cache * generator * seq cnf * cnf :=\n  match es with\n  | [::] => (m, c, g, rcs, rlrs)\n  | hd::tl => let '(m', c', g', cs, lr) := bit_blast_bexp_hcache E m c g hd in\n              bit_blast_hbexps_hcache_conjs_rec E m' c' g'\n                                                (catrev cs rcs) ([:: lr]::rlrs) tl\n  end.\n\nDefinition bit_blast_hbexps_hcache_conjs E m c g es :=\n  bit_blast_hbexps_hcache_conjs_rec E m c g [::] [::] es.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_empty E m c g rcs rlrs :\n  bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs [::] = (m, c, g, rcs, rlrs).\nProof. reflexivity. Qed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_singleton E m c g rcs rlrs e :\n  bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs [:: e] =\n  let '(m', c', g', cs, lr) := bit_blast_bexp_hcache E m c g e in\n  (m', c', g', (catrev cs rcs), [::lr]::rlrs).\nProof. reflexivity. Qed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cons E m c g rcs rlrs e es :\n  bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs (e::es) =\n  let '(m', c', g', cs, lr) := bit_blast_bexp_hcache E m c g e in\n  bit_blast_hbexps_hcache_conjs_rec E m' c' g'\n                                    (catrev cs rcs) ([::lr]::rlrs) es.\nProof. reflexivity. Qed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_rcons E m c g rcs rlrs es e :\n  bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs (rcons es e) =\n  let '(m', c', g', cs, lrs) := bit_blast_hbexps_hcache_conjs_rec\n                                  E m c g rcs rlrs es in\n  bit_blast_hbexps_hcache_conjs_rec E m' c' g' cs lrs [:: e].\nProof.\n  rewrite /=. elim: es m c g rcs rlrs e => [| hd tl IH] m c g rcs rlrs e //=.\n  dcase (bit_blast_bexp_hcache E m c g hd) => [[[[[m1 c1] g1] cs1] lr1] Hbb_hd].\n  rewrite -IH. reflexivity.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cat E m c g rcs rlrs es1 es2 :\n  bit_blast_hbexps_hcache_conjs_rec E m c g rcs rlrs (es1 ++ es2) =\n  let '(m', c', g', cs1, lrs1) := bit_blast_hbexps_hcache_conjs_rec\n                                    E m c g rcs rlrs es1 in\n  bit_blast_hbexps_hcache_conjs_rec E m' c' g' cs1 lrs1 es2.\nProof.\n  elim: es1 es2 m c g rcs rlrs => [| hd tl IH] es2 m c g rcs rlrs //=.\n  dcase (bit_blast_bexp_hcache E m c g hd) => [[[[[m1 c1] g1] cs1] lr1] Hbb_hd].\n  rewrite -IH. reflexivity.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_well_formed_cache\n      TE es m c g m' c' g' ics ilrs cs lrs :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE m c g ics ilrs (mapr hash_bexp es) = (m', c', g', cs, lrs) ->\n  well_formed_cache c -> well_formed_cache c'.\nProof.\n  elim: es m c g m' c' g' ics ilrs cs lrs =>\n  [| hd tl IH] im ic ig om oc og ics ilrs ocs olrs //=.\n  - case=> ? ? ? ? ?; subst. by apply.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec TE im ic ig ics ilrs (mapr hash_bexp tl))\n    => [[[[[m1 c1] g1] cs1] lrs1] Hbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE m1 c1 g1 (hash_bexp hd)) =>\n    [[[[[m2 c2] g2] cs2] lrs2] Hbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hwf_ic. move: (IH _ _ _ _ _ _ _ _ _ _ Hbb_tl Hwf_ic) => Hwf_c1.\n    exact: (bit_blast_bexp_hcache_well_formed_cache Hwf_c1 Hbb_hd).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cache_compatible\n      TE es m c g m' c' g' ics ilrs cs lrs fc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE m c g ics ilrs (mapr hash_bexp es) = (m', c', g', cs, lrs) ->\n  cache_compatible c fc -> exists fc', cache_compatible c' fc'.\nProof.\n  elim: es m c g m' c' g' ics ilrs cs lrs fc =>\n  [| hd tl IH] im ic ig om oc og ics ilrs ocs olrs fc //=.\n  - case=> ? ? ? ? ?; subst. move=> Hcomp. exists fc. assumption.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec TE im ic ig ics ilrs (mapr hash_bexp tl))\n    => [[[[[m1 c1] g1] cs1] lrs1] Hbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE m1 c1 g1 (hash_bexp hd)) =>\n    [[[[[m2 c2] g2] cs2] lrs2] Hbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hcomp. move: (IH _ _ _ _ _ _ _ _ _ _ _ Hbb_tl Hcomp) => [fc1 Hcomp_c1].\n    exact: (bit_blast_bexp_hcache_cache_compatible Hcomp_c1 Hbb_hd).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cache_compatible_chain\n      TE es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  exists ofc, exists oc, exists occ,\n        cache_compatible ohc ofc\n        /\\ CacheFlatten.cache_compatible ofc oc\n        /\\ Cache.compatible oc occ.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. move=> ? ? ? ?.\n    exists ifc. exists ic. exists icc. tauto.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec\n             TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hwfihc Hccihc Hccifc Hccic.\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _ Hhbb_tl Hwfihc Hccihc Hccifc Hccic)\n    => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 Hccc1]]]]].\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n    dcase (bit_blast_bexp_fcache TE hm1 fc1 hg1 hd) =>\n    [[[[[fm2 fc2] fg2] fcs2] flrs2] Hfbb_hd].\n    move: (bit_blast_bexp_hcache_fcache Hwfhc1 Hcchc1 Hhbb_hd Hfbb_hd)\n    => [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n    dcase (bit_blast_bexp_cache TE hm1 c1 hg1 hd) =>\n    [[[[[m2 c2] g2] cs2] lrs2] Hbb_hd]; subst.\n    move: (bit_blast_bexp_fcache_valid Hccfc1 Hfbb_hd Hbb_hd)\n    => [? [Hccfc2 [? [? ?]]]]; subst.\n    move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccc1 Hbb_hd)\n    => [cc2 [Hcbb_hd Hccc2]].\n    exists fc2. exists c2. exists cc2. tauto.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cache_compatible_chain_wf_bound\n      TE es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  exists ofc, exists oc, exists occ,\n        cache_compatible ohc ofc\n        /\\ CacheFlatten.cache_compatible ofc oc\n        /\\ Cache.compatible oc occ\n        /\\ CompCache.well_formed occ\n        /\\ CompCache.bound occ ohm.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. move=> ? ? ? ? ? ?.\n    exists ifc. exists ic. exists icc. tauto.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec\n             TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc.\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n              Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc)\n    => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 [Hccc1 [Hwfcc1 Hboundcc1]]]]]]].\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n    dcase (bit_blast_bexp_fcache TE hm1 fc1 hg1 hd) =>\n    [[[[[fm2 fc2] fg2] fcs2] flrs2] Hfbb_hd].\n    move: (bit_blast_bexp_hcache_fcache Hwfhc1 Hcchc1 Hhbb_hd Hfbb_hd)\n    => [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n    dcase (bit_blast_bexp_cache TE hm1 c1 hg1 hd) =>\n    [[[[[m2 c2] g2] cs2] lrs2] Hbb_hd]; subst.\n    move: (bit_blast_bexp_fcache_valid Hccfc1 Hfbb_hd Hbb_hd)\n    => [? [Hccfc2 [? [? ?]]]]; subst.\n    move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccc1 Hbb_hd)\n    => [cc2 [Hcbb_hd Hccc2]].\n    move: (bit_blast_bexp_ccache_bound_cache Hcbb_hd Hwfcc1 Hboundcc1) =>\n    [Hbbexpcc2 Hboundcc2].\n    move: (bit_blast_bexp_ccache_well_formed Hcbb_hd Hwfcc1) => Hwfcc2.\n    exists fc2. exists c2. exists cc2. tauto.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_preserve\n      TE es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  vm_preserve ihm ohm.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. move=> _ _ _ _. exact: vm_preserve_refl.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec TE ihm ihc ihg ihcs ihlrs\n                                             (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hwfihc Hccihc Hccifc Hccic.\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n              Hhbb_tl Hwfihc Hccihc Hccifc Hccic) => Hpre1.\n    apply: (vm_preserve_trans Hpre1).\n\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n    move: (bit_blast_hbexps_hcache_conjs_rec_cache_compatible_chain\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic)\n    => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 Hccc1]]]]].\n    exact: (bit_blast_bexp_hcache_preserve Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_cache_compatible_full\n      TE E es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  interp_cnf E (tflatten ohcs) ->\n  CompCache.interp_cache_ct E icc ->\n  CompCache.correct ihm icc ->\n  exists ofc, exists oc, exists occ,\n        cache_compatible ohc ofc\n        /\\ CacheFlatten.cache_compatible ofc oc\n        /\\ Cache.compatible oc occ\n        /\\ CompCache.well_formed occ\n        /\\ CompCache.bound occ ohm\n        /\\ CompCache.interp_cache_ct E occ\n        /\\ CompCache.correct ohm occ.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. move=> ? ? ? ? ? ? ? ? ?.\n    exists ifc. exists ic. exists icc. tauto.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec\n             TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> /andP [Hwf_hd Hwf_tl] Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n            Hcs Hcticc Hcorrihm.\n    rewrite interp_cnf_tflatten_catrev in Hcs. move/andP: Hcs => [Hhcs2 Hhcs1].\n\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n              Hhbb_tl Hwf_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n              Hhcs1 Hcticc Hcorrihm)\n    => [fc1 [c1 [cc1\n                   [Hcchc1 [Hccfc1 [Hccc1 [Hwfcc1 [Hboundcc1 [Hctcc1 Hcorrcc1]]]]]]]]].\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n    dcase (bit_blast_bexp_fcache TE hm1 fc1 hg1 hd) =>\n    [[[[[fm2 fc2] fg2] fcs2] flrs2] Hfbb_hd].\n    move: (bit_blast_bexp_hcache_fcache Hwfhc1 Hcchc1 Hhbb_hd Hfbb_hd)\n    => [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n    dcase (bit_blast_bexp_cache TE hm1 c1 hg1 hd) =>\n    [[[[[m2 c2] g2] cs2] lrs2] Hbb_hd]; subst.\n    move: (bit_blast_bexp_fcache_valid Hccfc1 Hfbb_hd Hbb_hd)\n    => [? [Hccfc2 [? [Heqs ?]]]]; subst.\n    move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccc1 Hbb_hd)\n    => [cc2 [Hcbb_hd Hccc2]].\n    move: (bit_blast_bexp_ccache_bound_cache Hcbb_hd Hwfcc1 Hboundcc1) =>\n    [Hbbexpcc2 Hboundcc2].\n    move: (bit_blast_bexp_ccache_well_formed Hcbb_hd Hwfcc1) => Hwfcc2.\n    rewrite (Heqs E) in Hhcs2.\n    move: (bit_blast_bexp_ccache_interp_cache_ct Hcbb_hd Hhcs2 Hctcc1) => Hctcc2.\n    move: (bit_blast_hbexps_hcache_conjs_rec_preserve\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic) => Hpreihm.\n    move: (bit_blast_bexp_ccache_correct_cache\n             Hcbb_hd Hwf_hd Hwfcc1 Hcorrcc1) => Hcorrcc2.\n    move: (CompCache.vm_preserve_correct Hpreihm Hcorrihm).\n    exists fc2. exists c2. exists cc2. tauto.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_bound\n      TE es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  bound_bexps es ohm.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n  dcase (bit_blast_hbexps_hcache_conjs_rec TE ihm ihc ihg ihcs ihlrs\n                                           (mapr hash_bexp tl))\n  => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n  rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n  dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n  [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n  move=> Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc.\n  move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n            Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc) => Hbbexpstlhm1.\n\n  move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n  => Hwfhc1.\n  move: (bit_blast_hbexps_hcache_conjs_rec_cache_compatible_chain_wf_bound\n           Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc)\n  => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 [Hccc1 [Hwfcc1 Hboundcc1]]]]]]].\n\n  move: (bit_blast_bexp_hcache_preserve Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1) => Hprehm1.\n  move: (vm_preserve_bound_bexps Hprehm1 Hbbexpstlhm1) => Hbbexpstlohm.\n  rewrite Hbbexpstlohm andbT.\n\n  exact: (bit_blast_bexp_hcache_bound\n            Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hwfcc1 Hboundcc1).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_adhere\n      TE es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  adhere ihm TE ->\n  adhere ohm TE.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. move=> _ _ _ _ ?; assumption.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec TE ihm ihc ihg ihcs ihlrs\n                                             (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> Hwfihc Hccihc Hccifc Hccic Hadihm.\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n              Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hadihm) => Hadhm1.\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n    move: (bit_blast_hbexps_hcache_conjs_rec_cache_compatible_chain\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic)\n    => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 Hccc1]]]]].\n    exact: (bit_blast_bexp_hcache_adhere\n              Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hadhm1).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_conform\n      TE E es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  adhere ihm TE ->\n  AdhereConform.conform_bexps es (mk_state E ohm) TE.\nProof.\n  move=> Hhbb Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc Hadihm.\n  apply: mk_state_conform_bexps.\n  - exact: (bit_blast_hbexps_hcache_conjs_rec_bound\n              Hhbb Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc).\n  - exact: (bit_blast_hbexps_hcache_conjs_adhere\n              Hhbb Hwfihc Hccihc Hccifc Hccic Hadihm).\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_conform\n      TE E es ohm ohc ohg ohcs ohlrs :\n  bit_blast_hbexps_hcache_conjs\n    TE init_vm init_hcache init_gen (mapr hash_bexp es) =\n  (ohm, ohc, ohg, ohcs, ohlrs) ->\n  AdhereConform.conform_bexps es (mk_state E ohm) TE.\nProof.\n  move=> Hbb.\n  exact: (bit_blast_hbexps_hcache_conjs_rec_conform\n            E Hbb init_hcache_well_formed init_hcache_fcache_compatible\n            init_fcache_compatible init_compatible init_ccache_well_formed\n            init_bound_cache (init_vm_adhere TE)).\nQed.\n\n\n\nFixpoint mk_conjs_rec res es :=\n  match es with\n  | [::] => res\n  | hd::tl => mk_conjs_rec (QFBV.Bconj res hd) tl\n  end.\n\nDefinition mk_conjs es :=\n  match es with\n  | [::] => QFBV.Btrue\n  | hd::tl => mk_conjs_rec hd tl\n  end.\n\nLemma mk_conjs_rec_rcons res es e :\n  mk_conjs_rec res (rcons es e) = QFBV.Bconj (mk_conjs_rec res es) e.\nProof.\n  by elim: es res e => [| hd tl IH] res e //=.\nQed.\n\nLemma mk_conjs_rcons es e :\n  mk_conjs (rcons es e) = if es == [::] then e\n                          else QFBV.Bconj (mk_conjs es) e.\nProof.\n  case: es e => [| hd tl] e //=. rewrite mk_conjs_rec_rcons.\n  reflexivity.\nQed.\n\nLemma mk_conjs_rec_eval s res es :\n  QFBV.eval_bexp (mk_conjs_rec res es) s = QFBV.eval_bexp res s\n                                           && (QFBV.eval_bexp (mk_conjs es) s).\nProof.\n  move: es res. apply: last_ind => //=.\n  - move=> res. rewrite andbT. reflexivity.\n  - move=> es e IH res. rewrite mk_conjs_rec_rcons /=.\n    rewrite {}IH. case: (QFBV.eval_bexp res s) => //=.\n    rewrite mk_conjs_rcons /=. by case: es.\nQed.\n\nLemma mk_conjs_eval_cons s e es :\n  QFBV.eval_bexp (mk_conjs (e::es)) s = QFBV.eval_bexp e s\n                                        && (QFBV.eval_bexp (mk_conjs es) s).\nProof.\n  rewrite /=. rewrite mk_conjs_rec_eval. reflexivity.\nQed.\n\nLemma mk_conjs_eval es s :\n  QFBV.eval_bexp (mk_conjs es) s <-> forall e, e \\in es -> QFBV.eval_bexp e s.\nProof.\n  elim: es => [| hd tl IH] //=. rewrite mk_conjs_rec_eval. split.\n  - move/andP=> [Hhd Htl]. move=> e Hin. rewrite in_cons in Hin.\n    case/orP: Hin => Hin.\n    + rewrite (eqP Hin). assumption.\n    + exact: ((proj1 IH) Htl e Hin).\n  - move=> H. rewrite (H hd (mem_head hd tl)) /=.\n    apply: (proj2 IH). move=> e Hin; apply: H. rewrite in_cons Hin orbT.\n    reflexivity.\nQed.\n\nLemma bound_bexps_rcons es e m :\n  bound_bexps (rcons es e) m = (bound_bexps es m) && (bound_bexp e m).\nProof.\n  elim: es e => [| hd tl IH] e //=.\n  - rewrite andbT. reflexivity.\n  - rewrite IH. rewrite Bool.andb_assoc. reflexivity.\nQed.\n\nLemma mk_conjs_rec_bound res es m :\n  bound_bexp res m ->\n  bound_bexps es m ->\n  bound_bexp (mk_conjs_rec res es) m.\nProof.\n  move: es res. apply: last_ind => //=. move=> es e IH res Hbb_res.\n  rewrite bound_bexps_rcons. move/andP=> [Hbb_es Hbb_e].\n  rewrite mk_conjs_rec_rcons /=. by rewrite (IH _ Hbb_res Hbb_es) Hbb_e.\nQed.\n\nLemma mk_conjs_bound es m :\n  bound_bexps es m ->\n  bound_bexp (mk_conjs es) m.\nProof.\n  case: es => //=. move=> e es /andP [Hbb_e Hbb_es].\n  exact: (mk_conjs_rec_bound Hbb_e Hbb_es).\nQed.\n\nLemma mk_conjs_rec_conform e es s E :\n  conform_bexp (mk_conjs_rec e es) s E =\n  conform_bexp e s E && conform_bexp (mk_conjs es) s E.\nProof.\n  move: es e. apply: last_ind => /=.\n  - move=> e. rewrite andbT. reflexivity.\n  - move=> es le IH e. rewrite mk_conjs_rec_rcons /=. rewrite {}IH.\n    case: (conform_bexp e s E) => //=. rewrite mk_conjs_rcons. by case: es.\nQed.\n\nLemma mk_conjs_conform es s E :\n  conform_bexp (mk_conjs es) s E = conform_bexps es s E.\nProof.\n  elim: es => [| e es IH] //=. rewrite mk_conjs_rec_conform IH. reflexivity.\nQed.\n\nLemma mk_conjs_rec_well_formed TE e es :\n  QFBV.well_formed_bexp (mk_conjs_rec e es) TE =\n  QFBV.well_formed_bexp e TE && QFBV.well_formed_bexps es TE.\nProof.\n  move: es. apply: last_ind => /=.\n  - rewrite andbT. reflexivity.\n  - move=> es le IH. rewrite mk_conjs_rec_rcons /=. rewrite IH.\n    rewrite QFBV.well_formed_bexps_rcons. rewrite andbA. reflexivity.\nQed.\n\nLemma mk_conjs_well_formed TE es :\n  QFBV.well_formed_bexp (mk_conjs es) TE = QFBV.well_formed_bexps es TE.\nProof.\n  case: es => [| e es] //=. rewrite mk_conjs_rec_well_formed. reflexivity.\nQed.\n\n\n\nDefinition size1 {A : Type} (s : seq A) :=\n  size s == 1.\n\nLemma size1_singleton {A : Type} (s : seq A) :\n  size1 s -> exists x, s = [:: x].\nProof. case: s => [| x1 s] //=. case: s => //=. move=> _. by exists x1. Qed.\n\nLemma interp_cnf_interp_word E cs :\n  interp_cnf E cs ->\n  all size1 cs ->\n  interp_word E (tflatten cs) = ones (size cs).\nProof.\n  elim: cs => [| c cs IH] //=. move/andP=> [Hc Hcs]. move/andP=> [Hsc Hscs].\n  rewrite tflatten_cons. move: (size1_singleton Hsc) => [x Heq]; subst.\n  rewrite /rev /=. rewrite cats1. rewrite interp_word_rcons.\n  rewrite ones_cons. rewrite -ones_rcons. rewrite /= orbF in Hc.\n  rewrite Hc. rewrite (IH Hcs Hscs). reflexivity.\nQed.\n\nLemma enc_bits_eval_conjs E s ohlrs es:\n  interp_cnf E ohlrs ->\n  all size1 ohlrs ->\n  enc_bits E (tflatten ohlrs) (mapr (fun e => QFBV.eval_bexp e s) es) ->\n  QFBV.eval_bexp (mk_conjs es) s.\nProof.\n  move=> Hcs Hs. rewrite /enc_bits. rewrite (interp_cnf_interp_word Hcs Hs).\n  clear Hcs Hs. elim: es ohlrs => [| e es IH] ohlrs //=.\n  rewrite mapr_cons. case: ohlrs => [| lr ohlrs] //=.\n  - move/eqP=> H. have Heq: size ([::] : cnf) =\n                            size (rcons\n                                    (mapr\n                                       (QFBV.eval_bexp^~ s) es) (QFBV.eval_bexp e s))\n    by rewrite -H. rewrite size_rcons in Heq. discriminate.\n  - rewrite ones_cons -ones_rcons. rewrite mk_conjs_rec_eval.\n    move/eqP=> H. move: (rcons_inj H) => {H} [] /eqP H1 H2.\n    rewrite -H2 andTb. exact: (IH _ H1).\nQed.\n\n\n\nLemma bit_blast_hbexps_hcache_conjs_rec_enc_bits\n      TE E es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc s ies :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  adhere ihm TE ->\n  interp_cnf E (add_prelude (tflatten (ohlrs :: ohcs))) ->\n  CompCache.interp_cache_ct E icc ->\n  CompCache.correct ihm icc ->\n  AdhereConform.conform_bexps es s TE ->\n  consistent ohm E s ->\n  enc_bits E (tflatten ihlrs) (mapr (fun e => QFBV.eval_bexp e s) ies) ->\n  enc_bits E (tflatten ohlrs) (mapr (fun e => QFBV.eval_bexp e s) (es ++ ies)).\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  - case=> ? ? ? ? ?; subst. done.\n  - rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n    dcase (bit_blast_hbexps_hcache_conjs_rec TE ihm ihc ihg ihcs ihlrs\n                                             (mapr hash_bexp tl))\n    => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n    rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n    dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n    [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n    move=> /andP [Hwf_hd Hwf_tl] Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n          Hadihm Hsat Hcticc Hcorricc /andP [Hco_hd Hco_tl] Hcoohm Hencihlrs.\n    move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n    => Hwfhc1.\n\n    rewrite interp_cnf_cons /= orbF in Hsat.\n    move/andP: Hsat=> [Hsat_tt Hsat].\n    rewrite interp_cnf_tflatten_cons in Hsat.\n    move/andP: Hsat=> [Hsat1 Hsat2].\n    rewrite interp_cnf_cons /= orbF in Hsat1.\n    move/andP: Hsat1=> [Hsat_olr Hsat_hlrs1].\n    rewrite interp_cnf_tflatten_catrev in Hsat2.\n    move/andP: Hsat2=> [Hsat_ofcs Hsat_hcs1].\n\n    move: (bit_blast_hbexps_hcache_conjs_rec_cache_compatible_full\n             Hhbb_tl Hwf_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n             Hsat_hcs1 Hcticc Hcorricc)\n    => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 [Hccc1 [Hwfcc1\n                                               [Hboundcc1 [Hctcc1 Hcorrcc1]]]]]]]]].\n    move: (bit_blast_hbexps_hcache_conjs_rec_bound\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc) => Hbbexp_tlhm1.\n    move: (bit_blast_bexp_hcache_preserve Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1)\n    => Hprehm1.\n    move: (bit_blast_bexp_hcache_bound\n             Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hwfcc1 Hboundcc1)\n    => Hbbexp_hdohm.\n\n    dcase (bit_blast_bexp_fcache TE hm1 fc1 hg1 hd) =>\n    [[[[[ofm ofc] ofg] ofcs] oflr] Hfbb_hd].\n    move: (bit_blast_bexp_hcache_fcache Hwfhc1 Hcchc1 Hhbb_hd Hfbb_hd) =>\n    [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n    dcase (bit_blast_bexp_cache TE hm1 c1 hg1 hd) =>\n    [[[[[om oc] og] ocs] olr] Hbb_hd].\n    move: (bit_blast_bexp_fcache_valid Hccfc1 Hfbb_hd Hbb_hd) =>\n    [? [Hccofc [? [Heqs [Heqn ?]]]]]; subst.\n    move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccc1 Hbb_hd)\n    => [cicc [Hcbb_hd Hccoc]].\n    move: (bit_blast_hbexps_hcache_conjs_adhere\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hadihm) => Hadhm1.\n    move: (bit_blast_bexp_hcache_adhere\n             Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hadhm1) => Hadohm.\n\n    rewrite (Heqs E) in Hsat_ofcs.\n\n    move: (bit_blast_bexp_ccache_correct\n             Hcbb_hd Hco_hd Hcoohm Hwf_hd Hwfcc1 (add_prelude_to Hsat_tt Hsat_ofcs)\n             Hctcc1 Hcorrcc1) => Hencolr.\n\n    rewrite tflatten_cons. rewrite {1}/rev /=. rewrite cats1.\n    rewrite mapr_cons. rewrite enc_bits_rcons.\n    rewrite Hencolr andbT.\n    move: (vm_preserve_consistent Hprehm1 Hcoohm) => Hcohm1.\n    apply: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n               Hhbb_tl Hwf_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n               Hadihm _ Hcticc Hcorricc Hco_tl Hcohm1 Hencihlrs).\n    rewrite add_prelude_expand interp_cnf_tflatten_cons /=.\n    rewrite Hsat_tt /=. by rewrite Hsat_hlrs1 Hsat_hcs1.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_enc_bits\n      TE E es ohm ohc ohg ohcs ohlrs s :\n  bit_blast_hbexps_hcache_conjs\n    TE init_vm init_hcache init_gen\n    (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  interp_cnf E (add_prelude (tflatten (ohlrs :: ohcs))) ->\n  AdhereConform.conform_bexps es s TE ->\n  consistent ohm E s ->\n  enc_bits E (tflatten ohlrs) (mapr (fun e => QFBV.eval_bexp e s) es).\nProof.\n  move=> Hbb Hwf_es Hcs Hco_es Hcoohm. rewrite -(cats0 es).\n  apply: (bit_blast_hbexps_hcache_conjs_rec_enc_bits\n            Hbb Hwf_es init_hcache_well_formed init_hcache_fcache_compatible\n            init_fcache_compatible init_compatible init_ccache_well_formed\n            init_bound_cache (init_vm_adhere TE) Hcs (init_interp_cache_ct E)\n            (init_correct init_vm) Hco_es Hcoohm). done.\nQed.\n\n\nLemma bit_blast_hbexps_hcache_conjs_rec_eval_conjs\n      TE E es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc s :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  adhere ihm TE ->\n  interp_cnf E (add_prelude (tflatten (ohlrs :: ohcs))) ->\n  CompCache.interp_cache_ct E icc ->\n  CompCache.correct ihm icc ->\n  AdhereConform.conform_bexps es s TE ->\n  consistent ohm E s ->\n  QFBV.eval_bexp (mk_conjs es) s.\nProof.\n  elim: es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc =>\n  [| hd tl IH] ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc //=.\n  rewrite mapr_cons. rewrite bit_blast_hbexps_hcache_conjs_rec_rcons.\n  dcase (bit_blast_hbexps_hcache_conjs_rec TE ihm ihc ihg ihcs ihlrs\n                                           (mapr hash_bexp tl))\n  => [[[[[hm1 hc1] hg1] hcs1] hlrs1] Hhbb_tl].\n  rewrite bit_blast_hbexps_hcache_conjs_rec_singleton.\n  dcase (bit_blast_bexp_hcache TE hm1 hc1 hg1 (hash_bexp hd)) =>\n  [[[[[hm2 hc2] hg2] hcs2] hlrs2] Hhbb_hd]. case=> ? ? ? ? ?; subst.\n  move=> /andP [Hwf_hd Hwf_tl] Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n          Hadihm Hsat Hcticc Hcorricc /andP [Hco_hd Hco_tl] Hcoohm.\n  move: (bit_blast_hbexps_hcache_conjs_rec_well_formed_cache Hhbb_tl Hwfihc)\n  => Hwfhc1.\n\n  rewrite interp_cnf_cons /= orbF in Hsat.\n  move/andP: Hsat=> [Hsat_tt Hsat].\n  rewrite interp_cnf_tflatten_cons in Hsat.\n  move/andP: Hsat=> [Hsat1 Hsat2].\n  rewrite interp_cnf_cons /= orbF in Hsat1.\n  move/andP: Hsat1=> [Hsat_olr Hsat_hlrs1].\n  rewrite interp_cnf_tflatten_catrev in Hsat2.\n  move/andP: Hsat2=> [Hsat_ofcs Hsat_hcs1].\n\n  move: (bit_blast_hbexps_hcache_conjs_rec_cache_compatible_full\n           Hhbb_tl Hwf_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n           Hsat_hcs1 Hcticc Hcorricc)\n  => [fc1 [c1 [cc1 [Hcchc1 [Hccfc1 [Hccc1 [Hwfcc1 [Hboundcc1 [Hctcc1 Hcorrcc1]]]]]]]]].\n  move: (bit_blast_hbexps_hcache_conjs_rec_bound\n           Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc) => Hbbexp_tlhm1.\n  move: (bit_blast_bexp_hcache_preserve Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1)\n  => Hprehm1.\n  move: (bit_blast_bexp_hcache_bound\n           Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hwfcc1 Hboundcc1)\n  => Hbbexp_hdohm.\n\n  rewrite mk_conjs_rec_eval. apply/andP; split.\n  - dcase (bit_blast_bexp_fcache TE hm1 fc1 hg1 hd) =>\n    [[[[[ofm ofc] ofg] ofcs] oflr] Hfbb_hd].\n    move: (bit_blast_bexp_hcache_fcache Hwfhc1 Hcchc1 Hhbb_hd Hfbb_hd) =>\n    [? [Hwfohc [Hccohc [? [? ?]]]]]; subst.\n    dcase (bit_blast_bexp_cache TE hm1 c1 hg1 hd) =>\n    [[[[[om oc] og] ocs] olr] Hbb_hd].\n    move: (bit_blast_bexp_fcache_valid Hccfc1 Hfbb_hd Hbb_hd) =>\n    [? [Hccofc [? [Heqs [Heqn ?]]]]]; subst.\n    move: (bit_blast_bexp_cache_is_bit_blast_bexp_ccache Hccc1 Hbb_hd)\n    => [cicc [Hcbb_hd Hccoc]].\n    move: (bit_blast_hbexps_hcache_conjs_adhere\n             Hhbb_tl Hwfihc Hccihc Hccifc Hccic Hadihm) => Hadhm1.\n    move: (bit_blast_bexp_hcache_adhere\n             Hhbb_hd Hwfhc1 Hcchc1 Hccfc1 Hccc1 Hadhm1) => Hadohm.\n\n    rewrite (Heqs E) in Hsat_ofcs.\n\n    move: (bit_blast_bexp_ccache_correct\n             Hcbb_hd Hco_hd Hcoohm Hwf_hd Hwfcc1 (add_prelude_to Hsat_tt Hsat_ofcs)\n             Hctcc1 Hcorrcc1).\n    rewrite /enc_bit. rewrite Hsat_olr. rewrite eq_sym. by move/eqP=> ->.\n  - move: (vm_preserve_consistent Hprehm1 Hcoohm) => Hcohm1.\n    apply: (IH _ _ _ _ _ _ _ _ _ _ _ _ _\n               Hhbb_tl Hwf_tl Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n               Hadihm _ Hcticc Hcorricc Hco_tl Hcohm1).\n    rewrite add_prelude_expand interp_cnf_tflatten_cons /=.\n    rewrite Hsat_tt /=. by rewrite Hsat_hlrs1 Hsat_hcs1.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_mk_state\n      TE E es ihm ihc ihg ihcs ihlrs ohm ohc ohg ohcs ohlrs ifc ic icc :\n  bit_blast_hbexps_hcache_conjs_rec\n    TE ihm ihc ihg ihcs ihlrs (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  well_formed_cache ihc ->\n  cache_compatible ihc ifc ->\n  CacheFlatten.cache_compatible ifc ic ->\n  Cache.compatible ic icc ->\n  CompCache.well_formed icc ->\n  CompCache.bound icc ihm ->\n  adhere ihm TE ->\n  interp_cnf E (add_prelude (tflatten (ohlrs :: ohcs))) ->\n  CompCache.interp_cache_ct E icc ->\n  CompCache.correct ihm icc ->\n  QFBV.eval_bexp (mk_conjs es) (mk_state E ohm).\nProof.\n  move=> Hbb Hwf_es Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc\n             Hadihm Hcs Hcticc Hcorricc.\n  apply: (bit_blast_hbexps_hcache_conjs_rec_eval_conjs\n            Hbb Hwf_es Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc Hadihm\n            Hcs Hcticc Hcorricc).\n  - exact: (bit_blast_hbexps_hcache_conjs_rec_conform\n              _ Hbb Hwfihc Hccihc Hccifc Hccic Hwficc Hboundicc Hadihm).\n  - exact: mk_state_consistent.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_mk_state\n      TE E es ohm ohc ohg ohcs ohlrs :\n  bit_blast_hbexps_hcache_conjs\n    TE init_vm init_hcache init_gen\n    (mapr hash_bexp es) = (ohm, ohc, ohg, ohcs, ohlrs) ->\n  QFBV.well_formed_bexps es TE ->\n  interp_cnf E (add_prelude (tflatten (ohlrs :: ohcs))) ->\n  QFBV.eval_bexp (mk_conjs es) (mk_state E ohm).\nProof.\n  rewrite /bit_blast_hbexps_hcache_conjs. move=> Hbb Hwf Hcs.\n  exact: (bit_blast_hbexps_hcache_conjs_rec_mk_state\n            Hbb Hwf init_hcache_well_formed init_hcache_fcache_compatible\n            init_fcache_compatible init_compatible init_ccache_well_formed\n            init_bound_cache (init_vm_adhere TE) Hcs\n            (init_interp_cache_ct E) (init_correct init_vm)).\nQed.\n\n\n(* Soundness of bit_blast_hbexps_hcache_conjs *)\n\nLemma bit_blast_hbexps_hcache_conjs_sat_sound TE es m c g cs lrs :\n  bit_blast_hbexps_hcache_conjs\n    TE init_vm init_hcache init_gen (mapr hash_bexp es) = (m, c, g, cs, lrs) ->\n  QFBV.well_formed_bexps es TE ->\n  (sat (add_prelude (tflatten (lrs::cs)))) ->\n  (exists s, AdhereConform.conform_bexps es s TE /\\\n             QFBV.eval_bexp (mk_conjs es) s).\nProof.\n  move=> Hhbb Hwf [E Hcs]. exists (mk_state E m). split.\n  - exact: (bit_blast_hbexps_hcache_conjs_conform _ Hhbb).\n  - exact: (bit_blast_hbexps_hcache_conjs_mk_state Hhbb Hwf Hcs).\nQed.\n\n\n\nDefinition bit_blast_bexps_hcache_conjs TE es : vm * cache * generator * cnf :=\n  let '(m', c', g', cs, lrs) :=\n      bit_blast_hbexps_hcache_conjs\n        TE init_vm init_hcache init_gen (mapr hash_bexp es) in\n  (m', c', g', add_prelude (tflatten (lrs::cs))).\n\nTheorem bit_blast_bexps_hcache_conjs_sat_sound TE es :\n  let '(m, c, g, cs) := bit_blast_bexps_hcache_conjs TE es in\n  QFBV.well_formed_bexps es TE ->\n  sat cs ->\n  (exists s, AdhereConform.conform_bexps es s TE /\\\n             QFBV.eval_bexp (mk_conjs es) s).\nProof.\n  rewrite /bit_blast_bexps_hcache_conjs.\n  dcase (bit_blast_hbexps_hcache_conjs\n           TE init_vm init_hcache init_gen\n           (mapr hash_bexp es)) => [[[[[m c] g] cs] lrs] Hbb].\n  move=> Hwf Hsat. exact: (bit_blast_hbexps_hcache_conjs_sat_sound Hbb Hwf Hsat).\nQed.\n\n\n(**)\n\nLemma init_hcache_hccache_compatible :\n  compatible init_hcache init_hccache.\nProof. done. Qed.\n\nLtac dcase_bb_base :=\n  match goal with\n  | |- context f [bit_blast_var ?E ?g ?v] =>\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_var E g v) => [[[g' cs] lrs] H]\n  | |- context f [bit_blast_eunop ?op ?g ?lrs] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (bit_blast_eunop op g lrs) => [[[g' cs'] lrs'] H]\n  | |- context f [bit_blast_ebinop ?op ?g ?lrs1 ?lrs2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (bit_blast_ebinop op g lrs1 lrs2) => [[[g' cs'] lrs'] H]\n  | |- context f [bit_blast_ite ?g ?lr ?ls1 ?ls2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (bit_blast_ite g lr ls1 ls2) => [[[g' cs'] lr'] H]\n  | |- context f [bit_blast_bbinop ?op ?g ?lrs1 ?lrs2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (bit_blast_bbinop op g lrs1 lrs2) => [[[g' cs'] lr'] H]\n  end.\n\nLtac dcase_bb_cache :=\n  match goal with\n  (**)\n  | |- context f [find_cet ?e ?c] =>\n    let Hfe_cet := fresh in\n    let lrs := fresh in\n    dcase (find_cet e c); case=> [lrs|] Hfe_cet\n  | |- context f [find_cbt ?e ?c] =>\n    let Hfe_cbt := fresh in\n    let lr := fresh in\n    dcase (find_cbt e c); case=> [lr|] Hfe_cbt\n  | |- context f [find_het ?e ?c] =>\n    let Hfe_het := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (find_het e c); case=> [[cs lrs]|] Hfe_het\n  | |- context f [find_hbt ?e ?c] =>\n    let Hfe_hbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (find_hbt e c); case=> [[cs lr]|] Hfe_hbt\n  (**)\n  | |- context f [SSAVM.find ?v ?m] =>\n    let lrs := fresh in\n    case: (SSAVM.find v m) => [lrs|]\n  | |- context f [bit_blast_exp_hcache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_hcache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_hcache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_hcache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lr] H]\n  | |- context f [bit_blast_exp_fcache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_fcache E m c g e) =>\n    [[[[[m' c'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_fcache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_fcache E m c g e) =>\n    [[[[[m' c'] g'] cs] lr] H]\n  (**)\n  | |- _ => dcase_bb_base\n  end.\n\nLtac dcase_bb_ccache :=\n  match goal with\n  | |- context f [find_cet ?e ?c] =>\n    let Hfe_cet := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (find_cet e c); case=> [[cs lrs]|] Hfe_cet\n  | |- context f [find_cbt ?e ?c] =>\n    let Hfe_cbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (find_cbt e c); case=> [[cs lr]|] Hfe_cbt\n  | |- context f [find_het ?e ?c] =>\n    let Hfe_het := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (find_het e c); case=> [[cs lrs]|] Hfe_het\n  | |- context f [find_hbt ?e ?c] =>\n    let Hfe_hbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (find_hbt e c); case=> [[cs lr]|] Hfe_hbt\n  (**)\n  | |- context f [SSAVM.find ?v ?m] =>\n    let lrs := fresh in\n    case: (SSAVM.find v m) => [lrs|]\n  | |- context f [bit_blast_exp_hccache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_hccache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_hccache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_hccache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lr] H]\n  | |- context f [bit_blast_exp_fccache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_fccache E m c g e) =>\n    [[[[[m' c'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_fccache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_fccache E m c g e) =>\n    [[[[[m' c'] g'] cs] lr] H]\n  (**)\n  | |- _ => dcase_bb_base\n  end.\n\nLtac myauto ::=\n  repeat\n    match goal with\n    | |- _ /\\ _ => split\n    | |- ?e = ?e => reflexivity\n    | H : ?p |- ?p => assumption\n    | |- (_, _, _, _, _, _) = (_, _, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ? ?; subst\n    | |- (_, _, _, _, _) = (_, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ?; subst\n    | H1 : ?e = Some _, H2 : ?e = None |- _ =>\n      rewrite H1 in H2; discriminate\n    (**)\n    | Hc : compatible ?oc ?cc,\n      Hf : find_cet ?e ?oc = Some _\n      |- context [CCacheHash.find_cet ?e ?cc] =>\n      let cs := fresh in\n      let H := fresh in\n      (move: (CacheHash.compatible_find_cet_some Hc Hf) => [cs H]);\n      rewrite H; clear Hf\n    | Hc : compatible ?oc ?cc,\n      Hf : find_cet ?e ?oc = None\n      |- context [CCacheHash.find_cet ?e ?cc] =>\n      let H := fresh in\n      (move: (CacheHash.compatible_find_cet_none Hc Hf) => H);\n      rewrite H; clear Hf\n    | Hc : compatible ?oc ?cc,\n      Hf : find_cbt ?e ?oc = Some _\n      |- context [CCacheHash.find_cbt ?e ?cc] =>\n      let cs := fresh in\n      let H := fresh in\n      (move: (CacheHash.compatible_find_cbt_some Hc Hf) => [cs H]);\n      rewrite H; clear Hf\n    | Hc : compatible ?oc ?cc,\n      Hf : find_cbt ?e ?oc = None\n      |- context [CCacheHash.find_cbt ?e ?cc] =>\n      let H := fresh in\n      (move: (CacheHash.compatible_find_cbt_none Hc Hf) => H);\n      rewrite H; clear Hf\n    | Hc : compatible ?oc ?cc |- context [CCacheHash.find_het ?e ?cc] =>\n      rewrite -(compatible_find_het e Hc)\n    | Hc : compatible ?oc ?cc |- context [CCacheHash.find_hbt ?e ?cc] =>\n      rewrite -(compatible_find_hbt e Hc)\n    (**)\n    | Hf : find_cet ?e ?oc = _ |- context [find_cet ?e ?oc] => rewrite Hf\n    | Hf : find_cbt ?e ?oc = _ |- context [find_cbt ?e ?oc] => rewrite Hf\n    | Hf : find_het ?e ?oc = _ |- context [find_het ?e ?oc] => rewrite Hf\n    | Hf : find_hbt ?e ?oc = _ |- context [find_hbt ?e ?oc] => rewrite Hf\n    (* apply induction hypothesis *)\n    | bit_blast_exp_hcache_is_bit_blast_exp_hccache :\n        (forall (TE : SSATE.env)\n                (m : vm) (c : cache)\n                (cc : CCacheHash.ccache)\n                (g : generator) (e : hexp)\n                (om : vm) (oc : cache)\n                (og : generator)\n                (ocs : seq cnf) (olrs : word),\n            compatible c cc ->\n            bit_blast_exp_hcache TE m c g e =\n            (om, oc, og, ocs, olrs) ->\n            exists occ : CCacheHash.ccache,\n              bit_blast_exp_hccache TE m cc g e =\n              (om, occ, og, ocs, olrs) /\\\n              compatible oc occ),\n        Hc : compatible ?c ?cc,\n        Hbb : bit_blast_exp_hcache ?TE ?m ?c ?g ?e = _ |- _ =>\n      let occ := fresh in\n      let Hcbb := fresh in\n      let Hcc := fresh in\n      move: (bit_blast_exp_hcache_is_bit_blast_exp_hccache\n               _ _ _ _ _ _ _ _ _ _ _ Hc Hbb) => [occ [Hcbb Hcc]]; clear Hbb\n    | bit_blast_bexp_hcache_is_bit_blast_bexp_hccache :\n        (forall (TE : SSATE.env)\n                (m : vm) (c : cache)\n                (cc : CCacheHash.ccache)\n                (g : generator)\n                (e : hbexp) (om : vm)\n                (oc : cache) (og : generator)\n                (ocs : seq cnf)\n                (olrs : literal),\n            compatible c cc ->\n            bit_blast_bexp_hcache TE m c g e =\n            (om, oc, og, ocs, olrs) ->\n            exists occ : CCacheHash.ccache,\n              bit_blast_bexp_hccache TE m cc g e =\n              (om, occ, og, ocs, olrs) /\\\n              compatible oc occ),\n        Hc : compatible ?c ?cc,\n        Hbb : bit_blast_bexp_hcache ?TE ?m ?c ?g ?e = _ |- _ =>\n      let occ := fresh in\n      let Hcbb := fresh in\n      let Hcc := fresh in\n      move: (bit_blast_bexp_hcache_is_bit_blast_bexp_hccache\n               _ _ _ _ _ _ _ _ _ _ _ Hc Hbb) => [occ [Hcbb Hcc]]; clear Hbb\n    (**)\n    | H1 : bit_blast_eunop ?op ?g ?ls = _,\n      H2 : bit_blast_eunop ?op ?g ?ls = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ?; subst\n    | H1 : bit_blast_ebinop ?op ?g ?ls1 ?ls2 = _,\n      H2 : bit_blast_ebinop ?op ?g ?ls1 ?ls2 = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ?; subst\n    | H1 : bit_blast_ite ?g ?c ?ls1 ?ls2 = _,\n      H2 : bit_blast_ite ?g ?c ?ls1 ?ls2 = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ?; subst\n    | H1 : bit_blast_exp_hccache ?TE ?m ?cc ?g ?e = _,\n      H2 : bit_blast_exp_hccache ?TE ?m ?cc ?g ?e = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ? ? ?; subst\n    | H1 : bit_blast_bexp_hccache ?TE ?m ?cc ?g ?e = _,\n      H2 : bit_blast_bexp_hccache ?TE ?m ?cc ?g ?e = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ? ? ?; subst\n    | H1 : bit_blast_bbinop ?op ?g ?ls1 ?ls2 = _,\n      H2 : bit_blast_bbinop ?op ?g ?ls1 ?ls2 = _ |- _ =>\n      (rewrite H1 in H2); case: H2 => ? ? ?; subst\n    (**)\n    | |- exists occ : CCacheHash.ccache,\n        (?om, ?cc, ?og, ?ocs, ?olrs) = (?om, occ, ?og, ?ocs, ?olrs) /\\ compatible _ occ =>\n      exists cc; (split; first try done)\n    | |- compatible (add_cet ?e ?olrs ?c) (CCacheHash.add_cet ?e ?ocs ?olrs ?cc) =>\n      apply: compatible_add_cet\n    | |- compatible (add_cbt ?e ?olr ?c) (CCacheHash.add_cbt ?e ?ocs ?olrb ?cc) =>\n      apply: compatible_add_cbt\n    | |- compatible (add_het ?e ?ocs ?olrs ?c) (CCacheHash.add_het ?e ?ocs ?olrs ?cc) =>\n      apply: compatible_add_het\n    | |- compatible (add_hbt ?e ?ocs ?olr ?c) (CCacheHash.add_hbt ?e ?ocs ?olr ?cc) =>\n      apply: compatible_add_hbt\n    (**)\n    | |- _ => dcase_bb_cache || dcase_bb_ccache\n    end.\n\nLemma bit_blast_exp_hcache_is_bit_blast_exp_hccache\n      TE m c cc g e om oc og ocs olrs :\n  CacheHash.compatible c cc ->\n  bit_blast_exp_hcache TE m c g e = (om, oc, og, ocs, olrs) ->\n  exists occ,\n    bit_blast_exp_hccache TE m cc g e = (om, occ, og, ocs, olrs)\n    /\\ CacheHash.compatible oc occ\nwith\n  bit_blast_bexp_hcache_is_bit_blast_bexp_hccache\n      TE m c cc g e om oc og ocs olrs :\n  CacheHash.compatible c cc ->\n  bit_blast_bexp_hcache TE m c g e = (om, oc, og, ocs, olrs) ->\n  exists occ,\n    bit_blast_bexp_hccache TE m cc g e = (om, occ, og, ocs, olrs)\n    /\\ CacheHash.compatible oc occ.\nProof.\n  (* bit_blast_exp_hcache_is_bit_blast_exp_hccache *)\n  case: e. case=> //=.\n  - move=> v z Hcc. by myauto.\n  - move=> bs z Hcc. by myauto.\n  - move=> op e z Hcc. by myauto.\n  - move=> op e1 e2 z Hcc. by myauto.\n  - move=> e1 e2 e3 z Hcc. by myauto.\n  (* bit_blast_bexp_hcache_is_bit_blast_bexp_hccache *)\n  case: e. case=> //=.\n  - move=> z Hcc. by myauto.\n  - move=> z Hcc. by myauto.\n  - move=> op e1 e2 z Hcc. by myauto.\n  - move=> e z Hcc. by myauto.\n  - move=> e1 e2 z Hcc. by myauto.\n  - move=> e1 e2 z Hcc. by myauto.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_rec_is_bit_blast_hbexps_hccache_conjs_rec\n      TE m c cc g rcs rlrs es om oc og ocs olrs :\n  CacheHash.compatible c cc ->\n  bit_blast_hbexps_hcache_conjs_rec TE m c g rcs rlrs es = (om, oc, og, ocs, olrs) ->\n  exists occ,\n    bit_blast_hbexps_hccache_conjs_rec TE m cc g rcs rlrs es = (om, occ, og, ocs, olrs)\n    /\\ CacheHash.compatible oc occ.\nProof.\n  elim: es m c cc g rcs rlrs om oc og ocs olrs\n  => [| e es IH] //= im ic icc ig ircs irlrs om oc og ocs olrs Hcc.\n  - case=> ? ? ? ? ?; subst. exists icc. done.\n  - dcase (bit_blast_bexp_hcache TE im ic ig e) => [[[[[m1 c1] g1] cs1] lrs1] Hbb1] Hbb2.\n    move: (bit_blast_bexp_hcache_is_bit_blast_bexp_hccache Hcc Hbb1) => [cc1 [Hcbb1 Hcc1]].\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ Hcc1 Hbb2) => [cc2 [Hcbb2 Hcc2]].\n    exists cc2. rewrite Hcbb1 Hcbb2. done.\nQed.\n\nLemma bit_blast_hbexps_hcache_conjs_is_bit_blast_hbexps_hccache_conjs\n      TE m c cc g es om oc og ocs olrs :\n  CacheHash.compatible c cc ->\n  bit_blast_hbexps_hcache_conjs TE m c g es = (om, oc, og, ocs, olrs) ->\n  exists occ,\n    bit_blast_hbexps_hccache_conjs TE m cc g es = (om, occ, og, ocs, olrs)\n    /\\ CacheHash.compatible oc occ.\nProof. exact: bit_blast_hbexps_hcache_conjs_rec_is_bit_blast_hbexps_hccache_conjs_rec. Qed.\n\n\n\n(* Completeness of bit_blast_hbexps_hcache_conjs *)\n\n\nLemma bit_blast_hbexps_hcache_conjs_sat_complete TE es m c g cs lrs :\n  bit_blast_hbexps_hcache_conjs\n    TE init_vm init_hcache init_gen (mapr hash_bexp es) = (m, c, g, cs, lrs) ->\n  QFBV.well_formed_bexps es TE ->\n  (exists s, AdhereConform.conform_bexps es s TE /\\\n             QFBV.eval_bexp (mk_conjs es) s) ->\n  (sat (add_prelude (tflatten (lrs::cs)))).\nProof.\n  move=> Hbb Hwf Hev.\n  move: (bit_blast_hbexps_hcache_conjs_is_bit_blast_hbexps_hccache_conjs\n           init_hcache_hccache_compatible Hbb) => [occ [Hcbb Hcocc]].\n  exact: (bit_blast_hbexps_hccache_conjs_sat_complete Hcbb Hwf Hev).\nQed.\n\nTheorem bit_blast_bexps_hcache_conjs_sat_complete TE es :\n  let '(m, c, g, cs) := bit_blast_bexps_hcache_conjs TE es in\n  QFBV.well_formed_bexps es TE ->\n  (exists s, AdhereConform.conform_bexps es s TE /\\\n             QFBV.eval_bexp (mk_conjs es) s) ->\n  sat cs.\nProof.\n  rewrite /bit_blast_bexps_hcache_conjs.\n  dcase (bit_blast_hbexps_hcache_conjs\n           TE init_vm init_hcache init_gen\n           (mapr hash_bexp es)) => [[[[[m c] g] cs] lrs] Hbb].\n  move=> Hwf Hev. exact: (bit_blast_hbexps_hcache_conjs_sat_complete Hbb Hwf Hev).\nQed.\n\n\n(* agree *)\n\nLemma agree_bit_blast_exp_hcache E1 E2 m c g (e : hexp) :\n  QFBV.MA.agree (QFBV.vars_exp e) E1 E2 ->\n  bit_blast_exp_hcache E1 m c g e =\n    bit_blast_exp_hcache E2 m c g e\nwith agree_bit_blast_bexp_hcache E1 E2 m c g (e : hbexp) :\n  QFBV.MA.agree (QFBV.vars_bexp e) E1 E2 ->\n  bit_blast_bexp_hcache E1 m c g e =\n    bit_blast_bexp_hcache E2 m c g e.\nProof.\n  - (* agree_bit_blast_exp_hcache *)\n    case: e. case; simpl.\n    + move=> v z Hag. rewrite (agree_bit_blast_var _ Hag). reflexivity.\n    + reflexivity.\n    + move=> op e z Hag. rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ Hag).\n      reflexivity.\n    + move=> op e1 e2 z Hag.\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      dcase (bit_blast_exp_hcache E2 m c g e1) => [[[[[m1 c1] g1] cs1] ls1] Hbb1].\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_r Hag)).\n      reflexivity.\n    + move=> b e1 e2 z Hag.\n      rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      move: (QFBV.MA.agree_union_set_r Hag) => {} Hag.\n      dcase (bit_blast_bexp_hcache E2 m c g b) => [[[[[mb cb] gb] csb] lsb] Hbbb].\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      dcase (bit_blast_exp_hcache E2 mb cb gb e1) => [[[[[m1 c1] g1] cs1] ls1] Hbb1].\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_r Hag)).\n      reflexivity.\n  - (* agree_bit_blast_bexp_hcache *)\n    case: e. case; simpl.\n    + reflexivity.\n    + reflexivity.\n    + move=> op e1 e2 n Hag.\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      dcase (bit_blast_exp_hcache E2 m c g e1) => [[[[[m1 c1] g1] cs1] ls1] Hbb1].\n      rewrite (agree_bit_blast_exp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_r Hag)).\n      reflexivity.\n    + move=> e n Hag. rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ Hag).\n      reflexivity.\n    + move=> e1 e2 n Hag.\n      rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      dcase (bit_blast_bexp_hcache E2 m c g e1) => [[[[[m1 c1] g1] cs1] ls1] Hbb1].\n      rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_r Hag)).\n      reflexivity.\n    + move=> e1 e2 n Hag.\n      rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_l Hag)).\n      dcase (bit_blast_bexp_hcache E2 m c g e1) => [[[[[m1 c1] g1] cs1] ls1] Hbb1].\n      rewrite (agree_bit_blast_bexp_hcache _ _ _ _ _ _ (QFBV.MA.agree_union_set_r Hag)).\n      reflexivity.\nQed.\n\nLemma agree_bit_blast_bexp_hcache_tflatten E1 E2 m c g (e : hbexp) :\n  QFBV.MA.agree (QFBV.vars_bexp e) E1 E2 ->\n  bit_blast_bexp_hcache_tflatten E1 m c g e =\n    bit_blast_bexp_hcache_tflatten E2 m c g e.\nProof.\n  rewrite /bit_blast_bexp_hcache_tflatten => Hag.\n  rewrite (agree_bit_blast_bexp_hcache _ _ _ Hag).\n  reflexivity.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/bbcache/BitBlastingCacheHash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18297633540340255}}
{"text": "From mathcomp Require Import\n     all_ssreflect\n     finmap.\n\nRequire Import Relations.\n\nFrom AUChain Require Import\n     Network\n     Protocol\n     GlobalState\n     Blocks\n     Messages\n     MessageTuple\n     Parameters\n     BlockTree\n     LocalState\n     StateMonad.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Schedule \n      This file contains the semantics for an execution of the protocol.\n**)\n\nDefinition upd_local (p: Party) (l: LocalState) (N: GlobalState) : GlobalState :=\n  N[[state_map := setf (state_map N) p l ]].\n\n(** Handy functions for using the network functionality to broadcast\n    several messages. **)\nDefinition flood_msgs (msgs : Messages) (N : GlobalState) : GlobalState :=\n  foldr flood_msg N msgs.\n\nDefinition flood_msgs_adv (msgs : seq (Message * DelayMap)) (N : GlobalState) : GlobalState :=\n  foldr (fun ' (m , \u03d5) => flood_msg_adv m \u03d5) N msgs.\n\n(** Our development is parameterised by a map deciding the honesty of\n    parties. **)\nParameter CorruptionStatus : Party -> Honesty.\n\n(** The adversary is modelled as two functions: \n    1) Decides how the adversary acts when baking.\n    2) Decides how the adversary acts when recieving \n       messages. *)\nParameter AdversarialBake:\n  Slot ->\n  History ->\n  MessagePool ->\n  State AdversarialState (seq (Message * DelayMap)).\n\nParameter AdversarialRcv:\n  Messages ->\n  Slot ->\n  History ->\n  MessagePool ->\n  State AdversarialState (seq (Message * DelayMap)).\n\nParameter TxSelection : Slot -> Party -> Transactions.\n\n(** We translate the map of honesty a boolean value. **)\nDefinition is_corrupt p : bool := CorruptionStatus p == Corrupt.\nDefinition is_honest p : bool := CorruptionStatus p == Honest.\n\n(** If the party is honest an honest step is taken with the correct\n    messages. Otherwise will the [AdversarialStep] function be called with\n    the correct inputs and the world updated accordingly to this.  **)\nDefinition party_bake_step_world (p : Party) (N : GlobalState) : GlobalState :=\n  if (state_map N).[? p] is Some l\n  then if ~~(is_corrupt p)\n       then let '(n_msgs, new_ls) := honest_bake (t_now N) (TxSelection (t_now N) p) l\n            in flood_msgs n_msgs (upd_local p new_ls N)\n       else let '(n_msgs, adv_state') := AdversarialBake (t_now N) (history N) (msg_buff N) (adv_state N)\n            in (flood_msgs_adv n_msgs N)[[adv_state := adv_state']]\n  else N.\n\n(** If the party is honest he calls the honest recieve functions.\n    Otherwise the [AdversarialRcv] function.  **)\nDefinition party_rcv_step_world (p : Party) (N : GlobalState) : GlobalState :=\n  if (state_map N).[? p] is Some l\n  then let '(msgs, N') := fetch_msgs p N in\n       if ~~(is_corrupt p)\n       then let '(_, new_ls) := honest_rcv msgs (t_now N') l\n            in (upd_local p new_ls N')\n       else let '(n_msgs, adv_state') := AdversarialRcv msgs (t_now N') (history N') (msg_buff N') (adv_state N')\n            in (flood_msgs_adv n_msgs N')[[adv_state := adv_state']]\n  else N.\n\nDefinition inc_round (N : GlobalState) : GlobalState :=\n  N[[t_now := S (t_now N)]].\n\n(** ** Definition: Related states **)\n\nReserved Notation \"A \u2933 B\" (at level 80, no associativity).\n\nNotation \"N '@' p\" := (progress N = p) (at level 20).\n\nInductive SingleStep: GlobalState -> GlobalState -> Prop :=\n(* Delivering messages to all parties *)\n| Deliver : forall N, N @ Ready -> N \u2933\n                 (foldr party_rcv_step_world N (exec_order N))[[progress := Delivered]]\n(* Executing all party concurrenctly *)\n| Bake : forall N, N @ Delivered -> N \u2933\n              (foldr party_bake_step_world N (exec_order N))[[progress := Baked]]\n(* When messages are delivered and  *)\n| NextRound : forall N, N @ Baked -> N \u2933 (inc_round (round_tick N))[[progress := Ready]]\n(* Permuting parties leads to related states *)\n| PermParties : forall N ps, perm_eq (exec_order N) ps -> N \u2933 N[[exec_order := ps]]\n(* Permuting message buffer leads to related states  *)\n| PermMsgs : forall N mb, perm_eq (msg_buff N) mb -> N \u2933 N[[msg_buff := mb]]\nwhere \"N \u2933 N'\" := (SingleStep N N').\n\n(** BigStep semantics are just the reflexive transitive closure of the\n    SingleStep relation **)\nDefinition BigStep (N N' : GlobalState) := clos_refl_trans_n1 GlobalState SingleStep N N'.\n\nNotation \"N '\u21d3' N'\" := (BigStep N N') (at level 20).\nNotation \"N '\u21d3[' s ']' N'\" := (N \u21d3 N' /\\ (s + t_now N) = (t_now N')) (at level 20).\nNotation \"N '\u21d3^+' N'\" := (N \u21d3 N' /\\ t_now N < t_now N') (at level 20).\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/Schedule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.18297633187088133}}
{"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\nFixpoint F (n:nat) : False := F (match F n with end).\n\n(* de Bruijn mix-up *)\n(* If accepted, Eval compute in f 0. loops *)\nDefinition f :=\n  let f (f1 f2:nat->nat) := f1 in\n  let _ := 0 in\n  let _ := 0 in\n  let g (f1 f2:nat->nat) := f2 in\n  let h := f in (* h = Rel 4 *)\n  fix F (n:nat) : nat :=\n  h F S n. (* here Rel 4 = g *)\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/coq/coq-8.3pl5-foundations/test-suite/failure/guard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18297632833836014}}
{"text": "(** printing \u22a2#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing \u22a2##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing \u22a2##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing \u22a2!    %\\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.\n\n(** * Precise Typing\n\n    Precise typing is used to reason about the types of variables and values.\n    Precise typing does not \"modify\" a variable's or value's type through subtyping.\n    - For values, precise typing allows to only retrieve the \"immediate\" type of the value.\n      It types objects with recursive types, and functions with dependent-function types. #<br>#\n      For example, if a value is the object [nu(x: {a: T}){a = x.a}], the only way to type\n      the object through precise typing is [G \u22a2! nu(x: {a: T}){a = x.a}: mu(x: {a: T})].\n    - For variables, we start out with a type [T=G(x)] (the type to which the variable is\n      bound in [G]). Then we use precise typing to additionally deconstruct [T]\n      by using recursion elimination and intersection elimination. #<br>#\n      For example, if [G(x)=mu(x: {a: T} /\\ {B: S..U})], then we can derive the following\n      precise types for [x]:               #<br>#\n      [G \u22a2! x: mu(x: {a: T} /\\ {B: S..U})] #<br>#\n      [G \u22a2! x: {a: T} /\\ {B: S..U}]        #<br>#\n      [G \u22a2! x: {a: T}]                    #<br>#\n      [G \u22a2! x: {B: S..U}].                *)\n\n(** ** Precise typing for values *)\nReserved Notation \"G '\u22a2!v' v ':' T\" (at level 40, v at level 59).\n\nInductive ty_val_p : ctx -> val -> typ -> Prop :=\n\n(** [G, x: T \u22a2 t^x: U^x]       #<br>#\n    [x fresh]                  #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015] #<br>#\n    [G \u22a2! lambda(T)t: forall(T) U]     *)\n| ty_all_intro_p : forall L G T t U,\n    (forall x, x \\notin L ->\n      G & x ~ T \u22a2 open_trm x t : open_typ x U) ->\n    G \u22a2!v val_lambda T t : typ_all T U\n\n(** [G, x: T^x \u22a2 ds^x :: T^x]   #<br>#\n    [x fresh]                   #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015]   #<br>#\n    [G \u22a2! nu(T)ds :: mu(T)]        *)\n| ty_new_intro_p : 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 \u22a2!v val_new T ds : typ_bnd T\n\nwhere \"G '\u22a2!v' v ':' T\" := (ty_val_p G v T).\n\nHint Constructors ty_val_p.\n\n\n(** * Precise Flow *)\n(** We use the precise flow relation to reason about the relations between\n    the precise type of a variable [G \u22a2! x: T] and the type that the variable\n    is bound to in the context [G(x)=T'].#<br>#\n    If [G(x) = T], the [precise_flow] relation describes all the types [U] that [x] can\n    derive through precise typing ([\u22a2!] (see paper)).\n    If [precise_flow x G T U], denoted as [G \u22a2 x: T \u2abc U],\n    then [G(x) = T] and [G \u22a2! x: U].   #<br>#\n    For example, if [G(x) = mu(x: {a: T} /\\ {B: S..U})], then we can derive the following\n    precise flows for [x]:                                                  #<br>#\n    [G \u22a2! x: mu(x: {a: T} /\\ {B: S..U}) \u2abc mu(x: {a: T} /\\ {B: S..U}]         #<br>#\n    [G \u22a2! x: mu(x: {a: T} /\\ {B: S..U}) \u2abc {a: T} /\\ {B: S..U}]               #<br>#\n    [G \u22a2! x: mu(x: {a: T} /\\ {B: S..U}) \u2abc {a: T}]                           #<br>#\n    [G \u22a2! x: mu(x: {a: T} /\\ {B: S..U}) \u2abc {B: S..U}]. *)\n\nReserved Notation \"G '\u22a2!' x ':' T '\u2abc' U\" (at level 40, x at level 59).\n\nInductive precise_flow : var -> ctx -> typ -> typ -> Prop :=\n\n(** [G(x) = T]       #<br>#\n    [ok G]           #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015] #<br>#\n    [G \u22a2! x: T \u2abc T] *)\n  | pf_bind : forall x G T,\n      binds x T G ->\n      G \u22a2! x: T \u2abc T\n\n(** [G \u22a2! x: T \u2abc mu(U)] #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015] #<br>#\n    [G \u22a2! x: T \u2abc U^x]       *)\n  | pf_open : forall x G T U,\n      G \u22a2! x: T \u2abc typ_bnd U ->\n      G \u22a2! x: T \u2abc open_typ x U\n\n(** [G \u22a2! x: T \u2abc U1 /\\ U2]   #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015]   #<br>#\n    [G \u22a2! x: T \u2abc U1]        *)\n  | pf_and1 : forall x G T U1 U2,\n      G \u22a2! x: T \u2abc typ_and U1 U2 ->\n      G \u22a2! x: T \u2abc U1\n\n(** [G \u22a2! x: T \u2abc U1 /\\ U2]   #<br>#\n    [\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015]   #<br>#\n    [G \u22a2! x: T \u2abc U2]        *)\n  | pf_and2 : forall x G T U1 U2,\n      G \u22a2! x: T \u2abc typ_and U1 U2 ->\n      G \u22a2! x: T \u2abc U2\n\nwhere \"G '\u22a2!' x ':' T '\u2abc' U\" := (precise_flow x G T U).\n\nHint Constructors precise_flow.\n\n(** ** Precise Flow Lemmas *)\n\n(** If [G \u22a2! x: T \u2abc U] then [G(x) = T]. *)\nLemma pf_binds: forall G x T U,\n    G \u22a2! x: T \u2abc U ->\n    binds x T G.\nProof.\n  introv Pf. induction Pf; auto.\nQed.\n\n(** If [G(x) = forall(S)T], then [x]'s precise type can be only [forall(S)T]. *)\nLemma precise_flow_all_inv : forall x G S T U,\n    G \u22a2! x: typ_all S T \u2abc U ->\n    U = typ_all S T.\nProof.\n  introv Hpf.\n  dependent induction Hpf; auto;\n    specialize (IHHpf S T eq_refl); inversion IHHpf.\nQed.\n\n(** The precise type of a value is inert. *)\nLemma precise_inert_typ : forall G v T,\n    G \u22a2!v v : T ->\n    inert_typ T.\nProof.\n  introv Ht. inversions Ht; constructor; rename T0 into T.\n  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 (ty_defs_record_type H);\n      assert (Hz': z \\notin fv_typ T) by auto;\n      apply* record_type_open\n  end.\nQed.\n\n(** The following two lemmas say that the type to which a variable is bound in an inert context is inert. *)\nLemma binds_inert : forall G x T,\n    binds x T G ->\n    inert G ->\n    inert_typ T.\nProof.\n  introv Bi HiG. induction HiG.\n  - false * binds_empty_inv.\n  - destruct (binds_push_inv Bi).\n    + destruct H1. subst. assumption.\n    + destruct H1. apply (IHHiG H2).\nQed.\n\n(** See [binds_inert]. *)\nLemma pf_inert_T : forall G x T U,\n    inert G ->\n    G \u22a2! x: T \u2abc U ->\n    inert_typ T.\nProof.\n  introv Hi Pf. induction Pf; eauto.\n  apply (binds_inert H Hi).\nQed.\n\n(** See [inert_typ_bnd_record] *)\nLemma pf_rcd_T : forall G x T U,\n    inert G ->\n    G \u22a2! x: (typ_bnd T) \u2abc U ->\n    record_type T.\nProof.\n  introv Hi Pf. apply (pf_inert_T Hi) in Pf; inversions Pf; assumption.\nQed.\n\n(** If [G(x) = mu(x: T)], then [x]'s precise type can be only [mu(x: T)]\n     or a record type. *)\nLemma pf_bnd_same_or_rcd : forall G x T U,\n    inert G ->\n    G \u22a2! x: typ_bnd T \u2abc U ->\n    U = typ_bnd T \\/ record_type U.\nProof.\n  introv Hi Pf.\n  dependent induction Pf; try solve [left*]; right.\n  - specialize (IHPf T Hi eq_refl). destruct IHPf as [eq | r].\n    * apply open_record_type.\n      inversion eq. apply* pf_rcd_T.\n    * inversion r. inversion H.\n  - destruct (IHPf T Hi eq_refl) as [F | Hr]. inversion F.\n    inversion Hr. inversions H.\n    exists ls. assumption.\n  - destruct (IHPf T Hi eq_refl) as [F | Hr]. inversion F.\n    inversion Hr. inversions H.\n    eexists. apply* rt_one.\nQed.\n\n(** If [x]'s precise type is [mu(x: U)], then [G(x) = mu(x: U)] *)\nLemma pf_inert_bnd_U: forall G x T U,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_bnd U ->\n    T = typ_bnd U.\nProof.\n  introv Hi Pf.\n  lets HT: (pf_inert_T Hi Pf).\n  destruct HT.\n  - apply precise_flow_all_inv in Pf. congruence.\n  - destruct (pf_bnd_same_or_rcd Hi Pf) as [Heq | Hr].\n    + auto.\n    + inversion Hr. inversion H0.\nQed.\n\n(** If [x]'s precise type is a field or type declaration, then [G(x)] is\n    a recursive type. *)\nLemma pf_inert_rcd_U: forall G x T D,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_rcd D ->\n    exists U, T = typ_bnd U.\nProof.\n  introv Hi Pf.\n  lets HT: (pf_inert_T Hi Pf).\n  destruct HT.\n  - apply precise_flow_all_inv in Pf. congruence.\n  - exists* T.\nQed.\n\n\n(** If [x]'s precise type is a record type, then [G(x)] is a recursive type. *)\nLemma pf_inert_rcd_typ_U: forall G x T Ds,\n    inert G ->\n    G \u22a2! x: T \u2abc Ds ->\n    record_type Ds ->\n    exists U, T = typ_bnd U.\nProof.\n  introv Hi Pf Hr.\n  lets HT: (pf_inert_T Hi Pf).\n  destruct HT.\n  - apply precise_flow_all_inv in Pf. subst.\n    inversion Hr. inversion H.\n  - exists* T.\nQed.\n\n(** The following two lemmas express that if [x]'s precise type is a function type,\n    then [G(x)] is the same function type. *)\nLemma pf_inert_lambda_U : forall x G S T U,\n    inert G ->\n    G \u22a2! x: U \u2abc typ_all S T ->\n    U = typ_all S T.\nProof.\n  introv Hi Pf.\n  lets Hiu: (pf_inert_T Hi Pf).\n  destruct Hiu.\n  - apply precise_flow_all_inv in Pf. congruence.\n  - destruct (pf_bnd_same_or_rcd Hi Pf) as [H1 | H1]; inversions H1.\n    inversion H0.\nQed.\n\n(** See [pf_inert_lambda_U]. *)\nLemma inert_precise_all_inv : forall x G S T U,\n    inert G ->\n    G \u22a2! x : U \u2abc typ_all S T ->\n    binds x (typ_all S T) G.\nProof.\n  introv Hi Htyp. lets H: (pf_inert_lambda_U Hi Htyp). subst.\n  apply* pf_binds.\nQed.\n\n(** In an inert context, the precise type of a variable\n    cannot be bottom. *)\nLemma pf_bot_false : forall G x T,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_bot ->\n    False.\nProof.\n  introv Hi Pf.\n  lets HT: (pf_inert_T Hi Pf). destruct HT.\n  - apply precise_flow_all_inv in Pf. congruence.\n  - destruct (pf_bnd_same_or_rcd Hi Pf); inversion H0. inversion H1.\nQed.\n\n(** In an inert context, the precise type of\n    a variable cannot be type selection. *)\nLemma pf_psel_false : forall G T x y A,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_sel y A ->\n    False.\nProof.\n  introv Hi Pf.\n  lets HT: (pf_inert_T Hi Pf). destruct HT.\n  - apply precise_flow_all_inv in Pf. congruence.\n  - destruct (pf_bnd_same_or_rcd Hi Pf); inversion H0. inversion H1.\nQed.\n\n(** If [G(x) = mu(T)], and [G \u22a2! x: ... /\\ D /\\ ...], then [T^x = ... /\\ D /\\ ...]. *)\nLemma pf_record_sub : forall x G T T' D,\n    inert G ->\n    G \u22a2! x: typ_bnd T \u2abc T' ->\n    record_has T' D ->\n    record_has (open_typ x T) D.\nProof.\n  introv Hi Pf Hr. dependent induction Pf; auto.\n  - inversions Hr.\n  - apply (pf_inert_bnd_U Hi) in Pf. congruence.\nQed.\n\n(** If [G(x) = mu(S)] and [G \u22a2! x: D], where [D] is a field or type declaration,\n    then [S^x = ... /\\ D /\\ ...]. *)\nLemma precise_flow_record_has: forall S G x D,\n    inert G ->\n    G \u22a2! x: typ_bnd S \u2abc typ_rcd D ->\n    record_has (open_typ x S) D.\nProof.\n  introv Hi Pf. apply* pf_record_sub.\nQed.\n\n(** If\n    - [G \u22a2! x: mu(T) \u2abc {A: T1..T1}]\n    - [G \u22a2! x: mu(T) \u2abc {A: T2..T2}]\n    then [T1 = T2]. *)\nLemma pf_record_unique_tight_bounds_rec : forall G x T A T1 T2,\n    inert G ->\n    G \u22a2! x: typ_bnd T \u2abc typ_rcd (dec_typ A T1 T1) ->\n    G \u22a2! x: typ_bnd T \u2abc typ_rcd (dec_typ A T2 T2) ->\n    T1 = T2.\nProof.\n  introv Hi Pf1 Pf2.\n  pose proof (precise_flow_record_has Hi Pf1) as H1.\n  pose proof (precise_flow_record_has Hi Pf2) as H2.\n  eapply unique_rcd_typ; eauto.\n  apply open_record_type; apply* pf_rcd_T.\nQed.\n\n(** If\n    - [G \u22a2! x: T \u2abc {A: T1..T1}]\n    - [G \u22a2! x: T \u2abc {A: T2..T2}]\n    then [T1 = T2]. *)(** *)\nLemma pf_inert_unique_tight_bounds : forall G x T T1 T2 A,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_rcd (dec_typ A T1 T1) ->\n    G \u22a2! x: T \u2abc typ_rcd (dec_typ A T2 T2) ->\n    T1 = T2.\nProof.\n  introv Hi Pf1 Pf2.\n  pose proof (pf_inert_rcd_U Hi Pf1) as [?U ?H]; subst.\n  apply* pf_record_unique_tight_bounds_rec.\nQed.\n\n(** The type to which a variable is bound in an environment is unique. *)\nLemma x_bound_unique: forall G x T1 T2 U1 U2,\n    G \u22a2! x: T1 \u2abc U1 ->\n    G \u22a2! x: T2 \u2abc U2 ->\n    T1 = T2.\nProof.\n  introv Pf1 Pf2.\n  apply pf_binds in Pf1.\n  apply pf_binds in Pf2.\n  apply (binds_functional Pf1 Pf2).\nQed.\n\n(** If a typing context is inert, then the variables in its domain are distinct. #<br>#\n    Note: [ok] is defined in [TLC.LibEnv.v]. *)\nLemma inert_ok : forall G,\n    inert G ->\n    ok G.\nProof.\n  introv Hi. induction Hi; auto.\nQed.\n\nHint Resolve inert_ok.\n\n(** If [G \u22a2! x: {A: S..U}] then [S = U]. *)\nLemma pf_dec_typ_inv : forall G x T A S U,\n    inert G ->\n    G \u22a2! x: T \u2abc typ_rcd (dec_typ A S U) ->\n    S = U.\nProof.\n  introv Hi Pf. destruct (pf_inert_rcd_U Hi Pf) as [V H]. subst.\n  destruct (pf_bnd_same_or_rcd Hi Pf); try congruence.\n  destruct H as [?ls ?H]. inversions H. inversions* H1.\nQed.\n\n(** Precise typing implies general typing. *)\n(** - for variables *)\nLemma precise_to_general: forall G x T U,\n    G \u22a2! x : T \u2abc U ->\n    G \u22a2 trm_var (avar_f x) : U.\nProof.\n  intros. induction H; intros; subst; eauto.\nQed.\n\n(** - for values *)\nLemma precise_to_general_v: forall G v T,\n    G \u22a2!v v : T ->\n    G \u22a2 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/PreciseTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18297632833836014}}
{"text": "From iris.base_logic.lib Require Export fancy_updates wsat.\nFrom iris.proofmode Require Import base tactics classes.\nFrom mwp Require Import mwp mwp_adequacy mwp_lifting.\nFrom iris.program_logic Require Export ectxi_language ectx_language language.\nFrom mwp.prelude Require Import base.\n\nSection mwp_indexed_step_fupd.\n  Context {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI : state \u039b \u2192 iProp \u03a3).\n\n  Typeclasses Transparent mwpC_state_interp mwpC_modality.\n\n  Program Definition mwpd_indexed_step_fupd : mwpData \u039b \u03a3 :=\n    {| mwpD_state_interp := mwpD_SI;\n       mwpD_Extra := [Prod];\n       mwpD_modality_index := [Prod nat];\n       mwpD_modality_bind_condition k k' f \u039e :=\n         k = k' + (f tt) \u2227 \u039e = \u03bb _, id;\n       mwpD_modality k E n \u03a6 := (|={E}[\u2205]\u25b7=>^k |={E}=> \u03a6 tt)%I;\n    |}.\n\n  Global Instance mwpC_indexed_step_fupd : mwpC mwpd_indexed_step_fupd.\n  Proof.\n    split.\n    - intros idx E m n P Q HPQ; simpl.\n      induction idx; simpl; first by apply fupd_ne.\n      by rewrite IHidx.\n    - iIntros (idx E1 E2 n P Q HE) \"HPQ HP\"; simpl.\n      iSpecialize (\"HPQ\" $! tt); simpl.\n      iInduction idx as [] \"IH\"; simpl.\n      + iApply fupd_wand_l; iFrame. by iApply fupd_mask_mono.\n      + iApply step_fupd_mask_mono; last (iMod \"HP\"; iModIntro); try set_solver.\n        iNext. iMod \"HP\"; iModIntro.\n        iApply (\"IH\" with \"HPQ HP\").\n    - intros idx E n P; simpl.\n      induction idx; simpl; first done.\n      iIntros \"HP\". iApply (step_fupd_wand with \"HP []\").\n      iApply IHidx.\n    - intros idx idx' f.\n      intros E n m P ? [-> ->]; simpl in *.\n      induction idx'; simpl.\n      + induction (f tt) as [|z]; simpl; first by iIntros \">>?\".\n        iIntros \">>H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n        by iApply IHz; iModIntro.\n      + iIntros \">H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n        by iApply IHidx'.\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_outer_fupd idx :\n    mwpMIsOuterModal mwpd_indexed_step_fupd idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    destruct idx; simpl; by iMod \"H\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_outer_bupd idx :\n    mwpMIsOuterModal mwpd_indexed_step_fupd idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    destruct idx; simpl; by iMod \"H\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_outer_except_0 idx :\n    mwpMIsOuterModal mwpd_indexed_step_fupd idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    destruct idx; simpl; by iMod \"H\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_inner_fupd idx :\n    mwpMIsInnerModal mwpd_indexed_step_fupd idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    iInduction idx as [] \"IH\"; simpl; first by iMod \"H\".\n    iMod \"H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n    by iApply \"IH\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_inner_bupd idx :\n    mwpMIsInnerModal mwpd_indexed_step_fupd idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    iInduction idx as [] \"IH\"; simpl; first by iMod \"H\".\n    iMod \"H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n    by iApply \"IH\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_is_inner_except_0 idx :\n    mwpMIsInnerModal mwpd_indexed_step_fupd idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    iInduction idx as [] \"IH\"; simpl; first by repeat iMod \"H\".\n    iMod \"H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n    by iApply \"IH\".\n  Qed.\n\n  Global Instance mwp_indexed_step_fupd_AlwaysSupportsShift idx :\n    idx \u2264 1 \u2192\n    mwpMAlwaysSupportsShift mwpd_indexed_step_fupd idx.\n  Proof.\n    rewrite /mwpMSupportsAtomicShift /mwpC_modality /mwpD_modality /=.\n    iIntros (Hidx n E1 E2 P) \"H\".\n    destruct idx as [|[]]; simpl; last lia.\n    - by repeat iMod \"H\".\n    - repeat iMod \"H\". iModIntro. iNext.\n      by repeat iMod \"H\".\n  Qed.\n\n  Global Program Instance mwp_indexed_step_fupd_SplitForStep idx :\n    mwpMSplitForStep mwpd_indexed_step_fupd idx :=\n    {|\n      mwpM_split_for_step_M1 E P := |={E, \u2205}=> P;\n      mwpM_split_for_step_M2 E P := |={\u2205, E}=> P;\n    |}%I.\n  Next Obligation.\n  Proof.\n    iIntros (idx n E P) \"HP /=\".\n    rewrite /mwpC_modality /mwpD_modality /=.\n    destruct idx as [|]; simpl.\n    - by repeat iMod \"HP\".\n    - by repeat iMod \"HP\"; iModIntro; iNext; iMod \"HP\"; iModIntro.\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    by iMod \"HP\"; iModIntro; iApply \"HPQ\".\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    iMod \"HP\"; iModIntro. by iApply \"HPQ\".\n  Qed.\n\n  Lemma mwp_indexed_step_fupd_bind K `{!LanguageCtx K} k k' E e \u03a6 :\n    MWP@{mwpd_indexed_step_fupd, k } e @ E {{ v; m,\n      MWP@{mwpd_indexed_step_fupd, k' } K (of_val v) @ E {{ w; n, \u03a6 w (m + n) }} }}\n    \u22a2 MWP@{mwpd_indexed_step_fupd, k + k' } K e @ E {{ (\u03bb v n _, \u03a6 v n) }}.\n  Proof.\n    iIntros \"H\".\n    iApply (mwp_bind _ _ _ _ _ (\u03bb _, id)); last eauto.\n    rewrite /mwpC_modality_bind_condition /=; split; [lia|done].\n  Qed.\n\n  Lemma mwpC_indexed_step_fupd_modality_le k k' E n \u03a6:\n    k' \u2264 k \u2192\n    mwpC_modality mwpd_indexed_step_fupd k' E n \u03a6\n    \u22a2 mwpC_modality mwpd_indexed_step_fupd k E n \u03a6.\n  Proof.\n    iIntros (Hk) \"H\".\n    rewrite /mwpC_modality /=.\n    replace k with (k' + (k - k')) by lia.\n    rewrite -step_fupdN_plus.\n    iApply step_fupdN_mono; last eauto.\n    by iIntros \"?\"; iApply step_fupdN_intro.\n  Qed.\n\n  Lemma mwp_indexed_step_fupd_index_intro k k' E e \u03a6 :\n    k' \u2264 k \u2192\n    MWP@{mwpd_indexed_step_fupd, k' } e @ E {{ \u03a6 }}\n    \u22a2 MWP@{mwpd_indexed_step_fupd, k } e @ E {{ \u03a6 }}.\n  Proof.\n    iIntros (?) \"H\".\n    rewrite mwp_eq /mwp_def.\n    iIntros (\u03c31 \u03c32 v n Hr) \"Hi\".\n    iApply (mwpC_indexed_step_fupd_modality_le); first done.\n    iApply \"H\"; eauto.\n  Qed.\n\n  Lemma mwp_indexed_step_fupd_index_step_fupd k k' E e \u03a6 :\n    (|={E}[\u2205]\u25b7=>^k' MWP@{mwpd_indexed_step_fupd, k } e @ E {{ \u03a6 }})%I\n    \u22a2 MWP@{mwpd_indexed_step_fupd, k' + k } e @ E {{ \u03a6 }}.\n  Proof.\n    iIntros \"H\".\n    rewrite mwp_eq /mwp_def.\n    iIntros (\u03c31 \u03c32 v n Hr) \"Hi\".\n    iApply step_fupdN_plus.\n    iApply (step_fupdN_wand with \"H\").\n    iIntros \"H\".\n    iApply \"H\"; eauto.\n  Qed.\n\nEnd mwp_indexed_step_fupd.\n\nSection lifting.\n\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI : state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 iProp \u03a3.\n\nLocal Instance : mwpC (mwpd_indexed_step_fupd mwpD_SI) := mwpC_indexed_step_fupd mwpD_SI.\nLocal Instance : \u2200 idx, mwpMSplitForStep (mwpd_indexed_step_fupd mwpD_SI) idx :=\n  mwp_indexed_step_fupd_SplitForStep mwpD_SI.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_fupd_lift_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n    (\u2200 \u03c31, mwpD_SI \u03c31 -\u2217\n      |={E, \u2205}=>\n     \u2200 e2 \u03c32,\n         \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n            (mwpD_SI \u03c32 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n                    e2 @ E {{ w; n, \u03a6 w (S n) }}))\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ (\u03bb v n _, \u03a6 v n) }}.\nProof.\n  by intros;\n    iApply (mwp_lift_step\n              (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2 \u03c32, prim_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  (\u2200 \u03c31 e2 \u03c32,\n      \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n        e2 @ E {{ w; n, \u03a6 w (S n) }})\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_step\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1);\n    simpl; eauto.\n  by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nLemma mwp_indexed_step_fupd_lift_atomic_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u2200 v2 \u03c32,\n            \u231cprim_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d\n             ={\u2205, E}=\u2217 (mwpD_SI \u03c32 \u2217 |={E}[\u2205]\u25b7=>^idx |={E}=> \u03a6 v2 1))\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx } e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros (??).\n  by iApply (mwp_lift_atomic_step\n               (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_atomic_det_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n  (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     (\u2203 v2 \u03c32,\n         \u231c\u2200 e2' \u03c32', prim_step e1 \u03c31 [] e2' \u03c32' [] \u2192\n                     \u03c32 = \u03c32' \u2227 to_val e2' = Some v2\u231d \u2227\n                     |={\u2205, E}=> mwpD_SI \u03c32 \u2217 |={E}[\u2205]\u25b7=>^idx |={E}=> \u03a6 v2 1))\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx } e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  by iIntros (??);\n  iApply (mwp_lift_atomic_det_step\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_det_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2' \u03c32, prim_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e2 @ E {{ v; n, \u03a6 v (S n) }}\n  \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_det_step\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1);\n    simpl; eauto.\n  by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nLemma mwp_indexed_step_fupd_pure_step `{!Inhabited (state \u039b)} idx E e1 e2 \u03c6 n \u03a6 :\n  PureExec \u03c6 n e1 e2 \u2192\n  \u03c6 \u2192\n  MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n    e2 @ E {{ v ; m, \u03a6 v (n + m) }}\n  \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros (Hexec H\u03c6) \"Hic\".\n  iApply (mwp_pure_step (mwpd_indexed_step_fupd mwpD_SI) idx); eauto.\n  clear Hexec.\n  iInduction n as [] \"IH\" forall (\u03a6); simpl; auto.\n  iApply fupd_mask_intro_subseteq; first set_solver.\n  iApply (\"IH\" $! (\u03bb w k, \u03a6 w (S k)) with \"Hic\").\nQed.\n\nEnd lifting.\n\nSection mwp_ectx_lifting.\n\nContext {\u039b : ectxLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI : state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 iProp \u03a3.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_indexed_step_fupd_lift_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n                     e2 @ E {{ w; n, \u03a6 w (S n) }}))\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  by intros;\n    iApply (mwp_lift_head_step\n              (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  (\u2200 \u03c31 e2 \u03c32,\n      \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n        e2 @ E {{ w; n, \u03a6 w (S n) }})\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_head_step\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1);\n    simpl; eauto.\n  by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nLemma mwp_indexed_step_fupd_lift_atomic_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     \u2200 v2 \u03c32,\n       \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n          (mwpD_SI \u03c32 \u2217 |={E}[\u2205]\u25b7=>^idx |={E}=> \u03a6 v2 1))\n     \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx } e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  by intros;\n    iApply (mwp_lift_atomic_head_step\n              (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_det_head_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e2 @ E {{ v; n, \u03a6 v (S n) }}\n  \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_det_head_step\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1);\n    simpl; eauto.\n  by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nEnd mwp_ectx_lifting.\n\nSection mwp_ectxi_lifting.\n\nContext {\u039b : ectxiLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI : state \u039b \u2192 iProp \u03a3).\n\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : (val \u039b) \u2192 nat \u2192 iProp \u03a3.\nImplicit Types v : (val \u039b).\nImplicit Types e : (expr \u039b).\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_indexed_step_fupd_lift_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        (\u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n                     e2 @ E {{ w; n, \u03a6 w (S n) }})))\n     \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  by iIntros (??);\n    iApply (mwp_lift_head_step'\n              (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n   (\u2200 \u03c31 e2 \u03c32,\n       \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n       MWP@{mwpd_indexed_step_fupd mwpD_SI, idx}\n         e2 @ E {{ w; n, \u03a6 w (S n) }})\n     \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_head_step'\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1); eauto.\n  simpl. by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nLemma mwp_indexed_step_fupd_lift_atomic_head_step' idx E \u03a6 e1:\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n      (\u2200 v2 \u03c32,\n          \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n           (mwpD_SI \u03c32 \u2217 |={E}[\u2205]\u25b7=>^idx |={E}=> \u03a6 v2 1)))\n    \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx } e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros (???).\n  by iApply (mwp_lift_atomic_head_step'\n               (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1).\nQed.\n\nLemma mwp_indexed_step_fupd_lift_pure_det_head_step' idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2') \u2192\n  MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e2 @ E {{ v; n, \u03a6 v (S n) }}\n  \u22a2 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx} e1 @ E {{ \u03bb v n _, \u03a6 v n }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_det_head_step'\n            (mwpd_indexed_step_fupd mwpD_SI) idx E (\u03bb v n _, \u03a6 v n) e1); eauto.\n  simpl. by iApply fupd_mask_intro_subseteq; first set_solver.\nQed.\n\nEnd mwp_ectxi_lifting.\n\nSection basmwp_soundness.\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI : state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nLemma mwp_indexed_step_fupd_adequacy_basic idx E e \u03c3 \u03a6 :\n  mwpD_SI \u03c3 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI, idx } e @ E {{ \u03a6 }} -\u2217\n    \u2200 (rd : Reds e \u03c3),\n      |={E}[\u2205]\u25b7=>^idx\n        |={E}=> mwpD_SI (end_state rd) \u2217 \u03a6 (end_val rd) (nstps rd) tt.\nProof.\n  iApply (mwp_adequacy_basic (mwpd_indexed_step_fupd mwpD_SI) idx E e \u03c3 \u03a6).\n Qed.\n\nEnd basmwp_soundness.\n\nSection soundness.\nContext {\u039b \u03a3} `{!invPreG \u03a3} {SI_data : Type} (mwpD_SI : SI_data \u2192 state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nProgram Instance indexed_step_fupd_Initialization SSI `{!InitData SSI} idx :\n  Initialization\n    unit\n    (\u03bb H : invG_pack \u03a3 SI_data, mwpd_indexed_step_fupd (mwpD_SI (PIG_cnt H)))\n    (\u03bb H, @mwpC_indexed_step_fupd \u039b \u03a3 _ (mwpD_SI (PIG_cnt H)))\n    (\u03bb _, idx) :=\n{|\n  initialization_modality Hi P := |={\u22a4}=> P;\n  initialization_seed_for_modality _ := wsat \u2217 ownE \u22a4;\n  initialization_seed_for_state_interp x := SSI (PIG_cnt x);\n  initialization_residue _ := \u25b7 wsat \u2217 \u25b7 ownE \u22a4;\n  initialization_elim_laters := 1;\n  initialization_mwpCM_soundness_arg := unit;\n  initialization_mwpCM_soundness_laters _ _ := S (S idx);\n  initialization_modality_initializer _ _ := True;\n  initialization_mwpCM_soundness_fun _ := tt;\n  initialization_Ex_conv _ x := x;\n|}%I.\nNext Obligation.\nProof.\n  intros; simpl.\n  iApply (init_data (\u03bb x, _ \u2217 SSI (PIG_cnt x)))%I.\nQed.\nNext Obligation.\nProof.\n  iIntros (? ? _ P Hi) \"[Hs HE] HP\".\n  rewrite uPred_fupd_eq /uPred_fupd_def.\n  iMod (\"HP\" with \"[$]\") as \"(Hs & HE & HP)\".\n  iModIntro. rewrite -!bi.later_sep.\n  iMod \"Hs\"; iMod \"HE\"; iMod \"HP\". iNext.\n  iFrame.\nQed.\nNext Obligation.\nProof.\n  iIntros (?? idx Hi P E n _) \"[[Hs HE] [_ HP]]\".\n  iNext.\n  rewrite /mwpC_modality /mwpD_modality /=.\n  rewrite uPred_fupd_eq /uPred_fupd_def /=.\n  replace \u22a4 with ((\u22a4 \u2216 E) \u222a E) by by rewrite difference_union_L; set_solver.\n  iDestruct (ownE_op with \"HE\") as \"[_ HE]\"; first set_solver.\n  iInduction idx as [] \"IH\".\n  { iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n    by iMod \"HP\". }\n  simpl.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iNext.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iApply (\"IH\" with \"Hs HP HE\").\nQed.\n\nLemma mwp_indexed_step_fupd_adequacy\n      SSI `{!InitData SSI} (idx : nat) E e \u03c3 (\u03a8 : val \u039b \u2192 nat \u2192 Prop):\n  (\u2200 (Hcnd : invG_pack \u03a3 SI_data),\n      SSI (PIG_cnt Hcnd) \u22a2\n       |={\u22a4}=> (mwpD_SI (PIG_cnt Hcnd) \u03c3 \u2217\n                MWP@{mwpd_indexed_step_fupd (mwpD_SI (PIG_cnt Hcnd)), idx }\n                e @ E {{ v ; n, \u231c\u03a8 v n\u231d }}))\n  \u2192 \u2200 (rd : Reds e \u03c3), \u03a8 (end_val rd) (@nstps \u039b _ _ rd).\nProof.\n  intros Hic rd.\n  apply (mwp_adequacy\n           _ _ _ _ (indexed_step_fupd_Initialization SSI idx) E e \u03c3 (\u03bb v n _, \u03a8 v n) tt).\n  by iIntros (?) \"?\"; iMod (Hic with \"[$]\") as \"[$ $]\".\nQed.\n\nEnd soundness.\n", "meta": {"author": "logsem", "repo": "modal-weakestpre", "sha": "9d9034f868a94e195a8a22f53af06a14e1529f3f", "save_path": "github-repos/coq/logsem-modal-weakestpre", "path": "github-repos/coq/logsem-modal-weakestpre/modal-weakestpre-9d9034f868a94e195a8a22f53af06a14e1529f3f/theories/mwp_modalities/mwp_indexed_step_fupd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18296454902429027}}
{"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.\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. Opaque Snuffle.Snuffle.\nRequire Import tweetnacl20140427.verif_crypto_stream_salsa20_xor.\n\nLemma crypto_stream_salsa20_tweet_ok: semax_body SalsaVarSpecs (*(crypto_stream_salsa20_xor_spec::*)SalsaFunSpecs\n      f_crypto_stream_salsa20_tweet\n      f_crypto_stream_salsa20_tweet_spec.\nProof.\nstart_function.\nabbreviate_semax.\nforward_call (c, k, nullval, nonce, d, Nonce, K, list_repeat (Z.to_nat (Int64.unsigned d)) Byte.zero, gv).\n{ simpl; entailer!. }\napply Zlength_list_repeat. apply Int64.unsigned_range.\n\nforward.\nQed.\n\n(*The crypto_stream function*)\nLemma crypto_stream_xsalsa20_tweet_ok:\n      semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_stream_xsalsa20_tweet\n      f_crypto_stream_xsalsa20_tweet_spec.\nProof.\nstart_function. unfold data_at_, field_at_. simpl.\nunfold Sigma_vector.\nforward_call (gv _sigma, k, nonce, v_s,\n        default_val (tarray tuchar 32),\n        ((Nonce, SIGMA), K)).\n{ unfold CoreInSEP, SByte. cancel. }\nIntros v.\nunfold CoreInSEP, SByte, Sigma_vector. normalize.\nassert_PROP (isptr nonce) as PN by entailer!.\nassert (exists HSalsaRes, hSalsaOut v =\n   match HSalsaRes with (q1, q2) =>\n     SixteenByte2ValList q1 ++ SixteenByte2ValList q2\n   end).\n{ unfold hSalsaOut.\n  exists ((littleendian_invert (Znth 0 v),\n           littleendian_invert (Znth 5 v),\n           littleendian_invert (Znth 10 v),\n           littleendian_invert (Znth 15 v)),\n          (littleendian_invert (Znth 6 v),\n           littleendian_invert (Znth 7 v),\n           littleendian_invert (Znth 8 v),\n           littleendian_invert (Znth 9 v))).\n  do 2 rewrite SixteenByte2ValList_char. repeat rewrite <- app_assoc. trivial. }\ndestruct H0 as [HSalsaRes HS]. rewrite HS.\nforward_call (c, v_s, offset_val 16 nonce, d, Nonce2, HSalsaRes, gv).\n{ unfold SByte, Sigma_vector, ThirtyTwoByte.\n  destruct HSalsaRes as [q1 q2]. cancel. }\nforward.\nunfold ThirtyTwoByte. entailer.\n Exists HSalsaRes. entailer. cancel.\ndestruct HSalsaRes as [q1 q2]. cancel.\nQed.\n\n(*The crypto_stream_xor function*)\nLemma crypto_stream_xsalsa20_tweet_xor_ok:\n      semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_stream_xsalsa20_tweet_xor\n      f_crypto_stream_xsalsa20_tweet_xor_spec.\nProof.\nstart_function.\nrename v_s into s. rename H into mLen. unfold data_at_, field_at_. simpl.\nunfold Sigma_vector.\nforward_call (gv _sigma, k, nonce, s,\n        default_val (tarray tuchar 32),\n        ((Nonce, SIGMA), K)).\n{ unfold CoreInSEP, SByte. cancel. }\nIntros v.\nunfold CoreInSEP, SByte, Sigma_vector. normalize.\nassert_PROP (isptr nonce) as PN by entailer!.\nassert (exists HSalsaRes, hSalsaOut v =\n   match HSalsaRes with (q1, q2) =>\n     SixteenByte2ValList q1 ++ SixteenByte2ValList q2\n   end).\n{ exists ((littleendian_invert (Znth 0 v),\n           littleendian_invert (Znth 5 v),\n           littleendian_invert (Znth 10 v),\n           littleendian_invert (Znth 15 v)),\n          (littleendian_invert (Znth 6 v),\n           littleendian_invert (Znth 7 v),\n           littleendian_invert (Znth 8 v),\n           littleendian_invert (Znth 9 v))).\n  do 2 rewrite SixteenByte2ValList_char. repeat rewrite <- app_assoc. trivial. }\ndestruct H0 as [[q1 q2] HS]. rewrite HS. \nforward_call (c, s, m, offset_val 16 nonce, d, Nonce2, (q1,q2), mCont, gv).\n{ unfold SByte, Sigma_vector, data_at_. cancel. }\nforward.\nExists (q1, q2). unfold ThirtyTwoByte. entailer!.\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/tweetnacl20140427/verif_crypto_stream.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.18294606486760573}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Locations.\nRequire Import DataType.\nRequire Import LAsm.\nRequire Import CDataTypes.\nRequire Import AsmExtra.\nRequire Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import PCurID.\nRequire Import PAbQueue.\nRequire Export CurIDGen.\nRequire Import PAbQueueCode.\nRequire Import ZArith.Zwf.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import Maps.\nRequire Import Heap.\nRequire Import RefinementTactic.\nRequire Import AuxLemma.\nRequire Import LayerTemplate2.\nRequire Import Implementation.\nRequire Import SeparateCompiler.\nRequire Import ClightImplemExtra.\nRequire Import LayerDefinition.\nRequire Import RealParams.\nRequire Import CInitSpecsMPTOp.\nRequire Import CInitSpecsMPTCommon.\nRequire Import CInitSpecsMPTBit.\nRequire Import CInitSpecsproc.\n\nOpen Local Scope string_scope.\nOpen Local Scope error_monad_scope.\n\nModule CURIDGENIMPL.\n  Export CurIDGen.CURIDGEN.\n\n  Lemma hprim_finite_type:\n    forall\n      (Q: PCURID.primOp -> Prop)\n      (Q_dec: forall p, {Q p} + {~ Q p}),\n      {forall p, Q p} + {~ forall p, Q p}.\n  Proof with (try (right; eauto; fail)).\n    intros.    \n    destruct (Q_dec PCURID.PAlloc)...\n    destruct (Q_dec PCURID.PFree)...\n    destruct (Q_dec PCURID.PSetPT)...\n    destruct (Q_dec PCURID.PPTRead)...\n    destruct (Q_dec PCURID.PPTResv)...\n    destruct (Q_dec PCURID.PKCtxtNew)...\n    destruct (Q_dec PCURID.PThreadFree)...\n    destruct (Q_dec PCURID.PKCtxtSwitch)...\n    destruct (Q_dec PCURID.PGetState)...\n    destruct (Q_dec PCURID.PSetState)...\n    destruct (Q_dec PCURID.PDeQueue)...\n    destruct (Q_dec PCURID.PEnQueue)...\n    destruct (Q_dec PCURID.PQueueRmv)...\n    destruct (Q_dec PCURID.PGetCurID)...\n    destruct (Q_dec PCURID.PSetCurID)...\n    destruct (Q_dec PCURID.PPTIn)...\n    destruct (Q_dec PCURID.PPTOut)...\n    destruct (Q_dec PCURID.PTrapIn)...\n    destruct (Q_dec PCURID.PTrapOut)...\n    destruct (Q_dec PCURID.PHostIn)...\n    destruct (Q_dec PCURID.PHostOut)...\n    destruct (Q_dec PCURID.PTrapGet)...\n    destruct (Q_dec PCURID.PTrapRet)...\n    destruct (Q_dec PCURID.PTDQueueInit)...\n    left; destruct p; assumption.\n  Defined.    \n\n  Section WithPrimitives.\n\n  Context `{real_params: RealParams}.\n\n    Notation HDATA := (PCURID.AbData(PgSize:=PgSize) (num_proc:=num_proc)(kern_low:=kern_low)\n                                    (kern_high:=kern_high) (maxpage:=maxpage) (num_chan := num_chan)).   \n    Notation LDATA := (PABQUEUE.AbData(PgSize:=PgSize)(num_proc:=num_proc) (kern_low:=kern_low)\n                                      (kern_high:=kern_high) (maxpage:=maxpage) (num_chan := num_chan)).                             \n  \n    Notation Hfundef := (Asm.fundef (external_function:= PCURID.primOp)).\n    Notation Lfundef := (Asm.fundef (external_function:= PABQUEUE.primOp)).\n\n    Notation funkind := (funkind (low:= PABQUEUE.primOp) Asm.code (Clight.fundef (external_function := PABQUEUE.primOp))).\n\n    Definition source_implem_extfuns (p: PCURID.primOp): funkind :=\n      match p with\n        | PCURID.PAlloc => Code _ (AST.External PABQUEUE.PAlloc)\n        | PCURID.PFree => Code _ (AST.External PABQUEUE.PFree)\n        | PCURID.PSetPT => Code _ (AST.External PABQUEUE.PSetPT)\n        | PCURID.PPTRead => Code _ (AST.External PABQUEUE.PPTRead)\n        | PCURID.PPTResv => Code _ (AST.External PABQUEUE.PPTResv)\n        | PCURID.PKCtxtNew => Code _ (AST.External PABQUEUE.PKCtxtNew)\n        | PCURID.PThreadFree => Code _ (AST.External PABQUEUE.PThreadFree)\n        | PCURID.PKCtxtSwitch => Code _ (AST.External PABQUEUE.PKCtxtSwitch)\n        | PCURID.PGetState => Code _ (AST.External PABQUEUE.PGetState)\n        | PCURID.PSetState => Code _ (AST.External PABQUEUE.PSetState)\n        | PCURID.PDeQueue => Code _ (AST.External PABQUEUE.PDeQueue)\n        | PCURID.PEnQueue => Code _ (AST.External PABQUEUE.PEnQueue)\n        | PCURID.PQueueRmv => Code _ (AST.External PABQUEUE.PQueueRmv)\n        | PCURID.PGetCurID => SourceFun (Clight.Internal PABQUEUECODE.f_get_curid) (AST.Internal nil)\n        | PCURID.PSetCurID => SourceFun (Clight.Internal PABQUEUECODE.f_set_curid) (AST.Internal nil)\n        | PCURID.PPTIn => Code _ (AST.External PABQUEUE.PPTIn)\n        | PCURID.PPTOut => Code _ (AST.External PABQUEUE.PPTOut)\n        | PCURID.PTrapIn => Code _ (AST.External PABQUEUE.PTrapIn)\n        | PCURID.PTrapOut => Code _ (AST.External PABQUEUE.PTrapOut)\n        | PCURID.PHostIn => Code _ (AST.External PABQUEUE.PHostIn)\n        | PCURID.PHostOut => Code _ (AST.External PABQUEUE.PHostOut)\n        | PCURID.PTrapGet => Code _ (AST.External PABQUEUE.PTrapGet)\n        | PCURID.PTrapRet => Code _ (AST.External PABQUEUE.PTrapRet)\n        | PCURID.PTDQueueInit => Code _ (AST.External PABQUEUE.PTDQueueInit)\n      end.\n\n    Notation varkind := (varkind unit Ctypes.type).\n\n    Definition source_implem_new_globs : list (ident * option (globdef funkind varkind)) :=\n        (CURID_LOC, Some (Gvar (mkglobvar (SourceVar tint tt) (wrap_init_data 1) false)))\n        :: nil.\n\n    Let NOREPET: list_norepet (CURID_LOC :: nil).\n    Proof.\n      case_eq (list_norepet_dec peq (CURID_LOC :: nil)); try discriminate; tauto.\n    Qed.\n\n    Definition source_implem : source_implem Asm.code unit PCURID.primOp (low := PABQUEUE.primOp) (Clight.fundef (external_function := PABQUEUE.primOp)) Ctypes.type.\n    Proof.\n      split.\n       exact source_implem_extfuns.\n       exact source_implem_new_globs.\n    Defined.\n\n    Let im : implem Asm.code unit PCURID.primOp (low := PABQUEUE.primOp) := implem_of_source_implem transf_clight_fundef Cshmgen.transl_globvar source_implem.\n\n    Notation Hprogram := (Asm.program (external_function:= PCURID.primOp)). \n    Notation Lprogram := (Asm.program (external_function:= PABQUEUE.primOp)).\n\n    Let Im_get_curid: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PCURID.PGetCurID).\n    Let Im_set_curid: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PCURID.PSetCurID).\n\n    Notation new_glbl := (new_glbl CURID_LOC).\n\n    Let impl_glbl :  list (ident * option (globdef Lfundef unit)) := nil.\n\n    (* This is basically an axiom that can be easily checked because PCURID.primOp is a finite type. However, in practice, generation of CertiKOS code will be very slow because compilation will have to occur twice, one for this check, and a second independently for the generation of the actual code. *)\n\n    Lemma extfun_compilation_succeeds_dec:\n      {forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm} +\n      {~ forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm}.\n    Proof.\n      apply hprim_finite_type.\n      intro.\n      destruct (source_implem_extfuns p); try (left; discriminate).\n      case_eq (transf_clight_fundef sf).\n       left. intros. inv H0. eauto.\n      intros. right. intro. exploit H0; eauto. destruct 1. congruence.\n    Defined.\n\n    Hypothesis extfun_compilation_succeeds:\n      forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm.\n\n    Section WithProg.\n\n    Variable prog: Hprogram.\n\n    Definition tprog: Lprogram := Implementation.transf_program im prog.\n\n    Let TRANSF: CURIDGEN.transf_program Im_get_curid Im_set_curid CURID_LOC impl_glbl prog = OK tprog.\n    Proof.\n      unfold tprog.\n      unfold Asm.program, Asm.fundef.\n      generalize (transf_program_eq im prog).\n      intros.\n      rewrite <- H.\n      unfold transf_program.\n      simpl.\n      f_equal.\n      apply FunctionalExtensionality.functional_extensionality.\n      destruct x; simpl.\n       reflexivity.\n      destruct p; reflexivity.\n    Qed.\n\n    Hypothesis prog_nonempty:\n      prog_defs_names prog <> nil.\n\n    Hypothesis prog_main_valid:\n      ~ Plt' (prog_main prog) (prog_first_symbol prog).\n\n    Hypothesis prog_first_valid:\n      ~ Plt' (prog_first_symbol prog) (get_next_symbol (map fst source_implem_new_globs)).\n\n    Let VALID_LOC: (CURID_LOC <> (prog_main prog)).\n    Proof.\n      intro.\n      exploit (get_next_symbol_prop CURID_LOC (map fst (source_implem_new_globs))).\n      simpl; tauto. \n      eapply Ple_not_Plt.\n      apply Ple_Ple'.\n      eapply Ple'_trans.\n      apply not_Plt'_Ple'.\n      eassumption.\n      apply not_Plt'_Ple'.\n      congruence.\n    Qed.       \n\n    Notation ge := (Genv.globalenv prog).\n    Notation tge := (Genv.globalenv tprog).\n        \n    Let NEW_INJ:  (forall s', Genv.find_symbol ge s' <> None -> \n                                     ~ In s' (map fst new_glbl)).\n    Proof.\n      change new_glbl with (implem_new_globs im).\n      eapply new_ids_fresh.\n      assumption.\n    Qed.\n\n    Let sprog : Clight.program (external_function := PABQUEUE.primOp) := source_program_only source_implem prog.\n    Let sge := Genv.globalenv sprog.\n\n    Let tsprog_strong : {tsprog | transf_clight_program sprog = OK tsprog}.\n    Proof.\n      case_eq (transf_clight_program sprog); eauto.\n      intros. exfalso.\n      refine (_ (Implementation.compilation_succeeds\n                    transf_clight_fundef\n                    Cshmgen.transl_globvar\n                    source_implem _ _ _\n                    prog)).\n      destruct 1.\n      exploit (transf_clight_fundef_to_program (external_function := PABQUEUE.primOp)); eauto.\n      unfold sprog in H.\n      congruence.\n      assumption.\n      simpl. destruct 1; try discriminate. destruct H0; try discriminate. \n      unfold Cshmgen.transl_globvar. eauto.\n    Qed.\n\n    Let tsprog := let (p, _) := tsprog_strong in p.\n\n    Let tsprog_prop : transf_clight_program sprog = OK tsprog.\n    Proof.\n      unfold tsprog.\n      destruct tsprog_strong.\n      assumption.\n    Qed.\n\n    Let tsge := Genv.globalenv tsprog.\n    \n    Lemma curid_loc_prop:\n      forall b0,\n        Genv.find_symbol tge CURID_LOC = Some b0 ->\n        Genv.find_symbol sge CURID_LOC = Some b0 /\\\n        Clight.type_of_global sge b0 = Some tint.\n    Proof.\n      intros.\n      refine (_ (find_new_var_prop _ _ source_implem NOREPET _ NEW_INJ\n                                   CURID_LOC\n                                   (mkglobvar (SourceVar tint tt) (wrap_init_data 1) false)\n                                   _ (refl_equal _) H)).\n      destruct 1.\n      split; auto.\n      unfold Clight.type_of_global.\n      unfold sge, sprog.\n      rewrite H1.\n      reflexivity.\n      simpl; tauto.\n    Qed.\n\n    Let well_idglob_impl_glbl: Genv.well_idglob_list impl_glbl = true.\n    Proof. reflexivity. Qed.\n\n    Let CURID_LOC_not_in: ~ In CURID_LOC (prog_defs_names prog).\n    Proof.\n      intro. exploit Genv.find_symbol_exists_ex; eauto. destruct 1.\n      assert (Genv.find_symbol ge CURID_LOC <> None) by congruence.\n      eapply NEW_INJ; eauto.\n      simpl; tauto.\n    Qed.\n\n    Lemma tprog_first_next:\n      prog_first_symbol tprog = get_first_symbol (map fst source_implem_new_globs) /\\\n      prog_next_symbol  tprog = prog_next_symbol prog.\n    Proof.\n      change (get_first_symbol (map fst source_implem_new_globs)) with (implem_first_symbol im).\n      unfold tprog.\n      apply transf_program_first_next_symbol.\n      assumption.\n      assumption.\n      discriminate.\n    Qed.\n\n    Lemma tprog_main_valid:\n      ~ Plt' (prog_main tprog) (prog_first_symbol tprog).\n    Proof.\n      Opaque Plt'.\n      simpl.\n      destruct tprog_first_next.\n      rewrite H.\n      apply Ple'_not_Plt'.\n      eapply Ple'_trans.\n      apply first_le_next.\n      discriminate.\n      eapply Ple'_trans.\n      apply not_Plt'_Ple'.\n      eassumption.\n      apply not_Plt'_Ple'.\n      assumption.\n    Qed.\n\n    Lemma tprog_nonempty:\n      prog_defs_names tprog <> nil.\n    Proof.\n      apply transf_program_nonempty.\n      assumption.\n    Qed.\n\n    Context `{PageFaultHandler_LOC: ident}.\n\n    Section WITHMEM.\n      \n      Local Instance HdataOp:AbstractDataOps HDATA:= (PCURID.abstract_data (Hnpc:= Hnpc)).\n\n      Context {mem__H} {mem__L}\n              `{Hlmmh: !LayerMemoryModel HDATA mem__H}\n              `{Hlmml: !LayerMemoryModel LDATA mem__L}\n              `{Hlmi: !LayerMemoryInjections HDATA LDATA mem__H mem__L}.\n\n      Instance HLayer: LayerDefinition (layer_mem:= Hlmmh) HDATA PCURID.primOp mem__H :=\n        PCURID.layer_def (Hnpc:=Hnpc)(PgSize:=PgSize) (num_proc:=num_proc)(HPS4:=HPS4)(Hlow:=Hlow)(Hhigh:=Hhigh)\n                         (kern_low:=kern_low) (kern_high:=kern_high) (maxpage:=maxpage) (real_abtcb := real_abtcb)\n                         (real_nps:=real_nps) (real_AT := real_AT)(real_ptp:=real_ptp)(real_pt:=real_pt) \n                         (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)\n                         (num_chan:= num_chan) (real_abq:= real_abq) (Hnchan:= Hnchan).\n      \n      Instance LLayer: LayerDefinition (layer_mem:= Hlmml) LDATA PABQUEUE.primOp mem__L :=\n        PABQUEUE.layer_def (Hnpc:=Hnpc)(PgSize:=PgSize) (num_proc:=num_proc)(HPS4:=HPS4)(Hlow:=Hlow)(Hhigh:=Hhigh)\n                           (kern_low:=kern_low) (kern_high:=kern_high) (maxpage:=maxpage) (real_abtcb := real_abtcb)\n                           (real_nps:=real_nps) (real_AT := real_AT)(real_ptp:=real_ptp)(real_pt:=real_pt) \n                           (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)\n                           (num_chan:= num_chan) (real_abq:= real_abq) (Hnchan:= Hnchan).    \n\n      Notation LLoad := (PABQUEUE.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation LStore := (PABQUEUE.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation HLoad := (PCURID.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation HStore := (PCURID.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n\n      Notation lstep := (PABQUEUE.step (NPT_LOC:=NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC) (HPS4:= HPS4)\n                                       (real_nps:= real_nps) (real_AT:= real_AT) (Hlow:= Hlow) (Hhigh:= Hhigh)\n                                       (real_ptp := real_ptp) (real_pt:= real_pt) (Hnpc := Hnpc) (real_ptb:= real_ptb)\n                                       (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)(real_abtcb:=real_abtcb)\n                                       (Hnchan := Hnchan) (real_abq:= real_abq)).\n\n      Notation LADT := PABQUEUE.ADT.\n\n      Let get_curid_spec:\n        forall r' b m'0 b1 r sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_get_curid)\n          -> Genv.find_funct_ptr ge b = Some (External PCURID.PGetCurID)\n          -> Genv.find_symbol tge CURID_LOC = Some b1\n          -> Mem.load Mint32 m'0 b1 0 = Some (Vint r)\n          -> PABQUEUE.ikern (LADT (Mem.get_abstract_data m'0)) = true\n          -> PABQUEUE.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PABQUEUE.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b1 = Some Tag_global\n          -> sig = mksignature nil (Some Tint)\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig nil                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m'0)) f' \n               /\\ Memtype.Mem.inject f' m'0 m0'\n               /\\ Mem.nextblock m'0 <= Mem.nextblock m0'              \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ r_ # (loc_external_result sig) = (Vint r)\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n        Proof.\n          intros.          \n          exploit curid_loc_prop; eauto.\n          destruct 1.\n          exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                     PCURID.primOp\n                     (exec_load := LLoad)\n                     (exec_store := LStore)\n                     (primitive_call := PABQUEUE.primitive_call)\n                     (is_primitive_call := PABQUEUE.is_primitive_call)\n                     (kernel_mode := PABQUEUE.kernel_mode)\n                  ).\n          apply PABQUEUE.exec_load_exec_loadex.\n          apply PABQUEUE.exec_store_exec_storeex.\n          apply PABQUEUE.extcall_not_primitive.\n          apply PABQUEUE.primitive_kernel_mode.\n          3: eassumption.\n          assumption.\n          assumption.\n          2: eassumption.\n          5: eassumption.\n          9: eassumption.\n          7: reflexivity.\n          intros; eapply PABQUEUECODE.get_curid_correct; eauto.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          unfold PABQUEUE.kernel_mode.\n          destruct (PABQUEUE.INV (Mem.get_abstract_data m'0)).\n          auto.\n          destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n          inv H20.\n          eauto 11.\n        Qed.\n\n    Let set_curid_spec:\n      forall r' b m'0 b0 m0 i sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_set_curid)\n          -> Genv.find_funct_ptr ge b = Some (External PCURID.PSetCurID)\n          -> Genv.find_symbol tge CURID_LOC = Some b0\n          -> Mem.store Mint32 m'0 b0 0 (Vint i) = Some m0\n          -> PABQUEUE.ikern (LADT (Mem.get_abstract_data m'0)) = true\n          -> PABQUEUE.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PABQUEUE.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b0 = Some Tag_global\n          -> sig = mksignature (Tint::nil) None\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint i:: nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m0)) f' \n               /\\ Memtype.Mem.inject f' m0 m0'\n               /\\ Mem.nextblock m0 <= Mem.nextblock m0'              \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ True\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n    Proof.\n      intros.\n      exploit curid_loc_prop; eauto.\n      destruct 1.      \n      exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                 PCURID.primOp\n                 (exec_load := LLoad)\n                 (exec_store := LStore)\n                 (primitive_call := PABQUEUE.primitive_call)\n                 (is_primitive_call := PABQUEUE.is_primitive_call)\n                 (kernel_mode := PABQUEUE.kernel_mode)\n              ).\n      apply PABQUEUE.exec_load_exec_loadex.\n      apply PABQUEUE.exec_store_exec_storeex.\n      apply PABQUEUE.extcall_not_primitive.\n      apply PABQUEUE.primitive_kernel_mode.\n      3: eassumption.\n      assumption.\n      assumption.\n      2: eassumption.\n      5: eassumption.\n      9: eassumption.\n      7: reflexivity.\n      intros; eapply PABQUEUECODE.set_curid_correct; eauto.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      unfold PABQUEUE.kernel_mode.\n      destruct (PABQUEUE.INV (Mem.get_abstract_data m'0)).\n      auto.\n      destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ H3).\n      eauto 11.\n    Qed.\n\n    Theorem transf_program_correct:\n      Smallstep.backward_simulation \n          (PCURID.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC)  \n                            (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= Hlmmh) (HPS4:= HPS4) (Hnpc:= Hnpc)\n                            (Hlow := Hlow) (Hhigh:= Hhigh) (real_ptp:= real_ptp) (real_pt:= real_pt) (real_abq:= real_abq)\n                            (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)\n                            (num_chan:= num_chan) (real_abtcb:= real_abtcb) (Hnchan:= Hnchan) prog) \n          (PABQUEUE.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC) \n                              (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= Hlmml) (HPS4:= HPS4) \n                              (Hlow := Hlow) (Hhigh:= Hhigh) (real_ptp:= real_ptp) (real_pt:= real_pt)\n                              (Hnpc:= Hnpc) (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC) \n                              (real_abtcb:= real_abtcb) (Hnchan:= Hnchan) (real_abq:= real_abq) tprog).\n    Proof.\n      eapply CURIDGEN.transf_program_correct; simpl; eauto.\n      Grab Existential Variables.\n      omega.\n    Qed.\n\n    End WITHMEM.\n\n    End WithProg.\n\n End WithPrimitives.\n\nEnd CURIDGENIMPL.\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/CurIDGenImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.18294605387050997}}
{"text": "From Perennial.goose_lang Require Import prelude.\nFrom Perennial.goose_lang Require Export ffi.grove_prelude.\nFrom Perennial.program_proof Require Import proof_prelude.\nFrom Perennial.program_proof.ctrexample Require Import interface.\nFrom Perennial.program_proof Require Import marshal_proof.\nFrom Goose.github_com.mit_pdos.gokv.ctrexample Require Import client.\nFrom Perennial.program_proof.grove_shared Require Import urpc_proof.\nFrom Perennial.program_proof.ctrexample Require Import wpc_proofmode.\n\nSection client_proof.\n\nContext `{!heapGS \u03a3}.\nContext `{!filesysG \u03a3}.\nContext `{!inG \u03a3 mono_natUR}.\nContext `{!urpcregG \u03a3}.\n\nLemma wpc_ClientMain \u03b3urpc_gn \u03b3 :\n  is_CtrServer_urpc \u03b3urpc_gn \u03b3 -\u2217\n    counter_lb \u03b3 0 -\u2217\n    WP main #()\n  {{\n      v, True\n  }}.\nProof.\n  iIntros \"#Hsrv #Hlb\".\n  wp_lam.\n  wp_pures.\n  wp_apply (wp_MakeClient).\n  iIntros (cl_ptr) \"Hcl\".\n  wp_pures.\n  wp_apply (wp_ref_to).\n  { eauto. }\n  iIntros (localBound_ptr) \"HlocalBound\".\n  wp_pures.\n\n  iAssert (\u2203 x, counter_lb \u03b3 x \u2217 localBound_ptr \u21a6[uint64T] #(U64 x))%I with \"[HlocalBound Hlb]\" as \"HH\".\n  {\n    iExists 0%nat. iFrame \"#\u2217\".\n  }\n  wp_forBreak.\n  wp_pures.\n\n  iClear \"Hlb\".\n  iDestruct \"HH\" as (localBound) \"[#Hlb HlocalBound]\".\n\n  wp_apply (wp_ref_of_zero).\n  { done. }\n  iIntros (rep) \"Hrep\".\n  wp_pures.\n  wp_apply (wp_NewSlice _ _ byteT).\n  iIntros (empty_req) \"Hempty_sl\".\n\n  iDestruct (is_slice_to_small with \"Hempty_sl\") as \"Hempty_sl\".\n  wp_apply (wp_Client__Call with \"[] [$Hcl $Hrep $Hempty_sl]\").\n  { iDestruct \"Hsrv\" as \"[$ _]\". }\n  {\n    instantiate (1:=(\u03bb l, \u2203 (x:nat), \u231chas_encoding l [EncUInt64 (U64 x)] \u2227 localBound \u2264 x\u231d \u2217 counter_lb \u03b3 x)%I).\n    iModIntro.\n    iModIntro.\n    simpl.\n    iIntros (x) \"Hctr\".\n    rewrite /counter_own /counter_lb.\n    iDestruct (own_valid_2 with \"Hctr Hlb\") as %Hineq.\n    (* FIXME: Q: what is setoid_rewrite, and why does it work when rewrite does not? *)\n    setoid_rewrite mono_nat_both_valid in Hineq.\n    rewrite mono_nat_auth_lb_op.\n    iDestruct (own_op with \"Hctr\") as \"[Hctr #Hlb2]\".\n    iDestruct (own_update with \"Hctr\") as \">$\".\n    { apply mono_nat_update. word. }\n    iModIntro.\n    iIntros.\n    iExists x.\n    unfold counter_lb.\n    iFrame \"#\".\n    iPureIntro.\n    split.\n    { done. }\n    lia.\n  }\n  iIntros (err) \"(Hcl & Hreq & Hrep)\".\n  wp_pures.\n  wp_if_destruct.\n  {\n    iLeft. iModIntro.\n    iSplitL \"\"; first done.\n    iFrame \"\u2217#\".\n    iExists _; iFrame \"\u2217#\".\n  }\n  destruct err.\n  {\n    exfalso.\n    destruct c; done.\n  }\n  iNamed \"Hrep\".\n  iDestruct \"Hrep\" as \"(Hrep & Hrep_sl & HPost)\".\n  iDestruct \"HPost\" as (x) \"[[%HencPost %Hlb2] Hlb2]\".\n  wp_pures.\n  wp_load.\n  wp_apply (wp_new_dec with \"[Hrep_sl]\").\n  { done. }\n  { done. }\n  iIntros (dec) \"Hdec\".\n  wp_pures.\n  wp_apply (wp_Dec__GetInt with \"Hdec\").\n  iIntros \"Hdec\".\n  wp_pures.\n  wp_load.\n  wp_pures.\n  wp_apply (wp_Assert).\n  {\n    apply bool_decide_eq_true.\n    (* FIXME: overflow related *)\n    admit.\n  }\n  wp_pures.\n  wp_store.\n  iModIntro.\n  iLeft.\n  iSplitL \"\"; first done.\n  iFrame.\n  iExists _; iFrame \"\u2217#\".\nAdmitted.\n\nEnd client_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/ctrexample/client.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.18293282003973224}}
{"text": "Require Import RelationClasses.\nRequire Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import MemoryDomain.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive sim_local (pview:SimPromises.t) (lc_src lc_tgt:Local.t): Prop :=\n| sim_local_intro\n    (TVIEW: TView.le (Local.tview lc_src) (Local.tview lc_tgt))\n    (PROMISES: SimPromises.sem pview SimPromises.bot (Local.promises lc_src) (Local.promises lc_tgt))\n.\n\n#[export]\nProgram Instance sim_local_PreOrder: PreOrder (sim_local SimPromises.bot).\nNext Obligation.\n  econs; try refl. apply SimPromises.sem_bot.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. econs; try etrans; eauto.\n  apply SimPromises.sem_bot_inv in PROMISES; auto.\n  apply SimPromises.sem_bot_inv in PROMISES0; auto.\n  rewrite PROMISES, PROMISES0. apply SimPromises.sem_bot.\nQed.\n\nLemma sim_local_nonsynch_loc\n      pview loc lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch_loc loc (Local.promises lc_tgt)):\n  Memory.nonsynch_loc loc (Local.promises lc_src).\nProof.\n  inv SIM. inv PROMISES.\n  ii. destruct msg; ss.\n  destruct (Memory.get loc t (Local.promises lc_tgt)) as [[? []]|] eqn:GET_TGT.\n  - exploit NONSYNCH; eauto. ss. i. subst.\n    exploit LE; eauto. intro X. rewrite GET in X. inv X.\n    unfold SimPromises.none_if, SimPromises.none_if_released. condtac; ss.\n  - exploit LE; eauto. s. i. congr.\n  - exploit COMPLETE; eauto. rewrite SimPromises.bot_spec. ss.\nQed.\n\nLemma sim_local_nonsynch\n      pview lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch (Local.promises lc_tgt)):\n  Memory.nonsynch (Local.promises lc_src).\nProof.\n  ii. eapply sim_local_nonsynch_loc; eauto.\nQed.\n\nLemma sim_local_memory_bot\n      pview lc_src lc_tgt\n      (SIM: sim_local pview lc_src lc_tgt)\n      (BOT: (Local.promises lc_tgt) = Memory.bot):\n  (Local.promises lc_src) = Memory.bot.\nProof.\n  inv SIM. inv PROMISES. rewrite BOT in *.\n  apply Memory.ext. i. rewrite Memory.bot_get.\n  destruct (Memory.get loc ts (Local.promises lc_src)) eqn:GET_SRC; ss.\n  destruct p.\n  exploit COMPLETE; eauto.\n  - apply Memory.bot_get.\n  - rewrite SimPromises.bot_spec. ss.\nQed.  \n\nLemma sim_local_promise\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to (SimPromises.none_if loc to pview msg) lc2_src mem2_src (SimPromises.kind_transf loc to pview kind)>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit sim_memory_closed_message; eauto. i.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { unfold SimPromises.none_if, SimPromises.none_if_released.\n    destruct msg; try condtac; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto. SimPromises.none_if_tac. eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_promise_bot\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit sim_local_promise; eauto.\n  rewrite SimPromises.none_if_bot.\n  rewrite SimPromises.kind_transf_bot. ss.\nQed.\n\nLemma sim_local_read\n      pview\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt ord_tgt lc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; eauto. i. des.\n  inv MSG. esplits; eauto.\n  - econs; eauto. eapply TViewFacts.readable_mon; eauto. apply TVIEW.\n  - econs; eauto. s. apply TViewFacts.read_tview_mon; auto.\n    + apply WF1_TGT.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des. inv MSG_WF. auto.\nQed.\n\nLemma sim_local_fulfill\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (PVIEW: SimPromises.mem loc to pview = false \\/ Ordering.le ord_tgt Ordering.plain)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src (SimPromises.none_if_released loc to pview released) ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local (SimPromises.unset loc to pview) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  guardH PVIEW.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { apply TViewFacts.write_released_mon; ss.\n    - apply LOCAL1.\n    - apply WF1_TGT.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  { econs. ss. }\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  { apply WF1_TGT. }\n  i. des. esplits.\n  - econs; eauto.\n    + SimPromises.none_if_tac.\n      * unguardH PVIEW. des; ss. unfold TView.write_released. condtac; [|refl].\n        destruct ord_src, ord_tgt; inv ORD; inv PVIEW; inv COND0.\n      * etrans; eauto.\n    + SimPromises.none_if_tac; viewtac.\n    + eapply TViewFacts.writable_mon; try exact WRITABLE; eauto. apply LOCAL1.\n  - econs; eauto. s. apply TViewFacts.write_tview_mon; auto.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n  - ss.\nQed.\n\nLemma sim_local_fulfill_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  exploit sim_local_fulfill; eauto.\n  { rewrite SimPromises.bot_spec. intuition. }\n  i. des. esplits; eauto.\n  rewrite SimPromises.unset_bot in *; ss.\nQed.\n\nLemma sim_local_promise_not_lower\n      pview\n      lc1_src\n      lc1_tgt mem1_tgt loc from to msg_tgt lc1 mem2_tgt kind\n      (LOCAL: sim_local pview lc1_src lc1_tgt)\n      (STEP: Local.promise_step lc1_tgt mem1_tgt loc from to msg_tgt lc1 mem2_tgt kind)\n      (KIND: negb (Memory.op_kind_is_lower kind)):\n  SimPromises.mem loc to pview = false.\nProof.\n  destruct (SimPromises.mem loc to pview) eqn:X; ss.\n  inv LOCAL. inv PROMISES. exploit PVIEW; eauto. i. des.\n  inv STEP. inv PROMISE; ss.\n  - exploit Memory.add_get0; try exact PROMISES; eauto. i. des. congr.\n  - exploit Memory.split_get0; try exact PROMISES; eauto. i. des. congr.\n  - exploit Memory.remove_get0; try exact PROMISES; eauto. i. des. congr.\nQed.\n\nLemma sim_local_write\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (PVIEW: SimPromises.mem loc to pview = false \\/\n              Ordering.le ord_tgt Ordering.plain \\/\n              Ordering.le Ordering.strong_relaxed ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src\n                                 released_src\n                                 ord_src lc2_src sc2_src mem2_src\n                                 (SimPromises.kind_transf loc to pview kind)>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local (SimPromises.unset loc to pview) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  guardH PVIEW.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_fulfill; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { unguardH PVIEW. des; intuition.\n    exploit Local.write_step_strong_relaxed; eauto. i.\n    left. eapply sim_local_promise_not_lower; try exact STEP1; eauto.\n  }\n  i. des.\n  exploit promise_fulfill_write; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. subst. esplits; eauto.\n  - apply TViewFacts.write_released_mon; ss;\n      try apply LOCAL1; try apply WF1_TGT.\n  - etrans; eauto.\nQed.\n\nLemma sim_local_write_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src\n                                 released_src\n                                 ord_src lc2_src sc2_src mem2_src\n                                 kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  hexploit sim_local_write; eauto.\n  { rewrite SimPromises.bot_spec. intuition. }\n  i. des. esplits; eauto.\n  - rewrite SimPromises.kind_transf_bot in *. eauto.\n  - rewrite SimPromises.unset_bot in *; ss.\nQed.\n\nLemma sim_local_update\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (PVIEW: SimPromises.mem loc to2 pview = false \\/\n              Ordering.le ord2_tgt Ordering.plain \\/\n              Ordering.le Ordering.strong_relaxed ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src\n                                  (SimPromises.kind_transf loc to2 pview kind)>> /\\\n    <<LOCAL3: sim_local (SimPromises.unset loc to2 pview) lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  guardH PVIEW.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_update_bot\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src kind>> /\\\n    <<LOCAL3: sim_local SimPromises.bot lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write_bot; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_fence\n      pview\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt sc1_tgt ordr_tgt ordw_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: Local.fence_step lc1_src sc1_src ordr_src ordw_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local pview lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT. esplits; eauto.\n  - econs; eauto. i. eapply sim_local_nonsynch; eauto.\n  - econs; try apply LOCAL1. s.\n    apply TViewFacts.write_fence_tview_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n    + eapply TViewFacts.read_fence_future; apply WF1_SRC.\n  - apply TViewFacts.write_fence_sc_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\nQed.\n\nLemma sim_local_promise_consistent\n      pview\n      lc_src lc_tgt\n      (LOCAL: sim_local pview lc_src lc_tgt)\n      (CONS_TGT: Local.promise_consistent lc_tgt):\n  <<CONS_SRC: Local.promise_consistent lc_src>>.\nProof.\n  inv LOCAL. inv PROMISES. ii.\n  destruct (Memory.get loc ts (Local.promises lc_tgt)) as [[]|] eqn:GETP.\n  - exploit LE; eauto. intro x. rewrite PROMISE in x. inv x.\n    destruct t0; ss.\n    exploit CONS_TGT; eauto. i.\n    eapply TimeFacts.le_lt_lt; eauto.\n    inv TVIEW. inv CUR. eauto.\n  - exploit COMPLETE; eauto. intro x.\n    rewrite MemoryDomain.bot_spec in x. ss.\nQed.\n\nLemma sim_local_failure\n      pview\n      lc1_src lc1_tgt\n      (STEP_TGT: Local.failure_step lc1_tgt)\n      (LOCAL1: sim_local pview lc1_src lc1_tgt):\n  <<STEP_SRC: Local.failure_step lc1_src>>.\nProof.\n  inv STEP_TGT.\n  hexploit sim_local_promise_consistent; eauto.\nQed.\n\nLemma sim_local_program_step\n      lang\n      th1_src\n      th1_tgt th2_tgt e_tgt\n      (STEP_TGT: @Thread.program_step lang e_tgt th1_tgt th2_tgt)\n      (WF1_SRC: Local.wf (Thread.local th1_src) (Thread.memory th1_src))\n      (WF1_TGT: Local.wf (Thread.local th1_tgt) (Thread.memory th1_tgt))\n      (SC1_SRC: Memory.closed_timemap (Thread.sc th1_src) (Thread.memory th1_src))\n      (SC1_TGT: Memory.closed_timemap (Thread.sc th1_tgt) (Thread.memory th1_tgt))\n      (MEM1_SRC: Memory.closed (Thread.memory th1_src))\n      (MEM1_TGT: Memory.closed (Thread.memory th1_tgt))\n      (STATE: (Thread.state th1_src) = (Thread.state th1_tgt))\n      (LOCAL: sim_local SimPromises.bot (Thread.local th1_src) (Thread.local th1_tgt))\n      (SC: TimeMap.le (Thread.sc th1_src) (Thread.sc th1_tgt))\n      (MEM: sim_memory (Thread.memory th1_src) (Thread.memory th1_tgt)):\n  exists e_src th2_src,\n    <<STEP_SRC: @Thread.program_step lang e_src th1_src th2_src>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<STATE: (Thread.state th2_src) = (Thread.state th2_tgt)>> /\\\n    <<LOCAL: sim_local SimPromises.bot (Thread.local th2_src) (Thread.local th2_tgt)>> /\\\n    <<SC: TimeMap.le (Thread.sc th2_src) (Thread.sc th2_tgt)>> /\\\n    <<MEM: sim_memory (Thread.memory th2_src) (Thread.memory th2_tgt)>>.\nProof.\n  destruct th1_src. ss. subst. inv STEP_TGT; ss.\n  inv LOCAL0; ss.\n  - esplits; (try by econs; [|econs 1]; eauto); ss.\n  - exploit sim_local_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 2]; eauto); ss.\n  - hexploit sim_local_write_bot; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 3]; eauto); ss.\n  - exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read; eauto; try refl. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    hexploit sim_local_write_bot; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 4]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 5]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 6]; eauto); ss.\n  - exploit sim_local_failure; eauto. i. des.\n    esplits; (try by econs; [|econs 7]; eauto); ss.\nQed.\n\nLemma sim_local_lower_src\n      pview1\n      lc1_src sc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_src mem2_src\n      loc from to val released\n      (LOCAL1: sim_local pview1 lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (STEP_SRC: Local.promise_step lc1_src mem1_src loc from to (Message.full val None) lc2_src mem2_src (Memory.op_kind_lower (Message.full val released))):\n  <<LOCAL2: exists pview2, sim_local pview2 lc2_src lc1_tgt>> /\\\n  <<MEM2: sim_memory mem2_src mem1_tgt>> /\\\n  <<WF2_SRC: Local.wf lc2_src mem2_src>>.\nProof.\n  splits.\n  - inv STEP_SRC. inv PROMISE.\n    exists (match Memory.get loc to (Local.promises lc1_tgt) with\n       | Some _ => SimPromises.set loc to pview1\n       | None => pview1\n       end).\n    inv LOCAL1. econs; ss. inv PROMISES0. econs; ss.\n    + ii.\n      exploit LE; eauto. intro x.\n      exploit Memory.lower_get0; try exact PROMISES; eauto. i.\n      erewrite Memory.lower_o; eauto.\n      unfold SimPromises.none_if, SimPromises.none_if_released.\n      destruct (Memory.get loc to (Local.promises lc1_tgt)) eqn:TGT.\n      * rewrite SimPromises.set_o. condtac; ss.\n        { des. subst. condtac; ss; cycle 1.\n          { revert COND0. condtac; ss. des; congr. }\n          rewrite GET in x. inv x. destruct msg; ss. inv H1; ss.\n        }\n        { guardH o. condtac.\n          { revert COND0. condtac; ss.\n            { des. subst. unguardH o. des; congr. }\n            guardH o0. i.\n            rewrite x. repeat f_equal. SimPromises.none_if_tac.\n          }\n          rewrite x. repeat f_equal. SimPromises.none_if_tac.\n          revert COND0. condtac; ss.\n        }\n      * condtac; ss. des. subst. congr.\n    + i. revert MEM0. condtac; ss; cycle 1.\n      { eapply PVIEW. }\n      rewrite SimPromises.set_o. condtac; ss; cycle 1.\n      { eapply PVIEW. }\n      i. des. subst. destruct p. destruct t0; eauto.\n      exploit LE; eauto. ss. i.\n      exploit Memory.lower_get0; try exact PROMISES; eauto. i. des. congr.\n    + i. revert SRC. erewrite Memory.lower_o; eauto. condtac; ss.\n      * i. des. inv SRC. eapply COMPLETE; eauto.\n        hexploit Memory.lower_get0; try exact PROMISES; eauto. i. des. eauto.\n      * i. eapply COMPLETE; eauto.\n  - etrans; [|eauto]. inv STEP_SRC. inv PROMISE. eapply lower_sim_memory; eauto. econs.\n  - eapply Local.promise_step_future; eauto.\nQed.\n\nLemma sim_local_nonsynch_src\n      pview\n      lang st sc\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      (LOCAL1: sim_local pview lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (LOCAL1_SRC: Local.wf lc1_src mem1_src)\n      (LOCAL2_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists pview2 lc2_src mem2_src,\n    <<STEP_SRC: rtc (@Thread.tau_step lang)\n                    (Thread.mk lang st lc1_src sc mem1_src)\n                    (Thread.mk lang st lc2_src sc mem2_src)>> /\\\n    <<NONSYNCH2: Memory.nonsynch (Local.promises lc2_src)>> /\\\n    <<LOCAL2: sim_local pview2 lc2_src lc1_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem1_tgt>>.\nProof.\n  inversion LOCAL1_SRC.\n  destruct FINITE. rename x into dom.\n  assert (FINITE' : forall (loc : Loc.t) (from to : Time.t) (msg : Message.t),\n             Memory.get loc to (Local.promises lc1_src) = Some (from, msg) ->\n             (match msg with\n              | Message.full _ (Some _) => True\n              | _ => False\n              end) ->\n             In (loc, to) dom).\n  { ii. eapply H. eauto. }\n  clear H. move dom after lc1_src. revert_until dom. revert pview.\n  induction dom.\n  { esplits; eauto. ii. destruct msg; ss. destruct released; ss.\n    exfalso. eapply FINITE'; eauto. ss.\n  }\n  destruct a as [loc to]. i.\n  destruct (Memory.get loc to (Local.promises lc1_src)) as [[? []]|] eqn:X; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intro x. inv x; ss.\n    inv H1. rewrite X in H. inv H. inv H0. }\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intro x. inv x; ss.\n    inv H1. congr.\n  }\n  destruct released; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. intro x. inv x; ss.\n    inv H1. rewrite H in X. inv X. ss.\n  }\n  exploit MemoryFacts.promise_exists_None; eauto.\n  { eapply MemoryFacts.released_time_lt; [by apply MEM1_SRC|]. apply LOCAL1_SRC. eauto. }\n  i. des.\n  exploit Memory.promise_future; try exact x0; try apply LOCAL1_SRC; eauto. i. des.\n  exploit sim_local_lower_src; eauto. i. des.\n  exploit IHdom; eauto.\n  { eapply Memory.future_closed_timemap; eauto. }\n  { eapply TView.future_closed; eauto. }\n  { s. i. inv x0. revert H.\n    erewrite Memory.lower_o; eauto. condtac; ss.\n    - i. des. inv H. ss.\n    - guardH o. i. exploit FINITE'; eauto. intro x. des; ss. inv x.\n      unguardH o. des; congr.\n  }\n  i. des. esplits; try exact NONSYNCH2; eauto.\n  econs 2; eauto. econs.\n  - econs. econs 1. econs; eauto.\n  - 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/SimLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1828208726055372}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Nat.\nRequire Import bedrock2.Array.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.Lift1Prop.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Scalars.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.Loops.\nRequire Import bedrock2.WeakestPrecondition.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import bedrock2.ZnWords.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Word.LittleEndianList.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Properties.\nRequire Import coqutil.Byte.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Tactics.Simp.\nRequire Import coqutil.Tactics.letexists.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.StateMachineProperties.\nRequire Import Bedrock2Experiments.Tactics.\nRequire Import Bedrock2Experiments.Word.\nRequire Import Bedrock2Experiments.WordProperties.\nRequire Import HmacSoftware.Constants.\nRequire Import HmacSoftware.HmacSemantics.\nRequire Import HmacSoftware.Hmac.\nRequire Import HmacSpec.SHA256.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIOPropertiesUnique.\nRequire Import Bedrock2Experiments.LibBase.BitfieldProperties.\nRequire Import Bedrock2Experiments.LibBase.MMIOLabels.\nImport Syntax.Coercions List.ListNotations HList.\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nLocal Open Scope Z_scope.\n\n(* TODO move to coqutil *)\nModule byte.\n  Lemma of_Z_unsigned: forall b,\n    byte.of_Z (byte.unsigned b) = b.\n  Proof.\n    intros. eapply byte.unsigned_inj. rewrite byte.unsigned_of_Z.\n    apply byte.wrap_unsigned.\n  Qed.\nEnd byte.\n\nModule List.\n  Lemma firstn_add{A: Type}(n m: nat)(l: list A):\n    List.firstn (n + m) l = List.firstn n l ++ List.firstn m (List.skipn n l).\n  Proof.\n    rewrite <- (List.firstn_skipn n l) at 1.\n    push_firstn; push_length; natsimpl.\n    apply Nat.min_case_strong; intros; push_firstn; repeat (f_equal; try lia).\n  Qed.\nEnd List.\n\nLemma le_split_combine: forall bs n,\n    n = List.length bs ->\n    le_split n (le_combine bs) = bs.\nProof. intros. subst. apply split_le_combine. Qed.\n\nHint Rewrite @length_le_split : push_length.\n\n(* bedrock2.ProgramLogic does cbv, which unfolds all constants *)\nLtac normalize_body_of_function f ::= Tactics.rdelta.rdelta f.\n\nSection Proofs.\n  Context {word: word.word 32} {mem: map.map word byte}\n          {word_ok: word.ok word} {mem_ok: map.ok mem}.\n  Context {timing: timing}.\n\n  (* Plug in the right state machine parameters; typeclass inference struggles here *)\n  Local Notation execution := (execution (M:=hmac_state_machine)).\n\n  Infix \"^+\" := word.add  (at level 50, left associativity).\n  Infix \"^-\" := word.sub  (at level 50, left associativity).\n  Infix \"^*\" := word.mul  (at level 40, left associativity).\n  Infix \"^<<\" := word.slu  (at level 37, left associativity).\n  Infix \"^>>\" := word.sru  (at level 37, left associativity).\n  Notation \"/[ x ]\" := (word.of_Z x) (* squeeze a Z into a word (beat it with a / to make it smaller) *)\n                         (format \"/[ x ]\").\n  Notation \"\\[ x ]\" := (word.unsigned x)  (* \\ is the open (removed) lid of the modulo box *)\n                         (format \"\\[ x ]\").    (* let a word fly into the large Z space *)\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  Lemma invert_read_status_done_false: forall input n val s,\n      read_step 4 (PROCESSING input n)\n                /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] val s ->\n      Z.testbit \\[val ^>> /[HMAC_INTR_STATE_HMAC_DONE_BIT]] 0 = false ->\n      s = PROCESSING input (n - 1) /\\ 0 < n.\n  Proof.\n    intros.\n    remember /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] as addr.\n    inversion H; subst. 1: auto.\n    exfalso. unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.\n    rewrite word.unsigned_sru_nowrap in H0. 2: {\n      rewrite word.unsigned_of_Z_0. reflexivity.\n    }\n    rewrite word.unsigned_of_Z_0 in H0.\n    rewrite Z.shiftr_0_r in H0.\n    congruence.\n  Qed.\n\n  Lemma invert_read_status_done_true: forall input n val s,\n      read_step 4 (PROCESSING input n)\n                /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] val s ->\n      Z.testbit \\[val ^>> /[HMAC_INTR_STATE_HMAC_DONE_BIT]] 0 = true ->\n      s = IDLE (sha256 input)\n               {| intr_enable := /[0];\n                  hmac_done := true;\n                  hmac_en := false;\n                  sha_en := true;\n                  swap_endian := true;\n                  swap_digest := false |}.\n  Proof.\n    intros.\n    remember /[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_INTR_STATE_REG_OFFSET] as addr.\n    inversion H; subst. 2: reflexivity.\n    exfalso. unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.\n    rewrite word.unsigned_sru_nowrap in H0. 2: {\n      rewrite word.unsigned_of_Z_0. reflexivity.\n    }\n    rewrite word.unsigned_of_Z_0 in H0.\n    rewrite Z.shiftr_0_r in H0.\n    congruence.\n  Qed.\n\n  Lemma invert_read_digest: forall b d i v s,\n      0 <= \\[i] < 8 ->\n      read_step 4 (IDLE b d)\n                (/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_DIGEST_7_REG_OFFSET] ^- i ^* /[4]) v s ->\n      s = IDLE b d /\\ v = /[le_combine (List.firstn 4 (List.skipn (Z.to_nat \\[i] * 4) b))].\n  Proof.\n    intros.\n    remember (/[TOP_EARLGREY_HMAC_BASE_ADDR + HMAC_DIGEST_7_REG_OFFSET] ^- i ^* /[4]) as a.\n    inversion H0. subst. split; [reflexivity|].\n    f_equal. f_equal. f_equal. f_equal. ZnWords.\n  Qed.\n\n  (* not needed in this file directly, but needed at proof linking time to discharge\n     assumption in AbsMMIOWritePropertiesUnique *)\n  Lemma execution_unique (t : trace) s1 s2 :\n    execution t s1 ->\n    execution t s2 ->\n    s1 = s2.\n  Proof.\n    eapply StateMachineProperties.execution_unique; intros;\n      cbn [state_machine.is_initial_state state_machine.read_step state_machine.write_step\n           hmac_state_machine] in *; simp.\n    all: try match goal with\n             | H: read_step _ _ _ _ _ |- _ => inversion H; subst; clear H\n             | H: write_step _ _ _ _ _ |- _ => inversion H; subst; clear H\n             end.\n  Admitted.\n\n  (* TODO move to bedrock2? *)\n  Notation bytearray := (array (mem := mem) ptsto (word.of_Z 1)).\n  Notation wordarray := (array (mem := mem) scalar32 (word.of_Z 4)).\n\n  Axiom TODO: False.\n\n  Lemma ptsto_aliasing_contradiction a b1 b2 (R: mem -> Prop) m\n        (Hsep: (ptsto a b1 * ptsto a b2 * R)%sep m)\n    : False.\n  Proof.\n    unfold sep in Hsep.\n    unfold map.split, ptsto in *.\n    simp.\n    unfold map.disjoint in *.\n    specialize (Hsepp1p0p1 a).\n    rewrite !map.get_put_same in Hsepp1p0p1.\n    eauto.\n  Qed.\n\n  (* Note: Often, we have a hypothesis `word.unsigned len = Z.of_nat (length l)`,\n     from which word.unsigned_range gives us a bound that's even 1 tighter *)\n  Lemma bytearray_max_length(a: word)(l: list byte)(R: mem -> Prop)(m: mem)\n        (Hsep: (bytearray a l * R)%sep m)\n    : Z.of_nat (List.length l) <= 2 ^ 32.\n  Proof.\n    remember (2 ^ 32) as B.\n    assert (Z.of_nat (List.length l) <= B \\/\n            B < Z.of_nat (List.length l)) as C by lia.\n    destruct C as [C | C]. 1: lia.\n    exfalso.\n    rewrite <- (List.firstn_nth_skipn _ (Z.to_nat B) l Byte.x00) in Hsep by lia.\n    rewrite <- (List.firstn_nth_skipn _ 0 (List.firstn (Z.to_nat B) l) Byte.x00) in Hsep by length_hammer.\n    autorewrite with listsimpl push_firstn in *.\n    seprewrite_in (array_append ptsto) Hsep.\n    seprewrite_in (array_append ptsto) Hsep.\n    seprewrite_in (array_append ptsto) Hsep.\n    seprewrite_in (array_cons ptsto) Hsep.\n    seprewrite_in (array_cons ptsto) Hsep.\n    eapply ptsto_aliasing_contradiction.\n    use_sep_assumption.\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. 1: reflexivity.\n    cancel_seps_at_indices 1%nat 0%nat. 1:f_equal; push_length; ZnWords.\n    ecancel_done.\n  Qed.\n\n  Lemma load_one_of_bytearray (addr addr': word) (values : list byte) R m\n    (Hsep : sep (bytearray addr values) R m)\n    : let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in\n      (n < List.length values)%nat ->\n      Memory.load access_size.one m addr' =\n      Some (word.of_Z (byte.unsigned (nth n values Byte.x00))).\n  Proof.\n    intros.\n    rewrite <-(List.firstn_nth_skipn _ _ values Byte.x00 H) in Hsep.\n    do 2 seprewrite_in (array_append ptsto) Hsep.\n    seprewrite_in (array_cons ptsto) Hsep.\n    seprewrite_in (array_nil ptsto) Hsep.\n    autorewrite with push_length natsimpl in *.\n    eapply load_one_of_sep.\n    use_sep_assumption.\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal. ZnWords.\n    }\n    ecancel_done.\n  Qed.\n\n  Lemma isolate_scalar32_of_bytarray: forall (addr addr': word) values,\n    let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in\n    (n + 4 <= Datatypes.length values)%nat ->\n    iff1 (bytearray addr values)\n         (bytearray addr (List.firstn n values) *\n          scalar32 addr' (word.of_Z (le_combine (List.firstn 4 (List.skipn n values)))) *\n          bytearray (word.add addr' (word.of_Z 4)) (List.skipn (n + 4) values))%sep.\n  Proof.\n    intros.\n    rewrite <- (List.firstn_skipn n values) at 1.\n    rewrite <- (List.firstn_skipn 4 (List.skipn n values)) at 1.\n    do 2 rewrite (array_append ptsto).\n    cancel.\n    cancel_seps_at_indices 0%nat 0%nat. {\n      unfold scalar32, truncated_word, truncated_scalar, littleendian, ptsto_bytes.ptsto_bytes.\n      f_equal. 1: ZnWords.\n      replace (bytes_per (width:=32) access_size.four)\n        with (Datatypes.length (List.firstn 4 (List.skipn n values)))\n        by (cbv [bytes_per]; length_hammer).\n      rewrite word.unsigned_of_Z_nowrap. 2: {\n        match goal with\n        | |- context[le_combine ?x] =>\n          pose proof (le_combine_bound x) as P\n        end.\n        autorewrite with push_length in P.\n        rewrite min_l in P by ZnWords.\n        exact P.\n      }\n      remember (List.firstn 4 (List.skipn n values)) as l.\n      assert (List.length l = 4%nat) as HL by (subst; length_hammer).\n      rewrite <- (le_split_combine _ 4) at 1. 2: {\n        symmetry. exact HL.\n      }\n      destruct l as [|b0 l]. 1: discriminate HL.\n      destruct l as [|b1 l]. 1: discriminate HL.\n      destruct l as [|b2 l]. 1: discriminate HL.\n      destruct l as [|b3 l]. 1: discriminate HL.\n      destruct l as [|b4 l]. 2: discriminate HL.\n      clear HL.\n      reflexivity.\n    }\n    cancel_seps_at_indices 0%nat 0%nat. {\n      f_equal.\n      - push_length. ZnWords.\n      - push_skipn. f_equal; lia.\n    }\n    ecancel_done.\n  Qed.\n\n  Lemma load_four_of_bytearray (addr addr': word) (values : list byte) R m\n    (Hsep : sep (bytearray addr values) R m)\n    : let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in\n      (n + 4 <= List.length values)%nat ->\n      Memory.load access_size.four m addr' =\n      Some (word.of_Z (le_combine (List.firstn 4 (List.skipn n values)))).\n  Proof.\n    intros.\n    eapply load_four_of_sep_32bit. 1: reflexivity.\n    seprewrite_in isolate_scalar32_of_bytarray Hsep. 1: subst n; eassumption.\n    ecancel_assumption.\n  Qed.\n\n  Lemma store_four_to_bytearray (addr addr' v: word) (values : list byte) R m (post: mem -> Prop):\n    sep (bytearray addr values) R m ->\n    let n := Z.to_nat (word.unsigned (word.sub addr' addr)) in\n    (n + 4 <= List.length values)%nat ->\n    (forall m', sep (bytearray addr (List.upds values n (le_split 4 (word.unsigned v)))) R m' ->\n               post m') ->\n    exists m', Memory.store access_size.four m addr' v = Some m' /\\ post m'.\n  Proof.\n    intros Hsep n HL HPost.\n    eapply store_four_of_sep.\n    - seprewrite_in isolate_scalar32_of_bytarray Hsep. 1: subst n; eassumption.\n      ecancel_assumption.\n    - clear dependent m. intros m Hsep. eapply HPost.\n      SeparationLogic.seprewrite isolate_scalar32_of_bytarray. {\n        rewrite List.upds_length. subst n. exact HL.\n      }\n      use_sep_assumption.\n      cancel.\n      unfold List.upds. change (Z.to_nat \\[addr' ^- addr]) with n.\n      pose proof (length_le_split 4 \\[v]).\n      cancel_seps_at_indices 0%nat 1%nat. {\n        f_equal.\n        repeat (listsimpl || push_skipn || push_firstn || push_length).\n        rewrite le_combine_split.\n        change (Z.of_nat 4 * 8) with 32.\n        rewrite word.wrap_unsigned.\n        rewrite word.of_Z_unsigned.\n        reflexivity.\n      }\n      cancel_seps_at_indices 0%nat 0%nat. {\n        f_equal.\n        repeat (listsimpl || natsimpl || push_firstn || push_length).\n        reflexivity.\n      }\n      cancel_seps_at_indices 0%nat 0%nat. {\n        f_equal.\n        rewrite length_le_split in *.\n        repeat (listsimpl || natsimpl || push_skipn || push_firstn || push_length).\n        f_equal; lia.\n      }\n      ecancel_done.\n  Qed.\n\n  Lemma Zlandb: forall (b1 b2: bool),\n      Z.land (if b1 then 1 else 0) (if b2 then 1 else 0) = if (andb b1 b2) then 1 else 0.\n  Proof. destruct b1; destruct b2; reflexivity. Qed.\n\n  Lemma then1_else0_nonzero: forall b: bool,\n      (if b then 1 else 0) <> 0 -> b = true.\n  Proof. destruct b; congruence. Qed.\n\n  Lemma then1_else0_zero: forall b: bool,\n      (if b then 1 else 0) = 0 -> b = false.\n  Proof. destruct b; congruence. Qed.\n\n  Lemma Zland_ones_to_mod: forall a ones,\n      ones = Z.ones (Z.log2_up ones) ->\n      Z.land a ones = a mod 2 ^ (Z.log2_up ones).\n  Proof.\n    intros. rewrite <- Z.land_ones. 2: apply Z.log2_up_nonneg.\n    f_equal. exact H.\n  Qed.\n\n  Lemma Zland_pow2_to_testbit: forall a pow2,\n      pow2 = 2 ^ (Z.log2_up pow2) ->\n      Z.land a pow2 = if Z.testbit a (Z.log2_up pow2) then pow2 else 0.\n  Proof.\n    intros.\n    eapply Z.bits_inj'. intros.\n    rewrite Z.land_spec.\n    rewrite prove_Zeq_bitwise.testbit_if.\n    rewrite H at 1.  rewrite H at 3.\n    rewrite Z.pow2_bits_eqb by apply Z.log2_up_nonneg.\n    rewrite Z.testbit_0_l.\n    destr (Z.eqb (Z.log2_up pow2) n).\n    + subst n. destruct (Z.testbit a (Z.log2_up pow2)); reflexivity.\n    + rewrite Bool.andb_false_r. destr (Z.testbit a (Z.log2_up pow2)); reflexivity.\n  Qed.\n\n  Ltac simpl_conditional :=\n    match goal with\n    | H: _ /\\ _ |- _ => destruct H\n    | H: _ |- _ => rewrite Zlandb in H\n    | H: word.eqb ?x ?y = true  |- _ => apply (word.eqb_true  x y) in H\n    | H: word.eqb ?x ?y = false |- _ => apply (word.eqb_false x y) in H\n    | H: andb ?b1 ?b2 = true |- _ => apply (Bool.andb_true_iff b1 b2) in H\n    | H: andb ?b1 ?b2 = false |- _ => apply (Bool.andb_false_iff b1 b2) in H\n    | H: orb ?b1 ?b2 = true |- _ => apply (Bool.orb_true_iff b1 b2) in H\n    | H: orb ?b1 ?b2 = false |- _ => apply (Bool.orb_false_iff b1 b2) in H\n    | H: _ |- _ => rewrite word.unsigned_and_nowrap in H\n    | H: _ |- _ => rewrite word.unsigned_if in H\n    | H: _ |- _ => rewrite word.unsigned_eqb in H\n    | H: _ |- _ => rewrite word.unsigned_ltu in H\n    | H: _ |- _ => rewrite word.unsigned_of_Z_small in H by\n          (lazymatch goal with\n           | |- _ <= ?x < 2 ^ _ =>\n             lazymatch isZcst x with true => cbv; intuition discriminate end\n           end)\n    | H: _ |- _ => apply then1_else0_nonzero in H\n    | H: _ |- _ => apply then1_else0_zero in H\n    | H: Z.eqb _ _ = true |- _ => apply Z.eqb_eq in H\n    | H: Z.eqb _ _ = false |- _ => apply Z.eqb_neq in H\n    | H: Z.ltb _ _ = true |- _ => eapply Z.ltb_lt in H\n    | H: Z.ltb _ _ = false |- _ => eapply Z.ltb_ge in H\n    | H: context[Z.land ?a ?ones] |- _ =>\n      lazymatch isZcst ones with true => idtac end;\n      let m := eval cbv in (2 ^ Z.log2_up ones) in\n      rewrite (Zland_ones_to_mod a ones eq_refl: _ = a mod m) in H\n    | H: context[Z.land ?a ?pow2] |- _ =>\n      let i := lazymatch isZcst pow2 with\n               | true => eval cbv in (Z.log2_up pow2)\n               | false => lazymatch pow2 with\n                          | 2 ^ ?m => m\n                          end\n               end in\n      rewrite (Zland_pow2_to_testbit a pow2 eq_refl:\n                 Z.land a pow2 = if Z.testbit a i then pow2 else 0) in H\n    | H: word.unsigned (if ?b then _ else _) = 0 |- _ => apply word.if_zero in H\n    | H: word.unsigned (if ?b then _ else _) <> 0 |- _ => apply word.if_nonzero in H\n    end.\n\n  Ltac simpl_conditionals := repeat simpl_conditional.\n\n  Global Instance spec_of_hmac_sha256_init : spec_of b2_hmac_sha256_init :=\n    fun function_env =>\n      forall tr m (R : mem -> Prop) (digest_buffer: list byte) (d: idle_data),\n      R m ->\n      execution tr (IDLE digest_buffer d) ->\n      call function_env b2_hmac_sha256_init tr m []\n        (fun tr' m' rets =>\n            rets = [] /\\ execution tr' (CONSUMING []) /\\ R m').\n  Lemma hmac_sha256_init_correct :\n    program_logic_goal_for_function! b2_hmac_sha256_init.\n  Proof.\n    repeat straightline.\n    straightline_call. 1: reflexivity. 1: eapply write_cfg. 1: eassumption.\n    repeat straightline.\n    straightline_call. 1: reflexivity. 1: eapply write_intr_enable. 1: eassumption.\n    cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.\n    repeat straightline.\n    straightline_call. 1: reflexivity. 1: eapply write_intr_state. 1: eassumption.\n    cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    straightline_call. 1: reflexivity. 1: eapply write_cfg. 1: eassumption.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.\n    straightline_call. 1: reflexivity. 1: eapply write_hash_start. {\n      (* bitfiddling *)\n      case TODO.\n    }\n    { match goal with\n      | H: execution ?t ?s1 |- execution ?t ?s2 => replace s2 with s1; [exact H|]\n      end.\n      f_equal. f_equal.\n      (* bitfiddling *)\n      all: case TODO.\n    }\n    repeat straightline.\n    ssplit; eauto.\n  Qed.\n\n  Global Instance spec_of_hmac_sha256_update : spec_of b2_hmac_sha256_update :=\n    fun function_env =>\n      forall tr m (R : mem -> Prop) (previous_input new_input: list byte) data_addr len,\n      word.unsigned len = Z.of_nat (length new_input) ->\n      data_addr <> word.of_Z 0 ->\n      (bytearray data_addr new_input * R)%sep m ->\n      execution tr (CONSUMING previous_input) ->\n      call function_env b2_hmac_sha256_update tr m [data_addr; len]\n        (fun tr' m' rets =>\n           rets = [word.of_Z Constants.kErrorOk] /\\\n           execution tr' (CONSUMING (previous_input ++ new_input)) /\\\n           (bytearray data_addr new_input * R)%sep m').\n\n  Lemma hmac_sha256_update_correct :\n    program_logic_goal_for_function! b2_hmac_sha256_update.\n  Proof.\n    repeat straightline.\n    unfold1_cmd_goal; cbv beta match delta [cmd_body].\n    repeat straightline.\n    subst v.\n    rewrite word.unsigned_if.\n    rewrite word.eqb_ne by assumption.\n    rewrite word.unsigned_of_Z_0.\n    split; intros E. 1: exfalso; apply E; reflexivity.\n    clear E.\n    repeat straightline.\n    set (data_aligned := word.of_Z (word.unsigned (word.add data_addr (word.of_Z 3)) / 4 * 4)).\n    rename fifo_reg into fifo_reg0, len into len0.\n\n    (* first while loop: *)\n    eapply (while [\"fifo_reg\"; \"data_sent\"; \"data\"; \"len\"]\n                  (fun measure t m fifo_reg data_sent data len =>\n                     data_addr = data /\\\n                     fifo_reg = fifo_reg0 /\\\n                     data_sent ^+ /[measure] = data_aligned /\\\n                     0 <= measure < 4 /\\\n                     \\[data_sent ^- data_addr] + \\[len] = Z.of_nat (List.length new_input) /\\\n                     (bytearray data_addr new_input * R)%sep m /\\\n                     execution t (CONSUMING (previous_input ++\n                        List.firstn (Z.to_nat \\[data_sent ^- data_addr]) new_input)))\n                  (Z.lt_wf 0)\n                  \\[data_aligned ^- data_addr]).\n    1: repeat straightline.\n    { (* invariant holds initially: *)\n      loop_simpl.\n      replace (Z.to_nat \\[data_addr ^- data_addr]) with 0%nat by ZnWords.\n      push_firstn; listsimpl.\n      ssplit; try assumption; try ZnWords. }\n    loop_simpl.\n    intros measure t m0 fifo_reg data_sent data len. (* TODO derive names automatically *)\n    repeat straightline.\n    { (* if br is true, running first loop body again satisfies invariant *)\n      subst br.\n      simpl_conditionals.\n      eexists. split. {\n        repeat straightline.\n        eexists. split.\n        { eapply load_one_of_bytearray. 1: eassumption. ZnWords. }\n        repeat straightline.\n      }\n      straightline_call.\n      { cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }\n      2: eassumption.\n      { eapply write_byte. 2: reflexivity.\n        match goal with\n        | |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)\n        end.\n        ZnWords. }\n      repeat straightline.\n      cbv [Markers.unique Markers.split].\n      eexists (measure - 1). ssplit; trivial; try ZnWords.\n      subst a.\n      eapply execution_step_write with (sz := 1%nat). 1: eassumption. 1: reflexivity.\n      cbv [state_machine.write_step hmac_state_machine].\n      replace (Z.to_nat \\[data_sent ^- data]) with\n              (S (Z.to_nat \\[data_sent0 ^- data])) by ZnWords.\n      rewrite <- (List.firstn_nth _ _ _ Byte.x00) by ZnWords.\n      rewrite List.app_assoc.\n      match goal with\n      | |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)\n      end.\n      eapply write_byte. 1: ZnWords.\n      f_equal. f_equal.\n      rewrite word.unsigned_of_Z_small by ZnWords.\n      rewrite byte.of_Z_unsigned.\n      reflexivity.\n    }\n    (* if br is false, code after first loop is correct: *)\n    subst br.\n    simpl_conditionals.\n    match goal with\n    | H: _ \\/ _ |- _ => destruct H as [A | A]; simpl_conditionals\n    end.\n    { (* if the first loop was ended because len=0, the remaining two loops are skipped: *)\n      eapply while_zero_iterations. {\n        repeat straightline.\n        subst v.\n        rewrite word.unsigned_ltu.\n        apply word.unsigned_inj.\n        rewrite word.unsigned_if.\n        destruct_one_match; ZnWords.\n      }\n      repeat straightline.\n      eapply while_zero_iterations. {\n        repeat straightline. ZnWords.\n      }\n      repeat straightline.\n      ssplit. 1: reflexivity. 2: eassumption.\n      match goal with\n      | H: execution ?t ?s1 |- execution ?t ?s2 =>\n        replace s2 with s1; [exact H|]\n      end.\n      f_equal. f_equal. push_firstn. reflexivity.\n    }\n    (* if the first loop was ended because `data_sent & 3 == 0`,\n       we have to step through the remaining two loops as well: *)\n    assert (data_sent = data_aligned) by ZnWords. subst data_sent.\n    clear dependent tr.\n    clear dependent measure.\n    clear dependent m.\n    match goal with\n    | H: word.unsigned ?L = Z.of_nat (List.length new_input) |- _ =>\n      pose proof (word.unsigned_range L) as LB;\n      rewrite H in LB;\n      clear dependent L\n    end.\n    rename data into data_addr, t into tr, len into len0.\n\n    (* second while loop: *)\n    eapply (while [\"fifo_reg\"; \"data_sent\"; \"data\"; \"len\"]\n                  (fun measure t m fifo_reg data_sent data len =>\n                     data_addr = data /\\\n                     fifo_reg = fifo_reg0 /\\\n                     measure = \\[len] /\\\n                     \\[data_sent] mod 4 = 0 /\\\n                     \\[data_sent ^- data_addr] + \\[len] = Z.of_nat (List.length new_input) /\\\n                     (bytearray data_addr new_input * R)%sep m /\\\n                     execution t (CONSUMING (previous_input ++\n                        List.firstn (Z.to_nat \\[data_sent ^- data_addr]) new_input)))\n                  (Z.lt_wf 0)\n                  \\[len0]).\n    1: repeat straightline.\n    { (* invariant holds initially: *)\n      loop_simpl.\n      ssplit; try assumption; try ZnWords. }\n    loop_simpl.\n    intros measure t m fifo_reg data_sent data len. (* TODO derive names automatically *)\n    repeat straightline.\n    { (* if br is true, running first loop body again satisfies invariant *)\n      subst br.\n      simpl_conditionals.\n      eexists. split. {\n        repeat straightline.\n        eexists. split.\n        { eapply load_four_of_bytearray. 1: eassumption. ZnWords. }\n        repeat straightline.\n      }\n      straightline_call.\n      { cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }\n      2: eassumption.\n      1: eapply write_word. 1: reflexivity.\n      repeat straightline.\n      cbv [Markers.unique Markers.split].\n      eexists (measure - 4). ssplit; trivial; try ZnWords.\n      subst a.\n      eapply execution_step_write with (sz := 4%nat). 1: eassumption. 1: reflexivity.\n      cbv [state_machine.write_step hmac_state_machine].\n      eapply write_word. rewrite <- List.app_assoc. f_equal.\n      subst data_sent.\n      match goal with\n      | |- context[le_combine ?x] =>\n        pose proof (le_combine_bound x) as P\n      end.\n      autorewrite with push_length in P.\n      rewrite min_l in P by ZnWords.\n      rewrite word.unsigned_of_Z_small by ZnWords.\n      rewrite le_split_combine. 2: {\n        rewrite List.firstn_length. ZnWords.\n      }\n      replace (Z.to_nat \\[data_sent0 ^+ /[4] ^- data])\n        with (Z.to_nat \\[data_sent0 ^- data] + 4)%nat by ZnWords.\n      apply List.firstn_add.\n    }\n    (* if br is false, code after second loop is correct: *)\n    subst br.\n    simpl_conditionals.\n    clear dependent tr.\n    clear dependent m0.\n    clear dependent len0.\n    rename data_sent into data_aligned_last.\n    rename data into data_addr, t into tr, len into len0.\n    set (data_past_end := data_addr ^+ /[Z.of_nat (List.length new_input)]).\n\n    (* third while loop: *)\n    eapply (while [\"fifo_reg\"; \"data_sent\"; \"data\"; \"len\"]\n                  (fun measure t m fifo_reg data_sent data len =>\n                     data_addr = data /\\\n                     fifo_reg = fifo_reg0 /\\\n                     measure = \\[len] /\\\n                     0 <= measure < 4 /\\\n                     \\[data_sent ^- data_addr] + \\[len] = Z.of_nat (List.length new_input) /\\\n                     (bytearray data_addr new_input * R)%sep m /\\\n                     execution t (CONSUMING (previous_input ++\n                        List.firstn (Z.to_nat \\[data_sent ^- data_addr]) new_input)))\n                  (Z.lt_wf 0)\n                  \\[len0]).\n    1: repeat straightline.\n    { (* invariant holds initially: *)\n      loop_simpl.\n      ssplit; try assumption; try ZnWords. }\n    loop_simpl.\n    intros measure t m0 fifo_reg data_sent data len. (* TODO derive names automatically *)\n    repeat straightline.\n    { (* if break condition is true, running third loop body again satisfies invariant *)\n      simpl_conditionals.\n      eexists. split. {\n        repeat straightline.\n        eexists. split.\n        { eapply load_one_of_bytearray. 1: eassumption. ZnWords. }\n        repeat straightline.\n      }\n      straightline_call.\n      { cbv [state_machine.reg_addr hmac_state_machine id]. reflexivity. }\n      2: eassumption.\n      { eapply write_byte. 2: reflexivity.\n        match goal with\n        | |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)\n        end.\n        ZnWords. }\n      repeat straightline.\n      cbv [Markers.unique Markers.split].\n      eexists (measure - 1). ssplit; trivial; try ZnWords.\n      subst a.\n      eapply execution_step_write with (sz := 1%nat). 1: eassumption. 1: reflexivity.\n      cbv [state_machine.write_step hmac_state_machine].\n      replace (Z.to_nat \\[data_sent ^- data]) with\n              (S (Z.to_nat \\[data_sent0 ^- data])) by ZnWords.\n      rewrite <- (List.firstn_nth _ _ _ Byte.x00) by ZnWords.\n      rewrite List.app_assoc.\n      match goal with\n      | |- context[byte.unsigned ?x] => pose proof (byte.unsigned_range x)\n      end.\n      eapply write_byte. 1: ZnWords.\n      f_equal. f_equal.\n      rewrite word.unsigned_of_Z_small by ZnWords.\n      rewrite byte.of_Z_unsigned.\n      reflexivity.\n    }\n    (* if break condition is false, `result = kErrorOk` is run and now we have to prove\n       the postcondition of the function: *)\n    split; [reflexivity|].\n    split; [|eassumption].\n    match goal with\n    | H: execution ?t ?s |- execution ?t ?s' => replace s' with s; [exact H|]\n    end.\n    push_firstn. reflexivity.\n  Qed.\n\n  Global Instance spec_of_hmac_sha256_final : spec_of b2_hmac_sha256_final :=\n    fun function_env =>\n      forall tr (m: mem) (R : mem -> Prop)\n             (input digest_trash: list Byte.byte) (digest_addr: word),\n      Z.of_nat (length digest_trash) = 32 ->\n      digest_addr <> word.of_Z 0 ->\n      (bytearray digest_addr digest_trash * R)%sep m ->\n      execution tr (CONSUMING input) ->\n      call function_env b2_hmac_sha256_final tr m [digest_addr]\n        (fun tr' (m': mem) rets =>\n           rets = [word.of_Z Constants.kErrorOk] /\\\n           execution tr' (IDLE (sha256 input) (* digest has been read, but still in device *)\n                            {| hmac_done := false; (* done flag was already cleared by this function *)\n                               intr_enable := word.of_Z 0;\n                               hmac_en := false;\n                               sha_en := true;\n                               swap_endian := true;\n                               swap_digest := false; |}) /\\\n           (* digest has been stored at correct memory location: *)\n           (bytearray digest_addr (sha256 input) * R)%sep m').\n\n  Lemma hmac_sha256_final_correct :\n    program_logic_goal_for_function! b2_hmac_sha256_final.\n  Proof.\n    repeat straightline.\n    assert (List.length (sha256 input) = 32)%nat by case TODO.\n    unfold1_cmd_goal; cbv beta match delta [cmd_body].\n    repeat straightline.\n    subst v.\n    rewrite word.unsigned_if.\n    rewrite word.eqb_ne by assumption.\n    rewrite word.unsigned_of_Z_0.\n    split; intros E. 1: exfalso; apply E; reflexivity.\n    clear E.\n    repeat straightline.\n    straightline_call.\n    repeat straightline.\n    straightline_call. 1: reflexivity. 1: eapply write_hash_process. 2: eassumption.\n    { case TODO. (* bitfiddling *) }\n    repeat straightline.\n    subst done.\n\n    (* first while loop *)\n    eapply atleastonce with (variables := [\"digest\"; \"reg\"; \"done\"])\n             (invariant := fun measure t m digest reg done =>\n               digest = digest_addr /\\\n               execution t (PROCESSING input measure) /\\\n               (bytearray digest_addr digest_trash \u22c6 R)%sep m).\n    { repeat straightline. }\n    { eapply (Z.lt_wf 0). }\n    { (* if condition initially is false, that's a contradiction, so we don't need to prove post: *)\n      repeat straightline. subst br. simpl_conditionals. exfalso. eauto. }\n    { (* invariant holds initially *)\n      loop_simpl. eauto. }\n    loop_simpl.\n    (* step through first loop body: *)\n    repeat straightline.\n    straightline_call. 1: reflexivity. {\n      (* to show that there exists at least one valid read step, we pick read_done_bit_done,\n         but the device could also choose read_done_bit_not_done, so later we'll have to treat\n         both cases *)\n      eapply read_done_bit_done with (v0 := /[1]).\n      rewrite word.unsigned_of_Z_1. reflexivity.\n    }\n    1: eassumption.\n    repeat straightline.\n    straightline_call.\n    (* TODO here we see that `x3 x4 x5 : word` should be named `\"digest\" \"reg\" \"done\"`,\n       respectively, automate this naming *)\n    repeat straightline.\n    { (* loop condition is true: need to show that invariant still holds with smaller measure *)\n      subst br.\n      rename x5 into done. subst done.\n      simpl_conditionals.\n      eexists (v - 1).\n      edestruct invert_read_status_done_false; [eassumption..|].\n      subst x.\n      split; [auto|lia]. }\n    (* loop condition is false: need to show that code after first loop is correct *)\n    subst br. simpl_conditionals.\n    eassert (x = _). {\n      eapply invert_read_status_done_true; eassumption.\n    }\n    subst x.\n    straightline_call. 1: reflexivity. 1: eapply write_intr_state. 1: eassumption.\n    cbn [intr_enable hmac_done hmac_en sha_en swap_endian swap_digest] in *.\n    repeat straightline.\n\n    clear dependent reg.\n    repeat match goal with\n           | H: execution ?t1 _ |- cmd _ _ ?t2 _ _ _ =>\n             tryif unify t1 t2 then fail else clear H\n           end.\n    repeat match goal with\n           | m1: @map.rep _ _ mem |- cmd _ _ _ ?m2 _ _ =>\n             tryif unify m1 m2 then fail else clear dependent m1\n           end.\n    rename a3 into tr.\n    clear dependent v.\n    match goal with\n    | H: Z.testbit \\[_ ^>> _] 0 = true |- _ => rename H into T\n    end.\n    unfold HMAC_INTR_STATE_HMAC_DONE_BIT in *.\n    rewrite word.unsigned_sru_nowrap in T. 2: {\n      rewrite word.unsigned_of_Z_0. reflexivity.\n    }\n    rewrite word.unsigned_of_Z_0 in T.\n    rewrite Z.shiftr_0_r in T.\n    rewrite T in *.\n\n    (* second while loop: *)\n    eapply (while [\"digest\"; \"reg\"; \"done\"; \"i\"]\n                  (fun remaining t m digest reg done i =>\n                     execution t (IDLE (sha256 input)\n                                       {| intr_enable := /[0];\n                                          hmac_done := false;\n                                          hmac_en := false;\n                                          sha_en := true;\n                                          swap_endian := true;\n                                          swap_digest := false\n                                       |}) /\\\n                     0 <= \\[i] <= 8 /\\\n                     0 <= remaining <= 32 /\\\n                     4 * \\[i] + remaining = 32 /\\\n                     digest = digest_addr /\\\n                     (bytearray digest (List.firstn (Z.to_nat (4 * \\[i])) (sha256 input) ++\n                                        List.skipn (Z.to_nat (4 * \\[i])) digest_trash) * R)%sep m)\n                  (Z.lt_wf 0) 32).\n    { repeat straightline. }\n    { (* invariant holds initially: *)\n      loop_simpl. subst i. rewrite word.unsigned_of_Z_0.\n      ssplit; try reflexivity; try assumption; try lia. }\n    loop_simpl.\n    repeat straightline.\n    { (* running loop body satisfies invariant *)\n      subst br. simpl_conditionals. subst i. rename x5 into i.\n      straightline_call. 1: reflexivity. 2: eassumption. 1: eapply read_digest with (i0 := \\[i]).\n      all: try reflexivity.\n      1-2: ZnWords.\n      repeat straightline.\n      eapply store_four_to_bytearray. 1: ecancel_assumption.\n      { subst a2. rewrite List.app_length. rewrite List.firstn_length. rewrite List.skipn_length.\n        ZnWords_pre.\n        Z.div_mod_to_equations.\n        (* Note: On Coq master of Aug 12, 2021, this goal is just solved by `lia`, but\n           with Coq 8.13.2, `lia` hangs, so we need more manual steps: *)\n        assert (2 ^ 32 <> 0) as NZ by (clear; lia).\n        repeat match goal with\n               | H: 2 ^ 32 = 0 -> _ |- _ => clear H\n               | H: 2 ^ 32 < 0 -> _ |- _ => clear H\n               | H: 0 < 2 ^ 32 -> _ |- _ => specialize (H eq_refl)\n               | H: 2 ^ 32 <> 0 -> _ |- _ => specialize (H NZ)\n               end.\n        subst.\n        clear H NZ.\n        clear dependent word.\n        Zify.zify.\n        repeat match goal with\n               | H: _ /\\ _ |- _ => destruct H\n               | H: _ \\/ _ |- _ => destruct H\n               end;\n        lia.\n      }\n      intros m Hm.\n      repeat straightline.\n      exists (v - 4).\n      split; [|lia].\n      split. {\n        subst a.\n        eapply execution_step_read with (sz := 4%nat). 1: eassumption. 1: reflexivity.\n        cbn [state_machine.read_step hmac_state_machine] in *.\n        match goal with\n        | H: read_step 4 ?s ?a ?v ?s1 |- read_step 4 ?s ?a ?v ?s2 =>\n          replace s2 with s1 at 2; [exact H|]\n        end.\n        eapply invert_read_digest with (i := i0). 1: lia. 1: eassumption.\n      }\n      split; [ZnWords|].\n      split; [ZnWords|].\n      split; [ZnWords|].\n      split; [reflexivity|].\n      use_sep_assumption.\n      cancel.\n      cancel_seps_at_indices 0%nat 0%nat. {\n        f_equal.\n        rewrite List.upds_app2. 2: {\n          push_length.\n          (* Note: `ZnWords` should just work here, but when it calls `lia`, `lia` hangs. *)\n          subst a2. rewrite H9. revert dependent v. clear -word_ok. intros.\n          pose proof word.unsigned_range i0.\n          replace (Init.Nat.min (Z.to_nat (4 * \\[i0])) 32) with (Z.to_nat (4 * \\[i0])) by lia.\n          replace \\[digest_addr ^+ i0 ^* /[4] ^- digest_addr] with \\[i0 ^* /[4]] by ZnWords.\n          ZnWords.\n        }\n        subst i.\n        replace (Z.to_nat (4 * \\[i0 ^+ /[1]])) with (Z.to_nat (4 * \\[i0]) + 4)%nat by ZnWords.\n        rewrite List.firstn_add. rewrite <- List.app_assoc.\n        f_equal.\n        unfold List.upds. push_length.\n        replace (Z.to_nat \\[a2 ^- digest_addr] -\n                 Init.Nat.min (Z.to_nat (4 * \\[i0])) (Datatypes.length (sha256 input)))%nat\n          with 0%nat.\n        2: {\n          (* Note: `ZnWords` should just work here, but when it calls `lia`, `lia` hangs. *)\n          subst a2. rewrite H9. revert dependent v. clear -word_ok. intros.\n          pose proof word.unsigned_range i0.\n          replace (Init.Nat.min (Z.to_nat (4 * \\[i0])) 32) with (Z.to_nat (4 * \\[i0])) by lia.\n          replace \\[digest_addr ^+ i0 ^* /[4] ^- digest_addr] with \\[i0 ^* /[4]] by ZnWords.\n          ZnWords.\n        }\n        repeat (push_firstn || push_length || listsimpl || natsimpl).\n        edestruct invert_read_digest as (_ & E). 2: eassumption. 1: ZnWords. subst.\n        rewrite word.unsigned_of_Z_nowrap. 2: {\n          match goal with\n          | |- context[le_combine ?x] =>\n            pose proof (le_combine_bound x) as P\n          end.\n          rewrite List.firstn_length in P. rewrite min_l in P by ZnWords.\n          exact P.\n        }\n        rewrite le_split_combine by length_hammer.\n        push_skipn.\n        repeat (f_equal; try lia).\n      }\n      ecancel_done.\n    }\n    (* postcondition holds at end  *)\n    subst br. simpl_conditionals. subst i. rename x5 into i.\n    replace (4 * \\[i]) with 32 in * by ZnWords.\n    rewrite List.firstn_all2 in * by ZnWords.\n    rewrite List.skipn_all2 in * by ZnWords.\n    autorewrite with listsimpl in *.\n    subst result.\n    auto.\n  Qed.\n\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/silveroak-opentitan/hmac/sw/HmacProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.18282086890504126}}
{"text": "(* En este archivo se demuestra la correcci\u00f3n de la acci\u00f3n call *)\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 RuntimePermissions.\nRequire Import ValidStateLemmas.\n\nSection Call.\n\nLemma callCorrect : forall (s:System) (ic:iCmp) (sac:SACall) (sValid: validstate s),\n    (pre (call ic sac) s) -> post_call ic sac s (call_post ic sac s).\nProof.\n    intros.\n    unfold post_call.\n    unfold call_post; simpl.\n    auto.\nQed.\n\nLemma notPreCallThenError : forall (s:System) (ic:iCmp) (sac:SACall), ~(pre (call  ic sac) s) -> validstate s -> exists ec : ErrorCode, response (step s (call  ic sac)) = error ec /\\ ErrorMsg s (call  ic sac) ec /\\ s = system (step s (call  ic sac)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_call in H.\n    unfold call_safe.\n    unfold call_pre.\n    case_eq (map_apply iCmp_eq (running (state s)) ic);intros.\n    case_eq (existsb (fun p : Perm => negb (appHasPermissionBool (getAppFromCmp c s) p s)) (getMandatoryPerms sac));intros.\n    exists not_enough_permissions.\n    split;auto.\n    split;auto.\n    exists c.\n    split;auto.\n    rewrite existsb_exists in H2.\n    apply ex_not_not_all.\n    destruct H2.\n    destruct H2.\n    exists (getAppFromCmp c s).\n    apply ex_not_not_all.\n    exists x.\n    apply ex_not_not_all.\n    assert (isSysPerm:=H2).\n    apply mandatoryPermsAllSystem in isSysPerm.\n    exists isSysPerm.\n    rewrite negb_true_iff in H3.\n    invertBool H3.\n    intro;apply H3.\n    apply appHasPermissionCorrect;auto.\n    apply H4.\n    apply ifRunningThenInApp in H1;auto.\n    destruct H1.\n    assert (getAppFromCmp c s=x0).\n    apply inAppThenGetAppFromCmp in H1;auto.\n    rewrite H5;auto.\n    unfold not;intros.\n    apply mandatoryPermsCorrect;auto.\n    destruct H.\n    exists c.\n    split;auto.\n    intros.\n    invertBool H2.\n    rewrite existsb_exists in H2.\n    apply NNPP.\n    intro;apply H2.\n    exists p.\n    split.\n    apply (mandatoryPermsCorrect sac p H);auto.\n    rewrite negb_true_iff.\n    rewrite <-not_true_iff_false.\n    intro;apply H5.\n    apply inAppThenGetAppFromCmp in H3;auto.\n    rewrite H3 in H6.\n    apply appHasPermissionCorrect;auto.\n    exists instance_not_running;auto.\nQed.\n\nLemma callIsSound :  forall (s:System) (ic:iCmp) (sac:SACall) (sValid: validstate s),\n        exec s (call ic sac) (system (step s (call ic sac))) (response (step s (call ic sac))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (call ic sac) s));intro.\n    left.\n    simpl.\n    assert(call_pre ic sac s = None).\n    unfold call_pre.\n    destruct H.\n    destruct H.\n    rewrite H.\n    assert (existsb (fun p : Perm => negb (appHasPermissionBool (getAppFromCmp x s) p s)) (getMandatoryPerms sac)=false).\n    rewrite <-not_true_iff_false.\n    unfold not;intros.\n    rewrite existsb_exists in H1.\n    destruct H1.\n    destruct H1.\n    assert (exists a:idApp, inApp x a s).\n    apply (ifRunningThenInApp s sValid x ic);auto.\n    destruct H3.\n    assert (isSystemPerm x0).\n    apply (mandatoryPermsAllSystem sac).\n    auto.\n    rewrite<- (mandatoryPermsCorrect sac x0 H4) in H1.\n    specialize (H0 x1 x0 H4 H3 H1).\n    rewrite negb_true_iff in H2.\n    rewrite<- not_true_iff_false in H2.\n    apply H2.\n    assert (getAppFromCmp x s = x1).\n    apply inAppThenGetAppFromCmp;auto.\n    rewrite H5.\n    apply appHasPermissionCorrect; auto.\n    rewrite H1.\n    auto.\n    \n    \n    \n    unfold call_safe;simpl.\n    rewrite H0;simpl.\n    split;auto.\n    split;auto.\n    apply callCorrect;auto.\n    right.\n    apply notPreCallThenError;auto.\n    \nQed.\nEnd Call.\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/CallIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1828208642177372}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\nRequire Import malloc.\nRequire Import spec_malloc.\nRequire Import linking.\n\nDefinition Gprog : funspecs := try_pre_fill_spec' ::  external_specs ++ user_specs_R ++ private_specs.\n(* It's sort of a hack that try_pre_fill_spec' is included in Gprog here.\n  If we don't, and since nobody else calls this function or includes it in their own\n  Gprog, then try_pre_fill_spec' won't be in any of the Gprogs;\n that means it won't be in the combined link_main.Gprog,\n  and then link_main.prog_correct will fail. \n*)\n\nLemma add_resvec_0: \n  forall rvec b, 0 <= b < BINS -> Zlength rvec = BINS -> (add_resvec rvec b 0) = rvec.\nProof.\n  intros. unfold add_resvec.\n  bdestruct(Zlength rvec =? BINS); [ | rep_omega].\n  bdestruct(0 <=? b); [ | rep_omega].\n  bdestruct(b <? BINS); [ | rep_omega].\n  simpl.\n  replace (Znth b rvec + 0) with (Znth b rvec) by omega.\n  rewrite upd_Znth_same_val; [auto | rep_omega].\nQed.\n\nLemma add_resvec_plus: \n  forall rvec b n m, 0 <= b < BINS -> Zlength rvec = BINS -> \n    (add_resvec (add_resvec rvec b n) b m) = (add_resvec rvec b (n+m)).\nProof.\n  intros. unfold add_resvec.\n  bdestruct(Zlength rvec =? BINS); [ | rep_omega].\n  bdestruct(0 <=? b); [ | rep_omega].\n  bdestruct(b <? BINS); [ | rep_omega]; simpl.\n  rewrite upd_Znth_Zlength.\n  bdestruct(Zlength rvec =? BINS); [ | rep_omega]; simpl.\n  rewrite upd_Znth_same; try rep_omega.\n  rewrite upd_Znth_twice; try rep_omega.\n  rewrite Z.add_assoc; reflexivity. rep_omega.\nQed.\n\nLemma body_try_pre_fill:  semax_body Vprog Gprog f_try_pre_fill try_pre_fill_spec'.\nProof. \nstart_function.\ndestruct H as [[Hnlo Hnhi] [Hreqlo Hreqhi]].\nassert_PROP (Zlength rvec = BINS) as Hrvec. {\n  unfold mem_mgr_R. entailer. rewrite Zlength_map in H0. entailer!. }\nforward_call(BINS-1). (*! t1 = bin2size(BINS-1) *)\nrep_omega.\nforward_if. (*! if n > t1 *)\n(* large case *)\n{ forward. (*! return 0 *)\n  Exists 0.\n  entailer!.\n  rewrite add_resvec_0; try rep_omega.\n}\n(* small case *)\nforward_call n; try rep_omega. (*! b = size2bin(n) *)\nforward. (*! ful = 0 *)\ndeadvars!.\nset (b:=size2binZ n).\nassert (Hb: 0 <= b < BINS) by (apply (size2bin_range n); rep_omega).\nforward_call b. (*! t3 = bin2size(b) *)\nforward. (*! chunks = (BIGBLOCK - WASTE) / t3 + WORD) *)\nentailer!.\n          pose proof (bin2size_range b Hb);\n          apply repr_inj_unsigned in H0; rep_omega.\nforward_while (*! while (req - ful > 0) *)\n    (EX ful:_,\n    PROP ( 0 <= ful <= Int.max_signed )\n     LOCAL (temp _n (Vptrofs (Ptrofs.repr n)); temp _req (Vptrofs (Ptrofs.repr req)); \n            temp _b (Vint (Int.repr b)); temp _ful (Vint (Int.repr ful)); \n            temp _chunks (Vint (Int.repr((BIGBLOCK-WA)/(bin2sizeZ b + WORD)))); \n            gvars gv)\n     SEP (mem_mgr_R gv (add_resvec rvec (size2binZ n) ful))).\n- (* init *)\nExists 0.\nrewrite add_resvec_0; try rep_omega.\nentailer!.\n   f_equal.\n   unfold Int.divu.\n   f_equal.\n   pose proof (bin2size_range b Hb); rewrite !Int.unsigned_repr by rep_omega.\n   reflexivity.\n- (* typecheck guard *)\nentailer!.\n- (* body preserves *)\nforward_if. (*! if (UINT_MAX - ful < chunks) *)\n(* case overflow *)\n{ forward. (*! return ful *)\n  Exists ful.\n  entailer!.\n}\n(* continue *) \nforward_call BIGBLOCK. (*! t3 = mmap0(BIGBLOCK) *)\nrep_omega.\nIntros p.\nforward_if. (*! if p==null *)\n-- if_tac; entailer!. \n-- (* case p==null *)\nif_tac. forward. Exists ful. entailer!. contradiction.\n-- (* case p<>null *)\nforward_call (n,p,gv,(add_resvec rvec b ful)). (*! pre_fill(n,p) *)\nif_tac. contradiction. subst b. entailer!. \ndestruct (eq_dec p nullval). contradiction.\nsplit; [rep_omega|auto].\nforward. (*! ful += chunks *)\n(* restore invar *)\nExists (ful + chunks_from_block b).\nentailer!.\n+\n  unfold chunks_from_block.\n  bdestruct (0 <=? b); [ | omega].\n  bdestruct (b <? BINS); [ | omega].\n  simpl.\n  split; auto.\n  pose proof (bin2size_range b Hb).\n  assert (0 <= (BIGBLOCK - WA) / (bin2sizeZ b + WORD))\n   by (apply Z.div_pos; rep_omega).\n  rewrite Int.signed_repr in H1.\n  split; try rep_omega.\n  split; try rep_omega.\n  apply Zdiv_le_upper_bound.\n  rep_omega. rep_omega.\n +\n  entailer!.\n  rewrite add_resvec_plus.\n  subst b.\n  entailer!.\n  apply size2bin_range; rep_omega.\n  rep_omega.\n- (* after loop *) \nforward. (*! return ful *)\nExists ful.\nentailer!.\nQed.\n\nDefinition module := [mk_body body_try_pre_fill].\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_try_pre_fill.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.1827802551092119}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\n\nRequire Import SoundUtil.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import Urelsp.\nRequire Import SemanticsSet.\nRequire Import ProperDownward.\nRequire Import ProperLevel.\nRequire Import Equivalence.\nRequire Import Subsumption.\nRequire Import SemanticsSimple.\nRequire Import SemanticsPi.\nRequire Import Defined.\n\n\nLocal Ltac prove_hygiene :=\n  repeat (first [ eapply subst_closub; eauto\n                | apply closub_dot\n                | apply hygiene_auto; cbn; 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\nLemma sound_set_formation_main :\n  forall lvo G a b c d mr ml,\n    hygiene (ctxpred G) a\n    -> hygiene (ctxpred G) b\n    -> hygiene (permit (ctxpred G)) c\n    -> hygiene (permit (ctxpred G)) d\n    -> (forall i s s',\n          pwctx i s s' G\n          -> exists pg R,\n               pgointerp s lvo pg\n               /\\ pgointerp s' lvo pg\n               /\\ interp pg true i (subst s a) R\n               /\\ interp pg false i (subst s' a) R\n               /\\ interp pg true i (subst s b) R\n               /\\ interp pg false i (subst s' b) R)\n    -> (forall i s s',\n          pwctx i s s' (hyp_tm a :: G)\n          -> exists pg R,\n               pgointerp (compose sh1 s) lvo pg\n               /\\ interp pg true i (subst s c) R\n               /\\ interp pg false i (subst s' c) R)\n    -> (forall i s s',\n          pwctx i s s' (hyp_tm a :: G)\n          -> exists pg R,\n               pgointerp (compose sh1 s) lvo pg\n               /\\ interp pg true i (subst s d) R\n               /\\ interp pg false i (subst s' d) R)\n    -> (forall i s s',\n          pwctx i s s' (hyp_tm c :: hyp_tm a :: G)\n          -> exists R,\n               interp toppg true i (subst s (subst sh1 d)) R\n               /\\ interp toppg false i (subst s' (subst sh1 d)) R\n               /\\ rel (den R) i (subst s mr) (subst s' mr))\n    -> (forall i s s',\n          pwctx i s s' (hyp_tm d :: hyp_tm a :: G)\n          -> exists R,\n               interp toppg true i (subst s (subst sh1 c)) R\n               /\\ interp toppg false i (subst s' (subst sh1 c)) R\n               /\\ rel (den R) i (subst s ml) (subst s' ml))\n    -> forall i s s',\n         pwctx i s s' G\n         -> exists pg R,\n              pgointerp s lvo pg\n              /\\ pgointerp s' lvo pg\n              /\\ interp pg true i (subst s (set a c)) R\n              /\\ interp pg false i (subst s' (set a c)) R\n              /\\ interp pg true i (subst s (set b d)) R\n              /\\ interp pg false i (subst s' (set b d)) R.\nProof.\nintros lvo G a b c d mr ml Hcla Hclb Hclc Hcld Hseqab Hseqc Hseqd Hseqcd Hseqdc i s s' Hs.\nso (seqctx_impl_closub _#4 (pwctx_impl_seqctx _#4 Hs)) as (Hcls & Hcls').\nso (Hseqab _#3 Hs) as (pg & A & Hlvl & Hlvr & Hal & Har & Hbl & Hbr).\nassert (den A = ceiling (S i) (den A)) as HeqA.\n  {\n  so (basic_impl_iutruncate _#6 Hal) as Heq.\n  exact (f_equal den Heq).\n  }\nexploit (extract_functional pg i (den A) (subst (under 1 s) c) (subst (under 1 s') c)) as (C & Hcl & Hcr); eauto using subst_closub_under_permit.\n  {\n  intros j m p Hmp.\n  assert (pwctx j (dot m s) (dot p s') (cons (hyp_tm a) G)) as Hss.\n    {\n    assert (j <= i) as Hj.\n      {\n      rewrite -> HeqA in Hmp.\n      destruct Hmp.\n      omega.\n      }\n    apply pwctx_cons_tm_seq; eauto using pwctx_downward.\n      {\n      eapply seqhyp_tm_leq; eauto using interp_increase, toppg_max.\n      }\n\n      {\n      intros j' t t' Ht.\n      so (Hseqab _#3 Ht) as (pg' & R & _ & _ & Hl & Hr & _).\n      eauto.\n      }\n    }\n  so (Hseqc _#3 Hss) as (pg' & R & Hlv' & Hcl & Hcr).\n  simpsubin Hlv'.\n  so (pgointerp_fun _#4 Hlvl Hlv'); subst pg'.\n  exists R.\n  simpsub.\n  auto.\n  }\nexploit (extract_functional pg i (den A) (subst (under 1 s) d) (subst (under 1 s') d)) as (D & Hdl & Hdr); eauto using subst_closub_under_permit.\n  {\n  intros j m p Hmp.\n  assert (pwctx j (dot m s) (dot p s') (cons (hyp_tm a) G)) as Hss.\n    {\n    assert (j <= i) as Hj.\n      {\n      rewrite -> HeqA in Hmp.\n      destruct Hmp.\n      omega.\n      }\n    apply pwctx_cons_tm_seq; eauto using pwctx_downward.\n      {\n      eapply seqhyp_tm_leq; eauto using interp_increase, toppg_max.\n      }\n\n      {\n      intros j' t t' Ht.\n      so (Hseqab _#3 Ht) as (pg' & R & _ & _ & Hl & Hr & _).\n      eauto.\n      }\n    }\n  so (Hseqd _#3 Hss) as (pg' & R & Hlv' & Hdl & Hdr).\n  simpsubin Hlv'.\n  so (pgointerp_fun _#4 Hlvl Hlv'); subst pg'.\n  exists R.\n  simpsub.\n  auto.\n  }\nexists pg, (iuset stop A C).\nassert (forall j e m n p q E (Hmn : rel (den A) j m n),\n          functional the_system pg true i (den A) (subst (under 1 s) e) E\n          -> functional the_system pg false i (den A) (subst (under 1 s') e) E\n          -> rel (den (pi1 E (urelspinj (den A) j m n Hmn))) j p q\n          -> (forall i s s',\n                pwctx i s s' (hyp_tm a :: G)\n                -> exists pg R,\n                     pgointerp (compose sh1 s) lvo pg\n                     /\\ interp pg true i (subst s e) R\n                     /\\ interp pg false i (subst s' e) R)\n          -> pwctx j (dot p (dot m s)) (dot q (dot n s')) (hyp_tm e :: hyp_tm a :: G)) as Hext.\n  {\n  intros j e m n p q E Hmn Hel Her Hpq Hseqe.\n  so (basic_member_index _#9 Hal Hmn) as Hj.\n  apply pwctx_cons_tm_seq.\n    {\n    apply pwctx_cons_tm_seq; eauto using pwctx_downward.\n      {\n      eapply (seqhyp_tm _#5 (iutruncate (S j) A)).\n        {\n        apply (basic_downward _#3 i); auto.\n        eapply interp_increase; eauto using toppg_max.\n        }\n\n        {\n        apply (basic_downward _#3 i); auto.\n        eapply interp_increase; eauto using toppg_max.\n        }\n\n        {\n        split; auto.\n        }\n      }\n\n      {\n      intros k u u' Hu.\n      so (Hseqab _#3 Hu) as (pg' & A' & _ & _ & Hl & Hr & _).\n      eauto.\n      }\n    }\n\n    {\n    invert Hel.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn) as Hmel; clear Hact.\n    simpsubin Hmel.\n    invert Her.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn) as Hmer; clear Hact.\n    simpsubin Hmer.\n    eapply seqhyp_tm; eauto using interp_increase, toppg_max.\n    }\n\n    {\n    intros k u u' Hu.\n    so (Hseqe _#3 Hu) as (pg' & R & _ & Hl & Hr).\n    simpsubin Hl.\n    simpsubin Hr.\n    eauto.\n    }\n  }\nassert (iuset stop A C = iuset stop A D) as Heq.\n  {\n  apply prod_extensionality; cbn; auto.\n  apply urel_extensionality.\n  fextensionality 3.\n  intros j m n.\n  cbn.\n  pextensionality.\n    {\n    intro H.\n    decompose H.\n    intros p q Hmn Hpq.\n    so (basic_member_index _#9 Hal Hmn) as Hj.\n    so (Hext _#7 Hmn Hcl Hcr Hpq Hseqc) as Hs'.\n    so (Hseqcd _#3 Hs') as (R & Hmdl & _ & Hx).\n    simpsubin Hmdl.\n    invert Hdl.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn) as Hmdl'.\n    simpsubin Hmdl'.\n    so (interp_fun _#7 Hmdl Hmdl'); subst R.\n    exists (subst (dot p (dot m s)) mr), (subst (dot q (dot n s')) mr), Hmn.\n    auto.\n    }\n\n    {\n    intro H.\n    decompose H.\n    intros p q Hmn Hpq.\n    so (basic_member_index _#9 Hal Hmn) as Hj.\n    so (Hext _#7 Hmn Hdl Hdr Hpq Hseqd) as Hs'.\n    so (Hseqdc _#3 Hs') as (R & Hmdl & _ & Hx).\n    simpsubin Hmdl.\n    invert Hcl.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn) as Hmdl'.\n    simpsubin Hmdl'.\n    so (interp_fun _#7 Hmdl Hmdl'); subst R.\n    exists (subst (dot p (dot m s)) ml), (subst (dot q (dot n s')) ml), Hmn.\n    auto.\n    }\n  }\nsimpsub.\ndo2 5 split; auto.\n  {\n  apply interp_eval_refl.\n  apply interp_set; auto.\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_set; auto.\n  }\n\n  {\n  rewrite -> Heq.\n  apply interp_eval_refl.\n  apply interp_set; auto.\n  }\n\n  {\n  rewrite -> Heq.\n  apply interp_eval_refl.\n  apply interp_set; auto.\n  }\nQed.               \n\n\nLemma sound_set_formation :\n  forall G a a' b b' mr ml,\n    pseq G (deqtype a a')\n    -> pseq (cons (hyp_tm a) G) (deqtype b b)\n    -> pseq (cons (hyp_tm a) G) (deqtype b' b')\n    (* b implies b' *)\n    -> pseq (hyp_tm b :: hyp_tm a :: G)\n         (deq mr mr (subst sh1 b'))\n    (* b' implies b *)\n    -> pseq (hyp_tm b' :: hyp_tm a :: G)\n         (deq ml ml (subst sh1 b))\n    -> pseq G (deqtype (set a b) (set a' b')).\nProof.\nintros G a b c d mr ml.\nrevert G.\nrefine (seq_pseq 4 [] a [] b [hyp_emp] c [hyp_emp] d 5 [] _ [_] _ [_] _ [_; _] _ [_; _] _ _ _); cbn.\nintros G Hcla Hclb Hclc Hcld Hseqab Hseqc Hseqd Hseqcd Hseqdc.\nrewrite -> seq_eqtype in Hseqab, Hseqc, Hseqd |- *.\nrewrite -> seq_deq in Hseqcd, Hseqdc.\nexploit (sound_set_formation_main None G a b c d mr ml) as H; auto.\n  {\n  intros i s s' Hs.\n  so (Hseqab _#3 Hs) as (R & H).\n  exists toppg, R.\n  do2 2 split; auto; cbn; auto.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqc _#3 Hs) as (R & Hl & Hr & _).\n  exists toppg, R.\n  split; auto.\n  cbn.\n  reflexivity.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqd _#3 Hs) as (R & Hl & Hr & _).\n  exists toppg, R.\n  split; auto.\n  cbn.\n  reflexivity.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqcd _#3 Hs) as (R & Hl & Hr & Hm & _).\n  eauto.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqdc _#3 Hs) as (R & Hl & Hr & Hm & _).\n  eauto.\n  }\nintros i s s' Hs.\nso (H _#3 Hs) as (pg & R & Hlv & _ & H').\ncbn in Hlv.\nsubst pg.\neauto.\nQed.\n\n\nLemma sound_set_formation_univ :\n  forall G lv a a' b b' mr ml,\n    pseq G (deq a a' (univ lv))\n    -> pseq (cons (hyp_tm a) G) (deq b b (univ (subst sh1 lv)))\n    -> pseq (cons (hyp_tm a) G) (deq b' b' (univ (subst sh1 lv)))\n    (* b implies b' *)\n    -> pseq (hyp_tm b :: hyp_tm a :: G)\n         (deq mr mr (subst sh1 b'))\n    (* b' implies b *)\n    -> pseq (hyp_tm b' :: hyp_tm a :: G)\n         (deq ml ml (subst sh1 b))\n    -> pseq G (deq (set a b) (set a' b') (univ lv)).\nProof.\nintros G lv a b c d mr ml.\nrevert G.\nrefine (seq_pseq 4 [] a [] b [hyp_emp] c [hyp_emp] d 5 [] _ [_] _ [_] _ [_; _] _ [_; _] _ _ _); cbn.\nintros G Hcla Hclb Hclc Hcld Hseqab Hseqc Hseqd Hseqcd Hseqdc.\nrewrite -> seq_univ in Hseqab, Hseqc, Hseqd |- *.\nrewrite -> seq_deq in Hseqcd, Hseqdc.\nexploit (sound_set_formation_main (Some lv) G a b c d mr ml) as H; auto.\n  {\n  intros i s s' Hs.\n  so (Hseqc _#3 Hs) as (pg & R & Hlv & _ & Hl & Hr & _).\n  exists pg, R.\n  split; auto.\n  unfold pgointerp.\n  simpsubin Hlv.\n  exact Hlv.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqd _#3 Hs) as (pg & R & Hlv & _ & Hl & Hr & _).\n  exists pg, R.\n  split; auto.\n  unfold pgointerp.\n  simpsubin Hlv.\n  exact Hlv.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqcd _#3 Hs) as (R & Hl & Hr & Hm & _).\n  eauto.\n  }\n\n  {\n  intros i s s' Hs.\n  so (Hseqdc _#3 Hs) as (R & Hl & Hr & Hm & _).\n  eauto.\n  }\nQed.\n\n\nLemma sound_set_intro :\n  forall G a b m n p,\n    pseq G (deq m n a)\n    -> pseq G (deq p p (subst1 m b))\n    -> pseq (hyp_tm a :: G) (deqtype b b)\n    -> pseq G (deq m n (set a b)).\nProof.\nintros G a b m n p.\nrevert G.\nrefine (seq_pseq 1 [hyp_emp] b 3 [] _ [] _ [_] _ _ _); cbn.\nintros G Hclb Hseqmn Hseqp Hseqb.\nrewrite -> seq_eqtype in Hseqb.\nrewrite -> seq_deq in Hseqmn, Hseqp |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqmn _#3 Hs) as (A & Hal & Har & Hm & Hn & Hmn).\nassert (den A = ceiling (S i) (den A)) as HeqA.\n  {\n  so (basic_impl_iutruncate _#6 Hal) as Heq.\n  exact (f_equal den Heq).\n  }\nexploit (extract_functional toppg i (den A) (subst (under 1 s) b) (subst (under 1 s') b)) as (B & Hbl & Hbr); eauto using subst_closub_under_permit.\n  {\n  intros j r t Hrt.\n  assert (pwctx j (dot r s) (dot t s') (cons (hyp_tm a) G)) as Hss.\n    {\n    assert (j <= i) as Hj.\n      {\n      rewrite -> HeqA in Hrt.\n      destruct Hrt.\n      omega.\n      }\n    apply pwctx_cons_tm_seq; eauto using pwctx_downward.\n      {\n      eapply seqhyp_tm_leq; eauto using interp_increase, toppg_max.\n      }\n\n      {\n      intros j' u u' Hu.\n      so (Hseqmn _#3 Hu) as (R & Hl & Hr & _).\n      eauto.\n      }\n    }\n  so (Hseqb _#3 Hss) as (R & Hbl & Hbr & _).\n  exists R.\n  simpsub.\n  auto.\n  }\nso (Hseqp _#3 Hs) as (Bm & Hbml & _ & Hp & _).\nsimpsubin Hbml.\ninvert Hbl.\nintros _ _ Hact.\nso (Hact _#3 (le_refl _) Hm) as H.\nsimpsubin H.\nso (basic_fun _#7 H Hbml); subst Bm; clear H Hbml.\nexists (iuset stop A B).\nsimpsub.\ndo2 4 split;\ntry (apply interp_eval_refl;\n     apply interp_set; auto).\n  {\n  cbn.\n  exists (subst s p), (subst s' p), Hm.\n  auto.\n  }\n\n  {\n  cbn.\n  exists (subst s p), (subst s' p), Hn.\n  force_exact Hp.\n  do 3 f_equal.\n  apply urelspinj_equal; auto.\n  }\n\n\n  {\n  cbn.\n  exists (subst s p), (subst s' p), Hmn.\n  force_exact Hp.\n  do 3 f_equal.\n  apply urelspinj_equal; auto.\n  }\nQed.\n\n\nLemma sound_set_elim1 :\n  forall G a b m n,\n    pseq G (deq m n (set a b))\n    -> pseq G (deq m n a).\nProof.\nintros G a b m n.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseq.\nrewrite -> seq_deq in Hseq |- *.\nintros i s s' Hs.\nso (Hseq i s s' Hs) as (R & Hl & Hr & Hm & Hn & Hmn); clear Hseq.\nsimpsubin Hl.\nsimpsubin Hr.\ninvert (basic_value_inv _#6 value_set Hl).\nintros A B Ha Hb Heq1.\ninvert (basic_value_inv _#6 value_set Hr).\nintros A' B' Ha' Hb' Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq2.\nsubst R.\nso (iuset_inj _#5 Heq); subst A'.\nexists A.\ndo2 4 split; auto.\n  {\n  cbn in Hm.\n  decompose Hm.\n  intros _ _ H _.\n  auto.\n  }\n\n  {\n  cbn in Hn.\n  decompose Hn.\n  intros _ _ H _.\n  auto.\n  }\n\n  {\n  cbn in Hmn.\n  decompose Hmn.\n  intros _ _ H _.\n  auto.\n  }\nQed.\n\n\nLemma sound_set_elim2 :\n  forall G a b m J,\n    pseq G (deq m m (set a b))\n    -> pseq (hyp_tm a :: G) (deqtype b b)\n    -> pseq (hyp_tm (subst1 m b) :: G) (substj sh1 J)\n    -> pseq G J.\nProof.\nintros G a b m J.\nrevert G.\nrefine (seq_pseq 0 3 [] _ [_] _ [_] _ _ _); cbn.\nintros G Hseqm Hseqb Hseqnp.\nrewrite -> seq_eqtype in Hseqb.\ndestruct J as [n p c].\nsimpsubin Hseqnp.\nrewrite -> seq_deq in Hseqm, Hseqnp |- *.\nassert (forall i s s',\n          pwctx i s s' G\n          -> pwctx i (dot (subst s m) s) (dot (subst s' m) s') (hyp_tm a :: G)) as Hsm.\n  {\n  intros i s s' Hs.\n  apply pwctx_cons_tm_seq; auto.\n    {\n    so (Hseqm _#3 Hs) as (R & Hl & Hr & Hm & _).\n    simpsubin Hl.\n    simpsubin Hr.\n    invert (basic_value_inv _#6 value_set Hl).\n    intros A B Hal _ Heq1.\n    invert (basic_value_inv _#6 value_set Hr).\n    intros A' B' Har _ Heq2.\n    so (eqtrans Heq1 (eqsymm Heq2)) as Heq.\n    clear Heq2.\n    subst R.\n    so (iuset_inj _#5 Heq); subst A'.\n    cbn in Hm.\n    decompose Hm.\n    intros _ _ Hm' _.\n    apply (seqhyp_tm _#5 A); auto.\n    }\n\n    {\n    intros j u u' Hu.\n    so (Hseqm _#3 Hu) as (R & Hl & Hr & Hm & _).\n    simpsubin Hl.\n    simpsubin Hr.\n    invert (basic_value_inv _#6 value_set Hl).\n    intros A B Hal _ Heq1.\n    invert (basic_value_inv _#6 value_set Hr).\n    intros A' B' Har _ Heq2.\n    so (eqtrans Heq1 (eqsymm Heq2)) as Heq.\n    clear Heq2.\n    so (iuset_inj _#5 Heq); subst A'.\n    eauto.\n    }\n  }\nintros i s s' Hs.\nso (Hseqm _#3 Hs) as (R & Hl & Hr & Hm & _).\nsimpsubin Hl.\nsimpsubin Hr.\ninvert (basic_value_inv _#6 value_set Hl); clear Hl.\nintros A B Hal Hbl Heq1.\ninvert (basic_value_inv _#6 value_set Hr); clear Hr.\nintros A' B' Har _ Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq2.\nsubst R.\nso (iuset_inj _#5 Heq); subst A'.\nclear B' Heq.\ncbn in Hm.\ndecompose Hm.\nintros q r Hm Hqr.\nassert (pwctx i (dot q s) (dot r s') (hyp_tm (subst1 m b) :: G)) as Hsqr.\n  {\n  apply pwctx_cons_tm_seq; auto.\n    {\n    simpsub.\n    apply (seqhyp_tm _#5 (pi1 B (urelspinj _#4 Hm))); auto.\n      {\n      invert Hbl.\n      intros _ _ Hact.\n      so (Hact _#3 (le_refl _) Hm) as H.\n      simpsubin H.\n      exact H.\n      }\n\n      {\n      invert Hbl.\n      intros _ _ Hact.\n      so (Hact _#3 (le_refl _) Hm) as Hbml.\n      so (Hseqb _#3 (Hsm _#3 Hs)) as (Bm & Hbml' & Hbmr & _).\n      simpsubin Hbml.\n      simpsubin Hbml'.\n      so (basic_fun _#7 Hbml Hbml'); subst Bm.\n      exact Hbmr.\n      }\n    }\n\n    {\n    intros j u u' Hu.\n    so (Hseqb _#3 (Hsm _#3 Hu)) as (R & Hl & Hr & _).\n    simpsub.\n    eauto.\n    }\n  }\nso (Hseqnp _#3 Hsqr) as (C & Hcl & Hcr & Hn & Hp & Hnp).\nsimpsubin Hcl.\nsimpsubin Hcr.\nsimpsubin Hn.\nsimpsubin Hp.\nsimpsubin Hnp.\nexists C.\ndo2 4 split; auto.\nQed.\n\n\nLemma interp_set_invert :\n  forall pg s s' i a a' b b' R,\n    interp pg s i (set a b) R\n    -> interp pg s' i (set a' b') R\n    -> exists A,\n         interp pg s i a A\n         /\\ interp pg s' i a' A.\nProof.\nintros pg s s' i a a' b b' R Hl Hr.\ninvert (basic_value_inv _#6 value_set Hl).\nintros A B Hal _ Heq1.\ninvert (basic_value_inv _#6 value_set Hr).\nintros A' B' Hal' _ Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq1 Heq2.\nso (iuset_inj _#5 Heq); subst A'.\neauto.\nQed.\n\n\nLemma sound_set_hyp_weaken :\n  forall G1 G2 a b J,\n    pseq (G2 ++ hyp_tm b :: hyp_tm a :: G1) J\n    -> pseq (G2 ++ hyp_tm b :: hyp_tm (set a b) :: G1) J.\nProof.\nintros G1 G2 a b J.\nrevert G1.\nrefine (seq_pseq_hyp 0 1 _ [_; _] _ _ [_; _] _ _); cbn.\nintros G Hseq HclJ.\nreplace J with (substj (under (length G2) id) J) in Hseq by (simpsub; reflexivity).\nreplace G2 with (substctx id G2) in Hseq by (simpsub; reflexivity).\neapply (subsume_seq _ _ (under (length G2) id)); eauto.\nrewrite -> length_substctx.\napply subsume_under.\ndo2 2 split.\n  {\n  intros j.\n  split.\n    {\n    intros Hj.\n    simpsub.\n    apply hygiene_var.\n    rewrite -> ctxpred_length in Hj |- *.\n    cbn in Hj |- *.\n    omega.\n    }\n\n    {\n    intros Hj.\n    simpsub.\n    simpsubin Hj.\n    invertc Hj.\n    intro Hj.\n    rewrite -> ctxpred_length in Hj |- *.\n    cbn in Hj |- *.\n    omega.\n    }\n  }\n\n  {\n  intros j.\n  split.\n    {\n    intros Hj.\n    simpsub.\n    apply hygiene_var.\n    rewrite -> ctxpred_length in Hj |- *.\n    cbn in Hj |- *.\n    omega.\n    }\n\n    {\n    intros Hj.\n    simpsub.\n    simpsubin Hj.\n    invertc Hj.\n    intro Hj.\n    rewrite -> ctxpred_length in Hj |- *.\n    cbn in Hj |- *.\n    omega.\n    }\n  }\nintros i ss ss' Hss.\ninvertc Hss.\nintros p q ss2 ss2' Hss Hpq Hleft2 Hright2 <- <-.\ninvertc Hss.\nintros m n s s' Hs Hmn Hleft1 Hright1 <- <-.\nsimpsubin Hmn.\ninvertc Hmn.\nintros R Hsetl Hsetr Hmn.\ninvertc Hpq.\nintros Bm Hbml Hbnr Hpq.\ninvert (basic_value_inv _#6 value_set Hsetl).\nintros A B Hal Hbl Heq1.\ninvert (basic_value_inv _#6 value_set Hsetr).\nintros A' B' Har Hbr Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq2.\nsubst R.\nso (iuset_inj _#5 Heq); subst A'; clear Heq.\nso Hmn as Hmnset.\ncbn in Hmn.\ndecompose Hmn.\nintros _ _ Hmn _.\ninvert Hbl.\nintros _ _ Hact.\nso (Hact _ _ _ (le_refl _) Hmn) as H; clear Hact.\nsimpsubin H.\nso (basic_fun _#7 Hbml H); subst Bm; clear H.\ndo2 4 split.\n  {\n  simpsub.\n  apply pwctx_cons_tm.\n    {\n    apply pwctx_cons_tm; auto.\n      {\n      eapply seqhyp_tm; eauto.\n      }\n\n      {\n      intros j u Hj Hu.\n      exploit (Hleft1 j false u) as H; auto using smaller_le, pwctx_impl_seqctx.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      invertc H.\n      intros R Hsetr' Hsetu.\n      so (interp_set_invert _#9 Hsetr' Hsetu) as (A' & Har' & Hau).\n      eapply relhyp_tm; eauto.\n      }\n\n      {\n      intros j u Hj Hu.\n      exploit (Hright1 j false u) as H; auto using smaller_le, pwctx_impl_seqctx.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      invertc H.\n      intros R Hsetu Hsetl'.\n      so (interp_set_invert _#9 Hsetu Hsetl') as (A' & Har' & Hau).\n      eapply relhyp_tm; eauto.\n      }\n    }\n\n    {\n    eapply seqhyp_tm; eauto.\n    }\n\n    {\n    intros j uu Hj Huu.\n    exploit (Hleft2 j false uu) as H; auto using smaller_le, pwctx_impl_seqctx.\n    rewrite -> qpromote_cons.\n    cbn.\n    invertc Huu.\n    intros n' u Hu Hmn' _ _ <-.\n    apply seqctx_cons; auto using pwctx_impl_seqctx.\n    simpsub.\n    simpsubin Hmn'.\n    invertc Hmn'.\n    intros A' Hal' Hau Hmn'.\n    so (basic_fun _#7 (basic_downward _#7 Hj Hal) Hal'); subst A'; clear Hal'.\n    apply (seqhyp_tm _#5 (iutruncate (S j) (iuset _ A B))).\n      {\n      eapply basic_downward; eauto.\n      }\n\n      {\n      exploit (Hleft1 j false u) as H; auto using smaller_le, pwctx_impl_seqctx.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      invertc H.\n      intros R Hsetr' Hsetu.\n      so (basic_fun _#7 (basic_downward _#7 Hj Hsetr) Hsetr'); subst R.\n      exact Hsetu.\n      }\n    \n      {\n      cbn.\n      split; [omega |].\n      destruct Hmn' as (_ & Hmn').\n      exists p, q, Hmn'.\n      refine (rel_from_dist _#6 _ (urel_downward_leq _#6 Hj Hpq)).\n      apply den_nonexpansive.\n      apply (pi2 B).\n      apply urelspinj_dist_diff; auto.\n      }\n    }\n\n    {\n    intros j uu Hj Huu.\n    exploit (Hright2 j false uu) as H; auto using smaller_le, pwctx_impl_seqctx.\n    rewrite -> qpromote_cons.\n    cbn.\n    invertc Huu.\n    intros m' u Hu Hmn' _ _ <-.\n    apply seqctx_cons; auto using pwctx_impl_seqctx.\n    simpsub.\n    simpsubin Hmn'.\n    invertc Hmn'.\n    intros A' Hau Har' Hmn'.\n    so (basic_fun _#7 (basic_downward _#7 Hj Har) Har'); subst A'; clear Har'.\n    apply (seqhyp_tm _#5 (iutruncate (S j) (iuset _ A B))).\n    2:{\n      eapply basic_downward; eauto.\n      }\n\n      {\n      exploit (Hright1 j false u) as H; auto using smaller_le, pwctx_impl_seqctx.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      invertc H.\n      intros R Hsetl' Hsetu.\n      so (basic_fun _#7 (basic_downward _#7 Hj Hsetl) Hsetl'); subst R.\n      exact Hsetu.\n      }\n    \n      {\n      cbn.\n      split; [omega |].\n      destruct Hmn' as (_ & Hmn').\n      exists p, q, Hmn'.\n      refine (rel_from_dist _#6 _ (urel_downward_leq _#6 Hj Hpq)).\n      apply den_nonexpansive.\n      apply (pi2 B).\n      apply urelspinj_dist_diff; auto.\n      eapply urel_downward_leq; eauto.\n      }\n    }\n  }\n\n  {\n  simpsub.\n  apply equivsub_refl.\n  }\n\n  {\n  simpsub.\n  apply equivsub_refl.\n  }\n\n  {\n  intros j d uu Hsmall Huu.\n  so (smaller_impl_le _#3 Hsmall) as Hj.\n  simpsubin Huu.\n  simpsub.\n  rewrite -> !qpromote_cons in Huu |- *.\n  rewrite -> !qpromote_hyp_tm in Huu |- *.\n  invertc Huu.\n  intros q' uu2 Huu Hpq' <-.\n  invertc Huu.\n  intros n' u Hu Hmn' <-.\n  apply seqctx_cons.\n    {\n    apply seqctx_cons; auto.\n    simpsub.\n    apply (seqhyp_tm _#5 (iutruncate (S j) (iuset stop A B))).\n      {\n      apply (basic_downward _#3 i); auto.\n      }\n\n      {\n      exploit (Hleft1 j d u) as H; auto.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      simpsub.\n      invertc H.\n      intros R Hsetr' Hsetu.\n      so (basic_fun _#7 (basic_downward _#7 Hj Hsetr) Hsetr'); subst R.\n      auto.\n      }\n\n      {\n      split; auto.\n      cbn.\n      simpsubin Hmn'.\n      invertc Hmn'.\n      intros R Hal' _ Hmn'.\n      so (basic_fun _#7 (basic_downward _#7 Hj Hal) Hal'); subst R.\n      destruct Hmn' as (_ & Hmn').\n      exists p, q, Hmn'.\n      refine (rel_from_dist _#6 _ (urel_downward_leq _#6 Hj Hpq)).\n      apply den_nonexpansive.\n      apply (pi2 B).\n      apply urelspinj_dist_diff; auto.\n      }\n    }\n\n    {\n    simpsub.\n    invertc Hmn'.\n    intros R Hal' _ Hmn'.\n    so (basic_fun _#7 (basic_downward _#7 Hj Hal) Hal'); subst R.\n    destruct Hmn' as (_ & Hmn').\n    invert Hbl.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn') as Hmblj; clear Hact.\n    simpsubin Hmblj.\n    simpsubin Hpq'.\n    invertc Hpq'.\n    intros R Hmblj' Hmbu Hpq'.\n    so (basic_fun _#7 Hmblj Hmblj'); subst R.\n    apply (seqhyp_tm _#5 (pi1 B (urelspinj _#4 Hmn'))); auto.\n    }\n  }\n\n  {\n  intros j d uu Hsmall Huu.\n  so (smaller_impl_le _#3 Hsmall) as Hj.\n  simpsubin Huu.\n  simpsub.\n  rewrite -> !qpromote_cons in Huu |- *.\n  rewrite -> !qpromote_hyp_tm in Huu |- *.\n  invertc Huu.\n  intros p' uu2 Huu Hpq' <-.\n  invertc Huu.\n  intros m' u Hu Hmn' <-.\n  apply seqctx_cons.\n    {\n    apply seqctx_cons; auto.\n    simpsub.\n    apply (seqhyp_tm _#5 (iutruncate (S j) (iuset stop A B))).\n      {\n      exploit (Hright1 j d u) as H; auto.\n      rewrite -> qpromote_hyp_tm in H.\n      simpsubin H.\n      simpsub.\n      invertc H.\n      intros R Hsetl' Hsetu.\n      so (basic_fun _#7 (basic_downward _#7 Hj Hsetl) Hsetl'); subst R.\n      auto.\n      }\n\n      {\n      apply (basic_downward _#3 i); auto.\n      }\n\n      {\n      split; auto.\n      cbn.\n      simpsubin Hmn'.\n      invertc Hmn'.\n      intros R _ Har' Hmn'.\n      so (basic_fun _#7 (basic_downward _#7 Hj Har) Har'); subst R.\n      destruct Hmn' as (_ & Hmn').\n      exists p, q, Hmn'.\n      refine (rel_from_dist _#6 _ (urel_downward_leq _#6 Hj Hpq)).\n      apply den_nonexpansive.\n      apply (pi2 B).\n      apply urelspinj_dist_diff; auto.\n      eapply urel_downward_leq; eauto.\n      }\n    }\n\n    {\n    simpsub.\n    invertc Hmn'.\n    intros R _ Har' Hmn'.\n    so (basic_fun _#7 (basic_downward _#7 Hj Har) Har'); subst R.\n    destruct Hmn' as (_ & Hmn').\n    invert Hbr.\n    intros _ _ Hact.\n    so (Hact _#3 Hj Hmn') as Hmblj; clear Hact.\n    simpsubin Hmblj.\n    simpsubin Hpq'.\n    invertc Hpq'.\n    intros R Hmbu Hmblj' Hpq'.\n    so (basic_fun _#7 Hmblj Hmblj'); subst R.\n    apply (seqhyp_tm _#5 (pi1 B' (urelspinj _#4 Hmn'))); auto.\n    }\n  }\nQed.\n\n\nLemma unit_urel_dist :\n  forall i i' j,\n    j <= i\n    -> j <= i'\n    -> @dist (wurel_ofe stop) (S j) (unit_urel stop i) (unit_urel stop i').\nProof.\nintros i i' j Hji Hji'.\nintros k Hk.\nfextensionality 2.\nintros m p.\ncbn.\npextensionality.\n  {\n  intro H.\n  decompose H.\n  intros _ _ Hclm Hclp Hsteps Hsteps'.\n  do2 5 split; auto.\n  omega.\n  }\n\n  {\n  intro H.\n  decompose H.\n  intros _ _ Hclm Hclp Hsteps Hsteps'.\n  do2 5 split; auto.\n  omega.\n  }\nQed.\n\n\nLemma sound_squash_idem :\n  forall G a b,\n    pseq G (deqtype (set a b) (set a b))\n    -> pseq G (deqtype (set a b) (set a (squash b))).\nProof.\nintros G a b.\nrevert G.\nrefine (seq_pseq 1 [hyp_emp] b 1 [] _ _ _); cbn.\nintros G Hclb Hseq.\nrewrite -> seq_eqtype in Hseq |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseq _#3 Hs) as (R & Hsetl & Hsetr & _).\nexists R.\ndo2 2 split; auto.\nsimpsubin Hsetl.\nsimpsubin Hsetr.\nsimpsub.\ninvert (basic_value_inv _#6 value_set Hsetl).\nintros A B Hal Hbl Heq1.\ninvert (basic_value_inv _#6 value_set Hsetr).\nintros A' B' Har Hbr Heq2.\nso (eqtrans Heq1 (eqsymm Heq2)) as Heq.\nclear Heq2.\nsubst R.\nso (iuset_inj _#5 Heq); subst A'.\nassert (den A = ceiling (S i) (den A)) as HeqA.\n  {\n  exact (f_equal den (basic_impl_iutruncate _#6 Hal)).\n  }\nset (Cf := fun (D : urelsp (den A) -n> siurel_ofe) x => iuset stop (iubase (unit_urel stop (urelsp_index _ x))) (semiconst_ne (unit_urel stop (urelsp_index _ x)) (pi1 D x))).\nassert (forall D,\n          @nonexpansive (urelsp (den A)) siurel_ofe (Cf D)) as Hne.\n  {\n  intros D j x y Hxy.\n  destruct j as [| j].\n    {\n    apply dist_zero.\n    }\n  so (urelsp_eta _ _ x) as (k & m & p & Hmp & ->).\n  so (urelsp_eta _ _ y) as (k' & n & q & Hnq & ->).\n  unfold Cf.\n  rewrite -> !urelsp_index_inj.\n  so (urelspinj_dist_index' _#11 Hxy) as [(<- & Hkj) | (Hjk & Hjk')].\n    {\n    apply dist_refl'.\n    do 3 f_equal.\n    apply urelspinj_equal.\n    so (urelspinj_dist_invert _#11 Hxy).\n    rewrite -> Nat.min_r in H; auto.\n    omega.\n    }\n  split; cbn -[dist].\n    {\n    intros j' Hj'.\n    cbn.\n    fextensionality 2.\n    intros r t.\n    pextensionality.\n      {\n      intro H.\n      decompose H.\n      intros u v Hrt Huv.\n      rewrite -> urelsp_index_inj in Huv.\n      exists u, v.\n      assert (rel (unit_urel stop k') j' r t) as Hrt'.\n        {\n        refine (rel_from_dist _#6 _ Hrt).\n        apply unit_urel_dist; omega.\n        }\n      exists Hrt'.\n      rewrite -> urelsp_index_inj.\n      force_exact Huv.\n      f_equal.\n      apply ceiling_collapse.\n      apply den_nonexpansive.\n      apply (pi2 D).\n      apply urelspinj_dist_diff; try omega.\n      so (urelspinj_dist_invert _#11 Hxy) as H.\n      rewrite -> Nat.min_l in H; [| omega].\n      apply (urel_downward_leq _#3 j); auto.\n      omega.\n      }\n\n      {\n      intro H.\n      decompose H.\n      intros u v Hrt Huv.\n      rewrite -> urelsp_index_inj in Huv.\n      exists u, v.\n      assert (rel (unit_urel stop k) j' r t) as Hrt'.\n        {\n        refine (rel_from_dist _#6 _ Hrt).\n        apply unit_urel_dist; omega.\n        }\n      exists Hrt'.\n      rewrite -> urelsp_index_inj.\n      force_exact Huv.\n      f_equal.\n      apply ceiling_collapse.\n      apply den_nonexpansive.\n      apply (pi2 D).\n      apply urelspinj_dist_diff; try omega.\n      so (urelspinj_dist_invert _#11 Hxy) as H.\n      apply (urel_zigzag _#4 q m).\n        {\n        apply (urel_downward_leq _#3 k'); auto.\n        omega.\n        }\n\n        {\n        rewrite -> Nat.min_l in H; [| omega].\n        apply (urel_downward_leq _#3 j); auto.\n        omega.\n        }\n\n        {\n        apply (urel_downward_leq _#3 k); auto.\n        omega.\n        }\n      }\n    }\n\n    {\n    apply meta_iurel_nonexpansive.\n    split; cbn -[dist]; [| apply dist_refl].\n    apply unit_urel_dist; omega.\n    }\n  }\nset (C := fun D => ((expair (Cf D) (Hne D)) : urelsp (den A) -n> siurel_ofe)).\nassert (forall D,\n          iuset stop A D = iuset stop A (C D)) as Heq'.\n  {\n  intro D.\n  apply prod_extensionality; cbn; auto.\n  apply urel_extensionality.\n  fextensionality 3.\n  intros j m n.\n  cbn.\n  pextensionality.\n    {\n    intro H.\n    decompose H.\n    intros p q Hmn Hpq.\n    exists triv, triv, Hmn.\n    cbn.\n    so (unit_urel_triv stop _ _ (le_refl j)) as Htriv.\n    exists p, q.\n    rewrite -> urelsp_index_inj.\n    exists Htriv.\n    rewrite -> !urelsp_index_inj.\n    split; auto.\n    }\n\n    {\n    intro H.\n    decompose H.\n    unfold semiconst_ne.\n    cbn.\n    intros p q Hmn Hpq.\n    rewrite -> urelsp_index_inj in Hpq.\n    decompose Hpq.\n    intros r t Hpq Hrt.\n    rewrite -> urelsp_index_inj in Hrt.\n    exists r, t, Hmn.\n    destruct Hrt as (_ & Hrt).\n    exact Hrt.\n    }\n  }\nsplit.\n  {\n  apply interp_eval_refl.\n  rewrite -> Heq'.\n  apply interp_set; auto.\n  apply functional_i; auto.\n    {\n    eapply subst_closub_under_permit; eauto.\n    unfold squash.\n    prove_hygiene.\n    }\n  intros j m p Hj Hmp.\n  unfold squash.\n  simpsub.\n  apply interp_eval_refl.\n  apply interp_set.\n    {\n    apply interp_eval_refl.\n    rewrite -> urelsp_index_inj.\n    apply interp_unit.\n    }\n  rewrite -> urelsp_index_inj.\n  apply functional_i.\n    {\n    eapply hygiene_subst; eauto.\n    intros k Hk.\n    destruct k as [| k]; simpsub.\n      {\n      apply hygiene_shift_permit; auto.\n      exact (urel_closed _#5 Hmp andel).\n      }\n\n      {\n      apply hygiene_shift_permit.\n      eapply project_closub; eauto.\n      }\n    }\n\n    {\n    cbn.\n    rewrite -> ceiling_unit.\n    rewrite -> Nat.min_id.\n    reflexivity.\n    }\n  intros j' q r Hj' Hqr.\n  cbn.\n  simpsub.\n  invert Hbl.\n  intros _ _ Hact.\n  so (Hact _ _ _ (le_trans _#3 Hj' Hj) (urel_downward_leq _#6 Hj' Hmp)) as H.\n  simpsubin H.\n  so (basic_downward _#7 (le_refl _) H) as Hint; clear H.\n  unfold semiconst.\n  rewrite -> urelsp_index_inj.\n  force_exact Hint.\n  f_equal.\n  apply iutruncate_collapse.\n  apply (pi2 B).\n  apply urelspinj_dist_diff; auto.\n  eapply urel_downward_leq; eauto.\n  }\n\n  {\n  rewrite -> Heq.\n  apply interp_eval_refl.\n  rewrite -> Heq'.\n  apply interp_set; auto.\n  apply functional_i; auto.\n    {\n    eapply subst_closub_under_permit; eauto.\n    unfold squash.\n    prove_hygiene.\n    }\n  intros j m p Hj Hmp.\n  unfold squash.\n  simpsub.\n  apply interp_eval_refl.\n  apply interp_set.\n    {\n    apply interp_eval_refl.\n    rewrite -> urelsp_index_inj.\n    apply interp_unit.\n    }\n  rewrite -> urelsp_index_inj.\n  apply functional_i.\n    {\n    eapply hygiene_subst; eauto.\n    intros k Hk.\n    destruct k as [| k]; simpsub.\n      {\n      apply hygiene_shift_permit; auto.\n      exact (urel_closed _#5 Hmp ander).\n      }\n\n      {\n      apply hygiene_shift_permit.\n      eapply project_closub; eauto.\n      }\n    }\n\n    {\n    cbn.\n    rewrite -> ceiling_unit.\n    rewrite -> Nat.min_id.\n    reflexivity.\n    }\n  intros j' q r Hj' Hqr.\n  cbn.\n  simpsub.\n  invert Hbr.\n  intros _ _ Hact.\n  so (Hact _ _ _ (le_trans _#3 Hj' Hj) (urel_downward_leq _#6 Hj' Hmp)) as H.\n  simpsubin H.\n  so (basic_downward _#7 (le_refl _) H) as Hint; clear H.\n  unfold semiconst.\n  rewrite -> urelsp_index_inj.\n  force_exact Hint.\n  f_equal.\n  apply iutruncate_collapse.\n  apply (pi2 B').\n  apply urelspinj_dist_diff; auto.\n  eapply urel_downward_leq; eauto.\n  }\nQed.\n\n\nLemma sound_set_formation_invert :\n  forall G a a' b b',\n    pseq G (deqtype (set a b) (set a' b'))\n    -> pseq G (deqtype a a').\nProof.\nintros G a b c d.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _).\ncbn.\nintros G Hseq.\nrewrite -> seq_eqtype in Hseq |- *.\nintros i s s' Hs.\nso (Hseq _ _ _ Hs) as (R & Hacl & Hacr & Hbdl & Hbdr).\nsimpsubin Hacl.\ninvert (basic_value_inv _#6 value_set Hacl).\nintros A B1 Hal _ Heq.\nsimpsubin Hacr.\ninvert (basic_value_inv _#6 value_set Hacr).\nintros A' B2 Har _ Heq'.\nso (eqtrans Heq (eqsymm Heq')) as H.\nso (iuset_inj _#5 H); subst A'.\nclear H Heq'.\nsimpsubin Hbdl.\ninvert (basic_value_inv _#6 value_set Hbdl).\nintros A' B3 Hbl _ Heq'.\nso (eqtrans Heq (eqsymm Heq')) as H.\nso (iuset_inj _#5 H); subst A'.\nclear H Heq'.\nsimpsubin Hbdr.\ninvert (basic_value_inv _#6 value_set Hbdr).\nintros A' B4 Hbr _ Heq'.\nso (eqtrans Heq (eqsymm Heq')) as H.\nso (iuset_inj _#5 H); subst A'.\nclear H Heq' Heq.\nexists A.\nauto.\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/SoundSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.18275200800421965}}
{"text": "Require Import VST.concurrency.conclib.\nRequire Import VST.concurrency.ghosts.\nRequire Import VST.atomics.verif_lock.\nRequire Import VST.progs64.incr.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition spawn_spec := DECLARE _spawn spawn_spec.\n\nDefinition cptr_lock_inv g1 g2 ctr := EX z : Z, data_at Ews tuint (Vint (Int.repr z)) ctr *\n  EX x : Z, EX y : Z, !!(z = x + y) && ghost_var gsh1 x g1 * ghost_var gsh1 y g2.\n\nDefinition incr_spec :=\n DECLARE _incr\n  WITH sh : share, g1 : gname, g2 : gname, left : bool, n : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         LOCAL (gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n (if left then g1 else g2))\n  POST [ tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 (n+1) (if left then g1 else g2)).\n\nDefinition read_spec :=\n DECLARE _read\n  WITH sh : share, g1 : gname, g2 : gname, n1 : Z, n2 : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         LOCAL (gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2)\n  POST [ tuint ]\n         PROP ()\n         LOCAL (temp ret_temp (Vint (Int.repr (n1 + n2))))\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2).\n\nDefinition thread_lock_R sh g1 g2 ctr lockc :=\n  lock_inv sh lockc (cptr_lock_inv g1 g2 ctr) * ghost_var gsh2 1 g1.\n\nDefinition thread_lock_inv sh g1 g2 ctr lockc lockt :=\n  selflock (thread_lock_R sh g1 g2 ctr lockc) sh lockt.\n\nDefinition thread_func_spec :=\n DECLARE _thread_func\n  WITH y : val, x : share * gname * gname * globals\n  PRE [ _args OF (tptr tvoid) ]\n         let '(sh, g1, g2, gv) := x in\n         PROP  (readable_share sh)\n         LOCAL (temp _args y; gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr));\n                ghost_var gsh2 0 g1;\n                lock_inv sh (gv _thread_lock) (thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)))\n  POST [ tptr tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP ().\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt 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; incr_spec; read_spec; thread_func_spec; main_spec]).\n\nLemma ctr_inv_exclusive : forall g1 g2 p,\n  exclusive_mpred (cptr_lock_inv g1 g2 p).\nProof.\n  intros; unfold cptr_lock_inv.\n  eapply derives_exclusive, exclusive_sepcon1 with (Q := EX x : Z, EX y : Z, _),\n    data_at__exclusive with (sh := Ews)(t := tuint); auto; simpl; try omega.\n  Intro z; apply sepcon_derives; [cancel|].\n  Intros x y; Exists x y; apply derives_refl.\nQed.\nHint Resolve ctr_inv_exclusive : exclusive.\n\nLemma thread_inv_exclusive : forall sh g1 g2 ctr lock lockt,\n  exclusive_mpred (thread_lock_inv sh g1 g2 ctr lock lockt).\nProof.\n  intros; apply selflock_exclusive.\n  unfold thread_lock_R.\n  apply exclusive_sepcon1; auto with exclusive.\nQed.\nHint Resolve thread_inv_exclusive : exclusive.\n\nLemma ghost_var_incr : forall g1 g2 x y n (left : bool), ghost_var gsh1 x g1 * ghost_var gsh1 y g2 * ghost_var gsh2 n (if left then g1 else g2) |--\n  |==> !!((if left then x else y) = n) && ghost_var Tsh (n+1) (if left then g1 else g2) * ghost_var gsh1 (if left then y else x) (if left then g2 else g1).\nProof.\n  destruct left.\n  - rewrite sepcon_assoc, (sepcon_comm _ (ghost_var _ _ _)), <- sepcon_assoc.\n    erewrite ghost_var_share_join' by eauto with share.\n    Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n    apply ghost_var_update.\n  - erewrite sepcon_assoc, ghost_var_share_join' by eauto with share.\n    Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n    apply ghost_var_update.\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 g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  forward.\n    eapply semax_pre_bupd.\nfirst [apply SEP_entail'_bupd | apply SEP_entail']; go_lower.\n   match goal with\n   | |- ?R |-- ?R2 =>\n         let r2 := fresh \"R2\" in\n         pose (r2 := R2); change_no_check (R |-- r2) end.\n\nlet x := fresh g1 in\n  unshelve evar ( x : gname ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac |].\nlet x := fresh g2 in\n  unshelve evar ( x : gname ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac |].\nlet x := fresh x in\n  unshelve evar ( x : Z ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac x'|].\nlet x := fresh y in\n  unshelve evar ( x : Z ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac |].\nlet x := fresh n in\n  unshelve evar ( x : Z ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac |].\nlet x := fresh left in\n  unshelve evar ( x : bool ); revgoals; [ let x' := eval unfold x in x in\n                                       idtac |].\nlet H' := adjust2_sep_apply (ghost_var_incr ?g0 ?g3 ?x0 ?y0 ?n0 ?left0) in\nmatch type of H' with\n  | ?TH =>\n      match apply_find_core TH with\n      | ?C |-- ?D => idtac \"1\";\n          let frame := fresh \"frame\" in\n          evar ( frame : list mpred ); apply derives_trans with (C * fold_right_sepcon frame)(*;\n           [ solve\n           [ cancel_for_sep_apply ]\n           | eapply derives_trans;\n              [ apply sepcon_derives; [ clear frame; apply H' | apply derives_refl ]\n              | let x := fresh \"x\" in\n                set (x := fold_right_sepcon frame); subst frame; unfold fold_right_sepcon in x; subst x;\n                 rewrite ?sepcon_emp ] ]*)\n      end\n  end.\necancel.\n(* This should be solvable with ecancel! *)\n  gather_SEP 2 3 4.\n  viewshift_SEP 0 (!!((if left then x else y) = n) && ghost_var Tsh (n+1) (if left then g1 else g2) *\n    ghost_var gsh1 (if left then y else x) (if left then g2 else g1)).\n  { go_lower.\n    destruct left.\n    - rewrite (sepcon_comm _ (ghost_var _ _ _)), <- sepcon_assoc.\n      erewrite ghost_var_share_join' by eauto with share.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update.\n    - erewrite ghost_var_share_join' by eauto with share.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update. }\n  Intros; forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists (z + 1).\n    rewrite <- (ghost_var_share_join gsh1 gsh2) by auto with share.\n    unfold Frame; instantiate (1 := [ghost_var gsh2 (n+1) (if left then g1 else g2)]); simpl.\n    destruct left.\n    - Exists (n+1) y; entailer!.\n    - Exists x (n+1); entailer!. }\n  forward.\nQed.\n\nLemma body_read : semax_body Vprog Gprog f_read read_spec.\nProof.\n  start_function.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  assert_PROP (x = n1 /\\ y = n2) as Heq.\n  { gather_SEP 2 4.\n    erewrite ghost_var_share_join' by eauto with share.\n    gather_SEP 3 4.\n    erewrite ghost_var_share_join' by eauto with share.\n    entailer!. }\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists z x y; entailer!. }\n  destruct Heq; forward.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (sh, g1, g2, true, 0, gv).\n  simpl.\n  forward_call ((gv _thread_lock), sh, thread_lock_R sh g1 g2 (gv _ctr) (gv _ctr_lock), thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    rewrite selflock_eq at 2; cancel. }\n  forward.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  set (ctr := gv _ctr); set (lockt := gv _thread_lock); set (lock := gv _ctr_lock).\n  forward.\n  forward.\n  forward.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g1.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g2.\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    rewrite <- !(ghost_var_share_join gsh1 gsh2 Tsh) by auto with share.\n    unfold cptr_lock_inv; Exists 0 0 0; entailer!. }\n  (* need to split off shares for the locks here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (lockt, Ews, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  forward_spawn _thread_func nullval (sh1, g1, g2, gv).\n  { erewrite <- lock_inv_share_join; try apply Hsh; auto.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.\n    subst ctr lock lockt; entailer!. }\n  forward_call (sh2, g1, g2, false, 0, gv).\n  forward_call (lockt, sh2, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  { subst ctr lock lockt; cancel. }\n  unfold thread_lock_inv at 2; unfold thread_lock_R.\n  rewrite selflock_eq.\n  Intros.\n  simpl.\n  forward_call (sh2, g1, g2, 1, 1, gv).\n  (* We've proved that t is 2! *)\n  forward_call (lock, sh2, cptr_lock_inv g1 g2 ctr).\n  { subst ctr lock; cancel. }\n  forward_call (lockt, Ews, sh1, thread_lock_R sh1 g1 g2 ctr lock, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; subst ctr lock; cancel. }\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; subst lock ctr; cancel. }\n  forward.\nQed.\n\nDefinition extlink := ext_link_prog prog.\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\n#[export] Existing Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons body_incr.\nsemax_func_cons body_read.\nsemax_func_cons body_thread_func.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_incr_ecancel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3140505449918074, "lm_q1q2_score": 0.1825585524222686}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import Exprs.\nRequire Import Hints.\nRequire Import Postcond.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire AssnMem.\nRequire AssnState.\nRequire Import Hints.\nRequire Import Infrules.\n\n\nSet Implicit Arguments.\n\n\nSection Filter.\n  Definition filter\n             (preserved: Exprs.Tag.t * id -> bool)\n             (inv: AssnState.Unary.t): AssnState.Unary.t :=\n    AssnState.Unary.update_ghost\n      (filter_AL_atom (preserved <*> (pair Exprs.Tag.ghost)))\n      (AssnState.Unary.update_previous\n         (filter_AL_atom (preserved <*> (pair Exprs.Tag.previous)))\n         inv).\n\n  Lemma filter_subset_idT st_unary f id invst_unary val\n        (VAL_SUBSET: (AssnState.Unary.sem_idT st_unary (filter f invst_unary) id = Some val)):\n    <<VAL: (AssnState.Unary.sem_idT st_unary invst_unary id = Some val)>>.\n  Proof.\n    destruct id. destruct t; ss.\n    - eapply lookup_AL_filter_some. exact VAL_SUBSET.\n    - eapply lookup_AL_filter_some. exact VAL_SUBSET.\n  Qed.\n\n  Lemma filter_subset_valueT conf_unary st_unary f vt invst_unary val\n        (VAL_SUBSET: (AssnState.Unary.sem_valueT\n                        conf_unary st_unary\n                        (filter f invst_unary) vt = Some val)):\n    <<VAL: (AssnState.Unary.sem_valueT conf_unary st_unary invst_unary vt = Some val)>>.\n  Proof.\n    red. destruct vt; ss.\n    eapply filter_subset_idT; eauto.\n  Qed.\n\n  Lemma filter_subset_list_valueT conf_unary st_unary f vts invst_unary val\n        (VAL_SUBSET: (AssnState.Unary.sem_list_valueT\n                        conf_unary st_unary\n                        (filter f invst_unary) vts = Some val)):\n    <<VAL: (AssnState.Unary.sem_list_valueT conf_unary st_unary invst_unary vts = Some val)>>.\n  Proof.\n    red. revert val VAL_SUBSET. induction vts; i; ss. destruct a.\n    Ltac exploit_with H x :=\n      (exploit H; [exact x|]; eauto; ii; des).\n    des_ifs; ss;\n      (all_once exploit_with filter_subset_valueT);\n      (exploit IHvts; eauto; i); clarify.\n  Qed.\n\n  Lemma filter_subset_expr conf_unary st_unary f expr invst_unary val\n        (VAL_SUBSET: (AssnState.Unary.sem_expr\n                        conf_unary st_unary\n                        (filter f invst_unary) expr = Some val)):\n    <<VAL: (AssnState.Unary.sem_expr conf_unary st_unary invst_unary expr = Some val)>>.\n  Proof.\n    red.\n    Ltac exploit_filter_subset_with x :=\n      match (type of x) with\n      | (AssnState.Unary.sem_valueT _ _ _ _ = Some _) =>\n        (exploit filter_subset_valueT; [exact x|]; eauto; ii; des)\n      | (AssnState.Unary.sem_list_valueT _ _ _ _ = Some _) =>\n        (exploit filter_subset_list_valueT; [exact x|]; eauto; ii; des)\n      end.\n    Time destruct expr; ss;\n      des_ifs; ss; (all_once exploit_filter_subset_with); clarify.\n  (* exploit_with: Finished transaction in 25.39 secs (25.194u,0.213s) (successful) *)\n  (* exploit_with_fast: Finished transaction in 7.575 secs (7.536u,0.044s) (successful) *)\n  Qed.\n\n  Lemma filter_preserved_valueT\n        conf_unary st_unary invst_unary vt val f\n        (VAL: AssnState.Unary.sem_valueT conf_unary st_unary invst_unary vt = Some val)\n        (PRESERVED: (sflib.is_true (List.forallb f (Exprs.ValueT.get_idTs vt)))):\n    <<VAL: AssnState.Unary.sem_valueT conf_unary st_unary (filter f invst_unary) vt = Some val>>.\n  Proof.\n    red. destruct vt; ss. repeat (des_bool; des).\n    unfold AssnState.Unary.sem_idT. destruct x. s.\n    destruct t; ss.\n    - rewrite lookup_AL_filter_spec in *. des_ifs.\n      unfold compose, Tag.t, Ords.id.t in *. rewrite PRESERVED in *. clarify.\n    - rewrite lookup_AL_filter_spec in *. des_ifs.\n      unfold compose, Tag.t, Ords.id.t in *. rewrite PRESERVED in *. clarify.\n  Qed.\n\n  Lemma filter_preserved_list_valueT\n        conf_unary st_unary invst_unary vts val f\n        (VAL: AssnState.Unary.sem_list_valueT conf_unary st_unary invst_unary vts = Some val)\n        (PRESERVED: sflib.is_true (List.forallb\n                                     (fun x => (List.forallb f (Exprs.ValueT.get_idTs x)))\n                                     (List.map snd vts))):\n    <<VAL: AssnState.Unary.sem_list_valueT conf_unary st_unary (filter f invst_unary) vts = Some val>>.\n  Proof.\n    revert val VAL PRESERVED. induction vts; i; ss.\n    destruct a. ss. repeat (des_bool; des).\n    des_ifs; ss.\n    - (exploit filter_preserved_valueT; [exact Heq1| |]; eauto; ii; des).\n      exploit IHvts; eauto; []; ii; des. clarify.\n    - (exploit filter_preserved_valueT; [exact Heq1| |]; eauto; ii; des).\n      exploit IHvts; eauto; []; ii; des. clarify.\n    - (exploit filter_preserved_valueT; [exact Heq0| |]; eauto; ii; des).\n      exploit IHvts; eauto; []; ii; des. clarify.\n  Qed.\n\n  Lemma filter_preserved_expr\n        conf_unary st_unary invst_unary expr val f\n        (VAL: AssnState.Unary.sem_expr conf_unary st_unary invst_unary expr = Some val)\n        (PRESERVED: List.forallb f (Exprs.Expr.get_idTs expr)):\n    <<VAL: AssnState.Unary.sem_expr conf_unary st_unary (filter f invst_unary) expr = Some val>>.\n  Proof.\n    red.\n    unfold Exprs.Expr.get_idTs in *.\n    eapply forallb_filter_map in PRESERVED. des.\n    unfold is_true in PRESERVED. (* des_bool should kill it!!!!!!! KILL ALL is_true *)\n\n    Ltac exploit_filter_preserved_with x :=\n      match (type of x) with\n      | (AssnState.Unary.sem_valueT _ _ (filter _ _) _ = _) => fail 1\n      | (AssnState.Unary.sem_list_valueT _ _ (filter _ _) _ = _) => fail 1\n      (* Above is REQUIRED in order to prevent inf loop *)\n      | (AssnState.Unary.sem_valueT _ _ _ _ = Some _) =>\n        (exploit filter_preserved_valueT; [exact x| |]; eauto; ii; des)\n      | (AssnState.Unary.sem_list_valueT _ _ _ _ = Some _) =>\n        (exploit filter_preserved_list_valueT; [exact x| |]; eauto; ii; des)\n      end.\n\n    Time destruct expr; ss;\n      repeat (des_bool; des); des_ifs; clarify;\n        (all_once exploit_filter_subset_with); clarify;\n          (all_once exploit_filter_preserved_with); clarify.\n  Qed.\n\n  Lemma In_map_incl {A} (f: Exprs.ExprPair.t -> list A) x xs\n        (IN: Exprs.ExprPairSet.In x xs):\n    <<IN: List.incl (f x) (List.concat (List.map f (Exprs.ExprPairSet.elements xs)))>>.\n  Proof.\n    rewrite ExprPairSetFacts.elements_iff in IN. induction IN; ss.\n    - subst. apply incl_appl. solve_leibniz. apply incl_refl.\n    - apply incl_appr. ss.\n  Qed.\n\n  Lemma filter_AL_atom_preserves_wf_lc\n        f mem lc\n        (WF_LOCAL : memory_props.MemProps.wf_lc mem lc)\n    : memory_props.MemProps.wf_lc mem (filter_AL_atom f lc).\n  Proof.\n    unfold memory_props.MemProps.wf_lc in *.\n    i. exploit WF_LOCAL; eauto.\n    eapply lookup_AL_filter_some; eauto.\n  Qed.\n\n  Lemma incl_implies_preserved\n        conf st invst0 expr val inv\n        (preserved: _ -> bool)\n        (PRESERVED: forall id (ID: In id (Assertion.get_idTs_unary inv)), preserved id)\n        (VAL: AssnState.Unary.sem_expr conf st invst0 expr = Some val)\n        (INCL: incl (Exprs.Expr.get_idTs expr) (Assertion.get_idTs_unary inv)):\n    <<PRESERVED: AssnState.Unary.sem_expr conf st (filter preserved invst0) expr = Some val>>.\n  Proof.\n    eapply filter_preserved_expr; eauto. apply forallb_forall. i.\n    apply PRESERVED. apply INCL. ss.\n  Qed.\n\n  Lemma filter_spec\n        conf st invst assnmem inv gmax public\n        (preserved: _ -> bool)\n        (PRESERVED: forall id (ID: In id (Assertion.get_idTs_unary inv)), preserved id)\n        (STATE: AssnState.Unary.sem conf st invst assnmem gmax public inv):\n    AssnState.Unary.sem conf st (filter preserved invst) assnmem gmax public inv.\n  Proof.\n    inv STATE. econs; eauto.\n    - ii.\n      exploit filter_subset_expr; eauto. i. des.\n      exploit LESSDEF; eauto. i. des.\n      exploit incl_implies_preserved; eauto.\n      eapply incl_tran; [|eapply incl_tran]; swap 2 3.\n      + apply incl_appr. apply incl_refl.\n      + unfold Assertion.get_idTs_unary.\n        apply incl_appl. apply incl_refl.\n      + eapply In_map_incl in H. des. refine H.\n    - inv NOALIAS. econs; i.\n      + eapply DIFFBLOCK; eauto.\n        * eapply filter_subset_valueT; eauto.\n        * eapply filter_subset_valueT; eauto.\n      + eapply NOALIAS0; eauto.\n        * eapply filter_subset_valueT; eauto.\n        * eapply filter_subset_valueT; eauto.\n    - ii. exploit PRIVATE; eauto.\n      eapply filter_subset_idT; eauto.\n    - apply filter_AL_atom_preserves_wf_lc. eauto.\n    - apply filter_AL_atom_preserves_wf_lc. eauto.\n  Qed.\nEnd Filter.\n\n\n\nLemma reduce_maydiff_lessdef_sound\n      m_src m_tgt\n      conf_src st_src\n      conf_tgt st_tgt\n      invst assnmem inv\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst assnmem inv)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st_src.(Mem) st_tgt.(Mem) assnmem):\n  <<STATE: AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst assnmem\n                            (reduce_maydiff_lessdef inv)>>.\nProof.\n  inversion STATE. econs; eauto. ii.\n  ss. rewrite IdTSetFacts.filter_b in NOTIN; [|solve_compat_bool].\n  repeat (des_bool; des); ss; cycle 2.\n  { exploit MAYDIFF; eauto. } clear MAYDIFF.\n  apply ExprPairSetFacts.exists_iff in NOTIN; [|solve_compat_bool].\n  red in NOTIN; des.\n  apply ExprPairSetFacts.exists_iff in NOTIN0; [|solve_compat_bool].\n  red in NOTIN0; des.\n  apply AssnState.get_lhs_in_spec in NOTIN0.\n  apply AssnState.get_rhs_in_spec in NOTIN.\n  destruct x, x0. ss. des. subst.\n  rename id0 into idt.\n\n  (* src lessdef x, t0 --> t0's result exists *)\n  inv SRC. clear NOALIAS UNIQUE PRIVATE.\n  exploit LESSDEF; eauto; []; ii; des. clear LESSDEF.\n\n  (* inject_expr t0, t1 --> t1's result exists *)\n  exploit AssnState.Rel.inject_expr_spec; eauto; []; ii; des.\n\n  (* tgt t1, x --> x's result exists *)\n  inv TGT. clear NOALIAS UNIQUE PRIVATE.\n  exploit LESSDEF; eauto; []; ii; des. clear LESSDEF.\n\n  (* val_src >= val_a >= val_tgt >= val_b *)\n  esplits; eauto.\n  exploit GVs.inject_lessdef_compose; eauto; []; ii; des.\n  exploit GVs.lessdef_inject_compose; try exact x0; eauto.\nQed.\n\nLemma reduce_maydiff_preserved_sem_idT st_src st_tgt\n      invst inv id val_src val_tgt\n  (VAL_SRC: AssnState.Unary.sem_idT st_src\n              (filter (reduce_maydiff_preserved inv) (AssnState.Rel.src invst)) id =\n            Some val_src)\n  (VAL_TGT: AssnState.Unary.sem_idT st_tgt (AssnState.Rel.tgt invst) id = Some val_tgt):\n  <<VAL_TGT: AssnState.Unary.sem_idT st_tgt\n    (filter (reduce_maydiff_preserved inv) (AssnState.Rel.tgt invst)) id = Some val_tgt>>.\nProof.\n  destruct id. unfold Ords.id.t in *. rename t0 into id.\n  unfold AssnState.Unary.sem_idT in *. ss.\n  unfold AssnState.Unary.sem_tag in *. ss.\n  unfold compose in *.\n  destruct t; ss.\n  - rewrite <- VAL_TGT.\n    rewrite lookup_AL_filter_spec in *.\n    rewrite lookup_AL_filter_spec in VAL_SRC. (* WHY SHOULD I WRITE IT ONCE AGAIN?? *)\n    des_ifs.\n  - rewrite <- VAL_TGT.\n    rewrite lookup_AL_filter_spec in *.\n    rewrite lookup_AL_filter_spec in VAL_SRC. (* WHY SHOULD I WRITE IT ONCE AGAIN?? *)\n    des_ifs.\nQed.\n\nLemma reduce_maydiff_non_physical_sound\n      m_src m_tgt\n      conf_src st_src\n      conf_tgt st_tgt\n      invst0 assnmem inv\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst0 assnmem inv)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st_src.(Mem) st_tgt.(Mem) assnmem):\n  exists invst1,\n    <<STATE: AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst1 assnmem\n                              (reduce_maydiff_non_physical inv)>>.\nProof.\n  exists (AssnState.Rel.update_both (filter (reduce_maydiff_preserved\n                                         ((Assertion.get_idTs_unary inv.(Assertion.src))\n                                            ++ (Assertion.get_idTs_unary inv.(Assertion.tgt))))) invst0).\n  red.\n  inv STATE.\n  econs; ss; cycle 2.\n  - ii. ss.\n    rewrite IdTSetFacts.filter_b in NOTIN; [|solve_compat_bool].\n    des_bool. des.\n    + exploit MAYDIFF; eauto.\n      { exploit filter_subset_idT; eauto. }\n      i. des. esplits; eauto.\n      eapply reduce_maydiff_preserved_sem_idT; eauto.\n    + destruct id0. unfold Ords.id.t in *.\n      rename t into __t__, t0 into __i__.\n      unfold AssnState.Unary.sem_idT in VAL_SRC. ss.\n      unfold AssnState.Unary.sem_tag in VAL_SRC. ss.\n      unfold compose in *.\n      destruct __t__; inv NOTIN.\n      * rewrite lookup_AL_filter_spec in VAL_SRC.\n        unfold Tag.t in *. rewrite H0 in VAL_SRC. ss.\n      * rewrite lookup_AL_filter_spec in VAL_SRC.\n        unfold Tag.t in *. rewrite H0 in VAL_SRC. ss.\n  - apply filter_spec; ss. i.\n    unfold reduce_maydiff_preserved. apply orb_true_iff. right.\n    rewrite find_app.\n    match goal with\n    | [|- context[match ?g with | Some _ => _ | None => _ end]] =>\n      let COND := fresh \"COND\" in\n      destruct g eqn:COND\n    end; ss.\n    eapply find_none in COND; [|eauto].\n    destruct (IdT.eq_dec id0 id0); ss.\n  - apply filter_spec; ss. i.\n    unfold reduce_maydiff_preserved. apply orb_true_iff. right.\n    rewrite find_app.\n    match goal with\n    | [|- context[match ?g with | Some _ => _ | None => _ end]] =>\n      let COND := fresh \"COND\" in\n      destruct g eqn:COND\n    end; ss.\n    apply In_eq_find. ss.\nGrab Existential Variables.\n  { eauto. }\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SoundInfruleReduceMaydiff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.18248937999302084}}
{"text": "From Coq Require Import Arith ZArith Psatz Bool String List Program.Equality Streams.\nRequire Import Sequences IMP Compil MachDeterm.\nImport ListNotations.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope list_scope.\n\n(** We add nondeterministic interruption to the deterministic\n    semantics, obtaining the full semantics for the machine. *)\n\n(* States of the stack machine under full semantics. For simplicity,\nwe assume that interruption causes the program to step to a special\nIntr configuration in one step. *)\nInductive config : Type :=\n| OK: Determ.config -> config\n| Intr: config.\nNotation \"$( pc , stk , s , g )\" := (OK (pc, stk, s, g)).\n\n(* Operational semantics of the stack machine: either the machine\nsteps according to the deterministic semantics, or it is\ninterrupted. *)\nInductive transition (C: code): config -> option event -> config -> Prop :=\n| trans_determ : forall conf conf' eopt,\n    Determ.transition C conf eopt conf' ->\n    transition C (OK conf) eopt (OK conf')\n| trans_intr : forall conf,\n    transition C (OK conf) (Some ev_intr) Intr.  \n\nDefinition transitions (C: code): config -> list event -> config -> Prop :=\n  star (transition C).\n\n(** The machine terminates normally on an Ihalt instruction, emitting trace tr. *)\nDefinition machine_terminates_ok (C: code) (s_init: store) (g_init: global_state)\n           (tr: trace) (s_final: store) (g_final: global_state) : Prop :=\n  exists pc, transitions C $(0, nil, s_init, g_init) tr $(pc, nil, s_final, g_final)\n         /\\ instr_at C pc = Some Ihalt.\n\n(** The machine emits trace tr and is then interrupted. *)\nDefinition machine_intr (C: code) (s_init: store) (g_init: global_state)\n           (tr : trace): Prop :=\n  transitions C $(0, nil, s_init, g_init) tr Intr. \n\n(** The machine emits trace tr then diverges silently. *)\nDefinition machine_diverges_silently\n           (C: code) (s_init: store) (g_init: global_state) (tr: trace) : Prop :=\n  diverges_silently (transition C) $(0, nil, s_init, g_init) tr.\n\n(** The machine diverges with an infinte sequence of events itr. *)\nDefinition machine_diverges_with_inftrace (C: code) (s_init: store)\n           (g_init: global_state) (itr: inftrace) : Prop :=\n  infseq_with_inftrace (transition C) $(0, nil, s_init, g_init) itr.\n\n(** The machine gets \"stuck\": it reaches a state from which it cannot\nstep but whose current instruction is not Ihalt.  *)\nDefinition machine_goes_wrong (C: code) (s_init: store) (g_init: global_state)\n           (tr: trace) : Prop :=\n  exists pc stk s g,\n      transitions C $(0, nil, s_init, g_init) tr $(pc, stk, s, g)\n   /\\ irred (transition C) $(pc, stk, s, g)\n   /\\ (instr_at C pc <> Some Ihalt \\/ stk <> nil).\n\n(** The machine emits trace tr, then reaches a state from which no\nfurther steps are possible. *)\nDefinition machine_terminates (C: code) (s_init: store) (g_init: global_state)\n           (tr: trace) : Prop :=\n    exists config', transitions C $(0, nil, s_init, g_init) tr config'\n               /\\ irred (transition C) config'.\n\n(* If the machine terminates, it must have either terminated normally,\nbeen interrupted, or gotten stuck. *)\nLemma machine_terminates_ok_intr_or_wrong: forall C s g tr,\n    machine_terminates C s g tr ->\n    (exists s' g', machine_terminates_ok C s g tr s' g') \\/\n    (machine_intr C s g tr) \\/\n    (machine_goes_wrong C s g tr).\nProof.\n  intros. inversion H as (conf' & Htrans & Hirred); subst. \n  destruct conf'.\n  - destruct c as [[[pc' stk'] s'] g'].\n    destruct (instr_at C pc') eqn:E; try destruct i;\n      try (right; right; repeat eexists; eauto; left; congruence).\n    destruct stk'.\n    + left. repeat eexists; eauto.\n    + right; right; repeat eexists; eauto; right; congruence. \n  - right; left. now unfold machine_intr. \nQed.\n\nLemma no_trans_from_intr : forall C eopt config,\n    ~(transition C Intr eopt config).\nProof.\n  intuition; inversion H.\nQed.\n\nLemma intr_irred : forall C,\n    irred (transition C) Intr.\nProof.\n  unfold irred. auto using no_trans_from_intr.\nQed.\n\n\n(** Proof of modified backward simulation between machine under\ndeterministic semantics and machine under full semantics. We show that\nif the machine admits trace tr under full semantics, then either it\nadmits trace tr under deterministic semantics, or tr is a prefix of\nsome tr' followed by interruption and the machine admits tr' under\ndeterministic semantics. *)\n\n(* Some helper lemmas *)\nLemma determ_implies_full_one: forall C conf eopt conf',\n    Determ.transition C conf eopt conf' ->\n    transition C (OK conf) eopt (OK conf').\nProof.\n  econstructor; eauto. \nQed.\n\nLemma determ_implies_full: forall C conf tr conf',\n    Determ.transitions C conf tr conf' ->\n    transitions C (OK conf) tr (OK conf').\nProof.\n  induction 1.\n  - econstructor.\n  - econstructor; eauto using transition.\n  - eapply star_step_ev; eauto using transition.\nQed.\n\nLemma full_OK_implies_determ_one: forall C conf eopt conf',\n    transition C (OK conf) eopt (OK conf') ->\n    Determ.transition C conf eopt conf'.\nProof.\n  inversion 1; subst; trivial.\nQed.\n\nLemma full_OK_implies_determ: forall C conf tr conf',\n    transitions C (OK conf) tr (OK conf') ->\n    Determ.transitions C conf tr conf'.\nProof.\n  intros until 1; dependent induction H. \n  - econstructor.\n  - destruct b.\n    + specialize (IHstar c conf').\n      apply star_step with (b := c).\n      now apply full_OK_implies_determ_one.\n      now apply IHstar.\n    + inversion H.\n  - destruct b.\n    + specialize (IHstar c conf').\n      apply star_step_ev with (b := c).\n      now apply full_OK_implies_determ_one.\n      now apply IHstar.\n    + exfalso. inversion H0; subst; inversion H1.\nQed.\n\nLemma full_OK_implies_determ_plus: forall C conf tr conf',\n    plus (transition C) (OK conf) tr (OK conf') ->\n    plus (Determ.transition C) conf tr conf'.\nProof.\n  intros. inversion H. \n  - destruct b.\n    + apply plus_left with (b := c0).\n      now apply full_OK_implies_determ_one.\n      now apply full_OK_implies_determ. \n    + inversion H1; inversion H5. \n - destruct b.\n    + apply plus_left_ev with (b := c0).\n      now apply full_OK_implies_determ_one.\n      now apply full_OK_implies_determ. \n    + inversion H1; inversion H5.\nQed.\n\nLemma irred_implies_determ_irred: forall C conf,\n    irred (transition C) (OK conf) -> irred (Determ.transition C) conf. \nProof.\n  intros.\n  unfold irred in *. intros.\n  specialize (H (OK b) eo). intuition.\n  apply H. now apply determ_implies_full_one. \nQed. \n\nDefinition wrong_implies_determ_wrong: forall C s g tr,\n    machine_goes_wrong C s g tr ->\n    Determ.machine_goes_wrong C s g tr.\nProof.\n  intros. unfold machine_goes_wrong in H. unfold Determ.machine_goes_wrong. \n  destruct H as (pc' & stk' & s' & g' & Htrans & Hirred & Hinsstk).\n  exists pc', stk', s', g'. \n  repeat split.\n  - now apply full_OK_implies_determ.\n  - now apply irred_implies_determ_irred.\n  - easy.\nQed. \n\nLocal Hint Constructors step Determ.transition transition star plus : code.\nLocal Hint Unfold imp_terminates imp_diverges_silently imp_diverges_with_inftrace\n      Determ.machine_terminates Determ.machine_diverges_silently Determ.machine_diverges_with_inftrace\n      Determ.transitions machine_terminates machine_diverges_silently machine_diverges_with_inftrace transitions : code.\nLocal Hint Resolve full_OK_implies_determ wrong_implies_determ_wrong irred_implies_determ_irred : code.\n\nLemma full_Intr_implies_prefix_OK: forall C conf tr,\n    transitions C (OK conf) tr Intr ->\n    exists conf' tr', transitions C (OK conf) tr' (OK conf') /\\\n                 transition C (OK conf') (Some ev_intr) Intr /\\\n                 tr = tr' ++ [ev_intr].\nProof.\n  intros until 1; dependent induction H; intros.\n  - destruct b.\n    + assert (OK c = OK c) by congruence. assert (Intr = Intr) by congruence.\n      specialize (IHstar c H1 H2).\n      destruct IHstar as (conf' & tr' & Hok & Hintr & Ht).\n      exists conf', tr'. split; eauto 10. econstructor; eauto.\n    + inversion H.\n  - destruct b.\n    + assert (OK c = OK c) by congruence. assert (Intr = Intr) by congruence.\n      specialize (IHstar c H1 H2).\n      destruct IHstar as (conf' & tr' & Hok & Hintr & Ht).\n      exists conf', (e :: tr'). repeat split; eauto 10. eapply star_step_ev; eauto.\n      rewrite Ht. now apply app_comm_cons.\n    + inversion H; subst.\n      exists conf, []. repeat split. econstructor. eauto.\n      cbn. inversion H0; subst; auto; inversion H1. \nQed.\n\n(** Modified backward simulation between deterministic and full\nsemantics, for all three valid behaviors. *)\nTheorem prefix_correct_full_to_determ_semantics: forall C s g tr,\n    machine_terminates C s g tr ->\n    (exists s' g', Determ.machine_terminates C s g tr s' g')\n    \\/ (exists m, tr = m ++ [ev_intr] /\\ Determ.machine_admits_finite C s g m)\n    \\/ (Determ.machine_goes_wrong C s g tr).\nProof.\n  intros.\n  apply machine_terminates_ok_intr_or_wrong in H. destruct H; [ | destruct H ].\n  - left. destruct H as (s' & g' & H). exists s', g'.\n    unfold machine_terminates_ok in H. unfold Determ.machine_terminates.\n    destruct H as (pc & Htrans & Hinstr).\n    exists pc; split; eauto using full_OK_implies_determ. \n  - right; left. unfold machine_intr in H.\n    apply full_Intr_implies_prefix_OK in H.\n    destruct H as (conf' & tr' & Hok & Hintr & Htr). exists tr'; split; auto.\n    unfold Determ.machine_admits_finite. exists conf'.\n    eauto using full_OK_implies_determ.     \n  - right; right; auto using wrong_implies_determ_wrong.\nQed.\n\nLemma divergence_implies_determ_divergence_silent: forall C s g tr,\n    machine_diverges_silently C s g tr ->\n    Determ.machine_diverges_silently C s g tr.\nProof.  \n  unfold Determ.machine_diverges_silently, machine_diverges_silently, diverges_silently. intros. \n  destruct H as (b & Hstar & Hinf). destruct b.\n  - exists c. split. now apply full_OK_implies_determ.\n    assert (forall C c, infseq_silent (transition C) (OK c) -> infseq_silent (Determ.transition C) c). {\n      clear. cofix CIH; intros.\n      inversion H; subst. destruct b; inversion H0; subst.\n      econstructor; eauto.\n    }\n    eauto.\n  - inversion Hinf. inversion H.\nQed. \n\nLemma divergence_implies_determ_divergence_inftrace: forall C s g itr,\n    machine_diverges_with_inftrace C s g itr ->\n    Determ.machine_diverges_with_inftrace C s g itr.\nProof.  \n  unfold machine_diverges_with_inftrace, Determ.machine_diverges_with_inftrace. intros.\n  apply infseq_with_inftrace_coinduction_principle with\n      (X := fun conf tr => infseq_with_inftrace (transition C) (OK conf) tr); auto.\n  intros. inversion H0; subst.\n  destruct b.\n  - exists c, t0, it. repeat split; auto using full_OK_implies_determ_plus.\n  - inversion H3; subst. inversion H4; subst; inversion H7. \nQed. \n\n\n(** Top-level compiler correctness theorems for all three types of behavior. *)\nTheorem compile_program_correct_terminating: forall c s g tr,\n    machine_terminates (compile_program c) s g tr ->\n    (exists s' g', imp_terminates c s g tr s' g')\n    \\/ (exists m, tr = m ++ [ev_intr] /\\ imp_admits_finite c s g m).\nProof.\n  intros.\n  apply prefix_correct_full_to_determ_semantics in H. destruct H; [ | destruct H ].\n  - left. destruct H as (s' & g' & Hdet). exists s', g'.\n    now apply Determ.compile_program_correct_terminating_backward. \n  - right. destruct H as (m & Htr & Hdet). exists m; split; auto.\n    unfold Determ.machine_admits_finite in Hdet. destruct Hdet as (machconf2 & Hdet).    \n    apply Determ.compile_program_correct_admits_finite in Hdet. \n    destruct Hdet as (impconf2 & Hstep).\n    unfold imp_admits_finite. eauto. \n  - now apply Determ.compile_program_never_goes_wrong in H. \nQed. \n\nTheorem compile_program_correct_diverging_silently: forall c s g tr,\n    machine_diverges_silently (compile_program c) s g tr ->\n    imp_diverges_silently c s g tr. \nProof.\n  intros.\n  apply Determ.compile_program_correct_diverging_silently_backward. \n  now apply divergence_implies_determ_divergence_silent. \nQed. \n\nTheorem compile_program_correct_diverging_with_inftrace: forall c s g itr itr',\n    machine_diverges_with_inftrace (compile_program c) s g itr ->\n    imp_diverges_with_inftrace c s g itr' -> EqSt itr itr'.  \nProof.\n  intros.\n  eapply Determ.compile_program_correct_diverging_with_inftrace_backward.\n  eapply divergence_implies_determ_divergence_inftrace; eauto.\n  eauto.\nQed. \n", "meta": {"author": "pratapsingh1729", "repo": "adapting-verified-compilation", "sha": "29f96eaf5db458662d2fab3ae6b112d094b80af8", "save_path": "github-repos/coq/pratapsingh1729-adapting-verified-compilation", "path": "github-repos/coq/pratapsingh1729-adapting-verified-compilation/adapting-verified-compilation-29f96eaf5db458662d2fab3ae6b112d094b80af8/coq/MachFull.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.182489376508854}}
{"text": "(* \n * \u00a9 2019 XXX.\n * \n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List.\n\nFrom SPICY Require Import\n     MyPrelude\n     AdversaryUniverse\n     ChMaps\n     Messages\n     Maps\n     Keys\n     Tactics\n     IdealWorld\n     RealWorld\n.\n\nImport RealWorld.RealWorldNotations.\nImport IdealWorld.IdealNotations.\n\nFixpoint content_eq {t__rw t__iw}\n         (m__rw : RealWorld.message.message t__rw)\n         (m__iw : IdealWorld.message.message t__iw) gks : Prop :=\n  match (m__rw, m__iw) with\n  | (RealWorld.message.Content c__rw, IdealWorld.message.Content c__iw) => c__rw = c__iw\n  | (RealWorld.message.Permission (id, pk) , IdealWorld.message.Permission (IdealWorld.construct_access a _)) =>\n    match (gks $? id) with\n    | Some (Keys.MkCryptoKey _ _ Keys.SymKey) => a = (IdealWorld.construct_permission true true)\n    | Some (Keys.MkCryptoKey id Keys.Signing Keys.AsymKey) => a = (IdealWorld.construct_permission true pk)\n    | Some (Keys.MkCryptoKey id Keys.Encryption Keys.AsymKey) => a = (IdealWorld.construct_permission pk true)\n    | _ => False\n    end\n  | (RealWorld.message.MsgPair m__rw1 m__rw2, IdealWorld.message.MsgPair m__iw1 m__iw2) =>\n    content_eq m__rw1 m__iw1 gks /\\ content_eq m__rw2 m__iw2 gks\n  | _ => False\n  end.\n\nDefinition resolve_perm (ps : IdealWorld.permissions) id :=\n  match id with\n  | ChMaps.Single ch => ps $? ch\n  | ChMaps.Intersection ch1 ch2 =>\n    match (ps $? ch1, ps $? ch2) with\n    | (Some p1, Some p2) => Some (IdealWorld.perm_intersection p1 p2)\n    | _ => None\n    end\n  end.\n\nDefinition not_replayed (cs : RealWorld.ciphers) (honestk : key_perms)\n           (uid : user_id) (froms : RealWorld.recv_nonces) {t} (msg : RealWorld.crypto t) :=\n  RealWorld.msg_honestly_signed honestk cs msg\n  && RealWorld.msg_to_this_user cs (Some uid) msg\n  && match msg_nonce_ok cs froms msg with\n     | Some f => true\n     | None   => false\n     end.\n\nDefinition key_perms_from_known_ciphers (cs : RealWorld.ciphers) (mycs : RealWorld.my_ciphers) (ks0 : key_perms) :=\n  fold_left (fun kys cid => match cs $? cid with\n                         | Some (RealWorld.SigCipher _ _ _ m) => kys $k++ RealWorld.findKeysMessage m\n                         | Some (RealWorld.SigEncCipher _ _ _ _ m) => kys $k++ RealWorld.findKeysMessage m\n                         | None => kys\n                         end) mycs ks0.\n\nDefinition key_perms_from_message_queue (cs : RealWorld.ciphers) (honestk: key_perms)\n           (msgs : RealWorld.queued_messages) (uid : user_id) (froms : RealWorld.recv_nonces) (ks0 : key_perms) :=\n  let cmsgs := clean_messages honestk cs (Some uid) froms msgs\n  in  fold_left (fun kys '(existT _ _ m) => kys $k++ RealWorld.findKeysCrypto cs m) cmsgs ks0.\n\nInductive compat_perm : option bool -> bool -> Prop :=\n| CompatEq :\n    compat_perm (Some false) false\n| CompatNone :\n    compat_perm None false\n| CompatTrue : forall sp,\n    compat_perm sp true.\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/MessageEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.18231696626465188}}
{"text": "Require Import Coq.ZArith.BinInt.\nRequire Import Coq.Strings.String.\nRequire Import riscv.Utility.Monads. Import OStateOperations.\nRequire Import riscv.Utility.MonadNotations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Platform.Memory. (* should go before Program because both define loadByte etc *)\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Spec.Execute.\nRequire Import riscv.Utility.PowerFunc.\nRequire Import riscv.Utility.Utility.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import riscv.Platform.Minimal.\nRequire Import coqutil.Map.Interface.\n\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 Register word}.\n\n  Local Notation empty_mem := (map.empty: Mem).\n\n  Definition mkLogItemLoad(addr: word)(value: w32): LogItem :=\n    ((empty_mem, \"loadWord\"%string, [addr]), (empty_mem, [int32ToReg value])).\n\n  Definition mkLogItemStore(addr: word)(value: w32): LogItem :=\n    ((empty_mem, \"storeWord\"%string, [addr; int32ToReg value]), (empty_mem, [])).\n\n  Instance IsRiscvMachineL: RiscvProgram (OState RiscvMachine) word := {\n      getRegister := getRegister;\n      setRegister := setRegister;\n      getPC := getPC;\n      setPC := setPC;\n      loadByte   := loadByte;\n      loadHalf   := loadHalf;\n      loadWord kind a :=\n        Bind get\n             (fun m =>\n                Bind (Monad := (OState_Monad _)) (* why does Coq infer OStateND_Monad?? *)\n                     (loadWord kind a)\n                     (fun res =>\n                        Bind (Monad := (OState_Monad _)) (* why does Coq infer OStateND_Monad?? *)\n                             (put (withLogItem (mkLogItemLoad a res) m))\n                             (fun _ => Return res)));\n(*\n        m <- get;\n        res <- (loadWord kind a);\n        put (withLogItem (mkLogItemLoad a res));;\n        Return res;\n*)\n\n      loadDouble := loadDouble;\n      storeByte   := storeByte;\n      storeHalf   := storeHalf;\n\n      storeWord kind a v :=\n        Bind get\n             (fun m =>\n                Bind (Monad := (OState_Monad _)) (* why does Coq infer OStateND_Monad?? *)\n                     (put (withLogItem (mkLogItemStore a v) m))\n                     (fun (_: unit) =>\n                        storeWord kind a v));\n\n      storeDouble := storeDouble;\n      makeReservation := makeReservation;\n      clearReservation := clearReservation;\n      checkReservation := checkReservation;\n      getCSRField := getCSRField;\n      setCSRField := setCSRField;\n      getPrivMode := getPrivMode;\n      setPrivMode := setPrivMode;\n      fence := fence;\n\n      endCycleNormal := endCycleNormal;\n      endCycleEarly{A} := @endCycleEarly _ _ _ _ _ A;\n  }.\n\nEnd Riscv.\n\n#[global] Existing Instance IsRiscvMachineL. (* needed because it was defined inside a Section *)\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/MinimalLogging.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.18227753049014572}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nFrom compcert Require Import Maps Linking.\n\nRequire Import sflib.\nRequire Import StdlibExt.\n\nRequire Import NWSysModel.\nRequire Import RTSysEnv.\nRequire main_prm config_prm.\nRequire Import LinkLemmas.\n\nSet Nested Proofs Allowed.\n\nLocal Open Scope Z_scope.\n\nLocal Opaque Z.of_nat Byte.unsigned nth.\n(* main_p.ip_init_data *)\n\nLocal Transparent Linker_program Linker_prog Linker_def Linker_fundef Linker_varinit Ctypes.Linker_fundef Linker_vardef Linker_types.\nLocal Transparent external_function_eq calling_convention_eq signature_eq typ_eq rettype_eq.\n\nLocal Opaque in_dec zeq.\n\n\nLemma link_v_IP_ADDR\n      nt nmc ip_bs\n  : link_vardef (main_prm.v_IP_ADDR nt nmc)\n                (config_prm.v_IP_ADDR nt nmc ip_bs) =\n    Some (config_prm.v_IP_ADDR nt nmc ip_bs).\nProof.\n  unfold main_prm.v_IP_ADDR, config_prm.v_IP_ADDR.\n  unfold link_vardef. ss.\n  destruct (zeq (nt + nmc) (nt + nmc)); ss.\nQed.\n\nLemma link_v_MCAST_MEMBER\n      mnt mnmc mfs\n  : link_vardef (main_prm.v_MCAST_MEMBER mnt mnmc)\n                (config_prm.v_MCAST_MEMBER mnt mnmc mfs) =\n    Some (config_prm.v_MCAST_MEMBER mnt mnmc mfs).\nProof.\n  unfold main_prm.v_MCAST_MEMBER, config_prm.v_MCAST_MEMBER.\n  simpl.\n  unfold link_vardef. ss.\n  destruct (zeq mnmc mnmc); ss.\n  destruct (zeq mnt mnt); ss.\nQed.\n\n\nSection PROGRAMS_OF_SYSTEM.\n\n  Context `{SystemEnv}.\n\n  Definition main_prog: Clight.program :=\n    main_prm.prog (Z.of_nat msg_size_k)\n                  (Z.of_nat max_num_tasks)\n                  (Z.of_nat max_num_mcasts).\n\n  Definition config_prog: Clight.program :=\n    config_prm.prog\n      (Z.of_nat max_num_tasks) (Z.of_nat max_num_mcasts)\n      (Z.of_nat period) (Z.of_nat max_clock_skew) (Z.of_nat max_nw_delay)\n      (Z.of_nat num_tasks) (Z.of_nat num_mcasts) (Z.of_nat msg_size)\n      (Z.of_nat port) dest_ips_brep mcast_memflags.\n\n  Lemma main_config_link_check_ok\n        dm1 dm2\n        (DM1: dm1 = prog_defmap main_prog)\n        (DM2: dm2 = prog_defmap config_prog)\n    : PTree_Properties.for_all\n        dm1 (link_prog_check main_prog config_prog) = true.\n  Proof.\n    apply PTree_Properties.for_all_correct.\n    intros id gd SOME.\n    rewrite DM1 in SOME.\n    unfold prog_defmap in SOME. ss.\n    apply PTree_Properties.in_of_list in SOME. ss.\n    des; clarify.\n    - unfold link_prog_check.\n      unfold prog_defmap. ss.\n\n      assert (IN_PUB1: In main_prm._IP_ADDR\n                          main_prm.public_idents).\n      { unfold main_prm.public_idents. ss.\n        repeat match goal with\n               | |- ?a = ?b \\/ _ =>\n                 match a with\n                 | b => left\n                 | _ => right\n                 end\n               end.\n        reflexivity. }\n\n      assert (IN_PUB2: In main_prm._IP_ADDR\n                          config_prm.public_idents).\n      { unfold config_prm.public_idents. ss.\n        repeat match goal with\n               | |- ?a = ?b \\/ _ =>\n                 match a with\n                 | config_prm._IP_ADDR => left\n                 | _ => right\n                 end\n               end.\n        reflexivity. }\n      desf.\n\n      rewrite link_v_IP_ADDR in *.\n      congruence.\n    - unfold link_prog_check.\n      unfold prog_defmap. ss.\n\n      assert (IN_PUB1: In main_prm._MCAST_MEMBER\n                          main_prm.public_idents).\n      { unfold main_prm.public_idents. ss.\n        repeat match goal with\n               | |- ?a = ?b \\/ _ =>\n                 match a with\n                 | b => left\n                 | _ => right\n                 end\n               end.\n        reflexivity. }\n\n      assert (IN_PUB2: In main_prm._MCAST_MEMBER\n                          config_prm.public_idents).\n      { unfold config_prm.public_idents. ss.\n        repeat match goal with\n               | |- ?a = ?b \\/ _ =>\n                 match a with\n                 | config_prm._MCAST_MEMBER => left\n                 | _ => right\n                 end\n               end.\n        reflexivity. }\n      desf.\n\n      rewrite link_v_MCAST_MEMBER in *.\n      congruence.\n  Qed.\n\n  (* Set Debug Cbv. *)\n  (* Local Opaque Bool.bool_dec eq_ind eq_ind_r. *)\n  (* Local Opaque link_prog_merge. *)\n\n  Definition mw_AST_prog: AST.program Clight.fundef type :=\n    let p1 := main_prog in\n    let p2 := config_prog in\n    let dm1 := prog_defmap p1 in\n    let dm2 := prog_defmap p2 in\n    {|\n    AST.prog_defs := PTree.elements (PTree.combine link_prog_merge dm1 dm2);\n    AST.prog_public := AST.prog_public p1 ++ AST.prog_public p2;\n    AST.prog_main := AST.prog_main p1 |}.\n\n  Lemma mw_AST_prog_linked\n    : link_prog main_prog config_prog = Some mw_AST_prog.\n  Proof.\n    unfold link_prog.\n    erewrite main_config_link_check_ok; eauto.\n  Qed.\n\n  Arguments Z.mul: simpl nomatch.\n\n  Definition prog_mw_types : list composite_definition.\n  Proof.\n    let k := eval cbn in (link_composite_defs\n                            (prog_types main_prog)\n                            (prog_types config_prog)) in\n        match k with\n        | Some ?a => exact a\n        end.\n  Defined.\n\n  Lemma prog_mw_types_linked\n    : link_composite_defs (prog_types main_prog)\n                          (prog_types config_prog) =\n      Some prog_mw_types.\n  Proof. ss. Qed.\n\n  Definition prog_mw: Clight.program :=\n    let p1 := main_prog in\n    let p2 := config_prog in\n    mkprogram prog_mw_types\n              (PTree.elements (PTree.combine link_prog_merge (prog_defmap p1) (prog_defmap p2)))\n              (AST.prog_public p1 ++ AST.prog_public p2)\n              (AST.prog_main p1)\n              I\n  .\n\n  Lemma prog_mw_linked\n    : link_program main_prog config_prog = Some prog_mw.\n  Proof.\n    apply link_program_eq; ss.\n    apply mw_AST_prog_linked.\n  Qed.\n\nEnd PROGRAMS_OF_SYSTEM.\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_impl/SystemProgs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3073580168652638, "lm_q1q2_score": 0.1821608352468375}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for code linearization *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Ordered.\nRequire Import FSets.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Errors.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import LTLtyping.\nRequire Import LTLin.\nRequire Import Linearize.\nRequire Import Lattice.\n\nModule NodesetFacts := FSetFacts.Facts(Nodeset).\n\nSection LINEARIZATION.\n\nContext `{Hcc: CompilerConfiguration}.\nVariable prog: LTL.program.\nVariable tprog: LTLin.program.\n\nHypothesis TRANSF: transf_program prog = OK tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma functions_translated:\n  forall v f,\n  Genv.find_funct ge v = Some f ->\n  exists tf,\n  Genv.find_funct tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_transf_partial transf_fundef _ TRANSF).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial transf_fundef _ TRANSF).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (Genv.find_symbol_transf_partial transf_fundef _ TRANSF).\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof (Genv.find_var_info_transf_partial transf_fundef _ TRANSF).\n\nLemma sig_preserved:\n  forall f tf,\n  transf_fundef f = OK tf ->\n  LTLin.funsig tf = LTL.funsig f.\nProof.\n  unfold transf_fundef, transf_partial_fundef; intros.\n  destruct f. monadInv H. monadInv EQ. reflexivity.\n  inv H. reflexivity.\nQed.\n\nLemma stacksize_preserved:\n  forall f tf,\n  transf_function f = OK tf ->\n  LTLin.fn_stacksize tf = LTL.fn_stacksize f.\nProof.\n  intros. monadInv H. auto.\nQed.\n\nLemma find_function_translated:\n  forall ros ls f,\n  LTL.find_function ge ros ls = Some f ->\n  exists tf,\n  find_function tge ros ls = Some tf /\\ transf_fundef f = OK tf.\nProof.\n  unfold LTL.find_function; intros; destruct ros; simpl.\n  apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n\n(** * Correctness of reachability analysis *)\n\n(** The entry point of the function is reachable. *)\n\nLemma reachable_entrypoint:\n  forall f, (reachable f)!!(f.(fn_entrypoint)) = true.\nProof.\n  intros. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux; intros reach A.\n  assert (LBoolean.ge reach!!(f.(fn_entrypoint)) true).\n  eapply DS.fixpoint_entry. eexact A. auto with coqlib.\n  unfold LBoolean.ge in H. tauto.\n  intros. apply PMap.gi.\nQed.\n\n(** The successors of a reachable instruction are reachable. *)\n\nLemma reachable_successors:\n  forall f pc pc' i,\n  f.(LTL.fn_code)!pc = Some i -> In pc' (successors_instr i) ->\n  (reachable f)!!pc = true ->\n  (reachable f)!!pc' = true.\nProof.\n  intro f. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux. intro reach; intros.\n  assert (LBoolean.ge reach!!pc' reach!!pc).\n  change (reach!!pc) with ((fun pc r => r) pc (reach!!pc)).\n  eapply DS.fixpoint_solution. eexact H.\n  unfold Kildall.successors_list, successors. rewrite PTree.gmap1.\n  rewrite H0; auto.\n  elim H3; intro. congruence. auto.\n  intros. apply PMap.gi.\nQed.\n\n(** * Properties of node enumeration *)\n\n(** An enumeration of CFG nodes is correct if the following conditions hold:\n- All nodes for reachable basic blocks must be in the list.\n- The list is without repetition (so that no code duplication occurs).\n\nWe prove that the result of the [enumerate] function satisfies both\nconditions. *)\n\nLemma nodeset_of_list_correct:\n  forall l s s',\n  nodeset_of_list l s = OK s' ->\n  list_norepet l\n  /\\ (forall pc, Nodeset.In pc s' <-> Nodeset.In pc s \\/ In pc l)\n  /\\ (forall pc, In pc l -> ~Nodeset.In pc s).\nProof.\n  induction l; simpl; intros. \n  inv H. split. constructor. split. intro; tauto. intros; tauto.\n  generalize H; clear H; caseEq (Nodeset.mem a s); intros.\n  inv H0.\n  exploit IHl; eauto. intros [A [B C]].\n  split. constructor; auto. red; intro. elim (C a H1). apply Nodeset.add_1. hnf. auto.\n  split. intros. rewrite B. rewrite NodesetFacts.add_iff. \n  unfold Nodeset.E.eq. unfold OrderedPositive.eq. tauto.\n  intros. destruct H1. subst pc. rewrite NodesetFacts.not_mem_iff. auto.\n  generalize (C pc H1). rewrite NodesetFacts.add_iff. tauto.\nQed.\n\nLemma check_reachable_correct:\n  forall f reach s pc i,\n  check_reachable f reach s = true ->\n  f.(LTL.fn_code)!pc = Some i ->\n  reach!!pc = true ->\n  Nodeset.In pc s.\nProof.\n  intros f reach s.\n  assert (forall l ok, \n    List.fold_left (fun a p => check_reachable_aux reach s a (fst p) (snd p)) l ok = true ->\n    ok = true /\\\n    (forall pc i,\n     In (pc, i) l ->\n     reach!!pc = true ->\n     Nodeset.In pc s)).\n  induction l; simpl; intros.\n  split. auto. intros. destruct H0.\n  destruct a as [pc1 i1]. simpl in H. \n  exploit IHl; eauto. intros [A B].\n  unfold check_reachable_aux in A. \n  split. destruct (reach!!pc1). elim (andb_prop _ _ A). auto. auto.\n  intros. destruct H0. inv H0. rewrite H1 in A. destruct (andb_prop _ _ A). \n  apply Nodeset.mem_2; auto.\n  eauto.\n\n  intros pc i. unfold check_reachable. rewrite PTree.fold_spec. intros.\n  exploit H; eauto. intros [A B]. eapply B; eauto. \n  apply PTree.elements_correct. eauto.\nQed.\n\nLemma enumerate_complete:\n  forall f enum pc i,\n  enumerate f = OK enum ->\n  f.(LTL.fn_code)!pc = Some i ->\n  (reachable f)!!pc = true ->\n  In pc enum.\nProof.\n  intros until i. unfold enumerate. \n  set (reach := reachable f).\n  intros. monadInv H. \n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit check_reachable_correct; eauto. intro.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]].\n  rewrite B in H2. destruct H2. elim (Nodeset.empty_1 H2). auto.\nQed.\n\nLemma enumerate_norepet:\n  forall f enum,\n  enumerate f = OK enum ->\n  list_norepet enum.\nProof.\n  intros until enum. unfold enumerate. \n  set (reach := reachable f).\n  intros. monadInv H. \n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]]. auto.\nQed.\n\n(** * Properties related to labels *)\n\n(** If labels are globally unique and the LTLin code [c] contains\n  a subsequence [Llabel lbl :: c1], then [find_label lbl c] returns [c1].\n*)\n\nFixpoint unique_labels (c: code) : Prop :=\n  match c with\n  | nil => True\n  | Llabel lbl :: c => ~(In (Llabel lbl) c) /\\ unique_labels c\n  | i :: c => unique_labels c\n  end.\n\nLemma find_label_unique:\n  forall lbl c1 c2 c3,\n  is_tail (Llabel lbl :: c1) c2 ->\n  unique_labels c2 ->\n  find_label lbl c2 = Some c3 ->\n  c1 = c3.\nProof.\n  induction c2.\n  simpl; intros; discriminate.\n  intros c3 TAIL UNIQ. simpl.\n  generalize (is_label_correct lbl a). case (is_label lbl a); intro ISLBL.\n  subst a. intro. inversion TAIL. congruence. \n  elim UNIQ; intros. elim H4. apply is_tail_in with c1; auto.\n  inversion TAIL. congruence. apply IHc2. auto. \n  destruct a; simpl in UNIQ; tauto.\nQed.\n\n(** Correctness of the [starts_with] test. *)\n\nLemma starts_with_correct:\n  forall lbl c1 c2 c3 s f sp ls m,\n  is_tail c1 c2 ->\n  unique_labels c2 ->\n  starts_with lbl c1 = true ->\n  find_label lbl c2 = Some c3 ->\n  plus step tge (State s f sp c1 ls m)\n             E0 (State s f sp c3 ls m).\nProof.\n  induction c1.\n  simpl; intros; discriminate.\n  simpl starts_with. destruct a; try (intros; discriminate).\n  intros. \n  apply plus_left with E0 (State s f sp c1 ls m) E0.\n  simpl. constructor. \n  simpl in H1;\n  destruct (peq lbl l).\n  subst l. replace c3 with c1. constructor.\n  apply find_label_unique with lbl c2; auto.\n  apply plus_star. \n  apply IHc1 with c2; auto. eapply is_tail_cons_left; eauto.\n  traceEq.\nQed.\n\n(** Connection between [find_label] and linearization. *)\n\nLemma find_label_add_branch:\n  forall lbl k s,\n  find_label lbl (add_branch s k) = find_label lbl k.\nProof.\n  intros. unfold add_branch. destruct (starts_with s k); auto.\nQed.\n\nLemma find_label_lin_instr:\n  forall lbl k b,\n  find_label lbl (linearize_instr b k) = find_label lbl k.\nProof.\n  intros lbl k. generalize (find_label_add_branch lbl k); intro.\n  induction b; simpl; auto.\n  case (starts_with n k); simpl; auto.\nQed.\n\nLemma find_label_lin_rec:\n  forall f enum pc b,\n  In pc enum ->\n  f.(LTL.fn_code)!pc = Some b ->\n  exists k, find_label pc (linearize_body f enum) = Some (linearize_instr b k).\nProof.\n  induction enum; intros.\n  elim H.\n  case (peq a pc); intro.\n  subst a. exists (linearize_body f enum).\n  simpl. rewrite H0. simpl. rewrite peq_true. auto.\n  assert (In pc enum). simpl in H. tauto.\n  elim (IHenum pc b H1 H0). intros k FIND.\n  exists k. simpl. destruct (LTL.fn_code f)!a. \n  simpl. rewrite peq_false. rewrite find_label_lin_instr. auto. auto.\n  auto.\nQed.\n\nLemma find_label_lin:\n  forall f tf pc b,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  exists k,\n  find_label pc (fn_code tf) = Some (linearize_instr b k).\nProof.\n  intros. monadInv H. simpl. \n  rewrite find_label_add_branch. apply find_label_lin_rec.\n  eapply enumerate_complete; eauto. auto.\nQed.\n\nLemma find_label_lin_inv:\n  forall f tf pc b k,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  find_label pc (fn_code tf) = Some k ->\n  exists k', k = linearize_instr b k'.\nProof.\n  intros. exploit find_label_lin; eauto. intros [k' FIND].\n  exists k'. congruence.\nQed.\n\nLemma find_label_lin_succ:\n  forall f tf s,\n  transf_function f = OK tf ->\n  valid_successor f s ->\n  (reachable f)!!s = true ->\n  exists k,\n  find_label s (fn_code tf) = Some k.\nProof.\n  intros. destruct H0 as [i AT]. \n  exploit find_label_lin; eauto. intros [k FIND].\n  exists (linearize_instr i k); auto.\nQed.\n\n(** Unique label property for linearized code. *)\n\nLemma label_in_add_branch:\n  forall lbl s k,\n  In (Llabel lbl) (add_branch s k) -> In (Llabel lbl) k.\nProof.\n  intros until k; unfold add_branch.\n  destruct (starts_with s k); simpl; intuition congruence.\nQed.\n\nLemma label_in_lin_instr:\n  forall lbl k b,\n  In (Llabel lbl) (linearize_instr b k) -> In (Llabel lbl) k.\nProof.\n  induction b; simpl; intros;\n  try (apply label_in_add_branch with n; intuition congruence);\n  try (intuition congruence).\n  destruct (starts_with n k); simpl in H.\n  apply label_in_add_branch with n; intuition congruence.\n  apply label_in_add_branch with n0; intuition congruence.\nQed.\n\nLemma label_in_lin_rec:\n  forall f lbl enum,\n  In (Llabel lbl) (linearize_body f enum) -> In lbl enum.\nProof.\n  induction enum.\n  simpl; auto.\n  simpl. destruct (LTL.fn_code f)!a. \n  simpl. intros [A|B]. left; congruence. \n  right. apply IHenum. eapply label_in_lin_instr; eauto.\n  intro; right; auto.\nQed.\n\nLemma unique_labels_add_branch:\n  forall lbl k,\n  unique_labels k -> unique_labels (add_branch lbl k).\nProof.\n  intros; unfold add_branch. \n  destruct (starts_with lbl k); simpl; intuition.\nQed.\n\nLemma unique_labels_lin_instr:\n  forall k b,\n  unique_labels k -> unique_labels (linearize_instr b k).\nProof.\n  induction b; intro; simpl; auto; try (apply unique_labels_add_branch; auto).\n  case (starts_with n k); simpl; apply unique_labels_add_branch; auto.\nQed.\n\nLemma unique_labels_lin_rec:\n  forall f enum,\n  list_norepet enum ->\n  unique_labels (linearize_body f enum).\nProof.\n  induction enum.\n  simpl; auto.\n  intro. simpl. destruct (LTL.fn_code f)!a. \n  simpl. split. red. intro. inversion H. elim H3.\n  apply label_in_lin_rec with f. \n  apply label_in_lin_instr with i. auto.\n  apply unique_labels_lin_instr. apply IHenum. inversion H; auto.\n  apply IHenum. inversion H; auto.\nQed.\n\nLemma unique_labels_transf_function:\n  forall f tf,\n  transf_function f = OK tf ->\n  unique_labels (fn_code tf).\nProof.\n  intros. monadInv H. simpl.\n  apply unique_labels_add_branch. \n  apply unique_labels_lin_rec. eapply enumerate_norepet; eauto.\nQed.\n\n(** Correctness of [add_branch]. *)\n\nLemma is_tail_find_label:\n  forall lbl c2 c1,\n  find_label lbl c1 = Some c2 -> is_tail c2 c1.\nProof.\n  induction c1; simpl.\n  intros; discriminate.\n  case (is_label lbl a). intro. injection H; intro. subst c2.\n  constructor. constructor.\n  intro. constructor. auto. \nQed.\n\nLemma is_tail_add_branch:\n  forall lbl c1 c2, is_tail (add_branch lbl c1) c2 -> is_tail c1 c2.\nProof.\n  intros until c2. unfold add_branch. destruct (starts_with lbl c1).\n  auto. eauto with coqlib.\nQed.\n\nLemma add_branch_correct:\n  forall lbl c k s f tf sp ls m,\n  transf_function f = OK tf ->\n  is_tail k tf.(fn_code) ->\n  find_label lbl tf.(fn_code) = Some c ->\n  plus step tge (State s tf sp (add_branch lbl k) ls m)\n             E0 (State s tf sp c ls m).\nProof.\n  intros. unfold add_branch.\n  caseEq (starts_with lbl k); intro SW.\n  eapply starts_with_correct; eauto.\n  eapply unique_labels_transf_function; eauto.\n  apply plus_one. apply exec_Lgoto. auto.\nQed.\n\n(** * Correctness of linearization *)\n\n(** The proof of semantic preservation is a simulation argument\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 invariant (horizontal lines above) is the [match_states]\n  predicate defined below.  It captures the fact that the flow\n  of data is the same in the source and linearized codes.\n  Moreover, whenever the source state is at node [pc] in its\n  control-flow graph, the transformed state is at a code\n  sequence [c] that starts with the label [pc]. *)\n\nInductive match_stackframes: LTL.stackframe -> LTLin.stackframe -> Prop :=\n  | match_stackframe_intro:\n      forall res f sp pc ls tf c,\n      transf_function f = OK tf ->\n      (reachable f)!!pc = true ->\n      valid_successor f pc ->\n      is_tail c (fn_code tf) ->\n      wt_function f ->\n      match_stackframes\n        (LTL.Stackframe res f sp ls pc)\n        (LTLin.Stackframe res tf sp ls (add_branch pc c)).\n\nInductive match_states: LTL.state -> LTLin.state -> Prop :=\n  | match_states_intro:\n      forall s f sp pc ls m tf ts c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (AT: find_label pc (fn_code tf) = Some c)\n        (WTF: wt_function f),\n      match_states (LTL.State s f sp pc ls m)\n                   (LTLin.State ts tf sp c ls m)\n  | match_states_call:\n      forall s f ls m tf ts,\n      list_forall2 match_stackframes s ts ->\n      transf_fundef f = OK tf ->\n      wt_fundef f ->\n      match_states (LTL.Callstate s f ls m)\n                   (LTLin.Callstate ts tf ls m)\n  | match_states_return:\n      forall s ls m ts,\n      list_forall2 match_stackframes s ts ->\n      match_states (LTL.Returnstate s ls m)\n                   (LTLin.Returnstate ts ls m).\n\nHypothesis wt_prog: wt_program prog.\n\nTheorem transf_step_correct:\n  forall s1 t s2, LTL.step ge s1 t s2 ->\n  forall s1' (MS: match_states s1 s1'),\n  exists s2', plus LTLin.step tge s1' t s2' /\\ match_states s2 s2'.\nProof.\n  induction 1; intros; try (inv MS);\n  try (generalize (wt_instrs _ WTF _ _ H); intro WTI).\n  (* Lnop *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  econstructor; split.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_find_label. eauto.\n  econstructor; eauto. \n  (* Lop *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  econstructor; split.\n  eapply plus_left'.\n  eapply @exec_Lop with (v := v); eauto.\n  rewrite <- H0. apply eval_operation_preserved. exact symbols_preserved.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n  (* Lload *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  econstructor; split.\n  eapply plus_left'.\n  apply exec_Lload with a.\n  rewrite <- H0. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n  (* Lstore *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  econstructor; split.\n  eapply plus_left'.\n  apply exec_Lstore with a. \n  rewrite <- H0. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n  (* Lcall *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  assert (VALID: valid_successor f pc'). inv WTI; auto.\n  exploit find_function_translated; eauto. intros [tf' [A B]].\n  econstructor; split.\n  apply plus_one. eapply @exec_Lcall with (f' := tf'); eauto.\n  symmetry; apply sig_preserved; auto.\n  econstructor; eauto.\n  constructor; auto. econstructor; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  destruct ros; simpl in H0.\n  eapply Genv.find_funct_prop; eauto.\n  destruct (Genv.find_symbol ge i); try discriminate.  \n  eapply Genv.find_funct_ptr_prop; eauto.\n\n  (* Ltailcall *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  exploit find_function_translated; eauto. intros [tf' [A B]].\n  econstructor; split.\n  apply plus_one. eapply @exec_Ltailcall with (f' := tf'); eauto.\n  symmetry; apply sig_preserved; auto.\n  rewrite (stacksize_preserved _ _ TRF). eauto.\n  econstructor; eauto.\n  destruct ros; simpl in H0.\n  eapply Genv.find_funct_prop; eauto.\n  destruct (Genv.find_symbol ge i); try discriminate.  \n  eapply Genv.find_funct_ptr_prop; eauto.\n\n  (* Lbuiltin *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  econstructor; split.\n  eapply plus_left'.\n  eapply exec_Lbuiltin. \n  eapply external_call_symbols_preserved; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n\n  (* Lcond *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  destruct b.\n  (* true *)\n  assert (REACH': (reachable f)!!ifso = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; eauto. intros [c'' AT'].\n  destruct (starts_with ifso c').\n  econstructor; split.\n  eapply plus_left'.  \n  eapply exec_Lcond_false; eauto.\n  rewrite eval_negate_condition; rewrite H0; auto.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n  econstructor; split.\n  apply plus_one. eapply exec_Lcond_true; eauto.\n  econstructor; eauto.\n  (* false *)\n  assert (REACH': (reachable f)!!ifnot = true).\n  eapply reachable_successors; eauto. simpl; auto.\n  exploit find_label_lin_succ; eauto. inv WTI; auto. intros [c'' AT'].\n  destruct (starts_with ifso c').\n  econstructor; split.\n  apply plus_one. eapply exec_Lcond_true; eauto.\n  rewrite eval_negate_condition; rewrite H0; auto.\n  econstructor; eauto.\n  econstructor; split.\n  eapply plus_left'. \n  eapply exec_Lcond_false; eauto.\n  eapply add_branch_correct; eauto.\n  eapply is_tail_add_branch. eapply is_tail_cons_left. \n  eapply is_tail_find_label. eauto.\n  traceEq.\n  econstructor; eauto.\n\n  (* Ljumptable *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  assert (REACH': (reachable f)!!pc' = true).\n  eapply reachable_successors; eauto. simpl. eapply list_nth_z_in; eauto.\n  exploit find_label_lin_succ; eauto.\n  inv WTI. apply H6. eapply list_nth_z_in; eauto. \n  intros [c'' AT'].\n  econstructor; split.\n  apply plus_one. eapply exec_Ljumptable; eauto. \n  econstructor; eauto.\n\n  (* Lreturn *)\n  destruct (find_label_lin_inv _ _ _ _ _ TRF H REACH AT) as [c' EQ].\n  simpl in EQ. subst c.\n  econstructor; split.\n  apply plus_one. eapply exec_Lreturn; eauto.\n  rewrite (stacksize_preserved _ _ TRF). eauto.\n  econstructor; eauto.\n \n  (* internal function *)\n  assert (REACH: (reachable f)!!(LTL.fn_entrypoint f) = true).\n    apply reachable_entrypoint.\n  inv H7. monadInv H6.   \n  exploit find_label_lin_succ; eauto. inv H1; auto. intros [c'' AT'].\n  generalize EQ; intro. monadInv EQ0. econstructor; simpl; split.\n  eapply plus_left'.  \n  eapply exec_function_internal; eauto.\n  simpl. eapply add_branch_correct. eauto.  \n  simpl. eapply is_tail_add_branch. constructor. eauto.\n  traceEq.\n  econstructor; eauto.\n\n  (* external function *)\n  monadInv H6. econstructor; split.\n  apply plus_one. eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto.\n  exact symbols_preserved. exact varinfo_preserved.\n  econstructor; eauto.\n\n  (* return *)\n  inv H3. inv H1.\n  exploit find_label_lin_succ; eauto. intros [c' AT].\n  econstructor; split.\n  eapply plus_left'.\n  eapply exec_return; eauto.\n  eapply add_branch_correct; eauto. traceEq.\n  econstructor; eauto.\nQed.\n\nLemma transf_initial_states:\n  forall st1, LTL.initial_state prog st1 ->\n  exists st2, LTLin.initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].  \n  exists (Callstate nil tf nil m0); split.\n  econstructor; eauto. eapply Genv.init_mem_transf_partial; eauto. \n  replace (prog_main tprog) with (prog_main prog).\n  rewrite symbols_preserved. eauto.\n  symmetry. apply (transform_partial_program_main transf_fundef _ TRANSF). \n  rewrite <- H3. apply sig_preserved. auto.\n  constructor. constructor. auto.\n  eapply Genv.find_funct_ptr_prop; eauto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r, \n  match_states st1 st2 -> LTL.final_state st1 r -> LTLin.final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv H4. constructor.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (LTL.semantics prog) (LTLin.semantics tprog).\nProof.\n  eapply forward_simulation_plus.\n  eexact symbols_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  eexact transf_step_correct.\nQed.\n\nEnd LINEARIZATION.\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/Linearizeproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.18197971878500463}}
{"text": "Require Import CertiGraph.lib.Coqlib.\nRequire Export VST.floyd.proofauto.\nRequire Import CertiGraph.mark.env_mark_bin.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.GraphBin.\nRequire Import CertiGraph.msl_application.Graph_Mark.\nRequire Import CertiGraph.msl_application.DagBin_Mark.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.mark.spatial_graph_bin_mark.\nRequire Import VST.msl.wand_frame.\nRequire Import VST.floyd.reassoc_seq.\nRequire Import VST.floyd.field_at_wand.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\nLocal Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\n(* Using unit for DE and DG, inspired by Graph *)\nNotation dag sh x g := (@reachable_dag_vertices_at _ _ _ _ _ _ unit unit _ mpred (@SGP pSGG_VST bool unit (sSGG_VST sh)) (SGA_VST sh) x g).\nNotation Graph := (@Graph pSGG_VST bool unit unit).\n#[local] Existing Instances MGS binGraph maGraph finGraph RGF.\n\nDefinition mark_spec :=\n DECLARE _mark\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (weak_valid g x)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (dag sh x g)\n  POST [ Tvoid ]\n      EX g': Graph,\n        PROP (mark x g g')\n        LOCAL()\n        SEP (dag sh x g').\n\nDefinition main_spec :=\n DECLARE _main\n  WITH u : globals\n  PRE  [] main_pre prog tt u\n  POST [ tint ] main_post prog u.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mark_spec ; main_spec]).\n\nLemma dag_local_facts: forall sh x (g: Graph), weak_valid g x -> dag sh x g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. destruct H.\n  - simpl in H. subst x. entailer!.\n  - destruct (vgamma g x) as [[d l] r] eqn:?.\n    pose proof (@root_unfold _ (sSGG_VST sh) g x d l r H Heqp); clear -H0.\n    simpl in *. rewrite H0. entailer!.\nQed.\n\nLemma body_mark: semax_body Vprog Gprog f_mark mark_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as dlr eqn:?H.\n  destruct dlr as [[d l] r].\n  rename H0 into H_GAMMA_g; symmetry in H_GAMMA_g.\n  rename H into H_weak_valid.\n\n  forward_if  (* if (x == 0) *)\n    (PROP  (pointer_val_val x <> nullval)\n     LOCAL (temp _x (pointer_val_val x))\n     SEP   (dag sh x g)).\n  - apply denote_tc_test_eq_split. 2: entailer!. apply dag_local_facts; auto.\n  - (* return *) forward. Exists g. entailer!. destruct x. 1: simpl in H; inversion H. apply (mark_null_refl g).\n  - (* skip *) forward. entailer!.\n  - Intros. assert (vvalid g x) as gx_vvalid. {\n      destruct H_weak_valid; [| auto].\n      unfold is_null_SGBA in H0; simpl in H0; subst x.\n      exfalso. apply H. auto.\n    } assert (isptr (pointer_val_val x) /\\ exists b i, x = ValidPointer b i). {\n      destruct x. 2: exfalso; apply H; reflexivity. split; simpl; auto.\n      exists b, i. reflexivity.\n    } destruct H0 as [? [b [i ?]]]. clear H0 H_weak_valid.\n    pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n    simpl in H0. simpl reachable_dag_vertices_at.\n    erewrite H0 by eauto. Intros.\n    change (vertex_at x (d, l, r)) with\n        (@data_at CompSpecs sh node_type\n                  (Vint (Int.repr (if d then 1 else 0)), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)).\n    forward. (* root_mark = x -> m; *)\n    eapply semax_pre with\n        (PROP  ()\n               LOCAL\n               (temp _root_mark (Vint (Int.repr (if d then 1 else 0)));\n                temp _x (pointer_val_val x))\n               SEP  (dag sh x g)).\n    1: { pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n         simpl in H2. simpl reachable_dag_vertices_at.\n         erewrite H2 by eauto; simpl vertex_at; entailer!.\n         }\n    forward_if  (* if (root_mark == 1) *)\n      (PROP (d = false)\n            LOCAL (temp _x (pointer_val_val x))\n            SEP (dag sh x g)).\n    + forward. (* return *) Exists g. entailer!.\n      eapply (mark_vgamma_true_refl g); eauto.\n      now destruct d.\n    + forward. (* skip; *) entailer!.\n      now destruct d.\n    +\n      pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n      simpl in H2. simpl reachable_dag_vertices_at.\n      erewrite H2 by eauto.\n      Intros. subst d.\n      change (vertex_at x (false, l, r)) with\n          (@data_at CompSpecs sh node_type\n                    (Vint (Int.repr 0), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)).\n      forward. (* l = x -> l; *) 1: entailer!; destruct l; simpl; auto.\n      forward. (* r = x -> r; *) 1: entailer!; destruct r; simpl; auto.\n      forward. (* x -> d = 1; *)\n      pose proof Graph_vgen_true_mark1 g x _ _ H_GAMMA_g gx_vvalid.\n      apply semax_pre with\n          (PROP  ()\n                 LOCAL (temp _r (pointer_val_val r);\n                        temp _l (pointer_val_val l);\n                        temp _x (pointer_val_val x))\n                 SEP (dag sh x (Graph_vgen g x true))).\n      1: { pose proof (@root_update_unfold _ (sSGG_VST sh) g).\n           simpl in H4. simpl reachable_dag_vertices_at.\n           erewrite H4 by eauto; simpl vertex_at; entailer!. }\n           forget (Graph_vgen g x true) as g1.\n      assert (weak_valid g1 l) by (eapply left_weak_valid; eauto).\n      (* mark(l); *)\n      localize [dag sh l g1].\n      forward_call (sh, g1, l).\n      Intros g2.\n      unlocalize [dag sh x g2] using g2 assuming H5.\n      1: { subst.\n           pose proof (@dag_ramify_left _ (sSGG_VST sh) g g1 (ValidPointer b i) l r gx_vvalid H_GAMMA_g H3).\n           simpl reachable_dag_vertices_at in *.\n           eapply H1.\n      }\n       assert (weak_valid g2 r) by (eapply right_weak_valid; eauto).\n      (* mark(r); *)\n      localize [dag sh r g2].\n      forward_call (sh, g2, r).\n      Intros g3.\n      unlocalize [dag sh x g3] using g3 assuming H7.\n      1: { subst.\n           pose proof (@dag_ramify_right _ (sSGG_VST sh) g\n                         _ _ _ _ _ gx_vvalid H_GAMMA_g H3 H5).\n           simpl reachable_dag_vertices_at in *; eapply H1.\n           }\n      (* ( return; ) *)\n      Exists g3. entailer!.\n      apply (mark1_mark_left_mark_right g g1 g2 g3 (ValidPointer b i) l r); auto.\nQed. (* Original: 114 seconds; VST 2.*: 2.739 secs *)\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/mark/verif_mark_bin_dag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.18178765418778037}}
{"text": "Require Import VST.concurrency.dry_machine.\nRequire Import VST.concurrency.erased_machine.\nRequire Import VST.concurrency.threads_lemmas.\nRequire Import VST.concurrency.permissions.\nRequire Import VST.concurrency.semantics.\nRequire Import VST.concurrency.concurrent_machine.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Axioms.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\nImport Concur.\n\nModule Type MachinesSig.\n  Declare Module SEM: Semantics.\n\n  Module DryMachine := DryMachineShell SEM.\n  Module ErasedMachine := ErasedMachineShell SEM.\n\n  Module DryConc := CoarseMachine mySchedule DryMachine.\n  Module FineConc := FineMachine mySchedule DryMachine.\n  (** SC machine*)\n  Module SC := FineMachine mySchedule ErasedMachine.\n\n  Import DryMachine ThreadPool.\n  Global Ltac pf_cleanup :=\n    repeat match goal with\n           | [H1: invariant ?X, H2: invariant ?X |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: mem_compatible ?TP ?M, H2: mem_compatible ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: is_true (leq ?X ?Y), H2: is_true (leq ?X ?Y) |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M, H2: containsThread ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThreadC _ ?TP _ _) ?M |- _] =>\n             apply cntUpdateC' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThread _ ?TP _ _ _) ?M |- _] =>\n             apply cntUpdate' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           end.\n\n\nEnd MachinesSig.\n\n\nModule Type AsmContext (SEM : Semantics)\n       (Machines : MachinesSig with Module SEM := SEM).\n\n  Import Machines.\n  Parameter initU: mySchedule.schedule.\n\n  Parameter init_mem : option Memory.Mem.mem.\n  Definition init_perm  :=\n    match init_mem with\n    | Some m => Some (getCurPerm m, empty_map)\n    | None => None\n    end.\n\n  Parameter the_ge : SEM.G.\n\n  Definition coarse_semantics:=\n    DryConc.MachineSemantics initU init_perm.\n\n  Definition fine_semantics:=\n    FineConc.MachineSemantics initU init_perm.\n\n  Definition sc_semantics :=\n    SC.MachineSemantics initU None.\n\n  Definition tpc_init f arg := initial_core coarse_semantics 0 the_ge f arg.\n  Definition tpf_init f arg := initial_core fine_semantics 0 the_ge f arg.\n  Definition sc_init f arg := initial_core sc_semantics 0 the_ge f arg.\n\nEnd AsmContext.\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/dry_context.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.18178763025881317}}
{"text": "Require Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.finfun Ssreflect.fintype Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.seq Ssreflect.tuple.\nRequire Import Ssreflect.path Ssreflect.fingraph  Ssreflect.finset.\nRequire Import x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.bitsrep x86proved.bitsops x86proved.bitsprops x86proved.bitsopsprops.\nRequire Import x86proved.spred x86proved.septac x86proved.spec x86proved.safe x86proved.x86.basic x86proved.x86.program x86proved.x86.macros x86proved.x86.call.\nRequire Import x86proved.x86.instr x86proved.monad x86proved.reader x86proved.writer x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.x86.mem x86proved.x86.exn x86proved.x86.eval x86proved.x86.instrcodec\n               x86proved.monadinst x86proved.x86.ioaction x86proved.bitsrep x86proved.bitsops x86proved.x86.eval x86proved.x86.step x86proved.pointsto x86proved.cursor.\nRequire Import x86proved.x86.program x86proved.x86.programassem x86proved.x86.reg x86proved.x86.instrsyntax x86proved.x86.instrrules.\nRequire Import x86proved.spectac x86proved.charge.iltac x86proved.triple.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(****************************************************************)\n(* C-style strings                                              *)\n(****************************************************************)\n\nDefinition CString (s: seq DWORD) := all (fun x => x != #0) s.\n\nLemma snocCString\n        (l1 : seq DWORD)(H: CString l1)\n        (c : DWORD)(_ : c != #0):\n  CString (l1 ++ [:: c]).\nProof.\n  rewrite /CString.\n  rewrite all_cat; apply /andP.\n  split; first by rewrite /CString in H; exact: H.\n  rewrite all_seq1.\n  done.\nQed.\n\nLemma snocMem (lo pd: DWORD)(l1 : seq DWORD)(c: DWORD):\n  pd :-> c ** lo -- pd :-> l1 |-- lo -- next (pd +# 3) :-> (cat l1 [:: c]).\nProof.\n  rewrite ->seqMemIsCat.\n  rewrite pairMemIsPair.\n  apply lexistsR with (x := pd).\n  rewrite ->seqMemIsCons.\n  ssimpl. rewrite /pointsTo; apply lexistsL => q.\n  rewrite -> memIsFixed. sdestruct => AP. sbazooka.\n  rewrite ->seqMemIsNil. apply apart_addBn_next in AP.\n sbazooka.\nQed.\n\nLemma catCString (l1: seq DWORD) (H1: CString l1) l2 (H2: CString l2):\n  CString (l1 ++ l2).\nProof.\n   rewrite /CString.\n   rewrite /CString in H1, H2.\n   by rewrite all_cat H1 H2.\nQed.\n\nDefinition memToS {R} {_:MemIs R} p q (s: seq DWORD) :=\n    CString s\n/\\\\ p -- q :-> s\n ** q :-> (#0: DWORD).\n\nDefinition pointsToS {R} {_:MemIs R} p (s: seq DWORD) :=\n  Exists q: DWORD, memToS p q s.\n\nNotation \"p '--' q ':-S>' x\" := (memToS p q x)\n    (at level 50, q at next level,  no associativity).\nNotation \"p ':-S>' x\" := (pointsToS p x)\n    (at level 50,  no associativity).\n\nLemma caseString_nil (q r: DWORD):\n  q -- r :-S> [::] |-- q == r /\\\\ r :-> (#0: DWORD).\nProof.\n  rewrite /memToS [CString _]/= /cat; sdestruct=> _.\n  rewrite seqMemIsNil.\n  sdestruct=> /eqP eq.\n  sbazooka.\nQed.\n\nLemma caseString_cons (q r: DWORD)(c: DWORD)(cs: seq DWORD) :\n  q -- r :-S> [:: c & cs] |-- (c != #0) /\\\\ q :-> c ** next (q +# 3) -- r :-S> cs.\nProof.\n  rewrite /memToS.\n  rewrite /CString /all-/all.\n  rewrite seqMemIsCons.\n  sdestruct=> /andP [cn0 cstr].\n  sdestruct=> q'.\n  ssplit.\n    * exact: cn0.\n    * sbazooka.\n      rewrite ->memIsFixed; sdestruct=> H. apply apart_addBn_next in H. rewrite H.\n      rewrite /pointsTo.\n      sbazooka.\nQed.\n\nLemma splitString (q r: DWORD)(l2: seq DWORD):\n     q -- r :-S> l2\n |--   ((l2 == [::]) && (q == r) /\\\\ q :-> (#0: DWORD))\n  \\\\// (Exists c: DWORD, Exists cs: seq DWORD,\n        ((l2 == [:: c & cs])\n      && (c != (#0: DWORD))\n      /\\\\ q :-> c ** next (q +# 3) -- r :-S>  cs)).\nProof.\n  case: l2.\n  * (* CASE: l2 =~ [::] *)\n    apply lorR1.\n    rewrite ->caseString_nil.\n    sdestruct=> /eqP <-.\n    sbazooka.\n    by apply /andP; split; done.\n\n  * (* CASE: l2 =~ [:: c & cs ] *)\n    move=> c cs.\n    apply lorR2.\n    apply lexistsR with (x := c);\n      apply lexistsR with (x := cs).\n    rewrite ->caseString_cons.\n    sbazooka.\n    by apply /andP; split; done.\nQed.\n\nLemma emptyString (lo hi: DWORD)(l: seq DWORD)(_ : CString l):\n  hi :-> (#0: DWORD) ** lo -- hi :-> l  |-- lo -- hi :-S> l.\nProof.\n  rewrite /memToS.\n  ssplit; first by done.\n  sbazooka.\nQed.\n\n\nLemma catString (lo hi pd: DWORD)(l1 l2: seq DWORD)(_: CString l1):\n  lo -- pd :-> l1 ** pd -- hi :-S> l2\n     |-- lo -- hi :-S> (cat l1 l2).\nProof.\n  rewrite /memToS.\n  rewrite ->seqMemIsCat. rewrite pairMemIsPair.\n  sdestruct=> l2IsString; ssplit; last by sbazooka.\n  rewrite /CString.\n  rewrite all_cat; apply /andP; split; by exact.\nQed.\n\nLemma memIsNextS (p q q' : DWORD) l : next p = mkCursor q' ->\n  next p -- q :-S> l |-- p+#1 -- q :-S> l.\nProof. move => H0.\ndestruct l.\n+ rewrite /memToS !seqMemIsNil.\n  sdestructs => H H'. sbazooka. by rewrite (nextIsInc H').\n+ rewrite /memToS !seqMemIsCons.\n  sdestructs => H H'. sbazooka. have H1 := nextIsInc H0. by  rewrite H0 -H1.\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/lib/regexp/stringbuff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.18163631044044842}}
{"text": "From Coq Require Import Reals Psatz.\nFrom stdpp Require Export binders strings.\nFrom stdpp Require Import gmap fin_maps.\nFrom iris.algebra Require Export ofe.\nFrom self.prelude Require Import stdpp_ext.\nFrom self.prob Require Import distribution.\nFrom self.program_logic Require Export language ectx_language ectxi_language.\nFrom self.prob_lang Require Export locations.\nFrom iris.prelude Require Import options.\nFrom self.prelude Require Import stdpp_ext.\n\nDelimit Scope expr_scope with E.\nDelimit Scope val_scope with V.\n\nModule prob_lang.\n\nInductive base_lit : Set :=\n  | LitInt (n : Z) | LitBool (b : bool) | LitUnit | LitLoc (l : loc) | LitLbl (l : loc).\nInductive un_op : Set :=\n  | NegOp | MinusUnOp.\nInductive bin_op : Set :=\n  | PlusOp | MinusOp | MultOp | QuotOp | RemOp (* Arithmetic *)\n  | AndOp | OrOp | XorOp (* Bitwise *)\n  | ShiftLOp | ShiftROp (* Shifts *)\n  | LeOp | LtOp | EqOp. (* Relations *)\n\nInductive expr :=\n  (* Values *)\n  | Val (v : val)\n  (* Base lambda calculus *)\n  | Var (x : string)\n  | Rec (f x : binder) (e : expr)\n  | App (e1 e2 : expr)\n  (* Base types and their operations *)\n  | UnOp (op : un_op) (e : expr)\n  | BinOp (op : bin_op) (e1 e2 : expr)\n  | If (e0 e1 e2 : expr)\n  (* Products *)\n  | Pair (e1 e2 : expr)\n  | Fst (e : expr)\n  | Snd (e : expr)\n  (* Sums *)\n  | InjL (e : expr)\n  | InjR (e : expr)\n  | Case (e0 : expr) (e1 : expr) (e2 : expr)\n  (* Heap *)\n  | Alloc (e : expr)\n  | Load (e : expr)\n  | Store (e1 : expr) (e2 : expr)\n  (* Probabilistic choice *)\n  | AllocTape (n : nat)\n  | Flip (e : expr)\nwith val :=\n  | LitV (l : base_lit)\n  | RecV (f x : binder) (e : expr)\n  | PairV (v1 v2 : val)\n  | InjLV (v : val)\n  | InjRV (v : val).\n\nBind Scope expr_scope with expr.\nBind Scope val_scope with val.\n\nNotation of_val := Val (only parsing).\n\nDefinition to_val (e : expr) : option val :=\n  match e with\n  | Val v => Some v\n  | _ => None\n  end.\n\n(** We assume the following encoding of values to 64-bit words: The least 3\nsignificant bits of every word are a \"tag\", and we have 61 bits of payload,\nwhich is enough if all pointers are 8-byte-aligned (common on 64bit\narchitectures). The tags have the following meaning:\n\n0: Payload is the data for a LitV (LitInt _).\n1: Payload is the data for a InjLV (LitV (LitInt _)).\n2: Payload is the data for a InjRV (LitV (LitInt _)).\n3: Payload is the data for a LitV (LitLoc _).\n4: Payload is the data for a InjLV (LitV (LitLoc _)).\n4: Payload is the data for a InjRV (LitV (LitLoc _)).\n6: Payload is one of the following finitely many values, which 61 bits are more\n   than enough to encode:\n   LitV LitUnit, InjLV (LitV LitUnit), InjRV (LitV LitUnit),\n   LitV 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  (* | LitProphecy _ | LitPoison => False *)\n  | LitInt _ | LitBool _  | LitLoc _ | LitLbl _ | LitUnit => True\n  end.\nDefinition val_is_unboxed (v : val) : Prop :=\n  match v with\n  | LitV l => lit_is_unboxed l\n  | InjLV (LitV l) => lit_is_unboxed l\n  | InjRV (LitV l) => lit_is_unboxed l\n  | _ => False\n  end.\n\nGlobal Instance lit_is_unboxed_dec l : Decision (lit_is_unboxed l).\nProof. destruct l; simpl; exact (decide _). Defined.\nGlobal Instance val_is_unboxed_dec v : Decision (val_is_unboxed v).\nProof. destruct v as [ | | | [] | [] ]; simpl; exact (decide _). Defined.\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 \u2228 val_is_unboxed v1.\nGlobal Arguments vals_compare_safe !_ !_ /.\n\n(* A tape is a product of a natural number n and a list of integers in {0,...,n} *)\nDefinition tape := prod nat (list Z).\n\n(* Typeclass stuff for tapes *)\nGlobal Instance tape_inhabited : Inhabited tape.\nProof. apply prod_inhabited; [apply Nat.inhabited | apply list_inhabited ]. Defined.\nGlobal Instance tape_eq_dec : EqDecision tape.\nProof. solve_decision. Defined.\n\n(** The state: a [loc]-indexed heap of [val]s, and [loc]-indexed tapes of\n    booleans. *)\nRecord state : Type := {\n  heap  : gmap loc val;\n  tapes : gmap loc tape\n}.\n\n(** Equality and other typeclass stuff *)\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof. by destruct v. Qed.\n\nLemma of_to_val e v : to_val e = Some v \u2192 of_val v = e.\nProof. destruct e=>//=. by intros [= <-]. Qed.\n\nGlobal Instance of_val_inj : Inj (=) (=) of_val.\nProof. intros ??. congruence. Qed.\n\nGlobal Instance base_lit_eq_dec : EqDecision base_lit.\nProof. solve_decision. Defined.\nGlobal Instance un_op_eq_dec : EqDecision un_op.\nProof. solve_decision. Defined.\nGlobal Instance bin_op_eq_dec : EqDecision bin_op.\nProof. solve_decision. Defined.\nGlobal Instance expr_eq_dec : EqDecision expr.\nProof.\n  refine (\n   fix go (e1 e2 : expr) {struct e1} : Decision (e1 = e2) :=\n     match e1, e2 with\n     | Val v, Val v' => cast_if (decide (v = v'))\n     | Var x, Var x' => cast_if (decide (x = x'))\n     | Rec f x e, Rec f' x' e' =>\n        cast_if_and3 (decide (f = f')) (decide (x = x')) (decide (e = e'))\n     | App e1 e2, App e1' e2' => cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | UnOp o e, UnOp o' e' => cast_if_and (decide (o = o')) (decide (e = e'))\n     | BinOp o e1 e2, BinOp o' e1' e2' =>\n        cast_if_and3 (decide (o = o')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | If e0 e1 e2, If e0' e1' e2' =>\n        cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | Pair e1 e2, Pair e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | Fst e, Fst e' => cast_if (decide (e = e'))\n     | Snd e, Snd e' => cast_if (decide (e = e'))\n     | InjL e, InjL e' => cast_if (decide (e = e'))\n     | InjR e, InjR e' => cast_if (decide (e = e'))\n     | Case e0 e1 e2, Case e0' e1' e2' =>\n        cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | Alloc e, Alloc e' => cast_if (decide (e = e'))\n     | Load e, Load e' => cast_if (decide (e = e'))\n     | Store e1 e2, Store e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | AllocTape n, AllocTape n' => cast_if (decide (n = n'))\n     | Flip e, Flip 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' =>\n        cast_if_and3 (decide (f = f')) (decide (x = x')) (decide (e = e'))\n     | PairV e1 e2, PairV e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | InjLV e, InjLV e' => cast_if (decide (e = e'))\n     | InjRV e, InjRV e' => cast_if (decide (e = e'))\n     | _, _ => right _\n     end\n   for go); try (clear go gov; abstract intuition congruence).\nDefined.\nGlobal Instance val_eq_dec : EqDecision val.\nProof. solve_decision. Defined.\nGlobal Instance state_eq_dec : EqDecision state.\nProof. solve_decision. Defined.\n\nGlobal Instance base_lit_countable : Countable base_lit.\nProof.\n refine (inj_countable' (\u03bb l, match l with\n  | LitInt n => inl (inl n)\n  | LitBool b => inl (inr b)\n  | LitUnit => inr (inl ())\n  | LitLoc l => inr (inr (inr l))\n  | LitLbl l => inr (inr (inl l))\n  end) (\u03bb l, match l with\n  | inl (inl n) => LitInt n\n  | inl (inr b) => LitBool b\n  | inr (inl ()) => LitUnit\n  | inr (inr (inr l)) => LitLoc l\n  | inr (inr (inl l)) => LitLbl l\n  end) _); by intros [].\nQed.\nGlobal Instance un_op_finite : Countable un_op.\nProof.\n refine (inj_countable' (\u03bb op, match op with NegOp => 0 | MinusUnOp => 1 end)\n  (\u03bb n, match n with 0 => NegOp | _ => MinusUnOp end) _); by intros [].\nQed.\nGlobal Instance bin_op_countable : Countable bin_op.\nProof.\n refine (inj_countable' (\u03bb op, match op with\n  | PlusOp => 0 | MinusOp => 1 | MultOp => 2 | QuotOp => 3 | RemOp => 4\n  | AndOp => 5 | OrOp => 6 | XorOp => 7 | ShiftLOp => 8 | ShiftROp => 9\n  | LeOp => 10 | LtOp => 11 | EqOp => 12\n  end) (\u03bb n, match n with\n  | 0 => PlusOp | 1 => MinusOp | 2 => MultOp | 3 => QuotOp | 4 => RemOp\n  | 5 => AndOp | 6 => OrOp | 7 => XorOp | 8 => ShiftLOp | 9 => ShiftROp\n  | 10 => LeOp | 11 => LtOp | _ => EqOp\n  end) _); by intros [].\nQed.\nGlobal Instance expr_countable : Countable expr.\nProof.\n set (enc :=\n   fix go e :=\n     match e with\n     | Val v => GenNode 0 [gov v]\n     | Var x => GenLeaf (inl (inl x))\n     | Rec f x e => GenNode 1 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); go e]\n     | App e1 e2 => GenNode 2 [go e1; go e2]\n     | UnOp op e => GenNode 3 [GenLeaf (inr (inr (inl op))); go e]\n     | BinOp op e1 e2 => GenNode 4 [GenLeaf (inr (inr (inr op))); go e1; go e2]\n     | If e0 e1 e2 => GenNode 5 [go e0; go e1; go e2]\n     | Pair e1 e2 => GenNode 6 [go e1; go e2]\n     | Fst e => GenNode 7 [go e]\n     | Snd e => GenNode 8 [go e]\n     | InjL e => GenNode 9 [go e]\n     | InjR e => GenNode 10 [go e]\n     | Case e0 e1 e2 => GenNode 11 [go e0; go e1; go e2]\n     | Alloc e => GenNode 12 [go e]\n     | Load e => GenNode 13 [go e]\n     | Store e1 e2 => GenNode 14 [go e1; go e2]\n     | AllocTape n => GenNode 15 [GenLeaf (inr (inl (inr n)))]\n     | Flip e => GenNode 16 [go e]\n     end\n   with gov v :=\n     match v with\n     | LitV l => GenLeaf (inr (inl (inl l)))\n     | RecV f x e =>\n        GenNode 0 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); go e]\n     | PairV v1 v2 => GenNode 1 [gov v1; gov v2]\n     | InjLV v => GenNode 2 [gov v]\n     | InjRV v => GenNode 3 [gov v]\n     end\n   for go).\n set (dec :=\n   fix go e :=\n     match e with\n     | GenNode 0 [v] => Val (gov v)\n     | GenLeaf (inl (inl x)) => Var x\n     | GenNode 1 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); e] => Rec f x (go e)\n     | GenNode 2 [e1; e2] => App (go e1) (go e2)\n     | GenNode 3 [GenLeaf (inr (inr (inl op))); e] => UnOp op (go e)\n     | GenNode 4 [GenLeaf (inr (inr (inr op))); e1; e2] => BinOp op (go e1) (go e2)\n     | GenNode 5 [e0; e1; e2] => If (go e0) (go e1) (go e2)\n     | GenNode 6 [e1; e2] => Pair (go e1) (go e2)\n     | GenNode 7 [e] => Fst (go e)\n     | GenNode 8 [e] => Snd (go e)\n     | GenNode 9 [e] => InjL (go e)\n     | GenNode 10 [e] => InjR (go e)\n     | GenNode 11 [e0; e1; e2] => Case (go e0) (go e1) (go e2)\n     | GenNode 12 [e] => Alloc (go e)\n     | GenNode 13 [e] => Load (go e)\n     | GenNode 14 [e1; e2] => Store (go e1) (go e2)\n     | GenNode 15 [GenLeaf (inr (inl (inr n)))] => AllocTape n\n     | GenNode 16 [e] => Flip (go e)\n     | _ => Val $ LitV LitUnit (* dummy *)\n     end\n   with gov v :=\n     match v with\n     | GenLeaf (inr (inl (inl l))) => LitV l\n     | GenNode 0 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); e] => RecV f x (go e)\n     | GenNode 1 [v1; v2] => PairV (gov v1) (gov v2)\n     | GenNode 2 [v] => InjLV (gov v)\n     | GenNode 3 [v] => InjRV (gov v)\n     | _ => LitV LitUnit (* dummy *)\n     end\n   for go).\n refine (inj_countable' enc dec _).\n refine (fix go (e : expr) {struct e} := _ with gov (v : val) {struct v} := _ for go).\n - destruct e as [v| | | | | | | | | | | | | | | | | ]; simpl; f_equal;\n     [exact (gov v)|done..].\n - destruct v; by f_equal.\nQed.\nGlobal Instance val_countable : Countable val.\nProof. refine (inj_countable of_val to_val _); auto using to_of_val. Qed.\nGlobal Program Instance state_countable : Countable state :=\n  {| encode \u03c3 := encode (\u03c3.(heap), \u03c3.(tapes));\n     decode p := '(h, t) \u2190 decode p; mret {|heap:=h; tapes:=t|} |}.\nNext Obligation. intros [h t]. rewrite decode_encode //=. Qed.\n\nGlobal Instance state_inhabited : Inhabited state :=\n  populate {| heap := inhabitant; tapes := inhabitant |}.\nGlobal Instance val_inhabited : Inhabited val := populate (LitV LitUnit).\nGlobal Instance expr_inhabited : Inhabited expr := populate (Val inhabitant).\n\nGlobal Instance tapes_lookup_total : LookupTotal loc (nat * list Z) (gmap loc tape).\nProof. apply map_lookup_total. Defined.\n\nCanonical Structure stateO := leibnizO state.\nCanonical Structure locO := leibnizO loc.\nCanonical Structure valO := leibnizO val.\nCanonical Structure exprO := leibnizO expr.\n\n(** Evaluation contexts *)\nInductive ectx_item :=\n  | AppLCtx (v2 : val)\n  | AppRCtx (e1 : expr)\n  | UnOpCtx (op : un_op)\n  | BinOpLCtx (op : bin_op) (v2 : val)\n  | BinOpRCtx (op : bin_op) (e1 : expr)\n  | IfCtx (e1 e2 : expr)\n  | PairLCtx (v2 : val)\n  | PairRCtx (e1 : expr)\n  | FstCtx\n  | SndCtx\n  | InjLCtx\n  | InjRCtx\n  | CaseCtx (e1 : expr) (e2 : expr)\n  | AllocCtx\n  | LoadCtx\n  | StoreLCtx (v2 : val)\n  | StoreRCtx (e1 : expr)\n  | FlipCtx.\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 v2 => Pair e (Val v2)\n  | PairRCtx e1 => Pair e1 e\n  | FstCtx => Fst e\n  | SndCtx => Snd e\n  | InjLCtx => InjL e\n  | InjRCtx => InjR e\n  | CaseCtx e1 e2 => Case e e1 e2\n  | AllocCtx => Alloc e\n  | LoadCtx => Load e\n  | StoreLCtx v2 => Store e (Val v2)\n  | StoreRCtx e1 => Store e1 e\n  | FlipCtx => Flip e\n  end.\n\nDefinition decomp_item (e : expr) : option (ectx_item * expr) :=\n  match e with\n  | App (Val _) (Val _)      => None\n  | App e (Val v)            => Some (AppLCtx v, e)\n  | App e1 e2                => Some (AppRCtx e1, e2)\n  | UnOp _ (Val _)           => None\n  | UnOp op e                => Some (UnOpCtx op, e)\n  | BinOp _ (Val _) (Val _)  => None\n  | BinOp op e (Val v)       => Some (BinOpLCtx op v, e)\n  | BinOp op e1 e2           => Some (BinOpRCtx op e1, e2)\n  | If (Val _) _ _           => None\n  | If e0 e1 e2              => Some (IfCtx e1 e2, e0)\n  | Pair (Val _) (Val _)     => None\n  | Pair e (Val v)           => Some (PairLCtx v, e)\n  | Pair e1 e2               => Some (PairRCtx e1, e2)\n  | Fst (Val _)              => None\n  | Fst e                    => Some (FstCtx, e)\n  | Snd (Val _)              => None\n  | Snd e                    => Some (SndCtx, e)\n  | InjL (Val _)             => None\n  | InjL e                   => Some (InjLCtx, e)\n  | InjR (Val _)             => None\n  | InjR e                   => Some (InjRCtx, e)\n  | Case (Val _) _ _         => None\n  | Case e0 e1 e2            => Some (CaseCtx e1 e2, e0)\n  | Alloc (Val _)            => None\n  | Alloc e                  => Some (AllocCtx, e)\n  | Load (Val _)             => None\n  | Load e                   => Some (LoadCtx, e)\n  | Store (Val _) (Val _)    => None\n  | Store e (Val v)          => Some (StoreLCtx v, e)\n  | Store e1 e2              => Some (StoreRCtx e1, e2)\n  | Flip (Val _)             => None\n  | Flip e                   => Some (FlipCtx, e)\n  | _                        => None\n  end.\n\n(** Substitution *)\nFixpoint subst (x : string) (v : val) (e : expr)  : expr :=\n  match e with\n  | Val _ => e\n  | Var y => if decide (x = y) then Val v else Var y\n  | Rec f y e =>\n     Rec f y $ if decide (BNamed x \u2260 f \u2227 BNamed x \u2260 y) then subst x v e else e\n  | App e1 e2 => App (subst x v e1) (subst x v e2)\n  | UnOp op e => UnOp op (subst x v e)\n  | BinOp op e1 e2 => BinOp op (subst x v e1) (subst x v e2)\n  | If e0 e1 e2 => If (subst x v e0) (subst x v e1) (subst x v e2)\n  | Pair e1 e2 => Pair (subst x v e1) (subst x v e2)\n  | Fst e => Fst (subst x v e)\n  | Snd e => Snd (subst x v e)\n  | InjL e => InjL (subst x v e)\n  | InjR e => InjR (subst x v e)\n  | Case e0 e1 e2 => Case (subst x v e0) (subst x v e1) (subst x v e2)\n  | Alloc e => Alloc (subst x v e)\n  | Load e => Load (subst x v e)\n  | Store e1 e2 => Store (subst x v e1) (subst x v e2)\n  | AllocTape n => AllocTape n\n  | Flip e => Flip (subst x v e)\n  end.\n\nDefinition subst' (mx : binder) (v : val) : expr \u2192 expr :=\n  match mx with BNamed x => subst x v | BAnon => \u03bb x, x 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) : base_lit :=\n  match op with\n  | PlusOp => LitInt (n1 + n2)\n  | MinusOp => LitInt (n1 - n2)\n  | MultOp => LitInt (n1 * n2)\n  | QuotOp => LitInt (n1 `quot` n2)\n  | RemOp => LitInt (n1 `rem` n2)\n  | AndOp => LitInt (Z.land n1 n2)\n  | OrOp => LitInt (Z.lor n1 n2)\n  | XorOp => LitInt (Z.lxor n1 n2)\n  | ShiftLOp => LitInt (n1 \u226a n2)\n  | ShiftROp => LitInt (n1 \u226b n2)\n  | LeOp => LitBool (bool_decide (n1 \u2264 n2))\n  | LtOp => LitBool (bool_decide (n1 < n2))\n  | EqOp => LitBool (bool_decide (n1 = n2))\n  end%Z.\n\nDefinition bin_op_eval_bool (op : bin_op) (b1 b2 : bool) : option base_lit :=\n  match op with\n  | PlusOp | MinusOp | MultOp | QuotOp | RemOp => None (* Arithmetic *)\n  | AndOp => Some (LitBool (b1 && b2))\n  | OrOp => Some (LitBool (b1 || b2))\n  | XorOp => Some (LitBool (xorb b1 b2))\n  | ShiftLOp | ShiftROp => None (* Shifts *)\n  | LeOp | LtOp => None (* InEquality *)\n  | EqOp => Some (LitBool (bool_decide (b1 = b2)))\n  end.\n\nDefinition bin_op_eval (op : bin_op) (v1 v2 : val) : option val :=\n  if decide (op = EqOp) then\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) => Some $ LitV $ bin_op_eval_int op n1 n2\n    | LitV (LitBool b1), LitV (LitBool b2) => LitV <$> bin_op_eval_bool op b1 b2\n    | _, _ => None\n    end.\n\nDefinition state_upd_heap (f: gmap loc val \u2192 gmap loc val) (\u03c3: state) : state :=\n  {| heap := f \u03c3.(heap); tapes := \u03c3.(tapes) |}.\nGlobal Arguments state_upd_heap _ !_ /.\n\nDefinition state_upd_tapes (f: gmap loc tape \u2192 gmap loc tape) (\u03c3: state) : state :=\n  {| heap := \u03c3.(heap); tapes := f \u03c3.(tapes) |}.\nGlobal Arguments state_upd_tapes _ !_ /.\n\nLemma state_upd_tapes_twice \u03c3 l n xs ys:\n state_upd_tapes <[l:=(n,ys)]> (state_upd_tapes <[l:=(n,xs)]> \u03c3)\n = state_upd_tapes <[l:=(n,ys)]> \u03c3.\nProof.\n  rewrite /state_upd_tapes.\n  simpl.\n  f_equal.\n  apply insert_insert.\nQed.\n\n#[local] Open Scope R.\n\nDefinition det_head_step_dec (e1 : expr) (\u03c31 : state) '(e2, \u03c32) : bool :=\n  match e1, e2 with\n  | Rec f x e, Val (RecV f' x' e') =>\n      bool_decide (f = f' \u2227 x = x' \u2227 e = e' \u2227 \u03c31 = \u03c32)\n  | Pair (Val v1) (Val v2), Val (PairV v1' v2') =>\n      bool_decide (v1 = v1' \u2227 v2 = v2' \u2227 \u03c31 = \u03c32)\n  | InjL (Val v), (Val (InjLV v')) =>\n      bool_decide (v = v' \u2227 \u03c31 = \u03c32)\n  | InjR (Val v), (Val (InjRV v')) =>\n      bool_decide (v = v' \u2227 \u03c31 = \u03c32)\n  | App (Val (RecV f x e1)) (Val v2), e' =>\n      bool_decide (e' = subst' x v2 (subst' f (RecV f x e1) e1) \u2227 \u03c31 = \u03c32)\n  | UnOp op (Val v), Val v' =>\n      bool_decide (un_op_eval op v = Some v' \u2227 \u03c31 = \u03c32)\n  | BinOp op (Val v1) (Val v2), Val v' =>\n      bool_decide (bin_op_eval op v1 v2 = Some v' \u2227 \u03c31 = \u03c32)\n  | If (Val (LitV (LitBool true))) e1 e2, e1' =>\n      bool_decide (e1 = e1' \u2227 \u03c31 = \u03c32)\n  | If (Val (LitV (LitBool false))) e1 e2, e2' =>\n      bool_decide (e2 = e2' \u2227 \u03c31 = \u03c32)\n  | Fst (Val (PairV v1 v2)), Val v1' =>\n      bool_decide (v1 = v1' \u2227 \u03c31 = \u03c32)\n  | Snd (Val (PairV v1 v2)), Val v2' =>\n      bool_decide (v2 = v2' \u2227 \u03c31 = \u03c32)\n  | Case (Val (InjLV v)) e1 e2, App e1' (Val v') =>\n      bool_decide (v = v' \u2227 e1 = e1' \u2227 \u03c31 = \u03c32)\n  | Case (Val (InjRV v)) e1 e2, App e2' (Val v') =>\n      bool_decide (v = v' \u2227 e2 = e2' \u2227 \u03c31 = \u03c32)\n  | Alloc (Val v), Val (LitV (LitLoc l)) =>\n      let \u2113 := fresh_loc \u03c31.(heap) in\n      bool_decide (l = \u2113 \u2227 \u03c32 = state_upd_heap <[\u2113:=v]> \u03c31)\n  | Load (Val (LitV (LitLoc l))), Val v =>\n      bool_decide (\u03c31.(heap) !! l = Some v \u2227 \u03c31 = \u03c32)\n  | Store (Val (LitV (LitLoc l))) (Val w), Val (LitV LitUnit) =>\n      bool_decide (is_Some (\u03c31.(heap) !! l) \u2227 \u03c32 = state_upd_heap <[l:=w]> \u03c31)\n  | _, _ => false\n  end.\n\n(*\n   AA: On the long run, I think it may be better to define a step function using\n   the monadic structure of the distributions, and then show that it is equivalent\n   to the pmf below. I think this will save us of some trouble when trying to reason\n   about head step reductions. Most of the cases are a dret, and the other 2 are\n   a dbind of the uniform distribution, so it should not be too hard to write.\n*)\n\nDefinition head_step (e1 : expr) (\u03c31 : state) : distr (expr * state) :=\n  match e1 with\n  | Rec f x e =>\n      dret ((Val (RecV f x e)), \u03c31)\n  | Pair (Val v1) (Val v2) =>\n      dret ((Val (PairV v1 v2)), \u03c31)\n  | InjL (Val v) =>\n      dret ((Val (InjLV v)), \u03c31)\n  | InjR (Val v) =>\n      dret ((Val (InjRV v)), \u03c31)\n  | App (Val (RecV f x e1)) (Val v2) =>\n      dret (subst' x v2 (subst' f (RecV f x e1) e1) , \u03c31)\n  | UnOp op (Val v) =>\n      match un_op_eval op v with\n        | Some w => dret (Val w, \u03c31)\n        | _ => dzero\n      end\n  | BinOp op (Val v1) (Val v2) =>\n      match bin_op_eval op v1 v2 with\n        | Some w => dret (Val w, \u03c31)\n        | _ => dzero\n      end\n  | If (Val (LitV (LitBool true))) e1 e2  =>\n      dret (e1 , \u03c31)\n  | If (Val (LitV (LitBool false))) e1 e2 =>\n      dret (e2 , \u03c31)\n  | Fst (Val (PairV v1 v2)) =>\n      dret (Val v1, \u03c31)\n  | Snd (Val (PairV v1 v2)) =>\n      dret (Val v2, \u03c31)\n  | Case (Val (InjLV v)) e1 e2 =>\n      dret (App e1 (Val v), \u03c31)\n  | Case (Val (InjRV v)) e1 e2 =>\n      dret (App e2 (Val v), \u03c31)\n  | Alloc (Val v) =>\n      let \u2113 := fresh_loc \u03c31.(heap) in\n      dret (Val (LitV (LitLoc \u2113)), state_upd_heap <[\u2113:=v]> \u03c31)\n  | Load (Val (LitV (LitLoc l))) =>\n      match \u03c31.(heap) !! l with\n        | Some v => dret (Val v, \u03c31)\n        | None => dzero\n      end\n  | Store (Val (LitV (LitLoc l))) (Val w) =>\n      match \u03c31.(heap) !! l with\n        | Some v => dret (Val (LitV LitUnit), state_upd_heap <[l:=w]> \u03c31)\n        | None => dzero\n      end\n  | AllocTape n =>\n        let \u2113 := fresh_loc \u03c31.(tapes) in\n        dret (Val (LitV (LitLbl \u2113)), state_upd_tapes <[\u2113:=(n,[])]> \u03c31)\n  (* TODO: add unlabelled flip taking nat *)\n  | Flip (Val (LitV LitUnit)) =>\n        dbind (\u03bb b, dret (Val (LitV (LitBool b)), \u03c31)) fair_coin\n  | Flip (Val (LitV (LitLbl l))) =>\n        match \u03c31.(tapes) !! l with\n        | Some (n, (z :: zs)) => (* the tape is non-empty so we consume the first integer *)\n            dret (Val (LitV (LitInt z)), state_upd_tapes <[l:=(n,zs)]> \u03c31)\n        | Some (n, []) => (* the tape is allocated but empty, so we sample from {0 ... n} uniformly *)\n            dbind (\u03bb m, dret (Val (LitV (LitInt (Z.of_nat m))), \u03c31)) (unif_distr n)\n        | None => (* if the tape is not allocated, we do a fair probabilistic choice between 0 and 1 *)\n            dbind (\u03bb m, dret (Val (LitV (LitInt (Z.of_nat m))), \u03c31)) (unif_distr 1)\n        end\n  | _ => dzero\n  end.\n\n\n\nDefinition head_step_pmf (e1 : expr) (\u03c31 : state) '(e2, \u03c32) : R :=\n  if det_head_step_dec e1 \u03c31 (e2, \u03c32)\n  then 1\n  else\n    match e1, e2 with\n    | AllocTape n, Val (LitV (LitLbl l)) =>\n        let \u2113 := fresh_loc \u03c31.(tapes) in\n        if bool_decide (l = \u2113 \u2227 \u03c32 = state_upd_tapes <[\u2113:=(n,[])]> \u03c31) then 1 else 0\n(* TODO: add unlabelled flip taking nat *)\n    | Flip (Val (LitV LitUnit)), Val (LitV (LitBool b)) =>\n        if bool_decide (\u03c31 = \u03c32) then 0.5 else 0\n    | Flip (Val (LitV (LitLbl l))), Val (LitV (LitInt z)) =>\n        match \u03c31.(tapes) !! l with\n        | Some (n, (z' :: zs)) => (* the tape is non-empty so we consume the first integer *)\n            if bool_decide (z = z' \u2227 \u03c32 = state_upd_tapes <[l:=(n,zs)]> \u03c31) then 1 else 0\n        | Some (n, []) => (* the tape is allocated but empty, so we sample from {0 ... n} uniformly *)\n            if bool_decide (\u03c31 = \u03c32 /\\ (0 <= z <= (Z.of_nat n))%Z) then (/(INR n+1)) else 0\n        | None => (* if the tape is not allocated, we do a fair probabilistic choice between 0 and 1 *)\n            if bool_decide (\u03c31 = \u03c32 /\\ (0 <= z <= 1)%Z) then 0.5 else 0\n        end\n    | _, _ => 0\n    end.\n\n\nLocal Ltac solve_dret :=\n  match goal with\n    | |- dret _ _ = 1 => apply dret_1_1; auto\n    | |- dret _ _ = 0 => apply dret_0; intro; simplify_eq; auto\n  end.\n\n\nLemma head_step_pmf_eq e1 \u03c31 e2 \u03c32 :\n  head_step e1 \u03c31 (e2, \u03c32) = head_step_pmf e1 \u03c31 (e2, \u03c32).\nProof.\n  (* TODO: Write a tactic to simplify this proof *)\n  destruct e1; simpl; auto; do 5 try (case_match; simplify_eq; auto); try (case_bool_decide; destruct_and ?; simplify_eq);\n  try (apply dret_1_1 ; auto); try (apply dret_0; intro; simplify_eq; auto).\n  + case_match; simplify_eq; auto.\n    case_bool_decide; destruct_and ?; simplify_eq; auto.\n  + case_bool_decide; auto.\n  + case_match; auto; try (case_bool_decide; destruct_and ?; simplify_eq; auto); try simplify_eq.\n  + case_match; auto; case_match; auto; try (case_match; auto); try (case_match; auto); try simplify_eq.\n    apply dret_1_1; auto.\n  + do 4 try (case_match; simplify_eq; auto).\n    apply dret_0; intro; destruct_and ?; simplify_eq; auto.\n  + do 4 try (case_match; simplify_eq; auto).\n    destruct H1; inversion H0.\n  + do 4 try (case_match; simplify_eq; auto).\n  + try (case_match; simplify_eq; auto);\n    try (apply dbind_dret_coin_zero; auto).\n    apply dbind_dret_coin_nonzero; eauto.\n    intros ? ? H.\n    inversion H; auto.\n  + try (case_match; simplify_eq; auto);\n    try (apply dbind_dret_coin_zero; auto).\n    intros ? H2.\n    inversion H2; auto.\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + try (apply dbind_dret_coin_zero; auto).\n  + do 4 try (case_match; simplify_eq; auto);\n    try (apply dbind_dret_unif_zero; auto);\n    try (case_bool_decide; destruct_and ?; simplify_eq; auto).\n    * apply dbind_dret_unif_nonzero.\n      ++ intros ? ? H2.\n         inversion H2.\n         apply Nat2Z.inj'; auto.\n      ++ exists (Z.to_nat n0); split; try lia.\n         do 4 f_equal; lia.\n    * apply dbind_dret_unif_zero.\n      intros m Hm H2.\n      inversion H2; simplify_eq; destruct H0; split; auto.\n      lia.\n    * apply dret_1_1; auto.\n    * apply dret_0; intro H2.\n      inversion H2.\n      apply H0; auto.\n  + do 2 try (case_match; simplify_eq; auto);\n    try (apply dbind_dret_unif_zero; auto).\n    try (case_bool_decide; destruct_and ?; simplify_eq; auto).\n    * assert (0.5 = /(INR 1 + 1)) as ->; [ simpl; lra | ].\n      apply (dbind_dret_unif_nonzero).\n      ++ intros ? ? H2.\n         inversion H2.\n         apply Nat2Z.inj'; auto.\n      ++ exists (Z.to_nat n); split; try lia.\n         do 4 f_equal; lia.\n    * apply dbind_dret_unif_zero.\n      intros m Hm H2.\n      inversion H2; simplify_eq; destruct H0; split; auto.\n      lia.\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\n  + try (apply dbind_dret_unif_zero; auto).\nQed.\n\n(* helper tactics to make the [head_step] proofs more tractable *)\n#[local] Tactic Notation \"solve_ex_seriesC_0\" :=\n  by (eapply ex_seriesC_ext; [|apply ex_seriesC_0]; intros [[]]).\n\n#[local] Tactic Notation \"solve_ex_single\" :=\n  (* decompose the expression as much as possible *)\n  repeat case_match; try solve_ex_seriesC_0; subst;\n  (* use that its equivalent to a singleton *)\n  eapply ex_seriesC_ext; [|eapply (ex_seriesC_singleton (_, _) 1)];\n  (* we can now decompose more to infer which singleton it is *)\n  intros []=>/=; case_bool_decide; subst;\n  [| repeat (case_bool_decide || case_match); try done; destruct_and!; simplify_eq];\n  (* the only case we're really intered in *)\n  simplify_eq; rewrite bool_decide_eq_true_2 //.\n\n#[local] Tactic Notation \"solve_SeriesC_0\" :=\n  by (rewrite SeriesC_0; [lra|]; intros [[]]; repeat case_match).\n\n#[local] Tactic Notation \"solve_SeriesC_single\"  :=\n  repeat case_match; try solve_SeriesC_0; subst;\n  erewrite SeriesC_ext; [erewrite (SeriesC_singleton (_,_) 1); lra|];\n  intros []=>/=; case_bool_decide;\n  subst; destruct_and?;\n  [|repeat (case_bool_decide || case_match); try done; destruct_and?; simplify_eq; exfalso; auto];\n  simplify_eq; rewrite bool_decide_eq_true_2 //.\n\nLemma Z_case_of_nat (z : Z) :\n  (exists n, z = Z.of_nat n) \\/ (exists n, z = (-1 * (Z.of_nat (S n)))%Z ).\nProof.\n  destruct z as [ | m | m].\n  + left. exists 0%nat; auto.\n  + left; exists (Pos.to_nat m); lia.\n  + right.\n    destruct (Pos2Nat.is_succ m) as [x Hx].\n    exists x; lia.\nQed.\n\n(*\nProgram Definition head_step (e1 : expr) (\u03c31 : state) : distr (expr * state) :=\n  MkDistr (head_step_pmf e1 \u03c31) _ _ _.\nNext Obligation. intros ???. rewrite /head_step_pmf. repeat case_match; try lra.\n(* TODO: write a tactic that also solves this case *)\nleft.\napply (RinvN_pos n0).\nQed.\nNext Obligation.\n  intros [] ?; rewrite /head_step_pmf /det_head_step_dec.\n  - solve_ex_seriesC_0.\n  - solve_ex_seriesC_0.\n  - solve_ex_single.\n  - solve_ex_single.\n  - case_match; try solve_ex_seriesC_0; subst.\n    destruct (un_op_eval op v); [solve_ex_single|solve_ex_seriesC_0].\n  - do 2 (case_match; try solve_ex_seriesC_0); subst.\n    destruct (bin_op_eval op v v0); [solve_ex_single|solve_ex_seriesC_0].\n  - do 3 (case_match; try solve_ex_seriesC_0). destruct b; solve_ex_single.\n  - solve_ex_single.\n  - solve_ex_single.\n  - solve_ex_single.\n  - solve_ex_single.\n  - solve_ex_single.\n  - do 2 (case_match; try solve_ex_seriesC_0); solve_ex_single.\n  - solve_ex_single.\n  - do 3 (case_match; try solve_ex_seriesC_0).\n    destruct (heap \u03c31 !! l0); [solve_ex_single|solve_ex_seriesC_0].\n  - do 4 (case_match; try solve_ex_seriesC_0).\n    destruct (heap \u03c31 !! l0); [solve_ex_single|].\n    eapply ex_seriesC_ext; [|apply ex_seriesC_0]; intros [[]]=>//=.\n    repeat case_match; done.\n  - solve_ex_single.\n  - do 3 (case_match; try solve_ex_seriesC_0).\n    + eapply ex_seriesC_ext;\n        [|eapply ex_seriesC_plus;\n          [eapply (ex_seriesC_singleton (Val (LitV (LitBool true)), \u03c31) 0.5)|\n           eapply (ex_seriesC_singleton (Val (LitV (LitBool false)), \u03c31) 0.5)]].\n      intros [? \u03c32]. simplify_eq. symmetry.\n      do 3 (case_match; simpl; try lra).\n      destruct b; repeat case_bool_decide; simplify_eq; try lra.\n    + destruct (\u03c31.(tapes) !! l0) as [[n [ | b bs]]| ] eqn:Heq.\n      * apply (ex_seriesC_ext (dbind (\u03bb x, dret (Val (LitV (LitInt (Z.of_nat x))), \u03c31)) (unif_distr n))); auto.\n        intros [m \u03c32]; simplify_eq.\n        rewrite /pmf/=/dbind_pmf.\n        setoid_rewrite unif_distr_pmf.\n        destruct (decide (\u03c31 = \u03c32)) as [H\u03c31 | H\u03c31].\n        (* TODO: Clean up *)\n        -- simplify_eq.\n           assert (forall a, (if bool_decide (Nat.le a n) then / (INR n + 1) else 0) * dret (Val (LitV (LitInt a)), \u03c32) (m, \u03c32) =\n                   (if bool_decide (m = Val (LitV (LitInt a)) /\\ Nat.le a n) then / (INR n + 1) else 0)) as Haux.\n          {\n            intro a.\n            rewrite /pmf/=/dret_pmf.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra; try done.\n            destruct H1; auto.\n          }\n          setoid_rewrite Haux.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          destruct (Z_case_of_nat n0) as [[m Hm] | [m Hm]].\n          ++\n          simplify_eq.\n          assert (forall a : nat, (if bool_decide (Val (LitV (LitInt m)) = Val (LitV (LitInt a)) \u2227 Nat.le a n) then / (INR n + 1) else 0) =\n                       (if bool_decide (a = m) then\n                         (if bool_decide (m <= n)%nat then / (INR n + 1) else 0) else 0)) as Haux2.\n          { intro a.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n            - destruct H1; auto.\n            - destruct H; auto.\n          }\n          setoid_rewrite Haux2.\n          clear Haux Haux2.\n          rewrite SeriesC_singleton.\n          case_bool_decide as Haux3.\n          ** case_bool_decide as Haux4; auto.\n             destruct Haux4; split; auto; lia.\n          ** case_bool_decide as Haux4; auto.\n             destruct Haux3; lia.\n          ++\n          simplify_eq.\n          erewrite SeriesC_ext; last first.\n          **\n            intro n0.\n            rewrite bool_decide_eq_false_2; [done | ].\n            intros [? ?]; simplify_eq; lia.\n          ** rewrite SeriesC_0; auto.\n             rewrite bool_decide_eq_false_2; auto.\n             intros [? ?]; lia.\n       -- assert (forall a : nat,\n                     ((if bool_decide (Nat.le a n) then / (INR n + 1) else 0) * dret (Val (LitV (LitInt a)), \u03c31) (m, \u03c32) = 0)) as Haux2.\n          {\n            intro a.\n            rewrite /pmf/=/dret_pmf.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n          }\n          setoid_rewrite Haux2.\n          rewrite SeriesC_0; auto.\n          case_match; auto.\n          case_match; auto.\n          case_match; auto.\n          rewrite bool_decide_eq_false_2; auto.\n          intros [? ?]; auto.\n      * solve_ex_single.\n      * eapply ex_seriesC_ext;\n          [|eapply ex_seriesC_plus;\n            [eapply (ex_seriesC_singleton (Val (LitV (LitInt 0)), \u03c31) 0.5)|\n              eapply (ex_seriesC_singleton (Val (LitV (LitInt 1)), \u03c31) 0.5)]].\n        intros [? \u03c32]. simplify_eq. symmetry.\n        do 3 (case_match; simpl; try lra).\n        destruct (decide(n=0%Z)).\n        -- simplify_eq.\n           repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n           destruct H; split; auto; lia.\n        -- destruct (decide (n=1%Z)).\n           ++ simplify_eq.\n              repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n              destruct H; split; auto; lia.\n           ++ simplify_eq.\n              repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n              lia.\nQed.\nNext Obligation.\n  intros [] ?; rewrite /head_step_pmf /det_head_step_dec.\n  - solve_SeriesC_0.\n  - solve_SeriesC_0.\n  - solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - case_match; try solve_SeriesC_0; subst.\n    destruct (un_op_eval op v); [solve_SeriesC_single|solve_SeriesC_0].\n  - do 2 (case_match; try solve_SeriesC_0); subst.\n    destruct (bin_op_eval op v v0); [solve_SeriesC_single|solve_SeriesC_0].\n  - do 3 (case_match; try solve_SeriesC_0). destruct b; solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - do 2 (case_match; try solve_SeriesC_0); solve_SeriesC_single.\n  - solve_SeriesC_single.\n  - do 3 (case_match; try solve_SeriesC_0).\n    destruct (heap \u03c31 !! l0); [solve_SeriesC_single|solve_SeriesC_0].\n  - do 4 (case_match; try solve_SeriesC_0).\n    destruct (heap \u03c31 !! l0); [|solve_SeriesC_0].\n    repeat case_match; try solve_SeriesC_0; subst.\n    erewrite SeriesC_ext; [erewrite (SeriesC_singleton (Val (LitV LitUnit), _) 1); lra|].\n    intros []. symmetry.\n    case_bool_decide; simplify_eq.\n    + rewrite bool_decide_eq_true_2 //.\n    + do 4 (case_match; try done).\n      case_bool_decide; simplify_eq; destruct_and!; simplify_eq.\n  - solve_SeriesC_single.\n  - do 3 (case_match; try solve_SeriesC_0).\n    + erewrite SeriesC_ext.\n      { erewrite SeriesC_plus;\n          [|eapply (ex_seriesC_singleton (Val (LitV (LitBool true)), \u03c31) 0.5)\n           |eapply (ex_seriesC_singleton (Val (LitV (LitBool false)), \u03c31) 0.5)].\n        rewrite 2!SeriesC_singleton. lra. }\n      intros [? \u03c32]. simplify_eq.\n      do 3 (case_match; simpl; try lra).\n      destruct b; repeat case_bool_decide; simplify_eq; try lra.\n    + destruct (\u03c31.(tapes) !! l0) as [[n [ | b bs]]| ] eqn:Heq.\n\n\n      * rewrite <- (SeriesC_ext (dbind (\u03bb x, dret (Val (LitV (LitInt (Z.of_nat x))), \u03c31)) (unif_distr n))); auto.\n        intros [m \u03c32]; simplify_eq.\n        rewrite /pmf/=/dbind_pmf.\n        setoid_rewrite unif_distr_pmf.\n        destruct (decide (\u03c31 = \u03c32)) as [H\u03c31 | H\u03c31].\n        (* TODO: Clean up *)\n        -- simplify_eq.\n           assert (forall a, (if bool_decide (Nat.le a n) then / (INR n + 1) else 0) * dret (Val (LitV (LitInt a)), \u03c32) (m, \u03c32) =\n                   (if bool_decide (m = Val (LitV (LitInt a)) /\\ Nat.le a n) then / (INR n + 1) else 0)) as Haux.\n          {\n            intro a.\n            rewrite /pmf/=/dret_pmf.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra; try done.\n            destruct H1; auto.\n          }\n          setoid_rewrite Haux.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          case_match; simplify_eq; simpl; try by rewrite SeriesC_0; auto.\n          destruct (Z_case_of_nat n0) as [[m Hm] | [m Hm]].\n          ++\n          simplify_eq.\n          assert (forall a : nat, (if bool_decide (Val (LitV (LitInt m)) = Val (LitV (LitInt a)) \u2227 Nat.le a n) then / (INR n + 1) else 0) =\n                       (if bool_decide (a = m) then\n                         (if bool_decide (m <= n)%nat then / (INR n + 1) else 0) else 0)) as Haux2.\n          { intro a.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n            - destruct H1; auto.\n            - destruct H; auto.\n          }\n          setoid_rewrite Haux2.\n          clear Haux Haux2.\n          rewrite SeriesC_singleton.\n          case_bool_decide as Haux3.\n          ** case_bool_decide as Haux4; auto.\n             destruct Haux4; split; auto; lia.\n          ** case_bool_decide as Haux4; auto.\n             destruct Haux3; lia.\n          ++\n          simplify_eq.\n          erewrite SeriesC_ext; last first.\n          **\n            intro n0.\n            rewrite bool_decide_eq_false_2; [done | ].\n            intros [? ?]; simplify_eq; lia.\n          ** rewrite SeriesC_0; auto.\n             rewrite bool_decide_eq_false_2; auto.\n             intros [? ?]; lia.\n       -- assert (forall a : nat,\n                     ((if bool_decide (Nat.le a n) then / (INR n + 1) else 0) * dret (Val (LitV (LitInt a)), \u03c31) (m, \u03c32) = 0)) as Haux2.\n          {\n            intro a.\n            rewrite /pmf/=/dret_pmf.\n            repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n          }\n          setoid_rewrite Haux2.\n          rewrite SeriesC_0; auto.\n          case_match; auto.\n          case_match; auto.\n          case_match; auto.\n          rewrite bool_decide_eq_false_2; auto.\n          intros [? ?]; auto.\n      * solve_SeriesC_single.\n      * erewrite SeriesC_ext.\n        { erewrite SeriesC_plus;\n            [ | eapply (ex_seriesC_singleton (Val (LitV (LitInt 0)), \u03c31) 0.5)|\n              eapply (ex_seriesC_singleton (Val (LitV (LitInt 1)), \u03c31) 0.5)].\n          rewrite 2!SeriesC_singleton. lra. }\n        intros [? \u03c32]. simplify_eq.\n        do 3 (case_match; simpl; try lra).\n        destruct (decide(n=0%Z)).\n        -- simplify_eq.\n           repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n           destruct H; split; auto; lia.\n        -- destruct (decide (n=1%Z)).\n           ++ simplify_eq.\n              repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n              destruct H; split; auto; lia.\n           ++ simplify_eq.\n              repeat case_bool_decide; destruct_and?; simplify_eq; try lra.\n              lia.\nQed.\n*)\n\nDefinition valid_add_int_to_tape (t : tape) (z : Z) : Prop :=\n  ( 0 <= z <= fst t)%Z.\n\nDefinition add_int_to_tape (t : tape) (z : Z) : tape :=\n  let: (n', zs) := t in (n', zs ++ [z]).\n\nFixpoint tape_step_pmf (n m : nat) (t1 : list Z) (t2 : list Z)  : R  :=\n  if bool_decide (n = m) then\n    match t1, t2 with\n    | [], [z] =>  if bool_decide (0 <= z /\\ z <= n)%Z then /(INR n + 1) else 0\n    | x::xs, z::zs =>\n        if bool_decide (x = z) then tape_step_pmf n m xs zs\n        else 0\n    | _, _ => 0\n    end\n  else 0.\n\n\nDefinition valid_state_step (\u03c31 : state) (\u03b1 : loc) (\u03c32 : state) (n : nat) (z : Z) : Prop :=\n  (* [\u03b1] has to be the label of an allocated tape *)\n  \u03b1 \u2208 dom \u03c31.(tapes) \u2227 \u03b1 \u2208 dom \u03c32.(tapes) /\\\n  (* the heap is the same but we add a bit to the [\u03b1] tape *)\n  let: (n' , zs) := (\u03c31.(tapes) !!! \u03b1) in\n  n = n' /\\ (0 <= z <= Z.of_nat n)%Z /\\ \u03c32.(tapes) !!! \u03b1 = (n, zs ++ [z]).\n\nLocal Instance valid_state_step_dec \u03c31 \u03b1 \u03c32 n z : Decision (valid_state_step \u03c31 \u03b1 \u03c32 n z).\nProof.\n  apply _.\nDefined.\n\n(*\nDefinition state_step_pmf (\u03c31 : state) (\u03b1 : loc) (\u03c32 : state) : R :=\n  if bool_decide (\u03b1 \u2208 dom \u03c31.(tapes)) then\n    match (\u03c31.(tapes) !!! \u03b1), (\u03c32.(tapes) !!! \u03b1) with\n      | (n, xs), (m, zs) => if bool_decide(valid_state_step \u03c31 \u03b1 \u03c32 n) then / (INR n + 1) else 0\n    end\n  else 0.\n\nLemma state_step_pmf_eq \u03c31 \u03b1 \u03c32 :\n  \u03b1 \u2208 dom \u03c31.(tapes) \u2192\n  state_step_pmf \u03c31 \u03b1 \u03c32 =\n    let (n, zs) := \u03c31.(tapes) !!! \u03b1 in\n    if bool_decide (exists z, \u03c32.(tapes) !!! \u03b1 = (n, zs ++ [z]) /\\\n                                 (0 <= z < n)%Z ) then /(INR n + 1) else 0.\n\nProgram Definition tape_step (n m : nat) (t : list Z) : distr (list Z) :=\n  MkDistr (tape_step_pmf n m t) _ _ _.\nNext Obligation.\n  intros n m t1 t2.\n  induction t1; simpl; destruct (bool_decide (n = m)); try lra.\n  + case_match; try lra.\n    case_match; try lra.\n    case_bool_decide; try lra.\n    admit.\n  + case_match; try lra.\n    case_bool_decide; try lra.\n\n\n(*\nLocal Instance valid_add_int_to_tape_dec t1 t2 z : Decision (valid_add_int_to_tape t1 t2 z).\nProof. apply _. Qed.\n\n\nDefinition valid_state_step (\u03c31 : state) (\u03b1 : loc) (\u03c32 : state) : Prop :=\n  (* [\u03b1] has to be the label of an allocated tape *)\n  \u03b1 \u2208 dom \u03c31.(tapes) \u2227 \u03b1 \u2208 dom \u03c32.(tapes) /\\\n  (* the heap is the same but we add a bit to the [\u03b1] tape *)\n  \u2203 z, valid_add_int_to_tape (\u03c31.(tapes) !!! \u03b1) (\u03c32.(tapes) !!! \u03b1) z.\n\nLocal Instance valid_state_step_dec \u03c31 \u03b1 \u03c32 : Decision (valid_state_step \u03c31 \u03b1 \u03c32).\nProof.\n  apply and_dec; [apply _ | ].\n  apply and_dec; [apply _ | ].\n  admit.\n  Admitted.\n*)\n*)\n\n\nDefinition state_step (\u03c31 : state) (\u03b1 : loc) : distr state :=\n  if bool_decide (\u03b1 \u2208 dom \u03c31.(tapes)) then\n    let: (n , zs) := (\u03c31.(tapes) !!! \u03b1) in\n    dmap (\u03bb z, state_upd_tapes (<[\u03b1 := (n , zs ++ [Z.of_nat z])]>) \u03c31) (unif_distr n)\n  else dzero.\n\n(*\nLocal Instance valid_state_step_dec \u03c31 \u03b1 \u03c32 n : Decision (valid_state_step \u03c31 \u03b1 \u03c32 n).\nAdmitted.\n\nDefinition state_step_pmf (\u03c31 : state) (\u03b1 : loc) (\u03c32 : state) : R :=\n  if bool_decide (\u03b1 \u2208 dom \u03c31.(tapes)) then\n    match (\u03c31.(tapes) !!! \u03b1), (\u03c32.(tapes) !!! \u03b1) with\n      | (n, xs), (m, zs) => if bool_decide(valid_state_step \u03c31 \u03b1 \u03c32 n) then / (INR n + 1) else 0\n    end\n  else 0.\n\n\nProgram Definition state_step (\u03c31 : state) (\u03b1 : loc) : distr state :=\n  MkDistr (state_step_pmf \u03c31 \u03b1) _ _ _.\nNext Obligation.\n  rewrite /state_step_pmf; intros. case_bool_decide; try lra.\n  destruct (tapes \u03c31 !!! \u03b1).\n  destruct (tapes a !!! \u03b1).\n  case_bool_decide; try lra.\n  left.\n  apply RinvN_pos.\nQed.\nNext Obligation.\n  intros.\n  rewrite /state_step_pmf.\n  destruct (decide (\u03b1 \u2208 dom \u03c31)).\n  -\n\nDefinition state_step_pmf (\u03c31 : state) (\u03b1 : loc) (\u03c32 : state) : R :=\n  if bool_decide (valid_state_step \u03c31 \u03b1 \u03c32) then 0.5 else 0.\n\nLemma state_step_pmf_eq \u03c31 \u03b1 \u03c32 :\n  \u03b1 \u2208 dom \u03c31.(tapes) \u2192\n  state_step_pmf \u03c31 \u03b1 \u03c32 =\n    (if bool_decide (\u03c32 = state_upd_tapes (<[\u03b1 := \u03c31.(tapes) !!! \u03b1 ++ [true]]>) \u03c31)\n     then 0.5 else 0)\n  + (if bool_decide (\u03c32 = state_upd_tapes (<[\u03b1 := \u03c31.(tapes) !!! \u03b1 ++ [false]]>) \u03c31)\n     then 0.5 else 0).\nProof.\n  intros H\u03b1.\n  rewrite /pmf /= /state_step_pmf /valid_state_step.\n  case_bool_decide as Heq.\n  - destruct Heq as [Hdom [[] ->]]; simplify_map_eq.\n    + rewrite bool_decide_eq_true_2 // bool_decide_eq_false_2; [lra|].\n      case. rewrite map_eq_iff => /(_ \u03b1) ?. simplify_map_eq.\n    + rewrite bool_decide_eq_false_2.\n      { rewrite bool_decide_eq_true_2 //. lra. }\n      case. rewrite map_eq_iff => /(_ \u03b1) ?. simplify_map_eq.\n  - apply not_and_l in Heq as [|Heq]; [done|].\n    rewrite !bool_decide_eq_false_2; [lra| |]; intros; eauto.\nQed.\n\nProgram Definition state_step (\u03c31 : state) (\u03b1 : loc) : distr state :=\n  MkDistr (state_step_pmf \u03c31 \u03b1) _ _ _.\nNext Obligation. rewrite /state_step_pmf. intros. case_bool_decide; lra. Qed.\nNext Obligation.\n  intros \u03c31 \u03b1.\n  destruct (decide (\u03b1 \u2208 dom \u03c31.(tapes))).\n  - eapply ex_seriesC_ext.\n    { intros \u03c32. rewrite state_step_pmf_eq //. }\n    eapply ex_seriesC_plus; eapply ex_seriesC_singleton.\n  - eapply (ex_seriesC_ext (\u03bb _, 0)); [|eapply ex_seriesC_0].\n    intros ?. rewrite /state_step_pmf bool_decide_eq_false_2 //.\n    by intros [].\nQed.\nNext Obligation.\n  intros \u03c31 \u03b1.\n  destruct (decide (\u03b1 \u2208 dom \u03c31.(tapes))).\n  - erewrite SeriesC_ext.\n    2 : { intros \u03c32. rewrite state_step_pmf_eq //. }\n    erewrite SeriesC_plus; [|eapply ex_seriesC_singleton..].\n    rewrite 2!SeriesC_singleton. lra.\n  - rewrite SeriesC_0; [lra|]. intros ?.\n    rewrite /state_step_pmf bool_decide_eq_false_2 //. by intros [].\nQed.\n*)\n\n(** Basic properties about the language *)\nGlobal Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. induction Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\n\nLemma fill_item_val Ki e :\n  is_Some (to_val (fill_item Ki e)) \u2192 is_Some (to_val e).\nProof. intros [v ?]. induction Ki; simplify_option_eq; eauto. Qed.\n\nLemma val_head_stuck e \u03c3 \u03c1 :\n  head_step e \u03c3 \u03c1 > 0 \u2192 to_val e = None.\nProof. destruct \u03c1, e; [|done..]. rewrite /pmf /=. lra. Qed.\nLemma head_ctx_step_val Ki e \u03c3 \u03c1 :\n  head_step (fill_item Ki e) \u03c3 \u03c1 > 0 \u2192 is_Some (to_val e).\nProof. destruct \u03c1, Ki; rewrite /pmf/=; repeat case_match; try (done || lra);\n         try (inversion H; lra).\nQed.\n\n(** A relational definition of the support of [head_step] to make it possible to\n    do inversion and prove reducibility easier c.f. lemma below *)\nInductive head_step_rel : expr \u2192 state \u2192 expr \u2192 state \u2192 Prop :=\n| RecS f x e \u03c3 :\n  head_step_rel (Rec f x e) \u03c3 (Val $ RecV f x e) \u03c3\n| PairS v1 v2 \u03c3 :\n  head_step_rel (Pair (Val v1) (Val v2)) \u03c3 (Val $ PairV v1 v2) \u03c3\n| InjLS v \u03c3 :\n  head_step_rel (InjL $ Val v) \u03c3 (Val $ InjLV v) \u03c3\n| InjRS v \u03c3 :\n  head_step_rel (InjR $ Val v) \u03c3 (Val $ InjRV v) \u03c3\n| BetaS f x e1 v2 e' \u03c3 :\n  e' = subst' x v2 (subst' f (RecV f x e1) e1) \u2192\n  head_step_rel (App (Val $ RecV f x e1) (Val v2)) \u03c3 e' \u03c3\n| UnOpS op v v' \u03c3 :\n  un_op_eval op v = Some v' \u2192\n  head_step_rel (UnOp op (Val v)) \u03c3 (Val v') \u03c3\n| BinOpS op v1 v2 v' \u03c3 :\n  bin_op_eval op v1 v2 = Some v' \u2192\n  head_step_rel (BinOp op (Val v1) (Val v2)) \u03c3 (Val v') \u03c3\n| IfTrueS e1 e2 \u03c3 :\n  head_step_rel (If (Val $ LitV $ LitBool true) e1 e2) \u03c3 e1 \u03c3\n| IfFalseS e1 e2 \u03c3 :\n  head_step_rel (If (Val $ LitV $ LitBool false) e1 e2) \u03c3 e2 \u03c3\n| FstS v1 v2 \u03c3 :\n  head_step_rel (Fst (Val $ PairV v1 v2)) \u03c3 (Val v1) \u03c3\n| SndS v1 v2 \u03c3 :\n  head_step_rel (Snd (Val $ PairV v1 v2)) \u03c3 (Val v2) \u03c3\n| CaseLS v e1 e2 \u03c3 :\n  head_step_rel (Case (Val $ InjLV v) e1 e2) \u03c3 (App e1 (Val v)) \u03c3\n| CaseRS v e1 e2 \u03c3 :\n  head_step_rel (Case (Val $ InjRV v) e1 e2) \u03c3 (App e2 (Val v)) \u03c3\n| AllocS v \u03c3 l :\n  l = fresh_loc \u03c3.(heap) \u2192\n  head_step_rel (Alloc (Val v)) \u03c3\n    (Val $ LitV $ LitLoc l) (state_upd_heap <[l:=v]> \u03c3)\n| LoadS l v \u03c3 :\n  \u03c3.(heap) !! l = Some v \u2192\n  head_step_rel (Load (Val $ LitV $ LitLoc l)) \u03c3 (of_val v) \u03c3\n| StoreS l v w \u03c3 :\n  \u03c3.(heap) !! l = Some v \u2192\n  head_step_rel (Store (Val $ LitV $ LitLoc l) (Val w)) \u03c3\n    (Val $ LitV LitUnit) (state_upd_heap <[l:=w]> \u03c3)\n| AllocTapeS n \u03c3 l :\n  l = fresh_loc \u03c3.(tapes) \u2192\n  head_step_rel (AllocTape n) \u03c3\n    (Val $ LitV $ LitLbl l) (state_upd_tapes <[l:=(n,[])]> \u03c3)\n| FlipTapeS l n z zs \u03c3 :\n  \u03c3.(tapes) !! l = Some (n, (z :: zs)) \u2192\n  head_step_rel (Flip (Val (LitV (LitLbl l)))) \u03c3 (Val $ LitV $ LitInt z) (state_upd_tapes <[l:=(n,zs)]> \u03c3)\n| FlipTapeEmptyS l n z \u03c3 :\n  \u03c3.(tapes) !! l = Some (n,[]) ->\n  (0 <= z <= Z.of_nat n)%Z ->\n  head_step_rel (Flip (Val (LitV (LitLbl l)))) \u03c3 (Val $ LitV $ LitInt z) \u03c3\n| FlipTapeUnallocS l z \u03c3 :\n  \u03c3.(tapes) !! l = None \u2192\n  (0 <= z <= 1)%Z ->\n  head_step_rel (Flip (Val (LitV (LitLbl l)))) \u03c3 (Val $ LitV $ LitInt z) \u03c3\n| FlipNoTapeS b \u03c3 :\n  head_step_rel (Flip (Val (LitV LitUnit))) \u03c3 (Val $ LitV $ LitBool b) \u03c3.\n\nCreate HintDb head_step.\nGlobal Hint Constructors head_step_rel : head_step.\n\nInductive state_step_rel : state \u2192 loc \u2192 state \u2192 Prop :=\n| AddTapeS z \u03b1 n zs \u03c3 :\n  \u03b1 \u2208 dom \u03c3.(tapes) \u2192\n  (\u03c3.(tapes) !!! \u03b1) = (n, zs) ->\n  (0 <= z <= Z.of_nat n)%Z ->\n  state_step_rel \u03c3 \u03b1 (state_upd_tapes <[\u03b1 := (n, zs ++ [z])]> \u03c3).\n\n(** A computational/destructing version of [inv_head_step] - only to be used for\n    the lemma below *)\nLocal Ltac inv_head_step'' :=\n  repeat\n    match goal with\n    | _ => progress simplify_map_eq/= (* simplify memory stuff *)\n    | H : to_val _ = Some _ |- _ => apply of_to_val in H\n    | H : is_Some (_ !! _) |- _ => destruct H\n    | H : @pmf _ _ _ (head_step ?e _) _ > 0  |- _ =>\n        rewrite /pmf /= in H;\n        repeat ((case_bool_decide_and_destruct in H || case_match); try (lra || done));\n        destruct_and?;\n        try (lra || done)\n    | H : bool_decide _ = _ |- _ =>\n        case_bool_decide; destruct_and?;\n        simplify_eq;\n        try lra;\n        try done;\n        eauto with head_step\n    end.\n\nLemma head_step_support_equiv_rel e1 e2 \u03c31 \u03c32 :\n  head_step e1 \u03c31 (e2, \u03c32) > 0 \u2194 head_step_rel e1 \u03c31 e2 \u03c32.\nProof.\n  split.\n  - intros Hstep.\n    rewrite head_step_pmf_eq in Hstep.\n    destruct e1; inv_head_step''; eauto with head_step;\n    (* TODO: Maybe write tactic to optimize this proof *)\n    (repeat case_match; try lra; try done;\n      case_bool_decide; destruct_and?; simplify_eq; eauto with head_step).\n      destruct H8.\n      eapply StoreS; eauto.\n  - rewrite head_step_pmf_eq.\n    inversion 1;\n      rewrite /pmf /= /head_step_pmf //; simplify_map_eq;\n      rewrite ?bool_decide_eq_true_2 //; try lra.\n    apply RinvN_pos.\nQed.\n\n(* NB: Classical proof *)\nLemma state_step_support_equiv_rel \u03c31 \u03b1 \u03c32 :\n  state_step \u03c31 \u03b1 \u03c32 > 0 \u2194 state_step_rel \u03c31 \u03b1 \u03c32.\nProof.\n  split.\n  - rewrite /pmf/=/state_step/=.\n    intro H; case_bool_decide.\n    + destruct (tapes \u03c31 !!! \u03b1) as (n & zs) eqn:H\u03b1.\n      simpl in H.\n      rewrite /dbind_pmf {2}/pmf/=/dret_pmf in H.\n      assert (\u2203 a, (0 <= a <= n)%Z /\\ \u03c32 = state_upd_tapes <[\u03b1:=(n, zs ++ [a])]> \u03c31) as (a & Ha1 & Ha2).\n     {\n       apply NNP_P.\n       intro H2.\n       pose proof (not_exists_forall_not _ _ H2) as H3.\n       simpl in H3.\n       rewrite (SeriesC_ext _ (\u03bb x, 0)) in H; last first.\n       - intro m.\n         apply Rmult_eq_0_compat.\n         specialize (H3 m).\n         apply not_and_or_not in H3; destruct H3.\n         + left.\n           rewrite unif_distr_pmf.\n           rewrite bool_decide_eq_false_2; auto; intro.\n           try lia.\n         + right.\n           rewrite bool_decide_eq_false_2; auto.\n      - rewrite SeriesC_0 in H; auto; lra.\n     }\n     rewrite Ha2.\n     eapply AddTapeS; auto.\n    + simpl in H; lra.\n  -\n    intro H; inversion H; simpl.\n    rewrite /pmf/=/state_step/=.\n    rewrite bool_decide_eq_true_2; auto.\n    rewrite H1; simpl.\n    rewrite /dbind_pmf.\n    apply Rlt_gt.\n    eapply (Rlt_le_trans); last first.\n    + apply (SeriesC_ge_elem _ (Z.to_nat z)); simpl; auto.\n      * intro x; auto.\n        apply Rmult_le_pos; auto.\n      * apply (ex_seriesC_le _ (unif_distr n)); auto.\n        intro m; split; [apply Rmult_le_pos; auto | ].\n        rewrite <- Rmult_1_r.\n        apply Rmult_le_compat_l; auto.\n    + simpl.\n      apply Rmult_lt_0_compat; auto.\n      * rewrite /pmf/=/unif_distr_pmf.\n        rewrite bool_decide_eq_true_2; try lia.\n        apply RinvN_pos.\n      * rewrite /pmf/=/dret_pmf.\n        rewrite bool_decide_eq_true_2; try lra.\n        do 5 f_equal; lia.\nQed.\n\n\nLemma foo {A} (l : list A) :\n (exists z zs, l = z :: zs) ->\n       (exists y ys, l = ys ++ [y]).\nProof.\n  intros (z & zs & Hz).\n  assert (l \u2260 []) as H; auto.\n  { rewrite Hz; intro H; inversion H. }\n  pose proof (exists_last H) as (y & ys & Hy);\n  eauto.\nQed.\n\nLemma bar {A} (l : list A) :\n  (exists y ys, l = ys ++ [y]) ->\n  (exists z zs, l = z :: zs).\nProof.\n  destruct l.\n  - intros (y & ys & Hy).\n    pose proof (app_cons_not_nil _ _ _ Hy); done.\n  - intros (y & ys & Hy).\n    destruct ys as [ | x xs].\n    + exists y. exists []. auto.\n    + exists x. exists (xs ++ [y]). auto.\nQed.\n\nLemma state_step_head_step_not_stuck e \u03c3 \u03c3' \u03b1 :\n  state_step \u03c3 \u03b1 \u03c3' > 0 \u2192 (\u2203 \u03c1, head_step e \u03c3 \u03c1 > 0) \u2194 (\u2203 \u03c1', head_step e \u03c3' \u03c1' > 0).\nProof.\n  rewrite state_step_support_equiv_rel.\n  inversion 1; simplify_eq.\n  split; intros [[e' \u03c3'] Hs].\n  - rewrite head_step_support_equiv_rel in Hs.\n    inversion_clear Hs;\n      try by eexists (_,_); eapply head_step_support_equiv_rel;\n      econstructor; eauto; simpl.\n    + pose proof (bar (zs ++ [z])).\n        assert (\u2203 (y : Z) (ys : list Z), zs ++ [z] = ys ++ [y]) as Haux; eauto.\n        specialize (H4 Haux) as (? & ? & ?); eauto.\n        rewrite H4.\n      destruct (decide (l = \u03b1)); subst;\n        eexists (_,_); eapply head_step_support_equiv_rel; econstructor.\n      * rewrite lookup_insert //.\n      * rewrite lookup_insert_ne //.\n    + destruct (decide (l = \u03b1)); subst.\n      * pose proof (bar (zs ++ [z])).\n        assert (\u2203 (y : Z) (ys : list Z), zs ++ [z] = ys ++ [y]) as Haux; eauto.\n        specialize (H5 Haux) as (x & xs & Hx); eauto.\n        rewrite Hx.\n        exists ((Val (LitV (LitInt x))),(state_upd_tapes <[\u03b1:=(n, xs)]> \u03c3')).\n        eapply head_step_support_equiv_rel; destruct_or?.\n        rewrite <- (state_upd_tapes_twice \u03c3' \u03b1 n (x :: xs) xs).\n        eapply FlipTapeS.\n        simpl.\n        apply lookup_insert.\n      * exists ((Val (LitV (LitInt 0))),(state_upd_tapes <[\u03b1:=(n, zs ++ [z])]> \u03c3')).\n        eapply head_step_support_equiv_rel; destruct_or?.\n        eapply (FlipTapeEmptyS l n0); eauto; try lia.\n        rewrite lookup_insert_ne; auto.\n    + destruct (decide (l = \u03b1)); subst.\n      * pose proof (bar (zs ++ [z])).\n        assert (\u2203 (y : Z) (ys : list Z), zs ++ [z] = ys ++ [y]) as Haux; eauto.\n        specialize (H5 Haux) as (x & xs & Hx); eauto.\n        rewrite Hx.\n        exists ((Val (LitV (LitInt x))),(state_upd_tapes <[\u03b1:=(n, xs)]> \u03c3')).\n        eapply head_step_support_equiv_rel; destruct_or?.\n        rewrite <- (state_upd_tapes_twice \u03c3' \u03b1 n (x :: xs) xs).\n        eapply FlipTapeS.\n        simpl.\n        apply lookup_insert.\n      * exists ((Val (LitV (LitInt 0))),(state_upd_tapes <[\u03b1:=(n, zs ++ [z])]> \u03c3')).\n        eapply head_step_support_equiv_rel; destruct_or?.\n        eapply (FlipTapeUnallocS l); eauto; try lia.\n        rewrite lookup_insert_ne; auto.\n   - rewrite head_step_support_equiv_rel in Hs.\n     inversion_clear Hs;\n       try by eexists (_,_); eapply head_step_support_equiv_rel;\n           econstructor; eauto; simpl.\n     + destruct (decide (l = \u03b1)); subst.\n       * destruct (tapes \u03c3 !! \u03b1) eqn:Heq.\n         -- destruct t as [m [ | x xs]].\n            { eexists (Val (LitV (LitInt 0)),_); eapply head_step_support_equiv_rel.\n              eapply FlipTapeEmptyS; eauto. lia. }\n            eexists (_,_); eapply head_step_support_equiv_rel.\n            by eapply FlipTapeS.\n         -- eexists (Val (LitV (LitInt 0)),_); eapply head_step_support_equiv_rel.\n            eapply FlipTapeUnallocS; eauto. lia.\n       * rewrite lookup_insert_ne // in H3.\n         eexists (_,_); eapply head_step_support_equiv_rel.\n         by econstructor.\n     + destruct (decide (l = \u03b1)); subst.\n       * destruct_or?; simplify_map_eq.\n         symmetry in H5.\n         apply app_cons_not_nil in H5; done.\n       * eexists (Val (LitV (LitInt 0)), \u03c3). eapply head_step_support_equiv_rel.\n         simplify_map_eq.\n         eapply FlipTapeEmptyS; eauto. lia.\n     + destruct (decide (l = \u03b1)); subst.\n       * destruct_or?; simplify_map_eq.\n       * eexists (Val (LitV (LitInt 0)), \u03c3); eapply head_step_support_equiv_rel.\n         simplify_map_eq.\n         eapply FlipTapeUnallocS; eauto. lia.\n  Unshelve. all: apply true.  (* FlipNoTapeS case *)\nQed.\n\nLemma state_step_mass \u03c3 \u03b1 :\n  \u03b1 \u2208 dom \u03c3.(tapes) \u2192 SeriesC (state_step \u03c3 \u03b1) = 1.\nProof.\n  intros Hdom.\n  rewrite /pmf /=.\n  rewrite /state_step.\n  rewrite bool_decide_eq_true_2; simpl; auto.\n  pose proof ((elem_of_dom (tapes \u03c3) \u03b1)) as (H2 & ?); auto.\n  specialize (H2 Hdom).\n  destruct H2 as [t Hx].\n  setoid_rewrite lookup_total_correct; eauto.\n  destruct t.\n  (* Hack to avoid Coq's overzealous simplification *)\n  assert\n    (SeriesC (let (pmf, _, _, _) := dmap (\u03bb z : nat, state_upd_tapes <[\u03b1:=(n, l ++ [Z.of_nat z])]> \u03c3) (unif_distr n) in pmf) =\n     SeriesC (dmap (\u03bb z : nat, state_upd_tapes <[\u03b1:=(n, l ++ [Z.of_nat z])]> \u03c3) (unif_distr n))) as ->; auto.\n  rewrite <- dmap_mass.\n  apply SeriesC_unif_distr.\nQed.\n\nLemma head_step_mass e \u03c3 :\n  (\u2203 \u03c1, head_step e \u03c3 \u03c1 > 0) \u2192 SeriesC (head_step e \u03c3) = 1.\nProof.\n  intros [[] Hs%head_step_support_equiv_rel].\n  inversion Hs; simplify_eq;\n   (* horrible automation to discharge all the the determinsitic cases *)\n   try by match goal with\n    | H : head_step_rel _ _ ?e ?\u03c3 |- _ =>\n        erewrite SeriesC_ext; [eapply (SeriesC_singleton (e, \u03c3))|];\n        intros [];\n        case_bool_decide; simplify_eq;\n        rewrite head_step_pmf_eq;\n        simplify_map_eq;\n        [rewrite bool_decide_eq_true_2 //\n        |repeat case_match; try done; simplify_eq; inv_head_step'']\n     end.\n  (* TODO: some nicer lemma for proving the following? Lots of duplication *)\n  - rewrite /head_step/=.\n    rewrite H.\n    rewrite (SeriesC_ext _ (dmap (\u03bb m : nat, (Val (LitV (LitInt m)), s)) (unif_distr n))).\n    2:{ intro; auto. }\n    rewrite <- dmap_mass.\n    apply SeriesC_unif_distr.\n  - rewrite /head_step/=.\n    rewrite H.\n    rewrite (SeriesC_ext _ (dmap (\u03bb m : nat, (Val (LitV (LitInt m)), s)) (unif_distr 1))).\n    2:{ intro; auto. }\n    rewrite <- dmap_mass.\n    apply SeriesC_unif_distr.\n  - rewrite /head_step/=.\n    rewrite (SeriesC_ext _ (dmap (\u03bb b0 : bool, (Val (LitV (LitBool b0)), s)) (fair_coin))).\n    2:{ intro; auto. }\n    rewrite <- dmap_mass.\n    apply SeriesC_fair_coin.\n Qed.\n\nLemma fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n  to_val e1 = None \u2192 to_val e2 = None \u2192\n  fill_item Ki1 e1 = fill_item Ki2 e2 \u2192 Ki1 = Ki2.\nProof. destruct Ki2, Ki1; naive_solver eauto with f_equal. Qed.\n\nFixpoint height (e : expr) : nat :=\n  match e with\n  | Val _ => 1\n  | Var _ => 1\n  | Rec _ _ e => 1 + height e\n  | App e1 e2 => 1 + height e1 + height e2\n  | UnOp _ e => 1 + height e\n  | BinOp _ e1 e2 => 1 + height e1 + height e2\n  | If e0 e1 e2 => 1 + height e0 + height e1 + height e2\n  | Pair e1 e2 => 1 + height e1 + height e2\n  | Fst e => 1 + height e\n  | Snd e => 1 + height e\n  | InjL e => 1 + height e\n  | InjR e => 1 + height e\n  | Case e0 e1 e2 => 1 + height e0 + height e1 + height e2\n  | Alloc e => 1 + height e\n  | Load e => 1 + height e\n  | Store e1 e2 => 1 + height e1 + height e2\n  | AllocTape n => 1\n  | Flip e => 1 + height e\n  end.\n\nDefinition expr_ord (e1 e2 : expr) : Prop := (height e1 < height e2)%nat.\n\nLemma expr_ord_wf' h e : (height e \u2264 h)%nat \u2192 Acc expr_ord e.\nProof.\n  rewrite /expr_ord. revert e; induction h.\n  { destruct e; simpl; lia. }\n  intros []; simpl;\n    constructor; simpl; intros []; eauto with lia.\nDefined.\n\nLemma expr_ord_wf : well_founded expr_ord.\nProof. red; intro; eapply expr_ord_wf'; eauto. Defined.\n\n(* TODO: this proof is slow, but I do not see how to make it faster... *)\nLemma decomp_expr_ord Ki e e' : decomp_item e = Some (Ki, e') \u2192 expr_ord e' e.\nProof.\n  rewrite /expr_ord /decomp_item.\n  destruct e; try done;\n  destruct Ki; simpl;\n    repeat case_match; intros [=]; subst; lia.\nQed.\n\nLemma decomp_fill_item Ki e :\n  to_val e = None \u2192 decomp_item (fill_item Ki e) = Some (Ki, e).\nProof. destruct Ki; simpl; by repeat case_match. Qed.\n\n(* TODO: this proof is slow, but I do not see how to make it faster... *)\nLemma decomp_fill_item_2 e e' Ki :\n  decomp_item e = Some (Ki, e') \u2192 fill_item Ki e' = e \u2227 to_val e' = None.\nProof.\n  destruct e; try done;\n    destruct Ki; simpl;\n    repeat case_match; intros [=]; subst; done.\nQed.\n\nDefinition get_active (\u03c3 : state) : list loc := elements (dom \u03c3.(tapes)).\n\nLemma state_step_get_active_mass \u03c3 \u03b1 :\n  \u03b1 \u2208 get_active \u03c3 \u2192 SeriesC (state_step \u03c3 \u03b1) = 1.\nProof. rewrite elem_of_elements. apply state_step_mass. Qed.\n\nLemma prob_lang_mixin :\n  EctxiLanguageMixin of_val to_val fill_item decomp_item expr_ord head_step state_step get_active.\nProof.\n  split; apply _ || eauto using to_of_val, of_to_val, val_head_stuck,\n    state_step_head_step_not_stuck, state_step_get_active_mass, head_step_mass,\n    fill_item_val, fill_item_no_val_inj, head_ctx_step_val,\n    decomp_fill_item, decomp_fill_item_2, expr_ord_wf, decomp_expr_ord.\nQed.\n\nEnd prob_lang.\n\n(** Language *)\nCanonical Structure prob_ectxi_lang := EctxiLanguage prob_lang.get_active prob_lang.prob_lang_mixin.\nCanonical Structure prob_ectx_lang := EctxLanguageOfEctxi prob_ectxi_lang.\nCanonical Structure prob_lang := LanguageOfEctx prob_ectx_lang.\n\n(* Prefer prob_lang names over ectx_language names. *)\nExport prob_lang.\n\nDefinition cfg : Type := expr * state.\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/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.1816022601890156}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import State Monad rBPFMonadOp.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nCheck upd_pc_incr.\nupd_pc_incr\n     : M unit\n *)\n\nSection Upd_pc_incr.\n  Context{S:special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [].\n  Definition res : Type := unit.\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := upd_pc_incr.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_upd_pc_incr.\n\n  Definition modifies  := ModSomething. (* of the C code *)\n  (* [match_mem] related the Coq monadic state and the C memory *)\n  (*Definition match_mem : stateM -> val -> Memory.Mem.mem -> Prop := fun stM v m => match_meminj_state state_block inject_id stM m.*)\n\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) ((unit:Type) ::args) :=\n    dcons  (fun (x:unit) => StateLess _ (is_state_handle))\n                             (DList.DNil _).\n\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun _  => StateLess _ (fun v => v = Vundef).\n\n  Lemma correct_function_upd_pc_incr : forall a, correct_function _ p args res f fn modifies false match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    repeat intro.\n    unfold f; simpl.\n    destruct upd_pc_incr eqn: Hupd_pc; [| constructor].\n    destruct p0.\n    intros.\n    unfold INV in H.\n    get_invariant _st. unfold eval_inv,is_state_handle in c. subst.\n\n    (** we need to get the proof of `upd_pc_incr` load/store permission *)\n    apply (upd_pc_store  _ (Int.add (pc_loc st) (Int.repr 1)) _) in MS as Hstore.\n    destruct Hstore as (m1 & Hstore).\n    (** pc \\in [ (state_block,0), (state_block,8) ) *)\n\n    (**according to the type of upd_pc_incr:\n         static void upd_pc_incr(struct bpf_state* st) \n       1. return value should be Vundef (i.e. void)\n       2. the new memory should change the value of pc, i.e. m_pc\n      *)\n    exists Vundef, m1, Events.E0.\n\n    split; unfold step2.\n    - (* goal: Smallstep.star  _ _ (State _ (Ssequence ... *)\n      repeat forward_star.\n\n      rewrite Ptrofs.add_zero.\n      destruct MS as (_ , Hpc, _, _, _, _, _, _, _, _).\n      fold Ptrofs.zero in Hpc.\n      rewrite Hpc; reflexivity.\n      reflexivity.\n      reflexivity.\n    - split_and; auto.\n      constructor.\n      eapply upd_pc_preserves_match_state; eauto.\n      unfold upd_pc_incr in Hupd_pc.\n      context_destruct_if_inversion.\n      unfold State.upd_pc, State.upd_pc_incr.\n      reflexivity.\nQed.\n\nEnd Upd_pc_incr.\n\nExisting Instance correct_function_upd_pc_incr.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_upd_pc_incr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.1816022531770288}}
{"text": "(** * Definition of a boolean-returning CFG parser-recognizer *)\nRequire Import Coq.Lists.List Coq.Program.Program Coq.Program.Wf Coq.Arith.Wf_nat Coq.Arith.Compare_dec Coq.Classes.RelationClasses Coq.Strings.String.\nRequire Import Coq.omega.Omega.\nRequire Import ParsingParses.Parsers.ContextFreeGrammar ParsingParses.Parsers.BooleanRecognizer ParsingParses.Parsers.MinimalParse.\nRequire Import ParsingParses.Parsers.BaseTypes ParsingParses.Parsers.BooleanBaseTypes.\nRequire Import ParsingParses.Parsers.Splitters.RDPList ParsingParses.Parsers.Splitters.BruteForce.\nRequire Import ParsingParses.Parsers.MinimalParseOfParse.\nRequire Import ParsingParses.Parsers.ContextFreeGrammarProperties ParsingParses.Parsers.WellFoundedParse.\nRequire Import ParsingParses.Common ParsingParses.Common.Wf.\nRequire Import Coq.Logic.Eqdep_dec.\n\nLocal Hint Extern 0 =>\nmatch goal with\n  | [ H : false = true |- _ ] => solve [ destruct (Bool.diff_false_true H) ]\n  | [ H : true = false |- _ ] => solve [ destruct (Bool.diff_true_false H) ]\nend.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nLocal Open Scope string_like_scope.\n\nSection sound.\n  Section general.\n    Context CharType (String : string_like CharType) (G : grammar CharType).\n    Context {data : @boolean_parser_dataT CharType String}\n            {cdata : @boolean_parser_completeness_dataT' _ String G data}\n            {rdata : @parser_removal_dataT' predata}.\n\n    Let P : string -> Prop\n      := fun p => is_valid_nonterminal initial_nonterminals_data p = true.\n\n    Section parts.\n      Local Hint Constructors parse_of_item parse_of parse_of_production.\n\n      (*Let H_subT valid\n        := sub_productions_listT is_valid_nonterminal valid initial_nonterminals_data.*)\n\n      Section item.\n        Context (str : StringWithSplitState String split_stateT)\n                (str_matches_nonterminal : string -> bool).\n\n        Definition str_matches_nonterminal_soundT\n          := forall nonterminal, str_matches_nonterminal nonterminal = true\n                          -> parse_of_item _ G str (NonTerminal _ nonterminal).\n\n        Definition str_matches_nonterminal_completeT P str0\n          := forall (valid : nonterminals_listT) nonterminal (H_sub : P str0 valid nonterminal),\n               minimal_parse_of_item (G := G) str0 valid str (NonTerminal _ nonterminal)\n               -> str_matches_nonterminal nonterminal = true.\n\n        Lemma parse_item_sound\n              (str_matches_nonterminal_sound : str_matches_nonterminal_soundT)\n              (it : item CharType)\n        : parse_item str_matches_nonterminal str it = true -> parse_of_item _ G str it.\n        Proof.\n          unfold parse_item, str_matches_nonterminal_soundT in *.\n          repeat match goal with\n                   | _ => intro\n                   | [ H : context[match ?E with _ => _ end] |- _ ] => atomic E; destruct E\n                   | [ |- context[match ?E with _ => _ end] ] => atomic E; destruct E\n                   | [ H : _ = true |- _ ] => apply bool_eq_correct in H\n                   | [ H : context[match ?E with _ => _ end] |- context[?E] ] => destruct E\n                   | _ => progress (simpl in *; subst)\n                   | _ => solve [ eauto ]\n                   | [ H : StringWithSplitState _ _ |- _ ] => destruct H\n                 end.\n        Defined.\n\n        Lemma parse_item_complete\n              str0\n              valid Pv\n              (str_matches_nonterminal_complete : str_matches_nonterminal_completeT Pv str0)\n              (it : item CharType)\n              (Hinit : forall nonterminal,\n                         minimal_parse_of_nonterminal (G := G) str0 valid str nonterminal\n                         -> Pv str0 valid nonterminal)\n        : minimal_parse_of_item (G := G) str0 valid str it\n          -> parse_item str_matches_nonterminal str it = true.\n        Proof.\n          unfold parse_item, str_matches_nonterminal_completeT in *.\n          repeat\n            repeat\n            match goal with\n              | _ => intro\n              | _ => reflexivity\n              | _ => eassumption\n              | [ |- _ /\\ _ ] => split\n              | [ |- ?x < ?x \\/ _ ] => right\n              | [ H : ?T |- ?T \\/ _ ] => left; exact H\n              | [ |- ?x = ?x \\/ _ ] => left; reflexivity\n              | [ |- _ \\/ ?x = ?x ] => right; reflexivity\n              | [ |- _ = true ] => apply bool_eq_correct\n              | [ H : context[?E] |- context[match ?E with _ => _ end] ] => destruct E\n              | [ H : minimal_parse_of _ _ _ [] |- _ ] => solve [ inversion H ]\n              | [ |- str_matches_nonterminal _ = true ]\n                => eapply str_matches_nonterminal_complete; [..| eassumption ]\n              | [ H : minimal_parse_of_item _ _ _ (Terminal _) |- _ ] => inversion_clear H\n              | [ H : minimal_parse_of_item _ _ _ (NonTerminal _ _) |- _ ] => inversion_clear H\n              | [ H : forall nonterminal, _ -> Pv _ _ nonterminal |- Pv _ _ _ ] => eapply H\n          end.\n        Qed.\n      End item.\n\n      Section item_ext.\n        Lemma parse_item_ext\n              (str : StringWithSplitState String split_stateT)\n              (str_matches_nonterminal1 str_matches_nonterminal2 : string -> bool)\n              (it : item CharType)\n              (ext : forall x, str_matches_nonterminal1 x = str_matches_nonterminal2 x)\n        : parse_item str_matches_nonterminal1 str it\n          = parse_item str_matches_nonterminal2 str it.\n        Proof.\n          unfold parse_item.\n          destruct it; auto;\n          match goal with\n            | [ |- context[match ?E with _ => _ end] ] => destruct E\n          end;\n          auto.\n        Qed.\n      End item_ext.\n\n      Section production.\n        Context (str0 : String)\n                (parse_nonterminal : forall (str : StringWithSplitState String split_stateT),\n                                str \u2264s str0\n                                -> string\n                                -> bool).\n\n        Definition parse_nonterminal_soundT\n          := forall str pf nonterminal,\n               @parse_nonterminal str pf nonterminal = true\n               -> parse_of_item _ G str (NonTerminal _ nonterminal).\n\n        Definition parse_nonterminal_completeT P\n          := forall valid (str : StringWithSplitState String split_stateT) pf nonterminal (H_sub : P str0 valid nonterminal),\n               minimal_parse_of_nonterminal (G := G) str0 valid str nonterminal\n               -> @parse_nonterminal str pf nonterminal = true.\n\n        Lemma parse_production_sound\n                 (parse_nonterminal_sound : parse_nonterminal_soundT)\n                 (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0)\n                 (prod : production CharType)\n        : parse_production parse_nonterminal str pf prod = true\n          -> parse_of_production _ G str prod.\n        Proof.\n          revert str pf; induction prod;\n          repeat match goal with\n                   | _ => intro\n                   | _ => progress simpl in *\n                   | _ => progress subst\n                   | _ => solve [ auto ]\n                   | [ H : fold_right orb false (map _ _) = true |- _ ] => apply fold_right_orb_map_sig1 in H\n                   | [ H : (_ || _)%bool = true |- _ ] => apply Bool.orb_true_elim in H\n                   | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n                   | _ => progress destruct_head sumbool\n                   | _ => progress destruct_head and\n                   | _ => progress destruct_head prod\n                   | _ => progress destruct_head sig\n                   | _ => progress destruct_head @StringWithSplitState\n                   | _ => progress simpl in *\n                   | _ => progress subst\n                   | [ H : (_ =s _) = true |- _ ] => apply bool_eq_correct in H\n                   | [ H : (_ =s _) = true |- _ ]\n                     => let H' := fresh in\n                        pose proof H as H';\n                          apply bool_eq_correct in H';\n                          progress subst\n                   | [ |- parse_of_production _ _ (_ ++ Empty _) [?it] ]\n                     => constructor\n                   | [ |- parse_of_item _ _ ?s _ ]\n                     => eapply parse_item_sound with (str := {| string_val := s |});\n                       hnf in *; solve [ eauto with nocore ]\n                 end.\n          { constructor;\n            solve [ eapply IHprod; eassumption\n                  | eapply parse_item_sound; try eassumption;\n                    hnf in parse_nonterminal_sound |- *;\n                    apply parse_nonterminal_sound ]. }\n        Defined.\n\n        Lemma parse_production_complete\n              valid Pv\n              (parse_nonterminal_complete : parse_nonterminal_completeT Pv)\n              (Hinit : forall str (pf : str \u2264s str0) nonterminal,\n                         minimal_parse_of_nonterminal (G := G) str0 valid str nonterminal\n                         -> Pv str0 valid nonterminal)\n              (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0)\n              (prod : production CharType)\n              (split_string_for_production_complete'\n               : forall str0 valid (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0),\n                   Forall_tails\n                     (fun prod' =>\n                        match prod' return Type with\n                          | nil => True\n                          | it::its => split_list_completeT (G := G) (valid := valid) (str0 := str0) it its str pf (split_string_for_production it its str)\n                        end)\n                     prod)\n        : minimal_parse_of_production (G := G) str0 valid str prod\n          -> parse_production parse_nonterminal str pf prod = true.\n        Proof.\n          revert valid str Hinit pf; induction prod;\n          [\n          | specialize (IHprod (fun str0 valid str pf => snd (split_string_for_production_complete' str0 valid str pf))) ];\n          repeat match goal with\n                   | _ => intro\n                   | _ => progress simpl in *\n                   | _ => progress subst\n                   | _ => progress destruct_head @StringWithSplitState\n                   | _ => solve [ auto ]\n                   | [ H : fold_right orb false (map _ _) = true |- _ ] => apply fold_right_orb_map_sig1 in H\n                   | [ H : (_ || _)%bool = true |- _ ] => apply Bool.orb_true_elim in H\n                   | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n                   | [ H : minimal_parse_of_production _ _ _ nil |- _ ] => inversion_clear H\n                   | [ |- (_ =s _) = true ] => apply bool_eq_correct\n                   | _ => progress destruct_head_hnf sumbool\n                   | _ => progress destruct_head_hnf and\n                   | _ => progress destruct_head_hnf sig\n                   | _ => progress destruct_head_hnf sigT\n                   | _ => progress destruct_head_hnf Datatypes.prod\n                   | _ => progress simpl in *\n                   | _ => progress subst\n                   | [ H : (_ =s _) = true |- _ ] => apply bool_eq_correct in H\n                   | [ H : (_ =s _) = true |- _ ]\n                     => let H' := fresh in\n                        pose proof H as H';\n                          apply bool_eq_correct in H';\n                          progress subst\n                   | [ H : minimal_parse_of_production _ _ _ (_::_) |- _ ] => inversion H; clear H; subst\n                   | [ H : ?s \u2264s _ |- context[split_string_for_production_correct ?it ?p {| string_val := ?s ; state_val := ?st |}] ]\n                     => let H' := fresh in\n                        pose proof\n                             (fun v a b p0 p1 p2\n                              => fst (@split_string_for_production_complete' _ v {| string_val := s ; state_val := st |} H) (existT _ (a, b) (p0, p1, p2))) as H';\n                          clear split_string_for_production_complete';\n                          simpl in H';\n                          specialize (fun a b p0 v p1 p2 => H' v a b p0 p1 p2)\n                   | [ H : forall a b, is_true (string_val a ++ string_val b =s _ ++ _) -> _ |- _ ]\n                     => specialize (fun st0 st1 => H {| state_val := st0 |} {| state_val := st1 |} (proj2 (@bool_eq_correct _ _ _ _) eq_refl))\n                   | [ H : forall a b, is_true (a ++ b =s _ ++ _) -> _ |- _ ]\n                     => specialize (H _ _ (proj2 (@bool_eq_correct _ _ _ _) eq_refl))\n                   | [ H : ?a -> ?b, H' : ?a |- _ ] => specialize (H H')\n                   | [ H : forall v : nonterminals_listT, @?a v -> @?b v |- _ ]\n                     => pose proof (H valid); pose proof (H initial_nonterminals_data); clear H\n                   | [ |- fold_right orb false (map _ _) = true ] => apply fold_right_orb_map_sig2\n                   | [ H : minimal_parse_of_item _ _ _ _ |- _ ] => inversion H; clear H; subst\n                   | [ |- (_ =s _) = true ] => apply bool_eq_correct\n                 end;\n          (lazymatch goal with\n            | [ H : In (?s1, ?s2) (split_string_for_production ?it ?prod {| string_val := ?str ; state_val := ?st |})\n                |- { x : { s1s2 : _ | (?f (fst s1s2) ++ ?f (snd s1s2) =s ?str) = true } | _ } ]\n              => let H' := fresh in\n                 pose proof (proj1 (@Forall_forall _ _ _) (split_string_for_production_correct it prod {| string_val := str ; state_val := st |}) _ H) as H';\n                   refine (exist _ (exist _ (s1, s2) _) _);\n                   simpl in *\n          end);\n          repeat match goal with\n                   | _ => split\n                   | [ |- (_ && _)%bool = true ] => apply Bool.andb_true_iff\n                   | [ |- (_ =s _) = true ] => apply bool_eq_correct\n                   | [ |- In _ (combine_sig _) ] => apply In_combine_sig\n                   | [ IHprod : _ |- _ ] => eapply IHprod; eassumption\n                 end;\n          eapply parse_nonterminal_complete; [..| eassumption ]; simpl;\n          repeat match goal with\n                   | _ => eassumption\n                   | _ => reflexivity\n                   | [ |- Pv _ _ _ ] => eapply Hinit; [ .. | eassumption ]\n                   | _ => etransitivity; [ | eassumption ];\n                          solve [ apply str_le1_append\n                                | apply str_le2_append ]\n                 end.\n          Grab Existential Variables.\n          assumption.\n          assumption.\n        Qed.\n      End production.\n\n      Section production_ext.\n        Lemma parse_production_ext\n              (str0 : String)\n              (parse_nonterminal1 parse_nonterminal2 : forall (str : StringWithSplitState String split_stateT),\n                                           str \u2264s str0\n                                           -> string\n                                           -> bool)\n              (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0) (prod : production CharType)\n              (ext : forall str' pf' nonterminal', parse_nonterminal1 str' pf' nonterminal'\n                                            = parse_nonterminal2 str' pf' nonterminal')\n        : parse_production parse_nonterminal1 str pf prod\n          = parse_production parse_nonterminal2 str pf prod.\n        Proof.\n          revert str pf.\n          induction prod as [|? ? IHprod]; simpl; intros; try reflexivity; [].\n          f_equal.\n          apply map_ext; intros.\n          apply f_equal2; [ apply parse_item_ext | apply IHprod ].\n          intros; apply ext.\n        Qed.\n      End production_ext.\n\n      Section productions.\n        Context (str0 : String)\n                (parse_nonterminal : forall (str : StringWithSplitState String split_stateT),\n                                str \u2264s str0\n                                -> string\n                                -> bool).\n\n        Local Ltac parse_productions_t :=\n          repeat match goal with\n                   | _ => intro\n                   | [ H : (_ || _)%bool = true |- _ ] => apply Bool.orb_true_elim in H\n                   | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n                   | [ |- (_ || _)%bool = true ] => apply Bool.orb_true_iff\n                   | [ |- (_ =s _) = true ] => apply bool_eq_correct\n                   | [ H : (_ =s _) = true |- _ ] => apply bool_eq_correct in H\n                   | _ => progress destruct_head_hnf sumbool\n                   | _ => progress destruct_head_hnf and\n                   | _ => progress destruct_head_hnf sig\n                   | _ => progress destruct_head_hnf sigT\n                   | _ => progress destruct_head_hnf Datatypes.prod\n                   | _ => progress simpl in *\n                   | _ => progress subst\n                   | [ H : parse_of _ _ _ nil |- _ ] => solve [ inversion H ]\n                   | [ H : parse_of _ _ _ (_::_) |- _ ] => inversion H; clear H; subst\n                   | [ H : minimal_parse_of _ _ _ nil |- _ ] => solve [ inversion H ]\n                   | [ H : minimal_parse_of _ _ _ (_::_) |- _ ] => inversion H; clear H; subst\n                   | [ H : parse_production _ _ _ _ = true |- _ ] => apply parse_production_sound with (str := {| string_val := _ |}) in H; try eassumption; []\n                   | _ => left; eapply parse_production_complete; eassumption\n                   | _ => solve [ eauto ]\n                 end.\n\n        Lemma parse_productions_sound\n                 (parse_nonterminal_sound : parse_nonterminal_soundT parse_nonterminal)\n                 (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0)\n                 (prods : productions CharType)\n        : parse_productions parse_nonterminal str pf prods = true\n          -> parse_of _ G str prods.\n        Proof.\n          destruct str as [str st]; simpl in *.\n          revert str pf st; induction prods; simpl.\n          { unfold parse_productions; simpl; intros ??? H; exfalso; clear -H.\n            abstract discriminate. }\n          { unfold parse_productions in *; simpl in *.\n            parse_productions_t. }\n        Defined.\n\n        Lemma parse_productions_complete\n              valid Pv\n              (parse_nonterminal_complete : parse_nonterminal_completeT parse_nonterminal Pv)\n              (Hinit : forall str (pf : str \u2264s str0) nonterminal,\n                         minimal_parse_of_nonterminal (G := G) str0 valid str nonterminal\n                         -> Pv str0 valid nonterminal)\n              (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0)\n              (prods : productions CharType)\n              (split_string_for_production_complete'\n               : forall str0 valid (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0),\n                   ForallT\n                     (Forall_tails\n                        (fun prod' =>\n                           match prod' return Type with\n                             | nil => True\n                             | it::its => split_list_completeT (G := G) (valid := valid) (str0 := str0) it its str pf (split_string_for_production it its str)\n                           end))\n                     prods)\n        : minimal_parse_of (G := G) str0 valid str prods\n          -> parse_productions parse_nonterminal str pf prods = true.\n        Proof.\n          destruct str as [str st]; simpl in *.\n          revert str pf st; induction prods; simpl.\n          { unfold parse_productions; simpl; intros ??? H; exfalso; clear -H.\n            abstract inversion H. }\n          { specialize (IHprods (fun str0 valid str pf => snd (split_string_for_production_complete' str0 valid str pf))).\n            pose proof (fun str0 valid str pf => fst (split_string_for_production_complete' str0 valid str pf)) as split_string_for_production_complete''.\n            clear split_string_for_production_complete'.\n            unfold parse_productions in *; simpl in *.\n            parse_productions_t. }\n        Defined.\n      End productions.\n\n      Section productions_ext.\n        Lemma parse_productions_ext\n              (str0 : String)\n              (parse_nonterminal1 parse_nonterminal2 : forall (str : StringWithSplitState String split_stateT),\n                                           str \u2264s str0\n                                           -> string\n                                           -> bool)\n              (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0) (prods : productions CharType)\n              (ext : forall str' pf' nonterminal', parse_nonterminal1 str' pf' nonterminal'\n                                            = parse_nonterminal2 str' pf' nonterminal')\n        : parse_productions parse_nonterminal1 str pf prods\n          = parse_productions parse_nonterminal2 str pf prods.\n        Proof.\n          revert str pf.\n          induction prods as [|? ? IHprod]; simpl; intros; try reflexivity; [].\n          unfold parse_productions; simpl.\n          apply f_equal2; [ apply parse_production_ext | apply IHprod ].\n          intros; apply ext.\n        Qed.\n      End productions_ext.\n\n      Section nonterminals.\n        Section step.\n          Context (str0 : String) (valid : nonterminals_listT)\n                  (parse_nonterminal\n                   : forall (p : String * nonterminals_listT),\n                       prod_relation (ltof _ Length) nonterminals_listT_R p (str0, valid)\n                       -> forall str : StringWithSplitState String split_stateT, str \u2264s fst p -> string -> bool).\n\n          Lemma parse_nonterminal_step_sound\n                (parse_nonterminal_sound : forall p pf, parse_nonterminal_soundT (@parse_nonterminal p pf))\n                (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0) (nonterminal : string)\n          : parse_nonterminal_step (G := G) parse_nonterminal _ pf nonterminal\n            = true\n            -> parse_of_item _ G str (NonTerminal _ nonterminal).\n          Proof.\n            unfold parse_nonterminal_step.\n            intro H'; constructor; revert H'.\n            edestruct lt_dec as [|n].\n            { intro H'.\n              apply parse_productions_sound in H'; trivial. }\n            { edestruct dec; [ | intro H''; exfalso; clear -H'';\n                                 abstract discriminate ].\n              pose proof (strle_to_sumbool _ pf) as pf'.\n              destruct pf' as [pf'|]; subst.\n              { destruct (n pf'). }\n              { intro H'.\n                apply parse_productions_sound in H'; trivial;\n                destruct_head @StringWithSplitState; subst; trivial. } }\n          Defined.\n\n          Lemma parse_nonterminal_step_complete\n                Pv\n                (parse_nonterminal_complete : forall p pf, parse_nonterminal_completeT (@parse_nonterminal p pf) (Pv p))\n                (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0) (nonterminal : string)\n                (Hnt : is_valid_nonterminal initial_nonterminals_data nonterminal)\n                (Hinit : forall str1,\n                           str1 \u2264s str ->\n                           forall nonterminal0,\n                             minimal_parse_of_nonterminal (G := G) str initial_nonterminals_data str1 nonterminal0 ->\n                             Pv (str : String, initial_nonterminals_data) str initial_nonterminals_data nonterminal0)\n                (Hinit' : forall str,\n                            str \u2264s str0 ->\n                            forall nonterminal0 : string,\n                              minimal_parse_of_nonterminal (G := G)\n                                                    str0 (remove_nonterminal valid nonterminal) str nonterminal0 ->\n                              Pv (str0, remove_nonterminal valid nonterminal) str0 (remove_nonterminal valid nonterminal) nonterminal0)\n          : minimal_parse_of_nonterminal (G := G) str0 valid str nonterminal\n            -> parse_nonterminal_step (G := G) parse_nonterminal _ pf nonterminal\n            = true.\n          Proof.\n            unfold parse_nonterminal_step.\n            edestruct lt_dec as [|n].\n            { intros H'.\n              inversion H'; clear H'; subst. (* Work around Anomaly: Evar ?425 was not declared. Please report. *)\n              { eapply parse_productions_complete; [ .. | eassumption ];\n                trivial.\n                intros; apply split_string_for_production_complete; assumption. }\n              { destruct_head @StringWithSplitState; subst.\n                match goal with\n                  | [ H : ?x < ?x |- _ ] => exfalso; clear -H; abstract omega\n                end. } }\n            { destruct pf as [pf|]; subst.\n              { destruct (n pf). }\n              { edestruct dec as [|pf']; simpl.\n                { intro H'.\n                  inversion_clear H'.\n                  { match goal with\n                      | [ H : ?T, H' : ~?T |- _ ] => destruct (H' H)\n                    end. }\n                  { let H' := match goal with H : minimal_parse_of _ _ _ _ |- _ => constr:H end in\n                    eapply parse_productions_complete in H'; eauto.\n                    eapply (@parse_nonterminal_complete (_, _)).\n                    intros; apply split_string_for_production_complete; assumption. } }\n                { intro H''; exfalso; clear -n H'' pf'.\n                  abstract (\n                      inversion_clear H'';\n                      (omega || congruence)\n                    ). } } }\n          Qed.\n        End step.\n\n        Section step_extensional.\n          Lemma parse_nonterminal_step_ext (str0 : String) (valid : nonterminals_listT)\n                (parse_nonterminal1 parse_nonterminal2: forall (p : String * nonterminals_listT),\n                                            prod_relation (ltof _ Length) nonterminals_listT_R p (str0, valid)\n                                            -> forall str : StringWithSplitState String split_stateT, str \u2264s fst p -> string -> bool)\n                (str : StringWithSplitState String split_stateT) (pf : str \u2264s str0) (nonterminal : string)\n                (ext : forall p pf0 str' pf' nonterminal', parse_nonterminal1 p pf0 str' pf' nonterminal'\n                                                    = parse_nonterminal2 p pf0 str' pf' nonterminal')\n          : parse_nonterminal_step (G := G) parse_nonterminal1 _ pf nonterminal\n            = parse_nonterminal_step (G := G) parse_nonterminal2 _ pf nonterminal.\n          Proof.\n            unfold parse_nonterminal_step.\n            edestruct lt_dec.\n            { apply parse_productions_ext; auto. }\n            { edestruct dec; trivial.\n              apply parse_productions_ext; auto. }\n          Qed.\n        End step_extensional.\n\n        Section wf.\n          Lemma parse_nonterminal_or_abort_sound\n                (p : String * nonterminals_listT) (str : StringWithSplitState String split_stateT)\n                (pf : str \u2264s fst p)\n                (nonterminal : string)\n          : parse_nonterminal_or_abort (G := G) p _ pf nonterminal\n            = true\n            -> parse_of_item _ G str (NonTerminal _ nonterminal).\n          Proof.\n            unfold parse_nonterminal_or_abort.\n            revert str pf nonterminal.\n            let Acca := match goal with |- context[@Fix3 _ _ _ _ _ ?Rwf _ _ ?a _ _ _] => constr:(Rwf a) end in\n            induction (Acca) as [? ? IHr];\n              intros str pf nonterminal.\n            rewrite Fix3_eq.\n            { apply parse_nonterminal_step_sound; assumption. }\n            { intros.\n              apply parse_nonterminal_step_ext.\n              trivial. }\n          Defined.\n\n          Lemma prod_relation_elim_helper {A R x} {valid : A}\n          : prod_relation (ltof String Length) R\n                          (fst x, valid) x\n            -> R valid (snd x).\n          Proof.\n            intros [ H | [? H] ].\n            { exfalso; simpl in *; clear -H.\n              unfold ltof in H; simpl in H.\n              abstract omega. }\n            { exact H. }\n          Qed.\n\n          Lemma parse_nonterminal_or_abort_complete\n                (Pv := fun (p : String * nonterminals_listT)\n                           (str0 : String) (valid0 : nonterminals_listT) (nt : string) =>\n                         is_valid_nonterminal initial_nonterminals_data nt\n                         /\\ sub_nonterminals_listT valid0 (snd p)\n                         /\\ sub_nonterminals_listT (snd p) initial_nonterminals_data)\n                (p : String * nonterminals_listT)\n          : @parse_nonterminal_completeT\n              (fst p)\n              (parse_nonterminal_or_abort (G := G) p)\n              (Pv p).\n          Proof.\n            unfold parse_nonterminal_or_abort.\n\n            let Acca := match goal with |- context[@Fix3 _ _ _ _ _ ?Rwf _ _ ?a] => constr:(Rwf a) end in\n            induction (Acca) as [x ? IHr];\n              intros valid str pf nonterminal ?.\n            rewrite Fix3_eq;\n              [\n              | solve [ intros;\n                        apply parse_nonterminal_step_ext;\n                        trivial ] ].\n            match goal with\n              | [ H : appcontext[?f]\n                  |- _ -> parse_nonterminal_step (fun y _ b c d => ?f y b c d) _ _ _ = true ]\n                => revert H;\n                  generalize f;\n                  let H' := fresh \"parse_nonterminal_step'\" in\n                  intros H' H\n            end.\n            destruct_head_hnf and.\n            intro; eapply parse_nonterminal_step_complete with (Pv := Pv); subst Pv;\n            [ intros; eapply IHr | .. ];\n            instantiate;\n            trivial; simpl in *;\n            try solve [ assumption\n                      | intros; reflexivity\n                      | intros; repeat split; reflexivity\n                      | intros; repeat split;\n                        try inversion_one_head @minimal_parse_of_nonterminal;\n                        try solve [ reflexivity\n                                  | assumption\n                                  | etransitivity; [ apply sub_nonterminals_listT_remove; apply remove_nonterminal_1 | assumption ] ] ];\n            [].\n            { eapply @expand_minimal_parse_of_nonterminal; [ .. | eassumption ];\n              trivial;\n              try solve [ reflexivity\n                        | apply remove_nonterminal_1\n                        | apply remove_nonterminal_2 ]. }\n          Defined.\n\n          Lemma parse_nonterminal_sound\n                (str : StringWithSplitState String split_stateT) (nonterminal : string)\n          : parse_nonterminal (G := G) str nonterminal\n            = true\n            -> parse_of_item _ G str (NonTerminal _ nonterminal).\n          Proof.\n            unfold parse_nonterminal, parse_nonterminal_or_abort.\n            apply parse_nonterminal_or_abort_sound.\n          Defined.\n\n          Lemma parse_nonterminal_complete'\n                (str : StringWithSplitState String split_stateT)\n                (nonterminal : string)\n                (H_init : is_valid_nonterminal initial_nonterminals_data nonterminal)\n          : minimal_parse_of_nonterminal (G := G) str initial_nonterminals_data str nonterminal\n            -> parse_nonterminal (G := G) str nonterminal\n               = true.\n          Proof.\n            unfold parse_nonterminal.\n            eapply (@parse_nonterminal_or_abort_complete\n                    (str : String, initial_nonterminals_data)).\n            repeat split; try reflexivity; assumption.\n          Defined.\n\n          Lemma parse_nonterminal_complete\n                (str : StringWithSplitState String split_stateT)\n                (nonterminal : string)\n                (p : parse_of _ G str (Lookup G nonterminal))\n                (H_valid_tree : Forall_parse_of_item\n                                  (fun _ p =>\n                                     is_valid_nonterminal initial_nonterminals_data p = true) (ParseNonTerminal _ p))\n          : parse_nonterminal (G := G) str nonterminal = true.\n          Proof.\n            apply parse_nonterminal_complete'; try assumption.\n            { exact (fst H_valid_tree). }\n            { pose proof (@minimal_parse_of_nonterminal__of__parse_of_nonterminal\n                            _ String G\n                            _\n                            _\n                            (S (size_of_parse_item (ParseNonTerminal _ p)))\n                            str str\n                            initial_nonterminals_data\n                            nonterminal\n                            p\n                            (Lt.lt_n_Sn _)\n                            (reflexivity _)\n                            (reflexivity _)\n                            H_valid_tree)\n                as p'.\n              destruct p' as [ [ p' ] | [ nonterminal' [ [ H0 H1 ] ] ] ].\n              { exact p'. }\n              { exfalso; congruence. } }\n          Qed.\n        End wf.\n      End nonterminals.\n    End parts.\n  End general.\nEnd sound.\n\nSection correct.\n  Context {CharType} {String : string_like CharType} {G : grammar CharType}.\n  Context `{cdata : @boolean_parser_correctness_dataT _ String G}.\n  Context (str : StringWithSplitState String split_stateT)\n          (nt : string).\n\n  Definition parse_nonterminal_correct\n  : (parse_nonterminal (G := G) str nt -> parse_of_item String G str (NonTerminal _ nt))\n    * (forall p : parse_of String G str (G nt),\n         Forall_parse_of_item\n           (fun _ nt => is_valid_nonterminal initial_nonterminals_data nt)\n           (ParseNonTerminal _ p)\n         -> parse_nonterminal (G := G) str nt).\n  Proof.\n    split.\n    { apply parse_nonterminal_sound. }\n    { apply parse_nonterminal_complete; exact _. }\n  Defined.\nEnd correct.\n\nSection brute_force_make_parse_of.\n  Variable G : grammar Ascii.ascii.\n\n  Definition brute_force_parse_sound\n             (str : @String Ascii.ascii string_stringlike)\n  : brute_force_parse G str = true -> parse_of_item _ G str (NonTerminal _ G).\n  Proof.\n    unfold brute_force_parse, brute_force_parse_nonterminal.\n    apply parse_nonterminal_sound.\n  Defined.\n\n  Definition brute_force_parse_complete'\n             (str : @String Ascii.ascii string_stringlike)\n  : @minimal_parse_of_nonterminal _ _ G (rdp_list_predata (G := G)) str (Valid_nonterminals G) str G\n    -> brute_force_parse G str = true.\n  Proof.\n    unfold brute_force_parse, brute_force_parse_nonterminal.\n    simpl; intro.\n    eapply parse_nonterminal_complete'; try eassumption; try exact _; try exact rdp_list_rdata'.\n    inversion_one_head @minimal_parse_of_nonterminal; assumption.\n  Defined.\n\n  Definition brute_force_parse_complete\n             (str : @String Ascii.ascii string_stringlike)\n             (p : parse_of _ G str G)\n             (H_valid_tree : Forall_parse_of_item\n                               (fun _ p =>\n                                  rdp_list_is_valid_nonterminal (Valid_nonterminals G) p = true) (ParseNonTerminal _ p))\n  : brute_force_parse G str = true.\n  Proof.\n    unfold brute_force_parse, brute_force_parse_nonterminal.\n    eapply parse_nonterminal_complete; try eassumption; try exact _; try exact rdp_list_rdata'.\n  Qed.\nEnd brute_force_make_parse_of.\n", "meta": {"author": "JasonGross", "repo": "parsing-parses", "sha": "8629e8e7b1e3e65ad6d152d08ce860d1385ecbf9", "save_path": "github-repos/coq/JasonGross-parsing-parses", "path": "github-repos/coq/JasonGross-parsing-parses/parsing-parses-8629e8e7b1e3e65ad6d152d08ce860d1385ecbf9/src/Parsers/BooleanRecognizerCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18145182904258483}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import CRelationClasses.\nFrom Equations.Type Require Import Relation Relation_Properties.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config BasicAst Reflect.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICOnOne PCUICAstUtils PCUICEquality\n     PCUICLiftSubst PCUICUnivSubst PCUICCases PCUICOnFreeVars.\n\nSet Default Goal Selector \"!\".\n\nImplicit Types (cf : checker_flags).\n\nDefinition cumul_predicate (cumul : context -> term -> term -> Type) \u0393 Re p p' :=\n  All2 (cumul \u0393) p.(pparams) p'.(pparams) *\n  (R_universe_instance Re p.(puinst) p'.(puinst) *\n  ((eq_context_gen eq eq p.(pcontext) p'.(pcontext)) *\n    cumul (\u0393 ,,, inst_case_predicate_context p) p.(preturn) p'.(preturn))).\n\nReserved Notation \" \u03a3 ;;; \u0393 \u22a2 t \u2264s[ pb ] u\" (at level 50, \u0393, t, u at next level,\n  format \"\u03a3  ;;;  \u0393  \u22a2  t  \u2264s[ pb ]  u\").\n\nDefinition cumul_Ind_univ {cf} (\u03a3 : global_env_ext) pb i napp :=\n  R_global_instance \u03a3 (eq_universe \u03a3) (compare_universe pb \u03a3) (IndRef i) napp.\n\nDefinition cumul_Construct_univ {cf} (\u03a3 : global_env_ext) pb  i k napp :=\n  R_global_instance \u03a3 (eq_universe \u03a3) (compare_universe pb \u03a3) (ConstructRef i k) napp.\n\n(** * Definition of cumulativity and conversion relations *)\n\nInductive cumulSpec0 {cf : checker_flags} (\u03a3 : global_env_ext) \u0393 (pb : conv_pb) : term -> term -> Type :=\n\n(* transitivity *)\n\n| cumul_Trans : forall t u v,\n    is_closed_context \u0393 -> is_open_term \u0393 u ->\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[pb] u ->\n    \u03a3 ;;; \u0393 \u22a2 u \u2264s[pb] v ->\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[pb] v\n\n(* symmetry *)\n\n| cumul_Sym : forall t u,\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] u ->\n    \u03a3 ;;; \u0393 \u22a2 u \u2264s[pb] t\n\n(* reflexivity *)\n\n| cumul_Refl : forall t,\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[pb] t\n\n(* Cumulativity rules *)\n\n| cumul_Ind : forall i u u' args args',\n    cumul_Ind_univ \u03a3 pb i #|args| u u' ->\n    All2 (fun t u => \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] u) args args' ->\n    \u03a3 ;;; \u0393 \u22a2 mkApps (tInd i u) args \u2264s[pb] mkApps (tInd i u') args'\n\n| cumul_Construct : forall i k u u' args args',\n    cumul_Construct_univ \u03a3 pb i k #|args| u u' ->\n    All2 (fun t u => \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] u) args args' ->\n    \u03a3 ;;; \u0393 \u22a2 mkApps (tConstruct i k u) args \u2264s[pb] mkApps (tConstruct i k u') args'\n\n| cumul_Sort : forall s s',\n    compare_universe pb \u03a3 s s' ->\n    \u03a3 ;;; \u0393 \u22a2 tSort s \u2264s[pb] tSort s'\n\n| cumul_Const : forall c u u',\n    R_universe_instance (compare_universe Conv \u03a3) u u' ->\n    \u03a3 ;;; \u0393 \u22a2 tConst c u \u2264s[pb] tConst c u'\n\n(* congruence rules *)\n\n| cumul_Evar : forall e args args',\n    All2 (fun t u => \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] u) args args' ->\n    \u03a3 ;;; \u0393 \u22a2 tEvar e args \u2264s[pb] tEvar e args'\n\n| cumul_App : forall t t' u u',\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[pb] t' ->\n    \u03a3 ;;; \u0393 \u22a2 u \u2264s[Conv] u' ->\n    \u03a3 ;;; \u0393 \u22a2 tApp t u \u2264s[pb] tApp t' u'\n\n| cumul_Lambda : forall na na' ty ty' t t',\n    eq_binder_annot na na' ->\n    \u03a3 ;;; \u0393 \u22a2 ty \u2264s[Conv] ty' ->\n    \u03a3 ;;; \u0393 ,, vass na ty \u22a2 t \u2264s[pb] t' ->\n    \u03a3 ;;; \u0393 \u22a2 tLambda na ty t \u2264s[pb] tLambda na' ty' t'\n\n| cumul_Prod : forall na na' a a' b b',\n    eq_binder_annot na na' ->\n    \u03a3 ;;; \u0393 \u22a2 a \u2264s[Conv] a' ->\n    \u03a3 ;;; \u0393 ,, vass na a \u22a2 b \u2264s[pb] b' ->\n    \u03a3 ;;; \u0393 \u22a2 tProd na a b \u2264s[pb] tProd na' a' b'\n\n| cumul_LetIn : forall na na' t t' ty ty' u u',\n    eq_binder_annot na na' ->\n    \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] t' ->\n    \u03a3 ;;; \u0393 \u22a2 ty \u2264s[Conv] ty' ->\n    \u03a3 ;;; \u0393 ,, vdef na t ty \u22a2 u \u2264s[pb] u' ->\n    \u03a3 ;;; \u0393 \u22a2 tLetIn na t ty u \u2264s[pb] tLetIn na' t' ty' u'\n\n| cumul_Case indn : forall p p' c c' brs brs',\n    cumul_predicate (fun \u0393 t u => \u03a3 ;;; \u0393 \u22a2 t \u2264s[Conv] u) \u0393 (compare_universe Conv \u03a3) p p' ->\n    \u03a3 ;;; \u0393 \u22a2 c \u2264s[Conv] c' ->\n    All2 (fun br br' =>\n      eq_context_gen eq eq (bcontext br) (bcontext br') \u00d7\n      \u03a3 ;;; \u0393 ,,, inst_case_branch_context p br \u22a2 bbody br \u2264s[Conv] bbody br'\n    ) brs brs' ->\n    \u03a3 ;;; \u0393 \u22a2 tCase indn p c brs \u2264s[pb] tCase indn p' c' brs'\n\n| cumul_Proj : forall p c c',\n    \u03a3 ;;; \u0393 \u22a2 c \u2264s[Conv] c' ->\n    \u03a3 ;;; \u0393 \u22a2 tProj p c \u2264s[pb] tProj p c'\n\n| cumul_Fix : forall mfix mfix' idx,\n    All2 (fun x y =>\n      \u03a3 ;;; \u0393 \u22a2 x.(dtype) \u2264s[Conv] y.(dtype) \u00d7\n      \u03a3 ;;; \u0393 ,,, fix_context mfix \u22a2 x.(dbody) \u2264s[Conv] y.(dbody) \u00d7\n      (x.(rarg) = y.(rarg)) \u00d7\n      eq_binder_annot x.(dname) y.(dname)\n    ) mfix mfix' ->\n    \u03a3 ;;; \u0393 \u22a2 tFix mfix idx \u2264s[pb] tFix mfix' idx\n\n| cumul_CoFix : forall mfix mfix' idx,\n    All2 (fun x y =>\n      \u03a3 ;;; \u0393 \u22a2 x.(dtype) \u2264s[Conv] y.(dtype) \u00d7\n      \u03a3 ;;; \u0393 ,,, fix_context mfix \u22a2 x.(dbody) \u2264s[Conv] y.(dbody) \u00d7\n      (x.(rarg) = y.(rarg)) \u00d7\n      eq_binder_annot x.(dname) y.(dname)\n    ) mfix mfix' ->\n    \u03a3 ;;; \u0393 \u22a2 tCoFix mfix idx \u2264s[pb] tCoFix mfix' idx\n\n(** Reductions *)\n\n(** Beta red *)\n| cumul_beta : forall na t b a,\n    \u03a3 ;;; \u0393 \u22a2 tApp (tLambda na t b) a \u2264s[pb] b {0 := a}\n\n(** Let *)\n| cumul_zeta : forall na b t b',\n    \u03a3 ;;; \u0393 \u22a2 tLetIn na b t b' \u2264s[pb] b' {0 := b}\n\n| cumul_rel i body :\n    option_map decl_body (nth_error \u0393 i) = Some (Some body) ->\n    \u03a3 ;;; \u0393 \u22a2 tRel i \u2264s[pb] lift0 (S i) body\n\n(** iota red *)\n| cumul_iota : forall ci c u args p brs br,\n    nth_error brs c = Some br ->\n    #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->\n    \u03a3 ;;; \u0393 \u22a2 tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs  \u2264s[pb] iota_red ci.(ci_npar) p args br\n\n(** Fix unfolding, with guard *)\n| cumul_fix : forall mfix idx args narg fn,\n    unfold_fix mfix idx = Some (narg, fn) ->\n    is_constructor narg args = true ->\n    \u03a3 ;;; \u0393 \u22a2 mkApps (tFix mfix idx) args \u2264s[pb] mkApps fn args\n\n(** CoFix-case unfolding *)\n| cumul_cofix_case : forall ip p mfix idx args narg fn brs,\n    unfold_cofix mfix idx = Some (narg, fn) ->\n    \u03a3 ;;; \u0393 \u22a2 tCase ip p (mkApps (tCoFix mfix idx) args) brs \u2264s[pb] tCase ip p (mkApps fn args) brs\n\n(** CoFix-proj unfolding *)\n| cumul_cofix_proj : forall p mfix idx args narg fn,\n    unfold_cofix mfix idx = Some (narg, fn) ->\n    \u03a3 ;;; \u0393 \u22a2 tProj p (mkApps (tCoFix mfix idx) args) \u2264s[pb] tProj p (mkApps fn args)\n\n(** Constant unfolding *)\n| cumul_delta : forall c decl body (isdecl : declared_constant \u03a3 c decl) u,\n    decl.(cst_body) = Some body ->\n    \u03a3 ;;; \u0393 \u22a2 tConst c u \u2264s[pb] body@[u]\n\n(** Proj *)\n| cumul_proj : forall p args u arg,\n    nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->\n    \u03a3 ;;; \u0393 \u22a2 tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args) \u2264s[pb] arg\n\nwhere \" \u03a3 ;;; \u0393 \u22a2 t \u2264s[ pb ] u \" := (@cumulSpec0 _ \u03a3 \u0393 pb t u) : type_scope.\n\nDefinition convSpec `{checker_flags} (\u03a3 : global_env_ext) \u0393 := cumulSpec0 \u03a3 \u0393 Conv.\nDefinition cumulSpec `{checker_flags} (\u03a3 : global_env_ext) \u0393 := cumulSpec0 \u03a3 \u0393 Cumul.\n\n(* ** Syntactic cumulativity up-to universes *)\n\nNotation \" \u03a3 ;;; \u0393 |- t <=s u \" := (@cumulSpec _ \u03a3 \u0393 t u) (at level 50, \u0393, t, u at next level).\nNotation \" \u03a3 ;;; \u0393 |- t =s u \" := (@convSpec _ \u03a3 \u0393 t u) (at level 50, \u0393, t, u at next level).\n\nInclude PCUICConversion.\n\nModule PCUICConversionParSpec <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.\n  Definition cumul_gen := @cumulSpec0.\nEnd PCUICConversionParSpec.\n\n\nNotation \" \u03a3 \u22a2 \u0393 \u2264s[ pb ] \u0394 \" := (@cumul_pb_context _ pb \u03a3 \u0393 \u0394) (at level 50, \u0393, \u0394 at next level) : type_scope.\nNotation \" \u03a3 \u22a2 \u0393 \u2264s \u0394 \" := (@cumul_pb_context _ Cumul \u03a3 \u0393 \u0394) (at level 50, \u0393, \u0394 at next level) : type_scope.\nNotation \" \u03a3 \u22a2 \u0393 =s \u0394 \" := (@cumul_pb_context _ Conv \u03a3 \u0393 \u0394) (at level 50, \u0393, \u0394 at next level) : type_scope.\n\n#[global]\nInstance cumul_spec_refl {cf:checker_flags} \u03a3 \u0393 pb : Reflexive (cumulSpec0 \u03a3 \u0393 pb).\nProof. intro; constructor 3. Qed.\n\n#[global]\nInstance conv_refl' {cf:checker_flags} \u03a3 \u0393 : Reflexive (convSpec \u03a3 \u0393) := _.\n\n#[global]\nInstance cumul_pb_decls_refl {cf:checker_flags} pb \u03a3 \u0393 \u0393' : Reflexive (cumul_pb_decls cumulSpec0 pb \u03a3 \u0393 \u0393').\nProof.\n  intros x. destruct x as [na [b|] ty]; constructor; auto.\n  all:constructor; reflexivity.\nQed.\n\n#[global]\nInstance conv_decls_refl {cf:checker_flags} \u03a3 \u0393 \u0393' : Reflexive (conv_decls cumulSpec0 \u03a3 \u0393 \u0393') := _.\n#[global]\nInstance cumul_decls_refl {cf:checker_flags} \u03a3 \u0393 \u0393' : Reflexive (cumul_decls cumulSpec0 \u03a3 \u0393 \u0393') := _.\n\nSection ContextConversion.\n  Context {cf : checker_flags}.\n  Context (\u03a3 : global_env_ext).\n\n  Notation conv_context := (conv_context cumulSpec0 \u03a3).\n  Notation cumul_context := (cumul_context cumulSpec0 \u03a3).\n\n  Global Instance cumul_pb_ctx_refl pb : Reflexive (cumul_pb_context cumulSpec0 pb \u03a3).\n  Proof using Type.\n    intro \u0393; induction \u0393; try econstructor; auto.\n    reflexivity.\n  Qed.\n\n  Global Instance conv_ctx_refl : Reflexive (conv_context) := _.\n  Global Instance cumul_ctx_refl : Reflexive (cumul_context) := _.\n\n  Definition conv_ctx_refl' \u0393 : conv_context \u0393 \u0393\n  := conv_ctx_refl \u0393.\n\n  Definition cumul_ctx_refl' \u0393 : cumul_context \u0393 \u0393\n    := cumul_ctx_refl \u0393.\n\nEnd ContextConversion.\n\nLemma cumulSpec0_ind_all :\n  forall {cf} (\u03a3 : global_env_ext)\n         (P : conv_pb -> context -> term -> term -> Type),\n\n        (* beta *)\n       (forall (pb : conv_pb) (\u0393 : context) (na : aname) (t b a : term),\n        P pb \u0393 (tApp (tLambda na t b) a) (b {0 := a})) ->\n\n        (* let *)\n       (forall (pb : conv_pb) (\u0393 : context) (na : aname) (b t b' : term), P pb \u0393 (tLetIn na b t b') (b' {0 := b})) ->\n\n       (forall (pb : conv_pb) (\u0393 : context) (i : nat) (body : term),\n        option_map decl_body (nth_error \u0393 i) = Some (Some body) -> P pb \u0393 (tRel i) ((lift0 (S i)) body)) ->\n\n        (* iota *)\n       (forall (pb : conv_pb) (\u0393 : context) (ci : case_info) (c : nat) (u : Instance.t) (args : list term)\n          (p : predicate term) (brs : list (branch term)) br,\n          nth_error brs c = Some br ->\n          #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->\n          P pb \u0393 (tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs)\n              (iota_red ci.(ci_npar) p args br)) ->\n\n        (* fix unfolding *)\n       (forall (pb : conv_pb) (\u0393 : context) (mfix : mfixpoint term) (idx : nat) (args : list term) (narg : nat) (fn : term),\n        unfold_fix mfix idx = Some (narg, fn) ->\n        is_constructor narg args = true -> P pb \u0393 (mkApps (tFix mfix idx) args) (mkApps fn args)) ->\n\n      (* cofix unfolding *)\n       (forall (pb : conv_pb) (\u0393 : context) ci (p : predicate term) (mfix : mfixpoint term) (idx : nat)\n          (args : list term) (narg : nat) (fn : term) (brs : list (branch term)),\n        unfold_cofix mfix idx = Some (narg, fn) ->\n        P pb \u0393 (tCase ci p (mkApps (tCoFix mfix idx) args) brs) (tCase ci p (mkApps fn args) brs)) ->\n\n       (forall (pb : conv_pb) (\u0393 : context) (p : projection) (mfix : mfixpoint term) (idx : nat) (args : list term)\n          (narg : nat) (fn : term),\n        unfold_cofix mfix idx = Some (narg, fn) -> P pb \u0393 (tProj p (mkApps (tCoFix mfix idx) args)) (tProj p (mkApps fn args))) ->\n\n        (* constant unfolding *)\n       (forall (pb : conv_pb) (\u0393 : context) c (decl : constant_body) (body : term),\n        declared_constant \u03a3 c decl ->\n        forall u : Instance.t, cst_body decl = Some body -> P pb \u0393 (tConst c u) (subst_instance u body)) ->\n\n        (* Proj *)\n       (forall (pb : conv_pb) (\u0393 : context)p (args : list term) (u : Instance.t)\n         (arg : term),\n           nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->\n           P pb \u0393 (tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args)) arg) ->\n\n        (* transitivity *)\n       (forall (pb : conv_pb) (\u0393 : context) (t u v : term),\n          is_closed_context \u0393 -> is_open_term \u0393 u ->\n          cumulSpec0 \u03a3 \u0393 pb t u -> P pb \u0393 t u ->\n          cumulSpec0 \u03a3 \u0393 pb u v -> P pb \u0393 u v ->\n          P pb \u0393 t v) ->\n\n        (* symmetry *)\n       (forall (pb : conv_pb) (\u0393 : context) (t u : term),\n        cumulSpec0 \u03a3 \u0393 Conv u t -> P Conv \u0393 u t ->\n         P pb \u0393 t u) ->\n\n        (* reflexivity *)\n        (forall (pb : conv_pb) (\u0393 : context) (t : term),\n        P pb \u0393 t t) ->\n\n        (* congruence rules *)\n\n        (forall (pb : conv_pb) (\u0393 : context) (ev : nat) (l l' : list term),\n          All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P Conv \u0393)) l l' -> P pb \u0393 (tEvar ev l) (tEvar ev l')) ->\n\n        (forall (pb : conv_pb) (\u0393 : context) (t t' u u' : term),\n          cumulSpec0 \u03a3 \u0393 pb t t' -> P pb \u0393 t t' ->\n          cumulSpec0 \u03a3 \u0393 Conv u u' -> P Conv \u0393 u u' ->\n          P pb \u0393 (tApp t u) (tApp t' u')) ->\n\n        (forall (pb : conv_pb) (\u0393 : context) (na na' : aname) (ty ty' t t' : term),\n          eq_binder_annot na na' ->\n          cumulSpec0 \u03a3 \u0393 Conv ty ty' -> P Conv \u0393 ty ty' ->\n          cumulSpec0 \u03a3 (\u0393 ,, vass na ty) pb t t' -> P pb (\u0393 ,, vass na ty) t t' ->\n          P pb \u0393 (tLambda na ty t) (tLambda na' ty' t')) ->\n\n        (forall (pb : conv_pb) (\u0393 : context) (na na' : binder_annot name) (a a' b b' : term),\n          eq_binder_annot na na' ->\n          cumulSpec0 \u03a3 \u0393 Conv a a' -> P Conv \u0393 a a' ->\n          cumulSpec0 \u03a3 (\u0393,, vass na a) pb b b' -> P pb (\u0393,, vass na a) b b' ->\n          P pb \u0393 (tProd na a b) (tProd na' a' b')) ->\n\n     (forall (pb : conv_pb) (\u0393 : context) (na na' : binder_annot name) (t t' ty ty' u u' : term),\n        eq_binder_annot na na' ->  cumulSpec0 \u03a3 \u0393 Conv t t' -> P Conv \u0393 t t' ->\n        cumulSpec0 \u03a3 \u0393  Conv ty ty' -> P Conv \u0393 ty ty' ->\n        cumulSpec0 \u03a3 (\u0393,, vdef na t ty) pb u u' -> P pb (\u0393,, vdef na t ty) u u' ->\n        P pb \u0393 (tLetIn na t ty u) (tLetIn na' t' ty' u')) ->\n\n      (forall (pb : conv_pb) (\u0393 : context) (indn : case_info) (p p' : predicate term)\n        (c c' : term) (brs brs' : list (branch term)),\n        cumul_predicate (fun \u0393 t u => cumulSpec0 \u03a3 \u0393 Conv t u \u00d7 P Conv \u0393 t u) \u0393\n          (compare_universe Conv \u03a3) p p' ->\n        cumulSpec0 \u03a3 \u0393 Conv c c' -> P Conv \u0393 c c' ->\n        All2\n          (Trel_conj (fun br br' : branch term =>\n               eq_context_gen eq eq (bcontext br) (bcontext br') *\n               cumulSpec0 \u03a3 (\u0393,,, inst_case_branch_context p br) Conv\n                 (bbody br) (bbody br'))\n            (fun br br' => P Conv (\u0393,,, inst_case_branch_context p br) (bbody br) (bbody br'))) brs brs' ->\n       P pb \u0393 (tCase indn p c brs) (tCase indn p' c' brs')) ->\n\n       (forall (pb : conv_pb) (\u0393 : context)\n          (p : projection) (c c' : term),\n        cumulSpec0 \u03a3 \u0393 Conv c c' -> P Conv \u0393 c c' ->\n         P pb \u0393 (tProj p c) (tProj p c')) ->\n\n       (forall (pb : conv_pb) (\u0393 : context)\n          (mfix : mfixpoint term) (mfix' : list (def term)) (idx : nat),\n          All2\n            (fun x y : def term =>\n             ((cumulSpec0 \u03a3 \u0393 Conv (dtype x) (dtype y) \u00d7\n                P Conv \u0393 (dtype x) (dtype y)\n               \u00d7 cumulSpec0 \u03a3 (\u0393,,, fix_context mfix) Conv\n                   (dbody x) (dbody y)) \u00d7\n                P Conv (\u0393,,, fix_context mfix) (dbody x) (dbody y) \u00d7 rarg x = rarg y) *\n             eq_binder_annot (dname x) (dname y)) mfix mfix' ->\n           P pb \u0393 (tFix mfix idx) (tFix mfix' idx)) ->\n\n       (forall (pb : conv_pb) (\u0393 : context)\n           (mfix : mfixpoint term) (mfix' : list (def term)) (idx : nat),\n           All2\n             (fun x y : def term =>\n              ((cumulSpec0 \u03a3 \u0393 Conv (dtype x) (dtype y) \u00d7\n                 P Conv \u0393 (dtype x) (dtype y)\n                \u00d7 cumulSpec0 \u03a3 (\u0393,,, fix_context mfix) Conv\n                    (dbody x) (dbody y)) \u00d7 P Conv (\u0393,,, fix_context mfix)\n                    (dbody x) (dbody y) \u00d7 rarg x = rarg y) *\n              eq_binder_annot (dname x) (dname y)) mfix mfix' ->\n            P pb \u0393 (tCoFix mfix idx) (tCoFix mfix' idx)) ->\n\n      (* cumulativity rules *)\n\n      (forall (pb : conv_pb)\n            (\u0393 : context) (i : inductive) (u u' : list Level.t)\n            (args args' : list term),\n      R_global_instance \u03a3 (eq_universe \u03a3) (compare_universe pb \u03a3) (IndRef i) #|args| u u' ->\n      All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P Conv \u0393)) args args' ->\n      P pb \u0393 (mkApps (tInd i u) args) (mkApps (tInd i u') args')) ->\n\n    (forall (pb : conv_pb)\n      (\u0393 : context) (i : inductive) (k : nat)\n      (u u' : list Level.t) (args args' : list term),\n      R_global_instance \u03a3 (eq_universe \u03a3) (compare_universe pb \u03a3) (ConstructRef i k) #|args| u u' ->\n      All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P Conv \u0393)) args args' ->\n      P pb \u0393 (mkApps (tConstruct i k u) args)\n              (mkApps (tConstruct i k u') args')) ->\n\n      (forall (pb : conv_pb)\n          (\u0393 : context) (s s' : Universe.t),\n          compare_universe pb \u03a3 s s' -> P pb \u0393 (tSort s) (tSort s')) ->\n\n      (forall (pb : conv_pb)\n          (\u0393 : context) (c : kername) (u u' : list Level.t),\n          R_universe_instance (compare_universe Conv \u03a3) u u' -> P pb \u0393 (tConst c u) (tConst c u') ) ->\n\n       forall (pb : conv_pb) (\u0393 : context) (t t0 : term), cumulSpec0 \u03a3 \u0393 pb t t0 -> P pb \u0393 t t0.\nProof.\n  intros. rename X24 into Xlast. revert pb \u0393 t t0 Xlast.\n  fix aux 5. intros pb \u0393 t u.\n  move aux at top.\n  destruct 1.\n  - eapply X8; eauto.\n  - eapply X9; eauto.\n  - eapply X10; eauto.\n  - eapply X20; eauto. clear -a aux.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X21; eauto. clear -a aux.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X22; eauto.\n  - eapply X23; eauto.\n  - eapply X11.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X12; eauto.\n  - eapply X13; eauto.\n  - eapply X14; eauto.\n  - eapply X15; eauto.\n  - eapply X16 ; eauto.\n    + unfold cumul_predicate in *. destruct c0 as [c0 [cuniv [ccontext creturn]]].\n      repeat split ; eauto.\n      * revert c0. generalize (pparams p), (pparams p').\n        fix aux' 3; destruct 1; constructor; auto.\n    + revert brs brs' a.\n      fix aux' 3; destruct 1; constructor; intuition auto.\n  - eapply X17 ; eauto.\n  - eapply X18 ; eauto.\n    revert a.\n    set (mfixAbs := mfix). unfold mfixAbs at 2 5.\n    clearbody mfixAbs.\n    revert mfix mfix'.\n    fix aux' 3; destruct 1; constructor.\n    + intuition auto.\n    + auto.\n  - eapply X19 ; eauto.\n    revert a.\n    set (mfixAbs := mfix). unfold mfixAbs at 2 5.\n    clearbody mfixAbs.\n    revert mfix mfix'.\n    fix aux' 3; destruct 1; constructor.\n    + intuition auto.\n    + auto.\n  - eapply X.\n  - eapply X0.\n  - eapply X1; eauto.\n  - eapply X2; eauto.\n  - eapply X3; eauto.\n  - eapply X4; eauto.\n  - eapply X5; eauto.\n  - eapply X6; eauto.\n  - eapply X7; eauto.\nDefined.\n\nLemma convSpec0_ind_all :\n  forall {cf} (\u03a3 : global_env_ext)\n         (P : context -> term -> term -> Type),\n\n        (* beta *)\n       (forall  (\u0393 : context) (na : aname) (t b a : term),\n        P \u0393 (tApp (tLambda na t b) a) (b {0 := a})) ->\n\n        (* let *)\n       (forall  (\u0393 : context) (na : aname) (b t b' : term), P  \u0393 (tLetIn na b t b') (b' {0 := b})) ->\n\n       (forall  (\u0393 : context) (i : nat) (body : term),\n        option_map decl_body (nth_error \u0393 i) = Some (Some body) -> P  \u0393 (tRel i) ((lift0 (S i)) body)) ->\n\n        (* iota *)\n       (forall  (\u0393 : context) (ci : case_info) (c : nat) (u : Instance.t) (args : list term)\n          (p : predicate term) (brs : list (branch term)) br,\n          nth_error brs c = Some br ->\n          #|args| = (ci.(ci_npar) + context_assumptions br.(bcontext))%nat ->\n          P  \u0393 (tCase ci p (mkApps (tConstruct ci.(ci_ind) c u) args) brs)\n              (iota_red ci.(ci_npar) p args br)) ->\n\n        (* fix unfolding *)\n       (forall  (\u0393 : context) (mfix : mfixpoint term) (idx : nat) (args : list term) (narg : nat) (fn : term),\n        unfold_fix mfix idx = Some (narg, fn) ->\n        is_constructor narg args = true -> P \u0393 (mkApps (tFix mfix idx) args) (mkApps fn args)) ->\n\n      (* cofix unfolding *)\n       (forall  (\u0393 : context) ci (p : predicate term) (mfix : mfixpoint term) (idx : nat)\n          (args : list term) (narg : nat) (fn : term) (brs : list (branch term)),\n        unfold_cofix mfix idx = Some (narg, fn) ->\n        P \u0393 (tCase ci p (mkApps (tCoFix mfix idx) args) brs) (tCase ci p (mkApps fn args) brs)) ->\n\n       (forall  (\u0393 : context) (p : projection) (mfix : mfixpoint term) (idx : nat) (args : list term)\n          (narg : nat) (fn : term),\n        unfold_cofix mfix idx = Some (narg, fn) -> P \u0393 (tProj p (mkApps (tCoFix mfix idx) args)) (tProj p (mkApps fn args))) ->\n\n        (* constant unfolding *)\n       (forall  (\u0393 : context) c (decl : constant_body) (body : term),\n        declared_constant \u03a3 c decl ->\n        forall u : Instance.t, cst_body decl = Some body -> P \u0393 (tConst c u) (subst_instance u body)) ->\n\n        (* Proj *)\n       (forall  (\u0393 : context) p (args : list term) (u : Instance.t)\n         (arg : term),\n           nth_error args (p.(proj_npars) + p.(proj_arg)) = Some arg ->\n           P  \u0393 (tProj p (mkApps (tConstruct p.(proj_ind) 0 u) args)) arg) ->\n\n        (* transitivity *)\n       (forall  (\u0393 : context) (t u v : term),\n          is_closed_context \u0393 -> is_open_term \u0393 u ->\n          cumulSpec0 \u03a3 \u0393 Conv t u -> P \u0393 t u ->\n          cumulSpec0 \u03a3 \u0393 Conv u v -> P \u0393 u v ->\n          P \u0393 t v) ->\n\n        (* symmetry *)\n       (forall  (\u0393 : context) (t u : term),\n        cumulSpec0 \u03a3 \u0393 Conv u t -> P \u0393 u t ->\n        P \u0393 t u) ->\n\n        (* reflexivity *)\n        (forall  (\u0393 : context) (t : term),\n        P \u0393 t t) ->\n\n        (* congruence rules *)\n\n        (forall  (\u0393 : context) (ev : nat) (l l' : list term),\n          All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P \u0393)) l l' -> P \u0393 (tEvar ev l) (tEvar ev l')) ->\n\n        (forall  (\u0393 : context) (t t' u u' : term),\n          cumulSpec0 \u03a3 \u0393 Conv t t' -> P \u0393 t t' ->\n          cumulSpec0 \u03a3 \u0393 Conv u u' -> P \u0393 u u' ->\n          P \u0393 (tApp t u) (tApp t' u')) ->\n\n        (forall  (\u0393 : context) (na na' : aname) (ty ty' t t' : term),\n          eq_binder_annot na na' ->\n          cumulSpec0 \u03a3 \u0393 Conv ty ty' -> P \u0393 ty ty' ->\n          cumulSpec0 \u03a3 (\u0393 ,, vass na ty) Conv t t' -> P (\u0393 ,, vass na ty) t t' ->\n          P \u0393 (tLambda na ty t) (tLambda na' ty' t')) ->\n\n        (forall  (\u0393 : context) (na na' : binder_annot name) (a a' b b' : term),\n          eq_binder_annot na na' ->\n          cumulSpec0 \u03a3 \u0393 Conv a a' -> P \u0393 a a' ->\n          cumulSpec0 \u03a3 (\u0393,, vass na a) Conv b b' -> P (\u0393,, vass na a) b b' ->\n          P \u0393 (tProd na a b) (tProd na' a' b')) ->\n\n     (forall  (\u0393 : context) (na na' : binder_annot name) (t t' ty ty' u u' : term),\n        eq_binder_annot na na' ->  cumulSpec0 \u03a3 \u0393 Conv t t' -> P \u0393 t t' ->\n        cumulSpec0 \u03a3 \u0393 Conv ty ty' -> P \u0393 ty ty' ->\n        cumulSpec0 \u03a3 (\u0393,, vdef na t ty) Conv u u' -> P (\u0393,, vdef na t ty) u u' ->\n        P \u0393 (tLetIn na t ty u) (tLetIn na' t' ty' u')) ->\n\n      (forall  (\u0393 : context) (indn : case_info) (p p' : predicate term)\n        (c c' : term) (brs brs' : list (branch term)),\n        cumul_predicate (fun \u0393 t u => cumulSpec0 \u03a3 \u0393 Conv t u * P \u0393 t u) \u0393 (compare_universe Conv \u03a3) p p' ->\n        cumulSpec0 \u03a3 \u0393 Conv c c' -> P \u0393 c c' ->\n        All2\n          (Trel_conj (fun br br' : branch term =>\n               eq_context_gen eq eq (bcontext br) (bcontext br') *\n               cumulSpec0 \u03a3 (\u0393,,, inst_case_branch_context p br) Conv\n                 (bbody br) (bbody br'))\n            (fun br br' => P (\u0393,,, inst_case_branch_context p br) (bbody br) (bbody br'))) brs brs' ->\n       P \u0393 (tCase indn p c brs) (tCase indn p' c' brs')) ->\n\n       (forall  (\u0393 : context)\n          (p : projection) (c c' : term),\n        cumulSpec0 \u03a3 \u0393 Conv c c' -> P \u0393 c c' ->\n         P \u0393 (tProj p c) (tProj p c')) ->\n\n       (forall  (\u0393 : context)\n          (mfix : mfixpoint term) (mfix' : list (def term)) (idx : nat),\n          All2\n            (fun x y : def term =>\n             ((cumulSpec0 \u03a3 \u0393 Conv (dtype x) (dtype y) \u00d7\n                P \u0393 (dtype x) (dtype y)\n               \u00d7 cumulSpec0 \u03a3 (\u0393,,, fix_context mfix) Conv\n                   (dbody x) (dbody y)) \u00d7 P (\u0393,,, fix_context mfix)\n                   (dbody x) (dbody y) \u00d7 rarg x = rarg y) *\n             eq_binder_annot (dname x) (dname y)) mfix mfix' ->\n           P \u0393 (tFix mfix idx) (tFix mfix' idx)) ->\n\n       (forall  (\u0393 : context)\n           (mfix : mfixpoint term) (mfix' : list (def term)) (idx : nat),\n           All2\n             (fun x y : def term =>\n              ((cumulSpec0 \u03a3 \u0393 Conv (dtype x) (dtype y) \u00d7\n                 P \u0393 (dtype x) (dtype y)\n                \u00d7 cumulSpec0 \u03a3 (\u0393,,, fix_context mfix) Conv\n                    (dbody x) (dbody y)) \u00d7 P (\u0393,,, fix_context mfix)\n                    (dbody x) (dbody y) \u00d7 rarg x = rarg y) *\n              eq_binder_annot (dname x) (dname y)) mfix mfix' ->\n            P \u0393 (tCoFix mfix idx) (tCoFix mfix' idx)) ->\n\n      (* cumulativiity rules *)\n\n      (forall\n            (\u0393 : context) (i : inductive) (u u' : list Level.t)\n            (args args' : list term),\n      R_global_instance \u03a3 (eq_universe \u03a3) (eq_universe \u03a3) (IndRef i) #|args| u u' ->\n      All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P \u0393)) args args' ->\n      P \u0393 (mkApps (tInd i u) args) (mkApps (tInd i u') args')) ->\n\n    (forall\n      (\u0393 : context) (i : inductive) (k : nat)\n      (u u' : list Level.t) (args args' : list term),\n      R_global_instance \u03a3 (eq_universe \u03a3) (eq_universe \u03a3) (ConstructRef i k) #|args| u u' ->\n      All2 (Trel_conj (cumulSpec0 \u03a3 \u0393 Conv) (P \u0393)) args args' ->\n      P \u0393 (mkApps (tConstruct i k u) args)\n              (mkApps (tConstruct i k u') args')) ->\n\n      (forall\n          (\u0393 : context) (s s' : Universe.t),\n          eq_universe \u03a3 s s' -> P \u0393 (tSort s) (tSort s')) ->\n\n      (forall\n          (\u0393 : context) (c : kername) (u u' : list Level.t),\n          R_universe_instance (eq_universe \u03a3) u u' -> P \u0393 (tConst c u) (tConst c u') ) ->\n\n       forall  (\u0393 : context) (t t0 : term), cumulSpec0 \u03a3 \u0393 Conv t t0 -> P \u0393 t t0.\nProof.\n  intros. rename X24 into Xlast. revert \u0393 t t0 Xlast.\n  fix aux 4. intros \u0393 t u.\n  move aux at top.\n  destruct 1.\n  - eapply X8; eauto.\n  - eapply X9; eauto.\n  - eapply X10; eauto.\n  - eapply X20; eauto. clear -a aux.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X21; eauto. clear -a aux.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X22; eauto.\n  - eapply X23; eauto.\n  - eapply X11.\n    revert args args' a.\n    fix aux' 3; destruct 1; constructor; auto.\n  - eapply X12; eauto.\n  - eapply X13; eauto.\n  - eapply X14; eauto.\n  - eapply X15; eauto.\n  - eapply X16 ; eauto.\n    + unfold cumul_predicate in *. destruct c0 as [c0 [cuniv [ccontext creturn]]].\n      repeat split ; eauto.\n      * revert c0. generalize (pparams p), (pparams p').\n        fix aux' 3; destruct 1; constructor; auto.\n    + revert brs brs' a.\n      fix aux' 3; destruct 1; constructor; intuition auto.\n  - eapply X17 ; eauto.\n  - eapply X18 ; eauto.\n    revert a.\n    set (mfixAbs := mfix). unfold mfixAbs at 2 5.\n    clearbody mfixAbs.\n    revert mfix mfix'.\n    fix aux' 3; destruct 1; constructor.\n    + intuition auto.\n    + auto.\n  - eapply X19 ; eauto.\n    revert a.\n    set (mfixAbs := mfix). unfold mfixAbs at 2 5.\n    clearbody mfixAbs.\n    revert mfix mfix'.\n    fix aux' 3; destruct 1; constructor.\n    + intuition auto.\n    + auto.\n  - eapply X.\n  - eapply X0.\n  - eapply X1; eauto.\n  - eapply X2; eauto.\n  - eapply X3; eauto.\n  - eapply X4; eauto.\n  - eapply X5; eauto.\n  - eapply X6; eauto.\n  - eapply X7; eauto.\nDefined.\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/PCUICCumulativitySpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.18145182904258483}}
{"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 MemOpen.\nRequire Import EchoHeader.\nRequire Import IPM HoareDef OpenDef.\nRequire Import Stack3A.\n\nSet Implicit Arguments.\n\n\n\n\nSection PROOF.\n\n  Context `{\u03a3: GRA.t}.\n  Context `{@GRA.inG stkRA \u03a3}.\n\n  Definition echo_body: list val -> itree hEs val :=\n    fun args =>\n      _ <- (pargs [] args)?;;;\n      `stk0: list Z    <- (ccallN \"input\" ([]: list Z));;;\n      `_: list Z    <- (ccallN \"output\" (stk0));;;\n      Ret Vundef\n  .\n\n\n\n\n  Let is_int_stack (h: mblock) (stk0: list Z): iProp :=\n    (OwnM (is_stack h (List.map Vint stk0)) \u2227 \u231cForall (fun z => (z <> (- 1)%Z) /\\ (intrange_64 z)) stk0\u231d)%I\n  .\n\n  Definition input_spec: fspec :=\n    mk_fspec (fun _ => ord_top)\n             (fun _ h _argh _argl =>\n                (\u2203 (stk0: list Z) (argl: list val),\n                  \u231c_argh = stk0\u2191 \u2227 _argl = argl\u2191 \u2227 argl = [Vptr h 0]\u231d\n                   ** (is_int_stack h stk0))%I)\n             (fun _ h _reth _retl => (\u2203 (stk1: list Z), \u231c_reth = stk1\u2191 \u2227 _retl = Vundef\u2191\u231d ** is_int_stack h stk1)%I)\n  .\n\n  Definition input_body: list Z -> itree hEs (list Z) :=\n    fun stk =>\n      n <- (ccallU \"getint\" ([]: list val));;;\n      assume(wf_val n);;;\n      n <- (parg Tint n)?;;;\n      if (dec n (- 1)%Z)\n      then Ret stk\n      else\n        ret <- (ccallN \"input\" (n :: stk));;; Ret ret\n  .\n\n\n\n\n\n  Definition output_spec: fspec :=\n    mk_fspec (fun _ => ord_top)\n             (fun _ h _argh _argl =>\n                (\u2203 (stk0: list Z) (argl: list val),\n                  \u231c_argh = stk0\u2191 \u2227 _argl = argl\u2191 \u2227 argl = [Vptr h 0]\u231d\n                   ** is_int_stack h stk0)%I)\n             (fun _ h _reth _retl => (\u2203 (stk1: list Z), \u231c_reth = stk1\u2191 \u2227 _retl = Vundef\u2191\u231d ** is_int_stack h stk1)%I)\n  .\n\n  Definition output_body: list Z -> itree hEs (list Z) :=\n    fun stk =>\n      ;;;\n      match stk with\n      | [] => Ret []\n      | n :: stk' =>\n        `_: val <- (ccallU \"putint\" ([Vint n]: list val));;;\n         ret <- (ccallN \"output\" (stk'));;;\n         Ret ret\n      end\n  .\n\n\n\n\n\n  Definition EchoSbtb: list (gname * kspecbody) :=\n    [(\"echo\", ksb_trivial (cfunU echo_body));\n    (\"input\",  mk_kspecbody input_spec (fun _ => triggerUB) (cfunN input_body));\n    (\"output\", mk_kspecbody output_spec (fun _ => triggerUB) (cfunN output_body))\n    ]\n  .\n\n  Definition EchoStb: list (gname * fspec).\n    eapply (Seal.sealing \"stb\").\n    let x := constr:(List.map (map_snd (fun ksb => ksb.(ksb_fspec): fspec)) EchoSbtb) in\n    let y := eval cbn in x in\n    eapply y.\n  Defined.\n\n  Definition KEchoSem: KModSem.t := {|\n    KModSem.fnsems := EchoSbtb;\n    KModSem.mn := \"Echo\";\n    KModSem.initial_mr := \u03b5;\n    KModSem.initial_st := (\u2205: gmap mblock (list Z))\u2191;\n  |}\n  .\n  Definition EchoSem (stb: gname -> option fspec): ModSem.t :=\n    KModSem.transl_tgt stb KEchoSem.\n\n\n\n  Definition KEcho: KMod.t := {|\n    KMod.get_modsem := fun _ => KEchoSem;\n    KMod.sk := [(\"echo\", Sk.Gfun); (\"input\", Sk.Gfun); (\"output\", Sk.Gfun)];\n  |}\n  .\n  Definition Echo (stb: Sk.t -> gname -> option fspec): Mod.t :=\n    KMod.transl_tgt stb KEcho.\n\nEnd PROOF.\nGlobal Hint Unfold EchoStb: stb.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/echo/Echo1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1814518290425848}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.WeakestPrecondition.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import Bedrock2Experiments.ProgramSemantics32.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIO.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.StateMachineProperties.\nImport Syntax.Coercions List.ListNotations.\nLocal Open Scope string_scope.\n\nSection Proof.\n  Context {word: word.word 32} {mem: map.map word Byte.byte}\n          {word_ok: word.ok word} {mem_ok: map.ok mem}\n          {M: state_machine.parameters} {M_ok: state_machine.ok M}\n          (execution_unique: forall t s1 s2, execution t s1 -> execution t s2 -> s1 = s2).\n\n  Global Instance spec_of_abs_mmio_write8 : spec_of \"abs_mmio_write8\" :=\n    fun function_env =>\n      forall (tr : trace) (m : mem) (s : M) (s' : M) (addr : word) (value : word) r,\n        state_machine.reg_addr r = addr ->\n        state_machine.write_step 1 s r value s' ->\n        execution tr s ->\n        call function_env abs_mmio_write8 tr m [addr; value]\n        (fun tr' m' rets =>\n          rets = []\n          /\\ tr' = ((map.empty, MMIOLabels.WRITE8, [addr; value], (map.empty, [])) :: tr)\n          /\\ (exists s'', execution tr' s'')\n          /\\ m = m'\n        ).\n  Lemma abs_mmio_write8_correct :\n    program_logic_goal_for_function! abs_mmio_write8.\n  Proof.\n    repeat straightline.\n    eapply (interact_write 1); repeat straightline.\n    - rewrite <- H. reflexivity.\n    - do 2 eexists; ssplit; eauto.\n    - rewrite <- H; ssplit; eauto.\n  Qed.\n\n  Global Instance spec_of_abs_mmio_write32 : spec_of \"abs_mmio_write32\" :=\n    fun function_env =>\n      forall (tr : trace) (m : mem) (s : M) (s' : M) (addr : word) (value : word) r,\n        state_machine.reg_addr r = addr ->\n        state_machine.write_step 4 s r value s' ->\n        execution tr s ->\n        call function_env abs_mmio_write32 tr m [addr; value]\n        (fun tr' m' rets =>\n          rets = []\n          /\\ tr' = ((map.empty, MMIOLabels.WRITE32, [addr; value], (map.empty, [])) :: tr)\n          /\\ (exists s'', execution tr' s'')\n          /\\ m = m'\n        ).\n  Lemma abs_mmio_write32_correct :\n    program_logic_goal_for_function! abs_mmio_write32.\n  Proof.\n    repeat straightline.\n    eapply (interact_write 4); repeat straightline.\n    - rewrite <- H. reflexivity.\n    - do 2 eexists; ssplit; eauto.\n    - rewrite <- H; ssplit; eauto.\n  Qed.\n\n  Global Instance spec_of_abs_mmio_read8 : spec_of \"abs_mmio_read8\" :=\n    fun function_env =>\n      forall (tr : trace) (m : mem) (s : M) (addr : word) r val s',\n        state_machine.reg_addr r = addr ->\n        state_machine.read_step 1 s r val s' ->\n        execution tr s ->\n        call function_env abs_mmio_read8 tr m [addr]\n        (fun tr' m' rets =>\n          exists s' val,\n          rets = [val]\n          /\\ tr' = ((map.empty, MMIOLabels.READ8, [addr], (map.empty, [val])) :: tr)\n          /\\ execution tr' s'\n          /\\ m = m'\n        ).\n  Lemma abs_mmio_read8_correct :\n    program_logic_goal_for_function! abs_mmio_read8.\n  Proof.\n    repeat straightline.\n    eapply (interact_read 1); repeat straightline; eauto.\n    - rewrite <- H. reflexivity.\n    - do 3 eexists; ssplit; eauto.\n      rewrite <- H. reflexivity.\n  Qed.\n\n  Global Instance spec_of_abs_mmio_read32 : spec_of \"abs_mmio_read32\" :=\n    fun function_env =>\n      forall (tr : trace) (m : mem) (s : M) (addr : word) r val s',\n        state_machine.reg_addr r = addr ->\n        state_machine.read_step 4 s r val s' ->\n        execution tr s ->\n        call function_env abs_mmio_read32 tr m [addr]\n        (fun tr' m' rets =>\n          exists s' val,\n          rets = [val]\n          /\\ tr' = ((map.empty, MMIOLabels.READ32, [addr], (map.empty, [val])) :: tr)\n          /\\ execution tr' s'\n          /\\ m = m'\n        ).\n  Lemma abs_mmio_read32_correct :\n    program_logic_goal_for_function! abs_mmio_read32.\n  Proof.\n    repeat straightline.\n    eapply (interact_read 4); repeat straightline; eauto.\n    - rewrite <- H. reflexivity.\n    - do 3 eexists; ssplit; eauto.\n      rewrite <- H. reflexivity.\n  Qed.\n\nEnd Proof.\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/LibBase/AbsMMIOProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.18136273416684703}}
{"text": "From Perennial.Helpers Require Import ModArith.\nFrom Perennial.program_proof Require Import grove_prelude std_proof.\nFrom Goose.github_com.mit_pdos.gokv Require Import memkv.\nFrom Perennial.program_proof.memkv Require Export memkv_shard_definitions memkv_marshal_getcid_proof memkv_shard_clerk_proof.\n\nSection memkv_getcid_proof.\n\nContext `{!heapGS \u03a3, erpcG \u03a3, urpcregG \u03a3, kvMapG \u03a3}.\n\nLemma wp_GetCIDRPC (s:loc) \u03b3 :\n  is_KVShardServer s \u03b3 -\u2217\n  {{{\n       True\n  }}}\n    KVShardServer__GetCIDRPC #s\n  {{{\n       cid, RET #cid; erpc_make_client_pre \u03b3.(erpc_gn) cid\n  }}}\n.\nProof.\n  iIntros \"#Hmemkv !#\" (\u03a6) \"_ H\u03a6\".\n  wp_lam.\n  iNamed \"Hmemkv\".\n  wp_loadField.\n  wp_apply wp_erpc_GetFreshCID; first done.\n  done.\nQed.\n\nEnd memkv_getcid_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_getcid_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.18136273045926923}}
{"text": "(** Notion of contextual refinement & proof that it is a precongruence wrt the logical relation *)\nFrom Autosubst Require Import Autosubst.\nFrom self.prob_lang Require Export lang.\nFrom self.prob_lang Require Import tactics.\nFrom iris.proofmode Require Import proofmode.\nFrom self.logrel Require Import model.\nFrom self.typing Require Export types interp fundamental.\n\nInductive ctx_item :=\n  (* Base lambda calculus *)\n  | CTX_Rec (f x : binder)\n  | CTX_AppL (e2 : expr)\n  | CTX_AppR (e1 : expr)\n  (* Base types and their operations *)\n  | CTX_UnOp (op : un_op)\n  | CTX_BinOpL (op : bin_op) (e2 : expr)\n  | CTX_BinOpR (op : bin_op) (e1 : expr)\n  | CTX_IfL (e1 : expr) (e2 : expr)\n  | CTX_IfM (e0 : expr) (e2 : expr)\n  | CTX_IfR (e0 : expr) (e1 : expr)\n  (* Products *)\n  | CTX_PairL (e2 : expr)\n  | CTX_PairR (e1 : expr)\n  | CTX_Fst\n  | CTX_Snd\n  (* Sums *)\n  | CTX_InjL\n  | CTX_InjR\n  | CTX_CaseL (e1 : expr) (e2 : expr)\n  | CTX_CaseM (e0 : expr) (e2 : expr)\n  | CTX_CaseR (e0 : expr) (e1 : expr)\n  (* Heap *)\n  | CTX_Alloc\n  | CTX_Load\n  | CTX_StoreL (e2 : expr)\n  | CTX_StoreR (e1 : expr)\n  (* Recursive Types *)\n  | CTX_Fold\n  | CTX_Unfold\n  (* Polymorphic Types *)\n  | CTX_TLam\n  | CTX_TApp\n  (* Existential types *)\n    (* Nb: we do not have an explicit PACK operation *)\n  | CTX_UnpackL (x : binder) (e2 : expr)\n  | CTX_UnpackR (x : binder) (e1 : expr)\n  | CTX_Flip\n.\n\nDefinition fill_ctx_item (ctx : ctx_item) (e : expr) : expr :=\n  match ctx with\n  (* Base lambda calculus *)\n  | CTX_Rec f x => Rec f x e\n  | CTX_AppL e2 => App e e2\n  | CTX_AppR e1 => App e1 e\n  (* Base types and operations *)\n  | CTX_UnOp op => UnOp op e\n  | CTX_BinOpL op e2 => BinOp op e e2\n  | CTX_BinOpR op e1 => BinOp op e1 e\n  | CTX_IfL e1 e2 => If e e1 e2\n  | CTX_IfM e0 e2 => If e0 e e2\n  | CTX_IfR e0 e1 => If e0 e1 e\n  (* Products *)\n  | CTX_PairL e2 => Pair e e2\n  | CTX_PairR e1 => Pair e1 e\n  | CTX_Fst => Fst e\n  | CTX_Snd => Snd e\n  (* Sums *)\n  | CTX_InjL => InjL e\n  | CTX_InjR => InjR e\n  | CTX_CaseL e1 e2 => Case e e1 e2\n  | CTX_CaseM e0 e2 => Case e0 e e2\n  | CTX_CaseR e0 e1 => Case e0 e1 e\n  (* Concurrency *)\n  (* Heap & atomic CAS/FAA *)\n  | CTX_Alloc => Alloc e\n  | CTX_Load => Load e\n  | CTX_StoreL e2 => Store e e2\n  | CTX_StoreR e1 => Store e1 e\n  (* Recursive & polymorphic types *)\n  | CTX_Fold => e\n  | CTX_Unfold => rec_unfold e\n  | CTX_TLam => \u039b: e\n  | CTX_TApp => TApp e\n  | CTX_UnpackL x e1 => unpack: x:=e in e1\n  | CTX_UnpackR x e0 => unpack: x:=e0 in e\n  | CTX_Flip => Flip e\n  end.\n\nDefinition ctx := list ctx_item.\n\n(* TODO: consider using foldl here *)\nDefinition fill_ctx (K : ctx) (e : expr) : expr := foldr fill_ctx_item e K.\n\n(** typed ctx *)\nInductive typed_ctx_item :\n    ctx_item \u2192 stringmap type \u2192 type \u2192 stringmap type \u2192 type \u2192 Prop :=\n  (* Base lambda calculus *)\n  | TP_CTX_Rec \u0393 \u03c4 \u03c4' f x :\n     typed_ctx_item (CTX_Rec f x) (<[f:=TArrow \u03c4 \u03c4']>(<[x:=\u03c4]>\u0393)) \u03c4' \u0393 (TArrow \u03c4 \u03c4')\n  | TP_CTX_AppL \u0393 e2 \u03c4 \u03c4' :\n     typed \u0393 e2 \u03c4 \u2192\n     typed_ctx_item (CTX_AppL e2) \u0393 (TArrow \u03c4 \u03c4') \u0393 \u03c4'\n  | TP_CTX_AppR \u0393 e1 \u03c4 \u03c4' :\n     typed \u0393 e1 (TArrow \u03c4 \u03c4') \u2192\n     typed_ctx_item (CTX_AppR e1) \u0393 \u03c4 \u0393 \u03c4'\n  (* Base types and operations *)\n  | TP_CTX_UnOp_Nat op \u0393 \u03c4 :\n     unop_int_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_UnOp op) \u0393 TInt \u0393 \u03c4\n  | TP_CTX_UnOp_Bool op \u0393 \u03c4 :\n     unop_bool_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_UnOp op) \u0393 TBool \u0393 \u03c4\n  | TP_CTX_BinOpL_Nat op \u0393 e2 \u03c4 :\n     typed \u0393 e2 TInt \u2192\n     binop_int_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpL op e2) \u0393 TInt \u0393 \u03c4\n  | TP_CTX_BinOpR_Nat op e1 \u0393 \u03c4 :\n     typed \u0393 e1 TInt \u2192\n     binop_int_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpR op e1) \u0393 TInt \u0393 \u03c4\n  | TP_CTX_BinOpL_Bool op \u0393 e2 \u03c4 :\n     typed \u0393 e2 TBool \u2192\n     binop_bool_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpL op e2) \u0393 TBool \u0393 \u03c4\n  | TP_CTX_BinOpR_Bool op e1 \u0393 \u03c4 :\n     typed \u0393 e1 TBool \u2192\n     binop_bool_res_type op = Some \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpR op e1) \u0393 TBool \u0393 \u03c4\n  | TP_CTX_BinOpL_UnboxedEq e2 \u0393 \u03c4 :\n     UnboxedType \u03c4 \u2192\n     typed \u0393 e2 \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpL EqOp e2) \u0393 \u03c4 \u0393 TBool\n  | TP_CTX_BinOpR_UnboxedEq e1 \u0393 \u03c4 :\n     UnboxedType \u03c4 \u2192\n     typed \u0393 e1 \u03c4 \u2192\n     typed_ctx_item (CTX_BinOpR EqOp e1) \u0393 \u03c4 \u0393 TBool\n  | TP_CTX_IfL \u0393 e1 e2 \u03c4 :\n     typed \u0393 e1 \u03c4 \u2192 typed \u0393 e2 \u03c4 \u2192\n     typed_ctx_item (CTX_IfL e1 e2) \u0393 (TBool) \u0393 \u03c4\n  | TP_CTX_IfM \u0393 e0 e2 \u03c4 :\n     typed \u0393 e0 (TBool) \u2192 typed \u0393 e2 \u03c4 \u2192\n     typed_ctx_item (CTX_IfM e0 e2) \u0393 \u03c4 \u0393 \u03c4\n  | TP_CTX_IfR \u0393 e0 e1 \u03c4 :\n     typed \u0393 e0 (TBool) \u2192 typed \u0393 e1 \u03c4 \u2192\n     typed_ctx_item (CTX_IfR e0 e1) \u0393 \u03c4 \u0393 \u03c4\n  (* Products *)\n  | TP_CTX_PairL \u0393 e2 \u03c4 \u03c4' :\n     typed \u0393 e2 \u03c4' \u2192\n     typed_ctx_item (CTX_PairL e2) \u0393 \u03c4 \u0393 (TProd \u03c4 \u03c4')\n  | TP_CTX_PairR \u0393 e1 \u03c4 \u03c4' :\n     typed \u0393 e1 \u03c4 \u2192\n     typed_ctx_item (CTX_PairR e1) \u0393 \u03c4' \u0393 (TProd \u03c4 \u03c4')\n  | TP_CTX_Fst \u0393 \u03c4 \u03c4' :\n     typed_ctx_item CTX_Fst \u0393 (TProd \u03c4 \u03c4') \u0393 \u03c4\n  | TP_CTX_Snd \u0393 \u03c4 \u03c4' :\n     typed_ctx_item CTX_Snd \u0393 (TProd \u03c4 \u03c4') \u0393 \u03c4'\n  (* Sums *)\n  | TP_CTX_InjL \u0393 \u03c4 \u03c4' :\n     typed_ctx_item CTX_InjL \u0393 \u03c4 \u0393 (TSum \u03c4 \u03c4')\n  | TP_CTX_InjR \u0393 \u03c4 \u03c4' :\n     typed_ctx_item CTX_InjR \u0393 \u03c4' \u0393 (TSum \u03c4 \u03c4')\n  | TP_CTX_CaseL \u0393 e1 e2 \u03c41 \u03c42 \u03c4' :\n     typed \u0393 e1 (TArrow \u03c41 \u03c4') \u2192 typed \u0393 e2 (TArrow \u03c42 \u03c4') \u2192\n     typed_ctx_item (CTX_CaseL e1 e2) \u0393 (TSum \u03c41 \u03c42) \u0393 \u03c4'\n  | TP_CTX_CaseM \u0393 e0 e2 \u03c41 \u03c42 \u03c4' :\n     typed \u0393 e0 (TSum \u03c41 \u03c42) \u2192 typed \u0393 e2 (TArrow \u03c42 \u03c4') \u2192\n     typed_ctx_item (CTX_CaseM e0 e2) \u0393 (TArrow \u03c41 \u03c4') \u0393 \u03c4'\n  | TP_CTX_CaseR \u0393 e0 e1 \u03c41 \u03c42 \u03c4' :\n     typed \u0393 e0 (TSum \u03c41 \u03c42) \u2192 typed \u0393 e1 (TArrow \u03c41 \u03c4') \u2192\n     typed_ctx_item (CTX_CaseR e0 e1) \u0393 (TArrow \u03c42 \u03c4') \u0393 \u03c4'\n  (* Heap *)\n  | TPCTX_Alloc \u0393 \u03c4 :\n     typed_ctx_item CTX_Alloc \u0393 \u03c4 \u0393 (TRef \u03c4)\n  | TP_CTX_Load \u0393 \u03c4 :\n     typed_ctx_item CTX_Load \u0393 (TRef \u03c4) \u0393 \u03c4\n  | TP_CTX_StoreL \u0393 e2 \u03c4 :\n     typed \u0393 e2 \u03c4 \u2192 typed_ctx_item (CTX_StoreL e2) \u0393 (TRef \u03c4) \u0393 ()\n  | TP_CTX_StoreR \u0393 e1 \u03c4 :\n     typed \u0393 e1 (TRef \u03c4) \u2192\n     typed_ctx_item (CTX_StoreR e1) \u0393 \u03c4 \u0393 ()\n  (* Polymorphic & recursive types *)\n  | TP_CTX_Fold \u0393 \u03c4 :\n     typed_ctx_item CTX_Fold \u0393 \u03c4.[(TRec \u03c4)/] \u0393 (TRec \u03c4)\n  | TP_CTX_Unfold \u0393 \u03c4 :\n     typed_ctx_item CTX_Unfold \u0393 (TRec \u03c4) \u0393 \u03c4.[(TRec \u03c4)/]\n  | TP_CTX_TLam \u0393 \u03c4 :\n     typed_ctx_item CTX_TLam (Autosubst_Classes.subst (ren (+1)) <$> \u0393) \u03c4 \u0393 (TForall \u03c4)\n  | TP_CTX_TApp \u0393 \u03c4 \u03c4' :\n     typed_ctx_item CTX_TApp \u0393 (TForall \u03c4) \u0393 \u03c4.[\u03c4'/]\n  (* | TP_CTX_Pack \u0393 \u03c4 \u03c4' : *)\n  (*    typed_ctx_item CTX_Pack \u0393 \u03c4.[\u03c4'/] \u0393 (TExists \u03c4) *)\n  | TP_CTX_UnpackL x e2 \u0393 \u03c4 \u03c42 :\n     <[x:=\u03c4]>(\u2909 \u0393) \u22a2\u209c e2 : (Autosubst_Classes.subst (ren (+1)) \u03c42) \u2192\n     typed_ctx_item (CTX_UnpackL x e2) \u0393 (TExists \u03c4) \u0393 \u03c42\n  | TP_CTX_UnpackR x e1 \u0393 \u03c4 \u03c42 :\n      \u0393 \u22a2\u209c e1 : TExists \u03c4 \u2192\n     typed_ctx_item (CTX_UnpackR x e1)\n                    (<[x:=\u03c4]>(\u2909 \u0393)) (Autosubst_Classes.subst (ren (+1)) \u03c42)\n                    \u0393 \u03c42\n  | TP_CTX_Flip \u0393 :\n     typed_ctx_item CTX_Flip \u0393 TTape \u0393 (TBool)\n.\n\nInductive typed_ctx: ctx \u2192 stringmap type \u2192 type \u2192 stringmap type \u2192 type \u2192 Prop :=\n  | TPCTX_nil \u0393 \u03c4 :\n     typed_ctx nil \u0393 \u03c4 \u0393 \u03c4\n  | TPCTX_cons \u03931 \u03c41 \u03932 \u03c42 \u03933 \u03c43 k K :\n     typed_ctx_item k \u03932 \u03c42 \u03933 \u03c43 \u2192\n     typed_ctx K \u03931 \u03c41 \u03932 \u03c42 \u2192\n     typed_ctx (k :: K) \u03931 \u03c41 \u03933 \u03c43.\n\n(** The main definition of contextual refinement that we use. An\n    alternative (equivalent) formulation which observes only\n    termination can be found in [contextual_refinement_alt.v] *)\nDefinition ctx_refines (\u0393 : stringmap type)\n    (e e' : expr) (\u03c4 : type) : Prop := \u2200 K \u03c3\u2080 (b : bool),\n  typed_ctx K \u0393 \u03c4 \u2205 TBool \u2192\n  (lim_exec_val (fill_ctx K e, \u03c3\u2080) #b <= lim_exec_val (fill_ctx K e', \u03c3\u2080) #b)%R.\n\nNotation \"\u0393 \u22a8 e '\u2264ctx\u2264' e' : \u03c4\" :=\n  (ctx_refines \u0393 e e' \u03c4) (at level 100, e, e' at next level, \u03c4 at level 200).\n\nLemma typed_ctx_item_typed k \u0393 \u03c4 \u0393' \u03c4' e :\n  typed \u0393 e \u03c4 \u2192 typed_ctx_item k \u0393 \u03c4 \u0393' \u03c4' \u2192\n  typed \u0393' (fill_ctx_item k e) \u03c4'.\nProof. induction 2; simpl; eauto using typed. Qed.\n\nLemma typed_ctx_typed K \u0393 \u03c4 \u0393' \u03c4' e :\n  typed \u0393 e \u03c4 \u2192 typed_ctx K \u0393 \u03c4 \u0393' \u03c4' \u2192 typed \u0393' (fill_ctx K e) \u03c4'.\nProof. induction 2; simpl; eauto using typed_ctx_item_typed. Qed.\n\nGlobal Instance ctx_refines_reflexive \u0393 \u03c4 :\n  Reflexive (fun e1 e2 => ctx_refines \u0393 e1 e2 \u03c4).\nProof. intros ?????. done. Qed.\n\nGlobal Instance ctx_refines_transitive \u0393 \u03c4 :\n  Transitive (fun e1 e2 => ctx_refines \u0393 e1 e2 \u03c4).\nProof.\n  intros e1 e2 e3 Hctx1 Hctx2 K \u03c3\u2080 b Hty.\n  pose proof (Hctx1 K \u03c3\u2080 b Hty) as H1.\n  pose proof (Hctx2 K \u03c3\u2080 b Hty) as H2.\n  by etrans.\nQed.\n\nLemma fill_ctx_app (K K' : ctx) (e : expr) :\n  fill_ctx K' (fill_ctx K e) = fill_ctx (K' ++ K) e.\nProof. by rewrite /fill_ctx foldr_app. Qed.\n\nLemma typed_ctx_compose (K K' : ctx) (\u03931 \u03932 \u03933 : stringmap type) (\u03c41 \u03c42 \u03c43 : type) :\n  typed_ctx K \u03931 \u03c41 \u03932 \u03c42 \u2192\n  typed_ctx K' \u03932 \u03c42 \u03933 \u03c43 \u2192\n  typed_ctx (K' ++ K) \u03931 \u03c41 \u03933 \u03c43.\nProof.\n  revert \u03931 \u03932 \u03933 \u03c41 \u03c42 \u03c43.\n  induction K' as [|k K'] => \u03931 \u03932 \u03933 \u03c41 \u03c42 \u03c43.\n  - by inversion 2; simplify_eq/=.\n  - intros HK.\n    inversion 1 as [|? ? ? ? ? ? ? ? Hx1 Hx2]; simplify_eq/=.\n    specialize (IHK' _ _ _ _ _ _ HK Hx2).\n    econstructor; eauto.\nQed.\n\nLemma ctx_refines_congruence \u0393 e1 e2 \u03c4 \u0393' \u03c4' K :\n  typed_ctx K \u0393 \u03c4 \u0393' \u03c4' \u2192\n  (\u0393 \u22a8 e1 \u2264ctx\u2264 e2 : \u03c4) \u2192\n  \u0393' \u22a8 fill_ctx K e1 \u2264ctx\u2264 fill_ctx K e2 : \u03c4'.\nProof.\n  intros HK Hctx K' \u03c3\u2080 b Hty.\n  rewrite !fill_ctx_app.\n  apply (Hctx (K' ++ K) \u03c3\u2080); auto.\n  eapply typed_ctx_compose; eauto.\nQed.\n\nDefinition ctx_equiv \u0393 e1 e2 \u03c4 :=\n  (\u0393 \u22a8 e1 \u2264ctx\u2264 e2 : \u03c4) \u2227 (\u0393 \u22a8 e2 \u2264ctx\u2264 e1 : \u03c4).\n\nNotation \"\u0393 \u22a8 e '=ctx=' e' : \u03c4\" :=\n  (ctx_equiv \u0393 e e' \u03c4) (at level 100, e, e' at next level, \u03c4 at level 200).\n\nSection bin_log_related_under_typed_ctx.\n  Context `{!prelogrelGS \u03a3}.\n\n  (* Precongruence *)\n  Lemma bin_log_related_under_typed_ctx \u0393 e e' \u03c4 \u0393' \u03c4' K :\n    (typed_ctx K \u0393 \u03c4 \u0393' \u03c4') \u2192\n    (\u25a1 \u2200 \u0394, ({\u0394;\u0393} \u22a8 e \u2264log\u2264 e' : \u03c4)) -\u2217\n      (\u2200 \u0394, {\u0394;\u0393'} \u22a8 fill_ctx K e \u2264log\u2264 fill_ctx K e' : \u03c4')%I.\n  Proof.\n    revert \u0393 \u03c4 \u0393' \u03c4' e e'.\n    induction K as [|k K]=> \u0393 \u03c4 \u0393' \u03c4' e e'; simpl.\n    - inversion_clear 1; trivial. iIntros \"#H\".\n      iIntros (\u0394). by iApply \"H\".\n    - inversion_clear 1 as [|? ? ? ? ? ? ? ? Hx1 Hx2].\n      specialize (IHK _ _ _ _ e e' Hx2).\n      inversion Hx1; subst; simpl; iIntros \"#Hrel\";\n        iIntros (\u0394).\n      + iApply (bin_log_related_rec with \"[-]\"); auto.\n        iModIntro. iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_app with \"[]\").\n        { iApply (IHK with \"[Hrel]\"); auto. }\n        by iApply fundamental.\n      + iApply (bin_log_related_app _ _ _ _ _ _ \u03c42 with \"[]\").\n        { by iApply fundamental. }\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_int_unop; eauto.\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_bool_unop; eauto.\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_int_binop;\n          try (by iApply fundamental); eauto.\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_int_binop;\n          try (by iApply fundamental); eauto.\n        by iApply (IHK with \"Hrel\"); auto.\n      + iApply bin_log_related_bool_binop;\n          try (by iApply fundamental); eauto.\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_bool_binop;\n          try (by iApply fundamental); eauto.\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_unboxed_eq; try (eassumption || by iApply fundamental).\n        by iApply (IHK with \"Hrel\").\n      + iApply bin_log_related_unboxed_eq; try (eassumption || by iApply fundamental).\n        by iApply (IHK with \"Hrel\").\n      + iApply (bin_log_related_if with \"[] []\");\n          try by iApply fundamental.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_if with \"[] []\");\n          try by iApply fundamental.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_if with \"[] []\");\n          try by iApply fundamental.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_pair with \"[]\").\n        { iApply (IHK with \"[Hrel]\"); auto. }\n        by iApply fundamental.\n      + iApply (bin_log_related_pair with \"[]\").\n        { by iApply fundamental. }\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_fst.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_snd.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_injl.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_injr.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_case with \"[] []\").\n        { iApply (IHK with \"[Hrel]\"); auto. }\n        { by iApply fundamental. }\n        by iApply fundamental.\n      + iApply (bin_log_related_case with \"[] []\").\n        { by iApply fundamental. }\n        { iApply (IHK with \"[Hrel]\"); auto. }\n        by iApply fundamental.\n      + iApply (bin_log_related_case with \"[] []\").\n        { by iApply fundamental. }\n        { by iApply fundamental. }\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_alloc with \"[]\").\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_load with \"[]\").\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_store with \"[]\");\n          try by iApply fundamental.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_store with \"[]\");\n          try by iApply fundamental.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_fold with \"[]\").\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_unfold with \"[]\").\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_tlam with \"[]\").\n        iIntros (\u03c4i). iModIntro.\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply (bin_log_related_tapp' with \"[]\").\n        iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_unpack.\n        * iApply (IHK with \"[Hrel]\"); auto.\n        * iIntros (A). by iApply fundamental.\n      + iApply bin_log_related_unpack.\n        * by iApply fundamental.\n        * iIntros (A). iApply (IHK with \"[Hrel]\"); auto.\n      + iApply bin_log_related_flip.\n        iApply (IHK with \"[Hrel]\"); auto.\n  Qed.\nEnd bin_log_related_under_typed_ctx.\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/contextual_refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.18112858863295325}}
{"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(*                       identity_abs_val                             *)\n(*                                                                    *)\n(*                          Barry Jay                                 *)\n(*                                                                    *)\n(**********************************************************************)\n\n\n\nAdd LoadPath \"..\" as IntensionalLib.\n\nRequire Import Arith Omega Max Bool List.\n\nFrom Bignums Require Import BigN. \n\nRequire Import IntensionalLib.Closure_calculus.Closure_calculus.\n\nRequire Import IntensionalLib.Fieska_calculus.Test.\nRequire Import IntensionalLib.Fieska_calculus.General.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Terms.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Tactics.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_reduction.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Normal.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Closed.\nRequire Import IntensionalLib.Fieska_calculus.Substitution.\nRequire Import IntensionalLib.Fieska_calculus.Fieska_Eval.\nRequire Import IntensionalLib.Fieska_calculus.Star.\nRequire Import IntensionalLib.Fieska_calculus.Fixpoints.\nRequire Import IntensionalLib.Fieska_calculus.Extensions.\nRequire Import IntensionalLib.Closure_to_Fieska.Tagging.\nRequire Import IntensionalLib.Closure_to_Fieska.Adding.\nRequire Import IntensionalLib.Closure_to_Fieska.Fieska_size.\n\nRequire Import IntensionalLib.Closure_to_Fieska.Abstraction_to_Combination.\n\n\nLemma size_identity_abs: \nsize (lambda_to_fieska (Abs Closure_calculus.Iop 0%nat (Closure_calculus.Ref 0%nat))) = 4436%bigN.\nProof. cbv. auto. Qed. \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/Closure_to_Fieska/identity_abs_val.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061854293323, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.18108581556769981}}
{"text": "From isla Require Import opsem.\n\nDefinition a7434 : isla_trace :=\n  Smt (DeclareConst 0%Z (Ty_BitVec 16%N)) Mk_annot :t:\n  Smt (DeclareConst 92%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R6\" [] (RegVal_Base (Val_Symbolic 92%Z)) Mk_annot :t:\n  Smt (DefineConst 95%Z (Manyop (Bvmanyarith Bvor) [Manyop (Bvmanyarith Bvand) [Val (Val_Symbolic 92%Z) Mk_annot; Val (Val_Bits (BV 64%N 0xffffffffffff%Z)) Mk_annot] Mk_annot; Binop ((Bvarith Bvshl)) (Unop (ZeroExtend 48%N) (Val (Val_Symbolic 0%Z) Mk_annot) Mk_annot) (Val (Val_Bits (BV 64%N 0x30%Z)) Mk_annot) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"R6\" [] (RegVal_Base (Val_Symbolic 95%Z)) Mk_annot :t:\n  Smt (DeclareConst 96%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 96%Z)) Mk_annot :t:\n  Smt (DefineConst 97%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 96%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 97%Z)) Mk_annot :t:\n  tnil\n.\n", "meta": {"author": "rems-project", "repo": "islaris", "sha": "fcc5791c74a2f791dee9080263cd64e42e73bc39", "save_path": "github-repos/coq/rems-project-islaris", "path": "github-repos/coq/rems-project-islaris/islaris-fcc5791c74a2f791dee9080263cd64e42e73bc39/pkvm_handler/a7434.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.18108581021308354}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*          for the C functions implemented in the MPTCommon layer     *)\n(*                                                                     *)\n(*                        Xiongnan (Newman) Wu                         *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import MPTCommon.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import PTKernGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import AbstractDataType.\nRequire Import MPTCommonCSource.\nRequire Import TacticsForTesting.\nRequire Import XOmega.\n\nModule MPTCOMMONCODE.\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n\n\n\n    Section PTINSERT.\n\n      Let L: compatlayer (cdata RData) := pt_read_pde \u21a6 gensem ptReadPDE_spec\n          \u2295 pt_insert_aux \u21a6 gensem ptInsertAux_spec\n          \u2295 pt_alloc_pde \u21a6 gensem ptAllocPDE_spec\n          \u2295 at_get_c \u21a6 gensem get_at_c_spec\n          \u2295 at_set_c \u21a6 gensem set_at_c0_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Local Open Scope Z_scope.\n\n      Section PTInsertBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** pt_read_pde *)\n\n        Variable bpt_read_pde: block.\n\n        Hypothesis hpt_read_pde1 : Genv.find_symbol ge pt_read_pde = Some bpt_read_pde. \n        \n        Hypothesis hpt_read_pde2 : Genv.find_funct_ptr ge bpt_read_pde = Some (External (EF_external pt_read_pde (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (** pt_insert_aux *)\n\n        Variable bpt_insert_aux: block.\n\n        Hypothesis hpt_insert_aux1 : Genv.find_symbol ge pt_insert_aux = Some bpt_insert_aux. \n        \n        Hypothesis hpt_insert_aux2 : Genv.find_funct_ptr ge bpt_insert_aux = Some (External (EF_external pt_insert_aux (signature_of_type (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) Tvoid cc_default).\n\n        (** pt_alloc_pde *)\n\n        Variable bpt_alloc_pde: block.\n\n        Hypothesis hpt_alloc_pde1 : Genv.find_symbol ge pt_alloc_pde = Some bpt_alloc_pde. \n        \n        Hypothesis hpt_alloc_pde2 : Genv.find_funct_ptr ge bpt_alloc_pde = Some (External (EF_external pt_alloc_pde (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (** at_get_c *)\n\n        Variable bat_get_c: block.\n\n        Hypothesis hat_get_c1 : Genv.find_symbol ge at_get_c = Some bat_get_c. \n        \n        Hypothesis hat_get_c2 : Genv.find_funct_ptr ge bat_get_c = Some (External (EF_external at_get_c (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        (** at_set_c *)\n\n        Variable bat_set_c: block.\n\n        Hypothesis hat_set_c1 : Genv.find_symbol ge at_set_c = Some bat_set_c. \n        \n        Hypothesis hat_set_c2 : Genv.find_funct_ptr ge bat_set_c = Some (External (EF_external at_set_c (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n\n        Lemma pt_insert_body_correct: forall m d d' env le proc_index vadr padr perm v,\n                                           env = PTree.empty _ ->\n                                           PTree.get tproc_index le = Some (Vint proc_index) ->\n                                           PTree.get tvadr le = Some (Vint vadr) ->\n                                           PTree.get tpadr le = Some (Vint padr) ->\n                                           PTree.get tperm le = Some (Vint perm) ->\n                                           ptInsert_spec (Int.unsigned proc_index) (Int.unsigned vadr)\n                                                         (Int.unsigned padr) (Int.unsigned perm) d = Some (d', Int.unsigned v) ->\n                                           high_level_invariant d ->\n                                           exists le',\n                                             exec_stmt ge env le ((m, d): mem) pt_insert_body E0 le' (m, d') (Out_return (Some (Vint v, tint))).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            generalize one_k_minus1; intro one_k_minus1.\n            intros.\n            subst.\n            unfold pt_insert_body.\n            destruct H5.\n            functional inversion H4; subst.\n            {\n              generalize (valid_nps H9); intro npsrange.\n              functional inversion H14; subst.\n              functional inversion H6; subst.\n              functional inversion H; subst.\n              unfold pt, pdi, pti, pt0, pdi0, pti0, pdt', pt' in *.\n              esplit.\n              repeat vcgen.\n              unfold ptReadPDE_spec.\n              unfold getPDE_spec.\n              rewrite H8, H9, H10, H11.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite H19.\n              instantiate (1:= Int.repr pi0).\n              rewrite Int.unsigned_repr.\n              reflexivity.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              unfold ptInsertAux_spec.\n              unfold setPTE_spec.\n              rewrite H8, H9, H10, H11, H12, H18, H19, H23.\n              unfold PTE_Arg.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite zle_le_true.\n              reflexivity.\n              unfold PTX.\n              assert (0 < one_k) by omega.\n              generalize (Z.mod_pos_bound (Int.unsigned vadr / 4096) one_k H26); intro.\n              change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              unfold get_at_c_spec.\n              simpl.\n              rewrite H10, H11, H21.\n              rewrite zle_lt_true.\n              instantiate (1:= Int.repr c).\n              rewrite Int.unsigned_repr; try omega.\n              reflexivity.\n              omega.\n              unfold set_at_c0_spec.\n              simpl.\n              rewrite H10, H11, H21.\n              rewrite zle_lt_true.\n              rewrite Int.unsigned_repr.\n              reflexivity.\n              omega.\n              omega.\n              repeat vcgen.\n              simpl.\n              rewrite H5.\n              rewrite Int.repr_unsigned.\n              repeat vcgen.\n            }\n            {\n              generalize (valid_nps H9); intro npsrange.\n              unfold pt, pdi, pti in *.\n              functional inversion H6; subst.\n              functional inversion H; subst.\n              esplit.\n              repeat vcgen.\n              unfold ptReadPDE_spec.\n              unfold getPDE_spec.\n              rewrite H8, H9, H10, H11, H13.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              change 0 with (Int.unsigned Int.zero).\n              reflexivity.\n              unfold PDX.\n              xomega.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              simpl.\n              rewrite H5.\n              rewrite Int.repr_unsigned.\n              repeat vcgen.\n            }\n            {\n              generalize (valid_nps H9); intro npsrange.\n              unfold pt, pdi, pti in *.\n              functional inversion H6; subst.\n              functional inversion H; subst.\n              functional inversion H14.\n              unfold pdi0 in *.\n              functional inversion H16.\n              unfold pt0, pdi1, pti0, pdt', pt' in *. \n              rewrite <- H19, <- H31 in *; simpl in *.\n              destruct _x4.\n              destruct a0.\n              esplit. \n              repeat vcgen.\n              unfold ptReadPDE_spec.\n              unfold getPDE_spec.\n              rewrite H8, H9, H10, H11, H13.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              change 0 with (Int.unsigned Int.zero).\n              reflexivity.\n              unfold PDX.\n              xomega.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              repeat vcgen.\n              unfold ptInsertAux_spec.\n              unfold setPTE_spec.\n              simpl.\n              rewrite H5, H8, H9, H10.\n              rewrite H11, H12, H27, H36.\n              repeat rewrite ZMap.gss.\n              unfold PTE_Arg.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite zle_le_true.\n              reflexivity.\n              unfold PTX.\n              assert (0 < one_k) by omega.\n              generalize (Z.mod_pos_bound (Int.unsigned vadr / 4096) one_k H40); intro.\n              change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              unfold get_at_c_spec.\n              simpl.\n              rewrite H10, H11, H38.\n              rewrite zle_lt_true.\n              instantiate (1:= Int.repr c0).\n              rewrite Int.unsigned_repr; try omega.\n              reflexivity.\n              omega.\n              unfold set_at_c0_spec.\n              simpl.\n              rewrite H10, H11, H38.\n              rewrite zle_lt_true.\n              repeat rewrite Int.unsigned_repr; try omega.\n              simpl.\n              unfold pdt', pt0, pdi1 in *.\n              rewrite <- H19; simpl in *.\n              assert (HSpeed:\n                        forall hp a p ptp ptp' a' ac,\n                          Some (d {HP : hp} {AT: a} {pperm: p} {ptpool: ptp} {AC: ac} {ptpool: ptp'} {AT: a'})\n                          = ret (d {HP : hp} {AT: a} {pperm: p} {ptpool: ptp} {AC: ac} {AT: a'} {ptpool: ptp'})).\n              {\n                intros. reflexivity.\n              }\n              repeat rewrite ZMap.gss.\n              apply HSpeed.\n              omega.\n              repeat vcgen.\n              repeat vcgen.\n\n              (* contradiction case *)\n              clear H15.\n              rewrite H20 in _x.\n              contradiction _x.\n              reflexivity.\n            }\n          Qed.\n\n      End PTInsertBody.\n\n\n      Theorem pt_insert_code_correct:\n        spec_le (pt_insert \u21a6 ptInsert_spec_low) (\u301apt_insert \u21a6 f_pt_insert \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *. \n        fbigstep_pre L'.\n        fbigstep (pt_insert_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp b2 Hb2fs Hb2fp b3 Hb3fs Hb3fp b4 Hb4fs Hb4fp m'0 labd labd' (PTree.empty _) \n                                      (bind_parameter_temps' (fn_params f_pt_insert)\n                                                             (Vint n::Vint vadr::Vint padr::Vint p0::nil)\n                                                             (create_undef_temps (fn_temps f_pt_insert)))) H0. \n      Qed.\n\n\n    End PTINSERT.\n\n\n\n    Section PTRMV.\n\n      Let L: compatlayer (cdata RData) := pt_read \u21a6 gensem ptRead_spec\n          \u2295 pt_rmv_aux \u21a6 gensem ptRmvAux_spec\n          \u2295 at_get_c \u21a6 gensem get_at_c_spec\n          \u2295 at_set_c \u21a6 gensem set_at_c0_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Local Open Scope Z_scope.\n\n      Section PTRmvBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** pt_read *)\n\n        Variable bpt_read: block.\n\n        Hypothesis hpt_read1 : Genv.find_symbol ge pt_read = Some bpt_read. \n        \n        Hypothesis hpt_read2 : Genv.find_funct_ptr ge bpt_read = Some (External (EF_external pt_read (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        (** pt_rmv_aux *)\n\n        Variable bpt_rmv_aux: block.\n\n        Hypothesis hpt_rmv_aux1 : Genv.find_symbol ge pt_rmv_aux = Some bpt_rmv_aux. \n        \n        Hypothesis hpt_rmv_aux2 : Genv.find_funct_ptr ge bpt_rmv_aux = Some (External (EF_external pt_rmv_aux (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n        (** at_get_c *)\n\n        Variable bat_get_c: block.\n\n        Hypothesis hat_get_c1 : Genv.find_symbol ge at_get_c = Some bat_get_c. \n        \n        Hypothesis hat_get_c2 : Genv.find_funct_ptr ge bat_get_c = Some (External (EF_external at_get_c (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        (** at_set_c *)\n\n        Variable bat_set_c: block.\n\n        Hypothesis hat_set_c1 : Genv.find_symbol ge at_set_c = Some bat_set_c. \n        \n        Hypothesis hat_set_c2 : Genv.find_funct_ptr ge bat_set_c = Some (External (EF_external at_set_c (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n\n        Lemma pt_rmv_body_correct: forall m d d' env le proc_index vadr v,\n                                           env = PTree.empty _ ->\n                                           PTree.get tproc_index le = Some (Vint proc_index) ->\n                                           PTree.get tvadr le = Some (Vint vadr) ->\n                                           ptRmv_spec (Int.unsigned proc_index) (Int.unsigned vadr) d = Some (d', Int.unsigned v) ->\n                                           exists le',\n                                             exec_stmt ge env le ((m, d): mem) pt_rmv_body E0 le' (m, d') (Out_return (Some (Vint v, tint))).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            generalize one_k_minus1; intro one_k_minus1.\n            intros.\n            subst.\n            unfold pt_rmv_body.\n            functional inversion H2; subst.\n            {\n              unfold pt, pdi, pti, pdt', pt' in *.\n              functional inversion H4.\n              assert(range: 0 < Int.unsigned v * 4096 + PermtoZ _x0 <= Int.max_unsigned).\n              {\n                unfold PermtoZ.\n                destruct _x0; try omega.\n                destruct b; omega.\n              }\n              assert(divval: (Int.unsigned v * 4096 + PermtoZ _x0) / 4096 = Int.unsigned v).\n              {\n                destruct _x0; simpl.\n                xomega.\n                xomega.\n                destruct b; xomega.\n              }\n              esplit.\n              repeat vcgen.\n              unfold ptRead_spec.\n              unfold getPTE_spec.\n              rewrite H6, H7, H8, H9.\n              unfold PTE_Arg.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite zle_le_true.\n              rewrite H11, H12.\n              instantiate (1:= (Int.repr (Int.unsigned v * 4096 + PermtoZ _x0))).\n              rewrite Int.unsigned_repr; try omega.\n              reflexivity.\n              unfold PTX.\n              assert (0 < one_k) by omega.\n              generalize (Z.mod_pos_bound (Int.unsigned vadr / 4096) one_k H16); intro.\n              change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              unfold ptRmvAux_spec.\n              unfold rmvPTE_spec.\n              rewrite H6, H7, H8, H9.\n              unfold PTE_Arg.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite zle_le_true.\n              rewrite H10, H11.\n              reflexivity.\n              unfold PTX.\n              assert (0 < one_k) by omega.\n              generalize (Z.mod_pos_bound (Int.unsigned vadr / 4096) one_k H16); intro.\n              change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              rewrite divval.\n              unfold get_at_c_spec.\n              simpl.\n              rewrite H8, H9, H14.\n              rewrite zle_lt_true.\n              instantiate (1:= Int.repr c).\n              rewrite Int.unsigned_repr; try omega.\n              reflexivity.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              rewrite divval.\n              unfold set_at_c0_spec.\n              simpl.\n              rewrite H8, H9, H14.\n              rewrite zle_lt_true.\n              reflexivity.\n              omega.\n              repeat vcgen.\n              simpl.\n              unfold sem_div.\n              unfold sem_binarith; simpl.\n              discharge_cmp.\n              rewrite divval.\n              rewrite Int.repr_unsigned.\n              reflexivity.\n            }\n            {\n              unfold pt, pdi, pti in *.\n              functional inversion H4.\n              esplit.\n              repeat vcgen.\n              unfold ptRead_spec.\n              unfold getPTE_spec.\n              rewrite H6, H7, H8, H9.\n              unfold PTE_Arg.\n              unfold PDE_Arg.\n              rewrite zle_lt_true.\n              rewrite zle_le_true.\n              rewrite zle_le_true.\n              rewrite H11, H12.\n              change 0 with (Int.unsigned Int.zero).\n              reflexivity.\n              unfold PTX.\n              assert (0 < one_k) by omega.\n              generalize (Z.mod_pos_bound (Int.unsigned vadr / 4096) one_k H14); intro.\n              change ((Int.max_unsigned / 4096) mod 1024) with 1023.\n              omega.\n              unfold PDX.\n              xomega.\n              omega.\n              discharge_cmp.\n              repeat vcgen.\n              simpl.\n              rewrite PTree.gss.\n              f_equal.\n              simpl.\n              unfold sem_div.\n              unfold sem_binarith; simpl.\n              discharge_cmp.\n              f_equal.\n              f_equal.\n              erewrite <- unsigned_inj.\n              reflexivity.\n              rewrite <- H3.\n              rewrite Int.unsigned_repr.\n              reflexivity.\n              xomega.\n            }\n          Qed.\n\n      End PTRmvBody.\n\n\n      Theorem pt_rmv_code_correct:\n        spec_le (pt_rmv \u21a6 ptRmv_spec_low) (\u301apt_rmv \u21a6 f_pt_rmv \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *. \n        fbigstep_pre L'.\n        fbigstep (pt_rmv_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp b2 Hb2fs Hb2fp b3 Hb3fs Hb3fp m'0 labd labd' (PTree.empty _) \n                                      (bind_parameter_temps' (fn_params f_pt_rmv)\n                                                             (Vint n::Vint vadr::nil)\n                                                             (create_undef_temps (fn_temps f_pt_rmv)))) H0. \n      Qed.\n\n    End PTRMV.\n\n\n\n    Section PTINITKERN.\n\n      Let L: compatlayer (cdata RData) := pt_init_comm \u21a6 gensem pt_init_comm_spec \u2295 set_PDE \u21a6 gensem setPDE_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Local Open Scope Z_scope.\n\n      Section PTInitKernBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** set_PDE *)\n\n        Variable bset_PDE: block.\n\n        Hypothesis hset_PDE1 : Genv.find_symbol ge set_PDE = Some bset_PDE. \n        \n        Hypothesis hset_PDE2 : Genv.find_funct_ptr ge bset_PDE = Some (External (EF_external set_PDE (signature_of_type (Tcons tint (Tcons tint  Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n        \n        (** pt_init_comm *)\n\n        Variable bptinitcomm: block.\n\n        Hypothesis hpt_init_comm1 : Genv.find_symbol ge pt_init_comm = Some bptinitcomm. \n        \n        Hypothesis hpt_init_comm2 : Genv.find_funct_ptr ge bptinitcomm = Some (External (EF_external pt_init_comm (signature_of_type (Tcons tint Tnil) Tvoid cc_default)) (Tcons tint Tnil) Tvoid cc_default).\n\n\n        Definition pt_init_kern_mk_rdata adt (index: Z) := adt {ptpool: (Calculate_pt_kern (Z.to_nat (index - 256)) (ptpool adt))}.\n\n        Section pt_init_kern_loop_proof.\n\n          Variable minit: memb.\n          Variable adt: RData.\n\n          Hypothesis init: init adt = true.\n          Hypothesis ipt: ipt adt = true.\n          Hypothesis pg: pg adt = false.\n          Hypothesis ihost: ihost adt = true.\n          Hypothesis ikern: ikern adt = true.\n\n          Definition pt_init_kern_loop_body_P (le: temp_env) (m: mem): Prop :=\n            PTree.get ti le = Some (Vint (Int.repr 256)) /\\ \n            m = (minit, adt).\n\n          Definition pt_init_kern_loop_body_Q (le : temp_env) (m: mem): Prop :=    \n            m = (minit, pt_init_kern_mk_rdata adt (960 - 1)).\n\n          Lemma pt_init_kern_loop_correct_aux : LoopProofSimpleWhile.t pt_init_kern_while_condition pt_init_kern_while_body ge (PTree.empty _) (pt_init_kern_loop_body_P) (pt_init_kern_loop_body_Q).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            apply LoopProofSimpleWhile.make with\n            (W := Z)\n              (lt := fun z1 z2 => (0 <= z2 /\\ z1 < z2)%Z)\n              (I := fun le (m: mem) w => exists i,\n                                           PTree.get ti le = Some (Vint i) /\\\n                                           256 <= Int.unsigned i <= 960 /\\ \n                                           (Int.unsigned i = 256 /\\ m = (minit, adt) \\/ Int.unsigned i > 256 /\\ m =(minit, pt_init_kern_mk_rdata adt (Int.unsigned i - 1))) /\\\n                                           w = 960 - Int.unsigned i\n              )\n            .\n            apply Zwf_well_founded.\n            intros.\n            unfold pt_init_kern_loop_body_P in H.\n            destruct H as [tile tmpH].\n            destruct tmpH as [pdtvalid msubst].\n            subst.\n            esplit. esplit. \n            repeat vcgen.\n            intros.\n            destruct H as [i tmpH].\n            destruct tmpH as [tile tmpH].\n            destruct tmpH as [irange tmpH].\n            destruct tmpH as [invar nval].\n            subst.\n            unfold pt_init_kern_while_condition.\n            unfold pt_init_kern_while_body.\n            destruct irange as [ilow ihigh].\n            apply Zle_lt_or_eq in ihigh.\n\n            Caseeq ihigh.\n\n            (* i < 960 *)\n            intro ihigh.\n\n            destruct m.\n\n            case_eq invar;intros.\n            (* i = 256 *)\n            destruct a.\n            injection e0; intros; subst.\n\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            exists (960 - Int.unsigned i - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            \n            right.\n            split.\n            omega.\n            unfold pt_init_kern_mk_rdata.\n            f_equal.\n            f_equal; auto.\n            rewrite e in *; simpl.\n            unfold Calculate_pt_kern_at_i.\n            reflexivity.\n            \n            (* i > 256 *)\n            destruct a as [ilo mval].\n            injection mval; intros; subst.\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            unfold setPDE_spec.\n            simpl.\n            rewrite ipt, pg, ihost, ikern, init.\n            unfold PDE_Arg.\n            unfold zle_lt, zle_le.\n            rewrite one_k_minus1.\n            repeat zdestruct.\n            exists (960 - Int.unsigned i - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            f_equal.\n            unfold pt_init_kern_mk_rdata.\n            replace (Int.unsigned i + 1 - 1 - 256) with (Z.succ (Int.unsigned i - 1 - 256)) by omega.\n            rewrite Z2Nat.inj_succ.\n            Opaque Z.of_nat.\n            simpl.\n            rewrite Nat2Z.inj_succ.\n            rewrite Z2Nat.id.\n            unfold Z.succ.\n            unfold Calculate_pt_kern_at_i.\n            assert(tmp2: (Int.unsigned i - 1 - 256 + 1 + 262144 / 1024) = Int.unsigned i).\n            {\n              change (262144 / 1024) with 256.\n              omega.\n            }\n            rewrite tmp2.\n            reflexivity.\n            omega.\n            omega.\n\n            (* i = 960 *)\n            intro ival.\n            rewrite ival in *.\n            esplit. esplit.\n            repeat vcgen.\n            unfold pt_init_kern_loop_body_Q.\n            Caseeq invar.\n            intro.\n            destruct H0.\n            omega.\n            intro tmpH.\n            destruct tmpH.\n            assumption.\n          Qed.\n\n        End pt_init_kern_loop_proof.\n\n        Lemma pt_init_kern_loop_correct: forall m adt adt' le,\n                                           PTree.get ti le = Some (Vint (Int.repr 256)) ->\n                                           init adt = true ->\n                                           ipt adt = true ->\n                                           pg adt = false ->\n                                           ihost adt = true ->\n                                           ikern adt = true ->\n                                           adt' = pt_init_kern_mk_rdata adt (960 - 1) ->\n                                           exists le', \n                                             exec_stmt ge (PTree.empty _) le ((m, adt): mem) (Swhile pt_init_kern_while_condition pt_init_kern_while_body) E0 le' (m, adt') Out_normal.\n        Proof.\n          intros.\n          generalize (pt_init_kern_loop_correct_aux m adt H0 H1 H2 H3 H4).\n          intro LP.\n          refine (_ (LoopProofSimpleWhile.termination _ _ _ _ _ _ LP le (m, adt) _)).\n          intro pre.\n          destruct pre as [le'' pre].\n          destruct pre as [m'' pre].\n          destruct pre as [pre1 pre2].\n          unfold pt_init_kern_loop_body_Q in pre2.\n          subst.\n          esplit; eassumption.\n          unfold pt_init_kern_loop_body_P.\n          repeat (split; auto).\n        Qed.\n\n        Lemma pt_init_kern_body_correct: forall m d d' env le mbi_adr,\n                                           env = PTree.empty _ ->\n                                           PTree.get tmbi_adr le = Some (Vint mbi_adr) ->\n                                           pt_init_kern_spec (Int.unsigned mbi_adr) d = Some d' ->\n                                           exists le',\n                                             exec_stmt ge env le ((m, d): mem) pt_init_kern_body E0 le' (m, d') Out_normal.\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          unfold pt_init_kern_body.\n          subst.\n          functional inversion H1.\n          simpl in *.\n\n          set (initd := d {vmxinfo: real_vmxinfo} {AT : real_AT (AT d)} {nps : real_nps} {AC: real_AC} {init : true} {ptpool: real_ptp (ptpool d)}\n                          {idpde : CalRealIDPDE.real_idpde (idpde d)}).\n          exploit (pt_init_kern_loop_correct m initd (pt_init_kern_mk_rdata initd (960 - 1)) (PTree.set ti (Vint (Int.repr 256)) (set_opttemp None Vundef le))); try rewrite <- H; try assumption; try reflexivity; try (rewrite PTree.gss; reflexivity).\n          intro stmt.\n          unfold initd in *.\n          destruct stmt as [le' stmt].\n          esplit.\n          change E0 with (E0**E0).\n          econstructor.\n          econstructor; vcgen; try simpleproof.\n          repeat vcgen.\n          repeat vcgen.\n          repeat vcgen.\n          repeat vcgen.\n          repeat vcgen.\n          repeat vcgen.\n          vcgen.\n          unfold pt_init_comm_spec.\n          rewrite H2, H3, H4, H5, H6.\n          reflexivity.\n          change E0 with (E0**E0).\n          econstructor.\n          repeat vcgen.\n          unfold pt_init_kern_mk_rdata, CalRealPT.real_pt in *.\n          Opaque Z.sub Z.add.\n          simpl in stmt.\n          apply stmt.\n        Qed.\n\n      End PTInitKernBody.\n\n      Theorem pt_init_kern_code_correct:\n        spec_le (pt_init_kern \u21a6 pt_init_kern_spec_low) (\u301apt_init_kern \u21a6 f_pt_init_kern \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (pt_init_kern_body_correct s (Genv.globalenv p) makeglobalenv b1 Hb1fs Hb1fp b0 Hb0fs Hb0fp m'0 labd labd' (PTree.empty _) \n                                        (bind_parameter_temps' (fn_params f_pt_init_kern)\n                                                               (Vint mbi_adr::nil)\n                                                               (create_undef_temps (fn_temps f_pt_init_kern)))) H0. \n      Qed.\n\n    End PTINITKERN.\n\n  End WithPrimitives.\n\nEnd MPTCOMMONCODE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MPTCommonCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.32423540551084407, "lm_q1q2_score": 0.18102937941598088}}
{"text": "Require Import Coq.Strings.String.\nFrom MetaCoq.ExtractedPluginDemo Require Import Lens Loader.\n\nSet Primitive Projections.\n\nRecord Point : Set :=\n  { x: nat;\n    y:nat\n  }.\n\nDefinition two:=1+2.\nAbout plus.\n\nLookupPrint two.\n\n\nFail Print zeroE.\n\nMake Lens Point.\n\nSearch Point.\n\nModule A.\n  Showoff.\nEnd A.\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/plugin-demo/test/test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.18099979468732882}}
{"text": "Require Import Bool List String Peano_dec Lia.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Msi Ex.Msi.Msi Ex.Msi.MsiObjInv Ex.Msi.MsiTopo.\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 Msi.ImplOStateIfc.\n\nLemma msi_InObjInds:\n  forall tr (Htr: tr <> Node nil),\n    InvReachable (impl Htr) step_m (InObjInds tr 0).\nProof.\n  intros.\n  apply tree2Topo_InObjInds_inv_ok.\n  - red; simpl; intros.\n    destruct ((implOStatesInit tr)@[oidx]) as [ost|] eqn:Host; simpl; auto.\n    destruct (in_dec idx_dec oidx ((c_li_indices (snd (tree2Topo tr 0)))\n                                     ++ c_l1_indices (snd (tree2Topo tr 0)))); auto.\n    rewrite implOStatesInit_None in Host by assumption.\n    discriminate.\n  - simpl; rewrite c_li_indices_head_rootOf by assumption.\n    apply SubList_cons; [left; reflexivity|].\n    simpl; apply SubList_cons_right.\n    rewrite map_app.\n    do 2 rewrite map_map.\n    apply SubList_app_6.\n    all: simpl; rewrite map_id; apply SubList_refl.\nQed.\n\nLemma msi_OstInds:\n  forall tr (Htr: tr <> Node nil),\n    InvReachable (impl Htr) step_m (OstInds tr 0).\nProof.\n  intros.\n  apply tree2Topo_OstInds_inv_ok.\n  red; simpl; intros.\n  split.\n  - rewrite c_li_indices_head_rootOf in H by assumption.\n    inv H.\n    + rewrite implOStatesInit_value_root by assumption; eauto.\n    + rewrite implOStatesInit_value_non_root by assumption; eauto.\n  - rewrite implORqsInit_value by assumption; eauto.\nQed.\n\nLemma msi_MsgConflictsInv:\n  forall tr (Htr: tr <> Node nil)\n         (Hrcinv: InvReachable (impl Htr) step_m (RootChnInv tr 0)),\n    InvReachable (impl Htr) step_m (MsgConflictsInv tr 0).\nProof.\n  intros.\n  apply tree2Topo_MsgConflicts_inv_ok\n    with (oinvs:= MsiObjInvs (fst (tree2Topo tr 0))); auto.\n  simpl; unfold mem, li, l1.\n  rewrite map_app.\n  do 2 rewrite map_trans.\n  do 2 rewrite map_id.\n  rewrite app_comm_cons.\n  rewrite <-c_li_indices_head_rootOf by assumption.\n  apply SubList_refl.\nQed.\n\nSection ObjInvOk.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Definition MsiUpLockInv (st: State): Prop :=\n    liftObjInvs MsiUpLockObjInv st.\n\n  Definition MsiDownLockInv (st: State): Prop :=\n    liftObjInvs (MsiDownLockObjInv topo) st.\n\n  (*! [MsiUpLockInv] *)\n\n  Lemma MsiUpLockInv_init:\n    Invariant.InvInit impl MsiUpLockInv.\n  Proof.\n    do 3 (red; simpl); intros; red; simpl.\n    destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n    destruct (implORqsInit tr)@[oidx] as [orq|] eqn:Horq; simpl; auto.\n    red; simpl.\n    unfold implORqsInit in Horq.\n    destruct (in_dec idx_dec oidx ((c_li_indices (snd (tree2Topo tr 0)))\n                                     ++ c_l1_indices (snd (tree2Topo tr 0)))).\n    - rewrite initORqs_value in Horq by assumption.\n      inv Horq.\n      mred.\n    - rewrite initORqs_None in Horq by assumption.\n      discriminate.\n  Qed.\n\n  Lemma MsiUpLockInv_update_None:\n    forall oss orqs pmsgs,\n      MsiUpLockInv {| st_oss := oss;\n                       st_orqs := orqs;\n                       st_msgs := pmsgs |} ->\n      forall oidx nost norq nmsgs,\n        norq@[upRq] = None ->\n        MsiUpLockInv {| st_oss := oss +[oidx <- nost];\n                         st_orqs := orqs +[oidx <- norq];\n                         st_msgs := nmsgs |}.\n  Proof.\n    cbv [MsiUpLockInv liftObjInvs liftObjInv MsiUpLockObjInv]; simpl; intros.\n    specialize (H oidx0).\n    mred; simpl.\n    rewrite H0; simpl; auto.\n  Qed.\n\n  Lemma MsiUpLockInv_no_update:\n    forall oss orqs pmsgs,\n      MsiUpLockInv {| st_oss := oss;\n                       st_orqs := orqs;\n                       st_msgs := pmsgs |} ->\n      forall oidx post porq nost norq nmsgs,\n        oss@[oidx] = Some post ->\n        nost#[owned] = post#[owned] ->\n        nost#[status] = post#[status] ->\n        nost#[dir].(dir_st) = post#[dir].(dir_st) ->\n        orqs@[oidx] = Some porq ->\n        norq@[upRq] = porq@[upRq] ->\n        MsiUpLockInv {| st_oss := oss +[oidx <- nost];\n                         st_orqs := orqs +[oidx <- norq];\n                         st_msgs := nmsgs |}.\n  Proof.\n    cbv [MsiUpLockInv liftObjInvs liftObjInv MsiUpLockObjInv]; simpl; intros.\n    mred; auto.\n    simpl; rewrite H1, H2, H3, H5.\n    specialize (H oidx).\n    rewrite H0, H4 in H; simpl in H.\n    assumption.\n  Qed.\n\n  Ltac disc_MsiUpLockInv_internal oidx :=\n    repeat\n      match goal with\n      | [Hdl: MsiUpLockInv _ |- _] =>\n        (specialize (Hdl oidx); do 2 red in Hdl; simpl in Hdl)\n      | [Hmv: ?m@[?i] = Some ?v, H: context [?m@[?i]] |- _] =>\n        rewrite Hmv in H; simpl in H\n      end;\n    disc_msi_obj_invs; dest.\n\n  Ltac disc_MsiDownLockInv_internal oidx :=\n    repeat\n      match goal with\n      | [Hdl: MsiDownLockInv _ |- _] =>\n        (specialize (Hdl oidx); do 2 red in Hdl; simpl in Hdl)\n      | [Hmv: ?m@[?i] = Some ?v, H: context [?m@[?i]] |- _] =>\n        rewrite Hmv in H; simpl in H\n      end;\n    disc_msi_obj_invs; dest.\n\n  Ltac solve_MsiUpLockInv oidx :=\n    try match goal with\n        | [Hul: MsiUpLockInv _ |- _] =>\n          let noidx := fresh \"oidx\" in\n          do 2 red; simpl; intro noidx;\n          red; simpl;\n          repeat (mred; simpl); [|apply Hul; fail]\n        end;\n    disc_MsiUpLockInv_internal oidx;\n    red; mred; simpl;\n    repeat\n      match goal with\n      | [H: _ <+- ?ov; _ |- _ <+- ?ov; _] =>\n        let Hov := fresh \"H\" in\n        let v := fresh \"v\" in\n        destruct ov as [v|] eqn:Hov; simpl in *; [|auto; fail]\n      | [H: msg_id ?rmsg = _ |- context [msg_id ?rmsg] ] =>\n        rewrite H; simpl\n      end;\n    repeat (find_if_inside;\n            [dest; try congruence; repeat split; intuition solve_msi|]);\n    auto.\n\n  Lemma MsiUpLockInv_mutual_step:\n    Invariant.MutualInvStep1 impl step_m MsiUpLockInv MsiDownLockInv.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (msi_GoodORqsInit Htr)\n                  (msi_GoodRqRsSys Htr) H) as Hftinv.\n    inv H2; [assumption..|].\n\n    simpl in H3; destruct H3; [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)))).\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n      simpl in *.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H4; destruct H4 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 (eapply MsiUpLockInv_update_None; eauto; fail).\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst; simpl in *.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H3).\n      destruct H2 as [pidx [? ?]].\n      pose proof (Htn _ _ H5); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H4; destruct H4.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H4; destruct H4 as [crls [? ?]].\n        apply in_map_iff in H4; destruct H4 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 (eapply MsiUpLockInv_update_None; eauto; fail).\n        all: try (eapply MsiUpLockInv_no_update; eauto; mred; fail).\n        all: solve_MsiUpLockInv oidx.\n      }\n\n      dest_in; disc_rule_conds_ex.\n      all: try (eapply MsiUpLockInv_update_None; eauto; mred; fail).\n      all: try (eapply MsiUpLockInv_no_update; eauto;\n                unfold addRqS; mred; fail).\n      all: try (solve_MsiUpLockInv oidx; fail).\n      all: try (solve_MsiUpLockInv oidx; unfold addRqS; mred; fail).\n      all: try (disc_MsiDownLockInv_internal oidx; solve_MsiUpLockInv oidx; fail).\n      { disc_MsiDownLockInv_internal oidx.\n        destruct H22; dest.\n        all: solve_MsiUpLockInv oidx.\n      }\n\n    - (*! Cases for L1 caches *)\n\n      (** Do case analysis per a rule. *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst.\n      dest_in; disc_rule_conds_ex.\n      all: try (eapply MsiUpLockInv_update_None; eauto; mred; fail).\n      all: try (solve_MsiUpLockInv oidx; fail).\n      all: solve_MsiUpLockInv oidx; unfold addRqS; mred.\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  (*! [MsiDownLockInv] *)\n\n  Lemma MsiDownLockInv_init:\n    Invariant.InvInit impl MsiDownLockInv.\n  Proof.\n    do 3 (red; simpl); intros; red; simpl.\n    destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n    destruct (implORqsInit tr)@[oidx] as [orq|] eqn:Horq; simpl; auto.\n    red; simpl.\n    unfold implORqsInit in Horq.\n    destruct (in_dec idx_dec oidx ((c_li_indices (snd (tree2Topo tr 0)))\n                                     ++ c_l1_indices (snd (tree2Topo tr 0)))).\n    - rewrite initORqs_value in Horq by assumption.\n      inv Horq.\n      mred.\n    - rewrite initORqs_None in Horq by assumption.\n      discriminate.\n  Qed.\n\n  Lemma MsiDownLockInv_update_None:\n    forall oss orqs pmsgs,\n      MsiDownLockInv {| st_oss := oss; st_orqs := orqs; st_msgs := pmsgs |} ->\n      forall oidx nost norq nmsgs,\n        norq@[downRq] = None ->\n        MsiDownLockInv {| st_oss := oss +[oidx <- nost];\n                          st_orqs := orqs +[oidx <- norq];\n                          st_msgs := nmsgs |}.\n  Proof.\n    cbv [MsiDownLockInv liftObjInvs liftObjInv MsiDownLockObjInv]; simpl; intros.\n    specialize (H oidx0).\n    mred; simpl.\n    rewrite H0; simpl; auto.\n  Qed.\n\n  Lemma MsiDownLockInv_no_update:\n    forall oss orqs pmsgs,\n      MsiDownLockInv {| st_oss := oss; st_orqs := orqs; st_msgs := pmsgs |} ->\n      forall oidx post porq nost norq nmsgs,\n        oss@[oidx] = Some post ->\n        nost#[owned] = post#[owned] ->\n        nost#[status] = post#[status] ->\n        nost#[dir] = post#[dir] ->\n        orqs@[oidx] = Some porq ->\n        norq@[downRq] = porq@[downRq] ->\n        MsiDownLockInv {| st_oss := oss +[oidx <- nost];\n                          st_orqs := orqs +[oidx <- norq];\n                          st_msgs := nmsgs |}.\n  Proof.\n    cbv [MsiDownLockInv liftObjInvs liftObjInv MsiDownLockObjInv]; simpl; intros.\n    mred; auto.\n    simpl; rewrite H1, H2, H3, H5.\n    specialize (H oidx).\n    rewrite H0, H4 in H; simpl in H.\n    assumption.\n  Qed.\n\n  Ltac solve_MsiDownLockInv oidx :=\n    try match goal with\n        | [Hdl: MsiDownLockInv _ |- _] =>\n          let noidx := fresh \"oidx\" in\n          do 2 red; simpl; intro noidx;\n          red; simpl;\n          repeat (mred; simpl); [|apply Hdl; fail]\n        end;\n    disc_MsiDownLockInv_internal oidx;\n    red; mred; simpl;\n    repeat\n      match goal with\n      | [H: _ <+- ?ov; _ |- _ <+- ?ov; _] =>\n        let Hov := fresh \"H\" in\n        let v := fresh \"v\" in\n        destruct ov as [v|] eqn:Hov; simpl in *; [|auto; fail]\n      | [H: msg_id ?rmsg = _ |- context [msg_id ?rmsg] ] =>\n        rewrite H; simpl\n      end;\n    repeat split;\n    repeat match goal with\n           | |- DownLockFromChild _ _ _ => red; simpl; eauto; fail\n           | |- context [map _ (map _ _)] => rewrite rqi_rss_map_map\n           | |- _ => repeat split; intuition solve_msi\n           end.\n\n  Lemma MsiDownLockInv_mutual_step:\n    Invariant.MutualInvStep2 impl step_m MsiUpLockInv MsiDownLockInv.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (msi_GoodORqsInit Htr)\n                  (msi_GoodRqRsSys Htr) H) as Hftinv.\n    inv H2; [assumption..|].\n\n    simpl in H3; destruct H3; [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)))).\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n      simpl in *.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H4; destruct H4 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 (eapply MsiDownLockInv_update_None; eauto; fail).\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst; simpl in *.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H3).\n      destruct H2 as [pidx [? ?]].\n      pose proof (Htn _ _ H5); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H4; destruct H4.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H4; destruct H4 as [crls [? ?]].\n        apply in_map_iff in H4; destruct H4 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 (eapply MsiDownLockInv_update_None; eauto; fail).\n        all: try (eapply MsiDownLockInv_no_update; eauto; mred; fail).\n        all: try (derive_child_chns cidx;\n                  derive_child_idx_in cidx;\n                  solve_MsiDownLockInv oidx).\n      }\n\n      dest_in; disc_rule_conds_ex.\n      all: try (eapply MsiDownLockInv_update_None; eauto; mred; fail).\n      all: try (eapply MsiDownLockInv_no_update; eauto;\n                unfold addRqS; mred; fail).\n      all: try (solve_MsiDownLockInv oidx; fail).\n      { disc_MsiUpLockInv_internal oidx.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        disc_rule_conds_ex.\n        solve_MsiDownLockInv oidx.\n      }\n\n    - (*! Cases for L1 caches *)\n\n      (** Do case analysis per a rule. *)\n      apply in_map_iff in H2; destruct H2 as [oidx [? ?]]; subst.\n      dest_in; disc_rule_conds_ex.\n      all: try (eapply MsiDownLockInv_update_None; eauto; mred; fail).\n      all: try (eapply MsiDownLockInv_no_update; eauto;\n                unfold addRqS; mred; fail).\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem MsiLockInv_ok:\n    InvReachable impl step_m (fun st => MsiUpLockInv st /\\ MsiDownLockInv st).\n  Proof.\n    eapply mutual_inv_reachable.\n    - typeclasses eauto.\n    - apply MsiUpLockInv_init.\n    - apply MsiDownLockInv_init.\n    - apply MsiUpLockInv_mutual_step.\n    - apply MsiDownLockInv_mutual_step.\n  Qed.\n\n  Corollary MsiObjInvs_ok:\n    InvReachable impl step_m (liftObjInvs (MsiObjInvs topo)).\n  Proof.\n    red; intros.\n    apply MsiLockInv_ok in H; dest.\n    red; intros.\n    specialize (H oidx); specialize (H0 oidx).\n    red; red in H, H0.\n    destruct (st_oss ist)@[oidx] as [ost|]; simpl in *; [|auto].\n    destruct (st_orqs ist)@[oidx] as [orq|]; simpl in *; [|auto].\n    split; assumption.\n  Qed.\n\n  Corollary MsiUpLockInv_ok:\n    InvReachable impl step_m MsiUpLockInv.\n  Proof.\n    red; intros.\n    apply MsiLockInv_ok; assumption.\n  Qed.\n\n  Corollary MsiDownLockInv_ok:\n    InvReachable impl step_m MsiDownLockInv.\n  Proof.\n    red; intros.\n    apply MsiLockInv_ok; assumption.\n  Qed.\n\nEnd ObjInvOk.\n\nLtac disc_MsiUpLockInv oidx :=\n  repeat\n    match goal with\n    | [Hdl: MsiUpLockInv _ |- _] =>\n      (specialize (Hdl oidx); do 2 red in Hdl; simpl in Hdl)\n    | [Hmv: ?m@[?i] = Some ?v, H: context [?m@[?i]] |- _] =>\n      rewrite Hmv in H; simpl in H\n    end;\n  disc_msi_obj_invs; dest.\n\nLtac disc_MsiDownLockInv oidx Hinv :=\n  specialize (Hinv oidx); do 2 red in Hinv; simpl in Hinv;\n  disc_rule_conds_ex; disc_msi_obj_invs; dest;\n  repeat\n    match goal with\n    | [Hrqi: rqi_msg _ = Some ?msg, Hmsg: msg_id ?msg = _ |- _] =>\n      rewrite Hmsg in Hinv; simpl in Hinv\n    | [H: DownLockFromChild _ _ _ /\\ _ |- _] => destruct H\n    | [H: DownLockFromParent _ _ /\\ _ |- _] => destruct H\n    | [Hdfc: DownLockFromChild _ _ _ |- _] =>\n      red in Hdfc; dest; disc_rule_conds_ex\n    | [Hdfp: DownLockFromParent _ _ |- _] =>\n      red in Hdfp; dest; disc_rule_conds_ex; solve_midx_false\n    end.\n\nSection RootChnInv.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma msi_RootChnInv_init:\n    Invariant.InvInit impl (RootChnInv tr 0).\n  Proof.\n    do 2 (red; simpl).\n    intros.\n    intro Hx; do 2 (red in Hx).\n    dest_in.\n  Qed.\n\n  Ltac disc_RootChnInv :=\n    intros;\n    let Hx := fresh \"H\" in\n    intro Hx;\n    repeat\n      match goal with\n      | [H: In _ (subtreeChildrenIndsOf _ _) |- _] =>\n        apply subtreeChildrenIndsOf_parentIdxOf in H; auto\n      | [Hm: InMPI (enqMsgs _ _) _ |- _] =>\n        apply InMP_enqMsgs_or in Hm; destruct Hm\n      | [Hinv: _ -> _ -> ~ InMPI _ _,  Hm: InMP _ _ (deqMsgs _ _) |- _] =>\n        apply InMP_deqMsgs in Hm; eapply Hinv; eauto\n      | [H: In (idOf ?idm, valOf ?idm) _ |- _] =>\n        let midx := fresh \"midx\" in\n        let msg := fresh \"msg\" in\n        destruct idm as [midx msg]; simpl in *\n      end;\n    disc_rule_conds_ex.\n\n  Ltac solve_RootChnInv :=\n    repeat\n      match goal with\n      | [H: In _ (remove _ _ (dir_sharers _)) |- _] => apply in_remove in H\n      | [H1: In _ ?l, H2: SubList ?l (subtreeChildrenIndsOf _ _) |- _] =>\n        apply H2 in H1\n      | [H: In _ (subtreeChildrenIndsOf _ _) |- _] =>\n        apply subtreeChildrenIndsOf_parentIdxOf in H; auto\n      | [H: In _ (map _ _) |- _] => apply in_map_iff in H; dest\n      | [H: (_, _) = (_, _) |- _] => inv H\n      | [H: _ \\/ _ \\/ _ |- _] => destruct H as [|[|]]; try discriminate\n      | [H: rqUpFrom _ = rqUpFrom _ |- _] => inv H\n      | [H: rsUpFrom _ = rsUpFrom _ |- _] => inv H\n      | [H: downTo _ = downTo _ |- _] => inv H\n\n      | [H: parentIdxOf _ ?oidx = Some ?oidx |- _] =>\n        exfalso; eapply parentIdxOf_not_eq in H; eauto\n      | [H1: ?oidx = rootOf _, H2: parentIdxOf _ ?oidx = Some _ |- _] => rewrite H1 in H2\n      | [H: parentIdxOf _ (rootOf _) = Some ?idx |- _] =>\n        eapply parentIdxOf_child_not_root with (pidx:= idx); eauto\n      | [H: In (rootOf _) (tl (c_li_indices _)) |- _] =>\n        exfalso; eapply tree2Topo_root_not_in_tl_li; eauto\n      | [H: In (rootOf _) (c_l1_indices _) |- _] =>\n        exfalso; eapply tree2Topo_root_not_in_l1; eauto\n      | [H1: In ?oidx (c_l1_indices _), H2: l1ExtOf ?oidx = rootOf _ |- _] =>\n        eapply tree2Topo_root_not_l1ExtOf; eauto\n      end.\n\n  Lemma msi_RootChnInv_step:\n    Invariant.InvStep impl step_m (RootChnInv tr 0).\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n    pose proof (footprints_ok\n                  (msi_GoodORqsInit Htr)\n                  (msi_GoodRqRsSys Htr) H) as Hftinv.\n    pose proof (MsiDownLockInv_ok H) as Hmftinv.\n    inv H1; [assumption|..].\n\n    1: {\n      red; simpl; intros.\n      intro Hx; apply InMP_enqMsgs_or in Hx.\n      destruct Hx; [|eapply H0; eauto].\n      apply in_map with (f:= idOf) in H4; simpl in H4.\n      apply H3 in H4; simpl in H4.\n      eapply DisjList_In_1.\n      + apply tree2Topo_minds_merqs_disj.\n      + eassumption.\n      + eapply tree2Topo_obj_chns_minds_SubList.\n        * rewrite c_li_indices_head_rootOf by assumption.\n          left; reflexivity.\n        * destruct H1 as [|[|]]; rewrite H1; simpl; tauto.\n    }\n\n    1: {\n      red; simpl; intros.\n      intro Hx; apply InMP_deqMsgs in Hx.\n      eapply H0; eauto.\n    }\n\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n\n      (** Abstract the root. *)\n      unfold RootChnInv in *; simpl in *.\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H3; destruct H3 as [crls [? ?]].\n      apply in_map_iff in H1; destruct H1 as [cidx [? ?]]; subst.\n      dest_in; try (disc_RootChnInv; solve_RootChnInv; fail).\n\n    - (*! Cases for Li caches *)\n      unfold RootChnInv in *; simpl in *.\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H3; destruct H3.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H3; destruct H3 as [crls [? ?]].\n        apply in_map_iff in H3; destruct H3 as [cidx [? ?]]; subst.\n        dest_in; try (disc_RootChnInv; solve_RootChnInv; fail).\n      }\n\n      dest_in.\n      all: try (disc_RootChnInv; solve_RootChnInv; fail).\n      all: try (disc_RootChnInv;\n                derive_footprint_info_basis oidx;\n                derive_child_chns cidx;\n                disc_rule_conds_ex;\n                solve_RootChnInv;\n                fail).\n      all: try (disc_RootChnInv;\n                derive_footprint_info_basis oidx;\n                [|disc_MsiDownLockInv oidx Hmftinv];\n                derive_child_chns upCIdx;\n                disc_rule_conds_ex;\n                solve_RootChnInv;\n                fail).\n      all: try (disc_RootChnInv;\n                derive_footprint_info_basis oidx;\n                [disc_MsiDownLockInv oidx Hmftinv|];\n                disc_rule_conds_ex;\n                solve_RootChnInv).\n\n    - (*! Cases for L1 caches *)\n      unfold RootChnInv in *; simpl in *.\n\n      (** Do case analysis per a rule. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n      dest_in.\n      all: try (disc_RootChnInv; solve_RootChnInv; fail).\n      all: try (disc_RootChnInv;\n                derive_footprint_info_basis oidx;\n                derive_child_chns cidx;\n                disc_rule_conds_ex;\n                solve_RootChnInv).\n\n      Unshelve.\n      all: assumption.\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem msi_RootChnInv_ok:\n    InvReachable impl step_m (RootChnInv tr 0).\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply msi_RootChnInv_init.\n    - apply msi_RootChnInv_step.\n  Qed.\n\nEnd RootChnInv.\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/Msi/MsiInvB.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.18099979165005065}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Coqlib.\nFrom compcert Require Import\n     AST Memory Globalenvs Maps Values Linking\n     Ctypes Clight Clightdefs.\n\nRequire Import ZArith String Bool List Lia.\n\nRequire Import sflib.\nRequire Import StdlibExt IntegersExt.\nRequire Import DiscreteTimeModel IPModel.\n\nRequire Import SysSem.\nRequire Import NWSysModel.\nRequire Import OSModel OSNodes.\nRequire Import RTSysEnv.\nRequire Import CProgEventSem.\nRequire Import SyncSysModel.\nRequire Import ProgSem.\nRequire Import LinkLemmas.\nRequire Import MWITree.\n\nRequire Import config_prm main_prm SystemProgs.\nRequire Import VerifProgBase.\nRequire Import MWLinkInversion.\nRequire Import PALSSystem.\n\nRequire Import dev.\nRequire Import AcStSystem.\n(* Require Import LinkDevice. *)\n\nLocal Opaque Z.to_nat Z.of_nat PTree.combine.\n\nImport ITreeNotations.\nImport ListNotations.\n\n(* Import ActiveStandby. *)\n\nSet Nested Proofs Allowed.\n\nLocal Open Scope Z.\n\n\nDefinition MAX_TIMEOUT: nat := 5.\n\n\nModule DevState.\n\n  Record t: Type :=\n    mk { owner_status: bool? ;\n         demand: nat ;\n       }.\n\n  Inductive wf: t -> Prop :=\n    Wf own dmd\n       (RANGE_TOUT: (dmd <= MAX_TIMEOUT)%nat)\n    : wf (mk own dmd).\n\n  Definition init: t :=\n    mk None O.\n\n  Lemma wf_init: wf init.\n  Proof.\n    econs; ss. nia.\n  Qed.\n\n  Definition set_owner_status (own: bool) (st: t): t :=\n    let 'mk _ dmd := st in\n    mk (Some own) dmd.\n\n  Lemma wf_set_owner_status own st\n        (WF: wf st)\n    : wf (set_owner_status own st).\n  Proof.\n    inv WF. econs; ss.\n  Qed.\n\n  Definition set_demand (dmd: nat) (st: t): t :=\n    let 'mk own _ := st in\n    mk own dmd.\n\n  Lemma wf_set_demand\n        dmd st\n        (VALID_DMD: (dmd <= MAX_TIMEOUT)%nat)\n    : wf (set_demand dmd st).\n  Proof.\n    destruct st.\n    econs; ss.\n  Qed.\n\n  Definition reduce_demand (st: t): t :=\n    let 'mk own dmd := st in\n    mk own (pred dmd).\n\n  Lemma wf_reduce_demand\n        st (WF_ST: wf st)\n    : wf (reduce_demand st).\n  Proof.\n    inv WF_ST.\n    econs; ss.\n    nia.\n  Qed.\n\n\n  (* Definition of_bytes (msg: bytes): t := *)\n  (*   let md_msg := Byte.signed (nth 0 msg Byte.zero) in *)\n  (*   let tout_msg := Byte.signed (nth 1 msg Byte.zero) in *)\n  (*   let qb_msg := Byte.signed (nth 2 msg Byte.zero) in *)\n  (*   let qe_msg := Byte.signed (nth 3 msg Byte.zero) in *)\n  (*   let q1_msg := Byte.signed (nth 4 msg Byte.zero) in *)\n  (*   let q2_msg := Byte.signed (nth 5 msg Byte.zero) in *)\n  (*   let q3_msg := Byte.signed (nth 6 msg Byte.zero) in *)\n  (*   let q4_msg := Byte.signed (nth 7 msg Byte.zero) in *)\n  (*   mk (mode_of_Z md_msg) tout_msg qb_msg qe_msg *)\n  (*      [q1_msg; q2_msg; q3_msg; q4_msg]. *)\n\n  (* Lemma wf_of_bytes msg: wf (of_bytes msg). *)\n  (* Proof. *)\n  (*   econs. *)\n  (*   - apply Byte.signed_range. *)\n  (*   - apply Byte.signed_range. *)\n  (*   - apply Byte.signed_range. *)\n  (*   - econs; [ apply Byte.signed_range |]. *)\n  (*     econs; [ apply Byte.signed_range |]. *)\n  (*     econs; [ apply Byte.signed_range |]. *)\n  (*     econs; [ apply Byte.signed_range |]. *)\n  (*     econs. *)\n  (*   - ss. *)\n  (* Qed. *)\n\n  Definition owner_status_to_Z (own: bool?): Z :=\n    match own with\n    | None => 0\n    | Some b => if b then 1 else 2\n    end.\n\n  Definition to_bytes (st: t): bytes :=\n    [ Byte.repr (owner_status_to_Z (owner_status st)) ;\n    Byte.repr (Z.of_nat (demand st))].\n\nEnd DevState.\n\n\nImport DevState.\n\nDefinition check_grant (inb: list bytes?): bool :=\n  match nth 1%nat inb None, nth 2%nat inb None with\n  | None, None => false\n  | _, _ => true\n  end.\n\nDefinition sync_dev_state (inb: list bytes?) (st: t): t :=\n  match nth 1%nat inb None, nth 2%nat inb None with\n  | None, None => st\n  | _, _ => set_owner_status true st\n  end.\n\nLemma wf_sync_dev_state\n      inb st\n      (WF_ST: wf st)\n  : wf (sync_dev_state inb st).\nProof.\n  inv WF_ST.\n  unfold sync_dev_state. ss.\n  desf.\nQed.\n\nDefinition get_new_demand: itree appE nat :=\n  d_raw_i <- trigger CheckDemand ;;\n  let d_raw := Z.to_nat (Int.signed d_raw_i) in\n  Ret (if (MAX_TIMEOUT <? d_raw)%nat then MAX_TIMEOUT else d_raw).\n\nDefinition update_demand (st: t): itree appE (t * bool) :=\n  if (demand st =? O)%nat then\n    d <- get_new_demand ;;\n    Ret (if (0 <? d)%nat then\n           (set_demand d st, true)\n         else (st, false))\n  else Ret (st, false).\n\nDefinition run_device (st: t): itree appE t :=\n  if (0 <? demand st)%nat then\n    trigger UseResource ;;\n    Ret (reduce_demand st)\n  else Ret st.\n\nDefinition job_device_itree (sytm: Z) (st: t) (inb: list bytes?)\n  : itree appE t :=\n  match owner_status st with\n  | None =>\n    trigger (AbstSendEvent mid_mcast rel_msg) ;;\n    trigger (WriteLog 0);;\n    Ret (set_owner_status false st)\n  | Some is_owner =>\n    let st_sync := sync_dev_state inb st in\n    '(st_ud, is_dupd) <- update_demand st_sync ;;\n    match owner_status st_ud with\n    | None => Ret st_ud (* unreachable *)\n    | Some is_owner_ud =>\n      if is_owner_ud then\n        st1 <- run_device st_ud ;;\n        if (demand st1 =? O)%nat then\n          trigger (AbstSendEvent mid_mcast rel_msg) ;;\n          trigger (WriteLog 0);;\n          Ret (set_owner_status false st1)\n        else\n          trigger (WriteLog 0);;\n          Ret st1\n      else\n        (if (is_dupd: bool) then\n           trigger (AbstSendEvent mid_mcast acq_msg)\n         else Ret tt) ;;\n        trigger (WriteLog 0);;\n        Ret st_ud\n    end\n  end.\n\n\nDefinition dev_job\n           (sytm: Z) (inb: list bytes?) (st: DevState.t)\n  : itree (obsE +' bsendE) DevState.t :=\n  job_device_itree sytm st inb.\n\nDefinition dev_mod: @AppMod.t obsE bytes :=\n  {| AppMod.abst_state_t := DevState.t ;\n     AppMod.job_itree := dev_job ;\n     AppMod.init_abst_state := DevState.init |}.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/apps/active_standby/app_verif/SpecDevice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.1809045414559467}}
{"text": "From iris.base_logic.lib Require Export fancy_updates wsat.\nFrom iris.proofmode Require Import base tactics classes.\nFrom mwp Require Import mwp mwp_adequacy mwp_lifting.\nFrom mwp.mwp_modalities Require Import mwp_indexed_step_fupd.\nFrom iris.program_logic Require Export ectxi_language ectx_language language.\n\nSection mwp_mwp_ISF.\n  Context {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n  Typeclasses Transparent mwpC_state_interp mwpC_modality.\n\n  Definition mwpd_mwp_ISF : mwpData \u039b \u03a3 :=\n    {| mwpD_state_interp := mwpD_SI;\n       mwpD_Extra := [Prod val \u039b; nat];\n       mwpD_modality_index := [Prod expr \u039b];\n       mwpD_modality_bind_condition e1 e2 f g :=\n         \u2203 K (_: LanguageCtx K),\n           e1 = K e2 \u2227 g = (\u03bb x y, (y.1, x.2 + y.2)) \u2227\n           \u2200 v k, f (v, k) = K (of_val v);\n      mwpD_modality idx E n \u03a6 :=\n        MWP@{mwpd_indexed_step_fupd mwpD_SI', n }\n          idx @ E {{ w; k, \u03a6 (w, k) }}%I;\n    |}.\n\n  Global Instance mwpC_mwp_ISF : mwpC mwpd_mwp_ISF.\n  Proof.\n    split.\n    - intros idx E m n ? ? ?; simpl. apply mwp_ne.\n      intros ? ? ?; auto.\n    - intros idx E1 E2 n \u03a6 \u03a8 HE; simpl.\n      iIntros \"HP Hic\".\n      iApply (mwp_strong_mono_wand _ _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      by iIntros (? ? ?) \"?\"; iApply \"HP\".\n    - iIntros (idx E n \u03a6) \"H\";simpl.\n      iApply mwp_indexed_step_fupd_index_intro; last eauto. simpl; lia.\n    - intros e e' f g E n m \u03a6 (K & HK & He & Hg & Hf); simplify_eq.\n      iIntros \"H\"; simpl.\n      iApply mwp_indexed_step_fupd_bind; simpl.\n      iApply (mwp_strong_mono_wand _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      iIntros (v l _); rewrite Hf /=.\n      iIntros \"H\".\n      iApply (mwp_strong_mono_wand _ _ _ _ _ _ (\u03bb v m _, _)); eauto; iFrame.\n      by iIntros (? j _) \"?\".\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_outer_fupd idx :\n    mwpMIsOuterModal mwpd_mwp_ISF idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_outer_bupd idx :\n    mwpMIsOuterModal mwpd_mwp_ISF idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_outer_except_0 idx :\n    mwpMIsOuterModal mwpd_mwp_ISF idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsOuterModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\". by iMod \"H\".\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_inner_fupd idx :\n    mwpMIsInnerModal mwpd_mwp_ISF idx (\u03bb E _ P, |={E}=> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_fupd _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_inner_bupd idx :\n    mwpMIsInnerModal mwpd_mwp_ISF idx (\u03bb _ _ P, |==> P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_bupd _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_is_inner_except_0 idx :\n    mwpMIsInnerModal mwpd_mwp_ISF idx (\u03bb _ _ P, \u25c7 P)%I.\n  Proof.\n    rewrite /mwpMIsInnerModal /mwpC_modality /mwpD_modality /=.\n    iIntros (E n P) \"H\".\n    by iApply (mwp_except_0 _ _ _ _ (\u03bb v m _, _)).\n  Qed.\n\n  Global Instance mwpC_mwp_ISF_SupportsAtomicShift idx :\n    mwpMSupportsAtomicShift mwpd_mwp_ISF idx.\n  Proof.\n    rewrite /mwpMSupportsAtomicShift /mwpC_modality /mwpD_modality /=.\n    iIntros (n E1 E2 \u03a6 Hn) \"H\".\n    iApply (mwp_shift (mwpd_indexed_step_fupd mwpD_SI'));\n      eauto using mwp_indexed_step_fupd_AlwaysSupportsShift.\n  Qed.\n\n  Global Program Instance mwpC_mwp_ISF_SplitForStep idx :\n    mwpMSplitForStep mwpd_mwp_ISF idx :=\n    {|\n      mwpM_split_for_step_M1 E P := |={E, \u2205}=> \u25b7 P;\n      mwpM_split_for_step_M2 E P := |={\u2205, E}=> P;\n    |}%I.\n  Next Obligation.\n  Proof.\n    iIntros (e n E P) \"HP /=\".\n    rewrite /mwpC_modality /mwpD_modality /=.\n    by iApply (mwp_indexed_step_fupd_index_step_fupd _ _ 1).\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    by iMod \"HP\"; iModIntro; iApply \"HPQ\".\n  Qed.\n  Next Obligation.\n  Proof.\n    iIntros (idx E P Q) \"HPQ HP /=\".\n    iMod \"HP\"; iModIntro. by iApply \"HPQ\".\n  Qed.\n\n  Lemma mwp_mwp_ISF_strong_bind\n        K `{!LanguageCtx K} K' `{!LanguageCtx K'} E e e' \u03a6 :\n    MWP@{mwpd_mwp_ISF, e'} e @ E {{ v; m | w ; k,\n      MWP@{mwpd_mwp_ISF, K' (of_val w)}\n        K (of_val v) @ E {{ w; n | u ; y, \u03a6 w (m + n) (u, (k + y)) }} }}\n    \u22a2 MWP@{mwpd_mwp_ISF, K' e'} K e @ E {{ \u03a6 }}.\n  Proof.\n    iIntros \"H\".\n    iApply (@mwp_bind _ _ _ mwpC_mwp_ISF K _ _ e'\n                     (\u03bb '(v, k), K' (of_val v))\n                     (\u03bb x y, (y.1, x.2 + y.2))).\n    { rewrite /mwpC_modality_bind_condition /=; eauto. }\n    iApply mwp_mono; last eauto.\n    intros ? ? []; auto.\n  Qed.\n\nLemma mwp_mwp_ISF_change_of_index e1' e2' f E e \u03a6 :\n  (\u2200 \u03a8 n,\n      MWP@{mwpd_indexed_step_fupd mwpD_SI', n}\n        e1' @ E {{ v; n | [_], \u03a8 (f (v, n)) }} -\u2217\n        MWP@{mwpd_indexed_step_fupd mwpD_SI', n}\n        e2' @ E {{ v; n | [_], \u03a8 (v, n) }})\n  -\u2217 MWP@{mwpd_mwp_ISF, e1'} e @ E {{ \u03bb v n x, \u03a6 v n (f x) }}\n  -\u2217 MWP@{mwpd_mwp_ISF, e2'} e @ E {{ \u03a6 }}.\nProof.\n  iIntros \"Hm H\".\n  iApply (mwp_change_of_index mwpd_mwp_ISF with \"[Hm] H\").\n  iIntros (\u03a8 n) \"H\".\n  by iApply \"Hm\".\nQed.\n\nEnd mwp_mwp_ISF.\n\nSection lifting.\n\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI': state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_fupd_lift_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n    (\u2200 \u03c31, mwpD_SI \u03c31 -\u2217\n      |={E, \u2205}=>\n     \u25b7 \u2200 e2 \u03c32,\n         \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n            (mwpD_SI \u03c32 \u2217 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n                    e2 @ E {{ v; n| [x], \u03a6 v (S n) x }}))\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (?) \"?\".\n  iApply (mwp_lift_step (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E); simpl; auto.\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2 \u03c32, prim_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n      \u231cprim_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e2 @ E\n        {{ v; n | [x], \u03a6 v (S n) x }})\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_step\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_mwp_ISF_lift_atomic_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 \u2200 v2 \u03c32,\n            \u231cprim_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d\n             ={\u2205, E}=\u2217 (mwpD_SI \u03c32 \u2217\n                        MWP@{mwpd_indexed_step_fupd mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (??).\n  by iApply (mwp_lift_atomic_step\n               (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E).\nQed.\n\nLemma mwp_mwp_ISF_lift_atomic_det_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  Atomic StronglyAtomic e1 \u2192\n  (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     \u25b7 (\u2203 v2 \u03c32,\n         \u231c\u2200 e2' \u03c32', prim_step e1 \u03c31 [] e2' \u03c32' [] \u2192\n                     \u03c32 = \u03c32' \u2227 to_val e2' = Some v2\u231d \u2227\n                     |={\u2205, E}=> mwpD_SI \u03c32 \u2217\n                          MWP@{mwpd_indexed_step_fupd mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by iIntros (??);\n    iApply (mwp_lift_atomic_det_step\n              (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_det_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 \u03c31 e2' \u03c32, prim_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  \u25b7 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(??) \"H\".\n  iApply (mwp_lift_pure_det_step\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_mwp_ISF_pure_step `{!Inhabited (state \u039b)} idx E e1 e2 \u03c6 n \u03a6 :\n  PureExec \u03c6 n e1 e2 \u2192\n  \u03c6 \u2192\n  \u25b7^n MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v ; m | [x], \u03a6 v (n + m) x }}\n  \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (Hexec H\u03c6) \"Hic\".\n  iApply (mwp_pure_step (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx); eauto.\n  clear Hexec.\n  iInduction n as [] \"IH\" forall (\u03a6); simpl; auto.\n  iApply step_fupd_intro; first set_solver.\n  iApply (\"IH\" $! (\u03bb w k, \u03a6 w (S k)) with \"Hic\").\nQed.\n\nEnd lifting.\n\nSection mwp_ectx_lifting.\n\nContext {\u039b : ectxLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\nImplicit Types v : val \u039b.\nImplicit Types e : expr \u039b.\nImplicit Types \u03c3 : state \u039b.\nImplicit Types P Q : iProp \u03a3.\nImplicit Types \u03a6 : val \u039b \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_mwp_ISF_lift_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 \u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n                          e2 @ E {{ w; n | [x], \u03a6 w (S n) x }}))\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by intros;\n    iApply (mwp_lift_head_step\n              (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n      \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n      MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n        e2 @ E {{ w; n| [x], \u03a6 w (S n) x }})\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_head_step\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_mwp_ISF_lift_atomic_head_step idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n     \u25b7 \u2200 v2 \u03c32,\n       \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n          (mwpD_SI \u03c32 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }}))\n     \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by intros;\n    iApply (mwp_lift_atomic_head_step\n              (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_det_head_step idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  sub_redexes_are_values e1 \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2')\u2192\n  \u25b7 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros(???) \"H\".\n  iApply (mwp_lift_pure_det_head_step\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1);\n    simpl; eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nEnd mwp_ectx_lifting.\n\nSection mwp_ectxi_lifting.\n\nContext {\u039b : ectxiLanguage}.\nContext {\u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : (val \u039b) \u2192 nat \u2192 val \u039b * nat \u2192 iProp \u03a3.\nImplicit Types v : (val \u039b).\nImplicit Types e : (expr \u039b).\n\nTypeclasses Transparent mwpC_state_interp mwpD_state_interp mwpC_modality.\n\nLemma mwp_mwp_ISF_lift_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n        \u25b7 (\u2200 e2 \u03c32,\n            \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d ={\u2205, E}=\u2217\n             (mwpD_SI \u03c32 \u2217 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n                            e2 @ E {{ w; n | [x], \u03a6 w (S n) x }})))\n     \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  by iIntros (??);\n    iApply (mwp_lift_head_step'\n              (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_head_step' idx E \u03a6 e1 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2 \u03c32, head_step e1 \u03c31 [] e2 \u03c32 [] \u2192 \u03c31 = \u03c32) \u2192\n  \u25b7 (\u2200 \u03c31 e2 \u03c32,\n       \u231chead_step e1 \u03c31 [] e2 \u03c32 []\u231d \u2192\n       MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n         e2 @ E {{ w; n | [x], \u03a6 w (S n) x }})\n     \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_head_step'\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1); eauto.\n   by iApply step_fupd_intro; first set_solver.\nQed.\n\nLemma mwp_mwp_ISF_lift_atomic_head_step' idx E \u03a6 e1:\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  Atomic StronglyAtomic e1 \u2192\n   (\u2200 \u03c31, mwpD_SI \u03c31 ={E, \u2205}=\u2217\n      \u25b7 (\u2200 v2 \u03c32,\n          \u231chead_step e1 \u03c31 [] (of_val v2) \u03c32 []\u231d ={\u2205, E}=\u2217\n           (mwpD_SI \u03c32 \u2217 MWP@{mwpd_indexed_step_fupd mwpD_SI', 0}\n                          idx @ E {{ v; n, \u03a6 v2 1 (v, n) }})))\n    \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???).\n  by iApply (mwp_lift_atomic_head_step'\n               (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1).\nQed.\n\nLemma mwp_mwp_ISF_lift_pure_det_head_step' idx E \u03a6 e1 e2 :\n  to_val e1 = None \u2192\n  (\u2200 Ki e', e1 = fill_item Ki e' \u2192 is_Some (to_val e')) \u2192\n  (\u2200 \u03c31 e2' \u03c32, head_step e1 \u03c31 [] e2' \u03c32 [] \u2192 \u03c31 = \u03c32 \u2227 e2 = e2') \u2192\n  \u25b7 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx}\n    e2 @ E {{ v; n | [x], \u03a6 v (S n) x }}\n  \u22a2 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e1 @ E {{ \u03a6 }}.\nProof.\n  iIntros (???) \"?\".\n  iApply (mwp_lift_pure_det_head_step'\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E \u03a6 e1); eauto.\n  by iApply step_fupd_intro; first set_solver.\nQed.\n\nEnd mwp_ectxi_lifting.\n\nSection basmwp_soundness.\nContext {\u039b \u03a3} `{!invG \u03a3} (mwpD_SI mwpD_SI' : state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nLemma mwp_mwp_ISF_adequacy_basic idx E e \u03c3 \u03a6 :\n  mwpD_SI \u03c3 \u2217 MWP@{mwpd_mwp_ISF mwpD_SI mwpD_SI', idx} e @ E {{ \u03bb v n x, \u03a6 v n x.1 x.2 }} -\u2217\n    \u2200 (rd : Reds e \u03c3),\n      MWP@{mwpd_indexed_step_fupd mwpD_SI', nstps rd}\n                          idx @ E {{ v; n, mwpD_SI (end_state rd) \u2217\n                                          \u03a6 (end_val rd) (nstps rd) v n }}.\nProof.\n  iApply (mwp_adequacy_basic\n            (mwpd_mwp_ISF mwpD_SI mwpD_SI') idx E e \u03c3 (\u03bb v n x, \u03a6 v n x.1 x.2)).\nQed.\n\nEnd basmwp_soundness.\n\nSection soundness.\n  Context {\u039b \u03a3} `{!invPreG \u03a3}\n          {SI_data : Type} (mwpD_SI : SI_data \u2192 state \u039b \u2192 iProp \u03a3)\n          {SI_data' : Type} (mwpD_SI' : SI_data' \u2192 state \u039b \u2192 iProp \u03a3).\n\nTypeclasses Transparent mwpC_state_interp mwpC_modality.\n\nProgram Instance mwp_ISF_Initialization\n        SSI SSI' `{!InitData SSI} `{!InitData SSI'} e' \u03c3' :\n  Initialization\n    (val \u039b * nat)\n    (\u03bb x : invG_pack \u03a3 (SI_data * SI_data'),\n           mwpd_mwp_ISF (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2))\n    (\u03bb x, @mwpC_mwp_ISF \u039b \u03a3 _ (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2))\n    (\u03bb _, e') :=\n{|\n  initialization_modality Hi P := |={\u22a4}=> P;\n  initialization_seed_for_modality _ := wsat \u2217 ownE \u22a4;\n  initialization_seed_for_state_interp x := SSI (PIG_cnt x).1 \u2217 SSI' (PIG_cnt x).2;\n  initialization_residue _ := \u25b7 wsat \u2217 \u25b7 ownE \u22a4;\n  initialization_elim_laters := 1;\n  initialization_mwpCM_soundness_arg := Reds e' \u03c3';\n  initialization_mwpCM_soundness_laters n _ := S (S n);\n  initialization_modality_initializer x _ := mwpD_SI' (PIG_cnt x).2 \u03c3';\n  initialization_mwpCM_soundness_fun rd := (end_val rd, nstps rd);\n  initialization_Ex_conv _ x := x;\n|}%I.\nNext Obligation.\nProof.\n  intros; simpl.\n  iApply init_data.\n  apply (init_invGpack (\u03bb x, SSI x.1 \u2217 SSI' x.2))%I.\nQed.\nNext Obligation.\nProof.\n  iIntros (???? e' \u03c3' P Hi) \"[Hs HE] HP\".\n  rewrite uPred_fupd_eq /uPred_fupd_def.\n  iMod (\"HP\" with \"[$]\") as \"(Hs & HE & HP)\".\n  iModIntro. rewrite -!bi.later_sep.\n  iMod \"Hs\"; iMod \"HE\"; iMod \"HP\". iNext.\n  iFrame.\nQed.\nNext Obligation.\nProof.\n  simpl.\n  iIntros (???? e' \u03c3' Hi P E n rd) \"[[Hs HE] [H\u03c3' HP]]\".\n  iNext.\n  rewrite /mwpC_modality /mwpD_modality /=.\n  iDestruct (mwp_indexed_step_fupd_adequacy_basic with \"[H\u03c3' $HP]\")\n    as \"HP\"; eauto.\n  iSpecialize (\"HP\" $! rd).\n  rewrite uPred_fupd_eq /uPred_fupd_def /=.\n  replace \u22a4 with ((\u22a4 \u2216 E) \u222a E) by by rewrite difference_union_L; set_solver.\n  iDestruct (ownE_op with \"HE\") as \"[_ HE]\"; first set_solver.\n  iInduction n as [] \"IH\".\n  { iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & ? & HP)\".\n    by iMod \"HP\". }\n  simpl.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iNext.\n  iMod (\"HP\" with \"[$Hs $HE]\") as \"(Hs & HE & HP)\".\n  iMod \"HP\"; iMod \"Hs\"; iMod \"HE\".\n  iApply (\"IH\" with \"Hs HP HE\").\nQed.\n\nLemma mwp_mwp_ISF_adequacy\n      SSI SSI' `{!InitData SSI} `{!InitData SSI'}\n      E e \u03c3 (e' : expr \u039b) \u03c3' (\u03a8 : val \u039b \u2192 nat \u2192 val \u039b \u2192 nat \u2192 Prop) :\n  (\u2200 (x : invG_pack \u03a3 (SI_data * SI_data')),\n       SSI (PIG_cnt x).1 \u2217 SSI' (PIG_cnt x).2 \u22a2\n       |={\u22a4}=> (mwpD_SI (PIG_cnt x).1 \u03c3 \u2217 mwpD_SI' (PIG_cnt x).2 \u03c3' \u2217\n              MWP@{mwpd_mwp_ISF (mwpD_SI (PIG_cnt x).1) (mwpD_SI' (PIG_cnt x).2), e'}\n              e @ E {{ v ; n| w; k,  \u231c\u03a8 v n w k\u231d }}))\n  \u2192 \u2200 (rd : Reds e \u03c3) (rd' : Reds e' \u03c3'),\n    \u03a8 (end_val rd) (@nstps \u039b _ _ rd) (end_val rd') (@nstps \u039b _ _ rd').\nProof.\n  intros Hic rd rd'.\n  by apply (mwp_adequacy\n              _ _ _ _ (mwp_ISF_Initialization SSI SSI' e' \u03c3') E e \u03c3\n              (\u03bb v n x, \u03a8 v n x.1 x.2) rd').\nQed.\n\nEnd soundness.\n", "meta": {"author": "logsem", "repo": "modal-weakestpre", "sha": "9d9034f868a94e195a8a22f53af06a14e1529f3f", "save_path": "github-repos/coq/logsem-modal-weakestpre", "path": "github-repos/coq/logsem-modal-weakestpre/modal-weakestpre-9d9034f868a94e195a8a22f53af06a14e1529f3f/theories/mwp_modalities/mwp_mwp_ISF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.29746994260479476, "lm_q1q2_score": 0.18076152825323794}}
{"text": "From aneris.aneris_lang.lib Require Export\n     assert_proof\n     network_util_proof set_proof map_proof nodup_proof coin_flip_proof inject.\nFrom aneris.examples.transaction_commit Require Import two_phase_prelude.\n\nSection transaction_manager.\n  Context `{!network_topo}.\n  Context `{!anerisG (TC_model RMs) \u03a3, !tcG \u03a3}.\n\n  Lemma wp_transaction_manager_recv_responses R T h l rcv vRMs :\n    is_set RMs vRMs \u2192\n    {{{ pending \u2217\n        is_rcvset_log l R tm \u2217\n        wp_nodup_rcv rcv tm (mkSocket (Some tm) true) l \u2217\n        tm \u2933 (R, T) \u2217\n        h \u21aa[ip_of_address tm] mkSocket (Some tm) true \u2217\n        tm \u2907 tm_si }}}\n      recv_responses rcv #(LitSocket h) vRMs @[ip_of_address tm]\n    {{{ (b : bool) R', RET #b;\n          pending \u2217 tm \u2933 (R', T) \u2217 h \u21aa[ip_of_address tm] mkSocket (Some tm) true \u2217\n          is_rcvset_log l R' tm \u2217\n          if b then [\u2217 set] rm \u2208 RMs, rm \u21a6\u25ef PREPARED \u2217 pending\n          else \u2203 rm, \u231crm \u2208 RMs\u231d \u2217 rm \u21a6\u25ef ABORTED \u2217 pending_discarded }}}.\n  Proof.\n    iIntros (HRMs \u03a6) \"(Hpend & Hl & #Hrcv & Htm & Hh & #Hsi) H\u03a6\". rewrite /recv_responses.\n    do 8 wp_pure _.\n    wp_apply (wp_set_empty socket_address); [done|]; iIntros (v Hv).\n    iAssert (\u2203 prepared, \u231cis_set prepared v\u231d \u2217\n             [\u2217 set] rm \u2208 prepared, rm \u21a6\u25ef (PREPARED : rm_stateO) \u2217 pending)%I as \"-#Hloop\".\n    { iExists _. eauto. }\n    clear Hv.\n    iL\u00f6b as \"IH\" forall (v R) \"Hloop\".\n    iDestruct \"Hloop\" as (X) \"[%HX Hprepared]\".\n    wp_pures.\n    wp_apply wp_set_equal; [done|].\n    iIntros ([] ?); simplify_eq.\n    { wp_pures. iApply \"H\u03a6\".  iFrame. }\n    wp_pures.\n    wp_apply (\"Hrcv\" with \"[$Hh $Htm $Hl $Hsi]\").\n    iIntros (m) \"(Hh & Htm & Hm & Hl & % & %)\".\n    wp_pures.\n    case_bool_decide.\n    - wp_pures. wp_apply (wp_set_add $! HX).\n      iIntros (X' HX').\n      wp_apply (\"IH\" with \"Hpend Hl Htm Hh H\u03a6\").\n      rewrite /tm_si.\n      iDestruct \"Hm\" as \"[% [(_ & Hal & Hpend) | [[% ?] | [% ?]]]]\"; [|congruence..].\n      iExists _. iFrame (HX').\n      destruct (decide (m_sender m \u2208 X)).\n      { by assert ({[m_sender m]} \u222a X = X) as -> by set_solver. }\n      iApply big_sepS_union; [set_solver|].\n      rewrite big_sepS_singleton. iFrame.\n    - wp_pures. iApply \"H\u03a6\".\n      iDestruct \"Hm\" as \"[% [(% & Hal & Hpend') | [(% & ? & Hshot) | (% & ? & Hdisc)]]]\";\n        [congruence| |].\n      { iDestruct (pending_shot with \"Hpend Hshot\") as %[]. }\n      iFrame. eauto.\n  Qed.\n\n  (** * Transaction manager spec *)\n  Lemma transaction_manager_spec vRMs :\n    is_set RMs vRMs \u2192\n    free_ports (ip_of_address tm) {[port_of_address tm]} -\u2217\n    ([\u2217 set] rm \u2208 RMs, rm \u2907 rm_si) -\u2217\n    tm \u2907 tm_si -\u2217\n    tm \u2933 (\u2205, \u2205) -\u2217\n    pending -\u2217\n    WP transaction_manager #tm vRMs @[ip_of_address tm]\n    {{ v, (\u231cv = #(\"COMMITTED\")\u231d \u2217 [\u2217 set] rm \u2208 RMs,  rm \u21a6\u25ef COMMITTED) \u2228\n          (\u231cv = #(\"ABORTED\")\u231d   \u2217 \u2203 rm, \u231crm \u2208 RMs\u231d \u2217 rm \u21a6\u25ef ABORTED) }}.\n  Proof.\n    iIntros (HRMs) \"Hp #Hrmsis #Htm_si Htm Hpend\".\n    rewrite /transaction_manager.\n    wp_pures. wp_socket h as \"Hh\". wp_pures. wp_socketbind.\n    wp_apply (wp_nodup_init _ (mkSocket _ _)); [done..|].\n    iIntros (l rcv) \"[Hlog #Hrcv]\". wp_let.\n    (* sending \"PREPARE\" to all *)\n    wp_apply (wp_sendto_all_set (\u03bb _, rm_si) with \"[$Hh $Htm]\"); auto.\n    { iFrame \"%\".\n      iApply (big_sepS_impl with \"Hrmsis\").\n      iIntros \"!#\" (??) \"Hsi\".\n      iFrame. by iLeft. }\n    iIntros (?) \"[Hh Htm]\". wp_seq.\n    wp_apply (wp_transaction_manager_recv_responses\n                with \"[$Hh $Hpend $Hlog $Htm $Hrcv $Htm_si]\"); [done|].\n    iIntros ([] R') \"(Hpend & Htm & Hh & Hlog & Hb)\".\n    - (* all RMs are prepared to commit *)\n      wp_pures.\n      iDestruct (big_sepS_sep with \"Hb\") as \"[#Hprepared Hpends]\".\n      iMod (tm_shot_prepared with \"Hpend Hpends\") as \"#Hshot\".\n      wp_apply (wp_sendto_all_set (\u03bb _, rm_si) with \"[$Hh $Htm]\"); [done|done|..].\n      { iFrame \"%\". iApply (big_sepS_impl with \"Hrmsis\").\n        iIntros \"!#\" (??) \"Hsi\". iFrame.\n        rewrite /rm_si /=. eauto. }\n      iIntros (?) \"(Hh & Htm)\". wp_pures.\n      wp_apply (wp_receivefrom_nodup_set with \"[] Hrcv [$Hh $Htm_si $Htm $Hlog //]\");\n        [done..| |].\n      { by iIntros \"!#\" (?) \"[% ?]\". }\n      iIntros (d' vd' ?) \"(%Hd' & %Hdom' & Hms & _ & Hh & Htm & Hlog)\".\n      wp_pures.\n      iPoseProof (tm_rm_committed with \"Hshot Hms\") as \"Hms\".\n      iDestruct (big_sepM_sep with \"Hms\") as \"[Hb Hms]\".\n      wp_apply (wp_map_iter (\u03bb _ b, \u231cb = \"COMMITTED\"\u231d)%I\n                            (\u03bb _ _, True)%I True%I _ _ d' with \"[] [$Hb //]\").\n      { iIntros (rm b \u039e) \"!# [_ ->] H\u039e\". do 3 wp_pure _.\n        wp_apply wp_assert. wp_pures. iSplit; [done|]. iModIntro. by iApply \"H\u039e\". }\n      iIntros \"_\".\n      wp_seq. iLeft. iSplit; [done|].\n      rewrite big_sepM_dom Hdom' //.\n    - (* someone aborted *)\n      wp_pures.\n      iMod (pending_discard with \"Hpend\") as \"#Hdisc\".\n      wp_apply (wp_sendto_all_set (\u03bb _, rm_si) with \"[$Hh $Htm]\"); [done|done|..].\n      { iFrame \"%\". iApply (big_sepS_impl with \"Hrmsis\").\n        iIntros \"!#\" (??) \"Hsi\". iFrame. rewrite /rm_si; eauto. }\n      iIntros (?) \"[Hh Htm]\". wp_pures.\n      iRight.\n      iDestruct \"Hb\" as (?) \"(?&?&?)\".\n      eauto.\n  Qed.\n\nEnd transaction_manager.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/transaction_commit/two_phase_tm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889206}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma sll_perm_eq_congr2 x h s_1 s_2 : perm_eq s_1 s_2 -> sll x s_1 h -> sll x s_2 h.\n  (* intros; hammer *)\n  move=>Heq Hsll; sslauto.\n  case: Hsll=>cond.\n  move=>[Heq1 ->].\n  constructor 1=>//=; sslauto.\n  move=>[v] [s2] [nxt] [h'].\n  move=>[Heq1 [-> Hssl]].\n  constructor 2=>//=.\n  exists v, s2, nxt, h'.\n  sslauto.\n  assumption.\nQed.\nHint Resolve sll_perm_eq_congr2: ssl_pred.\nLemma pure2 (x : nat) (y : nat) : @perm_eq nat_eqType ([:: x; y]) (([:: y]) ++ ([:: x])).\n  (* intros; hammer. *)\n  solve_perm_eq.\nQed.\nHint Resolve pure2: ssl_pure.\n\nDefinition sll_dupleton_type :=\n  forall (vprogs : nat * nat * ptr),\n  {(vghosts : ptr)},\n  STsep (\n    fun h =>\n      let: (x, y, r) := vprogs in\n      let: (a) := vghosts in\n      h = r :-> (a),\n    [vfun (_: unit) h =>\n      let: (x, y, r) := vprogs in\n      let: (a) := vghosts in\n      exists elems z,\n      exists h_sll_zelems_1,\n      @perm_eq nat_eqType (elems) ([:: x; y]) /\\ h = r :-> (z) \\+ h_sll_zelems_1 /\\ sll z elems h_sll_zelems_1\n    ]).\n\nProgram Definition sll_dupleton : sll_dupleton_type :=\n  Fix (fun (sll_dupleton : sll_dupleton_type) vprogs =>\n    let: (x, y, r) := vprogs in\n    Do (\n      a1 <-- @read ptr r;\n      z1 <-- allocb null 2;\n      nxtz1 <-- allocb null 2;\n      r ::= z1;;\n      (z1 .+ 1) ::= nxtz1;;\n      (nxtz1 .+ 1) ::= null;;\n      nxtz1 ::= x;;\n      z1 ::= y;;\n      ret tt\n    )).\nObligation Tactic := intro; move=>[[x y] r]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>a.\nmove=>[sigma_self].\nsubst h_self.\nssl_ghostelim_post.\ntry rename h_sll_zelems_1 into h_sll_zxy_1.\ntry rename H_sll_zelems_1 into H_sll_zxy_1.\nssl_read r.\ntry rename a into a1.\ntry rename h_sll_nxtzs1z_0z into h_sll_nxtzvnxtzs1nxtz_0z.\ntry rename H_sll_nxtzs1z_0z into H_sll_nxtzvnxtzs1nxtz_0z.\ntry rename h_sll_nxtnxtzs1nxtz_0nxtz into h_sll_s1nxtz_0nxtz.\ntry rename H_sll_nxtnxtzs1nxtz_0nxtz into H_sll_s1nxtz_0nxtz.\ntry rename h_sll_s1nxtz_0nxtz into h_sll__0nxtz.\ntry rename H_sll_s1nxtz_0nxtz into H_sll__0nxtz.\ntry rename h_sll_nxtzvnxtzs1nxtz_0z into h_sll_nxtzvnxtz_0z.\ntry rename H_sll_nxtzvnxtzs1nxtz_0z into H_sll_nxtzvnxtz_0z.\nssl_alloc z1.\ntry rename z into z1.\ntry rename h_sll_zxy_1 into h_sll_z1xy_1.\ntry rename H_sll_zxy_1 into H_sll_z1xy_1.\nssl_alloc nxtz1.\ntry rename nxtz into nxtz1.\ntry rename h_sll_nxtzvnxtz_0z into h_sll_nxtz1vnxtz_0z.\ntry rename H_sll_nxtzvnxtz_0z into H_sll_nxtz1vnxtz_0z.\nssl_write r.\nssl_write_post r.\nssl_write (z1 .+ 1).\nssl_write_post (z1 .+ 1).\nssl_write (nxtz1 .+ 1).\nssl_write_post (nxtz1 .+ 1).\ntry rename h_sll_nxtz1vnxtz_0z into h_sll_nxtz1x_0z.\ntry rename H_sll_nxtz1vnxtz_0z into H_sll_nxtz1x_0z.\nssl_write nxtz1.\nssl_write_post nxtz1.\nssl_write z1.\nssl_write_post z1.\nssl_emp;\nexists ([:: x; y]), (z1);\nexists (z1 :-> (y) \\+ z1 .+ 1 :-> (nxtz1) \\+ nxtz1 :-> (x) \\+ nxtz1 .+ 1 :-> (null));\nsslauto.\nssl_close 2;\nexists (y), (([:: x]) ++ (@nil nat)), (nxtz1), (nxtz1 :-> (x) \\+ nxtz1 .+ 1 :-> (null));\nsslauto.\nssl_close 2;\nexists (x), (@nil nat), (null), (empty);\nsslauto.\nssl_close 1;\nsslauto.\nQed.\n", "meta": {"author": "TyGuS", "repo": "ssl-htt", "sha": "3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d", "save_path": "github-repos/coq/TyGuS-ssl-htt", "path": "github-repos/coq/TyGuS-ssl-htt/ssl-htt-3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d/benchmarks/advanced/sll/sll_dupleton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889206}}
{"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.\nRequire Export Conventions1.\n\n(** The processor-dependent and EABI-dependent definitions are in\n    [arch/abi/Conventions1.v].  This file adds various processor-independent\n    definitions and lemmas. *)\n\nLemma loc_arguments_acceptable_2:\n  forall s l,\n  In l (regs_of_rpairs (loc_arguments s)) -> loc_argument_acceptable l.\nProof.\n  intros until l. generalize (loc_arguments_acceptable s). generalize (loc_arguments s).\n  induction l0 as [ | p pl]; simpl; intros.\n- contradiction.\n- rewrite in_app_iff in H0. destruct H0.\n  exploit H; eauto. destruct p; simpl in *; intuition congruence.\n  apply IHpl; auto.\nQed.\n\n(** ** Stack size of function arguments *)\n\n(** [size_arguments s] returns the number of [Outgoing] slots used\n  to call a function with signature [s]. *)\n\nDefinition max_outgoing_1 (accu: Z) (l: loc) : Z :=\n  match l with\n  | S Outgoing ofs ty => Z.max accu (ofs + typesize ty)\n  | _ => accu\n  end.\n\nDefinition max_outgoing_2 (accu: Z) (rl: rpair loc) : Z :=\n  match rl with\n  | One l => max_outgoing_1 accu l\n  | Twolong l1 l2 => max_outgoing_1 (max_outgoing_1 accu l1) l2\n  end.\n\nDefinition size_arguments (s: signature) : Z :=\n  List.fold_left max_outgoing_2 (loc_arguments s) 0.\n\n(** The offsets of [Outgoing] arguments are below [size_arguments s]. *)\n\nRemark fold_max_outgoing_above:\n  forall l n, fold_left max_outgoing_2 l n >= n.\nProof.\n  assert (A: forall n l, max_outgoing_1 n l >= n).\n  { intros; unfold max_outgoing_1. destruct l as [_ | []]; extlia. }\n  induction l; simpl; intros. \n  - lia.\n  - eapply Zge_trans. eauto.\n    destruct a; simpl. apply A. eapply Zge_trans; eauto.\nQed.\n\nLemma size_arguments_above:\n  forall s, size_arguments s >= 0.\nProof.\n  intros. apply fold_max_outgoing_above.\nQed.\n\nLemma loc_arguments_bounded:\n  forall (s: signature) (ofs: Z) (ty: typ),\n  In (S Outgoing ofs ty) (regs_of_rpairs (loc_arguments s)) ->\n  ofs + typesize ty <= size_arguments s.\nProof.\n  intros until ty.\n  assert (A: forall n l, n <= max_outgoing_1 n l).\n  { intros; unfold max_outgoing_1. destruct l as [_ | []]; extlia. }\n  assert (B: forall p n,\n             In (S Outgoing ofs ty) (regs_of_rpair p) ->\n             ofs + typesize ty <= max_outgoing_2 n p).\n  { intros. destruct p; simpl in H; intuition; subst; simpl.\n  - extlia.\n  - eapply Z.le_trans. 2: apply A. extlia.\n  - extlia. }\n  assert (C: forall l n,\n             In (S Outgoing ofs ty) (regs_of_rpairs l) ->\n             ofs + typesize ty <= fold_left max_outgoing_2 l n).\n  { induction l; simpl; intros.\n  - contradiction.\n  - rewrite in_app_iff in H. destruct H.\n  + eapply Z.le_trans. eapply B; eauto.\n    apply Z.ge_le. apply fold_max_outgoing_above.\n  + apply IHl; auto.\n  }\n  apply C. \nQed.\n\n(** ** Location of function parameters *)\n\n(** A function finds the values of its parameter in the same locations\n  where its caller stored them, except that the stack-allocated arguments,\n  viewed as [Outgoing] slots by the caller, are accessed via [Incoming]\n  slots (at the same offsets and types) in the callee. *)\n\nDefinition parameter_of_argument (l: loc) : loc :=\n  match l with\n  | S Outgoing n ty => S Incoming n ty\n  | _ => l\n  end.\n\nDefinition loc_parameters (s: signature) : list (rpair loc) :=\n  List.map (map_rpair parameter_of_argument) (loc_arguments s).\n\nLemma incoming_slot_in_parameters:\n  forall ofs ty sg,\n  In (S Incoming ofs ty) (regs_of_rpairs (loc_parameters sg)) ->\n  In (S Outgoing ofs ty) (regs_of_rpairs (loc_arguments sg)).\nProof.\n  intros.\n  replace (regs_of_rpairs (loc_parameters sg)) with (List.map parameter_of_argument (regs_of_rpairs (loc_arguments sg))) in H.\n  change (S Incoming ofs ty) with (parameter_of_argument (S Outgoing ofs ty)) in H.\n  exploit list_in_map_inv. eexact H. intros [x [A B]]. simpl in A.\n  exploit loc_arguments_acceptable_2; eauto. unfold loc_argument_acceptable; intros.\n  destruct x; simpl in A; try discriminate.\n  destruct sl; try contradiction.\n  inv A. auto.\n  unfold loc_parameters. generalize (loc_arguments sg). induction l as [ | p l]; simpl; intros.\n  auto.\n  rewrite map_app. f_equal; auto. destruct p; auto.\nQed.\n\n(** * Tail calls *)\n\n(** A tail-call is possible for a signature if the corresponding\n    arguments are all passed in registers. *)\n\n(** A tail-call is possible for a signature if the corresponding\n    arguments are all passed in registers. *)\n\nDefinition tailcall_possible (s: signature) : Prop :=\n  forall l, In l (regs_of_rpairs (loc_arguments s)) ->\n  match l with R _ => True | S _ _ _ => False end.\n\n(** Decide whether a tailcall is possible. *)\n\nDefinition tailcall_is_possible (sg: signature) : bool :=\n  List.forallb\n    (fun l => match l with R _ => true | S _ _ _ => false end)\n    (regs_of_rpairs (loc_arguments sg)).\n\nLemma tailcall_is_possible_correct:\n  forall s, tailcall_is_possible s = true -> tailcall_possible s.\nProof.\n  unfold tailcall_is_possible; intros. rewrite forallb_forall in H.\n  red; intros. apply H in H0. destruct l; [auto|discriminate].\nQed.\n\nLemma zero_size_arguments_tailcall_possible:\n  forall sg, size_arguments sg = 0 -> tailcall_possible sg.\nProof.\n  intros; red; intros. exploit loc_arguments_acceptable_2; eauto.\n  unfold loc_argument_acceptable.\n  destruct l; intros. auto. destruct sl; try contradiction. destruct H1.\n  generalize (loc_arguments_bounded _ _ _ H0).\n  generalize (typesize_pos ty). lia.\nQed.\n\n\n(** * Callee-save locations *)\n\n(** We classify locations as either\n- callee-save, i.e. preserved across function calls:\n  callee-save registers, [Local] and [Incoming] stack slots;\n- caller-save, i.e. possibly modified by a function call:\n  non-callee-save registers, [Outgoing] stack slots.\n\nConcerning [Outgoing] stack slots: several ABIs allow a function to modify\nthe stack slots used for passing parameters to this function.\nThe code currently generated by CompCert never does so, but the code\ngenerated by other compilers often does so (e.g. GCC for x86-32).\nHence, CompCert-generated code must not assume that [Outgoing] stack slots\nare preserved across function calls, because they might not be preserved\nif the called function was compiled by another compiler. \n*)\n\nDefinition callee_save_loc (l: loc) :=\n  match l with\n  | R r => is_callee_save r = true\n  | S sl ofs ty => sl <> Outgoing\n  end.\n\nDefinition agree_callee_save (ls1 ls2: Locmap.t) : Prop :=\n  forall l, callee_save_loc l -> ls1 l = ls2 l.\n\n(** * Assigning result locations *)\n\n(** Useful lemmas to reason about the result of an external call. *)\n\nLemma locmap_get_set_loc_result:\n  forall sg v rs l,\n  match l with R r => is_callee_save r = true | S _ _ _ => True end ->\n  Locmap.setpair (loc_result sg) v rs l = rs l.\nProof.\n  intros. apply Locmap.gpo. \n  assert (X: forall r, is_callee_save r = false -> Loc.diff l (R r)).\n  { intros. destruct l; simpl. congruence. auto. }\n  generalize (loc_result_caller_save sg). destruct (loc_result sg); simpl; intuition auto.\nQed.\n\nLemma locmap_get_set_loc_result_callee_save:\n  forall sg v rs l,\n  callee_save_loc l ->\n  Locmap.setpair (loc_result sg) v rs l = rs l.\nProof.\n  intros. apply locmap_get_set_loc_result. \n  red in H; destruct l; auto.\nQed.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/backend/Conventions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.18066671193889206}}
{"text": "Add Search Blacklist \"Private_\" \"_subproof\".\nSet Printing Depth 50.\nRemove Search Blacklist \"Private_\" \"_subproof\".\nAdd Search Blacklist \"Private_\" \"_subproof\".\nAdd LoadPath \"../..\".\nRequire Import BetaJulia.BasicPLDefs.Identifier.\nRequire Import BetaJulia.Sub0280a.BaseDefs.\nRequire Import BetaJulia.Sub0280a.BaseProps.\nRequire Import BetaJulia.Sub0280a.BaseMatchProps.\nRequire Import BetaJulia.Sub0280a.BaseSemSubProps.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nLemma sem_sub_k_exist_fresh_l : forall (k : nat) (X : id) (t : ty), fresh_in_ty X t -> ||-[ k][TExist X t]<= [t].\nProof.\n(intros k X t Hfresh).\n(intros w1).\nexists w1.\n(intros v Hm).\n(destruct w1).\n-\n(apply match_ty_exist__0_inv in Hm; contradiction).\n-\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hm]).\n(simpl in Hm).\n(rewrite subs_fresh_in_ty in Hm; try assumption).\n(eapply match_ty__ge_w).\neassumption.\n(repeat constructor).\nQed.\nLemma sem_sub_k_exist_fresh_r : forall (k : nat) (X : id) (t : ty), fresh_in_ty X t -> ||-[ k][t]<= [TExist X t].\nProof.\n(intros k X t Hfresh).\n(intros w1).\nexists (S w1).\n(intros v Hm).\n(apply match_ty_exist).\nexists (TEV X).\n(rewrite subs_fresh_in_ty; assumption).\nQed.\nLemma sem_sub_exist_fresh_l : forall (X : id) (t : ty), fresh_in_ty X t -> ||- [TExist X t]<= [t].\nProof.\n(intros X t Hfresh k).\n(apply sem_sub_k_exist_fresh_l).\nassumption.\nQed.\nLemma sem_sub_k_exist_pair : forall (k : nat) (X : id) (t1 t2 : ty), ||-[ k][TExist X (TPair t1 t2)]<= [TPair (TExist X t1) (TExist X t2)].\nProof.\n(intros k X t1 t2 w1).\nexists w1.\n(intros v Hm).\n(destruct w1).\n-\n(apply match_ty_exist__0_inv in Hm; contradiction).\n-\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hm]).\n(simpl in Hm).\n(apply match_ty_pair__inv in Hm).\n(destruct Hm as [v1 [v2 [Heq [Hm1 Hm2]]]]; subst).\n(apply match_ty_pair; apply match_ty_exist; exists tx; assumption).\nQed.\nLemma sem_sub_exist_pair : forall (X : id) (t1 t2 : ty), ||- [TExist X (TPair t1 t2)]<= [TPair (TExist X t1) (TExist X t2)].\nProof.\n(intros X t1 t2 k).\n(apply sem_sub_k_exist_pair).\nQed.\nLemma match_ty_ev__match_ty_any :\n  forall (k w : nat) (X : id) (t : ty), fresh_in_ty X t -> |-[ k, w] TEV X <$ t -> forall v : ty, value_type v -> |-[ k, w] v <$ t.\nProof.\n(intros k w).\ngeneralize dependent k.\n(induction w).\nadmit.\n(intros k X t HX Hm v Hv).\n(induction t).\nadmit.\nadmit.\nadmit.\nadmit.\n-\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hm]).\nSearch -IdSet.In.\n(destruct (beq_idP X i)).\n+\nsubst.\n(apply match_ty_exist).\nexists tx.\n(apply IHw with i; try assumption).\nAbort.\nLemma sem_sub_fresh_var__sem_sub_any :\n  forall (X : id) (t t' : ty) (X' : id),\n  IdSet.In X (FV t) -> fresh_in_ty X' t' -> ||- [[X := TVar X'] t]<= [t'] -> forall tx : ty, ||- [[X := tx] t]<= [t'].\nProof.\n(intros X t).\n(intros t' X' HX HX' Hsem tx).\n(intros k w1).\nspecialize (Hsem k w1).\n(destruct Hsem as [w2 Hsem]).\nexists w2.\n(intros v Hm).\nAbort.\nLemma sem_sub_fresh_var__sem_sub_exist' :\n  forall (X : id) (t t' : ty) (X' : id),\n  IdSet.In X (FV t) -> fresh_in_ty X' t' -> ||- [[X := TVar X'] t]<= [t'] -> forall tx : ty, ||- [[X := tx] t]<= [t'].\nProof.\n(intros X t t' X' HX HX' Hsem tx).\n(intros k w1).\nspecialize (Hsem k w1).\n(destruct Hsem as [w2 Hsem]).\nexists w2.\n(intros v Hm).\n(induction w1).\nAbort.\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/7/user-7-session-145.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3451052844289766, "lm_q1q2_score": 0.18063512326439762}}
{"text": "Load \"tactics\".\n\n(********DH_3_irr********************)\n(***********DH protocol 3 sessions, initiator, responder, responder********************)\n(*****************Real or random Secrecy*****************************************)\n(********************************************************************************)\n(******protocol Pi1 :The oracle reveals the actual Key if there is any*************)\n\n(********************************************************************************)\n\n\nDefinition phi0  := [ msg (G 0) ; msg (g 0)].\nDefinition mphi0 := (conv_mylist_listm phi0).\nDefinition grn (n:nat) := (exp (G 0) (g 0) (r n)).\n\nDefinition x1 := (f mphi0).\n(******start state****************)\nDefinition qa000:= (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) (grn 1 ) (if_then_else_M (EQ_M (to x1) (i 2)) (grn 2) (if_then_else_M (EQ_M (to x1) (i 3)) (grn 3)   O) ) )))).\n\n(************************)\nDefinition t12:= msg qa000.\nDefinition phi1 := phi0 ++ [ t12 ].\n\n\n(***********************************************************)\n\nDefinition mphi1 := (conv_mylist_listm phi1).\nDefinition mx1rn1 := (exp (G 0) (m x1) (r 1)).\nDefinition mx1rn2 := (exp (G 0) (m x1) (r 2)).\nDefinition grn2:= (exp (G 0) (g 0) (r 2)).\n\nDefinition x2 := (f mphi1).\n\nDefinition tta1 ( x2 x1 :message) (j :nat) := (EQ_M (reveal x2) (i j)) & (EQ_M (to x1) (i j)).\nDefinition tta2 (x3 x2 x1 :message) (j:nat) := (EQ_M (reveal x3) (i j)) & (EQ_M (to x2) (i j)) & (EQ_M (to x1) (i j))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new).\n\n(**********qa0000 -> qa1000, qa0010, qa0100, qa0001*************************************************)\n\nDefinition qa100 := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) acc  (if_then_else_M (EQ_M (to x2) (i 2)) (grn 2)  (if_then_else_M (EQ_M (to x2) (i 3)) (grn 3)   O)))))).\n\n\nDefinition qa010 := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1 (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) (grn 1)  (if_then_else_M (EQ_M (to x2) (i 3)) (grn 3)  O))))).\n\nDefinition qa001:= (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1 (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) (grn 1)  (if_then_else_M (EQ_M (to x2) (i 2)) (grn 2)  O))))).\n\nDefinition t13 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100 (if_then_else_M (EQ_M (to x1) (i 2)) qa010 (if_then_else_M (EQ_M (to x1) (i 3)) qa001  O) ) )))).\nDefinition phi2:= phi1 ++ [t13].\n\n\n\n(***************************************************************************)\n\nDefinition mphi2 := (conv_mylist_listm phi2).\nDefinition mx2rn1 := (exp (G 0) (m x2) (r 1)).\nDefinition mx2rn2 := (exp (G 0) (m x2) (r 2)).\nDefinition mx1rn3 := (exp (G 0) (m x1) (r 3)).\nDefinition mx2rn3 := (exp (G 0) (m x2) (r 3)).\nDefinition grn3:= (exp (G 0) (g 0) (r 3)).\nDefinition x3 := (f mphi2).\n\n\n\n(************* qa100 -> qbar, qa200, qa110, qa101, qbar*******************************************************)\n\nDefinition qa200 := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) (grn 2)  (if_then_else_M (EQ_M (to x3 ) (i 3)) (grn 3) O))))).\n\nDefinition qa110 := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1 (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) acc  (if_then_else_M (EQ_M (to x3 ) (i 3)) (grn 3) O)))))).\n \n\nDefinition qa101 :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) acc  (if_then_else_M (EQ_M (to x3 ) (i 2)) (grn 2) O)))))).\n(*************qa010 -> qbar, qa020, qa110, qa011*****************************)\n\nDefinition qa020:= (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) (grn 1) (if_then_else_M (EQ_M (to x3) (i 3)) (grn 3)\n   O)))).\n\nDefinition qa011 := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n \n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) (grn 1)\n  O)))))).\n(************qa001 -> qabar, qa101, qa011, qa002*****************************)\n\nDefinition qa002:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) (grn 1)\n (if_then_else_M (EQ_M (to x3) (i 2) ) (grn 2)  O)))).\n\n\n(***********************************************************)\n \n\nDefinition qa100_s := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qa200 (if_then_else_M (EQ_M (to x2) (i 2)) qa110  (if_then_else_M (EQ_M (to x2) (i 3)) qa101   O)))))).\n\n\nDefinition qa010_s := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020 (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa110  (if_then_else_M (EQ_M (to x2) (i 3)) qa011  O))))).\n\nDefinition qa001_s := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002 (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa101  (if_then_else_M (EQ_M (to x2) (i 2)) qa011  O))))).\n\nDefinition t14 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_s (if_then_else_M (EQ_M (to x1) (i 2)) qa010_s (if_then_else_M (EQ_M (to x1) (i 3)) qa001_s  O) ) )))).\nDefinition phi3:= phi2 ++ [t14].\n\n\n(*******************************************phi4*****************************************************)\n(************************************************************************************************)\nDefinition mphi3 := (conv_mylist_listm phi3).\nDefinition x4 := (f mphi3).\nDefinition mx3rn3 := (exp (G 0) (m x3) (r 3)).\nDefinition mx3rn2 := (exp (G 0) (m x3) (r 2)).\nDefinition mx3rn1 := (exp (G 0) (m x3) (r 1)).\n\nDefinition qa210 :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  (grn 3)  O))))))).\n\n\n\nDefinition qa201 := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  (grn 2)  O))))))).\n\nDefinition qa120 :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  acc (if_then_else_M (EQ_M (to x4) (i 3))  (grn 3)  O) ))).\n\n\n\nDefinition qa111 := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1 (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1 (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) acc O)))))))).\n\n \nDefinition qa102 :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) acc (if_then_else_M (EQ_M (to x4) (i 2)) (grn 2)  O)))).\n\n\nDefinition qa021 :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1 (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) (grn 1)  O )))).\n\nDefinition qa012 :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1 (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) (grn 1)  O )))).\n\n\nDefinition qa300 := (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 2)) (grn 2) (if_then_else_M (EQ_M (to x4) (i 3)) (grn 3) O)))).\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qa200_s := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qa210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa201 O))))).\n\nDefinition qa110_s := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120 (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111 O)))))).\n \n\nDefinition qa101_s :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa201  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111 O)))))).\n(*************qa010 -> qbar, qa020, qa110, qa011*****************************)\n\nDefinition qa020_s := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qa120 (if_then_else_M (EQ_M (to x3) (i 3)) qa021\n   O)))).\n\nDefinition qa011_s := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa111\n  O)))))).\n(************qa001 -> qabar, qa101, qa011, qa002*****************************)\n\nDefinition qa002_s:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa102\n (if_then_else_M (EQ_M (to x3) (i 2) ) qa012  O)))).\n\n\n(***********************************************************)\n \n\nDefinition qa100_ss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qa200_s (if_then_else_M (EQ_M (to x2) (i 2)) qa110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qa101_s   O)))))).\n\n\nDefinition qa010_ss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_s  O))))).\n\nDefinition qa001_ss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa101_s  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_s  O))))).\n\nDefinition t15 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_ss (if_then_else_M (EQ_M (to x1) (i 2)) qa010_ss (if_then_else_M (EQ_M (to x1) (i 3)) qa001_ss  O) ) )))).\nDefinition phi4:= phi3 ++ [t15].\n\n\n(*******************************************phi5****************************************************************)\n(***************************************************************************************************************)\n\n\nDefinition mphi4 := (conv_mylist_listm phi4).\nDefinition x5 := (f mphi4).\nDefinition mx4rn4 := (exp (G 0) (m x4) (r 4)).\nDefinition mx4rn3 := (exp (G 0) (m x4) (r 3)).\nDefinition mx4rn2 := (exp (G 0) (m x4) (r 2)).\nDefinition mx4rn1 := (exp (G 0) (m x4) (r 1)).\n\n\nDefinition qa220:=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) (grn 3) O) ))))))).\n\n\n\n\nDefinition qa211:=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n O)))))))))))).\n\n\nDefinition qa202 := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) (grn 2) O) ))))))).\n\nDefinition qa121 :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) acc O))))).\n\nDefinition qa112:=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) acc O))))).\n \nDefinition qa310 := (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3   (if_then_else_M (EQ_M (reveal x5) (i 3) ) O (if_then_else_M (EQ_M (to x5) (i 3)) (grn 3) O))))).\n\n\nDefinition qa022 :=  (if_then_else_M (EQ_M (reveal x5) (i 1) ) O (if_then_else_M (EQ_M (to x5) (i 1)) & (EQ_M (act x5) new) (grn 1) O) ).\n\nDefinition qa301 := (if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) (grn 2) O))))).\n\n \n(*************************************************************************************************)\n(*************************************************************************************************)\n\nDefinition qa210_s :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qa211  O))))))).\n\n\n\nDefinition qa201_s := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qa211  O))))))).\n\nDefinition qa120_s :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qa220 (if_then_else_M (EQ_M (to x4) (i 3))  qa121  O) ))).\n\n\n\nDefinition qa111_s := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa211 O)))))))).\n\n \nDefinition qa102_s :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202 (if_then_else_M (EQ_M (to x4) (i 2)) qa112  O)))).\n\n\nDefinition qa021_s :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022 (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa121  O )))).\n\nDefinition qa012_s :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022 (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa112  O )))).\n\n\nDefinition qa300_s := (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 2)) qa310 (if_then_else_M (EQ_M (to x4) (i 3)) qa301 O)))).\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qa200_ss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_s\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qa210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa201_s O))))).\n\nDefinition qa110_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_s (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_s  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111_s O)))))).\n \n\nDefinition qa101_ss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa201_s  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111_s O)))))).\n(*************qa010 -> qbar, qa020, qa110, qa011*****************************)\n\nDefinition qa020_ss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qa120_s (if_then_else_M (EQ_M (to x3) (i 3)) qa021_s\n   O)))).\n\nDefinition qa011_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_s\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_s\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_s\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa111_s\n  O)))))).\n(************qa001 -> qabar, qa101, qa011, qa002*****************************)\n\nDefinition qa002_ss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa102_s\n (if_then_else_M (EQ_M (to x3) (i 2) ) qa012_s  O)))).\n\n\n(***********************************************************)\n \n\nDefinition qa100_sss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qa200_ss (if_then_else_M (EQ_M (to x2) (i 2)) qa110_ss (if_then_else_M (EQ_M (to x2) (i 3)) qa101_ss   O)))))).\n\n\nDefinition qa010_sss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa110_ss  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_ss  O))))).\n\nDefinition qa001_sss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa101_ss  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_ss  O))))).\n\nDefinition t16 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_sss (if_then_else_M (EQ_M (to x1) (i 2)) qa010_sss (if_then_else_M (EQ_M (to x1) (i 3)) qa001_sss  O) ) )))).\nDefinition phi5:= phi4 ++ [t16].\n\n\n(*******************************************phi6****************************************************************)\n(***************************************************************************************************************)\n\n\nDefinition mphi5 := (conv_mylist_listm phi5).\nDefinition x6 := (f mphi5).\nDefinition mx5rn5 := (exp (G 0) (m x5) (r 4)).\nDefinition mx5rn4 := (exp (G 0) (m x5) (r 4)).\nDefinition mx5rn3 := (exp (G 0) (m x5) (r 3)).\nDefinition mx5rn2 := (exp (G 0) (m x5) (r 2)).\nDefinition mx5rn1 := (exp (G 0) (m x5) (r 1)).\n\nDefinition qa221 := \n\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn5\n\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\nO\n ))))))))))))))).\n\nDefinition qa212 := (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\n\n O))))))))))))))).\n\n\nDefinition qa122 :=  (if_then_else_M (EQ_M (reveal x6) (i 1) ) O  (if_then_else_M (EQ_M (to x6) (i 1)) acc O)).\n\nDefinition qa311 := (***i2***) (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n(***i3**)\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn5 O)))))))))).\n\nDefinition qa302 :=  (if_then_else_M (EQ_M (reveal x6) (i 2) ) O  (if_then_else_M (EQ_M (to x6) (i 2)) (grn 2) O) ).\n\nDefinition qa320 :=  (if_then_else_M (EQ_M (reveal x6) (i 3) ) O  (if_then_else_M (EQ_M (to x6) (i 3)) (grn 3) O) ).\n(***********************************************************************************************)\n(***********************************************************************************************)\n\nDefinition qa220_s :=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa320\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa320\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) qa221 O) ))))))).\n\n\n\n\nDefinition qa211_s :=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa221\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa311\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa311\n O)))))))))))).\n\n\nDefinition qa202_s := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa302\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa302   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qa212 O) ))))))).\n\nDefinition qa121_s :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa122\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qa221 O))))).\n\nDefinition qa112_s :=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa122\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qa212 O))))).\n \nDefinition qa310_s := (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa320  (if_then_else_M (EQ_M (reveal x5) (i 3) ) O (if_then_else_M (EQ_M (to x5) (i 3)) qa311 O))))).\n\n\nDefinition qa022_s :=  (if_then_else_M (EQ_M (reveal x5) (i 1) ) O (if_then_else_M (EQ_M (to x5) (i 1)) & (EQ_M (act x5) new) qa122 O) ).\n\nDefinition qa301_s := (if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa302\n (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qa311 O))))).\n\n \n(*************************************************************************************************)\n(*************************************************************************************************)\n\nDefinition qa210_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220_s  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310_s (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qa211_s  O))))))).\n\n\n\nDefinition qa201_ss := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202_s  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301_s (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qa211_s  O))))))).\n\nDefinition qa120_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qa220_s (if_then_else_M (EQ_M (to x4) (i 3))  qa121_s  O) ))).\n\n\n\nDefinition qa111_ss := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121_s\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112_s\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa211_s O)))))))).\n\n \nDefinition qa102_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202_s (if_then_else_M (EQ_M (to x4) (i 2)) qa112_s  O)))).\n\n\nDefinition qa021_ss :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa121_s  O )))).\n\nDefinition qa012_ss :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa112_s  O )))).\n\n\nDefinition qa300_ss := (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 2)) qa310_s (if_then_else_M (EQ_M (to x4) (i 3)) qa301_s O)))).\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qa200_sss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_ss\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qa210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa201_ss O))))).\n\nDefinition qa110_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_ss (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_ss  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111_ss O)))))).\n \n\nDefinition qa101_sss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa201_ss  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111_ss O)))))).\n(*************qa010 -> qbar, qa020, qa110, qa011*****************************)\n\nDefinition qa020_sss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qa120_ss (if_then_else_M (EQ_M (to x3) (i 3)) qa021_ss\n   O)))).\n\nDefinition qa011_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_ss\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_ss\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_ss\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa111_ss\n  O)))))).\n(************qa001 -> qabar, qa101, qa011, qa002*****************************)\n\nDefinition qa002_sss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa102_ss\n (if_then_else_M (EQ_M (to x3) (i 2) ) qa012_ss  O)))).\n\n\n(***********************************************************)\n \n\nDefinition qa100_ssss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qa200_sss (if_then_else_M (EQ_M (to x2) (i 2)) qa110_sss (if_then_else_M (EQ_M (to x2) (i 3)) qa101_sss   O)))))).\n\n\nDefinition qa010_ssss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa110_sss  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_sss  O))))).\n\nDefinition qa001_ssss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa101_sss  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_sss  O))))).\n\nDefinition t17 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_ssss (if_then_else_M (EQ_M (to x1) (i 2)) qa010_ssss (if_then_else_M (EQ_M (to x1) (i 3)) qa001_ssss  O) ) )))).\nDefinition phi6 := phi5 ++ [t17].\n\n\n(******************************phi7*********************************************)\n(****************************************************************************)\n\n\n\n\n\nDefinition mphi6 := (conv_mylist_listm phi6).\nDefinition x7 := (f mphi6).\nDefinition mx6rn6 := (exp (G 0) (m x6) (r 6)).\nDefinition mx6rn5 := (exp (G 0) (m x6) (r 5)).\nDefinition mx6rn4 := (exp (G 0) (m x6) (r 4)).\nDefinition mx6rn3 := (exp (G 0) (m x6) (r 3)).\nDefinition mx6rn2 := (exp (G 0) (m x6) (r 2)).\nDefinition mx6rn1 := (exp (G 0) (m x6) (r 1)).\n\nDefinition qa222 := (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x5) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x5) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x5) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x5) (i 1)) & (EQ_M (to x4) (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x6) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x6) new)) & (EQ_M (act x1) new) mx6rn1\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x6) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x6) new)) & (EQ_M (act x2) new) mx6rn2\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x6) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x6) new)) & (EQ_M (act x3) new) mx6rn3\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x6) (i 1)) & (EQ_M (to x4) (i 1))& (notb (EQ_M (act x6) new)) & (EQ_M (act x4) new) mx6rn4\n (if_then_else_M (EQ_M (reveal x7) (i 1)) & (EQ_M (to x6) (i 1)) & (EQ_M (to x5) (i 1))& (notb (EQ_M (act x6) new)) & (EQ_M (act x5) new) mx6rn5 O))))))))))))))).\n\nDefinition qa312:= (if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n  (if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n (if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n  (if_then_else_M  (EQ_M (reveal x7) (i 2)) & (EQ_M (to x6) (i 2)) mx6rn6 O)))))). \n\n\nDefinition qa321 :=  (if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1 \n (if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn1\n  (if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn1\n  (if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn1\n(if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn1 \n (if_then_else_M  (EQ_M (reveal x7) (i 3)) & (EQ_M (to x6) (i 3)) mx6rn1 O)))))). \n\n(*************************************************************************************************)\n(************************************************************************************************)\n\n\nDefinition qa221_s := \n\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) qa222\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) qa222\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) qa222\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) qa222\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) qa222\n\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa321\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa321\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) qa321\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) qa321 O\n))))))))))))))).\n\nDefinition qa212_s := (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) qa222\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) qa222\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) qa222\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) qa222\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) qa222\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa312\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa312\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) qa312\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) qa312\n\n O))))))))))))))).\n\nDefinition qa122_s :=  (if_then_else_M (EQ_M (reveal x6) (i 1) ) O  (if_then_else_M (EQ_M (to x6) (i 1)) qa222 O)).\n\nDefinition qa311_s := (***i2***) (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) qa321  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) qa321\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) qa321\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) qa321\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) qa321\n(***i3**)\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) qa312\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) qa312\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) qa312\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) qa312\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) qa312 O)))))))))).\n\nDefinition qa302_s :=  (if_then_else_M (EQ_M (reveal x6) (i 2) ) O  (if_then_else_M (EQ_M (to x6) (i 2)) qa312 O) ).\n\nDefinition qa320_s :=  (if_then_else_M (EQ_M (reveal x6) (i 3) ) O  (if_then_else_M (EQ_M (to x6) (i 3)) qa321 O) ).\n(***********************************************************************************************)\n(***********************************************************************************************)\n\nDefinition qa220_ss :=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa320_s\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa320_s\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) qa221_s O) ))))))).\n\n\n\n\nDefinition qa211_ss :=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa221_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa221_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa221_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa221_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa221_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa221_s\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa311_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa311_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa311_s\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa311_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa311_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa311_s\n O)))))))))))).\n\n\nDefinition qa202_ss := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa302_s\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa302_s   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qa212_s O) ))))))).\n\nDefinition qa121_ss :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa122_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa122_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa122_s\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qa221_s O))))).\n\nDefinition qa112_ss :=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa122_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa122_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa122_s\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qa212_s O))))).\n \nDefinition qa310_ss := (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa320_s\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa320_s  (if_then_else_M (EQ_M (reveal x5) (i 3) ) O (if_then_else_M (EQ_M (to x5) (i 3)) qa311_s O))))).\n\n\nDefinition qa022_ss :=  (if_then_else_M (EQ_M (reveal x5) (i 1) ) O (if_then_else_M (EQ_M (to x5) (i 1)) & (EQ_M (act x5) new) qa122_s O) ).\n\nDefinition qa301_ss := (if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa302_s\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa302_s\n (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qa311_s O))))).\n\n \n(*************************************************************************************************)\n(*************************************************************************************************)\n\nDefinition qa210_sss :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220_ss  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220_ss\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310_ss\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310_ss\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310_ss (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qa211_ss  O))))))).\n\n\n\nDefinition qa201_sss := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202_ss  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202_ss\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301_ss\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301_ss\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301_ss (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qa211_ss  O))))))).\n\nDefinition qa120_sss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qa220_ss (if_then_else_M (EQ_M (to x4) (i 3))  qa121_ss  O) ))).\n\n\n\nDefinition qa111_sss := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121_ss\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121_ss\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121_ss\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112_ss\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112_ss\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112_ss\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa211_ss O)))))))).\n\n \nDefinition qa102_sss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202_ss (if_then_else_M (EQ_M (to x4) (i 2)) qa112_ss  O)))).\n\n\nDefinition qa021_sss :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022_ss (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022_ss\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa121_ss  O )))).\n\nDefinition qa012_sss :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022_ss (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022_ss\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qa112_ss  O )))).\n\n\nDefinition qa300_sss := (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 2)) qa310_ss (if_then_else_M (EQ_M (to x4) (i 3)) qa301_ss O)))).\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qa200_ssss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_sss\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qa210_sss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa201_sss O))))).\n\nDefinition qa110_ssss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_sss (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_sss  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa210_sss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111_sss O)))))).\n \n\nDefinition qa101_ssss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_sss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_sss\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qa201_sss  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111_sss O)))))).\n(*************qa010 -> qbar, qa020, qa110, qa011*****************************)\n\nDefinition qa020_ssss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qa120_sss (if_then_else_M (EQ_M (to x3) (i 3)) qa021_sss\n   O)))).\n\nDefinition qa011_ssss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_sss\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_sss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_sss\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_sss\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa111_sss\n  O)))))).\n(************qa001 -> qabar, qa101, qa011, qa002*****************************)\n\nDefinition qa002_ssss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qa102_sss\n (if_then_else_M (EQ_M (to x3) (i 2) ) qa012_sss  O)))).\n\n\n(***********************************************************)\n \n\nDefinition qa100_sssss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qa200_ssss (if_then_else_M (EQ_M (to x2) (i 2)) qa110_ssss (if_then_else_M (EQ_M (to x2) (i 3)) qa101_ssss   O)))))).\n\n\nDefinition qa010_sssss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_ssss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa110_ssss  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_ssss  O))))).\n\nDefinition qa001_sssss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_ssss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qa101_ssss  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_ssss  O))))).\n\nDefinition t18 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_sssss (if_then_else_M (EQ_M (to x1) (i 2)) qa010_sssss (if_then_else_M (EQ_M (to x1) (i 3)) qa001_sssss  O) ) )))).\nDefinition phi7 := phi6 ++ [t18].\n\n\n\n\n\n\n\n(******************************************************************************************************************************************************)\n(******************************************************************************************************************************************************)\n(***********************protocol Pi2 : add transitions to qa2001************)\n(***************************************************************************)\n\n\n\n(*Definition phi21 := phi1.\nDefinition phi22 := phi2.\nDefinition phi23 := phi3. *)\n(***************phi24******************************)\n(*****************alpha = 1, beta =2**********************)\nDefinition qb210 :=   (if_then_else_M (EQ_M (reveal  x4) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) (if_then_else_M (EQ_M (reveal  x4) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  (grn 3)  O))))))))) .\n(***********alpha=1, beta=3******************************)\n\nDefinition qb201 :=  (if_then_else_M (EQ_M (reveal  x4) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) (if_then_else_M (EQ_M (reveal  x4) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  (grn 2)  O))))))))).\n\n  \n\n(**************************************************************************************************)\n\n(********************************************************************************************)\n(*******************************************************************************************)\nDefinition qb200_s := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qb210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qb201 O))))).\n\nDefinition qb110_s := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120 (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111 O)))))).\n\n\nDefinition qb101_s :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb201  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111 O)))))).\n\n\n\n\n\n\n(***********************************************************)\n\nDefinition qb100_ss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qb200_s (if_then_else_M (EQ_M (to x2) (i 2)) qb110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qb101_s   O)))))).\n\n\nDefinition qb010_ss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_s  O))))).\n\nDefinition qb001_ss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb101_s  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_s  O))))).\n\nDefinition t25 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qa100_ss (if_then_else_M (EQ_M (to x1) (i 2)) qa010_ss (if_then_else_M (EQ_M (to x1) (i 3)) qa001_ss  O) ) )))).\nDefinition phi24:= phi3 ++ [t25].\n\n\n\n\n\n(*********************************phi25***********************************************************)\n(*************************************************************************************************)\n\n\n(*********************alpha = 1, beta =2**********)\n\nDefinition qb211:=\n(if_then_else_M (EQ_M (reveal  x5) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n\n (if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n\n(if_then_else_M (EQ_M (reveal  x5) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n\n (if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n\n\n \n(*\n(if_then_else_M (EQ_M (reveal  x5) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) \n\n  *)  \n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n O)))))))))))))))).\n\n\n(*******************************************************************************************************************)\n(********************************************************************************************************************)\n\n\nDefinition qb210_s :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qb211  O))))))).\n\n\nDefinition qb201_s := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qb211  O))))))).\n\n\n\n\nDefinition qb111_s := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qb211 O)))))))).\n\n\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qb200_ss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_s\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qb210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qb201_s O))))).\n\nDefinition qb110_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_s (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_s  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qb111_s O)))))).\n \n\nDefinition qb101_ss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb201_s  (if_then_else_M (EQ_M (to x3 ) (i 2)) qb111_s O)))))).\n\nDefinition qb011_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_s\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_s\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_s\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qb111_s\n  O)))))).\n\n\n\n\n(***********************************************************)\n\nDefinition qb100_sss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qb200_ss (if_then_else_M (EQ_M (to x2) (i 2)) qb110_ss (if_then_else_M (EQ_M (to x2) (i 3)) qb101_ss   O)))))).\n\n\nDefinition qb010_sss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb110_ss  (if_then_else_M (EQ_M (to x2) (i 3)) qb011_ss  O))))).\n\nDefinition qb001_sss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb101_ss  (if_then_else_M (EQ_M (to x2) (i 2)) qb011_ss  O))))).\n\nDefinition t26 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qb100_sss (if_then_else_M (EQ_M (to x1) (i 2)) qb010_sss (if_then_else_M (EQ_M (to x1) (i 3)) qb001_sss  O) ) )))).\n\nDefinition phi25:= phi24 ++ [t26].\n\n(*****************************phi26***************************************************)\n(******alpha = 1, beta = 3************************)\n\nDefinition qb221 := (if_then_else_M (EQ_M (reveal  x6) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n\n\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn5\n\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\nO\n ))))))))))))))))).\n(******alpha= 1, beta =2**************)\nDefinition qb212 := \n(if_then_else_M (EQ_M (reveal  x6) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4)\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\n\n O))))))))))))))))).\n\n\n\nDefinition qb220_s :=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa320\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa320\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) qb221 O) ))))))).\n\n\n\n\nDefinition qb211_s :=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qb221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qb221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qb221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qb221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qb221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qb221\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa311\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa311\n O)))))))))))).\n\n\nDefinition qb202_s := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa302\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa302   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qb212 O) ))))))).\n\nDefinition qb121_s :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa122\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qb221 O))))).\n\nDefinition qb112_s :=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa122\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qb212 O))))).\n \n(***************************************************************************************)\n\n\n\nDefinition qb210_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qb220_s  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qb220_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310_s (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qb211_s  O))))))).\n\n\n\nDefinition qb201_ss := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qb202_s  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qb202_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301_s (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qb211_s  O))))))).\n\nDefinition qb120_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qb220_s (if_then_else_M (EQ_M (to x4) (i 3))  qb121_s  O) ))).\n\n\n\nDefinition qb111_ss := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qb121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qb121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qb121_s\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qb112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qb112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qb112_s\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qb211_s O)))))))).\n\n \nDefinition qb102_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202_s (if_then_else_M (EQ_M (to x4) (i 2)) qb112_s  O)))).\n\n\nDefinition qb021_ss :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qb121_s  O )))).\n\nDefinition qb012_ss :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qb112_s  O )))).\n(**************************************************************************)\n\nDefinition qb200_sss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_ss\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qb210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qb201_ss O))))).\n\nDefinition qb110_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qb120_ss (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qb120_ss  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qb111_ss O)))))).\n \n\nDefinition qb101_sss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qb102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qb102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qb201_ss  (if_then_else_M (EQ_M (to x3 ) (i 2)) qb111_ss O)))))).\n\n\nDefinition qb020_sss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qb120_ss (if_then_else_M (EQ_M (to x3) (i 3)) qb021_ss\n   O)))).\n\nDefinition qb011_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qb021_ss\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qb021_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qb012_ss\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qb012_ss\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qb111_ss\n  O)))))).\n\n\nDefinition qb002_sss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qb102_ss\n (if_then_else_M (EQ_M (to x3) (i 2) ) qb012_ss  O)))).\n\n(***********************************************************)\n\nDefinition qb100_ssss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qb200_sss (if_then_else_M (EQ_M (to x2) (i 2)) qb110_sss (if_then_else_M (EQ_M (to x2) (i 3)) qb101_sss   O)))))).\n\n\nDefinition qb010_ssss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qb020_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb110_sss  (if_then_else_M (EQ_M (to x2) (i 3)) qb011_sss  O))))).\n\nDefinition qb001_ssss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qb002_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qb101_sss  (if_then_else_M (EQ_M (to x2) (i 2)) qb011_sss  O))))).\n\nDefinition t27 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qb100_ssss (if_then_else_M (EQ_M (to x1) (i 2)) qb010_ssss (if_then_else_M (EQ_M (to x1) (i 3)) qb001_ssss  O) ) )))).\nDefinition phi26 := phi25 ++ [t27].\n\n(**************************phi27*********************************)\nDefinition phi27 := phi26 ++ [t18].\n\n\n(************************************************************************************)\n(************************************************************************************)\n(************************Protocol Pi2'': replace the output grn4 by mx12rn2 , mx13rn1 in the term qb2001 in Pi2**********)\n(************************************************************************************************************************)\n\n\n\n(*Definition phi31 := phi1.\nDefinition phi32 := phi2.\nDefinition phi33 := phi3.\n*)\n(*****************alpha = 1, beta =2**********************)\nDefinition qc210 :=   (if_then_else_M (EQ_M (reveal  x4) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2 (if_then_else_M (EQ_M (reveal  x4) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  (grn 3)  O))))))))) .\n(***********alpha=1, beta=3******************************)\n\nDefinition qc201 :=  (if_then_else_M (EQ_M (reveal  x4) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2 (if_then_else_M (EQ_M (reveal  x4) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  (grn 2)  O))))))))).\n\n  \n\n(**************************************************************************************************)\n\n(********************************************************************************************)\n(*******************************************************************************************)\nDefinition qc200_s := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qc210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qc201 O))))).\n\nDefinition qc110_s := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120 (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111 O)))))).\n\n\nDefinition qc101_s :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc201  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111 O)))))).\n\n\n\n\n\n\n(***********************************************************)\n\nDefinition qc100_ss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qc200_s (if_then_else_M (EQ_M (to x2) (i 2)) qc110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qc101_s   O)))))).\n\n\nDefinition qc010_ss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_s  O))))).\n\nDefinition qc001_ss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc101_s  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_s  O))))).\n\nDefinition t35 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qc100_ss (if_then_else_M (EQ_M (to x1) (i 2)) qc010_ss (if_then_else_M (EQ_M (to x1) (i 3)) qc001_ss  O) ) )))).\nDefinition phi34:= phi3 ++ [t35].\n\n\n\n\n\n(*********************************phi35***********************************************************)\n(*************************************************************************************************)\n\n\n(*********************alpha = 1, beta =2**********)\n\nDefinition qc211:=\n (if_then_else_M (EQ_M (reveal  x5) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2\n\n (if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1\n\n(if_then_else_M (EQ_M (reveal  x5) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2\n\n(if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1\n \n(*\n(if_then_else_M (EQ_M (reveal  x5) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) \n\n  *)  \n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n O)))))))))))))))).\n\n\n(*******************************************************************************************************************)\n(********************************************************************************************************************)\n\n\nDefinition qc210_s :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qc211  O))))))).\n\n\nDefinition qc201_s := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qc211  O))))))).\n\n\n\n\nDefinition qc111_s := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qc211 O)))))))).\n\n\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qc200_ss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_s\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qc210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qc201_s O))))).\n\nDefinition qc110_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_s (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_s  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qc111_s O)))))).\n \n\nDefinition qc101_ss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc201_s  (if_then_else_M (EQ_M (to x3 ) (i 2)) qc111_s O)))))).\n\nDefinition qc011_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_s\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_s\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_s\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qc111_s\n  O)))))).\n\n\n\n\n(***********************************************************)\n\nDefinition qc100_sss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qc200_ss (if_then_else_M (EQ_M (to x2) (i 2)) qc110_ss (if_then_else_M (EQ_M (to x2) (i 3)) qc101_ss   O)))))).\n\n\nDefinition qc010_sss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc110_ss  (if_then_else_M (EQ_M (to x2) (i 3)) qc011_ss  O))))).\n\nDefinition qc001_sss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc101_ss  (if_then_else_M (EQ_M (to x2) (i 2)) qc011_ss  O))))).\n\nDefinition t36 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qc100_sss (if_then_else_M (EQ_M (to x1) (i 2)) qc010_sss (if_then_else_M (EQ_M (to x1) (i 3)) qc001_sss  O) ) )))).\n\nDefinition phi35:= phi34 ++ [t36].\n(*****************************phi36***************************************************)\n(******alpha = 1, beta = 3************************)\n\nDefinition qc221 := (if_then_else_M (EQ_M (reveal  x6) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2 (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1\n\n\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn5\n\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\nO\n ))))))))))))))))).\n(******alpha= 1, beta =2**************)\nDefinition qc212 := \n(if_then_else_M (EQ_M (reveal  x6) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx2rn2 (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) mx3rn1\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\n\n O))))))))))))))))).\n\n\n\nDefinition qc220_s :=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa320\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa320\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) qc221 O) ))))))).\n\n\n\n\nDefinition qc211_s :=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qc221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qc221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qc221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qc221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qc221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qc221\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa311\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa311\n O)))))))))))).\n\n\nDefinition qc202_s := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa302\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa302   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qc212 O) ))))))).\n\nDefinition qc121_s :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa122\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qc221 O))))).\n\nDefinition qc112_s :=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa122\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qc212 O))))).\n \n(***************************************************************************************)\n\n\n\nDefinition qc210_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qc220_s  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qc220_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310_s (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qc211_s  O))))))).\n\n\n\nDefinition qc201_ss := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qc202_s  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qc202_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301_s (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qc211_s  O))))))).\n\nDefinition qc120_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qc220_s (if_then_else_M (EQ_M (to x4) (i 3))  qc121_s  O) ))).\n\n\n\nDefinition qc111_ss := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qc121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qc121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qc121_s\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qc112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qc112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qc112_s\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qc211_s O)))))))).\n\n \nDefinition qc102_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202_s (if_then_else_M (EQ_M (to x4) (i 2)) qc112_s  O)))).\n\n\nDefinition qc021_ss :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qc121_s  O )))).\n\nDefinition qc012_ss :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qc112_s  O )))).\n(**************************************************************************)\n\nDefinition qc200_sss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_ss\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qc210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qc201_ss O))))).\n\nDefinition qc110_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qc120_ss (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qc120_ss  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qc111_ss O)))))).\n \n\nDefinition qc101_sss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qc102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qc102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qc201_ss  (if_then_else_M (EQ_M (to x3 ) (i 2)) qc111_ss O)))))).\n\n\nDefinition qc020_sss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qc120_ss (if_then_else_M (EQ_M (to x3) (i 3)) qc021_ss\n   O)))).\n\nDefinition qc011_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qc021_ss\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qc021_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qc012_ss\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qc012_ss\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qc111_ss\n  O)))))).\n\n\nDefinition qc002_sss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qc102_ss\n (if_then_else_M (EQ_M (to x3) (i 2) ) qc012_ss  O)))).\n\n(***********************************************************)\n\nDefinition qc100_ssss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qc200_sss (if_then_else_M (EQ_M (to x2) (i 2)) qc110_sss (if_then_else_M (EQ_M (to x2) (i 3)) qc101_sss   O)))))).\n\n\nDefinition qc010_ssss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qc020_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc110_sss  (if_then_else_M (EQ_M (to x2) (i 3)) qc011_sss  O))))).\n\nDefinition qc001_ssss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qc002_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qc101_sss  (if_then_else_M (EQ_M (to x2) (i 2)) qc011_sss  O))))).\n\nDefinition t37 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qc100_ssss (if_then_else_M (EQ_M (to x1) (i 2)) qc010_ssss (if_then_else_M (EQ_M (to x1) (i 3)) qc001_ssss  O) ) )))).\nDefinition phi36 := phi35 ++ [t37].\n(**************************************************)\n\nDefinition phi37 := phi36 ++ [t18].\n\n\n\n(******************************Protocol Pi2' : replace the output grn4 by grn21 in the term qb2001 in Pi2********)\n(****************************************************************************************************************)\nDefinition grn21:= (exp (G 0) (exp (G 0) (g 0) (r 2)) (r 1)).\n(*****************alpha = 1, beta =2**********************)\nDefinition qd210 :=   (if_then_else_M (EQ_M (reveal  x4) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21 (if_then_else_M (EQ_M (reveal  x4) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  (grn 3)  O))))))))) .\n(***********alpha=1, beta=3******************************)\n\nDefinition qd201 :=  (if_then_else_M (EQ_M (reveal  x4) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21 (if_then_else_M (EQ_M (reveal  x4) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2 \n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  (grn 2)  O))))))))).\n\n  \n\n(**************************************************************************************************)\n\n(********************************************************************************************)\n(*******************************************************************************************)\nDefinition qd200_s := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qd210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qd201 O))))).\n\nDefinition qd110_s := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120 (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd210  (if_then_else_M (EQ_M (to x3 ) (i 3)) qa111 O)))))).\n\n\nDefinition qd101_s :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd201  (if_then_else_M (EQ_M (to x3 ) (i 2)) qa111 O)))))).\n\n\n\n\n\n\n(***********************************************************)\n\nDefinition qd100_ss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qd200_s (if_then_else_M (EQ_M (to x2) (i 2)) qd110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qd101_s   O)))))).\n\n\nDefinition qd010_ss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd110_s  (if_then_else_M (EQ_M (to x2) (i 3)) qa011_s  O))))).\n\nDefinition qd001_ss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_s (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd101_s  (if_then_else_M (EQ_M (to x2) (i 2)) qa011_s  O))))).\n\nDefinition t45 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qd100_ss (if_then_else_M (EQ_M (to x1) (i 2)) qd010_ss (if_then_else_M (EQ_M (to x1) (i 3)) qd001_ss  O) ) )))).\nDefinition phi44:= phi3 ++ [t45].\n\n\n\n\n\n(*********************************phi35***********************************************************)\n(*************************************************************************************************)\n\n\n(*********************alpha = 1, beta =2**********)\n\nDefinition qd211:=\n (if_then_else_M (EQ_M (reveal  x5) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n\n (if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n\n(if_then_else_M (EQ_M (reveal  x5) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n\n(if_then_else_M (EQ_M (reveal  x5) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n \n(*\n(if_then_else_M (EQ_M (reveal  x5) (i 1) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) (grn 4) \n\n  *)  \n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n O)))))))))))))))).\n\n\n(*******************************************************************************************************************)\n(********************************************************************************************************************)\n\n\nDefinition qd210_s :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa220  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa220\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310 (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qd211  O))))))).\n\n\nDefinition qd201_s := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa202  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa202\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301 (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qd211  O))))))).\n\n\n\n\nDefinition qd111_s := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa121\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qa121\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa112\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qa112\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qd211 O)))))))).\n\n\n\n(********************************************************************************************)\n(*******************************************************************************************)\n\nDefinition qd200_ss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_s\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qd210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qd201_s O))))).\n\nDefinition qd110_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa120_s (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa120_s  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd210_s  (if_then_else_M (EQ_M (to x3 ) (i 3)) qd111_s O)))))).\n \n\nDefinition qd101_ss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa102_s\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd201_s  (if_then_else_M (EQ_M (to x3 ) (i 2)) qd111_s O)))))).\n\nDefinition qd011_ss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qa021_s\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qa021_s\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qa012_s\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qa012_s\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qd111_s\n  O)))))).\n\n\n\n\n(***********************************************************)\n\nDefinition qd100_sss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qd200_ss (if_then_else_M (EQ_M (to x2) (i 2)) qd110_ss (if_then_else_M (EQ_M (to x2) (i 3)) qd101_ss   O)))))).\n\n\nDefinition qd010_sss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qa020_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd110_ss  (if_then_else_M (EQ_M (to x2) (i 3)) qd011_ss  O))))).\n\nDefinition qd001_sss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qa002_ss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd101_ss  (if_then_else_M (EQ_M (to x2) (i 2)) qd011_ss  O))))).\n\nDefinition t46 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qd100_sss (if_then_else_M (EQ_M (to x1) (i 2)) qd010_sss (if_then_else_M (EQ_M (to x1) (i 3)) qd001_sss  O) ) )))).\n\nDefinition phi45:= phi44 ++ [t46].\n(*****************************phi36***************************************************)\n(******alpha = 1, beta = 3************************)\n\nDefinition qd221 := (if_then_else_M (EQ_M (reveal  x6) (i 3) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21 (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 3))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n\n\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x1) (i 3)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x2) (i 3)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x3) (i 3)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x4) (i 3)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 3)) & (EQ_M (to x5) (i 3)) mx5rn5\n\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\nO\n ))))))))))))))))).\n(******alpha= 1, beta =2**************)\nDefinition qd212 := \n(if_then_else_M (EQ_M (reveal  x6) (i 2) ) & (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21 (if_then_else_M (EQ_M (reveal  x6) (i 1) ) &  (EQ_M (to  x3) (i 1)) &(EQ_M (to x2) (i 2))&(EQ_M (to x1) (i 1)) & (notb (EQ_M ( act x3) new)) &(EQ_M (act x1) new) &(EQ_M (m x2) (grn 1)) &(EQ_M (m  x3) (grn 2)) grn21\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x1) (i 2)) mx1rn1\n   (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x2) (i 2)) mx2rn2\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x3) (i 2)) mx3rn3\n  (if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x4) (i 2)) mx4rn4\n(if_then_else_M  (EQ_M (reveal x6) (i 2)) & (EQ_M (to x5) (i 2)) mx5rn5\n\n(if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x2)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) mx2rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) mx3rn1\n  (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x3)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) mx3rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) mx4rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) mx4rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x4)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) mx4rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x1)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x1) new) mx5rn1\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x2)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x2) new) mx5rn2\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x3)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x3) new) mx5rn3\n (if_then_else_M (EQ_M (reveal x6)  (i 1)) & (EQ_M (to x5)  (i 1)) & (EQ_M (to x4)  (i 1))& (notb (EQ_M (act x5) new)) & (EQ_M (act x4) new) mx5rn4\n\n O))))))))))))))))).\n\n\n\nDefinition qd220_s :=\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa320\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa320\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa320\n\n\n (if_then_else_M (EQ_M (reveal x5) (i 3) ) O  (if_then_else_M (EQ_M (to x5) (i 3)) qd221 O) ))))))).\n\n\n\n\nDefinition qd211_s :=(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qd221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qd221\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qd221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qd221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qd221\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qd221\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa311\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa311\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa311\n O)))))))))))).\n\n\nDefinition qd202_s := (if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa302\n\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x1) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x2) new) qa302\n(if_then_else_M (EQ_M (reveal x5) (i 1)) & (EQ_M (to x4) (i 1)) & (EQ_M (to x3) (i 1))& (notb (EQ_M (act x4) new)) & (EQ_M (act x3) new) qa302   (if_then_else_M (EQ_M (reveal x5) (i 2) ) O (if_then_else_M (EQ_M (to x5) (i 2)) qd212 O) ))))))).\n\nDefinition qd121_s :=\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x1) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x2) (i 3)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 3)) & (EQ_M (to x3) (i 3)) qa122\n\n\n     (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qd221 O))))).\n\nDefinition qd112_s :=   (if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x1) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x2) (i 2)) qa122\n(if_then_else_M (EQ_M (reveal x5) (i 2)) & (EQ_M (to x3) (i 2)) qa122\n (if_then_else_M (EQ_M (reveal x5) (i 1) ) O  (if_then_else_M (EQ_M (to x5) (i 1)) qd212 O))))).\n \n(***************************************************************************************)\n\n\n\nDefinition qd210_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qd220_s  (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qd220_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa310_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa310_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa310_s (if_then_else_M (EQ_M (reveal x4) (i 3) ) O (if_then_else_M (EQ_M (to x4) (i 3))  qd211_s  O))))))).\n\n\n\nDefinition qd201_ss := (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qd202_s  (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qd202_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa301_s\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x1) new) qa301_s\n\n(if_then_else_M  (EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1)) & (EQ_M (to x2) (i 1))& (notb (EQ_M (act x3) new)) & (EQ_M (act x2) new) qa301_s (if_then_else_M (EQ_M (reveal x4) (i 2) ) O (if_then_else_M (EQ_M (to x4) (i 2))  qd211_s  O))))))).\n\nDefinition qd120_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O   (if_then_else_M (EQ_M (reveal x4) (i 3) ) O  (if_then_else_M (EQ_M (to x4) (i 1))  qd220_s (if_then_else_M (EQ_M (to x4) (i 3))  qd121_s  O) ))).\n\n\n\nDefinition qd111_ss := (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qd121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qd121_s\n (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2)) qd121_s\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qd112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qd112_s\n (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x3) (i 3)) qd112_s\n\n       (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qd211_s O)))))))).\n\n \nDefinition qd102_ss :=  (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (reveal x4) (i 1) ) O (if_then_else_M (EQ_M (to x4) (i 1)) qa202_s (if_then_else_M (EQ_M (to x4) (i 2)) qd112_s  O)))).\n\n\nDefinition qd021_ss :=\n(if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x1) (i 3)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 3)) & (EQ_M (to x2) (i 3)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qd121_s  O )))).\n\nDefinition qd012_ss :=   (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2)) qa022_s (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2)) qa022_s\n\n (if_then_else_M (EQ_M (reveal x4) (i 1) ) O  (if_then_else_M (EQ_M (to x4) (i 1))& (EQ_M (act x4) new) qd112_s  O )))).\n(**************************************************************************)\n\nDefinition qd200_sss := (if_then_else_M  (EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1)) & (EQ_M (to x1) (i 1))& (notb (EQ_M (act x2) new)) & (EQ_M (act x1) new) qa300_ss\n\n\n (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M (EQ_M (to x3) (i 2)) qd210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qd201_ss O))))).\n\nDefinition qd110_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qd120_ss (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qd120_ss  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd210_ss  (if_then_else_M (EQ_M (to x3 ) (i 3)) qd111_ss O)))))).\n \n\nDefinition qd101_sss :=  (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qd102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qd102_ss\n (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O  (if_then_else_M (EQ_M (to x3) (i 1)) qd201_ss  (if_then_else_M (EQ_M (to x3 ) (i 2)) qd111_ss O)))))).\n\n\nDefinition qd020_sss := (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 3) ) O (if_then_else_M ((EQ_M (to x3) (i 1)) & (EQ_M (act x3) new)) qd120_ss (if_then_else_M (EQ_M (to x3) (i 3)) qd021_ss\n   O)))).\n\nDefinition qd011_sss := (if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x1) (i 2)) qd021_ss\n(if_then_else_M (EQ_M (reveal x3) (i 2)) & (EQ_M (to x2) (i 2)) qd021_ss\n (if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x1) (i 3)) qd012_ss\n(if_then_else_M (EQ_M (reveal x3) (i 3)) & (EQ_M (to x2) (i 3)) qd012_ss\n  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O  (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qd111_ss\n  O)))))).\n\n\nDefinition qd002_sss:=  (if_then_else_M (EQ_M (reveal x3) (i 1) ) O (if_then_else_M (EQ_M (reveal x3) (i 2) ) O (if_then_else_M (EQ_M (to x3 ) (i 1)) & (EQ_M (act x3) new) qd102_ss\n (if_then_else_M (EQ_M (to x3) (i 2) ) qd012_ss  O)))).\n\n(***********************************************************)\n\nDefinition qd100_ssss := (if_then_else_M (EQ_M (reveal x2) (i 1) ) O (if_then_else_M (EQ_M (reveal x2) (i 2) ) O (if_then_else_M (EQ_M (reveal x2) (i 3) ) O \n (if_then_else_M (EQ_M (to x2) (i 1)) qd200_sss (if_then_else_M (EQ_M (to x2) (i 2)) qd110_sss (if_then_else_M (EQ_M (to x2) (i 3)) qd101_sss   O)))))).\n\n\nDefinition qd010_ssss := (if_then_else_M (EQ_M (reveal x2) (i 2)) & (EQ_M (to x1) (i 2)) qd020_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 3) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd110_sss  (if_then_else_M (EQ_M (to x2) (i 3)) qd011_sss  O))))).\n\nDefinition qd001_ssss := (if_then_else_M (EQ_M (reveal x2) (i 3)) & (EQ_M (to x1) (i 3)) qd002_sss (if_then_else_M (EQ_M (reveal x2) (i 1) ) O  (if_then_else_M (EQ_M (reveal x2) (i 2) ) O  (if_then_else_M (EQ_M (to x2 ) (i 1)) & (EQ_M (act x2) new) qd101_sss  (if_then_else_M (EQ_M (to x2) (i 2)) qd011_sss  O))))).\n\nDefinition t47 :=  msg (if_then_else_M (EQ_M (reveal x1) (i 1) ) O (if_then_else_M (EQ_M (reveal x1) (i 2) ) O (if_then_else_M (EQ_M (reveal x1) (i 3) ) O (if_then_else_M ((EQ_M (to x1) (i 1)) & (EQ_M (act x1) new)) qd100_ssss (if_then_else_M (EQ_M (to x1) (i 2)) qd010_ssss (if_then_else_M (EQ_M (to x1) (i 3)) qd001_ssss  O) ) )))).\nDefinition phi46 := phi45 ++ [t47].\n(**************************************************)\n \nDefinition phi47 := phi46 ++ [t18].\n\n", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/DH_3_irr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.18060760891865435}}
{"text": "From Coq Require Import ZArith.\nRequire Import coqutil.Z.Lia.\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.Spec.Decode.\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 riscv.Proofs.DecodeEncode.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import compiler.SeparationLogic.\nRequire Import bedrock2.ptsto_bytes.\nRequire Import bedrock2.Scalars.\nRequire Import riscv.Utility.Encode.\nRequire Import riscv.Proofs.EncodeBound.\nRequire Import coqutil.Decidable.\nRequire Import compiler.GoFlatToRiscv.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import riscv.Utility.InstructionCoercions.\nRequire Import compiler.ForeverSafe.\nRequire Import compiler.RunInstruction.\nRequire Import compiler.DivisibleBy4.\nRequire Import coqutil.Tactics.Simp.\nImport Utility.\n\nSection EventLoop.\n\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  Local Notation trace := (list LogItem).\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  (* goodReadyState is the invariant which says that the machine is ready to execute\n     the next iteration of the infinite event loop.\n     It also gets a `done` boolean which says whether the PC is supposed to be at the\n     beginning or at the end of the loop body, and should check for that *)\n  Variable goodReadyState: bool -> RiscvMachineL -> Prop.\n\n  Variables pc_start pc_end: word.\n  Hypothesis pc_start_aligned: (word.unsigned pc_start) mod 4 = 0.\n  Hypothesis start_ne_end: pc_start <> pc_end.\n\n  Hypothesis goodReadyState_checks_PC: forall done m,\n      goodReadyState done m -> m.(getPc) = if done then pc_end else pc_start.\n\n  Hypothesis goodReadyState_preserved_by_jump_back:\n    forall (state: RiscvMachineL) newMetrics,\n      goodReadyState true state ->\n      let state' := (withPc pc_start\n                    (withNextPc (word.add pc_start (word.of_Z 4))\n                    (withMetrics newMetrics state))) in\n      valid_machine state' ->\n      goodReadyState false state'.\n\n  Hypothesis goodReadyState_implies_valid_machine: forall pc m,\n      goodReadyState pc m -> valid_machine m.\n\n  Variable jump: Z.\n  Variable iset: InstructionSet.\n  Hypothesis jump_bound: - 2 ^ 20 <= jump < 2 ^ 20.\n  Hypothesis jump_aligned: jump mod 4 = 0.\n  Hypothesis pc_end_def: pc_end = word.sub pc_start (word.of_Z jump).\n\n  Hypothesis goodReadyState_implies_jump_back_instr: forall m,\n      goodReadyState true m ->\n      (exists R, (ptsto_instr iset pc_end (Jal Register0 jump) * R)%sep m.(getMem)) /\\\n      subset (footpr (ptsto_instr iset pc_end (Jal Register0 jump)))\n             (of_list m.(getXAddrs)).\n\n  (* loop body: between pc_start and pc_end *)\n  Hypothesis body_correct: forall (initial: RiscvMachineL),\n      goodReadyState false initial ->\n      runsTo (mcomp_sat (run1 iset)) initial (goodReadyState true).\n\n  Definition runsToGood_Invariant(m: RiscvMachineL): Prop :=\n    runsTo (mcomp_sat (run1 iset)) m (goodReadyState false) /\\ valid_machine m.\n\n  (* \"runs to a good state\" is an invariant of the transition system\n     (note that this does not depend on the definition of runN) *)\n  Lemma runsToGood_is_Invariant: forall (st: RiscvMachineL),\n      runsToGood_Invariant st -> mcomp_sat (run1 iset) st runsToGood_Invariant.\n  Proof.\n    unfold runsToGood_Invariant.\n    intros m [R V].\n    eapply run1_get_sane with (P := (fun m => runsTo (mcomp_sat (run1 iset)) m (goodReadyState false))).\n    1, 3: eauto. revert R.\n    eapply runsTo_safe1_inv; cycle 1.\n    - intros. eapply body_correct; assumption.\n    - intros.\n      (* this is the loop verification code: *)\n      eapply runsToStep. {\n        specialize (goodReadyState_implies_jump_back_instr _ H).\n        destruct goodReadyState_implies_jump_back_instr. simp.\n        specialize (goodReadyState_checks_PC _ _ H). subst pc_end.\n        eapply run_Jal0; try eauto.\n        unfold program, array.\n        rewrite goodReadyState_checks_PC.\n        solve [ ecancel ].\n      }\n      simpl. intros. simp.\n      destruct_RiscvMachine state.\n      destruct_RiscvMachine mid.\n      subst.\n      apply runsToDone.\n      ssplit; try assumption; cbn;\n        ring_simplify (word.add (word.sub pc_start (word.of_Z jump)) (word.of_Z jump));\n        try reflexivity.\n      specialize (goodReadyState_checks_PC _ _ H). simpl in *. subst state_pc.\n      eapply goodReadyState_preserved_by_jump_back in H.\n      + simpl in H.\n        match goal with\n        | |- ?G => let T := type of H in replace G with T; [exact H|]\n        end.\n        repeat f_equal.\n        all: solve_word_eq word_ok.\n      + simpl.\n        match goal with\n        | H: valid_machine ?m1 |- valid_machine ?m2 => replace m2 with m1; [exact H|]\n        end.\n        f_equal. f_equal; solve_word_eq word_ok.\n    - intros state [C1 C2].\n      apply goodReadyState_checks_PC in C1.\n      apply goodReadyState_checks_PC in C2.\n      congruence.\n  Qed.\n\nEnd EventLoop.\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/RiscvEventLoop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.1805040074042205}}
{"text": "Set Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import basics.\nRequire Import enat.\nRequire Import allen.\nRequire Import signal.\nRequire Import compare.\nRequire Import borders.\nRequire Export reactives.\nRequire Import extend.\n\nSection allenfuns.\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\nLtac SAFE_ALLEN_RELATION2 :=\n  intros I1 I2 J1 J2 (E1,E2) (E3,E4) (LL1,RR1);\n  rewrite E1 in *; rewrite E2 in *; rewrite E3 in *; rewrite E4 in *;\n  split; auto.\n\n(*\n * HOLDS\n *)\nDefinition holds (p q:sig) : sig := fun t =>\n (exists (I:allen), (tas t I q) /\\ (on I p)).\n\n(*\n * OCCURS\n *)\nDefinition occurs (p q:sig) : sig :=\n (filter (fun I => (exists t, (in_allen t I) /\\ (p t))) q).\n\nLemma inc_sig_allen_occurs_right (p q:sig) :\n  (inc_sig_allen (occurs p q) q).\napply inc_sig_allen_filter.\nQed.\n\nLemma in_sig_occurs_has (p q:sig) (I:allen) :\n (in_sig I (occurs p q)) ->\n (exists t, (in_allen t I) /\\ (p t)).\nintros IInO.\napply (in_sig_filter IInO).\nintros A B EQA (t,(tInI,Pt)).\nexists t; split; auto.\napply (inc_allen_refl EQA tInI).\nQed.\n\nLemma occurs_not_right (p q:sig) (I J:allen) (t:nat) :\n (tas t I p) ->\n (tas t J q) ->\n (occurs (not_sig p) q t) ->\n ((left I)<=(left J)) ->\n (ilt (right I) (right J)).\nintros tIp tJq (JJ,((tInJJ,JJInq),(tt,(ttInJJ,NPtt)))) LL.\nG (tas_uniq (tas_def tInJJ JJInq) tJq); intros JJJ; clear tInJJ JJInq.\nG (eq_allen_in_allen JJJ ttInJJ). intros ttInJ. clear ttInJJ JJJ.\nG NPtt; clear NPtt.\napply contra. rewrite <- ile__not_ilt, not_sig_def, not_not.\nintros RR. apply (tas_p (I:=I)).\nsplit;[|apply (tas_sig tIp)].\napply (in_allen_inter ttInJ LL RR).\nQed.\n\nLemma up_os_upr (p q:sig) (t:nat) : (up (occurs (sync p q) q) t) -> (up q t).\nintros (GT0c,(I,(LI,IInO))).\nsplit;[auto|].\nexists I; split;[auto|].\napply (inc_sig_allen_filter IInO).\nQed.\n\nLemma up_os_os (p q:sig) (t:nat) : \n (up (occurs (sync p q) q) t) ->\n (occurs (sync p q) q t).\nintros UP.\napply (up_in UP).\nQed.\n\nLemma up_os_up (p q:sig) (t:nat) :\n (up q t) ->\n (occurs (sync p q) q t) ->\n (up p t).\nintros UQ (J,(tJq,(t2,(t2InJ,(UP2,UQ2))))).\nrewrite (up_shared tJq t2InJ UQ UQ2); auto.\nQed.\n\nLemma up_os_upl (p q:sig) (t:nat) : (up (occurs (sync p q) q) t) -> (up p t).\nintros UPO.\napply (up_os_up (up_os_upr UPO) (up_os_os UPO)).\nQed.\n\n\nLemma occurs_sync_shared_left (p q:sig) (I J1 J2:allen) (t2:nat) :\n (tas t2 I p) ->\n (tas (left I) J1 (occurs (sync p q) q)) ->\n (tas t2 J2 (occurs (sync p q) q)) ->\n (left J1)=(left J2).\nintros t2Ip t1J1O t2J2O.\nG (join_or_up t1J1O t2J2O (allen_left (tas_allen t2Ip))).\nintros [EQ | (t,((LT,GT),UP))]; [apply (proj1 EQ)|exfalso].\nG (lt_getS LT); intros (pt,PT). rewrite PT in *. clear PT t.\ncut (in_allen pt I);[intros ptInI|].\n- G (in_sig_slice (tas_sig t2Ip) ptInI).\n  G (before_up (up_os_upl UP)); auto.\n- split.\n    rewrite <- ltS__le; auto.\n  + G (allen_right (tas_allen t2Ip)); apply ilt_trans. simpl.\n    G GT. apply lt_le_trans. auto.\nQed.\n\nLemma sync_shared_left__starts (p q:sig) (I J:allen) (t t1:nat) :\n (tas t I p) ->\n (tas t J (occurs (sync p q) q)) ->\n (in_allen t1 I) ->\n (sync p q t1) ->\n (left I)=(left J).\nintros tIp tJO t1InI SY.\nG (sync_left_first (tas_mov tIp t1InI) SY); intros LI.\nrewrite <- LI in *. clear LI t1InI.\nG (inc_sig_sync_first (sync_comm SY)); intros qt1.\nG (get_sig qt1). intros (J1,t1J1q).\ncut (tas (left I) J1 (occurs (sync p q) q)); [intros t1J1O|].\n- rewrite <- (occurs_sync_shared_left tIp t1J1O tJO).\n  apply (sync__left (tas_left tIp) t1J1q SY).\n- apply (filter_tas t1J1q).\n  exists (left J1); split;[apply in_allen_left|auto].\n  rewrite <- (sync__left (tas_left tIp) t1J1q SY).\n  auto.\nQed.\n\n\n(*\n * OCCURS_UP\n *)\nDefinition occurs_up (p q:sig) := (occurs (up_after q p) p).\n\nLemma inc_sig_allen_occurs_up (p q:sig) : (inc_sig_allen (occurs_up p q) p).\n  apply inc_sig_allen_filter.\nQed.\n\nLemma in_sig_occup (p q:sig) (I J:allen) :\n (in_sig I p) ->\n (tas (left I) J q) ->\n 0 < (left I) ->\n (not_sig (up q) (left I)) ->\n (in_sig I (occurs_up p q)).\nintros Ip ttJq GT0 NUPQtt.\napply (filter_in_sig Ip).\nexists (left I). split.\n- apply in_allen_left.\n- split.\n  + split; [assumption|].\n    exists I. auto.\n  + split;[|assumption].\n    apply (tas_p ttJq).\nQed.\n\nLemma occoccup (p q:sig) (I J:allen) (t:nat) :\n (tas t I p) ->\n (tas (left I) J q) ->\n 0 < (left I) ->\n (not_sig (up q) (left I)) ->\n (ilt (right J) (right I)) ->\n (occurs (not_sig q) (occurs_up p q) t).\nintros tIp ttJq GT0 NUPQtt LT.\nexists I. split;[split|].\n- apply (tas_allen tIp).\n- apply (in_sig_occup (tas_sig tIp) ttJq GT0 NUPQtt).\n- apply (end_before_has_down ttJq LT).\nQed.\n\nLemma up_after_share_left (p q:sig) (I J:allen) (t l:nat) :\n  (tas t I (occurs_up q p)) ->\n  (tas t J (and_sig p q)) ->\n  (up_after p q l) ->\n  (in_allen l J) ->\n  l=(left I).\nintros tIO tJA ((GT0,(II,(LII,IIInq))),(Pl,NUpl)) lInL.\nrewrite LII in *; clear LII l.\nG (eq_sig_tas (and_sig_comm p q) tJA). intros tJrA.\nG (tas_filter_tas_arg tIO); intros tIq.\nG (in_sig_and__inc_allen tJrA tIq).\nintros JIncI.\nG (JIncI _ lInL). intros lInI.\nG (in_allen_left II). intros lInII.\nrewrite (tas_uniq_left (tas_def lInI (tas_sig tIq)) (tas_def lInII IIInq)).\nauto.\nQed.\n\nLemma up_after_left (p q:sig) (I:allen) :\n (in_sig I (occurs_up q p)) ->\n (exists K, (in_sig K p)\n         /\\ (left K)<(left I)\n         /\\ (ilt (Fix (left I)) (right K)) ).\nintros IInO.\ncut (exists t, (in_allen t I)/\\ (up_after p q t)).\n- intros (t,(tInI,((GT0,(II,(LII,IIInq))),(Pt,NUpt)))).\n  G (get_sig Pt); intros (K,(tInK,KInp)).\n  exists K; split; auto.\n  G (in_allen_left II); rewrite <- LII; intros tInII.\n  G (tas_uniq_left (tas_def tInII IIInq) (tas_def tInI (inc_sig_allen_occurs_right IInO))).\n  intros LILII.\n  G (nat_compare (left K) (left I)); intros [OK|[BAD|BAD]].\n  + split; auto.\n    rewrite <- LILII.\n    apply (le_ilt_trans (allen_left tInII) (allen_right tInK)).\n  + exfalso.\n    G NUpt; apply not_not; unfold up.\n    split;[apply GT0|].\n    exists K; split;[|auto].\n    rewrite BAD, LII; auto.\n  + exfalso; G BAD. apply le_not_gt.\n    rewrite <- LILII, <- LII; apply (allen_left tInK).\n- apply (in_sig_filter IInO).\n  intros A B EQ (t,(tInA,UP)).\n  exists t; split; [apply (eq_allen_in_allen EQ tInA)|auto].\nQed.\n\nLemma occurs_up_after_on_left (p q:sig) (I J K:allen) (t u':nat) :\n (tas t I (occurs_up q p)) ->\n (tas t J (and_sig p q)) ->\n (tas t K p) ->\n (in_allen u' J) ->\n (up_after p q u') ->\n (left K)<(left I).\nintros tIO tJA tKp u'InJ NPu'.\nG (up_after_left (tas_sig tIO)). intros (K2,(K2Inp,(K2I,ILT))).\nrewrite (tas_uniq_left (p:=p) (I1:=K) (I2:=K2) (t:=u')); auto.\n- apply (tas_mov tKp (in_sig_and__inc_allen tJA tKp u'InJ)).\n- split;[split|auto].\n  + apply lt_le.\n    apply (lt_le_trans _ _ _ K2I).\n    G (allen_left u'InJ).\n    apply le_trans.\n    G (eq_sig_tas (and_sig_comm p q) tJA). intros tJrA.\n    G (in_sig_and__inc_allen tJrA (tas_filter_tas_arg tIO)).\n    intros JincI.\n    apply (allen_left (JincI _ (in_allen_left J))).\n  + rewrite (up_after_share_left tIO tJA NPu' u'InJ); auto.\nQed.\n\nLemma overlaps_occurs_up (p q:sig) (I J:allen) (t:nat) :\n (tas t I p) ->\n (tas t J q) ->\n (left I) < (left J) ->\n (ilt (right I) (right J)) ->\n (tas t J (occurs_up q p)).\nintros tIp tJq LIJ RIJ.\nsplit;[apply (tas_allen tJq)|].\nsplit;[|split].\n- case_eq (left J); auto; intros lj LJ.\n  intros (K,(ljKq,_)).\n  G (tas_p ljKq).\n  apply (previous_left_out (tas_sig tJq) LJ).\n- case_eq (right J); auto; intros ri RJ.\n  intros (K,(ljKq,_)).\n  G (tas_p ljKq).\n  apply (bounded_right_out (tas_sig tJq) RJ).\n- intros t' t'InJ; exists J. split; [apply (tas_mov tJq t'InJ)|].\n  exists (left J). split;[|].\n  + apply in_allen_left.\n  + apply (overlaps_up_after_left tIp tJq LIJ RIJ).\n    apply (tas_has_intersection tJq tIp).\nQed.\n\n\n\n\n\n\n\n(*\n * AUXILARY ALLEN'S FUNCTIONS\n *)\n(*\n * init\n *)\nDefinition init (p:sig) : sig := (filter (fun I => (left I)=0) p).\n\n(*\n * final\n *)\nDefinition final (p:sig) : sig := (filter (fun I => (right I)=Inf) p).\n\nLemma not_final (p:sig) (I:allen) (t:nat) :\n (tas t I p) ->\n (not_sig (final p) t) ->\n (right I)<>Inf.\nintros tIp.\napply ncontra; intros RI.\nexists I; auto.\nQed.\n\nLemma not_final_fix_right (p:sig) (I:allen) (t:nat) :\n (tas t I p) ->\n (not_sig (final p) t) ->\n (exists ri, (right I)=(Fix ri)).\nintros tIp.\ncase_eq (right I).\n- intros ri RI _. exists ri; auto.\n- intros RI NF. exfalso.\n  G NF. rewrite not_sig_def. apply tilde. rewrite not_not.\n  exists I; auto.\nQed.\n\n\n(*\n * ALLEN'S FUNCION\n *)\n(*\n * MEETS\n *)\nDefinition Meets (x:allen) (y:allen) : Prop := (right x)=(Fix (left y)).\nDefinition meets := extend Meets.\n\nLemma meets_by_end (p q:sig) (I J:allen) (t:nat) :\n (tas t I p) ->\n (in_sig J (not_sig q)) ->\n (right I)=(right J) ->\n (not_sig (final p) t) ->\n (meets p q t).\nintros tIp JInNq RI NotF.\nexists I. split;[auto|].\nG (not_final_fix_right tIp NotF). intros (ri,FRI).\nG (previous_right FRI). intros (pri,PRI).\nrewrite PRI in *. clear PRI.\nrewrite FRI in RI.\nG (bounded_right_out JInNq (eq_sym RI)). rewrite not_sig_def, not_not. intros QSri.\nG (previous_right_in JInNq (eq_sym RI)); rewrite not_sig_def; intros NQri.\nG (up_allen_right NQri QSri); intros (K,(KInq,EQ)).\nexists K. split;[auto|unfold Meets; rewrite FRI, EQ; auto].\nQed.\n\n(*\n * MET\n *)\nDefinition MetBy (x:allen) (y:allen) : Prop := (Fix (left x))=(right y).\nDefinition met := extend MetBy.\n\n(*\n * EQ\n *)\nDefinition Eq (x:allen) (y:allen) : Prop := (eq_allen x y).\nDefinition eq := extend Eq.\n\nLemma Eq_inc : (inclusive_relation Eq). INC_CMP eq_le2 eq_ile. Qed.\n\nLemma inc_sig_eq_left (p q r:sig) :\n (inc_sig p (eq q r)) ->\n (inc_sig p q).\nintros INC.\napply (inc_sig_trans INC).\napply inc_sig_extend_left.\nQed.\n\n(*\n * STARTS\n *)\nDefinition Starts (x:allen) (y:allen) : Prop :=\n    (left x)=(left y)\n /\\ (ilt (right x) (right y)).\nDefinition starts := extend Starts.\n\nLemma Starts_inc : (inclusive_relation Starts). INC_CMP eq_le2 ilt_ile. Qed.\n\n(*\n * STARTED\n *)\nDefinition StartedBy (x:allen) (y:allen) : Prop :=\n    (left x)=(left y)\n /\\ (ilt (right y) (right x)).\nDefinition started := extend StartedBy.\n\nLemma startedBy_Starts (I J:allen) :\n (StartedBy I J) ->\n (Starts J I).\nintros (LL,RR); split; auto.\nQed.\n\n(*\n * ENDS\n *)\nDefinition Ends (x:allen) (y:allen) : Prop :=\n    (left y)<(left x)\n /\\ (right x)=(right y).\nDefinition ends := extend Ends.\n\nLemma ends_safe : (safe_allen_relation Ends). SAFE_ALLEN_RELATION2. Qed.\n\nLemma Ends_inc : (inclusive_relation Ends). INC_CMP lt_le eq_ile. Qed.\n\n(*\n * ENDED\n *)\nDefinition EndedBy (x:allen) (y:allen) : Prop :=\n    (left x)<(left y)\n /\\ (right x)=(right y).\nDefinition ended := extend EndedBy.\n\nLemma EndedBy_inc : (rinclusive_relation EndedBy). RINC_CMP lt_le eq_ile2. Qed.\n\n(*\n * OVERALAPS\n *)\nDefinition Overlaps (x:allen) (y:allen) : Prop :=\n    (left x)<(left y)\n /\\ (ilt (Fix (left y)) (right x))\n /\\ (ilt (right x) (right y)).\nDefinition overlaps := extend Overlaps.\n\n(*\n * OVERLAPPED\n *)\nDefinition OverlappedBy (x:allen) (y:allen) : Prop :=\n    (left y)<(left x)\n /\\ (ilt (Fix (left x)) (right y))\n /\\ (ilt (right y) (right x)).\nDefinition overlapped := extend OverlappedBy.\n \n(*\n * DURING\n *)\nDefinition During (x:allen) (y:allen) : Prop :=\n    (left y)<(left x)\n /\\ (ilt (right x) (right y)).\nDefinition during := extend During.\n\nLemma During_inc_allen (I J:allen) : (During I J) -> (inc_allen I J).\nintros (LL,RR).\napply (left_right_inc_allen (lt_le LL) (ilt_ile RR)).\nQed.\n\nLemma During_safe : (safe_allen_relation During). SAFE_ALLEN_RELATION2. Qed.\n\nLemma During_inc : (inclusive_relation During). INC_CMP lt_le ilt_ile. Qed.\n\nLemma eq_right_during (I J1 J2:allen) :\n (eq_allen J1 J2) ->\n (During I J1) ->\n (During I J2).\nintros (LL,RR) (L1,R1). rewrite LL in L1. rewrite RR in R1.\nsplit; auto.\nQed.\n\nLemma During_in_allen_left (I J:allen) :\n  (During I J) ->\n  (in_allen (left I) J).\nintros DRG.\napply (inc_allen_in_allen_left (During_inc DRG)).\nQed.\n\n\n\n(*\n * CONTAINS\n *)\nDefinition Contains (x:allen) (y:allen) : Prop :=\n    (left x)<(left y)\n /\\ (ilt (right y) (right x)).\nDefinition contains := extend Contains.\n\nLemma contains_has_left (I J:allen) : (Contains I J) -> (in_allen (left J) I).\nintros (LL,RR).\nsplit;[apply (lt_le LL) | apply (ilt_trans (wf J) RR)].\nQed.\n\nLemma During_Contains (I J:allen) : (During I J) -> (Contains J I).\nauto.\nQed.\n\nLemma Contains_During (I J:allen) : (Contains I J) -> (During J I).\nauto.\nQed.\n\n(*\n * OVER\n *)\nDefinition over (p q:sig) : sig := fun t =>\n  (exists I, (tas t I p)\n          /\\ (exists J, (tas t J q)\n                     /\\ ((left I) < (left J))\n                     /\\ (ilt (right I) (right J)) )).\n\nLemma ends_fix_over (p q:sig) (I J:allen) (t ri:nat) :\n (tas t I p) ->\n (tas t J q) ->\n (left J)<(left I) ->\n (right I)=(right J) ->\n (right I)=(Fix ri) ->\n (over q (imp_sig q p) t).\nintros tIp tJq LL RR RI.\nexists J. split;[auto|].\nG (get_sig (or_sig_right (not_sig q) (tas_p tIp))). intros (K,tKO).\nexists K. split;[auto|split].\n- apply (in_sig_imp_left tIp tJq tKO LL RR RI).\n- apply (in_sig_imp_right tIp tJq tKO LL RR RI).\nQed.\n\n\nEnd allenfuns.\n", "meta": {"author": "NicVolanschi", "repo": "Allen", "sha": "daf340d71f26f7fd589b46125853407b89280160", "save_path": "github-repos/coq/NicVolanschi-Allen", "path": "github-repos/coq/NicVolanschi-Allen/Allen-daf340d71f26f7fd589b46125853407b89280160/proof/allenfuns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.18041657265427138}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Bedrock.Word\n        Bedrock.Memory\n        Fiat.Computation.ListComputations.\n\nRequire Import\n        Fiat.Computation.IfDec\n        Fiat.QueryStructure.Specification.Operations.InsertAll\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.Examples.DnsServer.Packet\n        Fiat.Examples.DnsServer.RecursiveDNSSchema.\n\nImport Vectors.VectorDef.VectorNotations.\n\nLocal Open Scope vector.\nLocal Open Scope Tuple_scope.\n\nDefinition linkAuthorityToAdditional\n           (curTime : timeT)\n           (this : QueryStructure RecResolverSchema)\n           (authority : list resourceRecord)\n           (additional : list resourceRecord)\n  : Comp (QueryStructure RecResolverSchema) :=\n  authorityAndAdditional <-\n                         {aal | NoDup aal /\\\n                                forall (ns : NS_Record)\n                                       (ans : A_Record),\n                                  List.In < sDOMAIN :: (ns!sRDATA : DomainName),\n                                            sIP :: (ans!sRDATA : W) > aal\n                            <-> (List.In (NS_Record2RRecord ns) authority\n                                 /\\ List.In (A_Record2RRecord ans) additional\n                                 /\\ ns!sRDATA = ans!sNAME) };\n    `(this, _) <- @StatefulInsertAll RecResolverSchema _ _ _ this ``sSLIST\n                       () authorityAndAdditional\n                       (@QSInsert _)\n                       (fun aal _ => ret (< sQUERYCOUNT :: (natToWord _ 0 : W),\n                                          sTTL :: (curTime ^+ serverTTL : timeT ) > ++ aal, tt))\n                       (fun a s => ret s);\n    ret this\n.\n\nDefinition addAnswersToCache\n           (curTime : timeT)\n           (this : QueryStructure RecResolverSchema)\n           (answers : list resourceRecord)\n           (authority : list resourceRecord)\n           (additional : list resourceRecord)\n  : Comp (QueryStructure RecResolverSchema) :=\n  `(this, _) <- @StatefulInsertAll RecResolverSchema _ _ _ this ``sCACHE\n   () (answers ++ authority ++ additional)\n   (@QSInsert _)\n   (fun aal _ => ret (< sTTL :: curTime ^+ cachedTTL,\n                        sCACHETYPE :: ``\"Answer\",\n                        sDOMAIN :: aal!sNAME,\n                        sQTYPE :: aal!sTYPE,\n                        sCACHEDVALUE :: rRecord2CachedValue aal >, tt))\n   (fun a s => ret s);\n    ret this.\n\nDefinition DnsSpec : ADT _ :=\n  Def ADT {\n    rep := QueryStructure RecResolverSchema,\n\n    Def Constructor \"Init\" : rep := empty,,\n\n    Def Method3 \"Process\"\n        (this : rep)\n        (sourceIP : W)\n        (curTime : timeT)\n        (p : packet) : rep * packet * option W :=\n      If p!\"QR\" Then\n         (* It's a new request! *)\n         vs <- For (v in this!sCACHE) (* Search cache for an answer *)\n                    Where (p!\"question\"!\"qtype\" = CachedQueryTypes_inj v!sQTYPE)\n                    Where (curTime <= v!sTTL) (* only alive cached values *)\n                    Return (v ! sCACHEDVALUE) ;\n         If is_empty vs Then (* Need to launch a recursive query *)\n            (* Generate a unique ID for the new request. *)\n            (reqIDs <- For (req in this!sREQUESTS)\n                            Where (curTime <= req!sTTL)\n                            Return (req!sID);\n             newID <- { newID | ~ List.In newID reqIDs};\n             (* Find the best known servers to query *)\n             bestServer <- MaxElement\n                             (fun r r' : @Tuple SLISTHeading =>\n                                (prefix r!sDOMAIN r'!sDOMAIN)\n                                /\\ r!sQUERYCOUNT <= r'!sQUERYCOUNT)\n                             (For (server in this!sSLIST)\n                              Where (prefix server!sDOMAIN p!\"question\"!\"qname\")\n                              Where (curTime <= server!sTTL)\n                              Return server);\n             Ifopt bestServer as bestServer Then (* Pick the first server*)\n             `(this, _) <- Delete req from this ! sREQUESTS where (req!sTTL <= curTime);\n             `(this, b) <- Insert < sID :: newID,\n                                    sIP :: sourceIP,\n                                    sTTL :: curTime ^+ requestTTL > ++ p into this!sREQUESTS; (* Add the request to the list. *)\n             ret (this, (<\"id\" :: newID,\n                          \"QR\" :: false,\n                          \"Opcode\" :: ``\"Query\",\n                          \"AA\" :: false,\n                          \"TC\" :: false,\n                          \"RD\" :: true,\n                          \"RA\" :: false,\n                          \"RCode\" :: ``\"NoError\",\n                          \"question\" :: p!\"question\",\n                          \"answers\" :: [ ],\n                          \"authority\" :: [ ],\n                          \"additional\" :: [ ] >, Some bestServer!sIP))\n             Else (* There are no known servers that can answer this request. *)\n             ret (this, (buildempty false ``\"ServFail\" p, Some sourceIP)) (* This won't happen if the server has been properly initialized with the root servers. *)\n            )\n       Else                   (* Return cached answer *)\n       (answers <- { answers | NoDup answers\n                               /\\ forall ans : resourceRecord,\n                         List.In ans answers <->\n                         List.In (A := CachedValue) ans vs };\n          If is_empty answers Then (* It must be a cached failure *)\n             failures <- { failures | NoDup failures\n                                      /\\ forall fail : SOA_Record,\n                               List.In (A := resourceRecord) fail failures <->\n                               List.In (A := CachedValue) fail vs };\n             ret (this, (add_additionals failures (buildempty false ``\"NXDomain\" p), Some sourceIP)) (* Add the SoA record to additional and return negative result*)\n          Else\n          ret (this, (add_answers answers (buildempty false ``\"NoError\" p), Some sourceIP)))\n         (* Add the answers to the packet.  *)\n       Else (* It's a response *)\n       (reqs <- For (req in this!sREQUESTS)\n                     Where (req!sID = p!\"id\")\n                     Where (req!\"question\"!\"qtype\" = p!\"question\"!\"qtype\")\n                     Return req;\n        Ifopt List.hd_error reqs as req Then\n          (IfDec p!\"RCODE\" = ``\"NoError\" Then\n            (If isAnswer p Then    (* We have an answer! We first try to  the outstanding request that this is an answer to. *)\n                `(this, reqs) <- Delete req from this!sREQUESTS where (req!sID = p!\"id\");\n                this <- addAnswersToCache curTime this p!\"answers\" p!\"authority\" p!\"additional\";\n                ret (this, (<\"id\" :: req!\"id\",\n                             \"QR\" :: true,\n                             \"Opcode\" :: req!\"Opcode\",\n                             \"AA\" :: false,\n                             \"TC\" :: p!\"TC\",\n                             \"RD\" :: req!\"RD\",\n                             \"RA\" :: true,\n                             \"RCode\" :: ``\"NoError\",\n                             \"question\" :: req!\"question\",\n                             \"answers\" :: p!\"answers\",\n                             \"authority\" :: p!\"authority\",\n                             \"additional\" :: p!\"additional\" >, Some req!sIP) )\n\n           Else  (* We need to issue another query based on the response. *)\n           (this <- linkAuthorityToAdditional curTime this p!\"authority\" p!\"additional\";\n             bestServer <- MaxElement\n                             (fun r r' : @Tuple SLISTHeading =>\n                                (prefix r!sDOMAIN r'!sDOMAIN)\n                                /\\ r!sQUERYCOUNT <= r'!sQUERYCOUNT)\n                             (For (server in this!sSLIST)\n                              Where (prefix server!sDOMAIN p!\"question\"!\"qname\")\n                              Where (curTime <= server!sTTL)\n                              Return server);\n             Ifopt bestServer as bestServer Then (* Pick the first server*)\n               ret (this, (<\"id\" :: p!\"id\",\n                            \"QR\" :: false,\n                            \"Opcode\" :: ``\"Query\",\n                            \"AA\" :: false,\n                            \"TC\" :: false,\n                            \"RD\" :: true,\n                            \"RA\" :: false,\n                            \"RCode\" :: ``\"NoError\",\n                            \"question\" :: p!\"question\",\n                            \"answers\" :: [ ],\n                            \"authority\" :: [ ],\n                            \"additional\" :: [ ] >, Some bestServer!sIP))\n             Else\n               ret (this, (p, None ) )\n         ) )\n         Else (* We need to cache a negative response*)\n         (soas <- { soas | NoDup soas\n                           /\\ forall soa : SOA_Record,\n                        List.In soa soas <->\n                        List.In (A := resourceRecord) soa (p!\"authority\") };\n         Ifopt List.hd_error soas as soa Then (* The response has an SOA *)\n           reqType <- SingletonSet (fun b : CachedQueryTypes => req!\"question\"!\"qtype\" = CachedQueryTypes_inj b);\n           Ifopt reqType as reqType Then\n             (`(this, foo) <- Insert (< sTTL :: curTime ^+ cachedTTL,\n                                        sCACHETYPE :: ``\"Failure\",\n                                        sDOMAIN :: req!\"question\"!\"qname\",\n                                        sQTYPE :: reqType,\n                                        sCACHEDVALUE :: Failure2CachedValue (<\"RCODE\" :: (p!\"RCODE\" : ResponseCode) > ++ soa!sRDATA : FailureRecord ) > )\n               into this!sCACHE;\n              ret (this, (p, Some req!sIP))  )\n            Else (* It's not a record we care to cache *)\n             ret (this, (p, Some req!sIP) )\n           Else (* If there's no SOA record in authority, don't cache *)\n           ret (this, (p, Some req!sIP ) ) ) )\n         Else (* The answer is not affiliated with the packet *)\n           ret (this, (p, None ) ) )\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/Examples/DnsServer/RecursiveDNSResolver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.18035820360850516}}
{"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Cop Ctypes ClightC.\nRequire Import AsmC.\nRequire SimMemInjInvC.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import MatchSimModSem.\nRequire Import IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import CtypingC.\nRequire Import CopC.\n\nRequire Import MatchSimModSem.\nRequire Import Conventions1C.\n\nRequire Import ClightStepInj.\nRequire Import IdSimExtra IdSimInvExtra IdSimClightExtra.\nRequire Import mktac.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nSection INJINV.\n\nVariable P: SimMemInjInv.memblk_invariant.\n\nLocal Instance SimMemP: SimMem.class := SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P.\nLocal Instance SimSymbP: SimSymb.class SimMemP := SimMemInjInvC.SimSymbIdInv P.\n\nLocal Existing Instance SoundTop.Top.\n\nInductive match_states_clight_inv\n  : unit -> Clight.state -> Clight.state -> SimMem.t -> Prop :=\n| match_states_clight_intro\n    st_src st_tgt j m_src m_tgt sm0\n    (MWFSRC: m_src = sm0.(SimMem.src))\n    (MWFTGT: m_tgt = sm0.(SimMem.tgt))\n    (MWFINJ: j = sm0.(SimMemInjInv.minj).(SimMemInj.inj))\n    (MATCHST: match_states_clight_internal st_src st_tgt j m_src m_tgt)\n    (MWF: SimMem.wf sm0)\n  :\n    match_states_clight_inv\n      tt st_src st_tgt sm0\n.\n\nLemma clight_inj_inv_id\n      (clight: Clight.program)\n      (WF: Sk.wf (module2 clight))\n  :\n    exists mp,\n      (<<SIM: ModPair.sim mp>>)\n      /\\ (<<SRC: mp.(ModPair.src) = (module2 clight)>>)\n      /\\ (<<TGT: mp.(ModPair.tgt) = (module2 clight)>>)\n.\nProof.\n  eexists (ModPair.mk _ _ _); s. instantiate (3:= (SimMemInjInvC.mk bot1 _ _)).\n  esplits; eauto.\n  econs; ss; i.\n  { econs; ss; i; clarify. }\n  eapply match_states_sim with (match_states := match_states_clight_inv); ss.\n  - apply unit_ord_wf.\n  - eapply SoundTop.sound_state_local_preservation.\n\n  - i. ss. exploit SimSymbIdInv_match_globals.\n    { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n    inv INITTGT. inv SAFESRC. inv SIMARGS; ss. inv H. ss.\n    exploit match_globals_find_funct; eauto.\n    i. clarify.\n    esplits; eauto.\n    + econs; eauto.\n    + refl.\n    + econs; eauto. econs; eauto.\n      { inv TYP. inv TYP0. eapply inject_list_typify_list; eauto. }\n      econs.\n\n  - i. ss. exploit SimSymbIdInv_match_globals.\n    { inv SIMSKENV. ss. eauto. } intros GEMATCH.\n    des. inv SAFESRC. inv SIMARGS; ss. esplits. econs; ss.\n    + eapply match_globals_find_funct; eauto.\n    + inv TYP. econs; eauto.\n      erewrite <- inject_list_length; eauto.\n\n  - i. ss. inv MATCH; eauto.\n\n  - i. ss. clear SOUND. inv CALLSRC. inv MATCH. inv MATCHST. inv SIMSKENV. ss.\n    esplits; eauto.\n    + econs; ss; eauto.\n      * eapply SimSymbIdInv_find_None; eauto.\n        ii. clarify. ss. des. clarify.\n      * des. clear EXTERNAL.\n        unfold Genv.find_funct, Genv.find_funct_ptr in *. des_ifs_safe.\n        inv INJ. inv SIMSKELINK. inv INJECT. exploit IMAGE; eauto.\n        { left. eapply Genv.genv_defs_range; eauto. }\n        { i. des. clarify. inv SIMSKENV. des_ifs. esplits; eauto. }\n    + econs; ss.\n    + refl.\n    + instantiate (1:=top4). ss.\n\n  - i. ss. clear SOUND HISTORY.\n    exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n    inv AFTERSRC. inv MATCH. inv MATCHST.\n    esplits; eauto.\n    + econs; eauto. inv SIMRET; ss.\n    + inv SIMRET; ss. econs; eauto. econs; eauto.\n      { eapply inject_typify; et. }\n      ss. eapply match_cont_incr; try eassumption.\n      inv MLE. inv MLE1. inv MLE0. inv MLE. etrans; eauto.\n    + refl.\n\n  - i. ss. inv FINALSRC. inv MATCH. inv MATCHST. inv CONT.\n    esplits; eauto.\n    + econs.\n    + econs; eauto.\n    + refl.\n\n  - left. i. split.\n    + eapply modsem2_receptive.\n    + ii. inv MATCH. destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].\n      cinv MWF. cinv WF0. ss.\n      exploit clight_step_preserve_injection2; try eassumption.\n      { instantiate (1:=cgenv skenv_link_tgt clight). ss. }\n      { eapply function_entry2_inject. ss. }\n      { inv SIMSKENV. ss.\n        exploit SimMemInjInvC.skenv_inject_symbols_inject; eauto. }\n      { inv SIMSKENV. ss. exploit SimSymbIdInv_match_globals; eauto. } i. des.\n      exploit SimMemInjC.parallel_gen; eauto. i. des.\n      hexploit SimMemInjInv.le_inj_wf_wf; eauto.\n      { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.\n        - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.\n        - eapply Mem.unchanged_on_implies; eauto.\n          i. exploit INVRANGETGT; eauto. i. des. eauto. } intros MWFINV0.\n\n      esplits; eauto.\n      * left. apply plus_one. econs; ss; eauto.\n        eapply modsem2_determinate.\n      * instantiate (1:=SimMemInjInv.mk _ _ _). econs; ss; eauto.\n      * econs; ss; eauto.\nUnshelve. apply 0.\nQed.\n\nEnd INJINV.\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/IdSimClightIdInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.18027852573291583}}
{"text": "From sflib Require Import sflib.\nRequire Import Coq.Classes.RelationClasses.\nFrom Fairness Require Import Axioms NatStructsLarge.\nFrom Fairness Require Import PCMLarge.\nFrom Fairness Require Import Mod.\n\nSet Implicit Arguments.\n\n(* Definition _thsRA {A: Type}: URA.t := Auth.t (Excl.t A). *)\nGlobal Instance thsRA {A: Type}: URA.t := (thread_id ==> Auth.t (Excl.t A))%ra.\n(* Compute (URA.car (t:=_thsRA)). *)\n(* Global Instance thsRA {A: Type}: URA.t := Auth.t (@_thsRA A). *)\n\nSection THHAS.\n\n  Definition ae_white {A} (a: A) := @Auth.white (Excl.t A) (Some a).\n  Definition ae_black {A} (a: A) := @Auth.black (Excl.t A) (Some a).\n\n  Definition th_has {A: Type} (tid: thread_id) (a: A): (@thsRA A) :=\n    fun _tid => if (tid_dec _tid tid) then ae_white a else \u03b5.\n\n  Lemma unfold_th_has {A} tid (a: A):\n    th_has tid a = fun _tid => if (tid_dec _tid tid) then ae_white a else \u03b5.\n  Proof. reflexivity. Qed.\n\n  (* Definition th_has {A: Type} (tid: thread_id) (a: A): @thsRA A := Auth.black (_th_has tid a). *)\n\n  (* properties *)\n  Lemma th_has_hit {A: Type}: forall tid (a: A), (th_has tid a) tid = ae_white a.\n  Proof. i. rewrite unfold_th_has. des_ifs. Qed.\n\n  Lemma th_has_miss {A: Type}: forall tid tid' (MISS: tid <> tid') (a: A), (th_has tid a tid') = \u03b5.\n  Proof. i. rewrite unfold_th_has. des_ifs. Qed.\n\n  Lemma th_has_disj {A: Type}: forall tid0 tid1 (a0 a1: A),\n      URA.wf (th_has tid0 a0 \u22c5 th_has tid1 a1) -> tid0 <> tid1.\n  Proof. ii. do 2 ur in H. clarify. specialize (H tid1). rewrite !th_has_hit in H. ss. ur in H. ss. Qed.\n\nEnd THHAS.\nNotation \"tid |-> a\" := (th_has tid a) (at level 20).\nGlobal Opaque th_has.\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.black (e \u22c5 f1)\n  | _, _ => Auth.boom\n  end\n.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/simulation/ThreadsURA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.18022750008030253}}
{"text": "Require Import Fiat.Parsers.Grammars.JavaScriptAssignmentExpression.\nRequire Import Fiat.Parsers.Refinement.Tactics.\nRequire Import Fiat.Parsers.Refinement.DisjointRules.\nRequire Import Fiat.Parsers.Refinement.DisjointRulesRev.\nRequire Import Fiat.Parsers.ExtrOcamlParsers. (* for simpl rules for [find_first_char_such_that] *)\nRequire Import Fiat.Parsers.Refinement.BinOpBrackets.BinOpRules.\nRequire Import Fiat.Parsers.StringLike.String.\n\n(*Require Coq.micromega.Lia.\nRequire Coq.PArith.BinPos.\nRequire Coq.Lists.List.\nRequire Coq.Sorting.Mergesort.\nRequire Coq.Structures.OrdersEx.\nRequire Coq.Strings.Ascii.\nRequire Coq.Strings.String.\nRequire Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Fiat.Parsers.ContextFreeGrammar.Reflective.\nRequire Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Fiat.Parsers.Refinement.PossibleTerminalsSets.*)\nRequire ExplorationUtil.\nSet Ltac Profiling.\nSection IndexedImpl.\n  (*Context {HSLM : StringLikeMin Ascii.ascii}\n          {HSL : StringLike Ascii.ascii}\n          {HSI : StringIso Ascii.ascii}\n          {HSLP : StringLikeProperties Ascii.ascii}\n          {HSEP : StringEqProperties Ascii.ascii}\n          {HSIP : StringIsoProperties Ascii.ascii}.*)\n\n  Lemma ComputationalSplitter'\n  : FullySharpened (string_spec javascript_assignment_expression_pregrammar string_stringlike).\n  Proof.\n\n    Time start sharpening ADT.\n\n    Reset Ltac Profile.\n    Time start honing parser using indexed representation.\n    Show Ltac Profile.\n\n    Reset Ltac Profile.\n    Time hone method \"splits\".\n    Show Ltac Profile.\n    {\n      Reset Ltac Profile.\n      Time simplify parser splitter.\n      Show Ltac Profile.\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* = *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for *= \\s* ... N.B. This is different, requires 2-char binop *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* = *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for *= \\s* ... N.B. This is different, requires 2-char binop *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* = *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for *= \\s* ... N.B. This is different, requires 2-char binop *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* = *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for *= \\s* ... N.B. This is different, requires 2-char binop *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* & *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* & *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* & *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* binop search for ... \\s* & *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for = \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for = \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for = \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for = \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for < \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true instanceof Boolean instanceof new \"instanceof\"] and [true instanceof Boolean instanceof new instanceof] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for < \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true instanceof Boolean instanceof new \"instanceof\"] and [true instanceof Boolean instanceof new instanceof] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for < \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true instanceof Boolean instanceof new \"instanceof\"] and [true instanceof Boolean instanceof new instanceof] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true in Object in new \"in\"] and [true in Object in new in] (invalid parse) *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for < \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true instanceof Boolean instanceof new \"instanceof\"] and [true instanceof Boolean instanceof new instanceof] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ??? wtf [true in Object in new \"in\"] and [true in Object in new in] (invalid parse) *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for + \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for + \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for * \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for * \\s* ... *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ++ *) }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ++ *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ) *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ???  \"[]. a . a\", \"[]. a [ [] + [] ]\" *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse paren search for \\s* (...) N.B. this requires 0-char binops *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse paren search for \\s* (...) N.B. this requires 0-char binops *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ???  \"[]. a . a\", \"[]. a [ [] + [] ]\" *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse paren search for \\s* (...) N.B. this requires 0-char binops *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* ???  \"[]. a . a\", \"[]. a [ [] + [] ]\" *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse paren search for \\s* (...) N.B. this requires 0-char binops *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... *) }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ] *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse binop search for , \\s* ... (hopefully?) *) }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* } *) }\n      { Time shelve; refine_disjoint_search_for. }\n      { exfalso; admit. (* reverse disjoint + fixed length for ... \\s* ) *) }\n      { Time shelve; refine_disjoint_search_for. }\n      (*{ Time Import ExplorationUtil.\n        pose javascript_assignment_expression_pregrammar as G.\n        print_production javascript_assignment_expression_pregrammar (4, (0, 1)).\n        print_productions G \"LiteralField\".\n        print_productions G \"LiteralElement\".\n        print_productions G \"AssignmentExpression normal,allowIn\".\n        print_productions G \"MemberOperator\".\n        print_productions G \"CallExpression initial\".\n        print_productions G \"ShortNewSubexpression\".\n        print_productions G \"Arguments\".\n        print_productions G \"FullNewSubexpression\".\n        print_productions G \"FullNewSubexpression\".\n        print_productions G \"PrimaryExpression normal\".\n        print_productions G \"MemberOperator\".\n        print_chars \"MemberOperator\".\n        print_productions G \"ArgumentList\".\n        print_last_chars \"PostfixExpression normal\".\n        print_productions G \"RelationalExpression initial,noIn\".\n        print_productions G \"AdditiveExpression normal\".\n        print_productions G \"MultiplicativeExpression normal\".\n        print_productions G \"UnaryExpression normal\".\n        print_productions G \"PostfixExpression normal\".\n        print_productions G \"LeftSideExpression normal\".\n        print_productions G \"ShortNewExpression\".\n        print_productions G \"Arguments\".\n        print_productions G \"ShortNewSubexpression\".\n        print_productions G \"FullNewSubexpression\".\n        print_productions G \"PrimaryExpression normal\".\n        print_productions G \"SimpleExpression\".\n        print_productions G \"ObjectLiteral\".\n        print_productions G \"Identifier\".\n        print_productions G \"CallExpression normal\"\n        print_productions G \"SimpleExpression\".\n        print_productions G \"AssignmentExpression normal,noIn\".\n        print_chars \"CompoundAssignment\".\n        print_productions javascript_assignment_expression_pregrammar \"Expression initial,noIn\".\n        print_productions G \"AssignmentExpression normal,noIn\".\n        print_productions javascript_assignment_expression_pregrammar \"LeftSideExpression normal\".\n        print_productions javascript_assignment_expression_pregrammar \"AssignmentExpression normal,allowIn\".\n        print_productions G \"CompoundAssignment\".*)\n      (*{ Require Import ExplorationUtil.\n        print_production javascript_assignment_expression_pregrammar (4, (0, 2)).\nprint_productions javascript_assignment_expression_pregrammar \"LiteralField\". (*\"MemberOperator\". *)\n        pose javascript_assignment_expression_pregrammar as G.\n        print_productions javascript_assignment_expression_pregrammar \"LeftSideExpression normal\".\n        print_productions javascript_assignment_expression_pregrammar \"AssignmentExpression normal,allowIn\".\n        print_productions G \"CompoundAssignment\".*)\n\n      simplify parser splitter.\n      Show Ltac Profile.\n      (*\ntotal time:     84.328s\n\n tactic                                    self  total   calls       max\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\u2500rewrite_disjoint_search_for -----------   0.0%  39.4%      20    4.268s\n\u2500rewrite_disjoint_search_for_no_clear --   0.0%  39.3%      20    4.260s\n\u2500rewrite_once_disjoint_search_for ------   0.0%  38.8%      40    4.240s\n\u2500rewrite_once_disjoint_search_for_specia  33.6%  38.3%      40    4.212s\n\u2500refine_binop_table --------------------   0.0%  37.9%       4    8.036s\n\u2500setoid_rewrite_refine_binop_table_idx -  37.0%  37.9%       4    8.032s\n\u2500simplify parser splitter --------------   0.0%  18.7%       2   14.980s\n\u2500simplify_parser_splitter' -------------   0.0%  18.7%      31   12.444s\n\u2500simplify ------------------------------   0.0%  18.7%       2   14.980s\n\u2500eapply (refine_opt2_fold_right r_o retv  13.5%  13.5%       1   11.364s\n\u2500simplify with monad laws --------------   0.0%   4.4%      30    1.900s\n\u2500simplify_with_applied_monad_laws ------   0.0%   4.4%      30    1.900s\n\u2500rewrite_disjoint_rev_search_for -------   0.0%   3.9%       2    1.636s\n\u2500rewrite_disjoint_rev_search_for_no_clea   0.0%   3.8%       2    1.632s\n\u2500rewrite_once_disjoint_rev_search_for --   0.0%   3.8%       4    1.608s\n\u2500rewrite_once_disjoint_rev_search_for_sp   3.4%   3.7%       4    1.572s\n\u2500specialize (lem' H') ------------------   2.7%   2.7%      44    1.996s\n\n tactic                                    self  total   calls       max\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n\u2500rewrite_disjoint_search_for -----------   0.0%  39.4%      20    4.268s\n\u2514rewrite_disjoint_search_for_no_clear --   0.0%  39.3%      20    4.260s\n\u2514rewrite_once_disjoint_search_for ------   0.0%  38.8%      40    4.240s\n\u2514rewrite_once_disjoint_search_for_specia  33.6%  38.3%      40    4.212s\n\u2514specialize (lem' H') ------------------   2.6%   2.6%      40    1.996s\n\u2500refine_binop_table --------------------   0.0%  37.9%       4    8.036s\n\u2514setoid_rewrite_refine_binop_table_idx -  37.0%  37.9%       4    8.032s\n\u2500simplify parser splitter --------------   0.0%  18.7%       2   14.980s\n\u2514simplify ------------------------------   0.0%  18.7%       2   14.980s\n\u2514simplify_parser_splitter' -------------   0.0%  18.7%      31   12.444s\n \u251c\u2500eapply (refine_opt2_fold_right r_o re  13.5%  13.5%       1   11.364s\n \u2514\u2500simplify with monad laws ------------   0.0%   4.4%      30    1.900s\n  \u2514simplify_with_applied_monad_laws ----   0.0%   4.4%      30    1.900s\n\u2500rewrite_disjoint_rev_search_for -------   0.0%   3.9%       2    1.636s\n\u2514rewrite_disjoint_rev_search_for_no_clea   0.0%   3.8%       2    1.632s\n\u2514rewrite_once_disjoint_rev_search_for --   0.0%   3.8%       4    1.608s\n\u2514rewrite_once_disjoint_rev_search_for_sp   3.4%   3.7%       4    1.572s\n *)\n      Time finish honing parser method.\n    }\n\n    Time finish_Sharpening_SplitterADT.\n\n  Time Defined. (* 85 seconds *)\n\n  Lemma ComputationalSplitter\n  : FullySharpened (string_spec json'_grammar string_stringlike).\n  Proof.\n    Reset Ltac Profile.\n    Time make_simplified_splitter ComputationalSplitter'. (* 19 s *)\n    Show Ltac Profile.\n  Time Defined.\n\nTime End IndexedImpl.\n\nRequire Export Fiat.Parsers.ParserFromParserADT.\nRequire Export Fiat.Parsers.ExtrOcamlParsers.\nExport Fiat.Parsers.ExtrOcamlParsers.HideProofs.\nRequire Export Fiat.Parsers.StringLike.OcamlString.\n\nDefinition json_parser (str : Coq.Strings.String.string) : bool.\nProof.\n  Reset Ltac Profiling.\n  Time make_parser (@ComputationalSplitter(* _ String.string_stringlike _ _*)). (* 75 seconds *)\n  Show Ltac Profile.\nTime Defined.\n\n(*Definition json_parser_ocaml (str : Ocaml.Ocaml.string) : bool.\nProof.\n  Time make_parser (@ComputationalSplitter _ Ocaml.string_stringlike _ _). (* 0.82 s *)\nDefined.*)\n\nPrint json_parser(*_ocaml*).\n\nRecursive Extraction json_parser(*_ocaml*).\n(*\nDefinition main_json := premain json_parser.\nDefinition main_json_ocaml := premain_ocaml json_parser_ocaml.\n\nParameter reference_json_parser : Coq.Strings.String.string -> bool.\nParameter reference_json_parser_ocaml : Ocaml.Ocaml.string -> bool.\nExtract Constant reference_json_parser\n=> \"fun str ->\n  let needs_b : bool Pervasives.ref = Pervasives.ref false in\n  try\n    (List.iter (fun ch ->\n       match ch, !needs_b with\n       | 'a', false -> needs_b := true; ()\n       | 'b', true  -> needs_b := false; ()\n       | _, _       -> raise Not_found)\n       str;\n     if !needs_b then false else true)\n  with\n   | Not_found -> false\".\nExtract Constant reference_json_parser_ocaml\n=> \"fun str ->\n  let needs_b : bool Pervasives.ref = Pervasives.ref false in\n  try\n    (String.iter (fun ch ->\n       match ch, !needs_b with\n       | 'a', false -> needs_b := true; ()\n       | 'b', true  -> needs_b := false; ()\n       | _, _       -> raise Not_found)\n       str;\n     if !needs_b then false else true)\n  with\n   | Not_found -> false\".\n\nDefinition main_json_reference := premain reference_json_parser.\nDefinition main_json_reference_ocaml := premain_ocaml reference_json_parser_ocaml.\n\n(*\n(* val needs_b : bool Pervasives.ref;; *)\nlet needs_b = Pervasives.ref false;;\n\nlet chan = match Array.length Sys.argv with\n| 0 | 1 -> Pervasives.stdin\n| 2 -> let chan = Pervasives.open_in Sys.argv.(1)\n       in Pervasives.at_exit (fun () -> Pervasives.close_in chan);\n\t  chan\n| argc -> Pervasives.exit argc;;\n\n(* val line : string;; *)\nlet line = Pervasives.input_line chan;;\n\nString.iter (fun ch ->\n  match ch, !needs_b with\n  | 'a', false -> needs_b := true; ()\n  | 'b', true  -> needs_b := false; ()\n  | _, _       -> Pervasives.exit 1)\n  line;;\n\nPervasives.exit 0;;\n*)\n(*\nDefinition test0 := json_parser \"\".\nDefinition test1 := json_parser \"ab\".\nDefinition str400 := \"abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab\".\nDefinition test2 := json_parser (str400 ++ str400 ++ str400 ++ str400).\n\nRecursive Extraction test0 test1 test2.\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/Parsers/Refinement/SharpenedJavaScriptAssignmentExpression.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18022749312139755}}
{"text": "Load \"frame3\".\n(*\n(** * Frame [phi4] *)\nDefinition mphi3ttt n1 n2 := (phi2tt n1) ++ [msg ((pk 2), ( (e (b n2 19) 20),  (sign (sk 2) (e (b n2 19) 20))))].\nDefinition x4ttt n1 n2 := (f (conv_mylist_listm (mphi3ttt n1 n2))). \nDefinition phi3ttft n1  := (phi2tt n1) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1  (x3tt n1 ))))),  (bsign (sk 3)  (pi1 (pi2 (pi2  (x3tt n1 ))))))].\nDefinition x4ttft n1 := (f (conv_mylist_listm (phi3ttft n1))).\n\nDefinition phi3tftt n1 n2 := (phi2tft n1 n2) ++ [msg ok].\nDefinition x4tftt n1 n2 := (f (conv_mylist_listm (phi3tftt n1 n2))).\n\nDefinition phi3tftft n1 n2 := (phi2tft n1 n2) ++ [msg ok].\nDefinition x4tftft n1 n2 := (f (conv_mylist_listm (phi3tftft n1 n2))).\n\nDefinition phi3tftfft n1 n2 := (phi2tft n1 n2) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1 (x3tft n1 n2))))),  (bsign (sk 3)  (pi1 (pi2 (pi2 (x3tft n1 n2))))))].\nDefinition x4tftfft n1 n2 := (f (conv_mylist_listm (phi3tftfft n1 n2))).\nDefinition phi3tfftt n1  := (phi2tfft n1) ++ [msg ok].\nDefinition x4tfftt n1  := (f (conv_mylist_listm (phi3tfftt n1))).\n\nDefinition phi3tfftft n1 n2 := (phi2tfft n1) ++ [msg ((pk 2), ( (e (b n2 21) 22),  (sign (sk 2) (e (b n2 21) 22))))].\nDefinition x4tfftft n1 n2 := (f (conv_mylist_listm (phi3tfftft n1 n2))).\nDefinition phi3fttt n1 n2 := (phi2ftt n2) ++ [msg  ((pk 1), ( (e (b n1 23) 24),  (sign (sk 1) (e (b n1 23) 24))))].\n\nDefinition x4fttt n1 n2 := (f (conv_mylist_listm (phi3fttt n1 n2))).\nDefinition phi3fttft  n2 := (phi2ftt n2) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1 (x3ftt n2 ))))),  (bsign (sk 3)  (pi1 (pi2 (pi2 (x3ftt n2 ))))))].\n\nDefinition x4fttft n2 := (f (conv_mylist_listm (phi3fttft n2))).\nDefinition phi3ftftt n1 n2:= (phi2ftft n1 n2) ++ [msg ok].\nDefinition x4ftftt n1 n2 := (f (conv_mylist_listm (phi3ftftt n1 n2))).\nDefinition phi3ftftft n1 n2:= (phi2ftft n1 n2) ++ [msg ok].\nDefinition x4ftftft n1 n2 := (f (conv_mylist_listm (phi3ftftft n1 n2))).\nDefinition phi3ftftfft n1 n2:= (phi2ftft n1 n2) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1 (x3ftft n1 n2))))),  (bsign (sk 3)  (pi1 (pi2 (pi2 (x3ftft n1 n2))))))].\nDefinition x4ftftfft n1 n2 := (f (conv_mylist_listm (phi3tftft n1 n2))).\nDefinition phi3ftfftt  n2 := (phi2ftfft n2) ++ [msg ok].\nDefinition x4ftfftt n2 := (f (conv_mylist_listm (phi3ftfftt n2))).\n\nDefinition phi3ftfftft n1 n2 := (phi2ftfft n2) ++ [msg ((pk 1), ( (e (b n1 25) 26),  (sign (sk 1) (e (b n1 25) 26))))].\n\nDefinition x4ftfftft n1 n2 := (f (conv_mylist_listm (phi3ftfftft n1 n2))).\n\nDefinition phi3ffttt n1  := (phi2fftt n1) ++ [msg ok].\nDefinition x4ffttt n1 := (f (conv_mylist_listm (phi3ffttt n1))).\n\nDefinition phi3ffttft n1 n2 := (phi2fftt n1) ++ [msg ((pk 2), ( (e (b n2 27) 28),  (sign (sk 2) (e (b n2 27) 28))))].\nDefinition x4ffttft n1 n2 := (f (conv_mylist_listm (phi3ffttft n1 n2))).\n\nDefinition phi3fftftt  n2 := (phi2fftft n2) ++ [msg ok].\n\nDefinition x4fftftt n2 := (f (conv_mylist_listm (phi3fftftt n2))).\nDefinition phi3fftftft n1 n2 := (phi2fftft n2) ++ [msg  ((pk 1), ( (e (b n1 29) 30),  (sign (sk 1) (e (b n1 29) 30))))].\nDefinition x4fftftft n1 n2 := (f (conv_mylist_listm (phi3fftftft n1 n2))).\n(************************************************************************************************************************)\nDefinition mphi3 n1 n2 := (conv_mylist_listm (phi3 n1 n2)).\nDefinition x4 n1 n2 := (f (mphi3 n1 n2)). \n  \nDefinition q111 n1 n2 := (ifm  (eqm (to (x4ttt n1 n2)) (V 2))& (bacc (pk 3) (b n2 19) (r 20) (pi2 (x4ttt n1 n2))) ok\n                                     (admin (x4ttt n1 n2))).\n \nDefinition q112 n1 := (ifm  (eqm (to (x4ttft n1)) (V 2))  ((pk 2), ( (e (b n1 31) 32),  (sign (sk 2) (e (b n1 31) 32)))) O).\n \n (*************************************************)                       \n\n  \nDefinition q121 n1 n2 := (ifm (eqm (to (x4tftt n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 11) (r 12) (pi2 (x4tftt n1 n2))) ok\n                         (admin (x4tftt n1 n2))).\n\nDefinition q122 n1 n2 := (ifm (eqm (to (x4tftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x4tftft n1 n2))) ok\n                         (admin (x4tftft n1 n2))).\n \nDefinition  q123 n1 n2 := (ifm (eqm (to (x4tftfft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x4tftfft n1 n2))) ok\n                          (ifm (eqm (to (x4tftfft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 11) (r 12) (pi2 (x4tftfft n1 n2))) ok\n                               O)).\n(****************************************************)\n\nDefinition q131 n1 n2 := (ifm  (eqm (to (x4tfftt n1 )) (V 2))  ((pk 2), ( (e (b n2 33) 34),  (sign (sk 2) (e (b n2 33) 34)))) O).\n \nDefinition q132  n1 n2:=  (ifm (eqm (to (x4tfftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x4tfftft n1 n2))) ok\n                          (ifm (eqm (to (x4tfftft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 21) (r 22) (pi2 (x4tfftft n1 n2))) ok\n                               O)).\n(****************************************************)\n \nDefinition q211 n1 n2 :=  (ifm (eqm (to (x4fttt n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 23) (r 24) (pi1 (x4fttt n1 n2))) ok\n                          (admin (x4fttt n1 n2))).\n\nDefinition q212  n2 :=  (ifm  (eqm (to (x4fttft n2)) (V 2))  ((pk 2), ( (e (b n2 35) 36),  (sign (sk 2) (e (b n2 35) 36)))) O).\n\n\n(***************************************************)\n\nDefinition q221 n1 n2:=   (ifm (eqm (to (x4ftftt n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x4ftftt n1 n2))) ok\n                           (admin (x4ftftt n1 n2))).\nDefinition q222 n1 n2 :=  (ifm (eqm (to (x4ftftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 13) (r 14) (pi1 (x4ftftft n1 n2))) ok                               (admin (x4ftftft n1 n2))).\nDefinition q223 n1 n2 := (ifm (eqm (to (x4ftftfft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 13) (r 14) (pi1 (x4ftftfft n1 n2))) ok\n                         (ifm (eqm (to (x4ftftfft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x4ftftfft n1 n2))) ok\n                              O)).\n\n(***************************************************)\n\nDefinition q231 n1 n2 := (ifm (eqm (to (x4ftfftt n2)) (V 1))  ((pk 1), ( (e (b n1 37) 38),  (sign (sk 2) (e (b n1 37) 38)))) O).\n \nDefinition q232 n1 n2 := (ifm (eqm (to (x4ftfftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 25) (r 26) (pi1 (x2 n1 n2))) ok\n\n                              (ifm (eqm (to (x4ftfftft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x2 n1 n2))) ok\n                               O)).\n(***************************************************)\n\nDefinition q311  n1 n2 := (ifm  (eqm (to (x4ffttt n1 )) (V 2))  ((pk 2), ( (e (b n2 39) 40),  (sign (sk 2) (e (b n2 39) 40))))\n                                                    O).\nDefinition q312 n1 n2  :=  (ifm (eqm (to (x4ffttft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 15) (r 16) (pi1 (x4ffttft n1 n2))) ok\n                          (ifm (eqm (to (x4ffttft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 27) (r 28) (pi2 (x4ffttft n1 n2))) ok\n                               O)).\n\n(****************************************)\n\nDefinition q321  n1 n2 := (ifm  (eqm (to (x4fftftt n2)) (V 1))  ((pk 1), ( (e (b n1 41) 42),  (sign (sk 1) (e (b n1 41) 42)))) O).\n\nDefinition q322 n1 n2 :=  (ifm (eqm (to (x4fftftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 29) (r 30) (pi1 (x4fftftft n1 n2))) ok\n                          (ifm (eqm (to (x4fftftft n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 17) (r 18) (pi2 (x4fftftft n1 n2))) ok\n                               O)).\n\n(*****************************************)\n  \nDefinition q11_s n1 n2 :=  (ifm  (eqm (to (x3tt n1 )) (V 2)) (q111 n1 n2)\n                                      (ifm (achecks (x3tt n1 )) (q112 n1 )  O)).\n \nDefinition q12_s n1 n2 := (ifm (eqm (to (x3tft n1 n2)) (V 1))& (bacc (pk 3) (b n1 7) (r 8) (pi2 (x3tft n1 n2))) (q121 n1 n2)\n                                    (ifm (eqm (to (x3tft n1 n2)) (V 2))& (bacc (pk 3) (b n2 11) (r 12) (pi2 (x3tft n1 n2))) (q122 n1 n2)\n                                                    (ifm (achecks (x3tft n1 n2)) (q123 n1 n2) O))).\n \nDefinition q13_s n1 n2 := (ifm (eqm (to (x3tfft n1 )) (V 1))& (bacc (pk 3) (b n1 7) (r 8) (pi2 (x3tfft n1 ))) (q131 n1 n2)\n                                    (ifm  (eqm (to (x3tfft n1 )) (V 2)) (q132 n1 n2) O)).\n\n\nDefinition q21_s n1 n2 := (ifm  (eqm (to (x3ftt n2)) (V 1))  (q211 n1 n2)\n                                   (ifm (achecks (x3ftt n2)) (q212  n2) O)).\n\nDefinition q22_s n1 n2  := (ifm (eqm (to (x3ftft n1 n2)) (V 1))& (bacc (pk 3) (b n1 13) (r 14) (pi1 (x3ftft n1 n2))) (q221 n1 n2)\n                                    (ifm (eqm (to (x3ftft n1 n2)) (V 2))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x3ftft n1 n2))) (q222 n1 n2)\n                                                   (ifm (achecks (x3ftft n1 n2)) (q223 n1 n2) O))).\n \nDefinition q23_s n1 n2 := (ifm (eqm (to (x3ftfft  n2)) (V 2))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x3ftfft n2))) (q231 n1 n2)\n                        (ifm  (eqm (to (x3ftfft  n2)) (V 1))  (q232 n1 n2) O)).\n\n \nDefinition q31_s n1 n2 := (ifm (eqm (to (x3fftt n1 )) (V 1))& (bacc (pk 3) (b n1 15) (r 16) (pi1 (x3fftt n1 ))) (q311 n1 n2)\n                                    (ifm  (eqm (to (x3fftt n1 )) (V 2))  (q312 n1 n2) O)).\n\nDefinition q32_s n1 n2 := (ifm (eqm (to (x3fftft  n2)) (V 2))& (bacc (pk 3) (b n2 17) (r 18) (pi2 (x3fftft n2))) (q321 n1 n2)\n                                    (ifm  (eqm (to (x3fftft  n2)) (V 1)) (q322 n1 n2) O)).\n(********************************************************************************************)\n\nDefinition q1_ss n1 n2 := (ifm (eqm (to (x2t n1 )) (V 1))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x2t n1 )))  (q11_s n1 n2)\n\t\t\t           (ifm (eqm (to (x2t n1 )) (V 2))  (q12_s n1 n2)\n                                                  (ifm (achecks (x2t n1 )) (q13_s n1 n2) O))).\n \nDefinition q2_ss n1 n2 :=  (ifm (eqm (to (x2ft n2)) (V 2))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x2ft n2)))  (q21_s n1 n2)\n\t\t\t           (ifm (eqm (to (x2ft n2)) (V 1))  (q22_s n1 n2)\n                                                   (ifm (achecks (x2ft n2)) (q23_s n1 n2) O))).\n \nDefinition q3_ss n1 n2 := (ifm (eqm (to (x2fft)) (V 1)) (q31_s n1 n2)\n\t\t    \t            (ifm  (eqm (to (x2fft )) (V 2))  (q32_s n1 n2) O)).\n\n\nDefinition t3 n1 n2 :=  (ifm (eqm (to x1) (V 1)) (q1_ss n1 n2)\n\t\t    \t           (ifm (eqm (to x1) (V 2))  (q2_ss n1 n2)\n                                                   (ifm (achecks x1) (q3_ss n1 n2)\n                                                                   O))).\n\nDefinition phi4 n1 n2 := (phi3 n1 n2) ++ [msg (t3 n1 n2)] .\n\n(*\n\nTheorem frame4ind : (phi4 0 1) ~ (phi4 1 0).\nProof.  unfold phi4, phi3. unfold t2, t3. simpl.\n        unfold q1_s, q2_s, q3_s. unfold q1_ss, q2_ss, q3_ss.\n        repeat unf.\nrepeat unfold admin, achecks.\n  ufcma_pi1 x1.  \nufcma_pi1 (x2t 0).\nufcma_pi2 (x2t 0).\nufcma_pi1 (x2ft 1). \nufcma_pi2 (x2ft 0). \nufcma_pi1 (x2t 1).\nufcma_pi2 (x2t 1).\nufcma_pi1 (x2ft 0). \nrepeat aply_andB_elm.   \nrepeat (rew_mupbver;aply_bver; rew_hyps; try split; try reflexivity).\n\nrepeat unfold q11_s, q21_s. repeat unf.  unfold q12_s, q22_s.\nrepeat unfold q111, q112, q121, q122, q123, q121, q132, q211, q212, q221, q222, q223, q231, q232, q311, q312, q321, q322; repeat unfold q11, q12, q13, q21, q22, q23, q31, q32. repeat unf.\nrepeat unfold admin, achecks.  \nufcma_pi1 (x3ftft 0 1);\nufcma_pi2 (x3ftft 0 1);\nufcma_pi1 (x3ftft 1 0);\nufcma_pi2 (x3ftft 1 0).\nLtac unforge x1 n1 n2:=\n  ufcma_pi1 (x1 n1 n2); ufcma_pi2 (x1 n1 n2);   ufcma_pi1 (x1 n2 n1);   ufcma_pi2 (x1 n2 n1).\nunforge x3tft 0 1 .\nunforge x4tftft 0 1. \nunforge x4ftftt 0 1.\napply IFBRANCH_M4 with (ml1:= (phi0)) (ml2:= phi0).\nsimpl.\nrepeat aply_andB_elm.\n\napply IFBRANCH_M3 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)))]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)))]).\nsimpl.\napply IFBRANCH_M2 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)))]).\nsimpl. \nrepeat (rew_mupbver;aply_bver; rew_hyps; try split; try reflexivity).\n  aply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 1 0 1 7 8 H;\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x2t 0 ) (x2t 1) H.\nx1checks (x3tft 0 1) (x3tft 1 0) H. \nadminchecks (x3tft 0 1) (x3tft 1 0) H. \nLtac ver_suc1 n x1 e1 x2 e2 H:=\n  funapptrmhyp (bol (eqm (pi1 (pi2 x1)) e1)) (bol (eqm (pi1 (pi2 x2)) e2)) H;\n  funapptrmhyp (bol  (ver (pk n) e1 (pi2 (pi2 x1))))  (bol (ver (pk n) e2 (pi2 (pi2 x2)))) H.\n \nver_suc1 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\n  funapptrmhyp (msg (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O)) (msg    (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O)) H.\n  funapptrmhyp (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12)) (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))  (ifm (ver (pk 2) (e (b 0 11) 12) (pi2 (pi2 (pi2 (x3tft 1 0))))) (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                                                                                                                                                                                                         bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O)) H.\n\n  ver_suc1 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\n  funapptrmhyp (msg  (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O)) (msg  (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O)) H.\nfunapptrmhyp (msg   (ifm (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n            (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n            (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O) O)) H.\n\nfunapptrmhyp  (msg\n      (ifm (eqm (to (x3tft 0 1)) (pk 3))\n         (ifm (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n            (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O) O)\n         O))  (msg\n     (ifm (eqm (to (x3tft 1 0)) (pk 3))\n        (ifm (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n           (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n              (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                 (ifm\n                    (ver (pk 2) (e (b 0 11) 12) (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                    (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O) O) O)) H.\n\nrestrsublis H.\n(** subgoal *)\nsimpl.\napply IFBRANCH_M2 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)));\n    bol (eqm (to (x3tft 0 1)) (V 1))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)));\n   bol (eqm (to (x3tft 1 0)) (V 1))]). simpl.\nrepeat (rew_mupbver;aply_bver; rew_hyps; try split; try reflexivity).\n\n aply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 1 0 1 7 8 H;\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x2t 0 ) (x2t 1) H.\nx1checks (x3tft 0 1) (x3tft 1 0) H. \nadminchecks (x3tft 0 1) (x3tft 1 0) H. \n \nver_suc1 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\n  funapptrmhyp (msg (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O)) (msg    (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O)) H.\n  funapptrmhyp (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12)) (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))  (ifm (ver (pk 2) (e (b 0 11) 12) (pi2 (pi2 (pi2 (x3tft 1 0))))) (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                                                                                                                                                                                                         bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O)) H.\n\n  ver_suc1 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\n  funapptrmhyp (msg  (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O)) (msg  (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O)) H.\nfunapptrmhyp (msg   (ifm (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n            (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n            (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O) O)) H.\n\nfunapptrmhyp  (msg\n      (ifm (eqm (to (x3tft 0 1)) (pk 3))\n         (ifm (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n            (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O) O)\n         O))  (msg\n     (ifm (eqm (to (x3tft 1 0)) (pk 3))\n        (ifm (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n           (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n              (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                 (ifm\n                    (ver (pk 2) (e (b 0 11) 12) (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                    (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O) O) O)) H.\n\nrestrsublis H.\n(** subgoal *)\n\nsimpl.\napply IFBRANCH_M2 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)));\n    bol (eqm (to (x3tft 0 1)) (V 1)); bol (eqm (to (x3tft 0 1)) (V 2))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)));\n   bol (eqm (to (x3tft 1 0)) (V 1)); bol (eqm (to (x3tft 1 0)) (V 2))]). simpl.\nrepeat (rew_mupbver;aply_bver; rew_hyps; try split; try reflexivity).\n aply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 1 0 1 7 8 H;\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x2t 0 ) (x2t 1) H.\nx1checks (x3tft 0 1) (x3tft 1 0) H. \nadminchecks (x3tft 0 1) (x3tft 1 0) H. \n \nver_suc1 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\n  funapptrmhyp (msg (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O)) (msg    (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O)) H.\n  funapptrmhyp (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12)) (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))  (ifm (ver (pk 2) (e (b 0 11) 12) (pi2 (pi2 (pi2 (x3tft 1 0))))) (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                                                                                                                                                                                                         bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O)) H.\n\n  ver_suc1 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\n  funapptrmhyp (msg  (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O)) (msg  (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O)) H.\nfunapptrmhyp (msg   (ifm (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n            (ifm (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 0 1)))) (e (b 1 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 1 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 0 1))))) O) O) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n            (ifm (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3tft 1 0)))) (e (b 0 11) 12))\n                  (ifm\n                     (ver (pk 2) (e (b 0 11) 12)\n                        (pi2 (pi2 (pi2 (x3tft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3tft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3tft 1 0))))) O) O) O) O)) H.\nrestrsublis H.\n(** subgoal *)\n\n  (aply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 1 0 1 7 8 H;\nfunapp_vtrm 2 1 0 11 12 H;\nx1checks (x2t 0 ) (x2t 1) H;\nx1checks (x3tft 0 1) (x3tft 1 0) H;\nrestrsublis H).\n aply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 1 0 1 7 8 H;\nfunapp_vtrm 2 1 0 11 12 H;\nx1checks (x2t 0 ) (x2t 1) H;\nx1checks (x3tft 0 1) (x3tft 1 0) H;\nrestrsublis H.\n (** subgoal *)\n simpl.\n apply IFBRANCH_M4 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                             msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1))]). simpl.\n apply IFBRANCH_M3 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n    bol (eqm (to x1) (V 2));\n    msg (pk 2, (e (b 1 9) 10, sign (sk 2) (e (b 1 9) 10)))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n   bol (eqm (to x1) (V 2));\n   msg (pk 2, (e (b 0 9) 10, sign (sk 2) (e (b 0 9) 10)))]). simpl.\n repeat aply_andB_elm.\n repeat (rew_mupbver;aply_bver; rew_hyps; try split; try reflexivity).\n \n aply_blindness 3 10 14 0 1 (b 1 9) (b 0 13)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity.\nrep_commits 1 0 13 30 9 31 fr1 fr2 temp H H0.\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nfunapp_vtrm 1 0 1 13 14 H.\nx1checks (x2ft 1) (x2ft 0) H.\nx1checks (x3ftft 0 1) (x3ftft 1 0) H. \nadminchecks (x3ftft 0 1) (x3ftft 1 0) H. \n \nver_suc1 2 (pi2 (x3ftft 0 1)) (e (b 1 9) 10) (pi2 (x3ftft 1 0)) (e (b 0 9) 10) H.\n  funapptrmhyp (msg (ifm\n                     (ver (pk 2) (e (b 1 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 0 1))))) O))  (msg    (ifm\n                     (ver (pk 2) (e (b 0 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 1 0)))),\n                      bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 1 0))))) O)) H.\n   funapptrmhyp (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 0 1)))) (e (b 1 9) 10)) (ifm\n                     (ver (pk 2) (e (b 1 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 0 1))))) O) O)) (msg  (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 1 0)))) (e (b 0 9) 10))  (ifm (ver (pk 2) (e (b 0 9) 10) (pi2 (pi2 (pi2 (x3ftft 1 0))))) (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 1 0)))),\n                                                                                                                                                                                                         bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 1 0))))) O) O)) H.\n\n   ver_suc1 1 (pi1 (x3ftft 0 1)) (e (b 0 13) 14) (pi1 (x3ftft 1 0)) (e (b 1 13) 14) H.\n\n funapptrmhyp (msg  (ifm (ver (pk 1) (e (b 0 13) 14) (pi2 (pi2 (pi1 (x3ftft 0 1))))) (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 0 1)))) (e (b 1 9) 10)) (ifm\n                     (ver (pk 2) (e (b 1 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 0 1))))) O) O) O)) (msg (ifm (ver (pk 1) (e (b 1 13) 14) (pi2 (pi2 (pi1 (x3ftft 1 0)))))  (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 1 0)))) (e (b 0 9) 10))  (ifm (ver (pk 2) (e (b 0 9) 10) (pi2 (pi2 (pi2 (x3ftft 1 0))))) (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 1 0)))),\n                                                                                                                                                                                                         bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 1 0))))) O) O) O)) H.\n   funapptrmhyp  (msg\n              (ifm (eqm (pi1 (pi2 (pi1 (x3ftft 0 1)))) (e (b 0 13) 14))\n            (ifm (ver (pk 1) (e (b 0 13) 14) (pi2 (pi2 (pi1 (x3ftft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 0 1)))) (e (b 1 9) 10))\n                  (ifm\n                     (ver (pk 2) (e (b 1 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 0 1))))) O) O) O) O))\n           (msg\n               (ifm (eqm (pi1 (pi2 (pi1 (x3ftft 1 0)))) (e (b 1 13) 14))\n            (ifm (ver (pk 1) (e (b 1 13) 14) (pi2 (pi2 (pi1 (x3ftft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 1 0)))) (e (b 0 9) 10))\n                  (ifm\n                     (ver (pk 2) (e (b 0 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 1 0)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 1 0))))) O) O) O) O))\n          H.\n  funapptrmhyp  (msg\n      (ifm (eqm (to (x3ftft 0 1)) (pk 3)) \n         (ifm (eqm (pi1 (pi2 (pi1 (x3ftft 0 1)))) (e (b 0 13) 14))\n            (ifm (ver (pk 1) (e (b 0 13) 14) (pi2 (pi2 (pi1 (x3ftft 0 1)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 0 1)))) (e (b 1 9) 10))\n                  (ifm\n                     (ver (pk 2) (e (b 1 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 0 1)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 0 1)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 0 1))))) O) O) O) O)\n         O))   (msg\n      (ifm (eqm (to (x3ftft 1 0)) (pk 3))\n         (ifm (eqm (pi1 (pi2 (pi1 (x3ftft 1 0)))) (e (b 1 13) 14))\n            (ifm (ver (pk 1) (e (b 1 13) 14) (pi2 (pi2 (pi1 (x3ftft 1 0)))))\n               (ifm (eqm (pi1 (pi2 (pi2 (x3ftft 1 0)))) (e (b 0 9) 10))\n                  (ifm\n                     (ver (pk 2) (e (b 0 9) 10)\n                        (pi2 (pi2 (pi2 (x3ftft 1 0)))))\n                     (bsign (sk 3) (pi1 (pi2 (pi1 (x3ftft 1 0)))),\n                     bsign (sk 3) (pi1 (pi2 (pi2 (x3ftft 1 0))))) O) O) O) O)\n         O)) H.\n  restrsublis H.\n(** subgoal *)\n  simpl.\naply_blindness 3 10 11 0 1 (b 1 9) (b 0 9)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 2 15 H; try split; try reflexivity;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nx1checks (x2ft 1 ) (x2ft 0) H;\nrestrsublis H.\nreflexivity.\nQed. *)\n\nEnd foo_prot2. *)\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/frame4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.2877678035446343, "lm_q1q2_score": 0.18017838324240773}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Coq.Arith.Arith\n        Coq.Program.Program\n        Fiat.ADT\n        Fiat.ADT.ComputationalADT\n        Fiat.ADTNotation\n        Fiat.ADTRefinement\n        Fiat.ADTRefinement.BuildADTRefinements\n        Fiat.Fiat4Monitors.RADL_Topics\n        Fiat.Fiat4Monitors.RADL_Messages\n        Fiat.Fiat4Monitors.RADL_Flags.\n\nSection RADL_ADT.\n\n  Open Scope ADT_scope.\n  Open Scope string_scope.\n  Open Scope list_scope.\n  Open Scope ADTSig_scope.\n\n  Definition RADL_Init := \"Init\".\n  Definition RADL_Step := \"Step\".\n\n  Context {n : nat}.\n  Variable TopicTypes : Vector.t Type n. (* List of Topics in the Network. *)\n  Variable TopicNames : Vector.t string n. (* List of Topics IDs in the Network. *)\n\n  Record RADL_Node :=\n    { (* Subscription + Publication info for this node *)\n      RADL_NumSubscriptions : nat;\n      RADL_Subscriptions : Vector.t (Fin.t n) RADL_NumSubscriptions;\n      RADL_NumPublications : nat;\n      RADL_Publications : Vector.t (Fin.t n) RADL_NumPublications;\n      RADL_Defs : list string;\n      RADL_Period : string;\n      RADL_Path : string;\n      RADL_CXX : list string\n    }.\n\n  Definition radl_in_t (Node : RADL_Node) :=\n    MessageADT TopicTypes TopicNames (RADL_Subscriptions Node).\n  Definition radl_in_flags_t (Node : RADL_Node) :=\n    FlagsADT TopicNames (RADL_Subscriptions Node).\n  Definition radl_out_t (Node : RADL_Node) :=\n    MessageADT TopicTypes TopicNames (RADL_Publications Node).\n  Definition radl_out_flags_t (Node : RADL_Node) :=\n    FlagsADT TopicNames (RADL_Publications Node).\n\n  Definition RADL_ADTSig  (Node : RADL_Node)\n  : DecoratedADTSig :=                         (* A RADL Node is modeled as an ADT with a  *)\n    ADTsignature {                    (* single constructor and a step function. *)\n        Constructor RADL_Init      : unit -> rep,\n        Method      RADL_Step      : rep x (prod (cRep (radl_in_t Node)) (cRep (radl_in_flags_t Node)))\n                                     -> rep x (prod (cRep (radl_out_t Node)) (cRep (radl_out_flags_t Node)))\n      }.\n\n  (*Definition RADL_ADTSpec (Node : RADL_Node)\n  : ADT (RADL_ADTSig Node) :=\n    ADTRep unit (* Since RADL Nodes are untrusted, we'll treat their state as completely unknown *)\n           { Def Constructor RADL_Init (_ : unit) : rep := ret tt,\n             Def Method RADL_Step (r : rep, in_t : _) : _ :=\n               (* Again, since the RADL Node is untrusted code, we'll assume that it can publish\n                  whatever the heck it wants. *)\n               results <- {out_t : cRep (radl_out_t Node) | True };\n               result_flags <- {out_t : cRep (radl_out_flags_t Node) | True };\n             ret (tt, (results, result_flags)) }. *)\n\n  Record RADLM_Node :=\n    { (* The monitored node*)\n      RADLM_MonitoredNode : RADL_Node;\n      (* Additional Subscription + Publication info *)\n      RADLM_NumSubscriptions : nat;\n      RADLM_Subscriptions : Vector.t (Fin.t n) RADLM_NumSubscriptions;\n      RADLM_NumPublications : nat;\n      RADLM_Publications : Vector.t (Fin.t n) RADLM_NumPublications\n    }.\n\n  Definition radlm_in_t (Node : RADLM_Node) :=\n    MessageADT TopicTypes TopicNames (RADL_Subscriptions (RADLM_MonitoredNode Node)).\n  Definition radlm_in_flags_t (Node : RADLM_Node) :=\n    FlagsADT TopicNames (RADL_Subscriptions (RADLM_MonitoredNode Node)).\n\n  Definition radlm_out_t (Node : RADLM_Node) :=\n    MessageADT TopicTypes TopicNames (RADL_Publications (RADLM_MonitoredNode Node)).\n  Definition radlm_out_flags_t (Node : RADLM_Node) :=\n    FlagsADT TopicNames (RADL_Publications (RADLM_MonitoredNode Node)).\n\n  Definition radlm_monitor_in_t (Node : RADLM_Node) :=\n    MessageADT TopicTypes TopicNames (RADLM_Subscriptions Node).\n  Definition radlm_monitor_out_t (Node : RADLM_Node) :=\n    MessageADT TopicTypes TopicNames (RADLM_Publications Node).\n\n  Definition RADL_Start_Step := \"Start_Step\".\n  Definition RADL_Finish_Step := \"Finish_Step\".\n\n  Record RADLM_start_msg_t (MonitorNode : RADLM_Node) :=\n    { radlm_in : cRep (radlm_in_t MonitorNode);\n      radlm_in_flags : cRep (radlm_in_flags_t MonitorNode);\n      radlm_monitor_in : cRep (radlm_monitor_in_t MonitorNode) }.\n\n  Record RADLM_finish_msg_t (MonitorNode : RADLM_Node) :=\n    { radlm_out : cRep (radlm_out_t MonitorNode);\n      radlm_out_flags : cRep (radlm_out_flags_t MonitorNode) }.\n\n  Definition RADLM_ADTSig\n             (MonitorNode : RADLM_Node)\n             (InitDom : Type)\n  : DecoratedADTSig :=\n    ADTsignature {\n        Constructor RADL_Init       : InitDom -> rep,\n        (* Monitor Nodes have two methods which are used to guard the node's step function:\n           1) an initial step function that examines the subscriptions and decides whether\n           to pass them on (potentially modifying them) or to publish on its own. *)\n        Method      RADL_Start_Step : rep x RADLM_start_msg_t MonitorNode\n                                      -> rep x (cRep (radlm_in_t MonitorNode)\n                                                * cRep (radlm_in_flags_t MonitorNode)),\n        (* 2) A finish step function that examines the publications after a node's\n         step function has been called, potentially modifying the publications and publishing\n         its own topics. *)\n        Method      RADL_Finish_Step : rep x RADLM_finish_msg_t MonitorNode\n                                       -> rep x (cRep (radlm_out_t MonitorNode)\n                                                 * cRep (radlm_out_flags_t MonitorNode)\n                                                 * cRep (radlm_monitor_out_t MonitorNode))\n      }.\n\nEnd RADL_ADT.\n\nDefinition RADL_ADT {n} Topics Node :=\n  DecoratedADT (@RADL_ADTSig n (Vector.map Topic_Type Topics)\n                    (Vector.map Topic_Name Topics)\n                    Node).\n\nDefinition RADLM_ADT {n} Topics MonitorNode InitDom :=\n  DecoratedADT (@RADLM_ADTSig n (Vector.map Topic_Type Topics)\n                     (Vector.map Topic_Name Topics)\n                     MonitorNode InitDom).\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/Fiat4Monitors/RADL_Nodes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.18012210819474506}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Crypto.Util.ZRange.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.WfExtra.\nRequire Import Crypto.Rewriter.AllTacticsExtra.\nRequire Import Crypto.Rewriter.RulesProofs.\n\nModule Compilers.\n  Import Language.Compilers.\n  Import Language.API.Compilers.\n  Import Language.Wf.Compilers.\n  Import Language.WfExtra.Compilers.\n  Import Rewriter.AllTacticsExtra.Compilers.RewriteRules.GoalType.\n  Import Rewriter.AllTactics.Compilers.RewriteRules.Tactic.\n  Import Compilers.Classes.\n\n  Module Import RewriteRules.\n    Section __.\n      Context (invert_low invert_high : Z (*log2wordmax*) -> Z -> @option Z)\n              (value_range flag_range : zrange)\n              (Hlow : forall s v v', invert_low s v = Some v' -> v = Z.land v' (2^(s/2)-1))\n              (Hhigh : forall s v v', invert_high s v = Some v' -> v = Z.shiftr v' (s/2)).\n\n      Definition VerifiedRewriterToFancyWithCasts : VerifiedRewriter_with_args false false true (@fancy_with_casts_rewrite_rules_proofs invert_low invert_high value_range flag_range Hlow Hhigh).\n      Proof using All. make_rewriter. Defined.\n\n      Definition default_opts := Eval hnf in @default_opts VerifiedRewriterToFancyWithCasts.\n      Let optsT := Eval hnf in optsT VerifiedRewriterToFancyWithCasts.\n\n      Definition RewriteToFancyWithCasts (opts : optsT) {t : API.type} : API.Expr t -> API.Expr t.\n      Proof using invert_low invert_high value_range flag_range.\n        let v := (eval hnf in (@Rewrite VerifiedRewriterToFancyWithCasts opts t)) in exact v.\n      Defined.\n\n      Lemma Wf_RewriteToFancyWithCasts opts {t} e (Hwf : Wf e) : Wf (@RewriteToFancyWithCasts opts t e).\n      Proof using All. now apply VerifiedRewriterToFancyWithCasts. Qed.\n\n      Lemma Interp_RewriteToFancyWithCasts opts {t} e (Hwf : Wf e) : API.Interp (@RewriteToFancyWithCasts opts t e) == API.Interp e.\n      Proof using All. now apply VerifiedRewriterToFancyWithCasts. Qed.\n    End __.\n  End RewriteRules.\n\n  Module Export Hints.\n#[global]\n    Hint Resolve Wf_RewriteToFancyWithCasts : wf wf_extra.\n#[global]\n    Hint Opaque RewriteToFancyWithCasts : wf wf_extra interp interp_extra rewrite.\n#[global]\n    Hint Rewrite @Interp_RewriteToFancyWithCasts : interp interp_extra.\n  End Hints.\nEnd Compilers.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Rewriter/Passes/ToFancyWithCasts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.18012210311996135}}
{"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: PAbQueue                                 *)\n(*                                                                     *)\n(*          Provide initialization 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 PAbQueue layer, \nwhich will introduce abstraction of kernel context*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjFlatMem.\nRequire Export ObjContainer.\nRequire Export ObjVMM.\nRequire Export ObjLMM.\nRequire Export ObjShareMem.\nRequire Export ObjThread.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** **Definition of the raw data at MPTBit layer*)\n  (*Record RData :=\n    mkRData {\n        HP: flatmem; (**r we model the memory from 1G to 3G as heap*)\n        ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)\n        pe: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)\n        ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)\n        ihost: bool; (**r logic flag, shows whether it's in the host mode or not*)         \n        AT: ATable; (**r allocation table*)\n        nps: Z; (**r number of the pages*)\n\n        PT: Z; (**r the current page table index*)\n        ptpool: PTPool; (**r page table pool*)\n        ipt: bool; (**r pure logic flag, shows whether it's using the kernel's page table*)\n        pb : PTBitMap; (**r [page table bit map], indicating which page table has been used*)\n\n        kctxt: KContextPool; (**r kernel context pool*)\n        abtcb: AbTCBPool; (**r thread control blocks pool*)\n        abq: AbQueuePool (**r thread queue pool*)\n      }.*)\n\n  (** **Definition of the invariants at MPTNew layer*)\n  (** [0th page map] is reserved for the kernel thread*)\n  Record high_level_invariant (abd: RData) :=\n    mkInvariant {\n        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;\n        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);\n        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);\n        valid_kern: ipt abd = false -> pg abd = true;\n        valid_iptt: ipt abd = true -> ikern abd = true; \n        valid_iptf: ikern abd = false -> ipt abd = false; \n        valid_ihost: ihost abd = false -> pg abd = true /\\ ikern abd = true;\n        valid_container: Container_valid (AC abd);\n        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);\n        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;\n        valid_PMap: pg abd = true -> \n                    (forall i, 0<= i < num_proc ->\n                               PMap_valid (ZMap.get i (ptpool abd)));\n        (* 0th page map is reserved for the kernel thread*)          \n        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;\n        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));\n        valid_PT: pg abd = true -> 0<= PT abd < num_proc;\n        valid_dirty: dirty_ppage (pperm abd) (HP abd);\n\n        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);\n        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);\n\n        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;\n\n        valid_TCB: pg abd = true -> AbTCBCorrect_range (abtcb abd);\n        valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);\n        valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);\n        valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);\n        valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd)\n\n      }.\n\n  (** ** Definition of the abstract state ops *)\n  Global Instance pabqueue_data_ops : CompatDataOps RData :=\n    {\n      empty_data := init_adt;\n      high_level_invariant := high_level_invariant;\n      low_level_invariant := low_level_invariant;\n      kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n      observe := ObservationImpl.observe\n    }.\n\n  (** ** Proofs that the initial abstract_data should satisfy the invariants*)    \n  Section Property_Abstract_Data.\n\n    Lemma empty_data_high_level_invariant:\n      high_level_invariant init_adt.\n    Proof.\n      constructor; simpl; intros; auto; try inv H.\n      - apply empty_container_valid.\n      - eapply Lconsistent_ppage_init.\n      - eapply dirty_ppage_init.\n      - eapply consistent_pmap_init.\n      - eapply consistent_pmap_domain_init.\n      - eapply consistent_lat_domain_init.\n   Qed.\n\n    (** ** Definition of the abstract state *)\n    Global Instance pabqueue_data_prf : CompatData RData.\n    Proof.\n      constructor.\n      - apply low_level_invariant_incr.\n      - apply empty_data_low_level_invariant.\n      - apply empty_data_high_level_invariant.\n    Qed.\n\n  End Property_Abstract_Data.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Section ALLOC.\n      \n      Lemma alloc_high_level_inv:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0. constructor; simpl; eauto.\n        - intros; eapply LAT_kern_norm; eauto. eapply _x.\n        - intros; eapply LAT_usr_norm; eauto.\n        - eapply alloc_container_valid'; eauto.\n        - eapply Lconsistent_ppage_norm_alloc; eauto.\n        - intros; congruence.\n        - eapply dirty_ppage_gso_alloc; eauto.\n        - eapply consistent_pmap_gso_at_false; eauto. apply _x.\n        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.\n        - eapply consistent_lat_domain_gss_nil; eauto.\n        - zmap_solve.\n        - intros; apply NotInQ_gso_true; auto.\n      Qed.\n      \n      Lemma alloc_low_level_inv:\n        forall d d' i n n',\n          alloc_spec i d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma alloc_kernel_mode:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance alloc_inv: PreservesInvariants alloc_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply alloc_low_level_inv; eassumption.\n        - eapply alloc_high_level_inv; eassumption.\n        - eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n    End ALLOC.\n\n    Global Instance pfree_inv: PreservesInvariants pfree_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - intros; eapply LAT_kern_norm; eauto. \n      - intros; eapply LAT_usr_norm; eauto.\n      - eapply Lconsistent_ppage_norm_undef; eauto.\n      - eapply dirty_ppage_gso_undef; eauto.\n      - eapply consistent_pmap_gso_pperm_alloc; eauto.\n      - eapply consistent_pmap_domain_gso_at_0; eauto.\n      - eapply consistent_lat_domain_gss_nil; eauto.\n    Qed.\n\n    Global Instance trapin_inv: PrimInvariants trapin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance trapout_inv: PrimInvariants trapout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostin_inv: PrimInvariants hostin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostout_inv: PrimInvariants hostout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptin_inv: PrimInvariants ptin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptout_inv: PrimInvariants ptout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance fstore_inv: PreservesInvariants fstore_spec.\n    Proof.\n      split; intros; inv_generic_sem H; inv H0; functional inversion H2.\n      - functional inversion H. split; trivial.        \n      - functional inversion H.\n        split; subst; simpl; \n        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial. \n      - functional inversion H0.\n        split; simpl; try assumption.\n    Qed.\n\n    Global Instance setPT_inv: PreservesInvariants setPT_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Section PTINSERT.\n      \n      Section PTINSERT_PTE.\n\n        Lemma ptInsertPTE_high_level_inv:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. \n          - eapply LAT_usr_norm; eauto.\n          - eapply Lconsistent_ppage_norm; eassumption.\n          - eapply PMap_valid_gso_valid; eauto.\n          - functional inversion H2. functional inversion H1. \n            eapply PMap_kern_gso; eauto.\n          - functional inversion H2. functional inversion H0.\n            eapply consistent_pmap_ptp_same; try eassumption.\n            eapply consistent_pmap_gso_pperm_alloc'; eassumption.\n          - functional inversion H2.\n            eapply consistent_pmap_domain_append; eauto.\n            destruct (ZMap.get pti pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n          - eapply consistent_lat_domain_gss_append; eauto.\n            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n        Qed.\n\n        Lemma ptInsertPTE_low_level_inv:\n          forall d d' n vadr padr p n',\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptInsertPTE_kernel_mode:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTINSERT_PTE.\n\n      Section PTALLOCPDE.\n\n        Lemma ptAllocPDE_high_level_inv:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto. \n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. eapply _x.\n          - eapply LAT_usr_norm; eauto.\n          - eapply alloc_container_valid'; eauto.\n          - apply Lconsistent_ppage_norm_hide; try assumption.\n          - congruence.\n          - eapply PMap_valid_gso_pde_unp; eauto.\n            eapply real_init_PTE_defined.\n          - functional inversion H3. \n            eapply PMap_kern_gso; eauto.\n          - eapply dirty_ppage_gss; eauto.\n          - eapply consistent_pmap_ptp_gss; eauto; apply _x.\n          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.\n            eapply consistent_pmap_domain_ptp_unp; eauto.\n            apply real_init_PTE_unp.\n          - apply consistent_lat_domain_gss_nil; eauto.\n            apply consistent_lat_domain_gso_p; eauto.\n          - zmap_solve.\n          - apply NotInQ_gso_true; auto.\n        Qed.\n\n        Lemma ptAllocPDE_low_level_inv:\n          forall d d' n vadr v n',\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptAllocPDE_kernel_mode:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTALLOCPDE.\n\n      Lemma ptInsert_high_level_inv:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        - eapply ptInsertPTE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptInsertPTE_high_level_inv; try eassumption.\n          eapply ptAllocPDE_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_low_level_inv:\n        forall d d' n vadr padr p n' v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptInsertPTE_low_level_inv; try eassumption.\n          eapply ptAllocPDE_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_kernel_mode:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_kernel_mode; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n        - eapply ptInsertPTE_kernel_mode; try eassumption.\n          eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTINSERT.\n\n    Section PTRESV.\n\n      Lemma ptResv_high_level_inv:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        eapply ptInsert_high_level_inv; try eassumption.\n        eapply alloc_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_low_level_inv:\n        forall d d' n vadr p n' v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_low_level_inv; try eassumption.\n        eapply alloc_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_kernel_mode:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_kernel_mode; try eassumption.\n        eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptResv_low_level_inv; eassumption.\n        - eapply ptResv_high_level_inv; eassumption.\n        - eapply ptResv_kernel_mode; eassumption.\n      Qed.\n\n    End PTRESV.\n\n    Section OFFER_SHARE.\n\n      Section PTRESV2.\n\n        Lemma ptResv2_high_level_inv:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_high_level_inv; try eassumption.\n          - eapply alloc_high_level_inv; eassumption.\n          - eapply ptInsert_high_level_inv; try eassumption.\n            eapply alloc_high_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_low_level_inv:\n          forall d d' n vadr p n' vadr' p' l v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            low_level_invariant l d ->\n            low_level_invariant l d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_low_level_inv; try eassumption.\n          - eapply alloc_low_level_inv; eassumption.\n          - eapply ptInsert_low_level_inv; try eassumption.\n            eapply alloc_low_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_kernel_mode:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_kernel_mode; try eassumption.\n          - eapply alloc_kernel_mode; eassumption.\n          - eapply ptInsert_kernel_mode; try eassumption.\n            eapply alloc_kernel_mode; eassumption.\n        Qed.\n\n      End PTRESV2.\n\n      Global Instance offer_shared_mem_inv: \n        PreservesInvariants offer_shared_mem_spec.\n      Proof.\n        preserves_invariants_simpl';\n        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_kernel_mode; eauto.\n        - exploit ptResv2_kernel_mode; eauto.\n      Qed.\n\n    End OFFER_SHARE.\n\n    Global Instance shared_mem_status_inv: \n      PreservesInvariants shared_mem_status_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance kctxt_switch_inv: KCtxtSwitchInvariants kctxt_switch_spec.\n    Proof.\n      constructor; intros; functional inversion H. \n      - inv H1. constructor; trivial. \n        eapply kctxt_inject_neutral_gss_mem; eauto.\n      - inv H0. subst. constructor; auto; simpl in *; intros; try congruence.\n    Qed.\n       \n    Global Instance kctxt_new_inv: DNewInvariants kctxt_new_spec.\n    Proof.\n      constructor; intros; inv H0;\n      unfold ObjThread.kctxt_new_spec in *;\n      subdestruct; inv H; simpl; auto.\n      - (* low level invariant *)\n        constructor; trivial; intros; simpl in *.\n        eapply kctxt_inject_neutral_gss_flatinj'; eauto.\n        eapply kctxt_inject_neutral_gss_flatinj; eauto.\n\n      - (* high_level_invariant *)\n        constructor; simpl; eauto 2; try congruence; intros.\n        + exploit split_container_valid; eauto.\n          eapply container_split_some; eauto.\n          auto.\n        + unfold update_cusage, update_cchildren; zmap_solve.\n        + unfold update_cusage, update_cchildren; apply NotInQ_gso_true; auto.\n          zmap_simpl; repeat apply NotInQ_gso_true; auto.\n    Qed.\n\n    Global Instance set_state_inv: PreservesInvariants set_state0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n      - eapply AbTCBCorrect_range_gss; eauto.\n        eapply AbTCBCorrect_range_valid_b; eauto.\n      - eapply NotInQ_gso_state; eauto.\n      - eapply QCount_gso_state; eauto.\n      - eapply InQ_gso_state; eauto.\n    Qed.\n\n    Global Instance tdqueue_init_inv: PreservesInvariants tdqueue_init0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant.\n      - apply real_nps_range.\n      - apply real_lat_kern_valid.\n      - apply real_lat_usr_valid.\n      - apply real_container_valid.\n      - rewrite init_pperm0; try assumption.\n        apply Lreal_pperm_valid.        \n      - eapply real_pt_PMap_valid; eauto.\n      - apply real_pt_PMap_kern.\n      - omega.\n      - assumption.\n      - apply real_idpde_init.\n      - apply real_pt_consistent_pmap. \n      - apply real_pt_consistent_pmap_domain. \n      - apply Lreal_at_consistent_lat_domain.\n      - apply real_abtcb_range; auto.\n      - apply real_abq_range; auto.\n      - eapply real_abtcb_pb_notInQ; eauto.\n      - eapply real_abtcb_abq_QCount; eauto.\n      - eapply real_abq_tcb_inQ; eauto.\n    Qed.\n\n    Global Instance enqueue_inv: PreservesInvariants enqueue0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2;\n      functional inversion H5.\n      - eapply AbTCBCorrect_range_gss; eauto. omega.\n      - eapply AbQCorrect_range_gss_enqueue; eauto.\n      - eapply NotInQ_gso_ac; eauto.\n      - eapply QCount_gss_enqueue; eauto. \n      - eapply InQ_gss_enqueue; eauto.\n    Qed.\n\n    Global Instance dequeue_inv: PreservesInvariants dequeue0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - eapply AbTCBCorrect_range_gss; eauto. omega.\n      - eapply AbQCorrect_range_gss_remove; eauto.\n      - eapply NotInQ_gso_neg; eauto.\n      - eapply QCount_gss_remove; eauto.\n        eapply last_range_AbQ; eauto.\n      - eapply InQ_gss_remove; eauto.\n        + eapply last_range_AbQ; eauto.\n        + apply last_correct; auto.\n    Qed.\n\n    Global Instance queue_rmv_inv: PreservesInvariants queue_rmv0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2;\n      functional inversion H5.\n      - eapply AbTCBCorrect_range_gss; eauto. omega.\n      - eapply AbQCorrect_range_gss_remove; eauto.\n      - eapply NotInQ_gso_neg; eauto.\n      - eapply QCount_gss_remove; eauto.\n      - eapply InQ_gss_remove; eauto.\n        eapply QCount_valid; eauto.\n    Qed.\n\n    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    (*Global Instance thread_free_inv: PreservesInvariants thread_free_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - destruct (zeq i0 (Int.unsigned i)); subst.\n        + rewrite ZMap.gss. apply PT_init_common_pdt_usr.\n          apply real_free_pt_valid; apply valid_PT_common0; auto.\n        + rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) 0); subst. omega.\n        rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) 0); subst. omega.\n        rewrite ZMap.gso; auto.\n      - unfold PTB_defined in *; intros.\n        destruct (zeq (Int.unsigned i) i0); subst.\n        rewrite ZMap.gss.\n        red; intros HF; inv HF.\n        rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) i0); subst.\n        + rewrite ZMap.gss. unfold AbTCBCorrect in *.\n          refine_split'; eauto; omega.\n        + rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) i0); subst.\n        + rewrite ZMap.gss in *. inv H12; trivial.\n        + rewrite ZMap.gso in *; eauto.\n      - destruct (zeq (Int.unsigned i) i0); subst.\n        + rewrite ZMap.gss in *. inv H11. eauto.\n        + rewrite ZMap.gso in *; eauto.\n      - destruct (zeq (Int.unsigned i) i0); subst.\n        + rewrite ZMap.gss.\n          destruct (valid_inQ0 H4 _ _ _ H10 H11 H12 H13) as [s' HM].\n          rewrite H8 in HM. inv HM. omega.\n        + rewrite ZMap.gso; eauto.      \n    Qed.*)\n\n    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant;      \n      try eapply dirty_ppage_gss_copy; eauto.\n    Qed.\n\n    Global Instance device_output_inv: PreservesInvariants device_output_spec.\n    Proof. \n      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.\n    Qed.\n\n  End INV.\n\n  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).\n\n  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).\n\n  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).\n  Proof.\n    split; inversion 1; intros. \n    - functional inversion H0. split; trivial.\n    - functional inversion H1. \n      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.\n  Qed.\n\n  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n  Proof.\n    split; inversion 1; intros; constructor; auto.\n  Qed.\n\n  (** * Layer Definition *)\n  Definition pabqueue : compatlayer (cdata RData) :=\n    fload \u21a6 gensem fload_spec\n          \u2295 fstore \u21a6 gensem fstore_spec\n          \u2295 flatmem_copy \u21a6 gensem flatmem_copy_spec\n          \u2295 vmxinfo_get \u21a6 gensem vmxinfo_get_spec\n          \u2295 device_output \u21a6 gensem device_output_spec\n          \u2295 pfree \u21a6 gensem pfree_spec\n          \u2295 set_pt \u21a6 gensem setPT_spec\n          \u2295 pt_read \u21a6 gensem ptRead_spec\n          \u2295 pt_resv \u21a6 gensem ptResv_spec\n          \u2295 kctxt_new \u21a6 dnew_compatsem ObjThread.kctxt_new_spec\n          (*\u2295 pt_free \u21a6 gensem pt_free_spec*)\n          \u2295 shared_mem_status \u21a6 gensem shared_mem_status_spec\n          \u2295 offer_shared_mem \u21a6 gensem offer_shared_mem_spec\n\n          \u2295 get_state \u21a6 gensem get_state0_spec\n          \u2295 set_state \u21a6 gensem set_state0_spec\n          \u2295 tdqueue_init \u21a6 gensem tdqueue_init0_spec\n          \u2295 enqueue \u21a6 gensem enqueue0_spec\n          \u2295 dequeue \u21a6 gensem dequeue0_spec\n          \u2295 queue_rmv \u21a6 gensem queue_rmv0_spec\n\n          \u2295 pt_in \u21a6 primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n          \u2295 pt_out \u21a6 primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          \u2295 clear_cr2 \u21a6 gensem clearCR2_spec\n          \u2295 container_get_nchildren \u21a6 gensem container_get_nchildren_spec\n          \u2295 container_get_quota \u21a6 gensem container_get_quota_spec\n          \u2295 container_get_usage \u21a6 gensem container_get_usage_spec\n          \u2295 container_can_consume \u21a6 gensem container_can_consume_spec\n          \u2295 container_alloc \u21a6 gensem alloc_spec\n          \u2295 trap_in \u21a6 primcall_general_compatsem trapin_spec\n          \u2295 trap_out \u21a6 primcall_general_compatsem trapout_spec\n          \u2295 host_in \u21a6 primcall_general_compatsem hostin_spec\n          \u2295 host_out \u21a6 primcall_general_compatsem hostout_spec\n          \u2295 trap_get \u21a6 primcall_trap_info_get_compatsem trap_info_get_spec\n          \u2295 trap_set \u21a6 primcall_trap_info_ret_compatsem trap_info_ret_spec\n          \u2295 kctxt_switch \u21a6 primcall_kctxt_switch_compatsem kctxt_switch_spec\n          \u2295 accessors \u21a6 {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  (*Definition semantics := LAsm.Lsemantics pabqueue.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PAbQueue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.17983552744434414}}
{"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 TableAux2.Spec.\nRequire Import TableAux.Spec.\nRequire Import TableAux3.Specs.table_destroy_aux.\nRequire Import TableAux3.LowSpecs.table_destroy_aux.\nRequire Import TableAux3.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       granule_map_spec\n       get_g_rtt_refcount_spec\n       table_delete_spec\n       table_fold_spec\n       pgte_write_spec\n       invalidate_page_spec\n       invalidate_pages_in_block_spec\n       invalidate_block_spec\n       granule_put_spec\n       null_ptr_spec\n       set_g_rtt_rd_spec\n       granule_memzero_mapped_spec\n       granule_memzero_spec\n       granule_set_state_spec\n       buffer_unmap_spec\n    .\n\n\n  Lemma table_destroy_aux_spec_exists:\n    forall habd habd'  labd g_llt g_tbl ll_table level index map_addr res\n      (Hspec: table_destroy_aux_spec g_llt g_tbl ll_table level index map_addr habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', table_destroy_aux_spec0 g_llt g_tbl ll_table level index map_addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq peq fill_table. pose proof orb_64_range as orr.\n    pose proof IPA_PTE_IPA as ipi. pose proof IPA_PTE_IPA2 as ipi2.\n    pose proof pte_4096_range as p4096.\n    pose proof pte_2011_4096_range as p2_4096.\n    intros. destruct Hrel. inv id_rdata. destruct g_llt, g_tbl, ll_table.\n    unfold table_destroy_aux_spec, table_destroy_aux_spec0 in *; repeat autounfold in *.\n    hsimpl_hyp Hspec; inv Hspec; extract_prop_dec.\n    - simpl in *. grewrite. inv Prop2.\n      match goal with\n      | |- context [prop_dec (?a = ?a)] => destruct (prop_dec (a = a)); [ simpl | contra ]\n      end.\n      grewrite. solve_peq. simpl.\n      repeat (grewrite; try simpl_htarget; simpl in * ).\n      rewrite table_a5_d7. extract_if. bool_rel. grewrite. reflexivity. grewrite.\n      extract_if. destruct_if; reflexivity. grewrite.\n      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; simpl in * ).\n      solve_bool_range. grewrite.\n      destruct_if. destruct_if' Case; inversion Case.\n      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      extract_if. bool_rel; grewrite. omega. grewrite. solve_peq.\n      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      eexists; split. reflexivity. constructor.\n      rewrite (zmap_comm _ _ Prop3). bool_rel. grewrite. simpl.\n      destruct_if. reflexivity. reflexivity.\n      red; intro T; inv T. red; intro T; inv T. destruct_if; reflexivity.\n    - simpl in *. grewrite. inv Prop2.\n      match goal with\n      | |- context [prop_dec (?a = ?a)] => destruct (prop_dec (a = a)); [ simpl | contra ]\n      end.\n      grewrite. solve_peq. simpl.\n      repeat (grewrite; try simpl_htarget; simpl in * ).\n      solve_bool_range. grewrite. solve_bool_range. grewrite.\n      extract_if. bool_rel; grewrite. omega. grewrite.\n      extract_if. destruct_if. apply orb_64_range. autounfold. apply orb_64_range. autounfold.\n      rewrite table_a5_d7_m7. reflexivity. apply Prop1. autounfold. apply entry_to_phys_range. apply Prop1. reflexivity.\n      apply orb_64_range. autounfold. rewrite table_a5_d7_m7. reflexivity.\n      apply Prop1. autounfold. apply entry_to_phys_range. apply Prop1. grewrite.\n      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).\n      solve_bool_range. grewrite. solve_bool_range. grewrite.\n      destruct (Z.land (g_data (gnorm (gs (share labd)) @ z0)) @ 0 504403158265495552 / 72057594037927936 =? 2) eqn:ipa.\n      + rewrite ipi. grewrite. rewrite ZMap.gso. grewrite.\n        simpl_htarget. grewrite. simpl. simpl_htarget.\n        extract_if. bool_rel. grewrite. omega. grewrite. simpl.\n        repeat simpl_field; repeat swap_fields; simpl_htarget. solve_peq.\n        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.\n        repeat rewrite (zmap_comm _ _ Prop4).\n        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.\n        eexists. split. reflexivity. constructor. bool_rel. grewrite. simpl. reflexivity.\n        red; intro T; inv T. apply Prop1. apply Prop1. omega.\n      + rewrite ipi2. grewrite. rewrite ZMap.gso. grewrite.\n        simpl_htarget. grewrite. simpl. simpl_htarget.\n        extract_if. bool_rel. grewrite. omega. grewrite. simpl.\n        repeat simpl_field; repeat swap_fields; simpl_htarget. solve_peq.\n        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.\n        repeat rewrite (zmap_comm _ _ Prop4).\n        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.\n        eexists. split. reflexivity. constructor. bool_rel. grewrite. simpl. reflexivity.\n        red; intro T; inv T. apply Prop1. apply Prop1.\n      + red; intro T; inv T.\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/TableAux3/RefProof/table_destroy_aux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17977895242959835}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom lrust.typing Require Import typing.\nFrom iris.prelude Require Import options.\n\nSection get_x.\n  Context `{!typeGS \u03a3}.\n\n  Definition get_x : val :=\n    fn: [\"p\"] :=\n       let: \"p'\" := !\"p\" in\n       letalloc: \"r\" <- \"p'\" +\u2097 #0 in\n       delete [ #1; \"p\"] ;; return: [\"r\"].\n\n  Lemma get_x_type :\n    typed_val get_x (fn(\u2200 \u03b1, \u2205; &uniq{\u03b1}(\u03a0[int; int])) \u2192 &shr{\u03b1}int).\n  Proof.\n    intros E L. iApply type_fn; [solve_typing..|]. iIntros \"/= !>\". iIntros (\u03b1 \u03dd ret p).\n    inv_vec p=>p. simpl_subst.\n    iApply type_deref; [solve_typing..|]. iIntros (p'); simpl_subst.\n    iApply (type_letalloc_1 (&shr{\u03b1}int)); [solve_typing..|]. iIntros (r). simpl_subst.\n    iApply type_delete; [solve_typing..|].\n    iApply type_jump; solve_typing.\n  Qed.\nEnd get_x.\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/examples/get_x.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.17976837529812847}}
{"text": "Require Import HoareDef IntroHeader IntroF1 IntroFSep2 SimModSem.\nImport Sep.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics ProofMode.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\nSection SIMMODSEM.\n\n  Context `{\u03a3: GRA.t}.\n  Context `{@GRA.inG IRA.t \u03a3}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: _ -> W -> Prop :=\n    @mk_wf\n      _\n      unit\n      (fun _ _ _ => \u231cTrue\u231d%I)\n  .\n\n  Theorem correct: refines2 [IntroF1.F] [IntroFSep2.F].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); et; swap 2 3.\n    { ss. }\n    { esplits. econs; ss. eapply to_semantic. iIntros \"H\". iSplits; ss. }\n\n    econs; ss. init. harg. mDesAll.\n    des; clarify. unfold fF, ccallU. steps. astart 10. force_r. exists x. steps. force_r; ss. steps.\n    unfold Ncall. steps. des_ifs.\n    - unfold ccallU. steps. acatch. des. hcall _ _ with \"*\"; auto.\n      { esplits; ss; et. }\n      steps. astop. ss. steps. mDesAll; clarify. rewrite Any.upcast_downcast. ss. steps.\n      force_r; ss. steps. force_l. esplits. steps. hret _; ss.\n      { iModIntro. iFrame. iSplits; ss; et. }\n    - steps. astop. steps. force_l. esplits. steps.\n      mAssert _ with \"A\".\n      { iApply (OwnM_Upd with \"A\"). instantiate (1:=IRA.client false). r. clear_until H.\n        ur. i. des_ifs.\n      }\n      hret _; ss.\n      { iMod \"A1\". iModIntro. iFrame. iSplits; ss; et. }\n  Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/intro/IntroF12Sepproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17976837180848498}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import TableAux3.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import TableAux.Spec.\nRequire Import RunSMC.Spec.\nRequire Import TableWalk.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance TableWalk_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance TableWalk_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance table_walk_lock_unlock_inv: PreservesInvariants table_walk_lock_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance table_destroy_aux_inv: PreservesInvariants table_destroy_aux_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance invalidate_page_inv: PreservesInvariants invalidate_page_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_run_inv: PreservesInvariants smc_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance invalidate_block_inv: PreservesInvariants invalidate_block_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance table_create_aux_inv: PreservesInvariants table_create_aux_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance validate_table_commands_inv: PreservesInvariants validate_table_commands_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition TableWalk_fresh : compatlayer (cdata RData) :=\n      _table_walk_lock_unlock \u21a6 gensem table_walk_lock_unlock_spec\n      .\n\n    Definition TableWalk_passthrough : compatlayer (cdata RData) :=\n      _set_mapping \u21a6 gensem set_mapping_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _ns_granule_map \u21a6 gensem ns_granule_map_spec\n        \u2295 _granule_get \u21a6 gensem granule_get_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _table_destroy_aux \u21a6 gensem table_destroy_aux_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _granule_put \u21a6 gensem granule_put_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _invalidate_page \u21a6 gensem invalidate_page_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _entry_is_table \u21a6 gensem entry_is_table_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _get_wi_g_llt \u21a6 gensem get_wi_g_llt_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _smc_rec_run \u21a6 gensem smc_rec_run_spec\n        \u2295 _invalidate_block \u21a6 gensem invalidate_block_spec\n        \u2295 _granule_memzero \u21a6 gensem granule_memzero_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _ns_buffer_unmap \u21a6 gensem ns_buffer_unmap_spec\n        \u2295 _granule_memzero_mapped \u21a6 gensem granule_memzero_mapped_spec\n        \u2295 _pgte_read \u21a6 gensem pgte_read_spec\n        \u2295 _ns_buffer_read_data \u21a6 gensem ns_buffer_read_data_spec\n        \u2295 _table_create_aux \u21a6 gensem table_create_aux_spec\n        \u2295 _pgte_write \u21a6 gensem pgte_write_spec\n        \u2295 _validate_table_commands \u21a6 gensem validate_table_commands_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _get_wi_index \u21a6 gensem get_wi_index_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n      .\n\n    Definition TableWalk := TableWalk_fresh \u2295 TableWalk_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.1797527489782194}}
{"text": "(*\n * Copyright (c) 2020-2023 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 Import iris.proofmode.proofmode.\n\nFrom bedrock.lang.cpp Require Import ast semantics.\nFrom bedrock.lang.cpp.logic Require Import\n     pred path_pred heap_pred destroy\n     wp initializers.\nRequire Import bedrock.lang.bi.errors.\n\nModule Type Stmt.\n  #[local] Arguments wp_test [_ _ _] _ _ _.\n\n  (** weakest pre-condition for statements\n   *)\n  Section with_resolver.\n    Context `{\u03a3 : cpp_logic thread_info} {\u03c3 : genv}.\n    Variable (tu : translation_unit).\n\n    #[local] Notation wp := (wp tu).\n    #[local] Notation interp := (interp tu).\n    #[local] Notation wp_initialize := (wp_initialize tu).\n    #[local] Notation default_initialize := (default_initialize tu).\n\n\n    Implicit Types Q : Kpred.\n\n    Definition Kseq (Q : Kpred -> mpred) (k : Kpred) : Kpred :=\n      KP (funI rt =>\n          match rt with\n          | Normal => Q k\n          | rt => k rt\n          end).\n    #[global] Instance Kseq_mono : Proper (((\u22a2) ==> (\u22a2)) ==> (\u22a2) ==> (\u22a2)) Kseq.\n    Proof.\n      constructor => rt; rewrite /Kseq/KP/=.\n      destruct rt; try apply H; apply H0.\n    Qed.\n\n    Definition Kfree (free : FreeTemp) : Kpred -> Kpred :=\n      Kat_exit (interp free).\n\n    Lemma Kfree_frame free Q Q' rt :\n      Q rt -* Q' rt |-- Kfree free Q rt -* Kfree free Q' rt.\n    Proof.\n      iIntros \"X\". iApply Kat_exit_frame => //.\n      iIntros (??) \"H\"; by iApply interp_frame.\n    Qed.\n\n    (** * Expression Evaluation *)\n\n    Axiom wp_expr : forall \u03c1 e Q,\n        |> wp_discard tu \u03c1 e (fun free => interp free (Q Normal))\n        |-- wp \u03c1 (Sexpr e) Q.\n\n    (** * Declarations *)\n\n    (* This definition performs allocation of local variables.\n     *\n     * note that references do not allocate anything in the semantics, they are\n     * just aliases.\n     *\n     * TODO there is a lot of overlap between this and [wp_initialize] (which does initialization\n     * of aggregate fields).\n     *)\n    Definition wp_decl_var (\u03c1 \u03c1_init : region) (x : ident) (ty : type) (init : option Expr)\n               (k : region -> FreeTemp -> epred)\n      : mpred :=\n      Forall (addr : ptr),\n        let destroy frees :=\n            interp frees (k (Rbind x addr \u03c1) (FreeTemps.delete ty addr))\n        in\n        match init with\n        | Some init => wp_initialize \u03c1_init ty addr init $ fun frees => destroy frees\n        | None => default_initialize ty addr (fun frees => destroy frees)\n        end.\n\n    Lemma wp_decl_var_frame : forall x \u03c1 \u03c1_init init ty (k k' : region -> FreeTemps -> epred),\n        Forall a (b : _), k a b -* k' a b\n        |-- wp_decl_var \u03c1 \u03c1_init x ty init k -* wp_decl_var \u03c1 \u03c1_init x ty init k'.\n    Proof.\n      rewrite /wp_decl_var; intros.\n      iIntros \"X Y\" (addr); iSpecialize (\"Y\" $! addr); iRevert \"Y\".\n      case_match;\n        [ iApply wp_initialize_frame | iApply default_initialize_frame ];\n        iIntros (?); iApply interp_frame; iApply \"X\".\n    Qed.\n\n    (* An error used to say that thread safe initializers are not supported *)\n    Record thread_safe_initializer (d : VarDecl) : Prop := {}.\n\n    Fixpoint wp_decl (\u03c1 \u03c1_init : region) (d : VarDecl) (k : region -> FreeTemps -> epred) {struct d} : mpred :=\n      match d with\n      | Dvar x ty init => wp_decl_var \u03c1 \u03c1_init x ty init k\n      | Ddecompose init x ds =>\n        wp_decl_var \u03c1_init \u03c1_init x (type_of init) (Some init) (fun \u03c1_init' free =>\n          (fix continue ds \u03c1 k free :=\n             match ds with\n             | nil => k \u03c1 free\n             | d :: ds => wp_decl \u03c1 \u03c1_init' d (fun \u03c1 free' => continue ds \u03c1 k (FreeTemps.seq free' free))\n             end) ds \u03c1 k free)\n      | Dinit ts nm ty init =>\n        let do_init :=\n            match init with\n            | None => default_initialize ty (_global nm) (k \u03c1)\n            | Some init => wp_initialize \u03c1_init ty (_global nm) init (k \u03c1)\n            end\n        in\n        if ts then\n          UNSUPPORTED (thread_safe_initializer d)\n        else\n          _global nm |-> tblockR ty (cQp.mut 1) ** do_init\n      end.\n\n    Lemma wp_decl_frame : forall ds \u03c1 \u03c1_init m m',\n        Forall a b, m a b -* m' a b\n        |-- wp_decl \u03c1 \u03c1_init ds m -* wp_decl \u03c1 \u03c1_init ds m'.\n    Proof.\n      refine (fix IH ds := _); destruct ds; simpl; intros.\n      { iIntros \"X\"; by iApply wp_decl_var_frame. }\n      { iIntros \"A\". iApply wp_decl_var_frame.\n        iStopProof.\n        generalize dependent \u03c1; generalize dependent m. induction l; intros.\n        { iIntros \"X\" (??) \"Y\". iApply \"X\". eauto. }\n        { iIntros \"x\" (??). iApply IH.\n          iIntros (??) \"Z\". iRevert \"Z\". iApply (IHl with \"x\"); eauto. } }\n      { case_match; eauto.\n        case_match.\n        { iIntros \"? [$ X]\"; iRevert \"X\"; iApply wp_initialize_frame => //; iIntros (?); done. }\n        { iIntros \"? [$ X]\"; iRevert \"X\"; iApply default_initialize_frame => //. } }\n    Qed.\n\n    Fixpoint wp_decls (\u03c1 \u03c1_init : region) (ds : list VarDecl)\n             (k : region -> FreeTemps -> epred) : mpred :=\n      match ds with\n      | nil => k \u03c1 FreeTemps.id\n      | d :: ds => |> wp_decl \u03c1 \u03c1_init d (fun \u03c1 free => wp_decls \u03c1 \u03c1_init ds (fun \u03c1' free' => k \u03c1' (FreeTemps.seq free' free)))\n      end.\n\n    Lemma wp_decls_frame : forall ds \u03c1 \u03c1_init (Q Q' : region -> FreeTemps -> epred),\n        Forall a (b : _), Q a b -* Q' a b\n        |-- wp_decls \u03c1 \u03c1_init ds Q -* wp_decls \u03c1 \u03c1_init ds Q'.\n    Proof.\n      induction ds; simpl; intros.\n      - iIntros \"a\"; iApply \"a\".\n      - iIntros \"a b\"; iNext; iRevert \"b\".\n        iApply wp_decl_frame.\n        iIntros (??). iApply IHds. iIntros (??) \"X\". by iApply \"a\".\n    Qed.\n\n    (** * Blocks *)\n\n    Fixpoint wp_block (\u03c1 : region) (ss : list Stmt) (Q : Kpred) : mpred :=\n      match ss with\n      | nil => |> Q Normal\n      | Sdecl ds :: ss =>\n        wp_decls \u03c1 \u03c1 ds (fun \u03c1 free => |> wp_block \u03c1 ss (Kfree free Q))\n      | s :: ss =>\n        |> wp \u03c1 s (Kseq (wp_block \u03c1 ss) Q)\n      end.\n\n    Lemma wp_block_frame : forall body \u03c1 (Q Q' : Kpred),\n        (Forall rt, Q rt -* Q' rt) |-- wp_block \u03c1 body Q -* wp_block \u03c1 body Q'.\n    Proof.\n      clear.\n      induction body; simpl; intros.\n      - iIntros \"a b\"; iNext; iApply \"a\"; eauto.\n      - assert\n          (Forall rt, Q rt -* Q' rt |--\n                        (Forall ds, wp_decls \u03c1 \u03c1 ds (fun \u03c1' free => |> wp_block \u03c1' body (Kfree free Q)) -*\n                                    wp_decls \u03c1 \u03c1 ds (fun \u03c1' free => |> wp_block \u03c1' body (Kfree free Q'))) //\\\\\n                        (|> wp \u03c1 a (Kseq (wp_block \u03c1 body) Q) -*\n                            |> wp \u03c1 a (Kseq (wp_block \u03c1 body) Q'))).\n        { iIntros \"X\"; iSplit.\n          - iIntros (ds).\n            iApply wp_decls_frame. iIntros (??) \"x\"; iNext.\n            iRevert \"x\"; iApply IHbody.\n            iIntros (?); iApply Kfree_frame; iApply \"X\".\n          - iIntros \"x\"; iNext; iRevert \"x\"; iApply wp_frame; first by reflexivity.\n            iIntros (rt); destruct rt =>/=; eauto.\n            by iApply IHbody. }\n        iIntros \"X\".\n        iDestruct (H with \"X\") as \"X\".\n        destruct a; try solve [ iDestruct \"X\" as \"[_ $]\" ].\n        iDestruct \"X\" as \"[X _]\". iApply \"X\".\n    Qed.\n\n    Axiom wp_seq : forall \u03c1 Q ss,\n        wp_block \u03c1 ss Q |-- wp \u03c1 (Sseq ss) Q.\n\n    (** [if] *)\n\n    Axiom wp_if : forall \u03c1 e thn els Q,\n        |> Unfold WPE.wp_test (wp_test tu \u03c1 e (fun c free =>\n               interp free $\n               if c\n               then wp \u03c1 thn Q\n               else wp \u03c1 els Q))\n      |-- wp \u03c1 (Sif None e thn els) Q.\n\n    Axiom wp_if_decl : forall \u03c1 d e thn els Q,\n        wp \u03c1 (Sseq (Sdecl (d :: nil) :: Sif None e thn els :: nil)) Q\n        |-- wp \u03c1 (Sif (Some d) e thn els) Q.\n\n    (** * Loops *)\n    (* The loop rules are phrased using loop invariants. An alternative\n     * is to use their 1-step unfoldings and a greatest-fixpoint.\n     *\n     * Inconsistency: Certain infinite loops can be optimized away\n     * in C/C++. E.g. [while (1);] can be optimized to [;]. The loop\n     * rules do not support these.\n     *)\n\n    (* loop with invariant `I` *)\n    Definition Kloop (I : mpred) (Q : Kpred) : Kpred :=\n      KP (funI rt =>\n          match rt with\n          | Break => Q Normal\n          | Normal | Continue => I\n          | rt => Q rt\n          end).\n\n    Axiom wp_while : forall \u03c1 test body Q I,\n        I |-- wp \u03c1 (Sif None test body Sbreak) (Kloop I Q) ->\n        I |-- wp \u03c1 (Swhile None test body) Q.\n\n    (**\n       `while (T x = e) body` desugars to `{ T x = e; while (x) body }`\n     *)\n    Axiom wp_while_decl : forall \u03c1 d test body Q,\n            wp \u03c1 (Sseq (Sdecl (d :: nil) :: Swhile None test body :: nil)) Q\n        |-- wp \u03c1 (Swhile (Some d) test body) Q.\n\n    Axiom wp_for : forall \u03c1 test incr body Q I,\n        let incr_I :=\n          match incr with\n          | None => I\n          | Some incr => wp_discard tu \u03c1 incr (fun free => interp free I)\n          end\n        in\n        match test with\n        | None =>\n          I |-- wp \u03c1 body (Kloop incr_I Q)\n        | Some test =>\n          I |-- wp \u03c1 (Sif None test body Sbreak) (Kloop incr_I Q)\n        end ->\n        I |-- wp \u03c1 (Sfor None test incr body) Q.\n\n    (**\n       `for (init; test; incr) body` desugars to `{ init; for (; test; incr) body }`\n     *)\n    Axiom wp_for_init : forall \u03c1 init test incr b Q,\n            wp \u03c1 (Sseq (init :: Sfor None test incr b :: nil)) Q\n        |-- wp \u03c1 (Sfor (Some init) test incr b) Q.\n\n    (** ** `do` loops *)\n\n    Definition Kdo (\u03c1 : region) (e : Expr) (I : mpred) (Q : Kpred) : Kpred :=\n      KP (funI rt =>\n          match rt with\n          | Break => Q Normal\n          | Continue | Normal =>\n            Unfold WPE.wp_test (wp_test tu \u03c1 e (fun c free => interp free $ if c then I else Q Normal))\n          | rt => Q rt\n          end).\n\n    Axiom wp_do : forall \u03c1 test body Q I,\n        I |-- wp \u03c1 body (Kdo \u03c1 test I Q) ->\n        I |-- wp \u03c1 (Sdo body test) Q.\n\n    (** * Return *)\n\n    (* the semantics of return is like an initialization\n     * expression.\n     *)\n    Axiom wp_return_void : forall \u03c1 Q,\n        get_return_type \u03c1 = Tvoid ->\n        Q ReturnVoid |-- wp \u03c1 (Sreturn None) Q.\n\n    Axiom wp_return : forall \u03c1 e (Q : Kpred),\n          (let rty := erase_qualifiers (get_return_type \u03c1) in\n           Forall p, wp_initialize \u03c1 rty p e (fun frees =>\n                                         interp frees (Q (ReturnVal p))))\n           (* ^ NOTE discard [free] because we are extruding the scope of the value *)\n       |-- wp \u03c1 (Sreturn (Some e)) Q.\n\n    Axiom wp_return_frame : forall \u03c1 rv (Q Q' : Kpred),\n        match rv with\n        | None => Q ReturnVoid -* Q' ReturnVoid\n        | Some _ =>\n          (* NOTE unsound in the presence of exceptions *)\n          Forall v, Q (ReturnVal v) -* Q' (ReturnVal v)\n        end |-- wp \u03c1 (Sreturn rv) Q -* wp \u03c1 (Sreturn rv) Q'.\n\n    (** * Control flow: `break`, `continue` *)\n\n    Axiom wp_break : forall \u03c1 Q,\n        |> Q Break |-- wp \u03c1 Sbreak Q.\n    Axiom wp_break_frame : forall \u03c1 (Q Q' : Kpred),\n        Q Break -* Q' Break |-- wp \u03c1 Sbreak Q -* wp \u03c1 Sbreak Q'.\n\n    Axiom wp_continue : forall \u03c1 Q,\n        |> Q Continue |-- wp \u03c1 Scontinue Q.\n    Axiom wp_continue_frame : forall \u03c1 (Q Q' : Kpred),\n        Q Continue -* Q' Continue |-- wp \u03c1 Scontinue Q -* wp \u03c1 Scontinue Q'.\n\n    (** `switch` *)\n\n    (* compute the [Prop] that is known if this switch branch is taken *)\n    Definition wp_switch_branch (s : SwitchBranch) (v : Z) : Prop :=\n      match s with\n      | Exact i => v = i\n      | Range low high => low <= v <= high\n      end%Z.\n\n    (* This performs a syntactic check on [s] to ensure that there are no [case] or [default]\n       statements. This is used to avoid missing one of these statements which would compromise\n       the soundness of [wp_switch_block]\n     *)\n    Fixpoint no_case (s : Stmt) : bool :=\n      match s with\n      | Sseq ls => forallb no_case ls\n      | Sdecl _ => true\n      | Sif _ _ a b => no_case a && no_case b\n      | Swhile _ _ s => no_case s\n      | Sfor _ _ _ s => no_case s\n      | Sdo s _ => no_case s\n      | Sattr _ s => no_case s\n      | Sswitch _ _ _ => true\n      | Scase _\n      | Sdefault => false\n      | Sbreak\n      | Scontinue\n      | Sreturn _\n      | Sexpr _\n      | Sasm _ _ _ _ _ => true\n      | Slabeled _ s => no_case s\n      | Sgoto _ => true\n      | Sunsupported _ => false\n      end.\n\n    Fixpoint get_cases (ls : list Stmt) : list SwitchBranch :=\n      match ls with\n      | Scase sb :: ls =>\n        sb :: get_cases ls\n      | _ :: ls => get_cases ls\n      | nil => nil\n      end.\n\n    Definition default_from_cases (ls : list SwitchBranch) (v : Z) : Prop :=\n      (fold_right (fun sb P => ~wp_switch_branch sb v /\\ P) True ls).\n\n\n    (** apply the [wp] calculation to the body of a switch\n\n        NOTE that the semantics of [switch] statements is *very* conservative in the\n        current setup. In particular.\n\n          1. We do not support using a [case] to jump over a variable declaration\n          2. We do not support [case] statements that jump into the bodies of loops,\n             i.e. Duft's device.\n\n        Supporting 1 should not be difficult in principle.\n        Full support for 2 seems to require a more sophisticated setup for [wp].\n        In other work, this sort of thing is handled as essentially unstructured\n        programs.\n\n        We interpret the semantics of [wp_switch_block] by el\n     *)\n    Fixpoint wp_switch_block (Ldef : option (Z -> Prop)) (ls : list Stmt)\n      : option (list ((Z -> Prop) * list Stmt)) :=\n      match ls with\n      | Scase sb :: ls =>\n        (fun x => (wp_switch_branch sb, ls) :: x) <$> wp_switch_block Ldef ls\n      | Sdefault :: ls =>\n        match Ldef with\n        | None =>\n          (* NOTE in this case there were multiple [default] statements which is\n             not legal *)\n          None\n        | Some def =>\n          (fun x => (def, ls) :: x) <$> wp_switch_block None ls\n        end\n      | Sdecl _ :: ls' =>\n        (* NOTE this check ensures that we never case past a declaration which\n           could be problematic from a soundness point of view.\n         *)\n        if no_case (Sseq ls') then\n          wp_switch_block Ldef ls'\n        else\n          None\n      | s :: ls' =>\n        if no_case s then\n          wp_switch_block Ldef ls'\n        else\n          None\n      | nil =>\n        match Ldef with\n        | None => Some nil\n        | Some def => Some ((def, nil) :: nil)\n        end\n      end.\n\n    Definition Kswitch (k : Kpred) : Kpred :=\n      KP (fun rt =>\n            match rt with\n            | Break => k Normal\n            | rt => k rt\n            end).\n\n    Axiom wp_switch_decl : forall \u03c1 d e ls Q,\n        wp \u03c1 (Sseq (Sdecl (d :: nil) :: Sswitch None e ls :: nil)) Q\n        |-- wp \u03c1 (Sswitch (Some d) e ls) Q.\n\n    (* An error to say that a `switch` block with [body] is not supported *)\n    Record switch_block (body : list Stmt) : Prop := {}.\n\n    Axiom wp_switch : forall \u03c1 e b Q,\n        match wp_switch_block (Some $ default_from_cases (get_cases b)) b with\n        | None => UNSUPPORTED (switch_block b)\n        | Some cases =>\n          wp_operand tu \u03c1 e (fun v free => interp free $\n                    Exists vv : Z, [| v = Vint vv |] **\n                    [\u2227list] x \u2208 cases, [| x.1 vv |] -* wp_block \u03c1 x.2 (Kswitch Q))\n        end\n        |-- wp \u03c1 (Sswitch None e (Sseq b)) Q.\n\n    (* note: case and default statements are only meaningful inside of [switch].\n     * this is handled by [wp_switch_block].\n     *)\n    Axiom wp_case : forall \u03c1 sb Q, Q Normal |-- wp \u03c1 (Scase sb) Q.\n    Axiom wp_default : forall \u03c1 Q, Q Normal |-- wp \u03c1 Sdefault Q.\n\n  End with_resolver.\n\n  (* ideally, we would like to use the following line, but [cbn] does not seem to\n       like the !.\n      Arguments wp_decl_var _ _ _ _ !_ _ /. *)\n  #[global] Arguments wp_decl_var _ _ _ _ _ _ _ _ _ /.\n  #[global] Arguments wp_decl _ _ _ _ _ _ _ /. (* ! should occur on [d] *)\n\nEnd Stmt.\n\nDeclare Module S : Stmt.\n\nExport S.\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/stmt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17975274897821938}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import ITreeLang.\nRequire Import ITreeLib.\n\nSet Implicit Arguments.\n\n\nLemma intro_choose_sim_itree (v: Const.t):\n  sim_itree eq\n            (Ret tt)\n            (ITree.trigger MemE.choose;; Ret tt).\nProof.\n  unfold trigger. rewrite bind_vis.\n  pcofix CIH. ii. pfold. ii. splits; i.\n  { inv TERMINAL_TGT. ss. }\n  { right. esplits; eauto.\n    rewrite sim_local_promises_bot; eauto.\n  }\n  ii. right.\n  inv STEP_TGT; ss.\n  - (* internal *)\n    exploit sim_local_internal; eauto. i. des.\n    esplits; try apply GL2; eauto. inv LOCAL0; ss.\n  - (* choose *)\n    inv LOCAL0; dependent destruction STATE.\n    esplits; [|refl|econs 1|..]; ss.\n    left. rewrite bind_ret_l. eapply paco9_mon; [apply sim_itree_ret|]; ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/IntroChoose.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.17975274181177028}}
{"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.\nFrom cap_machine.rules Require Import rules_base rules_Mov.\n\nSection fundamental.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3} {sealsg: sealStoreG \u03a3}\n          {nainv: logrel_na_invs \u03a3}\n          `{MachineParameters}.\n\n  Notation D := ((leibnizO Word) -n> iPropO \u03a3).\n  Notation R := ((leibnizO Reg) -n> iPropO \u03a3).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma mov_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst : RegName) (src : Z + RegName) (P : D):\n    ftlr_instr r p b e a w (Mov dst src) P.\n  Proof.\n    intros Hp Hsome i Hbae Hi.\n    iIntros \"#IH #Hinv #Hinva #Hreg #Hread 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_Mov with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec; cycle 1.\n    { iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[Ha HP]\"); [iExists w; iFrame|iModIntro]. iNext.\n      iIntros \"_\".\n      iApply wp_value; auto. iIntros; discriminate. }\n    { (* TODO: it might be possible to refactor the proof below by using more simplify_map_eq *)\n      (* TODO: use incrementPC_inv *)\n      match goal with\n      | H: incrementPC _ = Some _ |- _ => apply incrementPC_Some_inv in H as (p''&b''&e''&a''& ? & HPC & Z & Hregs')\n      end. simplify_map_eq.\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[Ha HP]\"); [iExists w; iFrame|iModIntro].\n      iNext.\n      destruct (reg_eq_dec dst PC).\n      { subst dst. rewrite lookup_insert in HPC. inv HPC.\n        repeat rewrite insert_insert.\n        destruct src; simpl in *; try discriminate.\n        destruct (reg_eq_dec PC r0).\n        { subst r0. simplify_map_eq.\n          iIntros \"_\".\n          iApply (\"IH\" $! r with \"[%] [] [Hmap] [$Hown]\"); try iClear \"IH\"; eauto.\n          iModIntro. rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->]; iFrame \"Hinv\". }\n        { simplify_map_eq.\n          iDestruct (\"Hreg\" $! r0 _ _ H0) as \"Hr0\".\n          destruct (PermFlowsTo RX p'') eqn:Hpft; iIntros \"_\".\n          - iApply (\"IH\" $! r with \"[%] [] [Hmap] [$Hown]\"); try iClear \"IH\"; eauto.\n            + iModIntro.\n              destruct p''; simpl in Hpft; try discriminate; repeat (rewrite fixpoint_interp1_eq); simpl; auto.\n          - iApply (wp_bind (fill [SeqCtx])).\n            iDestruct ((big_sepM_delete _ _ PC) with \"Hmap\") as \"[HPC Hmap]\"; [apply lookup_insert|].\n            iApply (wp_notCorrectPC with \"HPC\"); [eapply not_isCorrectPC_perm; destruct p''; simpl in Hpft; try discriminate; eauto|].\n            iNext. iIntros \"HPC /=\".\n            iApply wp_pure_step_later; auto.\n            iNext; iIntros \"_\".\n            iApply wp_value.\n            iIntros. discriminate. } }\n      { rewrite lookup_insert_ne in HPC; auto.\n        rewrite lookup_insert in HPC. inv HPC.\n        iIntros \"_\".\n        iApply (\"IH\" $! (<[dst:=w0]> _) with \"[%] [] [Hmap] [$Hown]\"); eauto.\n        - intros; simpl.\n          rewrite lookup_insert_is_Some.\n          destruct (reg_eq_dec dst x0); auto; right; split; auto.\n          rewrite lookup_insert_is_Some.\n          destruct (reg_eq_dec PC x0); auto; right; split; auto.\n       - iIntros (ri v Hri Hvs).\n          destruct (reg_eq_dec ri dst).\n          + subst ri. rewrite lookup_insert in Hvs.\n            destruct src; simplify_map_eq.\n            * repeat rewrite fixpoint_interp1_eq; auto.\n            * destruct (reg_eq_dec PC r0).\n              { subst r0.\n                - simplify_map_eq.\n                  rewrite !fixpoint_interp1_eq /=.\n                destruct Hp as [Hp | Hp]; subst p''; try subst g'';\n                  (iFrame \"Hinv Hexec\"). }\n              simplify_map_eq.\n              iDestruct (\"Hreg\" $! r0 _ _ H0) as \"Hr0\". auto.\n          + repeat rewrite lookup_insert_ne in Hvs; auto.\n            iApply \"Hreg\"; auto.\n        - iModIntro. rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->]; iFrame \"Hinv\".\n      }\n    }\n    Unshelve. all: auto.\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/Mov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.1796691415782667}}
{"text": "Require Import List Ascii. \nRequire Import Ynot.\nRequire Import IO Net.\n\n(* todo what does Warning: Trying to mask the absolute name \"IO\" mean *)\n\nOpen Local Scope hprop_scope.\nOpen Local Scope stsepi_scope.\n\nSet Implicit Arguments.\n\nLtac rwpack X H := idtac;\n  match X with\n    | [_]%inhabited => idtac\n    | _ =>\n      match goal with\n        | [ H' : X = [_]%inhabited |- _ ] => rewrite -> H' in H\n        | [ H' : [_]%inhabited = X |- _ ] => rewrite -> H' in H\n      end\n  end.\n\nLtac rcombine := idtac;\n  match goal with\n    | [ H : (inhabit_unpack ?X _) = [_]%inhabited |- _ ] =>\n      rwpack X H; simpl in H; rewrite <- (pack_injective H)\n    | [ H : (inhabit_unpack2 ?X ?Y _) = [_]%inhabited |- _ ] =>\n      rwpack X H; rwpack Y H; simpl in H; rewrite <- (pack_injective H)\n  end.\n\nModule Type EXECPARAMS.\n\n  Parameter ccorrect : forall (req : list ascii), Trace -> Prop.\n  Parameter reply : list ascii -> list ascii -> Prop.\n\n  Parameter io : forall (req : list ascii) (tr : [Trace]),\n    STsep (tr ~~ traced tr)\n          (fun r:(list ascii * [Trace])=> tr ~~ tr' :~~ (snd r) in traced (tr' ++ tr) * [reply req (fst r)] * [ccorrect req tr']).\n\nEnd EXECPARAMS.\n\nModule ExecModel(A : EXECPARAMS).\n  Export A.\n\n  (* This correctness criteria says that we respond\n     to correct requests *)\n  Inductive correct (local: Net.SockAddr) : IO.Trace -> Prop :=\n  | NilCorrect   : correct local nil\n  | ConsCorrect  : forall remote past interim req resp, reply req resp -> correct local past ->\n    ccorrect req interim -> correct local (UDP.Sent local remote resp :: interim ++ UDP.Recd local remote req :: past).\n\n  (* A type for an exec server loop. *)\n  Definition exec_server_t local := IO.server_t (correct local) (NilCorrect local).\n\nEnd ExecModel.\n\nLemma nil_cons_app : forall (A : Type) (l2 : list A) (a : A) (l1 : list A),\n  (l1 ++ a :: nil) ++ l2 = l1 ++ a :: l2.\n  induction l1; auto. simpl. rewrite IHl1. auto.\nQed.\n\nModule ExecImpl(A : EXECPARAMS).\n  Module A := A.\n  Module AL := ExecModel(A).\n  Import AL.\n  Import A.\n\n  Definition iter : forall (local: Net.SockAddr) (tr: [IO.Trace]),\n    STsep (tr ~~ IO.traced tr * [correct local tr]) \n          (fun r:[IO.Trace] => tr ~~ r ~~ [correct local (r ++ tr)] * [r <> nil] * IO.traced (r ++ tr)).\n(**\n            Exists remote :@ Net.SockAddr, Exists s :@ list ascii, Exists rp :@ list ascii, Exists it :@ Trace, [reply s rp] *\n            [r = Net.UDP.Sent local remote rp :: it ++ Net.UDP.Recd local remote s :: nil] * IO.traced (r ++ tr)).\n**)\n  refine (fun local tr =>\n    x <- Net.UDP.recv local tr <@> _;\n    rtr <- io (snd x) (tr ~~~ UDP.Recd local (fst x) (snd x) :: tr) <@> _;\n    UDP.send local (fst x) (fst rtr)\n        (inhabit_unpack2 tr (snd rtr) (fun tr it => it ++ UDP.Recd local (fst x) (snd x) :: tr)) <@> _;;\n    {{Return (inhabit_unpack (snd rtr) (fun it => UDP.Sent local (fst x) (fst rtr) :: it ++ UDP.Recd local (fst x) (snd x) :: nil))}}).\n  solve [ inhabiter; unpack_conc; canceler; sep fail auto ].\n  solve [ sep fail auto ].\n  solve [ inhabiter; unpack_conc; repeat rcombine; canceler; sep fail auto ].\n  solve [ sep fail auto ].\n  inhabiter; unpack_conc; destruct (pack_type_inv (snd rtr)); repeat rcombine. simpl. rewrite H2. inhabiter. rewrite <- (pack_injective H3). canceler. sep fail auto.\n  solve [ sep fail auto ].\n  solve [ sep fail auto ].\n  intros; inhabiter; unpack_conc. destruct (pack_type_inv (snd rtr)). rewrite H3. simpl. intro_pure. rewrite H4 in H. repeat rcombine. rewrite <- (pack_injective H).\n    simpl. rewrite nil_cons_app. canceler.\n    sep fail ltac:(auto; try constructor; auto; try discriminate).\nQed.\n\nDefinition main : forall (local: Net.SockAddr),\n  STsep (traced nil)\n        (fun _:unit => Exists t :@ Trace, traced t).\n  refine (fun local => \n    xxx <- IO.forever\n             (fun t => [correct local t])\n             (fun t => {{ iter local t }})\n             [nil];\n   {{Return tt}});\n  sep fail ltac:(auto; try constructor).\nQed.\n\nEnd ExecImpl.\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/servers/UdpServer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17958974081446405}}
{"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(*|\nAADL Threads\n============\n\n.. coq:: none\n|*)\n\n(** Coq Library *)\nRequire Import List.\nImport ListNotations. (* from List *)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Bool.Sumbool.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.ZArith.ZArith.\nImport IfNotations.\n\n(** Oqarina library *)\nRequire Import Oqarina.coq_utils.all.\n\nRequire Import Oqarina.core.all.\nImport NaturalTime.\nRequire Import Oqarina.AADL.Kernel.all.\nRequire Import Oqarina.AADL.property_sets.all.\n\nRequire Import Oqarina.AADL.declarative.all.\nRequire Import Oqarina.AADL.instance.all.\nRequire Import Oqarina.AADL.behavior.port_variable.\n\nRequire Import Oqarina.formalisms.DEVS.parallel.all.\nRequire Import Oqarina.formalisms.all.\n\nImport AADL_Notations.\nOpen Scope aadl_scope.\n\nOpen Scope nat_scope.\n\n(*|\nThread State Variable\n---------------------\n\nEach AADL thread is associated to a state variable that stores the relevant parameters relative to is dispatch and scheduling by the underlying executive.\n\n.. coq:: none\n|*)\n\nSection Thread_State_Variable.\n\n(*|\n:coq:`Build_Dispatch_Trigger` returns the list of triggering features\n|*)\n\nDefinition Build_Dispatch_Trigger (l : list feature) :=\n  filter Is_Triggering_Feature l.\n  (* XXX should use also property Dispatch\\_Trigger *)\n\nInductive thread_state := Not_Activated | Idle | Ready | Running.\n\n(*|\n:coq:`thread_state_variable` defines the general state variable that stores\nthe current state of a thread. Its is made of a static part that is derived\nfrom the AADL model, and a dynamic part that is the current state used in the simulation. It is associated with a constructor :coq:`mk_thread_state_variable` and a well-formedness predicate.\n|*)\n\nRecord thread_state_variable : Type := {\n  (* static configuration parameters derived from AADL thread component *)\n  dispatch_protocol : Dispatch_Protocol;\n  period : Time;\n  deadline : AADL_Time;\n  priority : Z;\n  dispatch_able : bool;\n  wcet : Time;\n\n  (* dynamic status *)\n  clock : Time; (* clock with reset for evaluating dispatch *)\n  cet : Time;   (* execution time clock *)\n  delta_cet : Time ;\n  current_state : thread_state;\n  next_dispatch_time : Time;\n  input_ports : list port_variable;\n  output_ports : list port_variable;\n  dispatch_trigger : list feature;\n}.\n\n(*|\n* :coq:`mk_thread_state_variable` maps an AADL component to a :coq:`thread_state_variable`.\n|*)\n\nDefinition mk_thread_state_variable (t : component) : thread_state_variable := {|\n  dispatch_protocol := Map_Dispatch_Protocol (t->properties);\n  period := (Z.to_nat (Map_Period (t->properties))) ;\n  priority := Map_Priority (t->properties);\n  deadline := Map_Deadline (t->properties);\n  dispatch_able := Map_Dispatch_Able (t->properties);\n  wcet := Z.to_nat (snd (Map_Compute_Execution_Time (t->properties)));\n\n  clock := Zero;\n  cet := Zero;\n  delta_cet := Zero;\n  next_dispatch_time := Zero;\n  current_state := Not_Activated;\n  input_ports := Build_Input_Port_Variables (t->features);\n  output_ports := Build_Output_Port_Variables (t->features);\n  dispatch_trigger := Build_Dispatch_Trigger (t->features);\n|}.\n\n(*|\n:coq:`Compute_Entrypoint` defines the compute entrypoint of a thread.\n|*)\n\nDefinition Compute_Entry_Point := thread_state_variable -> thread_state_variable.\n\nDefinition Default_Compute_Entry_Point : Compute_Entry_Point :=\n  (fun x => x).\n\n(*|\n.. coq:: none\n|*)\n\n  Definition thread_state_variable_wf (t : thread_state_variable) :=\n    t.(dispatch_protocol) <> Unspecified_Dispatch_Protocol /\\\n    port_variable_list_wf t.(input_ports) /\\\n    port_variable_list_wf t.(output_ports)\n    .\n\n  Lemma thread_state_variable_wf_dec : forall t : thread_state_variable,\n    dec_sumbool (thread_state_variable_wf t).\n  Proof.\n    intros.\n    unfold thread_state_variable_wf.\n    repeat apply dec_sumbool_and.\n    - destruct (Dispatch_Protocol_eq_dec (dispatch_protocol t) Unspecified_Dispatch_Protocol).\n      * subst. auto.\n      * subst. auto.\n    - apply port_variable_list_wf_dec.\n    - apply port_variable_list_wf_dec.\n  Qed.\n\n(*|\n.. coq:: none\n|*)\n\nEnd Thread_State_Variable.\n\nLtac prove_thread_state_variable_wf :=\n  repeat match goal with\n    | |- thread_state_variable_wf _ => compute; repeat split; auto\n    | |- ( _ = Unspecified_Dispatch_Protocol -> False) => discriminate\n    | |- ( _ = Unspecified_Overflow_Handling_Protocol -> False) => discriminate\n    | |- ( _ = Unspecified_Dequeue_Protocol -> False) => discriminate\n    | |- NoDup  _  => apply NoDup_cons ; auto\n    | |- NoDup nil => apply NoDup_nil\n  end.\n\n(*|\nThread Dispatching\n------------------\n\nThis section captures the content of %\\S 5.4.2 of \\cite{as2-cArchitectureAnalysisDesign2017}%. Ultimately, we want to provide a definition of the :coq:`Enabled` function that controls the dispatch of a thread. The definition of this function relies on the state of some of its triggering features. In the following, we use directly the concept of thread state variable and port variables to define :coq:`Enabled` .\n\n.. coq:: none\n|*)\n\nSection AADL_Dispatching.\n\n(*|\nIntermediate Predicates\n^^^^^^^^^^^^^^^^^^^^^^^\n\nAll AADL dispatch protocols review the state of triggering features and the current clock. We build the :coq:`Thread_Has_Activated_Triggering_Feature` predicate as a conjunction of more basic predicates, in :coq:`Prop`, and demonstrate their decidability.\n\nFirst, we check whether the feature is activated, :coq:`Is_Feature_Activated`, then whether it is in the dispatch trigger, in :coq:`Feature_In_Dispatch_Trigger`.\n|*)\n\nDefinition Is_Feature_Activated (p : port_variable) :=\n  ~ PortQueue.Is_Empty p.(outer_variable).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Is_Feature_Activated_dec :\n  forall (p : port_variable),\n    { Is_Feature_Activated p } + { ~ Is_Feature_Activated p }.\nProof.\n  prove_dec.\nDefined.\n\n(*||*)\n\nDefinition Feature_In_Dispatch_Trigger (p : port_variable) (d : list feature) :=\n  In p.(port) d.\n\n(*|\n.. coq:: none\n|*)\n\nDefinition Feature_In_Dispatch_Trigger_dec :\n  forall (p : port_variable) (d : list feature),\n    dec_sumbool (Feature_In_Dispatch_Trigger p d).\nProof.\n  prove_dec.\nDefined.\n\n(*|\nFrom that point, we can build :coq:`Thread_Has_Activated_Triggering_Feature` that is true iff. the thread has at least one activated triggering feature that is also in the dispatch trigger.\n|*)\n\nDefinition Is_Activated_Triggering_Feature (p : port_variable)  (d : list feature) :=\n  Is_Feature_Activated p /\\ Feature_In_Dispatch_Trigger p d.\n\n(*|\n.. coq:: none\n|*)\n\nLemma Is_Activated_Triggering_Feature_dec:\n  forall (p : port_variable)  (d : list feature),\n    dec_sumbool (Is_Activated_Triggering_Feature p d).\nProof.\n  generalize Is_Feature_Activated_dec.\n  prove_dec.\nDefined.\n\nDefinition Is_Activated_Triggering_Feature_b (p : port_variable)  (d : list feature) :=\n  if Is_Activated_Triggering_Feature_dec p d is (left _) then true else false.\n\n(*||*)\n\nDefinition Has_Activated_Triggering_Feature\n  (l : list port_variable) (d : list feature)\n:=\n  All_Or (fun x => (Is_Activated_Triggering_Feature x d)) l.\n\n(*|\n.. coq:: none\n|*)\n\nLemma Has_Activated_Triggering_Feature_dec :\n  forall (l : list port_variable) (d : list feature),\n    { Has_Activated_Triggering_Feature l d } + { ~ Has_Activated_Triggering_Feature l d }.\nProof.\n  intros.\n  unfold Has_Activated_Triggering_Feature.\n  induction l.\n  - auto.\n  - unfold All_Or. apply dec_sumbool_or.\n    * apply Is_Activated_Triggering_Feature_dec.\n    * apply IHl.\nDefined.\n\n(*||*)\n\nDefinition Thread_Has_Activated_Triggering_Feature\n  (th : thread_state_variable)\n  :=\n  Has_Activated_Triggering_Feature th.(input_ports) th.(dispatch_trigger).\n\n(*|\n.. coq:: none\n|*)\n\n  Lemma Thread_Has_Activated_Triggering_Feature_dec :\n    forall (th : thread_state_variable),\n      { Thread_Has_Activated_Triggering_Feature th } +\n      { ~ Thread_Has_Activated_Triggering_Feature th }.\n  Proof.\n    generalize Has_Activated_Triggering_Feature_dec.\n    prove_dec.\n  Defined.\n\n(*|\nDefinition of :coq:`Enabled`\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFrom the previous definitions, we can now define the :coq:`Enabled` function that returns :coq:`true` when a thread is dispatched.\n\nA thread can be enable if it is \"dispatchable\". Then, we define basic predicates for each dispatch protocol.\n|*)\n\nDefinition Thread_Dispatchable (th : thread_state_variable) :=\n  (th.(dispatch_able) = true).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Thread_Dispatchable_dec:\n  forall (th : thread_state_variable),\n    { Thread_Dispatchable th } + { ~  Thread_Dispatchable th }.\nProof.\n  prove_dec.\nDefined.\n\n(*||*)\n\nDefinition Periodic_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th) /\\ (th.(clock) mod th.(period) = 0).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Periodic_Enabled_dec:\n  forall (th : thread_state_variable),\n   { Periodic_Enabled th } + { ~ Periodic_Enabled th }.\nProof.\n  prove_dec.\n  apply PeanoNat.Nat.eq_dec.\nDefined.\n\n(*||*)\n\nDefinition Aperiodic_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th) /\\\n    (Thread_Has_Activated_Triggering_Feature th).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Aperiodic_Enabled_dec:\n  forall (th : thread_state_variable),\n   { Aperiodic_Enabled th } + { ~ Aperiodic_Enabled th  }.\nProof.\n  prove_dec.\n  apply Thread_Has_Activated_Triggering_Feature_dec.\nDefined.\n\n(*||*)\n\nDefinition Sporadic_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th) /\\\n    th.(next_dispatch_time) <= th.(clock) /\\\n   (* th.(period) <= th.(clock) /\\ *)\n    Thread_Has_Activated_Triggering_Feature th.\n\n(*|\n.. coq:: none\n|*)\n\nLemma Sporadic_Enabled_dec:\n  forall (th : thread_state_variable),\n    { Sporadic_Enabled th } + { ~ Sporadic_Enabled th }.\nProof.\n  generalize Thread_Has_Activated_Triggering_Feature_dec.\n  generalize Compare_dec.le_dec.\n  prove_dec.\nDefined.\n\n(*||*)\n\nDefinition Timed_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th) /\\\n  ((th.(period) = th.(clock)) \\/\n  Thread_Has_Activated_Triggering_Feature th).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Timed_Enabled_dec:\n  forall (th : thread_state_variable),\n  { Timed_Enabled th } + { ~ Timed_Enabled th }.\nProof.\n  prove_dec.\n  apply PeanoNat.Nat.eq_dec.\n  apply Thread_Has_Activated_Triggering_Feature_dec.\nDefined.\n\n(*||*)\n\nDefinition Hybrid_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th) /\\ (th.(period) = th.(clock)) /\\\n  Thread_Has_Activated_Triggering_Feature th.\n\n(*|\n.. coq:: none\n|*)\n\nLemma Hybrid_Enabled_dec:\n  forall (th : thread_state_variable),\n    { Hybrid_Enabled th } + { ~ Hybrid_Enabled th }.\nProof.\n  prove_dec.\n  apply PeanoNat.Nat.eq_dec.\n  apply Thread_Has_Activated_Triggering_Feature_dec.\nDefined.\n\n(*||*)\n\nDefinition Background_Enabled (th : thread_state_variable) :=\n  (Thread_Dispatchable th).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Background_Enabled_dec:\n  forall (th : thread_state_variable),\n  { Background_Enabled th } + { ~ Background_Enabled th }.\nProof.\n  prove_dec.\nDefined.\n\n(*|\nThen we define the :coq:`Enabled` predicate\n|*)\n\nDefinition Enabled (th : thread_state_variable) :=\n  match th.(dispatch_protocol) with\n  | Periodic => Periodic_Enabled th\n  | Sporadic => Sporadic_Enabled th\n  | Aperiodic => Aperiodic_Enabled th\n  | Timed => Timed_Enabled th\n  | Hybrid => Hybrid_Enabled th\n  | Background => Background_Enabled th\n  | Unspecified_Dispatch_Protocol => False\n  end.\n\n(*|\n.. coq:: none\n|*)\n\nLemma Enabled_dec: forall (th : thread_state_variable),\n  dec_sumbool (Enabled th).\nProof.\n  generalize Periodic_Enabled_dec.\n  generalize Sporadic_Enabled_dec.\n  generalize Aperiodic_Enabled_dec.\n  generalize Background_Enabled_dec.\n  generalize Timed_Enabled_dec.\n  generalize Hybrid_Enabled_dec.\n  prove_dec.\nDefined.\n\n(*||*)\n\n  (** :coq:`Enabled_oracle` return a :coq:`bool` as a witness, for debugging purposes. *)\n\n  Definition Enabled_oracle (th : thread_state_variable) :=\n    if Enabled_dec th is (left _) then true else false.\n\n(*|\n.. coq:: none\n|*)\n\nEnd AADL_Dispatching.\n\n(*|\nPorts Queue Processing\n----------------------\n\nThe following is a first cut at formalizing ports from %\\S 8.3%. We capture the definition of :coq:`Frozen` for ports. First, we build ATF, the list of Activated Triggering Features.\n\n- :coq:`Activated_Triggering_Features` returns the list of Activated Triggering Features.\n|*)\n\nDefinition Activated_Triggering_Features'  (l : list port_variable) (d : list feature) :=\n  filter (fun x => Is_Activated_Triggering_Feature_b x d) l.\n\nDefinition Activated_Triggering_Features (th : thread_state_variable) :=\n  Activated_Triggering_Features' th.(input_ports) th.(dispatch_trigger).\n\n(*|\nThen, we can define the :coq:`Get_Elected_Triggering_Feature` that returns the elected features among Activated Triggering Features.\n|*)\n\nDefinition Get_Elected_Triggering_Feature (th : thread_state_variable) :=\n  Get_Port_Variable_With_Max_Urgency Invalid_Port_Variable\n      (Activated_Triggering_Features th).\n\n(*|\n:coq:`Current_Valid_IO_Time_Spec` returns the current IO_Time_Spec for the considered port variable. A port variable can be associated with a list of IO_Time_Spec. The current IO_Time_Spec denotes the IO_Time_Spec that is current to the thread state. %\\change{This version is highly simplified. We should define this in the standard first}%\n|*)\n\nDefinition Current_Valid_IO_Time_Spec\n  (p : port_variable)\n  (th : thread_state_variable)\n:=\n  hd Unspecified_IO_Time_Spec (projectionIO_Time_Spec p.(port_input_times)).\n\n(*|\nThe definition of the :coq:`Frozen` predicate relies on the previous definitions. A port variable is frozen based on the current thread state, the port IO_Time_Spec, etc.\n|*)\n\nDefinition Dispatch_Frozen (p : port_variable) (th : thread_state_variable) :=\n   (p = Get_Elected_Triggering_Feature  th) \\/\n       ~ (Feature_In_Dispatch_Trigger p th.(dispatch_trigger)).\n\n(*|\n.. coq:: none\n|*)\n\nLemma Dispatch_Frozen_dec:\n  forall p th, { Dispatch_Frozen p th } + { ~ Dispatch_Frozen p th }.\nProof.\n  generalize port_variable_eq_dec.\n  prove_dec.\nDefined.\n\n(*||*)\n\nDefinition Frozen (p : port_variable) (th : thread_state_variable) : Prop :=\n  match Current_Valid_IO_Time_Spec p th with\n  | Dispatch => Dispatch_Frozen p th\n  | NoIo => False\n  | Start _ => False\n  | Completion _ => False\n  | Unspecified_IO_Time_Spec => False\n  end.\n\nLemma Frozen_dec: forall p th,  { Frozen p th } + { ~ Frozen p th }.\nProof.\n  generalize Dispatch_Frozen_dec.\n  prove_dec.\nDefined.\n\nFixpoint Freeze_Port_Variables\n  (l : list port_variable)\n  (th : thread_state_variable)\n:=\n  match l with\n  | [] => []\n  | h :: t => match Frozen_dec h th with\n              | left _ => Receive_Input__ h :: Freeze_Port_Variables t th\n              | right _ => h :: Freeze_Port_Variables t th\n              end\nend.\n\nDefinition Frozen_Ports' (th : thread_state_variable): list port_variable :=\n  filter_dec port_variable_wf port_variable_wf_dec th.(input_ports).\n\n(*|\nRuntime support for threads -- Private API\n-------------------------------------------\n\n.. coq:: none\n|*)\n\nSection Thread_RTS.\n\n(*|\nA collection of runtime services is provided. A runtime service manipulates the thread state and its port variables.\n\n:coq:`advance_time` increments the clock of the thread state variable.\n|*)\n\nDefinition advance_time (th : thread_state_variable) (t : Time) (n : Time) := {|\n  (* Generic part *)\n  dispatch_protocol := th.(dispatch_protocol);\n  period := th.(period);\n  deadline := th.(deadline);\n  priority := th.(priority);\n  dispatch_able := th.(dispatch_able);\n  wcet := th.(wcet);\n\n  input_ports := th.(input_ports);\n  output_ports := th.(output_ports);\n  dispatch_trigger := th.(dispatch_trigger);\n  current_state := th.(current_state);\n  next_dispatch_time := th.(next_dispatch_time);\n\n  (* advance_time *)\n  clock := t;\n  delta_cet := n;\n  cet := th.(cet);\n|}.\n\nDefinition freeze_thread_ports (th : thread_state_variable)  := {|\n  (* Generic part *)\n  dispatch_protocol := th.(dispatch_protocol);\n  period := th.(period);\n  deadline := th.(deadline);\n  priority := th.(priority);\n  dispatch_able := th.(dispatch_able);\n  wcet := th.(wcet);\n\n  clock := th.(clock);\n  delta_cet := th.(delta_cet);\n  cet := th.(cet);\n\n  output_ports := th.(output_ports);\n  dispatch_trigger := th.(dispatch_trigger);\n  current_state := th.(current_state);\n  next_dispatch_time := th.(next_dispatch_time);\n\n  (* freeze_ports *)\n  input_ports := Freeze_Port_Variables th.(input_ports) th;\n|}.\n\nDefinition reset_thread_ports (th : thread_state_variable)  := {|\n  (* Generic part *)\n  dispatch_protocol := th.(dispatch_protocol);\n  period := th.(period);\n  deadline := th.(deadline);\n  priority := th.(priority);\n  dispatch_able := th.(dispatch_able);\n  wcet := th.(wcet);\n\n  clock := th.(clock);\n  delta_cet := th.(delta_cet);\n  cet := th.(cet);\n\n  output_ports := th.(output_ports);\n  dispatch_trigger := th.(dispatch_trigger);\n  current_state := th.(current_state);\n  next_dispatch_time := th.(next_dispatch_time);\n\n  (* reset_thread_ports *)\n  input_ports := map Reset_Port_Variable th.(input_ports) ;\n|}.\n\nDefinition compute_during (th : thread_state_variable) (t : Time) := {|\n  (* Generic part *)\n  dispatch_protocol := th.(dispatch_protocol);\n  period := th.(period);\n  deadline := th.(deadline);\n  priority := th.(priority);\n  dispatch_able := th.(dispatch_able);\n  wcet := th.(wcet);\n\n  input_ports := th.(input_ports);\n  output_ports := th.(output_ports);\n  dispatch_trigger := th.(dispatch_trigger);\n  current_state := th.(current_state);\n  next_dispatch_time := th.(next_dispatch_time);\n\n  (* compute_during *)\n  clock := th.(clock) + t;\n  cet := th.(cet) + t;\n  delta_cet := t;\n|}.\n\n(*|\n:coq:`store_in` stores a value in an outer\\_port of an AADL thread.\n|*)\n\nDefinition store_in\n  (t : thread_state_variable) (name : identifier) (value : bool) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  current_state := t.(current_state);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* store_in *)\n  input_ports := Store t.(input_ports) name (t.(clock), value);\n|}.\n\n(*|\nXXX\n|*)\n\nDefinition eval_enabled_thread_state (t : thread_state_variable) :=\nlet is_enabled := Enabled_oracle t in {|\n(* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock); (* XXX should reset the clock if enabled *)\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  input_ports := t.(input_ports);\n\n  (* eval_enabled_thread_state *)\n  current_state := if is_enabled then Ready else t.(current_state);\n  next_dispatch_time :=\n    if is_enabled then\n      match t.(dispatch_protocol) with\n      | Periodic => t.(clock) + t.(period)\n      | Sporadic => t.(clock) + t.(period)\n      | _ => t.(clock)\n      end\n    else t.(next_dispatch_time);\n|}.\n\nDefinition nop (t : thread_state_variable) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  current_state := t.(current_state);\n  clock := t.(clock);\n  cet := t.(cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  input_ports := t.(input_ports);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* set_running *)\n  delta_cet := 0;\n|}.\n\nDefinition set_running (t : thread_state_variable) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  input_ports := t.(input_ports);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* set_running *)\n  current_state := Running;\n|}.\n\nDefinition set_Idle (t : thread_state_variable) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  input_ports := t.(input_ports);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* set_Idle *)\n  current_state := Idle;\n  cet := 0;\n|}.\n\n(*|\nRuntime support for threads -- AADL RTS\n---------------------------------------\n\nThe definition of the RTS relies on the port functions presented in XXX.\n\n* :coq:`Await_Dispatch`\n|*)\n\nDefinition await_dispatch (t : thread_state_variable) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  input_ports := t.(input_ports);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* await_dispatch *)\n  current_state := Idle;\n\n  cet := 0;\n  delta_cet := 0;\n|}.\n\n(*|\n* :coq:`Get_Count`\n|*)\n\nDefinition get_count (t : thread_state_variable) (name : identifier) :=\n  Get_Count t.(input_ports) name.\n\n(*|\n* :coq:`Put_Value`\n|*)\n\nDefinition put_value\n  (t : thread_state_variable) (name : identifier) (value : bool) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  input_ports := t.(input_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  current_state := t.(current_state);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* put_value *)\n  output_ports := Store t.(output_ports) name (t.(clock), value);\n|}.\n\n(*|\n* :coq:`Send_Output`\n|*)\n\nDefinition send_output (t : thread_state_variable) (name : identifier) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  input_ports := t.(input_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  current_state := t.(current_state);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* send_output *)\n  output_ports := Send_Output t.(output_ports) name;\n|}.\n\n(*|\n* :coq:`Get_Value`\n|*)\n\nDefinition get_value (t : thread_state_variable) (name : identifier) :=\n  Get_Value t.(input_ports) name.\n\n(*|\n* :coq:`Next_Value`\n|*)\n\nDefinition next_value\n  (t : thread_state_variable) (name : identifier) (value : bool) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  current_state := t.(current_state);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* next_value *)\n  input_ports := Next_Value t.(input_ports) name;\n|}.\n\n(*|\n* :coq:`Receive_Input`\n|*)\n\nDefinition receive_input (t : thread_state_variable) (name : identifier) := {|\n  (* Generic part *)\n  dispatch_protocol := t.(dispatch_protocol);\n  period := t.(period);\n  deadline := t.(deadline);\n  priority := t.(priority);\n  dispatch_able := t.(dispatch_able);\n  wcet := t.(wcet);\n\n  clock := t.(clock);\n  cet := t.(cet);\n  delta_cet := t.(delta_cet);\n  output_ports := t.(output_ports);\n  dispatch_trigger := t.(dispatch_trigger);\n  current_state := t.(current_state);\n  next_dispatch_time := t.(next_dispatch_time);\n\n  (* receive_input *)\n  input_ports := Receive_Input t.(input_ports) name;\n|}.\n\n(*|\n.. coq:: none\n|*)\n\nEnd Thread_RTS.\n\n(*|\nExamples\n--------\n\nA Periodic Thread\n^^^^^^^^^^^^^^^^^\n\nIn this example, we first build a periodic AADL :coq:`Component`, we then map it to a :coq:`thread_state_variable` and perform some steps on it.\n|*)\n\nExample A_Periodic_Thread :=\n    thread: \"a_periodic_thread\" ->| \"pack::a_thread_classifier.impl\"\n        features: nil\n        subcomponents: nil\n        connections: nil\n        properties: [\n            property: Priority_Name ==>| PV_Int 42 ;\n            property: Dispatch_Protocol_Name ==>| PV_Enum (Id \"Periodic\") ;\n            property: Period_Name ==>| PV_IntU 500 (PV_Unit (Id \"ms\")) ;\n            property: Compute_Execution_Time_Name ==>|\n                PV_IntRange (PV_IntU 0 (PV_Unit (Id \"ms\")))\n                            (PV_IntU 100 (PV_Unit (Id \"ms\")))\n        ].\n\n(*|\nThis component is well-formed\n|*)\n\nLemma A_Periodic_Thread_wf : Well_Formed_Component_Instance A_Periodic_Thread.\nProof.\n  prove_Well_Formed_Component_Instance.\nQed.\n\nDefinition A_Periodic_Thread_State_ := set_Idle (mk_thread_state_variable (A_Periodic_Thread)).\n\nCheck A_Periodic_Thread_State_.\n\nLemma A_Periodic_Thread_State_valid : thread_state_variable_wf A_Periodic_Thread_State_ .\nProof.\n  prove_thread_state_variable_wf.\nQed.\n\n(** - \"activate\" the thread *)\n\nDefinition A_Periodic_Thread_State :=\n  eval_enabled_thread_state A_Periodic_Thread_State_.\n\n(** - At t = 0, the periodic thread is enabled *)\n\nLemma Periodic_t0_enabled : A_Periodic_Thread_State.(current_state) = Ready.\nProof.\n  compute.\n  trivial.\nQed.\n\n(** - \"do something\" *)\n\nDefinition A_Periodic_Thread_State' := advance_time A_Periodic_Thread_State 2 0.\nDefinition A_Periodic_Thread_State'' := await_dispatch A_Periodic_Thread_State'.\n\n(** - At t = 2, the periodic thread is not enabled *)\n\nLemma Periodic_t2_not_enabled :\n  A_Periodic_Thread_State''.(current_state) = Idle.\nProof.\n  trivial.\nQed.\n\n(*|\nA Sporadic Thread\n^^^^^^^^^^^^^^^^^\n\nIn this example, we consider a sporadic thread with one input event port.\n|*)\n\nExample A_Sporadic_Thread :=\nthread: \"a_periodic_thread\" ->| \"pack::a_thread_classifier.impl\"\n    features: [\n      feature: in_event \"a_feature\"\n    ]\n\n    subcomponents: nil\n    connections: nil\n    properties: [\n        property: Priority_Name ==>| PV_Int 42 ;\n        property: Dispatch_Protocol_Name ==>| PV_Enum (Id \"Sporadic\") ;\n        property: Period_Name ==>| PV_IntU 500 (PV_Unit (Id \"ms\")) ;\n        property: Compute_Execution_Time_Name ==>|\n            PV_IntRange (PV_IntU 0 (PV_Unit (Id \"ms\")))\n                        (PV_IntU 100 (PV_Unit (Id \"ms\")))\n    ].\n\n(*|\nThis component is well-formed\n|*)\n\nLemma A_Sporadic_Thread_wf : Well_Formed_Component_Instance A_Sporadic_Thread.\nProof.\n  prove_Well_Formed_Component_Instance.\nQed.\n\n(*|\nWe can continue and build a corresponding thread state variable, add an event, avance time and check whether the thread is enabled.\n|*)\n\nDefinition A_Sporadic_Thread_State_ := set_Idle (mk_thread_state_variable (A_Sporadic_Thread)).\n\nLemma A_Sporadic_Thread_State_valid : thread_state_variable_wf A_Sporadic_Thread_State_.\nProof.\n  prove_thread_state_variable_wf.\nQed.\n\nDefinition A_Sporadic_Thread_State := eval_enabled_thread_state A_Sporadic_Thread_State_.\n\n(*|\nInitially, the sporadic thread is not enabled\n|*)\n\nLemma Sporadic_tO_not_enabled :\n  Enabled_oracle (A_Sporadic_Thread_State) = false.\nProof. trivial. Qed.\n\n(*|\nInject two events. Because of the DropOldest policy used, with a queue size of 1, we loose the first event\n|*)\n\nDefinition A_Sporadic_Thread_State' :=\n  store_in A_Sporadic_Thread_State (Id \"a_feature\") false.\nDefinition A_Sporadic_Thread_State'' :=\n  store_in A_Sporadic_Thread_State' (Id \"a_feature\") true.\n\n(** - The thread is not enabled yet *)\n\nLemma Sporatic_tO_not_enabled' :\n  A_Sporadic_Thread_State''.(current_state) = Idle.\nProof. trivial. Qed.\n\n(** - We advance time *)\nDefinition th_ := advance_time A_Sporadic_Thread_State'' 500 0.\nDefinition th := eval_enabled_thread_state th_.\n\n(** - The thread is enabled, and we can check frozen port *)\n\nLemma Sporadic_t500_enabled : th.(current_state) = Ready.\nProof. trivial. Qed.\n\nLemma ETF:\n  Get_Port_Variable_Name (Get_Elected_Triggering_Feature (th)) = Id \"a_feature\".\nProof. trivial. Qed.\n\nCompute Frozen_Ports' th.\n\n(* - At this stage, we have not called receive_input, no event available *)\n\nLemma get_count_1 : get_count th (Id \"a_feature\") = 0%nat.\nProof. trivial. Qed.\n\n(* - Calling receive input *)\n\nDefinition th_rec := receive_input th (Id \"a_feature\").\n\nLemma get_count_2 : get_count th_rec (Id \"a_feature\") = 1%nat.\nProof. trivial. Qed.\n\nLemma get_value_1 : get_value th_rec (Id \"a_feature\") = (0,true).\nProof. trivial. Qed.\n\n(*|\nAADL thread as a P-DEVS\n-----------------------\n\nLet us turn this thread into a P-DEVS.\n\n* :coq:`X_thread` is the set of incoming messages the P-DEVS reacts to.\n|*)\n\nInductive X_thread : Set :=\n| thread_step\n| eval_enabled  (clock: Time)\n| run_thread (clock : Time) (duration : Time)\n| store_message (clock : Time) (port_name : identifier) (value : bool)\n| time_advance (clock : Time)\n.\n\nDefinition Y_thread : Type := X_thread.\n\nDefinition Synchronization_Message_Type_thread :=\n    Synchronization_Message_Type X_thread Y_thread.\n\n(*|\n* :coq:`S_thread` is the state variable of the P-DEVS. It is the cross-product of a label denoting the state and the actual state varoable. XXX thread_state_variable also has the Ready/Idle/Run state, is this redundant ?\n|*)\n\nInductive S_thread_labels : Set :=\n    | performing_thread_activation\n    | suspended_awaiting_dispatch\n    | performing_thread_computation .\n\nRecord S_thread := {\n  thread_l : S_thread_labels ;\n  thread_st : thread_state_variable ;\n  thread_ce : Compute_Entry_Point;\n  }.\n\nDefinition Update_S_thread\n  (s : S_thread)\n  (label : S_thread_labels)\n  (tsv : thread_state_variable)\n:=\n {| thread_l := label ; thread_st := tsv; thread_ce := s.(thread_ce) |} .\n\nDefinition Q_thread : Type := Q S_thread.\n\nDefinition Q_init_thread\n  (tsv : thread_state_variable)\n  (tce : Compute_Entry_Point)\n  : Q_thread :=\n  {| st := {| thread_l := performing_thread_activation ;\n              thread_st := tsv;\n              thread_ce := tce ;\n              |} ;\n    e := Zero |}.\n\nDefinition Update_Q\n  (q : Q_thread)\n  (label : S_thread_labels)\n  (tsv : thread_state_variable)\n:=\n  {| st := Update_S_thread q.(st) label tsv ; e := q.(e) |}.\n\n(*|\n* :coq:`\u03b4int_thread` updates the internal state of the thread\n\n  - (1) if the thread is Idle, we evaluate its enabled function using eval_enabled_thread_state. If the thread is Ready, we enter the performing thread conputation\n\n  - (2) if the thread is Running, and if its compute execution time is equal to its WCET, the thread becomes suspended (external AADL state) and Idle .\n\n  - Otherwise, we keep the existing state\n|*)\n\nDefinition \u03b4int_thread (s : S_thread) : S_thread :=\n  match s.(thread_st).(current_state) with\n\n    | Not_Activated  => s\n\n    | Idle => (* (1) *)\n      let state' := eval_enabled_thread_state s.(thread_st) in\n        match state'.(current_state) with\n        | Ready =>\n          let state'' := freeze_thread_ports state' in\n            Update_S_thread s performing_thread_computation state''\n\n        | _ =>  s\n        end\n\n    | Running => (* (2) *)\n    (* XXX must split compute_entrypoint into parts: await/fetch/execute/write\nall atomic except execute\n\n    *)\n      let state := s.(thread_ce) s.(thread_st) in\n\n      if state.(wcet) <=? state.(cet) then\n      let state' := reset_thread_ports state in\n        {| thread_l := suspended_awaiting_dispatch ;\n           thread_st := set_Idle state' ;\n           thread_ce := s.(thread_ce) |}\n\n      else\n        {| thread_l := performing_thread_computation;\n           thread_st := state;\n           thread_ce := s.(thread_ce) |}\n\n    | Ready  => s\n  end.\n\n(*|\n* :coq:`\u03b4ext_thread` take into account incoming messages to update\nthe thread state.\n|*)\n\nDefinition \u03b4ext_thread (q : Q_thread) (x : list X_thread) : S_thread :=\n  match q.(st).(thread_l), hd_error x with\n\n    | performing_thread_activation, Some thread_step =>\n      let state' := await_dispatch q.(st).(thread_st) in\n        {| thread_l  := suspended_awaiting_dispatch ;\n          thread_st := state' ;\n          thread_ce := q.(st).(thread_ce) |}\n\n    | suspended_awaiting_dispatch, Some (eval_enabled c) =>\n      let state' := advance_time q.(st).(thread_st) c 0 in\n        {| thread_l := q.(st).(thread_l) ;\n          thread_st := state' ;\n          thread_ce := q.(st).(thread_ce) |}\n\n    |  _, Some (time_advance c) =>\n      let state' := advance_time q.(st).(thread_st) c 0 in\n        {| thread_l := q.(st).(thread_l) ;\n          thread_st := state' ;\n          thread_ce := q.(st).(thread_ce) |}\n\n    | performing_thread_computation, Some (run_thread c n) =>\n      let state := set_running q.(st).(thread_st) in\n      let state' := advance_time state c n in\n        {| thread_l := performing_thread_computation ;\n          thread_st := state' ;\n          thread_ce := q.(st).(thread_ce) |}\n\n    | _, Some (store_message c p m) =>\n      let state' := store_in q.(st).(thread_st) p m in\n        {| thread_l :=  q.(st).(thread_l);\n           thread_st := state' ;\n           thread_ce := q.(st).(thread_ce) |}\n\n    | _, _ =>\n    let state' := nop q.(st).(thread_st) in\n      {| thread_l :=  q.(st).(thread_l);\n        thread_st := state' ;\n        thread_ce := q.(st).(thread_ce) |}\n\nend.\n\nDefinition \u03b4con_thread  := Build_Default_\u03b4con \u03b4int_thread \u03b4ext_thread.\n\nDefinition Y_output_thread : Type := Y_output Y_thread.\n\nDefinition \u03bb_thread (s : S_thread) : list Y_output_thread :=\n  match s with\n    | _ => [ no_output Y_thread ]\n  end.\n\nDefinition ta_thread (s : S_thread) : Time :=\n  match s.(thread_l) with\n    | performing_thread_activation => Zero\n\n    | suspended_awaiting_dispatch =>\n      match s.(thread_st).(dispatch_protocol) with\n        | Periodic =>\n          s.(thread_st).(next_dispatch_time) + s.(thread_st).(delta_cet)\n          - s.(thread_st).(clock)\n\n        | Sporadic => s.(thread_st).(delta_cet)\n\n        | _ => Zero\n      end\n\n    (* XXX if periodic, OK, if sporadic, should be 0*)\n\n    | performing_thread_computation => s.(thread_st).(delta_cet)\n  end.\n\nDefinition thread_DEVS_type : Type :=\n    DEVS_Atomic_Model S_thread X_thread Y_thread.\n\nDefinition thread_DEVS_Simulator_Type : Type :=\n    DEVS_Simulator S_thread X_thread Y_thread.\n\nDefinition thread_DEVS\n  (t : component)\n  (ce : Compute_Entry_Point)\n  : thread_DEVS_type := {|\n  devs_atomic_id := t->id ;\n  Q_init := Q_init_thread (mk_thread_state_variable t) ce;\n\n  ta := ta_thread;\n  \u03b4int := \u03b4int_thread;\n  \u03bb  := \u03bb_thread;\n  \u03b4ext := \u03b4ext_thread;\n  \u03b4con := \u03b4con_thread;\n|}.\n\nDefinition thread_Initial\n  (t : component)\n  (ce : Compute_Entry_Point)\n:=\n  Instantiate_DEVS_Simulator (t->id) (thread_DEVS t ce).\n\n(*|\nPeriodic thread test\n^^^^^^^^^^^^^^^^^^^^\n\nTranslate DEVS to a LTS\n|*)\n\nDefinition Periodic_Compute_Entry_Point : Compute_Entry_Point :=\n  fun x : thread_state_variable =>\n    compute_during x x.(delta_cet).\n\nDefinition A_Periodic_initial :=\n  thread_Initial A_Periodic_Thread Periodic_Compute_Entry_Point.\n\nDefinition thread_LTS := LTS_Of_DEVS (A_Periodic_initial).\n\nExample thread_LTS_0 := Init thread_LTS.\n\n(*|\n* Step#0: we confirm the correct initialization of a thread\n|*)\n\nLemma thread_LTS_0_OK :\n    Print_DEVS_Simulator thread_LTS_0 =\n    dbg Zero Zero\n    {|\n      thread_l := performing_thread_activation;\n      thread_st :=\n        {|\n          dispatch_protocol := Periodic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 0;\n          cet := 0;\n          delta_cet := 0;\n          current_state := Not_Activated;\n          next_dispatch_time := 0;\n          input_ports := [];\n          output_ports := [];\n          dispatch_trigger := []\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#1: We perform a :coq:`thread_step` to activate the thread. Because of the activation time allows the thread to be dispatched, the thread directly enters the :coq:`performing_thread_computation` state. This is expected because of the confluence function that executes first the external transition, then the internal one.\n|*)\n\nExample thread_LTS_1 :=\n  step_lts thread_LTS_0\n    (xs Y_thread Parent Parent Zero [ thread_step ]).\n\nLemma thread_LTS_1_OK :\n    Print_DEVS_Simulator thread_LTS_1 =\n    dbg Zero Zero\n    {|\n      thread_l := performing_thread_computation;\n      thread_st :=\n        {|\n          dispatch_protocol := Periodic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 0;\n          cet := 0;\n          delta_cet := 0;\n          current_state := Ready;\n          next_dispatch_time := 500;\n          input_ports := [];\n          output_ports := [];\n          dispatch_trigger := []\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#2: we \"run\" the thread for 50 ms\n|*)\n\nExample thread_LTS_2 :=\n    step_lts thread_LTS_1\n    (xs Y_thread Parent Parent Zero [ run_thread 0 50 ]).\n\nLemma thread_LTS_2_OK :\n    Print_DEVS_Simulator thread_LTS_2 =\n    dbg 0 50\n    {|\n      thread_l := performing_thread_computation;\n      thread_st :=\n        {|\n          dispatch_protocol := Periodic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 50;\n          cet := 50;\n          delta_cet := 50;\n          current_state := Running;\n          next_dispatch_time := 500;\n          input_ports := [];\n          output_ports := [];\n          dispatch_trigger := []\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#3: we \"run\" the thread for another 50 ms to see it being completed and go back to :coq:`suspended_awaiting_dispatch` state.\n|*)\n\nExample thread_LTS_3 :=\n    step_lts thread_LTS_2 (xs Y_thread Parent Parent 50%nat [ run_thread 50 50%nat ]).\n\nLemma thread_LTS_3_OK :\n    Print_DEVS_Simulator thread_LTS_3 =\n    dbg 50%nat 500%nat\n    {|\n      thread_l := suspended_awaiting_dispatch;\n      thread_st :=\n        {|\n          dispatch_protocol := Periodic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 100; (* XXX *)\n          cet := 0;\n          delta_cet := 50;\n          current_state := Idle;\n          next_dispatch_time := 500;\n          input_ports := [];\n          output_ports := [];\n          dispatch_trigger := []\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\nExample thread_LTS_4 :=\n    step_lts thread_LTS_3\n    (xs Y_thread Parent Parent 500 [ eval_enabled 500 ]).\n\nLemma thread_LTS_4_OK :\n    Print_DEVS_Simulator thread_LTS_4 =\n    dbg 500 500\n    {|\n      thread_l := performing_thread_computation;\n      thread_st :=\n             {|\n               dispatch_protocol := Periodic;\n               period := 500;\n               deadline := 0%Z;\n               priority := 42;\n               dispatch_able := true;\n               wcet := 100;\n               clock := 500;\n               cet := 0;\n               delta_cet := 0;\n               current_state := Ready;\n               next_dispatch_time := 1000;\n               input_ports := [];\n               output_ports := [];\n               dispatch_trigger := []\n             |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\nExample thread_LTS_5 :=\n    step_lts thread_LTS_4 (xs Y_thread Parent Parent 500 [ run_thread 500 100%nat ]).\n\nLemma thread_LTS_5_OK :\n    Print_DEVS_Simulator thread_LTS_5 =\n    dbg 500 1000\n         {|\n           thread_l := suspended_awaiting_dispatch;\n           thread_st :=\n             {|\n               dispatch_protocol := Periodic;\n               period := 500;\n               deadline := 0%Z;\n               priority := 42;\n               dispatch_able := true;\n               wcet := 100;\n               clock := 600;\n               cet := 0;\n               delta_cet := 100;\n               current_state := Idle;\n               next_dispatch_time := 1000;\n               input_ports := [];\n               output_ports := [];\n               dispatch_trigger := []\n             |};\n          thread_ce := Periodic_Compute_Entry_Point;\n          |} [].\nProof. trivial. Qed.\n\n(*|\nSporadic thread test\n^^^^^^^^^^^^^^^^^^^^\n\nTranslate DEVS to a LTS\n|*)\n\nDefinition Sporadic_Compute_Entry_Point : Compute_Entry_Point :=\n  fun x : thread_state_variable =>\n    compute_during x x.(delta_cet).\n\nDefinition A_Sporadic_initial :=\n  thread_Initial A_Sporadic_Thread Sporadic_Compute_Entry_Point.\n\nDefinition S_thread_LTS := LTS_Of_DEVS (A_Sporadic_initial).\n\nExample S_thread_LTS_0 := Init S_thread_LTS.\n\n(*|\n* Step#0: we confirm the correct initialization of a thread\n|*)\n\nCompute Print_DEVS_Simulator S_thread_LTS_0.\nLemma S_thread_LTS_0_OK :\n    Print_DEVS_Simulator S_thread_LTS_0 =\n    dbg Zero Zero\n    {|\n      thread_l := performing_thread_activation;\n      thread_st :=\n        {|\n          dispatch_protocol := Sporadic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 0;\n          cet := 0;\n          delta_cet := 0;\n          current_state := Not_Activated;\n          next_dispatch_time := 0;\n          input_ports :=\n          [{|\n             port :=\n               Feature (Id \"a_feature\") inF eventPort\n                 (Component (Id \"\") null (FQN [] (Id \"\") None) [] []\n                    [] []) [];\n             is_data := false;\n             inner_variable := [];\n             outer_variable := [];\n             port_input_times := Input_Time [Dispatch];\n             urgency := 0;\n             size := 1;\n             overflow_handling_protocol := DropOldest;\n             dequeue_protocol := OneItem;\n             dequeued_items := 0\n           |}];\n          output_ports := [];\n          dispatch_trigger :=\n          [Feature (Id \"a_feature\") inF eventPort\n             (Component (Id \"\") null (FQN [] (Id \"\") None) [] [] [] [])\n             []]\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n    |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#1: We perform a :coq:`thread_step` to activate the thread. XXX\n|*)\n\nExample S_thread_LTS_1 :=\n  step_lts S_thread_LTS_0\n    (xs Y_thread Parent Parent Zero [ thread_step ]).\n\nCompute Print_DEVS_Simulator S_thread_LTS_1.\n\nLemma S_thread_LTS_1_OK :\n    Print_DEVS_Simulator S_thread_LTS_1 =\n    dbg 0 0\n         {|\n           thread_l := suspended_awaiting_dispatch;\n           thread_st :=\n             {|\n               dispatch_protocol := Sporadic;\n               period := 500;\n               deadline := 0%Z;\n               priority := 42;\n               dispatch_able := true;\n               wcet := 100;\n               clock := 0;\n               cet := 0;\n               delta_cet := 0;\n               current_state := Idle;\n               next_dispatch_time := 0;\n               input_ports :=\n                 [{|\n                    port :=\n                      Feature (Id \"a_feature\") inF eventPort\n                        (Component (Id \"\") null (FQN [] (Id \"\") None) [] []\n                           [] []) [];\n                    is_data := false;\n                    inner_variable := [];\n                    outer_variable := [];\n                    port_input_times := Input_Time [Dispatch];\n                    urgency := 0;\n                    size := 1;\n                    overflow_handling_protocol := DropOldest;\n                    dequeue_protocol := OneItem;\n                    dequeued_items := 0\n                  |}];\n               output_ports := [];\n               dispatch_trigger :=\n                 [Feature (Id \"a_feature\") inF eventPort\n                    (Component (Id \"\") null (FQN [] (Id \"\") None) [] [] [] [])\n                    []]\n             |};\n             thread_ce := Periodic_Compute_Entry_Point;\n             |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#2: We send an event to the sporadic thread, the thread is immediatly dispatched.\n|*)\n\nExample S_thread_LTS_2 :=\n  step_lts S_thread_LTS_1\n    (xs Y_thread Parent Parent 0 [ store_message 0 (Id \"a_feature\") false ]).\n\nCompute Print_DEVS_Simulator S_thread_LTS_2.\n\nLemma S_thread_LTS_2_OK :\n    Print_DEVS_Simulator S_thread_LTS_2 =\n    dbg 0 0\n    {|\n      thread_l := performing_thread_computation;\n      thread_st :=\n        {|\n          dispatch_protocol := Sporadic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 0;\n          cet := 0;\n          delta_cet := 0;\n          current_state := Ready;\n          next_dispatch_time := 500;\n          input_ports :=\n            [{|\n               port :=\n                 Feature (Id \"a_feature\") inF eventPort\n                   (Component (Id \"\") null (FQN [] (Id \"\") None) [] []\n                      [] []) [];\n               is_data := false;\n               inner_variable := [(0, false)];\n               outer_variable := [];\n               port_input_times := Input_Time [Dispatch];\n               urgency := 0;\n               size := 1;\n               overflow_handling_protocol := DropOldest;\n               dequeue_protocol := OneItem;\n               dequeued_items := 0\n             |}];\n          output_ports := [];\n          dispatch_trigger :=\n            [Feature (Id \"a_feature\") inF eventPort\n               (Component (Id \"\") null (FQN [] (Id \"\") None) [] [] [] [])\n               []]\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n        |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#3: We execute the thread for 100 time units. The thread goes to the :coq:`suspended_awaiting_dispatch` state.\n|*)\n\nExample S_thread_LTS_3 :=\n  step_lts S_thread_LTS_2\n    (xs Y_thread Parent Parent 0  [ run_thread 0 100%nat ]).\n\nCompute Print_DEVS_Simulator S_thread_LTS_3.\n\nLemma S_thread_LTS_3_OK :\n    Print_DEVS_Simulator S_thread_LTS_3 =\n    dbg 0 100\n    {|\n      thread_l := suspended_awaiting_dispatch;\n      thread_st :=\n        {|\n          dispatch_protocol := Sporadic;\n          period := 500;\n          deadline := 0%Z;\n          priority := 42;\n          dispatch_able := true;\n          wcet := 100;\n          clock := 100;\n          cet := 0;\n          delta_cet := 100;\n          current_state := Idle;\n          next_dispatch_time := 500;\n          input_ports :=\n            [{|\n               port :=\n                 Feature (Id \"a_feature\") inF eventPort\n                   (Component (Id \"\") null (FQN [] (Id \"\") None) [] []\n                      [] []) [];\n               is_data := false;\n               inner_variable := [];\n               outer_variable := [];\n               port_input_times := Input_Time [Dispatch];\n               urgency := 0;\n               size := 1;\n               overflow_handling_protocol := DropOldest;\n               dequeue_protocol := OneItem;\n               dequeued_items := 0\n             |}];\n          output_ports := [];\n          dispatch_trigger :=\n            [Feature (Id \"a_feature\") inF eventPort\n               (Component (Id \"\") null (FQN [] (Id \"\") None) [] [] [] [])\n               []]\n        |};\n        thread_ce := Periodic_Compute_Entry_Point;\n        |} [].\nProof. trivial. Qed.\n\n(*|\n* Step#4: We just step .\n|*)\n\nExample S_thread_LTS_4 :=\n  step_lts S_thread_LTS_3\n    (xs Y_thread Parent Parent 100 [ thread_step  ]).\n\nCompute Print_DEVS_Simulator S_thread_LTS_4.\n\nLemma S_thread_LTS_4_OK :\n    Print_DEVS_Simulator S_thread_LTS_4 =\n    dbg 100 100\n         {|\n           thread_l := suspended_awaiting_dispatch;\n           thread_st :=\n             {|\n               dispatch_protocol := Sporadic;\n               period := 500;\n               deadline := 0%Z;\n               priority := 42;\n               dispatch_able := true;\n               wcet := 100;\n               clock := 100;\n               cet := 0;\n               delta_cet := 0;\n               current_state := Idle;\n               next_dispatch_time := 500;\n               input_ports :=\n                 [{|\n                    port :=\n                      Feature (Id \"a_feature\") inF eventPort\n                        (Component (Id \"\") null (FQN [] (Id \"\") None) [] []\n                           [] []) [];\n                    is_data := false;\n                    inner_variable := [];\n                    outer_variable := [];\n                    port_input_times := Input_Time [Dispatch];\n                    urgency := 0;\n                    size := 1;\n                    overflow_handling_protocol := DropOldest;\n                    dequeue_protocol := OneItem;\n                    dequeued_items := 0\n                  |}];\n               output_ports := [];\n               dispatch_trigger :=\n                 [Feature (Id \"a_feature\") inF eventPort\n                    (Component (Id \"\") null (FQN [] (Id \"\") None) [] [] [] [])\n                    []]\n             |};\n             thread_ce := Periodic_Compute_Entry_Point;\n             |} [].\nProof. trivial. Qed.\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/behavior/thread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17958973018625063}}
{"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 ProD3.examples.cms.verif_Win1.\nRequire Import ProD3.examples.cms.verif_Win2.\nRequire Import ProD3.examples.cms.verif_Win3.\nRequire Import ProD3.examples.cms.verif_CMS_1.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_4_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_5_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_index_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_window_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_3_body) : func_specs.\n\nDefinition P4_bf2_win_md_t_clear (f cf if' : Z) (new_clear_index : Sval) (is : list Sval) :=\n  if f=? cf then\n    P4_bf2_win_md_t (P4Bit 8 CLEAR) (Zrepeat new_clear_index 5)\n  else\n    P4_bf2_win_md_t (P4Bit 8 NOOP) is.\n\nDefinition tbl_set_win_clear_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_2\"; \"api_2\"];\n               [\"act_set_clear_win_2\"; \"api_3\"];\n               [\"act_set_clear_win_3\"; \"api_1\"];\n               [\"act_set_clear_win_3\"; \"api_2\"];\n               [\"act_set_clear_win_3\"; \"api_3\"];\n               [\"act_set_clear_win_4\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_2\"];\n               [\"act_set_clear_win_4\"; \"api_3\"];\n               [\"act_set_clear_win_5\"; \"api_1\"];\n               [\"act_set_clear_win_5\"; \"api_2\"];\n               [\"act_set_clear_win_5\"; \"api_3\"]]) []\n    WITH (timer : Z * bool) (clear_index_1 hash_index_1 hash_index_2 hash_index_3 hash_index_4 hash_index_5 : Sval)\n      (H_timer : 0 <= fst timer < frame_tick_tocks * num_frames),\n      PRE\n        (ARG []\n        (MEM [([\"api\"], P4Bit 8 CLEAR);\n              ([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"hash_index_4\", hash_index_4);\n                  (\"hash_index_5\", hash_index_5);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (let cf := get_clear_frame timer in\n        let if' := get_insert_frame cf in\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"hash_index_4\", hash_index_4);\n                  (\"hash_index_5\", hash_index_5);\n                  (\"win_1\", P4_bf2_win_md_t_clear 0 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5]);\n                  (\"win_2\", P4_bf2_win_md_t_clear 1 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5]);\n                  (\"win_3\", P4_bf2_win_md_t_clear 2 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3; hash_index_4; hash_index_5])])]\n        (EXT [])))))%arg_ret_assr.\n\nLemma tbl_set_win_clear_body :\n  func_sound ge tbl_set_win_fd nil tbl_set_win_clear_spec.\nProof.\n  start_function; elim_trivial_cases.\n  - replace (get_clear_frame timer) with 0. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_1_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 1. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_2_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 2. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_3_body.\n    { entailer. }\n    { entailer. }\n  - lia.\nQed.\n\nDefinition cms_clear := @cms_clear num_frames num_rows num_slots H_num_frames H_num_rows H_num_slots\n  frame_tick_tocks.\n\nDefinition CMS_clear_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (key : Val) (tstamp : Z) (cf : cms num_frames num_rows num_slots),\n      PRE\n        (ARG [eval_val_to_sval key; P4Bit 8 CLEAR; P4Bit 48 tstamp; P4Bit_ value_w]\n        (MEM []\n        (EXT [cms_repr p index_w panes rows cf])))\n      POST\n        (ARG_RET [P4Bit_ value_w] ValBaseNull\n        (MEM []\n        (EXT [cms_repr p index_w panes rows (cms_clear cf (Z.odd (tstamp/tick_time)))]))).\n\nLemma CMS_clear_body :\n  func_sound ge CMS_fd nil CMS_clear_spec.\nProof.\n  Time start_function.\n  destruct cf as [[ps ?H] ? ?].\n  unfold cms_repr.\n  cbn [proj1_sig] in *.\n  destruct_list ps.\n  normalize_EXT.\n  Time step.\n  Time step_call tbl_hash_index_1_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_2_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_3_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_4_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_5_body.\n  { entailer. }\n  Intros _.\n  set (is := (exist _ [hash1 key; hash2 key; hash3 key; hash4 key; hash5 key] eq_refl : listn Z 5)).\n  set (clear_is := (exist _ (Zrepeat cms_clear_index 5) eq_refl : listn Z 5)).\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`is)). {\n    repeat first [apply Forall_cons | apply Forall_nil].\n    all : unfold hash1, hash2, hash3;\n      apply Z.mod_pos_bound; lia.\n  }\n  P4assert (0 <= cms_clear_index < num_slots). {\n    unfold fil_clear_index_repr.\n    Intros i'.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    subst.\n    apply Z.mod_pos_bound.\n    lia.\n  }\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`clear_is)). {\n    repeat first [\n      assumption\n    | constructor\n    ].\n  }\n  step_call tbl_clear_index_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_clear_window_body.\n  { entailer. }\n  Intros _.\n  set (new_timer := update_timer cms_timer (Z.odd (tstamp / tick_time))).\n  P4assert (0 <= fst new_timer < num_frames * frame_tick_tocks).\n  { unfold timer_repr.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    auto.\n  }\n  step_call tbl_set_win_clear_body.\n  { entailer. }\n  { auto. }\n  Intros _.\n  (* unfold and fold in the post condition *)\n  unfold cms_clear, ConModel.cms_clear.\n  unfold proj1_sig.\n  fold new_timer.\n  replace (exist (fun i : list Z => Zlength i = num_rows) (Zrepeat cms_clear_index num_rows) _) with clear_is. 2 : {\n    apply subset_eq_compat. auto.\n  }\n  assert (0 <= get_clear_frame new_timer < num_frames). {\n    unfold ConModel.get_clear_frame.\n    split.\n    - apply Z.div_le_lower_bound; lia.\n    - apply Z.div_lt_upper_bound; lia.\n  }\n  destruct (get_clear_frame new_timer =? 0) eqn:?.\n  { replace (get_clear_frame new_timer) with 0 by lia.\n    step_call verif_Win1.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 1) eqn:?.\n  { replace (get_clear_frame new_timer) with 1 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 2) eqn:?.\n  { replace (get_clear_frame new_timer) with 2 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_call tbl_merge_wins_1_body.\n    { entailer. }\n    { reflexivity. }\n    { reflexivity. }\n    Intros _.\n    simpl_assertion.\n    step_into.\n    { hoare_func_table; elim_trivial_cases.\n      { clear -H5; lia. }\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  lia.\nTime Qed.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/cms/verif_CMS_clear.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17958973018625063}}
{"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(*                                                                     *)\n(*              Load and Store Semantics for Primitives                *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the load and store semantics for primitives at all layers*)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Globalenvs.\nRequire Import ASTExtra.\nRequire Import AsmX.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import LAsm.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import FlatMemory.\nRequire Import GlobIdent.\nRequire Import Integers.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import AsmImplLemma.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.ClightModules.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatClightSem.\nRequire Import liblayers.compcertx.MemWithData.\n\nRequire Import AbstractDataType.\nRequire Import FlatLoadStoreSem.\nRequire Import LoadStoreDef.\n\nSection Load_Store.\n\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{HD: CompatData RData}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Notation HDATAOps := (cdata (cdata_ops := data_ops) RData).\n  \n  Section GE.\n    \n    Context {F V} (ge: Genv.t F V).\n\n    Section Accessor.\n\n      Variable accessor: int64 -> Z -> memory_chunk -> (mwd HDATAOps) -> regset -> preg -> Asm.outcome (mem:= mwd HDATAOps).\n\n      Open Scope Z_scope.\n\n      Definition exec_guest_intel_accessor1 (adr: int) (chunk: memory_chunk) (m: mwd HDATAOps) (rs: regset) (rd: preg) :=\n        let ofs := (Int.unsigned adr) in \n        match (Genv.find_symbol ge EPT_LOC) with\n          | Some b => \n            match Mem.loadv Mint32 m (Vptr b (Int.repr ((EPT_PML4_INDEX ofs) * 8 + 4))) with\n              | Some (Vptr b0 adr1) =>\n                if (peq b0 b) then\n                  let ofs1 := (Int.unsigned adr1) / PgSize * PgSize + 4 in\n                  match Mem.loadv Mint32 m (Vptr b (Int.repr (ofs1 + (EPT_PDPT_INDEX ofs) * 8))) with\n                    | Some (Vptr b0 adr2) =>\n                      if peq b0 b then\n                        let ofs2 := (Int.unsigned adr2) / PgSize * PgSize + 4 in\n                        match Mem.loadv Mint32 m (Vptr b (Int.repr (ofs2 + (EPT_PDIR_INDEX ofs) * 8))) with\n                          | Some (Vptr b0 adr3) =>\n                            if peq b0 b then\n                              let ofs3 := (Int.unsigned adr3) / PgSize * PgSize in\n                              match Mem.loadv Mint64 m (Vptr b (Int.repr (ofs3 + (EPT_PTAB_INDEX ofs) * 8))) with\n                                | Some (Vlong n) =>\n                                  accessor n ofs chunk m rs rd\n                                | _ => Stuck\n                              end\n                            else Stuck\n                          | _ => Stuck\n                        end\n                      else Stuck\n                    | _ => Stuck\n                  end\n                else Stuck\n              | _ => Stuck\n            end\n          | _ => Stuck\n        end.\n\n      Lemma exec_guest_intel_accessor1_high_level_invariant:\n        forall adr chunk m rs rd rs' m',\n          exec_guest_intel_accessor1 adr chunk m rs rd = Next rs' m' ->\n          high_level_invariant (snd m) ->\n          (forall i i',\n             accessor i i' chunk m rs rd = Next rs' m' ->\n             high_level_invariant (snd m')) ->\n          high_level_invariant (snd m').\n      Proof.\n        unfold exec_guest_intel_accessor1. intros until m'.\n        destruct (Genv.find_symbol ge EPT_LOC); try discriminate.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (EPT_PML4_INDEX (Int.unsigned adr) * 8 + 4)))); try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i / 4096 * 4096 + 4 + EPT_PDPT_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i0 / 4096 * 4096 + 4 + EPT_PDIR_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint64 m\n                            (Vptr b (Int.repr (Int.unsigned i1 / 4096 * 4096 + EPT_PTAB_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        intros. eauto.\n      Qed.\n\n      Lemma exec_guest_intel_accessor1_asm_invariant:\n        forall chunk rd,\n        forall adr m rs rs' m',\n          exec_guest_intel_accessor1 adr chunk m rs rd = Next rs' m' ->\n          AsmX.asm_invariant ge rs m ->\n          (forall i i',\n             accessor i i' chunk m rs rd = Next rs' m' ->\n             AsmX.asm_invariant ge rs' m') ->\n          AsmX.asm_invariant ge rs' m'.\n      Proof.\n        unfold exec_guest_intel_accessor1. intros until m'.\n        destruct (Genv.find_symbol ge EPT_LOC); try discriminate.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (EPT_PML4_INDEX (Int.unsigned adr) * 8 + 4)))); try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i / 4096 * 4096 + 4 + EPT_PDPT_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i0 / 4096 * 4096 + 4 + EPT_PDIR_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint64 m\n                            (Vptr b (Int.repr (Int.unsigned i1 / 4096 * 4096 + EPT_PTAB_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        intros; eauto.\n      Qed.\n\n      Lemma exec_guest_intel_accessor1_low_level_invariant:\n        forall adr chunk m rs rd rs' m',\n          exec_guest_intel_accessor1 adr chunk m rs rd = Next rs' m' ->\n          CompatData.low_level_invariant (Mem.nextblock m) (snd m) ->\n          (forall i i',\n             accessor i i' chunk m rs rd = Next rs' m' ->\n             CompatData.low_level_invariant (Mem.nextblock m') (snd m')) ->\n          CompatData.low_level_invariant (Mem.nextblock m') (snd m').\n      Proof.\n        unfold exec_guest_intel_accessor1. intros until m'.\n        destruct (Genv.find_symbol ge EPT_LOC); try discriminate.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (EPT_PML4_INDEX (Int.unsigned adr) * 8 + 4)))); try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i / 4096 * 4096 + 4 + EPT_PDPT_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint32 m\n                            (Vptr b (Int.repr (Int.unsigned i0 / 4096 * 4096 + 4 + EPT_PDIR_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        destruct (peq b0 b); contra_inv; subst.\n        destruct (Mem.loadv Mint64 m\n                            (Vptr b (Int.repr (Int.unsigned i1 / 4096 * 4096 + EPT_PTAB_INDEX (Int.unsigned adr) * 8)))); \n          try discriminate.\n        destruct v; try discriminate.\n        intros; eauto.\n      Qed.\n\n    End Accessor.\n\n  End GE.\n\n  Section EQ.\n\n    Context `{accessor1: int64 -> Z -> memory_chunk -> (mwd HDATAOps) -> regset -> preg -> Asm.outcome (mem:= mwd HDATAOps)}.\n    Context `{accessor2: int64 -> Z -> memory_chunk -> (mwd HDATAOps) -> regset -> preg -> Asm.outcome (mem:= mwd HDATAOps)}.\n \n    Lemma exec_guest_intel_accessor1_eq:\n      forall {F V} (ge1 ge2: Genv.t F V) i chunk m rs r\n             (SYMB : (forall i, Genv.find_symbol ge2 i = Genv.find_symbol ge1 i))\n             (ACC: (forall i1 i2, accessor2 i1 i2 chunk m rs r = accessor1 i1 i2 chunk m rs r)),\n        exec_guest_intel_accessor1 ge2 accessor2 i chunk m rs r =\n        exec_guest_intel_accessor1 ge1 accessor1 i chunk m rs r.\n    Proof.\n      intros. unfold exec_guest_intel_accessor1.\n      repeat rewrite SYMB.\n      destruct (Genv.find_symbol ge1 EPT_LOC); try reflexivity.\n      destruct (Mem.loadv Mint32 m\n                          (Vptr b (Int.repr (EPT_PML4_INDEX (Int.unsigned i) * 8 + 4)))); try reflexivity.\n      destruct v; try reflexivity.\n      destruct (Mem.loadv Mint32 m\n                          (Vptr b (Int.repr (Int.unsigned i0 / 4096 * 4096 + 4 + EPT_PDPT_INDEX (Int.unsigned i) * 8)))); try reflexivity.\n      destruct v; try reflexivity.\n      destruct (Mem.loadv Mint32 m\n                          (Vptr b (Int.repr (Int.unsigned i1 / 4096 * 4096 + 4 + EPT_PDIR_INDEX (Int.unsigned i) * 8)))); try reflexivity.\n      destruct v; try reflexivity.\n      destruct (Mem.loadv Mint64 m\n                          (Vptr b (Int.repr (Int.unsigned i2 / 4096 * 4096 + EPT_PTAB_INDEX (Int.unsigned i) * 8)))); try reflexivity.\n      destruct v; try reflexivity.\n      erewrite ACC; trivial.\n    Qed.\n\n  End EQ.\n\nEnd Load_Store.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/flatmem/GuestAccessIntelDef0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.17937463187310093}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\nRequire Import VST.floyd.sublist.\n\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.general_lemmas.\nRequire Import sha.spec_sha.\n\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_pure_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import VST.floyd.library.\n\nRequire Import hmacdrbg.verif_hmac_drbg_seed_common.\n\nModule Instantiate_eq.\n\nDefinition OptionalNonce: option (list byte) := None. (*The implementation takes nonce from entropy, using the el*3/2 calculation*)\n\n(*NIST, Section 10.1: highest supported sec strength is given by the hash function's\nsecurity strength for preimage resistance. For SHA256, this is\n(according to NIST SP 800-107, Table 1, page 11) 256 bits. See also Appendix B2 of NIST SP 800-90A. *)\nDefinition highest_supported_security_strength := 32. (* in bytes -- see comment for reseed*)\n\n(*Q: should we use the sec strength of HMAC, calculated according to Section 5.3.4 of\nNIST SP 800-107 instead?*)\nDefinition requested_security_strength:= 32.  (*same as in reseed*)\n\n\nDefinition prediction_resistance_supported:bool:=true.\n\nDefinition mbedtls_HMAC256_DRBG_instantiate_function (entropy_stream: ENTROPY.stream)\n         entropy_len pr_flag (personalization_string: list byte): ENTROPY.result DRBG_state_handle :=\n    HMAC256_DRBG_instantiate_function entropy_len entropy_len OptionalNonce\n            highest_supported_security_strength max_personalization_string_length\n            prediction_resistance_supported entropy_stream\n            requested_security_strength pr_flag personalization_string.\n\nDefinition entlen:Z := 32.\n\n\nParameter Entropy_addSuccess1: forall n m s s1 l1 s2 l2,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.success l2 s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.success (l1++l2) s2.\n\nParameter Entropy_addSuccess2: forall n m s s1 l1 s2 e,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.error e s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s2.\n\nParameter Entropy_addError: forall n m s s1 e, ENTROPY.get_bytes n s = ENTROPY.error e s1 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s1.\n\nLemma Entropy_le n s l ss: ENTROPY.success l ss = ENTROPY.get_bytes n s ->\n  forall m, (m <= n)%nat -> exists l' s', ENTROPY.success l' s' = ENTROPY.get_bytes m s.\nProof. intros.\n  remember (ENTROPY.get_bytes m s) as d.\n  destruct d. eexists; eexists; trivial.\n  symmetry in H; symmetry in Heqd.\n  specialize (Entropy_addError _ (n-m)%nat _ _ _ Heqd).\n     rewrite le_plus_minus_r; trivial.\n  intros HH; rewrite HH in *. discriminate.\nQed.\n\nLemma Entropy_addSuccess3: forall n m s ss l,\n        ENTROPY.get_bytes n s = ENTROPY.success l ss -> (m <= n)%nat ->\n        exists l1 s1, ENTROPY.get_bytes m s = ENTROPY.success l1 s1 /\\ \n        exists l2, ENTROPY.get_bytes (n-m)%nat s1 = ENTROPY.success l2 ss /\\ l=l1++l2.\nProof. intros.\n  remember (ENTROPY.get_bytes m s). destruct r.\n+ exists l0, s0; split; trivial.\n  symmetry in Heqr.\n  remember (ENTROPY.get_bytes (n-m)%nat s0) as t.\n  destruct t; symmetry in Heqt.\n  - specialize (Entropy_addSuccess1 m (n-m)%nat s s0). rewrite Heqr, Heqt, le_plus_minus_r; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H. exists l1; split; trivial.\n  - specialize (Entropy_addSuccess2 m (n-m)%nat s s0). rewrite Heqr, Heqt, le_plus_minus_r; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H.\n+ symmetry in Heqr; exfalso. \n  specialize (Entropy_addError m (n-m)%nat s). rewrite Heqr, le_plus_minus_r; trivial.\n  intros X. rewrite (X _ _ (eq_refl _)) in H. inv H.\nQed.\n\nLemma instantiate_eq es prflag pers:\n      instantiate_function_256 es prflag pers =\n      mbedtls_HMAC256_DRBG_instantiate_function es entlen prflag pers.\nProof. unfold instantiate_function_256, mbedtls_HMAC256_DRBG_instantiate_function, \n   HMAC256_DRBG_instantiate_function, DRBG_instantiate_function, HMAC256_DRBG_instantiate_algorithm; simpl; intros.\ndestruct (Zlength pers >? max_personalization_string_length).\n+ destruct prflag; trivial.\n+ unfold entlen, get_entropy; simpl. \n  remember (ENTROPY.get_bytes 48 es) as r.\n  destruct r; symmetry in Heqr. \n  - destruct (Entropy_addSuccess3 _ 32 _ _ _ Heqr) as [l1 [s1 [E32 [l2 [E16 L]]]]]. omega.\n    simpl in E16. rewrite E32, E16; subst.\n    unfold HMAC_DRBG_instantiate_algorithm. simpl. rewrite app_assoc. destruct prflag; trivial.\n  - remember  (ENTROPY.get_bytes 32 es) as t; destruct t; symmetry in Heqt.\n    * remember (ENTROPY.get_bytes 16 s0) as w; destruct w; symmetry in Heqw.\n      ++ specialize (Entropy_addSuccess1 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr. congruence.\n      ++ specialize (Entropy_addSuccess2 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\n    * specialize (Entropy_addError _ 16 _ _ _ Heqt). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\nQed.\n\nLemma instantiate_reseed d s pr_flag rc ri (ZLc'256F : (Zlength d >? 256) = false):\n      mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag  d =\n      mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs initial_key initial_value rc 48 pr_flag ri) d.\nProof. rewrite <- instantiate256_reseed, instantiate_eq; trivial. Qed.\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque initial_key. Opaque initial_value.\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque list_repeat. \n\n(*specification for the expected case, in which 0<=len<=256.\n  But use mbedtls_HMAC256_DRBG_instantiate_function PROP of PRE and assume SUCCESS*)\nDefinition hmac_drbg_seed_simple_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z,\n        handle_ss: DRBG_state_handle * ENTROPY.stream, gv: globals\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP (len = Zlength Data /\\ 0 <= len <=256 /\\\n             mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n             = ENTROPY.success (fst handle_ss) (snd handle_ss))\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvars gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val,\n                 match (fst Ctx, fst handle_ss) with ((M1, (M2, M3)), ((((newV, newK), newRC), newEL), newPR))\n                   => let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                      !!(ret_value = Int.zero) \n                      && data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                         hmac256drbg_relate (HMAC256DRBGabs newK newV newRC 32 newPR 10000) CtxFinal *\n                         Stream (snd handle_ss) \n                end;\n            mem_mgr gv).\n\nLemma body_hmac_drbg_seed_simple: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_simple_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 RES]]. destruct handle_ss as [handle ss]. simpl in RES.\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n\n  Intros v. rename H into Hv.\n  forward.\n  forward_if.\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros. Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!.\n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, initial_key, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { split3; auto. split; auto.\n  }\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    + elim H; trivial. \n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rep_omega. }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;3;4;5;9] FR_CTX.\n  freeze [1;7;8;9] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    simpl. entailer!.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split3; auto. split. rep_omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. (*change Int.modulus with 4294967296.*) rep_omega.\n     unfold contents_with_add. simple_if_tac. rep_omega. rewrite Zlength_nil; rep_omega.\n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. simple_if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + omega.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. omega. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite RES in HeqMRS. inv HeqMRS. \n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST. \n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. omega. }\n  rewrite <- instantiate_reseed, RES in HeqMRS; trivial. subst MRS. clear H RES Heqd. \n  destruct handle as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12;13] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  thaw ALLSEP. thaw OLD_MD. Exists p. \n  cancel;  normalize. \n  apply andp_right. solve [apply prop_right; repeat split; trivial].\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty.\nTime Qed. (*Coq8.6: 26secs*)\n\n(*Spec that does not assume len<=256 and includes a clause \n  for the case where mbedtls_HMAC256_DRBG_instantiate_function yields\n  Entropy.ERROR, ie no hypothesis about mbedtls_HMAC256_DRBG_instantiate_function in PROP of PRE*)\nDefinition hmac_drbg_seed_full_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z, gv: globals\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvars gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val,\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 (48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else match mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n                        with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end;\n             mem_mgr gv).\n\nLemma body_hmac_drbg_seed_full: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_full_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as (*[PREQ*) [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]](*]*).\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n  forward_if.\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros. Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!.\n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n(*\n  replace_SEP 1 (UNDER_SPEC.EMPTY Ews p).\n  { entailer!. \n    eapply derives_trans. 2: apply UNDER_SPEC.mkEmpty.\n    fix_hmacdrbg_compspecs. apply derives_refl.\n  }\n*)\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, initial_key, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { split3; auto. split; auto. \n  }\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  deadvars!.\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    + elim H; trivial. \n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rep_omega. }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;3;4;5;9] FR_CTX.\n  freeze [1;7;8;9] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    simpl; entailer!.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split3; auto. split. rep_omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. rep_omega.\n    unfold contents_with_add. simple_if_tac. rep_omega. rewrite Zlength_nil; rep_omega.\n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. simple_if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. normalize. cancel. simpl. \n      Exists p. thaw OLD_MD. normalize.\n      apply andp_right. apply prop_right; repeat split; trivial. cancel.\n      apply hmac_interp_empty.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. omega. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite <- HeqMRS. \n        normalize.\n        apply andp_right. apply prop_right; repeat split; trivial.\n        cancel. apply hmac_interp_empty.\n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  unfold return_value_relate_result in H.\n  destruct MRS. 2:{ exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  }\n  clear H.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate. simpl in *. rewrite Heqd2.\n  thaw ALLSEP. thaw OLD_MD. Exists p. cancel.\n  normalize.\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. omega. }\n  rewrite <- instantiate_reseed in HeqMRS; trivial.\n  rewrite <- HeqMRS.\n  normalize.\n  apply andp_right. apply prop_right; repeat split; trivial.\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty. \nTime Qed. (*Coq8.6: 32secs*)\n   (*Feb 22nd 2017: 245.406 secs (233.843u,0.203s) (successful)*)\n   (*earlier: 69.671 secs (59.578u,0.015s) (successful)*)\n\nEnd Instantiate_eq.\n\nLemma ReseedRes: forall X r v, @return_value_relate_result X r (Vint v) -> Int.eq v (Int.repr (-20864)) = false.\nProof. intros.\n  unfold return_value_relate_result in H.\n  destruct r. inv H; reflexivity.\n  destruct e; inv H; try reflexivity.\n  apply Int.eq_false. eapply ENT_GenErrAx.\nQed.\n\nDefinition preseed_relate V rc pr ri (r : hmac256drbgstate):mpred:=\n    match r with\n     (md_ctx', (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))) =>\n    md_empty md_ctx' &&\n    !! (map Vubyte V = V' /\\\n        Zlength V = 32 /\\\n        Vint (Int.repr rc) = reseed_counter'(* /\\\n        Vint (Int.repr entropy_len) = entropy_len'*) /\\\n        Vint (Int.repr ri) = reseed_interval' /\\\n        Val.of_bool pr = prediction_resistance')\n   end.\n\nDefinition hmac_drbg_seed_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        (*CTX: hmac256drbgabs,*)\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr:bool, ri:Z, VV:list byte, gv: globals\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len (*<= 336 Int.max_unsigned*) /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvars gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate VV rc pr ri Ctx;\n         (*hmac256drbg_relate CTX Ctx;*)\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                  (*hmac256drbg_relate CTX Ctx *) preseed_relate VV rc pr ri Ctx *\n                  Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val, (* malloc_token Tsh (Tstruct _hmac_ctx_st noattr) p * *)\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 ((*hmac256drbgabs_entropy_len initial_state_abs*)48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs VV (list_repeat 32 Byte.one) rc 48 pr 10000 in\n                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else let myABS := HMAC256DRBGabs VV (list_repeat 32 Byte.one) rc 48 pr 10000\n                      in match mbedtls_HMAC256_DRBG_reseed_function s myABS\n                                (contents_with_add data (Zlength Data) Data)\n                         with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs VV (list_repeat 32 Byte.one) rc 48 pr 10000 in\n                                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end;\n         mem_mgr gv).\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\n\nLemma body_hmac_drbg_seed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]].\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n\n  forward_if.\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!. \n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  rename H1 into ZL_VV.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, VV, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { rewrite ZL_VV, ptrofs_add_repr_0_r; simpl.\n    apply prop_right; repeat split; trivial.\n  }\n  { split3; auto. split; auto.\n  }\n  Intros.\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite ZL_VV; entailer!.\n  }\n  { rewrite sepcon_comm. apply sepcon_derives.\n      eapply derives_trans. apply data_at_memory_block.\n        rewrite ZL_VV. simpl. cancel. cancel. }\n  (*{ split. apply semax_call.writable_share_top.\n    rewrite ZL_V0, client_lemmas.int_max_unsigned_eq. omega. }*)\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9;1] ALLSEP.\n(*  set (ent_len := new_ent_len (Zlength V0)) in *.*)\n\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    { elim H; trivial. }\n    { clear H. forward. forward. entailer!. }\n  }\n  forward. simpl. drop_LOCAL 1%nat. (*_t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rep_omega. }\n\n  set (myABS := HMAC256DRBGabs VV (list_repeat 32 Byte.one) rc 48 pr 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;3;4;5;13] FR_CTX.\n  freeze [1;7;8;9] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { go_lower. thaw INI. clear KVStreamInfoDataFreeBlk. thaw FR_CTX.\n    unfold_data_at 2%nat.\n    subst ST; simpl. cancel. normalize.\n    apply andp_right. apply prop_right. repeat split; trivial.\n    unfold md_full. simpl.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split3; auto. split. rep_omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. (*change Int.modulus with 4294967296.*) rep_omega.\n       unfold contents_with_add. simple_if_tac. rep_omega. rewrite Zlength_nil; rep_omega.\n  }\n\n  Intros v.\n\n  forward.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. normalize. simpl. cancel.\n      Exists p. thaw OLD_MD. normalize.\n      apply andp_right. apply prop_right; repeat split; trivial. cancel.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. normalize.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer; simpl.\n        Intros. Exists p. thaw OLD_MD. cancel. normalize.\n        apply andp_right. apply prop_right; repeat split; trivial.\n        cancel.\n  }\n  { rename H into Hv. forward.\n    go_lower. simpl in Hv. apply typed_false_of_bool in Hv. apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv. subst v.\n    entailer!.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold return_value_relate_result in H.\n  destruct MRS. 2:{ exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  }\n  clear H. unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11] XX.\n  forward. forward. \n  Exists Int.zero. simpl. symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate.\n  apply andp_right. apply prop_right; split; trivial. \n  thaw XX. thaw OLD_MD. cancel. simpl in *. rewrite Heqd2, <- HeqMRS.\n  Exists p. normalize. \n  apply andp_right. apply prop_right; repeat split; trivial.\n  unfold_data_at 1%nat. cancel.\nTime Qed. (*Coq8.6: 40secs*)\n          (*Jan 22nd 2017: 267.171 secs (182.812u,0.015s) (successful)*)\n          (*earlier: Finished transaction in 121.296 secs (70.921u,0.062s) (successful)*)\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/hmacdrbg/verif_hmac_drbg_NISTseed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17928955007993205}}
{"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(** Register allocation by external oracle and a posteriori validation. *)\n\nRequire Import FSets.\nRequire FSetAVLplus.\nRequire Archi.\nRequire Import Coqlib.\nRequire Import Ordered.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Lattice.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Memdata.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Kildall.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import RTLtyping.\nRequire Import LTL.\n\n(** The validation algorithm used here is described in\n  \"Validating register allocation and spilling\", \n  by Silvain Rideau and Xavier Leroy,\n  in Compiler Construction (CC 2010), LNCS 6011, Springer, 2010. *)\n\n(** * Structural checks *)\n\n(** As a first pass, we check the LTL code returned by the external oracle\n  against the original RTL code for structural conformance.\n  Each RTL instruction was transformed into a LTL basic block whose\n  shape must agree with the RTL instruction.  For example, if the RTL\n  instruction is [Istore(Mint32, addr, args, src, s)], the LTL basic block\n  must be of the following shape:\n- zero, one or several \"move\" instructions\n- a store instruction [Lstore(Mint32, addr, args', src')]\n- a [Lbranch s] instruction.\n\n  The [block_shape] type below describes all possible cases of structural\n  maching between an RTL instruction and an LTL basic block.\n*)\n\nDefinition moves := list (loc * loc)%type.\n\nInductive block_shape: Type :=\n  | BSnop (mv: moves) (s: node)\n  | BSmove (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSmakelong (src1 src2: reg) (dst: reg) (mv: moves) (s: node)\n  | BSlowlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BShighlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSop (op: operation) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': mreg)\n         (mv2: moves) (s: node)\n  | BSopdead (op: operation) (args: list reg) (res: reg)\n         (mv: moves) (s: node)\n  | BSload (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSloaddead (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv: moves) (s: node)\n  | BSload2 (addr1 addr2: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args1': list mreg) (dst1': mreg)\n         (mv2: moves) (args2': list mreg) (dst2': mreg)\n         (mv3: moves) (s: node)\n  | BSload2_1 (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSload2_2 (addr addr': addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSstore (chunk: memory_chunk) (addr: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args': list mreg) (src': mreg)\n         (s: node)\n  | BSstore2 (addr1 addr2: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args1': list mreg) (src1': mreg)\n         (mv2: moves) (args2': list mreg) (src2': mreg)\n         (s: node)\n  | BScall (sg: signature) (ros: reg + ident) (args: list reg) (res: reg)\n         (mv1: moves) (ros': mreg + ident) (mv2: moves) (s: node)\n  | BStailcall (sg: signature) (ros: reg + ident) (args: list reg)\n         (mv1: moves) (ros': mreg + ident)\n  | BSbuiltin (ef: builtin) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': list mreg)\n         (mv2: moves) (s: node)\n  | BSannot (text: ident) (targs: list annot_arg) (args: list reg) (res: reg)\n         (mv: moves) (args': list loc) (s: node)\n  | BScond (cond: condition) (args: list reg)\n         (mv: moves) (args': list mreg) (s1 s2: node)\n  | BSjumptable (arg: reg)\n         (mv: moves) (arg': mreg) (tbl: list node)\n  | BSreturn (arg: option reg)\n         (mv: moves).\n\n(** Extract the move instructions at the beginning of block [b].\n  Return the list of moves and the suffix of [b] after the moves. *)\n\nFixpoint extract_moves (accu: moves) (b: bblock) {struct b} : moves * bblock :=\n  match b with\n  | Lgetstack sl ofs ty dst :: b' =>\n      extract_moves ((S sl ofs ty, R dst) :: accu) b'\n  | Lsetstack src sl ofs ty :: b' =>\n      extract_moves ((R src, S sl ofs ty) :: accu) b'\n  | Lop op args res :: b' =>\n      match is_move_operation op args with\n      | Some arg => extract_moves ((R arg, R res) :: accu) b'\n      | None => (List.rev accu, b)\n      end\n  | _ =>\n      (List.rev accu, b)\n  end.\n\nDefinition check_succ (s: node) (b: LTL.bblock) : bool :=\n  match b with\n  | Lbranch s' :: _ => peq s s'\n  | _ => false\n  end.\n\nNotation \"'do' X <- A ; B\" := (match A with Some X => B | None => None end)\n         (at level 200, X ident, A at level 100, B at level 200)\n         : option_monad_scope.\n\nNotation \"'assertion' A ; B\" := (if A then B else None)\n         (at level 200, A at level 100, B at level 200)\n         : option_monad_scope.\n\nLocal Open Scope option_monad_scope.\n\n(** Classify operations into moves, 64-bit integer operations, and other\n  arithmetic/logical operations. *)\n\nInductive operation_kind: operation -> list reg -> Type :=\n  | operation_Omove: forall arg, operation_kind Omove (arg :: nil)\n  | operation_Omakelong: forall arg1 arg2, operation_kind Omakelong (arg1 :: arg2 :: nil)\n  | operation_Olowlong: forall arg, operation_kind Olowlong (arg :: nil)\n  | operation_Ohighlong: forall arg, operation_kind Ohighlong (arg :: nil)\n  | operation_other: forall op args, operation_kind op args.\n\nDefinition classify_operation (op: operation) (args: list reg) : operation_kind op args :=\n  match op, args with\n  | Omove, arg::nil => operation_Omove arg\n  | Omakelong, arg1::arg2::nil => operation_Omakelong arg1 arg2\n  | Olowlong, arg::nil => operation_Olowlong arg\n  | Ohighlong, arg::nil => operation_Ohighlong arg\n  | op, args => operation_other op args\n  end.\n\n(** Check RTL instruction [i] against LTL basic block [b].  \n  On success, return [Some] with a [block_shape] describing the correspondence.\n  On error, return [None]. *)\n\nDefinition pair_instr_block\n               (i: RTL.instruction) (b: LTL.bblock) : option block_shape :=\n  match i with\n  | Inop s =>\n      let (mv, b1) := extract_moves nil b in\n      assertion (check_succ s b1); Some(BSnop mv s)\n  | Iop op args res s =>\n      match classify_operation op args with\n      | operation_Omove arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmove arg res mv s)\n      | operation_Omakelong arg1 arg2 =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmakelong arg1 arg2 res mv s)\n      | operation_Olowlong arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSlowlong arg res mv s)\n      | operation_Ohighlong arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BShighlong arg res mv s)\n      | operation_other _ _ =>\n          let (mv1, b1) := extract_moves nil b in\n          match b1 with\n          | Lop op' args' res' :: b2 =>\n              let (mv2, b3) := extract_moves nil b2 in\n              assertion (eq_operation op op');\n              assertion (check_succ s b3);\n              Some(BSop op args res mv1 args' res' mv2 s)\n          | _ =>\n              assertion (check_succ s b1);\n              Some(BSopdead op args res mv1 s)\n          end\n      end\n  | Iload chunk addr args dst s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lload chunk' addr' args' dst' :: b2 =>\n          if chunk_eq chunk Mint64 then\n            assertion (chunk_eq chunk' Mint32);\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lload chunk'' addr'' args'' dst'' :: b4 =>\n                let (mv3, b5) := extract_moves nil b4 in\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr''));\n                assertion (check_succ s b5);\n                Some(BSload2 addr addr'' args dst mv1 args' dst' mv2 args'' dst'' mv3 s)\n            | _ =>\n                assertion (check_succ s b3);\n                if (eq_addressing addr addr') then\n                  Some(BSload2_1 addr args dst mv1 args' dst' mv2 s)\n                else\n                 (assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr'));\n                  Some(BSload2_2 addr addr' args dst mv1 args' dst' mv2 s))\n            end\n          else (\n            let (mv2, b3) := extract_moves nil b2 in\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b3);\n            Some(BSload chunk addr args dst mv1 args' dst' mv2 s))\n      | _ =>\n          assertion (check_succ s b1);\n          Some(BSloaddead chunk addr args dst mv1 s)\n      end\n  | Istore chunk addr args src s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lstore chunk' addr' args' src' :: b2 =>\n          if chunk_eq chunk Mint64 then\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lstore chunk'' addr'' args'' src'' :: b4 =>\n                assertion (chunk_eq chunk' Mint32);\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr''));\n                assertion (check_succ s b4);\n                Some(BSstore2 addr addr'' args src mv1 args' src' mv2 args'' src'' s)\n            | _ => None\n            end\n          else (\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b2);\n            Some(BSstore chunk addr args src mv1 args' src' s))\n      | _ => None\n      end\n  | Icall sg ros args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcall sg' ros' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (signature_eq sg sg');\n          assertion (check_succ s b3);\n          Some(BScall sg ros args res mv1 ros' mv2 s)\n      | _ => None\n      end\n  | Itailcall sg ros args =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ltailcall sg' ros' :: b2 =>\n          assertion (signature_eq sg sg');\n          Some(BStailcall sg ros args mv1 ros')\n      | _ => None\n      end\n  | Ibuiltin ef args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lbuiltin ef' args' res' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (builtin_eq ef ef');\n          assertion (check_succ s b3);\n          Some(BSbuiltin ef args res mv1 args' res' mv2 s)\n      | Lannot ef' args' :: b2 =>\n          assertion (builtin_eq ef ef');\n          assertion (check_succ s b2);\n          match ef with\n          | EF_annot txt typ => Some(BSannot txt typ args res mv1 args' s)\n          | _ => None\n          end\n      | _ => None\n      end\n  | Icond cond args s1 s2 =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcond cond' args' s1' s2' :: b2 =>\n          assertion (eq_condition cond cond');\n          assertion (peq s1 s1');\n          assertion (peq s2 s2');\n          Some(BScond cond args mv1 args' s1 s2)\n      | _ => None\n      end\n  | Ijumptable arg tbl =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ljumptable arg' tbl' :: b2 =>\n          assertion (list_eq_dec peq tbl tbl');\n          Some(BSjumptable arg mv1 arg' tbl)\n      | _ => None\n      end\n  | Ireturn arg =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lreturn :: b2 => Some(BSreturn arg mv1)\n      | _ => None\n      end\n  end.\n\n(** Check all instructions of the RTL function [f1] against the corresponding\n  basic blocks of LTL function [f2].  Return a map from CFG nodes to\n  [block_shape] info. *)\n\nDefinition pair_codes (f1: RTL.function) (f2: LTL.function) : PTree.t block_shape :=\n  PTree.combine\n    (fun opti optb => do i <- opti; do b <- optb; pair_instr_block i b)\n    (RTL.fn_code f1) (LTL.fn_code f2).\n\n(** Check the entry point code of the LTL function [f2].  It must be\n  a sequence of moves that branches to the same node as the entry point\n  of RTL function [f1]. *)\n\nDefinition pair_entrypoints (f1: RTL.function) (f2: LTL.function) : option moves :=\n  do b <- (LTL.fn_code f2)!(LTL.fn_entrypoint f2);\n  let (mv, b1) := extract_moves nil b in\n  assertion (check_succ (RTL.fn_entrypoint f1) b1);\n  Some mv.\n\n(** * Representing sets of equations between RTL registers and LTL locations. *)\n\n(** The Rideau-Leroy validation algorithm manipulates sets of equations of\n  the form [pseudoreg = location [kind]], meaning:\n- if [kind = Full], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the value of [pseudoreg] in the original\n  RTL code;\n- if [kind = Low], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the low 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code;\n- if [kind = High], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the high 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code.\n*)\n\nInductive equation_kind : Type := Full | Low | High.\n\nRecord equation := Eq {\n  ekind: equation_kind;\n  ereg: reg;\n  eloc: loc\n}.\n\n(** We use AVL finite sets to represent sets of equations.  Therefore, we need\n  total orders over equations and their components. *)\n\nModule IndexedEqKind <: INDEXED_TYPE.\n  Definition t := equation_kind.\n  Definition index (x: t) :=\n    match x with Full => 1%positive | Low => 2%positive | High => 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 (x y: t) : {x=y} + {x<>y}.\n  Proof. decide equality. Defined.\nEnd IndexedEqKind.\n\nModule OrderedEqKind := OrderedIndexed(IndexedEqKind).\n\n(** This is an order over equations that is lexicographic on [ereg], then\n  [eloc], then [ekind]. *)\n\nModule OrderedEquation <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    (OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H. \n    destruct H0. left; eapply Plt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H. \n    destruct H0. auto. \n    destruct H0. right; split; auto.\n    intuition. \n    left; eapply OrderedLoc.lt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim Plt_strict; eauto.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedPositive.compare (ereg x) (ereg y)).\n  - apply LT. red; auto.\n  - destruct (OrderedLoc.compare (eloc x) (eloc y)).\n    + apply LT. red; auto. \n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red. \n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec (x y: t) : {x = y} + {x <> y}.\n  Proof.\n    intros. decide equality. \n    apply Loc.eq.\n    apply peq.\n    apply IndexedEqKind.eq.\n  Defined.\nEnd OrderedEquation.\n\n(** This is an alternate order over equations that is lexicgraphic on\n  [eloc], then [ereg], then [ekind]. *)\n\nModule OrderedEquation' <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    (Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H. \n    destruct H0. left; eapply OrderedLoc.lt_trans; eauto. \n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H. \n    destruct H0. auto. \n    destruct H0. right; split; auto.\n    intuition. \n    left; eapply Plt_trans; eauto. \n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim Plt_strict; eauto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedLoc.compare (eloc x) (eloc y)).\n  - apply LT. red; auto.\n  - destruct (OrderedPositive.compare (ereg x) (ereg y)).\n    + apply LT. red; auto. \n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red. \n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec: forall (x y: t), {x = y} + {x <> y} := OrderedEquation.eq_dec.\nEnd OrderedEquation'.\n\nModule EqSet := FSetAVLplus.Make(OrderedEquation).\nModule EqSet2 := FSetAVLplus.Make(OrderedEquation').\n\n(** We use a redundant representation for sets of equations, comprising\n  two AVL finite sets, containing the same elements, but ordered along\n  the two orders defined above.  Playing on properties of lexicographic\n  orders, this redundant representation enables us to quickly find\n  all equations involving a given RTL pseudoregister, or all equations\n  involving a given LTL location or overlapping location. *)\n\nRecord eqs := mkeqs {\n  eqs1 :> EqSet.t;\n  eqs2 : EqSet2.t;\n  eqs_same: forall q, EqSet2.In q eqs2 <-> EqSet.In q eqs1\n}.\n\n(** * Operations on sets of equations *)\n\n(** The empty set of equations. *)\n\nProgram Definition empty_eqs := mkeqs EqSet.empty EqSet2.empty _.\nNext Obligation.\n  split; intros. eelim EqSet2.empty_1; eauto. eelim EqSet.empty_1; eauto.\nQed.\n\n(** Adding or removing an equation from a set. *)\n\nProgram Definition add_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.add q (eqs1 e)) (EqSet2.add q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0). \n  apply EqSet.add_1; auto.\n  apply EqSet.add_2. apply (eqs_same e). apply EqSet2.add_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0). \n  apply EqSet2.add_1; auto.\n  apply EqSet2.add_2. apply (eqs_same e). apply EqSet.add_3 with q; auto.\nQed.\n\nProgram Definition remove_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.remove q (eqs1 e)) (EqSet2.remove q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0). \n  eelim EqSet2.remove_1; eauto.\n  apply EqSet.remove_2; auto. apply (eqs_same e). apply EqSet2.remove_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0). \n  eelim EqSet.remove_1; eauto.\n  apply EqSet2.remove_2; auto. apply (eqs_same e). apply EqSet.remove_3 with q; auto.\nQed.\n\n(** [reg_unconstrained r e] is true if [e] contains no equations involving\n  the RTL pseudoregister [r].  In other words, all equations [r' = l [kind]]\n  in [e] are such that [r' <> r]. *)\n\nDefinition select_reg_l (r: reg) (q: equation) := Pos.leb r (ereg q).\nDefinition select_reg_h (r: reg) (q: equation) := Pos.leb (ereg q) r.\n\nDefinition reg_unconstrained (r: reg) (e: eqs) : bool :=\n  negb (EqSet.mem_between (select_reg_l r) (select_reg_h r) (eqs1 e)).\n\n(** [loc_unconstrained l e] is true if [e] contains no equations involving\n  the LTL location [l] or a location that partially overlaps with [l].\n  In other words, all equations [r = l' [kind]] in [e] are such that\n  [Loc.diff l' l]. *)\n\nDefinition select_loc_l (l: loc) :=\n  let lb := OrderedLoc.diff_low_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lb with LT _ => false | _ => true end.\nDefinition select_loc_h (l: loc) :=\n  let lh := OrderedLoc.diff_high_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lh with GT _ => false | _ => true end.\n\nDefinition loc_unconstrained (l: loc) (e: eqs) : bool :=\n  negb (EqSet2.mem_between (select_loc_l l) (select_loc_h l) (eqs2 e)).\n\nDefinition reg_loc_unconstrained (r: reg) (l: loc) (e: eqs) : bool :=\n  reg_unconstrained r e && loc_unconstrained l e.\n\n(** [subst_reg r1 r2 e] simulates the effect of assigning [r2] to [r1] on [e].\n  All equations of the form [r1 = l [kind]] are replaced by [r2 = l [kind]].\n*)\n\nDefinition subst_reg (r1 r2: reg) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e => add_equation (Eq (ekind q) r2 (eloc q)) (remove_equation q e))\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_reg_kind r1 k1 r2 k2 e] simulates the effect of assigning\n  the [k2] part of [r2] to the [k1] part of [r1] on [e].\n  All equations of the form [r1 = l [k1]] are replaced by [r2 = l [k2]].\n*)\n\nDefinition subst_reg_kind (r1: reg) (k1: equation_kind) (r2: reg) (k2: equation_kind) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e =>\n      if IndexedEqKind.eq (ekind q) k1\n      then add_equation (Eq k2 r2 (eloc q)) (remove_equation q e)\n      else e)\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_loc l1 l2 e] simulates the effect of assigning [l2] to [l1] on [e].\n  All equations of the form [r = l1 [kind]] are replaced by [r = l2 [kind]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1]. \n*)\n\nDefinition subst_loc (l1 l2: loc) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            Some (add_equation (Eq (ekind q) (ereg q) l2) (remove_equation q e))\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [loc_type_compat env l e] checks that for all equations [r = l] in [e],\n  the type [env r] of [r] is compatible with the type of [l]. *)\n\nDefinition sel_type (k: equation_kind) (ty: typ) : typ :=\n  match k with\n  | Full => ty\n  | Low | High => Tint\n  end.\n\nDefinition loc_type_compat (env: regenv) (l: loc) (e: eqs) : bool :=\n  EqSet2.for_all_between\n    (fun q => subtype (sel_type (ekind q) (env (ereg q))) (Loc.type l))\n    (select_loc_l l) (select_loc_h l) (eqs2 e).\n\n(** [add_equations [r1...rN] [m1...mN] e] adds to [e] the [N] equations\n    [ri = R mi [Full]].  Return [None] if the two lists have different lengths.\n*)\n\nFixpoint add_equations (rl: list reg) (ml: list mreg) (e: eqs) : option eqs :=\n  match rl, ml with\n  | nil, nil => Some e\n  | r1 :: rl, m1 :: ml => add_equations rl ml (add_equation (Eq Full r1 (R m1)) e)\n  | _, _ => None\n  end.\n\n(** [add_equations_args] is similar but additionally handles the splitting\n  of pseudoregisters of type [Tlong] in two locations containing the\n  two 32-bit halves of the 64-bit integer. *)\n\nFunction add_equations_args (rl: list reg) (tyl: list typ) (ll: list loc) (e: eqs) : option eqs :=\n  match rl, tyl, ll with\n  | nil, nil, nil => Some e\n  | r1 :: rl, Tlong :: tyl, l1 :: l2 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Low r1 l2) (add_equation (Eq High r1 l1) e))\n  | r1 :: rl, (Tint|Tfloat|Tsingle) :: tyl, l1 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Full r1 l1) e)\n  | _, _, _ => None\n  end.\n\n(** [add_equations_res] is similar but is specialized to the case where\n  there is only one pseudo-register. *)\n\nFunction add_equations_res (r: reg) (oty: option typ) (ll: list loc) (e: eqs) : option eqs :=\n  match oty with\n  | Some Tlong =>\n      match ll with\n      | l1 :: l2 :: nil => Some (add_equation (Eq Low r l2) (add_equation (Eq High r l1) e))\n      | _ => None\n      end\n  | _ =>\n      match ll with\n      | l1 :: nil => Some (add_equation (Eq Full r l1) e)\n      | _ => None\n      end\n  end.\n\n(** [remove_equations_res] is similar to [add_equations_res] but removes\n  equations instead of adding them. *)\n\nFunction remove_equations_res (r: reg) (oty: option typ) (ll: list loc) (e: eqs) : option eqs :=\n  match oty with\n  | Some Tlong =>\n      match ll with\n      | l1 :: l2 :: nil =>\n          if Loc.diff_dec l2 l1\n          then Some (remove_equation (Eq Low r l2) (remove_equation (Eq High r l1) e))\n          else None\n      | _ => None\n      end\n  | _ =>\n      match ll with\n      | l1 :: nil => Some (remove_equation (Eq Full r l1) e)\n      | _ => None\n      end\n  end.\n\n(** [add_equations_ros] adds an equation, if needed, between an optional\n  pseudoregister and an optional machine register.  It is used for the\n  function argument of the [Icall] and [Itailcall] instructions. *)\n\nDefinition add_equation_ros (ros: reg + ident) (ros': mreg + ident) (e: eqs) : option eqs :=\n  match ros, ros' with\n  | inl r, inl mr => Some(add_equation (Eq Full r (R mr)) e)\n  | inr id, inr id' => assertion (ident_eq id id'); Some e\n  | _, _ => None\n  end.\n\n(** [can_undef ml] returns true if all machine registers in [ml] are\n  unconstrained and can harmlessly be undefined. *)\n\nFixpoint can_undef (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => loc_unconstrained (R m1) e && can_undef ml e\n  end.\n\nFixpoint can_undef_except (l: loc) (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => \n      (Loc.eq l (R m1) || loc_unconstrained (R m1) e) && can_undef_except l ml e\n  end.\n\n(** [no_caller_saves e] returns [e] if all caller-save locations are\n  unconstrained in [e].  In other words, [e] contains no equations\n  involving a caller-save register or [Outgoing] stack slot. *)\n\nDefinition no_caller_saves (e: eqs) : bool :=\n  EqSet.for_all\n   (fun eq =>\n     match eloc eq with\n       | R r =>\n           zle 0 (index_int_callee_save r) || zle 0 (index_float_callee_save r)\n       | S Outgoing _ _ => false\n       | S _ _ _ => true\n       end)\n    e.\n\n(** [compat_left r l e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l [Full]]. *)\n\nDefinition compat_left (r: reg) (l: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | Full => Loc.eq l (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [compat_left2 r l1 l2 e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l1 [High]] or [r = l2 [Low]]. *)\n\nDefinition compat_left2 (r: reg) (l1 l2: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | High => Loc.eq l1 (eloc q)\n        | Low => Loc.eq l2 (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [ros_compatible_tailcall ros] returns true if [ros] is a function\n  name or a caller-save register.  This is used to check [Itailcall]\n  instructions. *)\n\nDefinition ros_compatible_tailcall (ros: mreg + ident) : bool :=\n  match ros with\n  | inl r => In_dec mreg_eq r destroyed_at_call\n  | inr id => true\n  end.\n\n(** * The validator *)\n\nDefinition destroyed_by_move (src dst: loc) :=\n  match src, dst with\n  | S sl ofs ty, _ => destroyed_by_getstack sl\n  | _, S sl ofs ty => destroyed_by_setstack ty\n  | _, _ => destroyed_by_op Omove\n  end.\n\nDefinition well_typed_move (env: regenv) (dst: loc) (e: eqs) : bool :=\n  match dst with\n  | R r => true\n  | S sl ofs ty => loc_type_compat env dst e\n  end.\n\n(** Simulate the effect of a sequence of moves [mv] on a set of\n  equations [e].  The set [e] is the equations that must hold\n  after the sequence of moves.  Return the set of equations that\n  must hold before the sequence of moves.  Return [None] if the\n  set of equations [e] cannot hold after the sequence of moves. *)\n\nFixpoint track_moves (env: regenv) (mv: moves) (e: eqs) : option eqs :=\n  match mv with\n  | nil => Some e\n  | (src, dst) :: mv =>\n      do e1 <- track_moves env mv e;\n      assertion (can_undef_except dst (destroyed_by_move src dst)) e1;\n      assertion (well_typed_move env dst e1);\n      subst_loc dst src e1\n  end.\n\n(** [transfer_use_def args res args' res' undefs e] returns the set\n  of equations that must hold \"before\" in order for the equations [e]\n  to hold \"after\" the execution of RTL and LTL code of the following form:\n<<\n                RTL                            LTL\n         use pseudoregs args            use machine registers args'\n         define pseudoreg res           undefine machine registers undef\n                                        define machine register res'\n>>\n  As usual, [None] is returned if the equations [e] cannot hold after\n  this execution.\n*)\n\nDefinition transfer_use_def (args: list reg) (res: reg) (args': list mreg) (res': mreg)\n                            (undefs: list mreg) (e: eqs) : option eqs :=\n  let e1 := remove_equation (Eq Full res (R res')) e in\n  assertion (reg_loc_unconstrained res (R res') e1);\n  assertion (can_undef undefs e1);\n  add_equations args args' e1.\n\nDefinition kind_first_word := if Archi.big_endian then High else Low.\nDefinition kind_second_word := if Archi.big_endian then Low else High.\n\n(** The core transfer function.  It takes a set [e] of equations that must\n  hold \"after\" and a block shape [shape] representing a matching pair\n  of an RTL instruction and an LTL basic block.  It returns the set of\n  equations that must hold \"before\" these instructions, or [None] if\n  impossible. *)\n\nDefinition transfer_aux (f: RTL.function) (env: regenv)\n                        (shape: block_shape) (e: eqs) : option eqs :=\n  match shape with\n  | BSnop mv s =>\n      track_moves env mv e\n  | BSmove src dst mv s =>\n      track_moves env mv (subst_reg dst src e)\n  | BSmakelong src1 src2 dst mv s =>\n      let e1 := subst_reg_kind dst High src1 Full e in\n      let e2 := subst_reg_kind dst Low src2 Full e1 in\n      assertion (reg_unconstrained dst e2);\n      track_moves env mv e2\n  | BSlowlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src Low e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BShighlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src High e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BSop op args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args res args' res' (destroyed_by_op op) e1;\n      track_moves env mv1 e2\n  | BSopdead op args res mv s =>\n      assertion (reg_unconstrained res e);\n      track_moves env mv e\n  | BSload chunk addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args dst args' dst' (destroyed_by_load chunk addr) e1;\n      track_moves env mv1 e2\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s =>\n      do e1 <- track_moves env mv3 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst2')) e1 in\n      assertion (loc_unconstrained (R dst2') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args2' e2;\n      do e4 <- track_moves env mv2 e3;\n      let e5 := remove_equation (Eq kind_first_word dst (R dst1')) e4 in\n      assertion (loc_unconstrained (R dst1') e5);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e5);\n      assertion (reg_unconstrained dst e5);\n      do e6 <- add_equations args args1' e5;\n      track_moves env mv1 e6\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_first_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSloaddead chunk addr args dst mv s =>\n      assertion (reg_unconstrained dst e);\n      track_moves env mv e\n  | BSstore chunk addr args src mv args' src' s =>\n      assertion (can_undef (destroyed_by_store chunk addr) e);\n      do e1 <- add_equations (src :: args) (src' :: args') e;\n      track_moves env mv e1\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s =>\n      assertion (can_undef (destroyed_by_store Mint32 addr') e);\n      do e1 <- add_equations args args2' \n                  (add_equation (Eq kind_second_word src (R src2')) e);\n      do e2 <- track_moves env mv2 e1;\n      assertion (can_undef (destroyed_by_store Mint32 addr) e2);\n      do e3 <- add_equations args args1' \n                  (add_equation (Eq kind_first_word src (R src1')) e2);\n      track_moves env mv1 e3\n  | BScall sg ros args res mv1 ros' mv2 s =>\n      let args' := loc_arguments sg in\n      let res' := map R (loc_result sg) in\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_res res (sig_res sg) res' e1;\n      assertion (forallb (fun l => reg_loc_unconstrained res l e2) res');\n      assertion (no_caller_saves e2);\n      do e3 <- add_equation_ros ros ros' e2;\n      do e4 <- add_equations_args args (sig_args sg) args' e3;\n      track_moves env mv1 e4\n  | BStailcall sg ros args mv1 ros' =>\n      let args' := loc_arguments sg in\n      assertion (tailcall_is_possible sg);\n      assertion (opt_typ_eq sg.(sig_res) f.(RTL.fn_sig).(sig_res));\n      assertion (ros_compatible_tailcall ros');\n      do e1 <- add_equation_ros ros ros' empty_eqs;\n      do e2 <- add_equations_args args (sig_args sg) args' e1;\n      track_moves env mv1 e2\n  | BSbuiltin ef args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let args' := map R args' in\n      let res' := map R res' in\n      do e2 <- remove_equations_res res (sig_res (builtin_sig ef)) res' e1;\n      assertion (reg_unconstrained res e2);\n      assertion (forallb (fun l => loc_unconstrained l e2) res');\n      assertion (can_undef (destroyed_by_builtin ef) e2);\n      do e3 <- add_equations_args args (sig_args (builtin_sig ef)) args' e2;\n      track_moves env mv1 e3\n  | BSannot txt typ args res mv1 args' s =>\n      do e1 <- add_equations_args args (annot_args_typ typ) args' e;\n      track_moves env mv1 e1\n  | BScond cond args mv args' s1 s2 =>\n      assertion (can_undef (destroyed_by_cond cond) e);\n      do e1 <- add_equations args args' e;\n      track_moves env mv e1\n  | BSjumptable arg mv arg' tbl =>\n      assertion (can_undef destroyed_by_jumptable e);\n      track_moves env mv (add_equation (Eq Full arg (R arg')) e)\n  | BSreturn None mv =>\n      track_moves env mv empty_eqs\n  | BSreturn (Some arg) mv =>\n      let arg' := map R (loc_result (RTL.fn_sig f)) in\n      do e1 <- add_equations_res arg (sig_res (RTL.fn_sig f)) arg' empty_eqs;\n      track_moves env mv e1\n  end.\n\n(** The main transfer function for the dataflow analysis.  Like [transfer_aux],\n  it infers the equations that must hold \"before\" as a function of the\n  equations that must hold \"after\".  It also handles error propagation\n  and reporting. *)\n\nDefinition transfer (f: RTL.function) (env: regenv) (shapes: PTree.t block_shape)\n                    (pc: node) (after: res eqs) : res eqs :=\n  match after with\n  | Error _ => after\n  | OK e =>\n      match shapes!pc with\n      | None => Error(MSG \"At PC \" :: POS pc :: MSG \": unmatched block\" :: nil)\n      | Some shape =>\n          match transfer_aux f env shape e with\n          | None => Error(MSG \"At PC \" :: POS pc :: MSG \": invalid register allocation\" :: nil)\n          | Some e' => OK e'\n          end\n      end\n  end.\n\n(** The semilattice for dataflow analysis.  Operates on analysis results\n  of type [res eqs], that is, either a set of equations or an error\n  message.  Errors correspond to [Top].  Sets of equations are ordered\n  by inclusion. *)\n\nModule LEq <: SEMILATTICE.\n\n  Definition t := res eqs.\n\n  Definition eq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Equal a b\n    | Error _, Error _ => True\n    | _, _ => False\n    end.\n\n  Lemma eq_refl: forall x, eq x x.\n  Proof.\n    intros; destruct x; simpl; auto. red; tauto. \n  Qed.\n\n  Lemma eq_sym: forall x y, eq x y -> eq y x.\n  Proof.\n    unfold eq; intros; destruct x; destruct y; auto. \n    red in H; red; intros. rewrite H; tauto.\n  Qed. \n\n  Lemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    unfold eq; intros. destruct x; destruct y; try contradiction; destruct z; auto.\n    red in H; red in H0; red; intros. rewrite H. auto. \n  Qed.\n\n  Definition beq (x y: t) := \n    match x, y with\n    | OK a, OK b => EqSet.equal a b\n    | Error _, Error _ => true\n    | _, _ => false\n    end.\n\n  Lemma beq_correct: forall x y, beq x y = true -> eq x y.\n  Proof.\n    unfold beq, eq; intros. destruct x; destruct y. \n    apply EqSet.equal_2. auto.\n    discriminate.\n    discriminate.\n    auto.\n  Qed.\n\n  Definition ge (x y: t) := \n    match x, y with\n    | OK a, OK b => EqSet.Subset b a\n    | Error _, _ => True\n    | _, Error _ => False\n    end.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge, EqSet.Equal, EqSet.Subset; intros. \n    destruct x; destruct y; auto. intros; rewrite H; auto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge, EqSet.Subset; intros.\n    destruct x; auto; destruct y; try contradiction.\n    destruct z; eauto. \n  Qed.\n\n  Definition bot: t := OK empty_eqs.\n \n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot, EqSet.Subset; simpl; intros.\n    destruct x; auto. intros. elim (EqSet.empty_1 H).\n  Qed.\n\n  Program Definition lub (x y: t) : t :=\n    match x, y return _ with\n    | OK a, OK b =>\n        OK (mkeqs (EqSet.union (eqs1 a) (eqs1 b))\n                  (EqSet2.union (eqs2 a) (eqs2 b)) _)\n    | OK _, Error _ => y\n    | Error _, _ => x\n    end.\n  Next Obligation.\n    split; intros. \n    apply EqSet2.union_1 in H. destruct H; rewrite eqs_same in H. \n    apply EqSet.union_2; auto. apply EqSet.union_3; auto.\n    apply EqSet.union_1 in H. destruct H; rewrite <- eqs_same in H. \n    apply EqSet2.union_2; auto. apply EqSet2.union_3; auto.\n  Qed.\n\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub, ge, EqSet.Subset; intros. \n    destruct x; destruct y; auto. \n    intros; apply EqSet.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, EqSet.Subset; intros. \n    destruct x; destruct y; auto. \n    intros; apply EqSet.union_3; auto. \n  Qed.\n\nEnd LEq.\n\n(** The backward dataflow solver is an instantiation of Kildall's algorithm. *)\n\nModule DS := Backward_Dataflow_Solver(LEq)(NodeSetBackward).\n\n(** The control-flow graph that the solver operates on is the CFG of\n  block shapes built by the structural check phase.  Here is its notion\n  of successors. *)\n\nDefinition successors_block_shape (bsh: block_shape) : list node :=\n  match bsh with\n  | BSnop mv s => s :: nil\n  | BSmove src dst mv s => s :: nil\n  | BSmakelong src1 src2 dst mv s => s :: nil\n  | BSlowlong src dst mv s => s :: nil\n  | BShighlong src dst mv s => s :: nil\n  | BSop op args res mv1 args' res' mv2 s => s :: nil\n  | BSopdead op args res mv s => s :: nil\n  | BSload chunk addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s => s :: nil\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s => s :: nil\n  | BSloaddead chunk addr args dst mv s => s :: nil\n  | BSstore chunk addr args src mv1 args' src' s => s :: nil\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s => s :: nil\n  | BScall sg ros args res mv1 ros' mv2 s => s :: nil\n  | BStailcall sg ros args mv1 ros' => nil\n  | BSbuiltin ef args res mv1 args' res' mv2 s => s :: nil\n  | BSannot txt typ args res mv1 args' s => s :: nil\n  | BScond cond args mv args' s1 s2 => s1 :: s2 :: nil\n  | BSjumptable arg mv arg' tbl => tbl\n  | BSreturn optarg mv => nil\n  end.\n\nDefinition analyze (f: RTL.function) (env: regenv) (bsh: PTree.t block_shape) :=\n  DS.fixpoint_allnodes bsh successors_block_shape (transfer f env bsh).\n\n(** * Validating and translating functions and programs *)\n\n(** Checking equations at function entry point.  The RTL function receives\n  its arguments in the list [rparams] of pseudoregisters.  The LTL function\n  receives them in the list [lparams] of locations dictated by the\n  calling conventions, with arguments of type [Tlong] being split in\n  two 32-bit halves.  We check that the equations [e] that must hold\n  at the beginning of the functions are compatible with these calling\n  conventions, in the sense that all equations involving a pseudoreg\n  [r] from [rparams] is of the form [r = l [Full]] or [r = l [Low]]\n  or [r = l [High]], where [l] is the corresponding element of [lparams].\n\n  Note that [e] can contain additional equations [r' = l [kind]]\n  involving pseudoregs [r'] not in [rparams]: these equations are\n  automatically satisfied since the initial value of [r'] is [Vundef]. *)\n\nFunction compat_entry (rparams: list reg) (tys: list typ) (lparams: list loc) (e: eqs)\n                      {struct rparams} : bool :=\n  match rparams, tys, lparams with\n  | nil, nil, nil => true\n  | r1 :: rl, Tlong :: tyl, l1 :: l2 :: ll =>\n      compat_left2 r1 l1 l2 e && compat_entry rl tyl ll e\n  | r1 :: rl, (Tint|Tfloat|Tsingle) :: tyl, l1 :: ll =>\n      compat_left r1 l1 e && compat_entry rl tyl ll e\n  | _, _, _ => false\n  end.\n\n(** Checking the satisfiability of equations inferred at function entry\n  point.  We also check that the RTL and LTL functions agree in signature\n  and stack size. *)\n\nDefinition check_entrypoints_aux (rtl: RTL.function) (ltl: LTL.function)\n                                 (env: regenv) (e1: eqs) : option unit :=\n  do mv <- pair_entrypoints rtl ltl;\n  do e2 <- track_moves env mv e1;\n  assertion (compat_entry (RTL.fn_params rtl)\n                          (sig_args (RTL.fn_sig rtl))\n                          (loc_parameters (RTL.fn_sig rtl)) e2);\n  assertion (can_undef destroyed_at_function_entry e2);\n  assertion (zeq (RTL.fn_stacksize rtl) (LTL.fn_stacksize ltl));\n  assertion (signature_eq (RTL.fn_sig rtl) (LTL.fn_sig ltl));\n  Some tt.\n\nLocal Close Scope option_monad_scope.\nLocal Open Scope error_monad_scope.\n\nDefinition check_entrypoints (rtl: RTL.function) (ltl: LTL.function)\n                             (env: regenv) (bsh: PTree.t block_shape)\n                             (a: PMap.t LEq.t): res unit :=\n  do e1 <- transfer rtl env bsh (RTL.fn_entrypoint rtl) a!!(RTL.fn_entrypoint rtl);\n  match check_entrypoints_aux rtl ltl env e1 with\n  | None => Error (msg \"invalid register allocation at entry point\")\n  | Some _ => OK tt\n  end.\n\n(** Putting it all together, this is the validation function for\n  a source RTL function and an LTL function generated by the external\n  register allocator. *)\n\nDefinition check_function (rtl: RTL.function) (ltl: LTL.function) (env: regenv): res unit :=\n  let bsh := pair_codes rtl ltl in\n  match analyze rtl env bsh with\n  | None => Error (msg \"allocation analysis diverges\")\n  | Some a => check_entrypoints rtl ltl env bsh a\n  end.\n\n(** [regalloc] is the external register allocator.  It is written in OCaml\n  in file [backend/Regalloc.ml]. *)\n\nParameter regalloc: RTL.function -> res LTL.function.\n\n(** Register allocation followed by validation. *)\n\nDefinition transf_function (f: RTL.function) : res LTL.function :=\n  match type_function f with\n  | Error m => Error m\n  | OK env =>\n      match regalloc f with\n      | Error m => Error m\n      | OK tf => do x <- check_function f tf env; OK tf\n      end\n  end.\n\nDefinition transf_fundef (fd: RTL.fundef) : res LTL.fundef :=\n  AST.transf_partial_fundef transf_function fd.\n\nDefinition transf_program (p: RTL.program) : res LTL.program :=\n  transform_partial_program transf_fundef p.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.17928955007993203}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable p_ : Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Universe -> Prop.\nVariable goal_ : Prop.\nVariable dom_ : Universe -> Prop.\n\nVariable a9_ : Universe.\nVariable a8_ : Universe.\nVariable a7_ : Universe.\nVariable a6_ : Universe.\nVariable a5_ : Universe.\nVariable a4_ : Universe.\nVariable a38_ : Universe.\nVariable a37_ : Universe.\nVariable a36_ : Universe.\nVariable a35_ : Universe.\nVariable a34_ : Universe.\nVariable a33_ : Universe.\nVariable a32_ : Universe.\nVariable a31_ : Universe.\nVariable a30_ : Universe.\nVariable a3_ : Universe.\nVariable a29_ : Universe.\nVariable a28_ : Universe.\nVariable a27_ : Universe.\nVariable a26_ : Universe.\nVariable a25_ : Universe.\nVariable a24_ : Universe.\nVariable a23_ : Universe.\nVariable a22_ : Universe.\nVariable a21_ : Universe.\nVariable a20_ : Universe.\nVariable a2_ : Universe.\nVariable a19_ : Universe.\nVariable a18_ : Universe.\nVariable a17_ : Universe.\nVariable a16_ : Universe.\nVariable a15_ : Universe.\nVariable a14_ : Universe.\nVariable a13_ : Universe.\nVariable a12_ : Universe.\nVariable a11_ : Universe.\nVariable a10_ : Universe.\nVariable a1_ : Universe.\n\nVariable ax1_1 : (dom_ a1_ /\\ (dom_ a2_ /\\ (dom_ a3_ /\\ (dom_ a4_ /\\ (dom_ a5_ /\\ (dom_ a6_ /\\ (dom_ a7_ /\\ (dom_ a8_ /\\ (dom_ a9_ /\\ (dom_ a10_ /\\ (dom_ a11_ /\\ (dom_ a12_ /\\ (dom_ a13_ /\\ (dom_ a14_ /\\ (dom_ a15_ /\\ (dom_ a16_ /\\ (dom_ a17_ /\\ (dom_ a18_ /\\ (dom_ a19_ /\\ (dom_ a20_ /\\ (dom_ a21_ /\\ (dom_ a22_ /\\ (dom_ a23_ /\\ (dom_ a24_ /\\ (dom_ a25_ /\\ (dom_ a26_ /\\ (dom_ a27_ /\\ (dom_ a28_ /\\ (dom_ a29_ /\\ (dom_ a30_ /\\ (dom_ a31_ /\\ (dom_ a32_ /\\ (dom_ a33_ /\\ (dom_ a34_ /\\ (dom_ a35_ /\\ (dom_ a36_ /\\ (dom_ a37_ /\\ dom_ a38_))))))))))))))))))))))))))))))))))))).\nVariable ax2_2 : (forall A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24 A25 A26 A27 A28 A29 A30 A31 A32 A33 A34 A35 A36 A37 A38 : Universe, ((dom_ A1 /\\ (dom_ A2 /\\ (dom_ A3 /\\ (dom_ A4 /\\ (dom_ A5 /\\ (dom_ A6 /\\ (dom_ A7 /\\ (dom_ A8 /\\ (dom_ A9 /\\ (dom_ A10 /\\ (dom_ A11 /\\ (dom_ A12 /\\ (dom_ A13 /\\ (dom_ A14 /\\ (dom_ A15 /\\ (dom_ A16 /\\ (dom_ A17 /\\ (dom_ A18 /\\ (dom_ A19 /\\ (dom_ A20 /\\ (dom_ A21 /\\ (dom_ A22 /\\ (dom_ A23 /\\ (dom_ A24 /\\ (dom_ A25 /\\ (dom_ A26 /\\ (dom_ A27 /\\ (dom_ A28 /\\ (dom_ A29 /\\ (dom_ A30 /\\ (dom_ A31 /\\ (dom_ A32 /\\ (dom_ A33 /\\ (dom_ A34 /\\ (dom_ A35 /\\ (dom_ A36 /\\ (dom_ A37 /\\ dom_ A38))))))))))))))))))))))))))))))))))))) -> p_ A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 A22 A23 A24 A25 A26 A27 A28 A29 A30 A31 A32 A33 A34 A35 A36 A37 A38)).\nVariable ax3_3 : (p_ a38_ a37_ a36_ a35_ a34_ a33_ a32_ a31_ a30_ a29_ a28_ a27_ a26_ a25_ a24_ a23_ a22_ a21_ a20_ a19_ a18_ a17_ a16_ a15_ a14_ a13_ a12_ a11_ a10_ a9_ a8_ a7_ a6_ a5_ a4_ a3_ a2_ a1_ -> goal_).\n\nTheorem lemma38_4 : 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/crafted-hard/l38_hard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.17928954658066915}}
{"text": "(* Uniqueness of Typing *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom MetaCoq Require Import Ast utils Typing.\nFrom Translation\nRequire Import util SAst SLiftSubst Equality SCommon Conversion ITyping\n               ITypingInversions ITypingLemmata ContextConversion.\nImport ListNotations.\n\nSection Uniqueness.\n\nContext `{Sort_notion : Sorts.notion}.\n\nLtac unitac h1 h2 :=\n  ttinv h1 ; ttinv h2 ;\n  eapply conv_trans ; [\n    eapply conv_sym ; eassumption\n  | idtac\n  ].\n\nLemma uniqueness :\n  forall {\u03a3 \u0393 A B u},\n    type_glob \u03a3 ->\n    \u03a3 ;;; \u0393 |-i u : A ->\n    \u03a3 ;;; \u0393 |-i u : B ->\n    A \u2261 B.\nProof.\n  intros \u03a3 \u0393 A B u hg h1 h2.\n  revert \u0393 A B h1 h2.\n  induction u ; intros \u0393 A B h1 h2.\n  all: try unitac h1 h2. all: try assumption.\n  - cbn in *. erewrite @safe_nth_irr with (isdecl' := is) in h0. assumption.\n  - specialize (IHu1 _ _ _ h0 h5).\n    specialize (IHu2 _ _ _ h h3).\n    eapply conv_trans. 2: eapply h7.\n    pose proof (sort_conv_inv IHu1) as e1.\n    pose proof (sort_conv_inv IHu2) as e2.\n    subst. apply conv_refl.\n  - eapply nl_conv ; try eassumption ; reflexivity.\n  - specialize (IHu1 _ _ _ h0 h5).\n    specialize (IHu2 _ _ _ h h3).\n    eapply conv_trans. 2: eapply h7.\n    pose proof (sort_conv_inv IHu1) as e1.\n    pose proof (sort_conv_inv IHu2) as e2.\n    subst. apply conv_refl.\n  - eapply conv_trans ; [| exact h11 ].\n    apply cong_Sum ; apply conv_refl.\n  - specialize (IHu1 _ _ _ h0 h6).\n    pose proof (sort_conv_inv IHu1) as e. subst. assumption.\n  - specialize (IHu1 _ _ _ h0 h7).\n    pose proof (sort_conv_inv IHu1) as e. subst. assumption.\n  - specialize (IHu _ _ _ h0 h7).\n    pose proof (heq_conv_inv IHu) as e. split_hyps.\n    eapply conv_trans. 2: exact h11.\n    apply cong_Eq ; assumption.\n  - specialize (IHu _ _ _ h5 h11).\n    pose proof (heq_conv_inv IHu) as e. split_hyps.\n    eapply conv_trans ; [ | exact h13 ].\n    apply cong_Heq ; assumption.\n  - specialize (IHu1 _ _ _ h7 h16).\n    specialize (IHu2 _ _ _ h8 h17).\n    pose proof (heq_conv_inv IHu1) as e1.\n    pose proof (heq_conv_inv IHu2) as e2. split_hyps.\n    eapply conv_trans ; [ | exact h19 ].\n    apply cong_Heq ; assumption.\n  - specialize (IHu1 _ _ _ h4 h9).\n    specialize (IHu2 _ _ _ h3 h8).\n    pose proof (eq_conv_inv IHu1) as e1. split_hyps.\n    eapply conv_trans ; [| exact h11 ].\n    apply cong_Heq ; try assumption.\n    + apply conv_refl.\n    + apply cong_Transport ; try assumption.\n      all: apply conv_refl.\n  - specialize (IHu3 _ _ _ h0 h9).\n    pose proof (heq_conv_inv IHu3) as e3. split_hyps.\n    pose proof (sort_conv_inv H). subst.\n    assert (hh : \u03a3 ;;; \u0393,, A1 |-i u1 : sSort z0).\n    { eapply type_ctxconv ; try eassumption.\n      - econstructor ; try eassumption.\n        eapply typing_wf. eassumption.\n      - constructor.\n        + apply ctxconv_refl.\n        + apply conv_sym. assumption.\n    }\n    specialize (IHu1 _ _ _ h5 hh).\n    pose proof (sort_conv_inv IHu1). subst.\n    eapply conv_trans ; [| exact h15 ].\n    apply cong_Heq.\n    + apply conv_refl.\n    + apply cong_Prod ; try assumption.\n      apply conv_refl.\n    + apply conv_refl.\n    + apply cong_Prod ; try assumption. apply conv_refl.\n  - specialize (IHu5 _ _ _ h0 h12).\n    pose proof (heq_conv_inv IHu5) as e5. split_hyps.\n    pose proof (sort_conv_inv H). subst.\n    eapply conv_trans ; [| exact h21 ].\n    apply cong_Heq ; try assumption.\n    + apply cong_Prod ; try assumption. apply conv_refl.\n    + apply cong_Lambda ; try assumption. all: apply conv_refl.\n    + apply cong_Prod ; try assumption. apply conv_refl.\n    + apply cong_Lambda ; try assumption. all: apply conv_refl.\n  - specialize (IHu3 _ _ _ h3 h16).\n    specialize (IHu4 _ _ _ h0 h15).\n    specialize (IHu6 _ _ _ h4 h17).\n    pose proof (heq_conv_inv IHu3).\n    pose proof (heq_conv_inv IHu4).\n    pose proof (heq_conv_inv IHu6).\n    split_hyps.\n    eapply conv_trans ; [| exact h27 ].\n    apply cong_Heq ; try assumption.\n    + apply substs_conv. assumption.\n    + apply cong_App ; try assumption. apply conv_refl.\n    + apply substs_conv. assumption.\n    + apply cong_App ; try assumption. apply conv_refl.\n  - specialize (IHu3 _ _ _ h0 h9).\n    pose proof (heq_conv_inv IHu3) as e3. split_hyps.\n    pose proof (sort_conv_inv H). subst.\n    assert (hh : \u03a3 ;;; \u0393,, A1 |-i u1 : sSort z0).\n    { eapply type_ctxconv ; try eassumption.\n      - econstructor ; try eassumption.\n        eapply typing_wf. eassumption.\n      - constructor.\n        + apply ctxconv_refl.\n        + apply conv_sym. assumption.\n    }\n    specialize (IHu1 _ _ _ h5 hh).\n    pose proof (sort_conv_inv IHu1). subst.\n    eapply conv_trans ; [| exact h15 ].\n    apply cong_Heq.\n    + apply conv_refl.\n    + apply cong_Sum ; try assumption.\n      apply conv_refl.\n    + apply conv_refl.\n    + apply cong_Sum ; try assumption. apply conv_refl.\n  - specialize IHu3 with (1 := h0) (2 := h15).\n    specialize IHu5 with (1 := h3) (2 := h16).\n    specialize IHu6 with (1 := h4) (2 := h17).\n    pose proof (heq_conv_inv IHu3).\n    pose proof (heq_conv_inv IHu5).\n    pose proof (heq_conv_inv IHu6).\n    split_hyps.\n    eapply conv_trans ; [| exact h27 ].\n    apply cong_Heq.\n    + apply cong_Sum ; try apply conv_refl. assumption.\n    + apply cong_Pair ; try apply conv_refl ; assumption.\n    + apply cong_Sum ; try apply conv_refl. assumption.\n    + apply cong_Pair ; try apply conv_refl ; assumption.\n  - specialize IHu3 with (1 := h0) (2 := h12).\n    specialize IHu5 with (1 := h3) (2 := h13).\n    pose proof (heq_conv_inv IHu3).\n    pose proof (heq_conv_inv IHu5).\n    split_hyps.\n    eapply conv_trans ; [| exact h21 ].\n    apply cong_Heq ; try assumption.\n    + apply cong_Pi1 ; try assumption. apply conv_refl.\n    + apply cong_Pi1 ; try assumption. apply conv_refl.\n  - specialize IHu3 with (1 := h0) (2 := h12).\n    specialize IHu5 with (1 := h3) (2 := h13).\n    pose proof (heq_conv_inv IHu3).\n    pose proof (heq_conv_inv IHu5).\n    split_hyps.\n    eapply conv_trans ; [| exact h21 ].\n    apply cong_Heq ; try assumption.\n    + apply substs_conv.\n      apply cong_Pi1 ; try assumption. apply conv_refl.\n    + apply cong_Pi2 ; try assumption. apply conv_refl.\n    + apply substs_conv.\n      apply cong_Pi1 ; try assumption. apply conv_refl.\n    + apply cong_Pi2 ; try assumption. apply conv_refl.\n  - specialize (IHu1 _ _ _ h0 h12).\n    specialize (IHu2 _ _ _ h h10).\n    specialize (IHu3 _ _ _ h3 h13).\n    pose proof (heq_conv_inv IHu1).\n    pose proof (heq_conv_inv IHu2).\n    pose proof (heq_conv_inv IHu3).\n    split_hyps. subst.\n    pose proof (sort_conv_inv H). subst.\n    eapply conv_trans ; [| exact h21 ].\n    apply cong_Heq ; try apply conv_refl.\n    + apply cong_Eq ; assumption.\n    + apply cong_Eq ; assumption.\n  - specialize (IHu1 _ _ _ h0 h9).\n    specialize (IHu2 _ _ _ h h7).\n    pose proof (heq_conv_inv IHu1).\n    pose proof (heq_conv_inv IHu2).\n    split_hyps.\n    pose proof (sort_conv_inv H). subst.\n    eapply conv_trans ; [| exact h15 ].\n    apply cong_Heq.\n    + apply cong_Eq ; assumption.\n    + apply cong_Refl ; assumption.\n    + apply cong_Eq ; assumption.\n    + apply cong_Refl ; assumption.\n  - specialize (IHu _ _ _ h0 h7).\n    pose proof (eq_conv_inv IHu). split_hyps.\n    eapply conv_trans ; [| exact h11 ].\n    apply cong_Heq ; assumption.\n  - specialize (IHu1 _ _ _ h h6).\n    specialize (IHu3 _ _ _ h0 h8).\n    apply conv_sym in IHu1. pose proof (sort_conv_inv IHu1). subst.\n    pose proof (heq_conv_inv IHu3). split_hyps.\n    eapply conv_trans ; [| exact h13 ].\n    apply cong_Eq ; assumption.\n  - specialize (IHu1 _ _ _ h0 h5).\n    eapply conv_trans ; [| exact h7 ].\n    assumption.\n  - specialize (IHu _ _ _ h3 h7).\n    pose proof (pack_conv_inv IHu).\n    split_hyps.\n    eapply conv_trans ; [| exact h9 ].\n    assumption.\n  - specialize (IHu _ _ _ h3 h7).\n    pose proof (pack_conv_inv IHu).\n    split_hyps.\n    eapply conv_trans ; [| exact h9 ].\n    assumption.\n  - specialize (IHu _ _ _ h3 h7).\n    pose proof (pack_conv_inv IHu).\n    split_hyps.\n    eapply conv_trans ; [| exact h9 ].\n    apply cong_Heq ; try assumption ; apply conv_refl.\n  - rewrite h4 in h0. inversion h0. subst. assumption.\nDefined.\n\nEnd Uniqueness.", "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/Uniqueness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.17927716416084485}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.compact_prod_sum.\nRequire Import VST.floyd.mapsto_memory_block.\nRequire Import VST.floyd.nested_pred_lemmas.\nRequire Import VST.floyd.jmeq_lemmas.\nRequire Import VST.zlist.sublist.\n\nRequire Export VST.floyd.fieldlist.\nRequire Export VST.floyd.aggregate_type.\n\nOpen Scope Z.\nOpen Scope logic.\n\n(******************************************\n\nDefinition and lemmas about rangespec\n\n******************************************)\n\nFixpoint rangespec (lo: Z) (n: nat) (P: Z -> val -> mpred): val -> mpred :=\n  match n with\n  | O => fun _ => emp\n  | S n' => P lo * rangespec (Z.succ 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 (Z.succ 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; [| lia].\n      rewrite Nat2Z.inj_succ.\n      rewrite <- Z.add_1_r.\n      lia.\n    - apply IHlen. intros.\n      apply H; [| lia].\n      rewrite Nat2Z.inj_succ.\n      rewrite <- Z.add_1_r.\n      pose proof Zle_0_nat (S len).\n      lia.\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 lia.\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      apply derives_refl.\n  + erewrite H; eauto.\n      apply derives_refl.\n    lia.\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. lia.\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      lia.\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}{d: Inhabitant 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)) p.\n\nDefinition struct_pred (m: members) {A: member -> Type} (P: forall it, A it -> val -> mpred) (v: compact_prod (map A m)) (p: val): mpred.\nProof.\n  destruct m as [| a m]; [exact emp | ].\n  revert a v; induction m as [| b m]; intros ? v.\n  + simpl in v.\n    exact (P _ v p).\n  + simpl in v.\n    exact ((P _ (fst v) p) * IHm _ (snd v)).\nDefined.\n\n(* when unfold, do cbv [struct_pred list_rect]. *)\n\nDefinition union_pred (m: members) {A: member -> Type} (P: forall it, A it -> val -> mpred) (v: compact_sum (map A m)) (p: val): mpred.\nProof.\n  destruct m as [| a m]; [exact emp |].\n  revert a v; induction m as [| b 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 _ 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: member -> Type}\n                             (P: forall it, A it -> Prop) (v: compact_prod (map A m)) : Prop.\nProof.\n  destruct m as [| a m]; [exact True | ].\n  revert a v; induction m as [| b m]; intros ? v.\n  + simpl in v.\n    exact (P _ v).\n  + simpl in v.\n    exact ((P _ (fst v)) /\\ IHm _ (snd v)).\nDefined.\n\nDefinition union_Prop (m: members) {A: member -> Type}\n               (P: forall it, A it -> Prop) (v: compact_sum (map A m)): Prop.\nProof.\n  destruct m as [| a m]; [exact True |].\n  revert a v; induction m as [| b 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 _ v).\nDefined.\n\n(******************************************\n\nProperties\n\n******************************************)\n\nLemma array_pred_len_0: forall {A}{d: Inhabitant A} lo hi P p,\n  hi = lo ->\n  array_pred lo hi P (@nil A) p = emp.\nProof.\n  intros.\n  unfold array_pred.\n  replace (Z.to_nat (hi - lo)) with 0%nat by (symmetry; apply Z_to_nat_neg; lia).\n  simpl.\n  rewrite prop_true_andp by (unfold Zlength; simpl; lia).\n  reflexivity.\nQed.\n\nLemma array_pred_len_1: forall {A}{d: Inhabitant A} i P (v: A) p,\n  array_pred 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 lia.\n  simpl. rewrite sepcon_emp.\n  rewrite prop_true_andp by (unfold Zlength; simpl; lia).\n  unfold Znth. rewrite Z.sub_diag. rewrite if_false by lia. change (Z.to_nat 0) with 0%nat. auto.\nQed.\n\nLemma split_array_pred: forall {A}{d: Inhabitant A} lo mid hi P (v: list A) p,\n  lo <= mid <= hi ->\n  Zlength v = hi - lo ->\n  array_pred lo hi P v p =\n  array_pred lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred 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 lia; lia).\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 lia; f_equal; lia).\n  assert (lo = mid - Z.of_nat n)\n    by (rewrite Heqn; rewrite Z2Nat.id by lia; lia).\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, Nat.add_0_l.\n    apply rangespec_ext; intros.\n    rewrite Z2Nat.id in H0 by lia.\n    f_equal.\n    rewrite Znth_sublist, Z.add_0_r by lia.\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; lia).\n      reflexivity.\n    - replace (rangespec (Z.succ lo) (n + Z.to_nat (hi - mid))\n              (fun i : Z => P i (Znth (i - lo) v)) 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))) p).\n      2:{\n        apply rangespec_ext; intros.\n        f_equal.\n        rewrite <- Znth_succ by lia; auto.\n      }\n      rewrite Nat2Z.inj_succ in H0.\n      rewrite IHn by lia.\n      f_equal.\n      * apply rangespec_ext; intros.\n        f_equal.\n        rewrite Znth_sublist, Z.add_0_r by lia.\n        rewrite <- Znth_succ by lia; auto.\n        rewrite Znth_sublist, Z.add_0_r by lia.\n        reflexivity.\n      * apply rangespec_ext; intros.\n        f_equal.\n        rewrite Z2Nat.id in H1 by lia.\n        rewrite Znth_sublist by lia.\n        rewrite Znth_sublist by lia.\n        replace (i - mid + (mid - Z.succ lo)) with (i - Z.succ lo) by lia.\n        rewrite <- Znth_succ by lia; auto.\n         f_equal; lia.\nQed.\n\nLemma array_pred_shift: forall {A}{d: Inhabitant A} (lo hi lo' hi' mv : Z) P' P (v: list A) 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) p = P i (Znth (i-lo) v) p) ->\n  array_pred lo' hi' P' v p = array_pred lo hi P v p.\nProof.\n  intros.\n  unfold array_pred.\n  apply andp_prop_ext; [lia | intros].\n  replace (hi' - lo') with (hi - lo) by lia.\n  destruct (zlt hi lo). rewrite Z2Nat_neg by lia. reflexivity.\n  apply pred_ext; apply rangespec_shift_derives; intros.\n  rewrite H4; rewrite Z2Nat.id in H3 by lia.\n  rewrite H1; auto; lia.\n  rewrite <- H4; rewrite Z2Nat.id in H3 by lia.\n  rewrite H1; auto; lia.\nQed.\n\nLemma array_pred_ext_derives: forall {A B} (dA: Inhabitant A) (dB: Inhabitant B)\n         lo hi P0 P1 (v0: list A) (v1: list B) p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0) p |-- P1 i (Znth (i-lo) v1) p) ->\n  array_pred  lo hi P0 v0 p |-- array_pred lo hi P1 v1 p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  rewrite prop_true_andp by lia.\n  apply rangespec_ext_derives.\n  intros.\n  destruct (zlt hi lo).\n  + rewrite Z2Nat_neg  in H2 by lia.\n    change (Z.of_nat 0) with 0 in H2. lia.\n  + rewrite Z2Nat.id in H2 by lia.\n    apply H0. lia.\nQed.\n\nLemma array_pred_ext: forall {A B} (dA: Inhabitant A) (dB: Inhabitant B) lo hi P0 P1 \n        (v0: list A) (v1: list B) p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0) p = P1 i (Znth (i-lo) v1) p) ->\n  array_pred lo hi P0 v0 p = array_pred lo hi P1 v1 p.\nProof.\n  intros; apply pred_ext; apply array_pred_ext_derives; intros; try lia;\n  rewrite H0; auto.\nQed.\n\nLemma at_offset_array_pred: forall  {A} {d: Inhabitant A} lo hi P (v: list A) ofs p,\n  at_offset (array_pred lo hi P v) ofs p = array_pred 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 lia; subst i'; clear H0.\n  rewrite at_offset_eq.\n  auto.\nQed.\n\nLemma array_pred_sepcon: forall  {A} {d: Inhabitant A} lo hi P Q (v: list A) p,\n  array_pred lo hi P v p * array_pred lo hi Q v p = array_pred lo hi (P * Q) v p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  apply andp_prop_ext; [lia | intros].\n  rewrite rangespec_sepcon.\n  auto.\nQed.\n\nOpaque member_dec.\n\nLemma name_member_get:\n  forall i m, name_member (get_member i m) = i.\nProof.\ninduction m; simpl; intros.\nauto.\nif_tac.\nauto.\nauto.\nQed.\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 [| a0 m]; [simpl; auto |].\n  revert a0 v0 v1 H H0; induction m as [| a1 m]; intros.\n  + specialize (H0 (name_member a0)).\n    simpl in H0.\n    if_tac in H0; [| congruence].\n    specialize (H0 v0 v1).\n    spec H0; [left; reflexivity |].\n    destruct (member_dec a0 a0); [| congruence].\n    unfold eq_rect_r in H0; rewrite <- !eq_rect_eq in H0.\n    simpl.\n    exact H0.\n  + change (struct_pred (a0:: a1 :: m) P0 v0 p) with\n      (P0 a0 (fst v0) p * struct_pred (a1 :: m) P0 (snd v0) p).\n    change (struct_pred (a0 :: a1 :: m) P1 v1 p) with\n      (P1 a0 (fst v1) p * struct_pred (a1 :: m) P1 (snd v1) p).\n    apply sepcon_derives.\n    - specialize (H0 (name_member a0)).\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 a0 a0); [| 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 (name_member a1) then a1 else get_member i m)\n                    with (get_member i (a1::m)) in H0.\n        destruct (member_dec (get_member i (a1::m)) a0); [ | exact H0].\n        exfalso; clear - e H2. subst a0.\n        rewrite name_member_get in H2. contradiction.\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;      apply derives_refl.\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 (name_member 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 [| a0 m]; [auto |].\n  unfold proj_struct, field_type in *.\n  revert a0 H v; induction m as [| a1 m]; intros a0 H.\n  + intros; subst P'; simpl.\n    rewrite if_false; auto.\n    intro; apply H; subst; left; auto.\n  + set (M := a1 :: m).\n    simpl compact_prod; simpl Ctypes.field_type.\n    intros v.\n    subst M.\n    change (struct_pred (a0:: a1 :: m) P v p)\n      with (P _ (fst v) p * struct_pred (a1 :: m) P (snd v) p).\n    change (struct_pred (a0 :: a1 :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred (a1 :: m) P' (snd v) p).\n    destruct (ident_eq i (name_member a0)).\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 (name_member 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 [| a0 m]; [inv H0 |].\n  unfold proj_struct, field_type in *.\n  revert a0 H v d H0; induction m as [| a1 m]; intros.\n  + subst P'; simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq _ _); [| congruence].\n    destruct (member_dec a0 a0); [| 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 := a1 :: m).\n    simpl compact_prod in v |- *; simpl Ctypes.field_type in d |- *.\n    subst M.\n    change (struct_pred (a0 :: a1 :: m) P v p)\n      with (P _ (fst v) p * struct_pred (a1 :: m) P (snd v) p).\n    change (struct_pred (a0 :: a1 :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred (a1 :: m) P' (snd v) p).\n    unfold get_member in d|-*; fold (get_member i (a1::m)) in d|-*.\n     destruct (ident_eq i (name_member a0)).\n    - f_equal.\n      * simpl.\n         destruct (member_dec _ _) ; [ | 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.\n        subst i. 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        change (if ident_eq i (name_member a1) then a1 else get_member i m) with (get_member i (a1::m)).\n        destruct (member_dec (get_member i (a1::m)) a0).\n        exfalso. clear - H0 H1 e. subst. apply H1. \n        rewrite name_member_get. auto.\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 (name_member 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 [| a0 m]; [inv H0 |].\n  unfold proj_struct, field_type in *.\n  revert a0 H v v0 H0; induction m as [| a1 m]; intros.\n  + subst P'; simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq _ _); [| congruence].\n    destruct (member_dec a0 a0); [| 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 (a0 :: a1 :: m) v v0)).\n    change (struct_pred (a0 :: a1 :: m) P v' p)\n      with (P _ (fst v') p * struct_pred (a1 :: m) P (snd v') p).\n    change (struct_pred (a0 :: a1 :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred (a1 :: m) P' (snd v) p).\n    subst v'.\n    unfold upd_struct.\n    change (get_member i (a0::a1::m)) with\n       (if ident_eq i (name_member a0) then a0 else get_member i (a1::m))\n       in v0|-*.\n    destruct (ident_eq i _).\n    - subst i.\n      simpl.\n      destruct (member_dec a0 a0); [| congruence].\n      f_equal.\n      * simpl.\n        unfold eq_rect_r; rewrite <- eq_rect_eq.\n        auto.\n      * simpl.\n        unfold eq_rect_r; rewrite <- eq_rect_eq.\n        change (snd (v0, snd v)) with (snd v).\n        change (struct_pred (a1 :: m) P (snd v) p = P' a0 (fst v) p * struct_pred (a1 :: m) P' (snd v) p).\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      simpl. \n      destruct (member_dec _ _).\n      change (get_member i (a1::m) = a0) in e.\n      exfalso; clear - e H0 H1. subst. apply H1. rewrite name_member_get. auto.\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 (name_member 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 [| a0 m]; [auto |].\n  revert a0 v; induction m as [| a1 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 [| a0 m]; [auto |].\n  revert a0 v; induction m as [| a1 m]; intros.\n  + simpl.\n    auto.\n  + change (struct_pred (a0::a1::m) P v p)\n      with (P a0 (fst v) p * struct_pred (a1 :: 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 [| a0 m]; [| revert a0 v; induction m as [| a1 m]; intros].\n  + simpl.\n    rewrite emp_sepcon; auto.\n  + simpl.\n    auto.\n  + change (struct_pred (a0 :: a1 :: m) P v p)\n      with (P a0 (fst v) p * struct_pred (a1 :: m) P (snd v) p).\n    change (struct_pred (a0 :: a1 :: m) Q v p)\n      with (Q a0 (fst v) p * struct_pred (a1 :: m) Q (snd v) p).\n    change (struct_pred (a0 :: a1 :: m) (fun it => P it * Q it) v p)\n      with (P a0 (fst v) p * Q a0 (fst v) p * struct_pred (a1 :: 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 (Hin: in_members i m) d0 d1, members_union_inj v0 (get_member i m) -> members_union_inj v1 (get_member 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 [| a0 m]; [simpl; auto |].\n  revert a0 v0 v1 H H0 H1; induction m as [| a1 m]; intros.\n  + specialize (H1 (name_member a0)).\n    simpl in H1.\n    if_tac in H1; [| congruence].\n   spec H1. left; auto.\n    specialize (H1 v0 v1).\n    spec H1; [if_tac; [auto | congruence] |].\n    spec H1; [if_tac; [auto | congruence] |].\n    destruct (member_dec a0 a0); [| 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    2:{\n      clear - H. unfold members_no_replicate in H. apply compute_list_norepet_e in H. inv H.\n      contradict H2. apply in_map with (f := name_member) in H2. auto.\n    }\n    destruct v0 as [v0 | v0], v1 as [v1 | v1]; try solve [inversion H0].\n    - specialize (H1 (name_member a0)).\n      simpl in H1.\n      if_tac in H1; [| congruence].\n   spec H1. left; auto.\n      specialize (H1 v0 v1).\n      spec H1; [if_tac; [auto | congruence] |].\n      spec H1; [if_tac; [auto | congruence] |].\n      destruct (member_dec a0 a0); [| 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      change (get_member i (a0::a1::m)) with\n           (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n      if_tac in H1. (* i = i0 vs i <> i0 *)\n      * clear - H H2 H4.\n        pose proof compact_sum_inj_in v0 (get_member i (a1 :: m)) member_dec.\n        spec H0; [exact H2 |].\n        subst.\n        apply in_map with (f := name_member) in H0.\n        rewrite name_member_get in H0.\n        tauto.\n      * spec H1.\n         right; auto.\n         specialize (H1 d0 d1).\n         unfold compact_sum_inj, proj_compact_sum, list_rect in H1.\n        destruct (member_dec (get_member i (a1::m)) a0).\n        exfalso. clear - e H4. subst. rewrite name_member_get in H4. congruence.\n        apply (H1 H2 H3).\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 (Hin: in_members i m) d0 d1, members_union_inj v0 (get_member i m) -> members_union_inj v1 (get_member 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; apply derives_refl.\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 (get_member 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 [| a0 m]; [congruence |].\n  clear H0.\n  revert a0 v H H1; induction m as [| a1 m]; intros.\n  + simpl.\n    specialize (H1 (name_member a0)); simpl in H1.\n    destruct (ident_eq (name_member a0) (name_member a0)); [| congruence].\n    apply H1; left; auto.\n  + destruct v; simpl.\n    - specialize (H1 (name_member a0)); simpl in H1.\n      destruct (ident_eq (name_member a0) (name_member a0)); [| congruence].\n      apply H1; left; auto.\n    - pose proof H.\n      rewrite members_no_replicate_ind in H; destruct H.\n      apply (IHm a1); auto.\n      intros.\n      specialize (H1 i).\n     change (get_member i (a0::a1::m)) with (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n      destruct (ident_eq i (name_member a0)).\n      exfalso; clear - H0 H3 e. subst. unfold members_no_replicate in H0. apply compute_list_norepet_e in H0. inv H0.\n      apply H2. apply H3. \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 (get_member 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 [| a0 m]; [inv H0 |].\n  revert a0 v d H H0 H1; induction m as [| a1 m]; intros.\n  + destruct H0; [simpl in H0; subst i | tauto].\n    simpl in *.\n    destruct (ident_eq _ _ ); [| congruence].\n    destruct (member_dec a0 a0); [| 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     change (get_member i (a0::a1::m)) with (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n     simpl proj_union.\n     destruct (ident_eq i (name_member a0)).\n    - subst i.\n      destruct (member_dec a0 a0); [| congruence].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      destruct v; auto.\n      simpl. auto.\n      apply (union_pred_derives_const (a1 :: m)); [auto | congruence |].\n      intros.\n      specialize (H1 i).\n      change (get_member i (a0::a1::m)) with (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n      rewrite if_false in H1. apply H1.\n      right; auto. \n      clear - H4 H2. apply compute_list_norepet_e in H2. inv H2.\n      contradict H1. subst; auto. \n    - change (if ident_eq i (name_member a1) then a1 else get_member i m) with (get_member i (a1::m)) in *.\n       destruct (member_dec _ _).\n       exfalso; clear - n e. subst.\n       rewrite name_member_get in *. congruence.\n       destruct v.\n       unfold union_pred. unfold list_rect.\n       specialize (H1 (name_member a0)). \n        simpl get_member in H1.\n       rewrite if_true in H1 by auto. apply H1. left. auto.\n      apply IHm; auto. destruct H0; auto.  congruence.\n       intros.\n        specialize (H1 i').\n        simpl in H1. rewrite if_false in H1.\n        apply H1. right; auto.\n        clear - H2 H4. intro; subst. apply compute_list_norepet_e in H2. inv H2.\n        apply H1. 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 (get_member i m) m) as [?H | ?H];\n   [ | contradiction H1; apply in_get_member; auto].\n  clear v.\n  destruct m as [| a0 m]; [inv H0 |].\n  revert a0 v0 H H0 H1; induction m as [| a1 m]; intros.\n  + simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq _ _); [| congruence].\n    destruct (member_dec a0 a0); [| 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 _ _); [| congruence].\n      destruct (member_dec a0 a0); [| congruence].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      auto.\n    -\n       change (get_member i (a0::a1::m)) with (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n      destruct (ident_eq _ _).\n      exfalso; clear - e H H0 H1. subst.\n      apply compute_list_norepet_e in H. inv H. apply H4.\n      destruct H0. left; auto. right; auto.\n      unfold union_pred. unfold list_rect.\n      destruct (member_dec _ _).\n      exfalso.\n      clear - H H0 H1 e. forget (a1::m) as m1. subst a0. \n      apply compute_list_norepet_e in H. inv H. rewrite name_member_get in H4. contradiction.\n      apply (IHm a1); auto.\n      apply members_no_replicate_ind in H. tauto.\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 (get_member 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 [| a0 m]; [simpl; auto |].\n  revert a0 v; induction m as [| a1 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 [| a0 m]; [auto |].\n  revert a0 v; induction m as [| a1 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 [| a0 m]; [| revert a0 v; induction m as [| a1 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: member -> 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 (get_member i m) (f (get_member i m))) ->\n  struct_Prop m P (compact_prod_gen f m).\nProof.\n  intros.\n  destruct m as [| a0 m]; [simpl; auto |].\n  revert a0 H H0; induction m as [| a1 m]; intros.\n  + simpl.\n    specialize (H0 (name_member a0)).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + change (struct_Prop (a0 :: a1 :: m) P\n             (compact_prod_gen f (a0 :: a1 :: m)))\n    with (P a0 (f a0) /\\\n            struct_Prop (a1 :: m) P (compact_prod_gen f (a1 :: m))).\n    split.\n    - specialize (H0 (name_member a0)).\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 a1); auto.\n      intros.\n      specialize (H0 i).\n      simpl in H0.\n      destruct (ident_eq i (name_member a0)); [subst; tauto |].\n      apply H0; right; auto.\nQed.\n\nLemma struct_Prop_proj: forall m (F: member -> Type) (P: forall it, F it -> Prop) v i d,\n  in_members i m ->\n  struct_Prop m P v ->\n  P (get_member i m) (proj_struct i m v d).\nProof.\n  intros.\n  destruct m as [| a0 m]; [inversion H |].\n  revert a0 v d H H0; induction m as [| a1 m]; intros.\n  + inversion H; [simpl in H0; subst| tauto].\n    simpl in *.\n    destruct (ident_eq _ _); [| tauto].\n    destruct (member_dec a0 a0); [| tauto].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    auto.\n  + destruct (ident_eq i (name_member a0)).\n    - subst.\n      simpl in *.\n      destruct (ident_eq _ _ ); [| tauto].\n      destruct (member_dec a0 a0); [| tauto].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      exact (proj1 H0).\n    - assert (in_members i (a1 :: m)) by (inversion H; [subst; tauto | auto]).\n      simpl in *.\n      destruct (ident_eq _ _); [tauto |].\n      destruct (member_dec _ _).\n      exfalso; clear - e n.\n      change (if  ident_eq i (name_member a1) then a1 else get_member i m) \n       with (get_member i (a1::m))  in e. subst. rewrite name_member_get in n. contradiction.\n      apply IHm; auto.\n      exact (proj2 H0).\nQed.\n\nLemma union_Prop_compact_sum_gen: forall m (F: member -> 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 (get_member i m) (f (get_member i m))) ->\n  union_Prop m P (compact_sum_gen (fun _ => true) f m).\nProof.\n  intros.\n  destruct m as [| a0 m]; [simpl; auto |].\n  destruct m as [| a1 m].\n  + simpl.\n    specialize (H0 (name_member a0)).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + simpl.\n    specialize (H0 (name_member a0)).\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: member -> Type) (P: forall it, F it -> Prop) v i d,\n  members_union_inj v (get_member i m) ->\n  union_Prop m P v ->\n  P (get_member i m) (proj_union i m v d).\nProof.\n  intros.\n  destruct m as [| a0 m]; [inversion H |].\n  revert a0 v d H H0; induction m as [| a1 m]; intros.\n  + simpl in H. simpl proj_union.\n    unfold eq_rect_r.\n     if_tac in H; [| tauto].\n    change (if ident_eq i (name_member a0) then a0 else Member_plain i Tvoid) with\n              (get_member i (a0::nil)) in *.\n    simpl in H0.\n    destruct a0; simpl in *.\n   if_tac.  rewrite <- eq_rect_eq; auto.\n   unfold eq_rect. destruct H1. simpl. auto.\n   if_tac.  rewrite <- eq_rect_eq; auto.\n   unfold eq_rect. destruct H1. simpl. auto.\n  + \n    unfold proj_union. \n    change (get_member i (a0::a1::m)) with (if ident_eq i (name_member a0) then a0 else get_member i (a1::m)) in *.\n    if_tac. \n    - subst.\n     simpl. \n      simpl in H.\n      destruct (member_dec a0 a0); [| tauto].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      destruct v; [| inversion H].\n      auto.\n    - assert (members_union_inj v (get_member i (a1 :: m))) \n       by (simpl in H; destruct (ident_eq i (name_member a0)); [tauto | auto]).\n      set (j := get_member i (a1::m)) in *.\n      simpl in H|-*.\n      destruct (member_dec _ _).\n      subst a0.\n      exfalso; clear - j H1. subst j. rewrite name_member_get in H1. contradiction.\n      destruct v; [ tauto | ]. \n      apply IHm; auto.\nQed.\n\nLemma array_pred_local_facts: forall {A}{d: Inhabitant A} lo hi P (v: list A) p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred 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 lia.\n    assert (hi - Z.succ lo >= 0).\n    {\n      destruct (zlt (hi - Z.succ lo) 0); auto.\n      assert (Z.succ (hi - Z.succ lo) <= 0) by lia.\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 lia]; inv H1.\n    }\n    rewrite Z2Nat.inj_succ in H1 |- * by lia.\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))) p)\n    with (rangespec (Z.succ lo) (length v)\n            (fun i : Z => P i (Znth (i - Z.succ lo) v)) p).\n    2:{\n      apply rangespec_ext; intros.\n      change v with (skipn 1 (a :: v)) at 1.\n      rewrite <- Znth_succ by lia.\n      auto.\n    }\n    rewrite H3.\n    eapply derives_trans; [apply sepcon_derives; [apply H | apply IHv; auto] |].\n    - lia.\n    - intros; apply H; lia.\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 (get_member 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 [| a0 m]; [simpl; apply prop_right; auto |].\n  revert a0 v H H0; induction m as [| a1 m]; intros.\n  + simpl.\n    specialize (H0 (name_member a0)).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + change (struct_Prop (a0 :: a1 :: m) R v)\n      with (R a0 (fst v) /\\ struct_Prop (a1 :: m) R (snd v)).\n    change (struct_pred (a0 :: a1 :: m) P v p)\n      with (P a0 (fst v) p * struct_pred (a1 :: m) P (snd v) p).\n    rewrite members_no_replicate_ind in H.\n\n    pose proof H0 (name_member a0).\n    simpl in H1.\n    if_tac in H1; [| congruence].\n    specialize (H1 (fst v)).\n    spec H1; [left; auto |].\n\n    specialize (IHm a1 (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 (name_member a0)); [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 (get_member 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 [| a0 m]; [simpl; apply prop_right; auto |].\n  revert a0 v H H0; induction m as [| a1 m]; intros.\n  + simpl.\n    specialize (H0 (name_member a0)).\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 (name_member a0).\n      simpl in H1.\n      if_tac in H1; [| congruence].\n      specialize (H1 a).\n      apply H1; left; auto.\n    - specialize (IHm a1 c).\n      spec IHm; [tauto |].\n      apply IHm.\n      intros.\n      specialize (H0 i).\n      simpl in H0.\n      destruct (ident_eq i (name_member a0)); [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: Inhabitant A} sh t lo hi (v: list A) b ofs,\n  0 <= ofs + sizeof t * lo /\\ ofs + sizeof t * hi < Ptrofs.modulus ->\n  0 <= lo <= hi ->\n  Zlength v = hi - lo ->\n  array_pred lo hi\n    (fun i _ p => memory_block sh (sizeof t) (offset_val (sizeof t * i) p)) v\n    (Vptr b (Ptrofs.repr ofs)) =\n   memory_block sh (sizeof t * (hi - lo)) (Vptr b (Ptrofs.repr (ofs + sizeof t * lo))).\nProof.\n  intros.\n  unfold array_pred.\n  rewrite prop_true_andp by auto; clear H1.\n  f_equal.\n  remember (Z.to_nat (hi - lo)) as n eqn:HH.\n  revert lo HH H H0 v; induction n; intros.\n  + simpl.\n    pose proof arith_aux00 _ _ (proj2 H0) HH.\n    rewrite H1, Z.mul_0_r, memory_block_zero_Vptr.\n    reflexivity.\n  + simpl.\n    pose proof arith_aux01 _ _ _ HH.\n    solve_mod_modulus.\n    pose_size_mult cs t (0 :: hi - Z.succ lo :: hi - lo :: nil).\n    rewrite IHn; [| apply arith_aux02; auto | lia | lia | exact v].\n    replace (ofs + sizeof  t * Z.succ lo) with (ofs + sizeof t * lo + sizeof t) by lia.\n    rewrite <- memory_block_split by (auto; lia).\n    f_equal.\n    lia.\nQed.\n\nLemma mapsto_zeros_zero_Vptr\n     : forall (sh : share) (b : block) (z : ptrofs),\n       mapsto_zeros 0 sh (Vptr b z) = emp.\nProof.\nintros.\nunfold mapsto_zeros. simpl.\nrewrite prop_true_andp. reflexivity.\nrep_lia.\nQed.\n\nLemma mapsto_zeros_split\n     : forall (sh : share) (b : block) (ofs n m : Z),\n       0 <= n ->\n       0 <= m ->\n       n + m <= n + m + ofs < Ptrofs.modulus ->\n       mapsto_zeros (n + m) sh (Vptr b (Ptrofs.repr ofs)) =\n       mapsto_zeros n sh (Vptr b (Ptrofs.repr ofs)) *\n       mapsto_zeros m sh (Vptr b (Ptrofs.repr (ofs + n))).\nProof.\nintros.\nunfold mapsto_zeros.\nrewrite !Ptrofs.unsigned_repr by rep_lia.\nrewrite !prop_true_andp by rep_lia.\nrewrite !mapsto_memory_block.address_mapsto_zeros_eq.\nrewrite !Z2Nat.id by lia.\napply mapsto_memory_block.address_mapsto_zeros'_split; lia.\nQed.\n\nLemma mapsto_zeros_array_pred: forall  {A}{d: Inhabitant A} sh t lo hi (v: list A) b ofs,\n  0 <= ofs + sizeof t * lo /\\ ofs + sizeof t * hi < Ptrofs.modulus ->\n  0 <= lo <= hi ->\n  Zlength v = hi - lo ->\n   mapsto_zeros (sizeof t * (hi - lo)) sh (Vptr b (Ptrofs.repr (ofs + sizeof t * lo))) |--\n  array_pred lo hi\n    (fun i _ p => mapsto_zeros (sizeof t) sh (offset_val (sizeof t * i) p)) v\n    (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros.\n  unfold array_pred.\nOpaque mapsto_zeros.\n  rewrite prop_true_andp by auto; clear H1.\n  f_equal.\n  remember (Z.to_nat (hi - lo)) as n eqn:HH.\n  revert lo HH H H0 v; induction n; intros.\n  +  simpl. \n    pose proof arith_aux00 _ _ (proj2 H0) HH.\n    rewrite H1, Z.mul_0_r, mapsto_zeros_zero_Vptr.\n    auto.\n  + simpl.\n    pose proof arith_aux01 _ _ _ HH.\n    solve_mod_modulus.\n    pose_size_mult cs t (0 :: hi - Z.succ lo :: hi - lo :: nil).\n    eapply derives_trans; [ | apply sepcon_derives; [apply derives_refl | apply IHn; try lia; try exact v]].\n    replace (ofs + sizeof  t * Z.succ lo) with (ofs + sizeof t * lo + sizeof t) by lia.\n    rewrite <- mapsto_zeros_split by (auto; lia).\n    apply derives_refl'.\n    f_equal.\n    lia.\nTransparent mapsto_zeros.\nQed.\n\nLemma memory_block_array_pred': forall {A}{d: Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred 0 z\n     (fun i _ p =>\n      memory_block sh (sizeof t) (offset_val (sizeof t * i) p))\n             (Zrepeat a z)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros.\n  rewrite memory_block_array_pred.\n  f_equal. f_equal. lia. f_equal. f_equal. rewrite Z.mul_0_r. lia.\n  rewrite Z.mul_0_r. split; lia. lia.\n  rewrite Z.sub_0_r. auto. rewrite Zlength_Zrepeat by lia.\n  lia.\nQed.\n\nLemma mapsto_zeros_array_pred': forall {A}{d: Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  mapsto_zeros (sizeof t * z) sh (Vptr b (Ptrofs.repr ofs)) |--\n  array_pred 0 z\n     (fun i _ p =>\n      mapsto_zeros (sizeof t) sh(offset_val (sizeof t * i) p))\n             (Zrepeat a z)\n     (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros.\n  eapply derives_trans; [ | apply mapsto_zeros_array_pred; try lia].\n  apply derives_refl'.\n  f_equal. lia. f_equal. f_equal. lia.\n  rewrite Zlength_Zrepeat by lia.\n  lia.\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  plain_members m = true ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (name_member it) m sz - field_offset cenv_cs (name_member it) m))\n     (offset_val (field_offset cenv_cs (name_member it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  unfold field_offset, Ctypes.field_offset, field_offset_next.\n  intros sh m sz A v b ofs NIL_CASE PLAIN NO_REPLI; intros.\n  destruct m as [| a0 m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  pose (t0 := type_member a0).\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 lia; intros.\n  revert H; pattern sz at 2 4; replace sz with (sz - align 0 (alignof t0)) by lia; intros.\n  pattern 0 at 1; rewrite <- H1.\n  clear NIL_CASE H1.\n  destruct a0; try discriminate. simpl in t0. subst t0. simpl in PLAIN.\n  rename id into i0. rename t into t0. \n  revert H H0. generalize 0 at 1 2 4 5 6 7 8 9; revert i0 t0 v PLAIN NO_REPLI;\n  induction m as [| a1 m]; intros.\n  + simpl.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    reflexivity.\n  + match goal with\n    | |- struct_pred (Member_plain i0 t0 :: a1 :: m) ?P v ?p = _ =>\n           change (struct_pred (Member_plain i0 t0 :: a1 :: m) P v p) with\n             (P (Member_plain i0 t0) (fst v) p * struct_pred (a1 :: m) P (snd v) p);\n           simpl (P (Member_plain i0 t0) (fst v) p)\n    end.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    destruct a1 as [i1 t1|]; try discriminate.\n   destruct v as [v0 v1].\n   rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n    specialize (IHm i1 t1 v1 PLAIN NO_REPLI (align z (alignof t0) + sizeof t0)).\n    simpl snd.\n    fold (sizeof t0) in *. fold (alignof t0) in *.\n    erewrite struct_pred_ext.\n    -\n     rewrite IHm;\n        [| simpl in H |- *; \n          fold (sizeof t0) in *; fold (alignof t0) in *;\n          fold (sizeof t1) in *; fold (alignof t1) in *;\n          pose_align_le; pose_sizeof_pos; lia\n         | pose_align_le; pose_sizeof_pos; lia].\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 lia.\n      rewrite <- memory_block_split by\n        (simpl in H; \n          fold (sizeof t0) in *; fold (alignof t0) in *;\n          fold (sizeof t1) in *; fold (alignof t1) in *;revert H; pose_align_le; pose_sizeof_pos; intros; lia).\n      f_equal; lia.\n    - \n      auto.\n    - intros.\n      solve_mod_modulus.\n      unfold fst.\n      rewrite !name_member_get.\n      assert (i <> name_member (Member_plain i0 t0)).\n      simpl. clear - H2 NOT_IN.  contradict NOT_IN. subst i0. simpl. auto.\n      rewrite (neq_field_offset_rec_cons cenv_cs i (Member_plain i0 t0)) by auto.\n      rewrite (neq_field_offset_next_rec_cons cenv_cs i (Member_plain i0 t0)) by  auto.\n      reflexivity.\nQed.\n\nLemma mapsto_zeros_zero: forall (sh : share) (p : val), \n   mapsto_zeros 0 sh p = !! isptr p && emp.\nProof.\nintros.\nunfold mapsto_zeros; simpl. destruct p; simpl; normalize.\nrewrite prop_true_andp by rep_lia.\nreflexivity.\nQed.\n\nLemma mapsto_zeros_struct_pred: forall sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  plain_members m = true ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  mapsto_zeros sz sh (Vptr b (Ptrofs.repr ofs)) |--\n  struct_pred m\n   (fun it _ p =>\n     (mapsto_zeros (field_offset_next cenv_cs (name_member it) m sz - field_offset cenv_cs (name_member it) m)) sh\n     (offset_val (field_offset cenv_cs (name_member it) m) p)) v (Vptr b (Ptrofs.repr ofs)).\nProof.\n  Opaque mapsto_zeros.\n  unfold field_offset, Ctypes.field_offset, field_offset_next.\n  intros sh m sz A v b ofs NIL_CASE PLAIN NO_REPLI; intros.\n  destruct m as [| a0 m].\n  1: rewrite (NIL_CASE eq_refl), mapsto_zeros_zero; simpl; normalize.\n  pose (t0 := type_member a0).\n  assert (align 0 (alignof t0) = 0) by apply align_0, alignof_pos.\n  revert H0; pattern ofs at 1 3; replace ofs with (ofs + align 0 (alignof t0)) by lia; intros.\n  revert H; pattern sz at 2 3; replace sz with (sz - align 0 (alignof t0)) by lia; intros.\n  pattern 0 at 3; rewrite <- H1.\n  clear NIL_CASE H1.\n  destruct a0; try discriminate. simpl in t0. subst t0. simpl in PLAIN.\n  rename id into i0. rename t into t0. \n  revert H H0. generalize 0 at 1 2 4 5 6 7 8 9. revert i0 t0 v PLAIN NO_REPLI;\n  induction m as [| a1 m]; intros.\n  + simpl.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    unfold alignof.\n   apply derives_refl. \n  +\n    destruct a1 as [i1 t1|]; try discriminate.\n   simpl in PLAIN.\n match goal with\n    | |- _ |-- struct_pred (Member_plain i0 t0 :: Member_plain i1 t1 :: m) ?P v ?p =>\n           change (struct_pred (Member_plain i0 t0 :: Member_plain i1 t1 :: m) P v p) with\n             (P (Member_plain i0 t0) (fst v) p * struct_pred (Member_plain i1 t1 :: m) P (snd v) p);\n           simpl (P (Member_plain i0 t0) (fst v) p)\n    end.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n   destruct v as [v0 v1].\n   rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n    specialize (IHm i1 t1 v1 PLAIN NO_REPLI (align z (alignof t0) + sizeof t0)).\n    simpl snd.\n    fold (sizeof t0) in *. fold (alignof t0) in *.\n    erewrite struct_pred_ext.\n    fold (sizeof t0) in *. fold (alignof t0) in *.\n    fold (sizeof t1) in *. fold (alignof t1) in *.\n     eapply derives_trans; [ | apply sepcon_derives; [apply derives_refl | \n                       apply IHm]]; clear IHm;\n        [ |  simpl in H |- *; \n          fold (sizeof t0) in *; fold (alignof t0) in *;\n          fold (sizeof t1) in *; fold (alignof t1) in *;\n          pose_align_le; pose_sizeof_pos; lia\n         | pose_align_le; pose_sizeof_pos; lia].\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 lia.\n      rewrite <- mapsto_zeros_split by\n        (simpl in H; \n          fold (sizeof t0) in *; fold (alignof t0) in *;\n          fold (sizeof t1) in *; fold (alignof t1) in *;revert H; pose_align_le; pose_sizeof_pos; intros; lia).\n     apply derives_refl';  f_equal; lia.\n     auto.\n     intros.\n      solve_mod_modulus.\n      rewrite !name_member_get.\n      assert (i <> name_member (Member_plain i0 t0)).\n      simpl. clear - H2 NOT_IN.  contradict NOT_IN. subst i0. simpl. auto.\n      rewrite (neq_field_offset_rec_cons cenv_cs i (Member_plain i0 t0)) by auto.\n      rewrite (neq_field_offset_next_rec_cons cenv_cs i (Member_plain i0 t0)) by  auto.\n      reflexivity.\nTransparent mapsto_zeros.\nQed.\nLemma memory_block_union_pred: forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros sh m sz A v b ofs NIL_CASE; intros.\n  destruct m as [| a0 m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  clear NIL_CASE.\n  revert a0 v; induction m as [| a1 m]; intros.\n  + simpl; auto.\n  + destruct v.\n    - simpl; auto.\n    - apply IHm.\nQed.\n\nLemma mapsto_zeros_union_pred: forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  mapsto_zeros sz sh (Vptr b (Ptrofs.repr ofs)) |--\n  union_pred m (fun it _ => mapsto_zeros sz sh) v (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros sh m sz A v b ofs NIL_CASE; intros.\n  destruct m as [| a0 m].\n  1: rewrite (NIL_CASE eq_refl), mapsto_zeros_zero; simpl; normalize.\n  clear NIL_CASE.\n  revert a0 v; induction m as [| a1 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: Inhabitant 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: member -> 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: member -> 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: member -> Type} (P: forall it, A it -> Prop) (v: compact_prod (map A m)), Prop := @struct_Prop.\n\nDefinition union_Prop: forall (m: members) {A: member -> 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: Inhabitant A} lo hi P p,\n  hi = lo ->\n  array_pred lo hi P nil p = emp\n:= @array_pred_len_0.\n\nDefinition array_pred_len_1: forall {A}{d: Inhabitant A} i P v p,\n  array_pred i (i + 1) P (v :: nil) p =  P i v p\n:= @array_pred_len_1.\n\nDefinition split_array_pred: forall  {A}{d: Inhabitant A} lo mid hi P v p,\n  lo <= mid <= hi ->\n  Zlength v = (hi-lo) ->\n  array_pred lo hi P v p =\n  array_pred lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred mid hi P (sublist (mid-lo) (hi-lo) v) p\n:= @split_array_pred.\n\nDefinition array_pred_shift: forall {A} {d: Inhabitant A} lo hi lo' hi' mv \n              P' P v p,\n  lo - lo' = mv ->\n  hi - hi' = mv ->\n  (forall i i', lo <= i < hi -> i - i' = mv ->\n           P' i' (Znth (i - lo) v) p = P i (Znth (i - lo) v) p) ->\n  array_pred lo' hi' P' v p = array_pred lo hi P v p\n:= @array_pred_shift.\n\nDefinition array_pred_ext_derives:\n  forall {A B} {dA: Inhabitant A} {dB: Inhabitant B} lo hi P0 P1 \n            (v0: list A) (v1: list B) p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n      P0 i (Znth (i-lo) v0) p |-- P1 i (Znth (i-lo) v1) p) ->\n  array_pred lo hi P0 v0 p |-- array_pred lo hi P1 v1 p\n:= @array_pred_ext_derives.\n\nDefinition array_pred_ext:\n  forall {A B} {dA: Inhabitant A} {dB: Inhabitant B} lo hi P0 P1 (v0: list A) (v1: list B)  p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n     P0 i (Znth (i - lo) v0) p = P1 i (Znth (i - lo) v1) p) ->\n  array_pred lo hi P0 v0 p = array_pred lo hi P1 v1 p\n:= @array_pred_ext.\n\nDefinition at_offset_array_pred: forall {A} {d: Inhabitant A} lo hi P v ofs p,\n  at_offset (array_pred lo hi P v) ofs p = array_pred 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: Inhabitant A} lo hi P Q (v: list A) p,\n  array_pred lo hi P v p * array_pred lo hi Q v p = array_pred 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 (get_member 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 (Hin: in_members i m) d0 d1, members_union_inj v0 (get_member i m) -> members_union_inj v1 (get_member 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 (Hin: in_members i m) d0 d1, members_union_inj v0 (get_member i m) -> members_union_inj v1 (get_member 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: member -> 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 (get_member i m) (f (get_member 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: member -> Type) (P: forall it, F it -> Prop) v i d,\n  in_members i m ->\n  struct_Prop m P v ->\n  P (get_member i m) (proj_struct i m v d)\n:= @struct_Prop_proj.\n\nDefinition union_Prop_compact_sum_gen: forall m (F: member -> 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 (get_member i m) (f (get_member 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: member -> Type) (P: forall it, F it -> Prop) v i d,\n  members_union_inj v (get_member i m) ->\n  union_Prop m P v ->\n  P (get_member i m) (proj_union i m v d)\n:= @union_Prop_proj.\n\nDefinition array_pred_local_facts: forall {A} {d: Inhabitant A} lo hi P v p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred 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 (get_member 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 (get_member i m) v0 p |-- !! R _ v0) ->\n  union_pred m P v p |-- !! union_Prop m R v\n:= @union_pred_local_facts.\n\nEnd aggregate_pred.\n\nRequire Import VST.floyd.reptype_lemmas.\n\n(******************************************\n\nAuxiliary predicates\n\n******************************************)\n\nSection AUXILIARY_PRED.\n\nContext {cs: compspecs}.\n\nVariable sh: share.\n\nDefinition struct_data_at_rec_aux (m m0: members) (sz: Z) \n       (P: ListType (map (fun it => reptype (field_type (name_member it) m0) -> (val -> mpred)) m))\n       (v: compact_prod (map (fun it => reptype (field_type (name_member it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| a0 m]; [exact (fun _ => emp) |].\n  revert a0 v P; induction m as [| a0 m]; intros ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs (name_member a0) m0 + sizeof (field_type (name_member a0) m0))\n            (field_offset_next cenv_cs (name_member a0) m0 sz)\n            (at_offset (a v) (field_offset cenv_cs (name_member a0) m0))).\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs (name_member a1) m0 + sizeof (field_type (name_member a1) m0))\n            (field_offset_next cenv_cs (name_member a1) m0 sz)\n            (at_offset (a (fst v)) (field_offset cenv_cs (name_member a1) m0)) * IHm a0 (snd v) b)%logic.\nDefined.\n\nDefinition union_data_at_rec_aux (m m0: members) (sz: Z)\n      (P: ListType (map (fun it => reptype (field_type (name_member it) m0) -> (val -> mpred)) m))\n      (v: compact_sum (map (fun it => reptype (field_type (name_member it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| a0 m]; [exact (fun _ => emp) |].\n  revert a0 v P; induction m as [| a0 m]; intros ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh (sizeof (field_type (name_member a0) 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 (name_member a1) m0)) sz (a v)).\n    - exact (IHm a0 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 (name_member it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (name_member it) m0 + sizeof (field_type (name_member it) m0))\n       (field_offset_next cenv_cs (name_member it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (name_member it) m0))) v.\nProof.\n  intros.\n  destruct m as [| a0 m]; [reflexivity |].\n  revert a0 v; induction m as [| a0 m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_data_at_rec_aux (a1 :: a0 :: m) m0 sz\n     (ListTypeGen (fun it : member => reptype (field_type (name_member it) m0) -> val -> mpred)\n        P (a1 :: a0 :: m)) v) with\n     (withspacer sh\n       (field_offset cenv_cs (name_member a1) m0 + sizeof (field_type (name_member a1) m0))\n         (field_offset_next cenv_cs (name_member a1) m0 sz)\n           (at_offset (P a1 (fst v)) (field_offset cenv_cs (name_member a1) m0)) *\n      struct_data_at_rec_aux (a0 :: m) m0 sz\n     (ListTypeGen (fun it : member => reptype (field_type (name_member it) m0) -> val -> mpred)\n        P (a0 :: m)) (snd v))%logic.\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\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 (name_member it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (name_member it) m0))\n       sz\n       (P it v)) v.\nProof.\n  intros.\n  destruct m as [| a0 m]; [reflexivity |].\n  revert a0 v; induction m as [| a0 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 (name_member it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (name_member it) m0)) m)) : Prop.\nProof.\n  destruct m as [| a0 m]; [exact True |].\n  revert a0 v P; induction m as [| a0 m]; intros ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    apply (a v).\n  + simpl in v, P.\n    inversion P; subst.\n    apply (a (fst v) /\\ IHm a0 (snd v) b).\nDefined.\n\nDefinition union_value_fits_aux (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (name_member it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (name_member it) m0)) m)) : Prop.\nProof.\n  destruct m as [| a0 m]; [exact True |].\n  revert a0 v P; induction m as [| a0 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 a0 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 (name_member it) m0) -> Prop)\n     P m) v =\n  struct_Prop m P v.\nProof.\n  intros.\n  destruct m as [| a0 m]; [reflexivity |].\n  revert a0 v; induction m as [| a0 m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_value_fits_aux (a1 :: a0 :: m) m0\n     (ListTypeGen (fun it : member => reptype (field_type (name_member it) m0) -> Prop)\n        P (a1 :: a0 :: m)) v) with\n     (P a1 (fst v) /\\  struct_value_fits_aux (a0 :: m) m0\n     (ListTypeGen (fun it : member => reptype (field_type (name_member it) m0) -> Prop)\n        P (a0 :: m)) (snd v)).\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\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 (name_member it) m0) -> Prop)\n     P m) v =\n  union_Prop m P v.\nProof.\n  intros.\n  destruct m as [| a0 m]; [reflexivity |].\n  revert a0 v; induction m as [| a0 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) \n     (P: ListType (map (fun it => reptype (field_type (name_member it) m0) -> (val -> mpred)) m)) \n     (v: compact_prod (map (fun it => reptype (field_type (name_member 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) \n    (P: ListType (map (fun it => reptype (field_type (name_member it) m0) -> (val -> mpred)) m)) \n    (v: compact_sum (map (fun it => reptype (field_type (name_member 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 (name_member it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (name_member it) m0 + sizeof (field_type (name_member it) m0))\n       (field_offset_next cenv_cs (name_member it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (name_member 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 (name_member it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (name_member 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 (name_member it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (name_member 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 (name_member it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (name_member 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 (name_member 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 (name_member 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 : Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred 0 z\n     (fun i _ p =>\n      memory_block sh (sizeof t)\n        (offset_val (sizeof t * i) p)) (Zrepeat a z)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_array_pred'.\n\nDefinition mapsto_zeros_array_pred:\n  forall {cs: compspecs} {A : Type} {d : Inhabitant A} (a: A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  mapsto_zeros (sizeof t * z) sh (Vptr b (Ptrofs.repr ofs)) |--\n  array_pred 0 z\n     (fun i _ p =>\n      mapsto_zeros (sizeof t) sh\n        (offset_val (sizeof t * i) p)) (Zrepeat a z)\n     (Vptr b (Ptrofs.repr ofs))\n:= @mapsto_zeros_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  plain_members m = true ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (name_member it) m sz - field_offset cenv_cs (name_member it) m))\n     (offset_val (field_offset cenv_cs (name_member it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_struct_pred.\n\nDefinition mapsto_zeros_struct_pred:\n  forall {cs: compspecs} sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  plain_members m = true ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  mapsto_zeros sz sh (Vptr b (Ptrofs.repr ofs)) |--\n  struct_pred m\n   (fun it _ p =>\n     (mapsto_zeros (field_offset_next cenv_cs (name_member it) m sz - field_offset cenv_cs (name_member it) m)) sh\n     (offset_val (field_offset cenv_cs (name_member it) m) p)) v (Vptr b (Ptrofs.repr ofs))\n:= @mapsto_zeros_struct_pred.\n\nDefinition memory_block_union_pred:\n  forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_union_pred.\n\nDefinition mapsto_zeros_union_pred:\n  forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  mapsto_zeros sz sh (Vptr b (Ptrofs.repr ofs)) |--\n  union_pred m (fun it _ => mapsto_zeros sz sh) v (Vptr b (Ptrofs.repr ofs))\n:= @mapsto_zeros_union_pred.\n\nEnd auxiliary_pred.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/aggregate_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.17927716416084485}}
{"text": "Require Import CertiGraph.dispose.env_dispose_bi.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.spanning_tree.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.GraphBi.\nRequire Import CertiGraph.msl_application.GraphBi_Mark.\nRequire Import CertiGraph.data_structure.spatial_graph_dispose_bi.\nRequire Import CertiGraph.data_structure.spatial_graph_unaligned_bi_VST.\nRequire Import CertiGraph.floyd_ext.share.\nRequire CertiGraph.graph.weak_mark_lemmas.\nImport CertiGraph.graph.weak_mark_lemmas.WeakMarkGraph.\n\nRequire Import VST.msl.wand_frame.\nRequire Import VST.floyd.reassoc_seq.\nRequire Import VST.floyd.field_at_wand.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\nLocal Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nDefinition vertices_at sh g P := (@vertices_at _ _ _ _ _ _ (@SGP pSGG_VST bool unit (sSGG_VST sh)) _ g P).\nDefinition graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ unit unit _ mpred (@SGP pSGG_VST bool unit (sSGG_VST sh)) _ x g).\nNotation Graph := (@Graph pSGG_VST bool unit unit).\nExisting Instances MGS biGraph maGraph finGraph RGF.\n\nDefinition mark_spec :=\n DECLARE _mark\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (weak_valid g x)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (graph sh x g)\n  POST [ Tvoid ]\n        EX g': Graph,\n        PROP (mark x g g')\n        LOCAL()\n        SEP (graph sh x g').\n\nDefinition spanning_spec :=\n  DECLARE _spanning\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (vvalid g x; fst (fst (vgamma g x)) = false)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (graph sh x g)\n  POST [ Tvoid ]\n        EX g': Graph,\n        PROP (spanning_tree g x g')\n        LOCAL()\n        SEP (vertices_at sh (reachable g x) g').\n\nDefinition dispose_spec :=\n  DECLARE _dispose\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (weak_valid g x; is_tree g x)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (graph sh x g)\n  POST [ Tvoid ]\n        PROP ()\n        LOCAL()\n        SEP (emp).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mark_spec ; spanning_spec ; dispose_spec ; main_spec]).\n\nLemma graph_local_facts: forall sh x (g: Graph), vvalid g x -> @derives mpred Nveric (graph sh x g) (valid_pointer (pointer_val_val x)).\nProof.\n  intros.\n  eapply derives_trans; [apply (@va_reachable_root_stable_ramify pSGG_VST _ _ _ (sSGG_VST sh) g x (vgamma g x)); auto |].\n  simpl vertex_at. unfold trinode. simpl. entailer!.\nQed.\n\nLemma graph_left_local_facts: forall sh x (g: Graph) d l r, vvalid g x -> vgamma g x = (d, l, r) -> graph sh x g |-- valid_pointer (pointer_val_val l).\nProof.\n  intros.\n  eapply derives_trans; [apply (@graph_ramify_aux1_left pSGG_VST (sSGG_VST sh) g x d l r); auto | ].\n  assert (weak_valid g l) by (apply (gamma_left_weak_valid g x d l r); auto). destruct H1.\n  - simpl in H1. subst l. simpl pointer_val_val.\n    apply sepcon_valid_pointer1.\n    unfold pred. simpl reachable_vertices_at. entailer!.\n  - apply sepcon_valid_pointer1. apply graph_local_facts; auto.\nQed.\n\nLemma graph_right_local_facts: forall sh x (g1 g2: Graph) l l' r,\n    vvalid g1 x -> vgamma g1 x = (true, l, r) -> vvalid g2 x -> vgamma g2 x = (true, l', r) -> edge_spanning_tree g1 (x, L) g2 ->\n    vertices_at sh (reachable g1 x) g2 |-- valid_pointer (pointer_val_val r).\nProof.\n  intros.\n  eapply derives_trans; [apply (@graph_ramify_aux1_right pSGG_VST (sSGG_VST sh) g1 g2 x l r); auto | ].\n  assert (weak_valid g2 r) by (apply (gamma_right_weak_valid g2 x true l' r); auto). destruct H4.\n  - simpl in H4. subst r. simpl pointer_val_val. apply sepcon_valid_pointer1.\n    unfold pred. simpl reachable_vertices_at. entailer!.\n  - apply sepcon_valid_pointer1. apply graph_local_facts; auto.\nQed.\n\nLemma body_spanning: semax_body Vprog Gprog f_spanning spanning_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as dlr eqn:?H.\n  destruct dlr as [[d l] r].\n  assert (d = false) by (simpl in H1; auto).\n  subst.\n  assert (Hisptr: isptr (pointer_val_val x)). {\n    destruct x. simpl. auto.\n    apply (valid_not_null g) in H. exfalso; auto.\n    reflexivity.\n  }\n  localize [data_at sh node_type (Vint (Int.repr 0), (pointer_val_val l, pointer_val_val r))\n                    (pointer_val_val x)].\n  forward. 1: entailer!; destruct l; simpl; auto.\n  forward. 1: entailer!; destruct r; simpl; auto.\n  forward.\n  unlocalize [graph sh x (Graph_vgen g x true)].\n  1: {\n    apply (@root_update_ramify _ (sSGG_VST sh) g x _ (false, l, r) (true, l, r)); auto.\n    eapply Graph_vgen_vgamma; eauto.\n  }\n  (* if (l) { *)\n  symmetry in H1.\n  pose proof Graph_vgen_true_mark1 g x _ _ H1 H.\n  assert (H_GAMMA_g1: vgamma (Graph_vgen g x true) x = (true, l, r)) by\n   (eapply Graph_vgen_vgamma; eauto).\n  assert (vvalid (Graph_vgen g x true) x) by\n      (destruct H2 as [[? _] _]; apply H2; auto).\n  forget (Graph_vgen g x true) as g1.\n  forward_if\n    (EX g2: Graph,\n     PROP  (edge_spanning_tree g1 (x, L) g2)\n     LOCAL (temp _r (pointer_val_val r);\n            temp _l (pointer_val_val l);\n            temp _x (pointer_val_val x))\n     SEP (vertices_at sh (reachable g1 x) g2)).\n  - apply denote_tc_test_eq_split. 2: entailer!. apply (graph_left_local_facts _ _ _ true l r); auto.\n  - (* root_mark = l -> m; *)\n    localize [data_at sh node_type (vgamma2cdata (vgamma g1 l)) (pointer_val_val l)].\n    remember (vgamma g1 l) as dlr in |-*.\n    destruct dlr as [[dd ll] rr].\n    forward. simpl vgamma2cdata at 1.\n    replace (if dd then 1 else 0) with (if node_pred_dec (marked g1) l then 1 else 0).\n    2: {\n      destruct (node_pred_dec (marked g1)); destruct dd; auto; symmetry in Heqdlr.\n      apply vgamma_is_false in Heqdlr. simpl in a. unfold unmarked in Heqdlr. hnf in Heqdlr.\n      unfold Ensembles.In in Heqdlr. simpl in Heqdlr. apply Heqdlr in a. exfalso; auto.\n      apply vgamma_is_true in Heqdlr. exfalso; auto.\n    }\n    rewrite Heqdlr. clear dd ll rr Heqdlr.\n    unlocalize [graph sh x g1].\n    + destruct (vgamma g1 l) as [[dd ll] rr] eqn:? .\n      assert (vvalid g1 l). {\n        assert (weak_valid g1 l) by (eapply gamma_left_weak_valid; eauto).\n        destruct H5; auto. hnf in H5. subst. exfalso; intuition.\n      } unfold vgamma2cdata.\n      apply (@va_reachable_internal_stable_ramify pSGG_VST _ _ _ (sSGG_VST sh) g1 x l (dd, ll, rr)); auto.\n      apply (gamma_left_reachable_included g1 _ _ _ _ H3 H_GAMMA_g1 l).\n      apply reachable_by_refl; auto.\n    + (* if (root_mark == 0) { *)\n      Opaque node_pred_dec.\n      Opaque pSGG_VST.\n      (* remember (if node_pred_dec (marked g1) l then 1 else 0). *)\n      forward_if\n        (EX g2: Graph,\n         PROP  (edge_spanning_tree g1 (x, L) g2)\n         LOCAL (temp _r (pointer_val_val r);\n                temp _l (pointer_val_val l);\n                temp _x (pointer_val_val x))\n         SEP (vertices_at sh (reachable g1 x) g2)).\n      * (* spanning(l); *)\n        Transparent node_pred_dec.\n        Transparent pSGG_VST.\n        destruct (node_pred_dec (marked g1) l). 1: inversion H5.\n        localize [graph sh l g1].\n        assert (vvalid g1 l). {\n          apply gamma_left_weak_valid in H1. 2: auto.\n          destruct H2.\n          rewrite (weak_valid_si _ _ _ H2) in H1.\n          destruct H1. 2: auto.\n          hnf in H1. subst l.\n          simpl in H4. exfalso; auto.\n        } assert (fst (fst (vgamma g1 l)) = false). {\n          simpl in n.\n          simpl. destruct (vlabel g1 l) eqn:? ; auto.\n          symmetry in Heqb. apply n in Heqb. inversion Heqb.\n        } forward_call (sh, g1, l).\n        Intros g'.\n        unlocalize [vertices_at sh (reachable g1 x) g'] using g' assuming H8.\n        1: apply (@graph_ramify_aux1_left _ (sSGG_VST sh) g1 x true l r); auto.\n        Exists g'.\n        unfold vertices_at; simpl Graph.vertices_at.\n        entailer!.\n        assert (l = dst g1 (x, L)) by (simpl in H_GAMMA_g1; inversion H_GAMMA_g1; auto).\n        unfold edge_spanning_tree. if_tac; subst l; [exfalso|]; auto.\n      * (* x -> l = 0; *)\n        destruct (node_pred_dec (marked g1) l). 2: exfalso; auto.\n        localize [data_at sh node_type (Vint (Int.repr 1), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)].\n        forward.\n        unlocalize [vertices_at sh (reachable g1 x) (Graph_gen_left_null g1 x)].\n        1: apply (@graph_gen_left_null_ramify _ (sSGG_VST sh) g1 x true l r); auto.\n        Exists (Graph_gen_left_null g1 x).\n        unfold vertices_at; simpl Graph.vertices_at.\n        entailer!.\n        apply (edge_spanning_tree_left_null g1 x true l r); auto.\n  - forward. Exists g1. entailer!. 2: apply derives_refl. apply edge_spanning_tree_invalid.\n    + apply (@left_valid _ _ _ _ _ _ g1 _ _) in H3; auto.\n    + intro. apply (valid_not_null g1 l).\n      * assert (l = dst g1 (x, L)) by (simpl in H_GAMMA_g1; inversion H_GAMMA_g1; auto). rewrite H9. apply H8.\n      * hnf. destruct l. 1: inversion H4. auto.\n  - (* if (r) { *)\n    Intros g2.\n    assert (vvalid g2 x) by (rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x); auto).\n    destruct (edge_spanning_tree_left_vgamma g1 g2 x l r H3 H_GAMMA_g1 H4) as [l' H_GAMMA_g2].\n    unfold vertices_at. simpl.\n    forward_if\n      (EX g3: Graph,\n       PROP  (edge_spanning_tree g2 (x, R) g3)\n       LOCAL (temp _r (pointer_val_val r);\n              temp _l (pointer_val_val l);\n              temp _x (pointer_val_val x))\n       SEP (vertices_at sh (reachable g1 x) g3)).\n    + apply denote_tc_test_eq_split. 2: entailer!. apply (graph_right_local_facts _ _ _ _ l l' r); auto.\n    + (* root_mark = r -> m; *)\n      localize [data_at sh node_type (vgamma2cdata (vgamma g2 r)) (pointer_val_val r)].\n      remember (vgamma g2 r) as dlr in |-*. destruct dlr as [[dd ll] rr].\n      forward. simpl vgamma2cdata at 1.\n      replace (if dd then 1 else 0) with (if node_pred_dec (marked g2) r then 1 else 0).\n      2: {\n        destruct (node_pred_dec (marked g2)); destruct dd; auto; symmetry in Heqdlr.\n        apply vgamma_is_false in Heqdlr. simpl in a. unfold unmarked in Heqdlr. hnf in Heqdlr.\n        unfold Ensembles.In in Heqdlr. simpl in Heqdlr. apply Heqdlr in a. exfalso; auto.\n        apply vgamma_is_true in Heqdlr. exfalso; auto.\n      } rewrite Heqdlr. clear dd ll rr Heqdlr.\n      unlocalize [vertices_at sh (reachable g1 x) g2].\n      * destruct (vgamma g2 r) as [[dd ll] rr] eqn:? .\n        assert (vvalid g1 r). {\n          assert (weak_valid g1 r) by (eapply gamma_right_weak_valid; eauto).\n          destruct H7; auto. hnf in H7; subst. exfalso; intuition.\n        } unfold vgamma2cdata; apply (@vertices_at_ramif_1_stable _ _ _ _ _ _ _ (SGA_VST sh) _ _ r (dd, ll, rr)); auto.\n        apply (gamma_right_reachable_included g1 _ _ _ _ H3 H_GAMMA_g1 r).\n        apply reachable_by_refl; auto.\n      * (* if (root_mark == 0) { *)\n        Opaque node_pred_dec.\n        Opaque pSGG_VST.\n        unfold vertices_at; simpl.\n        forward_if\n          (EX g3: Graph,\n           PROP  (edge_spanning_tree g2 (x, R) g3)\n           LOCAL (temp _r (pointer_val_val r);\n                  temp _l (pointer_val_val l);\n                  temp _x (pointer_val_val x))\n           SEP (vertices_at sh (reachable g1 x) g3)).\n        -- (* spanning(r); *)\n          Transparent node_pred_dec.\n          Transparent pSGG_VST.\n          destruct (node_pred_dec (marked g2) r). 1: inversion H7.\n          localize [graph sh r g2].\n          assert (vvalid g1 r). {\n            assert (weak_valid g1 r) by (eapply gamma_right_weak_valid; eauto).\n            destruct H8; auto. hnf in H8; subst. exfalso; intuition.\n          }\n          assert (vvalid g2 r) by (rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x); auto).\n          assert (fst (fst (vgamma g2 r)) = false). {\n            simpl in n |-* . destruct (vlabel g2 r) eqn:? ; auto.\n            symmetry in Heqb. apply n in Heqb. exfalso; auto.\n          }\n          forward_call (sh, g2, r).\n          Intros g3.\n          unlocalize [vertices_at sh (reachable g1 x) g3] using g3 assuming H11.\n          1: apply (@graph_ramify_aux1_right _ (sSGG_VST sh) g1 g2 x l r); auto.\n          Exists g3.\n          unfold vertices_at; simpl Graph.vertices_at.\n          entailer!.\n          assert (r = dst g2 (x, R)) by (simpl in H_GAMMA_g2; inversion H_GAMMA_g2; auto).\n          unfold edge_spanning_tree. if_tac; subst r; [exfalso |]; auto. (* killed again by simpl. *)\n        -- (* x -> r = 0; *)\n          destruct (node_pred_dec (marked g2) r). 2: exfalso; auto.\n          localize [data_at sh node_type (Vint (Int.repr 1), (pointer_val_val l', pointer_val_val r)) (pointer_val_val x)].\n          forward.\n          unlocalize [vertices_at sh (reachable g1 x) (Graph_gen_right_null g2 x)].\n          1: apply (@graph_gen_right_null_ramify _ (sSGG_VST sh) g1 g2 x true l' r); auto.\n          Exists (Graph_gen_right_null g2 x).\n          unfold vertices_at. simpl Graph.vertices_at.\n          entailer!. apply (edge_spanning_tree_right_null g2 x true l' r); auto.\n    + forward. Exists g2. entailer!. apply edge_spanning_tree_invalid.\n      * apply (@right_valid _ _ _ _ _ _ g2 _ _) in H5; auto.\n      * intro. apply (valid_not_null g2 r).\n        -- assert (r = dst g2 (x, R)) by (simpl in H_GAMMA_g2; inversion H_GAMMA_g2; auto). rewrite H11. apply H10.\n        -- hnf. destruct r. 1: inversion H6. auto.\n    + (* return *)\n      Intros g3.\n      unfold vertices_at; simpl Graph.vertices_at.\n      Exists g3. entailer!.\n      * apply (edge_spanning_tree_spanning_tree g g1 g2 g3 x l r); auto.\n      * destruct H2. apply derives_refl'. apply vertices_at_Same_set. rewrite H2; reflexivity.\nQed. (* original: 5500 sec, VST 2.*: 8.91 secs *)\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/dispose/verif_dispose_bi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.17927715727681542}}
{"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.lang Require Import lang.\nFrom HypVeri.algebra Require Import base base_extra mem pagetable trans mailbox.\nFrom HypVeri.logrel Require Export logrel big_sepSS map_zip_extra logrel_extra big_sepSS.\nFrom HypVeri Require Import proofmode.\nFrom stdpp Require fin_map_dom.\nImport uPred.\n\nSection logrel_prim_extra.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{hypparams:!HypervisorParameters}.\n  Context `{vmG: !gen_VMG \u03a3}.\n\n  (* slice *)\n  Global Instance slice_trans_wf_sep \u03a61 \u03a62:\n    SliceTransWf \u03a61 ->\n    SliceTransWf \u03a62 ->\n    SliceTransWf (\u03bb trans i j, ((\u03a61 trans i j) :iProp \u03a3) \u2217 ((\u03a62 trans i j) :iProp \u03a3))%I.\n  Proof.\n    intros.\n    split.\n    intros.\n    rewrite (slice_trans_valid \u03a61) //.\n    rewrite (slice_trans_valid \u03a62) //.\n  Qed.\n\n  Global Instance slice_trans_wf_later \u03a61 :\n    SliceTransWf \u03a61 ->\n    SliceTransWf (\u03bb trans i j, \u25b7 (\u03a61 trans i j) :iProp \u03a3)%I.\n  Proof.\n    intros.\n    split.\n    intros.\n    rewrite (slice_trans_valid \u03a61) //.\n  Qed.\n\n  Instance slice_transaction_pagetable_entries_transferred_wf\n    : SliceTransWf transaction_pagetable_entries_transferred_slice.\n  Proof.\n    split.\n    intros i j trans trans' Heq.\n    rewrite /transaction_pagetable_entries_transferred_slice /=.\n    iInduction trans as [|k v m Hlk] \"IH\" using map_ind forall (trans' Heq).\n    rewrite /trans_preserve_slice map_filter_empty in Heq.\n    iSplit.\n    {\n      iIntros \"_\".\n      symmetry in Heq.\n      apply map_filter_empty_iff in Heq.\n      iApply big_sepFM_False_weak.\n      intros ? ? ? [? ?].\n      efeed specialize Heq;eauto.\n    }\n    {\n      iIntros \"_\".\n      iApply big_sepFM_empty.\n    }\n    assert (trans_preserve_slice i j m (delete k trans')).\n    {\n      rewrite /trans_preserve_slice in Heq.\n      rewrite /trans_preserve_slice.\n      destruct (decide (v.1.1.1.1 = i \u2227 v.1.1.1.2 = j)).\n      rewrite map_filter_insert_True // in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_insert //.\n      rewrite map_filter_lookup_None;left;done.\n      rewrite map_filter_insert_False // in Heq.\n      rewrite map_filter_delete in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_idemp.\n      rewrite -map_filter_delete.\n      rewrite delete_notin //.\n    }\n    destruct (decide ((v.1.1.1.1 = i \u2227 v.1.1.1.2 = j))).\n    {\n      iSpecialize (\"IH\" $! (delete k trans') H).\n      assert (trans' !! k = Some v).\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite map_filter_insert_True // in Heq.\n        assert (filter\n                  (\u03bb kv : Addr * (VMID * VMID * gset PID * transaction_type * bool),\n                      kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 = j) trans' !! k = Some v).\n        rewrite -Heq lookup_insert //.\n        rewrite map_filter_lookup_Some in H0.\n        destruct H0;done.\n      }\n      iSplit.\n      iIntros \"H\".\n      destruct (decide (v.1.2 = Donation)).\n      rewrite big_sepFM_insert_True //.\n      iApply big_sepFM_lookup_Some'. eauto.\n      split;done.\n      iDestruct \"H\" as \"[$ ?]\".\n      iApply \"IH\";done.\n      rewrite big_sepFM_insert_False //.\n      2: intros [_ ?];done.\n      iApply big_sepFM_delete_False.\n      eauto. intros [_ ?];done.\n      by iApply \"IH\".\n      iIntros \"H\".\n      destruct (decide (v.1.2 = Donation)).\n      rewrite big_sepFM_insert_True //.\n      iDestruct (big_sepFM_lookup_Some with \"H\") as \"[$ H]\". auto.\n      split;done.\n      by iApply \"IH\".\n      rewrite big_sepFM_insert_False //.\n      iApply \"IH\".\n      iApply (big_sepFM_delete_False with \"H\").\n      eauto. intros [_ ?];done.\n      intros [_ ?];done.\n    }\n    {\n      rewrite big_sepFM_insert_False //.\n      2: intros [? _];done.\n      assert (trans_preserve_slice i j m trans').\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite /trans_preserve_slice.\n        rewrite -Heq.\n        rewrite map_filter_insert_False.\n        2: intro;done.\n        rewrite delete_notin //.\n      }\n      iSpecialize (\"IH\" $! (delete k trans') H0).\n      iApply \"IH\".\n    }\n    Qed.\n\n  Instance slice_retrievable_transaction_transferred_wf\n    : SliceTransWf retrievable_transaction_transferred_slice.\n  Proof.\n    split.\n    intros i j trans trans' Heq.\n    rewrite /retrievable_transaction_transferred_slice /=.\n    iInduction trans as [|k v m Hlk] \"IH\" using map_ind forall (trans' Heq).\n    rewrite /trans_preserve_slice map_filter_empty in Heq.\n    iSplit.\n    {\n      iIntros \"_\".\n      symmetry in Heq.\n      apply map_filter_empty_iff in Heq.\n      iSplitL.\n      iApply big_sepFM_False_weak.\n      intros ? ? ? [? ?].\n      efeed specialize Heq;eauto.\n      iApply big_sepFM_False_weak.\n      intros ? ? ? [? ?].\n      efeed specialize Heq;eauto.\n    }\n    {\n      iIntros \"_\".\n      iSplitL; iApply big_sepFM_empty.\n    }\n    assert (trans_preserve_slice i j m (delete k trans')).\n    {\n      rewrite /trans_preserve_slice in Heq.\n      rewrite /trans_preserve_slice.\n      destruct (decide (v.1.1.1.1 = i \u2227 v.1.1.1.2 = j)).\n      rewrite map_filter_insert_True // in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_insert //.\n      rewrite map_filter_lookup_None;left;done.\n      rewrite map_filter_insert_False // in Heq.\n      rewrite map_filter_delete in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_idemp.\n      rewrite -map_filter_delete.\n      rewrite delete_notin //.\n    }\n    destruct (decide ((v.1.1.1.1 = i \u2227 v.1.1.1.2 = j))).\n    {\n      iSpecialize (\"IH\" $! (delete k trans') H).\n      assert (trans' !! k = Some v).\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite map_filter_insert_True // in Heq.\n        assert (filter\n                  (\u03bb kv : Addr * (VMID * VMID * gset PID * transaction_type * bool),\n                      kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 = j) trans' !! k = Some v).\n        rewrite -Heq lookup_insert //.\n        rewrite map_filter_lookup_Some in H0.\n        destruct H0;done.\n      }\n      iDestruct \"IH\" as \"[IH1 IH2]\".\n      iSplit.\n      {\n        iIntros \"H\".\n        destruct (decide (v.2 = false)).\n        rewrite big_sepFM_insert_True //.\n        rewrite big_sepFM_insert_True //.\n        iDestruct \"H\" as \"[[k H1] [k' H2]]\".\n        iDestruct (\"IH1\" with \"[$H1 $H2]\") as \"[H1 H2]\".\n        iSplitL \"k H1\".\n        iApply big_sepFM_lookup_Some'. eauto. done. iFrame.\n        iApply big_sepFM_lookup_Some'. eauto. done. iFrame.\n        rewrite big_sepFM_insert_True //.\n        iDestruct \"H\" as \"[[k H1] H2]\".\n        rewrite big_sepFM_insert_False //.\n        2: intros [_ ?];done.\n        iDestruct (\"IH1\" with \"[$H1 $H2]\") as \"[H1 H2]\".\n        iSplitL \"k H1\".\n        iApply big_sepFM_lookup_Some'. eauto. done. iFrame.\n        iApply big_sepFM_delete_False. eauto. intros [_ ?]. done. iFrame.\n      }\n      {\n      iIntros \"H\".\n      iDestruct \"H\" as \"[H1 H2]\".\n      destruct (decide (v.2 = false)).\n      rewrite big_sepFM_insert_True //.\n      rewrite big_sepFM_insert_True //.\n      iDestruct (big_sepFM_lookup_Some with \"H1\") as \"[$ H1]\". auto. done.\n      iDestruct (big_sepFM_lookup_Some with \"H2\") as \"[$ H2]\". auto. done.\n      iApply \"IH2\". iFrame.\n      rewrite big_sepFM_insert_True //.\n      rewrite big_sepFM_insert_False //.\n      2: intros [_ ?];done.\n      iDestruct (big_sepFM_lookup_Some with \"H1\") as \"[$ H1]\". auto. done.\n      iDestruct (big_sepFM_delete_False with \"H2\") as \"H2\". auto. done. intros [_ ?];done.\n      iApply \"IH2\".\n      iFrame.\n      }\n    }\n    {\n      rewrite big_sepFM_insert_False //.\n      rewrite big_sepFM_insert_False //.\n      2: intros [? _];done.\n      assert (trans_preserve_slice i j m trans').\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite /trans_preserve_slice.\n        rewrite -Heq.\n        rewrite map_filter_insert_False.\n        2: intro;done.\n        rewrite delete_notin //.\n      }\n      iSpecialize (\"IH\" $! (delete k trans') H0).\n      iApply \"IH\".\n    }\n  Qed.\n\n  (* almost same proof! *)\n  Instance slice_transferred_memory_pages_wf\n    : SliceTransWf transferred_memory_slice.\n  Proof.\n    split.\n    intros i j trans trans' Heq.\n    rewrite /transferred_memory_slice /=.\n    iInduction trans as [|k v m Hlk] \"IH\" using map_ind forall (trans' Heq).\n    rewrite /trans_preserve_slice map_filter_empty in Heq.\n    iSplit.\n    {\n      iIntros \"_\".\n      symmetry in Heq.\n      apply map_filter_empty_iff in Heq.\n      iApply big_sepFM_False_weak.\n      intros ? ? ? [? ?].\n      efeed specialize Heq;eauto.\n    }\n    {\n      iIntros \"_\".\n      iApply big_sepFM_empty.\n    }\n    assert (trans_preserve_slice i j m (delete k trans')).\n    {\n      rewrite /trans_preserve_slice in Heq.\n      rewrite /trans_preserve_slice.\n      destruct (decide (v.1.1.1.1 = i \u2227 v.1.1.1.2 = j)).\n      rewrite map_filter_insert_True // in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_insert //.\n      rewrite map_filter_lookup_None;left;done.\n      rewrite map_filter_insert_False // in Heq.\n      rewrite map_filter_delete in Heq.\n      rewrite map_filter_delete.\n      rewrite -Heq.\n      rewrite delete_idemp.\n      rewrite -map_filter_delete.\n      rewrite delete_notin //.\n    }\n    destruct (decide ((v.1.1.1.1 = i \u2227 v.1.1.1.2 = j))).\n    {\n      iSpecialize (\"IH\" $! (delete k trans') H).\n      assert (trans' !! k = Some v).\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite map_filter_insert_True // in Heq.\n        assert (filter\n                  (\u03bb kv : Addr * (VMID * VMID * gset PID * transaction_type * bool),\n                      kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 = j) trans' !! k = Some v).\n        rewrite -Heq lookup_insert //.\n        rewrite map_filter_lookup_Some in H0.\n        destruct H0;done.\n      }\n      iSplit.\n      iIntros \"H\".\n      destruct (decide (\u00ac ((k, v).2.2 = true \u2227 (k, v).2.1.2 = Lending))).\n      rewrite big_sepFM_insert_True //.\n      iApply big_sepFM_lookup_Some'. eauto.\n      split;done.\n      iDestruct \"H\" as \"[$ ?]\".\n      iApply \"IH\";done.\n      rewrite big_sepFM_insert_False //.\n      2: intros [_ ?];done.\n      iApply big_sepFM_delete_False.\n      eauto. intros [_ ?];done.\n      by iApply \"IH\".\n      iIntros \"H\".\n      destruct (decide (\u00ac ((k, v).2.2 = true \u2227 (k, v).2.1.2 = Lending))).\n      rewrite big_sepFM_insert_True //.\n      iDestruct (big_sepFM_lookup_Some with \"H\") as \"[$ H]\". eauto.\n      split;done.\n      by iApply \"IH\".\n      rewrite big_sepFM_insert_False //.\n      iApply \"IH\".\n      iApply (big_sepFM_delete_False with \"H\").\n      eauto. intros [_ ?];done.\n      intros [_ ?];done.\n    }\n    {\n      rewrite big_sepFM_insert_False //.\n      2: intros [? _];done.\n      assert (trans_preserve_slice i j m trans').\n      {\n        rewrite /trans_preserve_slice in Heq.\n        rewrite /trans_preserve_slice.\n        rewrite -Heq.\n        rewrite map_filter_insert_False.\n        2: intro;done.\n        rewrite delete_notin //.\n      }\n      iSpecialize (\"IH\" $! (delete k trans') H0).\n      iApply \"IH\".\n    }\n  Qed.\n\n  Global Instance slice_transfer_all_wf : SliceTransWf slice_transfer_all.\n  Proof.\n    rewrite /slice_transfer_all /=. apply _.\n  Qed.\n\n  Global Instance slice_transfer_all_timeless i j trans: Timeless (slice_transfer_all trans i j).\n  Proof.\n    rewrite /slice_transfer_all /=. apply _.\n  Qed.\n\n  (* Global Instance slice_rxs_wf_sep \u03a61 \u03a62: *)\n  (*   SliceRxsWf \u03a61 -> *)\n  (*   SliceRxsWf \u03a62 -> *)\n  (*   SliceRxsWf (\u03bb trans i j, ((\u03a61 trans i j) :iProp \u03a3) \u2217 ((\u03a62 trans i j) :iProp \u03a3))%I. *)\n  (* Proof. *)\n  (*   intros. *)\n  (*   split. *)\n  (*   { *)\n  (*     intros. *)\n  (*     rewrite (slice_rxs_empty \u03a61) //. *)\n  (*     rewrite (slice_rxs_empty \u03a62) //. *)\n  (*     iSplit;done. *)\n  (*   } *)\n  (*   { *)\n  (*     intros. *)\n  (*     rewrite (slice_rxs_sym \u03a61) //. *)\n  (*     rewrite (slice_rxs_sym \u03a62) //. *)\n  (*   } *)\n  (* Qed. *)\n\n  Lemma slice_preserve_except i s {\u03a6 : _ -> _ -> _ -> iProp \u03a3} `{!SliceTransWf \u03a6} trans trans':\n    except i trans = except i trans' ->\n    big_sepSS_except s i (\u03a6 trans) \u22a3\u22a2 big_sepSS_except s i (\u03a6 trans').\n  Proof.\n    iIntros (Heq).\n    rewrite /big_sepSS_except. rewrite /big_sepSS.\n    iApply big_sepS_proper. iIntros (? Hin).\n    iApply big_sepS_proper. iIntros (? Hin').\n    iApply (slice_trans_valid \u03a6).\n    rewrite /trans_preserve_slice.\n    assert (x \u2260 i). set_solver + Hin.\n    assert (x0 \u2260 i). set_solver + Hin'.\n    rewrite /except in Heq.\n    apply map_eq. intros.\n    destruct (filter\n    (\u03bb kv : Addr * (VMID * VMID * gset PID * transaction_type * bool),\n       kv.2.1.1.1.1 = x \u2227 kv.2.1.1.1.2 = x0) trans !! i0) eqn:Hlk.\n    symmetry.\n    rewrite map_filter_lookup_Some in Hlk.\n    destruct Hlk as [Hlk [? ?]].\n    assert (filter (\u03bb kv : Addr * transaction, \u00ac (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i))\n          trans !! i0 = Some t).\n    rewrite map_filter_lookup_Some.\n    split;first done.\n    intros [? |?];subst i;[subst x|subst x0];done.\n    rewrite Heq in H3.\n    rewrite map_filter_lookup_Some in H3.\n    destruct H3 as [Hlk' nP].\n    rewrite map_filter_lookup_Some.\n    split;first done. split;done.\n    symmetry.\n    rewrite map_filter_lookup_None in Hlk.\n    rewrite map_filter_lookup_None.\n    destruct Hlk as [Hlk | ?].\n    rewrite -(delete_notin trans i0 ) //in Heq.\n    rewrite map_filter_delete in Heq.\n    assert (filter (\u03bb kv : Addr * transaction, \u00ac (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i))\n          trans' !! i0 = None).\n    rewrite -Heq lookup_delete //.\n    rewrite map_filter_lookup_None in H1.\n    destruct H1.\n    { left;done. }\n    {\n      right. intros.\n      specialize (H1 x1 H2).\n      intros []. simpl in *. apply H1.\n      intros [|]. rewrite H5 in H3. done. rewrite H5 in H4. done.\n    }\n    right. intros. intros [].\n    assert (filter (\u03bb kv : Addr * transaction, \u00ac (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i))\n          trans' !! i0 = Some x1).\n    rewrite map_filter_lookup_Some.\n    split;first done.\n    intros [? |?];subst i;[subst x|subst x0];done.\n    rewrite -Heq in H5.\n    rewrite map_filter_lookup_Some in H5.\n    destruct H5.\n    specialize (H1 x1 H5).\n    apply H1.\n    split;done.\n  Qed.\n\n  Lemma elem_of_set_of_vmids i:\n    i \u2208 set_of_vmids.\n  Proof.\n    rewrite /set_of_vmids.\n    rewrite elem_of_list_to_set.\n    rewrite elem_of_list_In.\n    apply in_list_of_vmids.\n  Qed.\n\n  Lemma slice_trans_unify (\u03a6: _ -> _ -> _ -> iProp \u03a3) `{Hwf:!SliceTransWf \u03a6} trans trans' i:\n    dom (only i trans') ## dom (except i trans) ->\n    big_sepSS_except set_of_vmids i (\u03a6 trans) \u2217\n    big_sepSS_singleton set_of_vmids i (\u03a6 (only i trans' \u222a trans))\n    \u22a2  big_sepSS set_of_vmids (\u03a6 (only i trans' \u222a trans)).\n  Proof.\n    iIntros (Hdisj) \"(except & only)\".\n    assert (set_of_vmids = (set_of_vmids \u2216 {[i]}) \u222a {[i]}).\n    pose proof (elem_of_set_of_vmids i). rewrite difference_union_L. set_solver + H.\n    rewrite H.\n    iApply big_sepSS_union_singleton. set_solver +.\n    rewrite -H. iSplitL \"except\".\n    {\n      iApply (slice_preserve_except with \"except\").\n      symmetry.\n      rewrite -except_only_union //.\n    }\n    {\n      done.\n    }\n  Qed.\n\n  Lemma big_sepFM_trans_split i (trans: gmap Addr transaction) `{\u2200 x, Decision (Q x)} (\u03a6: _ -> _ -> iPropO \u03a3):\n    map_Forall (\u03bb k (v:transaction), v.1.1.1.1 \u2260 v.1.1.1.2) trans ->\n    big_sepFM trans (\u03bb kv : Addr * transaction, ((kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i) \u2227 (Q kv))%type) \u03a6\n    \u22a3\u22a2\n    (big_sepFM trans (\u03bb kv : Addr * transaction, (kv.2.1.1.1.1 = i \u2227 (Q kv))%type) \u03a6 \u2217\n     big_sepFM trans (\u03bb kv : Addr * transaction, (kv.2.1.1.1.2 = i \u2227 (Q kv))%type) \u03a6).\n  Proof.\n    intros Hfalse.\n    rewrite -big_sepFM_split_lor_weak.\n    2:{ intros ? ? ? [[? _ ] [? _]].\n        eapply (Hfalse);eauto.\n        rewrite H1 H2 //.\n    }\n    apply big_sepFM_iff.\n    intros. split.\n    intros [[|] ];eauto.\n    intros [[]|[]];eauto.\n  Qed.\n\n  Lemma big_sepFM_big_sepS_trans_sndr i (trans: gmap Addr transaction) `{\u2200 x, Decision (Q x)} (\u03a6: _ -> _ -> iPropO \u03a3):\n  ([\u2217 set] y \u2208 set_of_vmids, big_sepFM trans (\u03bb kv : Addr * transaction, ((kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 = y) \u2227 Q kv)%type) \u03a6)\n  \u22a3\u22a2 big_sepFM trans (\u03bb kv : Addr * transaction, (kv.2.1.1.1.1 = i \u2227 Q kv)%type) \u03a6.\n  Proof.\n    rewrite (big_sepFM_iff (Q:= (\u03bb kv, (kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 \u2208 set_of_vmids) \u2227 Q kv))).\n    2:{\n      intros. split.\n      intros []. split;auto;split;auto. apply elem_of_set_of_vmids.\n      intros [[] ?]. split;done.\n    }\n    iInduction set_of_vmids as [|x s Hin] \"IH\" using set_ind_L.\n    {\n      iSplit; iIntros.\n      iApply big_sepFM_False.\n      intros ? [[_ ?] _].\n      set_solver.\n      by iApply big_sepS_empty.\n    }\n    {\n      rewrite big_sepS_union //.\n      2: set_solver+ Hin.\n      rewrite big_sepS_singleton.\n      rewrite (big_sepFM_iff\n                 (P:= (\u03bb kv, ((kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 \u2208 {[x]} \u222a s) \u2227 Q kv)))\n                 (Q:= (\u03bb kv, ((kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 = x) \u2227 Q kv \u2228 (kv.2.1.1.1.1 = i \u2227 kv.2.1.1.1.2 \u2208 s) \u2227 Q kv)%type))).\n      2:{\n        intros kv. rewrite elem_of_union. split.\n        intros [[? [|]] ?]. left;split;auto;split;auto. set_solver.\n        right;split;auto.\n        intros [[[] ?]|[[] ?]];split;auto;split;auto.\n        left;set_solver.\n      }\n      rewrite big_sepFM_split_lor.\n      2:{ intros ? ([[] ?]&[]&?). set_solver. }\n      iSplit;iIntros \"[$ ?]\"; by iApply \"IH\".\n    }\n  Qed.\n\n  Lemma big_sepFM_big_sepS_trans_rcvr i (trans: gmap Addr transaction) `{\u2200 x, Decision (Q x)} (\u03a6: _ -> _ -> iPropO \u03a3):\n  ([\u2217 set] y \u2208 set_of_vmids, big_sepFM trans (\u03bb kv : Addr * transaction, ((kv.2.1.1.1.1 = y \u2227 kv.2.1.1.1.2 = i) \u2227 Q kv)%type) \u03a6)\n  \u22a3\u22a2 big_sepFM trans (\u03bb kv : Addr * transaction, (kv.2.1.1.1.2 = i \u2227 Q kv)%type) \u03a6.\n  Proof.\n    rewrite (big_sepFM_iff (Q:= (\u03bb kv, (kv.2.1.1.1.1 \u2208 set_of_vmids \u2227 kv.2.1.1.1.2 = i) \u2227 Q kv))).\n    2:{\n      intros. split.\n      intros []. split;auto;split;auto. apply elem_of_set_of_vmids.\n      intros [[] ?]. split;done.\n    }\n    iInduction set_of_vmids as [|x s Hin] \"IH\" using set_ind_L.\n    {\n      iSplit; iIntros.\n      iApply big_sepFM_False.\n      intros ? [[? _] _].\n      set_solver.\n      by iApply big_sepS_empty.\n    }\n    {\n      rewrite big_sepS_union //.\n      2: set_solver+ Hin.\n      rewrite big_sepS_singleton.\n      rewrite (big_sepFM_iff\n                 (P:= (\u03bb kv, ((kv.2.1.1.1.1 \u2208 {[x]} \u222a s \u2227 kv.2.1.1.1.2 = i) \u2227 Q kv)))\n                 (Q:= (\u03bb kv, ((kv.2.1.1.1.1 = x \u2227 kv.2.1.1.1.2 = i) \u2227 Q kv \u2228 (kv.2.1.1.1.1 \u2208 s \u2227 kv.2.1.1.1.2 = i) \u2227 Q kv)%type))).\n      2:{\n        intros kv. rewrite elem_of_union. split.\n        intros [[[|] ?] ?]. left;split;auto. set_solver.\n        right;split;auto.\n        intros [[[] ?]|[[] ?]];split;auto.\n        split;set_solver.\n      }\n      rewrite big_sepFM_split_lor.\n      2:{ intros ? ([[]?]&[]&?). set_solver. }\n      iSplit;iIntros \"[$ ?]\"; by iApply \"IH\".\n    }\n  Qed.\n\n  Lemma transaction_pagetable_entries_transferred_only_equiv i v (trans: gmap Addr transaction):\n    trans_neq trans ->\n    i \u2260 v ->\n    (transaction_pagetable_entries_transferred_slice trans i v) \u2217 (transaction_pagetable_entries_transferred_slice trans v i) \u22a3\u22a2\n      transaction_pagetable_entries_transferred i (only v trans).\n  Proof.\n    intros ? Hne.\n    rewrite /only.\n    rewrite /transaction_pagetable_entries_transferred_slice.\n    rewrite /transaction_pagetable_entries_transferred.\n    rewrite big_sepFM_filter.\n    rewrite (big_sepFM_iff_weak (P:=(\u03bb x : Addr * transaction,\n          (((x.2.1.1.1.1 = i \u2228 x.2.1.1.1.2 = i) \u2227 x.2.1.2 = Donation)\n           \u2227 (x.2.1.1.1.1 = v \u2228 x.2.1.1.1.2 = v))%type))\n              (Q:= (\u03bb x : Addr * transaction,\n          (((x.2.1.1.1.1 = i \u2227 x.2.1.1.1.2 = v) \u2227 x.2.1.2 = Donation)\n           \u2228 ((x.2.1.1.1.1 = v \u2227 x.2.1.1.1.2 = i) \u2227 x.2.1.2 = Donation))%type))).\n    rewrite big_sepFM_split_lor_weak //.\n    intros ???.\n    specialize (H _ _ H0).\n    intros [[[] ?] [[] ?]].\n    subst i. simpl in H. simpl in H5. done.\n    intros ???.\n    split.\n    intros [[] ?].\n    destruct H1.\n    left.\n    destruct H3.\n    rewrite H1 // in H3.\n    split;auto.\n    destruct H3.\n    right;done.\n    rewrite H1 // in H3.\n    intros [[[] ?]| [[] ?]].\n    split;auto.\n    split;auto.\n  Qed.\n\n  Lemma transaction_pagetable_entries_transferred_equiv i (trans: gmap Addr transaction):\n    trans_neq trans ->\n    big_sepSS_singleton set_of_vmids i (transaction_pagetable_entries_transferred_slice trans) \u22a3\u22a2\n      transaction_pagetable_entries_transferred i trans.\n  Proof.\n    intros Hfalse.\n    rewrite /transaction_pagetable_entries_transferred.\n    rewrite big_sepFM_trans_split //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids i).\n    case_decide; last done. clear H0.\n    assert (transaction_pagetable_entries_transferred_slice trans i i \u22a3\u22a2 emp%I) as Hemp.\n    rewrite /transaction_pagetable_entries_transferred_slice.\n    iSplit;iIntros \"_\"; first done.\n    iApply big_sepFM_False_weak.\n    intros ??? [[] _]. specialize (Hfalse _ _ H0). subst i. simpl in Hfalse;done.\n    rewrite <-sep_emp. rewrite -Hemp. rewrite sep_comm. rewrite sep_assoc.\n    rewrite -(big_sepS_singleton (\u03bb x, transaction_pagetable_entries_transferred_slice\n                                         trans i x \u2217\n   transaction_pagetable_entries_transferred_slice trans x i)%I i).\n   rewrite -big_sepS_union;last set_solver+.\n    assert ({[i]} \u222a set_of_vmids \u2216 {[i]} = set_of_vmids) as ->. rewrite union_comm_L.\n    rewrite difference_union_L. set_solver.\n    rewrite big_sepS_sep /=.\n    iSplit.\n    iIntros \"(H1 & H2)\";iSplitL \"H1\";\n      first iApply big_sepFM_big_sepS_trans_sndr.\n    iApply big_sepS_proper.\n    2: iExact \"H1\".\n    intros. iApply big_sepFM_iff.\n    intros. split;intros [[] []];split;eauto.\n    iApply big_sepFM_big_sepS_trans_rcvr.\n    iApply big_sepS_proper.\n    2: iExact \"H2\".\n    intros. iApply big_sepFM_iff.\n    intros. split;intros [[] []];split;eauto.\n    iIntros \"[H1 H2]\". iSplitL \"H1\".\n    iDestruct (big_sepFM_big_sepS_trans_sndr with \"H1\") as \"H1\". done.\n    iApply big_sepFM_big_sepS_trans_rcvr. done.\n   Qed.\n\n  Lemma transaction_pagetable_entries_transferred_split i j trans:\n    transaction_pagetable_entries_transferred i trans \u22a3\u22a2\n    transaction_pagetable_entries_transferred i (only j trans) \u2217\n    transaction_pagetable_entries_transferred i (except j trans).\n  Proof.\n    rewrite /only /except.\n    rewrite /transaction_pagetable_entries_transferred.\n    rewrite 2?big_sepFM_filter.\n    rewrite -big_sepFM_split_lor.\n    2: intros ? [[] []];done.\n    iApply big_sepFM_iff.\n    intros. split.\n    intros [? ?].\n    destruct (decide (kv.2.1.1.1.1 = j \u2228 kv.2.1.1.1.2 = j));[left|right];done.\n    intros [[? _]|[? _]];done.\n  Qed.\n\n  Lemma retrievable_transaction_transferred_only_equiv i v (trans: gmap Addr transaction):\n    trans_neq trans ->\n    i \u2260 v ->\n    (retrievable_transaction_transferred_slice trans i v) \u2217 (retrievable_transaction_transferred_slice trans v i) \u22a3\u22a2\n      retrievable_transaction_transferred i (only v trans).\n  Proof.\n    intros ? Hne.\n    rewrite /only.\n    rewrite /retrievable_transaction_transferred_slice.\n    rewrite /retrievable_transaction_transferred.\n    rewrite 2!big_sepFM_filter.\n    rewrite (big_sepFM_iff_weak (P:=(\u03bb x : Addr * transaction,\n          (((x.2.1.1.1.1 = i \u2228 x.2.1.1.1.2 = i) \u2227 x.2.2 = false)\n           \u2227 (x.2.1.1.1.1 = v \u2228 x.2.1.1.1.2 = v))%type))\n              (Q:= (\u03bb x : Addr * transaction,\n          (((x.2.1.1.1.1 = i \u2227 x.2.1.1.1.2 = v) \u2227 x.2.2 = false)\n           \u2228 ((x.2.1.1.1.1 = v \u2227 x.2.1.1.1.2 = i) \u2227 x.2.2 = false))%type))).\n    rewrite big_sepFM_split_lor_weak //.\n    rewrite (big_sepFM_iff_weak (P:=(\u03bb x : Addr * transaction,\n          ((x.2.1.1.1.1 = i \u2228 x.2.1.1.1.2 = i)\n           \u2227 (x.2.1.1.1.1 = v \u2228 x.2.1.1.1.2 = v))%type))\n              (Q:= (\u03bb x : Addr * transaction,\n          ((x.2.1.1.1.1 = i \u2227 x.2.1.1.1.2 = v)\n           \u2228 (x.2.1.1.1.1 = v \u2227 x.2.1.1.1.2 = i))%type))).\n    rewrite big_sepFM_split_lor_weak //.\n    rewrite -2?sep_assoc //. f_equiv.\n    rewrite sep_comm -sep_assoc. f_equiv. rewrite sep_comm //.\n    intros ???. specialize (H _ _ H0).\n    intros [[[] ?] [[] ?]]. subst v. simpl in H. simpl in H2. done.\n    intros ???. split.\n    intros [[] ?].\n    destruct H1. left. destruct H2. rewrite H1 // in Hne. split;auto.\n    destruct H2. right;done. rewrite -H1 // in Hne.\n    intros [[[] ?]| [[] ?]]. split;auto. split;auto.\n    intros ???. specialize (H _ _ H0).\n    intros [[[] ?] [[] ?]].\n    subst v. simpl in H. simpl in H4. done.\n    intros ???. split.\n    intros [[] ?].\n    destruct H1. left. destruct H3. rewrite H1 // in H3. split;auto.\n    destruct H3. right; done. rewrite H1 // in H3.\n    intros [[[] ?]| [[] ?]]. split;auto. split;auto.\n  Qed.\n\n  Lemma retrievable_transaction_transferred_equiv i (trans: gmap Addr transaction):\n    trans_neq trans ->\n    big_sepSS_singleton set_of_vmids i (retrievable_transaction_transferred_slice trans) \u22a3\u22a2\n    retrievable_transaction_transferred i trans.\n  Proof.\n    iIntros (Hneq).\n    rewrite /retrievable_transaction_transferred.\n    rewrite big_sepFM_trans_split //.\n    rewrite (big_sepFM_iff\n               (P:= (\u03bb kv, kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i))\n               (Q:= (\u03bb kv, (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i) \u2227 (True:Prop)))).\n    2: { intros ?;split;eauto;intro. destruct H; done. }\n    rewrite big_sepFM_trans_split //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids i).\n    case_decide; last done. clear H0.\n    assert (retrievable_transaction_transferred_slice trans i i \u22a3\u22a2 emp%I) as Hemp.\n    iSplit;iIntros \"_\"; first done.\n    rewrite /retrievable_transaction_transferred_slice.\n    iSplitL; iApply big_sepFM_False_weak.\n    intros ??? [[]]. specialize (Hneq _ _ H0). simpl in Hneq;done.\n    intros ??? [[] _]. subst i. specialize (Hneq _ _ H0). simpl in Hneq;done.\n    rewrite <-sep_emp. rewrite -Hemp. rewrite sep_comm.\n    rewrite sep_assoc.\n    rewrite -(big_sepS_singleton (\u03bb x, retrievable_transaction_transferred_slice trans i x \u2217\n                                         retrievable_transaction_transferred_slice trans x i)%I i).\n    rewrite -big_sepS_union;last set_solver.\n    assert ({[i]} \u222a set_of_vmids \u2216 {[i]} = set_of_vmids) as ->. rewrite union_comm_L.\n    rewrite difference_union_L. set_solver.\n    rewrite big_sepS_sep /=.\n    rewrite /retrievable_transaction_transferred_slice.\n    rewrite 2?big_sepS_sep /=.\n    iSplit.\n    iIntros \"[[H11 H12] [H21 H22]]\";iSplitL \"H11 H21\".\n    iSplitL \"H11\";  [iApply big_sepFM_big_sepS_trans_sndr | iApply big_sepFM_big_sepS_trans_rcvr];\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n    iSplitL \"H12\";  [iApply big_sepFM_big_sepS_trans_sndr | iApply big_sepFM_big_sepS_trans_rcvr];\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n    iIntros \"[[H11 H12] [H21 H22]]\";iSplitL \"H11 H21\".\n    iSplitL \"H11\";  rewrite -big_sepFM_big_sepS_trans_sndr.\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n    iSplitL \"H12\";  rewrite -big_sepFM_big_sepS_trans_rcvr.\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n    iApply big_sepS_mono; iFrame;\n    iIntros (??) \"H\";iApply (big_sepFM_iff with \"H\"); (intros; split;intros [];done).\n   Qed.\n\n  Lemma retrievable_transaction_transferred_split i j trans:\n    retrievable_transaction_transferred i trans \u22a3\u22a2\n    retrievable_transaction_transferred i (only j trans) \u2217\n    retrievable_transaction_transferred i (except j trans).\n  Proof.\n    rewrite /only /except.\n    rewrite /retrievable_transaction_transferred.\n    rewrite 4?big_sepFM_filter.\n    rewrite -sep_assoc.\n    rewrite (sep_comm (big_sepFM trans\n    (\u03bb x : Addr * transaction, (((x.2.1.1.1.1 = i \u2228 x.2.1.1.1.2 = i) \u2227 x.2.2 = false) \u2227 (x.2.1.1.1.1 = j \u2228 x.2.1.1.1.2 = j))%type)\n    (\u03bb (k : Addr) (v : transaction), k -{1 / 4}>t v.1 \u2217 k -{1 / 2}>re v.2)%I)).\n    rewrite -sep_assoc.\n    rewrite -big_sepFM_split_lor.\n    rewrite sep_assoc.\n    rewrite -big_sepFM_split_lor.\n    2: intros ? [[] []];done.\n    2: intros ? [[] []];done.\n    f_equiv.\n    apply big_sepFM_iff.\n    intros. split.\n    intros ?.\n    destruct (decide (kv.2.1.1.1.1 = j \u2228 kv.2.1.1.1.2 = j));[left|right];done.\n    intros [[? _]|[? _]];done.\n    apply big_sepFM_iff.\n    intros. split.\n    intros [? ?].\n    destruct (decide (kv.2.1.1.1.1 = j \u2228 kv.2.1.1.1.2 = j));[right|left];done.\n    intros [[? _]|[? _]];done.\n  Qed.\n\n  Lemma transferred_memory_only_equiv i v trans:\n  trans_neq trans ->\n  trans_ps_disj trans ->\n  i \u2260 v ->\n  transferred_memory_slice trans v i \u2217 transferred_memory_slice trans i v \u22a3\u22a2\n    \u2203 mem, memory_pages (transferred_memory_pages i (only v trans)) mem.\n  Proof.\n    iIntros (Hneq Hdisj Hneqi).\n    rewrite /transferred_memory_slice.\n    rewrite -big_sepFM_split_lor.\n    2: { intros ? [[[] _] [[] _]]. apply Hneqi. subst i v. done. }\n    rewrite /only /transferred_memory_pages.\n    rewrite map_filter_filter.\n    simpl.\n    iInduction trans as [|h tran m Hlk] \"IH\" using map_ind.\n    {\n      iSplit; iIntros \"H\".\n      iExists \u2205.\n      rewrite /transferred_memory_pages.\n      rewrite map_filter_empty.\n      rewrite pages_in_trans_empty //.\n      iApply memory_pages_empty.\n      iApply big_sepFM_empty.\n    }\n    {\n      rewrite /trans_neq map_Forall_insert // in Hneq.\n      destruct Hneq as [Hneq Hneq'].\n      apply trans_ps_disj_insert_2 in Hdisj;auto.\n      destruct Hdisj as [Hdisj Hdisj'].\n      iSpecialize (\"IH\" $! Hneq' Hdisj').\n      destruct (decide((tran.1.1.1.1 = v \u2227 tran.1.1.1.2 = i) \u2227 \u00ac (tran.2 = true \u2227 tran.1.2 = Lending)\n               \u2228 (tran.1.1.1.1 = i \u2227 tran.1.1.1.2 = v) \u2227 \u00ac (tran.2 = true \u2227 tran.1.2 = Lending))).\n      {\n        destruct (decide ((tran.1.1.1.1 = v \u2227 tran.1.1.1.2 = i) \u2227 \u00ac (tran.2 = true \u2227 tran.1.2 = Lending))).\n        {\n          rewrite big_sepFM_insert_True //=.\n          (* 2: { destruct a;auto. } *)\n          rewrite map_filter_insert_True //.\n          rewrite pages_in_trans_insert //.\n          2: { rewrite map_filter_lookup_None. left;done. }\n          rewrite memory_pages_split_union'.\n          iSplit; iIntros \"[$ ?]\"; by iApply \"IH\".\n          set s := (pages_in_trans (filter (\u03bb '(_, x), ((x.1.1.1.1 = i \u2228 x.1.1.1.2 = i) \u2227 \u00ac (x.2 = true \u2227 x.1.2 = Lending)) \u2227 (x.1.1.1.1 = v \u2228 x.1.1.1.2 = v)) m)).\n          assert (s \u2286 pages_in_trans m).\n          apply pages_in_trans_subseteq.\n          apply map_filter_subseteq.\n          set_solver + Hdisj H.\n          destruct a as [[] ?]. split;auto. \n        }\n        {\n          rewrite big_sepFM_insert_True //=.\n          rewrite map_filter_insert_True //.\n          rewrite pages_in_trans_insert //.\n          2: { rewrite map_filter_lookup_None. left;done. }\n          rewrite memory_pages_split_union'.\n          iSplit. iIntros \"[? ?]\". iFrame. iApply \"IH\". iFrame.\n          iIntros \"[? ?]\". iFrame. iApply \"IH\". iFrame.\n          set s := (pages_in_trans (filter (\u03bb '(_, x), ((x.1.1.1.1 = i \u2228 x.1.1.1.2 = i) \u2227 \u00ac (x.2 = true \u2227 x.1.2 = Lending)) \u2227 (x.1.1.1.1 = v \u2228 x.1.1.1.2 = v)) m)).\n          assert (s \u2286 pages_in_trans m).\n          apply pages_in_trans_subseteq.\n          apply map_filter_subseteq.\n          set_solver + Hdisj H.\n          destruct o as [|];first done.\n          destruct H as [[] ?]. split;auto. \n        }\n      }\n      {\n        rewrite big_sepFM_insert_False //=.\n        rewrite map_filter_insert_False //.\n        rewrite delete_notin //.\n          intros [[[] ?] []].\n          rewrite -H -H1 // in Hneqi.\n          apply n. right;split;auto.\n          apply n. left;split;auto.\n          rewrite -H -H1 // in Hneqi.\n      }\n    }\n  Qed.\n\n  Lemma transferred_memory_slice_empty i j: \u22a2 transferred_memory_slice \u2205 i j.\n  Proof.\n    iIntros.\n    rewrite /transferred_memory_slice.\n    iApply big_sepFM_empty.\n  Qed.\n\n  Lemma transferred_memory_equiv i trans:\n    trans_neq trans ->\n    trans_ps_disj trans ->\n    big_sepSS_singleton set_of_vmids i (transferred_memory_slice trans) \u22a3\u22a2\n    \u2203 mem, memory_pages (transferred_memory_pages i trans) mem.\n  Proof.\n    iIntros (Hneq Hdisj).\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids i).\n    case_decide; last done. clear H0.\n    assert (transferred_memory_slice trans i i\u22a3\u22a2 emp%I) as Hemp.\n    iSplit;iIntros \"_\"; first done.\n    rewrite /transferred_memory_slice.\n    iApply big_sepFM_False_weak.\n    intros ??? [[]]. specialize (Hneq _ _ H0). subst i. simpl in Hneq;done.\n    rewrite <-sep_emp. rewrite -Hemp. rewrite sep_comm. rewrite sep_assoc.\n    rewrite -(big_sepS_singleton (\u03bb x, transferred_memory_slice trans i x \u2217\n                                         transferred_memory_slice trans x i)%I i).\n    rewrite -big_sepS_union;last set_solver.\n    assert ({[i]} \u222a set_of_vmids \u2216 {[i]} = set_of_vmids) as ->. rewrite union_comm_L.\n    rewrite difference_union_L. set_solver.\n    clear Hemp.\n    iInduction trans as [|h tran m Hlk] \"IH\" using map_ind.\n    {\n      iSplit; iIntros \"H\".\n      iExists \u2205.\n      rewrite /transferred_memory_pages.\n      rewrite map_filter_empty.\n      rewrite pages_in_trans_empty //.\n      iApply memory_pages_empty.\n      rewrite big_sepS_proper.\n      erewrite big_sepS_emp. done.\n      intros. iSplit;auto.\n      iIntros \"_\".\n      rewrite /transferred_memory_slice.\n      iSplitL; iApply big_sepFM_empty.\n    }\n    {\n      rewrite 2?big_sepS_sep.\n      rewrite /transferred_memory_slice.\n      rewrite 2?big_sepFM_big_sepS_trans_sndr.\n      rewrite 2?big_sepFM_big_sepS_trans_rcvr.\n      rewrite /trans_neq map_Forall_insert // in Hneq.\n      destruct Hneq as [Hneq Hneq'].\n      apply trans_ps_disj_insert_2 in Hdisj;auto.\n      destruct Hdisj as [Hdisj Hdisj'].\n      iSpecialize (\"IH\" $! Hneq' Hdisj').\n      destruct (decide(((tran.1.1.1.1 = i \u2228 tran.1.1.1.2 = i) \u2227 \u00ac (tran.2 = true \u2227 tran.1.2 = Lending)))).\n      {\n        destruct (decide (tran.1.1.1.1 = i)).\n        {\n          rewrite big_sepFM_insert_True //=.\n          2: destruct a;auto.\n          rewrite big_sepFM_insert_False //=.\n          2: {\n            intros []. subst i. done.\n          }\n          rewrite -sep_assoc.\n          rewrite /transferred_memory_pages.\n          rewrite map_filter_insert_True //.\n          rewrite pages_in_trans_insert //.\n          2: { rewrite map_filter_lookup_None. left;done. }\n          rewrite memory_pages_split_union'.\n          iSplit; iIntros \"[$ ?]\"; by iApply \"IH\".\n          assert (pages_in_trans (filter\n          (\u03bb kv : Addr * (leibnizO VMID * leibnizO VMID * gset PID * transaction_type * bool),\n             (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i) \u2227 \u00ac (kv.2.2 = true \u2227 kv.2.1.2 = Lending)) m) \u2286 pages_in_trans m).\n          apply pages_in_trans_subseteq.\n          apply map_filter_subseteq.\n          set_solver + Hdisj H0.\n        }\n        {\n          rewrite big_sepFM_insert_False //=.\n          2: {\n            intros []. done.\n          }\n          rewrite big_sepFM_insert_True //=.\n          2: {\n            destruct a as [[|]?];eauto. done.\n          }\n          rewrite /transferred_memory_pages.\n          rewrite map_filter_insert_True //.\n          rewrite pages_in_trans_insert //.\n          2: { rewrite map_filter_lookup_None. left;done. }\n          rewrite memory_pages_split_union'.\n          iSplit. iIntros \"[? [? ?]]\". iFrame. iApply \"IH\". iFrame.\n          iIntros \"[? ?]\". iFrame. iApply \"IH\". iFrame.\n          assert (pages_in_trans (filter\n          (\u03bb kv : Addr * (leibnizO VMID * leibnizO VMID * gset PID * transaction_type * bool),\n             (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i) \u2227 \u00ac (kv.2.2 = true \u2227 kv.2.1.2 = Lending)) m) \u2286 pages_in_trans m).\n          apply pages_in_trans_subseteq.\n          apply map_filter_subseteq.\n          set_solver + Hdisj H0.\n        }\n      }\n      {\n        rewrite 2?big_sepFM_insert_False //=.\n        2: {\n          intros [] ;apply n. split;eauto.\n        }\n        2: {\n          intros [] ;apply n. split;eauto.\n        }\n        rewrite /transferred_memory_pages.\n        rewrite map_filter_insert_False //.\n        rewrite delete_notin //.\n      }\n    }\n  Qed.\n\n  Lemma transferred_memory_split i v trans:\n    trans_neq trans ->\n    trans_ps_disj trans ->\n    (\u2203 mem, memory_pages (transferred_memory_pages i trans) mem)\n    \u22a3\u22a2 (\u2203 mem, memory_pages (transferred_memory_pages i (only v trans)) mem) \u2217\n    \u2203 mem, memory_pages (transferred_memory_pages i (except v trans)) mem.\n  Proof.\n    iIntros (Hneq Hdisj).\n    rewrite /transferred_memory_pages.\n    pose proof (only_except_disjoint v trans).\n    pose proof (map_filter_subseteq (\u03bb kv : Addr * (leibnizO VMID * leibnizO VMID * gset PID * transaction_type * bool),\n          (kv.2.1.1.1.1 = i \u2228 kv.2.1.1.1.2 = i) \u2227 \u00ac (kv.2.2 = true \u2227 kv.2.1.2 = Lending))).\n    pose proof (H0 (only v trans)).\n    pose proof (H0 (except v trans)).\n    apply subseteq_dom in H1.\n    apply subseteq_dom in H2.\n    rewrite -memory_pages_split_union'.\n    rewrite -pages_in_trans_union.\n    rewrite -map_filter_union.\n    rewrite only_except_union //.\n    rewrite map_disjoint_dom //.\n    set_solver + H H1 H2.\n    apply (pages_in_trans_disj _ _ trans);auto.\n    transitivity (only v trans). done. apply only_subseteq.\n    transitivity (except v trans). done. apply except_subseteq.\n    set_solver + H H1 H2.\n  Qed.\n\n  Lemma slice_transfer_all_equiv k (trans: gmap Addr transaction) \u03a6:\n      (\u2200 i j trans, (i = k \u2228 j = k) -> \u03a6 trans i j \u22a3\u22a2 slice_transfer_all trans i j) ->\n      big_sepSS_singleton set_of_vmids k (\u03a6 trans) \u22a3\u22a2 big_sepSS_singleton set_of_vmids k (slice_transfer_all trans).\n  Proof.\n    intros H\u03a6.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    rewrite (H\u03a6 k k);last (left;done).\n    iSplit.\n    iIntros \"[$ H]\".\n    iApply (big_sepS_proper with \"H\").\n    intros.\n    rewrite -(H\u03a6 k x);last (left;done).\n    rewrite -(H\u03a6 x k);last (right;done).\n    done.\n    iIntros \"[$ H]\".\n    iApply (big_sepS_proper with \"H\").\n    intros.\n    rewrite -(H\u03a6 k x);last (left;done).\n    rewrite -(H\u03a6 x k);last (right;done).\n    done.\n  Qed.\n\n  Lemma transferred_only_equiv k (trans: gmap Addr transaction) \u03a6:\n      (\u2200 i j trans, (i = k \u2228 j = k) -> \u03a6 trans i j \u22a3\u22a2 slice_transfer_all trans i j) ->\n      trans_neq trans ->\n      trans_ps_disj trans ->\n      big_sepSS_singleton set_of_vmids k (\u03a6 trans) \u22a3\u22a2\n      transaction_pagetable_entries_transferred k trans \u2217\n      retrievable_transaction_transferred k trans \u2217\n      (\u2203 mem_trans, memory_pages (transferred_memory_pages k trans) mem_trans).\n  Proof.\n    intros H\u03a6 Hneq Hdisj.\n    rewrite slice_transfer_all_equiv //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    rewrite !big_sepS_sep.\n    rewrite -transaction_pagetable_entries_transferred_equiv //.\n    rewrite -retrievable_transaction_transferred_equiv //.\n    rewrite -transferred_memory_equiv //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    rewrite !big_sepS_sep.\n    iSplit.\n    iIntros \"(? & ($ & $ & $) & ($ & $ & $))\".\n    rewrite /slice_transfer_all //.\n    iIntros \"([? [$ $]] & [? [$ $]] & [? [$ $]])\".\n    rewrite /slice_transfer_all. iFrame.\n  Qed.\n\n  Lemma slice_transfer_all_equiv_later k (trans: gmap Addr transaction) \u03a6:\n      (\u2200 i j trans, (i = k \u2228 j = k) -> \u03a6 trans i j \u22a3\u22a2 slice_transfer_all trans i j) ->\n      big_sepSS_singleton set_of_vmids k (\u03bb i j, \u25b7 \u03a6 trans i j) \u22a3\u22a2 big_sepSS_singleton set_of_vmids k (\u03bb i j, \u25b7 slice_transfer_all trans i j).\n  Proof.\n    intros H\u03a6.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    rewrite (H\u03a6 k k);last (left;done).\n    iSplit.\n    iIntros \"[$ H]\".\n    iApply (big_sepS_proper with \"H\").\n    intros.\n    rewrite -(H\u03a6 k x);last (left;done).\n    rewrite -(H\u03a6 x k);last (right;done).\n    done.\n    iIntros \"[$ H]\".\n    iApply (big_sepS_proper with \"H\").\n    intros.\n    rewrite -(H\u03a6 k x);last (left;done).\n    rewrite -(H\u03a6 x k);last (right;done).\n    done.\n  Qed.\n\n  Lemma transferred_only_equiv_later k (trans: gmap Addr transaction) \u03a6:\n      (\u2200 i j trans, (i = k \u2228 j = k) -> \u03a6 trans i j \u22a3\u22a2 slice_transfer_all trans i j) ->\n      trans_neq trans ->\n      trans_ps_disj trans ->\n      big_sepSS_singleton set_of_vmids k (\u03bb i j, \u25b7 \u03a6 trans i j) \u22a3\u22a2\n      \u25b7 (transaction_pagetable_entries_transferred k trans \u2217\n      retrievable_transaction_transferred k trans \u2217\n      (\u2203 mem_trans, memory_pages (transferred_memory_pages k trans) mem_trans)).\n  Proof.\n    intros H\u03a6 Hneq Hdisj.\n    rewrite slice_transfer_all_equiv_later //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    rewrite !big_sepS_sep.\n    rewrite -transaction_pagetable_entries_transferred_equiv //.\n    rewrite -retrievable_transaction_transferred_equiv //.\n    rewrite -transferred_memory_equiv //.\n    rewrite /big_sepSS_singleton.\n    pose proof (elem_of_set_of_vmids k).\n    case_decide; last done. clear H0 H.\n    iSplit.\n    iIntros \"(? & H)\".\n    iNext.\n    rewrite !big_sepS_sep.\n    iDestruct \"H\" as \"[($&$&$) ($&$&$)]\".\n    rewrite /slice_transfer_all //.\n    iIntros \"(H1 & H2)\".\n    rewrite -2?big_sepS_later.\n    rewrite -2?later_sep.\n    iNext.\n    rewrite !big_sepS_sep.\n    iDestruct \"H1\" as \"[$ [$ $]]\".\n    iDestruct \"H2\" as \"[[$ [$ $]] [$ [$ $]]]\".\n  Qed.\n\n  Lemma rx_state_match_equiv_later i rxs \u03a6:\n    (\u2200 os, (match os with\n                 | None => True\n                 | _ => \u03a6 i os i \u22a3\u22a2 slice_rx_state i os\n                end)) ->\n    (\u03a6 i None i \u22a3\u22a2 True) ->\n    base_extra.is_total_gmap rxs ->\n   \u25b7 (\u2200 rs : option (Addr * VMID), \u231crxs !! i = Some rs\u231d -\u2217 rx_state_match i rs \u2217 \u03a6 i rs i)\n   \u22a3\u22a2\n   \u25b7 (rx_state_get i rxs \u2217 (\u2203 p_rx : PID, RX@i:=p_rx \u2217 (\u2203 mem_rx : lang.mem, memory_page p_rx mem_rx))).\n  Proof.\n    iIntros (H\u03a6 H\u03a6' total).\n    iSplit.\n      {\n        iIntros \"H\".\n        iNext.\n        specialize (total i).\n        destruct total.\n        iDestruct (\"H\" $! x with \"[]\") as \"[H1 H2]\".\n        iPureIntro. done.\n        rewrite /rx_state_get.\n        specialize (H\u03a6 x).\n        destruct x.\n        rewrite H\u03a6.\n        rewrite /rx_state_match.\n        destruct p.\n        rewrite /slice_rx_state /=.\n        iDestruct \"H2\" as \"[H1' H2]\".\n        iSplitL \"H1 H1'\".\n        iIntros \"% %\".\n        rewrite H0 in H.\n        inversion H. subst rs.\n        iDestruct (rx_state_split i 1%Qp (Some (f,v))) as \"[_ H]\".\n        iApply (\"H\" with \"[$H1 $H1']\").\n        iFrame.\n        rewrite /slice_rx_state /=.\n        iDestruct \"H1\" as \"[H1 $]\".\n        iIntros \"% %\".\n        rewrite H0 in H.\n        inversion H.\n        iFrame \"H1\".\n      }\n      {\n        iIntros \"H\".\n        iNext.\n        rewrite /rx_state_get.\n        iDestruct \"H\" as \"[H1 H2]\".\n        iIntros \"% %\".\n        iDestruct (\"H1\" $! rs with \"[]\") as \"H1\".\n        iPureIntro. done.\n        specialize (H\u03a6 rs).\n        destruct rs.\n        rewrite H\u03a6.\n        rewrite /rx_state_match.\n        destruct p.\n        rewrite /slice_rx_state /=.\n        iFrame \"H2\".\n        iDestruct (rx_state_split i 1%Qp (Some (f,v))) as \"[H _]\".\n        iApply (\"H\" with \"H1\").\n        rewrite /slice_rx_state /=.\n        iFrame \"H2\".\n        iFrame.\n        rewrite H\u03a6' //.\n      }\n  Qed.\n\n  Lemma rx_state_match_equiv i rs rxs \u03a6:\n    (\u2200 os, (match os with\n                 | None => True\n                 | _ => \u03a6 i os V0 \u22a3\u22a2 slice_rx_state i os\n                end)) ->\n    (\u2200 i j, \u03a6 i None j \u22a3\u22a2 True) ->\n    rxs !! i = Some rs ->\n   rx_state_match i rs \u2217 \u03a6 i rs V0 \u22a3\u22a2\n                   rx_state_get i rxs \u2217 (\u2203 p_rx : PID, RX@i:=p_rx \u2217 (\u2203 mem_rx : lang.mem, memory_page p_rx mem_rx)).\n   Proof.\n    iIntros (H\u03a6 H\u03a6' Hlookup).\n    iSplit.\n    {\n        iIntros \"H\".\n        iDestruct \"H\" as \"[H1 H2]\".\n        rewrite /rx_state_get.\n        specialize (H\u03a6 rs).\n        destruct rs.\n        rewrite H\u03a6.\n        rewrite /rx_state_match.\n        destruct p.\n        rewrite /slice_rx_state /=.\n        iDestruct \"H2\" as \"[H1' H2]\".\n        iSplitL \"H1 H1'\".\n        iIntros \"% %\".\n        rewrite H in Hlookup.\n        inversion Hlookup.\n        iDestruct (rx_state_split i 1%Qp (Some (f,v))) as \"[_ H]\".\n        iApply (\"H\" with \"[$H1 $H1']\").\n        iFrame.\n        rewrite /slice_rx_state /=.\n        iDestruct \"H1\" as \"[H1 $]\".\n        iIntros \"% %\".\n        rewrite H in Hlookup.\n        inversion Hlookup.\n        iFrame \"H1\".\n      }\n      {\n        iIntros \"H\".\n        rewrite /rx_state_get.\n        iDestruct \"H\" as \"[H1 H2]\".\n        iDestruct (\"H1\" $! rs with \"[]\") as \"H1\".\n        iPureIntro. done.\n        specialize (H\u03a6 rs).\n        destruct rs.\n        rewrite H\u03a6.\n        rewrite /rx_state_match.\n        destruct p.\n        rewrite /slice_rx_state /=.\n        iFrame \"H2\".\n        iDestruct (rx_state_split i 1%Qp (Some (f,v))) as \"[H _]\".\n        iApply (\"H\" with \"H1\").\n        rewrite /slice_rx_state /=.\n        iFrame \"H2\".\n        iFrame.\n        rewrite H\u03a6' //.\n      }\n    Qed.\n\n  Lemma rx_states_split_zero {\u03a6_r} rxs:\n      is_total_gmap rxs ->\n      (\u2200 os, match os with\n              | None => True\n              | _ => \u03a6_r V0 os V0 \u22a3\u22a2 slice_rx_state V0 os\n              end) ->\n      rx_states_global rxs \u2217\n      rx_states_transferred \u03a6_r rxs\n      \u22a2\n      rx_states_global (delete V0 rxs) \u2217\n      rx_states_transferred \u03a6_r (delete V0 rxs) \u2217\n      rx_state_get V0 rxs \u2217\n      \u2203 p_rx, RX@V0 := p_rx \u2217\n      (\u2203 mem_rx, memory_page p_rx mem_rx).\n  Proof.\n    iIntros (Htotal Hequiv) \"(global & transferred)\".\n    rewrite /rx_states_global /rx_states_transferred.\n    pose proof (Htotal V0) as [rs Hlookup_rs].\n    iDestruct (big_sepM_delete with \"global\") as \"[rs global]\";eauto.\n    iDestruct (big_sepM_delete with \"transferred\") as \"[t transferred]\";eauto.\n    iFrame.\n    destruct rs.\n    {\n      iDestruct (Hequiv  (Some p) with \"t\") as \"[R ( % & ? & ?)]\".\n      rewrite /rx_state_match /slice_rx_state /=.\n      iSplitL \"rs R\".\n      rewrite /rx_state_get.\n      iIntros (?) \"%Hlk\".\n      rewrite Hlookup_rs in Hlk.\n      inversion Hlk.\n      iApply (rx_state_split V0 _ (Some p)). iFrame.\n      iExists p_rx. iFrame.\n    }\n    {\n      rewrite /rx_state_match.\n      iDestruct \"rs\" as \"[? R]\".\n      iSplitR \"R\".\n      rewrite /rx_state_get.\n      iIntros (?) \"%Hlk\".\n      rewrite Hlookup_rs in Hlk.\n      inversion Hlk.\n      done.\n      done.\n    }\n  Qed.\n\n  Lemma rx_states_split_zero_later {\u03a6_r} rxs:\n      is_total_gmap rxs ->\n      (\u2200 os, match os with\n              | None => True\n              | _ => \u03a6_r V0 os V0 \u22a3\u22a2 slice_rx_state V0 os\n              end) ->\n      rx_states_global rxs \u2217\n      \u25b7 rx_states_transferred \u03a6_r rxs\n      \u22a2\n      rx_states_global (delete V0 rxs) \u2217\n      \u25b7 rx_states_transferred \u03a6_r (delete V0 rxs) \u2217\n      \u25b7 rx_state_get V0 rxs \u2217\n      \u25b7 \u2203 p_rx, RX@V0 := p_rx \u2217\n      (\u2203 mem_rx, memory_page p_rx mem_rx).\n  Proof.\n    iIntros (Htotal Hequiv) \"(global & transferred)\".\n    rewrite /rx_states_global /rx_states_transferred.\n    pose proof (Htotal V0) as [rs Hlookup_rs].\n    iDestruct (big_sepM_delete with \"global\") as \"[rs global]\";eauto.\n    iDestruct (big_sepM_delete with \"transferred\") as \"[t transferred]\";eauto.\n    iFrame.\n    destruct rs.\n    {\n      iDestruct (Hequiv (Some p) with \"t\") as \"t\".\n      rewrite /rx_state_match /slice_rx_state /=.\n      rewrite !later_sep.\n      iDestruct (\"t\") as \"(R & ?)\".\n      iSplitL \"rs R\".\n      rewrite /rx_state_get.\n      iIntros (?) \"%Hlk\".\n      rewrite Hlookup_rs in Hlk.\n      inversion Hlk.\n      iApply (rx_state_split V0 _ (Some p)). iFrame.\n      rewrite later_sep //.\n      done.\n    }\n    {\n      rewrite /rx_state_match.\n      iDestruct \"rs\" as \"[? R]\".\n      iSplitR \"R\".\n      rewrite /rx_state_get.\n      iIntros (?) \"%Hlk\".\n      rewrite Hlookup_rs in Hlk.\n      inversion Hlk.\n      done.\n      done.\n    }\n  Qed.\n\n  Lemma rx_state_merge_zero {\u03a6_r} rxs:\n      is_total_gmap rxs ->\n      (\u2200 os, match os with\n              | None => True\n              | _ => \u03a6_r V0 os V0 \u22a3\u22a2 slice_rx_state V0 os\n              end) ->\n      rx_states_global (delete V0 rxs) \u2217\n      rx_states_transferred \u03a6_r (delete V0 rxs) \u2217\n      rx_state_get V0 rxs \u2217\n      (\u2203 p_rx, RX@V0 := p_rx \u2217\n      (\u2203 mem_rx, memory_page p_rx mem_rx))\n      \u22a2\n      rx_states_global rxs \u2217\n      rx_states_transferred \u03a6_r rxs.\n  Proof.\n    iIntros (Htotal Hequiv) \"(global & transferred & rx_state & rx)\".\n    rewrite /rx_states_global /rx_states_transferred.\n    pose proof (Htotal V0) as [rs Hlookup_rs].\n    rewrite (big_sepM_delete _ rxs V0 rs);auto.\n    iFrame \"global\".\n    rewrite (big_sepM_delete _ rxs V0 rs);auto.\n    iFrame \"transferred\".\n    iDestruct (\"rx_state\" $! rs with \"[]\") as \"rx_state\". done.\n    destruct rs.\n    {\n      rewrite /rx_state_match.\n      iDestruct (rx_state_split with \"rx_state\") as \"[$ ?]\".\n      rewrite (Hequiv (Some p)).\n      rewrite /slice_rx_state.\n      iFrame.\n    }\n    {\n      rewrite /rx_state_match.\n      iFrame.\n    }\n  Qed.\n\n  Lemma rx_state_merge_zero_later {\u03a6_r} rxs:\n      is_total_gmap rxs ->\n      (\u2200 os, match os with\n              | None => True\n              | _ => \u03a6_r V0 os V0 \u22a3\u22a2 slice_rx_state V0 os\n              end) ->\n      rx_states_global (delete V0 rxs) \u2217\n      \u25b7 rx_states_transferred \u03a6_r (delete V0 rxs) \u2217\n      rx_state_get V0 rxs \u2217\n      (\u2203 p_rx, RX@V0 := p_rx \u2217\n      (\u2203 mem_rx, memory_page p_rx mem_rx))\n      \u22a2\n      rx_states_global rxs \u2217\n      \u25b7 rx_states_transferred \u03a6_r rxs.\n  Proof.\n    iIntros (Htotal Hequiv) \"(global & transferred & rx_state & rx)\".\n    rewrite /rx_states_global /rx_states_transferred.\n    pose proof (Htotal V0) as [rs Hlookup_rs].\n    rewrite (big_sepM_delete _ rxs V0 rs);auto.\n    iFrame \"global\".\n    rewrite (big_sepM_delete _ rxs V0 rs);auto.\n    iFrame \"transferred\".\n    iDestruct (\"rx_state\" $! rs with \"[]\") as \"rx_state\". done.\n    destruct rs.\n    {\n      rewrite /rx_state_match.\n      iDestruct (rx_state_split with \"rx_state\") as \"[$ ?]\".\n      rewrite (Hequiv (Some p)).\n      rewrite /slice_rx_state.\n      iFrame.\n    }\n    {\n      rewrite /rx_state_match.\n      iFrame.\n      iNext. done.\n    }\n  Qed.\n\n  Lemma rx_states_split {\u03a6_r} `{!SliceRxsWf \u03a6_r} (i:VMID) rxs:\n      (\u2200 i os,\n         match os with\n         | None => True\n         | Some (_ ,k) => k = V0\n        end ->\n         \u03a6_r i os i \u22a3\u22a2 \u03a6_r i os V0) ->\n      is_total_gmap rxs ->\n      rx_states_global rxs \u2217\n      rx_states_transferred \u03a6_r rxs\n      \u22a2\n      rx_states_global (delete i rxs) \u2217\n      rx_states_transferred \u03a6_r (delete i rxs) \u2217\n      (\u2200 rs : option (Addr * VMID), \u231crxs !! i = Some rs\u231d -\u2217 rx_state_match i rs \u2217 \u03a6_r i rs i).\n  Proof.\n    iIntros (H Htotal) \"(global & transferred)\".\n    rewrite /rx_states_global /rx_states_owned /rx_states_transferred.\n    pose proof (Htotal i) as [rs Hlookup_rs].\n    iDestruct (big_sepM_delete with \"global\") as \"[rs global]\";eauto.\n    iDestruct (big_sepM_delete with \"transferred\") as \"[t transferred]\";eauto.\n    iFrame.\n    iIntros (?) \"%Hlk\".\n    rewrite Hlookup_rs in Hlk.\n    inversion Hlk. subst rs0.\n    destruct rs.\n    {\n      iFrame.\n      destruct p.\n      destruct (decide (v = V0)).\n      iDestruct (H with \"t\") as \"t\";done.\n      pose proof (@slice_rxs_sym _ _ \u03a6_r _ i (Some (f, v))).\n      simpl in H0.\n      rewrite H0 //.\n    }\n    {\n      rewrite (slice_rxs_empty).\n      iSplitL. iFrame \"rs\". done.\n    }\n  Qed.\n\n  Lemma rx_states_split_later {\u03a6_r} `{!SliceRxsWf \u03a6_r} (i:VMID) rxs:\n      (\u2200 i os,\n         match os with\n         | None => True\n         | Some (_ ,k) => k = V0\n        end ->\n         \u03a6_r i os i \u22a3\u22a2 \u03a6_r i os V0) ->\n      is_total_gmap rxs ->\n      rx_states_global rxs \u2217\n      \u25b7 rx_states_transferred \u03a6_r rxs\n      \u22a2\n      rx_states_global (delete i rxs) \u2217\n      \u25b7 rx_states_transferred \u03a6_r (delete i rxs) \u2217\n      \u25b7 (\u2200 rs : option (Addr * VMID), \u231crxs !! i = Some rs\u231d -\u2217 rx_state_match i rs \u2217 \u03a6_r i rs i).\n  Proof.\n    iIntros (H Htotal) \"(global & transferred)\".\n    rewrite /rx_states_global /rx_states_owned /rx_states_transferred.\n    pose proof (Htotal i) as [rs Hlookup_rs].\n    iDestruct (big_sepM_delete with \"global\") as \"[rs global]\";eauto.\n    iDestruct (big_sepM_delete with \"transferred\") as \"[t transferred]\";eauto.\n    iFrame.\n    iIntros (?) \"%Hlk\".\n    rewrite Hlookup_rs in Hlk.\n    inversion Hlk. subst rs0.\n    destruct rs.\n    {\n      iFrame.\n      destruct p.\n      destruct (decide (v = V0)).\n      iDestruct (H with \"t\") as \"t\";done.\n      pose proof (@slice_rxs_sym _ _ \u03a6_r _ i (Some (f, v))).\n      simpl in H0.\n      rewrite H0 //.\n    }\n    {\n      rewrite (slice_rxs_empty).\n      iSplitL. iFrame \"rs\". done.\n    }\n  Qed.\n\n  Lemma rx_states_merge_yield {\u03a6_r} `{!SliceRxsWf \u03a6_r} v rxs rs:\n    is_total_gmap rxs ->\n    rx_state_match v rs \u2217\n    \u25b7 \u03a6_r v rs V0 \u2217\n    rx_states_global (delete v rxs) \u2217\n    \u25b7 rx_states_transferred \u03a6_r (delete v rxs) \u22a2\n    rx_states_global  (<[v := rs]> rxs) \u2217\n    \u25b7 rx_states_transferred \u03a6_r (<[v := rs]> rxs).\n    Proof.\n      iIntros (Htotal) \"(rx_state & \u03a6 & global & transferred)\".\n      rewrite /rx_states_global.\n      rewrite big_sepM_insert_delete.\n      iFrame.\n      rewrite /rx_states_transferred.\n      rewrite big_sepM_insert_delete.\n      iFrame.\n      destruct rs;done.\n    Qed.\n\n  (* XXX: to show equiv, we need rxs!! j = Some None (and more?) *)\n  Lemma rx_states_merge_send {\u03a6_r} `{!SliceRxsWf \u03a6_r} v rxs rs l j:\n    is_total_gmap rxs ->\n    rx_state_match v rs \u2217\n    \u25b7 \u03a6_r v rs V0 \u2217\n    \u25b7 \u03a6_r j (Some(l,v)) V0 \u2217\n    rx_states_global (<[j:= Some (l,v)]>(delete v rxs)) \u2217\n    \u25b7 rx_states_transferred \u03a6_r (delete v rxs) \u22a2\n    rx_states_global  (<[j:= Some (l,v)]>(<[v := rs]> rxs)) \u2217\n    \u25b7 rx_states_transferred \u03a6_r (<[j:= Some (l,v)]>(<[v := rs]> rxs)).\n  Proof.\n    iIntros (Htotal) \"(rx_match & \u03a6v & \u03a6j & global & transferred)\".\n    rewrite /rx_states_global.\n    rewrite big_sepM_insert_delete.\n    rewrite big_sepM_insert_delete.\n    iDestruct \"global\" as \"[match_j global]\".\n    iAssert (\u231cj \u2260 v\u231d)%I with \"[match_j]\" as \"%Hneq\".\n    {\n      iDestruct \"match_j\" as \"[_ %]\".\n      simpl in H. done.\n    }\n    iFrame.\n    rewrite delete_insert_ne //.\n    rewrite big_sepM_insert_delete.\n    rewrite delete_commute.\n    iFrame.\n    rewrite /rx_states_transferred.\n    rewrite big_sepM_insert_delete.\n    rewrite delete_insert_ne //.\n    rewrite big_sepM_insert_delete.\n    iFrame.\n    specialize (Htotal j) as [? ?].\n    rewrite (big_sepM_delete _ _ j).\n    rewrite delete_commute //.\n    iDestruct \"transferred\" as \"[_ $]\".\n    destruct rs;done.\n    rewrite lookup_delete_ne //.\n  Qed.\n\nEnd logrel_prim_extra.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/logrel/logrel_prim_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.17912319985946976}}
{"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 exclude9 : reducibility -> excluded_arity 9.\nProof.\nmove=> Hrec; Presentation.\nPcase L0_1: s[9] <= 5.\n  Pcase L1_1: s[8] <= 5.\n    Pcase L2_1: s[7] <= 5.\n      Pcase L3_1: s[6] <= 5.\n        Pcase L4_1: s[5] <= 5.\n          Pcase: s[1] <= 5.\n            Reducible.\n          Pcase: s[4] <= 5.\n            Reducible.\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=2 T[2]<=0 T[3]<=2 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[4,5]<=7 [].\n          Pcase: s[3] > 7.\n            Hubcap T[3]<=0 T[4]<=2 T[5]<=4 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[1,2]<=4 [].\n          Pcase L5_1: s[2] <= 5.\n            Pcase: s[1] <= 6.\n              Reducible.\n            Pcase: s[4] > 8.\n              Hubcap T[3]<=3 T[4]<=0 T[5]<=4 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[1,2]<=4 [].\n            Pcase L6_1: s[4] > 6.\n              Pcase: s[1] > 8.\n                Hubcap T[1]<=0 T[2]<=3 T[5]<=4 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                       T[3,4]<=4 [].\n              Pcase: h[5] <= 5.\n                Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=4\n                       [].\n              Pcase: h[6] > 5.\n                Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=4\n                       [].\n              Hubcap T[5]<=4 T[6]<=5 T[8]<=5 T[1,2]<=4 T[3,4]<=4 T[7,9]<=8 [].\n            Pcase: s[3] <= 5.\n              Similar to *L6_1[5].\n            Pcase: s[3] <= 6.\n              Reducible.\n            Pcase: h[4] <= 5.\n              Reducible.\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: s[1] > 7.\n              Hubcap T[2]<=2 T[3]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[1,9]<=5 T[4,5]<=5\n                     [].\n            Pcase: h[2] <= 5.\n              Reducible.\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=1 T[4]<=2 T[5]<=4 T[6]<=5 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[4,5]<=5 [].\n            Pcase: h[5] <= 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[5]<=3 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[4,6]<=6 [].\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[4]<=1 T[5]<=3 T[6]<=5 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[4]<=1 T[5]<=4 T[6]<=5 T[8]<=5\n                   T[7,9]<=8 [].\n          Pcase: s[3] <= 5.\n            Similar to *L5_1[5].\n          Pcase: s[4] > 7.\n            Hubcap T[4]<=0 T[5]<=4 T[6]<=5 T[7]<=5 T[8]<=5 T[1,9]<=7 T[2,3]<=4 [].\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[2,3]<=4 T[4,5]<=7 [].\n          Pcase L5_2: h[5] <= 5.\n            Pcase: s[4] <= 6.\n              Reducible.\n            Pcase: h[6] <= 6.\n              Reducible.\n            Pcase: s[3] > 6.\n              Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=4\n                     [].\n            Pcase: s[1] <= 6.\n              Pcase: h[1] <= 5.\n                Reducible.\n              Pcase: s[2] > 6.\n                Hubcap T[3]<=0 T[5]<=3 T[6]<=5 T[7]<=5 T[9]<=4 T[1,8]<=6 T[2,4]<=7\n                       [].\n              Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[1,8]<=7 T[2,9]<=6 T[3,4]<=4 [].\n            Pcase: s[2] > 6.\n              Hubcap T[1]<=3 T[3]<=0 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[2,4]<=5 [].\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[1,9]<=5 T[3,4]<=5\n                     [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=4 T[2]<=0 T[3]<=0 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[3] <= 5.\n              Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,3]<=4 T[2,4]<=4\n                     [].\n            Pcase: h[2] > 5.\n              Hubcap T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[1,9]<=6 T[3,4]<=4\n                     [].\n            Pcase: h[4] > 5.\n              Hubcap T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[1,9]<=7 T[2,3]<=2\n                     [].\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=4 T[8]<=5 T[2,3]<=2 T[7,9]<=8\n                     [].\n            Pcase: h[8] <= 6.\n              Reducible.\n            Pcase: h[9] > 5.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=4 T[9]<=3\n                     T[2,3]<=2 [].\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,4]<=6 T[2,3]<=2 [].\n          Pcase: h[1] <= 5.\n            Similar to *L5_2[5].\n          Pcase L5_3: h[6] > 5.\n            Pcase: h[2] > 6.\n              Hubcap T[5]<=3 T[7]<=5 T[9]<=4 T[1,8]<=6 T[2,3]<=4 T[4,6]<=8 [].\n            Pcase: h[3] > 6.\n              Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=4\n                     [].\n            Pcase: h[4] > 6.\n              Hubcap T[5]<=3 T[7]<=5 T[9]<=4 T[1,8]<=8 T[2,3]<=4 T[4,6]<=6 [].\n            Pcase: h[6] <= 6.\n              Pcase: h[7] <= 6.\n                Reducible.\n              Pcase: s[1] > 6.\n                Hubcap T[5]<=3 T[6]<=4 T[8]<=5 T[1,2]<=4 T[3,4]<=6 T[7,9]<=8 [].\n              Pcase: s[2] > 6.\n                Hubcap T[1]<=2 T[2]<=4 T[5]<=3 T[6]<=4 T[8]<=5 T[3,4]<=4 T[7,9]<=8\n                       [].\n              Pcase: h[2] <= 5.\n                Reducible.\n              Pcase: s[3] > 6.\n                Hubcap T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=4 T[8]<=5 T[1,2]<=4 T[7,9]<=8\n                       [].\n              Hubcap T[1]<=3 T[4]<=3 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[2,3]<=3 [].\n            Pcase L6_1: s[2] > 6.\n              Pcase: s[1] > 6.\n                Hubcap T[1]<=2 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4\n                       T[3,4]<=3 [].\n              Hubcap T[2]<=4 T[5]<=3 T[6]<=5 T[7]<=5 T[9]<=4 T[1,8]<=6 T[3,4]<=3\n                     [].\n            Pcase: s[3] <= 6.\n              Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,4]<=5 T[2,3]<=3\n                     [].\n            Pcase: h[9] > 5.\n              Similar to *L6_1[5].\n            Pcase: h[8] <= 6.\n              Reducible.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=3 T[3,4]<=5 [].\n          Pcase: h[9] > 5.\n            Similar to *L5_3[5].\n          Pcase: h[7] <= 6.\n            Reducible.\n          Pcase: h[8] <= 6.\n            Reducible.\n          Pcase: s[2] > 6.\n            Hubcap T[5]<=4 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[3,4]<=3 [].\n          Pcase: s[3] > 6.\n            Hubcap T[5]<=4 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=3 T[3,4]<=5 [].\n          Hubcap T[5]<=4 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=4 [].\n        Pcase: s[1] <= 5.\n          Similar to L4_1[1].\n        Pcase L4_2: s[4] <= 5.\n          Pcase: s[5] <= 6.\n            Reducible.\n          Pcase: s[3] <= 5.\n            Pcase: s[2] <= 5.\n              Reducible.\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=1 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[2] > 7.\n              Hubcap T[1]<=3 T[2]<=0 T[3]<=4 T[4]<=4 T[5]<=1 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[4] > 5.\n              Pcase: s[1] > 6.\n                Hubcap T[4]<=3 T[5]<=1 T[6]<=4 T[7]<=5 T[8]<=5 T[1,9]<=6 T[2,3]<=6\n                       [].\n              Hubcap T[3]<=3 T[4]<=3 T[5]<=1 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[1,2]<=5 [].\n            Pcase: h[3] <= 5.\n              Reducible.\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: s[1] <= 6.\n              Hubcap T[1]<=3 T[2]<=1 T[3]<=4 T[4]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[5,6]<=4 [].\n            Pcase: s[2] > 6.\n              Hubcap T[3]<=4 T[4]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[5,6]<=4\n                     [].\n            Pcase: h[2] <= 5.\n              Reducible.\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=3 T[3]<=4 T[4]<=4 T[7]<=5 T[8]<=5 T[1,9]<=5 T[5,6]<=4\n                     [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=3 T[2]<=1 T[3]<=4 T[4]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[5,6]<=4 [].\n            Hubcap T[2]<=3 T[3]<=4 T[4]<=4 T[7]<=5 T[8]<=5 T[1,9]<=5 T[5,6]<=4 [].\n          Pcase: s[2] <= 5.\n            Pcase: s[1] <= 6.\n              Reducible.\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[5] > 8.\n              Hubcap T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=0 T[6]<=4 T[7]<=5 T[8]<=5\n                     T[1,9]<=5 [].\n            Pcase: s[1] > 8.\n              Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=3 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[5,6]<=5 [].\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=3 T[3]<=5 T[4]<=3 T[7]<=5 T[8]<=5 T[1,9]<=4 T[5,6]<=5\n                     [].\n            Pcase: s[1] <= 7.\n              Hubcap T[1]<=1 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[2]<=3 T[3]<=5 T[4]<=3 T[7]<=5 T[8]<=5 T[1,9]<=4 T[5,6]<=5\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=1 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=1 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Hubcap T[2]<=3 T[3]<=5 T[4]<=3 T[7]<=5 T[8]<=5 T[1,9]<=5 T[5,6]<=4 [].\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[1] > 6.\n            Pcase: s[2] > 6.\n              Hubcap T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[1,2]<=4 [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=4 T[2]<=0 T[3]<=4 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[5] > 7.\n              Hubcap T[4]<=3 T[7]<=5 T[8]<=5 T[1,9]<=7 T[2,3]<=5 T[5,6]<=5 [].\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: h[6] <= 5.\n              Reducible.\n            Pcase: h[2] > 5.\n              Hubcap T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[1,9]<=6 T[2,3]<=5\n                     [].\n            Hubcap T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[1,9]<=7 T[2,3]<=4 [].\n          Pcase: s[5] > 8.\n            Hubcap T[5]<=0 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=6 [].\n          Pcase: s[2] > 6.\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[5] > 7.\n              Hubcap T[7]<=5 T[8]<=5 T[9]<=4 T[1,4]<=5 T[2,3]<=6 T[5,6]<=5 [].\n            Pcase: h[5] <= 5.\n              Reducible.\n            Pcase: h[6] <= 5.\n              Reducible.\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[2]<=4 T[3]<=1 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[7] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=5\n                     T[8]<=5 T[9]<=4 [].\n            Hubcap T[2]<=4 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[9]<=4\n                   T[1,8]<=6 [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: s[3] > 6.\n            Hubcap T[3]<=4 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[1,2]<=4 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[3]<=3 T[4]<=3 T[7]<=5 T[8]<=5 T[2,9]<=6 T[5,6]<=5 [].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=3 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[2,3]<=4 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=2 T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Hubcap T[4]<=3 T[5]<=2 T[6]<=4 T[7]<=5 T[9]<=4 T[1,8]<=7 T[2,3]<=5 [].\n        Pcase: s[2] <= 5.\n          Similar to *L4_2[4].\n        Pcase: s[3] <= 5.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[4,5]<=5 [].\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[5] > 7.\n            Hubcap T[3]<=4 T[4]<=3 T[5]<=0 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[1,2]<=5 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[3]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[4,5]<=5 [].\n          Pcase: h[3] > 5.\n            Hubcap T[3]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[4,5]<=5 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[2,3]<=5 T[4,5]<=4 [].\n          Pcase L5_1: s[2] > 6.\n            Pcase: s[1] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                     T[4,5]<=5 [].\n            Pcase: s[4] > 6.\n              Hubcap T[3]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=5 T[4,5]<=5\n                     [].\n            Hubcap T[3]<=3 T[4]<=3 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=5 T[5,6]<=5 [].\n          Pcase: s[4] > 6.\n            Similar to *L5_1[4].\n          Pcase: s[1] <= 6.\n            Reducible.\n          Pcase: s[5] <= 6.\n            Reducible.\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Hubcap T[2]<=3 T[3]<=4 T[4]<=3 T[7]<=5 T[8]<=5 T[1,9]<=5 T[5,6]<=5 [].\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[4,5]<=6\n                 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[4,5]<=6\n                 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=5\n                 T[9]<=4 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=4 T[4]<=0 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[2,3]<=4\n                 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[5]<=0 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[3,4]<=4\n                 [].\n        Pcase: s[3] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[2]<=0 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,3]<=7 T[4,5]<=5 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[4,5]<=5 [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: s[4] > 6.\n            Hubcap T[3]<=2 T[4]<=2 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4\n                   T[1,2]<=4 [].\n          Hubcap T[3]<=4 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=4 T[4,5]<=4 [].\n        Pcase L4_3: s[1] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[7]<=5 T[8]<=5 T[9]<=4 T[3,4]<=4 T[5,6]<=7 [].\n          Pcase: s[4] > 6.\n            Hubcap T[6]<=4 T[7]<=5 T[8]<=5 T[1,9]<=7 T[2,3]<=3 T[4,5]<=6 [].\n          Pcase: s[5] > 6.\n            Hubcap T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=5 T[3,4]<=4 T[5,6]<=7 [].\n          Hubcap T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,4]<=6 T[2,3]<=3 [].\n        Pcase: s[5] > 6.\n          Similar to *L4_3[4].\n        Pcase: s[2] <= 6.\n          Hubcap T[1]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[2,3]<=3 T[4,5]<=6 [].\n        Pcase: s[4] > 6.\n          Hubcap T[3]<=0 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=6 T[4,5]<=6 [].\n        Hubcap T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=3 [].\n      Pcase: s[1] <= 5.\n        Similar to L3_1[1].\n      Pcase L3_2: s[5] <= 5.\n        Pcase L4_1: s[4] <= 5.\n          Pcase: s[6] <= 6.\n            Reducible.\n          Pcase: s[3] <= 5.\n            Pcase: s[2] <= 5.\n              Similar to L3_1[5].\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[4]<=5 T[5]<=4 T[6]<=1 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[2] > 7.\n              Hubcap T[1]<=3 T[2]<=0 T[3]<=4 T[4]<=5 T[5]<=4 T[6]<=1 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase L6_1: s[1] > 6.\n              Pcase: s[2] > 6.\n                Hubcap T[3]<=4 T[4]<=5 T[5]<=4 T[6]<=1 T[8]<=5 T[1,2]<=4 T[7,9]<=7\n                       [].\n              Pcase: h[2] <= 5.\n                Reducible.\n              Pcase: s[6] > 8.\n                Hubcap T[1]<=3 T[3]<=4 T[4]<=5 T[6]<=0 T[8]<=5 T[2,5]<=6 T[7,9]<=7\n                       [].\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=2 T[3]<=4 T[4]<=5 T[6]<=1 T[8]<=5 T[2,5]<=6 T[7,9]<=7\n                       [].\n              Pcase: h[3] > 5.\n                Hubcap T[4]<=5 T[6]<=1 T[8]<=5 T[1,2]<=5 T[3,5]<=7 T[7,9]<=7 [].\n              Pcase: h[4] <= 6.\n                Reducible.\n              Pcase: f1[2] <= 5.\n                Reducible.\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=1 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Hubcap T[2]<=2 T[3]<=4 T[4]<=5 T[5]<=4 T[8]<=5 T[1,9]<=6 T[6,7]<=4\n                     [].\n            Pcase: s[2] > 6.\n              Similar to *L6_1[7].\n            Reducible.\n          Pcase: s[2] <= 5.\n            Pcase: s[1] > 8.\n              Hubcap T[1]<=0 T[2]<=3 T[4]<=4 T[5]<=4 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[3,6]<=6 [].\n            Pcase: h[5] <= 5.\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[6] <= 5.\n                Reducible.\n              Pcase: s[1] > 7.\n                Hubcap T[2]<=3 T[4]<=4 T[5]<=4 T[6]<=1 T[8]<=5 T[1,3]<=6 T[7,9]<=7\n                       [].\n              Pcase: s[1] <= 6.\n                Hubcap T[1]<=5 T[4]<=4 T[5]<=4 T[8]<=5 T[9]<=4 T[2,3]<=4 T[6,7]<=4\n                       [].\n              Pcase: s[3] > 6.\n                Hubcap T[2]<=2 T[4]<=4 T[5]<=4 T[6]<=1 T[8]<=5 T[1,3]<=7 T[7,9]<=7\n                       [].\n              Pcase: h[2] <= 6.\n                Hubcap T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=5 T[1,9]<=7 T[6,7]<=4\n                       [].\n              Pcase: s[6] > 8.\n                Hubcap T[3]<=5 T[4]<=4 T[5]<=4 T[6]<=0 T[8]<=5 T[1,2]<=5 T[7,9]<=7\n                       [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=1 T[8]<=5\n                       T[7,9]<=7 [].\n              Hubcap T[1]<=1 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=4 T[6]<=1 T[8]<=5\n                     T[7,9]<=7 [].\n            Pcase: s[3] > 8.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=0 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=2 T[2]<=3 T[4]<=4 T[5]<=3 T[8]<=5 T[3,6]<=6 T[7,9]<=7\n                     [].\n            Pcase: s[3] <= 6.\n              Hubcap T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=1 T[8]<=5 T[1,2]<=6 T[7,9]<=7\n                     [].\n            Pcase: s[6] > 8.\n              Hubcap T[1]<=5 T[4]<=3 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[2,3]<=6 [].\n            Pcase: s[1] > 6.\n              Hubcap T[1]<=4 T[2]<=2 T[4]<=3 T[5]<=3 T[8]<=5 T[3,6]<=6 T[7,9]<=7\n                     [].\n            Pcase: s[3] > 7.\n              Pcase: s[6] > 7.\n                Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=4 T[2]<=2 T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Pcase: f1[1] <= 5.\n                Reducible.\n              Pcase: h[3] > 5.\n                Hubcap T[2]<=3 T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=3 T[8]<=5 T[9]<=4\n                       T[1,7]<=8 [].\n              Pcase: h[5] <= 6.\n                Hubcap T[1]<=5 T[2]<=3 T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Pcase: h[6] > 5.\n                Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Hubcap T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=3 T[6]<=3 T[1,8]<=9 T[7,9]<=7\n                     [].\n            Pcase: s[6] > 7.\n              Hubcap T[4]<=3 T[5]<=3 T[6]<=1 T[8]<=5 T[9]<=4 T[1,7]<=8 T[2,3]<=6\n                     [].\n            Pcase: h[7] <= 5.\n              Reducible.\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=2 T[4]<=3 T[5]<=3 T[8]<=5 T[9]<=4 T[1,7]<=7 T[3,6]<=6\n                     [].\n            Pcase: h[2] <= 5.\n              Hubcap T[2]<=3 T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=3 T[8]<=5 T[9]<=4\n                     T[1,7]<=8 [].\n            Pcase: f1[1] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[3,6]<=4 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[4] <= 5.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[5] <= 6.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[8]<=5\n                   T[7,9]<=7 [].\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: h[2] > 6.\n            Hubcap T[4]<=4 T[8]<=5 T[9]<=4 T[1,7]<=6 T[2,3]<=5 T[5,6]<=6 [].\n          Pcase: h[5] <= 5.\n            Pcase: h[4] <= 5.\n              Reducible.\n            Pcase: h[6] <= 5.\n              Reducible.\n            Pcase: s[1] > 6.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=1 T[8]<=5 T[2,3]<=5 T[7,9]<=7\n                     [].\n            Hubcap T[4]<=4 T[5]<=4 T[8]<=5 T[1,2]<=6 T[3,9]<=7 T[6,7]<=4 [].\n          Pcase: s[1] > 6.\n            Hubcap T[1]<=4 T[5]<=3 T[8]<=5 T[2,3]<=5 T[4,6]<=6 T[7,9]<=7 [].\n          Pcase: s[2] > 6.\n            Hubcap T[5]<=3 T[8]<=5 T[9]<=4 T[1,7]<=6 T[2,3]<=6 T[4,6]<=6 [].\n          Pcase: s[3] <= 6.\n            Hubcap T[4]<=3 T[5]<=3 T[8]<=5 T[1,2]<=6 T[3,6]<=6 T[7,9]<=7 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=1 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=4 [].\n          Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5\n                 [].\n        Pcase: s[3] <= 5.\n          Pcase: s[2] <= 5.\n            Similar to *L4_1[3].\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[4,6]<=8 [].\n          Pcase: s[4] > 8.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[6] > 8.\n            Hubcap T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=5 [].\n          Pcase: h[8] > 5.\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=0 T[2]<=3 T[5]<=3 T[8]<=5 T[9]<=4 T[3,7]<=7 T[4,6]<=8\n                     [].\n            Pcase: s[6] > 7.\n              Hubcap T[4]<=5 T[5]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[1,2]<=5 T[3,6]<=5\n                     [].\n            Pcase: h[2] <= 5.\n              Hubcap T[5]<=3 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,7]<=6 T[4,6]<=8 [].\n            Pcase: h[3] > 5.\n              Hubcap T[5]<=3 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,7]<=6 T[4,6]<=8 [].\n            Pcase: s[4] > 7.\n              Hubcap T[3]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[4,5]<=4\n                     [].\n            Pcase: h[8] <= 6.\n              Hubcap T[5]<=3 T[7]<=3 T[8]<=4 T[1,2]<=5 T[3,9]<=7 T[4,6]<=8 [].\n            Pcase: h[9] > 5.\n              Hubcap T[5]<=3 T[8]<=4 T[1,2]<=5 T[4,6]<=8 T[3,7]<=7 T[3,9]<=7\n                     T[7,9]<=7 [].\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: s[1] > 6.\n              Pcase: s[2] > 6.\n                Hubcap T[1]<=2 T[2]<=2 T[5]<=3 T[8]<=5 T[9]<=4 T[3,7]<=6 T[4,6]<=8\n                       [].\n              Pcase: f1[2] <= 5.\n                Reducible.\n              Pcase: h[4] > 5.\n                Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                       T[4,6]<=7 [].\n              Pcase: s[4] > 6.\n                Hubcap T[1]<=1 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Pcase: s[6] <= 6.\n                Reducible.\n              Pcase: f1[4] <= 5.\n                Reducible.\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=1 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=3\n                       T[8]<=5 T[9]<=4 [].\n              Hubcap T[1]<=1 T[2]<=3 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=1 T[7]<=3\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[2] <= 6.\n              Reducible.\n            Pcase: s[6] <= 6.\n              Hubcap T[1]<=1 T[2]<=3 T[3]<=2 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[4,5]<=6 [].\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=3\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=4 T[7]<=3 T[8]<=5 T[9]<=4\n                     T[5,6]<=6 [].\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: h[5] > 5.\n              Hubcap T[3]<=3 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=3 T[8]<=5 T[9]<=4\n                     T[1,2]<=5 [].\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=5 T[5]<=3 T[6]<=1 T[7]<=3 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[9] <= 6.\n            Reducible.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=3\n                   T[4,6]<=8 [].\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[7]<=4 T[8]<=5 T[4,6]<=6 T[5,9]<=6 [].\n          Pcase: s[6] > 7.\n            Hubcap T[4]<=5 T[5]<=3 T[6]<=1 T[7]<=4 T[8]<=5 T[1,2]<=5 T[3,9]<=7 [].\n          Pcase: s[6] > 6.\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=3 T[2]<=3 T[5]<=2 T[7]<=4 T[8]<=5 T[3,9]<=6 T[4,6]<=7\n                     [].\n            Pcase: h[7] <= 6.\n              Reducible.\n            Pcase: h[2] <= 5.\n              Hubcap T[3]<=3 T[4]<=5 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=3\n                     T[1,2]<=4 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=3 T[7]<=4 T[8]<=5\n                     T[6,9]<=6 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[4]<=4 T[7]<=4 T[8]<=5 T[3,9]<=6 T[5,6]<=5\n                     [].\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=2 T[7]<=4 T[8]<=5\n                     T[6,9]<=6 [].\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[1] <= 6.\n            Hubcap T[1]<=1 T[2]<=3 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                   T[9]<=3 [].\n          Pcase: s[2] > 6.\n            Hubcap T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3\n                   T[1,2]<=4 [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: s[4] <= 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=2 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                   T[9]<=3 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[3]<=3 T[7]<=4 T[8]<=5 T[9]<=3 T[2,5]<=5 T[4,6]<=8 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3\n                   T[4,5]<=6 [].\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3\n                   T[4,5]<=5 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=4 T[8]<=5\n                 T[9]<=3 [].\n        Pcase: s[2] <= 5.\n          Pcase L5_1: s[1] > 6.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[4] > 7.\n              Hubcap T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[1,2]<=6 [].\n            Pcase: s[6] > 8.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[8]<=5\n                     T[7,9]<=7 [].\n            Pcase: s[6] > 7.\n              Pcase: s[1] > 7.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[8]<=5\n                       T[7,9]<=7 [].\n              Hubcap T[5]<=3 T[6]<=2 T[8]<=5 T[1,2]<=6 T[3,4]<=7 T[7,9]<=7 [].\n            Pcase: s[1] > 8.\n              Hubcap T[1]<=0 T[2]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=7\n                     T[3,6]<=8 T[4,6]<=8 [].\n            Pcase L6_1: h[8] <= 5.\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[9] <= 6.\n                Reducible.\n              Pcase: h[6] > 5.\n                Pcase: s[1] > 7.\n                  Hubcap T[1]<=2 T[2]<=3 T[7]<=4 T[8]<=5 T[9]<=3 T[3,4]<=7\n                         T[5,6]<=6 [].\n                Hubcap T[7]<=4 T[8]<=5 T[9]<=3 T[1,2]<=6 T[3,4]<=6 T[5,6]<=6 [].\n              Pcase: s[1] > 7.\n                Hubcap T[1]<=2 T[2]<=3 T[7]<=4 T[8]<=5 T[9]<=3 T[3,5]<=6 T[4,6]<=7\n                       [].\n              Pcase: s[6] > 6.\n                Hubcap T[7]<=4 T[8]<=5 T[9]<=3 T[1,2]<=6 T[3,4]<=6 T[5,6]<=6 [].\n              Pcase: f1[6] <= 5.\n                Reducible.\n              Pcase: s[3] > 6.\n                Hubcap T[1]<=4 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3\n                       T[3,4]<=4 [].\n              Hubcap T[3]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=3 T[1,2]<=6 T[4,6]<=6\n                     [].\n            Pcase: h[8] <= 6.\n              Hubcap T[5]<=3 T[7]<=3 T[8]<=4 T[9]<=3 T[1,2]<=6 T[3,4]<=7 T[3,6]<=8\n                     T[4,6]<=8 [].\n            Pcase: h[1] <= 5.\n              Pcase: h[9] <= 6.\n                Reducible.\n              Pcase: s[1] > 7.\n                Hubcap T[1]<=2 T[2]<=3 T[5]<=3 T[7]<=4 T[8]<=4 T[9]<=3 T[3,4]<=7\n                       T[3,6]<=8 T[4,6]<=8 [].\n              Hubcap T[2]<=2 T[5]<=3 T[7]<=4 T[8]<=4 T[9]<=3 T[1,6]<=8 T[3,4]<=6\n                     [].\n            Pcase: h[9] > 5.\n              Hubcap T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=3 T[1,7]<=6 T[3,4]<=7 T[3,6]<=8\n                     T[4,6]<=8 [].\n            Pcase: s[6] > 6.\n              Similar to *L6_1[3].\n            Pcase: s[3] > 6.\n              Hubcap T[2]<=2 T[5]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[1,6]<=8 T[3,4]<=4\n                     [].\n            Pcase: s[4] <= 6.\n              Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=4\n                     T[8]<=5 T[9]<=4 [].\n            Pcase: s[1] > 7.\n              Pcase: h[2] > 5.\n                Hubcap T[1]<=0 T[2]<=3 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=1 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4\n                       T[8]<=5 T[9]<=4 [].\n              Hubcap T[1]<=1 T[2]<=3 T[3]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[4,5]<=5 [].\n            Pcase: h[3] > 5.\n              Hubcap T[2]<=2 T[8]<=5 T[9]<=4 T[1,6]<=8 T[3,7]<=5 T[4,5]<=6 [].\n            Hubcap T[2]<=3 T[8]<=5 T[9]<=4 T[1,6]<=7 T[3,7]<=6 T[4,5]<=5 [].\n          Pcase: s[6] > 6.\n            Similar to *L5_1[3].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Hubcap T[2,3]<=5 T[4,5]<=5 T[7,9]<=7 T[1,6]<=9 T[1,8]<=9 T[6,8]<=9 [].\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=7\n                 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                 T[9]<=4 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                 T[9]<=4 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=4 T[4]<=0 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=5\n                 [].\n        Pcase: s[6] > 8.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase: s[6] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[8]<=5 T[1,2]<=5 T[3,4]<=7 T[5,6]<=6 T[7,9]<=7 [].\n          Pcase: s[2] > 6.\n            Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=5 T[5,6]<=6 [].\n          Pcase: s[3] > 6.\n            Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[3,4]<=6 T[5,6]<=6 [].\n          Pcase: h[2] > 6.\n            Hubcap T[2]<=2 T[8]<=5 T[9]<=4 T[1,7]<=6 T[3,4]<=7 T[5,6]<=6 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=5 T[5,6]<=6 [].\n          Pcase: h[1] > 6.\n            Hubcap T[8]<=5 T[1,2]<=5 T[3,4]<=7 T[5,6]<=6 T[7,9]<=7 [].\n          Pcase: f1[1] <= 5.\n            Reducible.\n          Pcase: h[1] > 5.\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=4 T[2]<=3 T[5]<=2 T[6]<=4 T[8]<=5 T[3,4]<=5 T[7,9]<=7\n                     [].\n            Pcase: s[6] > 7.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[8]<=5 T[2,3]<=5 T[7,9]<=7\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[4]<=4 T[8]<=5 T[2,3]<=4 T[5,6]<=6 T[7,9]<=7 [].\n            Pcase: h[4] > 6.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=2 T[4]<=3 T[8]<=5 T[5,6]<=6 T[7,9]<=7\n                     [].\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=4 T[4]<=3 T[5]<=2 T[6]<=4 T[8]<=5 T[2,3]<=5 T[7,9]<=7\n                     [].\n            Pcase: h[7] <= 5.\n              Reducible.\n            Pcase: f1[4] <= 5.\n              Reducible.\n            Pcase: h[2] <= 5.\n              Hubcap T[1]<=4 T[5]<=3 T[8]<=5 T[2,6]<=5 T[3,4]<=6 T[7,9]<=7 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=4 T[5]<=3 T[8]<=5 T[2,3]<=5 T[4,6]<=6 T[7,9]<=7 [].\n            Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[8]<=5 T[2,3]<=4 T[7,9]<=7 [].\n          Pcase: h[9] <= 6.\n            Reducible.\n          Pcase: s[4] > 6.\n            Hubcap T[3]<=2 T[4]<=4 T[5]<=2 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=6 [].\n          Pcase: s[6] > 7.\n            Hubcap T[5]<=3 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=7 T[6,7]<=5 [].\n          Hubcap T[5]<=3 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=6 T[6,7]<=6 [].\n        Pcase: s[4] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[3]<=0 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[1,9]<=6 T[2,4]<=7 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[3,4]<=3 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[3,4]<=5 [].\n          Pcase: h[3] > 6.\n            Hubcap T[3]<=0 T[4]<=4 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=5 [].\n          Pcase: h[4] > 5.\n            Hubcap T[4]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[1,9]<=7 T[2,3]<=4 [].\n          Pcase: h[5] > 5.\n            Hubcap T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=6 T[3,4]<=4 T[6,9]<=8 [].\n          Pcase: f2[4] <= 5.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[5]<=2 T[6]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=5 [].\n          Pcase: f1[6] <= 5.\n            Reducible.\n          Pcase: s[1] > 6.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[1,9]<=7 T[2,3]<=3 T[2,4]<=5\n                   T[3,4]<=5 [].\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[7] > 5.\n            Hubcap T[5]<=3 T[1,2]<=6 T[3,4]<=5 T[6,8]<=9 T[7,9]<=7 [].\n          Pcase: h[8] <= 6.\n            Reducible.\n          Pcase: f1[6] <= 6.\n            Reducible.\n          Pcase: h[9] > 5.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=4 T[9]<=3 T[1,2]<=6 T[3,4]<=5 [].\n          Pcase: h[1] <= 6.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=4 T[3,4]<=5 [].\n          Pcase: h[3] > 5.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=4 T[1,4]<=6 T[2,3]<=3 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=1 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                 T[9]<=4 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=6 T[3,4]<=4 T[6,9]<=8 [].\n        Pcase: s[3] > 6.\n          Hubcap T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=5 T[3,4]<=5 T[6,9]<=8 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[6,9]<=8\n                 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=4 T[2]<=2 T[5]<=3 T[7]<=4 T[8]<=5 T[3,4]<=4 T[6,9]<=8 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=4 T[4]<=2 T[5]<=3 T[7]<=4 T[8]<=5 T[2,3]<=4 T[6,9]<=8 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[5]<=2 T[7]<=4 T[8]<=5 T[3,4]<=5 T[6,9]<=7 [].\n        Pcase: f1[6] <= 5.\n          Reducible.\n        Pcase: h[7] > 6.\n          Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[8]<=5 T[1,2]<=6 T[7,9]<=7 [].\n        Pcase: f1[6] <= 6.\n          Reducible.\n        Pcase: h[5] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=5 T[3,4]<=5 T[6,9]<=8 [].\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=5 T[3,4]<=5 T[6,9]<=8 [].\n          Pcase: h[3] <= 5.\n            Hubcap T[2]<=3 T[5]<=3 T[7]<=4 T[1,8]<=7 T[3,4]<=5 T[6,9]<=8 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=2 T[5]<=3 T[7]<=4 T[8]<=5\n                   T[6,9]<=8 [].\n          Pcase: h[8] <= 6.\n            Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[1,2]<=5 T[3,4]<=5 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=5 T[9]<=4\n                   T[3,4]<=5 [].\n          Pcase: h[9] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3\n                   T[3,4]<=5 [].\n          Hubcap T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[3,4]<=5 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[1] > 6.\n          Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=4 T[6,9]<=8 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[4]<=3 T[5]<=3 T[7]<=4 T[1,8]<=8 T[2,3]<=4 T[6,9]<=8 [].\n        Pcase: h[3] > 5.\n          Hubcap T[4]<=3 T[5]<=3 T[7]<=4 T[1,8]<=8 T[2,3]<=4 T[6,9]<=8 [].\n        Hubcap T[3]<=2 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=5 T[6,9]<=8 [].\n      Pcase: s[2] <= 5.\n        Similar to *L3_2[3].\n      Pcase L3_3: s[4] <= 5.\n        Pcase: s[3] <= 5.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[2] > 7.\n            Hubcap T[1]<=3 T[2]<=0 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=0 T[6]<=3 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: s[6] > 7.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5\n                   T[9]<=4 [].\n          Pcase: h[2] <= 5.\n            Hubcap T[3]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=4 T[5,6]<=5 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=3 T[2]<=1 T[3]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[5,6]<=5 [].\n          Pcase: h[5] > 6.\n            Hubcap T[3]<=4 T[4]<=4 T[5]<=1 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=5 [].\n          Pcase: h[6] <= 5.\n            Hubcap T[3]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[5,6]<=4 [].\n          Pcase: h[7] > 6.\n            Hubcap T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=1 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[1,2]<=5 [].\n          Pcase: h[1] > 6.\n            Hubcap T[1]<=1 T[2]<=3 T[3]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[5,6]<=5 [].\n          Pcase L5_1: s[1] > 6.\n            Pcase: s[2] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4\n                     T[5,6]<=5 [].\n            Pcase: f1[2] <= 5.\n              Reducible.\n            Pcase: s[5] > 6.\n              Hubcap T[3]<=4 T[7]<=4 T[8]<=5 T[1,2]<=5 T[4,5]<=6 T[6,9]<=6 [].\n            Hubcap T[3]<=4 T[4]<=4 T[8]<=5 T[1,2]<=5 T[5,6]<=5 T[7,9]<=7 [].\n          Pcase: s[6] > 6.\n            Similar to *L5_1[3].\n          Pcase: s[2] <= 6.\n            Reducible.\n          Pcase: s[5] <= 6.\n            Reducible.\n          Pcase: f1[1] <= 5.\n            Reducible.\n          Pcase: f1[6] <= 5.\n            Reducible.\n          Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,6]<=5 T[2,3]<=6 T[4,5]<=6 [].\n        Pcase: s[1] > 6.\n          Hubcap T[4]<=4 T[7]<=4 T[8]<=5 T[1,9]<=7 T[2,3]<=5 T[5,6]<=5 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=5\n                 T[9]<=4 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=5 T[5,6]<=5 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[4]<=3 T[5]<=0 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=7\n                 [].\n        Pcase: s[6] > 7.\n          Hubcap T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6\n                 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=3 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=5 T[5,6]<=5 [].\n        Pcase: h[3] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[5,6]<=5 [].\n        Pcase: h[4] > 5.\n          Hubcap T[3]<=3 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[5,6]<=5 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=6 T[5,6]<=4 [].\n        Pcase: s[5] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4\n                   T[5,6]<=5 [].\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[3]<=4 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[5,6]<=4 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[2] <= 5.\n            Hubcap T[1]<=3 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=3 T[2,3]<=7 T[5,6]<=5 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5\n                   T[6,9]<=6 [].\n          Hubcap T[3]<=4 T[4]<=3 T[5]<=3 T[7]<=4 T[8]<=5 T[1,2]<=5 T[6,9]<=6 [].\n        Pcase: s[6] <= 6.\n          Reducible.\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[8]<=5 T[9]<=4 T[6,7]<=5\n                 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=3 T[4]<=4 T[5]<=3 T[8]<=5 T[9]<=3 T[2,3]<=7 T[6,7]<=5 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=2 T[8]<=5 T[7,9]<=7\n                 [].\n        Hubcap T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[8]<=5 T[1,2]<=5 T[7,9]<=7 [].\n      Pcase: s[3] <= 5.\n        Similar to *L3_3[3].\n      Pcase: s[1] > 6.\n        Hubcap T[6]<=4 T[7]<=4 T[8]<=5 T[1,9]<=7 T[2,3]<=4 T[4,5]<=6 [].\n      Pcase: s[2] > 6.\n        Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=4 T[5,6]<=7 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=5\n               T[9]<=4 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=2 T[6]<=4 T[7]<=4 T[8]<=5\n               T[9]<=4 [].\n      Pcase: s[5] > 6.\n        Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=7 T[3,4]<=4 T[5,6]<=6 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[8]<=5 T[9]<=4 T[2,3]<=6 T[4,5]<=4 T[6,7]<=7 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=3 T[6]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=4 T[4,5]<=6 [].\n      Pcase: h[3] > 6.\n        Hubcap T[1]<=4 T[2]<=2 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=4 T[5,6]<=7 [].\n      Pcase: h[5] > 6.\n        Hubcap T[1]<=4 T[2]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=4 T[5,6]<=5 [].\n      Pcase: h[6] > 6.\n        Hubcap T[1]<=4 T[6]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=6 T[4,5]<=4 [].\n      Pcase L3_4: h[8] > 5.\n        Pcase: s[3] > 6.\n          Hubcap T[3]<=4 T[4]<=2 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[5,6]<=6 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=4 T[4]<=2 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=5 T[5,6]<=6 [].\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=4 T[7]<=3 T[9]<=4 T[2,8]<=8 T[3,4]<=6 T[5,6]<=5 [].\n        Pcase: f1[6] <= 5.\n          Reducible.\n        Pcase: h[7] > 5.\n          Hubcap T[1]<=4 T[7]<=3 T[9]<=4 T[2,3]<=6 T[4,5]<=5 T[6,8]<=8 [].\n        Pcase: h[8] <= 6.\n          Reducible.\n        Pcase: h[9] > 5.\n          Hubcap T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6 T[3,4]<=6 T[5,6]<=6 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=4 T[4]<=4 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=4 T[5,6]<=5 [].\n        Pcase: h[1] > 6.\n          Hubcap T[3]<=3 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=5 T[5,6]<=6 [].\n        Pcase: f1[1] <= 5.\n          Reducible.\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[7]<=4 T[8]<=5 T[9]<=4 T[1,2]<=6 T[3,4]<=5 T[5,6]<=6 [].\n        Pcase: f1[1] <= 6.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=4 T[4]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[2,3]<=4 T[5,6]<=6 [].\n        Pcase: f1[2] <= 6.\n          Reducible.\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=4 T[5,6]<=6 [].\n        Hubcap T[1]<=4 T[2]<=2 T[7]<=4 T[8]<=5 T[9]<=4 T[3,4]<=5 T[5,6]<=6 [].\n      Pcase: h[9] > 5.\n        Similar to *L3_4[3].\n      Reducible.\n    Pcase: s[1] <= 5.\n      Similar to L2_1[1].\n    Pcase L2_2: s[5] <= 5.\n      Pcase: s[4] <= 5.\n        Pcase: s[3] <= 5.\n          Similar to L2_1[5].\n        Pcase: s[6] <= 5.\n          Similar to L2_1[6].\n        Pcase: s[2] <= 5.\n          Pcase: s[6] > 7.\n            Hubcap T[2]<=3 T[4]<=4 T[5]<=4 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[1,3]<=8 [].\n          Pcase: s[7] > 7.\n            Hubcap T[2]<=3 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4\n                   T[1,3]<=8 [].\n          Pcase L5_1: s[1] <= 6.\n            Pcase: s[3] <= 6.\n              Reducible.\n            Pcase: s[3] > 8.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=0 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=6 [].\n            Pcase: h[2] > 5.\n              Pcase: s[3] > 7.\n                Hubcap T[1]<=4 T[2]<=2 T[3]<=1 T[4]<=4 T[5]<=4 T[6]<=4 T[9]<=4\n                       T[7,8]<=7 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=6\n                       [].\n              Pcase: h[6] > 6.\n                Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=7 T[6,7]<=5\n                       [].\n              Pcase: s[6] <= 6.\n                Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[6]<=3 T[9]<=4 T[3,4]<=7 T[7,8]<=6\n                       [].\n              Pcase: s[7] > 6.\n                Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                       T[6,7]<=4 [].\n              Pcase: h[2] <= 6.\n                Hubcap T[2]<=2 T[8]<=4 T[9]<=4 T[1,7]<=6 T[3,4]<=7 T[5,6]<=7 [].\n              Pcase: h[4] <= 6.\n                Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4\n                       T[6,7]<=6 [].\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=4 T[7]<=3\n                       T[8]<=4 T[9]<=4 [].\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=5 [].\n            Pcase: f1[1] <= 5.\n              Reducible.\n            Pcase: s[3] <= 7.\n              Hubcap T[1]<=5 T[2]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=4 T[6,7]<=6\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=5 T[2]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=4 T[6,7]<=6\n                     [].\n            Pcase: s[6] <= 6.\n              Hubcap T[2]<=3 T[5]<=4 T[9]<=4 T[1,8]<=8 T[3,4]<=5 T[6,7]<=6 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=4 [].\n            Hubcap T[2]<=3 T[8]<=4 T[9]<=4 T[1,7]<=7 T[3,4]<=5 T[5,6]<=7 [].\n          Pcase: s[3] <= 6.\n            Similar to *L5_1[6].\n          Pcase: s[1] > 8.\n            Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=8 [].\n          Pcase: s[3] > 8.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=8 [].\n          Pcase L5_2: s[6] > 6.\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=6 [].\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=6 [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[2]<=2 T[3]<=4 T[4]<=4 T[8]<=4 T[9]<=4 T[1,7]<=5 T[5,6]<=7\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=6\n                     [].\n            Hubcap T[2]<=2 T[8]<=4 T[9]<=4 T[1,7]<=6 T[3,4]<=7 T[5,6]<=7 [].\n          Pcase: s[7] > 6.\n            Similar to *L5_2[6].\n          Hubcap T[2]<=2 T[5]<=4 T[8]<=4 T[1,9]<=6 T[3,4]<=6 T[6,7]<=8 [].\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=8\n                 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=8\n                 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=8\n                 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase L4_1: h[4] <= 5.\n          Pcase: h[5] <= 6.\n            Reducible.\n          Pcase L5_1: s[1] > 6.\n            Pcase: s[2] > 6.\n              Hubcap T[1]<=3 T[2]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7\n                     [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=4 T[2]<=0 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=7 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6\n                     [].\n            Pcase: s[7] > 6.\n              Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=2 T[9]<=4 T[2,3]<=5 T[7,8]<=7\n                     [].\n            Pcase: h[2] > 5.\n              Hubcap T[4]<=4 T[5]<=4 T[8]<=4 T[1,9]<=6 T[2,3]<=5 T[6,7]<=7 [].\n            Hubcap T[4]<=4 T[5]<=4 T[8]<=4 T[1,9]<=7 T[2,3]<=4 T[6,7]<=7 [].\n          Pcase: s[6] > 6.\n            Hubcap T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[3,4]<=7 T[6,7]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[5]<=4 T[6]<=2 T[9]<=4 T[1,2]<=6 T[3,4]<=7 T[7,8]<=7 [].\n          Pcase: s[2] > 6.\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=7 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[2] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=7 [].\n            Pcase: h[3] > 6.\n              Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                     T[6,7]<=7 [].\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=4\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: f1[6] <= 5.\n              Reducible.\n            Pcase: h[7] > 6.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: h[8] > 5.\n              Hubcap T[2]<=4 T[3]<=2 T[4]<=4 T[5]<=4 T[9]<=4 T[1,8]<=5 T[6,7]<=7\n                     [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: s[3] <= 6.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Similar to *L5_1[6].\n          Hubcap T[4]<=3 T[5]<=4 T[9]<=4 T[1,8]<=7 T[2,3]<=5 T[6,7]<=7 [].\n        Pcase: h[1] <= 5.\n          Similar to *L4_1[6].\n        Pcase L4_2: h[5] > 5.\n          Pcase: s[1] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[4]<=3 T[8]<=4 T[9]<=4 T[3,5]<=7 T[6,7]<=7 [].\n          Pcase: s[2] > 6.\n            Hubcap T[3]<=2 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=7 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=4 T[6,7]<=7 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[4]<=3 T[6]<=2 T[9]<=4 T[3,5]<=7 T[7,8]<=7 [].\n          Hubcap T[4]<=3 T[1,8]<=7 T[2,9]<=6 T[3,5]<=7 T[6,7]<=7 [].\n        Pcase: h[9] > 5.\n          Similar to *L4_2[6].\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[8] <= 5.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5 T[1,2]<=6 T[1,3]<=6\n                 T[2,3]<=6 [].\n        Pcase: s[7] > 6.\n          Hubcap T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5 T[1,2]<=6 T[1,3]<=6\n                 T[2,3]<=6 [].\n        Pcase: s[2] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Hubcap T[1]<=1 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5\n                 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=1 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: h[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: h[6] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase: f1[6] <= 5.\n          Reducible.\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=3 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: h[8] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: f1[2] > 5.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[1] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=3\n                 [].\n        Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[2,3]<=3\n               [].\n      Pcase L3_1: s[2] <= 5.\n        Pcase L4_1: s[3] <= 5.\n          Pcase: s[6] > 7.\n            Hubcap T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[1,4]<=8 [].\n          Pcase L5_1: h[6] > 5.\n            Pcase: s[1] <= 6.\n              Pcase: s[4] <= 6.\n                Reducible.\n              Pcase: s[4] > 7.\n                Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[8]<=4 T[9]<=4\n                       T[6,7]<=5 [].\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[5] <= 5.\n                Reducible.\n              Pcase: s[6] > 5.\n                Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=2 T[8]<=4 T[9]<=4\n                       T[6,7]<=5 [].\n              Pcase: s[7] <= 6.\n                Reducible.\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[7]<=1\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[8] <= 5.\n                Reducible.\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[7]<=2\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[4]<=1 T[5]<=3 T[6]<=3 T[7]<=2\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: f1[1] <= 5.\n                Reducible.\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=5 T[2]<=3 T[3]<=3 T[4]<=1 T[5]<=3 T[6]<=3 T[7]<=2\n                       T[8]<=4 T[9]<=4 [].\n              Hubcap T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[1,7]<=6 [].\n            Pcase: s[4] > 8.\n              Hubcap T[2]<=4 T[4]<=0 T[5]<=3 T[8]<=4 T[9]<=4 T[1,6]<=7 T[3,7]<=8\n                     [].\n            Pcase: s[6] > 5.\n              Pcase: s[1] > 7.\n                Hubcap T[1]<=1 T[2]<=4 T[3]<=4 T[8]<=4 T[9]<=4 T[4,6]<=7 T[5,7]<=6\n                       [].\n              Pcase: s[4] > 7.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=2 T[8]<=4 T[9]<=4\n                       T[6,7]<=7 [].\n              Pcase: s[7] > 7.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=2 T[7]<=0\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=4\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: s[4] > 6.\n                Pcase: s[6] > 6.\n                  Hubcap T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=2 T[9]<=4 T[1,8]<=7\n                         T[6,7]<=5 [].\n                Pcase: s[7] > 6.\n                  Hubcap T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=2 T[6]<=2 T[1,8]<=7\n                         T[7,9]<=7 [].\n                Hubcap T[1]<=4 T[2]<=4 T[5]<=2 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=6\n                       [].\n              Pcase: h[1] <= 5.\n                Reducible.\n              Pcase: s[7] > 6.\n                Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=2 T[9]<=4\n                       T[7,8]<=6 [].\n              Pcase: s[6] <= 6.\n                Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=2 T[8]<=4 T[9]<=4\n                       T[6,7]<=6 [].\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=3\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[4] > 6.\n                Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=3\n                       T[8]<=4 T[9]<=4 [].\n              Pcase: f1[4] <= 5.\n                Reducible.\n              Pcase: h[5] > 5.\n                Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=2 T[6]<=3 T[7]<=3\n                       T[8]<=4 T[9]<=4 [].\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=1 T[7]<=3\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: s[7] > 8.\n              Hubcap T[2]<=4 T[3]<=4 T[6]<=3 T[7]<=0 T[9]<=4 T[1,5]<=7 T[4,8]<=8\n                     [].\n            Pcase: s[7] <= 6.\n              Hubcap T[1]<=2 T[2]<=4 T[5]<=3 T[6]<=4 T[8]<=4 T[3,7]<=8 T[4,9]<=5\n                     [].\n            Pcase: s[1] > 8.\n              Hubcap T[1]<=0 T[2]<=4 T[3]<=4 T[5]<=4 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[4,7]<=7 [].\n            Pcase: s[4] <= 6.\n              Hubcap T[1]<=2 T[3]<=4 T[5]<=4 T[6]<=3 T[9]<=4 T[2,7]<=5 T[4,8]<=8\n                     [].\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=1 T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[4,7]<=7 [].\n            Pcase: h[2] <= 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[4,7]<=6 [].\n            Pcase: s[4] > 7.\n              Hubcap T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[1,7]<=7 [].\n            Pcase: s[7] > 7.\n              Hubcap T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=1 T[9]<=4\n                     T[1,8]<=7 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                     T[4,7]<=7 [].\n            Pcase: h[4] <= 5.\n              Reducible.\n            Pcase: h[6] <= 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[9]<=4\n                     T[7,8]<=6 [].\n            Pcase: h[8] > 6.\n              Hubcap T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[9]<=4 T[1,8]<=7 T[4,7]<=5\n                     [].\n            Pcase: h[8] <= 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=4\n                     T[8]<=3 T[9]<=3 [].\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[9]<=4 T[1,8]<=6 T[4,7]<=6\n                     [].\n            Pcase: h[4] > 6.\n              Hubcap T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[9]<=4 T[1,8]<=7 T[4,7]<=5\n                     [].\n            Pcase: h[9] > 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[8]<=3 T[9]<=3\n                     T[4,7]<=5 [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                   T[4,7]<=6 [].\n          Pcase: s[7] > 6.\n            Pcase: s[6] > 6.\n              Hubcap T[2]<=4 T[3]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[1,4]<=7 T[6,7]<=4\n                     [].\n            Pcase: h[8] > 5.\n              Pcase: s[1] > 8.\n                Hubcap T[1]<=0 T[3]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4\n                       T[2,4]<=8 [].\n              Pcase: s[4] > 8.\n                Hubcap T[2]<=4 T[3]<=4 T[4]<=0 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4\n                       T[1,5]<=8 [].\n              Pcase L7_1: s[1] <= 6.\n                Pcase: s[4] <= 6.\n                  Reducible.\n                Pcase: s[4] > 7.\n                  Hubcap T[1]<=5 T[2]<=4 T[4]<=1 T[7]<=2 T[9]<=4 T[3,5]<=7\n                         T[6,8]<=7 [].\n                Pcase: h[4] <= 5.\n                  Reducible.\n                Pcase: h[5] <= 5.\n                  Reducible.\n                Pcase: s[6] > 5.\n                  Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=2 T[7]<=2\n                         T[8]<=4 T[9]<=4 [].\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=2 T[5]<=4 T[6]<=4 T[7]<=2\n                       T[8]<=3 T[9]<=4 [].\n              Pcase: s[4] <= 6.\n                Pcase: s[1] > 7.\n                  Hubcap T[1]<=1 T[3]<=4 T[5]<=4 T[7]<=2 T[9]<=4 T[2,4]<=8\n                         T[6,8]<=7 [].\n                Pcase: h[2] <= 5.\n                  Reducible.\n                Pcase: h[1] <= 5.\n                  Reducible.\n                Pcase: s[6] <= 5.\n                  Similar to L7_1[3].\n                Pcase: f1[6] <= 5.\n                  Reducible.\n                Hubcap T[1]<=2 T[3]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,4]<=8 T[6,7]<=4\n                       [].\n              Pcase: s[1] > 7.\n                Hubcap T[1]<=1 T[2]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4\n                       T[3,4]<=7 [].\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4\n                       T[4,5]<=6 [].\n              Pcase: s[4] > 7.\n                Hubcap T[2]<=4 T[3]<=4 T[6]<=4 T[7]<=2 T[9]<=4 T[1,8]<=7 T[4,5]<=5\n                       [].\n              Pcase: s[6] > 5.\n                Hubcap T[2]<=4 T[5]<=3 T[6]<=3 T[7]<=2 T[9]<=4 T[1,8]<=7 T[3,4]<=7\n                       [].\n              Pcase: h[3] > 5.\n                Similar to L5_1[6].\n              Pcase: h[9] > 5.\n                Similar to L5_1[3].\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[5] <= 5.\n                Reducible.\n              Pcase: h[7] <= 5.\n                Reducible.\n              Pcase: h[1] <= 5.\n                Reducible.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=4 T[7]<=2\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: h[9] <= 6.\n              Reducible.\n            Pcase: s[6] <= 5.\n              Similar to L5_1[3].\n            Pcase: f1[6] <= 5.\n              Reducible.\n            Pcase: s[7] > 7.\n              Hubcap T[2]<=4 T[3]<=4 T[5]<=4 T[6]<=3 T[7]<=0 T[8]<=3 T[9]<=4\n                     T[1,4]<=7 [].\n            Pcase: s[1] > 6.\n              Hubcap T[2]<=4 T[3]<=4 T[6]<=3 T[8]<=3 T[9]<=3 T[1,4]<=7 T[5,7]<=6\n                     [].\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[5]<=3 T[7]<=3 T[8]<=3 T[9]<=4\n                   T[4,6]<=4 [].\n          Pcase: s[6] <= 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=4 T[6]<=4 T[8]<=4\n                   T[7,9]<=8 [].\n          Pcase: s[6] > 6.\n            Pcase: s[1] > 7.\n              Hubcap T[1]<=1 T[3]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,4]<=8 T[6,7]<=6\n                     [].\n            Pcase: s[4] > 7.\n              Hubcap T[1]<=5 T[2]<=4 T[5]<=2 T[8]<=4 T[9]<=4 T[3,4]<=5 T[6,7]<=6\n                     [].\n            Pcase: s[4] > 6.\n              Pcase: h[2] <= 5.\n                Hubcap T[1]<=5 T[3]<=3 T[5]<=2 T[8]<=4 T[9]<=4 T[2,4]<=6 T[6,7]<=6\n                       [].\n              Pcase: s[1] > 6.\n                Hubcap T[2]<=4 T[5]<=2 T[6]<=4 T[8]<=4 T[9]<=4 T[1,7]<=5 T[3,4]<=7\n                       [].\n              Pcase: h[4] <= 5.\n                Reducible.\n              Pcase: h[5] <= 5.\n                Reducible.\n              Pcase: h[8] <= 5.\n                Reducible.\n              Pcase: h[2] > 6.\n                Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=2 T[8]<=4 T[9]<=4\n                       T[6,7]<=6 [].\n              Pcase: f1[1] <= 5.\n                Reducible.\n              Pcase: h[3] > 5.\n                Hubcap T[1]<=5 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=3\n                       T[8]<=4 T[9]<=4 [].\n              Hubcap T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=2 T[9]<=4 T[1,8]<=8 T[6,7]<=6\n                     [].\n            Pcase: s[1] <= 6.\n              Reducible.\n            Pcase: h[2] <= 5.\n              Reducible.\n            Pcase: h[1] <= 5.\n              Reducible.\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=2 T[8]<=4 T[9]<=4\n                     T[6,7]<=6 [].\n            Hubcap T[1]<=2 T[3]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,4]<=8 T[6,7]<=5 [].\n          Pcase: s[1] <= 6.\n            Reducible.\n          Pcase: s[4] <= 6.\n            Reducible.\n          Pcase: f1[6] <= 5.\n            Reducible.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=1 T[2]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=8 [].\n          Pcase: h[2] <= 5.\n            Reducible.\n          Pcase: s[4] > 8.\n            Hubcap T[2]<=4 T[3]<=4 T[4]<=0 T[5]<=3 T[6]<=4 T[8]<=4 T[9]<=4\n                   T[1,7]<=7 [].\n          Pcase: s[4] > 7.\n            Pcase: h[2] > 6.\n              Hubcap T[2]<=4 T[5]<=3 T[9]<=4 T[1,8]<=6 T[3,4]<=5 T[6,7]<=8 [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=3 T[8]<=4 T[9]<=4\n                     T[6,7]<=8 [].\n            Pcase: h[4] <= 5.\n              Reducible.\n            Pcase: h[5] > 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=0 T[5]<=3 T[8]<=4 T[9]<=4\n                     T[6,7]<=7 [].\n            Pcase: h[7] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=3 T[7]<=3\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: h[7] <= 5.\n              Hubcap T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=4 T[8]<=4 T[9]<=4\n                     T[1,7]<=6 [].\n            Pcase: f1[7] <= 5.\n              Reducible.\n            Pcase: h[8] > 6.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=3 T[7]<=3\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: h[8] <= 5.\n              Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=3 T[7]<=4\n                     T[8]<=4 T[9]<=3 [].\n            Pcase: h[9] > 5.\n              Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=4 T[7]<=4\n                     T[8]<=3 T[9]<=3 [].\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=1 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=8 [].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: h[2] > 6.\n            Hubcap T[2]<=4 T[5]<=3 T[9]<=4 T[1,8]<=6 T[3,4]<=6 T[6,7]<=7 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=7 [].\n          Pcase: h[4] <= 5.\n            Reducible.\n          Pcase: h[7] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=2 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: h[8] > 6.\n            Hubcap T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[9]<=4 T[1,8]<=7 T[6,7]<=6 [].\n          Pcase: h[8] <= 5.\n            Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4\n                   T[9]<=3 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: h[7] <= 5.\n            Hubcap T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                   T[1,7]<=6 [].\n          Pcase: h[9] > 5.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=3\n                   T[9]<=3 [].\n          Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[8]<=4 T[9]<=4 T[6,7]<=7\n                 [].\n        Pcase: s[6] <= 5.\n          Similar to L4_1[6].\n        Pcase: s[1] > 8.\n          Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[4]<=4 T[8]<=4 T[9]<=4 T[5,6]<=7\n                 T[5,7]<=8 T[6,7]<=8 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=0 T[8]<=4 T[9]<=4 T[4,7]<=7 T[5,6]<=7 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=5 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4 T[2,3]<=7\n                 [].\n        Pcase: s[7] > 7.\n          Hubcap T[5]<=4 T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4 T[1,3]<=8 T[2,4]<=7 [].\n        Pcase: s[1] <= 6.\n          Pcase: s[4] > 7.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[9]<=4\n                   T[7,8]<=7 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[8]<=4 T[9]<=4 T[2,5]<=6 T[3,4]<=6 T[6,7]<=6 [].\n          Pcase: f1[1] <= 5.\n            Reducible.\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=5 T[8]<=4 T[9]<=4 T[2,5]<=6 T[3,4]<=5 T[6,7]<=6 [].\n          Pcase: s[7] <= 6.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=5 T[2]<=3 T[5]<=4 T[6]<=3 T[9]<=4 T[3,4]<=4 T[7,8]<=7 [].\n          Hubcap T[9]<=4 T[1,8]<=8 T[2,4]<=6 T[3,5]<=6 T[6,7]<=6 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[1] > 7.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=8 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=2 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=8 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[1,8]<=5 T[7,9]<=7 [].\n          Hubcap T[1]<=2 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=7 T[6,7]<=7 [].\n        Pcase: s[4] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=4\n                   T[3,4]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=2 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[6]<=3 T[9]<=4 T[3,4]<=6 T[7,8]<=7 [].\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=5 T[6,7]<=8 [].\n        Pcase: s[6] > 6.\n          Hubcap T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[3,4]<=7 T[6,7]<=6 [].\n        Pcase: s[7] <= 6.\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[6]<=3 T[9]<=4 T[3,4]<=6 T[7,8]<=7 [].\n        Hubcap T[2]<=3 T[5]<=4 T[6]<=3 T[1,8]<=6 T[3,4]<=7 T[7,9]<=7 [].\n      Pcase: s[3] <= 5.\n        Pcase: s[6] <= 5.\n          Similar to *L3_1[5].\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[8]<=4 T[9]<=4 T[2,5]<=6 T[3,7]<=8 T[4,6]<=8 [].\n        Pcase: s[2] > 7.\n          Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[8]<=4 T[9]<=4 T[4,6]<=8 T[5,7]<=8 [].\n        Pcase: s[4] > 8.\n          Hubcap T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[8]<=4 T[9]<=4 T[1,7]<=8\n                 [].\n        Pcase: s[6] > 7.\n          Hubcap T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4 T[1,3]<=8 T[2,4]<=8 [].\n        Pcase: s[7] > 7.\n          Hubcap T[7]<=0 T[8]<=4 T[9]<=4 T[1,5]<=8 T[2,4]<=8 T[3,6]<=6 [].\n        Pcase: s[4] <= 6.\n          Pcase: h[9] > 5.\n            Pcase: s[2] > 6.\n              Hubcap T[3]<=3 T[4]<=5 T[9]<=4 T[1,2]<=5 T[5,8]<=7 T[6,7]<=6 [].\n            Pcase: s[6] > 6.\n              Hubcap T[3]<=4 T[5]<=3 T[8]<=4 T[1,2]<=6 T[4,9]<=8 T[6,7]<=5 [].\n            Hubcap T[1,2]<=6 T[6,7]<=6 T[3,5]<=7 T[3,9]<=7 T[4,8]<=8 T[4,9]<=8\n                   T[5,8]<=7 [].\n          Pcase: h[8] <= 5.\n            Reducible.\n          Pcase: h[1] <= 5.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[8]<=4 T[9]<=4 T[4,6]<=8 T[5,7]<=6 T[1,2]<=6 T[1,3]<=6\n                   T[2,3]<=5 [].\n          Pcase: s[6] <= 6.\n            Hubcap T[8]<=4 T[9]<=4 T[4,6]<=7 T[5,7]<=6 T[1,2]<=6 T[1,3]<=6\n                   T[2,3]<=7 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=3 T[4]<=5 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=7 T[6,7]<=4 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=6 [].\n          Pcase: f1[4] <= 5.\n            Reducible.\n          Pcase: s[1] <= 6.\n            Hubcap T[3]<=3 T[4]<=5 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=5 T[6,7]<=6 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=3 T[4]<=5 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=1 T[2]<=3 T[3]<=4 T[4]<=5 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: f1[2] <= 6.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=2 T[6]<=4 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[4]<=5 T[5]<=3 T[6]<=1 T[7]<=3 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[4] > 7.\n          Pcase: s[1] > 6.\n            Hubcap T[3]<=3 T[4]<=2 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=8 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[4]<=2 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=8 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[4]<=2 T[5]<=2 T[6]<=4 T[9]<=4\n                   T[7,8]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[3]<=3 T[4]<=2 T[5]<=3 T[6]<=3 T[9]<=4 T[1,2]<=8 T[7,8]<=7 [].\n          Hubcap T[3]<=3 T[4]<=2 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=7 T[6,7]<=7 [].\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=2 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=7 [].\n        Pcase: s[6] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=2 T[8]<=4 T[9]<=4 T[1,2]<=7 T[6,7]<=6 [].\n        Pcase: s[7] <= 6.\n          Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=7 [].\n        Pcase: s[1] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=3 T[9]<=4 T[1,2]<=6 T[7,8]<=7 [].\n        Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[9]<=4 T[1,2]<=7 T[7,8]<=7 [].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=2 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=4 T[3,4]<=7\n               [].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[4]<=0 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=4 T[2,3]<=5\n               [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[7] > 8.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=0 T[8]<=4 T[9]<=4 T[2,3]<=6\n               [].\n      Pcase L3_2: h[9] > 5.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=5 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=1 T[8]<=3 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase: s[7] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=3 T[9]<=3 T[1,2]<=5 T[3,4]<=7 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=2 T[2]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=3 T[9]<=4\n                   T[3,4]<=5 [].\n          Pcase: s[3] > 6.\n            Hubcap T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=3 T[9]<=4 T[1,2]<=5 T[3,4]<=6 [].\n          Pcase: s[4] > 6.\n            Hubcap T[3]<=2 T[6]<=4 T[7]<=4 T[8]<=3 T[9]<=4 T[1,2]<=6 T[4,5]<=7 [].\n          Pcase: s[6] > 5.\n            Hubcap T[5]<=4 T[8]<=3 T[9]<=4 T[1,2]<=6 T[3,4]<=7 T[6,7]<=6 [].\n          Pcase: h[2] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[8]<=3\n                   T[7,9]<=7 [].\n          Pcase: h[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=4 T[8]<=3\n                   T[7,9]<=7 [].\n          Pcase: h[4] > 5.\n            Hubcap T[5]<=4 T[6]<=4 T[8]<=3 T[1,2]<=6 T[3,4]<=6 T[7,9]<=7 [].\n          Pcase: h[2] > 5.\n            Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[8]<=3 T[1,2]<=5 T[7,9]<=7 [].\n          Pcase: h[3] <= 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=4 T[6]<=4 T[8]<=3 T[3,4]<=6 T[7,9]<=7 [].\n          Pcase: h[5] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=4 T[6]<=4 T[8]<=3 T[3,4]<=5 T[7,9]<=7 [].\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[8]<=3 T[2,3]<=4 T[7,9]<=7 [].\n        Pcase: s[6] > 5.\n          Hubcap T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[3,4]<=6 T[6,7]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=4 T[3,4]<=6 [].\n        Pcase: s[2] > 6.\n          Hubcap T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=6 T[3,4]<=4 [].\n        Pcase: s[4] > 6.\n          Hubcap T[3]<=2 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=5 T[4,5]<=7 [].\n        Pcase: h[4] <= 5.\n          Reducible.\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[3,4]<=6\n                 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,4]<=7 T[2,3]<=3 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4\n                 T[9]<=3 [].\n        Pcase: h[4] > 6.\n          Hubcap T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=5\n                 [].\n        Pcase: h[5] > 6.\n          Hubcap T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=5\n                 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[1] > 6.\n          Hubcap T[1]<=3 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[2,5]<=5 T[3,4]<=6 [].\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3 T[3,4]<=5\n                 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: h[7] > 6.\n          Hubcap T[1]<=4 T[2]<=2 T[5]<=4 T[6]<=4 T[7]<=3 T[8]<=4 T[9]<=3 T[3,4]<=6\n                 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: h[8] > 5.\n          Hubcap T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=3 T[9]<=3 T[1,2]<=5 T[3,4]<=6 [].\n        Hubcap T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4 T[9]<=3 T[1,2]<=4 T[3,4]<=6 [].\n      Pcase: h[8] <= 5.\n        Reducible.\n      Pcase: h[1] <= 5.\n        Reducible.\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=4 [].\n      Pcase: h[3] > 6.\n        Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[3,4]<=5 T[5,7]<=8 [].\n      Pcase L3_3: h[1] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=1 T[2]<=4 T[6]<=4 T[8]<=4 T[9]<=4 T[3,4]<=5 T[5,7]<=8 [].\n        Pcase: s[3] > 6.\n          Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=6 T[5,7]<=8 [].\n        Pcase: s[4] > 6.\n          Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[3,4]<=5 T[5,7]<=8 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=7 T[6,7]<=6 [].\n        Pcase: s[7] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=7 T[6,7]<=7 [].\n          Pcase: s[6] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=7 T[6,7]<=5 [].\n          Pcase: h[6] > 5.\n            Similar to *L3_2[5].\n          Pcase: h[5] <= 5.\n            Reducible.\n          Pcase: h[7] <= 5.\n            Reducible.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4 T[1,2]<=5\n                 [].\n        Pcase: s[1] > 6.\n          Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=6 T[5,7]<=8 [].\n        Pcase: s[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7 [].\n        Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=6 T[5,7]<=8 [].\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6 [].\n      Pcase: s[7] > 6.\n        Pcase: s[1] > 6.\n          Hubcap T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=7 T[6,7]<=7 [].\n        Pcase: f1[1] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=5 T[6,7]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=1 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=4 T[8]<=4 T[9]<=4 T[2,3]<=4 T[4,5]<=7 T[6,7]<=7 [].\n        Pcase: s[6] > 5.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=5 [].\n        Pcase: h[5] > 6.\n          Similar to *L3_3[5].\n        Pcase: h[6] > 5.\n          Similar to *L3_2[5].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4 T[2,3]<=4\n               [].\n      Pcase: s[1] > 6.\n        Hubcap T[6]<=4 T[8]<=4 T[9]<=4 T[1,2]<=4 T[3,4]<=6 T[5,7]<=8 [].\n      Pcase: f1[1] <= 5.\n        Reducible.\n      Pcase: s[6] > 5.\n        Reducible.\n      Pcase: h[5] > 6.\n        Similar to *L3_3[5].\n      Pcase: h[6] > 5.\n        Similar to *L3_2[5].\n      Pcase: h[5] <= 5.\n        Reducible.\n      Pcase: h[7] <= 5.\n        Reducible.\n      Pcase: s[4] > 6.\n        Hubcap T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6 T[3,4]<=4 [].\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: f1[7] <= 5.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=2 T[8]<=4 T[9]<=4 T[2,3]<=4\n               [].\n      Pcase L3_4: h[2] <= 5.\n        Pcase: s[2] <= 6.\n          Reducible.\n        Pcase: f1[1] <= 6.\n          Reducible.\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Hubcap T[1]<=3 T[2]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[3,4]<=4\n               [].\n      Pcase: h[4] <= 5.\n        Similar to *L3_4[5].\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=1 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=4 T[2]<=1 T[3]<=2 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[2,3]<=4 T[2,4]<=5\n               T[3,4]<=6 [].\n      Pcase: f1[2] <= 5.\n        Reducible.\n      Pcase: h[4] > 6.\n        Hubcap T[3]<=1 T[4]<=3 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6\n               [].\n      Hubcap T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[3,4]<=5 [].\n    Pcase: s[3] <= 5.\n      Similar to *L2_2[2].\n    Pcase L2_3: s[2] <= 5.\n      Pcase: s[6] > 7.\n        Hubcap T[4]<=4 T[6]<=0 T[7]<=3 T[8]<=4 T[9]<=4 T[1,3]<=9 T[2,5]<=6 [].\n      Pcase L3_1: s[1] <= 6.\n        Pcase: s[3] > 8.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=0 T[4]<=3 T[5]<=5 T[8]<=4 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase: s[4] > 7.\n          Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=3 T[8]<=4 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=2 T[8]<=4 T[9]<=4 T[6,7]<=5\n                 [].\n        Pcase: h[9] > 5.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=5 T[3]<=4 T[4]<=2 T[5]<=4 T[9]<=4 T[2,8]<=7 T[6,7]<=4 [].\n          Pcase: s[7] > 8.\n            Hubcap T[1]<=5 T[6]<=3 T[7]<=0 T[8]<=3 T[9]<=4 T[2,5]<=8 T[3,4]<=7 [].\n          Pcase: s[6] > 5.\n            Pcase: s[3] > 7.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[9]<=4 T[5,8]<=7 T[6,7]<=6\n                     [].\n            Pcase: s[4] > 6.\n              Hubcap T[1]<=5 T[5]<=2 T[9]<=4 T[2,8]<=7 T[3,4]<=6 T[6,7]<=6 [].\n            Pcase: s[7] > 7.\n              Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=0\n                     T[8]<=3 T[9]<=4 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=4 T[9]<=4 T[3,4]<=7 T[6,7]<=6 T[2,5]<=6 T[2,8]<=6\n                     T[5,8]<=7 [].\n            Pcase: f1[1] <= 5.\n              Reducible.\n            Pcase: s[6] > 6.\n              Hubcap T[1]<=5 T[9]<=4 T[2,8]<=7 T[6,7]<=6 T[3,4]<=7 T[3,5]<=5\n                     T[4,5]<=5 [].\n            Pcase: s[4] <= 5.\n              Hubcap T[1]<=5 T[8]<=3 T[9]<=4 T[2,4]<=6 T[3,5]<=7 T[6,7]<=5 [].\n            Pcase: s[3] > 6.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[8]<=4 T[9]<=4 T[4,5]<=4 T[6,7]<=6\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4\n                     T[6,7]<=6 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[8]<=3 T[9]<=4 T[4,5]<=6 T[6,7]<=5\n                     [].\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[8]<=3 T[9]<=4 T[4,5]<=5 T[6,7]<=5 [].\n          Pcase: s[7] <= 6.\n            Reducible.\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=2 T[8]<=3\n                   T[9]<=4 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[4]<=4 T[6]<=3 T[8]<=3 T[9]<=4\n                   T[5,7]<=4 [].\n          Pcase: s[4] <= 5.\n            Hubcap T[1]<=5 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3 T[9]<=4\n                   T[2,3]<=6 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=2 T[8]<=3\n                   T[9]<=4 [].\n          Pcase: s[7] > 7.\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=1\n                     T[8]<=3 T[9]<=4 [].\n            Pcase: f1[1] <= 5.\n              Reducible.\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=1\n                     T[8]<=3 T[9]<=4 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[6]<=3 T[7]<=1 T[8]<=3 T[9]<=4\n                     T[4,5]<=7 [].\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[6]<=3 T[7]<=1 T[8]<=3 T[9]<=4\n                   T[4,5]<=6 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[8] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[6]<=3 T[7]<=2 T[8]<=3 T[9]<=4\n                   T[4,5]<=6 [].\n          Pcase: f1[1] <= 5.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=2 T[8]<=3\n                   T[9]<=4 [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=3 T[6]<=3 T[7]<=2 T[8]<=3 T[9]<=4\n                   T[4,5]<=6 [].\n          Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[6]<=3 T[7]<=2 T[8]<=3 T[9]<=4 T[4,5]<=5\n                 [].\n        Pcase: h[8] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[7] > 8.\n          Hubcap T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4 T[1,2]<=8 T[1,3]<=8 T[2,5]<=8\n                 T[3,4]<=7 T[4,5]<=8 [].\n        Pcase: f1[1] <= 5.\n          Hubcap T[1]<=2 T[8]<=4 T[9]<=4 T[2,5]<=7 T[3,4]<=7 T[6,7]<=6 [].\n        Pcase: s[6] <= 5.\n          Pcase: s[7] <= 6.\n            Reducible.\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[6]<=3 T[8]<=4 T[9]<=4\n                   T[5,7]<=6 [].\n          Pcase: s[4] > 6.\n            Hubcap T[3]<=3 T[6]<=3 T[7]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[4,5]<=6 [].\n          Pcase: s[5] > 6.\n            Hubcap T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=2 T[7]<=2 T[8]<=4 T[9]<=4\n                   T[1,2]<=8 [].\n          Pcase: h[4] > 6.\n            Hubcap T[6]<=3 T[8]<=4 T[9]<=4 T[1,3]<=7 T[2,4]<=6 T[5,7]<=6 [].\n          Pcase: h[5] > 6.\n            Hubcap T[3]<=4 T[4]<=2 T[6]<=3 T[8]<=4 T[9]<=4 T[1,2]<=8 T[5,7]<=5 [].\n          Pcase: h[6] > 5.\n            Hubcap T[6]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=7 T[5,7]<=5 [].\n          Pcase: f1[5] <= 5.\n            Reducible.\n          Pcase: f1[5] <= 6.\n            Hubcap T[6]<=3 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=7 T[5,7]<=4 [].\n          Pcase: s[3] > 6.\n            Pcase: s[4] > 5.\n              Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=1 T[5]<=4 T[6]<=3 T[7]<=2\n                     T[8]<=4 T[9]<=4 [].\n            Pcase: s[7] <= 7.\n              Hubcap T[1]<=5 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4\n                     T[2,3]<=6 [].\n            Pcase: h[2] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=1\n                     T[8]<=4 T[9]<=4 [].\n            Hubcap T[1]<=5 T[2]<=3 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=4 T[9]<=4\n                   T[3,4]<=5 [].\n          Pcase: s[4] <= 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=1 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: s[7] > 7.\n            Hubcap T[5]<=4 T[6]<=3 T[7]<=1 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=6 [].\n          Hubcap T[6]<=3 T[7]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[1,3]<=8 T[2,5]<=7\n                 T[3,4]<=6 T[4,5]<=6 [].\n        Pcase: s[3] > 7.\n          Hubcap T[2]<=3 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,3]<=6 T[6,7]<=6 [].\n        Pcase: s[4] > 6.\n          Hubcap T[5]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=6 T[6,7]<=6 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=4 T[7]<=0 T[8]<=4 T[9]<=4 T[5,6]<=5\n                 [].\n        Pcase: s[5] > 6.\n          Pcase: s[3] > 6.\n            Hubcap T[2]<=3 T[4]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[1,3]<=8 T[6,7]<=5 [].\n          Pcase: s[4] > 5.\n            Hubcap T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=5 T[6,7]<=5 [].\n          Hubcap T[3]<=4 T[4]<=2 T[7]<=4 T[8]<=4 T[9]<=4 T[1,2]<=8 T[5,6]<=4 [].\n        Pcase: s[7] > 6.\n          Hubcap T[8]<=4 T[9]<=4 T[2,5]<=7 T[6,7]<=4 T[1,3]<=8 T[1,4]<=8 T[3,4]<=7\n                 [].\n        Pcase: h[5] > 6.\n          Hubcap T[3]<=4 T[4]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[5,6]<=5 T[5,7]<=6\n                 T[6,7]<=6 [].\n        Pcase: h[6] > 6.\n          Hubcap T[6]<=2 T[7]<=3 T[8]<=4 T[9]<=4 T[3,4]<=7 T[1,2]<=8 T[1,5]<=7\n                 T[2,5]<=6 [].\n        Pcase: f1[5] <= 5.\n          Hubcap T[5]<=1 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=7 T[6,7]<=6 [].\n        Pcase: h[2] > 5.\n          Pcase: s[3] <= 6.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=5 T[6,7]<=6 [].\n          Pcase: s[4] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: s[6] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[2] <= 6.\n            Hubcap T[2]<=2 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,3]<=7 T[6,7]<=6 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: f1[6] <= 5.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=2 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5\n                 [].\n        Pcase: s[6] > 6.\n          Hubcap T[5]<=2 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=6 T[6,7]<=6 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: s[3] <= 6.\n          Hubcap T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=8 T[3,4]<=6 T[6,7]<=5 [].\n        Pcase: s[4] > 5.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=1 T[5]<=3 T[6]<=2 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Hubcap T[2]<=3 T[4]<=3 T[7]<=4 T[8]<=4 T[9]<=4 T[1,3]<=7 T[5,6]<=5 [].\n      Pcase: s[3] > 8.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[7]<=5 T[8]<=4 T[9]<=4 T[5,6]<=8\n               [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[7]<=5 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[5] > 8.\n        Hubcap T[2]<=3 T[4]<=3 T[5]<=0 T[6]<=3 T[7]<=5 T[8]<=4 T[9]<=4 T[1,3]<=8\n               [].\n      Pcase: s[4] > 5.\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=2 T[5]<=4 T[6]<=4 T[7]<=5 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[5] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=0 T[6]<=3 T[7]<=5 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[8]<=4 T[9]<=4 T[4,5]<=5 T[6,7]<=6 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[6]<=3 T[9]<=4 T[4,5]<=7 T[7,8]<=5 [].\n        Pcase L4_1: h[8] > 6.\n          Pcase: s[1] > 8.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=4\n                   T[4,5]<=7 [].\n          Pcase: s[3] > 6.\n            Hubcap T[2]<=2 T[3]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,6]<=7 T[4,5]<=5 [].\n          Pcase: s[5] > 6.\n            Hubcap T[2]<=3 T[5]<=4 T[7]<=4 T[8]<=4 T[9]<=4 T[1,6]<=6 T[3,4]<=5 [].\n          Pcase: s[6] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[8]<=4 T[9]<=4 T[4,5]<=6 T[6,7]<=5 [].\n          Pcase: s[7] <= 6.\n            Similar to *L3_1[2].\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[6]<=3 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[4,5]<=7 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[6]<=3 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[4,5]<=6 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=4 T[6]<=3 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[3,4]<=6 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[6]<=3 T[7]<=3 T[8]<=4 T[9]<=4\n                   T[4,5]<=7 [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[2]<=3 T[3]<=3 T[6]<=3 T[7]<=3 T[9]<=4 T[1,8]<=7 T[4,5]<=7 [].\n          Hubcap T[2]<=3 T[3]<=4 T[6]<=3 T[7]<=3 T[9]<=4 T[1,8]<=7 T[4,5]<=6 [].\n        Pcase: s[1] > 8.\n          Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[7]<=5 T[8]<=4 T[4,5]<=7 T[6,9]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[2]<=2 T[3]<=4 T[8]<=4 T[1,7]<=8 T[4,5]<=5 T[6,9]<=7 [].\n        Pcase: h[4] > 6.\n          Hubcap T[2]<=3 T[3]<=3 T[8]<=4 T[1,7]<=8 T[4,5]<=5 T[6,9]<=7 [].\n        Pcase: h[5] > 6.\n          Hubcap T[2]<=3 T[5]<=3 T[8]<=4 T[1,7]<=8 T[3,4]<=5 T[6,9]<=7 [].\n        Pcase: f1[3] <= 5.\n          Hubcap T[2]<=2 T[3]<=2 T[8]<=4 T[1,7]<=8 T[4,5]<=7 T[6,9]<=7 [].\n        Pcase: h[3] > 5.\n          Hubcap T[2]<=2 T[3]<=3 T[8]<=4 T[1,7]<=8 T[4,5]<=6 T[6,9]<=7 [].\n        Pcase: s[6] > 5.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=2 T[2]<=3 T[3]<=4 T[8]<=4 T[9]<=4 T[4,5]<=6 T[6,7]<=7 [].\n          Pcase: s[4] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[5]<=2 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=5 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=4 T[9]<=4 T[5,6]<=4 T[7,8]<=7 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=6 T[6,7]<=7 [].\n          Hubcap T[2]<=3 T[7]<=4 T[8]<=4 T[1,9]<=7 T[3,4]<=7 T[5,6]<=5 [].\n        Pcase: s[7] <= 6.\n          Similar to *L3_1[2].\n        Pcase: h[1] > 6.\n          Similar to *L4_1[2].\n        Pcase: s[4] > 6.\n          Hubcap T[2]<=3 T[3]<=3 T[6]<=3 T[8]<=4 T[9]<=4 T[1,7]<=7 T[4,5]<=6 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[6]<=2 T[7]<=4 T[8]<=4 T[9]<=4 T[4,5]<=5\n                 [].\n        Pcase: s[1] > 7.\n          Hubcap T[2]<=3 T[3]<=4 T[6]<=3 T[7]<=4 T[9]<=4 T[1,8]<=5 T[4,5]<=7 [].\n        Pcase: h[2] > 5.\n          Hubcap T[2]<=3 T[5]<=4 T[6]<=3 T[8]<=4 T[9]<=4 T[1,7]<=6 T[3,4]<=6 [].\n        Pcase: f1[1] <= 5.\n          Reducible.\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[2]<=3 T[3]<=4 T[6]<=2 T[8]<=4 T[9]<=4 T[1,7]<=7 T[4,5]<=6 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: h[4] > 5.\n          Hubcap T[2]<=3 T[3]<=3 T[6]<=3 T[1,8]<=7 T[4,5]<=7 T[7,9]<=7 [].\n        Hubcap T[2]<=3 T[3]<=4 T[6]<=3 T[1,8]<=7 T[4,5]<=6 T[7,9]<=7 [].\n      Pcase: h[9] <= 5.\n        Pcase: h[8] <= 5.\n          Reducible.\n        Pcase: h[1] <= 5.\n          Reducible.\n        Pcase: s[3] > 7.\n          Hubcap T[2]<=2 T[4]<=3 T[6]<=4 T[8]<=4 T[9]<=4 T[1,3]<=5 T[5,7]<=8 [].\n        Pcase: s[5] > 7.\n          Hubcap T[2]<=3 T[4]<=3 T[6]<=3 T[8]<=4 T[9]<=4 T[1,3]<=7 T[5,7]<=6 [].\n        Pcase: s[7] > 8.\n          Hubcap T[2]<=3 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=0 T[8]<=4 T[9]<=4 T[1,3]<=7\n                 [].\n        Pcase: s[1] > 8.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=5 T[8]<=4 T[9]<=4\n                   T[6,7]<=8 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=3 T[7]<=5 T[8]<=4 T[9]<=4\n                   T[5,6]<=6 [].\n          Pcase: s[6] > 5.\n            Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=4 T[6]<=3 T[8]<=4 T[9]<=4 T[5,7]<=7\n                 [].\n        Pcase: s[6] > 6.\n          Pcase: s[1] > 7.\n            Hubcap T[1]<=1 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: h[1] <= 6.\n            Reducible.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=2 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=3 T[6]<=2 T[7]<=2 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=1 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=3 T[8]<=4 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase L4_1: h[2] > 5.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[8]<=4 T[9]<=4 T[4,6]<=6 T[5,7]<=8 [].\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=1 T[2]<=3 T[4]<=3 T[8]<=4 T[9]<=4 T[3,6]<=7 T[5,7]<=8 [].\n          Pcase: s[6] > 5.\n            Hubcap T[3]<=5 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=3 T[6,7]<=6 [].\n          Hubcap T[3]<=5 T[4]<=4 T[6]<=3 T[8]<=4 T[9]<=4 T[1,2]<=3 T[5,7]<=7 [].\n        Pcase: s[7] > 7.\n          Hubcap T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=4 T[9]<=4 T[1,3]<=7 T[2,4]<=6 [].\n        Pcase: s[1] > 7.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=1 T[2]<=2 T[3]<=4 T[4]<=3 T[6]<=4 T[8]<=4 T[9]<=4\n                   T[5,7]<=8 [].\n          Pcase: s[6] > 5.\n            Hubcap T[1]<=1 T[2]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[3,4]<=8 T[6,7]<=6 [].\n          Pcase: s[7] <= 6.\n            Similar to *L3_1[2].\n          Pcase: h[7] > 5.\n            Similar to *L4_1[2].\n          Hubcap T[1]<=1 T[2]<=3 T[3]<=5 T[4]<=4 T[6]<=2 T[8]<=4 T[9]<=4 T[5,7]<=7\n                 [].\n        Pcase: s[5] > 6.\n          Hubcap T[2]<=2 T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=4 T[8]<=4 T[9]<=4 T[1,3]<=7\n                 [].\n        Pcase: s[6] > 5.\n          Pcase: s[3] > 6.\n            Hubcap T[2]<=2 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,3]<=7 T[6,7]<=6 [].\n          Pcase: h[3] <= 5.\n            Reducible.\n          Pcase: h[1] <= 6.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: h[7] <= 5.\n            Reducible.\n          Pcase: h[3] <= 6.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4\n                   T[6,7]<=6 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Pcase: f1[5] <= 5.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=4\n                   T[9]<=4 [].\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5\n                 [].\n        Pcase: s[7] <= 6.\n          Similar to *L3_1[2].\n        Pcase: h[7] > 5.\n          Similar to *L4_1[2].\n        Pcase: h[6] <= 5.\n          Reducible.\n        Pcase: h[8] <= 6.\n          Reducible.\n        Hubcap T[2]<=2 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3 T[8]<=4 T[9]<=4 T[1,3]<=7\n               [].\n      Pcase: s[6] > 6.\n        Hubcap T[3]<=5 T[4]<=4 T[9]<=3 T[1,2]<=6 T[5,6]<=6 T[7,8]<=6 [].\n      Pcase: s[7] > 7.\n        Hubcap T[3]<=5 T[5]<=5 T[6]<=3 T[8]<=3 T[9]<=3 T[1,2]<=6 T[4,7]<=5 [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[8]<=4 T[9]<=3 T[4,7]<=7 T[5,6]<=8 [].\n      Pcase L3_2: s[3] > 6.\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[8]<=4 T[9]<=3 T[4,7]<=7 T[5,6]<=8 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=2 T[7]<=5 T[8]<=4 T[9]<=3 T[5,6]<=6\n                 [].\n        Pcase: s[6] > 5.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n                 [].\n        Hubcap T[2]<=2 T[3]<=4 T[9]<=3 T[1,7]<=7 T[4,6]<=6 T[5,8]<=8 [].\n      Pcase: s[1] > 8.\n        Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=4 T[9]<=3 T[5,7]<=8 T[6,8]<=7 [].\n      Pcase: s[6] > 5.\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=5 T[5]<=4 T[9]<=3 T[4,8]<=7 T[6,7]<=6 [].\n        Pcase: s[5] > 6.\n          Hubcap T[3]<=5 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=3 T[1,2]<=6 T[6,7]<=5 [].\n        Pcase: s[7] > 6.\n          Hubcap T[3]<=5 T[4]<=4 T[5]<=4 T[8]<=3 T[9]<=3 T[1,2]<=6 T[6,7]<=5 [].\n        Pcase: h[8] <= 5.\n          Reducible.\n        Pcase: h[2] <= 6.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n                 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n                 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n                 [].\n        Pcase: f1[3] <= 6.\n          Reducible.\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=3\n                 T[9]<=3 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=3 T[8]<=3 T[9]<=3 T[6,7]<=6\n                 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=5\n               [].\n      Pcase: s[5] > 6.\n        Similar to *L3_2[2].\n      Pcase: s[7] <= 6.\n        Similar to *L3_1[2].\n      Pcase: s[1] > 7.\n        Hubcap T[2]<=3 T[3]<=5 T[5]<=5 T[8]<=3 T[9]<=3 T[1,4]<=5 T[6,7]<=6 [].\n      Pcase: h[4] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n               [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[5] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=3 T[9]<=3 T[6,7]<=6\n               [].\n      Pcase: f1[5] <= 5.\n        Reducible.\n      Pcase: h[9] <= 6.\n        Hubcap T[3]<=5 T[4]<=4 T[5]<=5 T[8]<=3 T[9]<=3 T[1,2]<=5 T[6,7]<=5 [].\n      Pcase L3_3: h[8] > 5.\n        Pcase: h[2] <= 6.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=5 T[8]<=3 T[9]<=3 T[6,7]<=5\n                 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=3 T[8]<=3\n                 T[9]<=3 [].\n        Pcase: f1[3] <= 6.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3 T[8]<=3\n                 T[9]<=3 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3\n               T[9]<=3 [].\n      Pcase: h[1] > 5.\n        Similar to *L3_3[2].\n      Reducible.\n    Pcase: s[6] <= 5.\n      Similar to *L2_3[2].\n    Pcase: s[4] <= 5.\n      Pcase: s[1] > 6.\n        Hubcap T[4]<=4 T[5]<=4 T[8]<=4 T[1,9]<=7 T[2,3]<=5 T[6,7]<=6 [].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6 [].\n      Pcase: s[5] > 6.\n        Hubcap T[3]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=5 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[7] > 6.\n        Hubcap T[3]<=4 T[4]<=4 T[9]<=4 T[1,2]<=6 T[5,6]<=5 T[7,8]<=7 [].\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6 [].\n      Pcase: h[3] > 6.\n        Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[6,7]<=6 [].\n      Pcase: h[4] > 5.\n        Hubcap T[3]<=3 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=6 [].\n      Pcase: f1[3] <= 5.\n        Reducible.\n      Pcase: h[5] > 5.\n        Hubcap T[1]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=6 [].\n      Pcase: f1[5] <= 5.\n        Reducible.\n      Pcase: h[6] > 6.\n        Hubcap T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[9]<=4 T[1,2]<=6 T[7,8]<=7 [].\n      Pcase: h[7] > 6.\n        Hubcap T[3]<=4 T[4]<=4 T[7]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[5,6]<=5 [].\n      Pcase: h[8] <= 5.\n        Hubcap T[1]<=2 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=2 T[8]<=4\n               T[9]<=4 [].\n      Pcase: h[9] > 5.\n        Hubcap T[1]<=3 T[4]<=4 T[8]<=3 T[2,3]<=7 T[5,6]<=7 T[7,9]<=6 [].\n      Pcase: h[1] <= 5.\n        Reducible.\n      Pcase: h[8] > 6.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=4 [].\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: h[1] > 6.\n        Hubcap T[1]<=2 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=6 T[6,7]<=6 [].\n      Pcase: f1[1] <= 5.\n        Reducible.\n      Pcase L3_1: h[2] <= 5.\n        Pcase: s[2] <= 6.\n          Reducible.\n        Pcase: f1[1] <= 6.\n          Reducible.\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: h[7] <= 5.\n          Reducible.\n        Pcase: f1[6] <= 5.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase: f1[3] <= 6.\n          Reducible.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=4\n                 T[9]<=4 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5\n               [].\n      Pcase: h[7] <= 5.\n        Similar to *L3_1[2].\n      Pcase: s[2] > 6.\n        Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=6\n               [].\n      Pcase: f1[2] <= 5.\n        Reducible.\n      Pcase: s[6] > 6.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[7]<=3 T[8]<=4 T[9]<=4 T[2,3]<=6\n               [].\n      Pcase: f1[6] <= 5.\n        Reducible.\n      Pcase L3_2: h[3] > 5.\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=4\n                 T[9]<=4 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5\n               [].\n      Pcase: h[6] > 5.\n        Similar to *L3_2[2].\n      Pcase: f1[3] <= 6.\n        Reducible.\n      Pcase: f1[5] <= 6.\n        Reducible.\n      Hubcap T[3]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[6,7]<=5 [].\n    Pcase: s[1] > 6.\n      Hubcap T[1]<=4 T[2]<=2 T[7]<=4 T[8]<=4 T[9]<=4 T[3,4]<=6 T[5,6]<=6 [].\n    Pcase: s[2] > 6.\n      Hubcap T[1]<=3 T[2]<=4 T[3]<=2 T[8]<=4 T[9]<=4 T[4,5]<=6 T[6,7]<=7 [].\n    Pcase: s[3] > 6.\n      Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=2 T[7]<=4 T[8]<=4 T[9]<=4 T[5,6]<=6 [].\n    Pcase: s[4] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[5]<=2 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=7 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=2 T[5]<=4 T[8]<=4 T[9]<=4 T[6,7]<=5 [].\n    Pcase: s[6] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=3 T[5]<=2 T[8]<=4 T[9]<=4 T[6,7]<=6 [].\n    Pcase: s[7] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=2 T[9]<=4 T[7,8]<=7 [].\n    Pcase: h[2] > 5.\n      Hubcap T[3]<=3 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[1,2]<=6 T[6,7]<=7 [].\n    Pcase: h[3] > 5.\n      Hubcap T[1]<=4 T[4]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=7 [].\n    Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[8]<=4 T[9]<=4 T[3,4]<=5 T[6,7]<=7 [].\n  Pcase: s[1] <= 5.\n    Similar to L1_1[1].\n  Pcase L1_2: s[6] <= 5.\n    Pcase: s[5] <= 5.\n      Similar to L1_1[6].\n    Pcase: s[7] <= 5.\n      Similar to L1_1[7].\n    Pcase: s[3] <= 5.\n      Pcase: s[2] <= 5.\n        Similar to L1_1[3].\n      Pcase: s[4] <= 5.\n        Similar to L1_1[4].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=3 [].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=0 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[5] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=0 T[6]<=3 T[7]<=4 T[8]<=4\n               T[9]<=4 [].\n      Pcase: s[7] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=0 T[8]<=3\n               T[9]<=4 [].\n      Pcase: s[8] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=3 T[8]<=0\n               T[9]<=3 [].\n      Pcase L3_1: h[3] > 6.\n        Pcase: s[1] > 6.\n          Hubcap T[1]<=4 T[2]<=1 T[3]<=3 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3 T[4,5]<=7\n                 [].\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=3 T[7]<=4 T[8]<=4 T[1,2]<=5 T[4,5]<=7 T[6,9]<=7 [].\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=2 T[7]<=4 T[8]<=4 T[4,5]<=6 T[6,9]<=7 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[6]<=3 T[7]<=4 T[8]<=4 T[9]<=4 T[4,5]<=5\n                 [].\n        Hubcap T[3]<=3 T[1,2]<=6 T[4,5]<=7 T[6,9]<=7 T[7,8]<=7 [].\n      Pcase: h[4] > 6.\n        Similar to *L3_1[4].\n      Pcase: h[6] > 6.\n        Similar to L3_1[3].\n      Pcase: h[7] > 6.\n        Similar to *L3_1[1].\n      Pcase: h[9] > 6.\n        Similar to L3_1[6].\n      Pcase: h[1] > 6.\n        Similar to *L3_1[7].\n      Pcase L3_2: s[1] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3 T[1,2]<=4\n                 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: s[4] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=3 [].\n        Pcase: f1[4] <= 5.\n          Reducible.\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=4\n                 T[9]<=3 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: s[7] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=3 T[7]<=3 T[8]<=3\n                 T[9]<=3 [].\n        Pcase: f1[7] <= 5.\n          Reducible.\n        Pcase: s[8] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=3 T[8]<=3\n                 T[9]<=2 [].\n        Pcase: f1[8] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[7]<=4 T[8]<=4 T[9]<=3 T[1,2]<=5 T[3,6]<=7 T[4,5]<=7 [].\n        Pcase: f1[2] <= 6.\n          Reducible.\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3 T[4,5]<=7\n                 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=4 T[6]<=3 T[9]<=3 T[4,5]<=7 T[7,8]<=7 [].\n      Pcase: s[2] > 6.\n        Similar to *L3_2[7].\n      Pcase: s[4] > 6.\n        Similar to L3_2[3].\n      Pcase: s[5] > 6.\n        Similar to *L3_2[4].\n      Pcase: s[7] > 6.\n        Similar to L3_2[6].\n      Pcase: s[8] > 6.\n        Similar to *L3_2[1].\n      Pcase: f1[1] <= 5.\n        Reducible.\n      Pcase: f1[2] <= 5.\n        Reducible.\n      Pcase: f1[4] <= 5.\n        Reducible.\n      Pcase: f1[5] <= 5.\n        Reducible.\n      Pcase: f1[7] <= 5.\n        Reducible.\n      Pcase: f1[8] <= 5.\n        Reducible.\n      Pcase: h[2] > 6.\n        Hubcap T[1]<=3 T[2,6]<=6 T[3,7]<=7 T[4,8]<=7 T[5,9]<=7 [].\n      Pcase: h[3] > 5.\n        Hubcap T[3]<=3 T[5]<=4 T[6]<=4 T[1,2]<=6 T[4,9]<=6 T[7,8]<=7 [].\n      Hubcap T[3]<=4 T[4]<=4 T[6]<=3 T[1,2]<=7 T[5,9]<=6 T[7,8]<=6 [].\n    Pcase L2_1: s[4] <= 5.\n      Pcase: s[1] > 8.\n        Hubcap T[1]<=0 T[2]<=3 T[3]<=5 T[4]<=4 T[9]<=3 T[5,7]<=8 T[6,8]<=7 [].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=5 T[8]<=4 T[9]<=4 T[6,7]<=7\n               [].\n      Pcase: s[3] > 8.\n        Hubcap T[1]<=5 T[2]<=3 T[3]<=0 T[4]<=3 T[9]<=4 T[5,7]<=8 T[6,8]<=7 [].\n      Pcase: s[5] > 8.\n        Hubcap T[2]<=4 T[4]<=3 T[5]<=0 T[6]<=3 T[7]<=4 T[1,8]<=8 T[3,9]<=8 [].\n      Pcase: s[2] > 5.\n        Pcase: s[1] > 7.\n          Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=4 T[5]<=5 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=3 [].\n        Pcase: s[3] > 7.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[5]<=5 T[6]<=4 T[7]<=4 T[8]<=4\n                 T[9]<=4 [].\n        Pcase: s[7] > 7.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=0 T[8]<=3 T[9]<=4 T[2,3]<=7\n                 [].\n        Pcase: s[8] > 7.\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[5]<=5 T[7]<=3 T[8]<=0 T[9]<=3 T[4,6]<=7\n                 [].\n        Pcase: s[5] > 6.\n          Pcase: s[1] > 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=4 T[9]<=3\n                   T[2,3]<=5 [].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=4 T[9]<=4\n                   T[2,3]<=5 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[6]<=2 T[9]<=4 T[2,3]<=7 T[7,8]<=6 [].\n          Pcase: s[8] > 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[6]<=3 T[9]<=3 T[2,3]<=7 T[7,8]<=6 [].\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=4 T[9]<=4\n                   T[2,3]<=6 [].\n          Pcase: s[5] > 7.\n            Pcase: h[2] > 5.\n              Hubcap T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=4 T[8]<=4 T[1,9]<=7 T[2,3]<=7\n                     [].\n            Pcase: h[3] > 5.\n              Hubcap T[1]<=4 T[4]<=3 T[6]<=3 T[7]<=4 T[8]<=4 T[2,9]<=7 T[3,5]<=5\n                     [].\n            Pcase: f1[2] <= 6.\n              Reducible.\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=2 T[6]<=3 T[7]<=4\n                     T[8]<=4 T[9]<=4 [].\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=3 T[7]<=4 T[8]<=4 T[9]<=4\n                   T[5,6]<=4 [].\n          Pcase: h[6] <= 5.\n            Reducible.\n          Pcase: h[2] > 5.\n            Hubcap T[4]<=3 T[5]<=3 T[6]<=3 T[1,9]<=7 T[2,3]<=7 T[7,8]<=7 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[4]<=3 T[6]<=3 T[2,9]<=7 T[3,5]<=6 T[7,8]<=7 [].\n          Pcase: f1[2] <= 6.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=2 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=4\n                   T[9]<=4 [].\n          Hubcap T[1]<=4 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[2,9]<=6 T[7,8]<=7 [].\n        Pcase: s[1] > 6.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=5 T[2,3]<=5 T[6,9]<=6 T[7,8]<=6 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[4]<=3 T[5]<=5 T[2,3]<=5 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=3 T[4]<=4 T[5]<=5 T[2,3]<=5 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: h[3] > 6.\n          Hubcap T[3]<=3 T[4]<=4 T[5]<=5 T[1,2]<=5 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: h[5] > 5.\n          Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[2,3]<=6 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: h[9] > 5.\n          Hubcap T[3]<=4 T[5]<=5 T[9]<=3 T[1,2]<=6 T[4,6]<=7 T[7,8]<=5 [].\n        Pcase: h[4] > 6.\n          Hubcap T[4]<=3 T[5]<=5 T[6,9]<=7 T[7,8]<=6 T[1,2]<=7 T[1,3]<=6 T[2,3]<=6\n                 [].\n        Pcase: f1[3] <= 5.\n          Reducible.\n        Pcase: h[4] > 5.\n          Hubcap T[3]<=3 T[4]<=3 T[5]<=5 T[1,2]<=6 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: s[8] > 6.\n          Pcase: s[2] > 6.\n            Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=5 T[6]<=3 T[9]<=3\n                   T[7,8]<=5 [].\n          Pcase: f1[2] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[4]<=4 T[5]<=5 T[6]<=3 T[9]<=3 T[2,3]<=7 T[7,8]<=4 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=3 T[4]<=4 T[5]<=5 T[6]<=3 T[9]<=3 T[2,3]<=7 T[7,8]<=5 [].\n          Pcase: f1[2] <= 6.\n            Reducible.\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[3]<=3 T[4]<=4 T[5]<=5 T[6]<=3 T[2,9]<=6 T[7,8]<=5 [].\n          Hubcap T[1]<=4 T[3]<=4 T[4]<=4 T[5]<=5 T[6]<=3 T[2,9]<=5 T[7,8]<=5 [].\n        Pcase: f1[8] <= 5.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[9]<=4 T[5,7]<=7 T[6,8]<=6 [].\n        Pcase: f1[2] <= 5.\n          Reducible.\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=3 T[4]<=4 T[9]<=3 T[2,3]<=7 T[5,7]<=7 T[6,8]<=6 [].\n        Pcase: f1[1] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Pcase: s[7] <= 6.\n            Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[6]<=2 T[9]<=4 T[2,3]<=7 T[7,8]<=6 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3 T[8]<=3 T[9]<=4\n                   T[2,3]<=7 [].\n          Hubcap T[1]<=3 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3 T[9]<=4 T[2,3]<=7\n                 [].\n        Pcase: f1[1] <= 6.\n          Reducible.\n        Pcase: f1[2] <= 6.\n          Reducible.\n        Pcase: s[7] <= 6.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=2 T[9]<=4 T[2,3]<=6 T[7,8]<=6 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=2 T[7]<=3 T[8]<=3 T[9]<=4 T[2,3]<=6\n                 [].\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3 T[9]<=4 T[2,3]<=6\n               [].\n      Pcase: s[7] > 7.\n        Hubcap T[6]<=3 T[7]<=0 T[8]<=3 T[1,4]<=8 T[2,5]<=8 T[3,9]<=8 [].\n      Pcase: s[8] > 7.\n        Hubcap T[1]<=5 T[8]<=0 T[9]<=3 T[2,5]<=8 T[3,6]<=8 T[4,7]<=6 [].\n      Pcase L3_1: s[1] <= 6.\n        Pcase: f1[1] <= 5.\n          Hubcap T[1]<=2 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=5 T[6,9]<=6 T[7,8]<=6 [].\n        Pcase: f1[1] <= 6.\n          Pcase: s[3] > 7.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=5 T[6,9]<=7 T[7,8]<=6 [].\n          Pcase: s[5] > 7.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6,9]<=6 T[7,8]<=6 [].\n          Pcase: h[3] > 5.\n            Hubcap T[4]<=3 T[1,2]<=6 T[3,5]<=8 T[6,9]<=7 T[7,8]<=6 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=4 T[2,9]<=6 T[3,5]<=8 T[4,6]<=6 T[7,8]<=6 [].\n          Pcase: s[3] > 6.\n            Pcase: s[5] > 6.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[9]<=4\n                     T[7,8]<=6 [].\n            Pcase: f1[5] <= 5.\n              Reducible.\n            Pcase: s[7] <= 6.\n              Hubcap T[1]<=4 T[4]<=3 T[5]<=5 T[2,9]<=5 T[3,6]<=7 T[7,8]<=6 [].\n            Pcase: s[8] > 6.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=3\n                     T[7,8]<=4 [].\n            Pcase: h[2] <= 6.\n              Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=3\n                     T[7,8]<=5 [].\n            Pcase: h[4] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=4\n                     T[7,8]<=6 [].\n            Pcase: f1[3] <= 5.\n              Reducible.\n            Pcase: h[6] > 5.\n              Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=4\n                     T[8]<=3 T[9]<=4 [].\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3\n                   T[9]<=4 [].\n          Pcase: s[5] <= 6.\n            Reducible.\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=2 T[9]<=3\n                   T[7,8]<=5 [].\n          Pcase: s[8] <= 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[9]<=2\n                   T[7,8]<=6 [].\n          Pcase: h[2] <= 6.\n            Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[6]<=3 T[9]<=2 T[2,3]<=8 T[7,8]<=6 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=3 T[8]<=4\n                   T[9]<=3 [].\n          Pcase: f1[3] <= 6.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=2 T[8]<=4\n                   T[9]<=3 [].\n          Pcase: f2[5] <= 5.\n            Reducible.\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=2 T[8]<=4\n                   T[9]<=3 [].\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=3 T[8,9]<=5\n                 [].\n        Pcase: s[3] > 7.\n          Pcase: s[5] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=4\n                   T[8,9]<=7 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=3 T[5]<=5 T[6]<=4 T[9]<=4\n                   T[7,8]<=6 [].\n          Hubcap T[1]<=5 T[2]<=3 T[5]<=5 T[3,4]<=4 T[6,9]<=7 T[7,8]<=6 [].\n        Pcase: s[5] > 7.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=2 T[6]<=3 T[7]<=4\n                   T[8,9]<=7 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=2 T[9]<=3\n                   T[7,8]<=5 [].\n          Pcase: s[8] <= 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=4 T[8]<=3\n                   T[9]<=2 [].\n          Pcase: h[2] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=3 T[8]<=4\n                   T[9]<=3 [].\n          Hubcap T[1]<=5 T[2]<=4 T[4]<=3 T[6]<=3 T[7]<=3 T[3,5]<=6 T[8,9]<=6 [].\n        Pcase L4_1: h[2] > 5.\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=4 T[2]<=2 T[4]<=3 T[3,5]<=8 T[6,9]<=7 T[7,8]<=6 [].\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=4 T[2,4]<=5 T[3,5]<=8 T[6,9]<=7 T[7,8]<=6 [].\n          Pcase: h[5] > 5.\n            Hubcap T[1]<=4 T[3]<=4 T[5]<=4 T[2,6]<=6 T[4,9]<=6 T[7,8]<=6 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[4]<=3 T[3,5]<=8 T[6,9]<=6 T[7,8]<=6 [].\n          Pcase: s[5] <= 6.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=2\n                   T[8,9]<=7 [].\n          Pcase: f2[5] <= 5.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[5]<=4 T[6]<=2 T[4,9]<=6 T[7,8]<=6 [].\n          Pcase: s[8] <= 6.\n            Reducible.\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=3 T[8]<=4\n                   T[9]<=3 [].\n          Pcase: f1[3] <= 6.\n            Reducible.\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=2 T[8]<=4\n                   T[9]<=3 [].\n          Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=3 T[7]<=3 T[8,9]<=5\n                 [].\n        Pcase: h[5] > 5.\n          Pcase: s[5] <= 6.\n            Similar to *L4_1[4].\n          Pcase: s[3] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[9]<=4\n                   T[7,8]<=6 [].\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=2 T[9]<=3\n                   T[7,8]<=5 [].\n          Pcase: s[8] <= 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=4 T[8]<=3\n                   T[9]<=2 [].\n          Pcase: h[3] > 5.\n            Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=3\n                   T[8,9]<=6 [].\n          Pcase: f1[3] <= 5.\n            Reducible.\n          Pcase: h[4] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=2 T[5]<=3 T[6]<=3 T[7]<=3\n                   T[8,9]<=6 [].\n          Pcase: f1[3] <= 6.\n            Reducible.\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=2\n                   T[8,9]<=6 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=2 T[7]<=2\n                   T[8,9]<=6 [].\n          Pcase: f1[7] <= 5.\n            Reducible.\n          Pcase: h[5] <= 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=2 T[6]<=3 T[7]<=3\n                   T[8,9]<=5 [].\n          Pcase: h[8] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=3\n                   T[8,9]<=4 [].\n          Hubcap T[1]<=4 T[2]<=4 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=3\n                 T[9]<=2 [].\n        Pcase: s[3] <= 6.\n          Pcase: s[5] <= 6.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=4 T[6]<=2 T[9]<=3\n                   T[7,8]<=5 [].\n          Pcase: s[8] <= 6.\n            Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=3\n                   T[9]<=2 [].\n          Pcase: h[6] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=2\n                   T[8,9]<=6 [].\n          Pcase: h[7] > 5.\n            Hubcap T[1]<=5 T[2]<=4 T[3]<=4 T[4]<=3 T[5]<=4 T[6]<=2 T[7]<=2\n                   T[8,9]<=6 [].\n          Hubcap T[1]<=5 T[3]<=4 T[5]<=4 T[6]<=3 T[7]<=3 T[2,4]<=6 T[8,9]<=5 [].\n        Pcase: s[5] > 6.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=2 T[5]<=4 T[6,9]<=6 T[7,8]<=6 [].\n        Pcase: f1[5] <= 5.\n          Reducible.\n        Pcase: f1[5] <= 6.\n          Pcase: h[6] <= 6.\n            Reducible.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[4]<=3 T[5]<=4 T[6]<=2 T[3,9]<=7 T[7,8]<=6 [].\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=4 T[6]<=3 T[9]<=3 T[7,8]<=5\n                 [].\n        Pcase L4_2: h[6] > 5.\n          Pcase: s[7] > 6.\n            Hubcap T[1]<=5 T[2]<=3 T[4]<=3 T[5]<=4 T[6]<=2 T[3,9]<=7 T[7,8]<=6 [].\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=4 T[4]<=3 T[5]<=4 T[6]<=3 T[9]<=3 T[7,8]<=5\n                 [].\n        Pcase: h[1] > 5.\n          Similar to *L4_2[4].\n        Pcase: h[3] <= 5.\n          Hubcap T[1]<=5 T[2]<=3 T[4]<=3 T[5]<=5 T[9]<=3 T[3,6]<=7 T[7,8]<=4 [].\n        Pcase: s[7] <= 6.\n          Hubcap T[1]<=5 T[2]<=3 T[4]<=3 T[5]<=5 T[9]<=3 T[3,6]<=6 T[7,8]<=5 [].\n        Pcase: s[8] > 6.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=3 T[7,8]<=4\n                 [].\n        Pcase: h[8] <= 5.\n          Reducible.\n        Pcase: h[3] <= 6.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=4 T[7,8]<=5\n                 [].\n        Pcase: h[4] > 5.\n          Hubcap T[1]<=5 T[2]<=3 T[3]<=2 T[4]<=3 T[5]<=5 T[6]<=3 T[9]<=4 T[7,8]<=5\n                 [].\n        Hubcap T[1]<=5 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=5 T[6]<=3 T[7]<=1 T[8]<=3\n               T[9]<=4 [].\n      Pcase: s[5] <= 6.\n        Similar to *L3_1[4].\n      Pcase: s[3] > 6.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[4]<=2 T[5]<=4 T[6]<=3 T[7]<=4 T[8]<=4\n               T[9]<=3 [].\n      Pcase: s[7] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=2 T[9]<=3 T[7,8]<=6\n               [].\n      Pcase: s[8] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=4 T[6]<=3 T[9]<=2 T[7,8]<=6\n               [].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=2 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[7]<=4 T[8]<=4\n               T[9]<=3 [].\n      Hubcap T[1]<=3 T[2]<=3 T[3]<=5 T[4]<=3 T[5]<=3 T[6]<=3 T[9]<=3 T[7,8]<=7 [].\n    Pcase: s[2] <= 5.\n      Similar to *L2_1[4].\n    Pcase: s[1] > 6.\n      Hubcap T[1]<=4 T[6]<=4 T[7]<=4 T[8]<=4 T[9]<=3 T[2,3]<=4 T[4,5]<=7 [].\n    Pcase: s[2] > 6.\n      Hubcap T[3]<=2 T[7]<=4 T[8]<=4 T[1,2]<=6 T[4,5]<=7 T[6,9]<=7 [].\n    Pcase: s[3] > 6.\n      Hubcap T[1]<=4 T[2]<=2 T[3]<=4 T[7]<=4 T[8]<=4 T[4,5]<=5 T[6,9]<=7 [].\n    Pcase: s[4] > 6.\n      Hubcap T[1]<=4 T[7]<=4 T[8]<=4 T[2,3]<=5 T[4,5]<=6 T[6,9]<=7 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=4 T[6]<=3 T[7]<=4 T[8]<=4 T[9]<=4 T[2,3]<=6 T[4,5]<=5 [].\n    Pcase: s[7] > 6.\n      Hubcap T[1]<=4 T[6]<=3 T[9]<=4 T[2,3]<=6 T[4,5]<=7 T[7,8]<=6 [].\n    Pcase: s[8] > 6.\n      Hubcap T[1]<=4 T[6]<=4 T[9]<=3 T[2,3]<=6 T[4,5]<=7 T[7,8]<=6 [].\n    Hubcap T[3,4]<=6 T[6,9]<=7 T[7,8]<=7 T[1,2]<=7 T[1,5]<=7 T[2,5]<=7 [].\n  Pcase: s[3] <= 5.\n    Similar to L1_2[3].\n  Pcase L1_3: s[7] <= 5.\n    Pcase: s[4] <= 5.\n      Similar to L1_2[7].\n    Pcase L2_1: s[5] <= 5.\n      Pcase: s[2] <= 5.\n        Similar to L1_2[5].\n      Pcase: s[1] > 7.\n        Hubcap T[1]<=0 T[2]<=2 T[3]<=4 T[4]<=4 T[6]<=5 T[8]<=5 T[9]<=3 T[5,7]<=7\n               [].\n      Pcase: s[2] > 7.\n        Hubcap T[1]<=3 T[2]<=0 T[3]<=2 T[4]<=4 T[5]<=4 T[6]<=5 T[8]<=5 T[7,9]<=7\n               [].\n      Pcase: s[3] > 7.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=0 T[4]<=3 T[5]<=4 T[6]<=5 T[8]<=5 T[7,9]<=7\n               [].\n      Pcase: s[4] > 7.\n        Hubcap T[1]<=4 T[2]<=4 T[3]<=2 T[4]<=0 T[5]<=3 T[6]<=5 T[8]<=5 T[7,9]<=7\n               [].\n      Pcase: s[6] > 8.\n        Hubcap T[1]<=4 T[2]<=4 T[5]<=3 T[6]<=0 T[7]<=3 T[8]<=5 T[9]<=4 T[3,4]<=7\n               [].\n      Pcase: s[8] > 8.\n        Hubcap T[1]<=4 T[2]<=4 T[5]<=4 T[6]<=5 T[7]<=3 T[8]<=0 T[9]<=3 T[3,4]<=7\n               [].\n      Pcase L3_1: s[1] > 6.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[6]<=5 T[8]<=5 T[9]<=3 T[3,4]<=5 T[5,7]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=0 T[6]<=5 T[8]<=5 T[9]<=3 T[3,4]<=6 T[5,7]<=7 [].\n        Pcase: s[4] > 6.\n          Hubcap T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[1,2]<=5 T[3,4]<=5 [].\n        Pcase: s[6] > 6.\n          Hubcap T[5]<=3 T[6]<=4 T[7]<=3 T[8]<=5 T[9]<=3 T[1,2]<=5 T[3,4]<=7 [].\n        Pcase: s[8] > 6.\n          Hubcap T[5]<=4 T[6]<=5 T[7]<=3 T[8]<=4 T[9]<=2 T[1,2]<=5 T[3,4]<=7 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=3 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[2,3]<=4\n                 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=4 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[2,3]<=3\n                 [].\n        Hubcap T[1]<=3 T[2]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[3,4]<=5\n               [].\n      Pcase: s[4] > 6.\n        Similar to *L3_1[5].\n      Pcase: h[3] > 6.\n        Hubcap T[3]<=2 T[1,2]<=5 T[4,7]<=7 T[5,8]<=8 T[6,9]<=8 [].\n      Pcase: f1[1] <= 5.\n        Pcase: h[1] <= 6.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[1]<=1 T[2]<=3 T[3]<=2 T[4]<=4 T[6]<=5 T[8]<=5 T[9]<=3 T[5,7]<=7\n                 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=2 T[2]<=2 T[3]<=4 T[6]<=5 T[9]<=3 T[4,7]<=6 T[5,8]<=8 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[5]<=3 T[6]<=4 T[7]<=3 T[8]<=5 T[9]<=3 T[3,4]<=7\n                 [].\n        Pcase: s[8] > 6.\n          Hubcap T[1]<=2 T[2]<=3 T[5]<=4 T[6]<=5 T[7]<=3 T[8]<=4 T[9]<=2 T[3,4]<=7\n                 [].\n        Pcase: h[5] <= 5.\n          Reducible.\n        Pcase: h[2] > 5.\n          Hubcap T[1]<=1 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5\n                 T[9]<=3 [].\n        Hubcap T[1]<=2 T[2]<=3 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[3,4]<=5\n               [].\n      Pcase: f1[4] <= 5.\n        Pcase: h[5] <= 6.\n          Reducible.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=2 T[4]<=2 T[5]<=3 T[6]<=5 T[8]<=5 T[1,2]<=6 T[7,9]<=7 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=1 T[5]<=3 T[6]<=5 T[8]<=5 T[7,9]<=7\n                 [].\n        Pcase: s[6] > 6.\n          Hubcap T[1]<=4 T[4]<=2 T[5]<=2 T[6]<=4 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase: s[8] > 6.\n          Hubcap T[1]<=4 T[4]<=2 T[5]<=3 T[6]<=5 T[7]<=3 T[8]<=4 T[9]<=3 T[2,3]<=6\n                 [].\n        Hubcap T[1]<=3 T[4]<=2 T[5]<=3 T[6]<=5 T[7]<=4 T[8]<=5 T[9]<=3 T[2,3]<=5\n               [].\n      Pcase: f1[1] <= 6.\n        Pcase: s[2] > 6.\n          Hubcap T[3]<=2 T[1,2]<=5 T[4,7]<=7 T[5,8]<=8 T[6,9]<=8 [].\n        Pcase: s[3] > 6.\n          Hubcap T[1]<=3 T[2,7]<=5 T[3,4]<=6 T[5,8]<=8 T[6,9]<=8 [].\n        Pcase: s[6] > 7.\n          Hubcap T[1]<=3 T[4]<=4 T[5]<=3 T[6]<=2 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=6\n                 [].\n        Pcase: s[8] > 7.\n          Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[6]<=5 T[7]<=3 T[8]<=2 T[9]<=3 T[2,3]<=6\n                 [].\n        Pcase: h[3] > 5.\n          Hubcap T[1]<=3 T[2,3]<=4 T[4,7]<=7 T[5,8]<=8 T[6,9]<=8 [].\n        Pcase: h[2] <= 5.\n          Hubcap T[1]<=2 T[6]<=5 T[9]<=3 T[2,3]<=5 T[4,7]<=7 T[5,8]<=8 [].\n        Pcase: h[4] > 6.\n          Hubcap T[1]<=3 T[2,3]<=5 T[4,7]<=6 T[5,8]<=8 T[6,9]<=8 [].\n        Pcase: h[9] > 5.\n          Hubcap T[6]<=5 T[1,9]<=5 T[2,3]<=6 T[4,7]<=7 T[5,8]<=7 [].\n        Pcase: h[1] > 6.\n          Hubcap T[6]<=5 T[9]<=3 T[1,2]<=4 T[5,8]<=8 T[3,4]<=7 T[3,7]<=7 T[4,7]<=7\n                 [].\n        Pcase: h[5] > 5.\n          Hubcap T[4]<=3 T[5]<=3 T[8]<=5 T[1,7]<=6 T[2,3]<=5 T[6,9]<=8 [].\n        Pcase: h[1] > 5.\n          Hubcap T[1]<=2 T[4]<=4 T[5]<=4 T[7]<=3 T[9]<=3 T[2,3]<=5 T[6,8]<=9 [].\n        Pcase: h[2] > 6.\n          Hubcap T[1]<=3 T[2]<=2 T[7]<=3 T[3,4]<=7 T[5,9]<=7 T[6,8]<=8 [].\n        Pcase: f1[2] <= 6.\n          Reducible.\n        Pcase: s[6] <= 6.\n          Hubcap T[1]<=3 T[7]<=3 T[9]<=3 T[2,5]<=7 T[3,4]<=6 T[6,8]<=8 [].\n        Pcase: s[8] > 6.\n          Hubcap T[1]<=3 T[2]<=4 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=4 T[7]<=2 T[8]<=4\n                 T[9]<=3 [].\n        Pcase: f1[8] <= 5.\n          Reducible.\n        Pcase: h[4] <= 5.\n          Hubcap T[1]<=3 T[2]<=3 T[3]<=2 T[4]<=4 T[5]<=3 T[8]<=5 T[9]<=4 T[6,7]<=6\n                 [].\n        Pcase: h[6] > 5.\n          Hubcap T[1]<=3 T[2]<=4 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[3,4]<=5\n                 [].\n        Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=3 T[5]<=3 T[8]<=5 T[9]<=4 T[6,7]<=6\n               [].\n      Pcase: s[3] > 6.\n        Hubcap T[5,8]<=8 T[6,9]<=8 T[1,2]<=5 T[1,7]<=7 T[2,3]<=5 T[3,4]<=6\n               T[4,7]<=6 [].\n      Pcase: s[2] > 6.\n        Hubcap T[1,2]<=6 T[5,8]<=8 T[6,9]<=8 T[3,4]<=5 T[3,7]<=5 T[4,7]<=7 [].\n      Pcase: s[6] > 7.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[6]<=2 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=5\n               [].\n      Pcase: s[8] > 7.\n        Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[6]<=5 T[7]<=3 T[8]<=2 T[9]<=3 T[2,3]<=5\n               [].\n      Pcase: h[4] > 6.\n        Hubcap T[1]<=4 T[2,3]<=4 T[4,7]<=6 T[5,8]<=8 T[6,9]<=8 [].\n      Pcase: h[5] > 5.\n        Hubcap T[4]<=3 T[5]<=3 T[8]<=5 T[1,7]<=7 T[2,3]<=4 T[6,9]<=8 [].\n      Pcase: h[1] > 5.\n        Hubcap T[1]<=3 T[4]<=4 T[7]<=3 T[2,3]<=5 T[5,8]<=8 T[6,9]<=7 [].\n      Pcase: h[2] > 5.\n        Hubcap T[7]<=3 T[1,2]<=5 T[3,4]<=7 T[5,9]<=7 T[6,8]<=8 [].\n      Pcase: h[3] > 5.\n        Hubcap T[1]<=4 T[4]<=4 T[7]<=3 T[2,3]<=4 T[5,9]<=7 T[6,8]<=8 [].\n      Pcase: f1[2] <= 6.\n        Reducible.\n      Pcase: s[6] <= 6.\n        Hubcap T[1]<=4 T[7]<=3 T[9]<=3 T[2,5]<=6 T[3,4]<=6 T[6,8]<=8 [].\n      Pcase: s[8] > 6.\n        Hubcap T[1]<=4 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=3 T[6]<=4 T[7]<=2 T[8]<=4\n               T[9]<=3 [].\n      Pcase: h[4] <= 5.\n        Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=4 T[5]<=3 T[7]<=3 T[9]<=4 T[6,8]<=8\n               [].\n      Pcase: h[6] > 5.\n        Hubcap T[1]<=4 T[2]<=3 T[5]<=3 T[6]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[3,4]<=5\n               [].\n      Hubcap T[1]<=4 T[2]<=2 T[3]<=3 T[4]<=3 T[5]<=3 T[7]<=3 T[9]<=4 T[6,8]<=8 [].\n    Pcase: s[2] <= 5.\n      Similar to L2_1[2].\n    Pcase: s[1] > 6.\n      Hubcap T[1]<=4 T[6]<=4 T[7]<=4 T[8]<=5 T[9]<=3 T[2,3]<=4 T[4,5]<=6 [].\n    Pcase: s[2] > 6.\n      Hubcap T[1]<=3 T[2]<=4 T[8]<=5 T[3,4]<=4 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: s[3] > 6.\n      Hubcap T[3]<=4 T[4]<=2 T[8]<=5 T[1,2]<=5 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: s[4] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[8]<=5 T[2,3]<=5 T[5,6]<=5 T[7,9]<=7 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[8]<=5 T[3,4]<=4 T[5,6]<=6 T[7,9]<=7 [].\n    Pcase: s[6] > 6.\n      Hubcap T[1]<=4 T[4]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=6 T[5,6]<=5 [].\n    Pcase: s[8] > 6.\n      Hubcap T[1]<=4 T[4]<=3 T[7]<=3 T[8]<=4 T[9]<=3 T[2,3]<=6 T[5,6]<=7 [].\n    Pcase: h[2] > 6.\n      Hubcap T[1]<=3 T[2]<=2 T[3]<=3 T[4]<=3 T[8]<=5 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: h[3] > 6.\n      Hubcap T[1]<=4 T[2]<=2 T[3]<=2 T[4]<=3 T[8]<=5 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: h[4] > 6.\n      Hubcap T[1]<=4 T[4]<=2 T[8]<=5 T[2,3]<=5 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: h[5] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[4]<=2 T[8]<=5 T[5,6]<=5 T[7,9]<=7 [].\n    Pcase: h[6] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=3 T[6]<=3 T[8]<=5 T[4,5]<=4 T[7,9]<=7 [].\n    Pcase: h[7] > 6.\n      Hubcap T[1]<=4 T[4]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=6 T[5,6]<=5 [].\n    Pcase: f1[6] <= 5.\n      Reducible.\n    Pcase: h[7] > 5.\n      Hubcap T[1]<=4 T[6]<=3 T[7]<=3 T[8]<=5 T[9]<=4 T[2,3]<=6 T[4,5]<=5 [].\n    Pcase: h[3] > 5.\n      Hubcap T[4]<=3 T[1,8]<=8 T[2,3]<=5 T[5,6]<=7 T[7,9]<=7 [].\n    Pcase: h[2] <= 5.\n      Hubcap T[2]<=3 T[1,7]<=7 T[3,4]<=5 T[5,6]<=7 T[8,9]<=8 [].\n    Pcase: h[4] > 5.\n      Hubcap T[3,4]<=5 T[5,6]<=7 T[7,9]<=7 T[1,2]<=7 T[1,8]<=8 T[2,8]<=8 [].\n    Hubcap T[1]<=4 T[3]<=3 T[6]<=4 T[2,8]<=7 T[4,5]<=5 T[7,9]<=7 [].\n  Pcase: s[2] <= 5.\n    Similar to L1_3[2].\n  Pcase L1_4: s[4] <= 5.\n    Pcase: s[5] <= 5.\n      Similar to L1_1[5].\n    Pcase: s[1] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=3 T[2,3]<=5 T[6,7]<=6 [].\n    Pcase: s[2] > 7.\n      Hubcap T[1]<=3 T[2]<=0 T[3]<=3 T[4]<=4 T[5]<=4 T[6]<=4 T[7]<=4 T[8]<=4\n             T[9]<=4 [].\n    Pcase: s[3] > 6.\n      Hubcap T[1]<=4 T[4]<=3 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6 [].\n    Pcase: s[5] > 6.\n      Hubcap T[1]<=4 T[4]<=3 T[9]<=4 T[2,3]<=7 T[5,6]<=5 T[7,8]<=7 [].\n    Pcase: s[6] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[9]<=4 T[2,3]<=7 T[5,6]<=6 T[7,8]<=5 [].\n    Pcase: s[7] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[9]<=4 T[2,3]<=7 T[5,6]<=5 T[7,8]<=6 [].\n    Pcase: s[8] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[9]<=3 T[2,3]<=7 T[5,6]<=7 T[7,8]<=5 [].\n    Pcase: h[2] > 6.\n      Hubcap T[1]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[2,3]<=5 T[6,7]<=6 [].\n    Pcase: h[3] > 6.\n      Hubcap T[3]<=3 T[4]<=4 T[5]<=4 T[8]<=4 T[9]<=4 T[1,2]<=5 T[6,7]<=6 [].\n    Pcase: h[4] > 5.\n      Hubcap T[1]<=4 T[4]<=3 T[9]<=4 T[2,3]<=6 T[5,6]<=6 T[7,8]<=7 [].\n    Pcase: f1[3] <= 5.\n      Reducible.\n    Pcase: h[5] > 5.\n      Hubcap T[1]<=4 T[4]<=3 T[5]<=3 T[6]<=3 T[9]<=4 T[2,3]<=6 T[7,8]<=7 [].\n    Pcase: f1[5] <= 5.\n      Reducible.\n    Pcase: h[7] > 6.\n      Hubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4]<=4 T[9]<=4 T[5,6]<=5 T[7,8]<=5 [].\n    Pcase: h[8] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[8]<=3 T[9]<=4 T[2,3]<=7 T[5,6]<=7 T[5,7]<=5\n             T[6,7]<=5 [].\n    Pcase: h[6] > 6.\n      Hubcap T[1]<=4 T[4]<=4 T[5]<=3 T[2,3]<=7 T[6,9]<=5 T[7,8]<=7 [].\n    Pcase: f1[6] <= 5.\n      Reducible.\n    Pcase: s[2] > 6.\n      Hubcap T[1]<=3 T[2]<=3 T[3]<=3 T[4]<=4 T[5]<=4 T[6,9]<=7 T[7,8]<=6 [].\n    Pcase: f1[2] <= 5.\n      Reducible.\n    Pcase: h[9] > 5.\n      Hubcap T[1]<=3 T[2]<=4 T[3]<=4 T[4]<=4 T[9]<=3 T[5,6]<=7 T[7,8]<=5 [].\n    Pcase: f1[8] <= 5.\n      Reducible.\n    Pcase: h[1] > 5.\n      Hubcap T[1]<=3 T[2]<=4 T[3]<=4 T[4]<=4 T[9]<=3 T[5,6]<=7 T[7,8]<=5 [].\n    Pcase: f1[1] <= 5.\n      Reducible.\n    Pcase: f1[7] <= 5.\n      Reducible.\n    Pcase: h[2] > 5.\n      Hubcap T[1]<=3 T[4]<=4 T[9]<=4 T[2,3]<=7 T[5,6]<=6 T[7,8]<=6 [].\n    Hubcap T[1]<=4 T[4]<=4 T[9]<=4 T[2,3]<=6 T[5,6]<=6 T[7,8]<=6 [].\n  Pcase: s[5] <= 5.\n    Similar to L1_4[5].\n  Hubcap T[1]<=4 T[8]<=4 T[9]<=4 T[2,3]<=6 T[4,5]<=6 T[6,7]<=6 [].\nPcase: s[1] <= 5.\n  Similar to L0_1[1].\nPcase: s[2] <= 5.\n  Similar to L0_1[2].\nPcase: s[3] <= 5.\n  Similar to L0_1[3].\nPcase: s[4] <= 5.\n  Similar to L0_1[4].\nPcase: s[5] <= 5.\n  Similar to L0_1[5].\nPcase: s[6] <= 5.\n  Similar to L0_1[6].\nPcase: s[7] <= 5.\n  Similar to L0_1[7].\nPcase: s[8] <= 5.\n  Similar to L0_1[8].\nHubcap T[1]<=4 T[2]<=4 T[3]<=4 T[4,5]<=6 T[6,7]<=6 T[8,9]<=6 [].\nQed.\n", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/present9.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17912319732372245}}
{"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: MPTKern                                 *)\n(*                                                                     *)\n(*          initialize the page map of the kernel thread               *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the MPTKern layer, which will initialize kernel's page table ([0th page table])*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import AbstractDataType.\nRequire Export MPTCommon.\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Section PTINSERT.\n \n      Section PTINSERT_PTE.\n\n        Lemma ptInsertPTE_high_level_inv:\n          forall d d' n vadr padr p,\n            ptInsertPTE_spec n vadr padr p d = Some d' ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto. \n          inv H0; constructor_gso_simpl_tac.\n          - intros; eapply AT_kern_norm; eauto. \n          - intros; eapply AT_usr_norm; eauto.\n          - apply ptInsertPTE_quota_bounded_AT in H; auto.\n          - eapply consistent_ppage_norm; eassumption.\n          - intros. congruence.\n        Qed.\n\n        Lemma ptInsertPTE_low_level_inv:\n          forall d d' n vadr padr p n',\n            ptInsertPTE_spec n vadr padr p d = Some d' ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptInsertPTE_kernel_mode:\n          forall d d' n vadr padr p,\n            ptInsertPTE_spec n vadr padr p d = Some d' ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTINSERT_PTE.\n\n      Lemma ptInsert_high_level_inv:\n        forall d d' n vadr padr p v,\n          ptInsert_spec n vadr padr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        - eapply ptInsertPTE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptInsertPTE_high_level_inv; try eassumption.\n          eapply ptAllocPDE_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_low_level_inv:\n        forall d d' n vadr padr p n' v,\n          ptInsert_spec n vadr padr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptInsertPTE_low_level_inv; try eassumption.\n          eapply ptAllocPDE_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_kernel_mode:\n        forall d d' n vadr padr p v,\n          ptInsert_spec n vadr padr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_kernel_mode; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n        - eapply ptInsertPTE_kernel_mode; try eassumption.\n          eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptInsert_inv: PreservesInvariants ptInsert_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptInsert_low_level_inv; eassumption.\n        - eapply ptInsert_high_level_inv; eassumption.\n        - eapply ptInsert_kernel_mode; eassumption.\n      Qed.\n\n    End PTINSERT.\n\n    Global Instance ptRmv_inv: PreservesInvariants ptRmv_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto;\n      try (rewrite ZMap.gso; eauto; fail).\n      - intros; eapply AT_kern_norm; eauto. \n      - intros; eapply AT_usr_norm; eauto.\n      - apply ptRmv_quota_bounded_AT in H2; auto.\n      - eapply consistent_ppage_norm; eassumption.\n    Qed.\n\n    Global Instance pt_init_kern_inv: PreservesInvariants pt_init_kern_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n      - apply real_nps_range.\n      - apply real_at_kern_valid.\n      - apply real_at_usr_valid.\n      - apply real_container_valid.\n      - apply real_quota_bounded_AT.\n      - rewrite init_pperm; try assumption.\n        apply real_pperm_valid.        \n    Qed.\n\n  End INV.\n\n  (** * Layer Definition *)\n  (** ** Layer Definition newly introduced  *)\n  Definition mptkern_fresh : compatlayer (cdata RData) :=\n    pt_insert \u21a6 gensem ptInsert_spec\n              \u2295 pt_rmv \u21a6 gensem ptRmv_spec\n              \u2295 pt_init_kern \u21a6 gensem pt_init_kern_spec.\n\n  (** ** Layer Definition passthrough  *)\n  Definition mptkern_passthrough : compatlayer (cdata RData) :=\n    fload \u21a6 gensem fload_spec\n          \u2295 fstore \u21a6 gensem fstore_spec\n          \u2295 flatmem_copy \u21a6 gensem flatmem_copy_spec\n          \u2295 vmxinfo_get \u21a6 gensem vmxinfo_get_spec\n          \u2295 device_output \u21a6 gensem device_output_spec\n          \u2295 set_pg \u21a6 gensem setPG1_spec\n          \u2295 at_get_c \u21a6 gensem get_at_c_spec\n          \u2295 at_set_c \u21a6 gensem set_at_c0_spec\n          \u2295 pfree \u21a6 gensem pfree'_spec\n          \u2295 set_pt \u21a6 gensem setPT'_spec\n\n          \u2295 pt_read \u21a6 gensem ptRead_spec\n          \u2295 pt_read_pde \u21a6 gensem ptReadPDE_spec\n          \u2295 pt_free_pde \u21a6 gensem ptFreePDE_spec\n\n          \u2295 pt_in \u21a6 primcall_general_compatsem' ptin'_spec (prim_ident:= pt_in)\n          \u2295 pt_out \u21a6 primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          \u2295 clear_cr2 \u21a6 gensem clearCR2_spec\n          \u2295 container_get_parent \u21a6 gensem container_get_parent_spec\n          \u2295 container_get_nchildren \u21a6 gensem container_get_nchildren_spec\n          \u2295 container_get_quota \u21a6 gensem container_get_quota_spec\n          \u2295 container_get_usage \u21a6 gensem container_get_usage_spec\n          \u2295 container_can_consume \u21a6 gensem container_can_consume_spec\n          \u2295 container_split \u21a6 gensem container_split_spec\n          \u2295 container_alloc \u21a6 gensem container_alloc_spec\n          \u2295 trap_in \u21a6 primcall_general_compatsem trapin_spec\n          \u2295 trap_out \u21a6 primcall_general_compatsem trapout_spec\n          \u2295 host_in \u21a6 primcall_general_compatsem hostin_spec\n          \u2295 host_out \u21a6 primcall_general_compatsem hostout_spec\n          \u2295 trap_get \u21a6 primcall_trap_info_get_compatsem trap_info_get_spec\n          \u2295 trap_set \u21a6 primcall_trap_info_ret_compatsem trap_info_ret_spec\n          \u2295 accessors \u21a6 {| exec_load := (@exec_loadex _ _ Hmwd); \n                           exec_store := (@exec_storeex _ _ Hmwd) |}.\n\n  (** * Layer Definition *)\n  Definition mptkern : compatlayer (cdata RData) := mptkern_fresh \u2295 mptkern_passthrough.\n\n  (*Definition semantics := LAsm.Lsemantics mptintro.*)\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  Function pt_init_spec (mbi_adr:Z) (adt: RData): option RData :=\n    match (init adt, pg adt, ikern adt, ihost adt, ipt adt) with\n      | (false, false, true, true, true) => \n        Some adt {vmxinfo: real_vmxinfo} {pg: true} {AT: real_AT (AT adt)} {nps: real_nps}\n             {AC: real_AC} {init: true} {PT: 0} {ptpool: real_pt (ptpool adt)}\n             {idpde: real_idpde (idpde 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/mm/MPTKern.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.1790382913505735}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        CertifiedExtraction.Extraction.QueryStructures.Basics\n        CertifiedExtraction.Extraction.QueryStructures.TupleToListW\n        CertifiedExtraction.Extraction.QueryStructures.EnsemblesOfTuplesAndListW\n        CertifiedExtraction.Extraction.QueryStructures.CallRules.CallRules.\n\nRequire Import CertifiedExtraction.Extraction.QueryStructures.Wrappers.\nRequire Import Fiat.QueryStructure.Implementation.DataStructures.BagADT.QueryStructureImplementation.\n\nRequire Import Bedrock.Platform.Facade.CompileUnit2.\n\nRequire Export\n        CertifiedExtraction.ADT2CompileUnit\n        CertifiedExtraction.Extraction.Extraction\n        CertifiedExtraction.Extraction.QueryStructures.Decompose.\n\nRequire Import\n        Bedrock.Memory\n        Bedrock.Platform.Facade.DFModule\n        Bedrock.Platform.Facade.CompileUnit2.\n\nTransparent CallBagMethod.\nArguments CallBagMethod : simpl never.\nArguments wrap : simpl never.\nArguments ListWToTuple: simpl never.\n\nDefinition BagSanityConditions {N} tbl :=\n  TuplesF.functional (IndexedEnsemble_TupleToListW (N := N) tbl)\n  /\\ exists idx, TuplesF.minFreshIndex (IndexedEnsemble_TupleToListW tbl) idx.\n\nLemma Lift_Ensemble :\n  forall n r idx (el: FiatWTuple n),\n    Ensembles.In _ r\n                 {| IndexedEnsembles.elementIndex := idx;\n                    IndexedEnsembles.indexedElement := el |} <->\n    Ensembles.In _ (IndexedEnsemble_TupleToListW r)\n                 {| TuplesF.elementIndex := idx;\n                    TuplesF.indexedElement := TupleToListW el |}.\nProof.\n  split; intros.\n  - econstructor; intuition eauto.\n    unfold RelatedIndexedTupleAndListW; split; simpl; eauto.\n  - destruct H;  unfold RelatedIndexedTupleAndListW in *; intuition.\n    simpl in *; subst.\n    destruct x; simpl in *; subst.\n    unfold TupleToListW in H2.\n    apply ilist2ToListW_inj in H2; subst; eauto.\nQed.\n\nLemma BagSanityConditions_Add:\n  forall n (r : FiatWBag n) el,\n    TuplesF.functional (IndexedEnsemble_TupleToListW r) ->\n    IndexedEnsembles.UnConstrFreshIdx r (IndexedEnsembles.elementIndex el) ->\n    BagSanityConditions (Ensembles.Add IndexedEnsembles.IndexedElement r el).\nProof.\n  split; unfold TuplesF.functional, TuplesF.minFreshIndex; intros; intuition.\n  - destruct t1; destruct t2; simpl in *; subst; f_equal.\n    destruct H2; destruct H1; intuition.\n    destruct H2; destruct H3; subst.\n    + unfold TuplesF.tupl in *.\n      unfold RelatedIndexedTupleAndListW in *; simpl in *; intuition.\n      subst.\n      destruct x; destruct x0; simpl in *; subst.\n      apply Lift_Ensemble in H2; apply Lift_Ensemble in H1.\n      pose proof (H _ _ H1 H2 (eq_refl _)); injections; eauto.\n    + destruct H2.\n      unfold RelatedIndexedTupleAndListW in *; simpl in *; intuition; subst.\n      destruct x0; destruct el; simpl in *; subst.\n      unfold TuplesF.UnConstrFreshIdx in H1.\n      unfold IndexedEnsembles.UnConstrFreshIdx in H0.\n      apply H0 in H1; simpl in *.\n      omega.\n    + destruct H1.\n      unfold RelatedIndexedTupleAndListW in *; simpl in *; intuition; subst.\n      destruct x; destruct el; simpl in *; subst.\n      unfold IndexedEnsembles.UnConstrFreshIdx in H0.\n      apply H0 in H2; simpl in *.\n      omega.\n    + destruct H2; destruct H1.\n      unfold RelatedIndexedTupleAndListW in *; simpl in *; intuition; subst.\n      reflexivity.\n  - exists (S (IndexedEnsembles.elementIndex el)); split.\n    + unfold TuplesF.UnConstrFreshIdx in *; intros.\n      destruct H1 as [? [? ? ] ].\n      unfold RelatedIndexedTupleAndListW in *; simpl in *; intuition; subst.\n      destruct element; simpl in *; subst.\n      * destruct H1.\n        destruct x; simpl in *.\n        apply H0 in H1; simpl in *; omega.\n        destruct H1; omega.\n    + intros.\n      inversion H1; subst.\n      unfold TuplesF.UnConstrFreshIdx in *.\n      assert (lt (TuplesF.elementIndex (IndexedElement_TupleToListW el)) (IndexedEnsembles.elementIndex el) ).\n      eapply H2.\n      econstructor; split.\n      unfold Ensembles.Add.\n      econstructor 2.\n      reflexivity.\n      unfold RelatedIndexedTupleAndListW; eauto.\n      destruct el; simpl in *; omega.\n      unfold TuplesF.UnConstrFreshIdx in *; intros.\n      assert (lt (IndexedEnsembles.elementIndex el) idx').\n      eapply (H2 {| TuplesF.elementIndex := _;\n                    TuplesF.indexedElement := _ |}); simpl.\n      unfold IndexedEnsemble_TupleToListW.\n      simpl; eexists; split.\n      econstructor 2.\n      reflexivity.\n      unfold RelatedIndexedTupleAndListW; simpl; split; eauto.\n      omega.\nQed.\n\nLtac _compile_CallBagFind :=\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            match constr:((pre, post)) with\n            | (Cons (NTSome (H := ?h) ?vdb) (ret (prim_fst ?db)) (fun _ => ?tenv), Cons NTNone ?bf _) =>\n              match bf with\n              | CallBagMethod Fin.F1 BagFind ?db ?kwd =>\n                let vsnd := gensym \"snd\" in\n                let vtmp := gensym \"tmp\" in\n                eapply CompileSeq\n                with ([[bf as retv]]\n                        :: [[(NTSome (H := h) vdb)\n                              ->> prim_fst (Refinements.UpdateIndexedRelation\n                                            (QueryStructureSchema.QueryStructureSchemaRaw\n                                               ProcessScheduler.SchedulerSchema)\n                                            (icons3 ProcessScheduler.SearchUpdateTerm inil3)\n                                            db Fin.F1 (fst retv)) as _]]\n                        :: [[`vsnd ->> snd retv as s]]\n                        :: tenv);\n                [ match kwd with\n                  | (Some ?v, (None, fun _ => true)) =>\n                    let vkwd := find_fast (wrap (WrappingType := Value QsADTs.ADTValue) v) ext in\n                    match vkwd with\n                    | Some ?vkwd => apply (WBagOfTuples2Compilation.CompileFindFirst_spec\n                                            (* FIXME get (Fin.FS Fin.F1) generically *)\n                                            (Fin.FS Fin.F1) (vkey := vkwd) _ (table := prim_fst db))\n                    end\n                  | (None, (Some ?v, fun _ => true)) =>\n                    let vkwd := find_fast (wrap (WrappingType := Value QsADTs.ADTValue) v) ext in\n                    match vkwd with\n                    | Some ?vkwd => apply (WBagOfTuples2Compilation.CompileFindSecond_spec\n                                            (* FIXME get (Fin.F1) generically *)\n                                            _ (Fin.F1) (vkey := vkwd) (table := prim_fst db))\n                    end\n                  end | ]\n              end\n            end).\n\nLtac _compile_length :=\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            match constr:((pre, post)) with\n            | (?pre, Cons ?k (ret (bool2w (EqNat.beq_nat (Datatypes.length (rev ?seq)) 0))) (fun _ => ?pre')) =>\n              let vlst := find_fast (wrap (FacadeWrapper := WrapInstance (H := QS_WrapFiatWTupleList)) seq) ext in\n              match vlst with\n              | Some ?vlst => eapply (WTupleListCompilation.CompileEmpty_spec (idx := 3) (vlst := vlst))\n              end\n            end).\n\n\nLtac _compile_CallBagInsert := (* FIXME should do the insert in the second branch *)\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            match constr:((pre, post)) with\n            | (Cons (NTSome (H := ?h) ?vrep) (ret ?db) (fun _ => ?tenv),\n               Cons NTNone ?bm (fun a => Cons ?vret _ (fun _ => Cons (NTSome ?vrep') (ret a) (fun _ => ?tenv')))) =>\n              unify vrep vrep';\n                match bm with\n                | (CallBagMethod _ BagInsert _ (ilist2.icons2 ?a (ilist2.icons2 ?b (ilist2.icons2 ?c ilist2.inil2)))) =>\n                  let vtmp := gensym \"tmp\" in\n                  let vtup := gensym \"tup\" in\n                  (* match pre with *)\n                  change (ilist2.icons2 a (ilist2.icons2 b (ilist2.icons2 c ilist2.inil2))) with (ListWToTuple [[[a; b; c]]]);\n                    apply CompileSeq with (Cons (NTSome (H := h) vrep) (ret db)\n                                                (fun _ => Cons (NTSome (H := WrapInstance (H := WTupleCompilation.FiatWrapper)) vtup) (ret ((ListWToTuple [[[a; b; c]]]): FiatWTuple 3)) (fun _ => tenv)));\n                    [ | eapply CompileSeq; [ let vtmp := gensym \"vtmp\" in eapply (WBagOfTuples2Compilation.CompileInsert_spec (vtmp := vtmp)) | ] ]\n                end\n            end).\n\n\nLtac explode n :=\n  match n with\n  | 0 => idtac\n  | S ?n =>\n    compile_do_use_transitivity_to_handle_head_separately;\n      [ | apply ProgOk_Chomp_Some; [ | intros; explode n ] ]\n  end.\n\nLtac _compile_allocTuple :=\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            match constr:((pre, post)) with\n            | (?pre, Cons ?k (ret ?tup) (fun _ => ?pre)) =>\n              match type of tup with\n              | FiatWTuple _ =>\n                let v1 := gensym \"v1\" in\n                let v2 := gensym \"v2\" in\n                let v3 := gensym \"v3\" in\n                let o1 := gensym \"o1\" in\n                let o2 := gensym \"o2\" in\n                let o3 := gensym \"o3\" in\n                let vlen := gensym \"vlen\" in\n                let vtmp := gensym \"vtmp\" in\n                apply (WTupleCompilation.CompileNew_spec (v1 := \"v1\") (v2 := \"v2\") (v3 := \"v3\") (o1 := \"o1\") (o2 := \"o2\") (o3 := \"o3\") (vlen := \"vlen\") (vtmp := \"vtmp\")); try explode 6\n              end\n            end).\n\nLtac _compile_destructor_unsafe vtmp tenv tenv' ::=\n     let vtmp2 := gensym \"tmp'\" in\n     let vsize := gensym \"size\" in\n     let vtest := gensym \"test\" in\n     let vhead := gensym \"head\" in\n     first [ unify tenv tenv';\n             apply (WTupleListCompilation.CompileDeleteAny_spec\n                      (N := 3) (vtmp := vtmp) (vtmp2 := vtmp2) (vsize := vsize)\n                      (vtest := vtest) (vhead := vhead))\n           | eapply CompileSeq;\n             [ apply (WTupleListCompilation.CompileDeleteAny_spec\n                        (N := 3) (vtmp := vtmp) (vtmp2 := vtmp2) (vsize := vsize)\n                        (vtest := vtest) (vhead := vhead)) | ] ].\n\nLemma map_rev_def :\n  forall {A B} f seq,\n    @map A B f (rev seq) = revmap f seq.\nProof.\n  intros; reflexivity.\nQed.\n\nLtac _compile_map ::= (* \u2018_compile_map\u2019 from the stdlib uses generic push-pop methods *)\n  match_ProgOk\n     ltac:(fun prog pre post ext env =>\n             let vhead := gensym \"head\" in\n             let vhead' := gensym \"head'\" in\n             let vtest := gensym \"test\" in\n             let vtmp := gensym \"tmp\" in\n             match constr:((pre, post)) with\n             | (Cons (NTSome ?vseq) (ret ?seq) ?tenv, Cons (NTSome ?vret) (ret (revmap _ ?seq')) ?tenv') =>\n               unify seq seq';\n               apply (WTupleListCompilation.CompileMap_TuplesToWords\n                        (N := 3) seq (vhead := vhead) (vhead' := vhead') (vtest := vtest) (vtmp := vtmp))\n             end).\n\nLtac _compile_get :=\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            let vtmp := gensym \"tmp\" in\n            match constr:((pre, post)) with\n            | (Cons (NTSome (H:=?h) ?k) (ret ?tup) ?tenv, Cons (NTSome (H:=?h') ?k') (ret (GetAttributeRaw ?tup' ?idx')) _) =>\n              unify tup tup';\n                let vpos := gensym \"pos\" in\n                eapply CompileSeq with (Cons (NTSome (H:=h) k) (ret tup)\n                                             (fun a => Cons (NTSome (H:=h') k') (ret (ilist2.ith2 tup' idx'))\n                                                         (fun _ => tenv a)));\n                  [ apply (WTupleCompilation.CompileGet_spec (N := 3) tup' idx' (vpos := vpos)) |\n                    let vtmp := gensym \"tmp\" in\n                    let vsize := gensym \"size\" in\n                    apply (WTupleCompilation.CompileDelete_spec (vtmp := vtmp) (vsize := vsize)) ]\n            end).\n\nLemma GLabelMapFacts_map_add_1 :\n  (* This is a hack to transform a rewrite into an apply (setoid_rewrite is too slow). *)\n  forall (elt B : Type) (f : elt -> B) (k : GLabelMapFacts.M.key) (v : elt) (m : GLabelMapFacts.M.t elt) m0,\n    GLabelMapFacts.M.Equal (GLabelMapFacts.M.map f m) m0 ->\n    GLabelMapFacts.M.Equal (GLabelMapFacts.M.map f (m ### k ->> v)) (m0 ### k ->> f v).\nProof.\n  intros * H; rewrite GLabelMapFacts.map_add, H; reflexivity.\nQed.\n\nRequire Import Fiat.CertifiedExtraction.PureFacadeLemmas.\n\nLtac GLabelMap_fast_apply_map :=\n  (* This tactic simplifies an expression like [map f (add k1 v1 (add ...))]\n     into [add k1 (f v1) (add ...)]. Using setoid_rewrite repeatedly was too\n     slow, so it relies on a separate lemma and an evar to do its job. *)\n  etransitivity;\n  [ |\n    match goal with\n    | [  |- GLabelMap.Equal ?ev ?complex_expr ] =>\n      match complex_expr with (* Not a lazy match: not all [GLabelMap.map]s can be removed *)\n      | context Ctx [GLabelMap.map ?f ?m] =>\n        lazymatch type of f with\n        | ?elt -> ?elt' =>\n          let m' := fresh in\n          evar (m' : GLabelMap.t elt');\n          (* This block is essentially [setoid_replace (GLabelMap.map f m) m'] with\n               relation [@GLabelMap.Equal elt'], but it fails before calling the setoid\n               machinery if the relation doesn't actually hold. *)\n          let __eq := fresh in\n          assert (@GLabelMap.Equal elt' (GLabelMap.map f m) m') as __eq;\n          [ unfold m' in *; clear m'; try unfold m;\n            solve [repeat apply GLabelMapFacts_map_add_1; apply GLabelMapFacts.map_empty] | ];\n          (* Now that we have an equality between subterms, plug it in the larger term *)\n          (* This because setoid_rewrite __eq took one hour *)\n          let simpler_term := context Ctx[m'] in\n          unify ev simpler_term;\n          symmetry in __eq;\n          repeat match goal with\n                 | [  |- GLabelMap.Equal ?x ?x ] => reflexivity\n                 | [  |- GLabelMap.Equal (GLabelMapFacts.UWFacts.WFacts.P.update _ _)\n                                        (GLabelMapFacts.UWFacts.WFacts.P.update _ _) ] =>\n                   apply GLabelMapFacts_UWFacts_WFacts_P_update_morphism\n                 | _ => exact __eq\n                 end\n        end\n      end\n    end ].\n\nLtac _compile_cleanup_env_helper :=\n  GLabelMap_fast_apply_map;\n  GLabelMap_fast_apply_map;\n  reflexivity.\n\nLtac __compile_cleanup_env :=\n  match_ProgOk\n    ltac:(fun prog pre post ext env =>\n            match env with\n            | GLabelMapFacts.UWFacts.WFacts.P.update _ _ =>\n              eapply Proper_ProgOk; [ reflexivity | _compile_cleanup_env_helper | reflexivity.. | idtac ];\n              match_ProgOk ltac:(fun prog pre post ext env => set env)\n            end).\n\nLtac __compile_prepare_merged_env_for_compile_do_side_conditions :=\n  lazymatch goal with\n  | [ |- GLabelMap.MapsTo _ _ ?env ] =>\n    lazymatch eval unfold env in env with\n    | GLabelMapFacts.UWFacts.WFacts.P.update _ _ =>\n      unfold env; apply GLabelMapFacts.UWFacts.WFacts.P.update_mapsto_iff; left\n    end\n  end.\n\nLtac __compile_pose_query_structure :=\n  (* Removing this pose makes the [apply CompileTuples2_findFirst_spec] loop.\n     No idea why. *)\n  match goal with\n  | [ r: IndexedQueryStructure _ _ |- _ ] =>\n    match goal with\n    | [ r' := _ : IndexedQueryStructure _ _ |- _ ] => fail 1\n    | _ => pose r\n    end\n  end.\n\nLtac __compile_discharge_bag_side_conditions_step :=\n  match goal with\n  | _ => cleanup\n  | _ => progress injections\n  | _ => progress simpl in *\n  | _ => progress computes_to_inv\n  | _ => progress unfold CallBagMethod in *\n  | _ => progress (find_if_inside; simpl in * )\n  | [  |- BagSanityConditions (Ensembles.Add _ _ _) ] => apply BagSanityConditions_Add\n  | [  |- BagSanityConditions _ ] => split; solve [intuition eauto]\n  | _ => eassumption\n  end.\n\nLtac __compile_discharge_bag_side_conditions_internal :=\n  solve [repeat __compile_discharge_bag_side_conditions_step].\n\nLtac __compile_discharge_bag_side_conditions :=\n  match goal with\n  | [  |- TuplesF.functional _ ] => __compile_discharge_bag_side_conditions_internal\n  | [  |- TuplesF.minFreshIndex _ _ ] => __compile_discharge_bag_side_conditions_internal\n  | [  |- BagSanityConditions _ ] => __compile_discharge_bag_side_conditions_internal\n  end.\n\nLtac __compile_unfold :=\n     match goal with\n     | _ => progress unfold If_Then_Else in *\n     end.\n\nLtac __compile_clear_bodies_of_ax_spec :=\n  repeat (unfold GenExports, map_aug_mod_name, aug_mod_name,\n          GLabelMapFacts.uncurry; simpl);\n  repeat lazymatch goal with\n    | |- context[GenAxiomaticSpecs ?a0 ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?a7] =>\n      let a := fresh in\n      pose (GenAxiomaticSpecs a0 a1 a2 a3 a4 a5 a6 a7) as a;\n      change (GenAxiomaticSpecs a0 a1 a2 a3 a4 a5 a6 a7) with a;\n      clearbody a\n    end.\n\nLtac __compile_start_compiling_module imports :=\n  lazymatch goal with\n  | [  |- sigT (fun _ => BuildCompileUnit2TSpec  _ _ _ _ _ _ _ _ _ _ _ _ _ _ ) ] =>\n    eexists;\n    unfold DecomposeIndexedQueryStructure', DecomposeIndexedQueryStructurePre', DecomposeIndexedQueryStructurePost';\n    eapply (BuildCompileUnit2T' imports); try apply eq_refl (* reflexivity throws an Anomaly *)\n  | [  |- forall _: (Fin.t _), (sigT _)  ] =>\n    __compile_clear_bodies_of_ax_spec;\n    eapply IterateBoundedIndex.Lookup_Iterate_Dep_Type; repeat (apply Build_prim_prod || exact tt)\n  end.\n\nLtac __compile_start_compiling_method :=\n  lazymatch goal with\n  | [  |- sigT (fun (_: Stmt) => _) ] =>\n    eexists; repeat match goal with\n                    | _ => progress simpl\n                    | _ => progress intros\n                    | [  |- _ /\\ _ ] => split\n                    end\n  end.\n\nLtac __compile_decide_NoDup :=\n  repeat lazymatch goal with\n    | [  |- NoDup _ ] => econstructor\n    | [  |- not (List.In _ _) ] => simpl; intuition congruence\n    end.\n\nLtac __compile_start_compiling_step imports :=\n  match goal with\n  | [ H: BagSanityConditions _ |- _ ] => destruct H as [ ? [ ? ? ] ]\n  | _ => __compile_start_compiling_module imports\n  | _ => __compile_start_compiling_method\n  | _ => __compile_discharge_bag_side_conditions\n  | _ => __compile_decide_NoDup\n  end.\n\nLtac __compile_method_step :=\n  match goal with\n  | _ => __compile_unfold\n  | _ => __compile_cleanup_env\n  | _ => __compile_pose_query_structure\n  | _ => __compile_prepare_merged_env_for_compile_do_side_conditions\n  | _ => __compile_discharge_bag_side_conditions\n  | _ => _compile_step\n  | _ => _compile_CallBagFind\n  | _ => _compile_CallBagInsert\n  | _ => _compile_length\n  | _ => _compile_allocTuple\n  | _ => _compile_get\n  | _ => apply CompileConstantBool\n  | _ => reflexivity\n  | _ => progress simpl\n  | _ => setoid_rewrite map_rev_def\n  end.\n\nLtac _compile env :=\n  repeat __compile_start_compiling_step env;\n  repeat __compile_method_step.\n\nTransparent Vector.to_list.\n\nDefinition QSEnv_Ax : GLabelMap.t (AxiomaticSpec QsADTs.ADTValue) :=\n  (GLabelMap.empty _)\n  ### (\"ADT\", \"WordList_new\") ->> (QsADTs.WordListADTSpec.New)\n  ### (\"ADT\", \"WordList_delete\") ->> (QsADTs.WordListADTSpec.Delete)\n  ### (\"ADT\", \"WordList_pop\") ->> (QsADTs.WordListADTSpec.Pop)\n  ### (\"ADT\", \"WordList_empty\") ->> (QsADTs.WordListADTSpec.Empty)\n  ### (\"ADT\", \"WordList_push\") ->> (QsADTs.WordListADTSpec.Push)\n  ### (\"ADT\", \"WordList_copy\") ->> (QsADTs.WordListADTSpec.Copy)\n  ### (\"ADT\", \"WordList_rev\") ->> (QsADTs.WordListADTSpec.Rev)\n  ### (\"ADT\", \"WordList_length\") ->> (QsADTs.WordListADTSpec.Length)\n\n  ### (\"ADT\", \"WTuple_new\") ->> (QsADTs.WTupleADTSpec.New)\n  ### (\"ADT\", \"WTuple_delete\") ->> (QsADTs.WTupleADTSpec.Delete)\n  ### (\"ADT\", \"WTuple_copy\") ->> (QsADTs.WTupleADTSpec.Copy)\n  ### (\"ADT\", \"WTuple_get\") ->> (QsADTs.WTupleADTSpec.Get)\n  ### (\"ADT\", \"WTuple_put\") ->> (QsADTs.WTupleADTSpec.Put)\n\n  ### (\"ADT\", \"WTupleList_new\") ->> (QsADTs.WTupleListADTSpec.New)\n  ### (\"ADT\", \"WTupleList_delete\") ->> (QsADTs.WTupleListADTSpec.Delete)\n  ### (\"ADT\", \"WTupleList_copy\") ->> (QsADTs.WTupleListADTSpec.Copy)\n  ### (\"ADT\", \"WTupleList_pop\") ->> (QsADTs.WTupleListADTSpec.Pop)\n  ### (\"ADT\", \"WTupleList_empty\") ->> (QsADTs.WTupleListADTSpec.Empty)\n  ### (\"ADT\", \"WTupleList_push\") ->> (QsADTs.WTupleListADTSpec.Push)\n  ### (\"ADT\", \"WTupleList_rev\") ->> (QsADTs.WTupleListADTSpec.Rev)\n  ### (\"ADT\", \"WTupleList_length\") ->> (QsADTs.WTupleListADTSpec.Length)\n\n  ### (\"ADT\", \"WBagOfTuples0_new\") ->> (QsADTs.WBagOfTuples0ADTSpec.New)\n  ### (\"ADT\", \"WBagOfTuples0_insert\") ->> (QsADTs.WBagOfTuples0ADTSpec.Insert)\n  ### (\"ADT\", \"WBagOfTuples0_enumerate\") ->> (QsADTs.WBagOfTuples0ADTSpec.Enumerate)\n\n  ### (\"ADT\", \"WBagOfTuples1_new\") ->> (QsADTs.WBagOfTuples1ADTSpec.New)\n  ### (\"ADT\", \"WBagOfTuples1_insert\") ->> (QsADTs.WBagOfTuples1ADTSpec.Insert)\n  ### (\"ADT\", \"WBagOfTuples1_find\") ->> (QsADTs.WBagOfTuples1ADTSpec.Find)\n  ### (\"ADT\", \"WBagOfTuples1_enumerate\") ->> (QsADTs.WBagOfTuples1ADTSpec.Enumerate)\n\n  ### (\"ADT\", \"WBagOfTuples2_new\") ->> (QsADTs.WBagOfTuples2ADTSpec.New)\n  ### (\"ADT\", \"WBagOfTuples2_insert\") ->> (QsADTs.WBagOfTuples2ADTSpec.Insert)\n  ### (\"ADT\", \"WBagOfTuples2_findBoth\") ->> (QsADTs.WBagOfTuples2ADTSpec.FindBoth)\n  ### (\"ADT\", \"WBagOfTuples2_findFirst\") ->> (QsADTs.WBagOfTuples2ADTSpec.FindFirst)\n  ### (\"ADT\", \"WBagOfTuples2_findSecond\") ->> (QsADTs.WBagOfTuples2ADTSpec.FindSecond)\n  ### (\"ADT\", \"WBagOfTuples2_enumerate\") ->> (QsADTs.WBagOfTuples2ADTSpec.Enumerate).\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/Extraction/QueryStructures/QueryStructures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.17903827928843247}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gmap_view namespace_map agree frac.\nFrom iris.base_logic.lib Require Export own.\nFrom iris Require Import options.\nImport uPred.\n\n(** This file provides a generic mechanism for a language-level point-to\nconnective [l \u21a6{q} v] reflecting the physical heap.  This library is designed to\nbe used as a singleton (i.e., with only a single instance existing in any\nproof), with the [gen_heapG] typeclass providing the ghost names of that unique\ninstance.  That way, [mapsto] does not need an explicit [gname] parameter.\nThis mechanism can be plugged into a language and related to the physical heap\nby using [gen_heap_interp \u03c3] in the state interpretation of the weakest\nprecondition. See heap-lang for an example.\n\nIf you are looking for a library providing \"ghost heaps\" independent of the\nphysical state, you will likely want explicit ghost names and are thus better\noff using [algebra.lib.gmap_view] together with [base_logic.lib.own].\n\nThis library is generic in the types [L] for locations and [V] for values and\nsupports fractional permissions.  Next to the point-to connective [l \u21a6{q} v],\nwhich keeps track of the value [v] of a location [l], this library also provides\na way to attach \"meta\" or \"ghost\" data to locations. This is done as follows:\n\n- When one allocates a location, in addition to the point-to connective [l \u21a6 v],\n  one also obtains the token [meta_token l \u22a4]. This token is an exclusive\n  resource that denotes that no meta data has been associated with the\n  namespaces in the mask [\u22a4] for the location [l].\n- Meta data tokens can be split w.r.t. namespace masks, i.e.\n  [meta_token l (E1 \u222a E2) \u22a3\u22a2 meta_token l E1 \u2217 meta_token l E2] if [E1 ## E2].\n- Meta data can be set using the update [meta_token l E ==\u2217 meta l N x] provided\n  [\u2191N \u2286 E], and [x : A] for any countable [A]. The [meta l N x] connective is\n  persistent and denotes the knowledge that the meta data [x] has been\n  associated with namespace [N] to the location [l].\n\nTo make the mechanism as flexible as possible, the [x : A] in [meta l N x] can\nbe of any countable type [A]. This means that you can associate e.g. single\nghost names, but also tuples of ghost names, etc.\n\nTo further increase flexibility, the [meta l N x] and [meta_token l E]\nconnectives are annotated with a namespace [N] and mask [E]. That way, one can\nassign a map of meta information to a location. This is particularly useful when\nbuilding abstractions, then one can gradually assign more ghost information to a\nlocation instead of having to do all of this at once. We use namespaces so that\nthese can be matched up with the invariant namespaces. *)\n\n(** To implement this mechanism, we use three resource algebras:\n\n- A [gmap_view L V], which keeps track of the values of locations.\n- A [gmap_view L gname], which keeps track of the meta information of\n  locations. More specifically, this RA introduces an indirection: it keeps\n  track of a ghost name for each location.\n- The ghost names in the aforementioned authoritative RA refer to namespace maps\n  [namespace_map (agree positive)], which store the actual meta information.\n  This indirection is needed because we cannot perform frame preserving updates\n  in an authoritative fragment without owning the full authoritative element\n  (in other words, without the indirection [meta_set] would need [gen_heap_interp]\n  as a premise).\n *)\n\n(** The CMRAs we need, and the global ghost names we are using.\n\nTypically, the adequacy theorem will use [gen_heap_init] to obtain an instance\nof this class; everything else should assume it as a premise.  *)\nClass gen_heapG (L V : Type) (\u03a3 : gFunctors) `{Countable L} := GenHeapG {\n  gen_heap_inG :> inG \u03a3 (gmap_viewR L (leibnizO V));\n  gen_meta_inG :> inG \u03a3 (gmap_viewR L gnameO);\n  gen_meta_data_inG :> inG \u03a3 (namespace_mapR (agreeR positiveO));\n  gen_heap_name : gname;\n  gen_meta_name : gname\n}.\nArguments gen_heap_name {L V \u03a3 _ _} _ : assert.\nArguments gen_meta_name {L V \u03a3 _ _} _ : assert.\n\nClass gen_heapPreG (L V : Type) (\u03a3 : gFunctors) `{Countable L} := {\n  gen_heap_preG_inG :> inG \u03a3 (gmap_viewR L (leibnizO V));\n  gen_meta_preG_inG :> inG \u03a3 (gmap_viewR L gnameO);\n  gen_meta_data_preG_inG :> inG \u03a3 (namespace_mapR (agreeR positiveO));\n}.\n\nDefinition gen_heap\u03a3 (L V : Type) `{Countable L} : gFunctors := #[\n  GFunctor (gmap_viewR L (leibnizO V));\n  GFunctor (gmap_viewR L gnameO);\n  GFunctor (namespace_mapR (agreeR positiveO))\n].\n\nInstance subG_gen_heapPreG {\u03a3 L V} `{Countable L} :\n  subG (gen_heap\u03a3 L V) \u03a3 \u2192 gen_heapPreG L V \u03a3.\nProof. solve_inG. Qed.\n\nSection definitions.\n  Context `{Countable L, hG : !gen_heapG L V \u03a3}.\n\n  Definition gen_heap_interp (\u03c3 : gmap L V) : iProp \u03a3 := \u2203 m : gmap L gname,\n    (* The [\u2286] is used to avoid assigning ghost information to the locations in\n    the initial heap (see [gen_heap_init]). *)\n    \u231c dom _ m \u2286 dom (gset L) \u03c3 \u231d \u2227\n    own (gen_heap_name hG) (gmap_view_auth (\u03c3 : gmap L (leibnizO V))) \u2217\n    own (gen_meta_name hG) (gmap_view_auth (m : gmap L gnameO)).\n\n  Definition mapsto_def (l : L) (q : Qp) (v: V) : iProp \u03a3 :=\n    own (gen_heap_name hG) (gmap_view_frag l (DfracOwn q) (v : leibnizO V)).\n  Definition mapsto_aux : seal (@mapsto_def). Proof. by eexists. Qed.\n  Definition mapsto := mapsto_aux.(unseal).\n  Definition mapsto_eq : @mapsto = @mapsto_def := mapsto_aux.(seal_eq).\n\n  Definition meta_token_def (l : L) (E : coPset) : iProp \u03a3 :=\n    \u2203 \u03b3m, own (gen_meta_name hG) (gmap_view_frag l DfracDiscarded \u03b3m) \u2217\n          own \u03b3m (namespace_map_token E).\n  Definition meta_token_aux : seal (@meta_token_def). Proof. by eexists. Qed.\n  Definition meta_token := meta_token_aux.(unseal).\n  Definition meta_token_eq : @meta_token = @meta_token_def := meta_token_aux.(seal_eq).\n\n  Definition meta_def `{Countable A} (l : L) (N : namespace) (x : A) : iProp \u03a3 :=\n    \u2203 \u03b3m, own (gen_meta_name hG) (gmap_view_frag l DfracDiscarded \u03b3m) \u2217\n          own \u03b3m (namespace_map_data N (to_agree (encode x))).\n  Definition meta_aux : seal (@meta_def). Proof. by eexists. Qed.\n  Definition meta := meta_aux.(unseal).\n  Definition meta_eq : @meta = @meta_def := meta_aux.(seal_eq).\nEnd definitions.\nArguments meta {L _ _ V \u03a3 _ A _ _} l N x.\n\nLocal Notation \"l \u21a6{ q } v\" := (mapsto l q v)\n  (at level 20, q at level 50, format \"l  \u21a6{ q }  v\") : bi_scope.\nLocal Notation \"l \u21a6 v\" := (mapsto l 1 v) (at level 20) : bi_scope.\n\nLocal Notation \"l \u21a6{ q } -\" := (\u2203 v, l \u21a6{q} v)%I\n  (at level 20, q at level 50, format \"l  \u21a6{ q }  -\") : bi_scope.\nLocal Notation \"l \u21a6 -\" := (l \u21a6{1} -)%I (at level 20) : bi_scope.\n\nLemma gen_heap_init `{Countable L, !gen_heapPreG L V \u03a3} \u03c3 :\n  \u22a2 |==> \u2203 _ : gen_heapG L V \u03a3, gen_heap_interp \u03c3.\nProof.\n  iMod (own_alloc (gmap_view_auth (\u03c3 : gmap L (leibnizO V)))) as (\u03b3h) \"Hh\".\n  { exact: gmap_view_auth_valid. }\n  iMod (own_alloc (gmap_view_auth (\u2205 : gmap L gnameO))) as (\u03b3m) \"Hm\".\n  { exact: gmap_view_auth_valid. }\n  iModIntro. iExists (GenHeapG L V \u03a3 _ _ _ _ _ \u03b3h \u03b3m).\n  iExists \u2205; simpl. iFrame \"Hh Hm\". by rewrite dom_empty_L.\nQed.\n\nSection gen_heap.\n  Context {L V} `{Countable L, !gen_heapG L V \u03a3}.\n  Implicit Types P Q : iProp \u03a3.\n  Implicit Types \u03a6 : V \u2192 iProp \u03a3.\n  Implicit Types \u03c3 : gmap L V.\n  Implicit Types m : gmap L gname.\n  Implicit Types l : L.\n  Implicit Types v : V.\n\n  (** General properties of mapsto *)\n  Global Instance mapsto_timeless l q v : Timeless (l \u21a6{q} v).\n  Proof. rewrite mapsto_eq /mapsto_def. apply _. Qed.\n  Global Instance mapsto_fractional l v : Fractional (\u03bb q, l \u21a6{q} v)%I.\n  Proof.\n    intros p q. rewrite mapsto_eq /mapsto_def -own_op gmap_view_frag_add //.\n  Qed.\n  Global Instance mapsto_as_fractional l q v :\n    AsFractional (l \u21a6{q} v) (\u03bb q, l \u21a6{q} v)%I q.\n  Proof. split. done. apply _. Qed.\n\n  Lemma mapsto_agree l q1 q2 v1 v2 : l \u21a6{q1} v1 -\u2217 l \u21a6{q2} v2 -\u2217 \u231cv1 = v2\u231d.\n  Proof.\n    apply wand_intro_r.\n    rewrite mapsto_eq /mapsto_def -own_op own_valid discrete_valid.\n    apply pure_mono. intros [_ ?]%gmap_view_frag_op_valid_L. done.\n  Qed.\n\n  Lemma mapsto_combine l q1 q2 v1 v2 :\n    l \u21a6{q1} v1 -\u2217 l \u21a6{q2} v2 -\u2217 l \u21a6{q1 + q2} v1 \u2217 \u231cv1 = v2\u231d.\n  Proof.\n    iIntros \"Hl1 Hl2\". iDestruct (mapsto_agree with \"Hl1 Hl2\") as %->.\n    iCombine \"Hl1 Hl2\" as \"Hl\". eauto with iFrame.\n  Qed.\n\n  Global Instance ex_mapsto_fractional l : Fractional (\u03bb q, l \u21a6{q} -)%I.\n  Proof.\n    intros p q. iSplit.\n    - iDestruct 1 as (v) \"[H1 H2]\". iSplitL \"H1\"; eauto.\n    - iIntros \"[H1 H2]\". iDestruct \"H1\" as (v1) \"H1\". iDestruct \"H2\" as (v2) \"H2\".\n      iDestruct (mapsto_agree with \"H1 H2\") as %->. iExists v2. by iFrame.\n  Qed.\n  Global Instance ex_mapsto_as_fractional l q :\n    AsFractional (l \u21a6{q} -) (\u03bb q, l \u21a6{q} -)%I q.\n  Proof. split. done. apply _. Qed.\n\n  Lemma mapsto_valid l q v : l \u21a6{q} v -\u2217 \u2713 q.\n  Proof.\n    rewrite mapsto_eq /mapsto_def own_valid !discrete_valid.\n    rewrite gmap_view_frag_valid //.\n  Qed.\n  Lemma mapsto_valid_2 l q1 q2 v1 v2 : l \u21a6{q1} v1 -\u2217 l \u21a6{q2} v2 -\u2217 \u2713 (q1 + q2)%Qp.\n  Proof.\n    iIntros \"H1 H2\". iDestruct (mapsto_agree with \"H1 H2\") as %->.\n    iApply (mapsto_valid l _ v2). by iFrame.\n  Qed.\n\n  Lemma mapsto_mapsto_ne l1 l2 q1 q2 v1 v2 :\n    \u00ac \u2713(q1 + q2)%Qp \u2192 l1 \u21a6{q1} v1 -\u2217 l2 \u21a6{q2} v2 -\u2217 \u231cl1 \u2260 l2\u231d.\n  Proof.\n    iIntros (?) \"Hl1 Hl2\"; iIntros (->).\n    by iDestruct (mapsto_valid_2 with \"Hl1 Hl2\") as %?.\n  Qed.\n\n  (** General properties of [meta] and [meta_token] *)\n  Global Instance meta_token_timeless l N : Timeless (meta_token l N).\n  Proof. rewrite meta_token_eq /meta_token_def. apply _. Qed.\n  Global Instance meta_timeless `{Countable A} l N (x : A) : Timeless (meta l N x).\n  Proof. rewrite meta_eq /meta_def. apply _. Qed.\n  Global Instance meta_persistent `{Countable A} l N (x : A) : Persistent (meta l N x).\n  Proof. rewrite meta_eq /meta_def. apply _. Qed.\n\n  Lemma meta_token_union_1 l E1 E2 :\n    E1 ## E2 \u2192 meta_token l (E1 \u222a E2) -\u2217 meta_token l E1 \u2217 meta_token l E2.\n  Proof.\n    rewrite meta_token_eq /meta_token_def. intros ?. iDestruct 1 as (\u03b3m1) \"[#H\u03b3m Hm]\".\n    rewrite namespace_map_token_union //. iDestruct \"Hm\" as \"[Hm1 Hm2]\".\n    iSplitL \"Hm1\"; eauto.\n  Qed.\n  Lemma meta_token_union_2 l E1 E2 :\n    meta_token l E1 -\u2217 meta_token l E2 -\u2217 meta_token l (E1 \u222a E2).\n  Proof.\n    rewrite meta_token_eq /meta_token_def.\n    iDestruct 1 as (\u03b3m1) \"[#H\u03b3m1 Hm1]\". iDestruct 1 as (\u03b3m2) \"[#H\u03b3m2 Hm2]\".\n    iDestruct (own_valid_2 with \"H\u03b3m1 H\u03b3m2\") as %[_ ->]%gmap_view_frag_op_valid_L.\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %?%namespace_map_token_valid_op.\n    iExists \u03b3m2. iFrame \"H\u03b3m2\". rewrite namespace_map_token_union //. by iSplitL \"Hm1\".\n  Qed.\n  Lemma meta_token_union l E1 E2 :\n    E1 ## E2 \u2192 meta_token l (E1 \u222a E2) \u22a3\u22a2 meta_token l E1 \u2217 meta_token l E2.\n  Proof.\n    intros; iSplit; first by iApply meta_token_union_1.\n    iIntros \"[Hm1 Hm2]\". by iApply (meta_token_union_2 with \"Hm1 Hm2\").\n  Qed.\n\n  Lemma meta_token_difference l E1 E2 :\n    E1 \u2286 E2 \u2192 meta_token l E2 \u22a3\u22a2 meta_token l E1 \u2217 meta_token l (E2 \u2216 E1).\n  Proof.\n    intros. rewrite {1}(union_difference_L E1 E2) //.\n    by rewrite meta_token_union; last set_solver.\n  Qed.\n\n  Lemma meta_agree `{Countable A} l i (x1 x2 : A) :\n    meta l i x1 -\u2217 meta l i x2 -\u2217 \u231cx1 = x2\u231d.\n  Proof.\n    rewrite meta_eq /meta_def.\n    iDestruct 1 as (\u03b3m1) \"[H\u03b3m1 Hm1]\"; iDestruct 1 as (\u03b3m2) \"[H\u03b3m2 Hm2]\".\n    iDestruct (own_valid_2 with \"H\u03b3m1 H\u03b3m2\") as %[_ ->]%gmap_view_frag_op_valid_L.\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %H\u03b3; iPureIntro.\n    move: H\u03b3. rewrite -namespace_map_data_op namespace_map_data_valid.\n    move=> /to_agree_op_inv_L. naive_solver.\n  Qed.\n  Lemma meta_set `{Countable A} E l (x : A) N :\n    \u2191 N \u2286 E \u2192 meta_token l E ==\u2217 meta l N x.\n  Proof.\n    rewrite meta_token_eq meta_eq /meta_token_def /meta_def.\n    iDestruct 1 as (\u03b3m) \"[H\u03b3m Hm]\". iExists \u03b3m. iFrame \"H\u03b3m\".\n    iApply (own_update with \"Hm\"). by apply namespace_map_alloc_update.\n  Qed.\n\n  (** Update lemmas *)\n  Lemma gen_heap_alloc \u03c3 l v :\n    \u03c3 !! l = None \u2192\n    gen_heap_interp \u03c3 ==\u2217 gen_heap_interp (<[l:=v]>\u03c3) \u2217 l \u21a6 v \u2217 meta_token l \u22a4.\n  Proof.\n    iIntros (H\u03c3l). rewrite /gen_heap_interp mapsto_eq /mapsto_def meta_token_eq /meta_token_def /=.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 Hm]\".\n    iMod (own_update with \"H\u03c3\") as \"[H\u03c3 Hl]\".\n    { eapply (gmap_view_alloc _ l (DfracOwn 1)); done. }\n    iMod (own_alloc (namespace_map_token \u22a4)) as (\u03b3m) \"H\u03b3m\".\n    { apply namespace_map_token_valid. }\n    iMod (own_update with \"Hm\") as \"[Hm Hlm]\".\n    { eapply (gmap_view_alloc _ l DfracDiscarded); last done.\n      move: H\u03c3l. rewrite -!(not_elem_of_dom (D:=gset L)). set_solver. }\n    iModIntro. iFrame \"Hl\". iSplitL \"H\u03c3 Hm\"; last by eauto with iFrame.\n    iExists (<[l:=\u03b3m]> m). iFrame. iPureIntro.\n    rewrite !dom_insert_L. set_solver.\n  Qed.\n\n  Lemma gen_heap_alloc_gen \u03c3 \u03c3' :\n    \u03c3' ##\u2098 \u03c3 \u2192\n    gen_heap_interp \u03c3 ==\u2217\n    gen_heap_interp (\u03c3' \u222a \u03c3) \u2217 ([\u2217 map] l \u21a6 v \u2208 \u03c3', l \u21a6 v) \u2217 ([\u2217 map] l \u21a6 _ \u2208 \u03c3', meta_token l \u22a4).\n  Proof.\n    revert \u03c3; induction \u03c3' as [| l v \u03c3' Hl IH] using map_ind; iIntros (\u03c3 Hdisj) \"H\u03c3\".\n    { rewrite left_id_L. auto. }\n    iMod (IH with \"H\u03c3\") as \"[H\u03c3'\u03c3 H\u03c3']\"; first by eapply map_disjoint_insert_l.\n    decompose_map_disjoint.\n    rewrite !big_opM_insert // -insert_union_l //.\n    by iMod (gen_heap_alloc with \"H\u03c3'\u03c3\") as \"($ & $ & $)\";\n      first by apply lookup_union_None.\n  Qed.\n\n  Lemma gen_heap_valid \u03c3 l q v : gen_heap_interp \u03c3 -\u2217 l \u21a6{q} v -\u2217 \u231c\u03c3 !! l = Some v\u231d.\n  Proof.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 _]\". iIntros \"Hl\".\n    rewrite /gen_heap_interp mapsto_eq /mapsto_def.\n    iDestruct (own_valid_2 with \"H\u03c3 Hl\") as %[??]%gmap_view_both_valid_L.\n    iPureIntro. done.\n  Qed.\n\n  Lemma gen_heap_update \u03c3 l v1 v2 :\n    gen_heap_interp \u03c3 -\u2217 l \u21a6 v1 ==\u2217 gen_heap_interp (<[l:=v2]>\u03c3) \u2217 l \u21a6 v2.\n  Proof.\n    iDestruct 1 as (m H\u03c3m) \"[H\u03c3 Hm]\".\n    iIntros \"Hl\". rewrite /gen_heap_interp mapsto_eq /mapsto_def.\n    iDestruct (own_valid_2 with \"H\u03c3 Hl\") as %[_ Hl]%gmap_view_both_valid_L.\n    iMod (own_update_2 with \"H\u03c3 Hl\") as \"[H\u03c3 Hl]\".\n    { eapply gmap_view_update. }\n    iModIntro. iFrame \"Hl\". iExists m. iFrame.\n    iPureIntro. apply (elem_of_dom_2 (D:=gset L)) in Hl.\n    rewrite dom_insert_L. set_solver.\n  Qed.\nEnd gen_heap.\n", "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/gen_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.1790382771486982}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\nRequire Import TableDataOpsRef1.Layer.\nRequire Import TableDataOpsRef2.Code.table_create2.\n\nRequire Import TableDataOpsRef2.LowSpecs.table_create2.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _table_create \u21a6 gensem table_create_spec\n      \u2295 _table_create1 \u21a6 gensem table_create1_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_table_create: block.\n    Hypothesis h_table_create_s : Genv.find_symbol ge _table_create = Some b_table_create.\n    Hypothesis h_table_create_p : Genv.find_funct_ptr ge b_table_create\n                                  = Some (External (EF_external _table_create\n                                                   (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons tulong Tnil))))) tulong cc_default))\n                                         (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons tulong Tnil))))) tulong cc_default).\n    Local Opaque table_create_spec.\n\n    Variable b_table_create1: block.\n    Hypothesis h_table_create1_s : Genv.find_symbol ge _table_create1 = Some b_table_create1.\n    Hypothesis h_table_create1_p : Genv.find_funct_ptr ge b_table_create1\n                                   = Some (External (EF_external _table_create1\n                                                    (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons tulong Tnil))))) tulong cc_default))\n                                          (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons tulong Tnil))))) tulong cc_default).\n    Local Opaque table_create1_spec.\n\n    Lemma table_create2_body_correct:\n      forall m d d' env le g_rd_base g_rd_offset map_addr level g_rtt_base g_rtt_offset rtt_addr res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))\n             (HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))\n             (HPTlevel: PTree.get _level le = Some (Vlong level))\n             (HPTg_rtt: PTree.get _g_rtt le = Some (Vptr g_rtt_base (Int.repr g_rtt_offset)))\n             (HPTrtt_addr: PTree.get _rtt_addr le = Some (Vlong rtt_addr))\n             (Hspec: table_create2_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned map_addr)) (VZ64 (Int64.unsigned level)) (g_rtt_base, g_rtt_offset) (VZ64 (Int64.unsigned rtt_addr)) d = Some (d', VZ64 (Int64.unsigned res))),\n           exists le', (exec_stmt ge env le ((m, d): mem) table_create2_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).\n    Proof.\n      solve_code_proof Hspec table_create2_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef2/CodeProof/table_create2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17903827218749505}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n   Lemmas about static semantics of heap objects. \n\n*)\n\nRequire Export LanguageModuleDef.\nRequire Export DynamicSemanticsTypeSubstitution.\nRequire Export DynamicSemanticsHeapObjects.\nRequire Export DynamicSemantics.\nRequire Export DynamicSemanticsTypeSubstitution.\nRequire Export StaticSemanticsKindingAndContextWellFormedness.\nRequire Export StaticSemanticsKindingAndContextWellFormednessLemmas.\nRequire Export StaticSemantics.\nRequire Export TypeSafety.\nRequire Export CpdtTactics.\nRequire Export TacticNotations.\nRequire Export Tacticals.\n\nLemma gettype_weakening:\n  forall (u : Upsilon) (x : EV.T) (tau' tau : Tau) (p : Path),\n    WFU u ->\n    gettype u x [] tau' p tau ->\n    forall (u' : Upsilon), \n      U.extends u u' = true ->\n      WFU u' ->\n      gettype u' x [] tau' p tau.\nProof.\n  intros u x tau' tau p WFUder 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   intros.\n   apply IHgettypeder with (u':=u') in WFUder; try assumption.\n   constructor; try assumption.\n  Case \"gettype u x p (cross t0 t1) (i_pe one_pe :: p') tau\".\n   intros.\n   apply IHgettypeder with (u':=u') in WFUder; try assumption.\n   constructor; try assumption.\n  Case \"gettype u x p (etype aliases alpha k tau') (u_pe :: p') tau)\".\n   intros.\n   pose proof WFUder as WFUder'.\n   apply IHgettypeder with (u':=u') in WFUder; try assumption.\n   apply gettype_etype with (tau'':= tau''); try assumption.\n   apply U.map_extends_some_agreement with (c:= u); try assumption.\n   apply WFU_implies_nodup; try assumption.\n   apply WFU_implies_nodup; try assumption.   \nQed.\n\nLemma refp_weakening:\n  forall (h : Heap) (u : Upsilon),\n    H.nodup h = true ->\n    refp h u ->\n    forall (h' : Heap),\n      H.nodup h' = true ->\n      H.extends h h' = true ->\n      refp h' u.\nProof.\n  intros h u noduph refpder.\n  (* h, h' or refp. *)\n  induction refpder.\n  Case \"u = []\".\n   intros.\n   constructor.\n  Case \"refp_pack\".\n   intros.\n   apply refp_pack with (tau:= tau) (alpha:= alpha) (k:= k) (v:= v) (v':= v');\n     try assumption.\n   apply H.map_extends_some_agreement with (c:= h); try assumption.\n   apply IHrefpder; try assumption.\n   (* Scotch Whiskey society wierd but wonderful. *)\nQed.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3.1/StaticSemanticsHeapObjectsLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.17885223663839298}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word Lib.Indexer.\nRequire Import Kami.Syntax Kami.Notations Kami.Semantics Kami.Specialize Kami.Duplicate.\nRequire Import Kami.Wf Kami.Tactics.\nRequire Import Kami.PrimFifo.\nRequire Import Ex.MemTypes Ex.SC Ex.MemAsync Ex.ProcDec.\n\nSet Implicit Arguments.\n\nSection D2eInst.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Definition d2eEltI :=\n    STRUCT { \"opType\" :: Bit 2;\n             \"dst\" :: Bit rfIdx;\n             \"addr\" :: Bit addrSize;\n             \"byteEn\" :: Array Bool dataBytes;\n             \"val1\" :: Data dataBytes;\n             \"val2\" :: Data dataBytes;\n             \"rawInst\" :: Data instBytes;\n             \"curPc\" :: Pc iaddrSize;\n             \"nextPc\" :: Pc iaddrSize;\n             \"epoch\" :: Bool }.\n\n  Definition d2ePackI ty \n             (opTy: Expr ty (SyntaxKind (Bit 2)))\n             (dst: Expr ty (SyntaxKind (Bit rfIdx)))\n             (addr: Expr ty (SyntaxKind (Bit addrSize)))\n             (byteEn: Expr ty (SyntaxKind (Array Bool dataBytes)))\n             (val1 val2: Expr ty (SyntaxKind (Data dataBytes)))\n             (rawInst: Expr ty (SyntaxKind (Data instBytes)))\n             (curPc: Expr ty (SyntaxKind (Pc iaddrSize)))\n             (nextPc: Expr ty (SyntaxKind (Pc iaddrSize)))\n             (epoch: Expr ty (SyntaxKind Bool)): Expr ty (SyntaxKind (Struct d2eEltI)) :=\n    STRUCT { \"opType\" ::= opTy;\n             \"dst\" ::= dst;\n             \"addr\" ::= addr;\n             \"byteEn\" ::= byteEn;\n             \"val1\" ::= val1;\n             \"val2\" ::= val2;\n             \"rawInst\" ::= rawInst;\n             \"curPc\" ::= curPc;\n             \"nextPc\" ::= nextPc;\n             \"epoch\" ::= epoch }%kami_expr.\n\n  Definition d2eOpTypeI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Bit 2)) := (#d2e!d2eEltI@.\"opType\")%kami_expr.\n  Definition d2eDstI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Bit rfIdx)) := (#d2e!d2eEltI@.\"dst\")%kami_expr.\n  Definition d2eAddrI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Bit addrSize)) := (#d2e!d2eEltI@.\"addr\")%kami_expr.\n  Definition d2eByteEnI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Array Bool dataBytes)) := (#d2e!d2eEltI@.\"byteEn\")%kami_expr.\n  Definition d2eVal1I ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Data dataBytes)) := (#d2e!d2eEltI@.\"val1\")%kami_expr.\n  Definition d2eVal2I ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Data dataBytes)) := (#d2e!d2eEltI@.\"val2\")%kami_expr.\n  Definition d2eRawInstI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Data instBytes)) := (#d2e!d2eEltI@.\"rawInst\")%kami_expr.\n  Definition d2eCurPcI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Pc iaddrSize)) := (#d2e!d2eEltI@.\"curPc\")%kami_expr.\n  Definition d2eNextPcI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind (Pc iaddrSize)) := (#d2e!d2eEltI@.\"nextPc\")%kami_expr.\n  Definition d2eEpochI ty (d2e: fullType ty (SyntaxKind (Struct d2eEltI)))\n    : Expr ty (SyntaxKind Bool) := (#d2e!d2eEltI@.\"epoch\")%kami_expr.\n\nEnd D2eInst.\n\nSection E2wInst.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Definition e2wEltI :=\n    STRUCT { \"decInst\" :: Struct (d2eEltI addrSize iaddrSize instBytes dataBytes rfIdx);\n             \"val\" :: Data dataBytes }.\n\n  Definition e2wPackI ty\n             (decInst: Expr ty (SyntaxKind (Struct (d2eEltI addrSize iaddrSize instBytes dataBytes rfIdx))))\n             (val: Expr ty (SyntaxKind (Data dataBytes))) : Expr ty (SyntaxKind (Struct e2wEltI))\n    := STRUCT { \"decInst\" ::= decInst;\n                \"val\" ::= val }%kami_expr.\n\n  Definition e2wDecInstI ty (e2w: fullType ty (SyntaxKind (Struct e2wEltI)))\n    : Expr ty (SyntaxKind (Struct (d2eEltI addrSize iaddrSize instBytes dataBytes rfIdx))) :=\n    (#e2w!e2wEltI@.\"decInst\")%kami_expr.\n  Definition e2wValI ty (e2w: fullType ty (SyntaxKind (Struct e2wEltI)))\n    : Expr ty (SyntaxKind (Data dataBytes)) := (#e2w!e2wEltI@.\"val\")%kami_expr.\n\nEnd E2wInst.\n  \n(* A three-staged processor, where three sets -- {fetch, decode}, {execute}, and \n * {mem, write-back} -- are modularly separated to form each stage. \"epoch\" registers are\n * used to handle incorrect branch prediction. Like a decoupled processor, memory operations are\n * stalled until getting the response.\n *)\nSection ProcThreeStage.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Definition RqFromProc := MemTypes.RqFromProc dataBytes (Bit addrSize).\n  Definition RsToProc := MemTypes.RsToProc dataBytes.\n\n  Definition memReq := memReq addrSize dataBytes.\n  Definition memRep := memRep dataBytes.\n\n  (* Abstract d2eElt *)\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  (* Abstract e2wElt *)\n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n  \n  Definition d2eFifoName := \"d2e\"%string.\n  Definition d2eEnq := MethodSig (d2eFifoName -- \"enq\")(d2eElt) : Void.\n  Definition d2eDeq := MethodSig (d2eFifoName -- \"deq\")() : d2eElt.\n\n  (** For redirecting a correct pc: a previous pc is sent as well to train\n   * the branch predictor. *)\n  Definition W2DStr := STRUCT { \"prevPc\" :: Pc addrSize; \"nextPc\" :: Pc addrSize }.\n  Definition w2dElt := Struct W2DStr.\n  Definition w2dFifoName := \"w2d\"%string.\n  Definition w2dEnq := MethodSig (w2dFifoName -- \"enq\")(w2dElt) : Void.\n  Definition w2dDeq := MethodSig (w2dFifoName -- \"deq\")() : w2dElt.\n  Definition w2dFull := MethodSig (w2dFifoName -- \"isFull\")() : Bool.\n\n  Definition e2wFifoName := \"e2w\"%string.\n  Definition e2wEnq := MethodSig (e2wFifoName -- \"enq\")(e2wElt) : Void.\n  Definition e2wDeq := MethodSig (e2wFifoName -- \"deq\")() : e2wElt.\n  \n  Section RegFile.\n    Variable rfInit: ConstT (Vector (Data dataBytes) rfIdx).\n\n    Definition regFile := MODULE {\n      Register \"rf\" : Vector (Data dataBytes) rfIdx <- rfInit\n\n      with Method \"getRf1\" () : Vector (Data dataBytes) rfIdx :=\n        Read rf <- \"rf\";\n        Ret #rf\n\n      with Method \"getRf2\" () : Vector (Data dataBytes) rfIdx :=\n        Read rf <- \"rf\";\n        Ret #rf\n\n      with Method \"setRf\" (rf: Vector (Data dataBytes) rfIdx) : Void :=\n        Write \"rf\" <- #rf;\n        Retv\n    }.\n      \n    Definition getRf1 := MethodSig \"getRf1\"() : Vector (Data dataBytes) rfIdx.\n    Definition getRf2 := MethodSig \"getRf2\"() : Vector (Data dataBytes) rfIdx.\n    Definition setRf := MethodSig \"setRf\"(Vector (Data dataBytes) rfIdx) : Void.\n\n  End RegFile.\n\n  Section Epoch.\n    \n    Definition epoch := MODULE {\n      Register \"eEpoch\" : Bool <- false\n\n      with Method \"getEpoch\" () : Bool :=\n        Read epoch <- \"eEpoch\";\n        Ret #epoch\n\n      with Method \"toggleEpoch\" () : Void :=\n        Read epoch <- \"eEpoch\";\n        Write \"eEpoch\" <- !#epoch;\n        Retv\n    }.\n\n    Definition getEpoch := MethodSig \"getEpoch\"() : Bool.\n    Definition toggleEpoch := MethodSig \"toggleEpoch\"() : Void.\n\n  End Epoch.\n\n  Section ScoreBoard.\n\n    Definition scoreBoard := MODULE {\n      Register \"sbFlags\" : Vector Bool rfIdx <- Default\n                                 \n      with Method \"sbSearch1_Ld\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n\n      with Method \"sbSearch2_Ld\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n\n      with Method \"sbSearch1_St\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n            \n      with Method \"sbSearch2_St\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n\n      with Method \"sbSearch1_Nm\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n            \n      with Method \"sbSearch2_Nm\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n\n      with Method \"sbSearch3_Nm\" (sidx: Bit rfIdx) : Bool :=\n        Read flags <- \"sbFlags\";\n        Ret #flags@[#sidx]\n            \n      with Method \"sbInsert\" (nidx: Bit rfIdx) : Void :=\n        Read flags <- \"sbFlags\";\n        Write \"sbFlags\" <- #flags@[#nidx <- $$true];\n        Retv\n\n      with Method \"sbRemove\" (nidx: Bit rfIdx) : Void :=\n        Read flags <- \"sbFlags\";\n        Write \"sbFlags\" <- #flags@[#nidx <- $$false];\n        Retv\n    }.\n\n    Definition sbSearch1_Ld := MethodSig \"sbSearch1_Ld\"(Bit rfIdx) : Bool.\n    Definition sbSearch2_Ld := MethodSig \"sbSearch2_Ld\"(Bit rfIdx) : Bool.\n    Definition sbSearch1_St := MethodSig \"sbSearch1_St\"(Bit rfIdx) : Bool.\n    Definition sbSearch2_St := MethodSig \"sbSearch2_St\"(Bit rfIdx) : Bool.\n    Definition sbSearch1_Nm := MethodSig \"sbSearch1_Nm\"(Bit rfIdx) : Bool.\n    Definition sbSearch2_Nm := MethodSig \"sbSearch2_Nm\"(Bit rfIdx) : Bool.\n    Definition sbSearch3_Nm := MethodSig \"sbSearch3_Nm\"(Bit rfIdx) : Bool.\n    Definition sbInsert := MethodSig \"sbInsert\"(Bit rfIdx) : Void.\n    Definition sbRemove := MethodSig \"sbRemove\"(Bit rfIdx) : Void.\n    \n  End ScoreBoard.\n\n  Section FetchDecode.\n    Variable (pcInit : ConstT (Pc addrSize)).\n\n    Definition fetchDecode := MODULE {\n      Register \"pc\" : Pc addrSize <- pcInit\n      with Register \"pinit\" : Bool <- Default\n      with Register \"pinitRq\" : Bool <- Default\n      with Register \"pinitRqOfs\" : Bit iaddrSize <- Default\n      with Register \"pinitRsOfs\" : Bit iaddrSize <- Default\n      with Register \"pgm\" : Vector (Data instBytes) iaddrSize <- Default\n      with Register \"fEpoch\" : Bool <- false\n\n      (** Phase 1: initialize the program [pinit == false] *)\n\n      with Rule \"pgmInitRq\" :=\n        Read pinit <- \"pinit\";\n        Assert !#pinit;\n        Read pinitRq <- \"pinitRq\";\n        Assert !#pinitRq;\n        Read pinitRqOfs : Bit iaddrSize <- \"pinitRqOfs\";\n        Assert ((UniBit (Inv _) #pinitRqOfs) != $0);\n\n        Call memReq(STRUCT { \"addr\" ::= toAddr _ pinitRqOfs;\n                             \"op\" ::= $$false;\n                             \"byteEn\" ::= $$Default;\n                             \"data\" ::= $$Default });\n        Write \"pinitRqOfs\" <- #pinitRqOfs + $1;\n        Retv\n\n      with Rule \"pgmInitRqEnd\" :=\n        Read pinit <- \"pinit\";\n        Assert !#pinit;\n        Read pinitRq <- \"pinitRq\";\n        Assert !#pinitRq;\n        Read pinitRqOfs : Bit iaddrSize <- \"pinitRqOfs\";\n        Assert ((UniBit (Inv _) #pinitRqOfs) == $0);\n        Call memReq(STRUCT { \"addr\" ::= toAddr _ pinitRqOfs;\n                             \"op\" ::= $$false;\n                             \"byteEn\" ::= $$Default;\n                             \"data\" ::= $$Default });\n        Write \"pinitRq\" <- $$true;\n        Write \"pinitRqOfs\" : Bit iaddrSize <- $0;\n        Retv\n        \n      with Rule \"pgmInitRs\" :=\n        Read pinit <- \"pinit\";\n        Assert !#pinit;\n        Read pinitRsOfs : Bit iaddrSize <- \"pinitRsOfs\";\n        Assert ((UniBit (Inv _) #pinitRsOfs) != $0);\n\n        Call ldData <- memRep();\n        LET ldVal <- #ldData!RsToProc@.\"data\";\n        LET inst <- alignInst _ ldVal;\n        Read pgm <- \"pgm\";\n        Write \"pgm\" <- #pgm@[#pinitRsOfs <- #inst];\n        Write \"pinitRsOfs\" <- #pinitRsOfs + $1;\n        Retv\n\n      with Rule \"pgmInitRsEnd\" :=\n        Read pinit <- \"pinit\";\n        Assert !#pinit;\n        Read pinitRsOfs : Bit iaddrSize <- \"pinitRsOfs\";\n        Assert ((UniBit (Inv _) #pinitRsOfs) == $0);\n\n        Call ldData <- memRep();\n        LET ldVal <- #ldData!RsToProc@.\"data\";\n        LET inst <- alignInst _ ldVal;\n        Read pgm <- \"pgm\";\n        Write \"pgm\" <- #pgm@[#pinitRsOfs <- #inst];\n        Write \"pinit\" <- !#pinit;\n        Write \"pinitRsOfs\" : Bit iaddrSize <- $0;\n        Retv\n\n      (** Phase 2: fetch/decode the program [pinit == true] *)\n          \n      with Rule \"modifyPc\" :=\n        Read pinit <- \"pinit\";\n        Assert #pinit;\n        Call correctPc <- w2dDeq();\n        Write \"pc\" <- #correctPc!W2DStr@.\"nextPc\";\n        Read pEpoch <- \"fEpoch\";\n        Write \"fEpoch\" <- !#pEpoch;\n        Retv\n          \n      with Rule \"instFetchLd\" :=\n        Read pinit <- \"pinit\";\n        Call w2dFull <- w2dFull();\n        Assert !#w2dFull;\n        Read ppc : Pc addrSize <- \"pc\";\n        Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n        Assert #pinit;\n        LET rawInst <- #pgm@[toIAddr _ ppc];\n        Call rf <- getRf1();\n\n        Nondet npc : SyntaxKind (Pc addrSize);\n        Read epoch <- \"fEpoch\";\n        Write \"pc\" <- #npc;\n\n        LET opType <- getOptype _ rawInst;\n        Assert (#opType == $$opLd);\n\n        LET srcIdx <- getLdSrc _ rawInst;\n        LET dst <- getLdDst _ rawInst;\n        Call stall1 <- sbSearch1_Ld(#srcIdx);\n        Call stall2 <- sbSearch2_Ld(#dst);\n        Assert !(#stall1 || #stall2);\n        LET addr <- getLdAddr _ rawInst;\n        LET srcVal <- #rf@[#srcIdx];\n        LET laddr <- calcLdAddr _ addr srcVal;\n        Call d2eEnq(d2ePack #opType #dst #laddr $$Default $$Default $$Default\n                            #rawInst #ppc #npc #epoch);\n        Call sbInsert(#dst);\n        Retv\n\n      with Rule \"instFetchSt\" :=\n        Read pinit <- \"pinit\";\n        Call w2dFull <- w2dFull();\n        Assert !#w2dFull;\n        Read ppc : Pc addrSize <- \"pc\";\n        Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n        Assert #pinit;\n        LET rawInst <- #pgm@[toIAddr _ ppc];\n        Call rf <- getRf1();\n\n        Nondet npc: SyntaxKind (Pc addrSize);\n        Read epoch <- \"fEpoch\";\n        Write \"pc\" <- #npc;\n\n        LET opType <- getOptype _ rawInst;\n        Assert (#opType == $$opSt);\n\n        LET srcIdx <- getStSrc _ rawInst;\n        LET vsrcIdx <- getStVSrc _ rawInst;\n        Call stall1 <- sbSearch1_St(#srcIdx);\n        Call stall2 <- sbSearch2_St(#vsrcIdx);\n        Assert !(#stall1 || #stall2);\n\n        LET addr <- getStAddr _ rawInst;\n        LET srcVal <- #rf@[#srcIdx];\n        LET stVal <- #rf@[#vsrcIdx];\n        LET saddr <- calcStAddr _ addr srcVal;\n        LET byteEn <- calcStByteEn _ rawInst;\n        Call d2eEnq(d2ePack #opType $$Default #saddr #byteEn #stVal $$Default\n                            #rawInst #ppc #npc #epoch);\n        Retv\n\n      with Rule \"instFetchNm\" :=\n        Read pinit <- \"pinit\";\n        Call w2dFull <- w2dFull();\n        Assert !#w2dFull;\n        Read ppc : Pc addrSize <- \"pc\";\n        Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n        Assert #pinit;\n        LET rawInst <- #pgm@[toIAddr _ ppc];\n        Call rf <- getRf1();\n\n        Nondet npc: SyntaxKind (Pc addrSize);\n        Read epoch <- \"fEpoch\";\n        Write \"pc\" <- #npc;\n\n        LET opType <- getOptype _ rawInst;\n        Assert (#opType == $$opNm);\n\n        LET dst <- getDst _ rawInst;\n        LET idx1 <- getSrc1 _ rawInst;\n        LET idx2 <- getSrc2 _ rawInst;\n        Call stall1 <- sbSearch1_Nm(#idx1);\n        Call stall2 <- sbSearch2_Nm(#idx2);\n        Call stall3 <- sbSearch3_Nm(#dst);\n        Assert !(#stall1 || #stall2 || #stall3);\n\n        LET val1 <- #rf@[#idx1];\n        LET val2 <- #rf@[#idx2];\n        \n        Call d2eEnq(d2ePack #opType #dst $$Default $$Default #val1 #val2\n                            #rawInst #ppc #npc #epoch);\n        Call sbInsert(#dst);\n        Retv\n    }.\n\n  End FetchDecode.\n\n  Section Execute.\n\n    Definition executer := MODULE {\n      Rule \"execNm\" :=\n        Call rf <- getRf2();\n        Call d2e <- d2eDeq();\n        LET ppc <- d2eCurPc _ d2e;\n        Assert d2eOpType _ d2e == $$opNm;\n        \n        LET rawInst <- d2eRawInst _ d2e;\n        LET val1 <- d2eVal1 _ d2e;\n        LET val2 <- d2eVal2 _ d2e;\n        LET execVal <- doExec _ val1 val2 ppc rawInst;\n        Call e2wEnq (e2wPack #d2e #execVal);\n        Retv\n\n      with Rule \"execBypass\" :=\n        Call rf <- getRf2();\n        Call d2e <- d2eDeq();\n        Assert d2eOpType _ d2e != $$opNm;\n        Call e2wEnq (e2wPack #d2e $$Default);\n        Retv\n    }.\n\n  End Execute.\n\n  Section WriteBack.\n    \n    Definition commitPc {ty} ppc npcp st rawInst :=\n      (Write \"lastPc\" <- #ppc;\n       LET npc <- getNextPc ty st ppc rawInst;\n       If (#npc != #npcp)\n       then\n         Call toggleEpoch();\n         Call w2dEnq(STRUCT { \"prevPc\" ::= #ppc;\n                              \"nextPc\" ::= #npc });\n         Retv\n       else\n         Retv\n        as _;\n         Retv)%kami_action.\n\n    Definition wb := MODULE {\n      Register \"stall\" : Bool <- false\n      with Register \"stalled\" : d2eElt <- Default\n      with Register \"lastPc\" : Pc addrSize <- Default\n                                       \n      with Rule \"wrongEpoch\" :=\n        Read stall <- \"stall\";\n        Assert !#stall;\n        Call e2w <- e2wDeq();\n        LET d2e <- e2wDecInst _ e2w;\n        LET fEpoch <- d2eEpoch _ d2e;\n        Call eEpoch <- getEpoch();\n        Assert (#fEpoch != #eEpoch);\n\n        If (d2eOpType _ d2e == $$opLd || d2eOpType _ d2e == $$opNm)\n        then\n          LET dst <- d2eDst _ d2e;\n          Call sbRemove(#dst);\n          Retv\n        else\n          Retv\n        as _;\n        Retv\n\n      with Rule \"reqLd\" :=\n        Read stall <- \"stall\";\n        Assert !#stall;\n        Call e2w <- e2wDeq();\n        LET d2e <- e2wDecInst _ e2w;\n\n        LET fEpoch <- d2eEpoch _ d2e;\n        Call eEpoch <- getEpoch();\n        Assert (#fEpoch == #eEpoch);\n\n        Assert d2eOpType _ d2e == $$opLd;\n        LET laddr <- d2eAddr _ d2e;\n        Call memReq(STRUCT { \"addr\" ::= #laddr;\n                             \"op\" ::= $$false;\n                             \"byteEn\" ::= $$Default;\n                             \"data\" ::= $$Default });\n        Write \"stall\" <- $$true;\n        Write \"stalled\" <- #d2e;\n        Retv\n                        \n      with Rule \"reqSt\" :=\n        Read stall <- \"stall\";\n        Assert !#stall;\n        Call e2w <- e2wDeq();\n        LET d2e <- e2wDecInst _ e2w;\n\n        LET fEpoch <- d2eEpoch _ d2e;\n        Call eEpoch <- getEpoch();\n        Assert (#fEpoch == #eEpoch);\n\n        Assert d2eOpType _ d2e == $$opSt;\n        LET saddr <- d2eAddr _ d2e;\n        LET byteEn <- d2eByteEn _ d2e;\n        Call memReq(STRUCT { \"addr\" ::= #saddr;\n                             \"op\" ::= $$true;\n                             \"byteEn\" ::= #byteEn;\n                             \"data\" ::= d2eVal1 _ d2e });\n        Write \"stall\" <- $$true;\n        Write \"stalled\" <- #d2e;\n        Retv\n                                \n      with Rule \"repLd\" :=\n        Read stall <- \"stall\";\n        Assert #stall;\n        Call val <- memRep();\n        Call rf <- getRf2();\n        Read stalled : d2eElt <- \"stalled\";\n        Assert d2eOpType _ stalled == $$opLd;\n        LET dst <- d2eDst _ stalled;\n        Assert (#dst != $0);\n\n        LET rawInst <- d2eRawInst _ stalled;\n        LET laddr <- d2eAddr _ stalled;\n        LET ldValWord <- #val!RsToProc@.\"data\";\n        LET ldType <- getLdType _ rawInst;\n        LET ldVal <- calcLdVal _ laddr ldValWord ldType;\n        Call setRf (#rf@[#dst <- #ldVal]);\n        \n        Call sbRemove(#dst);\n        Write \"stall\" <- $$false;\n        LET ppc <- d2eCurPc _ stalled;\n        LET npcp <- d2eNextPc _ stalled;\n        LET rawInst <- d2eRawInst _ stalled;\n        commitPc ppc npcp rf rawInst\n\n      with Rule \"repLdZ\" :=\n        Read stall <- \"stall\";\n        Assert #stall;\n        Call val <- memRep();\n        Call rf <- getRf2();\n        Read stalled : d2eElt <- \"stalled\";\n        Assert d2eOpType _ stalled == $$opLd;\n        LET dst <- d2eDst _ stalled;\n        Assert (#dst == $0);\n        Call sbRemove(#dst);\n        Write \"stall\" <- $$false;\n        LET ppc <- d2eCurPc _ stalled;\n        LET npcp <- d2eNextPc _ stalled;\n        LET rawInst <- d2eRawInst _ stalled;\n        commitPc ppc npcp rf rawInst\n\n      with Rule \"repSt\" :=\n        Read stall <- \"stall\";\n        Assert #stall;\n        Call val <- memRep();\n        Call rf <- getRf2();\n        Read stalled : d2eElt <- \"stalled\";\n        Assert d2eOpType _ stalled == $$opSt;\n        Write \"stall\" <- $$false;\n        LET ppc <- d2eCurPc _ stalled;\n        LET npcp <- d2eNextPc _ stalled;\n        LET rawInst <- d2eRawInst _ stalled;\n        commitPc ppc npcp rf rawInst\n                                \n      with Rule \"wbNm\" :=\n        Read stall <- \"stall\";\n        Assert !#stall;\n        Call rf <- getRf2();\n        Call e2w <- e2wDeq();\n        LET d2e <- e2wDecInst _ e2w;\n\n        LET fEpoch <- d2eEpoch _ d2e;\n        Call eEpoch <- getEpoch();\n        Assert (#fEpoch == #eEpoch);\n\n        Assert d2eOpType _ d2e == $$opNm;\n        LET dst <- d2eDst _ d2e;\n        Assert (#dst != $0);\n        LET val <- e2wVal _ e2w;\n        Call setRf(#rf@[#dst <- #val]);\n        Call sbRemove(#dst);\n        LET ppc <- d2eCurPc _ d2e;\n        LET npcp <- d2eNextPc _ d2e;\n        LET rawInst <- d2eRawInst _ d2e;\n        commitPc ppc npcp rf rawInst\n\n      with Rule \"wbNmZ\" :=\n        Read stall <- \"stall\";\n        Assert !#stall;\n        Call rf <- getRf2();\n        Call e2w <- e2wDeq();\n        LET d2e <- e2wDecInst _ e2w;\n\n        LET fEpoch <- d2eEpoch _ d2e;\n        Call eEpoch <- getEpoch();\n        Assert (#fEpoch == #eEpoch);\n\n        Assert d2eOpType _ d2e == $$opNm;\n        LET dst <- d2eDst _ d2e;\n        Assert (#dst == $0);\n        Call sbRemove(#dst);\n        LET ppc <- d2eCurPc _ d2e;\n        LET npcp <- d2eNextPc _ d2e;\n        LET rawInst <- d2eRawInst _ d2e;\n        commitPc ppc npcp rf rawInst\n    }.\n    \n  End WriteBack.\n\n  Definition procThreeStage (init: ProcInit addrSize dataBytes rfIdx) :=\n    ((fetchDecode (pcInit init))\n       ++ regFile (rfInit init)\n       ++ scoreBoard\n       ++ PrimFifo.fifo PrimFifo.primPipelineFifoName d2eFifoName d2eElt\n       ++ PrimFifo.fifoF PrimFifo.primBypassFifoName w2dFifoName w2dElt\n       ++ executer\n       ++ epoch\n       ++ PrimFifo.fifo PrimFifo.primPipelineFifoName e2wFifoName e2wElt\n       ++ wb)%kami.\n\nEnd ProcThreeStage.\n\n#[global] Hint Unfold regFile scoreBoard fetchDecode executer epoch wb procThreeStage : ModuleDefs.\n#[global] Hint Unfold RqFromProc RsToProc memReq memRep\n     d2eFifoName d2eEnq d2eDeq\n     W2DStr w2dElt w2dFifoName w2dEnq w2dDeq w2dFull\n     getRf1 getRf2 setRf getEpoch toggleEpoch\n     e2wFifoName e2wEnq e2wDeq\n     sbSearch1_Ld sbSearch2_Ld sbSearch1_St sbSearch2_St\n     sbSearch1_Nm sbSearch2_Nm sbSearch3_Nm\n     sbInsert sbRemove\n     commitPc : MethDefs.\n\nSection ProcThreeStageM.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n\n  Definition p3st init :=\n    procThreeStage fetch dec exec\n                   d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                   d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                   e2wPack e2wDecInst e2wVal\n                   init.\n\nEnd ProcThreeStageM.\n\n#[global] Hint Unfold p3st : ModuleDefs.\n\nSection Facts.\n  Variable inName outName: string.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wDst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n\n  Lemma regFile_ModEquiv:\n    forall init, ModPhoasWf (@regFile dataBytes rfIdx init).\n  Proof. kequiv. Qed.\n  #[local] Hint Resolve regFile_ModEquiv.\n\n  Lemma scoreBoard_ModEquiv:\n    ModPhoasWf (scoreBoard rfIdx).\n  Proof. kequiv. Qed.\n  #[local] Hint Resolve scoreBoard_ModEquiv.\n\n  Lemma fetchDecode_ModEquiv:\n    forall pcInit,\n      ModPhoasWf (fetchDecode fetch dec d2ePack pcInit).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve fetchDecode_ModEquiv.\n\n  Lemma executer_ModEquiv:\n    ModPhoasWf (executer exec d2eOpType d2eVal1 d2eVal2 d2eRawInst d2eCurPc e2wPack).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve executer_ModEquiv.\n\n  Lemma epoch_ModEquiv:\n    ModPhoasWf epoch.\n  Proof. kequiv. Qed.\n  #[local] Hint Resolve epoch_ModEquiv.\n  \n  Lemma wb_ModEquiv:\n    ModPhoasWf (wb dec exec\n                   d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1\n                   d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                   e2wDecInst e2wVal).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve wb_ModEquiv.\n  \n  Lemma procThreeStage_ModEquiv:\n    forall init,\n      ModPhoasWf (p3st fetch dec exec\n                       d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                       d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                       e2wPack e2wDecInst e2wVal init).\n  Proof.\n    kequiv.\n  Qed.\n\nEnd Facts.\n\n#[global] Hint Resolve regFile_ModEquiv\n     scoreBoard_ModEquiv\n     fetchDecode_ModEquiv\n     executer_ModEquiv\n     epoch_ModEquiv\n     wb_ModEquiv\n     procThreeStage_ModEquiv.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/ProcThreeStage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.1787912275382378}}
{"text": "From Paco Require Import paco.\n\nFrom CTree Require Import\n\t   CTree Eq Interp.Internalize Interp.FoldCTree.\n\n(* Universe issue, TO FIX *)\nUnset Universe Checking.\nUnset Auto Template Polymorphism.\n\nFrom ITree Require Import\n\t   ITree Eq Interp InterpFacts.\n\nFrom Coq Require Import\n\t   Morphisms Program.\nOpen Scope ctree.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nDefinition h_embed {E C} : E ~> ctree E C :=\n  fun _ e => CTree.trigger e.\nDefinition embed' {E} : itree E ~> ctree E (B01) := interp h_embed.\nDefinition embed {E C} : itree (C +' E) ~> ctree E (B01 +' C) :=\n  fun _ t => internalize (embed' t).\n\nNotation \"t '-' l '\u2192' u\" := (trans l t u)\n                              (at level 50, only printing,\n                                format \"t  '-' l '\u2192'  u\").\n\nNotation \"t '-' l '\u2192' u\" := (transR l t u)\n                              (at level 50, only printing,\n                                format \"t  '-' l '\u2192'  u\").\n\n#[local] Notation iobserve  := observe.\n#[local] Notation _iobserve := _observe.\n#[local] Notation cobserve  := CTreeDefinitions.observe.\n#[local] Notation _cobserve := CTreeDefinitions._observe.\n#[local] Notation iRet x    := (Ret x).\n#[local] Notation iVis e k  := (Vis e k).\n#[local] Notation iTau t    := (Tau t).\n#[local] Notation cRet x    := (CTreeDefinitions.Ret x).\n#[local] Notation cGuard t   := (CTreeDefinitions.Guard t).\n#[local] Notation cVis e k  := (CTreeDefinitions.Vis e k).\n\n(** Unfolding of [interp]. *)\nDefinition _interp {E F C R} `{B1 -< C} (f : E ~> ctree F C) (ot : itreeF E R _)\n  : ctree F C R :=\n  match ot with\n  | RetF r => CTreeDefinitions.Ret r\n  | TauF t => cGuard (interp f t)\n  | VisF e k => CTree.bind (f _ e) (fun x => cGuard (interp f (k x)))\n  end.\n\nLemma unfold_interp_ctree {E F C X} `{B1 -< C} (h: E ~> ctree F C) (t : itree E X):\n  (interp h t \u2245 _interp h (iobserve t))%ctree.\nProof.\n  revert t.\n  coinduction R CIH.\n  intros; cbn*.\n  Opaque CTree.bind.\n  unfold cobserve; cbn.\n  destruct (iobserve t) eqn:ot; try now cbn; auto.\n  match goal with\n    |- equb _ _ (_cobserve ?t) (_cobserve ?u) =>\n      fold (cobserve t);\n      fold (cobserve u)\n  end.\n  Transparent CTree.bind.\n  cbn.\n  rewrite Equ.bind_map.\n  apply (fbt_bt (@bind_ctx_equ_t F _ X0 X0 X X eq eq) R), in_bind_ctx.\n  reflexivity.\n  intros ? ? <-.\n  constructor; intros ?.\n  reflexivity.\nQed.\n\n#[global] Instance embed_eq {E C X}:\n\tProper (eq_itree eq ==> equ eq) (@embed E C X).\nProof.\n\tunfold Proper, respectful.\n\tcoinduction r CIH.\n\tintros t u bisim. unfold embed, embed', internalize.\n  rewrite 2 unfold_interp_ctree.\n  rewrite 2 FoldCTree.unfold_interp.\n\tpunfold bisim.\n\tinv bisim; pclearbot; try easy.\n\t- cbn*.\n    constructor; intros ?.\n    step.\n    cbn*.\n    constructor; intros ?.\n    now apply CIH.\n\t- cbn.\n    upto_bind_eq.\n    constructor; intros ?.\n    rewrite 2 FoldCTree.unfold_interp.\n    cbn.\n    step; cbn*.\n    constructor; intros ?.\n    step; cbn*.\n    constructor; intros ?.\n    apply CIH, REL.\nQed.\n\nFrom Coq Require Import Datatypes.\n\n(* This is actually not trivial.\n   There are two ways to encode itrees' taus:\n   - If we use tauI, then I believe we have eutt mapping to sbisim I believe.\n   Proving so however is tricky: [eutt] has a weird behavior that consists of\n   being allowed to either look at taus (tau/tau rule) or ignore them (asymmetric rules).\n   In contrast, [sbisim] can only ignore [tauI]. In the Tau/Tau case, it's therefore quite\n   unclear how the proof should proceed: fundamentally, the rule is useful in [eutt] if and\n   only if the computations are both [spin] from now on --- in all other cases it can be\n   replaced by two asymmetric rules.\n   And as it turns out, if it is indeed [spin] against [spin], then [sbisim] relate [spinI]\n   against itself as well.\n   But how do we turn this into a proof?\n   - If we use tauV, then [eutt] certainly does not map against sbisim --- actually, it maps\n   against [equ] as well in this case. However, I think it should map against [wbisim], but\n   that remains to be proved.\n\n *)\n\nNotation embed_ t :=\n  match iobserve t with\n  | RetF r => CTreeDefinitions.Ret r\n  | TauF t => cGuard (cGuard (embed t))\n  | VisF (inl1 e) k =>\n      match e,k with\n      | c, k => brS c (fun x => cGuard (cGuard (cGuard (embed (k x)))))\n      end\n  | VisF (inr1 e) k => CTreeDefinitions.vis e (fun x => cGuard (cGuard (cGuard (embed (k x)))))\n  end.\n\nLemma unfold_embed {E C X} (t : itree (C +' E) X) : (embed t \u2245 embed_ t)%ctree.\nProof.\n  unfold embed, embed', internalize at 1.\n  rewrite unfold_interp_ctree, FoldCTree.unfold_interp.\n  cbn.\n  destruct (iobserve t) eqn:EQ; cbn; auto.\n  - step; cbn.\n    constructor; intros ?.\n    step; cbn.\n    reflexivity.\n  - destruct e.\n    + cbn.\n      rewrite Equ.unfold_bind at 1.\n      cbn.\n      step; cbn; constructor; intros ?.\n      rewrite Equ.bind_ret_l.\n      step; cbn; constructor; intros ?.\n      rewrite FoldCTree.unfold_interp; cbn.\n      rewrite Equ.unfold_bind at 1.\n      step; cbn; constructor; intros ?.\n      rewrite Equ.bind_ret_l.\n      step; cbn; constructor; intros ?.\n      auto.\n    + cbn.\n      rewrite Equ.unfold_bind at 1.\n      cbn.\n      step; cbn; constructor; intros ?.\n      rewrite Equ.bind_ret_l.\n      step; cbn; constructor; intros ?.\n      rewrite FoldCTree.unfold_interp; cbn.\n      rewrite Equ.unfold_bind at 1.\n      step; cbn; constructor; intros ?.\n      rewrite Equ.bind_ret_l.\n      step; cbn; constructor; intros ?.\n      auto.\nQed.\n\nLemma trans_embed_inv E C X : forall (t1 : itree (C +' E) X) l t2',\n    trans l (embed t1) t2' ->\n    (exists r : X, (t2' \u2245 stuckD)%ctree /\\ l = val r)\n    \\/ exists t2, (t2' ~ @embed E C X t2)%ctree.\nProof.\n  unfold trans.\n  intros * TR.\n  cbn in TR; red in TR.\n  remember (embed t1) as et1.\n  cut (\n      ((et1 \u2245 embed t1)%ctree \\/ (et1 \u2245 cGuard (embed t1))%ctree) ->\n      (exists r : X, (t2' \u2245 stuckD)%ctree /\\ l = val r)\n      \\/ exists t2 : itree (C +' E) X, t2' ~ embed t2).\n\n  intros H; eapply H; eauto; left; subst; auto.\n  clear Heqet1.\n  revert t1.\n  dependent induction TR.\n  - intros ? EQ.\n    destruct EQ as [EQ | EQ].\n    + rewrite (unfold_embed t1) in EQ.\n      step in EQ.\n      rewrite <- x in EQ.\n      destruct (iobserve t1) eqn:EQ1; try now inv EQ.\n      * dependent induction EQ.\n        specialize (REL x0).\n        specialize (IHTR _ t2' (k x0) eq_refl).\n        edestruct IHTR; eauto.\n      * destruct e.\n        inv EQ.\n        inv EQ.\n    + step in EQ.\n      rewrite <- x in EQ.\n      clear x et1.\n      dependent induction EQ.\n      specialize (REL x0).\n      specialize (IHTR _ t2' (k x0) eq_refl).\n      edestruct IHTR; eauto.\n  - intros * EQ.\n    assert (t2' \u2245 t)%ctree by (step; now rewrite x).\n    setoid_rewrite H0.\n    clear t2' x H0.\n    setoid_rewrite <- H.\n    clear t H.\n    destruct EQ as [EQ | EQ].\n    + rewrite (ctree_eta et1), <- x1 in EQ;\n        clear et1 x1.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t1) eqn:EQ1; try now step in EQ; inv EQ.\n      destruct e; [| step in EQ; inv EQ].\n      step in EQ; dependent induction EQ.\n      setoid_rewrite (REL x0).\n      right.\n      eexists; rewrite !sb_guard.\n      reflexivity.\n    + rewrite (ctree_eta et1), <- x1 in EQ;\n        clear et1 x1.\n      step in EQ; inv EQ.\n\n  - intros * EQ.\n    assert (t2' \u2245 t)%ctree by (step; now rewrite x).\n    setoid_rewrite H0.\n    clear t2' x H0.\n    setoid_rewrite <- H.\n    clear t H.\n    destruct EQ as [EQ | EQ].\n    + rewrite (ctree_eta et1), <- x1 in EQ;\n        clear et1 x1.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t1) eqn:EQ1; try now step in EQ; inv EQ.\n      destruct e0.\n      step in EQ; inv EQ.\n      step in EQ; dependent induction EQ.\n      setoid_rewrite (REL x0).\n      right; eexists.\n      rewrite !sb_guard.\n      reflexivity.\n    + rewrite (ctree_eta et1), <- x1 in EQ;\n        clear et1 x1.\n      step in EQ; inv EQ.\n  - intros * EQ.\n    assert (t2' \u2245 br false branch0 k)%ctree by (step; now rewrite x).\n    setoid_rewrite H.\n    clear t2' x H.\n    destruct EQ as [EQ | EQ].\n    + rewrite (ctree_eta et1), <- x0 in EQ.\n      clear et1 x0.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t1) eqn:EQ1; try now step in EQ; inv EQ.\n      * dependent induction EQ.\n        left; eexists; split; eauto.\n\n        rewrite brD0_always_stuck; reflexivity.\n      * destruct e; step in EQ; inv EQ.\n    + step in EQ; rewrite <- x0 in EQ; inv EQ.\nQed.\n\n(* TODO THIS IS REDUNDANT WITH THE DEF IN FOLDCTREE! *)\nInductive productive {E X} : itree E X -> Prop :=\n| prod_ret {r t} (EQ: eq_itree eq t (Ret r)) : productive t\n| prod_vis {Y} {e : E Y} {k t} (EQ: eq_itree eq t (Vis e k)) : productive t\n| prod_tau {u t} (EQ: eq_itree eq t (Tau u)) (PROD : productive u) : productive t.\n\n#[global] Instance eq_itree_productive {E X} : Proper (eq_itree eq ==> flip impl) (@productive E X).\nProof.\n  intros t u EQ PR.\n  revert t EQ.\n  induction PR; intros.\n  - eapply prod_ret.\n    rewrite EQ0; eauto.\n  - eapply prod_vis.\n    rewrite EQ0; eauto.\n  - eapply prod_tau.\n    rewrite EQ0; eauto.\n    apply IHPR.\n    reflexivity.\nQed.\n\nLemma embed_trans_productive_aux E C X : forall l t (T u : ctree E (B01 +' C) X),\n    trans l T u ->\n    (equ eq T (embed t) \\/ equ eq T (cGuard (embed t))) ->\n    productive t.\nProof.\n  intros * TR EQ.\n  unfold trans in TR.\n  cbn in TR; red in TR.\n  CTreeDefinitions.genobs T oT.\n  CTreeDefinitions.genobs u ou.\n  revert T HeqoT u Heqou t EQ.\n  induction TR; intros.\n  - subst.\n    destruct EQ as [EQ | EQ].\n    + rewrite ctree_eta, <- HeqoT in EQ.\n      rewrite itree_eta.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t0); try now step in EQ; inv EQ.\n      * eapply prod_tau; [reflexivity|].\n        eapply IHTR.\n        reflexivity.\n        reflexivity.\n        step in EQ; dependent induction EQ.\n        specialize (REL x).\n        auto.\n      * destruct e; step in EQ; inv EQ.\n    + specialize (IHTR _ eq_refl _ eq_refl).\n      rewrite ctree_eta, <- HeqoT in EQ.\n      step in EQ; dependent induction EQ.\n      specialize (REL x).\n      apply IHTR.\n      auto.\n  - destruct EQ as [EQ | EQ].\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t0); try now step in EQ; inv EQ.\n      destruct e; eapply prod_vis; eauto.\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      step in EQ; inv EQ.\n  - destruct EQ as [EQ | EQ].\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t0); try now step in EQ; inv EQ.\n      destruct e0; eapply prod_vis; eauto.\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      step in EQ; inv EQ.\n  - destruct EQ as [EQ | EQ].\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      rewrite unfold_embed in EQ.\n      destruct (iobserve t); try now step in EQ; inv EQ.\n      eapply prod_ret; eauto.\n      eapply prod_vis; eauto.\n    + rewrite itree_eta.\n      rewrite ctree_eta, <- HeqoT in EQ.\n      step in EQ; inv EQ.\nQed.\n\nLemma embed_trans_productive E C X : forall l t (u : ctree E (B01 +' C) X),\n    trans l (embed t) u ->\n    productive t.\nProof.\n  intros * TR.\n  eapply embed_trans_productive_aux; eauto.\nQed.\n\nLemma embed_eutt {E C X}:\n  Proper (eutt eq ==> sbisim eq) (@embed E C X).\nProof.\n  unfold Proper,respectful.\n  coinduction ? CIH.\n  symmetric using idtac.\n  - intros * HR * EQ.\n    apply HR; symmetry; assumption.\n  - intros t u EUTT.\n    cbn; intros * TR.\n    pose proof embed_trans_productive TR as PROD.\n    revert u TR EUTT.\n    induction PROD.\n    + intros.\n      rewrite EQ in EUTT,TR.\n      rewrite unfold_embed in TR; cbn in TR.\n      pose proof trans_ret_inv TR as (EQ' & ->).\n      punfold EUTT; cbn in EUTT; red in EUTT.\n      remember (iobserve (iRet r)) as ot;\n        remember (iobserve u) as ou.\n      revert u Heqou.\n      induction EUTT; subst; pclearbot; try now inv Heqot.\n      * intros.\n        inv Heqot.\n        do 2 eexists; split; [|split].\n        rewrite unfold_embed, <- Heqou.\n        etrans.\n        all: reflexivity.\n      * intros.\n        edestruct IHEUTT; try reflexivity.\n        destruct H as (? & ? & ? & ->).\n        do 2 eexists; split; [|split].\n        rewrite unfold_embed, <- Heqou.\n        apply trans_guard, trans_guard; eauto.\n        assumption.\n        reflexivity.\n    + intros.\n      rewrite EQ in EUTT,TR.\n      rewrite unfold_embed in TR; cbn in TR.\n      destruct e.\n      * apply trans_brS_inv in TR; destruct TR as (? & EQ' & ->).\n        punfold EUTT; cbn in EUTT; red in EUTT.\n        remember (iobserve (iVis (inl1 c) k)) as ot;\n          remember (iobserve u) as ou.\n        revert u Heqou.\n        induction EUTT; subst; try now inv Heqot.\n        ** intros.\n           dependent induction Heqot.\n           do 2 eexists; split; [|split].\n           rewrite unfold_embed, <- Heqou.\n           etrans.\n           rewrite EQ'.\n           rewrite !sb_guard.\n           apply CIH.\n           pclearbot; apply REL.\n           reflexivity.\n        ** intros.\n           edestruct IHEUTT; try reflexivity.\n           destruct H as (? & ? & ? & ->).\n           do 2 eexists; split; [|split].\n           rewrite unfold_embed, <- Heqou.\n           apply trans_guard, trans_guard.\n           eauto.\n           assumption.\n           reflexivity.\n      * apply trans_vis_inv in TR; destruct TR as (? & EQ' & ->).\n        punfold EUTT; cbn in EUTT; red in EUTT.\n        remember (iobserve (iVis (inr1 e) k)) as ot;\n          remember (iobserve u) as ou.\n        revert u Heqou.\n        induction EUTT; subst; try now inv Heqot.\n        ** intros.\n           dependent induction Heqot.\n           do 2 eexists; split; [|split].\n           rewrite unfold_embed, <- Heqou.\n           etrans.\n           rewrite EQ'.\n           rewrite !sb_guard.\n           apply CIH.\n           pclearbot; apply REL.\n           reflexivity.\n        ** intros.           \n           edestruct IHEUTT; try reflexivity.\n           destruct H as (? & ? & ? & ->).\n           do 2 eexists; split; [|split].\n           rewrite unfold_embed, <- Heqou.\n           apply trans_guard, trans_guard.\n           eauto.\n           assumption.\n           reflexivity.\n    + intros.\n      rewrite EQ in EUTT,TR.\n      rewrite unfold_embed in TR; cbn in TR.\n      do 2 apply trans_guard_inv in TR.\n      apply IHPROD.\n      auto.\n      rewrite tau_eutt in EUTT; auto.\nQed.\n\n(* Other things to consider if time permitted:\n   - partial inverse\n   - embedded itrees are internally deterministic\n *)\n\n(* Maybe simpler to just write a coinductive relation *)\n(*Definition partial_inject {E X} : ctree E X -> itree E (option X) :=\n\tcofix _inject t :=\n\t match CTreeDefinitions.observe t with\n\t| CTreeDefinitions.RetF x => Ret (Some x)\n\t| @BrF _ _ _ _ n t =>\n\t\t(match n as x return n = x -> itree E (option X) with\n\t\t\t\t\t | O => fun _ => Ret None\n\t\t\t\t\t | 1 => fun pf => eq_rect_r\n\t \t\t\t\t\t\t\t\t\t\t\t\t\t(fun n1 : nat => (Fin.t n1 -> ctree E X) -> itree E (option X))\n\t \t\t\t\t\t\t\t\t\t\t\t\t\t(fun t2 : Fin.t 1 -> ctree E X => Tau (_inject (t2 Fin.F1)))\n\t \t\t\t\t\t\t\t\t\t\t\t\t\tpf t\n\t\t\t\t\t | _ => fun _ => Ret None\n\t\t end eq_refl)\n\t| CTreeDefinitions.VisF e k => Vis e (fun x => _inject (k x))\n\t end.\n\nDefinition option_rel {A B : Type} (R : A -> B -> Prop) : option A -> option B -> Prop :=\n\tfun x y => match x, y with\n\t|\tSome x, Some y => R x y\n\t| _, _ => False\n\tend.\n\n(* This is probably false: no reason for the embedding to succeed. *)\nLemma partial_inject_eq {E X} :\n\tProper (equ eq ==> eq_itree (option_rel eq)) (@partial_inject E X).\nAdmitted.*)\n\nVariant is_detF {E C X} `{B1 -< C} (is_det : ctree E C X -> Prop) : ctree E C X -> Prop :=\n| Ret_det : forall x, is_detF is_det (CTreeDefinitions.Ret x)\n| Vis_det : forall {Y} (e : E Y) k,\n\t(forall y, is_det (k y)) ->\n\tis_detF is_det (CTreeDefinitions.Vis e k)\n| Tau_det : forall t,\n\t(is_det t) ->\n\tis_detF is_det (CTreeDefinitions.Guard t).\n\nDefinition is_det {E C X} `{B1 -< C} := paco1 (@is_detF E C X _) bot1.\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/ITree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1787912259677374}}
{"text": "From stdpp Require Import gmap mapset.\nFrom iris.heap_lang Require Import proofmode notation.\nFrom iris.algebra Require Import auth frac gset gmap excl.\nFrom iris.base_logic Require Export invariants.\nFrom iris.base_logic Require Import cancelable_invariants.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.prelude Require Import options.\n\nFrom iris_examples.spanning_tree Require Import graph.\n\n(* children cofe *)\nCanonical Structure chlO := leibnizO (option loc * option loc).\n(* The graph monoid. *)\nDefinition graphN : namespace := nroot .@ \"SPT_graph\".\nDefinition graphUR : ucmra :=\n  optionUR (prodR fracR (gmapR loc (exclR chlO))).\n(* The monoid for talking about which nodes are marked.\nThese markings are duplicatable. *)\nDefinition markingUR : ucmra := gsetUR loc.\n\n(** The CMRA we need. *)\nClass graphG \u03a3 := GraphG\n  {\n    graph_marking_inG :> inG \u03a3 (authR markingUR);\n    graph_marking_name : gname;\n    graph_inG :> inG \u03a3 (authR graphUR);\n    graph_name : gname\n  }.\n(** The Functor we need. *)\n(*Definition graph\u03a3 : gFunctors := #[auth\u03a3 graphUR].*)\n\nSection marking_definitions.\n  Context `{irisGS heap_lang \u03a3, graphG \u03a3}.\n\n  Definition is_marked (l : loc) : iProp \u03a3 :=\n    own graph_marking_name (\u25ef {[ l ]}).\n\n  Global Instance marked_persistentP x : Persistent (is_marked x).\n  Proof. apply _. Qed.\n\n  Lemma dup_marked l : is_marked l \u22a3\u22a2 is_marked l \u2217 is_marked l.\n  Proof.  by rewrite /is_marked -own_op -auth_frag_op idemp_L. Qed.\n\n  Lemma new_marked {E} (m : markingUR) l :\n  own graph_marking_name (\u25cf m) ={E}=\u2217\n  own graph_marking_name (\u25cf (m \u22c5 ({[l]} : gset loc))) \u2217 is_marked l.\n  Proof.\n    iIntros \"H\". rewrite -own_op (comm _ m).\n    iMod (own_update with \"H\") as \"Y\"; eauto.\n    apply auth_update_alloc.\n    setoid_replace ({[l]} : gset loc) with (({[l]} : gset loc) \u22c5 \u2205) at 2\n      by (by rewrite right_id).\n    apply op_local_update_discrete; auto.\n  Qed.\n\n  Lemma already_marked {E} (m : gset loc) l : l \u2208 m \u2192\n    own graph_marking_name (\u25cf m) ={E}=\u2217\n    own graph_marking_name (\u25cf m) \u2217 is_marked l.\n  Proof.\n    iIntros (Hl) \"Hm\". iMod (new_marked with \"Hm\") as \"[H1 H2]\"; iFrame.\n    rewrite gset_op (comm _ m) (subseteq_union_1_L {[l]} m); trivial.\n    by apply elem_of_subseteq_singleton.\n  Qed.\n\nEnd marking_definitions.\n\n(* The monoid representing graphs *)\nDefinition Gmon := gmapR loc (exclR chlO).\n\nDefinition excl_chlC_chl (ch : exclR chlO) : option (option loc * option loc) :=\n  match ch with\n  | Excl w => Some w\n  | Excl_Bot => None\n  end.\n\nDefinition Gmon_graph (G : Gmon) : graph loc := omap excl_chlC_chl G.\n\nDefinition Gmon_graph_dom (G : Gmon) :\n  \u2713 G \u2192 dom (gset loc) (Gmon_graph G) = dom (gset _) G.\nProof.\n  intros Hvl; apply set_eq=> i. rewrite !elem_of_dom lookup_omap.\n  specialize (Hvl i). split.\n  - revert Hvl; case _ : (G !! i) => [[]|] //=; eauto.\n    intros _ [? Hgi]; inversion Hgi.\n  - intros Hgi; revert Hgi Hvl. intros [[] Hgi]; rewrite Hgi; inversion 1; eauto.\nQed.\n\nDefinition child_to_val (c : option loc) : val :=\n  match c with\n  | None => NONEV\n  | Some l => SOMEV #l\n  end.\n\n(* convert the data of a node to a value in the heap *)\nDefinition children_to_val (ch : option loc * option loc) : val :=\n  (child_to_val (ch.1), child_to_val (ch.2)).\n\nDefinition marked_graph := gmap loc (bool * (option loc * option loc)).\nIdentity Coercion marked_graph_gmap: marked_graph >-> gmap.\n\nDefinition of_graph_elem (G : Gmon) i v\n  : option (bool * (option loc * option loc)) :=\n  match Gmon_graph G !! i with\n  | Some w => Some (true, w)\n  | None => Some (false,v)\n  end.\n\nDefinition of_graph (g : graph loc) (G : Gmon) : marked_graph :=\n  map_imap (of_graph_elem G) g.\n\n(* facts *)\n\nGlobal Instance Gmon_graph_proper : Proper ((\u2261) ==> (=)) Gmon_graph.\nProof. solve_proper. Qed.\n\nLemma new_Gmon_dom (G : Gmon) x w :\n  dom (gset loc) (G \u22c5 {[x := w]}) = dom (gset loc) G \u222a {[x]}.\nProof. by rewrite dom_op dom_singleton_L. Qed.\n\nDefinition of_graph_empty (g : graph loc) :\n  of_graph g \u2205 = fmap (\u03bb x, (false, x)) g.\nProof.\n  apply: map_eq => i.\n  rewrite map_lookup_imap /of_graph_elem lookup_fmap lookup_omap //.\nQed.\n\nLemma of_graph_dom_eq g G :\n  \u2713 G \u2192 dom (gset loc) g = dom (gset loc) (Gmon_graph G) \u2192\n  of_graph g G = fmap (\u03bb x, (true, x) )(Gmon_graph G).\nProof.\n  intros HGvl. rewrite Gmon_graph_dom // => Hd. apply map_eq => i.\n  assert (Hd' : i \u2208 dom (gset _) g \u2194 i \u2208 dom (gset _) G) by (by rewrite Hd).\n  revert Hd'; clear Hd. specialize (HGvl i); revert HGvl.\n  rewrite /of_graph /of_graph_elem /Gmon_graph map_lookup_imap lookup_fmap\n    lookup_omap ?elem_of_dom.\n  case _ : (g !! i); case _ : (G !! i) => [[]|] /=; inversion 1; eauto;\n    intros [? ?];\n    match goal with\n      H : _ \u2192 @is_Some ?A None |- _ =>\n       assert (Hcn : @is_Some A None) by eauto;\n         destruct Hcn as [? Hcn]; inversion Hcn\n    end.\nQed.\n\nSection definitions.\n  Context `{heapGS \u03a3, graphG \u03a3}.\n\n  Definition own_graph (q : frac) (G : Gmon) : iProp \u03a3 :=\n    own graph_name (\u25ef (Some (q, G) : graphUR)).\n\n  Global Instance own_graph_proper q : Proper ((\u2261) ==> (\u22a3\u22a2)) (own_graph q).\n  Proof. solve_proper. Qed.\n\n  Definition heap_owns (M : marked_graph) (markings : gmap loc loc) : iProp \u03a3 :=\n    ([\u2217 map] l \u21a6 v \u2208 M, \u2203 (m : loc), \u231cmarkings !! l = Some m\u231d\n       \u2217 l \u21a6 (#m, children_to_val (v.2)) \u2217 m \u21a6 #(LitBool (v.1)))%I.\n\n  Definition graph_inv (g : graph loc) (markings : gmap loc loc) : iProp \u03a3 :=\n    (\u2203 (G : Gmon), own graph_name (\u25cf Some (1%Qp, G))\n      \u2217 own graph_marking_name (\u25cf dom (gset _) G)\n      \u2217 heap_owns (of_graph g G) markings \u2217 \u231cstrict_subgraph g (Gmon_graph G)\u231d\n    )%I.\n\n  Global Instance graph_inv_timeless g Mrk : Timeless (graph_inv g Mrk).\n  Proof. apply _. Qed.\n\n  Context `{cinvG \u03a3}.\n  Definition graph_ctx \u03ba g Mrk : iProp \u03a3 := cinv graphN \u03ba (graph_inv g Mrk).\n\n  Global Instance graph_ctx_persistent \u03ba g Mrk : Persistent (graph_ctx \u03ba g Mrk).\n  Proof. apply _. Qed.\n\nEnd definitions.\n\nNotation \"l [\u21a6] v\" := ({[l := Excl v]}) (at level 70, format \"l  [\u21a6]  v\").\n\nTypeclasses Opaque graph_ctx graph_inv own_graph.\n\nSection graph_ctx_alloc.\n  Context `{heapGS \u03a3, cinvG \u03a3, inG \u03a3 (authR markingUR), inG \u03a3 (authR graphUR)}.\n\n  Lemma graph_ctx_alloc (E : coPset) (g : graph loc) (markings : gmap loc loc)\n        (HNE : (nclose graphN) \u2286 E)\n  : ([\u2217 map] l \u21a6 v \u2208 g, \u2203 (m : loc), \u231cmarkings !! l = Some m\u231d\n       \u2217 l \u21a6 (#m, children_to_val v) \u2217 m \u21a6 #false)\n     ={E}=\u2217 \u2203 (Ig : graphG \u03a3) (\u03ba : gname), cinv_own \u03ba 1 \u2217 graph_ctx \u03ba g markings\n             \u2217 own_graph 1%Qp \u2205.\n  Proof using Type*.\n    iIntros \"H1\".\n    iMod (own_alloc (\u25cf (\u2205 : markingUR))) as (mn) \"H2\"; first by apply auth_auth_valid.\n    iMod (own_alloc (\u25cf (Some (1%Qp, \u2205 : Gmon) : graphUR)\n                      \u22c5 \u25ef (Some (1%Qp, \u2205 : Gmon) : graphUR))) as (gn) \"H3\".\n    { by apply auth_both_valid_discrete. }\n    iDestruct \"H3\" as \"[H31 H32]\".\n    set (Ig := GraphG _ _ mn _ gn).\n    iExists Ig.\n    iAssert (graph_inv g markings) with \"[H1 H2 H31]\" as \"H\".\n    { unfold graph_inv. iExists \u2205. rewrite dom_empty_L. iFrame \"H2 H31\".\n      iSplitL; [|iPureIntro].\n      - rewrite /heap_owns of_graph_empty  big_sepM_fmap; eauto.\n      - rewrite /Gmon_graph omap_empty; apply strict_subgraph_empty. }\n    iMod (cinv_alloc _ graphN with \"[H]\") as (\u03ba) \"[Hinv key]\".\n    { iNext. iExact \"H\". }\n    iExists \u03ba.\n    rewrite /own_graph /graph_ctx //=; by iFrame.\n  Qed.\n\nEnd graph_ctx_alloc.\n\nLemma marked_was_unmarked (G : Gmon) x v :\n  \u2713 ({[x := Excl v]} \u22c5 G) \u2192 G !! x = None.\nProof.\n  intros H2; specialize (H2 x).\n  revert H2; rewrite lookup_op lookup_singleton. intros H2.\n    by rewrite (excl_validN_inv_l O _ _ (proj1 (cmra_valid_validN _) H2 O)).\nQed.\n\nLemma mark_update_lookup_base (G : Gmon) x v :\n  \u2713 ({[x := Excl v]} \u22c5 G) \u2192 ({[x := Excl v]} \u22c5 G) !! x = Some (Excl v).\nProof.\n  intros H2; rewrite lookup_op lookup_singleton.\n  erewrite marked_was_unmarked; eauto.\nQed.\n\nLemma mark_update_lookup_ne_base (G : Gmon) x i v :\n  i \u2260 x \u2192 ({[x := Excl v]} \u22c5 G) !! i = G !! i.\nProof. intros H. by rewrite lookup_op lookup_singleton_ne //= left_id_L. Qed.\n\nLemma of_graph_dom g G : dom (gset loc) (of_graph g G) = dom (gset _) g.\nProof.\n  apply set_eq=>i.\n  rewrite ?elem_of_dom map_lookup_imap /of_graph_elem lookup_omap.\n  case _ : (g !! i) => [x|]; case _ : (G !! i) => [[]|] //=; split;\n  intros [? Hcn]; inversion Hcn; eauto.\nQed.\n\nLemma in_dom_of_graph (g : graph loc) (G : Gmon) x (b : bool) v :\n  \u2713 G \u2192 of_graph g G !! x = Some (b, v) \u2192 b \u2194 x \u2208 dom (gset _) G.\nProof.\n  rewrite /of_graph /of_graph_elem map_lookup_imap lookup_omap elem_of_dom.\n  intros Hvl; specialize (Hvl x); revert Hvl;\n  case _ : (g !! x) => [?|]; case _ : (G !! x) => [[] ?|] //=;\n    intros Hvl; inversion Hvl; try (inversion 1; subst); split;\n    try (inversion 1; fail); try (intros [? Hcn]; inversion Hcn; fail);\n    subst; eauto.\nQed.\n\nGlobal Instance of_graph_proper g : Proper ((\u2261) ==> (=)) (of_graph g).\nProof. solve_proper. Qed.\n\n\nLemma mark_update_lookup (g : graph loc) (G : Gmon) x v :\n  x \u2208 dom (gset loc) g \u2192\n  \u2713 ((x [\u21a6] v) \u22c5 G) \u2192 of_graph g ((x [\u21a6] v) \u22c5 G) !! x = Some (true, v).\nProof.\n  rewrite elem_of_dom /is_Some. intros [w H1] H2.\n  rewrite /of_graph /of_graph_elem map_lookup_imap H1 lookup_omap; simpl.\n  rewrite mark_update_lookup_base; trivial.\nQed.\n\nLemma mark_update_lookup_ne (g : graph loc) (G : Gmon) x i v :\n  i \u2260 x \u2192 of_graph g ((x [\u21a6] v) \u22c5 G) !! i = (of_graph g G) !! i.\nProof.\n  intros H. rewrite /of_graph /of_graph_elem ?map_lookup_imap ?lookup_omap; simpl.\n  rewrite mark_update_lookup_ne_base //=.\nQed.\n\nSection graph.\n  Context `{heapGS \u03a3, graphG \u03a3}.\n\n  Lemma own_graph_valid q G : own_graph q G \u22a2 \u2713 G.\n  Proof.\n    iIntros \"H\". unfold own_graph.\n    by iDestruct (own_valid with \"H\") as %[_ ?]%auth_frag_valid.\n  Qed.\n\n  Lemma auth_own_graph_valid q G : own graph_name (\u25cf Some (q, G))  \u22a2 \u2713 G.\n  Proof.\n    iIntros \"H\". unfold own_graph.\n    iDestruct (own_valid with \"H\") as %VAL.\n    move : VAL => /auth_auth_valid [_ ?] //.\n  Qed.\n\n  Lemma whole_frac (G G' : Gmon):\n    own graph_name (\u25cf Some (1%Qp, G)) \u2217 own_graph 1 G' \u22a2 \u231cG = G'\u231d.\n  Proof.\n    iIntros \"[H1 H2]\". rewrite /own_graph.\n    iCombine \"H1\" \"H2\" as \"H\".\n    iDestruct (own_valid with \"H\") as %[H1 H2]%auth_both_valid_discrete.\n    iPureIntro.\n    apply option_included in H1; destruct H1 as [H1|H1]; [inversion H1|].\n    destruct H1 as (u1 & u2 & Hu1 & Hu2 & H3);\n      inversion Hu1; inversion Hu2; subst.\n    destruct H3 as [[_ H31%leibniz_equiv]|H32]; auto.\n    inversion H32 as [[q x] H4].\n    inversion H4 as [H41 H42]; simpl in *.\n    assert (\u2713 (1 \u22c5 q)%Qp) by (rewrite -H41; done).\n    exfalso; eapply exclusive_l; eauto; typeclasses eauto.\n  Qed.\n\n  Lemma graph_divide q G G' :\n    own_graph q (G \u22c5 G') \u22a3\u22a2 own_graph (q / 2) G \u2217 own_graph (q / 2) G'.\n  Proof.\n    replace q with ((q / 2) + (q / 2))%Qp at 1 by (by rewrite Qp_div_2).\n      by rewrite /own_graph -own_op.\n  Qed.\n\n  Lemma mark_graph {E} (G : Gmon) q x w : G !! x = None \u2192\n    own graph_name (\u25cf Some (1%Qp, G)) \u2217 own_graph q \u2205\n    ={E}=\u2217\n    own graph_name (\u25cf Some (1%Qp, {[x := Excl w]} \u22c5 G)) \u2217 own_graph q (x [\u21a6] w).\n  Proof.\n    iIntros (Hx) \"H\". rewrite -?own_op.\n    iMod (own_update with \"H\") as \"H'\"; eauto.\n    apply auth_update, option_local_update, prod_local_update;\n      first done; simpl.\n    rewrite -{2}[(x [\u21a6] w)]right_id.\n    apply op_local_update_discrete; auto.\n    rewrite -insert_singleton_op; trivial. apply insert_valid; done.\n  Qed.\n\n  Lemma update_graph {E} (G : Gmon) q x w m :\n    G !! x = None \u2192\n    own graph_name (\u25cf Some (1%Qp, {[x := Excl m]} \u22c5 G))\n       \u2217 own_graph q (x [\u21a6] m)\n      \u22a2 |={E}=> own graph_name (\u25cf Some (1%Qp, {[x := Excl w]} \u22c5 G))\n                  \u2217 own_graph q (x [\u21a6] w).\n  Proof.\n    iIntros (Hx) \"H\". rewrite -?own_op.\n    iMod (own_update with \"H\") as \"H'\"; eauto.\n    apply auth_update, option_local_update, prod_local_update;\n      first done; simpl.\n    rewrite -!insert_singleton_op; trivial.\n    replace (<[x:=Excl w]> G) with (<[x:=Excl w]> (<[x:=Excl m]> G))\n      by (by rewrite insert_insert).\n    eapply singleton_local_update; first (by rewrite lookup_insert);\n    apply exclusive_local_update; done.\n  Qed.\n\n  Lemma graph_pointsto_marked (G : Gmon) q x w :\n    own graph_name (\u25cf Some (1%Qp, G)) \u2217 own_graph q (x [\u21a6] w)\n      \u22a2 \u231cG = {[x := Excl w]} \u22c5 (delete x G)\u231d.\n  Proof.\n    rewrite /own_graph -?own_op. iIntros \"H\".\n    iDestruct (own_valid with \"H\") as %[H1 H2]%auth_both_valid_discrete.\n    iPureIntro.\n    apply option_included in H1; destruct H1 as [H1|H1]; [inversion H1|].\n    destruct H1 as (u1 & u2 & Hu1 & Hu2 & H1);\n      inversion Hu1; inversion Hu2; subst.\n    destruct H1 as [[_ H11%leibniz_equiv]|H12]; simpl in *.\n    + by rewrite -H11 delete_singleton right_id_L.\n    + apply prod_included in H12; destruct H12 as [_ H12]; simpl in *.\n      rewrite -insert_singleton_op ?insert_delete_insert; last by rewrite lookup_delete.\n      apply: map_eq => i. apply leibniz_equiv, equiv_dist => n.\n      destruct (decide (x = i)); subst;\n        rewrite ?lookup_insert ?lookup_insert_ne //.\n      apply singleton_included_l in H12. destruct H12 as [y [H31 H32]].\n      rewrite H31 (Some_included_exclusive _ _ H32); try done.\n      destruct H2 as [H21 H22]; simpl in H22.\n      specialize (H22 i); revert H22; rewrite H31; done.\n  Qed.\n\n  Lemma graph_open (g :graph loc) (markings : gmap loc loc) (G : Gmon) x\n  : x \u2208 dom (gset _) g \u2192\n    own graph_name (\u25cf Some (1%Qp, G)) \u2217 heap_owns (of_graph g G) markings \u22a2\n    own graph_name (\u25cf Some (1%Qp, G))\n    \u2217 heap_owns (delete x (of_graph g G)) markings\n    \u2217 (\u2203 u : bool * (option loc * option loc), \u231cof_graph g G !! x = Some u\u231d\n         \u2217 \u2203 (m : loc), \u231cmarkings !! x = Some m\u231d \u2217 x \u21a6 (#m, children_to_val (u.2))\n           \u2217 m \u21a6 #(u.1)).\n  Proof.\n    iIntros (Hx) \"(Hg & Ha)\".\n    assert (Hid : x \u2208 dom (gset _) (of_graph g G)) by (by rewrite of_graph_dom).\n    revert Hid; rewrite elem_of_dom /is_Some. intros [y Hy].\n    rewrite /heap_owns -{1}(insert_id _ _ _ Hy) -insert_delete_insert.\n    rewrite big_sepM_insert; [|apply lookup_delete_None; auto].\n    iDestruct \"Ha\" as \"[H $]\". iFrame \"Hg\". iExists _; eauto.\n  Qed.\n\n  Lemma graph_close g markings G x :\n    heap_owns (delete x (of_graph g G)) markings\n    \u2217 (\u2203 u : bool * (option loc * option loc), \u231cof_graph g G !! x = Some u\u231d\n        \u2217 \u2203 (m : loc), \u231cmarkings !! x = Some m\u231d \u2217 x \u21a6 (#m, children_to_val (u.2))\n            \u2217 m \u21a6 #(u.1))\n    \u22a2 heap_owns (of_graph g G) markings.\n  Proof.\n    iIntros \"[Ha Hl]\". iDestruct \"Hl\" as (u) \"[Hu Hl]\". iDestruct \"Hu\" as %Hu.\n    rewrite /heap_owns -{2}(insert_id _ _ _ Hu) -insert_delete_insert.\n    rewrite big_sepM_insert; [|apply lookup_delete_None; auto]. by iFrame \"Ha\".\n  Qed.\n\n  Lemma marked_is_marked_in_auth (mr : gset loc) l :\n    own graph_marking_name (\u25cf mr) \u2217 is_marked l \u22a2 \u231cl \u2208 mr\u231d.\n  Proof.\n    iIntros \"H\". unfold is_marked. rewrite -own_op.\n    iDestruct (own_valid with \"H\") as %Hvl.\n    move : Hvl => /auth_both_valid_discrete [[z Hvl'] _].\n    iPureIntro.\n    rewrite Hvl' /= !gset_op !elem_of_union elem_of_singleton; tauto.\n  Qed.\n\n  Lemma marked_is_marked_in_auth_sepS (mr : gset loc) m :\n    own graph_marking_name (\u25cf mr) \u2217 ([\u2217 set] l \u2208 m, is_marked l) \u22a2 \u231cm \u2286 mr\u231d.\n  Proof.\n    iIntros \"[Hmr Hm]\". rewrite big_sepS_forall bi.pure_forall.\n    iIntros (x). rewrite bi.pure_impl. iIntros (Hx).\n    iApply marked_is_marked_in_auth.\n    iFrame. by iApply \"Hm\".\n  Qed.\n\nEnd graph.\n\n(* Graph properties *)\n\nLemma delete_marked g G x w :\n  delete x (of_graph g G) = delete x (of_graph g ((x [\u21a6] w) \u22c5 G)).\nProof.\n  apply: map_eq => i. destruct (decide (i = x)).\n  - subst; by rewrite ?lookup_delete.\n  - rewrite ?lookup_delete_ne //= /of_graph /of_graph_elem ?map_lookup_imap\n      ?lookup_omap; case _ : (g !! i) => [v|] //=.\n    by rewrite lookup_op lookup_singleton_ne //= left_id_L.\nQed.\n\nLemma in_dom_conv (G G' : Gmon) x : \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset loc) (Gmon_graph G)\n  \u2192 (Gmon_graph (G \u22c5 G')) !! x = (Gmon_graph G) !! x.\nProof.\n  intros HGG. specialize (HGG x). revert HGG.\n  rewrite /get_left /Gmon_graph elem_of_dom /is_Some ?lookup_omap lookup_op.\n  case _ : (G !! x) => [[]|]; case _ : (G' !! x) => [[]|]; do 2 inversion 1;\n    simpl in *; auto; congruence.\nQed.\nLemma in_dom_conv' (G G' : Gmon) x: \u2713(G \u22c5 G') \u2192 x \u2208 dom (gset loc) (Gmon_graph G')\n  \u2192 (Gmon_graph (G \u22c5 G')) !! x = (Gmon_graph G') !! x.\nProof. rewrite comm; apply in_dom_conv. Qed.\nLemma get_left_conv (G G' : Gmon) x xl : \u2713 (G \u22c5 G') \u2192\n  x \u2208 dom (gset _) (Gmon_graph G) \u2192 get_left (Gmon_graph (G \u22c5 G')) x = Some xl\n  \u2194 get_left (Gmon_graph G) x = Some xl.\nProof. intros. rewrite /get_left in_dom_conv; auto. Qed.\nLemma get_left_conv' (G G' : Gmon) x xl : \u2713 (G \u22c5 G') \u2192\n  x \u2208 dom (gset _) (Gmon_graph G') \u2192 get_left (Gmon_graph (G \u22c5 G')) x = Some xl\n  \u2194 get_left (Gmon_graph G') x = Some xl.\nProof. rewrite comm; apply get_left_conv. Qed.\nLemma get_right_conv (G G' : Gmon) x xl : \u2713 (G \u22c5 G') \u2192\n  x \u2208 dom (gset _) (Gmon_graph G) \u2192 get_right (Gmon_graph (G \u22c5 G')) x = Some xl\n  \u2194 get_right (Gmon_graph G) x = Some xl.\nProof. intros. rewrite /get_right in_dom_conv; auto. Qed.\nLemma get_right_conv' (G G' : Gmon) x xl : \u2713 (G \u22c5 G') \u2192\n  x \u2208 dom (gset _) (Gmon_graph G') \u2192 get_right (Gmon_graph (G \u22c5 G')) x = Some xl\n  \u2194 get_right (Gmon_graph G') x = Some xl.\nProof. rewrite comm; apply get_right_conv. Qed.\n\nLemma in_op_dom (G G' : Gmon) y : \u2713(G \u22c5 G') \u2192\n  y \u2208 dom (gset loc) (Gmon_graph G) \u2192 y \u2208 dom (gset loc) (Gmon_graph (G \u22c5 G')).\nProof. refine (\u03bb H x, _ x); rewrite ?elem_of_dom ?in_dom_conv ; eauto. Qed.\nLemma in_op_dom' (G G' : Gmon) y : \u2713(G \u22c5 G') \u2192\n  y \u2208 dom (gset loc) (Gmon_graph G') \u2192 y \u2208 dom (gset loc) (Gmon_graph (G \u22c5 G')).\nProof. rewrite comm; apply in_op_dom. Qed.\n\nLocal Hint Resolve cmra_valid_op_l cmra_valid_op_r in_op_dom in_op_dom' : core.\n\nLemma in_op_dom_alt (G G' : Gmon) y : \u2713(G \u22c5 G') \u2192\n  y \u2208 dom (gset loc) G \u2192 y \u2208 dom (gset loc) (G \u22c5 G').\nProof. intros HGG; rewrite -?Gmon_graph_dom; eauto. Qed.\nLemma in_op_dom_alt' (G G' : Gmon) y : \u2713(G \u22c5 G') \u2192\n  y \u2208 dom (gset loc) G' \u2192 y \u2208 dom (gset loc) (G \u22c5 G').\nProof. intros HGG; rewrite -?Gmon_graph_dom; eauto. Qed.\n\nLocal Hint Resolve in_op_dom_alt in_op_dom_alt' : core.\nLocal Hint Extern 1 => eapply get_left_conv + eapply get_left_conv' +\n  eapply get_right_conv + eapply get_right_conv' : core.\n\nLocal Hint Extern 1 (_ \u2208 dom (gset loc) (Gmon_graph _)) =>\n  erewrite Gmon_graph_dom : core.\n\nLocal Hint Resolve path_start path_end : core.\n\nLemma path_conv (G G' : Gmon) x y p :\n  \u2713 (G \u22c5 G') \u2192 maximal (Gmon_graph G) \u2192 x \u2208 dom (gset _) G \u2192\n  valid_path (Gmon_graph (G \u22c5 G')) x y p \u2192 valid_path (Gmon_graph G) x y p.\nProof.\n  intros Hv Hm. rewrite -Gmon_graph_dom //=; eauto. revert x y.\n  induction p as [|[] p IHp]; inversion 2; subst; econstructor; eauto;\n    try eapply IHp; try eapply Hm; eauto.\nQed.\nLemma path_conv_back (G G' : Gmon) x y p :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset _) G \u2192\n  valid_path (Gmon_graph G) x y p \u2192 valid_path (Gmon_graph (G \u22c5 G')) x y p.\nProof.\n  intros Hv. rewrite -Gmon_graph_dom //=; eauto. revert x y.\n  induction p as [|[] p]; inversion 2; subst; econstructor; eauto.\nQed.\nLemma path_conv' (G G' : Gmon) x y p :\n  \u2713 (G \u22c5 G') \u2192 maximal (Gmon_graph G') \u2192 x \u2208 dom (gset _) G' \u2192\n  valid_path (Gmon_graph (G \u22c5 G')) x y p \u2192 valid_path (Gmon_graph G') x y p.\nProof. rewrite comm; eapply path_conv. Qed.\nLemma path_conv_back' (G G' : Gmon) x y p :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset _) G' \u2192\n  valid_path (Gmon_graph G') x y p \u2192 valid_path (Gmon_graph (G \u22c5 G')) x y p.\nProof. rewrite comm; apply path_conv_back. Qed.\n\nLocal Ltac in_dom_Gmon_graph :=\n  rewrite Gmon_graph_dom //= ?dom_op ?elem_of_union ?dom_singleton\n      ?elem_of_singleton.\n\nLemma get_left_singleton x vl vr :\n  get_left (Gmon_graph (x [\u21a6] (vl, vr))) x = vl.\nProof. rewrite /get_left /Gmon_graph lookup_omap lookup_singleton; done. Qed.\nLemma get_right_singleton x vl vr :\n  get_right (Gmon_graph (x [\u21a6] (vl, vr))) x = vr.\nProof. rewrite /get_right /Gmon_graph lookup_omap lookup_singleton; done. Qed.\n\nLemma graph_in_dom_op (G G' : Gmon) x :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset loc) G \u2192 x \u2209 dom (gset _) G'.\nProof.\n  intros HGG. specialize (HGG x). revert HGG. rewrite ?elem_of_dom lookup_op.\n  case _ : (G !! x) => [[]|]; case _ : (G' !! x) => [[]|]; inversion 1;\n  do 2 (intros [? Heq]; inversion Heq; clear Heq).\nQed.\nLemma graph_in_dom_op' (G G' : Gmon) x :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset loc) G' \u2192 x \u2209 dom (gset _) G.\nProof. rewrite comm; apply graph_in_dom_op. Qed.\nLemma graph_op_path (G G' : Gmon) x z p :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset _) G \u2192 valid_path (Gmon_graph G') z x p \u2192 False.\nProof.\n  intros ?? Hp%path_end; rewrite Gmon_graph_dom in Hp; eauto.\n  eapply graph_in_dom_op; eauto.\nQed.\nLemma graph_op_path' (G G' : Gmon) x z p :\n  \u2713 (G \u22c5 G') \u2192 x \u2208 dom (gset _) G' \u2192 valid_path (Gmon_graph G) z x p \u2192 False.\nProof. rewrite comm; apply graph_op_path. Qed.\n\nLemma in_dom_singleton (x : loc) (w : chlO) :\n  x \u2208 dom (gset loc) (x [\u21a6] w : gmap loc _).\nProof. by rewrite dom_singleton elem_of_singleton. Qed.\n\n\nLocal Hint Resolve graph_op_path graph_op_path' in_dom_singleton : core.\n\nLemma maximal_op (G G' : Gmon) : \u2713 (G \u22c5 G') \u2192 maximal (Gmon_graph G)\n  \u2192 maximal (Gmon_graph G') \u2192 maximal (Gmon_graph (G \u22c5 G')).\nProof.\n  intros Hvl [_ HG] [_ HG']. split; trivial => x v.\n  rewrite Gmon_graph_dom ?dom_op ?elem_of_union -?Gmon_graph_dom; eauto.\n  intros [Hxl|Hxr].\n  - erewrite get_left_conv, get_right_conv; eauto.\n  - erewrite get_left_conv', get_right_conv'; eauto.\nQed.\n\nLemma maximal_op_singleton (G : Gmon) x vl vr :\n  \u2713 ((x [\u21a6] (vl, vr)) \u22c5 G) \u2192 maximal(Gmon_graph G) \u2192\n  match vl with | Some xl => xl \u2208 dom (gset _) G | None => True end \u2192\n  match vr with | Some xr => xr \u2208 dom (gset _) G | None => True end \u2192\n  maximal (Gmon_graph ((x [\u21a6] (vl, vr)) \u22c5 G)).\nProof.\n  intros HGG [_ Hmx] Hvl Hvr; split; trivial => z v. in_dom_Gmon_graph.\n  intros [Hv|Hv]; subst.\n  - erewrite get_left_conv, get_right_conv, get_left_singleton,\n          get_right_singleton; eauto.\n    destruct vl as [xl|]; destruct vr as [xr|]; intros [Hl|Hr];\n      try inversion Hl; try inversion Hr; subst; eauto.\n  - erewrite get_left_conv', get_right_conv', <- Gmon_graph_dom; eauto.\nQed.\n\nLocal Hint Resolve maximal_op_singleton maximal_op get_left_singleton\n  get_right_singleton : core.\n\nLemma maximally_marked_tree_both (G G' : Gmon) x xl xr :\n  \u2713 ((x [\u21a6] (Some xl, Some xr)) \u22c5 (G \u22c5 G')) \u2192\n  xl \u2208 dom (gset _) G \u2192 tree (Gmon_graph G) xl \u2192 maximal (Gmon_graph G) \u2192\n  xr \u2208 dom (gset _) G' \u2192 tree (Gmon_graph G') xr \u2192 maximal (Gmon_graph G') \u2192\n  tree (Gmon_graph ((x [\u21a6] (Some xl, Some xr)) \u22c5 (G \u22c5 G'))) x \u2227\n  maximal (Gmon_graph ((x [\u21a6] (Some xl, Some xr)) \u22c5 (G \u22c5 G'))).\nProof.\n  intros Hvl Hxl tl ml Hxr tr mr; split.\n  - intros l. in_dom_Gmon_graph. intros [?|[HlG|HlG']]; first subst.\n    + exists []; split.\n      { constructor 1; trivial. in_dom_Gmon_graph; auto. }\n      { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso. apply get_left_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_left_singleton in Hl; inversion Hl; subst.\n          apply path_conv' in Hpv; eauto.\n        - exfalso. apply get_right_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_right_singleton in Hl; inversion Hl; subst.\n          apply path_conv' in Hpv; eauto. }\n   + edestruct tl as [q [qv Hq]]; eauto.\n     exists (true :: q). split; [econstructor; eauto|].\n     { eapply path_conv_back'; eauto; eapply path_conv_back; eauto. }\n     { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso; eapply path_conv_back in qv; eauto.\n        - apply get_left_conv in Hl; eauto.\n          rewrite get_left_singleton in Hl. inversion Hl; subst.\n          apply path_conv', path_conv in Hpv; eauto. erewrite Hq; eauto.\n        - exfalso. apply get_right_conv in Hl; eauto.\n          rewrite get_right_singleton in Hl; inversion Hl; subst.\n          do 2 apply path_conv' in Hpv; eauto. }\n  + edestruct tr as [q [qv Hq]]; eauto.\n     exists (false :: q). split; [econstructor; eauto|].\n     { eapply path_conv_back'; eauto; eapply path_conv_back'; eauto. }\n     { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso; eapply path_conv_back' in qv; eauto.\n        - exfalso. apply get_left_conv in Hl; eauto.\n          rewrite get_left_singleton in Hl; inversion Hl; subst.\n          apply path_conv', path_conv in Hpv; eauto.\n        - apply get_right_conv in Hl; eauto.\n          rewrite get_right_singleton in Hl. inversion Hl; subst.\n          apply path_conv', path_conv' in Hpv; eauto. erewrite Hq; eauto. }\n  - apply maximal_op_singleton; eauto.\nQed.\n\nLemma maximally_marked_tree_left (G : Gmon) x xl :\n  \u2713 ((x [\u21a6] (Some xl, None)) \u22c5 G) \u2192\n  xl \u2208 dom (gset _) G \u2192 tree (Gmon_graph G) xl \u2192 maximal (Gmon_graph G) \u2192\n  tree (Gmon_graph ((x [\u21a6] (Some xl, None)) \u22c5 G)) x \u2227\n  maximal (Gmon_graph ((x [\u21a6] (Some xl, None)) \u22c5 G)).\nProof.\n  intros Hvl Hxl tl ml; split.\n  - intros l. in_dom_Gmon_graph. intros [?|HlG]; first subst.\n    + exists []; split.\n      { constructor 1; trivial. in_dom_Gmon_graph; auto. }\n      { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso. apply get_left_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_left_singleton in Hl; inversion Hl; subst.\n          apply path_conv' in Hpv; eauto.\n        - exfalso. apply get_right_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_right_singleton in Hl; inversion Hl. }\n   + edestruct tl as [q [qv Hq]]; eauto.\n     exists (true :: q). split; [econstructor; eauto|].\n     { eapply path_conv_back'; eauto; eapply path_conv_back; eauto. }\n     { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso; eauto.\n        - apply get_left_conv in Hl; eauto.\n          rewrite get_left_singleton in Hl. inversion Hl; subst.\n          apply path_conv' in Hpv; eauto. erewrite Hq; eauto.\n        - exfalso. apply get_right_conv in Hl; eauto.\n          rewrite get_right_singleton in Hl; inversion Hl. }\n - apply maximal_op_singleton; eauto.\nQed.\n\nLemma maximally_marked_tree_right (G : Gmon) x xr :\n  \u2713 ((x [\u21a6] (None, Some xr)) \u22c5 G) \u2192\n  xr \u2208 dom (gset _) G \u2192 tree (Gmon_graph G) xr \u2192 maximal (Gmon_graph G) \u2192\n  tree (Gmon_graph ((x [\u21a6] (None, Some xr)) \u22c5 G)) x \u2227\n  maximal (Gmon_graph ((x [\u21a6] (None, Some xr)) \u22c5 G)).\nProof.\n  intros Hvl Hxl tl ml; split.\n  - intros l. in_dom_Gmon_graph. intros [?|HlG]; first subst.\n    + exists []; split.\n      { constructor 1; trivial. in_dom_Gmon_graph; auto. }\n      { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso. apply get_left_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_left_singleton in Hl; inversion Hl.\n        - exfalso. apply get_right_conv in Hl; [| |in_dom_Gmon_graph]; eauto.\n          rewrite get_right_singleton in Hl; inversion Hl; subst.\n          apply path_conv' in Hpv; eauto. }\n   + edestruct tl as [q [qv Hq]]; eauto.\n     exists (false :: q). split; [econstructor; eauto|].\n     { eapply path_conv_back'; eauto; eapply path_conv_back; eauto. }\n     { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - exfalso; eauto.\n        - exfalso. apply get_left_conv in Hl; eauto.\n          rewrite get_left_singleton in Hl; inversion Hl.\n        - apply get_right_conv in Hl; eauto.\n          rewrite get_right_singleton in Hl. inversion Hl; subst.\n          apply path_conv' in Hpv; eauto. erewrite Hq; eauto. }\n - apply maximal_op_singleton; eauto.\nQed.\n\nLemma maximally_marked_tree_none (x : loc) :\n  \u2713 ((x [\u21a6] (None, None)) : Gmon) \u2192\n  tree (Gmon_graph (x [\u21a6] (None, None))) x \u2227\n  maximal (Gmon_graph (x [\u21a6] (None, None))).\nProof.\n  intros Hvl; split.\n  - intros l. in_dom_Gmon_graph. intros ?; subst.\n    + exists []; split.\n      { constructor 1; trivial. in_dom_Gmon_graph; auto. }\n      { intros p Hp. destruct p; inversion Hp as [| ? ? Hl Hpv| ? ? Hl Hpv];\n          trivial; subst.\n        - rewrite get_left_singleton in Hl; inversion Hl.\n        - rewrite get_right_singleton in Hl; inversion Hl. }\n - split; trivial. intros z v. in_dom_Gmon_graph. intros ? [Hl|Hl]; subst.\n    + rewrite get_left_singleton in Hl; inversion Hl.\n    + rewrite get_right_singleton in Hl; inversion Hl.\nQed.\n\nLemma update_valid (G : Gmon) x v w : \u2713 ((x [\u21a6] v) \u22c5 G) \u2192 \u2713 ((x [\u21a6] w) \u22c5 G).\nProof.\n  intros Hvl i; specialize (Hvl i); revert Hvl.\n  rewrite ?lookup_op. destruct (decide (i = x)).\n  - subst; rewrite ?lookup_singleton; case _ : (G !! x); done.\n  - rewrite ?lookup_singleton_ne //=.\nQed.\n\nLemma of_graph_unmarked (g : graph loc) (G : Gmon) x v :\n  of_graph g G !! x = Some (false, v) \u2192 g !! x = Some v.\nProof.\n  rewrite map_lookup_imap /of_graph_elem lookup_omap.\n  case _ : (g !! x); case _ : (G !! x) => [[]|]; by inversion 1.\nQed.\nLemma get_lr_disj (G G' : Gmon) i : \u2713 (G \u22c5 G') \u2192\n  (get_left (Gmon_graph (G \u22c5 G')) i = get_left (Gmon_graph G) i \u2227\n   get_right (Gmon_graph (G \u22c5 G')) i = get_right (Gmon_graph G) i \u2227\n   get_left (Gmon_graph G') i = None \u2227\n   get_right (Gmon_graph G') i = None) \u2228\n  (get_left (Gmon_graph (G \u22c5 G')) i = get_left (Gmon_graph G') i \u2227\n   get_right (Gmon_graph (G \u22c5 G')) i = get_right (Gmon_graph G') i \u2227\n   get_left (Gmon_graph G) i = None \u2227\n   get_right (Gmon_graph G) i = None).\nProof.\n  intros Hvl. specialize (Hvl i). revert Hvl.\n  rewrite /get_left /get_right /Gmon_graph ?lookup_omap ?lookup_op.\n  case _ : (G !! i) => [[]|]; case _ : (G' !! i) => [[]|]; inversion 1;\n    simpl; auto.\nQed.\nLemma mark_update_strict_subgraph (g : graph loc) (G G' : Gmon) : \u2713 (G \u22c5 G') \u2192\n  strict_subgraph g (Gmon_graph G) \u2227 strict_subgraph g (Gmon_graph G') \u2194\n  strict_subgraph g (Gmon_graph (G \u22c5 G')).\nProof.\n  intros Hvl; split.\n  - intros [HG HG'] i.\n  destruct (get_lr_disj G G' i) as [(-> & -> & _ & _)|(-> & -> & _ & _)]; eauto.\n  - intros HGG; split => i.\n    + destruct (get_lr_disj G G' i) as [(<- & <- & _ & _)|(_ & _ & -> & ->)];\n       eauto using strict_sub_children_None.\n    + destruct (get_lr_disj G G' i) as [(_ & _ & -> & ->)|(<- & <- & _ & _)];\n       eauto using strict_sub_children_None.\nQed.\nLemma strinct_subgraph_singleton (g : graph loc) x v :\n  x \u2208 dom (gset loc) g \u2192 (\u2200 w, g !! x = Some w \u2192 strict_sub_children w v)\n  \u2194 strict_subgraph g (Gmon_graph (x [\u21a6] v)).\nProof.\n  rewrite elem_of_dom; intros [u Hu]; split.\n  - move => /(_ _ Hu) Hgw i.\n    rewrite /get_left /get_right /Gmon_graph lookup_omap.\n    destruct (decide (i = x)); subst.\n    + by rewrite Hu lookup_singleton; simpl.\n    + rewrite lookup_singleton_ne; auto. by case _ : (g !! i) => [[[?|] [?|]]|].\n  - intros Hg w Hw; specialize (Hg x). destruct v as [v1 v2]; simpl. revert Hg.\n    rewrite Hu in Hw; inversion Hw; subst.\n    by rewrite get_left_singleton get_right_singleton /get_left /get_right Hu.\nQed.\nLemma mark_strict_subgraph (g : graph loc) (G : Gmon) x v :\n  \u2713 ((x [\u21a6] v) \u22c5 G) \u2192 x \u2208 dom (gset loc) g \u2192\n  of_graph g G !! x = Some (false, v) \u2192 strict_subgraph g (Gmon_graph G) \u2192\n  strict_subgraph g (Gmon_graph ((x [\u21a6] v) \u22c5 G)).\nProof.\n  intros Hvl Hdx Hx Hsg. apply mark_update_strict_subgraph; try split; eauto.\n  eapply strinct_subgraph_singleton; erewrite ?of_graph_unmarked; eauto.\n  inversion 1; auto using strict_sub_children_refl.\nQed.\nLemma update_strict_subgraph (g : graph loc) (G : Gmon) x v w :\n  \u2713 ((x [\u21a6] v) \u22c5 G) \u2192 x \u2208 dom (gset loc) g \u2192\n  strict_subgraph g (Gmon_graph ((x [\u21a6] w) \u22c5 G)) \u2192\n  strict_sub_children w v \u2192\n  strict_subgraph g (Gmon_graph ((x [\u21a6] v) \u22c5 G)).\nProof.\n  intros Hvl Hdx Hx Hsc1 Hsc2.\n  apply mark_update_strict_subgraph in Hx; eauto using update_valid.\n  destruct Hx as [Hx1 Hx2].\n  apply mark_update_strict_subgraph; try split; try tauto.\n  pose proof (proj1 (elem_of_dom _ _) Hdx) as [u Hu].\n  eapply strinct_subgraph_singleton in Hx1; eauto.\n  apply strinct_subgraph_singleton; trivial.\n  intros u' Hu'; rewrite Hu in Hu'; inversion Hu'; subst.\n  intuition eauto using strict_sub_children_trans.\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/spanning_tree/mon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.17879122402993008}}
{"text": "Require Import Lia IndefiniteDescription Arith.\nFrom hahn Require Import Hahn.\nRequire Import AuxRel.\nRequire Import Labels.\nRequire Import Events.\nRequire Import Execution.\nRequire Import View.\n\nSet Implicit Arguments.\n\nSection SCOHDeclarative.\n\nVariable G: execution. \n\nDefinition scoh_consistent :=\n  SCpL G  /\\\n  irreflexive ((rf G)\u207b\u00b9 \u2a3e (co G \u2a3e (co G))) /\\\n  \u27ea PORF : irreflexive (hb G) \u27eb.\n\nLemma hb_irr (CONS : scoh_consistent) : irreflexive (hb G).\nProof using. apply CONS. Qed.\n\nLemma scoh_rmw_atomicity (WF: Wf G) (CONS : scoh_consistent) :\n  rmw_atomicity G.\nProof using.\n  unfold scoh_consistent, rmw_atomicity in *; desc.\n  rewrite wf_rfE, wf_rfD; ins; unfolder in *; ins; desf.\n  destruct (classic (x = y)) as [|NEQ]; desf.\n  { edestruct (CONS y). apply ct_step.\n    basic_solver. }\n  eapply (wf_co_total WF) in NEQ; ins; desf; ins.    \n  { splits; ins; intro; desf; eauto 10. }\n  { edestruct (CONS x). apply ct_ct.\n    exists y; split; apply t_step; basic_solver. }\n  unfolder. splits; auto.\n  apply wf_rfl in H0; ins.\nQed.\n \nLemma scoh_rf_irr (CONS : scoh_consistent) : irreflexive (rf G).\nProof using. rewrite rf_in_hb. by apply hb_irr. Qed.\n\nLemma rf_w_in_co (WF: Wf G) (CONS : scoh_consistent) :\n  (rf G) \u2a3e \u2997is_w\u2998 \u2286 (co G).\nProof using.\n  unfolder. intros x y [RF WY].\n  destruct (classic (x = y)) as [|NEQ]; subst.\n  { exfalso. eapply scoh_rf_irr; eauto. }\n  apply (wf_rfE WF) in RF. unfolder in RF. desf.\n  apply (wf_rfD WF) in RF0. unfolder in RF0. desf.\n  edestruct (wf_co_total WF) with (a:=x) (b:=y) as [|HH]; eauto.\n  1,2: unfolder; splits; eauto.\n  { symmetry. by apply (wf_rfl WF). }\n  exfalso.\n  cdes CONS. eapply CONS0.\n  apply ct_ct. eexists. split; apply ct_step.\n  all: basic_solver.\nQed.\n\n(* TODO: move to more appropriate place or replace with co_ninit. *)\nLemma co_init_r (WF: Wf G)\n      x y (CO : co G x y) (INITY : is_init y) :\n  False.\nProof.\n  apply co_ninit in CO; auto. unfolder in CO. desf.\nQed.\n\nEnd SCOHDeclarative.\n", "meta": {"author": "volodeyka", "repo": "trust-coq", "sha": "108aea7c1ea2852fe81e1cbf63450fed6b892435", "save_path": "github-repos/coq/volodeyka-trust-coq", "path": "github-repos/coq/volodeyka-trust-coq/trust-coq-108aea7c1ea2852fe81e1cbf63450fed6b892435/src/models/SCOH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32423538592116924, "lm_q1q2_score": 0.17852639165535697}}
{"text": "From Paco Require Import paco.\nFrom ITree Require Import ITree.\nRequire Import sflib.\n\nRequire Import StdlibExt IntegersExt.\nRequire Import SysSem.\nRequire Import SyncSysModel Executable.\n\nRequire Import MSteps FMSim FMSim_Switch.\nRequire Import PALSSystem.\n\nRequire Import RTSysEnv.\nRequire Import CProgEventSem.\n\nRequire Import BehavUtils SystemInvariant.\n\nRequire console ctrl dev.\n\nRequire Import AcStSystem.\nRequire Import SpecConsole SpecController SpecDevice.\nRequire Import CProgEventSem.\n\nRequire Import AcStRefinement.\n\nRequire Import ITreeTac.\nRequire Import ZArith Streams List Lia Bool.\n\n\n(* Local Opaque Z.of_nat Z.to_nat. *)\n(* Import ActiveStandby. *)\n\nSet Nested Proofs Allowed.\n\n\nDefinition acst_sinv: system_invariant\n                        (PALSSys.as_exec active_standby_system).\nAdmitted.\n\n(* event in a period-trace *)\nDefinition event_in_ptrace (tid: Tid) (evt: event obsE)\n           (ptr: list (events obsE)): Prop :=\n  exists ptr_n,\n    <<PTR_N: nth_error ptr tid = Some ptr_n>> /\\\n    <<EVT_IN_PTR_N: In evt ptr_n>>.\n\nDefinition event_in_trace (tid: Tid) (tm: Z) (evt: event obsE)\n           (tr: list (list (Z * events obsE))): Prop :=\n  exists tr_n es,\n    <<TR_N: nth_error tr tid = Some tr_n>> /\\\n    <<ES_IN_TR_N: In (tm, es) tr_n>> /\\\n    <<EVT_IN_ES: In evt es>>.\n\nSection SYS_INV.\n  Let exec_sys: ExecutableSpec.t :=\n    PALSSys.as_exec active_standby_system.\n  Let prd: Z := ExecutableSpec.period exec_sys.\n  Let nts: nat := length (ExecutableSpec.apps exec_sys).\n\n  Definition went_wrong: abs_data _ acst_sinv -> Prop.\n  Admitted.\n\n  Definition start_control\n    : abs_data _ acst_sinv -> Prop.\n  Admitted.\n\n\n  Inductive dchain\n    : (abs_data _ acst_sinv) -> list (abs_data _ acst_sinv) -> Prop :=\n  | DataChain_One\n      d\n      (WF_D: abs_data_wf _ _ d)\n    : dchain d []\n  | DataChain_Step\n      d1 d2 ds\n      (NEXT: abs_data_next _ acst_sinv d1 d2)\n      (WF_D1: abs_data_wf _ _ d1)\n      (REST_CHAIN: dchain d2 ds)\n    : dchain d1 (d2 :: ds)\n  .\n\n  (* Lemma start_and_went_wrong_trace *)\n  (*       tm0 d0 inbs0 lsts0 *)\n  (*       tr d1 inbs1 lsts1 steps *)\n  (*       (SYNC_TIME: (prd | tm0)%Z) *)\n  (*       (SINV_STEPS: sinv_steps _ acst_sinv tm0 *)\n  (*                               (d0, inbs0, lsts0) *)\n  (*                               ((tr, d1, inbs1, lsts1) :: steps)) *)\n  (*   : *)\n\nEnd SYS_INV.\n\n\nSection LIVENESS.\n  Let exec_sys: ExecutableSpec.t :=\n    PALSSys.as_exec active_standby_system.\n  Let prd: Z := ExecutableSpec.period exec_sys.\n  Let nts: nat := length (ExecutableSpec.apps exec_sys).\n\n  Definition dev_wait\n    : (abs_data _ acst_sinv) -> Tid ->\n      nat(*demand*) -> nat(*wait_cnt*) -> Prop.\n  Admitted.\n\n  Definition dev_owner\n    : (abs_data _ acst_sinv) -> Tid -> nat (*demand left*) -> Prop.\n  Admitted.\n\n  Definition dev_failed: abs_data _ acst_sinv -> Tid -> Prop.\n  Admitted.\n\n  Lemma dev_wait_advance\n        (d d': abs_data _ acst_sinv)\n        tid_dev dmd w\n        (NEXT: abs_data_next _ _ d d')\n        (WAIT_S_W: dev_wait d tid_dev dmd (S w))\n        (WF_D: abs_data_wf _ acst_sinv d)\n    : <<WENT_WRONG: went_wrong d'>> \\/\n      <<DEVICE_FAILED: dev_failed d' tid_dev>> \\/\n      <<DEV_WAIT_REDUCED: dev_wait d' tid_dev dmd w>>.\n  Proof.\n  Admitted.\n\n  Lemma dev_wait_zero\n        d tid_dev dmd\n        (WAIT_ZERO: dev_wait d tid_dev dmd O)\n        (WF_D: abs_data_wf _ acst_sinv d)\n    : dev_owner d tid_dev dmd.\n  Proof.\n  Admitted.\n\n  Lemma dev_wait_safe\n        d tid_dev dmd w\n        (WAIT: dev_wait d tid_dev dmd w)\n        (WF_D: abs_data_wf _ acst_sinv d)\n    : ~ went_wrong d.\n  Proof.\n  Admitted.\n\n  Lemma dev_wait_not_failed\n        d tid_dev dmd w\n        (WAIT: dev_wait d tid_dev dmd w)\n        (WF_D: abs_data_wf _ acst_sinv d)\n    : ~ dev_failed d tid_dev.\n  Proof.\n  Admitted.\n\n  Lemma dev_owner_advance\n        d tid_dev dmd d'\n        (OWNER: dev_owner d tid_dev (S dmd))\n        (WF_D: abs_data_wf _ acst_sinv d)\n        (NEXT: abs_data_next _ _ d d')\n    : <<WENT_WRONG: went_wrong d'>> \\/\n      <<OWNER_REDUCED: dev_owner d tid_dev dmd>>.\n  Proof.\n  Admitted.\n\n  Lemma dev_owner_safe\n        d tid_dev dmd\n        (WAIT: dev_owner d tid_dev dmd)\n        (WF_D: abs_data_wf _ acst_sinv d)\n    : ~ went_wrong d.\n  Proof.\n  Admitted.\n\n  Inductive owner_dchain (tid_dev: Tid)\n    : nat -> list (abs_data _ acst_sinv) -> Prop :=\n  | OwnerDataChain_Base\n      d0\n      (OWNER_ZERO: dev_owner d0 tid_dev O)\n      (WF_D0: abs_data_wf _ _ d0)\n    : owner_dchain tid_dev O [d0]\n  | OwnerDataChain_Cons\n      dmd d ds\n      (OWNER_N: dev_owner d tid_dev (S dmd))\n      (WF_D0: abs_data_wf _ _ d)\n      (OWNER_DATAS_REST: owner_dchain tid_dev dmd ds)\n    : owner_dchain tid_dev (S dmd) (d :: ds)\n  .\n\n  (* Lemma demand_wait_start *)\n  (*       d1 inbs1 lsts1 tm1 *)\n  (*       tr lsts_out *)\n  (*       tid_dev (dmd_raw: int) (dmd: nat) *)\n  (*       d2 inbs2 lsts2 *)\n  (*       (MATCH_LOCALS1: iForall2 *)\n  (*                         (match_local _ acst_sinv tm1 d1) *)\n  (*                         0 inbs1 lsts1) *)\n  (*       (WF_D1: abs_data_wf _ _ d1) *)\n  (*       (SAFE_D1: ~ went_wrong d1) *)\n  (*       (LOCAL_STEPS: Forall4 (run_local exec_sys tm1) *)\n  (*                             inbs1 lsts1 tr lsts_out) *)\n  (*       (LOCAL_STATES': lsts2 = map fst lsts_out) *)\n  (*       (INBS1: inbs2 = imap (fun tid _ => *)\n  (*                               map (SNode.get_outbox_msg_by_dest *)\n  (*                                      tid) (map snd lsts_out)) *)\n  (*                            0 (repeat tt nts)) *)\n  (*       (SAFE_TRACE: Forall safe_trace tr) *)\n  (*       (DMD_POS: 0 < dmd) *)\n  (*       (ACTUAL_DEMAND: dmd = Nat.min MAX_TIMEOUT (Z.to_nat (Int.signed dmd_raw))) *)\n  (*       (EVT_IN_TR: event_in_trace tid_dev (Event (inl1 CheckDemand) dmd_raw) tr) *)\n  (*       (MATCH_LOCALS2: iForall2 *)\n  (*                         (match_local _ acst_sinv (tm1 + prd)%Z d2) *)\n  (*                         0 inbs2 lsts2) *)\n  (*       (WF_D2: abs_data_wf _ _ d2) *)\n  (*   : exists wait_max, *)\n  (*     <<WENT_WRONG: went_wrong d2>> \\/ *)\n  (*     <<WAIT_START: dev_wait d2 tid_dev wait_max dmd>> *)\n  (* . *)\n  (* Proof. *)\n  (* Admitted. *)\n\n  Lemma dchain_wait_to_owner\n        d ds\n        tid_dev (dmd: nat) w\n        (DCHAIN: dchain d ds)\n        (WAIT_START: dev_wait d tid_dev dmd w)\n        (LEN_DS: dmd <= length ds)\n    : exists ds_w d_wend ds',\n      <<DCHAIN_DIV: d :: ds = ds_w ++ d_wend :: ds'>> /\\\n      <<LEN_DS_W: length ds_w <= w>> /\\\n      (<<WENT_WRONG: went_wrong d_wend>> \\/\n       <<DEV_FAILED: dev_failed d_wend tid_dev>> \\/\n       <<BECAME_OWNER: dev_owner d_wend tid_dev dmd>>).\n  Proof.\n  Admitted.\n\n  Lemma dev_wait_dmd_le_max\n        d tid_dev dmd w\n        (WAIT: dev_wait d tid_dev dmd w)\n    : dmd <= MAX_TIMEOUT.\n  Proof.\n  Admitted.\n\n  Lemma owner_dchain_cases\n        d tid_dev dmd\n        (OWNER: dev_owner d tid_dev dmd)\n    : forall ds\n        (DS_LEN: dmd <= length ds)\n        (DCHAIN: dchain d ds)\n    ,\n      Exists went_wrong ds \\/\n      Exists (flip dev_failed tid_dev) ds \\/\n      exists ds_use ds_rest,\n        <<DS_DIV: d :: ds = ds_use ++ ds_rest>> /\\\n        <<USES: owner_dchain tid_dev dmd ds_use>>.\n  Proof.\n  Admitted.\n\n  Lemma liveness_dchain_cases\n        tid_dev\n        d (dmd: nat) w\n        (WAITING: dev_wait d tid_dev dmd w)\n    : forall ds\n        (DS_LEN: length ds = w + MAX_TIMEOUT)\n        (DCHAIN: dchain d ds),\n      ((* CTRL_FAILED *)\n        Exists went_wrong ds) \\/\n      ((* DEV_FAILED *)\n        Exists (flip dev_failed tid_dev) ds) \\/\n      ((* USE RESOURCE *)\n        exists ds1 ds_use ds2,\n          <<DS_DIV: d :: ds = ds1 ++ ds_use ++ ds2>> /\\\n          <<USES: owner_dchain tid_dev dmd ds_use>>)\n  .\n  Proof.\n    i.\n    hexploit dev_wait_dmd_le_max; eauto. intro DMD_LE_MAX.\n    hexploit dchain_wait_to_owner; eauto.\n    { nia. }\n    i. des.\n    { left.\n      destruct ds_w.\n      { simpl in DCHAIN_DIV. clarify.\n        exfalso.\n        hexploit dev_wait_safe; eauto.\n        inv DCHAIN; done.\n      }\n      simpl in DCHAIN_DIV. clarify.\n      apply Exists_exists.\n      esplits.\n      { apply in_or_app. right.\n        simpl. left. eauto. }\n      done.\n    }\n    { right. left.\n      destruct ds_w.\n      { simpl in DCHAIN_DIV. clarify.\n        exfalso.\n        hexploit dev_wait_not_failed; eauto.\n        inv DCHAIN; done.\n      }\n      simpl in DCHAIN_DIV. clarify.\n      apply Exists_exists.\n      esplits.\n      { apply in_or_app. right.\n        simpl. left. eauto. }\n      done.\n    }\n\n    assert (DCHAIN_WEND: dchain d_wend ds').\n    { clear - DCHAIN_DIV DCHAIN.\n      destruct ds_w as [|h t].\n      { ss. clarify. }\n\n      ss. clarify.\n      depgen h.\n      induction t as [| h' t' IH]; i; ss; clarify.\n      { inv DCHAIN. ss. }\n      inv DCHAIN.\n      eauto.\n    }\n\n    hexploit owner_dchain_cases; eauto.\n    { cut (length (d::ds) = length ds_w + S (length ds')).\n      { s. nia. }\n      rewrite DCHAIN_DIV.\n      rewrite app_length. s. reflexivity.\n    }\n    assert (DS'_DS: forall x, In x ds' -> In x ds).\n    { i. destruct ds_w; simpl in DCHAIN_DIV; clarify.\n      apply in_or_app. right. right. eauto. }\n\n    intros [WRONG | [DFAIL | OK]].\n    - left.\n      apply Exists_exists.\n      apply Exists_exists in WRONG. des.\n      esplits; eauto.\n    - right. left.\n      apply Exists_exists.\n      apply Exists_exists in DFAIL. des.\n      esplits; eauto.\n    - des.\n      right. right.\n      esplits; eauto.\n      rewrite DCHAIN_DIV.\n      rewrite DS_DIV. eauto.\n  Qed.\n\n\n  Lemma dev_failed_trace_nil\n        d tid_dev (tm: Z)\n        inbs lsts tr lsts_out\n        (DEV_FAILED: dev_failed d tid_dev)\n        (SYNC_TIME: (prd | tm)%Z)\n        (MATCH: iForall2 (match_local _ acst_sinv tm d)\n                         O inbs lsts)\n        (WF_D: abs_data_wf _ _ d)\n        (* steps *)\n        (LOCAL_STEPS: Forall4 (run_local exec_sys tm)\n                              inbs lsts tr lsts_out)\n    : forall e, ~ event_in_ptrace tid_dev e tr.\n  Proof.\n  Admitted.\n\n  Lemma dev_owner_trace_use\n        d tid_dev (tm: Z) (dmd: nat)\n        inbs lsts tr lsts_out\n        d' inbs' lsts'\n        (OWNER: dev_owner d tid_dev (S dmd))\n        (SYNC_TIME: (prd | tm)%Z)\n        (MATCH: iForall2 (match_local _ acst_sinv tm d)\n                         O inbs lsts)\n        (WF_D: abs_data_wf _ _ d)\n        (* steps *)\n        (LOCAL_STEPS: Forall4 (run_local exec_sys tm)\n                              inbs lsts tr lsts_out)\n        (LOCAL_STATES': lsts' = map fst lsts_out)\n        (INBS': inbs' = imap (fun tid _ =>\n                                map (SNode.get_outbox_msg_by_dest\n                                       tid) (map snd lsts_out))\n                             0 (repeat tt nts))\n        (MATCH1: iForall2 (match_local _ acst_sinv tm d')\n                         O inbs' lsts')\n        (WF_D': abs_data_wf _ _ d')\n        (OWNER': dev_owner d' tid_dev dmd)\n    : event_in_ptrace tid_dev (Event (inl1 UseResource) tt) tr.\n  Proof.\n  Admitted.\n\nEnd LIVENESS.\n\nLocal Opaque Z.to_nat Z.of_nat.\n\nSection LIVENESS_BEH.\n  Let exec_sys :=\n    (PALSSys.as_exec active_standby_system).\n  Let prd := (ExecutableSpec.period exec_sys).\n  Let nts := (length (ExecutableSpec.apps exec_sys)).\n\n  Let PRD_POS: (0 < prd)%Z.\n  Proof.\n    change prd with (Z.of_nat period).\n    change period with (Z.to_nat ActiveStandby.period).\n    ss.\n  Qed.\n\n  Variable tm_init: Z.\n\n  Let dsys: DSys.t := ExecutableSpec.as_dsys\n                        exec_sys tm_init None.\n\n  Let st_init := (0%Z, ExecutableSpec.sys_itree\n                         exec_sys tm_init None).\n\n  (* no events except console *)\n  Definition trace_pre\n             (tr: list (list (Z * events obsE))): Prop.\n  Admitted.\n\n  (* Definition start_ctrl_trace *)\n  (*            (tr: list (list (Z * events obsE))): Prop. *)\n  (* Admitted. *)\n\n  Definition log_in_trace (tid: Tid) (tm:Z)\n             (tr: list (list (Z * events obsE))): Prop :=\n    exists (v: Z),\n      event_in_trace tid tm (Event (inl1 (WriteLog v)) tt) tr.\n\n  Inductive trace_ctrl_fsd\n            (tm: Z)\n            (tr: list (list (Z * events obsE)))\n    : (bool?) -> Prop :=\n    TraceCtrlFsd\n      fsd\n      (FST_FSD: fsd = Some true \\/ log_in_trace tid_ctrl1 tm tr)\n      (SND_FSD: fsd = Some false \\/ log_in_trace tid_ctrl2 tm tr)\n    : trace_ctrl_fsd tm tr fsd.\n  (* | TraceCtrlFsd_Snd *)\n  (*     (FST_OK: log_in_trace tid_ctrl1 tm tr) *)\n  (*     (SND_FAILED: ~ log_in_trace tid_ctrl2 tm tr) *)\n  (*   : trace_ctrl_fsd tm tr (Some false) *)\n  (* | TraceCtrlFsd_None *)\n  (*     (FST_OK: log_in_trace tid_ctrl1 tm tr) *)\n  (*     (SND_OK: log_in_trace tid_ctrl2 tm tr) *)\n  (*   : trace_ctrl_fsd tm tr None *)\n  (* . *)\n\n  Inductive fsd_le: bool? -> bool? -> Prop :=\n  | FsdLe_Eq x\n    : fsd_le x x\n  | FsdLe_None x\n    : fsd_le x None\n  .\n\n  Inductive fsd_next: bool? -> bool? -> Prop :=\n  | FsdNext_None1 fsd\n    : fsd_next None fsd\n  | FsdNext_None2 fsd\n    : fsd_next fsd None\n  | FsdNext_eq sd\n    : fsd_next (Some sd) (Some sd)\n  .\n\n  Lemma trace_ctrl_fsd_le\n        tm tr fsd fsd'\n        (FSD: trace_ctrl_fsd tm tr fsd)\n        (LE: fsd_le fsd' fsd)\n    : trace_ctrl_fsd tm tr fsd'.\n  Proof.\n    inv LE; ss.\n    inv FSD.\n    des; ss.\n    econs; eauto.\n  Qed.\n\n  (* Inductive trace_ctrl_on *)\n  (*   : Z * bool? -> Z * bool? (* exclusive *) -> *)\n  (*     list (list (Z * events obsE)) -> Prop := *)\n  (* | TraceCtrlOn_Base *)\n  (*     tr tm fsd *)\n  (*     (* (SYNC_TIME: (prd | tm)%Z) *) *)\n  (*     (* (FAILED_SIDE: trace_ctrl_fsd tm tr fsd) *) *)\n  (*   : trace_ctrl_on (tm, fsd) (tm, fsd) tr *)\n  (* | TraceCtrlOn_Cons *)\n  (*     tr tm fsd *)\n  (*     fsd1 tm' fsd' *)\n  (*     (SYNC_TIME: (prd | tm)%Z) *)\n  (*     (FAILED_SIDE: trace_ctrl_fsd tm tr fsd) *)\n  (*     (CTRL_ON_REST: trace_ctrl_on ((tm + prd)%Z, fsd1) *)\n  (*                                  (tm', fsd') tr) *)\n  (*     (FSD_LE: fsd_le fsd fsd1) *)\n  (*   : trace_ctrl_on (tm, fsd) (tm', fsd') tr *)\n  (* . *)\n\n  Definition tid_c_of_side (sd: bool): Tid :=\n    if sd then tid_ctrl1 else tid_ctrl2.\n\n  Lemma trace_ctrl_fsd_Some\n        tm tr fsd sd\n        (FSD: trace_ctrl_fsd tm tr fsd)\n        (FSD_SOME: fsd = Some sd)\n    : log_in_trace (tid_c_of_side (negb sd)) tm tr.\n  Proof.\n    subst fsd.\n    inv FSD. des; clarify.\n    destruct sd; ss.\n  Qed.\n\n  Inductive trace_ctrl_on\n             (tm_s tm_e: Z)\n             (fsd_s fsd_e: bool?)\n             (tr: list (list (Z * events obsE)))\n    : Prop :=\n    TraceCtrlOn\n      (TM_S_SYNC: (prd | tm_s)%Z)\n      (START_FST: trace_ctrl_fsd tm_s tr fsd_s)\n      (CHAIN_EXISTS:\n         forall tm1 sd\n           (TM1_SYNC: (prd | tm1)%Z)\n           (* (TM_NEXT: (tm2 = tm1 + prd)%Z) *)\n           (TM1_LBND: (tm_s <= tm1 < tm_e)%Z)\n           (* (TM2_UBND: (tm2 < tm_e)%Z) *)\n           (OFF_AT_TM: ~ log_in_trace (tid_c_of_side sd) tm1 tr)\n         ,\n           <<ON_OTHER: log_in_trace (tid_c_of_side (negb sd)) tm1 tr>> /\\\n           ((* chain exists *)\n             <<ON_OTHER_NEXT: log_in_trace (tid_c_of_side (negb sd)) (tm1 + prd)%Z tr>> \\/\n           (* last log *)\n             <<LAST_TIME: (tm_e <= tm1 + prd)%Z>> /\\\n             <<LAST_FAILED_SIDE: fsd_e = Some sd>>))\n  .\n\n  Lemma divide_next_eq\n        p a b\n        (P_POS: (0 < p)%Z)\n        (DIV1: (p | a)%Z)\n        (DIV2: (p | b)%Z)\n        (GT: (a < b <= a + prd)%Z)\n    : (b = a + prd)%Z.\n  Proof.\n  Admitted.\n\n  Lemma trace_ctrl_on_app\n        tr tm_s tm_m tm_e\n        fsd_s fsd_m fsd_m' fsd_e\n        (ON1: trace_ctrl_on tm_s tm_m fsd_s fsd_m tr)\n        (ON2: trace_ctrl_on tm_m tm_e fsd_m' fsd_e tr)\n        (FSD_NEXT: fsd_next fsd_m fsd_m')\n    : trace_ctrl_on tm_s tm_e fsd_s fsd_e tr.\n  Proof.\n    inv ON1.\n    renames TM_S_SYNC START_FST CHAIN_EXISTS into\n            TM_S_SYNC1 START_FST1 CHAIN_EXISTS1.\n    inv ON2.\n\n    econs; eauto. i.\n    destruct (Z_lt_ge_dec tm1 tm_m) as [LT|GE].\n    - hexploit CHAIN_EXISTS1; eauto.\n      { nia. }\n      i. des.\n      { eauto. }\n\n      assert (TM_M_EQ: (tm_m = tm1 + prd)%Z).\n      { eapply divide_next_eq; eauto. }\n\n      split; ss.\n      left.\n      subst fsd_m.\n\n      inv FSD_NEXT.\n      + inv START_FST. des; clarify.\n        r. destruct sd; ss.\n      + inv START_FST. des; clarify.\n        destruct sd; ss.\n\n    - hexploit CHAIN_EXISTS; eauto.\n      nia.\n  Qed.\n\n  Definition device_task_id (tid: Tid): Prop :=\n    tid = tid_dev1 \\/ tid = tid_dev2 \\/ tid = tid_dev3.\n\n  Inductive trace_pos_demand\n            (tid_dev: Tid) (tm: Z) (dmd: nat)\n            (tr: list (list (Z * events obsE))): Prop :=\n    TracePosDemand\n      (dmd_i: int)\n      (DEV_TASK_ID: device_task_id tid_dev)\n      (RANGE_DEMAND: 0 < dmd <= MAX_TIMEOUT)\n      (DMD_TO_NAT2: Z_to_nat2 (Int.signed dmd_i) = Some dmd)\n      (DEMAND_EVT_IN_TRACE:\n         event_in_trace tid_dev tm\n                        (Event (inl1 CheckDemand) dmd_i) tr)\n  .\n\n  Lemma liveness_exec\n        scnt_pre tr_pre st_pre\n        tr_s st_s\n        scnt1 tr1 st1\n        tr_dmd st_w exec_w\n        (STEPS_PRE: msteps dsys scnt_pre st_init tr_pre st_pre)\n        (STEPS_CSTART: msteps dsys 1 st_pre tr_s st_s)\n        (STEPS_ALIVE: msteps dsys scnt1 st_s tr1 st1)\n        (STEPS_DEMAND: msteps dsys 1 st1 tr_dmd st_w)\n        (PRE_TR: trace_pre tr_pre)\n        (CSTART_TR: trace_ctrl_on tr1)\n        (EXEC_ST: DSys.exec_state dsys st_w exec_w)\n    : True.\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/sys_verif/AcStProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.17846799081372897}}
{"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 PBFTexecute4.\nRequire Export PBFTsame_states.\n\n\nSection PBFTagreement.\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  Lemma agreement :\n    forall (eo : EventOrdering) (e1 e2 : Event) v1 v2 ts c j1 j2 r1 r2 a1 a2 i1 i2,\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 i1\n      -> loc e2 = PBFTreplica i2\n      -> In (send_reply (mk_reply v1 ts c j1 r1 a1)) (output_system_on_event_ldata PBFTsys e1)\n      -> In (send_reply (mk_reply v2 ts c j2 r2 a2)) (output_system_on_event_ldata PBFTsys e2)\n      -> r1 = r2.\n  Proof.\n    introv sendbyz ckeys atmost eqloc1 eqloc2 out1 out2.\n\n    applydup @output_system_on_event_ldata_implies_state_sm_on_event in out1 as h;\n      [|introv; simpl in *; unfold PBFTsys, PBFTnstate; remember (loc e1); destruct n; ginv; eauto 3 with pbft; try apply replicas_never_stop].\n    revert h; unfold PBFTnstate; rewrite eqloc1; introv h; exrepnd.\n\n    applydup @output_system_on_event_ldata_implies_state_sm_on_event in out2 as z;\n      [|introv; simpl in *; unfold PBFTsys, PBFTnstate; remember (loc e2); destruct n; ginv; eauto 3 with pbft; try apply replicas_never_stop].\n    revert z; unfold PBFTnstate; rewrite eqloc2; introv z; exrepnd.\n\n    pose proof (state_sm_before_event_some_between3 e1 e1 (PBFTreplicaSM i1) st) as q.\n    repeat (autodimp q hyp); eauto 3 with eo; exrepnd.\n\n    pose proof (state_sm_before_event_some_between3 e2 e2 (PBFTreplicaSM i2) st0) as w.\n    repeat (autodimp w hyp); eauto 3 with eo; exrepnd.\n\n    rename st into st1.\n    rename st0 into st.\n    rename s' into st2.\n    rename s'0 into st0.\n\n    eapply replies_from in out1; eauto.\n    eapply replies_from in out2; eauto.\n    exrepnd.\n\n    subst.\n\n    match goal with\n    | [ H1 : committed_log _ _ = _, H2 : committed_log _ _ = _ |- _ ] =>\n      rename H1 into com1; rename H2 into com2; dup com1 as com\n    end.\n\n    match goal with\n    | [ H1 : find_first_reply _ _ _ = _, H2 : find_first_reply _ _ _ = _ |- _ ] =>\n      rename H1 into ffr1; rename H2 into ffr2\n    end.\n\n    match goal with\n    | [ H1 : find_last_reply_entry_corresponding_to_client _ _ = _,\n             H2 : find_last_reply_entry_corresponding_to_client _ _ = _,\n                  H3 : find_last_reply_entry_corresponding_to_client _ _ = _,\n                       H4 : find_last_reply_entry_corresponding_to_client _ _ = _ |- _ ] =>\n      rename H1 into fl1; rename H2 into fl2; rename H3 into fl3; rename H4 into fl4\n    end.\n\n    match goal with\n    | [ H1 : reply2requests _ _ _ _ _ _ = _, H2 : reply2requests _ _ _ _ _ _ = _ |- _ ] =>\n      rename H1 into r2rs1; rename H2 into r2rs2\n    end.\n\n    match goal with\n    | [ H1 : request2info _ = _, H2 : request2info _ = _ |- _ ] =>\n      rename H1 into r2i1; rename H2 into r2i2\n    end.\n\n    destruct (SeqNumDeq (next_to_execute st0) (next_to_execute st2)) as [d|d].\n\n    {\n      rewrite d in *.\n\n      eapply PBFT_A_1_11_before in com;\n        try exact com2; try (exact q0); try (exact w0); auto; eauto 3 with pbft eo;[].\n      apply eq_digests_implies_eq_requests in com; subst.\n\n      rewrite ffr1 in ffr2; ginv.\n\n      pose proof (next_to_execute_from_before eo e1 e2 j1 j2 st2 st0) as u.\n      repeat (autodimp u hyp);[].\n      repnd.\n      rewrite u0 in *.\n      rewrite u in *.\n\n      pose proof (same_states_if_same_next_to_execute eo e1 e2 j1 j2 st1 st) as v.\n      repeat (autodimp v hyp); try (complete (allrw; tcsp));[].\n      repnd.\n      try rewrite v0 in *.\n      try rewrite v in *.\n\n      eapply matching_reply2requests_implies in r2rs1; try (exact r2rs2).\n      repnd; subst.\n\n      rewrite fl1 in *; ginv.\n      rewrite fl2 in *; ginv.\n\n      rewrite r2i1 in *; ginv.\n      smash_pbft.\n    }\n\n    assert (seqnum2nat (next_to_execute st0) <> seqnum2nat (next_to_execute st2)) as d'.\n    { intro xx; destruct d.\n      destruct (next_to_execute st0), (next_to_execute st2); simpl in *; tcsp. }\n\n    apply not_eq in d'; repndors;[|].\n\n    {\n      assert (next_to_execute st <= next_to_execute st2) as lenext by (allrw; simpl; omega).\n      applydup next_to_execute_is_greater_than_one in z0; auto;[].\n\n      rewrite <- ite_first_state_sm_on_event_as_before in q0.\n      unfold ite_first in *.\n      destruct (dec_isFirst e1) as [d1|d1]; ginv; subst; simpl in *;[].\n      pose proof (last_reply_state_increases\n                    eo (local_pred e1) j1 st2\n                    (next_to_execute st)) as u.\n      repeat (autodimp u hyp); autorewrite with eo; auto;\n        try omega; eauto 3 with pbft eo;[].\n      exrepnd.\n\n      pose proof (same_states_if_same_next_to_execute eo e' e2 j j2 st' st) as v.\n      repeat (autodimp v hyp); try (complete (allrw; auto)); eauto 4 with pbft eo;[].\n      repnd.\n      rewrite v in u0.\n\n      applydup u0 in fl4.\n      exrepnd.\n\n      match goal with\n      | [ H : context[reply2requests j1] |- _ ] => rename H into rep2req\n      end.\n      applydup reply2requests_implies_last_reply_state_extends in rep2req as ext.\n      applydup ext in fl0.\n      exrepnd.\n      rewrite fl8 in *; ginv.\n\n      assert (ts <= lre_timestamp e4) as lets by omega.\n\n      autodimp fl5 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp fl9 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp out0 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n\n      assert (lre_reply e4 = Some r1) as eqr1 by (pbft_dest_all x; try omega).\n\n      assert (Some r1 = Some r2) as eqrs by congruence.\n      ginv.\n    }\n\n    {\n      assert (next_to_execute st1 <= next_to_execute st0) as lenext by (allrw; simpl; omega).\n      applydup next_to_execute_is_greater_than_one in h0; auto;[].\n\n      rewrite <- ite_first_state_sm_on_event_as_before in w0.\n      unfold ite_first in *.\n      destruct (dec_isFirst e2) as [d1|d1]; ginv; subst; simpl in *;[].\n      pose proof (last_reply_state_increases\n                    eo (local_pred e2) j2 st0\n                    (next_to_execute st1)) as u.\n      repeat (autodimp u hyp); autorewrite with eo; auto; try omega; eauto 3 with pbft eo;[].\n      exrepnd.\n\n      pose proof (same_states_if_same_next_to_execute eo e' e1 j j1 st' st1) as v.\n      repeat (autodimp v hyp); try (complete (allrw; auto)); eauto 5 with pbft eo;[].\n      repnd.\n      rewrite v in u0.\n\n      applydup u0 in fl2.\n      exrepnd.\n\n      match goal with\n      | [ H : context[reply2requests j2] |- _ ] => rename H into rep2req\n      end.\n      applydup reply2requests_implies_last_reply_state_extends in rep2req as ext.\n      applydup ext in fl0.\n      exrepnd.\n      rewrite fl8 in *; ginv.\n\n      assert (ts <= lre_timestamp e0) as lets by omega.\n\n      autodimp fl5 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp fl9 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp out14 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n\n      assert (lre_reply e0 = Some r2) as eqr2 by (pbft_dest_all x; try omega).\n\n      assert (Some r1 = Some r2) as eqrs by congruence.\n      ginv.\n    }\n  Qed.\n\n\n(*  Definition mk_reply\n             (v : View)\n             (t : Timestamp)\n             (c : Client)\n             (i : Rep)\n             (r : PBFTresult)\n             (a : Tokens) : Reply :=\n    reply (bare_reply v t c i r) a.\n\n  Lemma sent_replies_are_committed :\n    forall (eo : EventOrdering) (e : Event) p dst st i,\n      loc e = PBFTreplica i\n      -> In (send_reply v t c i r) (output_system_on_event_ldata PBFTsys eo e)\n      -> state_sm_on_event (PBFTreplicaSM i) eo e = Some st\n      -> prepare_in_log p (log st) = true\n      -> exists n,\n          committed_log (request_data ) (log e).\n  Proof.\n  Qed.*)\n\n\n(*\n  Lemma in_check_send_replies_implies :\n    forall i v ks\n           (giop : option GeneratedInfo)\n           (msgs : DirectedMsgs)\n           (sn   : SeqNum)\n           (m    : DirectedMsg)\n           (st1 st2 : PBFTstate),\n      check_send_replies i v ks giop st1 sn = (msgs, st2)\n      -> In m msgs\n      -> exists (prepop : option Prepare)\n                (commop : option Commit)\n                (entry : PBFTlogEntry),\n          giop = Some (MkGeneratedInfo prepop commop entry)\n          /\\ is_committed_entry entry = true\n          /\\ m = send_check_ready check_ready (PBFTreplica i)\n          /\\ st2 = add_to_ready st1 sn.\n  Proof.\n    introv h j.\n    unfold check_send_replies in h.\n    destruct giop; simpl in *; tcsp.\n    - destruct g.\n      dest_cases x; ginv; simpl in *; tcsp.\n      + inversion h; subst; clear h; simpl in *; repndors; subst; tcsp.\n        eexists; eexists; eexists; dands; eauto.\n      + inversion h; subst; clear h; simpl in *; tcsp.\n    - inversion h; subst; simpl in *; tcsp.\n  Qed.\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_returns_prep_comm_rep :\n    forall (slf  : Rep)\n           (pps  : list (Pre_prepare * PBFTdigest))\n           (st1 st2 : PBFTstate)\n           (msgs : DirectedMsgs)\n           (m    : DirectedMsg),\n      add_prepares_to_log_from_new_view_pre_prepares slf st1 pps = (st2, msgs)\n      -> In m msgs\n      -> (exists i p, m = MkDMsg i (PBFTprepare p))\n         \\/\n         (exists i c, m = MkDMsg i (PBFTcommit c))\n         \\/\n         (exists i r, m = MkDMsg i (PBFTcheck_ready r)).\n  Proof.\n    induction pps; introv e i; simpl in *; ginv.\n\n    - inversion e; clear e; subst; simpl in *; tcsp.\n\n    - dest_cases w; symmetry in Heqw.\n      dest_cases x; symmetry in Heqx.\n      inversion e; clear e; subst.\n      apply in_app_iff in i; repndors.\n\n      + unfold add_prepare_to_log_from_new_view_pre_prepare in Heqw.\n        repnd; simpl in *.\n        dest_cases y; symmetry in Heqy; simpl in *; tcsp;[|].\n\n        * dest_cases u; symmetry in Hequ; simpl in *; tcsp;[].\n          dest_cases v; symmetry in Heqv; simpl in *; tcsp;[].\n          inversion Heqw; subst; clear Heqw.\n          apply in_app_iff in i; repndors.\n\n          { unfold check_broadcast_prepare in i.\n            dest_cases q; subst; simpl in *.\n            destruct q; simpl in *.\n            dest_cases p; symmetry in Heqp; simpl in *; tcsp;[|].\n\n            - inversion Heqv; subst; clear Heqv; simpl in *.\n              dest_cases k; symmetry in Heqk; simpl in *; tcsp;[].\n              dest_cases r; subst; simpl in *;tcsp;[|].\n\n              + apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                left.\n                eexists; eexists; reflexivity.\n\n              + apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                left.\n                eexists; eexists; reflexivity.\n\n            - inversion Heqv; clear Heqv; subst; simpl in *.\n              dest_cases k; symmetry in Heqk; simpl in *; tcsp.\n              dest_cases r; symmetry in Heqr; simpl in *; tcsp;[|].\n\n              + apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                left.\n                eexists; eexists; reflexivity.\n\n              + apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                left.\n                eexists; eexists; reflexivity. }\n\n          { unfold check_broadcast_commit in i.\n            dest_cases q; symmetry in Heqq; subst; simpl in *; tcsp;[|].\n\n            - destruct q; simpl in *.\n              dest_cases k; symmetry in Heqk; simpl in *; tcsp;[|].\n\n              + inversion Heqv; clear Heqv; subst; simpl in *.\n                apply in_app_iff in i; simpl in *; repndors; tcsp.\n\n                * dest_cases r; symmetry in Heqr; simpl in *; tcsp;[].\n                  dest_cases p; subst; simpl in *; tcsp;[|].\n\n                  { apply in_broadcast2others in i; exrepnd; subst.\n                    right; left.\n                    eexists; eexists; reflexivity. }\n\n                  { apply in_broadcast2others in i; exrepnd; subst.\n                    right; left.\n                    eexists; eexists; reflexivity. }\n\n                * subst; simpl in *.\n                  right; right.\n                  eexists; eexists; reflexivity.\n\n              + inversion Heqv; clear Heqv; subst; simpl in *; tcsp.\n                allrw app_nil_r.\n                dest_cases q; symmetry in Heqq.\n                dest_cases r; subst; simpl in *; tcsp;[|].\n\n                * apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                  right; left.\n                  eexists; eexists; reflexivity.\n\n                * apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n                  right; left.\n                  eexists; eexists; reflexivity.\n\n            - inversion Heqv; clear Heqv; subst; simpl in *; tcsp. }\n\n        * inversion Heqw; clear Heqw; subst; simpl in *.\n          apply in_broadcast2others in i; exrepnd; subst.\n          left.\n          eexists; eexists; reflexivity.\n\n      + eapply IHpps in Heqx;[|eauto]; auto.\n  Qed.\n\n  Lemma update_state_new_view_returns_checkpoint :\n    forall (slf  : Rep)\n           (nv   : NewView)\n           (st1 st2 : PBFTstate)\n           (msgs : DirectedMsgs)\n           (m    : DirectedMsg),\n      update_state_new_view slf st1 nv = (st2, msgs)\n      -> In m msgs\n      -> (exists i c, m = MkDMsg i (PBFTcheckpoint c)).\n  Proof.\n    introv h i.\n    unfold update_state_new_view in h.\n    dest_cases w; symmetry in Heqw;[].\n    dest_cases y; symmetry in Heqy;[|].\n\n    - dest_cases z; subst; simpl in *;[|].\n\n      + dest_cases x; symmetry in Heqx.\n        inversion h; subst; clear h.\n        unfold broadcast_checkpoint_op in i.\n        dest_cases q; subst; simpl in *.\n        apply in_broadcast2others in i; exrepnd; subst; simpl in *.\n        exists o q; auto.\n\n      + inversion h; subst; clear h; simpl in *; tcsp.\n\n    - inversion h; subst; clear h; simpl in *; tcsp.\n  Qed.\n\n  (* replies are sent on receipt of check_ready messages *)\n  Lemma send_reply_iff :\n    forall (eo : EventOrdering) (e : Event) v t c i r a,\n      In (send_reply (mk_reply v t c i r a)) (output_system_on_event_ldata PBFTsys eo e)\n      <->\n      (\n        exists (n      : Rep)\n               (cr     : CheckReady)\n               (st st' : PBFTstate)\n               (sns    : list SeqNum)\n               (entry  : PBFTlogEntry)\n               (reps   : list (option Reply))\n               (smst   : PBFTsm_state)\n               (lastr  : LastReplyState)\n               (msgs   : DirectedMsgs),\n          loc e = PBFTreplica n\n          /\\ trigger e = PBFTcheck_ready cr\n          /\\ state_sm_before_event (PBFTreplicaSM n) eo e = Some st\n          /\\ find_entry (log st) (next_to_execute st) = Some entry\n          /\\ reply2requests\n               n\n               (current_view st)\n               (local_keys st)\n               (log_entry2requests entry)\n               (sm_state st)\n               (last_reply_state st) = (reps, smst, lastr)\n          /\\ check_broadcast_checkpoint\n               n\n               (next_to_execute st)\n               (current_view st)\n               (local_keys st)\n               (change_log_entry\n                  (change_last_reply_state\n                     (change_sm_state (increment_next_to_execute st) smst) lastr)\n                  (add_replies2entry entry reps)) = (st', msgs)\n          /\\ ready st = next_to_execute st :: sns\n          /\\ In (mk_reply v t c i r a) (list_option2list reps)\n\n      ).\n  Proof.\n    introv.\n    rewrite in_output_system_on_event_ldata.\n    split; intro h.\n\n    - unfold PBFTsys in h.\n      remember (loc e) as n; destruct n; simpl in *;\n        unfold MStateMachine in *; ginv;\n          [|apply MhaltedSM_output in h; tcsp];[].\n\n      rw @loutput_sm_on_event_unroll2 in h; simpl in h.\n\n      unfold PBFTreplica_update in h at 1; simpl in h.\n\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      match goal with\n      | [ H : context[option_map _ ?s] |- _ ] =>\n        remember s as sop; symmetry in Heqsop; destruct sop; simpl in *; tcsp\n      end.\n\n      destruct trig; simpl in *; tcsp.\n\n      + unfold PBFThandle_request in h; simpl in h.\n        dest_all w.\n        repndors; tcsp; ginv.\n\n      + unfold PBFThandle_pre_prepare in h; simpl in *.\n        dest_all w;[].\n\n        apply in_app_iff in h; repndors;[|].\n\n        * unfold check_broadcast_prepare in h.\n          dest_all x.\n          destruct x; simpl in *.\n          fold DirectedMsgs in *.\n          dest_all x.\n\n        * apply in_app_iff in h;repndors;[|].\n\n          { unfold check_broadcast_commit in h.\n            dest_all x.\n            destruct x; simpl in *.\n            fold DirectedMsgs in *.\n            dest_all x. }\n\n          { match goal with\n            | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n              eapply in_check_send_replies_implies in H;[|exact h]\n            end.\n            exrepnd; subst; simpl in *; ginv. }\n\n      + unfold PBFThandle_prepare in h; simpl in *.\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y;[].\n        dest_cases y; symmetry in Heqy; simpl in *;[].\n        dest_cases z;[].\n        dest_cases z; symmetry in Heqz; simpl in *;[].\n        dest_cases w; symmetry in Heqw; simpl in *;[].\n        dest_cases u; symmetry in Hequ; simpl in *;[].\n\n        apply in_app_iff in h; repndors.\n\n        { unfold check_broadcast_commit in h.\n          destruct w0; simpl in *; tcsp;[].\n          destruct g; simpl in *; tcsp;[].\n          dest_cases d; symmetry in Heqd;[].\n          dest_cases q; symmetry in Heqq; ginv;[|].\n\n          { dest_cases t; simpl in *;[|].\n            - apply in_broadcast2others in h; exrepnd; ginv.\n            - apply in_broadcast2others in h; exrepnd; ginv. }\n\n          { dest_cases t; simpl in *;[|].\n            - apply in_broadcast2others in h; exrepnd; ginv.\n            - apply in_broadcast2others in h; exrepnd; ginv. }\n        }\n\n        { eapply in_check_send_replies_implies in Hequ;[|exact h].\n          exrepnd; subst; simpl in *; ginv. }\n\n      + unfold PBFThandle_commit in h; simpl in *.\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y;[].\n        dest_cases y; symmetry in Heqy; simpl in *;[].\n        dest_cases z;[].\n        dest_cases z; symmetry in Heqz; simpl in *;[].\n        dest_cases w; symmetry in Heqw; simpl in *;[].\n        dest_cases u; symmetry in Hequ; simpl in *;[].\n\n        eapply in_check_send_replies_implies in Hequ;[|exact h].\n        exrepnd; subst; simpl in *; ginv.\n\n      + unfold PBFThandle_checkpoint in h.\n        dest_cases x;[].\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y; symmetry in Heqy; simpl in *;[].\n        dest_cases z; symmetry in Heqz; simpl in *;[].\n        dest_cases w; symmetry in Heqw; simpl in *;[].\n        dest_cases u; symmetry in Hequ; simpl in *;[].\n        repndors; tcsp; ginv.\n\n      + unfold PBFThandle_check_ready in h; simpl in *.\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n\n        unfold find_and_execute_requests in Heqx.\n        dest_cases w; symmetry in Heqw; repnd; ginv;[].\n\n        unfold execute_requests in Heqw.\n        remember (ready p) as rd; symmetry in Heqrd.\n        destruct rd; [inversion Heqw; subst; simpl in *; tcsp|];[].\n\n        dest_cases y; subst; simpl in *; tcsp;[|];\n          [|inversion Heqw; subst; simpl in *; tcsp];[].\n\n        dest_cases y; symmetry in Heqy; simpl in *; tcsp;[|];\n          [|inversion Heqw; subst; simpl in *; tcsp];[].\n        dest_cases u; symmetry in Hequ; repnd; simpl in *.\n        dest_cases q; symmetry in Heqq.\n        inversion Heqw; subst; clear Heqw; simpl in *.\n\n        apply in_app_iff in h; simpl in *; repndors; ginv;[|].\n\n        {\n          apply in_map_iff in h; exrepnd.\n          inversion h1; clear h1.\n          remember (reply2client x) as cl.\n          subst; simpl in *; GC.\n\n          exists n c0 p w1 w0 y u2 u0 u1 q1.\n          dands; auto.\n        }\n\n        {\n          unfold check_broadcast_checkpoint in Heqq; simpl in *.\n          dest_cases w; symmetry in Heqw; simpl in *; tcsp;[|].\n\n          - dest_cases z; symmetry in Heqz; ginv.\n            apply in_broadcast2others in h; exrepnd; ginv.\n\n          - inversion Heqq; subst; simpl in *; tcsp.\n        }\n\n      + repndors; tcsp; ginv.\n\n      + unfold PBFThandle_expired_timer in h.\n        dest_cases x;[].\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y; symmetry in Heqy; simpl in *; tcsp;[|].\n\n        * repnd; simpl in *.\n          apply in_broadcast2others in h; exrepnd; ginv.\n\n        * apply in_broadcast2others in h; exrepnd; ginv.\n\n      + unfold PBFThandle_view_change in h.\n        dest_cases x; simpl in *;[].\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y; symmetry in Heqy; simpl in *;[].\n        dest_cases z; symmetry in Heqz; simpl in *;[].\n        dest_cases q; symmetry in Heqq; simpl in *;[].\n        repnd; simpl in *.\n        dest_cases w; symmetry in Heqw; repnd; simpl in *;[].\n        apply in_broadcast2others in h; exrepnd; ginv.\n\n      + unfold PBFThandle_new_view in h.\n        dest_cases x;[].\n        dest_cases x; symmetry in Heqx; simpl in *;[].\n        dest_cases y; symmetry in Heqy; simpl in *;[].\n        dest_cases z; symmetry in Heqz; simpl in *;[].\n        dest_cases w; symmetry in Heqw; simpl in *;[].\n        dest_cases q; symmetry in Heqq; simpl in *;[].\n        dest_cases u; symmetry in Hequ; simpl in *;[].\n        dest_cases k; symmetry in Heqk; simpl in *;[].\n        apply in_app_iff in h; repndors.\n\n        * eapply add_prepares_to_log_from_new_view_pre_prepares_returns_prep_comm_rep in Hequ;[|exact h].\n          repndors; exrepnd; ginv.\n\n        * eapply update_state_new_view_returns_checkpoint in Heqk;[|eauto].\n          exrepnd; ginv.\n\n    - exrepnd.\n      unfold PBFTsys.\n\n      allrw; simpl.\n\n      rw @loutput_sm_on_event_unroll2; simpl.\n\n      unfold PBFTreplica_update at 1; simpl.\n      allrw.\n      fold DirectedMsgs in *.\n\n      match goal with\n      | [ |- context[option_map _ ?s] ] =>\n        remember s as sop; symmetry in Heqsop; destruct sop; simpl in *; tcsp\n      end;[].\n      ginv.\n\n      unfold PBFThandle_check_ready.\n      unfold find_and_execute_requests.\n      unfold execute_requests.\n      allrw; simpl.\n\n      dest_cases w.\n      allrw; simpl.\n      apply in_app_iff; simpl.\n\n      left.\n      apply in_map_iff; eexists; dands;[reflexivity|].\n      auto.\n  Qed.\n\n  Definition hidden_check_broadcast_checkpoint\n             (slf    : Rep)\n             (sn     : SeqNum)\n             (vn     : View)\n             (keys   : local_key_map)\n             (s      : PBFTstate)\n             (s'     : PBFTstate)\n             (msgs   : DirectedMsgs) : Prop\n    := check_broadcast_checkpoint slf sn vn keys s = (s', msgs).\n\n  Notation \"'CHECK_BROADCAST_CHECKPOINT'\" :=\n    (hidden_check_broadcast_checkpoint _ _ _ _ _ _ _).\n\n  Lemma hide_check_broadcast_checkpoint :\n    forall slf sn vn keys s s' msgs,\n      (check_broadcast_checkpoint slf sn vn keys s = (s', msgs))\n      = hidden_check_broadcast_checkpoint slf sn vn keys s s' msgs.\n  Proof. auto. Qed.\n\n  Definition hidden_reply2requests\n             (slf    : Rep)\n             (view   : View)\n             (keys   : local_key_map)\n             (reqs   : list Request)\n             (state  : PBFTsm_state)\n             (lastr  : LastReplyState)\n             (reps   : list (option Reply))\n             (state' : PBFTsm_state)\n             (lastr' : LastReplyState) : Prop\n    := reply2requests slf view keys reqs state lastr = (reps, state', lastr').\n\n  Notation \"'REPLY2REQUESTS'\" :=\n    (hidden_reply2requests _ _ _ _ _ _ _ _ _).\n\n  Lemma hide_reply2requests :\n    forall slf view keys reqs state lastr reps state' lastr',\n      (reply2requests slf view keys reqs state lastr = (reps, state', lastr'))\n      = hidden_reply2requests slf view keys reqs state lastr reps state' lastr'.\n  Proof. auto. Qed.\n\n  Ltac hide_hyps :=\n    repeat match goal with\n           | [ H : check_broadcast_checkpoint _ _ _ _ _ = (_, _) |- _ ] =>\n             rewrite hide_check_broadcast_checkpoint in H\n           | [ H : reply2requests _ _ _ _ _ _ = (_, _, _) |- _ ] =>\n             rewrite hide_reply2requests in H\n           end.\n\n  Ltac unhide_hyps :=\n    repeat match goal with\n           | [ H : hidden_check_broadcast_checkpoint _ _ _ _ _ _ _ |- _ ] =>\n             rewrite <- hide_check_broadcast_checkpoint in H\n           | [ H : hidden_check_broadcast_checkpoint _ _ _ _ _ _ _ _ _ |- _ ] =>\n             rewrite <- hide_reply2requests in H\n           end.\n\n  Lemma in_reply2requests :\n    forall slf view keys reqs state lastr rep reps state' lastr',\n      reply2requests slf view keys reqs state lastr = (reps, state', lastr')\n      -> In rep (list_option2list reps)\n      ->\n      exists (req : Request)\n             (reqs1 reqs2 : list Request)\n             (reps1 reps2 : list (option Reply))\n             (state1 state2 : PBFTsm_state)\n             (lastr1 lastr2 : LastReplyState),\n        reqs = reqs1 ++ req :: reqs2\n        /\\ reply2requests slf view keys reqs1 state lastr = (reps1, state1, lastr1)\n        /\\ reply2request slf view keys req state1 lastr1 = (Some rep, state2, lastr2)\n        /\\ reply2requests slf view keys reqs2 state2 lastr2 = (reps2, state', lastr').\n  Proof.\n    induction reqs; introv e i; simpl in *; ginv; simpl in *; tcsp.\n    dest_cases w; symmetry in Heqw; repnd.\n    dest_cases y; symmetry in Heqy; repnd.\n    ginv; simpl in *.\n    dest_cases x; subst; simpl in *; repndors; subst; tcsp;[| |].\n\n    - exists a ([] : list Request) reqs ([] : list (option Reply)) y2 state w0 lastr w1.\n      simpl; dands; auto.\n\n    - eapply IHreqs in Heqy;[|eauto]; clear IHreqs.\n      exrepnd; subst.\n      exists req (a :: reqs1) reqs2 (Some x :: reps1) reps2 state1 state2 lastr1 lastr2; simpl.\n      allrw; simpl; dands; auto.\n\n    - eapply IHreqs in Heqy;[|eauto]; clear IHreqs.\n      exrepnd; subst.\n      exists req (a :: reqs1) reqs2 (None :: reps1) reps2 state1 state2 lastr1 lastr2; simpl.\n      allrw; simpl; dands; auto.\n  Qed.\n\n  Lemma eq_timestamps : forall t1 t2, timestamp2nat t1 = timestamp2nat t2 -> t1 = t2.\n  Proof.\n    introv; destruct t1, t2; simpl in *; auto.\n  Qed.\n\n  Lemma in_reply2request :\n    forall slf view keys req state lastr rep state' lastr',\n      reply2request slf view keys req state lastr = (Some rep, state', lastr')\n      ->\n      exists opr ts c entry result,\n        request2info req = Some (opr, ts, c)\n        /\\ find_last_reply_entry_corresponding_to_client lastr c = Some entry\n        /\\ rep = reply (bare_reply view ts c slf result) (authenticate (PBFTmsg_bare_reply (bare_reply view ts c slf result)) keys)\n        /\\\n        (\n          (\n            lre_timestamp entry < ts\n            /\\ PBFTsm_update c state opr = (result, state')\n            /\\ lastr' = update_last_reply_timestamp_and_result lastr c ts result\n          )\n          \\/\n          (\n            lre_timestamp entry = ts\n            /\\ lre_reply entry = Some result\n            /\\ lastr' = lastr\n            /\\ state' = state\n          )\n        ).\n\n  Proof.\n    introv e.\n    unfold reply2request in e.\n    dest_all w;[|].\n\n    - exists w0 w3 w2 w w1; dands; auto.\n\n    - exists w0 w3 w2 w w5; dands; tcsp.\n      right; dands; auto; try omega.\n      apply eq_timestamps; omega.\n  Qed.\n\n  Lemma PBFTagreement :\n    forall (eo : EventOrdering),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> internal_messages_were_sent_usys eo PBFTsys\n      -> forall (e1 e2 : Event)\n                (c     : Client)\n                (t     : Timestamp)\n                (v1 v2 : View)\n                (i1 i2 : Rep)\n                (r1 r2 : PBFTresult)\n                (tok1 tok2 : Tokens),\n        isCorrect e1\n        -> isCorrect e2\n        -> In (send_reply (mk_reply v1 t c i1 r1 tok1)) (output_system_on_event_ldata PBFTsys eo e1)\n        -> In (send_reply (mk_reply v2 t c i2 r2 tok2)) (output_system_on_event_ldata PBFTsys eo e2)\n        -> r1 = r2.\n  Proof.\n    introv sentbyz sentint isCor1 isCor2 send1 send2.\n\n    destruct (PBFTresdeq r1 r2) as [d|d]; auto.\n    assert False; tcsp.\n\n    (* replies are sent in response to check-ready messages *)\n    apply send_reply_iff in send1.\n    apply send_reply_iff in send2.\n    exrepnd.\n\n    repeat match goal with\n           | [ H : reply2requests _ _ _ _ _ _ = _ |- _ ] =>\n             eapply in_reply2requests in  H;[|eauto];[]\n           end.\n    exrepnd.\n\n    match goal with\n    | [ H : reply2request _ _ _ _ _ _ = _ |- _ ] => apply in_reply2request in H\n    end.\n\n    SearchAbout reply2requests.\n\n  (*\n    hide_hyps.\n\n    pose proof (sentint e2) as q.\n    match goal with\n    | [ H1 : trigger ?e = _ , H2 : context[is_internal_message (trigger ?e)] |- _ ] =>\n      rewrite H1 in H2\n    end.\n    repeat (autodimp q hyp);[].\n    exrepnd.\n*)\n\n\n  Qed.\n*)\n\nEnd PBFTagreement.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFTagreement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.1784075048997109}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CroniesTermInterface.\n\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.CandidateEntriesInterface.\n\nRequire Import VerdiRaft.RefinementSpecLemmas.\nRequire Import VerdiRaft.RefinementCommonTheorems.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.PrevLogCandidateEntriesTermInterface.\n\nSection PrevLogCandidateEntriesTerm.\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 {cei : candidate_entries_interface}.\n  Context {cti : cronies_term_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Lemma prevLog_candidateEntriesTerm_init :\n    refined_raft_net_invariant_init prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_init, prevLog_candidateEntriesTerm.\n    simpl. intuition.\n  Qed.\n\n  Lemma candidateEntriesTerm_ext : forall t sigma sigma',\n      (forall h, sigma' h = sigma h) ->\n      candidateEntriesTerm t sigma ->\n      candidateEntriesTerm t sigma'.\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    repeat find_higher_order_rewrite. intuition.\n  Qed.\n\n  Lemma candidateEntriesTerm_same : forall st st' t,\n       candidateEntriesTerm t st ->\n       (forall h, cronies (fst (st' h)) = cronies (fst (st h))) ->\n       (forall h, currentTerm (snd (st' h)) = currentTerm (snd (st h))) ->\n       (forall h, type (snd (st' h)) = type (snd (st h))) ->\n       candidateEntriesTerm t st'.\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    repeat find_higher_order_rewrite.\n    intuition.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_client_request :\n    refined_raft_net_invariant_client_request prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply candidateEntriesTerm_same; eauto; intros;\n      update_destruct_simplify; auto.\n      + now erewrite update_elections_data_client_request_cronies by eauto.\n      + find_apply_lem_hyp handleClientRequest_type. intuition.\n      + find_apply_lem_hyp handleClientRequest_type. intuition.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and. subst. simpl in *.\n      exfalso. eapply handleClientRequest_no_append_entries; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma update_elections_data_timeout_cronies :\n    forall h d out d' l t,\n      handleTimeout h (snd d) = (out, d', l) ->\n      cronies (update_elections_data_timeout h d) t = cronies (fst d) t \\/\n      (t = currentTerm d' /\\ type d' = Candidate /\\\n       cronies (update_elections_data_timeout h d) t = votesReceived d').\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto.\n    break_match; auto.\n  Qed.\n\n  Lemma handleClientRequest_preserves_candidateEntriesTerm:\n    forall net h d t out l,\n      refined_raft_intermediate_reachable net ->\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      candidateEntriesTerm t (nwState net) ->\n      candidateEntriesTerm t\n                           (update name_eq_dec (nwState net) h\n                                   (update_elections_data_timeout h (nwState net h), d)).\n  Proof using cti. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists. break_and.\n    match goal with\n    | [ H : handleTimeout _ _ = _ |- _ ] =>\n      pose proof H;\n        eapply update_elections_data_timeout_cronies with (t := t) in H\n    end. break_or_hyp.\n    - update_destruct_simplify; auto.\n      find_copy_apply_lem_hyp handleTimeout_type_strong.\n      intuition; repeat find_rewrite; auto.\n      find_apply_lem_hyp wonElection_exists_voter.\n      break_exists.\n      find_apply_lem_hyp in_dedup_was_in.\n      find_copy_apply_lem_hyp cronies_term_invariant; auto.\n      simpl in *.\n      lia.\n    - update_destruct_simplify; auto.\n      find_copy_apply_lem_hyp handleTimeout_type_strong.\n      find_apply_lem_hyp wonElection_exists_voter.\n      break_exists.\n      find_apply_lem_hyp in_dedup_was_in.\n      find_copy_apply_lem_hyp cronies_term_invariant; auto.\n      intuition; subst; repeat find_rewrite; auto;\n      simpl in *; lia.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_timeout :\n    refined_raft_net_invariant_timeout prevLog_candidateEntriesTerm.\n  Proof using cti. \n    unfold refined_raft_net_invariant_timeout, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply handleClientRequest_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      exfalso. eapply handleTimeout_not_is_append_entries; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntries_preserves_candidateEntriesTerm :\n    forall net h t n pli plt es ci d m t',\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update name_eq_dec (nwState net) h\n                                 (update_elections_data_appendEntries\n                                    h\n                                    (nwState net h) t n pli plt es ci, d)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists. break_and.\n    update_destruct_simplify.\n    - rewrite update_elections_data_appendEntries_cronies.\n      find_apply_lem_hyp handleAppendEntries_type.\n      intuition; subst; repeat find_rewrite; auto.\n      discriminate.\n    - intuition.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_append_entries :\n    refined_raft_net_invariant_append_entries prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply handleAppendEntries_preserves_candidateEntriesTerm; eauto.\n    - exfalso. eapply handleAppendEntries_not_append_entries; eauto.\n      simpl in *. subst. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntriesReply_preserves_candidateEntriesTerm :\n  forall net h h' t es r st' ms t',\n    handleAppendEntriesReply h (snd (nwState net h)) h' t es r = (st', ms) ->\n    refined_raft_intermediate_reachable net ->\n    candidateEntriesTerm t' (nwState net) ->\n    candidateEntriesTerm t' (update name_eq_dec (nwState net) h (fst (nwState net h), st')).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    find_apply_lem_hyp handleAppendEntriesReply_type.\n    update_destruct_simplify.\n    - intuition; repeat find_rewrite; auto. discriminate.\n    - auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eauto using handleAppendEntriesReply_preserves_candidateEntriesTerm.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      find_apply_lem_hyp handleAppendEntriesReply_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma update_elections_data_requestVote_cronies_same :\n    forall h h' t lli llt st,\n      cronies (update_elections_data_requestVote h h' t h' lli llt st) =\n      cronies (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma advanceCurrentTerm_same_or_type_follower :\n    forall st t,\n      advanceCurrentTerm st t = st \\/\n      type (advanceCurrentTerm st t) = Follower.\n  Proof using. \n    unfold advanceCurrentTerm.\n    intros. repeat break_match; auto.\n  Qed.\n\n  Lemma handleRV_advanceCurrentTerm_preserves_candidateEntriesTerm :\n    forall net h h' t lli llt t',\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t'\n                       (update name_eq_dec (nwState net) h\n                               (update_elections_data_requestVote h h' t h' lli llt (nwState net h),\n                                advanceCurrentTerm (snd (nwState net h)) t)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct_simplify; intuition.\n    - now rewrite update_elections_data_requestVote_cronies_same.\n    - intros.\n      match goal with\n      | [ H : context [advanceCurrentTerm ?st ?t] |- _ ] =>\n        pose proof advanceCurrentTerm_same_or_type_follower st t\n      end.\n      intuition.\n      + repeat find_rewrite. auto.\n      + congruence.\n  Qed.\n\n  Lemma handleRequestVote_preserves_candidateEntriesTerm :\n    forall net h h' t lli llt d t' m,\n      handleRequestVote h (snd (nwState net h)) t h' lli llt = (d, m) ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update name_eq_dec (nwState net) h\n                                 (update_elections_data_requestVote\n                                    h h' t h' lli llt (nwState net h), d)).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct_simplify; intuition.\n    - now rewrite update_elections_data_requestVote_cronies_same.\n    - unfold handleRequestVote, advanceCurrentTerm in *.\n      repeat break_match; do_bool; repeat find_inversion; simpl in *; break_and; try discriminate; auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_request_vote :\n    refined_raft_net_invariant_request_vote prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply handleRequestVote_preserves_candidateEntriesTerm; eauto.\n    - exfalso. eapply handleRequestVote_no_append_entries; eauto.\n      simpl in *. subst. eauto 10.\n  Qed.\n\n  Lemma handleRequestVoteReply_preserves_candidateEntriesTerm :\n    forall net h h' t r st' t',\n      handleRequestVoteReply h (snd (nwState net h)) h' t r = st' ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update name_eq_dec (nwState net) h\n                                 (update_elections_data_requestVoteReply h h' t r (nwState net h),\n                                  st')).\n  Proof using cci. \n    unfold candidateEntriesTerm.\n    intros.\n    break_exists_exists.\n    update_destruct_simplify; auto.\n    break_and.\n    unfold raft_data in *. simpl in *.\n    unfold update_elections_data_requestVoteReply.\n    match goal with\n    | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n      remember (handleRequestVoteReply h st h' t r) as new_state\n    end; find_copy_apply_lem_hyp handleRequestVoteReply_spec.\n    repeat (break_match); intuition; repeat find_rewrite; intuition;\n    simpl; break_if; auto.\n    - find_apply_lem_hyp cronies_correct_invariant.\n      unfold cronies_correct in *. intuition.\n      unfold votes_received_leaders in *.\n      match goal with\n      | H :  Leader = _ |- _ =>\n        symmetry in H\n      end. find_apply_hyp_hyp.\n      eapply wonElection_no_dup_in;\n        eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n    - destruct (serverType_eq_dec (type (snd (nwState net x))) Leader); intuition.\n      find_apply_lem_hyp cronies_correct_invariant; auto.\n      eapply wonElection_no_dup_in;\n        eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply prevLog_candidateEntriesTerm.\n  Proof using cci. \n    unfold refined_raft_net_invariant_request_vote_reply, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp.\n    find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n    eapply candidateEntriesTerm_ext; eauto.\n    subst.\n    eapply handleRequestVoteReply_preserves_candidateEntriesTerm; eauto.\n  Qed.\n\n  Lemma doLeader_preserves_candidateEntriesTerm :\n    forall net gd d h os d' ms t',\n      nwState net h = (gd, d) ->\n      doLeader d h = (os, d', ms) ->\n      candidateEntriesTerm t' (nwState net) ->\n      candidateEntriesTerm t' (update name_eq_dec (nwState net) h (gd, d')).\n  Proof using. \n    unfold candidateEntriesTerm.\n    intros. break_exists_exists.\n    break_and.\n    update_destruct_simplify; auto.\n    split.\n    - match goal with\n      | [ H : nwState ?net ?h = (?x, _) |- _ ] =>\n        replace (x) with (fst (nwState net h)) in * by (rewrite H; auto)\n      end.\n      intuition.\n    - match goal with\n      | [ H : nwState ?net ?h = (_, ?x) |- _ ] =>\n        replace (x) with (snd (nwState net h)) in * by (rewrite H; auto); clear H\n      end.\n      find_apply_lem_hyp doLeader_type.\n      intuition. subst. repeat find_rewrite.\n      auto.\n  Qed.\n\n  Lemma getNextIndex_ext :\n    forall st st' h,\n      nextIndex st' = nextIndex st ->\n      log st' = log st ->\n      getNextIndex st' h = getNextIndex st h.\n  Proof using. \n    unfold getNextIndex.\n    intros.\n    repeat find_rewrite.\n    auto.\n  Qed.\n\n  Lemma replicaMessage_ext :\n    forall st st' h h',\n      nextIndex st' = nextIndex st ->\n      log st' = log st ->\n      currentTerm st' = currentTerm st ->\n      commitIndex st' = commitIndex st ->\n      replicaMessage st' h h' = replicaMessage st h h'.\n  Proof using. \n    unfold replicaMessage.\n    intros.\n    repeat break_match; repeat tuple_inversion; repeat find_rewrite;\n    erewrite getNextIndex_ext in * by eauto; congruence.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_do_leader :\n    refined_raft_net_invariant_do_leader prevLog_candidateEntriesTerm.\n  Proof using cei. \n    unfold refined_raft_net_invariant_do_leader, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_apply_hyp_hyp.\n      eapply candidateEntriesTerm_ext; eauto.\n      eapply doLeader_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      find_copy_eapply_lem_hyp doLeader_messages; eauto.\n      break_and. intuition.\n      + lia.\n      + break_exists. break_and.\n        red.\n        find_apply_lem_hyp candidate_entries_invariant.\n        unfold CandidateEntries, candidateEntries_host_invariant in *.\n        find_apply_lem_hyp findAtIndex_elim. break_and.\n        match goal with\n        | [ H : nwState ?net ?h = (?y, ?x) |- _ ] =>\n          replace (x) with (snd (nwState net h)) in * by (rewrite H; auto);\n          replace (y) with (fst (nwState net h)) in * by (rewrite H; auto)\n        end.\n\n        eapply_prop_hyp In In.\n        subst.\n        find_eapply_lem_hyp (doLeader_preserves_candidateEntries); eauto.\n\n        match goal with\n        | [ H : nwState ?net ?h = (?y, ?x) |- _ ] => clear H\n        end.\n\n        unfold candidateEntries in *. break_exists_exists.\n        find_higher_order_rewrite.\n        update_destruct_simplify; auto.\n  Qed.\n\n  Lemma doGenericServer_preserves_candidateEntriesTerm :\n    forall net gd d h os d' ms t,\n      nwState net h = (gd, d) ->\n      doGenericServer h d = (os, d', ms) ->\n      candidateEntriesTerm t (nwState net) ->\n      candidateEntriesTerm t (update name_eq_dec (nwState net) h (gd, d')).\n  Proof using. \n    intros.\n    find_apply_lem_hyp doGenericServer_type. break_and.\n    eapply candidateEntriesTerm_same; eauto.\n    - intros. update_destruct_simplify; auto.\n      find_rewrite. simpl. auto.\n    - intros. update_destruct_simplify; auto.\n      repeat find_rewrite.  auto.\n    - intros. update_destruct_simplify; auto.\n      repeat find_rewrite.  auto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_do_generic_server :\n    refined_raft_net_invariant_do_generic_server prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp. break_or_hyp.\n    - eapply candidateEntriesTerm_ext; eauto.\n      eapply doGenericServer_preserves_candidateEntriesTerm; eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      subst. simpl in *.\n      find_apply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, prevLog_candidateEntriesTerm.\n    simpl. intros.\n    find_apply_hyp_hyp.\n    eapply candidateEntriesTerm_ext with (sigma := (nwState net)).\n    - auto.\n    - eauto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_reboot :\n    refined_raft_net_invariant_reboot prevLog_candidateEntriesTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, prevLog_candidateEntriesTerm, reboot.\n    simpl. intros.\n    eapply candidateEntriesTerm_ext; eauto.\n    repeat find_rewrite.\n    find_apply_hyp_hyp.\n    unfold candidateEntriesTerm in *.\n    break_exists_exists.\n    update_destruct_simplify; auto.\n    repeat find_rewrite.\n    simpl in *. intuition.\n    discriminate.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      prevLog_candidateEntriesTerm net.\n  Proof using cci cti cei rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply prevLog_candidateEntriesTerm_init.\n    - apply prevLog_candidateEntriesTerm_client_request.\n    - apply prevLog_candidateEntriesTerm_timeout.\n    - apply prevLog_candidateEntriesTerm_append_entries.\n    - apply prevLog_candidateEntriesTerm_append_entries_reply.\n    - apply prevLog_candidateEntriesTerm_request_vote.\n    - apply prevLog_candidateEntriesTerm_request_vote_reply.\n    - apply prevLog_candidateEntriesTerm_do_leader.\n    - apply prevLog_candidateEntriesTerm_do_generic_server.\n    - apply prevLog_candidateEntriesTerm_state_same_packet_subset.\n    - apply prevLog_candidateEntriesTerm_reboot.\n  Qed.\n\n  Instance plceti : prevLog_candidateEntriesTerm_interface.\n  Proof.\n    constructor.\n    apply prevLog_candidateEntriesTerm_invariant.\n  Qed.\nEnd PrevLogCandidateEntriesTerm.\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/PrevLogCandidateEntriesTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771308191989, "lm_q1q2_score": 0.17827365725771907}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules rules_LoadU_derived.\nFrom cap_machine Require Import rules_binary rules_binary_LoadU_derived.\nFrom cap_machine Require Export iris_extra addr_reg_sample contiguous stack_macros_helpers.\nFrom cap_machine.binary_model.examples_binary Require Import macros_binary.\nFrom cap_machine Require Import macros.\n\nFrom cap_machine.binary_model Require Import logrel_binary fundamental_binary region_invariants_batch_uninitialized_binary.\n\nLtac iPrologue_s prog :=\n  let str_destr := constr:((\"(Hsi & \" ++ prog ++ \")\")%string) in\n  iDestruct prog as str_destr.\n\nLtac iEpilogue_s :=\n   iMod (do_step_pure _ [] with \"[$Hspec $Hj]\") as \"Hj\";auto;\n   iSimpl in \"Hj\".\n\nSection conf.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {stsg : STSG Addr region_type \u03a3} {heapg : heapG \u03a3}\n          {nainv: logrel_na_invs \u03a3} {cfg : cfgSG \u03a3}\n          `{MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_invariants_binary.region_type)).\n  Notation WORLD := (prodO STS_STD STS).\n  Implicit Types W : WORLD.\n\n  Definition conf_instrs z :=\n    prepstackU_instrs r_stk 1 1 ++\n    [loadU_r_z r_t0 r_stk (-1); (* since parameters are passer on the stack, no need to check that the input is below the stack bound *)\n    pushU_z_instr r_stk z] ++\n    rclear_instrs (list_difference all_registers [PC;r_t0]) ++\n    [jmp r_t0].\n\n\n  Definition conf1 a z1 :=\n    ([\u2217 list] a_i;w_i \u2208 a;(conf_instrs z1), a_i \u21a6\u2090 w_i)%I.\n  Definition conf2 a z2:=\n    ([\u2217 list] a_i;w_i \u2208 a;(conf_instrs z2), a_i \u21a3\u2090 w_i)%I.\n\n\n  Lemma conf_spec_12 z1 z2 (* stack values *)\n        W pc_p pc_g pc_b pc_e (* PC *)\n        conf_addrs (* program addresses: same for implementation and specification *)\n        a_first a_last (* special adresses *)\n        wstk wstk' (* stack *)\n        rmap rmap' (* registers *)\n        \u03b91 (* invariant names *) :\n\n    (* PC assumptions *)\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last ->\n\n    (* Program adresses assumptions *)\n    contiguous_between conf_addrs a_first a_last ->\n\n    (* footprint of the register map *)\n    dom (gset RegName) rmap = all_registers_s \u2216 {[PC;r_stk]} \u2192\n    dom (gset RegName) rmap' = all_registers_s \u2216 {[PC;r_stk]} \u2192\n\n    {{{ spec_ctx \u2217 \u2907 Seq (Instr Executable)\n      \u2217 r_stk \u21a6\u1d63 wstk\n      \u2217 r_stk \u21a3\u1d63 wstk'\n      \u2217 PC \u21a6\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 PC \u21a3\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap, r_i \u21a6\u1d63 w_i)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap', r_i \u21a3\u1d63 w_i)\n      (* stack *)\n      \u2217 interp W (wstk,wstk')\n      (* token which states all non atomic invariants are closed *)\n      \u2217 na_own logrel_nais \u22a4\n      (* trusted code *)\n      \u2217 na_inv logrel_nais \u03b91 (conf1 conf_addrs z1 \u2217 conf2 conf_addrs z2)\n      (* we start out with arbitrary sts *)\n      \u2217 sts_full_world W\n      \u2217 region W\n    }}}\n      Seq (Instr Executable)\n      {{{ v, RET v; \u231cv = HaltedV\u231d \u2192\n             \u2203 r W', \u2907 of_val HaltedV\n                   \u2217 full_map r\n                   \u2217 registers_mapsto r.1\n                   \u2217 spec_registers_mapsto r.2\n                   \u2217 \u231crelated_sts_priv_world W W'\u231d\n                   \u2217 na_own logrel_nais \u22a4\n                   \u2217 sts_full_world W'\n                   \u2217 region W' }}}.\n  Proof.\n    iIntros (Hvpc Hcont Hrdom Hsdom \u03c6) \"(#Hspec & Hj & Hr_stk & Hs_stk & HPC & HsPC & Hrmap\n    & Hsmap & #Hstk_valid & Hown & #Hconfprogs & Hsts & Hr) H\u03c6\".\n    iDestruct (interp_eq with \"Hstk_valid\") as %<-.\n    iMod (na_inv_acc with \"Hconfprogs Hown\") as \"([>Hprog >Hsprog] & Hown & Hcls)\";auto.\n    (* Get registers from implementation and specification side of the code *)\n    assert (is_Some (rmap !! r_t0)) as [w0 Hw0];[apply elem_of_gmap_dom;rewrite Hrdom;set_solver+|].\n    assert (is_Some (rmap !! r_t1)) as [w1 Hw1];[apply elem_of_gmap_dom;rewrite Hrdom;set_solver+|].\n    assert (is_Some (rmap !! r_t2)) as [w2 Hw2];[apply elem_of_gmap_dom;rewrite Hrdom;set_solver+|].\n    assert (is_Some (rmap' !! r_t0)) as [w0' Hsw0];[apply elem_of_gmap_dom;rewrite Hsdom;set_solver+|].\n    assert (is_Some (rmap' !! r_t1)) as [w1' Hsw1];[apply elem_of_gmap_dom;rewrite Hsdom;set_solver+|].\n    assert (is_Some (rmap' !! r_t2)) as [w2' Hsw2];[apply elem_of_gmap_dom;rewrite Hsdom;set_solver+|].\n    iDestruct (big_sepM_delete with \"Hrmap\") as \"[Hr_t0 Hrmap]\";[apply Hw0|].\n    iDestruct (big_sepM_delete _ _ r_t1 with \"Hrmap\") as \"[Hr_t1 Hrmap]\";[rewrite lookup_delete_ne//;eauto|].\n    iDestruct (big_sepM_delete _ _ r_t2 with \"Hrmap\") as \"[Hr_t2 Hrmap]\";[rewrite !lookup_delete_ne//;eauto|].\n    iDestruct (big_sepM_delete with \"Hsmap\") as \"[Hs_t0 Hsmap]\";[apply Hsw0|].\n    iDestruct (big_sepM_delete _ _ r_t1 with \"Hsmap\") as \"[Hs_t1 Hsmap]\";[rewrite lookup_delete_ne//;eauto|].\n    iDestruct (big_sepM_delete _ _ r_t2 with \"Hsmap\") as \"[Hs_t2 Hsmap]\";[rewrite !lookup_delete_ne//;eauto|].\n    (* prepstackU *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link.\n    iDestruct (big_sepL2_length with \"Hcode\") as %Hcode_length.\n    iDestruct (big_sepL2_app' with \"Hsprog\") as \"[Hscode Hsprog]\";auto.\n    iMod (prepstackU_s_spec with \"[$HsPC $Hscode $Hs_stk $Hspec $Hj Hs_t1 Hs_t2 ]\") as \"H\";[eauto..|].\n    { iSplitL \"Hs_t1\";eauto. }\n    iApply (prepstackU_spec with \"[- $HPC $Hcode $Hr_stk]\");[eauto..|].\n    iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|].\n    iNext. destruct (isPermWord wstk URWLX) eqn:Hperm;[|(* Failure *) iApply \"H\u03c6\";iIntros (Hcontr);inversion Hcontr].\n    (* cleanup of stack information *)\n    destruct wstk as [| [ [ [ [p_stk l_stk] b_stk] e_stk] a_stk] ];[inversion Hperm|]. iExists l_stk,b_stk, e_stk, a_stk.\n    destruct p_stk;inversion Hperm. iSplit;auto.\n    iDestruct \"H\" as (l b e a' Heq) \"H\". inversion Heq. subst l b e a'.\n    destruct (1%nat + 1%nat <? e_stk - b_stk)%Z eqn:Hsize;[|(* Failure *) iApply \"H\u03c6\";iIntros (Hcontr);inversion Hcontr].\n    destruct (b_stk + 1%nat <=? a_stk)%Z eqn:Hle;[|(* Failure *) iApply \"H\u03c6\";iIntros (Hcontr);inversion Hcontr].\n    iDestruct (writeLocalAllowedU_implies_local with \"Hstk_valid\") as %Hmonotone;auto. destruct l_stk;inversion Hmonotone.\n    iIntros \"Hstack\".\n    iDestruct \"Hstack\" as (a Ha) \"(HPC & Hprepstack & Hr_stk & Hr_t1 & Hr_t2)\".\n    iDestruct \"H\" as (a' Ha') \"(Hj & HsPC & Hsprepstack & Hs_stk & Hs_t1 & Hs_t2)\".\n    clear Heq. assert (a = a') as Heq;[clear -Ha Ha';solve_addr|subst a';clear Ha'].\n    revert Hsize Hle; rewrite Z.ltb_lt Z.leb_le =>Hsize Hle.\n\n    (* pop r_stk r_t0 *)\n    (* in order to pop, we must first open the region at b_stk *)\n    iDestruct (writeLocalAllowedU_valid_cap_below_implies _ _ _ _ _ _ b_stk with \"Hstk_valid\") as %Ha_param_W;[auto|..].\n    { clear -Hle Hsize Ha. rewrite andb_true_iff Z.leb_le Z.ltb_lt. solve_addr. }\n    { clear -Hle. solve_addr. }\n    iDestruct (read_allowedU_inv _ b_stk with \"Hstk_valid\") as  \"Hrel\";[clear -Hsize;solve_addr|auto|].\n    iDestruct (region_open_monotemp with \"[$Hr $Hsts $Hrel]\") as (wret wret') \"(Hr & Hsts & Hstate & Hb_stk & Hb_stk' & #Hmono & #Hwret_valid)\";auto.\n    iSimpl in \"Hwret_valid\".\n    iAssert (\u25b7 \u231cwret = wret'\u231d)%I as \"#><-\".\n    { iNext. iDestruct (interp_eq with \"Hwret_valid\") as %->. auto. }\n    (* loadU r_t0 r_stk -1 *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link0.\n    iDestruct (big_sepL2_length with \"Hcode\") as %Hcode_length0.\n    iDestruct (big_sepL2_app' with \"Hsprog\") as \"[Hscode Hsprog]\";auto.\n    destruct_addr_list l_code0.\n    iPrologue \"Hcode\". apply contiguous_between_cons_inv_first in Hcont_code0 as Heq. subst link.\n    iApply (rules_LoadU_derived.wp_loadU_success with \"[$HPC $Hi $Hr_t0 $Hr_stk $Hb_stk]\");\n      [apply decode_encode_instrW_inv|iCorrectPC l_code0 link0|auto..].\n    { clear -Hle Hsize Ha. rewrite andb_true_iff Z.leb_le Z.ltb_lt. solve_addr. }\n    { iContiguous_next_a Hcont_code0. }\n    iEpilogue \"(HPC & Hr_t0 & Hprog_done & Hr_stk & Hb_stk)\".\n    iPrologue_s \"Hscode\".\n    iMod (step_loadU_success _ [SeqCtx] with \"[$Hspec $Hj $HsPC $Hsi $Hs_t0 $Hs_stk $Hb_stk']\")\n      as \"(Hj & HsPC & Hs_t0 & Hsprog_done & Hs_stk & Hb_stk')\";\n      [apply decode_encode_instrW_inv|iCorrectPC l_code0 link0|auto..].\n    { clear -Hle Hsize Ha. rewrite andb_true_iff Z.leb_le Z.ltb_lt. solve_addr. }\n    { iContiguous_next_a Hcont_code0. }\n    iEpilogue_s.\n    (* we can close the world again *)\n    iDestruct (region_close_monotemp with \"[$Hstate $Hb_stk $Hb_stk' $Hr $Hrel $Hmono $Hwret_valid]\") as \"Hr\";auto.\n\n    (* pushu r_stk r_env *)\n    (* we have reached a part of the code which will require us to make a pub^b_stk change to the world *)\n    (* we will therefore first uninitialize all addresses at or above b_stk *)\n    iMod (uninitialize_region _ b_stk with \"[$Hsts $Hr]\") as (m Hmcond) \"[Hsts Hr]\".\n    (* next we can open the region at b_stk, which we will first assert is in m *)\n    iDestruct (valid_uninitialized_condition _ m with \"Hstk_valid\") as %Hstk_cond;auto.\n    (* next we can open the world at a *)\n    assert (b_stk <= a < e_stk)%a as Hstk_bounds.\n    { split;[clear -Ha;solve_addr|]. clear -Hsize Ha. solve_addr. }\n    pose proof (Hstk_cond a Hstk_bounds) as [ [v1 v2] Hw].\n    iDestruct (read_allowedU_inv _ a with \"Hstk_valid\") as \"Hrel'\";[clear -Hsize Ha;solve_addr|auto|].\n    iDestruct (region_open_uninitialized with \"[$Hrel' $Hr $Hsts]\") as \"(Hr & Hsts & Hstate & Ha & Ha')\";[eauto|..].\n    (* and we are ready to push a new value b_stk *)\n    assert (is_Some (a + 1))%a as [b_stk1 Hb_next].\n    { clear -Hstk_bounds. destruct (a + 1)%a eqn:Hsome;eauto. exfalso. solve_addr. }\n    iDestruct \"Hcode\" as \"[HpushU _]\".\n    iDestruct \"Hscode\" as \"[HspushU _]\".\n    assert ((a0 + 1)%a = Some link0) as Hlast.\n    { eapply contiguous_between_last;eauto. }\n    iApply (pushU_z_spec with \"[- $HPC $HpushU $Hr_stk $Ha]\");\n      [iCorrectPC l_code0 link0| |apply Hlast|apply Hb_next|..].\n    { apply andb_true_iff. split;[apply Z.leb_le|apply Z.ltb_lt];clear -Hstk_bounds;solve_addr. }\n    iNext. iIntros \"(HPC & HpushU & Hr_stk & Hb_stk)\".\n    iMod (push_pop_binary.pushU_z_spec with \"[$Hspec $Hj $HsPC $HspushU $Hs_stk $Ha']\")\n      as \"(Hj & HsPC & HspushU & Hs_stk & Hb_stk')\";\n      [iCorrectPC l_code0 link0| |apply Hlast|apply Hb_next|auto..].\n    { apply andb_true_iff. split;[apply Z.leb_le|apply Z.ltb_lt];clear -Hstk_bounds;solve_addr. }\n    (* we can now close the world again *)\n    pose proof (uninitialized_condition _ _ _ Hmcond) as Hmcond_alt.\n    iMod (uninitialize_open_region_change _ _ a with \"[$Hb_stk $Hb_stk' $Hrel' $Hsts $Hr $Hstate]\") as \"[Hr Hsts]\";\n      [clear;solve_addr|auto|].\n    { intros. apply Hmcond_alt. clear -H0 Ha. solve_addr. }\n\n    (* and we can now finish executing the instructions without more changes to W *)\n    (* rclear RegName/{PC;r_t0} *)\n    iPrologue_multi \"Hprog\" Hcont Hvpc link1.\n    iDestruct (big_sepL2_length with \"Hcode\") as %Hcode_length1.\n    iDestruct (big_sepL2_app' with \"Hsprog\") as \"[Hscode Hsprog]\";auto.\n\n    iDestruct (big_sepM_insert with \"[$Hrmap $Hr_t2]\") as \"Hrmap\";[apply lookup_delete|rewrite insert_delete -!delete_insert_ne//].\n    iDestruct (big_sepM_insert with \"[$Hrmap $Hr_t1]\") as \"Hrmap\";[apply lookup_delete|rewrite insert_delete].\n    iDestruct (big_sepM_insert with \"[$Hrmap $Hr_stk]\") as \"Hrmap\".\n    { rewrite lookup_insert_ne// lookup_delete_ne// !lookup_insert_ne//. apply not_elem_of_dom. rewrite Hrdom. set_solver-. }\n\n    iDestruct (big_sepM_insert with \"[$Hsmap $Hs_t2]\") as \"Hsmap\";[apply lookup_delete|rewrite insert_delete -!delete_insert_ne//].\n    iDestruct (big_sepM_insert with \"[$Hsmap $Hs_t1]\") as \"Hsmap\";[apply lookup_delete|rewrite insert_delete].\n    iDestruct (big_sepM_insert with \"[$Hsmap $Hs_stk]\") as \"Hsmap\".\n    { rewrite lookup_insert_ne// lookup_delete_ne// !lookup_insert_ne//. apply not_elem_of_dom. rewrite Hsdom. set_solver-. }\n\n    iApply (rclear_spec_gmap with \"[- $HPC $Hcode $Hrmap]\");[eauto..|].\n    { apply not_elem_of_list. constructor. }\n    { assert (length l_code1 = 31) as Hlength4.\n      clear -Hlength Hlength0 Hlength1. rewrite app_length Hlength1 in Hlength0. lia.\n      destruct l_code1;inversion Hlength4. apply contiguous_between_cons_inv_first in Hcont_code1 as ->.\n      auto. }\n    { clear -Hrdom. rewrite !dom_delete_L !dom_insert_L Hrdom list_to_set_difference -/all_registers_s /=. clear. set_solver. }\n    iNext. iIntros \"[HPC [Hdom Hrclear]]\".\n    iDestruct \"Hdom\" as (rmap1) \"[Hregs #Hregs_cond]\". iDestruct \"Hregs_cond\" as %[Hrdom1 Hzeroes].\n    iMod (rclear_s_spec_gmap with \"[$Hspec $Hj $HsPC $Hscode $Hsmap]\") as \"(Hj & HsPC & Hdom & Hsrclear)\";[eauto..|].\n    { apply not_elem_of_list. constructor. }\n    { assert (length l_code1 = 31) as Hlength4.\n      clear -Hlength Hlength0 Hlength1. rewrite app_length Hlength1 in Hlength0. lia.\n      destruct l_code1;inversion Hlength4. apply contiguous_between_cons_inv_first in Hcont_code1 as ->.\n      auto. }\n    { clear -Hsdom. rewrite !dom_insert_L !dom_delete_L !dom_insert_L Hsdom list_to_set_difference -/all_registers_s /=. clear. set_solver. }\n    iDestruct \"Hdom\" as (rmap2) \"[Hsregs #Hsegs_cond]\". iDestruct \"Hsegs_cond\" as %[Hrdom2 Hzeroes2].\n\n    (* jmp r_t0 *)\n    prep_addr_list_full l_rest1 Hcont.\n    iPrologue \"Hprog\".\n    iPrologue_s \"Hsprog\".\n    iMod (step_jmp_success _ [SeqCtx] with \"[$Hspec $Hj $HsPC $Hsi $Hs_t0]\")\n      as \"(Hj & HsPC & Hsi & Hs_t0)\";\n      [apply decode_encode_instrW_inv|iCorrectPC link1 a_last|auto..].\n    iApply (wp_jmp_success with \"[$HPC $Hi $Hr_t0]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link1 a_last|].\n\n    (* first we will update the varilidy of wret to the new world *)\n    set (W' := (<s[a:=Uninitialized (inl z1, inl z2)]s>(uninitialize W m))).\n    assert (related_sts_a_world W W' b_stk) as Hrelated.\n    { eapply related_sts_a_trans_world;[apply uninitialize_related_pub_a|];eauto.\n      apply related_sts_a_uninitialized. clear -Ha; solve_addr. apply Hstk_cond. auto. }\n    iDestruct (\"Hmono\" $! _ _ Hrelated with \"Hwret_valid\") as \"Hwret_valid'\". iSimpl in \"Hwret_valid'\".\n    iDestruct (jmp_or_fail_binary_spec with \"Hspec Hwret_valid'\") as \"Hcond\".\n    destruct (decide (isCorrectPC (updatePcPerm wret))).\n    2: { iEpilogue \"(HPC & _)\". iApply \"Hcond\". iFrame. iApply \"H\u03c6\". iIntros (Hcontr). inversion Hcontr. }\n    iDestruct \"Hcond\" as (p g b e a' Heq) \"Hcond\". rewrite Heq.\n    iSpecialize (\"Hcond\" $! (<[PC:=inl 0%Z]> (<[r_t0:=wret]> rmap1),<[PC:=inl 0%Z]> (<[r_t0:=wret]> rmap2)) W' with \"[]\").\n    { destruct g;iPureIntro.\n      apply related_sts_priv_refl_world. apply related_sts_priv_refl_world. apply related_sts_a_refl_world. }\n\n    (* we can now establish the continuation *)\n    iEpilogue \"(HPC & Hi & Hr_t0)\".\n    iEpilogue_s.\n\n    (* first we will close the program invariant *)\n    iMod (\"Hcls\" with \"[Hprepstack Hsprepstack Hprog_done Hsprog_done\n                        Hrclear Hsrclear Hi Hsi HpushU HspushU $Hown]\") as \"Hown\".\n    { iNext. iFrame. simpl. done. }\n\n    (* next we must establish that the current register state is valid *)\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t0]\") as \"Hregs\".\n    { apply not_elem_of_dom. rewrite Hrdom1. set_solver-. }\n    iDestruct (big_sepM_insert with \"[$Hregs $HPC]\") as \"Hregs\".\n    { rewrite lookup_insert_ne//. apply not_elem_of_dom. rewrite Hrdom1. set_solver-. }\n    iDestruct (big_sepM_insert with \"[$Hsregs $Hs_t0]\") as \"Hsregs\".\n    { apply not_elem_of_dom. rewrite Hrdom2. set_solver-. }\n    iDestruct (big_sepM_insert with \"[$Hsregs $HsPC]\") as \"Hsregs\".\n    { rewrite lookup_insert_ne//. apply not_elem_of_dom. rewrite Hrdom2. set_solver-. }\n    iDestruct (\"Hcond\" with \"[$Hown $Hr $Hsts $Hj Hregs Hsregs]\") as \"[_ Hconf]\".\n    {  rewrite -(insert_insert (<[_:=_]> rmap1) PC _ (inl 0%Z)) -(insert_insert (<[_:=_]> rmap2) PC _ (inl 0%Z)) Heq /=.\n       iFrame \"Hsregs Hregs\". iSplit;[iPureIntro|].\n       - simpl. intros x. split. all: apply elem_of_gmap_dom.\n         rewrite !dom_insert_L Hrdom1 list_to_set_difference.\n         2: rewrite !dom_insert_L Hrdom2 list_to_set_difference.\n         all: clear.\n         all: pose proof (all_registers_s_correct x). all: set_solver.\n       - iIntros (r HPC). rewrite /RegLocate. rewrite lookup_insert_ne// (lookup_insert_ne _ PC)//.\n         destruct (decide (r_t0 = r));[subst;rewrite !lookup_insert;eauto|rewrite !lookup_insert_ne;auto].\n         rewrite Hzeroes. rewrite Hzeroes2. rewrite !fixpoint_interp1_eq. done.\n         rewrite Hrdom2. 2: rewrite Hrdom1. all: clear -HPC n. all: pose proof (all_registers_s_correct r).\n         all: rewrite list_to_set_difference. all: set_solver. }\n    iApply (wp_wand with \"Hconf\").\n    iIntros (v). iIntros \"Hcond'\". iApply \"H\u03c6\".\n    iIntros (Hhalted). iDestruct (\"Hcond'\" $! Hhalted) as (r W'') \"(?&?&?&?&%&?&?&?)\".\n    iExists _,_;iFrame.\n    iPureIntro. eapply related_sts_a_priv_trans_world;eauto.\n  Qed.\n\n\n  (* --------------------------------------------------------------------------------------------------- *)\n  (* ------------------------------------ left to right refinement ------------------------------------- *)\n  (* --------------------------------------------------------------------------------------------------- *)\n\n  Definition confL a := conf1 a 2.\n  Definition confR a := conf2 a 3.\n\n  Lemma conf_spec_LR W pc_p pc_g pc_b pc_e (* PC *)\n        conf_addrs (* program addresses: same for implementation and specification *)\n        a_first a_last (* special adresses *)\n        wstk wstk' (* stack *)\n        rmap rmap' (* registers *)\n        \u03b91 (* invariant names *) :\n\n    (* PC assumptions *)\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last ->\n\n    (* Program adresses assumptions *)\n    contiguous_between conf_addrs a_first a_last ->\n\n    (* footprint of the register map *)\n    dom (gset RegName) rmap = all_registers_s \u2216 {[PC;r_stk]} \u2192\n    dom (gset RegName) rmap' = all_registers_s \u2216 {[PC;r_stk]} \u2192\n\n    {{{ spec_ctx \u2217 \u2907 Seq (Instr Executable)\n      \u2217 r_stk \u21a6\u1d63 wstk\n      \u2217 r_stk \u21a3\u1d63 wstk'\n      \u2217 PC \u21a6\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 PC \u21a3\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap, r_i \u21a6\u1d63 w_i)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap', r_i \u21a3\u1d63 w_i)\n      (* stack *)\n      \u2217 interp W (wstk,wstk')\n      (* token which states all non atomic invariants are closed *)\n      \u2217 na_own logrel_nais \u22a4\n      (* trusted code *)\n      \u2217 na_inv logrel_nais \u03b91 (confL conf_addrs \u2217 confR conf_addrs)\n      (* we start out with arbitrary sts *)\n      \u2217 sts_full_world W\n      \u2217 region W\n    }}}\n      Seq (Instr Executable)\n      {{{ v, RET v; \u231cv = HaltedV\u231d \u2192\n             \u2203 r W', \u2907 of_val HaltedV\n                   \u2217 full_map r\n                   \u2217 registers_mapsto r.1\n                   \u2217 spec_registers_mapsto r.2\n                   \u2217 \u231crelated_sts_priv_world W W'\u231d\n                   \u2217 na_own logrel_nais \u22a4\n                   \u2217 sts_full_world W'\n                   \u2217 region W' }}}.\n  Proof.\n    iIntros (Hvpc Hcont Hrdom Hsdom \u03c6) \"(#Hspec & Hj & Hr_stk & Hs_stk & HPC & HsPC & Hrmap\n    & Hsmap & #Hstk_valid & Hown & #Hconfprogs & Hsts & Hr) H\u03c6\".\n    iDestruct (conf_spec_12 with \"[$Hspec $Hj $Hr_stk $Hs_stk $HPC $HsPC $Hrmap $Hsmap\n    $Hstk_valid $Hown $Hconfprogs $Hsts $Hr] H\u03c6\") as \"$\";eauto.\n  Qed.\n\n  (* --------------------------------------------------------------------------------------------------- *)\n  (* ------------------------------------ right to left refinement ------------------------------------- *)\n  (* --------------------------------------------------------------------------------------------------- *)\n\n  Definition confL' a := conf2 a 2.\n  Definition confR' a := conf1 a 3.\n\n  Lemma conf_spec_RL W pc_p pc_g pc_b pc_e (* PC *)\n        conf_addrs (* program addresses: same for implementation and specification *)\n        a_first a_last (* special adresses *)\n        wstk wstk' (* stack *)\n        rmap rmap' (* registers *)\n        \u03b91 (* invariant names *) :\n\n    (* PC assumptions *)\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last ->\n\n    (* Program adresses assumptions *)\n    contiguous_between conf_addrs a_first a_last ->\n\n    (* footprint of the register map *)\n    dom (gset RegName) rmap = all_registers_s \u2216 {[PC;r_stk]} \u2192\n    dom (gset RegName) rmap' = all_registers_s \u2216 {[PC;r_stk]} \u2192\n\n    {{{ spec_ctx \u2217 \u2907 Seq (Instr Executable)\n      \u2217 r_stk \u21a6\u1d63 wstk\n      \u2217 r_stk \u21a3\u1d63 wstk'\n      \u2217 PC \u21a6\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 PC \u21a3\u1d63 inr ((pc_p,pc_g),pc_b,pc_e,a_first)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap, r_i \u21a6\u1d63 w_i)\n      \u2217 ([\u2217 map] r_i\u21a6w_i \u2208 rmap', r_i \u21a3\u1d63 w_i)\n      (* stack *)\n      \u2217 interp W (wstk,wstk')\n      (* token which states all non atomic invariants are closed *)\n      \u2217 na_own logrel_nais \u22a4\n      (* trusted code *)\n      \u2217 na_inv logrel_nais \u03b91 (confR' conf_addrs \u2217 confL' conf_addrs)\n      (* we start out with arbitrary sts *)\n      \u2217 sts_full_world W\n      \u2217 region W\n    }}}\n      Seq (Instr Executable)\n      {{{ v, RET v; \u231cv = HaltedV\u231d \u2192\n             \u2203 r W', \u2907 of_val HaltedV\n                   \u2217 full_map r\n                   \u2217 registers_mapsto r.1\n                   \u2217 spec_registers_mapsto r.2\n                   \u2217 \u231crelated_sts_priv_world W W'\u231d\n                   \u2217 na_own logrel_nais \u22a4\n                   \u2217 sts_full_world W'\n                   \u2217 region W' }}}.\n  Proof.\n    iIntros (Hvpc Hcont Hrdom Hsdom \u03c6) \"(#Hspec & Hj & Hr_stk & Hs_stk & HPC & HsPC & Hrmap\n    & Hsmap & #Hstk_valid & Hown & #Hconfprogs & Hsts & Hr) H\u03c6\".\n    iDestruct (conf_spec_12 with \"[$Hspec $Hj $Hr_stk $Hs_stk $HPC $HsPC $Hrmap $Hsmap\n    $Hstk_valid $Hown $Hconfprogs $Hsts $Hr] H\u03c6\") as \"$\";eauto.\n  Qed.\n\nEnd conf.\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/confidentiality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17827365725771904}}
{"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(** The Mach intermediate language: operational semantics. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import Mach.\nRequire Stacklayout.\n\nSection WITHMEM.\nContext `{Hmem: Mem.MemoryModel}.\n\n(** The semantics for Mach is close to that of [Linear]: they differ only\n  on the interpretation of stack slot accesses.  In Mach, these\n  accesses are interpreted as memory accesses relative to the\n  stack pointer.  More precisely:\n- [Mgetstack ofs ty r] is a memory load at offset [ofs * 4] relative\n  to the stack pointer.\n- [Msetstack r ofs ty] is a memory store at offset [ofs * 4] relative\n  to the stack pointer.\n- [Mgetparam ofs ty r] is a memory load at offset [ofs * 4]\n  relative to the pointer found at offset 0 from the stack pointer.\n  The semantics maintain a linked structure of activation records,\n  with the current record containing a pointer to the record of the\n  caller function at offset 0.\n\nIn addition to this linking of activation records, the\nsemantics also make provisions for storing a back link at offset\n[f.(fn_link_ofs)] from the stack pointer, and a return address at\noffset [f.(fn_retaddr_ofs)].  The latter stack location will be used\nby the Asm code generated by [Asmgen] to save the return address into\nthe caller at the beginning of a function, then restore it and jump to\nit at the end of a function.  The Mach concrete semantics does not\nattach any particular meaning to the pointer stored in this reserved\nlocation, but makes sure that it is preserved during execution of a\nfunction.  The [return_address_offset] predicate from module\n[Asmgenretaddr] is used to guess the value of the return address that\nthe Asm code generated later will store in the reserved location.\n*)\n\nDefinition load_stack (m: mem) (sp: val) (ty: typ) (ofs: int) :=\n  Mem.loadv (chunk_of_type ty) m (Val.add sp (Vint ofs)).\n\nDefinition store_stack (m: mem) (sp: val) (ty: typ) (ofs: int) (v: val) :=\n  Mem.storev (chunk_of_type ty) m (Val.add sp (Vint ofs)) v.\n\n(** Extract the values of the arguments to an external call. *)\n\nInductive extcall_arg: regset -> mem -> val -> loc -> val -> Prop :=\n  | extcall_arg_reg: forall rs m sp r,\n      extcall_arg rs m sp (R r) (rs r)\n  | extcall_arg_stack: forall rs m sp ofs ty v,\n      load_stack m sp ty (Int.repr (Stacklayout.fe_ofs_arg + 4 * ofs)) = Some v ->\n      extcall_arg rs m sp (S (Outgoing ofs ty)) v.\n\nDefinition extcall_arguments\n    (rs: regset) (m: mem) (sp: val) (sg: signature) (args: list val) : Prop :=\n  list_forall2 (extcall_arg rs m sp) (loc_arguments sg) args.\n\n(** Extract the values of the arguments to an annotation. *)\n\nInductive annot_arg: regset -> mem -> val -> annot_param -> val -> Prop :=\n  | annot_arg_reg: forall rs m sp r,\n      annot_arg rs m sp (APreg r) (rs r)\n  | annot_arg_stack: forall rs m stk base chunk ofs v,\n      Mem.load chunk m stk (Int.unsigned base + ofs) = Some v ->\n      annot_arg rs m (Vptr stk base) (APstack chunk ofs) v.\n\nDefinition annot_arguments\n   (rs: regset) (m: mem) (sp: val) (params: list annot_param) (args: list val) : Prop :=\n  list_forall2 (annot_arg rs m sp) params args.\n\n(** Mach execution states. *)\n\nInductive stackframe: Type :=\n  | Stackframe:\n      forall (f: function)    (**r calling function *)\n             (sp: val)        (**r stack pointer in calling function *)\n             (c: code),       (**r program point in calling function *)\n      stackframe.\n\nInductive state `{mem_ops: Mem.MemoryOps mem}: Type :=\n  | State:\n      forall (stack: list stackframe)  (**r call stack *)\n             (f: function)             (**r 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 (stack: list stackframe)  (**r call stack *)\n             (fd: fundef)              (**r function to call *)\n             (rs: regset)              (**r register state *)\n             (m: mem),                 (**r memory state *)\n      state\n  | Returnstate:\n      forall (stack: list stackframe)  (**r call stack *)\n             (rs: regset)              (**r register state *)\n             (m: mem),                 (**r memory state *)\n      state.\n\nDefinition parent_sp (s: list stackframe) : val :=\n  match s with\n  | nil => Vptr Mem.nullptr Int.zero\n  | Stackframe f sp c :: s' => sp\n  end.\n\nSection RELSEM.\n\nVariable ge: genv.\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 f sp ofs ty dst c rs m v,\n      load_stack m sp Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      load_stack m (parent_sp s) ty ofs = Some v ->\n      step (State s f sp (Mgetparam ofs ty dst :: c) rs m)\n        E0 (State s f 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 f sp sig ros c rs m fd,\n      find_function ge ros rs = Some fd ->\n      step (State s f sp (Mcall sig ros :: c) rs m)\n        E0 (Callstate (Stackframe f sp c :: s)\n                       fd rs m)\n  | exec_Mtailcall:\n      forall s f stk soff sig ros c rs m fd m' m'',\n      find_function ge ros rs = Some fd ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      Mem.free m stk 0 (Int.unsigned f.(fn_retaddr_ofs)) = Some m' ->\n      Mem.free m' stk (Int.unsigned f.(fn_retaddr_ofs) + 4) f.(fn_stacksize) = Some m'' ->\n      step (State s f (Vptr stk soff) (Mtailcall sig ros :: c) rs m)\n        E0 (Callstate s fd 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      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      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 f sp lbl c rs m c',\n      find_label lbl f.(fn_code) = Some c' ->\n      step (State s f sp (Mgoto lbl :: c) rs m)\n        E0 (State s f sp c' rs m)\n  | exec_Mcond_true:\n      forall s f sp cond args lbl c rs m c',\n      eval_condition cond rs##args m = Some true ->\n      find_label lbl f.(fn_code) = Some c' ->\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_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 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      find_label lbl f.(fn_code) = Some c' ->\n      step (State s f sp (Mjumptable arg tbl :: c) rs m)\n        E0 (State s f sp c' (undef_temps rs) m)\n  | exec_Mreturn:\n      forall s f stk soff c rs m m' m'',\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      Mem.free m stk 0 (Int.unsigned f.(fn_retaddr_ofs)) = Some m' ->\n      Mem.free m' stk (Int.unsigned f.(fn_retaddr_ofs) + 4) f.(fn_stacksize) = Some m'' ->\n      step (State s f (Vptr stk soff) (Mreturn :: c) rs m)\n        E0 (Returnstate s rs m'')\n  | exec_function_internal:\n      forall s f rs m m1 m2 m3 stk,\n      Mem.alloc m 0 f.(fn_stacksize) = (m1, stk) ->\n      Mem.free m1 stk (Int.unsigned f.(fn_retaddr_ofs)) (Int.unsigned f.(fn_retaddr_ofs) + 4) = Some m2 ->\n      let sp := Vptr stk Int.zero in\n      store_stack m2 sp Tint f.(fn_link_ofs) (parent_sp s) = Some m3 ->\n      (4 | Int.unsigned f.(fn_retaddr_ofs)) ->\n      step (Callstate s (Internal f) rs m)\n        E0 (State s f sp f.(fn_code) (undef_temps rs) m3)\n  | exec_function_external:\n      forall s ef rs m t rs' args res m',\n      external_call ef ge args m t res m' ->\n      extcall_arguments rs m (parent_sp s) (ef_sig ef) args ->\n      rs' = (rs#(loc_result (ef_sig ef)) <- res) ->\n      step (Callstate s (External ef) rs m)\n         t (Returnstate s rs' m')\n  | exec_return:\n      forall s f sp c rs m,\n      step (Returnstate (Stackframe f sp c :: s) rs m)\n        E0 (State s f sp c rs m).\n\nEnd RELSEM.\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b fd m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some b ->\n      Genv.find_funct_ptr ge b = Some fd ->\n      initial_state p (Callstate nil fd (Regmap.init Vundef) m0).\n\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall rs m r,\n      rs (loc_result (mksignature nil (Some Tint))) = Vint r ->\n      final_state (Returnstate nil rs m) r.\n\nDefinition semantics (p: program) :=\n  Semantics step (initial_state p) final_state (Genv.globalenv p).\n\nEnd WITHMEM.\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/Machsem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17827365725771904}}
{"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(** The Mach intermediate language: abstract syntax.\n\n  Mach is the last intermediate language before generation of assembly\n  code.  \n*)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Stacklayout.\n\n(** * Abstract syntax *)\n\n(** Like Linear, the Mach language is organized as lists of instructions\n  operating over machine registers, with default fall-through behaviour\n  and explicit labels and branch instructions.  \n\n  The main difference with Linear lies in the instructions used to\n  access the activation record.  Mach has three such instructions:\n  [Mgetstack] and [Msetstack] to read and write within the activation\n  record for the current function, at a given word offset and with a\n  given type; and [Mgetparam], to read within the activation record of\n  the caller. \n\n  These instructions implement a more concrete view of the activation\n  record than the the [Lgetstack] and [Lsetstack] instructions of\n  Linear: actual offsets are used instead of abstract stack slots, and the\n  distinction between the caller's frame and the callee's frame is\n  made explicit. *)\n\nDefinition label := positive.\n\nInductive instruction: Type :=\n  | Mgetstack: int -> typ -> mreg -> instruction\n  | Msetstack: mreg -> int -> typ -> instruction\n  | Mgetparam: int -> typ -> mreg -> instruction\n  | Mop: operation -> list mreg -> mreg -> instruction\n  | Mload: memory_chunk -> addressing -> list mreg -> mreg -> instruction\n  | Mstore: memory_chunk -> addressing -> list mreg -> mreg -> instruction\n  | Mcall: signature -> mreg + ident -> instruction\n  | Mtailcall: signature -> mreg + ident -> instruction\n  | Mbuiltin: builtin -> list mreg -> list mreg -> instruction\n  | Mannot: builtin -> list annot_param -> instruction\n  | Mlabel: label -> instruction\n  | Mgoto: label -> instruction\n  | Mcond: condition -> list mreg -> label -> instruction\n  | Mjumptable: mreg -> list label -> instruction\n  | Mreturn: instruction\n\nwith annot_param: Type :=\n  | APreg: mreg -> annot_param\n  | APstack: memory_chunk -> Z -> annot_param.\n\nDefinition code := list instruction.\n\nRecord function: Type := mkfunction\n  { fn_sig: signature;\n    fn_code: code;\n    fn_stacksize: Z;\n    fn_link_ofs: int;\n    fn_retaddr_ofs: int }.\n\nDefinition fundef := AST.fundef function.\n\nDefinition program := AST.program fundef unit.\n\nDefinition funsig (fd: fundef) :=\n  match fd with\n  | Internal f => fn_sig f\n  | External ef => ef_sig ef\n  end.\n\nDefinition genv := Genv.t fundef unit.\n\n(** * Operational semantics *)\n\n(** The semantics for Mach is close to that of [Linear]: they differ only\n  on the interpretation of stack slot accesses.  In Mach, these\n  accesses are interpreted as memory accesses relative to the\n  stack pointer.  More precisely:\n- [Mgetstack ofs ty r] is a memory load at offset [ofs * 4] relative\n  to the stack pointer.\n- [Msetstack r ofs ty] is a memory store at offset [ofs * 4] relative\n  to the stack pointer.\n- [Mgetparam ofs ty r] is a memory load at offset [ofs * 4]\n  relative to the pointer found at offset 0 from the stack pointer.\n  The semantics maintain a linked structure of activation records,\n  with the current record containing a pointer to the record of the\n  caller function at offset 0.\n\nIn addition to this linking of activation records, the\nsemantics also make provisions for storing a back link at offset\n[f.(fn_link_ofs)] from the stack pointer, and a return address at\noffset [f.(fn_retaddr_ofs)].  The latter stack location will be used\nby the Asm code generated by [Asmgen] to save the return address into\nthe caller at the beginning of a function, then restore it and jump to\nit at the end of a function.  The Mach concrete semantics does not\nattach any particular meaning to the pointer stored in this reserved\nlocation, but makes sure that it is preserved during execution of a\nfunction.  The [return_address_offset] parameter is used to guess the\nvalue of the return address that the Asm code generated later will\nstore in the reserved location.\n*)\n\nDefinition load_stack (m: mem) (sp: val) (ty: typ) (ofs: int) :=\n  Mem.loadv (chunk_of_type ty) m (Val.add sp (Vint ofs)).\n\nDefinition store_stack (m: mem) (sp: val) (ty: typ) (ofs: int) (v: val) :=\n  Mem.storev (chunk_of_type ty) m (Val.add sp (Vint ofs)) v.\n\nModule RegEq.\n  Definition t := mreg.\n  Definition eq := mreg_eq.\nEnd RegEq.\n\nModule Regmap := EMap(RegEq).\n\nDefinition regset := Regmap.t val.\n\nNotation \"a ## b\" := (List.map a b) (at level 1).\nNotation \"a # b <- c\" := (Regmap.set b c a) (at level 1, b at next level).\n\nFixpoint undef_regs (rl: list mreg) (rs: regset) {struct rl} : regset :=\n  match rl with\n  | nil => rs\n  | r1 :: rl' => Regmap.set r1 Vundef (undef_regs rl' rs)\n  end.\n\nLemma undef_regs_other:\n  forall r rl rs, ~In r rl -> undef_regs rl rs r = rs r.\nProof.\n  induction rl; simpl; intros. auto. rewrite Regmap.gso. apply IHrl. intuition. intuition.\nQed.\n\nLemma undef_regs_same:\n  forall r rl rs, In r rl -> undef_regs rl rs r = Vundef.\nProof.\n  induction rl; simpl; intros. tauto.\n  destruct H. subst a. apply Regmap.gss.\n  unfold Regmap.set. destruct (RegEq.eq r a); auto. \nQed.\n\nFixpoint set_regs (rl: list mreg) (vl: list val) (rs: regset) : regset :=\n  match rl, vl with\n  | r1 :: rl', v1 :: vl' => set_regs rl' vl' (Regmap.set r1 v1 rs)\n  | _, _ => rs\n  end.\n\nDefinition is_label (lbl: label) (instr: instruction) : bool :=\n  match instr with\n  | Mlabel lbl' => if peq lbl lbl' then true else false\n  | _ => false\n  end.\n\nLemma is_label_correct:\n  forall lbl instr,\n  if is_label lbl instr then instr = Mlabel lbl else instr <> Mlabel lbl.\nProof.\n  intros.  destruct instr; simpl; try discriminate.\n  case (peq lbl l); intro; congruence.\nQed.\n\nFixpoint find_label (lbl: label) (c: code) {struct c} : option code :=\n  match c with\n  | nil => None\n  | i1 :: il => if is_label lbl i1 then Some il else find_label lbl il\n  end.\n\nLemma find_label_incl:\n  forall lbl c c', find_label lbl c = Some c' -> incl c' c.\nProof.\n  induction c; simpl; intros. discriminate.\n  destruct (is_label lbl a). inv H. auto with coqlib. eauto with coqlib. \nQed.\n\nSection RELSEM.\n\nVariable return_address_offset: function -> code -> int -> Prop.\n\nVariable ge: genv.\n\nDefinition find_function_ptr\n        (ge: genv) (ros: mreg + ident) (rs: regset) : option block :=\n  match ros with\n  | inl r =>\n      match rs r with\n      | Vptr b ofs => if Int.eq ofs Int.zero then Some b else None\n      | _ => None\n      end\n  | inr symb =>\n      Genv.find_symbol ge symb\n  end.\n\n(** Extract the values of the arguments to an external call. *)\n\nInductive extcall_arg: regset -> mem -> val -> loc -> val -> Prop :=\n  | extcall_arg_reg: forall rs m sp r,\n      extcall_arg rs m sp (R r) (rs r)\n  | extcall_arg_stack: forall rs m sp ofs ty v,\n      load_stack m sp ty (Int.repr (Stacklayout.fe_ofs_arg + 4 * ofs)) = Some v ->\n      extcall_arg rs m sp (S Outgoing ofs ty) v.\n\nDefinition extcall_arguments\n    (rs: regset) (m: mem) (sp: val) (sg: signature) (args: list val) : Prop :=\n  Forall2 (extcall_arg rs m sp) (loc_arguments sg) args.\n\n(** Extract the values of the arguments to an annotation. *)\n\nInductive annot_arg: regset -> mem -> val -> annot_param -> val -> Prop :=\n  | annot_arg_reg: forall rs m sp r,\n      annot_arg rs m sp (APreg r) (rs r)\n  | annot_arg_stack: forall rs m stk base chunk ofs v,\n      Mem.load chunk m stk (Int.unsigned base + ofs) = Some v ->\n      annot_arg rs m (Vptr stk base) (APstack chunk ofs) v.\n\nDefinition annot_arguments\n   (rs: regset) (m: mem) (sp: val) (params: list annot_param) (args: list val) : Prop :=\n  Forall2 (annot_arg rs m sp) params args.\n\n(** Mach execution states. *)\n\n(** Mach execution states. *)\n\nInductive stackframe: Type :=\n  | Stackframe:\n      forall (f: block)       (**r pointer to calling function *)\n             (sp: val)        (**r stack pointer in calling function *)\n             (retaddr: val)   (**r Asm return address in calling function *)\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      state\n  | Callstate:\n      forall (stack: list stackframe)  (**r call stack *)\n             (f: block)                (**r pointer to function to call *)\n             (rs: regset),             (**r register state *)\n      state\n  | Returnstate:\n      forall (stack: list stackframe)  (**r call stack *)\n             (rs: regset),             (**r register state *)\n      state.\n\nDefinition parent_sp (s: list stackframe) : val :=\n  match s with\n  | nil => Vzero\n  | Stackframe f sp ra c :: s' => sp\n  end.\n\nDefinition parent_ra (s: list stackframe) : val :=\n  match s with\n  | nil => Vzero\n  | Stackframe f sp ra c :: s' => ra\n  end.\n\nInductive step: state * mem -> trace -> state * mem -> 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' rs',\n      store_stack m sp ty ofs (rs src) = Some m' ->\n      rs' = undef_regs (destroyed_by_setstack ty) rs ->\n      step (State s f sp (Msetstack src ofs ty :: c) rs, m)\n        E0 (State s f sp c rs', m')\n  | exec_Mgetparam:\n      forall s fb f sp ofs ty dst c rs m v rs',\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m sp Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      load_stack m (parent_sp s) ty ofs = Some v ->\n      rs' = (rs # temp_for_parent_frame <- Vundef # dst <- v) ->\n      step (State s fb sp (Mgetparam ofs ty dst :: c) rs, m)\n        E0 (State s fb sp c rs', m)\n  | exec_Mop:\n      forall s f sp op args res c rs m v rs',\n      eval_operation ge sp op rs##args m = Some v ->\n      rs' = ((undef_regs (destroyed_by_op op) rs)#res <- v) ->\n      step (State s f sp (Mop op args res :: c) rs, m)\n        E0 (State s f sp c rs', m)\n  | exec_Mload:\n      forall s f sp chunk addr args dst c rs m a v rs',\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.loadv chunk m a = Some v ->\n      rs' = ((undef_regs (destroyed_by_load chunk addr) rs)#dst <- v) ->\n      step (State s f sp (Mload chunk addr args dst :: c) rs, m)\n        E0 (State s f sp c rs', m)\n  | exec_Mstore:\n      forall s f sp chunk addr args src c rs m m' a rs',\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.storev chunk m a (rs src) = Some m' ->\n      rs' = undef_regs (destroyed_by_store chunk addr) rs ->\n      step (State s f sp (Mstore chunk addr args src :: c) rs, m)\n        E0 (State s f sp c rs', m')\n  | exec_Mcall:\n      forall s fb sp sig ros c rs m f f' ra,\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      return_address_offset f c ra ->\n      step (State s fb sp (Mcall sig ros :: c) rs, m)\n        E0 (Callstate (Stackframe fb sp (Vptr fb ra) c :: s)\n                       f' rs, m)\n  | exec_Mtailcall:\n      forall s fb stk soff sig ros c rs m f f' m',\n      find_function_ptr ge ros rs = Some f' ->\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_retaddr_ofs) = Some (parent_ra s) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      step (State s fb (Vptr stk soff) (Mtailcall sig ros :: c) rs, m)\n        E0 (Callstate s f' rs, m')\n  | exec_Mbuiltin:\n      forall s f sp rs m ef args res b t vl rs' m',\n      builtin_call' ef ge rs##args m t vl m' ->\n      rs' = set_regs res vl (undef_regs (destroyed_by_builtin ef) rs) ->\n      step (State s f sp (Mbuiltin ef args res :: b) rs, m)\n         t (State s f sp b rs', 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      builtin_call' ef ge vargs m t v m' ->\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' rs',\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      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      step (State s fb sp (Mcond cond args lbl :: c) rs, m)\n        E0 (State s fb sp c' rs', m)\n  | exec_Mcond_false:\n      forall s f sp cond args lbl c rs m rs',\n      eval_condition cond rs##args m = Some false ->\n      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      step (State s f sp (Mcond cond args lbl :: c) rs, m)\n        E0 (State s f sp c rs', m)\n  | exec_Mjumptable:\n      forall s fb f sp arg tbl c rs m n lbl c' rs',\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      rs' = undef_regs destroyed_by_jumptable rs ->\n      step (State s fb sp (Mjumptable arg tbl :: c) rs, m)\n        E0 (State s fb sp c' rs', m)\n  | exec_Mreturn:\n      forall s fb stk soff c rs m f m',\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_link_ofs) = Some (parent_sp s) ->\n      load_stack m (Vptr stk soff) Tint f.(fn_retaddr_ofs) = Some (parent_ra s) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      step (State s fb (Vptr stk soff) (Mreturn :: c) rs, m)\n        E0 (Returnstate s rs, m')\n  | exec_function_internal:\n      forall s fb rs m f m1 m2 m3 stk rs',\n      Genv.find_funct_ptr ge fb = Some (Internal f) ->\n      Mem.alloc m 0 f.(fn_stacksize) = (m1, stk) ->\n      let sp := Vptr stk Int.zero in\n      store_stack m1 sp Tint f.(fn_link_ofs) (parent_sp s) = Some m2 ->\n      store_stack m2 sp Tint f.(fn_retaddr_ofs) (parent_ra s) = Some m3 ->\n      rs' = undef_regs destroyed_at_function_entry rs ->\n      step (Callstate s fb rs, m)\n        E0 (State s fb sp f.(fn_code) rs', m3)\n  | exec_function_external:\n      forall s fb rs m t rs' ef args res m',\n      Genv.find_funct_ptr ge fb = Some (External ef) ->\n      extcall_arguments rs m (parent_sp s) (ef_sig ef) args ->\n      external_call' ef ge args m t res m' ->\n      rs' = set_regs (loc_result (ef_sig ef)) res rs ->\n      step (Callstate s fb rs, m)\n         t (Returnstate s rs', m')\n  | exec_return:\n      forall s f sp ra c rs m,\n      step (Returnstate (Stackframe f sp ra c :: s) rs, m)\n        E0 (State s f sp c rs, m).\n\nEnd RELSEM.\n\nInductive initial_state (p: program): state * mem -> Prop :=\n  | initial_state_intro: forall fb m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some fb ->\n      initial_state p (Callstate nil fb (Regmap.init Vundef), m0).\n\nInductive final_state: state * mem -> int -> Prop :=\n  | final_state_intro: forall rs m r retcode,\n      loc_result signature_main = r :: nil ->\n      rs r = Vint retcode ->\n      final_state (Returnstate nil rs, m) retcode.\n\nLemma store_stack_forward:\n  forall m1 sp ty x v m2,\n  store_stack m1 sp ty x v = Some m2 -> Mem.forward m1 m2.\nProof.\n  unfold store_stack. eauto using Mem.storev_forward.\nQed.\nLemma semantics_forward:\n  forall rao ge s1 m1 t s2 m2,\n  step rao ge (s1,m1) t (s2,m2) -> Mem.forward m1 m2.\nProof.\n  intros; inv H; eauto 10 using Mem.forward_refl, Mem.storev_forward,\n    Mem.free_forward, Mem.alloc_forward, external_call_forward',\n    Mem.forward_trans, Mem.alloc_forward, builtin_call_forward'.\nQed.\n\nDefinition semantics (rao: function -> code -> int -> Prop) (p: program) :=\n  Semantics (step rao) (initial_state p) final_state (Genv.globalenv p) (semantics_forward rao).\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Mach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33807713081919877, "lm_q1q2_score": 0.17827365725771901}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import LemmaNat Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import opcode_synthesis verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\nFrom bpf.verifier.simulation Require Import correct_is_well_src correct_is_not_div_by_zero correct_is_shift_range.\n\n\n(**\nCheck bpf_verifier_opcode_alu64_reg.\nbpf_verifier_opcode_alu64_reg\n     : nat -> int64 -> M bool\n\n*)\nOpen Scope Z_scope.\n\nDefinition opcode_alu64_reg_if (op: nat) : opcode_alu64_reg :=\n  if Nat.eqb op 15%nat then ADD64_REG\n  else if Nat.eqb op 31%nat then SUB64_REG\n  else if Nat.eqb op 47%nat then MUL64_REG\n  else if Nat.eqb op 63%nat then DIV64_REG\n  else if Nat.eqb op 79%nat then OR64_REG\n  else if Nat.eqb op 95%nat then AND64_REG\n  else if Nat.eqb op 111%nat then LSH64_REG\n  else if Nat.eqb op 127%nat then RSH64_REG\n  else if Nat.eqb op 159%nat then MOD64_REG\n  else if Nat.eqb op 175%nat then XOR64_REG\n  else if Nat.eqb op 191%nat then MOV64_REG\n  else if Nat.eqb op 207%nat then ARSH64_REG\n  else ALU64_REG_ILLEGAL.\n\nLemma opcode_alu64_reg_eqb_eq : forall a b,\n    opcode_alu64_reg_eqb a b = true -> a = b.\nProof.\n  destruct a,b ; simpl ;congruence.\nQed.\n\nLemma lift_opcode_alu64_reg :\n  forall (E: nat -> opcode_alu64_reg)\n         (F: nat -> opcode_alu64_reg) n,\n    ((fun n => opcode_alu64_reg_eqb (E n) (F n) = true) n) <->\n      (((fun n => opcode_alu64_reg_eqb (E n) (F n)) n) = true).\nProof.\n  intros.\n  simpl. reflexivity.\nQed.\n\nLemma byte_to_opcode_alu64_reg_if_same:\n  forall (op: nat),\n    (op <= 255)%nat ->\n    nat_to_opcode_alu64_reg op = opcode_alu64_reg_if op.\nProof.\n  intros.\n  unfold nat_to_opcode_alu64_reg, opcode_alu64_reg_if.\n  apply opcode_alu64_reg_eqb_eq.\n  match goal with\n  | |- ?A = true => set (P := A)\n  end.\n  pattern op in P.\n  match goal with\n  | P := ?F op |- _=>\n      apply (Forall_exec_spec F 255)\n  end.\n  vm_compute.\n  reflexivity.\n  assumption.\nQed.\n\nLemma bpf_verifier_opcode_alu64_reg_match:\n  forall op\n    (Hop: (op <= 255)%nat)\n    (Halu : nat_to_opcode_alu64_reg op = ALU64_REG_ILLEGAL),\n      15  <> (Z.of_nat op) /\\\n      31  <> (Z.of_nat op) /\\\n      47  <> (Z.of_nat op) /\\\n      63  <> (Z.of_nat op) /\\\n      79  <> (Z.of_nat op) /\\\n      95  <> (Z.of_nat op) /\\\n      111 <> (Z.of_nat op) /\\\n      127 <> (Z.of_nat op) /\\\n      159 <> (Z.of_nat op) /\\\n      175 <> (Z.of_nat op) /\\\n      191 <> (Z.of_nat op) /\\\n      207 <> (Z.of_nat op).\nProof.\n  intros.\n  rewrite byte_to_opcode_alu64_reg_if_same in Halu; auto.\n  unfold opcode_alu64_reg_if in Halu.\n  change 15  with (Z.of_nat 15%nat).\n  change 31  with (Z.of_nat 31%nat).\n  change 47  with (Z.of_nat 47%nat).\n  change 63  with (Z.of_nat 63%nat).\n  change 79  with (Z.of_nat 79%nat).\n  change 95  with (Z.of_nat 95%nat).\n  change 111 with (Z.of_nat 111%nat).\n  change 127 with (Z.of_nat 127%nat).\n  change 159 with (Z.of_nat 159%nat).\n  change 175 with (Z.of_nat 175%nat).\n  change 191 with (Z.of_nat 191%nat).\n  change 207 with (Z.of_nat 207%nat).\n\n  repeat match goal with\n  | H : (if ?X then _ else _) = _ |- _ /\\ _ =>\n    split; [destruct X eqn: Hnew; [inversion H |\n      rewrite Nat.eqb_neq in Hnew;\n      intro Hfalse; apply Hnew;\n      symmetry in Hfalse;\n      apply Nat2Z.inj in Hfalse;\n      assumption]\n    | destruct X eqn: Hnew; [inversion H| clear Hnew]]\n  | H : (if ?X then _ else _) = _ |- _ =>\n    destruct X eqn: Hnew; [inversion H |\n      rewrite Nat.eqb_neq in Hnew;\n      intro Hfalse; apply Hnew;\n      symmetry in Hfalse;\n      apply Nat2Z.inj in Hfalse;\n      assumption]\n  end.\nQed.\n\nSection Bpf_verifier_opcode_alu64_reg.\n  Context {S:special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(nat:Type); (int64:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := bpf_verifier_opcode_alu64_reg.\n\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_bpf_verifier_opcode_alu64_reg.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (opcode_correct x))\n     (dcons (fun x => StateLess _ (int64_correct x))\n      (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x => StateLess _ (bool_correct x).\n\n  Instance correct_function_bpf_verifier_opcode_alu64_reg : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f, bpf_verifier_opcode_alu64_reg.\n    simpl. (*\n    unfold nat_to_opcode_alu64_reg. *)\n    (** goal: correct_body _ _\n              match x with\n              | op_BPF_ADD32 => bindM (upd_reg ... *)\n    unfold INV.\n    destruct nat_to_opcode_alu64_reg eqn: Halu. (**r case discussion on each alu64_instruction *)\n    - (**r ADD64_REG *)\n      eapply correct_statement_switch with (n:= 15).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 15%nat). {\n          clear - Halu.\n          do 15 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 192 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 15) with 15 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r SUB64_REG *)\n      eapply correct_statement_switch with (n:= 31).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros Hst H; simpl in H.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 31%nat). {\n          clear - Halu.\n          do 31 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 176 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 31) with 31 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r MUL64_REG *)\n      eapply correct_statement_switch with (n:= 47).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 47%nat). {\n          clear - Halu.\n          do 47 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 160 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 47) with 47 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r DIV64_REG *)\n      eapply correct_statement_switch with (n:= 63).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 63%nat). {\n          clear - Halu.\n          do 63 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 144 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 63) with 63 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r OR64_REG *)\n      eapply correct_statement_switch with (n:= 79).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 79%nat). {\n          clear - Halu.\n          do 79 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 128 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 79) with 79 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r AND64_REG *)\n      eapply correct_statement_switch with (n:= 95).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 95%nat). {\n          clear - Halu.\n          do 95 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 112 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 95) with 95 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r LSH64_REG *)\n      eapply correct_statement_switch with (n:= 111).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 111%nat). {\n          clear - Halu.\n          do 111 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 96 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 111) with 111 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r RSH64_REG *)\n      eapply correct_statement_switch with (n:= 127).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 127%nat). {\n          clear - Halu.\n          do 127 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 80 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 127) with 127 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r MOD64_REG *)\n      eapply correct_statement_switch with (n:= 159).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 159%nat). {\n          clear - Halu.\n          do 159 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 48 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 159) with 159 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r XOR64_REG *)\n      eapply correct_statement_switch with (n:= 175).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 175%nat). {\n          clear - Halu.\n          do 175 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 32 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 175) with 175 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r MOV64_REG *)\n      eapply correct_statement_switch with (n:= 191).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 191%nat). {\n          clear - Halu.\n          do 191 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          do 16 (destruct c; [inversion Halu|]).\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 191) with 191 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r ARSH64_REG *)\n      eapply correct_statement_switch with (n:= 207).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_alu64_reg in Halu.\n        assert (Hc_eq: c = 207%nat). {\n          clear - Halu.\n          do 207 (destruct c; [inversion Halu|]).\n          destruct c; [reflexivity|].\n          inversion Halu.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 207) with 207 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r ALU64_REG_ILLEGAL *)\n      eapply correct_statement_switch_ex.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold eval_inv, opcode_correct in c1.\n        destruct c1 as (c1 & Hc1_range).\n        exists (Z.of_nat c).\n        split.\n        unfold exec_expr.\n        rewrite p0.\n        rewrite c1.\n        reflexivity.\n        split.\n\n        change Int.modulus with 4294967296.\n        lia.\n\n        unfold select_switch.\n        unfold select_switch_case.\n        apply bpf_verifier_opcode_alu64_reg_match in Halu; auto.\n        destruct Halu as (Hfirst & Halu). eapply Coqlib.zeq_false in Hfirst. rewrite Hfirst; clear Hfirst.\n        repeat match goal with\n        | H: ?X <> ?Y /\\ _ |- context[Coqlib.zeq ?X ?Y] =>\n            destruct H as (Hfirst & H);\n            eapply Coqlib.zeq_false in Hfirst; rewrite Hfirst; clear Hfirst\n        end.\n        eapply Coqlib.zeq_false in Halu; rewrite Halu; clear Halu.\n        (* default *)\n        simpl.\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        exists (Vint (Int.repr 0)).\n        unfold exec_expr.\n        split; [reflexivity|].\n        unfold eval_inv, match_res, bool_correct, Int.one.\n        split; [reflexivity|].\n        split; [reflexivity|].\n        intros.\n        constructor.\n        reflexivity.\nQed.\n\nEnd Bpf_verifier_opcode_alu64_reg.\n\nClose Scope Z_scope.\n\nExisting Instance correct_function_bpf_verifier_opcode_alu64_reg.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_bpf_verifier_opcode_alu64_reg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3007455914759599, "lm_q1q2_score": 0.17824187147876042}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils lib.fmap_utils.\nRequire Import common.types.\nRequire Import concrete.concrete.\nRequire Import symbolic.symbolic.\nRequire Import cfi.symbolic.\nRequire Import cfi.property.\nRequire Import cfi.rules.\nRequire Import cfi.classes.\nRequire Import symbolic.rules.\nRequire Import symbolic.refinement_common.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Conc.\nSection ConcreteSection.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {ids : cfi_id mt}\n        {e : rules.fencodable mt cfi_tags}.\n\nVariable cfg : id -> id -> bool.\n\nDefinition valid_jmp := classes.valid_jmp cfg.\n\n(*allow attacker to change only things tagged USER DATA! all the rest should be equiv*)\n\n\nDefinition no_violation (cst : Concrete.state mt) :=\n  let '(Concrete.State mem _  _ pc@tpc _) := cst in\n  (forall i cti ti src,\n    getm mem pc = Some i@cti ->\n    @fdecode _ _ e Symbolic.M cti = Some (User ti) ->\n    @fdecode _ _ e Symbolic.P tpc = Some (INSTR (Some src)) ->\n    exists dst,\n        ti = INSTR (Some dst) /\\ cfg src dst) /\\\n  (forall i cti ti src,\n     getm mem pc = Some i@cti ->\n     @fdecode _ _ e Symbolic.M cti = Some (Entry ti) ->\n     @fdecode _ _ e Symbolic.P tpc = Some (INSTR (Some src)) ->\n     exists dst,\n       ti = INSTR (Some dst) /\\ cfg src dst).\n\nDefinition cast k : Symbolic.tag_type cfi_tags k -> cfi_tag :=\n  match k return Symbolic.tag_type cfi_tags k -> cfi_tag with\n  | Symbolic.M => fun t => t\n  | _ => fun t => t\n  end.\n\nDefinition cast' k (t : cfi_tag) : Symbolic.tag_type cfi_tags k :=\n  match k with\n  | Symbolic.M => t\n  | _ => t\n  end.\n\n(*Defined in terms of atom_equiv for symbolic tags*)\n(* TODO: as a sanity check, please prove reflexivity for this and\n   the other attacker relations. That will ensure that the attacker\n   can at least keep things the same. *)\nInductive atom_equiv k (a : atom (mword mt) (mword mt)) (a' : atom (mword mt) (mword mt)) : Prop :=\n  | user_equiv : forall v v' ct ut ct' ut',\n                   a = v@ct ->\n                   @fdecode _ _ e k ct = Some (wtag_of_tag ut) ->\n                   a' = v'@ct' ->\n                   @fdecode _ _ e k ct' = Some (wtag_of_tag ut') ->\n                   Sym.atom_equiv v@(cast ut) v'@(cast ut') ->\n                   atom_equiv k a a'\n  | any_equiv : (~ exists ut, @fdecode _ _ e k (taga a) = Some (wtag_of_tag ut)) ->\n                a = a' ->\n                atom_equiv k a a'.\n\nDefinition equiv (mem mem' : Concrete.memory mt) :=\n  pointwise (atom_equiv Symbolic.M) mem mem'.\n\nDefinition reg_equiv (regs : Concrete.registers mt) (regs' : Concrete.registers mt) :=\n  forall r, exists x x',\n    getm regs r = Some x /\\\n    getm regs' r = Some x' /\\\n    atom_equiv Symbolic.R x x'.\n\nInductive step_a : Concrete.state mt ->\n                   Concrete.state mt -> Prop :=\n| step_attack : forall mem reg cache pc tpc epc mem' reg'\n                  (INUSER: @fdecode _ _ e Symbolic.P tpc)\n                  (REQUIV: reg_equiv reg reg')\n                  (MEQUIV: equiv mem mem'),\n                  step_a (Concrete.State mem reg cache pc@tpc epc)\n                         (Concrete.State mem' reg' cache pc@tpc epc).\n\nLocal Notation \"x .+1\" := (x + 1)%w.\nLocal Open Scope word_scope.\n\nDefinition csucc (st : Concrete.state mt) (st' : Concrete.state mt) : bool :=\n  let pc_s := vala (Concrete.pc st) in\n  let pc_s' := vala (Concrete.pc st') in\n  if in_monitor st || in_monitor st' then true else\n  match (getm (Concrete.mem st) pc_s) with\n    | Some i =>\n      match (@fdecode _ _ e Symbolic.M (taga i)) with\n        | Some (User (INSTR (Some src))) =>\n          match decode_instr (vala i) with\n            | Some (Jump r)\n            | Some (Jal r) =>\n              match (getm (Concrete.mem st) pc_s') with\n                | Some i' =>\n                  match (@fdecode _ _ e Symbolic.M (taga i')) with\n                    | Some (User (INSTR (Some dst))) =>\n                      cfg src dst\n                    | Some (Entry (INSTR (Some dst))) =>\n                      is_nop (vala i') && cfg src dst\n                    | _ => false\n                  end\n                | _ => false\n              end\n            | Some (Bnz r imm) =>\n              (pc_s' == pc_s .+1) || (pc_s' == pc_s + swcast imm)\n            | None => false\n            | _ => pc_s' == pc_s .+1\n          end\n        | Some (User (INSTR None)) =>\n          match decode_instr (vala i) with\n            | Some (Jump r)\n            | Some (Jal r) =>\n              false\n            | Some (Bnz r imm) =>\n              (pc_s' == pc_s .+1) || (pc_s' == pc_s + swcast imm)\n            | None => false\n            | _ => pc_s' == pc_s .+1\n          end\n       (* this says that if cst,cst' is in user mode then it's\n          not sensible to point to monitor memory*)\n        | Some (User DATA)\n        | Some (Entry _)\n        | None => false\n      end\n    | None => false\n  end.\n\nInstance sp : Symbolic.params := Sym.sym_cfi cfg.\n\nVariable mi : refinement_common.monitor_invariant.\n\nVariable stable : Symbolic.syscall_table mt.\n\n(* This is basically the initial_refine assumption on preservation *)\nDefinition cinitial (cs : Concrete.state mt) :=\n  exists ss, Sym.initial stable ss /\\ refine_state mi stable ss cs.\n\nVariable masks : Concrete.Masks.\n\nDefinition all_attacker (xs : seq (Concrete.state mt)) : Prop :=\n  forall x1 x2, In2 x1 x2 xs -> step_a x1 x2 /\\ ~ Concrete.step _ masks x1 x2.\n\nLemma all_attacker_red ast ast' axs :\n  all_attacker (ast :: ast' :: axs) ->\n  all_attacker (ast' :: axs).\nProof.\n  intros ATTACKER asi asj IN2.\n  assert (IN2' : In2 asi asj (ast :: ast' :: axs))\n    by (simpl; auto).\n  apply ATTACKER in IN2'.\n  assumption.\nQed.\n\nDefinition stopping (ss : seq (Concrete.state mt)) : Prop :=\n  (all_attacker ss /\\ all in_user ss)\n  \\/\n  (exists user monitor,\n    ss = user ++ monitor /\\\n    all_attacker user /\\ all in_user user /\\\n    all in_monitor monitor).\n\nProgram Instance concrete_cfi_machine : cfi_machine := {\n  state := [eqType of Concrete.state mt];\n  initial s := cinitial s;\n\n  step s1 s2 := Concrete.step ops masks s1 s2;\n  step_a := step_a;\n\n  succ := csucc;\n  stopping := stopping\n}.\n\nEnd ConcreteSection.\n\nEnd Conc.\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/concrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.17824186776430587}}
{"text": "Require Import GhostSimulations.\nRequire Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import RaftMsgRefinementInterface.\n\nRequire Import CommonTheorems.\n\nRequire Import SpecLemmas.\n\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import RefinedLogMatchingLemmasInterface.\nRequire Import GhostLogCorrectInterface.\nRequire Import GhostLogsLogPropertiesInterface.\nRequire Import TermSanityInterface.\nRequire Import AllEntriesLeaderSublogInterface.\nRequire Import GhostLogAllEntriesInterface.\n\nRequire Import GhostLogLogMatchingInterface.\n\n\nSection GhostLogLogMatching.\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 {rmri : raft_msg_refinement_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {glci : ghost_log_correct_interface}.\n  Context {lphogli : log_properties_hold_on_ghost_logs_interface}.\n  Context {tsi : term_sanity_interface}.\n  Context {aelsi : allEntries_leader_sublog_interface}.\n  Context {glaei : ghost_log_allEntries_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  Definition ghost_log_entries_match_nw (net : network) : Prop :=\n    forall p p',\n      In p (nwPackets net) ->\n      In p' (nwPackets net) ->\n      entries_match (fst (pBody p)) (fst (pBody p')).\n\n  Definition ghost_log_entries_match (net : network) : Prop :=\n    ghost_log_entries_match_host net /\\\n    ghost_log_entries_match_nw net.\n\n  Definition lifted_entries_contiguous net :=\n    forall h,\n      contiguous_range_exact_lo (log (snd (nwState net h))) 0.\n\n  Definition lifted_entries_sorted net :=\n    forall h,\n      sorted (log (snd (nwState net h))).\n  \n  Lemma lifted_entries_contiguous_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_contiguous net.\n  Proof using rlmli rmri. \n    intros.\n    enough (entries_contiguous (mgv_deghost net)) by\n        (unfold entries_contiguous, lifted_entries_contiguous, mgv_deghost in *;\n         simpl in *;\n         repeat break_match; simpl in *; auto).\n    apply msg_lift_prop; eauto using entries_contiguous_invariant.\n  Qed.\n\n  Lemma lifted_entries_sorted_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_sorted net.\n  Proof using rlmli rmri. \n    intros.\n    enough (entries_sorted (mgv_deghost net)) by\n        (unfold entries_sorted, lifted_entries_sorted, mgv_deghost in *;\n         simpl in *;\n         repeat break_match; simpl in *; auto).\n    apply msg_lift_prop; eauto using entries_sorted_invariant.\n  Qed.\n\n  Definition lifted_entries_contiguous_nw net :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      contiguous_range_exact_lo es pli.\n\n  Lemma lifted_entries_contiguous_nw_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_contiguous_nw net.\n  Proof using rlmli rmri. \n    intros.\n    assert (entries_contiguous_nw (mgv_deghost net)) by\n        (apply msg_lift_prop; eauto using entries_contiguous_nw_invariant).\n    unfold entries_contiguous_nw, lifted_entries_contiguous_nw, mgv_deghost in *;\n      intros.\n    simpl in *;\n      repeat break_match; simpl in *; auto.\n    match goal with\n      | H : context [contiguous_range_exact_lo] |- _ =>\n        specialize (H (@mgv_deghost_packet _ _ _ ghost_log_params p));\n          eapply H; simpl in *; eauto\n    end.\n    apply in_map_iff. eexists; eauto.\n  Qed.\n\n  Definition lifted_entries_match net :=\n    forall h h',\n      entries_match (log (snd (nwState net h))) (log (snd (nwState net h'))).\n\n  Lemma lifted_entries_match_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_match net.\n  Proof using rlmli rmri. \n    intros.\n    unfold lifted_entries_match; intros.\n    find_eapply_lem_hyp msg_lift_prop;\n      [|intros; eapply (entries_match_invariant ltac:(eauto) h h'); eauto].\n    simpl in *.\n    repeat break_match; simpl in *; auto.\n  Qed.\n  \n  Definition lifted_no_entries_past_current_term_host net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma lifted_no_entries_past_current_term_host_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_no_entries_past_current_term_host net.\n  Proof using tsi rmri. \n    intros.\n    enough (no_entries_past_current_term_host (deghost (mgv_deghost net))) by\n        (unfold no_entries_past_current_term_host, lifted_no_entries_past_current_term_host, deghost, mgv_deghost in *;\n         simpl in *;\n         repeat break_match; simpl in *; auto).\n    apply msg_lift_prop_all_the_way; eauto.\n    intros.\n    eapply no_entries_past_current_term_invariant; eauto.\n  Qed.\n  \n  Lemma ghost_log_sorted :\n    forall net p,\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      sorted (fst (pBody p)).\n  Proof using lphogli rlmli rmri. \n    assert (msg_log_property sorted) by\n        (unfold msg_log_property; intros; eapply lifted_entries_sorted_invariant; eauto).\n    intros.\n    find_eapply_lem_hyp log_properties_hold_on_ghost_logs_invariant; eauto.\n  Qed.\n\n  Lemma ghost_log_contiguous :\n    forall net p,\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      contiguous_range_exact_lo (fst (pBody p)) 0.\n  Proof using lphogli rlmli rmri. \n    assert (msg_log_property (fun x => contiguous_range_exact_lo x 0)) by\n        (unfold msg_log_property; intros; eapply lifted_entries_contiguous_invariant; eauto).\n    intros.\n    find_eapply_lem_hyp log_properties_hold_on_ghost_logs_invariant;\n      eauto; simpl in *; auto.\n  Qed.\n\n  Definition lifted_allEntries_leader_sublog (net : network) :=\n    forall leader e h,\n      type (snd (nwState net leader)) = Leader ->\n      In e (map snd (allEntries (fst (nwState net h)))) ->\n      eTerm e = currentTerm (snd (nwState net leader)) ->\n      In e (log (snd (nwState net leader))).\n\n  Lemma lifted_allEntries_leader_sublog_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_allEntries_leader_sublog net.\n  Proof using aelsi rmri. \n    intros.\n    unfold lifted_allEntries_leader_sublog; intros.\n    find_eapply_lem_hyp msg_lift_prop;\n      [|intros; eapply allEntries_leader_sublog_invariant; eauto].\n    simpl in *.\n    unfold allEntries_leader_sublog in *.\n    unfold mgv_deghost in *.\n    simpl in *.\n    repeat break_match; simpl in *; eauto.\n  Qed.\n  \n  Lemma ghost_log_entries_match_init :\n    msg_refined_raft_net_invariant_init ghost_log_entries_match.\n  Proof using. \n    red. split;\n      red; intros; simpl in *; intuition.\n  Qed.\n\n  Lemma handleAppendEntries_ghost_log:\n    forall (p : packet) (net : network) (d : raft_data) \n      (m : msg) (t : term) (n : name) (pli : logIndex) \n      (plt : term) (es : list entry) (ci : logIndex) \n      (h : Net.name),\n      msg_refined_raft_intermediate_reachable net ->\n      entries_match (log (snd (nwState net h))) (fst (pBody p)) ->\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      In p (nwPackets net) -> log d = log (snd (nwState net h)) \\/ log d = fst (pBody p).\n  Proof using lphogli glci rlmli rmri. \n    intros.\n    find_copy_eapply_lem_hyp ghost_log_correct_invariant; eauto;\n    repeat conclude_using eauto.\n    find_apply_lem_hyp handleAppendEntries_log.\n    intuition; subst; auto.\n    - repeat find_rewrite.\n      rewrite sorted_findGtIndex_0; auto;\n      [|eapply ghost_log_sorted; eauto].\n      intros.\n      eapply ghost_log_contiguous; eauto.\n    - right.\n      repeat find_rewrite.\n      break_exists. intuition.\n      subst.\n      replace (eIndex x0) with (eIndex x).\n      eapply thing; eauto; repeat find_rewrite; auto using findGtIndex_Prefix;\n      try solve [eapply ghost_log_sorted; eauto];\n      try solve [eapply ghost_log_contiguous; eauto];\n      try solve [eapply lifted_entries_sorted_invariant; eauto];\n      try solve [eapply lifted_entries_contiguous_nw_invariant; eauto].\n  Qed.\n\n  Hint Resolve entries_match_refl.\n  Hint Resolve entries_match_sym.\n    \n  Lemma ghost_log_entries_match_append_entries :\n    msg_refined_raft_net_invariant_append_entries' ghost_log_entries_match.\n  Proof using lphogli glci rlmli rmri. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + match goal with\n        | [ H : msg_refined_raft_intermediate_reachable (mkNetwork _ _) |- _ ] => clear H\n        end.\n        find_apply_hyp_hyp. intuition.\n        * find_eapply_lem_hyp handleAppendEntries_ghost_log; eauto.\n          intuition; repeat find_rewrite; eauto.\n        * subst. simpl in *.\n          find_eapply_lem_hyp handleAppendEntries_ghost_log; eauto.\n      + find_apply_hyp_hyp. intuition; eauto.\n        subst. simpl in *. unfold write_ghost_log.\n        simpl.\n        replace d with (snd (nwState {| nwPackets := ps'; nwState := st' |} (pDst p))) by\n            (simpl; find_higher_order_rewrite; rewrite_update; reflexivity).\n        replace (nwState net h) with (nwState {| nwPackets := ps'; nwState := st' |} h)by\n            (simpl; find_higher_order_rewrite; rewrite_update; reflexivity).\n        apply lifted_entries_match_invariant; auto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto.\n      + subst. simpl in *.\n        unfold write_ghost_log.\n        simpl.\n        match goal with\n        | [ H : context [handleAppendEntries] |- _ ] =>\n          eapply handleAppendEntries_ghost_log in H; eauto\n        end.\n        intuition.\n        * find_rewrite. eauto.\n        * find_rewrite. eauto.\n      + subst. simpl in *.\n        unfold write_ghost_log.\n        simpl.\n        match goal with\n        | [ H : context [handleAppendEntries] |- _ ] =>\n          eapply handleAppendEntries_ghost_log in H; eauto\n        end.\n        intuition.\n        * find_rewrite. eauto.\n        * find_rewrite. eauto.\n      + subst. simpl in *. apply entries_match_refl.\n  Qed.\n\n  Ltac packet_simpl :=\n    first [do_in_map; subst; simpl in *;\n           unfold add_ghost_msg in *;\n           do_in_map; subst; simpl in *|subst; simpl in *].\n\n  Arguments write_ghost_log / _ _ _ _ _.\n  \n  Lemma ghost_log_entries_match_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply ghost_log_entries_match.\n  Proof using rlmli rmri. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + find_apply_hyp_hyp. intuition.\n        * erewrite handleAppendEntriesReply_log; eauto.\n        * packet_simpl. apply entries_match_refl.\n      + find_apply_hyp_hyp. intuition.\n        * eauto.\n        * packet_simpl.\n          erewrite handleAppendEntriesReply_log with (st'0 := d) by eauto.\n          eapply lifted_entries_match_invariant; eauto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto.\n      + subst. simpl in *.\n        do_in_map. subst. simpl in *.\n        unfold add_ghost_msg in *. do_in_map. subst. simpl in *.\n        erewrite handleAppendEntriesReply_same_log by eauto.\n        eauto.\n      + subst. simpl in *.\n        do_in_map. subst. simpl in *.\n        unfold add_ghost_msg in *. do_in_map. subst. simpl in *.\n        erewrite handleAppendEntriesReply_same_log by eauto.\n        eauto.\n      + subst. simpl in *.\n        repeat do_in_map. subst. simpl in *.\n        unfold add_ghost_msg in *. repeat do_in_map. subst. simpl in *.\n        auto.\n  Qed.\n\n  Lemma ghost_log_entries_match_request_vote :\n    msg_refined_raft_net_invariant_request_vote' ghost_log_entries_match.\n  Proof using rlmli rmri. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + find_apply_hyp_hyp. intuition.\n        * erewrite handleRequestVote_log; eauto.\n        * packet_simpl. auto.\n      + find_apply_hyp_hyp. intuition.\n        * eauto.\n        * packet_simpl.\n          erewrite handleRequestVote_log with (st'0 := d) by eauto.\n          eapply lifted_entries_match_invariant; eauto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto.\n      + subst. simpl in *. erewrite handleRequestVote_log; eauto.\n      + subst. simpl in *. erewrite handleRequestVote_log; eauto.\n      + subst. simpl in *. erewrite handleRequestVote_log; eauto.\n  Qed.\n\n  Lemma ghost_log_entries_match_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply ghost_log_entries_match.\n  Proof using. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      erewrite handleRequestVoteReply_log; eauto.\n    - repeat find_apply_hyp_hyp; intuition; eauto;\n      repeat packet_simpl; eauto.\n  Qed.\n\n  Lemma sorted_entries_match_cons :\n    forall l l' e,\n      sorted (e :: l) ->\n      entries_match l l' ->\n      (~ exists e', eIndex e' = eIndex e /\\ eTerm e' = eTerm e /\\ In e'  l') ->\n      entries_match (e :: l) l'.\n  Proof using. \n    intros. simpl in *.\n    intuition.\n    unfold entries_match in *.\n    split; simpl in *; intuition; subst_max; auto;\n    try solve [find_false; eauto].\n    - find_apply_hyp_hyp. omega.\n    - eapply H0; eauto.\n    - right. eapply H0; eauto.\n  Qed.\n\n  Lemma ghost_log_entries_match_client_request :\n    msg_refined_raft_net_invariant_client_request ghost_log_entries_match.\n  Proof using glaei aelsi tsi rlmli rmri. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - find_copy_apply_lem_hyp handleClientRequest_packets.\n      subst. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      find_apply_lem_hyp handleClientRequest_log.\n      intuition; subst; simpl in *; repeat find_rewrite; eauto.\n      break_exists_name e.\n      intuition; repeat find_rewrite; simpl in *. subst.\n      eapply sorted_entries_match_cons; eauto.\n      + simpl. intuition; try solve [eapply lifted_entries_sorted_invariant; eauto].\n        * find_eapply_lem_hyp maxIndex_is_max; eauto; try omega.\n          eapply lifted_entries_sorted_invariant; eauto.\n        * repeat find_rewrite.\n          find_eapply_lem_hyp lifted_no_entries_past_current_term_host_invariant; eauto.\n      + intuition.\n        break_exists. intuition.\n        repeat find_rewrite.\n        enough (exists x, In x (log (snd (nwState net h0))) /\\ eIndex x = eIndex e /\\ eTerm x = eTerm e).\n        * break_exists. intuition. repeat find_rewrite.\n          find_eapply_lem_hyp maxIndex_is_max; eauto;\n          unfold raft_data in *; simpl in *;\n          unfold raft_data in *; simpl in *;\n          [omega|]. eapply lifted_entries_sorted_invariant; eauto.\n        * find_eapply_lem_hyp ghost_log_allEntries_invariant; eauto.\n          break_exists.\n          repeat find_rewrite.\n          find_copy_eapply_lem_hyp lifted_allEntries_leader_sublog_invariant; eauto.\n          apply in_map_iff. eexists; intuition; eauto; auto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      find_copy_apply_lem_hyp handleClientRequest_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma ghost_log_entries_match_timeout :\n    msg_refined_raft_net_invariant_timeout ghost_log_entries_match.\n  Proof using rlmli rmri. \n    red.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + find_apply_hyp_hyp. intuition.\n        * erewrite handleTimeout_log_same; eauto.\n        * packet_simpl. eauto.\n      + find_apply_hyp_hyp. intuition.\n        packet_simpl.\n        erewrite handleTimeout_log_same with (d' := d) by eauto.\n        eapply lifted_entries_match_invariant; eauto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite handleTimeout_log_same; eauto.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite handleTimeout_log_same; eauto.\n      + repeat do_in_map. subst. unfold add_ghost_msg in *. repeat do_in_map.\n        subst. simpl in *. auto.\n  Qed.\n\n  Lemma ghost_log_entries_match_do_leader :\n    msg_refined_raft_net_invariant_do_leader ghost_log_entries_match.\n  Proof using rlmli rmri. \n    red. 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    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + find_apply_hyp_hyp. intuition.\n        * erewrite doLeader_log; eauto.\n        * packet_simpl. eauto.\n      + find_apply_hyp_hyp. intuition.\n        packet_simpl.\n        erewrite doLeader_log with (st'0 := d') by eauto.\n        eapply lifted_entries_match_invariant; eauto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite doLeader_log; eauto.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite doLeader_log; eauto.\n      + repeat do_in_map. subst. unfold add_ghost_msg in *. repeat do_in_map.\n        subst. simpl in *. auto.\n  Qed.\n\n  Lemma ghost_log_entries_match_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server ghost_log_entries_match.\n  Proof using rlmli rmri. \n    red. 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    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto.\n      + find_apply_hyp_hyp. intuition.\n        * erewrite doGenericServer_log; eauto.\n        * packet_simpl. eauto.\n      + find_apply_hyp_hyp. intuition.\n        packet_simpl.\n        erewrite doGenericServer_log with (st'0 := d') by eauto.\n        eapply lifted_entries_match_invariant; eauto.\n    - find_apply_hyp_hyp.\n      find_apply_hyp_hyp.\n      intuition.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite doGenericServer_log; eauto.\n      + do_in_map. subst. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        erewrite doGenericServer_log; eauto.\n      + repeat do_in_map. subst. unfold add_ghost_msg in *. repeat do_in_map.\n        subst. simpl in *. auto.\n  Qed.\n\n  Lemma ghost_log_entries_match_reboot :\n    msg_refined_raft_net_invariant_reboot ghost_log_entries_match.\n  Proof using. \n    red. 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    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n      repeat find_reverse_rewrite; eauto.\n    - repeat find_reverse_rewrite; eauto.\n  Qed.\n\n  Lemma ghost_log_entries_match_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset ghost_log_entries_match.\n  Proof using. \n    red. intros.\n    split; red; intros; simpl in *; intuition;\n    unfold ghost_log_entries_match in *; break_and.\n    - find_apply_hyp_hyp. repeat find_reverse_higher_order_rewrite. eauto.\n    - repeat find_apply_hyp_hyp. eauto.\n  Qed.\n\n  Lemma ghost_log_entries_match_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      ghost_log_entries_match net.\n  Proof using glaei aelsi tsi lphogli glci rlmli rmri. \n    intros.\n    apply msg_refined_raft_net_invariant'; auto.\n    - apply ghost_log_entries_match_init.\n    - apply msg_refined_raft_net_invariant_client_request'_weak.\n      apply ghost_log_entries_match_client_request.\n    - apply msg_refined_raft_net_invariant_timeout'_weak.\n      apply ghost_log_entries_match_timeout.\n    - apply ghost_log_entries_match_append_entries.\n    - apply msg_refined_raft_net_invariant_append_entries_reply'_weak.\n      apply ghost_log_entries_match_append_entries_reply.\n    - apply ghost_log_entries_match_request_vote.\n    - apply msg_refined_raft_net_invariant_request_vote_reply'_weak.\n      apply ghost_log_entries_match_request_vote_reply.\n    - apply msg_refined_raft_net_invariant_do_leader'_weak.\n      apply ghost_log_entries_match_do_leader.\n    - apply msg_refined_raft_net_invariant_do_generic_server'_weak.\n      apply ghost_log_entries_match_do_generic_server.\n    - apply msg_refined_raft_net_invariant_subset'_weak.\n      apply ghost_log_entries_match_state_same_packet_subset.\n    - apply msg_refined_raft_net_invariant_reboot'_weak. apply ghost_log_entries_match_reboot.\n  Qed.\n\n  Instance glemi : ghost_log_entries_match_interface.\n  Proof.\n    split.\n    apply ghost_log_entries_match_invariant.\n  Qed.\nEnd GhostLogLogMatching.", "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/GhostLogLogMatchingProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1782386553054247}}
{"text": "Require Import VST.msl.msl_standard.\nRequire Import VST.veric.base.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.Clight_lemmas.\nRequire Import VST.veric.tycontext.\nRequire Import VST.veric.expr2.\nRequire Export VST.veric.environ_lemmas.\nRequire Import VST.veric.binop_lemmas2.\n(*Require Import VST.veric.binop_lemmas.*)\nRequire Import VST.veric.expr_lemmas2.\nImport Cop.\nImport Cop2.\n\nOpaque tc_andp. (* This is needed otherwise certain Qeds take\n    forever in Coq 8.3.  *)\n\nLemma type_eq_true : forall a b, proj_sumbool  (type_eq a b) =true  -> a = b.\nProof. intros. destruct (type_eq a b). auto. simpl in H. inv H.\nQed.\n\n(** Definitions of some environments **)\nDefinition empty_genv cenv := Build_genv (Globalenvs.Genv.empty_genv fundef type nil) cenv.\nDefinition empty_tenv := PTree.empty val.\n\nDefinition empty_environ cenv : environ :=\nmkEnviron (filter_genv (empty_genv cenv)) (Map.empty _) (Map.empty _).\n\nLemma Zle_bool_rev: forall x y, Zle_bool x y = Zge_bool y x.\nProof.\nintros. pose proof (Zle_cases x y). pose proof (Zge_cases y x).\ndestruct (Zle_bool x y); destruct (Zge_bool y x); auto;\nelimtype False; omega.\nQed.\n\n(** Typechecking soundness **)\n\nTransparent Float.to_int.\nTransparent Float.to_intu.\nTransparent Float32.to_int.\nTransparent Float32.to_intu.\n\n\nLemma isCastR: forall {CS: compspecs} tfrom tto a,\n  denote_tc_assert (isCastResultType tfrom tto a) =\n denote_tc_assert\nmatch classify_cast tfrom tto with\n| Cop.cast_case_default => tc_FF  (invalid_cast tfrom tto)\n| Cop.cast_case_f2i _ Signed => tc_andp (tc_Zge a Int.min_signed ) (tc_Zle a Int.max_signed)\n| Cop.cast_case_s2i _ Signed => tc_andp (tc_Zge a Int.min_signed ) (tc_Zle a Int.max_signed)\n| Cop.cast_case_f2i _ Unsigned => tc_andp (tc_Zge a 0) (tc_Zle a Int.max_unsigned)\n| Cop.cast_case_s2i _ Unsigned => tc_andp (tc_Zge a 0) (tc_Zle a Int.max_unsigned)\n| Cop.cast_case_i2l _ =>\n           tc_andp (tc_bool (is_int_type tfrom) (invalid_cast_result tfrom tto))\n             (if is_pointer_type tto then tc_iszero a else tc_TT)\n| Cop.cast_case_l2i _ _ => \n           tc_andp (tc_bool (is_long_type tfrom) (invalid_cast_result tfrom tto))\n             (if is_pointer_type tto then tc_iszero a else tc_TT)\n| Cop.cast_case_pointer  => \n           if eqb_type tfrom tto then tc_TT else\n           (if orb  (andb (is_pointer_type tto) (is_pointer_type tfrom))\n                       (if Archi.ptr64\n                        then (andb (is_long_type tto) (is_long_type tfrom)) \n                        else (andb (is_int_type tto) (is_int_type tfrom)))\n              then tc_TT\n              else tc_iszero a)\n| Cop.cast_case_l2l => tc_bool (is_long_type tfrom && is_long_type tto) (invalid_cast_result tto tto)\n| Cop.cast_case_f2bool => tc_bool (is_float_type tfrom) (invalid_cast_result tfrom tto)\n| Cop.cast_case_s2bool => tc_bool (is_single_type tfrom) (invalid_cast_result tfrom tto)\n| Cop.cast_case_l2bool => \n      if is_pointer_type tfrom\n      then tc_test_eq a (Econst_long Int64.zero (Tlong Unsigned noattr))\n      else tc_TT\n| Cop.cast_case_i2bool =>\n      if is_pointer_type tfrom\n      then tc_test_eq a (Econst_int Int.zero (Tint I32 Unsigned noattr))\n      else tc_TT\n| Cop.cast_case_void => tc_noproof\n| _ => match tto with\n      | Tint _ _ _  => tc_bool (is_int_type tfrom) (invalid_cast_result tto tto)\n      | Tfloat F64 _  => tc_bool (is_anyfloat_type tfrom) (invalid_cast_result tto tto)\n      | Tfloat F32 _  => tc_bool (is_anyfloat_type tfrom) (invalid_cast_result tto tto)\n      | _ => tc_FF (invalid_cast tfrom tto)\n      end\nend.\nProof. intros; extensionality rho.\n unfold isCastResultType.\n destruct (classify_cast tfrom tto) eqn:?; auto.\nQed.\n\nLemma Z2R_pow_0_lt:\n  forall e,\n  0 <= e ->\n  Rdefinitions.Rlt 0 (Fcore_Raux.Z2R (2 ^ e)).\nProof.\nintros.\nrewrite <- (Z2Nat.id e) by auto.\nclear.\ninduction (Z.to_nat e).\nsimpl.\napply RIneq.Rlt_0_1.\nrewrite inj_S.\nrewrite Z.pow_succ_r by omega.\nrewrite Fcore_Raux.Z2R_mult.\napply RIneq.Rmult_lt_0_compat; auto.\nsimpl.\nclear.\napply DiscrR.Rlt_R0_R2.\nQed.\n\nDefinition general_offloat (prec emax : Z)\n    (f:  Fappli_IEEE.binary_float prec emax) : option Z :=\n  match f with\n  | Fappli_IEEE.B754_zero _ => Some 0\n  | Fappli_IEEE.B754_infinity _ => None\n  | Fappli_IEEE.B754_nan _ _ => None\n  | Fappli_IEEE.B754_finite s m 0 _ => Some (Fcore_Zaux.cond_Zopp s (Z.pos m))\n  | Fappli_IEEE.B754_finite s m (Z.pos e) _ =>\n      Some (Fcore_Zaux.cond_Zopp s (Z.pos m) * Z.pow_pos 2 e)\n  | Fappli_IEEE.B754_finite s m (Z.neg e) _ =>\n      Some (Fcore_Zaux.cond_Zopp s (Z.pos m / Z.pow_pos 2 e))\n  end.\n\nDefinition general_float_to_int (prec emax : Z) (lo hi: Z) (f: Fappli_IEEE.binary_float prec emax) : option int :=\n option_map Int.repr\n   (Fappli_IEEE_extra.ZofB_range prec emax f lo hi).\n\nGoal Zoffloat = general_offloat 53 1024.\nreflexivity.\nQed.\n\nGoal Zofsingle = general_offloat 24 128.\nreflexivity.\nQed.\n\nGoal Float.to_int = general_float_to_int 53 1024 Int.min_signed Int.max_signed.\nreflexivity.\nQed.\n\nGoal Float.to_intu = general_float_to_int 53 1024 0 Int.max_unsigned.\nreflexivity.\nQed.\n\nGoal Float32.to_int = general_float_to_int 24 128 Int.min_signed Int.max_signed.\nreflexivity.\nQed.\n\nGoal Float32.to_intu = general_float_to_int 24 128 0 Int.max_unsigned.\nreflexivity.\nQed.\n\nLemma general_float_to_int_ok:\n  forall prec emax lo hi f z,\n    general_offloat prec emax f = Some z ->\n    lo <= z <= hi ->\n    general_float_to_int prec emax lo hi f = Some (Int.repr z).\nProof.\nintros.\nunfold general_offloat in H.\nunfold general_float_to_int.\ndestruct H0 as [H0 H1].\napply Z.leb_le in H0; apply Z.leb_le in H1.\ndestruct f; inv H.\n{ (* zero case *)\nrewrite Fappli_IEEE_extra.ZofB_range_correct. simpl.\nunfold Fcore_Raux.Ztrunc.\nrewrite Fcore_Raux.Rlt_bool_false by apply RIneq.Rle_refl.\nreplace (Fcore_Raux.Zfloor 0) with 0.\nrewrite H0,H1. reflexivity.\nunfold Fcore_Raux.Zfloor.\nreplace (Rdefinitions.up 0) with 1; [reflexivity |].\napply R_Ifp.tech_up; simpl.\napply RIneq.Rlt_0_1.\nrewrite Raxioms.Rplus_comm.\nrewrite RIneq.Rplus_0_r. apply RIneq.Rle_refl.\n}\n(* nonzero case *)\ndestruct (zle 0 e).\n* (* 0 <= e *)\nassert (z = Fcore_Zaux.cond_Zopp b (Z.pos m) * Z.pow 2 e). {\n  destruct e; inv H3.\n  rewrite Z.pow_0_r. rewrite Z.mul_1_r. auto.\n  rewrite Zpower_pos_nat. rewrite Zpower_nat_Z.\n  rewrite positive_nat_Z; auto.\n  pose proof (Pos2Z.neg_is_neg p); omega.\n}\nclear H3. subst z.\nrewrite Fappli_IEEE_extra.ZofB_range_correct.\nreplace\n   (Fcore_Raux.Ztrunc\n      (Fappli_IEEE.B2R prec emax (Fappli_IEEE.B754_finite prec emax b m e e0)))\n  with (Fcore_Zaux.cond_Zopp b (Z.pos m) * 2^e).\nrewrite H0,H1; clear H0 H1.\nrewrite (Fappli_IEEE_extra.is_finite_strict_finite prec emax).\nreflexivity.\nreflexivity.\nunfold Fcore_Zaux.cond_Zopp.\nunfold Fcore_Raux.Ztrunc.\ndestruct b; [rewrite Fcore_Raux.Rlt_bool_true | rewrite Fcore_Raux.Rlt_bool_false].\n+\nunfold Fappli_IEEE.B2R.\nunfold Fcore_Zaux.cond_Zopp.\nunfold Fcore_Raux.Zceil.\nunfold Fcore_Raux.Zfloor.\nsymmetry; apply Fcore_Raux.Zceil_imp; split.\neapply RIneq.Rlt_le_trans.\napply Fcore_Raux.Z2R_lt.\ninstantiate (1 := - Z.pos m * 2 ^ e). omega.\nunfold Fcore_defs.F2R.\nrewrite Fcore_Raux.Z2R_mult.\nmatch goal with |- _ ?A ?B => replace B with A; [apply RIneq.Rle_refl | ] end.\nf_equal.\nsimpl.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nreflexivity.\nmatch goal with |- _ ?A ?B => replace B with A; [apply RIneq.Rle_refl | ] end.\nunfold Fcore_defs.F2R.\nrewrite Fcore_Raux.Z2R_mult.\nsimpl.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nsimpl.\nauto.\n+\nsimpl. unfold Fcore_defs.F2R.\nsimpl.\nrewrite RIneq.Ropp_mult_distr_l_reverse.\napply RIneq.Ropp_lt_gt_0_contravar.\nunfold Rdefinitions.Rgt.\napply RIneq.Rmult_lt_0_compat.\nclear.\nrewrite Fcore_Raux.P2R_INR.\napply RIneq.lt_0_INR.\napply Pos2Nat.is_pos.\nsimpl.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nsimpl.\napply Z2R_pow_0_lt; auto.\n+\nunfold Fappli_IEEE.B2R.\nunfold Fcore_Zaux.cond_Zopp.\nsymmetry; apply Fcore_Raux.Zfloor_imp; split.\nmatch goal with |- _ ?A ?B => replace B with A; [apply RIneq.Rle_refl | ] end.\nunfold Fcore_defs.F2R.\nrewrite Fcore_Raux.Z2R_mult.\nsimpl.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nsimpl.\nauto.\nunfold Fcore_defs.F2R.\neapply RIneq.Rle_lt_trans.\ninstantiate (1:= (Fcore_Raux.Z2R (Z.pos m * 2 ^ e ))).\nrewrite Fcore_Raux.Z2R_mult.\nsimpl.\nrewrite !Fcore_Raux.P2R_INR.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nsimpl.\nmatch goal with |- _ ?A ?B => replace B with A; [apply RIneq.Rle_refl | ] end.\nf_equal.\n(* symmetry; apply Fcore_Raux.P2R_INR. *)\nrewrite Fcore_Raux.Z2R_plus.\nrewrite Raxioms.Rplus_comm.\nrewrite <- RIneq.Rplus_0_r at 1.\nrewrite Raxioms.Rplus_comm at 1.\napply RIneq.Rplus_lt_le_compat.\napply RIneq.Rlt_0_1.\napply RIneq.Req_le. auto.\n+\nunfold Fappli_IEEE.B2R.\nunfold Fcore_Zaux.cond_Zopp.\nunfold Fcore_defs.F2R.\nsimpl.\napply RIneq.Rmult_le_pos.\nrewrite Fcore_Raux.P2R_INR.\napply RIneq.pos_INR.\nrewrite <- Fcore_Raux.Z2R_Zpower by auto.\nsimpl.\napply RIneq.Rlt_le.\napply Z2R_pow_0_lt; auto.\n* (* e < 0 *)\nassert (HH: (Fcore_Raux.Z2R (2 ^ (- e))) <> Rdefinitions.R0). {\nassert (Rdefinitions.R0 <> Fcore_Raux.Z2R (2 ^ (- e))); auto.\napply RIneq.Rlt_not_eq.\napply (Z2R_pow_0_lt (-e)).\nomega.\n}\nassert (z = Fcore_Zaux.cond_Zopp b (Z.pos m / Z.pow 2 (- e))). {\n  destruct e; inv H3.\n  omega. pose proof (Zgt_pos_0 p); omega. clear g.\n  rewrite Zpower_pos_nat. rewrite Zpower_nat_Z.\n  rewrite positive_nat_Z; auto.\n}\nclear H3. subst z.\nrewrite Fappli_IEEE_extra.ZofB_range_correct.\nreplace\n   (Fcore_Raux.Ztrunc\n      (Fappli_IEEE.B2R prec emax (Fappli_IEEE.B754_finite prec emax b m e e0)))\n  with (Fcore_Zaux.cond_Zopp b (Z.pos m / 2^(-e))).\nrewrite H0,H1; clear H0 H1.\nrewrite (Fappli_IEEE_extra.is_finite_strict_finite prec emax).\nreflexivity.\nreflexivity.\nunfold Fcore_Zaux.cond_Zopp.\nunfold Fcore_Raux.Ztrunc.\ndestruct b; [rewrite Fcore_Raux.Rlt_bool_true | rewrite Fcore_Raux.Rlt_bool_false].\n+\nclear - g.\nunfold Fappli_IEEE.B2R.\nunfold Fcore_Zaux.cond_Zopp.\nunfold Fcore_Raux.Zceil.\nf_equal.\nunfold Fcore_defs.F2R.\nsimpl.\nrewrite RIneq.Ropp_mult_distr_l_reverse.\nrewrite RIneq.Ropp_involutive.\nrewrite <- Fcore_Raux.Zfloor_div by (apply Z.pow_nonzero; omega).\nrewrite <- (Z.opp_involutive e) at 2.\nrewrite (Fcore_Raux.bpow_opp _ (-e)).\nsymmetry.\nrewrite <- Fcore_Raux.Z2R_Zpower by omega.\nsimpl.\nunfold Rdefinitions.Rdiv.\nauto.\n+\nsimpl.\napply Fcore_float_prop.F2R_lt_0_compat.\nsimpl.  pose proof (Pos2Z.neg_is_neg m); omega.\n+\nsimpl.\nunfold Fcore_defs.F2R.\nsimpl.\nrewrite <- (Z.opp_involutive e) at 2.\nrewrite (Fcore_Raux.bpow_opp _ (-e)).\nrewrite <- Fcore_Raux.Z2R_Zpower by omega.\nsimpl.\nrewrite <- Fcore_Raux.Zfloor_div by (apply Z.pow_nonzero; omega).\nreflexivity.\n+\nsimpl.\nunfold Fcore_defs.F2R.\nsimpl.\nrewrite <- (Z.opp_involutive e).\nrewrite (Fcore_Raux.bpow_opp _ (-e)).\nrewrite <- Fcore_Raux.Z2R_Zpower by omega.\nsimpl.\napply RIneq.Rmult_le_pos.\nrewrite Fcore_Raux.P2R_INR.\napply RIneq.pos_INR.\napply RIneq.Rlt_le.\napply RIneq.Rinv_0_lt_compat.\napply Z2R_pow_0_lt; omega.\nQed.\n\n\nLemma float_to_int_ok:\n  forall f z,\n    Zoffloat f = Some z ->\n    Int.min_signed <= z <= Int.max_signed ->\n    Float.to_int f = Some (Int.repr z).\nProof.\napply general_float_to_int_ok.\nQed.\n\nLemma float_to_intu_ok:\n  forall f z,\n    Zoffloat f = Some z ->\n    0 <= z <= Int.max_unsigned ->\n    Float.to_intu f = Some (Int.repr z).\nProof.\napply general_float_to_int_ok.\nQed.\n\nLemma single_to_int_ok:\n  forall f z,\n    Zofsingle f = Some z ->\n    Int.min_signed <= z <= Int.max_signed ->\n    Float32.to_int f = Some (Int.repr z).\nProof.\napply general_float_to_int_ok.\nQed.\n\nLemma single_to_intu_ok:\n  forall f z,\n    Zofsingle f = Some z ->\n    0 <= z <= Int.max_unsigned ->\n    Float32.to_intu f = Some (Int.repr z).\nProof.\napply general_float_to_int_ok.\nQed.\n\n(* not necessary if rewrite denote_tc_assert_andp *)\n(*\nLemma denote_tc_assert_andp_e:\n  forall a b rho, denote_tc_assert Delta (tc_andp a b) rho ->\n         denote_tc_assert Delta a rho /\\ denote_tc_assert Delta b rho.\nProof.\nintros.\nrewrite denote_tc_assert_andp in H; auto.\nQed.\n*)\nLemma andb_zleb:\n forall i j k : Z,  i <= j <= k ->\n      (i <=? j) && (j <=? k) = true.\nProof.\nintros ? ? ? [? ?]; rewrite andb_true_iff; split;\n apply Z.leb_le; auto.\nQed.\n\nLemma sign_ext_range':\n    forall n x, 0 < n < Int.zwordsize ->\n      - two_p (n - 1) <= Int.signed (Int.sign_ext n x) <= two_p (n - 1) -1.\nProof.\nintros.\npose proof (Int.sign_ext_range n x H).\nomega.\nQed.\n\nLemma zero_ext_range':\n  forall n x, 0 <= n < Int.zwordsize ->\n     0 <= Int.unsigned (Int.zero_ext n x) <= two_p n - 1.\nProof.\nintros.\n pose proof (Int.zero_ext_range n x H); omega.\nQed.\n\nLemma int64_eq_e: forall i, Int64.eq i Int64.zero = true -> i=Int64.zero.\nProof.\nintros.\npose proof (Int64.eq_spec i Int64.zero). rewrite H in H0; auto.\nQed.\n\nLemma long_int_zero_lem:\n  forall i, Int64.eq (Int64.repr (Int64.unsigned i)) Int64.zero = true ->\n    Int.repr (Int64.unsigned i) = Int.zero.\nProof.\n intros.\n apply int64_eq_e in H.\nunfold Int.zero.\nrewrite Int64.repr_unsigned in H.\nsubst.\nreflexivity.\nQed.\n\nLemma typecheck_cast_sound:\n forall {CS: compspecs} Delta rho m e t,\n typecheck_environ Delta rho ->\n (denote_tc_assert (typecheck_expr Delta e) rho m ->\n   tc_val (typeof e) (eval_expr e rho))  ->\ndenote_tc_assert (typecheck_expr Delta (Ecast e t)) rho m ->\ntc_val (typeof (Ecast e t)) (eval_expr (Ecast e t) rho).\nProof.\nintros until t; intros H H1 H0.\nsimpl in *. unfold_lift.\nrewrite denote_tc_assert_andp in H0.\ndestruct H0.\nspecialize (H1 H0); clear H0.\nunfold  sem_cast, force_val1.\nrewrite isCastR in H2.\ndestruct (classify_cast (typeof e) t)\n     as [ | | | | | | | | sz [ | ] | sz [ | ] | | | | | | [ | ] | [ | ] | | | | | | | |  ]\n   eqn:H3;\n   try contradiction;\n destruct t as [ | [ | | | ] [ | ] | [ | ] | [ | ] | | | | | ];\n    try discriminate H3; try contradiction;\n destruct (typeof e) as [ | [ | | | ] [ | ] | [ | ] | [ | ] | | | | | ];\n    try discriminate H3; try contradiction;\n  unfold classify_cast in H3;\n  try replace (if Archi.ptr64 then false else false) with false in H2 by (destruct Archi.ptr64; auto);\n  repeat (progress unfold_lift in H2; simpl in H2);  (* needed ? *)\n  unfold tc_val, is_pointer_type in *;\n  repeat match goal with |- context [eqb_type ?A ?B] =>\n              let J := fresh \"J\" in \n              destruct (eqb_type A B) eqn:J;\n             [apply eqb_type_true in J | apply eqb_type_false in J]\n    end;\n  repeat match goal with H: context [eqb_type ?A ?B] |- _ =>\n              let J := fresh \"J\" in \n              destruct (eqb_type A B) eqn:J;\n             [apply eqb_type_true in J | apply eqb_type_false in J]\n    end;\n   try discriminate;\n   rewrite ?if_true in H3 by auto; rewrite ?if_false in H3 by (clear; congruence);\n   try (destruct Archi.ptr64 eqn:?Hp; try discriminate; [idtac]);\n  repeat match goal with\n       | H: app_pred (denote_tc_assert (tc_andp _ _) _) _ |- _ => \n          rewrite denote_tc_assert_andp in H; destruct H\n       | H: app_pred (denote_tc_assert (if ?A then _ else _) _) _ |- _ =>\n           first [change A with false in H | change A with true in H]; cbv iota in H\n       | H: app_pred (denote_tc_assert (tc_iszero _) _) _ |- _ =>\n                   rewrite denote_tc_assert_iszero in H\n       | H: app_pred (denote_tc_assert (tc_bool _ _) _) _ |- _ => apply tc_bool_e in H\n       | H: app_pred (denote_tc_assert _ _) _ |- _ =>\n             unfold denote_tc_assert, denote_tc_Zle, denote_tc_Zge in H;\n             unfold_lift in H\n       end;\n   destruct (eval_expr e rho); try solve [contradiction H1];\n   try apply I;\n   try solve [contradiction];\n   unfold sem_cast_pointer, sem_cast_i2i, sem_cast_f2f, sem_cast_s2s,\n   sem_cast_f2i, sem_cast_s2i, cast_float_int, is_pointer_or_null, force_val in *;\n   repeat rewrite Hp in *;\n   repeat match goal with\n        | H: app_pred (prop _) _ |- _ => apply is_true_e in H; \n                                      try (apply int_eq_e in H; subst)\n       end;\n    auto;\n    inv H3;\n   try (simpl in H1|-*;\n      match goal with\n      | |- context[Int.sign_ext ?n ?x] =>\n      apply (sign_ext_range' n x); compute; split; congruence\n      | |- context[Int.zero_ext ?n ?x] =>\n      apply (zero_ext_range' n x); compute; try split; congruence\n     end);\n   simpl; \n    try match goal with |- (if ?A then _ else _) = _ \\/ (if ?A then _ else _) = _ =>\n      destruct A; solve [auto]\n     end;\n  repeat  match goal with\n    | H: app_pred match ?A with Some _ => _ | None => _ end _ |- _ =>\n         destruct A eqn:?; [  | contradiction H]\n    | H: app_pred (prop _) _ |- _ => apply is_true_e in H;\n           rewrite ?Z.leb_le, ?Z.geb_le in H\n   end.\n\nall: try (first [ erewrite float_to_int_ok | erewrite float_to_intu_ok\n          | erewrite single_to_int_ok | erewrite single_to_intu_ok];\n          [ | eassumption | split; assumption]).\nall:   try match goal with\n     | |- context[Int.sign_ext ?n ?x] =>\n      apply (sign_ext_range' n x); compute; split; congruence\n     | |- context[Int.zero_ext ?n ?x] =>\n      apply (zero_ext_range' n x); compute; try split; congruence\n   end.\nall: try apply I.\nall: rewrite ?Hp; hnf; auto.\nall: apply long_int_zero_lem; auto.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/veric/expr_lemmas3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.1779431507268667}}
{"text": "(** printing \u22a2#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing \u22a2##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing \u22a2##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing \u22a2!    %\\vdash_!%       #&vdash;<sub>!</sub>#         *)\n(** remove printing ~ *)\n\nSet Implicit Arguments.\n\nRequire Import Coq.Program.Equality String.\nRequire Import Definitions Weakening Narrowing.\nRequire Import ConstrLangAlt ConstrTyping ConstrWeakening ConstrSubenvironments.\nRequire Import ConstrEntailment.\nRequire Import ConstrSubtypingLaws.\n\n\nLemma strengthen_constr_general_typing : forall C1 C2 G t T,\n  C1 \u22a9 C2 ->\n  (C2, G) \u22a2c t : T ->\n  (C1, G) \u22a2c t : T\nwith strengthen_constr_general_typing_def : forall C1 C2 G d D,\n  C1 \u22a9 C2 ->\n  (C2, G) /-c d : D ->\n  (C1, G) /-c d : D\nwith strengthen_constr_general_typing_defs : forall C1 C2 G ds D,\n  C1 \u22a9 C2 ->\n  (C2, G) /-c ds :: D ->\n  (C1, G) /-c ds :: D\nwith strengthen_constr_general_subtyping : forall C1 C2 G T U,\n  C1 \u22a9 C2 ->\n  (C2, G) \u22a2c T <: U ->\n  (C1, G) \u22a2c T <: U.\nProof.\n  all: introv He Ht.\n  - gen C1. dependent induction Ht; introv He.\n    -- constructor. assumption.\n    -- pick_fresh x.\n       apply cty_all_intro with L. introv Hne0.\n       apply* H0.\n    -- apply* cty_all_elim.\n    -- apply cty_new_intro with L.\n       introv Hn. specialize (H x Hn). apply* strengthen_constr_general_typing_defs.\n    -- apply cty_new_elim. apply* IHHt.\n    -- apply cty_let with L T. apply* IHHt.\n       introv Hne. specialize (H0 x Hne). apply* H0.\n    -- apply cty_rec_intro. apply* IHHt.\n    -- apply cty_rec_elim. apply* IHHt.\n    -- apply cty_and_intro; try apply* IHHt1; try apply* IHHt2.\n    -- apply cty_sub with T. apply* IHHt. apply* strengthen_constr_general_subtyping.\n  - gen C1. dependent induction Ht; introv He.\n    -- constructor.\n    -- constructor. apply* strengthen_constr_general_typing.\n  - gen C1. dependent induction Ht; introv He.\n    -- constructor. apply* strengthen_constr_general_typing_def.\n    -- constructor. apply* IHHt. apply* strengthen_constr_general_typing_def.\n       exact H0.\n  - gen C1. dependent induction Ht; introv He.\n    -- apply csubtyp_intro with x S S'; try assumption.\n       apply* IHHt. apply* ent_cong_and.\n    -- apply* csubtyp_inst. apply* ent_trans.\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/StrengtheningConstr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.1779431472538819}}
{"text": "From ConCert.Utils Require Import Extras.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution.Test Require Import QCTest.\nFrom ConCert.Examples.Congress Require Import Congress.\nFrom ConCert.Examples.Congress Require Export CongressGens.\nFrom ConCert.Examples.Congress Require Export CongressPrinters.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import List. Import ListNotations.\n\n\nDefinition LocalChainBase : ChainBase := TestUtils.LocalChainBase.\n\nDefinition chain1 : ChainBuilder := builder_initial.\nDefinition chain2 : ChainBuilder := unpack_result (add_block chain1 []).\nDefinition chain3 : ChainBuilder := unpack_result\n  (add_block chain2 [build_transfer creator person_1 10]).\n\nDefinition setup_rules :=\n  {| min_vote_count_permille := 200; (* 20% of congress needs to vote *)\n      margin_needed_permille := 501;\n      debating_period_in_blocks := 0; |}.\n\nDefinition setup := Congress.build_setup setup_rules.\nDefinition deploy_congress : ActionBody :=\n  create_deployment 5 Congress.contract setup.\nDefinition chain4 : ChainBuilder :=\n  unpack_result (add_block chain3 [build_deploy person_1 5 Congress.contract setup]).\nDefinition congress_1 : Address :=\n  match outgoing_txs (builder_trace chain4) person_1 with\n  | tx :: _ => tx_to tx\n  | _ => person_1\n  end.\nDefinition congress_ifc : ContractInterface Congress.Msg :=\n  match get_contract_interface chain4 congress_1 Congress.Msg with\n  | Some x => x\n  (* Using unpack_option here is extremely slow *)\n  | None =>\n    @build_contract_interface\n      _ _\n      creator\n      (fun a m => deploy_congress)\n  end.\n\n(* person_1 adds person_1 and person_2 as members of congress *)\nDefinition add_person p :=\n  congress_ifc.(send) 0 (Some (add_member p)).\nDefinition chain5 : ChainBuilder :=\n  let acts := [build_act person_1 person_1 (add_person person_1);\n               build_act person_1 person_1 (add_person person_2)] in\n  unpack_result (add_block chain4 acts).\nDefinition create_proposal_call :=\n  congress_ifc.(send) 0 (Some (create_proposal [cact_transfer person_3 3])).\n\nDefinition congress_chain := chain5.\nDefinition congress_caddr := addr_of_Z 128%Z.\n\nModule NotationInfo <: TestNotationParameters.\n  Definition gAction := (fun env => GCongressAction env act_depth congress_caddr).\n  Definition init_cb := congress_chain.\nEnd NotationInfo.\nModule TN := TestNotations NotationInfo. Import TN.\n(* Sample gChain. *)\n\nDefinition nr_cacts (msg : option Congress.Msg) :=\n  match msg with\n  | Some (create_proposal ls) => length ls\n  | _ => 0\n  end.\n\nDefinition num_cacts_in_state state :=\n  sumnat (fun '(k, v) => length (actions v)) (FMap.elements (proposals state)).\n\n(* This property states that the number of actions to be performed by the congress never increases\n   more than the actions that are added in proposals, i.e. actions can't appear out of nowhere. *)\n(* If we replace '<=' with '<' QC finds a counterexample - a proposal can contain an empty list of actions, so they are equal before/after add_proposal *)\nDefinition receive_state_well_behaved state msg new_state (resp_acts : list ActionBody) :=\n  num_cacts_in_state new_state + length resp_acts <=\n  num_cacts_in_state state + nr_cacts msg.\n\n#[export]\nInstance receive_state_well_behaved_dec_ {state : Congress.State}\n                                         {msg : option Congress.Msg}\n                                         {new_state : Congress.State}\n                                         {resp_acts : list ActionBody}\n                                         : Dec (receive_state_well_behaved state msg new_state resp_acts).\nProof.\n  intros;\n  unfold receive_state_well_behaved;\n  constructor;\n  apply le_dec.\nQed.\n\n#[export]\nInstance receive_state_well_behaved_checkable {state : Congress.State}\n                                              {msg : option Congress.Msg}\n                                              {new_state : Congress.State}\n                                              {resp_acts : list ActionBody}\n                                              : Checkable (receive_state_well_behaved state msg new_state resp_acts).\nProof. apply testDec. Qed.\n\nDefinition receive_state_well_behaved_P (chain : Chain)\n                                        (cctx : ContractCallContext)\n                                        (old_state : Congress.State)\n                                        (msg : Congress.Msg)\n                                        (result : option (Congress.State * list ActionBody)) :=\n  checker match result with\n  | Some (new_state, resp_acts) =>\n    (receive_state_well_behaved old_state (Some msg) new_state resp_acts)?\n  | _ => false\n  end.\n\n(* QuickChick (\n  {{fun _ _ => true}}\n  congress_caddr\n  {{receive_state_well_behaved_P}}\n). *)\n(* coqtop-stdout:+++ Passed 10000 tests (0 discards) *)\n\nOpen Scope nat.\n\n(* A property about the way States are generated. *)\n(* It says that a State generated at some time slot cannot contain proposals later than this time slot. *)\nDefinition state_proposals_proposed_in_valid_P (block_slot : nat) (state : Congress.State) :=\n  let proposals := map snd (FMap.elements (proposals state)) in\n  forallb (fun p => proposed_in p <=? block_slot) proposals.\n\nDefinition state_proposals_proposed_in_valid (cs : ChainState) :=\n  let state_opt := get_contract_state Congress.State cs congress_caddr in\n  whenFail (show cs.(env_chain))\n  match state_opt with\n  | Some state => checker (state_proposals_proposed_in_valid_P cs.(current_slot) state)\n  | None => checker true\n  end.\n\n(* QuickChick (forAllBlocks state_proposals_proposed_in_valid). *)\n(* coqtop-stdout:+++ Passed 10000 tests (0 discards) *)\n\nDefinition congress_has_votes_on_some_proposal (cs : ChainState) :=\n  let state_opt := get_contract_state Congress.State cs congress_caddr in\n  match state_opt with\n  | Some state =>\n       let proposals := map snd (FMap.elements (proposals state)) in\n    existsb (fun proposal =>\n      0 <? FMap.size proposal.(votes)\n    ) proposals\n  | None => false\n  end.\n\n(* QuickChick (chain5 ~~> congress_has_votes_on_some_proposal). *)\n(* Success - found witness satisfying the predicate!\n+++ Failed (as expected) after 7 tests and 0 shrinks. (0 discards) *)\n\n(* This assumes that in a previous block, there was an active proposal *)\nDefinition congress_finished_a_vote (cs : ChainState) :=\n  let acts := cs.(chain_state_queue) in\n  let act_is_finish_vote (act : Action) :=\n    match act.(act_body) with\n    | act_call _ _ msg =>\n      match deserialize Congress.Msg _ msg with\n      | Some (Congress.finish_proposal _) => true\n      | _ => false\n      end\n    | _ => false\n    end in\n    existsb act_is_finish_vote acts.\n\n(* QuickChick (chain5 ~~> congress_finished_a_vote). *)\n(* Success - found witness satisfying the predicate!\n+++ Failed (as expected) after 14 tests and 0 shrinks. (0 discards) *)\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/congress/tests/CongressTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.17794314725388188}}
{"text": "(* A deterministic RiscvMachine performing only internal MMIO,\n   i.e. MMIO between the processor and a hardware device simulator that\n   does not show up in the event trace.\n   No external MMIO (ie interaction with the external world) is performed\n   by this machine, so mach.(getMachine).(getLog) always remains [].\n   Based on riscv.Platform.Minimal *)\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Bool.Bvector.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import riscv.Utility.Monads. Import OStateOperations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Utility.FreeMonad.\nRequire Import riscv.Spec.Primitives.\nRequire Export riscv.Platform.RiscvMachine.\nRequire Export riscv.Platform.MaterializeRiscvProgram.\nRequire Export Bedrock2Experiments.RiscvMachineWithCavaDevice.ExtraRiscvMachine.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Word.Bitwidth32.\nRequire Import riscv.Platform.Sane.\nRequire Export Cava.TLUL.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\nImport ListNotations.\n\n(* TODO move to riscv-coq *)\nModule free.\n  Section WithParams.\n    Context {action: Type} {result: action -> Type} {state: Type}\n            (interp_action: forall a: action, OState state (result a)) {answer: Type}.\n    Definition interp_as_OState_body interp_as_OState (m: free action result answer):\n      OState state answer :=\n      match m with\n      | free.ret x => Return x\n      | free.act a k => Bind (interp_action a) (fun r => interp_as_OState (k r))\n      end.\n    Fixpoint interp_as_OState(m: free action result answer): OState state answer :=\n      interp_as_OState_body interp_as_OState m.\n  End WithParams.\nEnd free.\n\nModule device.\n  (* A deterministic device, to be instantiated with a Cava device *)\n  Class device := {\n    (* circuit state, will be instantiated with result of Cava.Core.Circuit.circuit_state *)\n    state: Type;\n\n    (* tells whether the device is in a state where it's ready to be used, typically\n       includes Cava.Core.Circuit.reset_state *)\n    is_ready_state: state -> Prop;\n\n    (* the d2h output the device produced when it transitioned to the state *)\n    (* TODO: probably need to add to [device_implements_state_machine] something like\n     [forall s h2d d2h s', run1 s h2d = (s', d2h) -> last_d2h s' = d2h] *)\n    last_d2h: state -> tl_d2h;\n\n    (* run one simulation step, will be instantiated with Cava.Semantics.Combinational.step *)\n    run1: (* input: TileLink host-2-device *)\n      state -> tl_h2d ->\n      (* output: next state, TileLink device-2-host *)\n      state;\n\n    (* lowest address of the MMIO address range used to communicate with this device *)\n    addr_range_start: Z;\n\n    (* one past the highest MMIO address *)\n    addr_range_pastend: Z;\n\n    (* max number of device cycles this device takes to serve read/write requests, ie\n       max number of run1 calls with active read/write request until the device responds *)\n    maxRespDelay: state -> nat;\n  }.\n  (* Note: there are two levels of \"polling until a response is available\":\n     - on the hardware level, using runUntilResp, which appears as\n       blocking I/O for the software\n     - on the software level, using MMIO reads on some status register,\n       where the MMIO read immediately gives a \"busy\" response, and the\n       software keeps polling until the MMIO read returns a \"done\" response *)\n\n  Definition waitForResp{D: device} :=\n    fix rec(fuel: nat)(s: device.state): option device.state :=\n      let next := device.run1 s (set_d_ready true tl_h2d_default) in\n      if d_valid (device.last_d2h next) then\n        Some next\n      else\n        match fuel with\n        | O => None\n        | S fuel' => rec fuel' next\n        end.\n\n  (* returning None means out of fuel and must not happen if fuel >= device.maxRespDelay.\n     It is also assumed that [a_valid h2d = true] and [d_ready h2d = true].\n     When the result is [Some res], retrieve the response d2h by calling\n     [device.last_d2h res]. *)\n  Definition runUntilResp{D: device}(h2d: tl_h2d) :=\n    fix rec(fuel: nat)(s: device.state): option device.state :=\n      let next := device.run1 s h2d in\n      if a_ready (device.last_d2h s) then\n        if d_valid (device.last_d2h next) then\n          Some next\n        else\n          match fuel with\n          | O => None\n          | S fuel' => waitForResp fuel' next\n          end\n      else\n        match fuel with\n        | O => None\n        | S fuel' => rec fuel' next\n        end.\n\n  Section WithWordAndDevice.\n    Context {word: Interface.word.word 32} {word_ok: word.ok word} {D: device}.\n\n    Definition isMMIOAddr(a: word): Prop :=\n      device.addr_range_start <= word.unsigned a < device.addr_range_pastend.\n\n    Definition isMMIOAddrB(a: word)(n: nat): bool :=\n      (device.addr_range_start <=? word.unsigned a) &&\n      (word.unsigned a + Z.of_nat n <=? device.addr_range_pastend).\n  End WithWordAndDevice.\nEnd device.\nNotation device := device.device.\nGlobal Coercion device.state: device >-> Sortclass.\n\n(* Needed because of https://github.com/coq/coq/issues/14031 *)\n#[export] Hint Extern 1 (MachineWidth _) => exact MkMachineWidth.MachineWidth_XLEN\n  : typeclass_instances.\n\n(* TODO move to coqutil *)\nModule word. Section WithParams.\n  Context {width: Z} {word: word.word width}.\n  Definition leu(a b: word) := negb (word.gtu a b).\n  Definition geu(a b: word) := negb (word.ltu a b).\nEnd WithParams. End word.\n\nSection WithParams.\n  Context {word: Interface.word.word 32}.\n  Context {word_ok: word.ok word}.\n\n  Context {D: device}.\n  Context {mem: map.map word byte}.\n  Context {Registers: map.map Register word}.\n\n  (* redefine monad notations with explicit type in Bind, otherwise Coq might will\n     infer the wrong instance in loadN, without backtracking enough *)\n  Notation \"x <- m1 ; m2\" := (Bind (M := OState (ExtraRiscvMachine D)) m1 (fun x => m2))\n    (right associativity, at level 60).\n  Notation \"m1 ;; m2\" := (Bind (M := OState (ExtraRiscvMachine D)) m1 (fun _ => m2))\n    (right associativity, at level 60).\n\n  Definition update(f: ExtraRiscvMachine D -> ExtraRiscvMachine D):\n    OState (ExtraRiscvMachine D) unit :=\n    m <- get; put (f m).\n\n  Definition updateExtra(f: D -> D): OState (ExtraRiscvMachine D) unit :=\n    update (fun m => withExtraState (f m.(getExtraState)) m).\n\n  Definition fail_if_None{R}(o: option R): OState (ExtraRiscvMachine D) R :=\n    match o with\n    | Some x => Return x\n    | None => fail_hard\n    end.\n\n  Definition N_to_word(v: N): word :=\n    word.of_Z (Z.of_N v).\n\n  Definition word_to_N(w: word): N :=\n    Z.to_N (word.unsigned w).\n\n  Definition runUntilResp(h2d: tl_h2d):\n    OState (ExtraRiscvMachine D) word :=\n    mach <- get;\n    new_device_state <- fail_if_None\n                         (device.runUntilResp h2d (device.maxRespDelay mach.(getExtraState))\n                                              mach.(getExtraState));\n    put (withExtraState new_device_state mach);;\n    Return (N_to_word (d_data (device.last_d2h new_device_state))).\n\n  Definition mmioLoad(log2_nbytes: nat)(addr: word)\n    : OState (ExtraRiscvMachine D) (HList.tuple byte (2 ^ log2_nbytes)) :=\n    let h2d : tl_h2d :=\n        set_a_valid true\n        (set_a_opcode Get\n        (set_a_size (N.of_nat log2_nbytes)\n        (set_a_address (word_to_N addr)\n        (set_d_ready true tl_h2d_default)))) in\n    v <- runUntilResp h2d;\n    Return (LittleEndian.split (2 ^ log2_nbytes) (word.unsigned v)).\n\n  Definition mmioStore(log2_nbytes: nat)(addr: word)(v: HList.tuple byte (2 ^ log2_nbytes))\n    : OState (ExtraRiscvMachine D) unit :=\n    let h2d : tl_h2d :=\n        set_a_valid true\n        (set_a_opcode PutFullData\n        (set_a_size (N.of_nat log2_nbytes)\n        (set_a_address (word_to_N addr)\n        (set_a_data (Z.to_N (LittleEndian.combine (2 ^ log2_nbytes) v))\n        (set_d_ready true tl_h2d_default))))) in\n    ignored <- runUntilResp h2d;\n    Return tt.\n\n  Definition loadN(log2_nbytes: nat)(kind: SourceType)(a: word):\n    OState (ExtraRiscvMachine D) (HList.tuple byte (2 ^ log2_nbytes)) :=\n    mach <- get;\n    match Memory.load_bytes (2 ^ log2_nbytes) mach.(getMachine).(getMem) a with\n    | Some v =>\n      match kind with\n      | Fetch => if isXAddr4B a mach.(getMachine).(getXAddrs) then Return v else fail_hard\n      | _ => Return v\n      end\n    | None => if device.isMMIOAddrB a (2 ^ log2_nbytes) then mmioLoad log2_nbytes a else fail_hard\n    end.\n\n  Definition storeN(log2_nbytes: nat)(kind: SourceType)(a: word)(v: HList.tuple byte ( 2 ^ log2_nbytes)) :=\n    mach <- get;\n    match Memory.store_bytes (2 ^ log2_nbytes) mach.(getMachine).(getMem) a v with\n    | Some m => update (withMem m)\n    | None => if device.isMMIOAddrB a (2 ^ log2_nbytes) then mmioStore log2_nbytes a v else fail_hard\n    end;;\n    update (fun mach => withXAddrs (invalidateWrittenXAddrs (2 ^ log2_nbytes) a mach.(getXAddrs)) mach).\n\n  Definition interpret_action(a: riscv_primitive): OState (ExtraRiscvMachine D) (primitive_result a) :=\n    match a with\n    | GetRegister reg =>\n        if Z.eq_dec reg Register0 then\n          Return (word.of_Z 0)\n        else\n          mach <- get;\n          match map.get mach.(getMachine).(getRegs) reg with\n          | Some v => Return v\n          | None => Return (word.of_Z 0)\n          end\n    | SetRegister reg v =>\n        if Z.eq_dec reg Register0 then\n          Return tt\n        else\n          update (fun mach => withRegs (map.put mach.(getMachine).(getRegs) reg v) mach)\n    | GetPC => mach <- get; Return mach.(getMachine).(getPc)\n    | SetPC newPC => update (withNextPc newPC)\n    | LoadByte ctxid a => loadN 0 ctxid a\n    | LoadHalf ctxid a => loadN 1 ctxid a\n    | LoadWord ctxid a => loadN 2 ctxid a\n    | LoadDouble ctxid a => loadN 3 ctxid a\n    | StoreByte ctxid a v => storeN 0 ctxid a v\n    | StoreHalf ctxid a v => storeN 1 ctxid a v\n    | StoreWord ctxid a v => storeN 2 ctxid a v\n    | StoreDouble ctxid a v => storeN 3 ctxid a v\n    | EndCycleNormal => update (fun m => (withPc m.(getNextPc)\n                                         (withNextPc (word.add m.(getNextPc) (word.of_Z 4)) m)))\n    | EndCycleEarly _\n    | MakeReservation _\n    | ClearReservation _\n    | CheckReservation _\n    | GetCSRField _\n    | SetCSRField _ _\n    | GetPrivMode\n    | SetPrivMode _\n    | Fence _ _\n        => fail_hard\n    end.\n\n  Definition device_step_without_IO(d: D): D :=\n    let next_state := device.run1 d (set_d_ready true tl_h2d_default) in next_state.\n\n  Fixpoint device_steps(n: nat): OState (ExtraRiscvMachine D) unit :=\n    match n with\n    | O => Return tt\n    | S n' => updateExtra device_step_without_IO;; device_steps n'\n    end.\n\n  (* In the time that the riscv core needs to execute the i-th instruction, how many\n     cycles does the device execute? *)\n  Definition schedule := nat -> nat.\n\n  Section WithSchedule.\n    Context (sched: schedule).\n\n    Definition nth_step(n: nat): OState (ExtraRiscvMachine D) unit :=\n      device_steps (sched n);; free.interp_as_OState interpret_action (Run.run1 RV32IM).\n\n    Fixpoint run_rec(steps_done steps_remaining: nat): OState (ExtraRiscvMachine D) unit :=\n      match steps_remaining with\n      | O => Return tt\n      | S n => nth_step steps_done;; run_rec (S steps_done) n\n      end.\n\n    Definition run(steps_remaining: nat)(s: ExtraRiscvMachine D): option (ExtraRiscvMachine D) :=\n      match run_rec 0 steps_remaining s with\n      | (Some tt, final) => Some final\n      | (None, _) => None\n      end.\n  End WithSchedule.\n\nEnd WithParams.\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/RiscvMachineWithCavaDevice/InternalMMIOMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.30404168757891037, "lm_q1q2_score": 0.17789514232831866}}
{"text": "(** * Extensions for Prelude from Embedding *)\n\n(** Extends Prelude from Embedding with new definitions required for extraction *)\n\nFrom ConCert.Embedding Require Import Ast.\nFrom ConCert.Embedding Require Import Notations.\nFrom ConCert.Embedding Require Import PCUICTranslate.\nFrom ConCert.Embedding Require Import TranslationUtils.\nFrom ConCert.Embedding Require Import Prelude.\nFrom ConCert.Embedding Require Import Utils.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Utils Require Import Automation.\nFrom Coq Require Import String.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import List.\n\nFrom MetaCoq.Template Require Import All.\n\nImport MCMonadNotation.\nImport ListNotations.\nImport BaseTypes.\nOpen Scope list.\nOpen Scope nat.\n\n(** ** Wrappers for some primitive types *)\n\nMetaCoq Run\n        ( mp_ <- tmCurrentModPath tt ;;\n          let mp := (PCUICTranslate.string_of_modpath mp_ ++ \"@\")%string in\n          mkNames mp [\"address\"; \"time\"; \"ContractAddr\";\n                      \"UserAddr\"; \"Time\" ; \"Money\" ] \"_coq\").\n\n\nDefinition address_ty :=\n  [\\ data address =\n      ContractAddr [Nat,_]\n    | UserAddr [Nat, _] \\].\n\nMetaCoq Unquote Inductive (global_to_tc address_ty).\n\nDefinition time_ty :=\n  [\\ data time = Time [Nat,_] \\].\n\nMetaCoq Unquote Inductive (global_to_tc time_ty).\n\nDefinition money := to_string_name <% Z %>.\n\n\n(** Comparison for addresses and time *)\n\nDefinition ltb_time (t1 t2 : time_coq) :=\n  let '(Time_coq n1) := t1 in\n    let '(Time_coq n2) := t2 in\n    n1 <? n2.\n\nDefinition leb_time (t1 t2 : time_coq) :=\n  let '(Time_coq n1) := t1 in\n  let '(Time_coq n2) := t2 in\n  n1 <=? n2.\n\nDefinition eqb_addr (a1 a2 : address_coq) :=\n  match a1,a2 with\n  | ContractAddr_coq n1, ContractAddr_coq n2 => Nat.eqb n1 n2\n  | UserAddr_coq n1, UserAddr_coq n2 => Nat.eqb n1 n2\n  | _, _ => false\n  end.\n\n\n(** Additional notations for addresses *)\n\n Notation \"a ==a b\" := [| {eConst (to_string_name <% eqb_addr %>)} {a} {b} |]\n                        (in custom expr at level 0).\n\n\n(** Additional notations for time *)\n\nNotation \"a <t b\" := [| {eConst (to_string_name <% ltb_time %>)} {a} {b} |]\n                      (in custom expr at level 0).\nNotation \"a <=t b\" := [| {eConst (to_string_name <% leb_time %>)} {a} {b} |]\n                       (in custom expr at level 0).\n\n(** A simplified representation of a call context.\n    Contains: current time, sender, transaction amount, contract's balance *)\nNotation \"'CallCtx'\" := [! time \u00d7 (address \u00d7 (money \u00d7 money)) !]\n                         (in custom type at level 0).\n\nNotation \"'current_time' st\" :=\n  [| first time (address \u00d7 (money \u00d7 money)) {st} |]\n    (in custom expr at level 0).\n\nNotation \"'sender_addr' st\" :=\n  [| first address (money \u00d7 money) (second time (address \u00d7 (money \u00d7 money)) {st}) |]\n    (in custom expr at level 0).\n\nNotation \"'sent_amount' st\" :=\n  [| first money money (second address (money \u00d7 money) (second time (address \u00d7 (money \u00d7 money)) {st})) |]\n    (in custom expr at level 0).\n\nNotation \"'acc_balance' st\" :=\n  [| second money money (second address (money \u00d7 money) (second time (address \u00d7 (money \u00d7 money)) {st})) |]\n    (in custom expr at level 0).\n\nNotation \"'mkCallCtx' now sender sent_am bal \" :=\n  [| Pair time (address \u00d7 (money \u00d7 money)) {now}\n          (Pair address (money \u00d7 money) {sender}\n                (Pair money money {sent_am} {bal} )) |]\n    (in custom expr at level 0).\n\n(** A simple representation of the call context *)\n\n(** current_time, sender_add, sent_amount, acc_balance *)\nDefinition SimpleCallCtx : Set := time_coq \u00d7 (address_coq \u00d7 (Amount \u00d7 Amount)).\n\n(** These projections correspond to the notations above *)\nDefinition sc_current_time (ctx : SimpleCallCtx) : time_coq := ctx.1.\nDefinition sc_sender_addr (ctx : SimpleCallCtx) : address_coq := ctx.2.1.\nDefinition sc_sent_amount (ctx : SimpleCallCtx) : Z := ctx.2.2.1.\nDefinition sc_acc_balance (ctx : SimpleCallCtx) : Z := ctx.2.2.2.\n\n\nDefinition is_contract (addr: address_coq) :=\n  match addr with\n  | ContractAddr_coq _ => true\n  | UserAddr_coq _ => false\n  end.\n\nDefinition encode_addr (addr: address_coq) : nat + nat :=\n  match addr with\n  | ContractAddr_coq x => inl x\n  | UserAddr_coq x => inr x\n  end.\n\nDefinition decode_addr (addr: nat + nat) : address_coq :=\n  match addr with\n  | inl x => ContractAddr_coq x\n  | inr x => UserAddr_coq x\n  end.\n\n\nGlobal Program Instance CB : ChainBase :=\n  build_chain_base address_coq eqb_addr _ _ _ _ is_contract.\nNext Obligation.\n  intros a b. destruct a,b; simpl.\n  - destruct (n =? n0)%nat eqn:Heq.\n    * constructor. now rewrite Nat.eqb_eq in *.\n    * constructor. now rewrite NPeano.Nat.eqb_neq in *.\n  - now constructor.\n  - now constructor.\n  - destruct (n =? n0)%nat eqn:Heq.\n    * constructor. now rewrite Nat.eqb_eq in *.\n    * constructor. now rewrite NPeano.Nat.eqb_neq in *.\nQed.\nNext Obligation.\n  intros ??. unfold base.Decision.\n  decide equality; apply Nat.eq_dec.\nQed.\nNext Obligation.\n  assert (cnat : countable.Countable (nat + nat)) by typeclasses eauto.\n  destruct cnat as [e d H].\n  unshelve econstructor.\n  * intros addr. destruct addr.\n    exact (e (inl n)).\n    exact (e (inr n)).\n  * intros i.\n    destruct (d i).\n    ** destruct s as [n | n].\n       exact (Some (ContractAddr_coq n)).\n       exact (Some (UserAddr_coq n)).\n    ** exact None.\n  * cbn; intros addr.\n    destruct addr;\n    now rewrite H.\nDefined.\nNext Obligation.\n  assert (snat : Serializable.Serializable (nat + nat)) by typeclasses eauto.\n  destruct snat as [s d H].\n  unshelve econstructor.\n  * intros addr. destruct addr.\n    exact (s (inl n)).\n    exact (s (inr n)).\n  * intros i.\n    destruct (d i) as [v | ].\n    ** destruct v as [n | n].\n       exact (Some (ContractAddr_coq n)).\n       exact (Some (UserAddr_coq n)).\n    ** exact None.\n  * cbn; intros addr.\n    destruct addr;\n      now rewrite H.\nDefined.\n\nDefinition init_wrapper {setup storage}\n           (init : SimpleCallCtx -> setup -> storage)\n           (ch : Chain)\n           (ctx : ContractCallContext) : setup -> storage :=\n  let simple_ctx :=\n      (Time_coq ch.(current_slot),\n       ((ctx.(ctx_from)),\n        ((ctx.(ctx_amount), ctx.(ctx_contract_balance))))) in\n    init simple_ctx.\n\n\n(** Our approximation for finite maps. We cannot use the one defined in the\n    Embedding.Prelude, because it cannot be made parametric wrt. the type of\n    keys doe to limitations of the embedding (types cannot be constants,\n    only inductives) *)\nModule Maps.\n  Open Scope nat.\n\n\n  MetaCoq Run\n          ( mp_ <- tmCurrentModPath tt ;;\n            let mp := (PCUICTranslate.string_of_modpath mp_ ++ \"@\")%string in\n            mkNames mp [\"addr_map\" ] \"_coq\").\n\n  Definition addr_map_acorn :=\n    [\\ data addr_map =\n          \"mnil\" [_]\n        | \"mcons\" [address, money, addr_map,_] \\].\n\n  MetaCoq Unquote Inductive (global_to_tc addr_map_acorn).\n\n  Definition Map := to_string_name <% addr_map_coq %>.\n\n  Fixpoint lookup_map (m : addr_map_coq) (key : address_coq) : option Z :=\n    match m with\n    | mnil => None\n    | mcons k v m' =>\n      if (eqb_addr key k) then Some v else lookup_map m' key\n    end.\n\n  (* Ported from FMapWeaklist of StdLib *)\n  Fixpoint add_map (k : address_coq) (x : Z) (s : addr_map_coq) : addr_map_coq :=\n  match s with\n   | mnil => mcons k x mnil\n   | mcons k' y l => if eqb_addr 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                              | Some _ => true\n                              | None => false\n                              end.\n\n  Lemma lookup_map_add k v m : lookup_map (add_map k v m) k = Some v.\n  Proof.\n    induction m.\n    + simpl. destruct k; simpl; now rewrite PeanoNat.Nat.eqb_refl.\n    + simpl. destruct (eqb_addr k a) eqn:Heq.\n      * destruct k; simpl; now rewrite PeanoNat.Nat.eqb_refl.\n      * simpl. now rewrite Heq.\n  Qed.\n\n  Fixpoint to_list (m : addr_map_coq) : list (address_coq * Z)%type :=\n    match m with\n    | mnil => nil\n    | mcons k v tl => cons (k,v) (to_list tl)\n    end.\n\n  Fixpoint of_list (l : list (address_coq * Z)) : addr_map_coq :=\n    match l with\n    | nil => mnil\n    | cons (k,v) tl => mcons k v (of_list tl)\n    end.\n\n  Lemma of_list_to_list m: of_list (to_list m) = m.\n  Proof. induction m; simpl; congruence. Qed.\n\n  Lemma to_list_of_list l: to_list (of_list l) = l.\n  Proof. induction l as [ | x l']; simpl; auto.\n         destruct x. simpl; congruence. Qed.\n\n  Fixpoint map_forallb (p : Z -> bool)(m : addr_map_coq) : bool :=\n    match m with\n    | mnil => true\n    | mcons k v m' => p v && map_forallb p m'\n    end.\n\n  Lemma map_forallb_lookup_map p m k v :\n    map_forallb p m = true ->\n    lookup_map m k = Some v ->\n    p v = true.\n  Proof.\n    revert k v p.\n    induction m; intros; try discriminate; simpl in *.\n    propify. destruct (eqb_addr _ _); auto.\n    * now inversion H0; subst.\n    * easy.\n  Qed.\n\n\n  (** Notations for functions on finite maps *)\n\n  Notation \"'MNil'\" := [| {eConstr Map \"mnil\"} |]\n                         (in custom expr at level 0).\n\n  Notation \"'mfind' a b\" := [| {eConst (to_string_name <% 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\n  Notation \"'madd' a b c\" := [| {eConst (to_string_name <% 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\n  Notation \"'mem' a b\" := [| {eConst (to_string_name <% 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\nEnd Maps.\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/embedding/extraction/PreludeExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17787909313926037}}
{"text": "Require Import CSet Util Filter Take MoreList OUnion AllInRel MapDefined MapUpdate Position.\nRequire Import IL Annotation LabelsDefined.\nRequire Import Liveness.Liveness TrueLiveness SimI.\nRequire Import RenamedApart.\nRequire Import SpillSound ReconstrLive DoSpill.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\nLemma agree_on_eq_oval (D:set var) (f g: var -> option val)\n  : agree_on _eq D f g\n    -> agree_on eq D f g.\nProof.\n  intros; hnf; intros.\n  eapply H in H0. inv H0; eauto; simpl in *; congruence.\nQed.\n\nLemma sim_write_moves D r L V s L' V' s' xl yl (Len:\u276cxl\u276d = \u276cyl\u276d)\n  : (forall (V'':onv val), agree_on eq D (V'[xl <-- lookup_list V' yl]) V''\n                        -> paco3 (sim_gen (S':=I.state)) r SimExt (L, V, s) (L', V'', s'))\n    -> defined_on (of_list yl) V'\n    -> disj (of_list xl) (of_list yl)\n    -> NoDupA _eq xl\n    -> paco3 (sim_gen (S':=I.state)) r SimExt (L, V, s)\n            (L', V', write_moves xl yl s').\nProof.\n  intros SIM Def Disj Uniq.\n  length_equify. general induction Len.\n  - simpl in *. eapply SIM; eauto.\n  - simpl in *; dcr; invt NoDupA.\n    edestruct Def; [cset_tac|].\n    pone_step_right; simpl. rewrite <- H.\n    eapply IHLen; intros; eauto using injective_on_incl.\n    eapply SIM.\n    + rewrite <- update_nodup_commute_eq; simpl; eauto with len.\n      erewrite lookup_list_agree; eauto.\n      symmetry. eapply agree_on_update_dead; eauto.\n      eapply disj_not_in.\n      eapply disj_incl; eauto with cset.\n    + rewrite H; eapply defined_on_update_some;\n        eauto using defined_on_incl with cset.\n    + eapply disj_incl; eauto with cset.\nQed.\n\nLemma sim_I_moves (slot : var -> var) k \u039b ZL r L L' V V' R M s sl RML\n  : spill_sound k ZL \u039b (R,M) s sl\n    -> injective_on (getSp sl \u222a getL sl) slot\n    -> disj (getSp sl \u222a getL sl) (map slot (getSp sl \u222a getL sl))\n    -> defined_on (getSp sl \u222a (map slot (getL sl) \\ map slot (getSp sl))) V'\n    -> (forall V'', agree_on eq (R \u222a map slot M \u222a map slot (getSp sl) \u222a getL sl)\n                       (V' [slot \u229d elements (getSp sl) <-- lookup_list V' (elements (getSp sl))]\n                           [elements (getL sl) <-- lookup_list (V'[slot \u229d elements (getSp sl) <-- lookup_list V' (elements (getSp sl))]) (slot \u229d elements (getL sl))]) V''\n              -> paco3 (sim_gen (S':=I.state)) r SimExt (L, V, s)\n                      (L', V'', do_spill slot s (setTopAnn sl ({}, {}, snd (getAnn sl))) ZL RML))\n    -> sim r SimExt (L, V, s) (L', V', do_spill slot s sl ZL RML).\nProof.\n  simpl. unfold sim. revert_except s.\n  intros ? ? ? ? ? ? ? ? ? ? ? ? ? SPS Inj Disj Def SIM.\n  rewrite do_spill_extract_writes.\n  exploit L_sub_SpM; eauto.\n  exploit Sp_sub_R; eauto.\n  eapply (@sim_write_moves (R \u222a map slot M \u222a map slot (getSp sl) \u222a map slot (getL sl)));\n    try rewrite ?of_list_map, of_list_elements; eauto. eauto with len.\n  intros ? Agr3.\n  eapply (@sim_write_moves (R \u222a map slot M \u222a map slot (getSp sl) \u222a getL sl)); try rewrite ?of_list_map, of_list_elements; eauto. eauto with len.\n  intros ? Agr4.\n  - rewrite update_with_list_agree in Agr4; eauto;\n      [| symmetry; eapply agree_on_incl; eauto; clear; rewrite of_list_elements; cset_tac\n       |eauto with len].\n    erewrite <- (lookup_list_agree) in Agr4.\n    eapply SIM; eauto.\n    rewrite of_list_map, of_list_elements; eauto.\n    eapply agree_on_incl; eauto with cset.\n  - eapply defined_on_agree_eq; eauto using agree_on_incl with cset.\n    rewrite (incl_union_minus _ _ (map slot (getSp sl))).\n    eapply defined_on_union.\n    + hnf; intros.\n      rewrite <- (of_list_elements _ (getSp sl)) in H1.\n      rewrite <- of_list_map in H1; eauto.\n      edestruct update_with_list_lookup_in_list; try eapply H1; dcr.\n      Focus 2. rewrite H5. inv_get. eapply get_elements_in in H3.\n      rewrite lookup_list_map in H4; inv_get.\n      eapply get_elements_in in H4.\n      eauto with cset.\n      eauto with len.\n    + hnf; intros.\n      rewrite lookup_set_update_not_in_Z; eauto.\n      eapply Def; eauto with cset.\n      rewrite of_list_map, of_list_elements; eauto.\n      revert H1; clear_all; cset_tac.\n  - eapply disj_incl; eauto with cset.\n  - eapply elements_3w.\n  - eauto using defined_on_incl with cset.\n  - symmetry.\n     eapply disj_incl; eauto with cset.\n  - eapply injective_nodup_map; eauto.\n    rewrite of_list_elements. eauto using injective_on_incl with cset.\n    eapply elements_3w.\nQed.\n\nInstance proper_onv (\u03f1:var -> option val)\n  : (@Proper (forall _ : var, option val)\n             (@respectful var (option val) (@_eq var (@SOT_as_OT var (@eq var) _))\n                          (@eq (option val))) \u03f1) | 0.\nProof.\n  intuition.\nQed.\n\nInstance proper_onv' (\u03f1:var -> option val)\n  : @Proper (forall _ : var, option val)\n            (@respectful var (option val) (@_eq var (@SOT_as_OT var (@eq var) _))\n                         (@_eq (option val) (@option_OrderedType val OrderedType_int))) \u03f1 | 0.\nProof.\n  intuition.\nQed.\n\nLemma load_agree_after_spill_load (slot : var -> var) (V V':var->option val) VD R M Sp L0\n      (Inj : injective_on VD slot)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n  : agree_on eq L0 V\n             (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                 [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           \u229d slot \u229d elements L0]).\nProof.\n  eapply agree_on_update_list; try eapply proper_onv; eauto with len.\n  rewrite of_list_elements. eapply agree_on_empty; eauto with cset.\n  rewrite !lookup_list_map. rewrite map_map. rewrite <- !lookup_list_map.\n  eapply lookup_list_agree. rewrite lookup_list_map.\n  rewrite of_list_elements.\n  etransitivity; [| eapply agree_on_eq_oval, agree_on_update_list_map];\n    [ | eauto with len | eapply proper_var | eapply proper_onv'\n      | eapply injective_on_incl; eauto; rewrite <- VDincl, of_list_elements; clear; cset_tac ].\n  rewrite (set_decomp Sp).\n  eapply agree_on_union.\n  ++ rewrite lookup_list_map.\n    etransitivity; [eapply agree_on_incl; [ eapply Agr1| rewrite <- SpR; clear; cset_tac]|].\n    eapply agree_on_update_list; [ eapply proper_onv | eauto with len |\n                                   | rewrite lookup_list_map; reflexivity ].\n    rewrite of_list_elements. eapply agree_on_empty; clear; cset_tac.\n  ++ rewrite lookup_list_map.\n    eapply agree_on_update_list_dead.\n    eapply agree_on_incl; eauto. rewrite LSpM. clear; cset_tac.\n    rewrite of_list_elements. hnf; intros; cset_tac.\nQed.\n\nLemma regs_untouched_after_spill_load (slot : var -> var) (V V' V'':var->option val) VD R M K Sp L0\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n      (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V')\n      (VDincl:Sp \u222a L0 [<=] VD)\n  :  agree_on eq ((R \\ K) \\ L0) V V''.\nProof.\n  etransitivity; [eapply agree_on_incl; [eapply Agr1| clear; cset_tac]|].\n  etransitivity; [|eapply agree_on_incl; [eapply Agr3| clear; cset_tac]].\n  eapply agree_on_update_list_dead.\n  eapply agree_on_update_list_dead. reflexivity.\n  rewrite of_list_map, of_list_elements; eauto.\n  symmetry. eapply disj_incl; eauto; only 2: eauto with cset.\n  rewrite <- Incl. clear; cset_tac.\n  rewrite of_list_elements. clear; hnf; intros; cset_tac.\nQed.\n\nLemma regs_agree_after_spill_load (slot : var -> var) (V V' V'':var -> option val) VD R M K Sp L0\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n      (Inj : injective_on VD slot) (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n  : agree_on eq (R \\ K \u222a L0) V V''.\nProof.\n  etransitivity; [|eapply agree_on_incl; [eapply Agr3| clear; cset_tac]].\n  rewrite union_comm, union_exclusive.\n  eapply agree_on_union.\n  -- eapply load_agree_after_spill_load; eauto.\n  -- eapply regs_untouched_after_spill_load; eauto.\n     reflexivity.\nQed.\n\nLemma spills_agree_after_spill_load (slot : var -> var) (V V' V'':var->option val) VD R M Sp L0\n      (Inj : injective_on VD slot) (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n  : agree_on eq Sp V (fun x : var => V'' (slot x)).\nProof.\n  eapply agree_on_comp; eauto; [ symmetry; eapply agree_on_incl; eauto; clear_all; cset_tac | ].\n  etransitivity; [eapply agree_on_incl; [eapply Agr1| eauto with cset]|].\n  eapply agree_on_update_list_dead_slot; eauto.\n  etransitivity; [| eapply agree_on_eq_oval, agree_on_update_list_map];\n    [ | eauto with len | eapply proper_var | eapply proper_onv'\n      | eapply injective_on_incl; eauto; rewrite <- VDincl, of_list_elements;\n        clear; cset_tac ].\n  eapply agree_on_update_list; [ eapply proper_onv | eauto with len |\n                                 | rewrite lookup_list_map; reflexivity ].\n  eapply agree_on_empty. rewrite of_list_elements. cset_tac.\n  eapply disj_incl; eauto with cset.\n  rewrite of_list_elements, <- Incl, LSpM, <- SpR; reflexivity.\nQed.\n\nLemma mem_untouched_after_spill_load (slot : var -> var) (V V' V'':var->option val) VD R M Sp L0\n      (Inj : injective_on VD slot) (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n  : agree_on eq (M \\ Sp) V (fun x : var => V'' (slot x)).\nProof.\n  etransitivity; [eapply agree_on_incl; [eapply Agr2| eauto with cset ]|].\n  eapply agree_on_comp_both; eauto using proper_onv.\n  etransitivity; [| eapply agree_on_incl; [eapply Agr3| eauto]].\n  - eapply agree_on_update_list_dead.\n    eapply agree_on_update_list_dead. reflexivity.\n    rewrite of_list_map, of_list_elements; eauto.\n    intros.\n    eapply injective_disj; eauto.\n    hnf; intros; cset_tac.\n    eapply injective_on_incl; eauto. rewrite <- Incl. rewrite SpR at 1.\n    cset_tac.\n    rewrite of_list_elements.\n    eapply disj_incl; eauto.\n    rewrite <- Incl, LSpM, <- SpR. eauto. eauto with cset.\n  - rewrite minus_incl. clear. cset_tac.\nQed.\n\nLemma mem_agrees_after_spill_load (slot : var -> var) (V V' V'':var->option val) VD R M Sp L0\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n      (Inj : injective_on VD slot) (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n  : agree_on eq (Sp \u222a M) V (fun x : var => V'' (slot x)).\nProof.\n  rewrite union_exclusive.\n  eapply agree_on_union.\n  -- eapply spills_agree_after_spill_load; try eapply Agr3; eauto.\n  -- eapply mem_untouched_after_spill_load; try eapply Agr3; eauto.\nQed.\n\n\nLemma mem_agrees_after_spill_load_update (slot : var -> var) (V V' V'':var->option val) VD R M Sp L0 x v\n      (Agr5 : agree_on eq (Sp \u222a M) V (fun x : var => V'' (slot x)))\n      (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD) (NotIn: x \u2209 Sp \u222a M)\n      (xIn:x \u2208 VD)\n      (Agr1 : agree_on eq R V V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n  : agree_on eq (Sp \u222a M) (V [x <- \u23a3 v \u23a6]) (fun x0 : var => (V'' [x <- \u23a3 v \u23a6]) (slot x0)).\nProof.\n  eapply agree_on_update_dead_both_comp_right; eauto.\n  eapply disj_incl; eauto. rewrite SpR, Incl. revert xIn; clear. cset_tac.\n  rewrite SpR, Incl. cset_tac.\nQed.\n\nLemma RKL_incl X `{OrderedType X} (R K L D D':set X)\n  :  R \\ K \u222a L \u2286 R \u222a D \u222a D' \u222a L.\nProof.\n  cset_tac.\nQed.\n\nHint Resolve RKL_incl | 0: cset.\n\nLemma defined_on_after_spill_load (slot : var -> var) (V V' V'':var->option val) VD R M Sp L0  K\n      (Agr5 : agree_on eq (Sp \u222a M) V (fun x : var => V'' (slot x)))\n      (Disj : disj VD (map slot VD)) (Incl : R \u222a M [<=] VD)\n      (Agr1 : agree_on eq R V V') (Def : defined_on (R \u222a map slot M) V')\n      (Agr2 : agree_on eq M V (fun x : var => V' (slot x)))\n      (VDincl:Sp \u222a L0 [<=] VD) (SpR:Sp [<=] R) (LSpM:L0 [<=] Sp \u222a M)\n      (Agr3 : agree_on eq (R \u222a map slot M \u222a map slot Sp \u222a L0)\n                       (V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                           [elements L0 <-- V' [slot \u229d elements Sp <-- V' \u229d elements Sp]\n                                     \u229d slot \u229d elements L0]) V'')\n  : defined_on (R \\ K \u222a L0 \u222a map slot (Sp \u222a M)) V''.\nProof.\n  assert (defined_on Sp V') as DefSp by eauto using defined_on_incl with cset.\n  rewrite union_exclusive.\n  eapply defined_on_union.\n  -- eapply defined_on_agree_eq; [|eapply agree_on_incl;[eapply Agr3|eauto with cset]].\n     rewrite union_comm, union_exclusive. eapply defined_on_union.\n     ++ eapply defined_on_update_list'; eauto with len.\n       rewrite of_list_elements. clear; hnf; intros; cset_tac.\n       eapply defined_on_defined. clear; intuition.\n       rewrite of_list_map, of_list_elements; eauto.\n       eapply defined_on_update_list'; eauto with len.\n       rewrite of_list_map, of_list_elements; eauto.\n       rewrite LSpM. eapply (defined_on_incl Def); eauto.\n       rewrite map_union; eauto. clear; cset_tac.\n       eapply defined_on_defined. clear; intuition. eauto.\n       rewrite of_list_elements. eauto.\n     ++ eapply defined_on_agree_eq; [| eapply agree_on_update_list_dead; try reflexivity].\n       eapply defined_on_update_list'; eauto with len.\n       rewrite of_list_map, of_list_elements; eauto.\n       eapply (defined_on_incl Def). clear; cset_tac.\n       eapply defined_on_defined. clear; intuition. eauto.\n       rewrite of_list_elements. eauto.\n       rewrite of_list_elements. eauto. clear; hnf; intros; cset_tac.\n  -- rewrite map_union; eauto.\n     eapply defined_on_agree_eq; [ | eapply agree_on_incl; [ eapply Agr3| clear; cset_tac]];\n       eauto.\n     eapply defined_on_agree_eq; [| eapply agree_on_update_list_dead; try reflexivity].\n     eapply defined_on_update_list'; eauto with len.\n     rewrite of_list_map, of_list_elements; eauto.\n     eapply (defined_on_incl Def). clear; cset_tac.\n     eapply defined_on_defined. clear; intuition. eauto.\n     rewrite of_list_elements. eauto.\n     rewrite of_list_elements. clear; hnf; intros; 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/SpillMovesAgree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17775843308769568}}
{"text": "From mathcomp.ssreflect Require Import ssreflect seq ssrbool.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.AST.     (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Integers.\n\nRequire Import msl.Axioms.\nRequire Import Coq.ZArith.ZArith.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.event_semantics.\nRequire Export concurrency.semantics.\nRequire Import concurrency.threadPool. Export threadPool.\n\nRequire Import concurrency.machine_semantics.\nRequire Import concurrency.permissions.\nRequire Import concurrency.bounded_maps.\nRequire Import concurrency.addressFiniteMap.\n\nRequire Import concurrency.scheduler.\nRequire Import Coq.Program.Program.\n\nRequire Import concurrency.safety.\n\nRequire Import concurrency.coinductive_safety.\n\n\n\nNotation EXIT :=\n  (EF_external \"EXIT\" (mksignature (AST.Tint::nil) None)).\n\nNotation CREATE_SIG := (mksignature (AST.Tint::AST.Tint::nil) None cc_default).\nNotation CREATE := (EF_external \"spawn\" CREATE_SIG).\n\nNotation READ :=\n  (EF_external \"READ\"\n               (mksignature (AST.Tint::AST.Tint::AST.Tint::nil) (Some AST.Tint) cc_default)).\nNotation WRITE :=\n  (EF_external \"WRITE\"\n               (mksignature (AST.Tint::AST.Tint::AST.Tint::nil) (Some AST.Tint) cc_default)).\n\nNotation MKLOCK :=\n  (EF_external \"makelock\" (mksignature (AST.Tint::nil) None cc_default)).\nNotation FREE_LOCK :=\n  (EF_external \"freelock\" (mksignature (AST.Tint::nil) None cc_default)).\n\nNotation LOCK_SIG := (mksignature (AST.Tint::nil) None cc_default).\nNotation LOCK := (EF_external \"acquire\" LOCK_SIG).\nNotation UNLOCK_SIG := (mksignature (AST.Tint::nil) None cc_default).\nNotation UNLOCK := (EF_external \"release\" UNLOCK_SIG).\n\nModule Type EventSig.\n  Declare Module TID: ThreadID.\n  Import TID.\n\n  Definition evRes := (access_map * access_map)%type.\n  Definition evDelta := (delta_map * delta_map)%type.\n\n  Inductive sync_event : Type :=\n  | release : address (*-> option (evRes * evDelta)*) -> option evRes -> sync_event\n  | acquire : address (*-> option (evRextes * evDelta)*) -> option evDelta -> sync_event\n  | mklock :  address -> sync_event\n  | freelock : address -> sync_event\n  | spawn : address -> option (evRes * evDelta) -> option evDelta -> sync_event\n  | failacq: address -> sync_event.\n\n  Inductive machine_event : Type :=\n  | internal: TID.tid -> mem_event -> machine_event\n  | external : TID.tid -> sync_event -> machine_event.\n\nEnd EventSig.\n\n\nModule Type ConcurrentMachineSig.\n  Declare Module ThreadPool: ThreadPoolSig.\n  Declare Module Events: EventSig.\n  Import ThreadPool.\n  Import Events.\n  Import SEM.\n\n  Notation thread_pool := ThreadPool.t.\n  (** Memories*)\n  Parameter richMem: Type.\n  Parameter dryMem: richMem -> mem.\n  Parameter diluteMem : mem -> mem.\n\n  (** Environment and Threadwise semantics *)\n  (** These values come from SEM *)\n\n  (** The thread pool respects the memory*)\n  Parameter mem_compatible: thread_pool -> mem -> Prop.\n  Parameter invariant: thread_pool -> Prop.\n\n  (** Step relations *)\n  Parameter threadStep:\n    G -> forall {tid0 ms m},\n      containsThread ms tid0 -> mem_compatible ms m ->\n      thread_pool -> mem -> seq mem_event -> Prop.\n  Axiom threadStep_equal_run:\n    forall g i tp m cnt cmpt tp' m' tr,\n      @threadStep g i tp m cnt cmpt tp' m' tr ->\n      forall j,\n        (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n        (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n  Parameter syncStep:\n    bool -> (* if it's a Coarse machine. Temp solution to propagating changes. *)\n    G -> forall {tid0 ms m},\n      containsThread ms tid0 -> mem_compatible ms m ->\n      thread_pool -> mem -> sync_event -> Prop.\n\n  Axiom syncstep_equal_run:\n    forall b g i tp m cnt cmpt tp' m' tr,\n      @syncStep b g i tp m cnt cmpt tp' m' tr ->\n      forall j,\n        (exists cntj q, @getThreadC j tp cntj = Krun q) <->\n        (exists cntj' q', @getThreadC j tp' cntj' = Krun q').\n\n  Axiom syncstep_not_running:\n    forall b g i tp m cnt cmpt tp' m' tr,\n      @syncStep b g i tp m cnt cmpt tp' m' tr ->\n      forall cntj q, ~ @getThreadC i tp cntj = Krun q.\n\n  Parameter threadHalted:\n    forall {tid0 ms},\n      containsThread ms tid0 -> Prop.\n\n  Axiom threadHalt_update:\n    forall i j, i <> j ->\n      forall tp cnt cnti c' cnt',\n        (@threadHalted j tp cnt) <->\n        (@threadHalted j (@updThreadC i tp cnti c') cnt') .\n\n  Axiom syncstep_equal_halted:\n    forall b g i tp m cnti cmpt tp' m' tr,\n      @syncStep b g i tp m cnti cmpt tp' m' tr ->\n      forall j cnt cnt',\n        (@threadHalted j tp cnt) <->\n        (@threadHalted j tp' cnt').\n\n  Axiom threadStep_not_unhalts:\n    forall g i tp m cnt cmpt tp' m' tr,\n      @threadStep g i tp m cnt cmpt tp' m' tr ->\n      forall j cnt cnt',\n        (@threadHalted j tp cnt) ->\n        (@threadHalted j tp' cnt') .\n\n\n  (*Parameter initial_machine: C -> thread_pool.*)\n\n  Parameter init_mach : option RES.res  -> G -> val -> list val -> option thread_pool.\n\nEnd ConcurrentMachineSig.\n\n\nModule Type ConcurrentMachine.\n  Declare Module SCH: Scheduler.\n  Declare Module TP: ThreadPoolSig.\n  Declare Module SIG: ConcurrentMachineSig with Module ThreadPool:= TP.\n\n  Import SCH.\n  Import TP.\n  Import SIG.Events.\n\n  Notation event_trace := (seq machine_event).\n\n  Definition MachState : Type:= (schedule * event_trace * t)%type.\n\n  Parameter MachineSemantics: schedule -> option RES.res ->\n                              CoreSemantics SIG.ThreadPool.SEM.G MachState mem.\n\n  Axiom initial_schedule: forall genv main vals U U' p c tr,\n      initial_core (MachineSemantics U p) genv main vals = Some (U',tr,c) ->\n      U' = U /\\ tr = nil.\nEnd ConcurrentMachine.\n\nModule CoarseMachine (SCH:Scheduler)(SIG : ConcurrentMachineSig with Module ThreadPool.TID:=SCH.TID with Module Events.TID :=SCH.TID) <: ConcurrentMachine with Module SCH:= SCH with Module TP:= SIG.ThreadPool  with Module SIG:= SIG.\n  Module SCH:=SCH.\n  Module TP:=SIG.ThreadPool.\n  Module SIG:=SIG.\n  Import SCH SIG TID ThreadPool ThreadPool.SEM Events.\n\n  Notation Sch:=schedule.\n  Notation machine_state := ThreadPool.t.\n\n  Notation event_trace := (seq machine_event).\n\n  (** Resume and Suspend: threads running must be preceded by a Resume\n     and followed by Suspend.  This functions wrap the state to\n     indicate it's ready to take a syncronisation step or resume\n     running. (This keeps the invariant that at most one thread is not\n     at_external) *)\n\n  Inductive start_thread' genv: forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | StartThread: forall tid0 ms ms' c_new vf arg\n                    (ctn: containsThread ms tid0)\n                    (Hcode: getThreadC ctn = Kinit vf arg)\n                    (Hinitial: initial_core Sem genv vf (arg::nil) = Some c_new)\n                    (Hinv: invariant ms)\n                    (Hms': updThreadC ctn (Krun c_new)  = ms'),\n      start_thread' genv ctn ms'.\n  Definition start_thread genv: forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @start_thread' genv.\n  Inductive resume_thread': forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | ResumeThread: forall tid0 ms ms' c c' X\n                    (ctn: containsThread ms tid0)\n                    (Hat_external: at_external Sem c = Some X)\n                    (Hafter_external: after_external Sem None c = Some c')\n                    (Hcode: getThreadC ctn = Kresume c Vundef)\n                    (Hinv: invariant ms)\n                    (Hms': updThreadC ctn (Krun c')  = ms'),\n      resume_thread' ctn ms'.\n  Definition resume_thread: forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @resume_thread'.\n\n  Inductive suspend_thread': forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | SuspendThread: forall tid0 ms ms' c X\n                     (ctn: containsThread ms tid0)\n                     (Hcode: getThreadC ctn = Krun c)\n                     (Hat_external: at_external Sem c = Some X)\n                     (Hinv: invariant ms)\n                     (Hms': updThreadC ctn (Kblocked c) = ms'),\n      suspend_thread' ctn ms'.\n  Definition suspend_thread : forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @suspend_thread'.\n\n  Inductive machine_step {genv:G}:\n    Sch -> event_trace -> machine_state -> mem -> Sch ->\n    event_trace -> machine_state -> mem -> Prop :=\n  | start_step:\n      forall tid U ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: start_thread genv Htid ms'),\n        machine_step U [::] ms m U [::] ms' m\n  | resume_step:\n      forall tid U ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: resume_thread Htid ms'),\n        machine_step U [::] ms m U [::] ms' m\n  | thread_step:\n      forall tid U ms ms' m m' ev\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: threadStep genv Htid Hcmpt ms' m' ev),\n        machine_step U [::] ms m U [::] ms' m'\n  | suspend_step:\n      forall tid U U' ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep:suspend_thread Htid ms'),\n        machine_step U [::] ms m U' [::] ms' m\n  | sync_step:\n      forall tid U U' ms ms' m m' ev\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: syncStep true genv Htid Hcmpt ms' m' ev),\n        machine_step U [::] ms m  U' [::] ms' m'\n  | halted_step:\n      forall tid U U' ms m\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Hinv: invariant ms)\n        (Hhalted: threadHalted Htid),\n        machine_step U [::] ms m  U' [::] ms m\n  | schedfail :\n      forall tid U U' ms m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: ~ containsThread ms tid)\n        (Hinv: invariant ms)\n        (HschedS: schedSkip U = U'),        (*Schedule Forward*)\n        machine_step U [::] ms m U' [::] ms m.\n\n  (*Lemma to deal with the trivial trace*)\n  Lemma trace_nil: forall ge U tr st m U' tr' st' m',\n      @machine_step ge U tr st m U' tr' st' m' ->\n  tr = nil /\\ tr' = nil.\n  Proof. move=> ge U tr st m U' tr' st' m' ms; inversion ms; intuition. Qed.\n\n  (*The new semantics bellow makes internal (thread) and external (machine) steps explicit*)\n  Inductive internal_step {genv:G}:\n    Sch -> machine_state -> mem -> machine_state -> mem -> Prop :=\n  | thread_step':\n      forall tid U ms ms' m m' ev\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: threadStep genv Htid Hcmpt ms' m' ev),\n        internal_step U ms m ms' m'.\n\n  Inductive external_step  {genv:G}:\n    Sch -> event_trace -> machine_state -> mem -> Sch ->\n    event_trace -> machine_state -> mem -> Prop :=\n  | start_state': forall tid U ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: start_thread genv Htid ms'),\n        external_step U [::] ms m U [::] ms' m\n  | resume_step':\n      forall tid U ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: resume_thread Htid ms'),\n        external_step U [::] ms m U [::] ms' m\n  | suspend_step':\n      forall tid U U' ms ms' m\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep:suspend_thread Htid ms'),\n        external_step U [::] ms m U' [::] ms' m\n  | sync_step':\n      forall tid U U' ms ms' m m' ev\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: syncStep true genv Htid Hcmpt ms' m' ev),\n        external_step U [::] ms m  U' [::] ms' m'\n  | halted_step':\n      forall tid U U' ms m\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Hinv: invariant ms)\n        (Hhalted: threadHalted Htid),\n        external_step U [::] ms m  U' [::] ms m\n  | schedfail':\n      forall tid U U' ms m\n        (HschedN: schedPeek U = Some tid)\n        (Htid: ~ containsThread ms tid)\n        (Hinv: invariant ms)\n        (HschedS: schedSkip U = U'),        (*Schedule Forward*)\n        external_step U [::] ms m U' [::] ms m.\n  (*Symmetry*)\n  (* These steps are basically the same: *)\n  Lemma step_equivalence1: forall ge U tr st m U' tr' st' m',\n    @machine_step ge U tr st m U' tr' st' m' ->\n    (U=U' /\\ tr = tr' /\\  @internal_step ge U st m st' m') \\/\n    @external_step ge U tr st m U' nil st' m'.\n  Proof.\n    move=> ge U tr st m U' tr' st' m' ms.\n    inversion ms;\n      first[ solve [ left; repeat split=>//; econstructor; eauto] |\n             solve[right; econstructor; eauto]].\n  Qed.\n  Lemma step_equivalence2: forall ge U st m st' m',\n      @internal_step ge U st m st' m' ->\n      @machine_step ge U nil st m U nil st' m'.\n  Proof. move=>  ge U st m st' m' istp.\n         by inversion istp; econstructor; eauto.\n  Qed.\n   Lemma step_equivalence3: forall ge U tr st m U' tr' st' m',\n      @external_step ge U tr st m U' tr' st' m' ->\n      @machine_step ge U tr st m U' tr' st' m'.\n   Proof. move=>  ge U tr st m U' nil st' m' estp.\n          inversion estp;\n          [\n              solve[econstructor 1 ; eauto]|\n              solve[econstructor 2 ; eauto]|\n              solve[econstructor 4 ; eauto]|\n              solve[econstructor 5 ; eauto]|\n              solve[econstructor 6 ; eauto]|\n              solve[econstructor 7 ; eauto]].\n   Qed.\n\n  Definition MachState: Type := (Sch * event_trace * machine_state)%type.\n\n  Definition MachStep G (c:MachState) (m:mem)\n             (c' :MachState) (m':mem) :=\n    @machine_step G (fst (fst c)) (snd (fst c)) (snd c)  m\n                  (fst (fst c')) (snd (fst c')) (snd c')  m'.\n\n  Definition at_external (st : MachState)\n    : option (external_function * list val) := None.\n\n  Definition after_external (ov : option val) (st : MachState) :\n    option (MachState) := None.\n\n  (*not clear what the value of halted should be*)\n  (*Nick: IMO, the machine should be halted when the schedule is empty.\n            The value is probably unimportant? *)\n  (*Santiago: I belive empty schedule should \"diverge\". After all that's *)\n  Definition halted (st : MachState) : option val :=\n    match schedPeek (fst (fst st)) with\n    | Some _ => None\n    | _ => Some Vundef\n    end.\n\n  (*Lemma halted_al_schedules: forall st,\n      halted st ->*)\n\n\n  Definition init_machine (U:schedule) (r : option RES.res) the_ge\n             (f : val) (args : list val)\n    : option MachState :=\n    match init_mach r the_ge f args with\n    | None => None\n    | Some c => Some (U, [::], c)\n    end.\n\n  Program Definition MachineSemantics (U:schedule) (r : option RES.res):\n    CoreSemantics G MachState mem.\n  intros.\n  apply (@Build_CoreSemantics _ MachState _\n                              (init_machine U r)\n                              at_external\n                              after_external\n                              halted\n                              MachStep\n        );\n    unfold at_external, halted; try reflexivity.\n  intros. inversion H; subst; rewrite HschedN; reflexivity.\n  auto.\n  Defined.\n\n  Definition init_machine' (r : option RES.res) the_ge\n             (f : val) (args : list val)\n    : option (machine_state) :=\n    match init_mach r the_ge f args with\n    | None => None\n    | Some c => Some (c)\n    end.\n\n  (*This is not used anymore:\n   * find_thread\n   * running_thread *)\n  Definition find_runnin (c:@ctl C): bool :=\n    match c with\n    | Krun _ => true\n    | _ => false\n    end.\n  Definition running_thread: machine_state -> option tid:=\n    fun st => find_thread st find_runnin.\n\n    Definition unique_Krun tp i :=\n     forall j cnti q,\n       @getThreadC j tp cnti = Krun q ->\n       ~ @threadHalted j tp cnti  ->\n       eq_tid_dec i j.\n\n\n  Program Definition new_MachineSemantics (U:schedule) (r : option RES.res):\n    @ConcurSemantics G tid schedule event_trace machine_state mem.\n  apply (@Build_ConcurSemantics _ tid schedule event_trace  machine_state _\n                              (init_machine' r)\n                              (fun U st => halted (U, nil, st))\n                              (fun ge U st m st' m' =>\n                                 @internal_step ge U st m\n                                                st' m'\n                              )\n                              (fun ge U (tr:event_trace) st m U' tr' st' m' =>\n                                 @external_step ge U tr st m\n                                                U' tr' st' m'\n                              )\n                              unique_Krun\n                              (*fun A => running_thread A*))\n         ;\n    unfold at_external, halted; try reflexivity.\n  - intros. inversion H; subst; rewrite HschedN; reflexivity.\n  - intros. inversion H; subst; rewrite HschedN; reflexivity.\n  Defined.\n\n(*\n  Definition MachineSemantics:= MachineSemantics'.*)\n  Lemma initial_schedule: forall genv main vals U U' p c tr,\n      initial_core (MachineSemantics U p) genv main vals = Some (U',tr,c) ->\n      U' = U /\\ tr = nil.\n        simpl. unfold init_machine. intros.\n        destruct (init_mach p genv main vals); try solve[inversion H].\n        inversion H; subst; split; auto.\n  Qed.\n\n  Lemma corestep_empty_trace: forall genv U tr tr' c m c' m' U',\n      MachStep genv (U,tr,c) m (U', tr', c') m' ->\n      tr = nil /\\ tr' = nil.\n  Proof.\n    intros.\n    inversion H; subst; simpl in *; auto.\n  Qed.\n\n  (** Schedule safety of the coarse-grained machine*)\n  Inductive csafe (ge : G) (st : MachState) (m : mem) : nat -> Prop :=\n  | Safe_0: csafe ge st m 0\n  | HaltedSafe: forall n, halted st -> csafe ge st m n\n  | CoreSafe : forall tp' m' n\n                 (Hstep: MachStep ge st m (fst (fst st),[::],tp') m')\n                 (Hsafe: csafe ge (fst (fst st),[::],tp') m' n),\n      csafe ge st m (S n)\n  | AngelSafe: forall tp' m' n\n                 (Hstep: MachStep ge st m (schedSkip (fst (fst st)),[::],tp') m')\n                 (Hsafe: forall U'', csafe ge (U'',[::],tp') m' n),\n      csafe ge st m (S n).\n\n  Section new_safety.\n  (** *I create a new type of safety that satisfies (forall n, safeN) -> safe and is preserved by simulations. *)\n\n    Inductive sem_with_halt ge: MachState -> mem -> MachState -> mem -> Prop:=\n    | halt_with_step st m: halted st -> sem_with_halt ge st m st m\n    | step_with_halt st m st' m' : MachStep ge st m st' m' -> sem_with_halt ge st m st' m'.\n\n  Definition new_state: Type:= seq machine_event * machine_state * mem.\n  Definition mk_nstate (st:MachState) m:new_state:= (snd (fst st), snd st, m).\n  Definition mk_ostate (st:new_state) U :MachState:= (U, fst (fst st), snd (fst st)).\n  Definition new_step ge (st: new_state) U st' U': Prop:=\n    sem_with_halt ge (mk_ostate st U) (snd st) (mk_ostate st' U') (snd st').\n\n  (*Definition valid (st: MachState): Prop:=\n    match (running_thread (snd st)), (schedPeek (fst (fst st))) with\n    | _, None => True\n    | None, _ => True\n    | Some a, Some b => eq_tid_dec a b (* || containsThread_dec b (snd st) *)\n    end.*)\n\n  Section valid_schedule.\n\n    Definition is_running tp i:=\n      exists cnti q, @getThreadC i tp cnti = Krun q /\\ ~ @threadHalted i tp cnti.\n\n    Lemma unique_runing_not_running:\n      forall tp i,\n        unique_Krun tp i ->\n        is_running tp i \\/\n        forall j, unique_Krun tp j.\n    Proof.\n      unfold unique_Krun, is_running.\n      intros.\n      destruct (Classical_Prop.classic\n                  (exists (cnti : containsThread tp i) (q : C),\n                      getThreadC cnti = Krun q /\\ ~ threadHalted cnti))\n        as [[cnti [q [KRUN Not_HALTED]]] | NO]; [left|right].\n      + exists cnti, q; auto.\n      + intros j j0 cnti q KRUN NOT_HALTED.\n        specialize (H _ _ _ KRUN NOT_HALTED).\n        destruct (eq_tid_dec i j0); try solve[inversion H].\n        subst i.\n        exfalso; apply NO.\n        exists cnti, q; split; assumption.\n    Qed.\n\n    Corollary unique_runing_not_running':\n      forall tp i,\n        unique_Krun tp i ->\n        ~ is_running tp i ->\n        forall j, unique_Krun tp j.\n    Proof.\n      intros. destruct (unique_runing_not_running _ _ H).\n      - contradict H0; assumption.\n      - apply H1.\n    Qed.\n\n  Lemma no_running_one_running:\n    forall tp,\n      (forall j, unique_Krun tp j) ->\n      forall i cnti c, unique_Krun (@updThreadC i tp cnti (Krun c)) i.\n  Proof.\n    unfold unique_Krun.\n    intros.\n    destruct (eq_tid_dec i j); auto; exfalso; eapply n.\n    erewrite <- (gsoThreadCC _ (cntUpdateC' cnti0)) in H0; auto.\n    eapply H with (j:=i) in H0.\n    destruct (eq_tid_dec i j); inversion H0; assumption.\n    intros HH; apply H1.\n    eapply threadHalt_update in HH; eauto.\n    Grab Existential Variables.\n    assumption.\n  Qed.\n  Lemma one_running_no_running:\n    forall tp i,\n      (unique_Krun tp i) ->\n      forall j cnti c, unique_Krun (@updThreadC i tp cnti (Kblocked c)) j.\n  Proof.\n    unfold unique_Krun.\n    intros.\n    destruct (eq_tid_dec i j0).\n    - subst i.\n      rewrite (gssThreadCC cnti0) in H0; inversion H0.\n    - rewrite <- (gsoThreadCC n (cntUpdateC' cnti0)) in H0.\n      eapply H with (j:=j0) in H0.\n      exfalso; apply n;\n      destruct (eq_tid_dec i j0); auto; inversion H0.\n      intros HH; apply H1.\n      eapply threadHalt_update in HH; eauto.\n  Qed.\n\n  Lemma no_running_no_running:\n    forall tp,\n      (forall h, unique_Krun tp h ) ->\n      forall i j cnti c, unique_Krun (@updThreadC i tp cnti (Kblocked c)) j.\n  Proof.\n    unfold unique_Krun.\n    intros.\n    destruct (eq_tid_dec i j0).\n    - subst i.\n      rewrite (gssThreadCC cnti0) in H0; inversion H0.\n    - rewrite <- (gsoThreadCC n (cntUpdateC' cnti0)) in H0.\n      eapply H with (j:=j0) in H0.\n      eassumption.\n      intros HH; apply H1.\n      eapply threadHalt_update in HH; eauto.\n  Qed.\n\n  End valid_schedule.\n\n  Definition correct_schedule(st: MachState): Prop:=\n    match schedPeek (fst (fst st)) with\n    | Some i => unique_Krun (snd st) i\n    | None => True\n    end.\n\n  Definition valid (st: MachState): Prop:=\n    correct_schedule st.\n\n  Definition bounded_mem (m: mem) := bounded_maps.bounded_map (snd (getMaxPerm m)) .\n\n  Definition new_valid st U := correct_schedule (mk_ostate st U).\n  Definition new_valid_bound st U :=\n    correct_schedule (mk_ostate st U) /\\ bounded_mem (snd st).\n  Definition ksafe_new_step (ge : G) (st : MachState) (m : mem) : nat -> Prop :=\n    ksafe _ _ (new_step ge) new_valid (mk_nstate st m) (fst (fst st)).\n  Definition safe_new_step (ge : G) (st : MachState) (m : mem) : Prop :=\n    safe _ _ (new_step ge) new_valid (mk_nstate st m) (fst (fst st)).\n  Definition safe_new_step_bound (ge : G) (st : MachState) (m : mem) : Prop :=\n    safe _ _ (new_step ge) new_valid_bound (mk_nstate st m) (fst (fst st)).\n\n  (*Things that we must prove:*)\n  Lemma sch_dec': forall (U U': Sch), {U = U'} + {U <> U'}.\n  Proof. apply SCH.sch_dec. Qed.\n  Lemma step_sch: forall {ge U tr tp m U' tr' tp' m'}, MachStep ge (U, tr, tp) m (U', tr', tp') m' -> U=U' \\/ schedSkip(U)=U'.\n  Proof.\n    intros.\n    inversion H;\n      simpl in *;\n      subst; first[left; reflexivity | right; reflexivity | idtac].\n  Qed.\n  Lemma step_trace: forall {ge U tr tp m U' tr' tp' m'}, MachStep ge (U, tr, tp) m (U', tr', tp') m' -> nil = tr'.\n  Proof.\n    intros.\n    inversion H;\n      simpl in *; auto.\n  Qed.\n  (*Most cases in this proof are similar. Should automate!*)\n  Lemma step_sch_correct: forall {ge st m st' m'}, MachStep ge st m st' m'  -> correct_schedule st -> correct_schedule st'.\n  Proof.\n    unfold correct_schedule in *.\n    intros.\n    destruct st as [[a b] c]; destruct st' as [[a' b' ] c'].\n    inversion H; subst; simpl in *.\n    - inversion Htstep; subst.\n      rewrite HschedN in H0; rewrite HschedN.\n      eapply no_running_one_running.\n      destruct (unique_runing_not_running _ _ H0) as [HH | HH]; auto.\n      destruct HH as [cnt' [c' [KRUN NOT_HALTED]]].\n      pose (@gLockSetCode tid0 c).\n      replace cnt' with ctn in KRUN.\n      + rewrite Hcode in KRUN; inversion KRUN.\n      + eapply msl.Axioms.proof_irr.\n    - inversion Htstep; subst.\n      rewrite HschedN in H0; rewrite HschedN.\n      eapply no_running_one_running.\n      destruct (unique_runing_not_running _ _ H0) as [HH | HH]; auto.\n      destruct HH as [cnt' [c' [KRUN NOT_HALTED]]].\n      pose (@gLockSetCode tid0 c).\n      replace cnt' with ctn in KRUN.\n      + rewrite Hcode in KRUN; inversion KRUN.\n      + eapply msl.Axioms.proof_irr.\n    - subst.\n      destruct (schedPeek a'); auto.\n      intros j cntj q j_runs j_not_halted.\n      inversion HschedN; subst tid0.\n      assert (Htstep':=Htstep).\n      apply threadStep_equal_run with (j:=j) in Htstep.\n      assert (HH: exists (cntj : containsThread c' j) (q : C),\n              getThreadC cntj = Krun q).\n      { exists cntj, q; auto. }\n      apply Htstep in HH; destruct HH as [cnt [q0 j_runs0]].\n      eapply H0; eauto.\n      intros HH; apply j_not_halted;\n      eapply threadStep_not_unhalts; eauto.\n    - destruct (schedPeek a') eqn:SCH'; auto.\n      rewrite HschedN in H0.\n      inversion Htstep; subst.\n      eapply one_running_no_running in H0.\n      destruct (unique_runing_not_running _ _ H0) as [HH | HH]; auto.\n      destruct HH as [cnt' [c' [KRUN NOT_HALTED]]].\n      erewrite gssThreadCC in KRUN. inversion KRUN.\n    - subst.\n      rewrite HschedN in H0.\n      destruct (schedPeek (schedSkip a)) eqn:AAA; auto.\n      unfold unique_Krun in H0.\n      intros j cntj q j_runs j_not_halted.\n\n      assert (Htstep':=Htstep).\n      eapply syncstep_equal_run in Htstep'.\n      assert (HH: exists (cntj : containsThread c' j) (q : C),\n                 getThreadC cntj = Krun q).\n      { exists cntj, q; auto. }\n      apply Htstep' in HH; destruct HH as [cnt [q0 j_runs0]].\n\n      destruct (eq_tid_dec tid0 j); subst.\n      + exfalso; eapply\n                 (syncstep_not_running _ _ _ _ _ _ _ _ _ _ Htstep).\n        eapply j_runs0.\n      + destruct (Classical_Prop.classic (threadHalted cnt)) as [halt | n_halt].\n        * exfalso; apply j_not_halted.\n          eapply (syncstep_equal_halted ) in Htstep; eauto.\n          eapply Htstep; eassumption.\n        * eapply H0 in j_runs0; eauto.\n          exfalso; apply n; destruct (eq_tid_dec tid0 j); auto; inversion j_runs0.\n    - destruct (schedPeek a') eqn:SCH'; auto.\n      rewrite HschedN in H0.\n      subst c'.\n      destruct (unique_runing_not_running _ _ H0) as [HH | HH]; auto.\n      intros j cnti q KRUN NOT_HALT.\n      assert (HHH:= NOT_HALT).\n      contradict HHH.\n      specialize (H0 _ _ _ KRUN NOT_HALT).\n      destruct (eq_tid_dec tid0 j); try solve[inversion H0].\n      subst tid0.\n      replace cnti with Htid; auto.\n      eapply msl.Axioms.proof_irr.\n    - destruct (schedPeek a') eqn:SCH'; auto.\n      rewrite HschedN in H0.\n      subst c'.\n      intros j cnti q KRUN NOT_HALT.\n      assert (HHH:= NOT_HALT).\n      contradict HHH.\n      specialize (H0 _ _ _ KRUN NOT_HALT).\n      destruct (eq_tid_dec tid0 j); try solve[inversion H0].\n      subst tid0.\n      contradict Htid; assumption.\n  Qed.\n\n  Lemma step_valid: forall {ge st m st' m'},\n      MachStep ge st m st' m'  ->\n      valid st ->\n      valid st'.\n  Proof. intros ? ? ? ? ?; eapply step_sch_correct. Qed.\n\n  Lemma step_new_valid: forall {ge st m st' m'},\n      MachStep ge st m st' m'  ->\n      new_valid (mk_nstate st m) (fst (fst st)) ->\n      new_valid (mk_nstate st' m') (fst (fst st')).\n  Proof. intros ? ? ? ? ? STEP VAL.\n         eapply step_sch_correct; eauto.\n  Qed.\n\n\n  Lemma step_correct_schedule: forall {ge U tr tp m tr' tp' m'},\n      MachStep ge (U, tr, tp) m (schedSkip U, tr', tp') m' ->\n      correct_schedule (U, tr, tp) ->\n      forall U'', correct_schedule (U'', tr', tp').\n  Proof.\n    unfold correct_schedule in *.\n    intros ? ? ? ? ? ? ? ? ?.\n\n    inversion H; subst; simpl in *;\n    match goal with\n    | [ H: schedPeek (schedSkip ?U) = Some _, H': U = schedSkip U  |- _ ] =>\n      solve[rewrite <- H' in H; apply end_of_sch in H'; rewrite H' in H; inversion H]\n    | _ => idtac\n    end.\n    - rewrite HschedN; intros.\n      destruct (schedPeek U''); auto.\n      inversion Htstep; subst.\n      intros j cnti q KRUN NOT_HALT.\n      unfold unique_Krun in H0.\n      destruct (eq_tid_dec tid0 j).\n      + subst tid0. rewrite gssThreadCC in KRUN; inversion KRUN.\n      + erewrite <- (gsoThreadCC n (cntUpdateC' cnti))  in KRUN; eauto.\n        eapply H0 in KRUN.\n        destruct (eq_tid_dec tid0 j) as [e|e].\n        * rewrite e in n; exfalso; apply n; auto.\n        * inversion KRUN.\n          intros HALT; eapply NOT_HALT.\n          Set Printing Implicit.\n          eapply threadHalt_update in HALT; eauto.\n    - rewrite HschedN.\n      intros. destruct (schedPeek U'') eqn:UUU; trivial.\n      intros j cnti q KRUN NOT_HALT.\n      assert (HH: exists (cntj : containsThread tp' j) (q : C),\n                   getThreadC cntj = Krun q).\n        { exists cnti, q; assumption. }\n        eapply syncstep_equal_run in HH; eauto.\n        destruct HH as [cntj [q0 KRUN']].\n\n        assert (HH:=KRUN').\n        eapply H0 in HH.\n\n        assert (HH': ~ @threadHalted j tp cntj).\n        { intros HH'. apply NOT_HALT.\n          eapply syncstep_equal_halted in Htstep; eauto.\n          eapply Htstep.\n          exact HH'. }\n        apply HH in HH'.\n\n        destruct (eq_tid_dec tid0 j); try solve[ inversion HH'].\n        subst.\n        eapply syncstep_not_running in Htstep.\n        exfalso; apply Htstep.\n        eassumption.\n    - rewrite HschedN. intros UNIQUE U''.\n      destruct (schedPeek U'') eqn:UUU; trivial.\n      intros j cnti q KRUN NOT_HALT.\n      specialize (UNIQUE _ _ _ KRUN NOT_HALT).\n      destruct (eq_tid_dec tid0 j); try solve[inversion UNIQUE]; subst tid0.\n      exfalso; apply NOT_HALT.\n      replace cnti with Htid by eapply msl.Axioms.proof_irr; auto.\n    - rewrite HschedN. intros UNIQUE U''.\n      destruct (schedPeek U'') eqn:UUU; trivial.\n      intros j cnti q KRUN NOT_HALT.\n      specialize (UNIQUE _ _ _ KRUN NOT_HALT).\n      destruct (eq_tid_dec tid0 j); try solve[inversion UNIQUE]; subst tid0.\n      exfalso; apply Htid.\n      eassumption.\n  Qed.\n\n  Lemma step_sch_valid: forall {ge U tr tp m tr' tp' m'}, MachStep ge (U, tr, tp) m (schedSkip U, tr', tp') m' -> valid (U, tr, tp) -> forall U'', valid (U'', tr', tp').\n  Proof. intros; eapply step_correct_schedule; eauto. Qed.\n\n  Lemma step_sch_new_valid:\n    forall {ge U tr tp m tr' tp' m'},\n      MachStep ge (U, tr, tp) m (schedSkip U, tr', tp') m' ->\n      new_valid (tr, tp, m) U ->\n      forall U'', new_valid (tr', tp', m') U''.\n  Proof. intros ? ? ? ? ? ? ? ? STEP VAL.\n         eapply step_correct_schedule; eauto.\n\n  Qed.\n\n\n  Lemma safety_equivalence':\n    forall ge st_ m,\n      (forall U n, new_valid (nil, st_, m) U -> ksafe_new_step ge (U, nil, st_) m n) ->\n      (forall U n, new_valid (nil, st_, m) U ->  csafe ge (U, nil, st_) m n).\n  Proof.\n    move=> ge st_ m KSF' U n VAL.\n    assert (KSF: forall U, new_valid (nil, st_, m) U -> ksafe_new_step ge (U, nil, st_) m n) by (move=> U'' NV; apply: KSF'=>// ).\n    clear KSF'.\n    (* assert (VAL_: new_valid (nil, st_, m) U).\n    { rewrite /new_valid /mk_ostate /=.\n      split; auto. *)\n    (*  by rewrite /new_valid /mk_ostate /= //. clear VAL.*)\n\n    (*move: VAL_=> /(KSF _ n) KSF_new.*)\n    move: st_ m KSF U VAL.\n    induction n.\n    - constructor.\n    - move => st_ m KSF U nVAL.\n      move: (nVAL) => /KSF => KSF_new.\n      inversion KSF_new; subst.\n      move: H0; rewrite /new_step /mk_nstate /= => STEP_halt.\n      inversion STEP_halt.\n      + subst; move: H6; rewrite /mk_ostate=> H6; apply: HaltedSafe=>//.\n      + subst; move: H; rewrite /mk_ostate /= => H.\n          assert (HH:=step_trace H); rewrite -HH in H.\n        destruct (step_sch H).\n        * subst U'; apply: (CoreSafe _ _ _ (snd (fst st')) (snd st')) =>/= //.\n          { apply: IHn => //.\n            - move => U'' nVAL'; rewrite /ksafe_new_step /mk_nstate => /=.\n              destruct st' as [p m0]; destruct p=> /=. simpl in HH; rewrite -HH in H1.\n              apply: H1=> //.\n            - rewrite /new_valid /mk_ostate=> /=.\n              apply: (step_new_valid H) =>//.\n          }\n        * subst U'. apply: (AngelSafe _ _ _ (snd (fst st')) (snd st'))=>//.\n          move=>U''.\n          { destruct st' as [[tr' tp'] m'] => /=; eapply IHn.\n            - move => U0 nVAL0. rewrite /ksafe_new_step /mk_nstate=> /=.\n              simpl in HH; rewrite -HH in H1.\n              by apply: H1.\n            - simpl in H.\n              eapply (step_sch_new_valid H); eauto.\n          }\n  Qed.\n\n  Lemma safety_equivalence:\n    forall ge tp m,\n      (forall U, new_valid (nil, tp, m) U) ->\n      (forall n U, ksafe_new_step ge (U, nil, tp) m n) ->\n      (forall n U, csafe ge (U, nil, tp) m n).\n  Proof. by move => ? ? ? H ? ? ?; apply: safety_equivalence'; try apply: H. Qed.\n\n  (** *I further create a different type of safety that discriminates non-determinism*)\n\n  Definition explicit_safety ge (U:Sch) (st:machine_state) (m:mem): Prop:=\n    exp_safety _ _ (fun U stm => halted (U, nil, fst stm))\n                   (fun U stm stm' => @internal_step ge U (fst stm) (snd stm) (fst stm') (snd stm'))\n                   (fun U stm U' stm' => @external_step ge U nil (fst stm) (snd stm) U' nil (fst stm') (snd stm'))\n                   (fun U stm => @new_valid (nil,fst stm, snd stm) U) U (st,m).\n\n  Definition explicit_safety_bounded ge (U:Sch) (st:machine_state) (m:mem): Prop:=\n    exp_safety _ _ (fun U stm => halted (U, nil, fst stm))\n                   (fun U stm stm' => @internal_step ge U (fst stm) (snd stm) (fst stm') (snd stm'))\n                   (fun U stm U' stm' => @external_step ge U nil (fst stm) (snd stm) U' nil (fst stm') (snd stm'))\n                   (fun U stm => @new_valid_bound (nil,fst stm, snd stm) U) U (st,m).\n\n  (*CoInductive explicit_safety ge (U:Sch) (st:machine_state) (m:mem): Prop:=\n  | halted_safety : halted (U, nil, st) -> explicit_safety ge U st m\n  | internal_safety st' m': @internal_step ge U st m st' m' ->\n                            (forall U', new_valid (nil, st', m') U' -> explicit_safety ge U' st' m') ->\n                            explicit_safety ge U st m\n  | external_safety U' st' m': @external_step ge U nil st m U' nil st' m' ->\n                            (forall U', new_valid (nil, st', m') U' -> explicit_safety ge U' st' m') ->\n                            explicit_safety ge U st m.*)\n\n  (*BUT, this is basically the same safety!!! *)\n  Lemma safety_equivalence21: forall ge st m,\n      (forall U, new_valid (nil, st, m) U ->\n             safe_new_step ge (U, nil, st) m) ->\n      forall U, new_valid (nil, st, m) U ->\n            explicit_safety ge U st m.\n  Proof.\n    move => ge.\n    cofix.\n    move =>  st m sns_all U /sns_all sns.\n    inversion sns.\n    move: H; rewrite /mk_nstate /= => stp.\n    inversion stp; subst.\n    - move: H6; rewrite /mk_ostate /= => hltd.\n      eapply (halted_safety); simpl; assumption.\n    - destruct st' as [[tr tp] m'].\n      move: H H0; rewrite /mk_ostate /MachStep /= => HH.\n      move: HH (HH)  => /trace_nil [] ? -> /step_equivalence1 [[] -> [] ? istp | estp] sns_all'.\n      + eapply (internal_safety).\n        instantiate (1:=(tp,m')); simpl. exact istp.\n        eapply safety_equivalence21 => //.\n      + eapply (external_safety).\n        instantiate (1:=(tp,m')); simpl. exact estp.\n        eapply safety_equivalence21 => //.\n  Qed.\n\n  Lemma safety_equivalence22: forall ge st m,\n      (forall U, new_valid (nil, st, m) U ->\n            explicit_safety ge U st m) ->\n      (forall U, new_valid (nil, st, m) U ->\n             safe_new_step ge (U, nil, st) m).\n  Proof.\n    move => ge.\n    cofix.\n    move =>  st m es_all U /es_all es.\n    inversion es.\n    - econstructor.\n      + econstructor. rewrite /mk_nstate /mk_ostate /= //.\n      + rewrite /mk_nstate /= => U'' VAL.\n        apply: safety_equivalence22 => //.\n    - econstructor.\n      + econstructor 2.\n        instantiate(1:=(@nil machine_event, fst y', snd y')).\n        rewrite /mk_nstate /mk_ostate /MachStep /=.\n        move: H => / step_equivalence2.\n        instantiate(1:=U).\n        simpl => //.\n      + rewrite /mk_nstate /= => U'' VAL.\n        destruct y';\n        apply: safety_equivalence22 => //.\n    - econstructor.\n      + econstructor 2.\n        instantiate(1:=(@nil machine_event, fst y' ,  snd y')).\n        rewrite /mk_nstate /mk_ostate /MachStep /=.\n        move: H => / step_equivalence3.\n        instantiate(1:=x').\n        simpl => //.\n      + rewrite /mk_nstate /= => U'' VAL.\n        destruct y';\n        apply: safety_equivalence22 => //.\n  Qed.\n  Lemma safety_equivalence2: forall ge st m,\n      (forall U, new_valid (nil, st, m) U ->\n             safe_new_step ge (U, nil, st) m) <->\n      (forall U, new_valid (nil, st, m) U ->\n            explicit_safety ge U st m).\n  Proof.\n    move => ge st m; split;\n           [apply: safety_equivalence21 | apply: safety_equivalence22].\n  Qed.\n\n  (** * AND another safety: explicift safety with stutter *)\n  Section newer_semantics_with_stutter.\n    Context {core_data: Type}\n            {core_ord : core_data -> core_data -> Prop}\n            (core_ord_wf : well_founded core_ord).\n\n    Definition stutter_stepN_safety ge cd (U:Sch) (st:machine_state) (m:mem): Prop:=\n    @exp_safetyN_stutter _ _ (fun U stm => halted (U, nil, fst stm))\n                   (fun U stm stm' => @internal_step ge U (fst stm) (snd stm) (fst stm') (snd stm'))\n                   (fun U stm U' stm' => @external_step ge U nil (fst stm) (snd stm) U' nil (fst stm') (snd stm'))\n                   (fun U stm => @new_valid (nil,fst stm, snd stm) U)\n                   core_data core_ord\n                   cd U (st,m).\n\n    Variable default: core_data.\n\n    (*This lemma is not needed but it's cool\n      How come the standard library doesn't have it!? *)\n    Lemma weak_well_founded_induction:\n      forall (A : Type) (R : A -> A -> Prop),\n      (forall P, P \\/ ~P) ->\n        well_founded R ->\n        forall P : A -> Prop,\n          (forall x: A, ~ (exists y:A, R y x) -> P x) ->\n          (forall x : A, (exists y : A, R y x /\\ P y) -> P x) ->\n          forall a : A, P a.\n    Proof.\n      move => A R EM WF P base ind a.\n      specialize (WF a).\n      induction WF.\n      generalize (EM (exists y: A, R y x)) ; move => [[]y Ryx | is_base ].\n      - by apply: ind; exists y; split; auto.\n      - by apply: base.\n    Qed.\n\n    End newer_semantics_with_stutter.\n\n\n  End new_safety.\n\n  Lemma csafe_reduce:\n    forall ge sched tp mem n m,\n      csafe ge (sched, [::], tp) mem n ->\n      m <= n ->\n      csafe ge (sched, [::], tp) mem m.\n  Proof.\n    intros. generalize n mem tp sched H0 H.\n    induction m.\n    intros. constructor.\n    intros.\n    assert (exists n', n0 = S n').\n    { clear - H1. induction H1. exists m; auto.\n      destruct IHle. exists (S x); auto. }\n    destruct H3 as [n' H3].\n    subst.\n    inversion H2.\n    + constructor 2; auto.\n    + econstructor 3; eauto.\n      simpl. subst. eapply IHm.\n      omega. simpl in Hsafe. instantiate (1:=n').\n      Focus 2. simpl in Hsafe. eauto.\n      omega.\n    + econstructor 4; eauto.\n      simpl. subst. intros. eapply IHm.\n      omega. simpl in Hsafe. instantiate (1:=n').\n      Focus 2. simpl in Hsafe. eauto.\n      omega.\n  Qed.\n\nEnd CoarseMachine.\n\nModule FineMachine (SCH:Scheduler)(SIG : ConcurrentMachineSig with Module ThreadPool.TID:=SCH.TID with Module Events.TID:=SCH.TID)<: ConcurrentMachine with Module SCH:= SCH with Module TP:= SIG.ThreadPool with Module SIG:= SIG.\n  Module SCH:=SCH.\n  Module TP:=SIG.ThreadPool.\n  Module SIG:=SIG.\n  Import SCH SIG TID ThreadPool ThreadPool.SEM Events.\n\n  Notation Sch:=schedule.\n  Notation machine_state := ThreadPool.t.\n  Notation event_trace := (seq machine_event).\n\n  Inductive start_thread' genv: forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | StartThread: forall tid0 ms ms' c_new vf arg\n                   (ctn: containsThread ms tid0)\n                   (Hcode: getThreadC ctn = Kinit vf arg)\n                   (Hinitial: initial_core Sem genv vf (arg::nil) = Some c_new)\n                   (Hinv: invariant ms)\n                   (Hms': updThreadC ctn (Krun c_new)  = ms'),\n      start_thread' genv ctn ms'.\n  Definition start_thread genv: forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @start_thread' genv.\n\n  Inductive resume_thread': forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | ResumeThread: forall tid0 ms ms' c c' X\n                    (ctn: containsThread ms tid0)\n                    (Hat_external: at_external Sem c = Some X)\n                    (Hafter_external:\n                       after_external Sem None c = Some c')\n                    (Hcode: getThreadC ctn = Kresume c Vundef)\n                    (Hinv: invariant ms)\n                    (Hms': updThreadC ctn (Krun c')  = ms'),\n      resume_thread' ctn ms'.\n  Definition resume_thread: forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @resume_thread'.\n\n  Inductive suspend_thread': forall {tid0} {ms:machine_state},\n      containsThread ms tid0 -> machine_state -> Prop:=\n  | SuspendThread: forall tid0 ms ms' c X\n                     (ctn: containsThread ms tid0)\n                     (Hcode: getThreadC ctn = Krun c)\n                     (Hat_external: at_external Sem c = Some X)\n                     (Hinv: invariant ms)\n                     (Hms': updThreadC ctn (Kblocked c) = ms'),\n      suspend_thread' ctn ms'.\n  Definition suspend_thread : forall {tid0 ms},\n      containsThread ms tid0 -> machine_state -> Prop:=\n    @suspend_thread'.\n\n  Inductive machine_step {genv:G}:\n    Sch -> event_trace -> machine_state -> mem -> Sch\n    -> event_trace -> machine_state -> mem -> Prop :=\n  | start_step:\n      forall tid U U' ms ms' m tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: start_thread genv Htid ms'),\n        machine_step U tr ms m U' tr ms' m\n  | resume_step:\n      forall tid U U' ms ms' m tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: resume_thread Htid ms'),\n        machine_step U tr ms m U' tr ms' m\n  | thread_step:\n      forall tid U U' ms ms' m m' ev tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: threadStep genv Htid Hcmpt ms' m' ev),\n        machine_step U tr ms m U'\n                     (tr ++ (List.map (fun mev => internal tid mev) ev))\n                     ms' (diluteMem m')\n  | suspend_step:\n      forall tid U U' ms ms' m tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: suspend_thread Htid ms'),\n        machine_step U tr ms m U' tr ms' m\n  | sync_step:\n      forall tid U U' ms ms' m m' tr ev\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Htstep: syncStep false genv Htid Hcmpt ms' m' ev),\n        machine_step U tr ms m U' (tr ++ [:: external tid ev]) ms' m'\n  | halted_step:\n      forall tid U U' ms m tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Htid: containsThread ms tid)\n        (Hcmpt: mem_compatible ms m)\n        (Hinv: invariant ms)\n        (Hhalted: threadHalted Htid),\n        machine_step U tr ms m U' tr ms m\n  | schedfail :\n      forall tid U U' ms m tr\n        (HschedN: schedPeek U = Some tid)\n        (HschedS: schedSkip U = U')        (*Schedule Forward*)\n        (Hcmpt: mem_compatible ms m)\n        (Hinv: invariant ms)\n        (Htid: ~ containsThread ms tid),\n        machine_step U tr ms m U' tr ms m.\n\n  Definition MachState: Type := (Sch * event_trace * machine_state)%type.\n\n  Definition MachStep G (c:MachState) (m:mem)\n             (c' :MachState) (m':mem) :=\n    @machine_step G (fst (fst c)) (snd (fst c)) (snd c)  m\n                  (fst (fst c')) (snd (fst c')) (snd c')  m'.\n\n  Definition at_external (st : MachState)\n    : option (external_function * list val) := None.\n\n  Definition after_external (ov : option val) (st : MachState) :\n    option (MachState) := None.\n\n  Definition halted (st : MachState) : option val :=\n    match schedPeek (fst (fst st)) with\n    | Some _ => None\n    | _ => Some Vundef\n    end.\n\n  Definition init_machine (U:schedule) (p : option RES.res) the_ge\n             (f : val) (args : list val) : option MachState :=\n    match init_mach p the_ge f args with\n    | None => None\n    | Some c => Some (U, [::],c)\n    end.\n\n  Program Definition MachineSemantics (U:schedule) (p : option RES.res):\n    CoreSemantics G MachState mem.\n  intros.\n  apply (@Build_CoreSemantics _ MachState _\n                              (init_machine U p)\n                              at_external\n                              after_external\n                              halted\n                              MachStep\n        );\n    unfold at_external, halted; try reflexivity.\n  intros. inversion H; subst; rewrite HschedN; reflexivity.\n  auto.\n  Defined.\n\n\n  Lemma initial_schedule: forall genv main vals U U' p c tr,\n      initial_core (MachineSemantics U p) genv main vals = Some (U',tr,c) ->\n      U' = U /\\ tr = nil.\n        simpl. unfold init_machine. intros.\n        destruct (init_mach p genv main vals); try solve[inversion H].\n        inversion H; subst; split; auto.\n  Qed.\n\n  (** Schedule safety of the fine-grained machine*)\n   Inductive fsafe (ge : SEM.G) (tp : thread_pool) (m : mem) (U : Sch)\n    : nat -> Prop :=\n  | Safe_0: fsafe ge tp m U 0\n  | HaltedSafe : forall n tr, halted (U, tr, tp) -> fsafe ge tp m U n\n  | StepSafe : forall (tp' : thread_pool) (m' : mem)\n                 (tr tr': event_trace) n,\n      MachStep ge (U, tr, tp) m (schedSkip U, tr', tp') m' ->\n      fsafe ge tp' m' (schedSkip U) n ->\n      fsafe ge tp m U (S n).\n\nEnd FineMachine.\n\nModule Events <: EventSig\n   with Module TID:=NatTID.\n\n Module TID := NatTID.\n Import TID event_semantics.\n\n (** Synchronization Events.  The release/acquire cases include the\nfootprints of permissions moved  when applicable*)\n Definition evRes := (access_map * access_map)%type.\n Definition evDelta := (delta_map * delta_map)%type.\n\n Inductive sync_event : Type :=\n | release : address (*-> option (evRes * evDelta)*) -> option evRes -> sync_event\n | acquire : address -> option evDelta (*option (evRes * evDelta) -> option evRes*)  -> sync_event\n | mklock :  address -> sync_event\n | freelock : address -> sync_event\n | spawn : address -> option (evRes * evDelta) -> option evDelta -> sync_event\n | failacq: address -> sync_event.\n\n (** Machine Events *)\n  Inductive machine_event : Type :=\n  | internal: TID.tid -> mem_event -> machine_event\n  | external : TID.tid -> sync_event -> machine_event.\n\n  Definition thread_id ev : tid :=\n    match ev with\n    | internal i _ => i\n    | external i _ => i\n    end.\n\n  Inductive act : Type :=\n  | Read : act\n  | Write : act\n  | Alloc : act\n  | Free : act\n  | Release : act\n  | Acquire : act\n  | Mklock : act\n  | Freelock : act\n  | Failacq : act\n  | Spawn : act.\n\n  Definition is_internal ev :=\n    match ev with\n    | internal _ _ => true\n    | _ => false\n    end.\n\n  Definition is_external ev :=\n    match ev with\n    | external _ _ => true\n    | _ => false\n    end.\n\n  Definition action ev : act :=\n    match ev with\n    | internal _ mev =>\n      match mev with\n      | event_semantics.Write _ _ _ => Write\n      | event_semantics.Read _ _ _ _ => Read\n      | event_semantics.Alloc _ _ _ => Alloc\n      | event_semantics.Free _ => Free\n      end\n    | external _ sev =>\n      match sev with\n      | release _ _ => Release\n      | acquire _ _ => Acquire\n      | mklock _ => Mklock\n      | freelock _ => Freelock\n      | failacq _ => Failacq\n      | spawn _ _ _ => Spawn\n      end\n    end.\n\n  Definition location ev : option (address*nat) :=\n    match ev with\n    | internal _ mev =>\n      match mev with\n      | event_semantics.Write b ofs vs => Some ((b, ofs), length vs)\n      | event_semantics.Read b ofs _ vs => Some ((b, ofs), length vs)\n      | _ => None\n      end\n    | external _ sev =>\n      match sev with\n      | release addr _ => Some (addr, lksize.LKSIZE_nat)\n      | acquire addr _ => Some (addr, lksize.LKSIZE_nat)\n      | mklock addr => Some (addr, lksize.LKSIZE_nat)\n      | freelock addr => Some (addr, lksize.LKSIZE_nat)\n      | spawn addr _ _ => Some (addr, lksize.LKSIZE_nat)\n      | failacq addr => Some (addr, lksize.LKSIZE_nat)\n      end\n    end.\n\nEnd Events.", "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/concurrent_machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17775843308769568}}
{"text": "Require Import Eqdep Lia Framework FSParameters CachedDiskLayer.\nRequire Import BatchOperations Log LogCache.\nRequire Import ATCDLayer.\nRequire Import ATCD_TS_BatchOperations_Recovery ATCD_TS_Log_Recovery.\n\nSet Nested Proofs Allowed.\n\nLemma combine_same_to_map:\n  forall T (l: list T),\n  combine l l = map (fun t => (t, t)) l.\n  Proof.\n    induction l; simpl; eauto.\n    rewrite IHl; eauto.\n  Qed.\n\n\nLemma LogCache_TS_write_batch_to_cache:\nforall u l1 l2 l3 l4 s1 s2 o s1' t,\nexec CachedDiskLang u o s1 \n(LogCache.write_batch_to_cache l1 l3)\n     (Finished s1' t) ->\n  length l1 = length l2 ->\n  length l3 = length l4 ->\nexists s2' t,\nexec CachedDiskLang u o s2 \n(LogCache.write_batch_to_cache l2 l4)\n     (Finished s2' t).\nProof.\ninduction l1; destruct l2; simpl in *;\ntry lia; intros; repeat invert_exec.\n{\n  intros; do 2 eexists; repeat econstructor. \n}\n{\n  cleanup; destruct l4; simpl in *; try lia;\n  repeat invert_exec;\n  try solve [do 2 eexists; repeat econstructor].\n  edestruct IHl1. \n  eauto.\n  3: cleanup; do 2 eexists; repeat econstructor; eauto.\n  all: eauto.\n}\nQed.\n\nLemma LogCache_TS_write_lists_to_cache:\nforall u l1 l2 s1 s2 o s1' t,\nexec CachedDiskLang u o s1 \n(LogCache.write_lists_to_cache l1)\n     (Finished s1' t) ->\n  length l1 = length l2 ->\n  Forall2 (fun lx ly => length (fst lx) = length (fst ly) /\\\n  length (snd lx) = length (snd ly)) l1 l2 -> \nexists s2' t,\nexec CachedDiskLang u o s2 \n(LogCache.write_lists_to_cache l2)\n     (Finished s2' t).\nProof.\ninduction l1; destruct l2; simpl in *;\ntry lia; intros; repeat invert_exec.\n{\n  intros; do 2 eexists; repeat econstructor. \n}\n{\n  inversion H1; cleanup.\n  eapply LogCache_TS_write_batch_to_cache with (l2:=fst p) (l4:= snd p)in H; cleanup.\n  edestruct IHl1. \n  eauto. \n  3:cleanup; do 2 eexists; repeat econstructor; eauto.\n  all: eauto.\n}\nQed.\n\n\nLemma LogCache_TS_write_batch_to_cache_crashed:\nforall u l1 l2 l3 l4 s1 s2 o s1',\nexec CachedDiskLang u o s1 \n(LogCache.write_batch_to_cache l1 l3)\n     (Crashed s1') ->\n  length l1 = length l2 ->\n  length l3 = length l4 ->\nexists s2',\nexec CachedDiskLang u o s2 \n(LogCache.write_batch_to_cache l2 l4)\n     (Crashed s2').\nProof.\ninduction l1; destruct l2; simpl in *;\ntry lia; intros; repeat invert_exec.\n{\n  intros; eexists; repeat econstructor. \n}\n{\n  cleanup; destruct l4; simpl in *; try lia;\n  repeat invert_exec;\n  try solve [eexists; repeat econstructor].\n\n  split_ors; cleanup; repeat invert_exec.\n  {\n    eexists; repeat econstructor; eauto.\n  }\n  edestruct IHl1. \n  eauto.\n  3: cleanup; eexists; repeat econstructor; eauto.\n  all: eauto.\n}\nQed.\n\nLemma LogCache_TS_write_lists_to_cache_crashed:\nforall u l1 l2 s1 s2 o s1',\nexec CachedDiskLang u o s1 \n(LogCache.write_lists_to_cache l1)\n     (Crashed s1') ->\n  length l1 = length l2 ->\n  Forall2 (fun lx ly => length (fst lx) = length (fst ly) /\\\n  length (snd lx) = length (snd ly)) l1 l2 -> \nexists s2',\nexec CachedDiskLang u o s2 \n(LogCache.write_lists_to_cache l2)\n     (Crashed s2').\nProof.\ninduction l1; destruct l2; simpl in *;\ntry lia; intros; repeat invert_exec.\n{\n  intros; eexists; repeat econstructor. \n}\n{\n  inversion H1; cleanup.\n  split_ors; cleanup; repeat invert_exec.\n  {\n    eapply LogCache_TS_write_batch_to_cache_crashed with (l2:=fst p) (l4:= snd p)in H; cleanup.\n    eexists; repeat econstructor; eauto.\n    all: eauto.\n  }\n  eapply LogCache_TS_write_batch_to_cache with (l2:=fst p) (l4:= snd p)in H2; cleanup.\n  edestruct IHl1. \n  eauto. \n  3:cleanup; eexists; repeat econstructor; eauto.\n  all: eauto.\n}\nQed.\n\n\n\nLemma LogCache_TS_recover:\nforall u s1 s2 o s1' t txns1 txns2 sa1 sa2 hdr1 hdr2 valid_part,\nexec CachedDiskLang u o s1 LogCache.recover\n     (Finished s1' t) ->\n\n((exists (hdr_blockset: set value) (log_blocksets: list (set value)),\nLog.log_rep_explicit Log.Hdr_Synced Log.Synced valid_part hdr1 \ntxns1 hdr_blockset log_blocksets (snd s1) /\\\n(valid_part = Log.Old_Part ->\n Log.hash (Log.current_part hdr1) <> \n rolling_hash hash0 (firstn (Log.count (Log.current_part hdr1)) \n (map fst log_blocksets)))) /\\\nsa1 = total_mem_map fst (shift (plus data_start) \n(list_upd_batch_set (snd (snd s1)) (map Log.addr_list txns1) (map Log.data_blocks txns1))) /\\\n(forall a, a >= data_start -> snd ((snd (snd s1)) a) = []) /\\ \n(forall a vs, snd (snd s1) a = vs -> snd vs = nil)) ->\n\n((exists (hdr_blockset: set value) (log_blocksets: list (set value)),\nLog.log_rep_explicit Log.Hdr_Synced Log.Synced valid_part hdr2 \ntxns2 hdr_blockset log_blocksets (snd s2) /\\\n(valid_part = Log.Old_Part ->\n Log.hash (Log.current_part hdr2) <> \n rolling_hash hash0 (firstn (Log.count (Log.current_part hdr2)) \n (map fst log_blocksets)))) /\\\nsa2 = total_mem_map fst (shift (plus data_start) \n(list_upd_batch_set (snd (snd s2)) (map Log.addr_list txns2) (map Log.data_blocks txns2))) /\\\n(forall a, a >= data_start -> snd ((snd (snd s2)) a) = []) /\\ \n(forall a vs, snd (snd s2) a = vs -> snd vs = nil)) ->\n\nlength txns1 = length txns2 ->\n\n(Log.count (Log.current_part hdr1) = Log.count (Log.current_part hdr2)) ->\n\nForall2\n(fun rec1 rec2 : Log.txn_record =>\n Log.start rec1 = Log.start rec2 /\\\n Log.addr_count rec1 = Log.addr_count rec2 /\\\n Log.data_count rec1 = Log.data_count rec2)\n(map Log.record txns1)\n(map Log.record txns2) ->\n\nexists s2' t,\nexec CachedDiskLang u o s2 LogCache.recover\n     (Finished s2' t).\nProof.\nTransparent LogCache.recover.\nOpaque Log.recover.\nunfold LogCache.recover in *.\nsimpl in *; intros;\ncleanup; repeat invert_exec.\n\nunfold Log.log_reboot_rep in *.\nsimpl in *; intros;\ncleanup; repeat invert_exec.\n\neapply_fresh Log_TS_recover in H13; eauto; cleanup.\neapply_fresh Specs.recover_finished in H; eauto.\neapply_fresh Specs.recover_finished in H13; eauto.\nall: try solve[unfold Log.log_reboot_rep; \nrewrite <- H3 in *; eauto;\ndo 4 eexists; intuition eauto].\n2:{\n  unfold Log.log_reboot_rep; \ndo 4 eexists; intuition eauto.\n}\neapply LogCache_TS_write_lists_to_cache in H5; cleanup.\n\ndo 2 eexists; repeat econstructor; eauto.\nrewrite cons_app; repeat econstructor; eauto.\neapply lift2_exec_step; eauto.\n\ndo 2 rewrite combine_length; do 4 rewrite map_length; eauto.\napply forall_forall2.\napply Forall_forall; intros.\nrepeat rewrite <- combine_map' in H14.\napply in_map_iff in H14; cleanup; simpl.\n\nrepeat rewrite combine_same_to_map in H15.\nrewrite <- combine_map' in H15.\napply in_map_iff in H15; cleanup; simpl.\napply forall2_forall in H4.\neapply Forall_forall in H4; eauto.\n2: rewrite <- combine_map'; eapply in_map_iff; eauto.\n2:repeat rewrite combine_length_eq; repeat rewrite map_length; eauto.\nsimpl in *.\n\nunfold Log.log_rep_explicit, Log.log_rep_inner, \nLog.txns_valid in *; logic_clean.\ndestruct x7; \neapply_fresh in_combine_l in H15;\neapply_fresh in_combine_r in H15;\nsimpl in *.\n\neapply Forall_forall in H24; eauto.\neapply Forall_forall in H32; eauto.\nunfold Log.txn_well_formed, Log.record_is_valid in *; logic_clean.\nrewrite H35, H46.\nsplit; try lia.\nrepeat rewrite firstn_length_l; try lia.\n\nUnshelve.\nexact CachedDiskLang.\nQed.\n\n\nLemma LogCache_TS_recover_crashed:\nforall u s1 s2 o s1' txns1 txns2 sa1 sa2 hdr1 hdr2 valid_part,\nexec CachedDiskLang u o s1 LogCache.recover (Crashed s1') ->\n\n((exists (hdr_blockset: set value) (log_blocksets: list (set value)),\nLog.log_rep_explicit Log.Hdr_Synced Log.Synced valid_part hdr1 \ntxns1 hdr_blockset log_blocksets (snd s1) /\\\n(valid_part = Log.Old_Part ->\nLog.hash (Log.current_part hdr1) <> \nrolling_hash hash0 (firstn (Log.count (Log.current_part hdr1)) \n(map fst log_blocksets)))) /\\\nsa1 = total_mem_map fst (shift (plus data_start) \n(list_upd_batch_set (snd (snd s1)) (map Log.addr_list txns1) (map Log.data_blocks txns1))) /\\\n(forall a, a >= data_start -> snd ((snd (snd s1)) a) = []) /\\ \n(forall a vs, snd (snd s1) a = vs -> snd vs = nil)) ->\n\n((exists (hdr_blockset: set value) (log_blocksets: list (set value)),\nLog.log_rep_explicit Log.Hdr_Synced Log.Synced valid_part hdr2 \ntxns2 hdr_blockset log_blocksets (snd s2) /\\\n(valid_part = Log.Old_Part ->\nLog.hash (Log.current_part hdr2) <> \nrolling_hash hash0 (firstn (Log.count (Log.current_part hdr2)) \n(map fst log_blocksets)))) /\\\nsa2 = total_mem_map fst (shift (plus data_start) \n(list_upd_batch_set (snd (snd s2)) (map Log.addr_list txns2) (map Log.data_blocks txns2))) /\\\n(forall a, a >= data_start -> snd ((snd (snd s2)) a) = []) /\\ \n(forall a vs, snd (snd s2) a = vs -> snd vs = nil)) ->\n\nlength txns1 = length txns2 ->\n\n(Log.count (Log.current_part hdr1) = Log.count (Log.current_part hdr2)) ->\n\nForall2\n(fun rec1 rec2 : Log.txn_record =>\nLog.start rec1 = Log.start rec2 /\\\nLog.addr_count rec1 = Log.addr_count rec2 /\\\nLog.data_count rec1 = Log.data_count rec2)\n(map Log.record txns1)\n(map Log.record txns2) ->\n\nexists s2',\nexec CachedDiskLang u o s2 LogCache.recover (Crashed s2').\nProof.\nTransparent LogCache.recover.\nOpaque Log.recover.\nunfold LogCache.recover in *.\nsimpl in *; intros;\ncleanup; repeat invert_exec.\nsplit_ors; cleanup; repeat invert_exec.\neexists; repeat econstructor.\n\nunfold Log.log_reboot_rep in *.\nsimpl in *; intros;\ncleanup; repeat invert_exec.\n\nsplit_ors; cleanup; repeat invert_exec.\n{\neapply_fresh Log_TS_recover_crashed in H9; eauto; cleanup.\nrewrite cons_app.\neexists; econstructor; eauto.\nrepeat econstructor.\neconstructor.\neapply lift2_exec_step_crashed; eauto.\nrewrite <- H3 in *; eauto.\n}\n{\neapply_fresh Log_TS_recover in H13; eauto; cleanup.\neapply_fresh Specs.recover_finished in H14; eauto.\neapply_fresh Specs.recover_finished in H13; eauto.\nall: try solve[unfold Log.log_reboot_rep; \nrewrite <- H3 in *; eauto;\ndo 4 eexists; intuition eauto].\n2:{\n  unfold Log.log_reboot_rep; \ndo 4 eexists; intuition eauto.\n}\n\neapply LogCache_TS_write_lists_to_cache_crashed in H9; cleanup.\nrewrite cons_app.\neexists; repeat econstructor; eauto.\neapply lift2_exec_step; eauto.\n\n\nrepeat rewrite combine_length_eq; repeat rewrite map_length; eauto.\napply forall_forall2.\napply Forall_forall; intros.\nrepeat rewrite <- combine_map' in H.\napply in_map_iff in H; cleanup; simpl.\n\nrepeat rewrite combine_same_to_map in H15.\nrewrite <- combine_map' in H15.\napply in_map_iff in H15; cleanup; simpl.\napply forall2_forall in H4.\neapply Forall_forall in H4; eauto.\n2: rewrite <- combine_map'; eapply in_map_iff; eauto.\n2:repeat rewrite combine_length_eq; repeat rewrite map_length; eauto.\nsimpl in *.\n\nunfold Log.log_rep_explicit, Log.log_rep_inner, \nLog.txns_valid in *; logic_clean.\ndestruct x4; \neapply_fresh in_combine_l in H15;\neapply_fresh in_combine_r in H15;\nsimpl in *.\n\neapply Forall_forall in H24; eauto.\neapply Forall_forall in H32; eauto.\nunfold Log.txn_well_formed, Log.record_is_valid in *; logic_clean.\nrewrite H35, H46.\nsplit; try lia.\nrepeat rewrite firstn_length_l; try lia.\n}\nUnshelve.\nall: exact CachedDiskLang.\nQed.\n\n", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/Storage/TerminationSensivitiy/ATCD_TS/TSRecovery/ATCD_TS_LogCache_Recovery.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.17775842945380024}}
{"text": "(* En este archivo se demuestra la correcci\u00f3n de la acci\u00f3n receiveIntent *)\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.\nRequire Export Coq.Arith.PeanoNat.\nImport PeanoNat.Nat.\n\nSection ReceiveIntent.\n\nLemma receiveIntentCorrect : forall (s:System) (i:Intent) (ic:iCmp) (a:idApp) (sValid: validstate s),\n    (pre (receiveIntent i ic a) s) -> post_receiveIntent i ic a s (receiveIntent_post i ic a s).\nProof.\n    intros.\n    unfold post_receiveIntent.\n    simpl in H.\n    unfold pre_receiveIntent in H;simpl in H.\n    destruct H as [run H].\n    destruct H.\n    destruct_conj H.\n    assert (maybeIntentForAppCmp i a ic s = Some x) as maybeintent.\n    apply inttForAppMaybeIntt;auto.\n    remember (iCmpGenerator (map_getKeys (running (state s)))) as theIC.\n    destruct H2.\n    destruct_conj H1.\n    split.\n  - exists theIC.\n    exists x.\n    split;auto.\n    split;auto.\n    assert (~In theIC (map_getKeys (running (state s)))).\n    rewrite HeqtheIC.\n    apply generatorWorksWell.\n    split.\n    unfold insNotInState;intros.\n    unfold not;intros.\n    case_eq (map_apply iCmp_eq (running (state s)) theIC);intros.\n    apply H5.\n    rewrite valueIffExists in H8.\n    unfold map_getKeys.\n    rewrite in_map_iff.\n    exists {| item_index := theIC; item_info := c |}.\n    split;auto.\n    apply (runningCorrect);auto.\n    rewrite H8 in H7.\n    unfold is_Value in H7.\n    apply H7.\n    split.\n    unfold receiveIntent_post.\n    unfold runCmp.\n    rewrite maybeintent.\n    split;intros.\n    simpl.\n    unfold performRunCmp.\n    assert (theIC <> ic').\n    unfold not;intros.\n    apply H5.\n    unfold map_getKeys.\n    rewrite in_map_iff.\n    rewrite valueIffExists in H7.\n    exists {| item_index := ic'; item_info := c' |}.\n    simpl.\n    auto.\n    apply (runningCorrect);auto.\n    \n    rewrite<- H7.\n    simpl.\n    apply overrideNotEq.\n    rewrite<- HeqtheIC.\n    auto.\n    split;intros.\n    simpl in H7.\n    rewrite<- HeqtheIC in H7.\n    unfold performRunCmp in H7.\n    elim (classic (theIC = ic'));intros.\n    right.\n    split;auto.\n    rewrite H8 in H7.\n    symmetry in H7.\n    rewrite <-addAndApply in H7.\n    inversion H7.\n    auto.\n    left.\n    rewrite overrideNotEq in H7.\n    auto.\n    auto.\n    \n    simpl.\n    unfold performRunCmp.\n    rewrite<- HeqtheIC.\n    split.\n    symmetry.\n    apply addAndApply.\n    \n    apply addPreservesCorrectness.\n    apply runningCorrect;auto.\n    \n    \n    case_eq (intType i);intros.\n    split;intros.\n    specialize (H4 H7).\n    case_eq (path (data i));intros.\n    left.\n    exists u.\n    specialize (H4 u H9).\n    destruct H4.\n    remember (getAnyCProviderWithUri u s) as theCP.\n    \n    exists theCP.\n    destruct H4.\n    split;auto.\n    split;auto.\n    unfold getAnyCProviderWithUri in HeqtheCP.\n    remember (fun cp : CProvider => existsResBool cp u s) as theFun.\n    assert (In theCP (getSomes Cmp CProvider (fun cmp : Cmp => match cmp with | cmpAct _ => None | cmpSrv _ => None | cmpCP cp => Some cp | cmpBR _ => None end) (getAllComponents s)) /\\ theFun theCP =true).\n    rewrite HeqtheCP.\n    apply ifExistsFilter.\n    exists x1.\n    rewrite filter_In.\n    split.\n    apply inGetSomes.\n    exists (cmpCP x1).\n    split;auto.\n    destruct H4.\n    destruct H4.\n    apply getAllComponentsIffInApp;auto.\n    exists x2.\n    auto.\n    rewrite HeqtheFun.\n    apply existsRes_iff;auto.\n    destruct H11.\n    rewrite HeqtheFun in H12.\n    apply existsRes_iff;auto.\n    \n    unfold grantTempPerm.\n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    rewrite H7.\n    rewrite H9.\n    simpl.\n    unfold performGrantTempPerm.\n    rewrite<-HeqtheIC.\n    split;intros.\n    split;intros.\n    \n    assert (theIC <> ic').\n    unfold not;intros.\n    assert (exists c, map_apply iCmp_eq (running (state s)) ic' = Value iCmp c).\n    apply (ifDelTPermsThenRunning s sValid ic' cp' u' pt');auto.\n    destruct H13.\n    apply H5.\n    unfold map_getKeys.\n    rewrite in_map_iff.\n    exists {| item_index := ic'; item_info := x2 |}.\n    simpl.\n    split;auto.\n    rewrite<- valueIffExists.\n    exact H13.\n    apply (runningCorrect);auto.\n    \n    rewrite overrideNotEq.\n    auto.\n    unfold not;intros.\n    apply H12.\n    inversion H13.\n    auto.\n    \n    split;intros.\n    \n    elim (classic (theIC = ic' /\\ theCP = cp' /\\ u = u'));intros.\n    right.\n    destruct_conj H12.\n    rewrite H13 in H11.\n    rewrite <-H12 in H11.\n    rewrite HeqtheCP in H11.\n    rewrite H15 in H11.\n    rewrite <-addAndApply in H11.\n    inversion H11.\n    auto.\n    left.\n    rewrite overrideNotEq in H11.\n    auto.\n    unfold not;intros.\n    apply H12.\n    rewrite HeqtheCP.\n    inversion H13.\n    auto.\n    rewrite HeqtheCP.\n    rewrite<- addAndApply.\n    auto.\n    apply addPreservesCorrectness.\n    apply delTPermsCorrect;auto.\n    \n    \n    right.\n    split;auto.\n    \n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    rewrite H9.\n    simpl.\n    rewrite H7.\n    auto.\n    split;intros;discriminate H8.\n    split;intros.\n    discriminate H8.\n    split;intros.\n    \n    \n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    simpl.\n    rewrite H7.\n    auto.\n    discriminate H8.\n    split;intros.\n    discriminate H8.\n    split;intros.\n    discriminate H8.\n    \n    \n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    simpl.\n    rewrite H7.\n    auto.\n    \n  - split.\n    unfold removeIntent.\n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    simpl.\n    split;intros.\n    rewrite <-removeSthElse in H5.\n    destruct H5.\n    auto.\n    split;intros.\n    elim (classic ((ic',i') = (ic,i)));intros.\n    right.\n    inversion H7;auto.\n    left.\n    apply removeSthElse.\n    auto.\n    rewrite<- removeSthElse.\n    unfold not;intros.\n    destruct H5.\n    apply H5;auto.\n    \n    unfold receiveIntent_post.\n    rewrite maybeintent.\n    simpl.\n    repeat (split;auto).\nQed.\n\n\nLemma notPreReceiveIntentThenError : forall (s:System) (i:Intent) (ic:iCmp) (a:idApp), ~(pre (receiveIntent i ic a) s) -> validstate s -> exists ec : ErrorCode, response (step s (receiveIntent i ic a)) = error ec /\\ ErrorMsg s (receiveIntent i ic a) ec /\\ s = system (step s (receiveIntent i ic a)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_receiveIntent in H.\n    unfold receiveIntent_safe.\n    unfold receiveIntent_pre.\n    case_eq (maybeIntentForAppCmp i a ic s);intros. \n    case_eq (isCProviderBool c);intros.\n    exists cmp_is_CProvider.\n    split;auto.\n    split;auto.\n    exists c.\n    apply inttForAppMaybeInttBack in H1;auto.\n    apply isCProviderBool_iff in H2.\n    split;auto.\n\n    case_eq (negb (canRunBool a s)); intros.\n    exists should_verify_permissions.\n    split; auto.\n    clear H.\n    split.\n    rewrite negb_true_iff in H3.\n    unfold canRunBool in H3.\n    unfold not. intros. unfold canRun in H.\n    destruct H.\n    case_eq (InBool idApp idApp_eq a (alreadyVerified (state s))); intros.\n    rewrite H4 in H3. simpl in H3. inversion H3.\n    apply notInBoolNotIn in H4. contradiction.\n\n    destruct H as [m [n [H4 [H5 H6]]]].\n    unfold getManifestForApp in H3.\n    unfold RuntimePermissions.isManifestOfApp in H4.\n    destruct H4.\n    rewrite H, H5 in H3.\n    case_eq (InBool idApp idApp_eq a (alreadyVerified (state s))); intros.\n    rewrite H4 in H3. inversion H3.\n    rewrite H4 in H3. simpl in H3.\n\n    assert (vulnerableSdk < n). auto.\n    rewrite <- ltb_lt in H7. rewrite H3 in H7.\n    inversion H7.\n\n    case_eq (InBool idApp idApp_eq a (alreadyVerified (state s))); intros.\n    rewrite H4 in H3. inversion H3.\n    rewrite H4 in H3. simpl in H3. clear H4.\n    destruct H as [sysapp [H7 [H8 H9]]].\n    case_eq (map_apply idApp_eq (manifest (environment s)) a); intros.\n\n    assert (exists m: Manifest,\n      map_apply idApp_eq (manifest (environment s)) a = Value idApp m).\n    exists m0; auto.\n\n    assert (In sysapp (systemImage (environment s)) /\\ idSI sysapp = a).\n    auto.\n\n    apply (ifSysImgNoManifestInEnv s H0) in H10.\n    contradiction.\n\n    rewrite H in H3. clear H.\n    destructVS H0.\n    unfold notDupSysApp in notDupSysAppVS.\n\n    induction (systemImage (environment s)).\n    inversion H7.\n\n    simpl in H3.\n    destruct (idApp_eq a (idSI a0)).\n    simpl in H3.\n\n    assert (In a0 (a0::l)). simpl. left. auto.\n    rewrite e in H8.\n\n    assert (In sysapp (a0::l) /\\\n      In a0 (a0::l) /\\ idSI sysapp = idSI a0).\n    auto.\n    apply notDupSysAppVS in H0.\n    rewrite <- H0 in H3. rewrite H9 in H3.\n    rewrite H5 in H3.\n    assert (vulnerableSdk < n). auto.\n    rewrite <- ltb_lt in H4. rewrite H3 in H4.\n    inversion H4.\n\n    simpl in H7.\n    destruct H7. symmetry in H8.\n    rewrite H in n0. contradiction.\n    apply IHl. intros.\n    destruct H0. destruct H4.\n    assert (In s1 (a0 :: l)). simpl. right. auto.\n    assert (In s2 (a0 :: l)). simpl. right. auto.\n    apply notDupSysAppVS. auto.\n\n    auto. auto.\n\n\n    simpl. auto.\n\n    case_eq (map_apply iCmp_eq (running (state s)) ic);intros.\n    case_eq (isCProviderBool c0);intros.\n    exists cmp_is_CProvider.\n    split;auto.\n    split;auto.\n    exists c0.\n    apply isCProviderBool_iff in H5.\n    split;auto.\n\n    case_eq (negb (canStartBool c0 c s));intros.\n    exists a_cant_start_b.\n    split;auto.\n    split;auto.\n    exists c,c0.\n    apply inttForAppMaybeInttBack in H1;auto.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H6.\n    invertBool H6.\n    intro.\n    apply H6.\n    apply canStartCorrect;auto.\n\n    destruct (intType i).\n    destruct (path (data i)).\n    case_eq (existsb (receiveIntentCmpRequirements c0 u s (intentActionType i)) (getAllComponents s));intros.\n    destruct H.\n    split.\n  - rewrite negb_false_iff in H3.\n    apply canRunBool_canRun. auto.\n  - exists c.\n\n    split.\n    apply inttForAppMaybeInttBack in H1;auto.\n\n    split.\n    invertBool H2.\n    intro.\n    apply H2.\n    apply isCProviderBool_iff;auto.\n\n    exists c0.\n    split;auto.\n\n    split.\n    invertBool H5.\n    intro.\n    apply H5.\n    apply isCProviderBool_iff;auto.\n\n    split.\n    rewrite negb_false_iff in H6.\n    apply canStartCorrect;auto.\n    split;intros.\n\n    rewrite existsb_exists in H7.\n    destruct H7.\n    destruct H7.\n    unfold receiveIntentCmpRequirements in H9.\n    destruct x;try discriminate H9.\n    exists c1.\n    rewrite andb_true_iff in H9.\n    destruct H9.\n    rewrite andb_true_iff in H9.\n    destruct H9.\n    inversion H8.\n    rewrite <- H13 in *.\n    split.\n    apply existsRes_iff;auto.\n    split.\n    apply canGrantCorrect;auto.\n    unfold canRead.\n    unfold canWrite.\n    unfold canReadBool in H10.\n    unfold canWriteBool in H10.\n    destruct (intentActionType i); try rewrite orb_true_iff in H10.\n    destruct H10.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    destruct H10.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n\n    rewrite andb_true_iff in H10.\n    destruct H10.\n    split.\n    rewrite orb_true_iff in H10.\n    destruct H10.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    rewrite orb_true_iff in H12.\n    destruct H12.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    destruct H.\n    discriminate H.\n\n  - exists no_CProvider_fits.\n    split;auto.\n    split;auto.\n    exists c0.\n    split;auto.\n    split;auto.\n    intros.\n    inversion H8.\n    rewrite <-H10 in *.\n    invertBool H7.\n    intro.\n    apply H7.\n    destruct H9.\n    destruct_conj H9.\n    rewrite existsb_exists.\n    exists (cmpCP x).\n    split.\n    unfold existsRes in H11.\n    destruct H11.\n    destruct H11.\n    apply getAllComponentsIffInApp;auto.\n    exists x0;auto.\n    unfold receiveIntentCmpRequirements.\n    rewrite andb_true_iff.\n    split.\n    rewrite andb_true_iff.\n    split.\n    apply existsRes_iff;auto.\n    apply canGrantCorrect;auto.\n    unfold canRead in H13.\n    unfold canWrite in H13.\n    unfold canReadBool.\n    unfold canWriteBool.\n    destruct (intentActionType i).\n    rewrite orb_true_iff.\n    destruct H13.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    rewrite orb_true_iff.\n    destruct H13.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    rewrite andb_true_iff.\n    destruct H13.\n    split;rewrite orb_true_iff.\n    destruct H12.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n    destruct H13.\n    left.\n    apply canDoThisBoolCorrect;auto.\n    right.\n    apply delPermsBoolCorrect;auto.\n\n  - destruct H.\n    split.\n -- rewrite negb_false_iff in H3.\n    apply canRunBool_canRun. auto.\n -- exists c.\n\n    split.\n    apply inttForAppMaybeInttBack in H1;auto.\n\n    split.\n    invertBool H2.\n    intro.\n    apply H2.\n    apply isCProviderBool_iff;auto.\n\n    exists c0.\n    split;auto.\n\n    split.\n    invertBool H5.\n    intro.\n    apply H5.\n    apply isCProviderBool_iff;auto.\n\n    split.\n    rewrite negb_false_iff in H6.\n    apply canStartCorrect;auto.\n    split;intros.\n    discriminate H7.\n    destruct H.\n    discriminate H.\n\n  - destruct H.\n    split.\n -- rewrite negb_false_iff in H3.\n    apply canRunBool_canRun. auto.\n -- exists c.\n\n    split.\n    apply inttForAppMaybeInttBack in H1;auto.\n\n    split.\n    invertBool H2.\n    intro.\n    apply H2.\n    apply isCProviderBool_iff;auto.\n\n    exists c0.\n    split;auto.\n\n    split.\n    invertBool H5.\n    intro.\n    apply H5.\n    apply isCProviderBool_iff;auto.\n\n    split.\n    rewrite negb_false_iff in H6.\n    apply canStartCorrect;auto.\n    split;intros.\n    discriminate H.\n    destruct H.\n    discriminate H.\n\n  - destruct (brperm i).\n    case_eq (appHasPermissionBool a p s);intro.\n    destruct H.\n    split.\n -- rewrite negb_false_iff in H3.\n    apply canRunBool_canRun. auto.\n -- exists c.\n\n    split.\n    apply inttForAppMaybeInttBack in H1;auto.\n\n    split.\n    invertBool H2.\n    intro.\n    apply H2.\n    apply isCProviderBool_iff;auto.\n\n    exists c0.\n    split;auto.\n\n    split.\n    invertBool H5.\n    intro.\n    apply H5.\n    apply isCProviderBool_iff;auto.\n\n    split.\n    rewrite negb_false_iff in H6.\n    apply canStartCorrect;auto.\n    split;intros.\n    discriminate H.\n    destruct H.\n    exists p.\n    rewrite <-appHasPermissionCorrect in H7;auto.\n -- exists not_enough_permissions.\n    split;auto.\n    split;auto.\n    split;auto.\n    split;auto.\n    unfold not.\n    intros.\n    inversion H7.\n    inversion H8.\n    exists p.\n    split;auto.\n    invertBool H7.\n    intro.\n    apply H7.\n    apply appHasPermissionCorrect;auto.\n\n -- destruct H.\n    split.\n    rewrite negb_false_iff in H3.\n    apply canRunBool_canRun. auto.\n    exists c.\n\n    split.\n    apply inttForAppMaybeInttBack in H1;auto.\n\n    split.\n    invertBool H2.\n    intro.\n    apply H2.\n    apply isCProviderBool_iff;auto.\n\n    exists c0.\n    split;auto.\n\n    split.\n    invertBool H5.\n    intro.\n    apply H5.\n    apply isCProviderBool_iff;auto.\n\n    split.\n    rewrite negb_false_iff in H6.\n    apply canStartCorrect;auto.\n    split;intros.\n    discriminate H.\n    destruct H.\n    destruct H7;auto.\n  - exists instance_not_running.\n    split;auto.\n  - exists no_such_intt.\n    split;auto.\n    split;auto.\n    intro.\n    destruct H2.\n    apply inttForAppMaybeIntt in H2;auto.\n    rewrite H2 in H1.\n    discriminate H1.\nQed.\n\nLemma receiveIntentIsSound : forall (s:System) (i:Intent) (ic:iCmp) (a:idApp) (sValid: validstate s),\n        exec s (receiveIntent i ic a) (system (step s (receiveIntent i ic a))) (response (step s (receiveIntent i ic a))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (receiveIntent i ic a) s));intro.\n    left.\n    simpl.\n    assert(receiveIntent_pre i ic a s = None).\n    unfold receiveIntent_pre.\n    destruct H as [CR H].\n    destruct H.\n    destruct_conj H.\n    assert (maybeIntentForAppCmp i a ic s = Some x) as maybeintent.\n    apply inttForAppMaybeIntt;auto.\n    rewrite maybeintent.\n    rewrite isCProviderBool_iff in H.\n    rewrite not_true_iff_false in H.\n    rewrite H.\n    destruct H2.\n    destruct_conj H1.\n    rewrite H2.\n    rewrite isCProviderBool_iff in H1.\n    rewrite not_true_iff_false in H1.\n    rewrite H1.\n    assert (canStartBool x0 x s = true).\n    apply canStartCorrect;auto.\n    rewrite H5.\n    assert (negb true=false).\n    rewrite negb_false_iff.\n    auto.\n    rewrite H7.\n    case_eq (intType i);intros.\n    case_eq (path (data i));intros.\n    assert (existsb (receiveIntentCmpRequirements x0 u s (intentActionType i)) (getAllComponents s)=true).\n    rewrite existsb_exists.\n    specialize (H4 H8 u H9).\n    destruct H4.\n    destruct_conj H4.\n    exists (cmpCP x1).\n    unfold receiveIntentCmpRequirements.\n    split.\n    unfold getAllComponents.\n    destruct H10.\n    destruct H10.\n    destruct H10.\n    rewrite in_concat.\n    exists (cmp x3).\n    rewrite in_app_iff.\n    destruct H10.\n    split;auto.\n    destruct H10.\n    left.\n    rewrite in_map_iff.\n    exists x3.\n    split;auto.\n    apply inGetValuesBack.\n    exists (Value idApp x3).\n    split;auto.\n    rewrite in_map_iff.\n    exists x2.\n    split;auto.\n    apply (ifManifestThenInApps s sValid x2 x3);auto.\n    right.\n    rewrite in_map_iff.\n    destruct H10.\n    destruct_conj H10.\n    exists x4.\n    rewrite H16.\n    auto.\n    assert (existsResBool x1 u s = true).\n    apply existsRes_iff;auto.\n    assert (canGrantBool x1 u s=true).\n    apply canGrantCorrect;auto.\n    unfold canReadBool.\n    unfold canWriteBool.\n    unfold canRead in H12.\n    unfold canWrite in H12.\n    rewrite H11.\n    rewrite H13.\n    case_eq (intentActionType i);intros; rewrite H14 in H12;destruct H12.\n    assert (canDoThisBool x0 x1 s readE=true).\n    apply canDoThisBoolCorrect;auto.\n    rewrite H15;auto.\n    assert (delPermsBool x0 x1 u Read s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H15;auto.\n    rewrite orb_true_r.\n    auto.\n    \n    assert (canDoThisBool x0 x1 s writeE=true).\n    apply canDoThisBoolCorrect;auto.\n    rewrite H15;auto.\n    assert (delPermsBool x0 x1 u Write s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H15;auto.\n    rewrite orb_true_r.\n    auto.\n    \n    destruct H12.\n    assert (canDoThisBool x0 x1 s readE=true).\n    apply canDoThisBoolCorrect;auto.\n    rewrite H16;auto.\n    \n    destruct H15.\n    assert (canDoThisBool x0 x1 s writeE=true).\n    apply canDoThisBoolCorrect;auto.\n    rewrite H17;auto.\n    assert (delPermsBool x0 x1 u Write s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H17;auto.\n    rewrite orb_true_r.\n    auto.\n    \n    destruct H15.\n    assert (canDoThisBool x0 x1 s writeE=true).\n    apply canDoThisBoolCorrect;auto.\n    rewrite H16;auto.\n    assert (delPermsBool x0 x1 u Read s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H17;auto.\n    rewrite orb_true_r.\n    auto.\n    \n    \n    assert (delPermsBool x0 x1 u Read s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H16;auto.\n    rewrite orb_true_r.\n    auto.\n    assert (delPermsBool x0 x1 u Write s=true).\n    apply delPermsBoolCorrect;auto.\n    rewrite H17;auto.\n    rewrite orb_true_r.\n    auto.\n\n    apply canRun_canRunBool in CR.\n    rewrite CR. simpl.\n\n    rewrite H10.\n    auto.\n    auto.\n    apply canRun_canRunBool in CR.\n    rewrite CR. simpl.\n    auto. auto.\n    apply canRun_canRunBool in CR.\n    rewrite CR. simpl. auto. auto.\n    apply canRun_canRunBool in CR.\n    rewrite CR. simpl.\n    case_eq (brperm i);intros.\n    assert (appHasPermissionBool a p s=true).\n    assert (exists p : Perm, brperm i = Some p /\\ RuntimePermissions.appHasPermission a p s).\n    apply H6.\n    split;auto.\n    unfold not;intros.\n    rewrite H9 in H10.\n    inversion H10.\n    destruct H10.\n    destruct H10.\n    rewrite H10 in H9.\n    inversion H9.\n    rewrite H13 in H11.\n    apply appHasPermissionCorrect;auto.\n    rewrite H10;auto.\n    auto. auto.\n    \n    unfold receiveIntent_safe;simpl.\n    rewrite H0;simpl.\n    split;auto.\n    split;auto.\n    apply receiveIntentCorrect;auto.\n    right.\n    apply notPreReceiveIntentThenError;auto.\nQed.\nEnd ReceiveIntent.\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/ReceiveIntentIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1777370439009159}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import RunSMC.Spec.\nRequire Import TableDataSMC.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance TableDataSMC_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance TableDataSMC_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance smc_rtt_create_inv: PreservesInvariants smc_rtt_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rtt_destroy_inv: PreservesInvariants smc_rtt_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rtt_map_inv: PreservesInvariants smc_rtt_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rtt_unmap_inv: PreservesInvariants smc_rtt_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_data_create_inv: PreservesInvariants smc_data_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_data_destroy_inv: PreservesInvariants smc_data_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_data_create_unknown_inv: PreservesInvariants smc_data_create_unknown_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_destroy_inv: PreservesInvariants data_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_create_unknown_inv: PreservesInvariants data_create_unknown_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_run_inv: PreservesInvariants smc_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance data_create_inv: PreservesInvariants data_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition TableDataSMC_fresh : compatlayer (cdata RData) :=\n      _smc_rtt_create \u21a6 gensem smc_rtt_create_spec\n        \u2295 _smc_rtt_destroy \u21a6 gensem smc_rtt_destroy_spec\n        \u2295 _smc_rtt_map \u21a6 gensem smc_rtt_map_spec\n        \u2295 _smc_rtt_unmap \u21a6 gensem smc_rtt_unmap_spec\n        \u2295 _smc_data_create \u21a6 gensem smc_data_create_spec\n        \u2295 _smc_data_destroy \u21a6 gensem smc_data_destroy_spec\n        \u2295 _smc_data_create_unknown \u21a6 gensem smc_data_create_unknown_spec\n      .\n\n    Definition TableDataSMC_passthrough : compatlayer (cdata RData) :=\n      _data_destroy \u21a6 gensem data_destroy_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _data_create_unknown \u21a6 gensem data_create_unknown_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _smc_rec_run \u21a6 gensem smc_rec_run_spec\n        \u2295 _data_create \u21a6 gensem data_create_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n      .\n\n    Definition TableDataSMC := TableDataSMC_fresh \u2295 TableDataSMC_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.1774978293863926}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableAux.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef3.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition smc_rtt_create_spec0 (rtt_addr: Z64) (rd_addr: Z64) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match rtt_addr, rd_addr, map_addr, level with\n    | VZ64 _rtt_addr, VZ64 _rd_addr, VZ64 _map_addr, VZ64 _level =>\n      let _ret := 0 in\n      rely is_int64 _map_addr;\n      rely is_int64 _level;\n      when _t'1 == validate_table_commands_spec (VZ64 _map_addr) (VZ64 _level) (VZ64 1) (VZ64 3) (VZ64 3) adt;\n      rely is_int _t'1;\n      rely is_int64 _t'1;\n      let _ret := _t'1 in\n      if (_ret =? 0) then\n        rely is_int64 _rtt_addr;\n        when'' _g_rtt_base, _g_rtt_ofst, adt == find_lock_granule_spec (VZ64 _rtt_addr) (VZ64 1) adt;\n        rely is_int _g_rtt_ofst;\n        when _t'6 == is_null_spec (_g_rtt_base, _g_rtt_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          rely is_int64 _rd_addr;\n          when'' _g_rd_base, _g_rd_ofst, adt == find_lock_granule_spec (VZ64 _rd_addr) (VZ64 2) adt;\n          rely is_int _g_rd_ofst;\n          when _t'5 == is_null_spec (_g_rd_base, _g_rd_ofst) adt;\n          rely is_int _t'5;\n          if (_t'5 =? 1) then\n            let _ret := 1 in\n            when adt == granule_unlock_spec (_g_rtt_base, _g_rtt_ofst) adt;\n            Some (adt, (VZ64 _ret))\n          else\n            when' _ret, adt == table_create3_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 _ret;\n            when adt == granule_unlock_spec (_g_rd_base, _g_rd_ofst) adt;\n            when adt == granule_unlock_spec (_g_rtt_base, _g_rtt_ofst) adt;\n            Some (adt, (VZ64 _ret))\n      else\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/TableDataSMC/LowSpecs/smc_rtt_create.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.17747665124526993}}
{"text": "(******************************************************************************)\n(** * RC11 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.\nRequire Import RC11.\n\nSet Implicit Arguments.\n\nSection RC11_TO_IMM_S.\n\nVariable G : execution.\n\nNotation \"'E'\" := (acts_set 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 \"'rmw_dep'\" := (rmw_dep G).\n\nNotation \"'fr'\" := (fr G).\nNotation \"'eco'\" := (eco G).\nNotation \"'coe'\" := (coe G).\nNotation \"'coi'\" := (coi G).\nNotation \"'deps'\" := (deps G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'rfe'\" := (rfe G).\n\nNotation \"'detour'\" := (detour G).\n\nNotation \"'rs'\" := (rs G).\nNotation \"'release'\" := (release G).\nNotation \"'sw'\" := (sw G).\nNotation \"'hb'\" := (hb G).\n\nNotation \"'ar_int'\" := (ar_int G).\nNotation \"'ppo'\" := (ppo G).\nNotation \"'bob'\" := (bob G).\n\nNotation \"'ar'\" := (ar G).\n\nNotation \"'lab'\" := (lab G).\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 \"'F'\" := (fun a => is_true (is_f 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 \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\n(******************************************************************************)\n(** relations are contained in the corresponding ones **  *)\n(******************************************************************************)\n\nLemma s_imm_consistentimplies_rc11_consistent (WF: Wf G) \n      (COND: \u2997R \\\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997W \\\u2081 Rel\u2998 \u2286 sb \u2a3e \u2997F \u2229\u2081 Acq/Rel\u2998 \u2a3e sb \u222a \u2997R\u2998 \u2a3e deps \u2a3e \u2997W\u2998 \u222a rmw) sc\n      (IPC : imm_s.imm_psc_consistent G sc) :\n  rc11_consistent G.\nProof using.\n  cdes IPC. cdes IC.\n  red. splits; auto.\n  rewrite rfi_union_rfe with (G:=G). \n  unfold Execution.rfi; rewrite inclusion_inter_l2, <- unionA, unionK.\n  eapply acyclic_ud with (adom := W) (bdom := R); eauto using sb_acyclic.\n  1-2: by destruct WF; unfold Execution.rfe; rewrite wf_rfD; eauto using minus_doma, minus_domb with hahn. \n  assert (T:= @sb_trans G); relsf; clear T.\n  eapply irreflexive_inclusion, Cext; apply inclusion_t_t2. \n  unfold imm_s.ar, imm_s_ppo.ar_int; unionL; eauto with hahn.\n  arewrite (R \u2261\u2081 (R \u2229\u2081 Acq) \u222a\u2081 (R \\\u2081 Acq)).\n    by unfolder; split; ins; desf; destruct (is_acq lab x); auto. \n  rewrite id_union; relsf; unionL.\n    by rewrite inclusion_seq_eqv_r at 1; unfold imm_bob.bob; auto 10 with hahn.\n  arewrite (W \u2261\u2081 (W \u2229\u2081 Rel) \u222a\u2081 (W \\\u2081 Rel)) at 1.\n    by unfolder; split; ins; desf; destruct (is_rel lab x); auto. \n  rewrite id_union; relsf; unionL.\n    by rewrite inclusion_seq_eqv_l at 1; unfold imm_bob.bob, imm_bob.fwbob; auto 10 with hahn.\n  rewrite COND.\n  sin_rewrite rmw_in_ppo; auto.\n  arewrite (\u2997R\u2998 \u2a3e deps \u2a3e \u2997W\u2998 \u2286 ppo).\n  { rewrite <- deps_rfi_in_ppo.\n    sin_rewrite (ct_step deps).\n    rewrite unionC, ct_unionE.\n    basic_solver. }\n  unionL.\n  { rewrite <- seq_eqvK, seqA, <- seqA. \n    apply inclusion_step2_ct; unfold imm_bob.bob, imm_bob.fwbob; auto 10 with hahn. }\n  all: etransitivity; [|by apply ct_step].\n  all: basic_solver 20.\nQed.\n\nEnd RC11_TO_IMM_S.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/rc11/RC11Toimm_s.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17745939166389446}}
{"text": "(******************************************************************************)\n(* PipeCheck: Specifying and Verifying Microarchitectural                     *)\n(* Enforcement of Memory Consistency Models                                   *)\n(*                                                                            *)\n(* Copyright (c) 2014 Daniel Lustig, Princeton University                     *)\n(* All rights reserved.                                                       *)\n(*                                                                            *)\n(* This library is free software; you can redistribute it and/or              *)\n(* modify it under the terms of the GNU Lesser General Public                 *)\n(* License as published by the Free Software Foundation; either               *)\n(* version 2.1 of the License, or (at your option) any later version.         *)\n(*                                                                            *)\n(* This library is distributed in the hope that it will be useful,            *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of             *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU          *)\n(* Lesser General Public License for more details.                            *)\n(*                                                                            *)\n(* You should have received a copy of the GNU Lesser General Public           *)\n(* License along with this library; if not, write to the Free Software        *)\n(* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  *)\n(* USA                                                                        *)\n(******************************************************************************)\n\nRequire Import Ensembles.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import List.\nImport ListNotations.\nRequire Import wmm.\nRequire Import util2.\nRequire Import dot.\nRequire Import topsort.\nRequire Import stages.\n\n(** * gem5 O3 Pipeline *)\n\n(** ** Local Reorderings at different stages *)\n\n(** [FIFO]: any ordering guaranteed at the input is also guaranteed at the\n  output.  This is the common case. *)\nDefinition FIFO : LocalReordering := fun _ => fun ordering => ordering.\n\n(** [NoOrderGuarantees]: Operations can leave the stage in any order; nothing\n  is guaranteed. *)\nDefinition NoOrderGuarantees : LocalReordering := fun _ => fun _ => [].\n\n(** [Restore]: The output order is guaranteed to match some previous\n  ordering *)\nDefinition Restore (n : nat) : LocalReordering :=\n  fun e => fun _ => nth n e [].\n\n(** ** Special Edge Maps *)\n\n(** In some cases, we need to add certain extra edges to the graph to\n  capture non-local effects. *)\n\n(** In most cases, though, we don't need to add any special edges *)\nDefinition NoSpecialEdges : SpecialEdgeMap :=\n  fun _ _ _ => [].\n\n(** The store buffer only allows one outstanding unacknowledged store at a\n  time. *)\n\n(** ** Same Address *)\n(** *** Load  x -> Load  x (Locally) : Speculative Load Reordering *)\n\nFixpoint LoadCacheLineSpecialEdges\n  (n c : nat)\n  (e_before : list Event)\n  (e : Event)\n  (e_after : list Event)\n  : GlobalGraph :=\n  [((9 * c + 4, eiid e), (9 * c + 5, eiid e), \"LoadCacheLine\")].\n\nFixpoint SpeculativeLoadReorderingSpecialEdges\n  (n c : nat)\n  (e_before : list Event)\n  (e : Event)\n  (e_after : list Event)\n  : GlobalGraph :=\n  match e_after with\n  | h::t =>\n    match (dirn h, nat_compare (loc e) (loc h)) with\n    | (R, Eq) =>\n      ((4 + 9 * c, eiid e), (5 + 9 * c, eiid h), \"SLR\")\n      :: SpeculativeLoadReorderingSpecialEdges n c e_before e t\n    | _ => SpeculativeLoadReorderingSpecialEdges n c e_before e t\n    end\n  | _ => []\n  end.\n\nFixpoint LoadSpecialEdges\n  (n c : nat)\n  (e_before : list Event)\n  (e : Event)\n  (e_after : list Event)\n  : GlobalGraph :=\n  LoadCacheLineSpecialEdges n c e_before e e_after ++\n  SpeculativeLoadReorderingSpecialEdges n c e_before e e_after.\n\n(** *** Load  x -> Store x (Locally) : Load checks for entries <= ID in store buffer\n  Interpret FR edges as ``don't look at later stores'' *)\n(** *** Store x -> Load  x (Locally) : Stores check for ordering violations\n  When the store executes, squash the load if it already performed.\n  Store set predictors are here too. *)\n\nFixpoint StoreLoadSpecialEdges\n  (n c : nat)\n  (e_before : list Event)\n  (e : Event)\n  (e_after : list Event)\n  : GlobalGraph :=\n  match e_after with\n  | h::t =>\n    match (dirn h, nat_compare (loc e) (loc h)) with\n    | (R, Eq) => [((4 + 9 * c, eiid e), (3 + 9 * c, eiid h), \"StoreLoad\")]\n    | _ => StoreLoadSpecialEdges n c e_before e t\n    end\n  | _ => []\n  end.\n\n(** *** Store x -> Store x (Locally) : Store buffer ordered by pre-issue order\n  Performing location is rename, not execute!  SB slot reserved at rename! *)\n\n(** ** Different Address *)\n(** *** Load  x -> Load  y (Remotely) : Fails! *)\n(** *** Load  x -> Store y (Remotely) : Load -> In-order commit -> Store *)\n(** *** Store x -> Store y (Remotely) : Store buffer is one at a time *)\n\nFixpoint StoreBufferSpecialEdges\n  (n c : nat)\n  (e_before : list Event)\n  (e : Event)\n  (e_after : list Event)\n  : GlobalGraph :=\n  match e_after with\n  | h::t =>\n    match dirn h with\n    | R => StoreBufferSpecialEdges n c e_before e t\n    | W => [((9 * n + 1, eiid e), (9 * c + 7, eiid h), \"StoreBuffer\")]\n    end\n  | _ => []\n  end.\n\n(** * Pipeline Definition *)\n\n(** ** Pipeline Stages *)\n\n(** Each pipeline stage is defined by a name, a [LocalReordering],\n  and a function adding any special edges (in this case, only at the store\n  buffer). *)\n\nDefinition gem5_O3_PipelineStages n c := [\n  mkStage \"Fetch\"               FIFO                    NoSpecialEdges;\n  mkStage \"Decode\"              FIFO                    NoSpecialEdges;\n  mkStage \"Rename\"              FIFO                    NoSpecialEdges;\n  mkStage \"Issue\"               NoOrderGuarantees       NoSpecialEdges;\n  mkStage \"Execute\"             NoOrderGuarantees       NoSpecialEdges;\n  mkStage \"CacheLineInvalidate\" NoOrderGuarantees       NoSpecialEdges;\n  mkStage \"Writeback\"           NoOrderGuarantees       NoSpecialEdges;\n  mkStage \"Commit\"              (Restore (2 + 9 * c))   NoSpecialEdges;\n  mkStage \"StoreBuffer\"         FIFO                    (StoreBufferSpecialEdges n c)\n].\n    \nDefinition gem5_O3_MemoryHierarchyStages := [\n  mkStage \"L2CacheForWrites\"  NoOrderGuarantees NoSpecialEdges;\n  mkStage \"Retire\"            NoOrderGuarantees NoSpecialEdges\n].\n\nDefinition gem5_O3_AllStages n :=\n  fold_left (app (A:=_)) (map (gem5_O3_PipelineStages n) [0 ... n-1]) []\n  ++ gem5_O3_MemoryHierarchyStages.\n\nDefinition StagesOfCore\n  (c : nat)\n  (l : list nat)\n  : list nat :=\n  map (fun x => x + 9 * c) l.\n\n(** ** Pipeline Paths *)\n\nDefinition gem5_O3_PathOptions\n  (n : nat)\n  (e : Event)\n  : PathOptions :=\n  let c := proc (iiid e) in\n  match dirn e with\n  | R => [\n    mkPathOption (String.append \"Read\" (stringOfNat (loc e))) e\n      (StagesOfCore c [0 ... 4] ++ StagesOfCore c [6 ... 8])\n      [mkPerformStages (4 + 9 * c) [0 ... n-1] [0 ... n-1] (Some (5 + 9 * c)) true]\n      (LoadSpecialEdges n c)\n    ]\n  | W => [\n    mkPathOption (String.append \"Write\" (stringOfNat (loc e))) e\n      (StagesOfCore c [0 ... 4] ++ StagesOfCore c [6 ... 8] ++ StagesOfCore n [0; 1])\n      [mkPerformStages (2 + 9 * c) [c] [c] None false;\n       mkPerformStages (9 * n) [0 ... n-1] [0 ... n-1] None true]\n      (StoreLoadSpecialEdges n c)\n    ]\n  end.\n\n(** ** Pipeline Definition *)\n\nDefinition gem5_O3_Pipeline (n : nat) :=\n  mkPipeline\n    \"gem5_O3\"\n    (gem5_O3_AllStages n)\n    (gem5_O3_PathOptions n).\n\n", "meta": {"author": "daniellustig", "repo": "pipecheck", "sha": "7b70b585be8c0a946869e991f459c57c29f73c9b", "save_path": "github-repos/coq/daniellustig-pipecheck", "path": "github-repos/coq/daniellustig-pipecheck/pipecheck-7b70b585be8c0a946869e991f459c57c29f73c9b/gem5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17745938658167737}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import Hints.\nRequire Import Postcond.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire AssnMem.\nRequire AssnState.\nRequire Import Inject.\nRequire Import SoundBase.\nRequire Import SoundForgetStackCall.\nRequire Import SoundForgetMemoryCall.\nRequire Import SoundPostcondCmdAdd.\nRequire Import opsem_wf.\nRequire Import memory_props.\nRequire Import Exprs.\nImport OpsemPP.\n\nSet Implicit Arguments.\n\n\nLemma postcond_cmd_inject_event_call\n      m_src conf_src st0_src cmds_src\n      m_tgt conf_tgt st0_tgt cmds_tgt\n      id_src fun_src args_src noret_src clattrs_src typ_src varg_src\n      id_tgt fun_tgt args_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt\n      invst0 assnmem0 inv0\n      (CONF : AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE : AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (MEM : AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem0)\n      (CMDS_SRC: st0_src.(EC).(CurCmds) = (insn_call id_src noret_src clattrs_src typ_src varg_src fun_src args_src) :: cmds_src)\n      (CMDS_TGT: st0_tgt.(EC).(CurCmds) = (insn_call id_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt fun_tgt args_tgt) :: cmds_tgt)\n      (INJECT_EVENT: postcond_cmd_inject_event\n                       (insn_call id_src noret_src clattrs_src typ_src varg_src fun_src args_src)\n                       (insn_call id_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt fun_tgt args_tgt) inv0)\n  : <<NORET: noret_src = noret_tgt>> /\\\n    <<CLATTRS: clattrs_src = clattrs_tgt>> /\\\n    <<TYP: typ_src = typ_tgt>> /\\\n    <<VARG: varg_src = varg_tgt>> /\\\n    <<FUN:\n      forall funval2_src\n        (FUN_SRC: getOperandValue conf_src.(CurTargetData) fun_src st0_src.(EC).(Locals) conf_src.(Globals) = Some funval2_src),\n      exists funval1_tgt,\n        <<FUN_TGT: getOperandValue conf_tgt.(CurTargetData) fun_tgt st0_tgt.(EC).(Locals) conf_tgt.(Globals) = Some funval1_tgt>> /\\\n        <<INJECT: genericvalues_inject.gv_inject assnmem0.(AssnMem.Rel.inject) funval2_src funval1_tgt>>>> /\\\n  <<ARGS:\n    forall args2_src\n      (ARGS_SRC: params2GVs (conf_src.(CurTargetData))\n                            args_src st0_src.(EC).(Locals) conf_src.(Globals) = Some args2_src),\n    exists args1_tgt,\n      (<<ARGS_TGT: params2GVs (conf_tgt.(CurTargetData)) args_tgt\n                             st0_tgt.(EC).(Locals) conf_tgt.(Globals) = Some args1_tgt>>) /\\\n      (<<INJECT: list_forall2 (genericvalues_inject.gv_inject\n                                 assnmem0.(AssnMem.Rel.inject)) args2_src args1_tgt>>) /\\\n      (<<VALID_SRC: List.Forall (MemProps.valid_ptrs (Memory.Mem.nextblock st0_src.(Mem))) args2_src>>) /\\\n      (<<VALID_TGT: List.Forall (MemProps.valid_ptrs (Memory.Mem.nextblock st0_tgt.(Mem))) args1_tgt>>)\n        >>\n.\nProof.\n  ss. unfold is_true in *.\n  repeat (des_bool; des).\n  des_sumbool. subst.\n  esplits; auto.\n  { (* funval *)\n    i.\n    exploit AssnState.Rel.inject_value_spec; eauto.\n    { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n    i. des.\n    esplits; eauto.\n    erewrite <- AssnState.Unary.sem_valueT_physical. eauto.\n  }\n  { (* args *)\n    clear -CONF STATE MEM INJECT_EVENT0.\n    revert dependent args_tgt.\n    induction args_src.\n    - i. ss. des_ifs.\n      esplits; ss; econs.\n    - i. destruct args_tgt; ss.\n      destruct a as [[ty_s attr_s] val_s].\n      destruct p as [[ty_t attr_t] val_t].\n      repeat (des_bool; des).\n      des_sumbool. subst.\n\n      des_ifs; cycle 1.\n      + exploit IHargs_src; eauto. i. des. congruence.\n      + exploit AssnState.Rel.inject_value_spec; eauto.\n        { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n        rewrite AssnState.Unary.sem_valueT_physical. i. des. congruence.\n      + exploit IHargs_src; eauto. i. des.\n        esplits; eauto.\n        * clarify.\n          econs; eauto.\n          exploit AssnState.Rel.inject_value_spec; eauto.\n          { rewrite AssnState.Unary.sem_valueT_physical. eauto. }\n          rewrite AssnState.Unary.sem_valueT_physical. i. des. clarify.\n        * econs; eauto.\n          eapply get_operand_valid_ptr; eauto; try apply STATE; try apply MEM.\n        * rewrite Heq0 in *. clarify.\n          econs; eauto.\n          eapply get_operand_valid_ptr; eauto; try apply STATE; try apply MEM.\n  }\nQed.\n\nLemma postcond_cmd_add_lessdef_call\n      id noret clattrs typ varg funval args s\n  : postcond_cmd_add_lessdef (insn_call id noret clattrs typ varg funval args) s =\n    if noret then s else\n      Exprs.ExprPairSet.add\n        (Exprs.Expr.value (Exprs.ValueT.const (const_undef typ)),\n         Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, id)))\n        s\n.\nProof.\n  unfold postcond_cmd_add_lessdef, postcond_cmd_get_lessdef. ss.\n  destruct noret; eauto.\nQed.\n\nLemma postcond_cmd_add_noret_call\n      id_src fun_src args_src\n      id_tgt fun_tgt args_tgt\n      clattrs typ varg inv\n  : postcond_cmd_add (insn_call id_src true clattrs typ varg fun_src args_src)\n                     (insn_call id_tgt true clattrs typ varg fun_tgt args_tgt) inv =\n    reduce_maydiff inv.\nProof.\n  destruct inv. destruct src. destruct tgt. ss.\nQed.\n\nLemma postcond_cmd_add_ret_call\n      id_src fun_src args_src\n      id_tgt fun_tgt args_tgt\n      clattrs typ varg inv\n  : postcond_cmd_add (insn_call id_src false clattrs typ varg fun_src args_src)\n                     (insn_call id_tgt false clattrs typ varg fun_tgt args_tgt) inv =\n    reduce_maydiff\n      (Assertion.update_tgt\n         (Assertion.update_lessdef\n            (Exprs.ExprPairSet.add\n               (Exprs.Expr.value (Exprs.ValueT.const (const_undef typ)),\n                Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, id_tgt)))))\n         (Assertion.update_src\n            (Assertion.update_lessdef\n               (Exprs.ExprPairSet.add\n                  (Exprs.Expr.value (Exprs.ValueT.const (const_undef typ)),\n                   Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, id_src)))))\n                                     (remove_def_from_maydiff id_src id_tgt inv))).\nProof. ss. Qed.\n\nLemma updateAddAL_lessdef_undef\n      conf st invst assnmem gmax public inv\n      locals id gv typ\n      (LOCALS : updateAddAL GenericValue locals id gv = Locals (EC st))\n      (STATE : AssnState.Unary.sem conf st invst assnmem gmax public inv)\n      (CHUNK: exists mcs, flatten_typ conf.(CurTargetData) typ = Some mcs /\\ List.map snd gv = mcs)\n      gv_\n      (FIT: fit_gv conf.(CurTargetData) typ gv_ = Some gv)\n  : AssnState.Unary.sem conf st invst assnmem gmax public\n                       (Assertion.update_lessdef\n                          (Exprs.ExprPairSet.add\n                             (Exprs.Expr.value (Exprs.ValueT.const (const_undef typ)),\n                              Exprs.Expr.value (Exprs.ValueT.id (Exprs.Tag.physical, id))))\n                          inv).\nProof.\n  inv STATE. econs; eauto.\n  ii. ss. simpl_ep_set.\n  - solve_leibniz.\n    ss. esplits.\n    { unfold AssnState.Unary.sem_idT. ss.\n      rewrite <- LOCALS. apply lookupAL_updateAddAL_eq. }\n    exploit const2GV_undef; eauto. i. des.\n    { clarify. apply all_undef_lessdef_aux; eauto.\n      eapply fit_gv_undef_or_has_chunkb; eauto.\n    }\n  - apply LESSDEF; eauto.\nQed.\n\nLemma postcond_cmd_add_call\n      m_src conf_src st0_src retval1_src id_src fun_src args_src locals0_src\n      m_tgt conf_tgt st0_tgt retval1_tgt id_tgt fun_tgt args_tgt locals0_tgt\n      invst0 assnmem inv0\n      noret clattrs typ varg\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem inv0)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem)\n      (RETURN_SRC : return_locals (CurTargetData conf_src) retval1_src id_src noret typ locals0_src = Some st0_src.(EC).(Locals))\n      (RETURN_TGT : return_locals (CurTargetData conf_tgt) retval1_tgt id_tgt noret typ locals0_tgt = Some st0_tgt.(EC).(Locals))\n      (RETVAL : lift2_option (genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem)) retval1_src retval1_tgt)\n  : exists invst1,\n    <<STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst1 assnmem\n                              (postcond_cmd_add\n                                 (insn_call id_src noret clattrs typ varg fun_src args_src)\n                                 (insn_call id_tgt noret clattrs typ varg fun_tgt args_tgt) inv0)>>.\nProof.\n  unfold return_locals in *. des_ifs; ss.\n  - rewrite postcond_cmd_add_noret_call.\n    exploit SoundReduceMaydiff.reduce_maydiff_sound; eauto.\n  - rename H0 into LOCALS_TGT. rename H1 into LOCALS_SRC.\n    rewrite postcond_cmd_add_ret_call.\n    exploit SoundReduceMaydiff.reduce_maydiff_sound; try (by intro PR; exact PR); eauto.\n    unfold remove_def_from_maydiff.\n    des_ifs.\n    + instantiate (1:=invst0).\n      inv STATE.\n      econs; try by (eapply updateAddAL_lessdef_undef; eauto);\n        (eapply fit_gv_chunks_aux; eauto).\n      { ss. }\n      i. destruct id0 as []. ss.\n      rewrite Exprs.IdTSetFacts.remove_b in *.\n      des_bool. des.\n      * eauto.\n      * simtac. unfold Exprs.IdTSetFacts.eqb in *.\n        des_ifs.\n        unfold Exprs.IdT.lift in *. clarify.\n        solve_leibniz. clarify.\n        econs.\n        esplits.\n        { unfold AssnState.Unary.sem_idT. ss.\n          rewrite <- LOCALS_TGT.\n          apply lookupAL_updateAddAL_eq. }\n        { unfold AssnState.Unary.sem_idT in *. ss.\n          exploit genericvalues_inject.simulation__fit_gv; eauto.\n          { inv MEM. eauto. }\n          i. des.\n          inv CONF. inv INJECT.\n          rewrite TARGETDATA in *.\n          rewrite <- LOCALS_SRC in VAL_SRC.\n          rewrite lookupAL_updateAddAL_eq in VAL_SRC.\n          clarify.\n      }\n      * ss.\n    + inv STATE.\n      econs; [ | | | by eauto|];\n        ss; try by (eapply updateAddAL_lessdef_undef; eauto);\n        (eapply fit_gv_chunks_aux; eauto).\n  - rewrite postcond_cmd_add_noret_call.\n    exploit SoundReduceMaydiff.reduce_maydiff_sound; eauto.\nQed.\n\nLemma postcond_call_sound\n      m_src conf_src st0_src id_src noret_src clattrs_src typ_src varg_src fun_src args_src cmds_src\n      m_tgt conf_tgt st0_tgt id_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt fun_tgt args_tgt cmds_tgt\n      invst0 assnmem0 inv0 inv1\n      (CONF : AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (CMDS_SRC: st0_src.(EC).(CurCmds) = (insn_call id_src noret_src clattrs_src typ_src varg_src fun_src args_src) :: cmds_src)\n      (CMDS_TGT: st0_tgt.(EC).(CurCmds) = (insn_call id_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt fun_tgt args_tgt) :: cmds_tgt)\n      (POSTCOND:\n         postcond_cmd\n           (insn_call id_src noret_src clattrs_src typ_src varg_src fun_src args_src)\n           (insn_call id_tgt noret_tgt clattrs_tgt typ_tgt varg_tgt fun_tgt args_tgt)\n           inv0 = Some inv1)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (WF_SRC: wf_State conf_src st0_src)\n      (WF_TGT: wf_State conf_tgt st0_tgt)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem0)\n  :\n  <<NORET: noret_src = noret_tgt>> /\\\n  <<CLATTRS: clattrs_src = clattrs_tgt>> /\\\n  <<TYP: typ_src = typ_tgt>> /\\\n  <<VARG: varg_src = varg_tgt>> /\\\n  <<FUN:\n    forall funval2_src\n      (FUN_SRC: getOperandValue conf_src.(CurTargetData) fun_src st0_src.(EC).(Locals) conf_src.(Globals) = Some funval2_src),\n    exists funval1_tgt,\n      <<FUN_TGT: getOperandValue conf_tgt.(CurTargetData) fun_tgt st0_tgt.(EC).(Locals) conf_tgt.(Globals) = Some funval1_tgt>> /\\\n      <<INJECT: genericvalues_inject.gv_inject assnmem0.(AssnMem.Rel.inject) funval2_src funval1_tgt>>>> /\\\n  <<ARGS:\n    forall args2_src\n      (ARGS_SRC: params2GVs (conf_src.(CurTargetData))\n                            args_src st0_src.(EC).(Locals) conf_src.(Globals) = Some args2_src),\n    exists args1_tgt,\n      (<<ARGS_TGT: params2GVs (conf_tgt.(CurTargetData)) args_tgt\n                             st0_tgt.(EC).(Locals) conf_tgt.(Globals) = Some args1_tgt>>) /\\\n      (<<INJECT: list_forall2 (genericvalues_inject.gv_inject\n                                 assnmem0.(AssnMem.Rel.inject)) args2_src args1_tgt>>) /\\\n      (<<VALID_SRC: List.Forall (MemProps.valid_ptrs (Memory.Mem.nextblock st0_src.(Mem))) args2_src>>) /\\\n      (<<VALID_TGT: List.Forall (MemProps.valid_ptrs (Memory.Mem.nextblock st0_tgt.(Mem))) args1_tgt>>)\n        >> /\\\n  <<RETURN:\n    forall assnmem1 mem1_src mem1_tgt retval1_src retval1_tgt locals1_src\n      (INCR: AssnMem.Rel.le (AssnMem.Rel.lift st0_src.(Mem) st0_tgt.(Mem)\n                                            (memory_blocks_of conf_src st0_src.(EC).(Locals) inv0.(Assertion.src).(Assertion.unique))\n                                            (memory_blocks_of conf_tgt st0_tgt.(EC).(Locals) inv0.(Assertion.tgt).(Assertion.unique))\n                                            (memory_blocks_of_t conf_src st0_src invst0.(AssnState.Rel.src) inv0.(Assertion.src).(Assertion.private))\n                                            (memory_blocks_of_t conf_tgt st0_tgt invst0.(AssnState.Rel.tgt) inv0.(Assertion.tgt).(Assertion.private))\n                                            assnmem0) assnmem1)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt mem1_src mem1_tgt assnmem1)\n      (RETVAL: TODO.lift2_option (genericvalues_inject.gv_inject assnmem1.(AssnMem.Rel.inject)) retval1_src retval1_tgt)\n      (VALID: valid_retvals mem1_src mem1_tgt retval1_src retval1_tgt)\n      (RETURN_SRC: return_locals\n                     conf_src.(CurTargetData)\n                     retval1_src id_src noret_src typ_src\n                     st0_src.(EC).(Locals)\n                   = Some locals1_src),\n    exists locals2_tgt invst2 assnmem2,\n      <<RETURN_TGT: return_locals\n                      conf_tgt.(CurTargetData)\n                      retval1_tgt id_tgt noret_tgt typ_tgt\n                      st0_tgt.(EC).(Locals)\n                    = Some locals2_tgt>> /\\\n      <<INCR: AssnMem.Rel.le assnmem0 assnmem2>> /\\\n      <<STATE:\n        AssnState.Rel.sem\n          conf_src conf_tgt\n          (mkState (mkEC st0_src.(EC).(CurFunction)\n                         st0_src.(EC).(CurBB)\n                         cmds_src\n                         st0_src.(EC).(Terminator)\n                         locals1_src\n                         st0_src.(EC).(Allocas))\n                   st0_src.(ECS) mem1_src)\n          (mkState (mkEC st0_tgt.(EC).(CurFunction)\n                         st0_tgt.(EC).(CurBB)\n                         cmds_tgt\n                         st0_tgt.(EC).(Terminator)\n                         locals2_tgt\n                         st0_tgt.(EC).(Allocas))\n                   st0_tgt.(ECS) mem1_tgt)\n          invst2 assnmem2 inv1>> /\\\n      <<MEM: AssnMem.Rel.sem conf_src conf_tgt mem1_src mem1_tgt assnmem2>>>>.\nProof.\n  Local Opaque postcond_cmd_inject_event.\n  unfold postcond_cmd, postcond_cmd_check in *. ss.\n  rewrite <- (ite_spec noret_src None (Some id_src)) in *.\n  rewrite <- (ite_spec noret_tgt None (Some id_tgt)) in *.\n  des_ifs.\n  rewrite negb_false_iff in *.\n\n  exploit postcond_cmd_inject_event_Subset; eauto.\n  { etransitivity; [apply forget_stack_call_Subset|apply forget_memory_call_Subset]. }\n  i. des.\n\n  exploit postcond_cmd_inject_event_call; eauto. i. des. subst.\n  esplits; eauto. i.\n\n  exploit forget_memory_call_sound; try exact STATE; eauto.\n  i. des.\n\n  exploit forget_stack_call_sound; eauto.\n  { inv CONF. eauto. }\n  { rewrite CMDS_SRC. instantiate (1:= cmds_src). econs. apply sublist_refl. }\n  { rewrite CMDS_TGT. instantiate (1:= cmds_tgt). econs. apply sublist_refl. }\n  { apply forget_memory_call_unique_implies_private. }\n  { apply forget_memory_call_unique_implies_private. }\n  { rewrite MEM_INJ. eauto. }\n  i. des.\n\n  exploit postcond_cmd_add_call; eauto.\n  { rewrite MEM_INJ. eauto. }\n  i. des.\n\n  esplits; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SoundPostcondCall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.17727186406596618}}
{"text": "Require Import VST.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 VST.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.\nassert (M1: Int.modulus = 4294967296) by reflexivity.\nassert (HM1: Int.half_modulus = 2147483648) by reflexivity.\nassert (iWS:Int.iwordsize = Int.repr 32) by reflexivity.\nassert (X: Int.unsigned (Int.repr 32) = 32). apply Int.unsigned_repr. rewrite int_max_unsigned_eq; omega.\nassert (zWS: Int.zwordsize = 32) by reflexivity.\nspecialize (Int.unsigned_range c); intros Y.\ndestruct (Int.ltu c Int.iwordsize) eqn:?H.\n  Focus 2. {\n    apply ltu_false_inv in H0.\n    change (Int.unsigned Int.iwordsize) with 32 in H0.\n    unfold Int.signed in H.\n    destruct (zlt (Int.unsigned c) Int.half_modulus); omega.\n  } Unfocus.\ndestruct (Int.ltu (Int.sub (Int.repr 32) c) Int.iwordsize) eqn:?H.\n  Focus 2. {\n    apply ltu_false_inv in H1.\n    unfold Int.sub in H1.\n    change (Int.unsigned (Int.repr 32)) with 32 in H1.\n    change (Int.unsigned Int.iwordsize) with 32 in H1.\n    unfold Int.signed in H.\n    rewrite Int.unsigned_repr in H1.\n    + destruct (zlt (Int.unsigned c) Int.half_modulus); omega.\n    + rewrite int_max_unsigned_eq.\n      destruct (zlt (Int.unsigned c) Int.half_modulus); omega.\n  } Unfocus.\nTime forward. (*8.8*)   \n{\n  entailer!.\n  rewrite H0, H1; simpl; auto.\n}\nunfold Int.signed in H.\ndestruct (zlt (Int.unsigned c) Int.half_modulus); [| omega].\nentailer!.\nunfold sem_shift; simpl. rewrite H0, H1; simpl.\nunfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\nrewrite Z.mod_small; simpl; try omega.\nunfold Int.sub.\nrewrite Int.and_mone, X, Int.unsigned_repr; trivial.\nrewrite int_max_unsigned_eq; omega.\nTime Qed. (*0.1*)\n(*\nLemma L32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_L32 L32_spec.\nProof.\nstart_function. forward.\ndestruct (Int.ltu c Int.iwordsize) eqn:?H.\n  Focus 2. {\n    apply ltu_false_inv in H0.\n    change (Int.unsigned Int.iwordsize) with 32 in H0.\n    omega.\n  } Unfocus.\n  destruct (Int.ltu (Int.sub (Int.repr 32) c) Int.iwordsize) eqn:?H.\n  Focus 2. {\n    apply ltu_false_inv in H1.\n    unfold Int.sub in H1.\n    change (Int.unsigned (Int.repr 32)) with 32 in H1.\n    rewrite Int.unsigned_repr in H1 by rep_omega.\n    change (Int.unsigned Int.iwordsize) with 32 in H1.\n    omega.\n  } Unfocus.\nTime forward. (*8.8*)  \n{\n  entailer!.\n<<<<<<< HEAD\n  rewrite H0, H1; simpl; auto.\n  split3; auto.\n  unfold Int.signed.\n  if_tac. rep_omega. repable_signed.\n=======\n  rewrite H0, H1; simpl; auto. intuition. omega.\n>>>>>>> master\n}\nentailer!.\nassert (W: Int.zwordsize = 32). reflexivity.\nassert (U: Int.unsigned Int.iwordsize=32). reflexivity.\nunfold sem_shift; simpl. rewrite H0, H1; simpl.\nunfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\nrewrite Z.mod_small, W; simpl; try omega.\nunfold Int.sub.\nrewrite Int.and_mone.\nchange (Int.unsigned (Int.repr 32)) with 32.\nrewrite Int.unsigned_repr by rep_omega.\nauto.\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\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  assert (HH: 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          = Byte.unsigned (Znth i [b0; b1; b2; b3; c0; c1; c2; c3] Byte.zero)).\n  solve [ erewrite <- (Znth_map' Byte.unsigned) with (d:= Z.zero); [ reflexivity | apply I ] ].\n  forward. \n  + entailer!. rewrite HH. \n    rewrite Int.unsigned_repr. apply Byte.unsigned_range_2. apply Byte_unsigned_range_32.\n  + simpl; rewrite HH. forward.\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    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  rewrite if_true; trivial.\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        myadmit. (*!! typecheck_error (invalid_cast_result tuchar tuchar)*)\n        solve [entailer!]. \n  Time forward. entailer. myadmit. (*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. myadmit.  myadmit.  myadmit.  myadmit.  myadmit.\n    myadmit.  myadmit.  myadmit.  myadmit.  myadmit. }\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. myadmit.  myadmit.  myadmit.  myadmit.  myadmit.\n    myadmit.  myadmit.  myadmit.  myadmit.  myadmit. }\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. myadmit.\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. myadmit.\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!. myadmit. (*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. myadmit. (*typecheck_error (invalid_cast_result tuchar tuchar)*) }\n\n  forward. entailer. simpl. myadmit. (*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": "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_ld_st.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.17727185570655818}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base reg mem pagetable mailbox base_extra.\nFrom HypVeri Require Import machine_extra lifting rules.rules_base.\nFrom HypVeri.lang Require Import lang_extra reg_extra.\n\nSection mov.\n\nContext `{hypparams: HypervisorParameters}.\nContext `{vmG: !gen_VMG \u03a3}.\n\nLemma mov_word {E i w1 w3 q s p_tx} a w2 ra :\n  decode_instruction w1 = Some (Mov ra (inl w2)) ->\n  (tpa a) \u2208 s ->\n  (tpa a) \u2260 p_tx ->\n  {SS{{ \u25b7 (PC @@ i ->r a)\n        \u2217 \u25b7 (a ->a w1)\n        \u2217 \u25b7 (i -@{ q }A> s)\n        \u2217 \u25b7 TX@ i := p_tx\n        \u2217 \u25b7 (ra @@ i ->r w3)}}}\n    ExecI @ i ; E\n  {{{ RET (false, ExecI);  (PC @@ i ->r (a ^+ 1)%f)\n                           \u2217 (a ->a w1)\n                           \u2217 (i -@{ q }A> s)\n                           \u2217 TX@ i := p_tx\n                           \u2217 ra @@ i ->r w2 }}}.\nProof.\n  iIntros (Hdecode Hin Hnottx \u03d5) \"( >Hpc & >Hapc & >Hacc & >Htx & >Hra) H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  iDestruct \"H\u03c3\" as \"(H1 & Hmem & Hreg & Hmb & ? & ? & Haccess & H2)\".\n  pose proof (decode_instruction_valid w1 _ Hdecode) as Hvalidinstr.\n  inversion Hvalidinstr as [imm dst Hvalidra | | | | | | | | | | |].\n  subst imm dst.\n  inversion Hvalidra as [HneqPC HneqNZ].\n  (* valid regs *)\n  iDestruct ((gen_reg_valid2 i PC a ra w3 Hcur) with \"Hreg Hpc Hra\") as \"[%HPC %Hra]\".\n  (* valid pt *)  \n  iDestruct (access_agree_check_true _ i with \"Haccess Hacc\") as %Hacc;eauto.\n  iDestruct (mb_valid_tx i p_tx with \"Hmb Htx\") as %Htx.\n  subst p_tx.\n  (* valid mem *)\n  iDestruct (gen_mem_valid a w1 with \"Hmem Hapc\") as \"%Hmem\".\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    eapply (reducible_normal i _ a w1); eauto.\n  - (* step *)\n    iModIntro.\n    iIntros (m2 \u03c32) \"[%P PAuth] %HstepP\".\n    eapply (step_ExecI_normal i _ a w1) in HstepP;eauto.\n    remember (exec _ \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec (mov_word_ExecI \u03c31 ra _ HneqPC HneqNZ) /update_incr_PC /update_reg in Heqc2.\n    destruct HstepP; subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    rewrite p_upd_pc_mem p_upd_reg_mem.\n    all: try rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    all: try rewrite p_upd_pc_trans p_upd_reg_trans //.\n    all: try rewrite p_upd_pc_mb p_upd_reg_mb //.\n    rewrite Hcur. iFrame.\n    (* updated part *)\n    rewrite -> (u_upd_pc_regs _ i a 1); eauto.\n    + rewrite u_upd_reg_regs.\n      iDestruct ((gen_reg_update2_global PC i a (a ^+ 1)%f ra i w3 w2 ) with \"Hreg Hpc Hra\") as \">[Hreg [pc ra]]\"; eauto.\n      iModIntro.\n      iFrame \"Hreg\".\n      iSplitL \"PAuth\".\n      by iExists P.\n      rewrite /just_scheduled_vms /just_scheduled.\n      assert (filter\n                (\u03bb id : vmid,\n                        base.negb (scheduled \u03c31 id) &&\n                        scheduled (update_offset_PC (update_reg_global \u03c31 i ra w2) 1) id = true)\n                (seq 0 n) = []) as ->.\n      {\n        rewrite /scheduled /machine.scheduler //= /scheduler Hcur.\n        rewrite p_upd_pc_current_vm p_upd_reg_current_vm.\n        rewrite Hcur.\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      iSplitL \"\";first done.\n      assert ((scheduled (update_offset_PC (update_reg_global \u03c31 i ra w2) 1) i) = true) as ->.\n      {\n        rewrite /scheduled /machine.scheduler //= /scheduler.\n        rewrite p_upd_pc_current_vm p_upd_reg_current_vm.\n        rewrite Hcur.\n        by case_bool_decide.\n      }\n      simpl.\n      iApply \"H\u03d5\".\n      iFrame \"Hapc Hacc pc ra Htx\".\n    + rewrite u_upd_reg_regs.\n      repeat solve_reg_lookup.\n      intros Q; symmetry in Q; inversion Q; contradiction.\n    Qed.\n\nLemma mov_reg {E i w1 w3 q s p_tx} a w2 ra rb :\n  decode_instruction w1 = Some (Mov ra (inr rb)) ->\n  (tpa a) \u2208 s ->\n  (tpa a) \u2260 p_tx ->\n  {SS{{  \u25b7 (PC @@ i ->r a)\n         \u2217 \u25b7 (a ->a w1)\n         \u2217 \u25b7 (i -@{ q }A> s)\n         \u2217 \u25b7 (TX@ i := p_tx)\n         \u2217 \u25b7 (ra @@ i ->r w2)\n         \u2217 \u25b7 (rb @@ i ->r w3) }}}\n    ExecI @ i ;E\n  {{{ RET (false, ExecI); PC @@ i ->r (a ^+ 1)%f\n                   \u2217 a ->a w1\n                   \u2217 i -@{ q }A> s\n                   \u2217 TX@ i := p_tx\n                   \u2217 ra @@ i ->r w3\n                   \u2217 rb @@ i ->r w3}}}.\nProof.\n  iIntros (Hdecode Hin Hnottx \u03d5) \"(>Hpc & >Hapc & >Hacc & >tx & >Hra & >Hrb) H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  pose proof (decode_instruction_valid w1 _ Hdecode) as Hvalidinstr.\n  inversion Hvalidinstr as [ | src dst Hvalidra Hvalidrb Hneqrarb | | | | | | | | | |] .\n  subst src dst.\n  inversion Hvalidra as [ HneqPCa HneqNZa ].\n  inversion Hvalidrb as [ HneqPCb HneqNZb ].\n  iDestruct \"H\u03c3\" as \"(Htok & Hmem & Hreg & Hmb & ? & ? & Haccess & ?)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid3 i PC a ra w2 rb w3 Hcur) with \"Hreg Hpc Hra Hrb\") as \"[%HPC [%Hra %Hrb]]\".\n  (* valid pt *)\n  iDestruct (access_agree_check_true _ i with \"Haccess Hacc\") as %Hacc;eauto.\n  iDestruct (mb_valid_tx i p_tx with \"Hmb tx\") as %Htx.\n  subst p_tx.\n  (* valid mem *)\n  iDestruct (gen_mem_valid a w1 with \"Hmem Hapc\") as \"%Hmem\".\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    eapply (reducible_normal i _ a w1);eauto.\n  - (* step *)\n    iModIntro.\n    iIntros (m2 \u03c32) \"[%P PAuth] %HstepP\".\n    eapply (step_ExecI_normal i _ a w1) in HstepP;eauto.\n    remember (exec _ \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec (mov_reg_ExecI \u03c31 ra rb w3 HneqPCa HneqNZa HneqPCb HneqNZb Hrb)  /update_incr_PC /update_reg  in Heqc2.\n    destruct HstepP;subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    rewrite p_upd_pc_mem p_upd_reg_mem.\n    all: try rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    all: try rewrite p_upd_pc_trans p_upd_reg_trans //.\n    all: try rewrite p_upd_pc_mb p_upd_reg_mb //.\n    rewrite Hcur. iFrame.\n    (* updated part *)\n    rewrite -> (u_upd_pc_regs _ i a 1);eauto.\n    + rewrite u_upd_reg_regs.\n      iDestruct ((gen_reg_update2_global PC i a (a ^+ 1)%f ra i w2 w3 ) with \"Hreg Hpc Hra\") as \">(Hreg & pc & ra)\";eauto.\n      iModIntro.\n      iFrame \"Hreg\".\n      iSplitL \"PAuth\".\n      by iExists P.\n      iSplitL \"\".\n      rewrite /just_scheduled_vms /just_scheduled.\n      assert (filter\n                (\u03bb id : vmid,\n                        base.negb (scheduled \u03c31 id) &&\n                        scheduled (update_offset_PC (update_reg_global \u03c31 i ra w3) 1) id = true)\n                (seq 0 n) = []) as ->.\n      {\n        rewrite /scheduled /machine.scheduler //= /scheduler Hcur.\n        rewrite p_upd_pc_current_vm p_upd_reg_current_vm.\n        rewrite Hcur.\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      assert ((scheduled (update_offset_PC (update_reg_global \u03c31 i ra w3) 1) i) = true) as ->.\n      {\n        rewrite /scheduled /machine.scheduler //= /scheduler.\n        rewrite p_upd_pc_current_vm p_upd_reg_current_vm.\n        rewrite Hcur.\n        by case_bool_decide.\n      }\n      simpl.\n      iApply \"H\u03d5\".\n      by iFrame \"Hapc Hacc Hrb ra pc\".\n    + rewrite u_upd_reg_regs.\n      repeat solve_reg_lookup.\n      intros P'; symmetry in P';inversion P'; contradiction.\nQed.\n\nEnd mov.\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/mov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.17725814257121117}}
{"text": "(*\n * \u00a9 2020 XXX.\n * \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     ModelCheck\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require 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 ShareSecretSymmetricEncProtocol.\n\n  (* User ids *)\n  Notation USR1 := 0.\n  Notation USR2 := 1.\n  \n  Section IW_Simple.\n    Import IdealWorld.\n\n    Notation perms_CH := 0.\n    Notation CH := (Single perms_CH).\n\n    Notation empty_chs := (#0 #+ (CH, [])).\n\n    Definition PERMS := $0 $+ (perms_CH, {| read := true; write := true |}).\n\n    Definition simple_users :=\n      [\n        (mkiUsr USR1 PERMS \n                (\n                  n <- Gen\n                  ; _ <- Send (Content n) CH\n                  ; @Return (Base Nat) n\n        ));\n        (mkiUsr USR2 PERMS\n                ( m <- @Recv Nat CH\n                ; @Return (Base Nat) (extractContent m)))\n        ].\n\n    Definition simple_univ_start :=\n      mkiU empty_chs simple_users.\n\n  End IW_Simple.\n\n  Section IW.\n    Import IdealWorld.\n\n    Notation pCH12 := 0.\n    Notation pCH21 := 1.\n    Notation CH12  := (# pCH12).\n    Notation CH21  := (# pCH21).\n\n    Notation empty_chs := (#0 #+ (CH12, []) #+ (CH21, [])).\n\n    Notation PERMS1 := ($0 $+ (pCH12, owner) $+ (pCH21, reader)).\n    Notation PERMS2 := ($0 $+ (pCH12, reader) $+ (pCH21, owner)).\n\n    Notation ideal_users :=\n      [\n        (mkiUsr USR1 PERMS1 \n                ( chid <- CreateChannel\n                  ; _ <- Send (sharePerm chid writer) CH12\n                  ; m <- @Recv Access (chid #& pCH21)\n                  ; n <- Gen\n                  ; _ <- Send (Content n) (getPerm m #& pCH12)\n                  ; @Return (Base Nat) n\n        )) ;\n      (mkiUsr USR2 PERMS2\n              ( m <- @Recv Access CH12\n                ; chid <- CreateChannel\n                ; _ <- Send (sharePerm chid owner) (getPerm m #& pCH21)\n                ; m <- @Recv Nat (chid #& pCH12)\n                ; @Return (Base Nat) (extractContent m)\n      ))\n      ].\n\n    Definition ideal_univ_start :=\n      mkiU empty_chs ideal_users.\n\n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    Notation KID1 := 0.\n    Notation KID2 := 1.\n\n    Notation KEYS := [ skey KID1 ; skey KID2 ].\n\n    Notation KEYS1 := ($0 $+ (KID1, true) $+ (KID2, false)).\n    Notation KEYS2 := ($0 $+ (KID1, false) $+ (KID2, true)).\n\n    Definition real_users :=\n      [\n        MkRUserSpec USR1 KEYS1\n                    ( kp <- GenerateKey AsymKey Encryption\n                      ; c1 <- Sign KID1 USR2 (sharePubKey kp)\n                      ; _  <- Send USR2 c1\n                      ; c2 <- @Recv Access (SignedEncrypted KID2 (fst kp) true)\n                      ; m  <- Decrypt c2\n                      ; n  <- Gen\n                      ; c3 <- SignEncrypt KID1 (getKey m) USR2 (message.Content n)\n                      ; _  <- Send USR2 c3\n                      ; @Return (Base Nat) n) ;\n\n      MkRUserSpec USR2 KEYS2\n                  ( c1 <- @Recv Access (Signed KID1 true)\n                    ; v  <- Verify KID1 c1\n                    ; kp <- GenerateKey SymKey Encryption\n                    ; c2 <- SignEncrypt KID2 (getKey (snd v)) USR1 (sharePrivKey kp)\n                    ; _  <- Send USR1 c2\n                    ; c3 <- @Recv Nat (SignedEncrypted KID1 (fst kp) true)\n                    ; m  <- Decrypt c3\n                    ; @Return (Base Nat) (extractContent m) )\n      ].\n\n    Definition real_univ_start :=\n      mkrU (mkKeys KEYS) real_users.\n  End RW.\n\n  #[export] Hint Unfold\n       simple_univ_start\n       ideal_univ_start\n       real_univ_start\n    : user_build.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with user_build; simpl) : core.\n  \nEnd ShareSecretSymmetricEncProtocol.\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/protocols/ShareSecretProtocolSymmetricEnc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17722765639388435}}
{"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(** The RTL intermediate language: abstract syntax and semantics.\n  RTL stands for \"Register Transfer Language\". This is the first\n  intermediate language after Cminor and CminorSel.\n*)\n\nRequire Import Coqlib Maps.\nRequire Import AST Integers Values Events Memory Globalenvs Smallstep.\nRequire Import Op Registers RTL.\n\n(** * Abstract syntax *)\n\n(** RTLMach is almost same as RTL, the only difference here is we use\n    the memory opration [record_frame_mach] to record new frame instead\n    of [record_frame_vm] which is used in all semantics before.\n    This new opration calculates only the first framesize of a tailcall\n    stage to give the whole stack consumption after a record operation.\n    Which is precisely the machine deals with tailcalls.\n*)\n\nSection ORACLE.\n\nVariable fn_stack_requirements : ident -> Z.\n\nSection RELSEM.\n\nVariable ge: genv.\n(** The transitions are presented as an inductive predicate\n  [step ge st1 t st2], where [ge] is the global environment,\n  [st1] the initial state, [st2] the final state, and [t] the trace\n  of system calls performed during this transition. *)\n\nInductive step: state -> trace -> state -> Prop :=\n  | exec_Inop:\n      forall s f sp pc rs m pc',\n      (fn_code f)!pc = Some(Inop pc') ->\n      step (State s f sp pc rs m)\n        E0 (State s f sp pc' rs m)\n  | exec_Iop:\n      forall s f sp pc rs m op args res pc' v,\n      (fn_code f)!pc = Some(Iop op args res pc') ->\n      eval_operation ge sp op rs##args m = Some v ->\n      step (State s f sp pc rs m)\n        E0 (State s f sp pc' (rs#res <- v) m)\n  | exec_Iload:\n      forall s f sp pc rs m chunk addr args dst pc' a v,\n      (fn_code f)!pc = Some(Iload chunk addr args dst pc') ->\n      eval_addressing ge sp addr rs##args = Some a ->\n      Mem.loadv chunk m a = Some v ->\n      step (State s f sp pc rs m)\n        E0 (State s f sp pc' (rs#dst <- v) m)\n  | exec_Istore:\n      forall s f sp pc rs m chunk addr args src pc' a m',\n      (fn_code f)!pc = Some(Istore chunk addr args src pc') ->\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 pc rs m)\n        E0 (State s f sp pc' rs m')\n  | exec_Icall:\n      forall s f sp pc rs m sig ros args res pc' fd id,\n      ros_is_ident ros rs id ->\n      (fn_code f)!pc = Some(Icall sig ros args res pc') ->\n      find_function ge ros rs = Some fd ->\n      funsig fd = sig ->\n      step (State s f sp pc rs m)\n        E0 (Callstate (Stackframe res f sp pc' rs :: s) fd rs##args m id)\n  | exec_Itailcall:\n      forall s f stk pc rs m sig ros args fd m' id m'' m''',\n      ros_is_ident ros rs id ->\n      (fn_code f)!pc = Some(Itailcall sig ros args) ->\n      find_function ge ros rs = Some fd ->\n      funsig fd = sig ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      Mem.return_frame m' = Some m'' ->\n      Mem.pop_stage m'' = Some m''' ->\n      step (State s f (Vptr stk Ptrofs.zero) pc rs m)\n        E0 (Callstate s fd rs##args m''' id)\n  | exec_Ibuiltin:\n      forall s f sp pc rs m ef args res pc' vargs t vres m',\n      (fn_code f)!pc = Some(Ibuiltin ef args res pc') ->\n      eval_builtin_args ge (fun r => rs#r) sp m args vargs ->\n      external_call ef ge vargs m t vres m' ->\n      step (State s f sp pc rs m)\n         t (State s f sp pc' (regmap_setres res vres rs) m')\n  | exec_Icond:\n      forall s f sp pc rs m cond args ifso ifnot b pc',\n      (fn_code f)!pc = Some(Icond cond args ifso ifnot) ->\n      eval_condition cond rs##args m = Some b ->\n      pc' = (if b then ifso else ifnot) ->\n      step (State s f sp pc rs m)\n        E0 (State s f sp pc' rs m)\n  | exec_Ijumptable:\n      forall s f sp pc rs m arg tbl n pc',\n      (fn_code f)!pc = Some(Ijumptable arg tbl) ->\n      rs#arg = Vint n ->\n      list_nth_z tbl (Int.unsigned n) = Some pc' ->\n      step (State s f sp pc rs m)\n        E0 (State s f sp pc' rs m)\n  | exec_Ireturn:\n      forall s f stk pc rs m or m' m'' m''',\n      (fn_code f)!pc = Some(Ireturn or) ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      Mem.return_frame m' = Some m'' ->\n      Mem.pop_stage m'' = Some m''' ->\n      step (State s f (Vptr stk Ptrofs.zero) pc rs m)\n        E0 (Returnstate s (regmap_optget or Vundef rs) m''')\n  | exec_function_internal:\n      forall s f args m m' m'' m''' stk id path,\n      Mem.alloc_frame m id = (m',path) ->\n      Mem.alloc m' 0 f.(fn_stacksize) = (m'', stk) ->\n      Mem.record_frame (Mem.push_stage m'')(Memory.mk_frame (fn_stack_requirements id)) = Some m''' ->\n      step (Callstate s (Internal f) args m id)\n        E0 (State s\n                  f\n                  (Vptr stk Ptrofs.zero)\n                  f.(fn_entrypoint)\n                  (init_regs args f.(fn_params))\n                  m''')\n  | exec_function_external:\n      forall s ef args res t m m' sz,\n      external_call ef ge args m t res m' ->\n      step (Callstate s (External ef) args m sz)\n         t (Returnstate s res m')\n  | exec_return:\n      forall res f sp pc rs s vres m,\n      step (Returnstate (Stackframe res f sp pc rs :: s) vres m)\n        E0 (State s f sp pc (rs#res <- vres) m).\n\nLemma exec_Iop':\n  forall s f sp pc rs m op args res pc' rs' v,\n  (fn_code f)!pc = Some(Iop op args res pc') ->\n  eval_operation ge sp op rs##args m = Some v ->\n  rs' = (rs#res <- v) ->\n  step (State s f sp pc rs m)\n    E0 (State s f sp pc' rs' m).\nProof.\n  intros. subst rs'. eapply exec_Iop; eauto.\nQed.\n\nLemma exec_Iload':\n  forall s f sp pc rs m chunk addr args dst pc' rs' a v,\n  (fn_code f)!pc = Some(Iload chunk addr args dst pc') ->\n  eval_addressing ge sp addr rs##args = Some a ->\n  Mem.loadv chunk m a = Some v ->\n  rs' = (rs#dst <- v) ->\n  step (State s f sp pc rs m)\n    E0 (State s f sp pc' rs' m).\nProof.\n  intros. subst rs'. eapply exec_Iload; eauto.\nQed.\n\nEnd RELSEM.\n\n(** Execution of whole programs are described as sequences of transitions\n  from an initial state to a final state.  An initial state is a [Callstate]\n  corresponding to the invocation of the ``main'' function of the program\n  without arguments and with an empty call stack. *)\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b f m0 m1 b0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      funsig f = signature_main ->\n      Mem.alloc m0 0 0 = (m1,b0) ->\n      initial_state p (Callstate nil f nil m1 (prog_main p)).\n\n(** A final state is a [Returnstate] with an empty call stack. *)\n\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall r m,\n      final_state (Returnstate nil (Vint r) m) r.\n\n(** The small-step semantics for a program. *)\n\nDefinition semantics (p: program) :=\n  Semantics step (initial_state  p) final_state (Genv.globalenv p).\n\n(** This semantics is receptive to changes in events. *)\n\nLemma semantics_receptive:\n  forall (p: program), receptive (semantics p).\nProof.\n  intros. constructor; simpl; intros.\n(* receptiveness *)\n  assert (t1 = E0 -> exists s2, step (Genv.globalenv p) s t2 s2).\n    intros. subst. inv H0. exists s1; auto.\n  inversion H; subst; auto.\n  exploit external_call_receptive; eauto. intros [vres2 [m2 EC2]].\n  exists (State s0 f sp pc' (regmap_setres res vres2 rs) m2). econstructor; eauto.\n  exploit external_call_receptive; eauto. intros [vres2 [m2 EC2]].\n  exists (Returnstate s0 vres2 m2). econstructor; eauto.\n(* trace length *)\n  red; intros; inv H; simpl; try lia.\n  eapply external_call_trace_length; eauto.\n  eapply external_call_trace_length; eauto.\nQed.\n\n(** * Operations on RTL abstract syntax *)\n\n(** Transformation of a RTL function instruction by instruction.\n  This applies a given transformation function to all instructions\n  of a function and constructs a transformed function from that. *)\nEnd ORACLE.\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/RTLmach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.17722765639388433}}
{"text": "Require Import VST.sepcomp.semantics.\n\nRequire Import VST.veric.Clight_base.\nRequire Import VST.veric.Clight_core.\nRequire Import VST.veric.Clight_lemmas.\nRequire Import VST.sepcomp.step_lemmas.\nRequire Import VST.sepcomp.event_semantics.\nRequire Import VST.veric.SeparationLogic.\nRequire Import VST.veric.juicy_extspec.\nRequire Import VST.veric.juicy_mem.\nRequire VST.veric.NullExtension.\n(*Require Import VST.veric.Clight_sim.*)\nRequire Import VST.veric.SeparationLogicSoundness.\nRequire Import VST.sepcomp.extspec.\nRequire Import VST.msl.msl_standard.\n\nImport VericSound.\nImport VericMinimumSeparationLogic.\nImport VericMinimumSeparationLogic.CSHL_Def.\nImport VericMinimumSeparationLogic.CSHL_Defs.\nImport Clight.\n\nDefinition ignores_juice Z (J: external_specification juicy_mem external_function Z) : Prop :=\n  (forall e t b tl vl x jm jm',\n     m_dry jm = m_dry jm' ->\n    ext_spec_pre J e t b tl vl x jm ->\n    ext_spec_pre J e t b tl vl x jm') /\\\n (forall ef t b ot v x jm jm',\n     m_dry jm = m_dry jm' -> \n    ext_spec_post J ef t b ot v x jm ->\n    ext_spec_post J ef t b ot v x jm') /\\\n (forall v x jm jm',\n     m_dry jm = m_dry jm' -> \n     ext_spec_exit J v x jm ->\n     ext_spec_exit J v x jm').\n\nImport VST.veric.compcert_rmaps.R.\n\nDefinition mem_evolve (m m': mem) : Prop :=\n   (* dry version of resource_decay *)\n forall loc,\n match access_at m loc Cur, access_at m' loc Cur with\n | None, None => True\n | None, Some Freeable => True\n | Some Freeable, None => True\n | Some Writable, Some p' => p' = Writable\n | Some p, Some p' => p=p' /\\ access_at m loc Max = access_at m' loc Max\n | _, _ => False\n end.\n\nInstance mem_evolve_refl : RelationClasses.Reflexive mem_evolve.\nProof.\n  repeat intro.\n  destruct (access_at x loc Cur); auto.\n  destruct p; auto.\nQed.\n\nDefinition ext_spec_mem_evolve (Z: Type) \n  (D: external_specification mem external_function Z) :=\n forall ef w b tl vl ot v z m z' m',\n    ext_spec_pre D ef w b tl vl z m ->\n    ext_spec_post D ef w b ot v z' m' ->\n    mem_evolve m m'.\n\nDefinition juicy_dry_ext_spec (Z: Type)\n   (J: external_specification juicy_mem external_function Z)\n   (D: external_specification mem external_function Z)\n   (dessicate: forall ef jm, ext_spec_type J ef -> ext_spec_type D ef) :=\n  (forall e t t' b tl vl x jm,\n    dessicate e jm t = t' ->\n    (ext_spec_pre J e t b tl vl x jm ->\n    ext_spec_pre D e t' b tl vl x (m_dry jm))) /\\\n (forall ef t t' b ot v x jm0 jm,\n    (exists tl vl x0, dessicate ef jm0 t = t' /\\ ext_spec_pre J ef t b tl vl x0 jm0) ->\n    (level jm <= level jm0)%nat ->\n    resource_at (m_phi jm) = resource_fmap (approx (level jm)) (approx (level jm)) oo juicy_mem_lemmas.rebuild_juicy_mem_fmap jm0 (m_dry jm) ->\n    ghost_of (m_phi jm) = Some (ghost_PCM.ext_ghost x, compcert_rmaps.RML.R.NoneP) :: ghost_fmap (approx (level jm)) (approx (level jm)) (tl (ghost_of (m_phi jm0))) ->\n    (ext_spec_post D ef t' b ot v x (m_dry jm) ->\n     ext_spec_post J ef t b ot v x jm)) /\\\n (forall v x jm,\n     ext_spec_exit J v x jm <->\n     ext_spec_exit D v x (m_dry jm)).\n\nDefinition juicy_dry_ext_spec_make (Z: Type) \n   (J: external_specification juicy_mem external_function Z) :\n   external_specification mem external_function Z.\ndestruct J.\napply Build_external_specification with ext_spec_type.\nintros e t b tl vl x m.\napply (forall jm, m_dry jm = m -> (* external ghost matches x -> *) ext_spec_pre e t b tl vl x jm).\nintros e t b ot v x m.\napply (forall jm, m_dry jm = m -> ext_spec_post e t b ot v x jm).\nintros v x m.\napply (forall jm, m_dry jm = m -> ext_spec_exit v x jm).\nDefined.\n\n\nDefinition dessicate_id Z \n   (J: external_specification juicy_mem external_function Z) :\n   forall ef (jm : juicy_mem), ext_spec_type J ef -> \n       ext_spec_type (juicy_dry_ext_spec_make Z J) ef.\nintros.\ndestruct J; simpl in *. apply X.\nDefined.\n\nLemma jdes_make_lemma:\n  forall Z J, ignores_juice Z J ->\n    juicy_dry_ext_spec Z J (juicy_dry_ext_spec_make Z J)\n     (dessicate_id Z J).\nProof.\nintros.\ndestruct H as [? [? ?]], J; split; [ | split3]; simpl in *; intros; auto.\n-\nsubst t'.\neapply H. symmetry; eassumption.  auto.\n-\ndestruct H2 as (? & ? & ? & ? & ?).\nsubst t'.\neapply H0; auto.\n-\neapply H1. symmetry; eassumption. auto.\nQed.\n\nDefinition mem_rmap_cohere m phi :=\n  contents_cohere m phi /\\\n  access_cohere m phi /\\\n  max_access_cohere m phi /\\ alloc_cohere m phi.\n\nLemma age_to_cohere:\n forall m phi n,\n    mem_rmap_cohere m phi -> mem_rmap_cohere m (age_to.age_to n phi).\nProof.\nintros.\ndestruct H as [? [? [? ?]]].\nsplit; [ | split3]; hnf; intros.\n-\nhnf in H.\nrewrite age_to_resource_at.age_to_resource_at in H3.\ndestruct (phi @ loc) eqn:?H; inv H3.\ndestruct (H _ _ _ _ _ H4); split; subst; auto.\n-\nrewrite age_to_resource_at.age_to_resource_at .\nspecialize (H0 loc).\nrewrite H0.\ndestruct (phi @ loc); simpl; auto.\n-\nrewrite age_to_resource_at.age_to_resource_at .\nspecialize (H1 loc).\ndestruct (phi @ loc); simpl; auto.\n-\nrewrite age_to_resource_at.age_to_resource_at .\nspecialize (H2 loc H3).\nrewrite H2.\nreflexivity.\nQed.\n\nLemma set_ghost_cohere:\n forall m phi g H,\n    mem_rmap_cohere m phi -> \n   mem_rmap_cohere m (initial_world.set_ghost phi g H).\nProof.\nintros.\nunfold initial_world.set_ghost.\nrename H into Hg. rename H0 into H.\ndestruct H as [? [? [? ?]]].\nsplit; [ | split3]; hnf; intros.\n-\nhnf in H.\nrewrite resource_at_make_rmap in H3.\ndestruct (phi @ loc) eqn:?H; inv H3.\ndestruct (H _ _ _ _ _ H4); split; subst; auto.\n-\nrewrite resource_at_make_rmap.\nspecialize (H0 loc).\nrewrite H0.\ndestruct (phi @ loc); simpl; auto.\n-\nrewrite resource_at_make_rmap.\nspecialize (H1 loc).\ndestruct (phi @ loc); simpl; auto.\n-\nrewrite resource_at_make_rmap.\nspecialize (H2 loc H3).\nrewrite H2.\nreflexivity.\nQed.\n\nLemma mem_evolve_cohere:\n  forall jm m' phi',\n   mem_evolve (m_dry jm) m' ->\n   compcert_rmaps.RML.R.resource_at phi' =\n     juicy_mem_lemmas.rebuild_juicy_mem_fmap jm m' ->\n   mem_rmap_cohere m' phi'.\nProof.\nintros.\ndestruct jm.\nsimpl in *.\nunfold  juicy_mem_lemmas.rebuild_juicy_mem_fmap in H0.\nsimpl in H0.\nsplit; [ | split3].\n-\nhnf; intros; specialize (H loc).\nrewrite (JMaccess loc) in *.\nrewrite H0 in *; clear H0; simpl in *.\ndestruct (phi @ loc) eqn:?H.\nsimpl in H. if_tac in H.\nif_tac in H1.\ninv H1; auto.\ninv H1.\nif_tac in H1.\ninv H1; auto.\ninv H1.\ndestruct k; simpl in *.\ndestruct (perm_of_sh sh0) as [[ | | | ] | ] eqn:?H; try contradiction ;auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try contradiction; try discriminate; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\nif_tac in H1; inv H1; auto.\ninv H1; auto.\ninv H1; auto.\ninv H1; auto.\n-\nhnf; intros; specialize (H loc).\nrewrite H0; clear H0.\nrewrite (JMaccess loc) in *.\ndestruct (phi @ loc) eqn:?H.\nsimpl in H. if_tac in H.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ] eqn:?H; try contradiction; try discriminate; simpl; auto.\nunfold perm_of_sh. rewrite if_true by auto. rewrite if_true by auto. auto.\nsubst. rewrite if_true by auto; auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ] eqn:?H; try contradiction; try discriminate; simpl; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\nrewrite if_false by auto; auto.\ndestruct k; simpl in *; auto.\ndestruct (perm_of_sh sh) as [[ | | | ] | ] eqn:?H; try contradiction ;auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\nsimpl. rewrite if_true; auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\nelimtype False; clear - r H1.\nunfold perm_of_sh in H1. if_tac in H1. if_tac in H1; inv H1.\nrewrite if_true in H1 by auto. inv H1.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\nunfold perm_of_sh in H1. if_tac in H1. if_tac in H1; inv H1.\nrewrite if_true in H1 by auto. inv H1.\nunfold perm_of_sh in H1. if_tac in H1. if_tac in H1; inv H1.\nrewrite if_true in H1 by auto.\ninv H1.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ]  eqn:?H; try solve [contradiction]; try discriminate; auto.\nsimpl in H; destruct H; discriminate.\nsimpl in H; destruct H; discriminate.\nsimpl in H; destruct H; discriminate.\n-\nhnf; intros; specialize (H loc).\nrewrite H0; clear H0.\nrewrite (JMaccess loc) in *.\ndestruct (phi @ loc) eqn:?H.\nsimpl in H. if_tac in H.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ] eqn:?H; try contradiction; try discriminate; simpl; auto.\neapply perm_order''_trans; [apply access_cur_max | ].\nrewrite H2.\nunfold perm_of_sh. rewrite if_true by auto. rewrite if_true by auto. constructor.\nsubst sh. rewrite if_true by auto.\napply po_None.\ndestruct (access_at m' loc Cur) as [[ | | | ] | ] eqn:?H; try contradiction; try discriminate; simpl; auto.\ndestruct H; discriminate.\ndestruct H; discriminate.\ndestruct H; discriminate.\nrewrite if_false by auto.\neapply perm_order''_trans; [apply access_cur_max | ].\nrewrite H2. constructor.\ndestruct k; simpl in *; auto.\ndestruct (perm_of_sh sh) as [[ | | | ] | ] eqn:?H; try contradiction ;auto.\neapply perm_order''_trans; [apply access_cur_max | ].\ndestruct (access_at m' loc Cur). destruct H; subst.\nmatch goal with |- Mem.perm_order'' _ ?A =>\n  destruct A; try constructor\nend.\nsimpl.\nrewrite if_true by auto. auto.\neapply perm_order''_trans; [apply access_cur_max | ].\ndestruct (access_at m' loc Cur). destruct H; subst.\nrewrite if_true. simpl. rewrite H1. apply perm_refl.\nclear - r H1.\nunfold perm_of_sh in H1.\nif_tac in H1. if_tac in H1. inv H1; constructor.\ninv H1; constructor.\nrewrite if_true in H1 by auto. inv H1; constructor.\ncontradiction.\neapply perm_order''_trans; [apply access_cur_max | ].\ndestruct (access_at m' loc Cur). destruct H; subst.\nrewrite if_true. simpl. rewrite H1. apply perm_refl.\nclear - r H1.\nunfold perm_of_sh in H1.\nif_tac in H1. if_tac in H1. inv H1; constructor.\ninv H1; constructor.\nrewrite if_true in H1 by auto. inv H1; constructor.\ncontradiction.\neapply perm_order''_trans; [apply access_cur_max | ].\ndestruct (access_at m' loc Cur). destruct H; subst.\nrewrite if_true. simpl. rewrite H1. apply perm_refl.\nclear - r H1.\nunfold perm_of_sh in H1.\nif_tac in H1. if_tac in H1. inv H1; constructor.\ninv H1; constructor.\nrewrite if_true in H1 by auto. inv H1; constructor.\ncontradiction.\neapply perm_order''_trans; [apply access_cur_max | ].\ndestruct (access_at m' loc Cur). destruct p0; try contradiction.\nmatch goal with |- Mem.perm_order'' _ ?A =>\n  destruct A; try constructor\nend.\nelimtype False.\nclear - H1 r.\nunfold perm_of_sh in H1.\nif_tac in H1. if_tac in H1. inv H1; constructor.\ninv H1; constructor.\nrewrite if_true in H1 by auto. inv H1; constructor.\ndestruct (access_at m' loc Cur); try contradiction.\ndestruct H; subst p0.\nspecialize (JMmax_access loc).\nrewrite H0 in JMmax_access.\nsimpl in JMmax_access.\nunfold max_access_at in *.\nrewrite <- H1. auto.\ndestruct (access_at m' loc Cur); try contradiction.\ndestruct H; subst p0.\nspecialize (JMmax_access loc).\nrewrite H0 in JMmax_access.\nsimpl in JMmax_access.\nunfold max_access_at in *.\nrewrite <- H1. auto.\nsimpl in H.\ndestruct (access_at m' loc Cur); try contradiction.\ndestruct H; subst.\nsimpl.\nspecialize (JMmax_access loc).\nrewrite H0 in JMmax_access.\nsimpl in JMmax_access.\nunfold max_access_at in *.\nrewrite <- H1. auto.\n-\nhnf; intros; specialize (H loc).\nrewrite H0; clear H0.\nspecialize (JMalloc loc).\nrewrite (JMaccess loc) in *.\ndestruct (phi @ loc) eqn:?H.\nsimpl in H. if_tac in H.\ndestruct loc as [b z]. \nrewrite nextblock_access_empty in *by auto.\nsubst.\nsimpl.\nf_equal. apply proof_irr.\ndestruct loc as [b z]. \nrewrite nextblock_access_empty in * by auto.\ncontradiction.\ndestruct loc as [b z]. \nrewrite nextblock_access_empty in * by auto.\nsimpl.\ndestruct k; auto; try contradiction H.\nsimpl in H.\ndestruct loc as [b z]. \nrewrite nextblock_access_empty in * by auto.\ncontradiction.\nQed.\n\nLemma whole_program_sequential_safety_ext:\n   forall {CS: compspecs} {Espec: OracleKind} (initial_oracle: OK_ty) \n     (EXIT: semax_prog.postcondition_allows_exit Espec tint)\n     (dryspec: ext_spec OK_ty)\n     (dessicate : forall (ef : external_function) jm,\n               ext_spec_type OK_spec ef ->\n               ext_spec_type dryspec ef)\n     (JDE: juicy_dry_ext_spec _ (@JE_spec OK_ty OK_spec) dryspec dessicate)\n     (DME: ext_spec_mem_evolve _ dryspec)\n     prog V G m,\n     @semax_prog Espec (*NullExtension.Espec*) CS prog initial_oracle V G ->\n     Genv.init_mem prog = Some m ->\n     exists b, exists q,\n       Genv.find_symbol (Genv.globalenv prog) (prog_main prog) = Some b /\\\n       initial_core  (cl_core_sem (globalenv prog))\n           0 m q m (Vptr b Ptrofs.zero) nil /\\\n       forall n,\n        @dry_safeN _ _ _ OK_ty (semax.genv_symb_injective)\n            (cl_core_sem (globalenv prog))\n            (*(dryspec  OK_ty)*) dryspec\n            (Build_genv (Genv.globalenv prog) (prog_comp_env prog)) \n             n initial_oracle q m.\nProof.\n intros.\n destruct (@semax_prog_rule Espec CS _ _ _ _ \n     0 (*additional temporary argument - TODO (Santiago): FIXME*)\n     initial_oracle EXIT H H0) as [b [q [[H1 H2] H3]]].\n destruct (H3 O) as [jmx [H4x [H5x [H6x [H7x _]]]]].\n destruct (H2 jmx H4x) as [jmx' [H8x H8y]].\n exists b, q. (* , (m_dry jmx'). *)\n split3; auto.\n rewrite H4x in H8y. auto.\n subst. simpl. clear H5x H6x H7x H8y.\n forget (m_dry jmx) as m. clear jmx.\n intro n.\n specialize (H3 n).\n destruct H3 as [jm [? [? [? [? _]]]]].\n unfold semax.jsafeN in H6.\n subst m.\n assert (joins (compcert_rmaps.RML.R.ghost_of (m_phi jm))\n   (Some (ghost_PCM.ext_ref initial_oracle, compcert_rmaps.RML.R.NoneP) :: nil)) as J.\n { destruct (compcert_rmaps.RML.R.ghost_of (m_phi jm)); inv H5.\n   eexists; constructor; constructor.\n   instantiate (1 := (_, _)); constructor; simpl; constructor; auto.\n   instantiate (1 := (Some _, _)); repeat constructor; simpl; auto. }\n clear - JDE DME H4 J H6.\n  rewrite <- H4 in H6|-*.\n assert (level jm <= n)%nat by lia.\n clear H4; rename H into H4.\n forget initial_oracle as ora.\n revert ora jm q H4 J H6; induction n; simpl; intros.\n assert (level (m_phi jm) = 0%nat) by lia. rewrite H; constructor.\n inv H6.\n - constructor.\n -\n   rewrite <- level_juice_level_phi in H4.\n   destruct H0 as (?&?&?&Hg).\n   eapply safeN_step.\n   + red. red. fold (globalenv prog). eassumption.\n   + destruct (H1 (Some (ghost_PCM.ext_ref ora, compcert_rmaps.RML.R.NoneP) :: nil)) as (m'' & J'' & (? & ? & ?) & ?); auto.\n     { eexists; apply join_comm, core_unit. }\n     { rewrite Hg.\n       destruct J; eexists; apply compcert_rmaps.RML.ghost_fmap_join; eauto. }\n     replace (m_dry m') with (m_dry m'') by auto.\n     change (level (m_phi jm)) with (level jm) in *.\n     replace n0 with (level m'') by lia.\n     apply IHn; auto. lia.\n     replace (level m'') with n0 by lia. auto.\n -\n   destruct dryspec as [ty pre post exit]. simpl in *. (* subst ty. *)\n   destruct JE_spec as [ty' pre' post' exit']. simpl in *.\n   change (level (m_phi jm)) with (level jm) in *.\n   destruct JDE as [JDE1 [JDE2 JDE3]].\n   specialize (JDE1 e x (dessicate e jm x)); simpl in JDE1.\n   eapply safeN_external.\n     eassumption.\n     apply JDE1. reflexivity. assumption.\n     simpl. intros.\n     assert (H20: exists jm', m_dry jm' = m' \n                      /\\ (level jm' = n')%nat\n                      /\\ juicy_safety.pures_eq (m_phi jm) (m_phi jm')\n                      /\\ resource_at (m_phi jm') = resource_fmap (approx (level jm')) (approx (level jm')) oo juicy_mem_lemmas.rebuild_juicy_mem_fmap jm (m_dry jm')\n                      /\\ compcert_rmaps.RML.R.ghost_of (m_phi jm') = Some (ghost_PCM.ext_ghost z', compcert_rmaps.RML.R.NoneP) :: ghost_fmap (approx (level jm')) (approx (level jm')) (tl (ghost_of (m_phi jm)))). {\n     destruct (juicy_mem_lemmas.rebuild_juicy_mem_rmap jm m') \n            as [phi [? [? ?]]].\n     assert (own.ghost_approx phi (Some (ghost_PCM.ext_ghost z', NoneP) :: tl (compcert_rmaps.RML.R.ghost_of phi)) =\n        Some (ghost_PCM.ext_ghost z', NoneP) :: tl (compcert_rmaps.RML.R.ghost_of phi)) as Happrox.\n     { simpl; f_equal.\n        rewrite <- compcert_rmaps.RML.ghost_of_approx at 2.\n        destruct (compcert_rmaps.RML.R.ghost_of phi); auto. }\n     set (phi1 := initial_world.set_ghost _ _ Happrox).\n     assert (level phi1 = level phi /\\ resource_at phi1 = resource_at phi) as [Hl1 Hr1].\n     { subst phi1; unfold initial_world.set_ghost; rewrite level_make_rmap, resource_at_make_rmap; auto. }\n     pose (phi' := age_to.age_to n' phi1).\n     assert (mem_rmap_cohere m' phi'). {\n       clear - H1 Hr1 Hl1 H8 H7 H6 H3 DME JDE1.\n       apply JDE1 in H1; [ | reflexivity].\n       specialize (DME e _ _ _ _ _ _ _ _ _ _ H1 H6).\n     subst phi'.\n     apply age_to_cohere.\n     subst phi1.\n     apply set_ghost_cohere.\n     eapply mem_evolve_cohere; eauto.\n   }\n    destruct H10 as [H10 [H11 [H12 H13]]].\n     pose (jm' := mkJuicyMem _ _ H10 H11 H12 H13).\n     exists jm'.\n     split; [ | split3].\n     subst jm'; simpl; auto.\n     subst jm' phi'; simpl. apply age_to.level_age_to. lia.\n     hnf. split. intro loc. subst jm' phi'. simpl.\n     rewrite age_to_resource_at.age_to_resource_at.\n     rewrite Hr1, H8. unfold juicy_mem_lemmas.rebuild_juicy_mem_fmap.\n     destruct (m_phi jm @ loc); auto. rewrite age_to.level_age_to by lia.\n      reflexivity.\n     intro loc. subst jm' phi'. simpl.\n     rewrite age_to_resource_at.age_to_resource_at.\n     rewrite Hr1, H8. unfold juicy_mem_lemmas.rebuild_juicy_mem_fmap; simpl.\n     destruct (m_phi jm @ loc); auto.\n     if_tac; simpl; auto. destruct k; simpl; auto. if_tac; simpl; eauto. simpl; eauto.\n     subst jm' phi'. simpl m_phi.\n     rewrite age_to_resource_at.age_to_ghost_of.\n     subst phi1.\n     split.\n     extensionality; unfold compose; simpl.\n     rewrite age_to_resource_at.age_to_resource_at, age_to.level_age_to by lia.\n     unfold initial_world.set_ghost; rewrite resource_at_make_rmap.\n     rewrite H8; auto.\n     unfold initial_world.set_ghost; rewrite ghost_of_make_rmap; simpl.\n     rewrite age_to.level_age_to, H9 by (rewrite level_make_rmap; lia); simpl; auto.\n   }\n   destruct H20 as [jm'  [H26 [H27 [H28 [H29 Hg']]]]].\n   specialize (H2 ret jm' z' n' Hargsty Hretty).\n   spec H2. lia.\n    spec H2. hnf; split3; auto. lia.\n  spec H2.\n  eapply JDE2; eauto 6. lia. subst m'. apply H6.\n  destruct H2 as [c' [H2a H2b]]; exists c'; split; auto.\n  hnf in H2b.\n  specialize (H2b (Some (ghost_PCM.ext_ref z', compcert_rmaps.RML.R.NoneP) :: nil)).\n  spec H2b. apply join_sub_refl.\n  spec H2b.\n  { rewrite Hg'.\n    eexists (Some (ghost_PCM.ext_both z', compcert_rmaps.RML.R.NoneP) :: _);\n      repeat constructor.  }\n  destruct H2b as [jm'' [? [? ?]]].\n  destruct H7 as [? [? ?]].\n  subst m'. rewrite <- H7.\n  specialize (IHn  z' jm'' c').\n  subst n'. rewrite <- H9.\n  change (level (m_phi jm'')) with (level  jm'') in IHn.\n  apply IHn. lia.\n  auto.\n  rewrite H9; auto.\n - eapply safeN_halted; eauto.\n    apply JDE. auto.\n Unshelve. simpl. split; [apply Share.nontrivial | hnf]. exists None; constructor.\nQed.\n\nRequire Import VST.veric.juicy_safety.\n\nDefinition fun_id (ext_link: Strings.String.string -> ident) (ef: external_function) : option ident :=\n  match ef with EF_external id sig => Some (ext_link id) | _ => None end.\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/SequentialClight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.1772276538491074}}
{"text": "Require Import CertiGraph.lib.Coqlib.\nRequire Export VST.floyd.proofauto.\nRequire Import CertiGraph.mark.env_mark_bi.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.graph.path_lemmas.\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.DagBi_Mark.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.mark.spatial_graph_bi_mark.\nRequire Import VST.msl.wand_frame.\nRequire Import VST.floyd.reassoc_seq.\nRequire Import VST.floyd.field_at_wand.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\nLocal Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\n(* Using unit for DE and DG, inspired by Graph *)\nNotation dag sh x g := (@reachable_dag_vertices_at _ _ _ _ _ _ unit unit _ mpred (@SGP pSGG_VST bool unit (sSGG_VST sh)) (SGA_VST sh) x g).\nNotation Graph := (@Graph pSGG_VST bool unit unit).\nExisting Instances MGS biGraph maGraph finGraph RGF.\n\nDefinition mark_spec :=\n DECLARE _mark\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (weak_valid g x)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (dag sh x g)\n  POST [ Tvoid ]\n      EX g': Graph,\n        PROP (mark x g g')\n        LOCAL()\n        SEP (dag sh x g').\n\nDefinition main_spec :=\n DECLARE _main\n  WITH u : globals\n  PRE  [] main_pre prog tt u\n  POST [ tint ] main_post prog u.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mark_spec ; main_spec]).\n\nLemma dag_local_facts: forall sh x (g: Graph), weak_valid g x -> dag sh x g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. destruct H.\n  - simpl in H. subst x. entailer!.\n  - destruct (vgamma g x) as [[d l] r] eqn:?.\n    pose proof (@root_unfold _ (sSGG_VST sh) g x d l r H Heqp); clear -H0.\n    simpl in *. rewrite H0. entailer!.\nQed.\n\nLemma body_mark: semax_body Vprog Gprog f_mark mark_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as dlr eqn:?H.\n  destruct dlr as [[d l] r].\n  rename H0 into H_GAMMA_g; symmetry in H_GAMMA_g.\n  rename H into H_weak_valid.\n\n  forward_if  (* if (x == 0) *)\n    (PROP  (pointer_val_val x <> nullval)\n     LOCAL (temp _x (pointer_val_val x))\n     SEP   (dag sh x g)).\n  - apply denote_tc_test_eq_split. 2: entailer!. apply dag_local_facts; auto.\n  - (* return *) forward. Exists g. entailer!. destruct x. 1: simpl in H; inversion H. apply (mark_null_refl g).\n  - (* skip *) forward. entailer!.\n  - Intros. assert (vvalid g x) as gx_vvalid. {\n      destruct H_weak_valid; [| auto].\n      unfold is_null_SGBA in H0; simpl in H0; subst x.\n      exfalso. apply H. auto.\n    } assert (isptr (pointer_val_val x) /\\ exists b i, x = ValidPointer b i). {\n      destruct x. 2: exfalso; apply H; reflexivity. split; simpl; auto.\n      exists b, i. reflexivity.\n    } destruct H0 as [? [b [i ?]]]. clear H0 H_weak_valid.\n    pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n    simpl in H0. simpl reachable_dag_vertices_at.\n    erewrite H0 by eauto. Intros.\n    change (vertex_at x (d, l, r)) with\n        (@data_at CompSpecs sh node_type\n                  (Vint (Int.repr (if d then 1 else 0)), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)).\n    forward. (* root_mark = x -> m; *)\n    eapply semax_pre with\n        (PROP  ()\n               LOCAL\n               (temp _root_mark (Vint (Int.repr (if d then 1 else 0)));\n                temp _x (pointer_val_val x))\n               SEP  (dag sh x g)).\n    1: { pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n         simpl in H2. simpl reachable_dag_vertices_at.\n         erewrite H2 by eauto; simpl vertex_at; entailer!.\n         }\n    forward_if  (* if (root_mark == 1) *)\n      (PROP (d = false)\n            LOCAL (temp _x (pointer_val_val x))\n            SEP (dag sh x g)).\n    + forward. (* return *) Exists g. entailer!.\n      eapply (mark_vgamma_true_refl g); eauto.\n      now destruct d.\n    + forward. (* skip; *) entailer!.\n      now destruct d.\n    +\n      pose proof (@root_unfold _ (sSGG_VST sh) g x d l r gx_vvalid).\n      simpl in H2. simpl reachable_dag_vertices_at.\n      erewrite H2 by eauto.\n      Intros. subst d.\n      change (vertex_at x (false, l, r)) with\n          (@data_at CompSpecs sh node_type\n                    (Vint (Int.repr 0), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)).\n      forward. (* l = x -> l; *) 1: entailer!; destruct l; simpl; auto.\n      forward. (* r = x -> r; *) 1: entailer!; destruct r; simpl; auto.\n      forward. (* x -> d = 1; *)\n      pose proof Graph_vgen_true_mark1 g x _ _ H_GAMMA_g gx_vvalid.\n      apply semax_pre with\n          (PROP  ()\n                 LOCAL (temp _r (pointer_val_val r);\n                        temp _l (pointer_val_val l);\n                        temp _x (pointer_val_val x))\n                 SEP (dag sh x (Graph_vgen g x true))).\n      1: { pose proof (@root_update_unfold _ (sSGG_VST sh) g).\n           simpl in H4. simpl reachable_dag_vertices_at.\n           erewrite H4 by eauto; simpl vertex_at; entailer!. }\n           forget (Graph_vgen g x true) as g1.\n      assert (weak_valid g1 l) by (eapply left_weak_valid; eauto).\n      (* mark(l); *)\n      localize [dag sh l g1].\n      forward_call (sh, g1, l).\n      Intros g2.\n      unlocalize [dag sh x g2] using g2 assuming H5.\n      1: { subst.\n           pose proof (@dag_ramify_left _ (sSGG_VST sh) g g1 (ValidPointer b i) l r gx_vvalid H_GAMMA_g H3).\n           simpl reachable_dag_vertices_at in *.\n           eapply H1.\n      }\n       assert (weak_valid g2 r) by (eapply right_weak_valid; eauto).\n      (* mark(r); *)\n      localize [dag sh r g2].\n      forward_call (sh, g2, r).\n      Intros g3.\n      unlocalize [dag sh x g3] using g3 assuming H7.\n      1: { subst.\n           pose proof (@dag_ramify_right _ (sSGG_VST sh) g\n                         _ _ _ _ _ gx_vvalid H_GAMMA_g H3 H5).\n           simpl reachable_dag_vertices_at in *; eapply H1.\n           }\n      (* ( return; ) *)\n      Exists g3. entailer!.\n      apply (mark1_mark_left_mark_right g g1 g2 g3 (ValidPointer b i) l r); auto.\nQed. (* Original: 114 seconds; VST 2.*: 2.739 secs *)\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/mark/verif_mark_bi_dag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.17722765024389237}}
{"text": "From ITree Require Import\n     Subevent\n     Indexed.Sum.\n\nFrom CTree Require Import\n     CTree\n     Interp.Interp\n     Equ\n     SBisim\n     Core.Utils.\n\nFrom ExtLib Require Import\n     Monad\n     Traversable\n     RelDec.\n\nFrom Coq Require Import\n     Vector     \n     Fin (* fin definition here *)\n     Program.Equality\n     Program.Basics\n     Classes.Morphisms\n     Classes.RelationClasses\n     Lia.\n\nFrom Equations Require Import\n     Equations.\n\nFrom DSL Require Import\n     System\n     Utils\n     Vectors\n     Ltac.\n\nFrom Coinduction Require Import\n     rel coinduction tactics.\n\nImport EquNotations.\nImport MonadNotation.\nImport ProperNotations.\nImport SBisimNotations.\n\nLocal Open Scope monad_scope.\nLocal Open Scope vector_scope.\nLocal Open Scope fin_vector_scope.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\n(** Network *)\nModule Network(S: Systems).\n  Module Messaging := Messaging(S).\n  Module Storage := Storage(S).\n  Export Monads Storage Messaging S.\n\n  Notation InitSys n E R := (vec n (ctree E R)) (only parsing).\n  Notation Sys n E R := (vec n (Task n E R)) (only parsing).\n  Notation SysLeaf n R := (option (vec n (R * queue n))) (only parsing).\n  Notation SysTree n E R := (ctree E (SysLeaf n R)) (only parsing).\n\n  Equations get_running{E A m n}(v: vec m (Task n E A))\n            (i: fin (num_running v)): (fin m * ctree E A * queue n) :=\n    get_running ((Running _ _) :: ts) (FS k) :=\n      let '(i, a, q) := get_running ts k in (FS i, a, q);\n    get_running ((Done _ _) :: ts) k :=\n      let '(i, a, q) := get_running ts k in (FS i, a, q);\n    get_running ((Blocked _ _) :: ts) k :=\n      let '(i, a, q) := get_running ts k in (FS i, a, q);\n    get_running ((Running a q) :: ts) F1 := (F1, a ,q).\n\n  (** Blocking processes might cause a deadlock, in which case we return 'None'\n      or `Some (vec n _)` (every agent returned)\n   *)\n  Equations schedule_network_0 {E A m n} (a: vec m (Task n E A))\n            (H: num_running a = 0): option (vec m (A * queue n)) :=\n    schedule_network_0 [] _ := Some [];\n    schedule_network_0 ((Done r q)::ts) _ :=\n      option_map (fun l => (r, q) :: l) (schedule_network_0 ts _);\n    schedule_network_0 ((Blocked _ _)::ts) _ := None.\n\n  Equations schedule_one{R: Type}{E: Type -> Type}{n: nat}\n            (schedule: Sys n (Net n +' E) R -> SysTree n E R)\n            (sys: Sys n (Net n +' E) R)\n            (r: fin (num_running sys)) : SysTree n E R :=\n    schedule_one schedule sys r with get_running sys r => {\n        schedule_one _ _ _ (i, a, q) with observe a => {\n          (** Returns a value *)\n          schedule_one _ _ _ _ (RetF v) :=\n            TauI (schedule (sys @ i := Done v q));\n        \n          (** A previous choice, traverse it *)\n          schedule_one _ _ _ _ (ChoiceF b n' k) :=\n            Choice b n' (fun i' => schedule (sys @ i := Running (k i') q));\n\n          (** A network `send` effect, interpet it! *)\n          schedule_one _ _ _ _ (VisF (inl1 (Send m)) k) with (sys $ principal m)=>{\n            (** Deliver to running *)\n            schedule_one _ _ _ (i, _, _) _ (Running c q) :=\n              let msg' := {| principal := i; payload := payload m |} in\n              let sys' := sys @ i := Running (k tt) q in\n              let recp := principal m in\n              TauI (schedule (sys' @ recp := Running c (List.cons msg' q)));\n            \n            (** Deliver to blocked processes and unblock them *)\n            schedule_one _ _ _ (i, _, _) _ (Blocked c q) :=\n              let msg' := {| principal := i; payload := payload m |} in\n              let sys' := sys @ i := Running (k tt) q in\n              let recp := principal m in\n              TauI (schedule (sys' @ recp := Running c (List.cons msg' q)));\n            \n            (** Do not deliver to Done processes *)\n            schedule_one _ _ _ (i, _, _) _ (Done _ _) :=\n            TauI (schedule (sys @ i := Running (k tt) q))\n          };\n\n          (** Receive a message *)\n          schedule_one _ _ _ _ (VisF (inl1 Recv) k) with last q => {\n            (** Pop the msg from the end *)\n            schedule_one _ _ _ (i, _, _) _ (Some msg) :=\n              TauI (schedule (sys @ i := Running (k msg) (init q)));\n            (** Becomes blocked if no messages in q *)\n            schedule_one _ _ _ (i, _, _) _ None :=\n              TauI (schedule (sys @ i := Blocked a q))\n          };\n\n          (** Broadcast a message to everyone *)\n          schedule_one _ _ _ _ (VisF (inl1 (Broadcast b)) k) :=\n            let msg := {| principal := i; payload := b |} in\n            let sys' := map (fun a => match a with\n                                      | Running a q => Running a (List.cons msg q)\n                                      | Done a q => Done a q\n                                      | Blocked a q => Running a (List.cons msg q)\n                                      end) sys in \n            TauI (schedule (sys' @ i := Running (k tt) q));\n              \n          (** Some other downstream effect *)\n          schedule_one _ _ _ _ (VisF (inr1 e) k) :=\n            TauI (schedule (sys @ i := Running (trigger e >>= k) q))\n        }\n      }.\n  (** TODO: NON-det version \n      sys'' <- mapT (fun a: list Msg * itree Net R =>\n      let (q', a') := a in\n      CTrees.choiceV2\n      (CTrees.Ret (msg :: q', a'))\n      (CTrees.Ret (q', a'))) sys';;\n      \n      CTrees.TauV (schedule sys'' done)\n   *)\n\n  Definition schedule_network{R: Type}{E}{n: nat}\n             (schedule: Sys n (Net n +' E) R -> SysTree n E R)\n             (sys: Sys n (Net n +' E) R): SysTree n E R :=\n    match num_running sys as n1 return\n          (num_running sys = n1 -> SysTree n E R) with\n    | 0 => fun Hnr: num_running sys = 0 =>\n             Ret (schedule_network_0 sys Hnr)\n    | S n1 => fun Hnr: num_running sys = S n1 =>\n                r <- choice false (num_running sys) ;;\n                schedule_one schedule sys r\n    end eq_refl.\n  \n  CoFixpoint schedule {R: Type}{E: Type -> Type}{n: nat} :=\n    @schedule_network R E n schedule.\n\n  Lemma rewrite_schedule: forall n R E (s: Sys n (Net n +' E) R),\n      schedule s \u2245 schedule_network schedule s.\n  Proof.\n    intros.\n    __step_equ.\n    eauto.\n  Qed.\n\n  Typeclasses eauto := 6.\n\n  Transparent schedule.\n  Transparent schedule_one.\n  Transparent schedule_network_0.\n  Transparent get_running.\n  Transparent vector_replace.\n\n  (** Evaluates Net *)\n  Definition run_network{E R n} (s: InitSys n (Net n +' E) R): SysTree n E R :=\n    schedule (Vector.map (fun it => Running it List.nil) s).\n\n  #[global] Instance sbisim_clos_network_goal{n E R}:\n    Proper (sbisim ==> eq ==> sbisim) (fun h ts => @run_network E R (S n) (h :: ts)).\n  Proof.\n    unfold Proper, respectful, run_network.\n    intros x y Hxy nx ny Hn.\n    cbn.\n    remember (map (fun it : ctree (Net (S n) +' E) R => Running it Datatypes.nil) nx) as netx.\n    remember (map (fun it : ctree (Net (S n) +' E) R => Running it Datatypes.nil) ny) as nety.\n    eapply transitivity with (y:=schedule_one schedule (Running x List.nil :: netx) (F1)); cbn.\n    - desobs x.\n      cbn.\n  Admitted.\n\nEnd Network.\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/Network.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.17722764812301622}}
{"text": "Require Import Eqdep_dec Arith Omega List ListUtils Rounding Psatz.\nRequire Import Word WordAuto AsyncDisk Pred PredCrash GenSepN Array SepAuto.\nRequire Import Rec Prog BasicProg Hoare RecArrayUtils Log.\nRequire Import FMapAVL FMapMem.\nRequire Import MapUtils.\nRequire Import Structures.OrderedType.\nRequire Import Structures.OrderedTypeEx.\nImport ListNotations.\n\nSet Implicit Arguments.\n\n\nModule LogRecArray (RA : RASig).\n\n  Module Defs := RADefs RA.\n  Import RA Defs.\n\n  Definition items_valid xp (items : itemlist) :=\n    xparams_ok xp /\\ RAStart xp <> 0 /\\\n    length items = (RALen xp) * items_per_val /\\\n    Forall Rec.well_formed items.\n\n  (** rep invariant *)\n  Definition rep xp (items : itemlist) :=\n    ( exists vl, [[ vl = ipack items ]] *\n      [[ items_valid xp items ]] *\n      arrayN (@ptsto _ addr_eq_dec valuset) (RAStart xp) (synced_list vl))%pred.\n\n  Definition get lxp xp ix ms :=\n    let '(bn, off) := (ix / items_per_val, ix mod items_per_val) in\n    let^ (ms, v) <- LOG.read_array lxp (RAStart xp) bn ms;\n    Ret ^(ms, selN_val2block v off).\n\n  Definition put lxp xp ix item ms :=\n    let '(bn, off) := (ix / items_per_val, ix mod items_per_val) in\n    let^ (ms, v) <- LOG.read_array lxp (RAStart xp) bn ms;\n    let v' := block2val_updN_val2block v off item in\n    ms <- LOG.write_array lxp (RAStart xp) bn v' ms;\n    Ret ms.\n\n  (** read n blocks starting from the beginning *)\n  Definition read lxp xp nblocks ms :=\n    let^ (ms, r) <- LOG.read_range lxp (RAStart xp) nblocks iunpack nil ms;\n    Ret ^(ms, r).\n\n  (** write all items starting from the beginning *)\n  Definition write lxp xp items ms :=\n    ms <- LOG.write_range lxp (RAStart xp) (ipack items) ms;\n    Ret ms.\n\n  (** set all items to item0 *)\n  Definition init lxp xp ms :=\n    ms <- LOG.write_range lxp (RAStart xp) (repeat $0 (RALen xp)) ms;\n    Ret ms.\n\n  (* find the first item that satisfies cond *)\n  Definition ifind lxp xp (cond : item -> addr -> bool) ms :=\n    let^ (ms, ret) <- ForN i < (RALen xp)\n    Hashmap hm\n    Ghost [ F m xp items Fm crash sm m1 m2 ]\n    Loopvar [ ms ret ]\n    Invariant\n    LOG.rep lxp F (LOG.ActiveTxn m1 m2) ms sm hm *\n                              [[[ m ::: Fm * rep xp items ]]] *\n                              [[ forall st,\n                                   ret = Some st ->\n                                   cond (snd st) (fst st) = true\n                                   /\\ (fst st) < length items\n                                   /\\ snd st = selN items (fst st) item0 ]]\n    OnCrash  crash\n    Begin\n      If (is_some ret) {\n        Ret ^(ms, ret)\n      } else {\n        let^ (ms, v) <- LOG.read_array lxp (RAStart xp) i ms;\n        let r := ifind_block cond (val2block v) (i * items_per_val) in\n        match r with\n        (* loop call *)\n        | None => Ret ^(ms, None)\n        (* break *)\n        | Some ifs => Ret ^(ms, Some ifs)\n        end\n      }\n    Rof ^(ms, None);\n    Ret ^(ms, ret).\n\n  Local Hint Resolve items_per_val_not_0 items_per_val_gt_0 items_per_val_gt_0'.\n\n\n  Lemma items_valid_updN : forall xp items a v,\n    items_valid xp items ->\n    Rec.well_formed v ->\n    items_valid xp (updN items a v).\n  Proof.\n    unfold items_valid; intuition.\n    rewrite length_updN; auto.\n    apply Forall_wellformed_updN; auto.\n  Qed.\n\n  Lemma items_valid_upd_range : forall xp items len a v,\n    items_valid xp items ->\n    Rec.well_formed v ->\n    items_valid xp (upd_range items a len v).\n  Proof.\n    induction len; simpl; intros; auto using items_valid_updN.\n  Qed.\n\n  Lemma ifind_length_ok : forall xp i items,\n    i < RALen xp ->\n    items_valid xp items ->\n    i < length (synced_list (ipack items)).\n  Proof.\n    unfold items_valid; intuition.\n    eapply synced_list_ipack_length_ok; eauto.\n  Qed.\n\n  Lemma items_valid_length_eq : forall xp a b,\n    items_valid xp a ->\n    items_valid xp b ->\n    length (ipack a) = length (ipack b).\n  Proof.\n    unfold items_valid; intuition.\n    eapply ipack_length_eq; eauto.\n  Qed.\n\n  Theorem get_ok : forall lxp xp ix ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ ix < length items ]] *\n          [[[ m ::: Fm * rep xp items ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n          [[ r = selN items ix item0 ]]\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} get lxp xp ix ms.\n  Proof.\n    unfold get, rep.\n    safestep.\n    rewrite synced_list_length, ipack_length.\n    apply div_lt_divup; auto.\n\n    safestep.\n    subst; rewrite synced_list_selN; simpl.\n    erewrite selN_val2block_equiv.\n    apply ipack_selN_divmod; auto.\n    apply list_chunk_wellformed; auto.\n    unfold items_valid in *; intuition; auto.\n    apply Nat.mod_upper_bound; auto.\n  Qed.\n\n\n  Theorem put_ok : forall lxp xp ix e ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ ix < length items /\\ Rec.well_formed e ]] *\n          [[[ m ::: Fm * rep xp items ]]]\n    POST:hm' RET:ms' exists m',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms' sm hm' *\n          [[[ m' ::: Fm * rep xp (updN items ix e) ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} put lxp xp ix e ms.\n  Proof.\n    unfold put, rep.\n    hoare; subst.\n\n    (* [rewrite block2val_updN_val2block_equiv] somewhere *)\n\n    rewrite synced_list_length, ipack_length; apply div_lt_divup; auto.\n    rewrite synced_list_length, ipack_length; apply div_lt_divup; auto.\n    unfold items_valid in *; intuition auto.\n\n    apply arrayN_unify.\n    rewrite synced_list_selN, synced_list_updN; f_equal; simpl.\n    rewrite block2val_updN_val2block_equiv.\n    apply ipack_updN_divmod; auto.\n    apply list_chunk_wellformed.\n    unfold items_valid in *; intuition; auto.\n    apply Nat.mod_upper_bound; auto.\n    apply items_valid_updN; auto.\n  Qed.\n\n\n  Theorem read_ok : forall lxp xp nblocks ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ nblocks <= RALen xp ]] *\n          [[[ m ::: Fm * rep xp items ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n          [[ r = firstn (nblocks * items_per_val) items ]]\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} read lxp xp nblocks ms.\n  Proof.\n    unfold read, rep.\n    hoare.\n\n    rewrite synced_list_length, ipack_length.\n    unfold items_valid in *; intuition.\n    substl (length items); rewrite divup_mul; auto.\n\n    subst; rewrite synced_list_map_fst.\n    unfold items_valid in *; intuition.\n    eapply iunpack_ipack_firstn; eauto.\n  Qed.\n\n\n  Theorem write_ok : forall lxp xp items ms,\n    {< F Fm m0 sm m old,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ items_valid xp items ]] *\n          [[[ m ::: Fm * rep xp old ]]]\n    POST:hm' RET:ms' exists m',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms' sm hm' *\n          [[[ m' ::: Fm * rep xp items ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} write lxp xp items ms.\n  Proof.\n    unfold write, rep.\n    hoare.\n\n    unfold items_valid in *; intuition; auto.\n    erewrite synced_list_length, items_valid_length_eq; eauto.\n    rewrite vsupsyn_range_synced_list; auto.\n    erewrite synced_list_length, items_valid_length_eq; eauto.\n  Qed.\n\n\n  Theorem init_ok : forall lxp xp ms,\n    {< F Fm m0 sm m vsl,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ xparams_ok xp /\\ RAStart xp <> 0 /\\ length vsl = RALen xp ]] *\n          [[[ m ::: Fm * arrayN (@ptsto _ addr_eq_dec _) (RAStart xp) vsl ]]]\n    POST:hm' RET:ms' exists m',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms' sm hm' *\n          [[[ m' ::: Fm * rep xp (repeat item0 ((RALen xp) * items_per_val) ) ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} init lxp xp ms.\n  Proof.\n    unfold init, rep.\n    hoare.\n\n    rewrite repeat_length; omega.\n    rewrite vsupsyn_range_synced_list by (rewrite repeat_length; auto).\n    apply arrayN_unify; f_equal.\n    apply repeat_ipack_item0.\n\n    unfold items_valid; intuition.\n    rewrite repeat_length; auto.\n    apply Forall_repeat.\n    apply item0_wellformed.\n  Qed.\n\n  Hint Extern 0 (okToUnify (LOG.arrayP (RAStart _) _) (LOG.arrayP (RAStart _) _)) =>\n  constructor : okToUnify.\n\n  Hint Resolve\n       ifind_list_ok_cond\n       ifind_result_inbound\n       ifind_result_item_ok.\n\n  Theorem ifind_ok : forall lxp xp cond ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[[ m ::: Fm * rep xp items ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n        ( [[ r = None ]] \\/ exists st,\n          [[ r = Some st /\\ cond (snd st) (fst st) = true\n                         /\\ (fst st) < length items\n                         /\\ snd st = selN items (fst st) item0 ]])\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} ifind lxp xp cond ms.\n  Proof.\n    unfold ifind, rep.\n    safestep. eauto.\n    eassign items.\n    pred_apply_instantiate; cancel.\n    eauto.\n\n    safestep.\n    safestep.\n    safestep.\n    eapply ifind_length_ok; eauto.\n\n    unfold items_valid in *; intuition idtac.\n    step.\n    cancel.\n\n    safestep.\n    destruct a; cancel.\n    match goal with\n    | [ H: forall _, Some _ = Some _ -> _ |- _ ] =>\n      edestruct H; eauto\n    end.\n    or_r; cancel.\n    pimpl_crash.\n    eassign (exists ms', LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm)%pred.\n    cancel.\n    erewrite LOG.rep_hashmap_subset; eauto.\n\n    Unshelve. exact tt.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (get _ _ _ _) _) => apply get_ok : prog.\n  Hint Extern 1 ({{_}} Bind (put _ _ _ _ _) _) => apply put_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read _ _ _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (write _ _ _ _) _) => apply write_ok : prog.\n  Hint Extern 1 ({{_}} Bind (init _ _ _) _) => apply init_ok : prog.\n  Hint Extern 1 ({{_}} Bind (ifind _ _ _ _) _) => apply ifind_ok : prog.\n\n\n  (** operations using array spec *)\n\n  Definition get_array lxp xp ix ms :=\n    r <- get lxp xp ix ms;\n    Ret r.\n\n  Definition put_array lxp xp ix item ms :=\n    r <- put lxp xp ix item ms;\n    Ret r.\n\n  Definition read_array lxp xp nblocks ms :=\n    r <- read lxp xp nblocks ms;\n    Ret r.\n\n  Definition ifind_array lxp xp cond ms :=\n    r <- ifind lxp xp cond ms;\n    Ret r.\n\n  Theorem get_array_ok : forall lxp xp ix ms,\n    {< F Fm Fi m0 sm m items e,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[[ m ::: Fm * rep xp items ]]] *\n          [[[ items ::: Fi * (ix |-> e) ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' * [[ r = e ]]\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} get_array lxp xp ix ms.\n  Proof.\n    unfold get_array.\n    hoare.\n    eapply list2nmem_ptsto_bound; eauto.\n    subst; apply eq_sym.\n    eapply list2nmem_sel; eauto.\n  Qed.\n\n\n  Theorem put_array_ok : forall lxp xp ix e ms,\n    {< F Fm Fi m0 sm m items e0,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ Rec.well_formed e ]] *\n          [[[ m ::: Fm * rep xp items ]]] *\n          [[[ items ::: Fi * (ix |-> e0) ]]]\n    POST:hm' RET:ms' exists m' items',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms' sm hm' *\n          [[ items' = updN items ix e ]] *\n          [[[ m' ::: Fm * rep xp items' ]]] *\n          [[[ items' ::: Fi * (ix |-> e) ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} put_array lxp xp ix e ms.\n  Proof.\n    unfold put_array.\n    hoare.\n    eapply list2nmem_ptsto_bound; eauto.\n    eapply list2nmem_updN; eauto.\n  Qed.\n\n\n  Lemma read_array_length_ok : forall l xp Fm Fi m items nblocks,\n    length l = nblocks * items_per_val ->\n    (Fm * rep xp items)%pred (list2nmem m) ->\n    (Fi * arrayN (@ptsto _ addr_eq_dec _) 0 l)%pred (list2nmem items) ->\n    nblocks <= RALen xp.\n  Proof.\n    unfold rep; intuition.\n    destruct_lift H0.\n    unfold items_valid in *; subst; intuition.\n    apply list2nmem_arrayN_length in H1.\n    rewrite H, H3 in H1.\n    eapply Nat.mul_le_mono_pos_r.\n    apply items_per_val_gt_0.\n    auto.\n  Qed.\n\n  Lemma read_array_list_ok : forall (l : list item) nblocks items Fi,\n    length l = nblocks * items_per_val ->\n    (Fi \u2736 arrayN (@ptsto _ addr_eq_dec _) 0 l)%pred (list2nmem items) ->\n    firstn (nblocks * items_per_val) items = l.\n  Proof.\n    intros.\n    eapply arrayN_list2nmem in H0.\n    rewrite <- H; simpl in *; auto.\n    exact item0.\n  Qed.\n\n\n  Theorem read_array_ok : forall lxp xp nblocks ms,\n    {< F Fm Fi m0 sm m items l,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ length l = (nblocks * items_per_val)%nat ]] *\n          [[[ m ::: Fm * rep xp items ]]] *\n          [[[ items ::: Fi * arrayN (@ptsto _ addr_eq_dec _) 0 l ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n          [[ r = l ]]\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} read_array lxp xp nblocks ms.\n  Proof.\n    unfold read_array.\n    hoare.\n    eapply read_array_length_ok; eauto.\n    subst; eapply read_array_list_ok; eauto.\n  Qed.\n\n\n  Theorem ifind_array_ok : forall lxp xp cond ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[[ m ::: Fm * rep xp items ]]]\n    POST:hm' RET:^(ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n        ( [[ r = None ]] \\/ exists st,\n          [[ r = Some st /\\ cond (snd st) (fst st) = true ]] *\n          [[[ items ::: arrayN_ex (@ptsto _ addr_eq_dec _) items (fst st) * (fst st) |-> (snd st) ]]] )\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} ifind_array lxp xp cond ms.\n  Proof.\n    unfold ifind_array; intros.\n    hoare.\n    or_r; cancel.\n    apply list2nmem_ptsto_cancel; auto.\n  Qed.\n\n  Fact eq_rect_eq : forall (a : nat) (f : nat -> Type) v1 v2 c H,\n    eq_rect a f v1 c H = eq_rect a f v2 c H -> v1 = v2.\n  Proof.\n    intros a f v1 v2 c H.\n    subst; auto.\n  Qed.\n\n  Ltac eq_rect_eq := match goal with [H : eq_rect _ _ _ _ _ = eq_rect _ _ _ _ _ |- _] =>\n      apply eq_rect_eq in H;\n      eapply f_equal in H;\n      rewrite Rec.of_to_id in H;\n      rewrite Rec.of_to_id in H\n    end.\n\n  Lemma ipack_inj : forall ra l1 l2,\n    items_valid ra l1 ->\n    items_valid ra l2 ->\n    ipack l1 =ipack l2 -> l1 = l2.\n  Proof.\n    unfold items_valid.\n    intros ra.\n    generalize (RALen ra) as r; intro r; destruct r.\n    intros; subst; simpl in *; intuition.\n    rewrite length_nil with (l := l2); auto.\n    rewrite length_nil with (l := l1); auto.\n    induction r; intros; intuition.\n    simpl in *; rewrite plus_0_r in *.\n    rewrite ipack_one in *; auto.\n    rewrite ipack_one in *; auto.\n    match goal with [H : _::_ = _::_ |- _] => inversion H; clear H end.\n    unfold block2val, word2val, eq_rec_r, eq_rec in *.\n    simpl in *.\n    eq_rect_eq; auto; unfold Rec.well_formed; simpl; intuition.\n    repeat match goal with\n      [ lx : itemlist,\n        Hl : length ?lx = _,\n        H : context [ipack ?lx] |- _] =>\n        erewrite <- firstn_skipn with (l := lx) (n := items_per_val) in H;\n        erewrite ipack_app with (na := 1) in H;\n        [> erewrite <- firstn_skipn with (l := lx) | ];\n        [> erewrite ipack_one with (l := firstn _ _) in H | ]\n    end; simpl in *; try rewrite plus_0_r in *.\n    match goal with [H: _::_ = _::_ |- _ ] => inversion H end.\n    unfold block2val, word2val, eq_rec_r, eq_rec in *.\n    simpl in *.\n    eq_rect_eq.\n    f_equal; eauto.\n    apply IHr; intuition.\n    all : repeat (\n          auto || lia || split  ||\n          unfold item in *      ||\n          rewrite skipn_length  ||\n          apply forall_skipn    ||\n          apply forall_firstn   ||\n          apply firstn_length_l ).\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (get_array _ _ _ _) _) => apply get_array_ok : prog.\n  Hint Extern 1 ({{_}} Bind (put_array _ _ _ _ _) _) => apply put_array_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read_array _ _ _ _) _) => apply read_array_ok : prog.\n  Hint Extern 1 ({{_}} Bind (ifind_array _ _ _ _) _) => apply ifind_array_ok : prog.\n\n  (* If two arrays are in the same spot, their contents have to be equal *)\n  Hint Extern 0 (okToUnify (rep ?xp _) (rep ?xp _)) => constructor : okToUnify.\n\n  Theorem rep_inj : forall F1 F2 l1 l2 ra m,\n    (F1 * rep ra l1)%pred m -> (F2 * rep ra l2)%pred m -> l1 = l2.\n  Proof.\n    intros.\n    unfold rep in *.\n    repeat match goal with\n      [ H : (_ * (exis _))%pred _ |- _ ] => destruct_lift H\n      end.\n    match goal with\n      [ H : context[synced_list _] |- _] =>  eapply arrayN_unify', synced_list_inj in H\n    end.\n    eapply ipack_inj; eauto.\n    repeat rewrite synced_list_length.\n    repeat rewrite ipack_length.\n    f_equal.\n    unfold items_valid in *; intuition.\n    unfold item in *.\n    omega.\n    eassumption.\n  Qed.\n\n  Lemma items_wellformed : forall F xp l m,\n    (F * rep xp l)%pred m -> Forall Rec.well_formed l.\n  Proof.\n    unfold rep, items_valid; intuition.\n    destruct_lift H; auto.\n  Qed.\n\n  Lemma items_wellformed_pimpl : forall xp l,\n    rep xp l =p=> [[ Forall Rec.well_formed l ]] * rep xp l.\n  Proof.\n    unfold rep, items_valid; cancel.\n  Qed.\n\n  Lemma item_wellformed : forall F xp m l i,\n    (F * rep xp l)%pred m -> Rec.well_formed (selN l i item0).\n  Proof.\n    intros.\n    destruct (lt_dec i (length l)).\n    apply Forall_selN; auto.\n    eapply items_wellformed; eauto.\n    rewrite selN_oob by omega.\n    apply item0_wellformed.\n  Qed.\n\n  Lemma items_length_ok : forall F xp l m,\n    (F * rep xp l)%pred m ->\n    length l = (RALen xp) * items_per_val.\n  Proof.\n    unfold rep, items_valid; intuition.\n    destruct_lift H; auto.\n  Qed.\n\n  Lemma items_length_ok_pimpl : forall xp l,\n    rep xp l =p=> [[ length l = ((RALen xp) * items_per_val)%nat ]] * rep xp l.\n  Proof.\n    unfold rep, items_valid; cancel.\n  Qed.\n\n  Theorem xform_rep : forall xp l,\n    crash_xform (rep xp l) <=p=> rep xp l.\n  Proof.\n    unfold rep; intros; split.\n    xform_norm.\n    rewrite crash_xform_arrayN_synced; cancel.\n    cancel.\n    xform_normr; cancel.\n    rewrite <- crash_xform_arrayN_r; eauto.\n    apply possible_crash_list_synced_list.\n  Qed.\n\nEnd LogRecArray.\n\n\nModule LogRecArrayCache (RA : RASig).\n\n  Module LRA := LogRecArray RA.\n  Module Defs := LRA.Defs.\n  Import RA LRA.Defs.\n\n  Module Cache := FMapAVL.Make(Nat_as_OT).\n  Module CacheDefs := MapDefs Nat_as_OT Cache.\n  Definition Cache_type := Cache.t item.\n  Module M := MapMem Nat_as_OT Cache.\n  Definition cache0 : Cache_type := Cache.empty item.\n\n  Definition cache_ptsto i (v : item) : @pred _ addr_eq_dec _ :=\n    ( i |-> v \\/ emp )%pred.\n\n  Definition cache_rep (items : itemlist) (c : Cache_type) :=\n     arrayN cache_ptsto 0 items (M.mm _ c).\n\n  Definition rep xp (items : itemlist) c :=\n    ( LRA.rep xp items * [[ cache_rep items c ]] )%pred.\n\n  Definition get lxp xp ix cache ms :=\n    match Cache.find ix cache with\n    | Some v =>\n      Ret ^(cache, ms, v)\n    | None =>\n      let^ (ms, v) <- LRA.get lxp xp ix ms;\n      AlertModified;;\n      Ret ^(Cache.add ix v cache, ms, v)\n    end.\n\n  Definition put lxp xp ix item cache ms :=\n    ms <- LRA.put lxp xp ix item ms;\n    Ret ^(Cache.add ix item cache, ms).\n\n  Definition read := LRA.read.\n  Definition write := LRA.write.\n  Definition init := LRA.init.\n  Definition ifind := LRA.ifind.\n\n  Definition get_array lxp xp ix cache ms :=\n    r <- get lxp xp ix cache ms;\n    Ret r.\n\n  Definition put_array lxp xp ix item cache ms :=\n    r <- put lxp xp ix item cache ms;\n    Ret r.\n\n  Definition read_array lxp xp nblocks ms :=\n    r <- read lxp xp nblocks ms;\n    Ret r.\n\n  Definition ifind_array lxp xp cond ms :=\n    r <- ifind lxp xp cond ms;\n    Ret r.\n\n  Definition read_ok := LRA.read_ok.\n\n  Definition write_ok := LRA.write_ok.\n\n  Definition init_ok := LRA.init_ok.\n\n  Definition ifind_ok := LRA.ifind_ok.\n\n  Hint Extern 1 ({{_}} Bind (read _ _ _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (write _ _ _ _) _) => apply write_ok : prog.\n  Hint Extern 1 ({{_}} Bind (init _ _ _) _) => apply init_ok : prog.\n\n  Lemma item_wellformed : forall F xp m i l cache,\n    (F \u2736 rep xp l cache)%pred m ->\n    Rec.well_formed (selN l i item0).\n  Proof.\n    unfold rep.\n    intros.\n    destruct_lifts.\n    eauto using LRA.item_wellformed.\n  Qed.\n\n  Lemma items_length_ok_pimpl : forall xp l cache,\n    rep xp l cache =p=>\n    [[ length l = (RALen xp * items_per_val)%nat ]] \u2736 rep xp l cache.\n  Proof.\n    unfold rep.\n    intros xp l c m H.\n    rewrite LRA.items_length_ok_pimpl in H.\n    pred_apply.\n    cancel.\n  Qed.\n\n  Lemma xform_rep : forall xp l c,\n    crash_xform (rep xp l c) <=p=> rep xp l c.\n  Proof.\n    unfold rep.\n    intros.\n    xform_norm.\n    rewrite LRA.xform_rep.\n    split; cancel.\n  Qed.\n\n  Lemma cache_rep_empty : forall l,\n    cache_rep l (Cache.empty _).\n  Proof.\n    unfold cache_rep, M.mm.\n    intro l. generalize 0. revert l.\n    induction l; intros.\n    intro; auto.\n    simpl. unfold_sep_star.\n    repeat exists (M.mm _ (Cache.empty _)).\n    intuition.\n    cbv. intro. repeat deex. congruence.\n    right.\n    intro; auto.\n  Qed.\n\n  Lemma rep_clear_cache: forall xp items cache,\n    rep xp items cache =p=> rep xp items cache0.\n  Proof.\n    unfold rep. cancel.\n    apply cache_rep_empty.\n  Qed.\n\n  Lemma arrayN_cache_ptsto_oob: forall l i m x,\n    arrayN (cache_ptsto) x l m -> i >= length l + x \\/ i < x -> m i = None.\n  Proof.\n    induction l; cbn; intros; auto.\n    unfold sep_star in H.\n    rewrite sep_star_is in H.\n    unfold sep_star_impl in H.\n    repeat deex.\n    all: eapply mem_union_sel_none.\n    all : solve [\n      cbv in H2; intuition auto; apply H3; omega |\n      eapply IHl; eauto; omega].\n  Qed.\n\n  Lemma cache_rep_some : forall items i cache v d,\n    Cache.find i cache = Some v ->\n    i < length items ->\n    cache_rep items cache ->\n    v = selN items i d.\n  Proof.\n    unfold cache_rep.\n    intros items i cache v d.\n    change (Cache.find i cache) with (M.mm _ cache i).\n    generalize (M.mm item cache).\n    clear cache.\n    intros.\n    eapply isolateN_fwd in H1; eauto.\n    autorewrite with core in *.\n    unfold cache_ptsto in H1 at 2.\n    eapply pimpl_trans in H1.\n    2 : rewrite sep_star_assoc, sep_star_comm, sep_star_assoc; reflexivity.\n    2 : reflexivity.\n    unfold sep_star in H1.\n    rewrite sep_star_is in H1.\n    unfold sep_star_impl, or, ptsto, emp in H1.\n    intuition repeat deex.\n    erewrite mem_union_addr in H by eauto.\n    inversion H. eauto.\n    rewrite mem_union_sel_none in H; try congruence.\n    apply mem_union_sel_none.\n    eapply arrayN_cache_ptsto_oob; eauto. omega.\n    eapply arrayN_cache_ptsto_oob; eauto.\n    rewrite firstn_length_l; omega.\n  Qed.\n\n  Lemma cache_rep_add : forall items i cache d,\n    i < length items ->\n    cache_rep items cache ->\n    cache_rep items (Cache.add i (selN items i d) cache).\n  Proof.\n    unfold cache_rep in *.\n    intros.\n    rewrite M.mm_add_upd.\n    destruct (M.mm _ cache i) eqn:?.\n    eapply cache_rep_some in H0 as ?; eauto.\n    rewrite Mem.upd_nop; eauto.\n    rewrite Heqo. f_equal. eauto.\n    generalize dependent (M.mm _ cache). clear cache.\n    intros.\n    eapply arrayN_mem_upd_none; eauto.\n    edestruct arrayN_except as [H' _]; eauto; apply H' in H0; clear H'.\n    unfold sep_star in *.\n    rewrite sep_star_is in *.\n    unfold sep_star_impl in *.\n    repeat deex.\n    apply mem_union_none_sel in Heqo.\n    cbv [cache_ptsto or ptsto] in *.\n    intuition try congruence.\n    apply emp_empty_mem_only in H5. subst.\n    rewrite mem_union_empty_mem'. auto.\n    cbv [cache_ptsto ptsto or].\n    left.\n    intuition (destruct addr_eq_dec); eauto; congruence.\n  Unshelve.\n    exact item0.\n  Qed.\n\n  Lemma cache_ptsto_upd : forall i v0 v m,\n    cache_ptsto i v0 m -> cache_ptsto i v (Mem.upd m i v).\n  Proof.\n    cbv [cache_ptsto or].\n    intros.\n    left.\n    intuition auto.\n    pose proof (@ptsto_upd _ addr_eq_dec _ i v v0 emp).\n    eapply pimpl_trans; try apply H; try pred_apply; cancel.\n    pose proof (@ptsto_upd_disjoint _ addr_eq_dec _ emp i v).\n    eapply pimpl_trans; try apply H; try pred_apply; try cancel.\n    cbv in *; auto.\n  Qed.\n\n  Lemma cache_rep_updN : forall items cache i v,\n    i < length items ->\n    cache_rep items cache ->\n    cache_rep (updN items i v) (Cache.add i v cache).\n  Proof.\n    unfold cache_rep in *.\n    intros.\n    rewrite M.mm_add_upd.\n    generalize dependent (M.mm _ cache). clear cache.\n    intros.\n    edestruct arrayN_isolate as [H' _]; eauto; apply H' in H0; clear H'.\n    edestruct arrayN_isolate as [_ H']; [| apply H'; clear H'].\n    rewrite length_updN; eauto.\n    simpl in *.\n    rewrite selN_updN_eq by auto.\n    rewrite firstn_updN_oob by auto.\n    rewrite skipn_updN by auto.\n    revert H0.\n    unfold_sep_star.\n    intuition repeat deex.\n    assert (mem_disjoint m0 (Mem.upd m3 i v)).\n    cbv [cache_ptsto or ptsto] in H6.\n    cbv [mem_disjoint Mem.upd] in *.\n    intuition repeat deex.\n    destruct addr_eq_dec; subst; eauto 10.\n    destruct addr_eq_dec; subst; eauto 10.\n    erewrite arrayN_cache_ptsto_oob in H6; eauto; try congruence.\n    rewrite firstn_length_l; omega.\n    apply mem_disjoint_union in H0 as ?.\n    assert (mem_disjoint (Mem.upd m3 i v) m2).\n    cbv [cache_ptsto or ptsto] in H6.\n    cbv [mem_disjoint Mem.upd] in *.\n    intuition repeat deex.\n    destruct addr_eq_dec; subst; eauto 10.\n    destruct addr_eq_dec; subst; eauto 10.\n    erewrite arrayN_cache_ptsto_oob in H9; eauto; try congruence; omega.\n    repeat eexists; try eapply cache_ptsto_upd; eauto.\n    rewrite mem_union_comm with (m1 := m0) by auto.\n    repeat rewrite <- mem_union_upd.\n    f_equal.\n    apply mem_union_comm, mem_disjoint_comm; auto.\n    apply mem_disjoint_mem_union_split_l; auto.\n    apply mem_disjoint_comm.\n    eapply mem_disjoint_union_2.\n    apply mem_disjoint_comm.\n    eauto.\n  Unshelve. all : eauto.\n  Qed.\n\n  Theorem get_array_ok : forall lxp xp ix cache ms,\n    {< F Fm m0 sm m items,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ ix < length items ]] *\n          [[[ m ::: Fm * rep xp items cache ]]]\n    POST:hm' RET:^(cache', ms', r)\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm' *\n          [[[ m ::: Fm * rep xp items cache' ]]] *\n          [[ r = selN items ix item0 ]]\n    CRASH:hm' exists ms',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms' sm hm'\n    >} get_array lxp xp ix cache ms.\n  Proof.\n    unfold get_array, get, rep.\n    hoare.\n    all : eauto using cache_rep_some, cache_rep_add.\n  Qed.\n\n  Theorem put_array_ok : forall lxp xp ix e cache ms,\n    {< F Fm Fi m0 sm m items e0,\n    PRE:hm\n          LOG.rep lxp F (LOG.ActiveTxn m0 m) ms sm hm *\n          [[ Rec.well_formed e ]] *\n          [[[ m ::: Fm * rep xp items cache ]]] *\n          [[[ items ::: Fi * (ix |-> e0) ]]]\n    POST:hm' RET:^(cache', ms') exists m' items',\n          LOG.rep lxp F (LOG.ActiveTxn m0 m') ms' sm hm' *\n          [[ items' = updN items ix e ]] *\n          [[[ m' ::: Fm * rep xp items' cache' ]]] *\n          [[[ items' ::: Fi * (ix |-> e) ]]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} put_array lxp xp ix e cache ms.\n  Proof.\n    unfold put_array, put, rep.\n    hoare.\n    eapply list2nmem_ptsto_bound; eauto.\n    eapply cache_rep_updN; eauto.\n    eapply list2nmem_ptsto_bound; eauto.\n    eapply list2nmem_updN; eauto.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (get_array _ _ _ _ _) _) => apply get_array_ok : prog.\n  Hint Extern 1 ({{_}} Bind (put_array _ _ _ _ _ _) _) => apply put_array_ok : prog.\n\n  Hint Extern 0 (okToUnify (rep ?xp _ _) (rep ?xp _ _)) => constructor : okToUnify.\n\nEnd LogRecArrayCache.\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/LogRecArray.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.1771816594266699}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import MmioPTWalk.Spec.\nRequire Import RData.\nRequire Import Constants.\nRequire Import AbstractMachine.Spec.\nRequire Import MmioPTWalk.Layer.\nRequire Import HypsecCommLib.\n\nLocal Open Scope Z_scope.\n\nSection MmioSPTWalkSpec.\n\n  Definition clear_smmu_pt_spec (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    rely is_smmu index; rely is_smmu_cfg cbndx;\n    if halt adt then Some adt else\n    let id := SPT_ID in\n    match ZMap.get id (lock adt) with\n    | LockOwn true =>\n      let ttbr := SMMU_TTBR index cbndx in\n      let spt := spts (shared adt) in\n      let pt0 := ZMap.init (0, 0) in\n      let pgd_t0 := ZMap.init false in\n      let pmd_t0 := ZMap.init (ZMap.init false) in\n      let spt' := spt {spt_pt: (spt_pt spt) # ttbr == pt0} {spt_pgd_t: (spt_pgd_t spt) # ttbr == pgd_t0} {spt_pmd_t: (spt_pmd_t spt) # ttbr == pmd_t0} in\n      Some adt {tstate: 1} {shared: (shared adt) {spts: spt'}}\n    | _  => None\n    end.\n\n  Definition walk_smmu_pt_spec (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option Z64 :=\n    match addr with\n    | VZ64 addr =>\n      rely is_smmu index; rely is_smmu_cfg cbndx; rely is_smmu_addr addr;\n      if halt adt then Some (VZ64 0) else\n      let id := SPT_ID in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let ttbr := SMMU_TTBR index cbndx in\n        let pt := ttbr @ (spt_pt (spts (shared adt))) in\n        let gfn := addr / PAGE_SIZE in\n        match ZMap.get gfn pt with\n        | (pfn, pte) => Some (VZ64 pte)\n        end\n      | _  => None\n      end\n    end.\n\n  Definition local_spt_map (cbndx: Z) (index: Z) (addr: Z) (pte: Z) (spt: SPT) :=\n    let gfn := addr / PAGE_SIZE in\n    let pfn := (phys_page pte) / PAGE_SIZE in\n    let ttbr := SMMU_TTBR index cbndx in\n    let pt := ttbr @ (spt_pt spt) in\n    match gfn @ pt with\n    | (pfn0, pte0) =>\n      let pgd_next' := (if (stage2_pgd_index addr) @ (ttbr @ (spt_pgd_t spt)) then (spt_pgd_next spt) else (spt_pgd_next spt) + PAGE_SIZE) in\n      let pmd_next' := (if (pmd_index addr) @ ((stage2_pgd_index addr) @ (ttbr @ (spt_pmd_t spt)))\n                        then (spt_pmd_next spt) else (spt_pmd_next spt) + PAGE_SIZE) in\n      if (pgd_next' <=? SMMU_PMD_START) && (pmd_next'  <=? SMMU_POOL_END) then\n        let spt' := spt {spt_pt: (spt_pt spt) # ttbr == (pt # gfn == (pfn, pte))}\n                        {spt_pgd_t: (spt_pgd_t spt) # ttbr == ((ttbr @ (spt_pgd_t spt)) # (stage2_pgd_index addr) == true)}\n                        {spt_pmd_t: (spt_pmd_t spt) # ttbr ==\n                                    ((ttbr @ (spt_pmd_t spt)) # (stage2_pgd_index addr) ==\n                                    (((stage2_pgd_index addr) @ (ttbr @ (spt_pmd_t spt))) # (pmd_index addr) == true))}\n                        {spt_pgd_next: pgd_next'} {spt_pmd_next: pmd_next'}\n        in\n        Some (false, spt')\n      else Some (true, spt)\n    end.\n\n  Definition set_smmu_pt_spec (cbndx: Z) (index: Z) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match addr, pte with\n    | VZ64 addr, VZ64 pte =>\n      rely is_smmu index; rely is_smmu_cfg cbndx;\n      rely is_smmu_addr addr; rely is_int64 pte;\n      if halt adt then Some adt else\n      rely (tstate adt =? 0);\n      let id := SPT_ID in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        match local_spt_map cbndx index addr pte (spts (shared adt)) with\n        | Some (halt', spt') =>\n          Some adt {tstate: if halt' then 0 else 1} {halt: halt'} {shared: (shared adt) {spts: spt'}}\n        | _ => None\n        end\n      | _  => None\n      end\n    end.\n\n  Definition dev_load_ref_spec (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    match gfn with\n    | VZ64 gfn =>\n      dev_load_raw_spec (VZ64 gfn) reg cbndx index adt\n    end.\n\n  Definition dev_store_ref_spec (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    match gfn with\n    | VZ64 gfn =>\n      dev_store_raw_spec (VZ64 gfn) reg cbndx index adt\n    end.\n\nEnd MmioSPTWalkSpec.\n\nSection MmioSPTWalkSpecLow.\n\n  Context `{real_params: RealParams}.\n\n  Notation LDATA := RData.\n\n  Notation LDATAOps := (cdata (cdata_ops := MmioPTWalk_ops) LDATA).\n\n  Definition clear_smmu_pt_spec0 (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    smmu_pt_clear_spec cbndx index adt.\n\n  Definition walk_smmu_pt_spec0 (cbndx: Z) (index: Z) (addr: Z64) (adt: RData) : option Z64 :=\n    match addr with\n    | VZ64 addr =>\n      when' ttbr == get_smmu_cfg_hw_ttbr_spec cbndx index adt;\n      rely is_int64 ttbr;\n      when' pgd, adt1 == walk_smmu_pgd_spec (VZ64 ttbr) (VZ64 addr) 0 adt;\n      rely is_int64 pgd;\n      when' pmd, adt2 == walk_smmu_pmd_spec (VZ64 pgd) (VZ64 addr) 0 adt;\n      rely is_int64 pmd;\n      when' pte == walk_smmu_pte_spec (VZ64 pmd) (VZ64 addr) adt;\n      rely is_int64 pte;\n      check64_spec (VZ64 pte) adt\n    end.\n\n  Definition set_smmu_pt_spec0 (cbndx: Z) (index: Z) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match addr, pte with\n    | VZ64 addr, VZ64 pte =>\n      when' ttbr == get_smmu_cfg_hw_ttbr_spec cbndx index adt;\n      rely is_int64 ttbr;\n      when' pgd, adt1 == walk_smmu_pgd_spec (VZ64 ttbr) (VZ64 addr) 1 adt;\n      rely is_int64 pgd;\n      when' pmd, adt2 == walk_smmu_pmd_spec (VZ64 pgd) (VZ64 addr) 1 adt1;\n      rely is_int64 pmd;\n      set_smmu_pte_spec (VZ64 pmd) (VZ64 addr) (VZ64 pte) adt2\n    end.\n\n  Definition dev_load_ref_spec0 (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    match gfn with\n    | VZ64 gfn =>\n      dev_load_raw_spec (VZ64 gfn) reg cbndx index adt\n    end.\n\n  Definition dev_store_ref_spec0 (gfn: Z64) (reg: Z) (cbndx: Z) (index: Z) (adt: RData) : option RData :=\n    match gfn with\n    | VZ64 gfn =>\n      dev_store_raw_spec (VZ64 gfn) reg cbndx index adt\n    end.\n\n  Inductive clear_smmu_pt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | clear_smmu_pt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx index\n      (Hinv: high_level_invariant labd)\n      (Hspec: clear_smmu_pt_spec0 (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n      clear_smmu_pt_spec_low_step s WB ((Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive walk_smmu_pt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_smmu_pt_spec_low_intro s (WB: _ -> Prop) m'0 labd cbndx index addr res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_smmu_pt_spec0 (Int.unsigned cbndx) (Int.unsigned index) (VZ64 (Int64.unsigned addr)) labd = Some (VZ64 (Int64.unsigned res))):\n      walk_smmu_pt_spec_low_step s WB ((Vint cbndx)::(Vint index)::(Vlong addr)::nil) (m'0, labd) (Vlong res) (m'0, labd).\n\n  Inductive set_smmu_pt_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | set_smmu_pt_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' cbndx num addr pte\n      (Hinv: high_level_invariant labd)\n      (Hspec: set_smmu_pt_spec0 (Int.unsigned cbndx) (Int.unsigned num) (VZ64 (Int64.unsigned addr)) (VZ64 (Int64.unsigned pte)) labd = Some labd'):\n      set_smmu_pt_spec_low_step s WB ((Vint cbndx)::(Vint num)::(Vlong addr)::(Vlong pte)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive dev_load_ref_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | dev_load_ref_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg cbndx index\n      (Hinv: high_level_invariant labd)\n      (Hspec: dev_load_ref_spec0 (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n      dev_load_ref_spec_low_step s WB ((Vlong gfn)::(Vint reg)::(Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive dev_store_ref_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | dev_store_ref_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' gfn reg cbndx index\n      (Hinv: high_level_invariant labd)\n      (Hspec: dev_store_ref_spec0 (VZ64 (Int64.unsigned gfn)) (Int.unsigned reg) (Int.unsigned cbndx) (Int.unsigned index) labd = Some labd'):\n      dev_store_ref_spec_low_step s WB ((Vlong gfn)::(Vint reg)::(Vint cbndx)::(Vint index)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModelX}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Definition clear_smmu_pt_spec_low: compatsem LDATAOps :=\n      csem clear_smmu_pt_spec_low_step (type_of_list_type (Tint32::Tint32::nil)) Tvoid.\n\n    Definition walk_smmu_pt_spec_low: compatsem LDATAOps :=\n      csem walk_smmu_pt_spec_low_step (type_of_list_type (Tint32::Tint32::Tint64::nil)) Tint64.\n\n    Definition set_smmu_pt_spec_low: compatsem LDATAOps :=\n      csem set_smmu_pt_spec_low_step (type_of_list_type (Tint32::Tint32::Tint64::Tint64::nil)) Tvoid.\n\n    Definition dev_load_ref_spec_low: compatsem LDATAOps :=\n      csem dev_load_ref_spec_low_step (type_of_list_type (Tint64::Tint32::Tint32::Tint32::nil)) Tvoid.\n\n    Definition dev_store_ref_spec_low: compatsem LDATAOps :=\n      csem dev_store_ref_spec_low_step (type_of_list_type (Tint64::Tint32::Tint32::Tint32::nil)) Tvoid.\n\n  End WITHMEM.\n\nEnd MmioSPTWalkSpecLow.\n\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/sekvm/MmioSPTWalk/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1771816523627261}}
{"text": "Require Import RelationClasses.\nRequire Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive sim_local (lc_src lc_tgt:Local.t): Prop :=\n| sim_local_intro\n    (TVIEW: TView.le lc_src.(Local.tview) lc_tgt.(Local.tview))\n    (PROMISES: SimPromises.sem SimPromises.bot SimPromises.bot lc_src.(Local.promises) lc_tgt.(Local.promises))\n.\n\nProgram Instance sim_local_PreOrder: PreOrder sim_local.\nNext Obligation.\n  econs; try refl. apply SimPromises.sem_bot.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. econs; try etrans; eauto.\n  apply SimPromises.sem_bot_inv in PROMISES; auto.\n  apply SimPromises.sem_bot_inv in PROMISES0; auto.\n  rewrite PROMISES, PROMISES0. apply SimPromises.sem_bot.\nQed.\n\nLemma sim_local_nonsynch_loc\n      loc lc_src lc_tgt\n      (SIM: sim_local lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch_loc loc lc_tgt.(Local.promises)):\n  Memory.nonsynch_loc loc lc_src.(Local.promises).\nProof.\n  inv SIM. eapply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\nQed.\n\nLemma sim_local_nonsynch\n      lc_src lc_tgt\n      (SIM: sim_local lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch lc_tgt.(Local.promises)):\n  Memory.nonsynch lc_src.(Local.promises).\nProof.\n  ii. eapply sim_local_nonsynch_loc; eauto.\nQed.\n\nLemma sim_local_memory_bot\n      lc_src lc_tgt\n      (SIM: sim_local lc_src lc_tgt)\n      (BOT: lc_tgt.(Local.promises) = Memory.bot):\n  lc_src.(Local.promises) = Memory.bot.\nProof.\n  inv SIM. eapply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\nQed.\n\nLemma sim_local_promise\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 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 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_read\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt ord_tgt lc2_tgt)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply MEM1; eauto. i. des.\n  esplits; eauto.\n  - econs; eauto. eapply TViewFacts.readable_mon; eauto. apply TVIEW.\n  - econs; eauto. s. apply TViewFacts.read_tview_mon; auto.\n    + apply WF1_TGT.\n    + eapply MEM1_TGT. eauto.\nQed.\n\nLemma sim_local_fulfill\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (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 lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src 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  { apply TViewFacts.write_released_mon; ss.\n    - apply LOCAL1.\n    - apply WF1_TGT.\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    + eapply TViewFacts.writable_mon; eauto. apply LOCAL1.\n  - econs; eauto. s. apply TViewFacts.write_tview_mon; auto.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n  - ss.\nQed.\n\nLemma sim_local_write\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (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 lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src 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; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_fulfill; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  i. des.\n  exploit promise_fulfill_write; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. exploit ORD0; eauto.\n    - etrans; eauto.\n    - i. des. splits; auto. eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto. etrans; eauto.\nQed.\n\nLemma sim_local_update\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src kind>> /\\\n    <<LOCAL3: sim_local lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_fence\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt sc1_tgt ordr_tgt ordw_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: Local.fence_step lc1_src sc1_src ordr_src ordw_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT. esplits; eauto.\n  - econs; eauto. i. eapply sim_local_nonsynch; eauto.\n    apply RELEASE. etrans; eauto.\n  - econs; try apply LOCAL1. s.\n    apply TViewFacts.write_fence_tview_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\n    + eapply TViewFacts.read_fence_future; apply WF1_SRC.\n  - apply TViewFacts.write_fence_sc_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply WF1_TGT.\nQed.\n\nLemma sim_local_program_step\n      lang\n      th1_src\n      th1_tgt th2_tgt e_tgt\n      (STEP_TGT: @Thread.program_step lang e_tgt th1_tgt th2_tgt)\n      (WF1_SRC: Local.wf th1_src.(Thread.local) th1_src.(Thread.memory))\n      (WF1_TGT: Local.wf th1_tgt.(Thread.local) th1_tgt.(Thread.memory))\n      (SC1_SRC: Memory.closed_timemap th1_src.(Thread.sc) th1_src.(Thread.memory))\n      (SC1_TGT: Memory.closed_timemap th1_tgt.(Thread.sc) th1_tgt.(Thread.memory))\n      (MEM1_SRC: Memory.closed th1_src.(Thread.memory))\n      (MEM1_TGT: Memory.closed th1_tgt.(Thread.memory))\n      (STATE: th1_src.(Thread.state) = th1_tgt.(Thread.state))\n      (LOCAL: sim_local th1_src.(Thread.local) th1_tgt.(Thread.local))\n      (SC: TimeMap.le th1_src.(Thread.sc) th1_tgt.(Thread.sc))\n      (MEM: sim_memory th1_src.(Thread.memory) th1_tgt.(Thread.memory)):\n  exists e_src th2_src,\n    <<STEP_SRC: @Thread.program_step lang e_src th1_src th2_src>> /\\\n    <<EVENT: ThreadEvent.get_event e_src = ThreadEvent.get_event e_tgt>> /\\\n    <<STATE: th2_src.(Thread.state) = th2_tgt.(Thread.state)>> /\\\n    <<LOCAL: sim_local th2_src.(Thread.local) th2_tgt.(Thread.local)>> /\\\n    <<SC: TimeMap.le th2_src.(Thread.sc) th2_tgt.(Thread.sc)>> /\\\n    <<MEM: sim_memory th2_src.(Thread.memory) th2_tgt.(Thread.memory)>>.\nProof.\n  destruct th1_src. ss. subst. inv STEP_TGT; ss.\n  inv LOCAL0; ss.\n  - esplits; (try by econs; [|econs 1]; eauto); ss.\n  - exploit sim_local_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 2]; eauto); ss.\n  - hexploit sim_local_write; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 3]; eauto); ss.\n  - exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read; eauto; try refl. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    hexploit sim_local_write; eauto; try refl; try by viewtac. i. des.\n    esplits; (try by econs; [|econs 4]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 5]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 6]; eauto); ss.\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/SimLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.17710580256497613}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Candidate.\nRequire Import Semantics.\nRequire Import System.\nRequire Import Model.\nRequire Import MapTerm.\nRequire Import Extend.\nRequire Import Ofe.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import SemanticsKnot.\nRequire Import Spaces.\nRequire Import Equality.\nRequire Import Truncate.\nRequire Import Uniform.\nRequire Import Standard.\nRequire Import Hygiene.\nRequire Import Relation.\nRequire Import Dynamic.\nRequire Import ExtendTruncate.\nRequire Import ProperDownward.\n\nRequire Import SemanticsPi.\nRequire Import SemanticsEqual.\nRequire Import SemanticsAll.\nRequire Import SemanticsExist.\nRequire Import SemanticsMu.\nRequire Import SemanticsUniv.\nRequire Import SemanticsFut.\nRequire Import SemanticsGuard.\nRequire Import SemanticsKuniv.\nRequire Import SemanticsQuotient.\nRequire Import SemanticsSet.\nRequire Import SemanticsSigma.\nRequire Import SemanticsSimple.\nRequire Import SemanticsSubtype.\nRequire Import SemanticsWtype.\nRequire Import SemanticsEqtype.\nRequire Import ExtSpace.\nRequire Import PreSpacify.\nRequire Import Reduction.\nRequire Import Equivalence.\nRequire Import ProperEquiv.\nRequire Import ProperClosed.\nRequire Import SemanticsPositive.\n\n\n\n(* Not true for kinterp and cinterp. *)\nLemma interp_increase :\n  forall pg pg' s i a X,\n    le_page pg pg'\n    -> interp pg s i a X\n    -> interp pg' s i a X.\nProof.\nexploit \n  (semantics_ind the_system\n     (fun pg s i a X => True)\n     (fun pg s i a X => True)\n     (fun pg s i a X => forall pg', le_page pg pg' -> basicv the_system pg' s i a X)\n     (fun pg s i a X => True)\n     (fun pg s i a X => True)\n     (fun pg s i a X => forall pg', le_page pg pg' -> basic the_system pg' s i a X)\n     (fun pg s i A b B => forall pg', le_page pg pg' -> functional the_system pg' s i A b B))\n  as Hind;\neauto 6 using le_ord_trans, lt_le_ord_trans, le_ord_refl, str_mono, cex_mono, cin_mono, upd_cin_mono, le_page_trans with semantics.\n\n(* kuniv *)\n{\nintros pg s i m gpg h Hlv Hlt pg' Hlt'.\napply interp_kuniv; auto.\neapply lt_le_page_trans; eauto.\n}\n\n(* wrapup *)\n{\ndestruct Hind as (_ & _ & Hy & _).\nintros; eapply Hy; eauto.\n}\nQed.\n\n\nDefinition restrict_xobj (w : ordinal) (x : xobj stop) : xobj stop\n  :=\n  match x with\n  | objnone => objnone\n\n  | objsome Q h =>\n      match lt_ord_dec (level (pi1 Q)) w with\n      | left _ =>\n          objsome Q h\n\n      | right _ =>\n          objnone\n      end\n  end.\n\n\nDefinition restrict (w : ordinal) (x : obj stop) : obj stop\n  :=\n  objin (restrict_xobj w (objout x)).\n\n\nDefinition restrict_term (w : ordinal) (m : wterm stop) : wterm stop\n  :=\n  map_term (restrict w) m.\n\n\nLemma restrict_extend :\n  forall w m,\n    restrict_term w m\n    =\n    map_term (extend w stop) (map_term (extend stop w) m).\nProof.\nintros w m.\nrewrite -> map_term_compose.\nunfold restrict_term.\nf_equal.\nfextensionality 1.\nintro x.\nunfold restrict, extend, restrict_xobj, extend_xobj.\nf_equal.\nrewrite -> !objout_objin.\nset (y := objout x).\ndestruct y as [Q h |]; auto.\nset (X := lt_ord_dec (level (pi1 Q)) w).\ndestruct X as [Hlt | Hnlt]; auto.\nrewrite -> (lt_ord_dec_is _ _ h).\nreflexivity.\nQed.\n\n\nLemma restrict_ext :\n  forall w x,\n    restrict_term w (ext x) = ext (restrict w x).\nProof.\nintros w x.\nreflexivity.\nQed.\n\n\nLemma restrict_extt :\n  forall w x,\n    restrict_term w (extt x) = extt (restrict w x).\nProof.\nintros w x.\nreflexivity.\nQed.\n\n\n(* Don't think we actually use this. *)\nLemma restrict_idem :\n  forall w m, restrict_term w (restrict_term w m) = restrict_term w m.\nProof.\nintros w m.\nrewrite -> !restrict_extend.\n(* We know perfectly well that we'll have w <<= stop, but writing it this way\n   removes an annoying obligation.\n*)\nso (le_lt_ord_dec w stop) as [Hle | Hlt].\n  {\n  rewrite -> !(extend_term_cancel w stop); auto.\n  }\n\n  {\n  rewrite -> !(extend_term_cancel stop w); auto using lt_ord_impl_le_ord.\n  }\nQed.\n\n\nLemma extend_iurel_noncontractive :\n  forall v w (h : v <<= w) n (A B : car (wiurel_ofe v)),\n    @dist (wiurel_ofe w) n (extend_iurel h A) (extend_iurel h B)\n    -> dist n A B.\nProof.\nintros v w h n A B Hdist.\napply (dist_trans _ _ _ (iutruncate n A)).\n  {\n  apply dist_symm.\n  apply iutruncate_near.\n  }\napply (dist_trans _ _ _ (iutruncate n B)).\n2:{\n  apply iutruncate_near.\n  }\napply dist_refl'.\napply (extend_iurel_inj _ _ h).\nrewrite <- !iutruncate_extend_iurel.\napply iutruncate_collapse; auto.\nQed.\n\n\n(* restriction w m n  means that n can be obtained from m by replacing\n   objnones with objsomes at level at least w.\n\n   They cannot be replaced with just objsome at any level, because we\n   want the restrict_restriction property to hold.  More on why it\n   works this way in the comment preceding semantics_restriction.  \n*)\n\nInductive restriction (w : ordinal) : sterm -> sterm -> Prop :=\n| restriction_var :\n    forall i,\n      restriction w (var i) (var i)\n\n| restriction_oper :\n    forall a th r s,\n      restriction_row w a r s\n      -> restriction w (oper a th r) (oper a th s)\n\n| restriction_ext :\n    forall Q h,\n      w <<= level (pi1 Q)\n      -> restriction w (ext (objin objnone)) (ext (objin (objsome Q h)))\n\n| restriction_extt :\n    forall Q h,\n      w <<= level (pi1 Q)\n      -> restriction w (extt (objin objnone)) (extt (objin (objsome Q h)))\n\nwith restriction_row (w : ordinal) : forall a, row (obj stop) a -> row (obj stop) a -> Prop :=\n| restriction_nil :\n    restriction_row w nil rw_nil rw_nil\n\n| restriction_cons :\n    forall j a m n r s,\n      restriction w m n\n      -> restriction_row w a r s\n      -> restriction_row w (cons j a) (rw_cons m r) (rw_cons n s)\n.\n\n\nScheme restriction_term_mut_ind := Minimality for restriction Sort Prop\nwith   restriction_row_mut_ind := Minimality for restriction_row Sort Prop.\nCombined Scheme restriction_mut_ind from restriction_term_mut_ind, restriction_row_mut_ind.\n\n\nLemma restrict_restriction :\n  forall w m n,\n    restriction w m n\n    -> map_term (extend stop w) m = map_term (extend stop w) n.\nProof.\nintros w m n Hrest.\ninduct Hrest\n  using (fun X => restriction_term_mut_ind w X\n           (fun a r r' => map_row (extend stop w) r = map_row (extend stop w) r'));\nauto.\n\n(* oper *)\n{\nintros a th r s _ IH.\ncbn.\nf_equal.\napply IH.\n}\n\n(* ext *)\n{\nintros Q h Hwv.\ncbn.\nf_equal.\nf_equal.\nunfold extend.\nrewrite -> !objout_objin.\nf_equal.\ncbn.\nassert (~ level (pi1 Q) << w) as Hnlt.\n  {\n  intro H.\n  apply (lt_ord_irrefl w).\n  eapply le_lt_ord_trans; eauto.\n  }\nrewrite -> (lt_ord_dec_is_not _ _ Hnlt).\nreflexivity.\n}\n\n(* extt *)\n{\nintros Q h Hwv.\ncbn.\nf_equal.\nf_equal.\nunfold extend.\nrewrite -> !objout_objin.\nf_equal.\ncbn.\nassert (~ level (pi1 Q) << w) as Hnlt.\n  {\n  intro H.\n  apply (lt_ord_irrefl w).\n  eapply le_lt_ord_trans; eauto.\n  }\nrewrite -> (lt_ord_dec_is_not _ _ Hnlt).\nreflexivity.\n}\n\n(* cons *)\n{\nintros j a m n r s _ IH1 _ IH2.\ncbn.\nf_equal; auto.\n}\nQed.\n\n\nLemma restrict_impl_restriction :\n  forall w m,\n    restriction w (restrict_term w m) m.\nProof.\nintros w m.\npattern m.\napply (syntax_ind _ _ (fun a r => restriction_row w a (map_row (restrict w) r) r)); clear m;\neauto using restriction, restriction_row.\n(* oper *)\nintros a th r IH.\ncbn.\nrevert r IH.\ncases th; eauto using restriction_oper.\n\n(* ext *)\nintros x r Hr.\ninvertc Hr.\nintros _ <-.\ncbn.\nrewrite <- (objin_objout _ x) at 2.\nunfold restrict, restrict_xobj.\nset (y := objout x).\ndestruct y as [Q h |].\n  {\n  set (X := lt_ord_dec (level (pi1 Q)) w).\n  destruct X as [Hlt | Hnlt].\n    {\n    apply restriction_oper.\n    apply restriction_nil.\n    }\n\n    {\n    apply restriction_ext.\n    apply not_lt_ord_impl_le_ord; auto.\n    }\n  }\n\n  {\n  apply restriction_oper.\n  apply restriction_nil.\n  }\n\n(* extt *)\nintros x r Hr.\ninvertc Hr.\nintros _ <-.\ncbn.\nrewrite <- (objin_objout _ x) at 2.\nunfold restrict, restrict_xobj.\nset (y := objout x).\ndestruct y as [Q h |].\n  {\n  set (X := lt_ord_dec (level (pi1 Q)) w).\n  destruct X as [Hlt | Hnlt].\n    {\n    apply restriction_oper.\n    apply restriction_nil.\n    }\n\n    {\n    apply restriction_extt.\n    apply not_lt_ord_impl_le_ord; auto.\n    }\n  }\n\n  {\n  apply restriction_oper.\n  apply restriction_nil.\n  }\nQed.\n\n\nLemma restriction_decrease :\n  forall v w m n, v <<= w -> restriction w m n -> restriction v m n.\nProof.\nintros v w m n Hvw Hrest.\ninduct Hrest\n  using (fun X => restriction_term_mut_ind w X\n           (fun a r s => restriction_row v a r s)); \neauto using restriction, restriction_row, le_ord_trans.\nQed.\n\n\n(* This bobj stuff is pretty clumsy, but it allows us to reuse map_term results for restriction. *)\n\nInductive bobj w : Type :=\n| bobj_some : forall (Q : candidate), option (w <<= level (pi1 Q)) -> level (pi1 Q) << stop -> bobj w\n\n| bobj_none : bobj w\n.\n\n\nDefinition bobj_left w (x : bobj w) : obj stop :=\n  match x with\n  | bobj_some _ Q op h =>\n      objin (match op with\n             | Some _ => objnone\n             | None => objsome Q h\n             end)\n  | bobj_none _ => objin objnone\n  end.\n\n\nDefinition bobj_right w (x : bobj w) : obj stop :=\n  match x with\n  | bobj_some _ Q _ h => objin (objsome Q h)\n\n  | bobj_none _ => objin objnone\n  end.\n\n\nDefinition bobj_in w (x : obj stop) : bobj w :=\n  match objout x with\n  | objsome Q h => bobj_some _ Q None h\n  | objnone => bobj_none _\n  end.\n\n\nLemma bobj_left_in :\n  forall w x, bobj_left w (bobj_in w x) = x.\nProof.\nintros w x.\nrewrite <- (objin_objout _ x) at 2.\nunfold bobj_left, bobj_in.\nset (y := objout x).\ndestruct y as [Q h |]; auto.\nQed.\n\n\nLemma bobj_right_in :\n  forall w x, bobj_right w (bobj_in w x) = x.\nProof.\nintros w x.\nrewrite <- (objin_objout _ x) at 2.\nunfold bobj_right, bobj_in.\nset (y := objout x).\ndestruct y as [Q h |]; auto.\nQed.\n\n\nLemma map_as_restriction :\n  forall w m,\n    restriction w (map_term (bobj_left w) m) (map_term (bobj_right w) m).\nProof.\nintros w m.\ninduct m using\n  (fun X => term_mut_ind _ X\n     (fun a r => restriction_row w a (map_row (bobj_left w) r) (map_row (bobj_right w) r)));\neauto using restriction, restriction_row.\n(* oper *)\nintros a th r IH.\ncbn.\nrevert r IH.\ncases th; eauto using restriction_oper.\n\n(* ext *)\n{\nintros x r _.\nso (row_nil_invert _ r); subst r.\ncbn.\ndestruct x as [Q op h |].\n  {\n  destruct op as [h' |].\n    {\n    cbn.\n    apply restriction_ext; auto.\n    }\n\n    {\n    cbn.\n    apply restriction_oper.\n    apply restriction_nil.\n    }\n  }\n\n  {\n  cbn.\n  apply restriction_oper.\n  apply restriction_nil.\n  }\n}\n\n(* ext *)\n{\nintros x r _.\nso (row_nil_invert _ r); subst r.\ncbn.\ndestruct x as [Q op h |].\n  {\n  destruct op as [h' |].\n    {\n    cbn.\n    apply restriction_extt; auto.\n    }\n\n    {\n    cbn.\n    apply restriction_oper.\n    apply restriction_nil.\n    }\n  }\n\n  {\n  cbn.\n  apply restriction_oper.\n  apply restriction_nil.\n  }\n}\nQed.\n\n\nLemma restriction_as_map :\n  forall w m n,\n    restriction w m n\n    -> exists (p : term (bobj w)),\n         m = map_term (bobj_left w) p\n         /\\ n = map_term (bobj_right w) p.\nProof.\nintros w m n H.\ninduct H\n  using (fun X => restriction_term_mut_ind w X\n           (fun a r s =>\n              exists (t : row (bobj w) a),\n                r = map_row (bobj_left w) t\n                /\\ s = map_row (bobj_right w) t)).\n\n(* var *)\n{\nintro i.\nexists (var i).\ncbn.\nauto.\n}\n\n(* oper *)\n{\nintros a th r s _ IH.\ndestruct IH as (t & -> & ->).\nexists (oper a (map_operator (bobj_in w) th) t).\nsplit.\n  {\n  cbn.\n  rewrite -> map_operator_compose.\n  f_equal.\n  etransitivity.\n    {\n    symmetry.\n    apply map_operator_id.\n    }\n  f_equal.\n  fextensionality 1.\n  intro x.\n  symmetry.\n  apply bobj_left_in.\n  }\n\n  {\n  cbn.\n  rewrite -> map_operator_compose.\n  f_equal.\n  etransitivity.\n    {\n    symmetry.\n    apply map_operator_id.\n    }\n  f_equal.\n  fextensionality 1.\n  intro x.\n  symmetry.\n  apply bobj_right_in.\n  }\n}\n\n(* ext *)\n{\nintros Q h h'.\nexists (ext (bobj_some _ Q (Some h') h)).\ncbn.\nsplit; auto.\n}\n\n(* extt *)\n{\nintros Q h h'.\nexists (extt (bobj_some _ Q (Some h') h)).\ncbn.\nsplit; auto.\n}\n\n(* nil *)\n{\nexists rw_nil.\nauto.\n}\n\n(* cons *)\n{\nintros j a m n r s _ (p & -> & ->) _ (t & -> & ->).\nexists (rw_cons p t).\nauto.\n}\nQed.   \n\n\nLemma restriction_refl :\n  forall w m, restriction w m m.\nProof.\nintros w m.\nso (map_as_restriction _ (map_term (bobj_in w) m)) as H.\nrewrite -> !map_term_compose in H.\nforce_exact H.\nf_equal.\n  {\n  rewrite <- (map_term_id _ m) at 2.\n  f_equal.\n  fextensionality 1.\n  intro x.\n  apply bobj_left_in.\n  }\n\n  {\n  rewrite <- (map_term_id _ m) at 2.\n  f_equal.\n  fextensionality 1.\n  intro x.\n  apply bobj_right_in.\n  }\nQed.\n\n\nLemma restriction_hygiene :\n  forall P w m n, restriction w m n -> hygiene P m -> hygiene P n.\nProof.\nintros P w m n Hrest Hhyg.\nso (restriction_as_map _#3 Hrest) as (p & -> & ->).\napply map_hygiene.\neapply map_hygiene_conv; eauto.\nQed.\n\n\nLemma restriction_subst :\n  forall w s m m',\n    restriction w m m'\n    -> restriction w (subst s m) (subst s m').\nProof.\nintros w s m n Hrest.\nso (restriction_as_map _#3 Hrest) as (p & -> & ->).\nreplace s with (map_sub (bobj_left w) (map_sub (bobj_in w) s)) at 1.\n2:{\n  rewrite -> map_sub_compose.\n  rewrite <- (map_sub_id _ s) at 2.\n  f_equal.\n  fextensionality 1.\n  intro x.\n  apply bobj_left_in.\n  }\nreplace s with (map_sub (bobj_right w) (map_sub (bobj_in w) s)) at 2.\n2:{\n  rewrite -> map_sub_compose.\n  rewrite <- (map_sub_id _ s) at 2.\n  f_equal.\n  fextensionality 1.\n  intro x.\n  apply bobj_right_in.\n  }\nrewrite <- !map_subst.\napply map_as_restriction.\nQed.\n\n\nLemma restriction_funct1_under :\n  forall w i n n' m m',\n    restriction w n n'\n    -> restriction w m m'\n    -> restriction w (subst (under i (dot n id)) m) (subst (under i (dot n' id)) m').\nProof.\nintros w i n n' m m' Hrestn Hrestm.\nso (restriction_as_map _#3 Hrestm) as (p & -> & ->).\nso (restriction_as_map _#3 Hrestn) as (q & -> & ->).\nreplace (under i (dot (map_term (bobj_left w) q) id))\n  with  (map_sub (bobj_left w) (under i (dot q id))).\n2:{\n  simpmap.\n  reflexivity.\n  }\nreplace (under i (dot (map_term (bobj_right w) q) id))\n  with  (map_sub (bobj_right w) (under i (dot q id))).\n2:{\n  simpmap.\n  reflexivity.\n  }\nrewrite <- !map_subst.\napply map_as_restriction.\nQed.\n\n\nLemma restriction_funct1 :\n  forall w n n' m m',\n    restriction w n n'\n    -> restriction w m m'\n    -> restriction w (subst1 n m) (subst1 n' m').\nProof.\nintros w n n' m m' Hn Hm.\nunfold subst1.\nrewrite <- (under_zero _ (dot n id)).\nrewrite <- (under_zero _ (dot n' id)).\napply restriction_funct1_under; auto.\nQed.\n\n\nLemma restriction_reduces :\n  forall w m n p,\n    restriction w m n\n    -> star reduce m p\n    -> exists q,\n         restriction w p q\n         /\\ star reduce n q.\nProof.\nintros w m n p Hrest Hsteps.\nso (restriction_as_map _#3 Hrest) as (q & -> & ->).\nso (map_reduces_form _#5 Hsteps) as (r & -> & Hreduces').\nexists (map_term (bobj_right w) r).\nsplit.\n  {\n  apply map_as_restriction.\n  }\n\n  {\n  apply map_reduces; auto.\n  }\nQed.\n\n\nLemma restriction_steps :\n  forall w m n p,\n    restriction w m n\n    -> star step m p\n    -> exists q,\n         restriction w p q\n         /\\ star step n q.\nProof.\nintros w m n p Hrest Hsteps.\nso (restriction_as_map _#3 Hrest) as (q & -> & ->).\nso (map_steps_form _#5 Hsteps) as (r & -> & Hsteps').\nexists (map_term (bobj_right w) r).\nsplit.\n  {\n  apply map_as_restriction.\n  }\n\n  {\n  apply map_steps; auto.\n  }\nQed.\n\n\nLemma restriction_sh1_form :\n  forall w m n,\n    restriction w (subst sh1 m) n\n    -> exists n', n = subst sh1 n' /\\ restriction w m n'.\nProof.\nintros w m n Hrest.\nso (restriction_as_map _#3 Hrest) as (p & Heq & ->).\nsymmetry in Heq.\nso (map_term_sh1_form _#5 Heq) as (n & -> & ->).\nexists (map_term (bobj_right w) n).\nsplit.\n  {\n  rewrite -> map_subst.\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  apply map_as_restriction.\n  }\nQed.\n\n\nLemma restriction_robust :\n  forall w m n,\n    restriction w m n\n    -> robust 0 m <-> robust 0 n.\nProof.\nintros w m n Hrest.\nso (restriction_as_map _#3 Hrest) as (p & -> & ->).\nsplit; intro H; apply map_robust; eapply map_robust_conv; eauto.\nQed.\n\n\nLemma restriction_positive :\n  forall w m n,\n    restriction w m n\n    -> positive 0 m <-> positive 0 n.\nProof.\nintros w m n Hrest.\nso (restriction_as_map _#3 Hrest) as (p & -> & ->).\nsplit; intro H; apply map_positive; eapply map_positive_conv; eauto.\nQed.\n\n\nLemma restriction_negative :\n  forall w m n,\n    restriction w m n\n    -> negative 0 m <-> negative 0 n.\nProof.\nintros w m n Hrest.\nso (restriction_as_map _#3 Hrest) as (p & -> & ->).\nsplit; intro H; apply map_negative; eapply map_negative_conv; eauto.\nQed.\n\n\n(* The outer induction hypothesis. *)\nDefinition levind (w : ordinal) : Prop\n  :=\n  (forall pg s i a a' R,\n     str pg << w\n     -> cex pg <<= stop\n     -> restriction (cex pg) a a'\n     -> kinterp pg s i a R\n     -> kinterp pg s i a' R)\n  /\\\n  (forall pg s i a a' R,\n     str pg << w\n     -> cex pg <<= stop\n     -> restriction (cex pg) a a'\n     -> interp pg s i a R\n     -> interp pg s i a' R)\n  /\\\n  (forall pg s i a R v,\n     str pg << w\n     -> cex pg << v\n     -> v <<= stop\n     -> kinterp pg s i a R\n     -> kinterp pg s i (restrict_term v a) R)\n  /\\\n  (forall pg s i a R v,\n     str pg << w\n     -> cex pg << v\n     -> v <<= stop\n     -> interp pg s i a R\n     -> interp pg s i (restrict_term v a) R).\n\n\nLemma levind_decrease :\n  forall v w,\n    v <<= w\n    -> levind w\n    -> levind v.\nProof.\nintros v w Hvw H.\nunfold levind in H.\ndestruct H as (IH1 & IH2 & IH3 & IH4).\ndo2 3 split.\n  {\n  intros pg s i a a' R Hstr Hcex Hrest Hint.\n  eapply IH1; eauto using lt_le_ord_trans.\n  }\n\n  {\n  intros pg s i a a' R Hstr Hcex Hrest Hint.\n  eapply IH2; eauto using lt_le_ord_trans.\n  }\n\n  {\n  intros pg s i a R u Hstr Hcex Hu Hint.\n  eapply IH3; eauto using lt_le_ord_trans.\n  }\n\n  {\n  intros pg s i a R u Hstr Hcex Hu Hint.\n  eapply IH4; eauto using lt_le_ord_trans.\n  }\nQed.\n\n\nLemma interp_kext_bound :\n  forall pg i k K,\n    interp_kext pg i k K\n    -> level K <<= cin pg.\nProof.\nintros pg i k K H.\ndestruct H as (Q & h & _ & _ & Hlev & <-).\neapply le_ord_trans; eauto.\napply approx_level.\nQed.\n\n\nLemma semantics_level_bound :\n  (forall pg s i k K,\n     kinterp pg s i k K\n     -> level K <<= cin pg)\n  /\\\n  (forall pg s i c Q,\n     cinterp pg s i c Q\n     -> level (pi1 Q) <<= cin pg).\nProof.\nexploit\n  (semantics_ind the_system\n     (fun pg s i k K => level K <<= cin pg)\n     (fun pg s i a Q => level (pi1 Q) <<= cin pg)\n     (fun pg s i a R => True)\n     (fun pg s i k K => level K <<= cin pg)\n     (fun pg s i a Q => level (pi1 Q) <<= cin pg)\n     (fun pg s i a R => True)\n     (fun pg s i A b B => True))\n  as Hind;\ntry (intros; cbn; eauto using max_ord_lub, le_ord_zero, le_ord_trans, le_ord_refl; done).\n\n(* ext *)\n{\nintros pg s i Q h Hcin.\ncbn.\neapply le_ord_trans; eauto.\napply approx_level.\n}\n\n(* clam *)\n{\nintros pg s i k a K L A h HeqL Hk _ IH.\ncbn.\napply max_ord_lub; eauto using interp_kext_bound.\nso (IH i (le_refl _) (space_inhabitant _)) as H.\ncbn in H.\nrewrite <- HeqL in H.\nauto.\n}\n\n(* capp *)\n{\nintros pg s i a b K L A B _ IH _ _.\ncbn.\ncbn in IH.\neapply le_ord_trans; eauto.\napply le_ord_max_r.\n}\n\n(* ctlam *)\n{\nintros pg s i a b k K A f B _ _ Hk _ _ _.\ncbn.\napply max_ord_lub; auto using le_ord_refl.\neapply interp_kext_bound; eauto.\n}\n\n(* ctapp *)\n{\nintros pg s i b m l A K B n p Hnp _ _ IH.\ncbn.\ncbn in IH.\nexact (max_ord_lub_r _#3 IH).\n}\n\n(* cpi1 *)\n{\nintros pg s i a K L x _ IH.\ncbn.\ncbn in IH.\neapply max_ord_lub_l; eauto.\n}\n\n(* cpi2 *)\n{\nintros pg s i a K L x _ IH.\ncbn.\ncbn in IH.\neapply max_ord_lub_r; eauto.\n}\n\n(* wrapup *)\n{\ndestruct_all Hind; split; intros; eauto.\n}\nQed.\n\n\nLemma kinterp_level_bound :\n  forall pg s i k K,\n    kinterp pg s i k K\n    -> level K <<= cin pg.\nProof.\nexact (semantics_level_bound andel).\nQed.\n\n\nLemma cinterp_level_bound :\n  forall pg s i c Q,\n    cinterp pg s i c Q\n    -> level (pi1 Q) <<= cin pg.\nProof.\nexact (semantics_level_bound ander).\nQed.\n\n\n(* In retrospect, it might have been better to state the conclusion as\n   R = blur (cin pg) stop R.  But I'm not going back and changing it now.\n*)\nLemma semantics_level_internal :\n  forall pg s i a R (h : cin pg <<= stop),\n    levind (str pg)\n    -> interp pg s i a R\n    -> exists R', R = extend_iurel h R'.\nProof.\nexploit\n  (semantics_ind the_system\n     (fun pg s i k K => True)\n     (fun pg s i a Q => True)\n     (fun pg s i a R =>\n        levind (str pg) -> forall (h : cin pg <<= stop), exists R', R = extend_iurel h R')\n     (fun pg s i k K => True)\n     (fun pg s i a Q => True)\n     (fun pg s i a R =>\n        levind (str pg) -> forall (h : cin pg <<= stop), exists R', R = extend_iurel h R')\n     (fun pg s i A b B =>\n        levind (str pg)\n        -> forall\n             (A' : wurel (cin pg))\n             (heq : A = extend_urel (cin pg) stop A')\n             (h : cin pg <<= stop),\n               exists (B' : urelsp A' -n> wiurel_ofe (cin pg)),\n                 B =\n                 nearrow_compose \n                   (extend_iurel_ne h)\n                   (nearrow_compose\n                      B'\n                      (nearrow_compose\n                         (deextend_urelsp_ne h A')\n                         (transport_ne heq urelsp)))))                   \n  as Hind;\ntry (intros; cbn; eauto using max_ord_lub, le_ord_zero, le_ord_trans; done).\n\n(* con *)\n{\nintros pg s i lv a gpg R Hlv Hle Ha _ IHo h.\nexists (extend_iurel (cin_mono _ _ Hle) R).\nrewrite <- extend_iurel_compose.\nf_equal.\napply proof_irrelevance.\n}\n\n(* karrow_type *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo h) as (B' & ->).\nexists (iuarrow (cin pg) i A' B').\nrewrite -> extend_iuarrow.\nreflexivity.\n}\n\n(* arrow *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo h) as (B' & ->).\nexists (iuarrow (cin pg) i A' B').\nrewrite -> extend_iuarrow.\nreflexivity.\n}\n\n(* pi *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (den A') (eq_refl _) h) as (B' & ->).\nclear IH1 IH2.\nexists (iupi (cin pg) i A' B').\nrewrite -> extend_iupi.\nf_equal.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\n}\n\n(* intersect *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (den A') (eq_refl _) h) as (B' & ->).\nclear IH1 IH2.\nexists (iuintersect (cin pg) i A' B').\nrewrite -> extend_iuintersect.\nf_equal.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\n}\n\n(* prod *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo h) as (B' & ->).\nexists (iuprod (cin pg) A' B').\nrewrite -> extend_iuprod.\nreflexivity.\n}\n\n(* sigma *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (den A') (eq_refl _) h) as (B' & ->).\nclear IH1 IH2.\nexists (iusigma (cin pg) A' B').\nrewrite -> extend_iusigma.\nf_equal.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\n}\n\n(* set *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (den A') (eq_refl _) h) as (B' & ->).\nclear IH1 IH2.\nexists (iuset (cin pg) A' B').\nrewrite -> extend_iuset.\nf_equal.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\n}\n\n(* quotient *)\n{\nintros pg s i a b A B hs ht _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nset (Heq := eqsymm (extend_prod _ _ h (den A') (den A'))).\nso (IH2 IHo (prod_urel (cin pg) (den A') (den A')) Heq h) as (B' & ->).\ncbn in hs.\nso (deextend_symmish _ _ h (den A') (fun x => den (pi1 B' x)) hs) as hs'.\nso (deextend_transish _ _ h (den A') (fun x => den (pi1 B' x)) ht) as ht'.\nexists (iuquotient (cin pg) A' B' hs' ht').\nrewrite -> extend_iuquotient.\napply iuquotient_compat.\napply eq_impl_eq_dep_snd.\napply nearrow_extensionality.\nintros; auto.\n}\n\n(* guard *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (squash_urel (cin pg) (den A') i) (eqsymm (extend_squash _#4 h)) h) as (B' & ->).\nexists (iuguard (cin pg) i A' B').\nrewrite -> extend_iuguard.\nreflexivity.\n}\n\n(* fut zero *)\n{\nintros pg s a Hcla IHo h.\nexists (iufut0 (cin pg)).\nrewrite -> extend_iufut0.\nreflexivity.\n}\n\n(* fut *)\n{\nintros pg s i a A _ IH IHo h.\nso (IH IHo h) as (R & ->).\nexists (iufut (cin pg) (S i) R).\nrewrite -> extend_iufut.\nreflexivity.\n}\n\n(* void *)\n{\nintros pg s i H h.\nexists (iubase (void_urel (cin pg))).\nrewrite -> extend_iubase.\nrewrite -> extend_void; auto.\n}\n\n(* unit *)\n{\nintros pg s i H h.\nexists (iubase (unit_urel (cin pg) i)).\nrewrite -> extend_iubase.\nrewrite -> extend_unit; auto.\n}\n\n(* bool *)\n{\nintros pg s i H h.\nexists (iubase (bool_urel (cin pg) i)).\nrewrite -> extend_iubase.\nrewrite -> extend_bool; auto.\n}\n\n(* wt *)\n{\nintros pg s i a b A B _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (A' & ->).\nso (IH2 IHo (den A') (eq_refl _) h) as (B' & ->).\nclear IH1 IH2.\nexists (iuwt (cin pg) A' B').\nrewrite -> extend_iuwt.\nf_equal.\napply nearrow_extensionality.\nintro x.\ncbn.\nreflexivity.\n}\n\n(* equal *)\n{\nintros pg s i a m n p q A Hmp Hnq _ IH IHo h.\nso (IH IHo h) as (A' & ->).\nassert (srel s (den A') i (map_term (extend stop (cin pg)) m) (map_term (extend stop (cin pg)) p)) as Hmp'.\n  {\n  cbn in Hmp.\n  exact (extend_srel _#7 andel Hmp).\n  }\nassert (srel s (den A') i (map_term (extend stop (cin pg)) n) (map_term (extend stop (cin pg)) q)) as Hnq'.\n  {\n  cbn in Hnq.\n  exact (extend_srel _#7 andel Hnq).\n  }\nexists (iuequal (cin pg) s i A' _#4 Hmp' Hnq').\nrewrite -> extend_iuequal'.\napply iuequal_equal'; auto.\n  {\n  cbn.\n  rewrite -> extend_srel.\n  rewrite -> extend_term_compose_down; auto.\n  rewrite -> extend_term_compose_down; auto using le_ord_refl.\n  }\n\n  {\n  cbn.\n  rewrite -> extend_srel.\n  rewrite -> extend_term_compose_down; auto.\n  rewrite -> extend_term_compose_down; auto using le_ord_refl.\n  }\n}\n\n(* eqtype *)\n{\nintros pg s i a b R R' _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (Q & ->).\nso (IH2 IHo h) as (Q' & ->).\nexists (iueqtype (cin pg) i Q Q').\nunfold extend_iurel at 3.\nunfold iueqtype, eqtype_urel.\ncbn [fst snd].\nf_equal.\n  {\n  rewrite -> extend_property; auto.\n  apply property_urel_extensionality; auto.\n  intros j Hj.\n  unfold eqtype_property.\n  rewrite -> !iutruncate_extend_iurel.\n  split.\n    {\n    intros H.\n    eapply extend_iurel_inj.\n    exact H.\n    }\n\n    {\n    intro H.\n    f_equal; auto.\n    }\n  }\n\n  {\n  rewrite -> extend_meta_pair.\n  rewrite -> !extend_meta_iurel; auto.\n  }\n}\n\n(* subtype *)\n{\nintros pg s i a b R R' _ IH1 _ IH2 IHo h.\nso (IH1 IHo h) as (Q & ->).\nso (IH2 IHo h) as (Q' & ->).\nexists (iusubtype (cin pg) i Q Q').\nunfold extend_iurel at 3.\nunfold iusubtype, subtype_urel.\ncbn [fst snd].\nf_equal.\n  {\n  rewrite -> extend_property; auto.\n  apply property_urel_extensionality; auto.\n  intros j Hj.\n  unfold subtype_property.\n  split.\n    {\n    intros Hact k m p Hk Hmp.\n    exploit (Hact k (map_term (extend (cin pg) stop) m) (map_term (extend (cin pg) stop) p)) as H; auto.\n      {\n      cbn.\n      rewrite -> !extend_term_cancel; auto.\n      }\n    cbn in H.\n    rewrite -> !extend_term_cancel in H; auto.\n    }\n\n    {\n    intros Hact k m p Hk Hmp.\n    cbn.\n    apply Hact; auto.\n    }\n  }\n\n  {\n  rewrite -> extend_meta_pair.\n  rewrite -> !extend_meta_iurel; auto.\n  }\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A lev Hlv HintK _ Hle _ IH IHo h.\nset (wc := cin pg).\nso (kbasic_impl_approx _#6 HintK) as HeqK.\nassert (forall (x : spcar K),\n          exists! (R : wiurel wc),\n            iutruncate (S i) (pi1 A (std (S i) K x))\n            =\n            extend_iurel h R)\n  as Hexuniq.\n  {\n  intro x.\n  so (IH i (le_refl _) (transport HeqK spcar x) IHo h) as (R & HR).\n  exists R.\n  split.\n    {\n    rewrite <- HR.\n    rewrite -> embed_approx'.\n    reflexivity.\n    }\n\n    {\n    intros R' HR'.\n    apply (extend_iurel_inj _ _ h).\n    rewrite <- HR.\n    rewrite <- HR'.\n    rewrite -> embed_approx'.\n    reflexivity.\n    }\n  }\nso (choice _#3 Hexuniq) as (f & Hf).\nassert (@nonexpansive (space K) (wiurel_ofe wc) f) as Hne.\n  {\n  intros n x y Hdist.\n  apply (extend_iurel_noncontractive _ _ h).\n  rewrite <- !Hf.\n  apply iutruncate_nonexpansive.\n  apply (pi2 A).\n  apply std_nonexpansive; auto.\n  }\nset (A' := expair f Hne : space K -n> wiurel_ofe wc).\nexists (iuall wc K A').\nrewrite -> extend_iuall.\nf_equal.\nrewrite -> std_arrow_is.\ncbn.\napply nearrow_extensionality.\nintro x.\ncbn.\nchange (std (S i) (qtype stop) (pi1 A (std (S i) K x)) = extend_iurel h (f x)).\nrewrite -> std_type_is.\nrewrite <- Hf.\nreflexivity.\n}\n\n(* alltp *)\n{\nintros pg s i a A _ IH IHo h.\nset (wc := cin pg).\nso (choice (car (wiurel_ofe top)) (car (wiurel_ofe wc))\n      (fun X R => \n         iutruncate (S i) (pi1 A (X)) = extend_iurel h R)) as (f & Hf).\n  {\n  intro X.\n  so (IH i (le_refl _) X IHo h) as (R & Heq).\n  exists R.\n  split; auto.\n  intros R' Heq'.\n  exact (extend_iurel_inj _ _ h _ _ (eqtrans (eqsymm Heq) Heq')).\n  }\nassert (nonexpansive f) as Hne.\n  {\n  intros n x y Hdist.\n  apply (extend_iurel_noncontractive _ _ h).\n  rewrite <- !Hf.\n  apply iutruncate_nonexpansive.\n  apply (pi2 A); auto.\n  }\nexists (iualltp wc (expair f Hne)).\nrewrite -> extend_iualltp.\nf_equal.\napply nearrow_extensionality.\nintros X.\ncbn.\nrewrite <- Hf.\nreflexivity.\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A lev Hlv HintK _ Hle _ IH IHo h.\nset (wc := cin pg).\nso (kbasic_impl_approx _#6 HintK) as HeqK.\nassert (forall (x : spcar K),\n          exists! (R : wiurel wc),\n            iutruncate (S i) (pi1 A (std (S i) K x))\n            =\n            extend_iurel h R)\n  as Hexuniq.\n  {\n  intro x.\n  so (IH i (le_refl _) (transport HeqK spcar x) IHo h) as (R & HR).\n  exists R.\n  split.\n    {\n    rewrite <- HR.\n    rewrite -> embed_approx'.\n    reflexivity.\n    }\n\n    {\n    intros R' HR'.\n    apply (extend_iurel_inj _ _ h).\n    rewrite <- HR.\n    rewrite <- HR'.\n    rewrite -> embed_approx'.\n    reflexivity.\n    }\n  }\nso (choice _#3 Hexuniq) as (f & Hf).\nassert (@nonexpansive (space K) (wiurel_ofe wc) f) as Hne.\n  {\n  intros n x y Hdist.\n  apply (extend_iurel_noncontractive _ _ h).\n  rewrite <- !Hf.\n  apply iutruncate_nonexpansive.\n  apply (pi2 A).\n  apply std_nonexpansive; auto.\n  }\nset (A' := expair f Hne : space K -n> wiurel_ofe wc).\nexists (iuexist wc K A').\nrewrite -> extend_iuexist; auto using le_ord_refl.\nf_equal.\nrewrite -> std_arrow_is.\ncbn.\napply nearrow_extensionality.\nintro x.\ncbn.\nchange (std (S i) (qtype stop) (pi1 A (std (S i) K x)) = extend_iurel h (f x)).\nrewrite -> std_type_is.\nrewrite <- Hf.\nreflexivity.\n}\n\n(* extt *)\n{\nintros pg s i w R hw Hw IHo h.\nexists (extend_iurel Hw (iutruncate (S i) R)).\nrewrite <- extend_iurel_compose.\nf_equal.\napply proof_irrelevance.\n}\n\n(* mu *)\n{\nintros pg w s i a F Hw _ IH Hne Hmono Hrobust IHo h.\nexists (iubase (extend_urel w (cin pg) (mu_urel w (fun X => den (F X))))).\nrewrite -> extend_iubase.\nf_equal.\nrewrite <- extend_urel_compose_up; auto using cin_mono.\n}\n\n(* ispositive *)\n{\nintros pg s i a Hcl _ h.\nexists (iubase (ispositive_urel (cin pg) i a)).\nrewrite -> extend_iubase.\nunfold ispositive_urel.\nrewrite -> extend_property; auto.\n}\n\n(* isnegative *)\n{\nintros pg s i a Hcl _ h.\nexists (iubase (isnegative_urel (cin pg) i a)).\nrewrite -> extend_iubase.\nunfold isnegative_urel.\nrewrite -> extend_property; auto.\n}\n\n(* univ *)\n{\nintros pg s i lv gpg Hlv Hstr Hcex IHo h.\nset (wc := cin pg).\nexists ((extend_urel stop wc (univ_urel the_system i gpg),\n         meta_page gpg)).\nunfold iuuniv, extend_iurel.\ncbn.\nrewrite -> extend_meta_page.\nf_equal.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\npextensionality.\n  {\n  intros (Hj & R & Hm & Hp).\n  split; auto.\n  exists R.\n  rewrite -> sint_unroll in Hm, Hp |- *.\n  rewrite <- !restrict_extend.\n  split; apply (IHo anderrr); auto.\n  }\n\n  {\n  intros (Hj & R & Hm & Hp).\n  split; auto.\n  exists R.\n  rewrite -> sint_unroll in Hm, Hp |- *.\n  rewrite <- !restrict_extend in Hm, Hp.\n  so (lt_ord_impl_le_ord _ _ Hcex) as Hle.\n  so (le_ord_trans _#3 (cex_top gpg) (succ_nodecrease _)) as Hlestop.\n  so (restriction_decrease _#4 Hle (restrict_impl_restriction wc m)) as Hrestm.\n  so (restriction_decrease _#4 Hle (restrict_impl_restriction wc p)) as Hrestp.\n  split; eapply (IHo anderl); eauto.\n  }\n}\n\n(* kuniv *)\n{\nintros pg s i lv gpg hgt Hlv Hlt IHo h.\nset (wc := cin pg).\nexists ((extend_urel stop wc (kuniv_urel the_system i gpg hgt),\n         meta_page gpg)).\nunfold iukuniv, extend_iurel.\ncbn.\nrewrite -> extend_meta_page.\nf_equal.\napply urel_extensionality.\nfextensionality 3.\nintros j m p.\ncbn.\nso (lt_le_page_trans _#3 (lt_page_succ _ hgt) (lt_page_impl_le_page _ _ Hlt)) as Hlt'.\ndestruct Hlt as (Hstr & Hcex).\ndestruct Hlt' as (Hstr' & Hcex').\npextensionality.\n  {\n  intros (Hj & K & R & Hm & Hp & Hmt & Hpt).\n  split; auto.\n  exists K, R.\n  rewrite -> sintk_unroll in Hm, Hp |- *.\n  rewrite -> sint_unroll in Hmt, Hpt |- *.\n  rewrite <- !restrict_extend.\n  do2 3 split.\n    {\n    apply (IHo anderrl); auto.\n    }\n\n    {\n    apply (IHo anderrl); auto.\n    }\n\n    {\n    apply (IHo anderrr); auto.\n    }\n\n    {\n    apply (IHo anderrr); auto.\n    }\n  }\n\n  {\n  intros (Hj & K & R & Hm & Hp & Hmt & Hpt).\n  split; auto.\n  exists K, R.\n  rewrite -> sintk_unroll in Hm, Hp |- *.\n  rewrite -> sint_unroll in Hmt, Hpt |- *.\n  rewrite <- !restrict_extend in Hm, Hp, Hmt, Hpt.\n  do2 3 split.\n    {\n    eapply (IHo andel); eauto using lt_ord_impl_le_ord, le_ord_trans.\n    eapply restriction_decrease; eauto using restrict_impl_restriction, lt_ord_impl_le_ord.\n    }\n\n    {\n    eapply (IHo andel); eauto using lt_ord_impl_le_ord, le_ord_trans.\n    eapply restriction_decrease; eauto using restrict_impl_restriction, lt_ord_impl_le_ord.\n    }\n\n    {\n    eapply (IHo anderl); eauto.\n      {\n      eapply lt_le_ord_trans; eauto.\n      }\n    eapply restriction_decrease; eauto using restrict_impl_restriction, lt_ord_impl_le_ord.\n    }\n\n    {\n    eapply (IHo anderl); eauto.\n      {\n      eapply lt_le_ord_trans; eauto.\n      }\n    eapply restriction_decrease; eauto using restrict_impl_restriction, lt_ord_impl_le_ord.\n    }\n  }\n}\n\n(* functional *)\n{\nintros pg s i A' b B Hcl Hcoarse Hint IH IHo A heq h.\nsubst A'.\nset (wc := cin pg).\nassert (forall (C : urelsp_car A),\n          exists! (R : wiurel wc),\n            pi1 B (extend_urelsp h A C)\n            =\n            extend_iurel h R)\n  as Hexuniq.\n  {\n  intro C.\n  so (urelsp_eta _ _ C) as (j & m & p & Hmp & ->).\n  assert (rel (extend_urel wc stop A) j (map_term (extend wc stop) m) (map_term (extend wc stop) p)) as Hmp'.    \n    {\n    cbn.\n    rewrite -> !extend_term_cancel; auto.\n    }\n  so (transport Hcoarse (fun R => rel R j _ _) Hmp') as (H & _).\n  assert (j <= i) as Hj by omega; clear H.\n  so (IH j (map_term (extend wc stop) m) (map_term (extend wc stop) p) Hj Hmp' IHo h) as (R & Heq).\n  exists R.\n  split.\n    {\n    rewrite -> (extend_urelspinj _#8 Hmp').\n    exact Heq.\n    }\n\n    {\n    intros R' Heq'.\n    rewrite -> (extend_urelspinj _#8 Hmp') in Heq'.\n    apply (extend_iurel_inj _ _ h).\n    etransitivity.\n      {\n      symmetry.\n      exact Heq.\n      }\n    exact Heq'.\n    }\n  }\nso (choice _#3 Hexuniq) as (f & Hf).\nassert (@nonexpansive (urelsp A) (wiurel_ofe wc) f) as Hne.\n  {\n  intros n C D HCD.\n  apply (extend_iurel_noncontractive _ _ h).\n  rewrite <- !Hf.\n  apply (pi2 B).\n  apply extend_urelsp_nonexpansive; auto.\n  }\nexists (expair f Hne).\napply nearrow_extensionality.\nintro C.\ncbn.\n(* This seems more complicated than it should be. *)\nso (urelsp_eta _ _ C) as (j & m & p & Hmp & ->).\nrewrite -> deextend_urelsp_urelspinj.\nrewrite <- Hf.\nf_equal.\ncbn in Hmp.\nassert (rel (extend_urel wc stop A) j (map_term (extend wc stop) (map_term (extend stop wc) m)) (map_term (extend wc stop) (map_term (extend stop wc) p))) as Hmp'.\n  {\n  cbn.\n  rewrite -> !extend_term_cancel; auto.\n  }\nrewrite -> (extend_urelspinj _#8 Hmp').\napply urelspinj_equal.\ncbn.\nrewrite -> extend_term_cancel; auto.\n}\n\n(* wrapup *)\n{\ndestruct_all Hind; eauto.\n}\nQed.\n\n\nLemma natinterp_restriction :\n  forall w m m' i,\n    restriction w m m'\n    -> natinterp m i\n    -> natinterp m' i.\nProof.\nintros w m m' i Hrest Hint.\nrevert m' Hrest.\ninduct Hint.\n\n(* 0 *)\n{\nintros m n p Hclm Hstepsm Hstepsn Hstepsp m' Hrestm.\nso (restriction_steps _#4 Hrestm Hstepsm) as (np & H & Hstepsm').\ninvertc H.\nintros r Hr <-.\ninvertc Hr.\nintros n' r1 Hrestn Hr1 <-.\ninvertc Hr1.\nintros p' r2 Hrestp Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (ppair n' p') in *.\nso (restriction_steps _#4 Hrestn Hstepsn) as (q & H & Hstepsn').\ninvertc H.\nintros r Hr <-.\ninvertc Hr.\nintros <-.\nfold (@btrue (obj stop)) in *.\nso (restriction_steps _#4 Hrestp Hstepsp) as (? & H & Hl').\ninvertc H.\nintros r Hr <-.\ninvertc Hr.\nintros <-.\nfold (@triv (obj stop)) in *.\neapply natinterp_0; eauto.\neapply restriction_hygiene; eauto.\n}\n\n(* S *)\n{\nintros m n p i Hclm Hstepsm Hstepsn _ IH m' Hrestm.\nso (restriction_steps _#4 Hrestm Hstepsm) as (np & H & Hstepsm').\ninvertc H.\nintros r Hr <-.\ninvertc Hr.\nintros n' r1 Hrestn Hr1 <-.\ninvertc Hr1.\nintros p' r2 Hrestp Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (ppair n' p') in *.\nso (restriction_steps _#4 Hrestn Hstepsn) as (q & H & Hstepsn').\ninvertc H.\nintros r Hr <-.\ninvertc Hr.\nintros <-.\nfold (@bfalse (obj stop)) in *.\neapply natinterp_S; eauto.\neapply restriction_hygiene; eauto.\n}\nQed.\n\n\nLemma lvinterp_restriction :\n  forall w lv lv' u,\n    restriction w lv lv'\n    -> lvinterp lv u\n    -> lvinterp lv' u.\nProof.\nintros w lv lv' u Hrest Hlv.\ndestruct Hlv as (i & Hi & ->).\nexists i.\nsplit; auto.\neapply natinterp_restriction; eauto.\nQed.\n\n\nLemma pginterp_restriction :\n  forall w lv lv' pg,\n    restriction w lv lv'\n    -> pginterp lv pg\n    -> pginterp lv' pg.\nProof.\nintros w lv lv' pg Hrest Hlv.\ndestruct Hlv as (i & Hint & Hstr & Hcex & Hcin).\nexists i.\ndo2 3 split; auto.\neapply lvinterp_restriction; eauto.\nQed.\n\n\nLemma interp_kext_restriction :\n  forall w pg i k k' K,\n    restriction w k k'\n    -> interp_kext pg i k K\n    -> interp_kext pg i k' K.\nProof.\nintros w pg i k k' K Hrest Hint.\ndestruct Hint as (Q & h & Hcl & Hsteps & Hlev & <-).\nso (restriction_steps _#4 Hrest Hsteps) as (m & Hrest' & Hsteps').\nassert (m = ext (objin (objsome Q h))).\n  {\n  invertc Hrest'.\n    {\n    intros r Hr <-.\n    invertc Hr.\n    intros <-.\n    reflexivity.\n    }\n\n    {\n    intros Q' h' _ Heq _.\n    discriminate (objin_inj _ _ _ Heq).\n    }\n  }\nsubst m.\nso (restriction_hygiene _#4 Hrest Hcl) as Hcl'.\nexists Q, h.\nauto.\nQed.\n\n\nLemma interp_uext_restriction :\n  forall w pg i m m' R,\n    restriction w m m'\n    -> interp_uext pg i m R\n    -> interp_uext pg i m' R.\nProof.\nintros w pg i m m' R Hrest Hint.\ndestruct Hint as (v & Q & h & Hcl & Hsteps & Hlev & <-).\nso (restriction_steps _#4 Hrest Hsteps) as (n & Hrest' & Hsteps').\nassert (n = ext (objin (objsome (expair (qtype v) Q) h))).\n  {\n  invertc Hrest'.\n    {\n    intros r Hr <-.\n    invertc Hr.\n    intros <-.\n    reflexivity.\n    }\n\n    {\n    intros Q' h' _ Heq _.\n    discriminate (objin_inj _ _ _ Heq).\n    }\n  }\nsubst n.\nso (restriction_hygiene _#4 Hrest Hcl) as Hcl'.\nexists v, Q, h.\nauto.\nQed.\n\n\n(* We have to use restriction here, as opposed to saying\n   (a = restrict_term w a'), because the latter isn't preserved in\n   some cases.  For instance, in the clam case, you substitute using\n   an object that might be restricted away if you applied\n   (restrict_term w).\n\n   We use wc as the restriction level, which means that whenever\n   objnone is promoted to objsome, the level is at least wc.  (Which\n   means that (restrict_term wc) returns the same thing for each\n   term.)\n\n   In principle, we could say something stronger: that an objnone can\n   be promoted to any objsome, regardless of level.  But (to get ctapp\n   and equal to go through) this would require a similar property for\n   membership in uniform relations, which would be a bit messy to\n   state and which we would then have to prove for every type.  It\n   would be doable, but since we don't seem to need the stronger\n   statement, we don't bother.\n  *)\n\nLemma semantics_restriction :\n  (forall pg s i a a' Q,\n     levind (str pg)\n     -> restriction (cex pg) a a'\n     -> kinterp pg s i a Q\n     -> kinterp pg s i a' Q)\n  /\\\n  (forall pg s i a a' Q,\n     levind (str pg)\n     -> restriction (cex pg) a a'\n     -> cinterp pg s i a Q\n     -> cinterp pg s i a' Q)\n  /\\\n  (forall pg s i a a' R,\n     levind (str pg)\n     -> restriction (cex pg) a a'\n     -> interp pg s i a R\n     -> interp pg s i a' R).\nProof.\nexploit (semantics_ind the_system\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> kbasicv the_system pg s i m' X)\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> cbasicv the_system pg s i m' X)\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> basicv the_system pg s i m' X)\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> kbasic the_system pg s i m' X)\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> cbasic the_system pg s i m' X)\n           (fun pg s i m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> basic the_system pg s i m' X)\n           (fun pg s i A m X => forall m', levind (str pg) -> restriction (cex pg) m m' -> functional the_system pg s i A m' X))\n  as Hind;\ntry (intros;\n     match goal with\n     | H : restriction _ _ _ |- _ =>\n         invertc H\n     end;\n     intros;\n     (* keep from looping with repeat -- no operator has more than 3 subterms *)\n     do 4 (try\n             match goal with\n             | H : restriction_row _ _ _ _ |- _ =>\n                 invertc H; intros\n             end);\n     subst;\n     first [eapply interp_kunit\n           |eapply interp_type\n           |eapply interp_karrow\n           |eapply interp_ktarrow\n           |eapply interp_kprod\n           |eapply interp_kfut_zero\n           |eapply interp_kfut\n           |eapply interp_cunit\n           |eapply interp_capp\n           |eapply interp_cpair\n           |eapply interp_cpi1\n           |eapply interp_cpi2\n           |eapply interp_cnext_zero\n           |eapply interp_cnext\n           |eapply interp_cprev\n           |eapply interp_cty\n           |eapply interp_karrow_type\n           |eapply interp_arrow\n           |eapply interp_pi\n           |eapply interp_intersect\n           |eapply interp_prod\n           |eapply interp_sigma\n           |eapply interp_set\n           |eapply interp_fut_zero\n           |eapply interp_fut\n           |eapply interp_void\n           |eapply interp_unit\n           |eapply interp_bool\n           |eapply interp_guard\n           |eapply interp_wt\n           |eapply interp_eqtype\n           |eapply interp_subtype\n           ];\n     eauto using restriction_hygiene, restriction_decrease;\n     done).\n\n(* type *)\n{\nintros pg s i lv H mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv' Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (univ lv').\napply interp_type.\neapply pginterp_restriction; eauto.\n}\n\n(* krec *)\n{\nintros pg s i k K _ IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros k' r2 Hk Hr2 <-.\ninvert Hr2.\nintros <-.\nfold (rec k').\napply interp_krec.\napply IH; auto.\napply restriction_funct1; auto.\napply restriction_oper.\napply restriction_cons; auto.\n}\n\n(* ext *)\n{\nintros pg s i Q h Hcin mm _ Hrest.\ninvertc Hrest.\n  {\n  intros r1 Hr1 <-.\n  invertc Hr1.\n  intros <-.\n  apply interp_ext; auto.\n  }\n\n  {\n  intros Q' h' _ Heq <-.\n  discriminate (objin_inj _ _ _ Heq).\n  }\n}\n\n(* clam *)\n{\nintros pg s i k a K L A h HeqL Hintk _ IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros k' r2 Hk Hr2 <-.\ninvertc Hr2.\nintros a' r3 Ha Hr3 <-.\ninvertc Hr3.\nintros <-.\nfold (clam k' a').\neapply (interp_clam _#9 h); eauto using restriction_hygiene, interp_kext_restriction.\nintros j Hj x.\napply IH; auto.\napply restriction_subst; auto.\n}\n\n(* ctlam *)\n{\nintros pg s i a b k K A f B Hcl Hinta Hintk _ IH Hf mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros b' r3 Hb Hr3 <-.\ninvertc Hr3.\nintros k' r4 Hk Hr4 <-.\ninvertc Hr4.\nintros <-.\nfold (ctlam a' b' k').\neapply interp_ctlam; eauto using restriction_hygiene, restriction_decrease, interp_kext_restriction, interp_uext_restriction.\nintros j m n Hmn.\napply IH; auto.\napply restriction_subst; eauto using restriction_decrease.\n}\n\n(* ctapp *)\n{\nintros pg s i b m l A K B n p Hnp Hm Hintb IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros b' r2 Hb Hr2 <-.\ninvertc Hr2.\nintros m' r3 Hrestm Hr3 <-.\ninvertc Hr3.\nintros <-.\nfold (ctapp b' m').\neapply interp_ctapp; eauto.\nso (cinterp_level_bound _#5 Hintb) as Hlev.\ncbn in Hlev.\nso (le_ord_trans _#3 (le_ord_max_l l (level K)) (le_ord_trans _#3 Hlev (cin_cex pg))) as Hlev'.\nrewrite <- (restrict_restriction _#3 (restriction_decrease _#4 Hlev' Hrestm)); auto.\n}\n\n(* con *)\n{\nintros pg s i lv a gpg R Hintlv Hle _ IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv Hr2 <-.\ninvertc Hr2.\nintros a' r3 Ha Hr3 <-.\ninvertc Hr3.\nintros <-.\nfold (con lv' a').\neapply interp_con; eauto using pginterp_restriction.\napply IH; auto.\n  {\n  eapply levind_decrease; eauto.\n  apply str_mono; auto.\n  }\n\n  {\n  eapply restriction_decrease; eauto.\n  apply cex_mono; auto.\n  }\n}\n\n(* quotient *)\n{\nintros pg s i a b A B hs ht _ IH1 _ IH2 mm IHo Hrest.\ninvertc Hrest.\nintros r Hr <-.\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (a' & b' & ->).\nfold (quotient a' b') in *.\ninvertc Hr.\nintros Ha Hr.\ninvertc Hr.\nintros Hb _.\napply interp_quotient; auto using restriction_subst.\n}\n\n(* guard *)\n{\nintros pg s i a b A B _ IH1 _ IH2 mm IHo Hrest.\ninvertc Hrest.\nintros r Hr <-.\nso (row_invert_auto _ _ r) as H; cbn in H.\ndestruct H as (a' & b' & ->).\nfold (guard a' b') in *.\ninvertc Hr.\nintros Ha Hr.\ninvertc Hr.\nintros Hb _.\napply interp_guard; auto using restriction_subst.\n}\n\n(* equal *)\n{\nintros pg s i a m n p q A Hmp Hnq Hint IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros m' r3 Hm' Hr3 <-.\ninvertc Hr3.\nintros n' r4 Hn' Hr4 <-.\ninvertc Hr4.\nintros <-.\nfold (equal a' m' n').\nso (le_ord_trans _#3 (cin_top pg) (succ_nodecrease _)) as h.\nso (semantics_level_internal _#5 h IHo Hint) as (A' & ->).\nso Hmp as Hmp'.\nso Hnq as Hnq'.\nrewrite -> den_extend_iurel in Hmp', Hnq'.\nrewrite -> extend_srel in Hmp', Hnq'.\nrewrite -> (restrict_restriction _ m m') in Hmp'; auto.\n2:{\n  cbn.\n  exact (restriction_decrease _#4 (cin_cex pg) Hm').\n  }\nrewrite -> (restrict_restriction _ n n') in Hnq'; auto.\n2:{\n  cbn.\n  exact (restriction_decrease _#4 (cin_cex pg) Hn').\n  }\nrewrite <- extend_srel in Hmp', Hnq'.\nrewrite <- (den_extend_iurel _ _ h) in Hmp', Hnq'.\ncbn.\nmatch goal with\n| |- basicv _ _ _ _ _ ?X =>\n  replace X\n  with  (iuequal stop s i (extend_iurel h A') m' n' p q Hmp' Hnq')\nend.\n2:{\n  apply iuequal_equal; auto.\n  }\napply interp_equal; auto.\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A h Hintlv _ IH1 Hle _ IH2 mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv Hr2 <-.\ninvertc Hr2.\nintros k' r3 Hk Hr3 <-.\ninvertc Hr3.\nintros a' r4 Ha Hr4 <-.\ninvertc Hr4.\nintros <-.\nfold (all lv' k' a').\napply (interp_all _#7 gpg _ _ h); eauto using restriction_hygiene, pginterp_restriction.\n  {\n  apply IH1.\n    {\n    eapply levind_decrease; eauto.\n    apply str_mono; auto.\n    }\n\n    {\n    eapply restriction_decrease; eauto.\n    apply cex_mono; auto.\n    }\n  }\nintros j Hj x.\napply IH2; auto.\napply restriction_subst; auto.\n}\n\n(* alltp *)\n{\nintros pg s i a A _ IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros <-.\napply interp_alltp.\nintros j Hj x.\napply IH; auto.\napply restriction_subst; auto.\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A h Hintlv _ IH1 Hle _ IH2 mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv Hr2 <-.\ninvertc Hr2.\nintros k' r3 Hk Hr3 <-.\ninvertc Hr3.\nintros a' r4 Ha Hr4 <-.\ninvertc Hr4.\nintros <-.\nfold (all lv' k' a').\napply (interp_exist _#7 gpg _ _ h); eauto using restriction_hygiene, pginterp_restriction.\n  {\n  apply IH1.\n    {\n    eapply levind_decrease; eauto.\n    apply str_mono; auto.\n    }\n\n    {\n    eapply restriction_decrease; eauto.\n    apply cex_mono; auto.\n    }\n  }\nintros j Hj x.\napply IH2; auto.\napply restriction_subst; auto.\n}\n\n(* extt *)\n{\nintros pg s i w R h Hw m' IHo Hrest.\ninvertc Hrest.\n  {\n  intros r1 Hr1 <-.\n  invertc Hr1.\n  intros <-.\n  apply interp_extt; auto.\n  }\n\n  {\n  intros Q' h' _ Heq <-.\n  discriminate (objin_inj _ _ _ Heq).\n  }\n}\n\n(* mu *)\n{\nintros pg w s i a F Hw _ IH Hne Hmono Hrobust mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (mu a').\napply interp_mu; auto.\n  {\n  intros X h.\n  eapply IH; eauto.\n  apply restriction_subst; auto.\n  }\n\n  {\n  erewrite <- restriction_robust; eauto.\n  }\n}\n\n(* ispositive *)\n{\nintros pg s i a Hcl mm _ Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (ispositive a').\nreplace (ispositive_urel stop i a) with (ispositive_urel stop i a').\n2:{\n  apply property_urel_extensionality; auto.\n  intros _ _.\n  symmetry.\n  eapply restriction_positive; eauto.\n  }\napply interp_ispositive.\neapply restriction_hygiene; eauto.\n}\n\n(* isnegative *)\n{\nintros pg s i a Hcl mm _ Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros a' r2 Ha Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (isnegative a').\nreplace (isnegative_urel stop i a) with (isnegative_urel stop i a').\n2:{\n  apply property_urel_extensionality; auto.\n  intros _ _.\n  symmetry.\n  eapply restriction_negative; eauto.\n  }\napply interp_isnegative.\neapply restriction_hygiene; eauto.\n}\n\n(* rec *)\n{\nintros pg s i k K _ IH mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros k' r2 Hk Hr2 <-.\ninvert Hr2.\nintros <-.\nfold (rec k').\napply interp_rec.\napply IH; auto.\napply restriction_funct1; auto.\napply restriction_oper.\napply restriction_cons; auto.\n}\n\n(* univ *)\n{\nintros pg s i lv gpg Hintlv Hstr Hcex mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv' Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (univ lv').\napply interp_univ; eauto using pginterp_restriction.\n}\n\n(* kuniv *)\n{\nintros pg s i lv gpg h Hintlv Hlt mm IHo Hrest.\ninvertc Hrest.\nintros r1 Hr1 <-.\ninvertc Hr1.\nintros lv' r2 Hlv' Hr2 <-.\ninvertc Hr2.\nintros <-.\nfold (kuniv lv').\napply interp_kuniv; eauto using pginterp_restriction.\n}\n\n(* kinterp *)\n{\nintros pg s i k k' K Hcl Hsteps _ IH l IHo Hrest.\nso (restriction_steps _#4 Hrest Hsteps) as (l' & Hrest' & Hsteps').\napply (kinterp_eval _#5 l'); auto.\neapply restriction_hygiene; eauto.\n}\n\n(* cinterp *)\n{\nintros pg s i c c' K Hcl Hsteps _ IH d IHo Hrest.\nso (restriction_steps _#4 Hrest Hsteps) as (d' & Hrest' & Hsteps').\napply (cinterp_eval _#5 d'); auto.\neapply restriction_hygiene; eauto.\n}\n\n(* interp *)\n{\nintros pg s i a a' K Hcl Hsteps _ IH b IHo Hrest.\nso (restriction_steps _#4 Hrest Hsteps) as (b' & Hrest' & Hsteps').\napply (interp_eval _#5 b'); auto.\neapply restriction_hygiene; eauto.\n}\n\n(* functional *)\n{\nintros pg s i A b B Hclo Hcourse _ IH b' IHo Hrest.\napply functional_i; eauto using restriction_hygiene.\nintros j m p Hj Hmp.\napply IH; auto.\napply restriction_subst; auto.\n}\n\n(* wrapup *)\n{\ndestruct Hind as (Hk & Hc & Hy & _).\ndo2 2 split; intros; [eapply Hk | eapply Hc | eapply Hy]; eauto.\n}\nQed.\n\n\nLemma restrict_natinterp :\n  forall w m i,\n    natinterp m i\n    -> natinterp (map_term (restrict w) m) i.\nProof.\nintros w m i Hint.\ninduct Hint.\n\n(* 0 *)\n{\nintros m n p Hclm Hstepsm Hstepsn Hstepsp.\napply (natinterp_0 _ (map_term (restrict w) n) (map_term (restrict w) p)); auto using map_hygiene.\n  {\n  relquest.\n    {\n    apply map_steps; eauto.\n    }\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  relquest.\n    {\n    apply map_steps; eauto.\n    }\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  relquest.\n    {\n    apply map_steps; eauto.\n    }\n  simpmap.\n  reflexivity.\n  }\n}\n\n(* S *)\n{\nintros m n p i Hclm Hstepsm Hstepsn _ IH.\napply (natinterp_S _ (map_term (restrict w) n) (map_term (restrict w) p)); auto using map_hygiene.\n  {\n  relquest.\n    {\n    apply map_steps; eauto.\n    }\n  simpmap.\n  reflexivity.\n  }\n\n  {\n  relquest.\n    {\n    apply map_steps; eauto.\n    }\n  simpmap.\n  reflexivity.\n  }\n}\nQed.\n\n\nLemma restrict_lvinterp :\n  forall w m u,\n    lvinterp m u\n    -> lvinterp (map_term (restrict w) m) u.\nProof.\nintros w m u Hint.\ndestruct Hint as (i & Hi & ->).\nexists i.\nsplit; auto.\neapply restrict_natinterp; eauto.\nQed.\n\n\nLemma restrict_pginterp :\n  forall w m pg,\n    pginterp m pg\n    -> pginterp (map_term (restrict w) m) pg.\nProof.\nintros w m pg Hint.\ndestruct Hint as (i & Hint & Hstr & Hcex & Hcin).\nexists i.\ndo2 3 split; auto.\neapply restrict_lvinterp; eauto.\nQed.\n\n\nLemma restrict_interp_kext :\n  forall w pg i k K,\n    cin pg << w\n    -> interp_kext pg i k K\n    -> interp_kext pg i (map_term (restrict w) k) K.\nProof.\nintros w pg i k K Hcin Hint.\ndestruct Hint as (Q & h & Hcl & Hsteps & Hlev & <-).\nexists Q, h.\ndo2 3 split; auto.\n  {\n  apply map_hygiene; auto.\n  }\n\n  {\n  so (map_steps _ _ (restrict w) _ _ Hsteps) as Hsteps'.\n  force_exact Hsteps'.\n  f_equal.\n  simpmap.\n  f_equal.\n  unfold restrict.\n  rewrite -> objout_objin.\n  f_equal.\n  unfold restrict_xobj.\n  rewrite -> (lt_ord_dec_is _ _ (le_lt_ord_trans _#3 Hlev Hcin)).\n  reflexivity.\n  }\nQed.\n \n\nLemma restrict_interp_uext :\n  forall w pg i a R,\n    cin pg << w\n    -> interp_uext pg i a R\n    -> interp_uext pg i (map_term (restrict w) a) R.\nProof.\nintros w pg i a R Hcin Hint.\ndestruct Hint as (v & Q & h & Hcl & Hsteps & Hv & <-).\nexists v, Q, h.\ndo2 3 split; auto.\n  {\n  apply map_hygiene; auto.\n  }\n\n  {\n  so (map_steps _ _ (restrict w) _ _ Hsteps) as Hsteps'.\n  force_exact Hsteps'.\n  f_equal.\n  simpmap.\n  f_equal.\n  unfold restrict.\n  rewrite -> objout_objin.\n  f_equal.\n  unfold restrict_xobj.\n  cbn.\n  rewrite -> (lt_ord_dec_is _ _ (le_lt_ord_trans _#3 Hv Hcin)).\n  reflexivity.\n  }\nQed.\n \n\nLemma semantics_level_external :\n  (forall pg s i a R w,\n     levind (str pg)\n     -> cex pg << w\n     -> w <<= stop\n     -> kinterp pg s i a R\n     -> kinterp pg s i (restrict_term w a) R)\n  /\\\n  (forall pg s i a R w,\n     levind (str pg)\n     -> cex pg << w\n     -> w <<= stop\n     -> interp pg s i a R\n     -> interp pg s i (restrict_term w a) R).\nProof.\nexploit (semantics_ind the_system\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> kbasicv the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> cbasicv the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> basicv the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> kbasic the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> cbasic the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i m X => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> basic the_system pg s i (map_term (restrict w) m) X)\n           (fun pg s i A b B => forall w, levind (str pg) -> cex pg << w -> w <<= stop -> functional the_system pg s i A (map_term (restrict w) b) B))\n  as Hind;\ntry (intros;\n     simpmap;\n     eauto using map_hygiene, le_lt_ord_trans, restrict_pginterp with semantics;\n     done).\n\n(* krec *)\n{\nintros pg s i k K _ IH w IHo Hwc Hw.\nsimpmap.\napply interp_krec.\nso (IH _ IHo Hwc Hw) as H.\nsimpmapin H.\nexact H.\n}\n\n(* ext *)\n{\nintros pg s i Q h Hcin w _ Hw _.\nsimpmap.\nunfold restrict, restrict_xobj.\nrewrite -> objout_objin.\nrewrite -> (lt_ord_dec_is _ _ (le_lt_ord_trans _#3 (le_ord_trans _#3 Hcin (cin_cex pg)) Hw)).\napply interp_ext; auto.\n}\n\n(* clam *)\n{\nintros pg s i k a K L A h HeqL Hintk _ IH2 w IHo Hwc Hw.\nsimpmap.\napply (interp_clam _#9 h); eauto using map_hygiene.\n  {\n  eapply restrict_interp_kext; eauto.\n  eapply le_lt_ord_trans; eauto using cin_cex.\n  }\nintros j Hj x.\nso (IH2 j Hj x w IHo Hwc Hw) as H.\nsimpmapin H.\ncbn in H.\nrefine (semantics_restriction anderl _#6 IHo _ H); clear H.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\nrewrite <- restrict_ext.\napply restrict_impl_restriction.\n}\n\n(* ctlam *)\n{\nintros pg s i a b k K A f B Hcl Hinta Hintk _ IH Hf w IHo Hwc Hw.\nsimpmap.\nso (le_lt_ord_trans _#3 (cin_cex pg) Hwc) as Hcinw.\napply (interp_ctlam _#9 f); auto using map_hygiene, restrict_interp_kext, restrict_interp_uext.\nintros j m n Hmn.\nso (IH j m n Hmn w IHo Hwc Hw) as H.\nsimpmapin H.\nrefine (semantics_restriction anderl _#6 IHo _ H); clear H.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\napply restrict_impl_restriction.\n}\n\n(* ctapp *)\n{\nintros pg s i b m l A K B n p Hnp Hm Hint IH w IHo Hwc Hw.\nsimpmap.\napply interp_ctapp; auto.\nrewrite <- (restrict_restriction _ (restrict_term w m)) in Hm; auto.\napply (restriction_decrease _ w); auto using restrict_impl_restriction.\nso (cinterp_level_bound _#5 Hint) as Hlev.\ncbn in Hlev.\nexact (le_ord_trans _#3 (le_ord_max_l _ _) (le_ord_trans _#3 Hlev (le_ord_trans _#3 (cin_cex pg) (lt_ord_impl_le_ord _ _ Hwc)))).\n}\n\n(* con *)\n{\nintros pg s i lv a gpg R Hintlv Hle _ IH w IHo Hwc Hw.\nsimpmap.\napply interp_con; auto using restrict_pginterp.\napply IH; auto.\n  {\n  eapply levind_decrease; eauto.\n  apply str_mono; auto.\n  }\n\n  {\n  eapply le_lt_ord_trans; eauto.\n  apply cex_mono; auto.\n  }\n}\n\n(* quotient *)\n{\nintros pg s i a b A B hs ht _ IH1 _ IH2 w IHo Hwc Hw.\nsimpmap.\napply interp_quotient; auto.\nso (IH2 _ IHo Hwc Hw) as H.\nsimpmapin H.\nexact H.\n}\n\n(* guard *)\n{\nintros pg s i a b A B _ IH1 _ IH2 w IHo Hwc Hw.\nsimpmap.\napply interp_guard; auto.\nso (IH2 _ IHo Hwc Hw) as H.\nsimpmapin H.\nexact H.\n}\n\n(* equal *)\n{\nintros pg s i a m n p q A Hmp Hnq Hint IH w IHo Hwc Hstop.\nsimpmap.\nso (le_ord_trans _#3 (cin_top pg) (succ_nodecrease _)) as h.\nso (semantics_level_internal _#5 h IHo Hint) as (A' & ->).\nassert (srel s (den (extend_iurel h A')) i (restrict_term w m) p) as Hmp'.\n  {\n  rewrite -> den_extend_iurel.\n  rewrite -> extend_srel.\n  rewrite -> restrict_extend.\n  rewrite -> (extend_term_compose_up w stop (cin pg)); auto.\n  rewrite -> extend_term_compose_down; auto.\n  eauto using cin_cex, le_ord_trans, lt_ord_impl_le_ord.\n  }\nassert (srel s (den (extend_iurel h A')) i (restrict_term w n) q) as Hnq'.\n  {\n  rewrite -> den_extend_iurel.\n  rewrite -> extend_srel.\n  rewrite -> restrict_extend.\n  rewrite -> (extend_term_compose_up w stop (cin pg)); auto.\n  rewrite -> extend_term_compose_down; auto.\n  eauto using cin_cex, le_ord_trans, lt_ord_impl_le_ord.\n  }\ncbn.\nmatch goal with\n| |- basicv _ _ _ _ _ ?X =>\nreplace X\n  with  (iuequal stop s i (extend_iurel h A') (restrict_term w m) (restrict_term w n) p q Hmp' Hnq')\nend.\n2:{\n  apply iuequal_equal; auto.\n  }\napply interp_equal.\napply IH; auto.\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A h Hintlv Hintk IH1 Hle _ IH2 w IHo Hwc Hw.\nsimpmap.\napply (interp_all _#7 gpg _ _ h); eauto using map_hygiene, restrict_pginterp.\n  {\n  apply IH1; auto.\n    {\n    eapply levind_decrease; eauto.\n    apply str_mono; auto.\n    }\n  \n    {\n    eapply le_lt_ord_trans; eauto.\n    apply cex_mono; auto.\n    }\n  }\nintros j Hj x.\nso (IH2 j Hj x w IHo Hwc Hw) as H.\nsimpmapin H.\nrefine (semantics_restriction anderr _#6 IHo _ H); clear H.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\nrewrite <- restrict_ext.\napply restriction_oper.\napply restriction_cons.\n  {\n  fold (restrict_term w (fromsp stop gpg (approx j K))).\n  rewrite -> restrict_extend.\n  so (kinterp_level_bound _#5 Hintk) as HlevK.\n  assert (level (approx j K) << w) as HlevKw.\n    {\n    eapply le_lt_ord_trans.\n      {\n      apply approx_level.\n      }\n    eapply le_lt_ord_trans; eauto.\n    eapply le_lt_ord_trans.\n      {\n      exact (cin_mono _ _ Hle).\n      }\n    eapply le_lt_ord_trans; eauto.\n    apply cin_cex.\n    }\n  so (lt_le_ord_trans _#3 HlevKw Hw) as HlevKstop.\n  rewrite -> !extend_fromsp; auto.\n  apply restriction_refl.\n  }\napply restriction_cons; [| apply restriction_nil].\napply restrict_impl_restriction.\n}\n\n(* alltp *)\n{\nintros pg s i a A _ IH w IHo Hwc Hw.\nsimpmap.\napply interp_alltp.\nintros j Hj X.\nso (IH j Hj X w IHo Hwc Hw) as H.\nsimpmapin H.\nrefine (semantics_restriction anderr _#6 IHo _ H); clear H.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\nrewrite <- restrict_extt.\napply restrict_impl_restriction.\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A h Hintlv Hintk IH1 Hle _ IH2 w IHo Hwc Hw.\nsimpmap.\napply (interp_exist _#7 gpg _ _ h); eauto using map_hygiene, restrict_pginterp.\n  {\n  apply IH1; auto.\n    {\n    eapply levind_decrease; eauto.\n    apply str_mono; auto.\n    }\n  \n    {\n    eapply le_lt_ord_trans; eauto.\n    apply cex_mono; auto.\n    }\n  }\nintros j Hj x.\nso (IH2 j Hj x w IHo Hwc Hw) as H.\nsimpmapin H.\nrefine (semantics_restriction anderr _#6 IHo _ H); clear H.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\nrewrite <- restrict_ext.\napply restriction_oper.\napply restriction_cons.\n  {\n  fold (restrict_term w (fromsp stop gpg (approx j K))).\n  rewrite -> restrict_extend.\n  so (kinterp_level_bound _#5 Hintk) as HlevK.\n  assert (level (approx j K) << w) as HlevKw.\n    {\n    eapply le_lt_ord_trans.\n      {\n      apply approx_level.\n      }\n    eapply le_lt_ord_trans; eauto.\n    eapply le_lt_ord_trans.\n      {\n      exact (cin_mono _ _ Hle).\n      }\n    eapply le_lt_ord_trans; eauto.\n    apply cin_cex.\n    }\n  so (lt_le_ord_trans _#3 HlevKw Hw) as HlevKstop.\n  rewrite -> !extend_fromsp; auto.\n  apply restriction_refl.\n  }\napply restriction_cons; [| apply restriction_nil].\napply restrict_impl_restriction.\n}\n\n(* extt *)\n{\nintros pg s i w' R h Hw' w IHo Hwc Hw.\nsimpmap.\nunfold restrict.\nrewrite -> objout_objin.\ncbn.\nrewrite -> (lt_ord_dec_is _ _ (le_lt_ord_trans _#3 (le_ord_trans _#3 Hw' (cin_cex pg)) Hwc)).\napply interp_extt; auto.\n}\n\n(* mu *)\n{\nintros pg v s i a F Hv _ IH Hne Hmono Hrobust w IHo Hwc Hw.\nsimpmap.\napply interp_mu; auto.\n  {\n  intros X hv.\n  so (IH X hv w IHo Hwc Hw) as H.\n  simpmapin H.\n  force_exact H; clear H.\n  do 3 f_equal.\n  unfold restrict.\n  rewrite -> objout_objin.\n  cbn.\n  rewrite -> (lt_ord_dec_is _ _ (le_lt_ord_trans _#3 (le_ord_trans _#3 Hv (cin_cex pg)) Hwc)).\n  reflexivity.\n  }\n\n  {\n  eapply map_robust; eauto.\n  }\n}\n\n(* ispositive *)\n{\nintros pg s i a Hcl w _ Hwc Hw.\nsimpmap.\nreplace (ispositive_urel stop i a) with (ispositive_urel stop i (map_term (restrict w) a)).\n2:{\n  apply property_urel_extensionality; auto.\n  intros _ _.\n  split; intro H; [eapply map_positive_conv | apply map_positive]; eauto.\n  }\napply interp_ispositive.\napply map_hygiene; auto.\n}\n\n(* isnegative *)\n{\nintros pg s i a Hcl w _ Hwc Hw.\nsimpmap.\nreplace (isnegative_urel stop i a) with (isnegative_urel stop i (map_term (restrict w) a)).\n2:{\n  apply property_urel_extensionality; auto.\n  intros _ _.\n  split; intro H; [eapply map_negative_conv | apply map_negative]; eauto.\n  }\napply interp_isnegative.\napply map_hygiene; auto.\n}\n\n(* rec *)\n{\nintros pg s i k K _ IH w IHo Hwc Hw.\nsimpmap.\napply interp_rec.\nso (IH _ IHo Hwc Hw) as H.\nsimpmapin H.\nexact H.\n}\n\n(* kinterp *)\n{\nintros pg s i k k' K Hcl Hsteps _ IH w IHo Hwc Hw.\napply (kinterp_eval _#5 (map_term (restrict w) k')); auto using map_hygiene, map_steps.\n}\n\n(* cinterp *)\n{\nintros pg s i c c' Q Hcl Hsteps _ IH w IHo Hwc Hw.\napply (cinterp_eval _#5 (map_term (restrict w) c')); auto using map_hygiene, map_steps.\n}\n\n(* interp *)\n{\nintros pg s i a a' R Hcl Hsteps _ IH w IHo Hwc Hw.\napply (interp_eval _#5 (map_term (restrict w) a')); auto using map_hygiene, map_steps.\n}\n\n(* functional *)\n{\nintros pg s i A b B Hcl Hcoarse _ IH w IHo Hwc Hw.\napply functional_i; auto using map_hygiene.\nintros j m p Hj Hmp.\nso (IH j m p Hj Hmp w IHo Hwc Hw) as H.\nrefine (semantics_restriction anderr _#6 IHo _ H); clear H.\nsimpmap.\napply restriction_funct1; auto using restriction_refl.\napply (restriction_decrease _ w); auto using lt_ord_impl_le_ord.\napply restrict_impl_restriction.\n}\n\n(* wrapup *)\n{\ndestruct Hind as (Hk & _ & Hy & _).\nsplit; intros; [apply Hk | apply Hy]; auto.\n}\nQed.\n\n\nLemma semantics_levind :\n  forall w, levind w.\nProof.\nintros w.\nwfinduct w using lt_ord_wf.\nintros w IH.\ndo2 3 split.\n  {\n  intros pg s i a a' R Hwn Hwc Hrest Hint.\n  eapply semantics_restriction; eauto.\n  }\n\n  {\n  intros pg s i a a' R Hwn Hwc Hrest Hint.\n  eapply semantics_restriction; eauto.\n  }\n\n  {\n  intros pg s i a R v Hwn Hwc Hv Hint.\n  eapply semantics_level_external; eauto.\n  }\n\n  {\n  intros pg s i a R v Hwn Hwc Hv Hint.\n  eapply semantics_level_external; eauto.\n  }\nQed.\n\n\nLemma interp_level_internal :\n  forall pg s i a R (h : cin pg <<= stop),\n    interp pg s i a R\n    -> exists R', R = extend_iurel h R'.\nProof.\nintros pg s i a R h Hint.\neapply semantics_level_internal; eauto using semantics_levind.\nQed.\n\n\nLemma interp_level_external :\n  forall pg s i a R,\n   interp pg s i a R\n    -> interp pg s i (restrict_term (succ (cex pg)) a) R.\nProof.\nintros pg s i a R Hint.\neapply semantics_level_external; eauto using semantics_levind, succ_increase.\napply le_ord_succ.\napply cex_top.\nQed.\n\n\nLemma interp_level_restricted :\n  forall pg s i a R,\n    interp pg s i (restrict_term (succ (cex pg)) a) R\n    -> interp pg s i a R.\nProof.\nintros pg s i a R Hint.\nset (wc := cex pg).\nso (restriction_decrease _#4 (succ_nodecrease wc) (restrict_impl_restriction (succ wc) a)) as Hrest.\neapply semantics_restriction; eauto using semantics_levind.\nQed.\n\n\nLemma interp_level_external_iff :\n  forall pg s i a R,\n    interp pg s i a R\n    <->\n    interp pg s i (restrict_term (succ (cex pg)) a) R.\nProof.\nintros pg s i a R.\nsplit; eauto using interp_level_external, interp_level_restricted.\nQed.\n\n\nLemma interp_restriction :\n  forall pg s i a a' R,\n    restriction (cex pg) a a'\n    -> interp pg s i a R\n    -> interp pg s i a' R.\nProof.\nintros pg s i a a' R Hrest Hint.\neapply semantics_restriction; eauto using semantics_levind.\nQed.\n\n\nRequire Import ProperFun.\n\n\nLemma interp_fun :\n  forall pg pg' s i a R R',\n    interp pg s i a R\n    -> interp pg' s i a R'\n    -> R = R'.\nProof.\nintros pg1 pg2 s i a R R' H1 H2.\nso (interp_increase _#6 (le_page_max_l pg1 pg2) H1) as H1'.\nso (interp_increase _#6 (le_page_max_r pg1 pg2) H2) as H2'.\nexact (basic_fun _#7 H1' H2').\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/ProperLevel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.17707574231393083}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Template Require Import config utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICInduction\n     PCUICLiftSubst PCUICTyping PCUICGlobalEnv\n     PCUICWeakeningEnvTyp PCUICSubstitution PCUICEquality\n     PCUICReduction PCUICCumulativity PCUICConfluence PCUICClosed PCUICClosedTyp\n     PCUICContextConversion PCUICContextConversionTyp PCUICConversion PCUICInversion PCUICUnivSubst\n     PCUICArities PCUICValidity PCUICInductives PCUICInductiveInversion\n     PCUICSR PCUICCumulProp PCUICWfUniverses\n     PCUICOnFreeVars PCUICWellScopedCumulativity.\n\nRequire Import ssreflect ssrbool.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\n(** We show that principal types are derivable, without relying on normalization.\n  The principal type is burried in the proof here, but [PCUICSafeRetyping.type_of]\n  gives an explicit computation, but its definition and correctness proof requires\n  completeness of weak-head-reduction. *)\n\nSection Principality.\n  Context {cf : checker_flags}.\n  Context (\u03a3 : global_env_ext).\n  Context (wf\u03a3 : wf_ext \u03a3).\n\n  Ltac pih :=\n    lazymatch goal with\n    | ih : forall _ _ _, _ -> _ ;;; _ |- ?u : _ -> _,\n    h1 : _ ;;; _ |- ?u : _,\n    h2 : _ ;;; _ |- ?u : _\n    |- _ =>\n  specialize (ih _ _ _ h1 h2)\n  end.\n\n  Ltac insum :=\n    match goal with\n    | |- \u2211 x : _, _ =>\n      eexists\n    end.\n\n  Ltac intimes :=\n    match goal with\n    | |- _ \u00d7 _ =>\n      split\n    end.\n\n  Ltac outsum :=\n    match goal with\n    | ih : \u2211 x : _, _ |- _ =>\n      destruct ih as [? ?]\n    end.\n\n  Ltac outtimes :=\n    match goal with\n    | ih : _ \u00d7 _ |- _ =>\n      destruct ih as [? ?]\n    end.\n\n  Lemma isWfArity_sort \u0393 u :\n    wf_local \u03a3 \u0393 ->\n    wf_universe \u03a3 u ->\n    isWfArity \u03a3 \u0393 (tSort u).\n  Proof using Type.\n    move=> wf\u0393 wfu.\n    split. eapply isType_Sort; eauto. exists [], u. intuition auto.\n  Qed.\n  Hint Extern 10 (isWfArity _ _ (tSort _)) => apply isWfArity_sort : pcuic.\n\n  Ltac int inv := intros B hB; eapply inv in hB; auto; split; [|econstructor; eauto].\n  Hint Resolve wf_ext_wf : core.\n\n  Theorem principal_type {\u0393 u A} : \u03a3 ;;; \u0393 |- u : A ->\n    \u2211 C, (forall B, \u03a3 ;;; \u0393 |- u : B -> \u03a3 ;;; \u0393 \u22a2 C \u2264 B \u00d7 \u03a3 ;;; \u0393 |- u : C).\n  Proof using wf\u03a3.\n    intros hA.\n    induction u in \u0393, A, hA |- * using term_forall_list_ind.\n    - apply inversion_Rel in hA as iA. 2: auto.\n      destruct iA as [decl [? [e ?]]].\n      eexists; int inversion_Rel.\n      destruct hB as [decl' [? [e' ?]]].\n      rewrite e' in e. noconf e.\n      all: try eassumption.\n    - apply inversion_Var in hA. destruct hA.\n    - apply inversion_Evar in hA. destruct hA.\n    - apply inversion_Sort in hA as iA. 2: auto.\n      repeat outsum. repeat outtimes. subst.\n      exists (tSort (Universe.super s)).\n      int inversion_Sort.\n      repeat outsum. repeat outtimes. now subst.\n    - apply inversion_Prod in hA as [dom1 [codom1 iA]]; auto.\n      repeat outtimes.\n      specialize (IHu1 _ _ t) as [dom Hdom].\n      specialize (IHu2 _ _ t0) as [codom Hcodom].\n      destruct (Hdom _ t) as [e e'].\n      eapply ws_cumul_pb_Sort_r_inv in e as [domu [red leq]].\n      destruct (Hcodom _ t0) as [e e''].\n      eapply ws_cumul_pb_Sort_r_inv in e as [codomu [cored coleq]].\n      exists (tSort (Universe.sort_of_product domu codomu)).\n      int inversion_Prod.\n      repeat outsum; repeat outtimes.\n      + etransitivity. 1: auto. 2:eapply w0.\n        destruct (Hdom _ t1) as [le' u1'].\n        eapply ws_cumul_pb_Sort_r_inv in le' as [u' [redu' leu']].\n        destruct (Hcodom _ t2) as [le'' u2'].\n        eapply ws_cumul_pb_Sort_r_inv in le'' as [u'' [redu'' leu'']].\n        constructor => //. fvs. constructor.\n        apply leq_universe_product_mon; auto.\n        pose proof (closed_red_confluence red redu') as [v' [redl redr]].\n        eapply invert_red_sort in redl.\n        eapply invert_red_sort in redr. subst. now noconf redr.\n        pose proof (closed_red_confluence cored redu'') as [v' [redl redr]].\n        eapply invert_red_sort in redl.\n        eapply invert_red_sort in redr. subst. now noconf redr.\n      + eapply type_reduction; eauto. eapply red.\n      + eapply type_reduction; eauto. eapply cored.\n\n    - apply inversion_Lambda in hA => //; eauto.\n      repeat outsum. repeat outtimes.\n      destruct (IHu1 _ _ t) as [? ?].\n      destruct (IHu2 _ _ t0) as [? ?].\n      destruct (p _ t).\n      destruct (p0 _ t0).\n      exists (tProd n u1 x2).\n      int inversion_Lambda.\n      repeat outsum. repeat outtimes.\n      etransitivity; eauto.\n      apply ws_cumul_pb_Prod_l_inv in w2 as [na' [A' [B' [redA u1eq ?]]]] => //; auto.\n      destruct (p0 _ t4).\n      eapply ws_cumul_pb_Prod => //; auto.\n      transitivity A' => //. now symmetry.\n\n    - eapply inversion_LetIn in hA as (s1 & bty & Hu2 & Hu1 & Hu3 & Hcum); auto.\n      destruct (IHu1 _ _ Hu1) as [? p].\n      destruct (p _ Hu1).\n      destruct (IHu2 _ _ Hu2) as [? p'].\n      destruct (p' _ Hu2).\n      destruct (IHu3 _ _ Hu3) as [? p''].\n      destruct (p'' _ Hu3).\n      exists (tLetIn n u1 u2 x1).\n      int inversion_LetIn.\n      destruct hB as (s1' & bty' & Hu2' & Hu1' & Hu3' & Hcum'); eauto.\n      etransitivity; eauto.\n      eapply ws_cumul_pb_LetIn; eauto using wt_cumul_pb_refl.\n      now specialize (p'' _ Hu3') as [? ?].\n\n    - eapply inversion_App in hA as [na [dom [codom [tydom [tyarg tycodom]]]]] => //; auto.\n      destruct (IHu2 _ _ tyarg).\n      destruct (IHu1 _ _ tydom).\n      destruct (p _ tyarg). destruct (p0 _ tydom).\n      apply ws_cumul_pb_Prod_r_inv in w0 as [? [A' [B' [redA eqann u1eq ?]]]] => //; auto.\n      exists (subst [u2] 0 B').\n      intros ? hB.\n      eapply inversion_App in hB as [na' [dom' [codom' [tydom' [tyarg' tycodom']]]]] => //; auto.\n      destruct (p0 _ tydom').\n      destruct (p _ tyarg').\n      apply ws_cumul_pb_Prod_r_inv in w1 as [? [A'' [B'' [redA' eqann' u1eq' ?]]]] => //; auto.\n      destruct (closed_red_confluence redA redA') as [nfprod [redl redr]].\n      eapply invert_red_prod in redl as [? [? [? ? ?]]] => //. subst.\n      eapply invert_red_prod in redr as [? [? [? ? ?]]] => //. noconf e.\n      all:auto.\n      assert(\u03a3 ;;; \u0393 \u22a2 A' = A'').\n      { transitivity x3 => //; eauto using red_ws_cumul_pb.\n        symmetry. now apply red_ws_cumul_pb. }\n      assert(\u03a3 ;;; \u0393 ,, vass x1 A' \u22a2 B' = B'').\n      { transitivity x4 => //.\n        - now eapply red_ws_cumul_pb.\n        - symmetry. eapply (ws_cumul_pb_ws_cumul_ctx (pb:=Conv)); tea.\n          2:eapply red_ws_cumul_pb; tea.\n          constructor; auto. eapply ws_cumul_ctx_pb_refl. fvs.\n          constructor. reflexivity. now symmetry. }\n      split.\n      etransitivity; eauto.\n      eapply (substitution0_ws_cumul_pb (na:=na') (T:=dom')) => //.\n      have convctx : \u03a3 \u22a2 \u0393 ,, vass na' dom' = \u0393 ,, vass x1 A'.\n      { constructor. apply ws_cumul_ctx_pb_refl. fvs. constructor => //. transitivity A'' => //.\n        now symmetry. now symmetry. }\n      transitivity B'' => //. eapply (ws_cumul_pb_ws_cumul_ctx (pb':=Conv)); tea.\n      now apply ws_cumul_pb_eq_le.\n      eapply type_App'. tea.\n      eapply type_reduction; eauto. eapply redA.\n      eapply (type_ws_cumul_pb (pb:=Cumul)); eauto.\n      { eapply validity in t0; auto.\n        eapply isType_red in t0; [|exact redA].\n        eapply isType_tProd in t0 as [? ?]; eauto. }\n      transitivity dom' => //. transitivity A''.\n      all:apply ws_cumul_pb_eq_le; symmetry => //.\n\n    - eapply inversion_Const in hA as [decl ?] => //; auto.\n      repeat outtimes.\n      eexists; int inversion_Const.\n      destruct hB as [decl' [wf [declc' [cu cum]]]].\n      now rewrite -(declared_constant_inj _ _ d declc') in cum.\n\n    - eapply inversion_Ind in hA as [mdecl [idecl [? [Hdecl ?]]]] => //; auto.\n      repeat outtimes.\n      exists (subst_instance u (ind_type idecl)).\n      int inversion_Ind. destruct hB as [mdecl' [idecl' [? [Hdecl' ?]]]] => //.\n      red in Hdecl, Hdecl'. destruct Hdecl as [? ?].\n      destruct Hdecl' as [? ?]. red in H, H1.\n      rewrite H1 in H; noconf H.\n      rewrite H2 in H0; noconf H0.\n      repeat intimes; eauto. now destruct p.\n\n    - eapply inversion_Construct in hA as [mdecl [idecl [? [? [Hdecl ?]]]]] => //; auto.\n      repeat outtimes.\n      exists (type_of_constructor mdecl x (i, n) u).\n      int inversion_Construct. destruct hB as [mdecl' [idecl' [? [? [Hdecl' [? ?]]]]]] => //.\n      red in Hdecl, Hdecl'.\n      destruct Hdecl as [[? ?] ?].\n      destruct Hdecl' as [[? ?] ?].\n      red in H, H2. rewrite H2 in H. noconf H.\n      rewrite H3 in H0. noconf H0.\n      rewrite H4 in H1. now noconf H1.\n\n    - assert (wf \u03a3) by auto.\n      eapply inversion_Case in hA as (mdecl&idecl&isdecl&indices&[]&?); auto.\n      destruct (IHu _ _ scrut_ty) as [? p0].\n      destruct (p0 _ scrut_ty).\n      eapply ws_cumul_pb_Ind_r_inv in w0 as [u' [x0' [redr redu ?]]]; auto.\n      exists (mkApps ptm (indices ++ [u])); intros b hB; repeat split; auto.\n      2:econstructor; eauto.\n      eapply inversion_Case in hB as (mdecl'&idecl'&isdecl'&indices'&[]&?); tea. clear brs_ty0.\n      destruct (declared_inductive_inj isdecl isdecl') as [-> ->].\n      destruct (p0 _ scrut_ty0).\n      eapply ws_cumul_pb_Ind_r_inv in w1 as [u'' [x9' [redr' redu' ?]]]; auto.\n      assert (ws_cumul_pb_terms \u03a3 \u0393 x0' x9').\n      { destruct (closed_red_confluence redr redr') as [nf [r r0]].\n        eapply invert_red_mkApps_tInd in r as [args' [? ?]]; auto.\n        eapply invert_red_mkApps_tInd in r0 as [args'' [? ?]]; auto.\n        subst. solve_discr.\n        clear -wf\u03a3 i a a0 a1 a2.\n        transitivity args'; auto using red_terms_ws_cumul_pb_terms.\n        now symmetry; apply red_terms_ws_cumul_pb_terms. }\n      clear redr redr'.\n      etransitivity; [|tea].\n      eapply ws_cumul_pb_mkApps; auto. rewrite /ptm /predctx.\n      * eapply PCUICGeneration.type_it_mkLambda_or_LetIn in pret_ty.\n        eapply ws_cumul_pb_eq_le, wt_cumul_pb_refl. eapply pret_ty.\n      * eapply All2_app. 2:constructor; auto.\n        assert (ws_cumul_pb_terms \u03a3 \u0393 (pparams p ++ indices) (pparams p ++ indices')).\n        { transitivity x9'; tea. transitivity x0' => //. now symmetry. }\n        eapply All2_app_inv in X3 as [] => //.\n        eapply wt_cumul_pb_refl; tea.\n      * split; eauto.\n      * split; eauto.\n\n    - destruct s as [ind k pars]; simpl in *.\n      eapply inversion_Proj in hA=>//; auto.\n      repeat outsum. repeat outtimes.\n      simpl in *.\n      specialize (IHu _ _ t) as [C HP].\n      destruct (HP _ t).\n      eapply ws_cumul_pb_Ind_r_inv in w0 as [u' [x0' [redr redu ?]]]; auto.\n      exists (subst0 (u :: List.rev x0') (subst_instance u' (proj_type x3))).\n      intros B hB.\n      eapply inversion_Proj in hB=>//; auto.\n      repeat outsum. repeat outtimes.\n      simpl in *.\n      destruct (declared_projection_inj d d0) as [-> [-> [-> ?]]]. subst x9.\n      destruct (HP _ t1).\n      eapply ws_cumul_pb_Ind_r_inv in w1 as [u'' [x0'' [redr' redu' ?]]]; auto.\n      split; cycle 1.\n      eapply type_reduction in t0. 2:exact redr.\n      eapply (type_Proj _ _ _ _ _ _ _ _ _ _ d0); simpl; auto.\n      now rewrite (All2_length a).\n      destruct (closed_red_confluence redr redr') as [nf [redl redr'']].\n      eapply invert_red_mkApps_tInd in redl as [? [-> conv]]; auto.\n      eapply invert_red_mkApps_tInd in redr'' as [? [[=] conv']]; auto.\n      solve_discr.\n      etransitivity; eauto.\n      assert (consistent_instance_ext \u03a3 (ind_universes x6) u').\n      { eapply type_reduction in t2. 2:eapply redr.\n        eapply validity in t2; eauto.\n        destruct t2 as [s Hs].\n        eapply invert_type_mkApps_ind in Hs. intuition eauto. all:auto. eapply d. }\n      assert (consistent_instance_ext \u03a3 (ind_universes x6) x5).\n        { eapply validity in t1; eauto.\n          destruct t1 as [s Hs].\n          eapply invert_type_mkApps_ind in Hs. intuition eauto. all:auto. eapply d. }\n      set (p := {| proj_ind := ind; proj_npars := k; proj_arg := pars |}).\n      transitivity (subst0 (u :: List.rev x0') (subst_instance x5 (proj_type x3))); cycle 1.\n      eapply ws_cumul_pb_eq_le.\n      assert (ws_cumul_pb_terms \u03a3 \u0393 x0' x10).\n      { transitivity x0'' => //.\n        transitivity x0. auto using red_terms_ws_cumul_pb_terms.\n        symmetry. auto using red_terms_ws_cumul_pb_terms. }\n      eapply (substitution_ws_cumul_pb_subst_conv (\u03930 := projection_context ind x6 x7 u')\n      (\u03931 := projection_context ind x6 x7 x5) (\u0394 := [])); auto.\n      * eapply (projection_subslet _ _ _ _ _ _ p); eauto.\n        simpl. eapply type_reduction; eauto. eapply redr. simpl.\n        eapply type_reduction in t0. 2:eapply redr. eapply validity; eauto.\n      * split.\n        { eapply PCUICWeakeningTyp.weaken_wf_local; tea. pcuic. pcuic.\n          eapply (wf_projection_context _ (p:=p)); tea. pcuic. }\n        eapply (projection_subslet _ _ _ _ _ _ p); eauto.\n        simpl. eapply validity; eauto.\n      * constructor; auto. now eapply wt_cumul_pb_refl. now apply All2_rev.\n      * eapply ws_cumul_pb_refl.\n        { eapply wf_local_closed_context. cbn -[projection_context].\n          eapply PCUICWeakeningTyp.weaken_wf_local; pcuic.\n          eapply (wf_projection_context _ (p:=p)); pcuic. }\n        eapply declared_projection_closed in d0; eauto.\n        cbn in d0. len. rewrite (declared_minductive_ind_npars d) in d0.\n        len. rewrite on_free_vars_subst_instance.\n        rewrite closedn_on_free_vars //.\n        eapply closed_upwards; tea. lia.\n      * eapply (substitution_ws_cumul_pb (\u0393:=\u0393) (\u0393' := projection_context ind x6 x7 u') (\u0393'' := [])); auto.\n        eapply (projection_subslet _ _ _ _ _ _ p); eauto.\n        simpl. eapply type_reduction; eauto. eapply redr. simpl.\n        eapply type_reduction in t0. 2:eapply redr.\n        eapply validity; eauto. simpl in redu'.\n        rewrite e0 in redu'.\n        unshelve epose proof (projection_cumulative_indices d _ H H0 redu').\n        { eapply (PCUICWeakeningEnv.weaken_lookup_on_global_env' _ _ _ (wf\u03a3 : wf _) (proj1 (proj1 (proj1 d)))). }\n        eapply on_declared_projection in d0; eauto.\n        eapply weaken_ws_cumul_pb in X; eauto.\n\n    - pose proof (typing_wf_local hA).\n      apply inversion_Fix in hA as [decl [hguard [nthe [wf\u0393 [? [? ?]]]]]]=>//; auto.\n      exists (dtype decl).\n      intros B hB.\n      eapply inversion_Fix in hB as [decl' [hguard' [nthe' [wf\u0393' [? [? ?]]]]]]=>//; auto.\n      rewrite nthe' in nthe; noconf nthe.\n      repeat split; eauto.\n      eapply type_Fix; eauto.\n\n    - pose proof (typing_wf_local hA).\n      apply inversion_CoFix in hA as [decl [hguard [nthe [wf\u0393 [? [? ?]]]]]]=>//; auto.\n      exists (dtype decl).\n      intros B hB.\n      eapply inversion_CoFix in hB as [decl' [hguard' [nthe' [wf\u0393' [? [? ?]]]]]]=>//; auto.\n      rewrite nthe' in nthe; noconf nthe.\n      repeat split; eauto.\n      eapply type_CoFix; eauto.\n    - apply inversion_Prim in hA as [prim_ty [cdecl []]] => //; pcuic.\n      exists (tConst prim_ty []).\n      intros B hB.\n      apply inversion_Prim in hB as [prim_ty' [cdecl' []]] => //; pcuic.\n      econstructor; tea.\n  Qed.\n\n  (** A weaker version that is often convenient to use. *)\n  Lemma common_typing {\u0393 u A B} : \u03a3 ;;; \u0393 |- u : A -> \u03a3 ;;; \u0393 |- u : B ->\n    \u2211 C, \u03a3 ;;; \u0393 \u22a2 C \u2264 A \u00d7 \u03a3 ;;; \u0393 \u22a2 C \u2264 B \u00d7 \u03a3 ;;; \u0393 |- u : C.\n  Proof using wf\u03a3.\n    intros hA hB.\n    destruct (principal_type hA) as [P HP]; eauto.\n    exists P; split; eauto.\n    eapply HP; eauto.\n  Qed.\n\nEnd Principality.\n\nLemma principal_type_ind {cf:checker_flags} {\u03a3 \u0393 c ind u u' args args'} {wf\u03a3: wf_ext \u03a3} :\n  \u03a3 ;;; \u0393 |- c : mkApps (tInd ind u) args ->\n  \u03a3 ;;; \u0393 |- c : mkApps (tInd ind u') args' ->\n  (\u2211 ui',\n    PCUICEquality.R_global_instance \u03a3.1 (eq_universe (global_ext_constraints \u03a3))\n     (leq_universe (global_ext_constraints \u03a3)) (IndRef ind) #|args| ui' u *\n    PCUICEquality.R_global_instance \u03a3.1 (eq_universe (global_ext_constraints \u03a3))\n     (leq_universe (global_ext_constraints \u03a3)) (IndRef ind) #|args'| ui' u') *\n  ws_cumul_pb_terms \u03a3 \u0393 args args'.\nProof.\n  intros h h'.\n  destruct (common_typing _ wf\u03a3 h h') as [C [l [r ty]]].\n  eapply ws_cumul_pb_Ind_r_inv in l as [ui' [l' [red Ru eqargs]]]; auto.\n  eapply ws_cumul_pb_Ind_r_inv in r as [ui'' [l'' [red' Ru' eqargs']]]; auto.\n  destruct (closed_red_confluence red red') as [nf [redl redr]].\n  eapply invert_red_mkApps_tInd in redl as [args'' [-> eq0]]; auto.\n  eapply invert_red_mkApps_tInd in redr as [args''' [eqnf eq1]]; auto.\n  solve_discr.\n  split.\n  assert (#|args| = #|args'|).\n  now rewrite -(All2_length eqargs) -(All2_length eqargs') (All2_length a) (All2_length a0).\n  exists ui'. split; auto.\n\n  transitivity l'. now symmetry.\n  transitivity args'' => //. now apply red_terms_ws_cumul_pb_terms.\n  transitivity l''. symmetry. auto using red_terms_ws_cumul_pb_terms.\n  now symmetry.\nQed.\n\nLemma eq_term_leq_term {cf:checker_flags} {\u03a3 : global_env_ext} {x y} :\n  eq_term \u03a3 \u03a3 x y ->\n  leq_term \u03a3 \u03a3 x y.\nProof.\n  eapply eq_term_upto_univ_impl; auto; typeclasses eauto.\nQed.\n\nLemma eq_term_empty_leq_term {cf:checker_flags} {\u03a3 : global_env_ext} {x y} :\n  eq_term empty_global_env \u03a3 x y ->\n  leq_term empty_global_env \u03a3 x y.\nProof.\n  eapply eq_term_upto_univ_impl; auto; typeclasses eauto.\nQed.\n\nLemma eq_term_empty_eq_term {cf:checker_flags} {\u03a3 : global_env_ext} {x y} :\n  eq_term empty_global_env \u03a3 x y ->\n  eq_term \u03a3 \u03a3 x y.\nProof.\n  eapply eq_term_upto_univ_empty_impl; auto; typeclasses eauto.\nQed.\n\nLemma leq_term_empty_leq_term {cf:checker_flags} {\u03a3 : global_env_ext} {x y} :\n  leq_term empty_global_env \u03a3 x y ->\n  leq_term \u03a3 \u03a3 x y.\nProof.\n  eapply eq_term_upto_univ_empty_impl; auto; typeclasses eauto.\nQed.\n\nLemma eq_context_empty_eq_context {cf:checker_flags} {\u03a3 : global_env_ext} {x y} :\n  eq_context_upto empty_global_env (eq_universe \u03a3) (eq_universe \u03a3) x y ->\n  eq_context_upto \u03a3 (eq_universe \u03a3) (eq_universe \u03a3) x y.\nProof.\n  intros.\n  eapply All2_fold_impl; tea.\n  intros ???? []; constructor; eauto using eq_term_empty_eq_term.\n  all:now apply eq_term_empty_eq_term.\nQed.\n\nNotation eq_term_napp \u03a3 n x y :=\n  (eq_term_upto_univ_napp \u03a3 (eq_universe \u03a3) (eq_universe \u03a3) n x y).\n\nNotation leq_term_napp \u03a3 n x y :=\n    (eq_term_upto_univ_napp \u03a3 (eq_universe \u03a3) (leq_universe \u03a3) n x y).\n\nLemma eq_term_upto_univ_napp_leq {cf:checker_flags} {\u03a3 : global_env_ext} {n x y} :\n  eq_term_napp \u03a3 n x y ->\n  leq_term_napp \u03a3 n x y.\nProof.\n  eapply eq_term_upto_univ_impl; auto; typeclasses eauto.\nQed.\n\nLemma R_global_instance_empty_universe_instance Re Rle ref napp u u' :\n  R_global_instance empty_global_env Re Rle ref napp u u' ->\n  R_universe_instance Re u u'.\nProof.\n  rewrite /R_global_instance_gen.\n  now rewrite global_variance_empty.\nQed.\n\nLemma eq_context_upto_inst_case_context {cf : checker_flags} {\u03a3 : global_env_ext} pars pars' puinst puinst' ctx :\n  All2 (eq_term_upto_univ empty_global_env (eq_universe \u03a3) (eq_universe \u03a3)) pars pars' ->\n  R_universe_instance (eq_universe \u03a3) puinst puinst' ->\n  eq_context_upto \u03a3.1 (eq_universe \u03a3) (eq_universe \u03a3) (inst_case_context pars puinst ctx)\n    (inst_case_context pars' puinst' ctx).\nProof.\n  intros onps oninst.\n  rewrite /inst_case_context.\n  eapply eq_context_upto_subst_context. tc.\n  eapply eq_context_upto_univ_subst_instance; tc; auto.\n  eapply All2_rev. eapply All2_impl; tea.\n  intros. now eapply eq_term_empty_eq_term.\nQed.\n\nLemma typing_leq_term {cf:checker_flags} (\u03a3 : global_env_ext) \u0393 t t' T T' :\n  wf \u03a3.1 ->\n  on_udecl \u03a3.1 \u03a3.2 ->\n  \u03a3 ;;; \u0393 |- t : T ->\n  \u03a3 ;;; \u0393 |- t' : T' ->\n  leq_term empty_global_env \u03a3 t' t ->\n  (* No cumulativity of inductive types, as they can relate\n    inductives in different sorts. *)\n  \u03a3 ;;; \u0393 |- t' : T.\nProof.\n  intros wf\u03a3 onu Ht.\n  revert \u03a3 wf\u03a3 \u0393 t T Ht onu t' T'.\n  eapply (typing_ind_env\n  (fun \u03a3 \u0393 t T =>\n    forall (onu : on_udecl \u03a3.1 \u03a3.2),\n    forall t' T' : term, \u03a3 ;;; \u0393 |- t' : T' -> leq_term empty_global_env \u03a3 t' t -> \u03a3;;; \u0393 |- t' : T)\n  (fun \u03a3 \u0393 => wf_local \u03a3 \u0393)); auto;intros \u03a3 wf\u03a3 \u0393 wf\u0393; intros.\n    1-13:match goal with\n    [ H : leq_term _ _ _ _ |- _ ] => depelim H\n    end.\n  all:try solve [econstructor; eauto].\n\n  - eapply inversion_Sort in X0 as [wf [wfs cum]]; auto.\n    eapply type_Cumul' with (tSort (Universe.super s)).\n    constructor; auto. eapply PCUICArities.isType_Sort; pcuic.\n    apply cumul_Sort. now apply leq_universe_super.\n\n  - eapply inversion_Prod in X4 as [s1' [s2' [Ha [Hb Hs]]]]; auto.\n    specialize (X1 onu _ _ Ha).\n    specialize (X1 (eq_term_empty_leq_term X5_1)).\n    apply eq_term_empty_eq_term in X5_1.\n    eapply context_conversion in Hb. 3:{ constructor. apply conv_ctx_refl. constructor.\n      eassumption. constructor. eauto. }\n    all:eauto.\n    2:{ constructor; eauto. now exists s1. }\n    specialize (X3 onu _ _ Hb X5_2).\n    econstructor; eauto.\n    apply leq_term_empty_leq_term in X5_2.\n    eapply context_conversion; eauto.\n    constructor; pcuic. constructor; try now symmetry; now constructor.\n    pcuic.\n    constructor; pcuic.\n    constructor. now symmetry.\n\n  - eapply inversion_Lambda in X4 as (s & B & dom & codom & cum); auto.\n    specialize (X1 onu _ _ dom (eq_term_empty_leq_term X5_1)).\n    apply eq_term_empty_eq_term in X5_1.\n    assert(conv_context cumulAlgo_gen \u03a3 (\u0393 ,, vass na ty) (\u0393 ,, vass n t)).\n    { repeat constructor; pcuic. }\n    specialize (X3 onu t0 B).\n    forward X3 by eapply context_conversion; eauto; pcuic.\n    eapply (type_ws_cumul_pb (pb:=Conv)).\n    * econstructor. eauto. instantiate (1 := bty).\n      eapply context_conversion; eauto; pcuic.\n      constructor; pcuic. constructor; pcuic. symmetry; constructor; auto.\n    * have tyl := type_Lambda _ _ _ _ _ _ _ X0 X2.\n      now eapply PCUICValidity.validity in tyl.\n    * eapply ws_cumul_pb_Prod; eauto.\n      constructor; auto; fvs.\n      eapply ws_cumul_pb_refl. now eapply typing_closed_ctx in codom.\n      eapply type_closed, closedn_on_free_vars in X2.\n      now len in X2; len.\n\n  - eapply inversion_LetIn in X6 as (s1' & A & dom & bod & codom & cum); auto.\n    specialize (X1 onu _ _ dom (eq_term_empty_leq_term X7_2)).\n    specialize (X3 onu _ _ bod (eq_term_empty_leq_term X7_1)).\n    apply eq_term_empty_eq_term in X7_1.\n    apply eq_term_empty_eq_term in X7_2.\n    assert(\u03a3 \u22a2 \u0393 ,, vdef na t ty = \u0393 ,, vdef n b b_ty).\n    { constructor. eapply ws_cumul_ctx_pb_refl. fvs. constructor => //.\n      constructor; fvs. constructor; fvs. }\n    specialize (X5 onu u A).\n    forward X5 by eapply closed_context_conversion; eauto; pcuic.\n    specialize (X5 X7_3).\n    eapply leq_term_empty_leq_term in X7_3.\n    have uty : \u03a3 ;;; \u0393 ,, vdef na t ty |- u : b'_ty.\n    { eapply closed_context_conversion; eauto.\n      pcuic. now symmetry. }\n    eapply type_ws_cumul_pb.\n    * econstructor. eauto. eauto.\n      now instantiate (1 := b'_ty).\n    * eapply PCUICValidity.validity; eauto.\n      econstructor; eauto.\n    * eapply (ws_cumul_pb_LetIn (pb:=Conv)); pcuic.\n      constructor; auto; fvs.\n      constructor; fvs.\n      apply ws_cumul_pb_refl; fvs.\n\n  - eapply inversion_App in X6 as (na' & A' & B' & hf & ha & cum); auto.\n    unfold leq_term in X1.\n    eapply eq_term_upto_univ_empty_impl in X7_1.\n    specialize (X3 onu _ _ hf X7_1). all:try typeclasses eauto.\n    specialize (X5 onu _ _ ha (eq_term_empty_leq_term X7_2)).\n    eapply leq_term_empty_leq_term in X7_1.\n    eapply eq_term_empty_eq_term in X7_2.\n    eapply type_ws_cumul_pb.\n    * eapply type_App'; [eapply X3|eapply X5].\n    * eapply validity; pcuic.\n      eapply type_App; eauto.\n    * eapply ws_cumul_pb_eq_le.\n      eapply validity in X2; auto.\n      apply PCUICArities.isType_tProd in X2 as [tyA tyB].\n      eapply (substitution_ws_cumul_pb_subst_conv (\u03930 := [vass na A]) (\u03931 := [vass na A]) (\u0394 := [])); pcuic.\n      constructor. 2:constructor.\n      constructor; fvs.\n\n  - eapply inversion_Const in X1 as [decl' [wf [declc [cu cum]]]]; auto.\n    eapply type_Cumul'; eauto.\n    econstructor; eauto.\n    eapply validity; eauto.\n    econstructor; eauto.\n    eapply eq_term_upto_univ_cumulSpec.\n    pose proof (declared_constant_inj _ _ H declc); subst decl'.\n    eapply PCUICUnivSubstitutionConv.eq_term_upto_univ_subst_instance; eauto; typeclasses eauto.\n\n  - eapply inversion_Ind in X1 as [decl' [idecl' [wf [declc [cu cum]]]]]; auto.\n    eapply type_Cumul'; eauto.\n    econstructor; eauto.\n    eapply validity; eauto.\n    econstructor; eauto.\n    eapply eq_term_upto_univ_cumulSpec.\n    pose proof (declared_inductive_inj isdecl declc) as [-> ->].\n    eapply PCUICUnivSubstitutionConv.eq_term_upto_univ_subst_instance; eauto; typeclasses eauto.\n\n  - eapply inversion_Construct in X1 as [decl' [idecl' [cdecl' [wf [declc [cu cum]]]]]]; auto.\n    eapply (type_ws_cumul_pb (pb:=Conv)); eauto.\n    econstructor; eauto.\n    eapply validity; eauto.\n    econstructor; eauto.\n    pose proof (declared_constructor_inj isdecl declc) as [-> [-> ->]].\n    unfold type_of_constructor.\n    transitivity (subst0 (inds (inductive_mind ind) u (ind_bodies mdecl))\n    (subst_instance u0 cdecl'.(cstr_type))).\n    * have clctx : is_closed_context (\u0393 ,,, (arities_context (ind_bodies mdecl))@[u0]).\n      { rewrite on_free_vars_ctx_app. apply /andP ; split => //. fvs.\n        erewrite PCUICOnFreeVars.on_free_vars_ctx_subst_instance.\n        pose proof (declared_minductive_closed_arities declc).\n        now eapply closed_ctx_on_free_vars in H0. }\n      eapply (substitution_ws_cumul_pb_subst_conv (\u0394 := [])); eauto.\n      eapply weaken_subslet; tea; eapply subslet_inds; tea; eapply isdecl.\n      split; revgoals.\n      eapply weaken_subslet; tea; eapply subslet_inds; tea; eapply isdecl.\n      eapply PCUICWeakeningTyp.weaken_wf_local; tea.\n      eapply (wf_arities_context_inst isdecl); tea.\n      cbn. eapply conv_inds => //. fvs.\n      simpl. eapply ws_cumul_pb_refl => //. tea.\n      pose proof (declared_constructor_closed_gen_type declc) as cl.\n      eapply closedn_on_free_vars in cl. len.\n      rewrite -shiftnP_add. len in cl.\n      now rewrite on_free_vars_subst_instance.\n    * have cld : is_open_term (\u0393 ,,, arities_context (ind_bodies mdecl)) (cstr_type cdecl').\n      { pose proof (declared_constructor_closed_gen_type declc) as cl.\n        eapply closedn_on_free_vars in cl. len.\n        rewrite -shiftnP_add. len in cl. exact cl. }\n      constructor; auto. fvs.\n      { eapply on_free_vars_subst. eapply inds_is_open_terms.\n        len. len in cld. rewrite shiftnP_add.\n        now rewrite on_free_vars_subst_instance. }\n      { eapply on_free_vars_subst. eapply inds_is_open_terms.\n        len. len in cld. rewrite shiftnP_add.\n        now rewrite on_free_vars_subst_instance. }\n      eapply PCUICEquality.subst_eq_term.\n      eapply PCUICUnivSubstitutionConv.eq_term_upto_univ_subst_instance; eauto; typeclasses eauto.\n\n  - eassert (ctx_inst _ _ _ _ _) as Hctxi by now eapply ctx_inst_impl with (1 := X5).\n    assert (isType \u03a3 \u0393 (mkApps ptm (indices ++ [c]))).\n    { eapply validity. econstructor; eauto. all:split; eauto.\n      solve_all. }\n    eapply inversion_Case in X9 as (mdecl' & idecl' & decli' & indices' & data & cum); auto.\n    destruct (declared_inductive_inj isdecl decli'). subst mdecl' idecl'.\n    destruct data.\n    unshelve epose proof (X7 _ _ _ scrut_ty (eq_term_empty_leq_term X10)); tea.\n    pose proof (eq_term_empty_eq_term X10).\n    destruct e as [eqpars [eqinst [eqpctx eqpret]]].\n    eapply eq_term_empty_eq_term in eqpret.\n    eapply type_ws_cumul_pb.\n    * econstructor; eauto. all:split; eauto.\n    * tas.\n    * clear brs_ty.\n      eapply ws_cumul_pb_eq_le.\n      eapply ws_cumul_pb_mkApps; pcuic.\n      rewrite /ptm. constructor. fvs.\n      eapply PCUICGeneration.type_it_mkLambda_or_LetIn in pret_ty. subst predctx0; fvs.\n      eapply PCUICGeneration.type_it_mkLambda_or_LetIn in pret. subst predctx; fvs.\n      eapply PCUICEquality.eq_term_upto_univ_it_mkLambda_or_LetIn; tea. tc.\n      rewrite /predctx.\n      rewrite /case_predicate_context /case_predicate_context_gen.\n      eapply eq_context_upto_map2_set_binder_name. tea.\n      rewrite /pre_case_predicate_context_gen.\n      eapply eq_context_upto_inst_case_context => //.\n      eapply All2_app. 2:constructor; pcuic.\n      specialize (X3 _ _ scrut_ty (eq_term_empty_leq_term X10)).\n      unshelve epose proof (principal_type_ind scrut_ty X3) as [_ indconv]; tea.\n      split; auto.\n      eapply All2_app_inv in indconv as [convpars convinds] => //.\n      exact (All2_length eqpars).\n      constructor => //; fvs.\n\n  - eapply inversion_Proj in X3 as (u' & mdecl' & idecl' & cdecl' & pdecl' & args' & inv); auto.\n    intuition auto.\n    specialize (X3 _ _ a0 (eq_term_empty_leq_term X4)).\n    eapply eq_term_empty_eq_term in X4.\n    assert (wf_ext \u03a3) by (split; assumption).\n    pose proof (principal_type_ind X3 a0) as [Ruu' X3'].\n    eapply (type_ws_cumul_pb (pb:=Conv)).\n    * clear a0.\n      econstructor; eauto.\n      now rewrite (All2_length X3').\n    * eapply PCUICValidity.validity; eauto.\n      eapply type_Proj; eauto.\n    * destruct (declared_projection_inj a isdecl) as [-> [-> [-> ->]]].\n      set (ctx := PCUICInductives.projection_context p.(proj_ind) mdecl idecl u).\n      have clctx : is_closed_context (\u0393,,, ctx).\n      { rewrite /ctx.\n        eapply validity in X1.\n        eapply isType_mkApps_Ind_inv in X1 as [parsubst [argsubst []]]; tea. 2:exact a.\n        epose proof (wf_projection_context _ _ a c1).\n        rewrite on_free_vars_ctx_app. apply /andP; split; fvs.\n        eapply wf_local_closed_context in X1.\n        eapply on_free_vars_ctx_impl; tea => //.\n        move=> i //. }\n      eapply (substitution_ws_cumul_pb_subst_conv (\u03930 := ctx) (\u03931 := ctx) (\u0394 := [])); eauto.\n      + eapply PCUICInductives.projection_subslet; eauto.\n        eapply validity in X3; auto.\n      + split.\n        eapply PCUICWeakeningTyp.weaken_wf_local; tea.\n        eapply wf_projection_context; tea.\n        eapply validity in X3.\n        now eapply (isType_mkApps_Ind_inv _ a) in X3 as [? [? []]].\n        eapply PCUICInductives.projection_subslet; eauto.\n        eapply validity in X3; auto.\n      + constructor. constructor; fvs.\n        eapply All2_rev. eapply ws_cumul_pb_terms_refl => //; fvs.\n      + rewrite /ctx; eapply ws_cumul_pb_refl => //.\n        epose proof (declared_projection_closed a).\n        rewrite on_free_vars_subst_instance; len. len.\n        rewrite -(declared_minductive_ind_npars a).\n        eapply closedn_on_free_vars in H0.\n        now rewrite -plus_Sn_m -shiftnP_add.\n\n  - eapply inversion_Fix in X2 as (decl' & fixguard' & Hnth & types' & bodies & wffix & cum); auto.\n    eapply type_Cumul_alt.\n    econstructor; eauto.\n    eapply PCUICValidity.validity; eauto.\n    econstructor. 3:eapply H0. all:eauto.\n    eapply (All_impl X0); pcuicfo.\n    apply infer_typing_sort_impl with id X2; now intros [].\n    eapply (All_impl X1); pcuicfo; now destruct X2.\n    eapply All2_nth_error in a; eauto.\n    destruct a as [[[eqty _] _] _].\n    constructor. eapply eq_term_empty_leq_term in eqty.\n    now eapply leq_term_empty_leq_term.\n\n  - eapply inversion_CoFix in X2 as (decl' & fixguard' & Hnth & types' & bodies & wfcofix & cum); auto.\n    eapply type_Cumul_alt.\n    econstructor; eauto.\n    eapply PCUICValidity.validity; eauto.\n    eapply type_CoFix. 3:eapply H0. all:eauto.\n    eapply (All_impl X0); pcuicfo.\n    apply infer_typing_sort_impl with id X2; now intros [].\n    eapply (All_impl X1); pcuicfo; now destruct X2.\n    eapply All2_nth_error in a; eauto.\n    destruct a as [[[eqty _] _] _].\n    constructor. apply eq_term_empty_leq_term in eqty.\n    now eapply leq_term_empty_leq_term.\n\n  - depelim X2.\n    econstructor; tea.\n\n  - eapply type_Cumul'.\n    eapply X1; eauto. now exists s.\n    auto.\nQed.\n\nLemma typing_eq_term {cf:checker_flags} (\u03a3 : global_env_ext) \u0393 t t' T T' :\n  wf_ext \u03a3 ->\n  \u03a3 ;;; \u0393 |- t : T ->\n  \u03a3 ;;; \u0393 |- t' : T' ->\n  eq_term empty_global_env \u03a3 t t' ->\n  \u03a3 ;;; \u0393 |- t' : T.\nProof.\n  intros wf\u03a3 ht ht' eq.\n  eapply typing_leq_term; eauto. apply wf\u03a3.\n  now eapply eq_term_empty_leq_term.\nQed.\n\n(* Print Assumptions principal_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/PCUICPrincipality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.17704614301940602}}
{"text": "Set Warnings \"-notation-overridden\".\nSet Warnings \"-duplicate-clear\".\nSet Warnings \"-spurious-ssr-injection\".\n\nRequire Import Coq.Strings.String.\nRequire Import LinearScan.Lib.\nRequire Import LinearScan.UsePos.\nRequire Import LinearScan.Range.\nRequire Import LinearScan.Interval.\nRequire Import LinearScan.ScanState.\nRequire Import LinearScan.Spec.\nRequire Import LinearScan.Morph.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\nSection Spill.\n\nVariable maxReg : nat.          (* max number of registers *)\nDefinition PhysReg := 'I_maxReg.\n\nInductive SpillCondition (sd : ScanStateDesc maxReg) (uid : IntervalId sd)\n  (i : IntervalSig) :=\n  | NewToHandled : SpillCondition uid i\n  | UnhandledToHandled :\n      vnth (intervals sd) uid = i -> SpillCondition uid i\n  | ActiveToHandled xid reg   :\n      vnth (intervals sd) xid = i ->\n      (xid, reg) \\in active sd    -> SpillCondition uid i\n  | InactiveToHandled xid reg :\n      vnth (intervals sd) xid = i ->\n      (xid, reg) \\in inactive sd -> SpillCondition uid i.\n\nDefinition SpillConditionToT `(x : @SpillCondition sd uid i) :=\n  match x with\n  | NewToHandled                  => NewToHandledT uid\n  | UnhandledToHandled _          => UnhandledToHandledT uid\n  | ActiveToHandled xid reg _ _   => ActiveToHandledT xid reg\n  | InactiveToHandled xid reg _ _ => InactiveToHandledT xid reg\n  end.\n\nTactic Notation \"SpillCondition_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"NewToHandled\"\n  | Case_aux c \"UnhandledToHandled\"\n  | Case_aux c \"ActiveToHandled\"\n  | Case_aux c \"InactiveToHandled\"\n  ].\n\n(* Determine the optimal split position between an absolute lower bound\n   (anything lower and we cannot insert the split interval onto the unhandled\n   list for reprocessing) and an absolute upper bound (anything higher is not\n   valid according to the algorithm). Anything in between is fair game. *)\nProgram Definition optimalSplitPosition `(i : Interval d) (lb ub : nat) :\n  nat := ub.\n\nTheorem optimalSplitPosition_spec `(i : Interval d) (lb ub : nat) :\n  optimalSplitPosition i lb ub <= ub.\nProof. by []. Qed.\n\nLemma widen_fst_inj : forall a n, injective (@widen_fst n a).\nProof.\n  move=> a n.\n  rewrite /injective => [[[x1a H1] x1b] [[x2a H2] x2b]].\n  invert.\n  congr (_, _).\n  rewrite H0 in H1 *.\n  congr (Ordinal _).\n  exact: eq_irrelevance.\nQed.\n\nDefinition spillInterval `(st : ScanState InUse sd)\n  (i1 : IntervalSig) `(Hunh : unhandled sd = (uid, beg) :: us)\n  (Hbeg : beg <= ibeg i1.1) (spill : SpillCondition uid i1) (e : seq SSTrace) :\n  seq SSTrace +\n    { ss : ScanStateSig maxReg InUse\n    | if spill is UnhandledToHandled _\n      then if firstUseReqReg i1.2 is Some _\n           then SSMorphLen sd ss.1\n           else SSMorph sd ss.1\n      else SSMorphHasLen sd ss.1 }.\nProof.\n  have e2 := ESpillInterval (SpillConditionToT spill) :: e.\n\n  (* Is there a use position requiring a register in the interval?  If yes,\n     then split it again; otherwise, spill it. *)\n  case S: (firstUseReqReg i1.2) => [[splitPos2 /= Hmid2] |]; last first.\n    move/eqP in S.\n    SpillCondition_cases\n      (case: spill => [|Heqe|xid reg Heqe Hin|xid reg Heqe Hin]) Case.\n    - Case \"NewToHandled\".\n      move: (ScanState_newHandled st S) => st'.\n      apply: inr _.\n      exists (_; st').\n      apply Build_SSMorphHasLen => //=;\n      try apply Build_SSMorphLen => //=;\n      try apply Build_SSMorph => //=;\n      by rewrite size_map Hunh.\n\n    - Case \"UnhandledToHandled\".\n      rewrite [firstUseReqReg]lock in S.\n      destruct sd; simpl in *.\n      rewrite Hunh in st.\n      have Hreq: firstUseReqReg (vnth intervals uid).2 == None.\n        rewrite -lock in S.\n        by rewrite Heqe S.\n      move: (ScanState_moveUnhandledToHandled st Hreq) => st'.\n      apply: inr _.\n      exists (_; st').\n      exact: Build_SSMorph.\n\n    - Case \"ActiveToHandled\".\n      have Hreq : (firstUseReqReg (getInterval xid) == None)\n        by rewrite /getInterval Heqe.\n      move: (moveActiveToHandled st Hin (spilled:=true) Hreq)\n        => [sd' st' [[[?] H] _]].\n      apply: inr _.\n      exists (sd'; st').\n      apply Build_SSMorphHasLen => //=.\n      apply H.\n      by rewrite Hunh.\n\n    - Case \"InactiveToHandled\".\n      have Hreq : (firstUseReqReg (getInterval xid) == None)\n        by rewrite /getInterval Heqe.\n      move: (moveInactiveToHandled st Hin (spilled:=true) Hreq)\n        => [sd' st' [[[?] H] _]].\n      apply: inr _.\n      exists (sd'; st').\n      apply Build_SSMorphHasLen => //=.\n      apply H.\n      by rewrite Hunh.\n\n  have e3 := EIntervalHasUsePosReqReg splitPos2 :: e2.\n\n  pose optSplitPos2 := optimalSplitPosition i1.2 beg splitPos2.\n\n  case E: (ibeg i1.1 >= optSplitPos2).\n    (* This interval goes back on the unhandled list, to be processed in a\n       later iteration. Note: this cannot change the head of the unhandled\n       list. *)\n    case Hincr: (beg < ibeg i1.1); last first.\n      move=> *.\n      exact: inl (ECannotInsertUnhandled\n                    beg (ibeg i1.1) optSplitPos2 (iend i1.1) ::\n                  EIntervalBeginsAtSplitPosition :: e3).\n\n    have := ScanState_newUnhandled st i1.2.\n    rewrite Hunh => /=.\n    move/(_ Hincr).\n    rewrite /= => {st} st.\n\n    apply: inr (packScanState st; _).\n    case: spill => [|*|*|*];\n    apply Build_SSMorphHasLen => //=;\n    try apply Build_SSMorphLen => //=;\n    try apply Build_SSMorph => //=;\n    by rewrite /= insert_size /=.\n\n  have Hmid3 : ibeg i1.1 < optSplitPos2 < iend i1.1.\n    clear -Hbeg Hmid2 E.\n    rewrite /optSplitPos2 /optimalSplitPosition.\n    move/negbT in E.\n    rewrite -ltnNge in E.\n    by ordered.\n\n  (* Wimmer: \"All active and inactive intervals for this register intersecting\n     with current are split before the start of current and spilled to the\n     stack.  These split children are not considered during allocation any\n     more because they do not have a register assigned.  If they have a use\n     positions requiring a register, however, they must be reloaded again to a\n     register later on.  Therefore, they are split a second time before these\n     use positions, and the second split children are sorted into the\n     unhandled list.  They get a register assigned when the allocator advances\n     to the start position of these intervals.\" *)\n  case: (splitInterval i1.2 Hmid3) => [[i1_0 i1_1] [/= H1_1 H2_1 H3_1]] //.\n\n  (* jww (2015-05-21): This should be [None] by definition, but I lack the\n     evidence for now, from the first use of [firstUseReqReg] and then\n     [splitInterval] at the returned position. *)\n  case Hreq: (firstUseReqReg i1_0.2) => [[pos ?]|].\n    exact: inl (ECannotSpillIfRegisterRequiredBefore optSplitPos2 pos :: e3).\n  rewrite [firstUseReqReg]lock in Hreq.\n  move/eqP in Hreq.\n\n  (* The second interval will go back on the unhandled list, to be processed\n     in a later iteration. Note: By definition of [insert] and\n     [ScanState_newUnhandled], it cannot become the new first element.\n\n     jww (2015-05-22): This should be proven. *)\n  have := ScanState_newUnhandled st i1_1.2.\n  rewrite Hunh => /=.\n  have Hincr: (beg < ibeg i1_1.1) by ordered.\n  move/(_ Hincr).\n  rewrite /= => {st} st.\n\n  move: st.\n  set unh' := insert _ _ _.\n  set sd' := (X in ScanState _ X).\n  rewrite /= in sd' *.\n  move=> st.\n\n  have Hle : nextInterval sd <= nextInterval sd' by ordered.\n\n  (* The first interval goes onto the handled list, with no register assigned\n     to indicate a spill. *)\n  SpillCondition_cases\n    (case: spill => [|Heqe|xid reg Heqe Hin|xid reg Heqe Hin]) Case.\n  - Case \"NewToHandled\".\n    rewrite -lock in Hreq.\n    move: (ScanState_newHandled st Hreq) => {st} st.\n    apply: inr _.\n    exists (_; st).\n    apply Build_SSMorphHasLen => //=;\n    try apply Build_SSMorphLen => //=;\n    try apply Build_SSMorph => //=;\n    try by rewrite size_map insert_size;\n    by ordered.\n    by ordered.\n\n  - Case \"UnhandledToHandled\".\n    (* Update the state with the new dimensions of the first interval. *)\n    move: (ScanState_setInterval st)\n      => /= /(_ (widen_ord Hle uid) i1_0.1 i1_0.2).\n\n    have Hint : ibeg i1_0.1 ==\n                ibeg (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle uid)).1.\n      have ->: widen_ord Hle uid = widen_id uid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      by rewrite vnth_vshiftin Heqe -H2_1.\n\n    have Hend : iend i1_0.1 <=\n                iend (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle uid)).1.\n      have ->: widen_ord Hle uid = widen_id uid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      rewrite vnth_vshiftin Heqe.\n      by ordered.\n\n    case Hnot: (widen_ord Hle uid \\notin handledIds sd'); last first.\n      move=> *.\n      exact: inl (ECannotModifyHandledInterval uid :: e3).\n\n    move/(_ Hint Hend is_true_true).\n    rewrite /= => {Hint Hend Hnot st} st.\n\n    rewrite /sd' in st.\n    case U: unh' => [|u' us'] in sd' Hle st.\n      move: U.\n      rewrite /unh'.\n      clear.\n      rewrite /insert /= -/insert.\n      set b := lebf _ _ _.\n      by case: b; discriminate.\n    rewrite /unh' /insert /= -/insert /widen_fst in U.\n\n    have Hreq' : firstUseReqReg\n                   (vnth (vreplace (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                                   (widen_ord Hle uid)\n                                   (i1_0.1; i1_0.2)) (fst u')).2 == None.\n      case F: (lebf (@snd _ _)\n                    (widen_fst (uid, beg)) (ord_max, ibeg i1_1.1)) in U;\n      inversion U.\n        have ->: widen_id uid = widen_ord Hle uid.\n          rewrite /widen_id.\n          f_equal.\n          exact: eq_irrelevance.\n        rewrite -lock in Hreq.\n        by rewrite vnth_vreplace.\n      rewrite /lebf /= in F.\n      by ordered.\n\n    move: (ScanState_moveUnhandledToHandled st Hreq') => {Hreq' st} st.\n\n    apply: inr _.\n    exists (_; st).\n\n    apply Build_SSMorphLen => //=;\n    try apply Build_SSMorph => //=;\n    case F: (lebf (@snd _ _)\n                  (widen_fst (uid, beg)) (ord_max, ibeg i1_1.1)) in U;\n    inversion U => //;\n    by rewrite insert_size.\n\n  - Case \"ActiveToHandled\".\n    move: (ScanState_setInterval st)\n      => /= /(_ (widen_ord Hle xid) i1_0.1 i1_0.2).\n\n    have Hint : ibeg i1_0.1 ==\n                ibeg (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle xid)).1.\n      have ->: widen_ord Hle xid = widen_id xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      by rewrite vnth_vshiftin Heqe -H2_1.\n\n    have Hend : iend i1_0.1 <=\n                iend (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle xid)).1.\n      have ->: widen_ord Hle xid = widen_id xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      rewrite vnth_vshiftin Heqe.\n      by ordered.\n\n    case Hnot: (widen_ord Hle xid \\notin handledIds sd'); last first.\n      move=> *.\n      exact: inl (ECannotModifyHandledInterval xid :: e3).\n\n    move/(_ Hint Hend is_true_true).\n    rewrite /= => {Hint Hend Hnot st} st.\n\n    move: st.\n    set sd'' := (X in ScanState _ X).\n    rewrite /= in sd'' *.\n    move=> st.\n\n    pose elem := widen_fst (xid, reg).\n    have Hin' : elem \\in active sd'.\n      rewrite /sd' /= mem_map //=.\n      exact: widen_fst_inj.\n    case Helem: elem => [a b] in Hin'.\n\n    have Hreq' : if true\n                 then firstUseReqReg (vnth (intervals sd'') a).2 == None\n                 else true.\n      rewrite /elem /widen_fst in Helem.\n      inversion Helem.\n      rewrite -lock in Hreq.\n      have ->: widen_id xid = widen_ord Hle xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      by rewrite /sd'' [vnth _]/= vnth_vreplace.\n\n    move: (moveActiveToHandled st Hin' (spilled:=true) Hreq')\n      => [sd3 st3 [[[?] H] _]].\n    apply: inr _.\n    exists (sd3; st3).\n    apply Build_SSMorphHasLen => //=;\n    try apply Build_SSMorphLen => //=;\n    try apply Build_SSMorph => //=.\n    + by ordered.\n    + replace (unhandled sd') with unh' in H; last by auto.\n      rewrite /unh' insert_size /= in H.\n      by auto.\n    + replace (unhandled sd') with unh' in H; last by auto.\n      rewrite /unh' insert_size /= in H.\n      by auto.\n\n  - Case \"InactiveToHandled\".\n    move: (ScanState_setInterval st)\n      => /= /(_ (widen_ord Hle xid) i1_0.1 i1_0.2).\n\n    have Hint : ibeg i1_0.1 ==\n                ibeg (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle xid)).1.\n      have ->: widen_ord Hle xid = widen_id xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      by rewrite vnth_vshiftin Heqe -H2_1.\n\n    have Hend : iend i1_0.1 <=\n                iend (vnth (vshiftin (intervals sd) (i1_1.1; i1_1.2))\n                           (widen_ord Hle xid)).1.\n      have ->: widen_ord Hle xid = widen_id xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      rewrite vnth_vshiftin Heqe.\n      by ordered.\n\n    case Hnot: (widen_ord Hle xid \\notin handledIds sd'); last first.\n      move=> *.\n      exact: inl (ECannotModifyHandledInterval xid :: e3).\n\n    move/(_ Hint Hend is_true_true).\n    rewrite /= => {Hint Hend Hnot st} st.\n\n    move: st.\n    set sd'' := (X in ScanState _ X).\n    rewrite /= in sd'' *.\n    move=> st.\n\n    pose elem := widen_fst (xid, reg).\n    have Hin' : elem \\in inactive sd'.\n      rewrite /sd' /= mem_map //=.\n      exact: widen_fst_inj.\n    case Helem: elem => [a b] in Hin'.\n\n    have Hreq' : if true\n                 then firstUseReqReg (vnth (intervals sd'') a).2 == None\n                 else true.\n      rewrite /elem /widen_fst in Helem.\n      inversion Helem.\n      rewrite -lock in Hreq.\n      have ->: widen_id xid = widen_ord Hle xid.\n        rewrite /widen_id.\n        f_equal.\n        exact: eq_irrelevance.\n      by rewrite /sd'' [vnth _]/= vnth_vreplace.\n\n    move: (moveInactiveToHandled st Hin' (spilled:=true) Hreq')\n      => [sd3 st3 [[[?] H] _]].\n    apply: inr _.\n    exists (sd3; st3).\n    apply Build_SSMorphHasLen => //=;\n    try apply Build_SSMorphLen => //=;\n    try apply Build_SSMorph => //=.\n    + by ordered.\n    + replace (unhandled sd') with unh' in H; last by auto.\n      rewrite /unh' insert_size /= in H.\n      by auto.\n    + replace (unhandled sd') with unh' in H; last by auto.\n      rewrite /unh' insert_size /= in H.\n      by auto.\nDefined.\n\nDefinition spillCurrentInterval {pre} :\n  SState pre (@SSMorphHasLen maxReg) (@SSMorph maxReg) unit.\nProof.\n  move=> e ssi.\n  have e2 := ESpillCurrentInterval :: e.\n  case: ssi => sd.\n  case=> H. case: H => /=; case.\n  case Hunh: (unhandled sd) => //= [[uid beg] us].\n  move=> H1 H2 H3.\n  have := getInterval uid.\n  set d := (X in Interval X).\n  move=> i st.\n  case Hbeg2: (beg <= ibeg d); last first.\n    exact: inl (EIntervalBeginsBeforeUnhandled uid :: e).\n  case: (spillInterval st Hunh Hbeg2 (UnhandledToHandled (refl_equal _)) e)\n    => [err|[[sd' st'] H]].\n    exact: inl err.\n  apply: inr (tt, _).\n  apply: (Build_SSInfo _ st').\n  case: (firstUseReqReg (vnth (intervals sd) uid).2) => [[pos /= ?]|] in H.\n  case: H => [[/= ?] _].\n  apply Build_SSMorph => //=; by ordered.\n  case: H => [/= ?].\n  apply Build_SSMorph => //=; by ordered.\nDefined.\n\nEnd Spill.\n", "meta": {"author": "jwiegley", "repo": "linearscan", "sha": "1f8c74134d7634061d3cce4b2817708e9e82037d", "save_path": "github-repos/coq/jwiegley-linearscan", "path": "github-repos/coq/jwiegley-linearscan/linearscan-1f8c74134d7634061d3cce4b2817708e9e82037d/src/Spill.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.17704612927220717}}
{"text": "(** * Grothendieck Construction of a functor to Cat *)\nRequire Import Category.Core Functor.Core.\nRequire Import Pseudofunctor.FromFunctor.\nRequire Import Cat.Core.\nRequire Import Grothendieck.PseudofunctorToCat.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope morphism_scope.\n\nSection Grothendieck.\n  Context `{Funext}.\n\n  Variable P : PreCategory -> Type.\n  (*Context `{forall C, IsHProp (P C)}.*)\n  Context `{HF : forall C D, P C -> P D -> IsHSet (Functor C D)}.\n\n  Local Notation cat := (@sub_pre_cat _ P HF).\n\n  Variable C : PreCategory.\n  Variable F : Functor C cat.\n\n  (** ** Category of elements *)\n  Definition category : PreCategory\n    := category (pseudofunctor_of_functor_to_cat F).\n\n  (** ** First projection functor *)\n  Definition pr1 : Functor category C\n    := pr1 (pseudofunctor_of_functor_to_cat F).\nEnd Grothendieck.\n", "meta": {"author": "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/Grothendieck/ToCat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.17700248492592324}}
{"text": "Require Import Prelude.\nRequire Import Infrastructure.\n\nOpen Scope list_scope.\n\n(* Proofs regarding proposition 2.1 from the paper *)\nSection SimpleEquationProperties.\n\n  Variable \u03a3 : GADTEnv.\n\n  Lemma teq_reflexivity : forall \u0394 T,\n      entails_semantic \u03a3 \u0394 (T \u2261 T).\n    cbn.\n    intros.\n    auto.\n  Qed.\n\n  Lemma teq_symmetry : forall \u0394 T U,\n      entails_semantic \u03a3 \u0394 (T \u2261 U) ->\n      entails_semantic \u03a3 \u0394 (U \u2261 T).\n    cbn. intros.\n    symmetry.\n    auto.\n  Qed.\n\n  Lemma teq_transitivity : forall \u0394 T U V,\n      entails_semantic \u03a3 \u0394 (T \u2261 U) ->\n      entails_semantic \u03a3 \u0394 (U \u2261 V) ->\n      entails_semantic \u03a3 \u0394 (T \u2261 V).\n    cbn. intros.\n    transitivity (subst_tt' U \u0398); auto.\n  Qed.\n\n  Lemma subst_has_no_fv : forall \u03a3 \u0394 \u0398,\n      subst_matches_typctx \u03a3 \u0394 \u0398 ->\n      (forall X U, List.In (X, U) \u0398 -> fv_typ U = \\{}).\n  Proof.\n    induction 1; introv Hin.\n    - false.\n    - cbn in Hin.\n      destruct Hin as [Hin | Hin].\n      + inversions Hin.\n        lets Hfv: wft_gives_fv H.\n        cbn in Hfv.\n        apply~ fset_extens.\n      + apply* IHsubst_matches_typctx.\n    - apply* IHsubst_matches_typctx.\n  Qed.\n\n  Lemma teq_axiom : forall \u0394 T U,\n      List.In (tc_eq (T \u2261 U)) \u0394 ->\n      entails_semantic \u03a3 \u0394 (T \u2261 U).\n  Proof.\n    unfold entails_semantic.\n    induction \u0394; introv Hin M.\n    - contradiction.\n    - cbn in Hin.\n      destruct Hin as [Hin | Hin].\n      + subst. inversion M.\n        easy.\n      + inversion M; auto.\n        cbn.\n        repeat rewrite subst_tt_inside; auto.\n        * f_equal.\n          apply IH\u0394; auto.\n        * introv Uin.\n          lets Fr: subst_has_no_fv Uin.\n          -- eauto.\n          -- rewrite Fr. apply notin_empty.\n        * introv Uin.\n          lets Fr: subst_has_no_fv Uin.\n          -- eauto.\n          -- rewrite Fr. apply notin_empty.\n  Qed.\n\nEnd SimpleEquationProperties.\n\nLtac fold_from_list :=\n  repeat progress match goal with\n  | [ H: context[LibList.fold_right (fun (x : var) (acc : fset var) => \\{ x} \\u acc) \\{} ?L]  |- _ ] =>\n    fold (from_list L) in H\n  | |- context[LibList.fold_right (fun (x : var) (acc : fset var) => \\{ x} \\u acc) \\{} ?L] =>\n    fold (from_list L)\n                  end.\n\nLemma notin_from_list : forall As (A : var),\n    ~ (List.In A As) ->\n    A \\notin from_list As.\n  intros.\n  intro HF.\n  lets [A' [Hin Heq]]: in_from_list HF.\n  subst.\n  auto.\nQed.\n\nLemma spawn_unit_subst : forall \u03a3 As,\n    DistinctList As ->\n    exists \u0398, length \u0398 = length As /\\ subst_matches_typctx \u03a3 (tc_vars As) \u0398 /\\ substitution_sources \u0398 = from_list As.\nProof.\n  induction As as [| Ah Ats]; introv ADist.\n  - cbn.\n    exists (@nil (var * typ)).\n    splits~.\n    constructor.\n  - inversions ADist.\n    destruct IHAts as [LT [Len [Match Src]]]; auto.\n    exists ((Ah, typ_unit) :: LT).\n    splits.\n    + cbn. auto.\n    + constructor;\n        fold (List.map tc_var Ats);\n        fold (tc_vars Ats);\n        auto.\n      * rewrite Src.\n        apply~ notin_from_list.\n      * apply notin_dom_tc_vars.\n        apply~ notin_from_list.\n    + cbn.\n      fold_from_list.\n      fold (substitution_sources LT).\n      rewrite Src.\n      trivial.\nQed.\n\nLemma only_vars_is_tc_vars : forall \u0394,\n    (forall tc, List.In tc \u0394 -> exists A, tc = tc_var A) ->\n    exists As, \u0394 = tc_vars As.\nProof.\n  induction \u0394 as [| [A | eq] \u0394t].\n  - cbn. intros. exists (@nil var). cbn. trivial.\n  - cbn. intro Hin.\n    lets* [Ats EQ]: IH\u0394t.\n    exists (A :: Ats). cbn.\n    fold (tc_vars Ats).\n    f_equal.\n    auto.\n  - cbn. intro Hin.\n    false~ Hin. congruence.\nQed.\n\nLemma contradictory_env_test_0 : forall \u03a3 \u0394,\n    entails_semantic \u03a3 \u0394 (typ_unit \u2261 (typ_unit ** typ_unit)) ->\n    contradictory_bounds \u03a3 \u0394.\nProof.\n  introv Heq.\n  unfold contradictory_bounds.\n  intros.\n  unfold entails_semantic in *.\n  introv Hmatch.\n  exfalso.\n  lets HF: Heq Hmatch.\n  rewrite subst_tt\u0398_fresh in HF.\n  - rewrite subst_tt\u0398_fresh in HF.\n    + false.\n    + cbn. rewrite union_empty_r.\n      rewrite~ inter_empty_r.\n  - cbn.\n    rewrite~ inter_empty_r.\nQed.\n\nLemma subst_tt\u0398_into_abs : forall \u0398 A B,\n    subst_tt' (A ==> B) \u0398\n    =\n    (subst_tt' A \u0398) ==> (subst_tt' B \u0398).\n  induction \u0398 as [| [X T] \u0398]; cbn in *; trivial.\nQed.\nLemma subst_tt\u0398_into_tuple : forall \u0398 A B,\n    subst_tt' (A ** B) \u0398\n    =\n    (subst_tt' A \u0398) ** (subst_tt' B \u0398).\n  induction \u0398 as [| [X T] \u0398]; cbn in *; trivial.\nQed.\n\nLemma contradictory_env_test : forall \u03a3 \u0394 A B C D,\n    entails_semantic \u03a3 \u0394 ((A ==> B) \u2261 (C ** D)) ->\n    contradictory_bounds \u03a3 \u0394.\nProof.\n  introv Heq.\n  unfold contradictory_bounds.\n  intros.\n  unfold entails_semantic in *.\n  introv Hmatch.\n  exfalso.\n  lets HF: Heq Hmatch.\n  rewrite subst_tt\u0398_into_abs in HF.\n  rewrite subst_tt\u0398_into_tuple in HF.\n  congruence.\nQed.\n\nLemma empty_is_not_contradictory : forall \u03a3,\n    ~ (contradictory_bounds \u03a3 empty\u0394).\nProof.\n  intros.\n  intro HF.\n  unfold contradictory_bounds in HF.\n  asserts M: (subst_matches_typctx \u03a3 empty\u0394 (@nil (var*typ)));\n    try econstructor.\n  lets F: HF typ_unit (typ_unit ** typ_unit) (@nil (var * typ)) M.\n  cbn in F.\n  false.\nQed.\n\nLemma typing_exfalso : forall \u03a3 \u0394 E e T1 T2 TT,\n    {\u03a3, \u0394, E} \u22a2(TT) e \u2208 T1 ->\n    contradictory_bounds \u03a3 \u0394 ->\n    wft \u03a3 \u0394 T2 ->\n    {\u03a3, \u0394, E} \u22a2(Tgen) e \u2208 T2.\n  introv Typ Bounds.\n  eapply typing_eq; eauto.\nQed.\n\nLemma inversion_typing_eq : forall \u03a3 \u0394 E e T TT,\n    {\u03a3, \u0394, E} \u22a2(TT) e \u2208 T ->\n    exists T',\n      {\u03a3, \u0394, E} \u22a2(Treg) e \u2208 T' /\\ entails_semantic \u03a3 \u0394 (T \u2261 T').\nProof.\n  introv Htyp.\n  lets Htyp2: Htyp.\n  induction Htyp;\n    try match goal with\n        | [ H: {\u03a3, \u0394, E} \u22a2(Treg) ?e \u2208 ?T |- _ ] =>\n          exists T; split~; auto using teq_reflexivity\n        end.\n  lets [T' [IHTyp IHeq]]: IHHtyp Htyp.\n  exists T'.\n  split~.\n  eauto using teq_symmetry, teq_transitivity.\nQed.\n\nLemma subst_has_no_fv2 : forall \u03a3 \u0394 \u0398 Y,\n    subst_matches_typctx \u03a3 \u0394 \u0398 ->\n    (forall A U, List.In (A, U) \u0398 -> Y \\notin fv_typ U).\nProof.\n  introv M Hin.\n  lets EQ: subst_has_no_fv M Hin.\n  rewrite EQ.\n  auto.\nQed.\n\nLemma inversion_eq_arrow : forall \u03a3 \u0394 TA1 TB1 TA2 TB2,\n    entails_semantic \u03a3 \u0394 ((TA1 ==> TB1) \u2261 (TA2 ==> TB2)) ->\n    entails_semantic \u03a3 \u0394 (TA1 \u2261 TA2) /\\\n    entails_semantic \u03a3 \u0394 (TB1 \u2261 TB2).\nProof.\n  introv Sem; cbn in *.\n  split~;\n       introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_arrow in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_tuple : forall \u03a3 \u0394 TA1 TB1 TA2 TB2,\n    entails_semantic \u03a3 \u0394 ((TA1 ** TB1) \u2261 (TA2 ** TB2)) ->\n    entails_semantic \u03a3 \u0394 (TA1 \u2261 TA2) /\\\n    entails_semantic \u03a3 \u0394 (TB1 \u2261 TB2).\nProof.\n  introv Sem; cbn in *.\n  split~;\n       introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_tuple in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_typ_all : forall \u03a3 \u0394 T U,\n    entails_semantic \u03a3 \u0394 (typ_all T \u2261 typ_all U) ->\n    entails_semantic \u03a3 \u0394 (T \u2261 U).\nProof.\n  introv Sem; cbn in *.\n  introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_typ_all in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_typ_gadt : forall \u03a3 \u0394 Ts Us N,\n    List.length Ts = List.length Us ->\n    entails_semantic \u03a3 \u0394 (typ_gadt Ts N \u2261 typ_gadt Us N) ->\n    List.Forall2 (fun T U => entails_semantic \u03a3 \u0394 (T \u2261 U)) Ts Us.\nProof.\n  introv Len Sem.\n  apply F2_iff_In_zip.\n  split~.\n  intros T U In.\n  cbn in *.\n  introv M.\n  lets EQ: Sem M.\n  repeat rewrite subst_tt_prime_reduce_typ_gadt in EQ.\n  inversion EQ as [EQ2].\n  lets~ : lists_map_eq EQ2 In.\nQed.\n\nLemma equations_from_lists_map : forall F F1 F2 Ts Us,\n    List.length Ts = List.length Us ->\n    (forall T U, List.In (T,U) (zip Ts Us) -> F (tc_eq (T \u2261 U)) = tc_eq (F1 T \u2261 F2 U)) ->\n    List.map F (equations_from_lists Ts Us)\n    =\n    equations_from_lists (List.map F1 Ts) (List.map F2 Us).\nProof.\n  induction Ts as [| T Ts]; destruct Us as [| U Us];\n    introv Len;  try solve [inversion~ Len].\n  introv EQ.\n  cbn.\n  fold (equations_from_lists Ts Us).\n  fold (equations_from_lists (List.map F1 Ts) (List.map F2 Us)).\n  f_equal.\n  - apply EQ. cbn. auto.\n  - apply* IHTs.\n    introv In.\n    apply EQ. cbn. auto.\nQed.\n\nLemma empty_eq_is_equivalent : forall \u03a3 T1 T2,\n  entails_semantic \u03a3 empty\u0394 (T1 \u2261 T2) ->\n  T1 = T2.\nProof.\n  introv Sem.\n  cbn in *.\n  lets M: Sem (@nil (var * typ)).\n  forwards * : M.\n  constructor.\nQed.", "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/Equations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17695644628998497}}
{"text": "From F_mu_ref_conc_sub Require Export context_refinement.\nFrom iris.algebra Require Import auth frac agree.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import adequacy.\nFrom F_mu_ref_conc_sub Require Import soundness_unary.\n\nLemma basic_soundness \u03a3 `{heapPreIG \u03a3, inG \u03a3 (authR cfgUR)}\n    e e' \u03c4 v thp hp :\n  (\u2200 `{heapIG \u03a3, cfgSG \u03a3}, [] \u2223 [] \u22a8 e \u2264log\u2264 e' : \u03c4) \u2192\n  rtc erased_step ([e], \u2205) (of_val v :: thp, hp) \u2192\n  (\u2203 thp' hp' v', rtc erased_step ([e'], \u2205) (of_val v' :: thp', hp')).\nProof.\n  intros Hlog Hsteps.\n  cut (adequate NotStuck e \u2205 (\u03bb _ _, \u2203 thp' h v, rtc erased_step ([e'], \u2205) (of_val v :: thp', h))).\n  { destruct 1; naive_solver. }\n  eapply (wp_adequacy \u03a3 _); iIntros (Hinv ?).\n  iMod (gen_heap_init (\u2205 : gmap loc val)) as (GHG) \"Hh\".\n  iMod (own_alloc (\u25cf (to_tpool [e'], \u2205)\n    \u22c5 \u25ef ((to_tpool [e'] : tpoolUR, \u2205) : cfgUR))) as (\u03b3c) \"[Hcfg1 Hcfg2]\".\n  { apply auth_both_valid. split=>//. split=>//. apply to_tpool_valid. }\n  set (Hcfg := CFGSG _ _ \u03b3c).\n  iMod (inv_alloc specN _ (spec_inv ([e'], \u2205)) with \"[Hcfg1]\") as \"#Hcfg\".\n  { iNext. iExists [e'], \u2205. rewrite /to_gen_heap fin_maps.map_fmap_empty. auto. }\n  set (Heap\u03a3 := (HeapIG \u03a3 Hinv GHG)).\n  iExists (\u03bb \u03c3 _, gen_heap_ctx \u03c3); iFrame.\n  iExists (\u03bb _, True)%I.\n  iApply wp_fupd. iApply wp_wand_r.\n  iSplitL.\n  iPoseProof ((Hlog _ _ [] [] ([e'], \u2205)) with \"[$Hcfg] [] []\") as \"Hrel\".\n  { iSplit; eauto. by iIntros (? ?); rewrite lookup_nil; iIntros (?). }\n  { iApply (@logrel_binary.interp_env_nil \u03a3 Heap\u03a3). }\n  simpl.\n  replace e with e.[env_subst[]] at 2 by by asimpl.\n  iApply (\"Hrel\" $! 0 []).\n  { rewrite /tpool_mapsto. asimpl. by iFrame. }\n  iModIntro. iIntros (v1); iDestruct 1 as (v2) \"[Hj #Hinterp]\".\n  iInv specN as (tp \u03c3) \">[Hown Hsteps]\" \"Hclose\"; iDestruct \"Hsteps\" as %Hsteps'.\n  rewrite /tpool_mapsto /=.\n  iDestruct (own_valid_2 with \"Hown Hj\") as %Hvalid.\n  move: Hvalid=> /auth_both_valid\n    [/prod_included [/tpool_singleton_included Hv2 _] _].\n  destruct tp as [|? tp']; simplify_eq/=.\n  iMod (\"Hclose\" with \"[-]\") as \"_\"; [iExists (_ :: tp'), \u03c3; auto|].\n  iIntros \"!> !%\"; eauto.\nQed.\n\nLemma binary_soundness \u03a3 `{heapPreIG \u03a3, inG \u03a3 (authR cfgUR)}\n    \u039e \u0393 e e' \u03c4 :\n  (\u039e |\u209c \u0393 \u22a2\u209c e : \u03c4) \u2192 (\u039e |\u209c \u0393 \u22a2\u209c e' : \u03c4) \u2192\n  (\u2200 `{heapIG \u03a3, cfgSG \u03a3}, \u039e \u2223 \u0393 \u22a8 e \u2264log\u2264 e' : \u03c4) \u2192\n  \u039e \u2223 \u0393 \u22a8 e \u2264ctx\u2264 e' : \u03c4.\nProof.\n  intros He He' Hlog; repeat split; auto.\n  intros K thp \u03c3 v ?. eapply (basic_soundness \u03a3 _)=> ??.\n  eapply (bin_log_related_under_typed_ctx); eauto.\nQed.\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/soundness_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17695644628998497}}
{"text": "From iris.algebra Require Import excl auth frac 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_df auth_ext.\nRequire Export multicopy_util.\n\nSection multicopy_df_upsert.\n  Context {\u03a3} `{!heapG \u03a3, !multicopyG \u03a3, !multicopy_dfG \u03a3}.\n  Notation iProp := (iProp \u03a3).\n  Local Notation \"m !1 i\" := (nzmap_total_lookup i m) (at level 20).\n\n  Lemma nodePred_lockR_true \u03b3_s \u03b3_cn r n Cn Vn Vn' Tn bn : \n    node r n Vn' -\u2217 \n      lockR bn n (nodePred \u03b3_s \u03b3_cn r n Cn Vn Tn) -\u2217\n        \u231cbn = true\u231d.\n  Proof.\n    iIntros \"node Hl_n\".\n    destruct bn; try done.\n    iDestruct \"Hl_n\" as \"(Hl & HnP')\".\n    iDestruct \"HnP'\" as \"(n' & _)\".\n    iExFalso. iApply (node_sep_star r n). iFrame.\n  Qed.          \n\n  Lemma upsert_spec N \u03b3_te \u03b3_he \u03b3_s Prot \u03b3_cr \u03b3_cd \u03b3_d r d (k: K) (v: V) :\n    \u22a2 \u231ck \u2208 KS\u231d -\u2217 \n        (ghost_update_protocol N \u03b3_te \u03b3_he Prot k) -\u2217 \n        mcs_inv N \u03b3_te \u03b3_he \u03b3_s Prot \n          (Inv_DF \u03b3_s \u03b3_cr \u03b3_cd \u03b3_d r d) -\u2217\n            <<< \u2200 (t: T) H, MCS \u03b3_te \u03b3_he t H >>> \n                   upsert r #k #v @ \u22a4 \u2216 (\u2191(mcsN N))\n            <<< MCS \u03b3_te \u03b3_he (t + 1) (H \u222a {[(k, (v, t))]}), RET #() >>>.\n  Proof.\n    iIntros \"%\".\n    rename H into k_in_KS.\n    (* perform L\u00f6b induction by generating a hypothesis IH : \u25b7 goal *)\n    iL\u00f6b as \"IH\".\n    iIntros \"Ghost_updP #HInv\" (\u03a6) \"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_DF)\".\n    iDestruct \"Inv_DF\" as (Cr0 Vr0 Tr0 Cd0 Vd0 Td0) \"(r_neq_d & Hcir \n            & Hset & HlockR_r & Half_r & Hcts_r \n            & HlockR_d & Half_d & Hcts_d)\".\n    iModIntro. iSplitR \"AU Ghost_updP\". iNext. \n    iExists t0, H0. iFrame \"mcs_high\". \n    iExists Cr0, Vr0, Tr0, Cd0, Vd0, Td0. iFrame \"\u2217 #\".\n    \n    iModIntro.\n    awp_apply lockNode_spec_high without \"Ghost_updP\"; try done.\n    iPureIntro. auto.\n    (** Lock the node r **)\n    iAaccIntro with \"\"; try eauto with iFrame.\n     \n    iIntros (\u03b3_cn Cr Vr Tr) \"HnP_n\". iModIntro. \n    iIntros \"Ghost_updP\". wp_pures.\n    iDestruct \"HnP_n\" as \"(HnP_n & #r_is_locked)\".\n    iDestruct \"HnP_n\" as \"(node_r & HnP_C & HnP_frac)\".\n    wp_apply (addContents_spec with \"[$node_r]\"); try done.\n    iIntros (b Vr') \"(node_r & Hif)\".\n\n\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_frac HnP_C node_r ]\") \n            without \"Ghost_updP\" ; try done.\n      { \n        iFrame.\n      }\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_DF)\".\n      iDestruct \"Inv_DF\" as (Cr1 Vr1 Tr1 Cd1 Vd1 Td1) \"(r_neq_d & Hcir \n            & Hset & HlockR_r & Half_r & Hcts_r \n            & HlockR_d & Half_d & Hcts_d)\".\n\n      iDestruct \"mcs_high\" as \"(>MCS_auth & >HH & >HInit \n        & >HClock & >HUniq & Prot)\".\n\n      iDestruct \"HlockR_r\" as (br) \"HlockR_r\".\n      iDestruct \"HlockR_d\" as (bd) \"HlockR_d\".      \n      iDestruct \"Hif\" as %HCr.\n\n      set (Tr' := <[k := t1]> Tr).\n      set (Cr' := <[k := (v, t1)]> Cr).\n      set (H1' := H1 \u222a {[(k, (v, t1))]}).\n      \n      iPoseProof ((auth_own_incl \u03b3_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')) \u2208 H1) \u2228 (k' = k \u2227 v' = v \u2227 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 (\u231cset_of_map Cr' \u2286 H1'\u231d)%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 (\u25cf H) resource **)  \n      iMod (own_update \u03b3_s (\u25cf H1) (\u25cf H1') \n          with \"[$HH]\") as \"HH\".\n      { apply (auth_update_auth _ _ H1').\n        apply gset_local_update. set_solver. }\n      iMod (own_update \u03b3_s (\u25cf H1') \n             (\u25cf H1' \u22c5 \u25ef (set_of_map Cr')) \n              with \"[$HH]\") as \"HH\".\n      { subst H1'.\n        apply (auth_update_alloc _ (H1 \u222a {[(k, (v, t1))]}) (set_of_map Cr')).\n        apply local_update_discrete. intros m Valid_H1 H1_eq.\n        split; try done. rewrite /(\u03b5 \u22c5? 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' \u22c5? Some (H1 \u222a {[k, (v, t1)]})).\n        rewrite gset_op.\n        rewrite /(\u03b5) in H1_eq. unfold ucmra_unit in H1_eq.\n        simpl in H1_eq.\n        assert ((k, (v, t1)) \u2208 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 (\u231cHInit H1'\u231d)%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 \"Hown_Cr\".  \n      iDestruct \"HH\" as \"(HH & HnP_C)\".   \n\n      rewrite (big_sepS_delete _ KS k); last by eauto.\n      iDestruct \"HInit\" as %HInit.\n\n      iPoseProof (nodePred_lockR_true with \"[$node_r] [HlockR_r]\")\n         as \"%\". iFrame. subst br.\n        \n      (** Update contents-in-reach of r **)\n      iAssert (\u231cmap_of_set H1' = \n                        <[k:= (v, t1)]> (map_of_set H1)\u231d)%I as %Htrans_union.\n      { \n        iDestruct \"HUniq\" as %HUniq. \n        iPureIntro.\n        pose proof map_of_set_insert_eq k v t1 H1 HUniq HClock_H1 as mos_eq.\n        by subst H1'. \n      }\n\n      iAssert (\u231c\u03b3_cn = \u03b3_cr\u231d)%I as %gamma_cn_cr.\n      {\n\n        iDestruct \"r_is_locked\" as %r_is_locked.\n        iDestruct \"r_neq_d\" as %r_neq_d.\n        destruct r_is_locked as [ r_is_locked | r_not_locked].\n        destruct r_is_locked as [ r_is_r  gh_cn_cr ]. done.\n        destruct r_not_locked as [ r_is_d  gh_cn_cr ]. done.\n      }\n      subst \u03b3_cn.\n      \n      iAssert (\u231cCr = Cr1\u231d\u2217 \u231cVr = Vr1\u231d \u2217 \u231cTr = Tr1\u231d)%I as \"(%&%&%)\".\n      { iPoseProof (own_valid_2 _ _ _ with \"[$Half_r] [$HnP_frac]\") \n                as \"#HCr_equiv\".\n        iDestruct \"HCr_equiv\" as %HCr_equiv.\n        apply frac_agree_op_valid in HCr_equiv.\n        destruct HCr_equiv as [_ HCr_equiv].\n        apply leibniz_equiv_iff in HCr_equiv.\n        inversion HCr_equiv. iPureIntro. done. } subst Cr1 Vr1 Tr1.\n\n      iAssert (\u231ccir H1' Cr' Cd1\u231d)%I with \"[Hcir]\" as \"Hcir\".\n      { \n        iDestruct \"Hcir\" as %Hcir.\n        iPureIntro. \n        intros k' v' t'.\n        rewrite -> Htrans_union.\n        destruct (decide (k' = k)).\n        - subst k'. subst Cr'.\n          rewrite !lookup_insert.\n          split; try done. \n        - subst Cr'. \n          rewrite !lookup_insert_ne; try done.\n      }\n\n      (*\n      iAssert (\u231c(map_of_set H1) !!! k \u2264 T\u231d)%I as %H_le_T. \n      {\n        iPureIntro.\n        rewrite lookup_total_alt.\n        destruct ((map_of_set H1) !! k) eqn: hist_has_k.\n        - simpl.\n          unfold maxTS in MaxTS_H1.\n          destruct MaxTS_H1 as [MaxTS_H1 T_not_zero].\n          pose proof map_of_set_lookup_cases H1 k as H'.\n          destruct H' as [H' | [_ H']]; last first.\n          + rewrite H' in hist_has_k. inversion hist_has_k.\n          + destruct H' as [Tk [H' [_ H'']]].\n            rewrite H'' in hist_has_k. inversion hist_has_k.\n            subst Tk.\n            pose proof MaxTS_H1 k n H' as H'''.\n            clear -H'''; lia.\n        - simpl. lia.\n      }\n      *)\n\n      iAssert (\u231cHUnique H1'\u231d)%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')) \u2208 H1) \u2228 (k' = k \u2227 v' = v \u2227 t' = t1)) \n              as Hor by set_solver.\n        assert (((k', (v'', t')) \u2208 H1) \u2228 (k' = k \u2227 v'' = v \u2227 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 \"[Hcts_r]\" as \"Hcts_r\".\n      { iDestruct \"Hcts_r\" 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 \"HlockR_r\" as \"(Hlockr & _)\". wp_store.\n\n\n      (** Linearization **)    \n      iMod \"AU\" as (t' H1'')\"[MCS [_ Hclose]]\".\n      iAssert (\u231ct' = t1 \u2227 H1'' = H1\u231d)%I as \"(% & %)\". \n      { iPoseProof (MCS_agree with \"[$MCS_auth] [$MCS]\") as \"(% & %)\".\n        by iPureIntro. } subst t' H1''. \n      iDestruct \"MCS\" as \"(MCS\u25eft & MCS\u25efh & _)\".\n      iDestruct \"MCS_auth\" as \"(MCS\u25cft & MCS\u25cfh)\".\n      iMod ((auth_excl_update \u03b3_te (t1+1) t1 t1) with \"MCS\u25cft MCS\u25eft\") \n                                          as \"(MCS\u25cft & MCS\u25eft)\".\n      iMod ((auth_excl_update \u03b3_he (H1 \u222a {[(k, (v, t1))]}) H1 H1) with \"MCS\u25cfh MCS\u25efh\") \n                                          as \"(MCS\u25cfh & MCS\u25efh)\".\n      iCombine \"MCS\u25eft MCS\u25efh\" as \"(MCS_t & MCS_h)\".\n      iCombine \"MCS\u25cft MCS\u25cfh\" as \"MCS_auth\".\n      iMod (\"Hclose\" with \"[MCS_t MCS_h]\") as \"H\u03a6\".\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)) \u2208 H1') as H' by set_solver.\n        assert ((\u2200 (v' : V) (t' : nat), (k, (v', t')) \u2208 H1' \u2192 t' \u2264 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      (* Combine fractional ownerships of Cr. *)\n      iCombine \"HnP_frac Half_r\" as \"Half_r\".\n      iEval (rewrite <-frac_agree_op) in \"Half_r\".\n      iEval (rewrite Qp_half_half) in \"Half_r\".\n\n      (* Use combined ownerships to update Cr -> Cr'. *)\n      iMod ((own_update (\u03b3_cr) (to_frac_agree 1 (Cr, Vr, Tr))\n              (to_frac_agree 1 (Cr', Vr', Tr'))) with \"[$Half_r]\") \n              as \"Half_r\".\n      { apply cmra_update_exclusive.\n        unfold valid, cmra_valid. simpl. unfold prod_valid_instance.\n        split; simpl; try done. }\n\n      (* Break apart ownerships to be used separately. *)\n      iEval (rewrite <- Qp_half_half) in \"Half_r\".\n      iEval (rewrite frac_agree_op) in \"Half_r\".\n      iDestruct \"Half_r\" as \"(HnP_frac & Half_r)\".\n        \n      iModIntro. iFrame \"H\u03a6\".\n      iNext. iExists (t1+1), H1'. iFrame \"\u2217\".\n      iSplitR; first by iPureIntro.\n      iExists Cr', Vr', Tr', Cd1, Vd1, Td1. \n      iFrame \"Hcir\".\n      rewrite (big_sepS_delete _ (KS) k); last by eauto.\n      iFrame.\n      iSplitR \"HlockR_d\"; last first.\n      { by iExists bd. }\n      iExists false; iFrame.\n  Qed.\n  \nEnd multicopy_df_upsert.", "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_df_upsert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17695643930840244}}
{"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  subst id0. inv H1. destruct gd. destruct f0. \n  destruct (should_inline id f0).\n  rewrite PTree.gss in H0. rewrite ZMap.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  (* different *)\n  destruct gd. rewrite ZMap.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  exploit Genv.genv_symb_range; eauto. intros [A B]. unfold ZIndexed.t; omega.\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(** ** Soundness of the computed bounds over function resources *)\n\nRemark Pmax_l: forall x y, Ple x (Pmax x y).\nProof. intros; xomega. Qed.\n\nRemark Pmax_r: forall x y, Ple y (Pmax x y).\nProof. intros; xomega. Qed.\n\nLemma max_pc_function_sound:\n  forall f pc i, f.(fn_code)!pc = Some i -> Ple pc (max_pc_function f).\nProof.\n  intros until i. unfold max_pc_function. \n  apply PTree_Properties.fold_rec with (P := fun c m => c!pc = Some i -> Ple pc m).\n  (* extensionality *)\n  intros. apply H0. rewrite H; auto. \n  (* base case *)\n  rewrite PTree.gempty. congruence.\n  (* inductive case *)\n  intros. rewrite PTree.gsspec in H2. destruct (peq pc k). \n  inv H2. apply Pmax_r.\n  apply Ple_trans with a. auto. apply Pmax_l.\nQed.\n\nLemma max_def_function_instr:\n  forall f pc i, f.(fn_code)!pc = Some i -> Ple (max_def_instr i) (max_def_function f).\nProof.\n  intros. unfold max_def_function. eapply Ple_trans. 2: eapply Pmax_l. \n  revert H. \n  apply PTree_Properties.fold_rec with (P := fun c m => c!pc = Some i -> Ple (max_def_instr i) m).\n  (* extensionality *)\n  intros. apply H0. rewrite H; auto. \n  (* base case *)\n  rewrite PTree.gempty. congruence.\n  (* inductive case *)\n  intros. rewrite PTree.gsspec in H2. destruct (peq pc k). \n  inv H2. apply Pmax_r. \n  apply Ple_trans with a. auto. apply Pmax_l.\nQed.\n\nLemma max_def_function_params:\n  forall f r, In r f.(fn_params) -> Ple r (max_def_function f).\nProof.\n  assert (A: forall l m, Ple m (fold_left (fun m r => Pmax m r) l m)).\n    induction l; simpl; intros. \n    apply Ple_refl.\n    eapply Ple_trans. 2: eauto. apply Pmax_l.\n  assert (B: forall l m r, In r l -> Ple r (fold_left (fun m r => Pmax m r) l m)).\n    induction l; simpl; intros.\n    contradiction.\n    destruct H. subst a. eapply Ple_trans. 2: eapply A. apply Pmax_r. \n    eauto. \n  unfold max_def_function; intros. \n  eapply Ple_trans. 2: eapply Pmax_r. eauto. \nQed.\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\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  Ple pc s.(st_nextnode) \\/ Plt 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, Plt s.(st_nextnode) pc -> Ple 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  Ple 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  Ple 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  Ple 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  Ple 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  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. xomega.\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_def_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, Plt ctx.(dpc) pc -> Ple 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  Ple (max_def_instr instr) ctx.(mreg) ->\n  Ple (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', Plt s.(st_nextnode) pc' -> Ple 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_def_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. 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_def_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 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. subst 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, In (pc, instr) l -> Ple (max_def_instr instr) ctx.(mreg)) ->\n  (forall pc instr, In (pc, instr) l -> Ple (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', Plt s.(st_nextnode) pc' -> Ple 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: Ple (spc ctx pc) (st_nextnode s)) by eauto. unfold spc in B; 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 (Ple (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 (Ple (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. unfold spc in P. \n    assert (pc = pc0) by (unfold node; xomega). 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 Ple_trans; eauto. \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_def_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', Plt ctx.(dpc) pc' -> Ple 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_def_function_params; eauto. \n  intros. eapply iter_expand_instr_spec; eauto. \n    apply PTree.elements_keys_norepet. \n    intros. rewrite H1. eapply max_def_function_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    unfold spc. subst s0; simpl; xomega.\n  subst s0; simpl; auto.\n  intros. apply H8; auto. subst s0; simpl in H11; xomega.\n  intros. apply H8. unfold spc; xomega. \n    assert (Ple pc0 (max_pc_function f)).\n      eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.  \n    unfold spc. 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  Ple 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_def_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', Plt ctx.(dpc) pc' -> Ple 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_def_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": "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/Inliningspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17664657483014712}}
{"text": "From hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic DenseOrder Loc.\n\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_bob imm_s_ppo.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\n(* Require Import TraversalConfig. *)\nFrom imm Require Import TraversalOrder. \nFrom imm Require Import TLSCoherency.\nFrom imm Require Import IordCoherency.\nFrom imm Require Import SimClosure.\nRequire Import TlsEventSets.\nRequire Import Next. \nRequire Import EventsTraversalOrder.\n\n\nSet Implicit Arguments.\n\nSection ViewRelHelpers.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\nVariable IMMCON : imm_consistent G sc.\n\nNotation \"'co'\" := (co G).\nNotation \"'sw'\" := (sw G).\nNotation \"'hb'\" := (hb G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'lab'\" := (lab G).\nNotation \"'release'\" := (release G).\n\nNotation \"'Init'\" := (fun a => is_true (is_init a)).\nNotation \"'E'\" := (acts_set G).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_' l\" := (W \u2229\u2081 Loc_ l) (at level 1).\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 \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nContext\n  (T : trav_label -> Prop)\n  (TLSCOH  : tls_coherent G T)\n  (IORDCOH : iord_coherent G sc T). \n\nLemma msg_rel_co_irr l :\n  irreflexive (msg_rel G sc l \u2a3e co).\nProof using WF IMMCON.\n  unfold msg_rel.\n  intros x AA.\n  destruct AA as [y [[z [AA BB]] CC]].\n  eapply release_co_urr_irr; eauto.\n  1-4: by apply IMMCON.\n  eexists; split; [|eexists]; eauto.\nQed.\n\n\nLemma s_tm_cov_sc_fence\n      f ordf thread\n      (TID: tid f = thread)\n      (RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T)\n      (NEXT : next G (covered T) f)\n      (FPARAMS : lab f = Afence ordf)\n      (SC : Sc f) :\n  forall l,\n    S_tm G l (covered T \u222a\u2081 eq f) \u2261\u2081\n    S_tm G l (covered T) \u222a\u2081 t_acq G sc thread l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\n  cdes IMMCON.\n  intro l; split.\n  - unfold S_tm, t_acq.\n    rewrite s_tmr_union; relsf; unionL; splits; [basic_solver|].\n    unionR right.\n    rewrite (s_tmr_helper _ _ WF).\n    unfold c_acq, urr.\n    arewrite (sb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997covered T\u2998 \u2a3e sb \u2a3e \u2997eq f\u2998).\n      by revert NEXT; unfold next, dom_cond; basic_solver 21.\n    arewrite (\u2997covered T\u2998 \u2a3e sb \u2a3e \u2997eq f\u2998 \u2286 \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997covered T\u2998 \u2a3e sb^?).\n      by unfolder; ins; desf; splits; eauto using sb_tid_init.\n    basic_solver 42.\n  - unionL; [by unfold S_tm; rewrite s_tmr_union; basic_solver|].\n  unfold t_acq, S_tm.\n  rewrite s_tmr_union.\n  relsf.\n  unfold c_acq, urr.\n  rewrite (crE sc); relsf; unionL; splits.\n  { unionR right.\n    rewrite (s_tmr_helper _ _ WF).\n    arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997covered T\u2998 \u2286 \u2997dom_rel(sb \u2a3e \u2997eq f\u2998)\u2998).\n    { rewrite <- TID; rewrite next_helper'; eauto. basic_solver. }\n    arewrite (\u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997eq f\u2998) at 1 by type_solver.\n    basic_solver 42. }\n  arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997covered T\u2998 \u2286 \u2997covered T\u2998 \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998).\n  basic_solver.\n\n  arewrite ((release \u2a3e rf)^? \u2a3e \u2997covered T\u2998 \u2286 \u2997covered T\u2998 \u2a3e (release \u2a3e rf)^?).\n  { by case_refl _;\n      [basic_solver| rewrite !seqA; rewrite release_rf_covered; auto; basic_solver]. }\n  arewrite (hb^? \u2a3e \u2997covered T\u2998 \u2286 \u2997covered T\u2998 \u2a3e hb^?).\n  { by case_refl _; [basic_solver| rewrite hb_covered; auto; basic_solver]. }\n  arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e (hb \u2a3e \u2997F \u2229\u2081 Sc\u2998)^? \u2a3e sc \u2286 \u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e sc).\n  rewrite (dom_l (@wf_scD G sc Wf_sc)) at 1; rewrite (dom_r (wf_rfD WF)) at 1; hahn_frame_r; type_solver 42.\n\n  arewrite (sc \u2a3e \u2997covered T\u2998 \u2286 \u2997covered T\u2998 \u2a3e sc).\n  { now eapply sc_covered; eauto. }\n  unfold S_tmr; basic_solver 21.\nQed.\n\n\nLemma msg_rel_alt\n      (Wf_sc : wf_sc G sc)\n      w (WW : W w) (NCOV : ~ covered T w) (ISS : issuable G sc T w)\n      locw (LOC : loc lab w = Some locw) l:\n  dom_rel (msg_rel G sc l \u2a3e \u2997 eq w \u2998) \u2261\u2081\n  (if is_rel lab w\n   then t_cur G sc (tid w) l (covered T \u222a\u2081 eq w)\n   else t_rel G sc (tid w) l locw (covered T)) \u222a\u2081\n  dom_rel (msg_rel G sc l \u2a3e (rf \u2a3e rmw) \u2a3e \u2997 eq w \u2998).\nProof using WF TLSCOH IORDCOH IMMCON.\n  assert (E w) as EW.\n  { apply ISS. }\n  assert (~ is_init w) as WNIT.\n  { intros H. apply NCOV. eapply init_covered; vauto. }\n\n  assert (Rel w -> dom_rel (sb \u2a3e \u2997eq w\u2998) \u2261\u2081 (Tid_ (tid w) \u222a\u2081 Init) \u2229\u2081 covered T) as TT.\n  { intros REL. split.\n    { intros x [y H]. apply seq_eqv_r in H; desf.\n      split.\n      { by destruct (sb_tid_init H); [left|right]. }\n\n      eapply fwbob_issuable_in_C; eauto. eexists. apply seq_eqv_r. split; eauto.\n      apply sb_to_w_rel_in_fwbob. apply seq_eqv_r. split; vauto. }\n    intros x [TIDIN COV]. exists w.\n    apply seq_eqv_r; split; auto.\n    assert (E x) as EX by (eapply coveredE; eauto).\n    destruct TIDIN as [TID|INIT].\n    2: by eapply init_ninit_sb; eauto.\n    edestruct same_thread as [H|H].\n    3: by apply WNIT.\n    { apply ISS. }\n    { apply EX. }\n    1,3: done.\n    exfalso.\n    destruct H as [|H]; [by desf|].\n    apply NCOV.\n    eapply dom_sb_covered; eauto. eexists. apply seq_eqv_r. split; eauto. }\n  assert (Rel w -> dom_rel (sb \u2a3e \u2997eq w\u2998) \u2286\u2081 covered T) as TT'.\n  { intros H. rewrite (TT H). basic_solver. }\n\n  assert (~ Rel w ->\n          \u2997Rel\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998 \u2286\n          \u2997Rel\u2998 \u2a3e \u2997W_ locw \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid w) \u222a\u2081 Init\u2998 \u2a3e \u2997covered T\u2998 \u2a3e sb \u2a3e \u2997eq w\u2998) as QQ.\n  { intros HH.\n    arewrite (fwbob G \u2a3e \u2997eq w\u2998 \u2286 \u2997covered T\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998).\n    { intros x y H. apply seq_eqv_l; split; [|done].\n      apply seq_eqv_r in H. desc. subst. \n      eapply fwbob_issuable_in_C; eauto. eexists. apply seq_eqv_r. split; eauto. }\n    unfold fwbob; rewrite !seq_union_l. rewrite !seqA.\n    arewrite (\u2997W \u2229\u2081 Rel\u2998 \u2a3e \u2997eq w\u2998 \u2286 \u2205\u2082) by basic_solver.\n    arewrite (\u2997F \u2229\u2081 (fun a : actid => is_ra lab a)\u2998 \u2a3e \u2997eq w\u2998 \u2286 \u2205\u2082) by type_solver.\n    relsf; unionL.\n    - unfold same_loc; unfolder; ins; desf; splits; eauto.\n      by left; splits; congruence.\n      by apply (@sb_tid_init G).\n    - generalize (@sb_tid_init G).\n      basic_solver 21. }\n\n  unfold msg_rel at 1.\n  unfold imm_s_hb.release.\n  unfold imm_s_hb.rs.\n  rewrite rtE.\n  rewrite !seq_union_r. rewrite seq_union_l.\n  rewrite dom_union. apply set_equiv_union.\n  2: { apply dom_rel_more.\n       unfold msg_rel at 1. unfold imm_s_hb.release. unfold imm_s_hb.rs.\n       rewrite ct_end. basic_solver. }\n  rewrite seq_id_r.\n  unfold t_cur, t_rel.\n  split.\n  { rewrite !seqA.\n    arewrite (\u2997Rel\u2998 \u2a3e (\u2997F\u2998 \u2a3e sb)^? \u2a3e \u2997W\u2998 \u2a3e (sb \u2229 same_loc lab)^? \u2a3e \u2997W\u2998 \u2a3e \u2997eq w\u2998 \u2286\n              \u2997Rel\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998 \u222a \u2997Rel \u2229\u2081 eq w\u2998).\n    { case_refl _; case_refl _.\n      { basic_solver. }\n      all: unfold fwbob.\n      { basic_solver 42. }\n      all: arewrite (\u2997Rel\u2998 \u2a3e \u2997F\u2998 \u2286 \u2997Rel\u2998 \u2a3e \u2997F \u2229\u2081 (fun a => is_ra lab a)\u2998) by mode_solver.\n      2: arewrite (sb \u2a3e \u2997W\u2998 \u2a3e sb \u2229 same_loc lab \u2286 sb) by\n          (generalize (@sb_trans G); basic_solver).\n      all: basic_solver 42. }\n    rewrite seq_union_r.\n    desf.\n    { arewrite (Rel \u2229\u2081 eq w \u2261\u2081 eq w); [basic_solver|].\n      arewrite (urr G sc l \u2a3e \u2997Rel\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998 \u222a urr G sc l \u2a3e \u2997eq w\u2998 \u2286\n                urr G sc l \u2a3e \u2997eq w\u2998).\n      { rewrite union_absorb_l; [done|].\n        hahn_frame. etransitivity.\n        2: by apply urr_hb.\n        hahn_frame.\n        rewrite fwbob_in_bob. rewrite bob_in_sb.\n        rewrite sb_in_hb. basic_solver. }\n      rewrite urr_w_alt_union_eqv; auto.\n      apply dom_rel_mori.\n      arewrite (\u2997eq w\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997eq w\u2998) at 1 by basic_solver.\n      seq_rewrite (urr_w WF); relsf; unionL; [unionR left| basic_solver 12].\n      generalize (TT' Heq); basic_solver 21. }\n    arewrite (Rel \u2229\u2081 eq w \u2261\u2081 \u2205) by basic_solver.\n    rewrite <- dom_rel_ext with\n        (r := c_rel G sc (tid w) l locw (covered T))\n        (r' := (sb \u2a3e \u2997 eq w \u2998) ).\n    apply dom_rel_mori.\n    unfold c_rel.\n    rewrite crE. rewrite !seq_union_r. unionR right.\n    rewrite !seqA; rewrite QQ; [basic_solver 12| by rewrite Heq]. }\n  desf.\n  { rewrite urr_w_alt_union_eqv; auto.\n    relsf; unionL; splits; [|unfold urr; basic_solver 42].\n    rewrite crE at 1; relsf; unionL; splits.\n    - rewrite seq_eqvC; rewrite <- id_inter.\n      rewrite <- (TT Heq).\n      rewrite dom_rel_eqv_dom_rel.\n      apply dom_rel_mori.\n      rewrite !crE; relsf.\n      unionR left -> left. rewrite !seqA.\n      arewrite (\u2997eq w\u2998 \u2286 \u2997Rel\u2998 \u2a3e \u2997eq w\u2998) at 1 by basic_solver.\n      arewrite (\u2997eq w\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997eq w\u2998) at 1 by basic_solver.\n      hahn_frame. etransitivity;[|by apply urr_hb].\n      rewrite sb_in_hb. basic_solver.\n    - rewrite sb_in_hb at 1.\n      arewrite (hb \u2286 hb^?) at 1 .\n      arewrite_id \u2997covered T\u2998; rels.\n      sin_rewrite (@urr_hb G sc l).\n      basic_solver 21. }\n  unfold c_rel.\n  rewrite <- !id_inter.\n  intros x [y [z [HH [H'' JJ]]]]; subst.\n  exists w. apply seq_eqv_r; split; auto.\n  exists y; split; auto.\n  destruct JJ as [JJ1 [JJ2 [JJ3 JJ4]]].\n  assert (E y) as EY by (eapply coveredE; eauto). \n  assert (sb y w) as SBYW.\n  { destruct JJ3 as [TID|INIT].\n    2: by eapply init_ninit_sb; eauto.\n    edestruct same_thread as [H|H].\n    3: by apply WNIT.\n    { apply ISS. }\n    { apply EY. }\n    1,3: done.\n    exfalso.\n    destruct H as [|H]; [by desf|].\n    apply NCOV.\n    eapply dom_sb_covered; eauto. eexists. apply seq_eqv_r. split; eauto. }\n  apply seq_eqv_l; split; auto.\n  destruct JJ2.\n  { exists y; split; [by left|].\n    apply seq_eqv_l; split; [apply H|].\n    apply seq_eqv_r; split; auto.\n    right; split; auto. red. rewrite LOC; apply H. }\n  basic_solver 12.\nQed.\n\nLemma msg_rel_alt2\n      (Wf_sc : wf_sc G sc)\n      w (WW : W w) (NCOV : ~ covered T w) (ISS : issuable G sc T w)\n      locw (LOC : loc lab w = Some locw) l:\n  dom_rel (msg_rel G sc l \u2a3e \u2997 eq w \u2998) \u2261\u2081\n  (if is_rel lab w\n   then t_cur G sc (tid w) l (covered T)\n   else t_rel G sc (tid w) l locw (covered T)) \u222a\u2081\n  dom_rel (msg_rel G sc l \u2a3e (rf \u2a3e rmw) \u2a3e \u2997 eq w \u2998) \u222a\u2081\n  Rel \u2229\u2081 Loc_ l \u2229\u2081 eq w.\nProof using WF TLSCOH IORDCOH IMMCON.\n  rewrite msg_rel_alt; eauto.\n  desf.\n  2: by arewrite (Rel \u2229\u2081 Loc_ l \u2229\u2081 eq w \u2261\u2081 \u2205); basic_solver 10. \n  rewrite t_cur_urr_union_eqv_w; auto.\n  { arewrite (Rel \u2229\u2081 Loc_ l \u2229\u2081 eq w \u2261\u2081 Loc_ l \u2229\u2081 eq w).\n    2: by unfold t_cur, c_cur; basic_solver 10.\n    basic_solver 10. }\n  etransitivity; [| apply fwbob_issuable_in_C]; eauto. \n  generalize (@sb_to_w_rel_in_fwbob G) Heq. basic_solver 10. \nQed.\n\nLemma msg_rel_rfrmw_helper\n      w (WW : W w) (NCOV : ~ covered T w) (ISS : issuable G sc T w)\n      locw (LOC : loc lab w = Some locw) l:\n  dom_rel ((urr G sc l \u2a3e release) \u2a3e (rf \u2a3e rmw) \u2a3e \u2997eq w\u2998) \u2286\u2081\n  dom_rel (urr G sc l \u2a3e \u2997Rel\u2998 \u2a3e \u2997W_ locw \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid w) \u222a\u2081 Init\u2998 \u2a3e \u2997covered T\u2998)\n  \u222a\u2081 dom_rel ((urr G sc l \u2a3e release) \u2a3e (\u2997W_ex\u2998 \u2a3e rfi \u222a rfe) \u2a3e rmw \u2a3e \u2997eq w\u2998).\nProof using WF TLSCOH IMMCON.\nrewrite rfi_union_rfe; relsf; unionL; splits.\n2: basic_solver 12.\nunfold imm_s_hb.release.\nunfold imm_s_hb.rs.\nrewrite rtE; relsf.\nunionL; splits; cycle 1.\nrewrite rmw_W_ex at 1.\nrewrite <- !seqA.\nrewrite inclusion_ct_seq_eqv_r.\nunionR right -> left -> right; basic_solver 21.\nunionR left.\nrewrite !seqA.\narewrite ((sb \u2229 same_loc lab)^? \u2a3e \u2997W\u2998 \u2a3e rfi \u2a3e rmw \u2286 sb \u2229 same_loc lab).\n{ arewrite_id \u2997W\u2998; rewrite (rfi_in_sbloc' WF), (rmw_in_sb_loc WF).\n  generalize (@sb_same_loc_trans G); ins; relsf. }\narewrite (\u2997Rel\u2998 \u2a3e (\u2997F\u2998 \u2a3e sb)^? \u2a3e \u2997W\u2998 \u2a3e sb \u2229 same_loc lab \u2a3e \u2997eq w\u2998\n   \u2286 \u2997Rel\u2998 \u2a3e \u2997W_ locw \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid w) \u222a\u2081 Init\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998).\n{ \nrewrite crE at 1; relsf; unionL.\n- unfold fwbob.\nrewrite sb_tid_init' at 1.\nrewrite (init_pln WF) at 1.\nunfold same_tid.\nrelsf.\nunionR left -> left -> right.\nunfolder; ins; desf; splits; eauto 20.\nunfold same_loc in *; desf; eauto; left; splits; congruence.\nunfold same_loc in *; desf; eauto; left; splits; congruence.\nmode_solver 42.\n- \nrewrite !seqA.\narewrite (sb \u2a3e \u2997W\u2998 \u2a3e sb \u2229 same_loc lab \u2286 sb).\nby generalize (@sb_trans G); basic_solver.\narewrite (\u2997Rel\u2998 \u2a3e \u2997F\u2998 \u2a3e sb \u2a3e \u2997eq w\u2998 \u2286 \u2997Rel\u2998 \u2a3e \u2997F\u2998 \u2a3e \u2997Tid_ (tid w)\u2998 \u2a3e fwbob G \u2a3e \u2997eq w\u2998).\n{ unfold fwbob.\nrewrite sb_tid_init' at 1.\nrewrite (init_w WF).\nunfold same_tid.\nmode_solver 21. }\nbasic_solver.\n\n}\n\narewrite (\u2997eq w\u2998 \u2286 \u2997dom_cond (fwbob G) (covered T)\u2998).\n{ apply eqv_rel_mori. apply set_subset_eq.\n  eapply AuxDef.dom_rel_to_cond; eauto. apply fwbob_issuable_in_C; auto. }\nrewrite dom_cond_elim.\nbasic_solver 12.\nQed.\n\nLemma t_rel_msg_rel_rfrmw\n      w (WW : W w) (NCOV : ~ covered T w) (ISS : issuable G sc T w)\n      locw (LOC : loc lab w = Some locw) l:\n  t_rel G sc (tid w) l locw (covered T) \u222a\u2081 dom_rel (msg_rel G sc l \u2a3e (rf \u2a3e rmw) \u2a3e \u2997eq w\u2998) \u2261\u2081\n  t_rel G sc (tid w) l locw (covered T) \u222a\u2081\n  dom_rel (msg_rel G sc l \u2a3e (\u2997 W_ex \u2998 \u2a3e rfi \u222a rfe) \u2a3e rmw \u2a3e \u2997eq w\u2998).\nProof using WF TLSCOH IMMCON.\nins; split; unionL; desf.\n1,3: basic_solver.\n2: rewrite rfi_union_rfe; basic_solver 12.\nunfold t_rel, c_rel, msg_rel.\nby apply msg_rel_rfrmw_helper.\nQed.\n\nLemma t_cur_msg_rel_rfrmw\n      w (WW : W w) (NCOV : ~ covered T w) (ISS : issuable G sc T w) l:\n  t_cur G sc (tid w) l (covered T) \u222a\u2081 dom_rel (msg_rel G sc l \u2a3e (rf \u2a3e rmw) \u2a3e \u2997eq w\u2998) \u2261\u2081\n  t_cur G sc (tid w) l (covered T) \u222a\u2081\n  dom_rel (msg_rel G sc l \u2a3e (\u2997 W_ex \u2998 \u2a3e rfi \u222a rfe) \u2a3e rmw \u2a3e \u2997eq w\u2998).\nProof using WF TLSCOH IMMCON.\nins; split; unionL; desf.\n1,3: basic_solver.\n2: rewrite rfi_union_rfe; basic_solver 12.\nunfold t_cur, c_cur, msg_rel.\nassert (exists locw, loc lab w = Some locw).\nby unfold loc, is_w in *; destruct (lab w); eauto.\ndesc.\nrewrite msg_rel_rfrmw_helper; try edone.\nbasic_solver 21.\nQed.\n\nLemma t_cur_n_sc_fence_step\n      (Wf_sc : wf_sc G sc)\n      f (FENCE : F f) (NSC : ~ Sc f) (NEXT : next G (covered T) f)\n      (RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T):\n  forall l,\n    t_cur G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    if is_acq lab f\n    then t_acq G sc (tid f) l (covered T)\n    else t_cur G sc (tid f) l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\nins; split; rewrite t_cur_union; unionL; desf.\nby apply t_cur_in_t_acq.\n4: basic_solver.\nall: unfold t_cur, t_acq, c_cur, c_acq.\n- arewrite (\u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998) by basic_solver.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F \u2229\u2081 set_compl Sc \u2998 \u2a3e \u2997eq f\u2998) by basic_solver.\n  sin_rewrite (urr_f_non_sc WF); auto.\n  rewrite next_helper'; basic_solver 21.\n- arewrite (\u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998) by basic_solver.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081set_compl Acq \u2998 \u2a3e \u2997eq f\u2998) by basic_solver.\n  sin_rewrite (urr_f_non_acq WF); auto.\n  rewrite next_helper'; basic_solver 21.\n- rewrite crE at 1; relsf; unionL; splits; [basic_solver 12|].\n  unionR right.\n  rewrite next_helper'; eauto.\n  rewrite <- !seqA.\n  rewrite !dom_rel_eqv_dom_rel.\n  rewrite !seqA.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by basic_solver.\n  arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n  unfold imm_s_hb.sw; basic_solver 16.\n  arewrite (sw \u2286 hb^?).\n  sin_rewrite urr_hb.\n  basic_solver 21.\nQed.\n\nLemma t_acq_n_sc_fence_step\n      (Wf_sc : wf_sc G sc)\n      f (FENCE : F f) (NSC : ~ Sc f) (NEXT : next G (covered T) f):\n  forall l,\n    t_acq G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    t_acq G sc (tid f) l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\nins; split; rewrite t_acq_union; unionL; splits; desf; [|basic_solver].\nunfold t_acq, c_acq.\narewrite (\u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998) by basic_solver.\nrewrite next_helper'; eauto.\nrewrite <- !seqA.\nrewrite !dom_rel_eqv_dom_rel.\nrewrite !seqA.\nrewrite (dom_r (wf_rfD WF)) at 1.\nrewrite crE at 1; relsf; unionL; splits; [|type_solver].\narewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081set_compl Sc \u2998 \u2a3e \u2997eq f\u2998) at 1 by basic_solver.\nsin_rewrite (urr_f_non_sc WF); auto.\nbasic_solver 21.\nQed.\n\nLemma t_rel_n_sc_fence_step\n      (Wf_sc : wf_sc G sc)\n      f (FENCE : F f) (NSC : ~ Sc f) (NEXT : next G (covered T) f):\n  forall l l',\n    t_rel G sc (tid f) l l' (covered T \u222a\u2081 eq f) \u222a\u2081\n    (if LocSet.Facts.eq_dec l l'\n     then W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ (tid f) \u2229\u2081 (covered T \u222a\u2081 eq f)\n     else \u2205) \u2261\u2081\n    if is_acqrel lab f\n    then t_acq G sc (tid f) l (covered T)\n    else\n      if is_rel lab f\n      then t_cur G sc (tid f) l (covered T)\n      else\n        t_rel G sc (tid f) l l' (covered T) \u222a\u2081\n        (if LocSet.Facts.eq_dec l l'\n         then W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ (tid f) \u2229\u2081 (covered T)\n         else \u2205).\nProof using WF TLSCOH IORDCOH IMMCON.\nins; split; try rewrite t_rel_union; unionL; desf.\nby apply t_rel_in_t_acq.\nby apply t_rel_in_t_cur.\nall: try rewrite set_inter_union_r.\nall: unionL.\nall: try  basic_solver 8.\nall: try type_solver.\n5: unfold t_acq, c_acq, urr; basic_solver 42.\n5: unfold t_cur, c_cur, urr; basic_solver 42.\nall: try rewrite set_union_empty_r.\nall: unfold t_rel, c_rel, t_acq, c_acq, t_cur, c_cur.\nall: rewrite next_helper'; eauto.\nall: rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n- arewrite ( \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F\u2229\u2081set_compl Sc\u2998 \u2a3e \u2997eq f\u2998).\n  type_solver.\n  sin_rewrite (urr_f_non_sc WF); auto.\n  basic_solver 21.\n- arewrite ( \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F\u2229\u2081set_compl Acq\u2998 \u2a3e \u2997eq f\u2998).\n  mode_solver.\n  sin_rewrite (urr_f_non_acq WF); auto.\n  basic_solver 21.\n- arewrite ( \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F\u2229\u2081set_compl Acq\u2998 \u2a3e \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997eq f\u2998).\n  mode_solver.\n  sin_rewrite (urr_f_non_acq WF); auto.\n  basic_solver 21.\n- arewrite ( \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F\u2229\u2081set_compl Acq\u2998 \u2a3e \u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997eq f\u2998).\n  mode_solver.\n  sin_rewrite (urr_f_non_acq WF); auto.\n  basic_solver 21.\n- arewrite ((release \u2a3e rf)^? \u2a3e sb \u2a3e \u2997eq f\u2998 \u2286 hb^? \u2a3e \u2997eq f\u2998) at 1.\n  { rewrite crE at 1; relsf; unionL.\n    arewrite (sb \u2286 hb^?) at 1; basic_solver.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n    arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n    unfold imm_s_hb.sw; basic_solver 16.\n    arewrite (sw \u2286 hb^?); basic_solver. }\n  sin_rewrite urr_hb.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Rel \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n  basic_solver 21.\n- arewrite ((release \u2a3e rf)^? \u2a3e sb \u2a3e \u2997eq f\u2998 \u2286 hb^? \u2a3e \u2997eq f\u2998) at 1.\n  { rewrite crE at 1; relsf; unionL.\n    arewrite (sb \u2286 hb^?) at 1; basic_solver.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n    arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n    unfold imm_s_hb.sw; basic_solver 16.\n    arewrite (sw \u2286 hb^?); basic_solver. }\n  sin_rewrite urr_hb.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Rel \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n  basic_solver 21.\n- arewrite (sb \u2286 hb^?) at 1.\n  sin_rewrite urr_hb.\n  basic_solver 21.\n- arewrite (sb \u2286 hb^?) at 1.\n  sin_rewrite urr_hb.\n  basic_solver 21.\nQed.\n\nLemma sc_helper' (Wf_sc : wf_sc G sc)\n f (FENCE : F f) (SC : Sc f) (COV : coverable G sc T f) (NCOV : ~ covered T f) :\n \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997covered T\u2998 \u2261 \u2997dom_rel (sc \u2a3e \u2997eq f\u2998)\u2998.\nProof using WF TLSCOH IORDCOH IMMCON.\nsplit. \n- unfold coverable, dom_cond in *.\n  unfolder in *; desf; try type_solver. \n  ins; desf; splits; eauto.\n  eexists; splits; eauto.\n  eapply tot_ex.\n  * apply Wf_sc.\n  * basic_solver.\n  * generalize coveredE; basic_solver.\n  * intro; apply NCOV. eapply dom_sc_covered; vauto.\n  * intro; subst; eauto.\n- rewrite <- !id_inter. apply eqv_rel_mori. apply set_subset_inter_r. split.\n  { rewrite (wf_scD Wf_sc). basic_solver. } \n  rewrite <- dom_sc_coverable; eauto. basic_solver.  \nQed.\n\nLemma coverable_next_covered e\n      (COV: coverable G sc T e)\n      (NCOV : ~ covered T e):\n  next G (covered T) e. \nProof using TLSCOH. \n  red. split; auto. split; [apply COV| ].\n  red. erewrite <- dom_sb_coverable; eauto.\n  basic_solver. \nQed. \n\nLemma t_cur_sc_fence_step \n      (RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T)\n      f (FENCE : F f) (SC: Sc f) \n      (COV : coverable G sc T f) (NCOV : ~ covered T f) :\n  forall l,\n    t_cur G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    S_tm G l (covered T) \u222a\u2081 t_acq G sc (tid f) l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\n  cdes IMMCON.\nins; split; try rewrite t_cur_union; unionL; desf.\nby rewrite t_cur_in_t_acq; basic_solver.\nall: unfold t_cur, c_cur, S_tm, S_tmr, t_acq, c_acq, t_rel, c_rel.\n- arewrite (\u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998).\n  basic_solver.\n  sin_rewrite (urr_f_sc WF); auto.\n  rewrite !seqA.\n  arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e (hb \u2a3e \u2997F \u2229\u2081 Sc\u2998)^? \u2a3e sc^? \u2a3e \u2997eq f\u2998 \u2286 \u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e sc^? \u2a3e \u2997eq f\u2998).\n  { rewrite (dom_r (wf_rfD WF)) at 1.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998) at 1 by basic_solver.\n    rewrite (dom_l (wf_scD Wf_sc)) at 1.\n    hahn_frame_r; unfolder; ins; desf; eauto 20; type_solver. }\n  rewrite (crE sc); relsf.\n  rewrite <- !dom_eqv1.\n  unionL; splits.\n  * arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997eq f\u2998 \u2286 S_tmr G l (eq f)).\n    rewrite (s_tmr_helper l (eq f) WF).\n    rewrite next_helper'; eauto using coverable_next_covered.\n    rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n    unfold urr.\n    unionR right; basic_solver 42.\n  * unfold urr.\n    rewrite (sc_helper' Wf_sc FENCE); auto.\n    basic_solver 21.\n- unfold urr.\n  rewrite (sc_helper' Wf_sc FENCE); auto.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  rewrite (dom_l (wf_scD Wf_sc)) at 1.\n  unionR right; basic_solver 21.\n- rewrite crE at 1; relsf; unionL; splits; [basic_solver 12|].\n  unionR right.\n  rewrite next_helper'; eauto using coverable_next_covered.\n  rewrite <- !seqA.\n  rewrite !dom_rel_eqv_dom_rel.\n  rewrite !seqA.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n  arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n  unfold imm_s_hb.sw; basic_solver 16.\n  arewrite (sw \u2286 hb^?).\n  sin_rewrite urr_hb.\n  basic_solver 21.\nQed.\n\nLemma t_acq_sc_fence_step\n      f (FENCE : F f) (SC: Sc f) (COV : coverable G sc T f) (NCOV : ~ covered T f):\n  forall l,\n    t_acq G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    t_acq G sc (tid f) l (covered T) \u222a\u2081\n    S_tm G l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\n  cdes IMMCON.\nins; split; try rewrite t_acq_union; unionL; desf.\n1,3: basic_solver.\nall: unfold t_cur, c_cur, S_tm, S_tmr, t_acq, c_acq, t_rel, c_rel.\n- arewrite (\u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998).\n  basic_solver.\n  arewrite ((release \u2a3e rf)^? \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998).\n  rewrite (dom_r (wf_rfD WF)) at 1; type_solver.\n  sin_rewrite (urr_f_sc WF); auto.\n  rewrite !seqA.\n  arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e (hb \u2a3e \u2997F \u2229\u2081 Sc\u2998)^? \u2a3e sc^? \u2a3e \u2997eq f\u2998 \u2286 \u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e sc^? \u2a3e \u2997eq f\u2998).\n  { rewrite (dom_r (wf_rfD WF)) at 1.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998) at 1 by basic_solver.\n    rewrite (dom_l (wf_scD Wf_sc)) at 1.\n    hahn_frame_r; unfolder; ins; desf; eauto 20; type_solver. }\n  rewrite (crE sc); relsf; rewrite <- !dom_eqv1; unionL; splits.\n  * arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997eq f\u2998 \u2286 S_tmr G l (eq f)).\n    rewrite (s_tmr_helper l (eq f) WF).\n    rewrite next_helper'; eauto using coverable_next_covered.\n    rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n    unfold urr.\n    unionR left; basic_solver 42.\n  * unfold urr.\n    rewrite (sc_helper' Wf_sc FENCE); auto.\n    basic_solver 21.\n- unfold urr.\n  rewrite (sc_helper' Wf_sc FENCE); auto.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  rewrite (dom_l (wf_scD Wf_sc)) at 1.\n  unionR right; basic_solver 42.\nQed.\n\nLemma t_rel_sc_fence_step\n      f (FENCE : F f) (SC: Sc f) (COV : coverable G sc T f) (NCOV : ~ covered T f) :\n  forall l l',\n    t_rel G sc (tid f) l l' (covered T \u222a\u2081 eq f) \u222a\u2081\n    (if LocSet.Facts.eq_dec l l'\n     then W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ (tid f) \u2229\u2081 (covered T \u222a\u2081 eq f)\n     else \u2205) \u2261\u2081\n     S_tm G l (covered T) \u222a\u2081 t_acq G sc (tid f) l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\n  cdes IMMCON.\nins; split; try rewrite t_rel_union; unionL; desf.\nby rewrite t_rel_in_t_acq; basic_solver.\nall: unfold t_cur, c_cur, S_tm, S_tmr, t_acq, c_acq, t_rel, c_rel.\n2: by unfold urr; type_solver 42.\n- arewrite (\u2997Rel\u2998 \u2a3e \u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998 \u2a3e \u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998 \u2a3e \u2997Tid_ (tid f) \u222a\u2081 Init\u2998).\n  basic_solver.\n  sin_rewrite (urr_f_sc WF); auto.\n  rewrite !seqA.\n  arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e (hb \u2a3e \u2997F \u2229\u2081 Sc\u2998)^? \u2a3e sc^? \u2a3e \u2997eq f\u2998 \u2286 \u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e sc^? \u2a3e \u2997eq f\u2998).\n  { rewrite (dom_r (wf_rfD WF)) at 1.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997F \u2229\u2081 Sc\u2998 \u2a3e  \u2997eq f\u2998) at 1 by basic_solver.\n    rewrite (dom_l (wf_scD Wf_sc)) at 1.\n    hahn_frame_r; unfolder; ins; desf; eauto 20; type_solver. }\n  rewrite (crE sc); relsf; rewrite <- !dom_eqv1; unionL; splits.\n  * arewrite (\u2997W_ l\u2998 \u2a3e rf^? \u2a3e hb \u2a3e \u2997F \u2229\u2081 Sc\u2998 \u2a3e \u2997eq f\u2998 \u2286 S_tmr G l (eq f)).\n    rewrite (s_tmr_helper l (eq f) WF).\n    rewrite next_helper'; eauto using coverable_next_covered.\n    rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n    unfold urr.\n    unionR right; basic_solver 42.\n  * unfold urr.\n    rewrite (sc_helper' Wf_sc FENCE); auto.\n    basic_solver 21.\n- unfold urr.\n  rewrite (sc_helper' Wf_sc FENCE); auto.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  rewrite (dom_l (wf_scD Wf_sc)) at 1.\n  assert (Rel f) by mode_solver.\n  unionR left -> right; basic_solver 42.\n- unfold urr.\n  rewrite (sc_helper' Wf_sc FENCE); auto.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  rewrite (dom_l (wf_scD Wf_sc)) at 1.\n  assert (Rel f) by mode_solver.\n  unionR left -> right; basic_solver 42.\n- rewrite next_helper'; eauto using coverable_next_covered.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  arewrite ((release \u2a3e rf)^? \u2a3e sb \u2a3e \u2997eq f\u2998 \u2286 hb^? \u2a3e \u2997eq f\u2998) at 1.\n  { rewrite crE at 1; relsf; unionL.\n    arewrite (sb \u2286 hb^?) at 1; basic_solver.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n    arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n    unfold imm_s_hb.sw; basic_solver 16.\n    arewrite (sw \u2286 hb^?); basic_solver. }\n  sin_rewrite urr_hb.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Rel \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n  basic_solver 21.\n- rewrite next_helper'; eauto using coverable_next_covered.\n  rewrite <- !seqA, dom_rel_eqv_dom_rel, !seqA.\n  arewrite ((release \u2a3e rf)^? \u2a3e sb \u2a3e \u2997eq f\u2998 \u2286 hb^? \u2a3e \u2997eq f\u2998) at 1.\n  { rewrite crE at 1; relsf; unionL.\n    arewrite (sb \u2286 hb^?) at 1; basic_solver.\n    arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Acq \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n    arewrite (release \u2a3e rf \u2a3e sb \u2a3e \u2997F \u2229\u2081 Acq\u2998 \u2286 sw).\n    unfold imm_s_hb.sw; basic_solver 16.\n    arewrite (sw \u2286 hb^?); basic_solver. }\n  sin_rewrite urr_hb.\n  arewrite (\u2997eq f\u2998 \u2286 \u2997 F\u2229\u2081 Rel \u2998 \u2a3e \u2997eq f\u2998) at 1 by mode_solver.\n  basic_solver 21.\nQed.\n\n\n\nLemma t_cur_fence_step\n      (RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T)\n      f (FENCE : F f) (COV : coverable G sc T f) (NCOV : ~ covered T f):\n  forall l,\n    t_cur G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    if is_sc lab f\n    then S_tm G l (covered T) \u222a\u2081 t_acq G sc (tid f) l (covered T)\n    else\n      if is_acq lab f\n      then t_acq G sc (tid f) l (covered T)\n      else t_cur G sc (tid f) l (covered T).\nProof using WF TLSCOH IORDCOH IMMCON.\n  destruct (is_sc lab f) eqn: H.\n  apply t_cur_sc_fence_step; auto.\n  apply t_cur_n_sc_fence_step; auto.\n  by apply IMMCON.\n  by ins; desf.\n  apply coverable_next_covered; auto.\nQed.\n\nLemma t_acq_fence_step\n      f (FENCE : F f) (COV : coverable G sc T f) (NCOV : ~ covered T f):\n  forall l,\n    t_acq G sc (tid f) l (covered T \u222a\u2081 eq f) \u2261\u2081\n    t_acq G sc (tid f) l (covered T) \u222a\u2081\n    if is_sc lab f\n    then S_tm G l (covered T)\n    else \u2205.\nProof using WF TLSCOH IORDCOH IMMCON.\n  destruct (is_sc lab f) eqn: H.\n  apply t_acq_sc_fence_step; auto.\n  ins; rewrite set_union_empty_r; apply t_acq_n_sc_fence_step; auto.\n  by apply IMMCON.\n  by ins; desf.\n  apply coverable_next_covered; auto.\nQed.\n\nLemma t_rel_fence_step\n      f (FENCE : F f) (COV : coverable G sc T f) (NCOV : ~ covered T f) :\n  forall l l',\n    t_rel G sc (tid f) l l' (covered T \u222a\u2081 eq f) \u222a\u2081\n    (if LocSet.Facts.eq_dec l l'\n     then W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ (tid f) \u2229\u2081 (covered T \u222a\u2081 eq f)\n     else \u2205) \u2261\u2081\n    if is_sc lab f\n    then S_tm G l (covered T) \u222a\u2081 t_acq G sc (tid f) l (covered T)\n    else \n      if is_acqrel lab f\n      then t_acq G sc (tid f) l (covered T)\n      else\n        if is_rel lab f\n        then t_cur G sc (tid f) l (covered T)\n        else\n          (t_rel G sc (tid f) l l' (covered T) \u222a\u2081\n           (if LocSet.Facts.eq_dec l l'\n            then W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ (tid f) \u2229\u2081 (covered T)\n            else \u2205)).\nProof using WF TLSCOH IORDCOH IMMCON.\n  destruct (is_sc lab f) eqn: H.\n  apply t_rel_sc_fence_step; auto.\n  apply t_rel_n_sc_fence_step; auto.\n  by apply IMMCON.\n  by ins; desf.\n  apply coverable_next_covered; auto. \nQed.\n\nEnd ViewRelHelpers.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/travorder/TlsViewRelHelpers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.17664656410358306}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.msl.iter_sepcon.\nRequire Import malloc.\nRequire Import ASI_malloc.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\nRequire Import VSU_malloc_definitions.\nLocal Open Scope logic.\n(*\nDefinition Gprog : funspecs := user_specs_R ++ private_specs.\n*)\nLemma body_pre_fill i: semax_body MF_Vprog MF_Gprog f_pre_fill (pre_fill_spec' R_APD i).\nProof. \nstart_function. \nrewrite <- seq_assoc.  \nforward_call n. (*! b = size2bin(n) *)\ndestruct H as [[Hn_lo Hn_hi] Hp].\ntry rep_lia.\nforward.\nset (b:=size2binZ n). \nassert (Hb: 0 <= b < BINS) by (apply size2bin_range; rep_lia).\nforward_call b. (*! t2 = bin2size(b) *)\nsimpl. rewrite (mem_mgr_split_R gv b rvec) by apply Hb.\nIntros bins idxs lens.\nfreeze [1; 3] Otherlists.\ndeadvars!.\ntry destruct H as [[Hn_lo Hn_hi] Hp].\nforward. (*! t4 = bin[b] *)\nforward_call ((bin2sizeZ b), p, (Znth b bins), (Znth b lens), b). (*! t3 = list_from_block(t2,p,t4) *)\nIntros q.\nforward. (*! bin[b] = t3 *)\nthaw Otherlists.\n\n(* fold lists into mem_mgr_R *)\nreplace (size2binZ (bin2sizeZ b)) with b \n  by (subst b; rewrite claim3; try rep_lia).\nsimpl ASI_malloc.mem_mgr_R; unfold mem_mgr_R.\nset (bins':= upd_Znth b bins q).\nset (lens':= map Z.to_nat (add_resvec rvec b (chunks_from_block b))).\nassert (Hrveclen: Zlength rvec = BINS) by\n   ( subst lens; rewrite Zlength_map in H0; rep_lia). \nExists bins'. Exists idxs. Exists lens'.\nentailer!.\n{ split. unfold lens'. rewrite Zlength_map. rewrite Zlength_add_resvec; assumption.\n  apply add_resvec_no_neg; try assumption.\n  pose proof (chunks_from_block_nonneg (size2binZ n)).\n  assert (0 <= Znth (size2binZ n) rvec)\n    by (apply Forall_Znth; try rep_lia; try unfold no_neg in *; auto).\n  rep_lia.\n}\nset (idxs:= (map Z.of_nat (seq 0 (Z.to_nat BINS)))).\nset (lens:= (map Z.to_nat rvec)).\nassert (Zlength lens = BINS) by (unfold lens; rewrite Zlength_map; rep_lia).\nassert (Zlength idxs = BINS) by auto.\nrepeat (rewrite sublist_zip3; try rep_lia).  \nreplace (sublist 0 b bins) with (sublist 0 b bins') \n  by (unfold bins'; rewrite sublist_upd_Znth_l; try reflexivity; try rep_lia).\nreplace (sublist (b+1) BINS bins) with (sublist (b+1) BINS bins') \n  by (unfold bins'; rewrite sublist_upd_Znth_r; try reflexivity; try rep_lia).\nreplace (sublist 0 b lens) with (sublist 0 b lens').\n2: { unfold lens'. unfold lens.  do 2 rewrite sublist_map. f_equal.\n     unfold add_resvec. simple_if_tac''; auto.\n     rewrite sublist_upd_Znth_l; try rep_lia; reflexivity. }\nreplace (sublist (b + 1) BINS lens) with (sublist (b + 1) BINS lens').\n2: { unfold lens'. unfold lens.  do 2 rewrite sublist_map. f_equal. \n     unfold add_resvec. simple_if_tac''; auto.\n     rewrite sublist_upd_Znth_r; try rep_lia; reflexivity. }\nassert (Zlength bins' = BINS) by auto.\nassert (Zlength lens' = BINS) \n  by (unfold lens'; rewrite Zlength_map; rewrite Zlength_add_resvec; auto).\nrepeat (rewrite <- sublist_zip3; try rep_lia); try rep_lia.  \nreplace (Z.to_nat (chunks_from_block b) + Znth b lens)%nat with (Znth b lens').\n2: {unfold lens'.  rewrite Znth_map.\n    unfold add_resvec. simple_if_tac' Hcond.\n    2: { assert (Zlength rvec = BINS) by auto. \n         bdestruct(Zlength rvec =? BINS); simpl in Hcond; try contradiction.\n         bdestruct(0 <=? b); simpl in Hcond; try contradiction.\n         bdestruct(b<?BINS); simpl in Hcond; try contradiction.\n         discriminate.\n         rep_lia. \n         destruct Hb; contradiction.\n    }\n    rewrite upd_Znth_same; try rep_lia.\n    replace (Znth b lens) with (Z.to_nat (Znth b rvec)) \n      by (unfold lens; rewrite Znth_map; rep_lia).\n    rewrite <- Z2Nat.inj_add. f_equal. rep_lia.\n    apply chunks_from_block_nonneg.\n    apply Forall_Znth; try rep_lia; try unfold no_neg in *; auto.\n    rewrite Zlength_add_resvec; rep_lia.\n}\nreplace \n (mmlist (bin2sizeZ b) (Znth b lens') q nullval * TT *\n  iter_sepcon mmlist' (sublist 0 b (zip3 lens' bins' idxs)) *\n  iter_sepcon mmlist' (sublist (b + 1) BINS (zip3 lens' bins' idxs)) * TT)\nwith \n (iter_sepcon mmlist' (sublist 0 b (zip3 lens' bins' idxs)) *\n  iter_sepcon mmlist' (sublist (b + 1) BINS (zip3 lens' bins' idxs)) * \n  mmlist (bin2sizeZ b) (Znth b lens') q nullval * TT)\nby (apply pred_ext; entailer!).\nreplace q with (Znth b bins').\n2: (unfold bins'; rewrite upd_Znth_same; auto; rep_lia).\nrewrite mem_mgr_split'; try entailer!; auto.\nQed.\n(*\nDefinition module := [mk_body body_pre_fill].\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_pre_fill.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17660772094656704}}
{"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: automatic translation of a CompCert Clight floating-point\nexpression into a real-number expression with all rounding error terms\nand their correctness proofs.\n**)\n\nRequire Import Lia.\nFrom vcfloat Require Export FPCore. (* FPLang Rounding FPLangOpt.*)\nRequire compcert.common.AST compcert.common.Values.\nRequire Import compcert.lib.Floats.\nImport Binary BinPos.\n\nInductive val_inject: Values.val -> forall ty, ftype ty -> Prop :=\n| val_inject_single (f: ftype Tsingle):\n    val_inject (Values.Vsingle f) Tsingle f\n| val_inject_double f:\n    val_inject (Values.Vfloat f) Tdouble f\n.\n\nLemma val_inject_single_inv (f1: float32) (f2: ftype Tsingle):\n  val_inject (Values.Vsingle f1) Tsingle f2 ->\n  f1 = f2.\nProof.\n  inversion 1; subst.\n  revert H2.\n  apply Eqdep_dec.inj_pair2_eq_dec; auto.\n  apply type_eq_dec.\nQed.\n\nLemma val_inject_double_inv f1 f2:\n  val_inject (Values.Vfloat f1) Tdouble f2 ->\n  f1 = f2.\nProof.\n  inversion 1; subst.\n  revert H2.\n  apply Eqdep_dec.inj_pair2_eq_dec; auto.\n  apply type_eq_dec.\nQed.\n\nDefinition val_injectb v ty (f: ftype ty): bool :=\n  match v with\n    | Values.Vsingle f' =>\n      type_eqb Tsingle ty && binary_float_eqb f' f\n    | Values.Vfloat f' =>\n      type_eqb Tdouble ty && binary_float_eqb f' f\n    | _ => false\n  end.\n\nLemma val_injectb_inject v ty f:\n  val_injectb v ty f = true <-> val_inject v ty f.\nProof.\n  unfold val_injectb.\n  destruct v;\n  (try (split; (try congruence); inversion 1; fail));\n  rewrite Bool.andb_true_iff.\n  {\n    destruct (type_eqb Tdouble ty) eqn:EQ.\n    {\n      rewrite type_eqb_eq in EQ.\n      subst.\n      rewrite binary_float_eqb_eq.\n      split.\n      {\n        destruct 1; subst.\n        constructor.\n      }\n      intros; eauto using val_inject_double_inv.\n    }\n    split; try intuition congruence.\n    inversion 1; subst.\n    apply type_eqb_eq in H3.\n    congruence.\n  }\n  destruct (type_eqb Tsingle ty) eqn:EQ.\n  {\n    rewrite type_eqb_eq in EQ.\n    subst.\n    rewrite binary_float_eqb_eq.\n    split.\n    {\n      destruct 1; subst.\n      constructor.\n    }\n    intros; eauto using val_inject_single_inv.\n  }\n  split; try intuition congruence.\n  inversion 1; subst.\n  apply type_eqb_eq in H3.\n  congruence.  \nQed.\n\nLemma conv_nan_ex:\n  { conv_nan: forall ty1 ty2,\n                binary_float (fprec ty1) (femax ty1) -> (* guaranteed to be a nan, if this is not a nan then any result will do *)\n                nan_payload (fprec ty2) (femax ty2)\n  |\n  conv_nan Tsingle Tdouble = Floats.Float.of_single_nan\n  /\\\n  conv_nan Tdouble Tsingle = Floats.Float.to_single_nan\n  }.\nProof.\n  eapply exist.\n  Unshelve.\n  {\n    shelve.\n  }\n  intros ty1 ty2.\n  destruct (type_eq_dec ty1 Tsingle).\n  {\n    subst.\n    destruct (type_eq_dec ty2 Tdouble).\n    {\n      subst.\n      exact Floats.Float.of_single_nan.\n    }\n    auto using any_nan.\n  }\n  destruct (type_eq_dec ty1 Tdouble).\n  {\n    subst.\n    destruct (type_eq_dec ty2 Tsingle).\n    {\n      subst.\n      exact Floats.Float.to_single_nan.\n    }\n    intros.\n    auto using any_nan.\n  }\n  intros.\n  auto using any_nan.\n  Unshelve.\n  split; reflexivity.\nDefined.\n\nDefinition conv_nan := let (c, _) := conv_nan_ex in c.\n\nLemma single_double_ex (U: _ -> Type):\n  (forall ty, U ty) ->\n  forall s: U Tsingle,\n  forall d: U Tdouble,\n    {\n      f: forall ty, U ty |\n      f Tsingle = s /\\\n      f Tdouble = d\n    }.\nProof.\n  intro ref.\n  intros.\n  esplit.\n  Unshelve.\n  shelve.\n  intro ty.\n  destruct (type_eq_dec ty Tsingle).\n  {\n    subst.\n    exact s.\n  }\n  destruct (type_eq_dec ty Tdouble).\n  {\n    subst.\n    exact d.\n  }\n  apply ref.\n  Unshelve.\n  split; reflexivity.\nDefined.\n\nDefinition single_double (U: _ -> Type)\n           (f_: forall ty, U ty)\n           (s: U Tsingle)\n           (d: U Tdouble)\n:\n  forall ty, U ty :=\n  let (f, _) := single_double_ex U f_ s d in f.\n\nDefinition binop_nan :  forall ty, binary_float (fprec ty) (femax ty) ->\n       binary_float (fprec ty) (femax ty) ->\n       nan_payload (fprec ty) (femax ty) :=\n  single_double\n    (fun ty =>\n       binary_float (fprec ty) (femax ty) ->\n       binary_float (fprec ty) (femax ty) ->\n       nan_payload (fprec ty) (femax ty)) \n     (fun ty  _ _ => any_nan ty)\n     Floats.Float32.binop_nan\n     Floats.Float.binop_nan.\n\nDefinition abs_nan :=\n  single_double\n    (fun ty =>\n       binary_float (fprec ty) (femax ty) ->\n       nan_payload (fprec ty) (femax ty)) \n     (fun ty  _ => any_nan ty)\n     Floats.Float32.abs_nan\n     Floats.Float.abs_nan.\n\nDefinition opp_nan :=\n  single_double\n    (fun ty =>\n       binary_float (fprec ty) (femax ty) ->\n       nan_payload (fprec ty) (femax ty)) \n     (fun ty  _ => any_nan ty)\n     Floats.Float32.neg_nan\n     Floats.Float.neg_nan.\n\n\nModule FMA_NAN. \n(* some of these definitions adapted from [the open-source part of] CompCert  *)\nImport ZArith. Import Coq.Lists.List.\n\n(** Transform a Nan payload to a quiet Nan payload. *)\n\nDefinition quiet_nan_payload (t: type) (p: positive) :=\n  Z.to_pos (Zbits.P_mod_two_p (Pos.lor p ((Zaux.iter_nat xO (Z.to_nat (fprec t - 2)) 1%positive))) (Z.to_nat (fprec t - 1))).\n\nLemma quiet_nan_proof (t: type): forall p, Binary.nan_pl (fprec t) (quiet_nan_payload t p) = true.\nProof. \nintros.\npose proof (fprec_gt_one t).\n apply normalized_nan; auto; lia.\nQed.\n\nDefinition quiet_nan (t: type) (sp: bool * positive) : {x : ftype t | Binary.is_nan _ _ x = true} :=\n  let (s, p) := sp in\n  exist _ (Binary.B754_nan (fprec t) (femax t) s (quiet_nan_payload t p) (quiet_nan_proof t p)) (eq_refl true).\n\nDefinition default_nan (t: type) := (fst Archi.default_nan_64, iter_nat (Z.to_nat (fprec t - 2)) _ xO xH).\n\nInductive NAN_SCHEME := NAN_SCHEME_ARM | NAN_SCHEME_X86 | NAN_SCHEME_RISCV.\n\nDefinition the_nan_scheme : NAN_SCHEME.\nTransparent Archi.choose_nan_64.\ntry (unify Archi.choose_nan_64 Archi.default_nan_64; exact NAN_SCHEME_RISCV);\ntry (unify Archi.choose_nan_64 (fun l => match l with nil => Archi.default_nan_64 | n::_ => n end);\n      exact NAN_SCHEME_X86);\ntry (let p := constr:(Archi.choose_nan_64) in\n      let p := eval red in p in\n      match p with _ (fun p => negb (Pos.testbit p 51)) _ => idtac end;\n      exact NAN_SCHEME_ARM).\nOpaque Archi.choose_nan_64.\nDefined.\n\nDefinition ARMchoose_nan (is_signaling: positive -> bool) \n                      (default: bool * positive)\n                      (l0: list (bool * positive)) : bool * positive :=\n  let fix choose_snan (l1: list (bool * positive)) :=\n    match l1 with\n    | nil =>\n        match l0 with nil => default | n :: _ => n end\n    | ((s, p) as n) :: l1 =>\n        if is_signaling p then n else choose_snan l1\n    end\n  in choose_snan l0.\n\nDefinition choose_nan (t: type) : list (bool * positive) -> bool * positive :=\n match the_nan_scheme with\n | NAN_SCHEME_RISCV => fun _ => default_nan t\n | NAN_SCHEME_X86 => fun l => match l with nil => default_nan t | n :: _ => n end\n | NAN_SCHEME_ARM => ARMchoose_nan (fun p => negb (Pos.testbit p (Z.to_N (fprec t - 2))))\n                                          (default_nan t)\n end.\n\nDefinition cons_pl {t: type} (x : ftype t) (l : list (bool * positive)) :=\nmatch x with\n| Binary.B754_nan _ _ s p _ => (s, p) :: l\n| _ => l\nend.\n\nDefinition fma_nan_1 (t: type) (x y z: ftype t) : {x : ftype t | @Binary.is_nan (fprec t) (femax t) x = true} :=\n  let '(a, b, c) := Archi.fma_order x y z in\n  quiet_nan t (choose_nan t (cons_pl a (cons_pl b (cons_pl c nil)))).\n\nDefinition fma_nan_pl (t: type) (x y z: ftype t) : {x : ftype t | Binary.is_nan _ _ x = true} :=\n  match x, y with\n  | Binary.B754_infinity _ _ _, Binary.B754_zero _ _ _ | Binary.B754_zero _ _ _, Binary.B754_infinity _ _ _ =>\n      if Archi.fma_invalid_mul_is_nan\n      then quiet_nan t (choose_nan t (default_nan t :: cons_pl z nil))\n      else fma_nan_1 t x y z\n  | _, _ =>\n      fma_nan_1 t x y z\n  end.\n\nEnd FMA_NAN.\n\n#[export] Instance nans: Nans :=\n  {\n    conv_nan := conv_nan;\n    plus_nan := binop_nan;\n    mult_nan := binop_nan;\n    div_nan := binop_nan;\n    abs_nan := abs_nan;\n    opp_nan := opp_nan;\n    sqrt_nan := (fun ty _ => any_nan ty);\n    fma_nan := FMA_NAN.fma_nan_pl\n  }.\n\nLemma val_inject_eq_rect_r v ty1 e:\n  val_inject v ty1 e ->\n  forall ty2 (EQ: ty2 = ty1),\n    val_inject v ty2 (eq_rect_r _ e EQ).\nProof.\n  intros.\n  subst.\n  assumption.\nQed.\n      \nLemma val_inject_single_inv_r v f:\n  val_inject v Tsingle f ->\n  v = Values.Vsingle f.\nProof.\n  inversion 1; subst.\n  apply val_inject_single_inv in H.\n  congruence.\nQed.\n\nLemma val_inject_double_inv_r v f:\n  val_inject v Tdouble f ->\n  v = Values.Vfloat f.\nProof.\n  inversion 1; subst.\n  apply val_inject_double_inv in H.\n  congruence.\nQed.\n\n(** Why do we need this rewrite hint database?\n   You might think that all of this could be accomplished with \"change\"\n   instead of \"rewrite\".  But if you do that, then Qed takes forever. *)\nLemma Float32_add_rewrite: Float32.add = @BPLUS _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_add_rewrite : float_elim.\nLemma Float32_sub_rewrite: Float32.sub = @BMINUS _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_sub_rewrite : float_elim.\nLemma Float32_mul_rewrite: Float32.mul = @BMULT _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_mul_rewrite : float_elim.\nLemma Float32_div_rewrite: Float32.div = @BDIV _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_div_rewrite : float_elim.\nLemma Float32_neg_rewrite: Float32.neg = @BOPP _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_neg_rewrite : float_elim.\nLemma Float32_abs_rewrite: Float32.abs = @BABS _ Tsingle.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float32_abs_rewrite : float_elim.\n\nLemma Float_add_rewrite: Float.add = @BPLUS _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_add_rewrite : float_elim.\nLemma Float_sub_rewrite: Float.sub = @BMINUS _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_sub_rewrite : float_elim.\nLemma Float_mul_rewrite: Float.mul = @BMULT _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_mul_rewrite : float_elim.\nLemma Float_div_rewrite: Float.div = @BDIV _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_div_rewrite : float_elim.\nLemma Float_neg_rewrite: Float.neg = @BOPP _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_neg_rewrite : float_elim.\nLemma Float_abs_rewrite: Float.abs = @BABS _ Tdouble.  \nProof. reflexivity. Qed.\n#[export] Hint Rewrite Float_abs_rewrite : float_elim.\n\nLemma float_of_single_eq: Float.of_single = @cast _ Tdouble Tsingle.\nProof. reflexivity. Qed.\n\nLemma float32_to_double_eq: Float32.to_double = @cast _ Tdouble Tsingle.\nProof. reflexivity. Qed.\nLemma float32_of_float_eq: Float32.of_double = @cast _ Tsingle Tdouble.\nProof. reflexivity. Qed.\nLemma float_to_single_eq: Float.to_single = @cast _ Tsingle Tdouble.\nProof. reflexivity. Qed.\n#[export] Hint Rewrite float_of_single_eq float32_to_double_eq\n          float32_of_float_eq float_to_single_eq : float_elim.\n\nImport Float_notations.\n\nLemma B754_finite_ext:\n  forall prec emax s m e p1 p2,\n    Binary.B754_finite prec emax s m e p1 = Binary.B754_finite prec emax s m e p2.\nProof.\nintros.\nf_equal.\napply Classical_Prop.proof_irrelevance.\nQed.\n\nImport Integers.\n\nLtac canonicalize_float_constant x :=\nmatch x with\n| Float32.of_bits (Int.repr ?a) =>\n  const_Z a;\n  let x' := constr:(Bits.b32_of_bits a) in\n  let y := eval compute in x' in\n match y with\n   | Binary.B754_finite _ _ ?s ?m ?e _ =>\n     let z := constr:(b32_B754_finite s m e (@eq_refl bool true))\n      in change x with x'; \n        replace x' with z by (apply B754_finite_ext; reflexivity)\n   | Binary.B754_zero _ _ ?s => \n       let z := constr:(b32_B754_zero s) in\n       change x with z        \n  end\n| Float.of_bits (Int64.repr ?a) =>\n  const_Z a;\n  let x' := constr:(Bits.b64_of_bits a) in\n  let y := eval compute in x' in\n match y with\n   | Binary.B754_finite _ _ ?s ?m ?e _ =>\n     let z := constr:(b64_B754_finite s m e (@eq_refl bool true))\n      in change x with x'; \n        replace x' with z by (apply B754_finite_ext; reflexivity)\n   | Binary.B754_zero _ _ ?s => \n       let z := constr:(b64_B754_zero s) in\n       change x with z        \n  end\nend.\n\nLtac canonicalize_float_constants := \n  repeat\n    match goal with\n    | |- context [Binary.B754_finite 24 128 ?s ?m ?e ?p] =>\n         let x := constr:(Binary.B754_finite 24 128 s m e p) in\n         let e' := eval compute in e in\n         let z := constr:(b32_B754_finite s m e' (@eq_refl bool true)) in\n         replace x with z by (apply B754_finite_ext; reflexivity)\n    | |- context [Binary.B754_finite 53 1024 ?s ?m ?e ?p] =>\n         let x := constr:(Binary.B754_finite 53 1024 s m e p) in\n         let e' := eval compute in e in\n         let z := constr:(b64_B754_finite s m e' (@eq_refl bool true)) in\n         replace x with z by (apply B754_finite_ext; reflexivity)\n    | |- context [Float32.of_bits (Int.repr ?a)] =>\n     canonicalize_float_constant constr:(Float32.of_bits (Int.repr a))\n    | |- context [Float.of_bits (Int64.repr ?a)] =>\n     canonicalize_float_constant constr:(Float.of_bits (Int64.repr a))\n    end.\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/FPCompCert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17660771963230626}}
{"text": "Require Import ModelProperties. \nRequire Import AuxiliaryLemmas. \n \nSection addUsrGrpToAclIsSecure. \n \nLemma AddUsrGrpToAclPSS :\n forall (s t : SFSstate) (u : SUBJECT),\n SecureState s -> TransFunc u s AddUsrGrpToAcl t -> SecureState t. \nStartPSS. \ninversion H. \nunfold SecureState in |- *. \nBreakSS. \nsplit. \nunfold DACSecureState in |- *. \nsimpl in |- *. \nintros. \nelim (OBJeq_dec o o0). \nintro. \nrewrite <- a. \ncut (fsecmat (secmat s) o = None). \nintro. \nrewrite H6. \neauto. \n \nunfold fsecmat in |- *. \nauto. \n \nintro. \ncut\n (match fsecmat (secmat s) o0 with\n  | Some y => set_In u0 (ActReaders y) -> PreDACRead s u0 o0\n  | None => True\n  end /\\\n  match fsecmat (secmat s) o0 with\n  | Some y => set_In u0 (ActWriters y) -> PreDACWrite s u0 o0\n  | None => True\n  end). \nelim (fsecmat (secmat s) o0). \nunfold PreDACRead, PreDACWrite, addUsrGrpToAcl_acl in |- *. \nsimpl in |- *. \nelim (facl (acl s) o). \nintro. \nreplace\n (facl\n    (set_add ACLeq_dec\n       (o,\n       acldata (owner a) (group a) (set_add SUBeq_dec ru (UsersReaders a))\n         (set_add GRPeq_dec rg (GroupReaders a))\n         (set_add SUBeq_dec wu (UsersWriters a))\n         (set_add GRPeq_dec wg (GroupWriters a))\n         (set_add SUBeq_dec pu (UsersOwners a))\n         (set_add GRPeq_dec pg (GroupOwners a)))\n       (set_remove ACLeq_dec (o, a) (acl s))) o0) with \n (facl (acl s) o0). \nelim (facl (acl s) o0). \nauto. \n \nauto. \n \nunfold facl in |- *. \nauto. \n \nauto. \n \ntrivial. \n \nsplit. \napply ReadWriteImpRead. \nauto. \n \napply ReadWriteImpWrite. \nauto. \n \nauto. \n \nQed. \n \n \nLemma AddUsrGrpToAclPSP :\n forall (s t : SFSstate) (u : SUBJECT),\n StarProperty s -> TransFunc u s AddUsrGrpToAcl t -> StarProperty t. \nStartPSP. \ninversion H; auto. \nQed. \n \n \nLemma AddUsrGrpToAclPCP :\n forall s t : SFSstate, PreservesControlProp s AddUsrGrpToAcl t. \nintros; unfold PreservesControlProp in |- *; intros Sub TF; inversion TF;\n unfold ControlProperty in |- *. \ninversion H. \nsplit. \nintros. \nsplit. \nintro. \ninversion H6. \nsimpl in H8. \nelim (OBJeq_dec o o0); intro. \nrewrite <- a; auto. \n \ncut (y = z). \nintro. \ncut False. \ntauto. \n \nrewrite H10 in H9; inversion H9; auto. \n \ncut (facl (addUsrGrpToAcl_acl s o ru wu pu rg wg pg) o0 = facl (acl s) o0). \nintro H10; rewrite H10 in H8; rewrite H7 in H8; injection H8; auto. \n \nsymmetry  in |- *. \nunfold addUsrGrpToAcl_acl in |- *. \nelim (facl (acl s) o). \nintro; unfold facl in |- *; apply AddRemEq. \nauto. \n \nauto. \n \nsimpl in H8. \nelim (OBJeq_dec o o0); intro. \nrewrite <- a; auto. \n \ncut (y = z). \nintro. \ncut False. \ntauto. \n \nrewrite H10 in H9; inversion H9; auto. \n \ncut (facl (addUsrGrpToAcl_acl s o ru wu pu rg wg pg) o0 = facl (acl s) o0). \nintro H10; rewrite H10 in H8; rewrite H7 in H8; injection H8; auto. \n \nsymmetry  in |- *. \nunfold addUsrGrpToAcl_acl in |- *. \nelim (facl (acl s) o). \nintro; unfold facl in |- *; apply AddRemEq. \nauto. \n \nauto. \n \nintro;\n absurd\n  (MACObjCtrlAttrHaveChanged s\n     (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n        (AllGrp s) (RootGrp s) (SecAdmGrp s) (objectSC s)\n        (addUsrGrpToAcl_acl s o ru wu pu rg wg pg) \n        (secmat s) (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        (addUsrGrpToAcl_acl s o ru wu pu rg wg pg) \n        (secmat s) (files s) (directories s)) u0); \n auto. \n \nQed. \n \n \nEnd addUsrGrpToAclIsSecure. \n \nHint Resolve AddUsrGrpToAclPSS AddUsrGrpToAclPSP AddUsrGrpToAclPCP. ", "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/addUsrGrpToAclIsSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.17660771963230623}}
{"text": "(* GENERIC *)\n\nRequire Export MinBFTcount_gen2_request.\nRequire Export MinBFTcount_gen2_reply.\nRequire Export MinBFTcount_gen2_prepare.\nRequire Export MinBFTcount_gen2_commit.\nRequire Export MinBFTcount_gen2_accept.\nRequire Export MinBFTcount_gen2_debug.\n\n\nSection MinBFTcount_gen2.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n  Context { ti : TrustedInfo }.\n\n\n  Lemma cexec_increases :\n    forall {eo     : EventOrdering}\n           (e      : Event)\n           (s      : Rep)\n           (s1     : _)\n           (s2     : _)\n           (subs1  : n_procs _)\n           (subs2  : n_procs _),\n      ~ In MAINname (get_names subs1)\n      -> wf_procs subs1\n      -> are_procs_n_procs subs1\n      -> M_run_ls_on_this_one_event (MinBFTlocalSys_newP s s1 subs1) e\n         = Some (MinBFTlocalSys_newP s s2 subs2)\n      -> cexec s1 = cexec s2\n         \\/\n         exists r l,\n           cexec s2 = S (cexec s1)\n           /\\ In (send_accept (accept r (cexec s2)) l)\n                 (M_output_ls_on_this_one_event (MinBFTlocalSys_newP s s1 subs1) e).\n  Proof.\n    introv ni wf aps h.\n    remember (trigger e) as trig; symmetry in Heqtrig; destruct trig.\n    { destruct d; simpl in *.\n      { eapply cexec_increases_request; eauto. }\n      { eapply cexec_increases_reply; eauto. }\n      { eapply cexec_increases_prepare; eauto. }\n      { eapply cexec_increases_commit; eauto. }\n      { eapply cexec_increases_accept; eauto. }\n      { eapply cexec_increases_debug; eauto. } }\n    { apply map_option_Some in h; exrepnd; rev_Some; minbft_simp.\n      unfold trigger_op in *; rewrite Heqtrig in *; simpl in *; ginv. }\n    { apply map_option_Some in h; exrepnd; rev_Some; minbft_simp.\n      unfold trigger_op in *; rewrite Heqtrig in *; simpl in *; ginv. }\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    : MinBFTls)\n           (subs  : n_procs _),\n      lower_head 1 subs = true\n      -> ~ In MAINname (get_names subs)\n      -> wf_procs subs\n      -> are_procs_n_procs subs\n      -> M_run_ls_before_event (MinBFTlocalSysP s subs) 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' \u228f e\n           /\\ M_run_ls_before_event (MinBFTlocalSysP s subs) e' = Some ls'\n           /\\ In (send_accept (accept r' i) l') (M_output_ls_on_this_one_event ls' e').\n  Proof.\n    introv low ni wf aps eqls out.\n    applydup M_run_ls_before_event_ls_is_minbftP in eqls; exrepnd; subst; auto.\n    applydup accepted_if_executed_previous_step in out; ginv.\n\n    clear r l out eqls0.\n    revert s s0 subs subs' low ni wf aps eqls.\n\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv low ni wf aps eqls.\n    rewrite M_run_ls_before_event_unroll in eqls.\n    destruct (dec_isFirst e) as [d|d]; ginv; minbft_simp.\n\n    { apply eq_MinBFTlocalSys_newP_implies in eqls; repnd; subst; tcsp. }\n\n    apply map_option_Some in eqls; exrepnd; rev_Some.\n    applydup M_run_ls_before_event_ls_is_minbftP in eqls1; exrepnd; subst; auto.\n\n    dup eqls1 as eqBef.\n    eapply ind in eqls1; eauto 3 with eo; clear ind;[].\n    applydup similar_subs_preserves_get_names in eqls2.\n    apply cexec_increases in eqls0; eauto 3 with comp minbft;\n      try (complete (rewrite <- eqls3; auto));[].\n    repndors; exrepnd; tcsp;\n      try (complete (left; congruence));\n      try (complete (right; minbft_finish_eexists));[].\n\n    right.\n    exists r' l' e' ls'; dands; auto; eauto 3 with eo; try congruence.\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    : MinBFTls)\n           (subs  : n_procs _),\n      lower_head 1 subs = true\n      -> ~ In MAINname (get_names subs)\n      -> wf_procs subs\n      -> are_procs_n_procs subs\n      -> M_run_ls_before_event (MinBFTlocalSysP s subs) 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' \u228f e\n          /\\ M_run_ls_before_event (MinBFTlocalSysP s subs) 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 low ni wf aps 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 minbft_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  Definition lower_headF k {n} (f : Rep -> n_procs n) :=\n    forall r, lower_head k (f r) = true.\n\n  Definition not_in_namesF (cn : CompName) {n} (f : Rep -> n_procs n) :=\n    forall r, ~ In MAINname (get_names (f r)).\n\n  Definition wf_procsF {n} (f : Rep -> n_procs n) :=\n    forall r, wf_procs (f r).\n\n  Definition are_procs_n_procsF {n} (f : Rep -> n_procs n) :=\n    forall r, are_procs_n_procs (f r).\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           (subs  : Rep -> n_procs _),\n      lower_headF 1 subs\n      -> not_in_namesF MAINname subs\n      -> wf_procsF subs\n      -> are_procs_n_procsF subs\n      -> is_replica e\n      -> In (send_accept (accept r i2) l) (M_output_sys_on_event (MinBFTsysP subs) e)\n      -> i1 < i2\n      -> 0 < i1\n      -> exists r' l' e',\n          e' \u228f e\n          /\\ In (send_accept (accept r' i1) l') (M_output_sys_on_event (MinBFTsysP subs) e').\n  Proof.\n    introv low ni wf aps isr h lti lti0.\n    unfold M_output_sys_on_event in *.\n    unfold MinBFTsysP, 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           (subs  : Rep -> n_procs _),\n      lower_headF 1 subs\n      -> not_in_namesF MAINname subs\n      -> wf_procsF subs\n      -> are_procs_n_procsF subs\n      -> is_replica e\n      -> In (send_accept (accept r i) l) (M_output_sys_on_event (MinBFTsysP subs) e)\n      -> 0 < i.\n  Proof.\n    introv low ni wf aps isrep out.\n    unfold M_output_sys_on_event in *.\n    unfold MinBFTsysP, 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_minbftP in out1; exrepnd; subst; eauto.\n    eapply accepted_if_executed_previous_step in out0; subst; omega.\n  Qed.\n  Hint Resolve accepted_counter_positive : minbft.\n\n  Lemma M_output_ls_on_input_is_committed_implies :\n    forall u c ls,\n      M_run_ls_on_input (LOGlocalSys u) LOGname (is_committed_in c) = (ls, Some (log_out true))\n      -> is_committed c u = true\n         /\\ ls = LOGlocalSys u.\n  Proof.\n    introv out.\n    unfold M_run_ls_on_input, on_comp in out; simpl in *.\n    unfold M_run_sm_on_input in out; simpl in *.\n    unfold M_on_decr, M_break in out; simpl in *; minbft_simp.\n    inversion out; auto.\n  Qed.\n\nEnd MinBFTcount_gen2.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTcount_gen2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.17659610096676734}}
{"text": "Require Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.SimpleRecognizer.\nRequire Import Fiat.Parsers.SimpleRecognizerCorrect.\nRequire Import Fiat.Parsers.RecognizerPreOptimized.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.GenericRecognizerOptimized.\nRequire Import Fiat.Parsers.GenericRecognizerOptimizedTactics.\nRequire Import Fiat.Common.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}\n          {G : pregrammar Char}.\n  Context (Hvalid : is_true (grammar_rvalid G)).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Context {splitdata : @split_dataT Char _ _}.\n\n  Let data : boolean_parser_dataT :=\n    {| split_data := splitdata |}.\n  Let optdata : boolean_parser_dataT :=\n    {| split_data := optsplitdata |}.\n  Local Existing Instance data.\n\n  Let rdata' : @parser_removal_dataT' _ G predata := rdp_list_rdata'.\n  Local Existing Instance rdata'.\n\n  Local Arguments minus !_ !_.\n  Local Arguments min !_ !_.\n\n  Definition parse_nonterminal_opt'0\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    exact (@parse_nonterminal_opt _ _ G Hvalid _ simple_gendata str nt).\n  Defined.\n\n  Definition parse_nonterminal_opt'1\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'0 str nt) in\n    let h := head c in\n    let p := (eval cbv [proj1_sig h] in (proj1_sig c)) in\n    sigL_transitivity p; [ | abstract exact (proj2_sig c) ].\n\n    let T := match goal with |- @sig ?A _ => A end in\n    evar (b' : T).\n    sigL_transitivity b'; subst b'.\n    Focus 2.\n    { let gendata := match goal with |- context[@parse_nonterminal_opt _ _ _ _ _ ?gendata] => head gendata end in\n      cbv [parse_nonterminal_opt gendata].\n      cbv [GenericBaseTypes.parse_nt_T GenericBaseTypes.parse_item_T GenericBaseTypes.parse_production_T GenericBaseTypes.parse_productions_T GenericBaseTypes.ret_Terminal_false GenericBaseTypes.ret_Terminal_true GenericBaseTypes.ret_NonTerminal_false GenericBaseTypes.ret_NonTerminal_true GenericBaseTypes.ret_production_cons GenericBaseTypes.ret_orb_production GenericBaseTypes.ret_orb_production_base GenericBaseTypes.ret_production_nil_true GenericBaseTypes.ret_production_nil_false GenericBaseTypes.ret_orb_productions GenericBaseTypes.ret_orb_productions_base GenericBaseTypes.ret_nt GenericBaseTypes.ret_nt_invalid].\n      reflexivity. }\n    Unfocus.\n\n    eexists; reflexivity.\n  Defined.\n\n  Definition parse_nonterminal_opt\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'1 str nt) in\n    let h := head c in\n    let impl := (eval cbv [h proj1_sig] in (proj1_sig c)) in\n    (exists impl);\n      abstract (exact (proj2_sig c)).\n  Defined.\n\n  Lemma parse_nonterminal_opt_eq\n        {HSLP : StringLikeProperties Char}\n        {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}\n        (str : String)\n        (nt : String.string)\n    : @GenericCorrectnessBaseTypes.parse_nt_is_correct _ _ _ _ _ simple_gencdata2 str (of_nonterminal nt) (GenericRecognizerMin.parse_nonterminal str nt) (proj1_sig (parse_nonterminal_opt str nt)).\n  Proof.\n    let p := match goal with |- context[proj1_sig ?p] => p end in\n    rewrite (proj2_sig p).\n    refine (proj2 (@parse_nonterminal_optdata_eq _ _ _ G splitdata simple_gendata simple_gencdata2 _ _ str nt _ ) _).\n    unfold parse_nonterminal.\n    exact (GenericRecognizerMin.parse_nonterminal_correct (gcdata := simple_gencdata2) str nt).\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/SimpleRecognizerOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.17643454791881116}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import PSCIHandler.Spec.\nRequire Import CtxtSwitchAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance CtxtSwitchAux_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance CtxtSwitchAux_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance save_sysreg_state_inv: PreservesInvariants save_sysreg_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_sysreg_state_inv: PreservesInvariants restore_sysreg_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance save_ns_state_sysreg_state_inv: PreservesInvariants save_ns_state_sysreg_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_ns_state_sysreg_state_inv: PreservesInvariants restore_ns_state_sysreg_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance shiftl_inv: PreservesInvariants shiftl_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_to_idx_inv: PreservesInvariants addr_to_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_sysregs_inv: PreservesInvariants set_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_psci_call_inv: PreservesInvariants get_psci_result_forward_psci_call_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_inc_inv: PreservesInvariants granule_refcount_inc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_rec_run_inv: PreservesInvariants ns_buffer_read_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_pstate_inv: PreservesInvariants get_rec_pstate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_release_inv: PreservesInvariants atomic_granule_put_release_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_gprs_inv: PreservesInvariants get_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_asserted_inv: PreservesInvariants set_rec_ptimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_is_emulated_mmio_inv: PreservesInvariants get_rec_run_is_emulated_mmio_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_dec_inv: PreservesInvariants granule_refcount_dec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_masked_inv: PreservesInvariants get_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_header_inv: PreservesInvariants measurement_extend_data_header_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_lock_inv: PreservesInvariants granule_lock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_common_sysregs_inv: PreservesInvariants get_rec_common_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_rec_inv: PreservesInvariants is_addr_in_par_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sixty_four_inv: PreservesInvariants esr_sixty_four_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance run_realm_inv: PreservesInvariants run_realm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_g_rtt_refcount_inv: PreservesInvariants get_g_rtt_refcount_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_srt_inv: PreservesInvariants esr_srt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_pstate_inv: PreservesInvariants set_rec_pstate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_pc_inv: PreservesInvariants get_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_len_inv: PreservesInvariants access_len_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_masked_inv: PreservesInvariants set_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_read_inv: PreservesInvariants sysreg_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance null_ptr_inv: PreservesInvariants null_ptr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_ns_state_inv: PreservesInvariants get_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_masked_inv: PreservesInvariants set_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_esr_inv: PreservesInvariants set_rec_run_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_ns_state_inv: PreservesInvariants set_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_gprs_inv: PreservesInvariants set_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_hpfar_inv: PreservesInvariants set_rec_run_hpfar_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x0_inv: PreservesInvariants get_psci_result_x0_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x1_inv: PreservesInvariants get_psci_result_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x2_inv: PreservesInvariants get_psci_result_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance psci_rsi_inv: PreservesInvariants psci_rsi_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_masked_inv: PreservesInvariants get_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_g_llt_inv: PreservesInvariants set_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_last_run_info_esr_inv: PreservesInvariants get_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_is_write_inv: PreservesInvariants esr_is_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x3_inv: PreservesInvariants get_psci_result_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_index_inv: PreservesInvariants set_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance emulate_timer_ctl_read_inv: PreservesInvariants emulate_timer_ctl_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_inv: PreservesInvariants measurement_extend_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_IS_WRITE_inv: PreservesInvariants ESR_EL2_SYSREG_IS_WRITE_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance barrier_inv: PreservesInvariants barrier_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_mask_inv: PreservesInvariants access_mask_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sign_extend_inv: PreservesInvariants esr_sign_extend_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_dispose_pending_inv: PreservesInvariants set_rec_dispose_pending_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_g_rtt_inv: PreservesInvariants get_rd_g_rtt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_last_run_info_esr_inv: PreservesInvariants set_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_regs_inv: PreservesInvariants get_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x3_inv: PreservesInvariants get_psci_result_forward_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x2_inv: PreservesInvariants get_psci_result_forward_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x1_inv: PreservesInvariants get_psci_result_forward_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_exit_reason_inv: PreservesInvariants set_rec_run_exit_reason_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_ISS_RT_inv: PreservesInvariants ESR_EL2_SYSREG_ISS_RT_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_inv: PreservesInvariants atomic_granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_idreg_inv: PreservesInvariants read_idreg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_end_inv: PreservesInvariants get_rec_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_pc_inv: PreservesInvariants set_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_regs_inv: PreservesInvariants set_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_runnable_inv: PreservesInvariants get_rec_runnable_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_sysregs_inv: PreservesInvariants get_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_asserted_inv: PreservesInvariants set_rec_vtimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_emulated_write_val_inv: PreservesInvariants set_rec_run_emulated_write_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_far_inv: PreservesInvariants set_rec_run_far_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_emulated_read_val_inv: PreservesInvariants get_rec_run_emulated_read_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_inv: PreservesInvariants get_rec_vtimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_inv: PreservesInvariants get_rec_ptimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_g_rtt_rd_inv: PreservesInvariants set_g_rtt_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_inv: PreservesInvariants is_addr_in_par_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_write_inv: PreservesInvariants sysreg_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_base_inv: PreservesInvariants get_rec_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_unused_granule_inv: PreservesInvariants find_lock_unused_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_to_phys_inv: PreservesInvariants entry_to_phys_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance stage2_tlbi_ipa_inv: PreservesInvariants stage2_tlbi_ipa_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_get_inv: PreservesInvariants atomic_granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance link_table_inv: PreservesInvariants link_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance timer_condition_met_inv: PreservesInvariants timer_condition_met_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_is_level_aligned_inv: PreservesInvariants addr_is_level_aligned_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition CtxtSwitchAux_fresh : compatlayer (cdata RData) :=\n      _save_sysreg_state \u21a6 gensem save_sysreg_state_spec\n        \u2295 _restore_sysreg_state \u21a6 gensem restore_sysreg_state_spec\n        \u2295 _save_ns_state_sysreg_state \u21a6 gensem save_ns_state_sysreg_state_spec\n        \u2295 _restore_ns_state_sysreg_state \u21a6 gensem restore_ns_state_sysreg_state_spec\n      .\n\n    Definition CtxtSwitchAux_passthrough : compatlayer (cdata RData) :=\n      _shiftl \u21a6 gensem shiftl_spec\n        \u2295 _addr_to_idx \u21a6 gensem addr_to_idx_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _set_rec_sysregs \u21a6 gensem set_rec_sysregs_spec\n        \u2295 _get_psci_result_forward_psci_call \u21a6 gensem get_psci_result_forward_psci_call_spec\n        \u2295 _granule_refcount_inc \u21a6 gensem granule_refcount_inc_spec\n        \u2295 _ns_buffer_read_rec_run \u21a6 gensem ns_buffer_read_rec_run_spec\n        \u2295 _granule_put \u21a6 gensem granule_put_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _entry_is_table \u21a6 gensem entry_is_table_spec\n        \u2295 _get_rec_pstate \u21a6 gensem get_rec_pstate_spec\n        \u2295 _atomic_granule_put_release \u21a6 gensem atomic_granule_put_release_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _get_rec_run_gprs \u21a6 gensem get_rec_run_gprs_spec\n        \u2295 _set_rec_ptimer_asserted \u21a6 gensem set_rec_ptimer_asserted_spec\n        \u2295 _get_rec_run_is_emulated_mmio \u21a6 gensem get_rec_run_is_emulated_mmio_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _granule_refcount_dec \u21a6 gensem granule_refcount_dec_spec\n        \u2295 _get_rec_ptimer_masked \u21a6 gensem get_rec_ptimer_masked_spec\n        \u2295 _measurement_extend_data_header \u21a6 gensem measurement_extend_data_header_spec\n        \u2295 _granule_lock \u21a6 gensem granule_lock_spec\n        \u2295 _ns_buffer_unmap \u21a6 gensem ns_buffer_unmap_spec\n        \u2295 _granule_memzero_mapped \u21a6 gensem granule_memzero_mapped_spec\n        \u2295 _get_rec_common_sysregs \u21a6 gensem get_rec_common_sysregs_spec\n        \u2295 _is_addr_in_par_rec \u21a6 gensem is_addr_in_par_rec_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _esr_sixty_four \u21a6 gensem esr_sixty_four_spec\n        \u2295 _run_realm \u21a6 gensem run_realm_spec\n        \u2295 _get_g_rtt_refcount \u21a6 gensem get_g_rtt_refcount_spec\n        \u2295 _esr_srt \u21a6 gensem esr_srt_spec\n        \u2295 _set_rec_pstate \u21a6 gensem set_rec_pstate_spec\n        \u2295 _get_rec_pc \u21a6 gensem get_rec_pc_spec\n        \u2295 _granule_get \u21a6 gensem granule_get_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _access_len \u21a6 gensem access_len_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _set_rec_ptimer_masked \u21a6 gensem set_rec_ptimer_masked_spec\n        \u2295 _sysreg_read \u21a6 gensem sysreg_read_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _null_ptr \u21a6 gensem null_ptr_spec\n        \u2295 _get_ns_state \u21a6 gensem get_ns_state_spec\n        \u2295 _set_rec_vtimer_masked \u21a6 gensem set_rec_vtimer_masked_spec\n        \u2295 _get_wi_g_llt \u21a6 gensem get_wi_g_llt_spec\n        \u2295 _set_rec_run_esr \u21a6 gensem set_rec_run_esr_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _set_ns_state \u21a6 gensem set_ns_state_spec\n        \u2295 _set_rec_run_gprs \u21a6 gensem set_rec_run_gprs_spec\n        \u2295 _set_rec_run_hpfar \u21a6 gensem set_rec_run_hpfar_spec\n        \u2295 _get_psci_result_x0 \u21a6 gensem get_psci_result_x0_spec\n        \u2295 _get_psci_result_x1 \u21a6 gensem get_psci_result_x1_spec\n        \u2295 _get_psci_result_x2 \u21a6 gensem get_psci_result_x2_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _psci_rsi \u21a6 gensem psci_rsi_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _pgte_read \u21a6 gensem pgte_read_spec\n        \u2295 _get_rec_vtimer_masked \u21a6 gensem get_rec_vtimer_masked_spec\n        \u2295 _set_wi_g_llt \u21a6 gensem set_wi_g_llt_spec\n        \u2295 _get_rec_last_run_info_esr \u21a6 gensem get_rec_last_run_info_esr_spec\n        \u2295 _esr_is_write \u21a6 gensem esr_is_write_spec\n        \u2295 _get_psci_result_x3 \u21a6 gensem get_psci_result_x3_spec\n        \u2295 _get_wi_index \u21a6 gensem get_wi_index_spec\n        \u2295 _set_wi_index \u21a6 gensem set_wi_index_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _emulate_timer_ctl_read \u21a6 gensem emulate_timer_ctl_read_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _measurement_extend_data \u21a6 gensem measurement_extend_data_spec\n        \u2295 _ESR_EL2_SYSREG_IS_WRITE \u21a6 gensem ESR_EL2_SYSREG_IS_WRITE_spec\n        \u2295 _barrier \u21a6 gensem barrier_spec\n        \u2295 _access_mask \u21a6 gensem access_mask_spec\n        \u2295 _esr_sign_extend \u21a6 gensem esr_sign_extend_spec\n        \u2295 _set_rec_dispose_pending \u21a6 gensem set_rec_dispose_pending_spec\n        \u2295 _get_rd_g_rtt \u21a6 gensem get_rd_g_rtt_spec\n        \u2295 _set_rec_last_run_info_esr \u21a6 gensem set_rec_last_run_info_esr_spec\n        \u2295 _granule_memzero \u21a6 gensem granule_memzero_spec\n        \u2295 _get_rec_regs \u21a6 gensem get_rec_regs_spec\n        \u2295 _get_psci_result_forward_x3 \u21a6 gensem get_psci_result_forward_x3_spec\n        \u2295 _get_psci_result_forward_x2 \u21a6 gensem get_psci_result_forward_x2_spec\n        \u2295 _get_psci_result_forward_x1 \u21a6 gensem get_psci_result_forward_x1_spec\n        \u2295 _set_rec_run_exit_reason \u21a6 gensem set_rec_run_exit_reason_spec\n        \u2295 _ESR_EL2_SYSREG_ISS_RT \u21a6 gensem ESR_EL2_SYSREG_ISS_RT_spec\n        \u2295 _atomic_granule_put \u21a6 gensem atomic_granule_put_spec\n        \u2295 _read_idreg \u21a6 gensem read_idreg_spec\n        \u2295 _get_rec_par_end \u21a6 gensem get_rec_par_end_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _set_mapping \u21a6 gensem set_mapping_spec\n        \u2295 _set_rec_pc \u21a6 gensem set_rec_pc_spec\n        \u2295 _set_rec_regs \u21a6 gensem set_rec_regs_spec\n        \u2295 _get_rec_runnable \u21a6 gensem get_rec_runnable_spec\n        \u2295 _ns_granule_map \u21a6 gensem ns_granule_map_spec\n        \u2295 _get_rec_sysregs \u21a6 gensem get_rec_sysregs_spec\n        \u2295 _set_rec_vtimer_asserted \u21a6 gensem set_rec_vtimer_asserted_spec\n        \u2295 _set_rec_run_emulated_write_val \u21a6 gensem set_rec_run_emulated_write_val_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _set_rec_run_far \u21a6 gensem set_rec_run_far_spec\n        \u2295 _get_rec_run_emulated_read_val \u21a6 gensem get_rec_run_emulated_read_val_spec\n        \u2295 _get_rec_vtimer \u21a6 gensem get_rec_vtimer_spec\n        \u2295 _get_rec_ptimer \u21a6 gensem get_rec_ptimer_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _set_g_rtt_rd \u21a6 gensem set_g_rtt_rd_spec\n        \u2295 _ns_buffer_read_data \u21a6 gensem ns_buffer_read_data_spec\n        \u2295 _pgte_write \u21a6 gensem pgte_write_spec\n        \u2295 _is_addr_in_par \u21a6 gensem is_addr_in_par_spec\n        \u2295 _sysreg_write \u21a6 gensem sysreg_write_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _get_rec_par_base \u21a6 gensem get_rec_par_base_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _find_lock_unused_granule \u21a6 gensem find_lock_unused_granule_spec\n        \u2295 _entry_to_phys \u21a6 gensem entry_to_phys_spec\n        \u2295 _stage2_tlbi_ipa \u21a6 gensem stage2_tlbi_ipa_spec\n        \u2295 _atomic_granule_get \u21a6 gensem atomic_granule_get_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _link_table \u21a6 gensem link_table_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n        \u2295 _timer_condition_met \u21a6 gensem timer_condition_met_spec\n        \u2295 _addr_is_level_aligned \u21a6 gensem addr_is_level_aligned_spec\n      .\n\n    Definition CtxtSwitchAux := CtxtSwitchAux_fresh \u2295 CtxtSwitchAux_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.1764345339234729}}
{"text": "(*\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List\n     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     Messages\n     Keys\n     Tactics\n     RealWorld\n     SafeProtocol\n     SafetyAutomation\n     Simulation\n\n     Theory.InvariantsTheory\n     Theory.KeysTheory\n\n     ModelCheck.ModelCheck\n     ModelCheck.LabelsAlign\n     ModelCheck.ProtocolFunctions\n     ModelCheck.RealWorldStepLemmas\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.UniverseInversionLemmas\n.\n\nImport SafetyAutomation Gen.\n\nSet Implicit Arguments.\n\nLemma lookup_in_merge_perm :\n  forall kid (m m' : key_perms),\n    m $k++ m' $? kid = match m $? kid with\n                       | Some p => match m' $? kid with\n                                  | Some p' => Some (greatest_permission p p')\n                                  | None => Some p\n                                  end\n                       | None => m' $? kid\n                       end.\nProof.\n  intros; cases (m $? kid); cases (m' $? kid); solve_perm_merges.\nQed.\n\nSection RW.\n  Import RealWorld.\n\n  Fixpoint compute_na {t} (cmd: user_cmd t) : sigT user_cmd :=\n    match cmd with\n    | Bind c _ => compute_na c\n    | c => existT _ _ c\n    end.\n\n  Lemma compute_na_correct :\n    forall t (cmd : user_cmd t) t__n (cmd__n : user_cmd t__n),\n      compute_na cmd = existT _ _ cmd__n\n      -> nextAction cmd cmd__n.\n  Proof.\n    induct cmd\n    ; try solve [ unfold compute_na; simpl; intros; invert H; econstructor; eauto ].\n\n    intros.\n    constructor.\n    simpl in H0; eauto.\n  Qed.\n\n  Lemma invert_na :\n    forall t (cmd : user_cmd t) t__n (cmd__n : user_cmd t__n),\n      nextAction cmd cmd__n\n      -> compute_na cmd = existT _ _ cmd__n\n        /\\ projT1 (compute_na cmd) = t__n.\n  Proof.\n\n    induct cmd\n    ; try solve [ intros; unfold compute_na; invert H; split; eauto ].\n\n    intros; induct H; eauto.\n    intros; invert H0; eauto.\n  Qed.\n\nEnd RW.\n\nInductive NoSilent {A B} (uid : user_id) (U : RealWorld.universe A B) : Prop :=\n| Stuck :\n    (forall U', ~ indexedRealStep uid Silent U U')\n    -> NoSilent uid U.\n\nDefinition honest_heaps_sane {A} (usrs : honest_users A) (cs : ciphers) (gks : keys) :=\n  forall uid u,\n    usrs $? uid = Some u\n    -> (forall cid, List.In cid u.(c_heap) -> In cid cs)\n    /\\ (forall kid kp, u.(key_heap) $? kid = Some kp -> In kid gks)\n. \n\nLemma step_didnt_appear :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) uid1 ks ks' qmsgs qmsgs' mycs mycs' ms\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs ++ ms, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> lbl = Silent\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs ++ ms;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n      -> forall usrs'' (adv'' : user_data B) cs'' gks'',\n          usrs'' $? uid1 = Some {| key_heap := ks;\n                                   protocol := cmdc;\n                                   msg_heap := qmsgs;\n                                   c_heap   := mycs;\n                                   from_nons := froms;\n                                   sent_nons := sents;\n                                   cur_nonce := cur_n |}\n          -> (forall uid u, usrs'' $? uid = Some u -> exists u', usrs $? uid = Some u')\n          -> (forall cid c, cs'' $? cid = Some c -> cs $? cid = Some c)\n          -> (forall cid c, cs $? cid = Some c -> cs'' $? cid = Some c \\/ cs'' $? cid = None)\n          -> (forall kid k, gks $? kid = Some k -> gks'' $? kid = Some k \\/ gks'' $? kid = None)\n          -> (forall kid k, gks'' $? kid = Some k -> gks $? kid = Some k)\n          -> honest_heaps_sane usrs'' cs'' gks''\n          -> exists bd'',\n              step_user Silent suid\n                        (usrs'', adv'', cs'', gks'', ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n                        bd''.\nProof.\n  Local Ltac process_stuff :=\n    repeat\n      match goal with\n      | [ H : honest_heaps_sane ?usrs ?cs ?gks, USR : ?usrs $? _ = Some _ |- _ ] =>\n        specialize (H _ _ USR)\n        ; simpl in H\n        ; destruct H\n      | [ H : ?m $? _ = Some _, FN : (forall _ _, ?m $? _ = Some _ -> _) |- _ ] =>\n        apply FN in H\n      | [ H : List.In _ ?l, FN : (forall _, List.In _ ?l -> _) |- _ ] =>\n        apply FN in H\n      end\n    ; split_ors\n    ; clean_map_lookups\n    ; trivial.\n  \n  induction 1; inversion 1; inversion 1\n  ; intros\n  ; subst\n  ; try discriminate\n  ; try solve [ eexists; econstructor; eauto ]\n  ; eauto.\n\n  - eapply IHstep_user in H27; eauto.\n    split_ex; eauto.\n    dt x.\n    eexists; econstructor; eauto.\n  - eexists; eapply StepEncrypt with (c_id0 := next_key cs''); eauto using Maps.next_key_not_in\n    ; process_stuff.\n    \n  - eexists; econstructor; trivial.\n    process_stuff; split_ors; clean_map_lookups; eauto.\n    process_stuff; split_ors; clean_map_lookups; eauto.\n    process_stuff; split_ors; clean_map_lookups; eauto.\n    all: eauto.\n  - eexists; eapply StepSign with (c_id0 := next_key cs''); eauto using Maps.next_key_not_in\n    ; process_stuff.\n  - eexists; econstructor; eauto\n    ; process_stuff.\n  - eexists; eapply StepGenerateKey with (k_id0 := next_key gks''); eauto using Maps.next_key_not_in.\n\n    Unshelve.\n    auto.\nQed.\n\nLemma silent_step_then_silent_step_inv :\n  forall {A B} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd (Base A)) uid1 ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> lbl = Silent\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n\n      -> forall uid2 bd2 bd2' cmd2 ks2 qmsgs2 mycs2 froms2 sents2 cur_n2 usrs'' cmdc' ud2,\n\n          step_user Silent (Some uid2)\n                    (usrs'', adv', cs', gks', ks2, qmsgs2, mycs2, froms2, sents2, cur_n2, cmd2)\n                    bd2'\n          -> uid1 <> uid2\n          -> usrs $? uid2 = Some ud2\n          -> bd2 = build_data_step (mkUniverse usrs adv cs gks) ud2\n          -> usrs' $? uid2 = Some {| key_heap := ks2;\n                                    protocol := cmd2;\n                                    msg_heap := qmsgs2;\n                                    c_heap   := mycs2;\n                                    from_nons := froms2;\n                                    sent_nons := sents2;\n                                    cur_nonce := cur_n2 |}\n          -> usrs'' = usrs' $+ (uid1, {| key_heap := ks';\n                                        protocol := cmdc';\n                                        msg_heap := qmsgs';\n                                        c_heap   := mycs';\n                                        from_nons := froms';\n                                        sent_nons := sents';\n                                        cur_nonce := cur_n' |})\n          -> honest_heaps_sane usrs cs gks\n          -> exists bd2'',\n              step_user Silent (Some uid2) bd2 bd2''\n.\nProof.\n  induction 1; inversion 1; inversion 1; intros; subst\n  ; autorewrite with find_user_keys in *\n  ; try discriminate\n  ; try solve [\n          dt bd2'; clean_map_lookups\n          ; eapply step_didnt_appear with (ms := [])\n          ; try rewrite app_nil_r\n          ; simpl; eauto\n          ; intros\n          ; clean_map_lookups\n          ; trivial\n          ; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto].\n\n  - eapply IHstep_user in H28; eauto.\n      \n  - dt bd2'; clean_map_lookups\n    ; eapply step_didnt_appear with (ms := [])\n    ; try rewrite app_nil_r\n    ; simpl; eauto.\n\n    clean_map_lookups; trivial.\n    \n    intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n\n  - dt bd2'; clean_map_lookups\n    ; eapply step_didnt_appear with (ms := [])\n    ; try rewrite app_nil_r\n    ; simpl; eauto.\n    \n    clean_map_lookups; trivial.\n    \n    intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n\n  - dt bd2'; clean_map_lookups\n    ; eapply step_didnt_appear with (ms := [])\n    ; try rewrite app_nil_r\n    ; simpl; eauto.\n    \n    clean_map_lookups; trivial.\n    \n    intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto.\n    intros; destruct (k_id ==n kid); subst; clean_map_lookups; eauto.\n    intros; destruct (k_id ==n kid); subst; clean_map_lookups; eauto.\nQed.\n\nLemma NoSilent_no_indexed_silent_step :\n  forall A B uid (U : RealWorld.universe A B), \n    NoSilent uid U\n    -> forall U',\n      ~ indexedRealStep uid Silent U U'.\nProof.\n  invert 1; intros; eauto.\nQed.\n\nDefinition propNoSilent {A B} (U U' : RealWorld.universe A B) :=\n  forall uid, NoSilent uid U -> NoSilent uid U'.\n\nLemma all_users_NoSilent_no_indexed_silent_step :\n  forall A B uid (U : RealWorld.universe A B),\n    (forall uid ud, U.(RealWorld.users) $? uid = Some ud -> NoSilent uid U)\n    -> forall U',\n      ~ indexedRealStep uid Silent U U'.\nProof.\n  intros.\n  unfold not; intros.\n  generalize H0; invert H0.\n  apply H in H1.\n  eapply NoSilent_no_indexed_silent_step; eauto.\nQed.\n\nLemma silent_step_nochange_other_user_inv :\n  forall {A B C} suid lbl bd bd',\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n',\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> lbl = Silent\n      -> forall cmdc u_id1 u_id2 ud2,\n          suid = Some u_id1\n          -> u_id1 <> u_id2\n          -> usrs $? u_id1 = Some {| key_heap := ks;\n                                    protocol := cmdc;\n                                    msg_heap := qmsgs;\n                                    c_heap   := mycs;\n                                    from_nons := froms;\n                                    sent_nons := sents;\n                                    cur_nonce := cur_n |}\n          -> usrs' $? u_id2 = Some ud2\n          -> usrs $? u_id2 = Some ud2.\nProof.\n  induction 1; inversion 1; inversion 1\n  ; intros; subst\n  ; try discriminate\n  ; try solve [ clean_map_lookups; trivial ]\n  ; eauto.\nQed.\n\nLemma propNoSilent_silent_step :\n  forall A B (U U': RealWorld.universe A B) uid,\n    indexedRealStep uid Silent U U'\n    -> honest_heaps_sane U.(users) U.(all_ciphers) U.(all_keys)\n    -> propNoSilent U U'.\nProof.\n  unfold propNoSilent; intros.\n  invert H1.\n  constructor; unfold not; intros.\n\n  destruct (uid ==n uid0); subst.\n\n  apply H2 in H; auto.\n\n  invert H; invert H1.\n  destruct U, userData, userData0.\n  unfold build_data_step, buildUniverse in *; simpl in *; clean_map_lookups.\n\n  pose proof (silent_step_then_silent_step_inv H4).\n  pose proof (silent_step_nochange_other_user_inv H4).\n\n  specialize (H6 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ eq_refl eq_refl eq_refl).\n  specialize (H6 _ _ _ _ eq_refl n H3 H).\n  \n  specialize (H1 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ eq_refl eq_refl eq_refl eq_refl H3).\n  specialize (H1 _ _ _ _ _ _ _ _ _ _ _ _ _ H5 n H6 eq_refl H eq_refl).\n\n  specialize (H1 H0).\n\n  split_ex.\n  dt x.\n  eapply H2.\n  econstructor; simpl; eauto.\nQed.\n\nLemma ssteps_inv_silent :\n  forall A B st st',\n    (@stepSS A B) ^* st st'\n    -> forall (U U' : RealWorld.universe A B) uid U__i b,\n      st = (U,U__i,b)\n      -> indexedRealStep uid Silent U U'\n      -> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent U U')\n      -> exists U__r,\n          indexedRealStep uid Silent U U__r\n          /\\ (  st' = (U,U__i,b)\n               \\/  (stepSS (t__adv := B) ^* (U__r,U__i,b) st')\n            )\n          /\\ ( honest_heaps_sane U.(users) U.(all_ciphers) U.(all_keys)\n            -> propNoSilent U U__r ).\nProof.\n  intros.\n  subst; invert H.\n  - eexists; eauto 8 using propNoSilent_silent_step.\n  - invert H0; repeat equality1.\n    invert H.\n    + apply indexedModelStep_user_step in H6; split_ex; split_ors; subst.\n      * destruct ( uid ==n u_id ); subst.\n        clear H1 H4.\n        \n        eexists; repeat simple apply conj; eauto using propNoSilent_silent_step.\n        exfalso.\n\n        destruct (le_gt_dec u_id uid).\n        assert (uid > u_id) by lia.\n        eapply H5; eauto.\n        eapply H2; eauto.\n        \n      * invert H; invert H4.\n        exfalso.\n        clean_map_lookups\n        ; pose proof (user_step_label_deterministic _ _ _ _ _ _ _ _ _ H7 H8); discriminate.\n\n    + eapply H4 in H1; contradiction.\nQed.\n\nLemma ssteps_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 iu b,\n        st = (ru,iu,b)\n        -> st = st'\n          \\/ exists uid ru' iu0 iu' 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            /\\ (@stepSS A B) ^* (ru',iu',b) st'.\nProof.\n  intros; subst.\n  invert H0; clear_mislabeled_steps; eauto.\n  right.\n\n  invert H2; repeat equality1.\n  invert H0.\n  - exfalso; eapply H; eauto.\n  - invert H6; try contradiction.\n    clear_mislabeled_steps.\n    eauto 12.\nQed.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/src/ModelCheck/InvariantSearchLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.1763246495127315}}
{"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 Spec.\n\n  Definition table_map2_spec (g_rd: Pointer) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level with\n    | VZ64 map_addr, VZ64 level =>\n      rely is_int64 map_addr; rely (level >=? 3); rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      rely (peq (base g_rd) ginfo_loc);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx; rely is_gidx root_gidx;\n      when adt == query_oracle adt;\n      let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n      (* hold root lock *)\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n      rely (gtype groot =? GRANULE_STATE_TABLE);\n      (* walk deeper root *)\n      let entry0 := (g_data (gnorm groot)) @ idx0 in\n      rely is_int64 entry0;\n      let phys0 := __entry_to_phys entry0 3 in\n      let lv1_gidx := __addr_to_gidx phys0 in\n      if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n        (* level 1 valid, hold level 1 lock *)\n        let glv1 := (gs (share adt)) @ lv1_gidx in\n        rely prop_dec (glock glv1 = None);\n        rely (tbl_level (gaux glv1) =? 1);\n        (* walk deeper level 1 *)\n        rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n        rely (gtype glv1 =? GRANULE_STATE_TABLE);\n        let entry1 := (g_data (gnorm glv1)) @ idx1 in\n        rely is_int64 entry1;\n        let phys1 := __entry_to_phys entry1 3 in\n        let lv2_gidx := __addr_to_gidx phys1 in\n        if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n          (* level 2 valid, hold level 2 lock *)\n          let glv2 := (gs (share adt)) @ lv2_gidx in\n          rely (tbl_level (gaux glv2) =? 2);\n          rely prop_dec (glock glv2 = None);\n          if level =? 3 then\n            (* walk until level 2 *)\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n            map_table lv2_gidx idx2 level adt\n          else\n            (* walk deeper level 2 *)\n            rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);\n            rely (gtype glv2 =? GRANULE_STATE_TABLE);\n            let entry2 := (g_data (gnorm glv2)) @ idx2 in\n            rely is_int64 entry2;\n            let phys2 := __entry_to_phys entry2 3 in\n            let lv3_gidx := __addr_to_gidx phys2 in\n            if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then\n              (* level 2 valid, hold level 2 lock *)\n              let adt := adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv3_gidx) :: log adt} in\n              let glv3 := (gs (share adt)) @ lv3_gidx in\n              rely prop_dec (glock glv3 = None);\n              rely (tbl_level (gaux glv3) =? 3);\n              if level =? 4 then\n                (* walk until level 3 *)\n                let adt :=  adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in\n                map_table lv3_gidx idx3 level adt\n              else (* can't be other level *)\n                None\n            else\n              (* level 3 invalid *)\n              Some (adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: log adt}\n                        {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n        else\n          (* level 2 invalid *)\n          Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n      else\n        (* level 1 invalid *)\n        Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef2/Specs/table_map2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.17619485834545937}}
{"text": "(* ssreflect *)\n\nRequire Import ssreflect ssrbool ssrfun seq eqtype fintype.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import pos.\nRequire Import compcert_linking.\nRequire Import linking_proof.\nRequire Import context_equiv.\nRequire Import simulations.\nRequire Import rc_semantics.\nRequire Import nucular_semantics.\nRequire Import closed_simulations_lemmas.\nRequire Import safe_clight_rc.\nRequire Import Asm_coop.\nRequire Import Asm_nucular.\nRequire Import CompositionalCompiler.\n\n(** * Contextual Equivalence for CompCert Clight->x86 Asm *)\n\n(** Notations and convenient definitions: *)\n\nNotation Clight_module := (program Clight.fundef Ctypes.type).\nNotation Asm_module := (Asm_comp.program).\n\nDefinition mk_src_sem (p : Clight_module) :=\n  let ge := Genv.globalenv p in \n  @Modsem.mk Clight.fundef Ctypes.type ge Clight_coop.CL_core (Clight_eff.CL_eff_sem1 hf).\n\nDefinition mk_tgt_sem (tp : Asm_module) :=\n  let tge := Genv.globalenv tp in\n  @Modsem.mk Asm_comp.fundef unit tge Asm_coop.state (Asm_eff.Asm_eff_sem hf).\n\n(** Apply the contextual equivalence functor from [linking/context_equiv.v] to\n[linking/linking_proof.v]. *)\n\nModule CE := ContextEquiv LinkingSimulation.\n\nLemma compcert_equiv  \n(** There are [N] modules. *)\n  (N : pos)\n\n(** Source and target modules. ['I_N -> A], for [A : Type], is the type of finite\n  functions from [{0..N-1}] to [A]. *)\n  (source_modules : 'I_N -> Clight_module)\n  (target_modules : 'I_N -> Asm_module)\n\n(** The function [plt] maps a subset of the possible function names to the\n  modules in which they are defined. *)\n  (plt : ident -> option 'I_N) \n\n(** The entry point *)\n  (main : val) :\n\n(** Wrap the source and target modules as 'Modsem's (as in Section 3). *)\n  let sems_S (ix : 'I_N) := mk_src_sem (source_modules ix) in\n  let sems_T (ix : 'I_N) := mk_tgt_sem (target_modules ix) in\n  let prog_S := Prog.mk sems_S main in\n  let prog_T := Prog.mk sems_T main in\n\n(** [ge_top] and the two [domeq_*] hypotheses below constrain the source--target\n  global envs. of the modules in [sems_S] and [sems_T] to have equal domain, as\n  explained in Section 3. *)\n  forall ge_top : ge_ty,\n  forall domeq_S : (forall ix : 'I_N, genvs_domain_eq ge_top (sems_S ix).(Modsem.ge)),\n\n(** No module defines the same module twice. *)\n  forall lnr : (forall ix : 'I_N, list_norepet (map fst (prog_defs (source_modules ix)))),\n\n(** The target modules are (independently) compiled from the respective\n  source modules ([transf_clight_program] compiles Clight programs to Asm). *)\n  forall transf : \n    (forall ix : 'I_N, transf_clight_program (source_modules ix) \n                     = Errors.OK (target_modules ix)),\n\n(** All of the above together imply that [prog_S] and [prog_T] are contextually\n  equivalent. *) \n  Equiv_ctx ge_top plt prog_S prog_T.\n\nProof.\nmove=> sems_S sems_T prog_S prog_T ge_top deqS lnr transf.\nhave find_syms :\n  forall (i : 'I_N) (id : ident) (bf : block),\n  Genv.find_symbol (Modsem.ge (sems_S i)) id = Some bf ->\n  Genv.find_symbol (Modsem.ge (sems_T i)) id = Some bf.\n{ move=> idx id bf; rewrite /sems_S /sems_T /=; move: (transf idx)=> H.\n  by apply transf_clight_program_preserves_syms with (s := id) in H; rewrite H. }\napply: CE.equiv=> //.\nby move=> ix; apply: Clight_RC.\nby move=> ix; apply: Asm_is_nuc.\nmove=> ix; rewrite /Prog.sems/= => m m' m'' ge c c' c'' /= H H2. \nby eapply asm_step_det; eauto.\nmove=> ix; move: (transf ix)=> H.\nby eapply transf_clight_program_correct in H; eauto.\nQed.\n\nModule PR := ProgRefines LinkingSimulation.\n\nLemma compcert_refines\n  (N : pos)\n  (source_modules : 'I_N -> Clight_module)\n  (target_modules : 'I_N -> Asm_module)\n  (plt : ident -> option 'I_N) \n  (main : val) :\n  let sems_S (ix : 'I_N) := mk_src_sem (source_modules ix) in\n  let sems_T (ix : 'I_N) := mk_tgt_sem (target_modules ix) in\n  let prog_S := Prog.mk sems_S main in\n  let prog_T := Prog.mk sems_T main in\n  forall ge_top : ge_ty,\n  forall domeq_S : (forall ix : 'I_N, genvs_domain_eq ge_top (sems_S ix).(Modsem.ge)),\n  forall lnr : (forall ix : 'I_N, list_norepet (map fst (prog_defs (source_modules ix)))),\n  forall transf : \n    (forall ix : 'I_N, transf_clight_program (source_modules ix) \n                     = Errors.OK (target_modules ix)),\n  forall EM : ClassicalFacts.excluded_middle,\n  Prog_refines ge_top plt prog_S prog_T.\nProof.\nmove=> sems_S sems_T prog_S prog_T ge_top deqS lnr transf EM.\nhave find_syms :\n  forall (i : 'I_N) (id : ident) (bf : block),\n  Genv.find_symbol (Modsem.ge (sems_S i)) id = Some bf ->\n  Genv.find_symbol (Modsem.ge (sems_T i)) id = Some bf.\n{ move=> idx id bf; rewrite /sems_S /sems_T /=; move: (transf idx)=> H.\n  by apply transf_clight_program_preserves_syms with (s := id) in H; rewrite H. }\napply: PR.refines=> //.\nby move=> ix; apply: Clight_RC.\nby move=> ix; apply: Asm_is_nuc.\nmove=> ix; rewrite /Prog.sems/= => m m' m'' ge c c' c'' /= H H2. \nby eapply asm_step_det; eauto.\nmove=> ix; move: (transf ix)=> H.\nby eapply transf_clight_program_correct in H; eauto.\nQed.  \n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/linking/CompositionalComplements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.17612674302886622}}
{"text": "Require Import concurrency.dry_machine.\nRequire Import concurrency.erased_machine.\nRequire Import concurrency.threads_lemmas.\nRequire Import concurrency.permissions.\nRequire Import concurrency.semantics.\nRequire Import concurrency.concurrent_machine.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Axioms.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\nImport Concur.\n\nModule Type MachinesSig.\n  Declare Module SEM: Semantics.\n\n  Module DryMachine := DryMachineShell SEM.\n  Module ErasedMachine := ErasedMachineShell SEM.\n\n  Module DryConc := CoarseMachine mySchedule DryMachine.\n  Module FineConc := FineMachine mySchedule DryMachine.\n  (** SC machine*)\n  Module SC := FineMachine mySchedule ErasedMachine.\n\n  Import DryMachine ThreadPool.\n  Global Ltac pf_cleanup :=\n    repeat match goal with\n           | [H1: invariant ?X, H2: invariant ?X |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: mem_compatible ?TP ?M, H2: mem_compatible ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: is_true (leq ?X ?Y), H2: is_true (leq ?X ?Y) |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M, H2: containsThread ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThreadC _ ?TP _ _) ?M |- _] =>\n             apply cntUpdateC' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThread _ ?TP _ _ _) ?M |- _] =>\n             apply cntUpdate' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           end.\n\n\nEnd MachinesSig.\n\n\nModule Type AsmContext (SEM : Semantics)\n       (Machines : MachinesSig with Module SEM := SEM).\n\n  Import Machines.\n  Parameter initU: mySchedule.schedule.\n\n  Parameter init_mem : option Memory.Mem.mem.\n  Definition init_perm  :=\n    match init_mem with\n    | Some m => Some (getCurPerm m, empty_map)\n    | None => None\n    end.\n\n  Parameter the_ge : SEM.G.\n\n  Definition coarse_semantics:=\n    DryConc.MachineSemantics initU init_perm.\n\n  Definition fine_semantics:=\n    FineConc.MachineSemantics initU init_perm.\n\n  Definition sc_semantics :=\n    SC.MachineSemantics initU None.\n\n  Definition tpc_init f arg := initial_core coarse_semantics the_ge f arg.\n  Definition tpf_init f arg := initial_core fine_semantics the_ge f arg.\n  Definition sc_init f arg := initial_core sc_semantics the_ge f arg.\n\nEnd AsmContext.\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/dry_context.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17612673957284206}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Vectors.Vector\n        Coq.ZArith.ZArith.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.EnumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.WordFacts\n        Fiat.Narcissus.Common.ComposeCheckSum\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats\n        Fiat.Narcissus.BaseFormats\n        Fiat.Narcissus.Stores.EmptyStore.\n\nRequire Import Bedrock.Word.\n\nDefinition decode_IPChecksum\n  : ByteString -> CacheDecode -> option (() * ByteString * CacheDecode) :=\n  decode_unused_word (sz := 16).\n\nDefinition encode_word {sz} (w : word sz) : ByteString :=\n  encode_word' sz w ByteString_id.\n\nFixpoint Vector_checksum_bound n {sz} (bytes :ByteBuffer.t sz) acc : InternetChecksum.W16 :=\n  match n, bytes with\n  | 0, _ => acc\n  | _, Vector.nil => acc\n  | S 0, Vector.cons x _ _ => InternetChecksum.add_bytes_into_checksum x (wzero _) acc\n  | _, Vector.cons x _ Vector.nil => InternetChecksum.add_bytes_into_checksum x (wzero _) acc\n  | S (S n'), Vector.cons x _ (Vector.cons y _ t) =>\n    (Vector_checksum_bound n' t (InternetChecksum.add_bytes_into_checksum x y acc))\n  end.\n\nDefinition ByteBuffer_checksum_bound' n {sz} (bytes : ByteBuffer.t sz) : InternetChecksum.W16 :=\n  InternetChecksum.ByteBuffer_fold_left_pair InternetChecksum.add_bytes_into_checksum n bytes (wzero _) (wzero _).\n\nLemma ByteBuffer_checksum_bound'_ok' :\n  forall n {sz} (bytes :ByteBuffer.t sz) acc,\n    Vector_checksum_bound n bytes acc =\n    InternetChecksum.ByteBuffer_fold_left_pair InternetChecksum.add_bytes_into_checksum n bytes acc (wzero _).\nProof.\n  fix IH 3.\n  destruct bytes as [ | hd sz [ | hd' sz' tl ] ]; intros; simpl.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; try reflexivity.\n    rewrite IH; reflexivity.\nQed.\n\nLemma ByteBuffer_checksum_bound'_ok :\n  forall n {sz} (bytes :ByteBuffer.t sz),\n    Vector_checksum_bound n bytes (wzero _) = ByteBuffer_checksum_bound' n bytes.\nProof.\n  intros; apply ByteBuffer_checksum_bound'_ok'.\nQed.\n\nDefinition IPChecksum_Valid_dec (n : nat) (b : ByteString)\n  : {IPChecksum_Valid n b} + {~IPChecksum_Valid n b} := weq _ _.\n\nDefinition calculate_IPChecksum {S} {sz}\n  : AlignedEncodeM (S := S) sz :=\n  (fun v =>\n     (let checksum := InternetChecksum.ByteBuffer_checksum_bound 20 v in\n      (fun v idx s => SetByteAt (n := sz) 10 v 0 (wnot (split2 8 8 checksum)) ) >>\n                                                                                (fun v idx s => SetByteAt (n := sz) 11 v 0 (wnot (split1 8 8 checksum)))) v)%AlignedEncodeM.\n\nDefinition splitLength (len: word 16) : Vector.t (word 8) 2 :=\n  Vector.cons _ (split2 8 8 len) _ (Vector.cons _ (split1 8 8 len) _ (Vector.nil _)).\n\nDefinition Pseudo_Checksum_Valid\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (n : nat) (* Number of /bits/ in checksum; needed by\n                        ByteString2ListOfChar *)\n           (b : ByteString)\n  := onesComplement (wzero 8 :: protoCode ::\n                           to_list srcAddr ++ to_list destAddr ++ to_list (splitLength udpLength)\n                           ++ (ByteString2ListOfChar n b)\n                    )%list\n     = wones 16.\n\nImport VectorNotations.\n\nDefinition pseudoHeader_checksum\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           {sz} (packet: ByteBuffer.t sz) :=\n  InternetChecksum.ByteBuffer_checksum_bound (12 + measure)\n                                             (srcAddr ++ destAddr ++ [wzero 8; protoCode] ++ (splitLength udpLength) ++ packet).\n\nInfix \"^1+\" := (InternetChecksum.OneC_plus) (at level 50, left associativity).\n\nImport InternetChecksum.\n\nDefinition pseudoHeader_checksum'\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           {sz} (packet: ByteBuffer.t sz) :=\n  ByteBuffer_checksum srcAddr ^1+\n                               ByteBuffer_checksum destAddr ^1+\n                                                             zext protoCode 8 ^1+\n                                                                               udpLength ^1+\n                                                                                          InternetChecksum.ByteBuffer_checksum_bound measure packet.\n\nLemma OneC_plus_wzero_l :\n  forall w, OneC_plus (wzero 16) w = w.\nProof. reflexivity. Qed.\n\nLemma OneC_plus_wzero_r :\n  forall w, OneC_plus w (wzero 16) = w.\nProof.\n  intros; rewrite OneC_plus_comm; reflexivity.\nQed.\n\nLemma Buffer_fold_left16_acc_oneC_plus :\n  forall {sz} (packet: ByteBuffer.t sz) acc n,\n    ByteBuffer_fold_left16 add_w16_into_checksum n packet acc =\n    OneC_plus\n      (ByteBuffer_fold_left16 add_w16_into_checksum n packet (wzero 16))\n      acc.\nProof.\n  fix IH 2.\n  unfold ByteBuffer_fold_left16 in *.\n  destruct packet as [ | hd sz [ | hd' sz' tl ] ]; intros; simpl.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; unfold add_bytes_into_checksum, add_w16_into_checksum;\n      try rewrite OneC_plus_wzero_l, OneC_plus_comm; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; unfold add_bytes_into_checksum, add_w16_into_checksum;\n      try rewrite OneC_plus_wzero_l, OneC_plus_comm; try reflexivity.\n    rewrite (IH _ tl (hd' +^+ hd ^1+ acc)).\n    rewrite (IH _ tl (hd' +^+ hd)).\n    rewrite OneC_plus_assoc.\n    reflexivity.\nQed.\n\nLemma Vector_destruct_S :\n  forall {A sz} (v: Vector.t A (S sz)),\n  exists hd tl, v = hd :: tl.\nProof.\n  repeat eexists.\n  apply VectorSpec.eta.\nDefined.\n\nLemma Vector_destruct_O :\n  forall {A} (v: Vector.t A 0),\n    v = [].\nProof.\n  intro; apply Vector.case0; reflexivity.\nQed.\n\nLtac explode_vector :=\n  unfold ByteBuffer.t in *;\n  lazymatch goal with\n  | [ v: Vector.t ?A (S ?n) |- _ ] =>\n    let hd := fresh \"hd\" in\n    let tl := fresh \"tl\" in\n    rewrite (Vector.eta v) in *;\n    set (Vector.hd v: A) as hd; clearbody hd;\n    set (Vector.tl v: Vector.t A n) as tl; clearbody tl;\n    clear v\n  | [ v: Vector.t _ 0 |- _ ] =>\n    rewrite (Vector_destruct_O v) in *; clear v\n  end.\n\nLemma pseudoHeader_checksum'_ok :\n  forall (srcAddr : ByteBuffer.t 4)\n        (destAddr : ByteBuffer.t 4)\n         (measure : nat)\n         (udpLength : word 16)\n         (protoCode : word 8)\n         {sz} (packet: ByteBuffer.t sz),\n    pseudoHeader_checksum srcAddr destAddr measure udpLength protoCode packet =\n    pseudoHeader_checksum' srcAddr destAddr measure udpLength protoCode packet.\nProof.\n  unfold pseudoHeader_checksum, pseudoHeader_checksum'.\n  intros.\n  repeat explode_vector.\n  Opaque split1.\n  Opaque split2.\n  simpl in *.\n  unfold ByteBuffer_checksum, InternetChecksum.ByteBuffer_checksum_bound, add_w16_into_checksum,\n  add_bytes_into_checksum, ByteBuffer_fold_left16, ByteBuffer_fold_left_pair.\n  fold @ByteBuffer_fold_left_pair.\n  setoid_rewrite Buffer_fold_left16_acc_oneC_plus.\n  rewrite combine_split.\n  rewrite !OneC_plus_wzero_r, !OneC_plus_wzero_l, OneC_plus_comm.\n  repeat (f_equal; [ ]).\n  rewrite <- !OneC_plus_assoc.\n  reflexivity.\nQed.\n\nDefinition calculate_PseudoChecksum {S} {sz}\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (idx' : nat)\n  : AlignedEncodeM (S := S) sz :=\n  (fun v idx s =>\n     (let checksum := pseudoHeader_checksum' srcAddr destAddr measure udpLength protoCode v in\n      (fun v idx s => SetByteAt (n := sz) idx' v 0 (wnot (split2 8 8 checksum)) ) >>\n                                                                                  (fun v idx s => SetByteAt (n := sz) (1 + idx') v 0 (wnot (split1 8 8 checksum)))) v idx s)%AlignedEncodeM.\n\nLemma ByteBuffer_to_list_append {sz sz'}\n  : forall (v : ByteBuffer.t sz)\n           (v' : ByteBuffer.t sz'),\n    ByteBuffer.to_list (v ++ v')%vector\n    = ((ByteBuffer.to_list v) ++ (ByteBuffer.to_list v'))%list.\nProof.\n  induction v.\n  - reflexivity.\n  - simpl; intros.\n    unfold ByteBuffer.to_list at 1; unfold to_list.\n    f_equal.\n    apply IHv.\nQed.\n\nImport VectorNotations.\n\n\nLemma Pseudo_Checksum_Valid_bounded\n      {A}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      protoCode\n      (predicate : A -> Prop)\n      (format_A format_B : FormatM A ByteString)\n      (len_format_A : A -> nat)\n      (len_format_A_OK : forall a' b ctx ctx',\n          computes_to (format_A a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_A a')\n      (len_format_B : A -> nat)\n      (len_format_B_OK : forall a' b ctx ctx',\n          computes_to (format_B a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_B a')\n      (byte_aligned_A : forall a : A, len_format_A a mod 8 = 0)\n      (byte_aligned_B : forall a : A, len_format_B a mod 8 = 0)\n  : forall (data : A) (x : ByteString) (x0 : CacheFormat) (x1 : ByteString) (x2 : CacheFormat)\n           (ext ext' : ByteString) (env : CacheFormat) (c : word 16),\n    predicate data ->\n    format_A data env \u220b (x, x0) ->\n    format_B data (addE x0 16) \u220b (x1, x2) ->\n    Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode\n                          (bin_measure (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)))\n                          (mappend (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)) ext) ->\n    Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode\n                          (bin_measure (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)))\n                          (mappend (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)) ext').\nProof.\n  intros.\n    unfold Pseudo_Checksum_Valid in *.\n    revert H2.\n    rewrite !ByteString2ListOfChar_Over; eauto.\n    simpl; rewrite padding_eq_mod_8.\n    rewrite !length_ByteString_enqueue_ByteString.\n    rewrite Nat.add_mod by omega.\n    apply len_format_A_OK in H0.\n    apply len_format_B_OK in H1.\n    unfold format_checksum; rewrite length_encode_word', measure_mempty.\n    rewrite H0, byte_aligned_A, plus_O_n, NPeano.Nat.mod_mod, Nat.add_mod by omega.\n    rewrite H1, byte_aligned_B, <- plus_n_O, NPeano.Nat.mod_mod by omega.\n    reflexivity.\n    simpl; rewrite padding_eq_mod_8.\n    rewrite !length_ByteString_enqueue_ByteString.\n    rewrite Nat.add_mod by omega.\n    apply len_format_A_OK in H0.\n    apply len_format_B_OK in H1.\n    rewrite H0, byte_aligned_A, plus_O_n, NPeano.Nat.mod_mod, Nat.add_mod by omega.\n    rewrite H1, byte_aligned_B, <- plus_n_O, NPeano.Nat.mod_mod by omega.\n    unfold format_checksum; rewrite length_encode_word'; reflexivity.\nQed.\n\nLemma compose_PseudoChecksum_format_correct' {A}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      protoCode\n      (predicate : A -> Prop)\n      (P : CacheDecode -> Prop)\n      (P_inv : (CacheDecode -> Prop) -> Prop)\n      (P_invM : (CacheDecode -> Prop) -> Prop)\n      (format_A format_B : FormatM A ByteString)\n      (subformat : FormatM A ByteString)\n      (decode_measure : DecodeM (nat * _) _)\n      (len_format_A : A -> nat)\n      (len_format_A_OK : forall a' b ctx ctx',\n          computes_to (format_A a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_A a')\n      (len_format_B : A -> nat)\n      (len_format_B_OK : forall a' b ctx ctx',\n          computes_to (format_B a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_B a')\n      View_Predicate\n      format_measure\n  : cache_inv_Property P (fun P => P_inv P /\\ P_invM P) ->\n    (forall a, NPeano.modulo (len_format_A a) 8 = 0)\n    -> (forall a, NPeano.modulo (len_format_B a) 8 = 0)\n    ->\n    forall decodeA : _ -> CacheDecode -> option (A * _ * CacheDecode),\n      (cache_inv_Property P P_inv ->\n       CorrectDecoder monoid predicate predicate eq (format_A ++ format_unused_word 16 ++ format_B)%format decodeA P (format_A ++ format_unused_word 16 ++ format_B)%format) ->\n      (cache_inv_Property P P_invM ->\n          CorrectRefinedDecoder monoid predicate View_Predicate\n                                (fun a n => len_format_A a + 16 + len_format_B a = n * 8)\n                                (format_A ++ format_unused_word 16 ++ format_B)%format\n                                subformat\n                                decode_measure P\n                                format_measure) ->\n      (Prefix_Format _ (format_A ++ format_unused_word 16 ++ format_B) subformat)%format->\n      CorrectDecoder monoid predicate predicate eq\n                     (format_A ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16 ThenCarryOn format_B)\n                     (fun (bin : _) (env : CacheDecode) =>\n                          `(n, _, _) <- decode_measure bin env;\n                            if weqb (onesComplement (wzero 8 :: protoCode ::\n                                                       to_list srcAddr ++ to_list destAddr ++ to_list (splitLength udpLength)\n                                                       ++(ByteString2ListOfChar (n * 8) bin))%list) (wones 16) then\n                              decodeA bin env\n                            else None)\n                     P\n                     (format_A ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16 ThenCarryOn format_B).\nProof.\n  intros.\n  rename H4 into H4'; rename H3 into H4; rename H2 into H3.\n  eapply format_decode_correct_alt.\n  Focus 7.\n  (*7: {*)\n  {eapply (composeChecksum_format_correct'\n                 A _ monoid _ 16 (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode)).\n       - eapply H.\n       - specialize (H4 (proj2 H)).\n         split.\n         2: eauto.\n         eapply injection_decode_correct with (inj := fun n => mult n 8).\n         4: simpl.\n         eapply H4.\n         + intros.\n           instantiate (1 := fun a n => len_format_A a + 16 + len_format_B a = n).\n           eapply H6.\n         + intros; instantiate (1 := fun v => View_Predicate (Nat.div v 8)).\n           cbv beta.\n           rewrite Nat.div_mul; eauto.\n         + intros; apply unfold_computes; intros.\n           split.\n           2: rewrite unfold_computes in H5; intuition.\n           intros.\n           rewrite unfold_computes in H5; intuition.\n           instantiate (1 := fun v env t => format_measure (Nat.div v 8) env t).\n           cbv beta; rewrite Nat.div_mul; eauto.\n       - simpl; intros.\n         destruct t1; destruct t2; simpl fst in *; simpl snd in *.\n         apply unfold_computes in H7; apply unfold_computes in H6.\n         erewrite len_format_A_OK; eauto.\n         erewrite (len_format_B_OK _ b0); eauto.\n         unfold format_checksum; rewrite length_encode_word', measure_mempty.\n         rewrite <- H2; omega.\n       - eauto.\n       - eapply Pseudo_Checksum_Valid_bounded; eauto. }\n  all: try unfold flip, pointwise_relation, impl;\n    intuition eauto using EquivFormat_reflexive.\n  all: try unfold flip, pointwise_relation, impl;\n    intuition eauto using EquivFormat_reflexive.\n    instantiate (1 := fun (n : nat) a =>\n                    weq\n       (onesComplement\n          (wzero 8\n           :: (protoCode\n               :: to_list srcAddr ++\n                  to_list destAddr ++ to_list (splitLength udpLength) ++ ByteString2ListOfChar n a)%list))\n       (wones 16)).\n  unfold Compose_Decode.\n  Local Opaque Nat.div.\n  destruct (decode_measure a a0) as [ [ [? ?] ? ] | ]; simpl; eauto.\n  symmetry.\n  find_if_inside.\n  eapply weqb_true_iff in e; rewrite e; eauto.\n  destruct (weqb\n      (add_bytes_into_checksum (wzero 8) protoCode\n         (onesComplement\n            (to_list srcAddr ++\n             to_list destAddr ++ split2 8 8 udpLength :: (split1 8 8 udpLength :: ByteString2ListOfChar (n * 8) a)%list)))\n      WO~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1) eqn: ? ; eauto.\n  eapply weqb_true_iff in Heqb0.\n  congruence.\nQed.\n\nFixpoint aligned_Pseudo_checksum\n         (srcAddr : ByteBuffer.t 4)\n         (destAddr : ByteBuffer.t 4)\n         (pktlength : word 16)\n         id\n         measure\n         {sz}\n         (v : t Core.char sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       weqb (pseudoHeader_checksum' srcAddr destAddr measure pktlength id v)\n            (wones 16)\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v' idx'\n       | _ => false\n       end\n     end.\n\nLemma Vector_checksum_bound_acc'\n  : forall sz'' sz sz' (sz_lt : le sz' sz'') (v : Vector.t _ sz) b1 b2 acc,\n    Vector_checksum_bound sz' v (add_bytes_into_checksum b1 b2 acc) =\n    add_bytes_into_checksum b1 b2 (Vector_checksum_bound sz' v acc).\nProof.\n  induction sz''; intros.\n  - inversion sz_lt.\n    subst; reflexivity.\n  - inversion sz_lt; subst.\n    + clear sz_lt.\n      destruct sz''; simpl.\n      * destruct v; simpl; eauto.\n        rewrite add_bytes_into_checksum_swap; eauto.\n      * destruct v; simpl; eauto.\n        destruct v; simpl; eauto.\n        rewrite add_bytes_into_checksum_swap; eauto.\n        rewrite !IHsz'' by omega.\n        rewrite add_bytes_into_checksum_swap; eauto.\n    + eauto.\nQed.\n\nLemma Vector_checksum_bound_acc\n  : forall sz sz' (v : Vector.t _ sz) b1 b2 acc,\n    Vector_checksum_bound sz' v (add_bytes_into_checksum b1 b2 acc) =\n    add_bytes_into_checksum b1 b2 (Vector_checksum_bound sz' v acc).\nProof.\n  intros; eapply Vector_checksum_bound_acc'.\n  reflexivity.\nQed.\n\nLemma dequeue_byte_ByteString2ListOfChar\n  : forall m sz (v : Vector.t _ sz) b,\n    ByteString2ListOfChar ((S m) * 8) (build_aligned_ByteString (b :: v))\n    = cons b (ByteString2ListOfChar (m * 8) (build_aligned_ByteString (v))).\nProof.\n  intros; erewrite <- ByteString2ListOfChar_push_char.\n  f_equal.\n  pose proof (build_aligned_ByteString_append v [b]) as H; simpl in H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma ByteString2ListOfChar_overflow\n  : forall n,\n    ByteString2ListOfChar ((S n) * 8) (build_aligned_ByteString [])\n    = cons (wzero 8) (ByteString2ListOfChar (n * 8) (build_aligned_ByteString [])).\nProof.\n  reflexivity.\nQed.\n\nLemma InternetChecksum_To_ByteBuffer_Checksum':\n  forall (sz m : nat) (v : t Core.char sz),\n    checksum (ByteString2ListOfChar (m * 8) (build_aligned_ByteString v)) = ByteBuffer_checksum_bound m v.\nProof.\n  intros.\n  assert ((exists m', m = 2 * m') \\/ (exists m', m = S (2 * m'))).\n  { induction m; eauto.\n    destruct IHm; destruct_ex; subst; eauto.\n    left; exists (S x); omega.\n  }\n  destruct H as [ [? ?] | [? ?] ]; subst.\n  - rewrite (mult_comm 2).\n    apply InternetChecksum_To_ByteBuffer_Checksum.\n  - revert sz v.\n    induction x.\n    + intros; destruct v.\n      * reflexivity.\n      * rewrite dequeue_byte_ByteString2ListOfChar.\n        reflexivity.\n    + intros; destruct v.\n      * replace (S (2 * S x)) with ((S (S (S (2 * x))))) by omega.\n        rewrite ByteString2ListOfChar_overflow.\n        rewrite ByteString2ListOfChar_overflow.\n        unfold checksum; fold checksum.\n        rewrite IHx.\n        unfold ByteBuffer_checksum_bound, ByteBuffer_fold_left16.\n        simpl.\n        destruct (2 * x); eauto.\n      * rewrite dequeue_byte_ByteString2ListOfChar.\n        destruct v.\n        replace (2 * S x * 8) with ((S (S (2 * x))) * 8) by omega.\n        rewrite ByteString2ListOfChar_overflow.\n        unfold checksum; fold checksum.\n        rewrite IHx.\n        rewrite <- !ByteBuffer_checksum_bound_ok.\n        simpl.\n        destruct (2 * x); eauto.\n        replace (2 * S x * 8) with ((S (S (2 * x))) * 8) by omega.\n        rewrite dequeue_byte_ByteString2ListOfChar.\n        replace\n          (checksum (h :: (h0 :: ByteString2ListOfChar (S (2 * x) * 8) (build_aligned_ByteString v))%list))\n          with\n            (add_bytes_into_checksum\n               h h0\n               (checksum (ByteString2ListOfChar (S (2 * x) * 8) (build_aligned_ByteString v))%list))\n          by reflexivity.\n        rewrite IHx.\n        rewrite <- !ByteBuffer_checksum_bound_ok.\n        replace (2 * S x) with (S (S ( 2 * x))) by omega.\n        rewrite <- Vector_checksum_bound_acc; reflexivity.\nQed.\n\nLemma aligned_Pseudo_checksum_OK_1\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (pktlength : word 16)\n      id\n      measure\n      {sz}\n  : forall (v : t Core.char sz),\n    weqb\n      (InternetChecksum.add_bytes_into_checksum (wzero 8) id\n                                                (onesComplement(to_list srcAddr ++ to_list destAddr ++ split2 8 8  pktlength :: split1 8 8 pktlength :: (ByteString2ListOfChar (measure * 8) (build_aligned_ByteString v)))%list))\n      WO~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n    = aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v 0.\nProof.\n  simpl; intros.\n  unfold onesComplement.\n  rewrite <- pseudoHeader_checksum'_ok.\n  rewrite checksum_eq_Vector_checksum.\n  unfold pseudoHeader_checksum.\n  rewrite <- ByteBuffer_checksum_bound_ok.\n  unfold ByteBuffer.t in *.\n  simpl.\n    replace srcAddr with\n      (Vector.hd srcAddr :: Vector.hd (Vector.tl srcAddr)\n                 :: Vector.hd (Vector.tl (Vector.tl srcAddr))\n                 :: Vector.hd (Vector.tl (Vector.tl (Vector.tl srcAddr)))\n                 :: (@Vector.nil _))\n    by abstract (pattern srcAddr;\n              repeat (apply caseS'; let t' := fresh in intros ? t'; pattern t'); apply case0;\n              reflexivity).\n  replace destAddr with\n      (Vector.hd destAddr :: Vector.hd (Vector.tl destAddr)\n                 :: Vector.hd (Vector.tl (Vector.tl destAddr))\n                 :: Vector.hd (Vector.tl (Vector.tl (Vector.tl destAddr)))\n                 :: (@Vector.nil _))\n    by abstract (pattern destAddr;\n              repeat (apply caseS'; let t' := fresh in intros ? t'; pattern t'); apply case0;\n              reflexivity).\n  simpl.\n  repeat rewrite Vector_checksum_bound_acc.\n  rewrite <- checksum_eq_Vector_checksum.\n  f_equal.\n  rewrite ByteBuffer_checksum_bound_ok.\n  repeat rewrite (add_bytes_into_checksum_swap _ id); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl srcAddr))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl (Vector.tl (Vector.tl srcAddr))))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl destAddr))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl (Vector.tl (Vector.tl destAddr))))); f_equal.\n  f_equal.\n  apply InternetChecksum_To_ByteBuffer_Checksum'.\nQed.\n\nLemma aligned_Pseudo_checksum_OK_2\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (pktlength : word 16)\n      id\n      measure\n      {sz}\n  : forall (v : ByteBuffer.t (S sz)) (idx : nat),\n    aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v (S idx) =\n    aligned_Pseudo_checksum srcAddr destAddr pktlength id measure (Vector.tl v) idx.\nProof.\n  intros v; pattern sz, v.\n  apply Vector.caseS; reflexivity.\nQed.\n\nFixpoint aligned_IPchecksum\n         m\n         {sz}\n         (v : t Core.char sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       weqb (InternetChecksum.ByteBuffer_checksum_bound m v) (wones 16)\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => aligned_IPchecksum m v' idx'\n       | _ => false\n       end\n     end.\n\nCorollary aligned_IPChecksum_OK_1 :\n  forall m sz (v : ByteBuffer.t sz),\n    IPChecksum_Valid_check (m * 8) (build_aligned_ByteString v)\n    = aligned_IPchecksum m v 0.\nProof.\n  intros.\n  unfold IPChecksum_Valid_check, aligned_IPchecksum.\n  rewrite InternetChecksum_To_ByteBuffer_Checksum'.\n  higher_order_reflexivity.\nQed.\n\nLemma aligned_IPChecksum_OK_2\n      m\n      {sz}\n  : forall (v : ByteBuffer.t (S sz)) (idx : nat),\n    aligned_IPchecksum m v (S idx) =\n    aligned_IPchecksum m (Vector.tl v) idx.\nProof.\n  intros v; pattern sz, v.\n  apply Vector.caseS; reflexivity.\nQed.\n\nHint Extern 4 (weqb _ _ = _) =>\nrewrite aligned_Pseudo_checksum_OK_1; higher_order_reflexivity.\nHint Extern 4 => eapply aligned_Pseudo_checksum_OK_2.\n\nHint Extern 4 (IPChecksum_Valid_check _ _ = _ ) =>\nrewrite aligned_IPChecksum_OK_1; higher_order_reflexivity.\nHint Extern 4  => eapply aligned_IPChecksum_OK_2.\n\nLtac destruct_unit :=\n  repeat match goal with\n         | v : () |- _ => destruct v\n         end.\n\nLtac solve_seq_padding :=\n  repeat (intros; match goal with\n                  | H : sequence_Encode ?e1 ?e2 _ _ = Some (?t, _) |- padding ?t = 0 =>\n                    eapply sequence_Encoding_padding_0 in H; eauto\n                  end).\n\nLemma EncodeMEquivAlignedEncodeMForChecksum\n      {S A}\n      (enc1' enc2' enc3' : EncodeM S ByteString)\n      (encA' : A -> EncodeM S ByteString)\n      (f' : ByteString -> A)\n      (enc1 enc2 enc3 : forall sz, AlignedEncodeM sz)\n      (encA : A -> forall sz, AlignedEncodeM sz)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> A)\n      (enc1_OK : EncodeMEquivAlignedEncodeM enc1' enc1)\n      (enc2_OK : EncodeMEquivAlignedEncodeM enc2' enc2)\n      (enc3_OK : EncodeMEquivAlignedEncodeM enc3' enc3)\n      (encA_OK : forall a, EncodeMEquivAlignedEncodeM (encA' a) (encA a))\n      (enc1'_aligned : forall s ce t ce', enc1' s ce = Some (t, ce') -> padding t = 0)\n      (enc2'_aligned : forall s ce t ce', enc2' s ce = Some (t, ce') -> padding t = 0)\n      (enc3'_aligned : forall s ce t ce', enc3' s ce = Some (t, ce') -> padding t = 0)\n      (encA'_aligned : forall a s ce t ce', encA' a s ce = Some (t, ce') -> padding t = 0)\n      (enc'_sz_eq : forall s a ce t1 ce1 t2 ce2,\n          enc2' s ce = Some (t1, ce1) ->\n          encA' a s ce = Some (t2, ce2) ->\n          bin_measure t1 = bin_measure t2)\n      (f_OK : forall (b : ByteString)\n                idx (v1 : Vector.t Core.char idx)\n                m (v2 : Vector.t Core.char m)\n                (v : Vector.t Core.char (idx + ((numBytes b) + m))),\n          ByteString_enqueue_ByteString (build_aligned_ByteString v1)\n                                        (ByteString_enqueue_ByteString b (build_aligned_ByteString v2))\n          = build_aligned_ByteString v ->\n          f' b = f (numBytes b) v idx)\n  : EncodeMEquivAlignedEncodeM\n      (fun s ce =>\n         `(p, _) <- sequence_Encode enc1' (sequence_Encode enc2' enc3') s ce;\n           (fun a => (sequence_Encode enc1' (sequence_Encode (encA' a) enc3'))) (f' p) s ce)\n      (fun sz => EncodeAgain (enc1 sz >> enc2 sz >> enc3 sz)\n                          (fun idx' v idx s =>\n                             (fun a sz => enc1 sz >> encA a sz >> enc3 sz)\n                               (f (idx'-idx) v idx) sz v idx s))%AlignedEncodeM.\nProof.\n  apply EncodeMEquivAlignedEncodeMDep; eauto; intros;\n    repeat (apply Append_EncodeMEquivAlignedEncodeM; eauto);\n    solve_seq_padding.\n  apply sequence_Encoding_inv in H.\n  apply sequence_Encoding_inv in H0. destruct_conjs.\n  apply sequence_Encoding_inv in H9.\n  apply sequence_Encoding_inv in H4. destruct_conjs.\n  subst. rewrite !mappend_measure.\n  simpl in *. destruct_unit.\n  substss. injections. eauto.\nQed.\n\nDefinition f_bit_aligned_free {A} (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> A)\n  : ByteString -> A :=\n  fun bs => f (numBytes bs) (byteString bs) 0.\n\nLemma CorrectAlignedEncoderForChecksum\n      {S}\n      checksum_sz (checksum_valid : nat -> ByteString -> Prop)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A encode_B : forall sz, AlignedEncodeM sz)\n      (encode_C' : forall sz, AlignedEncodeM sz)\n      (encode_C : word checksum_sz -> forall sz, AlignedEncodeM sz)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> word checksum_sz)\n      (f_OK : forall idx n m (t : Vector.t Core.char n)\n                (v1 : Vector.t Core.char idx) (v2 : Vector.t Core.char m),\n         f n t 0 = f n (v1 ++ t ++ v2) idx)\n      (enc2' : EncodeM S ByteString)\n      (enc2_OK : EncodeMEquivAlignedEncodeM enc2' encode_C')\n      (encode_C_OK : forall a, EncodeMEquivAlignedEncodeM\n                            ((fun a _ ce => Some (format_checksum _ _ _ _ a, ce)) a) (encode_C a))\n      (enc2'_aligned : forall s ce t ce', enc2' s ce = Some (t, ce') -> padding t = 0)\n      n1\n      (format_B_sz_eq : forall s ce t ce',\n          format_B s ce \u220b (t, ce') -> bin_measure t = n1)\n      (checksum_sz_OK : checksum_sz mod 8 = 0)\n      (checksum_sz_OK' : forall s ce t ce', enc2' s ce = Some (t, ce') ->\n                                       checksum_sz = bin_measure t)\n      (checksum_OK : forall s ce b' ce',\n          enc2' s ce = Some (b', ce') ->\n          forall b1 b3 ext,\n            (exists s ce ce', format_B s ce \u220b (b1, ce')) ->\n            (exists s ce ce', format_A s ce \u220b (b3, ce')) ->\n            let a := (f_bit_aligned_free f) (mappend b1 (mappend b' b3)) in\n            let b2 := format_checksum _ _ _ checksum_sz a in\n            checksum_valid\n              (bin_measure (mappend b1 (mappend b2 b3)))\n              (mappend (mappend b1 (mappend b2 b3)) ext))\n      (checksum_OK' : forall s ce,\n          enc2' s ce = None ->\n          forall b1 b2 b3 ext,\n            ~checksum_valid\n              (bin_measure (mappend b1 (mappend b2 b3)))\n              (mappend (mappend b1 (mappend b2 b3)) ext))\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum checksum_valid OfSize checksum_sz ThenCarryOn format_A)\n      (fun sz => EncodeAgain (encode_B sz >> encode_C' sz >> encode_A sz)\n                          (fun idx' v idx s =>\n                             encode_C (f (idx'-idx) v idx) sz v (idx+n1/8) s))%AlignedEncodeM.\nProof.\n  destruct encoder_A_OK as [enc3' [HA1 [HA2 HA3]]].\n  destruct encoder_B_OK as [enc1' [HB1 [HB2 HB3]]].\n  exists (fun s ce =>\n       `(p, _) <- sequence_Encode enc1' (sequence_Encode enc2' enc3') s ce;\n       (fun a => (sequence_Encode enc1' (sequence_Encode\n                                        ((fun a _ ce => Some (format_checksum _ _ _ _ a, ce)) a)\n                                        enc3'))) ((f_bit_aligned_free f) p) s ce).\n  split; [| split]; intros.\n  - unfold composeChecksum, sequence_Encode. split; intros; simpl in *.\n    + intros [? ?]. intros.\n      computes_to_inv. injections.\n      destruct enc1' eqn:Henc1; [| discriminate]; destruct_conjs; simpl in *.\n      destruct enc2' eqn:Henc2; [| discriminate]; destruct_conjs; simpl in *.\n      destruct enc3' eqn:Henc3; [| discriminate]; destruct_conjs; simpl in *.\n      destruct_unit.\n      rewrite Henc3 in H. simpl in *. injections.\n      repeat computes_to_econstructor; eauto.\n      edestruct HB1. apply H in Henc1. apply Henc1.\n      repeat computes_to_econstructor; eauto. simpl.\n      edestruct HA1. apply H in Henc3. apply Henc3.\n      repeat computes_to_econstructor; eauto.\n      intros. eapply checksum_OK; eauto.\n      repeat eexists. simpl. apply HB1 in Henc1. eauto.\n      repeat eexists. simpl. apply HA1 in Henc3. eauto.\n      simpl. apply eq_ret_compute. repeat f_equal.\n    + intro. unfold Bind2 in H0.\n      computes_to_inv. destruct_conjs. injections. simpl in *. destruct_unit.\n      destruct enc1' eqn:Henc1; destruct_conjs; simpl in *; destruct_unit.\n      destruct enc2' eqn:Henc2; destruct_conjs; simpl in *; destruct_unit.\n      destruct enc3' eqn:Henc3; destruct_conjs; simpl in *; destruct_unit.\n      discriminate.\n      edestruct HA1. intuition eauto. intuition eauto.\n      edestruct HB1. intuition eauto.\n  - destruct sequence_Encode; [| discriminate]; destruct_conjs; simpl in *.\n    eapply sequence_Encoding_padding_0; try apply H; eauto.\n    intros.\n    eapply sequence_Encoding_padding_0; try apply H0; eauto.\n    intros. simpl in *. injections.\n    unfold format_checksum. rewrite encode_word'_padding. eauto.\n  - eapply EncodeMEquivAlignedEncodeM_morphism; cycle 1.\n    apply EncodeMEquivAlignedEncodeMForChecksum\n      with (encA' := (fun a _ ce => Some (format_checksum _ _ _ _ a, ce))); eauto.\n    + intros. injections.\n      unfold format_checksum. rewrite encode_word'_padding. eauto.\n    + intros. injections. unfold format_checksum.\n      rewrite length_encode_word'. rewrite measure_mempty.\n      apply checksum_sz_OK' in H. omega.\n    + unfold f_bit_aligned_free. instantiate (1:=f). intros.\n      assert (padding b = 0) as L1. {\n        apply (f_equal padding) in H. simpl in H.\n        rewrite padding_ByteString_enqueue_aligned_ByteString in H; eauto.\n        rewrite ByteString_enqueue_ByteString_padding_eq in H. simpl padding in H.\n        rewrite (Nat.mod_add _ 0 8) in H; eauto.\n        rewrite Nat.mod_small in H; eauto.\n        destruct b. simpl in *. auto.\n      }\n      assert (b = build_aligned_ByteString (byteString b)) as L2. {\n        revert L1. clear. intros.\n        destruct b. simpl. unfold build_aligned_ByteString. simpl in *.\n        subst. f_equal. eauto using shatter_word_0.\n        apply Core.le_uniqueness_proof.\n      }\n      revert L2 H. revert v.\n      generalize (byteString b). generalize (numBytes b). intros. rewrite L2 in H.\n      rewrite <- !build_aligned_ByteString_append in H.\n      apply build_aligned_ByteString_inj in H. subst.\n      eauto.\n    + intros. unfold EncodeAgain.\n      set (fun sz => encode_C' sz >> encode_A sz)%AlignedEncodeM as enc'.\n      set (fun sz => encode_B sz >> enc' sz)%AlignedEncodeM as enc.\n      match goal with\n      | |- context[Ifopt ?b _ _ _ _ as _ Then _ Else _] => replace b with (enc sz) by reflexivity\n      end.\n      destruct enc eqn:?; eauto.\n      destruct_conjs. simpl. unfold AppendAlignedEncodeM.\n\n      edestruct @AlignedEncoder_inv2 as [n2 [n3 [t1 [t23 [v23 ?]]]]]; try apply Heqa.\n      apply Append_EncodeMEquivAlignedEncodeM. 2 : eauto. eauto.\n      apply Append_EncodeMEquivAlignedEncodeM. 2 : eauto. eauto. eauto.\n      solve_seq_padding.\n      destruct_conjs. subst. simpl in *.\n\n      edestruct @AlignedEncoder_append_inv with (enc1:=encode_B)\n        as [nB [nC [nC3 [tB [tC3 [vB [vC3 [?ce ?]]]]]]]].\n      5 : apply H0.\n      3 : apply Append_EncodeMEquivAlignedEncodeM. all : eauto.\n      solve_seq_padding. destruct_conjs.\n      subst. simpl in *. destruct H. simpl in *.\n\n      assert (encode_B (idx + (nB + (nC + nC3))) (t1 ++ vB ++ vC3) idx w c =\n              Some (t1 ++ vB ++ vC3, idx+nB, ce)). {\n        assert (idx + nB + (nC + nC3) = idx + (nB + (nC + nC3))) as L by omega.\n        rewrite Vector_append_assoc with (H:=L). destruct L. simpl.\n        epose proof AlignedEncoder_extr as H'. eapply H'; eauto. clear H'.\n        eapply @AlignedEncoder_fixed; eauto.\n        eapply AlignedEncoder_extl; eauto.\n      } rewrite H. simpl.\n\n      assert (nB = n1/8). {\n        erewrite <- format_B_sz_eq; eauto.\n        epose proof AlignedEncoder_inv0 as L. eapply L in H1; eauto. clear L.\n        instantiate (1:=build_aligned_ByteString vB).\n        rewrite length_ByteString_no_padding; eauto.\n        rewrite Nat.mul_comm.\n        rewrite Nat.div_mul by auto.\n        reflexivity.\n        eapply HB1; eauto. eauto using AlignedEncoder_inv0.\n      } destruct H3.\n      destruct_unit. destruct encode_C eqn:?; eauto. destruct_conjs. simpl in *.\n\n      edestruct @AlignedEncoder_append_inv with (enc1:=encode_C')\n        as [nC' [nA [nA3 [tC [tA3 [vC [vA3 [?ce ?]]]]]]]]; try apply H2; eauto.\n      destruct_conjs.\n      subst. simpl in *. destruct H3. simpl in *. rename nC' into nC.\n\n      match goal with\n      | H : encode_C ?a _ _ _ _ _ = _ |- _ =>\n        edestruct @AlignedEncoder_inv with (enc:=(encode_C a))\n          as [nC' [n3' [t1C [tC' [tC3 [vC' ?]]]]]]\n      end; eauto.\n      intros. simpl in *. injections.\n      unfold format_checksum. rewrite encode_word'_padding. eauto.\n      destruct_conjs.\n\n      assert (nC = nC'). {\n        injections.\n        assert (checksum_sz = 8 * nC').\n        eapply (f_equal bin_measure) in H12. simpl in *.\n        unfold format_checksum in H12.\n        rewrite length_encode_word' in H12. rewrite measure_mempty in H12.\n        unfold length_ByteString in H12. simpl in H12. omega.\n        assert (checksum_sz = 8 * nC).\n        epose proof AlignedEncoder_inv0 as L. eapply L in H4; eauto. clear L.\n        apply checksum_sz_OK' in H4.\n        unfold length_ByteString in H4. simpl in H4. omega.\n        omega.\n      } subst nC'.\n\n      assert (n3' = nA + nA3) as L by omega. subst n3'.\n      assert (encode_A (idx + (nB + (nC + (nA + nA3)))) t n w c =\n              Some (t, n+nA, c)). {\n        rewrite (Vector_append_assoc _ _ _ H3) in H8.\n        clear Heqa0. destruct H3. simpl in *.\n        subst. apply Vector_append_inj in H8. destruct_conjs.\n        apply Vector_append_inj in H7. destruct_conjs. subst.\n        assert (idx + nB + nC + (nA + nA3) = idx + nB + (nC + (nA + nA3))) as L by omega.\n        rewrite (Vector_append_assoc _ _ _ L). destruct L. simpl.\n        epose proof AlignedEncoder_extl as L. eapply L; eauto. clear L.\n        destruct_unit.\n        eapply @AlignedEncoder_fixed; eauto.\n      } rewrite H11. simpl. reflexivity.\n      Unshelve.\n      eauto.\nQed.\n\nDefinition encode_word_const\n           {S : Type}\n           {n}\n  : word (n*8) -> forall sz, AlignedEncodeM (S:=S) sz :=\n  fun w sz v idx _ ce => SetCurrentBytes v idx w ce.\n\nDefinition encode_word_16_const {S : Type} := @encode_word_const S 2.\n\nDefinition encode_word_16_0 {S : Type} := @encode_word_16_const S (wzero 16).\n\nLemma format_word_is_encode_word {T}\n      {cache : Cache} {cacheAddNat : CacheAdd cache nat}\n      {monoid : Monoid T} {monoidUnit : QueueMonoidOpt monoid bool}\n      {n} (enc : EncodeM (word n) T)\n  : (forall s env,\n        (forall t env', enc s env = Some (t, env')\n                   -> refine (format_word s env) (ret (t, env')))\n        /\\ (enc s env = None ->\n           forall benv', ~ computes_to (format_word s env) benv')) ->\n    forall s env, enc s env = Some (encode_word' _ s mempty, addE env n).\nProof.\n  intros. destruct enc eqn:?; destruct_conjs.\n  - apply H in Heqe.\n    eapply Return_inv in Heqe; eauto. congruence.\n  - exfalso. eapply H; eauto.\n    computes_to_econstructor; eauto.\nQed.\n\nLemma EncodeMEquivAlignedEncodeM_const\n      {S A} {cache : Cache}\n      (enc' : EncodeM A ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n  : forall a, EncodeMEquivAlignedEncodeM (S:=S)\n           (fun _ ce => enc' a ce)\n           (fun sz v n _ ce => enc sz v n a ce).\nProof.\n  intros. repeat split; simpl; intros;\n            edestruct enc_OK as [? [? [? ?]]]; eauto.\nQed.\n\nLemma EncodeMEquivAlignedEncodeM_word_const\n      {S}\n      {n}\n  : forall (w : word (n*8)),\n    EncodeMEquivAlignedEncodeM\n      (fun (_ : S) env => Some (encode_word' _ w mempty, addE env (n*8)))\n      (encode_word_const w).\nProof.\n  intros.\n  destruct CorrectAlignedEncoderForFormatNChar with (sz:=n); eauto. destruct_conjs.\n  eapply EncodeMEquivAlignedEncodeM_const in H1.\n  match goal with\n  | H : EncodeMEquivAlignedEncodeM ?a _ |- EncodeMEquivAlignedEncodeM ?b _ =>\n    replace b with a\n  end. eauto.\n  extensionality s. extensionality ce.\n  eauto using format_word_is_encode_word.\nQed.\n\nDefinition AlignedEncoderForChecksum\n      {S}\n      n1\n      (encode_B encode_A : forall sz, AlignedEncodeM sz)\n      (f : nat -> forall {sz}, ByteBuffer.t sz -> nat -> word 16)\n  := (fun sz => EncodeAgain (encode_B sz >> encode_word_16_0 sz >> encode_A sz)\n                         (fun idx' v idx (s : S) =>\n                            encode_word_16_const (f (idx'-idx) v idx) sz v (idx+n1/8) s))%AlignedEncodeM.\n\nLocal Opaque encode_word'.\nLemma CorrectAlignedEncoderForChecksum'\n      {S}\n      (checksum_valid : nat -> ByteString -> Prop)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> word 16)\n      (f_OK : forall idx n m (t : Vector.t Core.char n)\n                (v1 : Vector.t Core.char idx) (v2 : Vector.t Core.char m),\n         f n t 0 = f n (v1 ++ t ++ v2) idx)\n      n1\n      (format_B_sz_eq : forall s ce t ce',\n          format_B s ce \u220b (t, ce') -> bin_measure t = n1)\n      (checksum_OK :\n         forall b1 b3 ext,\n            (exists s ce ce', format_B s ce \u220b (b1, ce')) ->\n            (exists s ce ce', format_A s ce \u220b (b3, ce')) ->\n           let a := (f_bit_aligned_free f)\n                      (mappend b1 (mappend (format_checksum _ _ _ _ (wzero 16)) b3)) in\n           let b2 := format_checksum _ _ _ 16 a in\n           checksum_valid\n             (bin_measure (mappend b1 (mappend b2 b3)))\n             (mappend (mappend b1 (mappend b2 b3)) ext))\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum checksum_valid OfSize 16 ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A f).\nProof.\n  unfold AlignedEncoderForChecksum.\n  eapply CorrectAlignedEncoderForChecksum; intros;\n    eauto using (EncodeMEquivAlignedEncodeM_word_const (n:=2));\n    simpl in H; match goal with\n                | H : Some (?a, _) = Some (?b, _) |- _ => replace b with a in * by congruence\n                | H : Some _ = None |- _ => discriminate H\n                end.\n  - apply encode_word'_padding.\n  - rewrite length_encode_word'. reflexivity.\n  - unfold format_checksum in *. eauto.\nQed.\n\nLemma ByteBuffer_checksum_bound_tail\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    InternetChecksum.ByteBuffer_checksum_bound sz (v++v') =\n    InternetChecksum.ByteBuffer_checksum_bound sz v.\nProof.\n  simpl. intros.\n  rewrite <- !InternetChecksum_To_ByteBuffer_Checksum'.\n  f_equal. rewrite build_aligned_ByteString_append.\n  replace (sz * 8) with (bin_measure (build_aligned_ByteString v)).\n  rewrite ByteString2ListOfChar_Over; eauto.\n  simpl. unfold length_ByteString. simpl. omega.\nQed.\n\nLemma padding_append_0\n      b1 b2\n  : padding b1 = 0 -> padding b2 = 0 -> padding (mappend b1 b2) = 0.\nProof.\n  intros.\n  rewrite padding_ByteString_enqueue_aligned_ByteString; eauto.\nQed.\n\nLemma refine_ret_ret_eq\n      {A} (a b : A)\n  : refine (ret a) (ret b) -> a = b.\nProof.\n  eauto using Return_inv.\nQed.\n\nLemma checksum_app_0\n  : forall l, checksum (wzero 8 :: wzero 8 :: l)%list = checksum l.\nProof.\n  intros. replace (wzero 8 :: (wzero 8 :: l))%list with ([wzero 8; wzero 8] ++ l)%list by reflexivity.\n  rewrite checksum_split; simpl; eauto.\n  exists 1. reflexivity.\nQed.\n\nLemma ByteString2ListOfChar_format_checksum\n      (w : word 16)\n  : let b := format_checksum _ _ _ _ w in\n    ByteString2ListOfChar (bin_measure b) b = [hi8 w; lo8 w]%list.\nProof.\n  simpl.\n  assert (refine (format_word w ()) (ret (build_aligned_ByteString ([hi8 w; lo8 w]), ()))). {\n    etransitivity.\n    Focus 2.\n    (* 2 : { *)\n      pose proof AlignedFormat2Char.\n      apply H; eauto. higher_order_reflexivity.\n    (* } *)\n    autorewrite with monad laws.\n    higher_order_reflexivity.\n  }\n  unfold format_word, format_checksum in *. simpl in *.\n  apply refine_ret_ret_eq in H. injections. rewrite H0.\n  rewrite ByteString2ListOfChar_eq'; eauto.\n  Unshelve.\n  simpl. exact ().\nQed.\n\nLocal Arguments Nat.modulo : simpl never.\nLemma ByteString_mod_16_padding\n  : forall b, bin_measure b mod 16 = 0 -> padding b = 0.\nProof.\n  intros.\n  rewrite padding_eq_mod_8. simpl in *.\n  apply Nat.mod_divides; eauto.\n  apply Nat.mod_divides in H; eauto.\n  destruct H as [x ?]. rewrite H. clear.\n  exists (2*x). omega.\nQed.\n\nFixpoint calculate_aligned_IPchecksum''\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       InternetChecksum.ByteBuffer_checksum_bound m v\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => calculate_aligned_IPchecksum'' m v' idx'\n       | _ => wzero _\n       end\n     end.\n\nRequire AlignedByteBuffer.\n\nDefinition calculate_aligned_IPchecksum'\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n  := match idx with\n     | 0 =>\n       InternetChecksum.ByteBuffer_checksum_bound m v\n     | S idx' =>\n       InternetChecksum.ByteBuffer_checksum_bound m (ByteBuffer.drop idx v)\n     end.\n\n  (* := match idx with *)\n  (*    | 0 => *)\n  (*      InternetChecksum.ByteBuffer_checksum_bound m v *)\n  (*    | S idx' => *)\n  (*      let (_, v') := (AlignedByteBuffer.bytebuffer_of_bytebuffer_range idx (sz - idx) v) in *)\n  (*      InternetChecksum.ByteBuffer_checksum_bound m v' *)\n  (*    end. *)\n\nLemma calculate_aligned_IPchecksum_eq\n      m\n      {sz}\n      (v : ByteBuffer.t sz) (idx : nat)\n  : calculate_aligned_IPchecksum' m v idx = calculate_aligned_IPchecksum'' m v idx.\nProof.\n  unfold calculate_aligned_IPchecksum'.\n  revert v m. revert sz.\n  induction idx; simpl; intros; try easy.\n  destruct v; simpl;\n    rewrite <- Eqdep_dec.eq_rect_eq_dec; try apply Nat.eq_dec.\n  - destruct m. reflexivity. destruct m; reflexivity.\n  - destruct idx; eauto.\n    assert (n = n - 0) as L by omega.\n    replace (ByteBuffer.drop 0 v) with (eq_rect _ _ v _ L).\n    destruct L. simpl. reflexivity.\n    simpl.\n    f_equal. apply Eqdep_dec.UIP_dec.\n    apply Nat.eq_dec.\n\n  (* unfold calculate_aligned_IPchecksum'. *)\n  (* revert v. revert sz. revert m. *)\n  (* induction idx; simpl; intros; try easy. *)\n  (* Local Opaque to_list. *)\n  (* destruct v; simpl. *)\n  (* - destruct m. reflexivity. *)\n  (*   unfold ByteBuffer_checksum_bound, ByteBuffer_fold_left16. simpl. destruct m; reflexivity. *)\n  (* - rewrite <- IHidx. destruct idx; simpl. *)\n  (*   + f_equal. *)\n  (*     replace (to_list (h :: v)) with (h :: (to_list v))%list by reflexivity. *)\n  (*     replace (n - 0) with (length (to_list v)). *)\n  (*     rewrite firstn_all. *)\n  (*   + f_equal. *)\nQed.\n\nLemma calculate_aligned_IPchecksum_front\n      m\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_IPchecksum' m (v'++v) idx =\n    calculate_aligned_IPchecksum' m v 0.\nProof.\n  intros.\n  rewrite calculate_aligned_IPchecksum_eq.\n  induction v'; eauto.\nQed.\n\nLemma calculate_aligned_IPchecksum_tail\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_IPchecksum' sz (v++v') 0 =\n    calculate_aligned_IPchecksum' sz v 0.\nProof.\n  intros. simpl.\n  rewrite ByteBuffer_checksum_bound_tail. reflexivity.\nQed.\n\nDefinition calculate_aligned_IPchecksum\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n  := wnot (calculate_aligned_IPchecksum' m v idx).\n\nLemma CorrectAlignedEncoderForIPChecksumThenC\n      {S}\n      (format_A format_B : FormatM S ByteString)\n      (encode_A : forall sz, AlignedEncodeM sz)\n      (encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      n1\n      (format_B_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_B s env \u220b (b, env') -> bin_measure b = n1)\n      (format_B_sz_OK : n1 mod 16 = 0)\n      (len_format_A : S -> nat)\n      (format_A_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_A s env \u220b (b, env') -> bin_measure b = len_format_A s)\n      (format_A_sz_OK : forall (s : S), len_format_A s mod 8 = 0)\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum IPChecksum_Valid OfSize 16 ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A calculate_aligned_IPchecksum).\nProof.\n  eapply CorrectAlignedEncoderForChecksum';\n    unfold calculate_aligned_IPchecksum; eauto; intros.\n  - rewrite calculate_aligned_IPchecksum_front.\n    rewrite calculate_aligned_IPchecksum_tail. reflexivity.\n  - destruct_conjs.\n    assert (bin_measure b1 mod 16 = 0) as L1 by (erewrite format_B_sz_OK'; eauto).\n    assert (padding b3 = 0) as L2 by (rewrite padding_eq_mod_8; erewrite format_A_sz_OK'; eauto).\n    unfold f_bit_aligned_free, IPChecksum_Valid, onesComplement. simpl in *.\n    rewrite <- InternetChecksum_To_ByteBuffer_Checksum'.\n    rewrite ByteString2ListOfChar_Over.\n    rewrite !build_aligned_ByteString_byteString_idem.\n    match goal with\n    | |- context [ByteString2ListOfChar (numBytes ?a * 8) ?a] =>\n      replace (numBytes a * 8) with (bin_measure a)\n    end.\n    2 : rewrite length_ByteString_no_padding; try omega.\n    rewrite !ByteString2ListOfChar_append.\n    rewrite !ByteString2ListOfChar_format_checksum.\n\n    assert (forall n, n mod 16 = 0 ->\n                 forall b, exists x, |ByteString2ListOfChar n b| = 2 * x) as L. {\n      clear. intros.\n      apply Nat.mod_divides in H; eauto. destruct H as [x ?].\n      replace (16 * x) with (8 * (2*x)) in * by omega.\n      subst.\n      rewrite ByteString2ListOfChar_len. eauto.\n    }\n    destruct L with (n:=bin_measure b1) (b:=b1) as [x1 ?]; eauto.\n    clear L.\n    set (ByteString2ListOfChar (bin_measure b1) b1) as l1 in *.\n    set (ByteString2ListOfChar (bin_measure b3) b3) as l3 in *.\n\n    unfold hi8, lo8.\n    rewrite split1_wzero, split2_wzero.\n    match goal with\n    | |- context [wnot (checksum ?a)] =>\n      assert (checksum a = checksum (l1 ++ l3))%list as L\n    end. {\n      rewrite !checksum_split; eauto. exists 1. reflexivity.\n    } rewrite L. clear L.\n    rewrite checksum_split; eauto.\n    rewrite checksum_split; eauto.\n    match goal with\n    | |- context [?a ^1+ (?b ^1+ ?c)] =>\n        assert (a ^1+ (b ^1+ c) = b ^1+ a ^1+ c) as L\n    end. {\n      rewrite <- !OneC_plus_assoc.\n      rewrite OneC_plus_comm.\n      rewrite <- !OneC_plus_assoc.\n      f_equal.\n      rewrite OneC_plus_comm.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite <- !checksum_split; eauto.\n    apply checksum_correct.\n    simpl. exists (1+x1). unfold Core.char in *. rewrite H7. omega.\n    simpl. exists 1. omega.\n    simpl. exists 1. omega.\n    all : destruct_conjs; simpl.\n    all : repeat match goal with\n                 | |- padding (ByteString_enqueue_ByteString _ _) = _ =>\n                   rewrite !padding_ByteString_enqueue_aligned_ByteString\n                 | |- padding (format_checksum _ _ _ _ _) = _ =>\n                   unfold format_checksum; rewrite encode_word'_padding\n                 | _ => eauto using ByteString_mod_16_padding\n                 end.\nQed.\n\n\nDefinition calculate_aligned_Pseudochecksum'\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) (idx : nat) :=\n  ByteBuffer_checksum srcAddr ^1+\n  ByteBuffer_checksum destAddr ^1+\n  zext protoCode 8 ^1+\n  udpLength ^1+\n  calculate_aligned_IPchecksum' m v idx.\n\nDefinition calculate_aligned_Pseudochecksum''\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) :=\n  calculate_aligned_IPchecksum' (12 + m)\n                                ([wzero 8; protoCode] ++ srcAddr ++ destAddr ++\n                                         (splitLength udpLength) ++ v) 0.\n\nLemma calculate_aligned_Pseudochecksum_equiv :\n  forall (srcAddr : ByteBuffer.t 4)\n    (destAddr : ByteBuffer.t 4)\n    (udpLength : word 16)\n    (protoCode : word 8)\n    (m : nat)\n    {sz} (v : ByteBuffer.t sz),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v 0 =\n    calculate_aligned_Pseudochecksum'' srcAddr destAddr udpLength protoCode m v.\nProof.\n  unfold calculate_aligned_Pseudochecksum', calculate_aligned_Pseudochecksum''.\n  intros.\n  repeat explode_vector.\n  Opaque split1.\n  Opaque split2.\n  simpl in *.\n  unfold ByteBuffer_checksum, InternetChecksum.ByteBuffer_checksum_bound, add_w16_into_checksum,\n  add_bytes_into_checksum, ByteBuffer_fold_left16, ByteBuffer_fold_left_pair.\n  fold @ByteBuffer_fold_left_pair.\n  setoid_rewrite Buffer_fold_left16_acc_oneC_plus.\n  rewrite combine_split.\n  rewrite !OneC_plus_wzero_r, !OneC_plus_wzero_l, OneC_plus_comm.\n  repeat (f_equal; [ ]).\n  rewrite <- !OneC_plus_assoc.\n  match goal with\n  | |- _ = ?a ^1+ ?b =>\n    assert (a ^1+ b = b ^1+ a) by (apply OneC_plus_comm)\n  end.\n  simpl in *. rewrite H.\n  rewrite <- !OneC_plus_assoc.\n  reflexivity.\nQed.\n\nLemma calculate_aligned_Pseudochecksum_front\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      m\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m (v'++v) idx =\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v 0.\nProof.\n  intros. unfold calculate_aligned_Pseudochecksum'.\n  f_equal. apply calculate_aligned_IPchecksum_front.\nQed.\n\nLemma calculate_aligned_Pseudochecksum_tail\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode sz (v++v') 0 =\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode sz v 0.\nProof.\n  intros. unfold calculate_aligned_Pseudochecksum'.\n  f_equal. apply calculate_aligned_IPchecksum_tail.\nQed.\n\nDefinition calculate_aligned_Pseudochecksum\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) (idx : nat) :=\n  wnot (calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v idx).\n\nLemma CorrectAlignedEncoderForPseudoChecksumThenC\n      {S}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A : forall sz, AlignedEncodeM sz)\n      (encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      n1\n      (format_B_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_B s env \u220b (b, env') -> bin_measure b = n1)\n      (format_B_sz_OK : n1 mod 16 = 0)\n      (len_format_A : S -> nat)\n      (format_A_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_A s env \u220b (b, env') -> bin_measure b = len_format_A s)\n      (format_A_sz_OK : forall (s : S), len_format_A s mod 8 = 0)\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16\n                ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A\n                                 (calculate_aligned_Pseudochecksum srcAddr destAddr udpLength protoCode)).\nProof.\n  apply CorrectAlignedEncoderForChecksum';\n    unfold calculate_aligned_Pseudochecksum; eauto with nocore; intros.\n  - rewrite calculate_aligned_Pseudochecksum_front.\n    rewrite calculate_aligned_Pseudochecksum_tail. reflexivity.\n  - destruct_conjs.\n    assert (bin_measure b1 mod 16 = 0) as L1 by (erewrite format_B_sz_OK'; eauto).\n    assert (padding b3 = 0) as L2 by (rewrite padding_eq_mod_8; erewrite format_A_sz_OK'; eauto).\n    unfold f_bit_aligned_free, Pseudo_Checksum_Valid, onesComplement.\n    rewrite calculate_aligned_Pseudochecksum_equiv.\n    unfold calculate_aligned_Pseudochecksum''.\n    unfold calculate_aligned_IPchecksum'.\n    rewrite <- InternetChecksum_To_ByteBuffer_Checksum'.\n    rewrite ByteString2ListOfChar_Over.\n    rewrite !build_aligned_ByteString_append.\n    rewrite !build_aligned_ByteString_byteString_idem.\n    rewrite Nat.mul_add_distr_r.\n    match goal with\n    | |- context [numBytes ?a * 8] =>\n      replace (numBytes a * 8) with (bin_measure a)\n    end.\n    2 : rewrite length_ByteString_no_padding; try omega.\n\n    match goal with\n    | |- context [wnot (checksum (ByteString2ListOfChar ?a ?b))] =>\n      assert (a = bin_measure b) as L\n    end. {\n      rewrite !@mappend_measure.\n      rewrite !Nat.add_assoc.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite !ByteString2ListOfChar_append.\n    rewrite !ByteString2ListOfChar_format_checksum.\n\n    assert (forall n, n mod 16 = 0 ->\n                 forall b, exists x, |ByteString2ListOfChar n b| = 2 * x) as L. {\n      clear. intros.\n      apply Nat.mod_divides in H; eauto. destruct H as [x ?].\n      replace (16 * x) with (8 * (2*x)) in * by omega.\n      subst.\n      rewrite ByteString2ListOfChar_len. eauto.\n    }\n    destruct L with (n:=bin_measure b1) (b:=b1) as [x1 ?]; eauto.\n    clear L.\n    set (ByteString2ListOfChar (bin_measure b1) b1) as l1 in *.\n    set (ByteString2ListOfChar (bin_measure b3) b3) as l3 in *.\n\n    rewrite !ByteString2ListOfChar_eq'.\n    simpl Core.byteString. unfold ByteBuffer.to_list.\n\n    unfold hi8, lo8.\n    rewrite split1_wzero, split2_wzero.\n    match goal with\n    | |- checksum (?a :: ?b :: ?l)%list = _ =>\n      replace (a :: b :: l)%list with (to_list (a :: [b])%vector ++ l)%list by reflexivity\n    end.\n    rewrite !app_assoc.\n    unfold Core.char in *.\n    match goal with\n    | |- context [(?a ++ l1)%list] => set (a ++ l1)%list as l1'\n    end.\n    assert (exists x, | l1' | = 2 * x) as L'. {\n      subst l1'. simpl.\n      rewrite !app_length. rewrite <- !ByteBuffer.to_list_length. rewrite H7.\n      exists (6+x1). omega.\n    } destruct L' as [x L'].\n    rewrite <- !app_assoc.\n    match goal with\n    | |- context [wnot (checksum ?a)] =>\n      assert (checksum a = checksum (l1' ++ l3))%list as L\n    end. {\n      rewrite !checksum_split; eauto.\n      exists 1. reflexivity.\n    } rewrite L. clear L.\n    rewrite checksum_split; eauto.\n    rewrite checksum_split; eauto.\n    match goal with\n    | |- context [?a ^1+ (?b ^1+ ?c)] =>\n        assert (a ^1+ (b ^1+ c) = b ^1+ a ^1+ c) as L\n    end. {\n      rewrite <- !OneC_plus_assoc.\n      rewrite OneC_plus_comm.\n      rewrite <- !OneC_plus_assoc.\n      f_equal.\n      rewrite OneC_plus_comm.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite <- !checksum_split; eauto.\n    apply checksum_correct.\n    rewrite !app_length. rewrite L'. simpl. exists (1+x). omega.\n    simpl. exists 1. omega.\n    simpl. exists 1. omega.\n\n    all : destruct_conjs; simpl.\n    all : repeat match goal with\n                 | |- padding (ByteString_enqueue_ByteString _ _) = _ =>\n                   rewrite !padding_ByteString_enqueue_aligned_ByteString\n                 | |- padding (format_checksum _ _ _ _ _) = _ =>\n                   unfold format_checksum; rewrite encode_word'_padding\n                 | _ => eauto using ByteString_mod_16_padding\n                 end.\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/Narcissus/BinLib/AlignedIPChecksum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3242353859211693, "lm_q1q2_score": 0.17601548612187023}}
{"text": "From iris.proofmode Require Import base proofmode classes.\nFrom transfinite.base_logic.lib Require Export fancy_updates.\nFrom melocoton Require Import stdpp_extra language_commons.\nFrom melocoton.language Require Export language weakestpre.\n(* FIXME: If we import iris.bi.weakestpre earlier texan triples do not\n   get pretty-printed correctly. *)\nFrom iris.bi Require Export weakestpre.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n\nSection wp.\nContext `{SI:indexT, !langG val \u039b \u03a3, !invG \u03a3}.\nImplicit Types P : iProp \u03a3.\nImplicit Types \u03a6 : val \u2192 iProp \u03a3.\nImplicit Types v : val.\nImplicit Types e : expr \u039b.\nImplicit Types \u03a8 : protocol val \u03a3.\nImplicit Types prog : lang_prog \u039b.\nImplicit Types pe : prog_environ \u039b \u03a3.\n\n\nDefinition program_fulfills\n  (\u03a8in : protocol val \u03a3) (p : mixin_prog (func \u039b)) (\u03a8should : protocol val \u03a3) : iProp \u03a3 :=\n  \u2200 s vv \u03a6, \u03a8should s vv \u03a6 -\u2217 \u231cp !! s <> None\u231d \u2217 WP (of_class _ (ExprCall s vv)) @ \u27e8p, \u03a8in\u27e9; \u22a4 {{ \u03a6 }}.\n\nDefinition env_fulfills\n  (p:prog_environ \u039b \u03a3) (\u03a8should : protocol val \u03a3) := program_fulfills p.(penv_proto) p.(penv_prog) \u03a8should.\n\nNotation \"\u03a8in '|-' p '::' \u03a8should\" := (program_fulfills \u03a8in p \u03a8should) (at level 25, p, \u03a8should at level 26) : bi_scope.\n\nDefinition spec_union (p1 p2 : protocol val \u03a3) : protocol val \u03a3 :=\n  \u03bb s vv \u03a6, (p1 s vv \u03a6 \u2228 p2 s vv \u03a6)%I.\nDefinition spec_inters (p1 p2 : protocol val \u03a3) : protocol val \u03a3 :=\n  \u03bb s vv \u03a6, (p1 s vv \u03a6 \u2227 p2 s vv \u03a6)%I.\n\n\nClass can_link (\u03a81 \u03a82 \u03a8axiom \u03a8res : protocol val \u03a3) (p1 p2 p3 : lang_prog \u039b) : Prop := {\n  p1_p2_disjoint : dom p1 ## dom p2;\n  \u03a8res_is_union : \u22a2 (\u2200 s vv \u03a6, \u03a8res s vv \u03a6 -\u2217 (spec_union \u03a81 \u03a82) s vv \u03a6)%I;\n  \u03a8axiom_is_axiomatic : \u22a2 (\u2200 s vv \u03a6, \u03a8axiom s vv \u03a6 -\u2217 \u231cs \u2209 dom p3\u231d)%I;\n  p1_satisfies_\u03a81 : \u22a2 (spec_union \u03a82 \u03a8axiom |- p1 :: \u03a81)%I;\n  p2_satisfies_\u03a82 : \u22a2 (spec_union \u03a81 \u03a8axiom |- p2 :: \u03a82)%I;\n  p3_is_union : p3 = (union_with (\u03bb _ _ : func \u039b, None) p1 p2);\n}.\n\nDefinition pairwise {X} (A:list X) (\u03a8 : X -> X -> Prop) :=\n  forall i j, i <> j -> match (nth_error A i, nth_error A j) with\n      (Some a, Some b) => \u03a8 a b\n     | _ => True end.\n\nDefinition spec_union_list (P : list (protocol val \u03a3)) : protocol val \u03a3 :=\n  \u03bb s vv \u03a6, (\u2203 i, match nth_error P i with Some pp => pp s vv \u03a6 | _ => \u231cFalse\u231d end)%I.\nDefinition spec_union_list_except k (P : list (protocol val \u03a3)) : protocol val \u03a3 :=\n  \u03bb s vv \u03a6, (\u2203 i, \u231ci <> k\u231d \u2217 match nth_error P i with Some pp => pp s vv \u03a6 | _ => \u231cFalse\u231d end)%I.\n\nFixpoint union_map_list (P : list (lang_prog \u039b)) : lang_prog \u039b := match P with\n  nil => \u2205\n | x::xr => union_with (\u03bb _ _ : func \u039b, None) x (union_map_list xr)\nend.\n\nLemma pairwise_subset {X} H (a : list X) x : pairwise (x::a) H -> pairwise a H.\nProof.\n  intros HH i j Hne.\n  specialize (HH (S i) (S j)). cbn in HH.\n  apply HH. congruence.\nQed.\n\nLemma union_map_list_spec x y (P:list (lang_prog \u039b)) :\n  (pairwise P (fun p1 p2 => dom p1 ## dom p2)) -> \n  ((union_map_list P) !! x = Some y <-> \u2203 k, In k P \u2227 k !! x = Some y).\nProof.\n  intros Hdis.\n  revert x y.\n  induction P; intros x y; first split; cbn.\n  - rewrite lookup_empty. intros H; congruence.\n  - intros (? & [] & ?).\n  - rewrite lookup_union_with.\n    destruct (a !! x) as [va|] eqn:Hva;\n    destruct (union_map_list P !! x) as [vP|] eqn:HvP; cbn; split; try congruence.\n    + intros _. apply IHP in HvP; last by eapply pairwise_subset.\n      destruct HvP as (k & (pos & Hpos)%In_nth_error & Heq).\n      specialize (Hdis 0 (S pos)); cbn in Hdis. rewrite Hpos in Hdis.\n      exfalso. assert (0 \u2260 S pos) as Hne by lia. specialize (Hdis Hne).\n      rewrite  elem_of_disjoint in Hdis. eapply Hdis.\n      all: by eapply elem_of_dom_2.\n    + injection 1; intros ->. exists a; repeat split; by try left.\n    + intros (k & [-> | Hk] & Heq); first congruence.\n      exfalso. assert (\u2203 k : lang_prog \u039b, In k P \u2227 k !! x = Some y) as H by by exists k.\n      apply IHP in H; first congruence. by eapply pairwise_subset.\n    + apply IHP in HvP; last by eapply pairwise_subset.\n      destruct HvP as (k & ? & ?).\n      injection 1; intros ->. exists k; repeat split; eauto.\n    + intros (k & [-> | Hk] & Heq); first congruence.\n      assert (\u2203 k : lang_prog \u039b, In k P \u2227 k !! x = Some y) as H by by exists k.\n      apply IHP in H; last by eapply pairwise_subset. congruence.\n    + intros (k & [-> | Hk] & Heq); first congruence.\n      assert (\u2203 k : lang_prog \u039b, In k P \u2227 k !! x = Some y) as H by by exists k.\n      apply IHP in H; last by eapply pairwise_subset. congruence.\nQed.\n\nLemma union_map_subset A p : \n  (pairwise A (fun p1 p2 => dom p1 ## dom p2)) -> p \u2208 A \u2192 p \u2286 union_map_list A.\nProof.\n  intros Hdis H. apply map_subseteq_spec.\n  intros i x Hin.\n  apply union_map_list_spec; first done.\n  exists p. split; eauto. by apply elem_of_list_In.\nQed.\n\nClass can_link_all \n    (\u03a8axiom \u03a8res : protocol val \u03a3) (pres : lang_prog \u039b)\n    (A : list (prod (protocol val \u03a3) (lang_prog \u039b))) := {\n  all_disjoint : pairwise (map snd A) (fun p1 p2 => dom p1 ## dom p2);\n  \u03a8res_is_big_union : \u22a2 (\u2200 s vv \u03a6, \u03a8res s vv \u03a6 -\u2217 (spec_union_list (map fst A)) s vv \u03a6)%I;\n  \u03a8axiom_is_axiomatic_all : \u22a2 (\u2200 s vv \u03a6, \u03a8axiom s vv \u03a6 -\u2217 \u231cs \u2209 dom pres\u231d)%I;\n  pres_is_union : pres = union_map_list (map snd A);\n  one_spec := fun i => spec_union (spec_union_list_except i (map fst A)) \u03a8axiom;\n  all_satisfy_spec : \u2200 i, match (nth_error A i) with None => True |\n      Some (\u03a8i, pi) =>  \u22a2 (one_spec i |- pi :: \u03a8i)%I end\n}.\n\n#[global]\nInstance can_link_can_link_all \u03a8axiom \u03a8res pres \u03a81 \u03a82 p1 p2 : can_link \u03a81 \u03a82 \u03a8axiom \u03a8res p1 p2 pres\n  -> can_link_all \u03a8axiom \u03a8res pres [(\u03a81,p1); (\u03a82,p2)].\nProof.\n  intros [H1 H2 H3 H4 H5 H6]; split; cbn.\n  - intros [|[|[|i]]] [|[|[|j]]] H; cbn; easy.\n  - iIntros (s vv \u03a6) \"Hres\". iPoseProof H2 as \"H2\".\n    iDestruct (\"H2\" $! s vv \u03a6 with \"Hres\") as \"[H2'|H2']\".\n    + iExists 0; cbn; done.\n    + iExists 1; cbn; done.\n  - done.\n  - rewrite H6. apply map_eq. intros i. rewrite ! lookup_union_with. rewrite lookup_empty.\n    destruct (p1 !! i), (p2 !! i); done.\n  - intros [|[|[|i]]]; cbn; try done.\n    all: iIntros (s vv \u03a6) \"Hres\"; cbn.\n    1: iPoseProof H4 as \"H\"; iSpecialize (\"H\" $! s vv \u03a6 with \"Hres\").\n    2: iPoseProof H5 as \"H\"; iSpecialize (\"H\" $! s vv \u03a6 with \"Hres\").\n    all: iDestruct \"H\" as \"[$ HWP]\".\n    all: iApply wp_proto_mono; last iApply \"HWP\".\n    all: cbn; intros s' vv' \u03a6'; iIntros \"[H|H]\".\n    2,4: by iRight. all: iLeft.\n    1: iExists 1. 2: iExists 0.\n    all: iSplitR; first done. all: done.\nQed.\n\nLemma wp_link_execs \u03a8axiom \u03a8res (pres : gmap string (\u039b.(func))) A :\n  can_link_all \u03a8axiom \u03a8res pres A\n  -> \u22a2 \u2200 e \u03a6 i, match (nth_error A i) with None => \u231cFalse\u231d | \n          Some (\u03a8i, pi) => WP e @ \u27e8pi, spec_union (spec_union_list_except i (map fst A)) \u03a8axiom \u27e9; \u22a4 {{ \u03a6 }} end\n     -\u2217 WP e @ \u27e8pres, \u03a8axiom\u27e9; \u22a4 {{ \u03a6 }}.\nProof.\n  intros [Hdis H\u03a8res Haxiom -> one_spec' Hsatis].\n  iL\u00f6b as \"IHe\". iIntros (e \u03a6 i).\n  destruct (nth_error A i) as [[\u03a8i pi]|] eqn:Heq; last (iIntros \"%H\"; done).\n  rewrite !wp_unfold /wp_pre /=.\n  iIntros \"H %\u03c3 H\u03c3\".\n  - iSpecialize (\"H\" $! \u03c3 with \"H\u03c3\").\n    iMod \"H\".\n    iDestruct \"H\" as \"[(%x & -> & H\u03c3 & H)|[(%s' & %vv' & %K & %HeqK & %H2 & >(%\u039e & H\u03c3 & [H\u03a8|H\u03a8] & H3))|(%HH & H3)]]\".\n    * iModIntro. iLeft. iExists _. iFrame. iPureIntro. done.\n    * iDestruct \"H\u03a8\" as \"(%kidx & %Hknei & H\u03a8)\". rewrite nth_error_map.\n      destruct (nth_error A kidx) as [[\u03a8c pc]|] eqn:Heqk; cbn; last iPure \"H\u03a8\" as [].\n      specialize (Hsatis kidx). rewrite Heqk in Hsatis.\n      iPoseProof (Hsatis) as \"Hsatis\".\n      iDestruct (\"Hsatis\" $! s' vv' \u039e with \"H\u03a8\")as \"(%HNone & H\u03a8)\".\n      rewrite wp_unfold /wp_pre /=.\n      iSpecialize (\"H\u03a8\" $! \u03c3 with \"H\u03c3\").\n      iMod \"H\u03a8\" as \"[(%x & %Heqx & H\u03c3 & H)|[(%s'2 & %vv'2 & %K'2 & %HeqK2 & %H''2 & >(%\u039e' & H\u03c3 & H\u03a8' & H3'))|(%HH2&H3')]]\".\n      -- exfalso. apply of_class_inj in Heqx. congruence.\n      -- exfalso. assert (K'2 = empty_ectx) as ->. \n         2: { rewrite fill_empty in HeqK2. apply of_class_inj in HeqK2. assert (s'2 = s') as -> by congruence; congruence. }\n         destruct (fill_class K'2 (of_class \u039b (ExprCall s'2 vv'2))) as [H1|[x Hx]].\n         { eexists. rewrite <- HeqK2. by rewrite to_of_class. }\n        { done. }\n          { exfalso. unfold to_val in Hx. rewrite to_of_class in Hx; congruence. }\n     -- destruct HH2 as (e' & \u03c3' & (KK & e1' & e2' & Heq2 & -> & Hstep)%prim_step_inv).\n          destruct (fill_class KK e1') as [->|[x Hx]].\n         { eexists. rewrite <- Heq2. by rewrite to_of_class. }\n         2: { apply val_head_stuck in Hstep. congruence. }\n         rewrite ! fill_empty in Heq2. subst e1'.\n         apply call_head_step in Hstep.\n         destruct Hstep as (Fn & Heqp2' & He2' & -> ). iRight. iRight.\n         assert (union_map_list (map snd A) !! s' = Some Fn) as Heqs'.\n         { apply union_map_list_spec; first done. exists pc; repeat split; try done.\n           apply in_map_iff. exists ((\u03a8c,pc)); repeat split. by eapply nth_error_In. }\n         iModIntro. iSplit; first iPureIntro.\n         { do 2 eexists. rewrite HeqK. econstructor; first done. 1:done.\n           apply call_head_step. exists Fn. repeat split; try done. }\n         subst e. iIntros (? ? (e'2 & -> & (Fn3 & Heqp3' & He3' & ->)%call_head_step)%head_reducible_prim_step_ctx).\n         2: { do 2 eexists.\n              apply call_head_step. exists Fn. repeat split; try done. }\n         rewrite Heqs' in Heqp3'. assert (e'2 = e2') as -> by congruence.\n         iSpecialize (\"H3'\" $! \u03c3 e2').\n         assert (prim_step pc (of_class \u039b (ExprCall s' vv')) \u03c3 e2' \u03c3) as Hstep2.\n         { apply head_prim_step. apply call_head_step. eexists; repeat split; done. }\n         iSpecialize (\"H3'\" $! Hstep2). iMod \"H3'\". iModIntro. iNext.\n         iMod \"H3'\" as \"(? & H3')\". iModIntro. iFrame.\n         iApply wp_bind. iApply (wp_wand with \"[H3']\").\n         { iApply (\"IHe\" $! _ _ kidx). rewrite Heqk. iApply \"H3'\". }\n         iIntros (r) \"Hr\". iSpecialize (\"H3\" $! r with \"Hr\"). iApply (\"IHe\" $! _ _ i). rewrite Heq. done.\n    * iRight. iLeft. iModIntro. do 3 iExists _; iSplitR; first done.\n      destruct (union_map_list (map snd A) !! s') as [v|] eqn:Heqv.\n      { iExFalso. iDestruct (Haxiom $! s' vv' \u039e with \"H\u03a8\") as \"%Hfalse\". exfalso.\n        apply Hfalse. eapply elem_of_dom_2. done. }\n      cbn. iSplitR; first done. iModIntro. iExists \u039e. iFrame. iNext.\n      iIntros (r) \"Hr\". iSpecialize (\"H3\" with \"Hr\"). iApply (\"IHe\" $! _ _ i). by rewrite Heq.\n    * iModIntro. iRight. iRight.\n      iSplitR.\n      { iPureIntro. eapply reducible_mono; last done.\n        apply union_map_subset; first done. apply elem_of_list_In.\n        apply in_map_iff. exists ((\u03a8i, pi)); split; eauto.\n        by eapply nth_error_In. }\n      iIntros (\u03c3' e' Hstep%prim_step_inv).\n      iSpecialize (\"H3\" $! \u03c3' e').\n      destruct Hstep as (K & e1' & e2' & -> & -> & H).\n      assert (prim_step pi (fill K e1') \u03c3 (fill K e2') \u03c3') as Hstep.\n      { econstructor. 1-2:done. destruct (to_class e1') as [[]|] eqn:Heqe1.\n        - exfalso. eapply val_head_step. apply of_to_class in Heqe1. erewrite Heqe1. done.\n        - apply of_to_class in Heqe1. subst e1'.\n          destruct HH as (? & \u03c3'2 & (e2'' & -> & (K2 & eK1 & eK2 & Heq1 & -> & HHstep)%prim_step_inv)%fill_step_inv).\n          2: unfold to_val; by rewrite to_of_class.\n          assert (K2 = empty_ectx) as ->.\n          1: { destruct (fill_class' K2 eK1) as [|[vv Hvv]].\n               1: eexists; rewrite <- Heq1; by rewrite to_of_class.\n               1: done.\n               exfalso. apply of_to_class in Hvv. subst eK1. eapply val_head_step. done. }\n          rewrite fill_empty in Heq1. subst eK1. apply call_head_step in H, HHstep.\n          destruct H as (FN1 & HFN1 &Happy1 & ->).\n          destruct HHstep as (FN2 & HFN2 &Happy2 & ->).\n          apply union_map_list_spec in HFN1; last done. destruct HFN1 as (? & [[\u03a8\u03a8 kk] [<- (kki & Hkki)%In_nth_error]]%in_map_iff & HFN1).\n          cbn in HFN1. destruct (decide (kki = i)) as [-> | Hcontr].\n          1: apply call_head_step; exists FN2; repeat split; try congruence.\n          exfalso. specialize (Hdis kki i Hcontr). rewrite ! nth_error_map in Hdis.\n          rewrite Hkki in Hdis. rewrite Heq in Hdis. cbn in Hdis. rewrite elem_of_disjoint in Hdis.\n          eapply Hdis; eapply elem_of_dom_2; done.\n        - by eapply head_step_no_call. }\n      iDestruct (\"H3\" $! Hstep) as \">H3\". iModIntro. iNext.\n      iMod \"H3\" as \"(H\u03c3 & HWP)\". iModIntro. iFrame. iApply (\"IHe\" $! _ _ i). rewrite Heq. done.\nQed.\n\nLemma wp_link_progs \u03a8axiom \u03a8res (pres : gmap string (\u039b.(func))) A :\n  can_link_all \u03a8axiom \u03a8res pres A\n -> \u22a2 \u03a8axiom |- pres :: \u03a8res.\nProof.\n  intros [Hdis H\u03a8res Haxiom -> one_spec' Hsatis].\n  iIntros (s vv \u03a6) \"H\". iPoseProof H\u03a8res as \"H\u03a8res\".\n    iDestruct (\"H\u03a8res\" with \"H\") as \"[%x Hx]\".\n    erewrite nth_error_map.\n    destruct (nth_error A x) as [[\u03a8i pi]|] eqn:Heq; last by iExFalso. cbn.\n    specialize (Hsatis x) as Hsatis2.\n    rewrite Heq in Hsatis2. iDestruct (Hsatis2 $! s vv \u03a6 with \"Hx\") as \"[%Hx1 Hx2]\".\n    destruct (union_map_list (map snd A) !! s) eqn:Hl2.\n  - iSplitR; first done. unshelve iApply (wp_link_execs _ _ _ _ $! _ _ x). 3: by split. rewrite Heq. done.\n  - exfalso. destruct (pi !! s) as [f|] eqn:Heqpi; try congruence.\n    assert (\u2203 k, In k ((map snd A)) \u2227 k !! s = Some f) as HH.\n    + exists pi; repeat split; try done. apply in_map_iff. exists (\u03a8i,pi).\n      repeat split; try done. eapply nth_error_In. done.\n    + apply union_map_list_spec in HH; try congruence. done.\nQed.\n\n\nEnd wp.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/language/wp_link.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1760034890710507}}
{"text": "Require Import String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Kami.Lib.Word.\nRequire Import Kami.Ex.IsaRv32 riscv.Spec.Decode.\nRequire Import riscv.Utility.Encode.\nRequire Import coqutil.Word.LittleEndian.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Tactics.rdelta.\nRequire Import processor.KamiWord.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import riscv.Spec.Machine.\nRequire riscv.Platform.Memory.\nRequire Import riscv.Spec.PseudoInstructions.\nRequire Import riscv.Proofs.EncodeBound.\nRequire Import riscv.Proofs.DecodeEncode.\nRequire Import riscv.Platform.Run.\nRequire Import riscv.Utility.MkMachineWidth.\nRequire Import riscv.Utility.Monads. Import MonadNotations.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire Import riscv.Platform.MinimalMMIO.\nRequire Import riscv.Platform.MetricMinimalMMIO.\nRequire Import riscv.Platform.FE310ExtSpec.\n\nRequire Import Kami.Syntax Kami.Semantics Kami.Tactics.\nRequire Import Kami.Ex.MemTypes Kami.Ex.SC Kami.Ex.SCMMInl Kami.Ex.SCMMInv.\n\nRequire Export processor.KamiProc.\nRequire Import processor.Consistency.\nRequire Import processor.KamiRiscvStep.\n\nLemma get_of_list_not_In:\n  forall (key: Type) (key_dec: forall k1 k2: key, {k1 = k2} + {k1 <> k2})\n         (value: Type) (map: map.map key value),\n    map.ok map ->\n    forall (l: list (key * value)) k,\n      ~ In k (List.map fst l) ->\n      map.get (map.of_list l) k = None.\nProof.\n  induction l as [|[k v] l]; simpl; intros;\n    [rewrite map.get_empty; reflexivity|].\n  destruct (key_dec k k0).\n  - intuition idtac.\n  - rewrite map.get_put_diff by auto.\n    apply IHl; intuition idtac.\nQed.\n\nLemma alignedXAddrsRange_zero_bound_in:\n  forall n a,\n    (wordToN a < N.of_nat n)%N -> In a (alignedXAddrsRange 0 n).\nProof.\n  induction n; [blia|].\n  intros.\n  assert (wordToN a = N.of_nat n \\/ wordToN a < N.of_nat n)%N by blia.\n  clear H; destruct H0.\n  - unfold alignedXAddrsRange; fold alignedXAddrsRange.\n    left; apply wordToN_inj.\n    rewrite H.\n    change (0 + n)%nat with n.\n    pose proof (wordToN_bound a); rewrite H in H0.\n    rewrite <-wordToN_NToWord_2 with (sz:= Z.to_nat width) (n:= N.of_nat n) by assumption.\n    rewrite NToWord_nat, Nnat.Nat2N.id; reflexivity.\n  - right; auto.\nQed.\n\nSection Equiv.\n  Context {Registers: map.map Z word}\n          {mem: map.map word byte}.\n\n  Local Notation M := (free action result).\n  Local Notation RiscvMachine := MetricRiscvMachine.\n  Local Existing Instance MetricMinimalMMIO.IsRiscvMachine.\n  Local Existing Instance MetricMinimalMMIOSatisfiesPrimitives.\n\n  (** * Processor, software machine, and states *)\n\n  Variable (instrMemSizeLg memSizeLg: Z).\n  Hypotheses (Hinstr1: 3 <= instrMemSizeLg)\n             (Hinstr2: instrMemSizeLg <= width - 2)\n             (Hkmem1: 2 + instrMemSizeLg < memSizeLg)\n             (Hkmem2: memSizeLg <= width)\n             (* 16 used to be disjoint to MMIO addresses.\n              * [Hkmem2] is meaningless assuming this [Hkmemdisj]\n              * but still having that in context ease some proofs. *)\n             (Hkmemdisj: memSizeLg <= 16).\n  Local Notation Hinstr := (conj Hinstr1 Hinstr2).\n\n  Variable (memInit: Vec (ConstT (Bit BitsPerByte)) (Z.to_nat memSizeLg)).\n  Definition kamiMemInit := ConstVector memInit.\n  Local Definition kamiProc :=\n    @KamiProc.proc instrMemSizeLg memSizeLg Hinstr kamiMemInit\n                   (kami_AbsMMIO (Z.to_N memSizeLg)).\n\n  (* redefine mcomp_sat to simplify for the case where no answer is returned *)\n  Local Notation mcomp_sat_unit m initialL post :=\n    (mcomp_sat m initialL (fun (_: unit) => post)).\n\n  Context (Registers_ok: map.ok Registers)\n          (mem_ok: map.ok mem).\n\n  Local Notation states_related :=\n    (@states_related Registers mem instrMemSizeLg memSizeLg Hinstr1 Hinstr2).\n  Local Notation kamiStep :=\n    (@kamiStep _ _ Hinstr1 Hinstr2 memInit).\n\n  Arguments Z.add: simpl never.\n\n  Lemma KamiLabelR_unique: forall {klbl t t'},\n      KamiLabelR klbl t ->\n      KamiLabelR klbl t' ->\n      t = t'.\n  Proof.\n    intros. inversion H; inversion H0; clear H H0; subst.\n    + reflexivity.\n    + rewrite H4 in H1. exfalso. eapply FMap.M.add_empty_neq. eassumption.\n    + rewrite H1 in H5. exfalso. eapply FMap.M.add_empty_neq. eassumption.\n    + simpl in *. rewrite H1 in H5.\n      apply (f_equal (FMap.M.find \"mmioExec\"%string)) in H5.\n      do 2 rewrite FMap.M.find_add_1 in H5.\n      apply Option.eq_of_eq_Some in H5.\n      apply Eqdep.EqdepTheory.inj_pair2 in H5.\n      inversion H5; subst; clear H5.\n      reflexivity.\n  Qed.\n\n  Inductive KamiLabelSeqR: list LabelT -> list Event -> Prop :=\n  | KamiSeqNil: KamiLabelSeqR nil nil\n  | KamiSeqCons:\n      forall klseq t,\n        KamiLabelSeqR klseq t ->\n        forall klbl nt,\n          KamiLabelR klbl nt ->\n          KamiLabelSeqR (klbl :: klseq) (nt ++ t).\n\n  (** * Rephrasing single step soundness in a more readable way *)\n\n  Definition KState: Type := KamiMachine * list LabelT.\n\n  Inductive kstep1: KState -> KState -> Prop :=\n  | KStep: forall (m1: KamiMachine) (t1: list LabelT) kupd klbl,\n      Step kamiProc m1 kupd klbl ->\n      kstep1 (m1, t1) (FMap.M.union kupd m1, klbl :: t1).\n\n  Definition CState: Type := RiscvMachine.\n\n  Definition cstep1(m1: CState)(P: CState -> Prop): Prop := mcomp_sat_unit (run1 iset) m1 P.\n\n  Inductive related: KState -> CState -> Prop :=\n  | Related: forall km kt eventTrace rm,\n      Kami.Semantics.reachable km kamiProc ->\n      states_related (km, eventTrace) rm ->\n      KamiLabelSeqR kt eventTrace ->\n      related (km, kt) rm.\n\n  Theorem kstep1_sound: forall ks1 ks2 rs1 P,\n      related ks1 rs1 ->\n      kstep1 ks1 ks2 ->\n      cstep1 rs1 P ->\n      related ks2 rs1 \\/\n      exists rs2, related ks2 rs2 /\\ P rs2.\n  Proof.\n    intros.\n    pose proof (KamiRiscvStep.kamiStep_sound instrMemSizeLg memSizeLg Hinstr1 Hinstr2\n      Hkmem1 Hkmem2 Hkmemdisj memInit Registers_ok mem_ok) as Q.\n    unfold cstep1, kamiStep in *.\n    inversion H. inversion H0. subst. inversion H8. subst. clear H H0 H8.\n    specialize Q with (1 := H2) (3 := H3) (4 := H1).\n    edestruct Q as [A | A]; clear Q.\n    - eauto.\n    - left. destruct A as [Q1 Q2]. econstructor.\n      + unfold reachable in *.\n        destruct H2 as [sigma H2]. inversion H2. subst; clear H2.\n        eexists. constructor. eapply Multi; eassumption.\n      + eassumption.\n      + inversion H4; subst; clear H4.\n        * change (KamiLabelSeqR [klbl] ([] ++ [])).\n          eapply KamiSeqCons. 1: exact KamiSeqNil.\n          eapply KamiSilent. assumption.\n        * inversion Q1. clear Q1. subst.\n          change (nt ++ t) with ([] ++ nt ++ t).\n          repeat eapply KamiSeqCons; try assumption. constructor. assumption.\n    - right. destruct A as [rs2 [tNew' [A [B C]]]].\n      exists rs2. split. 2: exact C.\n      econstructor. 2: exact B.\n      + unfold reachable in *.\n        destruct H2 as [sigma H2]. inversion H2. subst; clear H2.\n        eexists. constructor. eapply Multi; eassumption.\n      + eapply KamiSeqCons; eassumption.\n  Qed.\n\n  (** * Multistep and Behavior soundness *)\n\n  Inductive ksteps: KState -> KState -> Prop :=\n  | KSteps: forall m1 t1 m2 tNew,\n      Multistep kamiProc m1 m2 tNew ->\n      ksteps (m1, t1) (m2, tNew ++ t1).\n\n  (* Can't use this one here because we're not doing a simulation from Kami to compiler *)\n  Definition csteps: CState -> (CState -> Prop) -> Prop := runsTo cstep1.\n\n  Definition calways{State: Type}(Step: State -> (State -> Prop) -> Prop)(s: State)(P: State -> Prop): Prop :=\n    P s /\\ forall s', P s' -> Step s' P.\n\n  (* Can't use this one here because we don't really have a `kstep: KState -> KState -> Prop` that\n     we lift with *, but Kami requires its own ksteps (its own \"star\") *)\n  Definition kalways0{State: Type}(Step: State -> State -> Prop)(s: State)(P: State -> Prop): Prop :=\n    P s /\\ forall s1 s2, P s1 -> Step s1 s2 -> P s2.\n\n  Definition kalways{State: Type}(Stepstar: State -> State -> Prop)(s: State)(P: State -> Prop): Prop :=\n    forall s', Stepstar s s' -> P s'.\n\n  Theorem ksteps_sound: forall (inv: CState -> Prop) ks1 rs1,\n      related ks1 rs1 ->\n      calways cstep1 rs1 inv ->\n      kalways ksteps ks1 (fun ks2 => exists rs2, related ks2 rs2 /\\ inv rs2).\n  Proof.\n    unfold calways, kalways.\n    intros. destruct H0. inversion H1. subst. clear H1. revert H3 rs1 t1 H0 H.\n    induction 1; intros.\n    - subst. exists rs1. split; assumption.\n    - specialize IHMultistep with (1 := H0) (2 := H).\n      destruct IHMultistep as [rs2 [A B]].\n      edestruct kstep1_sound.\n      + exact A.\n      + econstructor. eassumption.\n      + eapply H2. exact B.\n      + eauto.\n      + eauto.\n  Qed.\n\n  Definition KamiImplMachine: Type := RegsT.\n\n  (* When running the processor on an FPGA, this memory module will be implemented in some\n     trusted Verilog code, and will forward requests either to a DRAM or to a source\n     from which the program to run can be loaded at startup.\n     This source could be a connection to a host computer, an SD card, a ROM, ...\n     In any case, we model this in Kami as a huge register file.\n     Therefore, a faithful Verilog implementation will have to make sure that all in-range\n     addresses behave like memory, including the ones from which the program is loaded.\n     One possible implementation would be this:\n     For each address which is designated as a \"program load address\", also have DRAM for it,\n     as well as an extra \"initialized bit\", which is set to false initially.\n     Whenever such an address is loaded, if the initialized bit is set, the value from the\n     DRAM is returned, otherwise the value from the program source is loaded, stored into\n     DRAM, and the bit is set to 1.\n     Whenever such an address is stored, the initialized bit is set, and the value is stored\n     into DRAM.\n     For the proofs, we model this component as a huge register file where the addresses\n     designated as \"program load adddresses\" are initialized to [prog], and the other\n     addresses are initialized to zero.\n     We'll use the convention that \"program load addresses\" are from 0 to 4*2^instrMemSizeLg,\n     and that the data memory goes from 4*2^instrMemSizeLg to dataMemSize\n     because then we don't have to pass the base program load address to this definition,\n     and to serve load/store requests in the Kami model, we can just ignore the upper bits\n     and use the lower bits to index into the Vector.\n   *)\n\n  Definition mm: Modules := Kami.Ex.SC.mm\n                              (existT _ rv32DataBytes eq_refl)\n                              kamiMemInit (kami_AbsMMIO (Z.to_N memSizeLg)).\n  Definition p4mm: Modules := p4mm Hinstr kamiMemInit (kami_AbsMMIO (Z.to_N memSizeLg)).\n\n  Fixpoint setRegsInit (kinits: kword 5 -> kword width) (n: nat): Registers :=\n    match n with\n    | O => map.put map.empty 0 $0\n    | S n' => map.put (setRegsInit kinits n') (Z.of_nat n) (kinits $n)\n    end.\n\n  Definition riscvRegsInit: Registers :=\n    setRegsInit (evalConstT (rfInit procInit)) 31.\n  Lemma regs_related_riscvRegsInit:\n    regs_related (evalConstT (rfInit procInit)) riscvRegsInit.\n  Proof.\n    red; intros.\n\n    clear -Registers_ok.\n    pose proof (wordToN_bound w).\n    change (NatLib.Npow2 (BinInt.Z.to_nat 5)) with 32%N in H.\n    assert (wordToN w = 0 \\/ wordToN w = 1 \\/ wordToN w = 2 \\/ wordToN w = 3 \\/\n            wordToN w = 4 \\/ wordToN w = 5 \\/ wordToN w = 6 \\/ wordToN w = 7 \\/\n            wordToN w = 8 \\/ wordToN w = 9 \\/ wordToN w = 10 \\/ wordToN w = 11 \\/\n            wordToN w = 12 \\/ wordToN w = 13 \\/ wordToN w = 14 \\/ wordToN w = 15 \\/\n            wordToN w = 16 \\/ wordToN w = 17 \\/ wordToN w = 18 \\/ wordToN w = 19 \\/\n            wordToN w = 20 \\/ wordToN w = 21 \\/ wordToN w = 22 \\/ wordToN w = 23 \\/\n            wordToN w = 24 \\/ wordToN w = 25 \\/ wordToN w = 26 \\/ wordToN w = 27 \\/\n            wordToN w = 28 \\/ wordToN w = 29 \\/ wordToN w = 30 \\/ wordToN w = 31)%N\n      by abstract blia.\n    clear H.\n    repeat match goal with\n           | H: _ \\/ _ |- _ => destruct H\n           end.\n\n    all: match goal with\n         | H: wordToN _ = ?n |- _ =>\n           change n with (wordToN (sz:= 5) $(N.to_nat n)) in H;\n             apply wordToN_inj in H; subst; simpl\n         end.\n    all: cbv [riscvRegsInit setRegsInit].\n    all: repeat rewrite map.get_put_diff by discriminate.\n    all: rewrite map.get_put_same.\n    all: reflexivity.\n  Qed.\n\n  Lemma riscvRegsInit_sound:\n    forall reg, 0 < reg < 32 -> map.get riscvRegsInit reg <> None.\n  Proof.\n    intros.\n    assert (reg = 1 \\/ reg = 2 \\/ reg = 3 \\/\n            reg = 4 \\/ reg = 5 \\/ reg = 6 \\/ reg = 7 \\/\n            reg = 8 \\/ reg = 9 \\/ reg = 10 \\/ reg = 11 \\/\n            reg = 12 \\/ reg = 13 \\/ reg = 14 \\/ reg = 15 \\/\n            reg = 16 \\/ reg = 17 \\/ reg = 18 \\/ reg = 19 \\/\n            reg = 20 \\/ reg = 21 \\/ reg = 22 \\/ reg = 23 \\/\n            reg = 24 \\/ reg = 25 \\/ reg = 26 \\/ reg = 27 \\/\n            reg = 28 \\/ reg = 29 \\/ reg = 30 \\/ reg = 31)\n      by abstract blia.\n    clear H.\n    repeat match goal with\n           | H: _ \\/ _ |- _ => destruct H\n           end.\n\n    all: subst.\n    all: cbv [riscvRegsInit setRegsInit].\n    all: repeat rewrite map.get_put_diff by discriminate.\n    all: rewrite map.get_put_same.\n    all: discriminate.\n  Qed.\n\n  Definition riscvMemInit : mem := map.of_list (List.map\n    (fun i : nat =>\n      (word.of_Z (Z.of_nat i),\n       byte.of_Z (uwordToZ (evalConstT kamiMemInit $i))))\n    (seq 0 (2 ^ Z.to_nat memSizeLg))).\n\n  Instance kword32: coqutil.Word.Interface.word 32 := KamiWord.word 32.\n  Instance kword32_ok: word.ok kword32. eapply KamiWord.ok. reflexivity. Qed.\n  Lemma riscvMemInit_get_None:\n    forall addr,\n      (kunsigned addr <? 2 ^ memSizeLg) = false ->\n      map.get riscvMemInit addr = None.\n  Proof.\n    intros.\n    apply get_of_list_not_In; [exact (@weq (Z.to_nat width))|assumption|].\n\n    intro Hx.\n    apply in_map_iff in Hx; destruct Hx as [[addr' v] [? Hx]].\n    simpl in H0; subst.\n    apply in_map_iff in Hx; destruct Hx as [n [? ?]].\n    inversion H0; subst; clear H0.\n    apply in_seq in H1; destruct H1 as [_ ?]; simpl in H0.\n\n    apply Nat2Z.inj_lt in H0.\n    rewrite N_Z_nat_conversions.Nat2Z.inj_pow in H0.\n    rewrite Z2Nat.id in H0 by blia.\n    simpl in H0.\n\n    match type of H with\n    | (?x <? ?y) = false => destruct (Z.ltb_spec x y); [discriminate|clear H]\n    end.\n    change kunsigned with (word.unsigned (width:= width)) in H1.\n    change kofZ with (word.of_Z (width:= width)) in H1.\n    rewrite word.unsigned_of_Z in H1.\n    cbv [word.wrap] in H1.\n    rewrite Z.mod_small in H1\n      by (split; [blia|];\n          eapply Z.lt_le_trans; [eassumption|];\n          apply Z.pow_le_mono_r; blia).\n    blia.\n  Qed.\n\n  Lemma mem_related_riscvMemInit : mem_related _ (evalConstT kamiMemInit) riscvMemInit.\n  Proof.\n    cbv [mem_related riscvMemInit].\n    intros addr.\n    case (kunsigned addr <? 2 ^ memSizeLg) eqn:H.\n    2: { apply riscvMemInit_get_None; assumption. }\n    assert (#addr < 2 ^ Z.to_nat memSizeLg)%nat.\n    { rewrite <-wordToN_to_nat.\n      apply Nat2Z.inj_lt.\n      rewrite N_nat_Z, N_Z_nat_conversions.Nat2Z.inj_pow.\n      rewrite Z2Nat.id by blia.\n      apply Z.ltb_lt; assumption.\n    }\n    erewrite Properties.map.get_of_list_In_NoDup; trivial.\n    1: eapply NoDup_nth_error; intros i j ?.\n    2: eapply (nth_error_In _ (wordToNat addr)).\n\n    { rewrite map_map; cbn; cbv [kofZ].\n      clear dependent addr.\n      rewrite !map_length, seq_length in H1.\n      rewrite (@map_nth_error _ _ _ _ _ i).\n      2: etransitivity; [eapply nth_error_nth'|];\n           rewrite ?seq_length, ?seq_nth; trivial.\n      destruct (lt_dec j (2^Z.to_nat memSizeLg)).\n      { rewrite (@map_nth_error _ _ _ _ _ j).\n        2: etransitivity; [eapply nth_error_nth'|];\n            rewrite ?seq_length, ?seq_nth; trivial.\n        intros HX.\n        injection HX; clear HX; intros HX.\n        eapply (f_equal (@wordToZ _)) in HX.\n        pose proof Z.pow_le_mono_r 2 memSizeLg 31 eq_refl ltac:(blia);\n        pose proof N_Z_nat_conversions.Z2Nat.inj_pow 2 memSizeLg ltac:(blia) ltac:(blia);\n        change (Z.to_nat 2) with 2%nat in *.\n        rewrite 2wordToZ_ZToWord'' in HX; try split;\n         change (BinInt.Z.of_nat (Pos.to_nat 32) - 1) with 31;\n         blia. }\n      { rewrite (proj2 (nth_error_None _ _)); try congruence.\n        rewrite map_length, seq_length; blia. } }\n    { replace (evalZeroExtendTrunc (BinInt.Z.to_nat memSizeLg) addr)\n        with (natToWord (Z.to_nat memSizeLg) (wordToNat addr)).\n      2: {\n        cbv [evalZeroExtendTrunc].\n        destruct (lt_dec _ _); [exfalso; apply Z2Nat.inj_lt in l; blia|].\n        apply wordToNat_inj.\n        rewrite wordToNat_natToWord_eqn.\n        rewrite wordToNat_split1.\n        cbv [eq_rec_r eq_rec]; rewrite wordToNat_eq_rect.\n        reflexivity.\n      }\n      rewrite (@map_nth_error _ _ _ _ _ (wordToNat addr)).\n      2: {\n        etransitivity; [eapply nth_error_nth'|].\n        all : rewrite ?seq_length, ?seq_nth; trivial.\n      }\n      do 2 f_equal.\n      eapply word.unsigned_inj.\n      rewrite word.unsigned_of_Z.\n      cbv [word.wrap]; rewrite <-word.wrap_unsigned; f_equal.\n      unfold word.unsigned, word, wordW, KamiWord.word, kword, kunsigned.\n      rewrite wordToN_nat, nat_N_Z; reflexivity.\n    }\n    Unshelve. all: exact O.\n  Qed.\n\n  Lemma states_related_init:\n    states_related\n      (initRegs (getRegInits (proc Hinstr kamiMemInit (kami_AbsMMIO (Z.to_N memSizeLg)))), [])\n      {| getMachine :=\n           {| RiscvMachine.getRegs := riscvRegsInit;\n              RiscvMachine.getPc := word.of_Z 0;\n              RiscvMachine.getNextPc := word.of_Z 4;\n              RiscvMachine.getMem := riscvMemInit;\n              RiscvMachine.getXAddrs := kamiXAddrs instrMemSizeLg;\n              RiscvMachine.getLog := nil; (* <-- intended to be nil *) |};\n         getMetrics := MetricLogging.EmptyMetricLog; |}.\n  Proof.\n    econstructor; try reflexivity.\n    - econstructor.\n    - eapply pRegsToT_init.\n    - intros; discriminate.\n    - split; reflexivity.\n    - apply regs_related_riscvRegsInit.\n    - apply mem_related_riscvMemInit.\n  Qed.\n\n  Lemma equivalentLabel_preserves_KamiLabelR:\n    forall l1 l2,\n      equivalentLabel (liftToMap1 (@idElementwise _)) l1 l2 ->\n      forall l,\n        KamiLabelR l2 l -> KamiLabelR l1 l.\n  Proof.\n    intros.\n    destruct l1 as [ann1 ds1 cs1], l2 as [ann2 ds2 cs2].\n    destruct H as [? [? ?]]; simpl in *.\n    rewrite SemFacts.liftToMap1_idElementwise_id in H, H1; subst.\n    inversion_clear H0; subst.\n    - apply KamiSilent; assumption.\n    - eapply KamiMMIO; eauto.\n  Qed.\n\n  Lemma equivalentLabelSeq_preserves_KamiLabelSeqR:\n    forall t1 t2,\n      equivalentLabelSeq (liftToMap1 (@idElementwise _)) t1 t2 ->\n      forall t,\n        KamiLabelSeqR t2 t ->\n        KamiLabelSeqR t1 t.\n  Proof.\n    induction 1; intros; [assumption|].\n    inversion_clear H1.\n    constructor; auto.\n    eapply equivalentLabel_preserves_KamiLabelR; eauto.\n  Qed.\n\n  Lemma riscv_init_memory_undef_on_MMIO:\n    map.undef_on riscvMemInit isMMIOAddr.\n  Proof.\n    cbv [map.undef_on map.agree_on]; intros.\n    cbv [elem_of] in H.\n    pose proof (mmio_mem_disjoint _ Hkmemdisj _ H); clear H.\n    rewrite map.get_empty.\n    apply riscvMemInit_get_None.\n    destruct (Z.ltb_spec (kunsigned k) (2 ^ memSizeLg)); intuition idtac.\n  Qed.\n\n  Lemma mmio_init_xaddrs_disjoint:\n    disjoint (of_list (kamiXAddrs instrMemSizeLg)) isMMIOAddr.\n  Proof.\n    cbv [disjoint of_list elem_of]; intros.\n    pose proof (mmio_mem_disjoint _ Hkmemdisj x).\n    destruct (Z.ltb_spec (kunsigned x) (2 ^ memSizeLg)).\n    - right; intro Hx; auto.\n    - left; intro Hx.\n      apply kamiXAddrs_isXAddr1_bound in Hx.\n      apply N2Z.inj_lt in Hx.\n      rewrite NatLib.Z_of_N_Npow2 in Hx.\n      assert (2 ^ BinInt.Z.of_nat (2 + Z.to_nat instrMemSizeLg) < 2 ^ memSizeLg)\n        by (apply Z.pow_lt_mono_r; blia).\n      cbv [kunsigned] in *.\n      blia.\n  Qed.\n\n  Lemma riscv_to_kamiImplProcessor:\n    forall (traceProp: list Event -> Prop)\n           (* --- hypotheses which will be proven by the compiler --- *)\n           (RvInv: RiscvMachine -> Prop)\n           (establishRvInv:\n              forall (m0RV: RiscvMachine),\n                m0RV.(RiscvMachine.getMem) = riscvMemInit ->\n                m0RV.(RiscvMachine.getPc) = word.of_Z 0 ->\n                m0RV.(RiscvMachine.getNextPc) = word.of_Z 4 ->\n                (forall a: word,\n                    0 <= word.unsigned a < 2 ^ (2 + instrMemSizeLg) ->\n                    In a m0RV.(RiscvMachine.getXAddrs)) ->\n                disjoint (of_list m0RV.(RiscvMachine.getXAddrs)) isMMIOAddr ->\n                (forall reg, 0 < reg < 32 -> map.get m0RV.(getRegs) reg <> None) ->\n                m0RV.(getLog) = nil ->\n                RvInv m0RV)\n           (preserveRvInv:\n              forall (m: RiscvMachine), RvInv m -> mcomp_sat_unit (run1 iset) m RvInv)\n           (useRvInv:\n              forall (m: RiscvMachine),\n                RvInv m -> exists t, traces_related t m.(getLog) /\\\n                                     traceProp t),\n    (* --- final end to end theorem will start here --- *)\n    forall (t: list LabelT) (mFinal: KamiImplMachine),\n      Behavior p4mm mFinal t ->\n      (* --- conclusion ---\n         The trace produced by the kami implementation can be mapped to an MMIO trace\n         (this guarantees that the only external behavior of the kami implementation is MMIO)\n         and moreover, this MMIO trace satisfies some desirable property. *)\n      exists (t': list Event), KamiLabelSeqR t t' /\\ traceProp t'.\n  Proof.\n    intros.\n    pose proof (@proc_correct instrMemSizeLg memSizeLg Hinstr kamiMemInit) as P.\n    unfold traceRefines in P.\n    specialize P with (1 := H).\n    destruct P as (mFinal' & t' & B & E).\n    inversion_clear B.\n    edestruct ksteps_sound as (rs2 & Rel & Inv). 2: unfold calways; split.\n    - econstructor.\n      + eapply Kami.SemFacts.reachable_init.\n      + eapply states_related_init.\n      + eapply KamiSeqNil.\n    - eapply establishRvInv; try reflexivity.\n      all: cbv [getXAddrs getMachine]; intros.\n      + apply alignedXAddrsRange_zero_bound_in.\n        apply N2Z.inj_lt.\n        rewrite nat_N_Z.\n        cbv [instrMemSize].\n        rewrite N_Z_nat_conversions.Nat2Z.inj_pow.\n        rewrite Nat2Z.inj_add, Z2Nat.id by blia.\n        apply H0.\n      + apply mmio_init_xaddrs_disjoint.\n      + apply riscvRegsInit_sound; assumption.\n    - exact preserveRvInv.\n    - econstructor. exact HMultistepBeh.\n    - specialize (useRvInv _ Inv).\n      inversion Rel. subst. clear Rel.\n      simpl in useRvInv.\n      destruct useRvInv as (t''' & R' & p).\n      eexists. split; [|exact p].\n      rewrite app_nil_r in H5.\n      inversion H3. subst. clear H3.\n      eapply equivalentLabelSeq_preserves_KamiLabelSeqR.\n      1: eassumption.\n      pose proof (traces_related_unique R' H4). subst t'''.\n      assumption.\n  Qed.\n\nEnd Equiv.\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/processor/src/processor/KamiRiscv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.17596658100840357}}
{"text": "(* Middle-end optimizer *)\n(* Inerting Speculation in CoreIR programs *)\n\nRequire Import RTL.\nRequire Import IR.\nRequire Import monad.\nRequire Import common.\nRequire Import Coqlib.\nRequire Import backend.\nRequire Import primitives.\nRequire Import anchor_insertion.\nRequire Import assume_insertion.\nRequire Import anchor_removal.\nRequire Import profiler_types.\nRequire Import Errors.\nRequire Import monad.\n\n(* Inserting Anchors in all functions according to the profiler wish *)\nFixpoint process_anc_list (p:program) (l:list (fun_id * list label)): program :=\n  match l with\n  | nil => p\n  | (fid, anc_lbl)::l' => process_anc_list (safe_insert_anchor p fid anc_lbl) l'\n  end.\n\n(* Processing each middle_end optimization sugeested by the profiler *)\n(* Using the safe optimizations: if one fails, it is just ignored by the optimizer *)\nFixpoint process_optim_list (p:program) (l:list (fun_id * middle_wish)): program :=\n  match l with\n  | nil => p\n  | (fid, AS_INS guard anc_lbl)::l' => process_optim_list (safe_insert_assume p fid guard anc_lbl) l'\n  end.\n\nDefinition middle_end (ps:profiler_state) (p:program): res program :=\n    do optims <- OK (middle_end_suggestion ps);\n    do fs_list <- OK (anchors_to_insert ps);\n    do pfs <- OK (process_anc_list p fs_list);\n    do newp <- OK (process_optim_list pfs optims);\n    OK (lowering newp).\n\n(* An error in optimization should not stop the execution *)\nDefinition safe_middle_end (ps:profiler_state) (p:program): program :=\n  safe_res (middle_end ps) p.\n\n\n", "meta": {"author": "Aurele-Barriere", "repo": "JIThm", "sha": "ad3ae5a3d6759a070195815e321df1b372d982b9", "save_path": "github-repos/coq/Aurele-Barriere-JIThm", "path": "github-repos/coq/Aurele-Barriere-JIThm/JIThm-ad3ae5a3d6759a070195815e321df1b372d982b9/coqjit/middle_end.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.17589391641260146}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import auth csum frac agree.\nFrom iris.bi Require Import fractional.\nFrom lrust.lifetime Require Import na_borrow.\nFrom lrust.typing Require Import typing.\nFrom lrust.typing.lib.refcell Require Import refcell.\nFrom iris.prelude Require Import options.\n\nDefinition refcell_refN := refcellN .@ \"ref\".\n\nSection ref.\n  Context `{!typeGS \u03a3, !refcellG \u03a3}.\n\n  (* The Rust type looks as follows (after some unfolding):\n\n     pub struct Ref<'b, T: ?Sized + 'b> {\n       value: &'b T,\n       borrow: &'b Cell<BorrowFlag>,\n     }\n  *)\n\n  Program Definition ref (\u03b1 : lft) (ty : type) :=\n    tc_opaque\n    {| ty_size := 2;\n       ty_own tid vl :=\n         match vl return _ with\n         | [ #(LitLoc lv);  #(LitLoc lrc) ] =>\n           \u2203 \u03bd q \u03b3 \u03b2 ty', ty.(ty_shr) (\u03b1 \u2293 \u03bd) tid lv \u2217\n             \u03b1 \u2291 \u03b2 \u2217 &na{\u03b2, tid, refcell_invN}(refcell_inv tid lrc \u03b3 \u03b2 ty') \u2217\n             q.[\u03bd] \u2217 own \u03b3 (\u25ef reading_stR q \u03bd)\n         | _ => False\n         end;\n       ty_shr \u03ba tid l :=\n          \u2203 \u03bd q \u03b3 \u03b2 ty' (lv lrc : loc),\n             \u03ba \u2291 \u03bd \u2217 &frac{\u03ba} (\u03bb q, l\u21a6\u2217{q} [ #lv; #lrc]) \u2217\n             \u25b7 ty.(ty_shr) (\u03b1 \u2293 \u03bd) tid lv \u2217\n             \u25b7 (\u03b1 \u2291 \u03b2) \u2217 \u25b7 &na{\u03b2, tid, refcell_invN}(refcell_inv tid lrc \u03b3 \u03b2 ty') \u2217\n             &na{\u03ba, tid, refcell_refN}(own \u03b3 (\u25ef reading_stR q \u03bd)) |}%I.\n  Next Obligation. iIntros (???[|[[]|][|[[]|][]]]) \"?\"; auto. Qed.\n  Next Obligation.\n    iIntros (\u03b1 ty E \u03ba l tid q ?) \"#LFT Hb Htok\".\n    iMod (bor_exists with \"LFT Hb\") as (vl) \"Hb\"; first done.\n    iMod (bor_sep with \"LFT Hb\") as \"[H\u21a6 Hb]\"; first done.\n    iMod (bor_fracture (\u03bb q, l \u21a6\u2217{q} vl)%I with \"LFT H\u21a6\") as \"#H\u21a6\"; first done.\n    destruct vl as [|[[|lv|]|][|[[|lrc|]|][]]];\n      try by iMod (bor_persistent with \"LFT Hb Htok\") as \"[>[] _]\".\n    iMod (bor_exists with \"LFT Hb\") as (\u03bd) \"Hb\"; first done.\n    iMod (bor_exists with \"LFT Hb\") as (q') \"Hb\"; first done.\n    iMod (bor_exists with \"LFT Hb\") as (\u03b3) \"Hb\"; first done.\n    iMod (bor_exists with \"LFT Hb\") as (\u03b2) \"Hb\"; first done.\n    iMod (bor_exists with \"LFT Hb\") as (ty') \"Hb\"; first done.\n    iMod (bor_sep with \"LFT Hb\") as \"[Hshr Hb]\"; first done.\n    iMod (bor_persistent with \"LFT Hshr Htok\") as \"[#Hshr Htok]\"; first done.\n    iMod (bor_sep with \"LFT Hb\") as \"[H\u03b1\u03b2 Hb]\"; first done.\n    iMod (bor_persistent with \"LFT H\u03b1\u03b2 Htok\") as \"[#H\u03b1\u03b2 Htok]\"; first done.\n    iMod (bor_sep with \"LFT Hb\") as \"[Hinv Hb]\"; first done.\n    iMod (bor_persistent with \"LFT Hinv Htok\") as \"[#Hinv $]\"; first done.\n    iMod (bor_sep with \"LFT Hb\") as \"[H\u03ba\u03bd Hb]\"; first done.\n    iDestruct (frac_bor_lft_incl with \"LFT [> H\u03ba\u03bd]\") as \"#H\u03ba\u03bd\".\n    { iApply bor_fracture; try done. by rewrite Qp_mul_1_r. }\n    iMod (bor_na with \"Hb\") as \"#Hb\"; first done. eauto 20.\n  Qed.\n  Next Obligation.\n    iIntros (??????) \"#? H\". iDestruct \"H\" as (\u03bd q \u03b3 \u03b2 ty' lv lrc) \"H\".\n    iExists _, _, _, _, _, _, _. iDestruct \"H\" as \"#(? & ? & $ & $ & $ & ?)\".\n    iSplit; last iSplit.\n    - by iApply lft_incl_trans.\n    - by iApply frac_bor_shorten.\n    - by iApply na_bor_shorten.\n  Qed.\n\n  Global Instance ref_wf \u03b1 ty `{!TyWf ty} : TyWf (ref \u03b1 ty) :=\n    { ty_lfts := [\u03b1]; ty_wf_E := ty_wf_E ty ++ ty_outlives_E ty \u03b1 }.\n\n  Global Instance ref_type_contractive \u03b1 : TypeContractive (ref \u03b1).\n  Proof. solve_type_proper. Qed.\n  Global Instance ref_ne \u03b1 : NonExpansive (ref \u03b1).\n  Proof. apply type_contractive_ne, _. Qed.\n\n  Global Instance ref_mono E L :\n    Proper (flip (lctx_lft_incl E L) ==> subtype E L ==> subtype E L) ref.\n  Proof.\n    iIntros (\u03b11 \u03b12 H\u03b1 ty1 ty2 Hty qmax qL) \"HL\".\n    iDestruct (Hty with \"HL\") as \"#Hty\". iDestruct (H\u03b1 with \"HL\") as \"#H\u03b1\".\n    iIntros \"!> #HE\". iDestruct (\"H\u03b1\" with \"HE\") as %H\u03b11\u03b12.\n    iDestruct (\"Hty\" with \"HE\") as \"(%&#Ho&#Hs)\". iSplit; [|iSplit; iModIntro].\n    - done.\n    - iIntros (tid [|[[]|][|[[]|][]]]) \"H\"=>//=.\n      iDestruct \"H\" as (\u03bd q' \u03b3 \u03b2 ty') \"(#Hshr & #H\u2291 & #Hinv & Htok & Hown)\".\n      iExists \u03bd, q', \u03b3, \u03b2, ty'. iFrame \"\u2217#\". iSplit.\n      + iApply ty_shr_mono; last by iApply \"Hs\".\n        iApply lft_intersect_mono; first by iApply lft_incl_syn_sem. iApply lft_incl_refl.\n      + iApply lft_incl_trans; first by iApply lft_incl_syn_sem. done.\n    - iIntros (\u03ba tid l) \"H /=\". iDestruct \"H\" as (\u03bd q' \u03b3 \u03b2 ty' lv lrc) \"H\".\n      iExists \u03bd, q', \u03b3, \u03b2, ty', lv, lrc. iDestruct \"H\" as \"#($&$&?&?&$&$)\". iSplit.\n      + iApply ty_shr_mono; last by iApply \"Hs\".\n        iApply lft_intersect_mono; first by iApply lft_incl_syn_sem. iApply lft_incl_refl.\n      + iApply lft_incl_trans; first by iApply lft_incl_syn_sem. done.\n  Qed.\n  Global Instance ref_mono_flip E L :\n    Proper (lctx_lft_incl E L ==> flip (subtype E L) ==> flip (subtype E L)) ref.\n  Proof. intros ??????. by apply ref_mono. Qed.\n  Lemma ref_mono' E L \u03b11 \u03b12 ty1 ty2 :\n    lctx_lft_incl E L \u03b12 \u03b11 \u2192 subtype E L ty1 ty2 \u2192\n    subtype E L (ref \u03b11 ty1) (ref \u03b12 ty2).\n  Proof. intros. by eapply ref_mono. Qed.\n  Global Instance ref_proper E L :\n    Proper (lctx_lft_eq E L ==> eqtype E L ==> eqtype E L) ref.\n  Proof. intros ??[]?? EQ. split; apply ref_mono'; try done; apply EQ. Qed.\n  Lemma ref_proper' E L \u03b11 \u03b12 ty1 ty2 :\n    lctx_lft_eq E L \u03b11 \u03b12 \u2192 eqtype E L ty1 ty2 \u2192\n    eqtype E L (ref \u03b11 ty1) (ref \u03b12 ty2).\n  Proof. intros. by eapply ref_proper. Qed.\nEnd ref.\n\nGlobal Hint Resolve refcell_mono' refcell_proper' : 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/lib/refcell/ref.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.1758939129062997}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Vectors.Vector\n        Coq.ZArith.ZArith.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.EnumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.WordFacts\n        Fiat.Narcissus.Common.ComposeCheckSum\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats\n        Fiat.Narcissus.BaseFormats\n        Fiat.Narcissus.Stores.EmptyStore.\n\nRequire Import Bedrock.Word.\n\nDefinition decode_IPChecksum\n  : ByteString -> CacheDecode -> Hopefully (() * ByteString * CacheDecode) :=\n  decode_unused_word (sz := 16).\n\nDefinition encode_word {sz} (w : word sz) : ByteString :=\n  encode_word' sz w ByteString_id.\n\nFixpoint Vector_checksum_bound n {sz} (bytes :ByteBuffer.t sz) acc : InternetChecksum.W16 :=\n  match n, bytes with\n  | 0, _ => acc\n  | _, Vector.nil => acc\n  | S 0, Vector.cons x _ _ => InternetChecksum.add_bytes_into_checksum x (wzero _) acc\n  | _, Vector.cons x _ Vector.nil => InternetChecksum.add_bytes_into_checksum x (wzero _) acc\n  | S (S n'), Vector.cons x _ (Vector.cons y _ t) =>\n    (Vector_checksum_bound n' t (InternetChecksum.add_bytes_into_checksum x y acc))\n  end.\n\nDefinition ByteBuffer_checksum_bound' n {sz} (bytes : ByteBuffer.t sz) : InternetChecksum.W16 :=\n  InternetChecksum.ByteBuffer_fold_left_pair InternetChecksum.add_bytes_into_checksum n bytes (wzero _) (wzero _).\n\nLemma ByteBuffer_checksum_bound'_ok' :\n  forall n {sz} (bytes :ByteBuffer.t sz) acc,\n    Vector_checksum_bound n bytes acc =\n    InternetChecksum.ByteBuffer_fold_left_pair InternetChecksum.add_bytes_into_checksum n bytes acc (wzero _).\nProof.\n  fix IH 3.\n  destruct bytes as [ | hd sz [ | hd' sz' tl ] ]; intros; simpl.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; try reflexivity.\n    rewrite IH; reflexivity.\nQed.\n\nLemma ByteBuffer_checksum_bound'_ok :\n  forall n {sz} (bytes :ByteBuffer.t sz),\n    Vector_checksum_bound n bytes (wzero _) = ByteBuffer_checksum_bound' n bytes.\nProof.\n  intros; apply ByteBuffer_checksum_bound'_ok'.\nQed.\n\nDefinition IPChecksum_Valid_dec (n : nat) (b : ByteString)\n  : {IPChecksum_Valid n b} + {~IPChecksum_Valid n b} := weq _ _.\n\nDefinition calculate_IPChecksum {S} {sz}\n  : AlignedEncodeM (S := S) sz :=\n  (fun v =>\n     (let checksum := InternetChecksum.ByteBuffer_checksum_bound 20 v in\n      (fun v idx s => SetByteAt (n := sz) 10 v 0 (wnot (split2 8 8 checksum)) ) >>\n                                                                                (fun v idx s => SetByteAt (n := sz) 11 v 0 (wnot (split1 8 8 checksum)))) v)%AlignedEncodeM.\n\nDefinition splitLength (len: word 16) : Vector.t (word 8) 2 :=\n  Vector.cons _ (split2 8 8 len) _ (Vector.cons _ (split1 8 8 len) _ (Vector.nil _)).\n\nDefinition Pseudo_Checksum_Valid\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (n : nat) (* Number of /bits/ in checksum; needed by\n                        ByteString2ListOfChar *)\n           (b : ByteString)\n  := onesComplement (wzero 8 :: protoCode ::\n                           to_list srcAddr ++ to_list destAddr ++ to_list (splitLength udpLength)\n                           ++ (ByteString2ListOfChar n b)\n                    )%list\n     = wones 16.\n\nImport VectorNotations.\n\nDefinition pseudoHeader_checksum\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           {sz} (packet: ByteBuffer.t sz) :=\n  InternetChecksum.ByteBuffer_checksum_bound (12 + measure)\n                                             (srcAddr ++ destAddr ++ [wzero 8; protoCode] ++ (splitLength udpLength) ++ packet).\n\nInfix \"^1+\" := (InternetChecksum.OneC_plus) (at level 50, left associativity).\n\nImport InternetChecksum.\n\nDefinition pseudoHeader_checksum'\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           {sz} (packet: ByteBuffer.t sz) :=\n  ByteBuffer_checksum srcAddr ^1+\n                               ByteBuffer_checksum destAddr ^1+\n                                                             zext protoCode 8 ^1+\n                                                                               udpLength ^1+\n                                                                                          InternetChecksum.ByteBuffer_checksum_bound measure packet.\n\nLemma OneC_plus_wzero_l :\n  forall w, OneC_plus (wzero 16) w = w.\nProof. reflexivity. Qed.\n\nLemma OneC_plus_wzero_r :\n  forall w, OneC_plus w (wzero 16) = w.\nProof.\n  intros; rewrite OneC_plus_comm; reflexivity.\nQed.\n\nLemma Buffer_fold_left16_acc_oneC_plus :\n  forall {sz} (packet: ByteBuffer.t sz) acc n,\n    ByteBuffer_fold_left16 add_w16_into_checksum n packet acc =\n    OneC_plus\n      (ByteBuffer_fold_left16 add_w16_into_checksum n packet (wzero 16))\n      acc.\nProof.\n  fix IH 2.\n  unfold ByteBuffer_fold_left16 in *.\n  destruct packet as [ | hd sz [ | hd' sz' tl ] ]; intros; simpl.\n  - destruct n as [ | [ | ] ]; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; unfold add_bytes_into_checksum, add_w16_into_checksum;\n      try rewrite OneC_plus_wzero_l, OneC_plus_comm; reflexivity.\n  - destruct n as [ | [ | ] ]; simpl; unfold add_bytes_into_checksum, add_w16_into_checksum;\n      try rewrite OneC_plus_wzero_l, OneC_plus_comm; try reflexivity.\n    rewrite (IH _ tl (hd' +^+ hd ^1+ acc)).\n    rewrite (IH _ tl (hd' +^+ hd)).\n    rewrite OneC_plus_assoc.\n    reflexivity.\nQed.\n\nLemma Vector_destruct_S :\n  forall {A sz} (v: Vector.t A (S sz)),\n  exists hd tl, v = hd :: tl.\nProof.\n  repeat eexists.\n  apply VectorSpec.eta.\nDefined.\n\nLemma Vector_destruct_O :\n  forall {A} (v: Vector.t A 0),\n    v = [].\nProof.\n  intro; apply Vector.case0; reflexivity.\nQed.\n\nLtac explode_vector :=\n  unfold ByteBuffer.t in *;\n  lazymatch goal with\n  | [ v: Vector.t ?A (S ?n) |- _ ] =>\n    let hd := fresh \"hd\" in\n    let tl := fresh \"tl\" in\n    rewrite (Vector.eta v) in *;\n    set (Vector.hd v: A) as hd; clearbody hd;\n    set (Vector.tl v: Vector.t A n) as tl; clearbody tl;\n    clear v\n  | [ v: Vector.t _ 0 |- _ ] =>\n    rewrite (Vector_destruct_O v) in *; clear v\n  end.\n\nLemma pseudoHeader_checksum'_ok :\n  forall (srcAddr : ByteBuffer.t 4)\n        (destAddr : ByteBuffer.t 4)\n         (measure : nat)\n         (udpLength : word 16)\n         (protoCode : word 8)\n         {sz} (packet: ByteBuffer.t sz),\n    pseudoHeader_checksum srcAddr destAddr measure udpLength protoCode packet =\n    pseudoHeader_checksum' srcAddr destAddr measure udpLength protoCode packet.\nProof.\n  unfold pseudoHeader_checksum, pseudoHeader_checksum'.\n  intros.\n  repeat explode_vector.\n  Opaque split1.\n  Opaque split2.\n  simpl in *.\n  unfold ByteBuffer_checksum, InternetChecksum.ByteBuffer_checksum_bound, add_w16_into_checksum,\n  add_bytes_into_checksum, ByteBuffer_fold_left16, ByteBuffer_fold_left_pair.\n  fold @ByteBuffer_fold_left_pair.\n  setoid_rewrite Buffer_fold_left16_acc_oneC_plus.\n  rewrite combine_split.\n  rewrite !OneC_plus_wzero_r, !OneC_plus_wzero_l, OneC_plus_comm.\n  repeat (f_equal; [ ]).\n  rewrite <- !OneC_plus_assoc.\n  reflexivity.\nQed.\n\nDefinition calculate_PseudoChecksum {S} {sz}\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (measure : nat)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (idx' : nat)\n  : AlignedEncodeM (S := S) sz :=\n  (fun v idx s =>\n     (let checksum := pseudoHeader_checksum' srcAddr destAddr measure udpLength protoCode v in\n      (fun v idx s => SetByteAt (n := sz) idx' v 0 (wnot (split2 8 8 checksum)) ) >>\n                                                                                  (fun v idx s => SetByteAt (n := sz) (1 + idx') v 0 (wnot (split1 8 8 checksum)))) v idx s)%AlignedEncodeM.\n\nLemma ByteBuffer_to_list_append {sz sz'}\n  : forall (v : ByteBuffer.t sz)\n           (v' : ByteBuffer.t sz'),\n    ByteBuffer.to_list (v ++ v')%vector\n    = ((ByteBuffer.to_list v) ++ (ByteBuffer.to_list v'))%list.\nProof.\n  induction v.\n  - reflexivity.\n  - simpl; intros.\n    unfold ByteBuffer.to_list at 1; unfold to_list.\n    f_equal.\n    apply IHv.\nQed.\n\nImport VectorNotations.\n\n\nLemma Pseudo_Checksum_Valid_bounded\n      {A}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      protoCode\n      (predicate : A -> Prop)\n      (format_A format_B : FormatM A ByteString)\n      (len_format_A : A -> nat)\n      (len_format_A_OK : forall a' b ctx ctx',\n          computes_to (format_A a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_A a')\n      (len_format_B : A -> nat)\n      (len_format_B_OK : forall a' b ctx ctx',\n          computes_to (format_B a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_B a')\n      (byte_aligned_A : forall a : A, len_format_A a mod 8 = 0)\n      (byte_aligned_B : forall a : A, len_format_B a mod 8 = 0)\n  : forall (data : A) (x : ByteString) (x0 : CacheFormat) (x1 : ByteString) (x2 : CacheFormat)\n           (ext ext' : ByteString) (env : CacheFormat) (c : word 16),\n    predicate data ->\n    format_A data env \u220b (x, x0) ->\n    format_B data (addE x0 16) \u220b (x1, x2) ->\n    Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode\n                          (bin_measure (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)))\n                          (mappend (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)) ext) ->\n    Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode\n                          (bin_measure (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)))\n                          (mappend (mappend x (mappend (format_checksum ByteString monoid ByteString_QueueMonoidOpt 16 c) x1)) ext').\nProof.\n  intros.\n    unfold Pseudo_Checksum_Valid in *.\n    revert H2.\n    rewrite !ByteString2ListOfChar_Over; eauto.\n    simpl; rewrite padding_eq_mod_8.\n    rewrite !length_ByteString_enqueue_ByteString.\n    rewrite Nat.add_mod by Lia.lia.\n    apply len_format_A_OK in H0.\n    apply len_format_B_OK in H1.\n    unfold format_checksum; rewrite length_encode_word', measure_mempty.\n    rewrite H0, byte_aligned_A, plus_O_n, NPeano.Nat.mod_mod, Nat.add_mod by Lia.lia.\n    rewrite H1, byte_aligned_B, <- plus_n_O, NPeano.Nat.mod_mod by Lia.lia.\n    reflexivity.\n    simpl; rewrite padding_eq_mod_8.\n    rewrite !length_ByteString_enqueue_ByteString.\n    rewrite Nat.add_mod by Lia.lia.\n    apply len_format_A_OK in H0.\n    apply len_format_B_OK in H1.\n    rewrite H0, byte_aligned_A, plus_O_n, NPeano.Nat.mod_mod, Nat.add_mod by Lia.lia.\n    rewrite H1, byte_aligned_B, <- plus_n_O, NPeano.Nat.mod_mod by Lia.lia.\n    unfold format_checksum; rewrite length_encode_word'; reflexivity.\nQed.\n\nLemma compose_PseudoChecksum_format_correct' {A}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      protoCode\n      (predicate : A -> Prop)\n      (P : CacheDecode -> Prop)\n      (P_inv : (CacheDecode -> Prop) -> Prop)\n      (P_invM : (CacheDecode -> Prop) -> Prop)\n      (format_A format_B : FormatM A ByteString)\n      (subformat : FormatM A ByteString)\n      (decode_measure : DecodeM (nat * _) _)\n      (len_format_A : A -> nat)\n      (len_format_A_OK : forall a' b ctx ctx',\n          computes_to (format_A a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_A a')\n      (len_format_B : A -> nat)\n      (len_format_B_OK : forall a' b ctx ctx',\n          computes_to (format_B a' ctx) (b, ctx')\n          -> length_ByteString b = len_format_B a')\n      View_Predicate\n      format_measure\n  : cache_inv_Property P (fun P => P_inv P /\\ P_invM P) ->\n    (forall a, NPeano.modulo (len_format_A a) 8 = 0)\n    -> (forall a, NPeano.modulo (len_format_B a) 8 = 0)\n    ->\n    forall decodeA : _ -> CacheDecode -> Hopefully (A * _ * CacheDecode),\n      (cache_inv_Property P P_inv ->\n       CorrectDecoder monoid predicate predicate eq (format_A ++ format_unused_word 16 ++ format_B)%format decodeA P (format_A ++ format_unused_word 16 ++ format_B)%format) ->\n      (cache_inv_Property P P_invM ->\n          CorrectRefinedDecoder monoid predicate View_Predicate\n                                (fun a n => len_format_A a + 16 + len_format_B a = n * 8)\n                                (format_A ++ format_unused_word 16 ++ format_B)%format\n                                subformat\n                                decode_measure P\n                                format_measure) ->\n      (Prefix_Format _ (format_A ++ format_unused_word 16 ++ format_B) subformat)%format->\n      forall e, CorrectDecoder monoid predicate predicate eq\n                     (format_A ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16 ThenCarryOn format_B)\n                     (fun (bin : _) (env : CacheDecode) =>\n                          `(n, _, _) <- decode_measure bin env;\n                            if weqb (onesComplement (wzero 8 :: protoCode ::\n                                                       to_list srcAddr ++ to_list destAddr ++ to_list (splitLength udpLength)\n                                                       ++(ByteString2ListOfChar (n * 8) bin))%list) (wones 16) then\n                              decodeA bin env\n                            else Error e)\n                     P\n                     (format_A ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16 ThenCarryOn format_B).\nProof.\n  intros.\n  rename H4 into H4'; rename H3 into H4; rename H2 into H3.\n  eapply format_decode_correct_alt.\n  7: {\n  eapply (composeChecksum_format_correct'\n                 A _ monoid _ 16 (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode)).\n       - eapply H.\n       - specialize (H4 (proj2 H)).\n         split.\n         2: eauto.\n         eapply injection_decode_correct with (inj := fun n => mult n 8).\n         4: simpl.\n         eapply H4.\n         + intros.\n           instantiate (1 := fun a n => len_format_A a + 16 + len_format_B a = n).\n           eapply H6.\n         + intros; instantiate (1 := fun v => View_Predicate (Nat.div v 8)).\n           cbv beta.\n           rewrite Nat.div_mul; eauto.\n         + intros; apply unfold_computes; intros.\n           split.\n           2: rewrite unfold_computes in H5; intuition.\n           intros.\n           rewrite unfold_computes in H5; intuition.\n           instantiate (1 := fun v env t => format_measure (Nat.div v 8) env t).\n           cbv beta; rewrite Nat.div_mul; eauto.\n       - simpl; intros.\n         destruct t1; destruct t2; simpl fst in *; simpl snd in *.\n         apply unfold_computes in H7; apply unfold_computes in H6.\n         erewrite len_format_A_OK; eauto.\n         erewrite (len_format_B_OK _ b0); eauto.\n         unfold format_checksum; rewrite length_encode_word', measure_mempty.\n         rewrite <- H2; Lia.lia.\n       - eauto.\n       - eapply Pseudo_Checksum_Valid_bounded; eauto. }\n  all: try unfold flip, pointwise_relation, impl;\n    intuition eauto using EquivFormat_reflexive.\n    instantiate (2 := fun (n : nat) a =>\n                    weq\n       (onesComplement\n          (wzero 8\n           :: (protoCode\n               :: to_list srcAddr ++\n                  to_list destAddr ++ to_list (splitLength udpLength) ++ ByteString2ListOfChar n a)%list))\n       (wones 16)).\n  unfold Compose_Decode.\n  Local Opaque Nat.div.\n  intros ??.\n  destruct (decode_measure t c) as [ [ [? ?] ? ] | ]; simpl; eauto.\n  symmetry.\n  find_if_inside.\n  eapply weqb_true_iff in e0; rewrite e0; eauto.\n  destruct (weqb\n      (add_bytes_into_checksum (wzero 8) protoCode\n         (onesComplement\n            (to_list srcAddr ++\n             to_list destAddr ++ split2 8 8 udpLength :: (split1 8 8 udpLength :: ByteString2ListOfChar (n * 8) t)%list)))\n      WO~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1) eqn: ? ; eauto.\n  eapply weqb_true_iff in Heqb0.\n  congruence.\n  Unshelve.\n  constructor.\nQed.\n\nFixpoint aligned_Pseudo_checksum\n         (srcAddr : ByteBuffer.t 4)\n         (destAddr : ByteBuffer.t 4)\n         (pktlength : word 16)\n         id\n         measure\n         {sz}\n         (v : t Core.char sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       weqb (pseudoHeader_checksum' srcAddr destAddr measure pktlength id v)\n            (wones 16)\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v' idx'\n       | _ => false\n       end\n     end.\n\nLemma Vector_checksum_bound_acc'\n  : forall sz'' sz sz' (sz_lt : le sz' sz'') (v : Vector.t _ sz) b1 b2 acc,\n    Vector_checksum_bound sz' v (add_bytes_into_checksum b1 b2 acc) =\n    add_bytes_into_checksum b1 b2 (Vector_checksum_bound sz' v acc).\nProof.\n  induction sz''; intros.\n  - inversion sz_lt.\n    subst; reflexivity.\n  - inversion sz_lt; subst.\n    + clear sz_lt.\n      destruct sz''; simpl.\n      * destruct v; simpl; eauto.\n        rewrite add_bytes_into_checksum_swap; eauto.\n      * destruct v; simpl; eauto.\n        destruct v; simpl; eauto.\n        rewrite add_bytes_into_checksum_swap; eauto.\n        rewrite !IHsz'' by Lia.lia.\n        rewrite add_bytes_into_checksum_swap; eauto.\n    + eauto.\nQed.\n\nLemma Vector_checksum_bound_acc\n  : forall sz sz' (v : Vector.t _ sz) b1 b2 acc,\n    Vector_checksum_bound sz' v (add_bytes_into_checksum b1 b2 acc) =\n    add_bytes_into_checksum b1 b2 (Vector_checksum_bound sz' v acc).\nProof.\n  intros; eapply Vector_checksum_bound_acc'.\n  reflexivity.\nQed.\n\nLemma dequeue_byte_ByteString2ListOfChar\n  : forall m sz (v : Vector.t _ sz) b,\n    ByteString2ListOfChar ((S m) * 8) (build_aligned_ByteString (b :: v))\n    = cons b (ByteString2ListOfChar (m * 8) (build_aligned_ByteString (v))).\nProof.\n  intros; erewrite <- ByteString2ListOfChar_push_char.\n  f_equal.\n  pose proof (build_aligned_ByteString_append v [b]) as H; simpl in H.\n  rewrite H.\n  reflexivity.\nQed.\n\nLemma ByteString2ListOfChar_overflow\n  : forall n,\n    ByteString2ListOfChar ((S n) * 8) (build_aligned_ByteString [])\n    = cons (wzero 8) (ByteString2ListOfChar (n * 8) (build_aligned_ByteString [])).\nProof.\n  reflexivity.\nQed.\n\nLemma InternetChecksum_To_ByteBuffer_Checksum':\n  forall (sz m : nat) (v : t Core.char sz),\n    checksum (ByteString2ListOfChar (m * 8) (build_aligned_ByteString v)) = ByteBuffer_checksum_bound m v.\nProof.\n  intros.\n  assert ((exists m', m = 2 * m') \\/ (exists m', m = S (2 * m'))).\n  { induction m; eauto.\n    destruct IHm; destruct_ex; subst; eauto.\n    left; exists (S x); Lia.lia.\n  }\n  destruct H as [ [? ?] | [? ?] ]; subst.\n  - rewrite (mult_comm 2).\n    apply InternetChecksum_To_ByteBuffer_Checksum.\n  - revert sz v.\n    induction x.\n    + intros; destruct v.\n      * reflexivity.\n      * rewrite dequeue_byte_ByteString2ListOfChar.\n        reflexivity.\n    + intros; destruct v.\n      * replace (S (2 * S x)) with ((S (S (S (2 * x))))) by Lia.lia.\n        rewrite ByteString2ListOfChar_overflow.\n        rewrite ByteString2ListOfChar_overflow.\n        unfold checksum; fold checksum.\n        rewrite IHx.\n        unfold ByteBuffer_checksum_bound, ByteBuffer_fold_left16.\n        simpl.\n        destruct (2 * x); eauto.\n      * rewrite dequeue_byte_ByteString2ListOfChar.\n        destruct v.\n        replace (2 * S x * 8) with ((S (S (2 * x))) * 8) by Lia.lia.\n        rewrite ByteString2ListOfChar_overflow.\n        unfold checksum; fold checksum.\n        rewrite IHx.\n        rewrite <- !ByteBuffer_checksum_bound_ok.\n        simpl.\n        destruct (2 * x); eauto.\n        replace (2 * S x * 8) with ((S (S (2 * x))) * 8) by Lia.lia.\n        rewrite dequeue_byte_ByteString2ListOfChar.\n        replace\n          (checksum (h :: (h0 :: ByteString2ListOfChar (S (2 * x) * 8) (build_aligned_ByteString v))%list))\n          with\n            (add_bytes_into_checksum\n               h h0\n               (checksum (ByteString2ListOfChar (S (2 * x) * 8) (build_aligned_ByteString v))%list))\n          by reflexivity.\n        rewrite IHx.\n        rewrite <- !ByteBuffer_checksum_bound_ok.\n        replace (2 * S x) with (S (S ( 2 * x))) by Lia.lia.\n        rewrite <- Vector_checksum_bound_acc; reflexivity.\nQed.\n\nLemma aligned_Pseudo_checksum_OK_1\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (pktlength : word 16)\n      id\n      measure\n      {sz}\n  : forall (v : t Core.char sz),\n    weqb\n      (InternetChecksum.add_bytes_into_checksum (wzero 8) id\n                                                (onesComplement(to_list srcAddr ++ to_list destAddr ++ split2 8 8  pktlength :: split1 8 8 pktlength :: (ByteString2ListOfChar (measure * 8) (build_aligned_ByteString v)))%list))\n      WO~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n    = aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v 0.\nProof.\n  simpl; intros.\n  unfold onesComplement.\n  rewrite <- pseudoHeader_checksum'_ok.\n  rewrite checksum_eq_Vector_checksum.\n  unfold pseudoHeader_checksum.\n  rewrite <- ByteBuffer_checksum_bound_ok.\n  unfold ByteBuffer.t in *.\n  simpl.\n    replace srcAddr with\n      (Vector.hd srcAddr :: Vector.hd (Vector.tl srcAddr)\n                 :: Vector.hd (Vector.tl (Vector.tl srcAddr))\n                 :: Vector.hd (Vector.tl (Vector.tl (Vector.tl srcAddr)))\n                 :: (@Vector.nil _))\n    by abstract (pattern srcAddr;\n              repeat (apply caseS'; let t' := fresh in intros ? t'; pattern t'); apply case0;\n              reflexivity).\n  replace destAddr with\n      (Vector.hd destAddr :: Vector.hd (Vector.tl destAddr)\n                 :: Vector.hd (Vector.tl (Vector.tl destAddr))\n                 :: Vector.hd (Vector.tl (Vector.tl (Vector.tl destAddr)))\n                 :: (@Vector.nil _))\n    by abstract (pattern destAddr;\n              repeat (apply caseS'; let t' := fresh in intros ? t'; pattern t'); apply case0;\n              reflexivity).\n  simpl.\n  repeat rewrite Vector_checksum_bound_acc.\n  rewrite <- checksum_eq_Vector_checksum.\n  f_equal.\n  rewrite ByteBuffer_checksum_bound_ok.\n  repeat rewrite (add_bytes_into_checksum_swap _ id); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl srcAddr))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl (Vector.tl (Vector.tl srcAddr))))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl destAddr))); f_equal.\n  repeat rewrite (add_bytes_into_checksum_swap _ (Vector.hd (Vector.tl (Vector.tl (Vector.tl destAddr))))); f_equal.\n  f_equal.\n  apply InternetChecksum_To_ByteBuffer_Checksum'.\nQed.\n\nLemma aligned_Pseudo_checksum_OK_2\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (pktlength : word 16)\n      id\n      measure\n      {sz}\n  : forall (v : ByteBuffer.t (S sz)) (idx : nat),\n    aligned_Pseudo_checksum srcAddr destAddr pktlength id measure v (S idx) =\n    aligned_Pseudo_checksum srcAddr destAddr pktlength id measure (Vector.tl v) idx.\nProof.\n  intros v; pattern sz, v.\n  apply Vector.caseS; reflexivity.\nQed.\n\nFixpoint aligned_IPchecksum\n         m\n         {sz}\n         (v : t Core.char sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       weqb (InternetChecksum.ByteBuffer_checksum_bound m v) (wones 16)\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => aligned_IPchecksum m v' idx'\n       | _ => false\n       end\n     end.\n\nCorollary aligned_IPChecksum_OK_1 :\n  forall m sz (v : ByteBuffer.t sz),\n    IPChecksum_Valid_check (m * 8) (build_aligned_ByteString v)\n    = aligned_IPchecksum m v 0.\nProof.\n  intros.\n  unfold IPChecksum_Valid_check, aligned_IPchecksum.\n  rewrite InternetChecksum_To_ByteBuffer_Checksum'.\n  higher_order_reflexivity.\nQed.\n\nLemma aligned_IPChecksum_OK_2\n      m\n      {sz}\n  : forall (v : ByteBuffer.t (S sz)) (idx : nat),\n    aligned_IPchecksum m v (S idx) =\n    aligned_IPchecksum m (Vector.tl v) idx.\nProof.\n  intros v; pattern sz, v.\n  apply Vector.caseS; reflexivity.\nQed.\n\n#[export]\nHint Extern 4 (weqb _ _ = _) =>\nrewrite aligned_Pseudo_checksum_OK_1; higher_order_reflexivity : core.\n#[export]\nHint Extern 4 => eapply aligned_Pseudo_checksum_OK_2 : core.\n\n#[export]\nHint Extern 4 (IPChecksum_Valid_check _ _ = _ ) =>\nrewrite aligned_IPChecksum_OK_1; higher_order_reflexivity : core.\n#[export]\nHint Extern 4  => eapply aligned_IPChecksum_OK_2 : core.\n\nLtac destruct_unit :=\n  repeat match goal with\n         | v : () |- _ => destruct v\n         end.\n\nLtac solve_seq_padding :=\n  repeat (intros; match goal with\n                  | H : sequence_Encode ?e1 ?e2 _ _ = Ok (?t, _) |- padding ?t = 0 =>\n                    eapply sequence_Encoding_padding_0 in H; eauto\n                  end).\n\nLemma EncodeMEquivAlignedEncodeMForChecksum\n      {S A}\n      (enc1' enc2' enc3' : EncodeM S ByteString)\n      (encA' : A -> EncodeM S ByteString)\n      (f' : ByteString -> A)\n      (enc1 enc2 enc3 : forall sz, AlignedEncodeM sz)\n      (encA : A -> forall sz, AlignedEncodeM sz)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> A)\n      (enc1_OK : EncodeMEquivAlignedEncodeM enc1' enc1)\n      (enc2_OK : EncodeMEquivAlignedEncodeM enc2' enc2)\n      (enc3_OK : EncodeMEquivAlignedEncodeM enc3' enc3)\n      (encA_OK : forall a, EncodeMEquivAlignedEncodeM (encA' a) (encA a))\n      (enc1'_aligned : forall s ce t ce', enc1' s ce = Ok (t, ce') -> padding t = 0)\n      (enc2'_aligned : forall s ce t ce', enc2' s ce = Ok (t, ce') -> padding t = 0)\n      (enc3'_aligned : forall s ce t ce', enc3' s ce = Ok (t, ce') -> padding t = 0)\n      (encA'_aligned : forall a s ce t ce', encA' a s ce = Ok (t, ce') -> padding t = 0)\n      (enc'_sz_eq : forall s a ce t1 ce1 t2 ce2,\n          enc2' s ce = Ok (t1, ce1) ->\n          encA' a s ce = Ok (t2, ce2) ->\n          bin_measure t1 = bin_measure t2)\n      (f_OK : forall (b : ByteString)\n                idx (v1 : Vector.t Core.char idx)\n                m (v2 : Vector.t Core.char m)\n                (v : Vector.t Core.char (idx + ((numBytes b) + m))),\n          ByteString_enqueue_ByteString (build_aligned_ByteString v1)\n                                        (ByteString_enqueue_ByteString b (build_aligned_ByteString v2))\n          = build_aligned_ByteString v ->\n          f' b = f (numBytes b) v idx)\n  : EncodeMEquivAlignedEncodeM\n      (fun s ce =>\n         `(p, _) <- sequence_Encode enc1' (sequence_Encode enc2' enc3') s ce;\n           (fun a => (sequence_Encode enc1' (sequence_Encode (encA' a) enc3'))) (f' p) s ce)\n      (fun sz => EncodeAgain (enc1 sz >> enc2 sz >> enc3 sz)\n                          (fun idx' v idx s =>\n                             (fun a sz => enc1 sz >> encA a sz >> enc3 sz)\n                               (f (idx'-idx) v idx) sz v idx s))%AlignedEncodeM.\nProof.\n  apply EncodeMEquivAlignedEncodeMDep; eauto; intros;\n    repeat (apply Append_EncodeMEquivAlignedEncodeM; eauto);\n    solve_seq_padding.\n  apply sequence_Encoding_inv in H.\n  apply sequence_Encoding_inv in H0. destruct_conjs.\n  apply sequence_Encoding_inv in H9.\n  apply sequence_Encoding_inv in H4. destruct_conjs.\n  subst. rewrite !mappend_measure.\n  simpl in *. destruct_unit.\n  substss. injections. eauto.\nQed.\n\nDefinition f_bit_aligned_free {A} (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> A)\n  : ByteString -> A :=\n  fun bs => f (numBytes bs) (byteString bs) 0.\n\nLemma CorrectAlignedEncoderForChecksum\n      {S}\n      checksum_sz (checksum_valid : nat -> ByteString -> Prop)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A encode_B : forall sz, AlignedEncodeM sz)\n      (encode_C' : forall sz, AlignedEncodeM sz)\n      (encode_C : word checksum_sz -> forall sz, AlignedEncodeM sz)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> word checksum_sz)\n      (f_OK : forall idx n m (t : Vector.t Core.char n)\n                (v1 : Vector.t Core.char idx) (v2 : Vector.t Core.char m),\n         f n t 0 = f n (v1 ++ t ++ v2) idx)\n      (enc2' : EncodeM S ByteString)\n      (enc2_OK : EncodeMEquivAlignedEncodeM enc2' encode_C')\n      (encode_C_OK : forall a, EncodeMEquivAlignedEncodeM\n                            ((fun a _ ce => Ok (format_checksum _ _ _ _ a, ce)) a) (encode_C a))\n      (enc2'_aligned : forall s ce t ce', enc2' s ce = Ok (t, ce') -> padding t = 0)\n      n1\n      (format_B_sz_eq : forall s ce t ce',\n          format_B s ce \u220b (t, ce') -> bin_measure t = n1)\n      (checksum_sz_OK : checksum_sz mod 8 = 0)\n      (checksum_sz_OK' : forall s ce t ce', enc2' s ce = Ok (t, ce') ->\n                                       checksum_sz = bin_measure t)\n      (checksum_OK : forall s ce b' ce',\n          enc2' s ce = Ok (b', ce') ->\n          forall b1 b3 ext,\n            (exists s ce ce', format_B s ce \u220b (b1, ce')) ->\n            (exists s ce ce', format_A s ce \u220b (b3, ce')) ->\n            let a := (f_bit_aligned_free f) (mappend b1 (mappend b' b3)) in\n            let b2 := format_checksum _ _ _ checksum_sz a in\n            checksum_valid\n              (bin_measure (mappend b1 (mappend b2 b3)))\n              (mappend (mappend b1 (mappend b2 b3)) ext))\n      (checksum_OK' : forall s ce,\n          is_error (enc2' s ce) ->\n          forall b1 b2 b3 ext,\n            ~checksum_valid\n              (bin_measure (mappend b1 (mappend b2 b3)))\n              (mappend (mappend b1 (mappend b2 b3)) ext))\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum checksum_valid OfSize checksum_sz ThenCarryOn format_A)\n      (fun sz => EncodeAgain (encode_B sz >> encode_C' sz >> encode_A sz)\n                          (fun idx' v idx s =>\n                             encode_C (f (idx'-idx) v idx) sz v (idx+n1/8) s))%AlignedEncodeM.\nProof.\n  destruct encoder_A_OK as [enc3' [HA1 [HA2 HA3]]].\n  destruct encoder_B_OK as [enc1' [HB1 [HB2 HB3]]].\n  exists (fun s ce =>\n       `(p, _) <- sequence_Encode enc1' (sequence_Encode enc2' enc3') s ce;\n       (fun a => (sequence_Encode enc1' (sequence_Encode\n                                        ((fun a _ ce => Ok (format_checksum _ _ _ _ a, ce)) a)\n                                        enc3'))) ((f_bit_aligned_free f) p) s ce).\n  split; [| split]; intros.\n  - unfold composeChecksum, sequence_Encode. split; intros; simpl in *.\n    + intros [? ?]. intros.\n      computes_to_inv. injections.\n      destruct enc1' eqn:Henc1; [| discriminate]; destruct_conjs; simpl in *.\n      destruct enc2' eqn:Henc2; [| discriminate]; destruct_conjs; simpl in *.\n      destruct enc3' eqn:Henc3; [| discriminate]; destruct_conjs; simpl in *.\n      destruct_unit.\n      rewrite Henc3 in H. simpl in *. injections.\n      repeat computes_to_econstructor; eauto.\n      edestruct HB1. apply H in Henc1. apply Henc1.\n      repeat computes_to_econstructor; eauto. simpl.\n      edestruct HA1. apply H in Henc3. apply Henc3.\n      repeat computes_to_econstructor; eauto.\n      intros. eapply checksum_OK; eauto.\n      repeat eexists. simpl. apply HB1 in Henc1. eauto.\n      repeat eexists. simpl. apply HA1 in Henc3. eauto.\n      simpl. apply eq_ret_compute. repeat f_equal.\n    + intro. unfold Bind2 in H0.\n      computes_to_inv. destruct_conjs. injections. simpl in *. destruct_unit.\n      destruct enc1' eqn:Henc1; destruct_conjs; simpl in *; destruct_unit.\n      destruct enc2' eqn:Henc2; destruct_conjs; simpl in *; destruct_unit.\n      destruct enc3' eqn:Henc3; destruct_conjs; simpl in *; destruct_unit.\n      tauto.\n      edestruct HA1.\n      * eapply H2; eauto. rewrite Henc3; auto.\n      * eapply checksum_OK'; eauto. rewrite Henc2; auto. \n      * edestruct HB1. eapply H2; eauto. rewrite Henc1; auto.\n  - destruct sequence_Encode; [| discriminate]; destruct_conjs; simpl in *.\n    eapply sequence_Encoding_padding_0; try apply H; eauto.\n    intros.\n    eapply sequence_Encoding_padding_0; try apply H0; eauto.\n    intros. simpl in *. injections.\n    unfold format_checksum. rewrite encode_word'_padding. eauto.\n  - eapply EncodeMEquivAlignedEncodeM_morphism; cycle 1.\n    apply EncodeMEquivAlignedEncodeMForChecksum\n      with (encA' := (fun a _ ce => Ok (format_checksum _ _ _ _ a, ce))); eauto.\n    + intros. injections.\n      unfold format_checksum. rewrite encode_word'_padding. eauto.\n    + intros. injections. unfold format_checksum.\n      rewrite length_encode_word'. rewrite measure_mempty.\n      apply checksum_sz_OK' in H. Lia.lia.\n    + unfold f_bit_aligned_free. instantiate (1:=f). intros.\n      assert (padding b = 0) as L1. {\n        apply (f_equal padding) in H. simpl in H.\n        rewrite padding_ByteString_enqueue_aligned_ByteString in H; eauto.\n        rewrite ByteString_enqueue_ByteString_padding_eq in H. simpl padding in H.\n        rewrite (Nat.mod_add _ 0 8) in H; eauto.\n        rewrite Nat.mod_small in H; eauto.\n        destruct b. simpl in *. auto.\n      }\n      assert (b = build_aligned_ByteString (byteString b)) as L2. {\n        revert L1. clear. intros.\n        destruct b. simpl. unfold build_aligned_ByteString. simpl in *.\n        subst. f_equal. eauto using shatter_word_0.\n        apply Core.le_uniqueness_proof.\n      }\n      revert L2 H. revert v.\n      generalize (byteString b). generalize (numBytes b). intros. rewrite L2 in H.\n      rewrite <- !build_aligned_ByteString_append in H.\n      apply build_aligned_ByteString_inj in H. subst.\n      eauto.\n    + intros. unfold EncodeAgain.\n      set (fun sz => encode_C' sz >> encode_A sz)%AlignedEncodeM as enc'.\n      set (fun sz => encode_B sz >> enc' sz)%AlignedEncodeM as enc.\n      match goal with\n      | |- context[HBind ?b _ _ _ _ as _ With _] => replace b with (enc sz) by reflexivity\n      end.\n      destruct enc eqn:?; eauto.\n      destruct_conjs. simpl. unfold AppendAlignedEncodeM.\n\n      edestruct @AlignedEncoder_inv2 as [n2 [n3 [t1 [t23 [v23 ?]]]]]; try apply Heqa.\n      apply Append_EncodeMEquivAlignedEncodeM. 2 : eauto. eauto.\n      apply Append_EncodeMEquivAlignedEncodeM. 2 : eauto. eauto. eauto.\n      solve_seq_padding.\n      destruct_conjs. subst. simpl in *.\n\n      edestruct @AlignedEncoder_append_inv with (enc1:=encode_B)\n        as [nB [nC [nC3 [tB [tC3 [vB [vC3 [?ce ?]]]]]]]].\n      5 : apply H0.\n      3 : apply Append_EncodeMEquivAlignedEncodeM. all : eauto.\n      solve_seq_padding. destruct_conjs.\n      subst. simpl in *. destruct H. simpl in *.\n\n      assert (encode_B (idx + (nB + (nC + nC3))) (t1 ++ vB ++ vC3) idx w c =\n              Ok (t1 ++ vB ++ vC3, idx+nB, ce)). {\n        assert (idx + nB + (nC + nC3) = idx + (nB + (nC + nC3))) as L by Lia.lia.\n        rewrite Vector_append_assoc with (H:=L). destruct L. simpl.\n        epose proof AlignedEncoder_extr as H'. eapply H'; eauto. clear H'.\n        eapply @AlignedEncoder_fixed; eauto.\n        eapply AlignedEncoder_extl; eauto.\n      } rewrite H. simpl.\n\n      assert (nB = n1/8). {\n        erewrite <- format_B_sz_eq; eauto.\n        epose proof AlignedEncoder_inv0 as L. eapply L in H1; eauto. clear L.\n        instantiate (1:=build_aligned_ByteString vB).\n        rewrite length_ByteString_no_padding; eauto.\n        rewrite Nat.mul_comm.\n        rewrite Nat.div_mul by auto.\n        reflexivity.\n        eapply HB1; eauto. eauto using AlignedEncoder_inv0.\n      } destruct H3.\n      destruct_unit. destruct encode_C eqn:?; eauto. destruct_conjs. simpl in *.\n\n      edestruct @AlignedEncoder_append_inv with (enc1:=encode_C')\n        as [nC' [nA [nA3 [tC [tA3 [vC [vA3 [?ce ?]]]]]]]]; try apply H2; eauto.\n      destruct_conjs.\n      subst. simpl in *. destruct H3. simpl in *. rename nC' into nC.\n\n      match goal with\n      | H : encode_C ?a _ _ _ _ _ = _ |- _ =>\n        edestruct @AlignedEncoder_inv with (enc:=(encode_C a))\n          as [nC' [n3' [t1C [tC' [tC3 [vC' ?]]]]]]\n      end; eauto.\n      intros. simpl in *. injections.\n      unfold format_checksum. rewrite encode_word'_padding. eauto.\n      destruct_conjs.\n\n      assert (nC = nC'). {\n        injections.\n        assert (checksum_sz = 8 * nC').\n        eapply (f_equal bin_measure) in H12. simpl in *.\n        unfold format_checksum in H12.\n        rewrite length_encode_word' in H12. rewrite measure_mempty in H12.\n        unfold length_ByteString in H12. simpl in H12. Lia.lia.\n        assert (checksum_sz = 8 * nC).\n        epose proof AlignedEncoder_inv0 as L. eapply L in H4; eauto. clear L.\n        apply checksum_sz_OK' in H4.\n        unfold length_ByteString in H4. simpl in H4. Lia.lia.\n        Lia.lia.\n      } subst nC'.\n\n      assert (n3' = nA + nA3) as L by Lia.lia. subst n3'.\n      assert (encode_A (idx + (nB + (nC + (nA + nA3)))) t n w c =\n              Ok (t, n+nA, c)). {\n        rewrite (Vector_append_assoc _ _ _ H3) in H8.\n        clear Heqa0. destruct H3. simpl in *.\n        subst. apply Vector_append_inj in H8. destruct_conjs.\n        apply Vector_append_inj in H7. destruct_conjs. subst.\n        assert (idx + nB + nC + (nA + nA3) = idx + nB + (nC + (nA + nA3))) as L by Lia.lia.\n        rewrite (Vector_append_assoc _ _ _ L). destruct L. simpl.\n        epose proof AlignedEncoder_extl as L. eapply L; eauto. clear L.\n        destruct_unit.\n        eapply @AlignedEncoder_fixed; eauto.\n      } rewrite H11. simpl. reflexivity.\n      Unshelve.\n      eauto.\nQed.\n\nDefinition encode_word_const\n           {S : Type}\n           {n}\n  : word (n*8) -> forall sz, AlignedEncodeM (S:=S) sz :=\n  fun w sz v idx _ ce => SetCurrentBytes v idx w ce.\n\nDefinition encode_word_16_const {S : Type} := @encode_word_const S 2.\n\nDefinition encode_word_16_0 {S : Type} := @encode_word_16_const S (wzero 16).\n\nLemma format_word_is_encode_word {T}\n      {cache : Cache} {cacheAddNat : CacheAdd cache nat}\n      {monoid : Monoid T} {monoidUnit : QueueMonoidOpt monoid bool}\n      {n} (enc : EncodeM (word n) T)\n  : (forall s env,\n        (forall t env', enc s env = Ok (t, env')\n                   -> refine (format_word s env) (ret (t, env')))\n        /\\ (is_error(enc s env) ->\n           forall benv', ~ computes_to (format_word s env) benv')) ->\n    forall s env, enc s env = Ok (encode_word' _ s mempty, addE env n).\nProof.\n  intros. destruct enc eqn:?; destruct_conjs.\n  - apply H in Heqe.\n    eapply Return_inv in Heqe; eauto. congruence.\n  - exfalso. eapply H; eauto. rewrite Heqe; constructor.\n    computes_to_econstructor; eauto.\nQed.\n\nLemma EncodeMEquivAlignedEncodeM_const\n      {S A} {cache : Cache}\n      (enc' : EncodeM A ByteString)\n      (enc : forall sz, AlignedEncodeM sz)\n      (enc_OK : EncodeMEquivAlignedEncodeM enc' enc)\n  : forall a, EncodeMEquivAlignedEncodeM (S:=S)\n           (fun _ ce => enc' a ce)\n           (fun sz v n _ ce => enc sz v n a ce).\nProof.\n  intros. repeat split; simpl; intros;\n            edestruct enc_OK as [? [? [? ?]]]; eauto.\nQed.\n\nLemma EncodeMEquivAlignedEncodeM_word_const\n      {S}\n      {n}\n  : forall (w : word (n*8)),\n    EncodeMEquivAlignedEncodeM\n      (fun (_ : S) env => Ok (encode_word' _ w mempty, addE env (n*8)))\n      (encode_word_const w).\nProof.\n  intros.\n  destruct CorrectAlignedEncoderForFormatNChar with (sz:=n); eauto. destruct_conjs.\n  eapply EncodeMEquivAlignedEncodeM_const in H1.\n  match goal with\n  | H : EncodeMEquivAlignedEncodeM ?a _ |- EncodeMEquivAlignedEncodeM ?b _ =>\n    replace b with a\n  end. eauto.\n  extensionality s. extensionality ce.\n  eauto using format_word_is_encode_word.\nQed.\n\nDefinition AlignedEncoderForChecksum\n      {S}\n      n1\n      (encode_B encode_A : forall sz, AlignedEncodeM sz)\n      (f : nat -> forall {sz}, ByteBuffer.t sz -> nat -> word 16)\n  := (fun sz => EncodeAgain (encode_B sz >> encode_word_16_0 sz >> encode_A sz)\n                         (fun idx' v idx (s : S) =>\n                            encode_word_16_const (f (idx'-idx) v idx) sz v (idx+n1/8) s))%AlignedEncodeM.\n\nLocal Opaque encode_word'.\nLemma CorrectAlignedEncoderForChecksum'\n      {S}\n      (checksum_valid : nat -> ByteString -> Prop)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (f : nat -> forall {sz}, Vector.t (word 8) sz -> nat -> word 16)\n      (f_OK : forall idx n m (t : Vector.t Core.char n)\n                (v1 : Vector.t Core.char idx) (v2 : Vector.t Core.char m),\n         f n t 0 = f n (v1 ++ t ++ v2) idx)\n      n1\n      (format_B_sz_eq : forall s ce t ce',\n          format_B s ce \u220b (t, ce') -> bin_measure t = n1)\n      (checksum_OK :\n         forall b1 b3 ext,\n            (exists s ce ce', format_B s ce \u220b (b1, ce')) ->\n            (exists s ce ce', format_A s ce \u220b (b3, ce')) ->\n           let a := (f_bit_aligned_free f)\n                      (mappend b1 (mappend (format_checksum _ _ _ _ (wzero 16)) b3)) in\n           let b2 := format_checksum _ _ _ 16 a in\n           checksum_valid\n             (bin_measure (mappend b1 (mappend b2 b3)))\n             (mappend (mappend b1 (mappend b2 b3)) ext))\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum checksum_valid OfSize 16 ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A f).\nProof.\n  unfold AlignedEncoderForChecksum.\n  eapply CorrectAlignedEncoderForChecksum; intros;\n    eauto using (EncodeMEquivAlignedEncodeM_word_const (n:=2));\n    simpl in H; match goal with\n                | H : Ok (?a, _) = Ok (?b, _) |- _ => replace b with a in * by congruence\n                | H : Ok _ = None |- _ => discriminate H\n                end.\n  - apply encode_word'_padding.\n  - rewrite length_encode_word'. reflexivity.\n  - unfold format_checksum in *. eauto.\nQed.\n\nLemma ByteBuffer_checksum_bound_tail\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    InternetChecksum.ByteBuffer_checksum_bound sz (v++v') =\n    InternetChecksum.ByteBuffer_checksum_bound sz v.\nProof.\n  simpl. intros.\n  rewrite <- !InternetChecksum_To_ByteBuffer_Checksum'.\n  f_equal. rewrite build_aligned_ByteString_append.\n  replace (sz * 8) with (bin_measure (build_aligned_ByteString v)).\n  rewrite ByteString2ListOfChar_Over; eauto.\n  simpl. unfold length_ByteString. simpl. Lia.lia.\nQed.\n\nLemma padding_append_0\n      b1 b2\n  : padding b1 = 0 -> padding b2 = 0 -> padding (mappend b1 b2) = 0.\nProof.\n  intros.\n  rewrite padding_ByteString_enqueue_aligned_ByteString; eauto.\nQed.\n\nLemma refine_ret_ret_eq\n      {A} (a b : A)\n  : refine (ret a) (ret b) -> a = b.\nProof.\n  eauto using Return_inv.\nQed.\n\nLemma checksum_app_0\n  : forall l, checksum (wzero 8 :: wzero 8 :: l)%list = checksum l.\nProof.\n  intros. replace (wzero 8 :: (wzero 8 :: l))%list with ([wzero 8; wzero 8] ++ l)%list by reflexivity.\n  rewrite checksum_split; simpl; eauto.\n  exists 1. reflexivity.\nQed.\n\nLemma ByteString2ListOfChar_format_checksum\n      (w : word 16)\n  : let b := format_checksum _ _ _ _ w in\n    ByteString2ListOfChar (bin_measure b) b = [hi8 w; lo8 w]%list.\nProof.\n  simpl.\n  assert (refine (format_word w ()) (ret (build_aligned_ByteString ([hi8 w; lo8 w]), ()))). {\n    etransitivity.\n    2 : {\n      pose proof AlignedFormat2Char.\n      apply H; eauto. higher_order_reflexivity.\n    }\n    autorewrite with monad laws.\n    higher_order_reflexivity.\n  }\n  unfold format_word, format_checksum in *. simpl in *.\n  apply refine_ret_ret_eq in H. injections. rewrite H0.\n  rewrite ByteString2ListOfChar_eq'; eauto.\n  Unshelve.\n  simpl. exact ().\nQed.\n\nLocal Arguments Nat.modulo : simpl never.\nLemma ByteString_mod_16_padding\n  : forall b, bin_measure b mod 16 = 0 -> padding b = 0.\nProof.\n  intros.\n  rewrite padding_eq_mod_8. simpl in *.\n  apply Nat.mod_divides; eauto.\n  apply Nat.mod_divides in H; eauto.\n  destruct H as [x ?]. rewrite H. clear.\n  exists (2*x). Lia.lia.\nQed.\n\nFixpoint calculate_aligned_IPchecksum''\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n         {struct idx}\n  := match idx with\n     | 0 =>\n       InternetChecksum.ByteBuffer_checksum_bound m v\n     | S idx' =>\n       match v with\n       | Vector.cons _ _ v' => calculate_aligned_IPchecksum'' m v' idx'\n       | _ => wzero _\n       end\n     end.\n\nRequire AlignedByteBuffer.\n\nDefinition calculate_aligned_IPchecksum'\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n  := match idx with\n     | 0 =>\n       InternetChecksum.ByteBuffer_checksum_bound m v\n     | S idx' =>\n       InternetChecksum.ByteBuffer_checksum_bound m (ByteBuffer.drop idx v)\n     end.\n\n  (* := match idx with *)\n  (*    | 0 => *)\n  (*      InternetChecksum.ByteBuffer_checksum_bound m v *)\n  (*    | S idx' => *)\n  (*      let (_, v') := (AlignedByteBuffer.bytebuffer_of_bytebuffer_range idx (sz - idx) v) in *)\n  (*      InternetChecksum.ByteBuffer_checksum_bound m v' *)\n  (*    end. *)\n\nLemma calculate_aligned_IPchecksum_eq\n      m\n      {sz}\n      (v : ByteBuffer.t sz) (idx : nat)\n  : calculate_aligned_IPchecksum' m v idx = calculate_aligned_IPchecksum'' m v idx.\nProof.\n  unfold calculate_aligned_IPchecksum'.\n  revert v m. revert sz.\n  induction idx; simpl; intros; try easy.\n  destruct v; simpl;\n    rewrite <- Eqdep_dec.eq_rect_eq_dec; try apply Nat.eq_dec.\n  - destruct m. reflexivity. destruct m; reflexivity.\n  - destruct idx; eauto.\n    assert (n = n - 0) as L by Lia.lia.\n    replace (ByteBuffer.drop 0 v) with (eq_rect _ _ v _ L).\n    destruct L. simpl. reflexivity.\n    simpl.\n    f_equal. apply Eqdep_dec.UIP_dec.\n    apply Nat.eq_dec.\n\n  (* unfold calculate_aligned_IPchecksum'. *)\n  (* revert v. revert sz. revert m. *)\n  (* induction idx; simpl; intros; try easy. *)\n  (* Local Opaque to_list. *)\n  (* destruct v; simpl. *)\n  (* - destruct m. reflexivity. *)\n  (*   unfold ByteBuffer_checksum_bound, ByteBuffer_fold_left16. simpl. destruct m; reflexivity. *)\n  (* - rewrite <- IHidx. destruct idx; simpl. *)\n  (*   + f_equal. *)\n  (*     replace (to_list (h :: v)) with (h :: (to_list v))%list by reflexivity. *)\n  (*     replace (n - 0) with (length (to_list v)). *)\n  (*     rewrite firstn_all. *)\n  (*   + f_equal. *)\nQed.\n\nLemma calculate_aligned_IPchecksum_front\n      m\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_IPchecksum' m (v'++v) idx =\n    calculate_aligned_IPchecksum' m v 0.\nProof.\n  intros.\n  rewrite calculate_aligned_IPchecksum_eq.\n  induction v'; eauto.\nQed.\n\nLemma calculate_aligned_IPchecksum_tail\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_IPchecksum' sz (v++v') 0 =\n    calculate_aligned_IPchecksum' sz v 0.\nProof.\n  intros. simpl.\n  rewrite ByteBuffer_checksum_bound_tail. reflexivity.\nQed.\n\nDefinition calculate_aligned_IPchecksum\n         m\n         {sz}\n         (v : ByteBuffer.t sz) (idx : nat)\n  := wnot (calculate_aligned_IPchecksum' m v idx).\n\nLemma CorrectAlignedEncoderForIPChecksumThenC\n      {S}\n      (format_A format_B : FormatM S ByteString)\n      (encode_A : forall sz, AlignedEncodeM sz)\n      (encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      n1\n      (format_B_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_B s env \u220b (b, env') -> bin_measure b = n1)\n      (format_B_sz_OK : n1 mod 16 = 0)\n      (len_format_A : S -> nat)\n      (format_A_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_A s env \u220b (b, env') -> bin_measure b = len_format_A s)\n      (format_A_sz_OK : forall (s : S), len_format_A s mod 8 = 0)\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum IPChecksum_Valid OfSize 16 ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A calculate_aligned_IPchecksum).\nProof.\n  eapply CorrectAlignedEncoderForChecksum';\n    unfold calculate_aligned_IPchecksum; eauto; intros.\n  - rewrite calculate_aligned_IPchecksum_front.\n    rewrite calculate_aligned_IPchecksum_tail. reflexivity.\n  - destruct_conjs.\n    assert (bin_measure b1 mod 16 = 0) as L1 by (erewrite format_B_sz_OK'; eauto).\n    assert (padding b3 = 0) as L2 by (rewrite padding_eq_mod_8; erewrite format_A_sz_OK'; eauto).\n    unfold f_bit_aligned_free, IPChecksum_Valid, onesComplement. simpl in *.\n    rewrite <- InternetChecksum_To_ByteBuffer_Checksum'.\n    rewrite ByteString2ListOfChar_Over.\n    rewrite !build_aligned_ByteString_byteString_idem.\n    match goal with\n    | |- context [ByteString2ListOfChar (numBytes ?a * 8) ?a] =>\n      replace (numBytes a * 8) with (bin_measure a)\n    end.\n    2 : rewrite length_ByteString_no_padding; try Lia.lia.\n    rewrite !ByteString2ListOfChar_append.\n    rewrite !ByteString2ListOfChar_format_checksum.\n\n    assert (forall n, n mod 16 = 0 ->\n                 forall b, exists x, |ByteString2ListOfChar n b| = 2 * x) as L. {\n      clear. intros.\n      apply Nat.mod_divides in H; eauto. destruct H as [x ?].\n      replace (16 * x) with (8 * (2*x)) in * by Lia.lia.\n      subst.\n      rewrite ByteString2ListOfChar_len. eauto.\n    }\n    destruct L with (n:=bin_measure b1) (b:=b1) as [x1 ?]; eauto.\n    clear L.\n    set (ByteString2ListOfChar (bin_measure b1) b1) as l1 in *.\n    set (ByteString2ListOfChar (bin_measure b3) b3) as l3 in *.\n\n    unfold hi8, lo8.\n    rewrite split1_wzero, split2_wzero.\n    match goal with\n    | |- context [wnot (checksum ?a)] =>\n      assert (checksum a = checksum (l1 ++ l3))%list as L\n    end. {\n      rewrite !checksum_split; eauto. exists 1. reflexivity.\n    } rewrite L. clear L.\n    rewrite checksum_split; eauto.\n    rewrite checksum_split; eauto.\n    match goal with\n    | |- context [?a ^1+ (?b ^1+ ?c)] =>\n        assert (a ^1+ (b ^1+ c) = b ^1+ a ^1+ c) as L\n    end. {\n      rewrite <- !OneC_plus_assoc.\n      rewrite OneC_plus_comm.\n      rewrite <- !OneC_plus_assoc.\n      f_equal.\n      rewrite OneC_plus_comm.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite <- !checksum_split; eauto.\n    apply checksum_correct.\n    simpl. exists (1+x1). unfold Core.char in *. rewrite H7. Lia.lia.\n    simpl. exists 1. Lia.lia.\n    simpl. exists 1. Lia.lia.\n    all : destruct_conjs; simpl.\n    all : repeat match goal with\n                 | |- padding (ByteString_enqueue_ByteString _ _) = _ =>\n                   rewrite !padding_ByteString_enqueue_aligned_ByteString\n                 | |- padding (format_checksum _ _ _ _ _) = _ =>\n                   unfold format_checksum; rewrite encode_word'_padding\n                 | _ => eauto using ByteString_mod_16_padding\n                 end.\nQed.\n\n\nDefinition calculate_aligned_Pseudochecksum'\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) (idx : nat) :=\n  ByteBuffer_checksum srcAddr ^1+\n  ByteBuffer_checksum destAddr ^1+\n  zext protoCode 8 ^1+\n  udpLength ^1+\n  calculate_aligned_IPchecksum' m v idx.\n\nDefinition calculate_aligned_Pseudochecksum''\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) :=\n  calculate_aligned_IPchecksum' (12 + m)\n                                ([wzero 8; protoCode] ++ srcAddr ++ destAddr ++\n                                         (splitLength udpLength) ++ v) 0.\n\nLemma calculate_aligned_Pseudochecksum_equiv :\n  forall (srcAddr : ByteBuffer.t 4)\n    (destAddr : ByteBuffer.t 4)\n    (udpLength : word 16)\n    (protoCode : word 8)\n    (m : nat)\n    {sz} (v : ByteBuffer.t sz),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v 0 =\n    calculate_aligned_Pseudochecksum'' srcAddr destAddr udpLength protoCode m v.\nProof.\n  unfold calculate_aligned_Pseudochecksum', calculate_aligned_Pseudochecksum''.\n  intros.\n  repeat explode_vector.\n  Opaque split1.\n  Opaque split2.\n  simpl in *.\n  unfold ByteBuffer_checksum, InternetChecksum.ByteBuffer_checksum_bound, add_w16_into_checksum,\n  add_bytes_into_checksum, ByteBuffer_fold_left16, ByteBuffer_fold_left_pair.\n  fold @ByteBuffer_fold_left_pair.\n  setoid_rewrite Buffer_fold_left16_acc_oneC_plus.\n  rewrite combine_split.\n  rewrite !OneC_plus_wzero_r, !OneC_plus_wzero_l, OneC_plus_comm.\n  repeat (f_equal; [ ]).\n  rewrite <- !OneC_plus_assoc.\n  match goal with\n  | |- _ = ?a ^1+ ?b =>\n    assert (a ^1+ b = b ^1+ a) by (apply OneC_plus_comm)\n  end.\n  simpl in *. rewrite H.\n  rewrite <- !OneC_plus_assoc.\n  reflexivity.\nQed.\n\nLemma calculate_aligned_Pseudochecksum_front\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      m\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m (v'++v) idx =\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v 0.\nProof.\n  intros. unfold calculate_aligned_Pseudochecksum'.\n  f_equal. apply calculate_aligned_IPchecksum_front.\nQed.\n\nLemma calculate_aligned_Pseudochecksum_tail\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      {sz}\n  : forall (v : ByteBuffer.t sz) (idx : nat) (v' : ByteBuffer.t idx),\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode sz (v++v') 0 =\n    calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode sz v 0.\nProof.\n  intros. unfold calculate_aligned_Pseudochecksum'.\n  f_equal. apply calculate_aligned_IPchecksum_tail.\nQed.\n\nDefinition calculate_aligned_Pseudochecksum\n           (srcAddr : ByteBuffer.t 4)\n           (destAddr : ByteBuffer.t 4)\n           (udpLength : word 16)\n           (protoCode : word 8)\n           (m : nat)\n           {sz} (v : ByteBuffer.t sz) (idx : nat) :=\n  wnot (calculate_aligned_Pseudochecksum' srcAddr destAddr udpLength protoCode m v idx).\n\nLemma CorrectAlignedEncoderForPseudoChecksumThenC\n      {S}\n      (srcAddr : ByteBuffer.t 4)\n      (destAddr : ByteBuffer.t 4)\n      (udpLength : word 16)\n      (protoCode : word 8)\n      (format_A format_B : FormatM S ByteString)\n      (encode_A : forall sz, AlignedEncodeM sz)\n      (encode_B : forall sz, AlignedEncodeM sz)\n      (encoder_B_OK : CorrectAlignedEncoder format_B encode_B)\n      (encoder_A_OK : CorrectAlignedEncoder format_A encode_A)\n      n1\n      (format_B_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_B s env \u220b (b, env') -> bin_measure b = n1)\n      (format_B_sz_OK : n1 mod 16 = 0)\n      (len_format_A : S -> nat)\n      (format_A_sz_OK' : forall (s : S) (b : ByteString) (env env' : CacheFormat),\n          format_A s env \u220b (b, env') -> bin_measure b = len_format_A s)\n      (format_A_sz_OK : forall (s : S), len_format_A s mod 8 = 0)\n  : CorrectAlignedEncoder\n      (format_B ThenChecksum (Pseudo_Checksum_Valid srcAddr destAddr udpLength protoCode) OfSize 16\n                ThenCarryOn format_A)\n      (AlignedEncoderForChecksum n1 encode_B encode_A\n                                 (calculate_aligned_Pseudochecksum srcAddr destAddr udpLength protoCode)).\nProof.\n  apply CorrectAlignedEncoderForChecksum';\n    unfold calculate_aligned_Pseudochecksum; eauto with nocore; intros.\n  - rewrite calculate_aligned_Pseudochecksum_front.\n    rewrite calculate_aligned_Pseudochecksum_tail. reflexivity.\n  - destruct_conjs.\n    assert (bin_measure b1 mod 16 = 0) as L1 by (erewrite format_B_sz_OK'; eauto).\n    assert (padding b3 = 0) as L2 by (rewrite padding_eq_mod_8; erewrite format_A_sz_OK'; eauto).\n    unfold f_bit_aligned_free, Pseudo_Checksum_Valid, onesComplement.\n    rewrite calculate_aligned_Pseudochecksum_equiv.\n    unfold calculate_aligned_Pseudochecksum''.\n    unfold calculate_aligned_IPchecksum'.\n    rewrite <- InternetChecksum_To_ByteBuffer_Checksum'.\n    rewrite ByteString2ListOfChar_Over.\n    rewrite !build_aligned_ByteString_append.\n    rewrite !build_aligned_ByteString_byteString_idem.\n    rewrite Nat.mul_add_distr_r.\n    match goal with\n    | |- context [numBytes ?a * 8] =>\n      replace (numBytes a * 8) with (bin_measure a)\n    end.\n    2 : rewrite length_ByteString_no_padding; try Lia.lia.\n\n    match goal with\n    | |- context [wnot (checksum (ByteString2ListOfChar ?a ?b))] =>\n      assert (a = bin_measure b) as L\n    end. {\n      rewrite !@mappend_measure.\n      rewrite !Nat.add_assoc.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite !ByteString2ListOfChar_append.\n    rewrite !ByteString2ListOfChar_format_checksum.\n\n    assert (forall n, n mod 16 = 0 ->\n                 forall b, exists x, |ByteString2ListOfChar n b| = 2 * x) as L. {\n      clear. intros.\n      apply Nat.mod_divides in H; eauto. destruct H as [x ?].\n      replace (16 * x) with (8 * (2*x)) in * by Lia.lia.\n      subst.\n      rewrite ByteString2ListOfChar_len. eauto.\n    }\n    destruct L with (n:=bin_measure b1) (b:=b1) as [x1 ?]; eauto.\n    clear L.\n    set (ByteString2ListOfChar (bin_measure b1) b1) as l1 in *.\n    set (ByteString2ListOfChar (bin_measure b3) b3) as l3 in *.\n\n    rewrite !ByteString2ListOfChar_eq'.\n    simpl Core.byteString. unfold ByteBuffer.to_list.\n\n    unfold hi8, lo8.\n    rewrite split1_wzero, split2_wzero.\n    match goal with\n    | |- checksum (?a :: ?b :: ?l)%list = _ =>\n      replace (a :: b :: l)%list with (to_list (a :: [b])%vector ++ l)%list by reflexivity\n    end.\n    rewrite !app_assoc.\n    unfold Core.char in *.\n    match goal with\n    | |- context [(?a ++ l1)%list] => set (a ++ l1)%list as l1'\n    end.\n    assert (exists x, | l1' | = 2 * x) as L'. {\n      subst l1'. simpl.\n      rewrite !app_length. rewrite <- !ByteBuffer.to_list_length. rewrite H7.\n      exists (6+x1). Lia.lia.\n    } destruct L' as [x L'].\n    rewrite <- !app_assoc.\n    match goal with\n    | |- context [wnot (checksum ?a)] =>\n      assert (checksum a = checksum (l1' ++ l3))%list as L\n    end. {\n      rewrite !checksum_split; eauto.\n      exists 1. reflexivity.\n    } rewrite L. clear L.\n    rewrite checksum_split; eauto.\n    rewrite checksum_split; eauto.\n    match goal with\n    | |- context [?a ^1+ (?b ^1+ ?c)] =>\n        assert (a ^1+ (b ^1+ c) = b ^1+ a ^1+ c) as L\n    end. {\n      rewrite <- !OneC_plus_assoc.\n      rewrite OneC_plus_comm.\n      rewrite <- !OneC_plus_assoc.\n      f_equal.\n      rewrite OneC_plus_comm.\n      reflexivity.\n    } rewrite L. clear L.\n    rewrite <- !checksum_split; eauto.\n    apply checksum_correct.\n    rewrite !app_length. rewrite L'. simpl. exists (1+x). Lia.lia.\n    simpl. exists 1. Lia.lia.\n    simpl. exists 1. Lia.lia.\n\n    all : destruct_conjs; simpl.\n    all : repeat match goal with\n                 | |- padding (ByteString_enqueue_ByteString _ _) = _ =>\n                   rewrite !padding_ByteString_enqueue_aligned_ByteString\n                 | |- padding (format_checksum _ _ _ _ _) = _ =>\n                   unfold format_checksum; rewrite encode_word'_padding\n                 | _ => eauto using ByteString_mod_16_padding\n                 end.\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/BinLib/AlignedIPChecksum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.331119752830196, "lm_q1q2_score": 0.17589391149775627}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.sepcomp.mem_lemmas.\n\n(** * Interaction Semantics *)\n\n(** NOTE: In the code, we call interaction semantics [CoreSemantics]. *)\n\n(** The [G] type parameter is the type of global environments, the type\n   [C] is the type of core states, and the type [E] is the type of\n   extension requests. *)\n\n(** [at_external] gives a way to determine when the sequential\n   execution is blocked on an extension call, and to extract the\n   data necessary to execute the call. *)\n\n(** [after_external] give a way to inject the extension call results\n   back into the sequential state so execution can continue. *)\n\n(** [initial_core] produces the core state corresponding to an entry\n   point of a module.  The arguments are the genv, a pointer to the\n   function to run, and the arguments for that function. *)\n\n(** [halted] indicates when a program state has reached a halted state,\n   and what it's exit code/return value is when it has reached such\n   a state. *)\n\n(** [corestep] is the fundamental small-step relation for the\n   sequential semantics. *)\n\n(** The remaining properties give basic sanity properties which constrain\n   the behavior of programs. *)\n(** -1 a state cannot be both blocked on an extension call and also step, *)\n(** -2 a state cannot both step and be halted, and *)\n(** -3 a state cannot both be halted and blocked on an external call. *)\nRecord CoreSemantics {C M : Type} : Type :=\n  { initial_core : nat -> M -> C -> M -> val -> list val -> Prop\n  ; at_external : C -> M -> option (external_function * list val)\n  ; after_external : option val -> C -> M -> option C\n  ; halted : C -> int -> Prop\n  ; corestep : C -> M -> C -> M -> Prop\n  ; corestep_not_halted:\n      forall m q m' q' i, corestep q m q' m' -> ~ halted q i\n  ; corestep_not_at_external:\n      forall m q m' q', corestep q m q' m' -> at_external q m = None }.\n\nArguments CoreSemantics : clear implicits.\n\nInductive mem_step m m' : Prop :=\n    mem_step_storebytes: forall b ofs bytes,\n       Mem.storebytes m b ofs bytes = Some m' -> mem_step m m'\n  | mem_step_alloc: forall lo hi b',\n       Mem.alloc m lo hi = (m',b') -> mem_step m m'\n  | mem_step_freelist: forall l,\n       Mem.free_list m l = Some m' -> mem_step m m'\n  (*Some non-observable external calls are not a single alloc/free/store-step*)\n  | mem_step_trans: forall m'',\n       mem_step m m'' -> mem_step m'' m' -> mem_step m m'.\n\nLocal Notation \"a # b\" := (PMap.get b a) (at level 1).\nRecord perm_lesseq (m m': mem):= {\n  perm_le_Cur:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Cur) ((Mem.mem_access m)#b ofs Cur)\n; perm_le_Max:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Max) ((Mem.mem_access m)#b ofs Max)\n; perm_le_cont:\n    forall b ofs, Mem.perm m b ofs Cur Readable ->\n     ZMap.get ofs (Mem.mem_contents m') !! b= ZMap.get ofs (Mem.mem_contents m) !! b\n; perm_le_nb: Mem.nextblock m = Mem.nextblock m'\n}.\n\n\n(* Memory semantics are CoreSemantics that are specialized to CompCert memories\n   and evolve memory according to mem_step. Previous notion CoopCoreSem is deprecated,\n   but for now retained in file CoopCoreSem.v *)\nRecord MemSem {C} :=\n  { csem :> @CoreSemantics C mem\n\n  ; corestep_mem : forall c m c' m' (CS: corestep csem c m c' m'), mem_step m m'\n  (*later, we'll want to add the following constraint\n  ; corestep_incr_perm: forall g c m c' m' (CS: corestep csem g c m c' m')  m1 (PLE: perm_lesseq m m1),\n         exists m1', corestep csem g c m1 c' m1' /\\ perm_lesseq m' m1'*)\n  }.\n\nArguments MemSem : clear implicits.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.17589391080854105}}
{"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 req.\n\nSection stack_macros.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          `{MP: MachineParameters}.\n\n\n  (* -------------------------------------- CHECKRA --------------------------------------- *)\n  (* the following macro checks that the input is a capability with at least RO permission  *)\n\n  Definition checkra_instrs_pre r off_to_blockU :=\n    [move_r r_t3 PC;\n    lea_z r_t3 (off_to_blockU);\n    getp r_t1 r;\n    sub_r_z r_t2 r_t1 (encodePerm RO);\n    move_r r_t4 PC;\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* if the permission is not RO, we must continue and skip the following jmp *)\n    jmp r_t3;\n    sub_r_z r_t2 r_t1 (encodePerm RX);\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* if the permission is not RX, we must continue and skip the following jmp *)\n    jmp r_t3;\n    sub_r_z r_t2 r_t1 (encodePerm RW);\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* if the permission is not RW, we must continue and skip the following jmp *)\n    jmp r_t3;\n    sub_r_z r_t2 r_t1 (encodePerm RWL);\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* if the permission is not RWL, we must continue and skip the following jmp *)\n    jmp r_t3;\n    sub_r_z r_t2 r_t1 (encodePerm RWX);\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* if the permission is not RWX, we must continue and skip the following jmp *)\n    jmp r_t3;\n    sub_r_z r_t2 r_t1 (encodePerm RWLX);\n    lea_z r_t4 4;\n    jnz r_t4 r_t2; (* finally if the permission is not RWLX, we must continue and skip the following jmp, and fail *)\n    jmp r_t3;\n    fail_end].\n\n  Local Definition off_to_blockU := length (checkra_instrs_pre r_t0 0).\n\n  Definition checkra_instrs r := checkra_instrs_pre r off_to_blockU ++ [move_z r_t1 0; move_z r_t2 0; move_z r_t3 0; move_z r_t4 0].\n\n  Definition checkra_pre r a : iProp \u03a3 :=\n    ([\u2217 list] a_i;w_i \u2208 a;(checkra_instrs_pre r off_to_blockU), a_i \u21a6\u2090 w_i)%I.\n  Definition checkra r a : iProp \u03a3 :=\n    ([\u2217 list] a_i;w_i \u2208 a;(checkra_instrs r), a_i \u21a6\u2090 w_i)%I.\n\n  Lemma branchperm_pre_spec r a w pc_p pc_g pc_b pc_e a_first a_last \u03c6 w1 w2 w3 w4 :\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      \u25b7 checkra_pre r a\n    \u2217 \u25b7 PC \u21a6\u1d63 inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    \u2217 \u25b7 r \u21a6\u1d63 w\n    \u2217 \u25b7 r_t1 \u21a6\u1d63 w1\n    \u2217 \u25b7 r_t2 \u21a6\u1d63 w2\n    \u2217 \u25b7 r_t3 \u21a6\u1d63 w3\n    \u2217 \u25b7 r_t4 \u21a6\u1d63 w4\n    \u2217 \u25b7 (if is_cap w then\n           \u2203 l p b e a', \u231cw = inr (p,l,b,e,a')\u231d \u2227\n           if readAllowed p then\n             (PC \u21a6\u1d63 inr (pc_p,pc_g,pc_b,pc_e,a_last) \u2217 checkra_pre r a \u2217\n                 r \u21a6\u1d63 inr (p,l,b,e,a') \u2217 (\u2203 w, r_t1 \u21a6\u1d63 w) \u2217 (\u2203 w, r_t2 \u21a6\u1d63 w) \u2217 (\u2203 w, r_t3 \u21a6\u1d63 w) \u2217 (\u2203 w, r_t4 \u21a6\u1d63 w)\n                 -\u2217 WP Seq (Instr Executable) {{ \u03c6 }})\n           else\n             \u03c6 FailedV\n        else \u03c6 FailedV)\n    \u22a2\n      WP Seq (Instr Executable) {{ \u03c6 }}.\n  Proof.\n    iIntros (Hvpc Hcont) \"(>Hprog & >HPC & >Hr & >Hr_t1 & >Hr_t2 & >Hr_t3 & >Hr_t4 & Hcont)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength. simpl in *.\n    prep_addr_list_full a Hcont.\n    assert (pc_p \u2260 E) as Hnp.\n    { eapply pc_range_not_E;eauto. }\n    pose proof (pc_range_perm _ _ _ _ _ _ _ Hvpc Hcont) as Hperms.\n    iAssert (\u231cr \u2260 PC\u231d)%I as %Hne.\n    { destruct (decide (r = PC)); auto; subst. iDestruct (regname_dupl_false with \"HPC Hr\") as %Hcontr. done. }\n    (* move_r r_t3 PC *)\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg_fromPC with \"[$Hi $HPC $Hr_t3]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n    iEpilogue \"(HPC & Hprog_done & Hr_t3)\".\n    (* lea r_t3 off1 *)\n    assert (a_first + off_to_blockU = Some a_last)%a as Hoff.\n    { apply contiguous_between_length in Hcont. auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t3]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hoff|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* getp r_t1 r *)\n    iPrologue \"Hprog\".\n    destruct w.\n    { (* if w is an integer, the getL will fail *)\n      iApply (wp_Get_fail with \"[$HPC $Hi $Hr_t1 $Hr]\");\n        [apply decode_encode_instrW_inv|auto|iCorrectPC a_first a_last|..].\n      iEpilogue \"_ /=\".\n      iApply wp_value. done. }\n    destruct c,p,p,p.\n    iApply (wp_Get_success with \"[$HPC $Hi $Hr $Hr_t1]\");\n      [apply decode_encode_instrW_inv|auto|iCorrectPC a_first a_last|iContiguous_next_a Hcont|auto..].\n    iEpilogue \"(HPC & Hi & Hr & Hr_t1)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iSimpl in \"Hr_t1\".\n    (* sub r_t2 r_t1 URW *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t2 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t4 PC *)\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg_fromPC with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a3 + 4 = Some a7)%a as Hlea.\n    { apply contiguous_between_incr_addr_middle with (i:=4) (j:=4) (ai:=a3) (aj:=a7) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hlea|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RO = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RO);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we keep checking *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* sub r_t2 r_t1 URWL *)\n    rewrite updatePcPerm_cap_non_E//.\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a7 + 4 = Some a11)%a as Hlea'.\n    { apply contiguous_between_incr_addr_middle with (i:=8) (j:=4) (ai:=a7) (aj:=a11) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hlea'|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RX = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RX);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we keep checking *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    rewrite updatePcPerm_cap_non_E//.\n    (* sub r_t2 r_t1 URWL *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a11 + 4 = Some a15)%a as Hlea''.\n    { apply contiguous_between_incr_addr_middle with (i:=12) (j:=4) (ai:=a11) (aj:=a15) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hlea''|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RW = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RW);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we keep checking *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    rewrite updatePcPerm_cap_non_E//.\n    (* sub r_t2 r_t1 URWL *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a15 + 4 = Some a19)%a as Hlea'''.\n    { apply contiguous_between_incr_addr_middle with (i:=16) (j:=4) (ai:=a15) (aj:=a19) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hlea'''|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RWL = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RWL);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we keep checking *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    rewrite updatePcPerm_cap_non_E//.\n    (* sub r_t2 r_t1 URWL *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a19 + 4 = Some a23)%a as Hlea''''.\n    { apply contiguous_between_incr_addr_middle with (i:=20) (j:=4) (ai:=a19) (aj:=a23) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hlea''''|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RWX = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RWX);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we keep checking *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    rewrite updatePcPerm_cap_non_E//.\n    (* sub r_t2 r_t1 URWL *)\n    iPrologue \"Hprog\".\n    iApply (wp_add_sub_lt_success_r_z with \"[$HPC $Hi $Hr_t1 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|eauto|iContiguous_next_a Hcont|iCorrectPC a_first a_last|..].\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t4 4 *)\n    assert (a23 + 4 = Some a27)%a as Hleaend.\n    { apply contiguous_between_incr_addr_middle with (i:=24) (j:=4) (ai:=a23) (aj:=a27) in Hcont;auto. }\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$Hi $HPC $Hr_t4]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|apply Hleaend|auto..].\n    { destruct Hperms as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t4)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* jnz r_t4 r_t2 *)\n    iPrologue \"Hprog\". iSimpl in \"Hr_t2\".\n    destruct (decide (encodePerm p - encodePerm RWLX = 0)%Z).\n    { (* if the permission is URW we are done and will jump to the last block *)\n      rewrite e.\n      iApply (wp_jnz_success_next with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next_a Hcont|..].\n      iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* jmp r_t3 *)\n      iPrologue \"Hprog\".\n      iApply (wp_jmp_success with \"[$Hi $Hr_t3 $HPC]\");\n        [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|auto|..].\n      iEpilogue \"(HPC & Hi & Hr_t3)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n      (* H\u03c6 *)\n      assert (p = RWLX);[apply encodePerm_inj;lia|subst p]. iSimpl in \"Hcont\".\n      iDestruct \"Hcont\" as (l0 p b e0 a' Heq) \"H\u03c6\". simplify_eq. iSimpl in \"H\u03c6\".\n      iApply \"H\u03c6\". rewrite updatePcPerm_cap_non_E//. iFrame \"HPC Hr\".\n      iSplitL \"Hprog Hprog_done\".\n      { iFrame. iDestruct \"Hprog_done\" as \"($&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$&$)\". }\n      iSplitL \"Hr_t1\";[eauto|]. iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t3\";eauto.\n    }\n    (* otherwise we go to the first block *)\n    iApply (wp_jnz_success_jmp with \"[$Hi $HPC $Hr_t4 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|intros;congruence|..].\n    iEpilogue \"(HPC & Hi & Hr_t4 & Hr_t2)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    iDestruct \"Hprog\" as \"[Hi Hprog]\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    rewrite updatePcPerm_cap_non_E//.\n    (* fail_end *)\n    iPrologue \"Hprog\".\n    iApply (wp_fail with \"[$HPC $Hi]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|].\n    iEpilogue \"(HPC & Hi)\". iApply wp_value.\n    (* H\u03c6 *)\n    iSimpl in \"Hcont\".\n    iDestruct \"Hcont\" as (l0 p0 b e a' Heq) \"Hcont\".\n    simplify_eq.\n    assert (readAllowed p0 = false) as ->.\n    { destruct p0;auto;exfalso;[apply n|apply n1|apply n2|apply n0|apply n3|apply n4]; clear;lia. }\n    iApply \"Hcont\".\n  Qed.\n\n\n  Lemma checkra_spec r a w pc_p pc_g pc_b pc_e a_first a_last \u03c6 w1 w2 w3 w4 :\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      \u25b7 checkra r a\n    \u2217 \u25b7 PC \u21a6\u1d63 inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    \u2217 \u25b7 r \u21a6\u1d63 w\n    \u2217 \u25b7 r_t1 \u21a6\u1d63 w1\n    \u2217 \u25b7 r_t2 \u21a6\u1d63 w2\n    \u2217 \u25b7 r_t3 \u21a6\u1d63 w3\n    \u2217 \u25b7 r_t4 \u21a6\u1d63 w4\n    \u2217 \u25b7 (if is_cap w then\n           \u2203 l p b e a', \u231cw = inr (p,l,b,e,a')\u231d \u2227\n           if readAllowed p then\n             (PC \u21a6\u1d63 inr (pc_p,pc_g,pc_b,pc_e,a_last) \u2217 checkra r a \u2217\n                 r \u21a6\u1d63 inr (p,l,b,e,a') \u2217 r_t1 \u21a6\u1d63 inl 0%Z \u2217 r_t2 \u21a6\u1d63 inl 0%Z \u2217 r_t3 \u21a6\u1d63 inl 0%Z \u2217 r_t4 \u21a6\u1d63 inl 0%Z\n                 -\u2217 WP Seq (Instr Executable) {{ \u03c6 }})\n           else\n             \u03c6 FailedV\n        else \u03c6 FailedV)\n    \u22a2\n      WP Seq (Instr Executable) {{ \u03c6 }}.\n  Proof.\n    iIntros (Hvpc Hcont) \"(>Hprog & >HPC & >Hr & >Hr_t1 & >Hr_t2 & >Hr_t3 & >Hr_t4 & Hcont)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength. simpl in *.\n    (* check block *)\n    iAssert (\u231cr \u2260 PC\u231d)%I as %Hne.\n    { destruct (decide (r = PC)); auto; subst. iDestruct (regname_dupl_false with \"HPC Hr\") as %Hcontr. done. }\n    iPrologue_multi \"Hprog\" Hcont Hvpc link.\n    iRename \"Hcode\" into \"Hcode_first\".\n    iApply (branchperm_pre_spec with \"[- $HPC $Hcode_first $Hr $Hr_t1 $Hr_t2 $Hr_t3 $Hr_t4]\"); [apply Hvpc_code|apply Hcont_code|].\n    iNext. destruct (is_cap w) eqn:Hcap;[|simpl;iFrame].\n    destruct w;inversion Hcap. destruct c,p,p,p.\n    destruct (readAllowed p) eqn:Hra.\n    - iDestruct \"Hcont\" as (l' p' b e a' Heq) \"Hcont\". simplify_eq. rewrite Hra.\n      iExists _,_,_,_,_. iSplit;eauto. rewrite Hra. iIntros \"(HPC & Hcheckra & Hr & Hr_t1 & Hr_t2 & Hr_t3 & Hr_t4)\".\n      iDestruct \"Hr_t1\" as (w1') \"Hr_t1\".\n      iDestruct \"Hr_t2\" as (w2') \"Hr_t2\".\n      iDestruct \"Hr_t3\" as (w3') \"Hr_t3\".\n      iDestruct \"Hr_t4\" as (w4') \"Hr_t4\".\n      prep_addr_list_full l_rest Hcont.\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 link a_last|iContiguous_next_a Hcont|].\n      iEpilogue \"(HPC & Hi1 & Hr_t1)\".\n      (* move r_t2 0 *)\n      iPrologue \"Hprog\".\n      iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t2]\");\n        [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next_a Hcont|].\n      iEpilogue \"(HPC & Hi2 & Hr_t2)\".\n      (* move r_t3 0 *)\n      iPrologue \"Hprog\".\n      iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t3]\");\n        [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next_a Hcont|].\n      iEpilogue \"(HPC & Hi3 & Hr_t3)\".\n      (* move r_t4 0 *)\n      iPrologue \"Hprog\".\n      iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t4]\");\n        [apply decode_encode_instrW_inv|iCorrectPC link a_last|..].\n      { eapply contiguous_between_last;eauto. }\n      iEpilogue \"(HPC & Hi4 & Hr_t4)\".\n      (* Hcont *)\n      iApply \"Hcont\".\n      iFrame.\n    - iDestruct \"Hcont\" as (l' p' b e a' Heq) \"Hcont\". simplify_eq. rewrite Hra.\n      iExists _,_,_,_,_. iSplit;eauto. rewrite Hra. iFrame.\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/checkra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.17589390939999788}}
{"text": "Require Import Bool Vector List String Peano_dec Lia.\nRequire Import Common FMap HVector IndexSupport Syntax Semantics.\nRequire Import Topology RqRsTopo.\nRequire Import RqRsLang. Import RqRsNotations.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template Ex.Msi.\nImport RuleTemplateNotations.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\n(** Design choices:\n * - Hierarchical (for an arbitrary tree topology)\n * - MSI\n * - Directory (not snooping)\n * - Invalidate (not update)\n * - Write-back (not write-through)\n * - Non-inclusive\n *)\n\nSection System.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo := fst (tree2Topo tr 0).\n  Let cifc := snd (tree2Topo tr 0).\n\n  Instance ImplOStateIfc: OStateIfc :=\n    {| ost_ty := [nat:Type; bool:Type; MSI:Type; DirT:Type]%vector |}.\n\n  Definition implOStateInit: OState :=\n    (0, (false, (msiNP, (dirInit, tt)))).\n\n  Definition implOStateInitRoot: OState :=\n    (0, (true, (msiM, (dirInit, tt)))).\n\n  Definition implOStatesInit: OStates :=\n    (fold_right (fun i m => m +[i <- implOStateInit]) []\n                (tl cifc.(c_li_indices) ++ cifc.(c_l1_indices)))\n    +[rootOf topo <- implOStateInitRoot].\n\n  Lemma implOStatesInit_value_non_root:\n    forall oidx,\n      In oidx (tl (c_li_indices cifc) ++ c_l1_indices cifc) ->\n      implOStatesInit@[oidx] = Some implOStateInit.\n  Proof.\n    intros; unfold implOStatesInit; fold cifc.\n    assert (~ In (rootOf topo) (tl (c_li_indices cifc) ++ c_l1_indices cifc)).\n    { pose proof (c_li_indices_head_rootOf 0 Htr).\n      pose proof (tree2Topo_WfCIfc tr 0); destruct H1 as [? _].\n      rewrite H0 in H1; inv H1; assumption.\n    }\n    induction (tl (c_li_indices cifc) ++ c_l1_indices cifc); [dest_in|].\n    simpl; icase oidx; [mred|].\n    mred.\n    - elim H0; right; assumption.\n    - apply IHl; auto.\n      intro; elim H0; right; assumption.\n  Qed.\n\n  Lemma implOStatesInit_value_root:\n    implOStatesInit@[rootOf topo] = Some implOStateInitRoot.\n  Proof.\n    intros; unfold implOStatesInit; fold cifc.\n    assert (~ In (rootOf topo) (tl (c_li_indices cifc) ++ c_l1_indices cifc)).\n    { pose proof (c_li_indices_head_rootOf 0 Htr).\n      pose proof (tree2Topo_WfCIfc tr 0); destruct H0 as [? _].\n      rewrite H in H0; inv H0; assumption.\n    }\n    induction (tl (c_li_indices cifc) ++ c_l1_indices cifc); mred.\n  Qed.\n\n  Lemma implOStatesInit_None:\n    forall oidx,\n      ~ In oidx (c_li_indices cifc ++ c_l1_indices cifc) ->\n      implOStatesInit@[oidx] = None.\n  Proof.\n    unfold implOStatesInit; intros.\n    mred.\n    - elim H.\n      subst topo cifc.\n      rewrite c_li_indices_head_rootOf by assumption.\n      left; reflexivity.\n    - assert (~ In oidx (tl (c_li_indices cifc) ++ c_l1_indices cifc)).\n      { subst topo cifc; rewrite c_li_indices_head_rootOf in H by assumption.\n        intro Hx; elim H; right; assumption.\n      }\n      clear -H0.\n      generalize dependent (tl (c_li_indices cifc) ++ c_l1_indices cifc).\n      induction l; simpl; intros; [reflexivity|].\n      mred.\n  Qed.\n\n  Definition implORqsInit: ORqs Msg :=\n    initORqs (cifc.(c_li_indices) ++ cifc.(c_l1_indices)).\n\n  Lemma implORqsInit_value:\n    forall oidx,\n      In oidx (c_li_indices cifc ++ c_l1_indices cifc) ->\n      implORqsInit@[oidx] = Some [].\n  Proof.\n    intros; unfold implORqsInit; fold cifc.\n    induction (c_li_indices cifc ++ c_l1_indices cifc); [dest_in|].\n    simpl; icase oidx; mred.\n  Qed.\n\n  Section Rules.\n    Variables (oidx cidx: IdxT).\n\n    Section L1.\n      (** NOTE: [cidx] will be instantiated to [l1ExtOf oidx]. *)\n\n      Definition l1GetSImm: Rule :=\n        rule 0~>0 from template immd {\n        receive Spec.getRq from cidx;\n        assert (fun ost orq mins => msiS <= ost#[status]);\n        (!|ost, _| --> (ost, <| Spec.getRs; ost#[val] |>))\n      }.\n\n      Definition l1GetSRqUpUp: Rule :=\n        rule 0~>1 from template rquu {\n          receive Spec.getRq from cidx to oidx;\n          assert (fun ost mins => ost#[status] <= msiI);\n          (!|ost, msg| --> <| msiRqS; O |>)\n      }.\n\n      Definition l1GetSRsDownDown: Rule :=\n        rule 0~>2 from template rsdd {\n          receive msiRsS;\n          hold Spec.getRq;\n          assert (fun _ _ _ => True);\n          (!|ost, min, rq, rsbTo|\n            --> (ost +#[val <- msg_value min]\n                     +#[status <- msiS],\n                  <| Spec.getRs; msg_value min |>))\n      }.\n\n      Definition l1DownSImm: Rule :=\n        rule 0~>3 from template immu {\n          receive msiDownRqS to oidx;\n          assert (fun ost orq mins => msiS <= ost#[status]);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- msiS],\n                             <| msiDownRsS; ost#[val] |>))\n      }.\n\n      Definition l1GetMImm: Rule :=\n        rule 1~>0 from template immd {\n          receive Spec.setRq from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[owned] = true /\\ ost#[status] = msiM);\n          (!|ost, msg| --> (ost +#[val <- msg_value msg], <| Spec.setRs; O |>))\n      }.\n\n      Definition l1GetMRqUpUp: Rule :=\n        rule 1~>1 from template rquu {\n          receive Spec.setRq from cidx to oidx;\n          assert (fun ost mins => ost#[status] <= msiS);\n          (!|ost, msg| --> <| msiRqM; O |>)\n      }.\n\n      Definition l1GetMRsDownDown: Rule :=\n        rule 1~>2 from template rsdd {\n          receive msiRsM;\n          hold Spec.setRq;\n          assert (fun _ _ _ => True);\n          (!|ost, min, rq, rsbTo|\n            --> (ost +#[status <- msiM]\n                     +#[owned <- true]\n                     +#[val <- msg_value rq],\n                  <| Spec.setRs; O |>))\n      }.\n\n      Definition l1DownIImmS: Rule :=\n        rule 1~>3~>0 from template immu {\n          receive msiDownRqIS to oidx;\n          assert (fun _ _ _ => True);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- invalidate ost#[status]],\n                             <| msiDownRsIS; O |>))\n      }.\n\n      Definition l1DownIImmM: Rule :=\n        rule 1~>3~>1 from template immu {\n          receive msiDownRqIM to oidx;\n          assert (fun ost orq mins => ost#[status] = msiM);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- invalidate ost#[status]],\n                             <| msiDownRsIM; O |>))\n      }.\n\n      Definition l1InvRqUpUp: Rule :=\n        rule 2~>0 from template rqsu {\n          to oidx;\n          assert (fun ost => ost#[owned] = false /\\ msiNP < ost#[status] < msiM);\n          (ost --> <| msiInvRq; O |>)\n      }.\n\n      (** NOTE: L1 writes back only when it is an owner, but here the\n       * precondition allows to write back regardless of its ownership.\n       * It is to ensure serializability of the system, and a cache controller\n       * in a real implementation should fire this rule only when the status\n       * is M. Thus this design has more behavior, but still correct. The parent\n       * should distinguish whether the data is valid or not by looking at its\n       * directory status.\n       *)\n      Definition l1InvRqUpUpWB: Rule :=\n        rule 2~>1 from template rqsu {\n          to oidx;\n          assert (fun ost => msiNP < ost#[status]);\n          (ost --> <| msiInvWRq; ost#[val] |>)\n      }.\n\n      Definition l1InvRsDownDown: Rule :=\n        rule 2~>2 from template rsds {\n          receive msiInvRs;\n          assert (fun _ _ _ => True);\n          (!|ost, _| --> (ost +#[owned <- false]\n                              +#[status <- msiNP]))\n      }.\n\n    End L1.\n\n    Section Li.\n\n      Definition liGetSImmS: Rule :=\n        rule 0~>0~>0~~cidx from template immd {\n          receive msiRqS from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[dir].(dir_st) <= msiS /\\ ost#[status] = msiS);\n          (!|ost, _| --> (ost +#[dir <- addSharer cidx ost#[dir]],\n                           <| msiRsS; ost#[val] |>))\n      }.\n\n      (** NOTE: it is important to note that the \"owned\" bit is not changed. *)\n      Definition liGetSImmM: Rule :=\n        rule 0~>0~>1~~cidx from template immd {\n          receive msiRqS from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[status] = msiM /\\ ost#[dir].(dir_st) = msiI);\n          (!|ost, _| --> (ost +#[status <- msiS]\n                              +#[dir <- setDirS [cidx]],\n                           <| msiRsS; ost#[val] |>))\n      }.\n\n      Definition liGetSRqUpUp: Rule :=\n        rule 0~>1~~cidx from template rquu {\n          receive msiRqS from cidx to oidx;\n          assert\n            (fun ost mins =>\n               ost#[owned] = false /\\\n               ost#[status] <= msiI /\\ ost#[dir].(dir_st) <= msiS);\n          (!|ost, msg| --> <| msiRqS; O |>)\n      }.\n\n      Definition liGetSRsDownDown: Rule :=\n        rule 0~>2~>0 from template rsdd {\n          receive msiRsS;\n          hold msiRqS;\n          assert (fun _ _ _ => True);\n          (!|ost, min, rq, rsbTo|\n            --> (ost +#[val <- msg_value min]\n                     +#[owned <- false]\n                     +#[status <- msiS]\n                     +#[dir <- addSharer (objIdxOf rsbTo) ost#[dir]],\n                  <| msiRsS; msg_value min |>))\n      }.\n\n      Definition liGetSRqUpDownM: Rule :=\n        rule 0~>3~~cidx from template rqud {\n          receive msiRqS from cidx to oidx;\n          assert\n            (fun ost mins =>\n               cidx <> ost#[dir].(dir_excl) /\\\n               In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM);\n          (!|ost, msg| --> ([ost#[dir].(dir_excl)], <| msiDownRqS; O |>))\n      }.\n\n      Definition liDownSRsUpDownM: Rule :=\n        rule 0~>4 from template rsudo {\n          receive msiDownRsS;\n          hold msiRqS;\n          assert (fun _ => True);\n          (!|ost, idm, rq, rsbTo|\n            --> (ost +#[owned <- true]\n                     +#[val <- msg_value (valOf idm)]\n                     +#[status <- msiS]\n                     +#[dir <- setDirS [objIdxOf rsbTo; objIdxOf (idOf idm)]],\n                  <| msiRsS; msg_value (valOf idm) |>))\n      }.\n\n      (** NOTE:\n       * 1) data should be sent along with [msiDownRsS], even when the status\n       * is S, since the parent might not have the up-to-date data (e.g., when\n       * the line is evicted).\n       * 2) when the status is S, it should be the owner since it previously had\n       * the status M.\n       *)\n      Definition liDownSImm: Rule :=\n        rule 0~>5 from template immu {\n          receive msiDownRqS to oidx;\n          assert\n            (fun ost orq mins =>\n               msiS <= ost#[status] /\\ ost#[dir].(dir_st) <= msiS);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- msiS],\n                             <| msiDownRsS; ost#[val] |>))\n      }.\n\n      Definition liDownSRqDownDownM: Rule :=\n        rule 0~>6 from template rqdd {\n          receive msiDownRqS to oidx;\n          assert\n            (fun ost mins =>\n               In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM);\n          (!|ost, msg| --> ([ost#[dir].(dir_excl)], <| msiDownRqS; O |>))\n      }.\n\n      Definition liDownSRsUpUp: Rule :=\n        rule 0~>7 from template rsuuo {\n          receive msiDownRsS;\n          hold msiDownRqS;\n          assert (fun _ => True);\n          (!|ost, idm, rq, rsbTo|\n            --> (ost +#[val <- msg_value (valOf idm)]\n                     +#[owned <- false]\n                     +#[status <- msiS]\n                     +#[dir <- setDirS [objIdxOf (idOf idm)]],\n                  <| msiDownRsS; msg_value (valOf idm) |>))\n      }.\n\n      Definition liGetMImm: Rule :=\n        rule 1~>0~~cidx from template immd {\n          receive msiRqM from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[status] = msiM \\/\n               (ost#[status] = msiS /\\ ost#[owned] = true /\\\n                ost#[dir].(dir_st) = msiS /\\ LastSharer ost#[dir] cidx));\n          (!|ost, msg| --> (ost +#[owned <- false]\n                                +#[status <- msiI]\n                                +#[dir <- setDirM cidx],\n                             <| msiRsM; O |>))\n      }.\n\n      Definition liGetMRqUpUp: Rule :=\n        rule 1~>1~~cidx from template rquu {\n          receive msiRqM from cidx to oidx;\n          assert\n            (fun ost mins =>\n               ost#[owned] = false /\\\n               ost#[status] <= msiS /\\ ost#[dir].(dir_st) <= msiS);\n          (!|ost, msg| --> <| msiRqM; O |>)\n      }.\n\n      (** This is the case where it's possible to directly respond a [msiRsM]\n       * message back since there are no internal sharers to invalidate.\n       *)\n      Definition liGetMRsDownDownDirI: Rule :=\n        rule 1~>2 from template rsdd {\n          receive msiRsM;\n          hold msiRqM;\n          assert\n            (fun ost orq mins =>\n               ost#[dir].(dir_st) = msiI \\/\n               (ost#[dir].(dir_st) = msiS /\\\n               LastSharer ost#[dir] (objIdxOf (getUpLockIdxBackI orq))));\n          (!|ost, min, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirM (objIdxOf rsbTo)],\n                  <| msiRsM; O |>))\n      }.\n\n      (** This is the case where internal invalidation is required\n       * due to sharers.\n       *)\n      Definition liGetMRsDownRqDownDirS: Rule :=\n        rule 1~>3 from template rsrq {\n          receive msiRsM to oidx;\n          hold msiRqM;\n          assert\n            (fun ost orq mins =>\n               RsDownRqDownSoundPrec\n                 topo oidx orq\n                 (remove idx_dec (objIdxOf (getUpLockIdxBackI orq))\n                         ost#[dir].(dir_sharers)) /\\\n               ost#[dir].(dir_sharers) <> nil /\\\n               SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n               OtherSharerExists ost#[dir] (objIdxOf (getUpLockIdxBackI orq)) /\\\n               ost#[dir].(dir_st) = msiS);\n          (!|ost, rq, rsbTo| --> (ost +#[owned <- true],\n                                   (remove idx_dec (objIdxOf rsbTo) ost#[dir].(dir_sharers),\n                                     <| msiDownRqIS; O |>)))\n      }.\n\n      Definition liGetMRqUpDownM: Rule :=\n        rule 1~>4~~cidx from template rqud {\n          receive msiRqM from cidx to oidx;\n          assert\n            (fun ost mins =>\n               cidx <> ost#[dir].(dir_excl) /\\\n               In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM);\n          (!|ost, msg| --> ([ost#[dir].(dir_excl)], <| msiDownRqIM; O |>))\n      }.\n\n      Definition liGetMRqUpDownS: Rule :=\n        rule 1~>5~~cidx from template rqud {\n          receive msiRqM from cidx to oidx;\n          assert\n            (fun ost mins =>\n               ost#[dir].(dir_sharers) <> nil /\\\n               SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n               OtherSharerExists ost#[dir] cidx /\\\n               ost#[owned] = true /\\ ost#[status] <= msiS /\\ ost#[dir].(dir_st) = msiS);\n          (!|ost, msg| --> (remove idx_dec cidx ost#[dir].(dir_sharers),\n                             <| msiDownRqIS; O |>))\n      }.\n\n      Definition liDownIRsUpDownS: Rule :=\n        rule 1~>6~>0 from template rsud {\n          receive msiDownRsIS;\n          hold msiRqM;\n          assert (fun ost => ost#[dir].(dir_st) = msiS);\n          (!|ost, mins, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirM (objIdxOf rsbTo)],\n                  <| msiRsM; O |>))\n      }.\n\n      Definition liDownIRsUpDownM: Rule :=\n        rule 1~>6~>1 from template rsud {\n          receive msiDownRsIM;\n          hold msiRqM;\n          assert (fun ost => ost#[dir].(dir_st) = msiM);\n          (!|ost, mins, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirM (objIdxOf rsbTo)],\n                  <| msiRsM; O |>))\n      }.\n\n      Definition liDownIImmS: Rule :=\n        rule 1~>7~>0 from template immu {\n          receive msiDownRqIS to oidx;\n          assert (fun ost orq mins => ost#[dir].(dir_st) = msiI);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- invalidate ost#[status]],\n                             <| msiDownRsIS; O |>))\n        }.\n\n      Definition liDownIImmM: Rule :=\n        rule 1~>7~>1 from template immu {\n          receive msiDownRqIM to oidx;\n          assert (fun ost orq mins =>\n                     ost#[status] = msiM /\\ ost#[dir].(dir_st) = msiI);\n          (!|ost, min| --> (ost +#[owned <- false]\n                                +#[status <- msiI],\n                             <| msiDownRsIM; O |>))\n      }.\n\n      Definition liDownIRqDownDownDirS: Rule :=\n        rule 1~>9~>0 from template rqdd {\n          receive msiDownRqIS to oidx;\n          assert\n            (fun ost mins =>\n               ost#[dir].(dir_sharers) <> nil /\\\n               SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[dir].(dir_st) = msiS);\n          (!|ost, msg| --> (ost#[dir].(dir_sharers), <| msiDownRqIS; O |>))\n      }.\n\n      Definition liDownIRqDownDownDirM: Rule :=\n        rule 1~>9~>1 from template rqdd {\n          receive msiDownRqIM to oidx;\n          assert\n            (fun ost mins =>\n               In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[dir].(dir_st) = msiM);\n          (!|ost, msg| --> ([ost#[dir].(dir_excl)], <| msiDownRqIM; O |>))\n      }.\n\n      Definition liDownIRqDownDownDirMS: Rule :=\n        rule 1~>9~>2 from template rqdd {\n          receive msiDownRqIM to oidx;\n          assert\n            (fun ost mins =>\n               ost#[dir].(dir_sharers) <> nil /\\\n               SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n               ost#[dir].(dir_st) = msiS);\n          (!|ost, msg| --> (ost#[dir].(dir_sharers), <| msiDownRqIS; O |>))\n      }.\n\n      Definition liDownIRsUpUpS: Rule :=\n        rule 1~>10~>0 from template rsuu {\n          receive msiDownRsIS;\n          hold msiDownRqIS;\n          assert (fun _ => True);\n          (!|ost, mins, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirI],\n                  <| msiDownRsIS; O |>))\n      }.\n\n      Definition liDownIRsUpUpMS: Rule :=\n        rule 1~>10~>2 from template rsuu {\n          receive msiDownRsIS;\n          hold msiDownRqIM;\n          assert (fun ost => ost#[dir].(dir_st) = msiS);\n          (!|ost, mins, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirI],\n                  <| msiDownRsIM; O |>))\n      }.\n\n      Definition liDownIRsUpUpM: Rule :=\n        rule 1~>10~>1 from template rsuu {\n          receive msiDownRsIM;\n          hold msiDownRqIM;\n          assert (fun ost => ost#[dir].(dir_st) = msiM);\n          (!|ost, mins, rq, rsbTo|\n            --> (ost +#[owned <- false]\n                     +#[status <- invalidate ost#[status]]\n                     +#[dir <- setDirI],\n                  <| msiDownRsIM; O |>))\n      }.\n\n      Definition liInvRqUpUp: Rule :=\n        rule 2~>0 from template rqsu {\n          to oidx;\n          assert (fun ost => ost#[owned] = false /\\\n                               msiNP < ost#[status] < msiM /\\\n                               ost#[dir].(dir_st) = msiI);\n          (ost --> <| msiInvRq; O |>)\n      }.\n\n      (** NOTE: ditto [l1InvRqUpUpWB]; a cache controller should not use this\n       * rule when [owned = false]; it's meaningless.\n       *)\n      Definition liInvRqUpUpWB: Rule :=\n        rule 2~>1 from template rqsu {\n          to oidx;\n          assert (fun ost =>\n                    ost#[dir].(dir_st) = msiI /\\\n                    ((ost#[owned] = true /\\ msiI < ost#[status]) \\/\n                    (ost#[owned] = false /\\ msiNP < ost#[status] <= msiS)));\n          (ost --> <| msiInvWRq; ost#[val] |>)\n      }.\n\n      Definition liInvRsDownDown: Rule :=\n        rule 2~>2 from template rsds {\n          receive msiInvRs;\n          assert (fun _ _ _ => True);\n          (!|ost, _| --> (ost +#[owned <- false]\n                              +#[status <- msiNP]))\n      }.\n\n      Definition liDropImm: Rule :=\n        rule 2~>3 from template imm {\n          assert (fun ost orq mins => ost#[status] <= msiS /\\ ost#[owned] = false);\n          (ost --> ost +#[status <- msiNP])\n      }.\n\n      Definition liInvImmI: Rule :=\n        rule 2~>5~~cidx from template immd {\n          receive msiInvRq from cidx;\n          assert (fun ost orq mins => getDir cidx ost#[dir] = msiI);\n          (!|ost, _| --> (ost, <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmS00: Rule :=\n        rule 2~>6~>0~>0~~cidx from template immd {\n          receive msiInvRq from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[owned] = false /\\\n               getDir cidx ost#[dir] = msiS /\\ LastSharer ost#[dir] cidx);\n          (!|ost, _| --> (ost +#[dir <- setDirI], <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmS01: Rule :=\n        rule 2~>6~>0~>1~~cidx from template immd {\n          receive msiInvRq from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[owned] = true /\\ ost#[status] = msiS /\\\n               getDir cidx ost#[dir] = msiS /\\ LastSharer ost#[dir] cidx);\n          (!|ost, _| --> (ost +#[status <- msiM]\n                              +#[dir <- setDirI], <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmS1: Rule :=\n        rule 2~>6~>1~~cidx from template immd {\n          receive msiInvRq from cidx;\n          assert\n            (fun ost orq mins =>\n               getDir cidx ost#[dir] = msiS /\\ NotLastSharer ost#[dir]);\n          (!|ost, _| --> (ost +#[dir <- removeSharer cidx ost#[dir]],\n                           <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmWBI: Rule :=\n        rule 2~>7~~cidx from template immd {\n          receive msiInvWRq from cidx;\n          assert (fun ost orq mins => getDir cidx ost#[dir] = msiI);\n          (!|ost, _| --> (ost, <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmWBS0: Rule :=\n        rule 2~>8~>0~~cidx from template immd {\n          receive msiInvWRq from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[owned] = false /\\\n               getDir cidx ost#[dir] = msiS /\\ LastSharer ost#[dir] cidx);\n          (!|ost, _| --> (ost +#[dir <- setDirI], <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmWBS1: Rule :=\n        rule 2~>8~>1~~cidx from template immd {\n          receive msiInvWRq from cidx;\n          assert\n            (fun ost orq mins =>\n               getDir cidx ost#[dir] = msiS /\\ NotLastSharer ost#[dir]);\n          (!|ost, _| --> (ost +#[dir <- removeSharer cidx ost#[dir]],\n                           <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmWBS: Rule :=\n        rule 2~>9~~cidx from template immd {\n          receive msiInvWRq from cidx;\n          assert\n            (fun ost orq mins =>\n               ost#[owned] = true /\\ ost#[status] = msiS /\\\n               getDir cidx ost#[dir] = msiS /\\ LastSharer ost#[dir] cidx);\n          (!|ost, msg| --> (ost +#[status <- msiM]\n                                +#[dir <- setDirI], <| msiInvRs; O |>))\n      }.\n\n      Definition liInvImmWBM: Rule :=\n        rule 2~>10~~cidx from template immd {\n          receive msiInvWRq from cidx;\n          assert (fun ost orq mins => getDir cidx ost#[dir] = msiM);\n          (!|ost, msg| --> (ost +#[dir <- setDirI]\n                                +#[owned <- true]\n                                +#[status <- msiM]\n                                +#[val <- msg_value msg],\n                             <| msiInvRs; O |>))\n      }.\n\n    End Li.\n\n  End Rules.\n\n  Section Objects.\n    Variable (oidx: IdxT).\n\n    Section L1.\n      Let eidx := l1ExtOf oidx.\n\n      Program Definition l1: Object :=\n        {| obj_idx := oidx;\n           obj_rules :=\n             [(** rules involved with [GetS] *)\n               l1GetSImm eidx; l1GetSRqUpUp oidx eidx;\n             l1GetSRsDownDown; l1DownSImm oidx;\n             (** rules involved with [GetM] *)\n             l1GetMImm eidx;\n             l1GetMRqUpUp oidx eidx;\n             l1GetMRsDownDown; l1DownIImmS oidx; l1DownIImmM oidx;\n             (** rules involved with [Put] *)\n             l1InvRqUpUp oidx; l1InvRqUpUpWB oidx; l1InvRsDownDown];\n           obj_rules_valid := _ |}.\n      Next Obligation.\n        inds_valid_tac.\n      Qed.\n\n    End L1.\n\n    Definition liRulesFromChild (cidx: IdxT): list Rule :=\n      [liGetSImmS cidx; liGetSImmM cidx; liGetSRqUpUp oidx cidx;\n      liGetSRqUpDownM oidx cidx; liGetMImm cidx; liGetMRqUpUp oidx cidx;\n      liGetMRqUpDownM oidx cidx; liGetMRqUpDownS oidx cidx;\n      liInvImmI cidx; liInvImmS00 cidx; liInvImmS01 cidx; liInvImmS1 cidx;\n      liInvImmWBI cidx; liInvImmWBS0 cidx; liInvImmWBS1 cidx;\n      liInvImmWBS cidx; liInvImmWBM cidx].\n\n    Definition liRulesFromChildren (coinds: list IdxT): list Rule :=\n      List.concat (map liRulesFromChild coinds).\n\n    Hint Unfold liRulesFromChild liRulesFromChildren: RuleConds.\n\n    Ltac disc_child_inds_disj :=\n      pose proof (tree2Topo_TreeTopo tr 0);\n      try match goal with\n          | [Hn: ?n1 <> ?n2,\n                 H1: nth_error (subtreeChildrenIndsOf ?topo ?sidx) ?n1 = Some _,\n                     H2: nth_error (subtreeChildrenIndsOf ?topo ?sidx) ?n2 = Some _ |- _] =>\n            eapply TreeTopo_children_inds_disj in Hn; eauto; destruct Hn\n          end.\n\n    Program Definition li: Object :=\n      {| obj_idx := oidx;\n         obj_rules :=\n           (liRulesFromChildren (subtreeChildrenIndsOf topo oidx))\n             (** rules involved with [GetS] *)\n             ++ [liGetSRsDownDown; liDownSRsUpDownM;\n                liDownSImm oidx; liDownSRqDownDownM oidx; liDownSRsUpUp]\n             (** rules involved with [GetM] *)\n             ++ [liGetMRsDownDownDirI; liGetMRsDownRqDownDirS oidx;\n                liDownIRsUpDownS; liDownIRsUpDownM;\n                liDownIImmS oidx; liDownIImmM oidx;\n                liDownIRqDownDownDirS oidx; liDownIRqDownDownDirM oidx;\n                liDownIRqDownDownDirMS oidx;\n                liDownIRsUpUpS; liDownIRsUpUpM; liDownIRsUpUpMS]\n             (** rules involved with [Put] *)\n             ++ [liInvRqUpUp oidx; liInvRqUpUpWB oidx; liInvRsDownDown; liDropImm];\n         obj_rules_valid := _ |}.\n    Next Obligation.\n      solve_inds_NoDup disc_child_inds_disj.\n    Qed.\n\n    Definition memRulesFromChild (cidx: IdxT): list Rule :=\n      [liGetSImmM cidx; liGetMImm cidx; liInvImmWBM cidx].\n\n    Definition memRulesFromChildren (coinds: list IdxT): list Rule :=\n      List.concat (map memRulesFromChild coinds).\n\n    Hint Unfold memRulesFromChild memRulesFromChildren: RuleConds.\n\n    Program Definition mem: Object :=\n      {| obj_idx := oidx;\n         obj_rules := memRulesFromChildren (subtreeChildrenIndsOf topo oidx);\n         obj_rules_valid := _ |}.\n    Next Obligation.\n      solve_inds_NoDup disc_child_inds_disj.\n    Qed.\n\n  End Objects.\n\n  Program Definition impl: System :=\n    {| sys_objs :=\n         ((mem (rootOf topo) :: map li (tl cifc.(c_li_indices)))\n            ++ map l1 cifc.(c_l1_indices));\n       sys_oinds_valid := _;\n       sys_minds := cifc.(c_minds);\n       sys_merqs := cifc.(c_merqs);\n       sys_merss := cifc.(c_merss);\n       sys_msg_inds_valid := _;\n       sys_oss_inits := implOStatesInit;\n       sys_orqs_inits := implORqsInit |}.\n  Next Obligation.\n    unfold mem, li, l1.\n    rewrite map_app.\n    do 2 rewrite map_trans.\n    do 2 rewrite map_id.\n    unfold topo, cifc.\n    rewrite app_comm_cons.\n    rewrite <-c_li_indices_head_rootOf by assumption.\n    apply tree2Topo_WfCIfc.\n  Qed.\n  Next Obligation.\n    apply tree2Topo_WfCIfc.\n  Qed.\n\nEnd System.\n\n#[global] Hint Unfold l1GetSImm l1GetSRqUpUp l1GetSRsDownDown\n l1DownSImm l1GetMImm l1GetMRqUpUp l1GetMRsDownDown\n l1DownIImmS l1DownIImmM l1InvRqUpUp l1InvRqUpUpWB l1InvRsDownDown: MsiRules.\n\n#[global] Hint Unfold liGetSImmS liGetSImmM\n liGetSRqUpUp liGetSRsDownDown\n liGetSRqUpDownM liDownSRsUpDownM\n liDownSImm liDownSRqDownDownM liDownSRsUpUp\n liGetMImm liGetMRqUpUp liGetMRsDownDownDirI liGetMRsDownRqDownDirS\n liGetMRqUpDownM liGetMRqUpDownS liDownIRsUpDownS liDownIRsUpDownM\n liDownIImmS liDownIImmM liDownIRqDownDownDirS liDownIRqDownDownDirM liDownIRqDownDownDirMS\n liDownIRsUpUpS liDownIRsUpUpM liDownIRsUpUpMS\n liInvRqUpUp liInvRqUpUpWB liInvRsDownDown\n liInvImmI liInvImmS00 liInvImmS01 liInvImmS1\n liInvImmWBI liInvImmWBS0 liInvImmWBS1 liInvImmWBS liInvImmWBM liDropImm: MsiRules.\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/Msi/Msi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.17585878329340884}}
{"text": "(* ill library for yalla *)\n\n\n(** * Intuitionistic Linear Logic *)\n(* Cut admissibility, see ill_prop.v for other properties *)\n\nRequire Import Arith_base.\nRequire Import List.\n\nRequire Import Injective.\nRequire Import List_more.\nRequire Import List_Type_more.\nRequire Import Permutation_Type_more.\nRequire Import genperm_Type.\nRequire Import flat_map_Type_more.\nRequire Import wf_nat_more.\n\nRequire Export ill_def.\n\n\nSection Cut_Elim_Proof.\n\nContext {P : ipfrag}.\n\nHypothesis P_gax_noN_l : forall a, In N (fst (projT2 (ipgax P) a)) -> False.\nHypothesis P_gax_at_l : forall a, Forall iatomic (fst (projT2 (ipgax P) a)).\nHypothesis P_gax_at_r : forall a, iatomic (snd (projT2 (ipgax P) a)).\nHypothesis P_gax_cut : forall a b l1 l2,\n                            fst (projT2 (ipgax P) b) = l1 ++ snd (projT2 (ipgax P) a) :: l2 -> \n                          { c | l1 ++ fst (projT2 (ipgax P) a) ++ l2 = fst (projT2 (ipgax P) c)\n                                /\\ snd (projT2 (ipgax P) b) = snd (projT2 (ipgax P) c) }.\n\nLemma cut_oc_comm_left : ipcut P = false -> forall n A C l1 l2, ill P (l1 ++ ioc A :: l2) C -> \n  (forall lw (pi0 : ill P (map ioc lw) A), ipsize pi0 < n -> ill P (l1 ++ map ioc lw ++ l2) C) ->\n  forall l0 (pi1 : ill P l0 (ioc A)), ipsize pi1 <= n -> ill P (l1 ++ l0 ++ l2) C.\nProof with myeasy_perm_Type.\nintros P_cutfree n A C l1 l2 pi2 ; induction n ; intros IH l0 pi1 Hs ;\n  remember (ioc A) as B ; destruct_ill pi1 f X l Hl Hr HP a ;\n  try (exfalso ; simpl in Hs ; clear -Hs ; myeasy ; fail) ; try inversion HeqB.\n- apply (ex_ir _ (l1 ++ l ++ l2)).\n  + simpl in Hs.\n    refine (IHn _ _ Hl _)...\n    intros ; refine (IH _ pi0 _)...\n  + apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n- list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n  list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l0) ; rewrite <- (app_assoc l).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply one_ilr.\n  list_simpl ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply tens_ilr.\n  list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n  list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l3).\n  simpl in Hs ; refine (IHn _ _ Hr _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n  list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l3).\n  simpl in Hs ; refine (IHn _ _ Hr _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply with_ilr1.\n  list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply with_ilr2.\n  list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply zero_ilr.\n- list_simpl ; rewrite app_assoc ; apply plus_ilr.\n  + list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0).\n    simpl in Hs ; refine (IHn _ _ Hl _)...\n    intros ; refine (IH _ pi0 _)...\n  + list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0).\n    simpl in Hs ; refine (IHn _ _ Hr _)...\n    intros ; refine (IH _ pi0 _)...\n- subst ; apply (IH _ Hl)...\n- list_simpl ; rewrite app_assoc ; apply de_ilr.\n  list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply wk_ilr.\n  list_simpl ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- list_simpl ; rewrite app_assoc ; apply co_ilr.\n  list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l0).\n  simpl in Hs ; refine (IHn _ _ Hl _)...\n  intros ; refine (IH _ pi0 _)...\n- rewrite f in P_cutfree ; inversion P_cutfree.\n- exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\nQed.\n\nLemma substitution_ioc : ipcut P = false -> forall A,\n  (forall l0 l1 l2 C, ill P l0 A -> ill P (l1 ++ A :: l2) C -> ill P (l1 ++ l0 ++ l2) C) ->\n  forall lw l C, ill P (map ioc lw) A -> ill P l C -> forall l' L,\n  l = l' ++ flat_map (cons (ioc A)) L -> ill P (l' ++ flat_map (app (map ioc lw)) L) C.\nProof with myeasy_perm_Type.\nintros P_cutfree A IHcut lw l C pi1 pi2.\ninduction pi2 ; intros l' L Heq.\n- destruct l' ; inversion Heq.\n  + destruct L ; inversion Heq.\n  + symmetry in H1 ; apply app_eq_nil in H1 ; destruct H1 ; subst.\n    destruct L ; inversion H1.\n    apply ax_ir.\n- case_eq (ipperm P) ; intros Hperm ; rewrite Hperm in p ; simpl in p ; subst.\n  + destruct (perm_Type_app_flat_map _ (map ioc lw) _ _ _ p) as [[L' l''] (Hnil' & HeqL' & HPL')] ;\n      simpl in Hnil' ; simpl in HeqL' ; simpl in HPL' ; subst.\n    eapply ex_ir ; [ | rewrite Hperm ; simpl ; apply HPL' ].\n    refine (IHpi2 _ _ _)...\n  + refine (IHpi2 _ _ _)...\n- assert (injective ioc) as Hinj by (intros x y Hxy ; inversion Hxy ; reflexivity).\n  destruct (perm_flat_map_cons_flat_map_app  _ ioc Hinj lw _ _ _ _ _ _ p Heq)\n    as [(((lw1',lw2'),(l1',l2')),(l'',L')) HH] ; simpl in HH ; destruct HH as (H1 & H2 & H3 & H4).\n  rewrite <- H4 ; apply (ex_oc_ir _ _ lw1')...\n  rewrite H3 ; apply IHpi2...\n- symmetry in Heq ; apply app_eq_nil in Heq ; destruct Heq as [H Heq] ; subst.\n  destruct L ; inversion Heq.\n  apply one_irr.\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply one_ilr.\n    rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply one_ilr.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ l0 ++ flat_map (app (map ioc lw)) L1)\n       with (flat_map (app (map ioc lw)) ((l ++ l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n- app_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply tens_irr...\n    refine (IHpi2_2 _ _ _)...\n  + rewrite flat_map_app ; list_simpl.\n    rewrite 3 app_assoc ; apply tens_irr...\n    * list_simpl.\n      replace (flat_map (app (map ioc lw)) L0 ++ map ioc lw ++ l)\n         with (flat_map (app (map ioc lw)) (L0 ++ l :: nil))\n        by (rewrite flat_map_app ; list_simpl ; reflexivity).\n      refine (IHpi2_1 _ _ _)...\n    * refine (IHpi2_2 _ _ _)...\n  + rewrite flat_map_app ; list_simpl.\n    rewrite app_assoc ; apply tens_irr...\n    * refine (IHpi2_1 _ _ _)...\n    * rewrite <- (app_nil_l _) ; refine (IHpi2_2 _ _ _)...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply tens_ilr.\n    rewrite 2 app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply tens_ilr.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ A0 :: B :: l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ A0 :: B :: l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n- apply lpam_irr.\n  induction L using rev_ind_Type ; list_simpl.\n  + change nil with (nil ++ flat_map (app (map ioc lw)) nil).\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; subst ; list_simpl...\n  + replace (flat_map (app (map ioc lw)) (L ++ x :: nil) ++ A0 :: nil)\n       with (flat_map (app (map ioc lw)) (L ++ (x ++ (A0 :: nil)) :: nil))\n      by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n    refine (IHpi2 _ _ _) ; subst ; list_simpl...\n    rewrite ? flat_map_app ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + app_vs_app_flat_map_inv Heq1.\n    * list_simpl ; apply lpam_ilr...\n      rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n    * list_simpl ; rewrite ? flat_map_app ; list_simpl.\n      rewrite (app_assoc l) ; rewrite (app_assoc _ (map ioc lw)) ; rewrite (app_assoc _ l3).\n      replace (((l ++ flat_map (app (map ioc lw)) L0) ++ map ioc lw) ++ l3)\n         with (l ++ flat_map (app (map ioc lw)) (L0 ++ l3 :: nil))\n        by (rewrite flat_map_app ; list_simpl ; reflexivity).\n      apply lpam_ilr...\n      -- refine (IHpi2_1 _ _ _)...\n      -- rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n    * list_simpl ; rewrite flat_map_app.\n      rewrite (app_assoc l) ; apply lpam_ilr.\n      -- refine (IHpi2_1 _ _ _)...\n      -- rewrite <- (app_nil_l (flat_map _ _)).\n         rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n  + app_vs_app_flat_map_inv Heq2.\n    * list_simpl ; rewrite ? flat_map_app ; list_simpl.\n      rewrite (app_assoc l') ; rewrite (app_assoc _ (map ioc lw)) ; rewrite (app_assoc _ l).\n      replace (((l' ++ flat_map (app (map ioc lw)) L0) ++ map ioc lw) ++ l)\n         with (l' ++ flat_map (app (map ioc lw)) (L0 ++ l :: nil))\n        by (rewrite flat_map_app ; list_simpl ; reflexivity).\n      apply lpam_ilr...\n      list_simpl.\n      replace (flat_map (app (map ioc lw)) (L0 ++ l :: nil) ++ B :: l1 ++ flat_map (app (map ioc lw)) L1)\n         with (flat_map (app (map ioc lw)) (L0 ++ (l ++ B :: l1) :: L1))\n        by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n      refine (IHpi2_2 _ _ _) ; rewrite ? flat_map_app ; list_simpl...\n    * list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n      rewrite (app_assoc l3) ; rewrite (app_assoc _ _ (l1 ++ _)) ; rewrite (app_assoc _ l1).\n      replace (((l3 ++ flat_map (app (map ioc lw)) L) ++ map ioc lw) ++ l1)\n         with (l3 ++ flat_map (app (map ioc lw)) (L ++ l1 :: nil))\n        by (rewrite flat_map_app ; list_simpl ; reflexivity).\n      rewrite 3 app_assoc ; apply lpam_ilr...\n      -- refine (IHpi2_1 _ _ _)...\n      -- list_simpl.\n         replace (flat_map (app (map ioc lw)) L0 ++ map ioc lw ++ l ++ B :: l4\n                                                 ++ flat_map (app (map ioc lw)) L2)\n            with (flat_map (app (map ioc lw)) (L0 ++ (l ++ B :: l4) :: L2))\n           by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n         refine (IHpi2_2 _ _ _) ; rewrite ? flat_map_app ; list_simpl...\n    * list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n      rewrite (app_assoc l3) ; rewrite 3 app_assoc ; apply lpam_ilr...\n      -- refine (IHpi2_1 _ _ _)...\n      -- list_simpl.\n         replace (flat_map (app (map ioc lw)) L0 ++ map ioc lw ++ l\n                                                 ++ B :: flat_map (app (map ioc lw)) L2)\n            with (flat_map (app (map ioc lw)) (L0 ++ (l ++ B :: nil) :: L2))\n           by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n         refine (IHpi2_2 _ _ _) ; rewrite ? flat_map_app ; list_simpl...\n- apply gen_irr.\n  induction L using rev_ind_Type ; list_simpl.\n  + change nil with (nil ++ flat_map (app (map ioc lw)) nil).\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; subst ; list_simpl...\n  + replace (flat_map (app (map ioc lw)) (L ++ x :: nil) ++ A0 :: nil)\n       with (flat_map (app (map ioc lw)) (L ++ (x ++ (A0 :: nil)) :: nil))\n      by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n    refine (IHpi2 _ _ _) ; subst ; list_simpl...\n    rewrite ? flat_map_app ; list_simpl...\n- destruct l' ; inversion Heq ; subst.\n  + destruct L ; inversion H0.\n  + list_simpl.\n    apply gen_ilr.\n    apply IHpi2...\n- apply lmap_irr.\n  rewrite app_comm_cons ; refine (IHpi2 _ _ _) ; subst ; list_simpl...\n- rewrite app_assoc in Heq ; elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply lmap_ilr...\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n  + replace (flat_map (cons (ioc A)) L0 ++ ioc A :: l)\n       with (flat_map (cons (ioc A)) (L0 ++ l :: nil))\n      in Heq1 by (rewrite flat_map_app ; list_simpl ; reflexivity).\n    app_vs_app_flat_map_inv Heq1.\n    * list_simpl ; rewrite ? flat_map_app ; list_simpl.\n      rewrite (app_assoc l2) ; rewrite (app_assoc _ (map ioc lw)) ; rewrite (app_assoc _ l).\n      replace (((l2 ++ flat_map (app (map ioc lw)) L0) ++ map ioc lw) ++ l)\n         with (l2 ++ flat_map (app (map ioc lw)) (L0 ++ l :: nil))\n        by (rewrite flat_map_app ; list_simpl ; reflexivity).\n      apply lmap_ilr...\n      -- refine (IHpi2_1 _ _ _)...\n      -- rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n    * induction L2 using rev_ind_Type ; [ | clear IHL2 ].\n      -- assert (L0 = L /\\ l = l2 ++ l4) as [Heq1 Heq2] ; subst.\n         { apply (f_equal (@rev _)) in Heq0.\n           rewrite ? rev_app_distr in Heq0.\n           inversion Heq0 ; subst.\n           apply (f_equal (@rev _)) in H1.\n           rewrite ? rev_involutive in H1 ; subst.\n           split... }\n         list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n         list_simpl in pi2_1.\n         rewrite 3 app_assoc ; apply lmap_ilr...\n         list_simpl ; rewrite <- app_assoc in IHpi2_2.\n         replace (flat_map (cons (ioc A)) (L ++ l2 :: nil) ++ B :: l3 ++ flat_map (cons (ioc A)) L1)\n            with (flat_map (cons (ioc A)) (L ++ (l2 ++ B :: l3) :: L1)) in IHpi2_2\n           by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n         assert (pi2' := IHpi2_2 _ _ eq_refl).\n         rewrite ? flat_map_app in pi2' ; list_simpl in pi2'...\n      -- assert (L0 = L ++ (l2 ++ l4) :: L2 /\\ l = x) as [Heq1 Heq2] ; subst.\n         { apply (f_equal (@rev _)) in Heq0.\n           rewrite ? rev_app_distr in Heq0 ; list_simpl in Heq0.\n           inversion Heq0 ; subst.\n           apply (f_equal (@rev _)) in H1.\n           rewrite ? rev_involutive in H1 ; subst.\n           rewrite ? rev_app_distr ; list_simpl ; split... }\n         list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n         rewrite 3 app_assoc ; rewrite (app_assoc l4) ; rewrite (app_assoc (l4 ++ _)) ; rewrite (app_assoc _ x).\n         apply lmap_ilr...\n         ++ list_simpl.\n            replace (flat_map (app (map ioc lw)) L2 ++ map ioc lw ++ x)\n               with (flat_map (app (map ioc lw)) (L2 ++ x :: nil))\n              by (rewrite flat_map_app ; list_simpl ; reflexivity).\n            refine (IHpi2_1 _ _ _)...\n         ++ list_simpl ; rewrite <- app_assoc in IHpi2_2.\n            replace (flat_map (cons (ioc A)) (L ++ l2 :: nil) ++ B :: l3 ++ flat_map (cons (ioc A)) L1)\n               with (flat_map (cons (ioc A)) (L ++ (l2 ++ B :: l3) :: L1)) in IHpi2_2\n              by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n            assert (pi2' := IHpi2_2 _ _ eq_refl).\n            rewrite ? flat_map_app in pi2' ; list_simpl in pi2'...\n    * induction L2 using rev_ind_Type ; [ | clear IHL2 ].\n      -- list_simpl in Heq0 ; subst.\n         list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n         list_simpl in pi2_1.\n         rewrite <- (app_nil_l (ilmap _ _ :: _)) ; rewrite 3 app_assoc ; apply lmap_ilr...\n         list_simpl ; rewrite <- app_assoc in IHpi2_2.\n         replace (flat_map (cons (ioc A)) (L0 ++ l :: nil) ++ B :: l3 ++ flat_map (cons (ioc A)) L1)\n            with (flat_map (cons (ioc A)) (L0 ++ (l ++ B :: l3) :: L1)) in IHpi2_2\n           by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n         assert (pi2' := IHpi2_2 _ _ eq_refl).\n         rewrite ? flat_map_app in pi2' ; list_simpl in pi2'...\n      -- assert (L0 = L ++ L2 /\\ l = x) as [Heq1 Heq2] ; subst.\n         { apply (f_equal (@rev _)) in Heq0.\n           rewrite ? rev_app_distr in Heq0 ; list_simpl in Heq0.\n           inversion Heq0 ; subst.\n           apply (f_equal (@rev _)) in H1.\n           rewrite rev_involutive in H1 ; subst.\n           rewrite rev_app_distr ; list_simpl ; split... }\n         list_simpl ; rewrite ? flat_map_app ; list_simpl ; rewrite ? flat_map_app ; list_simpl.\n         rewrite app_assoc ; rewrite (app_assoc _ (map ioc lw)) ; rewrite (app_assoc _ x) ; apply lmap_ilr...\n         ++ list_simpl.\n            replace (flat_map (app (map ioc lw)) L2 ++ map ioc lw ++ x)\n               with (flat_map (app (map ioc lw)) (L2 ++ x :: nil))\n              by (rewrite flat_map_app ; list_simpl ; reflexivity).\n            rewrite <- (app_nil_l _).\n            refine (IHpi2_1 _ _ _)...\n         ++ induction L using rev_ind_Type ; [ | clear IHL ].\n            ** list_simpl in IHpi2_2 ; list_simpl.\n               rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n            ** list_simpl ; rewrite <- app_assoc in IHpi2_2.\n               replace (flat_map (cons (ioc A)) (L ++ x0 :: nil) ++ B :: l3 ++ flat_map (cons (ioc A)) L1)\n                  with (flat_map (cons (ioc A)) (L ++ (x0 ++ B :: l3) :: L1)) in IHpi2_2\n                 by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n               assert (pi2' := IHpi2_2 _ _ eq_refl).\n               rewrite ? flat_map_app in pi2' ; list_simpl in pi2'.\n               rewrite ? flat_map_app ; list_simpl...\n- apply neg_irr.\n  rewrite app_comm_cons ; refine (IHpi2 _ _ _) ; subst ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + symmetry in Heq1 ; apply app_eq_nil in Heq1 ; destruct Heq1 as [Heq Heq1] ; subst.\n    destruct L ; inversion Heq1.\n    list_simpl ; apply neg_ilr...\n  + symmetry in Heq2 ; apply app_eq_nil in Heq2 ; destruct Heq2 as [Heq Heq2] ; subst.\n    destruct L1 ; inversion Heq2.\n    rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply neg_ilr.\n    rewrite <- 2 app_assoc.\n    replace (map ioc lw ++ l0)\n      with (flat_map (app (map ioc lw)) (l0 :: nil)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n- apply top_irr.\n- apply with_irr.\n  + refine (IHpi2_1 _ _ _) ; list_simpl...\n  + refine (IHpi2_2 _ _ _) ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply with_ilr1.\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply with_ilr1.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ A0 :: l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ A0 :: l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply with_ilr2.\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply with_ilr2.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ A0 :: l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ A0 :: l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply zero_ilr.\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply zero_ilr.\n- apply plus_irr1.\n  refine (IHpi2 _ _ _) ; subst ; list_simpl...\n- apply plus_irr2.\n  refine (IHpi2 _ _ _) ; subst ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply plus_ilr.\n    * rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_1 _ _ _) ; list_simpl...\n    * rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2_2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply plus_ilr ; rewrite <- 3 app_assoc.\n    * replace (map ioc lw ++ l ++ A0 :: l0 ++ flat_map (app (map ioc lw)) L1)\n        with (flat_map (app (map ioc lw)) ((l ++ A0 :: l0) :: L1)) by (list_simpl ; reflexivity).\n      rewrite <- flat_map_app ; refine (IHpi2_1 _ _ _)...\n      rewrite ? flat_map_app ; list_simpl...\n    * replace (map ioc lw ++ l ++ B :: l0 ++ flat_map (app (map ioc lw)) L1)\n        with (flat_map (app (map ioc lw)) ((l ++ B :: l0) :: L1)) by (list_simpl ; reflexivity).\n      rewrite <- flat_map_app ; refine (IHpi2_2 _ _ _)...\n      rewrite ? flat_map_app ; list_simpl...\n- symmetry in Heq ; decomp_map_Type Heq ; subst ; simpl in Heq2 ; simpl.\n  assert ({ Lw | flat_map (app (map ioc lw)) L = map ioc Lw }) as [Lw HeqLw].\n  { clear pi2 IHpi2 ; revert l2 Heq2 ; clear ; induction L ; intros l2 Heq2.\n    - exists nil...\n    - simpl in Heq2.\n      decomp_map_Type Heq2 ; subst.\n      inversion Heq1 ; subst ; simpl.\n      simpl in Heq4 ; apply IHL in Heq4.\n      destruct Heq4 as [Lw Heq4].\n      exists (lw ++ l1 ++ Lw) ; list_simpl ; rewrite <- Heq4... }\n  rewrite HeqLw ; rewrite <- map_app ; apply oc_irr.\n  list_simpl ; rewrite <- HeqLw ; refine (IHpi2 _ _ _).\n  rewrite Heq2 ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply de_ilr.\n    rewrite app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply de_ilr.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ A0 :: l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ A0 :: l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n  + inversion HeqA ; subst.\n    induction L0 using rev_ind_Type ; [ | clear IHL0 ].\n    * list_simpl ; list_simpl in IHpi2.\n      rewrite app_comm_cons in IHpi2 ; rewrite app_assoc in IHpi2.\n      assert (pi2' := IHpi2 _ _ eq_refl).\n      list_simpl in pi2' ; apply (IHcut _ _ _ _ pi1) in pi2'...\n    * rewrite <- ? app_assoc in IHpi2.\n      replace (flat_map (cons (ioc A)) (L0 ++ x :: nil) ++ A :: l ++ flat_map (cons (ioc A)) L1)\n         with (flat_map (cons (ioc A)) (L0 ++ (x ++ A :: l) :: L1)) in IHpi2\n        by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n      assert (pi2' := IHpi2 _ _ eq_refl).\n      rewrite flat_map_app in pi2' ; list_simpl in pi2'.\n      rewrite 3 app_assoc in pi2' ; apply (IHcut _ _ _ _ pi1) in pi2'...\n      list_simpl in pi2' ; rewrite ? flat_map_app ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply wk_ilr.\n    rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply wk_ilr.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n  + inversion HeqA ; subst.\n    induction L0 using rev_ind_Type ; [ | clear IHL0 ].\n    * list_simpl ; apply wk_list_ilr.\n      list_simpl in IHpi2 ; rewrite app_assoc in IHpi2.\n      rewrite app_assoc ; refine (IHpi2 _ _ _)...\n    * rewrite <- ? app_assoc in IHpi2.\n      replace (flat_map (cons (ioc A)) (L0 ++ x :: nil) ++ l ++ flat_map (cons (ioc A)) L1)\n         with (flat_map (cons (ioc A)) (L0 ++ (x ++ l) :: L1)) in IHpi2\n        by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n      assert (pi2' := IHpi2 _ _ eq_refl).\n      rewrite flat_map_app in pi2' ; list_simpl in pi2'.\n      list_simpl ; rewrite flat_map_app ; list_simpl.\n      rewrite 3 app_assoc ; apply wk_list_ilr ; list_simpl...\n- elt_vs_app_flat_map_inv Heq.\n  + list_simpl ; apply co_ilr.\n    rewrite 2 app_comm_cons ; rewrite app_assoc ; refine (IHpi2 _ _ _) ; list_simpl...\n  + rewrite flat_map_app.\n    list_simpl ; rewrite 3 app_assoc ; apply co_ilr.\n    rewrite <- 3 app_assoc.\n    replace (map ioc lw ++ l ++ ioc A0 :: ioc A0 :: l0 ++ flat_map (app (map ioc lw)) L1)\n      with (flat_map (app (map ioc lw)) ((l ++ ioc A0 :: ioc A0 :: l0) :: L1)) by (list_simpl ; reflexivity).\n    rewrite <- flat_map_app ; refine (IHpi2 _ _ _)...\n    rewrite ? flat_map_app ; list_simpl...\n  + inversion HeqA ; subst.\n    induction L0 using rev_ind_Type ; [ | clear IHL0 ].\n    * list_simpl ; apply co_list_ilr.\n      list_simpl in IHpi2.\n      replace (ioc A :: ioc A :: l ++ flat_map (cons (ioc A)) L1)\n         with (flat_map (cons (ioc A)) (nil :: l :: L1)) in IHpi2\n        by (list_simpl ; reflexivity).\n      replace (map ioc lw ++ map ioc lw ++ l ++ flat_map (app (map ioc lw)) L1)\n         with (flat_map (app (map ioc lw)) (nil :: l :: L1))\n        by (list_simpl ; reflexivity).\n      refine (IHpi2 _ _ _)...\n    * rewrite <- ? app_assoc in IHpi2.\n      replace (flat_map (cons (ioc A)) (L0 ++ x :: nil) ++ ioc A :: ioc A :: l ++ flat_map (cons (ioc A)) L1)\n         with (flat_map (cons (ioc A)) (L0 ++ x :: nil :: l :: L1)) in IHpi2\n        by (rewrite ? flat_map_app ; list_simpl ; reflexivity).\n      assert (pi2' := IHpi2 _ _ eq_refl).\n      rewrite flat_map_app in pi2' ; list_simpl in pi2'.\n      list_simpl ; rewrite flat_map_app ; list_simpl.\n      rewrite 3 app_assoc ; apply co_list_ilr ; list_simpl...\n- rewrite f in P_cutfree ; inversion P_cutfree.\n- assert (L = nil) as Hnil ; subst.\n  { specialize P_gax_at_l with a.\n    rewrite Heq in P_gax_at_l.\n    apply Forall_app_inv in P_gax_at_l ; destruct P_gax_at_l as [_ Hat].\n    destruct L ; inversion Hat...\n    inversion H1. }\n  list_simpl in Heq ; list_simpl ; subst ; apply gax_ir.\nQed.\n\nTheorem cut_ir_gaxat : forall A l0 l1 l2 C,\n  ill P l0 A -> ill P (l1 ++ A :: l2) C -> ill P (l1 ++ l0 ++ l2) C.\nProof with myeasy_perm_Type.\ncase_eq (ipcut P) ; intros P_cutfree.\n{ intros A l0 l1 l2 C pi1 pi2 ; eapply cut_ir... }\nenough (forall c s A l0 l1 l2 C (pi1 : ill P l0 A) (pi2 : ill P (l1 ++ A :: l2) C),\n          s = ipsize pi1 + ipsize pi2 -> ifsize A <= c -> ill P (l1 ++ l0 ++ l2) C) as IH\nby (intros A l0 l1 l2 C pi1 pi2 ; refine (IH _ _ A _ _ _ _ pi1 pi2 _ _) ; myeasy_perm_Type).\ninduction c as [c IHcut0] using lt_wf_rect.\nassert (forall A, ifsize A < c -> forall l0 l1 l2 C,\n          ill P l0 A -> ill P (l1 ++ A :: l2) C -> ill P (l1 ++ l0 ++ l2) C) as IHcut\n  by (intros A Hs l0 l1 l2 C pi1 pi2 ; refine (IHcut0 _ _ _ _ _ _ _ _ pi1 pi2 _ _) ; myeasy_perm_Type) ;\n  clear IHcut0.\ninduction s as [s IHsize0] using lt_wf_rect.\nassert (forall A l0 l1 l2 C (pi1 : ill P l0 A) (pi2 : ill P (l1 ++ A :: l2) C),\n          ipsize pi1 + ipsize pi2 < s -> ifsize A <= c -> ill P (l1 ++ l0 ++ l2) C)\n  as IHsize by (intros ; eapply IHsize0 ; myeasy_perm_Type) ; clear IHsize0.\nintros A l0 l1 l2 C pi1 pi2 Heqs Hc.\nrewrite_all Heqs ; clear s Heqs.\nremember (l1 ++ A :: l2) as l ; destruct_ill pi2 f X l Hl Hr HP a.\n- (* ax_ir *)\n  unit_vs_elt_inv Heql ; list_simpl...\n- (* ex_ir *)\n  simpl in IHsize.\n  case_eq (ipperm P) ; intros Hperm ; rewrite_all Hperm ; simpl in HP.\n  + assert (HP' := HP).\n    apply Permutation_Type_vs_elt_inv in HP' ; destruct HP' as [(l1',l2') Heq] ;\n      simpl in Heq ; subst.\n    apply Permutation_Type_app_inv in HP.\n    eapply (ex_ir _ (l1' ++ l0 ++ l2')) ; [ | rewrite Hperm ; apply Permutation_Type_app_middle ]...\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + subst.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* ex_oc_ir *)\n  simpl in IHsize.\n  dichot_Type_elt_app_exec Heql ; subst.\n  + rewrite 2 app_assoc.\n    eapply ex_oc_ir...\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + dichot_Type_elt_app_exec Heql1 ; subst.\n    * decomp_map_Type Heql0 ; subst ; simpl in HP ; simpl in pi1.\n      assert (HP' := HP).\n      apply Permutation_Type_vs_elt_inv in HP' ; destruct HP' as [(l1',l2') Heq] ;\n        simpl in Heq ; subst.\n      apply Permutation_Type_app_inv in HP.\n      revert Hl IHsize ; list_simpl ; rewrite app_assoc ; intros Hl IHsize.\n      rewrite app_assoc ; eapply (cut_oc_comm_left _ (ipsize pi1))...\n      -- list_simpl ; rewrite app_comm_cons ; change (ioc x :: map ioc l7) with (map ioc (x :: l7)) ;\n           rewrite (app_assoc (map ioc l4)) ; rewrite <- map_app.\n         apply (ex_oc_ir _ _ (l1' ++ x :: l2'))...\n         revert Hl IHsize ; list_simpl ; rewrite app_assoc ; intros Hl IHsize...\n      -- intros lw pi0 Hs'.\n         list_simpl ; rewrite (app_assoc (map ioc l4)) ; rewrite (app_assoc _ (map ioc l7)) ;\n           rewrite <- (app_assoc (map ioc l4)) ; rewrite <- 2 map_app ;\n           apply (ex_oc_ir _ _ (l1' ++ lw ++ l2'))...\n         list_simpl ; rewrite app_assoc.\n         refine (IHsize _ _ _ _ _ (oc_irr _ _ _ pi0) Hl _ _) ; simpl...\n    * rewrite <- 2 app_assoc.\n      eapply ex_oc_ir...\n      revert Hl IHsize ; simpl ; rewrite 2 app_assoc ; intros Hl IHsize.\n      rewrite 2 app_assoc ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* one_irr *)\n  destruct l1 ; inversion Heql.\n- (* one_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply one_ilr.\n    revert Hl IHsize ; simpl ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite app_assoc ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + remember (one_ilr _ _ _ _ Hl) as Hone ; clear HeqHone.\n    remember (ione) as C ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqC.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hone _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply one_ilr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* tens_irr *)\n  dichot_Type_elt_app_exec Heql ; subst.\n  + rewrite 2 app_assoc ; apply tens_irr...\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + rewrite <- app_assoc ; apply tens_irr...\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n- (* tens_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply tens_ilr.\n    revert Hl IHsize ; simpl ; rewrite 2 app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite 2 app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + remember (tens_ilr _ _ _ _ _ _ Hl) as Htens ; clear HeqHtens.\n    remember (itens A0 B) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * rewrite <- app_assoc ; rewrite app_assoc.\n      simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hr2 _)...\n      list_simpl ; refine (IHcut _ _ _ _ _ _ Hl2 Hl)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Htens _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply tens_ilr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* lpam_irr *)\n  revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n  apply lpam_irr.\n  list_simpl ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* lpam_ilr *)\n  simpl in IHsize ; trichot_Type_elt_elt_exec Heql.\n  + dichot_Type_elt_app_exec Heql1 ; subst.\n    * list_simpl ; rewrite 2 app_assoc.\n      apply lpam_ilr...\n      list_simpl ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n    * list_simpl ; apply lpam_ilr...\n      revert Hr IHsize ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hr IHsize.\n      rewrite app_comm_cons ; rewrite app_assoc.\n      refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n  + change (S (ipsize Hl + ipsize Hr)) with (ipsize (lpam_ilr _ _ _ _ _ _ _ Hl Hr)) in IHsize.\n    remember (lpam_ilr _ _ _ _ _ _ _ Hl Hr) as Hlpam ; clear HeqHlpam.\n    remember (ilpam A0 B) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l4 ++ l ++ l3 ++ l5)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * rewrite app_assoc.\n      simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl _)...\n      list_simpl ; change (A0 :: l5) with ((A0 :: nil) ++ l5) ; rewrite (app_assoc l).\n      refine (IHcut _ _ _ _ _ _ Hl2 Hr)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlpam _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc ; apply lpam_ilr...\n    revert Hr IHsize ; list_simpl ; intros Hr IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n- (* gen_irr *)\n  simpl in IHsize.\n  apply gen_irr.\n  revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n  refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* gen_ilr *)\n  destruct l1 ; inversion Heql ; subst.\n  + remember (gen_ilr _ _ _ Hl) as Hgen ; clear HeqHgen.\n    remember (igen A0) as D ; destruct_ill pi1 f X l' Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (nil ++ l' ++ l2)).\n      -- revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n         refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; eapply ex_oc_ir...\n      rewrite <- app_assoc ; rewrite (app_assoc l') ; rewrite (app_assoc _ l0) ; rewrite <- (app_assoc l').\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite <- app_comm_cons ; rewrite <- app_assoc ; rewrite app_assoc.\n      apply lpam_ilr...\n      rewrite <- app_assoc ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hr2 Hgen  _ _) ; simpl...\n    * subst ; list_simpl ; rewrite <- (app_nil_r _) ; rewrite <- app_assoc.\n      refine (IHcut _ _ _ _ _ _ Hl Hl2) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hr2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply zero_ilr.\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n         refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n         refine (IHsize _ _ _ _ _ Hr2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgen IHsize ; rewrite <- (app_nil_l _) ; intros Hgen IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hgen _ _) ; simpl...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + list_simpl ; apply gen_ilr.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _) ; simpl...\n- (* lmap_irr *)\n  simpl in IHsize.\n  apply lmap_irr.\n  revert Hl IHsize ; rewrite app_comm_cons ; intros Hl IHsize.\n  rewrite app_comm_cons ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* lmap_ilr *)\n  simpl in IHsize ; rewrite app_assoc in Heql ; trichot_Type_elt_elt_exec Heql.\n  + list_simpl ; apply lmap_ilr...\n    revert Hr IHsize ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hr IHsize.\n    rewrite app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n  + change (S (ipsize Hl + ipsize Hr)) with (ipsize (lmap_ilr _ _ _ _ _ _ _ Hl Hr)) in IHsize.\n    remember (lmap_ilr _ _ _ _ _ _ _ Hl Hr) as Hlmap  ; clear HeqHlmap.\n    revert Hlmap IHsize ; rewrite app_assoc ; intros Hlmap IHsize.\n    remember (ilmap A0 B) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ ((l4 ++ l3) ++ l ++ l5)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite 2 app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ;\n        rewrite <- (app_assoc l) ; rewrite app_assoc ; simpl in IHsize.\n      refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlmap _ _)...\n    * list_simpl ; simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl _)...\n      rewrite app_comm_cons ; refine (IHcut _ _ _ _ _ _ Hl2 Hr)...\n    * list_simpl ; rewrite 2 app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite 2 app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * list_simpl ; rewrite 2 app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1) ; rewrite app_assoc.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hlmap _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + dichot_Type_elt_app_exec Heql0 ; subst.\n    * list_simpl ; rewrite 2 app_assoc.\n      apply lmap_ilr...\n      revert Hr IHsize ; list_simpl ; intros Hr IHsize.\n      refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n    * list_simpl ; rewrite (app_assoc l6) ; rewrite (app_assoc _ l) ; apply lmap_ilr...\n      list_simpl ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* neg_irr *)\n  simpl in IHsize.\n  apply neg_irr.\n  revert Hl IHsize ; rewrite app_comm_cons ; intros Hl IHsize.\n  rewrite app_comm_cons ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* neg_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + destruct l3 ; inversion Heql1.\n  + remember (neg_ilr _ _ _ Hl) as Hneg ; clear HeqHneg.\n    remember (ineg A0) as D ; destruct_ill pi1 f X l' Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l ++ l' ++ nil)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; eapply ex_oc_ir...\n      rewrite <- app_assoc ; rewrite (app_assoc l') ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l').\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite <- app_comm_cons ; rewrite <- app_assoc ; rewrite app_assoc.\n      apply lpam_ilr...\n      rewrite <- app_assoc ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hneg _ _)...\n    * clear IHsize ; rewrite <- (app_nil_l (A :: l0)) in Hl2.\n      list_simpl ; simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl Hl2)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply zero_ilr.\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite <- ? app_assoc ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hneg _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply neg_ilr...\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* top_irr *)\n  apply top_irr.\n- (* with_irr *)\n  simpl in IHsize.\n  apply with_irr.\n  + refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n- (* with_ilr1 *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply with_ilr1.\n    revert Hl IHsize ; simpl ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + remember (with_ilr1 _ _ _ _ _ _ Hl) as Hwith ; clear HeqHwith.\n    remember (iwith A0 B) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl2 Hl)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply with_ilr1.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* with_ilr2 *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply with_ilr2.\n    revert Hl IHsize ; simpl ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + remember (with_ilr2 _ _ _ _ _ _ Hl) as Hwith ; clear HeqHwith.\n    remember (iwith B A0) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hr2 Hl)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hwith _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply with_ilr2.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* zero_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply zero_ilr.\n  + remember (zero_ilr _ l3 l4 C) as Hzero ; clear HeqHzero.\n    remember izero as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hzero _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply zero_ilr.\n- (* plus_irr1 *)\n  simpl in IHsize.\n  apply plus_irr1.\n  refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* plus_irr2 *)\n  simpl in IHsize.\n  apply plus_irr2.\n  refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* plus_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply plus_ilr.\n    * revert Hl IHsize ; simpl ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n      rewrite app_comm_cons ; rewrite app_assoc.\n      refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n    * revert Hr IHsize ; simpl ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hr IHsize.\n      rewrite app_comm_cons ; rewrite app_assoc.\n      refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n  + remember (plus_ilr _ _ _ _ _ _ Hl Hr) as Hplus ; clear HeqHplus.\n    remember (iplus A0 B) as D ; destruct_ill pi1 f X l Hl2 Hr2 HP a ; try inversion HeqD.\n    * apply (ex_ir _ (l3 ++ l ++ l4)).\n      -- simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n      -- apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n    * list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l2) ; rewrite <- (app_assoc l).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply one_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply tens_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr1.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply with_ilr2.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply zero_ilr.\n    * simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl2 Hl)...\n    * simpl in Hc ; subst ; refine (IHcut _ _ _ _ _ _ Hl2 Hr)...\n    * list_simpl ; rewrite app_assoc ; apply plus_ilr.\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n      -- list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n         simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply de_ilr.\n      list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply wk_ilr.\n      list_simpl ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * list_simpl ; rewrite app_assoc ; apply co_ilr.\n      list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hplus _ _)...\n    * rewrite f in P_cutfree ; inversion P_cutfree.\n    * exfalso ; assert (Hiq := P_gax_at_r a) ; rewrite H0 in Hiq ; inversion Hiq.\n  + rewrite 2 app_assoc.\n    apply plus_ilr.\n    * revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n      list_simpl ; refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n    * revert Hr IHsize ; list_simpl ; intros Hr IHsize.\n      list_simpl ; refine (IHsize _ _ _ _ _ pi1 Hr _ _)...\n- (* oc_irr *)\n  remember (oc_irr _ _ _ Hl) as Hloc ; rewrite HeqHloc in IHsize ; clear HeqHloc.\n  symmetry in Heql ; decomp_map_Type Heql ; subst ; simpl in pi1.\n  simpl in IHsize ; simpl in Hl ; list_simpl.\n  eapply (cut_oc_comm_left _ (ipsize pi1))...\n  + change (ioc x :: map ioc l6) with (map ioc (x :: l6)) ; rewrite <- map_app ; apply oc_irr...\n  + intros lw Hs' pi.\n    rewrite <- 2 map_app ; apply oc_irr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ (oc_irr _ _ _ Hs') Hl _ _) ; simpl...\n- (* de_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply de_ilr.\n    revert Hl IHsize ; simpl ; rewrite app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + eapply (cut_oc_comm_left _ (ipsize pi1))...\n    * apply de_ilr...\n    * intros lw Hs pi.\n      simpl in Hc ; refine (IHsize _ _ _ _ _ Hs Hl _ _) ; simpl...\n  + rewrite 2 app_assoc.\n    apply de_ilr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* wk_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply wk_ilr.\n    revert Hl IHsize ; simpl ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + eapply (cut_oc_comm_left _ (ipsize pi1))...\n    * apply wk_ilr...\n    * intros lw Hs pi.\n      apply wk_list_ilr...\n  + rewrite 2 app_assoc.\n    apply wk_ilr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* co_ilr *)\n  trichot_Type_elt_elt_exec Heql.\n  + list_simpl.\n    apply co_ilr.\n    revert Hl IHsize ; simpl ; rewrite 2 app_comm_cons ; rewrite app_assoc ; intros Hl IHsize.\n    rewrite 2 app_comm_cons ; rewrite app_assoc.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n  + eapply (cut_oc_comm_left _ (ipsize pi1))...\n    * apply co_ilr...\n    * intros lw Hs _.\n      replace (ioc A0 :: ioc A0 :: l4)\n         with (flat_map (cons (ioc A0)) (nil :: l4 :: nil)) in Hl  by (list_simpl ; reflexivity).\n      apply co_list_ilr.\n      replace (map ioc lw ++ map ioc lw ++ l4)\n         with (flat_map (app (map ioc lw)) (nil :: l4 :: nil)) by (list_simpl ; reflexivity).\n      refine (substitution_ioc _ _ _ _ _ _ _ _ _ _ _) ; list_simpl...\n      apply IHcut...\n  + rewrite 2 app_assoc.\n    apply co_ilr.\n    revert Hl IHsize ; list_simpl ; intros Hl IHsize.\n    refine (IHsize _ _ _ _ _ pi1 Hl _ _)...\n- (* cut_ir *)\n  rewrite f in P_cutfree ; inversion P_cutfree.\n- (* gax_ir *)\n  assert (Hiq := P_gax_at_l a) ; rewrite Heql in Hiq.\n  apply Forall_elt in Hiq.\n  simpl in IHsize.\n  remember (gax_ir _ a) as Hgax ; apply (f_equal ipsize) in HeqHgax ; simpl in HeqHgax.\n  destruct_ill pi1 f X l Hl2 Hr2 HP b ; try (exfalso ; inversion Hiq ; fail).\n  + list_simpl ; rewrite <- Heql ; apply (gax_ir _ a).\n  + apply (ex_ir _ (l1 ++ l ++ l2)).\n    * revert Hgax HeqHgax ; rewrite Heql ; intros Hgax HeqHgax.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n    * apply PEperm_Type_app_head ; apply PEperm_Type_app_tail...\n  + list_simpl ; rewrite app_assoc ; eapply ex_oc_ir...\n      list_simpl ; rewrite (app_assoc l) ; rewrite (app_assoc _ l0) ; rewrite <- (app_assoc l).\n      revert Hgax HeqHgax ; rewrite Heql ; intros Hgax HeqHgax.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply one_ilr.\n    list_simpl ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite (app_assoc l0) ; intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply tens_ilr.\n    list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l0) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply lpam_ilr...\n    list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l3) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hgax _ _)...\n  + exfalso.\n    apply (P_gax_noN_l a).\n    rewrite Heql.\n    apply in_elt.\n  + list_simpl ; rewrite app_assoc ; apply lmap_ilr...\n    list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l3) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hgax _ _)...\n  + exfalso.\n    apply (P_gax_noN_l a).\n    rewrite Heql.\n    apply in_elt.\n  + list_simpl ; rewrite app_assoc ; apply with_ilr1.\n    list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply with_ilr2.\n    list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply zero_ilr.\n  + list_simpl ; rewrite app_assoc ; apply plus_ilr.\n    * list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0) ;\n        intros Hgax HeqHgax.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n    * list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n      revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0) ;\n        intros Hgax HeqHgax.\n      simpl in IHsize ; refine (IHsize _ _ _ _ _ Hr2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply de_ilr.\n    list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite app_comm_cons ; rewrite (app_assoc l0) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply wk_ilr.\n    list_simpl ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite (app_assoc l0) ; intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + list_simpl ; rewrite app_assoc ; apply co_ilr.\n    list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l1).\n    revert Hgax HeqHgax ; rewrite Heql ; list_simpl ; rewrite 2 app_comm_cons ; rewrite (app_assoc l0) ;\n      intros Hgax HeqHgax.\n    simpl in IHsize ; refine (IHsize _ _ _ _ _ Hl2 Hgax _ _)...\n  + rewrite f in P_cutfree ; inversion P_cutfree.\n  + destruct (P_gax_cut b a _ _ Heql) as [x [Hx1 Hx2]].\n    rewrite Hx1 ; rewrite Hx2.\n    apply (gax_ir _ x).\nUnshelve. all : assumption.\nQed.\n\nEnd Cut_Elim_Proof.\n\n(** ** Variants on cut admissibility *)\n\n(** If axioms are atomic and closed under cut, then the cut rule is admissible:\nprovability is preserved if we remove the cut rule. *)\nLemma cut_admissible_ill {P} :\n  (forall a, In N (fst (projT2 (ipgax P) a)) -> False) ->\n  (forall a, Forall iatomic (fst (projT2 (ipgax P) a))) ->\n  (forall a, iatomic (snd (projT2 (ipgax P) a))) ->\n  (forall a b l1 l2, fst (projT2 (ipgax P) b) = l1 ++ snd (projT2 (ipgax P) a) :: l2 -> \n                  { c | l1 ++ fst (projT2 (ipgax P) a) ++ l2 = fst (projT2 (ipgax P) c)\n                        /\\ snd (projT2 (ipgax P) b) = snd (projT2 (ipgax P) c) }) ->\n  forall l C, ill P l C -> ill (cutrm_ipfrag P) l C.\nProof with myeeasy.\nintros HatNl Hatl Hatr Hcut l C pi.\ninduction pi ; try (econstructor ; myeeasy ; fail).\n- eapply cut_ir_gaxat...\n- assert (ipgax P = ipgax (cutrm_ipfrag P)) as Hgax by reflexivity.\n  revert a ; rewrite Hgax ; apply gax_ir.\nQed.\n\n(** If there are no axioms (except the identity rule), then the cut rule is valid. *)\nLemma cut_ir_axfree {P} : (projT1 (ipgax P) -> False) -> forall A l0 l1 l2 C, \n  ill P l0 A -> ill P (l1 ++ A :: l2) C -> ill P (l1 ++ l0 ++ l2) C.\nProof.\nintros P_axfree A l0 l1 l2 C pi1 pi2.\neapply cut_ir_gaxat ; try eassumption.\nall: intros a ; exfalso ; apply (P_axfree a).\nQed.\n\n(** If there are no axioms (except the identity rule), then the cut rule is admissible:\nprovability is preserved if we remove the cut rule. *)\nLemma cut_admissible_ill_axfree {P} : (projT1 (ipgax P) -> False) -> forall l C,\n  ill P l C -> ill (cutrm_ipfrag P) l C.\nProof.\nintros P_axfree l C pi.\neapply cut_admissible_ill ; try eassumption.\nall: intros a ; exfalso ; apply (P_axfree a).\nQed.\n\n\n(** ** Standard intuitionistic linear logic: [ill_ll] (no axiom, commutative) *)\n\n(** cut / axioms / permutation *)\nDefinition ipfrag_ill := mk_ipfrag false NoIAxioms true.\n(*                                 cut   axioms    perm  *)\nDefinition ill_ll := ill ipfrag_ill.\n\nLemma cut_ll_ir : forall A l0 l1 l2 C, \n  ill_ll l0 A -> ill_ll (l1 ++ A :: l2) C -> ill_ll (l1 ++ l0 ++ l2) C.\nProof with myeeasy.\nintros A l1 l2 pi1 pi2.\neapply cut_ir_axfree...\nintros a ; destruct a.\nQed.\n\nLemma cut_ll_admissible :\n  forall l C, ill (cutupd_ipfrag ipfrag_ill true) l C -> ill_ll l C.\nProof with myeeasy.\nintros l C pi.\ninduction pi ; try (now econstructor).\n- eapply ex_ir...\n- eapply ex_oc_ir...\n- eapply cut_ll_ir...\nQed.\n\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/yalla/ill_cut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.17568443843008813}}
{"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 (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 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 (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 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- destruct (Float32.eq_dec n1 Float32.zero).\n  subst n1. simpl. destruct (rs#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 (rs#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 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.of_int (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.of_int (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_mulfsimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vsingle n ->\n  let (op, args) := make_mulfsimm n r1 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.mulfs rs#r1 rs#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 (rs#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  rs#r1 = Vsingle n ->\n  let (op, args) := make_mulfsimm n r2 r1 r2 in\n  exists v, eval_operation ge (Vptr sp Int.zero) op rs##args m = Some v /\\ Val.lessdef (Val.mulfs rs#r1 rs#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 (rs#r2); simpl; auto. rewrite Float32.mul2_add; auto. \n  rewrite Float32.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 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(* 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(* mulfs *)\n  InvApproxRegs; SimplVM; inv H0. rewrite <- H2. apply make_mulfsimm_correct; auto.\n  InvApproxRegs; SimplVM; inv H0. fold (Val.mulfs (Vsingle n1) rs#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 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": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/arm/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.17568443160935512}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\n\nSet Implicit Arguments.\n\n\n(** rel-fenced *)\n\nDefinition local_relfenced (lc:Local.t) :=\n  (Local.mk (TView.mk\n               (fun _ => (TView.cur (Local.tview lc)))\n               (TView.cur (Local.tview lc))\n               (TView.acq (Local.tview lc)))\n            (Local.promises lc)\n            (Local.reserves lc)).\n\nLemma local_relfenced_wf\n      lc gl\n      (WF: Local.wf lc gl):\n  Local.wf (local_relfenced lc) gl.\nProof.\n  inv WF. econs; ss; eauto.\n  - inv TVIEW_WF. econs; ss. refl.\n  - inv TVIEW_CLOSED. econs; ss.\nQed.\n\nLemma local_relfenced_sim_local\n      lc gl\n      (WF: Local.wf lc gl):\n  sim_local lc (local_relfenced lc).\nProof.\n  econs; ss. econs; try refl; apply WF.\nQed.\n\nLemma sim_local_relfenced\n      lc_src\n      lc_tgt gl_tgt\n      (LOCAL: sim_local lc_src lc_tgt)\n      (LC_WF_TGT: Local.wf lc_tgt gl_tgt):\n  sim_local lc_src (local_relfenced lc_tgt).\nProof.\n  etrans; eauto using local_relfenced_sim_local.\nQed.\n\nLemma sim_local_internal_relfenced\n      e\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      (STEP_TGT: Local.internal_step e lc1_tgt gl1_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.internal_step e lc1_src gl1_src lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_relfenced lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  exploit local_relfenced_wf; try exact LC_WF1_TGT. i.\n  exploit sim_local_internal; try exact LOCAL1; eauto.\n  unfold local_relfenced. destruct lc1_tgt.\n  inv STEP_TGT; inv LOCAL; ss; eauto.\nQed.\n\nLemma sim_local_read_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (STEP_TGT: Local.read_step lc1_tgt gl1_tgt loc ts val released_tgt ord_tgt lc2_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src gl1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_relfenced lc2_tgt)>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try exact GET; try apply GLOBAL1. i. des. inv MSG.\n  esplits; eauto.\n  - econs; eauto; try by etrans; eauto.\n    eapply TViewFacts.readable_mon; eauto. apply TVIEW.\n  - econs; eauto. inv TVIEW. ss. econs; s.\n    + i. unfold LocFun.find. etrans; [apply LC_WF1_SRC|].\n      eauto using View.join_l.\n    + repeat apply View.join_le; ss.\n      * unfold View.singleton_ur_if. repeat condtac; viewtac.\n      * repeat condtac; viewtac.\n    + repeat apply View.join_le; ss.\n      * unfold View.singleton_ur_if. repeat condtac; viewtac.\n      * repeat condtac; viewtac.\nQed.\n\nLemma sim_local_write_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF_SRC: View.opt_wf releasedm_src)\n      (RELM_CLOSED_SRC: Memory.closed_opt_view releasedm_src (Global.memory gl1_src))\n      (RELM_WF_TGT: View.opt_wf releasedm_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.plain \\/ Ordering.le Ordering.acqrel ord_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt gl1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists released_src lc2_src gl2_src,\n    <<STEP_SRC: Local.write_step lc1_src gl1_src loc from to val releasedm_src released_src ord_src lc2_src gl2_src>> /\\\n    <<RELEASED: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src (local_relfenced lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  guardH ORD_TGT. inv STEP_TGT.\n  assert (REL:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) loc to releasedm_tgt ord_tgt)).\n  { unfold TView.write_released.\n    condtac; [|econs].\n    condtac; try by (destruct ord_src, ord_tgt; ss).\n    econs. unfold TView.write_tview. s.\n    repeat (condtac; aggrtac); try by apply LC_WF1_TGT.\n    + rewrite <- View.join_r. rewrite <- ? View.join_l. apply LOCAL1.\n    + rewrite <- View.join_r. rewrite <- ? View.join_l.\n      etrans; [|apply LOCAL1]. apply LC_WF1_SRC.\n    + unguard. des; destruct ord_src, ord_tgt; ss.\n  }\n  assert (REL_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply LC_WF1_SRC).\n  }\n  exploit sim_memory_add_exists; try exact WRITE; try apply GLOBAL1.\n  { econs 1. exact REL_WF. }\n  { econs; try exact REL; try refl.\n    apply ord_implb. eassumption.\n  }\n  i. des.\n  exploit sim_local_fulfill; try apply LOCAL1; eauto. i.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.writable_mon; try exact WRITABLE; eauto. apply LOCAL1.\n  - ss.\n  - inv LOCAL1. ss. econs; ss. inv TVIEW. econs; ss.\n    + i. rewrite LocFun.add_spec. condtac; ss.\n      * subst. unfold LocFun.find.\n        condtac; apply View.join_le; viewtac.\n        etrans; eauto. refl.\n      * unfold LocFun.find. etrans; [apply LC_WF1_SRC|].\n        eauto using View.join_l.\n    + apply View.join_le; viewtac.\n    + apply View.join_le; viewtac.\n  - econs; ss. apply GLOBAL1.\nQed.\n\nLemma sim_local_update_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      lc3_tgt gl3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt\n      (STEP1_TGT: Local.read_step lc1_tgt gl1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt gl1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt gl3_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (ORD2_TGT: Ordering.le ord2_tgt Ordering.plain \\/ Ordering.le Ordering.acqrel ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src gl3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src gl1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src gl1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src gl3_src>> /\\\n    <<LOCAL3: sim_local lc3_src (local_relfenced lc3_tgt)>> /\\\n    <<GLOBAL3: sim_global gl3_src gl3_tgt>>.\nProof.\n  guardH ORD2_TGT.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_read_relfenced; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_local_write_relfenced; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_fence_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt gl1_tgt ordr_tgt ordw_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt)\n      (ORDR_TGT: Ordering.le ordr_tgt Ordering.acqrel)\n      (ORDW_TGT: Ordering.le ordw_tgt Ordering.relaxed):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.fence_step lc1_src gl1_src ordr_src ordw_src lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_relfenced lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv STEP_TGT. esplits.\n  - econs; eauto.\n    i. inv LOCAL1. ss. rewrite PROMISES0.\n    apply PROMISES. destruct ordw_src, ordw_tgt; ss.\n  - inv LOCAL1. inv TVIEW. econs; ss.\n    econs; s; unfold LocFun.find; repeat condtac; aggrtac.\n    + etrans; eauto. apply LC_WF1_TGT.\n    + etrans; eauto. apply LC_WF1_TGT.\n    + etrans; eauto. apply LC_WF1_TGT.\n  - inv GLOBAL1. econs; ss.\n    unfold TView.write_fence_sc.\n    repeat (condtac; viewtac).\nQed.\n\nLemma sim_local_is_racy_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ord_src ord_tgt\n      (STEP_TGT: Local.is_racy lc1_tgt gl1_tgt loc to ord_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<STEP_SRC: Local.is_racy lc1_src gl1_src loc to ord_src>>.\nProof.\n  inv LOCAL1. inv GLOBAL1. inv STEP_TGT; ss.\n  - econs; congr.\n  - exploit sim_memory_get; try exact GET; try eassumption. i. des. inv MSG0.\n    econs; try exact GET0.\n    + eapply TViewFacts.racy_view_mon; eauto. apply TVIEW.\n    + i. destruct na, na1; ss.\n      exploit MSG; ss. destruct ord_src, ord_tgt; ss.\nQed.\n\nLemma sim_local_racy_read_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to val ord_src ord_tgt\n      (STEP_TGT: Local.racy_read_step lc1_tgt gl1_tgt loc to val ord_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<STEP_SRC: Local.racy_read_step lc1_src gl1_src loc to val ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy_relfenced; eauto.\nQed.\n\nLemma sim_local_racy_write_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ord_src ord_tgt\n      (STEP_TGT: Local.racy_write_step lc1_tgt gl1_tgt loc to ord_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  <<STEP_SRC: Local.racy_write_step lc1_src gl1_src loc to ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy_relfenced; eauto.\nQed.\n\nLemma sim_local_racy_update_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ordr_src ordw_src ordr_tgt ordw_tgt\n      (STEP_TGT: Local.racy_update_step lc1_tgt gl1_tgt loc to ordr_tgt ordw_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src gl1_src loc to ordr_src ordw_src>>.\nProof.\n  inv STEP_TGT; eauto.\n  exploit sim_local_is_racy_relfenced; eauto.\nQed.\n\nLemma sim_local_fence_src_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.fence_step lc1_src gl1_src Ordering.plain Ordering.acqrel lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_relfenced lc1_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl1_tgt>>.\nProof.\n  inv LOCAL1. inv TVIEW. ss.\n  esplits.\n  - econs; eauto. i. ss.\n  - econs; eauto. econs; ss; eauto.\n    repeat (condtac; aggrtac).\n  - inv GLOBAL1. ss.\nQed.\n\nLemma sim_local_fence_tgt_relfenced\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt gl1_tgt Ordering.plain Ordering.acqrel lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_relfenced lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt):\n  <<LOCAL2: sim_local lc1_src lc2_tgt>> /\\\n  <<GLOBAL2: sim_global gl1_src gl2_tgt>>.\nProof.\n  inv LOCAL1. inv TVIEW. inv STEP_TGT. splits.\n  - econs; ss.\n    unfold TView.read_fence_tview. condtac; ss.\n    unfold TView.write_fence_tview. econs; repeat (condtac; aggrtac).\n  - inv GLOBAL1. ss.\nQed.\n\n\n(** acquired *)\n\nDefinition local_acquired (lc:Local.t) :=\n  (Local.mk\n     (TView.read_fence_tview (Local.tview lc) Ordering.acqrel)\n     (Local.promises lc)\n     (Local.reserves lc)).\n\nLemma local_acquired_wf\n      lc gl\n      (WF: Local.wf lc gl):\n  Local.wf (local_acquired lc) gl.\nProof.\n  inv WF. econs; ss.\n  - inv TVIEW_WF. econs; ss.\n    + condtac; ss. etrans; eauto.\n    + condtac; ss. refl.\n  - inv TVIEW_CLOSED. econs; ss.\nQed.\n\nLemma sim_local_internal_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      e lc2_tgt gl2_tgt\n      (STEP_TGT: Local.internal_step e lc1_tgt gl1_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_acquired lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.internal_step e lc1_src gl1_src lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_acquired lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  exploit local_acquired_wf; try exact LC_WF1_TGT. i.\n  exploit sim_local_internal; try exact LOCAL1; eauto.\n  unfold local_acquired. destruct lc1_tgt.\n  inv STEP_TGT; inv LOCAL; ss; eauto.\nQed.\n\nLemma sim_local_read_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      loc ts val released_tgt\n      (STEP_TGT: Local.read_step lc1_tgt gl1_tgt loc ts val released_tgt Ordering.relaxed lc2_tgt)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src gl1_src loc ts val released_src Ordering.acqrel lc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_acquired lc2_tgt)>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; try apply GLOBAL1. i. des. inv MSG.\n  esplits; eauto.\n  - econs; eauto; try by (etrans; eauto). inv READABLE. econs; ss; i.\n    + rewrite <- PLN. apply TVIEW.\n    + rewrite <- RLX; ss. apply TVIEW.\n  - econs; eauto. s.\n    unfold TView.read_tview, TView.read_fence_tview. ss.\n    econs; repeat (condtac; aggrtac).\n    all: try by apply TVIEW.\n    all: try by apply LC_WF1_TGT.\n    + rewrite <- ? View.join_l. etrans; [apply TVIEW|]. apply LC_WF1_TGT.\n    + inv GL_WF1_TGT. inv MEM_CLOSED.\n      exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\n    + rewrite <- ? View.join_l. apply TVIEW.\n    + inv GL_WF1_TGT. inv MEM_CLOSED.\n      exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\nQed.\n\nLemma sim_local_write_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF_SRC: View.opt_wf releasedm_src)\n      (RELM_CLOSED_SRC: Memory.closed_opt_view releasedm_src (Global.memory gl1_src))\n      (RELM_WF_TGT: View.opt_wf releasedm_tgt)\n      (RELM_TO_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.strong_relaxed)\n      (STEP_TGT: Local.write_step lc1_tgt gl1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_acquired lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt))):\n  exists released_src lc2_src gl2_src,\n    <<STEP_SRC: Local.write_step lc1_src gl1_src loc from to val releasedm_src released_src ord_src lc2_src gl2_src>> /\\\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src (local_acquired lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (REL:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) loc to releasedm_tgt ord_tgt)).\n  { 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 LC_WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply LC_WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (REL_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply LC_WF1_SRC).\n  }\n  exploit sim_memory_add_exists; try exact WRITE; try apply GLOBAL1.\n  { econs 1. exact REL_WF. }\n  { econs; try exact REL; try refl.\n    apply ord_implb. eassumption.\n  }\n  i. des.\n  exploit sim_local_fulfill; try apply LOCAL1; try exact ORD; eauto. i.\n  esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n    exploit Memory.add_ts; eauto.\n  - ss.\n  - inv LOCAL1. ss. econs; ss.\n    unfold TView.write_tview, TView.read_fence_tview. ss.\n    econs; ss; repeat (try condtac; aggrtac).\n    all: try by destruct ord_src, ord_tgt.\n    all: try by apply LC_WF1_TGT.\n    + etrans; [apply TVIEW|]. aggrtac.\n    + etrans; [apply TVIEW|]. aggrtac.\n    + etrans; [apply LC_WF1_SRC|].\n      etrans; [apply TVIEW|]. aggrtac.\n    + etrans; [apply TVIEW|]. aggrtac.\n  - econs; ss. apply GLOBAL1.\nQed.\n\nLemma sim_local_update_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      lc3_tgt gl3_tgt\n      loc ts1 val1 released1_tgt\n      to2 val2 released2_tgt ord2_src ord2_tgt\n      (STEP1_TGT: Local.read_step lc1_tgt gl1_tgt loc ts1 val1 released1_tgt Ordering.relaxed lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt gl1_tgt loc ts1 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt gl3_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (ORD2_TGT: Ordering.le ord2_tgt Ordering.strong_relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists released1_src released2_src lc2_src lc3_src gl3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src gl1_src loc ts1 val1 released1_src Ordering.acqrel lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src gl1_src loc ts1 to2 val2 released1_src released2_src ord2_src lc3_src gl3_src>> /\\\n    <<LOCAL3: sim_local lc3_src (local_acquired lc3_tgt)>> /\\\n    <<GLOBAL3: sim_global gl3_src gl3_tgt>>.\nProof.\n  exploit sim_local_read_acquired; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n  exploit sim_local_write_acquired; try exact STEP2_TGT; try exact LOCAL2; eauto.\n  { inv STEP1_TGT. inv STEP_SRC. ss.\n    do 2 (condtac; ss).\n    rewrite View.join_bot_r.\n    repeat apply View.join_le; try apply LOCAL1; try refl.\n    inv REL; ss. apply View.bot_spec.\n  }\n  i. des.\n  esplits; try exact STEP_SRC; try exact STEP_SRC0; eauto.\nQed.\n\nLemma sim_local_is_racy_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to\n      (STEP_TGT: Local.is_racy lc1_tgt gl1_tgt loc to Ordering.relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt):\n  <<STEP_SRC: Local.is_racy lc1_src gl1_src loc to Ordering.acqrel>>.\nProof.\n  exploit sim_local_is_racy; try exact STEP_TGT;\n    try exact LOCAL1; try exact GLOBAL1; try refl; eauto. i. des.\n  inv x0; eauto.\nQed.\n\nLemma sim_local_racy_read_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to val\n      (STEP_TGT: Local.racy_read_step lc1_tgt gl1_tgt loc to val Ordering.relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt):\n  <<STEP_SRC: Local.racy_read_step lc1_src gl1_src loc to val Ordering.acqrel>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy_acquired; eauto.\nQed.\n\nLemma sim_local_racy_update_acquired\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ow\n      (STEP_TGT: Local.racy_update_step lc1_tgt gl1_tgt loc to Ordering.relaxed ow)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src gl1_src loc to Ordering.acqrel ow>>.\nProof.\n  inv STEP_TGT; eauto.\n  exploit sim_local_is_racy_acquired; eauto.\nQed.\n\n\n(* released *)\n\nLemma sim_local_fulfill_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc prm2 gprm2\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (FULFILL_TGT: Promises.fulfill lc1_tgt.(Local.promises) gl1_tgt.(Global.promises) loc Ordering.strong_relaxed prm2 gprm2):\n  Promises.fulfill lc1_src.(Local.promises) gl1_src.(Global.promises) loc Ordering.acqrel prm2 gprm2.\nProof.\n  destruct lc1_src, lc1_tgt, gl1_src, gl1_tgt.\n  inv LOCAL1. inv GLOBAL1. ss. subst.\n  inv FULFILL_TGT; eauto.\nQed.\n\nLemma sim_local_write_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF_SRC: View.opt_wf releasedm_src)\n      (RELM_CLOSED_SRC: Memory.closed_opt_view releasedm_src (Global.memory gl1_src))\n      (RELM_WF_TGT: View.opt_wf releasedm_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt gl1_tgt loc from to val releasedm_tgt released_tgt Ordering.strong_relaxed lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (RELEASED1: View.le (TView.cur (Local.tview lc1_tgt))\n                          (View.join ((TView.rel (Local.tview lc1_tgt)) loc) (View.singleton_ur loc to))):\n  exists released_src lc2_src gl2_src,\n    <<STEP_SRC: Local.write_step lc1_src gl1_src loc from to val releasedm_src released_src Ordering.acqrel lc2_src gl2_src>> /\\\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (REL:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) loc to releasedm_src Ordering.acqrel)\n     (TView.write_released (Local.tview lc1_tgt) loc to releasedm_tgt Ordering.strong_relaxed)).\n  { unfold TView.write_released, TView.write_tview. ss. viewtac;\n      try econs; repeat (condtac; aggrtac); try apply LC_WF1_TGT.\n    rewrite <- View.join_r. etrans; eauto. apply LOCAL1.\n  }\n  assert (REL_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) loc to releasedm_src Ordering.acqrel)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply LC_WF1_SRC).\n  }\n  exploit sim_memory_add_exists; try exact WRITE; try apply GLOBAL1.\n  { econs 1. exact REL_WF. }\n  { econs; try exact REL; [refl|].\n    instantiate (1:=Ordering.le Ordering.acqrel Ordering.na).\n    refl.\n  }\n  i. des.\n  exploit sim_local_fulfill_released; try apply LOCAL1; eauto. i.\n  esplits.\n  - econs; eauto.\n    inv WRITABLE. econs; ss. eapply TimeFacts.le_lt_lt; [apply LOCAL1|apply TS].\n  - ss.\n  - inv LOCAL1. econs; eauto. ss.\n    unfold TView.write_tview, View.singleton_ur_if. repeat (condtac; aggrtac).\n    econs; repeat (condtac; aggrtac);\n      (try by etrans; [apply LOCAL1|aggrtac]);\n      (try by rewrite <- ? View.join_r; econs; aggrtac);\n      (try apply LC_WF1_TGT).\n    + ss. i. unfold LocFun.find. repeat (condtac; aggrtac).\n      * etrans; eauto. apply TVIEW.\n      * apply TVIEW.\n    + ss. aggrtac; try apply LC_WF1_TGT.\n      rewrite <- ? View.join_l. apply TVIEW.\n    + ss. aggrtac; try apply LC_WF1_TGT.\n      rewrite <- ? View.join_l. apply TVIEW.\n  - inv GLOBAL1. econs; ss.\nQed.\n\nLemma sim_local_update_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      lc3_tgt gl3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      to2 val2 released2_tgt\n      (STEP1_TGT: Local.read_step lc1_tgt gl1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt gl1_tgt loc ts1 to2 val2 released1_tgt released2_tgt Ordering.strong_relaxed lc3_tgt gl3_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD1_TGT: Ordering.le ord1_tgt Ordering.strong_relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (RELEASED1: View.le (TView.cur (Local.tview lc1_tgt)) ((TView.rel (Local.tview lc1_tgt)) loc)):\n  exists released1_src released2_src lc2_src lc3_src gl3_src,\n    <<STEP1_SRC: Local.read_step lc1_src gl1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src gl1_src loc ts1 to2 val2 released1_src released2_src Ordering.acqrel lc3_src gl3_src>> /\\\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<LOCAL3: sim_local lc3_src lc3_tgt>> /\\\n    <<GLOBAL3: sim_global gl3_src gl3_tgt>>.\nProof.\n  exploit sim_local_read; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n  exploit sim_local_write_released; try exact STEP2_TGT; eauto.\n  { inv STEP1_TGT. ss.\n    condtac; try by (destruct ord1_tgt; ss).\n    rewrite View.join_bot_r.\n    apply View.join_le; ss.\n    inv STEP2_TGT. exploit Memory.add_ts; eauto. i.\n    aggrtac. condtac; aggrtac.\n  }\n  i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_is_racy_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to\n      (STEP_TGT: Local.is_racy lc1_tgt gl1_tgt loc to Ordering.strong_relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  <<STEP_SRC: Local.is_racy lc1_src gl1_src loc to Ordering.acqrel>>.\nProof.\n  exploit sim_local_is_racy;\n    try exact LOCAL1; try exact GLOBAL1; try refl; eauto. i. des.\n  inv x0; eauto.\nQed.\n\nLemma sim_local_racy_write_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to\n      (STEP_TGT: Local.racy_write_step lc1_tgt gl1_tgt loc to Ordering.strong_relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  <<STEP_SRC: Local.racy_write_step lc1_src gl1_src loc to Ordering.acqrel>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy_released; eauto.\nQed.\n\nLemma sim_local_racy_update_released\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ordr\n      (STEP_TGT: Local.racy_update_step lc1_tgt gl1_tgt loc to ordr Ordering.strong_relaxed)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src gl1_src loc to ordr Ordering.acqrel>>.\nProof.\n  exploit sim_local_racy_update;\n    try exact LOCAL1; try exact GLOBAL1; try refl; eauto. i. des.\n  inv x0.\n  - econs 1; eauto.\n  - econs 2; eauto.\n  - econs 3; eauto.\nQed.\n\n\n(** acqrel *)\n\nDefinition local_acqrel (lc:Local.t) :=\n  (Local.mk (TView.write_fence_tview\n               (TView.read_fence_tview (Local.tview lc) Ordering.acqrel)\n               TimeMap.bot\n               Ordering.acqrel)\n            (Local.promises lc)\n            (Local.reserves lc)).\n\nLemma local_acqrel_wf\n      lc gl\n      (WF: Local.wf lc gl):\n  Local.wf (local_acqrel lc) gl.\nProof.\n  inv WF. econs; ss.\n  - inv TVIEW_WF. econs; ss; repeat (condtac; ss).\n    + rewrite View.join_bot_r. apply ACQ.\n    + refl.\n    + rewrite View.join_bot_r. refl.\n  - inv TVIEW_CLOSED.\n    econs; ss. condtac; ss.\n    rewrite View.join_bot_r. apply ACQ.\nQed.\n\nLemma sim_local_internal_acqrel\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      e lc2_tgt gl2_tgt\n      (STEP_TGT: Local.internal_step e lc1_tgt gl1_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_acqrel lc1_tgt))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.internal_step e lc1_src gl1_src lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  exploit local_acqrel_wf; try exact LC_WF1_TGT. i.\n  exploit sim_local_internal; try exact LOCAL1; eauto.\n  destruct lc1_tgt.\n  inv STEP_TGT; inv LOCAL; ss; eauto.\nQed.\n\nLemma sim_local_write_acqrel\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF_SRC: View.opt_wf releasedm_src)\n      (RELM_CLOSED_SRC: Memory.closed_opt_view releasedm_src (Global.memory gl1_src))\n      (RELM_WF_TGT: View.opt_wf releasedm_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 gl1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists released_src lc2_src gl2_src,\n    <<STEP_SRC: Local.write_step lc1_src gl1_src loc from to val releasedm_src released_src ord_src lc2_src gl2_src>> /\\\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (REL:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) loc to releasedm_tgt ord_tgt)).\n  { 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 LC_WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply LC_WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (REL_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply LC_WF1_SRC).\n  }\n  exploit sim_memory_add_exists; try exact WRITE; try apply GLOBAL1.\n  { econs 1. exact REL_WF. }\n  { econs; try exact REL; try refl.\n    apply ord_implb. eassumption.\n  }\n  i. des.\n  exploit sim_local_fulfill; try apply LOCAL1; try exact ORD; eauto. i.\n  exploit Memory.add_ts; eauto. i.\n  esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n  - ss.\n  - inv LOCAL1. ss. econs; ss.\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 LC_WF1_TGT.\n    + etrans; [apply TVIEW|]. repeat (try condtac; aggrtac).\n    + etrans; [apply TVIEW|]. aggrtac.\n      etrans; [apply LC_WF1_TGT|].\n      etrans; [apply LC_WF1_TGT|]. aggrtac.\n    + etrans; [apply TVIEW|]. aggrtac.\n      etrans; [apply LC_WF1_TGT|].\n      etrans; [apply LC_WF1_TGT|]. aggrtac.\n    + etrans; [apply TVIEW|]. repeat (try condtac; aggrtac).\n      etrans; [apply LC_WF1_TGT|].\n      etrans; [apply LC_WF1_TGT|]. aggrtac.\n    + etrans; [apply TVIEW|]. ss. condtac; aggrtac.\n    + etrans; [apply TVIEW|]. aggrtac.\n  - inv GLOBAL1. ss.\nQed.\n\nLemma sim_local_update_acqrel\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      lc3_tgt gl3_tgt\n      loc ts1 val1 released1_tgt\n      to2 val2 released2_tgt ord2_src ord2_tgt\n      (STEP1_TGT: Local.read_step lc1_tgt gl1_tgt loc ts1 val1 released1_tgt Ordering.relaxed lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt gl1_tgt loc ts1 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt gl3_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (ORD2_TGT: Ordering.le ord2_tgt Ordering.acqrel)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt):\n  exists released1_src released2_src lc2_src lc3_src gl3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src gl1_src loc ts1 val1 released1_src Ordering.acqrel lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src gl1_src loc ts1 to2 val2 released1_src released2_src ord2_src lc3_src gl3_src>> /\\\n    <<LOCAL3: sim_local lc3_src (local_acqrel lc3_tgt)>> /\\\n    <<GLOBAL3: sim_global gl3_src gl3_tgt>>.\nProof.\n  exploit sim_local_read_acquired; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n  exploit sim_local_write_acqrel; try exact STEP2_TGT; try exact LOCAL2; eauto.\n  { inv STEP1_TGT. inv STEP_SRC. ss.\n    do 2 (condtac; ss).\n    rewrite View.join_bot_r.\n    repeat apply View.join_le; try apply LOCAL1; try refl.\n    inv REL; ss. apply View.bot_spec.\n  }\n  i. des.\n  esplits; try exact STEP_SRC; try exact STEP_SRC0; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/SimLocalAdvance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.17563827792496084}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\nRequire Import VST.zlist.sublist.\n\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.general_lemmas.\nRequire Import sha.spec_sha.\n\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_pure_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import VST.floyd.library.\n\nRequire Import hmacdrbg.verif_hmac_drbg_seed_common.\n\nModule Instantiate_eq.\n\nDefinition OptionalNonce: option (list byte) := None. (*The implementation takes nonce from entropy, using the el*3/2 calculation*)\n\n(*NIST, Section 10.1: highest supported sec strength is given by the hash function's\nsecurity strength for preimage resistance. For SHA256, this is\n(according to NIST SP 800-107, Table 1, page 11) 256 bits. See also Appendix B2 of NIST SP 800-90A. *)\nDefinition highest_supported_security_strength := 32. (* in bytes -- see comment for reseed*)\n\n(*Q: should we use the sec strength of HMAC, calculated according to Section 5.3.4 of\nNIST SP 800-107 instead?*)\nDefinition requested_security_strength:= 32.  (*same as in reseed*)\n\n\nDefinition prediction_resistance_supported:bool:=true.\n\nDefinition mbedtls_HMAC256_DRBG_instantiate_function (entropy_stream: ENTROPY.stream)\n         entropy_len pr_flag (personalization_string: list byte): ENTROPY.result DRBG_state_handle :=\n    HMAC256_DRBG_instantiate_function entropy_len entropy_len OptionalNonce\n            highest_supported_security_strength max_personalization_string_length\n            prediction_resistance_supported entropy_stream\n            requested_security_strength pr_flag personalization_string.\n\nDefinition entlen:Z := 32.\n\n\nParameter Entropy_addSuccess1: forall n m s s1 l1 s2 l2,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.success l2 s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.success (l1++l2) s2.\n\nParameter Entropy_addSuccess2: forall n m s s1 l1 s2 e,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.error e s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s2.\n\nParameter Entropy_addError: forall n m s s1 e, ENTROPY.get_bytes n s = ENTROPY.error e s1 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s1.\n\nLemma Entropy_le n s l ss: ENTROPY.success l ss = ENTROPY.get_bytes n s ->\n  forall m, (m <= n)%nat -> exists l' s', ENTROPY.success l' s' = ENTROPY.get_bytes m s.\nProof. intros.\n  remember (ENTROPY.get_bytes m s) as d.\n  destruct d. eexists; eexists; trivial.\n  symmetry in H; symmetry in Heqd.\n  specialize (Entropy_addError _ (n-m)%nat _ _ _ Heqd).\n     rewrite Nat.add_comm, Nat.sub_add; trivial.\n  intros HH; rewrite HH in *. discriminate.\nQed.\n\nLemma Entropy_addSuccess3: forall n m s ss l,\n        ENTROPY.get_bytes n s = ENTROPY.success l ss -> (m <= n)%nat ->\n        exists l1 s1, ENTROPY.get_bytes m s = ENTROPY.success l1 s1 /\\ \n        exists l2, ENTROPY.get_bytes (n-m)%nat s1 = ENTROPY.success l2 ss /\\ l=l1++l2.\nProof. intros.\n  remember (ENTROPY.get_bytes m s). destruct r.\n+ exists l0, s0; split; trivial.\n  symmetry in Heqr.\n  remember (ENTROPY.get_bytes (n-m)%nat s0) as t.\n  destruct t; symmetry in Heqt.\n  - specialize (Entropy_addSuccess1 m (n-m)%nat s s0). rewrite Heqr, Heqt, Nat.add_comm, Nat.sub_add; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H. exists l1; split; trivial.\n  - specialize (Entropy_addSuccess2 m (n-m)%nat s s0). rewrite Heqr, Heqt, Nat.add_comm, Nat.sub_add; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H.\n+ symmetry in Heqr; exfalso. \n  specialize (Entropy_addError m (n-m)%nat s). rewrite Heqr, Nat.add_comm, Nat.sub_add; trivial.\n  intros X. rewrite (X _ _ (eq_refl _)) in H. inv H.\nQed.\n\nLemma instantiate_eq es prflag pers:\n      instantiate_function_256 es prflag pers =\n      mbedtls_HMAC256_DRBG_instantiate_function es entlen prflag pers.\nProof. unfold instantiate_function_256, mbedtls_HMAC256_DRBG_instantiate_function, \n   HMAC256_DRBG_instantiate_function, DRBG_instantiate_function, HMAC256_DRBG_instantiate_algorithm; simpl; intros.\ndestruct (Zlength pers >? max_personalization_string_length).\n+ destruct prflag; trivial.\n+ unfold entlen, get_entropy; simpl. \n  remember (ENTROPY.get_bytes 48 es) as r.\n  destruct r; symmetry in Heqr. \n  - destruct (Entropy_addSuccess3 _ 32 _ _ _ Heqr) as [l1 [s1 [E32 [l2 [E16 L]]]]]. lia.\n    simpl in E16. rewrite E32, E16; subst.\n    unfold HMAC_DRBG_instantiate_algorithm. simpl. rewrite app_assoc. destruct prflag; trivial.\n  - remember  (ENTROPY.get_bytes 32 es) as t; destruct t; symmetry in Heqt.\n    * remember (ENTROPY.get_bytes 16 s0) as w; destruct w; symmetry in Heqw.\n      ++ specialize (Entropy_addSuccess1 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr. congruence.\n      ++ specialize (Entropy_addSuccess2 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\n    * specialize (Entropy_addError _ 16 _ _ _ Heqt). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\nQed.\n\nLemma instantiate_reseed d s pr_flag rc ri (ZLc'256F : (Zlength d >? 256) = false):\n      mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag  d =\n      mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs initial_key initial_value rc 48 pr_flag ri) d.\nProof. rewrite <- instantiate256_reseed, instantiate_eq; trivial. Qed.\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque initial_key. Opaque initial_value.\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque repeat. \n\n(*specification for the expected case, in which 0<=len<=256.\n  But use mbedtls_HMAC256_DRBG_instantiate_function PROP of PRE and assume SUCCESS*)\nDefinition hmac_drbg_seed_simple_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z,\n        handle_ss: DRBG_state_handle * ENTROPY.stream, gv: globals\n    PRE [(*_ctx OF*) tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         (*_md_info OF*) tptr (Tstruct _mbedtls_md_info_t noattr),\n         (*_custom OF*) tptr tuchar, (*_len OF*) tuint ]\n       PROP (len = Zlength Data /\\ 0 <= len <=256 /\\\n             mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n             = ENTROPY.success (fst handle_ss) (snd handle_ss))\n       (*LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvars gv)*)\n       PARAMS (ctx; info; data; Vint (Int.repr len)) GLOBALS (gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val,\n                 match (fst Ctx, fst handle_ss) with ((M1, (M2, M3)), ((((newV, newK), newRC), newEL), newPR))\n                   => let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (bool2val newPR, Vint (Int.repr 10000)))))) in\n                      !!(ret_value = Int.zero) \n                      && data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                         hmac256drbg_relate (HMAC256DRBGabs newK newV newRC 32 newPR 10000) CtxFinal *\n                         Stream (snd handle_ss) \n                end;\n            mem_mgr gv).\n\nLemma body_hmac_drbg_seed_simple: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_simple_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 RES]]. destruct handle_ss as [handle ss]. simpl in RES.\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n\n  Intros v. rename H into Hv.\n  forward.\n  forward_if.\n  { destruct Hv; try lia. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros. Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!.\n  forward_call (info).\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, initial_key, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { split; auto; computable. }\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n  my_auto.\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { discriminate. }\n  { clear H.\n    forward_if.\n    + discriminate. \n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl; auto.\n(*    all: rewrite Int.unsigned_repr by rep_lia; reflexivity.  for Coq 8.13 and before *)\n  }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (repeat Int.one 32), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (bool2val pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;3;4;5;9] FR_CTX.\n  freeze [1;7;8;9] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    simpl. entailer!.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split. computable. split. rep_lia. (* rewrite int_max_unsigned_eq; lia.*)\n     unfold contents_with_add. simple_if_tac. rep_lia. rewrite Zlength_nil; rep_lia.\n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. simple_if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + lia.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try lia.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; lia. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite RES in HeqMRS. inv HeqMRS. \n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST. \n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros. inv H.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. lia. }\n  rewrite <- instantiate_reseed, RES in HeqMRS; trivial. subst MRS. clear H RES Heqd. \n  destruct handle as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  thaw ALLSEP. thaw OLD_MD. Exists p. \n  cancel;  normalize. \n  apply andp_right. solve [apply prop_right; repeat split; trivial].\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty.\nTime Qed. (*Coq8.6: 26secs*)\n\n(*Spec that does not assume len<=256 and includes a clause \n  for the case where mbedtls_HMAC256_DRBG_instantiate_function yields\n  Entropy.ERROR, ie no hypothesis about mbedtls_HMAC256_DRBG_instantiate_function in PROP of PRE*)\nDefinition hmac_drbg_seed_full_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z, gv: globals\n    PRE [(*_ctx OF*) tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         (*_md_info OF*) tptr (Tstruct _mbedtls_md_info_t noattr),\n         (*_custom OF*) tptr tuchar, (*_len OF*) tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus)\n       PARAMS (ctx; info; data; Vint (Int.repr len)) GLOBALS (gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val,\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 (48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (repeat (Vint Int.one) 32, (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (bool2val pr_flag, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else match mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n                        with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (repeat (Vint Int.one) 32, (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (bool2val pr_flag, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (bool2val newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end;\n             mem_mgr gv).\n\nLemma body_hmac_drbg_seed_full: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_full_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as (*[PREQ*) [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]](*]*).\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n  forward_if.\n  { destruct Hv; try lia. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros. Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!.\n  forward_call info.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n(*\n  replace_SEP 1 (UNDER_SPEC.EMPTY Ews p).\n  { entailer!. \n    eapply derives_trans. 2: apply UNDER_SPEC.mkEmpty.\n    fix_hmacdrbg_compspecs. apply derives_refl.\n  }\n*)\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, initial_key, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { split; my_auto. }\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  deadvars!.\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { discriminate. }\n  { clear H.\n    forward_if.\n    + discriminate.\n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl; auto.\n(*    all: rewrite Int.unsigned_repr by rep_lia; reflexivity.  for Coq 8.13 and before *)\n  }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (repeat Int.one 32), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (bool2val pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;3;4;5;9] FR_CTX.\n  freeze [1;7;8;9] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    simpl; entailer!.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. computable. \n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. simple_if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. normalize. cancel. simpl. \n      Exists p. thaw OLD_MD. normalize.\n      apply andp_right. apply prop_right; repeat split; trivial. cancel.\n      apply hmac_interp_empty.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try lia.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc';  lia. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite <- HeqMRS. \n        normalize.\n        apply andp_right. apply prop_right; repeat split; trivial.\n        cancel. apply hmac_interp_empty.\n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros. inv H.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  unfold return_value_relate_result in H.\n  destruct MRS. 2:{ exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  }\n  clear H.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate. simpl in *. rewrite Heqd2.\n  thaw ALLSEP. thaw OLD_MD. Exists p. cancel.\n  normalize.\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. lia. }\n  rewrite <- instantiate_reseed in HeqMRS; trivial.\n  rewrite <- HeqMRS.\n  normalize.\n  apply andp_right. apply prop_right; repeat split; trivial.\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty. \nTime Qed. (*Coq8.6: 32secs*)\n   (*Feb 22nd 2017: 245.406 secs (233.843u,0.203s) (successful)*)\n   (*earlier: 69.671 secs (59.578u,0.015s) (successful)*)\n\nEnd Instantiate_eq.\n\nLemma ReseedRes: forall X r v, @return_value_relate_result X r (Vint v) -> Int.eq v (Int.repr (-20864)) = false.\nProof. intros.\n  unfold return_value_relate_result in H.\n  destruct r. inv H; reflexivity.\n  destruct e; inv H; try reflexivity.\n  apply Int.eq_false. eapply ENT_GenErrAx.\nQed.\n\nDefinition preseed_relate V rc pr ri (r : hmac256drbgstate):mpred:=\n    match r with\n     (md_ctx', (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))) =>\n    md_empty md_ctx' &&\n    !! (map Vubyte V = V' /\\\n        Zlength V = 32 /\\\n        Vint (Int.repr rc) = reseed_counter'(* /\\\n        Vint (Int.repr entropy_len) = entropy_len'*) /\\\n        Vint (Int.repr ri) = reseed_interval' /\\\n        bool2val pr = prediction_resistance')\n   end.\n\nDefinition hmac_drbg_seed_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH ctx: val, info:val, len: Z, data:val, Data: list byte,\n        Ctx: hmac256drbgstate,\n        (*CTX: hmac256drbgabs,*)\n        Info: md_info_state, s:ENTROPY.stream, rc:Z, pr:bool, ri:Z, VV:list byte, gv: globals\n    PRE [(*_ctx OF*) tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         (*_md_info OF*) tptr (Tstruct _mbedtls_md_info_t noattr),\n         (*_custom OF*) tptr tuchar, (*_len OF*) tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len (*<= 336 Int.max_unsigned*) /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus)\n       (*LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvars gv)*)\n       PARAMS (ctx; info; data; Vint (Int.repr len)) GLOBALS (gv)\n       SEP (\n         data_at Ews t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate VV rc pr ri Ctx;\n         (*hmac256drbg_relate CTX Ctx;*)\n         data_at Ews t_struct_mbedtls_md_info Info info;\n         da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n         K_vector gv; Stream s; mem_mgr gv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Ews t_struct_mbedtls_md_info Info info;\n            da_emp Ews (tarray tuchar (Zlength Data)) (map Vubyte Data) data;\n            K_vector gv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Ews t_struct_hmac256drbg_context_st Ctx ctx *\n                  (*hmac256drbg_relate CTX Ctx *) preseed_relate VV rc pr ri Ctx *\n                  Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val, (* malloc_token Tsh (Tstruct _hmac_ctx_st noattr) p * *)\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 ((*hmac256drbgabs_entropy_len initial_state_abs*)48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (repeat (Vint Int.one) 32, (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (bool2val pr, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs VV (repeat Byte.one 32) rc 48 pr 10000 in\n                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else let myABS := HMAC256DRBGabs VV (repeat Byte.one 32) rc 48 pr 10000\n                      in match mbedtls_HMAC256_DRBG_reseed_function s myABS\n                                (contents_with_add data (Zlength Data) Data)\n                         with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (repeat (Vint Int.one) 32, (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (bool2val pr, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs VV (repeat Byte.one 32) rc 48 pr 10000 in\n                                       data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vubyte newV, (Vint (Int.repr newRC), (Vint (Int.repr 32), (bool2val newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Ews t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end;\n         mem_mgr gv).\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\n\nLemma body_hmac_drbg_seed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]].\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Ews, Vint (Int.repr 1), info, gv).\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n\n  forward_if.\n  { destruct Hv; try lia. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; auto. }\n  subst v. clear Hv. simpl.\n  Intros p.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!. \n  forward_call info.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  rename H1 into ZL_VV.\n  thaw FIELDS.\n  freeze [2;4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;4;5;6;8] FR2.\n  forward_call (Vptr b i, Ews, ((info,(M2,p)):mdstate), 32, VV, b, Ptrofs.add i (Ptrofs.repr 12), Ews, gv).\n  { entailer!. simpl. rewrite ZL_VV, ptrofs_add_repr_0_r; trivial. \n  }\n  { split; auto. computable. }\n  Intros.\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Ews, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite ZL_VV; entailer!.\n  }\n  { rewrite sepcon_comm. apply sepcon_derives.\n      eapply derives_trans. apply data_at_memory_block.\n        rewrite ZL_VV. simpl. cancel. cancel. }\n  (*{ split. apply semax_call.writable_share_top.\n    rewrite ZL_V0, client_lemmas.int_max_unsigned_eq. lia. }*)\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Ews t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n(*  set (ent_len := new_ent_len (Zlength V0)) in *.*)\n\n  forward_if (temp _t'4 (Vint (Int.repr 32))).\n  { discriminate. }\n  { clear H.\n    forward_if.\n    { discriminate. }\n    { clear H. forward. forward. entailer!. }\n  }\n  forward. simpl. drop_LOCAL 1%nat. (*_t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl; auto.\n(*    all: rewrite Int.unsigned_repr by rep_lia; reflexivity.  for Coq 8.13 and before *)\n  }\n\n  set (myABS := HMAC256DRBGabs VV (repeat Byte.one 32) rc 48 pr 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (repeat Int.one 32), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (bool2val pr, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze FR_CTX := (data_at _ _ _ (Vptr b (Ptrofs.add i (Ptrofs.repr 12))))\n         (field_at _ _ [StructField _reseed_counter] _ (Vptr b i))\n         (field_at _ _ [StructField _entropy_len] _ (Vptr b i))\n         (UNDER_SPEC.REP _ _ p)\n         (malloc_token _ _ p).\n  freeze KVStreamInfoDataFreeBlk :=\n      (K_vector gv) \n      (data_at _ _ _ info)\n      (da_emp _ _ _ data)\n      (Stream s).\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;3;4;5] INI.\n  replace_SEP 0 (\n         data_at Ews t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { go_lower. thaw INI. clear KVStreamInfoDataFreeBlk. thaw FR_CTX.\n    unfold_data_at 2%nat.\n    subst ST; simpl. cancel. normalize.\n    apply andp_right. apply prop_right. repeat split; trivial.\n    unfold md_full. simpl.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [6] OLD_MD.\n  forward_call (Data, data, Ews, Zlength Data, Vptr b i, Ews, ST, myABS, Info, s, gv).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. computable.  }\n\n  Intros v.\n\n  forward.\n  forward_if (v = nullval).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST. (*rename H into Mcompat.*)\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. Intros. subst v; simpl. cancel.\n      Exists p. thaw OLD_MD. cancel. \n      apply andp_right; [ apply prop_right; trivial |  cancel; entailer!]. \n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try lia.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros. cancel. \n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n                                                     (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer; simpl.\n        Intros. Exists p. thaw OLD_MD. cancel.\n        apply andp_right. apply prop_right; trivial.\n        cancel. entailer!.\n  }\n  { rename H into Hv. forward. simpl in Hv. entailer!.\n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv. subst v; trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros. inv H.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold return_value_relate_result in H.\n  destruct MRS. 2:{ exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  }\n  clear H. unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11] XX.\n  forward. forward. \n  Exists Int.zero. simpl. symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate.\n  apply andp_right. apply prop_right; split; trivial. \n  thaw XX. thaw OLD_MD. cancel. simpl in *.\n  rewrite Heqd2. (* rewrite <- HeqMRS. *)\n  Exists p. \n  apply andp_right. apply prop_right; trivial.\n  unfold_data_at 1%nat. cancel. entailer!.\nTime Qed. (*Coq8.6: 40secs*)\n          (*Jan 22nd 2017: 267.171 secs (182.812u,0.015s) (successful)*)\n          (*earlier: Finished transaction in 121.296 secs (70.921u,0.062s) (successful)*)\n          (*Coq8.9, April 2019: 8.3s*)\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_NISTseed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.17563827099538495}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext uniq_tac.\nRequire Import machine_int multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_tactics mips_syntax mips_mint mips_frame.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\n\nRequire Import multi_negate_prg multi_negate_triple.\n\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope simu_scope.\n\n(** x <- - x, x signed *)\n\nLemma pfwd_sim_multi_negate (x : bipl.var.v) d k rx a0 :\n  uniq(rx, a0, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: nil) ->\n  x \\notin assoc.dom d ->\n  signed k rx \\notin assoc.cdom d ->\n  (x <- .--e (var_e x))%pseudo_expr%pseudo_cmd\n    <=p( state_mint (x |=> signed k rx \\U+ d), fun _ _ _ => 0 < Z_of_nat k < 2 ^^ 31 )\n  multi_negate rx a0.\nProof.\nmove=> Hset Hdisj x_d rx_d.\nrewrite /pfwd_sim.\nmove=> s st h [s_st_h k_231] s' exec_pseudo st' h' exec_asm.\n\nmove: (proj1 s_st_h x (signed k rx)).\nrewrite assoc.get_union_sing_eq.\ncase/(_ (refl_equal _)) => slen ptr A rx_fit encoding ptr_fit memA.\n\nmove: (multi_negate_triple rx a0 slen ptr A Hset) => hoare_triple.\n\nhave [st'' [h'' exec_triple_proj]] : exists st'' h'',\n  (Some (st, heap.proj h (heap.dom (heap_mint (signed k rx) st h))) --\n  multi_negate rx a0 ---> Some (st'', h''))%asm_cmd.\n  exists st', (heap.proj h' (heap.dom (heap_mint (signed k rx) st h))).\n  apply: (mips_syntax.triple_exec_proj _ _ _ hoare_triple) => //.\n  move: (heap_inclu_heap_mint_signed h st k rx).\n  move/heap.incluE => ->; exact memA.\n\nset postcond := (_ |--> cplt2 _ :: _ ** _)%asm_assert in hoare_triple.\n\nhave {hoare_triple}hoare_triple_postcond : (postcond ** assert_m.TT)%asm_assert st' h'.\n  move: {hoare_triple}(frame_rule_R _ _ _ hoare_triple assert_m.TT (assert_m.inde_TT _) (mips_frame.inde_cmd_mult_TT _)).\n  move/mips_seplog.hoare_prop_m.soundness.\n  rewrite /while.hoare_semantics.\n  move/(_ st h) => Hhoare_triple.\n  lapply Hhoare_triple; last first.\n    exists (heap_mint (signed k rx) st h), (h \\D\\ heap.dom (heap_mint (signed k rx) st h)).\n    split; first exact/heap.disj_difs'/inc_refl.\n    split; last by [].\n    apply heap.union_difsK; last by [].\n    exact: heap_inclu_heap_mint_signed.\n  case=> _.\n  by move/(_ _ _ exec_asm).\nhave rx_st_st' : ([rx ]_ st = [rx]_st')%asm_expr.\n  Reg_unchanged. rewrite [modified_regs _]/=. by Uniq_not_In.\nrewrite /state_mint; split.\n- move=> z mz.\n  case/assoc.get_union_Some_inv => [z_is_x | z_in_y_or_d].\n  + case/assoc.get_sing_inv : z_is_x => ? ?; subst z mz.\n    have not_weird_slen : ~ weird slen.\n      rewrite weirdE2.\n      case: encoding => H1 -> H3 H4.\n      move=> abs.\n      have : sgZ (s2Z slen) = -1.\n        case: (Zsgn_spec (s2Z slen)).\n          case=> _ abs'.\n          rewrite abs' in abs.\n          lia.\n        case.\n          case=> abs'.\n          by rewrite -abs' /= in abs.\n        by case.\n      move=> abs'.\n      rewrite abs' mulN1Z in abs.\n      apply Z.opp_inj in abs.\n      rewrite abs in k_231.\n      by case: k_231 => _ /ltZZ.\n    apply mkVarSigned with (cplt2 slen) ptr A => //.\n    * by rewrite -rx_st_st'.\n    * move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n      case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n      syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n      case: encoding => H1 H2 H3 H4.\n      apply mkSignMagn => //.\n      rewrite s2Z_cplt2 // H2 Zsgn_Zopp Zsgn_Zmult ZsgnK.\n      suff : sgZ (Z_of_nat k) = 1 by move=> ->; rewrite mulZ1; ring.\n      case: k_231 => k_231 _.\n      by apply Zsgn_pos in k_231.\n      by rewrite Zsgn_Zopp s2Z_cplt2 // Zsgn_Zopp H3.\n      rewrite s2Z_cplt2 // Zsgn_Zopp H4; ring.\n    * case: hoare_triple_postcond => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\n      apply con_heap_mint_signed_cons with h1 => //.\n      - rewrite h1Uh2.\n        apply heap.inclu_union_L => //.\n        by apply heap.inclu_refl.\n      - by rewrite -rx_st_st'.\n      - case: encoding => H1 H2 H3 H4.\n        by rewrite H1.\n      - by case: encoding.\n  + (* z \\in d *) have z_x : z <> x.\n      move=> ?; subst z.\n      apply assoc.get_Some_in in z_in_y_or_d.\n      rewrite -assoc.elts_dom in x_d.\n      move/negP : x_d; apply.\n      apply/mapP.\n      by exists (x, mz).\n    move: (proj2 s_st_h _ _ z_x mz (signed k rx)).\n    rewrite assoc.get_union_sing_neq; last by [].\n    rewrite assoc.get_union_sing_eq.\n    move/(_ z_in_y_or_d (refl_equal _)) => heap_mint_disj.\n    move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_triple_proj) => [st'_st'' [h''_h' h_h']].\n    have Hd_unchanged : forall v r, assoc.get v d = Some r ->\n      disj (mint_regs r) (mips_frame.modified_regs (multi_negate rx a0)).\n      move=> v r Hvr; rewrite [mips_frame.modified_regs _]/=; Disj_remove_dup.\n      apply (disj_incl_LR Hdisj); last by apply incl_refl_Permutation; PermutProve.\n      exact/incP/inc_mint_regs/(assoc.get_Some_in_cdom _ v).\n    have <- : heap_mint mz st h = heap_mint mz st' h'.\n      apply (heap_mint_state_invariant (heap_mint (signed k rx) st h) z s) => //.\n      move=> ry Hry; Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs mz)); last by [].\n      exact/disj_sym/(Hd_unchanged z).\n      move: (proj1 s_st_h z mz).\n      rewrite assoc.get_union_sing_neq; last by [].\n      exact.\n    apply var_mint_invariant with s st => //.\n    * move=> ry ry_my; Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs mz)); last by [].\n      exact/disj_sym/(Hd_unchanged z).\n    * Var_unchanged. rewrite /= mem_seq1; exact/negP/eqP.\n    * move: (proj1 s_st_h z mz).\n      rewrite assoc.get_union_sing_neq //; by apply.\n- have Hdom : heap.dom (heap_mint (signed k rx) st' h') = heap.dom (heap_mint (signed k rx) st h).\n    symmetry.\n    case: hoare_triple_postcond => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\n    rewrite /postcond in Hh1.\n    apply (dom_heap_mint_sign_state_invariant _ _ _ _ _ _ x s slen (cplt2 slen)) => //.\n      by move/assert_m.mapstos_get1/heap_get_heap_mint_inv : memA.\n    apply assert_m.mapstos_get1 in Hh1.\n    rewrite h1_U_h2. by apply heap.get_union_L => //.\n    apply assert_m.mapstos_get2 in memA.\n    apply assert_m.mapstos_get2 in Hh1.\n    rewrite h1_U_h2.\n    apply heap_get_heap_mint_inv in memA.\n    rewrite memA.\n    symmetry.\n    by apply heap.get_union_L.\n    apply mkVarSigned with slen ptr A => //.\n    by eapply dom_heap_invariant; eauto.\n  apply (state_mint_part2_one_variable _ _ _ _ _ _ _ _ s_st_h Hdom).\n  + move=> t x0 Ht Hx0.\n    Reg_unchanged. simpl mips_frame.modified_regs.\n    case/assoc.in_cdom_union_inv : Ht => Ht.\n    * rewrite assoc.cdom_sing /= seq.mem_seq1 in Ht.\n      move/eqP in Ht; subst t.\n      apply (@disj_not_In _ (mint_regs (signed k rx))); last by [].\n      Disj_remove_dup.\n      rewrite /=.\n      apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n    * apply (@disj_not_In _ (mint_regs t)); last by [].\n      Disj_remove_dup.\n      apply/disj_sym/(disj_incl_LR Hdisj); last by apply incl_refl_Permutation; PermutProve.\n      exact/incP/inc_mint_regs.\n  + move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_triple_proj); tauto.\n  + exact: (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_negate_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.17558265889646157}}
{"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(** Abstract syntax and semantics for the Csharpminor language. *)\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 Cminor.\nRequire Import Smallstep.\n\n(** Abstract syntax *)\n\n(** Csharpminor is a low-level imperative language structured in expressions,\n  statements, functions and programs.  Expressions include\n  reading global or local variables, reading store locations,\n  arithmetic operations, function calls, and conditional expressions\n  (similar to [e1 ? e2 : e3] in C). \n\n  Unlike in Cminor (the next intermediate language of the back-end),\n  Csharpminor local variables reside in memory, and their addresses can\n  be taken using [Eaddrof] expressions.\n*)\n\nInductive constant : Type :=\n  | Ointconst: int -> constant          (**r integer constant *)\n  | Ofloatconst: float -> constant.     (**r floating-point constant *)\n\nDefinition unary_operation : Type := Cminor.unary_operation.\nDefinition binary_operation : Type := Cminor.binary_operation.\n\nInductive expr : Type :=\n  | Evar : ident -> expr                (**r reading a scalar variable  *)\n  | Etempvar : ident -> expr            (**r reading a temporary variable *)\n  | Eaddrof : ident -> expr             (**r taking the address of a variable *)\n  | Econst : constant -> expr           (**r constants *)\n  | Eunop : unary_operation -> expr -> expr  (**r unary operation *)\n  | Ebinop : binary_operation -> expr -> expr -> expr (**r binary operation *)\n  | Eload : memory_chunk -> expr -> expr (**r memory read *)\n  | Econdition : expr -> expr -> expr -> expr. (**r conditional expression *)\n\n(** Statements include expression evaluation, variable assignment,\n  memory stores, function calls, an if/then/else conditional,\n  infinite loops, blocks and early block exits, and early function returns.\n  [Sexit n] terminates prematurely the execution of the [n+1] enclosing\n  [Sblock] statements. *)\n\nDefinition label := ident.\n\nInductive stmt : Type :=\n  | Sskip: stmt\n  | Sassign : ident -> expr -> stmt\n  | Sset : ident -> expr -> stmt\n  | Sstore : memory_chunk -> expr -> expr -> stmt\n  | Scall : option ident -> signature -> expr -> list expr -> stmt\n  | Sbuiltin : option ident -> external_function -> list 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  | Sswitch: expr -> lbl_stmt -> stmt\n  | Sreturn: option expr -> stmt\n  | Slabel: label -> stmt -> stmt\n  | Sgoto: label -> stmt\n\nwith lbl_stmt : Type :=\n  | LSdefault: stmt -> lbl_stmt\n  | LScase: int -> stmt -> lbl_stmt -> lbl_stmt.\n\n(** The variables can be either scalar variables\n  (whose type, size and signedness are given by a [memory_chunk]\n  or array variables (of the indicated sizes and alignment).\n  The only operation permitted on an array variable is taking its address. *)\n\nInductive var_kind : Type :=\n  | Vscalar(chunk: memory_chunk)\n  | Varray(sz al: Z).\n\nDefinition sizeof (lv: var_kind) : Z :=\n  match lv with\n  | Vscalar chunk => size_chunk chunk\n  | Varray sz al => Zmax 0 sz\n  end.\n\nDefinition type_of_kind (lv: var_kind) : typ :=\n  match lv with\n  | Vscalar chunk => type_of_chunk chunk\n  | Varray _ _ => Tint\n  end.\n\n(** Functions are composed of a return type, a list of parameter names\n  with associated [var_kind] descriptions, a list of\n  local variables with associated [var_kind] descriptions, and a\n  statement representing the function body.  *)\n\nDefinition variable_name (v: ident * var_kind) := fst v.\nDefinition variable_kind (v: ident * var_kind) := snd v.\n\nRecord function : Type := mkfunction {\n  fn_return: option typ;\n  fn_params: list (ident * var_kind);\n  fn_vars: list (ident * var_kind);\n  fn_temps: list ident;\n  fn_body: stmt\n}.\n\nDefinition fundef := AST.fundef function.\n\nDefinition program : Type := AST.program fundef var_kind.\n\nDefinition fn_sig (f: function) :=\n  mksignature (List.map type_of_kind (List.map variable_kind f.(fn_params)))\n              f.(fn_return).\n\nDefinition funsig (fd: fundef) :=\n  match fd with\n  | Internal f => fn_sig f\n  | External ef => ef_sig ef\n  end.\n\nDefinition fn_variables (f: function) := f.(fn_params) ++ f.(fn_vars).\n\nDefinition fn_params_names (f: function) := List.map variable_name f.(fn_params).\nDefinition fn_vars_names (f: function) := List.map variable_name f.(fn_vars).\n\n(** * Operational semantics *)\n\n(** Three evaluation environments are involved:\n- [genv]: global environments, map symbols and functions to memory blocks,\n    and maps symbols to variable informations (type [var_kind])\n- [env]: local environments, map local variables \n    to pairs (memory block, variable information)\n- [temp_env]: local environments, map temporary variables to\n    their current values.\n*)\n\nDefinition genv := Genv.t fundef var_kind.\nDefinition env := PTree.t (block * var_kind).\nDefinition temp_env := PTree.t val.\n\nDefinition empty_env : env := PTree.empty (block * var_kind).\nDefinition empty_temp_env : temp_env := PTree.empty val.\n\n(** Continuations *)\n\nInductive cont: Type :=\n  | Kstop: cont                         (**r stop program execution *)\n  | Kseq: stmt -> cont -> cont          (**r execute stmt, then cont *)\n  | Kblock: cont -> cont                (**r exit a block, then do cont *)\n  | Kcall: option ident -> function -> env -> temp_env -> cont -> cont.\n                                        (**r return to caller *)\n\n(** States *)\n\nInductive state: Type :=\n  | State:                      (**r Execution within a function *)\n      forall (f: function)              (**r currently executing function  *)\n             (s: stmt)                  (**r statement under consideration *)\n             (k: cont)                  (**r its continuation -- what to do next *)\n             (e: env)                   (**r current local environment *)\n             (le: temp_env)             (**r current temporary environment *)\n             (m: mem),                  (**r current memory state *)\n      state\n  | Callstate:                  (**r Invocation of a function *)\n      forall (f: fundef)                (**r function to invoke *)\n             (args: list val)           (**r arguments provided by caller *)\n             (k: cont)                  (**r what to do next  *)\n             (m: mem),                  (**r memory state *)\n      state\n  | Returnstate:                (**r Return from a function *)\n      forall (v: val)                   (**r Return value *)\n             (k: cont)                  (**r what to do next *)\n             (m: mem),                  (**r memory state *)\n      state.\n\n(** Pop continuation until a call or stop *)\n\nFixpoint call_cont (k: cont) : cont :=\n  match k with\n  | Kseq s k => call_cont k\n  | Kblock k => call_cont k\n  | _ => k\n  end.\n\nDefinition is_call_cont (k: cont) : Prop :=\n  match k with\n  | Kstop => True\n  | Kcall _ _ _ _ _ => True\n  | _ => False\n  end.\n\n(** Resolve [switch] statements. *)\n\nFixpoint select_switch (n: int) (sl: lbl_stmt) {struct sl} : lbl_stmt :=\n  match sl with\n  | LSdefault _ => sl\n  | LScase c s sl' => if Int.eq c n then sl else select_switch n sl'\n  end.\n\nFixpoint seq_of_lbl_stmt (sl: lbl_stmt) : stmt :=\n  match sl with\n  | LSdefault s => s\n  | LScase c s sl' => Sseq s (seq_of_lbl_stmt sl')\n  end.\n\n(** Find the statement and manufacture the continuation \n  corresponding to a label *)\n\nFixpoint find_label (lbl: label) (s: stmt) (k: cont) \n                    {struct s}: option (stmt * cont) :=\n  match s with\n  | Sseq s1 s2 =>\n      match find_label lbl s1 (Kseq s2 k) with\n      | Some sk => Some sk\n      | None => find_label lbl s2 k\n      end\n  | Sifthenelse a s1 s2 =>\n      match find_label lbl s1 k with\n      | Some sk => Some sk\n      | None => find_label lbl s2 k\n      end\n  | Sloop s1 =>\n      find_label lbl s1 (Kseq (Sloop s1) k)\n  | Sblock s1 =>\n      find_label lbl s1 (Kblock k)\n  | Sswitch a sl =>\n      find_label_ls lbl sl k\n  | Slabel lbl' s' =>\n      if ident_eq lbl lbl' then Some(s', k) else find_label lbl s' k\n  | _ => None\n  end\n\nwith find_label_ls (lbl: label) (sl: lbl_stmt) (k: cont) \n                   {struct sl}: option (stmt * cont) :=\n  match sl with\n  | LSdefault s => find_label lbl s k\n  | LScase _ s sl' =>\n      match find_label lbl s (Kseq (seq_of_lbl_stmt sl') k) with\n      | Some sk => Some sk\n      | None => find_label_ls lbl sl' k\n      end\n  end.\n\n\n(** Evaluation of operator applications. *)\n\nDefinition eval_constant (cst: constant) : option val :=\n  match cst with\n  | Ointconst n => Some (Vint n)\n  | Ofloatconst n => Some (Vfloat n)\n  end.\n\nDefinition eval_unop := Cminor.eval_unop.\n\nDefinition eval_binop := Cminor.eval_binop.\n\n(** Allocation of local variables at function entry.  Each variable is\n  bound to the reference to a fresh block of the appropriate size. *)\n\nInductive alloc_variables: env -> mem ->\n                           list (ident * var_kind) ->\n                           env -> mem -> Prop :=\n  | alloc_variables_nil:\n      forall e m,\n      alloc_variables e m nil e m\n  | alloc_variables_cons:\n      forall e m id lv vars m1 b1 m2 e2,\n      Mem.alloc m 0 (sizeof lv) = (m1, b1) ->\n      alloc_variables (PTree.set id (b1, lv) e) m1 vars e2 m2 ->\n      alloc_variables e m ((id, lv) :: vars) e2 m2.\n\n(** List of blocks mentioned in an environment, with low and high bounds *)\n\nDefinition block_of_binding (id_b_lv: ident * (block * var_kind)) :=\n  match id_b_lv with (id, (b, lv)) => (b, 0, sizeof lv) end.\n\nDefinition blocks_of_env (e: env) : list (block * Z * Z) :=\n  List.map block_of_binding (PTree.elements e).\n\nSection RELSEM.\n\nVariable ge: genv.\n\n(** Initialization of local variables that are parameters.  The value\n  of the corresponding argument is stored into the memory block\n  bound to the parameter. *)\n\nDefinition val_normalized (v: val) (chunk: memory_chunk) : Prop :=\n  Val.load_result chunk v = v.\n\nInductive bind_parameters: env ->\n                           mem -> list (ident * var_kind) -> list val ->\n                           mem -> Prop :=\n  | bind_parameters_nil:\n      forall e m,\n      bind_parameters e m nil nil m\n  | bind_parameters_scalar:\n      forall e m id chunk params v1 vl b m1 m2,\n      PTree.get id e = Some (b, Vscalar chunk) ->\n      val_normalized v1 chunk ->\n      Mem.store chunk m b 0 v1 = Some m1 ->\n      bind_parameters e m1 params vl m2 ->\n      bind_parameters e m ((id, Vscalar chunk) :: params) (v1 :: vl) m2\n  | bind_parameters_array:\n      forall e m id sz al params v1 vl b m1 m2,\n      PTree.get id e = Some (b, Varray sz al) ->\n      extcall_memcpy_sem sz al\n                         ge (Vptr b Int.zero :: v1 :: nil) m E0 Vundef m1 ->\n      bind_parameters e m1 params vl m2 ->\n      bind_parameters e m ((id, Varray sz al) :: params) (v1 :: vl) m2.\n\n\n(* Evaluation of the address of a variable: \n   [eval_var_addr prg ge e id b] states that variable [id] \n   in environment [e] evaluates to block [b]. *)\n\nInductive eval_var_addr: env -> ident -> block -> Prop :=\n  | eval_var_addr_local:\n      forall e id b vi,\n      PTree.get id e = Some (b, vi) ->\n      eval_var_addr e id b\n  | eval_var_addr_global:\n      forall e id b,\n      PTree.get id e = None ->\n      Genv.find_symbol ge id = Some b ->\n      eval_var_addr e id b.\n\n(* Evaluation of a reference to a scalar variable:\n   [eval_var_ref prg ge e id b chunk] states\n   that variable [id] in environment [e] evaluates to block [b]\n   and is associated with the memory chunk [chunk]. *)\n\nInductive eval_var_ref: env -> ident -> block -> memory_chunk -> Prop :=\n  | eval_var_ref_local:\n      forall e id b chunk,\n      PTree.get id e = Some (b, Vscalar chunk) ->\n      eval_var_ref e id b chunk\n  | eval_var_ref_global:\n      forall e id b gv chunk,\n      PTree.get id e = None ->\n      Genv.find_symbol ge id = Some b ->\n      Genv.find_var_info ge b = Some gv ->\n      gvar_info gv = Vscalar chunk ->\n      eval_var_ref e id b chunk.\n\n(** Evaluation of an expression: [eval_expr prg e m a v] states\n  that expression [a], in initial memory state [m] and local\n  environment [e], evaluates to value [v]. *)\n\nSection EVAL_EXPR.\n\nVariable e: env.\nVariable le: temp_env.\nVariable m: mem.\n\nInductive eval_expr: expr -> val -> Prop :=\n  | eval_Evar: forall id b chunk v,\n      eval_var_ref e id b chunk ->\n      Mem.load chunk m b 0 = Some v ->\n      eval_expr (Evar id) v\n  | eval_Etempvar: forall id v,\n      le!id = Some v ->\n      eval_expr (Etempvar id) v\n  | eval_Eaddrof: forall id b,\n      eval_var_addr e id b ->\n      eval_expr (Eaddrof id) (Vptr b Int.zero)\n  | eval_Econst: forall cst v,\n      eval_constant cst = Some v ->\n      eval_expr (Econst cst) v\n  | eval_Eunop: forall op a1 v1 v,\n      eval_expr a1 v1 ->\n      eval_unop op v1 = Some v ->\n      eval_expr (Eunop op a1) v\n  | eval_Ebinop: forall op a1 a2 v1 v2 v,\n      eval_expr a1 v1 ->\n      eval_expr a2 v2 ->\n      eval_binop op v1 v2 m = Some v ->\n      eval_expr (Ebinop op a1 a2) v\n  | eval_Eload: forall chunk a v1 v,\n      eval_expr a v1 ->\n      Mem.loadv chunk m v1 = Some v ->\n      eval_expr (Eload chunk a) v\n  | eval_Econdition: forall a b c v1 vb1 v2,\n      eval_expr a v1 ->\n      Val.bool_of_val v1 vb1 ->\n      eval_expr (if vb1 then b else c) v2 ->\n      eval_expr (Econdition a b c) v2.\n\n(** Evaluation of a list of expressions:\n  [eval_exprlist prg e m al vl] states that the list [al] of\n  expressions evaluate to the list [vl] of values.  The other\n  parameters are as in [eval_expr]. *)\n\nInductive eval_exprlist: list expr -> list val -> Prop :=\n  | eval_Enil:\n      eval_exprlist nil nil\n  | eval_Econs: forall a1 al v1 vl,\n      eval_expr a1 v1 -> eval_exprlist al vl ->\n      eval_exprlist (a1 :: al) (v1 :: vl).\n\nEnd EVAL_EXPR.\n\n(** Execution of an assignment to a variable. *)\n\nInductive exec_assign: env -> mem -> ident -> val -> mem -> Prop :=\n  exec_assign_intro: forall e m id v b chunk m',\n    eval_var_ref e id b chunk ->\n    val_normalized v chunk ->\n    Mem.store chunk m b 0 v = Some m' ->\n    exec_assign e m id v m'.\n\n(** One step of execution *)\n\nInductive step: state -> trace -> state -> Prop :=\n\n  | step_skip_seq: forall f s k e le m,\n      step (State f Sskip (Kseq s k) e le m)\n        E0 (State f s k e le m)\n  | step_skip_block: forall f k e le m,\n      step (State f Sskip (Kblock k) e le m)\n        E0 (State f Sskip k e le m)\n  | step_skip_call: forall f k e le m m',\n      is_call_cont k ->\n      f.(fn_return) = None ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      step (State f Sskip k e le m)\n        E0 (Returnstate Vundef k m')\n\n  | step_assign: forall f id a k e le m m' v,\n      eval_expr e le m a v ->\n      exec_assign e m id v m' ->\n      step (State f (Sassign id a) k e le m)\n        E0 (State f Sskip k e le m')\n\n  | step_set: forall f id a k e le m v,\n      eval_expr e le m a v ->\n      step (State f (Sset id a) k e le m)\n        E0 (State f Sskip k e (PTree.set id v le) m)\n\n  | step_store: forall f chunk addr a k e le m vaddr v m',\n      eval_expr e le m addr vaddr ->\n      eval_expr e le m a v ->\n      Mem.storev chunk m vaddr v = Some m' ->\n      step (State f (Sstore chunk addr a) k e le m)\n        E0 (State f Sskip k e le m')\n\n  | step_call: forall f optid sig a bl k e le m vf vargs fd,\n      eval_expr e le m a vf ->\n      eval_exprlist e le m bl vargs ->\n      Genv.find_funct ge vf = Some fd ->\n      funsig fd = sig ->\n      step (State f (Scall optid sig a bl) k e le m)\n        E0 (Callstate fd vargs (Kcall optid f e le k) m)\n\n  | step_builtin: forall f optid ef bl k e le m vargs t vres m',\n      eval_exprlist e le m bl vargs ->\n      external_call ef ge vargs m t vres m' ->\n      step (State f (Sbuiltin optid ef bl) k e le m)\n         t (State f Sskip k e (Cminor.set_optvar optid vres le) m')\n\n  | step_seq: forall f s1 s2 k e le m,\n      step (State f (Sseq s1 s2) k e le m)\n        E0 (State f s1 (Kseq s2 k) e le m)\n\n  | step_ifthenelse: forall f a s1 s2 k e le m v b,\n      eval_expr e le m a v ->\n      Val.bool_of_val v b ->\n      step (State f (Sifthenelse a s1 s2) k e le m)\n        E0 (State f (if b then s1 else s2) k e le m)\n\n  | step_loop: forall f s k e le m,\n      step (State f (Sloop s) k e le m)\n        E0 (State f s (Kseq (Sloop s) k) e le m)\n\n  | step_block: forall f s k e le m,\n      step (State f (Sblock s) k e le m)\n        E0 (State f s (Kblock k) e le m)\n\n  | step_exit_seq: forall f n s k e le m,\n      step (State f (Sexit n) (Kseq s k) e le m)\n        E0 (State f (Sexit n) k e le m)\n  | step_exit_block_0: forall f k e le m,\n      step (State f (Sexit O) (Kblock k) e le m)\n        E0 (State f Sskip k e le m)\n  | step_exit_block_S: forall f n k e le m,\n      step (State f (Sexit (S n)) (Kblock k) e le m)\n        E0 (State f (Sexit n) k e le m)\n\n  | step_switch: forall f a cases k e le m n,\n      eval_expr e le m a (Vint n) ->\n      step (State f (Sswitch a cases) k e le m)\n        E0 (State f (seq_of_lbl_stmt (select_switch n cases)) k e le m)\n\n  | step_return_0: forall f k e le m m',\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      step (State f (Sreturn None) k e le m)\n        E0 (Returnstate Vundef (call_cont k) m')\n  | step_return_1: forall f a k e le m v m',\n      eval_expr e le m a v ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      step (State f (Sreturn (Some a)) k e le m)\n        E0 (Returnstate v (call_cont k) m')\n  | step_label: forall f lbl s k e le m,\n      step (State f (Slabel lbl s) k e le m)\n        E0 (State f s k e le m)\n\n  | step_goto: forall f lbl k e le m s' k',\n      find_label lbl f.(fn_body) (call_cont k) = Some(s', k') ->\n      step (State f (Sgoto lbl) k e le m)\n        E0 (State f s' k' e le m)\n\n  | step_internal_function: forall f vargs k m m1 m2 e,\n      list_norepet (fn_params_names f ++ fn_vars_names f) ->\n      alloc_variables empty_env m (fn_variables f) e m1 ->\n      bind_parameters e m1 f.(fn_params) vargs m2 ->\n      step (Callstate (Internal f) vargs k m)\n        E0 (State f f.(fn_body) k e empty_temp_env m2)\n\n  | step_external_function: forall ef vargs k m t vres m',\n      external_call ef ge vargs m t vres m' ->\n      step (Callstate (External ef) vargs k m)\n         t (Returnstate vres k m')        \n\n  | step_return: forall v optid f e le k m,\n      step (Returnstate v (Kcall optid f e le k) m)\n        E0 (State f Sskip k e (Cminor.set_optvar optid v le) m).\n\nEnd RELSEM.\n\n(** Execution of whole programs are described as sequences of transitions\n  from an initial state to a final state.  An initial state is a [Callstate]\n  corresponding to the invocation of the ``main'' function of the program\n  without arguments and with an empty continuation. *)\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b f m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      funsig f = mksignature nil (Some Tint) ->\n      initial_state p (Callstate f nil Kstop m0).\n\n(** A final state is a [Returnstate] with an empty continuation. *)\n\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall r m,\n      final_state (Returnstate (Vint r) Kstop m) r.\n\n(** Wrapping up these definitions in a small-step semantics. *)\n\nDefinition semantics (p: program) :=\n  Semantics step (initial_state p) final_state (Genv.globalenv p).\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/cfrontend/Csharpminor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.17540525341937896}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\n(** Definition of matching relation between Coq and C representation *)\nFrom bpf.comm Require Import LemmaInt State MemRegion Regs Flag ListAsArray rBPFMemType.\nFrom compcert Require Import Coqlib Integers Values AST Clight Memory Memtype.\n\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic.\nFrom Coq Require Import ZArith.\nOpen Scope Z_scope.\n\nGlobal Transparent Archi.ptr64.\n\nDefinition match_region_at_ofs (mr:memory_region) (state_blk mrs_blk ins_blk: block) (ofs : ptrofs) (m: mem)  : Prop :=\n  (exists vl,  Mem.loadv AST.Mint32 m (Vptr mrs_blk ofs) = Some (Vint vl) /\\ (start_addr mr) = Vint vl)    /\\ (**r start_addr mr = Vint vl*)\n    (exists vl,  Mem.loadv AST.Mint32 m (Vptr mrs_blk (Ptrofs.add ofs (Ptrofs.repr 4))) = Some (Vint vl) /\\ (block_size mr) = Vint vl) /\\ (**r block_size mr = Vint vl*)\n    (exists vl,  Mem.loadv AST.Mint32 m (Vptr mrs_blk (Ptrofs.add ofs (Ptrofs.repr 8))) = Some (Vint vl) /\\ correct_perm (block_perm mr)  vl) /\\ (**r block_perm mr = Vint vl*)\n    (exists b, Mem.loadv AST.Mptr  m (Vptr mrs_blk (Ptrofs.add ofs (Ptrofs.repr 12))) = Some (Vptr b Ptrofs.zero) /\\ (block_ptr mr) = Vptr b Ptrofs.zero /\\ (Mem.valid_block m b /\\ b <> state_blk /\\ b <> mrs_blk /\\ b <> ins_blk)).\n\n\n(*Definition size_of_region  :=  16. (* 4 * 32 bits *)*)\n(*\nFixpoint match_list_region (m:mem) (bl_regions: block) (ofs:ptrofs) (l:list memory_region) :=\n  match l with\n  | nil => True\n  | mr :: l' => match_region_at_ofs  mr bl_regions ofs m /\\\n                  match_list_region  m bl_regions (Ptrofs.add ofs (Ptrofs.repr 16)) l'\n  end. *)\n\n(*\nFixpoint match_list_region (m:mem) (b: block) (ofs: nat) (l:list memory_region) :=\n  match l with\n  | nil => True\n  | mr :: l' => match_region_at_ofs mr b (Ptrofs.repr (16 * Z.of_nat ofs)) m /\\ match_list_region m b (ofs+1) l'\n  end. *)\n\nDefinition match_list_region (m:mem) (state_blk mrs_blk ins_blk: block) (l:list memory_region) :=\n  forall i, (0 <= i < List.length l)%nat -> match_region_at_ofs (List.nth i l default_memory_region) state_blk mrs_blk ins_blk (Ptrofs.repr (16 * Z.of_nat i)) m.\n\nDefinition match_regions (state_blk mrs_blk ins_blk: block) (st: State.state) (m:mem) :=\n  List.length (bpf_mrs st) = (mrs_num st) /\\ (**r the number of bpf_mrs is exactly the mrs_num *)\n  Z.of_nat (List.length (bpf_mrs st)) * 16 <= Ptrofs.max_unsigned /\\ (**r there is not overflow *)\n  match_list_region m state_blk mrs_blk ins_blk (bpf_mrs st).\n\n\nLemma match_regions_in:\n  forall l mr m state_blk mrs_blk ins_blk\n    (Hnth_error : In mr l)\n    (Hmatch : match_list_region m state_blk mrs_blk ins_blk l),\n      exists n, match_region_at_ofs mr state_blk mrs_blk ins_blk (Ptrofs.repr (16 * Z.of_nat n)) m.\nProof.\n  unfold match_list_region.\n  intros.\n  apply In_nth_error in Hnth_error.\n  destruct Hnth_error as (n & Hnth_error).\n  apply nth_error_some_length in Hnth_error as Hlen.\n  specialize (Hmatch n Hlen).\n  destruct Hlen as ( _ & Hlen).\n  apply nth_error_nth' with (d:= default_memory_region) in Hlen.\n  rewrite Hlen in Hnth_error.\n  inversion Hnth_error.\n  subst.\n  exists n; assumption.\nQed.\n\n(*\nFixpoint match_list_ins (m:mem) (b: block) (ofs:ptrofs) (l: MyListType) :=\n  match l with\n  | nil => True\n  | hd :: tl => Mem.loadv AST.Mint64 m (Vptr b ofs) = Some (Vlong hd) /\\\n                  match_list_ins m b (Ptrofs.add ofs (Ptrofs.repr 8)) tl\n  end. *)\n\nDefinition match_list_ins (m:mem) (b: block) (l: list int64) :=\n  forall i, (0 <= i < List.length l)%nat ->\n    Mem.loadv AST.Mint64 m  (Vptr b (Ptrofs.repr (8 * (Z.of_nat i)))) = Some (Vlong (List.nth i l Int64.zero)) (*/\\\n    0 <= (Int64.unsigned (Int64.shru (Int64.and (List.nth i l Int64.zero) (Int64.repr 4095)) (Int64.repr 8))) <= 10 /\\ (**r dst \\in [0,10] *)\n    0 <= (Int64.unsigned (Int64.shru (Int64.and (List.nth i l Int64.zero) (Int64.repr 65535)) (Int64.repr 12))) <= 10 (**r src \\in [0,10] *) *).\n\nDefinition match_ins (ins_blk: block) (st: State.state) (m:mem) :=\n  List.length (ins st) = (ins_len st) /\\\n  Z.of_nat (List.length (ins st)) * 8 <= Ptrofs.max_unsigned /\\\n  match_list_ins m ins_blk (ins st).\n\n\nClass special_blocks : Type :=\n  { st_blk : block;\n    mrs_blk  : block;\n    ins_blk  : block }.\n\nSection S.\n\n  Context {Blocks : special_blocks}.\n\n  Definition match_registers  (rmap:regmap) (bl_reg:block) (ofs : ptrofs) (m : mem) : Prop:=\n    forall (r:reg),\n    exists vl, Mem.loadv Mint64 m (Vptr bl_reg (Ptrofs.add ofs (Ptrofs.repr (8 * (id_of_reg r))))) = Some (Vlong vl) /\\ (**r it should be `(eval_regmap r rmap)`*)\n            Vlong vl = eval_regmap r rmap.\n           (*Val.inject inject_id (eval_regmap r rmap) (Vlong vl) . (**r each register is Vlong *)*)\n\n\n  (*Definition size_of_regs := 88. (**r 11 * 8: we have 11 regs R0 - R10 *)*)\n  Definition size_of_state (st: State.state) := 100 + 16 * (Z.of_nat (mrs_num st)) + 8 *(Z.of_nat (ins_len st)).\n\n(**r\nDefinition state_struct_def: Ctypes.composite_definition := \n  Ctypes.Composite state_id Ctypes.Struct [\n    (pc_id, C_U32);\n    (flag_id, C_S32);\n    (regmaps_id, C_regmap);;\n    (mem_num_id, C_U32)\n    (mem_regs_id, mem_region_type)\n  ] Ctypes.noattr.\n\n*)\n\n  Record match_state  (st: State.state) (m: mem) : Prop :=\n    {\n      munchange: Mem.unchanged_on (fun b _ => b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk) (bpf_m st) m; (**r (bpf_m st) = m - {state_blk, mrs_blk, ins_blk} *)\n      mpc      : Mem.loadv AST.Mint32 m (Vptr st_blk (Ptrofs.repr 0)) = Some (Vint  (pc_loc st));\n      mflags   : Mem.loadv AST.Mint32 m (Vptr st_blk (Ptrofs.repr 4)) = Some (Vint  (int_of_flag (flag st)));\n      mregs    : match_registers (regs_st st) st_blk (Ptrofs.repr 8) m;\n      mins_len : Mem.loadv AST.Mint32 m (Vptr st_blk (Ptrofs.repr 96)) = Some (Vint  (Int.repr (Z.of_nat (ins_len st)))) /\\ Z.of_nat (ins_len st) >= 1;\n      mins     : Mem.loadv AST.Mptr m (Vptr st_blk (Ptrofs.repr 100)) = Some (Vptr ins_blk (Ptrofs.repr 0)) /\\ match_ins ins_blk st m;\n      mmrs_num : Mem.loadv AST.Mint32 m (Vptr st_blk (Ptrofs.repr 104)) = Some (Vint  (Int.repr (Z.of_nat (mrs_num st)))) /\\\n                 (Z.of_nat(mrs_num st)) >= 1; (**r at least we have the memory region that corresponds to the input paramters of the interpreter *)\n      mem_regs : Mem.loadv AST.Mptr m (Vptr st_blk (Ptrofs.repr 108)) = Some (Vptr mrs_blk (Ptrofs.repr 0)) /\\ match_regions st_blk mrs_blk ins_blk st m;\n      mperm    : Mem.range_perm m st_blk 0 (size_of_state st) Cur Freeable /\\\n                 Mem.range_perm m mrs_blk   0 (Z.of_nat (mrs_num st)) Cur Freeable /\\\n                 Mem.range_perm m ins_blk   0 (Z.of_nat (ins_len st)) Cur Readable; (**r we also need to say `mrs/ins_blk` *)\n      minvalid : (~Mem.valid_block (bpf_m st) st_blk /\\\n                  ~Mem.valid_block (bpf_m st) mrs_blk /\\\n                  ~Mem.valid_block (bpf_m st) ins_blk) /\\\n                 (mrs_blk <> st_blk /\\ mrs_blk <> ins_blk /\\ ins_blk <> st_blk) /\\\n                 (forall b, b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk ->\n                  Mem.valid_block m b -> Mem.valid_block (bpf_m st) b);\n    }.\n\nEnd S.\n\n(* Permission Lemmas: deriving from riot-rbpf/MemInv.v *)\nLemma range_perm_included:\n  forall m b p lo hi ofs_lo ofs_hi, \n    lo <= ofs_lo -> ofs_lo < ofs_hi -> ofs_hi <= hi ->  (**r `<` -> `<=` *)\n    Mem.range_perm m b lo hi Cur p ->\n      Mem.range_perm m b ofs_lo ofs_hi Cur p.\nProof.\n  intros.\n  apply (Mem.range_perm_implies _ _ _ _ _ p _); [idtac | constructor].\n  unfold Mem.range_perm in *; intros.\n  apply H2.\n  lia.\nQed.\n\n(** Permission Lemmas: upd_pc *)\nLemma upd_pc_write_access:\n  forall m0 {bl:special_blocks} st\n    (Hst: match_state  st m0),\n    Mem.valid_access m0 Mint32 st_blk 0 Writable.\nProof.\n  intros; unfold Mem.valid_access; destruct Hst; clear - mem_regs0 mperm0; simpl in mem_regs0.\n  unfold match_regions, size_of_state in *.\n  destruct mperm0 as (mperm0 & _ & _).\n  apply (Mem.range_perm_implies _ _ _ _ _ _ Writable) in mperm0; [idtac | constructor].\n\n  unfold size_chunk, align_chunk.\n  split.\n  - simpl; apply (range_perm_included _ _ Writable _ _ 0 4) in mperm0; [assumption | lia | lia | idtac].\n    assert (H: 0<= Z.of_nat (State.mrs_num st)). { apply Nat2Z.is_nonneg. }\n    lia.\n  - apply Z.divide_0_r.\nQed.\n\nLemma upd_pc_store:\n  forall m0 {S: special_blocks} pc st\n    (Hst: match_state  st m0),\n    exists m1,\n    Mem.store AST.Mint32 m0 st_blk 0 (Vint pc) = Some m1.\nProof.\n  intros.\n  apply upd_pc_write_access  in Hst.\n  apply (Mem.valid_access_store _ _ _ _ (Vint pc)) in Hst.\n  destruct Hst as (m2 & Hstore).\n  exists m2; assumption.\nQed.\n\n(** Permission Lemmas: upd_flags *)\nLemma upd_flags_write_access:\n  forall m0 {S:special_blocks} st\n    (Hst: match_state  st m0),\n    Mem.valid_access m0 Mint32 st_blk 4 Writable.\nProof.\n  intros; unfold Mem.valid_access; destruct Hst; clear - mperm0; simpl in mperm0.\n  unfold size_of_state in *.\n  destruct mperm0 as (mperm0 & _ & _).\n  apply (Mem.range_perm_implies _ _ _ _ _ _ Writable) in mperm0; [idtac | constructor].\n\n  unfold size_chunk, align_chunk.\n  split.\n  - simpl.\n    apply (range_perm_included _ _ Writable _ _ 4 8) in mperm0; [assumption | lia | lia | lia].\n  - apply Z.divide_refl.\nQed.\n\nLemma upd_flags_store:\n  forall m0 {S: special_blocks} st v\n    (Hst: match_state  st m0),\n    exists m1,\n    Mem.store AST.Mint32 m0 st_blk 4 (Vint v) = Some m1.\nProof.\n  intros.\n  apply (upd_flags_write_access _ _ ) in Hst.\n  apply (Mem.valid_access_store _ _ _ _ (Vint v)) in Hst.\n  destruct Hst as (m2 & Hstore).\n  exists m2; assumption.\nQed.\n\n(** Permission Lemmas: upd_regs *)\nLemma upd_regs_write_access:\n  forall m0 {S: special_blocks} st r\n    (Hst: match_state  st m0),\n    Mem.valid_access m0 Mint64 st_blk (8 + (8 * (id_of_reg r))) Writable.\nProof.\n  intros; unfold Mem.valid_access; destruct Hst; clear - mperm0; simpl in mperm0.\n  unfold size_of_state in *.\n  destruct mperm0 as (mperm0 & _ & _).\n  apply (Mem.range_perm_implies _ _ _ _ _ _ Writable) in mperm0; [idtac | constructor].\n  assert (H: 0<= Z.of_nat (State.mrs_num st)). { apply Nat2Z.is_nonneg. }\n  apply (range_perm_included _ _ Writable _ _ 0 100) in mperm0; [idtac | lia | lia | lia].\n\n  unfold id_of_reg.\n  unfold size_chunk, align_chunk.\n  split.\n  - apply (range_perm_included _ _ Writable _ _ (8 + (8 * (id_of_reg r))) (8 + (8 * (id_of_reg r +1)))) in mperm0;\n  destruct r; simpl in *; try lia; try assumption.\n  - assert (Heq: forall x, 8 + 8 * x = 8 * (1 + x)). {\n      intros.\n      rewrite Zred_factor2.\n      reflexivity.\n    }\n    rewrite Heq.\n    apply Z.divide_factor_l.\nQed.\n\nLemma upd_regs_store:\n  forall m0 {S: special_blocks} st r v\n    (Hst: match_state  st m0),\n    exists m1,\n    Mem.store AST.Mint64 m0 st_blk (8 + (8 * (id_of_reg r))) (Vlong v) = Some m1.\nProof.\n  intros.\n  apply upd_regs_write_access with (r:=r) in Hst.\n  apply (Mem.valid_access_store _ _ _ _ (Vlong v)) in Hst.\n  destruct Hst as (m2 & Hstore).\n  exists m2; assumption.\nQed.\n\n(** Permission Lemmas: upd_mem_regions *)\n\n(** TODO: nothing to do because we never update memory_regions, it should be done before running the interpter *)\n\nDefinition match_region (st_blk mrs_blk ins_blk : block) (mr: memory_region) (v: val) (st: State.state) (m:Memory.Mem.mem) :=\n  exists o, v = Vptr mrs_blk o /\\\n              match_region_at_ofs mr st_blk mrs_blk ins_blk o m.\n\n(*\nDefinition match_region_list (st_blk mrs_blk ins_blk: block) (mrl: list memory_region) (v: val) (st: State.state) (m:Memory.Mem.mem) :=\n  v = Vptr mrs_blk Ptrofs.zero /\\\n  mrl = (bpf_mrs st) /\\\n  List.length mrl = (mrs_num st) /\\ (**r those two are from the match_state relation *)\n  match_list_region m st_blk mrs_blk ins_blk mrl. *)\n\nLemma same_memory_match_region :\n  forall st_blk mrs_blk ins_blk st st' m m' mr v\n         (UMOD : unmodifies_effect ModNothing m m' st st'),\n    match_region st_blk mrs_blk ins_blk mr v st m ->\n    match_region st_blk mrs_blk ins_blk mr v st' m'.\nProof.\n  intros.\n  unfold match_region in *.\n  destruct H as (o & E & MR).\n  exists o.\n  split; auto.\n  unfold match_region_at_ofs in *.\n  unfold unmodifies_effect in UMOD.\n  destruct UMOD; subst.\n  repeat rewrite <- UMOD by (simpl ; tauto).\n  intuition.\nQed.\n\n(**r a set of lemmas say upd_reg/flag/pc... don't change the memory/regs/flag/pc of rbpf *)\n\nLemma upd_reg_same_mem:\n  forall st0 r vl,\n    bpf_m st0 = bpf_m (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_pc:\n  forall st0 r vl,\n    pc_loc st0 = pc_loc (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_flag:\n  forall st0 r vl,\n    flag st0 = flag (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_mrs:\n  forall st0 r vl,\n    bpf_mrs st0 = bpf_mrs (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_mrs_num:\n  forall st0 r vl,\n    State.mrs_num st0 = State.mrs_num (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_ins:\n  forall st0 r vl,\n    ins st0 = ins (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_reg_same_ins_len:\n  forall st0 r vl,\n    ins_len st0 = ins_len (State.upd_reg r vl st0).\nProof.\n  unfold State.upd_reg.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_mem:\n  forall st0 pc,\n    bpf_m st0 = bpf_m (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_regs:\n  forall st0 pc,\n    regs_st st0 = regs_st (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_flag:\n  forall st0 pc,\n    flag st0 = flag (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_mrs:\n  forall st0 pc,\n    bpf_mrs st0 = bpf_mrs (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_mrs_num:\n  forall st0 pc,\n    State.mrs_num st0 = State.mrs_num (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_ins:\n  forall st0 pc,\n    ins st0 = ins (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_same_ins_len:\n  forall st0 pc,\n    ins_len st0 = ins_len (State.upd_pc pc st0).\nProof.\n  unfold State.upd_pc.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_mem:\n  forall st0,\n    bpf_m st0 = bpf_m (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_regs:\n  forall st0,\n    regs_st st0 = regs_st (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_flag:\n  forall st0,\n    flag st0 = flag (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_mrs:\n  forall st0,\n    bpf_mrs st0 = bpf_mrs (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_mrs_num:\n  forall st0,\n    State.mrs_num st0 = State.mrs_num (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_ins:\n  forall st0,\n    ins st0 = ins (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_pc_incr_same_ins_len:\n  forall st0,\n    ins_len st0 = ins_len (State.upd_pc_incr st0).\nProof.\n  unfold State.upd_pc_incr.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_mem:\n  forall st0 f,\n    bpf_m st0 = bpf_m (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_regs:\n  forall st0 f,\n    regs_st st0 = regs_st (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_pc:\n  forall st0 f,\n    pc_loc st0 = pc_loc (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_mrs:\n  forall st0 f,\n    bpf_mrs st0 = bpf_mrs (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_mrs_num:\n  forall st0 f,\n    State.mrs_num st0 = State.mrs_num (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_ins:\n  forall st0 f,\n    ins st0 = ins (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_flag_same_ins_len:\n  forall st0 f,\n    ins_len st0 = ins_len (State.upd_flag f st0).\nProof.\n  unfold State.upd_flag.\n  intros.\n  reflexivity.\nQed.\n\nLemma upd_unchanged_on:\n  forall st m0 m1 {S:special_blocks} chunk ofs vl\n  (Hst    : match_state  st m0)\n  (Hstore : Mem.store chunk m0 st_blk ofs vl = Some m1),\n    Mem.unchanged_on (fun b _ => b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk) m0 m1.\nProof.\n  intros.\n  destruct Hst. (*\n  destruct minj0.\n  clear - mi_inj mi_freeblocks minvalid0 munchange0 mByte0 Hstore. *)\n  eapply Mem.store_unchanged_on.\n  rewrite Hstore.\n  reflexivity.\n  intros.\n  intro.\n  destruct H0 as (H0 & _).\n  apply H0; reflexivity.\nQed.\n\nLemma upd_preserves_match_list_ins:\n  forall l chunk m0 m1 st_blk ins_blk ofs0 vl\n  (Hstore : Mem.store chunk m0 st_blk ofs0 vl = Some m1)\n  (mem_regs : match_list_ins m0 ins_blk l)\n  (Hneq_blk : st_blk <> ins_blk),\n    match_list_ins m1 ins_blk l.\nProof.\n  intro l.\n  induction l.\n  unfold match_list_ins in *.\n  intros.\n  simpl in H.\n  lia.\n\n  intros; simpl in *.\n  unfold match_list_ins in *.\n  intros.\n  specialize (mem_regs0 i H).\n  unfold Mem.loadv in *. (*\n  destruct mem_regs0 as (mem_regs0 & Hdst & Hsrc). *)\n  rewrite <- mem_regs0.\n  eapply Mem.load_store_other; eauto.\n   (*\n  split.\n  eapply Mem.load_store_other; eauto.\n  split; assumption. *)\nQed.\n\nLemma upd_preserves_match_list_region:\n  forall l chunk m0 m1 st_blk mrs_blk ins_blk b ofs0 vl\n  (Hstore : Mem.store chunk m0 b ofs0 vl = Some m1)\n  (mem_regs : match_list_region m0 st_blk mrs_blk ins_blk l)\n  (Hneq_blk : b <> mrs_blk),\n    match_list_region m1 st_blk mrs_blk ins_blk l.\nProof.\n  intro l.\n  induction l;\n  unfold match_list_region in *.\n  intros; simpl in *.\n  lia.\n\n  intros.\n  unfold match_region_at_ofs in *.\n  specialize (mem_regs0 i H).\n  destruct mem_regs0 as  ((vl0 & Hload0 & Heq0) & (vl1 & Hload1 & Heq1) & (vl2 & Hload2 & Heq2) & (blk3 & Hload3 & Heq_ptr)).\n\n  split.\n  exists vl0; rewrite <- Hload0; split; [\n  eapply Mem.load_store_other; eauto | assumption].\n\n  split.\n  exists vl1; rewrite <- Hload1; split; [\n  eapply Mem.load_store_other; eauto | assumption].\n\n  split.\n  exists vl2; rewrite <- Hload2; split; [\n  eapply Mem.load_store_other; eauto | assumption].\n\n  exists blk3; rewrite <- Hload3; split; [\n  eapply Mem.load_store_other; eauto | ].\n  intuition.\n  eapply Mem.store_valid_block_1; eauto.\nQed.\n\nLemma upd_reg_preserves_match_state:\n  forall st0 st1 m0 m1 {S:special_blocks} r vl\n  (Hst    : match_state  st0 m0)\n  (Hst1   : State.upd_reg r (Vlong vl) st0 = st1)\n  (Hstore : Mem.store AST.Mint64 m0 st_blk (8 + 8 * id_of_reg r) (Vlong vl) = Some m1),\n    match_state  st1 m1.\nProof.\n  intros.\n  subst.\n  set (Hst' := Hst).\n  destruct Hst'.\n  split; unfold Mem.loadv in *.\n  -\n    rewrite <- (upd_reg_same_mem _ r (Vlong vl)).\n    assert (Hunchanged_on': Mem.unchanged_on (fun (b : block) (_ : Z) => b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk) m0 m1). {\n      eapply Mem.store_unchanged_on; eauto.\n      intros.\n      intro.\n      destruct H0 as (H0 & _).\n      apply H0; reflexivity.\n    }\n    apply Mem.unchanged_on_trans with(m2:= m0); auto.\n  -\n    rewrite <- (upd_reg_same_pc _ r (Vlong vl)).\n    rewrite <- mpc0.\n    eapply Mem.load_store_other; eauto.\n    right; left.\n    unfold id_of_reg; simpl.\n    fold Ptrofs.zero.\n    rewrite Ptrofs.unsigned_zero.\n    destruct r; try lia.\n  - rewrite <- (upd_reg_same_flag _ r (Vlong vl)).\n    rewrite <- mflags0.\n    eapply Mem.load_store_other; eauto.\n    right; left.\n    rewrite Ptrofs_unsigned_repr_n; [| try simpl; lia].\n    unfold id_of_reg; simpl; destruct r; try lia.\n  - unfold match_registers in *.\n    intros.\n    specialize (mregs0 r0).\n    destruct mregs0 as (vl0 & mregs0 & mregs1).\n    unfold Mem.loadv, Ptrofs.add in *.\n\n    rewrite Hreg_eq in *.\n    destruct (reg_eq r0 r).\n    + (**r case: r0 = r *)\n      subst.\n      exists vl.\n      split.\n      assert (Hload_result: Val.load_result Mint64 (Vlong vl) = (Vlong vl)). {\n        reflexivity.\n      }\n      rewrite <- Hload_result.\n      eapply Mem.load_store_same; eauto.\n      unfold State.upd_reg; simpl.\n      rewrite eval_upd_regmap_same.\n      reflexivity.\n    +\n      exists vl0.\n      unfold State.upd_reg, regs_st.\n      \n      rewrite eval_upd_regmap_other.\n      split.\n      2:{\n        rewrite mregs1.\n        reflexivity.\n      }\n      rewrite <- mregs0.\n      eapply Mem.load_store_other; eauto.\n      right.\n      2:{ assumption. }\n      destruct r0, r; simpl; [try (exfalso; apply n; reflexivity) || (try left; lia) || (try right; lia) ..].\n  - simpl.\n    destruct mins_len0 as (mins_len0 & mins_len1).\n    split; [| assumption].\n\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    rewrite <- mins_len0.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    unfold id_of_reg, size_chunk; destruct r; lia.\n  - (**r match_ins *)\n    unfold match_ins.\n    unfold match_ins in mins0.\n    destruct mins0 as (Hload & mins_len & mins_max & mins0).\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    unfold id_of_reg, size_chunk; destruct r; lia.\n\n    split; [assumption | ].\n    split; [assumption | ].\n    assert (Hins_eq : ins (State.upd_reg r (Vlong vl) st0) = ins st0). {\n      unfold State.upd_reg.\n      simpl.\n      reflexivity.\n    }\n    rewrite Hins_eq; clear Hins_eq.\n    destruct minvalid0 as (_ & minvalid0 & _).\n    eapply upd_preserves_match_list_ins; eauto. intuition.\n  - rewrite <- (upd_reg_same_mrs_num _ r (Vlong vl)).\n    destruct mmrs_num0 as (Hload & Hge).\n    split; [| assumption].\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    unfold size_chunk.\n    assert (Hle_104: 8 + 8 * id_of_reg r + 8 <= 104). { unfold id_of_reg; destruct r; lia. }\n    rewrite Ptrofs_unsigned_repr_n; [| try simpl; lia].\n    assumption.\n  - unfold match_regions in *.\n    destruct mem_regs0 as (Hload & mrs_len & mrs_max & mem_regs0).\n    rewrite <- (upd_reg_same_mrs _ r (Vlong vl)).\n\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    unfold id_of_reg, size_chunk; destruct r; lia.\n\n    split; [assumption | ].\n    split; [assumption | ].\n    destruct minvalid0 as (_ & minvalid0 & _).\n    eapply upd_preserves_match_list_region; eauto. intuition.\n\n  - clear - mperm0 Hstore.\n    unfold Mem.range_perm in *.\n    destruct mperm0 as (mperm0 & mperm1 & mperm2).\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply mperm0.\n    unfold size_of_state in *.\n    rewrite <- upd_reg_same_mrs_num in *.\n    assumption.\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply mperm1.\n    unfold size_of_state in *.\n    rewrite <- upd_reg_same_mrs_num in *.\n    assumption.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply mperm2.\n    unfold size_of_state in *.\n    rewrite <- upd_reg_same_ins_len in *.\n    assumption.\n  - rewrite <- upd_reg_same_mem.\n    intuition.\n    apply H14; auto.\n    eapply Mem.store_valid_block_2; eauto.\nQed.\n\n\nLemma upd_pc_preserves_match_state:\n  forall st0 st1 m0 m1 {S:special_blocks} pc\n  (Hst    : match_state  st0 m0)\n  (Hst1   : State.upd_pc pc st0 = st1)\n  (Hstore : Mem.store AST.Mint32 m0 st_blk 0 (Vint pc) = Some m1),\n    match_state  st1 m1.\nProof.\n  intros.\n  subst.\n  set (Hst' := Hst).\n  split.\n  -\n    destruct Hst' as (Hunchanged_on, _, _, _, _, _, _, _, _, _).\n    rewrite <- upd_pc_same_mem.\n    assert (Hunchanged_on': Mem.unchanged_on (fun (b : block) (_ : Z) => b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk) m0 m1). {\n      eapply Mem.store_unchanged_on; eauto.\n      intros.\n      intro.\n      destruct H0 as(H0 & _).\n      apply H0; reflexivity.\n    }\n    apply Mem.unchanged_on_trans with(m2:= m0); auto.\n  -\n    destruct Hst' as (_ , Hpc, _, _, _, _, _, _, _, _).\n    unfold Mem.loadv in *.\n    fold Ptrofs.zero in *.\n    rewrite Ptrofs.unsigned_zero in *.\n    apply Mem.load_store_same in Hstore.\n    rewrite Hstore.\n    unfold Val.load_result.\n    reflexivity.\n  -\n    destruct Hst' as (_ , _, Hflag, _, _, _, _, _, _, _).\n    rewrite <- upd_pc_same_flag.\n    rewrite <- Hflag.\n    eapply Mem.load_store_other.\n    apply Hstore.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n; [| try simpl; lia].\n    reflexivity.\n  -\n    destruct Hst' as (_ , _, _, Hregs, _, _, _, _, _, _).\n    rewrite <- upd_pc_same_regs.\n    unfold match_registers in *.\n    intros.\n    specialize (Hregs r).\n    destruct Hregs as (vl & Hload & Hvl_eq).\n    exists vl.\n    split; [| assumption].\n    rewrite <- Hload.\n    unfold Mem.loadv.\n    eapply Mem.load_store_other.\n    apply Hstore.\n    right; right.\n    unfold Ptrofs.add in *.\n    unfold size_chunk.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    rewrite Ptrofs_unsigned_repr_id_of_reg in *.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    unfold id_of_reg; destruct r; lia.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    rewrite Ptrofs_unsigned_repr_n with (n:= 8 * id_of_reg r) in *; try (simpl; lia).\n    all: unfold id_of_reg; destruct r; lia.\n  - \n    destruct Hst' as (_ , _, _, _, (Hins_len & Hge), _, _, _, _, _).\n    rewrite <- upd_pc_same_ins_len.\n    split; [| assumption].\n    rewrite <- Hins_len.\n    simpl.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n  - \n    destruct Hst' as (_ , _, _, _, _, Hins, _, _, _, (_ & Hneq_blk & _)).\n    unfold match_ins in *.\n    destruct Hins as (Hload & Hins_len & Hins_max & Hins).\n    rewrite <- upd_pc_same_ins.\n    rewrite <- upd_pc_same_ins_len.\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    \n\n    split; [assumption |].\n    split; [assumption |].\n    eapply upd_preserves_match_list_ins; eauto. intuition.\n  - \n    destruct Hst' as (_ , _, _, _, _, _, (Hmrs_len & Hge), _, _, _).\n    rewrite <- upd_pc_same_mrs_num.\n    split; [| assumption].\n    rewrite <- Hmrs_len.\n    simpl.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n  - \n    destruct Hst' as (_ , _, _, _, _, _, _, Hmrs, _, (_ & Hneq_blk & _)).\n    unfold match_regions in *.\n    rewrite <- upd_pc_same_mrs.\n    rewrite <- upd_pc_same_mrs_num.\n    destruct Hmrs as (Hload & Hmrs_len & Hmrs_ge & Hmrs).\n\n\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n\n    split; [assumption| ].\n    split; [assumption| ].\n    eapply upd_preserves_match_list_region; eauto. intuition.\n  -\n    destruct Hst' as (_ , _, _, _, _, _, _, _, Hperm, _).\n    unfold size_of_state in *.\n    rewrite <- upd_pc_same_mrs_num.\n    unfold Mem.range_perm in *.\n    destruct Hperm as (Hperm0 & Hperm1 & Hperm2).\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm0.\n    assumption.\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm1.\n    assumption.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm2.\n    assumption.\n  -\n    destruct Hst' as (_ , _, _, _, _, _, _, _, _, Hvalid).\n    rewrite <- upd_pc_same_mem.\n    intuition.\n    apply H3; auto.\n    eapply Mem.store_valid_block_2; eauto.\nQed.\n\nLemma upd_flag_preserves_match_state:\n  forall st0 st1 m0 m1 {S: special_blocks} flag\n  (Hst    : match_state  st0 m0)\n  (Hst1   : State.upd_flag flag st0 = st1)\n  (Hstore : Mem.store AST.Mint32 m0 st_blk 4 (Vint (int_of_flag flag)) = Some m1),\n    match_state  st1 m1.\nProof.\n  intros.\n  subst.\n  set (Hst' := Hst).\n  split.\n  -\n    destruct Hst' as (Hunchanged_on, _, _, _, _, _, _, _, _, _).\n    rewrite <- upd_flag_same_mem.\n    assert (Hunchanged_on': Mem.unchanged_on (fun (b : block) (_ : Z) => b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk) m0 m1). {\n      eapply Mem.store_unchanged_on; eauto.\n      intros.\n      intro H0; destruct H0 as (H0 & _); apply H0; reflexivity.\n    }\n    apply Mem.unchanged_on_trans with(m2:= m0); auto.\n  -\n    destruct Hst' as (_ , Hpc, _, _, _, _, _, _, _, _).\n    rewrite <- upd_flag_same_pc.\n    rewrite <- Hpc.\n    eapply Mem.load_store_other.\n    apply Hstore.\n    right; left.\n    fold Ptrofs.zero; rewrite Ptrofs.unsigned_zero.\n    reflexivity.\n  -\n    destruct Hst' as (_ , _, Hflag, _, _, _, _, _, _, _).\n\n    unfold Mem.loadv in *.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    apply Mem.load_store_same in Hstore.\n    rewrite Hstore.\n    unfold Val.load_result.\n    reflexivity.\n  -\n    destruct Hst' as (_ , _, _, Hregs, _, _, _, _, _, _).\n    rewrite <- upd_flag_same_regs.\n    unfold match_registers in *.\n    intros.\n    specialize (Hregs r).\n    destruct Hregs as (vl & Hload & Hvl_eq).\n    exists vl.\n    split; [| assumption].\n    rewrite <- Hload.\n    unfold Mem.loadv.\n    eapply Mem.load_store_other.\n    apply Hstore.\n    right; right.\n    unfold Ptrofs.add in *.\n    unfold size_chunk.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    4:\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    4:\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n    all: unfold id_of_reg; destruct r; lia.\n  -\n    destruct Hst' as (_ , _, _, _, (Hins_len & Hge), _, _, _, _, _).\n    rewrite <- upd_flag_same_ins_len.\n    split; [| assumption].\n    rewrite <- Hins_len.\n    simpl.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n  - \n    destruct Hst' as (_ , _, _, _, _, Hins, _, _, _, (_ & Hneq_blk & _)).\n    unfold match_ins in *.\n    destruct Hins as (Hload & Hins_len & Hins_max & Hins).\n    rewrite <- upd_flag_same_ins.\n    rewrite <- upd_flag_same_ins_len.\n\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n\n    split; [assumption |].\n    split; [assumption |].\n    eapply upd_preserves_match_list_ins; eauto. intuition.\n  -\n    destruct Hst' as (_ , _, _, _, _, _, (Hmrs_len & Hge), _, _, _).\n    rewrite <- upd_flag_same_mrs_num.\n    split; [| assumption].\n    rewrite <- Hmrs_len.\n    simpl.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n  - \n    destruct Hst' as (_ , _, _, _, _, _, _, Hmrs, _, (_ & Hneq_blk & _)).\n    unfold match_regions in *.\n    rewrite <- upd_flag_same_mrs.\n    rewrite <- upd_flag_same_mrs_num.\n    destruct Hmrs as (Hload & Hmrs_len & Hmrs_ge & Hmrs).\n\n    split.\n    rewrite <- Hload.\n    eapply Mem.load_store_other; eauto.\n    right; right.\n    rewrite Ptrofs_unsigned_repr_n in *; try (simpl; lia).\n\n    split; [assumption| ].\n    split; [assumption| ].\n    eapply upd_preserves_match_list_region; eauto. intuition.\n  -\n    destruct Hst' as (_ , _, _, _, _, _, _, _, Hperm, _).\n    unfold size_of_state in *.\n    rewrite <- upd_flag_same_mrs_num.\n    unfold Mem.range_perm in *.\n    destruct Hperm as (Hperm0 & Hperm1 & Hperm2).\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm0.\n    assumption.\n    split; intros.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm1.\n    assumption.\n    eapply Mem.perm_store_1.\n    apply Hstore.\n    apply Hperm2.\n    assumption.\n  -\n    destruct Hst' as (_ , _, _, _, _, _, _, _, _, Hvalid).\n    rewrite <- upd_flag_same_mem.\n    intuition.\n    apply H3; auto.\n    eapply Mem.store_valid_block_2; eauto.\nQed.\n\nLemma match_state_implies_valid_pointer:\n  forall  {S:special_blocks} st m b ofs\n    (Hmatch : match_state  st m)\n    (Hvalid : Mem.valid_pointer (bpf_m st) b ofs = true),\n      Mem.valid_pointer m b ofs = true.\nProof.\n  intros.\n  rewrite Mem.valid_pointer_nonempty_perm in *.\n  destruct Hmatch.\n  eapply Mem.perm_unchanged_on; eauto.\n  simpl.\n  apply Mem.perm_valid_block in Hvalid.\n  clear - minvalid0 Hvalid.\n  destruct minvalid0 as ((Hv0 & Hv1 & Hv2) & H).\n  repeat split.\n  all: eapply Mem.valid_not_valid_diff; eauto.\nQed.\n\nLemma match_state_implies_loadv_equal:\n  forall {S: special_blocks} st m chunk b ofs v\n    (Hmatch : match_state  st m)\n    (Hload: Mem.load chunk (bpf_m st) b ofs = Some v),\n      Mem.load chunk m b ofs = Some v.\nProof.\n  intros.\n  set (Hmatch' := Hmatch).\n  destruct Hmatch' as (Hunchanged, _, _, _, _, _, _, _, _, Hinvalid).\n  rewrite <- Hload.\n  destruct Hinvalid as (Hinvalid & _ & Hvalid_block).\n  apply Mem.load_valid_access in Hload.\n  assert (Hload' : Mem.valid_access (bpf_m st) chunk b ofs Nonempty). {\n    eapply Mem.valid_access_implies; eauto.\n    constructor.\n  }\n  eapply Mem.valid_access_valid_block in Hload'; eauto.\n  eapply Mem.load_unchanged_on_1; eauto.\n  simpl; intros.\n  intuition congruence.\nQed.\n\nLemma store_match_state_same:\n  forall st1 m m1 m2 chunk b ofs addr\n    (Hstore : Mem.store chunk (bpf_m st1) b ofs addr = Some m)\n    (Hstore_m2 : Mem.store chunk m1 b ofs addr = Some m2)\n    (Hunchanged_on_contents : Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m1)) =\n                        Maps.ZMap.get ofs\n                          (Maps.PMap.get b (Mem.mem_contents (bpf_m st1)))),\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m2)) =\n      Maps.ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m)).\nProof.\n  intros.\n  apply Mem.store_mem_contents in Hstore as Hcontents0; auto.\n  apply Mem.store_mem_contents in Hstore_m2 as Hcontents1; auto.\n  rewrite Hcontents0, Hcontents1.\n  repeat rewrite Maps.PMap.gss.\n  clear - Hunchanged_on_contents.\n  generalize (encode_val chunk addr).\n  intros.\n  destruct l.\n  - simpl.\n    assumption.\n  - simpl.\n    rewrite Mem.setN_other; [|intros; lia].\n    rewrite Mem.setN_other; [|intros; lia].\n    repeat rewrite Maps.ZMap.gss.\n    reflexivity.\nQed.\n\nLemma store_match_state_same_other:\n  forall st1 m m1 m2 chunk b ofs ofs0 addr\n    (Hstore : Mem.store chunk (bpf_m st1) b ofs addr = Some m)\n    (Hstore_m2 : Mem.store chunk m1 b ofs addr = Some m2)\n    (Hother: ofs < ofs0 < ofs + size_chunk chunk)\n    (Hunchanged_on_contents : Maps.ZMap.get ofs0 (Maps.PMap.get b (Mem.mem_contents m1)) =\n                        Maps.ZMap.get ofs0\n                          (Maps.PMap.get b (Mem.mem_contents (bpf_m st1)))),\n      Maps.ZMap.get ofs0 (Maps.PMap.get b (Mem.mem_contents m2)) =\n      Maps.ZMap.get ofs0 (Maps.PMap.get b (Mem.mem_contents m)).\nProof.\n  intros.\n  apply Mem.store_mem_contents in Hstore as Hcontents0; auto.\n  apply Mem.store_mem_contents in Hstore_m2 as Hcontents1; auto.\n  rewrite Hcontents0, Hcontents1.\n  repeat rewrite Maps.PMap.gss.\n\n  assert (Hlen: List.length (encode_val chunk addr) = size_chunk_nat chunk) by apply encode_val_length.\n  revert Hlen.\n  generalize (encode_val chunk addr).\n  unfold size_chunk_nat.\n  intros.\n  assert (Hofs0_eq: exists n, 0 < Z.of_nat n < size_chunk chunk /\\ ofs0 = ofs+ Z.of_nat n). {\n    clear - Hother.\n    assert (Heq: Z.of_nat (Z.to_nat (ofs0 - ofs)) = ofs0 - ofs). {\n      rewrite Z2Nat.id.\n      reflexivity.\n      lia.\n    }\n    exists (Z.to_nat(ofs0 - ofs)).\n    lia.\n  }\n  destruct Hofs0_eq as (z & Hz_range & Hofs0_eq); subst.\n  repeat rewrite mem_get_in.\n  reflexivity.\n  lia.\n  lia.\nQed.\n\nLemma store_match_state_other:\n  forall st1 m m1 m2 chunk b ofs addr\n    (Hstore : Mem.store chunk (bpf_m st1) b ofs addr = Some m)\n    (Hstore_m2 : Mem.store chunk m1 b ofs addr = Some m2),\n    forall b0 ofs0\n    (Hother: b0 <> b \\/ ofs0 < ofs \\/ ofs + size_chunk chunk <= ofs0)\n    (Hunchanged_on_contents :\n      Maps.ZMap.get ofs0 (Maps.PMap.get b0 (Mem.mem_contents m1)) =\n      Maps.ZMap.get ofs0 (Maps.PMap.get b0 (Mem.mem_contents (bpf_m st1)))),\n      Maps.ZMap.get ofs0 (Maps.PMap.get b0 (Mem.mem_contents m2)) =\n      Maps.ZMap.get ofs0 (Maps.PMap.get b0 (Mem.mem_contents m)).\nProof.\n  intros.\n  apply Mem.store_mem_contents in Hstore as Hcontents0; auto.\n  apply Mem.store_mem_contents in Hstore_m2 as Hcontents1; auto.\n  rewrite Hcontents0, Hcontents1.\n  destruct (b0 =? b)%positive eqn: Hblk_eq; [rewrite Pos.eqb_eq in Hblk_eq | rewrite Pos.eqb_neq in Hblk_eq].\n  - subst.\n    repeat rewrite Maps.PMap.gss.\n    destruct Hother as [Hfalse | Hother]; [intuition|].\n    repeat rewrite Mem.setN_outside.\n    + assumption.\n    + rewrite Memdata.encode_val_length.\n      unfold size_chunk_nat, size_chunk.\n      unfold size_chunk in Hother.\n      destruct Hother as [Hle | Hge].\n      * left.\n        lia.\n      * right.\n        destruct chunk; lia.\n    + rewrite Memdata.encode_val_length.\n      unfold size_chunk_nat, size_chunk.\n      unfold size_chunk in Hother.\n      destruct Hother as [Hle | Hge].\n      * left.\n        lia.\n      * right.\n        destruct chunk; lia.\n  - repeat (rewrite Maps.PMap.gso; [| lia]).\n    assumption.\nQed.\n\nLemma store_reg_preserive_match_state:\n  forall {S:special_blocks} st1 st2 m1 chunk b ofs addr m\n    (Hst: match_state  st1 m1)\n    (Hstore: Mem.store chunk (bpf_m st1) b ofs addr = Some m)\n    (Hupd_st: upd_mem m st1 = st2),\n      exists m2,\n        Mem.store chunk m1 b ofs addr = Some m2 /\\\n        match_state  st2 m2.\nProof.\n  intros.\n  assert (Hvalid_blk': Mem.valid_block (bpf_m st1) b). {\n    destruct Hst as (Hunchanged_on, _, _, _, _, _, _, _, _, _).\n    apply Mem.store_valid_access_3 in Hstore.\n    assert (Hstore' : Mem.valid_access (bpf_m st1) chunk b ofs Nonempty). {\n      eapply Mem.valid_access_implies; eauto.\n      constructor.\n    }\n    eapply Mem.valid_access_valid_block in Hstore'; eauto.\n  }\n  assert (Hvalid_blk: Mem.valid_block m1 b). {\n    destruct Hst as (Hunchanged_on, _, _, _, _, _, _, _, _, _).\n    eapply Mem.valid_block_unchanged_on; eauto.\n  }\n\n  assert (Hinvalid: b <> st_blk /\\ b <> mrs_blk /\\ b <> ins_blk). {\n    destruct Hst as (_, _, _, _, _, _, _, _, _, Hinvalid).\n    destruct Hinvalid as ((Hinvalid0 & Hinvalid1 & Hinvalid2) & _ & _).\n    split.\n    intro; subst.\n    apply Hinvalid0; assumption.\n    split; intro; subst.\n    apply Hinvalid1; assumption.\n    apply Hinvalid2; assumption.\n  }\n\n  assert (Hvalid_access: Mem.valid_access m1 chunk b ofs Writable). {\n    destruct Hst.\n    destruct minvalid0 as ( _ & _ & Hvalid).\n    specialize (Hvalid b Hinvalid Hvalid_blk).\n    clear - munchange0 Hvalid Hvalid_blk Hinvalid Hstore.\n    destruct munchange0.\n\n    eapply Mem.store_valid_access_3 in Hstore as Hvalid_acc; eauto.\n    eapply Mem.valid_access_store with (v:= addr) in Hvalid_acc as Hres; eauto.\n\n    unfold Mem.valid_access in *.\n    destruct Hvalid_acc as (Hvalid_acc & Haligh).\n    split; [| assumption].\n    unfold Mem.range_perm in *.\n    intros.\n    specialize (Hvalid_acc ofs0 H).\n    specialize (unchanged_on_perm b ofs0 Cur Writable Hinvalid Hvalid).\n    apply unchanged_on_perm; assumption.\n  }\n  eapply Mem.valid_access_store with (v:= addr) in Hvalid_access; eauto.\n  destruct Hvalid_access as (m2 & Hstore_m2).\n  exists m2.\n  split; [assumption |].\n\n  subst.\n  set (Hst' := Hst).\n  split.\n  - (**r Mem.unchanged_on *)\n    destruct Hst' as (Hunchanged_on, _, _, _, _, _, _, _, _, _).\n    destruct Hunchanged_on.\n    unfold upd_mem; simpl.\n    split.\n    + eapply Mem.nextblock_store in Hstore_m2; auto.\n      rewrite Hstore_m2.\n      eapply Mem.nextblock_store in Hstore; auto.\n      rewrite Hstore.\n      assumption.\n    + intros.\n      eapply Mem.store_valid_block_2 in Hstore as Hvalid_block; eauto.\n      specialize (unchanged_on_perm b0 ofs0 k p H Hvalid_block).\n      eapply store_perm_iff with (b0:=b0) (ofs0:=ofs0) (k:=k) (p:=p) in Hstore as Hperm_1; eauto.\n      eapply store_perm_iff with (b0:=b0) (ofs0:=ofs0) (k:=k) (p:=p) in Hstore_m2 as Hperm_2; eauto.\n      intuition.\n    + intros.\n      eapply Mem.perm_store_2 in Hstore as Hperm; eauto.\n      specialize (unchanged_on_contents b0 ofs0 H Hperm).\n      clear unchanged_on_nextblock unchanged_on_perm H0 Hperm.\n\n      destruct (b0 =? b)%positive eqn: Hblk_eq; [rewrite Pos.eqb_eq in Hblk_eq | rewrite Pos.eqb_neq in Hblk_eq].\n      * (**r b0 = b *)\n        subst.\n        destruct (ofs0 =? ofs)%Z eqn: Hofs_eq; [rewrite Z.eqb_eq in Hofs_eq | rewrite Z.eqb_neq in Hofs_eq].\n        ** (**r ofs0 = ofs *)\n          subst.\n          eapply store_match_state_same; eauto.\n        ** (**r ofs0 <> ofs *)\n          rewrite Z.lt_gt_cases in Hofs_eq.\n          destruct Hofs_eq as [Hofs_le | Hofs_ge].\n          { (**r ofs0 < ofs*)\n            eapply store_match_state_other; eauto.\n          }\n          { (**r ofs < ofs0 *)\n            destruct (ofs + size_chunk chunk <=? ofs0)%Z eqn: Hge; [rewrite Z.leb_le in Hge | rewrite Z.leb_gt in Hge].\n            { (**r ofs + size_chunk chunk <= ofs0 *)\n              eapply store_match_state_other; eauto.\n            }\n            { (**r ofs < ofs0 < ofs + size_chunk chunk *)\n              eapply store_match_state_same_other; eauto.\n            }\n          }\n      * (**r b0 <> b *)\n        eapply store_match_state_other; eauto.\n  - (**r pc *)\n    destruct Hst' as (_, Hpc, _, _, _, _, _, _, _, _).\n    unfold Mem.loadv in *.\n    unfold upd_mem; simpl.\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n  - (**r flag *)\n    destruct Hst' as (_, _, Hflag, _, _, _, _, _, _, _).\n    unfold Mem.loadv in *.\n    unfold upd_mem; simpl.\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n  - (**r registers *)\n    destruct Hst' as (_, _, _, Hreg, _, _, _, _, _, _).\n    unfold match_registers in *.\n    intros.\n    specialize (Hreg r).\n    destruct Hreg as (vl & Hload & Hvl_eq).\n    unfold Mem.loadv in *.\n    unfold upd_mem; simpl regs_st.\n    exists vl.\n    split; [| assumption].\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n  - (**r ins_len *)\n    destruct Hst' as (_, _, _, _, Hins_len, _, _, _, _, _).\n    unfold Mem.loadv in *.\n    unfold upd_mem; simpl.\n    destruct Hins_len as (Hload & Hge).\n    split; [| assumption].\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n  - (**r ins *)\n    destruct Hst' as (_, _, _, _, _, Hins, _, _, _, _).\n    unfold Mem.loadv in *.\n    unfold match_ins in *.\n    destruct Hins as (Hload & Hlen & Hmax & Hmatch).\n    unfold upd_mem; simpl.\n    split.\n\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n\n    split; [assumption| ].\n    split; [assumption| ].\n    eapply upd_preserves_match_list_ins; eauto.\n    intuition.\n  - (**r mrs_num *)\n    destruct Hst' as (_, _, _, _, _, _, Hmrs_num, _, _, _).\n    unfold Mem.loadv in *.\n    destruct Hmrs_num as (Hload & Hother).\n    unfold upd_mem; simpl.\n    split.\n\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n\n    assumption.\n  - (**r mrs_block *)\n    destruct Hst' as (_, _, _, _, _, _, _, Hmrs_block, _, _).\n    unfold Mem.loadv in *.\n    unfold match_regions in *.\n    unfold upd_mem; simpl.\n    destruct Hmrs_block as (Hload & Hlen & Hmax & Hmatch).\n    split.\n\n    eapply Mem.load_store_other in Hstore_m2.\n    rewrite Hstore_m2.\n    assumption.\n    intuition.\n\n    split; [assumption| ].\n    split; [assumption| ].\n    eapply upd_preserves_match_list_region; eauto.\n    intuition.\n  - (**r range_perm *)\n    destruct Hst' as (_, _, _, _, _, _, _, _, Hrange_perm, _).\n    unfold size_of_state in *.\n    unfold upd_mem.\n    simpl mrs_num.\n    simpl ins_len.\n    destruct Hrange_perm as (Hrange_perm_st & Hrange_perm_mrs & Hrange_perm_ins).\n    split; [eapply store_range_perm; eauto; intuition |].\n    split; eapply store_range_perm; eauto; intuition.\n  - (**r valid_block *)\n    destruct Hst' as (_, _, _, _, _, _, _, _, _, Hvalid_block).\n    unfold upd_mem; simpl.\n    destruct Hvalid_block as (Hinvalid_blk & Hneq_blk & Hvalid).\n    destruct Hinvalid_blk as (Hinvalid_blk0 & Hinvalid_blk1 & Hinvalid_blk2).\n    split.\n    split.\n    intro H; apply Hinvalid_blk0; eapply Mem.store_valid_block_2; eauto.\n    split.\n    intro H; apply Hinvalid_blk1; eapply Mem.store_valid_block_2; eauto.\n    intro H; apply Hinvalid_blk2; eapply Mem.store_valid_block_2; eauto.\n    split; [assumption | ].\n    intros.\n    specialize (Hvalid b0 H).\n    eapply Mem.store_valid_block_2 in Hstore_m2; eauto.\n    specialize (Hvalid Hstore_m2).\n    eapply Mem.store_valid_block_1 in Hstore; eauto.\nQed.\n\nClose Scope Z_scope.\n\n#[global] Notation dcons := (DList.DCons (F:= fun x => x -> Inv State.state)).\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/MatchState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.17540525223093673}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Object Primitives                                      *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AuxStateDataType.\nRequire Import FlatMemory.\nRequire Import AbstractDataType.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Constant.\nRequire Import RealParams.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n(*Require Import CalRealIntelModule.*)\nRequire Import liblayers.compat.CompatGenSem.\n(*\nRequire Import ObjLMM.\nRequire Import ObjVMM.*)\n\nSection OBJ_Arg.\n\n  Function uctx_arg1_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_EAX (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_arg2_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_EBX (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_arg3_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_ECX (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_arg4_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_EDX (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_arg5_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_ESI (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_arg6_spec (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get U_EDI (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function uctx_set_errno_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_EAX (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  Function uctx_set_retval1_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_EBX (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  Function uctx_set_retval2_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_ECX (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  Function uctx_set_retval3_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_EDX (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  Function uctx_set_retval4_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_ESI (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  Function uctx_set_retval5_spec (n: Z) (adt : RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        let uctx := ZMap.get (cid adt) (uctxt adt) in\n        let uctx':= ZMap.set U_EDI (Vint (Int.repr n)) uctx in\n        Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n      | _ => None\n    end.\n\n  (*Function la2pa_resv_spec (vadr : Z) (adt: RData) : option (RData * Z):=\n    match (pg adt, ptRead_spec (cid adt) vadr adt) with\n      | (true, Some padr) =>\n        if zeq padr 0 then\n          match ptResv_spec (cid adt) vadr PT_PERM_PTU adt with\n            | Some (adt', _) =>\n              match ptRead_spec (cid adt) vadr adt' with\n                | Some padr' => \n                  if zlt_lt 0 padr' maxpage then\n                    Some (adt', padr' * PgSize + (vadr mod PgSize))\n                  else None\n                | _ => None\n              end\n            | _ => None\n          end\n        else\n          if zlt_lt 0 padr maxpage then\n            Some (adt, padr * PgSize + (vadr mod PgSize))\n          else None\n      | _ => None\n    end.*)\n\nEnd OBJ_Arg.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import AuxLemma.\nRequire Import Observation.\n\nSection OBJ_SIM.\n\n  Context `{Hobs: Observation}.\n\n  Context `{data : CompatData(Obs:=Obs) RData}.\n  Context `{data0 : CompatData(Obs:=Obs) RData}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Notation HDATAOps := (cdata (cdata_prf := data) RData).\n  Notation LDATAOps := (cdata (cdata_prf := data0) RData).\n\n  Context `{rel_prf: CompatRel _ (Obs:=Obs) (memory_model_ops:= memory_model_ops) _\n                               (stencil_ops:= stencil_ops) HDATAOps LDATAOps}.\n\n  Local Open Scope Z.\n\n  Context {re1: relate_impl_iflags}.\n  Context {re2: relate_impl_cid}.\n  Context {re3: relate_impl_uctxt}.\n\n  Definition uctx_argn_spec n (adt : RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        match (ZMap.get n (ZMap.get (cid adt) (uctxt adt))) with\n          | Vint n => Some (Int.unsigned n)\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Lemma uctx_argn_exist:\n    forall n, 0 <= n < UCTXT_SIZE ->\n    forall s habd z labd f,\n      uctx_argn_spec n habd = Some z ->\n      0 <= cid habd < num_proc ->\n      relate_AbData s f habd labd ->\n      uctx_argn_spec n labd = Some z.\n  Proof.\n    unfold uctx_argn_spec in *. intros.\n    exploit relate_impl_iflags_eq; eauto. inversion 1.\n    exploit relate_impl_cid_eq; eauto. intros.\n    exploit relate_impl_uctxt_eq; eauto.\n    revert H0; subrewrite. inversion 1; subdestruct.\n    inv HQ. inv H6. reflexivity.\n  Qed.\n\n  Lemma uctx_argn_sim:\n    forall n, 0 <= n < UCTXT_SIZE ->\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem (uctx_argn_spec n))\n          (id \u21a6 gensem (uctx_argn_spec n)).\n  Proof.\n    intros ? valid_n ? valid_cid.\n    layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n    match_external_states_simpl.\n    erewrite uctx_argn_exist; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma uctx_arg1_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg1_spec)\n          (id \u21a6 gensem uctx_arg1_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Lemma uctx_arg2_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg2_spec)\n          (id \u21a6 gensem uctx_arg2_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Lemma uctx_arg3_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg3_spec)\n          (id \u21a6 gensem uctx_arg3_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Lemma uctx_arg4_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg4_spec)\n          (id \u21a6 gensem uctx_arg4_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Lemma uctx_arg5_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg5_spec)\n          (id \u21a6 gensem uctx_arg5_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Lemma uctx_arg6_sim:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_arg6_spec)\n          (id \u21a6 gensem uctx_arg6_spec).\n  Proof.\n    apply uctx_argn_sim.\n    split; [ discriminate | reflexivity ].\n  Qed.\n\n  Section UCTX_SET_REGK_SIM.\n    Variable k : Z.\n    (* Hypothesis k_range : 0 <= k < UCTXT_SIZE. *)\n\n    Definition uctx_set_regk_spec (n: Z) (adt : RData) : option RData :=\n      match (ikern adt, pg adt, ihost adt) with\n        | (true, true, true) =>\n          let uctx := ZMap.get (cid adt) (uctxt adt) in\n          let uctx':= ZMap.set k (Vint (Int.repr n)) uctx in\n          Some (adt {uctxt: ZMap.set (cid adt) uctx' (uctxt adt)})\n        | _ => None\n      end.\n\n    Lemma uctx_set_regk_exist:\n      forall s habd habd' labd n f,\n        uctx_set_regk_spec n habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> 0 <= cid habd < num_proc\n        -> exists labd', uctx_set_regk_spec n labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold uctx_set_regk_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_cid_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_uctxt_update; try assumption.\n      unfold uctxt_inj; intros.\n      destruct (zeq i (cid labd)) as [ -> | ? ];\n        [ rewrite 2 ZMap.gss\n        | rewrite 2 ZMap.gso; try eapply relate_impl_uctxt_eq; eassumption ].\n      destruct (zeq j k) as [ -> | ? ];\n        [ rewrite 2 ZMap.gss; constructor\n        | rewrite 2 ZMap.gso; try eapply relate_impl_uctxt_eq; eassumption ].\n    Qed.\n\n    Context {mt1: match_impl_uctxt}.\n\n    Lemma uctx_set_regk_match:\n      forall s d d' m n f,\n        uctx_set_regk_spec n d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold uctx_set_regk_spec; intros. subdestruct; inv H; trivial.\n      eapply match_impl_uctxt_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) uctx_set_regk_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) uctx_set_regk_spec}.\n\n    Lemma uctx_set_regk_sim:\n      forall id,\n        (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                    0 <= cid d1 < num_proc) ->\n        sim (crel RData RData) (id \u21a6 gensem uctx_set_regk_spec)\n            (id \u21a6 gensem uctx_set_regk_spec).\n    Proof.\n      intros ? valid_cid. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit uctx_set_regk_exist; eauto; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply uctx_set_regk_match; eauto.\n    Qed.\n\n  End UCTX_SET_REGK_SIM.\n\n  Lemma uctx_set_errno_sim\n      {mt1: match_impl_uctxt}\n      {inv: PreservesInvariants (HD:= data) uctx_set_errno_spec}\n      {inv0: PreservesInvariants (HD:= data0) uctx_set_errno_spec}:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_set_errno_spec)\n          (id \u21a6 gensem uctx_set_errno_spec).\n  Proof uctx_set_regk_sim U_EAX.\n\n  Lemma uctx_set_retval1_sim\n      {mt1: match_impl_uctxt}\n      {inv: PreservesInvariants (HD:= data) uctx_set_retval1_spec}\n      {inv0: PreservesInvariants (HD:= data0) uctx_set_retval1_spec}:\n    forall id,\n      (forall d1, high_level_invariant (CompatDataOps:= data_ops) d1 ->\n                  0 <= cid d1 < num_proc) ->\n      sim (crel RData RData) (id \u21a6 gensem uctx_set_retval1_spec)\n          (id \u21a6 gensem uctx_set_retval1_spec).\n  Proof uctx_set_regk_sim U_EBX.\n\nEnd OBJ_SIM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjArg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17534290043917716}}
{"text": "(* The intermediate language of our JIT *)\n(* Designed to make speculative optimizations easier *)\n(* Inspired by CompCert's RTL and Sourir *)\n(* At first, input programs have no optimized versions. *)\n(* The framestate insertion inserts framestate instructions *)\n(* Dynamic Optimizations and Assume Insertion modify a specIR program *)\n(* Lowering transforms a specIR program into a lowered one with no framestate *)\n\nRequire Export String.\nRequire Export ZArith.\nRequire Export Znumtheory.\nRequire Export List.\nRequire Export Maps.\nRequire Export common.\nRequire Export events.\nRequire Export values.\nRequire Export Smallstep.\n\n(** * Syntax  *)\n(* Registers *)\nDefinition reg: Type := positive.\n\n(* Operands are either registers names or integer constants or addresses *)\nInductive op: Type :=\n| Reg : reg -> op\n| Cst: value -> op.\n\n(* Labels of the Control-Flow Graph *)\nDefinition label: Type := positive.\n\n(* Operations and Expressions *)\nInductive bin_operation: Type :=\n| Plus : bin_operation          (* CompCert's \"Plus\" notation for smallstep has been renamed \"SPlus\" *)\n| Minus : bin_operation\n| Mult : bin_operation\n| Gt : bin_operation\n| Lt : bin_operation\n| Geq : bin_operation\n| Leq : bin_operation\n| Eq: bin_operation.\n\nInductive un_operation: Type :=\n| UMinus : un_operation\n| Neg : un_operation\n| Assign : un_operation.\n\nInductive expr: Type :=\n| Binexpr: bin_operation -> op -> op -> expr\n| Unexpr: un_operation -> op -> expr.\n\n(* Function names/identifiers *)\nDefinition fun_id: Type := positive.\n\n(* Assigning multiple expressions to multiple registers for parallel assignment *)\nDefinition movelist: Type := list (reg * expr).\n\n(* Binding registers to an expression, for deoptimizations *)\nDefinition varmap: Type := list (reg * expr).\n\nDefinition empty_varmap: varmap := nil.\n\n(* Where to go to when deoptimizing *)\nDefinition deopt_target: Type := fun_id * label.\n\n(* Information to synthesize new stack frames in an Assume instruction *)\nDefinition synth_frame: Type :=\n  deopt_target * reg * varmap.\n\n(* Instructions as a Control Flow Graph *)\nInductive instruction: Type :=\n| Nop : option hint -> label -> instruction\n(* [Nop oh next] simply goes to the [next] instruction. [oh] may be a hint for the profiler *)\n| Op: expr -> reg -> label -> instruction\n(* [Op expr reg next] evaluates [expr], puts the result in [reg] and moves to [next] *)\n| Move: movelist -> label -> instruction\n(* [Move l next] updates the left-hand side of [l] with an evaluation of its right-hand side *)\n| Call : fun_id -> list expr -> reg -> label -> instruction\n(* [Call f exl retreg next] puts the returned value of [(f exl)] in [retreg] and moves to [next] *)\n| IReturn : expr -> instruction\n(* [Return expr] evaluates [expr] and returns it *)\n| Cond : expr -> label -> label -> instruction\n(* [Cond expr iftrue iffalse] evaluates [expr]. If it is 0, move to [iffalse], else to [iftrue] *)\n| Store : expr -> expr -> label -> instruction\n(* [Store expr1 expr2 next] stores the value of [expr1] in address [expr2] and moves to [next] *)\n| Load : expr -> reg -> label -> instruction\n(* [Load expr reg next] loads the value at address [expr] puts it in reg [reg], and moves to [next] *)\n| Printexpr : expr -> label -> instruction\n(* [Printexpr expr next] prints the value of [expr] and moves to [next] *)\n| Printstring : string -> label -> instruction\n(* [Printstring s next] prints the string [s] then moves to [next] *)\n| Framestate : deopt_target -> varmap -> list synth_frame -> label -> instruction\n(* [Framestate  (f,l) vm sl next] can either move to [next] or deoptimize to the base version of *)\n(* function [f] label [l], reconstructing the original environment with [vm] and [sl] *)\n| Assume : list expr -> deopt_target -> varmap -> list synth_frame -> label -> instruction\n(* [Assume le (f,l) vm sl next] first evaluates [le]. If all expressions are true then, *)\n(* it moves to [next]. Otherwise, we deoptimize to the base version of function [f] label [l] *)\n(* with the registers updated with the evaluation of [vm] *)\n(* each element of [sl] corresponds to a new stackframe to be synthesized *)\n| Fail : string -> instruction.\n(* [Fail s] has blocking semantics. The interpreter should fail with the error message s *)\n\n(* Successors of an instruction *)\n(* Only inside the specIR program, does not account for deoptimization *)\nDefinition instr_succ (i:instruction): list label :=\n  match i with\n  | Nop _ next => next::nil\n  | Op _ _ next => next::nil\n  | Move _ next => next::nil\n  | Call _ _ _ next => next::nil\n  | IReturn _ => nil\n  | Cond _ next1 next2 => next1::(next2::nil)\n  | Store _ _ next => next::nil\n  | Load _ _ next => next::nil\n  | Printexpr _ next => next::nil\n  | Printstring _ next => next::nil\n  | Framestate _ _ _ next => next::nil \n  | Assume _ _ _ _ next => next::nil\n  | Fail _ => nil\n  end.\n\n(** * Multi-language Programs  *)\n\n(* Some code for a function is a correspondence between labels and instructions *)\nDefinition code: Type := PTree.t instruction.\n\n(* A version is some code and an entry point *)\nRecord version: Type := mk_version {\n  ver_code: code;\n  ver_entry: label;\n}.\n\n(* Defining base versions: no speculative (Framestate & Assume) instructions *)\nInductive is_spec: instruction -> Prop :=\n| spec_assume: forall g tgt vm sl next,\n    is_spec (Assume g tgt vm sl next)\n| spec_framestate: forall tgt vm sl next,\n    is_spec (Framestate tgt vm sl next).           \n\nDefinition base_code (c:code): Prop :=\n  forall (pc:label) (i:instruction), c!pc = Some i -> ~ (is_spec i).\n\nDefinition base_version (v:version): Prop :=\n  base_code (ver_code v).\n\n(* A function contains a baseline version of the code, and may contain a speculative version as well if it has been optimized *)\nRecord function': Type := mk_function {\n  fn_params : list reg;\n  fn_base : version;\n  fn_opt : option version;\n  base_no_spec: base_version fn_base\n}.\n\nDefinition function: Type := function'.\n\n(* A program is a list of functions, associated with a fun_id, and the main function's id *)\nRecord program: Type := mk_program {\n  prog_main : fun_id;\n  prog_funlist : PTree.t function;\n}.\n\n(** * Semantics  *)\nDefinition find_function_list (fid:fun_id) (funlist:PTree.t function): option function :=\n  funlist ! fid.\n\nDefinition find_function (fid:fun_id) (p:program): option function :=\n  find_function_list fid (prog_funlist p).\n\n(* Find a base version given a function id and a program *)\nDefinition find_base_version (fid:fun_id) (p:program): option version :=\n  match (find_function fid p) with\n  | None => None\n  | Some f => Some (fn_base f)\n  end.\n\n(* Find current version in a function *)\nDefinition current_version (f:function): version :=\n  match (fn_opt f) with\n  | None => fn_base f\n  | Some o => o\n  end.\n\n(* Find the current version of a function in a program *)\nDefinition find_currver (fid:fun_id) (p:program): option version :=\n  match (find_function fid p) with\n  | None => None\n  | Some f => Some (current_version f)\n  end.\n\n(* The state of all registers *)\nDefinition reg_map: Type := PTree.t value.\nDefinition empty_regmap: reg_map := PTree.empty value.\n\n(* Stackframes *)\n(* Return register, calling function, next instruction in calling function, state of the registers in calling function *)\nInductive stackframe: Type :=\n| Stackframe : reg -> version -> label -> reg_map -> stackframe.\n\n(* The stack model is simply a list of stack frames *)\n(* The top of the stack is the head of the list *)\nDefinition stack: Type := list stackframe.\n\n\n(** * Memory Model  *)\n(* These are external parameters *)\nParameter mem_state: Type.\nParameter initial_memory: mem_state.\nParameter Load_: mem_state -> value -> option value.\nParameter Store_: mem_state -> value -> value -> option mem_state.\n\n\n(** * Semantics sates *)\nInductive state: Type :=\n| State:\n    forall (s:stack)                 (* call stack *)\n           (v:version)          (* current version being executed *)\n           (pc:label)           (* current label *)\n           (rm:reg_map)         (* state of the registers *)\n           (ms:mem_state),      (* state of the memory *)\n      state\n| Final:                        (* go into final state after returning from function main *)\n    forall (v:value)\n           (ms:mem_state),\n      state.\n\n(* Final value if it exists *)\nDefinition final_value (s:state): option value :=\n  match s with\n  | State _ _ _ _ _ => None\n  | Final v _ => Some v\n  end.\n\n(* Initial state of a program *)\nInductive initial_state (p:program): state -> Prop :=\n| intro_init_state:\n    forall f v\n      (FINDF: find_function (prog_main p) p = Some f)\n      (NOARGS: fn_params f = nil) (* the main function should have no parameters *)\n      (CURRVER: current_version f = v),\n      initial_state p (State nil v (ver_entry v) empty_regmap initial_memory).\n\nInductive final_state (p:program): state -> value -> Prop :=\n| intro_final_state:\n    forall v ms,\n      final_state p (Final v ms) v.\n\n(* Evaluating operands *)\nInductive eval_op : op -> reg_map -> value -> Prop :=\n| Eval_const: forall n rm, eval_op (Cst n) rm n\n| Eval_reg: forall v r rm\n              (GETRM: rm # r = Some v),\n    eval_op (Reg r) rm v.\n\n(* Conditions are done on values *)\nDefinition bool_to_val (b:bool): value :=\n  match b with\n  | true => Vint 1\n  | false => Vint 0\n  end.\n\n\n(* Evaluating Binary operations on values *)\nInductive eval_binop_values: bin_operation -> value -> value -> value -> Prop :=\n| Eval_plus : forall v1 v2, eval_binop_values Plus (Vint v1) (Vint v2) (Vint (v1+v2))\n| Eval_minus : forall v1 v2, eval_binop_values Minus (Vint v1) (Vint v2) (Vint (v1-v2))\n| Eval_mult : forall v1 v2, eval_binop_values Mult (Vint v1) (Vint v2) (Vint (v1*v2))\n| Eval_gt : forall v1 v2, eval_binop_values Gt (Vint v1) (Vint v2) (bool_to_val(Z.gtb v1 v2))\n| Eval_lt : forall v1 v2, eval_binop_values Lt (Vint v1) (Vint v2) (bool_to_val(Z.ltb v1 v2))\n| Eval_geq : forall v1 v2, eval_binop_values Geq (Vint v1) (Vint v2) (bool_to_val(Z.geb v1 v2))\n| Eval_leq : forall v1 v2, eval_binop_values Leq (Vint v1) (Vint v2) (bool_to_val(Z.leb v1 v2))\n| Eval_eq : forall v1 v2, eval_binop_values Eq (Vint v1) (Vint v2) (bool_to_val(Z.eqb v1 v2)).\n\n\n(* Evaluating Binary operations *)\nInductive eval_binop: bin_operation -> op -> op -> reg_map -> value -> Prop :=\n| Eval_binop:\n    forall binop o1 o2 v1 v2 v rm\n      (EVALL: eval_op o1 rm v1)\n      (EVALR: eval_op o2 rm v2)\n      (EVALV: eval_binop_values binop v1 v2 v),\n      eval_binop binop o1 o2 rm v.\n\n(* Negation of a value *)\nDefinition int_neg (i:Z) : Z :=\n  match i with\n  | 0 => 1\n  | _ => 0\n  end.\n\n(* Evaluating Unary operations on a value *)\nInductive eval_unop_value: un_operation -> value -> value -> Prop :=\n| Eval_uminus: forall v, eval_unop_value UMinus (Vint v) (Vint (-v))\n| Eval_neg: forall v, eval_unop_value Neg (Vint v) (Vint (int_neg v))\n| Eval_assign: forall v, eval_unop_value Assign v v. \n\n(* Evaluating Unary operations *)\nInductive eval_unop: un_operation -> op -> reg_map -> value -> Prop :=\n| Eval_unop: forall unop o rm v vres\n    (EVAL: eval_op o rm v)\n    (EVALV: eval_unop_value unop v vres),\n    eval_unop unop o rm vres.\n\n(* Evaluating expressions *)\nInductive eval_expr: expr -> reg_map -> value -> Prop :=\n| expr_binop:\n    forall binop o1 o2 rm v\n      (EVAL: eval_binop binop o1 o2 rm v),\n      eval_expr (Binexpr binop o1 o2) rm v\n| expr_unop:\n    forall unop o rm v\n      (EVAL: eval_unop unop o rm v),\n      eval_expr (Unexpr unop o) rm v.\n      \n(* Computing the next pc of [Cond op iftrue iffalse] when [op] evaluates to [v] *)\nDefinition pc_cond (v:value) (iftrue:label) (iffalse:label): label :=\n  match v with\n  | Vint 0 => iffalse\n  | Vint _ => iftrue\n  end.\n\n(* Checks if a list of expressions are all true (some Vint != Vint 0) *)\n(* Used to verify if the guard of an Assume should pass *)\n(* If an evaluation fails,  the list does not evaluate to a boolean *)\nInductive eval_list_expr: list expr -> reg_map -> bool -> Prop :=\n| eval_nil:\n    forall rm, eval_list_expr nil rm true\n| eval_cons_false:\n    forall ex le rm\n      (EVAL: eval_expr ex rm (Vint 0)),\n      eval_list_expr (ex::le) rm false\n| eval_cons_true:\n    forall ex le rm v res\n      (EVALH: eval_expr ex rm (Vint v))\n      (TRUE: Zne v 0)                (* v <> 0 *)\n      (EVALL: eval_list_expr le rm res),\n      eval_list_expr (ex::le) rm res.      \n\n(* evaluates a list of operands (arguments) *)\nInductive eval_list: list expr -> reg_map -> list value -> Prop :=\n| eval_list_nil:\n    forall rm, eval_list nil rm nil\n| eval_list_cons:\n    forall le rm lv ex v\n      (EVALH: eval_expr ex rm v)\n      (EVALL: eval_list le rm lv),\n      eval_list (ex::le) rm (v::lv).\n\n(* Initialize the register map when calling a function *)\nFixpoint init_regs (valist:list value) (params:list reg): option reg_map :=\n  match params with\n  | nil => match valist with\n           | nil => Some empty_regmap\n           | _ => None          (* too many arguments *)\n           end\n  | par::params' => match valist with\n                    | nil => None (* not enough arguments *)\n                    | val::valist' => match (init_regs valist' params') with\n                                     | None => None\n                                     | Some rm => Some (rm # par <- val)\n                                     end\n                    end\n  end.\n\n(* Updates the reg_map [rm] with the bindings of [ml] *)\n(* [rmeval] is the original [rm], used to evaluate the operands of [vm] *)\nInductive update_movelist' : movelist -> reg_map -> reg_map -> reg_map -> Prop :=\n| eval_ml_nil: forall rm rmeval,\n    update_movelist' nil rmeval rm rm\n| eval_ml_cons: forall r e ml v rmeval rm rm'\n    (EVAL: eval_expr e rmeval v)\n    (UPDATE: update_movelist' ml rmeval rm rm'),\n    update_movelist' ((r,e)::ml) rmeval rm (rm' # r <- v).\n\nDefinition update_movelist (ml:movelist) (rm:reg_map) (rm':reg_map): Prop :=\n  update_movelist' ml rm rm rm'.\n\n(** * Deoptimization Semantics  *)\n(* Creates a new Register Mapping given a varmap *)\nInductive update_regmap: varmap -> reg_map -> reg_map -> Prop :=\n| update_nil: forall rm,\n    update_regmap nil rm empty_regmap (* now we construct from the empty regmap *)\n| update_cons: forall r e vm v rm rm'\n    (EVAL: eval_expr e rm v)\n    (UPDATE: update_regmap vm rm rm'),\n    update_regmap ((r,e)::vm) rm (rm' # r <- v).\n      \n\n(* [synthesize_frame p rm sl s]: the list [sl] synthesizes the stack [s] under [rm] and [p] *)\nInductive synthesize_frame: program -> reg_map -> list synth_frame -> stack -> Prop :=\n| Synth_nil: forall p rm,\n    synthesize_frame p rm nil nil\n| Synth_cons: forall p s rm sl f l r vm update version\n    (UPDATE: update_regmap vm rm update)\n    (FINDV: find_base_version f p = Some version)\n    (SYNTH: synthesize_frame p rm sl s),\n    synthesize_frame p rm (((f,l),r,vm)::sl) ((Stackframe r version l update)::s).\n\n(** * Small-step transition system *)\n(* [step p s1 e s2] means that in program [p], state [s1] transitions to [s2] with event [e] *)\n(* This is the semantics of lowered programs (no Framestates) *)\nInductive lowered_step: program -> state -> trace -> state -> Prop :=\n| exec_Nop:\n    forall p s f pc rm ms next oh\n      (CODE: (ver_code f)!pc = Some (Nop oh next)),\n      lowered_step p (State s f pc rm ms) E0 (State s f next rm ms)\n| exec_Op:\n    forall p s f pc rm ms expr reg next v\n      (CODE: (ver_code f)!pc = Some (Op expr reg next))\n      (EVAL: eval_expr expr rm v),\n      lowered_step p (State s f pc rm ms) E0 (State s f next (rm # reg <- v) ms)\n| exec_Move:\n    forall p s f pc rm ms ml next newrm\n      (CODE: (ver_code f)!pc = Some (Move ml next))\n      (UPDATE: update_movelist ml rm newrm),\n      lowered_step p (State s f pc rm ms) E0 (State s f next newrm ms)\n| exec_Cond:\n    forall p s f pc rm ms expr iftrue iffalse newpc v\n      (CODE: (ver_code f)!pc = Some (Cond expr iftrue iffalse))\n      (EVAL: eval_expr expr rm v)\n      (NEXT: pc_cond v iftrue iffalse = newpc),\n      lowered_step p (State s f pc rm ms) E0 (State s f newpc rm ms)\n| exec_Call:\n    forall p s f pc rm ms fid args retreg next func valist newrm version\n      (CODE: (ver_code f)!pc = Some (Call fid args retreg next))\n      (FINDF: find_function fid p = Some func)\n      (CURRVER: current_version func = version)\n      (EVALL: eval_list args rm valist)\n      (INIT_REGS: init_regs valist func.(fn_params) = Some newrm),\n      lowered_step p (State s f pc rm ms) E0 (State (Stackframe retreg f next rm ::s) version version.(ver_entry) newrm ms)\n| exec_Return:\n    forall p s fcurr fprev pc next rmcurr rmprev ms retex retval retreg\n      (CODE: (ver_code fcurr)!pc = Some (IReturn retex))\n      (EVAL: eval_expr retex rmcurr retval),\n      lowered_step p (State (Stackframe retreg fprev next rmprev ::s) fcurr pc rmcurr ms) E0\n           (State s fprev next (rmprev # retreg <- retval) ms)\n| exec_Return_Final:\n    forall p f pc rm ms rex retval\n      (CODE: (ver_code f)!pc = Some (IReturn rex))\n      (EVAL: eval_expr rex rm retval),\n      lowered_step p (State nil f pc rm ms) E0 (Final retval ms)\n| exec_Printexpr:\n    forall p s f pc rm ms expr next printval\n      (CODE: (ver_code f)!pc = Some (Printexpr expr next))\n      (EVAL: eval_expr expr rm printval),\n      lowered_step p (State s f pc rm ms) ((Valprint printval)::E0) (State s f next rm ms)\n| exec_Printstring:\n    forall p s f pc rm ms str next\n      (CODE: (ver_code f)!pc = Some (Printstring str next)),\n      lowered_step p (State s f pc rm ms) ((Stringprint str)::E0) (State s f next rm ms)\n| exec_Store:\n    forall p s f pc rm ms expr1 expr2 next val addr newms\n      (CODE: (ver_code f)!pc = Some (Store expr1 expr2 next))\n      (EVAL_ST: eval_expr expr1 rm val)\n      (EVAL_AD: eval_expr expr2 rm addr)\n      (STORE: Store_ ms addr val = Some newms), (* using the Store_ parameter *)\n      lowered_step p (State s f pc rm ms) E0 (State s f next rm newms)\n| exec_Load:\n    forall p s f pc rm ms reg next expr addr val\n      (CODE: (ver_code f)!pc = Some (Load expr reg next))\n      (EVAL: eval_expr expr rm addr)\n      (LOAD: Load_ ms addr = Some val), (* using the Load_ parameter *)\n      lowered_step p (State s f pc rm ms) E0 (State s f next (rm # reg <- val) ms)\n| exec_Assume_holds:\n    forall p s f pc rm ms le tgt vm sl next\n      (CODE: (ver_code f)! pc = Some (Assume le tgt vm sl next))\n      (ASSUME_TRUE: eval_list_expr le rm true),\n      lowered_step p (State s f pc rm ms) E0 (State s f next rm ms)\n| exec_Assume_fails:\n    forall p s f pc rm ms le fa la vm sl next newver newrm synth\n      (CODE: (ver_code f)! pc = Some (Assume le (fa,la) vm sl next))\n      (ASSUME_FAILS: (eval_list_expr le rm false)) (* at least one assertion fails *)\n      (FINDF: find_base_version fa p = Some newver) (* the version we deoptimize to *)\n      (UPDATE: update_regmap vm rm newrm) (* updating the regmap as indicated in the assume *)\n      (SYNTH: synthesize_frame p rm sl synth), (* new synthesized stackframes *)\n      lowered_step p (State s f pc rm ms) E0 (State (synth++s) newver la newrm ms).\n\n(* Semantics given a lowered program *)\nDefinition lowered_sem (p:program) : semantics :=\n  Semantics_gen lowered_step (initial_state p) (final_state p) p.\n\n(** *  Non-deterministic semantics for speculative code *)\nInductive deopt_conditions : program -> state -> label -> stack -> version -> label -> reg_map -> Prop :=\n| deopt_cond:\n    forall p s f pc rm ms fa la vm sl next newver newrm synth\n      (CODE: (ver_code f)! pc = Some (Framestate (fa,la) vm sl next))\n      (FINDF: find_base_version fa p = Some newver) (* the version we deoptimize to *)\n      (UPDATE: update_regmap vm rm newrm) (* updating the regmap as indicated in the assume *)\n      (SYNTH: synthesize_frame p rm sl synth), (* new synthesized stackframes *)\n      deopt_conditions p (State s f pc rm ms) next synth newver la newrm.\n\n(* Non-deterministic semantics for the Framestate *)\nInductive specir_step: program -> state -> trace -> state -> Prop :=\n| nd_exec_lowered:\n    forall p s t s'\n      (STEP: lowered_step p s t s'),\n      specir_step p s t s'\n| nd_exec_Framestate_go_on:\n    forall p s f pc rm ms la next newver newrm synth\n      (DEOPT_COND: deopt_conditions p (State s f pc rm ms) next synth newver la newrm),\n      specir_step p (State s f pc rm ms) E0 (State s f next rm ms)\n| nd_exec_Framestate_deopt:\n    forall p s f pc rm ms la next newver newrm synth\n      (DEOPT_COND: deopt_conditions p (State s f pc rm ms) next synth newver la newrm),\n      specir_step p (State s f pc rm ms) E0 (State (synth++s) newver la newrm ms).\n\nDefinition specir_sem (p:program) : semantics :=\n  Semantics_gen specir_step (initial_state p) (final_state p) p.\n\n(** *  Loud semantics *)\n(* Semantics that explicitly outputs Go_on or Deopt events when going through Framestates *)\n(* This make the semantics determinate *)\n\n(* Semantics where the Framestate produce observable events *)\nInductive loud_step: program -> state -> trace -> state -> Prop :=\n| loud_exec_lowered:\n    forall p s t s'\n      (STEP: lowered_step p s t s'),\n      loud_step p s t s'\n| loud_exec_Framestate_go_on:\n    forall p s f pc rm ms la next newver newrm synth\n      (DEOPT_COND: deopt_conditions p (State s f pc rm ms) next synth newver la newrm),\n      loud_step p (State s f pc rm ms) (Loud_Go_on::nil) (State s f next rm ms)\n| loud_exec_Framestate_deopt:\n    forall p s f pc rm ms la next newver newrm synth\n      (DEOPT_COND: deopt_conditions p (State s f pc rm ms) next synth newver la newrm),\n      loud_step p (State s f pc rm ms) (Loud_Deopt::nil) (State (synth++s) newver la newrm ms).\n\nDefinition loud_sem (p:program) : semantics :=\n  Semantics_gen loud_step (initial_state p) (final_state p) p.\n\n\n(** * Helper functions  *)\n(* Replacing the optimized version of a function *)\nProgram Definition set_version_function (v:version) (f:function): function :=\n  mk_function (fn_params f) (fn_base f) (Some v) _.\nNext Obligation.\n  apply (base_no_spec f).\nQed.\n\n(* Removes the optimized version *)\nProgram Definition remove_opt_function (f:function): function :=\n  mk_function (fn_params f) (fn_base f) None _.\nNext Obligation.\n  apply (base_no_spec f).\nQed.\n\n(* Update a fun_list with the new function containing the new version *)\nDefinition set_version_funlist (fid:fun_id) (v:version) (fl:PTree.t function): PTree.t function :=\n  match (fl ! fid) with\n  | None => fl\n  | Some f => fl # fid <- (set_version_function v f)\n  end.\n\nDefinition remove_opt_funlist (fid:fun_id) (fl:PTree.t function): PTree.t function :=\n  match (fl ! fid) with\n  | None => fl\n  | Some f => fl # fid <- (remove_opt_function f)\n  end.\n\n(* Updates versions in a program. *)\nDefinition set_version (p:program) (fid:fun_id) (v:version): program :=\n  mk_program (prog_main p) (set_version_funlist fid v (prog_funlist p)).\n\nDefinition remove_opt (p:program) (fid:fun_id): program :=\n  mk_program (prog_main p) (remove_opt_funlist fid (prog_funlist p)).\n\n(* Max positive used in a PTree *)\nFixpoint max_pos' {A:Type} (vl:list (positive * A)): positive :=\n  match vl with\n  | nil => xH\n  | (vid,v)::vl' => Pos.max vid (max_pos' vl')\n  end.\n\nDefinition max_pos {A:Type} (tree:PTree.t A): positive :=\n  max_pos' (PTree.elements tree).\n\nDefinition max_label (c:code): label :=\n  max_pos c.\n\n(** * Finding fresh labels  *)\n(* Finds a label unused in c *)\nDefinition fresh_label' (c:code) :=\n  Pos.succ (max_label c).\n(* This simple version is often not good enough *)\n(* As the Kildall fixpoint solver is more efficient on programs with sorted labels *)\n(* It is often better to insert new instructions at a label that corresponds to its position in the code *)\n(* We use this other fresh_label function that tries to insert at a given label *)\n(* If it fails (the label is already used), it defaults to fresh_label' *)\n\n(* The number of tries before defaulting to fresh_label' *)\nParameter fuel_fresh: nat.\n\n(* Takes a suggested label *)\nFixpoint fresh_label_fuel (fuel:nat) (sug:label) (c:code): label :=\n  match fuel with\n  | O => fresh_label' c\n  | S fuel' =>\n    match (c!sug) with\n    | None => sug\n    | Some _ => fresh_label_fuel fuel' (Pos.succ sug) c\n    end\n  end.\n\nDefinition fresh_label (sug:label) (c:code): label :=\n  fresh_label_fuel fuel_fresh sug c.\n\n\n(** * Lowered Programs  *)\n(* Lowered Programs do not contain the Framestate instruction anymore *)\nInductive is_fs: instruction -> Prop :=\n| Is_Fs: forall tgt vm sl next,\n    is_fs (Framestate tgt vm sl next).\n\n(* Some lowered code has no Framestate instruction *)\nDefinition lowered_code (c:code): Prop :=\n  forall (pc:label) (i:instruction), c!pc = Some i -> ~ (is_fs i).\n\nDefinition lowered_version (v:version): Prop :=\n  lowered_code (ver_code v).\n\nDefinition lowered_function (f:function): Prop :=\n  forall v, fn_opt f = Some v -> lowered_version v.\n\nDefinition lowered_program (p:program): Prop :=\n  forall fid f, find_function fid p = Some f -> lowered_function f.\n\n\n(** * Input Programs *)\n(* An input program does not have any optimized version *)\nDefinition input_function (f:function): Prop :=\n  (fn_opt f) = None.\n\nDefinition input_program (p:program): Prop :=\n  forall fid f, find_function fid p = Some f -> input_function f.\n\n\n", "meta": {"author": "Aurele-Barriere", "repo": "CoreJIT", "sha": "8740d4149be649d0746d9f0d2d759b387a8f3246", "save_path": "github-repos/coq/Aurele-Barriere-CoreJIT", "path": "github-repos/coq/Aurele-Barriere-CoreJIT/CoreJIT-8740d4149be649d0746d9f0d2d759b387a8f3246/src/coqjit/specIR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.17533479990629858}}
{"text": "From iris.base_logic Require Import invariants.\nFrom iris_ni.logrel Require Import types interp.\nFrom iris_ni.program_logic Require Import dwp heap_lang_lifting.\nFrom iris.proofmode Require Import proofmode.\nFrom iris_ni.proofmode Require Import dwp_tactics.\nFrom iris.heap_lang Require Import lang proofmode.\nFrom iris.algebra Require Import excl.\n\nFrom iris.heap_lang.lib Require Export spin_lock.\n\nSection proof.\n  Context `{!heapDG \u03a3, !lockG \u03a3}.\n\n  Variable N : namespace.\n\n  Definition lock_inv (\u03b3 : gname) (l1 l2 : loc) (R : iProp \u03a3) : iProp \u03a3 :=\n    (\u2203 b : bool, l1 \u21a6\u2097 #b \u2217 l2 \u21a6\u1d63 #b \u2217\n       if b then True else own \u03b3 (Excl ()) \u2217 R)%I.\n\n  Definition is_lock (\u03b3 : gname) (lk1 lk2 : val) (R : iProp \u03a3) : iProp \u03a3 :=\n    (\u2203 l1 l2: loc, \u231clk1 = #l1\u231d \u2227 \u231clk2 = #l2\u231d\n        \u2227 inv N (lock_inv \u03b3 l1 l2 R))%I.\n\n  Definition locked (\u03b3 : gname) : iProp \u03a3 := own \u03b3 (Excl ()).\n\n\n  Lemma newlock_spec (R : iProp \u03a3) \u03a6 :\n    R -\u2217\n    (\u2200 \u03b3 lk1 lk2, is_lock \u03b3 lk1 lk2 R -\u2217 \u03a6 lk1 lk2) -\u2217\n    DWP newlock #() & newlock #() : \u03a6.\n  Proof.\n    iIntros \"R H\u03a6\".\n    unlock newlock. dwp_pures=>/=.\n    iApply dwp_fupd.\n    pose (\u03a81 := (\u03bb v, \u2203 l : loc, \u231cv = #l\u231d \u2217 l \u21a6\u2097 #false)%I).\n    pose (\u03a82 := (\u03bb v, \u2203 l : loc, \u231cv = #l\u231d \u2217 l \u21a6\u1d63 #false)%I).\n    iApply (dwp_atomic_lift_wp \u03a81 \u03a82).\n    { rewrite /TWP1. wp_alloc l as \"Hl\".\n      iExists l. eauto with iFrame. }\n    { rewrite /TWP2. wp_alloc l as \"Hl\".\n      iExists l. eauto with iFrame. }\n    iIntros (? ?). iDestruct 1 as (l1 ->) \"Hl1\". iDestruct 1 as (l2 ->) \"Hl2\".\n    iNext. iMod (own_alloc (Excl ())) as (\u03b3) \"H\u03b3\"; first done.\n    iMod (inv_alloc N _ (lock_inv \u03b3 l1 l2 R) with \"[-H\u03a6]\") as \"#Hinv\".\n    { iIntros \"!>\". iExists false. by iFrame. }\n    iModIntro. iApply (\"H\u03a6\" $! \u03b3).\n    iExists l1,l2. eauto with iFrame.\n  Qed.\n\n  Lemma try_acquire_spec \u03b3 lk1 lk2 R \u03a6 :\n    is_lock \u03b3 lk1 lk2 R -\u2217\n    (\u2200 b : bool, (if b then locked \u03b3 \u2217 R else True) -\u2217 \u03a6 #b #b) -\u2217\n    DWP try_acquire lk1 & try_acquire lk2 : \u03a6.\n  Proof.\n    iIntros \"#Hlk H\u03a6\". iDestruct \"Hlk\" as (l1 l2 -> ->) \"#Hinv\".\n    unlock try_acquire. dwp_pures=>/=.\n    dwp_bind (CmpXchg _ _ _) (CmpXchg _ _ _).\n    iApply dwp_atomic.\n    iInv N as (b) \"(>Hl1 & >Hl2 & HR)\" \"Hcl\". iModIntro.\n    pose (\u03a81 := (\u03bb v, \u231cv = (#b, #(negb b))%V\u231d \u2217 l1 \u21a6\u2097 #true)%I).\n    pose (\u03a82 := (\u03bb v, \u231cv = (#b, #(negb b))%V\u231d \u2217 l2 \u21a6\u1d63 #true)%I).\n    iApply (dwp_atomic_lift_wp \u03a81 \u03a82 with \"[Hl1] [Hl2] [-]\").\n    { rewrite /TWP1 /\u03a81. destruct b.\n      by wp_cmpxchg_fail; iFrame.\n      by wp_cmpxchg_suc; iFrame. }\n    { rewrite /TWP2 /\u03a82. destruct b.\n      by wp_cmpxchg_fail; iFrame.\n      by wp_cmpxchg_suc; iFrame. }\n    iIntros (? ?). iDestruct 1 as (->) \"Hl1\". iDestruct 1 as (->) \"Hl2\".\n    iNext. iMod (\"Hcl\" with \"[-HR H\u03a6]\") as \"_\".\n    { iNext. iExists true. by iFrame. }\n    iModIntro. dwp_pures. iApply dwp_value. iModIntro.\n    iApply (\"H\u03a6\" $! (negb b)).\n    by destruct b.\n  Qed.\n\n  Lemma acquire_spec \u03b3 lk1 lk2 R \u03a6 :\n    is_lock \u03b3 lk1 lk2 R -\u2217\n    (locked \u03b3 -\u2217 R -\u2217 \u03a6 #() #()) -\u2217\n    DWP acquire lk1 & acquire lk2 : \u03a6.\n  Proof.\n    iIntros \"#Hinv H\u03a6\".\n    unlock acquire. dwp_pures=>/=. iL\u00f6b as \"IH\".\n    dwp_bind (try_acquire _) (try_acquire _).\n    iApply (try_acquire_spec with \"Hinv\"). iIntros ([]).\n    - iIntros \"[Hlked HR]\". dwp_pures.\n      iApply dwp_value. by iApply (\"H\u03a6\" with \"Hlked HR\").\n    - iIntros \"_\". dwp_pures=>/=.\n      by iApply \"IH\".\n  Qed.\n\n  Lemma release_spec \u03b3 lk1 lk2 R \u03a6 :\n    is_lock \u03b3 lk1 lk2 R -\u2217\n    locked \u03b3 -\u2217\n    R -\u2217\n    \u03a6 #() #() -\u2217\n    DWP release lk1 & release lk2 : \u03a6.\n  Proof.\n    iIntros \"#Hinv Hlked HR H\u03a6\".\n    rewrite/release. dwp_pures=>/=.\n    iDestruct \"Hinv\" as (l1 l2 -> ->) \"#Hinv\".\n    pose (\u03a81 := (\u03bb v, \u231cv = #()\u231d \u2217 l1 \u21a6\u2097 #false)%I).\n    pose (\u03a82 := (\u03bb v, \u231cv = #()\u231d \u2217 l2 \u21a6\u1d63 #false)%I).\n    iApply dwp_atomic.\n    iInv N as (b) \"(>Hl1 & >Hl2 & Hb)\" \"Hcl\".\n    iApply (dwp_atomic_lift_wp \u03a81 \u03a82 with \"[Hl1] [Hl2] [-]\").\n    { rewrite /TWP1 /\u03a81. wp_store. eauto with iFrame. }\n    { rewrite /TWP2 /\u03a82. wp_store. eauto with iFrame. }\n    iIntros (? ?). iDestruct 1 as (->) \"Hl1\". iDestruct 1 as (->) \"Hl2\".\n    iNext. iMod (\"Hcl\" with \"[-H\u03a6]\") as \"_\".\n    { iNext. iExists false. by iFrame. }\n    eauto with iFrame.\n  Qed.\n\nEnd proof.\n\nSection semtyping.\n  Context `{!heapDG \u03a3}.\n\n  Lemma newlock_typed \u03be :\n    \u22a2 DWP newlock #() & newlock #() : \u27e6 tmutex \u27e7 \u03be.\n  Proof.\n    rewrite tmutex_eq.\n    unlock newlock. dwp_pures=>/=.\n    iApply logrel_alloc. iApply logrel_bool.\n  Qed.\n\n  Lemma acquire_typed \u03be :\n    \u22a2 DWP acquire & acquire : \u27e6 tarrow tmutex tunit Low \u27e7 \u03be.\n  Proof.\n    rewrite tmutex_eq.\n    unfold acquire. dwp_pures. iApply dwp_value. iModIntro.\n    rewrite interp_eq. iModIntro. iIntros (lk1 lk2) \"#Hlk\".\n    dwp_pures. iL\u00f6b as \"IH\".\n    rewrite {5 7}/try_acquire. dwp_pures.\n    dwp_bind (CmpXchg _ _ _) (CmpXchg _ _ _).\n    rewrite /tmutex (interp_eq (tref _)).\n    iDestruct \"Hlk\" as (l1 l2 -> ->) \"Hinv\".\n    iInv (locsN.@(l1, l2)) as (w1 w2) \"(>Hl1 & >Hl2 & >Hw)\".\n    iDestruct \"Hw\" as (b b' -> ->) \"%\".\n    assert (b = b') as <- by (destruct \u03be; eauto).\n    destruct b.\n    - pose (\u03a61 := (\u03bb v, \u231cv = (#true, #false)%V\u231d \u2227 l1 \u21a6\u2097 #true)%I).\n      pose (\u03a62 := (\u03bb v, \u231cv = (#true, #false)%V\u231d \u2227 l2 \u21a6\u1d63 #true)%I).\n      iApply (dwp_atomic_lift_wp \u03a61 \u03a62 with \"[Hl1] [Hl2] [-]\"); unfold TWP1, TWP2.\n      { wp_cmpxchg_fail. unfold \u03a61. iFrame. eauto. }\n      { wp_cmpxchg_fail. unfold \u03a62. iFrame. eauto. }\n      iIntros (? ?). iDestruct 1 as \"[-> Hl1]\". iDestruct 1 as \"[-> Hl2]\".\n      iNext. iModIntro. iSplitL \"Hl1 Hl2\".\n      { iNext. iExists _,_. iFrame. rewrite interp_eq.\n        iExists _,_. eauto with iFrame. }\n      dwp_pures. iApply \"IH\".\n    - pose (\u03a61 := (\u03bb v, \u231cv = (#false, #true)%V\u231d \u2227 l1 \u21a6\u2097 #true)%I).\n      pose (\u03a62 := (\u03bb v, \u231cv = (#false, #true)%V\u231d \u2227 l2 \u21a6\u1d63 #true)%I).\n      iApply (dwp_atomic_lift_wp \u03a61 \u03a62 with \"[Hl1] [Hl2] [-]\"); unfold TWP1, TWP2.\n      { wp_cmpxchg_suc. unfold \u03a61. iFrame. eauto. }\n      { wp_cmpxchg_suc. unfold \u03a62. iFrame. eauto. }\n      iIntros (? ?). iDestruct 1 as \"[-> Hl1]\". iDestruct 1 as \"[-> Hl2]\".\n      iNext. iModIntro. iSplitL \"Hl1 Hl2\".\n      { iNext. iExists _,_. iFrame. rewrite interp_eq.\n        iExists _,_. eauto with iFrame. }\n      dwp_pures. iApply logrel_unit.\n  Qed.\n\n  Lemma release_typed \u03be :\n    \u22a2 DWP release & release : \u27e6 tarrow tmutex tunit Low \u27e7 \u03be.\n  Proof.\n    rewrite tmutex_eq.\n    unfold release. dwp_pures. iApply dwp_value. iModIntro.\n    rewrite interp_eq. iModIntro. iIntros (lk1 lk2) \"#Hlk\".\n    dwp_pures. iApply logrel_store; eauto.\n    - rewrite /tmutex. iApply dwp_value. iApply \"Hlk\".\n    - iApply logrel_bool.\n  Qed.\n\nEnd semtyping.\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/lock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.1753347880213374}}
{"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 PBFTexecute4.\n\n\nSection PBFTexecute5.\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 next_to_execute_from_before :\n    forall (eo : EventOrdering) (ei ej : Event) (i j : Rep) (sti stj : PBFTstate),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> PBFT_at_most_f_byz2 eo [ei,ej]\n      -> loc ei = PBFTreplica i\n      -> loc ej = PBFTreplica j\n      -> state_sm_before_event (PBFTreplicaSM i) eo ei = Some sti\n      -> state_sm_before_event (PBFTreplicaSM j) eo ej = Some stj\n      -> next_to_execute sti = next_to_execute stj\n      -> sm_state sti = sm_state stj /\\ last_reply_state sti = last_reply_state stj.\n  Proof.\n    introv sendby ckeys atmost eqloc1 eqloc2 eqst1 eqst2 eqnext.\n    rewrite <- ite_first_state_sm_on_event_as_before in eqst1.\n    rewrite <- ite_first_state_sm_on_event_as_before in eqst2.\n    unfold ite_first in *.\n    destruct (dec_isFirst ei) as [d1|d1];\n      destruct (dec_isFirst ej) as [d2|d2];\n      ginv; subst; simpl in *; eauto 3 with pbft.\n\n    - apply state_if_initial_next_to_execute in eqst2; auto; autorewrite with eo; auto.\n      repnd; allrw; tcsp.\n\n    - apply state_if_initial_next_to_execute in eqst1; auto; autorewrite with eo; auto.\n\n    - eapply next_to_execute_from in eqst1; try (exact eqst2); auto;\n        autorewrite with eo; tcsp; eauto 5 with pbft eo.\n  Qed.\n\n  Lemma replies_match :\n    forall (eo : EventOrdering) (e1 e2 : Event) v1 v2 ts c j1 j2 r1 r2 a1 a2 i1 i2,\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> PBFT_at_most_f_byz2 eo [e1,e2]\n      -> loc e1 = PBFTreplica i1\n      -> loc e2 = PBFTreplica i2\n      -> In (send_reply (mk_reply v1 ts c j1 r1 a1)) (output_system_on_event_ldata PBFTsys eo e1)\n      -> In (send_reply (mk_reply v2 ts c j2 r2 a2)) (output_system_on_event_ldata PBFTsys eo e2)\n      -> r1 = r2.\n  Proof.\n    introv sendbyz ckeys atmost eqloc1 eqloc2 out1 out2.\n\n    pose proof (PBFTnever_stops eo e1 i1) as q.\n    pose proof (PBFTnever_stops_on_event eo e1 i1) as h.\n    pose proof (PBFTnever_stops eo e2 i2) as w.\n    pose proof (PBFTnever_stops_on_event eo e2 i2) as z.\n    exrepnd.\n\n    eapply replies_from in out1; eauto.\n    eapply replies_from in out2; eauto.\n    exrepnd.\n\n    subst.\n\n    match goal with\n    | [ H1 : committed_log _ _ = _, H2 : committed_log _ _ = _ |- _ ] =>\n      rename H1 into com1; rename H2 into com2; dup com1 as com\n    end.\n\n    match goal with\n    | [ H1 : find_first_reply _ _ _ = _, H2 : find_first_reply _ _ _ = _ |- _ ] =>\n      rename H1 into ffr1; rename H2 into ffr2\n    end.\n\n    match goal with\n    | [ H1 : find_last_reply_entry_corresponding_to_client _ _ = _,\n             H2 : find_last_reply_entry_corresponding_to_client _ _ = _,\n                  H3 : find_last_reply_entry_corresponding_to_client _ _ = _,\n                       H4 : find_last_reply_entry_corresponding_to_client _ _ = _ |- _ ] =>\n      rename H1 into fl1; rename H2 into fl2; rename H3 into fl3; rename H4 into fl4\n    end.\n\n    match goal with\n    | [ H1 : reply2requests _ _ _ _ _ _ = _, H2 : reply2requests _ _ _ _ _ _ = _ |- _ ] =>\n      rename H1 into r2rs1; rename H2 into r2rs2\n    end.\n\n    match goal with\n    | [ H1 : request2info _ = _, H2 : request2info _ = _ |- _ ] =>\n      rename H1 into r2i1; rename H2 into r2i2\n    end.\n\n    destruct (SeqNumDeq (next_to_execute st0) (next_to_execute st2)) as [d|d].\n\n    {\n      rewrite d in *.\n\n      eapply PBFT_A_1_11_before in com;\n        try exact com2; try (exact q0); try (exact w0); auto; eauto 3 with pbft;[].\n      apply eq_digests_implies_eq_requests in com; subst.\n\n      rewrite ffr1 in ffr2; ginv.\n\n      pose proof (next_to_execute_from_before eo e1 e2 j1 j2 st2 st0) as u.\n      repeat (autodimp u hyp);[].\n      repnd.\n      rewrite u0 in *.\n      rewrite u in *.\n\n      pose proof (next_to_execute_from eo e1 e2 j1 j2 st1 st) as v.\n      repeat (autodimp v hyp); try (complete (allrw; tcsp));[].\n      repnd.\n      try rewrite v0 in *.\n      try rewrite v in *.\n\n      eapply matching_reply2requests_implies in r2rs1; try (exact r2rs2).\n      repnd; subst.\n\n      rewrite fl1 in *; ginv.\n      rewrite fl2 in *; ginv.\n\n      rewrite r2i1 in *; ginv.\n      smash_pbft.\n    }\n\n    assert (seqnum2nat (next_to_execute st0) <> seqnum2nat (next_to_execute st2)) as d'.\n    { intro xx; destruct d.\n      destruct (next_to_execute st0), (next_to_execute st2); simpl in *; tcsp. }\n\n    apply not_eq in d'; repndors;[|].\n\n    {\n      assert (next_to_execute st <= next_to_execute st2) as lenext by (allrw; simpl; omega).\n      applydup next_to_execute_is_greater_than_one in z0; auto;[].\n\n      rewrite <- ite_first_state_sm_on_event_as_before in q0.\n      unfold ite_first in *.\n      destruct (dec_isFirst e1) as [d1|d1]; ginv; subst; simpl in *;[].\n      pose proof (last_reply_state_increases\n                    eo (local_pred e1) j1 st2\n                    (next_to_execute st)) as u.\n      repeat (autodimp u hyp); autorewrite with eo; auto;\n        try omega; eauto 3 with pbft;[].\n      exrepnd.\n\n      pose proof (next_to_execute_from eo e' e2 j j2 st' st) as v.\n      repeat (autodimp v hyp); try (complete (allrw; auto)); eauto 4 with pbft eo;[].\n      repnd.\n      rewrite v in u0.\n\n      applydup u0 in fl4.\n      exrepnd.\n\n      applydup reply2requests_implies_last_reply_state_extends in r2rs2 as ext.\n      applydup ext in fl0.\n      exrepnd.\n      rewrite fl8 in *; ginv.\n\n      assert (ts <= lre_timestamp e4) as lets by omega.\n\n      autodimp fl5 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp fl9 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp out0 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n\n      assert (lre_reply e4 = Some r1) as eqr1 by (dest_all x; try omega).\n\n      assert (Some r1 = Some r2) as eqrs by congruence.\n      ginv.\n    }\n\n    {\n      assert (next_to_execute st1 <= next_to_execute st0) as lenext by (allrw; simpl; omega).\n      applydup next_to_execute_is_greater_than_one in h0; auto;[].\n\n      rewrite <- ite_first_state_sm_on_event_as_before in w0.\n      unfold ite_first in *.\n      destruct (dec_isFirst e2) as [d1|d1]; ginv; subst; simpl in *;[].\n      pose proof (last_reply_state_increases\n                    eo (local_pred e2) j2 st0\n                    (next_to_execute st1)) as u.\n      repeat (autodimp u hyp); autorewrite with eo; auto; try omega; eauto 3 with pbft eo;[].\n      exrepnd.\n\n      pose proof (next_to_execute_from eo e' e1 j j1 st' st1) as v.\n      repeat (autodimp v hyp); try (complete (allrw; auto)); eauto 5 with pbft eo;[].\n      repnd.\n      rewrite v in u0.\n\n      applydup u0 in fl2.\n      exrepnd.\n\n      applydup reply2requests_implies_last_reply_state_extends in r2rs1 as ext.\n      applydup ext in fl0.\n      exrepnd.\n      rewrite fl8 in *; ginv.\n\n      assert (ts <= lre_timestamp e0) as lets by omega.\n\n      autodimp fl5 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp fl9 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n      autodimp out14 hyp;[apply eq_nats_implies_eq_timestamps; omega|].\n\n      assert (lre_reply e0 = Some r2) as eqr2 by (dest_all x; try omega).\n\n      assert (Some r1 = Some r2) as eqrs by congruence.\n      ginv.\n    }\n  Qed.\n\nEnd PBFTexecute5.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFTexecute5_backup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.1753347858535333}}
{"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.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\n\nSet Implicit Arguments.\n\n(** * Thread Steps in the Promising Semantics 2.1 *)\n\n(** This file defines the thread transitions in promising semantics 2.1 (PS2.1). *)\n\nInductive tau T\n          (step: forall (lo: Ordering.LocOrdMap) \n                        (e:ThreadEvent.t) (e1 e2:T), Prop) (lo: Ordering.LocOrdMap) (e1 e2:T) : Prop :=\n| tau_intro\n    e\n    (TSTEP: step lo e e1 e2)\n    (EVENT: ThreadEvent.get_machine_event e = MachineEvent.silent)\n.\n\nHint Constructors tau.\n\nInductive union E T (step: forall (lo: Ordering.LocOrdMap) (e:E) (e1 e2:T), Prop) (lo: Ordering.LocOrdMap)\n          (e1 e2:T): Prop :=\n| union_intro\n    e\n    (USTEP: step lo e e1 e2)\n.\nHint Constructors union.\n\n\nModule Thread.\n  Section Thread.\n    Variable (lang:language).\n\n    (** ** Thread State *)\n    (** The thread state contains:\n        - [state]: thread-local state;\n        - [local]: thread view and thread promise set;\n        - [sc]: timemap for SC fence;\n        - [memory]: memory in PS2.1 *)\n    Structure t := mk {\n      state: (Language.state lang);\n      local: Local.t;\n      sc: TimeMap.t;\n      memory: Memory.t;\n    }.\n\n    (** ** Thread Promise Step *)\n    (** It includes promise insert/lower/split, reservation and cancel step.\n        The pf label marks whether such step is a promise-free step.\n        For cancel step, pf = true. *)\n    Inductive promise_step: forall (pf: bool) (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | promise_step_intro\n        st lc1 sc1 mem1\n        loc from to msg kind\n        lc2 mem2 pf\n        (LOCAL: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n        (PF: pf = orb (andb (Memory.op_kind_is_lower_concrete kind) (Message.is_released_none msg))\n                      (Memory.op_kind_is_cancel kind))\n        :\n        promise_step pf (ThreadEvent.promise loc from to msg kind) (mk st lc1 sc1 mem1) (mk st lc2 sc1 mem2)\n    .\n\n    (** ** Thread Program Step *)\n    (**  thread-local state transition +\n         transistion on (thread-view, promises, timemap for SC fence, memory)  *)\n    Inductive program_step (e:ThreadEvent.t) (lo: Ordering.LocOrdMap): forall (e1 e2:t), 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: Local.program_step e lc1 sc1 mem1 lc2 sc2 mem2 lo):\n        program_step e lo (mk st1 lc1 sc1 mem1) (mk st2 lc2 sc2 mem2)\n    .\n    Hint Constructors program_step.\n\n    (** ** Thread step (thread transition) *)\n    (** Thread step in promising semantics contains two types of steps:\n        - [step_promise]: promise step;\n        - [step_program]: program step that executes the instruction. *)\n    Inductive step: forall (lo: Ordering.LocOrdMap) (pf: bool) (e:ThreadEvent.t) (e1 e2:t) , Prop :=\n    | step_promise\n        e e1 e2 lo pf\n        (STEP: promise_step pf e e1 e2):\n        step lo pf e e1 e2\n    | step_program\n        e e1 e2 lo\n        (STEP: program_step e lo e1 e2):\n        step lo true e e1 e2\n    .\n    Hint Constructors step.\n\n    Inductive step_allpf (lo: Ordering.LocOrdMap) (e:ThreadEvent.t) (e1 e2:t) : Prop :=\n    | step_nopf_intro\n        pf (STEP: step lo pf e e1 e2)\n    .\n    Hint Constructors step_allpf.\n\n    Definition tau_step (lo: Ordering.LocOrdMap):= tau step_allpf lo.\n    Hint Unfold tau_step.\n\n    Definition all_step (lo:Ordering.LocOrdMap) := union step_allpf lo.\n    Hint Unfold all_step.\n\n    Inductive opt_step: forall (lo: Ordering.LocOrdMap) (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | step_none\n        e lo:\n        opt_step lo ThreadEvent.silent e e\n    | step_some\n        pf e e1 e2 lo\n        (STEP: step lo pf e e1 e2):\n        opt_step lo e e1 e2\n    .\n    Hint Constructors opt_step.\n\n    Inductive opt_promise_step: forall (lo: Ordering.LocOrdMap) (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | opt_promise_step_none\n        lo e1:\n        opt_promise_step lo ThreadEvent.silent e1 e1\n    | opt_promise_step_some\n        pf lo e e1 e2\n        (STEP: promise_step pf e e1 e2):\n        opt_promise_step lo e e1 e2\n    . \n\n    Inductive opt_program_step: forall (lo: Ordering.LocOrdMap) (e:ThreadEvent.t) (e1 e2:t), Prop :=\n    | opt_program_step_none\n        lo e1:\n        opt_program_step lo ThreadEvent.silent e1 e1\n    | opt_program_step_some\n        lo e e1 e2\n        (STEP: program_step e lo e1 e2):\n        opt_program_step lo e e1 e2\n    .\n\n    Lemma tau_opt_tau\n          e1 e2 e3 e lo\n          (STEPS: rtc (tau_step lo) e1 e2)\n          (STEP: opt_step lo e e2 e3)\n          (EVENT: ThreadEvent.get_machine_event e = MachineEvent.silent):\n      rtc (tau_step lo) e1 e3.\n    Proof.\n      induction STEPS.\n      - inv STEP; eauto.\n      - exploit IHSTEPS; eauto.\n    Qed.\n\n    Lemma tau_opt_all\n          e1 e2 e3 e lo\n          (STEPS: rtc (tau_step lo) e1 e2)\n          (STEP: opt_step lo e e2 e3):\n      rtc (all_step lo) e1 e3.\n    Proof.\n      induction STEPS.\n      - inv STEP; eauto.\n      - exploit IHSTEPS; eauto. i.\n        econs 2; eauto.\n        inv H. inv TSTEP. econs. econs. eauto.\n    Qed.\n\n    (** ** Consistency *)\n    (** A thread state is consistent if the thread is able to fulfill\n        all its promises when executed in isolation. *)\n    Definition consistent (e:t) (lo: Ordering.LocOrdMap): Prop :=\n      forall mem1 sc1\n        (CAP: Memory.cap (memory e) mem1)\n        (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n        exists e2,\n          <<STEPS: rtc (tau_step lo) (mk (state e) (local e) sc1 mem1) e2>> /\\\n          <<PROMISES: (Local.promises (local e2)) = Memory.bot>>. \n\n    (* step_future *)\n    Lemma promise_step_future\n          pf e e1 e2 \n          (STEP: promise_step pf e e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\n    Proof.\n      inv STEP. ss.\n      exploit Local.promise_step_future; eauto. i. des.\n      splits; eauto. 2: refl.\n      eapply Memory.future_closed_timemap; eauto.\n    Qed.\n\n    Lemma program_step_future\n          lo e e1 e2\n          (STEP: program_step lo e e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\n    Proof.\n      inv STEP. ss. eapply Local.program_step_future; eauto.\n    Qed.\n\n    Lemma step_future\n          lo pf e e1 e2\n          (STEP: step lo pf e e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply promise_step_future; eauto.\n      - eapply program_step_future; eauto.\n    Qed.\n\n    Lemma opt_step_future\n          lo e e1 e2\n          (STEP: opt_step lo e e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; refl.\n      - eapply step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          e1 e2 lo\n          (STEP: rtc (all_step lo) e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\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\n          e1 e2 lo\n          (STEP: rtc (tau_step lo) e1 e2)\n          (WF1: Local.wf (local e1) (memory e1))\n          (SC1: Memory.closed_timemap (sc e1) (memory e1))\n          (CLOSED1: Memory.closed (memory e1)):\n      <<WF2: Local.wf (local e2) (memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (sc e2) (memory e2)>> /\\\n      <<CLOSED2: Memory.closed (memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local e1)) (Local.tview (local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (sc e1) (sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (memory e1) (memory e2)>>.\n    Proof.\n      eapply rtc_all_step_future; eauto.\n      eapply rtc_implies; [|eauto].\n      intros.\n      inv H; econstructor; eauto.\n    Qed.\n\n    (* step_inhabited *)\n    Lemma promise_step_inhabited\n          pf e e1 e2\n          (STEP: promise_step pf e e1 e2)\n          (INHABITED1: Memory.inhabited (memory e1)):\n      <<INHABITED2: Memory.inhabited (memory e2)>>.\n    Proof.\n      inv STEP. ss.\n      eapply Local.promise_step_inhabited; eauto.\n    Qed.\n\n    Lemma program_step_inhabited\n          lo e e1 e2\n          (STEP: program_step lo e e1 e2)\n          (INHABITED1: Memory.inhabited (memory e1)):\n      <<INHABITED2: Memory.inhabited (memory e2)>>.\n    Proof.\n      inv STEP. ss.\n      eapply Local.program_step_inhabited; eauto.\n    Qed.\n\n    Lemma step_inhabited\n          pf lo e e1 e2\n          (STEP: step lo pf e e1 e2)\n          (INHABITED1: Memory.inhabited (memory e1)):\n      <<INHABITED2: Memory.inhabited (memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply promise_step_inhabited; eauto.\n      - eapply program_step_inhabited; eauto.\n    Qed.\n\n    Inductive reserve_step (lo: Ordering.LocOrdMap) (e1 e2:t) : Prop :=\n    | reserve_step_intro\n        loc pf from to\n        (STEP: promise_step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) e1 e2)\n    .\n    Hint Constructors reserve_step.\n\n    Inductive cancel_step (lo: Ordering.LocOrdMap) (e1 e2:t): Prop :=\n    | cancel_step_intro\n        loc pf from to\n        (STEP: promise_step pf (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel) e1 e2)\n    .\n    Hint Constructors cancel_step.\n\n    (** ** Non-atomic Step *)\n    (** It corresponds to (NA) in Figure 10 in paper and includes:\n        + non-atomic memory read;\n        + non-atomic memory write;\n        + silent step that does not do memory accesses. *)\n    Inductive na_step (lo: Ordering.LocOrdMap) (e1 e2:t) : Prop := \n    | na_plain_read_step_intro\n      loc ts v R\n      (STEP: program_step (ThreadEvent.read loc ts v R Ordering.plain) lo e1 e2)\n    | na_plain_write_step_intro\n      loc from to v R\n      (STEP: program_step (ThreadEvent.write loc from to v R Ordering.plain) lo e1 e2)\n    | na_tau_step_intro \n      (STEP: program_step ThreadEvent.silent lo e1 e2)\n    .\n\n    (** NA step with location written *)\n    (* set of locations written *)\n    Definition WriteLoc := IdentSet.t.\n    Definition wloc_empty : WriteLoc := IdentSet.empty.\n\n    Lemma wloc_union_empty:\n      IdentSet.union IdentSet.empty IdentSet.empty = IdentSet.empty.\n    Proof.\n      eapply IdentSet.Self.eq_leibniz. ii. split; ii.\n      - eapply IdentSet.union_spec in H. des; eauto.\n      - eapply IdentSet.union_spec. eauto.\n    Qed.\n\n    (* na step with location written *)\n    Inductive na_step_wloc: forall (lo: Ordering.LocOrdMap) (wloc: WriteLoc) (e1 e2: t), Prop :=\n    | na_read_step_wloc_intro\n        lo e1 e2 loc ts v R\n        (STEP: program_step (ThreadEvent.read loc ts v R Ordering.plain) lo e1 e2):\n        na_step_wloc lo IdentSet.empty e1 e2\n    | na_write_step_wloc_intro\n        lo e1 e2 loc from to v R\n        (STEP: program_step (ThreadEvent.write loc from to v R Ordering.plain) lo e1 e2): \n        na_step_wloc lo (IdentSet.singleton loc) e1 e2\n    | na_tau_step_wloc_intro\n        lo e1 e2\n        (STEP: program_step ThreadEvent.silent lo e1 e2):\n        na_step_wloc lo IdentSet.empty e1 e2.\n\n    (* na steps with locations writen *) \n    Inductive na_steps_wloc: forall (lo: Ordering.LocOrdMap) (wloc: WriteLoc) (e1 e2: t), Prop :=\n    | nil_na_steps_wloc\n        lo e:\n        na_steps_wloc lo IdentSet.empty e e\n    | plus_na_steps_wloc\n        lo  e1 e2 e3 wloc1 wloc2\n        (STEP: na_step_wloc lo wloc1 e1 e2)\n        (STEPS: na_steps_wloc lo wloc2 e2 e3):\n        na_steps_wloc lo (IdentSet.union wloc1 wloc2) e1 e3.\n\n     (** ** PRC Step *)\n    (** It corresponds to (PRC) in Figure 10 in paper.\n        In Coq formalization, the promise, reservation and cancel steps are\n        all called [promise_step]. *)\n    Inductive prc_step (lo: Ordering.LocOrdMap) (e1 e2: t): Prop :=\n    | prc_step_intro\n        pf loc from to msg kind\n        (PRC: promise_step pf (ThreadEvent.promise loc from to msg kind) e1 e2).\n  \n    Inductive out_step (lo: Ordering.LocOrdMap) (e: Event.t) (e1 e2: t): Prop :=\n    | out_step_intro\n      e \n      (OUT: program_step (ThreadEvent.syscall e) lo e1 e2)\n    . \n\n    Inductive at_read_step (lo: Ordering.LocOrdMap) (e1 e2: t) : Prop :=\n    | at_read_step_intro\n        loc ts v R o\n        (STEP: program_step (ThreadEvent.read loc ts v R o) lo e1 e2)\n        (AT: Ordering.le Ordering.relaxed o).\n\n    Inductive at_write_step (lo: Ordering.LocOrdMap) (e1 e2: t) : Prop :=\n    | at_write_step_intro\n       loc from to v R o\n       (STEP: program_step (ThreadEvent.write loc from to v R o) lo e1 e2)\n       (AT: Ordering.le Ordering.relaxed o).\n\n    Inductive rmw_step (lo: Ordering.LocOrdMap) (e1 e2: t) : Prop :=\n    | rmw_step_intro\n        loc from to v1 v2 R1 R2 o1 o2\n        (STEP: program_step (ThreadEvent.update loc from to v1 v2 R1 R2 o1 o2) lo e1 e2).\n\n    Inductive fence_step (lo: Ordering.LocOrdMap) (e1 e2: t) : Prop :=\n    | fence_step_intro\n        o1 o2\n        (STEP: program_step (ThreadEvent.fence o1 o2) lo e1 e2).\n\n    (** ** Atomic Step *)\n    (** It corresponds to (AT) in Figure 10 in paper. *)\n    Inductive at_step (lo: Ordering.LocOrdMap) (e1 e2:t) : Prop := \n    | at_step_intro\n        (AT_STEP: at_read_step lo e1 e2 \\/ at_write_step lo e1 e2 \\/\n                  rmw_step lo e1 e2 \\/ fence_step lo e1 e2).\n\n    Inductive pf_promise_step (e1 e2: t): Prop :=\n    | pf_promise_step_intro\n        e\n        (PF_STEP: promise_step true e e1 e2).\n\n    Definition atmblk_step (lo: Ordering.LocOrdMap) (e1 e2: t): Prop :=\n      exists e' e'', \n      <<NA_STEPS: rtc (@na_step lo) e1 e'>> /\\ \n      <<AT_STEP: at_step lo e' e''>> /\\\n      <<PRC_STEPS: rtc (@prc_step lo) e'' e2>>.\n\n\n    (** ** Thread Done *)\n    (** A thread is done, iff. terminal + promise empty. *)\n    Definition is_done (e:t) : Prop :=\n      <<TERMINAL: Language.is_terminal lang (state e)>> /\\\n      <<PROMISES: (Local.promises (local e)) = Memory.bot>>.\n\n    (** ** Thread Abort *)\n    (** A thread abort, iff. the next thread-local state does not exist,\n        or accessing the atomic location via non-atomic memory accesses,\n        or accessing the non-atomic location via atomic memory accesses. *)\n    Definition is_abort (e1 :t) (lo: Ordering.LocOrdMap): Prop :=\n      <<PROMISES: Local.promise_consistent (local e1)>> /\\\n      <<ABORT: ~((exists e st2, (Language.step lang) e (state e1) st2) \\/\n                 Language.is_terminal lang (state e1)) \\/\n               (exists st2 x o v, ((Language.step lang) (ProgramEvent.read x v o) (state e1) st2 \n                     \\/ (Language.step lang) (ProgramEvent.write x v o) (state e1) st2) \n                            /\\ ~ Ordering.mem_ord_match o (lo x)) \\/\n                            (exists st2 x vr vw or ow, (Language.step lang) (ProgramEvent.update x vr vw or ow) (state e1) st2 /\\ lo x = Ordering.nonatomic)>>.\n\n    Inductive nprm_step (lo: Ordering.LocOrdMap) (e1 e2: t): Prop :=\n    | nprm_step_program_step\n        e\n        (PROG: program_step e lo e1 e2)\n        (TAU: ThreadEvent.get_machine_event e = MachineEvent.silent)\n    | nprm_step_pf_step\n        e\n        (PF: promise_step true e e1 e2).\n\n    Definition consistent_nprm (e:t) (lo: Ordering.LocOrdMap): Prop :=\n      forall mem1 sc1\n        (CAP: Memory.cap (memory e) mem1)\n        (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n        exists e2,\n          <<STEPS: rtc (nprm_step lo) (mk (state e) (local e) sc1 mem1) e2>> /\\\n                   <<PROMISES: (Local.promises (local e2)) = Memory.bot>>.\n    Definition not_rsv_ccl_scfence (e: ThreadEvent.t) :=\n      match e with\n      | ThreadEvent.syscall _ => false\n      | ThreadEvent.fence _ Ordering.seqcst => false\n      | ThreadEvent.promise _ _ _ _ Memory.op_kind_cancel => false\n      | ThreadEvent.promise _ _ _ Message.reserve Memory.op_kind_add => false\n      | _ => true\n      end. \n    \n    End Thread.\n\n  Lemma na_write_on_atomic_loc_is_abort\n        lang st lc sc mem lo st' val loc\n        (NA_WRITE: Language.step lang (ProgramEvent.write loc val Ordering.plain) st st')\n        (AT_LOC: lo loc = Ordering.atomic)\n        (PROM_CONS: Local.promise_consistent lc):\n    Thread.is_abort (Thread.mk lang st lc sc mem) lo.\n  Proof.\n    econs; eauto.\n    right; ss. left.\n    do 4 eexists.\n    split; eauto.\n    ii.\n    rewrite AT_LOC in H. ss.\n    des; ss.\n  Qed.\n\n  Lemma pf_promise_step_tview_unchange\n        lang (e e': Thread.t lang)\n        (PF: @Thread.pf_promise_step lang e e'):\n    Local.tview (Thread.local e) = Local.tview (Thread.local e').\n  Proof.\n    inv PF. inv PF_STEP; ss.\n    inv LOCAL; ss; eauto.\n  Qed.\n\n  Lemma pf_promise_steps_tview_unchange\n        lang (e e': Thread.t lang)\n        (PF: rtc (@Thread.pf_promise_step lang) e e'):\n    Local.tview (Thread.local e) = Local.tview (Thread.local e').\n  Proof.\n    induction PF; ss; eauto.\n    eapply pf_promise_step_tview_unchange in H.\n    rewrite <- IHPF. rewrite H. eauto.\n  Qed.\nEnd Thread.\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/Thread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.27202455109402257, "lm_q1q2_score": 0.1752450491116713}}
{"text": "Require Import Coq.Lists.List.\nRequire Import coqutil.Map.Interface coqutil.Map.Properties.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.Run.\n\nImport ListNotations.\n\nSection Sane.\n\n  Context {width: Z} {BW: Bitwidth width} {word: word width} {word_ok: word.ok word}.\n  Context {Registers: map.map Register word}.\n  Context {mem: map.map word byte}.\n  Context {M: Type -> Type}.\n  Context {MM: Monad M}.\n  Context {RVM: RiscvProgram M word}.\n  Context {PRParams: PrimitivesParams M RiscvMachine}.\n  Context {mcomp_sat_ok: mcomp_sat_spec PRParams}.\n\n  Lemma mcomp_sat_weaken: forall A initialL m (post1 post2: A -> RiscvMachine -> Prop),\n      (forall a mach, post1 a mach -> post2 a mach) ->\n      mcomp_sat m initialL post1 ->\n      mcomp_sat m initialL post2.\n  Proof.\n    intros.\n    rewrite <- (@right_identity M MM A m).\n    eapply spec_Bind.\n    eexists. split.\n    - exact H0.\n    - intros. simpl in *. apply spec_Return. eapply H. assumption.\n  Qed.\n\n  Lemma Return_sane: forall {A: Type} (a: A),\n      mcomp_sane (Return a).\n  Proof.\n    unfold mcomp_sane.\n    intros. eapply spec_Return in H0.\n    split.\n    - eauto.\n    - eapply (proj1 (spec_Return _ _ _)).\n      ssplit.\n      + assumption.\n      + exists nil. reflexivity.\n      + assumption.\n  Qed.\n\n  Lemma Bind_sane: forall {A B: Type} (m: M A) (f: A -> M B),\n      mcomp_sane m ->\n      (forall a, mcomp_sane (f a)) ->\n      mcomp_sane (Bind m f).\n  Proof.\n    intros *.\n    intros S1 S2.\n    unfold mcomp_sane in *.\n    intros.\n    eapply (proj2 (spec_Bind _ _ _ _)) in H0.\n    destruct H0 as (mid & C1 & C2).\n    split.\n    - specialize S1 with (1 := H) (2 := C1). destruct S1 as ((a & middle & S1a & S1b) & S1c).\n      specialize C2 with (1 := S1a).\n      specialize S2 with (1 := S1b) (2 := C2). destruct S2 as ((b & final & S2a) & S2b).\n      eauto.\n    - eapply spec_Bind.\n      exists (fun a middle => (mid a middle /\\\n                               exists diff1, getLog middle = diff1 ++ getLog st) /\\\n                              valid_machine middle).\n      split.\n      + specialize S1 with (1 := H) (2 := C1). destruct S1 as ((a & middle & S1a & S1b) & S1c).\n        exact S1c.\n      + intros. destruct H0 as ((HM & (diff1 & E1)) & V1).\n        specialize C2 with (1 := HM).\n        specialize S2 with (1 := V1) (2 := C2). destruct S2 as ((b & final & S2a & S2b) & S2c).\n        eapply mcomp_sat_weaken; [|exact S2c].\n        simpl. intros. destruct H0 as ((? & (diff2 & E2)) & V2).\n        split; [|assumption].\n        split; [assumption|].\n        rewrite E1 in E2.\n        rewrite List.app_assoc in E2.\n        eexists. exact E2.\n  Qed.\n\nEnd Sane.\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/Sane.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.2974699426047947, "lm_q1q2_score": 0.17517681163754115}}
{"text": "Require Import VST.progs.conclib.\nRequire Import VST.progs.ghosts.\nRequire Import VST.progs.incr.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\nDefinition spawn_spec := DECLARE _spawn spawn_spec.\nDefinition freelock2_spec := DECLARE _freelock2 (freelock2_spec _).\nDefinition release2_spec := DECLARE _release2 release2_spec.\n\nDefinition cptr_lock_inv g1 g2 ctr := EX z : Z, data_at Ews tuint (Vint (Int.repr z)) ctr *\n  EX x : Z, EX y : Z, !!(z = x + y) && ghost_var gsh1 x g1 * ghost_var gsh1 y g2.\n\nDefinition incr_spec :=\n DECLARE _incr\n  WITH sh : share, g1 : gname, g2 : gname, left : bool, n : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         LOCAL (gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n (if left then g1 else g2))\n  POST [ tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 (n+1) (if left then g1 else g2)).\n\nDefinition read_spec :=\n DECLARE _read\n  WITH sh : share, g1 : gname, g2 : gname, n1 : Z, n2 : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         LOCAL (gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2)\n  POST [ tuint ]\n         PROP ()\n         LOCAL (temp ret_temp (Vint (Int.repr (n1 + n2))))\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2).\n\nDefinition thread_lock_R sh g1 g2 ctr lockc :=\n  lock_inv sh lockc (cptr_lock_inv g1 g2 ctr) * ghost_var gsh2 1 g1.\n\nDefinition thread_lock_inv sh g1 g2 ctr lockc lockt :=\n  selflock (thread_lock_R sh g1 g2 ctr lockc) sh lockt.\n\nDefinition thread_func_spec :=\n DECLARE _thread_func\n  WITH y : val, x : share * gname * gname * globals\n  PRE [ _args OF (tptr tvoid) ]\n         let '(sh, g1, g2, gv) := x in\n         PROP  (readable_share sh)\n         LOCAL (temp _args y; gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr));\n                ghost_var gsh2 0 g1;\n                lock_inv sh (gv _thread_lock) (thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)))\n  POST [ tptr tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP ().\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog 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; incr_spec; read_spec; thread_func_spec; main_spec]).\n\nLemma ctr_inv_exclusive : forall g1 g2 p,\n  exclusive_mpred (cptr_lock_inv g1 g2 p).\nProof.\n  intros; unfold cptr_lock_inv.\n  eapply derives_exclusive, exclusive_sepcon1 with (Q := EX x : Z, EX y : Z, _),\n    data_at__exclusive with (sh := Ews)(t := tuint); auto; simpl; try omega.\n  Intro z; apply sepcon_derives; [cancel|].\n  Intros x y; Exists x y; apply derives_refl.\nQed.\nHint Resolve ctr_inv_exclusive.\n\nLemma thread_inv_exclusive : forall sh g1 g2 ctr lock lockt,\n  exclusive_mpred (thread_lock_inv sh g1 g2 ctr lock lockt).\nProof.\n  intros; apply selflock_exclusive.\n  unfold thread_lock_R.\n  apply exclusive_sepcon1; auto.\nQed.\nHint Resolve thread_inv_exclusive.\n\nLemma body_incr: semax_body Vprog Gprog f_incr incr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  forward.\n  gather_SEP 2 3 4.\n  viewshift_SEP 0 (!!((if left then x else y) = n) && ghost_var Tsh (n+1) (if left then g1 else g2) *\n    ghost_var gsh1 (if left then y else x) (if left then g2 else g1)).\n  { go_lower.\n    destruct left.\n    - rewrite (sepcon_comm _ (ghost_var _ _ _)), <- sepcon_assoc.\n      erewrite ghost_var_share_join' by eauto.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update.\n    - erewrite ghost_var_share_join' by eauto.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update. }\n  Intros; forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists (z + 1).\n    erewrite <- ghost_var_share_join by eauto.\n    unfold Frame; instantiate (1 := [ghost_var gsh2 (n+1) (if left then g1 else g2)]); simpl.\n    destruct left.\n    - Exists (n+1) y; entailer!.\n    - Exists x (n+1); entailer!. }\n  forward.\nQed.\n\nLemma body_read : semax_body Vprog Gprog f_read read_spec.\nProof.\n  start_function.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  assert_PROP (x = n1 /\\ y = n2) as Heq.\n  { gather_SEP 2 4.\n    erewrite ghost_var_share_join' by eauto.\n    gather_SEP 3 4.\n    erewrite ghost_var_share_join' by eauto.\n    entailer!. }\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists z x y; entailer!. }\n  destruct Heq; forward.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (sh, g1, g2, true, 0, gv).\n  simpl.\n  forward_call ((gv _thread_lock), sh, thread_lock_R sh g1 g2 (gv _ctr) (gv _ctr_lock), thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    rewrite selflock_eq at 2; cancel. }\n  forward.\nQed.\n\nLtac cancel_for_forward_call ::=\n  match goal with\n  | gv: globals |- _ =>\n    repeat\n    match goal with\n    | x := gv ?i |- context [gv ?i] =>\n        change (gv i) with x\n    end\n  | _ => idtac\n  end;\n  cancel_for_evar_frame.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  set (ctr := gv _ctr); set (lockt := gv _thread_lock); set (lock := gv _ctr_lock).\n  forward.\n  forward.\n  forward.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g1.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g2.\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    rewrite <- !(ghost_var_share_join gsh1 gsh2 Tsh) by auto.\n    unfold cptr_lock_inv; Exists 0 0 0; entailer!. }\n  (* need to split off shares for the locks here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (lockt, Ews, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  forward_spawn _thread_func nullval (sh1, g1, g2, gv).\n  { erewrite <- lock_inv_share_join; try apply Hsh; auto.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.\n    entailer!. }\n  forward_call (sh2, g1, g2, false, 0, gv).\n  simpl.\n  forward_call (lockt, sh2, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  unfold thread_lock_inv at 2; unfold thread_lock_R.\n  rewrite selflock_eq.\n  Intros.\n  forward_call (sh2, g1, g2, 1, 1, gv).\n  (* We've proved that t is 2! *)\n  forward_call (lock, sh2, cptr_lock_inv g1 g2 ctr).\n  forward_call (lockt, Ews, sh1, thread_lock_R sh1 g1 g2 ctr lock, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel. }\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel. }\n  forward.\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_incr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.17513092903711794}}
{"text": "Require Import PArith Arith.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import Configuration TView View Time Event Cell Thread Memory Local.\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import Execution_eco.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_bob imm_s_ppo.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\nFrom imm Require Import ProgToExecution.\n\nFrom imm Require Import TraversalConfig.\nRequire Import ExtTraversalConfig.\nRequire Import ExtTraversal.\nRequire Import MaxValue.\nRequire Import ViewRel.\nFrom imm Require Import ViewRelHelpers.\nRequire Import SimulationRel.\nRequire Import SimulationPlainStepAux.\nRequire Import PlainStepBasic.\nRequire Import SimState.\nRequire Import SimStateHelper.\nRequire Import PromiseLTS.\nRequire Import MemoryAux.\nRequire Import FtoCoherent.\nFrom imm Require Import AuxRel2.\nRequire Import ExistsIssueReservedInterval.\nRequire Import IssueReservedStepHelper.\nRequire Import MemoryClosedness.\nRequire Import SimulationRelProperties.\nRequire Import ReadPlainStepHelper.\n\nSet Implicit Arguments.\n\nSection IssueReservedRelPlainStep.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\nVariable CON : imm_consistent G sc.\n\nNotation \"'E'\" := G.(acts_set).\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).\n\nNotation \"'fr'\" := G.(fr).\nNotation \"'coe'\" := G.(coe).\nNotation \"'coi'\" := G.(coi).\nNotation \"'deps'\" := G.(deps).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'detour'\" := G.(detour).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sw'\" := G.(sw).\n\nNotation \"'lab'\" := G.(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 \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (fun a => is_true (is_rlx lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Acqrel'\" := (fun a => is_true (is_acqrel lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'W_ex'\" := G.(W_ex).\nNotation \"'W_ex_acq'\" := (W_ex \u2229\u2081 (fun a => is_true (is_xacq lab a))).\n\nLemma issue_rel_reserved_step_no_next PC T (S : actid -> Prop) f_to f_from thread r w smode\n      (TID : tid r = thread)\n      (REL : Rel w) (RMW : rmw r w)\n      (SW : S w)\n      (NONEXT : dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) \u2286\u2081 \u2205)\n\n      (TSTEP1 : ext_itrav_step\n                 G sc r (mkETC T S)\n                 (mkETC (mkTC (covered T \u222a\u2081 eq r) (issued T)) S))\n      (TSTEP2 : ext_itrav_step\n                  G sc w (mkETC (mkTC (covered T \u222a\u2081 eq r) (issued T)) S)\n                  (mkETC\n                     (mkTC (covered T \u222a\u2081 eq r) (issued T \u222a\u2081 eq w))\n                     (S \u222a\u2081 eq w \u222a\u2081 dom_sb_S_rfrmw G (mkETC T S) rfi (eq w))))\n\n      (TSTEP3 : ext_itrav_step\n                  G sc w\n                  (mkETC\n                     (mkTC (covered T \u222a\u2081 eq r) (issued T \u222a\u2081 eq w))\n                     (S \u222a\u2081 eq w \u222a\u2081 dom_sb_S_rfrmw G (mkETC T S) rfi (eq w)))\n                  (mkETC\n                     (mkTC (covered T \u222a\u2081 eq r \u222a\u2081 eq w) (issued T \u222a\u2081 eq w))\n                     (S \u222a\u2081 eq w \u222a\u2081 dom_sb_S_rfrmw G (mkETC T S) rfi (eq w))))\n\n      (SIMREL_THREAD : simrel_thread G sc PC T S f_to f_from thread smode) :\n\n  let T' := mkTC (covered T \u222a\u2081 eq r \u222a\u2081 eq w) (issued T \u222a\u2081 eq w) in\n  let S' := S \u222a\u2081 eq w \u222a\u2081 dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) in\n  exists f_to' PC',\n    \u27ea PCSTEP : (plain_step MachineEvent.silent thread)\u207a PC PC' \u27eb /\\\n    \u27ea SIMREL_THREAD : simrel_thread G sc PC' T' S' f_to' f_from thread smode \u27eb /\\\n    \u27ea SIMREL :\n        smode = sim_normal -> simrel G sc PC T S f_to f_from ->\n        simrel G sc PC' T' S' f_to' f_from \u27eb.\nProof using WF CON.\n  cdes SIMREL_THREAD. cdes COMMON. cdes LOCAL.\n\n  assert (coherence G) as COH by apply CON.\n  assert (wf_sc G sc) as WF_sc by apply CON.\n  assert (coh_sc G sc) as COH_sc by apply CON.\n\n  assert (NEXT : next G (covered T) r).\n  { eapply ext_itrav_step_cov_next with (T:=mkETC T S); eauto. }\n \n  assert (WTID : thread = tid w).\n  { rewrite <- TID. by apply WF.(wf_rmwt). }\n  assert (ISS : ~ issued T w).\n  { cdes TSTEP2. desf. unfold ecovered, eissued in *; simpls.\n    intros HH. apply NCOV. apply COVEQ. clear. basic_solver. }\n\n  assert (S \u2286\u2081 E \u2229\u2081 W) as SEW.\n  { generalize TCCOH.(etc_S_in_E). generalize (reservedW WF TCCOH). clear. basic_solver. }\n\n  assert (sc_per_loc G) as SC_PER_LOC.\n  { by apply coherence_sc_per_loc; cdes CON. }\n  assert (tc_coherent G sc T) as TCCOHs.\n  { apply TCCOH. }\n\n  assert (~ covered T r) as RNCOV.\n  { apply NEXT. }\n\n  cdes STATE. rewrite <- TID in *.\n  edestruct sim_state_to_events as [ev HH]; eauto.\n  desc.\n\n  apply clos_rt_rt1n in ESTEPS.\n  eapply (rtc_lang_tau_step_rtc_thread_tau_step\n            _ _ _ local PC.(Configuration.sc) PC.(Configuration.memory)) in ESTEPS.\n\n  assert (E r /\\ E w) as [RACT WACT].\n  { apply (wf_rmwE WF) in RMW.\n    apply seq_eqv_l in RMW; destruct RMW as [WW RMW].\n    apply seq_eqv_r in RMW; desf. }\n\n  assert (R r /\\ W w) as [RREAD WWRITE].\n  { apply (wf_rmwD WF) in RMW.\n    apply seq_eqv_l in RMW; destruct RMW as [WW RMW].\n    apply seq_eqv_r in RMW; desf. }\n\n  assert (exists w', rf w' r) as [w' RF].\n  { by cdes CON; eapply Comp; split. }\n\n  assert (exists xrmw locr valr ordr, lab r = Aload xrmw ordr locr valr) as PARAMS; desf.\n  { unfold is_r in RREAD.\n    destruct (lab r); desf.\n      by exists ex; exists l; exists v; exists o. }\n  assert (exists xordw locw valw ordw, lab w = Astore xordw ordw locw valw) as WPARAMS; desf.\n  { unfold is_w in WWRITE.\n    destruct (lab w); desf.\n      by exists s; exists l; exists v; exists o. }\n\n  assert (locw = locr) as SAME_PARAMS; subst.\n  { apply (wf_rmwl WF) in RMW.\n    unfold same_loc, loc in *; desf. }\n\n  assert (COV : coverable G sc T r).\n  { apply coverable_add_eq_iff; auto.\n    apply covered_in_coverable; [|clear; basic_solver].\n    apply TSTEP1. }\n\n  assert (issued T w') as WISS.\n  { red in COV. destruct COV as [_ [[COV|COV]|COV]].\n    1,3: type_solver.\n    eapply COV.\n    eexists. apply seq_eqv_r. eauto. }\n\n  assert (S w') as SW'.\n  { by apply TCCOH.(etc_I_in_S). }\n\n  assert (~ is_init r) as RNINIT.\n  { intros H; apply (init_w WF) in H.\n    type_solver. }\n  assert (sb r w) as WRSB.\n  { apply wf_rmwi in RMW; red in RMW; desf. }\n\n  assert (~ covered T w) as WNCOV.\n  { intros H; apply NEXT.\n    apply TCCOH in H. apply H.\n    exists w. by apply seq_eqv_r; split. }\n  assert (~ is_init w) as WNINIT.\n  { intros H. apply WNCOV. by apply TCCOH. }\n\n  assert (loc lab r = Some locr) as RLOC.\n  { unfold loc. by rewrite PARAMS. }\n  assert (val lab r = Some valr) as RVAL.\n  { unfold val. by rewrite PARAMS. }\n\n  assert (loc lab w = Some locr) as WLOC.\n  { unfold loc. by rewrite WPARAMS. }\n  assert (val lab w = Some valw) as WVAL.\n  { unfold val. by rewrite WPARAMS. }\n\n  assert (W w') as WPWRITE.\n  { apply (wf_rfD WF) in RF. apply seq_eqv_l in RF; desf. }\n  assert (E w') as WPACT.\n  { apply (wf_rfE WF) in RF. apply seq_eqv_l in RF; desf. }\n  assert (loc lab w' = Some locr) as WPLOC.\n  { assert (loc lab w' = loc lab r) as HH.\n    { by apply (wf_rfl WF). }\n    rewrite HH.\n      by unfold loc; rewrite PARAMS. }\n  assert (val lab w' = Some valr) as WPVAL.\n  { assert (val lab w' = val lab r) as HH.\n    { by apply wf_rfv. }\n    rewrite HH.\n      by unfold val; rewrite PARAMS. }\n\n  assert (co w' w) as COWPW.\n  { cdes CON.\n    eapply rf_rmw_in_co; eauto.\n    eexists; eauto. }\n\n  assert (tid w = tid r) as TIDWR.\n  { destruct (sb_tid_init WRSB); desf. }\n\n  set (S' := S \u222a\u2081 eq w \u222a\u2081\n               dom_sb_S_rfrmw G (mkETC (mkTC (covered T \u222a\u2081 eq r) (issued T)) S) rfi (eq w)).\n  assert (S' \u2286\u2081 E \u2229\u2081 W) as SEW'.\n  { unfold S'. rewrite SEW at 1. unionL; auto.\n    { generalize WACT WWRITE. clear. basic_solver. }\n    rewrite NONEXT. basic_solver. }\n\n  edestruct SIM_MEM as [rel' DOM'].\n  { apply WISS. }\n  all: eauto.\n  simpls. desc.\n  clear DOM'1.\n\n  assert ((rf \u2a3e rmw) w' w) as RFRMW.\n  { exists r; split; auto. }\n  \n  (* destruct DOM1 as [WMEM [p_rel]]; eauto. desc. *)\n  (* destruct H0; desc. *)\n  (* { exfalso. apply NINRMW. exists w'. apply seq_eqv_l; split; auto. } *)\n  (* assert (p = w'); subst. *)\n  (* { eapply wf_rfrmwf; eauto. } *)\n  (* rewrite INMEM0 in P_INMEM. inv P_INMEM. clear P_INMEM. *)\n  (* rename p_v into valr. rename p_rel into rel'. *)\n \n  destruct (SAME_RMW w RMW) as [SAME WREPR].\n  assert (ev = ProgramEvent.update\n                  locr valr valw\n                  (Event_imm_promise.rmod ordr)\n                  (Event_imm_promise.wmod ordw)) as EV.\n  { red in SAME; red in SAME; simpls.\n    rewrite PARAMS in *; simpls.\n    rewrite WPARAMS in *; simpls.\n    destruct ev; desf; vauto. }\n\n  assert (Events.mod lab r = ordr) as RORD.\n  { unfold Events.mod. by rewrite PARAMS. }\n  assert (Events.mod lab w = ordw) as WORD.\n  { unfold Events.mod. by rewrite WPARAMS. }\n\n  edestruct (@read_step_helper G WF sc CON) as [TCCOH' HH]; eauto.\n  desc. rewrite <- TIDWR in *.\n\n  assert (tc_coherent G sc (mkTC (covered T \u222a\u2081 eq r) (issued T)))\n    as TCCOH1.\n  { apply TSTEP1. }\n\n  assert (issuable G sc (mkTC (covered T \u222a\u2081 eq r) (issued T)) w) as WNNISS.\n  { eapply issuable_next_w; eauto.\n    split; simpls.\n    red; split; [split|]; auto.\n    { red. intros x [y SBB]. apply seq_eqv_r in SBB. desc. rewrite <- SBB0 in *.\n      clear y SBB0.\n      destruct (classic (x = r)) as [EQ|NEQ].\n      { by right. }\n      left.\n      edestruct sb_semi_total_r with (x:=w) (y:=x) (z:=r); eauto.\n      { apply NEXT. eexists. apply seq_eqv_r. eauto. }\n      exfalso. eapply WF.(wf_rmwi); eauto. }\n    clear WREPR REPR.\n    red; intros [H|H]; [by desf|].\n    type_solver. }\n\n  edestruct (fun w1 w2 x z k w3 w4 w5 =>\n               @issue_reserved_step_helper_no_next\n               G WF sc CON (mkTC (covered T \u222a\u2081 eq r) (issued T)) S\n               w1 w2 f_to f_from FCOH\n               (Configuration.mk x PC.(Configuration.sc) PC.(Configuration.memory))\n               w3 smode w4 w5 (Local.mk z k)\n            ) with (w:=w) (valw:=valw) (ordw:=Events.mod lab w)\n    as [p_rel H].\n  all: simpls.\n  2: by apply SIM_PROM0.\n  5: by apply PLN_RLX_EQ0.\n  all: eauto.\n  { ins. rewrite IdentMap.gso in *; eauto. }\n  { rewrite IdentMap.gss. eauto. }\n  desc. red in H. desc.\n  destruct H0 as [H|H]; desc.\n  { exfalso. apply NINRMW. exists w'. apply seq_eqv_l. split; eauto. }\n  assert (p = w') as PW.\n  { eapply wf_rfrmwf; eauto. }\n  rewrite PW in *; clear PW.\n  simpls.\n  assert (p_rel = rel') as PW.\n  { rewrite INMEM in P_INMEM. clear -P_INMEM. inv P_INMEM. }\n  rewrite PW in *; clear PW.\n  (* destruct H1 as [H1|H1]; red in H1; desc. *)\n  (* 2: done. *)\n  destruct (is_rel lab w) eqn:RELVV; simpls.\n  \n  set (f_to' := upd f_to w (Time.middle (f_from w) (f_to w))).\n  assert (ISSEQ_TO : forall e : actid, issued T e -> f_to' e = f_to e).\n  { ins. unfold f_to'. rewrite updo; auto. by intros HH; subst. }\n\n  set (pe := ThreadEvent.update\n               locr (f_from w) (f_to' w) valr valw\n               rel' (Some\n                       (View.join\n                          (View.join\n                             (View.join\n                                (View.join (TView.cur (Local.tview local))\n                                           (View.singleton_ur_if\n                                              (Ordering.le\n                                                 Ordering.relaxed\n                                                 (Event_imm_promise.rmod (Events.mod lab r))) locr\n                                              (f_to w')))\n                                (if\n                                    Ordering.le Ordering.acqrel\n                                                (Event_imm_promise.rmod (Events.mod lab r))\n                                  then View.unwrap rel'\n                                  else View.bot)) (View.unwrap rel'))\n                          (View.singleton_ur locr (f_to' w))))\n               (Event_imm_promise.rmod ordr) (Event_imm_promise.wmod ordw)).\n\n  assert (Rlx r /\\ Rlx w) as [RRLX WRLX].\n  { split. all: apply ALLRLX; by split. }\n\n  assert (Ordering.le Ordering.relaxed (Event_imm_promise.rmod ordr)) as RLX_ORDR.\n  { unfold is_rlx, mode_le, Events.mod in *; simpls.\n    rewrite PARAMS in *.\n    destruct ordr; simpls. }\n  assert (Ordering.le Ordering.relaxed (Event_imm_promise.wmod ordw)) as RLX_ORDW.\n  { unfold is_rlx, mode_le, Events.mod in *; simpls.\n    rewrite WPARAMS in *.\n    destruct ordw; simpls. }\n  assert (Ordering.le Ordering.acqrel (Event_imm_promise.wmod ordw)) as REL_ORDW.\n  { unfold is_rel, mode_le, Events.mod in *; simpls.\n    rewrite WPARAMS in *.\n    destruct ordw; simpls. }\n  assert (Ordering.le Ordering.strong_relaxed (Event_imm_promise.wmod ordw)) as SRLX_ORDW.\n  { unfold is_rel, mode_le, Events.mod in *; simpls.\n    rewrite WPARAMS in *.\n    destruct ordw; simpls. }\n\n  assert (f_to w' = f_from w) as FF.\n  { rewrite <- ISSEQ_TO; auto.\n    apply FCOH0; auto.\n    { by do 2 left. }\n    clear. basic_solver. }\n\n  assert (forall l to from msg \n                 (NEQ  : l <> locr \\/ to <> f_to  w)\n                 (NEQ' : l <> locr \\/ to <> f_to' w),\n             Memory.get l to memory_add = Some (from, msg) <->\n             Memory.get l to PC.(Configuration.memory) = Some (from, msg))\n    as NOTNEWM.\n  { ins. erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_neq; auto.\n    erewrite Memory.remove_o; eauto.\n    rewrite loc_ts_eq_dec_neq; auto. }\n\n  set (pe_cancel :=\n         ThreadEvent.promise\n           locr (f_from w) (f_to w) Message.reserve\n           Memory.op_kind_cancel).\n\n  assert (f_to w' <> f_to w) as FWNEQ.\n  { intros HH.\n    eapply f_to_eq with (I:=S) in HH; subst; eauto.\n    red. by rewrite WLOC. }\n  assert (f_to w' <> f_to' w) as FWNEQ'.\n  { rewrite <- ISSEQ_TO; auto.\n    intros HH.\n    eapply f_to_eq in HH; (try by apply FCOH0); subst; eauto.\n    { red. by rewrite WLOC. }\n    all: clear -SW'; basic_solver. }\n\n  assert (forall y : actid, covered T y /\\ tid y = tid r -> sb y r) as COVNR.\n  { intros y [COVY TIDY].\n    edestruct same_thread with (x:=r) (y:=y) as [[|SB]|SB]; eauto.\n    { apply TCCOH in COVY. apply COVY. }\n    { exfalso. apply RNCOV. by subst. }\n    exfalso. apply RNCOV. apply TCCOH in COVY.\n    apply COVY. eexists. apply seq_eqv_r. eauto. }\n  assert (doma (sb \u2a3e \u2997eq r\u2998) (covered T)) as DOMASBR.\n  { red. ins. eapply NEXT. red. eauto. }\n\n  exists f_to'.\n  eexists (Configuration.mk _ _ memory_add).\n  apply and_assoc. apply pair_app.\n  { split.\n    { eapply t_trans; apply t_step.\n      { set (pe'' := MachineEvent.silent).\n        arewrite (pe'' = ThreadEvent.get_machine_event pe_cancel) by simpls.\n        econstructor; eauto.\n        2: by unfold pe_cancel; desf.\n        apply Thread.step_promise.\n        constructor.\n        2: by simpls.\n        econstructor; eauto. }\n      set (pe' := MachineEvent.silent).\n      arewrite (pe' = ThreadEvent.get_machine_event pe) by simpls.\n      eapply plain_step_intro with (lang:=thread_lts (tid w)); eauto.\n      { simpls. rewrite IdentMap.gss; eauto. }\n      2: by unfold pe; clear; desf.\n      apply Thread.step_program.\n      constructor.\n      { assert (ev = ThreadEvent.get_program_event pe) as EV' by done.\n        rewrite EV' in STEP; eauto. }\n      unfold pe; eapply Local.step_update.\n      { econstructor; eauto.\n        { simpls. rewrite <- FF.\n          erewrite Memory.remove_o; eauto.\n          rewrite loc_ts_eq_dec_neq; eauto. }\n        (* TODO: generalize! *)\n        assert\n          (Time.le (View.rlx (TView.cur (Local.tview local)) locr) (f_from w))\n          as PP.\n        2: constructor; auto.\n        2: by cdes PLN_RLX_EQ; simpls; rewrite EQ_CUR.\n        edestruct (max_event_cur) as [a_max]; eauto; desc.\n        assert (E a_max) as EA.\n        { apply (wf_urrE WF) in CCUR.\n          revert CCUR; unfold seq; unfolder; ins; desf.\n            by apply CON. }\n        assert (issued T a_max) as AISS.\n        { assert (A: (urr G sc locr \u2a3e \u2997coverable G sc T\u2998) a_max r).\n            by basic_solver.\n            apply (urr_coverable) in A; try done.\n            revert A; unfold seq; unfolder; ins; desf. }\n        assert (S a_max) as SA by (by apply TCCOH.(etc_I_in_S)).\n        rewrite <- FF.\n        destruct (classic (a_max = w')) as [|AWNEQ]; [by desf|].\n        edestruct (@wf_co_total G WF (Some locr) a_max) as [AWCO|AWCO].\n        3: by apply AWNEQ.\n        2: basic_solver.\n        apply set_interA; split; auto.\n        hahn_rewrite (@wf_urrD G sc locr) in CCUR.\n        revert CCUR; clear; basic_solver 12.\n        { etransitivity; eauto.\n          apply Time.le_lteq; left.\n          eapply f_to_co_mon; eauto.\n          all: generalize SA SW'; clear; basic_solver. }\n        exfalso.\n        eapply transp_rf_co_urr_irr; eauto.\n        exists w'; split.\n        { right; red; apply RF. }\n        exists a_max; split; eauto. }\n      econstructor; eauto.\n      { unfold TView.write_released, TView.write_tview. simpls. rewrite RLX_ORDW.\n        rewrite REL_ORDW.\n        unfold View.singleton_ur_if. rewrite RORD.\n        rewrite RLX_ORDR.\n        unfold LocFun.add. rewrite Loc.eq_dec_eq.\n        rewrite View.join_comm with (lhs:=View.unwrap rel').\n        rewrite !View.join_assoc.\n        rewrite View.join_comm with (lhs:=View.unwrap rel').\n          by rewrite FF. }\n      { unfold TView.write_released, TView.read_tview. simpls.\n        constructor. unfold View.join. simpls.\n        rewrite <- RORD. by rewrite <- FF. }\n      simpls. auto. intros HH.\n      eapply nonsynch_loc_le with (mem2:=local.(Local.promises)); auto.\n      eapply memory_remove_le; eauto. }\n    unnw.\n    red; splits; red; splits; simpls.\n    { apply TSTEP3. }\n    { rewrite set_inter_union_r.\n      apply set_subset_union_l; split.\n      etransitivity; eauto.\n      all: clear; basic_solver. }\n    { ins. apply WF.(wf_rmwD) in RMW0.\n      apply seq_eqv_l in RMW0; destruct RMW0 as [RR RMW0].\n      apply seq_eqv_r in RMW0; destruct RMW0 as [RMW0 WW].\n      split; intros [[HH|HH]|HH].\n      { left; left. erewrite <- RMWCOV; eauto. }\n      { subst. right. eapply wf_rmwf; eauto. }\n      { subst. clear -WWRITE RR. type_solver. }\n      { left; left. erewrite RMWCOV; eauto. }\n      { subst. clear -WW RREAD. type_solver. }\n      subst. left; right.\n      eapply wf_rmw_invf; eauto. }\n    { intros e' EE. \n      destruct (Ident.eq_dec (tid e') (tid w)) as [EQ|NEQ].\n      { rewrite EQ. eexists.\n        rewrite IdentMap.gss. eauto. }\n      do 2 (rewrite IdentMap.gso; auto). }\n    { ins. destruct (Ident.eq_dec thread' (tid w)) as [EQ|NEQ].\n      { subst. rewrite IdentMap.gss in TID.\n        inversion TID. simpls. }\n      eapply PROM_IN_MEM1; eauto.\n      do 2 (rewrite IdentMap.gso in TID; auto).\n      do 2 (rewrite IdentMap.gso; eauto). }\n    { intros NFSC. etransitivity; [by apply SC_COV|].\n      clear. basic_solver. }\n    { intros QQ l.\n      eapply max_value_same_set.\n      { by apply SC_REQ1. }\n      apply s_tm_n_f_steps.\n      { apply TCCOH'. }\n      { clear. basic_solver. }\n      intros a [[H|H]|H] HH AA.\n      { apply HH. by left. }\n      { subst. clear -RREAD AA. type_solver. }\n      subst. clear -WWRITE AA. type_solver. }\n    { eapply Memory.add_closed with (mem1:=memory_cancel); eauto.\n      eapply Memory.cancel_closed; eauto. }\n    rewrite IdentMap.gss.\n    eexists; eexists; eexists; splits; eauto; simpls.\n    { erewrite tau_steps_step_same_instrs; eauto. }\n    { ins. edestruct PROM_DISJOINT0 as [HH|]; eauto.\n      do 2 (rewrite IdentMap.gso in *; eauto). }\n    { clear WREPR REPR. rewrite <- FF, <- RORD, <- WORD.\n      apply SIM_MEM1. }\n    { eapply sim_tview_write_step; eauto.\n      3: { rewrite <- FF.\n           eapply sim_tview_f_issued with (T:=mkTC (covered T \u222a\u2081 eq r) (issued T)); eauto.\n           eapply sim_tview_read_step; eauto. }\n      { apply set_subset_union_l; split.\n        all: intros x H.\n        { apply TCCOH in H; apply H. }\n          by desf. }\n      { red. ins. left. apply seq_eqv_r in REL0.\n        destruct REL0 as [SB [COVY|]]; subst.\n        { apply TCCOH in COVY. apply COVY. eexists.\n          apply seq_eqv_r. eauto. }\n        apply NEXT. eexists. apply seq_eqv_r. eauto. }\n      { intros [HH|HH]. \n        { by apply WNCOV. }\n        clear -HH RREAD WWRITE.\n        type_solver. }\n      { intros y [[COVY|XX] TIDY].\n        2: { subst. apply rmw_in_sb; auto. }\n        eapply sb_trans.\n        2: { apply rmw_in_sb; eauto. }\n        edestruct same_thread with (x:=r) (y:=y) as [[SS|SB]|SB]; eauto.\n        { apply TCCOH in COVY. apply COVY. }\n        { by rewrite TIDY. }\n        { by subst. }\n        exfalso. apply RNCOV. apply TCCOH in COVY.\n        apply COVY. eexists. apply seq_eqv_r. eauto. }\n      { intros y z HH. apply seq_eqv_r in HH. destruct HH as [SB HH].\n        rewrite <- HH in *. clear z HH.\n        destruct (classic (y = r)) as [|NEQ].\n        { by right. }\n        edestruct sb_semi_total_r with (x:=w) (y:=y) (z:=r) as [AA|AA]; eauto.\n        { left. apply NEXT. eexists. apply seq_eqv_r. eauto. }\n        exfalso. eapply WF.(wf_rmwi); eauto. }\n      { erewrite Memory.add_o; eauto. by rewrite loc_ts_eq_dec_eq. }\n      done. }\n    { cdes PLN_RLX_EQ. \n      unfold TView.write_tview, TView.read_tview; simpls.\n      unfold View.singleton_ur_if.\n      rewrite RLX_ORDR.\n      destruct (Ordering.le Ordering.acqrel (Event_imm_promise.wmod ordw)); simpls.\n      red; splits; simpls.\n      all: desf; simpls.\n      all: try rewrite REL_PLN_RLX0.\n      all: try rewrite EQ_CUR.\n      all: try rewrite EQ_ACQ.\n      1-4: reflexivity.\n      all: intros l; unfold LocFun.add.\n      all: destruct (Loc.eq_dec l locr) as [|NEQ]; subst.\n      2,4: by apply EQ_REL.\n      all: unfold View.join; simpls.\n      all: rewrite EQ_CUR.\n      2: done.\n        by rewrite REL_PLN_RLX. }\n    { assert (Memory.closed_timemap (TimeMap.singleton locr (f_to' w)) memory_add) as AA.\n      { unfold TimeMap.singleton, LocFun.add; red; ins.\n        destruct (Loc.eq_dec loc locr); subst; eauto.\n        erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq. eauto. }\n      assert (Memory.closed_timemap (TimeMap.singleton locr (f_from w)) memory_add) as BB.\n      { unfold TimeMap.singleton, LocFun.add; red; ins.\n        destruct (Loc.eq_dec loc locr); subst; eauto.\n        rewrite <- FF.\n        erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_neq; auto.\n        erewrite Memory.remove_o; eauto. rewrite loc_ts_eq_dec_neq; auto.\n        eauto. }\n      assert (forall tmap,\n                 Memory.closed_timemap tmap PC.(Configuration.memory) ->\n                 Memory.closed_timemap tmap memory_add) as HH.\n      { intros tmap HH. red. ins.\n        specialize (HH loc). desc.\n        exists from, val, released.\n        destruct (classic (loc = locr)) as [|]; subst; auto.\n        2: by apply NOTNEWM; auto.\n        apply NOTNEWM; auto.\n        { destruct (classic (tmap locr = f_to w)) as [EQ|]; subst; auto.\n          rewrite EQ in HH. exfalso.\n          edestruct SIM_RES_MEM with (b:=w) as [OO]; eauto.\n          rewrite OO in HH. inv HH. }\n        destruct (classic (tmap locr = f_to' w)) as [EQ|]; subst; auto.\n        rewrite EQ in HH. exfalso.\n        unfold f_to' in HH. rewrite NINMEM in HH. inv HH. }\n      unfold TView.write_tview, TView.read_tview; simpls.\n      red; splits; simpls.\n      all: desf; ins.\n      all: repeat (apply Memory.join_closed_timemap); auto.\n      all: try by (apply HH; apply MEM_CLOSE).\n      all: try by apply Memory.closed_timemap_bot.\n      all: unfold LocFun.add; destruct (Loc.eq_dec loc locr); subst; eauto.\n      2,4: by (apply HH; apply MEM_CLOSE).\n      all: unfold View.join; simpls.\n      all: repeat (apply Memory.join_closed_timemap); auto.\n      all: try by (apply HH; apply MEM_CLOSE).\n        by apply Memory.closed_timemap_bot. }\n    red. splits; eauto.\n    ins. rewrite (INDEX_RMW w RMW); auto.\n    rewrite TIDWR in *.\n    apply sim_state_cover_rmw_events; auto. }\n  intros [PCSTEP SIMREL_THREAD']; split; auto.\n  intros SMODE SIMREL.\n  subst. desc. red.\n  splits; [by apply SIMREL_THREAD'|].\n  simpls. ins.\n  destruct (classic (thread = tid w)) as [|TNEQ]; subst.\n  { apply SIMREL_THREAD'. }\n  set (AA:=TP).\n  apply IdentMap.Facts.add_in_iff in AA.\n  destruct AA as [AA|AA]; subst; auto.\n  { apply SIMREL_THREAD'. }\n  apply IdentMap.Facts.add_in_iff in AA.\n  destruct AA as [AA|AA]; subst; auto.\n  { clear -TNEQ. desf. }\n  apply SIMREL in AA. cdes AA.\n  eapply simrel_thread_local_step with (thread:=tid w) (PC:=PC) (T:=T) (S:=S); eauto.\n  11: { simpls.\n        eapply msg_preserved_trans.\n        2: by eapply msg_preserved_add; eauto.\n        eapply msg_preserved_cancel; eauto. }\n  10: { simpls.\n        eapply closedness_preserved_trans.\n        2: by eapply closedness_preserved_add; eauto.\n        eapply closedness_preserved_cancel; eauto. }\n  9: by eapply same_other_threads_steps; eauto.\n  all: simpls; eauto.\n  { erewrite coveredE; eauto.\n    clear -RACT WACT. basic_solver. }\n  { rewrite issuedE; eauto. generalize WACT. clear. basic_solver. }\n  1-5: clear; basic_solver.\n  { rewrite dom_sb_S_rfrmw_same_tid; auto. clear. basic_solver. }\n  { ins.\n    etransitivity; [|by symmetry; apply IdentMap.Facts.add_in_iff].\n    split.\n    { ins; eauto. right. apply IdentMap.Facts.add_in_iff. eauto. }\n    intros [|HH]; subst; auto.\n    { apply SIMREL_THREAD; auto. }\n    apply IdentMap.Facts.add_in_iff in HH.\n    destruct HH as [|HH]; subst; auto.\n    apply IdentMap.Facts.in_find_iff. rewrite LLH. clear. desf. }\n  { apply IdentMap.Facts.in_find_iff. rewrite LLH0. clear. desf. }\n  { eapply sim_prom_f_issued; eauto. }\n  { (* TODO: generalize to a lemma? *)\n    red. ins. apply SIM_RPROM0 in RES. desc.\n    assert (b <> w) as BNW.\n    { intros HH; desf. }\n    exists b. splits; auto.\n    unfold f_to'. rewrite updo; auto. }\n  { eapply sim_mem_f_issued; eauto. }\n  { ins.\n    assert (b <> w) as BNW.\n    { intros HH; desf. }\n    unfold f_to'. rewrite updo; auto.\n    apply SIM_RES_MEM1; auto. }\n  eapply sim_tview_f_issued; eauto.\nUnshelve.\napply state.\nQed.\n\nEnd IssueReservedRelPlainStep.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/reserve_steps/IssueReservedRelPlainStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1750392441648745}}
{"text": "Require 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 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 TView.\nRequire Import Local.\nRequire Import Promises.\nRequire Import Global.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import BoolMap.\n\nRequire Import ReorderInternal.\n\nRequire Import MemoryProps.\nRequire Import LowerMemory.\n\nSet Implicit Arguments.\n\n\n\nDefinition release_event (e: ThreadEvent.t): Prop :=\n  match e with\n  | ThreadEvent.update _ _ _ _ _ _ _ _ ordw => True\n  | ThreadEvent.write _ _ _ _ _ ord => Ordering.le Ordering.plain ord\n  | ThreadEvent.fence _ ordw => Ordering.le Ordering.plain ordw\n  | ThreadEvent.syscall _ => True\n  | ThreadEvent.failure => True\n  | ThreadEvent.racy_write _ _ _ _ => True\n  | ThreadEvent.racy_update _ _ _ _ _ _ => True\n  | _ => False\n  end.\n\nDefinition is_na_write (e: ThreadEvent.t): Prop :=\n  match e with\n  | ThreadEvent.write _ _ _ _ _ ord => Ordering.le ord Ordering.na\n  | ThreadEvent.update _ _ _ _ _ _ _ _ ordw => Ordering.le ordw Ordering.na\n  | _ => False\n  end.\n\nVariant lower_step {lang} e (th0 th2: Thread.t lang): Prop :=\n| lower_step_intro\n    th1\n    (CANCEL:\n      ((<<NWRITE: ~ is_na_write e>>) /\\ (<<EQ: th1 = th0>>))\n      \\/\n        (exists loc from to val,\n            (<<EVENT: e = ThreadEvent.write loc from to val None Ordering.na>>) /\\\n              (<<STEP: Thread.step (ThreadEvent.cancel loc from to) th0 th1>>) /\\\n              (<<PROMISED: th0.(Thread.local).(Local.promises) loc = true>>)))\n    (STEP: Thread.program_step e th1 th2)\n    (NRELEASE: ~ release_event e)\n.\n\nLemma lower_step_step lang e th0 th1\n      (STEP: @lower_step lang e th0 th1)\n  :\n  rtc (@Thread.all_step _) th0 th1.\nProof.\n  i. inv STEP. des.\n  { econs 2; [|refl]. econs; eauto. inv STEP0. econs; eauto. }\n  { econs 2; [|].\n    { econs. eauto. }\n    { econs; [|refl]. inv STEP0. econs; eauto. }\n  }\nQed.\n\nLemma tau_lower_step_tau_step lang:\n  tau (@lower_step lang) <2= rtc (@Thread.tau_step lang).\nProof.\n  i. inv PR. inv TSTEP. des.\n  { econs 2; [|refl]. econs; eauto. inv STEP. econs; eauto. }\n  { econs 2; [|].\n    { econs; eauto. }\n    { econs; [|refl]. inv STEP. econs; eauto. }\n  }\nQed.\n\nLemma tau_lower_steps_tau_steps\n      lang (th0 th1: Thread.t lang)\n      (STEPS: rtc (tau lower_step) th0 th1)\n  :\n  rtc (@Thread.tau_step _) th0 th1.\nProof.\n  eapply rtc_join. eapply rtc_implies; [|eauto].\n  eapply tau_lower_step_tau_step.\nQed.\n\nLemma lower_step_tau_lower_step\n      lang e (th0 th1: Thread.t lang)\n      (STEP: lower_step e th0 th1)\n  :\n    tau lower_step th0 th1.\nProof.\n  inv STEP. econs; eauto.\n  { econs; eauto. }\n  { destruct e; ss. }\nQed.\n\nLemma lower_step_future\n      e lang (th1 th2: Thread.t lang)\n      (STEP: lower_step e th1 th2)\n      (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n      (GL_WF1: Global.wf (Thread.global th1)):\n  (<<LC_WF2: Local.wf (Thread.local th2) (Thread.global th2)>>) /\\\n    (<<GL_WF2: Global.wf (Thread.global th2)>>) /\\\n    (<<TVIEW_FUTURE: TView.le (Local.tview (Thread.local th1)) (Local.tview (Thread.local th2))>>) /\\\n    (<<GL_FUTURE: Global.future (Thread.global th1) (Thread.global th2)>>).\nProof.\n  eapply Thread.rtc_all_step_future; eauto.\n  eapply lower_step_step; eauto.\nQed.\n\nLemma lower_steps_future\n      lang (th1 th2: Thread.t lang)\n      (STEPS: rtc (tau lower_step) th1 th2)\n      (LC_WF1: Local.wf (Thread.local th1) (Thread.global th1))\n      (GL_WF1: Global.wf (Thread.global th1)):\n  (<<LC_WF2: Local.wf (Thread.local th2) (Thread.global th2)>>) /\\\n    (<<GL_WF2: Global.wf (Thread.global th2)>>) /\\\n    (<<TVIEW_FUTURE: TView.le (Local.tview (Thread.local th1)) (Local.tview (Thread.local th2))>>) /\\\n    (<<GL_FUTURE: Global.future (Thread.global th1) (Thread.global th2)>>).\nProof.\n  eapply Thread.rtc_tau_step_future; eauto.\n  eapply tau_lower_steps_tau_steps; eauto.\nQed.\n\n\nSection REORDER.\n\n  Lemma split_program_step\n        lang e (th0 th2: Thread.t lang)\n        (STEP: Thread.program_step e th0 th2)\n        (NRELEASE: ~ release_event e)\n        (LOCAL: Local.wf (Thread.local th0) (Thread.global th0))\n        (CLOSED: Global.wf (Thread.global th0)):\n    (exists th1,\n        (<<INTERNALS: rtc (@Thread.internal_step _) th0 th1>>) /\\\n          (<<LOWER: rtc (tau lower_step) th1 th2>>) /\\\n          (<<STATE: th0.(Thread.state) = th1.(Thread.state)>>)) \\/\n      (exists th1 e_race,\n          (<<STEP: Thread.step e_race th0 th1>>) /\\\n            (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>))\n  .\n  Proof.\n    destruct (classic (exists th1 e_race,\n                          (<<STEP: Thread.step e_race th0 th1>>) /\\\n                            (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>))).\n    { auto. }\n    left.\n    cut (exists th1,\n            (<<INTERNALS: rtc (@Thread.internal_step _) th0 th1>>) /\\\n              (<<LOWER: lower_step e th1 th2>>) /\\\n              (<<STATE: th0.(Thread.state) = th1.(Thread.state)>>)).\n    { i. des. esplits; eauto. econs 2; [|refl]. eapply lower_step_tau_lower_step; eauto. }\n    inv STEP. inv LOCAL0; ss.\n    { esplits; [refl|..]; eauto. econs; ss.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n    { esplits; [refl|..]; eauto. econs; ss.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n    { destruct ord; ss.\n      inv LOCAL1. hexploit add_succeed_wf; eauto. i. des.\n      hexploit Memory.add_exists.\n      { eauto. }\n      { eauto. }\n      { eapply Message.wf_reserve. }\n      i. des.\n      hexploit Memory.add_exists_le.\n      { eapply LOCAL. }\n      { eauto. }\n      i. des. destruct (lc1.(Local.promises) loc) eqn:PROMISED.\n      { esplits.\n        { econs 2; [|refl]. econs. econs 2. econs; eauto. }\n        { econs; ss.\n          { right.\n            { esplits; eauto. econs. econs. econs; eauto. econs; eauto.\n              { eapply memory_add_remove; eauto. }\n              { eapply memory_add_remove; eauto. }\n            }\n          }\n          { econs; ss. econs; eauto. }\n        }\n        { ss. }\n      }\n      { destruct (gl1.(Global.promises) loc) eqn:RACE.\n        { exfalso. eapply H. esplits.\n          { econs 2.\n            2:{ eapply Local.program_step_racy_write. econs; eauto. }\n            { eauto. }\n          }\n          { ss. }\n        }\n        esplits.\n        { econs 2.\n          { econs. econs 2. econs; eauto. }\n          econs 2; [|refl].\n          { econs. econs 1. econs; eauto. }\n        }\n        { econs; ss.\n          { right.\n            { esplits; eauto.\n              2:{ rewrite loc_fun_add_spec. des_ifs. }\n              econs. econs. econs; eauto. econs; eauto.\n              { eapply memory_add_remove; eauto. }\n              { eapply memory_add_remove; eauto. }\n            }\n          }\n          { econs; ss. econs. econs; ss.\n            { inv FULFILL; cycle 1.\n              { inv REMOVE. rewrite PROMISED in *. ss. }\n              econs 2; eauto.\n              { econs.\n                { rewrite loc_fun_add_spec. des_ifs. }\n                { extensionality loc0. rewrite ! loc_fun_add_spec. des_ifs. }\n              }\n              { econs.\n                { rewrite loc_fun_add_spec. des_ifs. }\n                { extensionality loc0. rewrite ! loc_fun_add_spec. des_ifs. }\n              }\n            }\n            { eauto. }\n          }\n        }\n        { ss. }\n      }\n    }\n    { esplits; [refl|..]; eauto. econs; ss.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n    { esplits; [refl|..]; eauto. econs; ss.\n      { left. eauto. }\n      { econs; eauto. }\n    }\n  Qed.\n\n  Lemma split_step\n        lang e (th0 th2: Thread.t lang)\n        (STEP: Thread.step e th0 th2)\n        (NRELEASE: ~ release_event e)\n        (LOCAL: Local.wf (Thread.local th0) (Thread.global th0))\n        (CLOSED: Global.wf (Thread.global th0)):\n    (exists th1,\n        (<<INTERNALS: rtc (@Thread.internal_step _) th0 th1>>) /\\\n          (<<LOWER: rtc (tau lower_step) th1 th2>>) /\\\n          (<<STATE: th0.(Thread.state) = th1.(Thread.state)>>)) \\/\n      (exists th1 e_race,\n          (<<STEP: Thread.step e_race th0 th1>>) /\\\n            (<<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>))\n  .\n  Proof.\n    inv STEP.\n    { left. esplits.\n      { econs 2; [|refl]. econs; eauto. }\n      { refl. }\n      ss.\n    }\n    { hexploit split_program_step; eauto. econs; eauto. }\n  Qed.\n\n  Lemma reorder_lower_step_internal_step\n        lang e1 (th0 th1 th2: @Thread.t lang)\n        (WF: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (CLOSED: Global.wf th0.(Thread.global))\n        (STEP1: lower_step e1 th0 th1)\n        (STEP2: Thread.internal_step th1 th2):\n    exists th1',\n      (<<STEP1: rtc (@Thread.internal_step _) th0 th1'>>) /\\\n        (<<STEP2: lower_step e1 th1' th2>>) /\\\n        (<<STATE: th0.(Thread.state) = th1'.(Thread.state)>>).\n  Proof.\n    inv STEP1. des; subst.\n    { (* program; internal *)\n      inv STEP. inv STEP2. ss.\n      exploit reorder_program_internal; eauto.\n      { destruct e1; ss. destruct ordw; ss. }\n      i. unguard. des; subst.\n      { esplits; try refl. econs; eauto. econs; eauto. }\n      { esplits.\n        { econs 2; try refl. econs. eauto. }\n        { econs; eauto. econs; eauto. }\n        { ss. }\n      }\n    }\n\n    inv STEP0; inv LOCAL. inv STEP. inv LOCAL. ss.\n    inv STEP2. inv LOCAL.\n    { (* cancel; write; promise *)\n      destruct (Loc.eq_dec loc loc0); subst.\n      { exploit reorder_write_promise_same; eauto. i. unguard. des; subst.\n        { esplits; eauto. econs.\n          { right. esplits; eauto. }\n          { econs; eauto. }\n          { ss. }\n        }\n        { exploit reorder_cancel_promise; eauto. i. des.\n          esplits.\n          { econs 2; try refl. econs. econs 1. eauto. }\n          { econs.\n            { right. esplits; eauto. ss.\n              inv STEP0. inv PROMISE.\n              exploit BoolMap.add_get0; try exact ADD. i. des. ss.\n            }\n            { econs; eauto. }\n            { ss. }\n          }\n          { ss. }\n        }\n      }\n      { exploit reorder_write_promise; eauto. i. des.\n        exploit reorder_cancel_promise; eauto. i. des.\n        esplits.\n        { econs 2; try refl. econs. econs 1. eauto. }\n        { econs.\n          { right. esplits; eauto. ss.\n            inv STEP0. inv PROMISE. ss.\n            erewrite BoolMap.add_o; eauto. condtac; ss.\n          }\n          { econs; eauto. }\n          { ss. }\n        }\n        { ss. }\n      }\n    }\n\n    { (* cancel; write; reserve *)\n      exploit reorder_write_reserve; eauto. i. des.\n      exploit reorder_cancel_reserve; eauto.\n      { inv LOCAL0. inv CANCEL.\n        exploit Memory.remove_get0; try exact MEM. i. des.\n        exploit Memory.get_ts; try exact GET. i. des; ss. subst.\n        inv CLOSED. inv MEM_CLOSED.\n        rewrite INHABITED in *. ss.\n      }\n      { destruct (Loc.eq_dec loc loc0); auto. subst. right.\n        inv LOCAL1. inv LOCAL2. inv RESERVE. ss.\n        exploit Memory.add_get0; try exact WRITE. i. des.\n        exploit Memory.add_get0; try exact MEM. i. des.\n        exploit Memory.add_get1; try exact GET0; eauto. i.\n        exploit Memory.get_disjoint; [exact x0|exact GET2|]. i. des; ss.\n      }\n      i. des. esplits.\n      { econs 2; try refl. econs. econs 2. eauto. }\n      { econs.\n        { right. esplits; eauto. ss. inv STEP0. ss. }\n        { econs; eauto. }\n        { ss. }\n      }\n      { ss. }\n    }\n\n    { (* cancel; write; cancel *)\n      exploit reorder_write_cancel; eauto. i. des.\n      exploit reorder_cancel_cancel; [exact LOCAL0|..]; eauto. i. des.\n      esplits.\n      { econs 2; try refl. econs. econs 3. exact STEP0. }\n      { econs.\n        { right. esplits; eauto. ss. inv STEP0. ss. }\n        { econs; eauto. }\n        { ss. }\n      }\n      { ss. }\n    }\n  Qed.\n\n  Lemma reorder_lower_steps_internal_steps\n        lang (th0 th1 th2: @Thread.t lang)\n        (WF: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (CLOSED: Global.wf th0.(Thread.global))\n        (STEPS1: rtc (tau lower_step) th0 th1)\n        (STEPS2: rtc (@Thread.internal_step _) th1 th2):\n    exists th1',\n      (<<STEPS1: rtc (@Thread.internal_step _) th0 th1'>>) /\\\n        (<<STEPS2: rtc (tau lower_step) th1' th2>>) /\\\n        (<<STATE: th0.(Thread.state) = th1'.(Thread.state)>>).\n  Proof.\n    revert th2 STEPS2.\n    induction STEPS1; i.\n    { esplits; eauto using Forall2_refl.\n      clear - STEPS2.\n      induction STEPS2; eauto.\n      rewrite <- IHSTEPS2; eauto. inv H. ss.\n    }\n    inv H.\n    exploit lower_step_future; eauto. i. des.\n    exploit IHSTEPS1; eauto. i. des.\n    cut (exists th1'',\n            rtc (@Thread.internal_step _) x th1'' /\\\n              lower_step e th1'' th1' /\\\n              x.(Thread.state) = th1''.(Thread.state)).\n    { i. des. esplits; eauto. }\n    exploit Thread.rtc_internal_step_future; eauto. i. des.\n    clear z STEPS1 IHSTEPS1 STEPS2 STEPS3.\n    clear - WF CLOSED TSTEP STEPS0.\n    rename th1' into z, STEPS0 into STEPS.\n    revert x e WF CLOSED TSTEP.\n    induction STEPS; i.\n    { esplits; eauto. }\n    exploit lower_step_future; eauto. i. des.\n    exploit Thread.internal_step_future; eauto. i. des.\n    exploit reorder_lower_step_internal_step; try exact TSTEP; eauto. i. des.\n    exploit Thread.rtc_internal_step_future; eauto. i. des.\n    exploit IHSTEPS; try exact STEP2; eauto. i. des.\n    esplits; try exact x1; eauto.\n    { etrans; eauto. }\n    { congr. }\n  Qed.\n\nEnd REORDER.\n\n\nSection CHERRY.\n\n  (* unused *)\n  Variant cherrypicked A: (A * A) -> (A * A) -> Prop :=\n    | cherrypicked_unchanged\n        a0 a1\n      :\n      cherrypicked (a0, a1) (a0, a1)\n    | cherrypicked_changed\n        a0 a1 a\n      :\n      cherrypicked (a0, a1) (a, a)\n  .\n\n  Global Program Instance cherrypicked_PreOrder A: PreOrder (@cherrypicked A).\n  Next Obligation.\n  Proof.\n    ii. destruct x. econs 1.\n  Qed.\n  Next Obligation.\n  Proof.\n    ii. inv H; inv H0.\n    { econs 1. }\n    { econs 2. }\n    { econs 2. }\n    { econs 2. }\n  Qed.\n\n  Variant cherrypicked_promise:\n    ((bool * bool) * (bool * bool)) -> ((bool * bool) * (bool * bool)) -> Prop :=\n    | cherrypicked_promise_unchanged\n        gp_src lp_src gp_tgt lp_tgt\n      :\n      cherrypicked_promise ((gp_src, lp_src), (gp_tgt, lp_tgt)) ((gp_src, lp_src), (gp_tgt, lp_tgt))\n    | cherrypicked_promise_fulfilled\n      :\n      cherrypicked_promise ((true, true), (true, true)) ((false, false), (false, false))\n  .\n\n  Global Program Instance cherrypicked_promise_PreOrder: PreOrder (cherrypicked_promise).\n  Next Obligation.\n  Proof.\n    ii. destruct x as [[] []]. econs 1.\n  Qed.\n  Next Obligation.\n  Proof.\n    ii. inv H; inv H0.\n    { econs 1. }\n    { econs 2. }\n    { econs 2. }\n  Qed.\n\n  Definition cherrypicked_promises:\n    ((BoolMap.t * BoolMap.t) * (BoolMap.t * BoolMap.t))\n    ->\n      ((BoolMap.t * BoolMap.t) * (BoolMap.t * BoolMap.t))\n    -> Prop :=\n    fun '((gprm_src0, lprm_src0), (gprm_tgt0, lprm_tgt0))\n        '((gprm_src1, lprm_src1), (gprm_tgt1, lprm_tgt1)) =>\n      forall loc, cherrypicked_promise\n                    ((gprm_src0 loc, lprm_src0 loc), (gprm_tgt0 loc, lprm_tgt0 loc))\n                    ((gprm_src1 loc, lprm_src1 loc), (gprm_tgt1 loc, lprm_tgt1 loc)).\n\n  Global Program Instance cherrypicked_promises_PreOrder: PreOrder cherrypicked_promises.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_promises. ii. des_ifs. i. refl.\n  Qed.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_promises. ii. des_ifs. i. etrans; eauto.\n  Qed.\n\n  Variant cherrypicked_content:\n    ((option (Time.t * Message.t) * option (Time.t * Message.t)) * (option (Time.t * Message.t) * option (Time.t * Message.t))) -> ((option (Time.t * Message.t) * option (Time.t * Message.t)) * (option (Time.t * Message.t) * option (Time.t * Message.t))) -> Prop :=\n    | cherrypicked_content_unchanged\n        gm_src lm_src gm_tgt lm_tgt\n      :\n      cherrypicked_content ((gm_src, lm_src), (gm_tgt, lm_tgt)) ((gm_src, lm_src), (gm_tgt, lm_tgt))\n    | cherrypicked_content_fulfilled\n        from val released na\n      :\n      cherrypicked_content\n        ((Some (from, Message.reserve), Some (from, Message.reserve)), (Some (from, Message.reserve), Some (from, Message.reserve)))\n        ((Some (from, Message.message val released na), None), (Some (from, Message.message val released na), None))\n  .\n\n  Global Program Instance cherrypicked_content_PreOrder: PreOrder (cherrypicked_content).\n  Next Obligation.\n  Proof.\n    ii. destruct x as [[] []]. econs 1.\n  Qed.\n  Next Obligation.\n  Proof.\n    ii. inv H; inv H0.\n    { econs 1. }\n    { econs 2. }\n    { econs 2. }\n  Qed.\n\n  Definition cherrypicked_memory:\n    ((Memory.t * Memory.t) * (Memory.t * Memory.t))\n    ->\n      ((Memory.t * Memory.t) * (Memory.t * Memory.t))\n    -> Prop :=\n    fun '((mem_src0, rsv_src0), (mem_tgt0, rsv_tgt0))\n        '((mem_src1, rsv_src1), (mem_tgt1, rsv_tgt1)) =>\n      forall loc to, cherrypicked_content\n                       ((Memory.get loc to mem_src0, Memory.get loc to rsv_src0), (Memory.get loc to mem_tgt0, Memory.get loc to rsv_tgt0))\n                       ((Memory.get loc to mem_src1, Memory.get loc to rsv_src1), (Memory.get loc to mem_tgt1, Memory.get loc to rsv_tgt1)).\n\n  Global Program Instance cherrypicked_memory_PreOrder: PreOrder cherrypicked_memory.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_memory. ii. des_ifs. i. refl.\n  Qed.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_memory. ii. des_ifs. i. etrans; eauto.\n  Qed.\n\n  Definition cherrypicked_global:\n    ((Global.t * Local.t) * (Global.t * Local.t))\n    ->\n      ((Global.t * Local.t) * (Global.t * Local.t))\n    -> Prop :=\n    fun '((Global.mk sc_src0 gprm_src0 mem_src0, Local.mk tvw_src0 lprm_src0 rsv_src0), (Global.mk sc_tgt0 gprm_tgt0 mem_tgt0, Local.mk tvw_tgt0 lprm_tgt0 rsv_tgt0))\n        '((Global.mk sc_src1 gprm_src1 mem_src1, Local.mk tvw_src1 lprm_src1 rsv_src1), (Global.mk sc_tgt1 gprm_tgt1 mem_tgt1, Local.mk tvw_tgt1 lprm_tgt1 rsv_tgt1)) =>\n      (<<SC_SRC: sc_src1 = sc_src0>>) /\\\n        (<<SC_TGT: sc_tgt1 = sc_tgt0>>) /\\\n        (<<MEM: cherrypicked_memory ((mem_src0, rsv_src0), (mem_tgt0, rsv_tgt0)) ((mem_src1, rsv_src1), (mem_tgt1, rsv_tgt1))>>) /\\\n        (<<PRM: cherrypicked_promises ((gprm_src0, lprm_src0), (gprm_tgt0, lprm_tgt0)) ((gprm_src1, lprm_src1), (gprm_tgt1, lprm_tgt1))>>).\n\n  Global Program Instance cherrypicked_global_PreOrder: PreOrder cherrypicked_global.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_global. ii. des_ifs. splits; auto.\n    { refl. }\n    { refl. }\n  Qed.\n  Next Obligation.\n  Proof.\n    unfold cherrypicked_global. ii. des_ifs. des. subst. splits; auto.\n    { etrans; eauto. }\n    { etrans; eauto. }\n  Qed.\n\nEnd CHERRY.\n\n\nSection LOWERMEM.\n  Variable lang: language.\n\n  Lemma strong_le_racy\n        lc gl_src gl_tgt loc to_tgt ord\n        (SIMGLOBAL: Global.strong_le gl_tgt gl_src)\n        (RACE: Local.is_racy lc gl_tgt loc to_tgt ord)\n        (LOCAL: Local.wf lc gl_tgt)\n    :\n    exists to_src,\n      (<<RACE: Local.is_racy lc gl_src loc to_src ord>>).\n  Proof.\n    inv RACE.\n    { inv SIMGLOBAL. inv ADDNA. specialize (ADDNA0 loc). des.\n      { esplits. econs 1; eauto.\n        { eapply Bool.le_implb in PROMISES.\n          rewrite GET in PROMISES. ss.\n        }\n      }\n      { rr in LATEST. des. esplits. econs 2; eauto.\n        inv LOCAL. inv TVIEW_CLOSED. inv CUR.\n        specialize (PLN loc). des. eapply LATEST0 in PLN. auto.\n      }\n    }\n    { esplits. econs 2; eauto.\n      { eapply SIMGLOBAL. eauto. }\n    }\n  Qed.\n\n  Lemma lower_step_strong_future e_tgt st0 st1\n        lc0 lc1 gl_tgt0 gl_tgt1\n        gl_src0\n        (STEP: lower_step e_tgt (Thread.mk lang st0 lc0 gl_tgt0) (Thread.mk lang st1 lc1 gl_tgt1))\n\n        (SIMGLOBAL: Global.strong_le gl_tgt0 gl_src0)\n\n        (LOCALSRC: Local.wf lc0 gl_src0)\n        (LOCALTGT: Local.wf lc0 gl_tgt0)\n        (GLOBALSRC: Global.wf gl_src0)\n        (GLOBALTGT: Global.wf gl_tgt0)\n    :\n    (exists e_src gl_src1,\n        (<<STEP: lower_step e_src (Thread.mk lang st0 lc0 gl_src0) (Thread.mk lang st1 lc1 gl_src1)>>) /\\\n          (<<SIMGLOBAL: Global.strong_le gl_tgt1 gl_src1>>) /\\\n          (<<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n          (<<CHERRY: cherrypicked_global (gl_src0, lc0, (gl_tgt0, lc0)) (gl_src1, lc1, (gl_tgt1, lc1))>>)) \\/\n      (exists e_failure,\n          (<<STEP: Thread.step e_failure (Thread.mk lang st0 lc0 gl_src0) (Thread.mk lang st1 lc0 gl_src0)>>) /\\\n            (<<EVENT: ThreadEvent.get_machine_event e_failure = MachineEvent.failure>>)).\n  Proof.\n    inv STEP. des; subst.\n    { inv STEP0. inv LOCAL; ss.\n      { left. exists (ThreadEvent.silent). esplits.\n        { econs.\n          { left. eauto. }\n          { econs; eauto. }\n          { ss. }\n        }\n        { ss. }\n        { ss. }\n        { des_ifs. splits; ss; i; try refl. }\n      }\n      { left. exists (ThreadEvent.read loc to val released ord).\n        inv LOCAL0. esplits.\n        { econs.\n          { left. eauto. }\n          { econs; eauto. econs; eauto.\n            eapply SIMGLOBAL in GET. econs; eauto.\n          }\n          { ss. }\n        }\n        { ss. }\n        { ss. }\n        { des_ifs. splits; ss; i; try refl. }\n      }\n      { destruct ord; ss. }\n      { left. exists (ThreadEvent.fence ordr ordw).\n        inv LOCAL0. esplits.\n        { econs.\n          { left. eauto. }\n          { econs; eauto. econs; eauto. econs; eauto.\n            f_equal. eapply TViewFacts.write_fence_tview_acqrel.\n            destruct ordw; ss.\n          }\n          { ss. }\n        }\n        { inv SIMGLOBAL. econs.\n          { inv LE. econs; ss.\n            rewrite ! TViewFacts.write_fence_sc_acqrel; auto.\n            { destruct ordw; ss. }\n            { destruct ordw; ss. }\n          }\n          inv ADDNA. econs; eauto.\n        }\n        { ss. }\n        { des_ifs. splits; ss; i; try refl.\n          { destruct ordw; ss. }\n          { destruct ordw; ss. }\n        }\n      }\n      { left. inv LOCAL0. hexploit strong_le_racy; eauto.\n        i. des. exists (ThreadEvent.racy_read loc to_src val ord).\n        esplits.\n        { econs.\n          { left. eauto. }\n          { econs; eauto. }\n          { ss. }\n        }\n        { auto. }\n        { ss. }\n        { des_ifs. splits; ss; i; try refl. }\n      }\n    }\n    { inv STEP.\n      2:{ inv LOCAL; ss. }\n      inv STEP0; ss.\n      destruct (classic (exists to, Local.is_racy lc0 gl_src0 loc to Ordering.na)).\n      { des. right. esplits.\n        { econs 2.\n          2:{ eapply Local.program_step_racy_write. econs; eauto. }\n          { eauto. }\n        }\n        { ss. }\n      }\n      left. ss. exists (ThreadEvent.write loc from to val None Ordering.na).\n      inv LOCAL. inv LOCAL0. inv LOCAL. inv LOCAL1. ss.\n      inv CANCEL. hexploit Memory.remove_exists_le.\n      { eapply LOCALSRC. }\n      { eauto. }\n      i. des. hexploit add_succeed_wf; eauto. i. des.\n      hexploit (@Memory.add_exists mem2' loc from to); eauto.\n      { i. erewrite Memory.remove_o in GET2; eauto. des_ifs.\n        hexploit Memory.get_disjoint.\n        { eapply Memory.remove_get0. eapply H0. }\n        { eapply GET2. }\n        i. ss. des; clarify.\n      }\n      i. des.\n      assert (exists gprm_src1,\n                 (<<FULFILL: Promises.fulfill (Local.promises lc0) (Global.promises gl_src0) loc Ordering.na prm2 gprm_src1>>) /\\\n                   (<<SAME:__guard__((<<TGTG: gprm2 = gl_tgt0.(Global.promises)>>) /\\ (<<SRCG: gprm_src1 = gl_src0.(Global.promises)>>) /\\ (<<PRML: prm2 = lc0.(Local.promises)>>) \\/\n                                       ((<<TGTG: BoolMap.remove gl_tgt0.(Global.promises) loc gprm2>>) /\\ (<<SRCG: BoolMap.remove gl_src0.(Global.promises) loc gprm_src1>>) /\\ (<<PRML: BoolMap.remove lc0.(Local.promises) loc prm2>>)))>>)).\n      { inv FULFILL.\n        { esplits.\n          { econs 1; eauto. }\n          { left. splits; auto. }\n        }\n        { assert (SRC: Global.promises gl_src0 loc = true).\n          { inv REMOVE. eapply LOCALSRC in GET. auto. }\n          esplits.\n          { econs 2; eauto. }\n          { right. splits; auto. }\n        }\n      }\n      des. esplits.\n      { econs.\n        { right. esplits; eauto. }\n        { econs; eauto. }\n        { ss. }\n      }\n      { inv SIMGLOBAL. econs; ss.\n        { inv LE. econs; eauto; ss.\n          ii. erewrite (@Memory.add_o _ mem0) in LHS; eauto.\n          erewrite (@Memory.add_o _ mem2'); eauto.\n          erewrite (@Memory.remove_o _ (Global.memory gl_tgt0)) in LHS; eauto.\n          erewrite (@Memory.remove_o _ (Global.memory gl_src0)); eauto.\n          des_ifs. eapply MEMORY; eauto.\n        }\n        { inv ADDNA. econs; ss. i. specialize (ADDNA0 loc0). des.\n          { left. r in SAME. des; subst.\n            { auto. }\n            { inv TGTG. inv SRCG. rewrite ! loc_fun_add_spec.\n              r. clear - PROMISES. des_ifs.\n            }\n          }\n          { destruct (Loc.eq_dec loc0 loc); subst.\n            { right. inv LATEST. des. exfalso.\n              eapply H. esplits. econs 2; eauto.\n              inv LOCALTGT. inv TVIEW_CLOSED. inv CUR.\n              specialize (PLN loc). des.\n              eapply LATEST in PLN. auto.\n            }\n            { right. inv LATEST. des.\n              econs. esplits.\n              { erewrite Memory.add_get1; eauto.\n                eapply Memory.remove_get1 in GET; eauto.\n                des; eauto. subst; ss.\n              }\n              { i. erewrite Memory.add_o in GET0; eauto.\n                erewrite Memory.remove_o in GET0; eauto.\n                des_ifs; eauto. ss. des; subst; ss.\n              }\n            }\n          }\n        }\n      }\n      { ss. }\n      { des_ifs. splits; ss; i; try refl.\n        { erewrite (@Memory.add_o mem2); eauto.\n          erewrite (@Memory.remove_o mem0); eauto.\n          erewrite (@Memory.add_o mem1); eauto.\n          erewrite (@Memory.remove_o mem2'); eauto.\n          erewrite (@Memory.remove_o rsv2); eauto. des_ifs.\n          { ss. des; clarify.\n            eapply Memory.remove_get0 in MEM.\n            eapply Memory.remove_get0 in RSV.\n            eapply Memory.remove_get0 in H0. des.\n            rewrite GET3. rewrite GET. rewrite GET1. econs 2.\n          }\n          { econs. }\n        }\n        { r in SAME. des; subst.\n          { refl. }\n          { inv TGTG. inv SRCG. inv PRML.\n            rewrite ! loc_fun_add_spec. des_ifs.\n            { econs 2. }\n            { refl. }\n          }\n        }\n      }\n    }\n  Qed.\n\n  Lemma lower_steps_strong_future st0 st1\n        lc0 lc1 gl_tgt0 gl_tgt1\n        gl_src0\n        (STEPS: rtc (tau lower_step) (Thread.mk lang st0 lc0 gl_tgt0) (Thread.mk lang st1 lc1 gl_tgt1))\n\n        (SIMGLOBAL: Global.strong_le gl_tgt0 gl_src0)\n\n        (LOCALSRC: Local.wf lc0 gl_src0)\n        (LOCALTGT: Local.wf lc0 gl_tgt0)\n        (GLOBALSRC: Global.wf gl_src0)\n        (GLOBALTGT: Global.wf gl_tgt0)\n    :\n    (exists gl_src1,\n        (<<STEPS: rtc (tau lower_step) (Thread.mk lang st0 lc0 gl_src0) (Thread.mk lang st1 lc1 gl_src1)>>) /\\\n          (<<SIMGLOBAL: Global.strong_le gl_tgt1 gl_src1>>) /\\\n          (<<CHERRY: cherrypicked_global (gl_src0, lc0, (gl_tgt0, lc0)) (gl_src1, lc1, (gl_tgt1, lc1))>>)) \\/\n      (exists st0' st1' lc' gl' e_failure,\n          (<<STEPS: rtc (tau lower_step) (Thread.mk lang st0 lc0 gl_src0) (Thread.mk lang st0' lc' gl')>>) /\\\n            (<<STEP: Thread.step e_failure (Thread.mk lang st0' lc' gl') (Thread.mk lang st1' lc' gl')>>) /\\\n            (<<EVENT: ThreadEvent.get_machine_event e_failure = MachineEvent.failure>>)).\n  Proof.\n    remember (Thread.mk _ st0 lc0 gl_tgt0).\n    remember (Thread.mk _ st1 lc1 gl_tgt1).\n    revert st0 st1 lc0 lc1 gl_tgt0 gl_src0 gl_tgt1 Heqt Heqt0 SIMGLOBAL LOCALSRC LOCALTGT GLOBALSRC GLOBALTGT.\n    induction STEPS; i; clarify.\n    { left. esplits; eauto. refl. }\n    inv H. destruct y.\n    hexploit lower_step_future; eauto. i. des.\n    hexploit lower_step_strong_future; eauto. i. des.\n    2:{ right. esplits; eauto. }\n    hexploit lower_step_future; eauto. i. des. ss.\n    hexploit IHSTEPS; eauto. i. des.\n    { left. esplits.\n      { econs 2; [|eauto]. econs; eauto. rewrite EVENT0. auto. }\n      { auto. }\n      { des_ifs. des. subst. splits; auto; i; try by (etrans; eauto). }\n    }\n    { right. esplits.\n      { econs 2; [|eauto]. econs; eauto. rewrite EVENT0. auto. }\n      { eauto. }\n      { eauto. }\n    }\n  Qed.\nEnd LOWERMEM.\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/LowerStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.17482433453615698}}
{"text": "Require Import syntax.\nRequire Import Metatheory.\n\nRequire Import List.\nRequire Import ListSet.\nRequire Import Bool.\nRequire Import Arith.\nRequire Import Compare_dec.\nRequire Import Omega.\nRequire Import monad.\nRequire Import Decidable.\nRequire Import alist.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import maps_ext.\nRequire Import Memory.\nRequire Import Lattice.\nRequire Import targetdata.\nRequire Import util.\n\nModule LLVMinfra.\n\nExport LLVMsyntax.\n\n(**********************************)\n(* Definition for basic types, which can be refined for extraction. *)\n\nDefinition id_dec : forall x y : id, {x=y} + {x<>y} := eq_atom_dec.\nDefinition l_dec : forall x y : l, {x=y} + {x<>y} := eq_atom_dec.\nDefinition inbounds_dec : forall x y : inbounds, {x=y} + {x<>y} := bool_dec.\nDefinition tailc_dec : forall x y : tailc, {x=y} + {x<>y} := bool_dec.\nDefinition noret_dec : forall x y : noret, {x=y} + {x<>y} := bool_dec.\n\n(**********************************)\n(* LabelSet. *)\n\n  Definition lempty_set := empty_set l.\n  Definition lset_add (l1:l) (ls2:ls) := set_add eq_dec l1 ls2.\n  Definition lset_union (ls1 ls2:ls) := set_union eq_dec ls1 ls2.\n  Definition lset_inter (ls1 ls2:ls) := set_inter eq_dec ls1 ls2.\n  Definition lset_eqb (ls1 ls2:ls) :=\n    match (lset_inter ls1 ls2) with\n    | nil => true\n    | _ => false\n    end.\n  Definition lset_neqb (ls1 ls2:ls) :=\n    match (lset_inter ls1 ls2) with\n    | nil => false\n    | _ => true\n    end.\n  Definition lset_eq (ls1 ls2:ls) := lset_eqb ls1 ls2 = true.\n  Definition lset_neq (ls1 ls2:ls) := lset_neqb ls1 ls2 = true.\n  Definition lset_single (l0:l) := lset_add l0 (lempty_set).\n  Definition lset_mem (l0:l) (ls0:ls) := set_mem eq_dec l0 ls0.\n\n(**********************************)\n(* Inversion. *)\n\n  Definition getCmdLoc (i:cmd) : id :=\n  match i with\n  | insn_nop id => id\n  | insn_bop id _ sz v1 v2 => id\n  | insn_fbop id _ _ _ _ => id\n  (* | insn_extractelement id typ0 id0 c1 => id *)\n  (* | insn_insertelement id typ0 id0 typ1 v1 c2 => id *)\n  | insn_extractvalue id typs id0 c1 _ => id\n  | insn_insertvalue id typs id0 typ1 v1 c2 => id\n  | insn_malloc id _ _ _ => id\n  | insn_free id _ _ => id\n  | insn_alloca id _ _ _ => id\n  | insn_load id typ1 v1 _ => id\n  | insn_store id typ1 v1 v2 _ => id\n  | insn_gep id _ _ _ _ _ => id\n  | insn_trunc id _ typ1 v1 typ2 => id\n  | insn_ext id _ sz1 v1 sz2 => id\n  | insn_cast id _ typ1 v1 typ2 => id\n  | insn_icmp id cond typ v1 v2 => id\n  | insn_fcmp id cond typ v1 v2 => id\n  | insn_select id v0 typ v1 v2 => id\n  | insn_call id _ _ _ _ v0 paraml => id\n  end.\n\n  Definition getTerminatorID (i:terminator) : id :=\n  match i with\n  | insn_return id t v => id\n  | insn_return_void id => id\n  | insn_br id v l1 l2 => id\n  | insn_br_uncond id l => id\n  | insn_switch id t v l _ => id\n  (* | insn_invoke id typ id0 paraml l1 l2 => id *)\n  | insn_unreachable id => id\n  end.\n\n  Definition getPhiNodeID (i:phinode) : id :=\n  match i with\n  | insn_phi id _ _ => id\n  end.\n\n  Definition getValueID (v:value) : option id :=\n  match v with\n  | value_id id => Some id\n  | value_const _ => None\n  end.\n\n  Definition getInsnLoc (i:insn) : id :=\n  match i with\n  | insn_phinode p => getPhiNodeID p\n  | insn_cmd c => getCmdLoc c\n  | insn_terminator t => getTerminatorID t\n  end.\n\n  Definition isPhiNodeB (i:insn) : bool :=\n  match i with\n  | insn_phinode p => true\n  | insn_cmd c => false\n  | insn_terminator t => false\n  end.\n\n  Definition isPhiNode (i:insn) : Prop :=\n  isPhiNodeB i = true.\n\n  Definition getCmdID (i:cmd) : option id :=\n  match i with\n  | insn_nop id => None\n  | insn_bop id _ sz v1 v2 => Some id\n  | insn_fbop id _ _ _ _ => Some id\n  (* | insn_extractelement id typ0 id0 c1 => id *)\n  (* | insn_insertelement id typ0 id0 typ1 v1 c2 => id *)\n  | insn_extractvalue id typs id0 c1 _ => Some id\n  | insn_insertvalue id typs id0 typ1 v1 c2 => Some id\n  | insn_malloc id _ _ _ => Some id\n  | insn_free id _ _ => None\n  | insn_alloca id _ _ _ => Some id\n  | insn_load id typ1 v1 _ => Some id\n  | insn_store id typ1 v1 v2 _ => None\n  | insn_gep id _ _ _ _ _ => Some id\n  | insn_trunc id _ typ1 v1 typ2 => Some id\n  | insn_ext id _ sz1 v1 sz2 => Some id\n  | insn_cast id _ typ1 v1 typ2 => Some id\n  | insn_icmp id cond typ v1 v2 => Some id\n  | insn_fcmp id cond typ v1 v2 => Some id\n  | insn_select id v0 typ v1 v2 => Some id\n  | insn_call id nr _ _ _ v0 paraml => if nr then None else Some id\n  end.\n\nFixpoint getCmdsIDs (cs:cmds) : list atom :=\nmatch cs with\n| nil => nil\n| c::cs' =>\n    match getCmdID c with\n    | Some id1 => id1::getCmdsIDs cs'\n    | None => getCmdsIDs cs'\n    end\nend.\n\nDefinition getPhiNodesIDs (ps:phinodes) : list atom :=\n  map getPhiNodeID ps.\n\nDefinition getStmtsIDs (st:stmts) : list atom :=\nlet '(stmts_intro ps cs _) := st in\ngetPhiNodesIDs ps ++ getCmdsIDs cs.\n\nFixpoint getArgsIDs (la:args) : list atom :=\nmatch la with\n| nil => nil\n| (_,id1)::la' => id1::getArgsIDs la'\nend.\n\nDefinition getArgsOfFdef (f:fdef) : args :=\nmatch f with\n| fdef_intro (fheader_intro _ _ _ la _) _ => la\nend.\n\nDefinition getArgsIDsOfFdef (f:fdef) : list atom :=\nmatch f with\n| fdef_intro (fheader_intro _ _ _ la _) _ => getArgsIDs la\nend.\n\nDefinition getInsnID (i:insn) : option id :=\nmatch i with\n| insn_phinode p => Some (getPhiNodeID p)\n| insn_cmd c => getCmdID c\n| insn_terminator t => None\nend.\n\nLemma getCmdLoc_getCmdID : forall a i0,\n  getCmdID a = Some i0 ->\n  getCmdLoc a = i0.\nProof.\n  intros a i0 H.\n  destruct_cmd a; inv H; auto.\n    simpl.\n    match goal with\n    | H1: context [if ?n then _ else _] |- _ =>\n      destruct n; inv H1; auto\n    end.\nQed.\n\nFixpoint mgetoffset_aux (TD:LLVMtd.TargetData) (t:typ) (idxs:list Z) (accum:Z)\n  : option (Z * typ) :=\n  match idxs with\n  | nil => Some (accum, t)\n  | idx::idxs' =>\n     match t with\n     | typ_array _ t' =>\n         match (LLVMtd.getTypeAllocSize TD t') with\n         | Some sz =>\n             mgetoffset_aux TD t' idxs' (accum + (Z_of_nat sz) * idx)\n         | _ => None\n         end\n     | typ_struct lt =>\n         match (LLVMtd.getStructElementOffset TD t (Coqlib.nat_of_Z idx))\n         with\n         | Some ofs =>\n             do t' <- nth_error lt (Coqlib.nat_of_Z idx);\n               mgetoffset_aux TD t' idxs' (accum + (Z_of_nat ofs))\n         | _ => None\n         end\n     | _ => None\n     end\n  end.\n\nDefinition mgetoffset (TD:LLVMtd.TargetData) (t:typ) (idxs:list Z)\n  : option (Z * typ) :=\n(*let (_, nts) := TD in\ndo ut <- Constant.typ2utyp nts t;*)\nmgetoffset_aux TD t idxs 0.\n\nFixpoint intConsts2Nats (TD:LLVMtd.TargetData) (lv:list const)\n  : option (list Z):=\nmatch lv with\n| nil => Some nil\n| (const_int sz0 n) :: lv' =>\n  if Size.dec sz0 Size.ThirtyTwo\n  then\n    match (intConsts2Nats TD lv') with\n    | Some ns => Some ((INTEGER.to_Z n)::ns)\n    | None => None\n    end\n  else None\n| _ => None\nend.\n\n(** Statically idx for struct must be int, and idx for arr can be\n    anything without checking bounds. *)\nFixpoint getSubTypFromConstIdxs (idxs : list const) (t : typ) : option typ :=\nmatch idxs with\n| nil => Some t\n| idx :: idxs' =>\n  match t with\n  | typ_array sz t' => getSubTypFromConstIdxs idxs' t'\n  | typ_struct lt =>\n    match idx with\n    | (const_int sz i) =>\n      match (nth_error lt (INTEGER.to_nat i)) with\n      | Some t' => getSubTypFromConstIdxs idxs' t'\n      | None => None\n      end\n    | _ => None\n    end\n  | _ => None\n  end\nend.\n\nDefinition getConstGEPTyp (idxs : list const) (t : typ) : option typ :=\nmatch (idxs, t) with\n| (idx :: idxs', typ_pointer t0)  =>\n     (* The input t is already an element of a pointer typ *)\n     match (getSubTypFromConstIdxs idxs' t0) with\n     | Some t' => Some (typ_pointer t')\n     | _ => None\n     end\n| _ => None\nend.\n\nFixpoint getSubTypFromValueIdxs\n  (idxs : list (sz * value)) (t : typ) : option typ :=\nmatch idxs with\n| nil => Some t\n| (_, idx) :: idxs' =>\n  match t with\n  | typ_array sz t' => getSubTypFromValueIdxs idxs' t'\n  | typ_struct lt =>\n    match idx with\n    | value_const (const_int sz i) =>\n      match (nth_error lt (INTEGER.to_nat i)) with\n      | Some t' => getSubTypFromValueIdxs idxs' t'\n      | None => None\n      end\n    | _ => None\n    end\n  | _ => None\n  end\nend.\n\nDefinition getGEPTyp (idxs : list (sz * value)) (t : typ) : option typ :=\nmatch idxs with\n| nil => None\n| (_, idx) :: idxs' =>\n     (* The input t is already an element of a pointer typ *)\n     match (getSubTypFromValueIdxs idxs' t) with\n     | Some t' => Some (typ_pointer t')\n     | _ => None\n     end\nend.\n\nDefinition getCmdTyp (i:cmd) : option typ :=\nmatch i with\n| insn_nop _ => Some typ_void\n| insn_bop _ _ sz _ _ => Some (typ_int sz)\n| insn_fbop _ _ ft _ _ => Some (typ_floatpoint ft)\n(*\n| insn_extractelement _ typ _ _ => getElementTyp typ\n| insn_insertelement _ typ _ _ _ _ => typ *)\n| insn_extractvalue _ typ _ idxs typ' => Some typ'\n| insn_insertvalue _ typ _ _ _ _ => Some typ\n| insn_malloc _ typ _ _ => Some (typ_pointer typ)\n| insn_free _ typ _ => Some typ_void\n| insn_alloca _ typ _ _ => Some (typ_pointer typ)\n| insn_load _ typ _ _ => Some typ\n| insn_store _ _ _ _ _ => Some typ_void\n| insn_gep _ _ typ _ idxs typ' => Some (typ_pointer typ')\n| insn_trunc _ _ _ _ typ => Some typ\n| insn_ext _ _ _ _ typ2 => Some typ2\n| insn_cast _ _ _ _ typ => Some typ\n| insn_icmp _ _ _ _ _ => Some (typ_int Size.One)\n| insn_fcmp _ _ _ _ _ => Some (typ_int Size.One)\n| insn_select _ _ typ _ _ => Some typ\n| insn_call _ true _ _ _ _ _ => Some typ_void\n| insn_call _ false _ rt _ _ _ => Some rt\nend.\n\nDefinition getTerminatorTyp (i:terminator) : typ :=\nmatch i with\n| insn_return _ typ _ => typ\n| insn_return_void _ => typ_void\n| insn_br _ _ _ _ => typ_void\n| insn_br_uncond _ _ => typ_void\n| insn_switch _ typ _ _ _ => typ_void\n(* | insn_invoke _ typ _ _ _ _ => typ *)\n| insn_unreachable _ => typ_void\nend.\n\nDefinition getPhiNodeTyp (i:phinode) : typ :=\nmatch i with\n| insn_phi _ typ _ => typ\nend.\n\nDefinition getInsnTyp (i:insn) : option typ :=\nmatch i with\n| insn_phinode p => Some (getPhiNodeTyp p)\n| insn_cmd c => getCmdTyp c\n| insn_terminator t => Some (getTerminatorTyp t)\nend.\n\nDefinition getPointerEltTyp (t:typ) : option typ :=\nmatch t with\n| typ_pointer t' => Some t'\n| _ => None\nend.\n\nDefinition getValueIDs (v:value) : ids :=\nmatch (getValueID v) with\n| None => nil\n| Some id => id::nil\nend.\n\nFixpoint values2ids (vs:list value) : ids :=\nmatch vs with\n| nil => nil\n| value_id id::vs' => id::values2ids vs'\n| _::vs' => values2ids vs'\nend.\n\nDefinition getParamsOperand (lp:params) : ids :=\nlet '(_,vs) := split lp in values2ids vs.\n\nFixpoint list_prj1 (X Y:Type) (ls : list (X*Y)) : list X :=\nmatch ls with\n| nil => nil\n| (x, y)::ls' => x::list_prj1 X Y ls'\nend.\n\nFixpoint list_prj2 (X Y:Type) (ls : list (X*Y)) : list Y :=\nmatch ls with\n| nil => nil\n| (x, y)::ls' => y::list_prj2 X Y ls'\nend.\n\nDefinition getCmdOperands (i:cmd) : ids :=\nmatch i with\n| insn_nop _ => nil\n| insn_bop _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_fbop _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n(* | insn_extractelement _ _ v _ => getValueIDs v\n| insn_insertelement _ _ v1 _ v2 _ => getValueIDs v1 ++ getValueIDs v2\n*)\n| insn_extractvalue _ _ v _ _ => getValueIDs v\n| insn_insertvalue _ _ v1 _ v2 _ => getValueIDs v1 ++ getValueIDs v2\n| insn_malloc _ _ v _ => getValueIDs v\n| insn_free _ _ v => getValueIDs v\n| insn_alloca _ _ v _ => getValueIDs v\n| insn_load _ _ v _ => getValueIDs v\n| insn_store _ _ v1 v2 _ => getValueIDs v1 ++ getValueIDs v2\n| insn_gep _ _ _ v vs _ =>\n    getValueIDs v ++ values2ids (map snd vs)\n| insn_trunc _ _ _ v _ => getValueIDs v\n| insn_ext _ _ _ v1 typ2 => getValueIDs v1\n| insn_cast _ _ _ v _ => getValueIDs v\n| insn_icmp _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_fcmp _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_select _ v0 _ v1 v2 => getValueIDs v0 ++ getValueIDs v1 ++ getValueIDs v2\n| insn_call _ _ _ _ _ v0 lp => getValueIDs v0 ++ getParamsOperand lp\nend.\n\nDefinition valueInListValue (v0:value) (vs:list (sz * value)) : Prop :=\nIn v0 (map snd vs).\n\nDefinition valueInParams (v0:value) (lp:params) : Prop :=\nlet '(_, vs) := split lp in In v0 vs.\n\nDefinition valueInCmdOperands (v0:value) (i:cmd) : Prop :=\nmatch i with\n| insn_nop _ => False\n| insn_bop _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_fbop _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_extractvalue _ _ v _ _ => v0 = v\n| insn_insertvalue _ _ v1 _ v2 _ => v0 = v1 \\/ v0 = v2\n| insn_malloc _ _ v _ => v0 = v\n| insn_free _ _ v => v0 = v\n| insn_alloca _ _ v _ => v0 = v\n| insn_load _ _ v _ => v0 = v\n| insn_store _ _ v1 v2 _ => v0 = v1 \\/ v0 = v2\n| insn_gep _ _ _ v vs _ => v0 = v \\/ valueInListValue v0 vs\n| insn_trunc _ _ _ v _ => v0 = v\n| insn_ext _ _ _ v1 _ => v0 = v1\n| insn_cast _ _ _ v _ => v0 = v\n| insn_icmp _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_fcmp _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_select _ v1 _ v2 v3 => v0 = v1 \\/ v0 = v2 \\/ v0 = v3\n| insn_call _ _ _ _ _ v1 lp => v0 = v1 \\/ valueInParams v0 lp\nend.\n\nDefinition valueInTmnOperands (v0:value) (i:terminator) : Prop :=\nmatch i with\n| insn_return _ _ v => v = v0\n| insn_return_void _ => False\n| insn_br _ v _ _ => v = v0\n| insn_br_uncond _ _ => False\n| insn_switch _ _ v _ _ => v = v0\n| insn_unreachable _ => False\nend.\n\nDefinition valueInInsnOperands (v0:value) (instr:insn) : Prop :=\nmatch instr with\n| insn_phinode (insn_phi _ _ ls) =>\n    In v0 (list_prj1 _ _ ls)\n| insn_cmd c => valueInCmdOperands v0 c\n| insn_terminator tmn => valueInTmnOperands v0 tmn\nend.\n\nDefinition getTerminatorOperands (i:terminator) : ids :=\nmatch i with\n| insn_return _ _ v => getValueIDs v\n| insn_return_void _ => nil\n| insn_br _ v _ _ => getValueIDs v\n| insn_br_uncond _ _ => nil\n| insn_switch _ _ value _ _ => getValueIDs value\n(* | insn_invoke _ _ _ lp _ _ => getParamsOperand lp *)\n| insn_unreachable _ => nil\nend.\n\nDefinition getPhiNodeOperands (i:phinode) : ids :=\nmatch i with\n| insn_phi _ _ ls => values2ids (list_prj1 _ _ ls)\nend.\n\nDefinition getInsnOperands (i:insn) : ids :=\nmatch i with\n| insn_phinode p => getPhiNodeOperands p\n| insn_cmd c => getCmdOperands c\n| insn_terminator t => getTerminatorOperands t\nend.\n\nDefinition getCmdLabels (i:cmd) : ls :=\nmatch i with\n| insn_nop _ => nil\n| insn_bop _ _ _ _ _ => nil\n| insn_fbop _ _ _ _ _ => nil\n(* | insn_extractelement _ _ _ _ => nil\n| insn_insertelement _ _ _ _ _ _ => nil\n*)\n| insn_extractvalue _ _ _ _ _ => nil\n| insn_insertvalue _ _ _ _ _ _ => nil\n| insn_malloc _ _ _ _ => nil\n| insn_free _ _ _ => nil\n| insn_alloca _ _ _ _ => nil\n| insn_load _ _ _ _ => nil\n| insn_store _ _ _ _ _ => nil\n| insn_gep _ _ _ v  _ _ => nil\n| insn_trunc _ _ _ _ _ => nil\n| insn_ext _ _ _ _ _ => nil\n| insn_cast _ _ _ _ _ => nil\n| insn_icmp _ _ _ _ _ => nil\n| insn_fcmp _ _ _ _ _ => nil\n| insn_select _ _ _ _ _ => nil\n| insn_call _ _ _ _ _ _ _ => nil\nend.\n\nDefinition getTerminatorLabels (i:terminator) : ls :=\nmatch i with\n| insn_return _ _ _ => nil\n| insn_return_void _ => nil\n| insn_br _ _ l1 l2 => l1::l2::nil\n| insn_br_uncond _ l => l::nil\n| insn_switch _ _ _ l ls => l::list_prj2 _ _ ls\n(* | insn_invoke _ _ _ _ l1 l2 => l1::l2::nil *)\n| insn_unreachable _ => nil\nend.\n\nDefinition getPhiNodeLabels (i:phinode) : ls :=\nmatch i with\n| insn_phi _ _ ls => list_prj2 _ _ ls\nend.\n\nDefinition getInsnLabels (i:insn) : ls :=\nmatch i with\n| insn_phinode p => getPhiNodeLabels p\n| insn_cmd c => getCmdLabels c\n| insn_terminator tmn => getTerminatorLabels tmn\nend.\n\nFixpoint args2Typs (la:args) : list typ :=\nmatch la with\n| nil => nil\n| (t, _, id)::la' => t :: (args2Typs la')\nend.\n\nDefinition getFheaderTyp (fh:fheader) : typ :=\nmatch fh with\n| fheader_intro _ t _ la va => typ_function t (args2Typs la) va\nend.\n\nDefinition getFdecTyp (fdec:fdec) : typ :=\nmatch fdec with\n| fdec_intro fheader _ => getFheaderTyp fheader\nend.\n\nDefinition getFdefTyp (fdef:fdef) : typ :=\nmatch fdef with\n| fdef_intro fheader _ => getFheaderTyp fheader\nend.\n\nDefinition fheaderOfFdef (fdef:fdef) : fheader :=\nmatch fdef with\n| fdef_intro fh _ => fh\nend.\n\nDefinition getBindingTyp (ib:id_binding) : option typ :=\nmatch ib with\n| id_binding_cmd i => getCmdTyp i\n| id_binding_terminator i => Some (getTerminatorTyp i)\n| id_binding_phinode i => Some (getPhiNodeTyp i)\n| id_binding_gvar (gvar_intro _ _ _ t _ _) => Some (typ_pointer t)\n| id_binding_gvar (gvar_external _ _ t) => Some (typ_pointer t)\n| id_binding_arg (t, _, id) => Some t\n| id_binding_fdec fdec => Some (getFdecTyp fdec)\n| id_binding_none => None\nend.\n\nDefinition getCmdsFromBlock (b:block) : cmds :=\nmatch b with\n| (_, stmts_intro _ li _) => li\n(* | block_without_label li => li *)\nend.\n\nDefinition getTerminatorFromBlock (b:block) : terminator :=\nmatch b with\n| (_, stmts_intro _ _ t) => t\n(* | block_without_label li => li *)\nend.\n\nDefinition getFheaderID (fh:fheader) : id :=\nmatch fh with\n| fheader_intro _ _ id _ _ => id\nend.\n\nDefinition getFdecID (fd:fdec) : id :=\nmatch fd with\n| fdec_intro fh _ => getFheaderID fh\nend.\n\nDefinition getFdefID (fd:fdef) : id :=\nmatch fd with\n| fdef_intro fh _ => getFheaderID fh\nend.\n\nFixpoint getLabelViaIDFromList\n  (ls: list (value * l)) (branch:id) : option l :=\nmatch ls with\n| nil => None\n| ((value_id id), l) :: ls' =>\n  match (eq_dec id branch) with\n  | left _ => Some l\n  | right _ => getLabelViaIDFromList ls' branch\n  end\n| (_, l) :: ls' => getLabelViaIDFromList ls' branch\nend.\n\nDefinition getLabelViaIDFromPhiNode (phi:phinode) (branch:id) : option l :=\nmatch phi with\n| insn_phi _ _ ls => getLabelViaIDFromList ls branch\nend.\n\nFixpoint getLabelsFromIdls (idls:list (value * l)) : ls :=\nmatch idls with\n| nil => lempty_set\n| (_, l) :: idls' => lset_add l (getLabelsFromIdls idls')\nend.\n\nDefinition getLabelsFromPhiNode (phi:phinode) : ls :=\nmatch phi with\n| insn_phi _ _ ls => getLabelsFromIdls ls\nend.\n\nFixpoint getLabelsFromPhiNodes (phis:list phinode) : ls :=\nmatch phis with\n| nil => lempty_set\n| phi::phis' => lset_union (getLabelsFromPhiNode phi) (getLabelsFromPhiNodes phis')\nend.\n\nDefinition getIDLabelsFromPhiNode p : list (value * l) :=\nmatch p with\n| insn_phi _ _ idls => idls\nend.\n\nFixpoint getLabelViaIDFromIDLabels idls id : option l :=\nmatch idls with\n| nil => None\n| (value_id id0, l0) :: idls' => if eq_dec id id0 then Some l0 else getLabelViaIDFromIDLabels idls' id\n| (_, l0) :: idls' => getLabelViaIDFromIDLabels idls' id\nend.\n\nDefinition _getLabelViaIDPhiNode p id : option l :=\nmatch p with\n| insn_phi _ _ ls => getLabelViaIDFromIDLabels ls id\nend.\n\nDefinition getLabelViaIDPhiNode (phi:insn) id : option l :=\nmatch phi with\n| insn_phinode p => _getLabelViaIDPhiNode p id\n| _ => None\nend.\n\nDefinition getReturnTyp fdef : typ :=\nmatch fdef with\n| fdef_intro (fheader_intro _ t _ _ _) _ => t\nend.\n\nDefinition getGvarID g : id :=\nmatch g with\n| gvar_intro id _ _ _ _ _ => id\n| gvar_external id _ _ => id\nend.\n\nDefinition getCalledValue i : option value :=\nmatch i with\n| insn_cmd (insn_call _ _ _ _ _ v0 _) => Some v0\n| _ => None\nend.\n\nDefinition getCalledValueID i : option id :=\nmatch getCalledValue i with\n| Some v => getValueID v\n| _ => None\nend.\n\nDefinition getCallerReturnID (Caller:cmd) : option id :=\nmatch Caller with\n(* | insn_invoke i _ _ _ _ _ => Some i *)\n| insn_call fid true _ _ _ _ _ => None\n| insn_call fid false _ _ _ _ _ => Some fid\n| _ => None\nend.\n\nFixpoint getValueViaLabelFromValuels (vls:list (value * l)) (l0:l) : option value :=\nmatch vls with\n| nil => None\n| (v, l1) :: vls'=>\n  if (eq_dec l1 l0)\n  then Some v\n  else getValueViaLabelFromValuels vls' l0\nend.\n\nDefinition getValueViaBlockFromValuels (vls:list (value * l)) (b:block) : option value :=\ngetValueViaLabelFromValuels vls (fst b).\n\nDefinition getValueViaBlockFromPHINode (i:phinode) (b:block) : option value :=\nmatch i with\n| insn_phi _ _ vls => getValueViaBlockFromValuels vls b\nend.\n\nDefinition getPHINodesFromBlock (b:block) : list phinode :=\nmatch b with\n| (_, stmts_intro lp _ _) => lp\nend.\n\nDefinition getEntryBlock (fd:fdef) : option block :=\nmatch fd with\n| fdef_intro _ (b::_) => Some b\n| _ => None\nend.\n\nDefinition getEntryLabel (f:fdef) : option l :=\nmatch f with\n| fdef_intro _ ((l0, _)::_) => Some l0\n| _ => None\nend.\n\nDefinition floating_point_order (fp1 fp2:floating_point) : bool :=\nmatch (fp1, fp2) with\n| (fp_float, fp_double) => true\n| (fp_float, fp_x86_fp80) => true\n| (fp_float, fp_ppc_fp128) => true\n| (fp_float, fp_fp128) => true\n| (fp_double, fp_x86_fp80) => true\n| (fp_double, fp_ppc_fp128) => true\n| (fp_double, fp_fp128) => true\n| (fp_x86_fp80, fp_ppc_fp128) => true\n| (fp_x86_fp80, fp_fp128) => true\n| (_, _) => false\nend.\n\nDefinition wf_fcond (fc : fcond) : bool :=\nmatch fc with\n| fcond_ord => false\n| fcond_uno => false\n| _ => true\nend.\n\n(**********************************)\n(* Lookup. *)\n\n(* ID binding lookup *)\n\nFixpoint lookupCmdViaIDFromCmds (li:cmds) (id0:id) : option cmd :=\nmatch li with\n| nil => None\n| i::li' =>\n    if (eq_atom_dec id0 (getCmdLoc i))\n    then Some i else lookupCmdViaIDFromCmds li' id0\nend.\n\nFixpoint lookupPhiNodeViaIDFromPhiNodes (li:phinodes) (id0:id)\n  : option phinode :=\nmatch li with\n| nil => None\n| i::li' =>\n    if (eq_dec (getPhiNodeID i) id0) then Some i\n    else lookupPhiNodeViaIDFromPhiNodes li' id0\nend.\n\nDefinition lookupInsnViaIDFromBlock (b:block) (id0:id) : option insn :=\nmatch b with\n| (_, stmts_intro ps cs t) =>\n  match (lookupPhiNodeViaIDFromPhiNodes ps id0) with\n  | None =>\n      match (lookupCmdViaIDFromCmds cs id0) with\n      | None => if (eq_dec (getTerminatorID t) id0)\n                then Some (insn_terminator t) else None\n      | Some c => Some (insn_cmd c)\n      end\n  | Some re => Some (insn_phinode re)\n  end\nend.\n\nFixpoint lookupInsnViaIDFromBlocks (lb:blocks) (id:id) : option insn :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (lookupInsnViaIDFromBlock b id) with\n  | None => lookupInsnViaIDFromBlocks lb' id\n  | re => re\n  end\nend.\n\nDefinition lookupInsnViaIDFromFdef (f:fdef) (id0:id) : option insn :=\nlet '(fdef_intro _ bs) := f in lookupInsnViaIDFromBlocks bs id0.\n\nFixpoint lookupArgViaIDFromArgs (la:args) (id0:id) : option arg :=\nmatch la with\n| nil => None\n| (t, attrs, id')::la' =>\n    if (eq_dec id' id0) then Some (t, attrs, id')\n    else lookupArgViaIDFromArgs la' id0\nend.\n\n(* Block lookup from ID *)\n\nFixpoint getCmdsLocs (cs:list cmd) : ids :=\nmatch cs with\n| nil => nil\n| c::cs' => getCmdLoc c::getCmdsLocs cs'\nend.\n\nDefinition getStmtsLocs (sts:stmts) : ids :=\nmatch sts with\n| (stmts_intro ps cs t) =>\n  getPhiNodesIDs ps++getCmdsLocs cs++(getTerminatorID t::nil)\nend.\n\nFixpoint lookupBlockViaIDFromBlocks (lb:blocks) (id1:id) : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (In_dec eq_dec id1 (getStmtsIDs (snd b))) with\n  | left _ => Some b\n  | right _ => lookupBlockViaIDFromBlocks lb' id1\n  end\nend.\n\nDefinition lookupBlockViaIDFromFdef (fd:fdef) (id:id) : option block :=\nmatch fd with\n| fdef_intro fh lb => lookupBlockViaIDFromBlocks lb id\nend.\n\n(* Fun lookup from ID *)\n\nDefinition lookupFdecViaIDFromProduct (p:product) (i:id) : option fdec :=\nmatch p with\n| (product_fdec fd) => if eq_dec (getFdecID fd) i then Some fd else None\n| _ => None\nend.\n\nFixpoint lookupFdecViaIDFromProducts (lp:products) (i:id) : option fdec :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupFdecViaIDFromProduct p i) with\n  | Some fd => Some fd\n  | None => lookupFdecViaIDFromProducts lp' i\n  end\nend.\n\nDefinition lookupFdecViaIDFromModule (m:module) (i:id) : option fdec :=\n  let (os, dts, ps) := m in\n  lookupFdecViaIDFromProducts ps i.\n\nFixpoint lookupFdecViaIDFromModules (lm:modules) (i:id) : option fdec :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupFdecViaIDFromModule m i) with\n  | Some fd => Some fd\n  | None => lookupFdecViaIDFromModules lm' i\n  end\nend.\n\nDefinition lookupFdecViaIDFromSystem (s:system) (i:id) : option fdec :=\nlookupFdecViaIDFromModules s i.\n\nDefinition lookupFdefViaIDFromProduct (p:product) (i:id) : option fdef :=\nmatch p with\n| (product_fdef fd) => if eq_dec (getFdefID fd) i then Some fd else None\n| _ => None\nend.\n\nFixpoint lookupFdefViaIDFromProducts (lp:products) (i:id) : option fdef :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupFdefViaIDFromProduct p i) with\n  | Some fd => Some fd\n  | None => lookupFdefViaIDFromProducts lp' i\n  end\nend.\n\nDefinition lookupFdefViaIDFromModule (m:module) (i:id) : option fdef :=\n  let (os, dts, ps) := m in\n  lookupFdefViaIDFromProducts ps i.\n\nFixpoint lookupFdefViaIDFromModules (lm:modules) (i:id) : option fdef :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupFdefViaIDFromModule m i) with\n  | Some fd => Some fd\n  | None => lookupFdefViaIDFromModules lm' i\n  end\nend.\n\nDefinition lookupFdefViaIDFromSystem (s:system) (i:id) : option fdef :=\nlookupFdefViaIDFromModules s i.\n\n(*     ID type lookup                                    *)\n\nDefinition lookupTypViaIDFromCmd (i:cmd) (id0:id) : option typ :=\nmatch (getCmdTyp i) with\n| None => None\n| Some t =>\n  match (getCmdLoc i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nFixpoint lookupTypViaIDFromCmds (li:cmds) (id0:id) : option typ :=\nmatch li with\n| nil => None\n| i::li' =>\n  match (lookupTypViaIDFromCmd i id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromCmds li' id0\n  end\nend.\n\nDefinition lookupTypViaIDFromPhiNode (i:phinode) (id0:id) : option typ :=\nmatch (getPhiNodeTyp i) with\n| t =>\n  match (getPhiNodeID i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nFixpoint lookupTypViaIDFromPhiNodes (li:phinodes) (id0:id) : option typ :=\nmatch li with\n| nil => None\n| i::li' =>\n  match (lookupTypViaIDFromPhiNode i id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromPhiNodes li' id0\n  end\nend.\n\nDefinition lookupTypViaIDFromTerminator (i:terminator) (id0:id) : option typ :=\nmatch (getTerminatorTyp i) with\n| t =>\n  match (getTerminatorID i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nDefinition lookupTypViaIDFromBlock (b:block) (id0:id) : option typ :=\nmatch b with\n| (_, stmts_intro ps cs t) =>\n  match (lookupTypViaIDFromPhiNodes ps id0) with\n  | None =>\n    match (lookupTypViaIDFromCmds cs id0) with\n    | None => lookupTypViaIDFromTerminator t id0\n    | re => re\n    end\n  | re => re\n  end\nend.\n\nFixpoint lookupTypViaIDFromBlocks (lb:blocks) (id0:id) : option typ :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (lookupTypViaIDFromBlock b id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromBlocks lb' id0\n  end\nend.\n\nFixpoint lookupTypViaIDFromArgs (la:args) (id0:id) : option typ :=\nmatch la with\n| nil => None\n| (t1,_,id1)::la' =>\n    if (id0==id1) then Some t1 else lookupTypViaIDFromArgs la' id0\nend.\n\nDefinition lookupTypViaIDFromFdef (fd:fdef) (id0:id) : option typ :=\nmatch fd with\n| (fdef_intro (fheader_intro _ _ _ la _ ) lb) =>\n    match lookupTypViaIDFromArgs la id0 with\n    | None => lookupTypViaIDFromBlocks lb id0\n    | Some t => Some t\n    end\nend.\n\nDefinition lookupTypViaGIDFromProduct (p:product) (id0:id) : option typ :=\nmatch p with\n| product_fdef fd => if id0==(getFdefID fd) then Some (getFdefTyp fd) else None\n| product_gvar (gvar_intro id1 _ spec t _ _) => if id0==id1 then Some t else None\n| product_gvar (gvar_external id1 spec t) => if id0==id1 then Some t else None\n| product_fdec fc => if id0==(getFdecID fc) then Some (getFdecTyp fc) else None\nend.\n\nFixpoint lookupTypViaGIDFromProducts (lp:products) (id0:id) : option typ :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupTypViaGIDFromProduct p id0) with\n  | Some t => Some t\n  | None => lookupTypViaGIDFromProducts lp' id0\n  end\nend.\n\nDefinition lookupTypViaGIDFromModule (m:module) (id0:id) : option typ :=\n  let (os, dts, ps) := m in\n  lookupTypViaGIDFromProducts ps id0.\n\nFixpoint lookupTypViaGIDFromModules (lm:modules) (id0:id) : option typ :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupTypViaGIDFromModule m id0) with\n  | Some t => Some t\n  | None => lookupTypViaGIDFromModules lm' id0\n  end\nend.\n\nDefinition lookupTypViaGIDFromSystem (s:system) (id0:id) : option typ :=\nlookupTypViaGIDFromModules s id0.\n\nFixpoint lookupTypViaTIDFromNamedts (nts:namedts) (id0:id) : option typ :=\nmatch nts with\n| nil => None\n| (id1, typ1)::nts' =>\n  if (eq_dec id0 id1)\n  then Some (typ_struct typ1)\n  else lookupTypViaTIDFromNamedts nts' id0\nend.\n\nDefinition lookupTypViaTIDFromModule (m:module) (id0:id) : option typ :=\n  let (os, dts, ps) := m in\n  lookupTypViaTIDFromNamedts dts id0.\n\nFixpoint lookupTypViaTIDFromModules (lm:modules) (id0:id) : option typ :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupTypViaTIDFromModule m id0) with\n  | Some t => Some t\n  | None => lookupTypViaTIDFromModules lm' id0\n  end\nend.\n\nDefinition lookupTypViaTIDFromSystem (s:system) (id0:id) : option typ :=\nlookupTypViaTIDFromModules s id0.\n\n(**********************************)\n(* labels <-> blocks. *)\n\n  Definition lookupBlockViaLabelFromBlocks (bs:blocks) (l0:l) : option stmts :=\n  lookupAL _ bs l0.\n\n  Definition lookupBlockViaLabelFromFdef (f:fdef) (l0:l) : option stmts :=\n  let '(fdef_intro _ bs) := f in\n  lookupAL _ bs l0.\n\n(**********************************)\n(* generate block use-def *)\n\n  Definition getBlockLabel (b:block) : l := fst b.\n\n(**********************************)\n(* CFG. *)\n\n  Definition getTerminator (b:block) : terminator :=\n  match b with\n  | (_, stmts_intro _ _ t) => t\n  end.\n\n  Definition successors_terminator (tmn: terminator) : ls :=\n  match tmn with\n  | insn_return _ _ _ => nil\n  | insn_return_void _ => nil\n  | insn_br _ _ l1 l2 => l1::l2::nil\n  | insn_br_uncond _ l1 => l1::nil\n  | insn_switch _ _ _ l ls => nodup eq_atom_dec (l::list_prj2 _ _ ls)\n  | insn_unreachable _ => nil\n  end.\n\n  Definition terminator_match (tmn1 tmn2: terminator) : Prop :=\n  match tmn1, tmn2 with\n  | insn_return id1 _ _, insn_return id2 _ _ => id1 = id2\n  | insn_return_void id1, insn_return_void id2 => id1 = id2\n  | insn_br id1 _ l11 l12, insn_br id2 _ l21 l22 => \n      id1 = id2 /\\ l11 = l21 /\\ l12 = l22\n  | insn_br_uncond id1 l1, insn_br_uncond id2 l2 => id1 = id2 /\\ l1 = l2\n  | insn_switch id1 _ v1 l1 ls1, insn_switch id2 _ v2 l2 ls2 => id1 = id2 /\\ v1 = v2 /\\\n                                                                l1 = l2 /\\ ls1 = ls2\n  | insn_unreachable i1, insn_unreachable i2 => i1 = i2\n  | _, _ => False\n  end.\n\nLtac terminator_match_tac :=\nmatch goal with\n| J : terminator_match ?t1 ?t2 |- _ =>\n  destruct t1; destruct t2; simpl in J; inversion J; subst; auto;\n    match goal with\n    | J': ?id1 = _ /\\ ?id2 = _ /\\ ?id3 = _ |- _ =>\n      destruct J' as [? [? ?]]; subst id1 id2 id3; auto\n    | J': ?id1 = _ /\\ ?id2 = _ |- _ =>\n      destruct J' as [? ?]; subst id1 id2; auto\n    | J' : ?id0 = _ |- _ => subst id0; auto\n    end\nend.\n\n(**********************************)\n(* Classes. *)\n\nDefinition isPointerTypB (t:typ) : bool :=\nmatch t with\n| typ_pointer _ => true\n| _ => false\nend.\n\nDefinition isFunctionPointerTypB (t:typ) : bool :=\nmatch t with\n| typ_pointer (typ_function _ _ _) => true\n| _ => false\nend.\n\nDefinition isArrayTypB (t:typ) : bool :=\nmatch t with\n| typ_array _ _ => true\n| _ => false\nend.\n\n(*\nDefinition isInvokeInsnB (i:insn) : bool :=\nmatch i with\n| insn_invoke _ _ _ _ _ _ => true\n| _ => false\nend.\n*)\n\nDefinition isReturnInsnB (i:terminator) : bool :=\nmatch i with\n| insn_return _ _ _ => true\n| insn_return_void _ => true\n| _ => false\nend.\n\nDefinition _isCallInsnB (i:cmd) : bool :=\nmatch i with\n| insn_call _ _ _ _ _ _ _ => true\n| _ => false\nend.\n\nDefinition isCallInsnB (i:insn) : bool :=\nmatch i with\n| insn_cmd c => _isCallInsnB c\n| _ => false\nend.\n\nDefinition isNotValidReturnTypB (t:typ) : bool :=\nmatch t with\n| typ_label => true\n| typ_metadata => true\n| _ => false\nend.\n\nDefinition isValidReturnTypB (t:typ) : bool :=\nnegb (isNotValidReturnTypB t).\n\nDefinition isNotFirstClassTypB (t:typ) : bool :=\nmatch t with\n| typ_void => true\n(* | typ_opaque => true *)\n| typ_function _ _ _ => true\n| _ => false\nend.\n\nDefinition isFirstClassTypB (t:typ) : bool :=\nnegb (isNotFirstClassTypB t).\n\nDefinition isValidArgumentTypB (t:typ) : bool :=\nmatch t with\n(*| typ_opaque => true *)\n| _ => isFirstClassTypB t\nend.\n\nDefinition isNotValidElementTypB (t:typ) : bool :=\nmatch t with\n| typ_void => true\n| typ_label => true\n| typ_metadata => true\n| typ_function _ _ _ => true\n| _ => false\nend.\n\nDefinition isValidElementTypB (t:typ) : bool :=\nnegb (isNotValidElementTypB t).\n\nDefinition isBindingFdecB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_fdec fdec => true\n| _ => false\nend.\n\nDefinition isBindingGvarB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_gvar _ => true\n| _ => false\nend.\n\nDefinition isBindingArgB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_arg arg => true\n| _ => false\nend.\n\nDefinition isBindingCmdB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_cmd _ => true\n| _ => false\nend.\n\nDefinition isBindingTerminatorB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_terminator _ => true\n| _ => false\nend.\n\nDefinition isBindingPhiNodeB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_phinode _ => true\n| _ => false\nend.\n\nDefinition isBindingInsnB (ib:id_binding) : bool :=\nisBindingCmdB ib || isBindingTerminatorB ib || isBindingPhiNodeB ib.\n\nDefinition isPointerTyp typ := isPointerTypB typ = true.\n\nDefinition isFunctionPointerTyp t := isFunctionPointerTypB t = true.\n\n(* Definition isInvokeInsn insn := isInvokeInsnB insn = true. *)\n\nDefinition isReturnTerminator tmn := isReturnInsnB tmn = true.\n\nDefinition isNotValidReturnTyp typ := isNotValidReturnTypB typ = true.\n\nDefinition isValidReturnTyp typ := isValidReturnTypB typ = true.\n\nDefinition isNotFirstClassTyp typ := isNotFirstClassTypB typ = true.\n\nDefinition isFirstClassTyp typ := isFirstClassTypB typ = true.\n\nDefinition isValidArgumentTyp typ := isValidArgumentTypB typ = true.\n\nDefinition isNotValidElementTyp typ := isNotValidElementTypB typ = true.\n\nDefinition isValidElementTyp typ := isValidElementTypB typ = true.\n\nDefinition isBindingFdec ib : option fdec :=\nmatch ib with\n| id_binding_fdec f => Some f\n| _ => None\nend.\n\nDefinition isBindingArg ib : option arg :=\nmatch ib with\n| id_binding_arg a => Some a\n| _ => None\nend.\n\nDefinition isBindingGvar ib : option gvar :=\nmatch ib with\n| id_binding_gvar g => Some g\n| _ => None\nend.\n\nDefinition isBindingCmd ib : option cmd :=\nmatch ib with\n| id_binding_cmd c => Some c\n| _ => None\nend.\n\nDefinition isBindingPhiNode ib : option phinode :=\nmatch ib with\n| id_binding_phinode p => Some p\n| _ => None\nend.\n\nDefinition isBindingTerminator ib : option terminator :=\nmatch ib with\n| id_binding_terminator tmn => Some tmn\n| _ => None\nend.\n\nDefinition isBindingInsn ib : option insn :=\nmatch ib with\n| id_binding_cmd c => Some (insn_cmd c)\n| id_binding_phinode p => Some (insn_phinode p)\n| id_binding_terminator tmn => Some (insn_terminator tmn)\n| _ => None\nend.\n\nDefinition isAggregateTyp t :=\nmatch t with\n| typ_struct _ => True\n| typ_array _ _ => True\n| _ => False\nend.\n\nDefinition is_terminator (instr:insn) : bool :=\nmatch instr with\n| insn_terminator t => true\n| _ => false\nend.\n\nDefinition isnt_alloca c :=\nmatch c with\n| insn_alloca _ _ _ _ => False\n| _ => True\nend.\n\n(*************************************************)\n(*         Uniq                                  *)\n\nFixpoint getBlocksLocs (bs:blocks) : ids :=\nmatch bs with\n| nil => nil\n| b::bs' => getStmtsLocs (snd b)++getBlocksLocs bs'\nend.\n\nDefinition uniqBlocks bs : Prop :=\nlet ids := getBlocksLocs bs in\nuniq bs /\\ NoDup ids.\n\nDefinition uniqFdef fdef : Prop :=\nmatch fdef with\n| (fdef_intro (fheader_intro _ _ _ la _) bs) =>\n    uniqBlocks bs /\\ NoDup (getArgsIDs la ++ getBlocksLocs bs)\nend.\n\nDefinition uniqFdec fdec : Prop :=\nmatch fdec with\n| (fdec_intro (fheader_intro _ _ _ la _) _) =>\n    NoDup (getArgsIDs la)\nend.\n\nDefinition getProductID product : id :=\nmatch product with\n| product_gvar g => getGvarID g\n| product_fdec f => getFdecID f\n| product_fdef f => getFdefID f\nend.\n\nFixpoint getProductsIDs ps : ids :=\nmatch ps with\n| nil => nil\n| p::ps' => getProductID p::getProductsIDs ps'\nend.\n\nFixpoint getFdefsIDs ps : ids :=\nmatch ps with\n| nil => nil\n| product_fdef f::ps' => getFdefID f::getFdefsIDs ps'\n| _::ps' => getFdefsIDs ps'\nend.\n\nDefinition uniqProduct product : Prop :=\nmatch product with\n| product_gvar g => True\n| product_fdec f => uniqFdec f\n| product_fdef f => uniqFdef f\nend.\n\nDefinition uniqProducts ps : Prop :=\n  Forall uniqProduct ps.\n\nFixpoint getNamedtsIDs (dts:namedts) : ids :=\nmatch dts with\n| nil => nil\n| (id0, _)::dts' => id0::getNamedtsIDs dts'\nend.\n\nDefinition uniqModule m : Prop :=\nmatch m with\n| module_intro _ dts ps => uniqProducts ps /\\\n                           NoDup (getNamedtsIDs dts) /\\\n                           NoDup (getProductsIDs ps)\nend.\n\nFixpoint uniqModules ms : Prop :=\nmatch ms with\n| nil => True\n| m::ms' => uniqModule m /\\ uniqModules ms'\nend.\n\nDefinition uniqSystem s : Prop := uniqModules s.\n\n(**********************************)\n(* Dec. *)\n\nDefinition sumbool2bool A B (dec:sumbool A B) : bool :=\nmatch dec with\n| left _ => true\n| right _ => false\nend.\n\nLemma sumbool2bool_true : forall A B H,\n  sumbool2bool A B H = true -> A.\nProof.\n  intros.\n  unfold sumbool2bool in H0.\n  destruct H; auto.\n    inversion H0.\nQed.\n\nLemma sumbool2bool_false : forall A B H,\n  sumbool2bool A B H = false -> B.\nProof.\n  intros.\n  unfold sumbool2bool in H0.\n  destruct H; auto.\n    inversion H0.\nQed.\n\nLemma eq_sumbool2bool_true : forall A (a1 a2:A) (H:{a1=a2}+{~a1=a2}),\n  a1 = a2 ->\n  sumbool2bool _ _ H = true.\nProof.\n  intros; subst.\n  destruct H; auto.\nQed.\n\nLemma floating_point_dec : forall (fp1 fp2:floating_point), {fp1=fp2}+{~fp1=fp2}.\nProof.\n  decide equality.\nQed.\n\nLtac done_right := right; intro J; inversion J; subst; auto.\n\nLtac destruct_top_tac :=\n  match goal with\n  | |- { _ = ?t2 } + { _ <> ?t2 } => destruct t2; try solve [auto | done_right]\n  end.\n\nLemma varg_dec : forall x y : varg, {x=y} + {x<>y}.\nProof.\n  destruct x, y; try solve [auto | done_right].\n  match goal with\n  | |- context [{Some ?s1 = Some ?s2} + {Some ?s1 <> Some ?s2}] =>\n       destruct (@Size.dec s1 s2); try solve [auto | done_right]\n  end.\nQed.\n\nLtac destruct_wrt_type1 a1 a2:=\n  match type of a1 with\n  | sz => destruct (@Size.dec a1 a2)\n  | floating_point => destruct (@floating_point_dec a1 a2)\n  | varg => destruct (@varg_dec a1 a2)\n  | id => destruct (@id_dec a1 a2)\n  end.\n\nLtac destruct_dec_tac f :=\n  match goal with\n  | |- { ?c ?a1 = ?c ?a2 } + { ?c ?a1 <> ?c ?a2 } =>\n      f a1 a2\n  | |- { ?c ?a1 ?b1 = ?c ?a2 ?b2 } + { ?c ?a1 ?b1 <> ?c ?a2 ?b2 } =>\n      f a1 a2; f b1 b2\n  | |- { ?c ?a1 ?b1 ?c1 = ?c ?a2 ?b2 ?c2 } + { ?c ?a1 ?b1 ?c1 <> ?c ?a2 ?b2 ?c2 } =>\n      f a1 a2; f b1 b2; f c1 c2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 = ?c ?a2 ?b2 ?c2 ?d2 }  +\n       { ?c ?a1 ?b1 ?c1 ?d1 <> ?c ?a2 ?b2 ?c2 ?d2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 ?e1 = ?c ?a2 ?b2 ?c2 ?d2 ?e2 } +\n       { ?c ?a1 ?b1 ?c1 ?d1 ?e1 <> ?c ?a2 ?b2 ?c2 ?d2 ?e2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2;f e1 e2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 ?e1 ?f1 = ?c ?a2 ?b2 ?c2 ?d2 ?e2 ?f2 } +\n       { ?c ?a1 ?b1 ?c1 ?d1 ?e1 ?f1 <> ?c ?a2 ?b2 ?c2 ?d2 ?e2 ?f2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2; f e1 e2; f f1 f2\n  | |- {?a1 :: ?b1 = ?a2 :: ?b2} +\n       {?a1 :: ?b1 <> ?a2 :: ?b2} =>\n      f a1 a2; f b1 b2\n  end; subst; try solve [auto | done_right].\n\nLtac typ_mutrec_dec_subs_tac :=\n  let destruct_wrt_type a1 a2:=\n    match type of a1 with\n    | typ =>\n      match goal with\n      | H:forall t2 : typ, {a1 = t2} + {a1 <> t2} |- _ => destruct (@H a2)\n      end\n    | list typ =>\n      match goal with\n      | H:forall t2 : list typ, {a1 = t2} + {a1 <> t2} |- _ =>\n          destruct (@H a2); clear H\n      end\n    | _ => destruct_wrt_type1 a1 a2\n    end; subst; try solve [auto | done_right] in\n  destruct_dec_tac destruct_wrt_type.\n\nLtac typ_mutrec_dec_tac := destruct_top_tac; typ_mutrec_dec_subs_tac.\n\nDefinition typ_dec_prop (t1:typ) := forall t2, {t1=t2} + {~t1=t2}.\nDefinition list_typ_dec_prop (lt1:list typ) :=\n  forall lt2, {lt1=lt2} + {~lt1=lt2}.\n\n\nLemma typ_mutrec_dec :\n  (forall t1, typ_dec_prop t1) *\n  (forall lt1, list_typ_dec_prop lt1).\nProof.\n  apply typ_mutrec;\n  unfold typ_dec_prop, list_typ_dec_prop;\n  intros; try solve [abstract typ_mutrec_dec_tac].\nQed.\n\nLemma list_typ_dec : forall (lt1 lt2:list typ), {lt1=lt2} + {~lt1=lt2}.\nProof.\n  destruct typ_mutrec_dec; auto.\nQed.\n\nLemma typ_dec : forall (t1 t2:typ), {t1=t2} + {t1<>t2}.\nProof.\n  destruct typ_mutrec_dec; auto.\nQed.\n\n\nLemma bop_dec : forall (b1 b2:bop), {b1=b2}+{~b1=b2}.\nProof.\n  decide equality.\nQed.\n\nLemma fbop_dec : forall (b1 b2:fbop), {b1=b2}+{~b1=b2}.\nProof.\n  decide equality.\nQed.\n\nLemma extop_dec : forall (e1 e2:extop), {e1=e2}+{~e1=e2}.\nProof.\n  decide equality.\nQed.\n\nLemma castop_dec : forall (c1 c2:castop), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma cond_dec : forall (c1 c2:cond), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma fcond_dec : forall (c1 c2:fcond), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma truncop_dec : forall (t1 t2:truncop), {t1=t2}+{~t1=t2}.\nProof.\n  decide equality.\nQed.\n\nDefinition const_dec_prop (c1:const) := forall c2, {c1=c2} + {~c1=c2}.\nDefinition list_const_dec_prop (lc1:list const) :=\n  forall lc2, {lc1=lc2} + {~lc1=lc2}.\n\nLtac destruct_wrt_type2 a1 a2:=\nmatch type of a1 with\n| Int => destruct (@INTEGER.dec a1 a2)\n| Float => destruct (@FLOAT.dec a1 a2)\n| sz => destruct (@Size.dec a1 a2)\n| floating_point => destruct (@floating_point_dec a1 a2)\n| typ => destruct (@typ_dec a1 a2)\n| varg => destruct (@varg_dec a1 a2)\n| id => destruct (@id_dec a1 a2)\n| extop => destruct (@extop_dec a1 a2)\n| truncop => destruct (@truncop_dec a1 a2)\n| castop => destruct (@castop_dec a1 a2)\n| inbounds => destruct (@inbounds_dec a1 a2)\n| list typ => destruct (@list_typ_dec a1 a2)\n| cond => destruct (@cond_dec a1 a2)\n| fcond => destruct (@fcond_dec a1 a2)\n| fbop => destruct (@fbop_dec a1 a2)\n| bop => destruct (@bop_dec a1 a2)\n| _ => destruct_wrt_type1 a1 a2\nend.\n\nLtac const_mutrec_dec_subs_tac :=\n  let destruct_wrt_type a1 a2:=\n    match type of a1 with\n    | const =>\n      match goal with\n      | H:forall t2 : const, {a1 = t2} + {a1 <> t2} |- _ => destruct (@H a2)\n      end\n    | list const =>\n      match goal with\n      | H:forall t2 : list const, {a1 = t2} + {a1 <> t2} |- _ =>\n          destruct (@H a2); clear H\n      end\n    | _ => destruct_wrt_type2 a1 a2\n    end; subst; try solve [auto | done_right] in\n  destruct_dec_tac destruct_wrt_type.\n\nLtac const_mutrec_dec_tac := destruct_top_tac; const_mutrec_dec_subs_tac.\n\nLemma const_mutrec_dec :\n  (forall c1, const_dec_prop c1) *\n  (forall lc1, list_const_dec_prop lc1).\nProof.\n apply const_mutrec;\n  unfold const_dec_prop, list_const_dec_prop;\n  intros; try solve [abstract const_mutrec_dec_tac].\nQed.\n\nLemma const_dec : forall (c1 c2:const), {c1=c2}+{~c1=c2}.\nProof.\n  destruct const_mutrec_dec; auto.\nQed.\n\nLemma list_const_dec : forall (lc1 lc2:list const), {lc1=lc2} + {~lc1=lc2}.\nProof.\n  destruct const_mutrec_dec; auto.\nQed.\n\nLemma list_const_l_dec : forall (l1 l2:list (const * l)), {l1=l2} + {~l1=l2}.\nProof.\n  decide equality.\n  decide equality.\n  apply const_dec.\nQed.\n\nLemma value_dec : forall (v1 v2:value), {v1=v2}+{~v1=v2}.\nProof.\n  decide equality. apply const_dec.\nQed.\n\nLemma attribute_dec : forall (attr1 attr2:attribute),\n  {attr1=attr2}+{~attr1=attr2}.\nProof.\n  decide equality.\nQed.\n\nLemma attributes_dec : forall (attrs1 attrs2:attributes),\n  {attrs1=attrs2}+{~attrs1=attrs2}.\nProof.\n  decide equality.\n    destruct (@attribute_dec a a0); subst; try solve [auto | done_right].\nQed.\n\nLemma params_dec : forall (p1 p2:params), {p1=p2}+{~p1=p2}.\nProof.\n  decide equality.\n    destruct a as [ [t a] v]. destruct p as [ [t0 a0] v0].\n    destruct (@typ_dec t t0); subst; try solve [done_right].\n    destruct (@attributes_dec a a0); subst; try solve [done_right].\n    destruct (@value_dec v v0); subst; try solve [auto | done_right].\nQed.\n\nLemma list_value_l_dec : forall (l1 l2:list (value * l)), {l1=l2}+{~l1=l2}.\nProof.\n  decide equality.\n  decide equality.\n  decide equality.\n  apply const_dec.\nQed.\n\nLemma list_value_dec : forall (lv1 lv2: list (sz * value)), {lv1=lv2}+{~lv1=lv2}.\nProof.\n  decide equality.\n  decide equality.\n  apply value_dec.\n  apply Size.dec. (* eq_nat_dec works for the proofs, but on extraction,\n                     we want to map sz into int, and Size.dec to int cmp in OCaml.\n                     eq_nat_dec wont be changed on extraction. So, we should use\n                     Size.dec here. *)\nQed.\n\nLemma callconv_dec : forall (cc1 cc2:callconv), {cc1=cc2}+{~cc1=cc2}.\nProof.\n  decide equality.\nQed.\n\nLtac destruct_wrt_type3 a1 a2:=\nmatch type of a1 with\n| l => destruct (@id_dec a1 a2)\n| value => destruct (@value_dec a1 a2)\n| const => destruct (@const_dec a1 a2)\n| list const => destruct (@list_const_dec a1 a2)\n| list (const * l) => destruct (@list_const_l_dec a1 a2)\n| attribute => destruct (@attribute_dec a1 a2)\n| attributes => destruct (@attributes_dec a1 a2)\n| params => destruct (@params_dec a1 a2)\n| list (sz * value) => destruct (@list_value_dec a1 a2)\n| list (value * l) => destruct (@list_value_l_dec a1 a2)\n| callconv => destruct (@callconv_dec a1 a2)\n| align => destruct (Align.dec a1 a2)\n| noret => destruct (@noret_dec a1 a2)\n| tailc => destruct (@tailc_dec a1 a2)\n| _ => destruct_wrt_type2 a1 a2\nend.\n\nLtac insn_dec_tac :=\n  destruct_top_tac;\n  destruct_dec_tac destruct_wrt_type3.\n\nLemma cmd_dec : forall (c1 c2:cmd), {c1=c2}+{~c1=c2}.\nProof.\n  (cmd_cases (destruct c1) Case); destruct c2;\n    try solve [done_right | auto | abstract insn_dec_tac].\n  Case \"insn_call\".\n    match goal with\n    | |- {insn_call ?i0 ?n ?c ?rt ?va ?v ?p =\n            insn_call ?i1 ?n0 ?c0 ?rt0 ?va0 ?v0 ?p0} +\n         {insn_call ?i0 ?n ?c ?rt ?va ?v ?p <>\n            insn_call ?i1 ?n0 ?c0 ?rt0 ?va0 ?v0 ?p0} =>\n      destruct_wrt_type3 i0 i1; subst; try solve [done_right];\n      destruct_wrt_type3 v v0; subst; try solve [done_right];\n      destruct_wrt_type3 n n0; subst; try solve [done_right];\n      destruct_wrt_type3 rt rt0; subst; try solve [done_right];\n      destruct_wrt_type3 va va0; subst; try solve [done_right];\n      destruct_wrt_type3 p p0; subst; try solve [done_right];\n      destruct c as [tailc5 callconv5 attributes1 attributes2];\n      destruct c0 as [tailc0 callconv0 attributes0 attributes3];\n      destruct_wrt_type3 tailc5 tailc0; subst; try solve [done_right];\n      destruct_wrt_type3 callconv5 callconv0; subst; try solve [done_right];\n      destruct_wrt_type3 attributes1 attributes0; subst; try solve [done_right];\n      destruct_wrt_type3 attributes2 attributes3;\n        subst; try solve [auto|done_right]\n    end.\nQed.\n\nLemma terminator_dec : forall (tmn1 tmn2:terminator), {tmn1=tmn2}+{~tmn1=tmn2}.\nProof.\n  destruct tmn1; destruct tmn2;\n    try solve [done_right | auto | abstract insn_dec_tac].\nQed.\n\nLemma phinode_dec : forall (p1 p2:phinode), {p1=p2}+{~p1=p2}.\nProof.\n  destruct p1; destruct p2; try solve [done_right | auto | insn_dec_tac].\nQed.\n\nLemma insn_dec : forall (i1 i2:insn), {i1=i2}+{~i1=i2}.\nProof.\n  destruct i1 as [phinode5|cmd5|terminator5];\n  destruct i2 as [phinode0|cmd0|terminator0]; try solve [done_right | auto].\n    destruct (@phinode_dec phinode5 phinode0);\n      subst; try solve [auto | done_right].\n    destruct (@cmd_dec cmd5 cmd0); subst; try solve [auto | done_right].\n    destruct (@terminator_dec terminator5 terminator0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma cmds_dec : forall (cs1 cs2:list cmd), {cs1=cs2}+{~cs1=cs2}.\nProof.\n  induction cs1.\n    destruct cs2; subst; try solve [subst; auto | done_right].\n\n    destruct cs2; subst; try solve [done_right].\n    destruct (@cmd_dec a c); subst; try solve [done_right].\n    destruct (@IHcs1 cs2); subst; try solve [auto | done_right].\nQed.\n\nLemma phinodes_dec : forall (ps1 ps2:list phinode), {ps1=ps2}+{~ps1=ps2}.\nProof.\n  induction ps1.\n    destruct ps2; subst; try solve [subst; auto | done_right].\n\n    destruct ps2; subst; try solve [done_right].\n    destruct (@phinode_dec a p); subst; try solve [done_right].\n    destruct (@IHps1 ps2); subst; try solve [auto | done_right].\nQed.\n\nLemma block_dec : forall (b1 b2:block), {b1=b2}+{~b1=b2}.\nProof.\n  destruct b1 as [l5 [phinodes5 cmds5 terminator5]];\n  destruct b2 as [l0 [phinodes0 cmds0 terminator0]]; try solve [done_right | auto].\n    destruct (@id_dec l5 l0); subst; try solve [done_right].\n    destruct (@phinodes_dec phinodes5 phinodes0); subst; try solve [done_right].\n    destruct (@cmds_dec cmds5 cmds0); subst; try solve [done_right].\n    destruct (@terminator_dec terminator5 terminator0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma arg_dec : forall (a1 a2:arg), {a1=a2}+{~a1=a2}.\nProof.\n  destruct a1; destruct a2; try solve [subst; auto | done_right].\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct p. destruct p0.\n    destruct (@attributes_dec a a0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [auto | done_right].\nQed.\n\nLemma args_dec : forall (l1 l2:args), {l1=l2}+{~l1=l2}.\nProof.\n  induction l1.\n    destruct l2; subst; try solve [subst; auto | done_right].\n\n    destruct l2; subst; try solve [done_right].\n    destruct (@arg_dec a p); subst; try solve [done_right].\n    destruct (@IHl1 l2); subst; try solve [auto | done_right].\nQed.\n\nLemma visibility_dec : forall (vb1 vb2:visibility), {vb1=vb2}+{~vb1=vb2}.\nProof.\n  decide equality.\nQed.\n\nLemma linkage_dec : forall (lk1 lk2:linkage), {lk1=lk2}+{~lk1=lk2}.\nProof.\n  decide equality.\nQed.\n\nLemma fheader_dec : forall (f1 f2:fheader), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fnattrs5 typ5 id5 args5 varg5];\n  destruct f2 as [fnattrs0 typ0 id0 args0 varg0];\n    try solve [subst; auto | done_right].\n    destruct (@typ_dec typ5 typ0); subst; try solve [done_right].\n    destruct (@id_dec id5 id0); subst; try solve [done_right].\n    destruct fnattrs5 as [linkage5 visibility5 callconv5 attributes1\n                          attributes2].\n    destruct fnattrs0 as [linkage0 visibility0 callconv0 attributes0\n                          attributes3].\n    destruct (@visibility_dec visibility5 visibility0);\n      subst; try solve [done_right].\n    destruct (@varg_dec varg5 varg0); subst; try solve [done_right].\n    destruct (@attributes_dec attributes1 attributes0);\n      subst; try solve [done_right].\n    destruct (@attributes_dec attributes2 attributes3);\n      subst; try solve [done_right].\n    destruct (@callconv_dec callconv5 callconv0); subst; try solve [done_right].\n    destruct (@linkage_dec linkage5 linkage0); subst; try solve [done_right].\n    destruct (@args_dec args5 args0); subst; try solve [auto | done_right].\nQed.\n\nLemma blocks_dec : forall (lb lb':blocks), {lb=lb'}+{~lb=lb'}.\nProof.\n  induction lb.\n    destruct lb'; subst; try solve [subst; auto | done_right].\n\n    destruct lb'; subst; try solve [done_right].\n    destruct (@block_dec a b); subst; try solve [done_right].\n    destruct (@IHlb lb'); subst; try solve [auto | done_right].\nQed.\n\nLemma intrinsic_id_dec : forall (iid1 iid2:intrinsic_id),\n  {iid1=iid2}+{~iid1=iid2}.\nProof. decide equality. Qed.\n\nLemma external_id_dec : forall (eid1 eid2:external_id),\n  {eid1=eid2}+{~eid1=eid2}.\nProof. decide equality. Qed.\n\nLemma deckind_dec : forall (dck1 dck2: deckind), {dck1=dck2}+{~dck1=dck2}.\nProof.\n  destruct dck1 as [iid1|eid1].\n    destruct dck2 as [iid2|eid2]; try solve [done_right].\n      destruct (@intrinsic_id_dec iid1 iid2);\n        subst; try solve [auto | done_right].\n    destruct dck2 as [iid2|eid2]; try solve [done_right].\n      destruct (@external_id_dec eid1 eid2);\n        subst; try solve [auto | done_right].\nQed.\n\nLemma fdec_dec : forall (f1 f2:fdec), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fheader5 dck5];\n  destruct f2 as [fheader0 dck0]; try solve [subst; auto | done_right].\n    destruct (@deckind_dec dck5 dck0); subst; try solve [done_right].\n    destruct (@fheader_dec fheader5 fheader0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma fdef_dec : forall (f1 f2:fdef), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fheader5 blocks5];\n  destruct f2 as [fheader0 blocks0]; try solve [subst; auto | done_right].\n    destruct (@fheader_dec fheader5 fheader0); subst; try solve [done_right].\n    destruct (@blocks_dec blocks5 blocks0); subst; try solve [auto | done_right].\nQed.\n\nLemma gvar_spec_dec : forall (g1 g2:gvar_spec), {g1=g2}+{~g1=g2}.\nProof.\n  decide equality.\nQed.\n\nLemma gvar_dec : forall (g1 g2:gvar), {g1=g2}+{~g1=g2}.\nProof.\n  destruct g1 as [i0 l0 g t c a|i0 g t];\n  destruct g2 as [i1 l1 g0 t0 c0 a0|i1 g0 t0];\n    try solve [subst; auto | done_right].\n\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct (@linkage_dec l0 l1); subst; try solve [done_right].\n    destruct (@gvar_spec_dec g g0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [done_right].\n    destruct (@const_dec c c0); subst; try solve [done_right].\n    destruct (@Align.dec a a0); subst; try solve [auto | done_right].\n\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct (@gvar_spec_dec g g0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [auto | done_right].\nQed.\n\nLemma product_dec : forall (p p':product), {p=p'}+{~p=p'}.\nProof.\n  destruct p as [g|f|f]; destruct p' as [g0|f0|f0];\n    try solve [done_right | auto].\n    destruct (@gvar_dec g g0); subst; try solve [auto | done_right].\n    destruct (@fdec_dec f f0); subst; try solve [auto | done_right].\n    destruct (@fdef_dec f f0); subst; try solve [auto | done_right].\nQed.\n\nLemma products_dec : forall (lp lp':products), {lp=lp'}+{~lp=lp'}.\nProof.\n  induction lp.\n    destruct lp'; subst; try solve [subst; auto | done_right].\n\n    destruct lp'; subst; try solve [done_right].\n    destruct (@product_dec a p); subst; try solve [done_right].\n    destruct (@IHlp lp'); subst; try solve [auto | done_right].\nQed.\n\nLemma namedt_dec : forall (nt1 nt2:namedt), {nt1=nt2}+{~nt1=nt2}.\nProof.\n  destruct nt1 as [id5 l0];\n  destruct nt2 as [id0 l1]; try solve [subst; auto | done_right].\n    destruct (@id_dec id5 id0); subst; try solve [done_right].\n    destruct (@list_typ_dec l0 l1); subst; try solve [auto | done_right].\nQed.\n\nLemma namedts_dec : forall (nts nts':namedts), {nts=nts'}+{~nts=nts'}.\nProof.\n  induction nts.\n    destruct nts'; subst; try solve [subst; auto | done_right].\n\n    destruct nts'; subst; try solve [done_right].\n    destruct (@namedt_dec a n); subst; try solve [done_right].\n    destruct (@IHnts nts'); subst; try solve [auto | done_right].\nQed.\n\nLemma layout_dec : forall (l1 l2:layout), {l1=l2}+{~l1=l2}.\nProof.\n  destruct l1; destruct l2;\n    try solve [subst; auto | done_right | insn_dec_tac].\nQed.\n\nLemma layouts_dec : forall (l1 l2:layouts), {l1=l2}+{~l1=l2}.\nProof.\n  induction l1.\n    destruct l2; subst; try solve [subst; auto | done_right].\n\n    destruct l2; subst; try solve [done_right].\n    destruct (@layout_dec a l0); subst; try solve [done_right].\n    destruct (@IHl1 l2); subst; try solve [auto | done_right].\nQed.\n\nLemma module_dec : forall (m m':module), {m=m'}+{~m=m'}.\nProof.\n  destruct m as [l0 n p]; destruct m' as [l1 n0 p0];\n    try solve [done_right | auto].\n    destruct (@layouts_dec l0 l1); subst; try solve [done_right].\n    destruct (@namedts_dec n n0); subst; try solve [done_right].\n    destruct (@products_dec p p0); subst; try solve [auto | done_right].\nQed.\n\nLemma modules_dec : forall (lm lm':modules), {lm=lm'}+{~lm=lm'}.\nProof.\n  induction lm.\n    destruct lm'; subst; try solve [subst; auto | done_right].\n\n    destruct lm'; subst; try solve [done_right].\n    destruct (@module_dec a m); subst; try solve [done_right].\n    destruct (@IHlm lm'); subst; try solve [auto | done_right].\nQed.\n\nLemma system_dec : forall (s s':system), {s=s'}+{~s=s'}.\nProof.\n  apply modules_dec.\nQed.\n\n(**********************************)\n(* Eq. *)\nDefinition typEqB t1 t2 := sumbool2bool _ _ (typ_dec t1 t2).\n\nDefinition list_typEqB lt1 lt2 := sumbool2bool _ _ (list_typ_dec lt1 lt2).\n\nDefinition idEqB i i' := sumbool2bool _ _ (id_dec i i').\n\nDefinition constEqB c1 c2 := sumbool2bool _ _ (const_dec c1 c2).\n\nDefinition list_constEqB lc1 lc2 := sumbool2bool _ _ (list_const_dec lc1 lc2).\n\nDefinition valueEqB (v v':value) := sumbool2bool _ _ (value_dec v v').\n\nDefinition paramsEqB (lp lp':params) := sumbool2bool _ _ (params_dec lp lp').\n\nDefinition lEqB i i' := sumbool2bool _ _ (l_dec i i').\n\nDefinition list_value_lEqB (idls idls':list (value * l)) :=\n  sumbool2bool _ _ (list_value_l_dec idls idls').\n\nDefinition list_valueEqB idxs idxs' :=\n  sumbool2bool _ _ (list_value_dec idxs idxs').\n\nDefinition bopEqB (op op':bop) := sumbool2bool _ _ (bop_dec op op').\nDefinition extopEqB (op op':extop) := sumbool2bool _ _ (extop_dec op op').\nDefinition condEqB (c c':cond) := sumbool2bool _ _ (cond_dec c c').\nDefinition castopEqB (c c':castop) := sumbool2bool _ _ (castop_dec c c').\n\nDefinition cmdEqB (i i':cmd) := sumbool2bool _ _ (cmd_dec i i').\n\nDefinition cmdsEqB (cs1 cs2:list cmd) := sumbool2bool _ _ (cmds_dec cs1 cs2).\n\nDefinition terminatorEqB (i i':terminator) :=\n  sumbool2bool _ _ (terminator_dec i i').\n\nDefinition phinodeEqB (i i':phinode) := sumbool2bool _ _ (phinode_dec i i').\n\nDefinition phinodesEqB (ps1 ps2:list phinode) :=\n  sumbool2bool _ _ (phinodes_dec ps1 ps2).\n\nDefinition blockEqB (b1 b2:block) := sumbool2bool _ _ (block_dec b1 b2).\n\nDefinition blocksEqB (lb lb':blocks) := sumbool2bool _ _ (blocks_dec lb lb').\n\nDefinition argsEqB (la la':args) := sumbool2bool _ _ (args_dec la la').\n\nDefinition fheaderEqB (fh fh' : fheader) :=\n  sumbool2bool _ _ (fheader_dec fh fh').\n\nDefinition fdecEqB (fd fd' : fdec) := sumbool2bool _ _ (fdec_dec fd fd').\n\nDefinition fdefEqB (fd fd' : fdef) := sumbool2bool _ _ (fdef_dec fd fd').\n\nDefinition gvarEqB (gv gv' : gvar) := sumbool2bool _ _ (gvar_dec gv gv').\n\nDefinition productEqB (p p' : product) := sumbool2bool _ _ (product_dec p p').\n\nDefinition productsEqB (lp lp':products) :=\n  sumbool2bool _ _ (products_dec lp lp').\n\nDefinition layoutEqB (o o' : layout) := sumbool2bool _ _ (layout_dec o o').\n\nDefinition layoutsEqB (lo lo':layouts) := sumbool2bool _ _ (layouts_dec lo lo').\n\nDefinition moduleEqB (m m':module) := sumbool2bool _ _ (module_dec m m').\n\nDefinition modulesEqB (lm lm':modules) := sumbool2bool _ _ (modules_dec lm lm').\n\nDefinition systemEqB (s s':system) := sumbool2bool _ _ (system_dec s s').\n\nDefinition attributeEqB (attr attr':attribute) :=\n  sumbool2bool _ _ (attribute_dec attr attr').\n\nDefinition attributesEqB (attrs attrs':attributes) :=\n  sumbool2bool _ _ (attributes_dec attrs attrs').\n\nDefinition linkageEqB (lk lk':linkage) := sumbool2bool _ _ (linkage_dec lk lk').\n\nDefinition visibilityEqB (v v':visibility) :=\n  sumbool2bool _ _ (visibility_dec v v').\n\nDefinition callconvEqB (cc cc':callconv) :=\n  sumbool2bool _ _ (callconv_dec cc cc').\n\n(**********************************)\n(* Inclusion. *)\n\nFixpoint InCmdsB (i:cmd) (li:cmds) {struct li} : bool :=\nmatch li with\n| nil => false\n| i' :: li' => cmdEqB i i' || InCmdsB i li'\nend.\n\nFixpoint InPhiNodesB (i:phinode) (li:phinodes) {struct li} : bool :=\nmatch li with\n| nil => false\n| i' :: li' => phinodeEqB i i' || InPhiNodesB i li'\nend.\n\nDefinition cmdInBlockB (i:cmd) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro _ cmds _) => InCmdsB i cmds\nend.\n\nDefinition phinodeInBlockB (i:phinode) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro ps _ _) => InPhiNodesB i ps\nend.\n\nDefinition terminatorInBlockB (i:terminator) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro _ _ t) => terminatorEqB i t\nend.\n\nFixpoint InArgsB (a:arg) (la:args) {struct la} : bool :=\nmatch la with\n| nil => false\n| a' :: la' =>\n  match (a, a') with\n  | ((t, attrs, id), (t', attrs', id')) =>\n       typEqB t t' && attributesEqB attrs attrs' && idEqB id id'\n  end ||\n  InArgsB a la'\nend.\n\nDefinition argInFheaderB (a:arg) (fh:fheader) : bool :=\nmatch fh with\n| (fheader_intro _ t id la _) => InArgsB a la\nend.\n\nDefinition argInFdecB (a:arg) (fd:fdec) : bool :=\nmatch fd with\n| (fdec_intro fh _) => argInFheaderB a fh\nend.\n\nDefinition argInFdefB (a:arg) (fd:fdef) : bool :=\nmatch fd with\n| (fdef_intro fh lb) => argInFheaderB a fh\nend.\n\nFixpoint InBlocksB (b:block) (lb:blocks) {struct lb} : bool :=\nmatch lb with\n| nil => false\n| b' :: lb' => blockEqB b b' || InBlocksB b lb'\nend.\n\nDefinition blockInFdefB (b:block) (fd:fdef) : bool :=\nmatch fd with\n| (fdef_intro fh lb) => InBlocksB b lb\nend.\n\nFixpoint InProductsB (p:product) (lp:products) {struct lp} : bool :=\nmatch lp with\n| nil => false\n| p' :: lp' => productEqB p p' || InProductsB p lp'\nend.\n\nDefinition productInModuleB (p:product) (m:module) : bool :=\nlet (os, nts, ps) := m in\nInProductsB p ps.\n\nFixpoint InModulesB (m:module) (lm:modules) {struct lm} : bool :=\nmatch lm with\n| nil => false\n| m' :: lm' => moduleEqB m m' || InModulesB m lm'\nend.\n\nDefinition moduleInSystemB (m:module) (s:system) : bool :=\nInModulesB m s.\n\nDefinition productInSystemModuleB (p:product) (s:system) (m:module) : bool :=\nmoduleInSystemB m s && productInModuleB p m.\n\nDefinition blockInSystemModuleFdefB (b:block) (s:system) (m:module) (f:fdef)\n  : bool :=\nblockInFdefB b f && productInSystemModuleB (product_fdef f) s m.\n\nDefinition cmdInSystemModuleFdefBlockB\n  (i:cmd) (s:system) (m:module) (f:fdef) (b:block) : bool :=\ncmdInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition phinodeInSystemModuleFdefBlockB\n  (i:phinode) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nphinodeInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition terminatorInSystemModuleFdefBlockB\n  (i:terminator) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nterminatorInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition insnInSystemModuleFdefBlockB\n  (i:insn) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nmatch i with\n| insn_phinode p => phinodeInSystemModuleFdefBlockB p s m f b\n| insn_cmd c => cmdInSystemModuleFdefBlockB c s m f b\n| insn_terminator t => terminatorInSystemModuleFdefBlockB t s m f b\nend.\n\nDefinition insnInBlockB (i : insn) (b : block) :=\nmatch i with\n| insn_phinode p => phinodeInBlockB p b\n| insn_cmd c => cmdInBlockB c b\n| insn_terminator t => terminatorInBlockB t b\nend.\n\nDefinition cmdInFdefBlockB (i:cmd) (f:fdef) (b:block) : bool :=\ncmdInBlockB i b && blockInFdefB b f.\n\nDefinition phinodeInFdefBlockB (i:phinode) (f:fdef) (b:block) : bool :=\nphinodeInBlockB i b && blockInFdefB b f.\n\nDefinition terminatorInFdefBlockB (i:terminator) (f:fdef) (b:block) : bool :=\nterminatorInBlockB i b && blockInFdefB b f.\n\nDefinition insnInFdefBlockB\n  (i:insn) (f:fdef) (b:block) : bool :=\nmatch i with\n| insn_phinode p => phinodeInBlockB p b && blockInFdefB b f\n| insn_cmd c => cmdInBlockB c b && blockInFdefB b f\n| insn_terminator t => terminatorInBlockB t b && blockInFdefB b f\nend.\n\nDefinition blockInSystemModuleFdef b S M F :=\n  blockInSystemModuleFdefB b S M F = true.\n\nDefinition moduleInSystem M S := moduleInSystemB M S = true.\n\n(**********************************)\n(* parent *)\n\n(* matching (cmdInBlockB i b) in getParentOfCmdFromBlocksC directly makes\n   the compilation very slow, so we define this dec lemma first... *)\nLemma cmdInBlockB_dec : forall i b,\n  {cmdInBlockB i b = true} + {cmdInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (cmdInBlockB i0 b); auto.\nQed.\n\nLemma phinodeInBlockB_dec : forall i b,\n  {phinodeInBlockB i b = true} + {phinodeInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (phinodeInBlockB i0 b); auto.\nQed.\n\nLemma terminatorInBlockB_dec : forall i b,\n  {terminatorInBlockB i b = true} + {terminatorInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (terminatorInBlockB i0 b); auto.\nQed.\n\nFixpoint getParentOfCmdFromBlocks (i:cmd) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (cmdInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfCmdFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfCmdFromFdef (i:cmd) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfCmdFromBlocks i lb\nend.\n\nDefinition getParentOfCmdFromProduct (i:cmd) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfCmdFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfCmdFromProducts (i:cmd) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfCmdFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfCmdFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfCmdFromModule (i:cmd) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfCmdFromProducts i ps.\n\nFixpoint getParentOfCmdFromModules (i:cmd) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfCmdFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfCmdFromModules i lm'\n  end\nend.\n\nDefinition getParentOfCmdFromSystem (i:cmd) (s:system) : option block :=\n  getParentOfCmdFromModules i s.\n\nDefinition cmdHasParent (i:cmd) (s:system) : bool :=\nmatch (getParentOfCmdFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nFixpoint getParentOfPhiNodeFromBlocks (i:phinode) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (phinodeInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfPhiNodeFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromFdef (i:phinode) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfPhiNodeFromBlocks i lb\nend.\n\nDefinition getParentOfPhiNodeFromProduct (i:phinode) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfPhiNodeFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfPhiNodeFromProducts (i:phinode) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfPhiNodeFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfPhiNodeFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromModule (i:phinode) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfPhiNodeFromProducts i ps.\n\nFixpoint getParentOfPhiNodeFromModules (i:phinode) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfPhiNodeFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfPhiNodeFromModules i lm'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromSystem (i:phinode) (s:system) : option block :=\n  getParentOfPhiNodeFromModules i s.\n\nDefinition phinodeHasParent (i:phinode) (s:system) : bool :=\nmatch (getParentOfPhiNodeFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nFixpoint getParentOfTerminatorFromBlocks (i:terminator) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (terminatorInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfTerminatorFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfTerminatorFromFdef (i:terminator) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfTerminatorFromBlocks i lb\nend.\n\nDefinition getParentOfTerminatorFromProduct (i:terminator) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfTerminatorFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfTerminatorFromProducts (i:terminator) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfTerminatorFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfTerminatorFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfTerminatorFromModule (i:terminator) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfTerminatorFromProducts i ps.\n\nFixpoint getParentOfTerminatorFromModules (i:terminator) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfTerminatorFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfTerminatorFromModules i lm'\n  end\nend.\n\nDefinition getParentOfTerminatorFromSystem (i:terminator) (s:system) : option block :=\n  getParentOfTerminatorFromModules i s.\n\nDefinition terminatoreHasParent (i:terminator) (s:system) : bool :=\nmatch (getParentOfTerminatorFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nLemma productInModuleB_dec : forall b m,\n  {productInModuleB b m = true} + {productInModuleB b m = false}.\nProof.\n  intros b m. destruct (productInModuleB b m); auto.\nQed.\n\nFixpoint getParentOfFdefFromModules (fd:fdef) (lm:modules) {struct lm} : option module :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (productInModuleB_dec (product_fdef fd) m) with\n  | left _ => Some m\n  | right _ => getParentOfFdefFromModules fd lm'\n  end\nend.\n\nDefinition getParentOfFdefFromSystem (fd:fdef) (s:system) : option module :=\n  getParentOfFdefFromModules fd s.\n\nNotation \"t =t= t' \" := (typEqB t t') (at level 50).\nNotation \"n =n= n'\" := (beq_nat n n') (at level 50).\nNotation \"b =b= b'\" := (blockEqB b b') (at level 50).\nNotation \"i =cmd= i'\" := (cmdEqB i i') (at level 50).\nNotation \"i =phi= i'\" := (phinodeEqB i i') (at level 50).\nNotation \"i =tmn= i'\" := (terminatorEqB i i') (at level 50).\n\n(**********************************)\n(* Check to make sure that if there is more than one entry for a\n   particular basic block in this PHI node, that the incoming values\n   are all identical. *)\nFixpoint lookupIdsViaLabelFromIdls\n  (idls:list (value * l)) (l0:l) : list id :=\nmatch idls with\n| nil => nil\n| (value_id id1, l1) :: idls' =>\n  if (eq_dec l0 l1)\n  then set_add eq_dec id1 (lookupIdsViaLabelFromIdls idls' l0)\n  else (lookupIdsViaLabelFromIdls idls' l0)\n| (_, l1) :: idls' =>\n  lookupIdsViaLabelFromIdls idls' l0\nend.\n\nFixpoint _checkIdenticalIncomingValues\n  (idls idls0:list (value * l)) : Prop :=\nmatch idls with\n| nil => True\n| (_, l) :: idls' =>\n  (length (lookupIdsViaLabelFromIdls idls0 l) <= 1)%nat /\\\n  (_checkIdenticalIncomingValues idls' idls0)\nend.\n\nDefinition checkIdenticalIncomingValues (PN:phinode) : Prop :=\nmatch PN with\n| insn_phi _ _ idls => _checkIdenticalIncomingValues idls idls\nend.\n\n(**********************************)\n(* Instruction Signature *)\n\nModule Type SigValue.\n\n Parameter getNumOperands : insn -> nat.\n\nEnd SigValue.\n\nModule Type SigUser.\n Include SigValue.\n\nEnd SigUser.\n\nModule Type SigConstant.\n Include SigValue.\n\n Parameter getTyp : const -> option typ.\n\nEnd SigConstant.\n\nModule Type SigGlobalValue.\n Include SigConstant.\n\nEnd SigGlobalValue.\n\nModule Type SigFunction.\n Include SigGlobalValue.\n\n Parameter getDefReturnType : fdef -> typ.\n Parameter getDefFunctionType : fdef -> typ.\n Parameter def_arg_size : fdef -> nat.\n\n Parameter getDecReturnType : fdec -> typ.\n Parameter getDecFunctionType : fdec -> typ.\n Parameter dec_arg_size : fdec -> nat.\n\nEnd SigFunction.\n\nModule Type SigInstruction.\n Include SigUser.\n\n(* Parameter isInvokeInst : insn -> bool. *)\n Parameter isCallInst : cmd -> bool.\n\nEnd SigInstruction.\n\nModule Type SigReturnInst.\n Include SigInstruction.\n\n Parameter hasReturnType : terminator -> bool.\n Parameter getReturnType : terminator -> option typ.\n\nEnd SigReturnInst.\n\nModule Type SigCallSite.\n(* Parameter getCalledFunction : cmd -> system -> option fdef. *)\n Parameter getFdefTyp : fdef -> typ.\n Parameter arg_size : fdef -> nat.\n Parameter getArgument : fdef -> nat -> option arg.\n Parameter getArgumentType : fdef -> nat -> option typ.\n\nEnd SigCallSite.\n\nModule Type SigCallInst.\n Include SigInstruction.\n\nEnd SigCallInst.\n\n(*\nModule Type SigInvokeInst.\n Include SigInstruction.\n\n Parameter getNormalDest : system -> insn -> option block.\n\nEnd SigInvokeInst.\n*)\n\nModule Type SigBinaryOperator.\n Include SigInstruction.\n\n Parameter getFirstOperandType : fdef -> cmd -> option typ.\n Parameter getSecondOperandType : fdef -> cmd -> option typ.\n Parameter getResultType : cmd -> option typ.\n\nEnd SigBinaryOperator.\n\nModule Type SigPHINode.\n Include SigInstruction.\n\n Parameter getNumIncomingValues : phinode -> nat.\n Parameter getIncomingValueType : fdef  -> phinode -> i -> option typ.\nEnd SigPHINode.\n\n(* Type Signature *)\n\nModule Type SigType.\n Parameter isIntOrIntVector : typ -> bool.\n Parameter isInteger : typ -> bool.\n Parameter isSized : typ -> bool.\n Parameter getPrimitiveSizeInBits : typ -> sz.\nEnd SigType.\n\nModule Type SigDerivedType.\n Include SigType.\nEnd SigDerivedType.\n\nModule Type SigFunctionType.\n Include SigDerivedType.\n\n Parameter getNumParams : typ -> option nat.\n Parameter isVarArg : typ -> bool.\n Parameter getParamType : typ -> nat -> option typ.\nEnd SigFunctionType.\n\nModule Type SigCompositeType.\n Include SigDerivedType.\nEnd SigCompositeType.\n\nModule Type SigSequentialType.\n Include SigCompositeType.\n\n Parameter hasElementType : typ -> bool.\n Parameter getElementType : typ -> option typ.\n\nEnd SigSequentialType.\n\nModule Type SigArrayType.\n Include SigSequentialType.\n\n Parameter getNumElements : typ -> nat.\n\nEnd SigArrayType.\n\n(* Instruction Instantiation *)\n\nModule Value <: SigValue.\n\n Definition getNumOperands (i:insn) : nat :=\n   length (getInsnOperands i).\n\nEnd Value.\n\nModule User <: SigUser. Include Value.\n\nEnd User.\n\nModule Constant <: SigConstant.\n Include Value.\n\nFixpoint getTyp (c:const) : option typ :=\n match c with\n | const_zeroinitializer t => Some t\n | const_int sz _ => Some (typ_int sz)\n | const_floatpoint fp _ => Some (typ_floatpoint fp)\n | const_undef t => Some t\n | const_null t => Some (typ_pointer t)\n | const_arr t lc =>\n   Some\n   (match lc with\n   | nil => typ_array Size.Zero t\n   | c' :: lc' => typ_array (Size.from_nat (length lc)) t\n   end)\n | const_struct t lc => Some t\n(*\n   match getList_typ lc with\n   | Some lt => Some (typ_struct lt)\n   | None => None\n   end\n*)\n | const_gid t _ => Some (typ_pointer t)\n | const_truncop _ _ t => Some t\n | const_extop _ _ t => Some t\n | const_castop _ _ t => Some t\n | const_gep _ c idxs =>\n   match (getTyp c) with\n   | Some t => getConstGEPTyp idxs t\n   | _ => None\n   end\n | const_select c0 c1 c2 => getTyp c1\n | const_icmp c c1 c2 => Some (typ_int Size.One)\n | const_fcmp fc c1 c2 => Some (typ_int Size.One)\n | const_extractvalue c idxs =>\n   match (getTyp c) with\n   | Some t => getSubTypFromConstIdxs idxs t\n   | _ => None\n   end\n | const_insertvalue c c' lc => getTyp c\n | const_bop _ c1 c2 => getTyp c1\n | const_fbop _ c1 c2 => getTyp c1\n end.\n\nDefinition gen_utyps_maps_aux_\n  (gen_utyp_maps_aux : id -> list (id * typ) -> typ -> option typ) :=\nfix gen_utyps_maps_aux\n(cid:id) (m:list(id*typ)) (ts:list typ) : option (list typ) :=\nmatch ts with\n  | nil => Some nil\n  | t0 :: ts0 =>\n    do ut0 <- gen_utyp_maps_aux cid m t0;\n    do uts0 <- gen_utyps_maps_aux cid m ts0;\n    ret (ut0 :: uts0)\nend.\n\nFixpoint gen_utyp_maps_aux (cid:id) (m:list(id*typ)) (t:typ) : option typ :=\n match t with\n | typ_int s => Some (typ_int s)\n | typ_floatpoint f => Some (typ_floatpoint f)\n | typ_void => Some typ_void\n | typ_label => Some typ_label\n | typ_metadata => Some typ_metadata\n | typ_array s t0 =>\n   do ut0 <- gen_utyp_maps_aux cid m t0;\n   ret (typ_array s ut0)\n | typ_function t0 ts0 va =>\n     do ut0 <- gen_utyp_maps_aux cid m t0;\n     do uts0 <- gen_utyps_maps_aux_ gen_utyp_maps_aux cid m ts0;\n        ret (typ_function ut0 uts0 va)\n | typ_struct ts0 =>\n     do uts0 <- gen_utyps_maps_aux_ gen_utyp_maps_aux cid m ts0;\n     ret (typ_struct uts0)\n | typ_pointer t0 =>\n     match gen_utyp_maps_aux cid m t0 with\n     | Some ut0 => Some (typ_pointer ut0)\n     | None =>\n         match t0 with\n         | typ_namedt i => if eq_atom_dec i cid then Some t else None\n         | _ => None\n         end\n     end\n(* | typ_opaque => Some typ_opaque *)\n | typ_namedt i => lookupAL _ m i\n end.\n\nDefinition gen_utyps_maps_aux :=\n  gen_utyps_maps_aux_ gen_utyp_maps_aux.\n\nFixpoint gen_utyp_maps (nts:namedts) : list (id*typ) :=\nmatch nts with\n| nil => nil\n| (id0, t)::nts' =>\n  let results := gen_utyp_maps nts' in\n  match gen_utyp_maps_aux id0 results (typ_struct t) with\n  | None => results\n  | Some r => (id0, r)::results\n  end\nend.\n\nDefinition typs2utyps_aux_\n  (typ2utyp_aux : list (id * typ) -> typ -> option typ) :=\nfix typs2utyps_aux (m:list(id*typ)) (ts:list typ) : option (list typ) :=\n match ts with\n | nil => Some nil\n | t0 :: ts0 =>\n     do ut0 <- typ2utyp_aux m t0;\n     do uts0 <- typs2utyps_aux m ts0;\n     ret (ut0 :: uts0)\n end.\n\nFixpoint typ2utyp_aux (m:list(id*typ)) (t:typ) : option typ :=\n match t with\n | typ_int s => Some (typ_int s)\n | typ_floatpoint f => Some (typ_floatpoint f)\n | typ_void => Some typ_void\n | typ_label => Some typ_label\n | typ_metadata => Some typ_metadata\n | typ_array s t0 => do ut0 <- typ2utyp_aux m t0; ret (typ_array s ut0)\n | typ_function t0 ts0 va =>\n     do ut0 <- typ2utyp_aux m t0;\n     do uts0 <- typs2utyps_aux_ typ2utyp_aux m ts0;\n        ret (typ_function ut0 uts0 va)\n | typ_struct ts0 =>\n   do uts0 <- typs2utyps_aux_ typ2utyp_aux m ts0;\n   ret (typ_struct uts0)\n | typ_pointer t0 =>\n   do ut0 <- typ2utyp_aux m t0;\n   ret (typ_pointer ut0)\n(* | typ_opaque => Some typ_opaque *)\n | typ_namedt i => lookupAL _ m i\n end.\n\nDefinition typs2utyps_aux :=\n  typs2utyps_aux_ typ2utyp_aux.\n\nDefinition typ2utyp' (nts:namedts) (t:typ) : option typ :=\nlet m := gen_utyp_maps (List.rev nts) in\ntyp2utyp_aux m t.\n\nFixpoint subst_typ (i':id) (t' t:typ) : typ :=\n\n  let subst_typs :=\n    fix subst_typs (i':id) (t':typ) (ts:list typ) : list typ :=\n    match ts with\n    | nil => nil\n    | t0 :: ts0 =>\n     (subst_typ i' t' t0) :: (subst_typs i' t' ts0)\n    end in\n\n match t with\n | typ_int _ | typ_floatpoint _ | typ_void | typ_label | typ_metadata => t\n | typ_array s t0 => typ_array s (subst_typ i' t' t0)\n | typ_function t0 ts0 va =>\n     typ_function (subst_typ i' t' t0) (subst_typs i' t' ts0) va\n | typ_struct ts0 => typ_struct (subst_typs i' t' ts0)\n | typ_pointer t0 => typ_pointer (subst_typ i' t' t0)\n | typ_namedt i => if (eq_atom_dec i i') then t' else t\n end.\n\nFixpoint subst_typ_by_nts (nts:namedts) (t:typ) : typ :=\nmatch nts with\n| nil => t\n| (id', ts')::nts' =>\n    subst_typ_by_nts nts' (subst_typ id' (typ_struct ts') t)\nend.\n\nFixpoint subst_nts_by_nts (nts0 nts:namedts) : list (id*typ) :=\nmatch nts with\n| nil => nil\n| (id', t')::nts' =>\n    (id',(subst_typ_by_nts nts0 (typ_struct t')))::subst_nts_by_nts nts0 nts'\nend.\n\nDefinition typ2utyp (nts:namedts) (t:typ) : option typ :=\nlet m := subst_nts_by_nts nts nts in\ntyp2utyp_aux m t.\n\nDefinition unifiable_typ (TD:LLVMtd.TargetData) (t:typ) : Prop :=\n  let '(los,nts) := TD in\n  exists ut, typ2utyp nts t = Some ut /\\\n    LLVMtd.getTypeAllocSize TD ut = LLVMtd.getTypeAllocSize TD t.\n\nEnd Constant.\n\nModule GlobalValue <: SigGlobalValue.\n Include Constant.\n\nEnd GlobalValue.\n\nModule Function <: SigFunction.\n Include GlobalValue.\n\n Definition getDefReturnType (fd:fdef) : typ :=\n match fd with\n | fdef_intro (fheader_intro _ t _ _ _ ) _ => t\n end.\n\n Definition getDefFunctionType (fd:fdef) : typ := getFdefTyp fd.\n\n Definition def_arg_size (fd:fdef) : nat :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) => length la\n end.\n\n Definition getDecReturnType (fd:fdec) : typ :=\n match fd with\n | fdec_intro (fheader_intro _ t _ _ _ ) _ => t\n end.\n\n Definition getDecFunctionType (fd:fdec) : typ := getFdecTyp fd.\n\n Definition dec_arg_size (fd:fdec) : nat :=\n match fd with\n | fdec_intro (fheader_intro _ _ _ la _) _ => length la\n end.\n\nEnd Function.\n\nModule Instruction <: SigInstruction.\n Include User.\n\n(* Definition isInvokeInst (i:insn) : bool := isInvokeInsnB i. *)\n Definition isCallInst (i:cmd) : bool := _isCallInsnB i.\n\nEnd Instruction.\n\nModule ReturnInst <: SigReturnInst.\n Include Instruction.\n\n Definition hasReturnType (i:terminator) : bool :=\n match i with\n | insn_return _ t v => true\n | _ => false\n end.\n\n Definition getReturnType (i:terminator) : option typ :=\n match i with\n | insn_return _ t v => Some t\n | _ => None\n end.\n\nEnd ReturnInst.\n\nModule CallSite <: SigCallSite.\n\n Definition getFdefTyp (fd:fdef) : typ := getFdefTyp fd.\n\n Definition arg_size (fd:fdef) : nat :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) => length la\n end.\n\n Definition getArgument (fd:fdef) (i:nat) : option arg :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) =>\n    match (nth_error la i) with\n    | Some a => Some a\n    | None => None\n    end\n end.\n\n Definition getArgumentType (fd:fdef) (i:nat) : option typ :=\n match (getArgument fd i) with\n | Some (t, _, _) => Some t\n | None => None\n end.\n\nEnd CallSite.\n\nModule CallInst <: SigCallInst.\n Include Instruction.\n\nEnd CallInst.\n\nModule BinaryOperator <: SigBinaryOperator.\n Include Instruction.\n\n Definition getFirstOperandType (f:fdef) (i:cmd) : option typ :=\n match i with\n | insn_bop _ _ _ v1 _ =>\n   match v1 with\n   | value_id id1 => lookupTypViaIDFromFdef f id1\n   | value_const c => Constant.getTyp c\n   end\n | _ => None\n end.\n\n Definition getSecondOperandType (f:fdef) (i:cmd) : option typ :=\n match i with\n | insn_bop _ _ _ _ v2 =>\n   match v2 with\n   | value_id id2 => lookupTypViaIDFromFdef f id2\n   | value_const c => Constant.getTyp c\n   end\n | _ => None\n end.\n\n Definition getResultType (i:cmd) : option typ := getCmdTyp i.\n\nEnd BinaryOperator.\n\nModule PHINode <: SigPHINode.\n Include Instruction.\n\n Definition getNumIncomingValues (i:phinode) : nat :=\n match i with\n | (insn_phi _ _ ln) => (length ln)\n end.\n\n Definition getIncomingValueType (f:fdef) (i:phinode) (n:nat) : option typ :=\n match i with\n | (insn_phi _ _ ln) =>\n    match (nth_error ln n) with\n    | Some (value_id id, _) => lookupTypViaIDFromFdef f id\n    | Some (value_const c, _) => Constant.getTyp c\n    | None => None\n    end\n end.\n\nEnd PHINode.\n\n(* Type Instantiation *)\n\nModule Typ <: SigType.\n Definition isIntOrIntVector (t:typ) : bool :=\n match t with\n | typ_int _ => true\n | _ => false\n end.\n\n Definition isInteger (t:typ) : bool :=\n match t with\n | typ_int _ => true\n | _ => false\n end.\n\n (* isSizedDerivedType - Derived types like structures and arrays are sized\n    iff all of the members of the type are sized as well.  Since asking for\n    their size is relatively uncommon, move this operation out of line.\n\n    isSized - Return true if it makes sense to take the size of this type.  To\n    get the actual size for a particular target, it is reasonable to use the\n    TargetData subsystem to do this. *)\n Fixpoint isSized (t:typ) : bool :=\n   let isSizedListTyp :=\n     fix isSizedListTyp (lt : list typ) : bool :=\n     match lt with\n     | nil => true\n     | t :: lt' => isSized t && isSizedListTyp lt'\n     end in\n match t with\n | typ_int _ => true\n | typ_floatpoint _ => true\n | typ_array _ t' => isSized t'\n | typ_struct lt => isSizedListTyp lt\n | typ_pointer _ => true\n | _ => false\n end.\n\n  Definition getPrimitiveSizeInBits (t:typ) : sz :=\n  match t with\n  | typ_int sz => sz\n  | _ => Size.Zero\n  end.\n\nEnd Typ.\n\nModule DerivedType <: SigDerivedType.\n Include Typ.\nEnd DerivedType.\n\nModule FunctionType <: SigFunctionType.\n Include DerivedType.\n\n Definition getNumParams (t:typ) : option nat :=\n match t with\n | (typ_function _ lt _) =>\n     Some (length lt)\n | _ => None\n end.\n\n Definition isVarArg (t:typ) : bool := false.\n\n Definition getParamType (t:typ) (i:nat) : option typ :=\n match t with\n | (typ_function _ lt _) =>\n    match (nth_error lt i) with\n    | Some t => Some t\n    | None => None\n    end\n | _ => None\n end.\n\nEnd FunctionType.\n\nModule CompositeType <: SigCompositeType.\n Include DerivedType.\nEnd CompositeType.\n\nModule SequentialType <: SigSequentialType.\n Include CompositeType.\n\n Definition hasElementType (t:typ) : bool :=\n match t with\n | typ_array _ t' => true\n | _ => false\n end.\n\n Definition getElementType (t:typ) : option typ :=\n match t with\n | typ_array _ t' => Some t'\n | _ => None\n end.\n\nEnd SequentialType.\n\nModule ArrayType <: SigArrayType.\n Include SequentialType.\n\n Definition getNumElements (t:typ) : nat :=\n match t with\n | typ_array N _ => Size.to_nat N\n | _ => 0%nat\n end.\n\nEnd ArrayType.\n\n(* Definition typ2memory_chunk (t:typ) : option AST.memory_chunk := *)\n(*   match t with *)\n(*   | typ_int bsz => Some (AST.Mint (Size.to_nat bsz -1)) *)\n(*   | typ_floatpoint fp_float => Some AST.Mfloat32 *)\n(*   | typ_floatpoint fp_double => Some AST.Mfloat64 *)\n(*   | typ_floatpoint _ => None *)\n(*   | typ_pointer _ => Some (AST.Mint 31) *)\n(*   | _ => None *)\n(*   end. *)\n\nDefinition wf_alignment (TD:LLVMtd.TargetData) (t:typ) : Prop :=\nforall s a (abi_or_pref:bool),\n  LLVMtd.getTypeSizeInBits_and_Alignment TD abi_or_pref t = Some (s,a) ->\n  (a > 0)%nat.\n\nDefinition typ_eq_list_typ (nts:namedts) (t1:typ) (ts2:list typ) : bool :=\nmatch t1 with\n| typ_struct ts1 => list_typ_dec ts1 ts2\n| typ_namedt nid1 =>\n    match lookupAL _ nts nid1 with\n    | Some ts1 => list_typ_dec ts1 ts2\n    | _ => false\n    end\n| _ => false\nend.\n\nDefinition wf_intrinsics_id (iid:intrinsic_id) (rt:typ) (pt:list typ) (va:varg)\n  : Prop :=\nTrue.\n\nDefinition wf_external_id (eid:external_id) (rt:typ) (pt:list typ) (va:varg)\n  : Prop :=\nmatch eid with\n| eid_malloc =>\n    match rt, pt with\n    | typ_pointer (typ_int 8%nat), (typ_int sz) :: nil =>\n        match sz with\n        | 32%nat | 64%nat => True\n        | _ => False\n        end\n    | _, _ => False\n    end\n| eid_free =>\n    match rt, pt with\n    | typ_void, (typ_pointer (typ_int 8%nat)) :: nil\n    | _, _ => False\n    end\n| eid_other => True\n| eid_io => True\nend.\n\nDefinition wf_deckind (fh:fheader) (dck:deckind) : Prop :=\nlet '(fheader_intro _ rt _ la va) := fh in\nlet pt := args2Typs la in\nmatch dck with\n| deckind_intrinsic iid => wf_intrinsics_id iid rt pt va\n| deckind_external eid => wf_external_id eid rt pt va\nend.\n\n(**********************************)\n(* reflect *)\n\nCoercion is_true (b:bool) := b = true.\n\nInductive reflect (P:Prop) : bool -> Set :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~P -> reflect P false\n.\n\n(**********************************)\n(* get locs of a function *)\n\nDefinition getValueID' (v:value) : atoms :=\nmatch v with\n| value_id id => {{id}}\n| value_const _ => {}\nend.\n\nDefinition getFdefLocs fdef : ids :=\nmatch fdef with\n| fdef_intro (fheader_intro _ _ _ la _) bs => getArgsIDs la ++ getBlocksLocs bs\nend.\n\nDefinition id_fresh_in_value v1 i2 : Prop :=\nmatch v1 with\n| value_id i1 => i1 <> i2\n| _ => True\nend.\n\nFixpoint ids2atoms (ids0:ids) : atoms :=\nmatch ids0 with\n| nil => {}\n| id0::ids0' => {{id0}} `union` ids2atoms ids0'\nend.\n\nEnd LLVMinfra.\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/infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.17479343340907647}}
{"text": "(* Modified Smallstep library to verify dynamic optimizations *)\n\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import Coqlib.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import IR.\nRequire Import RTLblock.\nRequire Import mixed_sem.\nRequire Import monad_impl.\nRequire Import customSmallstep.\n\nSet Implicit Arguments.\n\n(** * Reflexivity of our match_states relations  *)\nDefinition reflexive {index:Type} {state:Type} (match_states: index -> state -> state -> Prop): Prop :=\n  forall s, exists i, match_states i s s.\n\n(** * Reflexivity on Call states  *)\nDefinition p_reflexive {index:Type} (P:mixed_state -> Prop) (match_states: index -> mixed_state -> mixed_state -> Prop):Prop :=\n  forall s, P s -> exists i, match_states i s s.\n\nInductive refl_point: mixed_state -> Prop :=\n| refl_call:\n    forall loc ms,\n      refl_point (S_Call loc, ms).\n\nDefinition call_refl {index:Type} (match_states: index -> mixed_state -> mixed_state -> Prop) : Prop :=\n  p_reflexive refl_point match_states.\n\n(** * Forward Internal Simulations between two transition semantics. *)\n(** The general form of a forward internal simulation. *)\nRecord forward_internal_simulation (p1 p2:program) (rtl1 rtl2: option (RTLfun+RTLblockfun)) (nc1 nc2: asm_codes) : Type :=\n  Forward_internal_simulation {\n    fsim_index: Type;\n    fsim_order: fsim_index -> fsim_index -> Prop;\n    fsim_order_wf: well_founded fsim_order;\n    fsim_match_states :> fsim_index -> mixed_state -> mixed_state -> Prop;\n    fsim_match_states_refl: call_refl fsim_match_states;\n    fsim_match_final_states:\n      forall i s1 s2 r,\n      fsim_match_states i s1 s2 -> final_mixed_state p1 s1 r -> final_mixed_state p2 s2 r;\n    fsim_simulation:\n      forall s1 t s1', Step (mixed_sem p1 rtl1 nc1) s1 t s1' ->\n      forall i s2, fsim_match_states i s1 s2 ->\n      exists i', exists s2',\n         (SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' \\/ (Star (mixed_sem p2 rtl2 nc2) s2 t s2' /\\ fsim_order i' i))\n      /\\ fsim_match_states i' s1' s2';\n  }.\n\n(* Implicit Arguments forward_simulation []. *)\nArguments forward_internal_simulation: clear implicits.\n\n(** An alternate form of the simulation diagram *)\n\nLemma fsim_simulation':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 (S: forward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2),\n  forall i s1 t s1', Step (mixed_sem p1 rtl1 nc1) s1 t s1' ->\n  forall s2, S i s1 s2 ->\n  (exists i', exists s2', SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' /\\ S i' s1' s2')\n  \\/ (exists i', fsim_order S i' i /\\ t = E0 /\\ S 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 H2.\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(* not needed *)\n\n(** ** Forward simulation of transition sequences *)\n(* not needed *)\n\n(** ** Composing two forward simulations *)\n(* We only compose backward simulations now *)\n\n\n(** * Backward simulations between two transition semantics. *)\n(** The general form of a backward internal simulation. *)\n(* The one used as an invariant of the JIT execution, on silent semantics *)\nRecord backward_internal_simulation (p1 p2: program) (rtl1 rtl2:option (RTLfun+RTLblockfun)) (nc1 nc2: asm_codes): Type :=\n  Backward_internal_simulation {\n    bsim_index: Type;\n    bsim_order: bsim_index -> bsim_index -> Prop;\n    bsim_order_wf: well_founded bsim_order;\n    (* bsim_order_trans: transitive _ bsim_order; *)\n    bsim_match_states :> bsim_index -> mixed_state -> mixed_state -> Prop;\n    bsim_match_states_refl: call_refl bsim_match_states;\n    bsim_match_final_states:\n      forall i s1 s2 r,\n      bsim_match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> final_mixed_state p2 s2 r ->\n      exists s1', Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ final_mixed_state p1 s1' r;\n    bsim_progress:\n      forall i s1 s2,\n      bsim_match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n      (exists r, final_mixed_state p2 s2 r) \\/\n      (exists t, exists s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2');\n    bsim_simulation:\n      forall s2 t s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n      forall i s1, bsim_match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n      exists i', exists s1',\n         (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ bsim_order i' i))\n      /\\ bsim_match_states i' s1' s2';\n  }.\n\n(** An alternate form of the simulation diagram *)\nLemma bsim_simulation':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 (S: backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2),\n  forall i s2 t s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n  forall s1, S i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  (exists i', exists s1', SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ S i' s1' s2')\n  \\/ (exists i', bsim_order S i' i /\\ t = E0 /\\ S 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 H3.\n  right; exists i'; auto.\n  left; exists i'; exists s1'; split; auto. econstructor; eauto.\nQed.\n\n(** ** Backward simulation diagrams. *)\n\n(** ** Backward simulation of transition sequences *)\nSection BACKWARD_SIMULATION_SEQUENCES.\n\nVariable p1 p2: program.\nVariable rtl1 rtl2: option (RTLfun+RTLblockfun).\nVariable nc1: asm_codes.\nVariable nc2: asm_codes.\nVariable S: backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2.\n\nLemma bsim_E0_star:\n  forall s2 s2', Star (mixed_sem p2 rtl2 nc2) s2 E0 s2' ->\n  forall i s1, S i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1', Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ S 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 (mixed_sem p1 rtl1 nc1) 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  S i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> safe (mixed_sem p2 rtl2 nc2) 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', SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' -> t = E0 ->\n  forall i s1, S i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n     (exists i', exists s1', SPlus (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ S i' s1' s2')\n  \\/ (exists i', clos_trans _ (bsim_order S) i' i /\\ S 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 with (s2:=s3); 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 (mixed_sem p2 rtl2 nc2) s2 t s2' -> (length t = 1)%nat ->\n  exists s2x, exists s2y, Star (mixed_sem p2 rtl2 nc2) s2 E0 s2x /\\ Step (mixed_sem p2 rtl2 nc2) s2x t s2y /\\ Star (mixed_sem p2 rtl2 nc2) 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; omegaContradiction.\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(* Transitive closure is transitive *)\nLemma clos_trans_trans :\n  forall (X:Type) R, transitive X (clos_trans X R).\nProof.\n  intros X R. unfold transitive. intros x y z H. generalize dependent z.\n  induction H; intros.\n  - apply t_trans with (y:=y). apply t_step. auto. auto.\n  - apply IHclos_trans1. apply IHclos_trans2. auto.\nQed.\n\n\n(** ** Composing two backward simulations *)\n\nSection COMPOSE_INTERNAL_BACKWARD_SIMULATIONS.\n\nVariable p1 p2 p3: program.\nVariable rtl1 rtl2 rtl3: option (RTLfun+RTLblockfun).\nVariable nc1: asm_codes.\nVariable nc2: asm_codes.\nVariable nc3: asm_codes.\nHypothesis p3_single_events: single_events (mixed_sem p3 rtl3 nc3).\nVariable S12: backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2.\nVariable S23: backward_internal_simulation p2 p3 rtl2 rtl3 nc2 nc3.\n\nLet bb_index : Type := (bsim_index S12 * bsim_index S23)%type.\n\nLet bb_order : bb_index -> bb_index -> Prop :=\n  lex_ord (clos_trans _ (bsim_order S12)) (bsim_order S23).\n\nInductive bb_match_states: bb_index -> mixed_state -> mixed_state -> Prop :=\n  | bb_match_later: forall i1 i2 s1 s3 s2x s2y,\n      S12 i1 s1 s2x -> Star (mixed_sem p2 rtl2 nc2) s2x E0 s2y -> S23 i2 s2y s3 ->\n      bb_match_states (i1, i2) s1 s3.\n\nLemma bb_match_at: forall i1 i2 s1 s3 s2,\n  S12 i1 s1 s2 -> S23 i2 s2 s3 ->\n  bb_match_states (i1, i2) s1 s3.\nProof.\n  intros. econstructor; eauto. apply star_refl.\nQed.\n\n\nLemma bb_simulation_base:\n  forall s3 t s3', Step (mixed_sem p3 rtl3 nc3) s3 t s3' ->\n  forall i1 s1 i2 s2, S12 i1 s1 s2 -> S23 i2 s2 s3 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1',\n    (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) 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 p3_single_events; eauto.\n    destruct t; auto. destruct t; auto. simpl. intros. omegaContradiction.\n  destruct EITHER.\n  (* 1.1 these are silent transitions *)\n  subst t. exploit bsim_E0_plus; 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. eexact P. eauto. auto. intros [i1' [s1x [X Y]]].\n  exploit bsim_simulation'. 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 (mixed_sem p3 rtl3 nc3) s3 t s3' ->\n  forall i s1, bb_match_states i s1 s3 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1',\n    (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) 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; 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\nLemma compose_backward_simulation: backward_internal_simulation p1 p3 rtl1 rtl3 nc1 nc3.\nProof.\n  apply Backward_internal_simulation with (bsim_order := bb_order) (bsim_match_states := bb_match_states).\n(* well founded *)\n  unfold bb_order. apply wf_lex_ord. apply wf_clos_trans. apply bsim_order_wf. apply bsim_order_wf.\n  (* transitivity *)\n  (* { unfold bb_order. apply transitive_lex_ord. *)\n  (*   - apply clos_trans_trans. *)\n  (*   - apply (bsim_order_trans S23). }   *)\n  (* reflexivity *)\n  { unfold call_refl, p_reflexive. intros s REFL.\n    specialize (bsim_match_states_refl S12). intros H. unfold call_refl, p_reflexive in H.\n    specialize (H s REFL). destruct H as [i2 MATCH1].\n    specialize (bsim_match_states_refl S23). intros H. unfold call_refl, p_reflexive in H.\n    specialize (H s REFL). destruct H as [i3 MATCH2].\n    exists (i2, i3). 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 S23); eauto.\n    eapply star_safe; eauto. eapply bsim_safe; eauto.\n  intros [s2' [A B]].\n  exploit bsim_E0_star. eapply star_trans. eexact H0. eexact A. auto. eauto. auto.\n  intros [i1' [s1' [C D]]].\n  exploit (bsim_match_final_states S12); 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 S23). eauto. eapply star_safe; eauto. eapply bsim_safe; eauto.\n(* simulation *)\n  exact bb_simulation.\nQed.\n\n\nEnd COMPOSE_INTERNAL_BACKWARD_SIMULATIONS.\n\n\nSection FORWARD_TO_BACKWARD.\n\nVariable p1 p2: program.\nVariable rtl1 rtl2: option (RTLfun+RTLblockfun).\nVariable nc1: asm_codes.\nVariables nc2: asm_codes.\nVariable FS: forward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2.\nHypothesis p1_receptive: receptive (mixed_sem p1 rtl1 nc1).\nHypothesis p2_determinate: determinate (mixed_sem p2 rtl2 nc2).\n\n(** Exploiting forward simulation *)\n\nInductive f2b_transitions: mixed_state -> mixed_state -> Prop :=\n  | f2b_trans_final: forall s1 s2 s1' r,\n      Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' ->\n      final_mixed_state p1 s1' r ->\n      final_mixed_state p2 s2 r ->\n      f2b_transitions s1 s2\n  | f2b_trans_step: forall s1 s2 s1' t s1'' s2' i' i'',\n      Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' ->\n      Step (mixed_sem p1 rtl1 nc1) s1' t s1'' ->\n      SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n      FS i' s1' s2 ->\n      FS i'' s1'' s2' ->\n      f2b_transitions s1 s2.\n\nLemma f2b_progress:\n  forall i s1 s2, FS i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> f2b_transitions s1 s2.\nProof.\n  intros i0; pattern i0. apply well_founded_ind with (R := fsim_order FS).\n  apply fsim_order_wf.\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: SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' \\/ (s2' = s2 /\\ t = E0 /\\ fsim_order FS i' i)).\n    intuition.\n    destruct (star_inv H0); intuition.\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 with (s1':=s1'0); 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 (mixed_sem p1 rtl1 nc1) s1 t s1' -> t <> E0 ->\n  forall i s2, FS i s1 s2 ->\n  exists i', exists s2', SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' /\\ FS 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. omegaContradiction.\nQed.\n\nLemma f2b_determinacy_inv:\n  forall s2 t' s2' t'' s2'',\n  Step (mixed_sem p2 rtl2 nc2) s2 t' s2' -> Step (mixed_sem p2 rtl2 nc2) 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.\nQed.\n\nLemma f2b_determinacy_star:\n  forall s s1, Star (mixed_sem p2 rtl2 nc2) s E0 s1 ->\n  forall t s2 s3,\n  Step (mixed_sem p2 rtl2 nc2) s1 t s2 -> t <> E0 ->\n  Star (mixed_sem p2 rtl2 nc2) s t s3 ->\n  Star (mixed_sem p2 rtl2 nc2) 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\nLemma trans_f2b_order:\n  transitive _ f2b_order.\nProof.\n  unfold transitive. intros x y z HXY HYZ.\n  inv HXY; inv HYZ.\n  - constructor. omega.\n  - constructor.\n  - constructor. omega.\n  - constructor.\nQed.\n\n(** Constructing the backward simulation *)\n\nInductive f2b_match_states: f2b_index -> mixed_state -> mixed_state -> Prop :=\n  | f2b_match_at: forall i s1 s2,\n      FS 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 (mixed_sem p1 rtl1 nc1) s1 t s1' ->  t <> E0 ->\n      Star (mixed_sem p2 rtl2 nc2) s2b E0 s2 ->\n      starN (step (mixed_sem p2 rtl2 nc2)) (globalenv (mixed_sem p2 rtl2 nc2)) n s2 t s2a ->\n      FS 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 (mixed_sem p2 rtl2 nc2)) (globalenv (mixed_sem p2 rtl2 nc2)) (S n) s2 E0 s2a ->\n      FS 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 (mixed_sem p2 rtl2 nc2)) (globalenv (mixed_sem p2 rtl2 nc2)) n s2 E0 s2a ->\n  FS 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 (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n  forall i s1, f2b_match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1',\n    (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) 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 p2_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 p1_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 p1_receptive). apply H1. apply MT. 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 p1_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. omega.\n  econstructor; eauto. eapply star_right; eauto.\n  (* 2.2 L2 make a non-silent transition *)\n  exploit not_silent_length. eapply (sr_traces p1_receptive); eauto. intros [EQ | EQ].\n  congruence.\n  subst. rewrite E0_right in *.\n  (* Use receptiveness to equate the traces *)\n  exploit (sr_receptive p1_receptive). apply H. apply MT. 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 p1_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; omega.\n  eapply f2b_match_after'; eauto.\n  congruence.\nQed.\n\n(** The backward simulation *)\n\nLemma forward_to_backward_simulation: backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2.\nProof.\n  eapply Backward_internal_simulation.\n   (* with (bsiml_order := f2b_order). (bsiml_match_states := f2b_match_states). *)\n  apply wf_f2b_order.\n  (* transitivity *)\n  (* apply trans_f2b_order. *)\n  (* reflexivity *)\n  { unfold call_refl, p_reflexive. intros s REFL.\n    specialize (fsim_match_states_refl FS). intros H. unfold call_refl, p_reflexive in H.\n    specialize (H s REFL). destruct H as [i MATCH].\n    exists (F2BI_after 0). eapply f2b_match_at. 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 p2_determinate); eauto). subst r0.\n  exists s1'; auto.\n  inv H4. exploit (sd_final_nostep p2_determinate); eauto. contradiction.\n  inv H5. congruence. exploit (sd_final_nostep p2_determinate); eauto. contradiction.\n  inv H2. exploit (sd_final_nostep p2_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  exact f2b_simulation_step.\nQed.\n\nEnd FORWARD_TO_BACKWARD.\n\n\n(** * Alernate internal backward definition  *)\n(* Where the order and match_states relation are made parameters *)\n(* This helps writing the external simulation invariant *)\n\nRecord backward_internal_simulation' (p1 p2: program) (rtl1 rtl2:option (RTLfun+RTLblockfun)) (nc1 nc2: asm_codes)\n       (idxt: Type)\n       (order: idxt -> idxt -> Prop)\n       (match_states: idxt -> mixed_state -> mixed_state -> Prop)\n  : Type :=\n  Backward_internal_simulation' {\n    order_wf: well_founded order;\n    (* order_trans: transitive _ order;   *)\n    match_states_refl: call_refl match_states;\n    match_final_states:\n      forall i s1 s2 r,\n      match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> final_mixed_state p2 s2 r ->\n      exists s1', Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ final_mixed_state p1 s1' r;\n    progress:\n      forall i s1 s2,\n      match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n      (exists r, final_mixed_state p2 s2 r) \\/\n      (exists t, exists s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2');\n    simulation:\n      forall s2 t s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n      forall i s1, match_states i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n      exists i', exists s1',\n         (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ order i' i))\n      /\\ match_states i' s1' s2';\n  }.\n\nLemma bsim_simulation'':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 idx (ord:idx->idx->Prop) ms\n    (S: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms),\n  forall i s2 t s2', Step (mixed_sem p2 rtl2 nc2) s2 t s2' ->\n  forall s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  (exists i', exists s1', SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ ms i' s1' s2')\n  \\/ (exists i', ord i' i /\\ t = E0 /\\ ms i' s1 s2').\nProof.\n  intros. exploit simulation; eauto.\n  intros [i' [s1' [A B]]]. intuition.\n  left; exists i'; exists s1'; auto.\n  inv H3.\n  right; exists i'; auto.\n  left; exists i'; exists s1'; split; auto. econstructor; eauto.\nQed.\n\n\n(* Equivalence between the two definition *)\nTheorem backward_eq:\n  forall p1 p2 rtl1 rtl2 nc1 nc2,\n    backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2 ->\n    exists idxt (order:idxt->idxt->Prop) ms, backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 order ms.\nProof.\n  intros p1 p2 rtl1 rtl2 nc1 nc2 X. exists (bsim_index X). exists (bsim_order X). exists (bsim_match_states X).\n  apply Backward_internal_simulation'; destruct X; auto.\nQed.\n\n\nTheorem eq_backward:\n  forall p1 p2 rtl1 rtl2 nc1 nc2,\n  forall idxt (order:idxt->idxt->Prop) ms, backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 order ms ->\n                                 backward_internal_simulation p1 p2 rtl1 rtl2 nc1 nc2.\nProof.\n  intros p1 p2 rtl1 rtl2 nc1 nc2 idxt order ms H.\n  apply Backward_internal_simulation with (bsim_order:=order) (bsim_match_states:=ms);\n    destruct H; auto.\nQed.\n  \n(** * Backward simulation reflexivity  *)\n(* This is used at the very beginning of the JIT proof, to show that there is an internal simulation between the initial program and itself *)\nDefinition refl_type := unit.\nInductive refl_order: unit -> unit -> Prop := .\nInductive refl_match_states: refl_type -> mixed_state -> mixed_state -> Prop :=\n| match_same: forall s, refl_match_states tt s s.\n\nTheorem wf_refl: well_founded refl_order.\nProof.\n  unfold well_founded. intros. destruct a. constructor. intros. inv H.\nQed.\n\nTheorem refl_refl: reflexive refl_match_states.\nProof.\n  unfold reflexive. intros. exists tt. constructor.\nQed.\n\nTheorem trans_refl: transitive _ refl_order.\nProof.\n  unfold transitive. intros. inv H.\nQed.\n\nLemma backward_refl:\n  forall p nc rtl,\n    backward_internal_simulation' p p rtl rtl nc nc refl_order refl_match_states.\nProof.\n  intros p rtl nc. apply Backward_internal_simulation'.\n  - apply wf_refl.\n  (* - apply trans_refl. *)\n  - unfold call_refl, p_reflexive. intros s REFL. exists tt. split; auto.\n  - intros i s1 s2 r H H0 H1. inv H. exists s2. split. apply star_refl. auto.\n  - intros i s1 s2 H H0. inv H. unfold safe in H0. apply H0. apply star_refl.\n  - intros s2 t s2' H i s1 H0 H1. inv H0. exists tt. exists s2'. split.\n    left. apply plus_one. auto. constructor.\nQed.\n\n(* non-explicit version *)\nLemma backward_internal_reflexivity:\n  forall p rtl nc, backward_internal_simulation p p rtl rtl nc nc.\nProof.\n  intros p rtl nc. eapply eq_backward. eapply backward_refl.\nQed.\n\n(** * Exploiting Sequences  *)\n\n(* Exploiting silent stars *)\nLemma bsim_E0_star':\n  forall (p1 p2: program) (rtl1 rtl2:option (RTLfun+RTLblockfun)) (nc1 nc2:asm_codes) idxt (ord:idxt->idxt->Prop) ms\n    (S: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms),\n  forall s2 s2', Star (mixed_sem p2 rtl2 nc2) s2 E0 s2' ->\n  forall i s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1', Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ ms i' s1' s2'.\nProof.\n  intros p1 p2 rtl1 rtl2 nc1 nc2 idxt ord ms S.\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 simulation; eauto. intros [i' [s1' [A B]]].\n  assert (Star (mixed_sem p1 rtl1 nc1) 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\n(* Exploiting silent plus *)\n(* We use the transitivity of the order to make this possible *)\n(* This shows that on a PLUS we can have a simulation diagram without changing orders *)\n(* Lemma bsim_E0_plus': *)\n(*   forall (p1 p2: program) (rtl1 rtl2: option RTLfun) (nc1 nc2: asm_codes) idxt (ord:idxt->idxt->Prop) ms *)\n(*     (S: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms), *)\n(*   forall s2 t s2', SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' -> t = E0 -> *)\n(*   forall i s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> *)\n(*      (exists i', exists s1', SPlus (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ ms i' s1' s2') *)\n(*   \\/ (exists i', ord i' i /\\ ms i' s1 s2'). *)\n(* Proof. *)\n(*   intros p1 p2 rtl1 rtl2 nc1 nc2 idxt ord ms S. *)\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. *)\n(*   intros [[i' [s1' [A B]]] | [i' [A [B C]]]]. *)\n(*   exploit bsim_E0_star'. eauto. apply plus_star with (s1:=s2); eauto. eauto.  *)\n(*   eapply star_safe; eauto. apply plus_star; eauto. *)\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. assert (OT: transitive _ ord) by apply (order_trans S). *)\n(*   unfold transitive in OT. eapply OT; eauto. *)\n(* Qed. *)\n\nLemma star_E0:\n  forall p rtl nc s1 s2,\n    Star (mixed_sem p rtl nc) s1 E0 s2 ->\n    SPlus (mixed_sem p rtl nc) s1 E0 s2 \\/ s1 = s2.\nProof.\n  intros. inv H.\n  right. auto. left. econstructor; eauto.\nQed.\n\n(* Lemma exploit_starstep: *)\n(*   forall (p1 p2: program) (rtl1 rtl2:option RTLfun) (nc1 nc2:asm_codes) idxt (ord:idxt->idxt->Prop) ms *)\n(*     (S: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms), *)\n(*   forall s2 t s2' s2'', Star (mixed_sem p2 rtl2 nc2) s2 E0 s2' -> *)\n(*                    Step (mixed_sem p2 rtl2 nc2) s2' t s2'' -> *)\n(*   forall i s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> *)\n(*           exists i', exists s1', (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ ord i' i) ) /\\ *)\n(*                        ms i' s1' s2''. *)\n(* Proof. *)\n(*   intros p1 p2 rtl1 rtl2 nc1 nc2 idxt ord ms S s2 t s2' s2'' STAR STEP i s1 MATCH SAFE. *)\n(*   apply star_E0 in STAR. destruct STAR as [PLUS | EQ]. *)\n(*   - specialize (bsim_E0_plus' S PLUS eq_refl i MATCH SAFE). *)\n(*     intros [[i' [s1' [PLUSSRC MATCH']]]|[i' [ORD MATCH']]]. *)\n(*     + assert (SAFE': safe (mixed_sem p1 rtl1 nc1) s1'). *)\n(*       { eapply star_safe; eauto. apply plus_star. auto. } *)\n(*       specialize ((simulation S) s2' t s2'' STEP i' s1' MATCH' SAFE'). *)\n(*       intros [i'' [s1'' [[PLUS' | [STAR ORD]] MATCH'']]]. *)\n(*       * exists i''. exists s1''. split; auto. left. eapply plus_trans; eauto. *)\n(*       * exists i''. exists s1''. split; auto. left. eapply plus_star_trans; eauto. *)\n(*     + specialize ((simulation S) s2' t s2'' STEP i' s1 MATCH' SAFE). *)\n(*       intros [i'' [s1'' [[PLUS' | [STAR ORD']] MATCH'']]]. *)\n(*       * exists i''. exists s1''. split; auto. *)\n(*       * exists i''. exists s1''. split; auto. right. split; auto. *)\n(*         assert (TRANS: transitive _ ord) by apply (order_trans S). unfold transitive in TRANS. *)\n(*         eapply TRANS; eauto. *)\n(*   - subst. *)\n(*     specialize ((simulation S) s2' t s2'' STEP i s1 MATCH SAFE). *)\n(*     intros [i' [s1' [[PLUS | [STAR ORD]] MATCH']]]. *)\n(*     + exists i'. exists s1'. split; auto. *)\n(*     + exists i'. exists s1'. split; auto. *)\n(* Qed. *)\n\n(** * Composing simulations explicitely  *)\nLemma bsim_E0_star'':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 i (ord:i->i->Prop) ms\n    (SIM: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms),\n  forall s2 s2', Star (mixed_sem p2 rtl2 nc2) s2 E0 s2' ->\n  forall i s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1', Star (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ ms i' s1' s2'.\nProof.\n  intros p1 p2 rtl1 rtl2 nc1 nc2 idx ord ms SIM.\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 simulation; eauto. intros [i' [s1' [A B]]].\n  assert (Star (mixed_sem p1 rtl1 nc1) 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_E0_plus'':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 i (ord:i->i->Prop) ms\n    (SIM: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms),\n  forall s2 t s2', SPlus (mixed_sem p2 rtl2 nc2) s2 t s2' -> t = E0 ->\n  forall i s1, ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n     (exists i', exists s1', SPlus (mixed_sem p1 rtl1 nc1) s1 E0 s1' /\\ ms i' s1' s2')\n  \\/ (exists i', clos_trans _ (ord) i' i /\\ ms i' s1 s2').\nProof.\n  intros p1 p2 rtl1 rtl2 nc1 nc2 idx ord ms SIM.\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 SIM. apply plus_star with (s1:=s2); eauto. eauto.\n  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\n\nSection COMPOSE_INTERNAL_BACKWARD_SIMULATIONS_EXPLICIT.\n\nVariable p1 p2 p3: program.\nVariable rtl1 rtl2 rtl3:option (RTLfun+RTLblockfun).\nVariable nc1: asm_codes.\nVariable nc2: asm_codes.\nVariable nc3: asm_codes.\nHypothesis p3_single_events: single_events (mixed_sem p3 rtl3 nc3).\nVariable i12: Type.\nVariable i23: Type.\nVariable ord12: i12 -> i12 -> Prop.\nVariable ord23: i23 -> i23 -> Prop.\nVariable ms12: i12 -> mixed_state -> mixed_state -> Prop.\nVariable ms23: i23 -> mixed_state -> mixed_state -> Prop.\nVariable S12: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord12 ms12.\nVariable S23: backward_internal_simulation' p2 p3 rtl2 rtl3 nc2 nc3 ord23 ms23.\n\n\nLet bb_index: Type := (i12 * i23)%type.\n\nLet bb_order: bb_index -> bb_index -> Prop :=\n  lex_ord (clos_trans _ ord12) (ord23).\n\nInductive bb_ms: bb_index -> mixed_state -> mixed_state -> Prop :=\n  | bb_later: forall i1 i2 s1 s3 s2x s2y,\n      ms12 i1 s1 s2x -> Star (mixed_sem p2 rtl2 nc2) s2x E0 s2y -> ms23 i2 s2y s3 ->\n      bb_ms (i1, i2) s1 s3.\n\nLemma bb_match_at':\n  forall i1 i2 s1 s2 s3,\n  ms12 i1 s1 s2 -> ms23 i2 s2 s3 ->\n  bb_ms (i1, i2) s1 s3.\nProof.\n  intros. econstructor; eauto. apply star_refl.\nQed.\n\nLemma bsim_safe':\n  forall p1 p2 rtl1 rtl2 nc1 nc2 i (ord:i->i->Prop) ms\n    (SIM: backward_internal_simulation' p1 p2 rtl1 rtl2 nc1 nc2 ord ms),\n  forall i s1 s2,\n  ms i s1 s2 -> safe (mixed_sem p1 rtl1 nc1) s1 -> safe (mixed_sem p2 rtl2 nc2) s2.\nProof.\n  intros; red; intros.\n  exploit bsim_E0_star''; eauto. intros [i' [s1' [A B]]].\n  eapply progress; eauto. eapply star_safe; eauto.\nQed.\n\n\nLemma bb_simulation_base':\n  forall s3 t s3', Step (mixed_sem p3 rtl3 nc3) s3 t s3' ->\n  forall i1 s1 i2 s2, ms12 i1 s1 s2 -> ms23 i2 s2 s3 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1',\n    (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ bb_order i' (i1, i2)))\n    /\\ bb_ms 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 p3_single_events; eauto.\n    destruct t; auto. destruct t; auto. simpl. intros. omegaContradiction.\n  destruct EITHER.\n  (* 1.1 these are silent transitions *)\n  subst t. exploit bsim_E0_plus''. apply S12. eauto. auto. eauto. auto.\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''. apply S12. eexact P. eauto. auto. intros [i1' [s1x [X Y]]].\n  exploit bsim_simulation''. apply 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_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 (mixed_sem p3 rtl3 nc3) s3 t s3' ->\n  forall i s1, bb_ms i s1 s3 -> safe (mixed_sem p1 rtl1 nc1) s1 ->\n  exists i', exists s1',\n    (SPlus (mixed_sem p1 rtl1 nc1) s1 t s1' \\/ (Star (mixed_sem p1 rtl1 nc1) s1 t s1' /\\ bb_order i' i))\n    /\\ bb_ms 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''. apply S12. eauto. auto. eauto. auto.\n  intros [[i1' [s1' [A B]]] | [i1' [A B]]].\n  (* 2.1 one or several silent transitions *)\n  exploit bb_simulation_base'. apply H.  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'. apply H.  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\n\nTheorem compose_backward_simulation':\n  backward_internal_simulation' p1 p3 rtl1 rtl3 nc1 nc3 (bb_order) (bb_ms).\nProof.\n  apply Backward_internal_simulation'. \n(* well founded *)\n  unfold bb_order. apply wf_lex_ord. apply wf_clos_trans. apply (order_wf S12). apply (order_wf S23).\n  (* transitivity *)\n  (* { unfold bb_order. apply transitive_lex_ord. *)\n  (*   - apply clos_trans_trans. *)\n  (*   - apply (order_trans S23). }   *)\n  (* reflexivity *)\n  { unfold call_refl, p_reflexive. intros s REFL.\n    specialize (match_states_refl S12). intros H. unfold call_refl, p_reflexive in H.\n    specialize (H s REFL). destruct H as [i2 MATCH1].\n    specialize (match_states_refl S23). intros H. unfold call_refl, p_reflexive in H.\n    specialize (H s REFL). destruct H as [i3 MATCH2].\n    exists (i2, i3). eapply bb_match_at'; eauto. }\n(* match final states *)\n  intros i s1 s3 r MS SAFE FIN. inv MS.\n  exploit (match_final_states S23 ); eauto.\n    eapply star_safe; eauto. eapply bsim_safe'; eauto. \n  intros [s2' [A B]].\n  exploit bsim_E0_star''. apply S12. eapply star_trans. eexact H0. eexact A. auto. eauto. auto.\n  intros [i1' [s1' [C D]]].\n  exploit (match_final_states S12); 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 (progress S23). eauto. eapply star_safe; eauto. eapply bsim_safe'; eauto.\n  (* simulation *)\n  exact bb_simulation'.\nQed.\n\nEnd COMPOSE_INTERNAL_BACKWARD_SIMULATIONS_EXPLICIT.\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/internal_simulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.31069437683198775, "lm_q1q2_score": 0.17466507761230046}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat seq eqtype fintype.\nFrom extructures Require Import ord fset fmap fperm.\nFrom CoqUtils Require Import word nominal.\n\nRequire Import lib.utils lib.fmap_utils common.types symbolic.symbolic symbolic.exec.\nRequire Import memory_safety.property memory_safety.symbolic memory_safety.abstract.\nRequire Import memory_safety.refinementAS.\nRequire Import memory_safety.classes memory_safety.executable memory_safety.propertyA.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection MemorySafety.\n\nLocal Open Scope fset_scope.\n\nImport Abstract.\n\nVariable mt : machine_types.\nVariable ops : machine_ops mt.\nVariable sr : syscall_regs mt.\nVariable addrs : memory_syscall_addrs mt.\n\nLocal Notation sstate := (@Symbolic.state mt (Sym.sym_memory_safety mt)).\nLocal Notation sstepf :=\n  (@stepf _ ops (Sym.sym_memory_safety mt) (@Sym.memsafe_syscalls _ ops _ addrs)).\nLocal Notation astate := (Abstract.state mt).\nLocal Notation astepf := (AbstractE.step ops _ addrs).\n\nLemma noninterference sst1 sst1' sst2 sst2' mi1 mi2 ast m1 m2 pm n :\n  stepn sstepf n sst1 = Some sst1' ->\n  stepn sstepf n sst2 = Some sst2' ->\n  refine_state mi1 (add_mem m1 ast) sst1 ->\n  refine_state mi2 (add_mem m2 (rename pm ast)) sst2 ->\n  fdisjoint (names ast) (domm m1) ->\n  fdisjoint (names (rename pm ast)) (domm m2) ->\n  exists ast' pm' mi1' mi2',\n    [/\\ refine_state mi1' (add_mem m1 ast') sst1',\n        refine_state mi2' (add_mem m2 (rename pm' ast')) sst2',\n        fdisjoint (names ast') (domm m1) &\n        fdisjoint (names (rename pm' ast')) (domm m2) ].\nProof.\nmove=> ex1 ex2 ref1 ref2 dis1 dis2.\nhave [mi1' [ast1' [ex1' ref1']]] := refinement ref1 ex1.\nhave [mi2' [ast2' [ex2' ref2']]] := refinement ref2 ex2.\nhave := noninterference ops sr addrs n dis1 dis2.\nrewrite ex1' ex2'.\ncase=> pm' [ast' [e1 dis1' e2 dis2']].\nexists ast', pm', mi1', mi2'; split=> //.\n  by rewrite -e1.\nby rewrite -e2.\nQed.\n\nEnd MemorySafety.\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/memory_safety/propertyS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.17464332497935178}}
{"text": "Require Import Coq.Strings.String Coq.Strings.HexString.\nRequire Import Coq.Init.Byte coqutil.Byte.\nRequire Import Coq.Lists.List.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Z_keyed_SortedListMap.\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nImport ListNotations.\n\n(* USAGE:\nDefinition mysymbols := Symbols.symbols myfinfo.\n./etc/bytedump.py MyRepo.MyFile.mysymbols > /tmp/l.s\nriscv64-elf-gcc -T mylinkerscript.lds -g -nostdlib /tmp/l.s -o /tmp/l\n*)\n\nDefinition LF : string := String (Coq.Strings.Ascii.Ascii false true false true false false false false) \"\".\n\nDefinition symbols_string (finfo : list (string * BinInt.Z)) : string :=\n  \".globl _start\" ++ LF ++\n  \"_start:\" ++ LF ++\n  String.concat \"\" (List.map (fun '(a, s) =>\n    \".org \" ++ HexString.of_Z a ++ LF ++\n    \".local \" ++ s ++ LF ++\n    s ++ \":\" ++ LF)%string\n    (SortedList.value (List.fold_right (fun '(k, v) m => map.put m v k) map.empty finfo))).\n\nDefinition symbols (finfo : list (string * BinInt.Z)) : list byte :=\n  String.list_byte_of_string (symbols_string finfo).\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/Symbols.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17460491340411385}}
{"text": "Require Import UNIVERSE.\n(* Require Import Events. *)\n(* Require Import Values. *)\n(* Require Import AST. *)\n(* Require Import Memory. *)\n(* Require Import Globalenvs. *)\n(* Require Import Smallstep. *)\nRequire Import CoqlibC.\n(* Require Import Skeleton. *)\n(* Require Import Integers. *)\n(* Require Import ASTC. *)\n(* Require Import Maps. *)\n\nRequire Import ModSem.\n\nSet Implicit Arguments.\n\n\n\nModule Mod.\n  (* TRANSLATION UNIT *)\n\n  (* I intentionally left \"datatype\" in to_skel and to_moduleenv. *)\n  (* 1) defining translation becomes more lightweight. *)\n  (* Consider RTL -> RTL. to_skel/to_moduleenv remains the same *)\n  (* 2) This definition will give an error when datatype is changed. *)\n  Record t: Type := mk {\n    datatype: Type;\n    get_sk: datatype -> Sk.t;\n    get_modsem: SkEnv.t -> datatype -> ModSem.t;\n    data: datatype;\n    get_modsem_skenv_spec: forall skenv,\n        <<PROJECTED: SkEnv.project skenv data.(get_sk) = data.(get_modsem skenv).(ModSem.skenv)>>;\n    get_modsem_skenv_link_spec: forall skenv_link,\n        <<EQ: data.(get_modsem skenv_link).(ModSem.skenv_link) = skenv_link>>\n  }.\n\n  Lemma get_modsem_projected_sk\n        (md: t) skenv\n        (INCL: SkEnv.includes skenv (get_sk md (data md))):\n      <<PROJECTED: SkEnv.project_spec skenv ((md.(get_sk) md.(data)))\n                                      ((md.(get_modsem) skenv) md.(data)).(ModSem.skenv)>>.\n  Proof.\n    erewrite <- get_modsem_skenv_spec. eapply SkEnv.project_impl_spec; et.\n  Qed.\n\n  Definition sk (md: t): Sk.t := md.(get_sk) md.(data).\n\n  Definition modsem (md: t) (skenv: SkEnv.t): ModSem.t := md.(get_modsem) skenv md.(data).\n\n  (* Module Atomic. *)\n  (* Section Atomic. *)\n\n  (*   Variable m: t. *)\n\n  (*   Program Definition trans: t := *)\n  (*     mk m.(get_sk) (fun ske dat => ModSem.Atomic.trans (m.(get_modsem) ske dat)) m.(data) _ _. *)\n  (*   Next Obligation. exploit get_modsem_skenv_spec; eauto. Qed. *)\n  (*   Next Obligation. exploit get_modsem_skenv_link_spec; eauto. Qed. *)\n\n  (* End Atomic. *)\n  (* End Atomic. *)\n\nEnd Mod.\n\nCoercion Mod.sk: Mod.t >-> Sk.t.\nCoercion Mod.modsem: Mod.t >-> Funclass.\n\nHint Unfold Mod.sk Mod.modsem.\n\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/sem/Mod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.174319305139643}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import CtxtSwitch.Spec.\nRequire Import RunAux.Spec.\nRequire Import RunComplete.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance RunComplete_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance RunComplete_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance complete_mmio_emulation_inv: PreservesInvariants complete_mmio_emulation_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance complete_hvc_exit_inv: PreservesInvariants complete_hvc_exit_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_to_idx_inv: PreservesInvariants addr_to_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_index_inv: PreservesInvariants set_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_inc_inv: PreservesInvariants granule_refcount_inc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_rec_run_inv: PreservesInvariants ns_buffer_read_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_inv: PreservesInvariants measurement_extend_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance barrier_inv: PreservesInvariants barrier_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_release_inv: PreservesInvariants atomic_granule_put_release_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance configure_realm_stage2_inv: PreservesInvariants configure_realm_stage2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_g_rtt_inv: PreservesInvariants get_rd_g_rtt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_dec_inv: PreservesInvariants granule_refcount_dec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_header_inv: PreservesInvariants measurement_extend_data_header_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_lock_inv: PreservesInvariants granule_lock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_inv: PreservesInvariants atomic_granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance run_realm_inv: PreservesInvariants run_realm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_g_rtt_refcount_inv: PreservesInvariants get_g_rtt_refcount_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_hcr_el2_inv: PreservesInvariants restore_hcr_el2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance reset_disposed_info_inv: PreservesInvariants reset_disposed_info_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_runnable_inv: PreservesInvariants get_rec_runnable_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance save_ns_state_inv: PreservesInvariants save_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance null_ptr_inv: PreservesInvariants null_ptr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance reset_last_run_info_inv: PreservesInvariants reset_last_run_info_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_g_rtt_rd_inv: PreservesInvariants set_g_rtt_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_g_llt_inv: PreservesInvariants set_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_realm_state_inv: PreservesInvariants restore_realm_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_unused_granule_inv: PreservesInvariants find_lock_unused_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_to_phys_inv: PreservesInvariants entry_to_phys_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance stage2_tlbi_ipa_inv: PreservesInvariants stage2_tlbi_ipa_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_get_inv: PreservesInvariants atomic_granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance link_table_inv: PreservesInvariants link_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_is_level_aligned_inv: PreservesInvariants addr_is_level_aligned_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition RunComplete_fresh : compatlayer (cdata RData) :=\n      _complete_mmio_emulation \u21a6 gensem complete_mmio_emulation_spec\n        \u2295 _complete_hvc_exit \u21a6 gensem complete_hvc_exit_spec\n      .\n\n    Definition RunComplete_passthrough : compatlayer (cdata RData) :=\n      _addr_to_idx \u21a6 gensem addr_to_idx_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _set_wi_index \u21a6 gensem set_wi_index_spec\n        \u2295 _granule_refcount_inc \u21a6 gensem granule_refcount_inc_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _ns_buffer_read_rec_run \u21a6 gensem ns_buffer_read_rec_run_spec\n        \u2295 _granule_put \u21a6 gensem granule_put_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _measurement_extend_data \u21a6 gensem measurement_extend_data_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _entry_is_table \u21a6 gensem entry_is_table_spec\n        \u2295 _barrier \u21a6 gensem barrier_spec\n        \u2295 _atomic_granule_put_release \u21a6 gensem atomic_granule_put_release_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _configure_realm_stage2 \u21a6 gensem configure_realm_stage2_spec\n        \u2295 _get_rd_g_rtt \u21a6 gensem get_rd_g_rtt_spec\n        \u2295 _granule_memzero \u21a6 gensem granule_memzero_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _granule_refcount_dec \u21a6 gensem granule_refcount_dec_spec\n        \u2295 _measurement_extend_data_header \u21a6 gensem measurement_extend_data_header_spec\n        \u2295 _granule_lock \u21a6 gensem granule_lock_spec\n        \u2295 _ns_buffer_unmap \u21a6 gensem ns_buffer_unmap_spec\n        \u2295 _granule_memzero_mapped \u21a6 gensem granule_memzero_mapped_spec\n        \u2295 _atomic_granule_put \u21a6 gensem atomic_granule_put_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _run_realm \u21a6 gensem run_realm_spec\n        \u2295 _get_g_rtt_refcount \u21a6 gensem get_g_rtt_refcount_spec\n        \u2295 _restore_hcr_el2 \u21a6 gensem restore_hcr_el2_spec\n        \u2295 _reset_disposed_info \u21a6 gensem reset_disposed_info_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _set_mapping \u21a6 gensem set_mapping_spec\n        \u2295 _get_rec_runnable \u21a6 gensem get_rec_runnable_spec\n        \u2295 _ns_granule_map \u21a6 gensem ns_granule_map_spec\n        \u2295 _granule_get \u21a6 gensem granule_get_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _save_ns_state \u21a6 gensem save_ns_state_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _null_ptr \u21a6 gensem null_ptr_spec\n        \u2295 _get_wi_g_llt \u21a6 gensem get_wi_g_llt_spec\n        \u2295 _reset_last_run_info \u21a6 gensem reset_last_run_info_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _set_g_rtt_rd \u21a6 gensem set_g_rtt_rd_spec\n        \u2295 _pgte_read \u21a6 gensem pgte_read_spec\n        \u2295 _ns_buffer_read_data \u21a6 gensem ns_buffer_read_data_spec\n        \u2295 _pgte_write \u21a6 gensem pgte_write_spec\n        \u2295 _set_wi_g_llt \u21a6 gensem set_wi_g_llt_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _restore_realm_state \u21a6 gensem restore_realm_state_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _find_lock_unused_granule \u21a6 gensem find_lock_unused_granule_spec\n        \u2295 _entry_to_phys \u21a6 gensem entry_to_phys_spec\n        \u2295 _stage2_tlbi_ipa \u21a6 gensem stage2_tlbi_ipa_spec\n        \u2295 _atomic_granule_get \u21a6 gensem atomic_granule_get_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _get_wi_index \u21a6 gensem get_wi_index_spec\n        \u2295 _link_table \u21a6 gensem link_table_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n        \u2295 _addr_is_level_aligned \u21a6 gensem addr_is_level_aligned_spec\n      .\n\n    Definition RunComplete := RunComplete_fresh \u2295 RunComplete_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17431929826210546}}
{"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 reg mem pagetable mailbox base_extra.\nFrom HypVeri.lang Require Import lang_extra reg_extra.\n\nSection br.\n\nContext `{hypparams: HypervisorParameters}.\nContext `{vmG: !gen_VMG \u03a3}.\n  \nLemma br {E i w1 w2 q s p} ai  ra :\n  decode_instruction w1 = Some(Br ra) ->\n  tpa ai \u2208 s ->\n  tpa ai \u2260 p ->\n    {SS{{  \u25b7 (PC @@ i ->r ai)\n           \u2217 \u25b7 (ai ->a w1)\n           \u2217 \u25b7 (ra @@ i ->r w2)\n           \u2217 \u25b7 (i -@{q}A> s)\n           \u2217 \u25b7 (TX@ i := p) }}} ExecI @ i; E\n    {{{ RET (false, ExecI);  (PC @@ i ->r  w2)\n                    \u2217 (ai ->a w1 \u2217 ra @@ i ->r w2)\n                    \u2217 (i -@{q}A> s)\n                    \u2217 (TX@ i := p)}}}.\nProof.\n  iIntros (Hdecode Hin Hne \u03d5) \"( >Hpc & >Hapc & >Hra & >Hacc & >HTX) H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  iDestruct \"H\u03c3\" as \"(#Hneq & Hmem & Hreg & Hmb & Hrx & Hown & Haccess & Hrest)\".\n  pose proof (decode_instruction_valid w1 (Br ra) Hdecode) as Hvalidinstr.\n  inversion Hvalidinstr as [ | | | | | | | | | |src Hvalidra |] .\n  subst src .\n  inversion Hvalidra as [ HneqPCa HneqNZa ].\n  (* valid regs *)\n  iDestruct ((gen_reg_valid2 i PC ai ra w2 Hcur) with \"Hreg Hpc Hra\") as \"[%HPC %Hra]\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"Haccess Hacc\") as %Hacc;first set_solver + Hin.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai w1  with \"Hmem Hapc\") as %Hmem.\n  iDestruct (mb_valid_tx i p with \"Hmb HTX\") as %Htx.\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i (Br ra) ai w1);eauto.\n    by rewrite Htx.\n  - (* step *)\n    iModIntro.\n    iIntros (m2 \u03c32) \"[%P PAuth] %HstepP\".\n    apply (step_ExecI_normal i (Br ra) ai w1 ) in HstepP;eauto.\n    remember (exec (Br ra) \u03c31) as c2 eqn:Heqc2.\n    rewrite /exec  /br Hra /= /update_incr_PC /update_reg in Heqc2;eauto.\n    destruct ra. contradiction. contradiction.\n    destruct HstepP;subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    all: eauto.\n    iFrame.\n    (* updated part *)\n    iDestruct ((gen_reg_update1_global PC i ai w2) with \"Hreg Hpc\") as \">[Hreg Hpc]\";eauto.\n    iModIntro.\n    rewrite /update_reg /=.\n    rewrite ->u_upd_reg_regs.\n    rewrite Hcur.\n    iFrame \"Hreg\".\n    iSplitL \"PAuth\".\n    by iExists P.\n    rewrite /just_scheduled_vms.\n    rewrite /just_scheduled.\n    assert (filter\n              (\u03bb id : vmid,\n                      base.negb (scheduled \u03c31 id) && scheduled (update_reg_global \u03c31 i PC w2) id = true)\n              (seq 0 n) = []) as ->.\n    {\n      rewrite /scheduled /machine.scheduler //= /scheduler Hcur.\n      rewrite p_upd_reg_current_vm.\n      rewrite Hcur.\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    iSimpl.\n    iFrame \"Hneq\".\n    iSplitL \"\";first done.\n    assert ((scheduled (update_reg_global \u03c31 i PC w2) i) = true) as ->.\n    rewrite /scheduled.\n    simpl.\n    rewrite /scheduler.\n    rewrite p_upd_reg_current_vm.\n    rewrite Hcur.\n    rewrite bool_decide_eq_true.\n    reflexivity.\n    simpl.\n    iApply (\"H\u03d5\" with \"[Hpc Hapc Hacc Hra HTX]\").\n    iFrame.\n    by rewrite Htx.\nQed.\nEnd br.\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/br.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.17422329463762665}}
{"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 Spec.\n\n  Definition table_destroy2_spec (g_rd: Pointer) (map_addr: Z64) (rtt_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level, rtt_addr with\n    | VZ64 map_addr, VZ64 level, VZ64 rtt_addr =>\n      rely is_int64 map_addr; rely is_int64 rtt_addr; rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      rely is_int64 idx0; rely is_int64 idx1; rely is_int64 idx2; rely is_int64 idx3;\n      let rtt_gidx := __addr_to_gidx rtt_addr in\n      rely is_gidx rtt_gidx;\n      rely (peq (base g_rd) ginfo_loc);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RTT2 = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx;\n      when adt == query_oracle adt;\n      (* hold root lock *)\n      rely is_gidx root_gidx;\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n      rely (gtype groot =? GRANULE_STATE_TABLE);\n      if level =? 1 then\n        (* walk until root *)\n        let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n        let adt :=  adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n        destroy_table root_gidx idx0 rtt_addr rtt_gidx 1 map_addr adt\n      else\n        (* walk deeper root *)\n        rely (level >? 1);\n        let entry0 := (g_data (gnorm groot)) @ idx0 in\n          rely is_int64 entry0;\n          let phys0 := __entry_to_phys entry0 3 in\n          let lv1_gidx := __addr_to_gidx phys0 in\n          rely is_int64 phys0;\n          if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n            (* level 1 valid, hold level 1 lock *)\n            let glv1 := (gs (share adt)) @ lv1_gidx in\n            rely prop_dec (glock glv1 = None);\n            rely (tbl_level (gaux glv1) =? 1);\n            if level =? 2 then\n              (* walk until level 1 *)\n              let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n              let adt :=  adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n              destroy_table lv1_gidx idx1 rtt_addr rtt_gidx 2 map_addr adt\n            else\n              (* walk deeper level 1 *)\n              rely (level >? 2);\n              rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n              rely (gtype glv1 =? GRANULE_STATE_TABLE);\n              let entry1 := (g_data (gnorm glv1)) @ idx1 in\n              rely is_int64 entry1;\n              let phys1 := __entry_to_phys entry1 3 in\n              let lv2_gidx := __addr_to_gidx phys1 in\n              rely is_int64 phys1;\n              if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n                (* level 2 valid, hold level 2 lock *)\n                let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n                let glv2 := (gs (share adt)) @ lv2_gidx in\n                rely (tbl_level (gaux glv2) =? 2);\n                rely prop_dec (glock glv2 = None);\n                if level =? 3 then\n                  (* walk until level 2 *)\n                  let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n                  destroy_table lv2_gidx idx2 rtt_addr rtt_gidx 3 map_addr adt\n                else None\n              else\n                (* level 2 invalid *)\n                rely is_int lv2_gidx;\n                Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n          else\n            (* level 1 invalid *)\n            rely is_int lv1_gidx;\n            Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef2/Specs/table_destroy2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17416210820255318}}
{"text": "Monomorphic Definition U1 := Type.\nMonomorphic Definition U2 := Type.\n\nSet Printing Universes.\nDefinition foo : True.\nlet t1 := type of U1 in\nlet t2 := type of U2 in\nidtac t1 t2;\npose (t1 : t2). exact I. \nDefined.\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_074.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.174162105897564}}
{"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 JaSyntax.\nRequire Import JaProgram.\nRequire Import JaSubtype.\nRequire Import JaProgramWf.\nRequire Import Jafun.\nRequire Import JaTactics.\nRequire Import JaUnique.\nOpen Scope list_scope.\nOpen Scope nat_scope.\n\nFrom Hammer Require Import Reconstr.\n\n\n\nModule VarName <: Name.\n  Definition name := JFVal.\n  Definition name_dec := JFVal_dec.\nEnd VarName.\n\nModule VarInEnv <: Declaration.\n  Include VarName.\n  Definition decl := (JFVal * JFACId)%type.\n  Definition name_of_decl : decl -> name := fst.\nEnd VarInEnv.\n\nModule Env := VarInEnv <+ ListUniq.\n\n\n\nDefinition JFEnv := Env.t.\n\nDefinition JFExEnv := list JFACId.\n\nSection EnvsInProgram.\n\n  Variable P : JFProgram.\n  Variable cdecl: JFClassDeclaration.\n  Variable md : JFMethodDeclaration.\n    \n(**\n   The operation of \u228e as defined in Section {sec:type-system}.\n   TODO: definicja zgodna z papierem, ale w papierze wyra\u017cenie poprawne,\n         ale \u017ale przedstawiaj\u0105ce intencje.\n*)\nFixpoint sumPlus (exs:JFExEnv) (ext:JFACId) :=\n  match ext with\n  | (C, cmod) =>\n    match exs with\n    | [] => [ext]\n    | (D, dmod) :: tl =>\n      if subtype_bool P D C\n      then sumPlus tl ext\n      else (D, dmod) :: (sumPlus tl ext)\n    end\n  end.\n\n\nFixpoint sumPlus' (exs:JFExEnv) (ext:JFACId) :=\n  match exs with\n  | [] => [ext]\n  | ext' :: tl =>\n    if JFACId_dec ext ext'\n    then ext :: tl\n    else ext' :: (sumPlus tl ext)\n  end.\n\nFixpoint sumPlusCtx (exs:JFExEnv) (Ctx:JFContext) :=\n  match Ctx with\n  | [] => exs\n  | cnode :: Ctx' => match cnode with\n                     | JFCtxLet cn x _ E2 => sumPlusCtx exs Ctx'\n                     | JFCtxTry _ mu cn x E2 => sumPlus (sumPlusCtx exs Ctx') (JFClass cn, mu)\n                     end\n  end.\n\nLemma sumPlusCtxLet:\n  forall Ctx Xi cn x E,\n    sumPlusCtx Xi (Ctx ++ [JFCtxLet cn x __ E]) = sumPlusCtx Xi Ctx.\nProof.\n  induction Ctx.\n  * intros.\n    simpl.\n    auto.\n  * intros.\n    destruct a.\n    ** simpl.\n       eauto.\n    ** simpl.\n       rewrite IHCtx.\n       eauto.\nQed.\n\nLemma sumPlusCtxTry:\n  forall Ctx Xi mu cn x E,\n    sumPlusCtx Xi (Ctx ++ [JFCtxTry __ mu cn x E]) = sumPlusCtx (sumPlus Xi (JFClass cn, mu)) Ctx.\nProof.\n  induction Ctx.\n  * intros.\n    simpl.\n    auto.\n  * intros.\n    simpl.\n    destruct a;eauto 2.\n    rewrite (IHCtx Xi);eauto 2.\nQed.\n    \n(**\n   The operation of \u2295 as defined in Appendix {sec:metatheory}.\n*)\nFixpoint oPlus (env:JFEnv) (l:Loc) (acid:JFACId) {struct env} :=\n  match l with\n  | null => env\n  | JFLoc _ =>\n    match env with\n    | [] => [((JFVLoc l), acid)]\n    | (v, acid') :: tl => if JFVal_dec v (JFVLoc l)\n                        then\n                          (v, infACId P acid acid') :: tl\n                        else\n                          (v, acid') :: (oPlus tl l acid)\n    end\n  end.\n\n\nLemma oplus_decompose_eq:\n  forall l acid1 acid2 Gamma,\n    l <> null ->\n    oPlus ((JFVLoc l, acid1) :: Gamma) l acid2 = (JFVLoc l, infACId P acid2 acid1) :: Gamma.\nProof.\n  intros.\n  destruct l; try contradiction.\n  unfold oPlus.\n  destruct (JFVal_dec (JFVLoc (JFLoc n)) (JFVLoc (JFLoc n)));try contradiction.\n  trivial.\nQed.\n\nLemma oPlus_neq:\n  forall l l' a a' Gamma,\n    JFVLoc l <> l' ->\n    oPlus ((l', a') :: Gamma) l a =\n    (l', a') :: (oPlus Gamma l a).\nProof.\n  destruct Gamma.\n  + intros.\n    destruct l.\n    ++ simpl. trivial.\n    ++ destruct l'.\n       +++ unfold oPlus.\n           destruct (JFVal_dec (JFVLoc l) (JFVLoc (JFLoc n))); try congruence.\n       +++ unfold oPlus.\n           destruct (JFVal_dec (JFSyn x) (JFVLoc (JFLoc n))); try congruence.\n  + intros.\n    destruct l.\n    ++ simpl. trivial.\n    ++ destruct l'.\n       +++ unfold oPlus.\n           destruct (JFVal_dec (JFVLoc l) (JFVLoc (JFLoc n))); try congruence.\n       +++ unfold oPlus.\n           destruct  (JFVal_dec (JFSyn x) (JFVLoc (JFLoc n))); try congruence.\nQed.\n\nLemma In_oPlus_Gamma:\n  forall Gamma v C mu D nu,\n    Env.names_unique Gamma ->\n    In (JFVLoc v, (C, mu)) (oPlus Gamma v (D, nu)) ->\n    exists mu', In (JFVLoc v, (C,mu')) Gamma \\/\n                C = D \\/ C = JFBotClass.\nProof.\n  induction Gamma.\n  + intros.\n    simpl in H0.\n    destruct v.\n    ++ inversion H0.\n    ++ simpl in H0.\n       destruct H0;try contradiction.\n       injection H0;intros;subst.\n       eauto.\n  + intros.\n    simpl in H0.\n    destruct v.\n    ++ eauto.\n    ++ destruct a.\n       destruct (JFVal_dec j (JFVLoc (JFLoc n))).\n       +++ subst.\n           destruct j0.\n           eapply Env.names_unique_zero in H;simpl;trivial.\n           pose (infClass_trichotomy P D j) as Tricho.\n           destruct Tricho as [Tricho|Tricho] ;try destruct Tricho as [Tricho|Tricho].\n           ++++ simpl in H0.\n                destruct H0;eauto.\n                injection H0;intros.\n                eexists. right;left.\n                congruence.\n           ++++ simpl in H0.\n                destruct H0;eauto.\n                injection H0;intros.\n                exists j0;left;left.\n                rewrite <- H2.\n                rewrite <- Tricho at 1.\n                auto.\n           ++++ simpl in H0.\n                destruct H0;eauto.\n                injection H0;intros.\n                eexists;right;right.\n                rewrite <- H2.\n                rewrite Tricho.\n                auto.\n       +++ simpl in H0.\n           destruct H0;try congruence.\n           eapply IHGamma in H0;eauto.\n           destruct H0.\n           exists x.\n           simpl.\n           destruct H0;eauto.\n           Unshelve. auto. auto. auto.\nQed.           \n       \nLemma in_oplus_eq:\n  forall l acid1 Gamma acid2 Cid Cn cdecl mid,\n    names_unique P ->\n    subtype_well_founded P ->\n    Cid = JFClass Cn ->\n    find_class P Cn = Some cdecl ->\n    Env.names_unique Gamma ->\n    l <> null ->\n    In (JFVLoc l, acid1) (oPlus Gamma l acid2) ->\n    leqIsLS P Cid mid acid1 acid2.\nProof.\n  induction Gamma.\n  + intros * ? ? ? ? ? ? HIn.\n    simpl in HIn.\n    destruct l.\n    ++ eapply in_nil in HIn; contradiction.\n    ++ apply in_inv in HIn.\n       destruct HIn as [ [= ->] | HIn].\n       +++ eauto.\n       +++ sauto.\n  + intros * ? ? ? ? Heu ? HIn.\n    destruct a as (x, Acid).\n    destruct (JFVal_dec x (JFVLoc l)).\n    ++ subst.\n       rewrite oplus_decompose_eq in HIn;eauto 2.\n       simpl in HIn.\n       destruct HIn as [ [=] | HIn]; eauto 2.\n       +++ eapply infACId_leqIsLS_L; eauto.\n       +++ eapply Env.names_unique_zero in Heu; eauto 1.\n           simpl in Heu.\n           eapply Env.name_noocc_In_decl_neq in Heu; eauto 1.\n           simpl in Heu.\n           contradiction.\n    ++ rewrite oPlus_neq in HIn;eauto 1.\n       simpl in HIn.\n       destruct HIn as [ [=] | HIn]; try congruence.\n       eapply IHGamma in HIn; eauto 1.\nQed.\n\nLemma in_oplus_neq:\n  forall Gamma l l' acid1 acid2,\n    l <> l' ->\n    In (JFVLoc l, acid1) (oPlus Gamma l' acid2) ->\n    In (JFVLoc l, acid1) Gamma.\nProof.\n  induction Gamma.\n  + intros.\n    simpl in H0.\n    destruct l'.\n    ++ inversion H0.\n    ++ simpl in H0.\n       simpl.\n       destruct H0.\n       +++ congruence.\n       +++ auto.\n  + intros.\n    simpl in H0.\n    destruct l'.\n    ++ simpl.\n       simpl in H0.\n       auto.\n    ++ destruct a.\n       destruct (JFVal_dec j (JFVLoc (JFLoc n))).\n       +++ subst j.\n           simpl.\n           simpl in H0.\n           destruct H0; try congruence.\n           right;auto.\n       +++ destruct H0.\n           ++++ rewrite <- H0.\n                simpl;left;auto.\n           ++++ eapply IHGamma in H0;auto.\n                simpl;right;auto.\nQed.\n       \nHint Resolve in_oplus_eq in_oplus_neq oPlus_neq oplus_decompose_eq.\n\nFixpoint loc2env_aux (cn:JFClassName) (mdecl:JFMethodDeclaration)\n         (vs:list JFVal) (num:nat) (res:JFEnv) {struct vs} :=\n  match vs with\n  | [] => res\n  | (JFVLoc lhd) :: tl =>\n    let acidpt := parTypM P (JFClass cn) (name_of_md mdecl) num in\n    (* parTypM returns rwr annotation for non-LS methods *)\n    match acidpt with\n    | None => res\n    | Some acid => loc2env_aux cn mdecl tl (num+1) (oPlus res lhd acid)\n    end\n  | (JFSyn x) :: tl => res\nend.\n\nDefinition loc2env (cn:JFClassName) (mdecl:JFMethodDeclaration)\n           (vs:list JFVal)  :=\n  loc2env_aux cn mdecl vs 0 [].\n\n(* \n  (x,Acid) \u2208 (oPlus Gamma x Acid')  \u2227  Acid \u2264: Acid'\n*)\nLemma In_oPlus : forall Gamma n D muD,\n    names_unique P ->\n    subtype_well_founded P ->\n    exists D' muD', In (JFVLoc (JFLoc n), (D', muD')) (oPlus Gamma (JFLoc n) (D, muD)) /\\\n             leqACId P (D',muD') (D,muD).\nProof.\n  intros.\n  induction Gamma.\n  + do 2 eexists.\n    simpl.\n    repeat split; auto with myhints.\n  + simpl.\n    destruct a as (x,(Dx,mux)).\n    destruct (JFVal_dec x (JFVLoc (JFLoc n))).\n    ++\n      subst.\n      do 2 eexists.\n      split.\n      +++ simpl; eauto 2.\n      +++ split.\n          ++++ eapply infClass_subL; eauto 1.\n          ++++ eapply infAnn_leq_l; eauto 1.\n    ++\n      simpl.\n      decompose_ex IHGamma.\n      decompose_and IHGamma.\n      do 2 eexists; eauto 3.\nQed.\n\nHint Resolve In_oPlus.\n\n(**\n  The operation par2env as defined in Section {sec:type-system}. \n  Here, the definition does not use ParTypM, but is equivalent.\n*)\nDefinition par2env :=\nmatch md with\n| JFMDecl _ mu _ vs _ _ =>\n      (JFSyn JFThis, (JFClass (name_of_cd cdecl), mu))\n       :: map\n            (fun H0 : JFXId * JFACId =>\n             let (x, acid) := H0 in (JFSyn (JFVar x), acid)) vs\n| JFMDecl0 _ _ vs _ _ =>\n      (JFSyn JFThis, (JFClass (name_of_cd cdecl), JFrwr))\n       :: map\n            (fun H0 : JFXId * JFCId =>\n             let (x, cid) := H0 in (JFSyn (JFVar x), (cid, JFrwr))) vs\nend.\n\n\nLemma par2env_equiv_parTypM : forall i,\n    nth i par2env (JFnull, (JFObject, JFrwr)) =\n    (nth i (JFSyn JFThis :: map (fun x => JFSyn (JFVar x)) (params_of_md md)) JFnull,\n     parTypM_of_md (JFClass (name_of_cd cdecl)) md i).\nProof.\n  destruct i.\n  + simpl.\n    unfold par2env.\n    unfold parTypM_of_md.\n    unfold name_of_cd.\n    sauto.\n  + unfold par2env.\n    unfold parTypM_of_md.\n    unfold name_of_cd.\n    replace (S i - 1) with i by auto with arith.\n    revert i.\n    destruct md; simpl.\n    * induction vs; sauto.\n    * induction vs; sauto.\nQed.\n\nDefinition subenv (Gamma1 Gamma2: JFEnv) : Prop :=\n  forall x Acid2, In (x,Acid2) Gamma2 ->\n                 exists Acid1,\n                   In (x,Acid1) Gamma1 /\\ leqIsLS P (JFClass (name_of_cd cdecl)) (name_of_md md) Acid1 Acid2.\n\nLemma subenv_cons :\n  forall Gamma1 Gamma2 x Acid,\n    subenv Gamma1 Gamma2 ->\n    subenv ((x,Acid)::Gamma1) ((x,Acid)::Gamma2).\nProof.\n  unfold subenv.\n  intros until 0.\n  intros ? ? ? H0.\n  inversion H0 as [H1|?].\n  + injection H1; intros; subst.\n    eexists.\n    split.\n    ++ sauto.\n    ++ eapply leqIsLS_refl; eauto.\n  + simpl In; firstorder.\nQed.\n\nLemma subenv_cons_sub:\n  forall Gamma1 Gamma2 x Acid1 Acid2,\n    leqIsLS P (JFClass (name_of_cd cdecl)) (name_of_md md) Acid1 Acid2 ->\n    subenv Gamma1 Gamma2 ->\n    subenv ((x,Acid1)::Gamma1) ((x,Acid2)::Gamma2).\nProof.\n  unfold subenv.\n  intros until 0.\n  intros ? ? ? ? H0.\n  inversion H0 as [H2|?].\n  + injection H2; intros; subst.\n    eexists.\n    sauto.\n  + simpl In; firstorder.\nQed.\n\nLemma subenv_refl:\n  forall Gamma,\n    subenv Gamma Gamma.\nProof.\n  induction Gamma.\n  + sauto.\n  + destruct a.\n    eauto using subenv_cons.\nQed.\n         \n  \nLemma subenv_oPlus:\n  forall Gamma x acid,\n    names_unique P ->\n    subtype_well_founded P -> \n    subenv (oPlus Gamma x acid) Gamma.\nProof.\n  induction Gamma.\n  + sauto.\n  + intros.\n    destruct x; simpl.\n    * apply subenv_refl.\n    * destruct a.\n      destruct (JFVal_dec j (JFVLoc (JFLoc n))).\n      - destruct (infACId P acid j0) eqn:Hinf.\n        -- eapply infACId_leqIsLS_R in Hinf;eauto.\n           eapply subenv_cons_sub;eauto using subenv_refl.\n      - auto using subenv_cons.\nQed.       \n\nHint Resolve subenv_cons subenv_cons_sub subenv_refl subenv_oPlus.\n\n\nLemma oPlus_non_null :\n  forall Gamma l Acid,\n    Forall (fun '(v, _) => isNonNullLoc v) Gamma ->\n    Forall (fun '(v, _) => isNonNullLoc v) (oPlus Gamma l Acid).\nProof.\n  destruct l.\n  * induction Gamma; simpl; trivial.\n  * induction Gamma; simpl.\n    ** intros ? _.\n       repeat constructor.\n    ** intros (v1, Acid1) H.\n       destruct a as (v2, Acid2).\n       ***\n         inversion_clear H.\n         destruct (JFVal_dec v2 (JFVLoc (JFLoc n))).\n         ****\n           subst.\n           destruct (infACId P (v1, Acid1) Acid2); repeat constructor; assumption.\n         ****\n           constructor; auto. \nQed.\n\nHint Resolve oPlus_non_null.\n\nLemma oPlus_null : forall Gamma Acid,\n    oPlus Gamma null Acid = Gamma.\nProof.\n  induction Gamma; sauto.\nQed.\n\nHint Rewrite oPlus_non_null.\n\nLemma name_occ_oPlus_eq:\n  forall Gamma v l acid,\n    v <> JFVLoc l ->\n    Env.name_occ (oPlus Gamma l acid) v = Env.name_occ Gamma v.\nProof.\n  induction Gamma.\n  + intros * Hne. \n    simpl.\n    Env.uniq v.\n    destruct l.\n    ++ trivial.\n    ++ unfold Env.NU.name_occ.\n       simpl map.\n       unfold count_occ.\n       destruct VarInEnv.name_dec; intuition.\n  + intros * Hne.\n    destruct a as (v1,acid1).\n    destruct v1 as [l'|x].\n    ++ destruct (JFVal_dec (JFVLoc l') (JFVLoc l)) as [e|e].\n       +++ injection e;intros;subst.\n           destruct l.\n           ++++ rewrite oPlus_null;auto.\n           ++++ rewrite oplus_decompose_eq;eauto 1.\n                congruence.\n       +++ rewrite oPlus_neq by auto.\n           destruct (JFVal_dec v (JFVLoc l)); Env.uniq v; intuition.\n    ++ rewrite oPlus_neq; try congruence.\n       destruct (JFVal_dec v (JFSyn x)); Env.uniq v; intuition.\nQed.\n\nImport Env.\n\nLemma name_occ_oPlus : \n  forall Gamma v l acid n,\n    v <> JFVLoc l ->\n    name_occ Gamma v = n ->\n    name_occ (oPlus Gamma l acid) v = n.\nProof.\n  intros.\n  now rewrite name_occ_oPlus_eq.\nQed.\n\nHint Resolve name_occ_oPlus.\n\nLemma names_unique_env_oPlus:\n  forall Gamma l acid,\n    Env.names_unique Gamma ->\n    Env.names_unique (oPlus Gamma l acid).\nProof.\n  induction Gamma.\n  + unfold names_unique.\n    intros.\n    intro v.\n    destruct l.\n    ++ simpl.\n       auto.\n    ++ simpl oPlus.\n       uniq v.\n       apply name_xi_small.\n  + intros.\n    destruct a as (v1,acid1).\n    destruct (JFVal_dec v1 (JFVLoc l)).\n    ++ subst.\n       destruct (Loc_dec l null).\n       +++ subst.\n           rewrite oPlus_null;eauto 1.\n       +++ rewrite oplus_decompose_eq;eauto 1.\n    ++ destruct (Loc_dec l null).\n       +++ subst.\n           rewrite oPlus_null;eauto 1.\n       +++ destruct v1.\n           ++++\n             rewrite oPlus_neq by eauto 2.\n             eapply names_unique_cons; eauto 3.\n           ++++\n             rewrite oPlus_neq by eauto 2.\n             eapply names_unique_cons; eauto 3.\nQed.\n\n\nHint Resolve names_unique_env_oPlus.\n\n(* TODO: Hack, \u017ceby ods\u0142oni\u0107 zas\u0142oni\u0119te names_unique... *)\nNotation names_unique := JaProgram.names_unique.\n\n\nLemma In_in_oPlus:\n  forall Gamma n D' muD' D'' muD'',\n  names_unique P ->\n  Env.names_unique Gamma ->\n  subtype_well_founded P ->\n  In (JFVLoc (JFLoc n), (D', muD')) Gamma -> \n  exists (D : JFCId) (muD : JFAMod),\n    In (JFVLoc (JFLoc n), (D, muD)) (oPlus Gamma (JFLoc n) (D'', muD'')) /\\\n    leqACId P (D, muD) (D', muD') /\\ leqACId P (D, muD) (D'', muD'').\nProof.     \n  intros * ? Hun ? HIn.\n  induction Gamma.\n  + do 2 eexists.\n    simpl.\n    repeat split; auto with myhints.\n  + simpl oPlus.\n    destruct a as (x,(Dx,mux)).\n    destruct (JFVal_dec x (JFVLoc (JFLoc n))).\n    ++\n      subst.\n      do 2 eexists.\n      split.\n      +++ simpl; eauto 2.\n      +++ assert (In (JFVLoc (JFLoc n), (Dx, mux))\n                 ((JFVLoc (JFLoc n), (Dx, mux)) :: Gamma)) as HInx.\n          { simpl; auto. }\n          eapply Env.name_once_In_unique in HIn; eauto 3.\n          (* {simpl; left; reflexivity.} *)\n          injection HIn.\n          intros; subst.\n          do 2 split; eauto 2 using infClass_subL, infClass_subR, infAnn_leq_l, infAnn_leq_r.\n    ++\n      simpl In in *.\n      destruct HIn; try congruence.\n      destruct IHGamma as (? & ? & ? & ? & ?); eauto 1; sauto.\nQed.\n\n\nLemma In_oPlus_other : forall x Acid l Acid' Gamma,\n      x <> JFVLoc l ->\n      In (x, Acid) Gamma ->\n      In (x, Acid) (oPlus Gamma l Acid').                \nProof.    \n  intros * Hneq.\n  induction Gamma.\n  { intros []. }  \n  destruct a as (v,Acid1).\n  intros HIn.\n  simpl.\n  destruct l; trivial.\n  destruct JFVal_dec.\n  + destruct HIn; try congruence.\n    red; auto.\n  + destruct HIn as [ -> | H].   \n    * red; auto.\n    * right; auto.\nQed.      \n\nHint Resolve In_oPlus_other.\n\nDefinition get_mu phi Gamma n : JFAMod :=\n  match phi with\n  | true =>\n    match find Gamma (JFVLoc (JFLoc n)) with\n    | None => JFatm\n    | Some (_,(DD,mu')) => mu'\n    end\n  | false => JFatm\n  end.\n\n\nEnd EnvsInProgram.", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaEnvs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.17416209762685414}}
{"text": "Require Import RelationClasses.\nRequire Import List.\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 PromiseConsistent.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import JoinedView.\nRequire Import Single.\nRequire Import Shorter.\n\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\nRequire SimMemory.\n\nRequire Import LocalPFThread.\nRequire Import TimeTraced.\nRequire Import PFConsistentStrong.\nRequire Import Mapping.\nRequire Import GoodFuture.\nRequire Import CapMap.\nRequire Import CapFlex.\nRequire Import Pred.\n\nRequire Import LocalPFSim.\nRequire Import CapMapTime.\nRequire Import LocalPFThreadTime.\n\nSet Implicit Arguments.\n\nSection RECOVER.\n\n  Variable L: Loc.t -> bool.\n  Variable times: Loc.t -> Time.t -> Prop.\n  Hypothesis WO: forall loc, well_ordered (times loc).\n  Hypothesis INCR: forall nat loc, times loc (incr_time_seq nat).\n\n  Inductive sim_thread\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom_self prom_others: Loc.t -> Time.t -> Prop)\n            (extra_self extra_others: Loc.t -> Time.t -> Time.t -> Prop):\n    forall lang (th_src th_mid th_tgt: Thread.t lang), Prop :=\n  | sim_thread_intro\n      lang st lc_src lc_mid lc_tgt\n      mem_src mem_mid mem_tgt sc_src sc_tgt\n      (LOCALPF: sim_local L times prom_self extra_self lc_src lc_mid)\n      (LOCALJOIN: JSim.sim_local views lc_mid lc_tgt)\n      (MEMPF: sim_memory L times (prom_others \\\\2// prom_self) (extra_others \\\\3// extra_self) mem_src mem_mid)\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n    :\n      sim_thread\n        views prom_self prom_others extra_self extra_others\n        (Thread.mk lang st lc_src sc_src mem_src)\n        (Thread.mk lang st lc_mid sc_src mem_mid)\n        (Thread.mk lang st lc_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_thread.\n\n  Inductive sim_thread_strong\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom_self prom_others: Loc.t -> Time.t -> Prop)\n            (extra_self extra_others: Loc.t -> Time.t -> Time.t -> Prop):\n    forall lang (th_src th_mid th_tgt: Thread.t lang), Prop :=\n  | sim_thread_strong_intro\n      lang st lc_src lc_mid lc_tgt\n      mem_src mem_mid mem_tgt sc_src sc_tgt\n      (LOCALPF: sim_local_strong L times prom_self extra_self (extra_others \\\\3// extra_self) lc_src lc_mid)\n      (LOCALJOIN: JSim.sim_local views lc_mid lc_tgt)\n      (MEMPF: sim_memory L times (prom_others \\\\2// prom_self) (extra_others \\\\3// extra_self) mem_src mem_mid)\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n    :\n      sim_thread_strong\n        views prom_self prom_others extra_self extra_others\n        (Thread.mk lang st lc_src sc_src mem_src)\n        (Thread.mk lang st lc_mid sc_src mem_mid)\n        (Thread.mk lang st lc_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_thread_strong.\n\n  Lemma sim_thread_strong_sim_thread\n    :\n      sim_thread_strong <9= sim_thread.\n  Proof.\n    ii. dep_inv PR. econs; eauto.\n    eapply sim_local_strong_sim_local; eauto.\n  Qed.\n\n  Lemma sim_thread_jsim_thread\n        views prom_self prom_others extra_self extra_others\n        lang th_src th_mid th_tgt\n        (THREAD: @sim_thread\n                   views prom_self prom_others extra_self extra_others\n                   lang th_src th_mid th_tgt)\n    :\n      JSim.sim_thread views th_mid th_tgt.\n  Proof.\n    dep_inv THREAD.\n  Qed.\n\n  Lemma sim_thread_step_silent\n        views0 prom_self0 prom_others extra_self0 extra_others\n        lang th_src0 th_mid0 th_tgt0 th_tgt1 pf_tgt e_tgt\n        (STEPTGT: Thread.step pf_tgt e_tgt th_tgt0 th_tgt1)\n        (THREAD: @sim_thread\n                   views0 prom_self0 prom_others extra_self0 extra_others\n                   lang th_src0 th_mid0 th_tgt0)\n        (WFTIME: wf_time_evt times e_tgt)\n        (NOREAD: no_read_msgs prom_others e_tgt)\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src0) (Thread.memory th_src0))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid0) (Thread.memory th_mid0))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt0) (Thread.memory th_tgt0))\n        (MEMSRC: Memory.closed (Thread.memory th_src0))\n        (MEMMID: Memory.closed (Thread.memory th_mid0))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt0))\n        (LOCALSRC: Local.wf (Thread.local th_src0) (Thread.memory th_src0))\n        (LOCALMID: Local.wf (Thread.local th_mid0) (Thread.memory th_mid0))\n        (LOCALTGT: Local.wf (Thread.local th_tgt0) (Thread.memory th_tgt0))\n\n        (MEMWF: memory_times_wf times (Thread.memory th_mid0))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt0))\n        (CONSISTENT: Local.promise_consistent (Thread.local th_tgt1))\n\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src0) loc ts) (views0 loc ts))\n\n        (REL: joined_released\n                views0 (Local.promises (Thread.local th_mid0)) (Local.tview (Thread.local th_mid0)).(TView.rel))\n        (JOINEDMEM: joined_memory views0 (Thread.memory th_mid0))\n        (VIEWS: wf_views views0)\n    :\n      exists th_mid1 th_src1 views1 prom_self1 extra_self1 pf_mid e_mid tr,\n        (<<STEPMID: JThread.step pf_mid e_mid th_mid0 th_mid1 views0 views1>>) /\\\n        (<<STEPSRC: Trace.steps tr th_src0 th_src1>>) /\\\n        (<<THREAD: sim_thread_strong\n                     views1 prom_self1 prom_others extra_self1 extra_others\n                     th_src1 th_mid1 th_tgt1>>) /\\\n        (<<EVENTJOIN: JSim.sim_event e_mid e_tgt>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src1) loc ts) (views1 loc ts)>>) /\\\n        (<<MEMWF: memory_times_wf times (Thread.memory th_mid1)>>) /\\\n        (<<MEMWFTGT: memory_times_wf times (Thread.memory th_tgt1)>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr>>)\n  .\n  Proof.\n    hexploit sim_thread_jsim_thread; eauto. intros JTHREAD.\n    exploit JSim.sim_thread_step; eauto. i. des.\n    dep_inv THREAD. destruct th1_src. ss.\n    hexploit sim_thread_step_silent; try apply STEP; eauto.\n    { inv EVENT0; ss. }\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. inv EVENT0; ss. }\n    { dep_inv SIM. eapply JSim.sim_local_promise_consistent; eauto. }\n    { inv EVENT0; ss. }\n    i. des. dep_inv SIM. esplits; eauto.\n    { inv STEP. ss. hexploit step_memory_times_wf; eauto. inv EVENT0; ss. }\n    { hexploit step_memory_times_wf; try apply STEPTGT; eauto. }\n  Qed.\n\n  Lemma sim_thread_steps_silent\n        views0 prom_self0 prom_others extra_self0 extra_others\n        lang th_src0 th_mid0 th_tgt0 th_tgt1 tr_tgt\n        (STEPTGT: Trace.steps tr_tgt th_tgt0 th_tgt1)\n        (THREAD: @sim_thread\n                   views0 prom_self0 prom_others extra_self0 extra_others\n                   lang th_src0 th_mid0 th_tgt0)\n\n        (EVENTS: List.Forall (fun the => <<SAT: (wf_time_evt times /1\\ no_read_msgs prom_others) (snd the)>> /\\ <<TAU: ThreadEvent.get_machine_event (snd the) = MachineEvent.silent>>) tr_tgt)\n\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src0) (Thread.memory th_src0))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid0) (Thread.memory th_mid0))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt0) (Thread.memory th_tgt0))\n        (MEMSRC: Memory.closed (Thread.memory th_src0))\n        (MEMMID: Memory.closed (Thread.memory th_mid0))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt0))\n        (LOCALSRC: Local.wf (Thread.local th_src0) (Thread.memory th_src0))\n        (LOCALMID: Local.wf (Thread.local th_mid0) (Thread.memory th_mid0))\n        (LOCALTGT: Local.wf (Thread.local th_tgt0) (Thread.memory th_tgt0))\n\n        (MEMWF: memory_times_wf times (Thread.memory th_mid0))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt0))\n        (CONSISTENT: Local.promise_consistent (Thread.local th_tgt1))\n\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src0) (Local.promises (Thread.local th_src0)) loc ts from Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src0) loc ts) (views0 loc ts))\n\n        (REL: joined_released\n                views0 (Local.promises (Thread.local th_mid0)) (Local.tview (Thread.local th_mid0)).(TView.rel))\n        (JOINEDMEM: joined_memory views0 (Thread.memory th_mid0))\n        (VIEWS: wf_views views0)\n    :\n      exists th_mid1 th_src1 views1 prom_self1 extra_self1 tr_src,\n        (<<STEPMID: JThread.rtc_tau th_mid0 th_mid1 views0 views1>>) /\\\n        (<<STEPSRC: Trace.steps tr_src th_src0 th_src1>>) /\\\n        (<<THREAD: sim_thread_strong\n                     views1 prom_self1 prom_others extra_self1 extra_others\n                     th_src1 th_mid1 th_tgt1>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src1) loc ts) (views1 loc ts)>>) /\\\n        (<<MEMWF: memory_times_wf times (Thread.memory th_mid1)>>) /\\\n        (<<MEMWFTGT: memory_times_wf times (Thread.memory th_tgt1)>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr_src>>)\n  .\n  Proof.\n    ginduction STEPTGT.\n    { i. dep_inv THREAD. inv LOCALPF. exploit sim_promise_weak_strengthen; eauto.\n      { eapply LOCALMID. }\n      { eapply LOCALSRC. }\n      { eapply LOCALSRC. }\n      { eapply LOCALSRC. }\n      i. des. exploit reserve_future_memory_steps; eauto. i. des. ss. esplits; eauto.\n      { econs; eauto. econs; eauto. }\n      { i. ss. eapply List.Forall_impl; eauto.\n        ii. ss. eapply semi_closed_view_future; eauto.\n        eapply Memory.future_future_weak. eapply reserve_future_future; eauto. }\n      { eapply reserving_trace_silent; eauto. }\n    }\n    i. subst. inv EVENTS. ss. des.\n    hexploit Thread.step_future; try apply STEP; eauto. i. des.\n    hexploit sim_thread_step_silent; eauto.\n    { eapply Trace.steps_promise_consistent; eauto. } i. des.\n    hexploit JThread.step_future; try apply STEPMID; eauto. i. des.\n    hexploit Trace.steps_future; try apply STEPSRC; eauto. i. des.\n    eapply sim_thread_strong_sim_thread in THREAD0. exploit IHSTEPTGT; eauto.\n    { i. eapply EXCLUSIVE in OTHER. des.\n      eapply unchangable_trace_steps_increase in UNCH; eauto. }\n    { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n      eapply unchangable_trace_steps_increase in OTHER; eauto. }\n    i. des. esplits; try apply THREAD1; try by assumption.\n    { econs; eauto. inv EVENTJOIN; ss. }\n    { eapply Trace.steps_trans; eauto. }\n    { eapply Forall_app; eauto. }\n  Qed.\n\n  Lemma sim_thread_consistent\n        views prom_self prom_others extra_self extra_others\n        lang th_src th_mid th_tgt\n        (CONSISTENTTGT: past_consistent times (Thread.memory th_src) th_tgt)\n        (THREAD: @sim_thread_strong\n                   views prom_self prom_others extra_self extra_others\n                   lang th_src th_mid th_tgt)\n        (SCSRC: Memory.closed_timemap (Thread.sc th_src) (Thread.memory th_src))\n        (SCMID: Memory.closed_timemap (Thread.sc th_mid) (Thread.memory th_mid))\n        (SCTGT: Memory.closed_timemap (Thread.sc th_tgt) (Thread.memory th_tgt))\n        (MEMSRC: Memory.closed (Thread.memory th_src))\n        (MEMMID: Memory.closed (Thread.memory th_mid))\n        (MEMTGT: Memory.closed (Thread.memory th_tgt))\n        (LOCALSRC: Local.wf (Thread.local th_src) (Thread.memory th_src))\n        (LOCALMID: Local.wf (Thread.local th_mid) (Thread.memory th_mid))\n        (LOCALTGT: Local.wf (Thread.local th_tgt) (Thread.memory th_tgt))\n        (MEMWF: memory_times_wf times (Thread.memory th_mid))\n        (MEMWFTGT: memory_times_wf times (Thread.memory th_tgt))\n        (EXCLUSIVE: forall loc ts (OTHER: prom_others loc ts),\n            exists from msg, <<UNCH: unchangable (Thread.memory th_src) (Local.promises (Thread.local th_src)) loc ts from msg>>)\n        (EXCLUSIVEEXTRA: forall loc ts from (OTHER: extra_others loc ts from),\n            (<<UNCH: unchangable (Thread.memory th_src) (Local.promises (Thread.local th_src)) loc ts from Message.reserve>>))\n        (EXCLUSIVE2: forall loc to (OTHER: prom_others loc to), ~ covered loc to (Local.promises (Thread.local th_mid)))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw (Thread.memory th_src) loc ts) (views loc ts))\n\n        (REL: joined_released\n                views (Local.promises (Thread.local th_mid)) (Local.tview (Thread.local th_mid)).(TView.rel))\n        (JOINEDMEM: joined_memory views (Thread.memory th_mid))\n        (VIEWS: wf_views views)\n    :\n      Thread.consistent th_src.\n  Proof.\n    dup THREAD. dep_inv THREAD.\n    hexploit sim_memory_strong_exists; eauto. i. des.\n    assert (MEMSRCSTRONG: Memory.closed mem_src').\n    { eapply sim_memory_same_closed; eauto.\n      eapply sim_memory_strong_sim_memory; eauto. }\n\n    hexploit (later_timemap_exists\n                times\n                INCR\n                (TimeMap.join\n                   (Memory.max_timemap mem_src')\n                   (TimeMap.join\n                      (Memory.max_timemap mem_src)\n                      (TimeMap.join\n                         (Memory.max_timemap mem_mid)\n                         (Memory.max_timemap mem_tgt))))). intros [tm ?]. des.\n\n    assert (TM0': forall loc,\n               Time.lt (Memory.max_ts loc mem_src') (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM0: forall loc,\n               Time.lt (Memory.max_ts loc mem_src) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM1: forall loc,\n               Time.lt (Memory.max_ts loc mem_mid) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). }\n    assert (TM2: forall loc,\n               Time.lt (Memory.max_ts loc mem_tgt) (tm loc)).\n    { i. eapply TimeFacts.le_lt_lt; eauto.\n      repeat ((try eapply Time.join_l); ((etrans; cycle 1); [eapply Time.join_r|])). refl. }\n\n    hexploit (@cap_flex_exists mem_src' tm); eauto.\n    intros [cap_src' CAPSRCSTRONG].\n    hexploit (@cap_flex_exists mem_mid tm); eauto.\n    intros [cap_mid CAPMID].\n    hexploit (@cap_flex_exists mem_tgt tm); eauto.\n    intros [cap_tgt CAPTGT].\n    hexploit (@Memory.max_concrete_timemap_exists mem_src); try apply MEMSRC.\n    intros [max MAX].\n\n    hexploit (@Memory.cap_exists mem_src); eauto. intros [mem1 CAP]. des.\n    hexploit (@Memory.max_concrete_timemap_exists mem1); eauto.\n    { eapply Memory.cap_closed in MEMSRC; eauto. eapply MEMSRC. } intros [sc1 SC_MAX].\n    assert (SCSRC0: Memory.closed_timemap sc1 mem_src).\n    { eapply concrete_promised_le_closed_timemap.\n      { eapply concrete_messages_le_concrete_promised_le.\n        eapply cap_flex_concrete_messages_le.\n        { eapply cap_cap_flex; eauto. }\n        { eauto. }\n        { i. ss. eapply Time.incr_spec. }\n      }\n      eapply Memory.max_concrete_timemap_closed; eauto.\n    }\n    assert (SCSRC1: Memory.closed_timemap sc1 mem_src').\n    { eapply concrete_promised_le_closed_timemap; eauto.\n      eapply concrete_messages_le_concrete_promised_le.\n      eapply sim_memory_same_concrete_messages_le; eauto.\n      eapply sim_memory_strong_sim_memory; eauto. }\n    assert (SCMID0: Memory.closed_timemap sc1 mem_mid).\n    { eapply concrete_promised_le_closed_timemap; try apply SCSRC0; eauto.\n      eapply concrete_messages_le_concrete_promised_le.\n      eapply sim_memory_concrete_messages_le; eauto. }\n    exploit (@Memory.max_concrete_timemap_exists mem_tgt).\n    { eapply MEMTGT. } intros [sctgt MAXTGT]. des.\n\n    hexploit (@concrete_promise_max_timemap_exists mem_tgt (Local.promises lc_tgt)).\n    { eapply MEMTGT. } intros [maxconcete MAXCONCRETE].\n\n    exploit (CONSISTENTTGT).\n    { instantiate (1:= cap_tgt). ss. eapply cap_flex_future_weak; eauto. }\n    { eapply cap_flex_closed; eauto. }\n    { eapply cap_flex_memory_times_wf; eauto. }\n    { eapply cap_flex_wf; eauto. }\n    i. des. ss.\n    instantiate (1:=sctgt) in STEPS.\n    instantiate (1:=Memory.max_timemap mem_src) in EVENTS.\n\n    hexploit sim_thread_steps_silent; simpl.\n    { eapply STEPS. }\n    { econs.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { eauto. }\n      { eapply sim_memory_strong_cap; eauto. }\n      { eapply (@cap_flex_sim_memory mem_mid mem_tgt); eauto. }\n      { instantiate (1:=sc1).\n        eapply Memory.max_concrete_timemap_spec.\n        { instantiate (1:=mem_mid).\n          exploit (@Memory.max_concrete_timemap_exists mem_mid); eauto.\n          { eapply MEMMID. } i. des.\n          exploit (@SimMemory.sim_memory_max_concrete_timemap mem_mid mem_tgt); eauto.\n          i. subst. auto.\n        }\n        auto.\n      }\n    }\n    { eapply Forall_impl; eauto. i. ss. des. splits; auto.\n      eapply no_read_msgs_mon; eauto. ii. des.\n      { inv LOCALJOIN. erewrite <- jsim_joined_promises_covered in H; eauto.\n        eapply EXCLUSIVE2; eauto.\n      }\n      { inv H.  set (MEM0:=(sim_memory_contents MEMPF) x0 x1).\n        rewrite GET in *. inv MEM0; ss. eapply NPROM. left. auto.\n      }\n      { eapply EXCLUSIVE in PR. des. inv UNCH.\n        eapply Memory.max_ts_spec in GET. des. timetac.\n      }\n    }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. } eauto. }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. } eauto. }\n    { ss. eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. }\n      eapply Memory.max_concrete_timemap_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_closed; eauto. }\n    { ss. eapply cap_flex_wf; eauto.\n      eapply sim_memory_strong_sim_local; eauto.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { inv LOCALPF. ss. }\n    }\n    { ss. eapply cap_flex_wf; eauto. }\n    { ss. eapply cap_flex_wf; eauto. }\n    { ss. eapply cap_flex_memory_times_wf; cycle 1; eauto. }\n    { ss. eapply cap_flex_memory_times_wf; cycle 1; eauto. }\n    { destruct FINAL.\n      { des. inv LOCAL. auto. }\n      { des. ii. erewrite H in *. erewrite Memory.bot_get in *. ss. }\n    }\n    { ss. ii. exploit EXCLUSIVE; eauto. i. des. inv UNCH.\n      set (CNT:=(sim_memory_strong_contents MEM) loc ts).\n      inv CNT; ss; try by (exfalso; eapply NPROM0; left; auto).\n      symmetry in H0. eapply CAPSRCSTRONG in H0. esplits. econs; eauto. }\n    { ss. ii. exploit EXCLUSIVEEXTRA; eauto. i. des. inv x.\n      set (CNT:=(sim_memory_strong_contents MEM) loc ts).\n      exploit ((sim_memory_strong_wf MEM) loc from ts).\n      { left. auto. } i. des.\n      inv CNT; ss; try by (exfalso; eapply NEXTRA; left; eauto).\n      eapply UNIQUE in EXTRA. subst.\n      symmetry in H0. eapply CAPSRCSTRONG in H0. esplits. econs; eauto. }\n    { ss. i. eapply List.Forall_impl; eauto. i. ss.\n      eapply semi_closed_view_future.\n      2: { eapply cap_flex_future_weak; eauto. }\n      { eapply concrete_promised_le_semi_closed_view; eauto.\n        eapply concrete_messages_le_concrete_promised_le.\n        eapply sim_memory_same_concrete_messages_le; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n    }\n    { ss. }\n    { ss. eapply joined_memory_cap_flex; eauto. }\n    { ss. }\n\n    i. des. hexploit (trace_times_list_exists tr_src). i. des.\n\n    hexploit (@cap_flex_map_exists\n                (Memory.max_timemap mem_src')\n                tm\n                (fun loc : Loc.t => Time.incr (Memory.max_ts loc mem_src))\n                times0); auto.\n    { i. erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src'); eauto.\n      { apply Time.incr_spec. }\n      { eapply sim_memory_strong_sim_memory; eauto. }\n    } i. des.\n\n    exploit (@Memory.max_concrete_timemap_exists mem_src').\n    { eapply MEMSRCSTRONG. } i. des.\n    hexploit concrete_messages_le_cap_flex_memory_map; try apply MAP.\n    { eapply sim_memory_same_concrete_messages_le.\n      { eapply sim_memory_strong_sim_memory; eauto. }\n      { eapply MEMPF. }\n    }\n    { eauto. }\n    { ii. ss. eapply max_concrete_ts_le_max_ts; eauto. }\n    { auto. }\n    { i. ss. eapply Time.incr_spec. }\n    { eauto. }\n    { eapply cap_cap_flex; eauto. }\n    { eauto. }\n    { eauto. }\n    intros MEMORYMAP. destruct th_src1. ss.\n    hexploit trace_steps_map; try apply MEMORYMAP.\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; eauto.\n      i. ss. eapply MAP in IN0. eauto. }\n    { eauto. }\n    { ss. }\n    { ss. }\n    { ss. }\n    { eapply cap_flex_wf; eauto.\n      eapply sim_memory_strong_sim_local; eauto.\n      { eapply sim_local_strong_sim_local; eauto. }\n      { inv LOCALPF. ss. }\n    }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    { eapply cap_flex_closed; eauto. }\n    { eapply Memory.max_concrete_timemap_closed; eauto. }\n    { eapply Memory.future_weak_closed_timemap.\n      { eapply cap_flex_future_weak; eauto. }\n      { eauto. }\n    }\n    { eapply map_ident_in_memory_local; eauto.\n      { ii. eapply MAP; auto.\n        erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src') in TS; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n      { eapply MAP. }\n    }\n    { eapply mapping_map_lt_collapsable_unwritable. eapply MAP. }\n    { eapply map_ident_in_memory_closed_timemap.\n      { ii. eapply MAP; auto.\n        erewrite (@sim_memory_same_max_ts_eq L times mem_src mem_src') in TS; eauto.\n        eapply sim_memory_strong_sim_memory; eauto. }\n      { eauto. }\n    }\n    { refl. }\n\n    i. des.\n    assert (SILENT0: List.Forall\n                      (fun the =>\n                         ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) ftr0).\n    { eapply List.Forall_forall. i.\n      eapply list_Forall2_in in H; eauto. i. des.\n      eapply Forall_forall in IN0; try apply SILENT. ss.\n      destruct a, x. ss. inv EVENT; ss.\n    }\n    eapply Trace.consistent_thread_consistent.\n    instantiate (1:=ftr0).\n\n    dep_inv THREAD.\n    { ii. ss. eapply Memory.cap_inj in CAP; eauto. subst.\n      eapply Memory.max_concrete_timemap_inj in SC_MAX; eauto. subst.\n      esplits; eauto. ss. unguard. des.\n      { left. esplits. econs 2. econs; eauto. econs.\n        eapply failure_step_map; eauto.\n        { eapply mapping_map_lt_map_le. eapply MAP. }\n        { eapply mapping_map_lt_map_eq. eapply MAP. }\n        eapply sim_failure_step; cycle 1.\n        { eapply sim_local_strong_sim_local; eauto. }\n        eapply JSim.sim_local_failure; eauto.\n      }\n      { right. esplits; eauto. ss. inv LOCAL.\n        cut ((Local.promises local) = Memory.bot).\n        { i. eapply bot_promises_map; eauto. erewrite <- H. eauto. }\n        eapply JSim.sim_local_memory_bot in LOCALJOIN0; auto.\n        inv LOCALPF0. ss.\n        eapply sim_promise_bot; eauto. eapply sim_promise_strong_sim_promise; eauto.\n      }\n    }\n  Qed.\n\n  Inductive sim_configuration\n            (views: Loc.t -> Time.t -> list View.t)\n            (prom: Ident.t -> Loc.t -> Time.t -> Prop)\n            (extra: Ident.t -> Loc.t -> Time.t -> Time.t -> Prop)\n            (proml: Ident.t -> list (Loc.t * Time.t))\n    :\n      forall (c_src c_mid c_tgt: Configuration.t), Prop :=\n  | sim_configuration_intro\n      ths_src sc_src mem_src\n      ths_mid mem_mid\n      ths_tgt sc_tgt mem_tgt\n      (THSPF: forall tid,\n          option_rel\n            (sim_statelocal L times (prom tid) (extra tid))\n            (IdentMap.find tid ths_src)\n            (IdentMap.find tid ths_mid))\n      (THSJOIN: forall tid,\n          option_rel\n            (JSim.sim_statelocal views)\n            (IdentMap.find tid ths_mid)\n            (IdentMap.find tid ths_tgt))\n      (BOT: forall tid (NONE: IdentMap.find tid ths_src = None),\n          (<<PROM: forall loc ts, ~ prom tid loc ts>>) /\\\n          (<<EXTRA: forall loc ts from, ~ extra tid loc ts from>>))\n      (MEMPF: sim_memory L times (all_promises (fun _ => True) prom) (all_extra (fun _ => True) extra) mem_src mem_mid)\n      (SCPF: TimeMap.le sc_src sc_tgt)\n\n      (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (MEMWF: memory_times_wf times mem_mid)\n      (MEMWFTGT: memory_times_wf times mem_tgt)\n      (PAST: forall tid lang st lc\n                    (GET: IdentMap.find tid ths_tgt = Some (existT _ lang st, lc)),\n          (<<CONSISTENT: past_consistent times mem_src (Thread.mk lang st lc sc_tgt mem_tgt)>>) \\/\n          ((<<PROM: forall loc ts, ~ prom tid loc ts>>) /\\\n           (<<EXTRA: forall loc ts from, ~ extra tid loc ts from>>) /\\\n           (<<EQ: IdentMap.find tid ths_src = IdentMap.find tid ths_mid>>)))\n      (PROML: forall tid loc ts (PROM: prom tid loc ts), List.In (loc, ts) (proml tid))\n    :\n      sim_configuration\n        views prom extra proml\n        (Configuration.mk ths_src sc_src mem_src)\n        (Configuration.mk ths_mid sc_src mem_mid)\n        (Configuration.mk ths_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_configuration.\n\n  Lemma non_time_time_sim_promise self extra prom_src prom_tgt\n        (SIM: LocalPFThread.sim_promise L times self extra prom_src prom_tgt)\n    :\n      LocalPFThreadTime.sim_promise L times self extra prom_src prom_tgt.\n  Proof.\n    inv SIM. econs; eauto. i.\n    specialize (sim_promise_contents loc ts).\n    inv sim_promise_contents; econs; eauto.\n  Qed.\n\n  Lemma non_time_time_sim_configuration c_src c_mid c_tgt\n        views prom extra proml\n        (SIM: LocalPFSim.sim_configuration L times (fun _ => True) views prom extra proml c_src c_mid c_tgt)\n    :\n      sim_configuration views prom extra proml c_src c_mid c_tgt.\n  Proof.\n    inv SIM. econs; eauto.\n    { i. clear - THSPF. specialize (THSPF tid). unfold option_rel in *. des_ifs.\n      dep_inv THSPF. econs; eauto. inv LOCAL. econs.\n      eapply non_time_time_sim_promise; eauto. }\n    { i. exploit BOT; eauto. i. des. split; auto. }\n    { i. destruct (IdentMap.find tid ths_tgt) eqn:TIDTGT.\n      { destruct p as [[lang st] lc]. exploit CONSISTENT; eauto. i.\n        eapply x in PROM. eauto. }\n      { specialize (THSPF tid). specialize (THSJOIN tid).\n        unfold option_rel in *. des_ifs. eapply BOT in Heq1.\n        des. exfalso. eapply PROM0; eauto. }\n    }\n  Qed.\n\n  Definition remember_first_promise_thread lang st\n             prom_self extra_self lc_src lc_mid views sc\n             loc to mem_src mem_mid extra_others prom_others\n             (LOCAL: sim_local L times prom_self extra_self lc_src lc_mid)\n             (WF: Local.wf lc_src mem_src)\n             (MEMORY: sim_memory L times (prom_others \\\\2// prom_self) (extra_others \\\\3// extra_self) mem_src mem_mid)\n             (FORGET: prom_self loc to)\n             (FIRST: forall ts (FORGET: (prom_others \\\\2// prom_self) loc ts), Time.le to ts)\n             (JOINEDMEM: joined_memory views mem_mid)\n             (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n             (EXCLUSIVE: forall loc' ts' (OTHER: prom_others loc' ts'),\n                 exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n             (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n                 (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n\n             (MWFSRC: Memory.closed mem_src)\n             (MWFTGT: Memory.closed mem_mid)\n             (WFTGT: Local.wf lc_mid mem_mid)\n    :\n      exists lc_src' mem_src' prom_self' extra_self' tr,\n        (<<PROM: prom_self' = fun l t => prom_self l t /\\ (loc, to) <> (l, t)>>) /\\\n        (<<STEPS: @Trace.steps lang tr (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st lc_src' sc mem_src')>>) /\\\n        (<<LOCAL: sim_local L times prom_self' extra_self' lc_src' lc_mid>>) /\\\n        (<<MEMORY: sim_memory L times (prom_others \\\\2// prom_self') (extra_others \\\\3// extra_self') mem_src' mem_mid>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr>>) /\\\n        (<<NNIL: tr <> []>>)\n  .\n  Proof.\n    inv LOCAL.\n    set (MEM := (sim_memory_contents MEMORY) loc to).\n    set (PROM := (sim_promise_contents PROMS) loc to).\n    inv PROM; clarify; try by (exfalso; eapply NPROM; right; eauto).\n    symmetry in H0. symmetry in H.\n    dup H. eapply WFTGT in H1.\n\n    assert (MLE0: Memory.le prom_src mem_src).\n    { eapply WF. }\n    assert (NBOT: to <> Time.bot).\n    { dup H0. eapply memory_get_ts_strong in H0. des; clarify.\n      inv WF. erewrite BOT in H2. ss. }\n\n    assert (NSELF: ~ (prom_others \\\\2// prom_self) loc from_src).\n    { ii. dup H2. hexploit FIRST; eauto.\n      i. eapply memory_get_ts_strong in H0. des; clarify. timetac.\n    }\n\n    exploit (sim_promise_extra PROMS); eauto. i. des.\n    exploit Memory.remove_exists; try apply GET. intros [prom_src1 REMOVEPROM1].\n    exploit Memory.remove_exists_le; try apply REMOVEPROM1; eauto. intros [mem_src1 REMOVEMEM1].\n    hexploit PreReserve.memory_remove_le_preserve; try apply MLE0; eauto. intros MLE1.\n    assert (PROMISE1: Local.promise_step (Local.mk tvw prom_src) mem_src loc to to0 Message.reserve (Local.mk tvw prom_src1) mem_src1 Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    exploit (@Memory.remove_exists prom_src1 loc from_src to Message.reserve).\n    { eapply Memory.remove_get1 in H0; eauto. des; clarify.\n      dup GET. eapply memory_get_ts_strong in GET0. des; clarify. timetac.\n    } intros [prom_src2 REMOVEPROM2].\n    exploit Memory.remove_exists_le; try apply REMOVEPROM2; eauto. intros [mem_src2 REMOVEMEM2].\n    hexploit PreReserve.memory_remove_le_preserve; try apply MLE1; eauto. intros MLE2.\n    assert (PROMISE2: Local.promise_step (Local.mk tvw prom_src1) mem_src1 loc from_src to Message.reserve (Local.mk tvw prom_src2) mem_src2 Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    exploit (@Memory.add_exists mem_src2 loc from_tgt to (Message.concrete val released)).\n    { ii. inv LHS. inv RHS. ss.\n      erewrite Memory.remove_o in GET2; eauto.\n      erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o. guardH o0.\n      destruct (Time.le_lt_dec x from_src).\n      { hexploit memory_get_disjoint_strong.\n        { eapply GET2. }\n        { eapply WF. eapply H0. }\n        i. des.\n        { subst. ss. destruct o; ss. }\n        { ss. set (MEM0:=(sim_memory_contents MEMORY) loc to2).\n          rewrite GET2 in MEM0. inv MEM0.\n          - exploit Memory.get_disjoint.\n            { symmetry. eapply H5. }\n            { eapply H1. }\n            i. des; clarify.\n            + timetac.\n            + eapply x1.\n              * instantiate (1:=to2). econs; ss.\n                { eapply TimeFacts.le_lt_lt.\n                  { eapply FROM1. } eapply TimeFacts.lt_le_lt.\n                  { eapply FROM0. }\n                  { eapply TO0. }\n                }\n                { refl. }\n              * econs; ss.\n                { eapply TimeFacts.lt_le_lt.\n                  { eapply FROM. }\n                  { eapply TO0. }\n                }\n                { left. auto. }\n          - eapply FIRST in PROM. timetac.\n          - eapply MEMORY in EXTRA. des.\n            eapply FIRST in FORGET0. eapply Time.lt_strorder.\n            eapply TimeFacts.lt_le_lt.\n            { eapply TS2. } etrans.\n            { left. eapply TS1. }\n            { eauto. }\n        }\n        { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply FROM0. } etrans.\n          { eapply TO. }\n          { eauto. }\n        }\n      }\n      { hexploit Memory.get_disjoint.\n        { eapply GET2. }\n        { eapply WF. eapply H0. }\n        i. des; subst; ss.\n        { destruct o; ss. }\n        { eapply H2; econs; eauto. }\n      }\n    }\n    { eapply memory_get_ts_strong in H. des; clarify. }\n    { eapply WFTGT in H. eapply MWFTGT in H. des. auto. } intros [mem_src3 ADDMEM3].\n    exploit Memory.add_exists_le; try apply ADDMEM3; eauto. intros [prom_src3 ADDPROM3].\n    hexploit PreReserve.memory_add_le_preserve; try apply MLE2; eauto. intros MLE3.\n    assert (PROMISE3': Memory.promise prom_src2 mem_src2 loc from_tgt to (Message.concrete val released) prom_src3 mem_src3 Memory.op_kind_add).\n    { econs; eauto.\n      - eapply MWFTGT in H1. des. auto.\n      - i. clarify. erewrite Memory.remove_o in GET0; eauto. des_ifs.\n        erewrite Memory.remove_o in GET0; eauto. des_ifs. ss. des; clarify.\n        exploit memory_get_from_inj.\n        { eapply GET0. }\n        { eapply WF in GET. eapply GET. }\n        i. des; clarify.\n    }\n\n    assert (PROMISE3: Local.promise_step (Local.mk tvw prom_src2) mem_src2 loc from_tgt to (Message.concrete val released) (Local.mk tvw prom_src3) mem_src3 Memory.op_kind_add).\n    { econs; eauto. econs; eauto. destruct released; eauto. econs.\n      eapply JOINEDMEM in H1. des.\n      eapply joined_view_semi_closed in JOINED0; eauto.\n      2: { eapply MWFSRC. }\n      eapply semi_closed_view_add; cycle 1; eauto.\n      eapply concrete_promised_le_semi_closed_view in JOINED0; eauto. ii.\n      eapply concrete_promised_increase_promise; eauto.\n      eapply concrete_promised_increase_promise; eauto.\n    }\n\n    destruct (classic (extra_self loc to0 to)) as [EXTRA|NEXTRA0].\n    { exists (Local.mk tvw prom_src3), mem_src3,\n      (fun l t => prom_self l t /\\ (loc, to) <> (l, t)),\n      (fun l t => if (loc_ts_eq_dec (l, t) (loc, to0)) then (fun _ => False) else (extra_self l t)).\n      esplits; try eassumption.\n      { auto. }\n      { econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 1.\n      }\n      { econs. econs.\n        - i. erewrite (@Memory.add_o prom_src3); eauto.\n          erewrite (@Memory.remove_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src1); eauto. des_ifs.\n          + ss. des; clarify. exfalso. eapply NEXTRA; eauto.\n          + ss. des; clarify.\n            set (PROM:=(sim_promise_contents PROMS) loc to0).\n            inv PROM; clarify; try by (exfalso; eapply NEXTRA0; eauto).\n            econs; eauto. ii. des; ss.\n          + ss. des; clarify. erewrite H. econs 2; eauto. ii. des; clarify.\n          + ss. guardH o. guardH o0.\n            set (PROM:=(sim_promise_contents PROMS) loc0 ts). inv PROM; clarify.\n            * econs 1; eauto. ii. des; auto.\n            * econs 2; eauto. ii. des; auto.\n            * econs 3; eauto. ii. des; auto.\n            * econs 4; eauto. split; auto. ii. destruct o0; clarify.\n            * econs 5; eauto. ii. des; ss.\n        - i. des_ifs. guardH o.\n          dup EXTRA0. eapply PROMS in EXTRA0. des. splits; auto.\n          ii. clarify. ss.\n          exploit sim_memory_extra_inj.\n          { eauto. }\n          { right. eapply EXTRA. }\n          { right. eapply EXTRA1. }\n          ii. destruct o; clarify.\n        - i. des. dup SELF. eapply PROMS in SELF1. des. exists to1. split; auto.\n          red. erewrite Memory.add_o; eauto.\n          erewrite Memory.remove_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n          + ss. des; clarify. exfalso. eapply NSELF; eauto. right. auto.\n          + ss. des; clarify.\n      }\n      { econs.\n        - i. erewrite (@Memory.add_o mem_src3); eauto.\n          erewrite (@Memory.remove_o mem_src2); eauto.\n          erewrite (@Memory.remove_o mem_src1); eauto. des_ifs.\n          + ss. des; clarify. exfalso. eapply NSELF; eauto. right. auto.\n          + ss. des; clarify.\n            set (MEM0:=(sim_memory_contents MEMORY) loc to0). inv MEM0; ss.\n            * econs 1; eauto.\n              { ii. eapply NPROM. unguard. destruct H2; des; auto. }\n              { ii. destruct H2; ss. eapply NEXTRA0. left. eauto. }\n            * exfalso. eapply NEXTRA0. right. eauto.\n            * exfalso. eapply NEXTRA0. right. eauto.\n            * econs 1; eauto.\n              { ii. eapply NPROM. unguard. destruct H2; des; auto. }\n              { ii. destruct H2; ss.\n                eapply EXCLUSIVEEXTRA in H2. inv H2. clarify. }\n          + ss. des; clarify. erewrite H1. econs 2; eauto.\n            * ii. destruct H2; des; clarify.\n              eapply EXCLUSIVE in H2. des. inv UNCH. clarify.\n            * ii. destruct H2; clarify.\n              { eapply EXCLUSIVEEXTRA in H2. inv H2. clarify. }\n              { eapply NEXTRA; eauto. }\n            * refl.\n            * i. eapply eq_lb_time.\n          + guardH o. guardH o0.\n            set (MEM0:=(sim_memory_contents MEMORY) loc0 ts). inv MEM0; ss.\n            * econs 1; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n            * econs 2; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n            * econs 3; eauto. destruct PROM.\n              { left. auto. }\n              { right. splits; auto. ii. destruct o0; des; clarify. }\n            * econs 4; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n        - i. des_ifs.\n          + ss. des; clarify. destruct EXTRA0; ss.\n            eapply EXCLUSIVEEXTRA in H2. inv H2. clarify.\n          + guardH o. dup EXTRA0. eapply (sim_memory_wf MEMORY) in EXTRA0.\n            des. splits; auto. destruct FORGET0.\n            * left. auto.\n            * right. splits; auto. ii. clarify. ss.\n              destruct o; ss; clarify.\n              exploit sim_memory_extra_inj.\n              { eauto. }\n              { eapply EXTRA1. }\n              { right. eauto. }\n              i. clarify.\n      }\n      { repeat econs; eauto. }\n      { ss. }\n    }\n    { assert (NOEXTRA: forall t, ~ (extra_others \\\\3// extra_self) loc t to).\n      { ii. destruct H2.\n        { eapply EXCLUSIVEEXTRA in H2. inv H2. ss.\n          dup GET. eapply WF in GET. exploit memory_get_from_inj.\n          { eapply GET. }\n          { eapply GET0. }\n          i. des; clarify.\n        }\n        set (PROM := (sim_promise_contents PROMS) loc t).\n        inv PROM; try by (eapply NEXTRA1; eauto).\n        exploit (sim_memory_wf MEMORY).\n        { right. eapply EXTRA. }\n        i. des. exploit UNIQUE.\n        { right. eapply H2. } i. clarify.\n        exploit memory_get_from_inj.\n        { symmetry. eapply H4. }\n        { eapply GET. }\n        i. des; clarify.\n      }\n\n      exploit (@Memory.add_exists mem_src3 loc to to0 Message.reserve).\n      { i. erewrite Memory.add_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto. des_ifs.\n        { ss. des; clarify. symmetry. eapply Interval.disjoint_imm. }\n        exploit Memory.get_disjoint.\n        { eapply WF. eapply GET. }\n        { eapply GET2. } i. des; clarify.\n      }\n      { eapply memory_get_ts_strong in GET. des; clarify. }\n      { econs; eauto. } intros [mem_src4 ADDMEM4].\n      exploit Memory.add_exists_le; try apply ADDMEM4; eauto. intros [prom_src4 ADDPROM4].\n\n      assert (PROMISE4: Local.promise_step (Local.mk tvw prom_src3) mem_src3 loc to to0 Message.reserve (Local.mk tvw prom_src4) mem_src4 Memory.op_kind_add).\n      { econs; eauto. econs; eauto. ss. }\n\n      exists (Local.mk tvw prom_src4), mem_src4, (fun l t => prom_self l t /\\ (loc, to) <> (l, t)), extra_self.\n      esplits; try eassumption.\n      { auto. }\n      { econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 2; [..|ss].\n        { econs; eauto. econs; eauto. }\n        econs 1.\n      }\n      { econs. econs.\n        - i. erewrite (@Memory.add_o prom_src4); eauto.\n          erewrite (@Memory.add_o prom_src3); eauto.\n          erewrite (@Memory.remove_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src1); eauto. des_ifs.\n          + ss. des; clarify.\n            set (PROM:=(sim_promise_contents PROMS) loc to0).\n            rewrite GET in *. inv PROM; clarify.\n            * econs 2; eauto. ii. des; clarify.\n            * econs 3; eauto. ii. des; clarify.\n            * econs 4; eauto. splits; auto. ii. clarify.\n              eapply memory_get_ts_strong in H0. des; clarify. timetac.\n          + ss. des; clarify. rewrite H. econs 2; eauto. ii. des; clarify.\n          + ss. guardH o. guardH o0.\n            set (PROM:=(sim_promise_contents PROMS) loc0 ts). inv PROM; clarify.\n            * econs 1; eauto. ii. des; auto.\n            * econs 2; eauto. ii. des; auto.\n            * econs 3; eauto. ii. des; auto.\n            * econs 4; eauto. split; auto. ii. destruct o0; clarify.\n            * econs 5; eauto. ii. des; ss.\n        - i. dup EXTRA. eapply PROMS in EXTRA. des. splits; auto.\n          ii. clarify. eapply NOEXTRA. right. eauto.\n        - i. des. dup SELF. eapply PROMS in SELF. des. exists to1. split; auto.\n          red. erewrite Memory.add_o; eauto. erewrite Memory.add_o; eauto.\n          erewrite Memory.remove_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n          + ss. des; clarify.\n          + ss. des; clarify. exfalso. eapply NSELF; eauto. right. auto.\n      }\n      { econs.\n        - i. erewrite (@Memory.add_o mem_src4); eauto.\n          erewrite (@Memory.add_o mem_src3); eauto.\n          erewrite (@Memory.remove_o mem_src2); eauto.\n          erewrite (@Memory.remove_o mem_src1); eauto. des_ifs.\n          + ss. des; clarify.\n            set (MEM0:=(sim_memory_contents MEMORY) loc to0). inv MEM0; ss.\n            * eapply WF in GET. rewrite GET in *. clarify.\n            * eapply WF in GET. rewrite GET in *. clarify.\n              econs 2; eauto. ii. eapply NPROM. unguard. des; auto.\n            * eapply WF in GET. rewrite GET in *. clarify. econs 3; eauto.\n              unguard. des; auto. right. splits; auto. ii. clarify.\n              eapply memory_get_ts_strong in GET. des; clarify. timetac.\n            * eapply WF in GET. rewrite GET in *. clarify.\n              exfalso. eapply NOEXTRA. eauto.\n          + ss. des; clarify. erewrite H1. econs 2; eauto.\n            * ii. destruct H2; des; clarify.\n              eapply EXCLUSIVE in H2. des. inv UNCH. clarify.\n            * ii. destruct H2; clarify.\n              { eapply EXCLUSIVEEXTRA in H2. inv H2. clarify. }\n              { eapply NEXTRA; eauto. }\n            * refl.\n            * i. eapply eq_lb_time.\n          + guardH o. guardH o0.\n            set (MEM0:=(sim_memory_contents MEMORY) loc0 ts). inv MEM0; ss.\n            * econs 1; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n            * econs 2; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n            * econs 3; eauto. destruct PROM.\n              { left. auto. }\n              { right. splits; auto. ii. destruct o0; des; clarify. }\n            * econs 4; eauto. ii. eapply NPROM. unguard. destruct H2; des; auto.\n        - i. dup EXTRA. eapply (sim_memory_wf MEMORY) in EXTRA.\n          des. splits; auto. destruct FORGET0.\n          + left. auto.\n          + right. splits; auto. ii. clarify.\n            exfalso. eapply NOEXTRA; eauto.\n      }\n      { repeat econs; eauto. }\n      { ss. }\n    }\n  Qed.\n\n  Lemma sim_configuration_forget_promise_exist\n        views prom extra proml c_src c_mid c_tgt\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        tid loc ts\n        (PROM: prom tid loc ts)\n    :\n      exists lang st lc_src from msg,\n        (<<TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<PROMISE: Memory.get loc ts (Local.promises lc_src) = Some (from, msg)>>)\n  .\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_src)) as\n        [[[lang st] lc_src]|] eqn:TID.\n    { inv SIM. specialize (THSPF tid). setoid_rewrite TID in THSPF. ss. des_ifs.\n      inv THSPF. inv LOCAL. set (CNT:=(sim_promise_contents PROMS) loc ts).\n      inv CNT; ss. esplits; eauto. }\n    { exfalso. inv SIM. eapply BOT in TID. des. eapply PROM0; eauto. }\n  Qed.\n\n  Lemma sim_configuration_extra_promise_exist\n        views prom proml extra c_src c_mid c_tgt\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        tid loc ts from\n        (PROM: extra tid loc ts from)\n    :\n      exists lang st lc_src,\n        (<<TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<PROMISE: Memory.get loc ts (Local.promises lc_src) = Some (from, Message.reserve)>>)\n  .\n  Proof.\n    destruct (IdentMap.find tid (Configuration.threads c_src)) as\n        [[[lang st] lc_src]|] eqn:TID.\n    { inv SIM. specialize (THSPF tid). setoid_rewrite TID in THSPF. ss. des_ifs.\n      inv THSPF. inv LOCAL. set (CNT:=(sim_promise_contents PROMS) loc ts).\n      inv CNT; try by (exfalso; eapply NEXTRA; eauto).\n      exploit ((sim_memory_wf MEMPF) loc from ts); eauto. i. des.\n      exploit (UNIQUE from0); eauto. i. subst. esplits; eauto. }\n    { exfalso. inv SIM. eapply BOT in TID. des. eapply EXTRA; eauto. }\n  Qed.\n\n  Lemma sim_configuration_forget_exclusive\n        views prom extra proml c_src c_mid c_tgt\n        tid lang st lc_src\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src))\n    :\n      forall loc ts\n             (PROM: all_promises (fun tid' => tid <> tid') prom loc ts),\n      exists (from : Time.t) (msg : Message.t),\n        (<<UNCH: unchangable (Configuration.memory c_src) (Local.promises lc_src) loc ts from msg>>).\n  Proof.\n    ii. dup WF_SRC. inv WF_SRC.\n    inv PROM. exploit sim_configuration_forget_promise_exist; eauto. i. des.\n    dup TID1. eapply WF in TID1. inv TID1. esplits. econs.\n    { eapply PROMISES. eauto. }\n    { inv WF. exploit DISJOINT; eauto. intros DISJ. inv DISJ.\n      destruct (Memory.get loc ts (Local.promises lc_src)) as [[from' msg']|] eqn:GET; auto.\n      exfalso. inv DISJOINT0. exploit DISJOINT1; eauto. i. des.\n      eapply memory_get_ts_strong in GET. des; subst; ss.\n      eapply memory_get_ts_strong in  PROMISE. des; subst; ss.\n      eapply x; eauto.\n      { econs; [|refl]. auto. }\n      { econs; ss. refl. }\n    }\n  Qed.\n\n  Lemma sim_configuration_extra_exclusive\n        views prom extra proml c_src c_mid c_tgt\n        tid lang st lc_src\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WF_SRC: Configuration.wf c_src)\n        (TID: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src))\n    :\n      forall loc ts from\n             (EXTRA: all_extra (fun tid' => tid <> tid') extra loc ts from),\n        (<<UNCH: unchangable (Configuration.memory c_src) (Local.promises lc_src) loc ts from Message.reserve>>).\n  Proof.\n    ii. dup WF_SRC. inv WF_SRC.\n    inv EXTRA. exploit sim_configuration_extra_promise_exist; eauto. i. des.\n    dup TID1. eapply WF in TID1. inv TID1. esplits. econs.\n    { eapply PROMISES. eauto. }\n    { inv WF. exploit DISJOINT; eauto. intros DISJ. inv DISJ.\n      destruct (Memory.get loc ts (Local.promises lc_src)) as [[from' msg']|] eqn:GET; auto.\n      exfalso. inv DISJOINT0. exploit DISJOINT1; eauto. i. des.\n      eapply memory_get_ts_strong in GET. des; subst; ss.\n      eapply memory_get_ts_strong in  PROMISE. des; subst; ss.\n      eapply x; eauto.\n      { econs; [|refl]. auto. }\n      { econs; ss. refl. }\n    }\n  Qed.\n\n  Lemma sim_configuration_sim_thread views prom extra proml\n        (c_src c_mid c_tgt: Configuration.t)\n        tid lang st lc_tgt\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (TIDTGT: IdentMap.find tid (Configuration.threads c_tgt) = Some (existT _ lang st, lc_tgt))\n    :\n      exists lc_src lc_mid,\n        (<<TIDSRC: IdentMap.find tid (Configuration.threads c_src) = Some (existT _ lang st, lc_src)>>) /\\\n        (<<TIDMID: IdentMap.find tid (Configuration.threads c_mid) = Some (existT _ lang st, lc_mid)>>) /\\\n        (<<SIM: sim_thread\n                  views\n                  (prom tid)\n                  (all_promises (fun tid' => tid <> tid') prom)\n                  (extra tid)\n                  (all_extra (fun tid' => tid <> tid') extra)\n                  (Thread.mk _ st lc_src (Configuration.sc c_src) (Configuration.memory c_src))\n                  (Thread.mk _ st lc_mid (Configuration.sc c_mid) (Configuration.memory c_mid))\n                  (Thread.mk _ st lc_tgt (Configuration.sc c_tgt) (Configuration.memory c_tgt))>>).\n  Proof.\n    inv SIM. ss.\n    specialize (THSJOIN tid). specialize (THSPF tid).\n    setoid_rewrite TIDTGT in THSJOIN. unfold option_rel in THSJOIN. des_ifs.\n    unfold option_rel in THSPF. des_ifs.\n    destruct p as [[lang_mid st_mid] lc_mid]. destruct p0 as [[lang_src st_src] lc_src].\n    dup THSPF. dup THSJOIN.\n    dep_inv THSPF0. dep_inv THSJOIN0. esplits; eauto. econs; eauto.\n    replace (all_promises (fun tid' => tid <> tid') prom \\\\2// prom tid) with\n        (all_promises (fun _ => True) prom); cycle 1.\n    { extensionality loc. extensionality ts.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n      { inv H. destruct (Ident.eq_dec tid tid0).\n        { subst. right. auto. }\n        { left. econs; eauto. }\n      }\n      { destruct H.\n        { inv H. econs; eauto. }\n        { econs; eauto. }\n      }\n    }\n    replace (all_extra (fun tid' => tid <> tid') extra \\\\3// extra tid) with\n        (all_extra (fun _ => True) extra); cycle 1.\n    { extensionality loc. extensionality ts. extensionality from.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n      { inv H. destruct (Ident.eq_dec tid tid0).\n        { subst. right. auto. }\n        { left. econs; eauto. }\n      }\n      { destruct H.\n        { inv H. econs; eauto. }\n        { econs; eauto. }\n      }\n    }\n    auto.\n  Qed.\n\n  Lemma remember_first_promise views prom extra proml\n        c_src c_mid c_tgt tid loc ts\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n        (FORGET: prom tid loc ts)\n        (FIRST: forall tid' ts' (FORGET: prom tid' loc ts'), Time.le ts ts')\n    :\n      exists extra' c_src',\n        (<<STEP: Configuration.step MachineEvent.silent tid c_src c_src'>>) /\\\n        (<<SIM: sim_configuration views (fun tid' => if (Ident.eq_dec tid' tid) then (fun l t => prom tid l t /\\ (loc, ts) <> (l, t)) else (prom tid')) extra' proml c_src' c_mid c_tgt>>).\n  Proof.\n    dup SIM. inv SIM0.\n    destruct (IdentMap.find tid ths_tgt) eqn:TIDTGT.\n    2: {\n      specialize (THSJOIN tid). specialize (THSPF tid).\n      rewrite TIDTGT in *. unfold option_rel in *. des_ifs.\n      eapply BOT in Heq0. des. exfalso. eapply PROM; eauto. }\n    destruct p as [[lang st] lc_tgt].\n    hexploit PAST; eauto. i. des.\n    2: { exfalso. eapply PROM; eauto. }\n    hexploit sim_configuration_sim_thread; eauto. i. des. ss. dep_inv SIM0.\n    generalize (sim_configuration_forget_exclusive SIM WFSRC TIDSRC). intros EXCLPROM.\n    generalize (sim_configuration_extra_exclusive SIM WFSRC TIDSRC). intros EXCLEXTRA.\n    exploit remember_first_promise_thread; eauto.\n    { eapply WFSRC in TIDSRC. eauto. }\n    { ii. destruct FORGET0; eauto. inv H. eapply FIRST; eauto. }\n    { eapply WFMID. }\n    { eapply WFSRC. }\n    { eapply WFMID. }\n    { eapply WFMID; eauto. } ss. i. des.\n\n    exploit Trace.steps_future; eauto.\n    { eapply WFSRC; eauto. }\n    { eapply WFSRC. }\n    { eapply WFSRC. } ss. i. des.\n\n    exploit sim_promise_weak_strengthen.\n    { eauto. }\n    { eapply MEMORY. }\n    { eapply WFMID; eauto. }\n    { eapply WF2. }\n    { eapply WF2. }\n    { eapply WF2. }\n    { inv LOCAL. eauto. }\n    { eauto. } i. des.\n    destruct lc_src'. eapply reserve_future_memory_steps in FUTURE. des. ss.\n\n    exploit Trace.steps_trans.\n    { eapply STEPS. }\n    { eapply STEPS0. }\n    intros STEPS1.\n    exploit Trace.steps_future; try apply STEPS1; eauto.\n    { ss. eapply WFSRC; eauto. }\n    { eapply WFSRC. }\n    { eapply WFSRC. } ss. i. des.\n\n    assert (SILENT1: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) (tr ++ tr0)).\n    { eapply Forall_app; eauto. eapply reserving_trace_silent; eauto. }\n\n    hexploit (list_match_rev (tr ++ tr0)). i. des.\n    { eapply app_eq_nil in H. des; ss. }\n    rewrite H in *.\n    dup STEPS1. eapply Trace.steps_separate in STEPS1. des.\n    inv STEPS4; clarify. inv STEPS1; clarify.\n    eapply Forall_app_inv in SILENT1. des. inv FORALL2. ss.\n    eapply Trace.silent_steps_tau_steps in STEPS3; eauto.\n\n    hexploit sim_thread_consistent.\n    { instantiate (3:=Thread.mk _ st (Local.mk tview prom_src') sc_src mem_src'0).\n      eapply past_consistent_mon.\n      { eauto. }\n      { refl. }\n      { eapply Memory.future_future_weak; eauto. }\n    }\n    { econs.\n      { econs; eauto. }\n      { destruct lc_mid. ss. inv LOCAL. eauto. }\n      { eauto. }\n      { eauto. }\n      { eapply SC. }\n    }\n    { ss. }\n    { eapply WFMID. }\n    { eapply WFTGT. }\n    { eauto. }\n    { eapply WFMID. }\n    { eapply WFTGT. }\n    { inv LOCAL. ss. }\n    { inv LOCAL. ss. eapply WFMID; eauto. }\n    { eapply WFTGT; eauto. }\n    { eauto. }\n    { eauto. }\n    { ss. i. eapply EXCLPROM in OTHER. des.\n      eapply unchangable_trace_steps_increase in STEPS2; eauto.\n    }\n    { ss. i. eapply EXCLEXTRA in OTHER. des.\n      eapply unchangable_trace_steps_increase in STEPS2; eauto.\n    }\n    { s. ii. inv OTHER.\n      specialize (THSPF tid0). unfold option_rel in THSPF. des_ifs.\n      2: { exfalso. eapply BOT in Heq. des. eapply PROM; eauto. }\n      inv THSPF. inv LOCAL0.\n      set (PROM:=(sim_promise_contents PROMS0) loc0 to). inv PROM; clarify.\n      destruct st0 as [lang0 st0].\n      inv WFMID. inv WF. ss. inv WF1. exploit DISJOINT; eauto. i.\n      inv H0. inv x. inv DISJOINT0. hexploit DISJOINT1; eauto. i. des.\n      eapply H0; eauto. econs; [|refl]. ss.\n      symmetry in H7. eapply memory_get_ts_strong in H7. des; clarify.\n      inv ITV. ss. inv FROM.\n    }\n    { ss. i. eapply Forall_impl; [|eapply JOINED].\n      i. ss. eapply semi_closed_view_future; eauto.\n      eapply Memory.future_future_weak; eauto.\n    }\n    { inv LOCAL. ss. eapply WFMID in TIDMID; eauto. }\n    { ss. eapply WFMID; eauto. }\n    { eapply WFMID; eauto. } i.\n\n    exists (fun tid' => if (Ident.eq_dec tid' tid) then extra_self' else (extra tid')). esplits.\n    { replace MachineEvent.silent with (ThreadEvent.get_machine_event e).\n      econs 2; eauto. ii. clarify. }\n    { econs; eauto.\n      - i. erewrite IdentMap.gsspec. des_ifs. setoid_rewrite TIDMID.\n        ss. econs; eauto. inv LOCALPF. inv LOCAL. econs; eauto.\n        eapply sim_promise_strong_sim_promise; eauto.\n      - ss. i. erewrite IdentMap.gsspec in NONE. des_ifs.\n        eapply BOT in NONE. des. splits; auto.\n      - match goal with\n        | _:sim_memory L times ?proms0 ?extra0 mem_src'0 mem_mid\n          |- sim_memory L times ?proms1 ?extra1 mem_src'0 mem_mid =>\n          (replace proms1 with proms0); [replace extra1 with extra0|]; eauto\n        end.\n        + extensionality l. extensionality from. extensionality to.\n          apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n          { destruct H2.\n            { inv H2. eapply all_extra_intro with (tid:=tid0); ss. des_ifs. }\n            { eapply all_extra_intro with (tid:=tid); ss. des_ifs. }\n          }\n          { inv H2. unguard. des_ifs; auto. eauto. }\n        + extensionality l. extensionality to.\n          apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i.\n          { destruct H2.\n            { inv H2. eapply all_promises_intro with (tid:=tid0); ss. des_ifs. }\n            { eapply all_promises_intro with (tid:=tid); ss. des_ifs. }\n          }\n          { inv H2. unguard. des_ifs; auto. eauto. }\n      - ss. i. eapply Forall_impl; [|eapply JOINED].\n        i. ss. eapply semi_closed_view_future; eauto.\n        eapply Memory.future_future_weak; eauto.\n      - i. exploit PAST; eauto. i. des.\n        { left. eapply past_consistent_mon; eauto.\n          { refl. }\n          { eapply Memory.future_future_weak; eauto. }\n        }\n        { right. rewrite IdentMap.gsspec. des_ifs.\n          dep_clarify. exfalso. eapply PROM; eauto.\n        }\n      - i. eapply PROML. des_ifs. des; auto.\n    }\n  Qed.\n\n  Lemma first_promise_exists (l: list (Ident.t * Loc.t * Time.t)) (loc: Loc.t):\n    (forall tid ts, ~ List.In (tid, loc, ts) l) \\/\n    (exists tid ts,\n        List.In (tid, loc, ts) l /\\\n        (forall tid' ts' (IN: List.In (tid', loc, ts') l), Time.le ts ts')).\n  Proof.\n    induction l.\n    { left. ii. ss. }\n    destruct a as [[tid' loc'] ts']. destruct (Loc.eq_dec loc loc').\n    { clarify. des.\n      - right. exists tid', ts'. ss. esplits; eauto.\n        i. des; clarify.\n        + refl.\n        + exfalso. eapply IHl; eauto.\n      - right. destruct (Time.le_lt_dec ts ts').\n        + exists tid, ts. ss. esplits; eauto.\n          i. des; clarify. eapply IHl0; eauto.\n        + exists tid', ts'. ss. esplits; eauto.\n          i. des; clarify.\n          * refl.\n          * eapply IHl0 in IN. etrans; eauto. left. auto.\n    }\n    { des.\n      - left. ii. ss. des; clarify. eapply IHl; eauto.\n      - right. exists tid, ts. ss. esplits; eauto.\n        i. des; clarify. eapply IHl0; eauto.\n    }\n  Qed.\n\n  Lemma filter_length_le A f (l: list A)\n    :\n      length (filter f l) <= length l.\n  Proof.\n    induction l; ss. des_ifs; ss.\n    - eapply le_n_S; eauto.\n    - econs. eauto.\n  Qed.\n\n  Lemma filter_length_decrease A f (l: list A) a\n        (IN: List.In a l)\n        (SAT: f a = false)\n    :\n      length (filter f l) < length l.\n  Proof.\n    revert a IN SAT. induction l; i; ss. des.\n    - clarify. eapply Lt.le_lt_n_Sm.\n      eapply filter_length_le.\n    - des_ifs.\n      + ss. eapply Lt.lt_n_S; eauto.\n      + eapply Lt.le_lt_n_Sm.\n        eapply filter_length_le.\n  Qed.\n\n  Lemma remember_list_decrease views prom extra proml pl\n        c_src c_mid c_tgt\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (COMPLETE: forall tid loc to (PROM: prom tid loc to), List.In (tid, loc, to) pl)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      pl = [] \\/\n      exists tid pl' prom' extra' c_src',\n        (<<STEP: Configuration.opt_step MachineEvent.silent tid c_src c_src'>>) /\\\n        (<<SIM: sim_configuration views prom' extra' proml c_src' c_mid c_tgt>>) /\\\n        (<<COMPLETE: forall tid loc to (PROM: prom' tid loc to), List.In (tid, loc, to) pl'>>) /\\\n        (<<DECREASE: length pl' < length pl>>)\n  .\n  Proof.\n    destruct pl as [|[[tid' loc] to'] pl]; auto. right.\n    hexploit (first_promise_exists ((tid', loc, to') :: pl) loc); eauto. i. des.\n    { exfalso. ss. eapply H; eauto. }\n    set (pl':= filter (fun tlt =>\n                         match tlt with\n                         | (tid0, loc0, to0) =>\n                           if Ident.eq_dec tid0 tid then\n                             if loc_ts_eq_dec (loc0, to0) (loc, ts) then false else true\n                           else\n                             true\n                         end) ((tid', loc, to') :: pl)).\n    assert (DECREASE: length pl' < length ((tid', loc, to') :: pl)).\n    { eapply filter_length_decrease.\n      { eapply H. }\n      des_ifs. ss. des; clarify.\n    }\n    exists tid, pl'.\n    destruct (classic (prom tid loc ts)) as [PROM|NPROM].\n    { exploit remember_first_promise; eauto. i. des.\n      exists (fun tid' => if LocSet.Facts.eq_dec tid' tid\n                          then fun l t => prom tid l t /\\ (loc, ts) <> (l, t) else prom tid'), extra', c_src'.\n      esplits; eauto. i. eapply filter_In.\n      des_ifs; des; ss; clarify; eauto.\n    }\n    { exists prom, extra, c_src. esplits; eauto. i.\n      eapply filter_In. splits; auto. des_ifs. ss. des; clarify. }\n  Qed.\n\n  Lemma concat_in A (ls: list (list A)):\n    forall a,\n      List.In a (concat ls) <-> (exists l, List.In l ls /\\ List.In a l).\n  Proof.\n    induction ls; ss.\n    - i. split; i; des; ss.\n    - i. split; i.\n      + eapply List.in_app_or in H. des.\n        * esplits; eauto.\n        * eapply IHls in H. des. esplits; eauto.\n      + eapply List.in_or_app. des; clarify.\n        * auto.\n        * right. eapply IHls; eauto.\n  Qed.\n\n  Lemma remember_all views prom extra proml\n        c_src c_mid c_tgt\n        (SIM: sim_configuration views prom extra proml c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      exists c_src',\n        (<<STEPS: rtc Configuration.tau_step c_src c_src'>>) /\\\n        (<<SIM: sim_configuration views (fun _ _ _ => False) (fun _ _ _ _ => False) proml c_src' c_mid c_tgt>>).\n  Proof.\n    assert (exists (pl: list (Ident.t * Loc.t * Time.t)),\n               forall tid loc to (PROM: prom tid loc to), List.In (tid, loc, to) pl).\n    { set (tids := List.map fst (IdentMap.elements (Configuration.threads c_tgt))).\n      set (promls := List.map (fun tid => List.map (fun locts => (tid, fst locts, snd locts)) (proml tid)) tids).\n      exists (concat promls). i.\n      inv SIM. destruct (IdentMap.find tid ths_tgt) as [[[lang st] lc]|] eqn:TID.\n      2: {\n        specialize (THSPF tid). specialize (THSJOIN tid). unfold option_rel in *.\n        rewrite TID in *. des_ifs.\n        eapply BOT in Heq0. des. exfalso. eapply PROM0; eauto.\n      }\n      eapply PROML in PROM.\n      assert (TIDIN: List.In tid tids).\n      { unfold tids. ss. eapply IdentMap.elements_correct in TID.\n        eapply List.in_map with (f := fst) in TID; eauto. }\n      eapply concat_in.\n      exists (List.map (fun locts => (tid, fst locts, snd locts)) (proml tid)). split.\n      { eapply List.in_map with (f:= fun tid0 => map (fun locts : Loc.t * Time.t => (tid0, fst locts, snd locts)) (proml tid0)) in TIDIN; eauto. }\n      { eapply List.in_map with (f:= fun locts : Loc.t * Time.t => (tid, fst locts, snd locts)) in PROM; eauto. }\n    }\n    des. remember (S (length pl)).\n    assert (LEN: length pl < n).\n    { clarify. } clear Heqn.\n    revert pl LEN prom H c_src extra SIM WFSRC. induction n.\n    { i. destruct pl; inv LEN. }\n    { i. exploit remember_list_decrease; eauto. i. des; clarify.\n      { exists c_src.\n        replace prom with (fun (_: Ident.t) (_: Loc.t) (_: Time.t) => False) in *.\n        { esplits; eauto.\n          match goal with\n          | _:sim_configuration ?views0 ?proms0 ?extra0 ?proml0 ?c_src0 ?c_mid0 ?c_tgt0\n            |- sim_configuration ?views1 ?proms1 ?extra1 ?proml1 ?c_src1 ?c_mid1 ?c_tgt1 =>\n            (replace extra1 with extra0); eauto\n          end.\n          extensionality tid. extensionality loc. extensionality from. extensionality ts.\n          apply Coq.Logic.PropExtensionality.propositional_extensionality.\n          split; i; ss.\n          inv SIM. exploit ((sim_memory_wf MEMPF)).\n          { econs; eauto. }\n          i. des. inv FORGET. ss.\n        }\n        extensionality tid. extensionality loc. extensionality ts.\n        apply Coq.Logic.PropExtensionality.propositional_extensionality. split; i; ss.\n        eapply H; eauto.\n      }\n      exploit (IHn pl'); eauto.\n      { eapply Lt.lt_n_Sm_le in LEN. eapply PeanoNat.Nat.lt_le_trans; eauto. }\n      { eapply Configuration.opt_step_future in STEP; eauto. des. auto. }\n      i. des. exists c_src'0. splits; eauto.\n      inv STEP; eauto. econs; eauto. econs; eauto.\n    }\n  Qed.\n\n  Lemma sim_promises_bot_eq prom_src prom_tgt\n        (SIM: sim_promise_strong L times bot2 bot3 bot3 prom_src prom_tgt)\n    :\n      prom_src = prom_tgt.\n  Proof.\n    eapply Memory.ext. i.\n    set (PROM:=(sim_promise_strong_contents SIM) loc ts). inv PROM; auto.\n    { des; clarify. }\n    { des; clarify. }\n    { des; clarify. }\n  Qed.\n\n  Inductive sim_configuration_strong\n            (tids: Ident.t -> bool)\n            (views: Loc.t -> Time.t -> list View.t)\n    :\n      forall (c_src c_mid c_tgt: Configuration.t), Prop :=\n  | sim_configuration_strong_intro\n      ths_src sc_src mem_src\n      ths_mid mem_mid\n      ths_tgt sc_tgt mem_tgt\n      (THSPF: forall tid,\n          option_rel\n            (if tids tid\n             then sim_statelocal L times bot2 bot3\n             else eq)\n            (IdentMap.find tid ths_src)\n            (IdentMap.find tid ths_mid))\n      (THSJOIN: forall tid,\n          option_rel\n            (JSim.sim_statelocal views)\n            (IdentMap.find tid ths_mid)\n            (IdentMap.find tid ths_tgt))\n      (MEMPF: sim_memory L times bot2 bot3 mem_src mem_mid)\n      (SCPF: TimeMap.le sc_src sc_tgt)\n\n      (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n      (MEMJOIN: SimMemory.sim_memory mem_mid mem_tgt)\n      (MEMWF: memory_times_wf times mem_mid)\n      (MEMWFTGT: memory_times_wf times mem_tgt)\n      (PAST: forall tid lang st lc\n                    (GET: IdentMap.find tid ths_tgt = Some (existT _ lang st, lc)),\n          (<<CONSISTENT: past_consistent times mem_src (Thread.mk lang st lc sc_tgt mem_tgt)>>) \\/\n           (<<EQ: IdentMap.find tid ths_src = IdentMap.find tid ths_mid>>))\n    :\n      sim_configuration_strong\n        tids views\n        (Configuration.mk ths_src sc_src mem_src)\n        (Configuration.mk ths_mid sc_src mem_mid)\n        (Configuration.mk ths_tgt sc_tgt mem_tgt)\n  .\n  Hint Constructors sim_configuration_strong.\n\n  Lemma strengthen_one tid views tids\n        c_src c_mid c_tgt\n        (SIM: sim_configuration_strong tids views c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      exists c_src',\n        (<<STEP: Configuration.opt_step MachineEvent.silent tid c_src c_src'>>) /\\\n        (<<SIM: sim_configuration_strong (fun tid' => if Ident.eq_dec tid' tid then false else tids tid') views c_src' c_mid c_tgt>>).\n  Proof.\n    assert (BOT2: (bot2: Loc.t -> Time.t -> Prop) \\\\2// bot2 = bot2).\n    { extensionality loc. extensionality ts.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality.\n      unguard. split; i; des; ss.\n    }\n    assert (BOT3: (bot3: Loc.t -> Time.t -> Time.t -> Prop) \\\\3// bot3 = bot3).\n    { extensionality loc. extensionality from. extensionality to.\n      apply Coq.Logic.PropExtensionality.propositional_extensionality.\n      unguard. split; i; des; ss.\n    }\n\n    inv SIM. dup THSPF. dup THSJOIN.\n    specialize (THSPF tid). specialize (THSJOIN tid).\n    unfold option_rel in THSPF, THSJOIN. des_ifs.\n    { inv THSPF. dep_inv THSJOIN. hexploit PAST; eauto. i. des.\n      2: {\n        esplits; [econs 1|].\n        econs; eauto.\n        i. specialize (THSPF0 tid0). des_ifs.\n        rewrite EQ. unfold option_rel. des_ifs.\n      }\n      inv LOCAL.\n      exploit (@sim_promise_weak_strengthen L times WO bot2 bot2 bot3 bot3 prom_src prom_tgt mem_src mem_mid).\n      { rewrite BOT2. rewrite BOT3. auto. }\n      { inv WFMID. ss. eapply WF in Heq; eauto. eapply Heq. }\n      { eapply WFSRC in Heq1; eauto. eapply Heq1. }\n      { eapply WFSRC in Heq1; eauto. eapply Heq1. }\n      { eapply WFSRC in Heq1; eauto. eapply Heq1. }\n      { auto. }\n      { auto. }\n      i. des.\n      eapply (@reserve_future_memory_steps lang st0 tvw sc_src) in FUTURE. des.\n      exploit Trace.steps_future; eauto; ss.\n      { eapply WFSRC in Heq1; eauto. }\n      { eapply WFSRC. }\n      { eapply WFSRC. } i. des. ss.\n      eapply Trace.silent_steps_tau_steps in STEPS.\n      2: { eapply reserving_trace_silent; eauto. }\n      eapply rtc_tail in STEPS. des.\n      { esplits.\n        { econs 2. inv STEPS0. inv TSTEP.\n          rewrite <- EVENT. econs 2; eauto.\n          { destruct e; ss. }\n          hexploit sim_thread_consistent.\n          { instantiate (1:=Thread.mk _ st0 lc_tgt0 sc_tgt mem_tgt).\n            instantiate (1:=Thread.mk _ st0 (Local.mk tvw prom_src') sc_src mem_src').\n            eapply past_consistent_mon.\n            { eauto. }\n            { refl. }\n            { eapply Memory.future_future_weak; eauto. }\n          }\n          { econs; eauto. econs; eauto. }\n          { ss. }\n          { eapply WFMID. }\n          { eapply WFTGT. }\n          { eauto. }\n          { eapply WFMID. }\n          { eapply WFTGT. }\n          { eauto. }\n          { inv WFMID. eapply WF in Heq. eauto. }\n          { eapply WFTGT; eauto. }\n          { eauto. }\n          { eauto. }\n          { ss. }\n          { ss. }\n          { ss. }\n          { i. eapply Forall_impl; eauto. i. ss.\n            eapply semi_closed_view_future; eauto.\n            eapply Memory.future_future_weak; eauto.\n          }\n          { inv WFMID. eapply REL in Heq. eauto. }\n          { eapply WFMID. }\n          { eapply WFMID. }\n          eauto.\n        }\n        { rewrite BOT2 in *. rewrite BOT3 in *. auto.\n          econs; eauto.\n          { i. specialize (THSPF0 tid0).\n            rewrite IdentMap.gsspec. ss. des_ifs.\n            rewrite Heq. ss. f_equal. f_equal.\n            eapply sim_promises_bot_eq; eauto.\n          }\n          { i. eapply Forall_impl; eauto. i. ss.\n            eapply semi_closed_view_future; eauto.\n            eapply Memory.future_future_weak; eauto.\n          }\n          { i. exploit PAST; eauto. i. des.\n            { left. eapply past_consistent_mon; eauto.\n              { refl. }\n              { eapply Memory.future_future_weak; eauto. }\n            }\n            { erewrite IdentMap.gsspec. des_ifs; eauto. dep_clarify.\n              left. eapply past_consistent_mon; eauto.\n              { refl. }\n              { eapply Memory.future_future_weak; eauto. }\n            }\n          }\n        }\n      }\n      { esplits; [econs 1|].\n        econs; eauto.\n        i. specialize (THSPF0 tid0). unfold option_rel in *. des_ifs.\n        f_equal. f_equal. eapply sim_promises_bot_eq; eauto.\n        rewrite BOT2 in *. rewrite BOT3 in *. auto.\n      }\n    }\n    { esplits; [econs 1|].\n      econs; eauto.\n      i. specialize (THSPF0 tid0). unfold option_rel in *. des_ifs.\n    }\n    { esplits; [econs 1|].\n      econs; eauto.\n      i. specialize (THSPF0 tid0). unfold option_rel in *. des_ifs.\n    }\n  Qed.\n\n  Lemma strengthen_finite views tidl tids\n        c_src c_mid c_tgt\n        (SIM: sim_configuration_strong tids views c_src c_mid c_tgt)\n        (COMPLETE: forall tid (TIDS: tids tid = true), List.In tid tidl)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      exists c_src',\n        (<<STEPS: rtc Configuration.tau_step c_src c_src'>>) /\\\n        (<<SIM: sim_configuration_strong (fun _ => false) views c_src' c_mid c_tgt>>).\n  Proof.\n    revert tids COMPLETE c_src SIM WFSRC. induction tidl.\n    { i. esplits; [econs 1|]. inv SIM. econs; eauto.\n      i. specialize (THSPF tid). des_ifs. exfalso. eapply COMPLETE; eauto. }\n    i. exploit (@strengthen_one a); eauto. i. des.\n    exploit Configuration.opt_step_future; eauto. i. des.\n    exploit IHtidl; eauto.\n    { i. ss. des_ifs. eapply COMPLETE in TIDS. des; clarify. }\n    i. des. exists c_src'0. splits; eauto. etrans; [|eauto].\n    inv STEP; eauto. econs 2; [|refl]. econs; eauto.\n  Qed.\n\n  Lemma strengthen_all views proml\n        c_src c_mid c_tgt\n        (SIM: sim_configuration views (fun _ _ _ => False) (fun _ _ _ _ => False) proml c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      exists c_src',\n        (<<STEPS: rtc Configuration.tau_step c_src c_src'>>) /\\\n        (<<SIM: sim_configuration_strong (fun _ => false) views c_src' c_mid c_tgt>>).\n  Proof.\n    set (tidl := List.map fst (IdentMap.elements (Configuration.threads c_src))).\n    set (tids := fun tid => match IdentMap.find tid (Configuration.threads c_src) with\n                            | Some _ => true\n                            | None => false\n                            end).\n    assert (SIMS: sim_configuration_strong tids views c_src c_mid c_tgt).\n    { inv SIM. econs; eauto.\n      { i. specialize (THSPF tid). des_ifs.\n        unfold tids in Heq. ss. unfold option_rel. des_ifs.\n        clear - Heq0 Heq2. setoid_rewrite Heq0 in Heq2. clarify. }\n      { clear - MEMPF. econs.\n        - i. set (MEM:=(sim_memory_contents MEMPF) loc ts). inv MEM.\n          + econs 1; ss.\n          + econs 2; ss.\n          + inv PROM. ss.\n          + inv EXTRA. ss.\n        - i. ss.\n      }\n      { i. exploit PAST; eauto. i. des; auto. }\n    }\n    eapply strengthen_finite; eauto.\n    instantiate (1:=tidl). i. unfold tids in TIDS. des_ifs.\n    eapply IdentMap.elements_correct in Heq.\n    eapply List.in_map with (f:=fst) in Heq. eauto.\n  Qed.\n\n  Lemma remembered_behavior views c_src c_mid c_tgt\n        (SIM: sim_configuration_strong (fun _ => false) views c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      behaviors SConfiguration.machine_step c_tgt <1=\n      behaviors SConfiguration.machine_step c_src.\n  Proof.\n    ii. cut (behaviors SConfiguration.machine_step c_mid x0).\n    { i. eapply Shorter.shorter_configuration_behavior; cycle 1.\n      { eauto. }\n      { eapply WFMID. }\n      { eauto. }\n      { inv SIM. replace ths_mid with ths_src in *.\n        { econs; eauto. ii.\n          set (MEM:=(sim_memory_contents MEMPF) loc to). inv MEM; ss.\n        }\n        { eapply IdentMap.eq_leibniz. ii.\n          specialize (THSPF y). unfold option_rel in THSPF. des_ifs.\n        }\n      }\n    }\n    { eapply JSim.machine_behavior; eauto. inv SIM. econs; eauto. }\n  Qed.\n\n  Lemma sim_configuration_behavior views prom extra proml c_src c_mid c_tgt\n        (SIM: LocalPFSim.sim_configuration L times (fun _ => True) views prom extra proml c_src c_mid c_tgt)\n        (WFSRC: Configuration.wf c_src)\n        (WFMID: JConfiguration.wf views c_mid)\n        (WFTGT: Configuration.wf c_tgt)\n    :\n      behaviors SConfiguration.machine_step c_tgt <1=\n      behaviors SConfiguration.machine_step c_src.\n  Proof.\n    eapply non_time_time_sim_configuration in SIM.\n    exploit remember_all; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. i. des.\n    exploit strengthen_all; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. i. des.\n    eapply SConfiguration.multi_step_equiv; eauto.\n    eapply rtc_tau_step_behavior.\n    { etrans; eauto. }\n    eapply SConfiguration.multi_step_equiv; eauto.\n    eapply remembered_behavior in PR; eauto.\n  Qed.\nEnd RECOVER.\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/RecoverForget.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.17412828755205056}}
{"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\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\n(*+ Operation for TimeReduce +*)\n(* Delay Time Reduce *)\nFixpoint TimReduce (a : asrt) : asrt :=\n  match a with\n  | p //\\\\ q => (TimReduce p) //\\\\ (TimReduce q)\n  | p \\\\// q => (TimReduce p) \\\\// (TimReduce q)\n  | p ** q => (TimReduce p) ** (TimReduce q)\n  | Aforall t p => Aforall (fun x : t => (TimReduce (p x)))\n  | Aexists t p => Aexists (fun x : t => (TimReduce (p x)))\n  | Aregdly t rsp v =>\n    match t with\n    | O => rsp |=> W v\n    | S t' => t' @ rsp |==> v\n    end\n  | ATimReduce p => ATimReduce (TimReduce p)\n  | _ => a\n  end.\n\nTheorem asrt_time_reduce' :\n  forall p M R R' F D D',\n    (M, (R, F), D) |= p -> (R', D') = exe_delay R D ->\n    (M, (R', F), D') |= TimReduce p.\nProof.\n  intro p. \n  induction p; intros;\n    try solve [simpls; simpljoin1; eauto]; simpl TimReduce.\n  -\n    eapply dly_reduce_Aemp_stable; eauto.\n  -\n    eapply dly_reduce_Amapsto_stable; eauto.\n  -\n    eapply dly_reduce_Aaexp_stable; eauto.\n  -\n    eapply dly_reduce_Aoexp_stable; eauto.\n  -\n    eapply dly_reduce_reg_stable; eauto.\n  -\n    destruct n.\n    eapply dlytime_zero_exe_dly; eauto.\n    eapply dlytime_gt_zero_reduce_exe_dly; eauto.\n  -\n    eapply dly_reduce_pure_stable; eauto.\n  -\n    eapply Afrmlist_exe_delay_stable; eauto.\n  -\n    simpl in H.\n    destruct H; eauto.\n    simpl; eauto.\n    simpl; eauto.\n  -\n    sep_star_split_tac.\n    simpls.\n    simpljoin1.\n    symmetry in H0.\n    eapply exe_dly_sep_split in H0; eauto.\n    simpljoin1.\n    eapply IHp1 in H; eauto.\n    eapply IHp2 in H3; eauto.\n    exists (m, (x, f0), D') (m0, (x0, f0), D').\n    simpls; eauto.\n    repeat (split; eauto).\nQed.\n\nTheorem asrt_time_reduce :\n  forall S p,\n    S |= p \u2193 -> S |= TimReduce p.\nProof.\n  intros.\n  simpl in H.\n  simpljoin1.\n  destruct_state S.\n  simpls.\n  eapply asrt_time_reduce'; eauto.\nQed.\n\n(*+ Lemmas about TimReduce +*)\nTheorem astar_TimReduce :\n  forall p q,\n    TimReduce (p ** q) = (TimReduce p) ** (TimReduce q).\nProof.\n  intros; simpl; eauto.\nQed.\n\nTheorem Regs_TimeReduce :\n  forall fmo fml fmi p,\n    TimReduce (Regs fmo fml fmi ** p) = Regs fmo fml fmi ** (TimReduce p).\nProof.\n  intros.\n  simpl.\n  unfold Regs, OutRegs, LocalRegs, InRegs.\n  destruct fmo, fml, fmi.\n  simpl.\n  eauto.\nQed.\n  \nTheorem GenRegs_TimeReduce :\n  forall grst p,\n    TimReduce (GenRegs grst ** p) = GenRegs grst ** (TimReduce 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    TimReduce (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    TimReduce (GenRegs_rm_one grst rr ** p) = GenRegs_rm_one grst rr ** (TimReduce p).\nProof.\n  intros.\n  simpl.\n  rewrite GenRegs_rm_one_TimReduce'; eauto.\nQed.\n\nTheorem RegSt_TimeReduce :\n  forall rn v p,\n    TimReduce (rn |=> v ** p) = rn |=> v ** (TimReduce p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nTheorem MemSto_TimeReduce :\n  forall l v p,\n    TimReduce (l |-> v ** p) = l |-> v ** (TimReduce p).\nProof.\n  intros.\n  simpl; eauto.\nQed.\n\nTheorem conj_TimeReduce :\n  forall p1 p2,\n    TimReduce (p1 //\\\\ p2) = (TimReduce p1) //\\\\ (TimReduce p2).\nProof.\n  intros; eauto.\nQed.\n\nTheorem disj_TimeReduce :\n  forall p1 p2,\n    TimReduce (p1 \\\\// p2) = (TimReduce p1) \\\\// (TimReduce p2).\nProof.\n  intros; eauto.\nQed.\n\nTheorem pure_TimeReduce :\n  forall pu p,\n    TimReduce ([| pu |] ** p) = [| pu |] ** (TimReduce p).\nProof.\n  intros; eauto.\nQed.\n\nTheorem Atrue_TimeReduce :\n  forall p,\n    TimReduce (Atrue ** p) = Atrue ** (TimReduce p).\nProof.\n  intros; eauto.\nQed.\n\nTheorem Afalse_TimReduce :\n  forall p,\n    TimReduce (Afalse ** p) = Afalse ** (TimReduce p).\nProof.\n  intros; eauto.\nQed.\n\nTheorem tmreduce_TimReduce :\n  forall p,\n    TimReduce (p \u2193) = (TimReduce p) \u2193.\nProof.\n  intros.\n  simpls.\n  eauto.\nQed.\n\nLtac TimReduce_simpl_bas :=\n  match goal with\n  | |- context [TimReduce (Regs ?fmo ?fml ?fmi ** ?p)] =>\n    rewrite Regs_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (GenRegs ?grst ** ?p)] =>\n    rewrite GenRegs_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (GenRegs_rm_one ?grst ?rr ** ?p)] =>\n    rewrite GenRegs_rm_one_TimReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (?rn |=> ?v ** ?p)] =>\n    rewrite RegSt_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (?l |-> ?v ** ?p)] =>\n    rewrite MemSto_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce ([| ?pu |] ** ?p)] =>\n    rewrite pure_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (Atrue ** ?p)] =>\n    rewrite Atrue_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (Afalse ** ?p)] =>\n    rewrite Afalse_TimReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (GenRegs_rm_one ?grst ?rr)] =>\n    rewrite GenRegs_rm_one_TimReduce'; TimReduce_simpl_bas\n  | |- context [TimReduce (?p1 //\\\\ ?p2)] =>\n    rewrite conj_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (?p1 \\\\// ?p2)] =>\n    rewrite disj_TimeReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (?p1 ** ?p2)] =>\n    rewrite astar_TimReduce; TimReduce_simpl_bas\n  | |- context [TimReduce (?p \u2193)] =>\n    rewrite tmreduce_TimReduce; TimReduce_simpl_bas\n  | _ => simpl TimReduce\n  end.\n\nLtac ins_tm_reduce_bas :=\n  match goal with\n  | |- |- {{ _ \u2193 }} _ {{ _ }} =>\n    eapply ins_conseq_rule;\n    [\n      let H := fresh in\n      introv H; eapply asrt_time_reduce in H; eauto | eauto..\n    ]; try TimReduce_simpl_bas\n  | _ => idtac\n  end.\n\nLtac TimReduce_simpl_in_bas H :=\n  match type of H with\n  | _ |= ?p =>\n    match p with\n    | context [TimReduce (Regs ?fmo ?fml ?fmi ** ?p)] =>\n      rewrite Regs_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [TimReduce (GenRegs ?grst ** ?p)] =>\n      rewrite GenRegs_TimeReduce in H; TimReduce_simpl_bas H\n    | context [(?rn |=> ?v ** ?p) \u2193] =>\n      rewrite RegSt_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [(?l |-> ?v ** ?p) \u2193] =>\n      rewrite MemSto_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [([| ?pu |] ** ?p) \u2193] =>\n      rewrite pure_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [(Atrue ** ?p) \u2193] =>\n      rewrite Atrue_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [(Afalse ** ?p) \u2193] =>\n      rewrite Afalse_TimReduce in H; TimReduce_simpl_in_bas H\n    | context [(?p1 //\\\\ ?p2) \u2193] =>\n      rewrite conj_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [(?p1 \\\\// ?p2) \u2193] =>\n      rewrite disj_TimeReduce in H; TimReduce_simpl_in_bas H\n    | context [TimReduce (?p \u2193)] =>\n      rewrite tmreduce_TimReduce in H; TimReduce_simpl_bas 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  \nLtac DlyFrameFree_elim_bas :=\n  match goal with\n  | |- DlyFrameFree (Atrue ** ?p) =>\n    eapply Atrue_DlyFrameFree; DlyFrameFree_elim_bas\n  | |- DlyFrameFree (Afalse ** ?p) =>\n    eapply Afalse_DlyFrameFree; DlyFrameFree_elim_bas\n  | |- DlyFrameFree (?rn |=> ?v ** ?p) =>\n    eapply RegSt_DlyFrameFree; DlyFrameFree_elim_bas\n  | |- DlyFrameFree (?l |-> ?v ** ?p) =>\n    eapply MapSto_DlyFrameFree; DlyFrameFree_elim_bas\n  | _ =>\n    try solve [simpl; eauto]\n  end.\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/example/lib/tm_dly_lemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.17406047972873043}}
{"text": "(** * Reflective lemmas for proving a splitter complete *)\nRequire Import Coq.Lists.List Coq.Strings.String.\nRequire Import ParsingParses.Parsers.ContextFreeGrammar.\nRequire Import ParsingParses.Parsers.BaseTypes ParsingParses.Parsers.BooleanBaseTypes.\nRequire Import ParsingParses.Parsers.Splitters.RDPList.\nRequire Import Coq.Init.Wf.\nRequire Import Coq.Arith.Wf_nat.\nRequire Import ParsingParses.Common.Wf.\nRequire Import ParsingParses.Common.\n\nSet Implicit Arguments.\n\n(** TODO: Generalize to more dependent splitters *)\nSection helpers.\n  Context {CharType} {String : string_like CharType} {G : grammar CharType}.\n  Context (split_valid_prod : forall (split_valid : string -> bool),\n                                production CharType -> bool).\n  Context (split_valid_prod_ext : forall (split_valid split_valid' : string -> bool)\n                                         (H : forall s, split_valid s = split_valid' s)\n                                         p,\n                                    split_valid_prod split_valid p = split_valid_prod split_valid' p).\n\n  Local Instance : parser_computational_predataT := @rdp_list_predata _ G.\n\n  Definition split_valid_step\n             (nt_valid : nonterminals_listT)\n             (split_valid : forall nt_valid', nonterminals_listT_R nt_valid' nt_valid -> string -> bool)\n             (nt : string)\n  : bool.\n  Proof.\n    refine (if Sumbool.sumbool_of_bool (is_valid_nonterminal nt_valid nt)\n            then\n              let split_valid' := split_valid (remove_nonterminal nt_valid nt) (remove_nonterminal_dec _ _ _)\n              in fold_right\n                   andb\n                   true\n                   (map (split_valid_prod split_valid') (Lookup G nt))\n            else\n              is_valid_nonterminal initial_nonterminals_data nt);\n    try assumption.\n  Defined.\n\n  Lemma split_valid_step_ext (valid : nonterminals_listT)\n        f g\n        (H : forall (valid' : nonterminals_listT)\n                    (pf : nonterminals_listT_R valid' valid)\n                    nt,\n               f valid' pf nt = g valid' pf nt)\n        nt\n  : split_valid_step f nt = split_valid_step g nt.\n  Proof.\n    unfold split_valid_step.\n    edestruct dec;\n      f_equal.\n    apply map_ext; intro x.\n    apply split_valid_prod_ext; trivial.\n  Qed.\n\n  Definition split_valid_nonterminal valid : string -> bool\n    := Fix1 _ ntl_wf _ split_valid_step valid.\n\n  Definition split_valid : bool\n    := fold_right\n         andb\n         true\n         (map (split_valid_nonterminal initial_nonterminals_data) initial_nonterminals_data).\n\n  Context {premethods : @parser_computational_dataT' _ _ (@rdp_list_data' _ String G)}.\n  Context split_stateT0 split_string_for_production0 split_string_for_production_correct0\n          (dummy : @boolean_parser_dataT _ String\n           := {| predata := @rdp_list_predata _ G;\n                 split_stateT := split_stateT0;\n                 split_string_for_production := split_string_for_production0;\n                 split_string_for_production_correct := split_string_for_production_correct0 |}).\n  Local Instance data0 : @boolean_parser_dataT _ String\n    := {| predata := @rdp_list_predata _ G;\n          split_stateT := split_stateT0;\n          split_string_for_production := split_string_for_production0;\n          split_string_for_production_correct := split_string_for_production_correct0 |}.\n\n  Context (split_valid_prod_tail : forall f x xs, split_valid_prod f (x::xs) = true -> split_valid_prod f xs = true).\n\n  Lemma split_complete\n        (H : split_valid = true)\n        str0 valid (str : StringWithSplitState String split_stateT0) (pf : str \u2264s str0) nt\n        (H' : is_valid_nonterminal initial_nonterminals_data nt = true)\n        (split_prod_each : forall it its,\n                             split_valid_prod\n                               (split_valid_nonterminal (remove_nonterminal initial_nonterminals_data nt))\n                               (it::its) = true\n                             -> split_list_completeT\n                                  (G := G) (str0 := str0) (valid := valid) it its str pf\n                                  (split_string_for_production0 it its str))\n  : ForallT\n      (Forall_tails\n         (fun prod =>\n            match prod with\n              | [] => True\n              | it :: its =>\n                @split_list_completeT _ String G data0 str0 valid it its str pf\n                                      (@split_string_for_production0 it its str)\n            end)) (Lookup G nt).\n  Proof.\n    pose proof H' as H''.\n    simpl in H''.\n    unfold rdp_list_is_valid_nonterminal in H''.\n    edestruct in_dec as [H'''|H''']; try discriminate; [].\n    apply (fun H => fold_right_andb_map_in H _ H''') in H.\n    unfold split_valid_nonterminal in H.\n    simpl in H.\n    rewrite Fix1_eq in H by apply split_valid_step_ext.\n    unfold split_valid_step in H at 1.\n    rewrite H' in H.\n    edestruct dec; try (simpl in *; congruence).\n    clear -H split_valid_prod_tail split_prod_each.\n    { induction (Lookup G nt); simpl in *; trivial.\n      intros; split;\n      repeat match goal with\n               | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | _ => solve [ eauto ]\n             end.\n      clear IHp.\n      clear -H split_valid_prod_tail split_prod_each.\n      let a := match goal with a : production _ |- _ => constr:a end in\n      induction a; simpl in *; trivial.\n      { intros; split;\n        repeat match goal with\n                 | [ H : (_ && _)%bool = true |- _ ] => apply Bool.andb_true_iff in H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : context[match ?a with _ => _ end] |- _ ] => atomic a; destruct a\n                 | _ => solve [ eauto ]\n                 | _ => progress simpl in *\n                 | _ => congruence\n               end. } }\n  Qed.\n\n  Lemma split_complete_simple\n        (split_prod_each\n         : forall nt it its str0 valid s1 s2 (pf : s1 ++ s2 \u2264s str0) st,\n             MinimalParse.minimal_parse_of_item (G := G) str0 valid s1 it\n             -> MinimalParse.minimal_parse_of_production (G := G) str0 valid s2 its\n             -> is_valid_nonterminal initial_nonterminals_data nt = true\n             -> split_valid_prod\n                  (split_valid_nonterminal (remove_nonterminal initial_nonterminals_data nt))\n                  (it::its) = true\n             -> { st1st2 : _\n                | In\n                    ({| string_val := s1; state_val := fst st1st2 |},\n                     {| string_val := s2; state_val := snd st1st2 |})\n                    (split_string_for_production0 it its {| string_val := s1 ++ s2; state_val := st |}) })\n        (H : split_valid = true)\n  : forall str0 valid (str : StringWithSplitState String split_stateT0) (pf : str \u2264s str0) nt,\n      is_valid_nonterminal initial_nonterminals_data nt = true ->\n      ForallT\n        (Forall_tails\n           (fun prod =>\n              match prod with\n                | [] => True\n                | it :: its =>\n                  @split_list_completeT _ String G data0 str0 valid it its str pf\n                                        (@split_string_for_production0 it its str)\n              end)) (Lookup G nt).\n  Proof.\n    intros str0 valid str pf nt H0.\n    apply split_complete; try assumption.\n    intros it its Hvalid [ [s1 s2] [ [ H' m1 ] m2 ] ].\n    destruct str as [str st].\n    simpl in *.\n    apply bool_eq_correct in H'.\n    subst.\n    specialize (split_prod_each\n                  nt it its str0 valid s1 s2 pf st m1 m2 H0 Hvalid).\n    eexists; repeat split.\n    exact (proj2_sig split_prod_each).\n    assumption.\n    assumption.\n  Qed.\nEnd helpers.\n", "meta": {"author": "JasonGross", "repo": "parsing-parses", "sha": "8629e8e7b1e3e65ad6d152d08ce860d1385ecbf9", "save_path": "github-repos/coq/JasonGross-parsing-parses", "path": "github-repos/coq/JasonGross-parsing-parses/parsing-parses-8629e8e7b1e3e65ad6d152d08ce860d1385ecbf9/src/Parsers/Splitters/Reflective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.17406046788979995}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import RmiSMC.Spec.\nRequire Import PSCIHandler.Spec.\nRequire Import CtxtSwitch.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance CtxtSwitch_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance CtxtSwitch_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance save_realm_state_inv: PreservesInvariants save_realm_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_hcr_el2_inv: PreservesInvariants restore_hcr_el2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_realm_state_inv: PreservesInvariants restore_realm_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance configure_realm_stage2_inv: PreservesInvariants configure_realm_stage2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance save_ns_state_inv: PreservesInvariants save_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance restore_ns_state_inv: PreservesInvariants restore_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance shiftl_inv: PreservesInvariants shiftl_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_to_idx_inv: PreservesInvariants addr_to_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_sysregs_inv: PreservesInvariants set_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_psci_call_inv: PreservesInvariants get_psci_result_forward_psci_call_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_inc_inv: PreservesInvariants granule_refcount_inc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_rec_run_inv: PreservesInvariants ns_buffer_read_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_release_inv: PreservesInvariants atomic_granule_put_release_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_gprs_inv: PreservesInvariants get_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_asserted_inv: PreservesInvariants set_rec_ptimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_is_emulated_mmio_inv: PreservesInvariants get_rec_run_is_emulated_mmio_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_dec_inv: PreservesInvariants granule_refcount_dec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_masked_inv: PreservesInvariants get_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_header_inv: PreservesInvariants measurement_extend_data_header_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_lock_inv: PreservesInvariants granule_lock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_rec_inv: PreservesInvariants is_addr_in_par_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sixty_four_inv: PreservesInvariants esr_sixty_four_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance run_realm_inv: PreservesInvariants run_realm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_g_rtt_refcount_inv: PreservesInvariants get_g_rtt_refcount_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_srt_inv: PreservesInvariants esr_srt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_pc_inv: PreservesInvariants get_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_len_inv: PreservesInvariants access_len_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_masked_inv: PreservesInvariants set_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_read_inv: PreservesInvariants sysreg_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance null_ptr_inv: PreservesInvariants null_ptr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_masked_inv: PreservesInvariants set_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_esr_inv: PreservesInvariants set_rec_run_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_gprs_inv: PreservesInvariants set_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_hpfar_inv: PreservesInvariants set_rec_run_hpfar_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x0_inv: PreservesInvariants get_psci_result_x0_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x1_inv: PreservesInvariants get_psci_result_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x2_inv: PreservesInvariants get_psci_result_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance psci_rsi_inv: PreservesInvariants psci_rsi_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_masked_inv: PreservesInvariants get_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_g_llt_inv: PreservesInvariants set_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_last_run_info_esr_inv: PreservesInvariants get_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_is_write_inv: PreservesInvariants esr_is_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x3_inv: PreservesInvariants get_psci_result_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_index_inv: PreservesInvariants set_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance emulate_timer_ctl_read_inv: PreservesInvariants emulate_timer_ctl_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_inv: PreservesInvariants measurement_extend_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_IS_WRITE_inv: PreservesInvariants ESR_EL2_SYSREG_IS_WRITE_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance barrier_inv: PreservesInvariants barrier_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_mask_inv: PreservesInvariants access_mask_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sign_extend_inv: PreservesInvariants esr_sign_extend_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_dispose_pending_inv: PreservesInvariants set_rec_dispose_pending_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_g_rtt_inv: PreservesInvariants get_rd_g_rtt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_last_run_info_esr_inv: PreservesInvariants set_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_regs_inv: PreservesInvariants get_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x3_inv: PreservesInvariants get_psci_result_forward_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x2_inv: PreservesInvariants get_psci_result_forward_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x1_inv: PreservesInvariants get_psci_result_forward_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_exit_reason_inv: PreservesInvariants set_rec_run_exit_reason_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_ISS_RT_inv: PreservesInvariants ESR_EL2_SYSREG_ISS_RT_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_inv: PreservesInvariants atomic_granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_idreg_inv: PreservesInvariants read_idreg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_end_inv: PreservesInvariants get_rec_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_pc_inv: PreservesInvariants set_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_regs_inv: PreservesInvariants set_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_runnable_inv: PreservesInvariants get_rec_runnable_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_sysregs_inv: PreservesInvariants get_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_asserted_inv: PreservesInvariants set_rec_vtimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_emulated_write_val_inv: PreservesInvariants set_rec_run_emulated_write_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_far_inv: PreservesInvariants set_rec_run_far_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_emulated_read_val_inv: PreservesInvariants get_rec_run_emulated_read_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_inv: PreservesInvariants get_rec_vtimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_inv: PreservesInvariants get_rec_ptimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_g_rtt_rd_inv: PreservesInvariants set_g_rtt_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_inv: PreservesInvariants is_addr_in_par_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_write_inv: PreservesInvariants sysreg_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_base_inv: PreservesInvariants get_rec_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_unused_granule_inv: PreservesInvariants find_lock_unused_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_to_phys_inv: PreservesInvariants entry_to_phys_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance stage2_tlbi_ipa_inv: PreservesInvariants stage2_tlbi_ipa_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_get_inv: PreservesInvariants atomic_granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance link_table_inv: PreservesInvariants link_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance timer_condition_met_inv: PreservesInvariants timer_condition_met_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_is_level_aligned_inv: PreservesInvariants addr_is_level_aligned_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition CtxtSwitch_fresh : compatlayer (cdata RData) :=\n      _save_realm_state \u21a6 gensem save_realm_state_spec\n        \u2295 _restore_hcr_el2 \u21a6 gensem restore_hcr_el2_spec\n        \u2295 _restore_realm_state \u21a6 gensem restore_realm_state_spec\n        \u2295 _configure_realm_stage2 \u21a6 gensem configure_realm_stage2_spec\n        \u2295 _save_ns_state \u21a6 gensem save_ns_state_spec\n        \u2295 _restore_ns_state \u21a6 gensem restore_ns_state_spec\n      .\n\n    Definition CtxtSwitch_passthrough : compatlayer (cdata RData) :=\n      _shiftl \u21a6 gensem shiftl_spec\n        \u2295 _addr_to_idx \u21a6 gensem addr_to_idx_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _set_rec_sysregs \u21a6 gensem set_rec_sysregs_spec\n        \u2295 _get_psci_result_forward_psci_call \u21a6 gensem get_psci_result_forward_psci_call_spec\n        \u2295 _granule_refcount_inc \u21a6 gensem granule_refcount_inc_spec\n        \u2295 _ns_buffer_read_rec_run \u21a6 gensem ns_buffer_read_rec_run_spec\n        \u2295 _granule_put \u21a6 gensem granule_put_spec\n        \u2295 _smc_granule_undelegate \u21a6 gensem smc_granule_undelegate_spec\n        \u2295 _entry_is_table \u21a6 gensem entry_is_table_spec\n        \u2295 _atomic_granule_put_release \u21a6 gensem atomic_granule_put_release_spec\n        \u2295 _smc_rec_destroy \u21a6 gensem smc_rec_destroy_spec\n        \u2295 _get_rec_run_gprs \u21a6 gensem get_rec_run_gprs_spec\n        \u2295 _set_rec_ptimer_asserted \u21a6 gensem set_rec_ptimer_asserted_spec\n        \u2295 _get_rec_run_is_emulated_mmio \u21a6 gensem get_rec_run_is_emulated_mmio_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _granule_refcount_dec \u21a6 gensem granule_refcount_dec_spec\n        \u2295 _get_rec_ptimer_masked \u21a6 gensem get_rec_ptimer_masked_spec\n        \u2295 _measurement_extend_data_header \u21a6 gensem measurement_extend_data_header_spec\n        \u2295 _granule_lock \u21a6 gensem granule_lock_spec\n        \u2295 _ns_buffer_unmap \u21a6 gensem ns_buffer_unmap_spec\n        \u2295 _granule_memzero_mapped \u21a6 gensem granule_memzero_mapped_spec\n        \u2295 _is_addr_in_par_rec \u21a6 gensem is_addr_in_par_rec_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _esr_sixty_four \u21a6 gensem esr_sixty_four_spec\n        \u2295 _run_realm \u21a6 gensem run_realm_spec\n        \u2295 _get_g_rtt_refcount \u21a6 gensem get_g_rtt_refcount_spec\n        \u2295 _esr_srt \u21a6 gensem esr_srt_spec\n        \u2295 _get_rec_pc \u21a6 gensem get_rec_pc_spec\n        \u2295 _granule_get \u21a6 gensem granule_get_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _access_len \u21a6 gensem access_len_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _set_rec_ptimer_masked \u21a6 gensem set_rec_ptimer_masked_spec\n        \u2295 _sysreg_read \u21a6 gensem sysreg_read_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _null_ptr \u21a6 gensem null_ptr_spec\n        \u2295 _set_rec_vtimer_masked \u21a6 gensem set_rec_vtimer_masked_spec\n        \u2295 _get_wi_g_llt \u21a6 gensem get_wi_g_llt_spec\n        \u2295 _set_rec_run_esr \u21a6 gensem set_rec_run_esr_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _set_rec_run_gprs \u21a6 gensem set_rec_run_gprs_spec\n        \u2295 _set_rec_run_hpfar \u21a6 gensem set_rec_run_hpfar_spec\n        \u2295 _get_psci_result_x0 \u21a6 gensem get_psci_result_x0_spec\n        \u2295 _get_psci_result_x1 \u21a6 gensem get_psci_result_x1_spec\n        \u2295 _get_psci_result_x2 \u21a6 gensem get_psci_result_x2_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _psci_rsi \u21a6 gensem psci_rsi_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _pgte_read \u21a6 gensem pgte_read_spec\n        \u2295 _get_rec_vtimer_masked \u21a6 gensem get_rec_vtimer_masked_spec\n        \u2295 _set_wi_g_llt \u21a6 gensem set_wi_g_llt_spec\n        \u2295 _get_rec_last_run_info_esr \u21a6 gensem get_rec_last_run_info_esr_spec\n        \u2295 _esr_is_write \u21a6 gensem esr_is_write_spec\n        \u2295 _get_psci_result_x3 \u21a6 gensem get_psci_result_x3_spec\n        \u2295 _get_wi_index \u21a6 gensem get_wi_index_spec\n        \u2295 _set_wi_index \u21a6 gensem set_wi_index_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _emulate_timer_ctl_read \u21a6 gensem emulate_timer_ctl_read_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _measurement_extend_data \u21a6 gensem measurement_extend_data_spec\n        \u2295 _ESR_EL2_SYSREG_IS_WRITE \u21a6 gensem ESR_EL2_SYSREG_IS_WRITE_spec\n        \u2295 _barrier \u21a6 gensem barrier_spec\n        \u2295 _access_mask \u21a6 gensem access_mask_spec\n        \u2295 _esr_sign_extend \u21a6 gensem esr_sign_extend_spec\n        \u2295 _set_rec_dispose_pending \u21a6 gensem set_rec_dispose_pending_spec\n        \u2295 _get_rd_g_rtt \u21a6 gensem get_rd_g_rtt_spec\n        \u2295 _set_rec_last_run_info_esr \u21a6 gensem set_rec_last_run_info_esr_spec\n        \u2295 _granule_memzero \u21a6 gensem granule_memzero_spec\n        \u2295 _get_rec_regs \u21a6 gensem get_rec_regs_spec\n        \u2295 _get_psci_result_forward_x3 \u21a6 gensem get_psci_result_forward_x3_spec\n        \u2295 _get_psci_result_forward_x2 \u21a6 gensem get_psci_result_forward_x2_spec\n        \u2295 _get_psci_result_forward_x1 \u21a6 gensem get_psci_result_forward_x1_spec\n        \u2295 _set_rec_run_exit_reason \u21a6 gensem set_rec_run_exit_reason_spec\n        \u2295 _ESR_EL2_SYSREG_ISS_RT \u21a6 gensem ESR_EL2_SYSREG_ISS_RT_spec\n        \u2295 _atomic_granule_put \u21a6 gensem atomic_granule_put_spec\n        \u2295 _read_idreg \u21a6 gensem read_idreg_spec\n        \u2295 _get_rec_par_end \u21a6 gensem get_rec_par_end_spec\n        \u2295 _smc_realm_activate \u21a6 gensem smc_realm_activate_spec\n        \u2295 _set_mapping \u21a6 gensem set_mapping_spec\n        \u2295 _set_rec_pc \u21a6 gensem set_rec_pc_spec\n        \u2295 _set_rec_regs \u21a6 gensem set_rec_regs_spec\n        \u2295 _get_rec_runnable \u21a6 gensem get_rec_runnable_spec\n        \u2295 _ns_granule_map \u21a6 gensem ns_granule_map_spec\n        \u2295 _get_rec_sysregs \u21a6 gensem get_rec_sysregs_spec\n        \u2295 _set_rec_vtimer_asserted \u21a6 gensem set_rec_vtimer_asserted_spec\n        \u2295 _set_rec_run_emulated_write_val \u21a6 gensem set_rec_run_emulated_write_val_spec\n        \u2295 _smc_granule_delegate \u21a6 gensem smc_granule_delegate_spec\n        \u2295 _set_rec_run_far \u21a6 gensem set_rec_run_far_spec\n        \u2295 _get_rec_run_emulated_read_val \u21a6 gensem get_rec_run_emulated_read_val_spec\n        \u2295 _get_rec_vtimer \u21a6 gensem get_rec_vtimer_spec\n        \u2295 _get_rec_ptimer \u21a6 gensem get_rec_ptimer_spec\n        \u2295 _smc_rec_create \u21a6 gensem smc_rec_create_spec\n        \u2295 _set_g_rtt_rd \u21a6 gensem set_g_rtt_rd_spec\n        \u2295 _ns_buffer_read_data \u21a6 gensem ns_buffer_read_data_spec\n        \u2295 _pgte_write \u21a6 gensem pgte_write_spec\n        \u2295 _is_addr_in_par \u21a6 gensem is_addr_in_par_spec\n        \u2295 _sysreg_write \u21a6 gensem sysreg_write_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _get_rec_par_base \u21a6 gensem get_rec_par_base_spec\n        \u2295 _smc_realm_create \u21a6 gensem smc_realm_create_spec\n        \u2295 _find_lock_unused_granule \u21a6 gensem find_lock_unused_granule_spec\n        \u2295 _entry_to_phys \u21a6 gensem entry_to_phys_spec\n        \u2295 _stage2_tlbi_ipa \u21a6 gensem stage2_tlbi_ipa_spec\n        \u2295 _atomic_granule_get \u21a6 gensem atomic_granule_get_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _link_table \u21a6 gensem link_table_spec\n        \u2295 _smc_realm_destroy \u21a6 gensem smc_realm_destroy_spec\n        \u2295 _timer_condition_met \u21a6 gensem timer_condition_met_spec\n        \u2295 _addr_is_level_aligned \u21a6 gensem addr_is_level_aligned_spec\n      .\n\n    Definition CtxtSwitch := CtxtSwitch_fresh \u2295 CtxtSwitch_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/CtxtSwitch/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1740604644021424}}
{"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base pagetable mem trans.\nFrom HypVeri.rules Require Import rules_base ldr.\nFrom HypVeri.logrel Require Import logrel logrel_extra.\nFrom HypVeri Require Import proofmode.\nImport uPred.\n\nSection ftlr_ldr.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{hypparams:!HypervisorParameters}.\n  Context `{vmG: !gen_VMG \u03a3}.\n\nLemma ftlr_ldr {i mem_acc_tx ai regs rxs ps_acc p_tx p_rx instr trans src dst} P:\n  base_extra.is_total_gmap regs ->\n  base_extra.is_total_gmap rxs ->\n  {[p_tx; p_rx]} \u2286 ps_acc ->\n  currently_accessible_in_trans_memory_pages i trans \u2286 ps_acc \u2216 {[p_tx; p_rx]} ->\n  p_rx \u2209 ps_acc \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i trans ->\n  p_tx \u2209 ps_acc \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i trans ->\n  regs !! PC = Some ai ->\n  tpa ai \u2208 ps_acc ->\n  tpa ai \u2260 p_tx ->\n  dom mem_acc_tx = set_of_addr (ps_acc \u2216 {[p_tx]}) ->\n  tpa ai \u2208 ps_acc \u2216 {[p_tx]} ->\n  mem_acc_tx !! ai = Some instr ->\n  decode_instruction instr = Some (Ldr dst src) ->\n  \u22a2 \u25b7 (\u2200 (a : gmap reg_name Addr) (a0 : gset PID) (a1 : gmap Addr transaction) (a2 : gmap VMID (option (Addr * VMID))),\n              \u231cbase_extra.is_total_gmap a2\u231d -\u2217\n              \u231cbase_extra.is_total_gmap a\u231d -\u2217\n              \u231c{[p_tx; p_rx]} \u2286 a0\u231d -\u2217\n              \u231ccurrently_accessible_in_trans_memory_pages i a1 \u2286 a0 \u2216 {[p_tx; p_rx]}\u231d -\u2217\n              \u231cp_rx \u2209 a0 \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i a1\u231d -\u2217\n              \u231cp_tx \u2209 a0 \u2216 {[p_rx; p_tx]} \u222a accessible_in_trans_memory_pages i a1\u231d -\u2217\n              ([\u2217 map] r\u21a6w \u2208 a, r @@ i ->r w) -\u2217\n              TX@i:=p_tx -\u2217\n              p_tx -@O> - \u2217 p_tx -@E> true -\u2217\n              mailbox.rx_page i p_rx -\u2217\n              i -@A> a0 -\u2217\n              pagetable_entries_excl_owned i (a0 \u2216 {[p_rx; p_tx]} \u2216 currently_accessible_in_trans_memory_pages i a1) -\u2217\n              transaction_hpool_global_transferred a1 -\u2217\n              transaction_pagetable_entries_transferred i a1 -\u2217\n              retrievable_transaction_transferred i a1 -\u2217\n              rx_state_get i a2 -\u2217\n              rx_states_global (delete i a2) -\u2217\n              transaction_pagetable_entries_owned i a1 -\u2217\n              retrieved_transaction_owned i a1 -\u2217\n              (\u2203 mem : lang.mem, memory_pages (a0 \u222a (accessible_in_trans_memory_pages i a1)) mem) -\u2217\n              (P a1 a2) -\u2217\n              WP ExecI @ i {{ _, True }}) -\u2217\n   ([\u2217 map] r\u21a6w \u2208 regs, r @@ i ->r w) -\u2217\n   TX@i:=p_tx -\u2217\n   p_tx -@O> - \u2217 p_tx -@E> true -\u2217\n   i -@A> ps_acc -\u2217\n   pagetable_entries_excl_owned i (ps_acc \u2216 {[p_rx; p_tx]} \u2216 (currently_accessible_in_trans_memory_pages i trans)) -\u2217\n   transaction_hpool_global_transferred trans -\u2217\n   transaction_pagetable_entries_transferred i trans -\u2217\n   retrievable_transaction_transferred i trans -\u2217\n   rx_state_get i rxs -\u2217\n   mailbox.rx_page i p_rx -\u2217\n   rx_states_global (delete i rxs) -\u2217\n   transaction_pagetable_entries_owned i trans -\u2217\n   retrieved_transaction_owned i trans -\u2217\n   (\u2203 mem1 : mem, memory_pages ((ps_acc \u222a (accessible_in_trans_memory_pages i trans)) \u2216 ps_acc) mem1) -\u2217\n   ([\u2217 map] k\u21a6v \u2208 mem_acc_tx, k ->a v) -\u2217\n   (\u2203 mem2 : mem, memory_page p_tx mem2) -\u2217\n   (P trans rxs) -\u2217\n   SSWP ExecI @ i {{ bm, (if bm.1 then VMProp_holds i (1 / 2) else True) -\u2217 WP bm.2 @ i {{ _, True }} }}.\n  Proof.\n    iIntros (Htotal_regs Htotal_rxs Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx Hlookup_PC Hin_ps_acc Hneq_ptx Hdom_mem_acc_tx Hin_ps_acc_tx Hlookup_mem_ai Heqn).\n    iIntros \"IH regs tx pgt_tx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state rx other_rx tran_pgt_owned\n                 retri_owned mem_rest mem_acc_tx mem_tx P\".\n    pose proof Heqn as Hdecode.\n    apply decode_instruction_valid in Heqn.\n    inversion Heqn as [| | ? ? Hvalid_dst Hvalid_src Hvalid_neq | | | | | | | | | ].\n    subst dst0 src0.\n    unfold reg_valid_cond in Hvalid_dst, Hvalid_src.\n    pose proof (Htotal_regs src) as [a_src Hlookup_src].\n    pose proof (Htotal_regs dst) as [w_dst Hlookup_dst].\n    (* getting registers *)\n    iDestruct ((reg_big_sepM_split_upd3 i Hlookup_PC Hlookup_src Hlookup_dst)\n                with \"[$regs]\") as \"(PC & r_src & r_dst & Hacc_regs)\"; [by destruct_and ! | by destruct_and ! | done | done |].\n    (* case analysis on src  *)\n    destruct (decide ((tpa a_src) \u2208 ps_acc)) as [Hin' | Hin''].\n    { (* has access to the page, more cases.. *)\n      destruct (decide((tpa a_src) = p_tx)).\n      { (* trying to read from tx page, fail *)\n        (* getting mem *)\n        iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with \"[mem_acc_tx]\")\n          as \"[mem_instr Hacc_mem_acc_tx]\"; first done.\n        iApply (ldr_access_tx (w3 := w_dst) ai a_src dst src with \"[PC pgt_acc tx mem_instr r_src r_dst]\"); iFrameAutoSolve.\n        iNext.\n        iIntros \"(tx & PC & a_instr & r_src & acc & r_dst) _\".\n        by iApply wp_terminated.\n      }\n      { (* normal case *)\n        destruct (decide (a_src = ai)) as [|Hneq''].\n        { (* exact same addr *)\n          iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with \"[mem_acc_tx]\")\n            as \"[mem_instr Hacc_mem_acc_tx]\"; first done.\n          iApply (ldr_same_addr (s := ps_acc) ai a_src dst src with \"[PC mem_instr r_src r_dst tx pgt_acc]\"); iFrameAutoSolve.\n          { symmetry;done. }\n          iNext. iIntros \"(PC & mem_instr & r_src & r_dst & pgt_acc & tx) _\".\n          iDestruct (\"Hacc_regs\" with \"[$PC $r_src $r_dst]\") as (regs') \"[%Htotal_regs' regs]\";iFrame.\n          iDestruct (\"Hacc_mem_acc_tx\" with \"mem_instr\") as \"mem_acc_tx\".\n          iApply (\"IH\" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with \"regs tx pgt_tx rx pgt_acc pgt_owned\n                        trans_hpool_global tran_pgt_transferred retri rx_state other_rx\n                           tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P\").\n          {\n            iDestruct (memory_pages_split_singleton' p_tx ps_acc with \"[mem_acc_tx $mem_tx]\") as \"mem_acc\". set_solver + Hsubset_mb.\n            iExists mem_acc_tx;by iFrame \"mem_acc_tx\".\n            iApply (memory_pages_split_diff' _ ps_acc with \"[$mem_rest $mem_acc]\").\n            set_solver +.\n          }\n        }\n        { (* different addresses *)\n          destruct (decide ((tpa a_src) = (tpa ai))) as [Heqn'|].\n          { (* in same page *)\n            pose proof Hin_ps_acc as Hin_ps_acc.\n            rewrite <-Heqn' in Hin_ps_acc.\n            assert (tpa a_src \u2208 ps_acc \u2216 {[p_tx]}) as Hin_ps_acc'.\n            set_solver + Hin_ps_acc n.\n            pose proof (elem_of_memory_pages_lookup _ _ _ Hin_ps_acc' Hdom_mem_acc_tx) as [w_src Hlookup_a_src].\n            iDestruct (mem_big_sepM_split2 mem_acc_tx Hneq'' Hlookup_a_src Hlookup_mem_ai with \"[$mem_acc_tx]\")\n              as \"[a_src [a_instr Hacc_mem_acc_tx]]\".\n            iApply (ldr_same_page (s := ps_acc) ai a_src dst src with \"[PC a_instr a_src r_src r_dst tx pgt_acc]\"); iFrameAutoSolve.\n            set_solver. intro; apply Hneq''. symmetry;done. symmetry;done.\n            iNext. iIntros \"(PC & mem_instr & r_src & a_src & r_dst & pgt_acc & tx) _\".\n            iDestruct (\"Hacc_regs\" with \"[$PC $r_src $r_dst]\") as (regs') \"[%Htotal_regs' regs]\";iFrame.\n            iDestruct (\"Hacc_mem_acc_tx\" with \"[a_src mem_instr]\") as \"mem_acc_tx\"; iFrame.\n            iApply (\"IH\" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with \"regs tx pgt_tx rx pgt_acc pgt_owned\n                       trans_hpool_global tran_pgt_transferred retri rx_state other_rx\n                           tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P\").\n            {\n              iDestruct (memory_pages_split_singleton' p_tx ps_acc with \"[mem_acc_tx $mem_tx]\") as \"mem_acc\". set_solver + Hsubset_mb.\n              iExists mem_acc_tx;by iFrame \"mem_acc_tx\".\n              iApply (memory_pages_split_diff' _ ps_acc with \"[$mem_rest $mem_acc]\").\n              set_solver +.\n            }\n          }\n          { (* in difference pages *)\n            (* getting mem *)\n            assert (tpa a_src \u2208 ps_acc \u2216 {[p_tx]}) as Hin_ps_acc'.\n            set_solver + Hin' n.\n            pose proof (elem_of_memory_pages_lookup _ _ _ Hin_ps_acc' Hdom_mem_acc_tx) as [w_src Hlookup_a_src].\n            iDestruct (mem_big_sepM_split2 mem_acc_tx Hneq'' Hlookup_a_src Hlookup_mem_ai with \"[$mem_acc_tx]\")\n              as \"[a_src [mem_instr Hacc_mem_acc_tx]]\".\n            iApply (ldr (s := ps_acc) ai a_src dst src with \"[PC mem_instr a_src r_src r_dst tx pgt_acc]\"); iFrameAutoSolve.\n            { set_solver. }\n            iNext. iIntros \"(PC & mem_instr & r_src & a_src & r_dst & pgt_acc & tx) _\".\n            iDestruct (\"Hacc_regs\" with \"[$PC $r_src $r_dst]\") as (regs') \"[%Htotal_regs' regs]\";iFrame.\n            iDestruct (\"Hacc_mem_acc_tx\" with \"[a_src mem_instr]\") as \"mem_acc_tx\"; iFrame.\n            iApply (\"IH\" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with \"regs tx pgt_tx rx pgt_acc pgt_owned\n                       trans_hpool_global tran_pgt_transferred retri rx_state other_rx\n                           tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P\").\n            {\n              iDestruct (memory_pages_split_singleton' p_tx ps_acc with \"[mem_acc_tx $mem_tx]\") as \"mem_acc\". set_solver + Hsubset_mb.\n              iExists mem_acc_tx;by iFrame \"mem_acc_tx\".\n              iApply (memory_pages_split_diff' _ ps_acc with \"[$mem_rest $mem_acc]\").\n              set_solver +.\n            }\n          }\n        }\n      }\n    }\n    { (* no access to the page, apply ldr_error *)\n      (* getting mem *)\n      (* we don't update memory *)\n      iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with \"[mem_acc_tx]\")\n        as \"[mem_instr Hacc_mem_acc_tx]\"; first done.\n      iApply (ldr_no_access (s := ps_acc) ai a_src dst src with \"[PC mem_instr r_src r_dst tx pgt_acc]\"); iFrameAutoSolve.\n      iNext. iIntros \"(PC & mem_instr & r_src & pgt_acc & r_dst & tx) _\".\n      by iApply wp_terminated.\n    }\n  Qed.\n\nEnd ftlr_ldr.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/logrel/ftlr_ldr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.1740500147071631}}
{"text": "Require Import ucos_include.\nRequire Import OSMutex_common.\nRequire Import os_ucos_h.\nRequire Import mutex_absop_rules.\nRequire Import sep_lemmas_ext.\nRequire Import symbolic_lemmas.\nRequire Import OSTimeDlyPure.\n\nRequire Import OSMutexPostPure.\n\nRequire Import OSQPostPure.\n\nRequire Import tcblist_setnode_lemmas.\nLocal Open Scope code_scope.\nLocal Open Scope nat_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope int_scope.\nLocal Open Scope list_scope.\n\n\n\nLemma post3 :\n\nforall (\n  v' v'0 v'1 v'2 : val\n)(\n  v'3 v'4 v'5 : list vallist\n)(\n  v'6 : list EventData\n)(\n  v'7 : list os_inv.EventCtr\n)(\n  v'8 : vallist\n)(\n  v'9 v'10 : val\n)(\n  v'11 : list vallist\n)(\n  v'12 : vallist\n)(\n  v'13 : list vallist\n)(\n  v'14 : vallist\n)(\n  v'15 : val\n)(\n  v'16 : EcbMod.map\n)(\n  v'17 : TcbMod.map\n)(\n  v'18 : int32\n)(\n  v'19 : addrval\n)(\n  v'21 : val\n)(\n  v'22 : list vallist\n)(\n  v'25 v'26 : list os_inv.EventCtr\n)(\n  v'27 v'28 : list EventData\n)(\n  v'30 : vallist\n)(\n  v'33 v'35 : list vallist\n)(\n  v'36 : vallist\n)(\n  v'38 : EcbMod.map\n)(\n  v'39 : TcbMod.map\n)(\n  v'42 v'46 : val\n)(\n  v'47 v'48 v'49 : EcbMod.map\n)(\n  w : waitset\n)(\n  H3 : ECBList_P v'46 Vnull v'26 v'28 v'48 v'39\n)(\n  H17 : EcbMod.join v'47 v'49 v'38\n)(\n  H12 : length v'25 = length v'27\n)(\n  H16 : isptr v'46\n)(\n  v'23 : addrval\n)(\n  x3 : val\n)(\n  H24 : isptr v'46\n)(\n  H20 : Int.unsigned ($ OS_EVENT_TYPE_MUTEX) <= 255\n)(\n  x : int32\n)(\n  H10 H22 : Int.unsigned x <= 65535\n)(\n  v'24 : val\n)(\n  v'43 v'45 : TcbMod.map\n)(\n  v'52 : block\n)(\n  H32 : join v'43 v'45 v'39\n)(\n  H30 : Vptr (v'52, Int.zero) <> Vnull\n)(\n  i6 : int32\n)(\n  H39 : Int.unsigned i6 <= 65535\n)(\n  H36 : isptr v'24\n)(\n  x7 : val\n)(\n  x10 : TcbMod.map\n)(\n  t : taskstatus\n)(\n  m : msg\n)(\n  H72 : TCBList_P x7 v'35 v'36 x10\n)(\n  H : RH_TCBList_ECBList_P v'16 v'17 (v'52, Int.zero)\n)(\n  H0 : RH_CurTCB (v'52, Int.zero) v'17\n)(\n  H7 : RH_TCBList_ECBList_P v'38 v'39 (v'52, Int.zero)\n)(\n  H8 : RH_CurTCB (v'52, Int.zero) v'39\n)(\n  H23 : isptr (Vptr (v'52, $ 0))\n)(\n  H29 : x&\u1d62$ OS_MUTEX_KEEP_LOWER_8 = $ OS_MUTEX_AVAILABLE \\/\n        x&\u1d62$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE\n)(\n  H35 : x&\u1d62$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE\n)(\n  H48 : Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) < 64\n)(\n  H4 : Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) = None -> w = nil\n)(\n  H13 : w <> nil -> Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) <> None\n)(\n  H25 : x&\u1d62$ OS_MUTEX_KEEP_LOWER_8 = $ OS_MUTEX_AVAILABLE ->\n        Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) = None /\\\n        Vptr (v'52, $ 0) = Vnull\n)(\n  H26 : x&\u1d62$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE ->\n        exists tid,\n        Vptr (v'52, $ 0) = Vptr tid /\\\n        Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) =\n        Some (tid, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n)(\n  v'32 : val\n)(\n  H46 : array_type_vallist_match OS_TCB \u2217 v'30\n)(\n  H51 : length v'30 = 64%nat\n)(\n  x0 : val\n)(\n  H54 : array_type_vallist_match Int8u v'36\n)(\n  H58 : length v'36 = \u2218 OS_RDY_TBL_SIZE\n)(\n  i7 : int32\n)(\n  H55 : Int.unsigned i7 <= 255\n)(\n  H57 : prio_in_tbl ($ OS_IDLE_PRIO) v'36\n)(\n  H56 : RL_Tbl_Grp_P v'36 (Vint32 i7)\n)(\n  x2 : int32\n)(\n  H59 : length OSUnMapVallist = 256%nat\n)(\n  H62 : true = rule_type_val_match Int8u (Vint32 x2)\n)(\n  fffbb : Int.unsigned x2 < 8\n)(\n  x4 : int32\n)(\n  H64 : Int.unsigned x4 <= 255\n)(\n  H65 : (Z.to_nat (Int.unsigned x4) < length OSUnMapVallist)%nat\n)(\n  x5 : int32\n)(\n  H66 : nth_val' (Z.to_nat (Int.unsigned x4)) OSUnMapVallist = Vint32 x5\n)(\n  H67 : Int.unsigned x5 <= 255\n)(\n  ttfasd : Int.unsigned x5 < 8\n)(\n  H27 : isptr x7\n)(\n  H38 : isptr m\n)(\n  x14 : int32\n)(\n  H82 : x14 = $ OS_STAT_RDY \\/\n        x14 = $ OS_STAT_SEM \\/\n        x14 = $ OS_STAT_Q \\/ x14 = $ OS_STAT_MBOX \\/ x14 = $ OS_STAT_MUTEX\n)(\n  x15 : val\n)(\n  H84 : x14 = $ OS_STAT_RDY -> x15 = Vnull\n)(\n  H37 : isptr x15\n)(\n  H40 : Int.unsigned x14 <= 255\n)(\n  last_condition : ProtectWrapper (x14 = $ OS_STAT_RDY /\\ i6 = $ 0)\n)(\n  r2 : Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7) < 8\n)(\n  r3 : Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3) < 8\n)(\n  H34 : array_type_vallist_match Int8u OSMapVallist\n)(\n  H69 : length OSMapVallist = 8%nat\n)(\n  H71 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)) < 8)%nat\n)(\n  x8 : int32\n)(\n  H74 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n          OSMapVallist = Vint32 x8\n)(\n  H75 : true = rule_type_val_match Int8u (Vint32 x8)\n)(\n  H76 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)) < 8)%nat\n)(\n  x9 : int32\n)(\n  H78 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)))\n          OSMapVallist = Vint32 x9\n)(\n  H79 : true = rule_type_val_match Int8u (Vint32 x9)\n)(\n  H80 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)) < 8)%nat\n)(\n  x11 : int32\n)(\n  H81 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)))\n          OSMapVallist = Vint32 x11\n)(\n  H83 : true = rule_type_val_match Int8u (Vint32 x11)\n)(\n  rr2 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)) <\n         length v'36)%nat\n)(\n  rr3 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)) <\n         length v'36)%nat\n)(\n  rrr2 : Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7) <\n         Z.of_nat (length v'36)\n)(\n  rrr3 : Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3) <\n         Z.of_nat (length v'36)\n)(\n  HH58 : length v'36 = Z.to_nat 8\n)(\n  aa2 : rule_type_val_match Int8u\n          (nth_val'\n             (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n             v'36) = true\n)(\n  x16 : int32\n)(\n  H91 : Int.unsigned x16 <= 255\n)(\n  x13 : int32\n)(\n  H87 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n          v'36 = Vint32 x13\n)(\n  H90 : Int.unsigned x13 <= 255\n)(\n  x12 : int32\n)(\n  H89 : Int.unsigned x12 <= 255\n)(\n  t1 : int32\n)(\n  t3 : Int.unsigned t1 <= 255\n)(\n  t11 : int32\n)(\n  t13 : Int.unsigned t11 <= 255\n)(\n  H15 : Int.unsigned (x >>\u1d62 $ 8) < 64\n)(\n  H47 : Int.ltu (x >>\u1d62 $ 8) (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) = true\n)(\n  H9 : forall (tid0 : tid) (opr : int32),\n       Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) = Some (tid0, opr) ->\n       Int.ltu (x >>\u1d62 $ 8) opr = true /\\ Int.unsigned opr < 64\n)(\n  backup : RLH_ECBData_P (DMutex (Vint32 x) (Vptr (v'52, $ 0)))\n             (absmutexsem (x >>\u1d62 $ 8)\n                (Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)), w)\n)(\n  H53 : nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8))) v'30 = Some x0\n)(\n  H77 : 0 <= Int.unsigned (x >>\u1d62 $ 8)\n)(\n  H85 : Int.unsigned (x >>\u1d62 $ 8) < 64\n)(\n  H43 : Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3) <= 255\n)(\n  H45 : Int.unsigned ($ 1<<\u1d62((x >>\u1d62 $ 8) >>\u1d62 $ 3)) <= 255\n)(\n  H44 : Int.unsigned ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)) <= 255\n)(\n  H42 : Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7) <= 255\n)(\n  H70 : TcbJoin (v'52, Int.zero) (x >>\u1d62 $ 8, t, m) x10 v'45\n)(\n  H41 : Int.unsigned (x >>\u1d62 $ 8) <= 255\n)(\n  H28 : Int.ltu (x >>\u1d62 $ 8) (x >>\u1d62 $ 8) = false\n)(\n  H73 : R_TCB_Status_P\n          (x7\n           :: v'24\n              :: x15\n                 :: m\n                    :: Vint32 i6\n                       :: Vint32 x14\n                          :: Vint32 (x >>\u1d62 $ 8)\n                             :: Vint32 ((x >>\u1d62 $ 8)&\u1d62$ 7)\n                                :: Vint32 ((x >>\u1d62 $ 8) >>\u1d62 $ 3)\n                                   :: Vint32 ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))\n                                      :: Vint32 ($ 1<<\u1d62((x >>\u1d62 $ 8) >>\u1d62 $ 3))\n                                         :: nil) v'36 \n          (x >>\u1d62 $ 8, t, m)\n)(\n  backup2 : TCBList_P (Vptr (v'52, Int.zero))\n              ((x7\n                :: v'24\n                   :: x15\n                      :: m\n                         :: Vint32 i6\n                            :: Vint32 x14\n                               :: Vint32 (x >>\u1d62 $ 8)\n                                  :: Vint32 ((x >>\u1d62 $ 8)&\u1d62$ 7)\n                                     :: Vint32 ((x >>\u1d62 $ 8) >>\u1d62 $ 3)\n                                        :: Vint32 ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))\n                                           :: Vint32\n                                                ($ 1<<\u1d62((x >>\u1d62 $ 8) >>\u1d62 $ 3))\n                                              :: nil) :: v'35) v'36 v'45\n)(\n  r1 : Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3) < 8\n)(\n  r4 : Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7) < 8\n)(\n  r5 : Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3) < 8\n)(\n  r6 : Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7) < 8\n)(\n  rr1 : (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)) < length v'36)%nat\n)(\n  rr4 : (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7)) < length v'36)%nat\n)(\n  rr5 : (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)) < length v'36)%nat\n)(\n  rr6 : (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7)) < length v'36)%nat\n)(\n  rrr1 : Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3) < Z.of_nat (length v'36)\n)(\n  rrr4 : Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7) < Z.of_nat (length v'36)\n)(\n  rrr5 : Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3) < Z.of_nat (length v'36)\n)(\n  rrr6 : Int.unsigned ((x >>\u1d62 $ 8)&\u1d62$ 7) < Z.of_nat (length v'36)\n)(\n  aa aa3 : rule_type_val_match Int8u\n          (nth_val' (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36) =\n        true\n)(\n  H88 : nth_val' (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36 =\n        Vint32 x16\n)(\n  H86 : nth_val' (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36 =\n        Vint32 x12\n)(\n  H92 : Int.unsigned (x >>\u1d62 $ 8) < Int.unsigned ($ Byte.modulus)\n)(\n  H94 : val_inj\n          (if Int.eq (x >>\u1d62 $ 8) (x >>\u1d62 $ 8)\n           then Some (Vint32 Int.one)\n           else Some (Vint32 Int.zero)) <> Vnull\n)(\n  H95 : val_inj\n          (if Int.eq (x >>\u1d62 $ 8) (x >>\u1d62 $ 8)\n           then Some (Vint32 Int.one)\n           else Some (Vint32 Int.zero)) <> Vundef\n)(\n  H96 : array_type_vallist_match Int8u\n          (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n             v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n)(\n  H97 : (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)) <\n         length\n           (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n              v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))))))%nat\n)(\n  t2 : nth_val'\n         (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n         (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36\n            (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))))) = \n       Vint32 t1\n)(\n  H98 : (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)) <\n         length\n           (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n              v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))))))%nat\n)(\n  t12 : nth_val' (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n          (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n             v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))))) =\n        Vint32 t11\n)(\n  v'34 : val\n)(\n  v'41 : addrval\n)(\n  v'59 : val\n)(\n  v'60 v'61 : int32\n)(\n  v'62 : vallist\n)(\n  v'69 v'71 : val\n)(\n  v'75 v'76 v'77 v'78 v'79 : int32\n)(\n  v'82 v'83 v'84 v'85 v'86 : val\n)(\n  v'87 : int32\n)(\n  v'88 v'89 v'90 v'91 v'92 : val\n)(\n  v'93 : block\n)(\n  v'94 : int32\n)(\n  H146 : (v'93, Int.zero) <> v'41\n)(\n  H113 : nth_val' (Z.to_nat (Int.unsigned v'60)) OSUnMapVallist = Vint32 v'76\n)(\n  H114 : nth_val' (Z.to_nat (Int.unsigned v'76)) v'62 = Vint32 v'77\n)(\n  H115 : nth_val' (Z.to_nat (Int.unsigned v'77)) OSUnMapVallist = Vint32 v'75\n)(\n  H116 : nth_val' (Z.to_nat (Int.unsigned v'76)) OSMapVallist = Vint32 v'79\n)(\n  H117 : nth_val' (Z.to_nat (Int.unsigned v'75)) OSMapVallist = Vint32 v'78\n)(\n  i0 : int32\n)(\n  H123 : Int.unsigned i0 <= 255\n)(\n  H124 : RL_Tbl_Grp_P v'62 (Vint32 v'60)\n)(\n  H125 : array_type_vallist_match Int8u v'62\n)(\n  v'95 : addrval\n)(\n  v'97 : block\n)(\n  H137 : array_type_vallist_match Int8u\n           (update_nth_val (Z.to_nat (Int.unsigned v'76)) v'62\n              (Vint32 (v'77&\u1d62Int.not v'78)))\n)(\n  H141 : length\n           (update_nth_val (Z.to_nat (Int.unsigned v'76)) v'62\n              (Vint32 (v'77&\u1d62Int.not v'78))) = \u2218 OS_EVENT_TBL_SIZE\n)(\n  H2 : ECBList_P v'42 (Vptr (v'97, Int.zero)) v'25 v'27 v'47 v'39\n)(\n  H14 : id_addrval' (Vptr (v'97, Int.zero)) OSEventTbl OS_EVENT = Some v'23\n)(\n  H6 : EcbMod.joinsig (v'97, Int.zero)\n         (absmutexsem (x >>\u1d62 $ 8)\n            (Some (v'52, $ 0, x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)), w) v'48 v'49\n)(\n  H138 : id_addrval' (Vptr (v'97, Int.zero)) OSEventTbl OS_EVENT = Some v'95\n)(\n  H49 : RL_RTbl_PrioTbl_P v'36 v'30 v'41\n)(\n  H50 : R_PrioTbl_P v'30 v'39 v'41\n)(\n  H52 : nth_val (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30 =\n        Some (Vptr v'41)\n)(\n  H93 : array_type_vallist_match OS_TCB \u2217\n          (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n             (update_nth_val\n                (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                (Vptr (v'52, Int.zero))) (Vptr v'41))\n)(\n  H104 : length\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41)) = 64%nat\n)(\n  H102 : RL_RTbl_PrioTbl_P\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (val_inj (or (Vint32 t1) (Vint32 x11))))\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41)) v'41\n)(\n  H103 : R_PrioTbl_P\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41))\n           (TcbMod.set v'39 (v'52, Int.zero)\n              (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m)) v'41\n)(\n  H31 : v'69 <> Vnull\n)(\n  H33 : TCBList_P v'69 v'33 v'36 v'43\n)(\n  H107 : nth_val' (Z.to_nat (Int.unsigned ((v'76<<\u1d62$ 3) +\u1d62  v'75)))\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41)) =\n         Vptr (v'93, Int.zero)\n)(\n  H130 : array_type_vallist_match OS_TCB \u2217\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41))\n)(\n  H143 : length\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41)) = 64%nat\n)(\n  H105 : nth_val' (Z.to_nat (Int.unsigned v'76))\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11))) = Vint32 v'94\n)(\n  H145 : prio_in_tbl ($ OS_IDLE_PRIO)\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11)))\n)(\n  H122 : array_type_vallist_match Int8u\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11)))\n)(\n  H144 : length\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11))) = \u2218 OS_RDY_TBL_SIZE\n)(\n  H121 : RL_Tbl_Grp_P\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11))) (Vint32 i0)\n)(\n  H131 : RL_RTbl_PrioTbl_P\n           (update_nth_val (Z.to_nat (Int.unsigned v'76))\n              (update_nth_val\n                 (Z.to_nat\n                    (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n                 (update_nth_val\n                    (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36\n                    (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n                 (Vint32 (Int.or t1 x11))) (Vint32 (Int.or v'94 v'78)))\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41)) v'41\n)(\n  H11 : array_type_vallist_match Int8u v'62\n)(\n  H19 : length v'62 = \u2218 OS_EVENT_TBL_SIZE\n)(\n  fffbb2 : (Z.to_nat (Int.unsigned x2) < length v'62)%nat\n)(\n  H19'' : length v'62 = Z.to_nat 8\n)(\n  H63 : nth_val' (Z.to_nat (Int.unsigned x2)) v'62 = Vint32 x4\n)(\n  H112 : rel_edata_tcbstat (DMutex (Vint32 x) (Vptr (v'52, $ 0))) v'87\n)(\n  H132 : R_PrioTbl_P\n           (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n              (update_nth_val\n                 (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                 (Vptr (v'52, Int.zero))) (Vptr v'41))\n           (TcbMod.set v'39 (v'52, Int.zero)\n              (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m)) v'41\n)(\n  H108 : tcblist_get (Vptr (v'93, Int.zero)) v'69\n           (v'33 ++\n            (x7\n             :: v'24\n                :: x15\n                   :: m\n                      :: Vint32 i6\n                         :: Vint32 x14\n                            :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n                               :: Vint32 ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)\n                                  :: Vint32\n                                       ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)\n                                     :: Vint32 x11 :: Vint32 x8 :: nil)\n            :: v'35) =\n         Some\n           (v'82\n            :: v'83\n               :: v'84\n                  :: v'85\n                     :: v'86\n                        :: Vint32 v'87\n                           :: v'88 :: v'89 :: v'90 :: v'91 :: v'92 :: nil)\n)(\n  H129 : ptr_in_tcblist (Vptr (v'52, Int.zero)) v'69\n           (set_node (Vptr (v'93, Int.zero))\n              (v'82\n               :: v'83\n                  :: Vnull\n                     :: Vptr (v'97, Int.zero)\n                        :: Vint32 Int.zero\n                           :: Vint32 (v'87&\u1d62Int.not ($ OS_STAT_MUTEX))\n                              :: v'88 :: v'89 :: v'90 :: v'91 :: v'92 :: nil)\n              v'69\n              (v'33 ++\n               (x7\n                :: v'24\n                   :: x15\n                      :: m\n                         :: Vint32 i6\n                            :: Vint32 x14\n                               :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n                                  :: Vint32\n                                       ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)\n                                     :: Vint32\n                                          ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62\n                                           $ 3)\n                                        :: Vint32 x11 :: Vint32 x8 :: nil)\n               :: v'35))\n)(\n  H134 : TCBList_P v'69\n           (v'33 ++\n            (x7\n             :: v'24\n                :: x15\n                   :: m\n                      :: Vint32 i6\n                         :: Vint32 x14\n                            :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n                               :: Vint32 ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)\n                                  :: Vint32\n                                       ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)\n                                     :: Vint32 x11 :: Vint32 x8 :: nil)\n            :: v'35)\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11)))\n           (TcbMod.set v'39 (v'52, Int.zero)\n              (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m))\n)(\n  H21 : Int.unsigned v'60 <= 255\n)(\n  fffa : length OSUnMapVallist = 256%nat ->\n         (Z.to_nat (Int.unsigned v'60) < 256)%nat ->\n         exists x,\n         Vint32 x2 = Vint32 x /\\ true = rule_type_val_match Int8u (Vint32 x)\n)(\n  H60 : (Z.to_nat (Int.unsigned v'60) < 256)%nat\n)(\n  H61 : nth_val' (Z.to_nat (Int.unsigned v'60)) OSUnMapVallist = Vint32 x2\n)(\n  H99 : val_inj\n          (notint\n             (val_inj\n                (if Int.eq v'60 ($ 0)\n                 then Some (Vint32 Int.one)\n                 else Some (Vint32 Int.zero)))) <> \n        Vint32 Int.zero\n)(\n  H100 : val_inj\n           (notint\n              (val_inj\n                 (if Int.eq v'60 ($ 0)\n                  then Some (Vint32 Int.one)\n                  else Some (Vint32 Int.zero)))) <> Vnull\n)(\n  H101 : val_inj\n           (notint\n              (val_inj\n                 (if Int.eq v'60 ($ 0)\n                  then Some (Vint32 Int.one)\n                  else Some (Vint32 Int.zero)))) <> Vundef\n)(\n  H68 : v'60 = $ 0 \\/\n        Int.ltu ((x2<<\u1d62$ 3) +\u1d62  x5) (x >>\u1d62 $ 8) = false /\\\n        (x2<<\u1d62$ 3) +\u1d62  x5 <> x >>\u1d62 $ 8\n)(\n  H142 : struct_type_vallist_match OS_EVENT\n           (update_nth_val 1\n              (V$ OS_EVENT_TYPE_MUTEX\n               :: Vint32 v'60\n                  :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil)\n              (Vint32 v'61))\n)(\n  H18 : RL_Tbl_Grp_P v'62 (Vint32 v'60)\n)(\n  H1 : ECBList_P v'42 Vnull\n         (v'25 ++\n          ((V$ OS_EVENT_TYPE_MUTEX\n            :: Vint32 v'60\n               :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil, v'62)\n           :: nil) ++ v'26)\n         (v'27 ++ (DMutex (Vint32 x) (Vptr (v'52, $ 0)) :: nil) ++ v'28) v'38\n         v'39\n)(\n  H5 : R_ECB_ETbl_P (v'97, Int.zero)\n         (V$ OS_EVENT_TYPE_MUTEX\n          :: Vint32 v'60 :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil,\n         v'62) v'39\n)(\n  H133 : R_ECB_ETbl_P (v'97, Int.zero)\n           (V$ OS_EVENT_TYPE_MUTEX\n            :: Vint32 v'60\n               :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil, v'62)\n           (TcbMod.set v'39 (v'52, Int.zero)\n              (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m))\n)(\n  H140 : RL_Tbl_Grp_P\n           (update_nth_val (Z.to_nat (Int.unsigned v'76)) v'62\n              (Vint32 (v'77&\u1d62Int.not v'78))) (Vint32 v'61)\n       )\n(struct_type_vallist_match_condition : struct_type_vallist_match OS_TCB_flag\n           (v'82\n            :: v'83\n               :: v'84\n                  :: v'85\n                     :: v'86\n                        :: Vint32 v'87\n                           :: v'88 :: v'89 :: v'90 :: v'91 :: v'92 :: nil))\n,\n   {|OS_spec, GetHPrio, OSLInv, I,\n   fun v : option val =>\n   ( <|| END v ||>  **\n    p_local OSLInv (v'52, Int.zero) init_lg **\n    ((EX v0 : val, LV pevent @ OS_EVENT \u2217 |-> v0) **\n     (EX v0 : val, LV os_code_defs.x @ Int8u |-> v0) **\n     (EX v0 : val, LV pip @ Int8u |-> v0) **\n     (EX v0 : val, LV prio @ Int8u |-> v0) **\n     (EX v0 : val, LV legal @ Int8u |-> v0) ** Aemp) **\n    Aie true ** Ais nil ** Acs nil ** Aisr empisr) **\n   A_dom_lenv\n     ((pevent, OS_EVENT \u2217)\n      :: (os_code_defs.x, Int8u)\n         :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil), Afalse|}\n   |- (v'52, Int.zero)\n   {{ <|| mutexpost (Vptr (v'97, Int.zero) :: nil) ||>  **\n     LV pevent @ OS_EVENT \u2217 |-> Vptr (v'97, Int.zero) **\n     Astruct (v'97, Int.zero) OS_EVENT\n       (V$ OS_EVENT_TYPE_MUTEX\n        :: Vint32 v'61\n           :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_UPPER_8)\n              :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil) **\n     Aarray v'95 (Tarray Int8u \u2218 OS_EVENT_TBL_SIZE)\n       (update_nth_val (Z.to_nat (Int.unsigned v'76)) v'62\n          (Vint32 (v'77&\u1d62Int.not v'78))) **\n     p_local OSLInv (v'52, Int.zero) init_lg **\n     Aie false **\n     Ais nil **\n     Acs (true :: nil) **\n     Aisr empisr **\n     A_isr_is_prop **\n     AEventData\n       (update_nth_val 1\n          (V$ OS_EVENT_TYPE_MUTEX\n           :: Vint32 v'60\n              :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil)\n          (Vint32 v'61)) (DMutex (Vint32 x) (Vptr (v'52, $ 0))) **\n     AOSUnMapTbl **\n     AOSMapTbl **\n     AOSRdyTblGrp\n       (update_nth_val (Z.to_nat (Int.unsigned v'76))\n          (update_nth_val\n             (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n             (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n             (Vint32 (Int.or t1 x11))) (Vint32 (Int.or v'94 v'78))) v'59 **\n     GAarray OSTCBPrioTbl (Tarray OS_TCB \u2217 64)\n       (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n          (update_nth_val\n             (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n             (Vptr (v'52, Int.zero))) (Vptr v'41)) **\n     tcbdllseg v'69 Vnull v'71 Vnull\n       (set_node (Vptr (v'93, Int.zero))\n          (v'82\n           :: v'83\n              :: Vnull\n                 :: Vptr (v'97, Int.zero)\n                    :: Vint32 Int.zero\n                       :: Vint32 (v'87&\u1d62Int.not ($ OS_STAT_MUTEX))\n                          :: v'88 :: v'89 :: v'90 :: v'91 :: v'92 :: nil)\n          v'69\n          (v'33 ++\n           (x7\n            :: v'24\n               :: x15\n                  :: m\n                     :: Vint32 i6\n                        :: Vint32 x14\n                           :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n                              :: Vint32 ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)\n                                 :: Vint32\n                                      ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)\n                                    :: Vint32 x11 :: Vint32 x8 :: nil)\n           :: v'35)) **\n     LV prio @ Int8u |-> Vint32 ((v'76<<\u1d62$ 3) +\u1d62  v'75) **\n     PV v'41 @ Int8u |-> v'34 **\n     LV os_code_defs.x @ Int8u |-> (V$ OS_STAT_MUTEX) **\n     LV legal @ Int8u |-> Vint32 x2 **\n     GV OSTCBList @ OS_TCB \u2217 |-> v'69 **\n     GV OSTCBCur @ OS_TCB \u2217 |-r-> Vptr (v'52, Int.zero) **\n     LV pip @ Int8u |-> Vint32 (x >>\u1d62 $ 8) **\n     GV OSEventList @ OS_EVENT \u2217 |-> v'42 **\n     evsllseg v'42 (Vptr (v'97, Int.zero)) v'25 v'27 **\n     evsllseg v'46 Vnull v'26 v'28 **\n     HECBList v'38 **\n     HTCBList v'39 **\n     HCurTCB (v'52, Int.zero) **\n     AOSEventFreeList v'3 **\n     AOSQFreeList v'4 **\n     AOSQFreeBlk v'5 **\n     AOSIntNesting **\n     AOSTCBFreeList v'21 v'22 **\n     AOSTime (Vint32 v'18) **\n     HTime v'18 **\n     AGVars **\n     atoy_inv' **\n     A_dom_lenv\n       ((pevent, OS_EVENT \u2217)\n        :: (os_code_defs.x, Int8u)\n           :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil) **\n     G& OSPlaceHolder @ Int8u == v'41 **\n     tcbdllflag v'69\n       (v'33 ++\n        (x7\n         :: v'24\n            :: x15\n               :: m\n                  :: Vint32 i6\n                     :: Vint32 x14\n                        :: Vint32 (x >>\u1d62 $ 8)\n                           :: Vint32 ((x >>\u1d62 $ 8)&\u1d62$ 7)\n                              :: Vint32 ((x >>\u1d62 $ 8) >>\u1d62 $ 3)\n                                 :: Vint32 ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7))\n                                    :: Vint32 ($ 1<<\u1d62((x >>\u1d62 $ 8) >>\u1d62 $ 3))\n                                       :: nil) :: v'35)}} \n   pevent \u2032 \u2192 OSEventCnt =\u2091 pevent \u2032 \u2192 OSEventCnt |\u2091 prio \u2032;\u209b\n   pevent \u2032 \u2192 OSEventPtr =\u2091 OSTCBPrioTbl \u2032 [prio \u2032];\u209b\n   EXIT_CRITICAL;\u209b\n   OS_Sched (\u00ad);\u209b\n                  RETURN \u2032 OS_NO_ERR {{Afalse}}.\n  \nProof.\n  intros.\n  rewrite H113 in H61.\n  inversion H61.\n  subst v'76.\n  rewrite H114 in H63.\n  inversion H63.\n  subst v'77.\n  rewrite H115 in H66.\n  inversion H66.\n  subst v'75.\n\n\n  \n  simpl ((update_nth_val 1\n              (V$ OS_EVENT_TYPE_MUTEX\n               :: Vint32 v'60\n                  :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil)\n              (Vint32 v'61))) in H142.\n  \n  hoare forward.\n  (* intro; tryfalse. *)\n\n  clear -H142; unfold OS_EVENT in *; simpl in *.\n  simpljoin; splits; auto.\n  math simpls.\n  eapply acpt_int_lemma0.\n  math simpl in H1.\n  exact H1.\n\n  math simpls.\n  clear -fffbb ttfasd; mauto.\n  try intro; tryfalse.\n\n  hoare forward.\n\n  clear -fffbb ttfasd; mauto.\n  clear -fffbb ttfasd; mauto.\n\n  rewrite update_nth_val_len_eq.\n  rewrite update_nth_val_len_eq.\n  rewrite H51.\n\n  clear -fffbb ttfasd; mauto.\n  \n  \n  \n  unfolds; simpl; auto.\n  rewrite H107.\n  reflexivity.\n\n  \n  assert (exists vvv, v'88 = Vint32 vvv).\n  {\n    clear -struct_type_vallist_match_condition.\n    unfolds in struct_type_vallist_match_condition.\n    unfold OS_TCB_flag in struct_type_vallist_match_condition.\n    simpl in struct_type_vallist_match_condition; simpljoin.\n    clear -H5; destruct v'88; tryfalse; eauto.\n    \n  }\n  simpljoin.\n  lets newtmp: tcblist_get_TCBList_P_get  H134.\n  eauto.\n  go.\n  simpljoin.\n\n  rename x1 into newowner_prio.\n  rename x6 into newowner_st.\n  rename x17 into newowner_msg.\n\n\nLemma post_exwt_succ_pre_mutex_new\n     : forall (v'36 v'13 : vallist) (v'12 : int32) \n         (v'32 : block) (v'15 : int32) (v'24 : block) \n         (v'35 v'0 : val) (v'8 : tid) (v'9 v'11 : EcbMod.map)\n         (x : val) (x0 : maxlen) (x1 : waitset)\n         (v'6 v'10 : EcbMod.map) (v'38 v'69 v'39 : int32) \n         (v'58 : block) (b : taskstatus) \n         (c :msg) (v'62 v'7 : TcbMod.map) \n         (vhold : addrval) pr o a ,\n       v'12 <> Int.zero ->\n       R_PrioTbl_P v'36 v'7 vhold ->\n       RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n       R_ECB_ETbl_P (v'32, Int.zero)\n         (V$OS_EVENT_TYPE_MUTEX\n          :: Vint32 v'12\n             :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n         v'13) v'7 ->\n       RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n       EcbMod.join v'9 v'10 v'11 ->\n       EcbMod.joinsig (v'32, Int.zero) (absmutexsem pr o , x1) v'6 v'10 ->\n       Int.unsigned v'12 <= 255 ->\n       array_type_vallist_match Int8u v'13 ->\n       length v'13 = \u2218OS_EVENT_TBL_SIZE ->\n       nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n       Int.unsigned v'38 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n       Int.unsigned v'69 <= 255 ->\n       nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n       Int.unsigned v'39 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39))) v'36 =\n       Vptr (v'58, Int.zero) ->\n       TcbJoin (v'58, Int.zero) (a, b, c) v'62 v'7 ->\n       a = (v'38<<\u1d62$ 3)+\u1d62v'39/\\ x1 <> nil /\\\n       (exists  b'', b = (wait (os_stat_mutexsem (v'32, Int.zero)) b'')) /\\\n       GetHWait v'7 x1 (v'58, Int.zero) /\\\n       TcbMod.get v'7 (v'58, Int.zero) = Some (a, b, c)\n.\nProof.\n  intros.\n  lets Hs :  tcbjoin_get_a  H16.\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  unfolds in H2.\n  destruct H2.\n  destruct H17 as (H17&Htype).\n  unfolds in H2.\n  unfolds in H17.\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  clear H16.\n  assert ( Int.unsigned v'38 < 8) as Hx by omega.\n  assert (Int.unsigned v'39 < 8) as Hy by omega.\n  clear H10 H12.\n  lets Hrs : math_xy_prio_cons Hx Hy.\n  unfold nat_of_Z in H0.\n  destruct H0 as (Hpr1 & Hpr2).\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  destruct Hpr2.\n  apply H0 in Hs.\n  destruct Hs;auto.\n  lets Hnth : nth_val'_imp_nth_val_vptr H15.\n  lets Hsd : Hpr1 Hrs Hnth.\n  destruct Hsd as (st & m & Hst);auto.\n  unfold get in *;simpl in *.\n  rewrite Hs in Hst.\n  inverts Hst.\n  split.\n  auto.\n  assert (Int.shru ((v'38<<\u1d62$ 3)+\u1d62v'39) ($ 3)= v'38).\n  eapply math_shrl_3_eq; eauto.\n  eapply nat_8_range_conver; eauto.\n  assert ( (Z.to_nat (Int.unsigned v'38))  < length v'13)%nat.\n  rewrite H8.\n  simpl.\n  unfold Pos.to_nat; simpl.\n  clear - Hx.\n  mauto.\n  lets Has : array_int8u_nth_lt_len H7 H4.\n  destruct Has as (i & Hnthz & Hinsa).\n  rewrite H11 in Hnthz.\n  inverts Hnthz.\n  assert ((((v'38<<\u1d62$ 3)+\u1d62v'39)&\u1d62$ 7) = v'39).\n  eapply math_8range_eqy; eauto.\n  eapply  nat_8_range_conver; eauto.\n  apply nth_val'_imp_nth_val_int in H11.\n  assert ( Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 H11 H10.\n  eapply  nat_8_range_conver; eauto.\n  destruct Hzs.\n  lets Has : math_8_255_eq H6 H9 H.\n  assert (i <> $ 0).\n  assert ($ 1<<\u1d62$ Z.of_nat \u2218(Int.unsigned v'38) = $ 1<<\u1d62v'38).\n  clear -Hx.\n  mauto.\n  rewrite H18 in H16.\n  apply H16 in Has.\n  apply ltu_eq_false in Has.\n  pose (Int.eq_spec i ($0)).\n  rewrite Has in y.\n  auto.\n  assert (PrioWaitInQ (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39)) v'13).\n  unfolds.\n  rewrite Int.repr_unsigned in *.\n  exists ( ((v'38<<\u1d62$ 3)+\u1d62v'39)&\u1d62$ 7 ).\n  exists (Int.shru ((v'38<<\u1d62$ 3)+\u1d62v'39) ($ 3) ).\n  rewrite H0 in *.\n  exists i.\n  splits; eauto.\n  rewrite H5.\n  eapply math_8_255_eq; eauto.\n  destruct H2 as (H2'&H2''&Hres&H2).\n  lets Hes : H2 H19.\n  unfold V_OSEventType in Hes.\n  simpl nth_val in Hes.\n  assert (Some (V$OS_EVENT_TYPE_MUTEX) = Some (V$OS_EVENT_TYPE_MUTEX)) by auto.\n  apply Hes in H20.\n  clear Hes.\n  rename H20 into Hes.\n  destruct Hes as (td & nn &mm & Hge).\n  destruct Hpr2 as (Hpr2 & Hpr3).\n  unfolds in Hpr3.\n  assert (td = (v'58, Int.zero)  \\/ td <> (v'58, Int.zero) ) by tauto.\n  destruct H20.\n  Focus 2.\n  lets Hass : Hpr3 H20 Hge Hs.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  rewrite Int.repr_unsigned in *.\n  subst td.\n    unfold get in *; simpl in *.\n\n  rewrite Hs in Hge.\n  inverts Hge.\n  destruct H3 as (H3'&H3''&Hres'&H3).\n  destruct H3 as (Heg1 & Heg2 & Heg3).\n  lets Hrgs : Heg2 Hs.\n  destruct Hrgs as (xx & z &  qw & Hem & Hin).\n  unfold get in *; simpl in *.\n\n  rewrite Hg in Hem.\n  inverts Hem.\n\n\n\n  assert (qw = nil \\/ qw <> nil) by tauto.\n  destruct H3.\n  subst qw.\n  simpl in Hin; tryfalse.\n  splits; auto.\n  eauto.\n  unfolds.\n  splits; auto.\n  do 3 eexists; splits; eauto.\n  intros.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (absmutexsem xx z, qw) /\\ In t' qw) .\n  splits; auto.\n  lets Habs : Heg1 H22.\n  destruct Habs as (prio' & m' & n' & Hbs).\n  do 3 eexists; splits; eauto.\n  destruct H17 as (H17'&H17''&Hres''&H17).\n  lets Hpro : H17 Hbs.\n  destruct Hpro as (Hpro&Hss).\n  clear Hss.\n  unfolds in Hpro.\n  destruct Hpro as (xa & xb & zz & Hran & Hxx & Hyy & Hnths & Hzz).\n  subst xa xb.\n  rewrite Int.repr_unsigned in *.\n  lets Hat : math_highest_prio_select H13 H9 H11 Hnths  Hzz;\n    try eapply int_usigned_tcb_range; try omega;\n    eauto.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 Hnths H23.\n  eapply nat_8_range_conver; eauto.\n  try eapply int_usigned_tcb_range; eauto.  \n  destruct Hzs.\n  assert (zz = $ 0 \\/ zz <> $ 0) by tauto.\n  destruct H26.\n  subst zz.\n  rewrite Int.and_commut in Hzz.\n  rewrite Int.and_zero in Hzz.\n  unfold Int.one in *.\n  unfold Int.zero in *.\n  assert ($ 1<<\u1d62(prio'&\u1d62$ 7) <> $ 0 ).\n  eapply math_prop_neq_zero2; eauto.\n  tryfalse.\n  assert (Int.ltu ($ 0) zz = true).\n  clear - H26.\n  int auto.\n  assert (0<=Int.unsigned zz ).\n  int auto.\n  assert (Int.unsigned zz = 0).\n  omega.\n  rewrite <- H0 in H26.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  apply H25 in H27.\n  assert ($ Z.of_nat \u2218(Int.unsigned (Int.shru prio' ($ 3))) = (Int.shru prio' ($ 3))).\n  clear -Hran.\n  mauto.\n  rewrite H28 in *.\n  auto.\n  lets Hasss : Hpr3 H20 Hs Hbs; eauto.\n  unfolds.\n  rewrite zlt_true; auto.\n  assert (Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) < Int.unsigned prio' \\/\n          Int.unsigned ((v'38<<\u1d62$ 3)+\u1d62v'39) = Int.unsigned prio').\n  omega.\n  destruct H23; auto; tryfalse.\n  false.\n  apply Hasss.\n  apply unsigned_inj; eauto.\nQed.\n\n\n\nassert ( newowner_prio = ((x2<<\u1d62$ 3)+\u1d62x5) /\\\n           w<>nil /\\\n           (exists  b'', newowner_st = (wait (os_stat_mutexsem (v'97, Int.zero)) b'')) /\\\n           GetHWait (TcbMod.set v'39 (v'52, Int.zero) (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m)) w (v'93,Int.zero) /\\\n           TcbMod.get (TcbMod.set v'39 (v'52, Int.zero) (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, t, m)) (v'93,Int.zero) = Some (newowner_prio,newowner_st,newowner_msg)).\n\nlets wzsrlgl: H61.\napply get_join in wzsrlgl.\ndestruct wzsrlgl as (wzs & rlgl).\n  {\n  eapply  post_exwt_succ_pre_mutex_new.\n  eauto.\n  eauto.\n  eauto.\n  4:exact H133.\n  10: assumption.\n  10: clear -fffbb; omega.\n  10: eauto.\n  3:go.\n  7:assumption.\n  7:assumption.\n  7:assumption.\n  7:assumption.\n  6:assumption.\n  6: clear -ttfasd; omega.\n  6:exact H107.\n  2:go.\n  4: exact H6.\n\n  Focus 2.\n  instantiate ( 1:=  (v'52, Int.zero)).\n  unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in t0.\n  destruct x18; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 r H73 ll lll).\n  subst t.\n  eapply return_rh_tcbl_ecbl_p; eauto.\n  2:eauto.\n  {\n    clear -H99.\n    remember (Int.eq v'60 ($ 0)) as b; destruct b; intro; subst; int auto.\n   }\n\n  exact rlgl.\n\n  }\n  \n\n  hoare abscsq.\n  apply noabs_oslinv.\n\n  (* mutex absop rules *)\n\n  eapply absinfer_mutexpost_return_exwt_succ. \n  go.\n  unfold get; simpl.\n  go.\n  simpljoin; go.\n\n  assert (t=rdy).\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n\n  unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in H120.\n\n  destruct x18; destruct p; simpljoin.\n  apply (OSTimeDlyPure.low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H120 H73 ll lll).\n  subst t.\n\n\n  eapply  return_gethwait; eauto.\n  instantiate (3 := v'97).\n\n  go.\n\n\n  unfold join in H32; simpl in H32.\n  unfold TcbJoin in H70; unfold join in H70; unfold sig in H70; simpl in H70.\n  \n  go.\n  simpljoin; eauto 1.\n  (*\n TcbMod.get\n          (TcbMod.set v'39 (v'52, Int.zero)\n             (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8, rdy, m)) \n          (v'93, Int.zero) = Some (newowner_prio, newowner_st, newowner_msg)\n (exists b' b'', newowner_st = wait (os_stat_mutexsem b') b'') \n  they cannot be same\n   *)\n  simpljoin.\n  clear -H61.\n  intro H; rewrite H in H61.\n  unfold get in H61; simpl in H61.\n  rewrite TcbMod.set_a_get_a in H61; tryfalse.\n  go.\n\n\n  unfold get ; simpl.\n  unfold join in H32; simpl in H32.\n  unfold TcbJoin in H70; unfold join in H70; unfold sig in H70; simpl in H70.\n  \n  go.\n\n \n  unfold get ; simpl.\n  unfold join in H32; simpl in H32.\n  unfold TcbJoin in H70; unfold join in H70; unfold sig in H70; simpl in H70.\n  \n  simpljoin.\n \n  rewrite TcbMod.set_a_get_a' in e1.\n  go.\n  (* same as before *)\n  (* clear -H147; go. *)\n\n  assert ( (v'52 , Int.zero) <> (v'93, Int.zero)).\n  unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in H109.\n  destruct x19; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H118 H73 ll lll).\n  subst t.\n\n  simpljoin.\n  clear -H61.\n  intro H; rewrite H in H61.\n  unfold get in H61; simpl in H61.\n  rewrite TcbMod.set_a_get_a in H61; tryfalse.\n  go.\n  clear -H63.\n\n  go.\n\n  remember (update_nth_val (Z.to_nat (Int.unsigned x2))\n          (update_nth_val\n             (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n             (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n             (Vint32 (Int.or t1 x11))) (Vint32 (Int.or v'94 v'78)))  as rdy_tbl.\n  remember       (update_nth_val (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n          (update_nth_val\n             (Z.to_nat (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n             (Vptr (v'52, Int.zero))) (Vptr v'41))(*       (update_nth_val (Z.to_nat (Int.unsigned (v'55>>\u1d62$ 8)))\n                                       * (update_nth_val\n                                       *    (Z.to_nat (Int.unsigned (v'55&$ OS_MUTEX_KEEP_LOWER_8)))\n                                       *    v'30 (Vptr (v'52, Int.zero))) (Vptr v'51)) *) as prio_tbl.\n\n  (* assert ( (Z.to_nat (Int.unsigned v'63)) < length rdy_tbl)%nat as fa.\n   * rewrite H152.\n   * clear -fffbb.\n   * mauto.\n   * lets aaa: array_int8u_nth_lt_len H151 fa.\n   * destruct aaa as (a1 & a2 & a3). *)\n  hoare lift 20%nat pre.\n  simpljoin.\n  lets bbb: TCBList_P_tcblist_get_TCBNode_P H108 H61.\n  eauto.\n\n  eapply backward_rule1.\n  intro.\n  \n  eapply set_node_elim.\n  2:eauto.\n  2:eauto.\n  2:  eauto.\n  5: compute; auto.\n  exact H129.\n  {\n    instantiate (3:=(update_nth_val (Z.to_nat (Int.unsigned x2))\n              (update_nth_val\n                 (Z.to_nat\n                    (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n                 (update_nth_val\n                    (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36\n                    (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n                 (Vint32 (Int.or t1 x11))) (Vint32 (Int.or v'94 v'78)))).\n   instantiate (1 := Vptr (v'97, Int.zero)).\n   instantiate (1 := rdy ).\n\n    eapply  TCBNode_P_set_rdy ; try assumption.\n    clear -fffbb ttfasd; mauto.\n    apply nth_val'2nth_val.\n    rewrite math_shrl_3_eq.\n    exact H105.\n    clear -ttfasd; mauto.\n    clear -fffbb; mauto.\n    assert ( rule_type_val_match Int8u (nth_val' (Z.to_nat (Int.unsigned x2))\n           (update_nth_val\n              (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n              (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n                 v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n              (Vint32 (Int.or t1 x11)))) = true).\n    apply array_type_vallist_match_imp_rule_type_val_match.\n    rewrite H144.\n    clear -fffbb; mauto.\n    assumption.\n    rewrite H105 in H63.\n    clear -H63.\n    unfolds in H63.\n    math simpl in H63.\n    auto.\n    4:exact bbb.\n    unfolds in H112; subst v'87; clear.\n    apply Int.and_not_self.\n    rewrite math_shrl_3_eq.\n    auto.\n    clear -ttfasd; mauto.\n    clear -fffbb; mauto.\n \n    rewrite math_8range_eqy.\n    2: clear -fffbb; mauto.\n    2: clear -ttfasd; mauto.\n\n\n    cut (Vint32 v'78 = Vint32 ($1 <<\u1d62 x5)).\n    clear; intro H; inverts H.\n    reflexivity.\n    rewrite <- H117.\n    apply xmapis1shlx.\n    clear -ttfasd; mauto.\n\n    (**************************TODO************************)\n    (* Lemma tcbnode_p_hold:\n     *   forall v'82 v'83 v'84 v'85 v'86 v'87 x2 x5 v'89 v'90 v'91 v'92 vl  x1 x6 newowner_msg new_msg,\n     *    TCBNode_P\n     *       (v'82\n     *        :: v'83\n     *           :: v'84\n     *              :: v'85\n     *                 :: v'86\n     *                    :: Vint32 v'87\n     *                       :: Vint32 ((x2<<\u1d62$ 3) +\u1d62  x5)\n     *                          :: v'89 :: v'90 :: v'91 :: v'92 :: nil)\n     *       vl\n     *       ((x2<<\u1d62$ 3) +\u1d62  x5, wait (os_stat_mutexsem x1) x6, newowner_msg)\n     *    ->\n     *     TCBNode_P\n     *  (v'82\n     *   :: v'83\n     *      :: Vnull\n     *         :: new_msg\n     *            :: Vint32 Int.zero\n     *               :: V$ OS_STAT_RDY\n     *                  :: Vint32 ((x2<<\u1d62$ 3) +\u1d62  x5)\n     *                     :: v'89 :: v'90 :: v'91 :: v'92 :: nil)\n     * vl ((x2<<\u1d62$ 3) +\u1d62  x5, rdy, new_msg).\n     * Proof.\n     *   SearchAbout TCBNode_P.\n     *   intros.\n     *   unfold TCBNode_P in *.\n     *   simpljoin.\n     *   splits.\n     *   Check set_node_elim_hoare.\n     *   unfolds; simpl; auto.\n     *   go.\n     *   clear -H1.\n     *   unfold RL_TCBblk_P in *.\n     *   simpljoin.\n     *   do 6 eexists.\n     *   splits.\n     *   go.\n     *   eauto.\n     *   eauto.\n     *   eauto.\n     *   eauto.\n     *   unfolds.\n     *   simpl.\n     *   go.\n     *   inverts H.\n     *   auto.\n     *   inverts H.\n     *   splits; auto.\n     *   eexists.\n     *   splits.\n     *   go.\n     *   intro; auto.\n     *   clear -H2.\n     *   unfold R_TCB_Status_P in *.\n     *   simpljoin; splits;\n     *   match goal with\n     *     | H: ?f _ _ _ |- ?f _ _ _ => clear -H; unfold f in *\n     *   end.\n     *   intros.\n     *   apply H in H0.\n     *   simpljoin; splits;\n     *   match goal with\n     *     | H: ?f _ _ _ |- ?f _ _ _ => clear -H; unfold f in *\n     *   end.\n     *   intros.\n     *   inverts H.\n     *   splits;  auto.\n     *   splits;  auto.\n     *   admit.\n     * \n     *   simpljoin; splits;\n     *   match goal with\n     *     | H: ?f _ _ _ |- ?f _ _ _ => clear -H; unfold f in *\n     *   end.\n     *   intros.\n     *   unfolds in H0.\n     *   apply H in H0.\n     *   inverts H.\n     *   splits;  auto.\n     *   splits;  auto.\n     *   admit.\n     * \n     * \n     *   \n     *   \n     * Admitted.\n     * Show.\n     * eapply tcbnode_p_hold; auto.\n     * unfolds in H112.\n     * \n     * exact bbb. *)\n  \n  }\n\n\n  remember ((update_nth_val\n        (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n        (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3))) v'36\n           (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n        (Vint32 (Int.or t1 x11)))) as rtbl.\n  {\n    unfolds.\n    assert((((x2<<\u1d62$ 3) +\u1d62  x5) >>\u1d62 $ 3) = x2) as eq1.\n    clear -fffbb ttfasd; mauto.\n    rewrite eq1.\n    assert((((x2<<\u1d62$ 3) +\u1d62  x5)&\u1d62$ 7) = x5) as eq2.\n    clear -fffbb ttfasd; mauto.\n    rewrite eq2.\n    do 3 eexists.\n    clear - fffbb ttfasd.\n    mauto.\n    splits; eauto.\n\n                                                                     \n  }\n\n  {\n    Lemma mutex_post_nodup:\n      forall v'30 v'39 v'41 prio' t m v'52,\n        R_PrioTbl_P v'30 v'39 v'41 ->\n        nth_val (Z.to_nat (Int.unsigned prio')) v'30 = Some (Vptr v'41) ->\n        R_Prio_No_Dup (TcbMod.set v'39 (v'52, Int.zero) (prio', t, m)).\n    Proof.\n      intros.\n      unfolds in H.\n      simpljoin.\n      unfolds.\n      intros.\n      assert ( tid = (v'52, Int.zero) \\/ tid <> (v'52, Int.zero)) by tauto.\n      destruct H6; intros.\n      subst tid.\n      unfold get in *; simpl in *.\n      rewrite TcbMod.set_a_get_a in H4.\n      inverts H4.\n      2:go.\n      rewrite TcbMod.set_a_get_a' in H5.\n      2:go.\n      lets ff: H1 H5.\n      simpljoin.\n      intro.\n      subst prio.\n      unfold nat_of_Z in H4.\n      rewrite H0 in H4.\n      inverts H4.\n      apply H6; auto.\n\n      rewrite TcbMod.set_a_get_a' in H4.\n      2:go.\n      assert ( tid' = (v'52, Int.zero) \\/ tid' <> (v'52, Int.zero)) by tauto.\n\n      destruct H7; intros.\n      subst tid'.\n\n      unfold get in *; simpl in *.\n      rewrite TcbMod.set_a_get_a in H5.\n      2:go.\n      inverts H5.\n\n      lets bb: H1 H4.\n      simpljoin.\n      intro; subst.\n      unfold nat_of_Z in H5.\n      rewrite H5 in H0.\n      inverts H0.\n      apply H7; auto.\n\n      unfold get in H5.\n      simpl in H5.\n      rewrite TcbMod.set_a_get_a' in H5; go.\n      unfolds in H2.\n      eapply H2.\n      2:eauto.\n      2:eauto.\n      auto.\n    Qed.\n\n    eapply mutex_post_nodup; eauto.\n    }\n\n      \n  hoare forward prim.\n  unfold AECBList.\n  unfold AOSMapTbl.\n  unfold AOSUnMapTbl.\n  unfold AOSTCBPrioTbl.\n  unfold AOSTCBList.\n  unfold AOSRdyTblGrp.\n  unfold AOSRdyTbl.\n  unfold AOSRdyGrp.\n  sep pauto.\n\n\n  sep cancel 1%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  sep cancel 6%nat 1%nat.\n  sep cancel 12%nat 2%nat.\n  (* sep lift 3%nat. *)\n  eapply evsllseg_compose with\n  (qptrl1:= v'25)\n    (qptrl2:=v'26)\n    (l:= (V$ OS_EVENT_TYPE_MUTEX\n              :: Vint32 v'61\n                 :: Vint32\n                      (Int.or (x&\u1d62$ OS_MUTEX_KEEP_UPPER_8)\n                         ((x2<<\u1d62$ 3) +\u1d62  x5))\n                    :: nth_val' (Z.to_nat (Int.unsigned ((x2<<\u1d62$ 3) +\u1d62  x5)))\n                         (update_nth_val\n                            (Z.to_nat (Int.unsigned (x >>\u1d62 $ 8)))\n                            (update_nth_val\n                               (Z.to_nat\n                                  (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)))\n                               v'30 (Vptr (v'52, Int.zero))) \n                            (Vptr v'41)) :: x3 :: v'46 :: nil))\n       (* (V$OS_EVENT_TYPE_MUTEX\n        *     ::  Vint32 (v'58&\u1d62Int.not v'67)\n        *     :: Vint32 (Int.or (v'55&\u1d62$ OS_MUTEX_KEEP_UPPER_8)\n        *                       ((v'63<<\u1d62$ 3)+\u1d62v'65))\n        *     ::  nth_val'\n        *     (Z.to_nat (Int.unsigned ((v'63<<\u1d62$ 3)+\u1d62v'65)))\n        *     (update_nth_val\n        *        (Z.to_nat (Int.unsigned (v'55>>\u1d62$ 8)))\n        *        (update_nth_val\n        *           (Z.to_nat\n        *              (Int.unsigned\n        *                 (v'55&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n        *           (Vptr (v'52, Int.zero))) \n        *        (Vptr v'51)) :: v'61 :: v'57 :: nil)) *)\n    (msgqls1:=v'27)\n    (msgqls2 := v'28)\n    (tl:=(Vptr (v'97, Int.zero)))\n    (x:=(* (update_nth_val\n         *       (Z.to_nat (Int.unsigned ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62 $ 3)))\n         *       (update_nth_val (Z.to_nat (Int.unsigned ((x >>\u1d62 $ 8) >>\u1d62 $ 3)))\n         *          v'36 (Vint32 (x12&\u1d62Int.not ($ 1<<\u1d62((x >>\u1d62 $ 8)&\u1d62$ 7)))))\n         *       (val_inj (or (Vint32 t1) (Vint32 x11)))) *)\n\n       (update_nth_val (Z.to_nat (Int.unsigned x2)) v'62\n                (Vint32 (x4&\u1d62Int.not v'78))) )\n    (msgq:=DMutex (Vint32 (Int.or (x &\u1d62$ OS_MUTEX_KEEP_UPPER_8)\n                                  ((x2<<\u1d62$ 3)+\u1d62x5)))\n                  ( nth_val' (Z.to_nat (Int.unsigned ((x2<<\u1d62$ 3)+\u1d62x5)))\n                             (update_nth_val (Z.to_nat (Int.unsigned (x>>\u1d62$ 8)))\n                                             (update_nth_val (Z.to_nat\n                                                                (Int.unsigned (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8))) v'30\n                                                             (Vptr (v'52, Int.zero))) \n                                             (Vptr v'41))) );\n    auto.\n  go.\n\n  unfold AEventNode.\n  unfold AEventData.\n\n  unfold_msg.\n  sep pauto.\n\n  sep cancel 2%nat 1%nat.\n  sep cancel 2%nat 1%nat.\n  rewrite <- H106.\n  (* instantiate (x7 := v'33).\n   * instantiate (x9 := v'35).\n   * instantiate (x8 := (x7\n   *                 :: v'24\n   *                    :: x15\n   *                       :: m\n   *                          :: Vint32 i6\n   *                             :: Vint32 x14\n   *                                :: Vint32 (x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)\n   *                                   :: Vint32\n   *                                        ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8)&\u1d62$ 7)\n   *                                      :: Vint32\n   *                                           ((x&\u1d62$ OS_MUTEX_KEEP_LOWER_8) >>\u1d62\n   *                                            $ 3)\n   *                                         :: Vint32 x11 :: Vint32 x8 :: nil)).\n   * sep lift 3%nat. *)\n  eapply tcbdllflag_hold.\n\n  2: sep cancel tcbdllflag.\n  Lemma set_node_eq_dllflag :\n    forall tcbl ptr  v'82 v'83 v'84 v'85 v'86 v'87 v'88 v'89 v'90 v'91 v'92 v'83' v'84' v'85' v'86' v'87' v'88' v'89' v'90' v'91' head,\n           tcblist_get ptr head tcbl = \n           Some\n             (v'82 :: v'83 :: v'84 :: v'85 :: v'86 :: v'87 :: v'88\n                   :: v'89 :: v'90 :: v'91 :: v'92 :: nil) ->\n           eq_dllflag tcbl (set_node ptr (v'82 :: v'83' :: v'84' :: v'85' :: v'86' :: v'87' :: v'88'\n                                           :: v'89' :: v'90' :: v'91' :: v'92 :: nil) head tcbl).\n  Proof.\n    induction tcbl.\n    intros.\n    simpl.\n    auto.\n    intros.\n    simpl.\n    remember (beq_val ptr head).\n    destruct b.\n    unfold tcblist_get in H.\n    rewrite <- Heqb in H.\n    simpl in H.\n    inverts H.\n    splits; auto.\n    Focus 2.\n    splits; auto.\n    eapply IHtcbl.\n    unfolds in H.\n    rewrite <- Heqb in H.\n    destruct a.\n    simpl in H.\n    inversion H.\n    simpl in H.\n    fold tcblist_get in H.\n    exact H.\n\n    apply eq_dllflag_refl.\n  Qed.\n\n\n  Lemma eq_dllflag_trans :\n    forall l1 l2 l3,\n      eq_dllflag l1 l2 ->\n      eq_dllflag l2 l3 ->\n      eq_dllflag l1 l3.\n  Proof.\n    induction l1.\n    intros.\n    simpl in H.\n    destruct l2; tryfalse.\n\n    simpl in H0.\n    destruct l3; tryfalse.\n    auto.\n    intros.\n    simpl in H.\n    destruct l2; tryfalse.\n    simpl in H0.\n    destruct l3; tryfalse.\n    simpl.\n    simpljoin.\n    splits.\n    rewrite H.\n    auto.\n    rewrite H3.\n    auto.\n    eapply IHl1.\n    eauto.\n    eauto.\n  Qed.\n\n  eapply eq_dllflag_trans.\n  2: eapply  set_node_eq_dllflag .\n  eapply tcbdllflag_hold_middle.\n  unfolds ; auto.\n  eauto.\n  eauto.\n\n  go.\n  go.\n  exact H138.\n  go.\n  \n  go.\n\n  clear -H142 H126.\n\n  unfolds in H142; unfold OS_EVENT in H142; simpl in H142; simpljoin.\n  math simpl in H0; clear -H0 H126; omega.\n\n  assert (Int.unsigned\n            (Int.or (x&\u1d62$ OS_MUTEX_KEEP_UPPER_8) ((x2<<\u1d62$ 3) +\u1d62  x5)) <= 65535).\n  apply acpt_intlemma6.\n\n  clear -fffbb ttfasd; mauto.\n\n  change Int16.max_unsigned with 65535 in H126.\n  clear -H126 H127; omega.\n\n  rewrite H107.\n  auto.\n\n  eapply r_priotbl_p_set_hold;eauto.\n\n{\nLemma rl_rtbl_priotbl_p_hold''\n     : forall (v'36 : vallist) (v'12 : int32) (v'13 : vallist)\n         (v'38 v'69 v'39 : int32) (v'58 : block) (v'40 v'41 v'57 : int32)\n         (v'37 : vallist) (vhold : block * int32) vvv,\n       (v'58, Int.zero) <> vhold ->\n       RL_RTbl_PrioTbl_P v'37 v'36 vhold ->\n       v'12 <> Int.zero ->\n       Int.unsigned v'12 <= 255 ->\n       array_type_vallist_match Int8u v'13 ->\n       length v'13 = \u2218 OS_EVENT_TBL_SIZE ->\n       array_type_vallist_match Int8u v'37 ->\n       length v'37 = \u2218 OS_EVENT_TBL_SIZE ->\n       nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n       Int.unsigned v'38 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n       Int.unsigned v'69 <= 255 ->\n       nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n       Int.unsigned v'39 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned ((v'38<<\u1d62$ 3) +\u1d62  v'39))) v'36 =\n       Vptr (v'58, Int.zero) ->\n       nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n       Int.unsigned v'40 <= 128 ->\n       nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n       Int.unsigned v'41 <= 128 ->\n       RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n       RL_Tbl_Grp_P v'37 (Vint32 v'57) ->\n       Int.unsigned v'57 <= 255 ->\n       array_type_vallist_match Int8u v'37 ->\n       length v'37 = \u2218 OS_RDY_TBL_SIZE ->\n       (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) = Vint32 vvv ->\n       RL_RTbl_PrioTbl_P\n         (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n            (val_inj\n               (or (Vint32 vvv)\n                   (Vint32 v'40)))) v'36 vhold.\nProof.\n  intros.\n  \n  rewrite <- H23.\n  eapply rl_rtbl_priotbl_p_hold; try assumption.\n  12: eauto.\n  12: eauto.\n  11: eauto.\n  9: eauto.\n  6: eauto.\n  6: eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\n  eauto.\nQed.\neapply rl_rtbl_priotbl_p_hold''; try assumption.\n6: eauto 1.\n7: eauto 1.\n8: eauto 1.\n9: eauto 1.\n9: eauto 1.\n10: eauto 1.\nassumption.\nclear -H99.\nintro; subst v'60; change (Int.eq  (Int.zero)  ($ 0)) with true in H99; apply H99; auto.\nassumption.\nassumption.\nassumption.\nclear -fffbb ; mauto.\nassumption.\nclear -ttfasd; mauto.\n3: assumption.\nidtac.\n3: exact H121.\n3: assumption.\nLemma osmapvalle128:\n  forall x y,\n    nth_val' (Z.to_nat (Int.unsigned x)) OSMapVallist = Vint32 y ->\n    Int.unsigned y <= 128.\nProof.\n  intros.\n  unfold OSMapVallist in H.\n  assert (Int.unsigned x<8 \\/ Int.unsigned x > 7).\n  omega.\n  elim H0; intros.\n  mauto_dbg.\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  destruct H1; [rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega| ..].\n  rewrite H1 in *; simpl in H; inverts H; ur_rewriter; omega.\n  remember (Int.unsigned x).\n  assert ( 7 < z) by omega.\n  apply Z2Nat.inj_lt in H2.\n  remember (Z.to_nat z).\n  change (Z.to_nat 7) with 7%nat in H2.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  destruct n; try omega.\n  induction n.\n  simpl in H.\n  inverts H.\n  simpl in H.\n  inverts H.\n  omega.\n  rewrite Heqz.\n  int auto.\nQed.\n\neapply osmapvalle128; eauto.\neapply osmapvalle128; eauto.\n                                                               \n}\n\n\nrewrite H107.\n  (* H146 : struct_type_vallist_match OS_TCB_flag\n   *          (v'82\n   *           :: v'83\n   *              :: v'84\n   *                 :: v'85\n   *                    :: v'86\n   *                       :: Vint32 v'87\n   *                          :: v'88 :: v'89 :: v'90 :: v'91 :: v'92 :: nil) *)\n{\n\n  assert (v'60 <> $ 0).\n{\n  clear -H99.\n  intro; subst v'60; change (Int.eq  (Int.zero)  ($ 0)) with true in H99; apply H99; auto.\n}\n\n{\n\nlets wzsrlgl: H61.\napply get_join in wzsrlgl.\ndestruct wzsrlgl as (wzs & rlgl).\n \neapply ecblist_p_post_exwt_hold_mutex_new; eauto.\nelim H68; intros; try solve [ clear -H127 H126; subst; tryfalse].\nclear -H127; simpljoin.\napply int_ltu_prop; auto.\n\nclear -fffbb; mauto.\nclear -ttfasd; mauto.\neapply osmapvalle128; eauto.\n\n\n unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in H136.\n  destruct x19; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H148 H73 ll lll).\n  subst t.\n\n  eapply return_ecbl_p; eauto.\n\n unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in H136.\n  destruct x19; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H148 H73 ll lll).\n  subst t.\n\n  eapply return_ecbl_p; eauto.\n\n  }\n\n\n\n\n }\nexact H119.\nexact H118.\nexact H111.\napply rh_curtcb_set_nct;auto.\nunfolds.\ndo 3 eexists.\nunfold get; simpl.\napply TcbMod.set_a_get_a.\ngo.\nintro HHH; inverts HHH.\n\n unfold1 TCBList_P in backup2.\n  simpljoin.\n  idtac.\n  idtac.\n  unfolds in H148.\n  destruct x19; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H151 H73 ll lll).\n  subst t.\n\n  rewrite TcbMod.set_a_get_a in H110; [inverts H110| go].\n\n\n  eapply rh_tcblist_ecblist_p_post_exwt_mutex ; eauto.\n  \n  unfold1 TCBList_P in backup2.\n  simpljoin.\n  unfolds in H148.\n  destruct x19; destruct p; simpljoin.\n  unprotect last_condition; destruct last_condition as (ll & lll); apply eq2inteq in ll; apply eq2inteq in lll.\n  assert (t=rdy).\n  apply (low_stat_rdy_imp_high _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H54 H58 H151 H73 ll lll).\n  subst t.\n\n  eapply return_rh_tcbl_ecbl_p; eauto.\n  unfolds in H109.\n  destruct H109; exact H109.\n\n  unfold AEventData; go.\n  hoare forward.\n  sep cancel p_local.\n  sep cancel 1%nat 5%nat.\n  sep cancel Aie.\n  sep cancel Ais.\n  sep cancel Acs.\n  sep cancel Aisr.\n  eauto.\n\n  unfolds; auto.\n  go.\n  unfold AEventData.\n  go.\n\n\n  intro; intros.\n  sep normal in H63.\n  sep destruct H63.\n  sep eexists.\n  sep cancel p_local.\n  simpl; auto.\n\n  intro; intros.\n  sep normal in H63.\n  sep destruct H63.\n  sep eexists.\n  sep cancel p_local.\n  simpl; auto.\n\n  \n  unfold AEventData.\n  hoare unfold.\n  hoare forward.\n  inverts H63; reflexivity.\nQed.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/proofs/mutex/OSMutexPostPart30.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.297469948832931, "lm_q1q2_score": 0.1740500147071631}}
{"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 SimPromises.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nLemma read_read_tview\n      loc1 ts1 released1 ord1\n      loc2 ts2 released2 ord2\n      tview0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.read_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.read_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\nQed.\n\nLemma read_write_tview\n      loc1 ts1 released1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.write_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  repeat condtac; aggrtac; try apply WF0.\nQed.\n\nLemma read_read_fence_tview\n      loc1 ts1 released1 ord1\n      ord2\n      tview0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.read_fence_tview tview0 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.read_fence_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  - repeat condtac; aggrtac; try apply WF0.\n  - repeat condtac; aggrtac; try apply WF0.\n  - repeat condtac; aggrtac; try apply WF0.\n    destruct ord1; inv COND; inv COND1.\nQed.\n\nLemma read_write_fence_tview\n      loc1 ts1 released1 ord1\n      ord2\n      tview0 sc0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.write_fence_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_read_tview\n      loc1 ts1 ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.write_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.read_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  condtac; aggrtac. condtac.\n  - destruct ord1; inv ORD1; inv COND0.\n  - aggrtac; try apply WF0.\nQed.\n\nLemma write_write_tview\n      loc1 ts1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.write_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac).\n  all: try by apply WF0.\nQed.\n\nLemma write_read_fence_tview\n      loc1 ts1 ord1\n      ord2\n      tview0 sc0\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.read_fence_tview tview0 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.read_fence_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_write_fence_tview\n      loc1 ts1 ord1\n      ord2\n      tview0 sc0\n      (ORD2: Ordering.le ord2 Ordering.acqrel)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       (TView.write_fence_sc tview0 sc0 ord2)\n       loc1 ts1 ord1)\n    (TView.write_fence_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma read_fence_read_tview\n      ord1\n      loc2 ts2 released2 ord2\n      tview0\n      (ORD2: Ordering.le ord2 Ordering.plain \\/ Ordering.le Ordering.acqrel ord2)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       ord1)\n    (TView.read_tview\n       (TView.read_fence_tview tview0 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\n  des; [|congr]. destruct ord2; inv ORD2; inv COND0.\nQed.\n\nLemma read_fence_write_tview\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       ord1)\n    (TView.write_tview\n       (TView.read_fence_tview tview0 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_fence_read_tview\n      ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.write_fence_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2) sc0 ord1)\n    (TView.read_tview\n       (TView.write_fence_tview tview0 sc0 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (repeat (condtac; aggrtac; try apply WF0)).\nQed.\n\nLemma write_fence_read_sc\n      ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TimeMap.le\n    (TView.write_fence_sc\n       (TView.read_tview tview0 loc2 ts2 released2 ord2) sc0 ord1)\n    (TView.write_fence_sc tview0 sc0 ord1).\nProof.\n  ii. unfold TView.write_fence_sc.\n  repeat condtac; aggrtac.\nQed.\n\nLemma write_fence_write_tview\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_fence_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 ord1)\n    (TView.write_tview\n       (TView.write_fence_tview tview0 sc0 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (repeat (condtac; aggrtac; try apply WF0)).\nQed.\n\nLemma write_fence_write_sc\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TimeMap.le\n    (TView.write_fence_sc\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 ord1)\n    (TView.write_fence_sc tview0 sc0 ord1).\nProof.\n  ii. unfold TView.write_fence_sc.\n  repeat condtac; aggrtac.\nQed.\n\nLemma read_fence_write_fence_tview\n      ord1\n      ord2\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       ord1)\n    (TView.write_fence_tview\n       (TView.read_fence_tview tview0 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- View.join_r. viewtac.\n    rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- View.join_r. viewtac.\n    rewrite <- TimeMap.join_r. apply WF0.\nQed.\n\nLemma read_write_tview_eq\n      loc1 ts1 released1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord2 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  (TView.read_tview\n     (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n     loc1 ts1 released1 ord1) =\n  (TView.write_tview\n     (TView.read_tview tview0 loc1 ts1 released1 ord1)\n     sc0 loc2 ts2 ord2).\nProof.\n  apply TView.antisym.\n  - apply read_write_tview; auto.\n  - apply write_read_tview; 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/opt/ReorderTView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.17397032998671053}}
{"text": "From iris.algebra Require Import auth list agree frac.\nFrom iris.program_logic Require Import adequacy ectxi_language.\nFrom iris_examples.logrel.F_mu_ref_conc Require Import soundness_binary.\nFrom iris_examples.logrel.F_mu_ref_conc.examples Require Import lock.\nFrom iris_examples.logrel.F_mu_ref_conc.examples.stack Require Import\n  CGF_stack CGL_stack stack_rules.\nFrom iris.proofmode Require Import tactics.\n\nDefinition stackN : namespace := nroot .@ \"stack\".\n\n\nSection Stack_refinement.\n  Context `{heapIG \u03a3, cfgSG \u03a3, inG \u03a3 (authR stackUR), inG \u03a3 stateUR}.\n  Notation D := (prodO valO valO -n> iPropO \u03a3).\n  Implicit Types \u0394 : listO D.\n\n\n\n  Lemma CGL_CGF_counter_refinement :\n    [] \u22a8 CGL_stack \u2264log\u2264 CGF_stack : TForall (TProd\n           (TArrow (TVar 0) TUnit)\n           (TArrow TUnit (TSum TUnit (TVar 0)))).\n  Proof.\n    iIntros (\u0394 [|] ?) \"#[Hspec H\u0393]\"; iIntros (j K) \"Hj\"; last first.\n    { iDestruct (interp_env_length with \"H\u0393\") as %[=]. }\n    iClear \"H\u0393\".\n    iAsimpl.\n    iApply wp_value.\n    iExists (TLamV _); iFrame \"Hj\".\n    clear j K. iAlways. iIntros (\u03c4i) \"%\". iIntros (j K) \"Hj /=\".\n    (** evaluate newlock and create stack *)\n    (* L *)\n    iApply wp_pure_step_later; auto;iNext;iAsimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_newlock;first done;iNext;iIntros (lL) \"HlL\";iAsimpl.\n    iApply wp_pure_step_later; first done; iNext;iAsimpl.\n    iApply (wp_bind (fill [AllocCtx; LetInCtx _])).\n    iApply wp_alloc;first done;iNext;iIntros (istkL) \"HistkL\";iAsimpl.\n    iApply (wp_bind (fill [LetInCtx _])).\n    iApply wp_alloc;first done;iNext;iIntros (stkL) \"HstkL\";iAsimpl.\n    iApply wp_pure_step_later; auto; iNext; iAsimpl.\n    (* F *)\n    iMod (do_step_pure _ j K with \"[$Hj]\") as \"Hj\"; eauto.\n    iMod (steps_newlock _ j (LetInCtx _ :: K)  with \"[$Hj]\") as (lF) \"[Hj HlF]\"; eauto;simpl.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto;iAsimpl.\n    iMod (step_alloc  _ j (LetInCtx _ :: K) with \"[$Hj]\") as (stkF) \"[Hj HstkF]\"; eauto;simpl.\n    iMod (do_step_pure with \"[$Hj]\") as \"Hj\"; eauto;iAsimpl.\n    (** alloc invariant*)\n    iMod (own_alloc (\u25cf (\u2205 : stackUR))) as (\u03b3) \"Hemp\"; first by apply auth_auth_valid.\n    set (istkG := StackG _ _ \u03b3).\n    change \u03b3 with (@stack_name _ istkG).\n    change H1 with (@stack_inG _ istkG).\n    clearbody istkG. clear \u03b3 H1.\n    (*?*)\n    iAssert (@stack_owns _ istkG _ \u2205) with \"[Hemp]\" as \"Hoe\".\n    { rewrite /stack_owns big_sepM_empty fmap_empty. iFrame \"Hemp\"; trivial. }\n    (*?*)\n    iMod (stack_owns_alloc with \"[$Hoe $HistkL]\") as \"[Hoe Hls]\".\n    iAssert (StackLink \u03c4i (LocV istkL, FoldV (InjLV UnitV))) with \"[Hls]\" as \"HLKL\".\n    { rewrite StackLink_unfold.\n      iExists _, _. iSplitR; simpl; trivial.\n      iFrame \"Hls\". iLeft. iSplit; trivial. }\n    iMod (own_alloc (newstate 1 istkL)) as (\u03b3) \"[H\u03b31 H\u03b32]\";first done.\n    iAssert ((\u2203 istkL v h b, (stack_owns h)\n                         \u2217 stkF \u21a6\u209b v\n                         \u2217 stkL \u21a6\u1d62 (LocV istkL) \u2217 \u03b3 \u2907[1/2] istkL\n                         \u2217 StackLink \u03c4i (LocV istkL, v)\n                         \u2217 lF \u21a6\u209b (#\u266dv false)\n                         \u2217 lL \u21a6\u1d62 (#\u266dv b) \u2217 ( \u231cb = true \u231d \u2228 \u231cb = false \u231d \u2217 \u03b3 \u2907[1/2] istkL)\n             )%I) with \"[Hoe HstkL HstkF HLKL HlF HlL H\u03b31 H\u03b32]\" as \"Hinv\".\n    { iExists istkL, _, _, false. iFrame \"Hoe HstkL HstkF HLKL HlF HlL\".  iFrame. iRight. iFrame. done. }\n    iMod (inv_alloc stackN with \"[Hinv]\") as \"#Hinv\"; [iNext; iExact \"Hinv\"|].\n    Opaque stack_owns.\n    (** split into push and pop*)\n    iApply wp_value.\n    iExists (PairV (CGF_locked_pushV _ _)\n                (CGF_locked_popV _ _)).\n    simpl.\n    rewrite CGF_locked_push_of_val CGF_locked_pop_of_val.\n    iFrame \"Hj\".\n    iExists (_, _), (_, _); iSplit; eauto.\n    iSplit; iAlways; clear j K.\n    - (* push *)\n      iIntros ( [v1 v2] ) \"#Hrel\". iIntros (j K) \"Hj /=\".\n      (* L *)\n      iApply wp_pure_step_later; auto;iNext;iAsimpl.\n      iApply (wp_bind (fill [SeqCtx _])).\n      (* acquire*)\n      Transparent acquire.\n      rewrite /acquire.\n      iL\u00f6b as \"Hlob\".\n      iApply wp_pure_step_later; auto;iNext;iAsimpl.\n      iApply (wp_bind (fill [IfCtx _ _])).\n      (* open invariant *)\n      iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  HstkL & H\u03b3 & HLKL & HlF & >HlL & [> ->|[> -> H\u03b32]])\" \"Hclose\".\n      + iApply (wp_cas_fail with \"HlL\"); auto; iNext; iIntros \"HlL\";iAsimpl.\n        iMod (\"Hclose\" with \"[-Hj]\") as \"_\".\n        { iNext. iExists istk2, _, _,true. iFrame. iLeft; done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply \"Hlob\".\n        iFrame.\n      + iApply (wp_cas_suc with \"HlL\"); auto; iNext; iIntros \"HlL\";iAsimpl.\n        iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n        { iNext. iExists istk2, _, _,true. iFrame. iLeft;done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply wp_value;iAsimpl.\n        iClear \"Hlob\".\n        clear v h.\n        (* acquire succ! *)\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [LetInCtx _])).\n        rewrite CGL_push_folding;iAsimpl.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [LetInCtx _])).\n        (* open invariant *)\n        iInv stackN as (istk2' v h b) \"(Hoe & HstkF &  HstkL & H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n        iApply (wp_load with \"HstkL\"); iNext; iIntros \"HstkL\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n        { iNext. iExists _, _, _,_. iFrame. }\n        iModIntro;iAsimpl.\n        clear  h b.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [StoreRCtx  (LocV _)])).\n        iApply wp_alloc;first done;iNext;iIntros (tmp) \"HtmpL\";iAsimpl.\n        iInv stackN as (istk2'' v' h b) \"(Hoe & HstkF &  HstkL & H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n        iApply (wp_store with \"HstkL\"); iNext; iIntros \"HstkL\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        iMod (makeElem_update _ _ _ tmp with \"H\u03b3 H\u03b31\") as \"[H\u03b3 H\u03b31]\".\n        (* F *)\n        iMod (steps_CGF_locked_push _ j K with \"[Hj HlF HstkF]\")\n            as \"[Hj [HstkF HlF]]\"; first solve_ndisj.\n        { rewrite CGF_locked_push_of_val. by iFrame \"Hspec HstkF Hj\". }\n        iMod (stack_owns_alloc with \"[$Hoe $HtmpL]\") as \"[Hoe HtmpL]\".\n        iDestruct \"Hbool\" as \"[-> |[-> H\u03b32]]\".\n        * (*b=true, release succ*)\n          iMod (\"Hclose\" with \"[-Hj  H\u03b3]\") as \"_\".\n        { iNext. iExists tmp,(FoldV (InjRV (PairV v2 v'))) , _,_. iFrame. iSplitL. do 2 rewrite StackLink_unfold. rewrite -StackLink_unfold. iExists tmp, _.  iFrame \"HtmpL\". simpl.  iSplitR. done. iRight. iExists v1,(LocV istk2),v2, v', istk2. iFrame \"#\". eauto. iLeft. done. }\n        clear v v' h istk2.\n        iApply (wp_bind (fill [LetInCtx _])).\n        iModIntro.\n        iApply wp_value;iAsimpl.\n        iApply wp_pure_step_later; auto; simpl; iNext;iAsimpl.\n        iApply (wp_bind (fill [SeqCtx _])).\n        (** release *)\n        Transparent release.\n        rewrite /release.\n        iApply wp_pure_step_later; auto; simpl; iNext.\n        iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  HstkL & >H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        iApply (wp_store with \"HlL\");iNext;iIntros \"HlL\".\n        iMod (\"Hclose\" with \"[-Hj]\") as \"_\".\n        { iNext. iExists _, _, _,_. iFrame. iRight. iFrame. done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; simpl; iNext.\n        iApply wp_value. iExists UnitV. iFrame. done.\n        * (*b=false, FALSE*)\n          iDestruct (makeElem_eq with \"H\u03b3 H\u03b32\") as %<-.\n          iDestruct (makeElem_entail with \"H\u03b31 H\u03b32\") as \"H\u03b3\u03b3\".\n          iDestruct (makeElem_entail with \"H\u03b3\u03b3 H\u03b3\") as \"H\u03b3\".\n          rewrite dummy.\n          iDestruct (invalid with \"H\u03b3\") as %[].\n    - (* pop *)\n      iIntros ( ? [-> ->] ); simpl. iIntros (j K) \"Hj /=\".\n      (* L *)\n      iApply wp_pure_step_later; auto;iNext;iAsimpl.\n      iApply (wp_bind (fill [SeqCtx _])).\n      (* acquire*)\n      iL\u00f6b as \"Hlob\".\n      iApply wp_pure_step_later; auto;iNext;iAsimpl.\n      iApply (wp_bind (fill [IfCtx _ _])).\n      iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  HstkL & H\u03b3 & HLKL & HlF & >HlL & [> ->|[> -> H\u03b32]])\" \"Hclose\".\n      + iApply (wp_cas_fail with \"HlL\"); auto; iNext; iIntros \"HlL\";iAsimpl.\n        iMod (\"Hclose\" with \"[-Hj]\") as \"_\".\n        { iNext. iExists istk2, _, _,true. iFrame. iLeft; done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply \"Hlob\".\n        iFrame.\n      + iApply (wp_cas_suc with \"HlL\"); auto; iNext; iIntros \"HlL\";iAsimpl.\n        iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n        { iNext. iExists istk2, _, _,true. iFrame. iLeft;done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply wp_value;iAsimpl.\n        iClear \"Hlob\".\n        clear v h.\n        (* acquire succ! *)\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [LetInCtx _])).\n        rewrite CGL_pop_folding;iAsimpl.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [LetInCtx _])).\n        iInv stackN as (istk2' v h b) \"(Hoe & HstkF &  HstkL & H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n        iApply (wp_load with \"HstkL\"); iNext; iIntros \"HstkL\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n        { iNext. iExists _, _, _,_. iFrame. }\n        iModIntro;iAsimpl.\n        clear  h b v.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [CaseCtx _ _])).\n        iInv stackN as (istk2' v h b) \"(Hoe & HstkF &  HstkL & >H\u03b31 & #HLKLinv & HlF & >HlL & Hbool)\" \"Hclose\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        rewrite StackLink_unfold.\n        iPoseProof \"HLKLinv\" as (istk2' tmp) \"[>%  [>HistkL [>[% %]|H2]]]\"; simplify_eq /=;\n        iClear \"HLKLinv\".\n        * (* stack is empty *)\n        iDestruct (stack_owns_later_open_close with \"Hoe HistkL\") as \"[>HistkL' Hoe]\".\n        iApply (wp_load with \"HistkL'\"); iNext; iIntros \"HistkL'\";iAsimpl.\n        (* F *)\n        rewrite CGF_locked_pop_of_val.\n        iMod (steps_CGF_locked_pop_fail with \"[$Hspec $HstkF $HlF $Hj]\")\n             as \"[Hj [HstkF HlF]]\"; first solve_ndisj.\n        (* L *)\n        iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n        { iNext. iExists _, _, _,_.  iFrame. iSplitL. by iApply (\"Hoe\" with \"HistkL'\").  rewrite StackLink_unfold.  iExists istk2',_. eauto. }\n        iModIntro;iAsimpl.\n        clear  h b.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply wp_value;iAsimpl.\n        iApply wp_pure_step_later; auto; iNext; iAsimpl.\n        iApply (wp_bind (fill [SeqCtx _])).\n        (* release *)\n        iApply wp_pure_step_later; auto; simpl; iNext.\n        iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  HstkL & >H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n        iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n        iApply (wp_store with \"HlL\");iNext;iIntros \"HlL\".\n        iMod (\"Hclose\" with \"[-Hj]\") as \"_\".\n        { iNext. iExists _, _, _,_. iFrame. iRight. iFrame. done. }\n        iModIntro.\n        iApply wp_pure_step_later; auto; simpl; iNext.\n        iApply wp_value. iExists (InjLV UnitV). iFrame. iLeft. iExists (UnitV, UnitV).  eauto 10.\n        * (* stack is not empty *)\n          iDestruct (stack_owns_later_open_close with \"Hoe HistkL\") as \"[>HistkL' Hoe]\".\n          iApply (wp_load with \"HistkL'\"); iNext; iIntros \"HistkL'\";iAsimpl.\n          iDestruct \"H2\" as (v1 stkL' v2 stkF' stkL'v) \"(% & % & % & ? & HLKL')\".\n          simplify_eq /=.\n          iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n          { iNext. iExists _, _, _,_. iFrame. iSplitL. iApply (\"Hoe\" with \"HistkL'\"). do 2 rewrite StackLink_unfold. rewrite -StackLink_unfold. iExists istk2', (InjRV (PairV v1 (FoldV (LocV stkL'v)))). iFrame \"#\".  iSplitR. eauto.  iRight. iExists v1, (LocV stkL'v), v2, stkF', stkL'v. simpl. iFrame\"#\". done. }\n          clear h b.\n          iModIntro.\n          iApply wp_pure_step_later; auto; simpl; iNext.\n          iApply (wp_bind (fill [UnfoldCtx; StoreRCtx (LocV stkL); SeqCtx _])).\n          iApply wp_pure_step_later; auto; simpl; iNext.\n          iApply wp_value;iAsimpl.\n          iApply (wp_bind (fill [StoreRCtx (LocV stkL); SeqCtx _])).\n          iApply wp_pure_step_later; auto; simpl; iNext.\n          iApply wp_value;iAsimpl.\n          iApply (wp_bind (fill [SeqCtx _])).\n          iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  >HstkL & >H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n          iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %->.\n          iApply (wp_store with \"HstkL\");iNext;iIntros \"HstkL\".\n          do 2 rewrite StackLink_unfold. rewrite -StackLink_unfold.\n          iPoseProof \"HLKL\" as (istk2' tmp) \"[Heq [HistkL' [[% %]|H2]]]\".\n          -- (* empty *)simpl. iDestruct \"Heq\" as %[=].\n             rewrite -H6.\n             iDestruct (stack_mapstos_agree with \"[HistkL HistkL']\") as %?;\n                                                                          first (iSplit; [iExact \"HistkL\"| iExact \"HistkL'\"]).\n             rewrite H1 in H5.\n             discriminate.\n          -- simpl. iDestruct \"Heq\" as %[=].\n             rewrite -H4.\n             iDestruct (stack_mapstos_agree with \"[HistkL HistkL']\") as %?;\n                                                                          first (iSplit; [iExact \"HistkL\"| iExact \"HistkL'\"]).\n\n             simplify_eq /=.\n             iClear \"HLKL'\".\n             iDestruct \"H2\" as (v1' stkL'' v2' stkF'' stkL''v) \"(% & % & % & #Hrel & HLKL')\".\n             simplify_eq /=.\n             (* F *)\n             rewrite CGF_locked_pop_of_val.\n             iMod (steps_CGF_locked_pop_suc _ j K with \"[$Hspec $HstkF $HlF $Hj]\") as \"[Hj [HstkF HlF]]\"; first solve_ndisj.\n\n             iMod (makeElem_update _ _ _ stkL''v with \"H\u03b3 H\u03b31\") as \"[H\u03b3 H\u03b31]\".\n             iDestruct \"Hbool\" as \"[-> |[-> H\u03b32]]\".\n             ++ (*b=true, release succ*)\n               iMod (\"Hclose\" with \"[-Hj H\u03b3]\") as \"_\".\n               {iNext. iExists stkL''v, stkF'', h, true.  iFrame . iLeft. done. }\n               clear h.\n               iModIntro.\n               iApply wp_pure_step_later; auto; simpl; iNext.\n               iApply (wp_bind (fill [InjRCtx ])).\n               iApply wp_pure_step_later; auto; simpl; iNext.\n               iApply wp_value;iAsimpl.\n               iApply wp_value;iAsimpl.\n               iApply wp_pure_step_later; auto; simpl; iNext.\n               iApply (wp_bind (fill [SeqCtx _ ])).\n               (* release *)\n               iApply wp_pure_step_later; auto; simpl; iNext.\n               iInv stackN as (istk2 v h b) \"(Hoe & HstkF &  HstkL & >H\u03b31 & HLKL & HlF & >HlL & Hbool)\" \"Hclose\".\n               iDestruct (makeElem_eq with \"H\u03b3 H\u03b31\") as %<-.\n               iApply (wp_store with \"HlL\");iNext;iIntros \"HlL\".\n               iMod (\"Hclose\" with \"[-Hj]\") as \"_\".\n               { iNext. iExists _, _, _,_. iFrame. iRight. iFrame. done. }\n               iModIntro.\n               iApply wp_pure_step_later; auto; simpl; iNext.\n               iApply wp_value. iExists (InjRV v2'). iFrame. iRight. iExists (v1', v2').  eauto 10.\n             ++ (*b=false, FALSE*)\n               iDestruct (makeElem_eq with \"H\u03b3 H\u03b32\") as %<-.\n               iDestruct (makeElem_entail with \"H\u03b31 H\u03b32\") as \"H\u03b3\u03b3\".\n               iDestruct (makeElem_entail with \"H\u03b3\u03b3 H\u03b3\") as \"H\u03b3\".\n               rewrite dummy.\n               iDestruct (invalid with \"H\u03b3\") as %[].\nQed.\n", "meta": {"author": "lzy0505", "repo": "iris_case_studies", "sha": "34e0e3cb9d33aad97cb021d5855c235fce7c90c8", "save_path": "github-repos/coq/lzy0505-iris_case_studies", "path": "github-repos/coq/lzy0505-iris_case_studies/iris_case_studies-34e0e3cb9d33aad97cb021d5855c235fce7c90c8/stack_refinement/CG_refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.1739006687296098}}
{"text": "Require Import Coq.Logic.Classical_Prop.\n\nRequire Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.Formalism.\nRequire Import SpecCert.Interval.\nRequire Import SpecCert.Memory.\nRequire Import SpecCert.Smm.Delta.Invariant.\nRequire Import SpecCert.Smm.Delta.Preserve.Architecture.\nRequire Import SpecCert.Smm.Software.\nRequire Import SpecCert.x86.\n\nLemma read_strat_uc\n      (r:  R)\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : partial_preserve (Read r pa v)\n                     (fun a => resolve_cache_strategy (proc a) pa = Uncachable)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hres Hpre Hpost.\n  unfold x86_postcondition, read_post in Hpost.\n  rewrite Hres in Hpost.\n  unfold read_uncachable_post in Hpost.\n  rewrite Hpost.\n  exact Hinv.\nQed.\n\nLemma read_strat_sh\n      (r:  R)\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : partial_preserve (Read r pa v)\n                     (fun a => resolve_cache_strategy (proc a) pa = SmrrHit)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hres Hpre Hpost.\n  unfold x86_postcondition, read_post in Hpost.\n  rewrite Hres in Hpost.\n  unfold read_smrrhit_post in Hpost.\n  rewrite Hpost.\n  exact Hinv.\nQed.\n\nLemma read_strat_smrr_wb\n      (r:  R)\n      (pa: PhysicalAddress)\n      (v:  Value)\n    : partial_preserve (Read r pa v)\n                       (fun a => is_inside_smrr (proc a) pa\n                                 /\\ smm_strategy (smrr (proc a)) = WriteBack)\n                       inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv [Hsmrr Hsmm] Hpre Hpost.\n  unfold x86_postcondition, read_post, resolve_cache_strategy in Hpost.\n  destruct is_inside_smrr_dec; [| intuition ].\n  destruct is_in_smm_dec.\n  + rewrite Hsmm in Hpost.\n    unfold read_writeback_post in Hpost.\n    destruct cache_hit_dec.\n    * rewrite Hpost.\n      exact Hinv.\n    * assert (is_inside_smram pa -> is_in_smm (proc a)).\n      intro H; exact i0.\n      apply (load_in_cache_from_memory_preserves_inv a a' pa Hinv H Hpost).\n  + unfold read_smrrhit_post in Hpost.\n    rewrite Hpost.\n    exact Hinv.\nQed.\n\nLemma read_strat_not_smrr\n      (r:  R)\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : partial_preserve (Read r pa v)\n                     (fun a => ~ is_inside_smrr (proc a) pa)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hnot_smrr Hpre Hpost.\n  unfold x86_postcondition, read_post in Hpost.\n  unfold resolve_cache_strategy in Hpost.\n  destruct is_inside_smrr_dec; [ intuition |].\n  case_eq (strategy (proc a)); intro Heqstrat; rewrite Heqstrat in Hpost.\n  + unfold read_uncachable_post in Hpost.\n    rewrite Hpost.\n    exact Hinv.\n  + unfold read_writeback_post in Hpost.\n    destruct cache_hit_dec.\n    * rewrite Hpost; exact Hinv.\n    * assert (is_inside_smram pa -> is_in_smm (proc a)).\n      intro H.\n      destruct Hinv as [Hsmramc [Hsmram [Hsmrr Hclean]]].\n      apply Hsmrr in H.\n      intuition.\n      apply (load_in_cache_from_memory_preserves_inv a a' pa Hinv H Hpost).\n  + unfold read_smrrhit_post in Hpost.\n    rewrite Hpost.\n    exact Hinv.\nQed.\n\nLemma read_inv\n      (r:  R)\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : preserve (Read r pa v) inv.\nProof.\n  unfold preserve.\n  intros a a' Hinv Hpre Hpost.\n  case_eq (resolve_cache_strategy (proc a) pa); intro Heqstrat.\n  + apply (read_strat_uc r pa v a a' Hinv Heqstrat Hpre Hpost).\n  + destruct (is_inside_smrr_dec (proc a) pa).\n    * unfold resolve_cache_strategy in Heqstrat.\n      destruct is_inside_smrr_dec; [| intuition ].\n      destruct is_in_smm_dec; [| discriminate ].\n      assert (is_inside_smrr (proc a) pa /\\ smm_strategy (smrr (proc a)) = WriteBack); [\n          split; trivial\n         |].\n      apply (read_strat_smrr_wb r pa v a a' Hinv H Hpre Hpost).\n    * apply (read_strat_not_smrr r pa v a a' Hinv n Hpre Hpost).\n  + apply (read_strat_sh r pa v a a' Hinv Heqstrat Hpre Hpost).\nQed.", "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/Read.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.30074557267388247, "lm_q1q2_score": 0.17367916994551572}}
{"text": "From Coq Require Import String Arith ZArith.\n\nFrom Vyper Require Import Config Map.\nFrom Vyper.L10 Require Import Base.\nFrom Vyper.L50 Require Import Types AST Builtins Expr LocalVars DynError Stmt.\n\n\n\nFixpoint interpret_call {C: VyperConfig}\n                        (max_call_depth: nat)\n                        (max_loop_iterations: nat)\n                        (builtins: string -> option yul_builtin)\n                        (funs: string -> option fun_decl)\n                        (f: fun_decl)\n                        (world: world_state)\n                        (arg_values: list dynamic_value)\n{struct max_call_depth}\n: world_state * option (expr_result (list dynamic_value))\n:= let _ := string_map_impl in\n   match max_call_depth with\n   | O => (world, None)\n   | S new_max_call_depth =>\n        match bind_vars_to_values (fd_inputs f) arg_values Map.empty with\n        | inl err =>\n            (* since L10-L40 produce a slightly better error message than \"too few values\",\n               namely \"function called with too few arguments\", it's better to repeat it here.\n             *)\n            (world, Some (expr_error\n                            match err with\n                            | DE_TooFewValues => \"function called with too few arguments\"\n                            | DE_TooManyValues => \"function called with too many arguments\"\n                            | _ => string_of_dynamic_error err\n                            end))\n        | inr loc_with_args_only =>\n            match bind_vars_to_zeros (fd_outputs f) loc_with_args_only with\n            | inl err => (world, Some (expr_error (string_of_dynamic_error err)))\n            | inr loc =>\n                let '(world', loc', result) :=\n                        interpret_block max_loop_iterations builtins funs (Some f)\n                                        (interpret_call new_max_call_depth max_loop_iterations \n                                                        builtins funs)\n                                        world loc nop (fd_body f)\n                in (world', match result with\n                            | None => None\n                            | Some StmtSuccess =>\n                                match get_vars_by_typenames (fd_outputs f) loc' with\n                                | inl err => Some (expr_error (string_of_dynamic_error err))\n                                | inr outputs => Some (ExprSuccess outputs)\n                                end\n                            | Some (StmtAbort AbortBreak)\n                            | Some (StmtAbort AbortContinue) =>\n                                Some (expr_error (string_of_dynamic_error DE_BreakContinueDisallowed))\n                            | Some (StmtAbort a) => Some (ExprAbort a)\n                            | Some (StmtReturnFromFunction x) => Some (ExprSuccess x)\n                            end)\n            end\n        end\n   end.\n\nDefinition interpret {C: VyperConfig}\n                     (max_call_depth: nat)\n                     (max_loop_iterations: nat)\n                     (builtins: string -> option yul_builtin)\n                     (funs: string -> option fun_decl)\n                     (fun_name: string)\n                     (world: world_state)\n                     (args: list dynamic_value)\n: world_state * option (expr_result (list dynamic_value))\n:= match funs fun_name with\n   | Some f => interpret_call max_call_depth max_loop_iterations builtins funs f world args\n   | None => (world, Some (expr_error \"declaration not found\"))\n   end.", "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/Call.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.17354905336916696}}
{"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 Peano_dec.\nRequire Import EquivDec.\nRequire Import Decidable.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import cNNRC.\nRequire Import cNNRCShadow.\nRequire Import TcNNRC.\n  \nSection TcNNRCShadow.\n  Hint Constructors nnrc_core_type : qcert.\n\n  Context {m:basic_model}.\n\n  Lemma nnrc_core_type_remove_duplicate_env {\u03c4cenv} l v x l' x' l'' e \u03c4:\n    nnrc_core_type \u03c4cenv (l ++ (v,x)::l' ++ (v,x')::l'') e \u03c4 <->\n    nnrc_core_type \u03c4cenv (l ++ (v,x)::l' ++ l'') e \u03c4.\n  Proof.\n    apply nnrc_core_type_lookup_equiv_prop; trivial.\n    apply lookup_remove_duplicate.\n  Qed.\n\n  Lemma nnrc_core_type_remove_free_env {\u03c4cenv} l v x l' e \u03c4 :\n    ~ In v (nnrc_free_vars e) ->\n    (nnrc_core_type \u03c4cenv (l ++ (v,x)::l') e \u03c4 <-> nnrc_core_type \u03c4cenv (l ++ l') e \u03c4).\n  Proof.\n    split; revert l v x l' \u03c4 H;\n      induction e; simpl; inversion 2; subst; intuition; eauto 3 with qcert.\n    - constructor. erewrite <- lookup_remove_nin; eauto.\n    - apply nin_app_or in H. intuition. qeauto.\n    - apply nin_app_or in H. intuition.\n      econstructor; eauto.\n      destruct (equiv_dec v v0); unfold Equivalence.equiv in *; subst.\n      + apply (nnrc_core_type_remove_duplicate_env nil v0 \u03c4\u2081 l) in H7; eauto.\n      + eapply (IHe2 ((v, \u03c4\u2081) :: l)); eauto. \n        intro; elim H2; apply remove_in_neq; eauto.\n    - apply nin_app_or in H. intuition.\n      econstructor; eauto.\n      destruct (equiv_dec v v0); unfold Equivalence.equiv in *; subst.\n      + apply (nnrc_core_type_remove_duplicate_env nil v0 \u03c4\u2081 l) in H7; eauto.\n      + eapply (IHe2 ((v, \u03c4\u2081) :: l)); eauto. \n        intro; elim H2; apply remove_in_neq; eauto.\n    - apply nin_app_or in H; destruct H as [? HH]; apply nin_app_or in HH.\n      intuition. qeauto.\n    - apply nin_app_or in H. destruct H as [neq1 neq2].\n      apply nin_app_or in neq2. destruct neq2 as [neq2 neq3].\n      econstructor; eauto.\n      + destruct (equiv_dec v v1); unfold Equivalence.equiv in *; subst.\n        * apply (nnrc_core_type_remove_duplicate_env nil v1 \u03c4l l) in H9; eauto.\n        * eapply (IHe2 ((v, \u03c4l) :: l)); eauto.\n          rewrite <- remove_in_neq in neq2; intuition.\n      + destruct (equiv_dec v0 v1); unfold Equivalence.equiv in *; subst.\n        * apply (nnrc_core_type_remove_duplicate_env nil v1 \u03c4r l) in H10; eauto.\n        * eapply (IHe3 ((v0, \u03c4r) :: l)); eauto.\n          rewrite <- remove_in_neq in neq3; intuition.\n    - constructor. erewrite lookup_remove_nin; eauto.\n    - apply nin_app_or in H. intuition. qeauto.\n    - apply nin_app_or in H. intuition.\n      econstructor; eauto.\n      destruct (equiv_dec v v0); unfold Equivalence.equiv in *; subst.\n      + apply (nnrc_core_type_remove_duplicate_env nil v0 \u03c4\u2081 l); eauto.\n      + eapply (IHe2 ((v, \u03c4\u2081) :: l)); eauto.\n        intro; elim H2; apply remove_in_neq; eauto.\n    - apply nin_app_or in H. intuition.\n      econstructor; eauto.\n      destruct (equiv_dec v v0); unfold Equivalence.equiv in *; subst.\n      + apply (nnrc_core_type_remove_duplicate_env nil v0 \u03c4\u2081 l); eauto.\n      + eapply (IHe2 ((v, \u03c4\u2081) :: l)); eauto. \n        intro; elim H2; apply remove_in_neq; eauto.\n    - apply nin_app_or in H; destruct H as [? HH]; apply nin_app_or in HH.\n      intuition.\n    - apply nin_app_or in H. destruct H as [neq1 neq2].\n      apply nin_app_or in neq2; destruct neq2  as [neq2 neq3].\n      econstructor; eauto.\n      + destruct (equiv_dec v v1); unfold Equivalence.equiv in *; subst.\n        * apply (nnrc_core_type_remove_duplicate_env nil v1 \u03c4l l); simpl; trivial.\n        * eapply (IHe2 ((v, \u03c4l) :: l)); eauto.\n          rewrite <- remove_in_neq in neq2; intuition.\n      + destruct (equiv_dec v0 v1); unfold Equivalence.equiv in *; subst.\n        * apply (nnrc_core_type_remove_duplicate_env nil v1 \u03c4r l); simpl; trivial.\n        * eapply (IHe3 ((v0, \u03c4r) :: l)); eauto.\n          rewrite <- remove_in_neq in neq3; intuition.\n  Qed.\n\n  Lemma nnrc_core_type_remove_disjoint_env {\u03c4cenv} l1 l2 l3 e \u03c4 :\n    disjoint (domain l2) (nnrc_free_vars e) ->\n    (nnrc_core_type \u03c4cenv (l1 ++ l2 ++ l3) e \u03c4 <-> nnrc_core_type \u03c4cenv (l1 ++ l3) e \u03c4).\n  Proof.\n    revert l1 l3.\n    induction l2; intros l1 l3 disj; simpl.\n    - tauto.\n    - simpl in disj.\n      apply disjoint_cons_inv1 in disj.\n      destruct disj as [disj nin].\n      destruct a; simpl in *.\n      rewrite nnrc_core_type_remove_free_env; trivial.\n      eauto.\n  Qed.\n\n  Lemma nnrc_core_type_remove_almost_free_env {\u03c4cenv} l v x l' e \u03c4 :\n    (In v (nnrc_free_vars e) -> In v (domain l)) ->\n    (nnrc_core_type \u03c4cenv (l ++ (v,x)::l') e \u03c4 <-> nnrc_core_type \u03c4cenv (l ++ l') e \u03c4).\n  Proof.\n    intros Hinn.\n    destruct (in_dec string_dec v (nnrc_free_vars e)) as [inn|inn].\n    - apply Hinn in inn.\n      apply in_domain_in in inn.\n      destruct inn as [? inn].\n      destruct (in_split _ _ inn) as [? [? ?]]; subst.\n      repeat rewrite app_ass; simpl.\n      apply nnrc_core_type_remove_duplicate_env.\n    - apply nnrc_core_type_remove_free_env; trivial.\n  Qed.\n\n  Lemma nnrc_core_type_remove_almost_disjoint_env {\u03c4cenv} l1 l2 l3 e \u03c4 :\n    (forall x,\n        In x (domain l2) -> \n        In x (nnrc_free_vars e) -> In x (domain l1)) ->\n    (nnrc_core_type \u03c4cenv (l1 ++ l2 ++ l3) e \u03c4 <-> nnrc_core_type \u03c4cenv (l1 ++ l3) e \u03c4).\n  Proof.\n    revert l1 l3.\n    induction l2; intros l1 l3 disj; simpl.\n    - tauto.\n    - simpl in disj.\n      destruct a; simpl in *.\n      rewrite nnrc_core_type_remove_almost_free_env; trivial.\n      + eauto.\n      + intuition.\n  Qed.\n  \n  Lemma nnrc_core_type_swap_neq {\u03c4cenv} l1 v1 x1 v2 x2 l2 e \u03c4 :\n    v1 <> v2 ->\n    (nnrc_core_type \u03c4cenv (l1++(v1,x1)::(v2,x2)::l2) e \u03c4 <-> \n     nnrc_core_type \u03c4cenv (l1++(v2,x2)::(v1,x1)::l2) e \u03c4).\n  Proof.\n    intros.\n    apply nnrc_core_type_lookup_equiv_prop; trivial.\n    apply lookup_swap_neq; trivial.\n  Qed.\n\n  Lemma nnrc_core_type_cons_subst {\u03c4cenv} e \u0393 v \u03c4\u2080 v' \u03c4 :\n    ~ (In v' (nnrc_free_vars e)) ->\n    ~ (In v' (nnrc_bound_vars e)) ->\n    (nnrc_core_type \u03c4cenv ((v',\u03c4\u2080)::\u0393) (nnrc_subst e v (NNRCVar v')) \u03c4 <->\n     nnrc_core_type \u03c4cenv ((v,\u03c4\u2080)::\u0393) e \u03c4).\n  Proof.\n    split; revert \u0393 v \u03c4\u2080 v' \u03c4 H H0;\n      induction e; simpl in *; unfold equiv_dec, string_eqdec; \n        trivial; intros \u0393 v\u2080 \u03c4\u2080 v' \u03c4 nfree nbound.\n    - intuition.\n      constructor.\n      destruct (string_dec v v\u2080); simpl; subst; intuition; inversion H; subst; simpl in *; repeat dest_eqdec; intuition.\n    - intuition.\n      constructor.\n      destruct (string_dec v v\u2080); simpl; subst; intuition; inversion H; subst; simpl in *; repeat dest_eqdec; intuition.\n    - inversion 1; subst. qeauto.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree, nbound.\n      intuition; qeauto.\n    - inversion 1; subst. qeauto.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree. intuition.\n      apply nin_app_or in H3. intuition.\n      match_destr_in H; subst.\n      + econstructor; eauto.\n        apply (nnrc_core_type_remove_duplicate_env nil v\u2080 \u03c4\u2081 nil); simpl.\n        generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4\u2081)::nil)); simpl; intros HH.\n        apply HH in H6; eauto.\n        intro; elim H1. apply remove_in_neq; eauto.\n      + econstructor; eauto.\n        apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n        eapply IHe2; eauto.\n        * intro; elim H1.\n          apply remove_in_neq; eauto.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree. intuition.\n      apply nin_app_or in H3. intuition.\n      match_destr_in H6; subst.\n      + econstructor; eauto.\n        apply (nnrc_core_type_remove_duplicate_env nil v\u2080 \u03c4\u2081 nil); simpl.\n        generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4\u2081)::nil)); simpl; intros HH.\n        apply HH in H6; eauto.\n        intro; elim H1. apply remove_in_neq; eauto.\n      + econstructor; eauto.\n        apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n        eapply IHe2; eauto.\n        * intro; elim H1.\n          apply remove_in_neq; eauto.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n    - inversion 1; subst.\n      apply nin_app_or in nfree; destruct nfree as [? HH]; apply nin_app_or in HH.\n      apply nin_app_or in nbound; destruct nbound as [? HHH]; apply nin_app_or in HHH.\n      intuition; qeauto.\n    - intro HH; inversion HH; subst; clear HH.\n      apply not_or in nbound; destruct nbound as [nb1 nb2].\n      apply not_or in nb2; destruct nb2 as [nb2 nb3].\n      repeat rewrite nin_app_or in nb3, nfree.\n      rewrite <- (remove_in_neq _ _ v) in nfree by congruence.\n      rewrite <- (remove_in_neq _ _ v0) in nfree by congruence.\n      econstructor.\n      + eapply IHe1; eauto 2; intuition.\n      + match_destr_in H7; subst.\n        * generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4l)::nil)); simpl;\n            intros re1; rewrite re1 in H7 by intuition.\n          generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil v\u2080 \u03c4l nil); simpl;\n            intros re2; rewrite re2 by intuition.\n          trivial.\n        * apply (nnrc_core_type_swap_neq nil); eauto 2; simpl.\n          apply (nnrc_core_type_swap_neq nil) in H7; eauto 2; simpl in *.\n          eapply IHe2; eauto 2; intuition.\n      + match_destr_in H8; subst.\n        * generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4r)::nil)); simpl;\n            intros re1; rewrite re1 in H8 by intuition.\n          generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil v\u2080 \u03c4r nil); simpl;\n            intros re2; rewrite re2 by intuition.\n          trivial.\n        * apply (nnrc_core_type_swap_neq nil); eauto 2; simpl.\n          apply (nnrc_core_type_swap_neq nil) in H8; eauto 2; simpl in *.\n          eapply IHe3; eauto 2; intuition.\n    - (* GroupBy Case: always fails for core? *)\n      intros.\n      inversion H.\n    - intuition.\n      destruct (string_dec v v\u2080); simpl; subst; intuition; \n        inversion H; subst; simpl in *; repeat dest_eqdec; intuition;\n          inversion H4; subst; constructor; simpl;\n            repeat dest_eqdec; intuition.\n    - intuition.\n      destruct (string_dec v v\u2080); simpl; subst; intuition; \n        inversion H; subst; simpl in *; repeat dest_eqdec; intuition;\n          inversion H4; subst; constructor; simpl;\n            repeat dest_eqdec; intuition.\n    - inversion 1; subst. qeauto.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree, nbound.\n      intuition; qeauto.\n    - inversion 1; subst. qeauto.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree. intuition.\n      apply nin_app_or in H3. intuition.\n      match_destr; subst.\n      + econstructor; eauto.\n        apply (nnrc_core_type_remove_duplicate_env nil v\u2080 \u03c4\u2081 nil) in H6; \n          simpl in H6.\n        generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4\u2081)::nil)); simpl; intros HH.\n        apply HH; eauto.\n        intro; elim H1. apply remove_in_neq; eauto.\n      + econstructor; eauto.\n        apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n        eapply IHe2; eauto.\n        * intro; elim H1.\n          apply remove_in_neq; eauto.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n    - inversion 1; subst.\n      rewrite nin_app_or in nfree. intuition.\n      apply nin_app_or in H3. intuition.\n      match_destr; subst.\n      + econstructor; eauto.\n        apply (nnrc_core_type_remove_duplicate_env nil v\u2080 \u03c4\u2081 nil) in H6; \n          simpl in H6.\n        generalize (@nnrc_core_type_remove_free_env \u03c4cenv ((v\u2080,\u03c4\u2081)::nil)); simpl; intros HH.\n        apply HH; eauto.\n        intro; elim H1. apply remove_in_neq; eauto.\n      + econstructor; eauto.\n        apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n        eapply IHe2; eauto.\n        * intro; elim H1.\n          apply remove_in_neq; eauto.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n    - inversion 1; subst.\n      apply nin_app_or in nfree; destruct nfree as [? HH]; apply nin_app_or in HH.\n      apply nin_app_or in nbound; destruct nbound as [? HHH]; apply nin_app_or in HHH.\n      intuition; eauto.\n    - apply not_or in nbound; destruct nbound as [nb1 nb2].\n      apply not_or in nb2; destruct nb2 as [nb2 nb3].\n      repeat rewrite nin_app_or in nb3, nfree.\n      rewrite <- (remove_in_neq _ _ v) in nfree by congruence.\n      rewrite <- (remove_in_neq _ _ v0) in nfree by congruence.    \n      intro HH; inversion HH; clear HH; subst.\n      econstructor.\n      + apply IHe1; eauto 2; intuition.\n      + match_destr; subst.\n        * generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil v\u2080 \u03c4l nil); simpl;\n            intros re1; rewrite re1 in H7.\n          apply (nnrc_core_type_remove_free_env ((v\u2080,\u03c4l)::nil)); intuition.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n          apply IHe2; eauto 2; intuition.\n          apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n      + match_destr; subst.\n        * generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil v\u2080 \u03c4r nil); simpl;\n            intros re1; rewrite re1 in H8.\n          apply (nnrc_core_type_remove_free_env ((v\u2080,\u03c4r)::nil)); intuition.\n        * apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n          apply IHe3; eauto 2; intuition.\n          apply (nnrc_core_type_swap_neq nil); eauto; simpl.\n    - (* GroupBy Case: always fails for core? *)\n      intros.\n      inversion H.\n  Qed.\n\n  Lemma nnrc_core_type_cons_subst_disjoint {\u03c4cenv} e e' \u0393 v \u03c4\u2080 \u03c4 :\n    disjoint (nnrc_bound_vars e) (nnrc_free_vars e') ->\n    nnrc_core_type \u03c4cenv \u0393 e' \u03c4\u2080 ->\n    nnrc_core_type \u03c4cenv ((v,\u03c4\u2080)::\u0393) e \u03c4 ->\n    nnrc_core_type \u03c4cenv \u0393 (nnrc_subst e v e') \u03c4.\n  Proof.\n    intros disj typ'.\n    revert \u0393 e' v \u03c4\u2080 \u03c4 disj typ'.\n    nnrc_cases (induction e) Case; simpl in *; \n      trivial; intros \u0393 v\u2080 \u03c4\u2080 v' \u03c4 nfree nbound; simpl;\n        intros typ; inversion typ; clear typ; subst;\n          unfold equiv_dec in *; simpl in * .\n    - Case \"NNRCGetConstant\"%string.\n      qeauto.\n    - Case \"NNRCVar\"%string.\n      match_destr.\n      + congruence.\n      + qauto.\n    - Case \"NNRCConst\"%string.\n      econstructor; trivial.\n    - Case \"NNRCBinop\"%string.\n      apply disjoint_app_l in nfree.\n      destruct nfree.\n      econstructor; eauto 2.\n    - Case \"NNRCUnop\"%string.\n      econstructor; eauto.\n    - Case \"NNRCLet\"%string.\n      apply disjoint_cons_inv1 in nfree.\n      destruct nfree as [disj nin].\n      apply disjoint_app_l in disj.\n      destruct disj as [disj1 disj2].\n      econstructor; eauto 2.\n      match_destr.\n      + red in e; subst.\n        generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil \u03c4\u2080 \u03c4\u2081 nil v' \u0393);\n          simpl; intros re1; apply re1; eauto.\n      + eapply IHe2; eauto 2.\n        * generalize (@nnrc_core_type_remove_free_env \u03c4cenv nil v \u03c4\u2081 \u0393 v\u2080);\n            simpl; intros re1; apply re1; eauto.\n        * generalize (@nnrc_core_type_swap_neq \u03c4cenv nil \u03c4\u2080 v' v \u03c4\u2081 \u0393 e2 \u03c4);\n            simpl; intros re1; apply re1; eauto.\n    - Case \"NNRCFor\"%string.\n      apply disjoint_cons_inv1 in nfree.\n      destruct nfree as [disj nin].\n      apply disjoint_app_l in disj.\n      destruct disj as [disj1 disj2].\n      econstructor; eauto 2.\n      match_destr.\n      + red in e; subst.\n        generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil \u03c4\u2080 \u03c4\u2081 nil v' \u0393);\n          simpl; intros re1; apply re1; eauto.\n      + eapply IHe2; eauto 2.\n        * generalize (@nnrc_core_type_remove_free_env \u03c4cenv nil v \u03c4\u2081 \u0393 v\u2080);\n            simpl; intros re1; apply re1; eauto.\n        * generalize (@nnrc_core_type_swap_neq \u03c4cenv nil \u03c4\u2080 v' v \u03c4\u2081 \u0393 e2 \u03c4\u2082);\n            simpl; intros re1; apply re1; eauto.\n    - Case \"NNRCIf\"%string.\n      apply disjoint_app_l in nfree.\n      destruct nfree as [disj1 disj2].\n      apply disjoint_app_l in disj2.\n      destruct disj2 as [disj2 disj3].\n      econstructor; eauto 2.\n    - Case \"NNRCEither\"%string.\n      apply disjoint_cons_inv1 in nfree.\n      destruct nfree as [disj nin].\n      apply disjoint_cons_inv1 in disj.\n      destruct disj as [disj nin2].\n      apply disjoint_app_l in disj.\n      destruct disj as [disj1 disj2].\n      apply disjoint_app_l in disj2.\n      destruct disj2 as [disj2 disj3].\n      econstructor; eauto 2.\n      + {\n          match_destr.\n          + red in e; subst.\n            generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil \u03c4\u2080 \u03c4l nil v' \u0393);\n              simpl; intros re1; apply re1; eauto.\n          + eapply IHe2; eauto 2.\n            * generalize (@nnrc_core_type_remove_free_env \u03c4cenv nil v \u03c4l \u0393 v\u2080);\n                simpl; intros re1; apply re1; eauto.\n            * generalize (@nnrc_core_type_swap_neq \u03c4cenv nil \u03c4\u2080 v' v \u03c4l \u0393 e2 \u03c4);\n                simpl; intros re1; apply re1; eauto.\n        }  \n      + {\n          match_destr.\n          + red in e; subst.\n            generalize (@nnrc_core_type_remove_duplicate_env \u03c4cenv nil \u03c4\u2080 \u03c4r nil v' \u0393);\n              simpl; intros re1; apply re1; eauto.\n          + eapply IHe3; eauto 2.\n            * generalize (@nnrc_core_type_remove_free_env \u03c4cenv nil v0 \u03c4r \u0393 v\u2080);\n                simpl; intros re1; apply re1; eauto.\n            * generalize (@nnrc_core_type_swap_neq \u03c4cenv nil \u03c4\u2080 v' v0 \u03c4r \u0393 e3 \u03c4);\n                simpl; intros re1; apply re1; eauto.\n        }\n  Qed.\n\n  Lemma nnrc_core_type_rename_pick_subst {\u03c4cenv} sep renamer avoid e \u0393 v \u03c4\u2080 \u03c4 :\n    (nnrc_core_type \u03c4cenv\n                    ((nnrc_pick_name sep renamer avoid v e,\u03c4\u2080)::\u0393)\n                    (nnrc_rename_lazy e v (nnrc_pick_name sep renamer avoid v e)) \u03c4\n     <->\n     nnrc_core_type \u03c4cenv ((v,\u03c4\u2080)::\u0393) e \u03c4).\n  Proof.\n    unfold nnrc_rename_lazy.\n    match_destr.\n    - rewrite <- e0.\n      tauto.\n    - rewrite nnrc_core_type_cons_subst; trivial.\n      + tauto.\n      + apply nnrc_pick_name_neq_nfree; trivial.\n      + apply nnrc_pick_name_bound.\n  Qed.\n\n  Theorem nnrc_core_unshadow_type {\u03c4cenv} sep renamer avoid \u0393 n \u03c4 :\n    nnrc_core_type \u03c4cenv \u0393 n \u03c4 <-> nnrc_core_type \u03c4cenv \u0393 (unshadow sep renamer avoid n) \u03c4.\n  Proof.\n    Hint Resolve really_fresh_from_free  really_fresh_from_bound : qcert.\n    split; revert \u0393 \u03c4; induction n; simpl in *; inversion 1; subst; qeauto; simpl.\n    - econstructor; [eauto|..].\n      apply nnrc_core_type_rename_pick_subst.\n      eauto.\n    - econstructor; [eauto|..].\n      apply nnrc_core_type_rename_pick_subst.\n      eauto.\n    - econstructor; [eauto|..].\n      apply nnrc_core_type_rename_pick_subst.\n      + eauto.\n      + apply nnrc_core_type_rename_pick_subst.\n        eauto.\n    - econstructor; [eauto|..].\n      apply nnrc_core_type_rename_pick_subst in H6.\n      eauto.\n    - econstructor; [eauto|..].\n      apply nnrc_core_type_rename_pick_subst in H6.\n      eauto.\n    - econstructor; [eauto|..].\n      + apply nnrc_core_type_rename_pick_subst in H8.\n        eauto.\n      + apply nnrc_core_type_rename_pick_subst in H9.\n        eauto.\n  Qed.\n\nEnd TcNNRCShadow.\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/cNNRC/Typing/TcNNRCShadow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1735490498387831}}
{"text": "Require Import VST.sepcomp.semantics.\n\nRequire Import VST.veric.juicy_base. \n\nRequire Import VST.veric.juicy_mem.  \nRequire Import VST.sepcomp.extspec.\nRequire Import VST.veric.ghost_PCM.\nRequire Import VST.veric.juicy_extspec.\n\nRequire Import VST.veric.res_predicates.\nRequire Import VST.veric.mpred.\nRequire Import VST.veric.seplog.\n\n(*Require Import VST.veric.initial_world. \nRequire Import VST.veric.SeparationLogic.\n *)\n\n(*********copied from initial_world***********)\nFixpoint find_id (id: ident) (G: funspecs) : option funspec  :=\n match G with\n | (id', f)::G' => if eq_dec id id' then Some f else find_id id G'\n | nil => None\n end.\n\nDefinition cond_approx_eq n A P1 P2 :=\n  (forall ts,\n      fmap (dependent_type_functor_rec ts (AssertTT A)) (approx n) (approx n) (P1 ts) =\n      fmap (dependent_type_functor_rec ts (AssertTT A)) (approx n) (approx n) (P2 ts)).\n\nDefinition func_at'' fsig cc A P Q :=\n  pureat (SomeP (SpecTT A) (packPQ P Q)) (FUN fsig cc).\n(*also copy lemmas on these from initial_world? or isolate in general file?*)\n\n(**********************************************)\n\n\nModule Type GENERAL_SEPARATION_LOGIC_SOUNDNESS.\n\n(*Declare Module ExtSpec: EXTERNAL_SPEC. *) \n(*Declare Module CSL: CLIGHT_SEPARATION_LOGIC.\nImport CSL. for semax_prog*)\n\n\nParameter F T: Type. (*Clight instantiates := fundef V:=type*)\n(*Record genv : Type := Build_genv { genv_genv : @Genv.t F T;  genv_cenv : composite_env }.\n\nParameter genv:Type.\n*)\nDefinition genv:Type := Genv.t F T.\n\n(*duplicated from tycontext to prevent specialization to Clight*)\nDefinition filter_genv (ge: genv) : genviron := Genv.find_symbol ge.\nDefinition empty_environ (ge: genv) := mkEnviron (filter_genv ge) (Map.empty _) (Map.empty _).\n\nParameter C: Type.\nParameter Sem: genv -> CoreSemantics C Memory.mem.\n\n(*Definition genv_symb_injective {F V} (ge: Genv.t F V) : extspec.injective_PTree block.\nProof.\nexists (Genv.genv_symb ge).\nhnf; intros.\neapply Genv.genv_vars_inj; eauto.\nDefined.*)\n(*Parameter genv_symb_injective: forall {F V:Type} (ge: Genv.t F V), extspec.injective_PTree block.*)\nParameter genv_symb_injective: genv -> extspec.injective_PTree block.\n\nDefinition jsafeN {Z} (Hspec : juicy_ext_spec Z) (ge: genv) :=\n  @jsafeN_ genv _ _ genv_symb_injective (*(genv_symb := fun ge: genv => Genv.genv_symb ge)*)\n           (Sem ge) Hspec ge.\n\nDefinition matchfunspecs (ge : genv) (G : funspecs) (Phi : rmap) :=\nforall (b : block) (fsig : compcert_rmaps.funsig)\n  (cc : calling_convention) (A : TypeTree)\n  (P\n   Q : forall ts : list Type,\n       (dependent_type_functor_rec ts (AssertTT A)) (pred rmap)),\n(func_at'' fsig cc A P Q (b, 0)) Phi ->\nexists\n  (id : ident) (P'\n                Q' : forall ts : list Type,\n                     (dependent_type_functor_rec ts (AssertTT A)) mpred) \n(P'_ne : super_non_expansive P') (Q'_ne : super_non_expansive Q'),\n  Genv.find_symbol ge id = Some b /\\\n  find_id id G = Some (mk_funspec fsig cc A P' Q' P'_ne Q'_ne) /\\\n  cond_approx_eq (level Phi) A P P' /\\ cond_approx_eq (level Phi) A Q Q'.\n\nDefinition EPoint_sound {Espec: OracleKind} FS m (h:nat) (entryPT:ident) (g:genv) :=\n     { b : block & { q : C &\n       (Genv.find_symbol g entryPT = Some b) *\n       (forall jm, m_dry jm = m -> exists jm', semantics.initial_core (juicy_core_sem (Sem g)) h\n                    jm q jm' (Vptr b Ptrofs.zero) nil) *\n       forall n z,\n         { jm |\n           m_dry jm = m /\\ level jm = n /\\\n           nth_error (ghost_of (m_phi jm)) 0 = Some (Some (ext_ghost z, NoneP)) /\\\n           jsafeN (@OK_spec Espec) g n z q jm /\\\n           res_predicates.no_locks (m_phi jm) /\\\n           matchfunspecs g FS (m_phi jm) /\\\n           app_pred (funspecs_assert (make_tycontext_s FS) (empty_environ g))  (m_phi jm) } } }%type.\n\n(*maybe generalize from single EP (\"main\") to multiple entry points?\nAxiom module_sound: forall Espec G m h entryPT g,\n      @EPoint_sound Espec G m h entryPT g.\n\nDefinition prog_sound {Espec: OracleKind} CS prog :=\n     @semax_prog Espec CS prog V G ->\n     forall h m,\n     @Genv.init_mem F T prog = Some m ->\n     @EPoint_sound Espec G m h (prog_main prog)  (globalenv prog).\n                                    *)\n\nEnd GENERAL_SEPARATION_LOGIC_SOUNDNESS.\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/GeneralSeparationLogicSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17354904630839937}}
{"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(** Register allocation by external oracle and a posteriori validation. *)\n\nRequire Import FSets.\nRequire FSetAVLplus.\nRequire Archi.\nRequire Import Coqlib.\nRequire Import Ordered.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Lattice.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Memdata.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Kildall.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import RTLtyping.\nRequire Import LTL.\n\n(** The validation algorithm used here is described in\n  \"Validating register allocation and spilling\", \n  by Silvain Rideau and Xavier Leroy,\n  in Compiler Construction (CC 2010), LNCS 6011, Springer, 2010. *)\n\n(** * Structural checks *)\n\n(** As a first pass, we check the LTL code returned by the external oracle\n  against the original RTL code for structural conformance.\n  Each RTL instruction was transformed into a LTL basic block whose\n  shape must agree with the RTL instruction.  For example, if the RTL\n  instruction is [Istore(Mint32, addr, args, src, s)], the LTL basic block\n  must be of the following shape:\n- zero, one or several \"move\" instructions\n- a store instruction [Lstore(Mint32, addr, args', src')]\n- a [Lbranch s] instruction.\n\n  The [block_shape] type below describes all possible cases of structural\n  maching between an RTL instruction and an LTL basic block.\n*)\n\nDefinition moves := list (loc * loc)%type.\n\nInductive block_shape: Type :=\n  | BSnop (mv: moves) (s: node)\n  | BSmove (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSmakelong (src1 src2: reg) (dst: reg) (mv: moves) (s: node)\n  | BSlowlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BShighlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSop (op: operation) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': mreg)\n         (mv2: moves) (s: node)\n  | BSopdead (op: operation) (args: list reg) (res: reg)\n         (mv: moves) (s: node)\n  | BSload (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSloaddead (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv: moves) (s: node)\n  | BSload2 (addr1 addr2: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args1': list mreg) (dst1': mreg)\n         (mv2: moves) (args2': list mreg) (dst2': mreg)\n         (mv3: moves) (s: node)\n  | BSload2_1 (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSload2_2 (addr addr': addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSstore (chunk: memory_chunk) (addr: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args': list mreg) (src': mreg)\n         (s: node)\n  | BSstore2 (addr1 addr2: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args1': list mreg) (src1': mreg)\n         (mv2: moves) (args2': list mreg) (src2': mreg)\n         (s: node)\n  | BScall (sg: signature) (ros: reg + ident) (args: list reg) (res: reg)\n         (mv1: moves) (ros': mreg + ident) (mv2: moves) (s: node)\n  | BStailcall (sg: signature) (ros: reg + ident) (args: list reg)\n         (mv1: moves) (ros': mreg + ident)\n  | BSbuiltin (ef: external_function) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': list mreg)\n         (mv2: moves) (s: node)\n  | BSannot (ef: external_function)\n         (args: list (annot_arg reg)) (args': list (annot_arg loc))\n         (s: node)\n  | BScond (cond: condition) (args: list reg)\n         (mv: moves) (args': list mreg) (s1 s2: node)\n  | BSjumptable (arg: reg)\n         (mv: moves) (arg': mreg) (tbl: list node)\n  | BSreturn (arg: option reg)\n         (mv: moves).\n\n(** Extract the move instructions at the beginning of block [b].\n  Return the list of moves and the suffix of [b] after the moves. *)\n\nFixpoint extract_moves (accu: moves) (b: bblock) {struct b} : moves * bblock :=\n  match b with\n  | Lgetstack sl ofs ty dst :: b' =>\n      extract_moves ((S sl ofs ty, R dst) :: accu) b'\n  | Lsetstack src sl ofs ty :: b' =>\n      extract_moves ((R src, S sl ofs ty) :: accu) b'\n  | Lop op args res :: b' =>\n      match is_move_operation op args with\n      | Some arg => extract_moves ((R arg, R res) :: accu) b'\n      | None => (List.rev accu, b)\n      end\n  | _ =>\n      (List.rev accu, b)\n  end.\n\nDefinition check_succ (s: node) (b: LTL.bblock) : bool :=\n  match b with\n  | Lbranch s' :: _ => peq s s'\n  | _ => false\n  end.\n\nNotation \"'do' X <- A ; B\" := (match A with Some X => B | None => None end)\n         (at level 200, X ident, A at level 100, B at level 200)\n         : option_monad_scope.\n\nNotation \"'assertion' A ; B\" := (if A then B else None)\n         (at level 200, A at level 100, B at level 200)\n         : option_monad_scope.\n\nLocal Open Scope option_monad_scope.\n\n(** Classify operations into moves, 64-bit integer operations, and other\n  arithmetic/logical operations. *)\n\nInductive operation_kind: operation -> list reg -> Type :=\n  | operation_Omove: forall arg, operation_kind Omove (arg :: nil)\n  | operation_Omakelong: forall arg1 arg2, operation_kind Omakelong (arg1 :: arg2 :: nil)\n  | operation_Olowlong: forall arg, operation_kind Olowlong (arg :: nil)\n  | operation_Ohighlong: forall arg, operation_kind Ohighlong (arg :: nil)\n  | operation_other: forall op args, operation_kind op args.\n\nDefinition classify_operation (op: operation) (args: list reg) : operation_kind op args :=\n  match op, args with\n  | Omove, arg::nil => operation_Omove arg\n  | Omakelong, arg1::arg2::nil => operation_Omakelong arg1 arg2\n  | Olowlong, arg::nil => operation_Olowlong arg\n  | Ohighlong, arg::nil => operation_Ohighlong arg\n  | op, args => operation_other op args\n  end.\n\n(** Check RTL instruction [i] against LTL basic block [b].  \n  On success, return [Some] with a [block_shape] describing the correspondence.\n  On error, return [None]. *)\n\nDefinition pair_instr_block\n               (i: RTL.instruction) (b: LTL.bblock) : option block_shape :=\n  match i with\n  | Inop s =>\n      let (mv, b1) := extract_moves nil b in\n      assertion (check_succ s b1); Some(BSnop mv s)\n  | Iop op args res s =>\n      match classify_operation op args with\n      | operation_Omove arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmove arg res mv s)\n      | operation_Omakelong arg1 arg2 =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmakelong arg1 arg2 res mv s)\n      | operation_Olowlong arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSlowlong arg res mv s)\n      | operation_Ohighlong arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BShighlong arg res mv s)\n      | operation_other _ _ =>\n          let (mv1, b1) := extract_moves nil b in\n          match b1 with\n          | Lop op' args' res' :: b2 =>\n              let (mv2, b3) := extract_moves nil b2 in\n              assertion (eq_operation op op');\n              assertion (check_succ s b3);\n              Some(BSop op args res mv1 args' res' mv2 s)\n          | _ =>\n              assertion (check_succ s b1);\n              Some(BSopdead op args res mv1 s)\n          end\n      end\n  | Iload chunk addr args dst s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lload chunk' addr' args' dst' :: b2 =>\n          if chunk_eq chunk Mint64 then\n            assertion (chunk_eq chunk' Mint32);\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lload chunk'' addr'' args'' dst'' :: b4 =>\n                let (mv3, b5) := extract_moves nil b4 in\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr''));\n                assertion (check_succ s b5);\n                Some(BSload2 addr addr'' args dst mv1 args' dst' mv2 args'' dst'' mv3 s)\n            | _ =>\n                assertion (check_succ s b3);\n                if (eq_addressing addr addr') then\n                  Some(BSload2_1 addr args dst mv1 args' dst' mv2 s)\n                else\n                 (assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr'));\n                  Some(BSload2_2 addr addr' args dst mv1 args' dst' mv2 s))\n            end\n          else (\n            let (mv2, b3) := extract_moves nil b2 in\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b3);\n            Some(BSload chunk addr args dst mv1 args' dst' mv2 s))\n      | _ =>\n          assertion (check_succ s b1);\n          Some(BSloaddead chunk addr args dst mv1 s)\n      end\n  | Istore chunk addr args src s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lstore chunk' addr' args' src' :: b2 =>\n          if chunk_eq chunk Mint64 then\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lstore chunk'' addr'' args'' src'' :: b4 =>\n                assertion (chunk_eq chunk' Mint32);\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr (Int.repr 4)) (Some addr''));\n                assertion (check_succ s b4);\n                Some(BSstore2 addr addr'' args src mv1 args' src' mv2 args'' src'' s)\n            | _ => None\n            end\n          else (\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b2);\n            Some(BSstore chunk addr args src mv1 args' src' s))\n      | _ => None\n      end\n  | Icall sg ros args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcall sg' ros' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (signature_eq sg sg');\n          assertion (check_succ s b3);\n          Some(BScall sg ros args res mv1 ros' mv2 s)\n      | _ => None\n      end\n  | Itailcall sg ros args =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ltailcall sg' ros' :: b2 =>\n          assertion (signature_eq sg sg');\n          Some(BStailcall sg ros args mv1 ros')\n      | _ => None\n      end\n  | Ibuiltin ef args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lbuiltin ef' args' res' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (external_function_eq ef ef');\n          assertion (check_succ s b3);\n          Some(BSbuiltin ef args res mv1 args' res' mv2 s)\n      | _ => None\n      end\n  | Iannot ef args s =>\n      match b with\n      | Lannot ef' args' :: b1 =>\n          assertion (external_function_eq ef ef');\n          assertion (check_succ s b1);\n          Some(BSannot ef args args' s)\n      | _ => None\n      end\n  | Icond cond args s1 s2 =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcond cond' args' s1' s2' :: b2 =>\n          assertion (eq_condition cond cond');\n          assertion (peq s1 s1');\n          assertion (peq s2 s2');\n          Some(BScond cond args mv1 args' s1 s2)\n      | _ => None\n      end\n  | Ijumptable arg tbl =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ljumptable arg' tbl' :: b2 =>\n          assertion (list_eq_dec peq tbl tbl');\n          Some(BSjumptable arg mv1 arg' tbl)\n      | _ => None\n      end\n  | Ireturn arg =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lreturn :: b2 => Some(BSreturn arg mv1)\n      | _ => None\n      end\n  end.\n\n(** Check all instructions of the RTL function [f1] against the corresponding\n  basic blocks of LTL function [f2].  Return a map from CFG nodes to\n  [block_shape] info. *)\n\nDefinition pair_codes (f1: RTL.function) (f2: LTL.function) : PTree.t block_shape :=\n  PTree.combine\n    (fun opti optb => do i <- opti; do b <- optb; pair_instr_block i b)\n    (RTL.fn_code f1) (LTL.fn_code f2).\n\n(** Check the entry point code of the LTL function [f2].  It must be\n  a sequence of moves that branches to the same node as the entry point\n  of RTL function [f1]. *)\n\nDefinition pair_entrypoints (f1: RTL.function) (f2: LTL.function) : option moves :=\n  do b <- (LTL.fn_code f2)!(LTL.fn_entrypoint f2);\n  let (mv, b1) := extract_moves nil b in\n  assertion (check_succ (RTL.fn_entrypoint f1) b1);\n  Some mv.\n\n(** * Representing sets of equations between RTL registers and LTL locations. *)\n\n(** The Rideau-Leroy validation algorithm manipulates sets of equations of\n  the form [pseudoreg = location [kind]], meaning:\n- if [kind = Full], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the value of [pseudoreg] in the original\n  RTL code;\n- if [kind = Low], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the low 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code;\n- if [kind = High], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the high 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code.\n*)\n\nInductive equation_kind : Type := Full | Low | High.\n\nRecord equation := Eq {\n  ekind: equation_kind;\n  ereg: reg;\n  eloc: loc\n}.\n\n(** We use AVL finite sets to represent sets of equations.  Therefore, we need\n  total orders over equations and their components. *)\n\nModule IndexedEqKind <: INDEXED_TYPE.\n  Definition t := equation_kind.\n  Definition index (x: t) :=\n    match x with Full => 1%positive | Low => 2%positive | High => 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 (x y: t) : {x=y} + {x<>y}.\n  Proof. decide equality. Defined.\nEnd IndexedEqKind.\n\nModule OrderedEqKind := OrderedIndexed(IndexedEqKind).\n\n(** This is an order over equations that is lexicographic on [ereg], then\n  [eloc], then [ekind]. *)\n\nModule OrderedEquation <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    (OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H. \n    destruct H0. left; eapply Plt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H. \n    destruct H0. auto. \n    destruct H0. right; split; auto.\n    intuition. \n    left; eapply OrderedLoc.lt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim Plt_strict; eauto.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedPositive.compare (ereg x) (ereg y)).\n  - apply LT. red; auto.\n  - destruct (OrderedLoc.compare (eloc x) (eloc y)).\n    + apply LT. red; auto. \n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red. \n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec (x y: t) : {x = y} + {x <> y}.\n  Proof.\n    intros. decide equality. \n    apply Loc.eq.\n    apply peq.\n    apply IndexedEqKind.eq.\n  Defined.\nEnd OrderedEquation.\n\n(** This is an alternate order over equations that is lexicgraphic on\n  [eloc], then [ereg], then [ekind]. *)\n\nModule OrderedEquation' <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    (Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H. \n    destruct H0. left; eapply OrderedLoc.lt_trans; eauto. \n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H. \n    destruct H0. auto. \n    destruct H0. right; split; auto.\n    intuition. \n    left; eapply Plt_trans; eauto. \n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim Plt_strict; eauto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedLoc.compare (eloc x) (eloc y)).\n  - apply LT. red; auto.\n  - destruct (OrderedPositive.compare (ereg x) (ereg y)).\n    + apply LT. red; auto. \n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red. \n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec: forall (x y: t), {x = y} + {x <> y} := OrderedEquation.eq_dec.\nEnd OrderedEquation'.\n\nModule EqSet := FSetAVLplus.Make(OrderedEquation).\nModule EqSet2 := FSetAVLplus.Make(OrderedEquation').\n\n(** We use a redundant representation for sets of equations, comprising\n  two AVL finite sets, containing the same elements, but ordered along\n  the two orders defined above.  Playing on properties of lexicographic\n  orders, this redundant representation enables us to quickly find\n  all equations involving a given RTL pseudoregister, or all equations\n  involving a given LTL location or overlapping location. *)\n\nRecord eqs := mkeqs {\n  eqs1 :> EqSet.t;\n  eqs2 : EqSet2.t;\n  eqs_same: forall q, EqSet2.In q eqs2 <-> EqSet.In q eqs1\n}.\n\n(** * Operations on sets of equations *)\n\n(** The empty set of equations. *)\n\nProgram Definition empty_eqs := mkeqs EqSet.empty EqSet2.empty _.\nNext Obligation.\n  split; intros. eelim EqSet2.empty_1; eauto. eelim EqSet.empty_1; eauto.\nQed.\n\n(** Adding or removing an equation from a set. *)\n\nProgram Definition add_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.add q (eqs1 e)) (EqSet2.add q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0). \n  apply EqSet.add_1; auto.\n  apply EqSet.add_2. apply (eqs_same e). apply EqSet2.add_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0). \n  apply EqSet2.add_1; auto.\n  apply EqSet2.add_2. apply (eqs_same e). apply EqSet.add_3 with q; auto.\nQed.\n\nProgram Definition remove_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.remove q (eqs1 e)) (EqSet2.remove q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0). \n  eelim EqSet2.remove_1; eauto.\n  apply EqSet.remove_2; auto. apply (eqs_same e). apply EqSet2.remove_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0). \n  eelim EqSet.remove_1; eauto.\n  apply EqSet2.remove_2; auto. apply (eqs_same e). apply EqSet.remove_3 with q; auto.\nQed.\n\n(** [reg_unconstrained r e] is true if [e] contains no equations involving\n  the RTL pseudoregister [r].  In other words, all equations [r' = l [kind]]\n  in [e] are such that [r' <> r]. *)\n\nDefinition select_reg_l (r: reg) (q: equation) := Pos.leb r (ereg q).\nDefinition select_reg_h (r: reg) (q: equation) := Pos.leb (ereg q) r.\n\nDefinition reg_unconstrained (r: reg) (e: eqs) : bool :=\n  negb (EqSet.mem_between (select_reg_l r) (select_reg_h r) (eqs1 e)).\n\n(** [loc_unconstrained l e] is true if [e] contains no equations involving\n  the LTL location [l] or a location that partially overlaps with [l].\n  In other words, all equations [r = l' [kind]] in [e] are such that\n  [Loc.diff l' l]. *)\n\nDefinition select_loc_l (l: loc) :=\n  let lb := OrderedLoc.diff_low_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lb with LT _ => false | _ => true end.\nDefinition select_loc_h (l: loc) :=\n  let lh := OrderedLoc.diff_high_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lh with GT _ => false | _ => true end.\n\nDefinition loc_unconstrained (l: loc) (e: eqs) : bool :=\n  negb (EqSet2.mem_between (select_loc_l l) (select_loc_h l) (eqs2 e)).\n\nDefinition reg_loc_unconstrained (r: reg) (l: loc) (e: eqs) : bool :=\n  reg_unconstrained r e && loc_unconstrained l e.\n\n(** [subst_reg r1 r2 e] simulates the effect of assigning [r2] to [r1] on [e].\n  All equations of the form [r1 = l [kind]] are replaced by [r2 = l [kind]].\n*)\n\nDefinition subst_reg (r1 r2: reg) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e => add_equation (Eq (ekind q) r2 (eloc q)) (remove_equation q e))\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_reg_kind r1 k1 r2 k2 e] simulates the effect of assigning\n  the [k2] part of [r2] to the [k1] part of [r1] on [e].\n  All equations of the form [r1 = l [k1]] are replaced by [r2 = l [k2]].\n*)\n\nDefinition subst_reg_kind (r1: reg) (k1: equation_kind) (r2: reg) (k2: equation_kind) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e =>\n      if IndexedEqKind.eq (ekind q) k1\n      then add_equation (Eq k2 r2 (eloc q)) (remove_equation q e)\n      else e)\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_loc l1 l2 e] simulates the effect of assigning [l2] to [l1] on [e].\n  All equations of the form [r = l1 [kind]] are replaced by [r = l2 [kind]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1]. \n*)\n\nDefinition subst_loc (l1 l2: loc) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            Some (add_equation (Eq (ekind q) (ereg q) l2) (remove_equation q e))\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [loc_type_compat env l e] checks that for all equations [r = l] in [e],\n  the type [env r] of [r] is compatible with the type of [l]. *)\n\nDefinition sel_type (k: equation_kind) (ty: typ) : typ :=\n  match k with\n  | Full => ty\n  | Low | High => Tint\n  end.\n\nDefinition loc_type_compat (env: regenv) (l: loc) (e: eqs) : bool :=\n  EqSet2.for_all_between\n    (fun q => subtype (sel_type (ekind q) (env (ereg q))) (Loc.type l))\n    (select_loc_l l) (select_loc_h l) (eqs2 e).\n\n(** [add_equations [r1...rN] [m1...mN] e] adds to [e] the [N] equations\n    [ri = R mi [Full]].  Return [None] if the two lists have different lengths.\n*)\n\nFixpoint add_equations (rl: list reg) (ml: list mreg) (e: eqs) : option eqs :=\n  match rl, ml with\n  | nil, nil => Some e\n  | r1 :: rl, m1 :: ml => add_equations rl ml (add_equation (Eq Full r1 (R m1)) e)\n  | _, _ => None\n  end.\n\n(** [add_equations_args] is similar but additionally handles the splitting\n  of pseudoregisters of type [Tlong] in two locations containing the\n  two 32-bit halves of the 64-bit integer. *)\n\nFunction add_equations_args (rl: list reg) (tyl: list typ) (ll: list loc) (e: eqs) : option eqs :=\n  match rl, tyl, ll with\n  | nil, nil, nil => Some e\n  | r1 :: rl, Tlong :: tyl, l1 :: l2 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Low r1 l2) (add_equation (Eq High r1 l1) e))\n  | r1 :: rl, (Tint|Tfloat|Tsingle) :: tyl, l1 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Full r1 l1) e)\n  | _, _, _ => None\n  end.\n\n(** [add_equations_res] is similar but is specialized to the case where\n  there is only one pseudo-register. *)\n\nFunction add_equations_res (r: reg) (oty: option typ) (ll: list loc) (e: eqs) : option eqs :=\n  match oty with\n  | Some Tlong =>\n      match ll with\n      | l1 :: l2 :: nil => Some (add_equation (Eq Low r l2) (add_equation (Eq High r l1) e))\n      | _ => None\n      end\n  | _ =>\n      match ll with\n      | l1 :: nil => Some (add_equation (Eq Full r l1) e)\n      | _ => None\n      end\n  end.\n\n(** [remove_equations_res] is similar to [add_equations_res] but removes\n  equations instead of adding them. *)\n\nFunction remove_equations_res (r: reg) (oty: option typ) (ll: list loc) (e: eqs) : option eqs :=\n  match oty with\n  | Some Tlong =>\n      match ll with\n      | l1 :: l2 :: nil =>\n          if Loc.diff_dec l2 l1\n          then Some (remove_equation (Eq Low r l2) (remove_equation (Eq High r l1) e))\n          else None\n      | _ => None\n      end\n  | _ =>\n      match ll with\n      | l1 :: nil => Some (remove_equation (Eq Full r l1) e)\n      | _ => None\n      end\n  end.\n\n(** [add_equations_ros] adds an equation, if needed, between an optional\n  pseudoregister and an optional machine register.  It is used for the\n  function argument of the [Icall] and [Itailcall] instructions. *)\n\nDefinition add_equation_ros (ros: reg + ident) (ros': mreg + ident) (e: eqs) : option eqs :=\n  match ros, ros' with\n  | inl r, inl mr => Some(add_equation (Eq Full r (R mr)) e)\n  | inr id, inr id' => assertion (ident_eq id id'); Some e\n  | _, _ => None\n  end.\n\n(** [add_equations_annot_arg] adds the needed equations for annotation\n   arguments. *)\n\nFixpoint add_equations_annot_arg (env: regenv) (arg: annot_arg reg) (arg': annot_arg loc) (e: eqs) : option eqs :=\n  match arg, arg' with\n  | AA_base r, AA_base l =>\n      Some (add_equation (Eq Full r l) e)\n  | AA_base r, AA_longofwords (AA_base lhi) (AA_base llo) =>\n      assertion (typ_eq (env r) Tlong);\n      Some (add_equation (Eq Low r llo) (add_equation (Eq High r lhi) e))\n  | AA_int n, AA_int n' =>\n      assertion (Int.eq_dec n n'); Some e\n  | AA_long n, AA_long n' =>\n      assertion (Int64.eq_dec n n'); Some e\n  | AA_float f, AA_float f' =>\n      assertion (Float.eq_dec f f'); Some e\n  | AA_single f, AA_single f' =>\n      assertion (Float32.eq_dec f f'); Some e\n  | AA_loadstack chunk ofs, AA_loadstack chunk' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (Int.eq_dec ofs ofs');\n      Some e\n  | AA_addrstack ofs, AA_addrstack ofs' =>\n      assertion (Int.eq_dec ofs ofs');\n      Some e\n  | AA_loadglobal chunk id ofs, AA_loadglobal chunk' id' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (ident_eq id id');\n      assertion (Int.eq_dec ofs ofs');\n      Some e\n  | AA_addrglobal id ofs, AA_addrglobal id' ofs' =>\n      assertion (ident_eq id id');\n      assertion (Int.eq_dec ofs ofs');\n      Some e\n  | AA_longofwords hi lo, AA_longofwords hi' lo' =>\n      do e1 <- add_equations_annot_arg env hi hi' e;\n      add_equations_annot_arg env lo lo' e1\n  | _, _ =>\n      None\n  end.\n\nFixpoint add_equations_annot_args (env: regenv)\n   (args: list(annot_arg reg)) (args': list(annot_arg loc)) (e: eqs) : option eqs :=\n  match args, args' with\n  | nil, nil => Some e\n  | a1 :: al, a1' :: al' =>\n      do e1 <- add_equations_annot_arg env a1 a1' e;\n      add_equations_annot_args env al al' e1\n  | _, _ => None\n  end.\n\n(** [can_undef ml] returns true if all machine registers in [ml] are\n  unconstrained and can harmlessly be undefined. *)\n\nFixpoint can_undef (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => loc_unconstrained (R m1) e && can_undef ml e\n  end.\n\nFixpoint can_undef_except (l: loc) (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => \n      (Loc.eq l (R m1) || loc_unconstrained (R m1) e) && can_undef_except l ml e\n  end.\n\n(** [no_caller_saves e] returns [e] if all caller-save locations are\n  unconstrained in [e].  In other words, [e] contains no equations\n  involving a caller-save register or [Outgoing] stack slot. *)\n\nDefinition no_caller_saves (e: eqs) : bool :=\n  EqSet.for_all\n   (fun eq =>\n     match eloc eq with\n       | R r =>\n           zle 0 (index_int_callee_save r) || zle 0 (index_float_callee_save r)\n       | S Outgoing _ _ => false\n       | S _ _ _ => true\n       end)\n    e.\n\n(** [compat_left r l e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l [Full]]. *)\n\nDefinition compat_left (r: reg) (l: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | Full => Loc.eq l (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [compat_left2 r l1 l2 e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l1 [High]] or [r = l2 [Low]]. *)\n\nDefinition compat_left2 (r: reg) (l1 l2: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | High => Loc.eq l1 (eloc q)\n        | Low => Loc.eq l2 (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [ros_compatible_tailcall ros] returns true if [ros] is a function\n  name or a caller-save register.  This is used to check [Itailcall]\n  instructions. *)\n\nDefinition ros_compatible_tailcall (ros: mreg + ident) : bool :=\n  match ros with\n  | inl r => In_dec mreg_eq r destroyed_at_call\n  | inr id => true\n  end.\n\n(** * The validator *)\n\nDefinition destroyed_by_move (src dst: loc) :=\n  match src, dst with\n  | S sl ofs ty, _ => destroyed_by_getstack sl\n  | _, S sl ofs ty => destroyed_by_setstack ty\n  | _, _ => destroyed_by_op Omove\n  end.\n\nDefinition well_typed_move (env: regenv) (dst: loc) (e: eqs) : bool :=\n  match dst with\n  | R r => true\n  | S sl ofs ty => loc_type_compat env dst e\n  end.\n\n(** Simulate the effect of a sequence of moves [mv] on a set of\n  equations [e].  The set [e] is the equations that must hold\n  after the sequence of moves.  Return the set of equations that\n  must hold before the sequence of moves.  Return [None] if the\n  set of equations [e] cannot hold after the sequence of moves. *)\n\nFixpoint track_moves (env: regenv) (mv: moves) (e: eqs) : option eqs :=\n  match mv with\n  | nil => Some e\n  | (src, dst) :: mv =>\n      do e1 <- track_moves env mv e;\n      assertion (can_undef_except dst (destroyed_by_move src dst)) e1;\n      assertion (well_typed_move env dst e1);\n      subst_loc dst src e1\n  end.\n\n(** [transfer_use_def args res args' res' undefs e] returns the set\n  of equations that must hold \"before\" in order for the equations [e]\n  to hold \"after\" the execution of RTL and LTL code of the following form:\n<<\n                RTL                            LTL\n         use pseudoregs args            use machine registers args'\n         define pseudoreg res           undefine machine registers undef\n                                        define machine register res'\n>>\n  As usual, [None] is returned if the equations [e] cannot hold after\n  this execution.\n*)\n\nDefinition transfer_use_def (args: list reg) (res: reg) (args': list mreg) (res': mreg)\n                            (undefs: list mreg) (e: eqs) : option eqs :=\n  let e1 := remove_equation (Eq Full res (R res')) e in\n  assertion (reg_loc_unconstrained res (R res') e1);\n  assertion (can_undef undefs e1);\n  add_equations args args' e1.\n\nDefinition kind_first_word := if Archi.big_endian then High else Low.\nDefinition kind_second_word := if Archi.big_endian then Low else High.\n\n(** The core transfer function.  It takes a set [e] of equations that must\n  hold \"after\" and a block shape [shape] representing a matching pair\n  of an RTL instruction and an LTL basic block.  It returns the set of\n  equations that must hold \"before\" these instructions, or [None] if\n  impossible. *)\n\nDefinition transfer_aux (f: RTL.function) (env: regenv)\n                        (shape: block_shape) (e: eqs) : option eqs :=\n  match shape with\n  | BSnop mv s =>\n      track_moves env mv e\n  | BSmove src dst mv s =>\n      track_moves env mv (subst_reg dst src e)\n  | BSmakelong src1 src2 dst mv s =>\n      let e1 := subst_reg_kind dst High src1 Full e in\n      let e2 := subst_reg_kind dst Low src2 Full e1 in\n      assertion (reg_unconstrained dst e2);\n      track_moves env mv e2\n  | BSlowlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src Low e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BShighlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src High e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BSop op args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args res args' res' (destroyed_by_op op) e1;\n      track_moves env mv1 e2\n  | BSopdead op args res mv s =>\n      assertion (reg_unconstrained res e);\n      track_moves env mv e\n  | BSload chunk addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args dst args' dst' (destroyed_by_load chunk addr) e1;\n      track_moves env mv1 e2\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s =>\n      do e1 <- track_moves env mv3 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst2')) e1 in\n      assertion (loc_unconstrained (R dst2') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args2' e2;\n      do e4 <- track_moves env mv2 e3;\n      let e5 := remove_equation (Eq kind_first_word dst (R dst1')) e4 in\n      assertion (loc_unconstrained (R dst1') e5);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e5);\n      assertion (reg_unconstrained dst e5);\n      do e6 <- add_equations args args1' e5;\n      track_moves env mv1 e6\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_first_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSloaddead chunk addr args dst mv s =>\n      assertion (reg_unconstrained dst e);\n      track_moves env mv e\n  | BSstore chunk addr args src mv args' src' s =>\n      assertion (can_undef (destroyed_by_store chunk addr) e);\n      do e1 <- add_equations (src :: args) (src' :: args') e;\n      track_moves env mv e1\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s =>\n      assertion (can_undef (destroyed_by_store Mint32 addr') e);\n      do e1 <- add_equations args args2' \n                  (add_equation (Eq kind_second_word src (R src2')) e);\n      do e2 <- track_moves env mv2 e1;\n      assertion (can_undef (destroyed_by_store Mint32 addr) e2);\n      do e3 <- add_equations args args1' \n                  (add_equation (Eq kind_first_word src (R src1')) e2);\n      track_moves env mv1 e3\n  | BScall sg ros args res mv1 ros' mv2 s =>\n      let args' := loc_arguments sg in\n      let res' := map R (loc_result sg) in\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_res res (sig_res sg) res' e1;\n      assertion (forallb (fun l => reg_loc_unconstrained res l e2) res');\n      assertion (no_caller_saves e2);\n      do e3 <- add_equation_ros ros ros' e2;\n      do e4 <- add_equations_args args (sig_args sg) args' e3;\n      track_moves env mv1 e4\n  | BStailcall sg ros args mv1 ros' =>\n      let args' := loc_arguments sg in\n      assertion (tailcall_is_possible sg);\n      assertion (opt_typ_eq sg.(sig_res) f.(RTL.fn_sig).(sig_res));\n      assertion (ros_compatible_tailcall ros');\n      do e1 <- add_equation_ros ros ros' empty_eqs;\n      do e2 <- add_equations_args args (sig_args sg) args' e1;\n      track_moves env mv1 e2\n  | BSbuiltin ef args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let args' := map R args' in\n      let res' := map R res' in\n      do e2 <- remove_equations_res res (sig_res (ef_sig ef)) res' e1;\n      assertion (reg_unconstrained res e2);\n      assertion (forallb (fun l => loc_unconstrained l e2) res');\n      assertion (can_undef (destroyed_by_builtin ef) e2);\n      do e3 <- add_equations_args args (sig_args (ef_sig ef)) args' e2;\n      track_moves env mv1 e3\n  | BSannot ef args args' s =>\n      add_equations_annot_args env args args' e\n  | BScond cond args mv args' s1 s2 =>\n      assertion (can_undef (destroyed_by_cond cond) e);\n      do e1 <- add_equations args args' e;\n      track_moves env mv e1\n  | BSjumptable arg mv arg' tbl =>\n      assertion (can_undef destroyed_by_jumptable e);\n      track_moves env mv (add_equation (Eq Full arg (R arg')) e)\n  | BSreturn None mv =>\n      track_moves env mv empty_eqs\n  | BSreturn (Some arg) mv =>\n      let arg' := map R (loc_result (RTL.fn_sig f)) in\n      do e1 <- add_equations_res arg (sig_res (RTL.fn_sig f)) arg' empty_eqs;\n      track_moves env mv e1\n  end.\n\n(** The main transfer function for the dataflow analysis.  Like [transfer_aux],\n  it infers the equations that must hold \"before\" as a function of the\n  equations that must hold \"after\".  It also handles error propagation\n  and reporting. *)\n\nDefinition transfer (f: RTL.function) (env: regenv) (shapes: PTree.t block_shape)\n                    (pc: node) (after: res eqs) : res eqs :=\n  match after with\n  | Error _ => after\n  | OK e =>\n      match shapes!pc with\n      | None => Error(MSG \"At PC \" :: POS pc :: MSG \": unmatched block\" :: nil)\n      | Some shape =>\n          match transfer_aux f env shape e with\n          | None => Error(MSG \"At PC \" :: POS pc :: MSG \": invalid register allocation\" :: nil)\n          | Some e' => OK e'\n          end\n      end\n  end.\n\n(** The semilattice for dataflow analysis.  Operates on analysis results\n  of type [res eqs], that is, either a set of equations or an error\n  message.  Errors correspond to [Top].  Sets of equations are ordered\n  by inclusion. *)\n\nModule LEq <: SEMILATTICE.\n\n  Definition t := res eqs.\n\n  Definition eq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Equal a b\n    | Error _, Error _ => True\n    | _, _ => False\n    end.\n\n  Lemma eq_refl: forall x, eq x x.\n  Proof.\n    intros; destruct x; simpl; auto. red; tauto. \n  Qed.\n\n  Lemma eq_sym: forall x y, eq x y -> eq y x.\n  Proof.\n    unfold eq; intros; destruct x; destruct y; auto. \n    red in H; red; intros. rewrite H; tauto.\n  Qed. \n\n  Lemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    unfold eq; intros. destruct x; destruct y; try contradiction; destruct z; auto.\n    red in H; red in H0; red; intros. rewrite H. auto. \n  Qed.\n\n  Definition beq (x y: t) := \n    match x, y with\n    | OK a, OK b => EqSet.equal a b\n    | Error _, Error _ => true\n    | _, _ => false\n    end.\n\n  Lemma beq_correct: forall x y, beq x y = true -> eq x y.\n  Proof.\n    unfold beq, eq; intros. destruct x; destruct y. \n    apply EqSet.equal_2. auto.\n    discriminate.\n    discriminate.\n    auto.\n  Qed.\n\n  Definition ge (x y: t) := \n    match x, y with\n    | OK a, OK b => EqSet.Subset b a\n    | Error _, _ => True\n    | _, Error _ => False\n    end.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge, EqSet.Equal, EqSet.Subset; intros. \n    destruct x; destruct y; auto. intros; rewrite H; auto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge, EqSet.Subset; intros.\n    destruct x; auto; destruct y; try contradiction.\n    destruct z; eauto. \n  Qed.\n\n  Definition bot: t := OK empty_eqs.\n \n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot, EqSet.Subset; simpl; intros.\n    destruct x; auto. intros. elim (EqSet.empty_1 H).\n  Qed.\n\n  Program Definition lub (x y: t) : t :=\n    match x, y return _ with\n    | OK a, OK b =>\n        OK (mkeqs (EqSet.union (eqs1 a) (eqs1 b))\n                  (EqSet2.union (eqs2 a) (eqs2 b)) _)\n    | OK _, Error _ => y\n    | Error _, _ => x\n    end.\n  Next Obligation.\n    split; intros. \n    apply EqSet2.union_1 in H. destruct H; rewrite eqs_same in H. \n    apply EqSet.union_2; auto. apply EqSet.union_3; auto.\n    apply EqSet.union_1 in H. destruct H; rewrite <- eqs_same in H. \n    apply EqSet2.union_2; auto. apply EqSet2.union_3; auto.\n  Qed.\n\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub, ge, EqSet.Subset; intros. \n    destruct x; destruct y; auto. \n    intros; apply EqSet.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, EqSet.Subset; intros. \n    destruct x; destruct y; auto. \n    intros; apply EqSet.union_3; auto. \n  Qed.\n\nEnd LEq.\n\n(** The backward dataflow solver is an instantiation of Kildall's algorithm. *)\n\nModule DS := Backward_Dataflow_Solver(LEq)(NodeSetBackward).\n\n(** The control-flow graph that the solver operates on is the CFG of\n  block shapes built by the structural check phase.  Here is its notion\n  of successors. *)\n\nDefinition successors_block_shape (bsh: block_shape) : list node :=\n  match bsh with\n  | BSnop mv s => s :: nil\n  | BSmove src dst mv s => s :: nil\n  | BSmakelong src1 src2 dst mv s => s :: nil\n  | BSlowlong src dst mv s => s :: nil\n  | BShighlong src dst mv s => s :: nil\n  | BSop op args res mv1 args' res' mv2 s => s :: nil\n  | BSopdead op args res mv s => s :: nil\n  | BSload chunk addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s => s :: nil\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s => s :: nil\n  | BSloaddead chunk addr args dst mv s => s :: nil\n  | BSstore chunk addr args src mv1 args' src' s => s :: nil\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s => s :: nil\n  | BScall sg ros args res mv1 ros' mv2 s => s :: nil\n  | BStailcall sg ros args mv1 ros' => nil\n  | BSbuiltin ef args res mv1 args' res' mv2 s => s :: nil\n  | BSannot ef args args' s => s :: nil\n  | BScond cond args mv args' s1 s2 => s1 :: s2 :: nil\n  | BSjumptable arg mv arg' tbl => tbl\n  | BSreturn optarg mv => nil\n  end.\n\nDefinition analyze (f: RTL.function) (env: regenv) (bsh: PTree.t block_shape) :=\n  DS.fixpoint_allnodes bsh successors_block_shape (transfer f env bsh).\n\n(** * Validating and translating functions and programs *)\n\n(** Checking equations at function entry point.  The RTL function receives\n  its arguments in the list [rparams] of pseudoregisters.  The LTL function\n  receives them in the list [lparams] of locations dictated by the\n  calling conventions, with arguments of type [Tlong] being split in\n  two 32-bit halves.  We check that the equations [e] that must hold\n  at the beginning of the functions are compatible with these calling\n  conventions, in the sense that all equations involving a pseudoreg\n  [r] from [rparams] is of the form [r = l [Full]] or [r = l [Low]]\n  or [r = l [High]], where [l] is the corresponding element of [lparams].\n\n  Note that [e] can contain additional equations [r' = l [kind]]\n  involving pseudoregs [r'] not in [rparams]: these equations are\n  automatically satisfied since the initial value of [r'] is [Vundef]. *)\n\nFunction compat_entry (rparams: list reg) (tys: list typ) (lparams: list loc) (e: eqs)\n                      {struct rparams} : bool :=\n  match rparams, tys, lparams with\n  | nil, nil, nil => true\n  | r1 :: rl, Tlong :: tyl, l1 :: l2 :: ll =>\n      compat_left2 r1 l1 l2 e && compat_entry rl tyl ll e\n  | r1 :: rl, (Tint|Tfloat|Tsingle) :: tyl, l1 :: ll =>\n      compat_left r1 l1 e && compat_entry rl tyl ll e\n  | _, _, _ => false\n  end.\n\n(** Checking the satisfiability of equations inferred at function entry\n  point.  We also check that the RTL and LTL functions agree in signature\n  and stack size. *)\n\nDefinition check_entrypoints_aux (rtl: RTL.function) (ltl: LTL.function)\n                                 (env: regenv) (e1: eqs) : option unit :=\n  do mv <- pair_entrypoints rtl ltl;\n  do e2 <- track_moves env mv e1;\n  assertion (compat_entry (RTL.fn_params rtl)\n                          (sig_args (RTL.fn_sig rtl))\n                          (loc_parameters (RTL.fn_sig rtl)) e2);\n  assertion (can_undef destroyed_at_function_entry e2);\n  assertion (zeq (RTL.fn_stacksize rtl) (LTL.fn_stacksize ltl));\n  assertion (signature_eq (RTL.fn_sig rtl) (LTL.fn_sig ltl));\n  Some tt.\n\nLocal Close Scope option_monad_scope.\nLocal Open Scope error_monad_scope.\n\nDefinition check_entrypoints (rtl: RTL.function) (ltl: LTL.function)\n                             (env: regenv) (bsh: PTree.t block_shape)\n                             (a: PMap.t LEq.t): res unit :=\n  do e1 <- transfer rtl env bsh (RTL.fn_entrypoint rtl) a!!(RTL.fn_entrypoint rtl);\n  match check_entrypoints_aux rtl ltl env e1 with\n  | None => Error (msg \"invalid register allocation at entry point\")\n  | Some _ => OK tt\n  end.\n\n(** Putting it all together, this is the validation function for\n  a source RTL function and an LTL function generated by the external\n  register allocator. *)\n\nDefinition check_function (rtl: RTL.function) (ltl: LTL.function) (env: regenv): res unit :=\n  let bsh := pair_codes rtl ltl in\n  match analyze rtl env bsh with\n  | None => Error (msg \"allocation analysis diverges\")\n  | Some a => check_entrypoints rtl ltl env bsh a\n  end.\n\n(** [regalloc] is the external register allocator.  It is written in OCaml\n  in file [backend/Regalloc.ml]. *)\n\nParameter regalloc: RTL.function -> res LTL.function.\n\n(** Register allocation followed by validation. *)\n\nDefinition transf_function (f: RTL.function) : res LTL.function :=\n  match type_function f with\n  | Error m => Error m\n  | OK env =>\n      match regalloc f with\n      | Error m => Error m\n      | OK tf => do x <- check_function f tf env; OK tf\n      end\n  end.\n\nDefinition transf_fundef (fd: RTL.fundef) : res LTL.fundef :=\n  AST.transf_partial_fundef transf_function fd.\n\nDefinition transf_program (p: RTL.program) : res LTL.program :=\n  transform_partial_program transf_fundef p.\n\n", "meta": {"author": "k-qy", "repo": "thesis", "sha": "51bf3bac68af9a70ab3bfbbafa7bb53ef4d83877", "save_path": "github-repos/coq/k-qy-thesis", "path": "github-repos/coq/k-qy-thesis/thesis-51bf3bac68af9a70ab3bfbbafa7bb53ef4d83877/func_spec/CompCert-2.5/backend/Allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17354904161970952}}
{"text": "Require Import Init.Datatypes Logic.FunctionalExtensionality.\nRequire Import Lists.List.\nRequire Import Functor Applicative Foldable Monoid Monad Comonad.\nRequire Import Identity Composition.\nRequire Import Coq.Arith.PeanoNat.\n\nSet Implicit Arguments.\n\n\nModule TypeClasses.\n\n  Import ListNotations Functor Applicative Monoid Monad Comonad Foldable. \n\n  Section Definitions.\n\n    \n  End Definitions.\n\n  Section Examples.\n\n\n  End Examples.\n  \n  (* TODO: add compose *)\n\n  (*  (* TOOD: comment *)\n  Class Contravariant (F: Type -> Type) :=\n    { cmap: forall {A B}, (A -> B) -> (F B -> F A)\n      ; _: True\n    }.\n\n  (* Invariant Functor *)\n  Class Invariant (F: Type -> Type) :=\n    { imap: forall {A B}, (B -> A) -> (A -> B) -> (F A -> F B)\n      ; _: True\n    }.\n\n  (* Profunctor *) (* Instance: (->) *)\n  Class Profunctor (F: Type -> Type -> Type) :=\n    { dimap: forall {A B C D}, (A -> B) -> (C -> D) -> (F B C) -> (F A D)\n      ; _: True\n    }.\n   *)\n  \n(*  Section Transformers.\n\n    Class MonadTrans (M: Type -> Type) (T: _) :=\n      { monadM :> Monad M\n        ; monadTM :> Monad (T M)\n        ; lift: forall {A}, M A -> (T M) A\n        ; _: (lift (.) unit) [=] unit\n        ; _: True\n      }.\n    \n  End Transformers. *)\n  \n\nEnd TypeClasses.", "meta": {"author": "GKerfImf", "repo": "Learning-Coq", "sha": "c1590a3f3c31440d0cd0936be0667ade3f64f268", "save_path": "github-repos/coq/GKerfImf-Learning-Coq", "path": "github-repos/coq/GKerfImf-Learning-Coq/Learning-Coq-c1590a3f3c31440d0cd0936be0667ade3f64f268/TypeClasses/TypeClasses.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.17346906826418299}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom Michocoq Require Import semantics util macros.\nImport syntax comparable error.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule ccgen(C : ContractContext).\nModule semantics := Semantics C. Import semantics.\nRequire Import String.\nOpen Scope string_scope.\n\nDefinition reconstr_op {self_type A B}\n           (op: @opcode self_type A B) : @opcode None A B :=\n  match op with\n  | APPLY _ _ _ _ b => @APPLY _ _ _ _ _ b\n  | DUP _ _ => DUP\n  | SWAP _ _ _ => SWAP\n  | UNIT _ => UNIT\n  | EQ _ => EQ\n  | NEQ _ => NEQ\n  | LT _ => LT\n  | GT _ => GT\n  | LE _ => LE\n  | GE _ => GE\n  | OR _ s _ => @OR _ _ s _\n  | AND _ _ s _ => @AND _ _ _ s _\n  | XOR _ s _ => @XOR _ _ s _\n  | NOT _ s _ => @NOT _ _ s _\n  | NEG _ s _ => @NEG _ _ s _\n  | ABS _ => ABS\n  | ISNAT _ => ISNAT\n  | INT _ => INT\n  | ADD _ _ _ _ => ADD\n  | SUB _ _ _ _ => SUB\n  | MUL _ _ _ _ => MUL\n  | EDIV _ _ _ _ => EDIV\n  | LSL _ => LSL\n  | LSR _ => LSR\n  | COMPARE _ _ => COMPARE\n  | CONCAT _ i _ => @CONCAT _ _ i _\n  | CONCAT_list _ i _ => @CONCAT_list _ _ i _\n  | SIZE _ i _ => @SIZE _ _ i _\n  | SLICE _ i _ => @SLICE _ _ i _\n  | PAIR _ _ _ => PAIR\n  | CAR _ _ _ => CAR\n  | CDR _ _ _ => CDR\n  | EMPTY_SET elt _ => EMPTY_SET elt\n  | MEM _ _ i _ => @MEM _ _ _ i _\n  | UPDATE _ _ _ i _ => @UPDATE _ _ _ _ i _\n  | EMPTY_MAP x y _ => EMPTY_MAP x y\n  | EMPTY_BIG_MAP x y _ => EMPTY_BIG_MAP x y\n  | GET _ i _ _ => @GET _ _ i _ _\n  | SOME _ _ => SOME\n  | NONE a _ => NONE a\n  | LEFT _ b _ => LEFT b\n  | RIGHT a _ _ => RIGHT a\n  | CONS _ _ => CONS\n  | NIL a _ => NIL a\n  | TRANSFER_TOKENS _ _ => TRANSFER_TOKENS\n  | SET_DELEGATE _ => SET_DELEGATE\n  | BALANCE _ => BALANCE\n  | ADDRESS _ _ => ADDRESS\n  | CONTRACT _ annot_opt p => CONTRACT annot_opt p\n  | SOURCE _ => SOURCE\n  | SENDER _ => SENDER\n  | AMOUNT _ => AMOUNT\n  | IMPLICIT_ACCOUNT _ => IMPLICIT_ACCOUNT\n  | NOW _ => NOW\n  | PACK _ _ => PACK\n  | UNPACK a _ => UNPACK a\n  | HASH_KEY _ => HASH_KEY\n  | BLAKE2B _ => BLAKE2B\n  | SHA256 _ => SHA256\n  | SHA512 _ => SHA512\n  | CHECK_SIGNATURE _ => CHECK_SIGNATURE\n  | DIG n _ _ _ Sn => DIG n Sn\n  | DUG n _ _ _ Sn => DUG n Sn\n  | DROP n _ _ An => DROP n An\n  | CHAIN_ID _ => CHAIN_ID\n  end.\n\nFixpoint reconstr {self_type a b tff} (ins: instruction_seq self_type tff a b) :\n  Datatypes.option (instruction_seq None tff a b) :=\n  match ins with\n  | NOOP _ _ => Some NOOP\n  | Tail_fail _ _ _ x => omap Tail_fail (reconstr1 x)\n  | SEQ _ _ _ _ _ x y =>\n    obind (fun a => omap a (reconstr y)) (omap SEQ (reconstr1 x))\n  end\nwith reconstr1 {self_type a b tff} (ins: instruction self_type tff a b) :\n  Datatypes.option (instruction None tff a b) :=\n  match ins with\n  | Instruction_seq _ _ _ _ x =>\n    omap Instruction_seq (reconstr x)\n  | FAILWITH _ _ _ _ => Some FAILWITH\n  | IF_ _ _ _ _ _ _ _ _ i x y =>\n    obind (fun a => omap a (reconstr y)) (omap (IF_ i) (reconstr x))\n  | LOOP_ _ _ _ _ _ _ i x => omap (LOOP_ i) (reconstr x)\n  | PUSH t x _ _ => Some (PUSH t x)\n  | LAMBDA x y _ _ _ z => omap (LAMBDA x y) (reconstr z)\n  | ITER _ _ _ _ _ x => omap ITER (reconstr x)\n  | MAP _ _ _ _ _ x => omap MAP (reconstr x)\n  | CREATE_CONTRACT _ _ _ g p an x => Some (CREATE_CONTRACT g p an x)\n  | SELF _ _ _ annot_opt H => None\n  | EXEC _ _ _ _ => Some EXEC\n  | DIP n _ _ _ _ An x => omap (DIP n An) (reconstr x)\n  | Instruction_opcode _ _ _ op => Some (Instruction_opcode (reconstr_op op))\n  end.\n\nOpen Scope michelson_scope.\n\nDefinition genprog {parameter_ty storage_ty}\n           (prog: full_contract false parameter_ty None storage_ty)\n           (validation_snippet: instruction_seq None false\n                                                (pair bytes mutez ::: [::])\n                                                (pair bytes mutez ::: [::]))\n  : Datatypes.option (instruction_seq None false (pair bytes mutez ::: [::])\n    (list (pair (pair syntax_type.string (lambda (pair bytes bytes)\n    (pair (list operation) bytes))) (pair bytes mutez)) ::: [::])) :=\n  match reconstr prog with\n  | Some prog0 =>\n    Some (validation_snippet;;;\n         {DIP1 {NIL _};\n         LAMBDA _ _\n                {\n                  UNPAIR; UNPACK parameter_ty;\n                  IF_NONE {PUSH _ (Comparable_constant syntax_type.string \"unpack param\"); FAILWITH}\n                          {\n                            SWAP; UNPACK storage_ty;\n                            IF_NONE {PUSH _ (Comparable_constant syntax_type.string \"unpack storage\"); FAILWITH}\n                                    (SWAP;; PAIR;; prog0;;;\n                                     {UNPAIR; DIP1 {PACK}; PAIR})\n                          }\n                };\n         PUSH _ (Comparable_constant syntax_type.string \"main\"); PAIR; PAIR; CONS})\n  | None => None\n  end.\n\nDefinition initprog :\n  instruction_seq None false (pair bytes mutez ::: [::])\n    (lambda (map syntax_type.string address)\n       (list (pair syntax_type.string bytes)) ::: [::]) :=\n  {DROP1; LAMBDA _ _ {DROP1; NIL (pair _ bytes)}}.\nEnd ccgen.\n", "meta": {"author": "kxcinc", "repo": "tsca-formaldev", "sha": "21e4af06aeab3208efbfe39c71793255d0bf6f44", "save_path": "github-repos/coq/kxcinc-tsca-formaldev", "path": "github-repos/coq/kxcinc-tsca-formaldev/tsca-formaldev-21e4af06aeab3208efbfe39c71793255d0bf6f44/ccgen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.17345965265230104}}
{"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 SeqLib.\nRequire Import Sequential.\nRequire Import OracleFacts.\n\nRequire Import SimAux.\nRequire Import SeqAux.\nRequire Import SequentialBehavior.\n\nSet Implicit Arguments.\n\n\nSection ADEQUACY.\n  Variable lang_src lang_tgt: language.\n  Variable state_step:\n    Perms.t -> MachineEvent.t -> SeqState.t lang_src -> SeqState.t lang_src -> Prop.\n\n  Hypothesis state_step_subset: state_step <4= (@SeqState.na_step _).\n\n  Hypothesis state_step_determ:\n    forall p st e0 e1 st0 st1\n           (DETERM: deterministic _ (SeqState.state st))\n           (STEP0: state_step p e0 st st0)\n           (STEP1: state_step p e1 st st1),\n      e0 = e1 /\\ st0 = st1.\n\n  Lemma refine_mon\n        (st_tgt: lang_tgt.(Language.state)) (st_src: lang_src.(Language.state))\n        (REFINE: SeqBehavior.refine _ _ st_tgt st_src)\n        (TOP: forall p m o (WF: Oracle.wf o),\n            SeqBehavior.behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_src m) p o)\n            <1=\n            SeqBehavior.behavior state_step (SeqThread.mk (SeqState.mk _ st_src m) p o)):\n    forall p m o (WF: Oracle.wf o),\n      SeqTrace.incl\n        (SeqBehavior.behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_tgt m) p o))\n        (SeqBehavior.behavior state_step (SeqThread.mk (SeqState.mk _ st_src m) p o)).\n  Proof.\n    ii. specialize (TOP p m o WF).\n    exploit REFINE; eauto. i. des. eauto.\n  Qed.\n\n\n  (** lemmas on event and event step *)\n\n  Lemma le_is_accessing\n        e1 e2\n        (LE: ProgramEvent.le e1 e2):\n    is_accessing e1 <-> is_accessing e2.\n  Proof.\n    destruct e1, e2; ss; inv LE; des; subst; ss.\n  Qed.\n\n  Lemma le_is_acquire\n        e1 e2\n        (LE: ProgramEvent.le e1 e2):\n    is_acquire e1 <-> is_acquire e2.\n  Proof.\n    destruct e1, e2; ss; inv LE; des; subst; ss.\n  Qed.\n\n  Lemma le_is_release\n        e1 e2\n        (LE: ProgramEvent.le e1 e2):\n    is_release e1 <-> is_release e2.\n  Proof.\n    destruct e1, e2; ss; inv LE; des; subst; ss.\n  Qed.\n\n  Lemma le_is_accessing_loc\n        e1 e2\n        (LE: ProgramEvent.le e1 e2):\n    (exists loc v1 v2,\n        is_accessing e1 = Some (loc, v1) /\\ is_accessing e2 = Some (loc, v2)) \\/\n    (is_accessing e1 = None /\\ is_accessing e2 = None).\n  Proof.\n    destruct e1, e2; des; subst; try inv LE; ss; eauto; left; esplits; eauto.\n  Qed.\n\n  Lemma similar_is_accessing_loc\n        e1 e2\n        (SIMILAR: similar e1 e2):\n    (exists loc v1 v2,\n        is_accessing e1 = Some (loc, v1) /\\ is_accessing e2 = Some (loc, v2)) \\/\n    (is_accessing e1 = None /\\ is_accessing e2 = None).\n  Proof.\n    destruct e1, e2; des; subst; try inv SIMILAR; ss; eauto; left; esplits; eauto.\n  Qed.\n\n  Lemma wsimilar_is_accessing_loc\n        e1 e2\n        (WSIMILAR: wsimilar e1 e2):\n    (exists loc v1 v2,\n        is_accessing e1 = Some (loc, v1) /\\ is_accessing e2 = Some (loc, v2)) \\/\n    (is_accessing e1 = None /\\ is_accessing e2 = None).\n  Proof.\n    destruct e1, e2; des; subst; try inv WSIMILAR; ss; eauto; left; esplits; eauto.\n  Qed.\n\n  Lemma wsimilar_is_acquire\n        e1 e2\n        (WSIMILAR: wsimilar e1 e2):\n    is_acquire e1 <-> is_acquire e2.\n  Proof.\n    destruct e1, e2; des; subst; try inv WSIMILAR; ss. des. subst. ss.\n  Qed.\n\n  Lemma le_wf_output\n        e1 e2 o\n        (LE: ProgramEvent.le e1 e2):\n    Oracle.wf_output e1 o <-> Oracle.wf_output e2 o.\n  Proof.\n    unfold Oracle.wf_output. unnw.\n    erewrite le_is_accessing, le_is_acquire, le_is_release; eauto.\n  Qed.\n\n  Lemma event_step_update_exists\n        e (o: option Perm.t) p1 m1\n        (WF_OUTPUT: o <-> is_accessing e):\n    exists i,\n      (<<WF: forall loc v_new,\n          ((exists v_old f_old, i = Some (loc, v_old, f_old, v_new)) <->\n           (is_accessing e = Some (loc, v_new)))>>) /\\\n      exists p2 m2, (<<STEP: SeqEvent.step_update i o p1 m1 p2 m2>>).\n  Proof.\n    exists (match is_accessing e with\n       | Some (loc, v_new) =>\n         Some (loc, m1.(SeqMemory.value_map) loc, m1.(SeqMemory.flags) loc, v_new)\n       | None => None\n       end).\n    split.\n    { split; i; des_ifs; des; ss; eauto. inv H. ss. }\n    { des_ifs; destruct o; try by intuition.\n      - esplits. econs; eauto. econs.\n      - esplits. econs.\n    }\n  Qed.\n\n  Lemma event_step_acquire_exists\n        e (o: option (Perms.t * ValueMap.t)) p1 m1\n        (WF_OUTPUT: o <-> is_acquire e):\n    exists (i: option Flags.t),\n      (<<WF: i <-> is_acquire e>>) /\\\n      exists p2 m2, (<<STEP: SeqEvent.step_acquire i o p1 m1 p2 m2>>).\n  Proof.\n    exists (if is_acquire e then Some m1.(SeqMemory.flags) else None).\n    split.\n    { split; i; des_ifs; des; ss; eauto. }\n    { des_ifs; destruct o as [[]|]; try by intuition.\n      - esplits. econs; eauto. econs.\n      - esplits. econs.\n    }\n  Qed.\n\n  Lemma event_step_release_exists\n        e (o: option Perms.t) p1 m1\n        (WF_OUTPUT: o <-> is_release e):\n    exists (i: option (ValueMap.t * Flags.t)),\n      (<<WF: i <-> is_release e>>) /\\\n      exists p2 m2, (<<STEP: SeqEvent.step_release i o p1 m1 p2 m2>>).\n  Proof.\n    exists (if is_release e then Some (m1.(SeqMemory.value_map), m1.(SeqMemory.flags)) else None).\n    split.\n    { split; i; des_ifs; des; ss; eauto. }\n    { des_ifs; destruct o; try by intuition.\n      - esplits. econs; eauto. econs.\n      - esplits. econs.\n    }\n  Qed.\n\n  Lemma event_step_exists\n        e o p1 m1\n        (WF_OUTPUT: Oracle.wf_output e o):\n    exists i,\n      (<<WF: SeqEvent.wf_input e i>>) /\\\n      exists p2 m2,\n        (<<STEP: SeqEvent.step i o p1 m1 p2 m2>>).\n  Proof.\n    unfold Oracle.wf_output in *. destruct o. ss. splitsH.\n    exploit (event_step_update_exists e out_access p1 m1); ss. i. des.\n    exploit (event_step_acquire_exists e out_acquire p2 m2); ss. i. des.\n    exploit (event_step_release_exists e out_release p0 m0); ss. i. des.\n    exists (SeqEvent.mk_input i i0 i1). split.\n    - unfold SeqEvent.wf_input. splits; ss.\n    - esplits. econs; eauto.\n  Qed.\n\n\n  (** definitions and lemmas on match_trace *)\n\n  Variant min_match (I: Type) (imatch: forall (d1 d2: Flags.t) (i_src i_tgt: I), Prop)\n          (d1 d2: Flags.t) (i_src i_tgt: I): Prop :=\n  | min_match_intro\n      (MATCH: imatch d1 d2 i_src i_tgt)\n      (MIN: forall d (MATCH: imatch d1 d i_src i_tgt), Flags.le d2 d)\n  .\n\n  Lemma min_access_match_exists\n        d1 d2 i_src i_tgt\n        (MATCH: SeqEvent.in_access_match d1 d2 i_src i_tgt):\n    exists d_min, min_match SeqEvent.in_access_match d1 d_min i_src i_tgt.\n  Proof.\n    i. inv MATCH.\n    { exists d1. econs; [econs 1; refl|]. i. inv MATCH. ss. }\n    exists (fun loc => if Loc.eq_dec loc l then false else (d1 loc)).\n    econs.\n    - econs; eauto. i. condtac; ss. refl.\n    - i. inv MATCH. ii. condtac; ss. eauto.\n  Qed.\n\n  Lemma min_acquire_match_exists\n        d1 d2 i_src i_tgt\n        (MATCH: SeqEvent.in_acquire_match d1 d2 i_src i_tgt):\n    exists d_min, min_match SeqEvent.in_acquire_match d1 d_min i_src i_tgt.\n  Proof.\n    inv MATCH.\n    { exists d1. econs; [econs 1; refl|]. i. inv MATCH. ss. }\n    exists Flags.bot. econs; ss. econs; eauto.\n  Qed.\n\n  Lemma min_release_match_exists\n        d1 d2 i_src i_tgt\n        (MATCH: SeqEvent.in_release_match d1 d2 i_src i_tgt):\n    exists d_min, min_match SeqEvent.in_release_match d1 d_min i_src i_tgt.\n  Proof.\n    inv MATCH.\n    { exists d1. econs; [econs 1; refl|]. i. inv MATCH. ss. }\n    exists (fun loc => if Const.le (v_tgt loc) (v_src loc)\n               then andb (orb (f_tgt loc) (d1 loc)) (negb (f_src loc))\n               else true).\n    econs; ii.\n    - econs; ii; des_ifs.\n      unfold Flags.join. condtac; ss.\n      + destruct (f_tgt loc), (d1 loc), (f_src loc); ss.\n      + destruct (f_tgt loc), (d1 loc), (f_src loc); ss.\n    - inv MATCH. condtac; ss.\n      + specialize (DEFERRED0 loc). unfold Flags.join in *.\n        destruct (f_tgt loc), (d1 loc), (f_src loc), (d loc); ss.\n      + specialize (VAL0 loc). destruct (d loc); ss.\n        exploit VAL0; eauto. i. congr.\n  Qed.\n\n  Lemma min_match_le_min\n        I imatch d1 d2 i_src i_tgt\n        (MIN: @min_match I imatch d1 d2 i_src i_tgt)\n        (MON: forall d1 d2 d1' d2' i_src i_tgt\n                (MATCH: imatch d1 d2 i_src i_tgt)\n                (LE1: Flags.le d1' d1)\n                (LE2: Flags.le d2 d2'),\n            imatch d1' d2' i_src i_tgt)\n        d1' d2'\n        (MATCH: imatch d1' d2' i_src i_tgt)\n        (LE: Flags.le d1 d1'):\n    Flags.le d2 d2'.\n  Proof.\n    exploit MON; try exact MATCH; try exact LE; try refl. i.\n    inv MIN. eapply MIN0; eauto.\n  Qed.\n\n  Lemma min_input_match_exists\n        d1 d2 i_src i_tgt\n        (MATCH: SeqEvent.input_match d1 d2 i_src i_tgt):\n    exists d_min, (<<MIN: min_match SeqEvent.input_match d1 d_min i_src i_tgt>>).\n  Proof.\n    inv MATCH.\n    exploit min_access_match_exists; eauto. intro MIN_ACCESS. des.\n    hexploit min_match_le_min; try exact MIN_ACCESS; try exact ACCESS;\n      eauto using SeqEvent.in_access_match_mon; try refl. i.\n    exploit SeqEvent.in_acquire_match_mon; try exact ACQUIRE; try exact H; try refl. i.\n    exploit min_acquire_match_exists; try exact x0. intro MIN_ACQUIRE. des.\n    hexploit min_match_le_min; try exact MIN_ACQUIRE; try exact ACQUIRE;\n      eauto using SeqEvent.in_acquire_match_mon. i.\n    exploit SeqEvent.in_release_match_mon; try exact RELEASE; try exact H0; try refl. i.\n    exploit min_release_match_exists; try exact x1. intro MIN_RELEASE. des.\n    clear d0 d2 d3 ACCESS ACQUIRE RELEASE H x0 H0 x1.\n    exists d_min1. econs.\n    { econs; [apply MIN_ACCESS|apply MIN_ACQUIRE|apply MIN_RELEASE]. }\n    i. inv MATCH.\n    hexploit min_match_le_min; try exact MIN_ACCESS; try exact ACCESS;\n      eauto using SeqEvent.in_access_match_mon; try refl. i.\n    hexploit min_match_le_min; try exact MIN_ACQUIRE; try exact ACQUIRE;\n      eauto using SeqEvent.in_acquire_match_mon. i.\n    hexploit min_match_le_min; try exact MIN_RELEASE; try exact RELEASE;\n      eauto using SeqEvent.in_release_match_mon.\n  Qed.\n\n  Inductive match_trace (imatch: forall (d1 d2: Flags.t) (i_src i_tgt: SeqEvent.input), Prop):\n    forall (d_init: Flags.t) (d: Flags.t) (tr_src tr_tgt: list (ProgramEvent.t * SeqEvent.input * Oracle.output)), Prop :=\n  | match_trace_nil\n      d:\n      match_trace imatch d d [] []\n  | match_trace_snoc\n      d_init d1 tr_src tr_tgt d2\n      e_src i_src o_src\n      e_tgt i_tgt o_tgt\n      (MATCH: match_trace imatch d_init d1 tr_src tr_tgt)\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (INPUT: imatch d1 d2 i_src i_tgt)\n      (OUTPUT: o_src = o_tgt):\n      match_trace imatch d_init d2 (tr_src ++ [(e_src, i_src, o_src)]) (tr_tgt ++ [(e_tgt, i_tgt, o_tgt)])\n  .\n\n  Variant simple_match_event: forall e_src e_tgt, Prop :=\n  | simple_match_event_intro\n      e_src i_src (o: Oracle.output)\n      e_tgt i_tgt\n      (EVENT: ProgramEvent.le e_tgt e_src)\n      (INPUT: oracle_similar_input (SeqEvent.get_oracle_input i_src) (SeqEvent.get_oracle_input i_tgt)):\n      simple_match_event (e_src, i_src, o) (e_tgt, i_tgt, o)\n  .\n\n  Global Program Instance simple_match_event_PreOrder: PreOrder simple_match_event.\n  Next Obligation.\n    ii. destruct x as [[]]. econs; refl.\n  Qed.\n  Next Obligation.\n    ii. inv H. inv H0. econs; etrans; eauto.\n  Qed.\n\n  Lemma match_trace_simple_match\n        d_init d tr_src tr_tgt\n        (TRACE: match_trace (min_match SeqEvent.input_match) d_init d tr_src tr_tgt):\n    Forall2 simple_match_event tr_src tr_tgt.\n  Proof.\n    induction TRACE; eauto. subst.\n    apply Forall2_app; ss. econs; ss. econs; eauto.\n    eapply input_match_similar. eapply INPUT.\n  Qed.\n\n  Lemma simple_match_follows1\n        orc0 tr1 tr2 orc\n        (MATCH: Forall2 simple_match_event tr1 tr2)\n        (FOLLOWS: oracle_follows_trace orc0 tr1 orc):\n    oracle_follows_trace orc0 tr2 orc.\n  Proof.\n    revert orc FOLLOWS. induction MATCH; i; eauto. inv H.\n    inv FOLLOWS. econs; i.\n    - exploit SOUND; try exact STEP. intros x. des. split.\n      + destruct e_src, e_tgt; ss; inv EVENT; des; subst; ss.\n      + i. exploit x0; try by (etrans; eauto). i. des. splits; auto.\n    - eapply COMPLETE; eauto; try by etrans; eauto.\n      destruct e_src, e_tgt; ss; inv EVENT; des; subst; ss.\n  Qed.\n\n  Lemma simple_match_follows2\n        orc0 tr1 tr2 orc\n        (MATCH: Forall2 simple_match_event tr1 tr2)\n        (FOLLOWS: oracle_follows_trace orc0 tr2 orc):\n    oracle_follows_trace orc0 tr1 orc.\n  Proof.\n    revert orc FOLLOWS. induction MATCH; i; eauto. inv H.\n    inv FOLLOWS. econs; i.\n    - exploit SOUND; try exact STEP. intros x. des. split.\n      + destruct e_src, e_tgt; ss; inv EVENT; des; subst; ss.\n      + i. exploit x0.\n        { etrans; eauto. symmetry. ss. }\n        i. des. splits; auto.\n    - eapply COMPLETE; eauto.\n      + destruct e_src, e_tgt; ss; inv EVENT; des; subst; ss.\n      + etrans; eauto. symmetry. ss.\n  Qed.\n\n  Lemma match_trace_cons\n        imatch d1 d2 tr_src tr_tgt\n        d0 e_src i_src o_src e_tgt i_tgt o_tgt\n        (TRACE: match_trace imatch d1 d2 tr_src tr_tgt)\n        (EVENT: ProgramEvent.le e_tgt e_src)\n        (INPUT: imatch d0 d1 i_src i_tgt)\n        (OUTPUT: o_src = o_tgt):\n    match_trace imatch d0 d2 ((e_src, i_src, o_src) :: tr_src) ((e_tgt, i_tgt, o_tgt) :: tr_tgt).\n  Proof.\n    induction TRACE.\n    { replace [(e_src, i_src, o_src)] with ([] ++ [(e_src, i_src, o_src)]) by ss.\n      replace [(e_tgt, i_tgt, o_tgt)] with ([] ++ [(e_tgt, i_tgt, o_tgt)]) by ss.\n      econs 2; eauto. econs.\n    }\n    exploit IHTRACE; eauto. i.\n    replace ((e_src, i_src, o_src) :: tr_src ++ [(e_src0, i_src0, o_src0)]) with\n      (((e_src, i_src, o_src) :: tr_src) ++ [(e_src0, i_src0, o_src0)]) by ss.\n    replace ((e_tgt, i_tgt, o_tgt) :: tr_tgt ++ [(e_tgt0, i_tgt0, o_tgt0)]) with\n      (((e_tgt, i_tgt, o_tgt) :: tr_tgt) ++ [(e_tgt0, i_tgt0, o_tgt0)]) by ss.\n    econs 2; eauto.\n  Qed.\n\n  Lemma trace_le_terminal_match\n        d_init tr_src v_src f_src tr_tgt v_tgt f_tgt\n        (LE: SeqTrace.le d_init\n                         (tr_tgt, SeqTrace.term v_tgt f_tgt)\n                         (tr_src, SeqTrace.term v_src f_src)):\n    exists d,\n      (<<MATCH: match_trace SeqEvent.input_match d_init d tr_src tr_tgt>>) /\\\n      (<<FLAGS: Flags.le (Flags.join d f_tgt) (f_src)>>).\n  Proof.\n    remember (tr_src, SeqTrace.term v_src f_src) as r_src.\n    remember (tr_tgt, SeqTrace.term v_tgt f_tgt) as r_tgt.\n    revert tr_src v_src f_src tr_tgt v_tgt f_tgt Heqr_src Heqr_tgt.\n    induction LE; i; subst; ss.\n    { inv Heqr_src. inv Heqr_tgt. esplits; eauto. econs 1. }\n    inv Heqr_src. inv Heqr_tgt.\n    exploit IHLE; eauto. i. des. clear IHLE.\n    esplits; eauto.\n    eapply match_trace_cons; eauto.\n  Qed.\n\n  Lemma trace_le_partial_match\n        P d_init tr_src tr_src_ex f_src tr_tgt f_tgt\n        (TRACE: Forall2 P tr_src tr_tgt)\n        (LE: SeqTrace.le d_init\n                         (tr_tgt, SeqTrace.partial f_tgt)\n                         (tr_src ++ tr_src_ex, SeqTrace.partial f_src)):\n    exists d w,\n      (<<MATCH: match_trace SeqEvent.input_match d_init d tr_src tr_tgt>>) /\\\n      (<<WRITING: SeqThread.writing_trace tr_src_ex w>>) /\\\n      (<<FLAGS: Flags.le (Flags.join d f_tgt) (Flags.join w f_src)>>).\n  Proof.\n    remember (tr_src ++ tr_src_ex, SeqTrace.partial f_src) as r_src.\n    remember (tr_tgt, SeqTrace.partial f_tgt) as r_tgt.\n    revert tr_src tr_src_ex f_src tr_tgt f_tgt Heqr_src Heqr_tgt TRACE.\n    induction LE; i; subst; ss.\n    { inv Heqr_src. inv Heqr_tgt. inv TRACE0. ss.\n      esplits; [econs 1|..]; eauto.\n    }\n    inv Heqr_src. inv Heqr_tgt. inv TRACE. inv H0.\n    exploit IHLE; eauto. i. des. clear IHLE.\n    esplits; eauto.\n    eapply match_trace_cons; eauto.\n  Qed.\n\n  Lemma trace_le_partial_step_match\n        P d_init tr_src e_src i_src o tr_src_ex f_src tr_tgt e_tgt i_tgt f_tgt\n        (TRACE: Forall2 P tr_src tr_tgt)\n        (LE: SeqTrace.le d_init\n                         (tr_tgt ++ [(e_tgt, i_tgt, o)], SeqTrace.partial f_tgt)\n                         (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.partial f_src)):\n    exists d1 d2,\n      (<<MATCH: match_trace SeqEvent.input_match d_init d1 tr_src tr_tgt>>) /\\\n      (<<EVENT: ProgramEvent.le e_tgt e_src>>) /\\\n      (<<INPUT_MATCH: SeqEvent.input_match d1 d2 i_src i_tgt>>).\n  Proof.\n    remember (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.partial f_src) as r_src.\n    remember (tr_tgt ++ [(e_tgt, i_tgt, o)], SeqTrace.partial f_tgt) as r_tgt.\n    revert tr_src e_src i_src o tr_src_ex f_src tr_tgt e_tgt i_tgt f_tgt TRACE Heqr_src Heqr_tgt.\n    induction LE; i; subst; ss.\n    { inv Heqr_src. inv Heqr_tgt. destruct tr_tgt; ss. }\n    inv TRACE; ss.\n    { inv Heqr_src. inv Heqr_tgt. esplits; eauto. econs. }\n    inv Heqr_src. inv Heqr_tgt.\n    exploit IHLE; eauto. i. des. clear IHLE.\n    esplits; eauto.\n    eapply match_trace_cons; eauto.\n  Qed.\n\n  Lemma writing_trace_no_acquire\n        tr w\n        (WRITING: SeqThread.writing_trace tr w):\n    forall e i o (IN: List.In (e, i, o) tr), ~ is_acquire e.\n  Proof.\n    induction WRITING; ss. i. inv IN; eauto. inv H. eauto.\n  Qed.\n\n  Lemma trace_le_ub_acquire_match\n        P d_init tr_src e_src i_src o tr_src_ex tr_tgt e_tgt i_tgt res_tgt\n        (TRACE: Forall2 P tr_src tr_tgt)\n        (ACQUIRE: is_acquire e_src)\n        (LE: SeqTrace.le d_init\n                         (tr_tgt ++ [(e_tgt, i_tgt, o)], res_tgt)\n                         (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.ub)):\n    exists d1 d2,\n      (<<MATCH: match_trace SeqEvent.input_match d_init d1 tr_src tr_tgt>>) /\\\n      (<<EVENT: ProgramEvent.le e_tgt e_src>>) /\\\n      (<<INPUT_MATCH: SeqEvent.input_match d1 d2 i_src i_tgt>>).\n  Proof.\n    remember (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.ub) as r_src.\n    remember (tr_tgt ++ [(e_tgt, i_tgt, o)], res_tgt) as r_tgt.\n    revert tr_src e_src i_src o tr_src_ex tr_tgt e_tgt i_tgt res_tgt TRACE ACQUIRE Heqr_src Heqr_tgt.\n    induction LE; i; subst; ss.\n    { inv Heqr_src.\n      hexploit writing_trace_no_acquire; eauto.\n      { rewrite in_app_iff. right. econs 1. eauto. }\n      i. ss.\n    }\n    inv TRACE; ss.\n    { inv Heqr_src. inv Heqr_tgt. esplits; eauto. econs. }\n    inv Heqr_src. inv Heqr_tgt.\n    exploit IHLE; eauto. i. des. clear IHLE.\n    esplits; eauto.\n    eapply match_trace_cons; eauto.\n  Qed.\n\n  Lemma writing_trace_app\n        l1 l2 w\n        (WRITING: SeqThread.writing_trace (l1 ++ l2) w):\n    exists w',\n      Flags.le w' w /\\\n      SeqThread.writing_trace l2 w'.\n  Proof.\n    revert l2 w WRITING. induction l1; ss; i.\n    { esplits; eauto. refl. }\n    inv WRITING. exploit IHl1; eauto. i. des.\n    esplits; eauto. etrans; eauto. apply Flags.join_ge_r.\n  Qed.\n\n  Lemma trace_le_ub_match\n        P d_init tr_tgt r_tgt tr_src tr\n        (TRACE: Forall2 P tr_src tr_tgt)\n        (LE: SeqTrace.le d_init (tr_tgt, r_tgt) (tr_src ++ tr, SeqTrace.ub)):\n    exists w, SeqThread.writing_trace tr w.\n  Proof.\n    revert d_init LE. induction TRACE; i.\n    { inv LE. eauto. }\n    inv LE; eauto.\n    replace (x :: l ++ tr) with ((x :: l) ++ tr) in * by ss.\n    exploit writing_trace_app; eauto. i. des. eauto.\n  Qed.\n\n  Lemma trace_le_ub_step_match\n        P d_init tr_tgt e i o r_tgt tr_src tr\n        (TRACE: Forall2 P tr_src tr_tgt)\n        (LE: SeqTrace.le d_init (tr_tgt ++ [(e, i, o)], r_tgt) (tr_src ++ tr, SeqTrace.ub)):\n    (exists w, SeqThread.writing_trace tr w) \\/\n    (exists e_src i_src tr' d1 d2,\n        (<<MATCH: match_trace SeqEvent.input_match d_init d1 tr_src tr_tgt>>) /\\\n        (<<TRACE: tr = (e_src, i_src, o) :: tr'>>) /\\\n        (<<EVENT: ProgramEvent.le e e_src>>) /\\\n        (<<INPUT: SeqEvent.input_match d1 d2 i_src i>>)).\n  Proof.\n    revert d_init LE. induction TRACE; ss; i.\n    { inv LE; eauto. right. esplits; eauto. econs. }\n    inv LE.\n    - replace (x :: l ++ tr) with ((x :: l) ++ tr) in * by ss.\n      exploit writing_trace_app; eauto. i. des. eauto.\n    - exploit IHTRACE; eauto. i. des; eauto. subst.\n      right. esplits; eauto.\n      eapply match_trace_cons; eauto.\n  Qed.\n\n  Lemma last_eq_inv\n        A l1 l2 (a1 a2: A)\n        (EQ: l1 ++ [a1] = l2 ++ [a2]):\n    l1 = l2 /\\ a1 = a2.\n  Proof.\n    split.\n    - erewrite <- (removelast_last l1 a1).\n      erewrite <- (removelast_last l2 a2).\n      congr.\n    - erewrite <- (last_last l1 a1 a1).\n      erewrite <- (last_last l2 a2 a1).\n      congr.\n  Qed.\n\n  Lemma min_match_trace_min\n        d_init d_min d tr_src tr_tgt\n        (MIN_TRACE: match_trace (min_match SeqEvent.input_match) d_init d_min tr_src tr_tgt)\n        (TRACE: match_trace SeqEvent.input_match d_init d tr_src tr_tgt):\n    Flags.le d_min d.\n  Proof.\n    revert d TRACE. induction MIN_TRACE; i.\n    { inv TRACE; try refl. destruct tr_src; ss. }\n    inv TRACE.\n    { destruct tr_src; ss. }\n    apply last_eq_inv in H2, H3. des. inv H1. inv H0.\n    hexploit IHMIN_TRACE; eauto. i.\n    eapply min_match_le_min; eauto using SeqEvent.input_match_mon.\n  Qed.\n\n  Lemma match_trace_le_terminal\n        d tr_src v_src f_src tr_tgt v_tgt f_tgt\n        (MIN_TRACE: match_trace (min_match SeqEvent.input_match) Flags.bot d tr_src tr_tgt)\n        (LE: SeqTrace.le Flags.bot\n                         (tr_tgt, SeqTrace.term v_tgt f_tgt)\n                         (tr_src, SeqTrace.term v_src f_src)):\n    Flags.le (Flags.join d f_tgt) f_src.\n  Proof.\n    exploit trace_le_terminal_match; eauto. i. des.\n    hexploit min_match_trace_min; eauto. i.\n    etrans; eauto.\n    apply Flags.join_mon_l; auto.\n  Qed.\n\n  Lemma match_trace_le_partial\n        d\n        tr_src tr_src_ex f_src\n        tr_tgt f_tgt\n        (MIN_TRACE: match_trace (min_match SeqEvent.input_match) Flags.bot d tr_src tr_tgt)\n        (LE: SeqTrace.le Flags.bot\n                         (tr_tgt, SeqTrace.partial f_tgt)\n                         (tr_src ++ tr_src_ex, SeqTrace.partial f_src)):\n    exists w,\n      (<<WRITING: SeqThread.writing_trace tr_src_ex w>>) /\\\n      (<<FLAGS: Flags.le (Flags.join d f_tgt) (Flags.join w f_src)>>).\n  Proof.\n    exploit trace_le_partial_match; try exact LE.\n    { eapply match_trace_simple_match; eauto. }\n    i. des. esplits; eauto.\n    etrans; eauto. apply Flags.join_mon_l.\n    eapply min_match_trace_min; eauto.\n  Qed.\n\n  Lemma match_trace_le_partial_step\n        d\n        tr_src e_src i_src o tr_src_ex f_src\n        tr_tgt e_tgt i_tgt f_tgt\n        (MIN_TRACE: match_trace (min_match SeqEvent.input_match) Flags.bot d tr_src tr_tgt)\n        (LE: SeqTrace.le Flags.bot\n                         (tr_tgt ++ [(e_tgt, i_tgt, o)], SeqTrace.partial f_tgt)\n                         (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.partial f_src)):\n    exists d1 d2,\n      (<<EVENT: ProgramEvent.le e_tgt e_src>>) /\\\n      (<<INPUT_MATCH: SeqEvent.input_match d1 d2 i_src i_tgt>>) /\\\n      (<<MIN: Flags.le d d1>>).\n  Proof.\n    exploit trace_le_partial_step_match; try exact LE.\n    { eapply match_trace_simple_match; eauto. }\n    i. des. esplits; eauto.\n    eapply min_match_trace_min; eauto.\n  Qed.\n\n  Lemma match_trace_le_ub_acquire\n        d\n        tr_src e_src i_src o tr_src_ex\n        tr_tgt e_tgt i_tgt f_tgt\n        (MIN_TRACE: match_trace (min_match SeqEvent.input_match) Flags.bot d tr_src tr_tgt)\n        (ACQUIRE: is_acquire e_src)\n        (LE: SeqTrace.le Flags.bot\n                         (tr_tgt ++ [(e_tgt, i_tgt, o)], SeqTrace.partial f_tgt)\n                         (tr_src ++ [(e_src, i_src, o)] ++ tr_src_ex, SeqTrace.ub)):\n    exists d1 d2,\n      (<<EVENT: ProgramEvent.le e_tgt e_src>>) /\\\n      (<<INPUT_MATCH: SeqEvent.input_match d1 d2 i_src i_tgt>>) /\\\n      (<<MIN: Flags.le d d1>>).\n  Proof.\n    exploit trace_le_ub_acquire_match; try exact LE; eauto.\n    { eapply match_trace_simple_match; eauto. }\n    i. des. esplits; eauto.\n    eapply min_match_trace_min; eauto.\n  Qed.\n\n\n  (** definitions and lemmas on state_steps *)\n\n  Inductive state_steps (lang: language)\n                        (step: forall (p: Perms.t) (e: MachineEvent.t) (st1 st2: SeqState.t lang), Prop):\n    forall (tr: list (ProgramEvent.t * SeqEvent.input * Oracle.output))\n      (st1 st2: SeqState.t lang) (p1 p2: Perms.t), Prop :=\n  | state_steps_refl\n      st p:\n      state_steps step [] st st p p\n  | state_steps_at_step\n      e i o st1 st2 st3 p1 p3\n      tr st4 p4\n      (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n      (LSTEP: lang.(Language.step) e st2.(SeqState.state) st3.(SeqState.state))\n      (ATOMIC: is_atomic_event e)\n      (INPUT: SeqEvent.wf_input e i)\n      (ESTEP: SeqEvent.step i o p1 st2.(SeqState.memory) p3 st3.(SeqState.memory))\n      (STEPS: state_steps step tr st3 st4 p3 p4):\n      state_steps step ((e, i, o)::tr) st1 st4 p1 p4\n  .\n\n  Lemma state_steps_last\n        lang step tr (st1 st2: SeqState.t lang) p1 p2\n        e i o st3 st4 p4 m4\n        (STEPS: state_steps step tr st1 st2 p1 p2)\n        (NASTEPS: rtc (step p2 MachineEvent.silent) st2 st3)\n        (LSTEP: lang.(Language.step) e st3.(SeqState.state) st4)\n        (ATOMIC: is_atomic_event e)\n        (INPUT: SeqEvent.wf_input e i)\n        (ESTEP: SeqEvent.step i o p2 st3.(SeqState.memory) p4 m4):\n    state_steps step (tr ++ [(e, i, o)]) st1 (SeqState.mk _ st4 m4) p1 p4.\n  Proof.\n    dependent induction STEPS; ss.\n    { econs 2; eauto.\n      - instantiate (1:=(SeqState.mk _ st4 m4)). ss.\n      - eauto.\n      - econs.\n    }\n    exploit IHSTEPS; eauto. i.\n    econs 2; try exact x; eauto.\n  Qed.\n\n  Lemma na_steps_behavior\n        lang (step: Perms.t -> MachineEvent.t -> SeqState.t lang -> SeqState.t lang -> Prop)\n        (st1 st2: SeqState.t lang) p orc tr\n        (STEPS: rtc (step p MachineEvent.silent) st1 st2)\n        (BEH: SeqBehavior.behavior step (SeqThread.mk st2 p orc) tr):\n    SeqBehavior.behavior step (SeqThread.mk st1 p orc) tr.\n  Proof.\n    induction STEPS; ss.\n    econs 4; try eapply IHSTEPS; eauto.\n    econs. ss.\n  Qed.\n\n  Lemma steps_behavior_terminal\n        lang step orc0 tr (st0 st1 st2: SeqState.t lang) p0 p1 orc\n        (STEPS: state_steps step tr st0 st1 p0 p1)\n        (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n        (TERMINAL: lang.(Language.is_terminal) st2.(SeqState.state))\n        (ORACLE: oracle_follows_trace orc0 tr orc):\n    SeqBehavior.behavior step\n                         (SeqThread.mk st0 p0 orc)\n                         (tr, SeqTrace.term st2.(SeqState.memory).(SeqMemory.value_map) st2.(SeqState.memory).(SeqMemory.flags)).\n  Proof.\n    revert orc ORACLE. induction STEPS; i.\n    - eapply na_steps_behavior; eauto.\n      destruct st2, memory. ss. econs 1; eauto.\n    - eapply na_steps_behavior; eauto.\n      inv ORACLE. exploit COMPLETE; try refl.\n      { eapply wf_input_oracle_wf_input; eauto. }\n      i. des. exploit SOUND; eauto. intros x. des. exploit x0; try refl. i. des.\n      econs 5; try eapply IHSTEPS; try eapply FOLLOWS; eauto.\n      destruct st0, st3. econs; eauto; try refl.\n  Qed.\n\n  Lemma steps_behavior_partial\n        lang step orc0 tr (st0 st1 st2: SeqState.t lang) p0 p1 orc\n        (STEPS: state_steps step tr st0 st1 p0 p1)\n        (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n        (ORACLE: oracle_follows_trace orc0 tr orc):\n    SeqBehavior.behavior step\n                         (SeqThread.mk st0 p0 orc)\n                         (tr, SeqTrace.partial st2.(SeqState.memory).(SeqMemory.flags)).\n  Proof.\n    revert orc ORACLE. induction STEPS; i.\n    - eapply na_steps_behavior; eauto.\n      destruct st2, memory. ss. econs 2; eauto.\n    - eapply na_steps_behavior; eauto.\n      inv ORACLE. exploit COMPLETE; try refl.\n      { eapply wf_input_oracle_wf_input; eauto. }\n      i. des. exploit SOUND; eauto. intros x. des. exploit x0; try refl. i. des.\n      econs 5; try eapply IHSTEPS; try eapply FOLLOWS; eauto.\n      destruct st0, st3. econs; eauto; try refl.\n  Qed.\n\n  Lemma steps_behavior_ub\n        lang step orc0 tr (st0 st1 st2 st3: SeqState.t lang) p0 p1 orc\n        (STEPS: state_steps step tr st0 st1 p0 p1)\n        (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n        (FAILURE: step p1 MachineEvent.failure st2 st3)\n        (ORACLE: oracle_follows_trace orc0 tr orc):\n    SeqBehavior.behavior step (SeqThread.mk st0 p0 orc) (tr, SeqTrace.ub).\n  Proof.\n    revert orc ORACLE. induction STEPS; i.\n    - eapply na_steps_behavior; eauto.\n      destruct st2. econs 3; eauto. econs. econs. eauto.\n    - eapply na_steps_behavior; eauto.\n      inv ORACLE. exploit COMPLETE; try refl.\n      { eapply wf_input_oracle_wf_input; eauto. }\n      i. des. exploit SOUND; eauto. intros x. des. exploit x0; try refl. i. des.\n      econs 5; try eapply IHSTEPS; try eapply FOLLOWS; eauto.\n      destruct st0, st4. econs; eauto; try refl.\n  Qed.\n\n  Lemma event_step_oracle_input\n        e ie o p1 m1 p2 m2\n        (WF: SeqEvent.wf_input e ie)\n        (STEP: SeqEvent.step ie o p1 m1 p2 m2):\n    SeqEvent.get_oracle_input ie = oracle_input_of_event e m1.\n  Proof.\n    destruct ie. inv STEP; ss.\n    unfold SeqEvent.wf_input, SeqEvent.get_oracle_input, oracle_input_of_event in *.\n    ss. splitsH.\n    repeat f_equal.\n    - inv UPD; ss; des_ifs; ss.\n      + specialize (H t t0). des. exploit H5; eauto. i. des. ss.\n      + specialize (H t t0). des. exploit H5; eauto. intros x. des. inv x.\n        inv MEM. ss.\n      + specialize (H loc v_new). des. exploit H; eauto. i. ss.\n    - inv ACQ; ss; condtac; ss; intuition.\n    - inv REL; ss; condtac; ss; intuition.\n  Qed.\n\n  Lemma steps_behavior_at_step\n        lang step orc0 tr (st0 st1 st2: SeqState.t lang) p0 p1 orc\n        e i o st3 p3 m3\n        (STEPS: state_steps step tr st0 st1 p0 p1)\n        (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n        (ATSTEP: lang.(Language.step) e st2.(SeqState.state) st3)\n        (ESTEP: SeqEvent.step i o p1 st2.(SeqState.memory) p3 m3)\n        (ATOMIC: is_atomic_event e)\n        (INPUT: SeqEvent.wf_input e i)\n        (OUTPUT: Oracle.wf_output e o)\n        (ORACLE: oracle_follows_trace (add_oracle e (SeqEvent.get_oracle_input i) o orc0) tr orc):\n    SeqBehavior.behavior step (SeqThread.mk st0 p0 orc)\n                         (tr ++ [(e, i, o)], SeqTrace.partial m3.(SeqMemory.flags)).\n  Proof.\n    revert orc ORACLE. induction STEPS; i.\n    { destruct st2. ss. destruct m3. ss.\n      assert (exists orc', Oracle.step e (SeqEvent.get_oracle_input i) o orc orc').\n      { inv ORACLE. punfold LE2. inv LE2.\n        exploit LE.\n        { econs. econs 1. }\n        i. des. esplits; eauto.\n      }\n      des.\n      esplits.\n      eapply na_steps_behavior; eauto. econs 5.\n      - econs; try refl; eauto.\n      - econs 2.\n    }\n    clear INPUT OUTPUT.\n    inv ORACLE. exploit COMPLETE; try refl.\n    { eapply wf_input_oracle_wf_input; eauto. }\n    i. des. exploit SOUND; eauto. intros x. des. exploit x0; try refl. i. des.\n    exploit IHSTEPS; eauto. i. des. esplits; eauto. ss.\n    eapply na_steps_behavior; eauto.\n    econs 5; try eapply IHSTEPS; try eapply FOLLOWS; eauto.\n    destruct st0, st4. econs; eauto; try refl.\n  Qed.\n\n  Lemma steps_behavior_oracle_step\n        lang step orc0 tr (st0 st1 st2: SeqState.t lang) p0 p1 orc\n        e i o st3 p3 m3 orc1\n        (STEPS: state_steps step tr st0 st1 p0 p1)\n        (NASTEPS: rtc (step p1 MachineEvent.silent) st1 st2)\n        (ATSTEP: lang.(Language.step) e st2.(SeqState.state) st3)\n        (ESTEP: SeqEvent.step i o p1 st2.(SeqState.memory) p3 m3)\n        (ATOMIC: is_atomic_event e)\n        (INPUT: SeqEvent.wf_input e i)\n        (OUTPUT: Oracle.wf_output e o)\n        (ORACLE: oracle_follows_trace orc0 tr orc)\n        (OSTEP: Oracle.step e (SeqEvent.get_oracle_input i) o orc0 orc1):\n    SeqBehavior.behavior step (SeqThread.mk st0 p0 orc)\n                         (tr ++ [(e, i, o)], SeqTrace.partial m3.(SeqMemory.flags)).\n  Proof.\n    revert orc ORACLE. induction STEPS; i.\n    { destruct st2. ss. destruct m3. ss.\n      assert (exists orc', Oracle.step e (SeqEvent.get_oracle_input i) o orc orc').\n      { inv ORACLE. punfold LE2. inv LE2.\n        exploit LE; eauto. i. des. eauto.\n      }\n      des.\n      esplits.\n      eapply na_steps_behavior; eauto. econs 5.\n      - econs; try refl; eauto.\n      - econs 2.\n    }\n    clear INPUT OUTPUT.\n    inv ORACLE. exploit COMPLETE; try refl.\n    { eapply wf_input_oracle_wf_input; eauto. }\n    i. des. exploit SOUND; eauto. intros x. des. exploit x0; try refl. i. des.\n    exploit IHSTEPS; eauto. i. des. esplits; eauto. ss.\n    eapply na_steps_behavior; eauto.\n    econs 5; try eapply IHSTEPS; try eapply FOLLOWS; eauto.\n    destruct st0, st4. econs; eauto; try refl.\n  Qed.\n\n  Lemma event_step_exists_full e p1 m1:\n    exists i o p2 m2,\n      (<<WF_INPUT: SeqEvent.wf_input e i>>) /\\\n      (<<WF_OUTPUT: Oracle.wf_output e o>>) /\\\n      (<<ESTEP: SeqEvent.step i o p1 m1 p2 m2>>).\n  Proof.\n    specialize (oracle_input_of_event_wf e m1). i.\n    exploit oracle_simple_output_wf; eauto. i.\n    exploit event_step_exists; eauto. i. des. esplits; eauto.\n  Qed.\n\n  Lemma wf_input_wf_output\n        e i o p1 m1 p2 m2\n        (STEP: SeqEvent.step i o p1 m1 p2 m2)\n        (WF: SeqEvent.wf_input e i):\n    Oracle.wf_output e o.\n  Proof.\n    destruct i, o. inv STEP. ss.\n    unfold SeqEvent.wf_input, Oracle.wf_output in *. ss. splitsH.\n    apply wf_in_access_some in H.\n    splitsH. splits.\n    - inv UPD; ss.\n    - inv ACQ; ss.\n    - inv REL; ss.\n  Qed.\n\n  Lemma state_steps_wf_trace\n        lang step tr (st1 st2: SeqState.t lang) p1 p2\n        (STEPS: state_steps step tr st1 st2 p1 p2):\n    wf_trace tr.\n  Proof.\n    induction STEPS; ss.\n    econs; eauto. split; ss.\n    eapply wf_input_wf_output; eauto.\n  Qed.\n\n  Lemma na_local_step_na_event\n        p me pe m1 m2\n        (STEP: SeqState.na_local_step p me pe m1 m2):\n    ~ is_atomic_event pe.\n  Proof.\n    ii. inv STEP; ss.\n    - destruct ord; ss.\n    - destruct ord; ss.\n    - unguard. des; destruct ordr, ordw; ss.\n  Qed.\n\n  Lemma similar_is_atomic\n        e1 e2\n        (E1: forall loc valr valw ordr ordw\n               (E: e1 = ProgramEvent.update loc valr valw ordr ordw),\n            Ordering.le Ordering.plain ordr /\\ Ordering.le Ordering.plain ordw)\n        (E2: forall loc valr valw ordr ordw\n               (E: e2 = ProgramEvent.update loc valr valw ordr ordw),\n            Ordering.le Ordering.plain ordr /\\ Ordering.le Ordering.plain ordw)\n        (SIMILAR: similar e1 e2):\n    is_atomic_event e1 <-> is_atomic_event e2.\n  Proof.\n    destruct e1, e2; ss; des; subst; ss.\n    - exploit E2; eauto. i. des.\n      destruct ordr, ordw; ss.\n    - exploit E1; eauto. i. des.\n      destruct ord, ordw; ss.\n  Qed.\n\n  Lemma le_is_atomic\n        e1 e2\n        (LE: ProgramEvent.le e1 e2):\n    is_atomic_event e1 <-> is_atomic_event e2.\n  Proof.\n    destruct e1, e2; ss; des; inv LE; ss.\n  Qed.\n\n  Lemma state_step_behavior\n        p st1 st2 orc tr r\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: state_step p MachineEvent.silent st1 st2)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p orc) (tr, r))\n        (TRACE: tr <> []):\n    SeqBehavior.behavior state_step (SeqThread.mk st2 p orc) (tr, r).\n  Proof.\n    inv BEH; ss.\n    - inv STEP0. exploit state_step_determ; [eauto|exact STEP|exact STEP1|]. i. des. subst. ss.\n    - inv STEP0. exploit state_step_subset; eauto. intros x. inv x.\n      punfold DETERM. inv DETERM.\n      exploit STEP_STEP; [exact LANG|exact LANG0|]. i. des.\n      exploit similar_is_atomic; eauto; try by (i; subst; eapply NO_NA_UPDATE; eauto). i.\n      rewrite x2 in *.\n      exploit na_local_step_na_event; eauto. ss.\n  Qed.\n\n  Lemma rtc_state_step_behavior\n        p st1 st2 orc tr r\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: rtc (state_step p MachineEvent.silent) st1 st2)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p orc) (tr, r))\n        (TRACE: tr <> []):\n    SeqBehavior.behavior state_step (SeqThread.mk st2 p orc) (tr, r).\n  Proof.\n    revert DETERM BEH. induction STEP; i; ss.\n    exploit state_step_behavior; eauto. i.\n    apply IHSTEP; eauto.\n    exploit state_step_subset; eauto. intros x0. inv x0. s.\n    punfold DETERM. inv DETERM. exploit PRESERVE; eauto. intros x.\n    inv x; ss.\n  Qed.\n\n  Lemma state_step_behavior_ub\n        p st1 st2 orc tr\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: state_step p MachineEvent.silent st1 st2)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p orc) (tr, SeqTrace.ub)):\n    SeqBehavior.behavior state_step (SeqThread.mk st2 p orc) (tr, SeqTrace.ub).\n  Proof.\n    inv BEH; ss.\n    - inv FAILURE. inv H.\n      exploit state_step_determ; [|exact STEP|exact STEP0|]; ss. i. des. ss.\n    - inv STEP0.\n      exploit state_step_determ; [|exact STEP|exact STEP1|]; ss. i. des. subst. ss.\n    - inv STEP0. exploit state_step_subset; eauto. intros x. inv x.\n      punfold DETERM. inv DETERM.\n      exploit STEP_STEP; [exact LANG|exact LANG0|]. i. des.\n      exploit similar_is_atomic; eauto; try by (i; subst; eapply NO_NA_UPDATE; eauto). i.\n      rewrite x2 in *.\n      exploit na_local_step_na_event; eauto. ss.\n  Qed.\n\n  Lemma rtc_state_step_behavior_ub\n        p st1 st2 orc tr\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: rtc (state_step p MachineEvent.silent) st1 st2)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p orc) (tr, SeqTrace.ub)):\n    SeqBehavior.behavior state_step (SeqThread.mk st2 p orc) (tr, SeqTrace.ub).\n  Proof.\n    revert DETERM BEH. induction STEP; i; ss.\n    exploit state_step_behavior_ub; eauto. i.\n    apply IHSTEP; eauto.\n    exploit state_step_subset; eauto. intros x0. inv x0. s.\n    punfold DETERM. inv DETERM. exploit PRESERVE; eauto. intros x.\n    inv x; ss.\n  Qed.\n\n  Lemma rtc_na_step_deterministic\n        lang p st1 st2\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEPS: rtc (@SeqState.na_step lang p MachineEvent.silent) st1 st2):\n    deterministic _ st2.(SeqState.state).\n  Proof.\n    induction STEPS; ss.\n    apply IHSTEPS. inv H. ss.\n    eapply step_deterministic; eauto.\n  Qed.\n\n  Lemma rtc_state_step_deterministic\n        p st1 st2\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: rtc (state_step p MachineEvent.silent) st1 st2):\n    deterministic _ st2.(SeqState.state).\n  Proof.\n    induction STEP; ss.\n    exploit state_step_subset; eauto. intros x0. inv x0.\n    apply IHSTEP. eapply step_deterministic; eauto.\n  Qed.\n\n  Lemma state_steps_deterministic\n        tr st1 st2 p1 p2\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (STEP: state_steps state_step tr st1 st2 p1 p2):\n    deterministic _ st2.(SeqState.state).\n  Proof.\n    induction STEP; ss.\n    apply IHSTEP. exploit rtc_state_step_deterministic; eauto. i.\n    eapply step_deterministic; eauto.\n  Qed.\n\n  Lemma rtc_na_step_receptive\n        lang p st1 st2\n        (RECEPTIVE: receptive _ st1.(SeqState.state))\n        (STEPS: rtc (@SeqState.na_step lang p MachineEvent.silent) st1 st2):\n    receptive _ st2.(SeqState.state).\n  Proof.\n    induction STEPS; ss.\n    apply IHSTEPS. inv H. ss.\n    eapply step_receptive; eauto.\n  Qed.\n\n  Lemma state_steps_receptive\n        lang tr st1 st2 p1 p2\n        (RECEPTIVE: receptive lang st1.(SeqState.state))\n        (STEP: state_steps (@SeqState.na_step _) tr st1 st2 p1 p2):\n    receptive _ st2.(SeqState.state).\n  Proof.\n    induction STEP; ss.\n    apply IHSTEP. exploit rtc_na_step_receptive; eauto. i.\n    eapply step_receptive; eauto.\n  Qed.\n\n  Lemma wf_input_in_access\n        e i1 i2\n        loc1 v_old1 f1 v_new1\n        loc2 v_old2 f2 v_new2\n        (WF1: SeqEvent.wf_input e i1)\n        (WF2: SeqEvent.wf_input e i2)\n        (IN1: i1.(SeqEvent.in_access) = Some (loc1, v_old1, f1, v_new1))\n        (IN2: i2.(SeqEvent.in_access) = Some (loc2, v_old2, f2, v_new2)):\n    loc1 = loc2 /\\ v_new1 = v_new2.\n  Proof.\n    unfold SeqEvent.wf_input in *. des.\n    destruct i1, i2. ss. subst.\n    specialize (UPDATE0 loc1 v_new1). des. exploit UPDATE0; eauto. i.\n    specialize (UPDATE loc2 v_new2). des. exploit UPDATE; eauto. intros x.\n    rewrite x in *. inv x0. ss.\n  Qed.\n\n  Lemma wf_input_similar\n        e i1 i2\n        (WF1: SeqEvent.wf_input e i1)\n        (WF2: SeqEvent.wf_input e i2):\n    oracle_similar_input (SeqEvent.get_oracle_input i1) (SeqEvent.get_oracle_input i2).\n  Proof.\n    unfold SeqEvent.wf_input in *. des. destruct i1, i2; ss.\n    unfold oracle_similar_input; ss.\n    etrans; eauto. repeat rewrite andb_true_iff. splits.\n    - destruct (is_accessing e) as [[loc v]|].\n      + specialize (UPDATE0 loc v). specialize (UPDATE loc v). des.\n        exploit UPDATE2; eauto. i. des. subst.\n        exploit UPDATE1; eauto. i. des. subst.\n        ss. apply Loc.eqb_refl.\n      + destruct in_access as [[[[]]]|].\n        { specialize (UPDATE0 t t2). des. exploit UPDATE0; eauto. ss. }\n        destruct in_access0 as [[[[]]]|].\n        { specialize (UPDATE t t2). des. exploit UPDATE; eauto. ss. }\n        ss.\n    - destruct in_acquire, in_acquire0; eauto.\n    - destruct in_release, in_release0; eauto.\n  Qed.\n\n  Lemma behavior_steps_partial\n        lang step (th1: SeqThread.t lang) tr f\n        (BEH: SeqBehavior.behavior step th1 (tr, SeqTrace.partial f)):\n    exists th2,\n      (<<STEPS: SeqThread.steps step tr th1 th2>>) /\\\n      (<<FAILURE: f = th2.(SeqThread.state).(SeqState.memory).(SeqMemory.flags)>>).\n  Proof.\n    remember (tr, SeqTrace.partial f) as r.\n    revert tr f Heqr. induction BEH; i; inv Heqr; ss.\n    - esplits; [econs 1|]; eauto.\n    - exploit IHBEH; eauto. i. des.\n      esplits; eauto. econs 2; eauto.\n    - exploit IHBEH; eauto. i. des.\n      esplits; eauto. econs 3; eauto.\n  Qed.\n\n  Lemma behavior_steps_ub\n        lang step (th1: SeqThread.t lang) tr\n        (BEH: SeqBehavior.behavior step th1 (tr, SeqTrace.ub)):\n    exists th2 st3,\n      (<<STEPS: SeqThread.steps step tr th1 th2>>) /\\\n      (<<FAILURE: step th2.(SeqThread.perm) MachineEvent.failure th2.(SeqThread.state) st3>>).\n  Proof.\n    remember (tr, SeqTrace.ub) as r.\n    revert tr Heqr.\n    dependent induction BEH; i; inv Heqr; ss.\n    - unfold SeqThread.failure in *. des. inv FAILURE0.\n      esplits; [econs 1|]; eauto.\n    - exploit IHBEH; eauto. i. des.\n      esplits; [econs 2; eauto|]; eauto.\n    - exploit IHBEH; eauto. i. des.\n      esplits; [econs 3; eauto|]; eauto.\n  Qed.\n\n  Lemma behavior_steps_at_step\n        lang step (th1: SeqThread.t lang) e i o tr r\n        (BEH: SeqBehavior.behavior step th1 ((e, i, o) :: tr, r)):\n    exists st2 st3,\n      (<<STEPS: rtc (step th1.(SeqThread.perm) MachineEvent.silent) th1.(SeqThread.state) st2>>) /\\\n      (<<STEP: lang.(Language.step) e st2.(SeqState.state) st3>>).\n  Proof.\n    remember ((e, i, o) :: tr, r) as res.\n    revert e i o tr r Heqres.\n    dependent induction BEH; i; inv Heqres; ss.\n    - exploit IHBEH; eauto. i. des.\n      inv STEP. ss.\n      esplits; [econs 2; eauto|]; eauto.\n    - inv STEP. ss. esplits; eauto.\n  Qed.\n\n  Lemma behavior_lang_atomic\n        e st1 st2 p1 orc1 e' i o tr r\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (LSTEP: lang_src.(Language.step) e st1.(SeqState.state) st2)\n        (ATOMIC: is_atomic_event e)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc1)\n                                   ((e', i, o) :: tr, r)):\n    exists st2' e0 i0 orc2 p2 m2,\n      (<<LANG: lang_src.(Language.step) e' st1.(SeqState.state) st2'>>) /\\\n      (<<SIMILAR: similar e e'>>) /\\\n      (<<ATOMIC: is_atomic_event e'>>) /\\\n      (<<EVENT: ProgramEvent.le e0 e'>>) /\\\n      (<<INPUT: Oracle.input_le i0 (SeqEvent.get_oracle_input i)>>) /\\\n      (<<ORACLE: Oracle.step e0 i0 o orc1 orc2>>) /\\\n      (<<MEM: SeqEvent.step i o p1 st1.(SeqState.memory) p2 m2>>) /\\\n      (<<INPUT: SeqEvent.wf_input e' i>>).\n  Proof.\n    inv BEH.\n    { inv STEP. exploit state_step_subset; eauto. intros x. inv x. ss.\n      exploit deterministic_step; [|exact LSTEP|exact LANG|]; ss. i. des.\n      punfold DETERM. inv DETERM.\n      exploit similar_is_atomic; eauto; try by (i; subst; eapply NO_NA_UPDATE; eauto). i.\n      rewrite x2 in *.\n      exploit na_local_step_na_event; eauto; ss.\n    }\n    inv STEP.\n    exploit deterministic_step; [|exact LSTEP|exact LANG|]; ss. i. des.\n    esplits; try exact LANG; eauto.\n  Qed.\n\n  Lemma at_step_behavior\n        e i o p1 st1 p2 st2\n        orc_init orc1 x l y ly r\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (LSTEP: lang_src.(Language.step) e st1.(SeqState.state) st2.(SeqState.state))\n        (ATOMIC: is_atomic_event e)\n        (INPUT: SeqEvent.wf_input e i)\n        (ESTEP: SeqEvent.step i o p1 st1.(SeqState.memory) p2 st2.(SeqState.memory))\n        (ORACLE: oracle_follows_trace orc_init (y :: ly) orc1)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc1) (x :: l, r))\n        (EVENT1: simple_match_event (e, i, o) y)\n        (* (EVENT2: simple_match_event x y) *):\n    exists orc2,\n      (<<EVENT: x = (e, i, o)>>) /\\\n      (<<ORACLE2: oracle_follows_trace orc_init ly orc2>>) /\\\n      (<<BEH2: SeqBehavior.behavior state_step (SeqThread.mk st2 p2 orc2) (l, r)>>).\n  Proof.\n    inv BEH.\n    { inv STEP. exploit state_step_subset; eauto. intros x0. inv x0.\n      punfold DETERM. inv DETERM.\n      exploit STEP_STEP; [exact LSTEP|exact LANG|]. i. des.\n      exploit similar_is_atomic; eauto; try by (i; subst; eapply NO_NA_UPDATE; eauto). i.\n      rewrite x3 in *. inv LOCAL; ss; try destruct ord; ss.\n    }\n    inv STEP. ss.\n    punfold DETERM. inv DETERM.\n    exploit STEP_STEP; [exact LSTEP|exact LANG|]. intros x. des.\n    destruct y as [[ey iy] oy].\n    replace o with oy in * by (inv EVENT1; ss).\n    replace e0 with e in *; cycle 1.\n    { clear - ORACLE EVENT1 ORACLE0 x EVENT.\n      inv EVENT1. clear INPUT.\n      inv ORACLE. exploit SOUND; eauto. i. des.\n      clear - x EVENT EVENT0 EVENT1.\n      unfold eq_reading_value in *.\n      destruct e1, e0, e, ey; ss; inv EVENT; inv EVENT0; des; subst; ss.\n      exploit x2; eauto. i. subst. ss.\n    }\n    assert (ISIMILAR: oracle_similar_input (SeqEvent.get_oracle_input iy) i1).\n    { clear - ORACLE EVENT1 ORACLE0 EVENT INPUT INPUT0 INPUT1. inv EVENT1.\n      apply input_le_similar in INPUT0.\n      exploit wf_input_similar; [exact INPUT|exact INPUT1|]. i.\n      symmetry. etrans; eauto.\n      symmetry. etrans; eauto.\n      symmetry. ss.\n    }\n    replace o0 with oy in *; cycle 1.\n    { clear - ORACLE EVENT1 ORACLE0 EVENT INPUT INPUT0 INPUT1 ISIMILAR. inv EVENT1.\n      inv ORACLE. exploit SOUND; eauto. intros x. des.\n      exploit x0; eauto. i. des. ss.\n    }\n    destruct st2. ss. exploit x0; eauto. i. subst.\n    exploit SeqEvent.step_inj; [exact ESTEP|exact MEM|..]; eauto.\n    { i. exploit wf_input_in_access; [exact INPUT|exact INPUT1|..]; eauto. }\n    i. des. subst.\n    esplits; eauto.\n    inv ORACLE. exploit SOUND; try exact ORACLE0. intros x1. des.\n    apply x2. ss.\n  Qed.\n\n  Lemma steps_behavior_prefix_terminal\n        tr_src tr_tgt\n        st1 st2 p1 p2\n        orc_init orc tr_src' v_src f_src\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (TRACE: Forall2 simple_match_event tr_src tr_tgt)\n        (STRACE: Forall2 simple_match_event tr_src' tr_tgt)\n        (STEPS: state_steps state_step tr_src st1 st2 p1 p2)\n        (ORACLE: oracle_follows_trace orc_init tr_tgt orc)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc)\n                                   (tr_src', SeqTrace.term v_src f_src)):\n    (<<TRACES: tr_src = tr_src'>>) /\\\n    exists st3,\n      (<<NASTEPS: rtc (state_step p2 MachineEvent.silent) st2 st3>>) /\\\n      (<<TERMINAL: lang_src.(Language.is_terminal) st3.(SeqState.state)>>) /\\\n      (<<VALUE_MAP: st3.(SeqState.memory).(SeqMemory.value_map) = v_src>>) /\\\n      (<<FLAGS: st3.(SeqState.memory).(SeqMemory.flags) = f_src>>).\n  Proof.\n    revert tr_src' tr_tgt orc v_src f_src TRACE STRACE ORACLE BEH.\n    induction STEPS; i.\n    { clear ORACLE DETERM. inv TRACE. inv STRACE. split; ss.\n      remember (SeqThread.mk st p orc) as th1.\n      remember ([], SeqTrace.term v_src f_src) as tr.\n      revert st v_src f_src Heqth1 Heqtr.\n      induction BEH; i; inv Heqth1; try inv Heqtr.\n      - esplits; eauto; ss.\n      - inv STEP. exploit IHBEH; eauto. i. des. esplits.\n        + econs 2; eauto.\n        + ss.\n        + ss.\n        + ss.\n    }\n    exploit rtc_state_step_behavior; eauto.\n    { ii. subst. inv STRACE. inv TRACE. }\n    i. inv TRACE. inv STRACE.\n    exploit at_step_behavior; try exact LSTEP; try exact x0; eauto.\n    { eapply rtc_state_step_deterministic; eauto. }\n    i. des. subst.\n    exploit IHSTEPS; try exact H5; try eapply BEH2; eauto.\n    { eapply step_deterministic; try eapply LSTEP; eauto.\n      eapply rtc_state_step_deterministic; eauto.\n    }\n    i. des. subst. esplits; eauto.\n  Qed.\n\n  Lemma steps_behavior_prefix_ub\n        tr_src tr_tgt\n        st1 st2 p1 p2\n        orc_init orc tr_src'\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (TRACE: Forall2 simple_match_event tr_src tr_tgt)\n        (STEPS: state_steps state_step tr_src st1 st2 p1 p2)\n        (ORACLE: oracle_follows_trace orc_init tr_tgt orc)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc) (tr_src', SeqTrace.ub)):\n    exists orc2 th tr st3,\n      (<<ORACLE2: oracle_follows_trace orc_init [] orc2>>) /\\\n      (<<TRACES: tr_src' = tr_src ++ tr>>) /\\\n      (<<STEPS: SeqThread.steps state_step tr (SeqThread.mk st2 p2 orc2) th>>) /\\\n      (<<FAILURE: state_step th.(SeqThread.perm) MachineEvent.failure th.(SeqThread.state) st3>>).\n  Proof.\n    revert tr_src' tr_tgt orc TRACE ORACLE BEH.\n    induction STEPS; i.\n    { exploit behavior_steps_ub; eauto. i. des.\n      inv TRACE. ss. esplits; eauto.\n    }\n    exploit rtc_state_step_behavior_ub; eauto. i. inv TRACE.\n    exploit rtc_state_step_deterministic; eauto. i.\n    destruct tr_src' as [|[[e' i'] o'] tr_src'].\n    { inv x0; ss.\n      - inv FAILURE. inv H.\n        exploit state_step_subset; eauto. intros x. inv x.\n        punfold x1. inv x1.\n        exploit STEP_STEP; [exact LSTEP|exact LANG|]. intros x. des.\n        exploit similar_is_atomic; try exact x; try by (i; subst; eapply NO_NA_UPDATE; eauto). intros x2.\n        rewrite x2 in *.\n        exploit na_local_step_na_event; eauto. ss.\n      - inv STEP. exploit state_step_subset; eauto. intros x. inv x.\n        punfold x1. inv x1.\n        exploit STEP_STEP; [exact LSTEP|exact LANG|]. intros x. des.\n        exploit similar_is_atomic; try exact x; try by (i; subst; eapply NO_NA_UPDATE; eauto). intros x2.\n        rewrite x2 in *.\n        exploit na_local_step_na_event; eauto. ss.\n    }\n    exploit at_step_behavior; try exact LSTEP; try exact x0; eauto. i. des. inv EVENT.\n    exploit IHSTEPS; try exact H3; try eapply BEH2; eauto.\n    { eapply step_deterministic; try eapply LSTEP; eauto. }\n    i. des. subst. esplits; eauto. ss.\n  Qed.\n\n  Lemma behavior_nil_partial_inv\n        lang step (th1: SeqThread.t lang) f\n        (BEH: SeqBehavior.behavior step th1 ([], SeqTrace.partial f)):\n    exists st2,\n      (<<STEPS: rtc (step th1.(SeqThread.perm) MachineEvent.silent)\n                    th1.(SeqThread.state) st2>>) /\\\n      (<<FLAGS: f = st2.(SeqState.memory).(SeqMemory.flags)>>).\n  Proof.\n    remember ([], SeqTrace.partial f) as r.\n    revert f Heqr. induction BEH; ss; i; inv Heqr; eauto.\n    exploit IHBEH; eauto. i. des.\n    esplits; try exact FLAGS.\n    inv STEP. ss. econs 2; eauto.\n  Qed.\n\n  Lemma steps_behavior_prefix_partial\n        tr_src tr_tgt\n        st1 st2 p1 p2\n        orc_init orc tr_src' tr_src_ex f_src\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (TRACE: Forall2 simple_match_event tr_src tr_tgt)\n        (STRACE: Forall2 simple_match_event tr_src' tr_tgt)\n        (STEPS: state_steps state_step tr_src st1 st2 p1 p2)\n        (ORACLE: oracle_follows_trace orc_init tr_tgt orc)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc)\n                                   (tr_src' ++ tr_src_ex, SeqTrace.partial f_src)):\n    (<<TRACES: tr_src = tr_src'>>) /\\\n    (<<EX: tr_src_ex = []>>) /\\\n    (exists st3,\n        ((<<PREFIX: rtc (state_step p2 MachineEvent.silent) st2 st3>>) \\/\n         (<<SUFFIX: rtc (state_step p2 MachineEvent.silent) st3 st2>>)) /\\\n        (<<FLAGS: f_src = st3.(SeqState.memory).(SeqMemory.flags)>>)) \\/\n    exists orc',\n      (<<LE1: oracle_le orc' orc_init>>) /\\\n      (<<LE2: oracle_le orc_init orc'>>) /\\\n      (<<TRACES: tr_src = tr_src'>>) /\\\n      (<<BEH_EX: SeqBehavior.behavior state_step (SeqThread.mk st2 p2 orc')\n                                      (tr_src_ex, SeqTrace.partial f_src)>>).\n  Proof.\n    destruct tr_src_ex as [|[[e i] o] tr_src_ex].\n    { left. rewrite app_nil_r in *.\n      revert tr_src' tr_tgt orc TRACE STRACE ORACLE BEH.\n      induction STEPS; i.\n      { inv TRACE. inv STRACE.\n        exploit behavior_nil_partial_inv; eauto. s. i. des.\n        esplits; try exact FLAGS; eauto.\n      }\n      inv TRACE. inv STRACE.\n      exploit rtc_state_step_behavior; eauto; ss. i.\n      exploit at_step_behavior; try exact LSTEP; try exact x1; eauto.\n      { eapply rtc_state_step_deterministic; eauto. }\n      i. des. subst.\n      exploit IHSTEPS; try exact H5; try eapply BEH2; eauto.\n      { eapply step_deterministic; try eapply LSTEP; eauto.\n        eapply rtc_state_step_deterministic; eauto.\n      }\n      i. des; subst; splits; auto.\n      - esplits; [|refl]. eauto.\n      - esplits; [|refl]. eauto.\n    }\n    right.\n    revert tr_src' tr_tgt orc TRACE STRACE ORACLE BEH.\n    induction STEPS; i.\n    { inv TRACE. inv STRACE. inv ORACLE. esplits; eauto. }\n    exploit rtc_state_step_behavior; eauto.\n    { destruct tr_src'; ss. }\n    i. inv TRACE. inv STRACE.\n    exploit at_step_behavior; try exact LSTEP; try exact x0; eauto.\n    { eapply rtc_state_step_deterministic; eauto. }\n    i. des. subst.\n    exploit IHSTEPS; try exact H5; try eapply BEH2; eauto.\n    { eapply step_deterministic; try eapply LSTEP; eauto.\n      eapply rtc_state_step_deterministic; eauto.\n    }\n    i. des. subst. esplits; eauto.\n  Qed.\n\n  Lemma trace_le_cases\n        d tr_tgt tr_src\n        (LE: SeqTrace.le d tr_tgt tr_src):\n    (<<TERM: exists tr_src' v_src f_src tr_tgt' v_tgt f_tgt,\n        tr_src = (tr_src', SeqTrace.term v_src f_src) /\\\n        tr_tgt = (tr_tgt', SeqTrace.term v_tgt f_tgt) /\\\n        List.Forall2 simple_match_event tr_src' tr_tgt' /\\\n        ValueMap.le v_tgt v_src>>) \\/\n    (<<PARTIAL: exists tr_src' tr_src_ex f_src tr_tgt' f_tgt,\n        tr_src = (tr_src' ++ tr_src_ex, SeqTrace.partial f_src) /\\\n        tr_tgt = (tr_tgt', SeqTrace.partial f_tgt) /\\\n        List.Forall2 simple_match_event tr_src' tr_tgt'>>) \\/\n    (<<UB: exists tr_src', tr_src = (tr_src', SeqTrace.ub)>>).\n  Proof.\n    induction LE.\n    { left. esplits; eauto. }\n    { right. left. esplits; eauto. refl. }\n    { right. right. esplits; eauto. }\n    des.\n    - inv TERM. inv TERM0.\n      left. esplits; eauto.\n      econs 2; eauto. econs; eauto.\n      eapply input_match_similar; eauto.\n    - inv PARTIAL. inv PARTIAL0.\n      right. left. esplits.\n      + replace ((e_src, i_src, o) :: tr_src' ++ tr_src_ex) with\n            (((e_src, i_src, o) :: tr_src') ++ tr_src_ex) by ss. refl.\n      + ss.\n      + econs 2; eauto. econs; eauto.\n        eapply input_match_similar; eauto.\n    - inv UB. right. right.\n      esplits; eauto.\n  Qed.\n\n  Lemma steps_implies\n        lang step1 step2 tr (th1 th2: SeqThread.t lang)\n        (IMPLIES: step1 <4= step2)\n        (STEPS: SeqThread.steps step1 tr th1 th2):\n    SeqThread.steps step2 tr th1 th2.\n  Proof.\n    induction STEPS; try by econs 1.\n    { econs 2; eauto. inv STEP. econs. eauto. }\n    { econs 3; eauto. }\n  Qed.\n\n  Lemma simple_match_last_inv\n        tr_src tr_tgt e_tgt\n        (MATCH: Forall2 simple_match_event tr_src (tr_tgt ++ [e_tgt])):\n    exists tr_src' e_src,\n      tr_src = tr_src' ++ [e_src] /\\\n        Forall2 simple_match_event tr_src' tr_tgt /\\\n        simple_match_event e_src e_tgt.\n  Proof.\n    revert tr_src MATCH. induction tr_tgt; ss; i.\n    { inv MATCH. inv H3. esplits; eauto. ss. }\n    inv MATCH. exploit IHtr_tgt; eauto. i. des. subst.\n    esplits; eauto. ss.\n  Qed.\n\n  Lemma rtc_step_steps_nil\n        lang step (st1: SeqState.t lang) p orc st2\n        (STEPS: rtc (step p MachineEvent.silent) st1 st2):\n    SeqThread.steps step [] (SeqThread.mk st1 p orc) (SeqThread.mk st2 p orc).\n  Proof.\n    induction STEPS; try by econs.\n    econs 2; eauto. econs. ss.\n  Qed.\n\n  Lemma steps_nil_rtc_step\n        lang step (st1: SeqState.t lang) p1 orc1 st2 p2 orc2\n        (STEPS: SeqThread.steps step [] (SeqThread.mk st1 p1 orc1) (SeqThread.mk st2 p2 orc2)):\n    rtc (step p1 MachineEvent.silent) st1 st2.\n  Proof.\n    dependent induction STEPS; eauto.\n    destruct th1. exploit IHSTEPS; eauto. i. clear IHSTEPS.\n    inv STEP. econs 2; eauto.\n  Qed.\n\n  Lemma behavior_step_inv\n        st1 p1 orc1\n        e st2 st3\n        e' i o tr r\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (NASTEPS: rtc (state_step p1 MachineEvent.silent) st1 st2)\n        (LSTEP: lang_src.(Language.step) e st2.(SeqState.state) st3)\n        (ATOMIC: is_atomic_event e)\n        (BEH: SeqBehavior.behavior state_step (SeqThread.mk st1 p1 orc1)\n                                   ((e', i, o) :: tr, r)):\n    exists th3,\n      SeqThread.at_step e' i o (SeqThread.mk st2 p1 orc1) th3.\n  Proof.\n    induction NASTEPS.\n    { inv BEH; ss; eauto.\n      inv STEP. exploit state_step_subset; eauto. intros x0.\n      inv x0. exploit deterministic_step; [|exact LSTEP|exact LANG|]; ss. i. des.\n      punfold DETERM. inv DETERM.\n      rewrite similar_is_atomic in ATOMIC; eauto;\n        try by (i; subst; eapply NO_NA_UPDATE; eauto).\n      inv LOCAL; ss; try destruct ord; ss.\n    }\n    inv BEH; ss.\n    { inv STEP. exploit state_step_determ; [|exact H|exact STEP0|]; ss. intros x0. des. subst.\n      exploit IHNASTEPS; eauto.\n      exploit state_step_subset; eauto. intros x1. inv x1. ss.\n      eapply step_deterministic; eauto.\n    }\n    { inv STEP. exploit state_step_subset; eauto. intros x.\n      inv x. exploit deterministic_step; [|exact LANG|exact LANG0|]; ss. i. des.\n      punfold DETERM. inv DETERM.\n      rewrite similar_is_atomic in ATOMIC0; eauto;\n        try by (i; subst; eapply NO_NA_UPDATE; eauto).\n      inv LOCAL; ss; try destruct ord; ss.\n    }\n  Qed.\n\n  Lemma deterministic_steps_inv\n        p1 st1 st2 e st3\n        e' i o tr orc1 st4 p4 orc4\n        (DETERM: deterministic _ st1.(SeqState.state))\n        (NASTEPS: rtc (state_step p1 MachineEvent.silent) st1 st2)\n        (LSTEP: lang_src.(Language.step) e st2.(SeqState.state) st3)\n        (ATOMIC: is_atomic_event e)\n        (STEPS: SeqThread.steps state_step ((e', i, o) :: tr)\n                                (SeqThread.mk st1 p1 orc1) (SeqThread.mk st4 p4 orc4)):\n    exists st3' p3 orc3,\n      similar e e' /\\\n      SeqThread.at_step e' i o (SeqThread.mk st2 p1 orc1) (SeqThread.mk st3' p3 orc3).\n  Proof.\n    exploit steps_cons_inv; eauto. i. des.\n    exploit steps_nil_rtc_step; eauto. i.\n    cut (similar e e' /\\ st0 = st2).\n    { i. des. subst. destruct th3. eauto. }\n    clear STEPS NASTEPS0 STEPS0. inv ATSTEP.\n    clear - state_step_subset state_step_determ DETERM NASTEPS LSTEP ATOMIC ATOMIC0 x0 LANG.\n    (* move NASTEPS at top. revert_until NASTEPS. *)\n    induction NASTEPS; ss; i.\n    { inv x0; ss.\n      - exploit deterministic_step; [|exact LSTEP|exact LANG|]; eauto. i. des. auto.\n      - exploit state_step_subset; eauto. intros x0. inv x0. ss.\n        exploit deterministic_step; [|exact LSTEP|exact LANG0|]; eauto. i. des.\n        destruct e; inv LOCAL; ss; inv x0; ss; des; subst;\n          try destruct ord; try destruct ord0; ss.\n    }\n    apply IHNASTEPS; auto.\n    { eapply rtc_state_step_deterministic; eauto. }\n    inv x0.\n    - exploit state_step_subset; try exact H. intros x. inv x.\n      exploit deterministic_step; [|exact LANG|exact LANG0|]; eauto. i. des.\n      destruct e'; inv LOCAL; ss; inv x0; ss; des; subst;\n        try destruct ord; try destruct ord0; ss.\n    - exploit state_step_determ; [|exact H|exact H0|..]; ss. i. des. subst. ss.\n  Qed.\n\n  Definition wf_in_access_old (m: SeqMemory.t) (i: option (Loc.t * Const.t * Flag.t * Const.t)): Prop :=\n    match i with\n    | Some (loc, v_old, f_old, _) =>\n      v_old = m.(SeqMemory.value_map) loc /\\\n      f_old = m.(SeqMemory.flags) loc\n    | None => True\n    end.\n\n  Lemma event_step_wf_in_access_old\n        i o p1 m1 p2 m2\n        (STEP: SeqEvent.step i o p1 m1 p2 m2):\n    wf_in_access_old m1 i.(SeqEvent.in_access).\n  Proof.\n    inv STEP; ss. inv UPD; ss. inv MEM; ss.\n  Qed.\n\n  Lemma refinement_implies_simulation_aux\n        (st_src: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n        (REFINE: forall p m o (WF: Oracle.wf o),\n            SeqTrace.incl\n              (SeqBehavior.behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_tgt m) p o))\n              (SeqBehavior.behavior state_step (SeqThread.mk (SeqState.mk _ st_src m) p o)))\n        (DETERM: deterministic _ st_src)\n        (RECEPTIVE: receptive _ st_tgt)\n        p m p1 d\n        tr_src st1_src\n        tr_tgt st0_tgt st1_tgt\n        (STEPS_SRC: state_steps state_step tr_src (SeqState.mk _ st_src m) st1_src p p1)\n        (STEPS_TGT: state_steps (@SeqState.na_step lang_tgt) tr_tgt (SeqState.mk _ st_tgt m) st0_tgt p p1)\n        (NASTEPS_TGT: rtc (SeqState.na_step p1 MachineEvent.silent) st0_tgt st1_tgt)\n        (TRACES: match_trace (min_match SeqEvent.input_match) Flags.bot d tr_src tr_tgt):\n      sim_seq (fun _ _ => True) p1 d st1_src st1_tgt.\n  Proof.\n    specialize (REFINE p m).\n    revert p1 d tr_src st1_src tr_tgt st0_tgt st1_tgt STEPS_SRC STEPS_TGT NASTEPS_TGT TRACES.\n    pcofix CIH. i. pfold.\n    destruct (classic (sim_seq_failure_case p1 st1_src)).\n    { econs 2; eauto. }\n    assert (NONUB: exists orc,\n               (<<WF: Oracle.wf orc>>) /\\\n               (forall th tr w\n                  (STEPS: SeqThread.steps (@SeqState.na_step _) tr (SeqThread.mk st1_src p1 orc) th)\n                  (TRACE: SeqThread.writing_trace tr w)\n                  (FAILURE: SeqThread.failure (@SeqState.na_step _) th),\n                 False)).\n    { clear - H. unfold sim_seq_failure_case in H.\n      apply not_all_ex_not in H. des. rename n into orc. exists orc.\n      destruct (classic (Oracle.wf orc)); cycle 1.\n      { exfalso. apply H. i. ss. }\n      split; ss. i. apply H. i. esplits; eauto.\n    }\n    des.\n\n    econs.\n    { (* terminal *)\n      ii. exploit steps_behavior_terminal; try exact STEPS_TGT; eauto.\n      { eapply (oracle_of_trace_follows tr_tgt orc). }\n      intro BEH_TGT.\n      exploit REFINE; try exact BEH_TGT.\n      { apply oracle_of_trace_wf. eapply state_steps_wf_trace; eauto. ss. }\n      intros x. des.\n      exploit trace_le_cases; eauto. i. des; try congr.\n      { (* src terminal *)\n        inv TERM0.\n        exploit steps_behavior_prefix_terminal; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des. subst.\n        esplits; try exact TERMINAL; eauto.\n        - eapply rtc_implies; try eapply state_step_subset. ss.\n        - eapply match_trace_le_terminal; eauto.\n      }\n      { (* src UB *)\n        subst.\n        exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des. subst.\n        exfalso.\n        inv ORACLE2. destruct th. ss.\n        exploit oracle_le_steps; try exact LE1; try exact STEPS. i. des.\n        exploit steps_implies; try exact x2; try apply state_step_subset. i.\n        exploit trace_le_ub_match; try eapply x0.\n        { eapply match_trace_simple_match; eauto. }\n        i. des. eapply NONUB0; eauto.\n        unfold SeqThread.failure. esplits. econs. eauto.\n      }\n    }\n\n    { (* na step *)\n      ii. destruct e.\n      { (* silent *)\n        esplits; eauto; try by econs 2.\n        right. eapply CIH; eauto. etrans; eauto.\n      }\n      { (* syscall *)\n        inv STEP_TGT. inv LOCAL; ss. destruct (p1 loc); ss.\n      }\n      { (* failure *)\n        exploit steps_behavior_ub; eauto.\n        { eapply (oracle_of_trace_follows tr_tgt orc). }\n        intro BEH_TGT.\n        exploit REFINE; try exact BEH_TGT.\n        { apply oracle_of_trace_wf; ss. eapply state_steps_wf_trace; eauto. }\n        intros x. des.\n        exploit trace_le_cases; eauto. i. des; try congr. subst.\n        exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des. subst.\n        exfalso.\n        inv ORACLE2. destruct th. ss.\n        exploit oracle_le_steps; try exact LE1; try exact STEPS. i. des.\n        exploit steps_implies; try exact x2; try apply state_step_subset. i.\n        exploit trace_le_ub_match; try eapply x0.\n        { eapply match_trace_simple_match; eauto. }\n        i. des. eapply NONUB0; eauto.\n        unfold SeqThread.failure. esplits. econs. eauto.\n      }\n    }\n\n    { (* at step *)\n      ii.\n      assert (exists (st_src1 : SeqState.t lang_src) (st_src2 : Language.state lang_src)\n                (e_src : ProgramEvent.t),\n                 rtc (state_step p1 MachineEvent.silent) st1_src st_src1 /\\\n                 Language.step lang_src e_src (SeqState.state st_src1) st_src2 /\\\n                 ProgramEvent.le e_tgt e_src).\n      { specialize (event_step_exists_full e_tgt p1 st1_tgt.(SeqState.memory)). i. des.\n        exploit steps_behavior_at_step; eauto.\n        { instantiate (2:=orc). eapply oracle_of_trace_follows. }\n        intro BEH_TGT. des.\n        exploit REFINE; try exact BEH_TGT.\n        { eapply oracle_of_trace_wf.\n          - eapply state_steps_wf_trace; eauto.\n          - eapply add_oracle_wf; eauto.\n            eapply wf_input_oracle_wf_input. ss.\n        }\n        intros x. des.\n        exploit trace_le_cases; eauto. intros x1. des; try congr; subst.\n        { (* src partial *)\n          inv PARTIAL0.\n          exploit simple_match_last_inv; try exact PARTIAL1. i. des. subst. clear PARTIAL1.\n          destruct e_src as [[e_src i_src] o_src]. inv x3.\n          rewrite <- app_assoc in x.\n          exploit steps_behavior_prefix_partial; try exact STEPS_SRC; try exact x; eauto.\n          { eapply match_trace_simple_match; eauto. }\n          { apply oracle_of_trace_follows. }\n          i. des; ss. symmetry in TRACES0. subst.\n          exploit behavior_steps_at_step; eauto. s. i. des.\n          esplits; try exact STEP; ss.\n        }\n        { (* src ub *)\n          exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n          { eapply match_trace_simple_match; eauto. }\n          { apply oracle_of_trace_follows. }\n          i. des; ss. subst. inv ORACLE2. destruct th. ss.\n          exploit add_oracle_steps_inv; try exact STEPS; eauto. i. des.\n          - exploit trace_le_ub_step_match; try eapply x0.\n            { eapply match_trace_simple_match; eauto. }\n            i. des.\n            + exfalso. eapply NONUB0.\n              * eapply steps_implies; try eapply x2. eauto.\n              * eauto.\n              * unfold SeqThread.failure. esplits. econs.\n                eapply state_step_subset; eauto.\n            + subst.\n              exploit steps_cons_inv; try exact x2. i. des.\n              exploit steps_nil_rtc_step; try exact NASTEPS. i.\n              inv ATSTEP. esplits; eauto.\n          - subst.\n            exploit steps_cons_inv; try exact STEPS. i. des.\n            exploit steps_nil_rtc_step; eauto. i. inv ATSTEP. esplits; eauto.\n        }\n      }\n\n      i. des. esplits; [eapply rtc_implies; try eapply H0|..]; eauto. i.\n      exploit steps_behavior_at_step; eauto.\n      { instantiate (2:=orc). eapply oracle_of_trace_follows. }\n      intro BEH_TGT. des.\n      exploit REFINE; try exact BEH_TGT.\n      { eapply oracle_of_trace_wf.\n        - eapply state_steps_wf_trace; eauto.\n        - eapply add_oracle_wf; eauto.\n          eapply wf_input_oracle_wf_input. ss.\n      }\n      intros x. des.\n      exploit trace_le_cases; eauto. intros x1. des; try congr; subst.\n      { (* src partial *)\n        inv PARTIAL0.\n        exploit simple_match_last_inv; try exact PARTIAL1. intros x1. des. subst. clear PARTIAL1.\n        destruct e_src0 as [[e_src0 i_src] o_src]. inv x3.\n        rewrite <- app_assoc in x.\n        exploit steps_behavior_prefix_partial; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        intros x1. des; ss. symmetry in TRACES0. subst.\n        exploit state_steps_deterministic; eauto; ss. intros x1.\n        exploit rtc_state_step_deterministic; try exact H0; eauto. i.\n        exploit rtc_state_step_behavior; try exact H0; eauto; ss. i.\n\n        exploit behavior_lang_atomic; try exact x5; eauto; ss.\n        { erewrite <- le_is_atomic; eauto. }\n        i. des.\n        exploit SeqEvent.step_inj_perms; [exact STEP_TGT0|exact MEM|..]; ss.\n        { clear - INPUT INPUT2 SIMILAR H2. i.\n          destruct i_src, i_tgt. ss. subst.\n          unfold SeqEvent.wf_input in *. ss. splitsH. clear H1 H3 H5 H6.\n          specialize (H loc2 v_new2). des. exploit H; eauto. intros x.\n          specialize (H0 loc1 v_new1). des. exploit H0; eauto. intros x0.\n          destruct e_src, e_src0, e_tgt; ss; des; subst; inv x; inv x0; ss; inv H2; ss.\n        }\n        i. subst.\n        rewrite <- app_assoc in x0.\n        exploit match_trace_le_partial_step; try exact x0; eauto. i. des.\n        exploit similar_le_eq; try exact SIMILAR; eauto. i. subst.\n        exploit SeqEvent.input_match_mon; try exact INPUT_MATCH; try exact MIN; try refl. i.\n        exploit min_input_match_exists; try exact x6. i. des.\n        esplits; try eapply MIN0; eauto.\n        right. eapply CIH; eauto.\n        - eapply state_steps_last; eauto.\n        - eapply state_steps_last; eauto.\n        - econs; eauto.\n      }\n\n      { (* src ub *)\n        exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des; ss. subst. inv ORACLE2. destruct th. ss.\n        exploit add_oracle_steps_inv; try exact STEPS; eauto. i. des.\n        { exploit trace_le_ub_step_match; try eapply x0.\n          { eapply match_trace_simple_match; eauto. }\n          i. des.\n          - exfalso. eapply NONUB0.\n            + eapply steps_implies; try eapply x2. eauto.\n            + eauto.\n            + unfold SeqThread.failure. esplits. econs.\n              eapply state_step_subset; eauto.\n          - subst.\n            hexploit min_match_trace_min; try exact MATCH; eauto. i.\n            exploit SeqEvent.input_match_mon; try exact INPUT0; eauto; try refl. i.\n            exploit min_input_match_exists; try exact x3. i. des.\n            exploit deterministic_steps_inv; try exact x2; eauto.\n            { eapply state_steps_deterministic; eauto. ss. }\n            { erewrite <- le_is_atomic; eauto. }\n            i. des.\n            exploit similar_le_eq; try exact x3; eauto. i. subst.\n            inv x1. ss.\n            exploit SeqEvent.step_inj_perms; [exact STEP_TGT0|exact MEM|..]; ss.\n            { clear - INPUT INPUT2 EVENT. i.\n              destruct i_src, i_tgt. ss. subst.\n              unfold SeqEvent.wf_input in *. ss. splitsH. clear H1 H2 H4 H5.\n              specialize (H loc2 v_new2). des. exploit H; eauto. intros x.\n              specialize (H0 loc1 v_new1). des. exploit H0; eauto. intros x0.\n              destruct e_src0, e_tgt; ss; des; subst; inv x; inv x0; ss; inv EVENT; ss.\n            }\n            i. subst. esplits; try eapply MIN; eauto.\n            right. eapply CIH; eauto.\n            + eapply state_steps_last; eauto.\n            + eapply state_steps_last; eauto.\n            + econs; eauto.\n        }\n        subst.\n\n        exploit deterministic_steps_inv; try exact STEPS; try exact H1; eauto.\n        { eapply state_steps_deterministic; eauto. ss. }\n        { erewrite <- le_is_atomic; eauto. }\n        i. des.\n        exploit similar_le_eq; try exact x2; eauto. i. symmetry in x4. subst.\n        inv x1. ss.\n        exploit SeqEvent.step_inj_perms; [exact STEP_TGT0|exact MEM|..]; ss.\n        { clear - INPUT INPUT2 EVENT. i.\n          destruct i', i_tgt. ss. subst.\n          unfold SeqEvent.wf_input in *. ss. splitsH. clear H1 H2 H4 H5.\n          specialize (H loc2 v_new2). des. exploit H; eauto. intros x.\n          specialize (H0 loc1 v_new1). des. exploit H0; eauto. intros x0.\n          destruct e_src, e_tgt; ss; des; subst; inv x; inv x0; ss; inv EVENT; ss.\n        }\n        i. subst.\n\n        cut (exists d1', SeqEvent.input_match d d1' i' i_tgt).\n        { i. des.\n          exploit min_input_match_exists; try exact H3. i. des.\n          esplits; try eapply MIN; eauto.\n          right. eapply CIH; eauto.\n          - eapply state_steps_last; eauto.\n          - eapply state_steps_last; eauto.\n          - econs; eauto.\n        }\n\n        destruct (is_acquire e_src) eqn:ACQ.\n        { exploit match_trace_le_ub_acquire; try exact x0; eauto. i. des.\n          exploit SeqEvent.input_match_mon; try exact INPUT_MATCH; eauto. refl.\n        }\n\n        cut (__guard__ (\n                 exists e_src' e_tgt' d1' i_src' i_tgt',\n                   (<<WSIMLAR: wsimilar e_tgt e_tgt'>>) /\\\n                   (<<LE': ProgramEvent.le e_tgt' e_src'>>) /\\\n                   (<<WF_SRC: SeqEvent.wf_input e_src' i_src'>>) /\\\n                   (<<WF_TGT: SeqEvent.wf_input e_tgt' i_tgt'>>) /\\\n                   (<<WF_ACCESS_SRC: wf_in_access_old m0 i_src'.(SeqEvent.in_access)>>) /\\\n                   (<<WF_ACCESS_TGT: wf_in_access_old st1_tgt.(SeqState.memory) i_tgt'.(SeqEvent.in_access)>>) /\\\n                   (<<IMATCH: SeqEvent.input_match d d1' i_src' i_tgt'>>))).\n        { exploit event_step_wf_in_access_old; try exact MEM. intro WF_OLD_SRC.\n          exploit event_step_wf_in_access_old; try exact STEP_TGT0. intro WF_OLD_TGT.\n          clear - H2 INPUT EVENT INPUT2 WF_OLD_SRC WF_OLD_TGT ACQ.\n          i. unguard. des. inv IMATCH.\n          unfold SeqEvent.wf_input in *. splitsH.\n          destruct i', i_tgt, i_src', i_tgt'. ss.\n          exists Flags.top. econs; ss.\n          - clear ACQUIRE RELEASE H1 H3 H5 H6 H8 H9 H11 H12.\n            instantiate (1:=d1). inv ACCESS.\n            + exploit wsimilar_is_accessing_loc; eauto. i. des.\n              { rewrite x0, x1 in *.\n                specialize (H loc v2). des. exploit H1; eauto. i. des. ss. }\n              exploit le_is_accessing_loc; try exact EVENT; eauto. i. des; try congr.\n              exploit le_is_accessing_loc; try exact LE'; eauto. i. des; try congr.\n              rewrite x0, x1, x3, x5 in *. ss.\n              destruct in_access as [[[[]]]|].\n              { specialize (H4 t t2). des. exploit H4; eauto. ss. }\n              destruct in_access0 as [[[[]]]|].\n              { specialize (H7 t t2). des. exploit H7; eauto. ss. }\n              econs. ss.\n            + exploit wsimilar_is_accessing_loc; eauto. i. des; cycle 1.\n              { rewrite x0, x1 in *.\n                specialize (H l v_new_tgt). des. exploit H; eauto. ss. }\n              exploit le_is_accessing_loc; try exact EVENT; eauto. i. des; try congr.\n              exploit le_is_accessing_loc; try exact LE'; eauto. i. des; try congr.\n              rewrite x0, x1, x3, x5 in *. ss.\n              destruct in_access as [[[[]]]|]; cycle 1.\n              { specialize (H4 loc0 v3). des. exploit H1; eauto. i. des. ss. }\n              destruct in_access0 as [[[[]]]|]; cycle 1.\n              { specialize (H7 loc v1). des. exploit H1; eauto. i. des. ss. }\n              inv x2. inv x4. ss. des. subst.\n              specialize (H7 loc1 v0). des. exploit H1; eauto. intros x. des. inv x.\n              specialize (H0 loc1 v5). des. exploit H3; eauto. intros x. des. inv x.\n              specialize (H4 loc1 v3). des. exploit H5; eauto. intros x. des. inv x.\n              econs; eauto.\n          - clear ACCESS RELEASE H H3 H0 H6 H4 H9 H7 H12.\n            instantiate (1:=d2).\n            exploit wsimilar_is_acquire; eauto. i.\n            exploit le_is_acquire; try exact EVENT. i.\n            exploit le_is_acquire; try exact LE'. i.\n            inv ACQUIRE.\n            + destruct in_acquire, in_acquire0, (is_acquire e_src), (is_acquire e_tgt),\n              (is_acquire e_src'), (is_acquire e_tgt'); intuition.\n              econs. ss.\n            + destruct in_acquire, in_acquire0, (is_acquire e_src), (is_acquire e_tgt),\n              (is_acquire e_src'), (is_acquire e_tgt'); intuition.\n          - clear ACCESS ACQUIRE H H1 H0 H5 H4 H8 H7 H11.\n            exploit le_is_release; try exact EVENT. i.\n            rewrite <- H12 in x0. rewrite <- H9 in x0.\n            destruct in_release, in_release0; try by intuition.\n            + destruct p, p0. econs; ss.\n              rewrite Flags.join_top_r. apply Flags.top_spec.\n            + econs. apply Flags.top_spec.\n        }\n\n        clear CIH INPUT OUTPUT STEP_TGT0 BEH_TGT x0 x STEPS FAILURE LE1 LE2 EVENT INPUT0\n              i_tgt o mem_tgt p3 i' tr' orc2 state0 perm oracle st3\n              orc3 x2 e0 i0 st1 m1 LANG ATOMIC0 EVENT0 INPUT1 ORACLE MEM INPUT2.\n        exploit receptive_oracle_progress; try exact STEP_TGT; try exact WF; eauto.\n        { eapply rtc_na_step_receptive; eauto.\n          eapply state_steps_receptive; eauto. ss.\n        }\n        i. des.\n        exploit PROGRESS.\n        { eapply (oracle_input_of_event_wf e' st1_tgt.(SeqState.memory)). }\n        i. des.\n        exploit event_step_exists; try exact WF0.\n        instantiate (1:=st1_tgt.(SeqState.memory)).\n        instantiate (1:=p1).\n        i. des.\n        exploit event_step_oracle_input; try exact STEP0; eauto. i. rewrite <- x0 in *.\n\n        exploit steps_behavior_oracle_step; try exact STEPS_TGT; try exact STEP; eauto.\n        { eapply oracle_of_trace_follows. }\n        i. exploit REFINE; try exact x1.\n        { apply oracle_of_trace_wf; ss.  eapply state_steps_wf_trace; eauto. }\n        intros x. des.\n        hexploit trace_le_cases; try exact x2. i. des; try congr.\n        { (* src partial *)\n          inv PARTIAL0.\n          exploit simple_match_last_inv; try exact PARTIAL1. i. des. subst.\n          rewrite <- app_assoc in *.\n          exploit steps_behavior_prefix_partial; try exact x; try exact STEPS_SRC; eauto.\n          { eapply match_trace_simple_match; eauto. }\n          { eapply oracle_of_trace_follows. }\n          i. des; ss. subst. inv x5.\n          exploit match_trace_le_partial_step; try exact x2; eauto. i. des.\n          exploit SeqEvent.input_match_mon; try exact INPUT_MATCH; try exact MIN; try refl. i.\n          exploit behavior_step_inv; try exact BEH_EX; eauto.\n          { eapply state_steps_deterministic; eauto. ss. }\n          { erewrite <- le_is_atomic; try exact ATOMIC; eauto. }\n          i. des. inv x6.\n          unguard. esplits; try exact x5; eauto.\n          - eapply event_step_wf_in_access_old; eauto.\n          - eapply event_step_wf_in_access_old; eauto.\n        }\n        { (* src ub *)\n          subst.\n          exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n          { eapply match_trace_simple_match; eauto. }\n          { apply oracle_of_trace_follows. }\n          i. des. subst. inv ORACLE2.\n          exploit trace_le_ub_step_match; try eapply x2.\n          { eapply match_trace_simple_match; eauto. }\n          i. des.\n          - exfalso. destruct th. ss.\n            exploit oracle_le_steps; try exact STEPS; eauto. i. des.\n            eapply NONUB0.\n            + eapply steps_implies; try eapply x5. eauto.\n            + eauto.\n            + unfold SeqThread.failure. esplits. econs.\n              eapply state_step_subset; eauto.\n          - subst. destruct th. ss.\n            exploit deterministic_steps_inv; try exact STEPS; eauto.\n            { eapply state_steps_deterministic; eauto. ss. }\n            { erewrite <- le_is_atomic; try exact ATOMIC; eauto. }\n            i. des. inv x3.\n            hexploit min_match_trace_min; try exact MATCH; eauto. i.\n            exploit SeqEvent.input_match_mon; try exact INPUT; try exact H3; try refl. i.\n            unguard. esplits; try exact x5; eauto.\n            + eapply event_step_wf_in_access_old; eauto.\n            + eapply event_step_wf_in_access_old; eauto.\n        }\n      }\n    }\n\n    { (* partial *)\n      ii. exploit steps_behavior_partial; try exact STEPS_TGT; eauto.\n      { eapply (oracle_of_trace_follows tr_tgt o). }\n      intro BEH_TGT.\n      exploit REFINE; try exact BEH_TGT.\n      { apply oracle_of_trace_wf. eapply state_steps_wf_trace; eauto. ss. }\n      intros x. des.\n      exploit trace_le_cases; eauto. i. des; try congr.\n      { (* src partial *)\n        inv PARTIAL0.\n        exploit steps_behavior_prefix_partial; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des; subst.\n        { exploit match_trace_le_partial; try exact x0; eauto. i. des.\n          exploit rtc_step_steps_nil; try exact PREFIX; eauto. i.\n          exploit steps_implies; try exact x2; try eapply state_step_subset. i.\n          esplits; try eapply x3; eauto.\n        }\n        { exploit match_trace_le_partial; try exact x0; eauto. i. des.\n          esplits; [econs 1|..]; eauto. s. left.\n          etrans; eauto. apply Flags.join_mon_r.\n          eapply na_steps_flags.\n          eapply rtc_implies; try eapply state_step_subset; eauto.\n        }\n        { exploit match_trace_le_partial; try exact x0; eauto. i. des.\n          exploit behavior_steps_partial; eauto. i. des. subst.\n          exploit steps_implies; try exact STEPS; try eapply state_step_subset. i.\n          destruct th2; ss.\n          exploit oracle_le_steps; try exact x2; eauto. i. des.\n          esplits; try exact x3; eauto.\n        }\n      }\n      { (* src UB *)\n        subst.\n        exploit steps_behavior_prefix_ub; try exact STEPS_SRC; try exact x; eauto.\n        { eapply match_trace_simple_match; eauto. }\n        { apply oracle_of_trace_follows. }\n        i. des. subst. inv ORACLE2.\n        exploit trace_le_ub_match; try exact x0.\n        { eapply match_trace_simple_match; eauto. }\n        i. des. destruct th. ss.\n        exploit steps_implies; try eapply state_step_subset; try eapply STEPS. i.\n        exploit oracle_le_steps; try exact x3; try eapply LE1. i. des.\n        esplits; eauto. s. right.\n        unfold SeqThread.failure. esplits. econs. eauto.\n      }\n    }\n  Qed.\n\n  Lemma seq_event_input_match_to_oracle_input_le\n        d d1 i_src i_tgt i0\n        (MATCH: SeqEvent.input_match d d1 i_src i_tgt)\n        (INPUT: Oracle.input_le i0 (SeqEvent.get_oracle_input i_tgt))\n    :\n    Oracle.input_le i0 (SeqEvent.get_oracle_input i_src).\n  Proof.\n    destruct i_src, i_tgt. inv MATCH. ss.\n    destruct i0; ss.\n    unfold SeqEvent.get_oracle_input, Oracle.input_le in *. ss. des. splits.\n    - clear - ACCESS ACCESS0. destruct in_access, in_access0, in_access1; ss; clarify.\n      + unfold Oracle.in_access_le in *. des_ifs. des. clarify; ss.\n        inv ACCESS. splits; auto. etrans; eauto.\n        etrans. 2: eauto. etrans. eauto. apply Flag.join_ge_l.\n      + inv ACCESS.\n      + inv ACCESS.\n    - clear - ACQUIRE ACQUIRE0. destruct in_acquire, in_acquire0, in_acquire1; ss; clarify.\n      + inv ACQUIRE.\n      + inv ACQUIRE.\n    - clear - RELEASE RELEASE0. destruct in_release, in_release0, in_release1; ss; clarify.\n      + inv RELEASE.\n      + inv RELEASE.\n  Qed.\n\n  Lemma thread_steps_app_behavior\n        th0 tr0 th1 tr1 R\n        (STEPS: SeqThread.steps (SeqState.na_step (lang:=lang_src)) tr0 th0 th1)\n        (BEH: SeqBehavior.behavior (SeqState.na_step (lang:=lang_src)) th1 (tr1, R))\n    :\n      SeqBehavior.behavior (SeqState.na_step (lang:=lang_src)) th0 (tr0 ++ tr1, R).\n  Proof.\n    depgen tr1. depgen R. induction STEPS; i; ss.\n    { econs 4; eauto. }\n    { econs 5; eauto. }\n  Qed.\n\n  Lemma sim_fail_ub\n        st p o tr d\n        (WF: Oracle.wf o)\n        (FAILURE: sim_seq_failure_case p st)\n    :\n      exists tr1 : SeqTrace.t,\n        SeqBehavior.behavior\n          (SeqState.na_step (lang:=lang_src))\n          {| SeqThread.state := st; SeqThread.perm := p; SeqThread.oracle := o |} tr1 /\\\n        SeqTrace.le d tr tr1.\n  Proof.\n    unfold sim_seq_failure_case in FAILURE. hexploit FAILURE; clear FAILURE. eauto. i; des.\n    exists (tr0, SeqTrace.ub). split.\n    2:{ eapply SeqTrace.le_ub; eauto. }\n    dup FAILURE. rename FAILURE0 into THREADFAIL.\n    unfold SeqThread.failure in FAILURE. des. inv FAILURE0.\n    replace tr0 with (tr0 ++ []).\n    2:{ apply app_nil_r. }\n    destruct st0. eapply thread_steps_app_behavior.\n    2:{ eapply SeqBehavior.behavior_ub. eauto. }\n    auto.\n  Qed.\n\n\n  Lemma simulation_implies_refinement_aux\n        (st_src: lang_src.(Language.state)) (st_tgt: lang_tgt.(Language.state))\n        p d m_src m_tgt\n        (SIM: sim_seq (fun _ _ => True) p d (SeqState.mk _ st_src m_src) (SeqState.mk _ st_tgt m_tgt))\n        o (WF: Oracle.wf o)\n        (* (RECEPTIVE: receptive _ st_tgt) (*maybe not needed*) *)\n    :\n      SeqTrace.incl\n        (SeqBehavior.behavior\n           (SeqState.na_step (lang:=lang_tgt))\n           {| SeqThread.state := {| SeqState.state := st_tgt; SeqState.memory := m_tgt |};\n              SeqThread.perm := p; SeqThread.oracle := o |})\n        (SeqBehavior.behavior\n           (SeqState.na_step (lang:=lang_src))\n           {| SeqThread.state := {| SeqState.state := st_src; SeqState.memory := m_src |};\n              SeqThread.perm := p; SeqThread.oracle := o |}).\n  Proof.\n    unfold SeqTrace.incl. i.\n    cut\n  (exists tr1 : SeqTrace.t,\n    SeqBehavior.behavior (SeqState.na_step (lang:=lang_src))\n      {| SeqThread.state := {| SeqState.state := st_src; SeqState.memory := m_src |}; SeqThread.perm := p; SeqThread.oracle := o |}\n      tr1 /\\ SeqTrace.le d tr0 tr1).\n    { i; des. esplits; eauto. eapply SeqTrace.le_deferred_mon; eauto. eapply Flags.bot_spec. }\n\n    match goal with | [H: SeqBehavior.behavior _ ?a _ |- _] => remember a as th_tgt0 end.\n    depgen st_src. depgen st_tgt. depgen o. depgen p. depgen m_src. depgen m_tgt. depgen d.\n    induction H.\n\n    4:{ i. clarify; ss.\n        punfold SIM. inv SIM.\n        2:{ eapply sim_fail_ub; eauto. }\n        inv STEP.\n        clear TERMINAL ATSTEP PARTIAL. unfold sim_seq_na_step_case in NASTEP.\n        hexploit NASTEP; clear NASTEP.\n        { eauto. }\n        i. des. pclearbot. destruct st1, st_src2. hexploit IHbehavior; clear IHbehavior.\n        2: refl. auto.\n        (* { replace state0 with (SeqState.state (SeqState.mk _ state0 memory)). 2: ss. eapply rtc_na_step_receptive. *)\n        (*   { instantiate (1:= (SeqState.mk _ st_tgt m_tgt)). ss. } *)\n        (*   econs. eauto. refl. *)\n        (* } *)\n        { eauto. }\n        i; des. esplits; eauto. eapply na_steps_behavior. 2: eauto. etrans. eauto.\n        clear -STEP. inv STEP.\n        - econs; eauto.\n        - refl.\n    }\n\n    1:{ i. clarify; ss.\n        punfold SIM. inv SIM.\n        2:{ eapply sim_fail_ub; eauto. }\n        clear NASTEP ATSTEP PARTIAL. unfold sim_seq_terminal_case in TERMINAL0. ss.\n        hexploit TERMINAL0; clear TERMINAL0.\n        { eauto. }\n        i; des. destruct m_src, st_src1. destruct memory. ss. esplits.\n        - eapply na_steps_behavior.\n          2:{ econs 1; eauto. }\n          eauto.\n        - econs 1; eauto.\n    }\n\n    2:{ i. clarify; ss.\n        punfold SIM. inv SIM.\n        2:{ eapply sim_fail_ub; eauto. }\n        unfold SeqThread.failure in FAILURE. des. inv FAILURE0.\n        clear TERMINAL ATSTEP PARTIAL. unfold sim_seq_na_step_case in NASTEP.\n        hexploit NASTEP; clear NASTEP.\n        { eauto. }\n        i. des. pclearbot. inv STEP0.\n        esplits.\n        - eapply na_steps_behavior. eauto.\n          destruct st_src1. eapply SeqBehavior.behavior_ub. unfold SeqThread.failure.\n          eexists. econs. eauto.\n        - econs 3. econs.\n    }\n\n    2:{ i. clarify; ss.\n        punfold SIM. inv SIM.\n        2:{ eapply sim_fail_ub; eauto. }\n        inv STEP.\n        clear TERMINAL NASTEP PARTIAL. unfold sim_seq_at_step_case in ATSTEP. ss.\n        hexploit ATSTEP; clear ATSTEP.\n        1,2: eauto.\n        i; des.\n        hexploit SIM; clear SIM.\n        1: eauto.\n        { punfold WF. inv WF. hexploit WF0; eauto. i; des. rewrite <- le_wf_output.\n          2: eapply EVENT. eauto. }\n        eauto.\n        i; des. pclearbot.\n        hexploit IHbehavior; clear IHbehavior.\n        2: refl.\n        { clear - WF ORACLE. punfold WF. inv WF. hexploit WF0; eauto. i; des. pclearbot. auto. }\n        (* { eapply step_receptive; eauto. } *)\n        eauto.\n        i; des. destruct tr1, st_src1. esplits.\n        - eapply na_steps_behavior. eauto. eapply SeqBehavior.behavior_at_step.\n          2: eauto.\n          ss. econs. eauto.\n          { rewrite <- le_is_atomic. eauto. etrans; eauto. refl. }\n          4,5: eauto.\n          3: eauto.\n          etrans; eauto. eapply seq_event_input_match_to_oracle_input_le; eauto.\n        - econs 4. eauto. auto. auto.\n    }\n\n    { i. clarify; ss.\n      punfold SIM. inv SIM.\n      2:{ eapply sim_fail_ub; eauto. }\n      clear TERMINAL NASTEP ATSTEP. unfold sim_seq_partial_case in PARTIAL. ss.\n      hexploit PARTIAL; clear PARTIAL. eauto. i; des.\n      2:{ destruct th. destruct state0. hexploit (SeqBehavior.behavior_ub FAILURE).\n          i. esplits.\n          - eapply thread_steps_app_behavior. 2: eapply H. eauto.\n          - econs 3. rewrite app_nil_r. eauto.\n      }\n      destruct th. destruct state0. destruct memory. ss.\n      esplits.\n      - eapply thread_steps_app_behavior. eauto. econs 2.\n      - rewrite app_nil_r. econs 2. eauto. auto.\n    }\n\n  Qed.\n\n  Lemma refinement_implies_simulation_determ\n          (st_src: lang_src.(Language.state))\n          (st_tgt: lang_tgt.(Language.state))\n          (REFINE: SeqBehavior.refine _ _ st_tgt st_src)\n          (DETERM: deterministic _ st_src)\n          (RECEPTIVE: receptive _ st_tgt)\n          (TOP: forall p m o (WF: Oracle.wf o),\n              SeqBehavior.behavior (@SeqState.na_step _) (SeqThread.mk (SeqState.mk _ st_src m) p o)\n              <1=\n              SeqBehavior.behavior state_step (SeqThread.mk (SeqState.mk _ st_src m) p o))\n    :\n      sim_seq_all (fun _ _ => True) st_src st_tgt.\n  Proof.\n    ii. eapply refinement_implies_simulation_aux; eauto; try by econs 1.\n    ii. exploit REFINE; eauto. i. des. eauto.\n  Qed.\nEnd ADEQUACY.\n\n\nTheorem simulation_implies_refinement lang_src lang_tgt\n        (st_src: lang_src.(Language.state))\n        (st_tgt: lang_tgt.(Language.state))\n        (SIM: sim_seq_all (fun _ _ => True) st_src st_tgt)\n  :\n  SeqBehavior.refine _ _ st_tgt st_src.\nProof.\n  unfold SeqBehavior.refine. i. eapply simulation_implies_refinement_aux. 2: auto.\n  unfold sim_seq_all in SIM. eauto.\nQed.\n\nTheorem refinement_implies_simulation lang_src lang_tgt\n        (st_src: lang_src.(Language.state))\n        (st_tgt: lang_tgt.(Language.state))\n        (REFINE: SeqBehavior.refine _ _ st_tgt st_src)\n        (DETERM: deterministic _ st_src)\n        (RECEPTIVE: receptive _ st_tgt)\n        (MONOTONE: monotone_read_state lang_src st_src)\n  :\n  sim_seq_all (fun _ _ => True) st_src st_tgt.\nProof.\n  eapply refinement_implies_simulation_determ; auto.\n  { i. inv PR. econs; eauto. inv LOCAL.\n    { econs 1; eauto. }\n    { econs 2; eauto. i. hexploit PERM; auto. i. subst. refl. }\n    { econs 3; eauto. }\n    { econs 4; eauto. }\n    { econs 5; eauto. }\n  }\n  { i. inv STEP0. inv STEP1.\n    punfold DETERM0. inv DETERM0.\n    hexploit STEP_STEP; [eapply LANG|eapply LANG0|..].\n    i. des. inv LOCAL; inv LOCAL0; ss.\n    { hexploit H0; eauto. i. subst. splits; auto. }\n    { des. subst. assert (val = val0).\n      { destruct (p loc0); ss.\n        { rewrite NPERM; auto. rewrite NPERM0; auto. }\n        { rewrite PERM; auto. rewrite PERM0; auto. }\n      }\n      subst. hexploit H0; eauto. i. subst. splits; auto.\n    }\n    { hexploit NO_NA_UPDATE; eauto. i. des.\n      red in ORD0. destruct ordr, ordw; des; ss.\n    }\n    { des. subst. hexploit H0; eauto. i. subst. splits; auto. }\n    { hexploit H0; eauto. i. subst. splits; auto. }\n    { hexploit NO_NA_UPDATE; eauto. i. des.\n      red in ORD. destruct ordr, ordw; des; ss.\n    }\n    { hexploit NO_NA_UPDATE; eauto. i. des. subst.\n      red in ORD. destruct ordr0, ordw0; des; ss.\n    }\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/SequentialRefinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1734596492486115}}
{"text": "From Coq Require Import String Ensembles Sorted Mergesort Permutation Classical_Prop.\nFrom RelationAlgebra Require Import prop monoid kat relalg kat_tac.\nFrom Catincoq.lib Require Import defs proprel Cat acyclic co linearext tactics relalglaws.\nFrom Catincoq.models Require rc11 sc.\nFrom Catincoq.zoo Require sc_nosm tso_nosm lamport.\nFrom Catincoq.zoo Require x86tso. (* NOT the one in models/, since we need MFENCE to be defined: *)\n\nOpen Scope string_scope.\n\nLtac destr :=\n  match goal with\n  | c : candidate |- _ =>\n    destruct c as\n     [events W R IW FW B RMW F po addr data ctrl rmw amo\n              rf loc ext int uset urel fin]\n  end.\n\nLtac destrunfold := destr; repeat autounfold with * in *.\n\nDefinition in_at {A} (l : list A) : nat -> A -> Prop :=\n  fun n x => List.nth_error l n = Some x.\n\nDefinition in_before {A} (l : list A) : A -> A -> Prop :=\n  fun x y => x = y \\/ exists n, exists m, n <= m /\\ in_at l n x /\\ in_at l m y.\n\n(** Cat idiom for inclusion *)\nLemma is_empty_included {A} (R S : relation A) : is_empty (R \u2293 !S) <-> R \u2266 S.\nProof.\n  symmetry.\n  unfold is_empty.\n  split; destruct_rel. firstorder.\n  destruct (classic (S x y)); firstorder.\nQed.\n\nInstance linearisations_weq_ (A : Type) :\n  Proper (weq --> weq --> weq --> iff) (Cat.linearisations : set A -> relation A -> set (relation A)).\nProof.\n  unfold Cat.linearisations, linear_extension_on, strict_total_order_on, strict_order, total_on, Proper, respectful, flip.\n  intros ? ? e1 ? ? e2 ? ? e3.\n  rewrite ?e1, ?e2, ?e3; tauto.\nQed.\n\nLemma linearisations_weq {A : Type} (E1 E2 : set A) (R1 R2 S1 S2 : relation A) :\n  E1 \u2261 E2 ->\n  R1 \u2261 R2 ->\n  S1 \u2261 S2 ->\n  Cat.linearisations E1 R1 S1 <->\n  Cat.linearisations E2 R2 S2.\nProof.\n  intros -> -> ->; tauto.\nQed.\n\nLtac hkat_help :=\n  repeat\n    match goal with\n    | H : ?r \u2266 [?a] \u22c5 ?r \u22c5 [?b] |- _ =>\n      let H1 := fresh H in\n      let H2 := fresh H in\n      assert (H1 : [!a] \u22c5 r \u2266 0) by (rewrite H; kat);\n      assert (H2 : r \u22c5 [!b] \u2266 0) by (rewrite H; kat);\n      clear H\n    end.\n\nLemma transitive_dot_tst_l {X} (R : relation X) (E : set X) :\n  is_transitive R -> is_transitive (R \u22c5 [E]).\nProof.\n  unfold is_transitive.\n  assert (R\u22c5[E]\u22c5(R\u22c5[E]) \u2266 R\u22c5R\u22c5[E]) as -> by kat.\n  intros ->; auto.\nQed.\n\nLemma transitive_dot_tst_r {X} (R : relation X) (E : set X) :\n  is_transitive R -> is_transitive ([E] \u22c5 R).\nProof.\n  unfold is_transitive.\n  assert ([E]\u22c5R\u22c5([E]\u22c5R) \u2266 [E]\u22c5(R\u22c5R)) as -> by kat.\n  intros ->; auto.\nQed.\n\nLemma transitive_cap {X} (R S : relation X) :\n  is_transitive R -> is_transitive S -> is_transitive (R \u2293 S).\nProof.\n  unfold is_transitive.\n  rewrite dotxcap, 2dotcapx.\n  intros -> ->.\n  lattice.\nQed.\n\nNotation \" x :: X \" := ((X : set _) x). (* TODO move/remove *)\n\nLemma ranging_spec {A} (R : relation A) (X : set A) :\n  R \u2266 R \u22c5 [X] <-> (forall x y, R x y -> X y).\nProof.\n  split; intros r x y xy.\n  - apply r in xy. types.\n  - relate. eauto.\nQed.\n\nLemma ranging_itr {A} (R : relation A) (X : set A) :\n  (forall x y, R x y -> y :: X) ->\n  (forall x y, (R^+) x y -> y :: X).\nProof.\n  rewrite <-!ranging_spec.\n  intros e; rewrite e at 1. kat.\nQed.\n\nLemma ranging_cup {A} (R S : relation A) (X : set A) :\n  (forall x y, R x y -> y :: X) ->\n  (forall x y, S x y -> y :: X) ->\n  (forall x y, (R \u2294 S) x y -> y :: X).\nProof.\n  rewrite <-!ranging_spec.\n  intros e f; rewrite e, f at 1. kat.\nQed.\n\nLemma ranging_capl {A} (R S : relation A) (X : set A) :\n  (forall x y, R x y -> y :: X) ->\n  (forall x y, (R \u2293 S) x y -> y :: X).\nProof.\n  rewrite <-!ranging_spec.\n  intros e; rewrite e at 1. destruct_rel. relate.\nQed.\n\nLemma ranging_capr {A} (R S : relation A) (X : set A) :\n  (forall x y, S x y -> y :: X) ->\n  (forall x y, (R \u2293 S) x y -> y :: X).\nProof.\n  rewrite <-!ranging_spec.\n  intros e; rewrite e at 1. destruct_rel. relate.\nQed.\n\nLemma domrng_char {A} (R : relation A) (X Y : set A) :\n  R \u2266 [X] \u22c5  R  \u22c5 [Y] <->\n  R \u2266 [X] \u22c5 top \u22c5 [Y].\nProof.\n  split. intros ->. ra. intros r x y xy. spec r x y xy. relate; types.\nQed.\n\nLemma itr_ext' {X} (R : relation X) x y : R x y -> R^+ x y.\nProof.\n  revert x y.\n  change (R \u2266 R^+).\n  ka.\nQed.\n\nLemma sc_lamport c\n      (no_atomic : rmw c \u2261 bot)\n      (no_mixed_size : unknown_relation c \"sm\" \u2261 1) :\n  sc.valid c <-> lamport.valid c.\nProof.\n  unfold sc.valid, lamport.valid.\n  (* maybe once the problem of location is solved, those will not\n  depend on the candidate so we won't need those 'pose proof's *)\n  pose proof @generate_orders_spec_3 c as GOS.\n  pose proof @generate_orders_total c as GOT.\n  pose proof @generate_orders_total' c as GOT'.\n  pose proof @generate_orders_order c as GOO.\n  pose proof @location_of_spec c as LOS.\n  destrunfold.\n  assert (loc_sym' : loc\u00b0 \u2261 loc).\n  { clear GOS GOT GOT' GOO LOS; split; destruct_rel; firstorder. }\n  split.\n\n  - (** Suppose we have a \"sc.cat\" execution, with a generated co *)\n    intros (co & Hco & atomic & sc).\n    rewrite no_mixed_size, dotx1 in sc. clear no_mixed_size no_atomic.\n    change @Cat.co_locs with @co_locs in Hco.\n    pose proof Hco as co_total%GOT.\n    pose proof Hco as co_total'%GOT'.\n    pose proof Hco as co_order%GOO.\n    apply GOS in Hco.\n    destruct Hco as (co_iwfw & co_loc & co_lin).\n    (* assert (co_loc : co \u2266 loc). *)\n    (* { transitivity ([W]\u22c5loc\u22c5[W]). rewrite co_total; ka. kat. } *)\n    assert (co_final : [W \u2293 !FW]\u22c5loc\u22c5[FW] \u2266 co).\n    { rewrite <-co_iwfw. intros x y. destruct_rel. relate. right. relate. }\n    (* assert (co_total' : [W] \u22c5 (!1 \u2293 loc) \u22c5 [W] \u2266 co \u2294 co\u00b0). *)\n    (* { rewrite capC, dotcap1_rel, co_total; try kat. *)\n    (*   destruct_rel. now left. now right. clear GOS. firstorder. } *)\n    assert (co_ww : co \u2266 [W] \u22c5 co \u22c5 [W]).\n    { apply domrng_char. transitivity ([W]\u22c5loc\u22c5[W]). 2:ra.\n      transitivity (co \u2294 co\u00b0). ra. rewrite <-co_total'. ra. }\n    assert (co_iw : co \u22c5 [IW] \u2266 0).\n    { intros w1 w2.\n      assert (([IW] \u2294 [!IW]) w1 w1).\n      { assert (a: 1 \u2266 [IW] \u2294 [!IW]) by kat. now apply a. }\n      destruct_rel.\n      - (* w1 and w2 related through IW;co;IW? no contradiction? *)\n        assert (w1 = w2) as <-. apply iw_uniq. relate. now apply co_loc.\n        assert ((co \u2294 co\u00b0) w1 w1) as f%co_total'%tst_dot_tst by (left; auto).\n        now apply f.\n      - (* w1 is not initial: then, cycle in co *)\n        exfalso.\n        assert (co w2 w1).\n        { apply co_iwfw. split. relate. now apply loc_sym, co_loc. left. relate. relate.\n          now apply loc_sym, co_loc. }\n        assert (c : co w1 w1) by now apply co_order; exists w2; auto.\n        exfalso.\n        eapply co_order. relate. eauto.\n    }\n    remember (rf\u00b0 \u22c5 co \u2293 !id) as fr.\n    set (com := fr \u2294 (rf \u2294 co)).\n    set (M := R \u2294 W).\n    set (M' := M \u2293 !IW).\n    (** We know po+com is acyclic, so we can extend it a total order *)\n    destruct (every_strict_order_can_be_total_on top (po \u2294 com)^+)\n      as (S & (St & Sirr) & lame & Stot & Sincl).\n    { intros; apply classic. }\n    { intros; apply classic. }\n    { destruct fin as [l]. exists l. intuition. }\n    { split. kat. revert sc. apply irreflexive_leq. unfold com. kat. }\n    assert (poS : po \u2266 S) by (rewrite <-Sincl; kat).\n    assert (coS : co \u2266 S) by (rewrite <-Sincl; unfold com; kat).\n    assert (frS : fr \u2266 S). now rewrite <-Sincl; unfold com; kat.\n    (** This total order is the \"S\" of the Lamport-style definition,\n     with some subtlety about initial writes *)\n    set (S' := [!IW] \u22c5 S \u22c5 [!IW]).\n    exists S'.\n    repeat apply conj; try rewrite is_empty_included.\n    (** S is indeed a \"linearisation\" *)\n    + (* transitive *)\n      unfold S'. transitivity ([!IW] \u22c5 (S \u22c5 S) \u22c5 [!IW]).\n      kat. rewrite St. auto.\n    + (* irreflexive *)\n      unfold S'. destruct_rel. apply Sirr. split. auto. reflexivity.\n    + (* domain/range *)\n      unfold S'. ra.\n    + (* totality *) unfold S', total_on. rewrite 2cnvdot, cnvtst, dotA.\n      transitivity ([!IW] \u22c5 (S \u2294 S\u00b0) \u22c5 [!IW]). 2:ka. unfold total_on in Stot.\n      rewrite <-Stot.\n      kat.\n    + (* extends [w]loc[fw] *)\n      rewrite cap_cartes.\n      cut ([W \u2293 !FW]\u22c5loc\u22c5[FW] \u2266 S). now intros ->; auto.\n      rewrite co_final. auto.\n    + (** S extends po *)\n      unfold S'. rewrite <-poS.\n      rewrite po_iw at 1.\n      kat.\n    + (** rf can be expressed in terms of S: inclusion 1 *)\n      rewrite cap_cartes.\n      rewrite cap_cartes_l.\n      set (S'' := S' \u2294 [IW]\u22c5loc\u22c5[M']).\n      set (WRS := [W]\u22c5(S'' \u2293 loc)\u22c5[R]).\n      change (rf \u2266 WRS \u2293 !(S''\u22c5WRS)).\n      apply leq_xcap.\n      * (* r <= WRS *)\n        assert (rf \u2266 loc \u2293 rf \u2293 rf) as -> by lattice.\n        assert (e: rf \u2266 (([IW] \u2294 [W \u2293 !IW]) \u22c5 rf \u22c5 [R] \u22c5 ([IW] \u2294 [R \u2293 !IW]))).\n        { clear GOS GOT GOO GOT' co_lin LOS.\n          hkat_help. (* Fail hkat. *) clear -rf_wr0 rf_wr1. hkat. }\n        rewrite e at 2.\n        ra_normalise.\n        subst WRS S'' S' M' M.\n        intros w r. destruct_rel.\n        -- relate. right. relate. left. types.\n        -- relate. exfalso. assert (w = r) as <- by now apply iw_uniq; relate.\n           apply (sc w w). relate.\n           assert (rf \u2266 (po \u2294 (fr \u2294 (rf \u2294 co)))^+) as a by ka.\n           now apply a.\n        -- relate. left. relate. apply Sincl. relate.\n           unfold com.\n           assert (rf \u2266 (po \u2294 (fr \u2294 (rf \u2294 co)))^+) as a by ka.\n           now apply a.\n        -- exfalso.\n           apply (sc w w). relate.\n           assert (rf \u22c5 co \u2266 (po \u2294 (fr \u2294 (rf \u2294 co)))^+) as a by ka.\n           apply a.\n           exists r; auto. apply co_iwfw. relate. left. relate. now apply loc_sym.\n      * (* r <= !(S'' WRS) *)\n        intros w1 r w1r [w2 w1w2 w2r].\n        assert (w1 <> w2).\n        { intros <-. unfold S'', S' in w1w2. destruct_rel.\n          eapply Sirr; split; eauto; reflexivity.\n          firstorder. }\n        types r.\n        types w1.\n        assert (w2 :: W) by (unfold WRS in *; types).\n        assert (loc w1 w2). { apply loc_trans with r. now apply rf_loc.\n          apply loc_sym. subst WRS. destruct_rel. apply loc_sym. auto. }\n        apply weq_spec, proj1 in co_total'.\n        destruct (co_total' w1 w2) as [D|D]. now relate.\n        -- assert (fr r w2).\n           { rewrite Heqfr. split. exists w1. apply w1r. apply D. intros ->.\n             (* WRS is acyclic *) subst WRS S'' S'. destruct_rel.\n             now apply (Sirr w2 w2); relate.\n             now types.\n             now apply (Sirr w2 w2); relate.\n             now types.\n           }\n           subst WRS S'' S'. clear w1w2.\n           destruct_rel.\n           ++ (* left component of WRS : S *)\n              assert (S r w2). now apply frS.\n              assert (S r r). now eapply St; exists w2; auto.\n              eapply Sirr with r r. relate.\n           ++ (* right component of WRS: IW loc M' *)\n              apply co_iw with w1 w2. exists w2; auto; relate.\n        -- subst WRS S'' S'. clear w2r.\n           destruct_rel.\n           ++ (* left component of WRS : S *)\n              assert (S w2 w1). now apply coS.\n              assert (S w1 w1). eapply St; exists w2; auto.\n              eapply Sirr with w1 w1. relate.\n           ++ (* right component of WRS: IW loc M' *)\n              apply co_iw with w2 w1. exists w1; auto. relate.\n    + (** Inclusion 2 *)\n      rewrite cap_cartes, cap_cartes_l.\n      subst S'.\n      intros w1 r [w1r short].\n      assert (r :: R). types.\n      destruct (r_rf r r ltac:(split; auto)) as [w2 _ qw].\n      types w2.\n      destruct (classic (w1 = w2)). congruence.\n      apply weq_spec, proj1 in co_total'.\n      destruct (co_total' w1 w2) as [D|D].\n      { relate. types. apply loc_trans with r. now destruct_rel.\n        apply loc_sym. now apply rf_loc. }\n      * (* w1 -co-> w2 -rf-> r, which should contradict the \"short\" hypothesis *)\n        destruct short. exists w2.\n        -- (* w1 to w2 *)\n           destruct (classic (IW w1)).\n           ++ (* w1 is initial *)\n              right. exists w2. exists w1. now split; auto. now apply co_loc.\n              split; auto. split. unfold M. right; auto.\n              intro. apply co_iw with w1 w2.\n              rewrite dot_tst. split. auto. relate.\n           ++ (* w1 is not initial *)\n              left. exists w2. exists w1. now split; auto. now apply coS.\n              split; auto. intro. apply co_iw with w1 w2.\n              rewrite dot_tst. split. auto. relate.\n        -- (* w2 to r *)\n           exists r. 2: now split; auto. exists w2. now split; auto.\n           split. 2: now apply rf_loc.\n           assert (r :: !IW). now types.\n           destruct (classic (IW w2)).\n           ++ (* w2 is initial *)\n              right. exists r. exists w2. now split; auto. now apply rf_loc.\n              split; auto. split. unfold M. left; auto. auto.\n           ++ (* w2 is not initial *)\n              left. exists r. exists w2. now split; auto.\n              assert (a: rf \u2266 S). rewrite <-Sincl. unfold com. kat. now apply a.\n              split; auto.\n      * (* w1 <-co- w2 -rf-> r, so r-fr->w1, and so r-WRS->w1 *)\n        exfalso.\n        change (co w2 w1) in D.\n        assert (fr r w1). { subst. split. now exists w2; auto.\n          unfold id. simpl. types r. types w1. intros ->. Fail now type.\n          (* cycle in w1r *) destruct_rel. now apply (Sirr w1 w1); relate.\n          types. }\n        clear short. destruct_rel.\n        -- (* in S *) apply Sirr with r r. split. apply St. exists w1.\n           now apply frS. assumption. reflexivity.\n        -- (* in IW loc M', but w1 cannot be in IW since w2 -co->w1 *)\n           eapply co_iw. exists w1. eauto. now split.\n\n  - (** Now suppose we have an execution with a Lamport-style \"S\"\n    total relation, we build a sc.cat execution, and in particular the\n    co between writes, which is S restricted to pairs of writes on the\n    same variable, with some detail accounting to initial variables *)\n    intros (S & ((Sirr, St) & Sdom & Stot & Sincl) & Spo & Srf & rfS).\n    rewrite is_empty_included in Srf, rfS, Spo.\n    pose proof antisym _ _ Srf rfS as S_rf. clear Srf rfS.\n    rewrite cap_cartes in S_rf.\n    rewrite cap_cartes_l in S_rf.\n    (** S doesn't touch any IW, so we add IW->W\\IW and ^+ *)\n    set (S_ := (S \u2294 [IW]\u22c5loc\u22c5[(R \u2294 W) \u2293 !IW])^+).\n    (* set (S_ := ([IW]\u22c5loc\u22c5[(R \u2294 W) \u2293 !IW] \u2294 1) \u22c5 S). *)\n    fold S_ in S_rf.\n    (* set (co_init := loc \u2293 [IW]\u22c5top\u22c5[(R \u2294 W) \u2293 !IW]). *)\n    set (co := [W] \u22c5 (S_ \u2293 loc) \u22c5 [W]).  (* \u2294 co_init). *)\n    exists co.\n    rewrite no_mixed_size, dotx1. clear no_mixed_size.\n    repeat apply conj.\n    + (** Properties of co *)\n      (* TODO : those are properties of co needed in the older\n      characterization of generate_orders, so we keep them here in\n      order to help proving the new characterization *)\n      assert (co_ww : co \u2266 [W]\u22c5co\u22c5[W]). {\n        unfold co. now kat.\n      }\n      assert (co_irr : co \u2293 1 \u2266 0). {\n        unfold co, S_.\n        destruct_rel.\n        cut (acyclic (S \u2294 [IW]\u22c5loc\u22c5[(R \u2294 W) \u2293 !IW])). now intros a; apply a.\n        apply acyclic_cup_excl2_l.\n        -- now rewrite Sdom; kat.\n        -- now kat.\n        -- now apply transitive_irreflexive_acyclic; auto.\n      }\n      assert (co_trans : co\u22c5co \u2266 co). {\n        apply transitive_dot_tst_l.\n        apply transitive_dot_tst_r.\n        apply transitive_cap.\n        now apply transitive_itr.\n        intros x y [z ? ?]. eapply loc_trans; eauto.\n      }\n      assert (co_loc : co \u2266 loc). {\n        subst co. rewrite leq_cap_r. kat.\n      }\n      assert (co_TODO_find_name :\n      forall x y : events, loc x y -> x :: W -> y :: W ->\n    ((loc \u2293 ([IW]\u22c5top\u22c5[W \u2293 !IW] \u2294 [W \u2293 !FW]\u22c5top\u22c5[FW])) x y -> co x y) /\\\n    (x <> y -> co x y \\/ co y x)). {\n        assert (co1 : loc \u2293 ([IW]\u22c5top\u22c5[W \u2293 !IW] \u2294 [W \u2293 !FW]\u22c5top\u22c5[FW]) \u2266 co).\n        { subst co S_.\n          rewrite <-Sincl, <-itr_ext.\n          rewrite <-(capI loc) at 1; rewrite <-capA.\n          rewrite capcup, !dotcap1_rel, !cap_cartes; try kat.\n          rewrite capC. apply cap_leq; auto.\n          apply join_leq.\n          - clear -iw_w fw_w.\n            hkat.\n          - clear -iw_w fw_w iw_fw loc_sym.\n            transitivity ([W \u2293 !FW]\u22c5loc\u22c5[FW]\u22c5([IW] \u2294 [!IW])). now kat.\n            ra_normalise.\n            apply join_leq. now hkat.\n            rewrite capC, inj_cap.\n            enough (E : [W]\u22c5loc\u22c5[FW]\u22c5[IW] \u2266 [FW]\u22c5[IW]\u22c5top). now mrewrite E; kat.\n            apply cnv_leq_iff. ra_simpl. rewrite !cnvtst.\n            rewrite inj_cap, dotA in iw_fw. rewrite <-iw_fw.\n            destruct_rel. relate. firstorder.\n        }\n        assert (co2 : [W] \u22c5 (!1 \u2293 loc) \u22c5 [W] \u2266 co \u2294 co\u00b0). {\n          subst S_ co.\n          transitivity (([IW] \u2294 [W \u2293 !IW]) \u22c5 (!1 \u2293 loc) \u22c5 ([IW] \u2294 [W \u2293 !IW])).\n          now kat.\n          ra_normalise.\n          elim_cnv.\n          rewrite loc_sym'.\n          repeat apply join_leq.\n          - rewrite dotcap1_rel; try kat.\n            assert ([W \u2293 !IW]\u22c5!1\u22c5[W \u2293 !IW] \u2261 [W]\u22c5([!IW]\u22c5!1\u22c5[!IW])\u22c5[W]) as -> by kat.\n            unfold total_on in Stot.\n            rewrite Stot.\n            destruct_rel.\n            + left. relate. apply itr_ext'. left. relate.\n            + right. relate. apply itr_ext'. left. relate.\n          - rewrite <-leq_cup_r, <-leq_cup_r, <-itr_ext.\n            destruct_rel. relate. right; types.\n          - rewrite <-leq_cup_l, <-leq_cup_r, <-itr_ext.\n            destruct_rel. relate. right; types.\n          - rewrite <-cap_cartes, <-capA, cap_cartes, iw_uniq, capC, capneg.\n            ra.\n        }\n        intros w1 w2 w1w2 Ww1 Ww2; split. apply co1.\n        intros d; apply co2.\n        relate.\n      }\n      change @Cat.cross with @cross.\n      change @Cat.co_locs with @co_locs.\n      apply GOS.\n      clear GOS GOT GOT' GOO.\n      split. 2:split. 2:easy. 2:intros l; split; [ split | split ].\n      * intros x y xy. relate.\n        apply co_TODO_find_name.\n        now apply xy.\n        now destruct_rel; relate.\n        now destruct_rel; relate.\n        now apply xy.\n      * apply is_irreflexive_spec2.\n        intros x y. destruct_rel. destruct (co_irr x x); relate.\n      * intros x z [y xy yz]. relate. apply co_trans. exists y; destruct_rel; auto.\n      * intros x y. destruct_rel. relate.\n      * intros x y. destruct_rel. relate.\n        (* assert (location_of x = location_of y). *)\n        (* assert (loc x y) by now apply LOS; congruence. *)\n        specialize (co_TODO_find_name x y).\n        destruct co_TODO_find_name as [_ [tot|tot]]; try relate.\n        now apply LOS; congruence.\n        now left; relate.\n        now right; relate.\n    + (** atomic. *)\n      unfold is_empty.\n      rewrite no_atomic; ra.\n    + (** Main acyclicity requirement, on po+com *)\n      apply acyclic_leq with S_.\n      * repeat apply join_leq.\n        -- (** po *) unfold S_. rewrite <-Spo. ka.\n        -- (** fr *)\n           intros r w2 ([w1 rw1 w1w2] & rw2). destruct_rel.\n           (** We use the totality of S *)\n           destruct (Stot r w2) as [T|T].\n           { (* Checking it's the right domain *)\n             relate.\n             - rewrite S_rf in rw1.\n               destruct_rel; try relate.\n             - subst co S_.\n               destruct_rel.\n               eapply ranging_itr; eauto.\n               apply ranging_cup.\n               + intros x y xy. apply Sdom in xy. types.\n               + intros x y xy. destruct_rel. types. relate.\n           }\n           ++ (** first case: S r w2. Then, S_ r w2 *)\n              assert (a : forall S : relation events, S \u2266 S^+) by (intro;ka). apply a.\n              left; auto.\n           ++ (** first case: S w2 r. Then rf w1 r can be shortcut\n                through w2, contradiction. *)\n              exfalso.\n              change (S w2 r) in T.\n              rewrite S_rf in rw1. destruct rw1 as [rw1 rw1']. apply rw1'.\n              exists w2.\n              ** (** First part of the path: co w1 w2 *)\n                 destruct (classic (IW w1)) as [w1i | w1ni].\n                 (* w1 initial *)\n                 { subst co. right. apply domrng_char in Sdom.\n                   relate. now destruct_rel. right; types. }\n                 (* w1 not initial *)\n                 assert (a: ([!IW] \u22c5 co) w1 w2) by relate.\n                 left. cut ([!IW]\u22c5co \u2266 S). intros H; now apply H.\n                 subst co S_.\n                 assert (S^+ \u2261 S) as <- by now apply itr_transitive.\n                 apply domrng_char in Sdom.\n                 rewrite Sdom at 1.\n                 rewrite leq_cap_l.\n                 kat.\n              ** (** Second part: we know S w2 r *)\n                 subst co.\n                 relate.\n                 now left.\n                 now apply loc_trans with w1; destruct_rel; auto; symmetry.\n        -- (** rf*) subst S_.\n           rewrite S_rf, 2leq_cap_l, <-itr_ext. kat.\n        -- (** co *)\n           unfold co. rewrite leq_cap_l. kat.\n      * (** S_ is indeed acyclic *)\n        unfold S_. rewrite acyclic_itr.\n        apply acyclic_cup. repeat apply conj.\n        -- apply transitive_irreflexive_acyclic; auto.\n        -- apply acyclic_incompatible_domain_range. now firstorder.\n        -- apply empty_acyclic. unfold is_empty.\n           rewrite itr_str_r.\n           rewrite itr_str_l.\n           clear no_atomic.\n           hkat.\nQed.\n\nLemma sc_nosm_stronger_than_x86tso c : is_transitive (po c) -> sc_nosm.valid c -> x86tso.valid c.\nProof.\n  intros Hpo.\n  unfold sc_nosm.valid, x86tso.valid.\n  intros (co & Hco & Hatom & Hsc). exists co. split. apply Hco. clear Hco.\n\n  destr; repeat autounfold with * in *.\n\n  split; [ | split ].\n  - (* sc => uniproc *)\n    revert Hsc.\n    apply acyclic_leq.\n    (* note: goal solvable by lattice *)\n    assert (po \u2293 loc \u2266 po) as -> by lattice.\n    ka.\n  - (* atomics *)\n    auto.\n  - (* sc => tso *)\n    revert Hsc.\n    apply acyclic_leq.\n    rewrite !cap_cartes.\n    assert (E0 : [empty \u2294 empty : set _] \u2261 (0 : relation events)) by kat.\n    assert (E1 : [top : set _] \u2261 (1 : relation events)) by kat.\n    rewrite E0, E1.\n    rewrite !leq_tst_1.\n    ra_normalise.\n    unfold is_transitive in Hpo. rewrite Hpo.\n    (* note: goal solvable by lattice *)\n    assert (rf \u2293 ext \u2266 rf) as -> by lattice.\n    ka.\nQed.\n\nLemma sc_nosm_stronger_than_tso_nosm c : is_transitive (po c) -> sc_nosm.valid c -> tso_nosm.valid c.\nProof.\n  intros Hpo.\n  unfold sc_nosm.valid, tso_nosm.valid.\n  intros (co & Hco & Hatom & Hsc). exists co. split. apply Hco. clear Hco.\n\n  destr.\n  repeat autounfold with * in *.\n\n  split; [ | split ].\n  - (* sc => uniproc *)\n    revert Hsc.\n    apply acyclic_leq.\n    assert (po \u2293 loc \u2266 po) as -> by lattice.\n    ka.\n  - (* atomics *)\n    auto.\n  - (* sc => tso *)\n    revert Hsc.\n    apply acyclic_leq.\n    ra_normalise.\n    rewrite !leq_tst_1.\n    unfold is_transitive in Hpo. ra_normalise. rewrite Hpo.\n    (* note: goal solvable by lattice *)\n    assert (rf \u2293 ext \u2266 rf) as -> by lattice.\n    ka.\nQed.\n\n(*\ncan sometimes be replaced with assert _ as -> by _.\nTactic Notation \"rew\" constr(e) :=\n  let E := fresh in assert (E : e); [ | rewrite E; clear E].\nTactic Notation \"rew\" constr(e) \"by\" tactic(t) :=\n  let E := fresh in assert (E : e) by t; rewrite E; clear E.\nTactic Notation \"rew\" constr(e) \"in\" hyp(H) :=\n  let E := fresh in assert (E : e); [ | rewrite E in H; clear E].\nTactic Notation \"rew\" constr(e) \"in\" hyp(H) \"by\" tactic(t) :=\n  let E := fresh in assert (E : e) by t; rewrite E in H; clear E.\n/*)\n\nLemma x86tso_stronger_than_tso_nosm c :\n  is_transitive (po c) ->\n  x86tso.valid c -> tso_nosm.valid c.\nProof.\n  intros Hpo.\n  unfold x86tso.valid, tso_nosm.valid.\n\n  intros (co & Hco & Huniproc & Hatom & Hghb). exists co; split; [ apply Hco | ].\n  split; [ | split ].\n  - (* uniproc *)\n    destrunfold.\n    revert Huniproc; apply acyclic_leq.\n    ka.\n  - (* atomic *)\n    auto.\n  - (* main *)\n    destrunfold.\n    revert Hghb; apply acyclic_leq.\n    rewrite !cap_cartes.\n    unfold empty.\n    hkat.\nQed.\n\nLemma tso_nosm_stronger_than_x86tso c :\n  [W c] \u22c5 [R c] \u2266 0 ->\n  rf c \u2266 [W c] \u22c5 rf c \u22c5 [R c] ->\n  irreflexive (po c) ->\n  is_transitive (po c) ->\n  tso_nosm.valid c -> x86tso.valid c.\nProof.\n  intros wr rf_wr po_irr po_trans.\n  unfold x86tso.valid, tso_nosm.valid.\n\n  intros (co & Hco & Huniproc & Hatom & Hghb). exists co; split; [ apply Hco | ].\n  split; [ | split ].\n  - (* uniproc *)\n    destrunfold.\n    revert Huniproc; apply acyclic_leq.\n    ka.\n  - (* atomic *)\n    auto.\n  - (* main *)\n    pose proof @generate_orders_dom c as god.\n    destrunfold.\n    set (MF := (uset _ : set _)) in Hghb. fold MF in Hghb.\n    rewrite !cap_cartes.\n\n    (* all of the complexity below is due to the fact that po[mf]po is\n     surrounded by [R+W] in tso_nosm but not in x86tso. This does not\n     matter in principle, because a cycle can escape po only through a\n     com. This intuition is formalized in [acyclic_range_domain],\n     which allows us to conclude, painfully, since range(rel) is not a\n     test *)\n    assert (E0 : [empty : set _] \u2261 (0 : relation events)) by kat.\n    assert (E1 : [top : set _] \u2261 (1 : relation events)) by kat.\n    (* simplication inside acyclic *)\n    eapply acyclic_weq.\n    { rewrite ?kat.inj_cup. ra_normalise. reflexivity. }\n    (* some simplification in Hgb *)\n    eapply acyclic_weq in Hghb; swap 1 2.\n    { rewrite ?kat.inj_cup, E0. ra_normalise. reflexivity. }\n    cut (acyclic (po\u22c5[MF]\u22c5po + (co + rf \u2229 ext + rf\u00b0\u22c5co \u2229 !id + [W]\u22c5po\u22c5[W] + [R]\u22c5po\u22c5[R \u2294 W]))).\n    { rewrite ?kat.inj_cup. apply acyclic_weq. hkat. }\n    rewrite acyclic_tst with (Dom := (R \u2294 W)) (Rng := (R \u2294 W)).\n    + (* apply acyclic_range_domain. *)\n      split.\n      { rewrite leq_tst_1.\n        apply acyclic_leq with po; ra_normalise; auto. apply acyclic_irreflexive.\n        cut (po^+ \u2261 po). intros ->; auto. apply itr_transitive; auto. }\n      assert (Hpo : (po\u22c5[MF]\u22c5po)^+ \u2266 po\u22c5[MF]\u22c5po).\n      { transitivity (po^+\u22c5[MF]\u22c5po^+). kat. rewrite itr_transitive; auto. }\n      rewrite Hpo.\n      revert Hghb; apply acyclic_leq.\n      assert ([!W] \u22c5 rf \u2266 0) by (rewrite rf_wr; kat).\n      assert (rf \u22c5 [!R] \u2266 0) by (rewrite rf_wr; kat).\n      hkat.\n    + set (frd :=  rf\u00b0\u22c5co \u2293 !id).\n      assert (co_ww : co \u2266 [W] \u22c5 co \u22c5 [W]) by now eapply god; eauto.\n      assert (frd_rw : frd \u2266 [R] \u22c5 frd \u22c5 [W]). {\n        unfold frd. rewrite co_ww, rf_wr at 1.\n        clear.\n        ra_normalise. rewrite !cnv_inj.\n        rewrite (leq_tst_1 W) at 1 2. ra_normalise.\n        rewrite dotcap1l_rel, dotcap1r_rel; kat || ra.\n      }\n      assert (rfe_wr : (rf \u2293 ext) \u2266 [W] \u22c5 (rf \u2293 ext) \u22c5 [R]). {\n        rewrite dotcap1l_rel, dotcap1r_rel. rewrite rf_wr at 1. auto. kat. kat.\n      }\n      rewrite rfe_wr, co_ww, frd_rw at 1.\n      kat.\nQed.\n\nLemma sc_nosm_stronger_than_rc11 c :\n  is_transitive (po c) ->\n  sc_nosm.valid c -> rc11.valid c.\nProof.\n  intros Hpo.\n  unfold sc_nosm.valid, rc11.valid.\n\n  intros (co & Hco & Hatom & Hsc). exists co; split; [ apply Hco | ].\n\n  split; [ | split; [ | split; [ | split; [ | split ] ] ] ].\n  - destrunfold.\n    admit.\n  - destrunfold.\n    admit.\n  - destrunfold.\n    admit.\n  - destrunfold.\n    revert Hatom.\n    apply is_empty_leq. unfold flip.\n    assert (complement' : forall A (R : relation A), complement R \u2261 !R).\n    { reflexivity || (intros; unfold complement, diff, universal; lattice). }\n    (* Fail fail rewrite complement'. *)\n    ra_normalise.\n(* c'est \u00e7a en fait ? c'est pas vrai a priori\n (\u27e6 RMW \u27e7 \u2294 rmw \u2293 (fr \u2293 !id) \u22c5 co\n         \u2266 rmw \u2293 (fre \u2293 !id) \u22c5 coe *)\n    admit.\n  - destrunfold.\n    repeat rewrite diag_inter.\n    repeat rewrite diag_union.\n    set (RLX := uset \"RLX\").\n    set (ACQ := uset \"ACQ\").\n    set (REL := uset \"REL\").\n    set (SC := uset \"SC\").\n    set (AR := uset \"ACQ_REL\").\n    Fail fail ra_normalise. (* bad idea: 8000 lines or so *)\n    set (ALL := ([ RLX ] \u2294 ([ REL ] \u2294 ([ AR ] \u2294 ([ ACQ ] \u2294 [ SC ]))))).\n    admit.\n  - destrunfold.\n    revert Hsc. apply acyclic_leq. unfold flip.\n    now lattice.\nAbort.\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/zoo/zoo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.1734596492486115}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.RefinementCommonDefinitions.\n\nRequire Import VerdiRaft.LeadersHaveLeaderLogsInterface.\nRequire Import VerdiRaft.EveryEntryWasCreatedInterface.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\nRequire Import VerdiRaft.CommonTheorems.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSection EveryEntryWasCreated.\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 {lhlli : leaders_have_leaderLogs_interface}.\n\n  Hint Constructors in_any_log : core.\n  (* proof sketch: prove for in_any_log. the only time new entries\n  come into the system is on a leader, and leaders have leaderLogs in\n  their term.  *)\n\n  Definition in_any_log_term_was_created net :=\n    forall e,\n      in_any_log net e ->\n      term_was_created net (eTerm e).\n\n  Ltac iae_case :=\n    match goal with\n      | [ H : in_any_log _ _ |- _ ] => invcs H\n    end.\n\n  Lemma term_was_created_preserved :\n    forall net net' t,\n      term_was_created net t ->\n      (forall h t ll,\n         In (t, ll) (leaderLogs (fst (nwState net h))) ->\n         In (t, ll) (leaderLogs (fst (nwState net' h)))) ->\n      term_was_created net' t.\n  Proof using. \n    intros. unfold term_was_created in *.\n    break_exists_exists. eauto.\n  Qed.\n\n  Ltac in_aer :=\n    repeat find_rewrite; eapply in_aer; eauto; repeat find_rewrite; reflexivity.\n\n  Lemma in_any_log_term_was_created_append_entries :\n    refined_raft_net_invariant_append_entries in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|\n     intros; simpl in *;\n     repeat find_higher_order_rewrite;\n     destruct_update; simpl in *; eauto;\n     rewrite update_elections_data_appendEntries_leaderLogs; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_apply_lem_hyp handleAppendEntries_log. intuition; try in_aer.\n      + repeat find_rewrite. eauto.\n      + repeat find_rewrite. do_in_app. intuition; try in_aer.\n        eauto using removeAfterIndex_in.\n    - find_eapply_lem_hyp handleAppendEntries_not_append_entries.\n      find_apply_hyp_hyp. intuition.\n      + match goal with\n          | _ : In ?p' (_ ++ _) |- _ => eapply @in_aer with (p := p'); eauto\n        end.\n      + subst. simpl in *.\n        find_false. unfold mEntries in *.\n        break_match; try congruence. subst.\n        repeat eexists; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_rewrite_lem update_elections_data_appendEntries_leaderLogs.\n      eauto.\n  Qed.\n\n  Lemma in_any_log_term_was_created_request_vote :\n    refined_raft_net_invariant_request_vote in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|\n     intros; simpl in *;\n     repeat find_higher_order_rewrite;\n     destruct_update; simpl in *; eauto;\n     rewrite leaderLogs_update_elections_data_requestVote; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_apply_lem_hyp handleRequestVote_log.\n      repeat find_rewrite. eauto.\n    - find_eapply_lem_hyp handleRequestVote_no_append_entries.\n      find_apply_hyp_hyp. intuition.\n      + match goal with\n          | _ : In ?p' (_ ++ _) |- _ => eapply @in_aer with (p := p'); eauto\n        end.\n      + subst. simpl in *.\n        find_false. unfold mEntries in *.\n        break_match; try congruence. subst.\n        repeat eexists; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_rewrite_lem leaderLogs_update_elections_data_requestVote.\n      eauto.\n  Qed.\n\n  Lemma in_any_log_term_was_created_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|\n     intros; simpl in *;\n     repeat find_higher_order_rewrite;\n     destruct_update; simpl in *; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_apply_lem_hyp handleAppendEntriesReply_log.\n      repeat find_rewrite. eauto.\n    - find_eapply_lem_hyp handleAppendEntriesReply_packets.\n      find_apply_hyp_hyp. intuition.\n      + match goal with\n          | _ : In ?p' (_ ++ _) |- _ => eapply @in_aer with (p := p'); eauto\n        end.\n      + subst. simpl in *. intuition.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n  Qed.\n\n  Lemma in_any_log_term_was_created_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|intros; simpl in *;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto;\n      eapply update_elections_data_requestVoteReply_old; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_rewrite_lem handleRequestVoteReply_log_rewrite; eauto.\n    - find_apply_hyp_hyp.\n      match goal with\n        | _ : In ?p' (_ ++ _) |- _ => eapply @in_aer with (p := p'); eauto\n      end.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n      intuition; eauto. subst.\n      find_rewrite_lem handleRequestVoteReply_log_rewrite. eauto.\n  Qed.\n\n  Ltac cr_in_log_in_leader_log :=\n    find_eapply_lem_hyp in_log; eapply_prop_hyp in_any_log_term_was_created in_any_log;\n    unfold term_was_created in *;\n    break_exists_exists;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; eauto;\n    rewrite update_elections_data_client_request_leaderLogs; eauto.\n\n  Ltac cr_in_aer_in_leader_log :=\n    find_eapply_lem_hyp in_aer; eauto; eapply_prop_hyp in_any_log_term_was_created in_any_log;\n    unfold term_was_created in *;\n    break_exists_exists;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; eauto;\n    rewrite update_elections_data_client_request_leaderLogs; eauto.\n  \n\n  Ltac cr_in_ll_in_leader_log :=\n    find_eapply_lem_hyp in_ll; eauto; eapply_prop_hyp in_any_log_term_was_created in_any_log;\n    unfold term_was_created in *;\n    break_exists_exists;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; eauto;\n    rewrite update_elections_data_client_request_leaderLogs; eauto.\n\n  Lemma in_any_log_term_was_created_client_request :\n    refined_raft_net_invariant_client_request in_any_log_term_was_created.\n  Proof using lhlli. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    iae_case.\n    - unfold term_was_created. simpl in *.\n      find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      + find_apply_lem_hyp handleClientRequest_log.\n        intuition; subst; repeat find_rewrite; try cr_in_log_in_leader_log.\n        break_exists. intuition.\n        repeat find_rewrite. simpl in *. intuition; subst.\n        * find_eapply_lem_hyp leaders_have_leaderLogs_invariant; eauto.\n          match goal with\n            | [h : name |- _ ] => (exists h)\n          end.\n          break_exists_exists.\n          repeat find_rewrite.\n          repeat find_higher_order_rewrite.\n          rewrite update_eq; auto. simpl.\n          rewrite update_elections_data_client_request_leaderLogs.\n          auto.\n        * cr_in_log_in_leader_log.\n      + cr_in_log_in_leader_log.\n    - find_apply_hyp_hyp. intuition.\n      + cr_in_aer_in_leader_log.\n      + do_in_map. subst.\n        find_eapply_lem_hyp handleClientRequest_no_append_entries; eauto.\n        simpl in *.\n        intuition. find_false.\n        unfold mEntries in *. break_match; try congruence.\n        repeat eexists; eauto.\n    - find_higher_order_rewrite.\n      destruct_update; simpl in *.\n      + find_rewrite_lem update_elections_data_client_request_leaderLogs.\n        cr_in_ll_in_leader_log.\n      + cr_in_ll_in_leader_log.\n  Qed.\n\n  \n  Lemma in_any_log_term_was_created_timeout :\n    refined_raft_net_invariant_timeout in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|intros; simpl in *;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto;\n      rewrite update_elections_data_timeout_leaderLogs; eauto]. \n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_eapply_lem_hyp handleTimeout_log_same; eauto.\n      repeat find_rewrite. eauto.\n    - find_apply_hyp_hyp. intuition; eauto.\n      do_in_map. subst. simpl in *.\n      find_eapply_lem_hyp handleTimeout_not_is_append_entries; eauto.\n      intuition. find_false.\n      unfold mEntries in *. break_match; try congruence.\n      repeat eexists; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_rewrite_lem update_elections_data_timeout_leaderLogs; eauto.\n  Qed.\n\n  Lemma in_any_log_term_was_created_do_leader :\n    refined_raft_net_invariant_do_leader in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. 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    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|intros; simpl in *;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_eapply_lem_hyp doLeader_log; eauto.\n      repeat find_rewrite. eauto.\n    - find_apply_hyp_hyp. intuition; eauto.\n      do_in_map. subst. simpl in *.\n      unfold mEntries in *. break_match; try congruence.\n      find_inversion.\n      find_eapply_lem_hyp doLeader_message_entries; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n  Qed.\n\n\n  Lemma in_any_log_term_was_created_do_generic_server :\n    refined_raft_net_invariant_do_generic_server in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. 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    eapply term_was_created_preserved; [eapply_prop in_any_log_term_was_created|];\n    [|intros; simpl in *;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto].\n    iae_case.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n      find_eapply_lem_hyp doGenericServer_log; eauto.\n      repeat find_rewrite. eauto.\n    - find_apply_hyp_hyp. intuition; eauto.\n      do_in_map. subst. simpl in *.\n      find_apply_lem_hyp doGenericServer_packets. subst.\n      simpl in *. intuition.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *; eauto.\n  Qed.\n\n\n  Lemma in_any_log_term_was_created_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset in_any_log_term_was_created.\n  Proof using. \n    red. intros. unfold in_any_log_term_was_created. intros.\n    unfold in_any_log_term_was_created, term_was_created in *.\n    iae_case.\n    - repeat find_reverse_higher_order_rewrite.\n      find_eapply_lem_hyp in_log.\n      eapply_prop_hyp in_any_log in_any_log.\n      break_exists_exists; repeat find_higher_order_rewrite; eauto.\n    - find_apply_hyp_hyp.\n      find_eapply_lem_hyp in_aer; eauto.\n      eapply_prop_hyp in_any_log in_any_log.\n      break_exists_exists; repeat find_higher_order_rewrite; eauto.\n    - repeat find_reverse_higher_order_rewrite.\n      find_eapply_lem_hyp in_ll; eauto.\n      eapply_prop_hyp in_any_log in_any_log.\n      break_exists_exists; repeat find_higher_order_rewrite; eauto.\n  Qed.\n\n\n  Lemma in_any_log_term_was_created_reboot :\n    refined_raft_net_invariant_reboot in_any_log_term_was_created.\n  Proof using. \n    red. unfold in_any_log_term_was_created, term_was_created. 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    iae_case; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *;\n      find_apply_lem_hyp in_log;\n      eapply_prop_hyp in_any_log in_any_log;\n      break_exists_exists;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto.\n    - repeat find_reverse_rewrite.\n      find_eapply_lem_hyp in_aer; eauto.\n      eapply_prop_hyp in_any_log in_any_log;\n      break_exists_exists;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto.\n    - repeat find_higher_order_rewrite.\n      destruct_update; simpl in *;\n      find_eapply_lem_hyp in_ll; eauto;\n      eapply_prop_hyp in_any_log in_any_log;\n      break_exists_exists;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *; eauto.\n  Qed.\n\n  Lemma in_any_log_term_was_created_init :\n    refined_raft_net_invariant_init in_any_log_term_was_created.\n  Proof using. \n    red. unfold in_any_log_term_was_created. intros.\n    iae_case; intuition.\n  Qed.\n\n  \n  Theorem in_any_log_term_was_created_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      in_any_log_term_was_created net.\n  Proof using lhlli rri. \n    intros.\n    eapply refined_raft_net_invariant; eauto.\n    - exact in_any_log_term_was_created_init.\n    - exact in_any_log_term_was_created_client_request.\n    - exact in_any_log_term_was_created_timeout.\n    - exact in_any_log_term_was_created_append_entries.\n    - exact in_any_log_term_was_created_append_entries_reply.\n    - exact in_any_log_term_was_created_request_vote.\n    - exact in_any_log_term_was_created_request_vote_reply.\n    - exact in_any_log_term_was_created_do_leader.\n    - exact in_any_log_term_was_created_do_generic_server.\n    - exact in_any_log_term_was_created_state_same_packet_subset.\n    - exact in_any_log_term_was_created_reboot.\n  Qed.\n\n  Instance eewci : every_entry_was_created_interface.\n  split.\n  - unfold every_entry_was_created. intros.\n    apply in_any_log_term_was_created_invariant; eauto.\n  - intros. apply in_any_log_term_was_created_invariant; auto.\n  Qed.\n\nEnd EveryEntryWasCreated.\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/EveryEntryWasCreatedProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.17345964584492204}}
{"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 DataSystem.\nRequire Import cNNRCSystem.\nRequire Import NNRC.\nRequire Import NNRCEq.\nRequire Import TNNRC.\n\nSection TNNRCEq.\n  (* A type-safe equivalence for rewrites *)\n\n  Context {m:basic_model}.\n\n  Definition tnnrc_rewrites_to (e1 e2:nnrc) : Prop :=\n    forall (\u03c4cenv \u03c4env : tbindings) (\u03c4out:rtype),\n      nnrc_type \u03c4cenv \u03c4env e1 \u03c4out ->\n      (nnrc_type \u03c4cenv \u03c4env e2 \u03c4out)\n      /\\ (forall (cenv:bindings),\n          forall (env:bindings),\n             bindings_type cenv \u03c4cenv ->\n             bindings_type env \u03c4env ->\n             @nnrc_eval _ brand_relation_brands cenv env e1\n             = @nnrc_eval _ brand_relation_brands cenv env e2).\n\n  Notation \"e1 \u21d2\u1d9c e2\" := (tnnrc_rewrites_to e1 e2) (at level 80).\n\n  Open Scope nnrc_scope.\n\n  Lemma data_normalized_bindings_type_map env \u03c4env :\n    bindings_type env \u03c4env ->\n    Forall (data_normalized brand_relation_brands) (map snd env).\n  Proof.\n    rewrite Forall_map.\n    apply bindings_type_Forall_normalized.\n  Qed.\n\n  Hint Resolve data_normalized_bindings_type_map : qcert.\n  \n  Lemma nnrc_rewrites_typed_with_untyped (e1 e2:nnrc) :\n    e1 \u2261\u1d9c e2 ->\n    (forall {\u03c4cenv: tbindings}\n            {\u03c4env: tbindings}\n            {\u03c4out:rtype}, nnrc_type \u03c4cenv \u03c4env e1 \u03c4out -> nnrc_type \u03c4cenv \u03c4env e2 \u03c4out)\n    -> e1 \u21d2\u1d9c e2.\n  Proof.\n    intros.\n    unfold tnnrc_rewrites_to; simpl; intros.\n    split; auto 2; intros.\n    apply H; qeauto.\n  Qed.\n\n  (****************\n   * Proper stuff *\n   ****************)\n\n  Hint Constructors nnrc_core_type : qcert.\n  Hint Constructors unary_op_type : qcert.\n  Hint Constructors binary_op_type : qcert.\n\n  Global Instance tnnrc_rewrites_to_pre : PreOrder tnnrc_rewrites_to.\n  Proof.\n    constructor; red; intros.\n    - unfold tnnrc_rewrites_to; intros.\n      split; try assumption; intros.\n      reflexivity.\n    - unfold tnnrc_rewrites_to in *; intros.\n      specialize (H \u03c4cenv \u03c4env \u03c4out H1).\n      elim H; clear H; intros.\n      specialize (H0 \u03c4cenv \u03c4env \u03c4out H).\n      elim H0; clear H0; intros.\n      split; try assumption; intros.\n      rewrite (H2 cenv env); try assumption.\n      rewrite (H3 cenv env); try assumption.\n      reflexivity.\n  Qed.\n  (* NNRCGetConstant *)\n\n  Global Instance tproper_NNRCGetConstant:\n    Proper (eq ==> tnnrc_rewrites_to) NNRCGetConstant.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    rewrite <- H.\n    split; try assumption.\n    intros; reflexivity.\n  Qed.\n\n  (* NNRCVar *)\n\n  Global Instance tproper_NNRCVar:\n    Proper (eq ==> tnnrc_rewrites_to) NNRCVar.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    rewrite <- H.\n    split; try assumption.\n    intros; reflexivity.\n  Qed.\n  \n  (* NNRCConst *)\n\n  Global Instance tproper_NNRCConst:\n    Proper (eq ==> tnnrc_rewrites_to) NNRCConst.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    rewrite <- H.\n    split; try assumption.\n    intros; reflexivity.\n  Qed.\n\n  (* NNRCBinop *)\n\n  Global Instance tproper_NNRCBinop:\n    Proper (eq ==> tnnrc_rewrites_to\n               ==> tnnrc_rewrites_to\n               ==> tnnrc_rewrites_to) NNRCBinop.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    rewrite H in *; clear H.\n    inversion H2; clear H2; subst.\n    econstructor; eauto.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4cenv \u03c4env \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    econstructor; eauto; intros.\n    intros.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4cenv \u03c4env \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    unfold nnrc_eval in *.\n    simpl.\n    rewrite (H3 cenv env H H2); rewrite (H4 cenv env H H2); reflexivity.\n  Qed.\n  \n  (* NNRCUnop *)\n\n  Global Instance tproper_NNRCUnop :\n    Proper (eq ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to) NNRCUnop.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    rewrite H in *; clear H.\n    inversion H1; clear H1; subst.\n    econstructor; eauto.\n    econstructor; eauto.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4\u2081 H6); elim H0; clear H0 H6; intros; assumption.\n    intros.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4\u2081 H6); elim H0; clear H0 H6; intros.\n    unfold nnrc_eval in *.\n    simpl. rewrite (H2 cenv env H H1); reflexivity.\n  Qed.\n\n  (* NNRCLet *)\n\n  Global Instance tproper_NNRCLet :\n    Proper (eq ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to) NNRCLet.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    unfold nnrc_eval,nnrc_type in *.\n    inversion H2; clear H2; subst.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4\u2081 H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4cenv ((y, \u03c4\u2081) :: \u03c4env) \u03c4out H9); elim H1; clear H1 H9; intros.\n    econstructor; eauto.\n    econstructor; eauto.\n    intros; simpl.\n    rewrite (H0 cenv env H3 H4).\n    case_eq (nnrc_core_eval brand_relation_brands cenv env (nnrc_to_nnrc_base y0));\n      intros; try reflexivity.\n    rewrite (H2 cenv ((y, d) :: env) H3); try reflexivity.\n    unfold bindings_type.\n    apply Forall2_cons; try assumption.\n    simpl; split; try reflexivity.\n    generalize (@typed_nnrc_yields_typed_data _ \u03c4cenv \u03c4\u2081 cenv env \u03c4env y0 H3 H4 H); intros.\n    elim H6; intros.\n    elim H7; clear H7; intros.\n    unfold nnrc_eval,nnrc_type in *.\n    rewrite H5 in H7.\n    inversion H7; assumption.\n  Qed.\n\n  (* NNRCFor *)\n\n  Lemma dcoll_wt (l:list data) (\u03c4:rtype) (\u03c4cenv \u03c4env:tbindings) (cenv env:bindings) (e:nnrc):\n    bindings_type cenv \u03c4cenv ->\n    bindings_type env \u03c4env ->\n    nnrc_core_type \u03c4cenv \u03c4env e (Coll \u03c4) ->\n    nnrc_core_eval brand_relation_brands cenv env e = Some (dcoll l) ->\n    forall x:data, In x l -> (data_type x \u03c4).\n  Proof.\n    intros.\n    generalize (@typed_nnrc_core_yields_typed_data _ \u03c4cenv (Coll \u03c4) cenv env \u03c4env e H H0 H1); intros.\n    elim H4; clear H4; intros.\n    elim H4; clear H4; intros.\n    rewrite H4 in H2.\n    inversion H2; clear H2.\n    subst.\n    dependent induction H5.\n    rtype_equalizer.\n    subst.\n    rewrite Forall_forall in H2.\n    apply (H2 x0 H3).\n  Qed.\n\n  Global Instance tproper_NNRCFor :\n    Proper (eq ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to) NNRCFor.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    inversion H2; clear H2; subst.\n    specialize (H0 \u03c4cenv \u03c4env (Coll \u03c4\u2081) H8); elim H0; clear H0 H8; intros.\n    specialize (H1 \u03c4cenv ((y, \u03c4\u2081) :: \u03c4env) \u03c4\u2082 H9); elim H1; clear H1 H9; intros.\n    econstructor; eauto.\n    econstructor; eauto.\n    intros; simpl.\n    unfold nnrc_eval,nnrc_type in *; simpl.\n    rewrite (H0 cenv env H3 H4).\n    case_eq (nnrc_core_eval brand_relation_brands cenv env (nnrc_to_nnrc_base y0));\n      intros; try reflexivity.\n    destruct d; try reflexivity.\n    assert (forall x, In x l -> (data_type x \u03c4\u2081))\n      by\n        (apply (dcoll_wt l \u03c4\u2081 \u03c4cenv \u03c4env cenv env (nnrc_to_nnrc_base y0)); assumption).\n    clear H5 H.\n    induction l; try reflexivity.\n    simpl in *.\n    assert (forall x : data, In x l -> data_type x \u03c4\u2081)\n      by (intros; apply (H6 x); right; assumption).\n    specialize (IHl H); clear H.\n    rewrite (H2 cenv ((y, a) :: env) H3).\n    destruct (nnrc_core_eval brand_relation_brands cenv ((y, a) :: env) (nnrc_to_nnrc_base y1)); try reflexivity.\n    - destruct ((lift_map (fun d1 : data => nnrc_core_eval brand_relation_brands cenv ((y, d1) :: env) (nnrc_to_nnrc_base x1)) l));\n      destruct ((lift_map (fun d1 : data => nnrc_core_eval brand_relation_brands cenv ((y, d1) :: env) (nnrc_to_nnrc_base y1)) l));\n      simpl in *; try congruence.\n    - unfold bindings_type.\n      apply Forall2_cons; try assumption.\n      simpl; split; try reflexivity.\n      apply (H6 a); left; reflexivity.\n  Qed.\n    \n  (* NNRCIf *)\n  Global Instance tproper_NNRCIf :\n    Proper (tnnrc_rewrites_to ==> tnnrc_rewrites_to\n                              ==> tnnrc_rewrites_to\n                              ==> tnnrc_rewrites_to) NNRCIf.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    inversion H2; clear H2; subst.\n    specialize (H \u03c4cenv \u03c4env Bool H7); elim H; clear H H7; intros.\n    specialize (H0 \u03c4cenv \u03c4env \u03c4out H9); elim H0; clear H0 H9; intros.\n    specialize (H1 \u03c4cenv \u03c4env \u03c4out H10); elim H1; clear H1 H10; intros.\n    econstructor; eauto.\n    econstructor; eauto.\n    intros; simpl.\n    unfold nnrc_eval,nnrc_type in *; simpl.\n    rewrite (H2 cenv env H5 H6). rewrite (H3 cenv env H5 H6). rewrite (H4 cenv env H5 H6).\n    reflexivity.\n  Qed.\n\n  (* NNRCEither *)\n  Global Instance tproper_NNRCEither :\n    Proper (tnnrc_rewrites_to ==> eq ==> tnnrc_rewrites_to\n                              ==> eq ==> tnnrc_rewrites_to\n                              ==> tnnrc_rewrites_to) NNRCEither.\n  Proof.\n    unfold Proper, respectful, tnnrc_rewrites_to; intros.\n    unfold nnrc_eval,nnrc_type in *; simpl.\n    subst.\n    simpl in H4.\n    inversion H4; clear H4; subst.\n    destruct (H _ _ _ H10).\n    destruct (H1 _ _ _ H11).\n    destruct (H3 _ _ _ H12).\n    clear H H1 H3.\n    simpl.\n    split; [qeauto | ]; intros.\n    rewrite H2; trivial.\n    destruct (@typed_nnrc_core_yields_typed_data _ _ _ _ _ _ _ H H1 H0) as [?[??]].\n    rewrite H3.\n    apply data_type_Either_inv in H8.\n    destruct H8 as [[?[??]]|[?[??]]]; subst.\n    - apply (H5 _ _ H). constructor; simpl; intuition; eauto.\n    - eapply (H7 _ _ H). constructor; simpl; intuition; eauto.\n  Qed.\n\n  (* NNRCGroupBy *)\n  Lemma group_by_macro_eq g sl n1 n2 :\n    NNRCGroupBy g sl n1 \u21d2\u1d9c NNRCGroupBy g sl n2\n    <-> nnrc_group_by g sl n1 \u21d2\u1d9c nnrc_group_by g sl n2.\n  Proof.\n    Opaque nnrc_group_by.\n    unfold tnnrc_rewrites_to; intros.\n    unfold nnrc_type in *.\n    unfold nnrc_eval in *.\n    split.\n    - simpl. auto.\n    - simpl. auto.\n    Transparent nnrc_group_by.\n  Qed.\n\n  Global Instance tproper_NNRCGroupBy :\n    Proper (eq ==> eq ==> tnnrc_rewrites_to ==> tnnrc_rewrites_to) NNRCGroupBy.\n  Proof.\n    unfold Proper, respectful; intros.\n    subst.\n    rewrite group_by_macro_eq.\n    unfold nnrc_group_by.\n    rewrite H1.\n    reflexivity.\n  Qed.\n\nEnd TNNRCEq.\n\nNotation \"e1 \u21d2\u1d9c e2\" := (tnnrc_rewrites_to e1 e2) (at level 80) : nnrc_scope.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/NNRC/Typing/TNNRCEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3311197462295937, "lm_q1q2_score": 0.173314813111201}}
{"text": "Require Import VerdiRaft.Raft.\n\nRequire Import VerdiRaft.LastAppliedLeCommitIndexInterface.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.CommonTheorems.\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\n\nSection LastAppliedLeCommitIndex.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Lemma lastApplied_le_commitIndex_appendEntries :\n    raft_net_invariant_append_entries lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleAppendEntries_same_lastApplied.\n    repeat find_rewrite.\n    find_apply_lem_hyp handleAppendEntries_log_detailed.\n    intuition; repeat find_rewrite; eauto;\n    eapply Nat.le_trans; eauto; eauto using Nat.le_max_l.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_appendEntriesReply :\n    raft_net_invariant_append_entries_reply lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_same_lastApplied.\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_same_commitIndex.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  \n  Lemma lastApplied_le_commitIndex_requestVote :\n    raft_net_invariant_request_vote lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleRequestVote_same_lastApplied.\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleRequestVote_same_commitIndex.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_requestVoteReply :\n    raft_net_invariant_request_vote_reply lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    rewrite handleRequestVoteReply_same_lastApplied.\n    rewrite handleRequestVoteReply_same_commitIndex. eauto.\n  Qed.\n\n\n  Lemma doLeader_same_lastApplied:\n    forall st (os : list raft_output) (d' : raft_data)\n      (ms : list (name * msg)) (h0 : name),\n      doLeader st h0 = (os, d', ms) ->\n      lastApplied d' = lastApplied st.\n  Proof using. \n    intros.\n    unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; simpl in *; find_inversion; auto.\n  Qed.\n\n  Lemma fold_left_max :\n    forall l y z,\n      (forall x, In x l ->\n            y <= x) ->\n      y <= z ->\n      y <= fold_left max l z.\n  Proof using. \n    induction l; simpl in *; auto.\n    intros.\n    specialize (IHl y (max z a)).\n    forward IHl; eauto. concludes.\n    forward IHl; [eapply Nat.le_trans; eauto; eauto using Nat.le_max_l|].\n    concludes. auto.\n  Qed.\n  \n  Lemma advanceCommitIndex_commitIndex :\n    forall st h,\n      commitIndex st <= commitIndex (advanceCommitIndex st h).\n  Proof using. \n    intros. unfold advanceCommitIndex. simpl in *.\n    apply fold_left_max; auto.\n    intros.\n    do_in_map. subst.\n    find_apply_lem_hyp filter_In.\n    repeat (intuition; do_bool).\n  Qed.\n  \n  Lemma doLeader_same_commitIndex :\n    forall st (os : list raft_output) (d' : raft_data)\n      (ms : list (name * msg)) (h0 : name),\n      doLeader st h0 = (os, d', ms) ->\n      commitIndex st <= commitIndex d'.\n  Proof using. \n    intros.\n    unfold doLeader in *.\n    repeat break_match; tuple_inversion; auto; eauto using advanceCommitIndex_commitIndex.\n    eapply Nat.le_trans; [eapply advanceCommitIndex_commitIndex with (h := h0)|]; eauto.\n  Qed.\n  \n  Lemma lastApplied_le_commitIndex_doLeader :\n    raft_net_invariant_do_leader lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp doLeader_same_lastApplied.\n    find_copy_apply_lem_hyp doLeader_same_commitIndex.\n    repeat find_rewrite. eapply Nat.le_trans; [|eauto]; eauto.\n  Qed.\n  \n  Lemma doGenericServer_lastApplied:\n    forall (h : name) \n      (st : raft_data) (out : list raft_output) (st' : raft_data)\n      (ms : list (name * msg)),\n      doGenericServer h st = (out, st', ms) ->\n      lastApplied st' <= max (lastApplied st) (commitIndex st).\n  Proof using. \n    intros. unfold doGenericServer in *. break_let. find_inversion.\n    simpl in *.\n    break_if; simpl in *; do_bool; auto.\n    - use_applyEntries_spec. subst. simpl in *.\n      eauto using Nat.le_max_r.\n    - use_applyEntries_spec. subst. simpl in *.\n      eauto using Nat.le_max_l.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_doGenericServer :\n    raft_net_invariant_do_generic_server lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp doGenericServer_commitIndex.\n    find_copy_apply_lem_hyp doGenericServer_lastApplied.\n    repeat find_rewrite.\n    erewrite Nat.max_r in *; eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_clientRequest :\n    raft_net_invariant_client_request lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleClientRequest_commitIndex.\n    find_copy_apply_lem_hyp handleClientRequest_lastApplied.\n    repeat find_rewrite. eauto.\n  Qed.\n  \n\n  Lemma lastApplied_le_commitIndex_timeout :\n    raft_net_invariant_timeout lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp handleTimeout_commitIndex.\n    find_copy_apply_lem_hyp handleTimeout_lastApplied.\n    repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_reboot :\n    raft_net_invariant_reboot lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    subst.\n    simpl in *. repeat find_reverse_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lastApplied_le_commitIndex_init :\n    raft_net_invariant_init lastApplied_le_commitIndex.\n  Proof using. \n    red. unfold lastApplied_le_commitIndex. intros.\n    simpl in *. auto.\n  Qed.\n\n  Theorem lastApplied_le_commitIndex_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      lastApplied_le_commitIndex net.\n  Proof using. \n    intros. apply raft_net_invariant; auto.\n    - apply lastApplied_le_commitIndex_init.\n    - apply lastApplied_le_commitIndex_clientRequest.\n    - apply lastApplied_le_commitIndex_timeout.\n    - apply lastApplied_le_commitIndex_appendEntries.\n    - apply lastApplied_le_commitIndex_appendEntriesReply.\n    - apply lastApplied_le_commitIndex_requestVote.\n    - apply lastApplied_le_commitIndex_requestVoteReply.\n    - apply lastApplied_le_commitIndex_doLeader.\n    - apply lastApplied_le_commitIndex_doGenericServer.\n    - apply lastApplied_le_commitIndex_state_same_packet_subset.\n    - apply lastApplied_le_commitIndex_reboot.\n  Qed.\n  \n  Instance lalcii : lastApplied_le_commitIndex_interface.\n  split. auto using lastApplied_le_commitIndex_invariant.\n  Qed.\n\nEnd LastAppliedLeCommitIndex.\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/LastAppliedLeCommitIndexProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.17299967809818959}}
{"text": "Require Import PeanoNat Lia List ListSupport.\nRequire Import Common FMap.\nRequire Import Syntax Semantics SemFacts StepM Invariant.\nRequire Import Serial SerialFacts.\nRequire Import Reduction Commutativity QuasiSeq Topology.\nRequire Import RqRsTopo RqRsFacts.\nRequire Import RqRsInvMsg RqRsInvLock RqRsInvAtomic RqRsInvSep.\n\n(* Required to prove serializability *)\nRequire Import RqRsRed RqUpRed RsUpRed RqDownRed RsDownRed.\n(* Required to prove nonmergeability *)\nRequire Import RqRsInvLockEx.\n\nSet Implicit Arguments.\n\nOpen Scope list.\nOpen Scope fmap.\n\nSection Pushable.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n  Variables (dtr: DTree)\n            (sys: System).\n\n  Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n             (oinvs: IdxT -> ObjInv)\n             (Hoinvs: InvReachable sys step_m (liftObjInvs oinvs))\n             (Hrrs: RqRsSys dtr sys oinvs).\n\n  Variables (phst: History)\n            (oidx ridx: IdxT)\n            (rins routs: list (Id Msg)).\n  Hypothesis (Hcont: ExtContinuousL sys phst (RlblInt oidx ridx rins routs)).\n\n  Local Definition nlbl := (RlblInt oidx ridx rins routs).\n\n  Section RqUp.\n    Hypothesis (Hru: RqUpMsgs dtr oidx rins).\n\n    Lemma rqUp_lpush_unit:\n      forall hst,\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        Reducible sys (hst ++ phst) (phst ++ hst).\n    Proof.\n      intros.\n      destruct H as [inits [ins [outs [eouts ?]]]].\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H2; inv H2.\n      destruct H1 as [pinits pins phst pouts peouts].\n      red in H0; dest.\n      pose proof (atomic_unique H0 H2); dest; subst.\n      pose proof (atomic_unique H5 H); dest; subst.\n      eapply rqUp_lpush_unit_reducible; eauto.\n      intro Hx; subst; elim H3; apply SubList_nil.\n    Qed.\n\n    Lemma rqUp_LPushableHst: LPushableHst sys phst nlbl.\n    Proof.\n      intros; red; intros.\n      inv H1; clear H8.\n      generalize dependent st3.\n      induction hsts; simpl; intros; [constructor|].\n      inv H0; inv H2.\n      rewrite <-app_assoc in H6.\n      eapply steps_split in H6; [|reflexivity].\n      destruct H6 as [sti [? ?]].\n      constructor; eauto.\n      intros; eapply rqUp_lpush_unit; eauto.\n    Qed.\n\n    Lemma rqUp_WellInterleavedHst: WellInterleavedHst sys phst nlbl.\n    Proof.\n      apply LPushableHst_WellInterleavedHst; auto.\n      eauto using rqUp_LPushableHst.\n    Qed.\n\n  End RqUp.\n\n  Section RsUp.\n    Hypothesis (Hru: RsUpMsgs dtr oidx rins).\n\n    Definition RsUpP: State -> Prop :=\n      fun st => Forall (InMPI st.(st_msgs)) rins.\n\n    Lemma rsUp_PInitializing:\n      PInitializing sys RsUpP phst.\n    Proof.\n      intros; red; intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n      inv H0.\n      red; eapply SubList_forall; [|eassumption].\n      eapply atomic_messages_eouts_in; eauto.\n    Qed.\n\n    Lemma rsUp_PPreserving:\n      forall hst,\n        Discontinuous phst hst ->\n        PPreserving sys RsUpP hst.\n    Proof.\n      intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n      inv H0.\n      destruct H as [inits1 [ins1 [outs1 [eouts1 [inits2 [ins2 [outs2 [eouts2 ?]]]]]]]].\n      dest.\n      eapply atomic_unique in H; [|eassumption]; dest; subst.\n\n      red; intros.\n      eapply atomic_messages_ins_ins.\n      - eapply H0.\n      - eassumption.\n      - assumption.\n      - eapply DisjList_comm, DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rsUp_rpush_unit:\n      forall hst,\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        ReducibleP sys RsUpP (nlbl :: hst) (hst ++ [nlbl]).\n    Proof.\n      intros.\n      destruct H as [inits [ins [outs [eouts ?]]]].\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H2; inv H2.\n      destruct H1 as [pinits pins phst pouts peouts].\n      red in H0; dest.\n      pose proof (atomic_unique H0 H2); dest; subst.\n      pose proof (atomic_unique H5 H); dest; subst.\n      eapply rsUp_rpush_unit_reducible; eauto.\n      - intro Hx; subst; elim H3; apply SubList_nil.\n      - eapply DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rsUp_RPushableHst:\n      RPushableHst sys RsUpP phst nlbl.\n    Proof.\n      intros; red; intros.\n      inv H1.\n      eapply steps_split in H6; [|reflexivity].\n      destruct H6 as [st4 [? ?]]; clear H1.\n      generalize dependent st4.\n      induction hsts as [|hst hsts] using list_ind_rev;\n        simpl; intros; [constructor|].\n\n      apply Forall_app_inv in H0; dest.\n      inv H1; clear H7.\n      apply Forall_app_inv in H2; dest.\n      inv H2; clear H9.\n\n      rewrite concat_app in H3; simpl in H3.\n      rewrite app_nil_r in H3.\n      eapply steps_split in H3; [|reflexivity].\n      destruct H3 as [sti [? ?]].\n\n      apply Forall_app; eauto.\n      constructor; auto.\n      split.\n      - apply rsUp_PPreserving; auto.\n      - intros; eapply rsUp_rpush_unit; eauto.\n    Qed.\n\n    Lemma rsUp_WellInterleavedHst:\n      WellInterleavedHst sys phst nlbl.\n    Proof.\n      apply RPushableHst_WellInterleavedHst with (P:= RsUpP); auto.\n      - eauto using rsUp_PInitializing.\n      - eauto using rsUp_RPushableHst.\n    Qed.\n\n  End RsUp.\n\n  Section RqDown.\n    Variable pobj: Object.\n    Hypothesis (Hrd: RqDownMsgs dtr sys oidx rins)\n               (Hpobj: In pobj sys.(sys_objs))\n               (Hcp: parentIdxOf dtr oidx = Some (obj_idx pobj)).\n\n    Definition RqDownLPush (hst: History) :=\n      exists loidx,\n        lastOIdxOf hst = Some loidx /\\\n        In loidx (subtreeIndsOf dtr oidx).\n\n    Definition RqDownRPush (hst: History) :=\n      exists loidx,\n        lastOIdxOf hst = Some loidx /\\\n        ~ In loidx (subtreeIndsOf dtr oidx).\n\n    Lemma rqDown_PInitializing:\n      PInitializing sys (RqDownP rins) phst.\n    Proof.\n      intros; red; intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n      inv H0.\n      red; eapply SubList_forall; [|eassumption].\n      eapply atomic_messages_eouts_in; eauto.\n    Qed.\n\n    Lemma rqDown_discontinuous_PPreserving:\n      forall hst,\n        Discontinuous phst hst ->\n        PPreserving sys RsUpP hst.\n    Proof.\n      intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n\n      inv H0.\n      destruct H as [inits1 [ins1 [outs1 [eouts1 [inits2 [ins2 [outs2 [eouts2 ?]]]]]]]].\n      dest.\n      eapply atomic_unique in H; [|eassumption]; dest; subst.\n\n      red; intros.\n      eapply atomic_messages_ins_ins.\n      - eapply H0.\n      - eassumption.\n      - assumption.\n      - eapply DisjList_comm, DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rqDown_PPreserving:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (PPreserving sys (RqDownP rins)) hsts.\n    Proof.\n      intros.\n      eapply Forall_impl; [|eapply H2].\n      simpl; intros hst ?.\n      eapply rqDown_discontinuous_PPreserving; assumption.\n    Qed.\n\n    Lemma rqDown_lpush_or_rpush:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RqDownLPush hst \\/ RqDownRPush hst) hsts.\n    Proof.\n      intros; clear -H0.\n      rewrite Forall_forall in H0.\n      apply Forall_forall.\n      intros hst ?.\n      specialize (H0 _ H).\n      destruct H0 as [inits [ints [outs [eouts ?]]]].\n      apply atomic_lastOIdxOf in H0.\n      destruct H0 as [loidx ?].\n      destruct (in_dec idx_dec loidx (subtreeIndsOf dtr oidx)).\n      - left; red; eauto.\n      - right; red; eauto.\n    Qed.\n\n    Lemma rqDown_lpush_unit:\n      forall hst,\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        RqDownLPush hst ->\n        Reducible sys (hst ++ phst) (phst ++ hst).\n    Proof.\n      intros.\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H3; inv H3.\n      inv H2.\n      destruct H0 as [inits1 [ins1 [outs1 [eouts1 ?]]]].\n      destruct H0 as [inits2 [ins2 [outs2 [eouts2 ?]]]]; dest.\n      pose proof (atomic_unique H6 H0); dest; subst; clear H0.\n      destruct H1 as [loidx [? ?]].\n      eapply rqDown_lpush_unit_reducible; eauto.\n      apply rqDown_PInitializing.\n    Qed.\n\n    Lemma rqDown_lpush_reducible:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RqDownLPush hst ->\n                             Reducible sys (hst ++ phst) (phst ++ hst)) hsts.\n    Proof.\n      intros.\n      inv_steps.\n      eapply steps_split in H6; [|reflexivity].\n      destruct H6 as [sti [? ?]].\n      clear H8.\n      generalize dependent st3.\n      induction hsts as [|hst hsts]; simpl; intros; [constructor|].\n      inv H0; inv H2.\n      eapply steps_split in H3; [|reflexivity].\n      destruct H3 as [hsti [? ?]].\n      specialize (IHhsts H7 H8 _ H0).\n      constructor; [|assumption].\n      intros; apply rqDown_lpush_unit; auto.\n    Qed.\n\n    Lemma rqDown_rpush_unit:\n      forall hst,\n        RqDownRPush hst ->\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        ReducibleP sys (RqDownP rins) (nlbl :: hst) (hst ++ [nlbl]).\n    Proof.\n      intros.\n      destruct H0 as [inits [ins [outs [eouts ?]]]].\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H3; inv H3.\n      destruct H2 as [pinits pins phst pouts peouts].\n      red in H1; dest.\n      pose proof (atomic_unique H1 H3); dest; subst; clear H3.\n      pose proof (atomic_unique H6 H0); dest; subst; clear H6.\n      destruct H as [loidx [? ?]].\n      eapply rqDown_rpush_unit_reducible; eauto.\n      eapply DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rqDown_rpush_reducible:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RqDownRPush hst ->\n                             ReducibleP sys (RqDownP rins) (nlbl :: hst) (hst ++ [nlbl])) hsts.\n    Proof.\n      intros.\n      clear H1.\n      induction hsts as [|hst hsts]; simpl; intros; [constructor|].\n      inv H0; inv H2.\n      constructor; eauto.\n      intros; eapply rqDown_rpush_unit; eauto.\n    Qed.\n\n    Lemma rqDown_LRPushable:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          LRPushable sys (RqDownP rins) RqDownLPush RqDownRPush hsts.\n    Proof.\n      intros; red; intros; subst.\n      apply Forall_app_inv in H0; dest.\n      inv H3; destruct H8 as [inits1 [ins1 [outs1 [eouts1 ?]]]].\n      apply Forall_app_inv in H9; dest.\n      inv H7; destruct H10 as [inits2 [ins2 [outs2 [eouts2 ?]]]].\n      destruct H4 as [lloidx [? ?]].\n      destruct H5 as [rloidx [? ?]].\n\n      assert (DisjList rins inits1 /\\ DisjList rins inits2).\n      { destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n        apply eq_sym in H12; inv H12.\n        apply Forall_app_inv in H2; dest.\n        inv H12; apply Forall_app_inv in H18; dest.\n        inv H15.\n        red in H17, H19; dest.\n        pose proof (atomic_unique H19 H3); dest; subst; clear H19.\n        pose proof (atomic_unique H16 H7); dest; subst; clear H16.\n        inv H10.\n        pose proof (atomic_unique H17 H19); dest; subst; clear H17.\n        pose proof (atomic_unique H15 H19); dest; subst; clear H15.\n        split; eapply DisjList_SubList; eassumption.\n      }\n      destruct H10.\n      eapply rqDown_LRPushable_unit_reducible; try eassumption.\n    Qed.\n\n    Lemma rqDown_WellInterleavedHst:\n      WellInterleavedHst sys phst nlbl.\n    Proof.\n      apply PushableHst_WellInterleavedHst with (P:= RqDownP rins); auto.\n      - eauto using rqDown_PInitializing.\n      - exists RqDownLPush, RqDownRPush.\n        intros; repeat split.\n        + eauto using rqDown_PPreserving.\n        + eauto using rqDown_lpush_or_rpush.\n        + eauto using rqDown_lpush_reducible.\n        + eauto using rqDown_rpush_reducible.\n        + eauto using rqDown_LRPushable.\n    Qed.\n\n  End RqDown.\n\n  Section RsDown.\n    Variable pobj: Object.\n    Hypothesis (Hrd: RsDownMsgs dtr sys oidx rins)\n               (Hpobj: In pobj sys.(sys_objs))\n               (Hcp: parentIdxOf dtr oidx = Some (obj_idx pobj)).\n\n    Definition RsDownLPush (hst: History) :=\n      exists loidx,\n        lastOIdxOf hst = Some loidx /\\\n        In loidx (subtreeIndsOf dtr oidx).\n\n    Definition RsDownRPush (hst: History) :=\n      exists loidx,\n        lastOIdxOf hst = Some loidx /\\\n        ~ In loidx (subtreeIndsOf dtr oidx).\n\n    Lemma rsDown_PInitializing:\n      PInitializing sys (RsDownP rins) phst.\n    Proof.\n      intros; red; intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n      inv H0.\n      red; eapply SubList_forall; [|eassumption].\n      eapply atomic_messages_eouts_in; eauto.\n    Qed.\n\n    Lemma rsDown_discontinuous_PPreserving:\n      forall hst,\n        Discontinuous phst hst ->\n        PPreserving sys RsUpP hst.\n    Proof.\n      intros.\n      destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H1; inv H1.\n\n      inv H0.\n      destruct H as [inits1 [ins1 [outs1 [eouts1 [inits2 [ins2 [outs2 [eouts2 ?]]]]]]]].\n      dest.\n      eapply atomic_unique in H; [|eassumption]; dest; subst.\n\n      red; intros.\n      eapply atomic_messages_ins_ins.\n      - eapply H0.\n      - eassumption.\n      - assumption.\n      - eapply DisjList_comm, DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rsDown_PPreserving:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (PPreserving sys (RsDownP rins)) hsts.\n    Proof.\n      intros.\n      eapply Forall_impl; [|eapply H2].\n      simpl; intros hst ?.\n      eapply rsDown_discontinuous_PPreserving; assumption.\n    Qed.\n\n    Lemma rsDown_lpush_or_rpush:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RsDownLPush hst \\/ RsDownRPush hst) hsts.\n    Proof.\n      intros; clear -H0.\n      rewrite Forall_forall in H0.\n      apply Forall_forall.\n      intros hst ?.\n      specialize (H0 _ H).\n      destruct H0 as [inits [ints [outs [eouts ?]]]].\n      apply atomic_lastOIdxOf in H0.\n      destruct H0 as [loidx ?].\n      destruct (in_dec idx_dec loidx (subtreeIndsOf dtr oidx)).\n      - left; red; eauto.\n      - right; red; eauto.\n    Qed.\n\n    Lemma rsDown_lpush_unit:\n      forall hst,\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        RsDownLPush hst ->\n        Reducible sys (hst ++ phst) (phst ++ hst).\n    Proof.\n      intros.\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H3; inv H3.\n      inv H2.\n      destruct H0 as [inits1 [ins1 [outs1 [eouts1 ?]]]].\n      destruct H0 as [inits2 [ins2 [outs2 [eouts2 ?]]]]; dest.\n      pose proof (atomic_unique H6 H0); dest; subst; clear H0.\n      destruct H1 as [loidx [? ?]].\n      eapply rsDown_lpush_unit_reducible; eauto.\n      apply rsDown_PInitializing.\n    Qed.\n\n    Lemma rsDown_lpush_reducible:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RsDownLPush hst ->\n                             Reducible sys (hst ++ phst) (phst ++ hst)) hsts.\n    Proof.\n      intros.\n      inv_steps.\n      eapply steps_split in H6; [|reflexivity].\n      destruct H6 as [sti [? ?]].\n      clear H8.\n      generalize dependent st3.\n      induction hsts as [|hst hsts]; simpl; intros; [constructor|].\n      inv H0; inv H2.\n      eapply steps_split in H3; [|reflexivity].\n      destruct H3 as [hsti [? ?]].\n      specialize (IHhsts H7 H8 _ H0).\n      constructor; [|assumption].\n      intros; apply rsDown_lpush_unit; auto.\n    Qed.\n\n    Lemma rsDown_rpush_unit:\n      forall hst,\n        RsDownRPush hst ->\n        AtomicEx hst ->\n        Discontinuous phst hst ->\n        ReducibleP sys (RsDownP rins) (nlbl :: hst) (hst ++ [nlbl]).\n    Proof.\n      intros.\n      destruct H0 as [inits [ins [outs [eouts ?]]]].\n      destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n      apply eq_sym in H3; inv H3.\n      destruct H2 as [pinits pins phst pouts peouts].\n      red in H1; dest.\n      pose proof (atomic_unique H1 H3); dest; subst; clear H3.\n      pose proof (atomic_unique H6 H0); dest; subst; clear H6.\n      destruct H as [loidx [? ?]].\n      eapply rsDown_rpush_unit_reducible; eauto.\n      eapply DisjList_SubList; eauto.\n    Qed.\n\n    Lemma rsDown_rpush_reducible:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          Forall (fun hst => RsDownRPush hst ->\n                             ReducibleP sys (RsDownP rins) (nlbl :: hst) (hst ++ [nlbl])) hsts.\n    Proof.\n      intros.\n      clear H1.\n      induction hsts as [|hst hsts]; simpl; intros; [constructor|].\n      inv H0; inv H2.\n      constructor; eauto.\n      intros; eapply rsDown_rpush_unit; eauto.\n    Qed.\n\n    Lemma rsDown_LRPushable:\n      forall st1,\n        Reachable (steps step_m) sys st1 ->\n        forall hsts st2,\n          Forall AtomicEx hsts ->\n          steps step_m sys st1 (nlbl :: List.concat hsts ++ phst) st2 ->\n          Forall (fun hst => Discontinuous phst hst) hsts ->\n          LRPushable sys (RsDownP rins) RsDownLPush RsDownRPush hsts.\n    Proof.\n      intros; red; intros; subst.\n      apply Forall_app_inv in H0; dest.\n      inv H3; destruct H8 as [inits1 [ins1 [outs1 [eouts1 ?]]]].\n      apply Forall_app_inv in H9; dest.\n      inv H7; destruct H10 as [inits2 [ins2 [outs2 [eouts2 ?]]]].\n      destruct H4 as [lloidx [? ?]].\n      destruct H5 as [rloidx [? ?]].\n\n      assert (DisjList rins inits1 /\\ DisjList rins inits2).\n      { destruct Hcont as [peouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n        apply eq_sym in H12; inv H12.\n        apply Forall_app_inv in H2; dest.\n        inv H12; apply Forall_app_inv in H18; dest.\n        inv H15.\n        red in H17, H19; dest.\n        pose proof (atomic_unique H19 H3); dest; subst; clear H19.\n        pose proof (atomic_unique H16 H7); dest; subst; clear H16.\n        inv H10.\n        pose proof (atomic_unique H17 H19); dest; subst; clear H17.\n        pose proof (atomic_unique H15 H19); dest; subst; clear H15.\n        split; eapply DisjList_SubList; eassumption.\n      }\n      destruct H10.\n      eapply rsDown_LRPushable_unit_reducible; try eassumption.\n    Qed.\n\n    Lemma rsDown_WellInterleavedHst:\n      WellInterleavedHst sys phst nlbl.\n    Proof.\n      apply PushableHst_WellInterleavedHst with (P:= RqDownP rins); auto.\n      - eauto using rsDown_PInitializing.\n      - exists RqDownLPush, RqDownRPush.\n        intros; repeat split.\n        + eauto using rsDown_PPreserving.\n        + eauto using rsDown_lpush_or_rpush.\n        + eauto using rsDown_lpush_reducible.\n        + eauto using rsDown_rpush_reducible.\n        + eauto using rsDown_LRPushable.\n    Qed.\n\n  End RsDown.\n\n  Lemma rqDown_ExtContinuousL_parent_in_system:\n    RqDownMsgs dtr sys oidx rins ->\n    forall st1,\n      Reachable (steps step_m) sys st1 ->\n      forall st2,\n        steps step_m sys st1 phst st2 ->\n        exists pobj,\n          In pobj (sys_objs sys) /\\\n          parentIdxOf dtr oidx = Some (obj_idx pobj).\n  Proof.\n    destruct Hrrs as [? [? ?]]; intros.\n    destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n    apply eq_sym in H6; inv H6.\n    destruct H5 as [pinits pins phst pouts peouts].\n    destruct H2 as [cobj [rqDown ?]]; dest; subst.\n    pose proof (edgeDownTo_Some (proj1 (proj2 H)) _ H10).\n    destruct H2 as [rqUp [rsUp [pidx ?]]]; dest.\n    eapply atomic_down_out_in_history in H6; eauto.\n    - eapply steps_object_in_system in H6; eauto.\n      destruct H6 as [pobj [? ?]]; subst.\n      exists pobj; auto.\n    - apply SubList_singleton_In in H8.\n      apply in_map; assumption.\n  Qed.\n\n  Lemma rsDown_ExtContinuousL_parent_in_system:\n    RsDownMsgs dtr sys oidx rins ->\n    forall st1,\n      Reachable (steps step_m) sys st1 ->\n      forall st2,\n        steps step_m sys st1 phst st2 ->\n        exists pobj,\n          In pobj (sys_objs sys) /\\\n          parentIdxOf dtr oidx = Some (obj_idx pobj).\n  Proof.\n    destruct Hrrs as [? [? ?]]; intros.\n    destruct Hcont as [eouts [oidx' [ridx' [rins' [routs' ?]]]]]; dest.\n    apply eq_sym in H6; inv H6.\n    destruct H5 as [pinits pins phst pouts peouts].\n    destruct H2 as [cobj [rsDown ?]]; dest; subst.\n    pose proof (edgeDownTo_Some (proj1 (proj2 H)) _ H10).\n    destruct H2 as [rqUp [rsUp [pidx ?]]]; dest.\n    eapply atomic_down_out_in_history in H6; eauto.\n    - eapply steps_object_in_system in H6; eauto.\n      destruct H6 as [pobj [? ?]]; subst.\n      exists pobj; auto.\n    - apply SubList_singleton_In in H8.\n      apply in_map; assumption.\n  Qed.\n\nEnd Pushable.\n\nTheorem rqrs_WellInterleaved:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System)\n         (Hiorqs: GoodORqsInit (initsOf sys)) (dtr: DTree)\n         (oinvs: IdxT -> ObjInv)\n         (Hoinvs: InvReachable sys step_m (liftObjInvs oinvs)),\n    RqRsSys dtr sys oinvs ->\n    WellInterleaved sys.\nProof.\n  intros; red; intros.\n  red; intros.\n\n  assert (exists oidx ridx rins routs,\n             l2 = RlblInt oidx ridx rins routs /\\\n             (RqUpMsgs dtr oidx rins \\/\n              RqDownMsgs dtr sys oidx rins \\/\n              RsUpMsgs dtr oidx rins \\/\n              RsDownMsgs dtr sys oidx rins)) as Hnlbl.\n  { destruct H as [? [? ?]].\n    red in H0.\n    destruct H0 as [eouts [oidx [ridx [rins [routs ?]]]]]; dest; subst.\n    inv H2.\n    eapply messages_in_cases in H14; eauto.\n    eauto 6.\n  }\n  destruct Hnlbl as [oidx [ridx [rins [routs ?]]]]; dest; subst.\n\n  destruct H6 as [|[|[|]]].\n  - eapply rqUp_WellInterleavedHst; eauto.\n  - assert (exists sti, steps step_m sys st1 hst1 sti).\n    { inv_steps.\n      eapply steps_split in H9; [|reflexivity].\n      destruct H9 as [sti [? ?]]; eauto.\n    }\n    destruct H6 as [sti ?].\n    destruct (rqDown_ExtContinuousL_parent_in_system Hiorqs H H0 H5 H1 H6)\n      as [pobj [? ?]].\n    eapply rqDown_WellInterleavedHst; eauto.\n  - eapply rsUp_WellInterleavedHst; eauto.\n  - assert (exists sti, steps step_m sys st1 hst1 sti).\n    { inv_steps.\n      eapply steps_split in H9; [|reflexivity].\n      destruct H9 as [sti [? ?]]; eauto.\n    }\n    destruct H6 as [sti ?].\n    destruct (rsDown_ExtContinuousL_parent_in_system Hiorqs H H0 H5 H1 H6)\n      as [pobj [? ?]].\n    eapply rsDown_WellInterleavedHst; eauto.\nQed.\n\nSection NonConfluent.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n  Variables (dtr: DTree)\n            (sys: System)\n            (oinvs: IdxT -> ObjInv).\n  Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n             (Hoinvs: InvReachable sys step_m (liftObjInvs oinvs))\n             (Hrrs: RqRsSys dtr sys oinvs).\n\n  Lemma rqrs_step_ins_or:\n    forall st1,\n      Reachable (steps step_m) sys st1 ->\n      forall oidx ridx rins routs st2,\n        step_m sys st1 (RlblInt oidx ridx rins routs) st2 ->\n        SubList (idsOf rins) (sys_merqs sys) \\/\n        SubList (idsOf rins) (sys_minds sys).\n  Proof.\n    intros.\n    pose proof H0.\n    eapply messages_in_cases in H1;\n      try apply Hiorqs; try apply Hrrs; [|assumption].\n    destruct H1 as [|[|[|]]]; disc_messages_in.\n    - left; apply SubList_nil.\n    - inv_step.\n      destruct H14; simpl in *.\n      apply SubList_singleton_In in H0.\n      apply in_app_or in H0.\n      destruct H0.\n      + right; apply SubList_cons; [assumption|apply SubList_nil].\n      + left; apply SubList_cons; [assumption|apply SubList_nil].\n    - inv_step.\n      destruct H14; simpl in *.\n      apply SubList_singleton_In in H0.\n      apply in_app_or in H0.\n      destruct H0.\n      + right; apply SubList_cons; [assumption|apply SubList_nil].\n      + left; apply SubList_cons; [assumption|apply SubList_nil].\n    - inv_step.\n      destruct H13.\n      right.\n      red; intros midx ?.\n      rewrite Forall_forall in H2; specialize (H2 _ H4).\n      destruct H2 as [cidx [? ?]].\n      apply H0 in H4.\n      apply in_app_or in H4; destruct H4; [assumption|].\n      exfalso.\n      apply Hrrs in H4.\n      destruct H4 as [eoidx ?].\n      eapply rqrsDTree_rqUp_rsUp_not_eq in H4; [|apply Hrrs|eassumption].\n      auto.\n    - inv_step.\n      destruct H14; simpl in *.\n      apply SubList_singleton_In in H0.\n      apply in_app_or in H0.\n      destruct H0.\n      + right; apply SubList_cons; [assumption|apply SubList_nil].\n      + left; apply SubList_cons; [assumption|apply SubList_nil].\n  Qed.\n\n  Lemma extAtomic_IntMsgsEmpty_next_ins:\n    forall 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 oidx ridx rins routs st3,\n          ~ SubList (idsOf rins) (sys_merqs sys) ->\n          step_m sys st2 (RlblInt oidx ridx rins routs) st3 ->\n          exists einits trs eouts,\n            In trs trss /\\\n            ExtAtomic sys einits trs eouts /\\\n            SubList rins eouts.\n  Proof.\n    intros.\n    pose proof H5.\n    eapply messages_in_cases in H6;\n      try apply Hiorqs; try apply Hrrs;\n        [|eapply reachable_steps; eassumption].\n    assert (Forall (InMPI st2.(st_msgs)) rins /\\\n            SubList (idsOf rins) (sys_minds sys)).\n    { pose proof H5.\n      apply rqrs_step_ins_or in H7; [|eapply reachable_steps; eassumption].\n      inv_step.\n      split.\n      { apply FirstMPI_Forall_InMP; assumption. }\n      { destruct H7; [exfalso; auto|auto]. }\n    }\n    clear H5; dest. (* clear [step_m] *)\n\n    destruct H6 as [|[|[|]]]; disc_messages_in.\n    - elim H4; apply SubList_nil.\n    - apply SubList_singleton_In in H7.\n      inv H5; clear H13.\n      eapply extAtomic_multi_IntMsgsEmpty_non_inits_InMPI in H12;\n        try eassumption.\n      destruct H12 as [einits [trs [eouts ?]]]; dest.\n      exists einits, trs, eouts.\n      repeat ssplit; [assumption..|].\n      apply SubList_cons; [assumption|apply SubList_nil].\n\n    - apply SubList_singleton_In in H7.\n      inv H5; clear H13.\n      eapply extAtomic_multi_IntMsgsEmpty_non_inits_InMPI in H12;\n        try eassumption.\n      destruct H12 as [einits [trs [eouts ?]]]; dest.\n      exists einits, trs, eouts.\n      repeat ssplit; [assumption..|].\n      apply SubList_cons; [assumption|apply SubList_nil].\n\n    - (* Pick a single [RsUp] message to get the previous transaction. *)\n      destruct rins as [|[rsUp1 rsm1] rins];\n        [exfalso; elim H4; apply SubList_nil|].\n      simpl in *.\n      apply SubList_cons_inv in H7; dest.\n      inv H5; inv H6; inv H8.\n      destruct H10 as [cidx1 [? ?]]; simpl in *.\n\n      eapply extAtomic_multi_IntMsgsEmpty_non_inits_InMPI in H12;\n        try eassumption.\n      destruct H12 as [einits1 [trs1 [eouts1 ?]]]; dest.\n      exists einits1, trs1, eouts1.\n\n      (* Now prove all the other [RsUp] messages are from\n       * this transaction as well. *)\n      repeat ssplit; try assumption.\n      red. intros [rsUp2 rsm2] ?.\n      inv H16; [inv H17; assumption|].\n\n      rewrite Forall_forall in H13, H14, H15.\n      specialize (H13 _ H17).\n      specialize (H14 _ H17).\n      apply in_map with (f:= idOf) in H17.\n      specialize (H15 _ H17).\n      destruct H15 as [cidx2 [? ?]].\n      simpl in *.\n      eapply extAtomic_multi_IntMsgsEmpty_non_inits_InMPI in H13;\n        try eassumption; [|apply H9 in H17; assumption].\n      destruct H13 as [einits2 [trs2 [eouts2 ?]]]; dest.\n\n      (* Prove two different [RsUp] messages are from the same transaction,\n       * by deriving a contradiction; if [trs1 <> trs2] then ..\n       *)\n      apply In_nth_error in H8; destruct H8 as [n1 ?].\n      apply In_nth_error in H13; destruct H13 as [n2 ?].\n      destruct (Nat.eq_dec n1 n2).\n      + subst; rewrite H8 in H13; inv H13.\n        pose proof (extAtomic_unique H10 H18); dest; subst.\n        assumption.\n      + exfalso.\n        eapply extAtomic_multi_rsUps_not_diverged\n          with (n3:= n1) (n4:= n2) (rsUp3:= (rsUp1, rsm1)) (rsUp4:= (rsUp2, rsm2))\n               (cidx3:= cidx1) (cidx4:= cidx2); eauto.\n        * red; auto.\n        * red; auto.\n\n    - apply SubList_singleton_In in H7.\n      inv H5; clear H13.\n      eapply extAtomic_multi_IntMsgsEmpty_non_inits_InMPI in H12;\n        try eassumption.\n      destruct H12 as [einits [trs [eouts ?]]]; dest.\n      exists einits, trs, eouts.\n      repeat ssplit; [assumption..|].\n      apply SubList_cons; [assumption|apply SubList_nil].\n  Qed.\n\n  Theorem rqrs_NonConfluent:\n    RqRsSys dtr sys oinvs -> NonConfluent sys.\n  Proof.\n    intros.\n    red; intros.\n    eapply steps_split in H2; [|reflexivity].\n    destruct H2 as [stt [? ?]].\n\n    inv H5.\n    pose proof H8.\n    apply atomic_beginning_label in H5.\n    destruct H5 as [ttrs [oidx [ridx [routs ?]]]]; subst.\n    eapply steps_split in H6; [|reflexivity].\n    destruct H6 as [sti [? ?]].\n    inv_steps.\n\n    eapply extAtomic_IntMsgsEmpty_next_ins in H14; eauto.\n    destruct H14 as [pinits [ptrs [peouts ?]]]; dest.\n\n    apply in_split in H5.\n    destruct H5 as [hsts2 [hsts1 ?]]; subst.\n\n    exists ptrs; eexists.\n    exists hsts1, hsts2, nil; simpl.\n    repeat ssplit.\n    - reflexivity.\n    - red; eauto 10.\n    - apply Forall_forall.\n      intros hst ?.\n      eapply extAtomic_Discontinuous\n        with (trss:= hsts2 ++ ptrs :: hsts1); try eassumption.\n      + apply in_or_app; right.\n        left; reflexivity.\n      + apply in_or_app; left; assumption.\n  Qed.\n\nEnd NonConfluent.\n\nCorollary rqrs_Serializable:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (sys: System)\n         (Hiorqs: GoodORqsInit (initsOf sys)) (dtr: DTree)\n         (oinvs: IdxT -> ObjInv) (Hoinvs: InvReachable sys step_m (liftObjInvs oinvs)),\n    RqRsSys dtr sys oinvs ->\n    SerializableSys sys.\nProof.\n  intros.\n  apply well_interleaved_serializable.\n  - eapply rqrs_NonConfluent; eauto.\n  - eapply rqrs_WellInterleaved; eauto.\nQed.\n\nClose Scope list.\nClose Scope fmap.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Dsl/RqRsCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.17291730148369586}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype tuple seq fintype.\nRequire Import procstate procstatemonad bitsops bitsprops bitsopsprops.\nRequire Import SPred septac spec spectac safe basic program.\nRequire Import instr instrsyntax instrrules reader pointsto cursor.\nRequire Import triple monad eval instrcodec enc encdechelp basicprog.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope instr_scope.\n\nLemma jmpBytes (i1 i2 i': DWORD) (p: program) (bytes : seq BYTE) :\n  i' :-> bytes |-- i' :-> p\n->\n  |-- ((|> safe @ (i' :-> p ** EIP ~= i')) -->>\n           safe @ (i' :-> bytes ** EIP ~= i1)) <@ (i1 -- i2 :-> JMP i').\nProof. move => H1.\nrewrite -> H1.\nspecapply JMP_I_rule.\nsbazooka. autorewrite with push_at. rewrite <- spec_reads_frame. apply limplValid.\ncancel1. cancel1. sbazooka.\nQed.\n\nLemma jmpBytes_basic (i j:DWORD) p (bytes: seq BYTE) P :\n  i -- j :-> bytes |-- i -- j :-> p ->\n  |-- safe @ (EIP ~= i ** P) <@ (i -- j :-> p) -> (*basic P p Q ->*)\n  |-- Forall i1, Forall j1:DWORD, (|> safe @ (EIP ~= i1 ** P)) <@ (i1 -- j1 :-> JMP i ** i -- j :-> bytes).\nProof. move => H1 H2.\nspecintros => i1 j1.\nspecapply JMP_I_rule. sbazooka.\nrewrite <- spec_reads_frame.\nautorewrite with push_at.\napply limplValid. cancel1.\nQed.\n\nLemma inlineBytes (i: DWORD) (p: program) (bytes: seq BYTE) :\n  i :-> bytes |-- i :-> p ->\n  |-- safe @ (i :-> p ** EIP ~= i) -->>\n      safe @ (i :-> bytes ** EIP ~= i).\nProof. move => H.\nrewrite -> H.\napply limplValid. cancel1.\nQed.\n\n(* Self-modifying code!\n   Effect is PUSH r\n*)\nDefinition selfModImp r (v: DWORD) : program :=\nLOCAL PUSHCONST;\n  MOV EDI, PUSHCONST;;\n  MOV [EDI], r;;\n  db #x\"68\";;\nPUSHCONST:;;\n  dd v.\n\nLemma interpReader_letSplit2 T m n (v:_) (r: _ -> _ -> Reader T) :\n  interpReader (let (x,y) := split2 n m v in r x y) = interpReader (r (high n v) (low m v)).\nProof. done.  Qed.\n\nHint Rewrite interpReader_bind interpReader_retn interpReader_letPair interpReader_letSplit2 : INTERP.\nLtac SOLVE :=\n  try repeat (try autorewrite with INTERP; try (sdestructs; intros); try discriminate).\n\nLtac CASESOLVE :=\n  (let E := fresh \"E\" in case E: (_ == _); try rewrite (eqP E); clear E; SOLVE).\n\n(* Extremely long-winded way of showing this! *)\nLemma PUSH_decoding (p addr: DWORD) q :\np -- q :-> PUSH addr -|-\n  (p :-> #x\"68\" ** next p -- q :-> addr) \\\\//\n  (Exists b, signTruncate _ (n:=7) addr = Some b /\\\\ p :-> #x\"6A\" ** next p -- q :-> b).\nProof.\nsplit.\n(* => *)\nrewrite /pointsTo{1}/memIs/readerMemIs/readNext/readInstr/readNext.\n(*apply lexistsL => q.*)\nrewrite -> interpReader_bindBYTE.\napply lexistsL => b. rewrite <-pointsToBYTE_byteIs.\nrewrite /pointsTo. sdestruct => p'. rewrite -> memIsBYTE_next_entails.\nsdestruct => H. subst.\n\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\nCASESOLVE.\n\n(* It is #x\"68\" *)\nrewrite {3}/memIs.\napply lorR1. sbazooka. injection x2 => ->.\nsubst. reflexivity.\n\n(* Test for #x\"6A\" *)\nCASESOLVE.\n(* It is #x\"6A\" *)\napply lorR2.\ninjection x2 => <-.\nsbazooka.\nby rewrite signExtendK.\nrewrite {3}/memIs/readerMemIs. sbazooka. subst. reflexivity.\n\n(* It's neither #x\"68\" nor #x\"6A\" *)\ndo 10 CASESOLVE.\ndo 10 CASESOLVE.\ndo 11 CASESOLVE.\ndestruct x0.\ndestruct r;  SOLVE.\ndo 10 CASESOLVE.\n\n(* <= *)\n(*rewrite {2}/pointsTo {1}/memIs/readerMemIs/readNext/readInstr. *)\napply lorL.\n\n(* 68 *)\nrewrite pointsToBYTE_byteIs.\nrewrite {2}/memIs/readerMemIs/readNext/readInstr.\nrewrite -> interpReader_bindBYTE.\napply lexistsR with #x\"68\".\nssimpl.\ntry replace (_ == _) with false by done.\ntry replace (_ == _) with false by done.\ntry replace (_ == _) with true by done.\nrewrite -> interpReader_bind.\napply lexistsR with q.\napply lexistsR with addr.\nrewrite -> interpReader_retn.\nsbazooka. reflexivity.\n\n(* 6A *)\nsdestructs => b SMALL.\nrewrite {2}/memIs/readerMemIs/readNext/readInstr.\nrewrite -> interpReader_bindBYTE.\napply lexistsR with #x\"6A\".\nrewrite pointsToBYTE_byteIs.\nssimpl.\ntry replace (_ == _) with false by done.\ntry replace (_ == _) with false by done.\ntry replace (_ == _) with false by done.\ntry replace (_ == _) with true by done.\nrewrite -> interpReader_bind.\napply lexistsR with q.\napply lexistsR with b.\nrewrite -> interpReader_retn.\nrewrite /memIs/readNext.\nrewrite (signTruncateK SMALL).\nsbazooka.\nQed.\n\n(*\nLemma MOV_PUSH_R_rule (p: DWORD) (r1 r2: Reg) (v1 v2:DWORD) :\n  |-- basic (r1~=p ** p :-> #x\"68\" ** next p :-> v1 ** r2~=v2)\n            (MOV [r1 + 1], r2)\n            (r1~=p ** p :-> PUSH v2 ** r2~=v2).\nProof.\n  rewrite PUSH_decoding => //.\n  have RULE:= (MOV_MR_rule (offset:=1) (r1:=r1) (r2:=r2) (p:=p) (v1:=v1) (v2:=v2)).\n  apply TRIPLE_basic => R.\n  rewrite /evalInstr/evalMOV.\n  triple_apply triple_letGetRegSep.\n  triple_apply evalMemSpecNone_rule.\n  triple_apply triple_setDWORDSep.\nAdmitted.  (*apply lorR1.\n  sbazooka.\n  reflexivity.\nQed.*)\n\n*)\n\nLemma dbDef (p:DWORD) q b : p -- q :-> db b -|- q = next p /\\\\ p :-> b.\nProof. split.\n+ simpl. sdestructs => b' -> <-. rewrite pointsToBYTE_byteIs. sbazooka.\n+ simpl. apply lexistsR with b. rewrite pointsToBYTE_byteIs. sbazooka.\nQed.\n\nLemma ddDef (p:DWORD) (d:DWORD) : p :-> dd d -|- p :-> d.\nProof. rewrite /dd/pointsTo.\nsplit.\n+ sdestruct => q. unfold_program. apply lexistsR with q. reflexivity.\n+ sdestruct => q. apply lexistsR with q. unfold_program. reflexivity.\nQed.\n\nLemma ddDefAux p q (d:DWORD) : p -- q :-> dd d -|- p -- q :-> d.\nProof. rewrite /dd. unfold_program. reflexivity. Qed.\n\n\nCorollary PUSH_DWORD_decoding (p addr: DWORD) j :\n  p :-> (#x\"68\":BYTE) ** next p -- j :-> addr |-- p -- j :-> PUSH addr.\nProof. rewrite ->PUSH_decoding. apply lorR1. reflexivity. Qed.\n\n(* A version of the PUSH_I rule in which the encoding is spelt out explicitly using\n   data directives *)\nLemma PUSH_I_BYTES_rule (sp v w:DWORD) :\n  |-- basic (ESP ~= sp    ** sp-#4 :-> w)\n            (db #x\"68\";; dd v)\n            (ESP ~= sp-#4 ** sp-#4 :-> v).\nProof.\nrewrite /basic.\nspecintros => i j.\nunfold_program.\nspecintros => i1. rewrite -> dbDef.\nspecintros => ->. rewrite -> ddDefAux.\nrewrite -> PUSH_DWORD_decoding.\nspecapply PUSH_I_rule.\nsbazooka. autorewrite with push_at.\nrewrite <- spec_reads_frame.\napply limplValid. cancel1. sbazooka.\nQed.\n\nLemma MOV_M0R_ruleAux (pd:DWORD) pe (r1 r2:Reg) (v1 v2: DWORD) :\n  |-- basic (r1 ~= pd ** pd -- pe :-> v1 ** r2 ~= v2)\n            (MOV [r1], r2)\n            (r1 ~= pd ** pd -- pe :-> v2 ** r2 ~= v2).\nProof. rewrite -> memIsFixed. specintros => ->.\nbasicapply MOV_M0R_rule. rewrite -> memIs_pointsTo. sbazooka.\nrewrite /pointsTo. sdestruct => q.\nrewrite -> memIsFixed. sdestruct => ->. sbazooka.\nQed.\n\nLemma modPUSH (r:Reg) (v w: DWORD) j2:\n  |-- Forall i, Forall j1,\n      (safe @ (EIP ~= j1 ** j1 :-> #x\"68\" ** j1+#1 -- j2 :-> v ** EDI ~= j1+#1 ** r ~= v) -->>\n      (safe @ (EIP ~= i **  j1 :-> #x\"68\" ** j1+#1 -- j2 :-> w ** EDI ~= j1+#1 ** r ~= v))) <@\n      (i -- j1 :-> MOV [EDI], r).\nProof.\nspecintros => i j1.\nspecapply\n  (MOV_M0R_ruleAux(pd := j1 +# 1) (pe := j2) (r1 := EDI) (r2 := r) (v1 := w) (v2 := v)).\nsbazooka.\nrewrite <- spec_reads_frame.\nautorewrite with push_at.\napply limplValid. cancel1.\nsbazooka.\nQed.\n\nLemma modPUSHAux (r:Reg) (v w: DWORD) j2:\n  |-- Forall i, Forall j1,\n      (safe @ (EIP ~= j1 ** j1+#1 -- j2 :-> v) -->>\n      (safe @ (EIP ~= i **  j1+#1 -- j2 :-> w))) @ (EDI ~= j1+#1 ** r~=v) <@\n      (i -- j1 :-> (MOV [EDI], r) ** j1 :-> #x\"68\").\nProof.\nspecintros => i j1.\nspecapply\n  (MOV_M0R_ruleAux(pd := j1 +# 1) (pe := j2) (r1 := EDI) (r2 := r) (v1 := w) (v2 := v)).\nsbazooka.\nrewrite <- spec_reads_frame.\nautorewrite with push_at.\napply limplValid. cancel1.\nsbazooka.\nQed.\n\nLemma TRIPLE_mysafe instr P Q (i j: DWORD):\n  (forall (R: SPred),\n   TRIPLE (EIP ~= j ** P ** R) (evalInstr instr) (Q ** R)) ->\n  |-- (|> safe @ Q -->> safe @ (EIP ~= i ** P)) @ (i -- j :-> instr).\nProof.\n  move=> H. autorewrite with push_at.\n  rewrite sepSPA. apply limplValid.\n  specialize (H (i -- j :-> instr)). admit.\nQed.\n\nLemma TRIPLE_mybasic instr P Q:\n  (forall (R: SPred), TRIPLE (P ** R) (evalInstr instr) (Q ** R)) ->\n  |-- Forall i, Forall j, (safe @ (EIP ~= i ** Q) -->> safe @ (EIP ~= j ** P))\n      @ (j -- i :-> instr).\nProof.\n  move=> H. specintros => i j.\n  rewrite ->(spec_later_weaken (safe @ (EIP~=i ** Q))).\n  apply TRIPLE_mysafe => R. triple_apply H.\nQed.\n\n\nLemma PUSH_rule src sp (v:DWORD) :\n  |-- specAtSrc src (fun w =>\n      Forall i, Forall j,\n      (safe @ (EIP ~= i ** ESP ~= sp-#4 ** sp-#4 :-> w) -->>\n       safe @ (EIP ~= j ** ESP ~= sp ** sp-#4 :-> v)) @ (j -- i :-> PUSH src)).\nProof.\nadmit.\nQed. (*rewrite /specAtSrc. destruct src.\n- apply TRIPLE_mybasic => R.\n  rewrite /evalInstr/evalSrc.\n  rewrite -> id_l.\n  triple_apply evalPush_rule.\n- elim: ms => [base indexAndScale offset].\n  case: indexAndScale => [[rix sc] |].\n  rewrite /specAtMemSpec.\n  + specintros => oldv pbase indexval.\n    autorewrite with push_at. apply TRIPLE_mybasic => R.\n    autounfold with eval. rewrite /evalSrc.\n    triple_apply evalMemSpec_rule.\n    triple_apply triple_letGetDWORDSep.\n    triple_apply evalPush_rule.\n  + rewrite /specAtMemSpec. specintros => oldv pbase.\n    autorewrite with push_at. apply TRIPLE_basic => R.\n    autounfold with eval. rewrite /evalSrc.\n    triple_apply evalMemSpecNone_rule.\n    triple_apply triple_letGetDWORDSep.\n    triple_apply evalPush_rule.\n\n- specintros => oldv.\n  autorewrite with push_at.\n  apply TRIPLE_basic => R.\n  rewrite /evalInstr.\n  triple_apply triple_letGetRegSep.\n  triple_apply evalPush_rule.\nQed.\n*)\n\n(*\nLemma basicWeaken P c Q :\n  (forall i j, |--    (safe @ (EIP~=j ** P) -->>\n          safe @ (EIP~=i ** Q)) <@\n         (i -- j :-> c)) ->\n  |--Forall i,\n     Forall j,\n         (safe @ (EIP~=j ** P) -->>\n          safe @ (EIP~=i ** Q)) @\n         (i -- j :-> c).\nProof. move => H.\nspecintros => i j. specialize (H i j).\nrewrite -> spec_reads_impl in H.\nrewrite <- spec_at_entails_reads in H.\nrewrite <- spec_at_reads in H. apply: H. specintros.\nrewrite -> spec_at_entails_reads in H.\nautorewrite with push_at in H.\nspecintros => i j. autorewrite with push_at. rewrite spec_reads_frame in H. apply H.\n*)\n\n Lemma my_at P Q R :\n    (safe @ P -->> safe @ Q) @ R |-- (safe @ (P ** R) -->> safe @ (Q ** R)).\n  Proof.\n    autorewrite with push_at. cancel1.\n  Qed.\n\nLemma modPushAndDoIt (r:Reg) (v w: DWORD) j2 sp:\n  |-- Forall i, Forall j1,\n      (safe @ (EIP ~= j2 ** j1+#1 -- j2 :-> v ** ESP ~= sp-#4 ** sp-#4 :-> v) -->>\n      (safe @ (EIP ~= i **  j1+#1 -- j2 :-> w ** ESP ~= sp    ** sp-#4 :-> w))) @ (EDI ~= j1+#1 ** r~=v ** j1 :-> #x\"68\") <@\n      (i -- j1 :-> (MOV [EDI], r)).\nProof. specintros => i j1.\n\nspecapply\n  (MOV_M0R_ruleAux(pd := j1 +# 1) (pe := j2) (r1 := EDI) (r2 := r) (v1 := w) (v2 := v)).\nsbazooka.\nrewrite <- spec_reads_frame.\nautorewrite with push_at.\nrewrite spec_at_at. (*autorewrite with push_at. *)\nLocate eq_pred.\nrewrite <- spec_at_at.\nrewrite <- spec_at_at.\ncancel1.\nsbazooka.\nhave M := (my_at (R := (j1 +# 1 -- j2 :-> v))).\nautorewrite with push_at. rewrite -> my_at. apply my_at. cancel1. apply (my_at (R := (j1 := #x.\nAdmitted.\n\n\nLemma modPushAndDoItAux (r:Reg) (v w: DWORD) j2 sp:\n  |-- Forall i, Forall j1,\n      (safe @ (EIP ~= j2 ** ESP ~= sp-#4 ** sp-#4 :-> v) -->>\n      (safe @ (EIP ~= i **  ESP ~= sp    ** sp-#4 :-> w)))\n      @ (EDI ~= j1+#1 ** r~=v) <@\n      (Exists d:DWORD, i -- j1 :-> (MOV [EDI], r) ** j1 :-> #x\"68\" ** (j1+#1) -- j2 :-> d).\nProof. specintro => i. specintro => j1.\nspecintros => d.  => specapply\n  (MOV_M0R_ruleAux(pd := j1 +# 1) (pe := j2) (r1 := EDI) (r2 := r) (v1 := w) (v2 := v)).\nsbazooka.\nrewrite <- spec_reads_frame.\n\n\nLemma selfModPUSH_R_rule (r:Reg) sp (v w:DWORD) i j :\n  |-- safe @ (EDI? ** r ~= v ** ESP ~= sp-#4 ** sp-#4 :-> v ** i -- j :-> (db #x\"68\";;\n  dd v)) -->>\n      safe @ (EDI? ** r ~= v ** ESP ~= sp ** sp-#4 :-> w ** i -- j :-> (db #x\"68\";; dd #0)).\nProof. have PIB := PUSH_I_BYTES_rule.\nspecialize (PIB sp v w).\nrewrite /basic in PIB.\nrewrite limplAdj in PIB.\nrewrite spec_reads_entails_at in PIB.\nspecapply PIB. PUSH_I_BYTES_rule. sbazooka.\n\nProof. rewrite /selfModImp.\napply basic_local => L.\neapply basic_seq. basicapply (MOV_RI_rule).\neapply basic_seq.\nbasicapply MOV_MR_rule. rewrite /basic.\nspecintros => i j.\nunfold_program.\nspecintros => i1 i2 -> -> i3.\nrewrite dbDef. specintros => ->. rewrite -> ddDefAux.\nrewrite empSPL.\n\nrewrite (sepSPC (i -- L :-> _)).\nrewrite <- spec_reads_merge.\nrewrite <- spec_reads_split. apply MOV_MR_rule.\nsbazooka.\nautorewrite with push_at.\nrewrite <- spec_reads_impl.\nrewrite spec_reads_swap.\nspecapply MOV_MR_rule.\nspecapply MOV_MR_rule.\nssimpl.\n\nrewrite ->(PUSH_DWORD_decoding C).\nrewrite {3}sepSPA. (i -- L :-> (MOV [EEI.\nspecapply MOV_MR_rule.\nsbazooka. ssimpl. rewrite <- spec_at_entails_reads.\nautorewrite with push_at.\nspecapply (inlineBytes (PUSH_DWORD_decoding (p:= L) (addr := v))).\n\nautorewrite with push_at.\nsetoid_rewrite -> ddDef.\n(* Problem here is that <@ doesn't permit changes to code *)\nspecapply (MOV_MR_rule). sbazooka. ; first last.\nrewrite <- spec_reads_frame.\nautorewrite with push_at. apply limplValid. cancel1.\nssimpl.\nrewrite /regAny. sbazooka.  ssimpl. apply: landL2.  autorewrite with push_at. rewrite <- spec_later_weaken.\nsbazooka. reflexivity. plit.\nssimpl.  sbazooka. rewrite / sbazooka. Qed.\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/selfmod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.172917296732146}}
{"text": "From Coq Require Import String ZArith NArith Eqdep_dec Lia.\n\nFrom Coq Require PropExtensionality.\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 FunCtx Expr.\n\nDefinition VarmapInj {C: VyperConfig}\n                     (varmap: string_map N)\n:= let _ := string_map_impl in\n   forall x y,\n     match Map.lookup varmap x with\n     | Some u =>\n         match Map.lookup varmap y with\n         | Some v => u = v -> x = y\n         | None => True\n         end\n     | None => True\n     end.\n\nLemma interpret_translated_small_stmt {C: VyperConfig}\n                        {bigger_call_depth_bound smaller_call_depth_bound: nat}\n                        (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n                        {cd20: L20.Descend.calldag}\n                        (builtins: string -> option builtin)\n                        (fc: fun_ctx cd20 bigger_call_depth_bound)\n                        {cd30: L30.Descend.calldag}\n                        (ok: translate_calldag cd20 = inr cd30)\n                        {do_call_20: forall\n                              (fc': fun_ctx cd20 smaller_call_depth_bound)\n                              (world: world_state)\n                              (arg_values: list uint256),\n                            world_state * expr_result uint256}\n                        {do_call_30: forall\n                              (fc': fun_ctx cd30 smaller_call_depth_bound)\n                              (world: world_state)\n                              (arg_values: list uint256),\n                            world_state * expr_result uint256}\n                        (DoCallOk: forall fc' world arg_values,\n                                     do_call_30 (translate_fun_ctx fc' ok) world arg_values\n                                      =\n                                     do_call_20 fc' world arg_values)\n                        (world: world_state)\n                        (locmap: string_map uint256)\n                        (locmem: memory)\n                        {ss20: L20.AST.small_stmt}\n                        {s30: L30.AST.stmt}\n                        (varmap: string_map N)\n                        (VI: VarmapInj varmap)\n                        (offset: N)\n                        (Agree: VarsAgree varmap locmap locmem)\n                        (Bound: VarsBound varmap offset)\n                        (StmtOk: translate_small_stmt varmap offset ss20 = inr s30)\n                        (CallOk30: let _ := string_set_impl in \n                           FSet.is_subset (L30.Callset.stmt_callset s30)\n                                          (L30.Callset.decl_callset\n                                             (fun_decl\n                                               (translate_fun_ctx fc ok)))\n                           = true)\n                        (CallOk20: let _ := string_set_impl in \n                           FSet.is_subset (L20.Callset.small_stmt_callset ss20)\n                                          (L20.Callset.decl_callset\n                                            (fun_decl fc))\n                           = true):\n   let _ := string_map_impl in\n   let _ := memory_impl in\n   let '(world30, mem30, result30) := L30.Stmt.interpret_stmt Ebound (translate_fun_ctx fc ok)\n                                                              do_call_30 builtins\n                                                              world locmem s30 CallOk30\n   in let '(world20, new_loc, result20) := L20.Stmt.interpret_small_stmt Ebound fc do_call_20 builtins\n                                                                world locmap ss20 CallOk20\n   in result30 = result20\n       /\\\n      world30 = world20\n       /\\\n      VarsAgree varmap new_loc mem30.\nProof.\ndestruct ss20; cbn in StmtOk.\n{ (* pass *)\n  inversion StmtOk. subst s30. cbn.\n  split. { trivial. }\n  split. { trivial. }\n  exact Agree.\n}\n{ (* abort *) inversion StmtOk. now subst s30. }\n{ (* return *)\n  remember (translate_expr varmap offset (N.succ offset) result) as e30.\n  destruct e30. { discriminate. }\n  inversion StmtOk. subst s30. cbn.\n  assert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                         varmap offset (N.succ offset) Agree Bound\n                                         (N.lt_succ_diag_r offset)\n                                         (eq_sym Heqe30)\n                                         (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                                         (L20.Callset.callset_descend_return eq_refl CallOk20)).\n  cbn in T.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Expr.interpret_expr as (world20, result20).\n  destruct result20, result30; try easy.\n  {\n    f_equal.\n    split. { f_equal. tauto. }\n    split. { tauto. }\n    destruct T as (T_world, (T_mem, (T_agree, T_dst))).\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                   offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  split. { tauto. }\n  split. { tauto. }\n  destruct T as (T_world, (T_mem, T_result)).\n  exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                               offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n}\n{ (* raise *)\n  remember (translate_expr varmap offset (N.succ offset) error) as e30.\n  destruct e30. { discriminate. }\n  inversion StmtOk. subst s30. cbn.\n  assert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                         varmap offset (N.succ offset) Agree Bound\n                                         (N.lt_succ_diag_r offset)\n                                         (eq_sym Heqe30)\n                                         (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                                         (L20.Callset.callset_descend_raise eq_refl CallOk20)).\n  cbn in T.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Expr.interpret_expr as (world20, result20).\n  destruct result20, result30; try easy.\n  {\n    split. { f_equal. f_equal. tauto. }\n    split. { tauto. }\n    destruct T as (T_world, (T_mem, T_result)).\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                               offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  destruct T as (T_world, (T_mem, T_result)).\n  split. { f_equal. f_equal. now inversion T_result. }\n  split. { trivial. }\n  exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                             offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n}\n{ (* assign *)\n  destruct lhs.\n  {\n    (* local *)\n    assert (B := Bound name). unfold map_lookup in *.\n    remember (Map.lookup varmap name) as m.\n    destruct m. 2:{ discriminate. }\n    remember (translate_expr varmap offset (N.succ offset) rhs) as e30.\n    destruct e30. { discriminate. }\n    inversion StmtOk. clear StmtOk. subst s30.\n    cbn.\n    assert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                           varmap offset (N.succ offset) Agree Bound\n                                           (N.lt_succ_diag_r _)\n                                           (eq_sym Heqe30)\n                                           (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                                           (L20.Callset.callset_descend_assign_rhs eq_refl CallOk20)).\n    cbn in T.\n    destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n    destruct L20.Expr.interpret_expr as (world20, result20).\n    destruct result20, result30; try easy.\n    2:{\n      cbn.\n      destruct T as (T_world, (T_mem, T_result)).\n      repeat (split; trivial).\n      exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                     offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n    }\n    unfold L20.Stmt.do_assign.\n    assert (A := Agree name).\n    destruct (Map.lookup locmap name). 2:{ now rewrite<- Heqm in A. }\n    split. { trivial. }\n    split. { tauto. }\n    destruct T as (T_world, (T_mem, (T_result, T_dst))).\n    intro x.\n    assert (V := vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                         offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem x).\n    assert (VIx := VI name x).\n    rewrite Map.insert_ok.\n    destruct (string_dec name x).\n    {\n      subst x.\n      destruct (Map.lookup varmap name). 2:{ easy. }\n      rewrite OpenArray.put_ok.\n      inversion Heqm. subst n0.\n      replace (n =? n)%N with true. 2:{ symmetry. apply N.eqb_eq. trivial. }\n      exact T_dst.\n    }\n    destruct (Map.lookup locmap x). 2:now destruct (Map.lookup varmap x).\n    remember (Map.lookup varmap x) as v.\n    destruct v. 2:exact V.\n    rewrite OpenArray.put_ok.\n    rewrite<- Heqm in VIx.\n    replace (n =? n1)%N with false. { exact V. }\n    symmetry. apply N.eqb_neq. tauto.\n  } (* local var *)\n  (* global var *)\n  cbn.\n  assert (B := Bound name). unfold map_lookup in *.\n  remember (translate_expr varmap offset (N.succ offset) rhs) as e30.\n  destruct e30. { discriminate. }\n  inversion StmtOk. clear StmtOk. subst s30.\n  cbn.\n  assert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                         varmap offset (N.succ offset) Agree Bound\n                                         (N.lt_succ_diag_r _)\n                                         (eq_sym Heqe30)\n                                         (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                                         (L20.Callset.callset_descend_assign_rhs eq_refl CallOk20)).\n  cbn in T.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Expr.interpret_expr as (world20, result20).\n  destruct result20, result30; try easy.\n  2:{\n    destruct T as (T_world, (T_mem, T_result)).\n    repeat (split; trivial).\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                   offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  unfold L20.Stmt.do_assign.\n  assert (A := Agree name).\n  unfold L20.Expr.storage_var_is_declared.\n  assert (D := translate_fun_ctx_declmap ok name).\n  destruct T as (T_world, (T_mem, (T_result, T_dst))).\n  destruct (cd_declmap cd20 name), (cd_declmap cd30 name); try easy.\n  2:{\n    split. { trivial. }\n    split. { trivial. }\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                               offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  destruct d; cbn in D; inversion D; subst.\n  {\n    split. { trivial. }\n    split. { now f_equal. }\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                   offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  destruct (make_varmap args). { discriminate. }\n  destruct translate_stmt. { discriminate. }\n  inversion D; subst.\n  split. { trivial. }\n  split. { trivial. }\n  exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                             offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n}\n(* expr *)\ncbn.\nunfold map_lookup in *.\nassert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                       varmap offset (N.succ offset) Agree Bound\n                                       (N.lt_succ_diag_r _)\n                                       StmtOk\n                                       CallOk30\n                                       (L20.Callset.callset_descend_expr_stmt eq_refl CallOk20)).\ncbn in T.\ndestruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\ndestruct L20.Expr.interpret_expr as (world20, result20).\ndestruct T as (T_world, (T_mem, T_result)).\ndestruct result20, result30; try easy;\nsplit; trivial;\nsplit; trivial;\nexact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                             offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\nQed.\n\nLemma interpret_translated_stmt {C: VyperConfig}\n                        {bigger_call_depth_bound smaller_call_depth_bound: nat}\n                        (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n                        {cd20: L20.Descend.calldag}\n                        (builtins: string -> option builtin)\n                        (fc: fun_ctx cd20 bigger_call_depth_bound)\n                        {cd30: L30.Descend.calldag}\n                        (ok: translate_calldag cd20 = inr cd30)\n                        {do_call_20: forall\n                              (fc': fun_ctx cd20 smaller_call_depth_bound)\n                              (world: world_state)\n                              (arg_values: list uint256),\n                            world_state * expr_result uint256}\n                        {do_call_30: forall\n                              (fc': fun_ctx cd30 smaller_call_depth_bound)\n                              (world: world_state)\n                              (arg_values: list uint256),\n                            world_state * expr_result uint256}\n                        (DoCallOk: forall fc' world arg_values,\n                                     do_call_30 (translate_fun_ctx fc' ok) world arg_values\n                                      =\n                                     do_call_20 fc' world arg_values)\n                        (world: world_state)\n                        (locmap: string_map uint256)\n                        (locmem: memory)\n                        {s20: L20.AST.stmt}\n                        {s30: L30.AST.stmt}\n                        (varmap: string_map N)\n                        (VI: VarmapInj varmap)\n                        (offset: N)\n                        (Agree: VarsAgree varmap locmap locmem)\n                        (Bound: VarsBound varmap offset)\n                        (StmtOk: translate_stmt varmap offset s20 = inr s30)\n                        (CallOk30: let _ := string_set_impl in \n                           FSet.is_subset (L30.Callset.stmt_callset s30)\n                                          (L30.Callset.decl_callset\n                                             (fun_decl\n                                               (translate_fun_ctx fc ok)))\n                           = true)\n                        (CallOk20: let _ := string_set_impl in \n                           FSet.is_subset (L20.Callset.stmt_callset s20)\n                                          (L20.Callset.decl_callset\n                                            (fun_decl fc))\n                           = true):\n   let _ := string_map_impl in\n   let _ := memory_impl in\n   let '(world30, mem30, result30) := L30.Stmt.interpret_stmt Ebound (translate_fun_ctx fc ok)\n                                                              do_call_30 builtins\n                                                              world locmem s30 CallOk30\n   in let '(world20, new_loc, result20) := L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins\n                                                                   world locmap s20 CallOk20\n   in result30 = result20\n       /\\\n      world30 = world20\n       /\\\n      VarsAgree varmap new_loc mem30.\nProof.\nrevert world offset varmap s30 StmtOk locmem locmap VI Agree Bound CallOk30 CallOk20.\ninduction s20; intros.\n{ (* small *)\n  apply (interpret_translated_small_stmt Ebound builtins fc ok DoCallOk world locmap locmem\n                                         varmap VI offset Agree Bound\n                                         StmtOk\n                                         CallOk30\n                                         (L20.Callset.callset_descend_small_stmt eq_refl CallOk20)).\n}\n{ (* LocalVarDecl *)\n  clear s m.\n  cbn. cbn in StmtOk.\n  assert (A := Agree name). unfold map_lookup in *.\n  remember (Map.lookup varmap name) as varmap_name.\n  destruct (Map.lookup locmap name), varmap_name; try easy.\n  clear A.\n  remember (translate_expr varmap offset (N.succ offset) init) as init30.\n  destruct init30. { discriminate. }\n  remember (translate_stmt (map_insert varmap name offset) (N.succ offset) s20) as body30.\n  destruct body30. { discriminate. }\n  inversion StmtOk. subst s30. clear StmtOk.\n  assert (T := interpret_translated_expr Ebound builtins fc ok DoCallOk world locmap locmem\n                                         varmap offset (N.succ offset) Agree Bound\n                                         (N.lt_succ_diag_r _)\n                                         (eq_sym Heqinit30)\n                                         (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                                         (L20.Callset.callset_descend_var_init eq_refl CallOk20)).\n  cbn in T. cbn.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Expr.interpret_expr as (world20, result20).\n  destruct T as (T_world, (T_mem, T_result)).\n  destruct result20, result30; try easy.\n  2:{ (* init failed *)\n    repeat (split; trivial).\n    exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                   offset (N.succ offset) Bound (N.lt_succ_diag_r _) T_mem).\n  }\n  (* init succeeded *)\n\n  assert (VI': VarmapInj (map_insert varmap name offset)).\n  {\n    unfold VarmapInj. intros x y.\n    unfold map_insert. repeat rewrite Map.insert_ok.\n    assert (VIxy := VI x y).\n    destruct (string_dec name x).\n    {\n      subst x.\n      destruct (string_dec name y). { easy. }\n      assert (By := Bound y).\n      destruct (Map.lookup varmap y). 2:{ trivial. }\n      intro E. subst.\n      apply N.lt_irrefl in By.\n      contradiction.\n    }\n    destruct (string_dec name y).\n    { (* this is a mirror of the previous branch with x and y swapped *)\n      subst y.\n      assert (Bx := Bound x).\n      destruct (Map.lookup varmap x). 2:{ trivial. }\n      intro E. subst.\n      apply N.lt_irrefl in Bx.\n      contradiction.\n    }\n    apply VIxy.\n  } (* VI' *)\n\n  assert (Agree': VarsAgree (map_insert varmap name offset) (map_insert locmap name value) mem30).\n  {\n    intro x.\n    unfold map_insert. repeat rewrite Map.insert_ok.\n    destruct (string_dec name x). { now subst. }\n    apply (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree offset (N.succ offset) Bound\n           (N.lt_succ_diag_r offset) T_mem x).\n  }\n\n  assert (Bound': VarsBound (map_insert varmap name offset) (N.succ offset)).\n  {\n    intro x.\n    unfold map_insert.\n    rewrite Map.insert_ok.\n    destruct (string_dec name x). { apply N.lt_succ_diag_r. }\n    assert (B := Bound x).\n    destruct (Map.lookup varmap x). 2:{ trivial. }\n    apply N.lt_lt_succ_r. exact B.\n  }\n\n  assert (IH := IHs20 world30 (N.succ offset) (map_insert varmap name offset) _ (eq_sym Heqbody30)\n                      mem30 (map_insert locmap name value)\n                      VI' Agree' Bound'\n                      (L30.Callset.callset_descend_semicolon_right eq_refl CallOk30)\n                      (L20.Callset.callset_descend_var_scope eq_refl CallOk20)).\n\n  assert (R:\n        (@Callset.callset_descend_semicolon_right C s s0 (@AST.Semicolon C s s0)\n           (@Callset.decl_callset C\n              (@fun_decl C (@AST.decl C) (@Callset.decl_callset C) false cd30 bigger_call_depth_bound\n                 (@translate_fun_ctx C bigger_call_depth_bound cd20 fc cd30 ok)))\n           (@eq_refl (@AST.stmt C) (@AST.Semicolon C s s0)) CallOk30)\n         =\n       (@Callset.callset_descend_semicolon_right C s s0 (@AST.Semicolon C s s0)\n           (@Callset.decl_callset C (@cached_translated_decl C bigger_call_depth_bound cd20 fc cd30 ok))\n           (@eq_refl (@AST.stmt C) (@AST.Semicolon C s s0)) CallOk30)).\n  { apply PropExtensionality.proof_irrelevance. }\n  rewrite R in IH. clear R.\n  destruct L30.Stmt.interpret_stmt as ((world30', mem30'), result30').\n  subst world30.\n  destruct (L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins world20\n            (map_insert locmap name value) s20\n            (Callset.callset_descend_var_scope eq_refl CallOk20)) as ((world20', loc20'), result20').\n  destruct IH as (IH_result, (IH_world, IH_agree)).\n  split. { trivial. }\n  split. { assumption. }\n  (* goal: VarsAgree varmap (map_remove loc20' name) mem30' *)\n  intro x. unfold map_remove.\n  rewrite Map.remove_ok.\n  assert (A := IH_agree x). unfold map_insert in A.\n  repeat rewrite Map.insert_ok in A.\n  destruct (string_dec name x).\n  { subst x. now rewrite<- Heqvarmap_name. }\n  exact A.\n}\n{ (* IfElseStmt *)\n  cbn in StmtOk.\n  remember (translate_expr varmap offset (N.succ offset) cond) as cond30.\n  destruct cond30. { discriminate. }\n  remember (translate_stmt varmap offset s20_1) as then30.\n  destruct then30. { discriminate. }\n  remember (translate_stmt varmap offset s20_2) as else30.\n  destruct else30. { discriminate. }\n  inversion StmtOk. subst s30. cbn.\n  clear s m.\n  assert (Hcond := interpret_translated_expr\n                            Ebound builtins fc ok DoCallOk world locmap locmem _ _\n                            (N.succ offset) Agree Bound\n                            (N.lt_succ_diag_r _) (eq_sym Heqcond30)\n                            (Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                            (L20.Callset.callset_descend_stmt_if_cond eq_refl CallOk20)).\n  cbn in Hcond.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct L20.Expr.interpret_expr as (world20, result20).\n  destruct Hcond as (Cond_world, (Cond_mem, Cond_result)).\n  destruct result20, result30; try easy.\n  2:{ (* error in condition *)\n    split. { trivial. }\n    split. { assumption. }\n    apply (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree offset (N.succ offset) Bound\n                                   (N.lt_succ_diag_r offset) Cond_mem).\n  }\n  destruct Cond_result as (Cond_result, Cond_value).\n  subst value.\n  (* condition computed *)\n  destruct (Z_of_uint256 (OpenArray.get mem30 offset) =? 0)%Z.\n  { (* else *)\n    subst world30.\n    assert (IH := IHs20_2 world20 offset varmap _ (eq_sym Heqelse30) mem30 locmap VI\n                          (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                                   _ _ Bound (N.lt_succ_diag_r offset) Cond_mem)\n                          Bound\n                          (L30.Callset.callset_descend_stmt_if_else eq_refl\n                            (L30.Callset.callset_descend_semicolon_right eq_refl CallOk30))\n                          (L20.Callset.callset_descend_stmt_if_else eq_refl CallOk20)).\n    cbn in IH.\n    destruct L30.Stmt.interpret_stmt as ((world30', mem30'), result30').\n    destruct (L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins world20 locmap s20_2\n                (L20.Callset.callset_descend_stmt_if_else eq_refl CallOk20)) as (world20', result20').\n    now destruct result20', result30'.\n  }\n  (* then *)\n  subst world30.\n  assert (IH := IHs20_1 world20 offset varmap _ (eq_sym Heqthen30) mem30 locmap VI\n                        (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                                 _ _ Bound (N.lt_succ_diag_r offset) Cond_mem)\n                        Bound\n                        (L30.Callset.callset_descend_stmt_if_then eq_refl\n                          (L30.Callset.callset_descend_semicolon_right eq_refl CallOk30))\n                        (L20.Callset.callset_descend_stmt_if_then eq_refl CallOk20)).\n  cbn in IH.\n  destruct L30.Stmt.interpret_stmt as ((world30', mem30'), result30').\n  destruct (L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins world20 locmap s20_2\n              (L20.Callset.callset_descend_stmt_if_else eq_refl CallOk20)) as (world20', result20').\n  now destruct result20', result30'.\n}\n2:{ (* Semicolon *)\n  cbn in StmtOk.\n  remember (translate_stmt varmap offset s20_1) as t1.\n  remember (translate_stmt varmap offset s20_2) as t2.\n  destruct t1. { discriminate. }\n  destruct t2. { discriminate. }\n  inversion StmtOk. subst s30. cbn.\n\n  assert (IH_1 := IHs20_1 world offset varmap _ (eq_sym Heqt1) locmem locmap VI Agree Bound\n                          (L30.Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                          (L20.Callset.callset_descend_semicolon_left eq_refl CallOk20)).\n  cbn in IH_1.\n  destruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\n  destruct (L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins world locmap s20_1\n             (L20.Callset.callset_descend_semicolon_left eq_refl CallOk20))\n     as ((world20, mem20), result20).\n  destruct result20, result30; try easy.\n  cbn in IH_1. destruct IH_1 as (IH1_result, (IH1_world, IH1_agree)).\n  clear IH1_result. subst world30.\n\n  assert (IH_2 := IHs20_2 world20 offset varmap _ (eq_sym Heqt2) mem30 mem20 VI \n                          IH1_agree\n                          Bound\n                          (L30.Callset.callset_descend_semicolon_right eq_refl CallOk30)\n                          (L20.Callset.callset_descend_semicolon_right eq_refl CallOk20)).\n  cbn in IH_2.\n  destruct L30.Stmt.interpret_stmt as ((world30', mem30'), result30').\n  destruct (L20.Stmt.interpret_stmt Ebound fc do_call_20 builtins world20 mem20 s20_2\n             (L20.Callset.callset_descend_semicolon_right eq_refl CallOk20))\n     as ((world20', mem20'), result20').\n  now destruct result20', result30'.\n} (* Semicolon *)\n(* -------------------------------------------------------------------------------------------------*)\n(* Loop *)\ncbn in StmtOk.\nremember (map_lookup varmap var) as lookup_var.\ndestruct lookup_var. { discriminate. }\nremember (Z_of_uint256 count =? 0)%Z as count_is_0.\ndestruct count_is_0. { discriminate. }\nremember (translate_expr varmap offset (N.succ offset) start) as start30.\ndestruct start30. { discriminate. }\nremember (translate_stmt (map_insert varmap var offset) (N.succ offset) s20) as body30.\ndestruct body30. { discriminate. }\ninversion StmtOk. subst s30. cbn. clear StmtOk.\nassert (Hstart := interpret_translated_expr\n                          Ebound builtins fc ok DoCallOk world locmap locmem _ _\n                          (N.succ offset) Agree Bound\n                          (N.lt_succ_diag_r _) (eq_sym Heqstart30)\n                          (Callset.callset_descend_semicolon_left eq_refl CallOk30)\n                          (L20.Callset.callset_descend_loop_start eq_refl CallOk20)).\ncbn in Hstart.\ndestruct L30.Stmt.interpret_stmt as ((world30, mem30), result30).\ndestruct L20.Expr.interpret_expr as (world20, result20).\nassert (Q: map_lookup locmap var = None).\n{\n  assert (A := Agree var).\n  unfold map_lookup in *.\n  rewrite<- Heqlookup_var in A.\n  now destruct (Map.lookup locmap var).\n}\nrewrite Q. rewrite<- Heqcount_is_0.\ndestruct result20, result30; try easy.\n2:{ (* start computation failed *)\n  destruct Hstart as (Start_world, (Start_mem, Start_result)).\n  repeat (split; trivial).\n  apply (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree offset (N.succ offset) Bound\n                               (N.lt_succ_diag_r offset) Start_mem).\n}\ndestruct Hstart as (Start_world, (Start_mem, (Start_result, Start_dst))).\nclear Start_result. subst world30. subst value.\nremember (Z_of_uint256 (uint256_of_Z (Z_of_uint256 (OpenArray.get mem30 offset) + Z_of_uint256 count - 1)) =?\n           Z_of_uint256 (OpenArray.get mem30 offset) + Z_of_uint256 count - 1)%Z\n  as no_overflow.\ndestruct no_overflow.\n2:{\n  repeat (split; trivial).\n  apply (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree offset (N.succ offset) Bound\n                                 (N.lt_succ_diag_r offset) Start_mem).\n}\n\n(* start computed, now the loop itself *)\nremember (Z.to_nat (Z_of_uint256 count)) as countdown. (* n in From10To20 *)\nremember (Z_of_uint256 (OpenArray.get mem30 offset)) as cursor.\n\n(* preparing induction *)\nremember (Z_of_uint256 (OpenArray.get mem30 offset) + Z_of_uint256 count - 1)%Z as cap.\n(* In From10To20 this happens within the induction for some reason *)\nassert (CapRange: (0 <= cap < 2 ^ 256)%Z).\n{\n  symmetry in Heqno_overflow. rewrite Z.eqb_eq in Heqno_overflow.\n  rewrite uint256_ok in Heqno_overflow.\n  rewrite Z.mod_small_iff in Heqno_overflow by apply two_to_256_ne_0.\n  subst cursor cap.\n  enough (~ (2 ^ 256 < (Z_of_uint256 (OpenArray.get mem30 offset) + Z_of_uint256 count - 1)%Z <= 0)%Z). \n  { tauto. }\n  intro Y.\n  assert (Bad := proj2 (Z.ltb_lt _ _) (Z.lt_le_trans _ _ _ (proj1 Y) (proj2 Y))).\n  cbn in Bad. discriminate.\n}\n\n(* Here Heqcap is the main loop equation: [\n\n      cap = Z_of_uint256 value + Z_of_uint256 count - 1\n\n  ] where cap is constant, value goes up and count goes down.\nHowever, in our interpretation of the count loop we allow overflow\nduring the last iteration, for example [\n\n    for i in count(2^256 - 2, 2):\n      ...\n\n] is the same as [\n\n    for i in [2^256 - 2, 2^256 - 1]:\n      ...\n] and therefore legit (except that the latter syntax is currently \nnot supported). Therefore the main loop equation must be weakened to this: *)\nassert (WeakMainLoopEq: \n          cap = (cursor + Z_of_uint256 count - 1)%Z\n           \\/\n          Z_of_uint256 count = 0%Z).\n{ left. subst cursor. exact Heqcap. }\nclear Heqcap.\n\nassert (Agree': VarsAgree varmap (map_remove locmap var) mem30).\n{\n  intro x.\n  unfold map_remove.\n  rewrite Map.remove_ok.\n  destruct string_dec.\n  { subst x. unfold map_lookup in Heqlookup_var. rewrite<- Heqlookup_var. trivial. }\n  exact (vars_agree_if_mem_agree varmap locmap locmem mem30 Agree\n                                 _ _ Bound (N.lt_succ_diag_r offset) Start_mem x).\n}\n\nclear Start_mem. (* we don't have a way to carry that through induction; Agree' is what we have instead *)\nclear Agree Q Heqcursor Heqno_overflow Heqcount_is_0.\nrevert count locmap world20 mem30 cursor Agree' WeakMainLoopEq\n       CallOk30 CallOk20 Heqcountdown.\ninduction countdown; intros. (* ----------- induction -------------*)\n{ repeat (split; trivial). }\n(* the following has plenty of dup from LocalVarDecl: *)\nassert (BodyInj: VarmapInj (map_insert varmap var offset)).\n{\n  unfold VarmapInj. intros x y.\n  unfold map_insert. repeat rewrite Map.insert_ok.\n  assert (VIxy := VI x y).\n  destruct (string_dec var x).\n  {\n    subst x.\n    destruct (string_dec var y). { easy. }\n    assert (By := Bound y).\n    destruct (Map.lookup varmap y). 2:{ trivial. }\n    intro E. subst.\n    apply N.lt_irrefl in By.\n    contradiction.\n  }\n  destruct (string_dec var y).\n  { (* this is a mirror of the previous branch with x and y swapped *)\n    subst y.\n    assert (Bx := Bound x).\n    destruct (Map.lookup varmap x). 2:{ trivial. }\n    intro E. subst.\n    apply N.lt_irrefl in Bx.\n    contradiction.\n  }\n  apply VIxy.\n}\nassert (BodyAgree: VarsAgree (map_insert varmap var offset) \n                             (map_insert locmap var (uint256_of_Z cursor))\n                             (OpenArray.put mem30 offset (uint256_of_Z cursor))).\n{\n  intro x.\n  unfold map_insert. repeat rewrite Map.insert_ok.\n  assert (A := Agree' x).\n  unfold map_remove in A. rewrite Map.remove_ok in A.\n  destruct (string_dec var x). { now rewrite OpenArray.put_same. }\n  assert (B := Bound x).\n  destruct (Map.lookup locmap x), (Map.lookup varmap x); try easy.\n  rewrite OpenArray.put_ok.\n  enough (F: (offset =? n0)%N = false) by now rewrite F.\n  rewrite N.eqb_neq.\n  intro H. rewrite<- H in B.\n  exact (N.lt_irrefl offset B).\n}\n\nassert (BodyBound: VarsBound (map_insert varmap var offset) (N.succ offset)).\n{\n  intro x.\n  unfold map_insert.\n  rewrite Map.insert_ok.\n  destruct (string_dec var x). { apply N.lt_succ_diag_r. }\n  assert (B := Bound x).\n  destruct (Map.lookup varmap x). 2:{ trivial. }\n  apply N.lt_lt_succ_r. exact B.\n}\n\nassert (BodyOk := IHs20 world20 (N.succ offset) (map_insert varmap var offset) _ (eq_sym Heqbody30)\n                        (OpenArray.put mem30 offset (uint256_of_Z cursor))\n                        (map_insert locmap var (uint256_of_Z cursor))\n                        BodyInj BodyAgree BodyBound\n                        (Callset.callset_descend_loop_body eq_refl\n                          (Callset.callset_descend_semicolon_right eq_refl CallOk30))\n                        (L20.Callset.callset_descend_loop_body eq_refl CallOk20)).\ncbn in BodyOk.\ndestruct L30.Stmt.interpret_stmt as ((world30', mem30'), result30').\ndestruct L20.Stmt.interpret_stmt as ((world20', mem20'), result20').\ndestruct BodyOk as (Body_result, (Body_world, Body_agree)).\nsubst result30' world30'.\nassert (PostBodyAgree: VarsAgree varmap (map_remove mem20' var) mem30').\n{\n  intro x. assert (A := Body_agree x). unfold map_remove.\n  rewrite Map.remove_ok.\n  unfold map_insert in A. repeat rewrite Map.insert_ok in A.\n  destruct (string_dec var x). 2:apply A.\n  subst x. unfold map_lookup in Heqlookup_var. now rewrite<- Heqlookup_var.\n}\n\n(* checking that the counter doesn't go below 0 *)\npose (count' := uint256_of_Z (Z.pred (Z_of_uint256 count))).\nassert (CountOk: countdown = Z.to_nat (Z_of_uint256 count')).\n{\n  unfold count'. rewrite uint256_ok.\n  assert (R := uint256_range count).\n  remember (Z_of_uint256 count) as z. clear Heqz.\n  assert (W: z = Z.succ (Z.of_nat countdown)).\n  {\n    rewrite<- Nat2Z.inj_succ. rewrite Heqcountdown.\n    symmetry. apply Z2Nat.id. tauto.\n  }\n  subst z. rewrite Z.pred_succ.\n  replace (Z.of_nat countdown mod 2 ^ 256)%Z with (Z.of_nat countdown).\n  { symmetry. apply Nat2Z.id. }\n  symmetry. apply Z.mod_small.\n  split.\n  { (* 0 <= countdown *) apply Nat2Z.is_nonneg. }\n  exact (Z.lt_trans _ _ _ (Z.lt_succ_diag_r (Z.of_nat countdown)) (proj2 R)).\n}\n\n(* strengthening WeakMainLoopEq *)\nassert (MainLoopEq: cap = (cursor + Z_of_uint256 count - 1)%Z).\n{\n  enough (Z_of_uint256 count <> 0%Z). { tauto. }\n  intro J. rewrite J in *.\n  cbn in Heqcountdown. discriminate.\n}\n\nassert (NextLoopEq: cap = (Z.succ cursor + Z_of_uint256 count' - 1)%Z).\n{\n  rewrite MainLoopEq.\n  enough (Z_of_uint256 count = Z_of_uint256 count' + 1)%Z by lia.\n  subst countdown.\n  assert (R := uint256_range count).\n  assert (R' := uint256_range count').\n  lia.\n}\n\nassert (WeakNextLoopEq: (cap = Z.succ cursor + Z_of_uint256 count' - 1 \\/ Z_of_uint256 count' = 0)%Z).\n{ left. apply NextLoopEq. }\n\nassert (IH := IHcountdown count' mem20' world20' mem30' (Z.succ cursor)\n                          PostBodyAgree WeakNextLoopEq CallOk30 CallOk20 CountOk).\n\nassert (FixCall30:\n            (@Callset.callset_descend_loop_body C (@AST.Loop C offset count' s1) s1 offset count'\n               (@Callset.decl_callset C\n                  (@cached_translated_decl C bigger_call_depth_bound cd20 fc cd30 ok))\n               (@eq_refl (@AST.stmt C) (@AST.Loop C offset count' s1))\n               (@Callset.callset_descend_semicolon_right C s0 (@AST.Loop C offset count' s1)\n                  (@AST.Semicolon C s0 (@AST.Loop C offset count' s1))\n                  (@Callset.decl_callset C\n                     (@cached_translated_decl C bigger_call_depth_bound cd20 fc cd30 ok))\n                  (@eq_refl (@AST.stmt C) (@AST.Semicolon C s0 (@AST.Loop C offset count' s1)))\n                  CallOk30))\n              =\n            (@Callset.callset_descend_loop_body C (@AST.Loop C offset count s1) s1 offset count\n          (@Callset.decl_callset C\n             (@cached_translated_decl C bigger_call_depth_bound cd20 fc cd30 ok))\n          (@eq_refl (@AST.stmt C) (@AST.Loop C offset count s1))\n          (@Callset.callset_descend_semicolon_right C s0 (@AST.Loop C offset count s1)\n             (@AST.Semicolon C s0 (@AST.Loop C offset count s1))\n             (@Callset.decl_callset C\n                (@cached_translated_decl C bigger_call_depth_bound cd20 fc cd30 ok))\n             (@eq_refl (@AST.stmt C) (@AST.Semicolon C s0 (@AST.Loop C offset count s1))) CallOk30))).\n{ apply PropExtensionality.proof_irrelevance. }\nrewrite FixCall30 in IH. clear FixCall30.\n\nassert (FixCall20:\n          (@L20.Callset.callset_descend_loop_body C (@L20.AST.Loop C var start count' s20) s20\n             var start count'\n             (@L20.Callset.decl_callset C\n                (@fun_decl C (@L20.AST.decl C) (@L20.Callset.decl_callset C) false cd20\n                   bigger_call_depth_bound fc))\n             (@eq_refl (@L20.AST.stmt C) (@L20.AST.Loop C var start count' s20)) CallOk20)\n            =\n          (@L20.Callset.callset_descend_loop_body C (@L20.AST.Loop C var start count s20) s20\n                var start count\n                (@L20.Callset.decl_callset C\n                   (@fun_decl C (@L20.AST.decl C) (@L20.Callset.decl_callset C) false cd20\n                      bigger_call_depth_bound fc))\n                (@eq_refl (@L20.AST.stmt C) (@L20.AST.Loop C var start count s20)) CallOk20)).\n{ apply PropExtensionality.proof_irrelevance. }\nrewrite FixCall20 in IH. clear FixCall20.\n\ndestruct result20'; try easy.\nnow destruct a.\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/From20To30/Stmt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.17278945444051216}}
{"text": "Require Import LambdaANF.cps LambdaANF.size_cps LambdaANF.cps_util LambdaANF.eval LambdaANF.logical_relations LambdaANF.set_util LambdaANF.identifiers LambdaANF.ctx\n        LambdaANF.Ensembles_util LambdaANF.List_util LambdaANF.alpha_conv LambdaANF.functions LambdaANF.uncurry\n        LambdaANF.shrink_cps_correct.\nRequire Import FunInd.\nRequire Import Coq.ZArith.Znumtheory Coq.Relations.Relations Coq.Arith.Wf_nat.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List Coq.MSets.MSets Coq.MSets.MSetRBT Coq.Numbers.BinNums\n        Coq.NArith.BinNat Coq.PArith.BinPos Coq.Sets.Ensembles micromega.Lia.\nRequire Import ExtLib.Structures.Monads ExtLib.Data.Monads.StateMonad.\n\nRequire Import Common.compM.\n\nImport ListNotations MonadNotation.\n\nSection list_lemmas.\n  Lemma set_lists_length : forall {A} (l : list M.elt) (l1 : list A) (rho rho1 : M.t A),\n    Some rho1 = set_lists l l1 rho -> length l = length l1.\n  Proof.\n    induction l; intros.\n    - (* [] *) destruct l1; [easy|now simpl in H].\n    - (* :: *) destruct l1; [now simpl in H|].\n      simpl. apply f_equal.\n      remember (set_lists l l1 rho).\n      destruct o.\n      + eapply IHl. simpl in H. eapply Heqo.\n      + simpl in H. now rewrite <- Heqo in H.\n  Qed.\n\n  Lemma exists_set_lists_iff_length : forall {A} (l : list M.elt) (l1 : list A) (rho : M.t A),\n    (exists rho1, Some rho1 = set_lists l l1 rho) <-> length l = length l1.\n  Proof.\n    induction l; split; intros.\n    - (* [] -> *) destruct H. destruct l1; [easy|now simpl in H].\n    - (* [] <- *) destruct l1; [now exists rho|easy].\n    - (* :: -> *) destruct H. destruct l1; [now simpl in H|].\n      simpl. apply f_equal.\n      simpl in H. remember (set_lists l l1 rho).\n      destruct o; [|congruence].\n      rewrite <- IHl with (rho := rho). now exists t. \n    - (* :: <- *) destruct l1; [easy|]. simpl in H. apply NPeano.Nat.succ_inj in H.\n      rewrite <- IHl with (rho := rho) in H. destruct H.\n      simpl. rewrite <- H. now exists (M.set a a0 x).\n  Qed.\n\n  Corollary exists_set_lists_length : forall {A} (l : list M.elt) (l1 : list A) (rho : M.t A),\n    (exists rho1, Some rho1 = set_lists l l1 rho) -> length l = length l1.\n  Proof. intros; now rewrite <- @exists_set_lists_iff_length with (rho := rho). Qed.\n\n  Corollary length_exists_set_lists : forall {A} (l : list M.elt) (l1 : list A) (rho : M.t A),\n     length l = length l1 -> (exists rho1, Some rho1 = set_lists l l1 rho).\n  Proof. intros; now rewrite @exists_set_lists_iff_length with (rho := rho). Qed.\n\n  (* nesting set_listss (TODO: move to cps.v?) *)\n  Lemma set_lists_set_lists : forall {A} (l l1 : list M.elt) (v v1 : list A) (rho rho1 rho2 : M.t A),\n    Some rho1 = set_lists l v rho ->\n    Some rho2 = set_lists l1 v1 rho1 ->\n    Some rho2 = set_lists (l1 ++ l) (v1 ++ v) rho.\n  Proof.\n    induction l1.\n    - (* [] *)\n      intros. assert (v1 = []) by (apply set_lists_length in H0; now destruct v1). subst.\n      inversion H0. now subst.\n    - (* :: *)\n      intros. destruct v1; [apply set_lists_length in H0; inversion H0|].\n      simpl in *. remember (set_lists l1 v1 rho1). destruct o; [|congruence].\n      now rewrite <- (IHl1 _ _ _ _ _ H Heqo).\n  Qed.\n\n  (* expose an M.set from a successful set_lists *)\n  Lemma set_set_lists : forall {A} h h1 (t : list M.elt) (t1 : list A) (rho rho2 : M.t A),\n    Some rho2 = set_lists (h :: t) (h1 :: t1) rho -> exists rho1,\n    rho2 = M.set h h1 rho1 /\\ Some rho1 = set_lists t t1 rho.\n  Proof.\n    simpl. intros. remember (set_lists t t1 rho). destruct o; [|congruence].\n    inversion H. inversion H. subst. eauto.\n  Qed.\n\n  Lemma set_lists_set : forall {A} a b (l : list M.elt) (v : list A) (rho : M.t A),\n    set_lists l v (M.set a b rho) = set_lists (l ++ [a]) (v ++ [b]) rho.\n  Proof.\n    induction l; intros.\n    - (* [] *) destruct v; [easy|destruct v; easy].\n    - (* :: *) destruct v. simpl.\n      assert (set_lists (l ++ [a]) [] rho = None) by (now destruct l). now rewrite H.\n      simpl in *.\n      remember (set_lists l v (M.set a b rho)).\n      remember (set_lists (l ++ [a]) (v ++ [b]) rho).\n      destruct o, o0; [| | |auto].\n      + rewrite <- IHl in Heqo0. rewrite <- Heqo in Heqo0. inversion Heqo0; now subst.\n      + apply set_lists_length in Heqo.\n        assert (length (l ++ [a]) = length (v ++ [b]))\n          by (repeat rewrite app_length; now rewrite Heqo).\n        apply @length_exists_set_lists with (rho := rho) in H. destruct H. congruence.\n      + assert (length l = length v). {\n          apply set_lists_length in Heqo0. \n          repeat rewrite app_length in Heqo0. simpl in Heqo0. lia.\n        }\n        apply @length_exists_set_lists with (rho := (M.set a b rho)) in H. destruct H. congruence.\n  Qed.\n\n  Lemma list_length_cons : forall {A} {B} h (l : list A) (t : list B),\n    length l = length (h :: t) -> exists h1 t1, l = h1 :: t1.\n  Proof. intros. destruct l; [easy|now exists a, l]. Qed.\n\n  Lemma list_length_snoc : forall {A} {B} (l : list A) (a : list B) b,\n    length l = length (a ++ [b]) -> exists a1 b1, l = a1 ++ [b1].\n  Proof.\n    induction l; intros.\n    - rewrite app_length in H. inversion H. rewrite Plus.plus_comm in H1. inversion H1.\n    - destruct a0.\n      + assert (l = []) by (destruct l; [easy|inversion H]). subst.\n        now exists [], a.\n      + inversion H. destruct (IHl _ _ H1) as [a1 [b1 Hab1]].\n        exists (a :: a1), b1. simpl. now apply f_equal.\n  Qed.\n\n  Lemma set_lists_fresh : forall {A} v1 v v2 w1 w w2 (rho rho1 : M.t A),\n    length v1 = length w1 ->\n    ~ List.In v v1 ->\n    Some rho1 = set_lists (v1 ++ [v] ++ v2) (w1 ++ [w] ++ w2) rho ->\n    M.get v rho1 = Some w.\n  Proof.\n    induction v1.\n    - intros. assert (w1 = []) by (destruct w1; easy; inversion H). subst.\n      simpl in H1. remember (set_lists v2 w2 rho).\n      destruct o; [|congruence]. inversion H1. now rewrite M.gss.\n    - intros. symmetry in H.\n      destruct (list_length_cons _ _ _ H) as [w1h [w1t Hw1]]. subst.\n      inversion H.\n      simpl in H1. remember (set_lists (v1 ++ v :: v2) (w1t ++ w :: w2) rho).\n      destruct o; [|congruence]. inversion H1; subst.\n      rewrite not_in_cons in H0. destruct H0.\n      rewrite M.gso; [|assumption].\n      eapply IHv1; [symmetry; eassumption|assumption|simpl; eassumption].\n  Qed.\n\n  Lemma get_list_set_lists_app : forall {A} v v1 w w1 (rho rho1 : M.t A),\n    length v = length w ->\n    NoDup v ->\n    Some rho1 = set_lists (v ++ v1) (w ++ w1) rho ->\n    get_list v rho1 = Some w.\n  Proof.\n    induction v; intros.\n    - assert (w = []) by (destruct w; easy; inversion H). now subst.\n    - inversion H0; subst. destruct w; [inversion H|].\n      simpl in H1. remember (set_lists (v ++ v1) (w ++ w1) rho).\n      destruct o; [|congruence]. inversion H1; subst.\n      simpl. rewrite get_list_set_neq; [|assumption].\n      erewrite IHv; [now rewrite M.gss|now inversion H|assumption|eassumption].\n  Qed.\n\n  Lemma Disjoint_FromList_cons_right : forall {A} (a : list A) h t,\n    Disjoint _ (FromList a) (FromList (h :: t)) ->\n    Disjoint _ (FromList a) (FromList t).\n  Proof.\n    intros. constructor. intros x contra.\n    inv contra. inv H.\n    contradiction (H2 x).\n    constructor; [|right]; assumption.\n  Qed.\n\n  Lemma get_list_set_lists_disjoint_app : forall {A} u v w v1 w1 (rho rho1 : M.t A),\n    Disjoint _ (FromList u) (FromList v) ->\n    length v = length w ->\n    Some rho1 = set_lists (v ++ v1) (w ++ w1) rho ->\n    exists rho2, Some rho2 = set_lists v1 w1 rho /\\ get_list u rho1 = get_list u rho2.\n  Proof.\n    induction v; intros.\n    - assert (w = []) by (destruct w; easy; inversion H). subst. now exists rho1.\n    - destruct w; inversion H0.\n      simpl in H1. remember (set_lists (v ++ v1) (w ++ w1) rho).\n      destruct o; [inversion H1; subst|congruence].\n      replace (get_list u (M.set a a0 t)) with (get_list u t).\n      eapply IHv; [|eassumption|assumption].\n      eapply Disjoint_FromList_cons_right. eassumption.\n      symmetry. apply get_list_set_neq.\n      intros contra. inversion H. contradiction (H2 a).\n      split; [assumption|now left].\n  Qed.\n\n  Lemma list_in_iff_Included : forall {A} a (l : list A),\n    List.In a l <-> In _ (FromList l) a.\n  Proof. split; intros; auto. Qed.\n\n  Lemma not_list_in_app : forall {A} a (l r : list A),\n    ~ List.In a (l ++ r) <-> ~ List.In a l /\\ ~ List.In a r.\n  Proof.\n    split; intros.\n    - induction l. split; [auto|]. assumption.\n      apply not_in_cons in H. destruct H.\n      destruct (IHl H0) as [H1 H2].\n      split; [|assumption].\n      intros [HL|HR]; congruence.\n    - destruct H. induction l. simpl. assumption.\n      apply not_in_cons in H. destruct H.\n      simpl. intros [HL|HR]; [congruence|now apply IHl in H1].\n  Qed.\nEnd list_lemmas.\n\n(* need a stronger definition of size to prove that the functional\n   induction scheme is well-founded *)\n(* Print exp. *)\nFixpoint sizeof_exp e : nat :=\n  match e with\n    (Econstr x _ ys e) => 1 + length ys + sizeof_exp e\n  | (Ecase x l) =>\n    1 + (fix sizeof_l l :=\n            match l with\n              [] => 0\n            | (t, e) :: l => 1 + sizeof_exp e + sizeof_l l\n            end) l\n  | (Eproj x _ _ y e) => 1 + sizeof_exp e\n  | (Eletapp _ _ _ xs e) => 1 + length xs + sizeof_exp e\n  | (Efun fds e) => 1 + sizeof_fundefs fds + sizeof_exp e\n  | (Eapp x _ ys) => 1 + length ys\n  | (Eprim x _ ys e) => 1 + length ys + sizeof_exp e\n  | (Eprim_val x p e) => 1 + sizeof_exp e\n  | (Ehalt x) => 1\n  end\nwith sizeof_fundefs f : nat := \n  match f with\n  | Fcons f t v e fds => 1 + sizeof_exp e + sizeof_fundefs fds\n  | Fnil => 0\n  end.\n\nDefinition sizeof (a : exp + fundefs) : nat :=\n  match a with inl e => sizeof_exp e | inr f => sizeof_fundefs f end.\n\nDefinition reflect_eq_var (a b : var) : (a = b) + (a <> b) :=\n  match Pos.eqb_spec a b with\n    ReflectT yes => inl yes\n  | ReflectF no => inr no\n  end.\n\n(* all variables in a list are distinct and disjoint from some set of used vars *)\nDefinition fresh_copies (s : Ensemble var) (l : list var) : Prop\n  := Disjoint _ s (FromList l) /\\ NoDup l.\n\n(* \"a small step\" of uncurrying *)\nInductive uncurry_step :\n  exp -> (* original expression *)\n  Ensemble var -> (* used variables *)\n  localMap -> (* already uncurried functions *)\n  exp -> (* expression w/ 1 function uncurried *)\n  Ensemble var -> (* new used variables *)\n  localMap -> (* new uncurried functions *)\n  Prop :=\n| uncurry_letapp : forall x f ft ys e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Eletapp x f ft ys e) s m (Eletapp x f ft ys e1) s1 m1\n| uncurry_constr : forall x c args e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Econstr x c args e) s m (Econstr x c args e1) s1 m1\n| uncurry_case_expr : forall x arms c e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Ecase x ((c, e) :: arms)) s m (Ecase x ((c, e1) :: arms)) s1 m1\n| uncurry_case_arms : forall x arms arms1 arm s s1 m m1,\n    uncurry_step (Ecase x arms) s m (Ecase x arms1) s1 m1 ->\n    uncurry_step (Ecase x (arm :: arms)) s m (Ecase x (arm :: arms1)) s1 m1\n| uncurry_proj : forall x c n y e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Eproj x c n y e) s m (Eproj x c n y e1) s1 m1\n| uncurry_prim_val : forall x p e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Eprim_val x p e) s m (Eprim_val x p e1) s1 m1\n| uncurry_prim : forall x p args e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Eprim x p args e) s m (Eprim x p args e1) s1 m1\n| uncurry_fun_expr : forall fds e e1 s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (Efun fds e) s m (Efun fds e1) s1 m1\n| uncurry_fun_fds : forall fds fds1 e s s1 m m1,\n    uncurry_fundefs_step fds s m fds1 s1 m1 ->\n    uncurry_step (Efun fds e) s m (Efun fds1 e) s1 m1\nwith uncurry_fundefs_step :\n  fundefs ->\n  Ensemble var ->\n  localMap ->\n  fundefs ->\n  Ensemble var ->\n  localMap ->\n  Prop :=\n| uncurry_fundefs_fds : forall f t args e fds fds1 s s1 m m1,\n    uncurry_fundefs_step fds s m fds1 s1 m1 ->\n    uncurry_fundefs_step (Fcons f t args e fds) s m (Fcons f t args e fds1) s1 m1\n| uncurry_fundefs_e : forall f t args e e1 fds s s1 m m1,\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_fundefs_step (Fcons f t args e fds) s m (Fcons f t args e1 fds) s1 m1\n| uncurry_fundefs_curried :\n    forall f f1 ft ft1 k kt fv fv1\n           g gt gv gv1 ge fds s m s',\n    match M.get g m with Some true => true | _ => false end = false ->\n    occurs_in_exp g ge = false ->\n    occurs_in_exp k ge = false ->\n    fresh_copies s gv1 ->\n    length gv1 = length gv ->\n    fresh_copies (s :|: FromList gv1) fv1 ->\n    length fv1 = length fv ->\n    ~(In _ (s :|: FromList gv1 :|: FromList fv1) f1) ->\n    s' <--> s :|: FromList gv1 :|: FromList fv1 :|: [set f1] ->\n    uncurry_fundefs_step \n      (Fcons f ft (k :: fv) (Efun (Fcons g gt gv ge Fnil) (Eapp k kt [g])) fds) s m\n      (Fcons f ft (k :: fv1)\n         (Efun (Fcons g gt gv1 (Eapp f1 ft1 (gv1 ++ fv1)) Fnil) (Eapp k kt [g]))\n         (Fcons f1 ft1 (gv ++ fv) ge fds))\n      s' \n      (M.set g true m)\n      (* TODO: restrict ft1? *)\n| uncurry_fundefs_curried_anf :\n    forall f f1 ft ft1 fv fv1\n           g gt gv gv1 ge fds s m s',\n    match M.get g m with Some true => true | _ => false end = false ->\n    occurs_in_exp g ge = false ->\n    fresh_copies s gv1 ->\n    length gv1 = length gv ->\n    fresh_copies (s :|: FromList gv1) fv1 ->\n    length fv1 = length fv ->\n    ~(In _ (s :|: FromList gv1 :|: FromList fv1) f1) ->\n    s' <--> s :|: FromList gv1 :|: FromList fv1 :|: [set f1] ->\n    uncurry_fundefs_step \n      (Fcons f ft fv (Efun (Fcons g gt gv ge Fnil) (Ehalt g)) fds) s m\n      (Fcons f ft fv1\n         (Efun (Fcons g gt gv1 (Eapp f1 ft1 (gv1 ++ fv1)) Fnil) (Ehalt g))\n         (Fcons f1 ft1 (gv ++ fv) ge fds))\n      s' \n      (M.set g true m).\n\nHint Constructors uncurry_step : core.\nHint Constructors uncurry_fundefs_step : core.\n\nScheme uncurry_step_mut := Minimality for uncurry_step Sort Prop\nwith uncurry_step_fundefs_mut := Minimality for uncurry_fundefs_step Sort Prop.\n\nLtac uncurry_step_induction P Q IHuncurry IH :=\n  apply uncurry_step_mut with (P := P) (P0 := Q);\n  [ intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros\n  | intros\n  ].\n\nLemma uncurry_step_mutual_ind : \nforall (P : exp -> Ensemble var -> localMap -> exp -> Ensemble var -> localMap -> Prop)\n  (P0 : fundefs -> Ensemble var -> localMap -> fundefs -> Ensemble var -> localMap -> Prop),\n(forall (x f : var) (ft : fun_tag) (ys : list var) (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1 -> P (Eletapp x f ft ys e) s m (Eletapp x f ft ys e1) s1 m1) ->\n(forall (x : var) (c : ctor_tag) (args : list var) (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 ->\n P e s m e1 s1 m1 -> P (Econstr x c args e) s m (Econstr x c args e1) s1 m1) ->\n(forall (x : var) (arms : list (ctor_tag * exp)) (c : ctor_tag) (e e1 : exp) (s s1 : Ensemble var)\n   (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 ->\n P e s m e1 s1 m1 -> P (Ecase x ((c, e) :: arms)) s m (Ecase x ((c, e1) :: arms)) s1 m1) ->\n(forall (x : var) (arms arms1 : list (ctor_tag * exp)) (arm : ctor_tag * exp) (s s1 : Ensemble var)\n   (m m1 : localMap),\n uncurry_step (Ecase x arms) s m (Ecase x arms1) s1 m1 ->\n P (Ecase x arms) s m (Ecase x arms1) s1 m1 ->\n P (Ecase x (arm :: arms)) s m (Ecase x (arm :: arms1)) s1 m1) ->\n(forall (x : var) (c : ctor_tag) (n : N) (y : var) (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1 -> P (Eproj x c n y e) s m (Eproj x c n y e1) s1 m1) ->\n(forall (x : var) p (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 ->\n P e s m e1 s1 m1 -> P (Eprim_val x p e) s m (Eprim_val x p e1) s1 m1) ->\n(forall (x : var) (p : prim) (args : list var) (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 ->\n P e s m e1 s1 m1 -> P (Eprim x p args e) s m (Eprim x p args e1) s1 m1) ->\n(forall (fds : fundefs) (e e1 : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1 -> P (Efun fds e) s m (Efun fds e1) s1 m1) ->\n(forall (fds fds1 : fundefs) (e : exp) (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_fundefs_step fds s m fds1 s1 m1 ->\n P0 fds s m fds1 s1 m1 -> P (Efun fds e) s m (Efun fds1 e) s1 m1) ->\n(forall (f6 : var) (t : fun_tag) (args : list var) (e : exp) (fds fds1 : fundefs) \n   (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_fundefs_step fds s m fds1 s1 m1 ->\n P0 fds s m fds1 s1 m1 -> P0 (Fcons f6 t args e fds) s m (Fcons f6 t args e fds1) s1 m1) ->\n(forall (f7 : var) (t : fun_tag) (args : list var) (e e1 : exp) (fds : fundefs) \n   (s s1 : Ensemble var) (m m1 : localMap),\n uncurry_step e s m e1 s1 m1 ->\n P e s m e1 s1 m1 -> P0 (Fcons f7 t args e fds) s m (Fcons f7 t args e1 fds) s1 m1) ->\n(forall (f9 f10 : var) (ft ft1 : fun_tag) (k : var) (kt : fun_tag) (fv fv1 : list var) \n   (g : positive) (gt : fun_tag) (gv gv1 : list var) (ge : exp) (fds : fundefs) \n   (s : Ensemble var) (m : M.t bool) (s' : Ensemble var),\n match M.get g m with\n | Some true => true\n | Some false => false\n | None => false\n end = false ->\n occurs_in_exp g ge = false ->\n occurs_in_exp k ge = false ->\n fresh_copies s gv1 ->\n length gv1 = length gv ->\n fresh_copies (s :|: FromList gv1) fv1 ->\n length fv1 = length fv ->\n ~ In var (s :|: FromList gv1 :|: FromList fv1) f10 ->\n s' <--> s :|: FromList gv1 :|: FromList fv1 :|: [set f10] ->\n P0 (Fcons f9 ft (k :: fv) (Efun (Fcons g gt gv ge Fnil) (Eapp k kt [g])) fds) s m\n   (Fcons f9 ft (k :: fv1) (Efun (Fcons g gt gv1 (Eapp f10 ft1 (gv1 ++ fv1)) Fnil) (Eapp k kt [g]))\n      (Fcons f10 ft1 (gv ++ fv) ge fds)) s'\n   (M.set g true m)) ->\n(forall (f10 f11 : var) (ft ft1 : fun_tag) (fv fv1 : list var) (g : positive) (gt : fun_tag)\n        (gv gv1 : list var) (ge : exp) (fds : fundefs) (s : Ensemble var) (m : M.t bool) \n        (s' : Ensemble var),\n      match m ! g with\n      | Some true => true\n      | _ => false\n      end = false ->\n      occurs_in_exp g ge = false ->\n      fresh_copies s gv1 ->\n      Datatypes.length gv1 = Datatypes.length gv ->\n      fresh_copies (s :|: FromList gv1) fv1 ->\n      Datatypes.length fv1 = Datatypes.length fv ->\n      ~ In var (s :|: FromList gv1 :|: FromList fv1) f11 ->\n      s' <--> s :|: FromList gv1 :|: FromList fv1 :|: [set f11] ->\n      P0 (Fcons f10 ft fv (Efun (Fcons g gt gv ge Fnil) (Ehalt g)) fds) s m\n        (Fcons f10 ft fv1 (Efun (Fcons g gt gv1 (Eapp f11 ft1 (gv1 ++ fv1)) Fnil) (Ehalt g))\n           (Fcons f11 ft1 (gv ++ fv) ge fds)) s' (M.set g true m)) ->\n  (forall (e : exp) (e0 : Ensemble var) (l : localMap) (e1 : exp) (e2 : Ensemble var)\n    (l0 : localMap), uncurry_step e e0 l e1 e2 l0 -> P e e0 l e1 e2 l0) /\\\n  (forall (f10 : fundefs) (e : Ensemble var) (l : localMap) (f11 : fundefs) \n    (e0 : Ensemble var) (l0 : localMap),\n    uncurry_fundefs_step f10 e l f11 e0 l0 ->\n    P0 f10 e l f11 e0 l0).\nProof.\n  intros. split.\n  apply (uncurry_step_mut P P0); assumption.\n  apply (uncurry_step_fundefs_mut P P0); assumption.\nQed.\n\n(* to do proofs simultaneously *) \nLtac uncurry_step_induction_mut P Q IHuncurry IH :=\n  apply uncurry_step_mutual_ind with (P := P) (P0 := Q);\n  [ intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros ? ? ? ? ? ? ? ? ? ? IHuncurry IH\n  | intros\n  | intros\n  ].\n\nLemma Union_Included_subst : forall {A} (a : Ensemble A) b b' c,\n  a \\subset b :|: c -> b \\subset b' -> a \\subset b' :|: c.\nProof with eauto with Ensembles_DB.\n  intros A a b b' c Hb Hb' x Hx.\n  destruct Hb with (x := x)...\nQed.\n\nLemma name_in_fundefs_bound_var_fundefs : forall fds,\n  name_in_fundefs fds \\subset bound_var_fundefs fds.\nProof with auto.\n  induction fds; [|simpl;auto with Ensembles_DB].\n  inversion 1; subst.\n  - inversion H0; subst...\n  - apply IHfds in H0...\nQed.\n\nLemma set_lists_set_permut : forall {A} x (y : A) xs ys rho rho',\n  ~ List.In x xs ->\n  Some rho' = set_lists xs ys (M.set x y rho) -> exists rho1,\n  Some rho1 = set_lists xs ys rho /\\ forall a,\n  M.get a rho' = M.get a (M.set x y rho1).\nProof.\n  intros A x y xs ys rho rho' Hx Hrho.\n  assert (Hrho1 : length xs = length ys) by now apply set_lists_length in Hrho.\n  eapply length_exists_set_lists in Hrho1; destruct Hrho1 as [rho1 Hrho1].\n  exists rho1; split; [apply Hrho1|].\n  intros a.\n  split_var_in_list a xs.\n  - assert (forall A (l : list A), Forall2 eq l l) by (induction l; auto); specialize H with (l := ys).\n    symmetry in Hrho, Hrho1.\n    destruct (set_lists_Forall2_get _ _ _ _ _ _ _ _ _ H Hrho Hrho1 i)\n      as [v1 [v2 [Hv1 [Hv2 Hv1_v2]]]]; subst.\n    rewrite M.gso.\n    transitivity (Some v2); auto.\n    intros Ha; contradiction Hx; now subst.\n  - erewrite <- set_lists_not_In; [|symmetry in Hrho; apply Hrho|assumption].\n    split_var_eq a x; [subst; now do 2 rewrite M.gss|].\n    do 2 (rewrite M.gso; [|assumption]).\n    erewrite <- @set_lists_not_In with (rho' := rho1); eauto.\nQed.\n\nLemma Ensemble_In : forall {U : Type} S a,\n  In U S a -> S a.\nProof. auto. Qed.\n\nLemma find_def_fundefs_append_eq : forall f B B1,\n  name_in_fundefs B f ->\n  find_def f (fundefs_append B B1) = find_def f B.\nProof.\n  induction B.\n  - intros; simpl.\n    destruct (M.elt_eq f v); subst; auto.\n    rewrite IHB; auto.\n    inv H; auto.\n    now inv H0.\n  - inversion 1.\nQed.\n\nLemma find_def_fundefs_append_neq : forall f B B1,\n  ~ name_in_fundefs B f ->\n  find_def f (fundefs_append B B1) = find_def f B1.\nProof.\n  induction B.\n  - intros; simpl.\n    destruct (M.elt_eq f v); subst.\n    contradiction H; now left.\n    apply IHB; intros contra.\n    contradiction H; now right.\n  - auto.\nQed.\n\nLemma occurs_free_fundefs_append : forall fds1 fds a,\n  ~ In _ (name_in_fundefs fds1) a ->\n  occurs_free_fundefs fds a ->\n  occurs_free_fundefs (fundefs_append fds1 fds) a.\nProof.\n  induction fds1.\n  intros fds a Ha Hfds.\n  simpl; apply Free_Fcons2.\n  apply IHfds1; auto.\n  intros contra; contradiction Ha.\n  now right.\n  intros contra; subst; contradiction Ha; now left.\n  auto.\nQed.\n\nLemma occurs_free_fundefs_append_l : forall fds1 fds a,\n  ~ In _ (name_in_fundefs fds) a ->\n  occurs_free_fundefs fds1 a ->\n  occurs_free_fundefs (fundefs_append fds1 fds) a.\nProof.\n  induction fds1.\n  intros fds a Ha Hfds.\n  inv Hfds.\n  constructor; auto.\n  intros contra.\n  assert (In _ (name_in_fundefs (fundefs_append fds1 fds)) a) by auto.\n  rewrite fundefs_append_name_in_fundefs in H; [|reflexivity].\n  inv H; contradiction.\n  apply Free_Fcons2; auto.\n  inversion 2.\nQed.\n\nLemma find_def_fundefs_append_neq_l: forall (f : var) (B B1 : fundefs),\n  unique_bindings_fundefs (fundefs_append B B1) ->\n  ~ name_in_fundefs B1 f ->\n  find_def f (fundefs_append B B1) = find_def f B.\nProof.\n  induction B.\n  intros B1 Huniq Hname.\n  simpl.\n  destruct (M.elt_eq f v); auto.\n  inv Huniq.\n  apply IHB; auto.\n  intros.\n  rewrite name_not_in_fundefs_find_def_None; auto.\nQed.\n\nLemma fundefs_append_unique : forall (f : var) (B B1 : fundefs),\n  unique_bindings_fundefs (fundefs_append B B1) ->\n  name_in_fundefs B1 f ->\n  ~ name_in_fundefs B f.\nProof.\n  induction B.\n  intros B1 Huniq Hname.\n  intros contra.\n  inv contra.\n  inv H.\n  inv Huniq.\n  contradiction H5.\n  apply Ensemble_In; erewrite fundefs_append_bound_vars; [|reflexivity]; right.\n  now apply name_in_fundefs_bound_var_fundefs.\n  inv Huniq.\n  unfold not in IHB; eapply IHB; eauto.\n  inversion 3.\nQed.\n\nLemma fundefs_append_unique_l : forall (f : var) (B1 B : fundefs),\n  unique_bindings_fundefs (fundefs_append B1 B) ->\n  name_in_fundefs B1 f ->\n  ~ name_in_fundefs B f.\nProof.\n  induction B1.\n  intros B Huniq Hname.\n  intros contra.\n  inv Hname.\n  inv H.\n  inv Huniq.\n  contradiction H5.\n  apply Ensemble_In; erewrite fundefs_append_bound_vars; [|reflexivity]; right.\n  now apply name_in_fundefs_bound_var_fundefs.\n  inv Huniq.\n  unfold not in IHB1; eapply IHB1; eauto.\n  inversion 2.\nQed.\n\nLemma fundefs_append_unique_and : forall B B1,\n  unique_bindings_fundefs (fundefs_append B B1) ->\n  unique_bindings_fundefs B /\\ unique_bindings_fundefs B1.\nProof.\n  induction B.\n  intros B1 Huniq; split.\n  inv Huniq.\n  constructor; auto.\n  intros contra.\n  contradiction H5; apply Ensemble_In; rewrite fundefs_append_bound_vars; [|reflexivity].\n  now left.\n  eapply Disjoint_Included_l; eauto.\n  intros a Ha; rewrite fundefs_append_bound_vars; [|reflexivity]; now left.\n  eapply Disjoint_Included_r; eauto.\n  intros a Ha; rewrite fundefs_append_bound_vars; [|reflexivity]; now left.\n  edestruct IHB; eauto.\n  inv Huniq.\n  edestruct IHB; eauto.\n  split; auto.\n  constructor.\nQed.\n\nLemma uncurry_step_preserves_ctag : forall x s m s1 m1 arms arms1,\n  uncurry_step (Ecase x arms) s m (Ecase x arms1) s1 m1 ->\n  Forall2 (fun p p' : ctor_tag * exp => fst p = fst p') arms arms1.\nProof.\n  induction arms; intros.\n  - destruct arms1; inv H.\n  - destruct arms1; inv H; (constructor; [easy|]); auto.\n    now apply List_util.Forall2_refl.\nQed.\n\nLemma Union_Included_subst_l: forall (A : Type) (a b b' c : Ensemble A),\n  a :|: b' \\subset c -> b \\subset b' -> a :|: b \\subset c.\nProof. intros; intros x Hx; destruct Hx; eauto with Ensembles_DB. Qed.\n\nLemma used_vars_fundefs_Fcons_Included: forall f t v e fds,\n  used_vars_fundefs fds \\subset used_vars_fundefs (Fcons f t v e fds).\nProof. intros; normalize_used_vars; auto with Ensembles_DB. Qed.\n\nLemma used_vars_Fcons_Included: forall f t v e fds,\n  used_vars e \\subset used_vars_fundefs (Fcons f t v e fds).\nProof. intros; normalize_used_vars; auto with Ensembles_DB. Qed.\n\nLemma used_vars_Eprim_cons_Included: forall x p a args e,\n  used_vars (Eprim x p args e) \\subset used_vars (Eprim x p (a :: args) e).\nProof. intros; repeat normalize_used_vars; normalize_sets; auto with Ensembles_DB. Qed.\n\nLemma used_vars_Efun_Included: forall fds e,\n  used_vars e \\subset used_vars (Efun fds e).\nProof. intros; normalize_used_vars; auto with Ensembles_DB. Qed.\n\nLemma used_vars_fundefs_Efun_Included: forall fds e,\n  used_vars_fundefs fds \\subset used_vars (Efun fds e).\nProof. intros; normalize_used_vars; auto with Ensembles_DB. Qed.\n\nLemma uncurry_step_s_nondecreasing_mut :\n  let P := (fun e s m e1 s1 m1 => s \\subset s1) in\n  let Q := (fun f s m f1 s1 m1 => s \\subset s1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with auto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH;\n    subst P; subst Q; simpl in *...\n  rewrite H7...\n  rewrite H6...\nQed.\n\nCorollary uncurry_step_s_nondecreasing : forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 -> s \\subset s1.\nProof. apply uncurry_step_s_nondecreasing_mut. Qed.\n\nCorollary uncurry_fundefs_step_s_nondecreasing : forall e s m e1 s1 m1,\n  uncurry_fundefs_step e s m e1 s1 m1 -> s \\subset s1.\nProof. apply uncurry_step_s_nondecreasing_mut. Qed.\n\nLemma Union_Included_lr : forall {A} (S1 S2 S3 : _ A),\n  S1 :|: S2 \\subset S3 -> S1 \\subset S3 /\\ S2 \\subset S3.\nProof. intros; split; [eapply Union_Included_l|eapply Union_Included_r]; eauto. Qed.\n\nLocal Ltac destruct_Union_Included :=\n  repeat match goal with\n    [ H : _ :|: _ \\subset _ |- _ ] => apply Union_Included_lr in H; destruct H\n  end.\n\nLocal Ltac inv_all :=\n  repeat match goal with\n  | [ H : Ensembles.In var _ _ |- _ ] => inv H\n  | [ H : List.In _ _ |- _ ] => inv H\n  | [ H : (_, _) = (_, _) |- _ ] => inv H\n  end;\n  eauto with Ensembles_DB.\n\nLemma uncurry_step_preserves_used_vars_mut :\n  let P := (fun e s m e1 s1 m1 => used_vars e \\subset s -> used_vars e1 \\subset s1) in\n  let Q := (fun f s m f1 s1 m1 =>\n              used_vars_fundefs f \\subset s ->\n              used_vars_fundefs f1 \\subset s1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *; intros He;\n  try destruct arm;\n  try solve [\n    (apply uncurry_step_s_nondecreasing in IHstep\n       || apply uncurry_fundefs_step_s_nondecreasing in IHstep);\n    repeat normalize_used_vars;\n    destruct_Union_Included;\n    try solve [eapply Included_trans; [|eauto]; eauto with Ensembles_DB];\n    apply Union_Included; eauto with Ensembles_DB;\n    eapply Included_trans; [|eauto]; eauto with Ensembles_DB].\n  - (* Eletapp *)\n    apply uncurry_step_s_nondecreasing in IHstep.\n    rewrite used_vars_Eletapp in *.\n    destruct_Union_Included.\n    apply Union_Included...\n    apply Union_Included...\n    apply Union_Included...\n    eapply Included_trans...\n  - (* Eproj *)\n    apply uncurry_step_s_nondecreasing in IHstep.\n    rewrite used_vars_Eproj in *.\n    destruct_Union_Included.\n    apply Union_Included; [|apply Union_Included]...\n  - apply uncurry_step_s_nondecreasing in IHstep. repeat normalize_used_vars; destruct_Union_Included.\n    eapply Union_Included; eauto with Ensembles_DB.\n  - (* Fcons e *)\n    apply uncurry_step_s_nondecreasing in IHstep.\n    rewrite used_vars_Fcons in *.\n    destruct_Union_Included.\n    apply Union_Included; [apply Union_Included|]...\n    all: eapply Included_trans; [|eassumption]...\n  - (* Fcons curried *)\n    rewrite H7.\n    repeat (rewrite used_vars_Fcons in * + rewrite used_vars_Efun in *).\n    destruct_Union_Included.\n    repeat rewrite Union_assoc.\n    repeat rewrite used_vars_Eapp.\n    apply Union_Included. apply Union_Included. apply Union_Included. apply Union_Included.\n    apply Union_Included. apply Union_Included. apply Union_Included. apply Union_Included.\n    apply Union_Included. apply Union_Included.\n    all: eauto with Ensembles_DB.\n    + intros a Ha; inv Ha. (* admit: this sort of stuff should be automated away *)\n      do 3 left; apply H15; now left.\n      left; now right.\n    + intros a Ha; inv_all.\n      rewrite FromList_app in H16; inv H16; eauto.\n    + intros a Ha; inv_all.\n      do 3 left; apply H11; rewrite used_vars_Eapp; auto.\n      contradiction.\n    + rewrite FromList_app.\n      rewrite FromList_cons in H15.\n      intros a Ha; inv Ha; do 3 left; eauto.\n  - (* anf *)\n    repeat normalize_used_vars; repeat normalize_sets.\n    rewrite H6.\n    repeat match goal with |- _ :|: _ \\subset _ => apply Union_Included end...\n    all: repeat apply Included_Union_preserv_l; eapply Included_trans; [|eassumption]...\nQed.\n\nCorollary uncurry_step_preserves_used_vars : forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 -> used_vars e \\subset s -> used_vars e1 \\subset s1.\nProof. apply uncurry_step_preserves_used_vars_mut. Qed.\n\nCorollary uncurry_fundefs_step_preserves_used_vars : forall e s m e1 s1 m1,\n  uncurry_fundefs_step e s m e1 s1 m1 ->\n  used_vars_fundefs e \\subset s ->\n  used_vars_fundefs e1 \\subset s1.\nProof. apply uncurry_step_preserves_used_vars_mut. Qed.\n\nLtac destruct_Union_Intersection :=\n  repeat match goal with\n    [ H : In _ (_ :&: _) _ |- _ ] => destruct H\n  | [ H : In _ (_ :|: _) _ |- _ ] => destruct H\n  end.\n\nLemma Intersection_Union_distr : forall {A} (S1 S2 S3 : _ A),\n  (S1 :|: S2) :&: S3 <--> (S1 :&: S3) :|: (S2 :&: S3).\nProof.\n  split; intros a Ha; destruct_Union_Intersection; auto with Ensembles_DB.\nQed.\n\nLemma uncurry_step_maintains_bindings_mut :\n  let P := (fun e s m e1 s1 m1 =>\n              used_vars e \\subset s -> bound_var e1 :&: s <--> bound_var e) in\n  let Q := (fun f s m f1 s1 m1 =>\n              used_vars_fundefs f \\subset s ->\n              bound_var_fundefs f1 :&: s <--> bound_var_fundefs f) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *; intros;\n  try destruct arm;\n  try (\n    repeat normalize_bound_var; repeat normalize_used_vars;\n    rewrite Intersection_Union_distr;\n    rewrite IH; [rewrite Intersection_Same_set; [reflexivity| ] |];\n    eapply Included_trans; [|eauto| |eauto]; eauto with Ensembles_DB).\n  - (* Eletapp *)\n    rewrite used_vars_Eletapp in *.\n    eauto with Ensembles_DB.\n  - (* Fcons fds *)\n    repeat rewrite bound_var_fundefs_Fcons.\n    repeat rewrite Intersection_Union_distr.\n    rewrite IH.\n    repeat rewrite Intersection_Same_set.\n    reflexivity.\n    all: rewrite used_vars_Fcons in H.\n    eapply Included_trans; [|eassumption]...\n    eapply Union_Included_r.\n    do 2 eapply Union_Included_l...\n    do 3 eapply Union_Included_l...\n    eapply Included_trans; [|eassumption]...\n  - (* Fcons e *)\n    repeat rewrite bound_var_fundefs_Fcons.\n    repeat rewrite Intersection_Union_distr.\n    rewrite IH.\n    repeat rewrite Intersection_Same_set.\n    reflexivity.\n    all: rewrite used_vars_Fcons in H.\n    eapply Included_trans; [|eassumption]...\n    eapply Union_Included_r.\n    do 2 eapply Union_Included_l...\n    do 3 eapply Union_Included_l...\n    eapply Included_trans; [|eassumption]...\n  - (* Fcons curried *)\n    assert (Hsubst :\n            bound_var_fundefs\n              (Fcons f9 ft (k :: fv1)\n                     (Efun (Fcons g gt gv1\n                                  (Eapp f10 ft1 (gv1 ++ fv1))\n                                  Fnil)\n                           (Eapp k kt [g]))\n                     (Fcons f10 ft1 (gv ++ fv) ge fds)) <-->\n           bound_var_fundefs\n              (Fcons f9 ft (k :: fv) (Efun (Fcons g gt gv ge Fnil) (Eapp k kt [g])) fds)\n              :|: FromList (f10 :: fv1 ++ gv1)). {\n      repeat (rewrite bound_var_fundefs_Fcons + rewrite bound_var_Efun).\n      repeat rewrite bound_var_Eapp.\n      repeat rewrite FromList_cons.\n      repeat rewrite FromList_app.\n      split; intros a Ha; destruct_Union_Intersection; auto 10 with Ensembles_DB.\n    }\n    assert (Hsubst1 : FromList (f10 :: fv1 ++ gv1) :&: s <--> Empty_set _). {\n      rewrite FromList_cons.\n      rewrite FromList_app.\n      split; intros a Ha; [|inv Ha].\n      repeat rewrite Union_demorgan in H6.\n      unfold fresh_copies in *.\n      repeat match goal with\n        [ H : _ /\\ _ |- _ ] => destruct H\n      | [ H : _ \\/ _ |- _ ] => destruct H\n      end.\n      destruct_Union_Intersection; inv_all.\n      contradiction.\n      inv H4. contradiction (H15 x); auto.\n      inv H2. contradiction (H15 x); auto.\n    }\n    rewrite Hsubst.\n    rewrite Intersection_Union_distr.\n    rewrite Hsubst1.\n    rewrite Intersection_Same_set.\n    now rewrite Union_Empty_set_neut_r.\n    eapply Union_Included_l; eauto.\n  - (* anf *)\n    repeat normalize_used_vars.\n    repeat normalize_bound_var.\n    repeat rewrite Intersection_Union_distr.\n    normalize_sets.\n    rewrite Ensemble_iff_In_iff; intros arbitrary.\n    assert (Hgv1 : FromList gv1 :&: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x' |inversion 1].\n      destruct H1 as [[Hfresh] Hdup].\n      contradiction (Hfresh x); now split. }\n    assert (Hfv1 : FromList fv1 :&: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x' |inversion 1].\n      destruct H3 as [[Hfresh] Hdup].\n      contradiction (Hfresh x); split; [now left|auto]. }\n    assert (Hf11 : f11 &: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x'; inv Hx |inversion 1].\n      contradiction H5; now (left; left). }\n    rewrite Hgv1, Hfv1, Hf11.\n    repeat rewrite In_or_Iff_Union.\n    repeat rewrite Intersection_Empty_set_abs_l.\n    repeat rewrite In_Empty_set.\n    assert (False_neut_r : forall A, A \\/ False <-> A) by tauto.\n    assert (False_neut_l : forall A, False \\/ A <-> A) by tauto.\n    repeat (rewrite False_neut_l || rewrite False_neut_r).\n    assert (Intersection_and_iff : forall S1 S2 x, In var (S1 :&: S2) x <-> In _ S1 x /\\ In _ S2 x). {\n      intros x; split; destruct 1; split; auto. }\n    repeat rewrite Intersection_and_iff; rewrite In_or_Iff_Union.\n    rename H7 into Hused.\n    clear - Hused.\n    specialize (Hused arbitrary).\n    unfold used_vars, used_vars_fundefs in Hused.\n    repeat rewrite In_or_Iff_Union in Hused.\n    tauto.\nQed.\n\nCorollary uncurry_step_maintains_bindings: forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 ->\n  used_vars e \\subset s ->\n  bound_var e1 :&: s <--> bound_var e.\nProof. apply uncurry_step_maintains_bindings_mut. Qed.\n\nCorollary uncurry_fundefs_step_maintains_bindings: forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s ->\n  bound_var_fundefs f1 :&: s <--> bound_var_fundefs f.\nProof. apply uncurry_step_maintains_bindings_mut. Qed.\n\nCorollary uncurry_step_maintains_bindings_fn: forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 ->\n  used_vars e \\subset s -> forall a,\n  In _ (bound_var e1) a ->\n  In _ s a ->\n  In _ (bound_var e) a.\nProof. intros; rewrite <- uncurry_step_maintains_bindings; eauto. Qed.\n\nCorollary uncurry_fundefs_step_maintains_bindings_fn: forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s -> forall a,\n  In _ (bound_var_fundefs f1) a ->\n  In _ s a ->\n  In _ (bound_var_fundefs f) a.\nProof. intros; rewrite <- uncurry_fundefs_step_maintains_bindings; eauto. Qed.\n\nLemma uncurry_step_maintains_used_vars_mut :\n  let P := (fun e s m e1 s1 m1 =>\n              used_vars e \\subset s -> used_vars e1 :&: s <--> used_vars e) in\n  let Q := (fun f s m f1 s1 m1 =>\n              used_vars_fundefs f \\subset s ->\n              used_vars_fundefs f1 :&: s <--> used_vars_fundefs f) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *; intros;\n  try destruct arm;\n  try (\n    repeat normalize_used_vars;\n    rewrite Intersection_Union_distr;\n    rewrite IH; [rewrite Intersection_Same_set; eauto with Ensembles_DB|];\n    eapply Included_trans; [|eauto| |eauto]; eauto with Ensembles_DB).\n  - (* Eletapp *)\n    repeat rewrite used_vars_Eletapp in *.\n    do 2 rewrite Intersection_Union_distr.\n    rewrite IH.\n    rewrite Intersection_Same_set...\n    rewrite Intersection_Same_set...\n    eapply Included_trans; [|eassumption]... \n    eapply Included_trans; [|eassumption]... \n  - (* Eproj *)\n    repeat rewrite used_vars_Eproj.\n    do 2 rewrite Intersection_Union_distr.\n    rewrite IH.\n    rewrite Intersection_Same_set...\n    rewrite Intersection_Same_set...\n    all: rewrite used_vars_Eproj in H...\n    eapply Included_trans; eauto...\n  - repeat normalize_used_vars. rewrite Intersection_Union_distr.\n    rewrite IH; [rewrite Intersection_Same_set; eauto with Ensembles_DB|].\n    eapply Included_trans; [|eauto]; eauto with Ensembles_DB.\n  - (* Fcons fds *)\n    repeat rewrite used_vars_Fcons.\n    repeat rewrite Intersection_Union_distr.\n    rewrite IH.\n    repeat rewrite Intersection_Same_set...\n    all: rewrite used_vars_Fcons in H.\n    eapply Included_trans; [|eassumption]...\n    eapply Union_Included_r.\n    do 2 eapply Union_Included_l...\n    do 3 eapply Union_Included_l...\n    eapply Included_trans; [|eassumption]...\n  - (* Fcons curried *)\n    assert (Hsubst :\n            used_vars_fundefs\n              (Fcons f9 ft (k :: fv1)\n                     (Efun (Fcons g gt gv1\n                                  (Eapp f10 ft1 (gv1 ++ fv1))\n                                  Fnil)\n                           (Eapp k kt [g]))\n                     (Fcons f10 ft1 (gv ++ fv) ge fds)) <-->\n           used_vars_fundefs\n              (Fcons f9 ft (k :: fv) (Efun (Fcons g gt gv ge Fnil) (Eapp k kt [g])) fds)\n              :|: FromList (f10 :: fv1 ++ gv1)). {\n      repeat (rewrite used_vars_Fcons + rewrite used_vars_Efun).\n      repeat rewrite used_vars_Eapp.\n      repeat rewrite FromList_cons.\n      repeat rewrite FromList_app.\n      split; intros a Ha; destruct_Union_Intersection; auto 10 with Ensembles_DB.\n    }\n    assert (Hsubst1 : FromList (f10 :: fv1 ++ gv1) :&: s <--> Empty_set _). {\n      rewrite FromList_cons.\n      rewrite FromList_app.\n      split; intros a Ha; [|inv Ha].\n      repeat rewrite Union_demorgan in H6.\n      unfold fresh_copies in *.\n      repeat match goal with\n        [ H : _ /\\ _ |- _ ] => destruct H\n      | [ H : _ \\/ _ |- _ ] => destruct H\n      end.\n      destruct_Union_Intersection; inv_all.\n      contradiction.\n      inv H4. contradiction (H15 x); auto.\n      inv H2. contradiction (H15 x); auto.\n    }\n    rewrite Hsubst.\n    rewrite Intersection_Union_distr.\n    rewrite Hsubst1.\n    rewrite Intersection_Same_set.\n    now rewrite Union_Empty_set_neut_r.\n    eapply Union_Included_l...\n  - (* anf *)\n    repeat normalize_used_vars; repeat normalize_sets.\n    repeat rewrite Intersection_Union_distr.\n    rewrite Ensemble_iff_In_iff; intros arbitrary.\n    assert (Hgv1 : FromList gv1 :&: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x' |inversion 1].\n      destruct H1 as [[Hfresh] Hdup].\n      contradiction (Hfresh x); now split. }\n    assert (Hfv1 : FromList fv1 :&: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x' |inversion 1].\n      destruct H3 as [[Hfresh] Hdup].\n      contradiction (Hfresh x); split; [now left|auto]. }\n    assert (Hf11 : f11 &: s <--> Empty_set _). {\n      split; [intros x' [x Hx]; clear x'; inv Hx |inversion 1].\n      contradiction H5; now (left; left). }\n    repeat rewrite In_or_Iff_Union.\n    rewrite Hgv1, Hfv1, Hf11.\n    repeat rewrite In_Empty_set.\n    assert (False_neut_r : forall A, A \\/ False <-> A) by tauto.\n    assert (False_neut_l : forall A, False \\/ A <-> A) by tauto.\n    repeat (rewrite False_neut_l || rewrite False_neut_r).\n    assert (Intersection_and_iff : forall S1 S2 x, In var (S1 :&: S2) x <-> In _ S1 x /\\ In _ S2 x). {\n      intros x; split; destruct 1; split; auto. }\n    repeat rewrite Intersection_and_iff.\n    rename H7 into Hused.\n    clear - Hused.\n    specialize (Hused arbitrary).\n    repeat rewrite In_or_Iff_Union in Hused.\n    tauto.\nQed.\n\nCorollary uncurry_step_maintains_used_vars: forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 ->\n  used_vars e \\subset s ->\n  used_vars e1 :&: s <--> used_vars e.\nProof. apply uncurry_step_maintains_used_vars_mut. Qed.\n\nCorollary uncurry_fundefs_step_maintains_used_vars: forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s ->\n  used_vars_fundefs f1 :&: s <--> used_vars_fundefs f.\nProof. apply uncurry_step_maintains_used_vars_mut. Qed.\n\nCorollary uncurry_step_maintains_used_vars_fn: forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 ->\n  used_vars e \\subset s -> forall a,\n  In _ (used_vars e1) a ->\n  In _ s a ->\n  In _ (used_vars e) a.\nProof. intros; rewrite <- uncurry_step_maintains_used_vars; eauto. Qed.\n\nCorollary uncurry_fundefs_step_maintains_used_vars_fn: forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s -> forall a,\n  In _ (used_vars_fundefs f1) a ->\n  In _ s a ->\n  In _ (used_vars_fundefs f) a.\nProof. intros; rewrite <- uncurry_fundefs_step_maintains_used_vars; eauto. Qed.\n\nLemma uncurry_step_preserves_unique_bindings_mut :\n  let P := (fun e s m e1 s1 m1 =>\n              used_vars e \\subset s ->\n              unique_bindings e ->\n              unique_bindings e1) in\n  let Q := (fun f s m f1 s1 m1 =>\n              used_vars_fundefs f \\subset s ->\n              unique_bindings_fundefs f ->\n              unique_bindings_fundefs f1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *; intros.\n  - (* Eletapp *)\n    rewrite used_vars_Eletapp in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Included_trans; [|eassumption]...\n    assert (unique_bindings e)...\n    constructor; auto.\n    intros contra.\n    contradiction H3.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n  - (* Econstr *)\n    rewrite used_vars_Econstr in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_r...\n    assert (unique_bindings e)...\n    constructor; auto.\n    intros contra.\n    contradiction H3.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n  - (* Ecase arm *)\n    rewrite used_vars_Ecase_cons in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_l...\n    constructor; auto.\n    constructor; intros a contra; destruct contra.\n    inv H7. contradiction (H3 x0).\n    split; auto.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n    apply H; right; now left.\n  - (* Ecase arms *)\n    destruct arm; rewrite used_vars_Ecase_cons in H; inv H0.\n    assert (used_vars (Ecase x arms) \\subset s).\n    eapply Union_Included_r...\n    constructor; auto.\n    constructor; intros a contra; destruct contra.\n    inv H7. contradiction (H3 x0).\n    split; auto.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n    apply H; left; now left.\n  - (* Eproj *)\n    rewrite used_vars_Eproj in H; inv H0.\n    assert (used_vars e \\subset s).\n    do 2 eapply Union_Included_r...\n    constructor; auto.\n    intros contra.\n    contradiction H3.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n  - (* Eprim_val *)\n    rewrite used_vars_Eprim_val in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_r...\n    constructor; auto.\n    intros contra; contradiction H3; eapply uncurry_step_maintains_bindings_fn; eauto.\n  - (* Eprim *)\n    rewrite used_vars_Eprim in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_r...\n    constructor; auto.\n    intros contra; contradiction H3; eapply uncurry_step_maintains_bindings_fn; eauto.\n  - (* Efun e *)\n    rewrite used_vars_Efun in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_r...\n    constructor; auto.\n    constructor; intros a contra; destruct contra.\n    inv H5. contradiction (H6 x).\n    split; auto.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n    apply H; left; now left.\n  - (* Efun fds *)\n    rewrite used_vars_Efun in H; inv H0.\n    assert (used_vars_fundefs fds \\subset s).\n    eapply Union_Included_l...\n    constructor; auto.\n    constructor; intros a contra; destruct contra.\n    inv H5. contradiction (H6 x).\n    split; auto.\n    eapply uncurry_fundefs_step_maintains_bindings_fn; eauto.\n    apply H; right; now left.\n  - (* Fcons fds *)\n    rewrite used_vars_Fcons in H; inv H0.\n    assert (used_vars_fundefs fds \\subset s).\n    eapply Union_Included_r...\n    constructor; auto.\n    intros contra.\n    contradiction H7; eapply uncurry_fundefs_step_maintains_bindings_fn; eauto.\n    constructor; intros a contra; destruct contra.\n    inv H9. contradiction (H3 x).\n    split; auto.\n    eapply uncurry_fundefs_step_maintains_bindings_fn; eauto.\n    constructor; intros a contra; destruct contra.\n    inv H10. contradiction (H3 x).\n    split; auto.\n    eapply uncurry_fundefs_step_maintains_bindings_fn; eauto.\n    apply H; left; right; now left.\n  - (* Fcons e *)\n    rewrite used_vars_Fcons in H; inv H0.\n    assert (used_vars e \\subset s).\n    eapply Union_Included_r. eapply Union_Included_l...\n    constructor; auto.\n    intros contra.\n    contradiction H6; eapply uncurry_step_maintains_bindings_fn; eauto.\n    constructor; intros a contra; destruct contra.\n    inv H8. contradiction (H3 x). split; auto.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n    constructor; intros a contra; destruct contra.\n    inv H10; contradiction (H3 x); split; auto.\n    eapply uncurry_step_maintains_bindings_fn; eauto.\n    apply H; right; now left.\n  - (* Fcons curried *)\n    repeat (rewrite used_vars_Fcons in H8 + rewrite used_vars_Efun in H8).\n    repeat rewrite Union_assoc in H8.\n    rewrite not_occurs_in_exp_iff_used_vars in H0.\n    rewrite not_occurs_in_exp_iff_used_vars in H1.\n    unfold fresh_copies in *; destruct H2; destruct H4.\n    repeat rewrite Union_demorgan in H6.\n    do 2 destruct H6.\n    constructor.\n    Local Ltac clear_false_bound_var_hyps :=\n      try match goal with\n        [ H : bound_var_fundefs Fnil _ |- _ ] => inv H\n      | [ H : bound_var (Eapp _ _ _) _ |- _ ] => inv H\n      | [ _ : _ |- ~ bound_var_fundefs Fnil _ ] => inversion 1\n      | [ _ : _ |- ~ bound_var (Eapp _ _ _) _ ] => inversion 1\n      end.\n    + intros contra; inv contra; clear_false_bound_var_hyps.\n      inv H17; inv_all; clear_false_bound_var_hyps.\n      * inv H9.\n        contradiction H19. constructor. constructor. now left.\n      * inv H2. contradiction (H15 f9).\n        split; auto. apply H8; now do 7 left.\n    + intros contra; inv contra.\n      inv_all.\n      * contradiction H6; apply H8; now do 7 left.\n      * rewrite FromList_app in H14; inv H14.\n        inv H9.\n        contradiction H20.\n        constructor.\n        constructor.\n        now right.\n        inv H9.\n        contradiction H25; now right.\n      * now inv H9.\n      * inv H9. contradiction H19.\n        constructor.\n        now apply Bound_Fcons3.\n    + constructor; intros a contra; destruct contra.\n      inv_all; clear_false_bound_var_hyps.\n      inv H18; inv_all; clear_false_bound_var_hyps.\n      inv H9; inv_all; clear_false_bound_var_hyps.\n      inv H21. contradiction (H9 x).\n      split; [|now left].\n      constructor; constructor; now constructor.\n      inv H2. contradiction (H15 x).\n      split; auto.\n      apply H8; do 6 left; right; now left.\n      inv H19; inv_all; clear_false_bound_var_hyps.\n      inv H4. contradiction (H14 x).\n      split; auto; left; apply H8; do 5 left; now right.\n      inv H4; contradiction (H15 x); split; auto; right.\n    + constructor; intros a contra; destruct contra.\n      inv_all; clear_false_bound_var_hyps.\n      * contradiction H6; apply H8; do 6 left; right; now left.\n      * rewrite FromList_app in H14; inv H14.\n        inv H9. inv H22. contradiction (H9 x).\n        split; auto; now left.\n        inv H9; inv H26. contradiction.\n      * inv H9. inv H23. contradiction (H9 x); split; auto; now left.\n      * contradiction H1; now left.\n      * rewrite FromList_app in H14; inv H14.\n        inv H4. contradiction (H14 x).\n        split; auto; left; apply H8; do 4 left; now right.\n        inv H4. contradiction (H14 x).\n        split; auto; left; apply H8; do 6 left; right; now right.\n      * inv H4. contradiction (H14 x).\n        split; auto; left; apply H8; right; now left.\n      * inv H4. contradiction (H14 x).\n        split; auto; left; apply H8; do 3 left; right; now left.\n    + constructor; intros a contra; destruct contra.\n      inv_all; clear_false_bound_var_hyps.\n      * inv H18; inv_all; clear_false_bound_var_hyps.\n        contradiction H6; apply H8; do 5 left; now right.\n      * rewrite FromList_app in H15; inv H15.\n        inv H19; inv_all; clear_false_bound_var_hyps.\n        inv H9. inv H27. inv H17. contradiction.\n        inv H2. contradiction (H16 x); split; auto.\n        apply H8; do 4 left; now right.\n        inv H19; inv_all; clear_false_bound_var_hyps.\n        inv H9. inv H27. inv H22. contradiction (H9 x).\n        split; auto; now right.\n        inv H2. contradiction (H16 x); split; auto.\n        apply H8; do 6 left; right; now right.\n      * inv H18; inv_all; clear_false_bound_var_hyps.\n        inv H9. inv H24. contradiction (H9 x); split; auto.\n        inv H2. contradiction (H15 x); split; auto.\n        apply H8; right; now left.\n      * inv H18; inv_all; clear_false_bound_var_hyps.\n        inv H9. inv H27. inv H16. contradiction.\n        inv H2. contradiction (H15 x). split; auto.\n        apply H8; do 3 left; right; now left.\n    + inversion 1; subst.\n      inv H9. contradiction H25; now left.\n      inv H4. contradiction (H16 f9); split; auto.\n      left; apply H8; now do 7 left.\n    + constructor; auto; intros contra.\n      inv H4. contradiction (H14 k); split; auto.\n      left; apply H8; do 6 left; right; now left.\n    + constructor; [constructor ..|]; clear_false_bound_var_hyps; auto.\n      rewrite bound_var_Eapp...\n      rewrite bound_var_fundefs_Fnil...\n      rewrite bound_var_Eapp...\n      intros contra.\n      inv H2. contradiction (H14 g); split; auto; apply H8.\n      do 5 left; now right.\n      constructor.\n      constructor.\n      rewrite bound_var_Eapp...\n    + constructor.\n      intros contra; contradiction H6; apply H8; do 3 left; right; now left.\n      intros contra; contradiction H6; apply H8; right; now left.\n      constructor; intros a contra; inv contra.\n      rewrite FromList_app in H15; destruct H15.\n      inv H9. inv H28. inv H18. inv H33. contradiction (H9 x); split; auto.\n      inv H9. inv H23. contradiction (H9 x); split; auto; now right.\n      constructor; intros a contra; inv contra.\n      rewrite FromList_app in H15; destruct H15.\n      inv H9. inv H25. contradiction (H9 x); split; auto.\n      inv H9. inv H24. contradiction (H9 x); split; auto; now right.\n      constructor; intros a contra; inv contra.\n      inv H9. inv H25. contradiction (H9 a); split; auto.\n      change (~ In _ (FromList (gv ++ fv)) f10).\n      intros contra; rewrite FromList_app in contra; destruct contra.\n      contradiction H6; apply H8; do 4 left; now right.\n      contradiction H6; apply H8; do 6 left; right; now right.\n      apply NoDup_app.\n      inv H9. inv H26. now inv H16.\n      inv H9. now inv H25.\n      constructor; intros a contra; inv contra.\n      inv H9. inv H23. contradiction (H9 a); split; auto; now right.\n      inv H9. inv H26. now inv H16.\n      now inv H9.\n  - (* anf *)\n    repeat normalize_used_vars; unfold used_vars, used_vars_fundefs in *.\n    repeat match goal with\n    | H : fresh_copies _ _ |- _ => destruct H\n    | H : ?S1 :|: ?S2 \\subset ?S3 |- _ => apply Union_Included_lr in H; destruct H\n    | H : unique_bindings (_ _) |- _ => inv H\n    | H : unique_bindings_fundefs (_ _) |- _ => inv H\n    end.\n    change (~ bound_var ?e ?x) with (~ In _ (bound_var e) x) in *;\n    change (~ bound_var_fundefs ?fds ?x) with (~ In _ (bound_var_fundefs fds) x) in *;\n    repeat normalize_bound_var_in_ctx.\n    repeat match goal with\n    | H : ~ In _ (_ :|: _) _ |- _ => rewrite Union_demorgan in H; destruct H\n    | H : Disjoint ?A (?S1 :|: ?S2) ?S3 |- _ =>\n      assert (Disjoint A S1 S3) by (apply Disjoint_Union_l in H; apply H);\n      apply Disjoint_Union_r in H\n    | H : Disjoint ?A ?S1 (?S2 :|: ?S3) |- _ => apply Disjoint_sym in H\n    end.\n    repeat progress multimatch goal with\n    | Hdis : Disjoint var s ?S2, Hsub : ?S1 \\subset s |- _ =>\n      match goal with\n      | Hconc : Disjoint var S1 S2 |- _ => idtac\n      | _ => assert (Disjoint var S1 S2) by (eapply Disjoint_Included_l; [apply Hsub|apply Hdis])\n      end\n    end.\n    assert (Disjoint_In_falso : forall S x, In var S x -> Disjoint var S [set x] -> False). {\n      intros S x Hin [Hdis]; contradiction (Hdis x); now constructor. }\n    repeat match goal with\n    | |- unique_bindings (_ _) => constructor\n    | |- unique_bindings_fundefs (_ _) => constructor\n    end;\n    change (~ bound_var ?e ?x) with (~ In _ (bound_var e) x) in *;\n    change (~ bound_var_fundefs ?fds ?x) with (~ In _ (bound_var_fundefs fds) x) in *;\n    change (~ FromList ?xs ?x) with (~ In _ (FromList xs) x) in *;\n    repeat normalize_bound_var; repeat normalize_sets;\n    repeat match goal with\n    | |- Disjoint _ (_ :|: _) _ => apply Union_Disjoint_l\n    | |- Disjoint _ _ (_ :|: _) => apply Union_Disjoint_r\n    | |- ~ In _ (_ :|: _) _ => rewrite Union_demorgan; split\n    | |- NoDup (_ ++ _) => apply NoDup_app\n    end...\n    + intros Hin. apply (Disjoint_In_falso _ _ Hin)...\n    + now apply Disjoint_sym.\nQed.\n\nCorollary uncurry_step_preserves_unique_bindings : forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 ->\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  unique_bindings e1.\nProof. apply uncurry_step_preserves_unique_bindings_mut. Qed.\n\nCorollary uncurry_fundefs_step_preserves_unique_bindings : forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s ->\n  unique_bindings_fundefs f ->\n  unique_bindings_fundefs f1.\nProof. apply uncurry_step_preserves_unique_bindings_mut. Qed.\n\nHint Constructors unique_bindings : core.\n\nLemma uncurry_fundefs_step_unique_names : forall a f s m f1 s1 m1,\n  used_vars_fundefs f \\subset s ->\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  name_in_fundefs f1 a ->\n  ~ name_in_fundefs f a ->\n  ~ In var s a.\nProof with eauto with Ensembles_DB.\n  intros a f s m f1 s1 m1 Hused Hstep Hf1 Hf.\n  induction Hstep; try solve [inv Hf1; [inv H0|]; contradiction Hf; [now left|now right]].\n  - apply IHHstep.\n    eapply Included_trans; [|eauto]; repeat normalize_used_vars...\n    inv Hf1; auto.\n    inv H; contradiction Hf; now left.\n    intros contra; contradiction Hf; now right.\n  - simpl in *.\n    inv Hf1; inv H0; inv H8.\n    + contradiction Hf; now left.\n    + inv H0. intros contra; contradiction H6; now do 2 left.\n    + contradiction Hf; now right.\n  - simpl in *.\n    inv Hf1.\n    + contradiction Hf; now left.\n    + destruct H7 as [Hf1|Hfds].\n      * inv H7.\n        intros Hin; contradiction H5; now do 2 left.\n      * contradiction Hf; now right.\nQed.\n\nLemma uncurry_fundefs_step_preserves_names : forall a f s m f1 s1 m1,\n  name_in_fundefs f a ->\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  name_in_fundefs f1 a.\nProof.\n  intros a f s m f1 s1 m1 Hf Hstep.\n  induction Hstep; try solve [inv Hf; [inv H0; now left|now right]].\n  - inv Hf.\n    inv H; now left.\n    right; now apply IHHstep.\n  - inv Hf.\n    inv H7; now left.\n    right; now right.\n  - inv Hf.\n    inv H7; now left.\n    right; now right.\nQed.\n\nLemma uncurry_fundefs_step_preserves_tags : forall a f s m f1 s1 m1 t v e t1 v1 e1,\n  used_vars_fundefs f \\subset s ->\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  find_def a f = Some (t, v, e) ->\n  find_def a f1 = Some (t1, v1, e1) ->\n  t = t1.\nProof with eauto 10 with Ensembles_DB.\n  intros a f s m f1 s1 m1 t v e t1 v1 e1 Hused Hstep Hf Hf1.\n  induction Hstep; simpl in Hf, Hf1; destruct (M.elt_eq a f); subst;\n    inv Hf; inv Hf1; auto;\n    try solve [rewrite H1 in H2; now inv H2].\n  - apply IHHstep; auto.\n    rewrite used_vars_Fcons in Hused.\n    eapply Included_trans...\n  - destruct (M.elt_eq a f1); subst.\n    + contradiction H6.\n      left; left.\n      apply Hused; left.\n      apply Bound_Fcons2.\n      apply name_in_fundefs_bound_var_fundefs.\n      eapply find_def_name_in_fundefs; eauto.\n    + rewrite H9 in H10; now inv H10.\n  - destruct (M.elt_eq a f1); subst.\n    + contradiction H5.\n      left; left.\n      apply Hused; left.\n      apply Bound_Fcons2.\n      apply name_in_fundefs_bound_var_fundefs.\n      eapply find_def_name_in_fundefs; eauto.\n    + rewrite H8 in H9; now inv H9.\nQed.\n\nLemma uncurry_fundefs_step_preserves_length : forall a f s m f1 s1 m1 t v e t1 v1 e1,\n  used_vars_fundefs f \\subset s ->\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  find_def a f = Some (t, v, e) ->\n  find_def a f1 = Some (t1, v1, e1) ->\n  length v = length v1.\nProof with eauto 10 with Ensembles_DB.\n  intros a f s m f1 s1 m1 t v e t1 v1 e1 Hused Hstep Hf Hf1.\n  induction Hstep; simpl in Hf, Hf1; destruct (M.elt_eq a f); subst;\n    inv Hf; inv Hf1; auto;\n    try solve [rewrite H1 in H2; now inv H2].\n  - apply IHHstep; auto.\n    rewrite used_vars_Fcons in Hused.\n    eapply Included_trans...\n  - simpl; now apply f_equal.\n  - destruct (M.elt_eq a f1); subst.\n    + contradiction H6.\n      left; left.\n      apply Hused; left.\n      apply Bound_Fcons2.\n      apply name_in_fundefs_bound_var_fundefs.\n      eapply find_def_name_in_fundefs; eauto.\n    + rewrite H9 in H10; now inv H10.\n  - destruct (M.elt_eq a f1); subst.\n    + contradiction H5.\n      left; left.\n      apply Hused; left.\n      apply Bound_Fcons2.\n      apply name_in_fundefs_bound_var_fundefs.\n      eapply find_def_name_in_fundefs; eauto.\n    + rewrite H8 in H9; now inv H9.\nQed.\n\nLemma find_def_body_occurs_free_Included : forall fds a t xs e,\n  find_def a fds = Some (t, xs, e) ->\n  occurs_free e \\subset name_in_fundefs fds :|: occurs_free_fundefs fds :|: FromList xs.\nProof.\n  induction fds; intros a t xs e0 Hfind; [|inv Hfind].\n  simpl in Hfind.\n  destruct (M.elt_eq a v).\n  - inv Hfind.\n    intros a Ha.\n    split_var_in_fundefs a (Fcons v t xs e0 fds) Hfds; [now do 2 left|].\n    split_var_in_list a xs; [now right|].\n    left; right; constructor; auto.\n    intro contra; subst; contradiction n; now left.\n    intros contra; contradiction n; now right.\n  - eapply Included_trans.\n    eapply IHfds; eauto.\n    intros b Hb; inv Hb; [inv H|]; [left; left; now right| |now right].\n    split_var_in_fundefs b (Fcons v f l e fds) Hfds; [left; now left|].\n    left; right.\n    apply Free_Fcons2; eauto.\n    intros contra; subst; contradiction n0; now left.\nQed.\n\nLemma Union_Setminus_Included : forall {U : Type} (A B : Ensemble U),\n  A :|: B \\\\ B \\subset A.\nProof.\n  intros U A B a Ha.\n  inv Ha.\n  inv H; auto; contradiction.\nQed.\n\nLemma fundefs_append_assoc : forall A B C,\n  fundefs_append A (fundefs_append B C) = fundefs_append (fundefs_append A B) C.\nProof.\n  induction A.\n  - intros B C; simpl. now rewrite IHA.\n  - auto.\nQed.\n\nLemma fundefs_append_used_vars : forall B B1,\n  used_vars_fundefs (fundefs_append B B1) <--> used_vars_fundefs B :|: used_vars_fundefs B1.\nProof with eauto 10 with Ensembles_DB.\n  induction B.\n  intros B1; split.\n  - intros a Ha.\n    simpl in Ha; rewrite used_vars_Fcons in Ha.\n    inv Ha. inv H. inv H0. inv H.\n    left; left; constructor; now left.\n    left; left; constructor; now right.\n    left; rewrite used_vars_Fcons...\n    rewrite IHB in H.\n    inv H.\n    left; rewrite used_vars_Fcons...\n    now right.\n  - intros a Ha.\n    rewrite used_vars_Fcons in Ha.\n    inv Ha. inv H. inv H0. inv H. inv H0.\n    all: simpl; rewrite used_vars_Fcons...\n    right; rewrite IHB...\n    right; rewrite IHB...\n  - intros B1; simpl; rewrite used_vars_Fnil...\nQed.\n\nLemma fundefs_append_ctx_exists : forall f' c',\n  exists c, forall e, c <[ e ]> = fundefs_append f' (c' <[ e ]>).\nProof.\n  induction f'.\n  intros c'; simpl.\n  edestruct IHf' as [c Hc].\n  exists (Fcons2_c v f l e c); intros e0; simpl.\n  now rewrite Hc.\n  intros c'.\n  eexists; simpl; eauto.\nQed.\n\nLemma fds_noncircular : forall f t v e fds, Fcons f t v e fds <> fds.\nProof. induction fds; inversion 1; now subst. Qed.\n\nLocal Ltac circular_fds :=\n  match goal with\n  | [ H : Fcons ?f ?t ?v ?e ?fds = ?fds |- _ ] =>\n    assert (Fcons f t v e fds <> fds) by apply fds_noncircular; contradiction\n  | [ H : ?fds = Fcons ?f ?t ?v ?e ?fds |- _ ] =>\n    symmetry in H; circular_fds\n  end.\n\nLemma uncurry_step_not_reflexive_mut :\n  let P := (fun e s m e1 s1 m1 => e <> e1 /\\ s <> s1 /\\ m <> m1) in\n  let Q := (fun f s m f1 s1 m1 => f <> f1 /\\ s <> s1 /\\ m <> m1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *;\n    (split; [|split]); try destruct IH as [? [? ?]]; auto;\n    intros contra; inv contra; try easy.\n  (* uncurry_fundefs_curried *)\n  - circular_fds.\n  - rewrite H7 in H6.\n    contradiction H6.\n    left; left; now right.\n  - apply f_equal with\n      (f := fun a =>\n              match M.get g a with\n              | Some true => true\n              | _ => false\n              end) in H8.\n    rewrite H in H8.\n    now rewrite M.gss in H8.\n  (* anf *)\n  - circular_fds.\n  - rewrite H6 in H5.\n    contradiction H5.\n    left; left; now right.\n  - apply f_equal with\n      (f := fun a =>\n              match M.get g a with\n              | Some true => true\n              | _ => false\n              end) in H7.\n    rewrite H in H7.\n    now rewrite M.gss in H7.\nQed.\n\nLocal Ltac solve_uncurry_step_not_reflexive :=\n  intros; intros H; destruct uncurry_step_not_reflexive_mut as [He Hf];\n  try (now apply He in H);\n  try (now apply Hf in H).\n\nCorollary uncurry_step_not_reflexive : forall e s m s1 m1, ~ uncurry_step e s m e s1 m1.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nCorollary uncurry_fundefs_step_not_reflexive : forall f s m s1 m1, ~ uncurry_fundefs_step f s m f s1 m1.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nCorollary uncurry_step_not_reflexive_s : forall e s m e1 m1, ~ uncurry_step e s m e1 s m1.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nCorollary uncurry_fundefs_step_not_reflexive_s : forall f s m f1 m1, ~ uncurry_fundefs_step f s m f1 s m1.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nCorollary uncurry_step_not_reflexive_m : forall e s m e1 s1, ~ uncurry_step e s m e1 s1 m.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nCorollary uncurry_fundefs_step_not_reflexive_m : forall f s m f1 s1, ~ uncurry_fundefs_step f s m f1 s1 m.\nProof. solve_uncurry_step_not_reflexive. Qed.\n\nLocal Ltac step_isnt_reflexive :=\n  match goal with\n  | [ H : uncurry_step ?a _ _ ?a _ _ |- _ ] =>\n    now apply uncurry_step_not_reflexive in H\n  | [ H : uncurry_fundefs_step ?a _ _ ?a _ _ |- _ ] =>\n    now apply uncurry_fundefs_step_not_reflexive in H\n  end.\n\nLemma circular_app_f_ctx : forall f t v e e1 e2 ctx,\n  Fcons f t v e (ctx <[ e1 ]>) <> ctx <[ e2 ]>.\nProof.\n  induction ctx; intros contra.\n  inv contra. circular_fds.\n  inv contra. contradiction.\nQed.\n\nLemma uncurry_step_subterm_invariant_mut :\n  (forall c, (fun c => forall e s m e1 s1 m1,\n    uncurry_step (c |[ e ]|) s m (c |[ e1 ]|) s1 m1 ->\n    uncurry_step e s m e1 s1 m1) c) /\\\n  (forall f, (fun f => forall e s m e1 s1 m1,\n    uncurry_fundefs_step (f <[ e ]>) s m (f <[ e1 ]>) s1 m1 ->\n    uncurry_step e s m e1 s1 m1) f).\nProof. (* with eauto with Ensembles_DB.*)\n  exp_fundefs_ctx_induction IHe IHf; simpl;\n    try rename e into c;\n    try intros arms e s m e1 s1 m1 Hstep;\n    try intros e s m e1 s1 m1 Hstep;\n    try solve [easy|inv Hstep; now apply IHe].\n  - (* Efun1_c *)\n    induction l.\n    + inv Hstep.\n      now apply IHe.\n      step_isnt_reflexive.\n    + apply IHl.\n      inv Hstep.\n      step_isnt_reflexive.\n      assumption.\n  - (* Efun2_c *)\n    apply IHe.\n    inv Hstep.\n    assumption.\n    step_isnt_reflexive.\n  - (* Fcons1_c *)\n    inv Hstep.\n    step_isnt_reflexive.\n    now apply IHf.\n  - (* Fcons2_c *)\n    inv Hstep.\n    step_isnt_reflexive.\n    now apply IHe.\n    apply IHe.\n    rewrite <- H2; rewrite <- H5.\n    apply uncurry_fun_fds; auto.\n    circular_fds.\n    circular_fds.\n  - (* Fcons3_c *)\n    inv Hstep.\n    + now apply IHf.\n    + step_isnt_reflexive.\n    + pose circular_app_f_ctx.\n      exfalso; eapply n; eauto.\n    + pose circular_app_f_ctx.\n      exfalso; eapply n; eauto.\nQed.\n\nCorollary uncurry_step_subterm_invariant : forall c e s m e1 s1 m1,\n  uncurry_step (c |[ e ]|) s m (c |[ e1 ]|) s1 m1 ->\n  uncurry_step e s m e1 s1 m1.\nProof. apply uncurry_step_subterm_invariant_mut. Qed.\n\nCorollary uncurry_fundefs_step_subterm_invariant : forall f e s m e1 s1 m1,\n  uncurry_fundefs_step (f <[ e ]>) s m (f <[ e1 ]>) s1 m1 ->\n  uncurry_step e s m e1 s1 m1.\nProof. apply uncurry_step_subterm_invariant_mut. Qed.\n\nLemma app_ctx_uncurry_step_mut : \n  (forall c, (fun c => forall e s m e1 s1 m1,\n    used_vars (c |[ e ]|) \\subset s ->\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (c |[ e ]|) s m (c |[ e1 ]|) s1 m1) c) /\\\n  (forall f, (fun f => forall e s m e1 s1 m1,\n    used_vars_fundefs (f <[ e ]>) \\subset s ->\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_fundefs_step (f <[ e ]>) s m (f <[ e1 ]>) s1 m1) f).\nProof with eauto with Ensembles_DB.\n  exp_fundefs_ctx_induction IHe IHf; simpl;\n    try rename e into c;\n    try intros arms e s m e1 s1 m1 Hused Hstep (* Huniq*);\n    try intros e s m e1 s1 m1 Hused Hstep (* Huniq*);\n    try assumption;\n    try (\n      constructor;\n      repeat normalize_used_vars;\n      ((apply IHe; auto) || (apply IHf; auto));\n      eapply Included_trans; [|eauto]; eauto with Ensembles_DB).\n  - rewrite used_vars_Eletapp...\n  - induction l; simpl in *.\n    + constructor; rewrite used_vars_Ecase_cons in Hused.\n      apply IHe; auto.\n      rewrite Union_commut in Hused.\n      eapply Included_trans...\n    + destruct a; constructor.\n      rewrite used_vars_Ecase_cons in Hused.\n      apply IHl; auto.\n      eapply Included_trans...\nQed.\n\nCorollary app_ctx_uncurry_step : forall c e s m e1 s1 m1,\n    used_vars (c |[ e ]|) \\subset s ->\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_step (c |[ e ]|) s m (c |[ e1 ]|) s1 m1.\nProof. apply app_ctx_uncurry_step_mut. Qed.\n\nCorollary app_ctx_uncurry_fundefs_step : forall f e s m e1 s1 m1,\n    used_vars_fundefs (f <[ e ]>) \\subset s ->\n    uncurry_step e s m e1 s1 m1 ->\n    uncurry_fundefs_step (f <[ e ]>) s m (f <[ e1 ]>) s1 m1.\nProof. apply app_ctx_uncurry_step_mut. Qed.\n\nLemma uncurry_step_increases_size_mut :\n  let P := (fun e s m e1 s1 m1 => sizeOf_exp e < sizeOf_exp e1) in\n  let Q := (fun f s m f1 s1 m1 => sizeOf_fundefs f < sizeOf_fundefs f1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q;\n  try (try destruct arm; simpl in *; lia).\nQed.\n\nCorollary uncurry_step_increases_size : forall e s m e1 s1 m1,\n  uncurry_step e s m e1 s1 m1 -> sizeOf_exp e < sizeOf_exp e1.\nProof. apply uncurry_step_increases_size_mut. Qed.\n\nCorollary uncurry_fundefs_step_increases_size : forall f s m f1 s1 m1,\n  uncurry_fundefs_step f s m f1 s1 m1 -> sizeOf_fundefs f < sizeOf_fundefs f1.\nProof. apply uncurry_step_increases_size_mut. Qed.\n\nLemma uncurry_step_acyclic : forall e s m e1 s1 m1 s2 m2,\n  uncurry_step e s m e1 s1 m1 -> ~ uncurry_step e1 s1 m1 e s2 m2.\nProof.\n  intros; intros H1.\n  apply uncurry_step_increases_size in H.\n  apply uncurry_step_increases_size in H1.\n  lia.\nQed.\n\nLemma uncurry_fundefs_step_acyclic : forall e s m e1 s1 m1 s2 m2,\n  uncurry_fundefs_step e s m e1 s1 m1 -> ~ uncurry_fundefs_step e1 s1 m1 e s2 m2.\nProof.\n  intros; intros H1.\n  apply uncurry_fundefs_step_increases_size in H.\n  apply uncurry_fundefs_step_increases_size in H1.\n  lia.\nQed.\n\nLocal Ltac step_isnt_cyclic :=\n  match goal with\n  | [ H : uncurry_step ?a _ _ ?b _ _,\n      H1 : uncurry_step ?b _ _ ?a _ _ |- _ ] =>\n    destruct (uncurry_step_acyclic _ _ _ _ _ _ _ _ H H1)\n  | [ H : uncurry_fundefs_step ?a _ _ ?b _ _,\n      H1 : uncurry_fundefs_step ?b _ _ ?a _ _ |- _ ] =>\n    destruct (uncurry_fundefs_step_acyclic _ _ _ _ _ _ _ _ H H1)\n  end.\n\nLemma uncurry_step_preserves_occurs_free_mut :\n  let P := (fun e s m e1 s1 m1 =>\n              used_vars e \\subset s ->\n              unique_bindings e ->\n              occurs_free e <--> occurs_free e1) in\n  let Q := (fun f s m f1 s1 m1 =>\n              used_vars_fundefs f \\subset s ->\n              unique_bindings_fundefs f ->\n              occurs_free_fundefs f <--> occurs_free_fundefs f1) in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  Local Ltac ensemble_compat_simpl := match goal with\n    [ _ : _ |- ?a :|: ?b \\subset ?a :|: ?c ] => apply Included_Union_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a \\\\ ?b \\subset ?a \\\\ ?c ] => apply Included_Setminus_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a :|: ?c \\subset ?b :|: ?c ] => apply Included_Union_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a \\\\ ?c \\subset ?b \\\\ ?c ] => apply Included_Setminus_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a :|: ?b <--> ?a :|: ?c ] => apply Same_set_Union_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a \\\\ ?b <--> ?a \\\\ ?c ] => apply Same_set_Setminus_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a :|: ?c <--> ?b :|: ?c ] => apply Same_set_Union_compat; eauto with Ensembles_DB\n  | [ _ : _ |- ?a \\\\ ?c <--> ?b \\\\ ?c ] => apply Same_set_Setminus_compat; eauto with Ensembles_DB\n  end.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *;\n  try destruct arm;\n  try (\n    repeat normalize_occurs_free;\n    repeat normalize_used_vars; intros Hused Huniq; inv Huniq;\n    destruct IH as [HL HR]; eauto; [eapply Included_trans; [|eauto]; eauto with Ensembles_DB|];\n    rewrite (conj HL HR : _ <--> _));\n  try reflexivity.\n  - (* Efun *)\n    ensemble_compat_simpl; split.\n    + intros a Ha; inv Ha; split; auto; intros contra.\n      assert (~ In var s a). {\n        eapply uncurry_fundefs_step_unique_names; eauto.\n        eapply Included_trans; [|eauto]...\n      }\n      contradiction H4; apply Hused; right; now right.\n    + ensemble_compat_simpl.\n      intros a Ha; eapply uncurry_fundefs_step_preserves_names; eauto.\n  - (* Fcons e *)\n    split.\n    + ensemble_compat_simpl.\n      intros a Ha; inv Ha.\n      repeat rewrite Union_demorgan in H0; destruct H0 as [Hf6 [Hargs Hfds]].\n      split; auto; intros contra; inv contra; inv H0; auto.\n      assert (~ In var s a). {\n        eapply uncurry_fundefs_step_unique_names; eauto.\n        eapply Included_trans; [|eauto]...\n      }\n      contradiction H0; apply Hused; left; right; now right.\n    + repeat ensemble_compat_simpl; intros a Ha; eapply uncurry_fundefs_step_preserves_names; eauto.\n  - (* Fcons cps uncurry *)\n    intros Hused Huniq.\n    do 2 rewrite occurs_free_fundefs_Fcons.\n    do 2 rewrite occurs_free_Efun; simpl; repeat rewrite Union_Empty_set_neut_r.\n    rewrite occurs_free_Eapp.\n    assert (Hrw : FromList [g] :|: [set k] \\\\ [set g] <--> [set k]). {\n      split; intros a Ha; inv Ha.\n      - inv H8. inv H10. now contradiction H9. inv H8. auto.\n      - constructor; [now right|].\n        intros contra; inv contra.\n        inv Huniq.\n        inv H15; contradiction (H8 a).\n        split; [|now left].\n        constructor; constructor; now left.\n    }\n    rewrite Hrw.\n    repeat normalize_occurs_free.\n    repeat (rewrite Union_Empty_set_neut_r + rewrite Setminus_Empty_set_abs_r).\n    assert (Hrw1 :\n      occurs_free ge \\\\ (g |: FromList gv) :|: [set k] \\\\\n        (f9 |: (FromList (k :: fv) :|: name_in_fundefs fds)) <-->\n      occurs_free ge \\\\ (f9 |: FromList gv :|: FromList fv :|: name_in_fundefs fds)). {\n      rewrite Setminus_Union_Included; [|rewrite FromList_cons; eauto with Ensembles_DB].\n      repeat rewrite <- Setminus_Union.\n      rewrite <- Included_Setminus_Disjoint with (s2 := [set g]).\n      repeat rewrite Setminus_Union.\n      rewrite Union_assoc, FromList_cons.\n      rewrite Union_commut.\n      repeat rewrite <- Setminus_Union.\n      rewrite <- Included_Setminus_Disjoint with (s2 := [set k]).\n      repeat rewrite Setminus_Union.\n      repeat rewrite Union_assoc.\n      rewrite Union_commut.\n      rewrite Union_commut with (s2 := FromList gv).\n      repeat rewrite Union_assoc...\n      apply Disjoint_Singleton_r; intros contra.\n      rewrite not_occurs_in_exp_iff_used_vars in H1; contradiction H1; now right.\n      apply Disjoint_Singleton_r; intros contra.\n      rewrite not_occurs_in_exp_iff_used_vars in H0; contradiction H0; now right.\n    }\n    rewrite Hrw1.\n    assert (Hrw2 : occurs_free_fundefs fds \\\\ [set f10] <--> occurs_free_fundefs fds). {\n      split...\n      intros a Ha; constructor...\n      intros contra; inv contra.\n      contradiction H6; do 2 left; apply Hused.\n      normalize_used_vars; right; now right.\n    }\n    rewrite Hrw2.\n    assert (Hrw3 :\n      occurs_free ge \\\\ (f10 |: (FromList (gv ++ fv) :|: name_in_fundefs fds)) <-->\n      occurs_free ge \\\\ (FromList gv :|: FromList fv :|: name_in_fundefs fds)). {\n      rewrite Union_commut.\n      rewrite <- Setminus_Union.\n      symmetry.\n      rewrite FromList_app.\n      apply Included_Setminus_Disjoint.\n      constructor; intros a contra; inv contra; inv H9.\n      contradiction H6; do 2 left; apply Hused.\n      inv H8.\n      normalize_used_vars; left; right.\n      normalize_used_vars; left; normalize_used_vars.\n      left; right; now right.\n    }\n    rewrite Hrw3.\n    assert (Hrw4 : FromList (gv1 ++ fv1) :|: [set f10] \\\\ (g |: FromList gv1) <-->\n                            f10 |: FromList fv1). {\n      rewrite Setminus_Union_distr.\n      assert (Hrw5 : [set f10] \\\\ (g |: FromList gv1) <--> [set f10]). {\n        symmetry.\n        apply Included_Setminus_Disjoint.\n        constructor; intros a contra; inv contra; inv H8.\n        inv H9; [inv H8|]; contradiction H6.\n        do 2 left; apply Hused; normalize_used_vars; left; right.\n        normalize_used_vars; left; normalize_used_vars; now do 3 left.\n        left; now right.\n      }\n      rewrite Hrw5.\n      rewrite Union_commut; apply Same_set_Union_compat...\n      rewrite FromList_app, Setminus_Union_distr.\n      assert (Hrw6 : FromList gv1 \\\\ (g |: FromList gv1) <--> Empty_set _).\n      apply Setminus_Included_Empty_set...\n      rewrite Hrw6; rewrite Union_Empty_set_neut_l.\n      symmetry.\n      apply Included_Setminus_Disjoint.\n      constructor; intros a contra; inv contra.\n      destruct H4 as [HL HR].\n      inv H9; [inv H4|].\n      inv HL; contradiction (H4 a).\n      split; auto.\n      left; apply Hused; normalize_used_vars; left; right.\n      normalize_used_vars; left; normalize_used_vars; now do 3 left.\n      inv HL; contradiction (H9 a); split; auto.\n    }\n    rewrite Hrw4.\n    assert (Hrw5 :\n      (f10 |: FromList fv1 :|: [set k]) \\\\\n        (f9 |: (FromList (k :: fv1) :|: (f10 |: name_in_fundefs fds))) <-->\n        Empty_set _). {\n      apply Setminus_Included_Empty_set.\n      intros a Ha; inv Ha; inv H8; [inv H9| |].\n      do 2 right; now left.\n      right; left; now right.\n      right; left; now left.\n    }\n    rewrite Hrw5; rewrite Union_Empty_set_neut_l.\n    rewrite Setminus_Union_distr.\n    rewrite Setminus_Union.\n    rewrite Union_commut with (s2 := [set f9]).\n    now repeat rewrite Union_assoc.\n  - (* anf uncurry *)\n    repeat normalize_used_vars.\n    apply not_occurs_in_exp_iff_used_vars in H0.\n    unfold used_vars, used_vars_fundefs in *.\n    repeat (normalize_occurs_free || normalize_bound_var || normalize_sets).\n    intros Hused Huniq.\n    repeat match goal with\n    | H : fresh_copies _ _ |- _ => destruct H\n    | H : ?S1 :|: ?S2 \\subset ?S3 |- _ => apply Union_Included_lr in H; destruct H\n    | H : unique_bindings (_ _) |- _ => inv H\n    | H : unique_bindings_fundefs (_ _) |- _ => inv H\n    | H : ~ In _ (_ :|: _) _ |- _ => rewrite Union_demorgan in H; destruct H\n    end.\n    change (~ bound_var ?e ?x) with (~ In _ (bound_var e) x) in *;\n    change (~ bound_var_fundefs ?fds ?x) with (~ In _ (bound_var_fundefs fds) x) in *;\n    repeat normalize_bound_var_in_ctx.\n    repeat match goal with\n    | H : ~ In _ (_ :|: _) _ |- _ => rewrite Union_demorgan in H; destruct H\n    | H : Disjoint ?A (?S1 :|: ?S2) ?S3 |- _ =>\n      assert (Disjoint A S1 S3) by (apply Disjoint_Union_l in H; apply H);\n      apply Disjoint_Union_r in H\n    | H : Disjoint ?A ?S1 (?S2 :|: ?S3) |- _ => apply Disjoint_sym in H\n    end.\n    repeat progress multimatch goal with\n    | Hdis : Disjoint var s ?S2, Hsub : ?S1 \\subset s |- _ =>\n      match goal with\n      | Hconc : Disjoint var S1 S2 |- _ => idtac\n      | _ => assert (Disjoint var S1 S2) by (eapply Disjoint_Included_l; [apply Hsub|apply Hdis])\n      end\n    | Hdis : ~ In var s ?x, Hsub : ?S \\subset s |- _ =>\n      match goal with\n      | Hconc : ~ In var S x |- _ => idtac\n      | _ => assert (~ In var S x) by\n            (let contra := fresh \"contra\" in intros contra;\n             contradiction Hdis; apply Hsub, contra)\n      end\n    end.\n    rewrite Ensemble_iff_In_iff; intros arbitrary.\n    repeat progress (cbn; (rewrite Union_demorgan || rewrite In_or_Iff_Union || rewrite not_In_Setminus)).\n    assert (True_neut_r : forall A, A /\\ True <-> A) by tauto.\n    assert (True_neut_l : forall A, True /\\ A <-> A) by tauto.\n    repeat rewrite identifiers.not_In_Empty_set.\n    repeat (rewrite True_neut_l || rewrite True_neut_r).\n    assert (Disjoint_Singleton : forall S x, Disjoint var [set x] S -> ~ In var S x). {\n      intros S x [Hdis] Hin; contradiction (Hdis x); now constructor. }\n    repeat multimatch goal with\n    | H : Disjoint ?A [set ?x] ?S |- _ =>\n      match goal with\n      | Hdup : ~ In A S x |- _ => idtac\n      | _ => assert (~ In A S x) by (apply Disjoint_Singleton in H; apply H)\n      end\n    end.\n    split; intros Hin; decompose [and or] Hin; clear Hin; try tauto.\n    + right; split; [|tauto].\n      left; split; [tauto|].\n      split; [|tauto].\n      inversion 1; now subst.\n    + right; split; [|tauto]; right; split; [tauto|].\n      inversion 1; now subst.\n    + left; split; [|tauto]; left; split; [tauto|].\n      split; [|tauto].\n      inversion 1; now subst.\nQed.\n\nLemma uncurry_step_preserves_closed : forall e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  uncurry_step e s m e1 s1 m1 -> closed_exp e -> closed_exp e1.\nProof with eauto with Ensembles_DB.\n  unfold closed_exp; intros.\n  destruct uncurry_step_preserves_occurs_free_mut.\n  rewrite <- H3; eauto.\nQed.\n\nLemma uncurry_step_preserves_occurs_free : forall e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  uncurry_step e s m e1 s1 m1 -> occurs_free e <--> occurs_free e1.\nProof with eauto with Ensembles_DB.\n  destruct uncurry_step_preserves_occurs_free_mut. now eauto.\nQed.\n\nInductive uncurry_rel :\n  nat ->\n  exp -> Ensemble var -> localMap ->\n  exp -> Ensemble var -> localMap ->\n  Prop :=\n| uncurry_rel_refl : forall e s m, uncurry_rel 0 e s m e s m\n| uncurry_rel_trans : forall n e s m e1 s1 m1 e2 s2 m2,\n      uncurry_step e s m e1 s1 m1 ->\n      uncurry_rel n e1 s1 m1 e2 s2 m2 ->\n      uncurry_rel (S n) e s m e2 s2 m2.\n\nInductive uncurry_rel_fundefs :\n  nat ->\n  fundefs -> Ensemble var -> localMap ->\n  fundefs -> Ensemble var -> localMap ->\n  Prop :=\n| uncurry_rel_fundefs_refl : forall f s m, uncurry_rel_fundefs 0 f s m f s m\n| uncurry_rel_fundefs_trans : forall n f s m f1 s1 m1 f2 s2 m2,\n      uncurry_fundefs_step f s m f1 s1 m1 ->\n      uncurry_rel_fundefs n f1 s1 m1 f2 s2 m2 ->\n      uncurry_rel_fundefs (S n) f s m f2 s2 m2.\n\nHint Constructors uncurry_rel : core.\nHint Constructors uncurry_rel_fundefs : core.\n\nLemma uncurry_rel_Sn : forall n e s m e1 s1 m1,\n  uncurry_rel (S n) e s m e1 s1 m1 -> exists e2 s2 m2,\n  uncurry_rel n e s m e2 s2 m2 /\\ uncurry_step e2 s2 m2 e1 s1 m1.\nProof.\n  induction n.\n  - do 3 eexists; split; auto.\n    inv H; now inv H2.\n  - intros.\n    inv H.\n    apply IHn in H2.\n    destruct H2 as [e3 [s3 [m3 [Hrel Hstep]]]].\n    do 3 eexists; split; eauto.\nQed.\n\nLemma Sn_uncurry_rel : forall n e s m e1 s1 m1 e2 s2 m2,\n  uncurry_rel n e s m e2 s2 m2 ->\n  uncurry_step e2 s2 m2 e1 s1 m1 ->\n  uncurry_rel (S n) e s m e1 s1 m1.\nProof.\n  induction 1; intros.\n  - econstructor; eauto.\n  - apply IHuncurry_rel in H1.\n    econstructor; eauto.\nQed.\n\nLemma uncurry_rel_fundefs_Sn : forall n e s m e1 s1 m1,\n  uncurry_rel_fundefs (S n) e s m e1 s1 m1 -> exists e2 s2 m2,\n  uncurry_rel_fundefs n e s m e2 s2 m2 /\\ uncurry_fundefs_step e2 s2 m2 e1 s1 m1.\nProof.\n  induction n.\n  - do 3 eexists; split; auto.\n    inv H; now inv H2.\n  - intros.\n    inv H.\n    apply IHn in H2.\n    destruct H2 as [e3 [s3 [m3 [Hrel Hstep]]]].\n    do 3 eexists; split; eauto.\nQed.\n\nLemma Sn_uncurry_rel_fundefs : forall n e s m e1 s1 m1 e2 s2 m2,\n  uncurry_rel_fundefs n e s m e2 s2 m2 ->\n  uncurry_fundefs_step e2 s2 m2 e1 s1 m1 ->\n  uncurry_rel_fundefs (S n) e s m e1 s1 m1.\nProof.\n  induction 1; intros.\n  - econstructor; eauto.\n  - apply IHuncurry_rel_fundefs in H1.\n    econstructor; eauto.\nQed.\n\nLemma uncurry_rel_compose : forall n1 n e s m e1 s1 m1 e2 s2 m2,\n  uncurry_rel n e s m e1 s1 m1 ->\n  uncurry_rel n1 e1 s1 m1 e2 s2 m2 ->\n  uncurry_rel (n1 + n) e s m e2 s2 m2.\nProof.\n  induction n1; intros; [inv H0; auto|].\n  apply uncurry_rel_Sn in H0.\n  destruct H0 as [e3 [s3 [m3 [Hrel Hstep]]]].\n  eapply Sn_uncurry_rel; eauto.\nQed.\n\nLemma uncurry_rel_fundefs_compose : forall n1 n e s m e1 s1 m1 e2 s2 m2,\n  uncurry_rel_fundefs n e s m e1 s1 m1 ->\n  uncurry_rel_fundefs n1 e1 s1 m1 e2 s2 m2 ->\n  uncurry_rel_fundefs (n1 + n) e s m e2 s2 m2.\nProof.\n  induction n1; intros; [inv H0; auto|].\n  apply uncurry_rel_fundefs_Sn in H0.\n  destruct H0 as [e3 [s3 [m3 [Hrel Hstep]]]].\n  eapply Sn_uncurry_rel_fundefs; eauto.\nQed.\n\nLemma uncurry_rel_preserves_unique_bindings : forall n e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  unique_bindings e1.\nProof.\n  induction n; [inversion 3; subst; auto|].\n  intros.\n  inv H1.\n  eapply IHn; [| |eassumption].\n  eapply uncurry_step_preserves_used_vars; eauto.\n  eapply uncurry_step_preserves_unique_bindings; eauto.\nQed.\n\nLemma uncurry_rel_preserves_closed : forall n e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  closed_exp e ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  closed_exp e1.\nProof.\n  induction n; [inversion 4; subst; auto|].\n  intros.\n  inv H2.\n  eapply IHn; [| | |eassumption].\n  eapply uncurry_step_preserves_used_vars; eauto.\n  eapply uncurry_step_preserves_unique_bindings; eauto.\n  eapply uncurry_step_preserves_closed; eauto.\nQed.\n\nLemma uncurry_rel_preserves_occurs_free : forall n e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  unique_bindings e ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  occurs_free e <--> occurs_free e1.\nProof.\n  induction n; [inversion 3; subst; auto|].\n  intros.\n  inv H1. subst. reflexivity.\n  intros. inv H1. eapply Same_set_trans.\n  now eapply uncurry_step_preserves_occurs_free; eauto.\n  eapply IHn; [| |eassumption].\n  eapply uncurry_step_preserves_used_vars; eauto.\n  eapply uncurry_step_preserves_unique_bindings; eauto.\nQed.\n\nLemma uncurry_rel_preserves_used_vars : forall n e s m e1 s1 m1,\n  used_vars e \\subset s ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  used_vars e1 \\subset s1.\nProof.\n  induction n; [inversion 2; subst; auto|].\n  intros.\n  inv H0.\n  eapply IHn; [|eassumption].\n  eapply uncurry_step_preserves_used_vars; eauto.\nQed.\n\nLemma uncurry_rel_s_nondecreasing : forall n e s m e1 s1 m1,\n  uncurry_rel n e s m e1 s1 m1 -> s \\subset s1.\nProof.\n  induction n; inversion 1; [eauto with Ensembles_DB|subst].\n  eapply Included_trans.\n  eapply uncurry_step_s_nondecreasing; eauto.\n  eapply IHn; eauto.\nQed.\n\nLemma uncurry_fundefs_rel_s_nondecreasing : forall n f s m f1 s1 m1,\n  uncurry_rel_fundefs n f s m f1 s1 m1 -> s \\subset s1.\nProof.\n  induction n; inversion 1; [eauto with Ensembles_DB|subst].\n  eapply Included_trans.\n  eapply uncurry_fundefs_step_s_nondecreasing; eauto.\n  eapply IHn; eauto.\nQed.\n\nLemma uncurry_fundefs_rel_preserves_used_vars : forall n f s m f1 s1 m1,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s ->\n  used_vars_fundefs f1 \\subset s1.\nProof.\n  induction n; inversion 1; [eauto with Ensembles_DB|subst]; intros.\n  apply uncurry_fundefs_step_preserves_used_vars in H1; auto.\n  eapply IHn; eauto.\nQed.\n\nLemma uncurry_fundefs_rel_preserves_unique_bindings : forall n f s m f1 s1 m1,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s ->\n  unique_bindings_fundefs f ->\n  unique_bindings_fundefs f1.\nProof.\n  induction 1; intros; auto.\n  apply IHuncurry_rel_fundefs.\n  eapply uncurry_fundefs_step_preserves_used_vars; eauto.\n  eapply uncurry_fundefs_step_preserves_unique_bindings; eauto.\nQed.\n\nLemma uncurry_rel_maintains_bindings_fn: forall n e s m e1 s1 m1,\n  uncurry_rel n e s m e1 s1 m1 ->\n  used_vars e \\subset s -> forall a,\n  In _ (bound_var e1) a ->\n  In _ s a ->\n  In _ (bound_var e) a.\nProof.\n  induction 1; intros; auto.\n  eapply uncurry_step_maintains_bindings_fn; eauto.\n  eapply IHuncurry_rel; eauto.\n  eapply uncurry_step_preserves_used_vars; eauto.\n  eapply uncurry_step_s_nondecreasing; eauto.\nQed.\n\nLemma uncurry_fundefs_rel_maintains_bindings_fn: forall n f s m f1 s1 m1,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s -> forall a,\n  In _ (bound_var_fundefs f1) a ->\n  In _ s a ->\n  In _ (bound_var_fundefs f) a.\nProof.\n  induction 1; intros; auto.\n  eapply uncurry_fundefs_step_maintains_bindings_fn; eauto.\n  eapply IHuncurry_rel_fundefs; eauto.\n  eapply uncurry_fundefs_step_preserves_used_vars; eauto.\n  eapply uncurry_fundefs_step_s_nondecreasing; eauto.\nQed.\n\nLemma uncurry_rel_maintains_used_vars_fn: forall n e s m e1 s1 m1,\n  uncurry_rel n e s m e1 s1 m1 ->\n  used_vars e \\subset s -> forall a,\n  In _ (used_vars e1) a ->\n  In _ s a ->\n  In _ (used_vars e) a.\nProof.\n  induction 1; intros; auto.\n  eapply uncurry_step_maintains_used_vars_fn; eauto.\n  eapply IHuncurry_rel; eauto.\n  eapply uncurry_step_preserves_used_vars; eauto.\n  eapply uncurry_step_s_nondecreasing; eauto.\nQed.\n\nLemma uncurry_fundefs_rel_maintains_used_vars_fn: forall n f s m f1 s1 m1,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  used_vars_fundefs f \\subset s -> forall a,\n  In _ (used_vars_fundefs f1) a ->\n  In _ s a ->\n  In _ (used_vars_fundefs f) a.\nProof.\n  induction 1; intros; auto.\n  eapply uncurry_fundefs_step_maintains_used_vars_fn; eauto.\n  eapply IHuncurry_rel_fundefs; eauto.\n  eapply uncurry_fundefs_step_preserves_used_vars; eauto.\n  eapply uncurry_fundefs_step_s_nondecreasing; eauto.\nQed.\n\nLemma app_ctx_uncurry_rel : forall n c e s m e1 s1 m1,\n  used_vars (c |[ e ]|) \\subset s ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  uncurry_rel n (c |[ e ]|) s m (c |[ e1 ]|) s1 m1.\nProof.\n  induction n; [inversion 2; subst; constructor|].\n  intros c e s m e1 s1 m1 Hused Hrel.\n  inv Hrel.\n  econstructor.\n  apply app_ctx_uncurry_step; eauto.\n  apply IHn; auto.\n  eapply uncurry_step_preserves_used_vars.\n  apply app_ctx_uncurry_step. all: eauto.\nQed.\n\nLemma app_ctx_uncurry_rel_fundefs : forall n f e s m e1 s1 m1,\n  used_vars_fundefs (f <[ e ]>) \\subset s ->\n  uncurry_rel n e s m e1 s1 m1 ->\n  uncurry_rel_fundefs n (f <[ e ]>) s m (f <[ e1 ]>) s1 m1.\nProof.\n  induction n; [inversion 2; subst; constructor|].\n  intros f e s m e1 s1 m1 Hused Hrel.\n  inv Hrel.\n  econstructor.\n  apply app_ctx_uncurry_fundefs_step; eauto.\n  apply IHn; auto.\n  eapply uncurry_fundefs_step_preserves_used_vars.\n  apply app_ctx_uncurry_fundefs_step. all: eauto.\nQed.\n\nLemma uncurry_rel_fundefs_Efun : forall n f s m f1 s1 m1 e,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  uncurry_rel n (Efun f e) s m (Efun f1 e) s1 m1.\nProof.\n  induction n; intros; inv H; auto.\n  eapply IHn in H2.\n  econstructor; eauto.\nQed.\n\nLemma uncurry_step_Ecase_l : forall v arms s m arms1 s1 m1,\n  uncurry_step (Ecase v arms) s m (Ecase v arms1) s1 m1 -> exists l c e e1 r,\n  arms = l ++ (c, e) :: r /\\ arms1 = l ++ (c, e1) :: r /\\ uncurry_step e s m e1 s1 m1.\nProof.\n  induction arms; intros; inv H.\n  exists [], c, e, e1, arms; eauto.\n  apply IHarms in H8.\n  destruct H8 as [l [c [e [e1 [r [Harms [Harms2 Hstep]]]]]]].\n  exists (a :: l), c, e, e1, r; split; [|split]; simpl; now f_equal.\nQed.\n\nLemma uncurry_rel_Ecase_l : forall n v arms s m arms1 s1 m1 c e,\n  uncurry_rel n (Ecase v arms) s m (Ecase v arms1) s1 m1 ->\n  uncurry_rel n (Ecase v ((c, e) :: arms)) s m (Ecase v ((c, e) :: arms1)) s1 m1.\nProof.\n  induction n; intros.\n  - now inv H.\n  - inv H.\n    inv H1.\n    + econstructor.\n      apply uncurry_case_arms.\n      apply uncurry_case_expr; eauto.\n      now apply IHn.\n    + econstructor.\n      do 2 apply uncurry_case_arms; eauto.\n      apply IHn; eauto.\nQed.\n\nLemma uncurry_rel_fundefs_Fcons : forall n f' t v f s m f1 s1 m1 e,\n  uncurry_rel_fundefs n f s m f1 s1 m1 ->\n  uncurry_rel_fundefs n (Fcons f' t v e f) s m (Fcons f' t v e f1) s1 m1.\nProof.\n  induction n; intros; inv H; auto.\n  eapply IHn in H2.\n  econstructor; eauto.\nQed.\n\nLemma uncurry_rel_case : forall n v l s m e s1 m1,\n  uncurry_rel n (Ecase v l) s m e s1 m1 -> exists l', e = Ecase v l'.\nProof.\n  induction n; intros.\n  - inv H; eauto.\n  - inv H; inv H1; now apply IHn in H2.\nQed.\n\nLemma uncurry_step_subst_mut :\n  let P := (fun e s m e1 s1 m1 => forall e' s' m' e1' s1' m1', \n    e = e' -> s <--> s' -> m = m' -> e1 = e1' -> s1 <--> s1' -> m1 = m1' ->\n    uncurry_step e' s' m' e1' s1' m1') in\n  let Q := (fun f s m f1 s1 m1 => forall f' s' m' f1' s1' m1', \n    f = f' -> s <--> s' -> m = m' -> f1 = f1' -> s1 <--> s1' -> m1 = m1' ->\n    uncurry_fundefs_step f' s' m' f1' s1' m1') in\n  (forall e s m e1 s1 m1, uncurry_step e s m e1 s1 m1 -> P e s m e1 s1 m1) /\\\n  (forall f s m f1 s1 m1, uncurry_fundefs_step f s m f1 s1 m1 -> Q f s m f1 s1 m1).\nProof with eauto with Ensembles_DB.\n  intros P Q.\n  uncurry_step_induction_mut P Q IHstep IH; subst P; subst Q; simpl in *; intros; try solve\n  [destruct e'; destruct e1'; try congruence; inv H; inv H2; constructor; apply IH; auto\n  |destruct f'; destruct f1'; try congruence; inv H; inv H2; constructor; apply IH; auto].\n  - destruct f'; destruct f1'; try congruence.\n    inv H8; inv H11.\n    constructor; unfold fresh_copies in *; destruct H2, H4; try split; auto;\n      try rewrite <- H9; try rewrite H12; try rewrite H7...\n    rewrite <- H12.\n    rewrite H7...\n    rewrite <- H7; rewrite H12...\n  - destruct f'; destruct f1'; try congruence.\n    inv H7; inv H10.\n    constructor; auto; unfold fresh_copies in *.\n    + now rewrite <- H8.\n    + now rewrite <- H8.\n    + now rewrite <- H8.\n    + now rewrite <- H8, <- H11.\nQed.\n\nCorollary uncurry_fundefs_step_subst : forall f s m f1 s1 m1 f' s' m' f1' s1' m1',\n  uncurry_fundefs_step f s m f1 s1 m1 ->\n  f = f' -> s <--> s' -> m = m' -> f1 = f1' -> s1 <--> s1' -> m1 = m1' ->\n  uncurry_fundefs_step f' s' m' f1' s1' m1'.\nProof. intros; eapply uncurry_step_subst_mut; eauto. Qed.\n\nCorollary uncurry_step_subst : forall e s m e1 s1 m1 e' s' m' e1' s1' m1',\n  uncurry_step e s m e1 s1 m1 ->\n  e = e' -> s <--> s' -> m = m' -> e1 = e1' -> s1 <--> s1' -> m1 = m1' ->\n  uncurry_step e' s' m' e1' s1' m1'.\nProof. intros; eapply uncurry_step_subst_mut; eauto. Qed.\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/uncurry_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.17252097950077866}}
{"text": "From hahn Require Import Hahn.\n\nRequire Import Events.\nRequire Import Execution.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection CO.\n\nVariables G : execution.\nVariable I : actid -> Prop.  (* issued *)\nVariable T : actid -> Prop.  (* all writes in certified thread *)\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'loc'\" := (loc lab).\nNotation \"'same_loc'\" := (same_loc lab).\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'W_' l\" := (W \u2229\u2081 Loc_ l) (at level 1).\n\nHypothesis IT: I \u222a\u2081 T \u2261\u2081 E \u2229\u2081 W.\n\nLemma IN_I: I \u2286\u2081 E \u2229\u2081 W.\nProof using IT.\nrewrite <- IT; basic_solver 21.\nQed.\n\nLemma IN_T: T \u2286\u2081 E \u2229\u2081 W.\nProof using IT.\nrewrite <- IT; basic_solver 21.\nQed.\n\nHypothesis wf_coE : co \u2261 \u2997E\u2998 \u2a3e co \u2a3e \u2997E\u2998.\nHypothesis wf_coD : co \u2261 \u2997W\u2998 \u2a3e co \u2a3e \u2997W\u2998.\nHypothesis wf_col : co \u2286 same_loc.\nHypothesis co_trans : transitive co.\nHypothesis wf_co_total : forall ol, is_total (E \u2229\u2081 W \u2229\u2081 (fun x => loc x = ol)) co.\nHypothesis co_irr : irreflexive co.\n\nDefinition col l := (\u2997Loc_ l\u2998 \u2a3e co \u2a3e \u2997Loc_ l\u2998).\n\nDefinition col0 l := (\u2997I\u2998 \u2a3e col l \u2a3e \u2997I\u2998 \u222a \u2997T\u2998 \u2a3e col l \u2a3e \u2997T\u2998 \u222a \u2997I\u2998 \u2a3e col l \u2a3e \u2997T\u2998)\u207a.\n\nDefinition new_col l := pref_union (col0 l) ((I \u2229\u2081 Loc_ l) \u00d7 (E \u2229\u2081 W \u2229\u2081 Loc_ l \\\u2081 I)).\n\nDefinition new_co x y := exists l, (new_col l) x y.\n\nLemma col_in_co l : col l \u2286 co.\nProof using. \nunfold col; basic_solver. \nQed.\n\nLemma co_in_col x y : co x y -> exists l, col l x y.\nProof using wf_coD wf_col.\nunfold new_co, col; ins; unfolder; ins; desf.\nhahn_rewrite (dom_l wf_coD) in H; unfolder in H; desc.\ngeneralize (is_w_loc lab x H); ins; desf.\neexists; splits; eauto.\neexists; splits; eauto.\neexists; splits; eauto.\napply wf_col in H0; unfold Events.same_loc in H0; congruence.\nQed.\n\nLemma wf_colE l : col l \u2261 \u2997E\u2998 \u2a3e col l \u2a3e \u2997E\u2998.\nProof using wf_coE. \napply dom_helper_3; unfold col; rewrite wf_coE; basic_solver. \nQed.\n\nLemma wf_colD l : col l \u2261 \u2997W_ l\u2998 \u2a3e col l \u2a3e \u2997W_ l\u2998.\nProof using wf_coD.\napply dom_helper_3; unfold col; rewrite wf_coD; basic_solver. \nQed.\n\nLemma wf_coll l : col l \u2286 same_loc.\nProof using wf_col.\nunfold col; rewrite wf_col; basic_solver. \nQed.\n\nLemma col_trans l : transitive (col l).\nProof using co_trans.\nunfold col.\nrewrite <- restr_relE.\nby apply transitive_restr.\nQed.\n\nLemma wf_col_total l : is_total (E \u2229\u2081 W \u2229\u2081 Loc_ l) (col l).\nProof using wf_coD wf_coE wf_co_total.\nrewrite wf_colD, wf_colE.\nunfold col; rewrite !seqA.\narewrite (\u2997W_ l\u2998 \u2a3e \u2997E\u2998 \u2a3e \u2997Loc_ l\u2998 \u2261 \u2997E \u2229\u2081 W \u2229\u2081 Loc_ l\u2998) by basic_solver.\narewrite (\u2997Loc_ l\u2998 \u2a3e \u2997E\u2998 \u2a3e \u2997W_ l\u2998 \u2261 \u2997E \u2229\u2081 W \u2229\u2081 Loc_ l\u2998) by basic_solver.\nrewrite <- restr_relE.\napply is_total_restr.\napply wf_co_total.\nQed.\n\nLemma col_irr l: irreflexive (col l).\nProof using co_irr.\nunfold col.\nrewrite <- restr_relE.\nby apply irreflexive_restr.\nQed.\n\nLemma acyclic_new_col l : acyclic (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\neapply acyclic_pref_union with (dom:=I \u2229\u2081 Loc_ l).\n- unfold col0.\n  arewrite_id \u2997I\u2998.\n  arewrite_id \u2997T\u2998.\n  relsf.\n  generalize (@col_trans l); ins; relsf; apply col_irr.\n- unfold col0; relsf.\n- assert (XX: restr_rel (I \u2229\u2081 Loc_ l) (col l) \u2286 col0 l).\n  by unfold col0; rewrite <- ct_step; basic_solver 21.\n  rewrite <- XX.\n  apply is_total_restr.\n  rewrite IN_I.\n  eapply wf_col_total.\n- unfolder; ins; desf; splits; eauto; intro; desf.\nQed.\n\nLemma wf_new_colE l : new_col l \u2261 \u2997E\u2998 \u2a3e new_col l \u2a3e \u2997E\u2998.\nProof using IT wf_coE.\napply dom_helper_3.\nunfold new_col, pref_union, col0; unfolder; ins; desf.\n2: by generalize (IN_I H); basic_solver 12.\ninduction H; [|basic_solver].\ndesf; apply (wf_colE l) in H0; unfolder in H0; desf; eauto.\nQed.\n\nLemma wf_new_colD l : new_col l \u2261 \u2997W_ l\u2998 \u2a3e new_col l \u2a3e \u2997W_ l\u2998.\nProof using IT wf_coD.\napply dom_helper_3.\nunfold new_col, pref_union, col0; unfolder; ins; desf.\n2: by generalize (IN_I H); basic_solver 12.\ninduction H; [|basic_solver].\ndesf; apply (wf_colD l) in H0; unfolder in H0; desf; eauto.\nQed.\n\nLemma wf_new_coll l : new_col l \u2286 same_loc.\nProof using IT wf_coD.\nrewrite wf_new_colD; unfold Events.same_loc.\nunfolder; ins; desf; congruence.\nQed.\n\nLemma wf_new_col_total l : is_total (E \u2229\u2081 W \u2229\u2081 Loc_ l) (new_col l).\nProof using IT wf_coD wf_coE wf_co_total.\nunfold new_col, pref_union.\nunfolder; ins; desf.\ndestruct (classic (col0 l a b)) as [|X]; eauto 8.\ndestruct (classic (col0 l b a)) as [|Y]; eauto 8.\nassert (XX: ~ (\u2997I\u2998 \u2a3e col l \u2a3e \u2997I\u2998 \u222a \u2997T\u2998 \u2a3e col l \u2a3e \u2997T\u2998 \u222a \u2997I\u2998 \u2a3e col l \u2a3e \u2997T\u2998) a b).\nby intro; eapply X; vauto.\nassert (YY: ~ (\u2997I\u2998 \u2a3e col l \u2a3e \u2997I\u2998 \u222a \u2997T\u2998 \u2a3e col l \u2a3e \u2997T\u2998 \u222a \u2997I\u2998 \u2a3e col l \u2a3e \u2997T\u2998) b a).\nby intro; eapply Y; vauto.\n \nassert (Ta: ~ I a -> T a).\nby assert (S: (E \u2229\u2081 W) a) by basic_solver; apply IT in S; unfolder in S; ins; desf.\nassert (Tb: ~ I b -> T b).\nby assert (S: (E \u2229\u2081 W) b) by basic_solver; apply IT in S; unfolder in S; ins; desf.\n\nassert (TOT: col l a b \\/ col l b a).\nby apply wf_col_total; basic_solver.\ndestruct (classic (I a)), (classic (I b)); desf.\n- exfalso; unfolder in XX; basic_solver 22.\n- exfalso; unfolder in YY; basic_solver 22.\n- exfalso; unfolder in XX; basic_solver 22.\n- eauto 20.\n- eauto 20.\n- exfalso; unfolder in YY; basic_solver 22.\n- exfalso; unfolder in XX; basic_solver 22.\n- exfalso; unfolder in YY; basic_solver 22.\nQed.\n\n\nLemma new_col_trans l : transitive (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\napply transitiveI; unfolder; ins; desf.\neapply tot_ex.\n- apply wf_new_col_total.\n- hahn_rewrite wf_new_colE in H0.\nhahn_rewrite wf_new_colD in H0.\nunfolder in H0; basic_solver 21.\n- hahn_rewrite wf_new_colE in H.\nhahn_rewrite wf_new_colD in H.\nunfolder in H; basic_solver 21.\n- intro.\neapply acyclic_new_col.\neapply t_trans, t_trans; vauto.\n- intro.\neapply acyclic_new_col.\neapply t_trans; vauto.\nQed.\n\nLemma new_col_irr l : irreflexive (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nred; ins; eapply acyclic_new_col; vauto.\nQed.\n\nLemma wf_new_coE : new_co \u2261 \u2997E\u2998 \u2a3e new_co \u2a3e \u2997E\u2998.\nProof using IT wf_coE.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (wf_new_colE l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma wf_new_coD : new_co \u2261 \u2997W\u2998 \u2a3e new_co \u2a3e \u2997W\u2998.\nProof using IT wf_coD.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (wf_new_colD l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma wf_new_col : new_co \u2286 same_loc.\nProof using IT wf_coD.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (@wf_new_coll l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma new_co_trans : transitive new_co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\nhahn_rewrite wf_new_colD in H0.\nhahn_rewrite wf_new_colD in H.\nunfolder in H0; unfolder in H; desf.\nexists l; eapply new_col_trans; eauto.\nQed.\n\nLemma wf_new_co_total : forall ol, is_total (E \u2229\u2081 W \u2229\u2081 (fun x => loc x = ol)) new_co.\nProof using IT wf_coD wf_coE wf_co_total.\nunfold new_co; ins; unfolder; ins; desf.\ngeneralize (is_w_loc lab a IWa1); ins; desf.\ncut (new_col l a b \\/ new_col l b a); [by basic_solver 21|].\napply wf_new_col_total; auto.\nbasic_solver.\nunfolder; splits; ins; desf; congruence.\nQed.\n\nLemma new_co_irr : irreflexive new_co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfold new_co; ins; unfolder; ins; desf.\neapply new_col_irr; eauto.\nQed.\n\nLemma new_co_I : new_co \u2a3e \u2997 I \u2998  \u2286 co \u2a3e \u2997 I \u2998.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfolder; intros x y [R K]; desf.\nunfold new_co in R; desc.\nhahn_rewrite wf_new_colE in R.\nhahn_rewrite wf_new_colD in R.\nunfolder in R; desf; splits; auto.\neapply tot_ex.\n- apply wf_co_total.\n- basic_solver.\n- unfolder; splits; eauto; congruence.\n- intro.\nassert (S: (E \u2229\u2081 W) z) by basic_solver.\napply IT in S; unfolder in S; ins; desf.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step; basic_solver 12.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step; basic_solver 12.\n- intro; subst.\neby eapply new_col_irr.\nQed.\n\nLemma T_new_co : \u2997 T \u2998 \u2a3e new_co  \u2286 \u2997 T \u2998 \u2a3e co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfolder; intros x y [K1 R]; desf.\nunfold new_co in R; desc.\nhahn_rewrite wf_new_colE in R.\nhahn_rewrite wf_new_colD in R.\nunfolder in R; desf; splits; auto.\neapply tot_ex.\n- apply wf_co_total.\n- basic_solver.\n- unfolder; splits; eauto; congruence.\n- intro.\nassert (S: (E \u2229\u2081 W) z) by basic_solver.\napply IT in S; unfolder in S; ins; desf.\n* eapply new_col_irr, new_col_trans; try edone.\n\nred; red; unfold col0, col. left; apply t_step.\nassert (I y \\/ T y) by (apply IT; basic_solver).\ndesf; basic_solver 12.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step.\nassert (I y \\/ T y) by (apply IT; basic_solver).\ndesf; basic_solver 12.\n- intro; subst.\neby eapply new_col_irr.\nQed.\n\nLemma new_co_in : new_co  \u2286 co \u2a3e \u2997 I \u2998 \u222a \n\u2997 T \u2998 \u2a3e co \u222a \u2997 I \\\u2081 T \u2998 \u2a3e new_co \u2a3e \u2997 T \\\u2081 I \u2998.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nrewrite (wf_new_coD), (wf_new_coE) at 1.\nrewrite !seqA.\narewrite (\u2997W\u2998 \u2a3e \u2997E\u2998 \u2286 \u2997E \u2229\u2081 W\u2998) by basic_solver.\narewrite (\u2997E\u2998 \u2a3e \u2997W\u2998 \u2286 \u2997E \u2229\u2081 W\u2998) by basic_solver.\nrewrite <- IT.\n\narewrite (I \u222a\u2081 T \u2286\u2081 (I \\\u2081 T) \u222a\u2081 T) at 1.\nunfolder; ins; desf; tauto.\n\narewrite (I \u222a\u2081 T \u2286\u2081 (T \\\u2081 I) \u222a\u2081 I) at 1.\nunfolder; ins; desf; tauto.\n\nrewrite !id_union; relsf.\n\nsin_rewrite !T_new_co.\nsin_rewrite new_co_I.\nbasic_solver 21.\nQed.\n\nLemma T_I_col0_I_T l : \n  \u2997 T \\\u2081 I \u2998 \u2a3e col0 l \u2a3e \u2997 I \\\u2081 T \u2998  \u2286 \n  \u2997 T \\\u2081 I \u2998 \u2a3e col l \u2a3e \u2997 I \u2229\u2081 T \u2998 \u2a3e col l \u2a3e \u2997 I \\\u2081 T \u2998.\nProof using co_trans.\nunfold col0 at 1.\narewrite (\u2997T\u2998 \u2286 \u2997T \\\u2081 I\u2998 \u222a \u2997I \u2229\u2081 T\u2998) at 2.\nunfolder; ins ;desf; tauto.\nrelsf.\nrewrite <- !unionA.\nrewrite unionC.\nrewrite <- !unionA.\nrewrite path_ut_first; relsf; unionL.\n- transitivity (\u2205\u2082 : actid -> actid -> Prop); [|basic_solver].\n  rewrite path_ut_last; relsf; unionL.\n  rewrite ct_begin; basic_solver.\n  rewrite (rtE (\u2997I\u2998 \u2a3e col l \u2a3e \u2997T\u2998 \u222a \u2997I\u2998 \u2a3e col l \u2a3e \u2997I\u2998)).\n  relsf; unionL.\n  basic_solver.\n  rewrite ct_begin; basic_solver.\n- arewrite (\u2997I\u2998 \u2a3e col l \u2a3e \u2997T\u2998 \u222a \u2997I\u2998 \u2a3e col l \u2a3e \u2997I\u2998 \u222a \u2997T\u2998 \u2a3e col l \u2a3e \u2997T \\\u2081 I\u2998 \u2286 col l).\n  basic_solver.\n  arewrite (col l \u222a \u2997T\u2998 \u2a3e col l \u2a3e \u2997I \u2229\u2081 T\u2998 \u2286 col l).\n  basic_solver.\n  generalize (@col_trans l); ins; relsf.\n  basic_solver 21.\nQed.\n\nLemma T_I_new_col_I_T l : \n  \u2997 T \\\u2081 I \u2998 \u2a3e new_col l \u2a3e \u2997 I \\\u2081 T \u2998  \u2286 \n  col l \u2a3e \u2997 I \u2229\u2081 T \u2998 \u2a3e col l.\nProof using co_trans.\nunfold new_col, pref_union.\nunfolder; ins; desf.\nassert (A: (\u2997 T \\\u2081 I \u2998 \u2a3e col0 l \u2a3e \u2997 I \\\u2081 T \u2998) x y) by basic_solver.\napply T_I_col0_I_T in A; unfolder in A; basic_solver 10.\nQed.\n\nLemma T_I_new_co_I_T : \n  \u2997 T \\\u2081 I \u2998 \u2a3e new_co \u2a3e \u2997 I \\\u2081 T \u2998  \u2286 \n  co \u2a3e \u2997 I \u2229\u2081 T \u2998 \u2a3e co.\nProof using co_trans.\nunfold new_co.\nunfolder; ins; desf.\nassert (A: (\u2997 T \\\u2081 I \u2998 \u2a3e new_col l \u2a3e \u2997 I \\\u2081 T \u2998) x y) by basic_solver.\napply T_I_new_col_I_T in A; unfolder in A; desf.\nunfold col in *; unfolder in *; desf; eauto 10.\nQed.\n\nLemma co_for_split: codom_rel (\u2997set_compl I\u2998 \u2a3e (immediate new_co)) \u2286\u2081 T.\nProof using IT wf_coD wf_coE.\nunfolder; ins; desf.\ndestruct (classic (T x)) as [|X]; auto.\nexfalso.\nhahn_rewrite wf_new_coE in H0.\nhahn_rewrite wf_new_coD in H0.\nunfolder in H0; desf.\nassert (Ix: I x).\nby assert (S: (E \u2229\u2081 W) x) by basic_solver; apply IT in S; unfolder in S; ins; desf.\nunfold new_co, new_col, pref_union in *; desc.\ndestruct H4 as [K|]; cycle 1.\nby unfolder in H2; basic_solver 21.\nunfold col0 in *.\ndestruct K.\nunfolder in H2; basic_solver 21.\neauto 12.\nQed.\n\nLemma new_col_helper l : \u2997 T \u2998 \u2a3e col l \u2a3e \u2997 I \u2229\u2081 T \u2998 \u2a3e col l \u2a3e \u2997 I \u2998 \u2286 new_col l.\nProof using.\nunfold new_col, pref_union, col0.\nunfolder; ins; left; desf.\neapply t_trans; apply t_step; eauto 15.\nQed.\n\nLemma new_co_helper : \u2997 T \u2998 \u2a3e co \u2a3e \u2997 I \u2229\u2081 T \u2998 \u2a3e co \u2a3e \u2997 I \u2998 \u2286 new_co.\nProof using wf_coD wf_col.\nunfold new_co.\nunfolder; ins; desf.\napply co_in_col in H0.\napply co_in_col in H2.\ndesf.\nassert (l = l0); subst.\n{ hahn_rewrite wf_colD in H0.\n  hahn_rewrite wf_colD in H2.\n  unfolder in *; desf. }\nexists l0.\napply new_col_helper.\nbasic_solver 12.\nQed.\n\nLemma I_co_in_new_co : \u2997 I \u2998 \u2a3e co \u2286 new_co.\nProof using IT wf_coD wf_coE wf_col.\nunfold new_co.\nunfolder; ins; desf.\napply co_in_col in H0.\ndesf.\nexists l.\nunfold new_col, pref_union, col0.\nleft.\napply t_step.\ndestruct (classic (I y)).\nbasic_solver 11.\nright; unfolder; splits; eauto.\nhahn_rewrite (wf_colE) in H0.\nhahn_rewrite (wf_colD) in H0.\nunfolder in H0; desf.\nassert ((I \u222a\u2081 T) y).\neapply IT; basic_solver.\nunfolder in *; desf.\nQed.\n\n\nEnd CO.\n\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/simhelpers/CertCOhelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.17252097607955305}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules logrel 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.\n\n(** This file contains specification side specs for macros.\n    The file contains pushz, rclear and prepstack (for now, only the macros needed by example)\n *)\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 {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {nainv: logrel_na_invs \u03a3} {cfg : cfgSG \u03a3}\n          `{MP: MachineParameters}.\n\n  (* --------------------------------------------------------------------------------- *)\n  (* --------------------------------------- PUSH ------------------------------------ *)\n  (* --------------------------------------------------------------------------------- *)\n\n  Definition pushU_z_s a1 r_stk z : iProp \u03a3 := (a1 \u21a3\u2090 pushU_z_instr r_stk z)%I.\n\n  Lemma pushU_z_spec E a1 a2 w z p g b e stk_b stk_e stk_a stk_a' :\n    isCorrectPC (inr ((p,g),b,e,a1)) \u2192\n    withinBounds ((URWLX,Directed),stk_b,stk_e,stk_a) = true \u2192\n    (a1 + 1)%a = Some a2 \u2192\n    (stk_a + 1)%a = Some stk_a' \u2192\n    nclose specN \u2286 E \u2192\n\n    spec_ctx\n    \u2217 \u2907 Seq (Instr Executable)\n    \u2217 \u25b7 pushU_z_s a1 r_stk z\n    \u2217 \u25b7 PC \u21a3\u1d63 inr ((p,g),b,e,a1)\n    \u2217 \u25b7 r_stk \u21a3\u1d63 inr ((URWLX,Directed),stk_b,stk_e,stk_a)\n    \u2217 \u25b7 stk_a \u21a3\u2090 w\n    ={E}=\u2217 \u2907 Seq (Instr Executable)\n         \u2217 PC \u21a3\u1d63 inr ((p,g),b,e,a2) \u2217 pushU_z_s a1 r_stk z \u2217\n         r_stk \u21a3\u1d63 inr ((URWLX,Directed),stk_b,stk_e,stk_a') \u2217 stk_a \u21a3\u2090 inl z.\n  Proof.\n    iIntros (Hvpc1 Hwb Hsuc Hstk Hnclose)\n            \"(#Hspec & Hj & Ha1 & HPC & Hr_stk & Hstk_a')\".\n    iMod (step_storeU_success_0_z _ [SeqCtx] with \"[$Hspec $Hj $HPC $Ha1 $Hr_stk $Hstk_a']\")\n      as \"(Hj & HPC & Ha1 & Hr_stk & Hstk_a)\";\n      [apply decode_encode_instrW_inv|eauto..].\n    iEpilogue_s.\n    iFrame. 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/push_pop_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.33458942798284697, "lm_q1q2_score": 0.17252097265832758}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmac_drbg.\nRequire Import spec_hmac_drbg.\n\nLemma sublist_app_exact1:\n  forall X (A B: list X), sublist 0 (Zlength A) (A ++ B) = A.\nProof.\n  intros.\n  pose proof (Zlength_nonneg A).\n  rewrite sublist_app1; try omega.\n  rewrite sublist_same; auto.\nQed.\n\nLemma sublist_app_exact2:\n  forall X (A B: list X), sublist (Zlength A) (Zlength A + Zlength B) (A ++ B) = B.\nProof.\n  intros.\n  pose proof (Zlength_nonneg A).\n  pose proof (Zlength_nonneg B).\n  rewrite sublist_app2; try omega.\n  rewrite sublist_same; auto; omega.\nQed.\n\nLemma isbyteZ_app: forall A B, Forall general_lemmas.isbyteZ A -> Forall general_lemmas.isbyteZ B -> Forall general_lemmas.isbyteZ (A ++ B).\nProof.\n  intros A B HA HB.\n  induction A as [|hdA tlA].\n  simpl; assumption.\n  simpl. inversion HA. constructor.\n  assumption.\n  apply IHtlA.\n  assumption.\nQed.\n\nCheck data_at_valid_ptr.\nLemma data_at_weak_valid_ptr: forall (sh : Share.t) (t : type) (v : reptype t) (p : val),\n       sepalg.nonidentity sh ->\n       sizeof cenv_cs t >= 0 -> data_at sh t v p |-- weak_valid_pointer p.\nProof.\nAdmitted.\nHint Resolve data_at_weak_valid_ptr: valid_pointer.\n\nLemma data_at_complete_split:\n  forall A B lengthA lengthB AB length p offset sh,\n    field_compatible (tarray tuchar (Zlength A + Zlength B)) [] p ->\n    lengthA = Zlength A ->\n    lengthB = Zlength B ->\n    length = lengthA + lengthB ->\n    offset = lengthA ->\n    AB = A ++ B ->\n    (data_at sh (tarray tuchar length) (AB) p) = (data_at sh (tarray tuchar lengthA) A p) * (data_at sh (tarray tuchar lengthB) B (offset_val (Int.repr offset) p)).\nProof.\n  intros until sh.\n  intros Hfield.\n  intros; subst.\n  pose proof (Zlength_nonneg A).\n  pose proof (Zlength_nonneg B).\n  assert (Hisptr: isptr p) by (destruct Hfield; assumption).\n  destruct p; try solve [inversion Hisptr]; clear Hisptr.\n  unfold tarray.\n  rewrite split2_data_at_Tarray_tuchar with (n1:=Zlength A); [|split; omega|rewrite Zlength_app; reflexivity].\n  rewrite sublist_app_exact1, sublist_app_exact2.\n  replace (Zlength A + Zlength B - Zlength A) with (Zlength B) by omega.\n  replace (field_address0 (Tarray tuchar (Zlength A + Zlength B) noattr) [ArraySubsc (Zlength A)] (Vptr b i)) with (Vptr b (Int.add i (Int.repr (Zlength A)))).\n  reflexivity.\n  rewrite field_address0_offset.\n  simpl. replace (0 + 1 * Zlength A) with (Zlength A) by omega. reflexivity.\n  destruct Hfield as [Hfield1 [Hfield2 [Hfield3 [Hfield4 [Hfield5 [Hfield6 [Hfield7 Hfield8]]]]]]].\n  unfold field_compatible0; repeat split; try assumption; auto; omega.\nQed.\n\nLemma body_hmac_drbg_reseed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs \n       f_mbedtls_hmac_drbg_reseed hmac_drbg_reseed_spec.\nProof.\n  start_function.\n  \n  name ctx' _ctx.\n  name add_len' _len.\n  name additional' _additional.\n\n  rename lvar0 into seed.\n  destruct initial_state_abs.\n  destruct initial_state as [md_ctx' [V' [reseed_counter' [entropy_len' [prediction_resistance' reseed_interval']]]]].\n  unfold hmac256drbg_relate.\n  normalize.\n\n  (* entropy_len = ctx->entropy_len *)\n  forward.\n\n  remember (if zlt 256 add_len then true else false) as add_len_too_high.\n\n  (* if (len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||\n        entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) *)\n  forward_if (PROP  ()\n      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      temp 146%positive (Val.of_bool add_len_too_high);\n      gvar sha._K256 kv)\n      SEP  (data_at_ Tsh (tarray tuchar 384) seed;\n      data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents))\n        additional;\n      data_at Tsh t_struct_hmac256drbg_context_st\n        (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))) ctx;\n      md_full key md_ctx';\n      data_at Tsh t_struct_mbedtls_md_info info_contents\n        (hmac256drbgstate_md_info_pointer\n           (md_ctx',\n           (map Vint (map Int.repr V),\n           (Vint (Int.repr reseed_counter),\n           (Vint (Int.repr entropy_len),\n           (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))));\n      Stream s; spec_sha.K_vector kv)\n  ).\n  {\n    rewrite zlt_true in Heqadd_len_too_high by assumption.\n    forward.\n    entailer!.    \n  }\n  {\n    rewrite zlt_false in Heqadd_len_too_high by assumption.\n    forward.\n    entailer!.\n    rewrite <- H12.\n    simpl in H2. subst entropy_len.\n    unfold Int.ltu.\n    destruct (zlt (Int.unsigned (Int.repr 384))\n                 (Int.unsigned (Int.repr (32 + Zlength contents)))).\n    rewrite Int.unsigned_repr_eq in l.\n    rewrite Zmod_small in l by auto.\n    rewrite Int.unsigned_repr_eq in l.\n    rewrite Zmod_small in l.\n    omega.\n    assert (0 <= Zlength contents <= 256) by omega.\n    rewrite hmac_pure_lemmas.IntModulus32. simpl.\n    change (Z.pow_pos 2 32) with 4294967296.\n    omega.\n    reflexivity.\n  }\n\n  forward_if (PROP  (add_len_too_high = false)\n      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP  (data_at_ Tsh (tarray tuchar 384) seed;\n      data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents))\n        additional;\n      data_at Tsh t_struct_hmac256drbg_context_st\n        (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))) ctx;\n      md_full key md_ctx';\n      data_at Tsh t_struct_mbedtls_md_info info_contents\n        (hmac256drbgstate_md_info_pointer\n           (md_ctx',\n           (map Vint (map Int.repr V),\n           (Vint (Int.repr reseed_counter),\n           (Vint (Int.repr entropy_len),\n           (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))));\n      Stream s; spec_sha.K_vector kv)\n  ).\n  {\n    forward.\n    unfold hmac_drbg_update_post, get_stream_result, hmac256drbg_relate.\n    Exists seed (Vint (Int.neg (Int.repr 5))).\n    rewrite andb_negb_r.\n    destruct (zlt 256 (Zlength contents)); inv Heqadd_len_too_high.\n    rewrite Z.gtb_ltb.\n    assert (Hlt: 256 <? Zlength contents = true) by (apply Z.ltb_lt; assumption).\n    rewrite Hlt.\n    unfold hmac256drbgabs_to_state.\n    entailer!.\n  }\n  {\n    forward.\n    entailer!.\n  }\n  assert_PROP (0 <= Zlength contents <= 256) as HZlength.\n  {\n    entailer!. destruct (zlt 256 (Zlength contents)); inversion H11. omega.\n  }\n\n  (* memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT ); *)\n  forward_call (Tsh, seed, 384, Int.zero).\n  {\n    rewrite data_at__memory_block.\n    change (sizeof cenv_cs (tarray tuchar 384)) with 384.\n    entailer!.\n  }\n  Intros vret; subst vret.\n\n  assert_PROP (field_compatible (tarray tuchar 384) [] seed) as Hfield by entailer!.\n  replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)\n         (list_repeat (Z.to_nat entropy_len) (Vint Int.zero)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))\n         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val (Int.repr entropy_len) seed))).\n  {\n    simpl in H2.\n    subst entropy_len.\n    entailer!.\n    apply derives_refl'; apply data_at_complete_split; auto.\n  }\n  normalize.\n\n  replace_SEP 0 (memory_block Tsh entropy_len seed).\n  {\n    entailer!.\n    simpl in H2; subst entropy_len.\n    apply data_at_memory_block.\n  }\n\n  (* get_entropy(seed, entropy_len ) *)\n  forward_call (Tsh, s, seed, entropy_len).\n  {\n    simpl in H2; subst entropy_len.\n    auto.\n  }\n  Intros vret.\n\n  (* if( get_entropy(seed, entropy_len ) != 0 ) *)\n  forward_if (\n      PROP  (vret=Vzero)\n      LOCAL  (temp 147%positive vret;\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP \n      (Stream\n         (get_stream_result\n            (entropy.get_entropy 0 entropy_len entropy_len false s));\n      match entropy.ENTROPY.get_bytes (Z.to_nat entropy_len) s with\n      | entropy.ENTROPY.success bytes _ =>\n          data_at Tsh (tarray tuchar entropy_len)\n            (map Vint (map Int.repr bytes)) seed\n      | entropy.ENTROPY.error _ _ => memory_block Tsh entropy_len seed\n      end;\n      data_at Tsh (tarray tuchar (384 - entropy_len))\n        (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))\n        (offset_val (Int.repr entropy_len) seed);\n      data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents))\n        additional;\n      data_at Tsh t_struct_hmac256drbg_context_st\n        (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))) ctx;\n      md_full key md_ctx';\n      data_at Tsh t_struct_mbedtls_md_info info_contents\n        (hmac256drbgstate_md_info_pointer\n           (md_ctx',\n           (map Vint (map Int.repr V),\n           (Vint (Int.repr reseed_counter),\n           (Vint (Int.repr entropy_len),\n           (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))));\n      spec_sha.K_vector kv)\n  ).\n  {\n    (* != 0 case *)\n    forward.\n    unfold hmac_drbg_update_post.\n    Exists seed (Vint (Int.neg (Int.repr (9)))).\n    unfold entropy.get_entropy in *.\n    destruct (entropy.ENTROPY.get_bytes (Z.to_nat entropy_len) s).\n    {\n      (* contradiction. cannot be a success *)\n      hnf in H11.\n      inv H11.\n      inversion H12.\n    }\n    rewrite andb_negb_r.\n    destruct (zlt 256 (Zlength contents)); inv Heqadd_len_too_high.\n    rewrite Z.gtb_ltb.\n    assert (Hlt: 256 <? Zlength contents = false) by (apply Z.ltb_nlt; assumption).\n    rewrite Hlt.\n    unfold hmac256drbg_relate, get_stream_result.\n    rewrite data_at__memory_block.\n    unfold hmac256drbgabs_to_state.\n    entailer!.    \n    eapply derives_trans. apply sepcon_derives; [apply derives_refl | apply data_at_memory_block].\n    apply derives_refl'.\n    destruct seed; inv Pseed.\n    simpl.\n    rewrite <- repr_unsigned with (i:=i).\n    simpl in H2; subst entropy_len.\n    change (1 * Z.max 0 (384 - 32))%Z with 352.\n    rewrite add_repr.\n    rewrite <- memory_block_split; auto.\n    clear - H14. rename H14 into Hlvar.\n    unfold lvar in Hlvar; unfold size_compatible in Hlvar.\n    destruct (Map.get (ve_of rho) _seed); try solve [inversion Hlvar].\n    destruct p. destruct (eqb_type (tarray tuchar 384) t); try solve [inversion Hlvar].\n    destruct Hlvar as [Hblock Hsize].\n    simpl in Hsize.\n    assert (Int.unsigned i >= 0) by (pose proof (Int.unsigned_range i); omega).\n    omega.\n  }\n  {\n    forward.\n    entailer!.\n    replace _id with Int.zero; [reflexivity|].\n    clear - H12. rename H12 into Hid.\n    pose proof (negb_sym (Int.eq _id (Int.repr 0)) false).\n    symmetry in Hid; apply H in Hid.\n    simpl in Hid.\n    symmetry; apply binop_lemmas2.int_eq_true. \n    auto.\n  }\n\n  (* now that we know entropy call succeeded, use that fact to simplify the SEP clause *)\n  remember (entropy.ENTROPY.get_bytes (Z.to_nat entropy_len) s) as entropy_result.\n  unfold entropy.get_entropy in H11;\n  rewrite <- Heqentropy_result in H11;\n  destruct entropy_result; [|\n  normalize;\n  simpl in H11; destruct e; [inversion H11 |\n  assert (contra: False) by (apply H11; reflexivity); inversion contra]\n  ].\n\n  rename l into entropy_bytes.\n\n  assert (Hentropy_bytes_length: Zlength (map Vint (map Int.repr entropy_bytes)) = 32).\n  {\n    repeat rewrite Zlength_map.\n    eapply entropy.ENTROPY.get_bytes_Zlength.\n    omega.\n    simpl in H2; subst entropy_len.\n    eassumption.\n  }\n  \n  gather_SEP 1 2.\n  replace_SEP 0 (data_at Tsh (tarray tuchar 384)\n         ((map Vint\n            (map Int.repr entropy_bytes)) ++ (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))) seed).\n  {\n    simpl in H2.\n    subst entropy_len.\n    entailer!.\n    apply derives_refl'; symmetry; apply data_at_complete_split; auto.\n    replace (Zlength (map Vint (map Int.repr entropy_bytes))) with 32 by assumption.\n    auto.\n  }\n\n  (* seedlen = entropy_len; *)\n  forward.\n\n  remember (if eq_dec additional nullval then false else if eq_dec add_len 0 then false else true) as non_empty_additional.\n\n  (* if additional != null *)\n  forward_if (\n      PROP  ()\n      LOCAL  (temp _seedlen (Vint (Int.repr entropy_len));\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      temp 148%positive (Val.of_bool non_empty_additional);\n      gvar sha._K256 kv)\n      SEP  (\n        data_at Tsh (tarray tuchar 384)\n         (map Vint (map Int.repr entropy_bytes) ++\n          list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) seed;\n        Stream\n        (get_stream_result\n           (entropy.get_entropy 0 entropy_len entropy_len false s));\n      data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents))\n        additional;\n      data_at Tsh t_struct_hmac256drbg_context_st\n        (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))) ctx;\n      md_full key md_ctx';\n      data_at Tsh t_struct_mbedtls_md_info info_contents\n        (hmac256drbgstate_md_info_pointer\n           (md_ctx',\n           (map Vint (map Int.repr V),\n           (Vint (Int.repr reseed_counter),\n           (Vint (Int.repr entropy_len),\n           (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))));\n      spec_sha.K_vector kv)\n  ).\n  {\n    (* TODO this should be easy with weakly valid pointer *)\n    unfold denote_tc_comparable.\n    assert_PROP (isptr additional) as Hisptr by entailer!. destruct additional; try solve [inversion Hisptr]; clear Hisptr.\n    entailer!.\n    admit.\n  }\n  {\n    forward.\n    entailer!.\n    rewrite <- H14.\n    destruct (eq_dec additional' nullval) as [additional_pos | additional_neg].\n    subst additional'; assert (contra: False) by (apply H12; reflexivity); inversion contra.\n    destruct (eq_dec (Zlength contents) 0) as [Zlength_pos | Zlength_neg].\n    rewrite Zlength_pos. reflexivity.\n    rewrite Int.eq_false. reflexivity.\n    intros contra.\n    apply repr_inj_unsigned in contra; omega.\n  }\n  {\n    forward.\n    entailer!.\n    destruct (eq_dec nullval nullval).\n    reflexivity.\n    assert (contra: False) by auto; inversion contra.\n  }\n\n  forward_if (\n      PROP  ()\n      LOCAL  (temp _seedlen (Vint (Int.repr (entropy_len + Zlength contents)));\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP \n      (data_at Tsh (tarray tuchar 384)\n         (map Vint\n            (map Int.repr entropy_bytes) ++ (map Vint (map Int.repr contents)) ++\n          list_repeat (Z.to_nat (384 - entropy_len - Zlength contents)) (Vint Int.zero)) seed;\n      Stream\n     (get_stream_result\n        (entropy.get_entropy 0 entropy_len entropy_len false s));\n      data_at Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents))\n        additional;\n      data_at Tsh t_struct_hmac256drbg_context_st\n        (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))) ctx;\n      md_full key md_ctx';\n      data_at Tsh t_struct_mbedtls_md_info info_contents\n        (hmac256drbgstate_md_info_pointer\n           (md_ctx',\n           (map Vint (map Int.repr V),\n           (Vint (Int.repr reseed_counter),\n           (Vint (Int.repr entropy_len),\n           (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))));\n      spec_sha.K_vector kv)\n  ).\n  {\n    replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)\n         (map Vint\n            (map Int.repr entropy_bytes)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))\n         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val (Int.repr entropy_len) seed))).\n    {\n      entailer!.\n      simpl in H2.\n      subst entropy_len.\n      replace (384 - 32) with 352 by omega.\n      apply derives_refl'; apply data_at_complete_split; auto.\n      rewrite Hentropy_bytes_length.\n      auto.\n    }\n    normalize.\n    assert_PROP (isptr seed) as Hisptr by entailer!. destruct seed; try solve [inversion Hisptr]; change (offset_val (Int.repr entropy_len) (Vptr b i)) with (Vptr b (Int.add i (Int.repr entropy_len))).\n    assert_PROP (field_compatible (Tarray tuchar (384 - entropy_len) noattr) \n          [] (Vptr b (Int.add i (Int.repr entropy_len)))) by entailer!.\n    replace_SEP 1 ((data_at Tsh (tarray tuchar (Zlength contents))\n         (list_repeat (Z.to_nat (Zlength contents)) (Vint Int.zero)) (Vptr b (Int.add i (Int.repr entropy_len)))) * (data_at Tsh (tarray tuchar (384 - entropy_len - Zlength contents))\n         (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents)) (Vint Int.zero)) (offset_val (Int.repr (Zlength contents)) (Vptr b (Int.add i (Int.repr entropy_len)))))).\n    {\n      simpl in H2; subst entropy_len.\n      replace (384 - 32) with 352 by omega.\n      remember (Vptr b (Int.add i (Int.repr 32))) as seed'.\n      clear Heqseed'.\n      entailer!.\n      replace (length contents) with (Z.to_nat (Zlength contents)) by\n        (rewrite Zlength_correct; apply Nat2Z.id).\n      apply derives_refl'; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto.\n      {\n        replace (Zlength contents + (352 - Zlength contents)) with (384 - 32) by omega.\n        assumption.\n      }\n      {\n        rewrite list_repeat_app.\n        rewrite <- Z2Nat.inj_add; try omega.\n        replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.\n        reflexivity.\n      }\n    }\n    normalize.\n    replace_SEP 0 (memory_block Tsh (Zlength contents) (Vptr b (Int.add i (Int.repr entropy_len)))).\n    entailer!. replace (Zlength contents) with (sizeof cenv_cs (tarray tuchar (Zlength contents))) at 2. apply data_at_memory_block. simpl. rewrite Zmax0r by omega. omega.\n    forward_call ((Tsh, Tsh), (Vptr b (Int.add i (Int.repr entropy_len))), additional, Zlength contents, map Int.repr contents).\n    {\n      (* type checking *)\n      unfold lvar in H15.\n      unfold eval_var.\n      destruct (Map.get (ve_of rho) _seed); [|inversion H15].\n      destruct p.\n      destruct (eqb_type (tarray tuchar 384)); [|inversion H15].\n      simpl. constructor.\n    }\n    {\n      (* match up function parameter *)\n      simpl in H2; rewrite H2.\n      entailer!.\n    }\n    {\n      (* match up SEP clauses *)\n      change (fst (Tsh, Tsh)) with Tsh;\n      change (snd (Tsh, Tsh)) with Tsh.\n      change (@data_at spec_sha.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional) with (@data_at hmac_drbg_compspecs.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional).\n      rewrite H1.\n      cancel.\n    }\n    {\n      (* prove the PROP clauses *)\n      repeat split; auto; omega.\n    }\n    Intros memcpy_vret. subst memcpy_vret.\n    forward.\n    change (fst (Tsh, Tsh)) with Tsh;\n    change (snd (Tsh, Tsh)) with Tsh.\n    change (@data_at spec_sha.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional) with (@data_at hmac_drbg_compspecs.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional).\n    gather_SEP 1 2.\n    replace_SEP 0 (data_at Tsh (tarray tuchar (384 - entropy_len)) ((map Vint (map Int.repr contents)) ++ (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents)) (Vint Int.zero))) (Vptr b (Int.add i (Int.repr entropy_len)))).\n    {\n      simpl in H2; subst entropy_len.\n      replace (384 - 32) with 352 by omega.\n      remember (Vptr b (Int.add i (Int.repr 32))) as seed'.\n      clear Heqseed'.\n      entailer!.\n      apply derives_refl'; symmetry; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto.\n      change ((fix map (l : list int) : list val :=\n               match l with\n               | [] => []\n               | a :: t => Vint a :: map t\n               end) (map Int.repr contents)) with (map Vint (map Int.repr contents)).\n      repeat rewrite Zlength_map.\n      replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.\n      assumption.\n    }\n    change (Vptr b (Int.add i (Int.repr entropy_len))) with (offset_val (Int.repr entropy_len) (Vptr b i)). remember (Vptr b i) as seed; clear Heqseed.\n    gather_SEP 2 0.\n    replace_SEP 0 (data_at Tsh (tarray tuchar 384) ((map Vint\n         (map Int.repr entropy_bytes)) ++ (map Vint (map Int.repr contents) ++\n       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))\n         (Vint Int.zero))) seed).\n    {\n      simpl in H2;\n      subst entropy_len.\n      replace (384 - 32) with 352 by omega.\n      entailer!.\n      apply derives_refl'; symmetry; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto.\n      rewrite Hentropy_bytes_length.\n      rewrite Zlength_app; rewrite Zlength_list_repeat; repeat rewrite Zlength_map; try omega.\n      replace (32 +\n         (Zlength contents + (352 - Zlength contents))) with 384 by omega.\n      assumption.\n    }\n    entailer!.\n  }\n  {\n    forward.\n    assert_PROP (contents = []).\n    {\n      destruct (eq_dec additional nullval). entailer!. destruct H20 as [contra H20']; inversion contra.\n      destruct (eq_dec add_len 0). entailer!. destruct contents; [reflexivity|]. rewrite Zlength_correct in e; simpl in e. inversion e.\n      rewrite H12 in Heqnon_empty_additional. inversion Heqnon_empty_additional.\n    }\n    subst contents.\n    change (Zlength []) with 0.\n    replace (384 - entropy_len - 0) with (384 - entropy_len) by omega.\n    entailer!.\n  }\n\n  replace_SEP 0 (\n    (data_at Tsh (tarray tuchar (entropy_len + Zlength contents)) (map Vint\n            (map Int.repr entropy_bytes) ++\n            map Vint (map Int.repr contents)) seed) *\n    (data_at Tsh (tarray tuchar (384 - (entropy_len + Zlength contents))) (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))\n            (Vint Int.zero)) (offset_val (Int.repr (entropy_len + Zlength contents)) seed))\n      ).\n  {\n    simpl in H2; subst entropy_len.\n    replace (384 - (32 + Zlength contents)) with (352 - Zlength contents) by omega.\n    replace (384 - 32) with 352 by omega.\n    rewrite app_assoc.\n    entailer!.\n    apply derives_refl'; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto; rewrite Zlength_app; rewrite Hentropy_bytes_length; repeat rewrite Zlength_map; auto.\n    replace (32 + Zlength contents + (352 - Zlength contents)) with 384 by omega.\n    assumption.\n  }\n  normalize.\n\n  do 2 rewrite map_map.\n  rewrite <- map_app.\n  rewrite <- map_map.\n\n  forward_call ((entropy_bytes ++ contents), seed, (entropy_len + Zlength contents), ctx, (md_ctx',\n        (map Vint (map Int.repr V),\n        (Vint (Int.repr reseed_counter),\n        (Vint (Int.repr entropy_len),\n        (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))), (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval), kv, info_contents).\n  {\n    (* prove the SEP clauses match up *)\n    unfold hmac256drbg_relate.\n    entailer!.\n  }\n  {\n    (* prove the PROP clauses *)\n    simpl in H2; subst entropy_len.\n    rewrite int_max_unsigned_eq.\n    repeat split; try omega.\n    {\n      rewrite Zlength_app.\n      repeat rewrite Zlength_map in Hentropy_bytes_length.\n      rewrite Hentropy_bytes_length.\n      change (Z.of_nat (Z.to_nat 32)) with 32.\n      reflexivity.\n    }\n    {\n      simpl; assumption.\n    }\n    {\n      apply isbyteZ_app.\n      eapply entropy.ENTROPY.get_bytes_isbyteZ; eauto. assumption.\n    }\n  }\n  unfold hmac_drbg_update_post; normalize.\n\n  gather_SEP 3 5.\n  replace_SEP 0 (data_at Tsh (tarray tuchar 384) ((map Vint\n         (map Int.repr entropy_bytes)) ++ (map Vint (map Int.repr contents) ++\n       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))\n         (Vint Int.zero))) seed).\n  {\n    simpl in H2;\n    subst entropy_len.\n    replace (384 - 32) with 352 by omega.\n    replace (384 - (32 + Zlength contents)) with (352 - Zlength contents) by omega.\n    rewrite app_assoc.\n    rewrite map_map.\n    rewrite map_app.\n    rewrite <- map_map.\n    replace (map (fun x : Z => Vint (Int.repr x)) contents) with (map Vint (map Int.repr contents)) by (rewrite map_map; auto).\n    entailer!.\n    apply derives_refl'; symmetry; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto; rewrite Zlength_app; rewrite Hentropy_bytes_length; repeat rewrite Zlength_map; auto.\n    replace (32 + Zlength contents + (352 - Zlength contents)) with 384 by omega.\n    assumption.\n  }\n  \n  (* ctx->reseed_counter = 1; *)\n  forward.\n\n  (* return 0 *)\n  forward.\n\n  unfold hmac_drbg_update_post.\n  unfold hmac256drbgabs_to_state.\n  Exists seed (Vint (Int.repr 0)).\n  rewrite andb_negb_r.\n  assert (HcontentsLength: Zlength contents >? 256 = false).\n  {\n    rewrite Z.gtb_ltb.\n    apply Z.ltb_nlt.\n    omega.\n  }\n  rewrite HcontentsLength.\n  unfold HMAC_DRBG_update.HMAC_DRBG_update.\n  idtac.\n  replace (map (fun x : Z => Vint (Int.repr x)) contents) with (map Vint (map Int.repr contents)) by (rewrite map_map; auto).\n  unfold hmac256drbg_relate.\n  unfold get_stream_result.\n  unfold entropy.get_entropy.\n  rewrite <- Heqentropy_result.\n  assert (Hnonempty_seed: exists hdSeed tlSeed, (entropy_bytes ++ contents) = hdSeed::tlSeed).\n  {\n    remember (entropy_bytes ++ contents) as seedContents.\n    destruct seedContents as [|hdSeed tlSeed].\n    {\n      (* this case can't be true. case: seedContents = [] *)\n      simpl in H2; subst entropy_len.\n      assert (contra: Zlength (entropy_bytes ++ contents) = 0) by (rewrite <- HeqseedContents; reflexivity).\n      rewrite Zlength_app in contra.\n      repeat rewrite Zlength_map in Hentropy_bytes_length; rewrite Hentropy_bytes_length in contra.\n      omega.\n    }\n    exists hdSeed. exists tlSeed.\n    reflexivity.\n  }\n  unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_update.\n  unfold HMAC_DRBG_update.HMAC_DRBG_update.\n  destruct Hnonempty_seed as [hdSeed [tlSeed Hnonempty_seed]];\n  rewrite Hnonempty_seed.\n  entailer!.\n  split; [apply hmac_common_lemmas.HMAC_Zlength| apply hmac_common_lemmas.isbyte_hmac].\nQed.\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/verif_hmac_drbg_reseed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.17252097265832753}}
{"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(* ************************************************************ *)\t\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(**************************************************************)\t\n(* stores *)\n\nSection Stores.\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\n(* XXX kill this off *)\nInductive val: Type := mkval (t: type) (a : value): val.\n\nDefinition Heap := NatMap.t val.\nDefinition Locals := NatMap.t val.\n\nEnd Stores.\n\n(**************************************************************)\t\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| 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 (mkval t 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.\n\nEnd Expressions.\n\n(**************************************************************)\t\n(* statements *)\n\nSection Statements.\n\n(* call, return, and start appear at higher levels *)\nInductive StmtSteps: Heap -> Locals -> stmt -> 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) h (NatMap.add id (mkval type a) loc) s_skip\n| step_load: forall h loc type lid e hid heapnum a,\n     (* XXX this is wrong (needs to handle heapnum) *)\n     ExprYields type loc e (v_addr (mkaddr type hid heapnum)) ->\n     NatMap.find hid h = Some (mkval type a) ->\n     StmtSteps h loc (s_load (mkvar type lid) e) h (NatMap.add lid (mkval type a) loc) s_skip\n| step_store: forall h loc type lid e hid heapnum a,\n     (* XXX this is wrong (needs to handle heapnum) *)\n     ExprYields type loc e a ->\n     ExprYields type loc (e_read (mkvar type lid)) (v_addr (mkaddr type hid heapnum)) ->\n     StmtSteps h loc (s_store (mkvar type lid) e) (NatMap.add hid (mkval type a) h) loc s_skip\n| step_scope: forall h loc s h' loc' s',\n     StmtSteps h loc s h' loc' s' ->\n     StmtSteps h loc (s_scope s) h' loc' (s_scope s')\n| step_endscope: forall h loc,\n     StmtSteps h loc (s_scope s_skip) 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 (s_scope 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 (s_scope 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 (s_scope 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_local: forall h loc id type e a,\n     NatMap.find id loc = None ->\n     ExprYields type loc e a ->\n     StmtSteps h loc (s_local (mkvar type id) e) h (NatMap.add id (mkval type a) loc) s_skip\n(* XXX\n| step_getlock: ?\n| step_putlock: ?\n*)\n.\n\nEnd Statements.\n\n(**************************************************************)\n(* stacks *)\n\nSection Stacks.\n\nInductive Stack: Type :=\n| stack_empty: Stack\n| stack_pending: forall (t : type), Locals -> var -> Stack -> Stack\n.\n\nInductive CallSteps: Stack -> Locals -> stmt ->\n                     Stack -> Locals -> stmt -> Prop :=\n| call_steps: forall loc stk retid rt paramid pt body arg argval,\n     ExprYields pt loc arg argval ->\n     CallSteps stk loc (s_call (mkvar rt retid)\n                               (mkproc rt (mkvar pt paramid) body)\n                               arg)\n               (stack_pending rt loc (mkvar rt retid) stk)\n               (NatMap.add paramid (mkval pt argval) (NatMap.empty val))\n               body\n.\n\nInductive ReturnSteps: Stack -> Locals -> stmt ->\n                        Stack -> Locals -> stmt -> Prop :=\n| return_steps: forall loc loc' rt retid stk ret retval,\n     ExprYields rt loc ret retval ->\n     ReturnSteps (stack_pending rt loc' (mkvar rt retid) stk) loc\n                                                              (s_return ret)\n                 stk loc' (s_assign (mkvar rt retid) (e_value rt retval))\n.\n\nEnd Stacks.\n\n(**************************************************************)\t\n(* threads *)\n\nSection Threads.\n\nInductive Thread: Type :=\n| thread: Locals -> Stack -> stmt -> Thread\n.\n\nInductive ThreadSteps: Heap -> Thread -> Heap -> Thread -> Prop :=\n| thread_steps_stmt: forall h loc stk s h' loc' s',\n     StmtSteps h loc s h' loc' s' ->\n     ThreadSteps h (thread loc stk s) h' (thread loc' stk s')\n| thread_steps_call_final: forall h loc stk s loc' stk' s',\n     CallSteps stk loc s stk' loc' s' ->\n     ThreadSteps h (thread loc stk s)\n\t\t h (thread loc' stk' s')\n| thread_steps_call_seq: forall h loc stk s s2 loc' stk' s',\n     CallSteps stk loc s stk' loc' s' ->\n     ThreadSteps h (thread loc stk (s_seq s s2))\n\t\t h (thread loc' stk' (s_seq s' s2))\n| thread_steps_return_final: forall h loc stk s loc' stk' s',\n     ReturnSteps stk loc s stk' loc' s' ->\n     ThreadSteps h (thread loc stk s)\n\t\t h (thread loc' stk' s')\n| thread_steps_return_seq: forall h loc stk s s2 loc' stk' s',\n     ReturnSteps stk loc s stk' loc' s' ->\n     ThreadSteps h (thread loc stk (s_seq s s2))\n\t\t h (thread loc' stk' s')\n.\n\n(* this is its own thing because it needs a different signature *)\nInductive ThreadStepsStart: Thread -> Thread -> Thread -> Prop :=\n| thread_steps_start: forall loc stk pt paramid body arg argval,\n     ExprYields pt loc arg argval ->\n     ThreadStepsStart\n\t(thread loc stk (s_start (mkproc t_unit (mkvar pt paramid) body) arg))\n        (thread loc stk s_skip)\n\t(thread (NatMap.add paramid (mkval pt argval) (NatMap.empty val)) stack_empty body)\n.\n\nEnd Threads.\n\n(**************************************************************)\t\n(* machines *)\n\nSection Machines.\n\nInductive Machine: Type :=\n| machine: Heap -> list Thread -> Machine\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\t\t  (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\t\t  (machine h (ts1 ++ [t1; t2] ++ 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/src/semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.17231907171283958}}
{"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.\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. Opaque Snuffle.Snuffle.\nRequire Import tweetnacl20140427.verif_crypto_stream_salsa20_xor.\n\nLemma crypto_stream_salsa20_tweet_ok: semax_body SalsaVarSpecs (*(crypto_stream_salsa20_xor_spec::*)SalsaFunSpecs\n      f_crypto_stream_salsa20_tweet\n      f_crypto_stream_salsa20_tweet_spec.\nProof.\nstart_function.\nabbreviate_semax.\nforward_call (c, k, nullval, nonce, d, Nonce, K, list_repeat (Z.to_nat (Int64.unsigned d)) Byte.zero, SV).\n{ simpl; entailer!. }\napply Zlength_list_repeat. apply Int64.unsigned_range.\n\nforward.\nQed.\n\n(*The crypto_stream function*)\nLemma crypto_stream_xsalsa20_tweet_ok:\n      semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_stream_xsalsa20_tweet\n      f_crypto_stream_xsalsa20_tweet_spec.\nProof.\nstart_function. unfold data_at_, field_at_. simpl.\nunfold Sigma_vector.\nforward_call (SV, k, nonce, v_s,\n        default_val (tarray tuchar 32),\n        ((Nonce, SIGMA), K)).\n{ unfold CoreInSEP, SByte. cancel. }\nIntros v.\nunfold CoreInSEP, SByte, Sigma_vector. normalize.\nassert_PROP (isptr nonce) as PN by entailer!.\nassert (exists HSalsaRes, hSalsaOut v =\n   match HSalsaRes with (q1, q2) =>\n     SixteenByte2ValList q1 ++ SixteenByte2ValList q2\n   end).\n{ unfold hSalsaOut.\n  exists ((littleendian_invert (Znth 0 v Int.zero),\n           littleendian_invert (Znth 5 v Int.zero),\n           littleendian_invert (Znth 10 v Int.zero),\n           littleendian_invert (Znth 15 v Int.zero)),\n          (littleendian_invert (Znth 6 v Int.zero),\n           littleendian_invert (Znth 7 v Int.zero),\n           littleendian_invert (Znth 8 v Int.zero),\n           littleendian_invert (Znth 9 v Int.zero))).\n  do 2 rewrite SixteenByte2ValList_char. repeat rewrite <- app_assoc. trivial. }\ndestruct H0 as [HSalsaRes HS]. rewrite HS.\nforward_call (c, v_s, offset_val 16 nonce, d, Nonce2, HSalsaRes, SV).\n{ unfold SByte, Sigma_vector, ThirtyTwoByte.\n  destruct HSalsaRes as [q1 q2]. cancel.\n  unfold data_at_. cancel. }\nforward.\nunfold ThirtyTwoByte. entailer.\n Exists HSalsaRes. entailer. cancel.\ndestruct HSalsaRes as [q1 q2]. cancel.\nQed.\n\n(*The crypto_stream_xor function*)\nLemma crypto_stream_xsalsa20_tweet_xor_ok:\n      semax_body SalsaVarSpecs SalsaFunSpecs\n      f_crypto_stream_xsalsa20_tweet_xor\n      f_crypto_stream_xsalsa20_tweet_xor_spec.\nProof.\nstart_function.\nrename v_s into s. rename H into mLen. unfold data_at_, field_at_. simpl.\nunfold Sigma_vector.\nforward_call (SV, k, nonce, s,\n        default_val (tarray tuchar 32),\n        ((Nonce, SIGMA), K)).\n{ unfold CoreInSEP, SByte. cancel. }\nIntros v.\nunfold CoreInSEP, SByte, Sigma_vector. normalize.\nassert_PROP (isptr nonce) as PN by entailer!.\nassert (exists HSalsaRes, hSalsaOut v =\n   match HSalsaRes with (q1, q2) =>\n     SixteenByte2ValList q1 ++ SixteenByte2ValList q2\n   end).\n{ exists ((littleendian_invert (Znth 0 v Int.zero),\n           littleendian_invert (Znth 5 v Int.zero),\n           littleendian_invert (Znth 10 v Int.zero),\n           littleendian_invert (Znth 15 v Int.zero)),\n          (littleendian_invert (Znth 6 v Int.zero),\n           littleendian_invert (Znth 7 v Int.zero),\n           littleendian_invert (Znth 8 v Int.zero),\n           littleendian_invert (Znth 9 v Int.zero))).\n  do 2 rewrite SixteenByte2ValList_char. repeat rewrite <- app_assoc. trivial. }\ndestruct H0 as [[q1 q2] HS]. rewrite HS. \nforward_call (c, s, m, offset_val 16 nonce, d, Nonce2, (q1,q2), mCont, SV).\n{ unfold SByte, Sigma_vector, data_at_. unfold ThirtyTwoByte at 2. cancel. }\nforward.\nExists (q1, q2). unfold ThirtyTwoByte. entailer!.\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/tweetnacl20140427/verif_crypto_stream.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1722708591215669}}
{"text": "Require Import Program.Basics Lia.\nFrom hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic Language.\nFrom imm Require Import Events Execution TraversalConfig Traversal\n     Prog ProgToExecution ProgToExecutionProperties imm_s imm_s_hb\n     SimState\n     CombRelations SimTraversal.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import EventStructure.\nRequire Import Consistency.\nRequire Import BasicStep.\nRequire Import EventToAction.\nRequire Import LblStep.\nRequire Import ProgES.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection SimRelCont.\n  Variable prog : Prog.t.\n  Variable S : ES.t.\n  Variable sc : relation actid.\n\n  Notation \"'SE'\" := S.(ES.acts_set).\n  Notation \"'SEinit'\" := S.(ES.acts_init_set).\n  Notation \"'SEninit'\" := S.(ES.acts_ninit_set).\n\n  Notation \"'Stid'\" := (S.(ES.tid)).\n  Notation \"'Slab'\" := (S.(ES.lab)).\n  Notation \"'Sloc'\" := (loc S.(ES.lab)).\n\n  Notation \"'K'\" := (ES.cont_set S) (at level 1).\n\n  Notation \"'STid' t\" := (fun x => Stid x = t) (at level 1).\n\n  Notation \"'SR'\" := (fun a => is_true (is_r Slab a)).\n  Notation \"'SW'\" := (fun a => is_true (is_w Slab a)).\n  Notation \"'SF'\" := (fun a => is_true (is_f Slab a)).\n  Notation \"'SRel'\" := (fun a => is_true (is_rel Slab a)).\n  Notation \"'SAcq'\" := (fun a => is_true (is_acq Slab a)).\n\n  Notation \"'Ssb'\" := (S.(ES.sb)).\n  Notation \"'Scf'\" := (S.(ES.cf)).\n  Notation \"'Srmw'\" := (S.(ES.rmw)).\n\n  Notation \"'thread_syntax' t\"  :=\n    (Language.syntax (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_st' t\" :=\n    (Language.state (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_init_st' t\" :=\n    (Language.init (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_cont_st' t\" :=\n    (fun st => existT _ (thread_lts t) st) (at level 10, only parsing).\n\n  Record simrel_cont :=\n    { contlang : forall k lang (state : lang.(Language.state))\n                        (INK : K (k, existT _ lang state)),\n        lang = thread_lts (ES.cont_thread S k);\n\n      contwf : forall k (state : thread_st (ES.cont_thread S k))\n                      (INK : K (k, thread_cont_st (ES.cont_thread S k) state)),\n          wf_thread_state (ES.cont_thread S k) state;\n\n      contstable : forall k (state : thread_st (ES.cont_thread S k))\n                          (INK : K (k, thread_cont_st (ES.cont_thread S k) state)),\n          stable_state state;\n\n      contrun : forall thread (lprog : thread_syntax thread)\n                       (INPROG : IdentMap.find thread prog = Some lprog),\n          exists (state : thread_st thread),\n            \u27ea INK : K (CInit thread, thread_cont_st thread state) \u27eb /\\\n            \u27ea INITST : (istep thread [])\uff0a (thread_init_st thread lprog) state\u27eb;\n\n      contreach :\n        forall k (state : thread_st (ES.cont_thread S k))\n               (lprog : thread_syntax (ES.cont_thread S k))\n               (INPROG : IdentMap.find (ES.cont_thread S k) prog =\n                         Some lprog)\n               (INK : K (k, thread_cont_st (ES.cont_thread S k) state)),\n          (step (ES.cont_thread S k))\uff0a\n            (thread_init_st (ES.cont_thread S k) lprog)\n            state;\n\n      continit : forall thread (state : thread_st thread)\n                        (INKi : K (CInit thread, thread_cont_st thread state)),\n          state.(eindex) = 0;\n\n      contseqn : forall e (state : thread_st (Stid e))\n                        (INKe : K (CEvent e, thread_cont_st (Stid e) state)),\n          state.(eindex) = 1 + ES.seqn S e;\n\n      (* contpc : forall e (state : thread_st (Stid e)) *)\n      (*                 (XE : X e) *)\n      (*                 (PC : pc (Stid e) (e2a S e)) *)\n      (*                 (INK : K S (CEvent e, thread_cont_st (Stid e) state)), *)\n      (*     @sim_state G sim_normal C (Stid e) state; *)\n\n      (* continitstate : *)\n      (*   forall thread (state : thread_st thread) *)\n      (*          (CEMP : C \u2229\u2081 GTid thread \u2286\u2081 \u2205) *)\n      (*          (INK : K S (CInit thread, thread_cont_st thread state)), *)\n      (*     @sim_state G sim_normal C thread state; *)\n\n    }.\n\n  Section SimRelContProps.\n\n    Variable WF : ES.Wf S.\n    Variable SRK : simrel_cont.\n\n    Lemma simrel_cont_adjacent_inK' k k' e e'\n          (st : thread_st (ES.cont_thread S k))\n          (KK : K (k, existT _ (thread_lts (ES.cont_thread S k)) st))\n          (ADJ : ES.cont_adjacent S k k' e e') :\n      exists st', K (k', existT _ (thread_lts (ES.cont_thread S k)) st').\n    Proof.\n      (* a piece of dark magic *)\n      edestruct ES.cont_adjacent_inK'\n        as [c KK'']; eauto.\n      assert\n        (exists st', c = existT _ (thread_lts (ES.cont_thread S k)) st')\n        as [st' EQc]; [|subst c; eauto].\n      arewrite (thread_lts (ES.cont_thread S k) = projT1 c).\n      2 : exists (projT2 c); eapply sigT_eta.\n      cdes ADJ.\n      rewrite kEQTID.\n      symmetry.\n      eapply contlang; eauto.\n      erewrite <- sigT_eta.\n      eapply KK''.\n    Qed.\n\n  End SimRelContProps.\n\nEnd SimRelCont.\n\nSection SimRelContLemmas.\n  Variable prog : Prog.t.\n  Variable S : ES.t.\n  Variable WF : ES.Wf S.\n  Variable SRK : simrel_cont prog S.\n\n  Notation \"'SE' S\" := S.(ES.acts_set) (at level 10).\n  Notation \"'SEinit' S\" := S.(ES.acts_init_set) (at level 10).\n  Notation \"'SEninit' S\" := S.(ES.acts_ninit_set) (at level 10).\n  Notation \"'Stid' S\" := (S.(ES.tid)) (at level 10).\n  Notation \"'Slab' S\" := S.(ES.lab) (at level 10).\n  Notation \"'Sloc' S\" := (loc S.(ES.lab)) (at level 10).\n\n  Notation \"'K' S\" := (S.(ES.cont_set)) (at level 10).\n\n  Notation \"'Ssb' S\" := S.(ES.sb) (at level 10).\n  Notation \"'Srmw' S\" := S.(ES.rmw) (at level 10).\n\n  Notation \"'thread_syntax' t\"  :=\n    (Language.syntax (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_st' t\" :=\n    (Language.state (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_init_st' t\" :=\n    (Language.init (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_cont_st' t\" :=\n    (fun st => existT _ (thread_lts t) st) (at level 10, only parsing).\n\n  Notation \"'cont_lang'\" :=\n    (fun S k => thread_lts (ES.cont_thread S k)) (at level 10, only parsing).\n\n  Notation \"'STid'\" := (fun S t x => ES.tid S x = t) (at level 1).\n\n  Lemma kstate_instrs k (state : thread_st (ES.cont_thread S k))\n        (lprog : thread_syntax (ES.cont_thread S k))\n        (INPROG : IdentMap.find (ES.cont_thread S k) prog = Some lprog)\n        (INK : K S (k, thread_cont_st (ES.cont_thread S k) state)) :\n    lprog = instrs state.\n  Proof.\n    eapply contreach in INK; eauto.\n    apply steps_same_instrs in INK. simpls.\n  Qed.\n\n  Lemma basic_step_simrel_cont k k' e e' S'\n        (st st' : thread_st (ES.cont_thread S k))\n        (BSTEP_ : basic_step_ (cont_lang S k) k k' st st' e e' S S'):\n        (* (STCOV : C \u2229\u2081 GTid_ (ES.cont_thread S k) \u2286\u2081 acts_set st.(ProgToExecution.G)) :  *)\n    simrel_cont prog S'.\n  Proof.\n    cdes BSTEP_.\n    assert (basic_step e e' S S') as BSTEP.\n    { econstructor; eauto. }\n\n    assert (Stid S' (opt_ext e e') = ES.cont_thread S k) as TIDee.\n    { edestruct e'; simpl;\n        [eapply basic_step_tid_e' | eapply basic_step_tid_e];\n        eauto. }\n\n    assert (st'.(eindex) = 1 + ES.seqn S' (opt_ext e e')) as ST_IDX.\n    { edestruct ilbl_step_cases as [l [l' HH]]; eauto.\n      { eapply contwf; eauto. }\n      { apply STEP. }\n      edestruct HH as [EE _].\n      apply opt_to_list_app_singl in EE.\n      destruct EE as [eqLBL eqLBL'].\n      edestruct e'; simpl; unfold opt_ext.\n      { destruct HH as [_ [HH | HH]].\n        { destruct HH as [_ [_ [_ [LBL _]]]].\n          subst l'. rewrite LBL in LABEL'. exfalso. auto. }\n        destruct HH as [IDX _].\n        erewrite IDX. simpl.\n        erewrite basic_step_seqn_e'; eauto.\n        arewrite (eindex st = ES.seqn S' e); [|lia].\n        edestruct k.\n        { erewrite continit; eauto.\n          erewrite basic_step_seqn_kinit; eauto. }\n        erewrite contseqn; eauto.\n        erewrite <- basic_step_seqn_kevent; eauto. }\n      destruct HH as [_ [HH | HH]].\n      2: by desf.\n      destruct HH as [IDX _].\n      erewrite IDX. simpl.\n      edestruct k.\n      { erewrite continit; eauto.\n        erewrite basic_step_seqn_kinit; eauto. }\n      erewrite contseqn; eauto.\n      erewrite <- basic_step_seqn_kevent; eauto. }\n\n    split.\n\n    (* contlang *)\n    { intros kk lang st'' INK.\n      eapply basic_step_cont_set in INK; eauto.\n      unfold set_union in INK. destruct INK as [HA | HB].\n      { erewrite basic_step_cont_thread; eauto.\n          by eapply SRK in HA. }\n      inversion HB.\n      rewrite <- KCE.\n      erewrite basic_step_cont_thread' with (k' := k').\n      all : eauto. }\n\n    (* contwf *)\n    { intros kk st'' KK.\n      eapply basic_step_cont_set in KK; eauto.\n      unfold set_union in KK.\n      destruct KK as [KK | KK].\n      { erewrite basic_step_cont_thread; eauto.\n        apply SRK.\n        erewrite <- basic_step_cont_thread; eauto. }\n      assert (kk = CEvent (opt_ext e e')) as kkEQ.\n      { by inversion KK. }\n      rewrite <- kkEQ in *.\n      assert (ES.cont_thread S' kk = (ES.cont_thread S k)) as Hkk.\n      { by rewrite kkEQ. }\n      rewrite Hkk in *.\n      inversion KK as [HH].\n      apply inj_pair2 in HH.\n      rewrite <- HH.\n      eapply wf_thread_state_steps.\n      { eapply SRK; eauto. }\n      eapply lbl_steps_in_steps.\n      do 2 econstructor.\n      eapply STEP. }\n\n    (* contstable *)\n    { intros kk st'' KK.\n      eapply basic_step_cont_set in KK; eauto.\n      unfold set_union in KK.\n      destruct KK as [KK | KK].\n      { eapply SRK.\n        erewrite <- basic_step_cont_thread; eauto. }\n      assert (kk = CEvent (opt_ext e e')) as kkEQ.\n      { by inversion KK. }\n      rewrite <- kkEQ in *.\n      assert (ES.cont_thread S' kk = (ES.cont_thread S k)) as Hkk.\n      { by rewrite kkEQ. }\n      rewrite Hkk in *.\n      inversion KK as [HH].\n      apply inj_pair2 in HH.\n      rewrite <- HH.\n      simpls.\n      unfold ilbl_step in STEP.\n      apply seqA in STEP.\n      apply seq_eqv_r in STEP.\n      desf. }\n\n    (* contrun *)\n    { intros thread lprog INP.\n      edestruct SRK.(contrun) as [st'' [Kinit ISTEP]]; eauto.\n      eexists; split; eauto.\n      eapply basic_step_cont_set; eauto.\n      left. eauto. }\n\n    (* contreach *)\n    { ins. red in INK. rewrite CONT' in INK.\n      apply in_inv in INK. destruct INK as [INK|INK].\n      2: { assert (ES.cont_thread S' k0 = ES.cont_thread S k0) as HH.\n           { eapply basic_step_cont_thread; eauto. }\n           rewrite HH in *.\n           eapply contreach; eauto. }\n      assert (k0 = k') as YY by inv INK; rewrite YY in *.\n      assert (ES.cont_thread S' k' = ES.cont_thread S k) as BB.\n      { eapply basic_step_cont_thread'; eauto. }\n      rewrite BB in *.\n      assert (state = st'); subst.\n      { apply pair_inj in INK. destruct INK as [AA INK]; subst.\n        inv INK. }\n      apply rt_rt. exists st. split.\n      { eapply contreach; eauto. }\n      apply inclusion_t_rt.\n      eapply ilbl_step_in_steps; eauto. }\n\n    (* contseqn *)\n    { intros thread st'' KK.\n      eapply basic_step_cont_set in KK; eauto.\n      unfold set_union in KK.\n      destruct KK as [KK | KK].\n      { by eapply SRK. }\n      exfalso. inversion KK. }\n    intros x st'' KK.\n    eapply basic_step_cont_set in KK; eauto.\n    unfold set_union in KK.\n    destruct KK as [KK | KK].\n    { assert (SE S x) as SEx.\n      { eapply ES.K_inEninit; eauto. }\n      erewrite basic_step_seqn_eq_dom; eauto.\n      eapply SRK. erewrite <- basic_step_tid_eq_dom; eauto. }\n    assert (x = opt_ext e e') as xEQ.\n    { by inversion KK. }\n    rewrite xEQ, TIDee in KK.\n    inversion KK as [HST].\n    apply inj_pair2 in HST.\n    congruence.\n  Qed.\n\n  Lemma basic_step_cont_icf_dom_same_lab_u2v k k' e e' S'\n        (st st' : thread_st (ES.cont_thread S k))\n        (BSTEP_ : basic_step_ (cont_lang S k) k k' st st' e e' S S') :\n    Slab S \u25a1\u2081 ES.cont_icf_dom S k \u2286\u2081 same_label_u2v (Slab S' e).\n  Proof.\n    cdes BSTEP_.\n    arewrite (Slab S' e = lbl).\n    { rewrite LAB'.\n      rewrite updo_opt, upds; auto.\n      destruct e' as [e'|]; auto.\n      unfold opt_ext in *. subst.\n      unfolder. lia. }\n    intros l [a [kICFx EQl]].\n    edestruct ES.cont_icf_dom_cont_adjacent\n      as [k'' [a' ADJ]]; eauto.\n    edestruct simrel_cont_adjacent_inK'\n      as [st'' KK'']; eauto.\n    edestruct ES.K_adj\n      with (k := k) (k' := k'') (st' := st'')\n      as [ll [ll' [EQll [EQll' STEP']]]]; eauto.\n    red in EQll, EQll', STEP'.\n    rewrite <- EQl.\n    rewrite <- EQll.\n    eapply same_label_u2v_ilbl_step.\n    { eapply STEP. }\n    apply STEP'.\n  Qed.\n\n  Lemma basic_step_cont_icf_dom_nR_same_lab k k' e e' S'\n        (st st' : thread_st (ES.cont_thread S k))\n        (BSTEP_ : basic_step_ (cont_lang S k) k k' st st' e e' S S') :\n    Slab S \u25a1\u2081 (ES.cont_icf_dom S k \u2229\u2081 set_compl (is_r (Slab S))) \u2286\u2081 eq (Slab S' e).\n  Proof.\n    cdes BSTEP_.\n    arewrite (Slab S' e = lbl).\n    { rewrite LAB'.\n      rewrite updo_opt, upds; auto.\n      destruct e' as [e'|]; auto.\n      unfold opt_ext in *. subst.\n      unfolder. lia. }\n    intros l [a [[kICFx nR] EQl]].\n    edestruct ES.cont_icf_dom_cont_adjacent\n      as [k'' [a' ADJ]]; eauto.\n    edestruct simrel_cont_adjacent_inK'\n      as [st'' KK'']; eauto.\n    edestruct ES.K_adj\n      with (k := k) (k' := k'') (st' := st'')\n      as [ll [ll' [EQll [EQll' STEP']]]]; eauto.\n    red in EQll, EQll', STEP'.\n    rewrite <- EQl.\n    rewrite <- EQll.\n    symmetry.\n    eapply same_label_nR_ilbl_step.\n    { eapply STEP'. }\n    { apply STEP. }\n    basic_solver.\n  Qed.\n\nEnd SimRelContLemmas.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/SimRelCont.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.29421498454004374, "lm_q1q2_score": 0.172145522781124}}
{"text": "Require Import AutoSep Wrap StringOps Malloc ArrayOps Buffers Bags.\nRequire Import RelDb.\n\nSet Implicit Arguments.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\n\n(** * Iterating over matching rows of a table *)\n\nOpaque mult.\nLocal Infix \";;\" := SimpleSeq : SP_scope.\n\nSection Condition.\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 row data in this variable.\n   * in these variables. *)\n  Variables data : string.\n\n  (* Test to use in filtering rows *)\n  Variable cond : condition.\n\n  (* One field test, storing Boolean result in \"matched\" *)\n  Definition compileEquality (e : equality) : chunk :=\n    match resolve sch (fst e) with\n      | None => Fail\n      | Some offset =>\n        \"tmp\" <- data;;\n        \"ibuf\" <-* \"tmp\";;\n        \"ilen\" <-* \"tmp\" + 4;;\n\n        Assert [Al bs, Al a : A, Al rcols, Al rbs,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |]\n            * [| inputOk V (exps cond) |] * invPre a V\n            * (V data ==*> V \"ibuf\", V \"ilen\") * array (posl rcols) (V data ^+ $8)\n            * array (lenl rcols) (V data ^+ $8 ^+ $(length sch * 4)) * array8 rbs (V \"ibuf\")\n            * [| length rbs = wordToNat (V \"ilen\") |] * [| length rcols = length sch |]\n            * [| inBounds (V \"ilen\") rcols |] * [| V data <> 0 |]\n            * [| freeable (V data) (2 + length sch + length sch) |]\n            * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (length rbs) |]\n            * [| natToW offset < natToW (length (posl rcols)) |]%word\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        \"tmp\" <- data + 8;;\n        \"ipos\" <-* \"tmp\" + (4 * offset)%nat;;\n\n        Assert [Al bs, Al a : A, Al rcols, Al rbs,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |]\n            * [| inputOk V (exps cond) |] * invPre a V\n            * (V data ==*> V \"ibuf\", V \"ilen\") * array (posl rcols) (V data ^+ $8)\n            * array (lenl rcols) (V data ^+ $8 ^+ $(length sch * 4)) * array8 rbs (V \"ibuf\")\n            * [| length rbs = wordToNat (V \"ilen\") |] * [| length rcols = length sch |]\n            * [| inBounds (V \"ilen\") rcols |] * [| V data <> 0 |]\n            * [| freeable (V data) (2 + length sch + length sch) |]\n            * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (length rbs) |]\n            * [| V \"ipos\" = Array.selN (posl rcols) offset |]\n            * [| natToW offset < natToW (length (lenl rcols)) |]%word\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        \"tmp\" <- data + 8;;\n        \"tmp\" <- \"tmp\" + (length sch * 4)%nat;;\n        \"tmp\" <-* \"tmp\" + (4 * offset)%nat;;\n\n        Assert [Al bs, Al a : A, Al rcols, Al rbs,\n          PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |]\n            * [| inputOk V (exps cond) |] * invPre a V\n            * (V data ==*> V \"ibuf\", V \"ilen\") * array (posl rcols) (V data ^+ $8)\n            * array (lenl rcols) (V data ^+ $8 ^+ $(length sch * 4)) * array8 rbs (V \"ibuf\")\n            * [| length rbs = wordToNat (V \"ilen\") |] * [| length rcols = length sch |]\n            * [| inBounds (V \"ilen\") rcols |] * [| V data <> 0 |]\n            * [| freeable (V data) (2 + length sch + length sch) |]\n            * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (length rbs) |]\n            * [| V \"ipos\" = Array.selN (posl rcols) offset |]\n            * [| V \"tmp\" = Array.selN (lenl rcols) offset |]\n          POST[R] array8 bs (V \"buf\") * invPost a V R];;\n\n        match snd e with\n          | Const s =>\n            If (\"tmp\" <> String.length s) {\n              (* Field value has wrong length to match. *)\n              \"matched\" <- 0\n            } else {\n              StringEq \"ibuf\" \"ilen\" \"ipos\" \"matched\" s\n              (fun (a_bs : A * list B) V => array8 (snd a_bs) (V \"buf\")\n                * [| length (snd a_bs) = wordToNat (V \"len\") |]\n                * [| inputOk V (exps cond) |] * invPre (fst a_bs) V\n                * Ex rcols,\n                  (V data ==*> V \"ibuf\", V \"ilen\") * array (posl rcols) (V data ^+ $8)\n                  * array (lenl rcols) (V data ^+ $8 ^+ $(length sch * 4))\n                  * [| length rcols = length sch |]\n                  * [| inBounds (V \"ilen\") rcols |] * [| V data <> 0 |]\n                  * [| freeable (V data) (2 + length sch + length sch) |]\n                  * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (wordToNat (V \"ilen\")) |]\n                  * [| V \"ipos\" = Array.selN (posl rcols) offset |])%Sep\n              (fun _ a_bs V R => array8 (snd a_bs) (V \"buf\") * invPost (fst a_bs) V R)%Sep\n            }\n          | Input pos len =>\n            If (\"tmp\" <> len) {\n              \"matched\" <- 0\n            } else {\n              \"matched\" <-- Call \"array8\"!\"equal\"(\"ibuf\", \"ipos\", \"buf\", pos, len)\n              [Al bs, Al a : A,\n                PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |]\n                  * [| inputOk V (exps cond) |] * row sch (V data) * invPre a V\n                POST[R] array8 bs (V \"buf\") * invPost a V R]\n            }\n        end\n    end%SP.\n\n  Variable mn : string.\n  Variable im : LabelMap.t assert.\n  Variable H : importsGlobal im.\n  Variable ns : list string.\n  Variable res : nat.\n\n  Definition eqinv' := Al bs, Al a : A,\n    PRE[V] array8 bs (V \"buf\") * [| length bs = wordToNat (V \"len\") |]\n      * [| inputOk V (exps cond) |]\n      * row sch (V data) * invPre a V\n    POST[R] array8 bs (V \"buf\") * invPost a V R.\n\n  Definition eqinv := eqinv' true (fun w => w).\n\n  Hypothesis not_rp : ~In \"rp\" ns.\n  Hypothesis included : incl baseVars ns.\n  Hypothesis reserved : (res >= 10)%nat.\n  Hypothesis wellFormed : wfEqualities ns sch cond.\n\n  Hypothesis weakenPre : (forall a V V', (forall x, x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n    -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x)\n  -> invPre a V ===> invPre a V').\n\n  Hypothesis weakenPost : (forall a V V' R, (forall x, x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\"\n    -> x <> \"ipos\" -> x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x)\n  -> invPost a V R = invPost a V' R).\n\n  Lemma resolve_ok : forall e s,\n    wfEquality ns s e\n    -> exists offset, resolve s (fst e) = Some offset\n      /\\ (offset < length s)%nat.\n    unfold wfEquality; induction s; simpl; intuition subst;\n      match goal with\n        | [ |- context[if ?E then _ else _] ] => destruct E\n      end; intuition eauto.\n    destruct H1; intuition idtac.\n    rewrite H3; eauto.\n  Qed.\n\n  Hypothesis matched_data : \"matched\" <> data.\n\n  Lemma compileEquality_post : forall e pre,\n    wfEquality ns sch e\n    -> (forall specs st,\n      interp specs (pre st)\n      -> interp specs (eqinv ns res st))\n    -> forall specs st,\n      interp specs (Postcondition (toCmd (compileEquality e) mn (im := im) H ns res pre) st)\n      -> interp specs (eqinv ns res st).\n    unfold compileEquality; intros.\n    match goal with\n      | [ H : _ |- _ ] => destruct (resolve_ok H); intuition idtac; destruct H\n    end.\n    match goal with\n      | [ H : resolve _ _ = _ |- _ ] => rewrite H in *\n    end.\n    destruct e as [ ? [ ] ]; simpl in *; intuition idtac.\n\n    v.\n    v.\n  Qed.\n\n  Hypothesis equal : \"array8\"!\"equal\" ~~ im ~~> ArrayOps.equalS.\n\n  Hypothesis data_rp : data <> \"rp\".\n  Hypothesis data_ibuf : data <> \"ibuf\".\n  Hypothesis data_ipos : data <> \"ipos\".\n  Hypothesis data_ilen : data <> \"ilen\".\n  Hypothesis data_tmp : data <> \"tmp\".\n  Hypothesis data_ns : In data ns.\n\n  Hypothesis goodSize_sch : goodSize (length sch).\n\n  Lemma length_posl : forall ls, length (posl ls) = length ls.\n    clear; induction ls; simpl; intuition.\n  Qed.\n\n  Lemma length_lenl : forall ls, length (lenl ls) = length ls.\n    clear; induction ls; simpl; intuition.\n  Qed.\n\n  Lemma length_match : forall x (ls : list (W * W)),\n    (x < length sch)%nat\n    -> length ls = length sch\n    -> natToW x < natToW (Datatypes.length ls).\n    generalize goodSize_sch; clear; intros.\n    pre_nomega.\n    rewrite wordToNat_natToWord_idempotent.\n    rewrite wordToNat_natToWord_idempotent.\n    congruence.\n    rewrite H0; assumption.\n    change (goodSize x); eapply goodSize_weaken; eauto.\n  Qed.\n\n  Lemma length_match_posl : forall x ls,\n    (x < length sch)%nat\n    -> length ls = length sch\n    -> natToW x < natToW (Datatypes.length (posl ls)).\n    intros; rewrite length_posl; auto using length_match.\n  Qed.\n\n  Lemma length_match_lenl : forall x ls,\n    (x < length sch)%nat\n    -> length ls = length sch\n    -> natToW x < natToW (Datatypes.length (lenl ls)).\n    intros; rewrite length_lenl; auto using length_match.\n  Qed.\n\n  Hint Immediate length_match_posl length_match_lenl.\n\n  Lemma selN_col : forall x ls,\n    (x < length sch)%nat\n    -> Array.sel ls (natToW x) = selN ls x.\n    generalize goodSize_sch; clear; unfold Array.sel; intros; f_equal.\n    apply wordToNat_natToWord_idempotent.\n    change (goodSize x).\n    eapply goodSize_weaken; eauto.\n  Qed.\n\n  Hint Immediate selN_col.\n\n  Lemma inBounds_selN' : forall len cols,\n    inBounds len cols\n    -> forall col, (col < length cols)%nat\n      -> (wordToNat (selN (posl cols) col) + wordToNat (selN (lenl cols) col) <= wordToNat len)%nat.\n    clear; induction cols; inversion 1; simpl; intuition; destruct col; intuition.\n  Qed.\n\n  Lemma inBounds_selN : forall len cols,\n    inBounds len cols\n    -> forall col a b c, a = selN (posl cols) col\n      -> b = selN (lenl cols) col\n      -> c = wordToNat len\n      -> (col < length cols)%nat\n      -> (wordToNat a + wordToNat b <= c)%nat.\n    intros; subst; eauto using inBounds_selN'.\n  Qed.\n\n  Hint Extern 1 (_ + _ <= _)%nat =>\n    eapply inBounds_selN; try eassumption; (cbv beta; congruence).\n\n  Lemma weakened_bound : forall pos cols x len,\n    inBounds len cols\n    -> pos = selN (posl cols) x\n    -> (x < length cols)%nat\n    -> pos <= len.\n    clear; intros; subst.\n    eapply inBounds_selN in H; try (reflexivity || eassumption).\n    nomega.\n  Qed.\n\n  Hint Extern 1 (_ <= _) => eapply weakened_bound; try eassumption; (cbv beta; congruence).\n\n  Hint Resolve use_inputOk.\n\n  Lemma In_exps : forall s e c,\n    In (s, e) c\n    -> In e (exps c).\n    clear; induction c; simpl; intuition (subst; auto).\n  Qed.\n\n  Hint Immediate In_exps.\n\n  Lemma compileEquality_vcs : forall e pre,\n    wfEquality ns sch e\n    -> In e cond\n    -> (forall specs st,\n      interp specs (pre st)\n      -> interp specs (eqinv ns res st))\n    -> vcs (VerifCond (toCmd (compileEquality e) mn (im := im) H ns res pre)).\n      unfold compileEquality; intros.\n      match goal with\n        | [ H : _ |- _ ] => destruct (resolve_ok H); intuition idtac; destruct H\n      end.\n      match goal with\n        | [ H : resolve _ _ = _ |- _ ] => rewrite H in *\n      end.\n      wrap0.\n\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n\n      destruct e as [ ? [ ] ]; simpl in *; intuition idtac.\n\n      repeat match goal with\n               | [ |- vcs _ ] => constructor\n             end; intros.\n\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n\n      repeat match goal with\n               | [ |- vcs _ ] => constructor\n             end; intros.\n\n      (* Something bizarre is happening here, with [destruct] not clearing a hypothesis\n       * within [propxFo]. *)\n      apply simplify_fwd in H25.\n      repeat match goal with\n               | [ H : simplify _ (Ex x, _) _ |- _ ] => destruct H\n             end.\n      apply simplify_bwd in H25.\n      v.\n\n      v.\n      v.\n      v.\n      v.\n  Qed.\n\n  Fixpoint compileEqualities (es : condition) : chunk :=\n    match es with\n      | nil => \"matched\" <- 1\n      | e :: es' =>\n        compileEquality e;;\n        If (\"matched\" = 0) {\n          Skip\n        } else {\n          compileEqualities es'\n        }\n    end%SP.\n\n  Lemma wfEqualities_inv1 : forall ns sch e es,\n    wfEqualities ns sch (e :: es)\n    -> wfEquality ns sch e.\n    inversion 1; auto.\n  Qed.\n\n  Lemma wfEqualities_inv2 : forall ns sch e es,\n    wfEqualities ns sch (e :: es)\n    -> wfEqualities ns sch es.\n    inversion 1; auto.\n  Qed.\n\n  Hint Immediate wfEqualities_inv1 wfEqualities_inv2.\n\n  Lemma compileEqualities_post : forall es pre,\n    wfEqualities ns sch es\n    -> (forall specs st,\n      interp specs (pre st)\n      -> interp specs (eqinv ns res st))\n    -> forall specs st,\n      interp specs (Postcondition (toCmd (compileEqualities es) mn (im := im) H ns res pre) st)\n      -> interp specs (eqinv ns res st).\n    induction es; simpl; intuition idtac;\n      (pre;\n        repeat (match goal with\n                  | [ H : interp _ (Postcondition (toCmd (compileEquality _) _ _ _ _ _) _) |- _ ] =>\n                    apply compileEquality_post in H\n                  | [ IH : forall pre : _ -> _, _, H : interp _ (Postcondition _ _) |- _ ] =>\n                    apply IH in H\n                end; eauto; pre); t).\n  Qed.\n\n  Lemma compileEqualities_vcs : forall es pre,\n    wfEqualities ns sch es\n    -> incl es cond\n    -> (forall specs st,\n      interp specs (pre st)\n      -> interp specs (eqinv ns res st))\n    -> vcs (VerifCond (toCmd (compileEqualities es) mn (im := im) H ns res pre)).\n    induction es; intros; try match goal with\n                                | [ H : incl _ cond |- _ ] => apply incl_peel in H\n                              end; wrap0;\n    (repeat (match goal with\n               | _ => apply compileEquality_vcs\n               | [ H : interp _ (Postcondition (toCmd (compileEquality _) _ _ _ _ _) _) |- _ ] =>\n                 apply compileEquality_post in H\n               | [ IH : forall pre : _ -> _, _ |- vcs _ ] =>\n                 apply IH\n             end; eauto; pre); t).\n  Qed.\nEnd Condition.\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/RelDbCondition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.17212553258922506}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Computation.ListComputations\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.Examples.DnsServer.Packet.\n\nRequire Import\n        Bedrock.Word\n        Bedrock.Memory.\n\n\nImport Vectors.VectorDef.VectorNotations.\n\nLocal Open Scope vector_scope.\n\nSection DecomposeEnumField.\n\n  (* Could use above to prove dependent inversion lemma, but *)\n  (* this is more of a sanity check than anything. *)\n  (* Lemma proj_SumType_inj_inverse {n}\n    : forall (v : Vector.t Type n)\n             (tag : Fin.t n)\n             (el : Vector.nth v tag),\n      SumType_proj v (inj_SumType v tag el) = el. *)\n\n  (* Goal: Convert from QueryStructure with a heading with a SumType *)\n  (* attribute to one that has multiple tables. *)\n  (* Is this a worthwhile refinement? We could just do this at data structure *)\n  (* selection time. OTOH, nice high-level refinement step that makes sense to *)\n  (* end-users and has applications in both DNS examples.  *)\n\n  Definition AddRawQueryStructureSchema\n             {m}\n             (raw_qs_schema : RawQueryStructureSchema)\n             (new_schemas : Vector.t RawSchema m)\n  : RawQueryStructureSchema :=\n    {| qschemaSchemas := Vector.append (qschemaSchemas raw_qs_schema) new_schemas;\n       qschemaConstraints := [ ] |}.\n\n  Fixpoint LiftTuple_AddRawQueryStructureSchema\n           {n m : nat}\n           (old_schemas : Vector.t RawSchema n)\n           (new_schemas : Vector.t RawSchema m)\n           Ridx\n           (tup : @RawTuple (GetNRelSchemaHeading old_schemas Ridx))\n           {struct old_schemas}\n    : @RawTuple\n        (GetNRelSchemaHeading (Vector.append old_schemas new_schemas)\n                              (Fin.L m Ridx)).\n    refine (match old_schemas in Vector.t _ n return\n                  forall (Ridx : Fin.t n),\n                    @RawTuple (GetNRelSchemaHeading old_schemas Ridx)\n                    -> @RawTuple\n                         (GetNRelSchemaHeading (Vector.append old_schemas new_schemas)\n                                               (Fin.L m Ridx)) with\n            | Vector.nil => fun Ridx tup => Fin.case0 (fun _ => _) Ridx\n            | Vector.cons _ _ _ => fun Ridx tup => _\n            end Ridx tup).\n    revert t tup0; pattern n0, Ridx0; apply Fin.caseS; simpl.\n    - intros; exact tup0.\n    - intros; exact (LiftTuple_AddRawQueryStructureSchema _ _ _ _ _ tup0).\n  Defined.\n\n  Definition AddRawQueryStructureSchema_AbsR\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (new_schemas : Vector.t RawSchema m)\n             (r_o : UnConstrQueryStructure qs_schema)\n             (r_n : UnConstrQueryStructure (AddRawQueryStructureSchema qs_schema new_schemas))\n    : Prop :=\n    (forall Ridx tup,\n        IndexedEnsemble_In (GetUnConstrRelation r_o Ridx) tup\n        <-> IndexedEnsemble_In (GetUnConstrRelation r_n (Fin.L m Ridx)) (LiftTuple_AddRawQueryStructureSchema _ _ Ridx tup)).\n\n  (* Define new schema *)\n\n  Fixpoint DecomposeHeading\n           {n m}\n           (attr : Fin.t n)\n           (sch : Vector.t Type n)\n           (a : Vector.t Type m)\n           {struct attr}\n    : Vector.t (Vector.t Type n) m :=\n    match attr in Fin.t n return Vector.t _ n ->  Vector.t (Vector.t _ n) m with\n    | Fin.F1 _ =>\n      fun sch =>\n        Vector.map (fun t => Vector.cons _ t _ (Vector.tl sch)) a\n    | Fin.FS _ attr' =>\n      fun sch =>\n        Vector.map (fun t => Vector.cons _ (Vector.hd sch) _ t)\n                   (DecomposeHeading attr' (Vector.tl sch) a)\n    end sch.\n\n  Fixpoint Tuple_mapHeading\n           {m q} {A' B' C}\n           (idx : Fin.t m)\n           (a : Vector.t C m)\n           (f : _ -> _ q)\n           (tup : ilist2 (A := A') (B := B') (Vector.map f a)[@idx])\n           {struct idx}\n    : ilist2 (B := B') (f a[@idx]).\n    refine (match idx in Fin.t m return\n                  forall (a : Vector.t C m)\n                         (f : _ -> _ q)\n                         (tup : ilist2 (B := B') (Vector.map f a)[@idx]),\n                    ilist2 (B := B') (f a[@idx]) with\n            | Fin.F1 _ => _\n            | Fin.FS _ idx' => _\n            end a f tup); clear a tup; intro; try revert idx';\n      pattern n, a; apply Vector.caseS.\n    - intros; exact tup.\n    - simpl; intros; eapply Tuple_mapHeading; eauto.\n  Defined.\n\n  Fixpoint Tuple_mapHeading_inv\n           {m q} {A' B' C}\n           (idx : Fin.t m)\n           (a : Vector.t C m)\n           (f : _ -> _ q)\n           (tup : ilist2 (B := B') (f a[@idx]))\n           {struct idx}\n    : ilist2 (A := A') (B := B') (Vector.map f a)[@idx].\n    refine (match idx in Fin.t m return\n                  forall (a : Vector.t C m)\n                         (f : _ -> _ q)\n                         (tup : ilist2 (B := B') (f a[@idx])),\n                    ilist2 (B := B') (Vector.map f a)[@idx] with\n            | Fin.F1 _ => _\n            | Fin.FS _ idx' => _\n            end a f tup); clear a tup; intro; try revert idx';\n      pattern n, a; apply Vector.caseS.\n    - intros; exact tup.\n    - simpl; intros; eapply Tuple_mapHeading_inv; eauto.\n  Defined.\n\n  Fixpoint Tuple_DecomposeHeading_inj\n           {n m}\n           (attrIdx : Fin.t n)\n           (heading : Vector.t Type n)\n           (a : Vector.t Type m)\n           (a_inj : forall idx, Vector.nth a idx -> Vector.nth heading attrIdx)\n           (idx : Fin.t m)\n           (tup : ilist2 (B := @id Type) (Vector.nth (DecomposeHeading attrIdx heading a) idx))\n           {struct attrIdx}\n    : ilist2 (B := @id Type) heading.\n    refine\n      (match attrIdx in Fin.t n return\n             forall (heading : Vector.t Type n)\n                    (a : Vector.t Type m)\n                    (a_inj : forall idx, Vector.nth a idx -> Vector.nth heading attrIdx)\n                    (idx : Fin.t m)\n                    (tup : ilist2 (B := @id Type) (Vector.nth (DecomposeHeading attrIdx heading a) idx)),\n               ilist2 (B := @id Type) heading with\n       | Fin.F1 _ => fun heading' => _\n       | Fin.FS _ attr' => fun heading' => _\n       end heading a a_inj idx tup).\n    - clear; pattern n0, heading'; eapply Vector.caseS.\n      simpl; intros.\n      exact (icons2 (B := @id Type)\n                    (a_inj idx (ilist2_hd (Tuple_mapHeading idx a _ tup)))\n                    (ilist2_tl (Tuple_mapHeading idx a _ tup))).\n    - revert attr'; pattern n0, heading'; eapply Vector.caseS.\n      simpl; intros.\n      exact (icons2\n               (ilist2_hd (Tuple_mapHeading _ _ _ tup0))\n               (Tuple_DecomposeHeading_inj\n                  _ _ attr' t _ a_inj0 _\n                  (ilist2_tl (Tuple_mapHeading _ _ _ tup0)))).\n  Defined.\n\n  Fixpoint Tuple_DecomposeHeading_proj\n           {n m}\n           (attrIdx : Fin.t n)\n           (heading : Vector.t Type n)\n           (a : Vector.t Type m)\n           (a_proj_index : Vector.nth heading attrIdx -> Fin.t m)\n           (a_proj : forall (attr : Vector.nth heading attrIdx),\n               a[@a_proj_index attr])\n           (tup : ilist2 (B := @id Type) heading)\n           {struct attrIdx}\n    : ilist2 (B := @id Type) (Vector.nth (DecomposeHeading attrIdx heading a) (a_proj_index (ith2 tup attrIdx))).\n    refine\n      (match attrIdx in Fin.t n return\n             forall\n               (heading : Vector.t Type n)\n               (a : Vector.t Type m)\n               (a_proj_index : Vector.nth heading attrIdx -> Fin.t m)\n               (a_proj : forall (attr : Vector.nth heading attrIdx),\n                   a[@a_proj_index attr])\n               (tup : ilist2 (B := @id Type) heading),\n               ilist2 (B := @id Type) (Vector.nth (DecomposeHeading attrIdx heading a) (a_proj_index (ith2 tup attrIdx))) with\n       | Fin.F1 _ => fun heading' => _\n       | Fin.FS _ attr' => fun heading' => _\n       end heading a a_proj_index a_proj tup).\n    - clear; pattern n0, heading'; eapply Vector.caseS.\n      simpl; intros.\n      exact (Tuple_mapHeading_inv\n               _ a _ (icons2 (B := @id Type) (a_proj (ilist2_hd tup)) (ilist2_tl tup))).\n    - revert attr'; pattern n0, heading'; eapply Vector.caseS.\n      simpl; intros.\n      refine (Tuple_mapHeading_inv\n                _ _ _\n                (icons2 (B := @id Type)\n                        (ilist2_hd tup0)\n                        (Tuple_DecomposeHeading_proj _ _ _ _ _ _ a_proj0 (ilist2_tl tup0)))).\n  Defined.\n\n  (* Could fuse this with Decompose Heading, but efficiency shouldn't matter too much. *)\n  Definition DecomposeSchema\n             {m}\n             (heading : RawSchema)\n             (attr : Fin.t _)\n             (a : Vector.t Type m)\n    : Vector.t RawSchema m :=\n    Vector.map\n      (fun rawheading =>\n         {| rawSchemaHeading := Build_RawHeading rawheading;\n            attrConstraints := None;\n            tupleConstraints := None |})\n      (DecomposeHeading attr (AttrList (rawSchemaHeading heading)) a).\n\n  Definition DecomposeRawQueryStructureSchema\n             {m}\n             (raw_qs_schema : RawQueryStructureSchema)\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n    : RawQueryStructureSchema :=\n    {| qschemaSchemas :=\n         DecomposeSchema (Vector.nth (qschemaSchemas raw_qs_schema) schemaIdx)\n                         attrIdx a;\n       qschemaConstraints := [ ] |}.\n\n  Definition Tuple_DecomposeRawQueryStructure_proj\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (tup : ilist2 (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)))\n    :  ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) (a_proj_index (GetAttributeRaw tup attrIdx)))).\n    unfold DecomposeRawQueryStructureSchema in *; simpl in *.\n    unfold GetNRelSchema, DecomposeSchema in *;\n      simpl in *.\n    erewrite VectorSpec.nth_map by eauto; simpl.\n    eapply Tuple_DecomposeHeading_proj; eauto.\n  Defined.\n\n  Definition Tuple_DecomposeRawQueryStructure_inj\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             (idx : Fin.t m)\n             (tup : ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) idx)))\n    : ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)).\n    unfold DecomposeRawQueryStructureSchema in *; simpl in *.\n    unfold GetNRelSchema, DecomposeSchema in *;\n      simpl in *.\n    erewrite VectorSpec.nth_map in tup by eauto; simpl.\n    simpl in tup.\n    eapply Tuple_DecomposeHeading_inj; eauto.\n  Defined.\n\n  Fixpoint Tuple_DecomposeRawQueryStructure_Tuple_inj\n           {n m : nat}\n           (headings : _ )\n           (idx : Fin.t m)\n           (tup : ilist2 (B := @id Type)\n                         (AttrList\n                            (rawSchemaHeading\n                               (Vector.map\n                                  (fun\n                                      rawheading : t Type n =>\n                                      {|\n                                        rawSchemaHeading := {|\n                                                             NumAttr := _;\n                                                             AttrList := rawheading |};\n                                        attrConstraints := None;\n                                        tupleConstraints := None |})\n                                  headings)[@idx])))\n           {struct idx}\n    : ilist2 (B := @id Type) headings[@idx].\n  Proof.\n    destruct idx; simpl in *;\n      revert tup; try revert idx;\n        pattern n0, headings; apply Vector.caseS.\n    - simpl; intros; exact tup.\n    - simpl; intros.\n      apply Tuple_DecomposeRawQueryStructure_Tuple_inj.\n      apply tup.\n  Defined.\n\n  Definition Tuple_DecomposeRawQueryStructure_inj'\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             (idx : Fin.t m)\n             (tup : ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) idx)))\n             (Tuple_inj :\n                ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) idx))\n                ->\n                ilist2 (B := @id Type)\n                       (DecomposeHeading attrIdx\n                                         (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) a)[@idx] := Tuple_DecomposeRawQueryStructure_Tuple_inj _ idx)\n    : ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)).\n    eapply Tuple_DecomposeHeading_inj; eauto.\n  Defined.\n\n  Fixpoint Tuple_DecomposeRawQueryStructure_Tuple_proj\n           {n m : nat}\n           (headings : _ )\n           (idx : Fin.t m)\n           (tup : ilist2 (B := @id Type) headings[@idx])\n           {struct idx}\n    :\n      ilist2 (B := @id Type)\n             (AttrList\n                (rawSchemaHeading\n                   (Vector.map\n                      (fun\n                          rawheading : t Type n =>\n                          {|\n                            rawSchemaHeading := {|\n                                                 NumAttr := _;\n                                                 AttrList := rawheading |};\n                            attrConstraints := None;\n                            tupleConstraints := None |})\n                      headings)[@idx]))\n  .\n  Proof.\n    destruct idx; simpl in *;\n      revert tup; try revert idx;\n        pattern n0, headings; apply Vector.caseS.\n    - simpl; intros; exact tup.\n    - simpl; intros.\n      apply Tuple_DecomposeRawQueryStructure_Tuple_proj.\n      apply tup.\n  Defined.\n\n  Definition Tuple_DecomposeRawQueryStructure_proj'\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (tup : ilist2 (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)))\n             (Tuple_proj :\n                ilist2 (B := @id Type)\n                       (DecomposeHeading attrIdx\n                                         (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) a)[@a_proj_index (GetAttributeRaw tup attrIdx)]\n                -> ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) (a_proj_index (GetAttributeRaw tup attrIdx))))\n              := Tuple_DecomposeRawQueryStructure_Tuple_proj _ (a_proj_index _))\n    : ilist2 (B := @id Type) (AttrList (GetNRelSchemaHeading (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)) (a_proj_index (GetAttributeRaw tup attrIdx)))).\n    eapply Tuple_proj; eapply Tuple_DecomposeHeading_proj; eauto.\n  Defined.\n\n  Definition DecomposeRawQueryStructureSchema_AbsR\n             {m : nat}\n             {qs_schema : RawQueryStructureSchema}\n             (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             (r_o : UnConstrQueryStructure qs_schema)\n             (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : Prop :=\n    (forall Ridx, Same_set _ (GetUnConstrRelation r_o Ridx)\n                           (GetUnConstrRelation (fst r_n) Ridx))\n    /\\ (forall Ridx tup,\n           In _ (GetUnConstrRelation (snd r_n) Ridx) tup\n           ->  In _ (GetUnConstrRelation (fst r_n) schemaIdx)\n                  {| elementIndex := elementIndex tup;\n                     indexedElement := Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj _ (indexedElement tup) |})\n    /\\ (forall tup,\n           In _ (GetUnConstrRelation (fst r_n) schemaIdx) tup\n           -> In _ (GetUnConstrRelation (snd r_n) (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx)))\n                 {| elementIndex := elementIndex tup;\n                    indexedElement := Tuple_DecomposeRawQueryStructure_proj' _ _ a _ a_proj (indexedElement tup) |})\n    /\\ (forall Ridx Ridx' tup tup' ,\n           In _ (GetUnConstrRelation (snd r_n) Ridx) tup\n           -> In _ (GetUnConstrRelation (snd r_n) Ridx') tup'\n           -> Ridx <> Ridx'\n           -> elementIndex tup <> elementIndex tup')\n    /\\ (forall Ridx tup,\n           In IndexedElement (GetUnConstrRelation (snd r_n) Ridx) tup\n           -> a_proj_index (GetAttributeRaw\n                              (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj _ (indexedElement tup)) attrIdx) = Ridx)\n    /\\ (forall Ridx, FiniteEnsemble (GetUnConstrRelation (snd r_n) Ridx)).\n\n  Definition DecomposeRawQueryStructureSchema_AbsR'\n             {m : nat}\n             {qs_schema : QueryStructureSchema}\n             ( schemaIdx' : BoundedIndex (QSschemaNames qs_schema))\n             (schemaIdx := ibound (indexb schemaIdx'))\n             {attrIdx' : BoundedIndex (HeadingNames (QSGetNRelSchemaHeading (qs_schema) schemaIdx'))}\n             (attrIdx := ibound (indexb attrIdx'))\n             (attrIdx_inj : Fin.t _ -> Fin.t _)\n             (EnumTypes : Vector.t Type m)\n             (f' : Vector.nth (AttrList _) (attrIdx_inj attrIdx) -> SumType EnumTypes)\n             (f'' : SumType EnumTypes -> Vector.nth (AttrList _) (attrIdx_inj attrIdx))\n             (a_proj_index : Vector.nth (AttrList _) (attrIdx_inj attrIdx) -> Fin.t m :=\n                fun attr => SumType_index EnumTypes (f' attr))\n             (a_proj : forall (attr : Vector.nth _ (attrIdx_inj attrIdx)), EnumTypes[@a_proj_index attr] :=\n                fun attr => SumType_proj EnumTypes (f' attr))\n             (a_inj : forall idx, Vector.nth EnumTypes idx -> Vector.nth (AttrList _) (attrIdx_inj attrIdx) :=\n                fun idx attr => f'' (inj_SumType EnumTypes idx attr))\n             (r_o : UnConstrQueryStructure qs_schema)\n             (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx (attrIdx_inj attrIdx) EnumTypes))\n    : Prop :=\n    DecomposeRawQueryStructureSchema_AbsR (qs_schema := qs_schema)\n                                          schemaIdx (attrIdx_inj attrIdx)\n                                          EnumTypes a_proj_index a_proj a_inj r_o r_n.\n\n  Definition DecomposeRawQueryStructureSchema_empty_AbsR\n             {m : nat}\n             {qs_schema : QueryStructureSchema}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx),\n      DecomposeRawQueryStructureSchema_AbsR\n        schemaIdx attrIdx a a_proj_index a_proj a_inj\n        (DropQSConstraints (QSEmptySpec qs_schema))\n        (DropQSConstraints (QSEmptySpec qs_schema),\n         imap2 (fun ns : RawSchema => rawRel (RelationSchema:=ns))\n               (Build_EmptyRelations\n                  (qschemaSchemas (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a)))).\n  Proof.\n    intros.\n    repeat split; simpl; intros; intuition.\n    - unfold GetUnConstrRelation in H.\n      rewrite <- ith_imap2,\n      EmptyRefinements.ith_Bounded_BuildEmptyRelations in H.\n      simpl in H; unfold IndexedEnsemble_In in H; destruct_ex;\n        inversion H.\n    - unfold GetUnConstrRelation, DropQSConstraints, QSEmptySpec in H.\n      rewrite <- ith_imap2 in H.\n      simpl in H.\n      rewrite EmptyRefinements.ith_Bounded_BuildEmptyRelations in H.\n      simpl in H; unfold IndexedEnsemble_In in H; destruct_ex;\n        inversion H.\n    - unfold UnConstrFreshIdx in *; intros.\n      unfold GetUnConstrRelation, DropQSConstraints, QSEmptySpec in H0.\n      rewrite <- ith_imap2 in H0.\n      simpl in H0.\n      rewrite EmptyRefinements.ith_Bounded_BuildEmptyRelations in H0.\n      destruct H0.\n    - unfold UnConstrFreshIdx in *; intros.\n      unfold GetUnConstrRelation, DropQSConstraints, QSEmptySpec in H.\n      rewrite <- ith_imap2 in H.\n      simpl in H.\n      rewrite EmptyRefinements.ith_Bounded_BuildEmptyRelations in H.\n      destruct H.\n    - unfold FiniteEnsemble; eexists nil.\n      unfold GetUnConstrRelation, DropQSConstraints, QSEmptySpec.\n      rewrite <- ith_imap2.\n      rewrite EmptyRefinements.ith_Bounded_BuildEmptyRelations.\n      apply  UnIndexedEnsembleListEquivalence_Empty_set.\n  Qed.\n\n  Definition DecomposeRawQueryStructureSchema_Insert_AbsR_neq\n             {m : nat}\n             {qs_schema : QueryStructureSchema}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             r_o\n             r_n,\n      DecomposeRawQueryStructureSchema_AbsR\n        schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      forall Ridx tup,\n        Ridx <> schemaIdx\n        -> DecomposeRawQueryStructureSchema_AbsR\n             schemaIdx attrIdx a a_proj_index a_proj a_inj\n             (UpdateUnConstrRelation r_o Ridx (EnsembleInsert tup (GetUnConstrRelation r_o Ridx)))\n             (UpdateUnConstrRelation (fst r_n) Ridx (EnsembleInsert tup (GetUnConstrRelation (fst r_n) Ridx)), snd r_n).\n  Proof.\n    repeat split; simpl; intros.\n    - destruct (fin_eq_dec Ridx Ridx0); subst;\n        unfold GetUnConstrRelation, UpdateUnConstrRelation.\n      + rewrite !ith_replace2_Index_eq.\n        unfold Included; intros.\n        inversion H1; subst; intuition.\n        * econstructor; eauto.\n        * econstructor 2; eapply (proj1 H Ridx0); apply H2.\n      + rewrite !ith_replace2_Index_neq; eauto.\n        unfold Included; intros; eapply (proj1 H Ridx0); apply H1.\n    - destruct (fin_eq_dec Ridx Ridx0); subst;\n        unfold GetUnConstrRelation, UpdateUnConstrRelation.\n      + rewrite !ith_replace2_Index_eq.\n        unfold Included; intros.\n        inversion H1; subst; intuition.\n        * econstructor; eauto.\n        * econstructor 2; eapply (proj1 H Ridx0); apply H2.\n      + rewrite !ith_replace2_Index_neq; eauto.\n        unfold Included; intros; eapply (proj1 H Ridx0); apply H1.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation.\n      rewrite !ith_replace2_Index_neq; eauto.\n      eapply (proj2 H); eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      rewrite !ith_replace2_Index_neq in H1; eauto.\n      eapply (proj2 H); eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      eapply H; eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      eapply H; eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      eapply H; eauto.\n  Qed.\n\n  Lemma Tuple_DecomposeRawQueryStructure_inj_inverse\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             tup,\n      Tuple_DecomposeRawQueryStructure_inj' schemaIdx attrIdx a a_inj\n                                            (a_proj_index (GetAttributeRaw tup attrIdx))\n                                            (Tuple_DecomposeRawQueryStructure_proj' schemaIdx attrIdx a a_proj_index a_proj\n                                                                                    tup) = tup.\n  Admitted.\n\n  Lemma ith_replace2_Index_eq':\n    forall (A : Type) (B : A -> Type) (m : nat) (n n' : Fin.t m) (As : t A m) (il : ilist2 As) (new_b : B As[@n'])\n           (H : n' = n),\n      ith2 (replace_Index2 As il n' new_b) n = @eq_rect _ _ (fun n => B As[@n]) new_b _ H.\n  Proof.\n    intros.\n    subst; unfold eq_rect; apply ith_replace2_Index_eq.\n  Qed.\n\n  Definition DecomposeRawQueryStructureSchema_Insert_AbsR_eq\n             {m : nat}\n             {qs_schema : QueryStructureSchema}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             r_o\n             r_n,\n      DecomposeRawQueryStructureSchema_AbsR\n        schemaIdx attrIdx a a_proj_index a_proj a_inj\n        r_o r_n\n      ->\n      forall tup\n             (freshIdx : UnConstrFreshIdx (GetUnConstrRelation (fst r_n) schemaIdx) (elementIndex tup)),\n        DecomposeRawQueryStructureSchema_AbsR\n          schemaIdx attrIdx a a_proj_index a_proj a_inj\n          (UpdateUnConstrRelation r_o schemaIdx (EnsembleInsert tup (GetUnConstrRelation r_o schemaIdx)))\n          (UpdateUnConstrRelation (fst r_n) schemaIdx (EnsembleInsert tup (GetUnConstrRelation (fst r_n) schemaIdx)),\n           UpdateUnConstrRelation (snd r_n)\n                                  (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))\n                                  (EnsembleInsert {| elementIndex := elementIndex tup;\n                                                     indexedElement :=\n                                                       Tuple_DecomposeRawQueryStructure_proj'\n                                                         _ _ _ _ a_proj\n                                                         (indexedElement tup) |} (GetUnConstrRelation (snd r_n) (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))))).\n    repeat split; simpl; intros.\n    - destruct (fin_eq_dec schemaIdx Ridx); subst;\n        unfold GetUnConstrRelation, UpdateUnConstrRelation.\n      + rewrite !ith_replace2_Index_eq.\n        unfold Included; intros.\n        inversion H0; subst; intuition.\n        * econstructor; eauto.\n        * econstructor 2; eapply (proj1 H Ridx); apply H1.\n      + rewrite !ith_replace2_Index_neq; eauto.\n        unfold Included; intros; eapply (proj1 H Ridx); apply H0.\n    - destruct (fin_eq_dec schemaIdx Ridx); subst;\n        unfold GetUnConstrRelation, UpdateUnConstrRelation.\n      + rewrite !ith_replace2_Index_eq.\n        unfold Included; intros.\n        inversion H0; subst; intuition.\n        * econstructor; eauto.\n        * econstructor 2; eapply (proj1 H Ridx); apply H1.\n      + rewrite !ith_replace2_Index_neq; eauto.\n        unfold Included; intros; eapply (proj1 H Ridx); apply H0.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      + rewrite !ith_replace2_Index_eq in *.\n        simpl in H0.\n        destruct (fin_eq_dec\n                    Ridx\n                    (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))); subst.\n        rewrite !ith_replace2_Index_eq in H0.\n        destruct H0 as [? | ?]; subst.\n        * destruct tup; subst; injections; simpl.\n          econstructor; f_equal; simpl.\n          erewrite <- Tuple_DecomposeRawQueryStructure_inj_inverse.\n          reflexivity.\n        * pose proof (proj1 (proj2 H) (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx)) tup0).\n          apply H1 in H0.\n          econstructor 2; eauto.\n        * rewrite !ith_replace2_Index_neq in H0 by eauto.\n          pose proof (proj1 (proj2 H) Ridx tup0 H0); eauto.\n          econstructor 2; eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      + rewrite !ith_replace2_Index_eq in H0.\n        destruct H0 as [? | ?]; subst.\n        * try rewrite !ith_replace2_Index_eq.\n          econstructor; econstructor; f_equal.\n        * apply (proj1 (proj2 (proj2 H)) tup0) in H0.\n          simpl in *.\n          destruct tup0; destruct tup; simpl in *.\n          clear r_o H.\n          destruct (fin_eq_dec (a_proj_index (GetAttributeRaw indexedElement attrIdx))\n                               (a_proj_index (GetAttributeRaw indexedElement0 attrIdx))\n                   ); subst;\n            [ | rewrite !ith_replace2_Index_neq; eauto].\n          symmetry in e;\n            erewrite ith_replace2_Index_eq' with (H := e).\n          revert H0; clear.\n          match goal with\n            |- context[In _ _ ?G] => generalize G; clear\n          end.\n          revert e.\n          match goal with\n            |- context[EnsembleInsert ?t _] =>\n            generalize t\n          end.\n          clear.\n          destruct e; simpl; intros.\n          unfold EnsembleInsert; intuition.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      destruct (fin_eq_dec\n                  Ridx\n                  (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx)));\n        destruct (fin_eq_dec\n                    Ridx'\n                    (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))); subst.\n      + congruence.\n      + rewrite ith_replace2_Index_eq in H0.\n        rewrite ith_replace2_Index_neq in H1 by eauto.\n        destruct H0 as [? | ?]; subst; simpl.\n        * apply (proj1 (proj2 H)) in H1; apply freshIdx in H1; simpl in *; try omega.\n        * apply H; eauto.\n      + rewrite ith_replace2_Index_neq in H0 by eauto.\n        rewrite ith_replace2_Index_eq in H1.\n        destruct H1 as [? | ?]; subst; simpl.\n        * apply (proj1 (proj2 H)) in H0; apply freshIdx in H0; simpl in *; omega.\n        * apply H; eauto.\n      + rewrite ith_replace2_Index_neq in H0 by eauto.\n        rewrite ith_replace2_Index_neq in H1 by eauto.\n        apply H; eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      destruct (fin_eq_dec\n                  Ridx\n                  (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))).\n      + subst.\n        rewrite ith_replace2_Index_eq in H0.\n        destruct H0 as [? | ?]; subst; simpl.\n        * repeat f_equal.\n          erewrite <- Tuple_DecomposeRawQueryStructure_inj_inverse;\n            reflexivity.\n        * apply H; eauto.\n      + rewrite ith_replace2_Index_neq in H0 by eauto.\n        apply H; eauto.\n    - unfold GetUnConstrRelation, UpdateUnConstrRelation in *.\n      destruct (fin_eq_dec\n                  Ridx\n                  (a_proj_index (GetAttributeRaw (indexedElement tup) attrIdx))).\n      + subst; rewrite ith_replace2_Index_eq.\n        apply FiniteEnsemble_Insert; eauto.\n        * unfold UnConstrFreshIdx in *; simpl in *; intros.\n          eapply (proj1 (proj2 H)) in H0; simpl in H0.\n          apply freshIdx in H0.\n          simpl in H0; eauto.\n        * apply H.\n      + rewrite ith_replace2_Index_neq by eauto.\n        apply H.\n  Qed.\n\n  Lemma UnConstrFreshIdx_Same_Set_Equiv {ElementType} :\n    forall (ensemble ensemble' : @IndexedEnsemble ElementType),\n      Same_set _ ensemble ensemble'\n      -> forall bound,\n        UnConstrFreshIdx ensemble bound\n        <-> UnConstrFreshIdx ensemble' bound.\n  Proof.\n    unfold Same_set, UnConstrFreshIdx; intros.\n    intuition.\n    - eapply H; eapply H1; eauto.\n    - eapply H; eapply H0; eauto.\n  Qed.\n\n  Lemma refine_UnConstrFreshIdx_Same_Set_Equiv {ElementType} :\n    forall (ensemble ensemble' : @IndexedEnsemble ElementType),\n      Same_set _ ensemble ensemble'\n      -> refine {idx : nat | UnConstrFreshIdx ensemble idx}\n                {idx : nat | UnConstrFreshIdx ensemble' idx}.\n  Proof.\n    intros.\n    unfold refine; intros; computes_to_inv; computes_to_econstructor.\n    rewrite UnConstrFreshIdx_Same_Set_Equiv; eauto.\n  Qed.\n\n  Corollary refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv\n            {m : nat}\n            {qs_schema : RawQueryStructureSchema}\n            (schemaIdx : Fin.t _)\n            (attrIdx : Fin.t _)\n            (a : Vector.t Type m)\n            (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n            (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n            (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n            (r_o : UnConstrQueryStructure qs_schema)\n            (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      -> refine {idx : nat | UnConstrFreshIdx (GetUnConstrRelation r_o schemaIdx) idx}\n                {idx : nat | forall Ridx', UnConstrFreshIdx (GetUnConstrRelation (snd r_n) Ridx') idx}.\n  Proof.\n    intros; etransitivity.\n    - apply refine_UnConstrFreshIdx_Same_Set_Equiv.\n      apply (proj1 H).\n    - eapply refineEquiv_pick_pick; unfold UnConstrFreshIdx; split; intros.\n      apply (proj1 (proj2 (proj2 H))) in H1.\n      apply H0 in H1; apply H1.\n      apply (proj1 (proj2 H)) in H1.\n      apply H0 in H1.\n      apply H1.\n  Qed.\n\n  Corollary refineEquiv_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv'\n            {m : nat}\n            {qs_schema : RawQueryStructureSchema}\n            (schemaIdx : Fin.t _)\n            (attrIdx : Fin.t _)\n            (a : Vector.t Type m)\n            (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n            (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n            (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n            (r_o : UnConstrQueryStructure qs_schema)\n            (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      -> forall Ridx,\n        refineEquiv {idx : nat | UnConstrFreshIdx (GetUnConstrRelation r_o Ridx) idx}\n               {idx : nat | UnConstrFreshIdx (GetUnConstrRelation (fst r_n) Ridx) idx}.\n  Proof.\n    intros; split; rewrite refine_UnConstrFreshIdx_Same_Set_Equiv;\n      try reflexivity.\n    apply (proj1 H).\n    unfold Same_set; split; apply (proj1 H).\n  Qed.\n\n  Corollary refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv'\n            {m : nat}\n            {qs_schema : RawQueryStructureSchema}\n            (schemaIdx : Fin.t _)\n            (attrIdx : Fin.t _)\n            (a : Vector.t Type m)\n            (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n            (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n            (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n            (r_o : UnConstrQueryStructure qs_schema)\n            (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      -> forall Ridx idx',\n        computes_to {idx : nat | UnConstrFreshIdx (GetUnConstrRelation r_o Ridx) idx} idx'\n        -> UnConstrFreshIdx (GetUnConstrRelation (fst r_n) Ridx) idx'.\n  Proof.\n    intros.\n    computes_to_inv.\n    rewrite <- UnConstrFreshIdx_Same_Set_Equiv; eauto.\n    apply (proj1 H Ridx).\n  Qed.\n\n  Local Transparent QueryResultComp.\n\n  Lemma flatten_CompList_ret:\n    forall (A B : Type) (f : A -> B) (l : list A),\n      refine (ret (map f l))\n             (FlattenCompList.flatten_CompList (map (fun a => ret [(f a)]) l))%list.\n  Proof.\n    induction l; simpl.\n    - reflexivity.\n    - setoid_rewrite <- IHl.\n      repeat setoid_rewrite refineEquiv_bind_unit.\n      simpl; reflexivity.\n  Qed.\n\n  Corollary DecomposeRawQueryStructureSchema_UpdateUnConstrRelationInsertC_eq\n            {m : nat}\n            {qs_schema : QueryStructureSchema}\n            {ResultT}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             r_o\n             r_n\n             (k : UnConstrQueryStructure qs_schema -> Comp ResultT)\n             (k' : _ -> Comp ResultT),\n      DecomposeRawQueryStructureSchema_AbsR\n        schemaIdx attrIdx a a_proj_index a_proj a_inj\n        r_o r_n\n      -> forall freshIdx tup,\n        computes_to {idx | UnConstrFreshIdx (GetUnConstrRelation r_o schemaIdx) idx} freshIdx\n        -> (forall r_o' r_n',\n               DecomposeRawQueryStructureSchema_AbsR\n                 schemaIdx attrIdx a a_proj_index a_proj a_inj\n                 r_o' r_n'\n               -> refine (k r_o') (k' r_n'))\n        ->\n        refine (r_o' <- UpdateUnConstrRelationInsertC r_o schemaIdx {| elementIndex := freshIdx; indexedElement := tup |};\n                  k r_o')\n               (r_n' <- UpdateUnConstrRelationInsertC (fst r_n) schemaIdx {| elementIndex := freshIdx; indexedElement := tup |};\n                  r_n'' <- UpdateUnConstrRelationInsertC (snd r_n)\n                        (a_proj_index (GetAttributeRaw tup attrIdx))\n                        {| elementIndex := freshIdx;\n                           indexedElement :=\n                             Tuple_DecomposeRawQueryStructure_proj'\n                               _ _ _ _ a_proj\n                               tup |};\n                  k' (r_n', r_n'')).\n  Proof.\n    Local Transparent UpdateUnConstrRelationInsertC.\n    unfold UpdateUnConstrRelationInsertC; intros.\n    repeat rewrite refineEquiv_bind_unit.\n    rewrite H1.\n    reflexivity.\n    simpl.\n    eapply (DecomposeRawQueryStructureSchema_Insert_AbsR_eq H); eauto.\n    eapply refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv'; eauto.\n  Qed.\n\n  Corollary DecomposeRawQueryStructureSchema_UpdateUnConstrRelationInsertC_neq\n            {m : nat}\n            {qs_schema : QueryStructureSchema}\n            {ResultT}\n    : forall (schemaIdx : Fin.t _)\n             (attrIdx : Fin.t _)\n             (a : Vector.t Type m)\n             (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n             (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n             (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n             r_o\n             r_n\n             (k : UnConstrQueryStructure qs_schema -> Comp ResultT)\n             (k' : _ -> Comp ResultT),\n      DecomposeRawQueryStructureSchema_AbsR\n        schemaIdx attrIdx a a_proj_index a_proj a_inj\n        r_o r_n\n      -> forall Ridx freshIdx tup,\n        Ridx <> schemaIdx\n        -> (forall r_o' r_n',\n               DecomposeRawQueryStructureSchema_AbsR\n                 schemaIdx attrIdx a a_proj_index a_proj a_inj\n                 r_o' r_n'\n               -> refine (k r_o') (k' r_n'))\n        ->\n        refine (r_o' <- UpdateUnConstrRelationInsertC r_o Ridx {| elementIndex := freshIdx; indexedElement := tup |};\n                  k r_o')\n               (r_n' <- UpdateUnConstrRelationInsertC (fst r_n) Ridx {| elementIndex := freshIdx; indexedElement := tup |};\n                  k' (r_n', snd r_n)).\n  Proof.\n    unfold UpdateUnConstrRelationInsertC; intros.\n    repeat rewrite refineEquiv_bind_unit.\n    rewrite H1.\n    reflexivity.\n    simpl; eapply (DecomposeRawQueryStructureSchema_Insert_AbsR_neq H); eauto.\n  Qed.\n\n  Fixpoint Iterate_Equiv_QueryResultComp\n           m\n           (heading : RawHeading)\n           (headings : Fin.t m -> RawHeading)\n           (Ensembles : forall (idx : Fin.t m),\n               @IndexedEnsemble (@RawTuple (headings idx)))\n           (inj_Tuple : forall (idx : Fin.t m),\n               @RawTuple (headings idx)\n               -> @RawTuple heading)\n           {struct m}\n    : Comp (list (@RawTuple heading)) :=\n    match m return\n          forall (headings : Fin.t m -> RawHeading),\n            (forall (idx : Fin.t m),\n                @IndexedEnsemble (@RawTuple (headings idx)))\n            -> (forall (idx : Fin.t m),\n                   @RawTuple (headings idx)\n                   -> @RawTuple heading)\n            -> Comp (list _)\n    with\n    | 0 => fun _ _ _ => (ret List.nil)\n    | S m =>\n      fun headings Ensembles inj_Tuple =>\n        res <- QueryResultComp (Ensembles Fin.F1)\n            (fun tup => ret [inj_Tuple Fin.F1 tup])%list;\n          res' <- Iterate_Equiv_QueryResultComp heading\n               (fun idx => headings (Fin.FS idx))\n               (fun idx => Ensembles (Fin.FS idx))\n               (fun idx tup => (inj_Tuple (Fin.FS idx) tup))\n          ;\n          ret (List.app res res')\n    end headings Ensembles inj_Tuple.\n\n  Lemma refine_UnIndexedEnsembleListEquivalence_Iterate_Equiv_QueryResultComp\n        m\n        (heading : RawHeading)\n        (headings : Fin.t m -> RawHeading)\n        (Ensembles : forall (idx : Fin.t m),\n            @IndexedEnsemble (@RawTuple (headings idx)))\n        (inj_Tuple : forall (idx : Fin.t m),\n            @RawTuple (headings idx)\n            -> @RawTuple heading)\n\n        (distinctIndexes : forall idx idx' tup tup',\n            idx <> idx'\n            -> Ensembles idx tup\n            -> Ensembles idx' tup'\n            -> elementIndex tup <> elementIndex tup')\n    : refine\n        {queriedList : list RawTuple |\n         UnIndexedEnsembleListEquivalence\n           (fun tup => exists idx tup',\n                tup = {| elementIndex := elementIndex tup';\n                         indexedElement := inj_Tuple idx (indexedElement tup') |}\n                /\\ In _ (Ensembles idx) tup')\n           queriedList}\n        (Iterate_Equiv_QueryResultComp heading headings Ensembles inj_Tuple).\n  Proof.\n    revert heading headings Ensembles inj_Tuple distinctIndexes.\n    induction m; simpl; intros; intros ? ?.\n    - computes_to_inv; subst; computes_to_econstructor.\n      unfold UnIndexedEnsembleListEquivalence; eexists nil; simpl;\n        intuition eauto.\n      unfold In in H; destruct_ex; intuition subst.\n      inversion x0.\n      constructor.\n    - unfold QueryResultComp in H.\n      computes_to_inv; subst.\n      eapply IHm in H'; computes_to_inv; clear IHm.\n      apply flatten_CompList_ret in H'0; computes_to_inv; subst.\n      computes_to_econstructor. unfold UnIndexedEnsembleListEquivalence in *;\n                                  destruct_ex; intuition; subst.\n      rewrite map_map.\n      replace (fun x1 : IndexedElement => inj_Tuple Fin.F1 (indexedElement x1))\n      with (fun x1 : IndexedElement => indexedElement {| elementIndex := elementIndex x1;\n                                                         indexedElement := inj_Tuple Fin.F1 (indexedElement x1) |}) by\n          (apply functional_extensionality; reflexivity).\n      rewrite <- map_map.\n      eexists (_ ++ _)%list.\n      rewrite map_app; intuition eauto.\n      + unfold In in *; destruct_ex; intuition subst.\n        revert headings Ensembles inj_Tuple distinctIndexes x0 x H0 H4 H2 H5 x3 H3.\n        pattern m, x2.\n        eapply Fin.caseS; clear m x2; intros.\n        * simpl in *; apply H0 in H3; apply in_or_app; left.\n          eapply in_map with\n          (f := (fun x1 : IndexedElement =>\n                   {| elementIndex := elementIndex x1;\n                      indexedElement := inj_Tuple Fin.F1 (indexedElement x1) |})) in H3.\n          apply H3.\n        * apply in_or_app; right.\n          eapply H2; eexists _,_; intuition eauto.\n      + apply in_app_or in H; unfold In in *; destruct_ex; intuition subst.\n        * apply in_map_iff in H1; destruct_ex; intuition subst.\n          eexists _, _; intuition eauto.\n          eapply H0; eauto.\n        * eapply H2 in H1.\n          destruct_ex; intuition subst.\n          eexists _, _; intuition eauto.\n      + rewrite map_app.\n        eapply NoDup_app_in_iff; intuition.\n        revert H4; clear; induction x0; simpl; intros; econstructor;\n          inversion H4; subst; eauto.\n        intro; apply H1; revert H; clear; induction x0; simpl; intuition auto.\n        rewrite map_map in H1.\n        apply in_map_iff in H; apply in_map_iff in H1.\n        destruct_ex; intuition; subst.\n        eapply H2 in H6; eapply H0 in H7.\n        destruct H6 as [? [? [? ?] ] ]; simpl in *; subst;\n          simpl in *.\n        eapply (distinctIndexes Fin.F1 (Fin.FS x1)); eauto.\n        intros; discriminate.\n      + intros; eapply distinctIndexes; eauto.\n        intro; apply H0.\n        apply Fin.FS_inj; eauto.\n  Qed.\n\n  Fixpoint Iterate_Equiv_QueryResultComp_body\n           m\n           {ResultT}\n           (heading : RawHeading)\n           (headings : Fin.t m -> RawHeading)\n           (Ensembles : forall (idx : Fin.t m),\n               @IndexedEnsemble (@RawTuple (headings idx)))\n           (inj_Tuple : forall (idx : Fin.t m),\n               @RawTuple (headings idx)\n               -> @RawTuple heading)\n           (body : @RawTuple heading -> Comp (list ResultT))\n           {struct m}\n    : Comp (list ResultT) :=\n    match m return\n          forall (headings : Fin.t m -> RawHeading),\n            (forall (idx : Fin.t m),\n                @IndexedEnsemble (@RawTuple (headings idx)))\n            -> (forall (idx : Fin.t m),\n                   @RawTuple (headings idx)\n                   -> @RawTuple heading)\n            -> Comp (list ResultT)\n    with\n    | 0 => fun _ _ _ => (ret List.nil)\n    | S m =>\n      fun headings Ensembles inj_Tuple =>\n        res <- QueryResultComp (Ensembles Fin.F1)\n            (fun tup => body (inj_Tuple Fin.F1 tup));\n          res' <- Iterate_Equiv_QueryResultComp_body heading\n               (fun idx => headings (Fin.FS idx))\n               (fun idx => Ensembles (Fin.FS idx))\n               (fun idx tup => (inj_Tuple (Fin.FS idx) tup))\n               body\n          ;\n          ret (List.app res res')\n    end headings Ensembles inj_Tuple.\n\n  Definition Iterate_Equiv_For_UnConstrQuery_In_body\n           {m : nat}\n           {qs_schema : RawQueryStructureSchema}\n           {ResultT}\n           (schemaIdx : Fin.t _)\n           (body : @RawTuple _ -> Comp (list ResultT))\n           (attrIdx : Fin.t _)\n           (a : Vector.t Type m)\n           (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n           (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n           (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n           (r_n : UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : Comp (list ResultT) :=\n    (fix Iterate_Equiv_For_UnConstrQuery_In_body' (m : nat) :=\n    match m return (Fin.t m -> Comp (list ResultT)) -> _\n    with\n    | 0 => fun results => ret nil\n    | S n'' => fun results =>\n        res <- results Fin.F1;\n        res' <- Iterate_Equiv_For_UnConstrQuery_In_body' n'' (fun idx => results (Fin.FS idx));\n        ret (List.app res res')\n    end) _ (fun idx => For (UnConstrQuery_In r_n idx\n                                             (fun tup => body (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj idx tup)))).\n\n  Definition Iterate_Equiv_Count_For_UnConstrQuery_In_body\n           {m : nat}\n           {qs_schema : RawQueryStructureSchema}\n           {ResultT}\n           (schemaIdx : Fin.t _)\n           (body : @RawTuple _ -> Comp (list ResultT))\n           (attrIdx : Fin.t _)\n           (a : Vector.t Type m)\n           (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n           (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n           (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n           (r_n : UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : Comp nat :=\n    (fix Iterate_Equiv_For_UnConstrQuery_In_body' (m : nat) :=\n    match m return (Fin.t m -> Comp nat) -> _\n    with\n    | 0 => fun results => ret 0\n    | S n'' => fun results =>\n        res <- results Fin.F1;\n        res' <- Iterate_Equiv_For_UnConstrQuery_In_body' n'' (fun idx => results (Fin.FS idx));\n        ret (res + res')\n    end) _ (fun idx => Count (For (UnConstrQuery_In r_n idx\n                                             (fun tup => body (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj idx tup))))).\n\n  Lemma refine_Iterate_Equiv_QueryResultComp_body\n        m\n        {ResultT : Type}\n        (heading : RawHeading)\n        (headings : Fin.t m -> RawHeading)\n        (Ensembles : forall (idx : Fin.t m),\n            @IndexedEnsemble (@RawTuple (headings idx)))\n        (inj_Tuple : forall (idx : Fin.t m),\n            @RawTuple (headings idx)\n            -> @RawTuple heading)\n        (body : @RawTuple heading -> Comp (list ResultT))\n    : refineEquiv\n        (results <- Iterate_Equiv_QueryResultComp heading headings Ensembles inj_Tuple;\n           FlattenCompList.flatten_CompList (map body results))\n        (Iterate_Equiv_QueryResultComp_body heading headings Ensembles inj_Tuple body).\n  Proof.\n    split.\n    - induction m; simpl.\n      + simplify with monad laws.\n        simpl; reflexivity.\n      + simplify with monad laws.\n        setoid_rewrite <- IHm.\n        repeat setoid_rewrite refineEquiv_bind_bind.\n        f_equiv; intro.\n        rewrite refineEquiv_swap_bind.\n        rewrite (refineEquiv_swap_bind\n                   (FlattenCompList.flatten_CompList (map (fun tup : RawTuple => body (inj_Tuple Fin.F1 tup)) a))).\n        f_equiv; intro.\n        induction a; simpl; simplify with monad laws.\n        * setoid_rewrite refineEquiv_bind_unit.\n          simpl; setoid_rewrite refineEquiv_unit_bind.\n          reflexivity.\n        * repeat setoid_rewrite refineEquiv_bind_bind.\n          simpl.\n          rewrite refineEquiv_swap_bind.\n          f_equiv; intro.\n          rewrite <- refineEquiv_bind_bind, IHa.\n          simplify with monad laws.\n          setoid_rewrite refineEquiv_bind_unit.\n          setoid_rewrite <- List.app_assoc.\n          reflexivity.\n    - induction m; simpl.\n      + setoid_rewrite refineEquiv_bind_unit.\n        simpl; reflexivity.\n      + repeat setoid_rewrite refineEquiv_bind_bind.\n        setoid_rewrite IHm.\n        repeat setoid_rewrite refineEquiv_bind_bind.\n        f_equiv; intro.\n        rewrite refineEquiv_swap_bind.\n        setoid_rewrite (refineEquiv_swap_bind\n                          _\n                          (Iterate_Equiv_QueryResultComp heading (fun idx : Fin.t m => headings (Fin.FS idx))\n                                                         (fun idx : Fin.t m => Ensembles (Fin.FS idx))\n                                                         (fun (idx : Fin.t m) (tup : RawTuple) => inj_Tuple (Fin.FS idx) tup))).\n        setoid_rewrite refineEquiv_bind_unit.\n        f_equiv; intro.\n        revert a0.\n        induction a; simpl; intros; simplify with monad laws.\n        * setoid_rewrite refineEquiv_bind_unit.\n          reflexivity.\n        * repeat setoid_rewrite refineEquiv_bind_bind.\n          repeat setoid_rewrite refineEquiv_bind_unit.\n          setoid_rewrite map_app.\n          simpl.\n          rewrite <- (refineEquiv_swap_bind (body (inj_Tuple Fin.F1 a))).\n          f_equiv; intro.\n          setoid_rewrite map_app in IHa.\n          setoid_rewrite <- refineEquiv_bind_bind; rewrite <- IHa.\n          repeat setoid_rewrite refineEquiv_bind_bind.\n          setoid_rewrite refineEquiv_bind_unit.\n          setoid_rewrite <- List.app_assoc.\n          f_equiv; intro.\n  Qed.\n\n  Lemma refine_UnIndexedEnsembleListEquivalence {A}\n    : forall s s',\n      (forall l, UnIndexedEnsembleListEquivalence s' l\n                 -> UnIndexedEnsembleListEquivalence s l)\n      -> refine {queriedList : list A | UnIndexedEnsembleListEquivalence s queriedList}\n                {queriedList : list A | UnIndexedEnsembleListEquivalence s' queriedList}.\n  Proof.\n    intros ? ?; computes_to_inv; computes_to_econstructor.\n    computes_to_inv.\n    eauto.\n  Qed.\n\n  Lemma UnIndexedEnsembleListEquivalence_app {A} :\n    forall (P Q : IndexedEnsemble) (l l' : list A),\n      Disjoint _ (fun idx => exists tup,\n                      In _ P {| elementIndex := idx;\n                                indexedElement := tup |})\n               (fun idx => exists tup,\n                    In _ Q {| elementIndex := idx;\n                              indexedElement := tup |})\n      -> UnIndexedEnsembleListEquivalence P l\n      -> UnIndexedEnsembleListEquivalence Q l'\n      -> UnIndexedEnsembleListEquivalence (Union _ P Q) (l ++ l').\n  Proof.\n    unfold UnIndexedEnsembleListEquivalence; intros.\n    destruct_ex; intuition.\n    eexists (x0 ++ x)%list; intuition; eauto.\n    - rewrite map_app; congruence.\n    - apply in_or_app.\n      setoid_rewrite <- H1; setoid_rewrite <- H3;\n        destruct H4; intuition.\n    - apply in_app_or in H4.\n      setoid_rewrite <- H1 in H4; setoid_rewrite <- H3 in H4.\n      intuition.\n    - rewrite map_app; apply NoDup_app_in_iff; intuition.\n      apply in_map_iff in H4; apply in_map_iff in H7;\n        destruct_ex; intuition; subst.\n      apply H1 in H10; apply H3 in H9.\n      inversion H; subst.\n      eapply (H0 (elementIndex x2)).\n      destruct x3; destruct x2; subst; simpl in *.\n      econstructor; unfold In.\n      eexists; eauto.\n      rewrite H4; eexists; eauto.\n  Qed.\n\n  Lemma refine_UnConstrQuery_In_DecomposeRawQueryStructureSchema_AbsR\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_o : UnConstrQueryStructure qs_schema)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      refine (UnConstrQuery_In r_o schemaIdx body) (UnConstrQuery_In (fst r_n) schemaIdx body).\n  Proof.\n    intros.\n    unfold UnConstrQuery_In, QueryResultComp; f_equiv.\n    rewrite refine_UnIndexedEnsembleListEquivalence.\n    reflexivity.\n    intros.\n    eapply UnIndexedEnsembleListEquivalence_Same_set; eauto.\n    destruct H.\n    unfold Same_set in *; intuition eauto.\n    apply H.\n    apply H.\n  Qed.\n\n  Lemma refine_Iterate_Equiv_QueryResultComp\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_o : UnConstrQueryStructure qs_schema)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      refine (UnConstrQuery_In r_o schemaIdx body)\n             (Iterate_Equiv_QueryResultComp_body\n                _ _\n                (GetUnConstrRelation (snd r_n))\n                (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj) body).\n  Proof.\n    intros.\n    erewrite refine_UnConstrQuery_In_DecomposeRawQueryStructureSchema_AbsR by eassumption.\n    rewrite <- refine_Iterate_Equiv_QueryResultComp_body.\n    unfold UnConstrQuery_In, QueryResultComp; f_equiv.\n    rewrite refine_UnIndexedEnsembleListEquivalence.\n    - unfold DecomposeRawQueryStructureSchema; simpl.\n      intros; rewrite <- refine_UnIndexedEnsembleListEquivalence_Iterate_Equiv_QueryResultComp.\n      + reflexivity.\n      + intros; destruct H as [? [? [? [? ?] ] ] ].\n        intro; pose proof (H5 _ _ _ _ H1 H2 H0); simpl in *; eauto.\n    - unfold UnIndexedEnsembleListEquivalence; simpl; intros.\n      destruct_ex; intuition; subst.\n      eexists x; intuition eauto.\n      apply H in H1.\n      apply H0.\n      eexists _, _; split; eauto.\n      simpl; destruct x0; simpl; f_equal.\n      symmetry; eapply Tuple_DecomposeRawQueryStructure_inj_inverse.\n      unfold In in *; apply H0 in H1; destruct_ex; intuition; subst.\n      apply (proj1 (proj2 H)) in H4; eassumption.\n  Qed.\n\n    Lemma refine_Iterate_For_UnConstrQuery_In_QueryResultComp\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : refine (For (Iterate_Equiv_QueryResultComp_body\n                _ _\n                (GetUnConstrRelation (snd r_n))\n                (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj) body))\n             (Iterate_Equiv_For_UnConstrQuery_In_body\n                schemaIdx body attrIdx a a_proj_index a_proj a_inj (snd r_n)).\n  Proof.\n    intros.\n    unfold Iterate_Equiv_For_UnConstrQuery_In_body.\n    destruct r_n as [ r_n' r_n].\n    unfold UnConstrQuery_In.\n    simpl.\n    generalize (GetUnConstrRelation r_n).\n    unfold DecomposeRawQueryStructureSchema; simpl.\n    generalize ((Tuple_DecomposeRawQueryStructure_inj' schemaIdx attrIdx a a_inj)).\n    simpl; clear.\n    generalize (DecomposeSchema (qschemaSchemas qs_schema)[@schemaIdx] attrIdx a); clear.\n    induction m; simpl; intros.\n    - rewrite refine_For_List; reflexivity.\n    - revert i i0 IHm.\n      pattern m, t; apply Vector.caseS; simpl; clear t; intros.\n      setoid_rewrite <- (IHm t (fun idx => i (Fin.FS idx)) (fun idx => i0 (Fin.FS idx))).\n      Local Transparent Query_For.\n      unfold Query_For.\n      autorewrite with monad laws.\n      clear; intros ? ?; computes_to_inv; subst.\n      repeat computes_to_econstructor; eauto using Permutation_app.\n      Local Opaque Query_For.\n  Qed.\n\n  Corollary refine_Iterate_For_UnConstrQuery_In\n          {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_o : UnConstrQueryStructure qs_schema)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      refine (For (UnConstrQuery_In r_o schemaIdx body))\n             (Iterate_Equiv_For_UnConstrQuery_In_body\n                schemaIdx body attrIdx a a_proj_index a_proj a_inj (snd r_n)).\n  Proof.\n    intros; rewrite <- refine_Iterate_For_UnConstrQuery_In_QueryResultComp.\n    rewrite (refine_Iterate_Equiv_QueryResultComp _ H); reflexivity.\n  Qed.\n\n  Lemma refine_Iterate_Count_For_UnConstrQuery_In_QueryResultComp\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : refine (Count (For (Iterate_Equiv_QueryResultComp_body\n                _ _\n                (GetUnConstrRelation (snd r_n))\n                (Tuple_DecomposeRawQueryStructure_inj' _ _ a a_inj) body)))\n             (Iterate_Equiv_Count_For_UnConstrQuery_In_body\n                schemaIdx body attrIdx a a_proj_index a_proj a_inj (snd r_n)).\n  Proof.\n    intros.\n    unfold Iterate_Equiv_Count_For_UnConstrQuery_In_body.\n    destruct r_n as [ r_n' r_n].\n    unfold UnConstrQuery_In.\n    simpl.\n    generalize (GetUnConstrRelation r_n).\n    unfold DecomposeRawQueryStructureSchema; simpl.\n    generalize ((Tuple_DecomposeRawQueryStructure_inj' schemaIdx attrIdx a a_inj)).\n    simpl; clear.\n    generalize (DecomposeSchema (qschemaSchemas qs_schema)[@schemaIdx] attrIdx a); clear.\n    induction m; simpl; intros.\n    - rewrite refine_For_List; rewrite refine_Count; simplify with monad laws; reflexivity.\n    - revert i i0 IHm.\n      pattern m, t; apply Vector.caseS; simpl; clear t; intros.\n      setoid_rewrite <- (IHm t (fun idx => i (Fin.FS idx)) (fun idx => i0 (Fin.FS idx))).\n      Local Transparent Query_For.\n      Local Transparent Count.\n      unfold Query_For.\n      unfold Count.\n      autorewrite with monad laws.\n      clear; intros ? ?; computes_to_inv; subst.\n      repeat computes_to_econstructor; eauto using Permutation_app.\n      rewrite app_length.\n      erewrite (Permutation_length H''''), Permutation_length; eauto using Permutation_app.\n      Local Opaque Query_For.\n      Local Opaque Count.\n  Qed.\n\n  Corollary refine_Iterate_Count_For_UnConstrQuery_In\n          {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_o : UnConstrQueryStructure qs_schema)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      refine (Count (For (UnConstrQuery_In r_o schemaIdx body)))\n             (Iterate_Equiv_Count_For_UnConstrQuery_In_body\n                schemaIdx body attrIdx a a_proj_index a_proj a_inj (snd r_n)).\n  Proof.\n    intros; rewrite (refine_Iterate_Equiv_QueryResultComp _ H),\n            refine_Iterate_Count_For_UnConstrQuery_In_QueryResultComp;\n    reflexivity.\n  Qed.\n\n  Lemma refine_Query_Where_Cond :\n    forall (ResultT : Type) (P Q : Prop)\n           (body : Comp (list ResultT)),\n      (P <-> Q)\n      -> refine (Query_Where P body)\n                (Query_Where Q body).\n  Proof.\n    unfold pointwise_relation, Query_Where; intros.\n    intros ? ?; intuition; computes_to_inv; computes_to_econstructor.\n    intuition; intros.\n  Qed.\n\n  Lemma refine_flatten_CompList_func' :\n    forall (A B : Type) (l : list A) (f f' : A -> Comp (list B)),\n      (forall v, List.In v l -> refine (f v) (f' v))\n      -> refine (FlattenCompList.flatten_CompList (map f l)) (FlattenCompList.flatten_CompList (map f' l)).\n  Proof.\n    induction l; simpl; intros.\n    - reflexivity.\n    - rewrite H by eauto.\n      f_equiv; intro.\n      rewrite IHl by eauto.\n      reflexivity.\n  Qed.\n\n  Lemma refine_Query_Where_True_Cond :\n    forall (ResultT : Type) (P : Prop )\n           (body : Comp (list ResultT)),\n      P\n      -> refine (Query_Where P body) body.\n  Proof.\n    intros.\n    etransitivity; intro.\n    apply refine_Query_Where_Cond with (Q := True).\n    intuition; intros.\n    intros; computes_to_econstructor; intuition.\n  Qed.\n\n  Lemma refine_Query_Where_False_Cond :\n    forall (ResultT : Type) (P : Prop )\n           (body : Comp (list ResultT)),\n      ~ P\n      -> refine (Query_Where P body) (ret nil).\n  Proof.\n    intros.\n    etransitivity; intro.\n    apply refine_Query_Where_Cond with (Q := False).\n    intuition; intros.\n    intros; computes_to_econstructor; intuition;\n      computes_to_inv; eauto.\n  Qed.\n\n  Lemma flatten_CompList_nil':\n    forall (A B : Type)(seq : list A),\n      refine (FlattenCompList.flatten_CompList (map (fun _ => ret nil) seq)) (ret (@nil B)).\n  Proof.\n    induction seq; simpl; unfold refine; intros; computes_to_inv; subst; eauto.\n  Qed.\n\n  Lemma refine_QueryResultComp_body_Where_False\n        {ResultT : Type}\n        {heading}\n        (body : @RawTuple heading -> Comp (list ResultT))\n        P R\n    :\n      (forall tup, In _ R tup -> ~ P (indexedElement tup))\n      -> FiniteEnsemble R\n      -> refine (QueryResultComp R (fun tup => Where (P tup) (body tup)))\n                (ret nil).\n  Proof.\n    intros; unfold QueryResultComp.\n    destruct H0.\n    refine pick val _; eauto.\n    simplify with monad laws.\n    rewrite refine_flatten_CompList_func' with (f' := fun _ => ret nil).\n    apply flatten_CompList_nil'.\n    intros; computes_to_econstructor; computes_to_inv; subst;\n      intuition.\n    unfold UnIndexedEnsembleListEquivalence in H0; destruct_ex;\n      intuition; subst.\n    apply in_map_iff in H1; destruct_ex; intuition; subst.\n    apply H in H2; intuition.\n    apply H0; eauto.\n  Qed.\n\n  Lemma refine_Iterate_Equiv_QueryResultComp_body_Where_False\n        m\n        {ResultT : Type}\n        (heading : RawHeading)\n        (headings : Fin.t m -> RawHeading)\n        (Ensembles : forall (idx : Fin.t m),\n            @IndexedEnsemble (@RawTuple (headings idx)))\n        (inj_Tuple : forall (idx : Fin.t m),\n            @RawTuple (headings idx)\n            -> @RawTuple heading)\n        (FiniteEnsembles : forall idx, FiniteEnsemble (Ensembles idx))\n        (body : @RawTuple heading -> Comp (list ResultT))\n        P\n    :\n      (forall idx tup, In _ (Ensembles idx) tup -> ~ P (inj_Tuple idx (indexedElement tup)))\n      -> refine\n           (Iterate_Equiv_QueryResultComp_body heading headings Ensembles inj_Tuple\n                                               (fun tup : RawTuple => Where (P tup)\n                                                                            (body tup) ))\n           (ret nil).\n  Proof.\n    induction m; simpl; intros.\n    - reflexivity.\n    - rewrite refine_QueryResultComp_body_Where_False; eauto.\n      simplify with monad laws.\n      apply IHm; eauto.\n  Qed.\n\n  Lemma refine_Iterate_Equiv_QueryResultComp_body_Where_And_eq\n        m\n        {ResultT : Type}\n        (heading : RawHeading)\n    : forall (headings : Fin.t m -> RawHeading)\n             (Ensembles : forall (idx : Fin.t m),\n                 @IndexedEnsemble (@RawTuple (headings idx)))\n             (inj_Tuple : forall (idx : Fin.t m),\n                 @RawTuple (headings idx)\n                 -> @RawTuple heading)\n             (FiniteEnsembles : forall idx, FiniteEnsemble (Ensembles idx))\n             (body : @RawTuple heading -> Comp (list ResultT))\n             idx\n             P Q,\n      (forall idx',\n          idx <> idx'\n          -> forall tup,\n            In _ (Ensembles idx') tup\n            -> ~ (P (inj_Tuple _ (indexedElement tup))))\n      -> (forall tup,\n             In _ (Ensembles idx) tup\n             -> P (inj_Tuple _ (indexedElement tup)))\n      -> refine\n           (Iterate_Equiv_QueryResultComp_body\n              heading headings Ensembles inj_Tuple\n              (fun tup => Where (P tup /\\ Q tup)\n                                (body tup)))\n           (QueryResultComp (Ensembles idx)\n                            (fun tup => Where (Q (inj_Tuple _ tup))\n                                              (body (inj_Tuple idx tup)))).\n  Proof.\n    induction m; simpl; intros.\n    - intros; inversion idx.\n    - destruct (fin_eq_dec idx Fin.F1).\n      + etransitivity.\n        * apply refine_under_bind_both; intros.\n          apply refine_under_bind; intros.\n          eapply refine_flatten_CompList_func'.\n          intros; rewrite (refine_Query_Where_Cond (Q := Q (inj_Tuple _ v))).\n          finish honing.\n          intros; computes_to_inv; unfold UnIndexedEnsembleListEquivalence in H1;\n            destruct_ex; intuition; subst.\n          apply in_map_iff in H2; destruct_ex; intuition; subst.\n          apply H1 in H6; apply H0 in H6; intuition.\n          rewrite e.\n          rewrite refine_Iterate_Equiv_QueryResultComp_body_Where_False.\n          simplify with monad laws;\n            rewrite app_nil_r; finish honing.\n          intuition eauto.\n          unfold not; intros; eapply H; intuition eauto.\n          rewrite e in H4; discriminate.\n        * simplify with monad laws.\n          unfold UnConstrQuery_In, QueryResultComp.\n          rewrite e.\n          reflexivity.\n      + rewrite refine_QueryResultComp_body_Where_False.\n        * simplify with monad laws.\n          revert IHm headings Ensembles inj_Tuple FiniteEnsembles P H H0 n; pattern m, idx.\n          apply Fin.caseS; simpl; intros.\n          congruence.\n          apply (IHm (fun n => headings (Fin.FS n))\n                     (fun n => Ensembles (Fin.FS n))\n                     (fun n tup => inj_Tuple (Fin.FS n) tup));\n            intros; eauto.\n          intro.\n          eapply (H (Fin.FS idx')); eauto.\n          intro; apply H1; apply Fin.FS_inj; eauto.\n        * unfold not; intros.\n          eapply H; intuition eauto.\n        * apply FiniteEnsembles.\n  Qed.\n\n  Lemma refine_QueryIn_Where\n        {m : nat}\n        {qs_schema : RawQueryStructureSchema}\n        {ResultT}\n        (schemaIdx : Fin.t _)\n        (body : @RawTuple _ -> Comp (list ResultT))\n        (attrIdx : Fin.t _)\n        (a : Vector.t Type m)\n        (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n        (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n        (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n        (r_o : UnConstrQueryStructure qs_schema)\n        (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n        idx\n        Q\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      ->\n      refine (UnConstrQuery_In r_o schemaIdx\n                               (fun tup => Where (a_proj_index (GetAttributeRaw tup attrIdx) =  idx\n                                                  /\\ Q tup)\n                                                 (body tup)))\n             (UnConstrQuery_In (snd r_n) idx (fun tup =>\n                                                Where (Q (Tuple_DecomposeRawQueryStructure_inj' _ _ _ a_inj _ tup))\n                                                      (body\n                                                         (Tuple_DecomposeRawQueryStructure_inj' _ _ _ a_inj _ tup)))).\n  Proof.\n    intros; rewrite (@refine_Iterate_Equiv_QueryResultComp m); eauto.\n    apply refine_Iterate_Equiv_QueryResultComp_body_Where_And_eq  with\n    (idx := idx); eauto.\n    - intros; apply H.\n    - intros; apply H in H1; rewrite H1; congruence.\n    - intros; apply H; eauto.\n  Qed.\n\n  Corollary refine_QueryIn_Where_True\n            {m : nat}\n            {qs_schema : RawQueryStructureSchema}\n            {ResultT}\n            (schemaIdx : Fin.t _)\n            (body : @RawTuple _ -> Comp (list ResultT))\n            (attrIdx : Fin.t _)\n            (a : Vector.t Type m)\n            (a_proj_index : Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx -> Fin.t m)\n            (a_proj : forall (attr : Vector.nth _ attrIdx), a[@a_proj_index attr])\n            (a_inj : forall idx, Vector.nth a idx -> Vector.nth (AttrList (GetNRelSchemaHeading (qschemaSchemas qs_schema) schemaIdx)) attrIdx)\n            (r_o : UnConstrQueryStructure qs_schema)\n            (r_n : UnConstrQueryStructure qs_schema * UnConstrQueryStructure (DecomposeRawQueryStructureSchema qs_schema schemaIdx attrIdx a))\n            idx\n    : DecomposeRawQueryStructureSchema_AbsR schemaIdx attrIdx a a_proj_index a_proj a_inj r_o r_n\n      -> refine (UnConstrQuery_In r_o schemaIdx\n                                  (fun tup => Where (a_proj_index (GetAttributeRaw tup attrIdx) = idx)\n                                                    (body tup)))\n                (UnConstrQuery_In (snd r_n) idx (fun tup =>\n                                                   body\n                                                     (Tuple_DecomposeRawQueryStructure_inj' _ _ _ a_inj _ tup))).\n  Proof.\n    etransitivity.\n    apply refine_UnConstrQuery_In; intro.\n    apply refine_Query_Where_Cond with\n    (Q := (a_proj_index (GetAttributeRaw a0 attrIdx) = idx) /\\ True);\n      intuition.\n    setoid_rewrite refine_QueryIn_Where; eauto.\n    apply refine_UnConstrQuery_In; intro.\n    apply refine_Query_Where_True_Cond; eauto.\n  Qed.\n\n  Arguments DecomposeRawQueryStructureSchema : simpl never.\n  Arguments DecomposeRawQueryStructureSchema_AbsR : simpl never.\n  Arguments inj_SumType : simpl never.\n  Arguments inj_SumType : simpl never.\n  Arguments SumType_proj : simpl never.\n  Arguments SumType_index : simpl never.\n  Arguments Vector.nth _ _ _ !_ / .\n\n  Definition EnumIDs := [\"A\"; \"NS\"; \"CNAME\"; \"SOA\" ].\n  Definition EnumID := Fin.t 4.\n  Definition EnumTypes := [nat : Type; string : Type; nat : Type; list nat : Type].\n  Definition EnumType := SumType EnumTypes.\n\n  Definition EESchema :=\n    Query Structure Schema\n          [ relation \"foo\" has\n                     schema <\"A\" :: nat, \"BID\" :: EnumID, \"B\" :: EnumType>\n            (*where (fun t => ibound (indexb t!\"BID\") = SumType_index _ t!\"B\" ) and (fun t t' => True) *);\n              relation \"bar\" has\n                       schema <\"C\" :: nat, \"D\" :: list string>\n          ]\n          enforcing [ ].\n\n  Definition EESpec : ADT _ :=\n    Def ADT {\n          rep := QueryStructure EESchema,\n\n                 Def Constructor \"Init\" : rep := empty,,\n\n                                                      Def Method1 \"AddData\" (this : rep) (t : _) : rep * bool :=\n            Insert t into this!\"foo\",\n\n            Def Method1 \"Process\" (this : rep) (p : EnumID) : rep * list _ :=\n              results <- For (r in this!\"foo\")\n                      Where ( (SumType_index _ r!\"B\") = p)\n                      Return r;\n          ret (this, results)}.\n\n  Definition EEImpl : FullySharpened EESpec.\n    unfold EESpec.\n    start sharpening ADT.\n    start_honing_QueryStructure'.\n    let AbsR' := constr:(@DecomposeRawQueryStructureSchema_AbsR' _ EESchema ``\"foo\" ``\"B\"\n                                                                 id EnumTypes id id) in  hone representation using AbsR'.\n    {\n      simplify with monad laws.\n      apply refine_pick_val.\n      apply DecomposeRawQueryStructureSchema_empty_AbsR.\n    }\n    { (* Insert *)\n      simpl in *; simplify with monad laws; cbv beta; simpl.\n      rewrite (refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv H0).\n      unfold H; eapply refine_under_bind; intros.\n      apply refine_under_bind_both; intros.\n      apply refine_pick_val.\n      eapply (DecomposeRawQueryStructureSchema_Insert_AbsR_eq H0).\n      eapply refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv in H1;\n        eauto.\n      eapply refine_UnConstrFreshIdx_DecomposeRawQueryStructureSchema_AbsR_Equiv';\n        eauto.\n      finish honing.\n    }\n    { (* Query *)\n      simpl in *; simplify with monad laws; cbv beta; simpl.\n      rewrite refine_For; simplify with monad laws.\n      rewrite (refine_QueryIn_Where_True _ H0).\n      simpl.\n      (* More refinements here. *)\n  Abort.\nEnd DecomposeEnumField.\n\nLtac simplify_GetAttributeRaw_inj :=\n  match goal with\n    |- context [UnConstrQuery_In ?r_n ?Ridx (fun tup =>  Query_Where (@?P tup) _)] =>\n    rewrite (fun ResultT =>\n               @refine_UnConstrQuery_In_Query_Where_Cond _ r_n Ridx ResultT P);\n    [ | intros; simpl;\n        match goal with\n          |- context [GetAttribute (Tuple_DecomposeRawQueryStructure_inj'\n                                      (qs_schema := ?qs_schema)\n                                      ?schemaIdx ?attrIdx ?a ?a_inj ?tag ?tup) ?attrIdx'] =>\n          let eq := eval compute in (fin_eq_dec attrIdx (ibound (indexb attrIdx'))) in\n              match eq with\n              | left ?e =>\n                let H := fresh in\n                assert (GetAttribute (Tuple_DecomposeRawQueryStructure_inj'\n                                        (qs_schema := qs_schema)\n                                        schemaIdx attrIdx a a_inj tag tup) attrIdx'\n                        = a_inj tag (GetAttributeRaw tup (ibound (indexb attrIdx')))) as H by reflexivity;\n                simpl in H; rewrite H; clear H; finish honing\n              |right ?e =>\n               let H := fresh in\n               assert (GetAttribute (Tuple_DecomposeRawQueryStructure_inj'\n                                       (qs_schema := qs_schema)\n                                       schemaIdx attrIdx a a_inj tag tup) attrIdx'\n                       = GetAttributeRaw tup (ibound (indexb attrIdx'))) as H by reflexivity;\n               simpl in H; rewrite H; clear H; finish honing\n              end\n        | |- context [GetAttributeRaw (Tuple_DecomposeRawQueryStructure_inj'\n                                      (qs_schema := ?qs_schema)\n                                      ?schemaIdx ?attrIdx ?a ?a_inj ?tag ?tup) ?attrIdx'] =>\n          let eq := eval compute in (fin_eq_dec attrIdx attrIdx') in\n              match eq with\n              | left ?e =>\n                let H := fresh in\n                assert (GetAttributeRaw (Tuple_DecomposeRawQueryStructure_inj'\n                                        (qs_schema := qs_schema)\n                                        schemaIdx attrIdx a a_inj tag tup) attrIdx'\n                        = a_inj tag (GetAttributeRaw tup  attrIdx')) as H by reflexivity;\n                simpl in H; rewrite H; clear H; finish honing\n              |right ?e =>\n               let H := fresh in\n               assert (GetAttributeRaw (Tuple_DecomposeRawQueryStructure_inj'\n                                       (qs_schema := qs_schema)\n                                       schemaIdx attrIdx a a_inj tag tup) attrIdx'\n                       = GetAttributeRaw tup attrIdx') as H by reflexivity;\n               simpl in H; rewrite H; clear H; finish honing\n              end\n        end]\n  end.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Examples/DnsServer/DecomposeSumField.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.1721255292117141}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.NotationsCustomEntry.\nRequire Import bedrock2.ToCString.\nRequire Import coqutil.Word.Interface.\nRequire Import Bedrock2Experiments.LibBase.MMIOLabels.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.Aes.Constants.\nRequire Import Bedrock2Experiments.Aes.AesSemantics.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIO.\nImport Syntax.Coercions List.ListNotations.\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope list_scope.\n\nSection Impl.\n  (* instantiated to `expr.literal SOME_Z_CONST` for proving and\n     compilation using the bedrock2 compiler, instantiated to\n     `expr.var STRING_NAME_OF_CONST` for pretty-printing to C code *)\n  Context {constant_vars : aes_constants expr}.\n\n  (* Notations for small constants *)\n  Local Notation \"0\" := (expr.literal 0) (in custom bedrock_expr).\n  Local Notation \"1\" := (expr.literal 1) (in custom bedrock_expr).\n  Local Notation \"2\" := (expr.literal 2) (in custom bedrock_expr).\n  Local Notation \"3\" := (expr.literal 3) (in custom bedrock_expr).\n  Local Notation \"4\" := (expr.literal 4) (in custom bedrock_expr).\n  Local Notation \"5\" := (expr.literal 5) (in custom bedrock_expr).\n  Local Notation \"6\" := (expr.literal 6) (in custom bedrock_expr).\n  Local Notation \"7\" := (expr.literal 7) (in custom bedrock_expr).\n  Local Notation \"8\" := (expr.literal 8) (in custom bedrock_expr).\n  Local Notation \"9\" := (expr.literal 9) (in custom bedrock_expr).\n\n  (**** aes.c\n    void aes_init(aes_cfg_t aes_cfg) {\n      REG32(AES_CTRL(0)) =\n          (aes_cfg.operation << AES_CTRL_OPERATION) |\n          ((aes_cfg.mode & AES_CTRL_MODE_MASK) << AES_CTRL_MODE_OFFSET) |\n          ((aes_cfg.key_len & AES_CTRL_KEY_LEN_MASK) << AES_CTRL_KEY_LEN_OFFSET) |\n          (aes_cfg.manual_operation << AES_CTRL_MANUAL_OPERATION);\n    };\n   ***)\n  Definition aes_init : func :=\n    let aes_cfg_operation := \"aes_cfg_operation\" in\n    let aes_cfg_mode := \"aes_cfg_mode\" in\n    let aes_cfg_key_len := \"aes_cfg_key_len\" in\n    let aes_cfg_manual_operation := \"aes_cfg_manual_operation\" in\n    let cfg_val := \"cfg_val\" in\n    (\"b2_aes_init\",\n     ([aes_cfg_operation; aes_cfg_mode; aes_cfg_key_len;\n      aes_cfg_manual_operation],\n      [], bedrock_func_body:(\n      abs_mmio_write32 (AES_CTRL0,\n                     ((aes_cfg_operation << AES_CTRL_OPERATION) |\n                      ((aes_cfg_mode & AES_CTRL_MODE_MASK)\n                         << AES_CTRL_MODE_OFFSET) |\n                      ((aes_cfg_key_len & AES_CTRL_KEY_LEN_MASK)\n                         << AES_CTRL_KEY_LEN_OFFSET) |\n                      (aes_cfg_manual_operation << AES_CTRL_MANUAL_OPERATION)))\n    ))).\n\n  (**** aes.c\n    void aes_key_put(const void *key, aes_key_len_t key_len) {\n      // Determine how many key registers to use.\n      size_t num_regs_key_used;\n      if (key_len == kAes256) {\n        num_regs_key_used = 8;\n      } else if (key_len == kAes192) {\n        num_regs_key_used = 6;\n      } else {\n        num_regs_key_used = 4;\n      }\n\n      // Write the used key registers.\n      for (int i = 0; i < num_regs_key_used; ++i) {\n        REG32(AES_KEY0(0) + i * sizeof(uint32_t)) = ((uint32_t * )key)[i];\n      }\n      // Write the unused key registers (the AES unit requires all key registers to\n      // be written).\n      for (int i = num_regs_key_used; i < AES_NUM_REGS_KEY; ++i) {\n        REG32(AES_KEY0(0) + i * sizeof(uint32_t)) = 0x0;\n      }\n    }\n   ***)\n  Definition aes_key_put : func :=\n    let key := \"key\" in\n    let key_len := \"key_len\" in\n    let num_regs_key_used := \"num_regs_key_used\" in\n    let i := \"i\" in\n    (\"b2_key_put\",\n     ([key; key_len],\n      [], bedrock_func_body:(\n      if (key_len == kAes256) {\n        num_regs_key_used = 8\n      } else {\n        if (key_len == kAes192) {\n          num_regs_key_used = 6\n        } else {\n          num_regs_key_used = 4\n        }\n      };\n\n      i = 0 ;\n      while (i < num_regs_key_used) {\n        output! WRITE32 (AES_KEY00 + (i * 4), load4(key + (i * 4)));\n        i = i + 1\n      };\n\n      i = num_regs_key_used ;\n      while (i < AES_NUM_REGS_KEY) {\n        output! WRITE32 (AES_KEY00 + (i * 4), 0);\n        i = i + 1\n      }\n    ))).\n\n  (**** aes.c\n    void aes_iv_put(const void *iv) {\n      // Write the four initialization vector registers.\n      for (int i = 0; i < AES_NUM_REGS_IV; ++i) {\n        REG32(AES_IV0(0) + i * sizeof(uint32_t)) = ((uint32_t * )iv)[i];\n      }\n    }\n   ***)\n  Definition aes_iv_put : func :=\n    let iv := \"iv\" in\n    let i := \"i\" in\n    (\"b2_iv_put\",\n     ([iv], [], bedrock_func_body:(\n      i = 0 ;\n      while (i < AES_NUM_REGS_IV) {\n        output! WRITE32 (AES_IV00 + (i * 4), load4( iv + (i * 4) ));\n        i = i + 1\n      }\n    ))).\n\n  (**** aes.c\n    void aes_data_put(const void *data) {\n      // Write the four input data registers.\n      for (int i = 0; i < AES_NUM_REGS_DATA; ++i) {\n        REG32(AES_DATA_IN0(0) + i * sizeof(uint32_t)) = ((uint32_t * )data)[i];\n      }\n    }\n   ***)\n  Definition aes_data_put : func :=\n    let data := \"data\" in\n    let i := \"i\" in\n    (\"b2_data_put\",\n     ([data], [],\n      bedrock_func_body:(\n      i = 0 ;\n      while (i < AES_NUM_REGS_DATA) {\n        output! WRITE32 (AES_DATA_IN00 + (i * 4), load4( data + (i * 4) ));\n        i = i + 1\n      }\n    ))).\n\n  (**** aes.c\n    void aes_data_get(void *data) {\n      // Read the four output data registers.\n      for (int i = 0; i < AES_NUM_REGS_DATA; ++i) {\n        ((uint32_t * )data)[i] = REG32(AES_DATA_OUT0(0) + i * sizeof(uint32_t));\n      }\n    }\n   ***)\n  Definition aes_data_get : func :=\n    let data := \"data\" in\n    let val := \"val\" in\n    let i := \"i\" in\n    (\"b2_data_get\",\n     ([data], [],\n      bedrock_func_body:(\n      i = 0 ;\n      while (i < AES_NUM_REGS_DATA) {\n        io! val = READ32 ( AES_DATA_OUT00 + (i * 4) ) ;\n        store4( data + (i * 4), val ) ; (* data[i] = val *)\n        i = i + 1\n      }\n    ))).\n\n  (**** aes.c\n    bool aes_data_ready(void) {\n      return (REG32(AES_STATUS(0)) & (0x1u << AES_STATUS_INPUT_READY));\n    }\n   ***)\n  Definition aes_data_ready : func :=\n    let status := \"status\" in\n    let out := \"out\" in\n    (\"b2_data_ready\",\n     ([], [out],\n      bedrock_func_body:(\n      unpack! status = abs_mmio_read32(AES_STATUS0);\n      out = status & (1 << AES_STATUS_INPUT_READY)\n    ))).\n\n  (**** aes.c\n    bool aes_data_valid(void) {\n      return (REG32(AES_STATUS(0)) & (0x1u << AES_STATUS_OUTPUT_VALID));\n    }\n   ***)\n  Definition aes_data_valid : func :=\n    let status := \"status\" in\n    let out := \"out\" in\n    (\"b2_data_valid\",\n     ([], [out],\n      bedrock_func_body:(\n      unpack! status = abs_mmio_read32 (AES_STATUS0) ;\n      out = status & (1 << AES_STATUS_OUTPUT_VALID)\n    ))).\n\n  (**** aes.c\n    bool aes_idle(void) {\n      return (REG32(AES_STATUS(0)) & (0x1u << AES_STATUS_IDLE));\n    }\n   ***)\n  Definition aes_idle : func :=\n    let status := \"status\" in\n    let out := \"out\" in\n    (\"b2_idle\",\n     ([], [out],\n      bedrock_func_body:(\n      unpack! status = abs_mmio_read32 (AES_STATUS0) ;\n      out = status & (1 << AES_STATUS_IDLE)\n    ))).\n\n  (**** aes.c\n    void aes_data_put_wait(const void *data) {\n      // Wait for AES unit to be ready for new input data.\n      while (!aes_data_ready()) {\n      }\n\n      // Provide the input data.\n      aes_data_put(data);\n    }\n   ***)\n  Definition aes_data_put_wait : func :=\n    let data := \"data\" in\n    let is_ready := \"is_ready\" in\n    (\"b2_data_put_wait\",\n     ([data], [],\n      bedrock_func_body:(\n      is_ready = 0 ;\n      while (is_ready == 0) {\n        unpack! is_ready = aes_data_ready ()\n      };\n\n      aes_data_put (data)\n    ))).\n\n  (**** aes.c\n\n    void aes_data_get_wait(void *data) {\n      // Wait for AES unit to have valid output data.\n      while (!aes_data_valid()) {\n      }\n\n      // Get the data.\n      aes_data_get(data);\n    }\n   ***)\n  Definition aes_data_get_wait : func :=\n    let data := \"data\" in\n    let is_valid := \"is_valid\" in\n    (\"b2_data_get_wait\",\n     ([data], [],\n      bedrock_func_body:(\n      is_valid = 0 ;\n      while (is_valid == 0) {\n        unpack! is_valid = aes_data_valid ()\n      };\n\n      aes_data_get (data)\n    ))).\nEnd Impl.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/firmware/Aes/Aes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.17212552583420318}}
{"text": "Require Import Bool Arith List Omega ListSet.\nRequire Import Recdef Morphisms.\nRequire Import Program.Tactics.\nRequire Import Relation_Operators.\nRequire FMapList.\nRequire FMapFacts.\nRequire Import Classical.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import OrderedType OrderedTypeEx DecidableType.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Sorting.Permutation.\nImport ListNotations.\nRequire Import SImpECommon.\n\n(*******************************************************************************\n*\n* SYNTAX\n*\n*******************************************************************************)\n\nSection Syntax.\n  Definition enclave : Type := nat.\n  Inductive mode : Type :=\n  | Normal : mode\n  | Encl : enclave -> mode.\n  \n  Inductive exp : Type :=\n  | Enat : nat -> exp\n  | Evar : var -> exp\n  | Eadd : exp -> exp -> exp\n  | Eloc : location -> exp\n  | Ederef : exp -> exp\n  | Elambda : mode -> com -> exp\n                                   \n  with com : Type :=\n  | Cskip : com\n  | Cassign : var -> exp -> com\n  | Cdeclassify : var -> exp -> com\n  | Cupdate : exp -> exp -> com\n  | Coutput : exp -> sec_level -> com\n  | Ccall : exp -> com\n  | Cenclave : enclave -> com -> com\n  | Cseq : list com -> com\n  | Cif : exp -> com -> com -> com\n  | Cwhile : exp -> com -> com.\n\n  Inductive val : Type :=\n  | Vlambda : mode -> com -> val\n  | Vnat : nat -> val\n  | Vloc : location -> val.\n\n  Function forall_subexp (e: exp) (P: exp -> Prop) : Prop :=\n    P e /\\\n    match e with\n    | Eadd e1 e2 => forall_subexp e1 P /\\ forall_subexp e2 P\n    | Ederef e' => forall_subexp e' P\n    | Elambda _ c => forall_subexp' c P\n    | _ => True\n    end\n  with forall_subexp' (c: com) (P: exp -> Prop) : Prop :=\n    match c with\n    | Cassign _ e => forall_subexp e P\n    | Cdeclassify _ e => forall_subexp e P\n    | Cupdate e1 e2 => forall_subexp e1 P /\\ forall_subexp e2 P\n    | Ccall e => forall_subexp e P\n    | Cenclave _ c' => forall_subexp' c' P\n    | Cseq cs => fold_left (fun acc c => forall_subexp' c P /\\ acc) cs True\n    | Cif e c1 c2 =>\n      forall_subexp e P /\\ forall_subexp' c1 P /\\ forall_subexp' c2 P\n    | Cwhile e c' => forall_subexp e P /\\ forall_subexp' c' P\n    | _ => True\n    end.\n\n  Definition exp_novars (e: exp) : Prop :=\n    forall_subexp e (fun e =>\n                       match e with\n                       | Evar _ => False\n                       | _ => True\n                       end).\n  \nEnd Syntax.\n\nSection Induction.\n  Variable P : com -> Type.\n  Variable P0: exp -> Type.\n  \n  Inductive Forall' (Q : com -> Type) : list com -> Type :=\n  | Forall_nil' : Forall' Q nil\n  | Forall_cons' : forall x l, Q x -> Forall' Q l -> Forall' Q (x::l).\n\n  Hypothesis Enat_case : forall n, P0 (Enat n).\n  Hypothesis Evar_case : forall x, P0 (Evar x).\n  Hypothesis Eadd_case : forall e1 e2,\n      P0 e1 -> P0 e2 -> P0 (Eadd e1 e2).\n  Hypothesis Eloc_case : forall l, P0 (Eloc l).\n  Hypothesis Ederef_case : forall e,\n      P0 e -> P0 (Ederef e).\n  Hypothesis Elambda_case : forall md c,\n      P c -> P0 (Elambda md c).\n\n  Hypothesis Cskip_case : P Cskip.\n  Hypothesis Cassign_case : forall x e,\n      P0 e -> P (Cassign x e).  \n  Hypothesis Cdeclassify_case : forall x e,\n      P0 e -> P (Cdeclassify x e).\n  Hypothesis Cupdate_case : forall e1 e2,\n      P0 e1 -> P0 e2 -> P (Cupdate e1 e2).\n  Hypothesis Coutput_case : forall e sl,\n      P0 e -> P (Coutput e sl).\n  Hypothesis Ccall_case : forall e,\n      P0 e -> P (Ccall e).\n  Hypothesis Cenclave_case : forall enc c,\n      P c -> P (Cenclave enc c).\n  Hypothesis Cseq_case : forall coms,\n      Forall' P coms -> P (Cseq coms).\n  Hypothesis Cif_case : forall e c1 c2,\n      P0 e -> P c1 -> P c2 -> P (Cif e c1 c2).\n  Hypothesis Cwhile_case : forall e c,\n      P0 e -> P c -> P (Cwhile e c).\n\n  Fixpoint com_rect' (c: com) : P c :=\n    match c with\n    | Cskip => Cskip_case\n    | Cassign x e => Cassign_case x e (exp_rect' e)\n    | Cdeclassify x e => Cdeclassify_case x e (exp_rect' e)\n    | Cupdate e1 e2 => Cupdate_case e1 e2 (exp_rect' e1) (exp_rect' e2)\n    | Coutput e sl => Coutput_case e sl (exp_rect' e)\n    | Ccall e => Ccall_case e (exp_rect' e)\n    | Cenclave enc c => Cenclave_case enc c (com_rect' c)\n    | Cseq coms =>\n      Cseq_case coms\n                ((fix com_list_rect (coms: list com) : Forall' P coms :=\n                    match coms with\n                    | [] => Forall_nil' P\n                    | h :: t => Forall_cons' P h t (com_rect' h) (com_list_rect t)\n                    end) coms)\n    | Cif e c1 c2 =>\n      Cif_case e c1 c2 (exp_rect' e) (com_rect' c1) (com_rect' c2)\n    | Cwhile e c => Cwhile_case e c (exp_rect' e) (com_rect' c)\n    end\n      \n  with\n  exp_rect' (e: exp) : P0 e :=\n    match e with\n    | Enat n => Enat_case n\n    | Evar x => Evar_case x\n    | Eadd e1 e2 => Eadd_case e1 e2 (exp_rect' e1) (exp_rect' e2)\n    | Eloc l => Eloc_case l\n    | Ederef e => Ederef_case e (exp_rect' e)\n    | Elambda md c => Elambda_case md c (com_rect' c)\n    end.\n  \nEnd Induction.\n\nSection Decidability.\n\n  Ltac auto_decide :=\n    try match goal with\n        | [x : nat, y : nat |- _] => destruct (Nat.eq_dec x y)\n        | [x : var, y : var |- _] => destruct (Nat.eq_dec x y)\n        | [x : enclave, y : enclave |- _] => destruct (Nat.eq_dec x y)\n        | [x : location, y : location |- _] => destruct (Nat.eq_dec x y)\n        | _ => idtac            \n        end; [left; now subst | right; congruence].\n\n   Ltac easy_dec :=\n     subst; auto; right; congruence.\n\n  Lemma mode_decidable : forall m1 m2 : mode, {m1 = m2} + {m1 <> m2}.\n  Proof.\n    intros; destruct m1; destruct m2; try (right; discriminate).\n    - left; auto.\n    - destruct (Nat.eq_dec e e0); [left; now subst | right; congruence].\n  Qed.\n   \n   Lemma exp_decidable : forall (e1 e2 : exp), {e1 = e2} + {e1 <> e2}.\n  Proof.\n    intro.\n    induction e1 using exp_rect' with\n    (P := fun c1 =>\n            forall c2, {c1 = c2} + {c1 <> c2}); intros.\n    1-6: destruct e2; try (right; discriminate).\n    7-14,16: destruct c2; try (right; discriminate).\n    1-2, 4: auto_decide.\n    - destruct IHe1_1 with e2_1; destruct IHe1_2 with e2_2; easy_dec.\n    - destruct IHe1 with e2; easy_dec.\n    - destruct IHe1 with c0; destruct (mode_decidable md m); easy_dec.\n    - auto.\n    - destruct IHe1 with e; subst; [auto_decide | right; congruence].\n    - destruct IHe1 with e; subst; [auto_decide | right; congruence].\n    - destruct IHe1_1 with e; destruct IHe1_2 with e0; easy_dec.\n    - destruct s; destruct sl; destruct IHe1 with e; easy_dec.\n    - destruct IHe1 with e; easy_dec.\n    - destruct IHe1 with c2; subst; [auto_decide | right; congruence].\n    - generalize l; induction coms; intros; destruct l0; try (right; discriminate); auto.\n      inversion X; subst.\n      destruct X0 with c; try (right; congruence).\n      apply IHcoms with (l := l0) in X1.\n      destruct X1; subst.\n      + left; inversion e0; subst; auto.\n      + right; congruence.\n    - destruct IHe1 with e; destruct IHe0 with c2; easy_dec.\n    - destruct c0; try (right; discriminate).\n      destruct IHe1 with e; destruct IHe0 with c0_1; destruct IHe2 with c0_2; easy_dec.\n  Qed.\n  \n  Lemma com_decidable : forall (c1 c2 : com), {c1 = c2} + {c1 <> c2}.\n  Proof.\n    intro.\n    induction c1 using com_rect' with\n    (P0 := fun e1 =>\n             forall e2, {e1 = e2} + {e1 <> e2}); intros.\n    1-2, 4-6: destruct e2; try (right; discriminate).\n    7-16: destruct c2; try (right; discriminate).\n    1-3: auto_decide.\n    - destruct IHc1 with e2; easy_dec.\n    - destruct IHc1 with c; destruct (mode_decidable md m); easy_dec.\n    - destruct e0; try (right; discriminate);\n        destruct IHc1 with e0_1; destruct IHc0 with e0_2; easy_dec.\n    - auto.\n    - destruct IHc1 with e0; subst; [auto_decide | right; congruence].\n    - destruct IHc1 with e0; subst; [auto_decide | right; congruence].\n    - destruct IHc1 with e; destruct IHc0 with e0; easy_dec.\n    - destruct s; destruct sl; destruct IHc1 with e0; easy_dec.\n    - destruct IHc1 with e0; easy_dec.\n    - destruct IHc1 with c2; subst; [auto_decide | right; congruence].\n    - generalize l; induction coms; intros; destruct l0; try (right; discriminate); auto.\n      inversion X; subst.\n      destruct X0 with c; try (right; congruence).\n      apply IHcoms with (l := l0) in X1.\n      destruct X1; subst.\n      + left; inversion e0; subst; auto.\n      + right; congruence.\n    - destruct IHc1_1 with e0; destruct IHc1_2 with c2_1; destruct IHc1_3 with c2_2; easy_dec.\n    - destruct IHc1 with e0; destruct IHc0 with c2; easy_dec.\n  Qed.\n  \n  Lemma val_decidable : forall (v1 v2 : val), {v1 = v2} + {v1 <> v2}.\n  Proof.\n    intro.\n    induction v1; intros; destruct v2; try (right; discriminate); try auto_decide.\n    destruct (mode_decidable m m0); destruct (com_decidable c c0); easy_dec.\n  Qed.\n      \n  Lemma prog_decidable : forall p1 p2 : (com + exp), {p1 = p2} + {p1 <> p2}.\n  Proof.\n    intros; destruct p1; destruct p2; try (right; discriminate);\n      [destruct (com_decidable c c0) | destruct (exp_decidable e e0)]; easy_dec.\n  Qed.\n\n  Lemma mode_prog_decidable : forall ep1 ep2 : (mode * (com + exp)), {ep1 = ep2} + {ep1 <> ep2}.\n  Proof.\n    intros; destruct ep1, ep2; destruct (mode_decidable m m0); destruct (prog_decidable s s0);\n      easy_dec.\n  Qed.\n  \nEnd Decidability.\n\n(*******************************************************************************\n*\n* ENCLAVE EQUIVALENCE\n*\n*******************************************************************************)\n\nSection Enclave_Equiv.\n  Fixpoint chi (c : com) : set (mode * (com + exp)) :=\n  let chi_exp :=\n      (fix chi_exp (e : exp) : set (mode * (com + exp)) :=\n         match e with\n         | Eadd e1 e2 => set_union mode_prog_decidable (chi_exp e1) (chi_exp e2)\n         | Ederef e1 => chi_exp e1\n         | Elambda Normal c => chi c\n         | Elambda m _ => set_add mode_prog_decidable (m, inr e) nil\n         | _ => nil\n         end)\n  \n  in\n  match c with\n  | Cassign _ e => chi_exp e\n  | Cdeclassify _ e => chi_exp e\n  | Cupdate e1 e2 => set_union mode_prog_decidable (chi_exp e1) (chi_exp e2)\n  | Coutput e _ => chi_exp e\n  | Ccall e => chi_exp e\n  | Cenclave enc c1 => set_add mode_prog_decidable (Encl enc, inl c1) nil\n  | Cseq c_lst => fold_left (fun acc elt => set_union mode_prog_decidable (chi elt) acc) c_lst nil\n  | Cif e c1 c2 => set_union mode_prog_decidable (chi_exp e)\n                            (set_union mode_prog_decidable (chi c1) (chi c2))\n  | _ => nil\n  end.\n\n  Definition enc_equiv (c1 c2 : com) := chi c1 = chi c2 -> Prop.\n\nEnd Enclave_Equiv.\n\n(*******************************************************************************\n*\n* SEMANTICS\n*\n*******************************************************************************)\n\nSection Semantics.\n  Definition reg : Type := register val.\n  Definition reg_init : reg := fun x => Vnat 0.\n  Definition mem : Type := memory val.\n  Definition loc_mode : Type := location -> mode.\n\n  Inductive event : Type :=\n  | Decl : exp -> mem -> event\n  | Mem : mem -> event\n  | Out : sec_level -> val -> event\n  | Update : mem -> location -> val -> event\n  | Assign : reg -> var -> val -> event\n  | ANonEnc : com -> event\n  | AEnc : forall c c' : com, enc_equiv c c'-> event\n  | Emp: event.\n  Definition trace : Type := list event.\n  (* Adding empty to the front of a trace doesn't change it *)\n  Axiom emp_eq : forall t,\n      Emp :: t = t.\n\n  Definition mode_access_ok (md: mode) (d: loc_mode) (l: location) :=\n    let lmd := d l in\n    match lmd with\n    | Normal => True\n    | Encl _ => md = lmd\n    end.\n  \n  Definition econfig : Type := exp * reg * mem.\n  Definition ecfg_exp (ecfg: econfig) : exp :=\n    match ecfg with (e, _, _) => e end.\n  Definition ecfg_reg (ecfg: econfig) : reg :=\n    match ecfg with (_, r, _) => r end.\n  Definition ecfg_update_exp (ecfg: econfig) (e: exp) : econfig :=\n    match ecfg with (_, r, m) => (e, r, m) end.\n  Definition esemantics : Type := mode -> loc_mode -> econfig -> val -> Prop.\n  \n  Inductive estep : esemantics :=\n  | Estep_nat : forall md d ecfg n,\n      ecfg_exp ecfg = Enat n ->\n      estep md d ecfg (Vnat n)\n  | Estep_loc : forall md d ecfg l,\n      ecfg_exp ecfg = Eloc l ->\n      estep md d ecfg (Vloc l)\n  | Estep_lambda : forall md d ecfg c,\n      ecfg_exp ecfg = Elambda md c ->\n      estep md d ecfg (Vlambda md c)\n  | Estep_var : forall md d ecfg x v,\n      ecfg_exp ecfg = Evar x ->\n      ecfg_reg ecfg x = v ->\n      estep md d ecfg v\n  | Estep_add : forall md d ecfg e1 e2 n1 n2,\n      ecfg_exp ecfg = Eadd e1 e2 ->\n      estep md d (ecfg_update_exp ecfg e1) (Vnat n1) ->\n      estep md d (ecfg_update_exp ecfg e2) (Vnat n2) ->\n      estep md d ecfg (Vnat (n1 + n2))\n  | Estep_deref : forall md d ecfg e r m l v,\n      ecfg = (Ederef e, r, m) ->\n      estep md d (e, r, m) (Vloc l) ->\n      m l = v ->\n      mode_access_ok md d l ->\n      estep md d ecfg v.\n  Hint Constructors estep.\n\n  (* Semantics for commands. *)\n  Definition cconfig : Type := com * reg * mem              .\n  Definition cterm : Type := reg * mem              .\n  Definition ccfg_com (ccfg: cconfig) : com :=\n    match ccfg with (c, _, _) => c end.\n  Definition ccfg_reg (ccfg: cconfig) : reg :=\n    match ccfg with (_, r, _) => r end.\n  Definition ccfg_mem (ccfg: cconfig) : mem :=\n    match ccfg with (_, _, m) => m end.\n  Definition ccfg_update_mem (ccfg: cconfig) (l: location) (v: val) : mem := \n    fun loc => if loc =? l then v\n               else (ccfg_mem ccfg) loc.\n  Definition ccfg_update_reg (ccfg: cconfig) (x: var) (v: val) : reg :=\n    fun var => if var =? x then v\n               else (ccfg_reg ccfg) var.\n  Definition ccfg_to_ecfg (e: exp) (ccfg : cconfig) : econfig :=\n    (e, (ccfg_reg ccfg), (ccfg_mem ccfg)).\n  Definition ccfg_update_com (c: com) (ccfg : cconfig) : cconfig :=\n    (c, (ccfg_reg ccfg), (ccfg_mem ccfg)).\n  Definition csemantics : Type := mode -> loc_mode -> cconfig -> cterm -> trace -> Prop.  \n\n  Inductive cstep : csemantics := \n  | Cstep_skip : forall md d ccfg,\n      ccfg_com ccfg = Cskip ->\n      cstep md d ccfg (ccfg_reg ccfg, ccfg_mem ccfg) []\n  | Cstep_assign : forall md d ccfg x e v r',\n      ccfg_com ccfg = Cassign x e ->\n      estep md d (ccfg_to_ecfg e ccfg) v ->\n      r' = ccfg_update_reg ccfg x v ->\n      cstep md d ccfg (r', ccfg_mem ccfg) [Assign (ccfg_reg ccfg) x v]\n  | Cstep_declassify : forall md d ccfg x e v r',\n      ccfg_com ccfg = Cdeclassify x e ->\n      exp_novars e ->\n      estep md d (ccfg_to_ecfg e ccfg) v ->\n      r' = ccfg_update_reg ccfg x v ->\n      cstep md d ccfg (r', ccfg_mem ccfg) [Decl e (ccfg_mem ccfg)]\n  | Cstep_update : forall md d ccfg e1 e2 l v m',\n      ccfg_com ccfg = Cupdate e1 e2 ->\n      estep md d (ccfg_to_ecfg e1 ccfg) (Vloc l) ->\n      estep md d (ccfg_to_ecfg e2 ccfg) v ->\n      m' = ccfg_update_mem ccfg l v ->\n      cstep md d ccfg (ccfg_reg ccfg, m') [Update (ccfg_mem ccfg) l v]\n  | Cstep_output : forall md d ccfg e sl v,\n      ccfg_com ccfg = Coutput e sl ->\n      estep md d (ccfg_to_ecfg e ccfg) v ->\n      sl = L \\/ sl = H ->\n      cstep md d ccfg (ccfg_reg ccfg, ccfg_mem ccfg) [Mem (ccfg_mem ccfg); Out sl v]\n  | Cstep_call : forall md d ccfg e c r' m' tr,\n      ccfg_com ccfg = Ccall e ->\n      estep md d (ccfg_to_ecfg e ccfg) (Vlambda md c) ->\n      cstep md d (ccfg_update_com c ccfg) (r', m') tr ->\n      cstep md d ccfg (r', m') tr\n  | Cstep_enclave : forall md d ccfg enc c r' m' tr,\n    md = Normal ->\n    ccfg_com ccfg = Cenclave enc c ->\n    cstep (Encl enc) d (c, ccfg_reg ccfg, ccfg_mem ccfg) (r', m') tr ->\n    cstep md d ccfg (r', m') tr\n  | Cstep_seq_nil : forall md d ccfg,\n      ccfg_com ccfg = Cseq [] ->\n      cstep md d ccfg (ccfg_reg ccfg, ccfg_mem ccfg) []\n  | Cstep_seq_hd : forall md d ccfg hd tl r m tr r' m' tr' t,\n      ccfg_com ccfg = Cseq (hd::tl) ->\n      cstep md d (ccfg_update_com hd ccfg) (r, m) tr ->\n      cstep md d (Cseq tl, r, m) (r', m') tr' ->\n      t = tr ++ tr' ->\n      cstep md d ccfg (r', m') t\n  | Cstep_if : forall md d ccfg e c1 c2 r' m' tr,\n      ccfg_com ccfg = Cif e c1 c2 ->\n      estep md d (ccfg_to_ecfg e ccfg) (Vnat 1) ->\n      cstep md d (ccfg_update_com c1 ccfg) (r', m') tr ->\n      cstep md d ccfg (r', m') tr\n  | Cstep_else : forall md d ccfg e c1 c2 r' m' tr,\n      ccfg_com ccfg = Cif e c1 c2 ->\n      estep md d (ccfg_to_ecfg e ccfg) (Vnat 0) ->\n      cstep md d (ccfg_update_com c2 ccfg) (r', m') tr ->\n      cstep md d ccfg (r', m') tr\n  | Cstep_while_t : forall md d ccfg e c r m tr r' m' tr',\n      ccfg_com ccfg = Cwhile e c ->\n      estep md d (ccfg_to_ecfg e ccfg) (Vnat 1) ->\n      cstep md d (ccfg_update_com c ccfg) (r, m) tr ->\n      cstep md d (Cwhile e c,r,m) (r', m') tr' ->\n      cstep md d ccfg (r', m') (tr++tr')\n  | Cstep_while_f : forall md d ccfg e c,\n      ccfg_com ccfg = Cwhile e c ->\n      estep md d (ccfg_to_ecfg e ccfg) (Vnat 0) ->\n      cstep md d ccfg (ccfg_reg ccfg, ccfg_mem ccfg) []\n  .\n  Hint Constructors cstep.\n\n  Inductive cstep_n_chaos : csemantics :=\n  | Nchaos_cstep : forall md d ccfg cterm t,\n      cstep md d ccfg cterm t -> cstep_n_chaos md d ccfg cterm t\n  | Nchaos_chaos : forall d ccfg cterm c' t' (HEncEq : enc_equiv (ccfg_com ccfg) c'),\n      cstep Normal d (c', ccfg_reg ccfg, ccfg_mem ccfg) cterm t' ->\n      cstep_n_chaos Normal d ccfg cterm\n                    (Mem (ccfg_mem ccfg) :: AEnc (ccfg_com ccfg) c' HEncEq :: t').\nEnd Semantics.\n\n(*******************************************************************************\n*\n* TYPING\n*\n*******************************************************************************)\n\nSection Typing.\n\n  Inductive ref_type : Set :=\n  | Mut\n  | Immut.\n\n  Inductive base_type : Type :=\n  | Tnat : base_type\n  | Tref : type -> mode -> ref_type -> base_type\n  | Tlambda (G: var -> option type) (p: sec_level) (md: mode) (G': var -> option type) : base_type\n                                                                     \n  with type : Type :=\n       | Typ : base_type -> sec_level -> type.\n\n  Definition context : Type := var -> option type.\n  Parameter Loc_Contxt : location -> option (type * ref_type).\n  \n  Lemma var_in_dom_dec : forall (G : context) x, {exists t, G x = Some t} + {G x = None}.\n  Proof.\n    intros. destruct G. simpl. \n    left; now exists t. right; auto.\n  Qed.\n                     \n  Lemma loc_in_dom_dec : forall l, {exists t rt, Loc_Contxt l = Some (t, rt)}\n                                     + {Loc_Contxt l = None}.\n  Proof.\n    intros. simpl. destruct (Loc_Contxt l). destruct p.\n    left; exists t; exists r; auto. right; auto.\n  Qed.\n      \n  Definition forall_loc (P: location -> type -> ref_type -> Prop) : Prop :=\n    forall l t rt, Loc_Contxt l = Some (t, rt) -> P l t rt.\n\n  Definition forall_dom (G: context) (P: var -> type -> Prop) : Prop :=\n       forall x t, G x = Some t -> P x t.\n  \n  Inductive type_le : type -> type -> Prop :=\n  | Type_le : forall s1 s2 p1 p2,\n      base_type_le s1 s2 ->\n      sec_level_le p1 p2 ->\n      type_le (Typ s1 p1) (Typ s2 p2)\n\n  with base_type_le : base_type -> base_type -> Prop :=\n  | Base_type_le_refl : forall s, base_type_le s s\n  | Base_type_le_lambda : forall G1 G1' G2 G2' p1 p2 md,\n      sec_level_le p2 p1 ->\n      context_le G2 G1 ->\n      context_le G1' G2' ->\n      base_type_le (Tlambda G1 p1 md G1')\n                   (Tlambda G2 p2 md G2')\n\n  with context_le : context -> context -> Prop :=\n  (* for right now, let's not assume that the domains are equal *)\n  | Context_le : forall G1 G2,\n      (forall x t,\n          G1 x = Some t ->\n          (* G2 must either not use the variable or have a greater type *)\n          (G2 x = None \\/ exists t', G2 x = Some t' /\\ type_le t t')) ->\n      (forall x t',\n          G2 x = Some t' -> exists t, G1 x = Some t /\\ type_le t t') ->\n      context_le G1 G2.\n  \n  Lemma context_le_refl : forall G, context_le G G.\n  Proof.\n    intros. apply Context_le. intros. right; exists t; destruct t; auto.\n    split; auto. apply Type_le. apply Base_type_le_refl. apply sec_level_le_refl.\n    intros; exists t'; split; auto; destruct t'; auto.\n    apply Type_le. apply Base_type_le_refl. apply sec_level_le_refl.\n  Qed.\n  \n  \n  Definition is_var_low_context (G: context) : Prop :=\n    forall_dom G (fun _ t => let (_, p) := t in p = L).\n\n  Function loc_in_exp (e: exp) (l: location) : Prop :=\n    match e with\n    | Eloc l' => l = l'\n    | Ederef e' => loc_in_exp e' l\n    | Eadd e1 e2 => loc_in_exp e1 l \\/ loc_in_exp e2 l\n    | _ => False\n    end.\n\n  Definition exp_locs_immutable (e: exp) :=\n    forall_subexp e (fun e =>\n                       match e with\n                       | Eloc n => set_In n (immutable_locs g0)\n                       | _ => True\n                       end).\n          \n  Axiom Loc_Contxt_wt : forall d, \n    forall_loc (fun l t _ =>\n                  let (_, p) := t in\n                  (p = H -> d l <> Normal)).\n\n  Inductive val_type : mode -> context -> loc_mode -> val -> type -> Prop :=\n  | VTnat: forall md g d n q,\n      val_type md g d (Vnat n) (Typ Tnat q) \n  | VTloc: forall md g d l md' t rt q,\n      d l = md' ->\n      Loc_Contxt l = Some (t, rt) ->\n      val_type md g d (Vloc l) (Typ (Tref t md' rt) q)\n  | VTlambda : forall md g d c p g' g'' q md0,\n      com_type p md g' d c g'' ->\n      val_type md0 g d (Vlambda md c) (Typ (Tlambda g' p md g'') q)\n  | VTvar : forall md g d x r bt p v,\n      g x = Some (Typ bt p) ->\n      r x = v ->\n      val_type md g d v (Typ bt p)\n  | VTmem : forall md g d md' p rt q m l v bt,\n      m l = v ->\n      val_type md g d (Vloc l) (Typ (Tref (Typ bt p) md' rt) q) ->\n      val_type md g d v (Typ bt (sec_level_join p q))\n  | VTbinop : forall md g d n1 n2 p q op,\n      val_type md g d (Vnat n1) (Typ Tnat p) ->\n      val_type md g d (Vnat n2) (Typ Tnat q) ->\n      val_type md g d (Vnat (op n1 n2)) (Typ Tnat (sec_level_join p q))\n\n  with exp_type : mode -> context -> loc_mode -> exp -> type -> Prop :=\n  | ETnat : forall md g d n,\n      exp_type md g d (Enat n) (Typ Tnat (L))\n  | ETvar : forall md g d x t,\n      g x = Some t ->\n      exp_type md g d (Evar x) t\n  | ETloc : forall md g d l md' t rt,\n      d l = md' ->\n      Loc_Contxt l = Some (t, rt) ->\n      exp_type md g d (Eloc l) (Typ (Tref t md' rt) (L))\n  | ETderef : forall md g d e md' s p rt q,\n      exp_type md g d e (Typ (Tref (Typ s p) md' rt) q) ->\n      md' = Normal \\/ md' = md ->\n      exp_type md g d (Ederef e) (Typ s (sec_level_join p q))\n  | ETlambda : forall md g d c p g' g'',\n      com_type p md g' d c g''->\n      exp_type md g d (Elambda md c) (Typ (Tlambda g' p md g'') (L))\n  | ETadd : forall md g d e1 e2 p q,\n      exp_type md g d e1 (Typ Tnat p) ->\n      exp_type md g d e2 (Typ Tnat q) ->\n      exp_type md g d (Eadd e1 e2) (Typ Tnat (sec_level_join p q))\n\n  with com_type : sec_level -> mode -> context -> loc_mode -> com -> context -> Prop :=\n  | CTskip : forall pc md g d,\n      com_type pc md g d Cskip g\n  | CTassign : forall pc md g d x e s p q vc',\n      exp_type md g d e (Typ s p) ->\n      q = sec_level_join p pc ->\n      sec_level_le q (L) \\/ md <> Normal ->\n      vc' = (fun y => if y =? x then Some (Typ s q) else g y) ->\n      com_type pc md g d (Cassign x e) (vc')\n  | CTdeclassify : forall md g d x e s p vc',\n      exp_type md g d e (Typ s p) ->\n      exp_novars e ->\n      exp_locs_immutable e ->\n      vc' = (fun y => if y =? x then Some (Typ s (L)) else g y) ->\n      com_type (L) md g d (Cdeclassify x e) (vc')\n  | CToutput : forall pc md g d e l s p,\n      exp_type md g d e (Typ s p) ->\n      sec_level_le (sec_level_join p pc) l ->\n      com_type pc md g d (Coutput e l) g\n  | CTupdate : forall pc md g d e1 e2 s p md' q p',\n      exp_type md g d e1 (Typ (Tref (Typ s p) md' Mut) q) ->\n      exp_type md g d e2 (Typ s p') ->\n      sec_level_le (sec_level_join (sec_level_join p' q) pc) p ->\n      md' = Normal \\/ md' = md ->\n      com_type pc md g d (Cupdate e1 e2) g\n  | Tifelse : forall pc md g d e c1 c2 pc' p g',\n      com_type pc' md g d c1 g' ->\n      com_type pc' md g d c2 g' ->\n      exp_type md g d e (Typ Tnat p) ->\n      sec_level_le (sec_level_join pc p) pc' ->\n      sec_level_le p (L) \\/ md <> Normal ->\n      com_type pc md g d (Cif e c1 c2) g'\n  | Tenclave : forall pc g d c i c' g',\n      c = Cenclave i c' ->\n      com_type pc (Encl i) g d c' g' ->\n      is_var_low_context g' ->\n      com_type pc Normal g d c g'\n  | Twhile : forall pc md g d c e p pc',\n      exp_type md g d e (Typ Tnat p) ->\n      com_type pc' md g d c g ->\n      sec_level_le (sec_level_join pc p) pc' ->\n      sec_level_le p L \\/ md <> Normal ->\n      com_type pc md g d (Cwhile e c) g\n  | Tseq : forall pc md g d c rest g' gn,\n      com_type pc md g d c g' ->\n      com_type pc md g' d (Cseq rest) gn ->\n      com_type pc md g d (Cseq (c :: rest)) gn\n  | Tseqnil : forall pc md g d,\n      com_type pc md g d (Cseq []) g\n  | Tcall : forall pc md G d e Gm Gp Gout q p,\n      exp_type md G d e (Typ (Tlambda Gm p md Gp) q) ->\n      sec_level_le (sec_level_join pc q) p ->\n      context_le G Gm ->\n      context_le Gp Gout ->\n      forall_dom G (fun x t => (Gp x = None) -> Gout x = Some t) ->\n      com_type pc md G d (Ccall e) Gout.\n\n  Axiom subsumption : forall pc1 pc2 md d G1 G1' G2 G2' c,\n      com_type pc1 md G1 d c G1' ->\n      sec_level_le pc2 pc1 ->\n      context_le G2 G1 ->\n      context_le G1' G2' ->\n      com_type pc2 md G2 d c G2'.\n  \n  Hint Constructors exp_type.\n  Hint Constructors val_type.\n  Hint Constructors com_type.\nEnd Typing.\n\nSection Initial_State.\n  Parameter minit : mem.\n\n  Definition meminit_wf minit d := forall l,\n      match minit l with\n      | Vlambda md c => exists Gm p Gp q rt,\n                        Loc_Contxt l = Some (Typ (Tlambda Gm p md Gp) q, rt) /\\\n                        com_type p md Gm d c Gp\n      | Vloc l => False\n      | Vnat n => exists q rt, Loc_Contxt l = Some (Typ (Tnat) q, rt)\n      end.\n\n  Axiom wf_minit : forall d, meminit_wf minit d.\n\n  Axiom Initial_State : forall d r' m',\n      exists c md tr, cstep md d (c,reg_init,minit) (r',m') tr.\nEnd Initial_State.\n\nSection Axioms.\n  (* These next four axioms follow from the statement of initial state above *)\n  Axiom No_Pointers : forall (m: mem) l l', m l <> Vloc l'.\n\n  Axiom Reg_Exp_Lambda : forall (r : reg) d x md c G Gm Gp p q,\n      r x = Vlambda md c /\\ G x = Some (Typ (Tlambda Gm p md Gp) q)\n      <-> exists md', exp_type md' G d (Elambda md c)\n                                 (Typ (Tlambda Gm p md Gp) L).\n\n  Axiom Reg_Exp_Loc : forall (r : reg) d x l G s p md' rt q,\n      r x = Vloc l /\\ G x = Some (Typ (Tref (Typ s p) md' rt) q) <->\n      exists md,\n        exp_type md G d (Eloc l) (Typ (Tref (Typ s p) md' rt) L) /\\ d l = md'.\n\n  Axiom Mem_Exp_Lambda : forall (m : mem) d l md c G Gm Gp p q rt,\n      m l = Vlambda md c /\\ Loc_Contxt l = Some (Typ (Tlambda Gm p md Gp) q, rt) <->\n      minit l = Vlambda md c \\/\n      (exists md',\n          exp_type md' G d (Elambda md c) (Typ (Tlambda Gm p md Gp) L)).\nEnd Axioms.\n\n\n\n\n\n", "meta": {"author": "aaronbembenek", "repo": "verified-auto-enclave", "sha": "732010057c4c80e5db849fe7877280f82899a68f", "save_path": "github-repos/coq/aaronbembenek-verified-auto-enclave", "path": "github-repos/coq/aaronbembenek-verified-auto-enclave/verified-auto-enclave-732010057c4c80e5db849fe7877280f82899a68f/SImpE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.566018549837479, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.1720932243853077}}
{"text": "(* ------------------------------------------------------- *)\n(** #<hr> <center> <h1>#\n        The double time redundancy (DTR) transformation   \n#</h1>#    \n-   Properties of memory block sub-part called rhsPar\n\n          Dmitry Burlyaev - Pascal Fradet - 2015\n#</center> <hr>#                                           *)\n(* ------------------------------------------------------- *)\n(*Add LoadPath \"..\\..\\Common\\\".\n        Require Import CirReflect . \nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\\". *)\nAdd LoadPath \"..\\..\\Common\\\".\nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\Transf\\\".\n\nRequire Import dtrTransform.\n\nSet Implicit Arguments.\n\n(* ##################################################################### *)\n(** Properties of sub-circuit of Memory Block called rhsPar w/o Glitches *)\n(* ##################################################################### *)\n\n(* State before/after for both cycles w/o errors *)\nLemma step_rhs: forall si_I sav_I rol_I fai_I rO_I sav2_I t rhs2,\n                step rhsPar {si_I,{{{ sav_I, rol_I},fai_I},{rO_I,sav2_I}}} t rhs2\n             -> let rNew:= if ((beq_buset_t sav2_I (~?))&&(beq_buset_t si_I (~0))&&(beq_buset_t rO_I (~0))) then (~0)\n                           else if (beq_buset_t sav2_I (~?))  then (~?)\n                           else if (beq_buset_t sav2_I (~1)) then si_I\n                           else rO_I in\n                t= {{ {{sav_I,rol_I}, fai_I}, si_I}, rNew} /\\ rhs2 = rhsPar.\nProof.\nintrov H. \nassert ( F:  fstep rhsPar {si_I, {sav_I, rol_I, fai_I, {rO_I, sav2_I}}}  = \n             Some ({{ {{sav_I,rol_I}, fai_I}, si_I}, \n                      if ((beq_buset_t sav2_I (~?))&&(beq_buset_t si_I (~0))\n                      &&(beq_buset_t rO_I (~0))) then (~0)\n                      else if (beq_buset_t sav2_I (~?))  then (~?)\n                      else if (beq_buset_t sav2_I (~1)) then si_I\n                      else rO_I},rhsPar)) by\n(Destruct_s sav2_I; destruct x; cbn; Destruct_s sav_I;  Destruct_s rol_I; \nDestruct_s fai_I; Destruct_s si_I; Destruct_s rO_I; \ndestruct x; destruct x0; destruct x1 ; destruct x2; destruct x3;\nvm_compute; try easy). \neapply fstep_imp_detstep in F; 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/memoryBlocks/rightStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.17202376828564006}}
{"text": "Require Import LayerDeps.\nRequire Import Ident.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\nRequire Import RmiAux.Spec.\nRequire Import BaremoreSMC.Spec.\nRequire Import RmiAux2.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Layer.\n\n  Context `{real_params: RealParams}.\n\n  Section InvDef.\n\n    Record high_level_invariant (adt: RData) :=\n      mkInvariants { }.\n\n    Global Instance RmiAux2_ops : CompatDataOps RData :=\n      {\n        empty_data := empty_adt;\n        high_level_invariant := high_level_invariant;\n        low_level_invariant := fun (b: block) (d: RData) => True;\n        kernel_mode adt := True\n      }.\n\n  End InvDef.\n\n  Section InvInit.\n\n    Global Instance RmiAux2_prf : CompatData RData.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvInit.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModelX}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Section InvProof.\n\n    Global Instance init_rec_regs_inv: PreservesInvariants init_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance init_rec_rvic_state_inv: PreservesInvariants init_rec_rvic_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance rec_granule_measure_inv: PreservesInvariants rec_granule_measure_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance shiftl_inv: PreservesInvariants shiftl_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_par_base_inv: PreservesInvariants get_rd_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_to_idx_inv: PreservesInvariants addr_to_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rvic_result_target_inv: PreservesInvariants set_rvic_result_target_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_sysregs_inv: PreservesInvariants set_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance validate_realm_params_inv: PreservesInvariants validate_realm_params_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_psci_call_inv: PreservesInvariants get_psci_result_forward_psci_call_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_inc_inv: PreservesInvariants granule_refcount_inc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_measurement_algo_inv: PreservesInvariants get_realm_params_measurement_algo_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_rec_run_inv: PreservesInvariants ns_buffer_read_rec_run_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_mark_realm_inv: PreservesInvariants smc_mark_realm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_state_inv: PreservesInvariants set_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_pstate_inv: PreservesInvariants get_rec_pstate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_release_inv: PreservesInvariants atomic_granule_put_release_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_gprs_inv: PreservesInvariants get_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_asserted_inv: PreservesInvariants set_rec_ptimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_timer_asserted_inv: PreservesInvariants get_timer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_inv: PreservesInvariants get_realm_params_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_rec_idx_inv: PreservesInvariants get_rec_rec_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_is_emulated_mmio_inv: PreservesInvariants get_rec_run_is_emulated_mmio_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_refcount_dec_inv: PreservesInvariants granule_refcount_dec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance interrupt_bitmap_dword_inv: PreservesInvariants interrupt_bitmap_dword_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_measurement_algo_inv: PreservesInvariants set_rd_measurement_algo_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_masked_inv: PreservesInvariants get_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_header_inv: PreservesInvariants measurement_extend_data_header_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_lock_inv: PreservesInvariants granule_lock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ptr_eq_inv: PreservesInvariants ptr_eq_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_common_sysregs_inv: PreservesInvariants get_rec_common_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_rec_inv: PreservesInvariants is_addr_in_par_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_par_base_inv: PreservesInvariants set_rec_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sixty_four_inv: PreservesInvariants esr_sixty_four_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rvic_mask_bits_inv: PreservesInvariants get_rvic_mask_bits_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance run_realm_inv: PreservesInvariants run_realm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_params_flags_inv: PreservesInvariants get_rec_params_flags_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_timer_masked_inv: PreservesInvariants get_timer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_target_rec_inv: PreservesInvariants get_target_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_psci_result_forward_psci_call_inv: PreservesInvariants set_psci_result_forward_psci_call_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_g_rtt_refcount_inv: PreservesInvariants get_g_rtt_refcount_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_srt_inv: PreservesInvariants esr_srt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_pstate_inv: PreservesInvariants set_rec_pstate_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_pc_inv: PreservesInvariants get_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_par_end_inv: PreservesInvariants get_rd_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_rec_valid_inv: PreservesInvariants is_rec_valid_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_par_base_inv: PreservesInvariants set_rd_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_par_size_inv: PreservesInvariants get_realm_params_par_size_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_len_inv: PreservesInvariants access_len_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_g_rec_rd_inv: PreservesInvariants get_g_rec_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_rtt_addr_inv: PreservesInvariants get_realm_params_rtt_addr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_ptimer_masked_inv: PreservesInvariants set_rec_ptimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_g_rec_list_inv: PreservesInvariants set_rd_g_rec_list_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_par_end_inv: PreservesInvariants set_rd_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_read_inv: PreservesInvariants sysreg_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance null_ptr_inv: PreservesInvariants null_ptr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance timer_is_masked_inv: PreservesInvariants timer_is_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rd_g_rtt_inv: PreservesInvariants set_rd_g_rtt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_ns_state_inv: PreservesInvariants get_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_g_rec_rd_inv: PreservesInvariants set_g_rec_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_masked_inv: PreservesInvariants set_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_esr_inv: PreservesInvariants set_rec_run_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rvic_result_ns_notify_inv: PreservesInvariants set_rvic_result_ns_notify_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance realm_get_rec_entry_inv: PreservesInvariants realm_get_rec_entry_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_ns_state_inv: PreservesInvariants set_ns_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_g_rec_inv: PreservesInvariants get_rec_g_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_gprs_inv: PreservesInvariants set_rec_run_gprs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_hpfar_inv: PreservesInvariants set_rec_run_hpfar_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x0_inv: PreservesInvariants get_psci_result_x0_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_runnable_inv: PreservesInvariants set_rec_runnable_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x1_inv: PreservesInvariants get_psci_result_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance interrupt_bit_inv: PreservesInvariants interrupt_bit_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x2_inv: PreservesInvariants get_psci_result_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_null_inv: PreservesInvariants is_null_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_rvic_enabled_inv: PreservesInvariants get_rec_rvic_enabled_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_target_rec_inv: PreservesInvariants set_target_rec_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_g_rec_list_inv: PreservesInvariants get_rd_g_rec_list_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_masked_inv: PreservesInvariants get_rec_vtimer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_g_llt_inv: PreservesInvariants set_wi_g_llt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_last_run_info_esr_inv: PreservesInvariants get_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_finish_inv: PreservesInvariants measurement_finish_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_g_rec_list_inv: PreservesInvariants get_rec_g_rec_list_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_is_write_inv: PreservesInvariants esr_is_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_x3_inv: PreservesInvariants get_psci_result_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_wi_index_inv: PreservesInvariants set_wi_index_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_timer_masked_inv: PreservesInvariants set_timer_masked_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance mpidr_to_rec_idx_inv: PreservesInvariants mpidr_to_rec_idx_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance emulate_timer_ctl_read_inv: PreservesInvariants emulate_timer_ctl_read_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_extend_data_inv: PreservesInvariants measurement_extend_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_IS_WRITE_inv: PreservesInvariants ESR_EL2_SYSREG_IS_WRITE_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance barrier_inv: PreservesInvariants barrier_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance access_mask_inv: PreservesInvariants access_mask_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance esr_sign_extend_inv: PreservesInvariants esr_sign_extend_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_dispose_pending_inv: PreservesInvariants set_rec_dispose_pending_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rd_g_rtt_inv: PreservesInvariants get_rd_g_rtt_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_last_run_info_esr_inv: PreservesInvariants set_rec_last_run_info_esr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rvic_result_x0_inv: PreservesInvariants set_rvic_result_x0_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance test_bit_acquire_64_inv: PreservesInvariants test_bit_acquire_64_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_psci_result_forward_x1_inv: PreservesInvariants set_psci_result_forward_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_regs_inv: PreservesInvariants get_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x3_inv: PreservesInvariants get_psci_result_forward_x3_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_rvic_inv: PreservesInvariants get_rec_rvic_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance realm_set_rec_entry_inv: PreservesInvariants realm_set_rec_entry_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x2_inv: PreservesInvariants get_psci_result_forward_x2_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_psci_result_forward_x1_inv: PreservesInvariants get_psci_result_forward_x1_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_exit_reason_inv: PreservesInvariants set_rec_run_exit_reason_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ESR_EL2_SYSREG_ISS_RT_inv: PreservesInvariants ESR_EL2_SYSREG_ISS_RT_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_put_inv: PreservesInvariants atomic_granule_put_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_rec_params_inv: PreservesInvariants ns_buffer_read_rec_params_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_three_delegated_granules_inv: PreservesInvariants find_lock_three_delegated_granules_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_bit_set_release_64_inv: PreservesInvariants atomic_bit_set_release_64_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance read_idreg_inv: PreservesInvariants read_idreg_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_end_inv: PreservesInvariants get_rec_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_g_rd_inv: PreservesInvariants set_rec_g_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_par_base_inv: PreservesInvariants get_realm_params_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance measurement_start_inv: PreservesInvariants measurement_start_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_psci_result_x0_inv: PreservesInvariants set_psci_result_x0_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_pc_inv: PreservesInvariants set_rec_pc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_regs_inv: PreservesInvariants set_rec_regs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_runnable_inv: PreservesInvariants get_rec_runnable_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_sysregs_inv: PreservesInvariants get_rec_sysregs_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_vtimer_asserted_inv: PreservesInvariants set_rec_vtimer_asserted_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_emulated_write_val_inv: PreservesInvariants set_rec_run_emulated_write_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_run_far_inv: PreservesInvariants set_rec_run_far_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance mpidr_is_valid_inv: PreservesInvariants mpidr_is_valid_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_run_emulated_read_val_inv: PreservesInvariants get_rec_run_emulated_read_val_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_g_rec_list_inv: PreservesInvariants set_rec_g_rec_list_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_vtimer_inv: PreservesInvariants get_rec_vtimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_rec_par_end_inv: PreservesInvariants set_rec_par_end_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance granule_get_state_inv: PreservesInvariants granule_get_state_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_ptimer_inv: PreservesInvariants get_rec_ptimer_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_bitmap_loc_inv: PreservesInvariants get_bitmap_loc_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance smc_mark_nonsecure_inv: PreservesInvariants smc_mark_nonsecure_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_realm_params_rec_list_addr_inv: PreservesInvariants get_realm_params_rec_list_addr_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance set_g_rtt_rd_inv: PreservesInvariants set_g_rtt_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_bit_clear_release_64_inv: PreservesInvariants atomic_bit_clear_release_64_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance is_addr_in_par_inv: PreservesInvariants is_addr_in_par_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance sysreg_write_inv: PreservesInvariants sysreg_write_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_par_base_inv: PreservesInvariants get_rec_par_base_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rec_g_rd_inv: PreservesInvariants get_rec_g_rd_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance init_rec_read_only_inv: PreservesInvariants init_rec_read_only_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_locked_granule_inv: PreservesInvariants get_locked_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance get_rvic_pending_bits_inv: PreservesInvariants get_rvic_pending_bits_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance find_lock_unused_granule_inv: PreservesInvariants find_lock_unused_granule_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance entry_to_phys_inv: PreservesInvariants entry_to_phys_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance stage2_tlbi_ipa_inv: PreservesInvariants stage2_tlbi_ipa_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance atomic_granule_get_inv: PreservesInvariants atomic_granule_get_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance user_step_inv: PreservesInvariants user_step_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance link_table_inv: PreservesInvariants link_table_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance timer_condition_met_inv: PreservesInvariants timer_condition_met_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n    Global Instance addr_is_level_aligned_inv: PreservesInvariants addr_is_level_aligned_spec.\n    Proof.\n      constructor; intros; simpl; eauto.\n      constructor.\n    Qed.\n\n  End InvProof.\n\n  Section LayerDef.\n\n    Definition RmiAux2_fresh : compatlayer (cdata RData) :=\n      _init_rec_regs \u21a6 gensem init_rec_regs_spec\n        \u2295 _init_rec_rvic_state \u21a6 gensem init_rec_rvic_state_spec\n        \u2295 _rec_granule_measure \u21a6 gensem rec_granule_measure_spec\n      .\n\n    Definition RmiAux2_passthrough : compatlayer (cdata RData) :=\n      _shiftl \u21a6 gensem shiftl_spec\n        \u2295 _get_rd_par_base \u21a6 gensem get_rd_par_base_spec\n        \u2295 _addr_to_idx \u21a6 gensem addr_to_idx_spec\n        \u2295 _el3_sync_lel \u21a6 gensem el3_sync_lel_spec\n        \u2295 _set_rvic_result_target \u21a6 gensem set_rvic_result_target_spec\n        \u2295 _set_rec_sysregs \u21a6 gensem set_rec_sysregs_spec\n        \u2295 _validate_realm_params \u21a6 gensem validate_realm_params_spec\n        \u2295 _get_psci_result_forward_psci_call \u21a6 gensem get_psci_result_forward_psci_call_spec\n        \u2295 _granule_refcount_inc \u21a6 gensem granule_refcount_inc_spec\n        \u2295 _get_realm_params_measurement_algo \u21a6 gensem get_realm_params_measurement_algo_spec\n        \u2295 _ns_buffer_read_rec_run \u21a6 gensem ns_buffer_read_rec_run_spec\n        \u2295 _granule_put \u21a6 gensem granule_put_spec\n        \u2295 _smc_mark_realm \u21a6 gensem smc_mark_realm_spec\n        \u2295 _set_rd_state \u21a6 gensem set_rd_state_spec\n        \u2295 _entry_is_table \u21a6 gensem entry_is_table_spec\n        \u2295 _get_rec_pstate \u21a6 gensem get_rec_pstate_spec\n        \u2295 _atomic_granule_put_release \u21a6 gensem atomic_granule_put_release_spec\n        \u2295 _get_rec_run_gprs \u21a6 gensem get_rec_run_gprs_spec\n        \u2295 _set_rec_ptimer_asserted \u21a6 gensem set_rec_ptimer_asserted_spec\n        \u2295 _get_timer_asserted \u21a6 gensem get_timer_asserted_spec\n        \u2295 _get_realm_params \u21a6 gensem get_realm_params_spec\n        \u2295 _get_rec_rec_idx \u21a6 gensem get_rec_rec_idx_spec\n        \u2295 _get_rec_run_is_emulated_mmio \u21a6 gensem get_rec_run_is_emulated_mmio_spec\n        \u2295 _read_reg \u21a6 gensem read_reg_spec\n        \u2295 _granule_refcount_dec \u21a6 gensem granule_refcount_dec_spec\n        \u2295 _interrupt_bitmap_dword \u21a6 gensem interrupt_bitmap_dword_spec\n        \u2295 _set_rd_measurement_algo \u21a6 gensem set_rd_measurement_algo_spec\n        \u2295 _get_rec_ptimer_masked \u21a6 gensem get_rec_ptimer_masked_spec\n        \u2295 _measurement_extend_data_header \u21a6 gensem measurement_extend_data_header_spec\n        \u2295 _granule_lock \u21a6 gensem granule_lock_spec\n        \u2295 _ns_buffer_unmap \u21a6 gensem ns_buffer_unmap_spec\n        \u2295 _granule_memzero_mapped \u21a6 gensem granule_memzero_mapped_spec\n        \u2295 _ptr_eq \u21a6 gensem ptr_eq_spec\n        \u2295 _get_rec_common_sysregs \u21a6 gensem get_rec_common_sysregs_spec\n        \u2295 _is_addr_in_par_rec \u21a6 gensem is_addr_in_par_rec_spec\n        \u2295 _get_rd_state \u21a6 gensem get_rd_state_spec\n        \u2295 _set_rec_par_base \u21a6 gensem set_rec_par_base_spec\n        \u2295 _esr_sixty_four \u21a6 gensem esr_sixty_four_spec\n        \u2295 _get_rvic_mask_bits \u21a6 gensem get_rvic_mask_bits_spec\n        \u2295 _run_realm \u21a6 gensem run_realm_spec\n        \u2295 _get_rec_params_flags \u21a6 gensem get_rec_params_flags_spec\n        \u2295 _get_timer_masked \u21a6 gensem get_timer_masked_spec\n        \u2295 _get_target_rec \u21a6 gensem get_target_rec_spec\n        \u2295 _set_psci_result_forward_psci_call \u21a6 gensem set_psci_result_forward_psci_call_spec\n        \u2295 _get_g_rtt_refcount \u21a6 gensem get_g_rtt_refcount_spec\n        \u2295 _esr_srt \u21a6 gensem esr_srt_spec\n        \u2295 _set_rec_pstate \u21a6 gensem set_rec_pstate_spec\n        \u2295 _get_rec_pc \u21a6 gensem get_rec_pc_spec\n        \u2295 _get_rd_par_end \u21a6 gensem get_rd_par_end_spec\n        \u2295 _is_rec_valid \u21a6 gensem is_rec_valid_spec\n        \u2295 _granule_get \u21a6 gensem granule_get_spec\n        \u2295 _set_rd_par_base \u21a6 gensem set_rd_par_base_spec\n        \u2295 _get_realm_params_par_size \u21a6 gensem get_realm_params_par_size_spec\n        \u2295 _buffer_unmap \u21a6 gensem buffer_unmap_spec\n        \u2295 _access_len \u21a6 gensem access_len_spec\n        \u2295 _enter_rmm \u21a6 gensem enter_rmm_spec\n        \u2295 _get_g_rec_rd \u21a6 gensem get_g_rec_rd_spec\n        \u2295 _get_realm_params_rtt_addr \u21a6 gensem get_realm_params_rtt_addr_spec\n        \u2295 _set_rec_ptimer_masked \u21a6 gensem set_rec_ptimer_masked_spec\n        \u2295 _set_rd_g_rec_list \u21a6 gensem set_rd_g_rec_list_spec\n        \u2295 _set_rd_par_end \u21a6 gensem set_rd_par_end_spec\n        \u2295 _sysreg_read \u21a6 gensem sysreg_read_spec\n        \u2295 _granule_set_state \u21a6 gensem granule_set_state_spec\n        \u2295 _null_ptr \u21a6 gensem null_ptr_spec\n        \u2295 _timer_is_masked \u21a6 gensem timer_is_masked_spec\n        \u2295 _set_rd_g_rtt \u21a6 gensem set_rd_g_rtt_spec\n        \u2295 _get_ns_state \u21a6 gensem get_ns_state_spec\n        \u2295 _set_g_rec_rd \u21a6 gensem set_g_rec_rd_spec\n        \u2295 _set_rec_vtimer_masked \u21a6 gensem set_rec_vtimer_masked_spec\n        \u2295 _get_wi_g_llt \u21a6 gensem get_wi_g_llt_spec\n        \u2295 _set_rec_run_esr \u21a6 gensem set_rec_run_esr_spec\n        \u2295 _granule_map \u21a6 gensem granule_map_spec\n        \u2295 _set_rvic_result_ns_notify \u21a6 gensem set_rvic_result_ns_notify_spec\n        \u2295 _realm_get_rec_entry \u21a6 gensem realm_get_rec_entry_spec\n        \u2295 _set_ns_state \u21a6 gensem set_ns_state_spec\n        \u2295 _get_rec_g_rec \u21a6 gensem get_rec_g_rec_spec\n        \u2295 _set_rec_run_gprs \u21a6 gensem set_rec_run_gprs_spec\n        \u2295 _set_rec_run_hpfar \u21a6 gensem set_rec_run_hpfar_spec\n        \u2295 _get_psci_result_x0 \u21a6 gensem get_psci_result_x0_spec\n        \u2295 _set_rec_runnable \u21a6 gensem set_rec_runnable_spec\n        \u2295 _get_psci_result_x1 \u21a6 gensem get_psci_result_x1_spec\n        \u2295 _interrupt_bit \u21a6 gensem interrupt_bit_spec\n        \u2295 _get_psci_result_x2 \u21a6 gensem get_psci_result_x2_spec\n        \u2295 _find_lock_granule \u21a6 gensem find_lock_granule_spec\n        \u2295 _is_null \u21a6 gensem is_null_spec\n        \u2295 _get_rec_rvic_enabled \u21a6 gensem get_rec_rvic_enabled_spec\n        \u2295 _assert_cond \u21a6 gensem assert_cond_spec\n        \u2295 _set_target_rec \u21a6 gensem set_target_rec_spec\n        \u2295 _pgte_read \u21a6 gensem pgte_read_spec\n        \u2295 _get_rd_g_rec_list \u21a6 gensem get_rd_g_rec_list_spec\n        \u2295 _get_rec_vtimer_masked \u21a6 gensem get_rec_vtimer_masked_spec\n        \u2295 _set_wi_g_llt \u21a6 gensem set_wi_g_llt_spec\n        \u2295 _get_rec_last_run_info_esr \u21a6 gensem get_rec_last_run_info_esr_spec\n        \u2295 _measurement_finish \u21a6 gensem measurement_finish_spec\n        \u2295 _get_rec_g_rec_list \u21a6 gensem get_rec_g_rec_list_spec\n        \u2295 _esr_is_write \u21a6 gensem esr_is_write_spec\n        \u2295 _get_psci_result_x3 \u21a6 gensem get_psci_result_x3_spec\n        \u2295 _get_wi_index \u21a6 gensem get_wi_index_spec\n        \u2295 _set_wi_index \u21a6 gensem set_wi_index_spec\n        \u2295 _set_timer_masked \u21a6 gensem set_timer_masked_spec\n        \u2295 _mpidr_to_rec_idx \u21a6 gensem mpidr_to_rec_idx_spec\n        \u2295 _granule_unlock \u21a6 gensem granule_unlock_spec\n        \u2295 _emulate_timer_ctl_read \u21a6 gensem emulate_timer_ctl_read_spec\n        \u2295 _exit_rmm \u21a6 gensem exit_rmm_spec\n        \u2295 _measurement_extend_data \u21a6 gensem measurement_extend_data_spec\n        \u2295 _ESR_EL2_SYSREG_IS_WRITE \u21a6 gensem ESR_EL2_SYSREG_IS_WRITE_spec\n        \u2295 _barrier \u21a6 gensem barrier_spec\n        \u2295 _access_mask \u21a6 gensem access_mask_spec\n        \u2295 _esr_sign_extend \u21a6 gensem esr_sign_extend_spec\n        \u2295 _set_rec_dispose_pending \u21a6 gensem set_rec_dispose_pending_spec\n        \u2295 _get_rd_g_rtt \u21a6 gensem get_rd_g_rtt_spec\n        \u2295 _set_rec_last_run_info_esr \u21a6 gensem set_rec_last_run_info_esr_spec\n        \u2295 _set_rvic_result_x0 \u21a6 gensem set_rvic_result_x0_spec\n        \u2295 _granule_memzero \u21a6 gensem granule_memzero_spec\n        \u2295 _test_bit_acquire_64 \u21a6 gensem test_bit_acquire_64_spec\n        \u2295 _set_psci_result_forward_x1 \u21a6 gensem set_psci_result_forward_x1_spec\n        \u2295 _get_rec_regs \u21a6 gensem get_rec_regs_spec\n        \u2295 _get_psci_result_forward_x3 \u21a6 gensem get_psci_result_forward_x3_spec\n        \u2295 _get_rec_rvic \u21a6 gensem get_rec_rvic_spec\n        \u2295 _realm_set_rec_entry \u21a6 gensem realm_set_rec_entry_spec\n        \u2295 _get_psci_result_forward_x2 \u21a6 gensem get_psci_result_forward_x2_spec\n        \u2295 _get_psci_result_forward_x1 \u21a6 gensem get_psci_result_forward_x1_spec\n        \u2295 _set_rec_run_exit_reason \u21a6 gensem set_rec_run_exit_reason_spec\n        \u2295 _ESR_EL2_SYSREG_ISS_RT \u21a6 gensem ESR_EL2_SYSREG_ISS_RT_spec\n        \u2295 _atomic_granule_put \u21a6 gensem atomic_granule_put_spec\n        \u2295 _ns_buffer_read_rec_params \u21a6 gensem ns_buffer_read_rec_params_spec\n        \u2295 _find_lock_three_delegated_granules \u21a6 gensem find_lock_three_delegated_granules_spec\n        \u2295 _atomic_bit_set_release_64 \u21a6 gensem atomic_bit_set_release_64_spec\n        \u2295 _read_idreg \u21a6 gensem read_idreg_spec\n        \u2295 _get_rec_par_end \u21a6 gensem get_rec_par_end_spec\n        \u2295 _set_rec_g_rd \u21a6 gensem set_rec_g_rd_spec\n        \u2295 _get_realm_params_par_base \u21a6 gensem get_realm_params_par_base_spec\n        \u2295 _measurement_start \u21a6 gensem measurement_start_spec\n        \u2295 _set_psci_result_x0 \u21a6 gensem set_psci_result_x0_spec\n        \u2295 _set_mapping \u21a6 gensem set_mapping_spec\n        \u2295 _set_rec_pc \u21a6 gensem set_rec_pc_spec\n        \u2295 _set_rec_regs \u21a6 gensem set_rec_regs_spec\n        \u2295 _get_rec_runnable \u21a6 gensem get_rec_runnable_spec\n        \u2295 _ns_granule_map \u21a6 gensem ns_granule_map_spec\n        \u2295 _get_rec_sysregs \u21a6 gensem get_rec_sysregs_spec\n        \u2295 _set_rec_vtimer_asserted \u21a6 gensem set_rec_vtimer_asserted_spec\n        \u2295 _set_rec_run_emulated_write_val \u21a6 gensem set_rec_run_emulated_write_val_spec\n        \u2295 _set_rec_run_far \u21a6 gensem set_rec_run_far_spec\n        \u2295 _mpidr_is_valid \u21a6 gensem mpidr_is_valid_spec\n        \u2295 _get_rec_run_emulated_read_val \u21a6 gensem get_rec_run_emulated_read_val_spec\n        \u2295 _set_rec_g_rec_list \u21a6 gensem set_rec_g_rec_list_spec\n        \u2295 _get_rec_vtimer \u21a6 gensem get_rec_vtimer_spec\n        \u2295 _set_rec_par_end \u21a6 gensem set_rec_par_end_spec\n        \u2295 _granule_get_state \u21a6 gensem granule_get_state_spec\n        \u2295 _get_rec_ptimer \u21a6 gensem get_rec_ptimer_spec\n        \u2295 _get_bitmap_loc \u21a6 gensem get_bitmap_loc_spec\n        \u2295 _smc_mark_nonsecure \u21a6 gensem smc_mark_nonsecure_spec\n        \u2295 _get_realm_params_rec_list_addr \u21a6 gensem get_realm_params_rec_list_addr_spec\n        \u2295 _set_g_rtt_rd \u21a6 gensem set_g_rtt_rd_spec\n        \u2295 _atomic_bit_clear_release_64 \u21a6 gensem atomic_bit_clear_release_64_spec\n        \u2295 _ns_buffer_read_data \u21a6 gensem ns_buffer_read_data_spec\n        \u2295 _pgte_write \u21a6 gensem pgte_write_spec\n        \u2295 _is_addr_in_par \u21a6 gensem is_addr_in_par_spec\n        \u2295 _sysreg_write \u21a6 gensem sysreg_write_spec\n        \u2295 _find_granule \u21a6 gensem find_granule_spec\n        \u2295 _get_rec_par_base \u21a6 gensem get_rec_par_base_spec\n        \u2295 _get_rec_g_rd \u21a6 gensem get_rec_g_rd_spec\n        \u2295 _init_rec_read_only \u21a6 gensem init_rec_read_only_spec\n        \u2295 _get_locked_granule \u21a6 gensem get_locked_granule_spec\n        \u2295 _get_rvic_pending_bits \u21a6 gensem get_rvic_pending_bits_spec\n        \u2295 _find_lock_unused_granule \u21a6 gensem find_lock_unused_granule_spec\n        \u2295 _entry_to_phys \u21a6 gensem entry_to_phys_spec\n        \u2295 _stage2_tlbi_ipa \u21a6 gensem stage2_tlbi_ipa_spec\n        \u2295 _atomic_granule_get \u21a6 gensem atomic_granule_get_spec\n        \u2295 _user_step \u21a6 gensem user_step_spec\n        \u2295 _link_table \u21a6 gensem link_table_spec\n        \u2295 _timer_condition_met \u21a6 gensem timer_condition_met_spec\n        \u2295 _addr_is_level_aligned \u21a6 gensem addr_is_level_aligned_spec\n      .\n\n    Definition RmiAux2 := RmiAux2_fresh \u2295 RmiAux2_passthrough.\n\n  End LayerDef.\n\nEnd Layer.\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/Layer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.33111972642778725, "lm_q1q2_score": 0.17202375307163212}}
{"text": "Require Import compcert.common.AST.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Values.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Maps.\nRequire Import Seccompconf.\n\nSet Implicit Arguments.\n\nInductive alu_safe : Type :=\n  | Aaddimm: int -> alu_safe\n  | Asubimm: int -> alu_safe\n  | Amulimm: int -> alu_safe\n  | Aandimm: int -> alu_safe\n  | Aorimm: int -> alu_safe\n  | Axorimm: int -> alu_safe\n  | Aadd: alu_safe\n  | Asub: alu_safe\n  | Amul: alu_safe\n  | Aand: alu_safe\n  | Aor: alu_safe\n  | Axor: alu_safe\n  | Aneg: alu_safe\n  .\n\nInductive alu_div : Type :=\n  | Adivimm: int -> alu_div\n  | Amodimm: int -> alu_div\n  | Adiv: alu_div\n  | Amod: alu_div\n  .\n\nInductive alu_shift : Type :=\n  | Alshimm: int -> alu_shift\n  | Arshimm: int -> alu_shift\n  | Alsh: alu_shift\n  | Arsh: alu_shift\n  .\n\nInductive condition : Type :=\n  | Jgtimm: int -> condition\n  | Jgeimm: int -> condition\n  | Jeqimm: int -> condition\n  | Jsetimm: int -> condition\n  | Jgt: condition\n  | Jge: condition\n  | Jeq: condition\n  | Jset: condition\n  .\n\nInductive instruction : Type :=\n  | Salu_safe: alu_safe -> instruction\n      (** A <- arithmetic *)\n  | Salu_div: alu_div -> instruction\n      (** A <- arithmetic *)\n  | Salu_shift: alu_shift -> instruction\n      (** A <- arithmetic *)\n  | Sld_w_abs: int -> instruction\n      (** A <- seccomp_bpf_load(k), access struct seccomp_data *)\n  | Sld_w_len: instruction\n      (** A <- sizeof(struct seccomp_data) *)\n  | Sldx_w_len: instruction\n      (** X <- sizeof(struct seccomp_data) *)\n  | Sld_imm: int -> instruction\n      (** A <- k *)\n  | Sldx_imm: int -> instruction\n      (** X <- k *)\n  | Sld_mem: int -> instruction\n      (** A <- [k] *)\n  | Sldx_mem: int -> instruction\n      (** X <- [k] *)\n  | Sst: int -> instruction\n      (** [k] <- A *)\n  | Sstx: int -> instruction\n      (** [k] <- X *)\n  | Sjmp_ja: int -> instruction\n  | Sjmp_jc: condition -> byte -> byte -> instruction\n  | Smisc_tax: instruction\n      (** X <- A *)\n  | Smisc_txa: instruction\n      (** A <- X *)\n  | Sret_k: int -> instruction\n      (** ret k **)\n  | Sret_a: instruction\n      (** ret A **)\n  .\n\nDefinition code := list instruction.\n\nSection PROGRAM.\n\nDefinition function := code.\n\nDefinition fundef := AST.fundef function.\n\nDefinition program := AST.program fundef unit.\n\nEnd PROGRAM.\n\nSection SEMANTICS.\n\nDefinition genv := Genv.t fundef unit.\n\nInductive state : Type :=\n  | State:\n    forall (a: int)              (**r accumulator *)\n           (x: int)              (**r index register *)\n           (sm: ZMap.t val)      (**r scratch memory *)\n           (f: function)         (**r current function *)\n           (c: code)             (**r current program point *)\n           (p: block)            (**r input packet *)\n           (m: mem),             (**r memory state *)\n    state\n  | Callstate:\n    forall (fd: fundef)          (**r calling function *)\n           (p: block)            (**r input packet *)\n           (m: mem),             (**r memory state *)\n    state\n  | Returnstate:\n    forall (v: int)              (**r local return value *)\n           (m: mem),             (**r memory state *)\n    state\n  .\n\nDefinition eval_alu_safe (op: alu_safe) (a: int) (x: int): int :=\n  match op with\n  | Aaddimm k => Int.add a k\n  | Asubimm k => Int.sub a k\n  | Amulimm k => Int.mul a k\n  | Aandimm k => Int.and a k\n  | Aorimm k => Int.or a k\n  | Axorimm k => Int.xor a k\n  | Aadd => Int.add a x\n  | Asub => Int.sub a x\n  | Amul => Int.mul a x\n  | Aand => Int.and a x\n  | Aor => Int.or a x\n  | Axor => Int.xor a x\n  | Aneg => Int.neg a\n  end.\n\nDefinition eval_alu_div (op: alu_div) (a: int) (x: int): int :=\n  match op with\n  | Adivimm k => Int.divu a k\n  | Amodimm k => Int.modu a k\n  | Adiv => Int.divu a x\n  | Amod => Int.modu a x\n  end.\n\nDefinition eval_alu_shift (op: alu_shift) (a: int) (x: int): int :=\n  match op with\n  | Alshimm k => Int.shl a k\n  | Arshimm k => Int.shru a k\n  | Alsh => Int.shl a x\n  | Arsh => Int.shru a x\n  end.\n\nDefinition eval_cond (cond: condition) (a: int) (x: int): bool :=\n  match cond with\n  | Jsetimm k => negb (Int.eq (Int.and a k) Int.zero)\n    (* A & k *)\n  | Jgtimm k => Int.cmpu Cgt a k\n    (* A > k *)\n  | Jgeimm k => Int.cmpu Cge a k\n    (* A >= k *)\n  | Jeqimm k => Int.eq a k\n    (* A == k *)\n  | Jset => negb (Int.eq (Int.and a x) Int.zero)\n    (* A & X *)\n  | Jgt => Int.cmpu Cgt a x\n    (* A > X *)\n  | Jge => Int.cmpu Cge a x\n    (* A >= X *)\n  | Jeq => Int.eq a x\n    (* A == X *)\n  end.\n\nInductive step (ge: genv) : state -> trace -> state -> Prop :=\n  | exec_Salu_safe:\n      forall op a x sm f b p m,\n      let a' := eval_alu_safe op a x in\n      step ge (State a x sm f (Salu_safe op :: b) p m)\n        E0 (State a' x sm f b p m)\n  (* NB: could return 0 for div by zero *)\n  | exec_Salu_div:\n      forall op a x sm f b p m,\n      let a' := eval_alu_div op a x in\n      step ge (State a x sm f (Salu_div op :: b) p m)\n        E0 (State a' x sm f b p m)\n  | exec_Salu_shift:\n      forall op a x sm f b p m,\n      let a' := eval_alu_shift op a x in\n      step ge (State a x sm f (Salu_shift op :: b) p m)\n        E0 (State a' x sm f b p m)\n  | exec_Sjmp_ja:\n      forall a x sm f k b p m,\n      let off := Int.unsigned k in\n      off < (list_length_z b) ->\n      step ge (State a x sm f (Sjmp_ja k :: b) p m)\n        E0 (State a x sm f (skipn (nat_of_Z off) b) p m)\n  | exec_Sjmp_jc:\n      forall cond jt jf a x sm f b p m,\n      let off := Byte.unsigned (if (eval_cond cond a x) then jt else jf) in\n      off < (list_length_z b) ->\n      step ge (State a x sm f (Sjmp_jc cond jt jf :: b) p m)\n        E0 (State a x sm f (skipn (nat_of_Z off) b) p m)\n  | exec_Sld_w_abs:\n      forall a a' k x sm f b p m,\n      let off := Int.unsigned k in\n      off < sizeof_seccomp_data ->\n      off mod 4 = 0 ->\n      Mem.load Mint32 m p off = Some (Vint a') ->\n      step ge (State a x sm f (Sld_w_abs k :: b) p m)\n        E0 (State a' x sm f b p m)\n  | exec_Sld_w_len:\n      forall a x sm f b p m,\n      let a' := Int.repr sizeof_seccomp_data in\n      step ge (State a x sm f (Sld_w_len :: b) p m)\n        E0 (State a' x sm f b p m)\n  | exec_Sldx_w_len:\n      forall a x sm f b p m,\n      let x' := Int.repr sizeof_seccomp_data in\n      step ge (State a x sm f (Sldx_w_len :: b) p m)\n        E0 (State a x' sm f b p m)\n  | exec_Sld_imm:\n      forall a x sm f k b p m,\n      step ge (State a x sm f (Sld_imm k :: b) p m)\n        E0 (State k x sm f b p m)\n  | exec_Sldx_imm:\n      forall a x sm f k b p m,\n      step ge (State a x sm f (Sldx_imm k :: b) p m)\n        E0 (State a k sm f b p m)\n  | exec_Sld_mem:\n      forall a a' k x sm f b p m,\n      let idx := Int.unsigned k in\n      idx < seccomp_memwords ->\n      ZMap.get idx sm = Vint a' ->\n      step ge (State a x sm f (Sld_mem k :: b) p m)\n        E0 (State a' x sm f b p m)\n  | exec_Smisc_tax:\n      forall a x sm f b p m,\n      step ge (State a x sm f (Smisc_tax :: b) p m)\n        E0 (State a a sm f b p m)\n  | exec_Smisc_txa:\n      forall a x sm f b p m,\n      step ge (State a x sm f (Smisc_txa :: b) p m)\n        E0 (State x x sm f b p m)\n  | exec_Sret_a:\n      forall a x sm f b p m,\n      step ge (State a x sm f (Sret_a :: b) p m)\n        E0 (Returnstate a m)\n  | exec_Sret_k:\n      forall a x sm f k b p m,\n      step ge (State a x sm f (Sret_k k :: b) p m)\n        E0 (Returnstate k m)\n  | exec_call:\n      forall f p m,\n      step ge (Callstate (Internal f) p m)\n        E0 (State Int.zero Int.zero (ZMap.init Vundef) f f p m)\n  .\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b fd m0 m1 m2 pkt,\n    let ge := Genv.globalenv p in\n    Genv.init_mem p = Some m0 ->\n    Genv.find_symbol ge p.(prog_main) = Some b ->\n    Genv.find_funct_ptr ge b = Some fd ->\n    Mem.alloc m0 0 sizeof_seccomp_data = (m1, pkt) ->\n    Mem.storebytes m1 pkt 0 (Memdata.inj_bytes seccomp_data) = Some m2 ->\n    initial_state p (Callstate fd pkt m2).\n\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall v m,\n      final_state (Returnstate v m) v.\n\nEnd SEMANTICS.\n", "meta": {"author": "utokyo-lzh", "repo": "Jitk", "sha": "7f7f6eb541c7e8a2613974fff5b4fc6fc0783182", "save_path": "github-repos/coq/utokyo-lzh-Jitk", "path": "github-repos/coq/utokyo-lzh-Jitk/Jitk-7f7f6eb541c7e8a2613974fff5b4fc6fc0783182/Seccomp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.17186450806089307}}
{"text": "(*\n * \u00a9 2020 XXX.\n * \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     ModelCheck\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require Import Sets.\n\nModule Foo <: Sets.EMPTY.\nEnd Foo.\nModule Export SN := Sets.SetNotations(Foo).\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nModule SecureDNSProtocol.\n\n  (* Start with two users, as that is the minimum for any interesting protocol *)\n  Notation USR1 := 0.\n  Notation USR2 := 1.\n  Notation USR3 := 2.\n\n  Parameter names : NatMap.t nat.\n  \n  Section IW.\n    Import IdealWorld.\n\n    (* Set up initial communication channels so each user can talk directly to the other *)\n    Notation pCH12 := 0.\n    Notation pCH21 := 1.\n    Notation pCH23 := 2.\n    Notation pCH32 := 3.\n    Notation CH12  := (# pCH12).\n    Notation CH21  := (# pCH21).\n    Notation CH23  := (# pCH23).\n    Notation CH32  := (# pCH32).\n\n    (* This is the initial channel vector, each channel should be represented and start with \n     * no messages.\n     *)\n    Notation empty_chs := (#0 #+ (CH12, []) #+ (CH21, []) #+ (CH23, []) #+ (CH32, [])).\n\n    Notation PERMS1 := ($0 $+ (pCH12, writer) $+ (pCH21, reader)).\n    Notation PERMS2 := ($0 $+ (pCH12, reader) $+ (pCH21, writer) $+ (pCH23, writer) $+ (pCH32, reader)).\n    Notation PERMS3 := ($0 $+ (pCH23, reader) $+ (pCH32, writer)).\n\n    Fixpoint idealServer (n : nat) {t} (r : << t >>) (c : cmd t) : cmd t :=\n      match n with\n      | 0   => @Return t r\n      | S i => (r' <- c ; idealServer i r' c)\n      end.\n\n    (* Fill in the users' protocol specifications here, adding additional users as needed.\n     * Note that all users must return an element of the same type, and that type needs to \n     * be one of: ...\n     *)\n    Notation ideal_users :=\n      [\n        (* Authorative DNS Server Specification *)\n        mkiUsr USR1 PERMS1\n               (\n                 @idealServer 1 (Base Nat) 1\n                              (\n                                m <- @Recv Nat CH21\n                                ; let ip := match names $? extractContent m with\n                                            | None   => 0\n                                            | Some a => a\n                                            end\n                                  in\n                                  _ <- Send (Content ip) CH12\n                                ; @Return (Base Nat) ip\n                              )\n               )\n        ;\n\n      (* Secure DNS Cache Specification *)\n      mkiUsr USR2 PERMS2\n             (\n               req <- @Recv Nat CH32\n               ; _ <- Send (Content (extractContent req)) CH21\n               ; ip1 <- @Recv Nat CH12\n               ; _ <- Send (Content (extractContent ip1)) CH23\n               ; @Return (Base Nat) (extractContent ip1)\n             )\n        ;\n\n      (* DNS Client Specification *)\n      mkiUsr USR3 PERMS3\n             (\n               _ <- Send (Content 0) CH32\n               ; ip1 <- @Recv Nat CH23\n               ; @Return (Base Nat) (extractContent ip1)\n             )\n      ].\n\n    (* This is where the entire specification universe gets assembled.  It is unlikely anything\n     * will need to change here.\n     *)\n    Definition ideal_univ_start :=\n      mkiU empty_chs ideal_users.\n      \n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    (* Key management needs to be bootstrapped.  Since all honest users must only send signed\n     * messages, we need some way of initially distributing signing keys in order to be able\n     * to begin secure communication.  This is analagous in the real world where we need to \n     * have some sort of trust relationship in order to distribute trusted keys.\n     * \n     * Here, each user has a public asymmetric signing key.\n     *)\n    Notation KID1 := 0.\n    Notation KID2 := 1.\n    Notation KID3 := 2.\n    Notation KID4 := 3.\n    Notation KID5 := 4.\n    Notation KID6 := 5.\n\n    Notation KEYS := [ skey KID1 ; ekey KID2 ; skey KID3 ; ekey KID4 ; skey KID5 ; ekey KID6 ].\n\n    Notation KEYS1 := ($0 $+ (KID1, true) $+ (KID2, true) $+ (KID3, false) $+ (KID4, false)).\n    Notation KEYS2 := ($0 $+ (KID1, false) $+ (KID2, false)\n                        $+ (KID3, true) $+ (KID4, true)\n                        $+ (KID5, false) $+ (KID6, false)).\n    Notation KEYS3 := ($0 $+ (KID3, false) $+ (KID4, false) $+ (KID5, true) $+ (KID6, true)).\n\n    Fixpoint realServer (n : nat) {t} (r : << t >>) (c : user_cmd t) : user_cmd t :=\n      match n with\n      | 0   => @Return t r\n      | S i => (r' <- c ; realServer i r' c)\n      end.\n\n    Notation real_users :=\n      [\n        (* Authoritative DNS server implementation *)\n        MkRUserSpec USR1 KEYS1\n                    (\n                      @realServer 1 (Base Nat) 1\n                                  ( c <- @Recv Nat (SignedEncrypted KID3 KID2 true)\n                                    ; m <- Decrypt c\n                                    ; let ip := match names $? (extractContent m) with\n                                                | None   => 0\n                                                | Some a => a\n                                                end\n                                      in ipC <- SignEncrypt KID1 KID4 USR2 (message.Content ip)\n                                    ; _ <- Send USR2 ipC\n                                    ; @Return (Base Nat) ip\n                                  )\n                    )\n        ;\n\n      (* Secure DNS Cache implementation *)\n      MkRUserSpec USR2 KEYS2\n                  (\n                    reqc <- @Recv Nat (SignedEncrypted KID5 KID4 true)\n                    ; req <- Decrypt reqc\n                    ; c1 <- SignEncrypt KID3 KID2 USR1 (message.Content (extractContent req))\n                    ; _ <- Send USR1 c1\n                    ; hostC <- @Recv Nat (SignedEncrypted KID1 KID4 true)\n                    ; host <- Decrypt hostC\n                    ; c2 <- SignEncrypt KID3 KID6 USR3 (message.Content (extractContent host))\n                    ; _ <- Send USR3 c2\n                    ; @Return (Base Nat) (extractContent host)\n                  ) \n        ;\n\n      (* DNS Client implementation *)\n      MkRUserSpec USR3 KEYS3\n                  (\n                    c <- SignEncrypt KID5 KID4 USR2 (message.Content 0)\n                    ; _ <- Send USR2 c\n                    ; hostC <- @Recv Nat (SignedEncrypted KID3 KID6 true)\n                    ; host <- Decrypt hostC\n                    ; @Return (Base Nat) (extractContent host)\n                  ) \n      ].\n\n    (* Here is where we put the implementation universe together.  Like above, it is \n     * unlikely anything will need to change here.\n     *)\n    Definition real_univ_start :=\n      mkrU (mkKeys KEYS) real_users.\n  End RW.\n\n  (* These are here to help the proof automation.  Don't change. *)\n  #[export] Hint Unfold\n       real_univ_start\n       ideal_univ_start\n    : user_build.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with user_build; simpl) : core.\n  \nEnd SecureDNSProtocol.\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/protocols/SecureDNS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1717875095396386}}
{"text": "(*\n\tcoqtop -R ../../../kami/Kami Kami -R $PWD BK \n*)\n\nRequire Import Bool String List Arith.\nRequire Import Kami.\nRequire Import Lib.Indexer Lib.Struct.\nRequire Import Bsvtokami.\nRequire Import MiniRiscvMMode.\nRequire Import Kami.Duplicate.\n\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\n\nDefinition spec := ProcMMode'modules (mkMiniRiscvMMode \"spec\" ($$(natToWord 1 0))%kami ($$ (natToWord 1 0))%kami ($$ (natToWord 1 0))%kami).\nDefinition impl := ProcMMode'modules (mkMiniRiscvMMode \"impl\" ($$(natToWord 1 0))%kami ($$ (natToWord 1 0))%kami ($$ (natToWord 1 0))%kami).\n\nCheck spec.\nCheck impl.\n\nCompute (map (fun reg => (attrName reg)) (getRegInits (spec))).\n\nHint Unfold spec impl: ModuleDefs.\n\nDefinition spec_impl_ruleMap (_: RegsT): string -> option string :=\n  fun regname => Some regname.\n\nCompute 1.\n\nLemma spec_ModEquiv:\n  ModPhoasWf spec.\nProof. kequiv. Qed.\nHint Resolve spec_ModEquiv.\n\nCompute 2.\n\nLemma impl_ModEquiv:\n  ModPhoasWf impl.\nProof. kequiv. Qed.\nHint Resolve impl_ModEquiv.\n\nCompute 3.\n\nRequire Import Kami.Wf.\nRequire Import Lib.Reflection.\nRequire Import Lib.StringEq.\n\nDefinition Is_true (b : bool) :=\n  match b with\n  | true => True\n  | false => False\n  end.\n\nTheorem eqb_a_a:\n  (forall a : bool, Is_true (eqb a a)).\nProof.\n  intros a.\n  case a.\n    simpl. exact I.\n    simpl. exact I.\nQed.\n\nTheorem spec_impl_refinement:\n  impl <<== spec.\nProof.\n  (* repeat autounfold with ModuleDefs. *)\n  apply traceRefines_inlining_left.\n  apply impl_ModEquiv.\n  kinline_compute.\n  noDup_tac.\n  remember (inlineF impl) as im eqn:Heq.\n  repeat autounfold with ModuleDefs in Heq.\n\n  cbv [string_eq attrName withPrefix append prefixSymbol] in Heq.\n  cbv [inlineF inline inlineDms inlineDms'\n               inlineDmToMod inlineDmToRules inlineDmToRule\n               inlineDmToDms inlineDmToDm inlineDm\n               filterDms filter\n               noInternalCalls noCalls\n               noCallsRules noCallsDms noCallDm isLeaf\n               getBody inlineArg\n               appendAction getAttribute\n               makeModule makeModule' max plus\n\t       ] in Heq.\n\n  cbv [getDefsBodies namesOf filter map app attrName string_eq ascii_eq] in Heq.\n  rewrite eqb_reflx in Heq.\n  rewrite andb_diag in Heq.\n\n  cbv [getDefsBodies namesOf filter map app attrName string_eq ascii_eq andb orb negb] in Heq.\n\n  cbv [inlineF inline inlineDms inlineDms'\n               inlineDmToMod inlineDmToRules inlineDmToRule\n               inlineDmToDms inlineDmToDm inlineDm\n               filterDms filter\n               noInternalCalls noCalls\n               noCallsRules noCallsDms noCallDm isLeaf\n               getBody inlineArg\n               appendAction getAttribute\n               makeModule makeModule' max plus\n               getRegInits getDefs getDefsBodies getRules namesOf\n               map app attrName attrType\n               getCalls getCallsR getCallsM getCallsA\n\t       ] in Heq.\n\n\n  cbv [inlineF inline inlineDms inlineDms'\n               inlineDmToMod inlineDmToRules inlineDmToRule\n               inlineDmToDms inlineDmToDm inlineDm\n               filterDms filter\n               noInternalCalls noCalls\n               noCallsRules noCallsDms noCallDm isLeaf\n               getBody inlineArg\n               appendAction getAttribute\n               makeModule makeModule' max plus\n               getRegInits getDefs getDefsBodies getRules namesOf\n               map app attrName attrType\n               getCalls getCallsR getCallsM getCallsA\n               ret arg fst snd projT1 projT2\n               string_in string_eq ascii_eq\n               eqb existsb andb orb negb] in Heq.\n\n  (* kinline_left implInlined. *)\n\n  kdecompose_nodefs spec_impl_regMap spec_impl_ruleMap.\nQed.\n", "meta": {"author": "jameyhicks", "repo": "mini-riscv-kami", "sha": "4cf39dfe4d34b8dc68e39159d85b2353e02449ce", "save_path": "github-repos/coq/jameyhicks-mini-riscv-kami", "path": "github-repos/coq/jameyhicks-mini-riscv-kami/mini-riscv-kami-4cf39dfe4d34b8dc68e39159d85b2353e02449ce/proof1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.17170341346986775}}
{"text": "\n(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export Quorum.\nRequire Export CorrectTrace.\nRequire Export Process.\n\n\nSection LearnAndKnow.\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\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n\n  Class LearnAndKnow (n : nat) :=\n    MkLearnAndKnow {\n        (* known raw data *)\n        lak_data : Type;\n\n        (* some distinguished information embedded in the data *)\n        lak_info : Type;\n\n        (* to compute the info from the data *)\n        lak_data2info : lak_data -> lak_info;\n\n        (* where we store data *)\n        lak_memory : Type;\n\n        (* explains what it means to know the data *)\n        lak_knows : lak_data -> lak_memory -> Prop;\n\n        (* \"owner\" of the data *)\n        lak_data2owner : lak_data -> node_type;\n\n        (* to verify the authenticity of the data *)\n        lak_data2auth : lak_data -> AuthenticatedData;\n        lak_verify : forall {eo : EventOrdering} (e : Event) (d : lak_data), bool;\n\n        (* the system *)\n        lak_output : Type;\n        lak_system : node_type -> StateMachine lak_memory msg lak_output;\n        lak_no_initial_memory : forall n d, ~ lak_knows d (sm_state (lak_system n));\n      }.\n\n  Context { p : nat }.\n  Context { lak : LearnAndKnow p }.\n\n  Definition lak_data2node (d : lak_data) : name :=\n    node2name (lak_data2owner d).\n\n  Definition knows\n             {eo : EventOrdering}\n             (e  : Event)\n             (d  : lak_data) :=\n    exists mem n,\n      loc e = node2name n\n      /\\ lak_knows d mem\n      /\\ state_sm_on_event (lak_system n) e = Some mem.\n\n  Definition knew\n             {eo : EventOrdering}\n             (e  : Event)\n             (d  : lak_data) :=\n    exists mem n,\n      loc e = node2name n\n      /\\ lak_knows d mem\n      /\\ state_sm_before_event (lak_system n) e = Some mem.\n\n  (* We know a list of length [n] of [lak_info] stuff that we got from various owners *)\n  Definition knows_certificate\n             {eo : EventOrdering}\n             (e : Event)\n             (n : nat)\n             (i : lak_info)\n             (P : list lak_data -> Prop) :=\n    exists (l : list lak_data),\n      n <= length l\n      /\\ no_repeats (map lak_data2owner l)\n      /\\ P l\n      /\\ forall d, In d l -> (knows e d /\\ i = lak_data2info d).\n\n  Definition learns {eo : EventOrdering} (e : Event) (d : lak_data) :=\n    exists n,\n      loc e = node2name n\n      /\\ In (lak_data2auth d) (bind_op_list get_contained_authenticated_data (trigger e))\n      (*/\\ verify_authenticated_data (loc e) (lak_data2auth d) (keys e) = true.*)\n      /\\ lak_verify e d = true.\n\n  Definition learned {eo : EventOrdering} (e : Event) (d : lak_data) :=\n    exists e', e' \u2291 e /\\ learns e' d.\n\n  Definition learns_or_knows (eo : EventOrdering) : Prop :=\n    forall (d  : lak_data) (e : Event),\n      knows e d\n      -> learned e d \\/ lak_data2node d = loc e.\n\n  Definition learns_if_knows (eo : EventOrdering) :=\n    forall (d  : lak_data) (e : Event),\n      learns e d\n      -> has_correct_trace_before e (lak_data2node d)\n      ->\n      exists e',\n        e' \u227a e\n        /\\ loc e' = lak_data2node d\n        /\\ knows e' d.\n\n  Lemma knows_implies_correct :\n    forall {eo : EventOrdering} (e : Event) (d : lak_data),\n      knows e d\n      -> has_correct_trace_before e (loc e).\n  Proof.\n    introv kn.\n    unfold knows in kn; exrepnd.\n    eapply state_sm_on_event_some_implies_has_correct_trace_before;eauto.\n  Qed.\n  Hint Resolve knows_implies_correct : eo.\n\n  Lemma knows_propagates :\n    forall {eo : EventOrdering} (e : Event) (d : lak_data),\n      learns_or_knows eo\n      -> learns_if_knows eo\n      -> knows e d\n      -> has_correct_trace_before e (lak_data2node d)\n      ->\n      exists e',\n        e' \u227c e\n        /\\ loc e' = lak_data2node d\n        /\\ knows e' d.\n  Proof.\n    introv lok lik knows ctrace.\n    pose proof (lok d e) as sent.\n    repeat (autodimp sent hyp);[].\n    repndors; repnd;[|exists e; dands; eauto 2 with eo];[].\n\n    unfold learned in *; exrepnd.\n\n    pose proof (lik d e') as h.\n    repeat (autodimp h hyp); eauto 3 with eo;[].\n    exrepnd.\n    exists e'0; dands; auto; eauto 4 with eo.\n  Qed.\n\n  Lemma knows_in_intersection :\n    forall {eo : EventOrdering}\n           (e1 e2 : Event)\n           (n : nat)\n           (i1 i2 : lak_info)\n           (P : list lak_data -> Prop)\n           (E : list Event)\n           (F : nat),\n      learns_or_knows eo\n      -> learns_if_knows eo\n      -> n <= num_nodes\n      -> num_nodes + F < 2 * n\n      -> knows_certificate e1 n i1 P\n      -> knows_certificate e2 n i2 P\n      -> exists_at_most_f_faulty E F\n      -> In e1 E\n      -> In e2 E\n      ->\n      exists e1' e2' d1 d2,\n        loc e1' = loc e2'\n        /\\ e1' \u227c e1\n        /\\ e2' \u227c e2\n        /\\ loc e1' = lak_data2node d1\n        /\\ loc e2' = lak_data2node d2\n        /\\ knows e1' d1\n        /\\ knows e2' d2\n        /\\ i1 = lak_data2info d1\n        /\\ i2 = lak_data2info d2.\n  Proof.\n    introv lok lik cond1 cond2 kna knb; introv atmost e1in e2in.\n    unfold knows_certificate in *.\n    destruct kna as [l1 [lena [norepa [conda impa]]]]; repnd.\n    destruct knb as [l2 [lenb [norepb [condb impb]]]]; repnd.\n\n    pose proof (overlapping_quorums_same_size\n                  (MkNRlist _ (map lak_data2owner l1) norepa)\n                  (MkNRlist _ (map lak_data2owner l2) norepb)\n                  n) as q.\n    simpl in q; autorewrite with list in *.\n    repeat (autodimp q hyp); try omega;[].\n    exrepnd.\n\n    pose proof (there_is_one_correct_before eo l E F) as h.\n    repeat (autodimp h hyp); try omega;[].\n    exrepnd.\n\n    pose proof (h0 e1) as ctrace1; simpl in ctrace1; autodimp ctrace1 hyp.\n    pose proof (h0 e2) as ctrace2; simpl in ctrace2; autodimp ctrace2 hyp.\n\n    applydup q3 in h1.\n    applydup q0 in h1.\n    allrw in_map_iff; exrepnd.\n\n    applydup impa in h5.\n    applydup impb in h4.\n    repnd.\n\n    pose proof (knows_propagates e1 x0) as w.\n    repeat (autodimp w hyp); try (complete (unfold lak_data2node; allrw; auto));[].\n\n    pose proof (knows_propagates e2 x) as z.\n    repeat (autodimp z hyp); try (complete (unfold lak_data2node; allrw; auto));[].\n\n    destruct w as [e1' w]; repnd.\n    destruct z as [e2' z]; repnd.\n    assert (loc e1' = loc e2') as eqloc' by (allrw; unfold lak_data2node; allrw; auto).\n\n    exists e1' e2' x0 x; dands; auto.\n  Qed.\n\n  Lemma local_knows_in_intersection :\n    forall {eo : EventOrdering}\n           (e : Event)\n           (n : nat)\n           (i1 i2 : lak_info)\n           (P : list lak_data -> Prop)\n           (E : list Event)\n           (F : nat),\n      n <= num_nodes\n      -> num_nodes + F < 2 * n\n      -> knows_certificate e n i1 P\n      -> knows_certificate e n i2 P\n      -> exists_at_most_f_faulty E F\n      -> In e E\n      ->\n      exists correct d1 d2,\n        has_correct_trace_before e (node2name correct)\n        /\\ lak_data2node d1 = lak_data2node d2\n        /\\ knows e d1\n        /\\ knows e d2\n        /\\ i1 = lak_data2info d1\n        /\\ i2 = lak_data2info d2\n        /\\ lak_data2owner d1 = correct\n        /\\ lak_data2owner d2 = correct.\n  Proof.\n    introv cond1 cond2 kna knb atmost ein.\n    unfold knows_certificate in *.\n    destruct kna as [l1 [lena [norepa [conda impa]]]]; repnd.\n    destruct knb as [l2 [lenb [norepb [condb impb]]]]; repnd.\n\n    pose proof (overlapping_quorums_same_size\n                  (MkNRlist _ (map lak_data2owner l1) norepa)\n                  (MkNRlist _ (map lak_data2owner l2) norepb)\n                  n) as q.\n    simpl in q; autorewrite with list in *.\n    repeat (autodimp q hyp); try omega;[].\n    exrepnd.\n\n    pose proof (there_is_one_correct_before eo l E F) as h.\n    repeat (autodimp h hyp); try omega;[].\n    exrepnd.\n\n    exists correct.\n\n    pose proof (h0 e) as ctrace1; simpl in ctrace1; autodimp ctrace1 hyp.\n\n    applydup q3 in h1.\n    applydup q0 in h1.\n    allrw in_map_iff; exrepnd.\n\n    applydup impa in h5.\n    applydup impb in h4.\n    repnd.\n\n    exists x0 x; dands; auto;[].\n    unfold lak_data2node; allrw; auto.\n  Qed.\n\n  Definition learns_or_knows_if_knew (eo : EventOrdering) : Prop :=\n    forall (d  : lak_data) (e : Event),\n      knew e d\n      -> learned e d \\/ lak_data2node d = loc e.\n\n  Lemma knew_implies_knows :\n    forall (eo : EventOrdering) (e : Event) (d : lak_data),\n      knew e d\n      -> knows (local_pred e) d.\n  Proof.\n    introv k.\n    unfold knew in *; exrepnd.\n    rewrite <- ite_first_state_sm_on_event_as_before in k1.\n    unfold ite_first in k1; destruct (dec_isFirst e) as [de|de];\n      [|exists mem n; autorewrite with eo; dands; auto];[].\n    ginv.\n    apply lak_no_initial_memory in k2; tcsp.\n  Qed.\n\n  Lemma learns_or_knows_implies_learns_or_knows_if_new :\n    forall (eo : EventOrdering),\n      learns_or_knows eo\n      -> learns_or_knows_if_knew eo.\n  Proof.\n    introv lok k.\n    apply knew_implies_knows in k.\n    apply lok in k; autorewrite with eo in *.\n    repeat (autodimp k hyp); eauto 3 with eo;[].\n    repndors; tcsp; left;[].\n    unfold learned in *; exrepnd.\n    exists e'; dands; auto; eauto 3 with eo.\n  Qed.\n\n  Lemma knows_implies :\n    forall {eo : EventOrdering} (e : Event) d,\n      knows e d\n      ->\n      exists mem mem' n,\n        loc e = node2name n\n        /\\ op_state (lak_system n) mem (trigger e) = Some mem'\n        /\\ lak_knows d mem'\n        /\\ state_sm_before_event (lak_system n) e = Some mem.\n  Proof.\n    introv kn.\n    unfold knows in kn; exrepnd.\n    rewrite state_sm_on_event_unroll2 in kn1.\n\n    match goal with\n    | [ H : context[map_option _ ?s] |- _ ] =>\n      remember s as sop; symmetry in Heqsop; destruct sop; simpl in *;[|ginv]\n    end.\n\n    exists l mem n; dands; auto.\n  Qed.\n\n  Lemma knows_implies_before_after :\n    forall {eo : EventOrdering} (e : Event) d,\n      knows e d\n      ->\n      exists mem mem' n,\n        loc e = node2name n\n        /\\ op_state (lak_system n) mem (trigger e) = Some mem'\n        /\\ lak_knows d mem'\n        /\\ state_sm_before_event (lak_system n) e = Some mem\n        /\\ state_sm_on_event (lak_system n) e = Some mem'.\n  Proof.\n    introv kn.\n    unfold knows in kn; exrepnd.\n    dup kn1 as ston.\n    rewrite state_sm_on_event_unroll2 in kn1.\n\n    match goal with\n    | [ H : context[map_option _ ?s] |- _ ] =>\n      remember s as sop; symmetry in Heqsop; destruct sop; simpl in *;[|ginv]\n    end.\n\n    exists l mem n; dands; auto.\n  Qed.\n\n  Lemma implies_knows :\n    forall {eo : EventOrdering} (e : Event) d n mem,\n      loc e = node2name n\n      -> lak_knows d mem\n      -> state_sm_on_event (lak_system n) e = Some mem\n      -> knows e d.\n  Proof.\n    introv eqloc k eqst.\n    eexists; eexists; dands; eauto.\n  Qed.\n  Hint Resolve implies_knows : eo.\n\n  Lemma learned_local_pred_implies :\n    forall (eo : EventOrdering) (e : Event) d,\n      learned (local_pred e) d\n      -> learned e d.\n  Proof.\n    introv h.\n    unfold learned in *; exrepnd.\n    eexists; dands; eauto; eauto 3 with eo.\n  Qed.\n  Hint Resolve learned_local_pred_implies : eo.\n\n  Lemma learned_local_le_implies :\n    forall (eo : EventOrdering) (e1 e2 : Event) d,\n      e1 \u2291 e2\n      -> learned e1 d\n      -> learned e2 d.\n  Proof.\n    introv lee h.\n    unfold learned in *; exrepnd.\n    eexists; dands;[|eauto]; eauto 3 with eo.\n  Qed.\n  Hint Resolve learned_local_le_implies : eo.\n\n  Definition learned_if_knows (eo : EventOrdering) :=\n    forall (d  : lak_data) (e : Event),\n      learned e d\n      -> has_correct_trace_before e (lak_data2node d)\n      ->\n      exists e',\n        e' \u227a e\n        /\\ loc e' = lak_data2node d\n        /\\ knows e' d.\n\n  Lemma learns_if_knows_implies_learned_if_knows :\n    forall (eo : EventOrdering),\n      learns_if_knows eo\n      -> learned_if_knows eo.\n  Proof.\n    introv lik l hc.\n    unfold learned in l; exrepnd.\n    apply lik in l0; autodimp l0 hyp; eauto 3 with eo.\n    exrepnd.\n    exists e'0; dands; eauto 3 with eo.\n  Qed.\n  Hint Resolve learns_if_knows_implies_learned_if_knows : eo.\n\n  Lemma knows_weak_certificate :\n    forall {eo : EventOrdering}\n           (e : Event)\n           (n : nat)\n           (i : lak_info)\n           (P : list lak_data -> Prop)\n           (E : list Event)\n           (F : nat),\n      F < n\n      -> knows_certificate e n i P\n      -> exists_at_most_f_faulty E F\n      -> In e E\n      ->\n      exists d,\n        has_correct_trace_before e (lak_data2node d)\n        /\\ knows e d\n        /\\ i = lak_data2info d.\n  Proof.\n    introv cond kn atmost ein.\n    unfold knows_certificate in *.\n    destruct kn as [l [len [norep [condp imp]]]]; repnd.\n    pose proof (there_is_one_correct_before eo (map lak_data2owner l) E F) as q.\n    repeat (autodimp q hyp); autorewrite with list in *; try omega.\n    exrepnd.\n    allrw in_map_iff; exrepnd; subst.\n    applydup imp in q2; repnd; simpl in *.\n    exists x; dands; auto.\n  Qed.\n\n  Lemma knows_weak_certificate_propagates :\n    forall {eo : EventOrdering}\n           (e : Event)\n           (n : nat)\n           (i : lak_info)\n           (P : list lak_data -> Prop)\n           (E : list Event)\n           (F : nat),\n      learns_or_knows eo\n      -> learns_if_knows eo\n      -> F < n\n      -> knows_certificate e n i P\n      -> exists_at_most_f_faulty E F\n      -> In e E\n      ->\n      exists e' d,\n        e' \u227c e\n        /\\ loc e' = lak_data2node d\n        /\\ knows e' d\n        /\\ i = lak_data2info d.\n  Proof.\n    introv lok lik cond kn atmost ein.\n    eapply knows_weak_certificate in kn; eauto; exrepnd; subst.\n    apply knows_propagates in kn2; auto.\n    exrepnd.\n    exists e' d; dands; auto.\n  Qed.\n\nEnd LearnAndKnow.\n\n\nLtac prove_knows :=\n  match goal with\n  | [ |- knows _ _ ] =>\n    eapply implies_knows; simpl;[| |eassumption];auto;\n    autorewrite with eo; auto\n  end.\n\n\nHint Resolve implies_knows : eo.\nHint Resolve learned_local_pred_implies : eo.\nHint Resolve learned_local_le_implies : eo.\nHint Resolve learns_if_knows_implies_learned_if_knows : eo.\nHint Resolve knows_implies_correct : eo.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/model/LearnAndKnows.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.17167956791137595}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import LinearScan.Lib.\nRequire Import LinearScan.Context.\nRequire Import LinearScan.Interval.\nRequire Import LinearScan.ScanState.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\nSection Trace.\n\n(* These T-suffixed types and constructors are for data that is meant to be\n   exported from Coq, and so must dwell in [Set]. *)\n\nDefinition IntervalIdT : Set := nat.\nDefinition PhysRegT : Set := nat.\n\nInductive SpillConditionT : Set :=\n  | NewToHandledT       of IntervalIdT\n  | UnhandledToHandledT of IntervalIdT\n  | ActiveToHandledT    of IntervalIdT & PhysRegT\n  | InactiveToHandledT  of IntervalIdT & PhysRegT.\n\nInductive SplitPositionT : Set :=\n  | BeforePosT of nat\n  | EndOfLifetimeHoleT of nat.\n\nDefinition TrueIfActiveT : Set := bool.\n\nInductive SSTrace : Set :=\n  | EIntersectsWithFixedInterval of nat & PhysRegT\n  | ESplitAssignedIntervalForReg of IntervalIdT & PhysRegT & SplitPositionT\n  | ESplitActiveOrInactiveInterval\n      of IntervalIdT & TrueIfActiveT & SplitPositionT\n  | EIntervalHasUsePosReqReg of nat\n  | EIntervalBeginsAtSplitPosition\n  | EMoveUnhandledToActive of IntervalIdT & PhysRegT\n  | ESplitActiveIntervalForReg of PhysRegT & SplitPositionT\n  | ESplitAnyInactiveIntervalForReg of PhysRegT & SplitPositionT\n  | ESpillInterval of SpillConditionT\n  | ESpillCurrentInterval\n  | ESplitUnhandledInterval of IntervalIdT & SplitPositionT\n  | ESplitCurrentInterval of IntervalIdT & SplitPositionT\n  | ETryAllocateFreeReg of PhysRegT & option nat & IntervalIdT\n  | EAllocateBlockedReg of PhysRegT & option nat & IntervalIdT\n  | ERemoveUnhandledInterval of IntervalIdT\n  | ECannotInsertUnhandled of nat & nat & nat & nat\n  | EIntervalBeginsBeforeUnhandled of IntervalIdT\n  | ENoValidSplitPosition of IntervalIdT\n  | ECannotSplitSingleton of IntervalIdT\n  | ERegisterAlreadyAssigned of PhysRegT\n  | ERegisterAssignmentsOverlap of PhysRegT & IntervalIdT & nat\n  | ECannotModifyHandledInterval of IntervalIdT\n  | EUnexpectedNoMoreUnhandled\n  | ECannotSpillIfRegisterRequired of IntervalIdT\n  | ECannotSpillIfRegisterRequiredBefore of IntervalIdT & nat\n  | EFuelExhausted\n  | EUnhandledIntervalsRemain\n  | EActiveIntervalsRemain\n  | EInactiveIntervalsRemain\n  | ENotYetImplemented of nat.\n\nEnd Trace.\n", "meta": {"author": "jwiegley", "repo": "linearscan", "sha": "1f8c74134d7634061d3cce4b2817708e9e82037d", "save_path": "github-repos/coq/jwiegley-linearscan", "path": "github-repos/coq/jwiegley-linearscan/linearscan-1f8c74134d7634061d3cce4b2817708e9e82037d/src/Trace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.17167097394119268}}
{"text": "Require Import mimperative mlattice language types mmemory id_and_loc Arith LibTactics tactics decision Coq.Program.Equality augmented low_equivalence List Coq.Program.Tactics.\n\nModule Preservation (L : Lattice) (M : Memory L).\n  Module LowEq := LowEquivalence L M.\n  Import LowEq B Aug Imp TDefs M T MemProp LatProp Lang L.\n  \n  Ltac invert_var_typing :=\n    match goal with\n      [H: expr_has_type _ (Var _) _ |- _] =>\n      inverts H\n    end.\n\nLemma array_type_is_not_recursive:\n  forall t l \u2113,\n    SecType (Array t \u2113) l = t -> False.\nProof.\n  apply (sectype_mut (fun t => forall l \u2113, Array (SecType t l) \u2113 = t -> False)\n                     (fun sect => forall l \u2113, SecType (Array sect \u2113) l = sect -> False)).\n  - intros.\n    discriminate.\n  - intros.\n    injects.\n    eauto.\n  - intros.\n    injects.\n    eauto.\nQed.\n\nLemma lookup_in_bounds_extend:\n  forall x m h loc l n v H1 H2,\n    (forall loc', v = ValLoc loc' -> reach m h loc') ->\n    ~ reach m h loc ->\n    dangling_pointer_free m h ->\n    lookup_in_bounds m h ->\n    lookup_in_bounds (extend_memory x (ValLoc loc) m) (h [loc \u2192 (n \u00d7 v, l), H1, H2]).\nProof.\n  intros.\n  unfolds.\n  intros.\n  destruct (decide (loc0 = loc)); subst.\n  - rewrite -> length_of_extend_eq in *.\n    rewrite_inj.\n    apply_heap_lookup_extend_eq.\n    rewrite_inj.\n    eauto.\n  - rewrite -> length_of_extend_neq in * by solve[eauto].\n    rewrite -> heap_lookup_extend_neq in * by solve[eauto 2].\n    rewrite_inj.\n    assert (reach m h loc0) by eauto 2 using reach_extend_implies_reach_if.\n    eauto.\nQed.\n\nLemma wf_stenv_subset:\n  forall \u03a3 h1 h2 H,\n    wf_stenv \u03a3 ([h1 \u228e h2, H]) -> wf_stenv \u03a3 h1.\nProof.\n  intros.\n  unfold wf_stenv in *.\n  intros.\n  super_destruct'.\n  splits*.\nQed.\nHint Resolve wf_stenv_subset.\n\nLemma reach_supset:\n  forall m h1 h2 loc H,\n    reach m h1 loc ->\n    reach m ([h1 \u228e h2, H]) loc.\nProof.\n  intros.\n  induction H0; eauto.\n\n  Unshelve.\n  - repeat constructor.\nQed.\nHint Resolve reach_supset.\n\nLemma reach_supset':\n  forall m h1 h2 loc H,\n    reach m h2 loc ->\n    reach m ([h1 \u228e h2, H]) loc.\nProof.\n  intros.\n  induction H0; eauto.\n\n  specialize (IHreach H).\n  assert (heap_lookup loc ([h1 \u228e h, H]) = Some (\u2113, \u03bc)).\n  {\n    rewrite -> disjoint_union_sym.\n    eauto.\n  }\n  eauto.\n  Unshelve.\n  - repeat constructor.\nQed.\nHint Resolve reach_supset'.\n\nLemma consistent_subset_helper:\n  forall m h1 h2 \u0393 \u03a3 H,\n    consistent m ([h1 \u228e h2, H]) \u0393 \u03a3 ->\n    consistent m h1 \u0393 \u03a3 /\\ consistent m h2 \u0393 \u03a3.\nProof.\n  intros.\n  destruct_consistent.\n  splits*.\n  - unfolds.\n    splits*.\n  - unfolds.\n    splits*.\n    intros.\n    eapply H1.\n    + eauto.\n    + eauto.\n    + rewrite -> disjoint_union_sym by eauto.\n      eauto.\n    + eauto.\n\nQed.\nHint Resolve consistent_subset_helper.\n\nLemma consistent_subset:\n  forall m h1 h2 \u0393 \u03a3 H,\n    consistent m ([h1 \u228e h2, H]) \u0393 \u03a3 ->\n    consistent m h1 \u0393 \u03a3.\nProof.\n  intros.\n  edestruct consistent_subset_helper; eauto.\nQed.\nHint Resolve consistent_subset.\n\nLemma dangling_pointer_free_subset:\n  forall m h1 h2 H,\n    dangling_pointer_free m ([h1 \u228e h2, H]) ->\n    (forall loc \u2113 \u03bc,\n        heap_lookup loc h2 = Some (\u2113, \u03bc) -> ~ reach m ([h1 \u228e h2, H]) loc) ->\n    dangling_pointer_free m h1.\nProof.\n  intros.\n  unfolds.\n  intros.\n  assert (exists \u2113 \u03bc, heap_lookup loc ([h1 \u228e h2, H]) = Some (\u2113, \u03bc)) by eauto.\n  super_destruct.\n  exists \u2113 \u03bc.\n  destruct (disjoint_union_heap_lookup2 h1 h2 loc \u2113 \u03bc _ H3).\n  - eauto.\n  - assert (~ reach m ([h1 \u228e h2, H]) loc) by eauto.\n    assert (reach m ([h1 \u228e h2, H]) loc) by eauto using reach_supset.\n    contradiction.\nQed.\nHint Resolve dangling_pointer_free_subset.\n\nLemma lookup_in_bounds_subset:\n  forall m h1 h2 H,\n    dangling_pointer_free m h1 ->\n    lookup_in_bounds m ([h1 \u228e h2, H]) ->\n    (forall loc \u2113 \u03bc,\n        heap_lookup loc h2 = Some (\u2113, \u03bc) -> ~ reach m ([h1 \u228e h2, H]) loc) ->\n    lookup_in_bounds m h1.\nProof.\n  intros.\n  unfold lookup_in_bounds in *.\n  intros.\n  assert (exists \u03bd, heap_lookup loc ([h1 \u228e h2, H]) = Some (\u2113, \u03bd)) by eauto.\n  super_destruct.\n  assert (exists v, lookup \u03bd n = Some v) by eauto.\n  super_destruct.\n  exists v.\n  super_destruct.\n  destruct_disjoint_heap_lookup.\n  + congruence.\n  + assert (heap_lookup loc h1 = None).\n    {\n      eapply disjoint_union_heap_lookup3.\n      - rewrite -> disjoint_union_sym.\n        erewrite -> disjoint_union_proof_irrelevance.\n        eauto.\n        Unshelve.\n        eauto.\n      - eauto.\n    }      \n    match goal with\n      [H: dangling_pointer_free _ _,\n          H2: reach _ _ _ |- _] =>\n      unfolds in H;\n        specialize (H loc H2)\n    end.\n    destruct_exists.\n    rewrite_inj.\n    discriminate.\nQed.\nHint Resolve lookup_in_bounds_subset.\n\nLemma heap_level_bound_subset:\n  forall m h1 h2 \u0393 \u03a3 H,\n    heap_level_bound \u0393 m ([h1 \u228e h2, H]) \u03a3 ->\n    heap_level_bound \u0393 m h1 \u03a3.\nProof.\n  intros.\n  splits*.\nQed.\nHint Resolve heap_level_bound_subset.\n\nLemma reach_from_supset:\n  forall x m h1 h2 loc H,\n    reach_from x m h1 loc ->\n    reach_from x m ([h1 \u228e h2, H]) loc.\nProof.\n  intros.\n  unfold reach_from in *.\n  super_destruct.\n  eexists.\n  dependent induction H0; eauto.\nQed.\nHint Resolve reach_from_supset.\n\nLemma gc_preserves_wf:\n  forall c pc pc' m h1 h2 h3 t \u0393 \u03a3 \u03b4 H1 H2 H3,\n    ([h1 \u228e h3, H1]) \u21dd (m, \u03b4) h1 ->\n    disjoint ([h1 \u228e h2, H2]) h3 ->\n    (forall loc \u2113 \u03bc, heap_lookup loc h3 = Some (\u2113, \u03bc) -> ~ reach m ([([h1 \u228e h2, H2]) \u228e h3, H3]) loc) ->\n    wellformed_aux \u0393 \u03a3 \u27e8 c, pc, m, [([h1 \u228e h2, H2]) \u228e h3, H3], t \u27e9 pc' ->\n    wellformed_aux \u0393 \u03a3 \u27e8 c, pc, m, [h1 \u228e h2, H2], t + \u03b4 \u27e9 pc'.\nProof.\n  intros.\n  induction c; constructor; invert_wf_aux; eauto.\nQed.\nHint Resolve gc_preserves_wf.\n\nLemma location_is_from_lookup_simple:\n  forall \u0393 level m e loc,\n    wf_tenv \u0393 m ->\n    {{\u0393 \u22a2 e : level}} ->\n    eval m e = Some (ValLoc loc) ->\n    exists x,\n      memory_lookup m x = Some (ValLoc loc) /\\ e = Var x.\nProof.\n  intros.\n  assert (exists x, e = Var x) by eauto using location_is_from_lookup.\n  super_destruct; subst.\n  exists x.\n  splits*.\nQed.\nHint Resolve location_is_from_lookup_simple.\n\nLemma var_exp_has_type_is_env_lookup:\n  forall \u0393 x t,\n    {{\u0393 \u22a2 Var x : t}} ->\n    \u0393 x = Some t.\nProof.\n  intros.\n  inverts H; eauto.\nQed.\nHint Resolve var_exp_has_type_is_env_lookup.\n\nLemma reach_update_with_num:\n  forall m h loc1 loc2 n k,\n    reach m (update_heap loc1 n (ValNum k) h) loc2 ->\n    reach m h loc2.\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - destruct (decide (loc1 = loc)); subst.\n    + assert (exists \u03bd, heap_lookup loc h = Some (\u2113, \u03bd) /\\ \u03bc = update_lookup \u03bd n (ValNum k)) by eauto.\n      super_destruct; subst.\n      destruct (decide (n = n0)); subst.\n      * rewrite -> lookup_update_eq in *.\n        discriminate.\n      * rewrite -> lookup_update_neq in * by solve[eauto].\n        eauto.\n    + rewrite -> heap_lookup_update_neq in * by solve[eauto].\n      eauto.\n      Unshelve.\n      * constructor; eauto.\n      * repeat constructor; eauto.\nQed.\n\nLemma reach_by_update_implies_reach_if:\n  forall m h l n loc1 loc2,\n    reach m (update_heap l n (ValLoc loc1) h) loc2 ->\n    reach m h loc1 ->\n    reach m h loc2.\nProof.\n  intros.\n  dependent induction H.\n  - eauto.\n  - specialize_gen.\n    destruct (decide (loc = l)); subst.\n    + assert (exists \u03bd, heap_lookup l h = Some (\u2113, \u03bd) /\\ \u03bc = update_lookup \u03bd n (ValLoc loc1))\n        by eauto.\n      super_destruct; subst.\n      destruct (decide (n = n0)); subst.\n      * rewrite -> lookup_update_eq in *.\n        rewrite_inj.\n        eauto.\n      * rewrite -> lookup_update_neq in * by solve[eauto].\n        eauto.\n    + rewrite -> heap_lookup_update_neq in * by solve[eauto].\n      eauto.\n      Unshelve.\n      * constructor; eauto.\n      * repeat constructor; eauto.\nQed.\n\nLemma reach_extend2:\n  forall m h x loc1 loc2 loc3 n \u2113 \u03bc,\n    heap_lookup loc1 h = Some (\u2113, \u03bc) ->\n    lookup \u03bc n = Some (ValLoc loc2) ->\n    reach m h loc1 -> \n    reach (extend_memory x (ValLoc loc2) m) h loc3 -> reach m h loc3.\nProof.\n  intros.\n  dependent induction H2.\n  - destruct (decide (x = x0)); subst.\n    * rewrite -> extend_memory_lookup_eq in *.\n      rewrite_inj.\n      eauto.\n    * rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n      eauto.\n  - assert (reach m h loc) by eauto.\n    eauto.\n\n    Unshelve.\n    + constructor; eauto.\n    + repeat constructor; eauto.\n    + constructor; eauto.\nQed.\n\nLemma reach_from_implies_array_type:\n  forall \u0393 x t l m h loc,\n    wf_tenv \u0393 m ->\n    \u0393 x = Some (SecType t l) ->\n    reach_from x m h loc ->\n    exists s \u2113, t = Array s \u2113.\nProof.\n  intros.\n  unfold reach_from in *.\n  super_destruct.\n  revert loc H1.\n  induction k; intros; subst.\n  - inverts H0.\n    inverts H1.\n    destruct t; eauto.\n    assert (exists n, ValLoc loc = ValNum n) by eauto.\n    super_destruct; discriminate.\n  - inverts H1.\n    eauto.\nQed.\nHint Resolve reach_from_implies_array_type.\n\nLemma no_backat_implies_wt_aux_mono:\n  forall \u0393 pc c pc',\n    ~ contains_backat c ->\n    wt_aux \u0393 pc c pc' ->\n    pc = pc'.\nProof.\n  intros.\n  dependent induction H0; eauto 2.\n  - firstorder.\n    congruence.\n  - exfalso; eauto 2.\nQed.\nHint Resolve no_backat_implies_wt_aux_mono.\n\nLemma preservation:\n  forall tenv stenv stenv' c1 pc1 m1 h1 t1 c2 pc2 m2 h2 t2 pc',\n    wellformed_aux tenv stenv (Config c1 pc1 m1 h1 t1) pc' ->\n    step (Config c1 pc1 m1 h1 t1) (Config c2 pc2 m2 h2 t2) tenv stenv stenv' ->\n    wellformed_aux tenv stenv' (Config c2 pc2 m2 h2 t2) pc'.\nProof.\n  intros tenv stenv stenv' c1 pc1 m1 h1 t1.\n  intros c2 pc2 m2 h2 t2 pc' H_wf H_step.\n  revert pc' c2 pc2 m2 h2 t2 H_wf H_step.\n  induction c1; intros; invert_step; subst; invert_wf_aux; subst.\n  (* Skip *)\n  - apply WellformedAux; intros; auto || (exfalso; eauto).\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto. \n  - eauto.\n  (* Assign *)\n  - assert ((i ::= e) <> Stop) by (intro H_absurd; discriminate H_absurd).\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    apply WellformedAux; eauto.\n    + invert_lifted.\n      rewrite_inj.\n      eapply wf_tenv_extend with (t := \u03c3); intros; (repeat subst); eauto.\n    + unfolds.\n      splits*.\n      { intros.\n        destruct (decide (i = x)); subst.\n        - rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e = Var x) by eauto 2.\n          super_destruct'; subst.\n          invert_var_typing.\n          invert_lifted.\n          eauto.\n        - rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          eauto 2.\n      }\n      {\n        intros.\n        destruct_consistent.\n        destruct v.\n        {\n          assert (reach m1 h2 loc1) by eauto 2 using reach_extend_with_num.\n          eauto.\n        }\n        {\n          destruct (decide (l0 = loc1)); subst.\n          - assert (exists x, memory_lookup m1 x = Some (ValLoc loc1) /\\ e = Var x) by eauto.\n            super_destruct; subst.\n            eauto.\n          - assert (exists x, memory_lookup m1 x = Some (ValLoc l0) /\\ e = Var x) by eauto.\n            super_destruct; subst.\n            eauto.\n        }\n      }\n    + intros; exfalso; eauto.\n    + (* Show: New memory is free of dangling pointers *)\n      unfolds.\n      intros.\n      invert_lifted.\n      rewrite_inj.      \n      invert_reach.\n      * destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          match goal with\n            [H: eval _ ?e = Some (ValLoc _) |- _] => destruct e\n          end.\n          - discriminate.\n          - eauto.\n          - assert (exists n, ValLoc loc = ValNum n)\n              by eauto using eval_binop_is_num.\n            destruct_exists.\n            discriminate.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          eauto.\n        }\n      * unfold dangling_pointer_free in *.\n        inverts H1.\n        {\n          destruct (decide (i = x)); subst.\n          - rewrite -> extend_memory_lookup_eq in *.\n            rewrite_inj.\n            assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e = Var x) by eauto.\n            super_destruct; subst.\n            eauto.\n          - rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n            eauto.\n        }\n        {\n          destruct v.\n          - assert (reach m1 h2 loc) by eauto using reach_extend_with_num.\n            eauto.\n          - assert (exists x, memory_lookup m1 x = Some (ValLoc l) /\\ e = Var x) by eauto.\n            super_destruct; subst.\n            destruct (decide (loc1 = l)); subst.\n            + eauto.\n            + assert (reach m1 h2 l) by eauto.\n              eauto using reach_extend.\n        }\n    + invert_lifted.\n      rewrite_inj.\n      unfolds.\n      intros.\n      destruct v.\n      * assert (reach m1 h2 loc) by eauto using reach_extend_with_num.\n        eauto.\n      * assert (exists x, memory_lookup m1 x = Some (ValLoc l) /\\ e = Var x) by eauto.\n        super_destruct; subst.\n        destruct (decide (loc = l)); subst; eauto using reach_extend.\n    + unfolds.\n      splits; eauto 2.\n      intros.\n      invert_lifted.\n      rewrite_inj.\n      destruct (decide (i = x)); subst.\n      * rewrite -> extend_memory_lookup_eq in *.\n        rewrite_inj.\n        assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e = Var x) by eauto.\n        super_destruct'; subst.\n        invert_var_typing.\n        eauto 2.\n      * rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n        eauto 2.\n      * intros.\n        invert_lifted.\n        destruct \u03c3.\n        { assert (exists n, v = ValNum n) by eauto.\n          super_destruct'; subst.\n          eauto using reach_extend_with_num.\n        }\n        { assert (exists loc, v = ValLoc loc) by eauto.\n          super_destruct'; subst.\n          destruct (decide (loc0 = loc)); subst.\n          - assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e = Var x) by eauto.\n            super_destruct; subst.\n            eauto.\n          - rewrite_inj.\n            assert (reach m1 h2 loc).\n            {\n              eapply reach_extend.\n              - eapply H0.\n              - assert (exists x, memory_lookup m1 x = Some (ValLoc loc0) /\\ e = Var x) by eauto.\n                super_destruct; subst.\n                eauto.\n            }\n            eauto 3.\n        }\n      * intros.\n        invert_lifted.\n        rewrite_inj.\n        destruct \u03c3.\n        {\n          assert (exists n, v = ValNum n) by eauto.\n          super_destruct; subst.\n          assert (reach m1 h2 loc1) by eauto 3 using reach_extend_with_num.\n          eauto.\n        }\n        {\n          assert (exists loc, v = ValLoc loc) by eauto.\n          super_destruct; subst.\n          assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e = Var x) by eauto.\n          super_destruct; subst.\n          assert (reach m1 h2 loc1).\n          {\n            eapply reach_extend.\n            - eapply H0.\n            - eauto.\n          }\n          eauto.\n        }\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  - (* If *)\n    assert ((If e c1_1 c2) <> Stop) by congruence.\n    assert ((If e c1_1 c2) <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    apply WellformedAux; intros; eauto.\n  - assert ((If e c2 c1_2) <> Stop) by congruence.\n    assert ((If e c2 c1_2) <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    apply WellformedAux; intros; eauto.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto 2.\n  - (* While *)\n    assert ((While e c1) <> Stop) by congruence.\n    assert ((While e c1) <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    apply WellformedAux; try assumption.\n    intros; exfalso; eauto.\n  - assert ((While e c1) <> Stop) by congruence.\n    assert ((While e c1) <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    apply WellformedAux; intros; try assumption.\n    apply (wt_aux_seq tenv pc' pc' pc'); eauto.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  (* Sequencing *)\n  - assert ((c1_1;; c2) <> Stop) by congruence.\n    assert ((c1_1;; c2) <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    invert_wt_cmd.\n    assert (pc2 = pc'0).\n    {      \n      eauto 3 using wt_aux_soundness.\n    }\n    subst.\n    assert (exists pc1', wellformed_aux tenv stenv \u27e8c1_1, pc1, m1, h1, t1\u27e9 pc1') by eauto.\n    super_destruct; subst.\n    assert (wellformed_aux tenv stenv' \u27e8STOP, pc'0, m2, h2, t2\u27e9 pc1') by eauto.\n    destruct_exists.\n    invert_wf_aux.\n    apply WellformedAux; intros; eauto.\n  - assert ((c1_1 ;; c1_2) <> Stop) by congruence.\n    assert ((c1_1 ;; c1_2) <> TimeOut) by congruence.\n    do 2 specialize_gen. \n    clear H.\n    invert_wt_cmd.\n    assert (wellformed_aux tenv stenv \u27e8c1_1, pc1, m1, h1, t1\u27e9 pc'0) by eauto.\n    assert (wellformed_aux tenv stenv' \u27e8c1', pc2, m2, h2, t2\u27e9 pc'0) by eauto.\n    destruct_exists.\n    invert_wf_aux.\n    apply WellformedAux; intros; try assumption.\n    + repeat specialize_gen.\n      eapply wt_aux_seq; eauto.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  (* At *)\n  - apply WellformedAux; intros; try assumption.\n    assert (At pc2 e c1 <> Stop) by congruence.\n    assert (At pc2 e c1 <> TimeOut) by congruence.    \n    do 2 specialize_gen.\n    invert_wt_cmd.\n    eapply wt_aux_seq.\n    + eauto.\n    + assert (pc2 = \u2113'') by eauto 2 using no_backat_implies_wt_aux_mono.\n      subst.\n      constructors; eauto 2 using flowsto_refl.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  (* Backat with wait *)\n  - apply WellformedAux; eauto. \n  (* Backat with progress *)\n  - assert (BackAt pc2 t1 <> Stop) by congruence.\n    assert (BackAt pc2 t1 <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    clear H.\n    invert_wt_cmd.\n    apply WellformedAux; eauto.\n    intro; exfalso; eauto.\n  - assert (BackAt pc2 t1 <> Stop) by congruence.\n    assert (BackAt pc2 t1 <> TimeOut) by congruence.\n    do 2 specialize_gen.\n    constructor; eauto 2.\n    intros.\n    exfalso; eauto 2.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  (* new *)\n  - let H1 := fresh in let H2 := fresh in\n    assert (NewArr i l e e0 <> Stop) as H1 by congruence;\n      assert (NewArr i l e e0 <> TimeOut) as H2 by congruence;\n      do 2 specialize_gen;\n      clear H1; clear H2.\n    invert_wt_cmd.\n    rewrite_inj.\n    apply WellformedAux; eauto.\n    + destruct \u03c40 as [\u03c3 \u2113].\n      eapply wf_tenv_extend; eauto.\n      intro; discriminate.\n    + destruct \u03c40 as [\u03c3 \u2113].\n      eapply wf_stenv_extend; intros; subst; eauto.   \n    + unfolds.\n      splits.\n      * intros.\n        destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          unfold extend_stenv.\n          rewrite -> eq_loc.\n          rewrite_inj.\n          reflexivity.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          destruct (decide (l1 = loc)); subst.\n          - invert_dang_free; eauto.\n            assert (exists \u2113 \u03bc, heap_lookup loc h1 = Some (\u2113, \u03bc)) by eauto.\n            destruct_exists.\n            rewrite_inj.\n            discriminate.\n          - unfold extend_stenv.\n            rewrite -> neq_loc by eauto.\n            destruct_consistent.\n            eauto.\n        }\n      * intros.\n        destruct (decide (loc1 = l1)); subst.\n        {\n          rewrite -> extend_stenv_lookup_eq in *.\n          apply_heap_lookup_extend_eq.\n          assert (v = ValLoc loc2).\n          {\n            match goal with\n              [H1: forall _, lookup _ _ = Some _,\n               H2: lookup _ ?n = Some _ |- _] =>\n              specialize (H1 n)\n            end.\n            rewrite_inj.\n            reflexivity.\n          }\n          subst.\n          rewrite_inj.\n          assert (exists y, memory_lookup m1 y = Some (ValLoc loc2) /\\ e0 = Var y) by eauto.\n          super_destruct; subst.\n          assert (exists \u2113 \u03bc, heap_lookup loc2 h1 = Some (\u2113, \u03bc)) by eauto.\n          super_destruct.\n          rewrite_inj.\n          assert (l1 <> loc2).\n          {\n            intro.\n            subst.\n            rewrite_inj.\n            discriminate.\n          }\n          rewrite -> extend_stenv_lookup_neq by solve[eauto].\n          eauto.\n        }\n        {\n          rewrite -> extend_stenv_lookup_neq in * by solve[eauto].\n          rewrite -> heap_lookup_extend_neq in * by solve[eauto 2].\n          destruct (decide (l1 = loc2)); subst.\n          - assert (~ reach m1 h1 loc2).\n            {\n              intro.\n              assert (exists \u2113 \u03bc, heap_lookup loc2 h1 = Some (\u2113, \u03bc)) by eauto.\n              super_destruct.\n              rewrite_inj.\n              discriminate.\n            }\n            assert (~ reach m1 h1 loc1).\n            {\n              intro.\n              eauto.\n            }\n            assert (forall loc' : loc, v = ValLoc loc' -> reach m1 h1 loc').\n            {\n              intros; subst.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              eauto.\n            }\n            match goal with\n              [H: ~ reach _ _ loc1 |- _] =>\n              contradict H\n            end.\n            eauto 2 using reach_extend_implies_reach_if.\n          - rewrite -> extend_stenv_lookup_neq by solve[eauto].\n            destruct_consistent.\n            assert (forall loc' : loc, v = ValLoc loc' -> reach m1 h1 loc').\n            {\n              intros; subst.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              eauto.\n            }\n            assert (~ reach m1 h1 l1).\n            {\n              intro.\n              assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n              super_destruct; subst.\n              rewrite_inj.\n              discriminate.\n            }\n            assert (reach m1 h1 loc1) by eauto 2 using reach_extend_implies_reach_if.\n            eauto.\n        }\n    + (* Show: Stop is Welltyped *)\n      intro.\n      exfalso; eauto.\n      \n    + (* Show: Dangling free memory and heap *)\n      unfolds.\n      intros.\n      destruct (decide (l1 = loc)); subst.\n      * assert (exists \u03bc,\n                   heap_lookup loc (h1 [loc \u2192 (n \u00d7 v, l), H1, H2]) = Some (l, \u03bc) /\\\n                   (forall n0 : nat, lookup \u03bc n0 = Some v)) by eauto.\n        super_destruct; subst.\n        eauto.\n      * assert (forall loc' : id_and_loc.loc, v = ValLoc loc' -> reach m1 h1 loc').\n        {\n          intros; subst.\n          assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n          super_destruct; subst.\n          eauto.\n        }\n        assert (loc <> l1) by eauto.\n        assert (~ reach m1 h1 l1).\n        {\n          intro.\n          assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n          super_destruct; subst.\n          rewrite_inj.\n          discriminate.\n        }\n        assert (reach m1 h1 loc) by eauto 2 using reach_extend_implies_reach_if.\n        destruct_consistent.\n        rewrite -> heap_lookup_extend_neq by solve[eauto].\n        eauto.      \n    + eapply lookup_in_bounds_extend; eauto 2.\n      * intros; subst.\n        assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n        super_destruct; subst.\n        eauto.\n      * intro.\n        assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n        super_destruct; subst.\n        rewrite_inj.\n        discriminate.\n    + unfolds.\n      splits.\n      * intros.\n        destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          apply_heap_lookup_extend_eq.\n          rewrite_inj.\n          reflexivity.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          destruct (decide (loc = l1)); subst.\n          - edestruct (heap_lookup_extend_eq l1 l n v h1); eauto 2.\n            super_destruct.\n            rewrite_inj.\n            invert_dang_free.\n            assert (exists \u2113 \u03bc, heap_lookup l1 h1 = Some (\u2113, \u03bc)) by eauto.\n            destruct_exists.\n            rewrite_inj.\n            discriminate.\n          - rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n            eauto 2.\n        }\n      * intros.\n        destruct (decide (loc = l1)); subst.\n        {\n          rewrite -> extend_stenv_lookup_eq in *.\n          rewrite_inj.\n          apply_heap_lookup_extend_eq.\n          rewrite_inj.\n          destruct (decide (loc' = l1)); subst.\n          - rewrite_inj.\n            assert (v = ValLoc l1) by congruence.\n            subst.\n            assert (exists x, memory_lookup m1 x = Some (ValLoc l1) /\\ e0 = Var x) by eauto.\n            super_destruct'; subst.\n            assert (reach m1 h1 l1) by eauto.\n            assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n            super_destruct; subst.\n            congruence.\n          - rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n            assert (exists loc, v = ValLoc loc) by eauto.\n            super_destruct'; subst.\n            assert (exists x, memory_lookup m1 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto.\n            super_destruct; subst.\n            invert_var_typing.\n            assert (loc = loc') by congruence; subst.\n            symmetry.\n            eauto 2.\n        }\n        {\n          rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n          rewrite -> extend_stenv_lookup_neq in * by solve[eauto].\n          destruct (decide (loc' = l1)); subst.\n          - apply_heap_lookup_extend_eq.\n            rewrite_inj.\n            assert (~ reach m1 h1 l1).\n            {\n              intro.\n              assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n              super_destruct; congruence.\n            }\n            assert (reach m1 h1 loc).\n            {\n              assert (forall loc', v = ValLoc loc' -> reach m1 h1 loc').\n              {\n                intros; subst.\n                assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n                super_destruct; subst.\n                eauto.\n              }              \n              eapply reach_extend_implies_reach_if; eauto.\n            }\n            assert (reach m1 h1 l1) by eauto 2.\n            contradiction.\n          - rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n            assert (~ reach m1 h1 l1).\n            {\n              intro.\n              assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n              super_destruct; congruence.\n            }\n            assert (reach m1 h1 loc).\n            {\n              assert (forall loc', v = ValLoc loc' -> reach m1 h1 loc').\n              {\n                intros; subst.\n                assert (exists x, memory_lookup m1 x = Some (ValLoc loc'0) /\\ e0 = Var x) by eauto.\n                super_destruct; subst.\n                eauto.\n              }              \n              eapply reach_extend_implies_reach_if; eauto.\n            }\n            eauto 2.\n        }\n      * intros.\n        destruct (decide (loc1 = l1)); subst.\n        {\n          apply_heap_lookup_extend_eq.\n          rewrite_inj.\n          destruct (decide (loc2 = l1)); subst.\n          - rewrite_inj.\n            eapply flowsto_refl.\n          - rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n            assert (wf_type bot (SecType (Array \u03c40 l) (\u2113_x, \u2218))) by eauto.\n            invert_wf_type.\n            assert (v = ValLoc loc2) by congruence; subst.\n            assert (exists x, memory_lookup m1 x = Some (ValLoc loc2) /\\ e0 = Var x) by eauto.\n            super_destruct; subst.\n            invert_var_typing.\n            destruct \u03c40 as [\u03c4 \u03b5].\n            assert (exists t, \u03c4 = Array t \u21132).\n            {\n              destruct \u03c4.\n              - assert (exists n, ValLoc loc2 = ValNum n) by eauto.\n                super_destruct; congruence.\n              - exists s.\n                eapply f_equal2; eauto 2.\n            }\n            super_destruct'; subst.\n            invert_wf_type.\n            eauto.\n        }\n        {\n          rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n          assert (reach m1 h1 loc1).\n          {\n            assert (~ reach m1 h1 l1).\n            {\n              intro.\n              assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n              super_destruct; congruence.\n            }\n            assert (forall loc' : loc, v = ValLoc loc' -> reach m1 h1 loc').\n            {\n              intros; subst.\n              assert (exists x, memory_lookup m1 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              eauto.\n            }\n            eapply reach_extend_implies_reach_if; eauto.\n          }\n          destruct (decide (loc2 = l1)); subst.\n          - apply_heap_lookup_extend_eq.\n            rewrite_inj.            \n            assert (reach m1 h1 l1) by eauto 2.\n            assert (exists l \u03bc, heap_lookup l1 h1 = Some (l, \u03bc)) by eauto.\n            super_destruct; subst.\n            congruence.\n          - rewrite -> heap_lookup_extend_neq in * by solve[eauto].\n            eauto 2.\n        }\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  (* Set array *)\n  - let H1 := fresh in let H2 := fresh in\n      assert (SetArr i e e0 <> Stop) as H1 by congruence;\n        assert (SetArr i e e0 <> TimeOut) as H2 by congruence;\n      do 2 specialize_gen;\n      clear H1; clear H2.\n    apply WellformedAux; eauto.\n    + unfolds.\n      intros.\n      splits~.\n      * intros.\n        destruct (decide (loc = l0)); subst.\n        {\n          _apply heap_lookup_update_eq2 in *.\n          super_destruct; subst.\n\n          destruct (decide (n0 = n)); subst.\n          - rewrite -> lookup_update_eq in *.\n            rewrite_inj.\n            invert_wt_cmd.\n            invert_lifted.\n            assert (\u03c3 = Int).\n            {\n              match goal with\n                [H: consistent _ _ _ _,\n                    H2: stenv' _ = Some _ |- _] =>\n                destruct H as [H _];\n                  erewrite -> H in H2; eauto\n              end.\n              rewrite_inj.\n              reflexivity.\n            }\n            subst.\n            eauto.\n          - rewrite -> lookup_update_neq in * by solve[eauto].\n            eauto.\n        }\n        {\n          assert (heap_lookup loc (update_heap l0 n v h1) = heap_lookup loc h1) by (apply heap_lookup_update_neq; assumption).\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          rewrite_inj.\n          eauto.\n        }\n      * intros.\n        destruct (decide (loc = l0)); subst.\n        {\n          _apply heap_lookup_update_eq2 in *; eauto 2.\n          destruct_exists.\n          super_destruct; subst.\n          destruct (decide (n0 = n)); subst.\n          - assert (heap_lookup l0 h1 <> None).\n            {\n              intro.\n              assert (exists \u2113 \u03bc, heap_lookup l0 h1 = Some (\u2113, \u03bc)) by eauto.\n              super_destruct; congruence.\n            }\n            rewrite -> lookup_update_eq in *.\n            rewrite_inj.\n            assert (SetArr i e e0 <> Stop) by (intro H_absurd; discriminate H_absurd).\n            invert_wt_cmd.\n            invert_lifted.            \n            assert (exists \u2113, \u03c3 = Array t \u2113).\n            {\n              match goal with\n                [H: consistent _ _ _ _,\n                    H2: stenv' _ = Some _ |- _] =>\n                destruct H as [H _];\n                  erewrite -> H in H2; eauto\n              end.\n              rewrite_inj.\n              eauto.\n            }\n            super_destruct; subst.\n            eauto using wt_array_e_is_loc.\n          - rewrite -> lookup_update_neq in *; eauto 2.\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          eauto.\n        }\n      * eauto.\n      * intros.\n        destruct (decide (loc = l0)); subst.\n        {\n          _apply heap_lookup_update_eq2 in *.\n          super_destruct; eauto 2.\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto 2].\n          eauto 2.\n        }\n    + unfolds.\n      splits~; eauto 2.\n      intros.\n      destruct (decide (loc1 = l0)); subst.\n      * destruct (decide (n0 = n)); subst.\n        {\n          _apply heap_lookup_update_eq2 in *.\n          destruct_exists.\n          super_destruct; subst.\n          rewrite -> lookup_update_eq in *.\n          rewrite_inj.\n          invert_wt_cmd.\n          invert_lifted.\n          edestruct location_is_from_lookup; eauto; subst.\n          repeat match goal with\n                   [H: expr_has_type _ (Var _) _ |- _] =>\n                   inverts H\n                 | [H: eval _ (Var _) = _ |- _] =>\n                   inverts H\n                 end.\n          invert_dang_free.\n          assert (exists \u2113 \u03bc, heap_lookup loc2 h1 = Some (\u2113, \u03bc)) by eauto.\n          match goal with\n            [H: consistent _ _ _ _ |- _] =>\n            destruct H as [H _]; erewrite -> H in * by eauto\n          end.\n          rewrite_inj.\n          eauto.\n        }\n        {\n          _apply heap_lookup_update_eq2 in *.\n          super_destruct.\n          subst.\n          rewrite -> lookup_update_neq in * by solve[eauto 2].\n          destruct_consistent; eauto.\n        }\n      * invert_wt_cmd.\n        invert_lifted.\n        rewrite -> heap_lookup_update_neq in * by solve[eauto 2].\n        destruct_consistent.\n        destruct v.\n        {\n          eauto using reach_update_with_num.\n        }\n        {\n          assert (exists x, memory_lookup m2 x = Some (ValLoc l1) /\\ e0 = Var x) by eauto.\n          super_destruct; subst.\n          destruct (decide (l0 = loc1)); subst.\n          - eauto.\n          - invert_var_typing.\n            assert (reach m2 h1 loc1).\n            {\n              eapply reach_by_update_implies_reach_if; eauto.\n            }\n            assert (reach m2 h1 l0) by eauto. \n            eauto.\n        }\n    + intro; exfalso; eauto.\n    + unfolds.\n      intros.\n      inverts H.\n      * assert (exists \u2113 \u03bc, heap_lookup loc h1 = Some (\u2113, \u03bc)) by (invert_dang_free; eauto).\n        destruct_exists.\n        destruct (decide (loc = l0)); subst.\n        {\n          eauto.\n        }\n        {\n          rewrite -> heap_lookup_update_neq by solve[eauto].\n          eauto.\n        }\n      * destruct (decide (loc0 = l0)); subst.\n        {\n          destruct (decide (n0 = n)); subst.\n          - _apply heap_lookup_update_eq2 in *; eauto 2.\n            destruct_exists.\n            super_destruct; subst.\n            rewrite -> lookup_update_eq in *.\n            rewrite_inj.        \n            invert_wt_cmd.\n            + assert (exists x, memory_lookup m2 x = Some (ValLoc loc) /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              invert_var_typing.\n              destruct (decide (loc = l0)); subst.\n              * eauto.\n              * rewrite -> heap_lookup_update_neq by solve[eauto].\n                eauto.\n          - assert (exists \u03bd, heap_lookup l0 h1 = Some (\u2113, \u03bd) /\\ \u03bc = update_lookup \u03bd n v) by eauto.\n            super_destruct; subst.\n            rewrite -> lookup_update_neq in * by solve[eauto].\n            destruct (decide (loc = l0)); subst.\n            {\n              eauto.\n            }\n            {\n              rewrite -> heap_lookup_update_neq by eauto 2.\n              eauto.\n            }\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          assert (reach m2 h1 l0) by eauto.\n          destruct (decide (loc = l0)); subst.\n          - assert (exists \u2113 \u03bc, heap_lookup l0 h1 = Some (\u2113, \u03bc)) by eauto.\n            super_destruct; subst.\n            eauto.\n          - rewrite -> heap_lookup_update_neq by solve[eauto].\n            assert (reach m2 h1 loc0).\n            {\n              destruct v.\n              - eauto using reach_update_with_num.\n              - invert_wt_cmd;\n                  assert (exists x, memory_lookup m2 x = Some (ValLoc l) /\\ e0 = Var x)\n                    by eauto;\n                  super_destruct; subst;\n                    eauto 3 using reach_by_update_implies_reach_if.\n            }\n            eauto.\n        } \n    + unfolds.\n      intros.\n      destruct (decide (loc = l0)); subst.\n      * rewrite -> length_of_update in *.\n        destruct (decide (n0 = n)); subst.\n        {\n          exists v.      \n          assert (reach m2 h1 l0) by eauto.\n          assert (exists \u2113 \u03bc, heap_lookup l0 h1 = Some (\u2113, \u03bc)) by eauto.\n          super_destruct; subst.\n          rewrite_inj.\n          _apply heap_lookup_update_eq2 in *.\n          super_destruct; subst.\n          eauto.\n        }\n        {\n          _apply heap_lookup_update_eq2 in *.\n          super_destruct; subst.\n          rewrite -> lookup_update_neq by solve[eauto 2].\n          eauto.\n        }\n      * rewrite -> heap_lookup_update_neq in * by solve[eauto 2].\n        rewrite -> length_of_update in *.\n        unfold lookup_in_bounds in *.\n        assert (reach m2 h1 l0) by eauto.\n        destruct v.\n        {\n          eauto using reach_update_with_num.\n        }\n        {\n          invert_wt_cmd.\n          assert (exists x, memory_lookup m2 x = Some (ValLoc l) /\\ e0 = Var x)\n            by eauto.\n          super_destruct; subst.\n          invert_var_typing.\n          assert (reach m2 h1 l) by eauto.\n          assert (reach m2 h1 loc) by eauto 2 using reach_by_update_implies_reach_if.\n          eauto.\n        }\n    + unfolds.\n      splits~.\n      * intros.\n        destruct (decide (loc = l0)); subst.\n        {\n          assert (exists \u03bd, heap_lookup l0 h1 = Some (l2, \u03bd) /\\ \u03bc = update_lookup \u03bd n v)\n            by eauto.\n          super_destruct; subst.\n          eauto 2.\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          eauto 2.\n        }\n      * intros.\n        assert (exists \u03bc, heap_lookup loc' h1 = Some (\u2113', \u03bc)).\n        {\n          destruct (decide (loc' = l0)); subst.\n          - assert (exists \u03bd0, heap_lookup l0 h1 = Some (\u2113', \u03bd0) /\\ \u03bd = update_lookup \u03bd0 n v) by eauto.\n            super_destruct; subst.\n            eauto.\n          - rewrite -> heap_lookup_update_neq in * by solve[eauto].\n            eauto.\n        }\n        assert (reach m2 h1 loc).\n        {\n          destruct v.\n          - eauto using reach_update_with_num.\n          - assert (reach m2 h1 l0) by eauto.\n            invert_wt_cmd.\n            assert (exists x, memory_lookup m2 x = Some (ValLoc l1) /\\ e0 = Var x) by eauto.\n            super_destruct; subst.\n            eapply reach_by_update_implies_reach_if; eauto 2.\n        }\n        \n        destruct (decide (loc = l0)); subst.\n        {\n          assert (exists \u03bd, heap_lookup l0 h1 = Some (\u2113, \u03bd) /\\ \u03bc = update_lookup \u03bd n v)\n            by eauto.\n          super_destruct; subst.\n          destruct (decide (n = n0)); subst.\n          - rewrite -> lookup_update_eq in *.\n            rewrite_inj.\n            invert_wt_cmd.\n            assert (exists x, memory_lookup m2 x = Some (ValLoc loc') /\\ e0 = Var x) by eauto.\n            super_destruct; subst.\n            invert_var_typing.\n            invert_lifted.\n            assert (exists \u03c4, \u03c3 = Array \u03c4 \u2113').\n            {\n              destruct \u03c3.\n              - assert (exists n, ValLoc loc' = ValNum n) by eauto.\n                super_destruct; discriminate.\n              - exists s0.\n                eapply f_equal2; eauto 2.\n            }\n            super_destruct; subst.\n            assert (stenv' loc' = Some \u03c4) by eauto.\n            rename l3 into \u03b5_arr.\n            assert (\u21130 = \u2113) by eauto 2; subst.\n            assert (stenv' l0 = Some (SecType (Array \u03c4 \u2113') \u03b5_arr)) by eauto.\n            rewrite_inj.\n            reflexivity.\n          - rewrite -> lookup_update_neq in * by solve[eauto].\n            eauto 2.\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          super_destruct; subst.\n          eauto 2.\n        }\n      * intros.\n        \n        assert (exists \u03bc, heap_lookup loc2 h1 = Some (\u21132, \u03bc)).\n        {\n          destruct (decide (loc2 = l0)); subst.\n          - assert (exists \u03bd0, heap_lookup l0 h1 = Some (\u21132, \u03bd0) /\\ \u03bd = update_lookup \u03bd0 n v) by eauto.\n            super_destruct; subst.\n            eauto.\n          - rewrite -> heap_lookup_update_neq in * by solve[eauto].\n            eauto.\n        }\n        destruct (decide (loc1 = l0)); subst.\n        {\n          assert (exists \u03bd, heap_lookup l0 h1 = Some (\u21131, \u03bd) /\\ \u03bc = update_lookup \u03bd n v) by eauto.\n          super_destruct; subst.\n          destruct (decide (n = n0)); subst.\n          - rewrite -> lookup_update_eq in *.\n            rewrite_inj.\n            invert_wt_cmd.\n            assert (exists x, memory_lookup m2 x = Some (ValLoc loc2) /\\ e0 = Var x) by eauto.\n            super_destruct; subst.\n            invert_var_typing.\n            invert_lifted.\n            assert (exists \u03c4, \u03c3 = Array \u03c4 \u21132).\n            {\n              destruct \u03c3.\n              - assert (exists n, ValLoc loc2 = ValNum n) by eauto.\n                super_destruct; discriminate.\n              - exists s.\n                eapply f_equal2; eauto 2.\n            }\n            super_destruct; subst.\n            assert (\u2113 = \u21131) by eauto 2; subst.\n            assert (stenv' l0 = Some (SecType (Array \u03c4 \u21132) l2)) by eauto.\n            assert (wf_type bot (SecType (Array (SecType (Array \u03c4 \u21132) l2) \u21131) \u03b5_x)) by eauto.\n            do 2 invert_wf_type.\n            eauto.\n          - rewrite -> lookup_update_neq in * by solve[eauto].\n            eauto 3.\n        }\n        {\n          rewrite -> heap_lookup_update_neq in * by solve[eauto].\n          super_destruct; subst.\n          assert (reach m2 h1 loc1).\n          {\n            destruct v; eauto 3 using reach_update_with_num.\n            assert (reach m2 h1 l).\n            {\n              invert_wt_cmd.\n              assert (exists x, memory_lookup m2 x = Some (ValLoc l) /\\ e0 = Var x) by eauto.\n              super_destruct; subst.\n              eauto.\n            }\n            eapply reach_by_update_implies_reach_if; eauto 3.\n          }\n          eauto 2.\n        }\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  - do 2 specialize_gen.\n    apply WellformedAux; eauto.\n    + invert_wt_cmd.\n      invert_lifted.\n      rewrite_inj.\n      eapply wf_tenv_extend; eauto.\n      * intros; subst.\n        eauto.\n      * intros; subst.\n        eauto.\n    + invert_wt_cmd.\n      invert_lifted.\n      unfold consistent.\n      splits.\n      * intros.\n        destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          destruct_consistent.\n          eauto.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          eauto.\n        }\n      * intros.\n        assert (reach m1 h2 loc1).\n        {\n          destruct v.\n          - eauto 2 using reach_extend_with_num.\n          - assert (reach m1 h2 l0) by eauto.\n            assert (reach m1 h2 l0) by eauto 3.\n            eapply reach_extend2 with (loc1 := l0).\n            + eauto\n            + match goal with\n                [H: lookup _ _ = Some (ValLoc l1) |- _] =>\n                eapply H\n              end.\n            + eauto.\n            + eauto.\n            + eauto.\n        }\n        destruct_consistent.\n        eauto.\n    + intro; exfalso; eauto.\n    + unfolds.\n      intros.\n      destruct v.\n      * eauto using reach_extend_with_num.\n      * assert (reach m1 h2 l0) by eauto 3.\n        eauto using reach_extend2.\n    + unfolds.\n      intros.\n      destruct v.\n      * eauto using reach_extend_with_num.\n      * assert (reach m1 h2 l) by eauto 3.\n        assert (reach m1 h2 loc) by eauto 2 using reach_extend2.\n        eauto.\n    + unfolds.\n      splits~.\n      * intros.\n        destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          rewrite_inj.\n          invert_wt_cmd.\n          invert_lifted.\n          rewrite_inj.\n          assert (\u21130 = \u2113) by eauto 2.\n          rewrite_inj.\n          subst.\n          rewrite_inj.\n          assert (reach m1 h2 l0) by eauto.\n          assert (stenv' l0 = Some (SecType (Array s l1) \u03b50)) by eauto.\n          destruct \u03b50 as [l3 \u03b9].\n          symmetry.\n          eauto 3.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          eauto 2.\n        }\n      * intros.\n        assert (reach m1 h2 loc).\n        {\n          destruct v; eauto 2 using reach_extend_with_num.\n          assert (reach m1 h2 l0) by eauto.\n          assert (reach m1 h2 l1).\n          {\n            eauto 2.\n          }\n          eauto 3.\n        }\n        eauto 3.\n      * intros.\n        assert (reach m1 h2 loc1).\n        {\n          destruct v; eauto 2 using reach_extend_with_num.\n          assert (reach m1 h2 l0) by eauto.\n          assert (reach m1 h2 l) by eauto 2.\n          eauto 3.\n        }\n        eauto 3.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  - let H1 := fresh in let H2 := fresh in\n    assert (Time i <> Stop) as H1 by congruence;\n      assert (Time i <> TimeOut) as H2 by congruence;\n      do 2 specialize_gen;\n      clear H1; clear H2.\n    apply WellformedAux; try eauto 2.\n    + invert_wt_cmd.\n      rewrite_inj.\n      eapply wf_tenv_extend; eauto.\n      * intros; subst.\n        discriminate.\n    + invert_wt_cmd.\n      unfolds.\n      splits.\n      * intros.\n        destruct (decide (i = x)); subst.\n        {\n          rewrite -> extend_memory_lookup_eq in *.\n          discriminate.\n        }\n        {\n          rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n          eauto.\n        }\n      * intros.\n        destruct_consistent.\n        eauto using reach_extend_with_num.\n    + intro; exfalso; eauto.\n    + unfolds.\n      intros.\n      assert (reach m1 h2 loc) by eauto 2 using reach_extend_with_num.\n      eauto.\n    + unfolds.\n      intros.\n      assert (reach m1 h2 loc) by eauto 2 using reach_extend_with_num.\n      eauto.\n    + unfolds.\n      splits; eauto 3 using reach_extend_with_num.\n      intros.\n      destruct (decide (i = x)); subst.\n      * rewrite -> extend_memory_lookup_eq in *.\n        discriminate.\n      * rewrite -> extend_memory_lookup_neq in * by solve[eauto].\n        eauto 2 using reach_extend_with_num.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n  - eapply gc_preserves_wf.\n    + eauto.\n    + eauto.\n    + eauto.\n    + erewrite -> disjoint_union_proof_irrelevance; eauto.\n\n      Unshelve.\n      * repeat constructor; eauto.\n      * repeat constructor; eauto.\n      * eauto.\n      * eauto.\nQed.\n\nEnd Preservation.", "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/preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3073580295544412, "lm_q1q2_score": 0.17160628482597431}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat seq eqtype fintype path fingraph.\nFrom extructures Require Import ord fset fmap fperm.\nFrom CoqUtils Require Import word nominal.\nRequire Import Coq.Strings.String.\n\nRequire Import lib.utils lib.fmap_utils common.types.\nRequire Import memory_safety.property memory_safety.abstract.\nRequire Import memory_safety.classes memory_safety.executable.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection MemorySafety.\n\nLocal Open Scope string_scope.\n\nLocal Open Scope fset_scope.\n\nImport Abstract.\n\nVariable mt : machine_types.\nVariable ops : machine_ops mt.\nVariable sr : syscall_regs mt.\nVariable addrs : memory_syscall_addrs mt.\n\nLocal Notation state := (state mt).\nLocal Notation pointer := [eqType of pointer mt].\nLocal Notation value := (value mt).\nLocal Notation astepf := (AbstractE.step ops sr addrs).\n\nImplicit Type m : memory mt.\nImplicit Type rs : registers mt.\nImplicit Type s : state.\nImplicit Type b : name.\nImplicit Type p : pointer.\nImplicit Type bs : {fset name}.\nImplicit Type v : value.\nImplicit Type pm : {fperm name}.\n\nDefinition references m b b' :=\n  [exists offs : mword mt * mword mt,\n    getv m (b, offs.1) == Some (VPtr (b', offs.2))].\n\nInductive reachable pc rs m b : Prop :=\n| ReachBasePc p of pc = VPtr p & p.1 = b\n| ReachBaseReg r p of rs r = Some (VPtr p) & p.1 = b\n| ReachHop b' of reachable pc rs m b' & references m b' b.\nHint Constructors reachable.\n\nDefinition reachable_blocks pc rs m bs :=\n  forall b, b \\in bs <-> reachable pc rs m b.\n\nDefinition live_blocks s bs :=\n  reachable_blocks (pc s) (regs s) (mem s) bs.\n\nLemma live_blocks_blocks s bs :\n  live_blocks s bs -> {subset bs <= blocks s}.\nProof.\nmove=> live b /live in_bs; apply/in_blocks.\nelim: b / in_bs\n      => [b ptr ? ?|b r ptr|b b' _ IH /existsP [[/= off off'] /eqP hget]].\n- by eapply BlocksPc; eauto.\n- by eapply BlocksReg; eauto.\nmove: hget; rewrite /getv /=.\ncase mem_b': (mem s b') => [fr|] //=.\nhave [in_bounds [hnth]|] //= := boolP (off < size fr).\nhave ?: VPtr (b, off') \\in fr.\n  by rewrite -hnth; apply mem_nth.\nby eapply BlocksMem; eauto.\nQed.\n\n(* FIXME: Right now, this doesn't say anything about memory reads. *)\nCoInductive valid_step s bs s' bs' : Prop :=\n| ValidNop of mem s = mem s' & {subset bs' <= bs}\n| ValidWrite p v of updv (mem s) p v = Some (mem s')\n                  & {subset bs' <= bs} & p.1 \\in bs\n| ValidAlloc b sz of malloc_fun (mem s) (blocks s) sz = (mem s', b)\n                   & {subset bs' <= b |: bs}\n| ValidFree b of Abstract.free_fun (Abstract.mem s) b = Some (Abstract.mem s')\n               & {subset bs' <= bs} & b \\in bs.\n\nCoInductive value_ok pc rs m : value -> Prop :=\n| VOkData x : value_ok pc rs m (VData x)\n| VOkPtr p of reachable pc rs m p.1 : value_ok pc rs m (VPtr p).\nHint Constructors value_ok.\n\nCoInductive valid_pc_upd (pc pc' : value) rs m : Prop :=\n| ValidPcUpd of value_ok pc rs m pc'.\nHint Constructors valid_pc_upd.\n\nCoInductive valid_reg_upd pc rs rs' m : Prop :=\n| ValidRegSame of rs = rs'\n| ValidRegUpd v r of updm rs r v = Some rs' & value_ok pc rs m v.\nHint Constructors valid_reg_upd.\n\nLemma upd_reachable pc pc' rs rs' m bs bs' :\n  reachable_blocks pc rs m bs ->\n  reachable_blocks pc' rs' m bs' ->\n  valid_pc_upd pc pc' rs m ->\n  valid_reg_upd pc rs rs' m ->\n  {subset bs' <= bs}.\nProof.\nmove=> hbs hbs' v_pc v_rs b /hbs' reach_b; apply/hbs.\nelim: b / reach_b {hbs hbs'} => [b [b' off] /= hpc' hb'|b r [b' off]/=|b b' _].\n- rewrite {}hb' {b'} in hpc'.\n  case: v_pc => v_pc.\n  by case: pc' / v_pc hpc' => [//|[b' off'] /= ? [<- _]].\n- move=> hr hb'; move: hr; rewrite {}hb' {b'}.\n  case: v_rs => [-> hr|v r' upd_rs]; first by eapply ReachBaseReg; eauto.\n  move: {upd_rs} (updm_set upd_rs)=> upd_rs v_ok.\n  rewrite {}upd_rs {rs'} setmE.\n  have [_{r}[vE]|_ hr] := altP eqP.\n    by case: v / v_ok vE => // - [b' off'] /= ? [<- _].\n  by eapply ReachBaseReg; eauto.\nby eapply ReachHop.\nQed.\n\nLemma get_reg_ok pc rs r m v bs :\n  rs r = Some v -> value_ok pc rs m v.\nProof.\ncase: v => [?|[b off get_rs]]; constructor.\nby eapply ReachBaseReg; eauto.\nQed.\n\nLemma get_mem_ok pc rs m p v :\n  value_ok pc rs m (VPtr p) ->\n  getv m p = Some v ->\n  value_ok pc rs m v.\nProof.\nmove=> p_ok; move: {1 2}(VPtr p) p_ok (erefl (VPtr p))=> v'.\ncase: v' / => // - [b off] b_reach [<-].\ncase: v => [?|[b' off' get_p]]; constructor.\neapply ReachHop; eauto; apply/existsP; exists (off,off')=> /=.\nby apply/eqP.\nQed.\n\nLemma lift_binop_ok pc rs m o v1 v2 v3 :\n  value_ok pc rs m v1 ->\n  value_ok pc rs m v2 ->\n  lift_binop o v1 v2 = Some v3 ->\n  value_ok pc rs m v3.\nProof.\nrewrite /lift_binop.\ncase: v1 / => [v1|[b1 off1] hb1]; case: v2 / => [v2|[b2 off2] hb2];\ncase: o=> //;\ntry match goal with\n| |- context[?b1 == ?b2] =>\n  have [b1_eq_b2|b1_neq_b2] // := altP (b1 =P b2)\nend;\nmove=> [<-]; constructor; done.\nQed.\n\nLtac simple_intros :=\n  move=> /= *;\n  repeat match goal with\n  | H : live_blocks ?s ?bs |- _ =>\n    match goal with\n    | _ : {subset bs <= blocks s} |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let live := fresh \"live\" in\n    let sub := fresh \"sub\" in\n    move: H => live;\n    have sub := live_blocks_blocks live;\n    simpl in live, sub; simpl\n  end;\n  apply: ValidNop; first done.\n\nLemma getv_upd m m' p v :\n  updv m p v = Some m' ->\n  forall p', getv m' p' = if p' == p then Some v else getv m p'.\nProof.\nrewrite /updv/getv/= => get_p p'; move: get_p.\ncase get_m: (m p.1) => [fr|] //.\nhave [leq_size_fr [<-]|//] := boolP (p.2 < size fr)%N.\nrewrite setmE -pair_eqE /=.\nhave [eq_p1|neq_p1 //] := altP (p'.1 =P p.1).\nrewrite size_cat size_take /= size_drop leq_size_fr.\nrewrite addnS -addSn addnC subnK //.\nhave [eq_p2|neq_p2] := altP (p'.2 =P p.2).\n  by rewrite eq_p2 leq_size_fr nth_cat size_take leq_size_fr ltnn subnn.\nrewrite eq_p1 get_m.\ncase: ifP => // leq_size_fr'.\nrewrite nth_cat size_take /= leq_size_fr; move: neq_p2; rewrite -!val_eqE /=.\ncase: (ltngtP p'.2 p.2) => [leq_p2|leq_p2'|eq_p2 //].\n  by rewrite nth_take //.\nmove: (leq_p2'); rewrite -{1}(addn0 p.2) -ltn_subRL => leq_subn.\nby rewrite -(@prednK (p'.2 - p.2))//= -subnS nth_drop addnC subnK // subnn.\nQed.\n\nLtac safe_step_simple_cases :=\n  simple_intros;\n  first [ solve [ eapply upd_reachable; try eassumption;\n                  unfold pc, regs, mem;\n                  eauto using get_reg_ok, get_mem_ok, lift_binop_ok;\n                  done ]\n        | failwith \"solve_simple_cases\" ].\n\nLemma safe_step s bs s' bs' :\n  step s s' ->\n  live_blocks s bs ->\n  live_blocks s' bs' ->\n  valid_step s bs s' bs'.\nProof.\ncase: s s' / => /=; try safe_step_simple_cases.\n- move=> m m' rs pc ptr i r1 r2 v _ _ get_ptr get_v upd_m /= hbs hbs'.\n  eapply ValidWrite; eauto.\n    move=> b' /hbs' b'_in_bs'; apply/hbs => {hbs hbs'}.\n    elim: b' / b'_in_bs'\n          => [b' p [<-] {p} <-|b' r p get_p <-\n             |b' b'' _ IH /existsP /= [off /eqP get_b'']] /=.\n    + by eapply ReachBasePc; eauto.\n    + by eapply ReachBaseReg; eauto.\n    move: get_b''; rewrite (getv_upd upd_m).\n    have [ptr_eq [v_eq]|ptr_neq get_b''] := altP (_ =P ptr).\n      by rewrite v_eq {get_ptr} in get_v; eapply ReachBaseReg; eauto.\n    by eapply ReachHop; eauto; apply/existsP; exists off; apply/eqP.\n  by apply/hbs; apply/(@ReachBaseReg _ _ _ ptr.1 r1 ptr); simpl; eauto.\n- move=> m m' rs rs' sz b pc' _ hm' hrs' get_pc' hbs hbs'.\n  have hsub := live_blocks_blocks hbs.\n  have hsub' := live_blocks_blocks hbs'.\n  eapply ValidAlloc; simpl; eauto=> b' /hbs' b'_in_bs' {hbs'}.\n  elim: b' / b'_in_bs'\n        => [b' p [<-] {p} <-|b' r p get_p <-\n           |b' b'' _ IH /existsP /= [off /eqP get_b']] /=.\n  + rewrite in_fsetU1; apply/orP; right; apply/hbs.\n    by eapply ReachBaseReg; eauto.\n  + move: get_p; rewrite (getm_upd hrs') in_fsetU1.\n    have [_{r} [<-]|r_neq get_p] := altP eqP; first by rewrite eqxx.\n    by apply/orP; right; apply/hbs; eapply ReachBaseReg; eauto.\n  rewrite !in_fsetU1 in IH *; have [//|neq_b' /=] := eqP.\n  case/orP: IH => [/eqP eq_b''|/hbs b''_in_bs].\n    move: get_b'; rewrite {}eq_b'' {b''}.\n    have [in_bounds|off_bounds] := boolP (off.1 < sz)%ord.\n      by rewrite (malloc_get hm' in_bounds).\n    rewrite -Ord.leqNgt in off_bounds.\n    by rewrite (malloc_get_out_of_bounds hm' off_bounds).\n  apply/hbs; eapply ReachHop; eauto; apply/existsP; exists off; apply/eqP.\n  move: get_b'; rewrite /getv/=.\n  have [eq_b''|neq_b''] := b'' =P b.\n    rewrite {}eq_b'' {b''} in b''_in_bs *.\n    by generalize (malloc_fresh hm'); move/hbs/hsub: b''_in_bs => ->.\n  by rewrite (malloc_get_neq hm' neq_b'').\nmove=> m m' rs ptr pc' harg hm' get_pc' /= hbs hbs'.\neapply ValidFree; simpl; first by eauto.\n  move=> b' /hbs' b'_in_bs'; apply/hbs.\n  elim: b' / b'_in_bs'\n        => [b' p [<-] {p} <-|b' r p get_p <-\n           |b' b'' _ IH /existsP /= [off /eqP get_b']] /=.\n  - by eapply ReachBaseReg; eauto.\n  - by eapply ReachBaseReg; eauto.\n  eapply ReachHop; eauto; apply/existsP; exists off; apply/eqP.\n  move: get_b'; rewrite /getv/=.\n  rewrite (get_free _ hm').\n  by have [eq_b''|neq_b''] := altP (b'' =P ptr.1).\nby apply/hbs => {get_pc'}; eapply ReachBaseReg; eauto.\nQed.\n\nLemma rename_valueE pm v :\n  rename pm v = match v with\n                | VData w => VData w\n                | VPtr ptr => VPtr (rename pm ptr.1, ptr.2)\n                end.\nProof. by case: v. Qed.\n\nLemma rename_dataE pm (w : mword mt) :\n  rename pm (VData w) = VData w.\nProof. by []. Qed.\n\nLemma rename_ptrE pm (ptr : pointer) :\n  rename pm (VPtr ptr) = VPtr (pm ptr.1, ptr.2).\nProof. by []. Qed.\n\nLemma rename_stateE pm s :\n  rename pm s = State (rename pm (mem s))\n                      (rename pm (regs s))\n                      (rename pm (pc s)).\nProof. by case: s. Qed.\n\nLemma renamewE k pm (w : word k) : rename pm w = w.\nProof. by []. Qed.\n\nLocal Open Scope fperm_scope.\n\nLemma rename_getv pm m ptr :\n  getv (rename pm m) ptr =\n  rename pm (getv m (rename pm^-1 ptr)).\nProof.\nrewrite /getv !renamemE fst_eqvar /= !renameoE.\ncase e: (m (rename _ _)) => [fr|] //=.\nrewrite [in RHS]fun_if /= !renamewE size_map.\ncase: ifP=> // in_bounds.\nby rewrite (nth_map (VData 0%w) _ _ in_bounds).\nQed.\n\nLemma rename_updv pm m m' ptr v :\n  updv m ptr v = Some m' ->\n  updv (rename pm m) (rename pm ptr) (rename pm v) =\n  Some (rename pm m').\nProof.\nrewrite /updv -[(rename pm ptr).1]fst_eqvar -[(rename pm m) _]getm_eqvar.\ncase m_ptr: (m ptr.1)=> [fr|] //=.\nrewrite renamewE size_map.\ncase: ifP=> //= h_off [<-].\nby rewrite setm_eqvar [in RHS]renamesE map_cat /= map_take map_drop.\nQed.\n\nLemma rename_updr pm rs rs' r v :\n  updm rs r v = Some rs' ->\n  updm (rename pm rs) r (rename pm v) = Some (rename pm rs').\nProof.\nrewrite /updm renamemE renamewE.\ncase rs_r: (rs r) => [v'|] //= [<-{rs'}].\nby rewrite setm_eqvar renamewE.\nQed.\n\nGlobal Instance lift_binop_eqvar f : {eqvar (@lift_binop mt f)}.\nProof.\ncase: f=> [] pm [w1|[p1 o1]] _ <- [w2|[p2 o2]] _ <- //=;\nrewrite ?renamewE ?(can_eq (renameK pm));\ntry match goal with\n| p1 : name, p2 : name |- context [?p1 == ?p2] =>\n  case: (altP (p1 =P p2)) => ? //; subst\nend;\nsolve [move=> [<-]; rewrite rename_valueE //=].\nQed.\n\nLemma rename_lift_binop pm f v1 v2 v3 :\n  lift_binop f v1 v2 = Some v3 ->\n  lift_binop f (rename pm v1) (rename pm v2) = Some (rename pm v3).\nProof. by move=> h; rewrite -[LHS]lift_binop_eqvar; rewrite h. Qed.\n\n(* Redeclaring instances to make type-class inference work *)\nCanonical memory_nominalType := Eval hnf in [nominalType of memory mt].\nCanonical frame_nominalType := Eval hnf in [nominalType of frame mt].\n\nLemma free_fun_eqvar : {eqvar @free_fun mt}.\nProof. by rewrite /free_fun /=; finsupp. Qed.\n\nLemma rename_free pm m m' b :\n  free_fun m b = Some m' ->\n  free_fun (rename pm m) (pm b) = Some (rename pm m').\nProof. by move=> h; rewrite -renamenE -[LHS]free_fun_eqvar h. Qed.\nHint Resolve rename_free : rename_step_db.\n\nLtac rename_getv :=\n  match goal with\n  | pm : {fperm name},\n    get : getv ?m ?ptr = Some ?v |- _ =>\n    match m with\n    | rename pm ?m' => fail 1\n    | _ => idtac\n    end;\n    match goal with\n    | _ : getv (rename pm m) (rename pm ptr) = _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let aget := fresh \"aget\" in\n    first [\n        have aget: getv (rename pm m) (rename pm ptr) = Some (rename pm v);\n        [ by rewrite rename_getv renameK get\n        | rewrite ?rename_dataE ?rename_ptrE in aget ]\n      | failwith \"rename_getv\" ]\n  end.\n\nLtac rename_updv :=\n  match goal with\n  | pm : {fperm name},\n    upd : updv ?m ?ptr ?v = Some ?m' |- _ =>\n    match m with\n    | rename pm ?m'' => fail 1\n    | _ => idtac\n    end;\n    match goal with\n    | _ : updv (rename pm m) (rename pm ptr) _ = _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let aupdm := fresh \"aupdm\" in\n    first [\n        have aupdm := rename_updv pm upd;\n        rewrite ?rename_dataE ?rename_ptrE in aupdm\n      | failwith \"rename_updv\" ]\n  end.\n\nLtac rename_getr :=\n  match goal with\n  | pm : {fperm name},\n    get : getm ?rs ?r = Some ?v |- _ =>\n    match rs with\n    | rename pm ?rs' => fail 1\n    | _ => idtac\n    end;\n    match goal with\n    | _ : getm (rename pm rs) r = _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let agetr := fresh \"agetr\" in\n    first [\n        have agetr: getm (rename pm rs) r = Some (rename pm v);\n        [ by rewrite renamemE renameK get\n        | rewrite ?rename_dataE ?rename_ptrE in agetr ]\n      | failwith \"rename_getr\" ]\n  end.\n\nLtac rename_updr :=\n  match goal with\n  | pm : {fperm name},\n    upd : updm ?rs ?r ?v = Some ?rs' |- _ =>\n    match rs with\n    | rename pm ?rs'' => fail 1\n    | _ => idtac\n    end;\n    match goal with\n    | _ : updm (rename pm rs) r _ = _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let aupdr := fresh \"aupdr\" in\n    first [\n        have aupdr := rename_updr pm upd;\n        rewrite ?rename_dataE ?rename_ptrE in aupdr\n      | failwith \"rename_updr\" ]\n  end.\n\nLtac rename_lift_binop :=\n  match goal with\n  | pm : {fperm name},\n    bo : lift_binop ?f ?v1 ?v2 = Some ?v3 |- _ =>\n    match v1 with\n    | rename pm _ => fail 1\n    | _ => idtac\n    end;\n    match goal with\n    | _ : lift_binop f (rename pm v1) (rename pm v2) = _ |- _ => fail 1\n    | |- _ => idtac\n    end;\n    let abinop := fresh \"abinop\" in\n    first [\n        have abinop := rename_lift_binop pm bo;\n        rewrite ?rename_dataE ?rename_ptrE in abinop\n      | failwith \"rename_lift_binop\" ]\n  end.\n\nLtac apply_rename_everywhere :=\n  first [ rename_getv | rename_updv | rename_getr | rename_updr\n        | rename_lift_binop ].\n\nLtac solve_rename_step_simpl :=\n  solve [ eauto\n        | eauto; simpl; eauto with rename_step_db\n        | eauto; try rewrite !(can_eq (renameK _)); eauto ].\n\nLtac rename_step_simple pm :=\n  intros; exists pm; rewrite !rename_stateE /=;\n  repeat apply_rename_everywhere;\n  rewrite ?rename_dataE /=;\n  s_econstructor solve_rename_step_simpl.\n\nLemma rename_step s s' pm :\n  step s s' ->\n  exists pm', step (rename pm s) (rename pm' s').\nProof.\ncase: s s' /; try rename_step_simple pm.\n- (* Bnz *)\n  move=> m rs p *; exists pm; rewrite !rename_stateE /=.\n  repeat apply_rename_everywhere.\n  rewrite !rename_ptrE /=.\n  (* No idea why unification can't solve this... *)\n  by eapply (@step_bnz _ _ _ _ _ _ (pm p.1, p.2)); eauto.\n- (* Malloc *)\n  move=> m m' rs rs' sz b pc' rs_arg.\n  set s := State _ _ _; set s' := rename pm s; set bs := blocks s.\n  pose b' := fresh (blocks s').\n  pose bs' := supp pm :|: blocks s :|: blocks s'.\n  pose b'' := fresh bs'.\n  pose pm' := fperm2 b' b'' * pm * fperm2 b b''.\n  rewrite /malloc_fun=> - [? ?]; subst b m'.\n  have pm'_s' : s' = rename pm' s.\n    apply/eq_in_rename=> x x_in; rewrite /pm' fpermM /= fpermM /=.\n    rewrite (@fperm2D _ _ _ x); first last.\n    + apply: contraTN x_in=> /eqP -> {x}; rewrite /b''.\n      apply: contra (freshP bs'); rewrite /bs'=> h; rewrite 2!in_fsetU -orbA.\n      by apply/or3P/Or32.\n    + apply: contraTN x_in=> /eqP -> {x}; exact/freshP.\n    rewrite fperm2D //.\n      rewrite /b' /s' /blocks names_rename.\n      by apply/eqP=> e; move: (freshP (pm @: names s)); rewrite -e mem_imfset.\n    rewrite /b''; apply/eqP=> e; move: (freshP bs'); rewrite -e /bs'.\n    by rewrite in_fsetU !negb_or /s' /blocks names_rename mem_imfset // andbF.\n  have pm'_b': pm' (fresh bs) = b'.\n    rewrite /pm' fpermM /= fperm2L fpermM /= (_ : pm b'' = b'') ?fperm2R.\n      done.\n    apply/suppPn/negP=> b''_in; move: (freshP bs').\n    by rewrite /bs' 2!in_fsetU !negb_or b''_in.\n  move=> h1 h2.\n  exists pm'; rewrite pm'_s'; eapply step_malloc; eauto.\n  + by rewrite /s /= renamemE renamewE rs_arg /= renameoE /= rename_valueE.\n  + rewrite /s /= /malloc_fun.\n    rewrite /b' pm'_s' /s /= in pm'_b'; rewrite -pm'_b' -renamenE.\n    rewrite setm_eqvar renamesE (eq_in_map _ id _).1 1?map_id; first by eauto.\n    by move=> x /nseqP [-> _].\n  + exact: (rename_updr _ h1).\n  by rewrite /s /= renamemE renamewE h2.\nQed.\n\nLemma names_state s :\n  names s = names (mem s) :|: names (regs s) :|: names (pc s).\nProof. by []. Qed.\n\nLemma getv_union m m' p v :\n  fdisjoint (names m) (domm m') ->\n  getv m p = Some v ->\n  getv (unionm m' m) p = Some v.\nProof.\nmove=> /(fdisjointP _ _)/(_ p.1) hdis; rewrite /getv unionmE.\ncase e: (m p.1)=> [fr|] //=; case: ifP=> inb // [<-].\nhave hin: p.1 \\in names m.\n  by apply/namesmP/(@PMFreeNamesKey _ _ _ _ p.1 fr)=> //; apply/namesnP.\nby rewrite -mem_domm (negbTE (hdis hin)) inb.\nQed.\nHint Resolve getv_union : separation.\n\nLemma getv_union' m m' p :\n  fdisjoint (names m) (domm m') ->\n  p.1 \\notin domm m' ->\n  getv (unionm m' m) p = getv m p.\nProof.\nby rewrite /getv !unionmE; move=> dis1 /dommPn -> /=.\nQed.\n\nLemma updv_union m m' m'' p v :\n  fdisjoint (names m) (domm m') ->\n  updv m p v = Some m'' ->\n  updv (unionm m' m) p v = Some (unionm m' m'').\nProof.\nmove=> /(fdisjointP _ _)/(_ p.1) hdis; rewrite /updv unionmE.\ncase e: (m p.1)=> [fr|] //=; case: ifP=> inb // [<-].\nhave hin: p.1 \\in names m.\n  by apply/namesmP/(@PMFreeNamesKey _ _ _ _ p.1 fr)=> //; apply/namesnP.\nrewrite -mem_domm (negbTE (hdis hin)) inb; congr some; apply/eq_fmap=> b.\nrewrite !(setmE, unionmE); have [-> {b}|//] := altP (b =P _).\nby rewrite -mem_domm (negbTE (hdis hin)).\nQed.\nHint Resolve updv_union : separation.\n\nLemma updv_union' m m' p v :\n  fdisjoint (names m) (domm m') ->\n  p.1 \\notin domm m' ->\n  updv (unionm m' m) p v =\n  if updv m p v is Some m'' then Some (unionm m' m'')\n  else None.\nProof.\nrewrite /updv unionmE => dis p_m' /=.\nrewrite (dommPn p_m'); case: getm => [fr|] //=.\ncase: ifP=> //= _; congr Some; apply/eq_fmap=> b.\nrewrite !(setmE, unionmE).\nhave [-> {b}|//] := altP (b =P p.1).\nby rewrite (dommPn p_m').\nQed.\n\nLemma free_union' m m' rs r p :\n  fdisjoint (names m) (domm m') ->\n  fdisjoint (names rs) (domm m') ->\n  rs r = Some (VPtr p) ->\n  free_fun (unionm m' m) p.1 =\n  if free_fun m p.1 is Some m'' then Some (unionm m' m'')\n  else None.\nProof.\nrewrite /free_fun !unionmE => dis1 dis2 get_r.\nhave m'_p : p.1 \\notin domm m'.\n  move/fdisjointP: dis2; apply.\n  apply/namesmP/@PMFreeNamesVal; try eassumption.\n  by rewrite names_valueE in_fset1.\nrewrite (dommPn m'_p) /=; case: (m p.1)=> [fr|] //=.\ncongr Some; apply/eq_fmap=> b.\nrewrite !(remmE, unionmE); have [-> {b}|//] := altP (b =P _).\nby rewrite (dommPn m'_p) /=.\nQed.\n\nLemma free_union m m' m'' b :\n  fdisjoint (names m) (domm m') ->\n  free_fun m b = Some m'' ->\n  free_fun (unionm m' m) b = Some (unionm m' m'').\nProof.\nmove=> /(fdisjointP _ _)/(_ b) hdis; rewrite /free_fun unionmE.\ncase e: (m b)=> [fr|] //= [<-].\nhave hin: b \\in names m.\n  by apply/namesmP/(@PMFreeNamesKey _ _ _ _ b fr)=> //; apply/namesnP.\nrewrite -mem_domm (negbTE (hdis hin)); congr some; apply/eq_fmap=> b'.\nrewrite !(remmE, unionmE); have [-> {b'}|//] := altP (b' =P _).\nby rewrite -mem_domm (negbTE (hdis hin)).\nQed.\nHint Resolve free_union : separation.\n\nDefinition add_mem m s :=\n  State (unionm m (mem s)) (regs s) (pc s).\n\nLemma get_reg_disjoint rs r v bs :\n  fdisjoint (names rs) bs ->\n  rs r = Some v ->\n  fdisjoint (names v) bs.\nProof.\nmove=> dis_rs get_rs; apply: fdisjoint_trans; try eassumption.\napply/fsubsetP=> /= n n_in; apply/namesmP.\nby apply: PMFreeNamesVal; eauto.\nQed.\n\nLemma get_mem_disjoint m x v bs :\n  fdisjoint (names m) bs ->\n  getv m x = Some v ->\n  fdisjoint (names v) bs.\nProof.\nrewrite /getv; case e: getm=> [fr|] //=.\ncase: ifP=> // x_fr dis [<-].\nhave {dis} dis : fdisjoint (names fr) bs.\n  apply: fdisjoint_trans; try eassumption.\n  apply/fsubsetP=> /= n n_in; apply/namesmP.\n  by apply: PMFreeNamesVal; eauto.\napply: fdisjoint_trans; try eassumption.\nby eapply nom_finsuppP; finsupp.\nQed.\n\nLemma lift_binop_disjoint f v1 v2 v3 bs :\n  lift_binop f v1 v2 = Some v3 ->\n  fdisjoint (names v1) bs ->\n  fdisjoint (names v2) bs ->\n  fdisjoint (names v3) bs.\nProof.\nmove=> op dis1 dis2.\nsuffices h: fsubset (names (Some v3)) (names v1 :|: names v2).\n  by apply: (fdisjoint_trans h); rewrite fdisjointUl dis1.\nby rewrite -op; eapply nom_finsuppP; finsupp.\nQed.\n\n(* FIXME: These declarations shouldn't be needed *)\nCanonical registers_nominalType := Eval hnf in [nominalType of registers mt].\nCanonical reg_nominalType := Eval hnf in [nominalType of reg mt].\n\nLemma upd_reg_disjoint rs rs' r bs v :\n  updm rs r v = Some rs' ->\n  fdisjoint (names rs) bs ->\n  fdisjoint (names v) bs ->\n  fdisjoint (names rs') bs.\nProof.\nmove=> h; rewrite (updm_set h) {h rs'} => dis_rs dis_v.\nsuffices: fdisjoint (names rs :|: names r :|: names v) bs.\n  apply: fdisjoint_trans; eapply nom_finsuppP.\n  (* FIXME: finsupp used to work here, but it does not anymore... *)\n  move=> s sP.\n  simple eapply nomR_app.\n  simple eapply nomR_app.\n  simple eapply nomR_app.\n  (* Weird: the typeclasses debugger claims that it is using [simple apply\n     setm_eqvar] to solve this goal.  However, adding [simple] below causes the\n     goal to fail.  *)\n  apply setm_eqvar.\n  (* finsupp. (* Does not work... *) *)\n  eapply nomR_nominalJ.\n  finsupp. (* Now it does work *)\n  finsupp.\n  by finsupp.\nby rewrite 2!fdisjointUl dis_rs dis_v namesT fdisjoint0s.\nQed.\n\nLemma upd_mem_disjoint m m' x bs v :\n  updv m x v = Some m' ->\n  fdisjoint (names m) bs ->\n  fdisjoint (names v) bs ->\n  fdisjoint (names m') bs.\nProof.\nrewrite /updv; case e: getm => [fr|] //=.\ncase: ifP=> // x_fr [<-] dis_m dis_v.\nhave dis_x : fdisjoint (names x.1) bs.\n  apply: fdisjoint_trans; try exact: dis_m.\n  apply/fsubsetP=> n n_x.\n  apply/namesmP.\n  by apply:PMFreeNamesKey; eauto.\nhave dis_fr : fdisjoint (names fr) bs.\n  apply: fdisjoint_trans; try exact: dis_m.\n  apply/fsubsetP=> /= n n_in; apply/namesmP.\n  by apply: PMFreeNamesVal; eauto.\nsuffices: fdisjoint (names m :|: names v :|: names x :|: names fr) bs.\n  apply: fdisjoint_trans.\n  eapply nom_finsuppP.\n  (* FIXME: finsupp cannot solve this by itself *)\n  move=> ??; eapply setm_eqvar.\n  eapply nomR_nominalJ. finsupp. finsupp. finsupp.\nrewrite fdisjointUl dis_fr fdisjointUl namespE namesT fsetU0 dis_x.\nby rewrite fdisjointUl dis_v dis_m.\nQed.\n\nLemma free_fun_disjoint m b m' bs :\n  fdisjoint (names m) bs ->\n  fdisjoint (names b) bs ->\n  free_fun m b = Some m' ->\n  fdisjoint (names m') bs.\nProof.\nmove=> dis_m dis_b e; rewrite -[names m']/(names (Some m')) -e.\nhave ?: fsubset (names (free_fun m b)) (names m :|: names b).\n  (* FIXME: finsupp used to solve this until 8.7, but it can't now... *)\n  eapply nom_finsuppP=> ??; eapply free_fun_eqvar; finsupp.\napply: fdisjoint_trans; first by eauto.\nby rewrite fdisjointUl /= dis_m.\nQed.\n\nLtac solve_frame_ok_disjoint :=\n  match goal with\n  | UPD : updm ?rs ?r ?v = Some ?rs',\n    DIS : is_true (fdisjoint (names ?rs) ?bs) |-\n    is_true (fdisjoint (names ?rs') ?bs) =>\n    apply: (upd_reg_disjoint UPD DIS)\n  | DIS : is_true (fdisjoint (names ?rs) ?bs),\n    GET : getm ?rs ?r = Some ?v |-\n    is_true (fdisjoint (names ?v) ?bs) =>\n    apply: (get_reg_disjoint DIS GET)\n  | _ : lift_binop _ _ _ = Some ?v |-\n    is_true (fdisjoint (names ?v) _) =>\n    apply: lift_binop_disjoint; eauto\n  | _ : getv _ _ = Some ?v |-\n    is_true (fdisjoint (names ?v) _) =>\n    apply: get_mem_disjoint; eauto\n  | _ : updv _ _ _ = Some ?m' |-\n    is_true (fdisjoint (names ?m') _) =>\n    apply: upd_mem_disjoint; eauto\n  | _ : free_fun _ _ = Some ?m |-\n    is_true (fdisjoint (names ?m) _) =>\n    apply: free_fun_disjoint; try eassumption\n  | |- is_true (fdisjoint _ _) => exact: fdisjoint0s\n  | _ => done\n  end.\n\nLtac solve_frame_ok_simpl :=\n  intros;\n  match goal with\n  | H : is_true [&& fdisjoint _ _, fdisjoint _ _ & fdisjoint _ _] |- _ =>\n    let dism := fresh \"dism\" in\n    let disrs := fresh \"disrs\" in\n    let disp := fresh \"disp\" in\n    case/and3P: H => [dism disrs disp];\n    exists fperm_one; rewrite rename1; split;\n    [rewrite /add_mem /=; s_econstructor solve [eauto with separation]|\n     rewrite 2!fdisjointUl /= -andbA; apply/and3P;\n     split; repeat solve_frame_ok_disjoint]\n  end.\n\nLemma frame_ok m s s' :\n  fdisjoint (names s) (domm m) ->\n  step s s' ->\n  exists pm,\n    step (add_mem m s) (add_mem m (rename pm s')) /\\\n    fdisjoint (names (rename pm s')) (domm m).\nProof.\nrewrite names_state 2!fdisjointUl -andbA.\nmove=> dis hstep; case: s s' / hstep dis=> /=; try solve_frame_ok_simpl.\n(* Malloc *)\nmove=> m' m'' rs rs' sz b [bpc opc].\nrewrite /blocks /add_mem /=; set s := State _ _ _; set s' := State _ _ _.\nset old := names s; set new := names s'.\nrewrite /malloc_fun=> get_sz [eb em''] upd get_ra; subst b m''.\ncase/and3P=> [dism disr disp]; exists (fperm2 (fresh old) (fresh new)).\nrewrite rename_valueE /= renamenE fperm2D; first last.\n- apply/eqP=> e; move: (freshP new); rewrite -e; move/negP; apply.\n  by rewrite /new; apply/in_blocks; econstructor; eauto.\n- apply/eqP=> e; move: (freshP old); rewrite -e; move/negP; apply.\n  by rewrite /new; apply/in_blocks; econstructor; eauto.\nrewrite setm_eqvar renamenE fperm2L renamesE.\nrewrite (@eq_in_map _ _ _ id _).1; last by move=> x /nseqP [-> ?] //.\nrewrite map_id namesNNE; first last.\n- apply: contra (freshP new); move: (fresh _)=> b.\n  rewrite /new /s' names_state /= => hin.\n  rewrite 2!in_fsetU -orbA; apply/orP; left; apply/namesmP.\n  move: (fdisjointP _ _ dism _ hin)=> nin.\n  case/namesmP: hin=> [b' fr hb' /namesnP e|b' fr hb' hb].\n    subst b'; apply/(@PMFreeNamesKey _ _ _ _ b fr); try by apply/namesnP.\n    by rewrite unionmE -mem_domm (negbTE nin).\n  have b'_in: b' \\in names m'.\n    by apply/namesmP/(@PMFreeNamesKey _ _ _ _ b' fr)=> //; apply/namesnP.\n  apply/(@PMFreeNamesVal _ _ _ _ b' fr)=> //.\n  move: (fdisjointP _ _ dism b' b'_in)=> nin'.\n  by rewrite unionmE -mem_domm (negbTE nin').\n- apply: contra (freshP old); move: (fresh _)=> bs.\n  by rewrite /old /s names_state /= => hin; rewrite 2!in_fsetU hin.\nhave := (rename_updr (fperm2 (fresh old) (fresh new)) upd).\nrewrite rename_valueE /= renamenE fperm2L namesNNE; first last.\n- apply: contra (freshP new); move: (fresh _)=> bs.\n  by rewrite /new /s' names_state /= => hin; rewrite 2!in_fsetU hin orbT.\n- apply: contra (freshP old); move: (fresh _)=> bs.\n  by rewrite /old /s names_state /= => hin; rewrite 2!in_fsetU hin orbT.\nmove=> upd'; split.\n  eapply step_malloc; eauto; rewrite /malloc_fun; congr pair.\n  apply/eq_fmap=> x; rewrite !(setmE, unionmE) -[blocks _]/new.\n  have [->{x}|hneq //] := altP (x =P _).\n  rewrite -mem_domm; suff -> : fresh new \\in domm m = false by [].\n  apply: contraNF (freshP new); move: (fresh _)=> b /dommP [fr Hfr].\n  rewrite /new /s' names_state /= 2!in_fsetU -orbA; apply/orP; left.\n  apply/namesmP/(@PMFreeNamesKey _ _ _ _ b fr); first by rewrite unionmE Hfr.\n  by apply/namesnP.\nrewrite rename_stateE /= (updm_set upd) !setm_eqvar renamenE fperm2L.\nrewrite renameT renamesE map_nseq /= 2!rename_valueE /= renamenE fperm2L.\nset pm := fperm2 _ _.\nhave sub_m'_m: fsubset (domm m') (names m').\n  by apply: fsubsetU; apply/orP; left; rewrite namesfsnE fsubsetxx.\nhave dis_pm : fdisjoint (names s) (supp pm).\n  rewrite names_state fdisjointC /pm /old /s /s' /=.\n  apply: fdisjoint_trans.\n  apply: fsubset_supp_fperm2.\n  rewrite !fdisjointUl fdisjointC fdisjoints1; apply/andP; split.\n    exact: freshP.\n  rewrite fdisjointC fdisjoints1 fdisjoint0s andbT.\n  apply: contra (freshP new); move: (fresh new); apply/fsubsetP.\n  rewrite /new /s' names_state /= 2!fsetU0; apply: fsetSU.\n  rewrite namesm_union_disjoint; first exact: fsubsetUr.\n  rewrite fdisjointC; apply: fdisjoint_trans; eauto.\nhave dis_new : fdisjoint (names (fresh new)) (domm m).\n  rewrite namesnE fdisjointC fdisjoints1.\n  apply: contra (freshP new); move: (fresh new); apply/fsubsetP.\n  rewrite /new /s' names_state /= fsetU0 namesm_union_disjoint.\n    apply: fsubsetU; apply/orP; left.\n    apply: fsubsetU; apply/orP; left.\n    by apply: fsubsetU; apply/orP; left; rewrite namesfsnE fsubsetxx.\n  rewrite fdisjointC; apply: fdisjoint_trans; eauto.\nhave -> : rename pm m' = m'.\n  apply: renameJ.\n  rewrite fdisjointC.\n  apply: fdisjoint_trans; try eassumption.\n  by rewrite /s names_state /= fsetU0 fsubsetUl.\nhave dis_rs: fdisjoint (names rs) (supp pm).\n  apply: fdisjoint_trans; try eassumption.\n  by rewrite /s names_state /= fsetU0 fsubsetUr.\nhave -> : rename pm rs = rs.\n  apply: renameJ.\n  by rewrite fdisjointC.\nhave -> : rename pm (VPtr (bpc, opc)) = VPtr (bpc, opc).\n  apply: renameJ.\n  rewrite fdisjointC.\n  by solve_frame_ok_disjoint.\nrewrite names_state /= 2!fdisjointUl -andbA; apply/and3P; split.\n(* FIXME: The generalizations below should not be needed to prove the set inclusions *)\n- have ?: fsubset (names (setm m' (fresh new) (nseq sz (VData 0%w))))\n                  (names m' :|: names (fresh new) :|: names (@VData mt 0%w)).\n    move: (fresh _) (VData _)=> ??.\n    eapply nom_finsuppP=> ??; eapply setm_eqvar; finsupp.\n  apply: fdisjoint_trans; first by eauto.\n  by rewrite 2!fdisjointUl dism dis_new /= fdisjoint0s.\n- have ?: fsubset (names (setm rs syscall_ret (@VPtr mt (fresh new, 0%w))))\n                  (names rs :|: names syscall_ret :|: names (@VPtr mt (fresh new, 0%w))).\n    move: syscall_ret (VPtr _) => ??.\n    eapply nom_finsuppP=> ??; eapply setm_eqvar; finsupp.\n  apply: fdisjoint_trans; first by eauto.\n  by rewrite 2!fdisjointUl disr fdisjoint0s /= fdisjointUl fdisjoint0s dis_new.\nby solve_frame_ok_disjoint.\n(* Free *)\napply: (@fdisjoint_trans _ _ (names (VPtr ptr))).\n  exact: fsubsetUl.\nsolve_frame_ok_disjoint.\n(* Last *)\nexact: (get_reg_disjoint disrs PTR).\nQed.\n\nLemma not_domm_rs rs r p m' :\n  fdisjoint (names rs) (domm m') ->\n  rs r = Some (VPtr p) ->\n  p.1 \\notin domm m'.\nProof.\nmove/fdisjointP=> dis get_r; apply: dis.\napply/namesmP/@PMFreeNamesVal; try eassumption.\nby rewrite names_valueE in_fset1.\nQed.\n\nLemma not_domm_pc p m' :\n  fdisjoint (names (VPtr p)) (domm m') ->\n  p.1 \\notin domm m'.\nProof. by rewrite names_valueE fdisjointC fdisjoints1. Qed.\n\nLtac solve_frame_error_step :=\n  match goal with\n  | e : (if ?pc == ?rhs then _ else _) = _ |- _ =>\n    move: e; have [->|?] := altP (pc =P rhs); move=> e //=\n  | |- context[addr _ == addr _] =>\n    rewrite (inj_eq (@uniq_addr _ addrs)) //=\n  | e : match ?x with _ => _ end = None |- _ => destruct x\n  | e : obind _ ?x = _ |- obind _ ?y = _ =>\n    match y with\n    | context[x] => destruct x eqn:?; simpl in * => //\n    end\n  | e : context[if isSome (getm ?rs ?r) then _ else _] |- _ =>\n    let E := fresh \"E\" in\n    case E: (getm rs r) e => [?|] //= e\n  | e : ?x = _ |- context[?x] => rewrite e //=\n  | |- context[free_fun (unionm _ _) _] =>\n    erewrite free_union'; try eassumption; simpl in *\n  | |- context[getv (unionm _ _) _] =>\n    erewrite getv_union'; try eassumption; simpl in *\n  | |- context[updv (unionm _ _) _ _] =>\n    erewrite updv_union'; try eassumption; simpl in *\n  | dis : is_true (fdisjoint (names ?rs) (domm ?m')),\n    get_r : getm ?rs _ = Some (VPtr ?p) |-\n    is_true (?p.1 \\notin domm ?m') =>\n    apply: not_domm_rs dis get_r\n  | dis : is_true (fdisjoint (names (VPtr ?p)) (domm ?m')) |-\n    is_true (?p.1 \\notin domm ?m') =>\n    exact: not_domm_pc dis\n  | |- _ => single_match_inv; subst=> //\n  end.\n\nLtac solve_frame_error :=\n  unfold updm in *; repeat solve_frame_error_step.\n\nLemma frame_error m s :\n  fdisjoint (names s) (domm m) ->\n  astepf s = None ->\n  astepf (add_mem m s) = None.\nProof.\ncase: s m => m rs pc m'.\nrewrite names_state /= 2!fdisjointUl -andbA /AbstractE.step /add_mem.\nby case/and3P=> dis_m dis_rs dis_pc *; solve_frame_error.\nQed.\n\nLemma noninterference s pm m1 m2 n :\n  fdisjoint (names s) (domm m1) ->\n  fdisjoint (names (rename pm s)) (domm m2) ->\n  match stepn astepf n (add_mem m1 s),\n        stepn astepf n (add_mem m2 (rename pm s)) with\n  | Some s1, Some s2 =>\n    exists pm' s',\n      [/\\ s1 = add_mem m1 s',\n          fdisjoint (names s') (domm m1),\n          s2 = add_mem m2 (rename pm' s') &\n          fdisjoint (names (rename pm' s')) (domm m2)]\n  | None, None => True\n  | _, _ => False\n  end.\nProof.\nelim: n pm s => [|n IH] pm s.\n  by move=> ?? /=; exists pm, s; split.\nmove=> dis1 dis2; rewrite (lock astepf) /= -lock.\ncase step0: (astepf s)=> [s'|].\n  move/AbstractE.stepP in step0.\n  have [pm1 [/AbstractE.stepP step1 dis1']] := frame_ok dis1 step0.\n  have [pm' step2] := rename_step pm step0.\n  have [pm2 [/AbstractE.stepP step2' dis2']] := frame_ok dis2 step2.\n  rewrite step1 step2'.\n  move/(_ (pm2 * pm' * pm1^-1) _ dis1'): IH.\n  rewrite renameA fperm_mulsKV -renameA.\n  by move/(_ dis2').\nrewrite frame_error //.\ncase step0': (astepf (rename pm s))=> [s'|].\n  move/AbstractE.stepP in step0'.\n  have [pm' {step0'} /AbstractE.stepP] := rename_step pm^-1 step0'.\n  by rewrite renameK step0.\nby rewrite frame_error.\nQed.\n\nEnd MemorySafety.\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/memory_safety/propertyA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.17150825491554386}}
{"text": "(* Assume insertion Delay: inserting Assume instruction *)\n(* This versions tries to insert an Assume after a Condition Instruction *)\n(* This showcases the possible separation of Framestate and Assume *)\n(* This is a pass of the dynamic optimizer *)\n\nRequire Export List.\nRequire Export Coqlib.\nRequire Export Maps.\nRequire Export specIR.\nRequire Export assume_insertion.\n\n(* Checks that a label is not in a list *)\nFixpoint not_in_list (l:list label) (lbl:label): bool :=\n  match l with\n  | nil => true\n  | lbl'::l' =>\n    match (Pos.eqb lbl' lbl) with\n    | true => false\n    | false => not_in_list l' lbl\n    end\n  end.\n\n(* Check that an instruction has for only predecessor some label *)\nDefinition only_pred (c:code) (next:label) (pred:label): bool :=\n  PTree.fold\n    (fun b lbl i =>\n       andb b\n            (match (Pos.eqb lbl pred) with\n             | true => true (* at the predecessor, we can point to next *)\n             | false => not_in_list (instr_succ i) next (* elsewehere, next should not be a successor *)\n             end))\n    c true.\n\n\n(* Verify that the assume can be inserted after a Cond Instruction *)\nDefinition validator (v:version) (fs_lbl: label) (guard:list expr) (params:list reg): res unit :=\n  match ((ver_code v)#fs_lbl) with\n  | Some (Framestate _ _ _ next) =>\n    match ((ver_code v)#next) with\n    | Some (Cond _ iftrue _) =>\n      match (only_pred (ver_code v) next fs_lbl) with\n      | true => \n        match (Pos.eqb next (ver_entry v)) with\n        | false =>\n          do abs <- try_op (defined_regs_analysis (ver_code v) params (ver_entry v)) \"Def_regs analysis failed\";\n            do def_regs <- OK(def_absstate_get next abs);\n            match def_regs with\n            | DefFlatRegset.Inj def =>\n              match (check_guard guard def) with\n              | true => OK tt\n              | false => Error \"The guard might evaluate to an error\"\n              end\n            | _ => Error \"The analysis couldn't get the exact set of defined registers\"\n            end\n        | true => Error \"The Condition is the entry of the version\"\n        end\n      | false => Error \"The Framestate instruction does not dominate the Condition\"\n      end\n    | _ => Error \"No Condition instruction after the Framestate\"\n    end\n  | _ => Error \"Not pointing to a valid Framestate\"\n  end.\n\n(* Returns the version where the Assume has been inserted *)\nDefinition insert_assume_version (v:version) (fid:fun_id) (guard:list expr) (fsl:label) (params:list reg): res version :=\n  do code <- OK(ver_code v);\n    do _ <- validator v fsl guard params; (* validating that the assume can be inserted *)\n    match code # fsl with\n    | Some (Framestate tgt vm sl next) =>\n      match code # next with\n      | Some (Cond condexpr iftrue iffalse) =>\n        do freshlbl <- OK (fresh_label (Pos.succ next) code);\n        do instr <- try_op (code # iftrue) \"Next Label is not used in the function\";\n          do update_cond <- OK (code # next <- (Cond condexpr freshlbl iffalse));\n          do new_code <- OK (update_cond # freshlbl <- (Assume guard tgt vm sl iftrue));\n          (* in the new assume, the deopt target, the varmap and the synth list are copied from the framestate *)\n          OK (mk_version new_code (ver_entry v))\n      | _ => Error \"The instruction after the Framestate is not a Cond Instruction\"\n      end\n    | _ => Error \"Not pointing to a valid Framestate\"\n    end.\n\n(* The optimization pass *)\nDefinition insert_assume_delay (fid: fun_id) (guard:list expr) (fs_lbl: label) (p:program): res program :=\n  do f <- try_op (find_function fid p) \"Function to optimize not found\";\n    do v <- OK(current_version f); (* the optimized code if it exists, the base version otherwise *)\n    do newv <- insert_assume_version v fid guard fs_lbl (fn_params f);\n    do new_program <- OK (set_version p fid newv);\n    OK (new_program).\n    \n\nDefinition safe_insert_assume_delay (p:program) (fid:fun_id) (guard:list expr) (fs_lbl: label): program :=\n  safe_res (insert_assume_delay fid guard fs_lbl) p.\n", "meta": {"author": "Aurele-Barriere", "repo": "CoreJIT", "sha": "8740d4149be649d0746d9f0d2d759b387a8f3246", "save_path": "github-repos/coq/Aurele-Barriere-CoreJIT", "path": "github-repos/coq/Aurele-Barriere-CoreJIT/CoreJIT-8740d4149be649d0746d9f0d2d759b387a8f3246/src/coqjit/assume_insertion_delay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1715082529144317}}
{"text": "Require Import Bedrock PreAutoSep.\n\n\nImport DefineStructured.\n\nSection Wrap.\n  Variable imports : LabelMap.t assert.\n  Hypothesis imports_global : importsGlobal imports.\n  Variable modName : string.\n\n  Variable body : cmd imports modName.\n  Variable postcondition : assert -> assert.\n  Variable verifCond : assert -> list Prop.\n\n  Hypothesis postcondition_ok : forall pre specs x,\n    vcs (verifCond pre)\n    -> interp specs ((body pre).(Postcondition) x)\n    -> interp specs (postcondition pre x).\n\n  Hypothesis verifCond_ok : forall pre,\n    vcs (verifCond pre)\n    -> vcs (body pre).(VerifCond).\n\n  Hint Extern 1 (_ < _)%N => nomega.\n  Hint Extern 1 (not (@eq LabelMap.key _ _)) => lomega.\n  Hint Extern 1 (@eq LabelMap.key _ _ -> False) => lomega.\n  Hint Extern 1 (LabelMap.MapsTo _ _ _) => apply imps_exit.\n\n  Transparent evalInstrs.\n\n  Definition Wrap : cmd imports modName.\n    red; refine (fun pre =>\n      let cout := body pre in\n      {|\n        Postcondition := postcondition pre;\n        VerifCond := verifCond pre;\n        Generate := fun Base Exit =>\n        let cg := cout.(Generate) (Nsucc Base) Base in\n          {|\n            Entry := Nsucc cg.(Entry);\n            Blocks := (cout.(Postcondition),\n              (nil, Uncond (RvLabel (modName, Local Exit))))\n            :: cg.(Blocks)\n          |}\n      |}); abstract (struct;\n        match goal with\n          | [ H : forall k' : LabelMap.key, _\n              |- context[Labels _ ?k]  ] =>\n            edestruct (H k) as [ ? [ ] ]; eauto;\n              match goal with\n                | [ H : _ = _ |- _ ] => solve [ rewrite H; eauto 6 ]\n              end\n          | [ |- context[LabelMap.add (_, Local ?Base) _ _] ] =>\n            assert (Base < N.succ Base)%N by nomega;\n              match goal with\n                | [ H : vcs _ |- _ ] => apply verifCond_ok in H\n              end; intuition struct\n        end).\n  Defined.\n\nEnd Wrap.\n\n\n(** * A simpler combinator, for [chunk]-level programs with explicit invariants ahoy *)\n\nSection WrapC.\n  Variable body : chunk.\n  \n  Definition assertC := bool\n    -> (W -> W)\n    -> list string\n    -> nat\n    -> assert.\n\n  Variables precondition postcondition : assertC.\n  Variable verifCond : LabelMap.t assert -> list string -> nat -> list Prop.\n\n  Hypothesis postcondition_covered : forall im mn H ns res pre specs st,\n    (forall specs st, interp specs (pre st)\n      -> interp specs (precondition true (fun x => x) ns res st))\n    -> vcs (verifCond im ns res)\n    -> interp specs ((toCmd body (im := im) mn H ns res pre).(Postcondition) st)\n    -> interp specs (postcondition true (fun x => x) ns res st).\n\n  Hypothesis verifCond_covered : forall im mn H ns res pre,\n    (forall specs st, interp specs (pre st) -> interp specs (precondition true (fun x => x) ns res st))\n    -> vcs (verifCond im ns res)\n    -> vcs ((toCmd body (im := im) mn H ns res pre).(VerifCond)).\n\n  Definition WrapC : chunk.\n    red; refine (fun ns res => Structured nil\n      (fun im mn H => Wrap im H mn (toCmd body mn H ns res)\n        (fun _ => postcondition true (fun x => x) ns res)\n        (fun pre => (forall specs st, interp specs (pre st) -> interp specs (precondition true (fun x => x) ns res st)) :: verifCond im ns res)\n        _ _)); abstract struct.\n  Defined.\nEnd WrapC.\n\n\n(** * Some tactics useful in clients of [Wrap] *)\n\nRequire Import Locals.\n\nLemma four_plus_variablePosition : forall x ns',\n  ~In \"rp\" ns'\n  -> In x ns'\n  -> 4 + variablePosition ns' x = variablePosition (\"rp\" :: ns') x.\n  unfold variablePosition at 2; intros.\n  destruct (string_dec \"rp\" x); auto; subst; tauto.\nQed.\n\nLtac prep_locals :=\n  unfold variableSlot in *; repeat rewrite four_plus_variablePosition in * by assumption;\n    repeat match goal with\n             | [ H : In ?X ?ls |- _ ] =>\n               match ls with\n                 | \"rp\" :: _ => fail 1\n                 | _ =>\n                   match goal with\n                     | [ _ : In X (\"rp\" :: ls) |- _ ] => fail 1\n                     | _ => assert (In X (\"rp\" :: ls)) by (simpl; tauto)\n                   end\n               end\n           end.\n\nLtac clear_fancy := repeat match goal with\n                             | [ H : importsGlobal _ |- _ ] => clear H\n                             | [ H : vcs _ |- _ ] => clear H\n                           end.\n\nLtac wrap0 :=\n  intros;\n    repeat match goal with\n             | [ H : vcs nil |- _ ] => clear H\n             | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; intros; subst\n             | [ H : vcs (_ ++ _) |- _ ] => specialize (vcs_app_bwd1 _ _ H);\n               specialize (vcs_app_bwd2 _ _ H); clear H; intros\n           end; simpl;\n    repeat match goal with\n             | [ |- vcs nil ] => constructor\n             | [ |- vcs (_ :: _) ] => constructor\n             | [ |- vcs (_ ++ _) ] => apply vcs_app_fwd\n           end; propxFo;\n    try match goal with\n          | [ H : forall stn : settings, _, H' : interp _ _ |- _ ] =>\n            specialize (H _ _ _ H')\n        end.\n\nLtac wrap1 := prep_locals; auto; clear_fancy.\n\nLtac app := match goal with\n              | [ H : _, H' : ?P |- _ ] => apply H in H';\n                try match goal with\n                      | [ H' : P |- _ ] => clear H'\n                    end\n            end.\n\nLtac handle_IH :=\n  try match goal with\n        | [ H : importsGlobal _ |- _ ] =>\n          match goal with\n            | [ IH : context[H] |- _ ] => clear H IH\n            | _ => clear H\n          end\n      end.\n\nLtac simp := post; unfold lvalIn, regInL, immInR in *; clear_fancy; prep_locals.\n\nLtac finish := descend; repeat (step auto_ext; descend); descend; step auto_ext.\n\n\n(** * Useful facts about instruction sequences not changing parts of machine state *)\n\nFixpoint scratchOnly (is : list instr) : Prop :=\n  match is with\n    | nil => True\n    | Assign (LvReg r) _ :: is' => r <> Sp /\\ scratchOnly is'\n    | Binop (LvReg r) _ _ _ :: is' => r <> Sp /\\ scratchOnly is'\n    | _ => False\n  end.\n\nLtac matcher := repeat match goal with\n                         | [ _ : context[match ?E with None => _ | _ => _ end] |- _ ] =>\n                           match E with\n                             | context[match _ with None => _ | _ => _ end] => fail 1\n                             | _ => destruct E; try discriminate\n                           end\n                         | [ |- context[match ?E with None => _ | _ => _ end] ] =>\n                           match E with\n                             | context[match _ with None => _ | _ => _ end] => fail 1\n                             | _ => destruct E; try discriminate\n                           end\n                       end.\n\nTransparent evalInstrs.\n\nTheorem scratchOnlySp : forall stn st' is st,\n  scratchOnly is\n  -> evalInstrs stn st is = Some st'\n  -> Regs st' Sp = Regs st Sp.\n  induction is as [ | [ [ ] | [ ] ] ]; simpl; intuition; matcher; try congruence;\n    erewrite IHis by eassumption; apply rupd_ne; auto.\nQed.\n\nTheorem scratchOnlyMem : forall stn st' is st,\n  scratchOnly is\n  -> evalInstrs stn st is = Some st'\n  -> Mem st' = Mem st.\n  induction is as [ | [ [ ] | [ ] ] ]; simpl; intuition; matcher; try congruence;\n    erewrite IHis by eassumption; reflexivity.\nQed.\n\nTheorem sepFormula_Mem : forall specs stn st st' P,\n  interp specs (![P] (stn, st))\n  -> Mem st' = Mem st\n  -> interp specs (![P] (stn, st')).\n  rewrite sepFormula_eq; unfold sepFormula_def; simpl; intros; congruence.\nQed.\n\nFixpoint spless (is : list instr) : Prop :=\n  match is with\n    | nil => True\n    | Assign (LvReg r) _ :: is' => r <> Sp /\\ spless is'\n    | Binop (LvReg r) _ _ _ :: is' => r <> Sp /\\ spless is'\n    | _ :: is' => spless is'\n  end.\n\nTheorem splessSp : forall stn st' is st,\n  spless is\n  -> evalInstrs stn st is = Some st'\n  -> Regs st' Sp = Regs st Sp.\n  induction is as [ | [ [ ] | [ ] ] ]; simpl; intuition; matcher; try congruence;\n    erewrite IHis by eassumption; simpl; try rewrite rupd_ne by auto; auto.\nQed.\n\nTheorem spless_app : forall is1 is2,\n  spless is1\n  -> spless is2\n  -> spless (is1 ++ is2).\n  induction is1 as [ | [ ] ]; simpl; intuition;\n    destruct l; intuition.\nQed.\n\nLemma evalInstrs_app_fwd_None : forall stn is2 is1 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\nLemma evalInstrs_app_fwd : forall stn is2 st' is1 st,\n  evalInstrs stn st (is1 ++ is2) = Some st'\n  -> exists st'', evalInstrs stn st is1 = Some st''\n    /\\ evalInstrs stn st'' is2 = Some st'.\n  induction is1; simpl; intuition eauto.\n  destruct (evalInstr stn st a); eauto; discriminate.\nQed.\n\nLemma evalInstr_evalInstrs : forall stn st i,\n  evalInstr stn st i = evalInstrs stn st (i :: nil).\n  simpl; intros; destruct (evalInstr stn st i); auto.\nQed.\n\nLemma evalAssign_rhs : forall stn st lv rv rv',\n  evalRvalue stn st rv = evalRvalue stn st rv'\n  -> evalInstr stn st (Assign lv rv) = evalInstr stn st (Assign lv rv').\n  simpl; intros.\n  rewrite H; reflexivity.\nQed.\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/Wrap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1715082529144317}}
{"text": "Require Import VerdiRaft.Raft.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.RefinementCommonTheorems.\n\nRequire Import VerdiRaft.CandidateEntriesInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.CroniesTermInterface.\nRequire Import VerdiRaft.LeaderLogsTermSanityInterface.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nRequire Import VerdiRaft.LeaderLogsCandidateEntriesInterface.\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  Context {rri : raft_refinement_interface}.\n  Context {cci : cronies_correct_interface}.\n  Context {cti : cronies_term_interface}.\n  Context {cei : candidate_entries_interface}.\n  Context {lltsi : leaderLogs_term_sanity_interface}.\n\n  Ltac start :=\n    red; unfold leaderLogs_candidateEntries; simpl; intros.\n\n  Lemma leaderLogs_candidateEntries_init :\n    refined_raft_net_invariant_init leaderLogs_candidateEntries.\n  Proof using. \n    start. contradiction.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_client_request :\n    refined_raft_net_invariant_client_request leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; simpl in *.\n      - find_rewrite_lem update_elections_data_client_request_leaderLogs. eauto.\n      - eauto. }\n    eapply candidateEntries_same.\n    - eauto.\n    - intros. update_destruct; rewrite_update; [|auto].\n      simpl. subst. eauto using update_elections_data_client_request_cronies.\n    - intros. update_destruct; rewrite_update; [|auto].\n      simpl. subst. find_apply_lem_hyp handleClientRequest_type. intuition.\n    - intros. update_destruct; rewrite_update; [|auto].\n      simpl. subst. find_apply_lem_hyp handleClientRequest_type. intuition.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_timeout :\n    refined_raft_net_invariant_timeout leaderLogs_candidateEntries.\n  Proof using cti. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; simpl in *.\n      - find_rewrite_lem update_elections_data_timeout_leaderLogs. eauto.\n      - eauto. }\n    unfold candidateEntries in *.\n    break_exists; break_and.\n    exists x.\n    update_destruct; rewrite_update; simpl in *; [|auto].\n    subst. split.\n    - assert (H100 := update_elections_data_timeout_cronies x (nwState net x) (eTerm e)).\n      intuition.\n      + find_rewrite. auto.\n      + exfalso.\n        find_apply_lem_hyp wonElection_exists_voter.\n        break_exists.\n        find_apply_lem_hyp in_dedup_was_in.\n        intro_refined_invariant cronies_term_invariant.\n        eapply_prop_hyp cronies_term In.\n        simpl in *.\n        lia.\n    - find_apply_lem_hyp handleTimeout_type_strong.\n      break_or_hyp; break_and.\n      + repeat find_rewrite. auto.\n      + intros. find_rewrite.\n        exfalso.\n        find_apply_lem_hyp wonElection_exists_voter.\n        break_exists.\n        find_apply_lem_hyp in_dedup_was_in.\n        intro_refined_invariant cronies_term_invariant.\n        eapply_prop_hyp cronies_term In.\n        simpl in *.\n        lia.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_append_entries :\n    refined_raft_net_invariant_append_entries leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    update_destruct; rewrite_update.\n    - simpl in *.\n      find_rewrite_lem update_elections_data_appendEntries_leaderLogs.\n      assert (candidateEntries e (nwState net)) by eauto.\n      unfold candidateEntries in *.\n      break_exists. break_and.\n      exists x.\n      update_destruct; rewrite_update; [|auto].\n      simpl. subst. rewrite update_elections_data_appendEntries_cronies.\n      split; [auto|].\n      find_apply_lem_hyp handleAppendEntries_type_term.\n      break_or_hyp; break_and.\n      * repeat find_rewrite. auto.\n      * unfold not. intros. find_rewrite. discriminate.\n    - assert (candidateEntries e (nwState net)) by eauto.\n      unfold candidateEntries in *.\n      break_exists. break_and.\n      exists x.\n      update_destruct; rewrite_update; [|auto].\n      simpl. subst. rewrite update_elections_data_appendEntries_cronies.\n      split; [auto|].\n      find_apply_lem_hyp handleAppendEntries_type_term.\n      break_or_hyp; break_and.\n      * repeat find_rewrite. auto.\n      * unfold not. intros. find_rewrite. discriminate.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; eauto. }\n    unfold candidateEntries in *.\n    break_exists. break_and.\n    exists x.\n    update_destruct; rewrite_update; simpl; [|auto].\n    subst. split; [auto|].\n    find_apply_lem_hyp handleAppendEntriesReply_type_term.\n    break_or_hyp; break_and.\n    - repeat find_rewrite. auto.\n    - unfold not. intros. find_rewrite. discriminate.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_request_vote :\n    refined_raft_net_invariant_request_vote leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; simpl in *.\n      - find_rewrite_lem leaderLogs_update_elections_data_requestVote. eauto.\n      - eauto. }\n    unfold candidateEntries in *.\n    break_exists. break_and.\n    exists x.\n    update_destruct; rewrite_update; simpl; [|auto].\n    subst. split.\n    - rewrite update_elections_data_requestVote_cronies. auto.\n    - find_apply_lem_hyp handleRequestVote_type_term.\n      break_or_hyp; break_and.\n      + repeat find_rewrite. auto.\n      + unfold not. intros. find_rewrite. discriminate.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply leaderLogs_candidateEntries.\n  Proof using cei cci. \n    start.\n    intro_refined_invariant candidate_entries_invariant.\n    eapply candidateEntries_ext; eauto.\n    subst.\n    repeat find_higher_order_rewrite.\n    find_rewrite_lem update_fun_comm. simpl in *.\n    update_destruct; rewrite_update.\n    - find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n      intuition.\n      + eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n      + subst. find_erewrite_lem handleRequestVoteReply_log.\n        eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n    - eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_do_leader :\n    refined_raft_net_invariant_do_leader leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; simpl in *.\n      - assert (In (t, ll) (leaderLogs (fst (nwState net h)))) by (repeat find_rewrite; eauto). eauto.\n      - eauto. }\n    unfold candidateEntries in *.\n    break_exists; break_and.\n    exists x.\n    update_destruct; rewrite_update; [|auto].\n    simpl. split.\n    - assert (gd = fst (nwState net h)). { repeat find_rewrite. simpl. auto. }\n      subst. auto.\n    - find_apply_lem_hyp doLeader_type.\n      break_and. find_rewrite. repeat find_rewrite.\n      auto.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_do_generic_server :\n    refined_raft_net_invariant_do_generic_server leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update; simpl in *.\n      - assert (In (t, ll) (leaderLogs (fst (nwState net h)))) by (repeat find_rewrite; eauto). eauto.\n      - eauto. }\n    unfold candidateEntries in *.\n    break_exists; break_and.\n    exists x.\n    update_destruct; rewrite_update; [|auto].\n    simpl. split.\n    - assert (gd = fst (nwState net h)). { repeat find_rewrite. simpl. auto. }\n      subst. auto.\n    - find_apply_lem_hyp doGenericServer_type.\n      break_and. find_rewrite. repeat find_rewrite.\n      auto.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_reverse_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)) by eauto.\n    unfold candidateEntries in *.\n    break_exists. break_and.\n    exists x.\n    repeat find_reverse_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_reboot :\n    refined_raft_net_invariant_reboot leaderLogs_candidateEntries.\n  Proof using. \n    start.\n    eapply candidateEntries_ext; eauto.\n    repeat find_higher_order_rewrite.\n    assert (candidateEntries e (nwState net)).\n    { update_destruct; rewrite_update.\n      - assert (gd = fst (nwState net h)). { repeat find_rewrite. simpl. auto. }\n        subst. eauto.\n      - eauto. }\n    unfold candidateEntries in *.\n    break_exists; break_and.\n    exists x.\n    update_destruct; rewrite_update; [|auto].\n    simpl. split.\n    - assert (gd = fst (nwState net h)). { repeat find_rewrite. simpl. auto. }\n      subst. auto.\n    - unfold not. intros. subst. unfold reboot in *. simpl in *. discriminate.\n  Qed.\n\n  Lemma leaderLogs_candidateEntries_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leaderLogs_candidateEntries net.\n  Proof using cei cti cci rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply leaderLogs_candidateEntries_init.\n    - apply leaderLogs_candidateEntries_client_request.\n    - apply leaderLogs_candidateEntries_timeout.\n    - apply leaderLogs_candidateEntries_append_entries.\n    - apply leaderLogs_candidateEntries_append_entries_reply.\n    - apply leaderLogs_candidateEntries_request_vote.\n    - apply leaderLogs_candidateEntries_request_vote_reply.\n    - apply leaderLogs_candidateEntries_do_leader.\n    - apply leaderLogs_candidateEntries_do_generic_server.\n    - apply leaderLogs_candidateEntries_state_same_packet_subset.\n    - apply leaderLogs_candidateEntries_reboot.\n  Qed.\n\n\n  Instance llcei : leaderLogs_candidate_entries_interface.\n  Proof.\n    constructor. exact leaderLogs_candidateEntries_invariant.\n  Qed.\nEnd CandidateEntriesInterface.\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/LeaderLogsCandidateEntriesProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.1712149796385971}}
{"text": "From iris.bi Require Export monpred.\nFrom iris.bi Require Import plainly.\nFrom iris.proofmode Require Import proofmode classes_make modality_instances.\nFrom iris.prelude Require Import options.\n\nClass MakeMonPredAt {I : biIndex} {PROP : bi} (i : I)\n      (P : monPred I PROP) (\ud835\udcdf : PROP) :=\n  make_monPred_at : P i \u22a3\u22a2 \ud835\udcdf.\nGlobal Arguments MakeMonPredAt {_ _} _ _%I _%I.\n(** Since [MakeMonPredAt] is used by [AsEmpValid] to import lemmas into the\nproof mode, the index [I] and BI [PROP] often contain evars. Hence, it is\nimportant to use the mode [!] also for the first two arguments. *)\nGlobal Hint Mode MakeMonPredAt ! ! - ! - : typeclass_instances.\n\nClass IsBiIndexRel {I : biIndex} (i j : I) := is_bi_index_rel : i \u2291 j.\nGlobal Hint Mode IsBiIndexRel + - - : typeclass_instances.\nGlobal Instance is_bi_index_rel_refl {I : biIndex} (i : I) : IsBiIndexRel i i | 0.\nProof. by rewrite /IsBiIndexRel. Qed.\nGlobal Hint Extern 1 (IsBiIndexRel _ _) => unfold IsBiIndexRel; assumption\n            : typeclass_instances.\n\n(** Frame [\ud835\udce1] into the goal [monPred_at P i] and determine the remainder [\ud835\udce0].\n    Used when framing encounters a monPred_at in the goal. *)\nClass FrameMonPredAt {I : biIndex} {PROP : bi} (p : bool) (i : I)\n      (\ud835\udce1 : PROP) (P : monPred I PROP) (\ud835\udce0 : PROP) :=\n  frame_monPred_at : \u25a1?p \ud835\udce1 \u2217 \ud835\udce0 -\u2217 P i.\nGlobal Arguments FrameMonPredAt {_ _} _ _ _%I _%I _%I.\nGlobal Hint Mode FrameMonPredAt + + + - ! ! - : typeclass_instances.\n\nSection modalities.\n  Context {I : biIndex} {PROP : bi}.\n\n  Lemma modality_objectively_mixin :\n    modality_mixin (@monPred_objectively I PROP)\n      (MIEnvFilter Objective) (MIEnvFilter Objective).\n  Proof.\n    split; simpl; split_and?; intros;\n      try select (TCDiag _ _ _) (fun H => destruct H);\n      eauto using bi.equiv_entails_1_2, objective_objectively,\n        monPred_objectively_mono, monPred_objectively_and,\n        monPred_objectively_sep_2 with typeclass_instances.\n  Qed.\n  Definition modality_objectively :=\n    Modality _ modality_objectively_mixin.\nEnd modalities.\n\nSection bi.\nContext {I : biIndex} {PROP : bi}.\nLocal Notation monPredI := (monPredI I PROP).\nLocal Notation monPred := (monPred I PROP).\nLocal Notation MakeMonPredAt := (@MakeMonPredAt I PROP).\nImplicit Types P Q R : monPred.\nImplicit Types \ud835\udcdf \ud835\udce0 \ud835\udce1 : PROP.\nImplicit Types \u03c6 : Prop.\nImplicit Types i j : I.\n\nGlobal Instance from_modal_objectively P :\n  FromModal True modality_objectively (<obj> P) (<obj> P) P | 1.\nProof. by rewrite /FromModal. Qed.\nGlobal Instance from_modal_subjectively P :\n  FromModal True modality_id (<subj> P) (<subj> P) P | 1.\nProof. by rewrite /FromModal /= -monPred_subjectively_intro. Qed.\n\nGlobal Instance from_modal_affinely_monPred_at \u03c6 `(sel : A) P Q \ud835\udce0 i :\n  FromModal \u03c6 modality_affinely sel P Q \u2192\n  MakeMonPredAt i Q \ud835\udce0 \u2192\n  FromModal \u03c6 modality_affinely sel (P i) \ud835\udce0 | 0.\nProof.\n  rewrite /FromModal /MakeMonPredAt /==> HPQ <- ?.\n  by rewrite -HPQ // monPred_at_affinely.\nQed.\nGlobal Instance from_modal_persistently_monPred_at \u03c6 `(sel : A) P Q \ud835\udce0 i :\n  FromModal \u03c6 modality_persistently sel P Q \u2192\n  MakeMonPredAt i Q \ud835\udce0 \u2192\n  FromModal \u03c6 modality_persistently sel (P i) \ud835\udce0 | 0.\nProof.\n  rewrite /FromModal /MakeMonPredAt /==> HPQ <- ?.\n  by rewrite -HPQ // monPred_at_persistently.\nQed.\nGlobal Instance from_modal_intuitionistically_monPred_at \u03c6 `(sel : A) P Q \ud835\udce0 i :\n  FromModal \u03c6 modality_intuitionistically sel P Q \u2192\n  MakeMonPredAt i Q \ud835\udce0 \u2192\n  FromModal \u03c6 modality_intuitionistically sel (P i) \ud835\udce0 | 0.\nProof.\n  rewrite /FromModal /MakeMonPredAt /==> HPQ <- ?.\n  by rewrite -HPQ // monPred_at_affinely monPred_at_persistently.\nQed.\nGlobal Instance from_modal_id_monPred_at \u03c6 `(sel : A) P Q \ud835\udce0 i :\n  FromModal \u03c6 modality_id sel P Q \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  FromModal \u03c6 modality_id sel (P i) \ud835\udce0.\nProof. rewrite /FromModal /MakeMonPredAt=> HPQ <- ?. by rewrite -HPQ. Qed.\n\nGlobal Instance make_monPred_at_pure \u03c6 i : MakeMonPredAt i \u231c\u03c6\u231d \u231c\u03c6\u231d.\nProof. by rewrite /MakeMonPredAt monPred_at_pure. Qed.\nGlobal Instance make_monPred_at_emp i : MakeMonPredAt i emp emp.\nProof. by rewrite /MakeMonPredAt monPred_at_emp. Qed.\nGlobal Instance make_monPred_at_sep i P \ud835\udcdf Q \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  MakeMonPredAt i (P \u2217 Q) (\ud835\udcdf \u2217 \ud835\udce0).\nProof. by rewrite /MakeMonPredAt monPred_at_sep=><-<-. Qed.\nGlobal Instance make_monPred_at_and i P \ud835\udcdf Q \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  MakeMonPredAt i (P \u2227 Q) (\ud835\udcdf \u2227 \ud835\udce0).\nProof. by rewrite /MakeMonPredAt monPred_at_and=><-<-. Qed.\nGlobal Instance make_monPred_at_or i P \ud835\udcdf Q \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  MakeMonPredAt i (P \u2228 Q) (\ud835\udcdf \u2228 \ud835\udce0).\nProof. by rewrite /MakeMonPredAt monPred_at_or=><-<-. Qed.\nGlobal Instance make_monPred_at_forall {A} i (\u03a6 : A \u2192 monPred) (\u03a8 : A \u2192 PROP) :\n  (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 MakeMonPredAt i (\u2200 a, \u03a6 a) (\u2200 a, \u03a8 a).\nProof. rewrite /MakeMonPredAt monPred_at_forall=>H. by setoid_rewrite <- H. Qed.\nGlobal Instance make_monPred_at_exists {A} i (\u03a6 : A \u2192 monPred) (\u03a8 : A \u2192 PROP) :\n  (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 MakeMonPredAt i (\u2203 a, \u03a6 a) (\u2203 a, \u03a8 a).\nProof. rewrite /MakeMonPredAt monPred_at_exist=>H. by setoid_rewrite <- H. Qed.\nGlobal Instance make_monPred_at_persistently i P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (<pers> P) (<pers> \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_persistently=><-. Qed.\nGlobal Instance make_monPred_at_affinely i P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (<affine> P) (<affine> \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_affinely=><-. Qed.\nGlobal Instance make_monPred_at_intuitionistically i P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (\u25a1 P) (\u25a1 \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_intuitionistically=><-. Qed.\nGlobal Instance make_monPred_at_absorbingly i P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (<absorb> P) (<absorb> \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_absorbingly=><-. Qed.\nGlobal Instance make_monPred_at_persistently_if i P \ud835\udcdf p :\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  MakeMonPredAt i (<pers>?p P) (<pers>?p \ud835\udcdf).\nProof. destruct p; simpl; apply _. Qed.\nGlobal Instance make_monPred_at_affinely_if i P \ud835\udcdf p :\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  MakeMonPredAt i (<affine>?p P) (<affine>?p \ud835\udcdf).\nProof. destruct p; simpl; apply _. Qed.\nGlobal Instance make_monPred_at_absorbingly_if i P \ud835\udcdf p :\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  MakeMonPredAt i (<absorb>?p P) (<absorb>?p \ud835\udcdf).\nProof. destruct p; simpl; apply _. Qed.\nGlobal Instance make_monPred_at_intuitionistically_if i P \ud835\udcdf p :\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  MakeMonPredAt i (\u25a1?p P) (\u25a1?p \ud835\udcdf).\nProof. destruct p; simpl; apply _. Qed.\nGlobal Instance make_monPred_at_embed i \ud835\udcdf : MakeMonPredAt i \u23a1\ud835\udcdf\u23a4 \ud835\udcdf.\nProof. by rewrite /MakeMonPredAt monPred_at_embed. Qed.\nGlobal Instance make_monPred_at_in i j : MakeMonPredAt j (monPred_in i) \u231ci \u2291 j\u231d.\nProof. by rewrite /MakeMonPredAt monPred_at_in. Qed.\nGlobal Instance make_monPred_at_default i P : MakeMonPredAt i P (P i) | 100.\nProof. by rewrite /MakeMonPredAt. Qed.\nGlobal Instance make_monPred_at_bupd `{!BiBUpd PROP} i P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (|==> P) (|==> \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_bupd=> <-. Qed.\n\nGlobal Instance from_assumption_make_monPred_at_l p i j P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 IsBiIndexRel j i \u2192 KnownLFromAssumption p (P j) \ud835\udcdf.\nProof.\n  rewrite /MakeMonPredAt /KnownLFromAssumption /FromAssumption /IsBiIndexRel=><- ->.\n  apply  bi.intuitionistically_if_elim.\nQed.\nGlobal Instance from_assumption_make_monPred_at_r p i j P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 IsBiIndexRel i j \u2192 KnownRFromAssumption p \ud835\udcdf (P j).\nProof.\n  rewrite /MakeMonPredAt /KnownRFromAssumption /FromAssumption /IsBiIndexRel=><- ->.\n  apply  bi.intuitionistically_if_elim.\nQed.\n\nGlobal Instance from_assumption_make_monPred_objectively p P Q :\n  FromAssumption p P Q \u2192 KnownLFromAssumption p (<obj> P) Q.\nProof.\n  by rewrite /KnownLFromAssumption /FromAssumption monPred_objectively_elim.\nQed.\nGlobal Instance from_assumption_make_monPred_subjectively p P Q :\n  FromAssumption p P Q \u2192 KnownRFromAssumption p P (<subj> Q).\nProof.\n  by rewrite /KnownRFromAssumption /FromAssumption -monPred_subjectively_intro.\nQed.\n\nGlobal Instance as_emp_valid_monPred_at \u03c6 P (\u03a6 : I \u2192 PROP) :\n  AsEmpValid0 \u03c6 P \u2192 (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 AsEmpValid \u03c6 (\u2200 i, \u03a6 i) | 100.\nProof.\n  rewrite /MakeMonPredAt /AsEmpValid0 /AsEmpValid /bi_emp_valid=> -> EQ.\n  setoid_rewrite <-EQ. split.\n  - move=>[H]. apply bi.forall_intro=>i. rewrite -H. by rewrite monPred_at_emp.\n  - move=>HP. split=>i. rewrite monPred_at_emp HP bi.forall_elim //.\nQed.\nGlobal Instance as_emp_valid_monPred_at_wand \u03c6 P Q (\u03a6 \u03a8 : I \u2192 PROP) :\n  AsEmpValid0 \u03c6 (P -\u2217 Q) \u2192\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 (\u2200 i, MakeMonPredAt i Q (\u03a8 i)) \u2192\n  AsEmpValid \u03c6 (\u2200 i, \u03a6 i -\u2217 \u03a8 i).\nProof.\n  rewrite /AsEmpValid0 /AsEmpValid /MakeMonPredAt. intros -> EQ1 EQ2.\n  setoid_rewrite <-EQ1. setoid_rewrite <-EQ2. split.\n  - move=>/bi.wand_entails HP. setoid_rewrite HP. by iIntros (i) \"$\".\n  - move=>HP. apply bi.entails_wand. split=>i. iIntros \"H\". by iApply HP.\nQed.\nGlobal Instance as_emp_valid_monPred_at_equiv \u03c6 P Q (\u03a6 \u03a8 : I \u2192 PROP) :\n  AsEmpValid0 \u03c6 (P \u2217-\u2217 Q) \u2192\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 (\u2200 i, MakeMonPredAt i Q (\u03a8 i)) \u2192\n  AsEmpValid \u03c6 (\u2200 i, \u03a6 i \u2217-\u2217 \u03a8 i).\nProof.\n  rewrite /AsEmpValid0 /AsEmpValid /MakeMonPredAt. intros -> EQ1 EQ2.\n  setoid_rewrite <-EQ1. setoid_rewrite <-EQ2. split.\n  - move=>/bi.wand_iff_equiv HP. setoid_rewrite HP. iIntros. iSplit; iIntros \"$\".\n  - move=>HP. apply bi.equiv_wand_iff. split=>i. by iSplit; iIntros; iApply HP.\nQed.\n\nGlobal Instance into_pure_monPred_at P \u03c6 i : IntoPure P \u03c6 \u2192 IntoPure (P i) \u03c6.\nProof. rewrite /IntoPure=>->. by rewrite monPred_at_pure. Qed.\nGlobal Instance from_pure_monPred_at a P \u03c6 i : FromPure a P \u03c6 \u2192 FromPure a (P i) \u03c6.\nProof. rewrite /FromPure=><-. by rewrite monPred_at_affinely_if monPred_at_pure. Qed.\nGlobal Instance into_pure_monPred_in i j : @IntoPure PROP (monPred_in i j) (i \u2291 j).\nProof. by rewrite /IntoPure monPred_at_in. Qed.\nGlobal Instance from_pure_monPred_in i j : @FromPure PROP false (monPred_in i j) (i \u2291 j).\nProof. by rewrite /FromPure monPred_at_in. Qed.\n\nGlobal Instance into_persistent_monPred_at p P Q \ud835\udce0 i :\n  IntoPersistent p P Q \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192 IntoPersistent p (P i) \ud835\udce0 | 0.\nProof.\n  rewrite /IntoPersistent /MakeMonPredAt  =>-[/(_ i) ?] <-.\n  by rewrite -monPred_at_persistently -monPred_at_persistently_if.\nQed.\n\nLemma into_wand_monPred_at_unknown_unknown p q R P \ud835\udcdf Q \ud835\udce0 i :\n  IntoWand p q R P Q \u2192 MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  IntoWand p q (R i) \ud835\udcdf \ud835\udce0.\nProof.\n  rewrite /IntoWand /MakeMonPredAt /bi_affinely_if /bi_persistently_if.\n  destruct p, q=> /bi.wand_elim_l' [/(_ i) H] <- <-; apply bi.wand_intro_r;\n  revert H; by rewrite monPred_at_sep ?monPred_at_affinely ?monPred_at_persistently.\nQed.\nLemma into_wand_monPred_at_unknown_known p q R P \ud835\udcdf Q i j :\n  IsBiIndexRel i j \u2192 IntoWand p q R P Q \u2192\n  MakeMonPredAt j P \ud835\udcdf \u2192 IntoWand p q (R i) \ud835\udcdf (Q j).\nProof.\n  rewrite /IntoWand /IsBiIndexRel /MakeMonPredAt=>-> ? ?.\n  eapply into_wand_monPred_at_unknown_unknown=>//. apply _.\nQed.\nLemma into_wand_monPred_at_known_unknown_le p q R P Q \ud835\udce0 i j :\n  IsBiIndexRel i j \u2192 IntoWand p q R P Q \u2192\n  MakeMonPredAt j Q \ud835\udce0 \u2192 IntoWand p q (R i) (P j) \ud835\udce0.\nProof.\n  rewrite /IntoWand /IsBiIndexRel /MakeMonPredAt=>-> ? ?.\n  eapply into_wand_monPred_at_unknown_unknown=>//. apply _.\nQed.\nLemma into_wand_monPred_at_known_unknown_ge p q R P Q \ud835\udce0 i j :\n  IsBiIndexRel i j \u2192 IntoWand p q R P Q \u2192\n  MakeMonPredAt j Q \ud835\udce0 \u2192 IntoWand p q (R j) (P i) \ud835\udce0.\nProof.\n  rewrite /IntoWand /IsBiIndexRel /MakeMonPredAt=>-> ? ?.\n  eapply into_wand_monPred_at_unknown_unknown=>//. apply _.\nQed.\n\nGlobal Instance into_wand_wand'_monPred p q P Q \ud835\udcdf \ud835\udce0 i :\n  IntoWand' p q ((P -\u2217 Q) i) \ud835\udcdf \ud835\udce0 \u2192 IntoWand p q ((P -\u2217 Q) i) \ud835\udcdf \ud835\udce0 | 100.\nProof. done. Qed.\nGlobal Instance into_wand_impl'_monPred p q P Q \ud835\udcdf \ud835\udce0 i :\n  IntoWand' p q ((P \u2192 Q) i) \ud835\udcdf \ud835\udce0 \u2192 IntoWand p q ((P \u2192 Q) i) \ud835\udcdf \ud835\udce0 | 100.\nProof. done. Qed.\n\nGlobal Instance from_forall_monPred_at_wand P Q (\u03a6 \u03a8 : I \u2192 PROP) i :\n  (\u2200 j, MakeMonPredAt j P (\u03a6 j)) \u2192 (\u2200 j, MakeMonPredAt j Q (\u03a8 j)) \u2192\n  FromForall ((P -\u2217 Q) i)%I (\u03bb j, \u231ci \u2291 j\u231d \u2192 \u03a6 j -\u2217 \u03a8 j)%I (to_ident_name idx).\nProof.\n  rewrite /FromForall /MakeMonPredAt monPred_at_wand=> H1 H2. do 2 f_equiv.\n  by rewrite H1 H2.\nQed.\nGlobal Instance from_forall_monPred_at_impl P Q (\u03a6 \u03a8 : I \u2192 PROP) i :\n  (\u2200 j, MakeMonPredAt j P (\u03a6 j)) \u2192 (\u2200 j, MakeMonPredAt j Q (\u03a8 j)) \u2192\n  FromForall ((P \u2192 Q) i)%I (\u03bb j, \u231ci \u2291 j\u231d \u2192 \u03a6 j \u2192 \u03a8 j)%I (to_ident_name idx).\nProof.\n  rewrite /FromForall /MakeMonPredAt monPred_at_impl=> H1 H2. do 2 f_equiv.\n  by rewrite H1 H2 bi.pure_impl_forall.\nQed.\n\nGlobal Instance into_forall_monPred_at_index P i :\n  IntoForall (P i) (\u03bb j, \u231ci \u2291 j\u231d \u2192 P j)%I | 100.\nProof.\n  rewrite /IntoForall. setoid_rewrite bi.pure_impl_forall.\n  do 2 apply bi.forall_intro=>?. by f_equiv.\nQed.\n\nGlobal Instance from_and_monPred_at P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  FromAnd P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  FromAnd (P i) \ud835\udce01 \ud835\udce02.\nProof.\n  rewrite /FromAnd /MakeMonPredAt /MakeMonPredAt=> <- <- <-.\n  by rewrite monPred_at_and.\nQed.\nGlobal Instance into_and_monPred_at p P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  IntoAnd p P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  IntoAnd p (P i) \ud835\udce01 \ud835\udce02.\nProof.\n  rewrite /IntoAnd /MakeMonPredAt /bi_affinely_if /bi_persistently_if.\n  destruct p=>-[/(_ i) H] <- <-; revert H;\n  by rewrite ?monPred_at_affinely ?monPred_at_persistently monPred_at_and.\nQed.\n\nGlobal Instance from_sep_monPred_at P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  FromSep P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  FromSep (P i) \ud835\udce01 \ud835\udce02.\nProof. rewrite /FromSep /MakeMonPredAt=> <- <- <-. by rewrite monPred_at_sep. Qed.\nGlobal Instance into_sep_monPred_at P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  IntoSep P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  IntoSep (P i) \ud835\udce01 \ud835\udce02.\nProof. rewrite /IntoSep /MakeMonPredAt=> -> <- <-. by rewrite monPred_at_sep. Qed.\nGlobal Instance from_or_monPred_at P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  FromOr P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  FromOr (P i) \ud835\udce01 \ud835\udce02.\nProof. rewrite /FromOr /MakeMonPredAt=> <- <- <-. by rewrite monPred_at_or. Qed.\nGlobal Instance into_or_monPred_at P Q1 \ud835\udce01 Q2 \ud835\udce02 i :\n  IntoOr P Q1 Q2 \u2192 MakeMonPredAt i Q1 \ud835\udce01 \u2192 MakeMonPredAt i Q2 \ud835\udce02 \u2192\n  IntoOr (P i) \ud835\udce01 \ud835\udce02.\nProof. rewrite /IntoOr /MakeMonPredAt=> -> <- <-. by rewrite monPred_at_or. Qed.\n\nGlobal Instance from_exist_monPred_at {A} P (\u03a6 : A \u2192 monPred) (\u03a8 : A \u2192 PROP) i :\n  FromExist P \u03a6 \u2192 (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 FromExist (P i) \u03a8.\nProof.\n  rewrite /FromExist /MakeMonPredAt=><- H. setoid_rewrite <- H.\n  by rewrite monPred_at_exist.\nQed.\nGlobal Instance into_exist_monPred_at {A} P (\u03a6 : A \u2192 monPred) name (\u03a8 : A \u2192 PROP) i :\n  IntoExist P \u03a6 name \u2192 (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 IntoExist (P i) \u03a8 name.\nProof.\n  rewrite /IntoExist /MakeMonPredAt=>-> H. setoid_rewrite <- H.\n  by rewrite monPred_at_exist.\nQed.\n\nGlobal Instance from_forall_monPred_at_objectively P (\u03a6 : I \u2192 PROP) i :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 FromForall ((<obj> P) i)%I \u03a6 (to_ident_name idx).\nProof.\n  rewrite /FromForall /MakeMonPredAt monPred_at_objectively=>H. by setoid_rewrite <- H.\nQed.\nGlobal Instance into_forall_monPred_at_objectively P (\u03a6 : I \u2192 PROP) i :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 IntoForall ((<obj> P) i) \u03a6.\nProof.\n  rewrite /IntoForall /MakeMonPredAt monPred_at_objectively=>H. by setoid_rewrite <- H.\nQed.\n\nGlobal Instance from_exist_monPred_at_ex P (\u03a6 : I \u2192 PROP) i :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 FromExist ((<subj> P) i) \u03a6.\nProof.\n  rewrite /FromExist /MakeMonPredAt monPred_at_subjectively=>H. by setoid_rewrite <- H.\nQed.\n(* TODO: this implementation uses [idx] as the automatic name for the index. In\ntheory a monPred could define an appropriate metavariable for indices with an\n[ident_name] argument to [MakeMonPredAt], but this is not implemented. *)\nGlobal Instance into_exist_monPred_at_ex P (\u03a6 : I \u2192 PROP) i :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192 IntoExist ((<subj> P) i) \u03a6 (to_ident_name idx).\nProof.\n  rewrite /IntoExist /MakeMonPredAt monPred_at_subjectively=>H. by setoid_rewrite <- H.\nQed.\n\nGlobal Instance from_forall_monPred_at {A} P (\u03a6 : A \u2192 monPred) name (\u03a8 : A \u2192 PROP) i :\n  FromForall P \u03a6 name \u2192 (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 FromForall (P i) \u03a8 name.\nProof.\n  rewrite /FromForall /MakeMonPredAt=><- H. setoid_rewrite <- H.\n  by rewrite monPred_at_forall.\nQed.\nGlobal Instance into_forall_monPred_at {A} P (\u03a6 : A \u2192 monPred) (\u03a8 : A \u2192 PROP) i :\n  IntoForall P \u03a6 \u2192 (\u2200 a, MakeMonPredAt i (\u03a6 a) (\u03a8 a)) \u2192 IntoForall (P i) \u03a8.\nProof.\n  rewrite /IntoForall /MakeMonPredAt=>-> H. setoid_rewrite <- H.\n  by rewrite monPred_at_forall.\nQed.\n\n(* Framing. *)\nGlobal Instance frame_monPred_at_enter p i \ud835\udce1 P \ud835\udce0 :\n  FrameMonPredAt p i \ud835\udce1 P \ud835\udce0 \u2192 Frame p \ud835\udce1 (P i) \ud835\udce0 | 2.\nProof. intros. done. Qed.\nGlobal Instance frame_monPred_at_here p P i j :\n  IsBiIndexRel i j \u2192 FrameMonPredAt p j (P i) P emp | 0.\nProof.\n  rewrite /FrameMonPredAt /IsBiIndexRel right_id bi.intuitionistically_if_elim=> -> //.\nQed.\n\nGlobal Instance frame_monPred_at_embed p \ud835\udce1 \ud835\udce0 \ud835\udcdf i :\n  Frame p \ud835\udce1 \ud835\udcdf \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (embed (B:=monPredI) \ud835\udcdf) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_embed. Qed.\nGlobal Instance frame_monPred_at_sep p P Q \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (P i \u2217 Q i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (P \u2217 Q) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_sep. Qed.\nGlobal Instance frame_monPred_at_and p P Q \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (P i \u2227 Q i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (P \u2227 Q) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_and. Qed.\nGlobal Instance frame_monPred_at_or p P Q \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (P i \u2228 Q i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (P \u2228 Q) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_or. Qed.\nGlobal Instance frame_monPred_at_wand p P R Q1 Q2 i j :\n  IsBiIndexRel i j \u2192\n  Frame p R Q1 Q2 \u2192\n  FrameMonPredAt p j (R i) (P -\u2217 Q1) ((P -\u2217 Q2) i).\nProof.\n  rewrite /Frame /FrameMonPredAt=>-> Hframe.\n  rewrite -monPred_at_intuitionistically_if -monPred_at_sep. apply monPred_in_entails.\n  change ((\u25a1?p R \u2217 (P -\u2217 Q2)) -\u2217 P -\u2217 Q1). apply bi.wand_intro_r.\n  rewrite -assoc bi.wand_elim_l. done.\nQed.\nGlobal Instance frame_monPred_at_impl P R Q1 Q2 i j :\n  IsBiIndexRel i j \u2192\n  Frame true R Q1 Q2 \u2192\n  FrameMonPredAt true j (R i) (P \u2192 Q1) ((P \u2192 Q2) i).\nProof.\n  rewrite /Frame /FrameMonPredAt=>-> Hframe.\n  rewrite -monPred_at_intuitionistically_if -monPred_at_sep. apply monPred_in_entails.\n  change ((\u25a1 R \u2217 (P \u2192 Q2)) -\u2217 P \u2192 Q1).\n  rewrite -bi.persistently_and_intuitionistically_sep_l. apply bi.impl_intro_r.\n  rewrite -assoc bi.impl_elim_l bi.persistently_and_intuitionistically_sep_l. done.\nQed.\nGlobal Instance frame_monPred_at_forall {X : Type} p (\u03a8 : X \u2192 monPred) \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u2200 x, \u03a8 x i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (\u2200 x, \u03a8 x) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_forall. Qed.\nGlobal Instance frame_monPred_at_exist {X : Type} p (\u03a8 : X \u2192 monPred) \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u2203 x, \u03a8 x i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (\u2203 x, \u03a8 x) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_exist. Qed.\n\nGlobal Instance frame_monPred_at_absorbingly p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (<absorb> P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (<absorb> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_absorbingly. Qed.\nGlobal Instance frame_monPred_at_affinely p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (<affine> P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (<affine> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_affinely. Qed.\nGlobal Instance frame_monPred_at_persistently p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (<pers> P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (<pers> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_persistently. Qed.\nGlobal Instance frame_monPred_at_intuitionistically p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u25a1 P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (\u25a1 P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_intuitionistically. Qed.\nGlobal Instance frame_monPred_at_objectively p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u2200 i, P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (<obj> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_objectively. Qed.\nGlobal Instance frame_monPred_at_subjectively p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u2203 i, P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (<subj> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_subjectively. Qed.\nGlobal Instance frame_monPred_at_bupd `{!BiBUpd PROP} p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (|==> P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (|==> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_bupd. Qed.\n\nGlobal Instance into_embed_objective P :\n  Objective P \u2192 IntoEmbed P (\u2200 i, P i).\nProof.\n  rewrite /IntoEmbed=> ?.\n  by rewrite {1}(objective_objectively P) monPred_objectively_unfold.\nQed.\n\nGlobal Instance elim_modal_at_bupd_goal `{!BiBUpd PROP} \u03c6 p p' \ud835\udcdf \ud835\udcdf' Q Q' i :\n  ElimModal \u03c6 p p' \ud835\udcdf \ud835\udcdf' (|==> Q i) (|==> Q' i) \u2192\n  ElimModal \u03c6 p p' \ud835\udcdf \ud835\udcdf' ((|==> Q) i) ((|==> Q') i).\nProof. by rewrite /ElimModal !monPred_at_bupd. Qed.\nGlobal Instance elim_modal_at_bupd_hyp `{!BiBUpd PROP} \u03c6 p p' P \ud835\udcdf \ud835\udcdf' \ud835\udce0 \ud835\udce0' i:\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  ElimModal \u03c6 p p' (|==> \ud835\udcdf) \ud835\udcdf' \ud835\udce0 \ud835\udce0' \u2192\n  ElimModal \u03c6 p p' ((|==> P) i) \ud835\udcdf' \ud835\udce0 \ud835\udce0'.\nProof. by rewrite /MakeMonPredAt /ElimModal monPred_at_bupd=><-. Qed.\nGlobal Instance elim_modal_at \u03c6 p p' \ud835\udcdf \ud835\udcdf' P P' V:\n  ElimModal \u03c6 p p' \u23a1\ud835\udcdf\u23a4 \u23a1\ud835\udcdf'\u23a4 P P' \u2192 ElimModal \u03c6 p p' \ud835\udcdf \ud835\udcdf' (P V) (P' V).\nProof.\n  rewrite /ElimModal -!embed_intuitionistically_if.\n  iIntros (HH H\u03c6) \"[? HP]\". iApply HH; [done|]. iFrame. iIntros (? <-) \"?\".\n  by iApply \"HP\".\nQed.\n\nGlobal Instance add_modal_at_bupd_goal `{!BiBUpd PROP} \u03c6 \ud835\udcdf \ud835\udcdf' Q i :\n  AddModal \ud835\udcdf \ud835\udcdf' (|==> Q i)%I \u2192 AddModal \ud835\udcdf \ud835\udcdf' ((|==> Q) i).\nProof. by rewrite /AddModal !monPred_at_bupd. Qed.\n\nGlobal Instance from_forall_monPred_at_plainly `{!BiPlainly PROP} i P \u03a6 :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192\n  FromForall ((\u25a0 P) i) (\u03bb j, \u25a0 (\u03a6 j))%I (to_ident_name idx).\nProof.\n  rewrite /FromForall /MakeMonPredAt=>HP\u03a6. rewrite monPred_at_plainly.\n  by setoid_rewrite HP\u03a6.\nQed.\nGlobal Instance into_forall_monPred_at_plainly `{!BiPlainly PROP} i P \u03a6 :\n  (\u2200 i, MakeMonPredAt i P (\u03a6 i)) \u2192\n  IntoForall ((\u25a0 P) i) (\u03bb j, \u25a0 (\u03a6 j))%I.\nProof.\n  rewrite /IntoForall /MakeMonPredAt=>HP\u03a6. rewrite monPred_at_plainly.\n  by setoid_rewrite HP\u03a6.\nQed.\n\nGlobal Instance is_except_0_monPred_at i P :\n  IsExcept0 P \u2192 IsExcept0 (P i).\nProof. rewrite /IsExcept0=>- [/(_ i)]. by rewrite monPred_at_except_0. Qed.\n\nGlobal Instance make_monPred_at_internal_eq `{!BiInternalEq PROP} {A : ofe} (x y : A) i :\n  MakeMonPredAt i (x \u2261 y) (x \u2261 y).\nProof. by rewrite /MakeMonPredAt monPred_at_internal_eq. Qed.\nGlobal Instance make_monPred_at_except_0 i P \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udce0 \u2192 MakeMonPredAt i (\u25c7 P) (\u25c7 \ud835\udce0).\nProof. by rewrite /MakeMonPredAt monPred_at_except_0=><-. Qed.\nGlobal Instance make_monPred_at_later i P \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udce0 \u2192 MakeMonPredAt i (\u25b7 P) (\u25b7 \ud835\udce0).\nProof. by rewrite /MakeMonPredAt monPred_at_later=><-. Qed.\nGlobal Instance make_monPred_at_laterN i n P \ud835\udce0 :\n  MakeMonPredAt i P \ud835\udce0 \u2192 MakeMonPredAt i (\u25b7^n P) (\u25b7^n \ud835\udce0).\nProof. rewrite /MakeMonPredAt=> <-. elim n=>//= ? <-. by rewrite monPred_at_later. Qed.\nGlobal Instance make_monPred_at_fupd `{!BiFUpd PROP} i E1 E2 P \ud835\udcdf :\n  MakeMonPredAt i P \ud835\udcdf \u2192 MakeMonPredAt i (|={E1,E2}=> P) (|={E1,E2}=> \ud835\udcdf).\nProof. by rewrite /MakeMonPredAt monPred_at_fupd=> <-. Qed.\n\nGlobal Instance into_internal_eq_monPred_at `{!BiInternalEq PROP}\n    {A : ofe} (x y : A) P i :\n  IntoInternalEq P x y \u2192 IntoInternalEq (P i) x y.\nProof. rewrite /IntoInternalEq=> ->. by rewrite monPred_at_internal_eq. Qed.\n\nGlobal Instance into_except_0_monPred_at_fwd i P Q \ud835\udce0 :\n  IntoExcept0 P Q \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192 IntoExcept0 (P i) \ud835\udce0.\nProof. rewrite /IntoExcept0 /MakeMonPredAt=> -> <-. by rewrite monPred_at_except_0. Qed.\nGlobal Instance into_except_0_monPred_at_bwd i P \ud835\udcdf Q :\n  IntoExcept0 P Q \u2192 MakeMonPredAt i P \ud835\udcdf \u2192 IntoExcept0 \ud835\udcdf (Q i).\nProof. rewrite /IntoExcept0 /MakeMonPredAt=> H <-. by rewrite H monPred_at_except_0. Qed.\n\nGlobal Instance maybe_into_later_monPred_at i n P Q \ud835\udce0 :\n  IntoLaterN false n P Q \u2192 MakeMonPredAt i Q \ud835\udce0 \u2192\n  IntoLaterN false n (P i) \ud835\udce0.\nProof.\n  rewrite /IntoLaterN /MaybeIntoLaterN /MakeMonPredAt=> -> <-. elim n=>//= ? <-.\n  by rewrite monPred_at_later.\nQed.\nGlobal Instance from_later_monPred_at i \u03c6 `(sel : A) n P Q \ud835\udce0 :\n  FromModal \u03c6 (modality_laterN n) sel P Q \u2192\n  MakeMonPredAt i Q \ud835\udce0 \u2192\n  FromModal \u03c6 (modality_laterN n) sel (P i) \ud835\udce0.\nProof.\n  rewrite /FromModal /MakeMonPredAt=> HPQ <- ?. rewrite -HPQ //.\n  elim n=>//= ? ->.\n  by rewrite monPred_at_later.\nQed.\n\nGlobal Instance frame_monPred_at_later p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u25b7 P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (\u25b7 P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_later. Qed.\nGlobal Instance frame_monPred_at_laterN p n P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (\u25b7^n P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (\u25b7^n P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_laterN. Qed.\nGlobal Instance frame_monPred_at_fupd `{!BiFUpd PROP} E1 E2 p P \ud835\udce1 \ud835\udce0 i :\n  Frame p \ud835\udce1 (|={E1,E2}=> P i) \ud835\udce0 \u2192 FrameMonPredAt p i \ud835\udce1 (|={E1,E2}=> P) \ud835\udce0.\nProof. rewrite /Frame /FrameMonPredAt=> ->. by rewrite monPred_at_fupd. Qed.\nEnd bi.\n(* When P and/or Q are evars when doing typeclass search on [IntoWand\n   (R i) P Q], we use [MakeMonPredAt] in order to normalize the\n   result of unification. However, when they are not evars, we want to\n   propagate the known information through typeclass search. Hence, we\n   do not want to use [MakeMonPredAt].\n\n   As a result, depending on P and Q being evars, we use a different\n   version of [into_wand_monPred_at_xx_xx]. *)\nGlobal Hint Extern 3 (IntoWand _ _ (monPred_at _ _) ?P ?Q) =>\n     is_evar P; is_evar Q;\n     eapply @into_wand_monPred_at_unknown_unknown\n     : typeclass_instances.\nGlobal Hint Extern 2 (IntoWand _ _ (monPred_at _ _) ?P (monPred_at ?Q _)) =>\n     eapply @into_wand_monPred_at_unknown_known\n     : typeclass_instances.\nGlobal Hint Extern 2 (IntoWand _ _ (monPred_at _ _) (monPred_at ?P _) ?Q) =>\n     eapply @into_wand_monPred_at_known_unknown_le\n     : typeclass_instances.\nGlobal Hint Extern 2 (IntoWand _ _ (monPred_at _ _) (monPred_at ?P _) ?Q) =>\n     eapply @into_wand_monPred_at_known_unknown_ge\n     : typeclass_instances.\n\nSection modal.\nContext {I : biIndex} {PROP : bi}.\nLocal Notation monPred := (monPred I PROP).\nImplicit Types P Q R : monPred.\nImplicit Types \ud835\udcdf \ud835\udce0 \ud835\udce1 : PROP.\nImplicit Types \u03c6 : Prop.\nImplicit Types i j : I.\n\nGlobal Instance elim_modal_at_fupd_goal `{!BiFUpd PROP} \u03c6 p p' E1 E2 E3 \ud835\udcdf \ud835\udcdf' Q Q' i :\n  ElimModal \u03c6 p p' \ud835\udcdf \ud835\udcdf' (|={E1,E3}=> Q i) (|={E2,E3}=> Q' i) \u2192\n  ElimModal \u03c6 p p' \ud835\udcdf \ud835\udcdf' ((|={E1,E3}=> Q) i) ((|={E2,E3}=> Q') i).\nProof. by rewrite /ElimModal !monPred_at_fupd. Qed.\nGlobal Instance elim_modal_at_fupd_hyp `{!BiFUpd PROP} \u03c6 p p' E1 E2 P \ud835\udcdf \ud835\udcdf' \ud835\udce0 \ud835\udce0' i :\n  MakeMonPredAt i P \ud835\udcdf \u2192\n  ElimModal \u03c6 p p' (|={E1,E2}=> \ud835\udcdf) \ud835\udcdf' \ud835\udce0 \ud835\udce0' \u2192\n  ElimModal \u03c6 p p' ((|={E1,E2}=> P) i) \ud835\udcdf' \ud835\udce0 \ud835\udce0'.\nProof. by rewrite /MakeMonPredAt /ElimModal monPred_at_fupd=><-. Qed.\n\nGlobal Instance elim_acc_at_None `{!BiFUpd PROP} {X} \u03c6 E1 E2 E3 E4 \u03b1 \u03b1' \u03b2 \u03b2' P P'x i :\n  (\u2200 x, MakeEmbed (\u03b1 x) (\u03b1' x)) \u2192 (\u2200 x, MakeEmbed (\u03b2 x) (\u03b2' x)) \u2192\n  ElimAcc (X:=X) \u03c6 (fupd E1 E2) (fupd E3 E4) \u03b1' \u03b2' (\u03bb _, None) P P'x \u2192\n  ElimAcc (X:=X) \u03c6 (fupd E1 E2) (fupd E3 E4) \u03b1 \u03b2 (\u03bb _, None) (P i) (\u03bb x, P'x x i).\nProof.\n  rewrite /ElimAcc /MakeEmbed. iIntros (H\u03b1 H\u03b2 HEA ?) \"Hinner Hacc\".\n  iApply (HEA with \"[Hinner]\"); first done.\n  - iIntros (x).  iSpecialize (\"Hinner\" $! x). rewrite -H\u03b1. by iIntros (? <-).\n  - iMod \"Hacc\". iDestruct \"Hacc\" as (x) \"[H\u03b1 Hclose]\". iModIntro. iExists x.\n    rewrite -H\u03b1 -H\u03b2. iFrame. iIntros (? _) \"H\u03b2\". by iApply \"Hclose\".\nQed.\nGlobal Instance elim_acc_at_Some `{!BiFUpd PROP} {X} \u03c6 E1 E2 E3 E4 \u03b1 \u03b1' \u03b2 \u03b2' \u03b3 \u03b3' P P'x i :\n  (\u2200 x, MakeEmbed (\u03b1 x) (\u03b1' x)) \u2192\n  (\u2200 x, MakeEmbed (\u03b2 x) (\u03b2' x)) \u2192\n  (\u2200 x, MakeEmbed (\u03b3 x) (\u03b3' x)) \u2192\n  ElimAcc (X:=X) \u03c6 (fupd E1 E2) (fupd E3 E4) \u03b1' \u03b2' (\u03bb x, Some (\u03b3' x)) P P'x \u2192\n  ElimAcc (X:=X) \u03c6 (fupd E1 E2) (fupd E3 E4) \u03b1 \u03b2 (\u03bb x, Some (\u03b3 x)) (P i) (\u03bb x, P'x x i).\nProof.\n  rewrite /ElimAcc /MakeEmbed. iIntros (H\u03b1 H\u03b2 H\u03b3 HEA ?) \"Hinner Hacc\".\n  iApply (HEA with \"[Hinner]\"); first done.\n  - iIntros (x).  iSpecialize (\"Hinner\" $! x). rewrite -H\u03b1. by iIntros (? <-).\n  - iMod \"Hacc\". iDestruct \"Hacc\" as (x) \"[H\u03b1 Hclose]\". iModIntro. iExists x.\n    rewrite -H\u03b1 -H\u03b2 -H\u03b3. iFrame. iIntros (? _) \"H\u03b2 /=\". by iApply \"Hclose\".\nQed.\n\nGlobal Instance add_modal_at_fupd_goal `{!BiFUpd PROP} E1 E2 \ud835\udcdf \ud835\udcdf' Q i :\n  AddModal \ud835\udcdf \ud835\udcdf' (|={E1,E2}=> Q i) \u2192 AddModal \ud835\udcdf \ud835\udcdf' ((|={E1,E2}=> Q) i).\nProof. by rewrite /AddModal !monPred_at_fupd. Qed.\n\n(* This hard-codes the fact that ElimInv with_close returns a\n   [(\u03bb _, ...)] as Q'. *)\nGlobal Instance elim_inv_embed_with_close {X : Type} \u03c6\n    \ud835\udcdfinv \ud835\udcdfin (\ud835\udcdfout \ud835\udcdfclose : X \u2192 PROP)\n    Pin (Pout Pclose : X \u2192 monPred)\n    Q Q' :\n  (\u2200 i, ElimInv \u03c6 \ud835\udcdfinv \ud835\udcdfin \ud835\udcdfout (Some \ud835\udcdfclose) (Q i) (\u03bb _, Q' i)) \u2192\n  MakeEmbed \ud835\udcdfin Pin \u2192 (\u2200 x, MakeEmbed (\ud835\udcdfout x) (Pout x)) \u2192\n  (\u2200 x, MakeEmbed (\ud835\udcdfclose x) (Pclose x)) \u2192\n  ElimInv (X:=X) \u03c6 \u23a1\ud835\udcdfinv\u23a4 Pin Pout (Some Pclose) Q (\u03bb _, Q').\nProof.\n  rewrite /MakeEmbed /ElimInv=>H <- Hout Hclose ?. iStartProof PROP.\n  setoid_rewrite <-Hout. setoid_rewrite <-Hclose.\n  iIntros (?) \"(?&?&HQ')\". iApply H; [done|]. iFrame. iIntros (x) \"?\".\n  by iApply \"HQ'\".\nQed.\nGlobal Instance elim_inv_embed_without_close  {X : Type}\n    \u03c6 \ud835\udcdfinv \ud835\udcdfin (\ud835\udcdfout : X \u2192 PROP) Pin (Pout : X \u2192 monPred) Q (Q' : X \u2192 monPred) :\n  (\u2200 i, ElimInv \u03c6 \ud835\udcdfinv \ud835\udcdfin \ud835\udcdfout None (Q i) (\u03bb x, Q' x i)) \u2192\n  MakeEmbed \ud835\udcdfin Pin \u2192 (\u2200 x, MakeEmbed (\ud835\udcdfout x) (Pout x)) \u2192\n  ElimInv (X:=X) \u03c6 \u23a1\ud835\udcdfinv\u23a4 Pin Pout None Q Q'.\nProof.\n  rewrite /MakeEmbed /ElimInv=>H <-Hout ?. iStartProof PROP.\n  setoid_rewrite <-Hout.\n  iIntros (?) \"(?&?&HQ')\". iApply H; [done|]. iFrame. iIntros (x) \"?\".\n  by iApply \"HQ'\".\nQed.\nEnd modal.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/proofmode/monpred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.17121497284794412}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Utility.MonadNotations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Datatypes.List.\nRequire Import coqutil.Datatypes.ListSet.\nRequire Export riscv.Platform.RiscvMachine.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Properties.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Platform.Sane.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\n\n\nClass MMIOSpec{width: Z}{BW: Bitwidth width}{word: word width} := {\n  (* should not say anything about alignment, just whether it's in the MMIO range *)\n  isMMIOAddr: word -> Prop;\n\n  (* alignment and load size checks *)\n  isMMIOAligned: nat -> word -> Prop;\n}.\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} {Registers: map.map Register word}.\n\n  Definition signedByteTupleToReg{n: nat}(v: HList.tuple byte n): word :=\n    word.of_Z (BitOps.signExtend (8 * Z.of_nat n) (LittleEndian.combine n v)).\n\n  Definition mmioLoadEvent(addr: word){n: nat}(v: HList.tuple byte n): LogItem :=\n    ((map.empty, \"MMIOREAD\"%string, [addr]), (map.empty, [signedByteTupleToReg v])).\n\n  Definition mmioStoreEvent(addr: word){n: nat}(v: HList.tuple byte n): LogItem :=\n    ((map.empty, \"MMIOWRITE\"%string, [addr; signedByteTupleToReg v]), (map.empty, [])).\n\n  Context {mmio_spec: MMIOSpec}.\n\n  Definition nonmem_store(n: nat)(ctxid: SourceType) a v mach post :=\n    isMMIOAddr a /\\ isMMIOAligned n a /\\\n    post (withXAddrs (invalidateWrittenXAddrs n a mach.(getXAddrs))\n         (withLogItem (@mmioStoreEvent a n v)\n         mach)).\n\n  Definition store(n: nat)(ctxid: SourceType) a v mach post :=\n    match Memory.store_bytes n mach.(getMem) a v with\n    | Some m => post (withXAddrs (invalidateWrittenXAddrs n a mach.(getXAddrs)) (withMem m mach))\n    | None => nonmem_store n ctxid a v mach post\n    end.\n\n  Definition nonmem_load(n: nat)(ctxid: SourceType) a mach (post: _ -> _ -> Prop) :=\n    isMMIOAddr a /\\ isMMIOAligned n a /\\\n    forall v, post v (withLogItem (@mmioLoadEvent a n v) mach).\n\n  Definition load(n: nat)(ctxid: SourceType) a mach post :=\n    (ctxid = Fetch -> isXAddr4 a mach.(getXAddrs)) /\\\n    match Memory.load_bytes n mach.(getMem) a with\n    | Some v => post v mach\n    | None => nonmem_load n ctxid a mach post\n    end.\n\n  Instance IsRiscvMachine: RiscvProgram (Post RiscvMachine) word. refine ({|\n    getRegister reg := fun mach post => _;\n    setRegister reg v := fun mach post => _;\n    loadByte   ctxid a := fun mach post => _;\n    loadHalf   ctxid a := fun mach post => _;\n    loadWord   ctxid a := fun mach post => _;\n    loadDouble ctxid a := fun mach post => _;\n    storeByte   ctxid a v := fun mach post => _;\n    storeHalf   ctxid a v := fun mach post => _;\n    storeWord   ctxid a v := fun mach post => _;\n    storeDouble ctxid a v := fun mach post => _;\n    makeReservation _  := fun _ _ => False;\n    clearReservation _ := fun _ _ => False;\n    checkReservation _ := fun _ _ => False;\n    getPC := fun mach post => _;\n    setPC newPC := fun mach post => _;\n    getCSRField _      := fun _ _ => False;\n    setCSRField _ _    := fun _ _ => False;\n    getPrivMode        := fun _ _ => False;\n    setPrivMode _      := fun _ _ => False;\n    fence _ _          := fun _ _ => False;\n    endCycleEarly _    := fun _ _ => False;\n    endCycleNormal     := fun mach post => _;\n  |}).\n  (* TODO: inline the terms below into the holes above while keeping Coq's typechecker happy *)\n  - exact (let v :=\n        if Z.eq_dec reg 0 then word.of_Z 0\n        else match map.get mach.(getRegs) reg with\n             | Some x => x\n             | None => word.of_Z 0 end in\n           post v mach).\n  - exact (let regs := if Z.eq_dec reg Register0\n                       then mach.(getRegs)\n                       else map.put mach.(getRegs) reg v in\n      post tt (withRegs regs mach)).\n  - exact (load 1 ctxid a mach post).\n  - exact (load 2 ctxid a mach post).\n  - exact (load 4 ctxid a mach post).\n  - exact (load 8 ctxid a mach post).\n  - exact (store 1 ctxid a v mach (post tt)).\n  - exact (store 2 ctxid a v mach (post tt)).\n  - exact (store 4 ctxid a v mach (post tt)).\n  - exact (store 8 ctxid a v mach (post tt)).\n  - exact (post mach.(getPc) mach).\n  - exact (post tt (withNextPc newPC mach)).\n  - exact (post tt (withPc mach.(getNextPc) (withNextPc (word.add mach.(getNextPc) (word.of_Z 4)) mach))).\n  Defined.\n\n  Definition MinimalMMIOPrimitivesParams: PrimitivesParams (Post RiscvMachine) RiscvMachine := {|\n    Primitives.mcomp_sat A (m: Post RiscvMachine A) mach post := m mach post;\n    Primitives.is_initial_register_value x := True;\n    Primitives.nonmem_load := nonmem_load;\n    Primitives.nonmem_store := nonmem_store;\n    Primitives.valid_machine mach :=\n      map.undef_on mach.(getMem) isMMIOAddr /\\ disjoint (of_list mach.(getXAddrs)) isMMIOAddr;\n  |}.\n\n  Lemma load_weaken_post n c a m (post1 post2:_->_->Prop)\n    (H: forall r s, post1 r s -> post2 r s)\n    : load n c a m post1 -> load n c a m post2.\n  Proof.\n    cbv [load nonmem_load].\n    destruct (Memory.load_bytes n (getMem m) a); intuition eauto.\n  Qed.\n\n  Lemma store_weaken_post n c a v m (post1 post2:_->Prop)\n    (H: forall s, post1 s -> post2 s)\n    : store n c a v m post1 -> store n c a v m post2.\n  Proof.\n    cbv [store nonmem_store].\n    destruct (Memory.store_bytes n (getMem m) a); intuition eauto.\n  Qed.\n\n  (* all the monadic riscv computations we will construct satisfy weakening, but it is not\n     explicit from the type *)\n  Definition weakening_for{S A: Type}(m: Post S A): Prop :=\n    forall post1 post2: A -> S -> Prop,\n      (forall a s, post1 a s -> post2 a s) ->\n      forall s, m s post1 -> m s post2.\n\n  Global Instance MinimalMMIOSatisfies_mcomp_sat_spec: mcomp_sat_spec MinimalMMIOPrimitivesParams.\n  Proof.\n    split; cbv [mcomp_sat MinimalMMIOPrimitivesParams Bind Return Post_Monad\n                PostMonadOperations.weaken]; intros. 2: reflexivity.\n    (* spec_Bind *)\n    split; intros.\n    - destruct H as (mid & ? & ?).\n      (* can't get weakening because the type \"Post RiscvMachine A\" does not guarantee that all\n         its inhabitant were constructed using the RiscvProgram primitives *)\n  Abort.\n\n  Lemma preserve_undef_on{memOk: map.ok Mem}: forall n (m m': Mem) a w s,\n      Memory.store_bytes n m a w = Some m' ->\n      map.undef_on m s ->\n      map.undef_on m' s.\n  Proof.\n    eauto using map.same_domain_preserves_undef_on, Memory.store_bytes_preserves_domain.\n  Qed.\n\n  Global Instance MinimalMMIOPrimitivesSane{memOk: map.ok Mem} :\n    PrimitivesSane MinimalMMIOPrimitivesParams.\n  Abort.\n\n  Global Instance MinimalMMIOSatisfiesPrimitives{memOk: map.ok Mem} :\n    Primitives MinimalMMIOPrimitivesParams.\n  Abort.\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/MinimalMMIO_Post.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277512, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.17115238212928247}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\nRequire bedrock2Examples.Demos.\nRequire Import coqutil.Decidable.\nRequire Import compiler.ExprImp.\nRequire Import compiler.NameGen.\nRequire Import compiler.Pipeline.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Utility.Words32Naive.\nRequire Import riscv.Utility.DefaultMemImpl32.\nRequire Import riscv.Utility.Monads.\nRequire Import compiler.util.Common.\nRequire Import coqutil.Decidable.\nRequire        riscv.Utility.InstructionNotations.\nRequire Import riscv.Platform.MinimalLogging.\nRequire Import bedrock2.MetricLogging.\nRequire Import riscv.Platform.MetricMinimal.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Utility.Encode.\nRequire Import coqutil.Map.SortedList.\nRequire Import compiler.MemoryLayout.\nRequire Import compiler.StringNameGen.\nRequire Import riscv.Utility.InstructionCoercions.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire bedrock2.Hexdump.\nRequire Import bedrock2Examples.swap.\nRequire Import bedrock2Examples.stackalloc.\nRequire Import compilerExamples.SpillingTests.\n\nOpen Scope Z_scope.\nOpen Scope string_scope.\nOpen Scope ilist_scope.\n\nDefinition var: Set := Z.\nDefinition Reg: Set := Z.\n\n\nLocal Existing Instance DefaultRiscvState.\n\nAxiom TODO: forall {T: Type}, T.\n\nLocal Instance funpos_env: map.map string Z := SortedListString.map _.\n\nDefinition compile_ext_call(posenv: funpos_env)(mypos stackoffset: Z)(s: FlatImp.stmt Z) :=\n  match s with\n  | FlatImp.SInteract _ fname _ =>\n    if string_dec fname \"nop\" then\n      [[Addi Register0 Register0 0]]\n    else\n      nil\n  | _ => []\n  end.\n\nNotation RiscvMachine := MetricRiscvMachine.\n\nLocal Existing Instance coqutil.Map.SortedListString.map.\nLocal Existing Instance coqutil.Map.SortedListString.ok.\n\nDefinition main_stackalloc :=\n  (\"main\", ([]: list String.string, []: list String.string,\n     cmd.stackalloc \"x\" 4 (cmd.stackalloc \"y\" 4 (cmd.call [] \"swap_swap\" [expr.var \"x\"; expr.var \"y\"])))).\n\nDefinition allFuns: list Syntax.func := [swap; swap_swap; main_stackalloc; stacknondet; stackdisj; long1].\n\nDefinition e := map.putmany_of_list allFuns map.empty.\n\n(* stack grows from high addreses to low addresses, first stack word will be written to\n   (stack_pastend-8), next stack word to (stack_pastend-16) etc *)\nDefinition stack_pastend: Z := 2048.\n\nLemma f_equal2: forall {A B: Type} {f1 f2: A -> B} {a1 a2: A},\n    f1 = f2 -> a1 = a2 -> f1 a1 = f2 a2.\nProof. intros. congruence. Qed.\n\nLemma f_equal3: forall {A B C: Type} {f1 f2: A -> B -> C} {a1 a2: A} {b1 b2: B},\n    f1 = f2 -> a1 = a2 -> b1 = b2 -> f1 a1 b1 = f2 a2 b2.\nProof. intros. congruence. Qed.\n\nLemma f_equal3_dep: forall {A B C: Type} {f1 f2: A -> B -> C} {a1 a2: A} {b1 b2: B},\n    f1 = f2 -> a1 = a2 -> b1 = b2 -> f1 a1 b1 = f2 a2 b2.\nProof. intros. congruence. Qed.\n\n\nLocal Instance RV32I_bitwidth: FlatToRiscvCommon.bitwidth_iset 32 RV32I.\nProof. reflexivity. Qed.\n\nDefinition swap_asm: list Instruction.\n  let r := eval cbv in (compile compile_ext_call e) in set (res := r).\n  match goal with\n  | res := Success (?x, _, _) |- _ => exact x\n  end.\nDefined.\n\nModule PrintAssembly.\n  Import riscv.Utility.InstructionNotations.\n  Goal True. let r := eval unfold swap_asm in swap_asm in idtac (* r *). Abort.\n  (*\n  swap_swap:\n     addi    x2, x2, -20   // decrease sp\n     sw      x2, x1, 8     // save ra\n     sw      x2, x3, 0     // save registers modified by swap_swap\n     sw      x2, x4, 4\n     lw      x3, x2, 12    // load args\n     lw      x4, x2, 16\n     sw      x2, x3, -8    // store args for first call to swap\n     sw      x2, x4, -4\n     jal     x1, 36        // first call to swap\n     sw      x2, x3, -8    // store args for second call to swap\n     sw      x2, x4, -4\n     jal     x1, 24        // second call to swap\n     lw      x3, x2, 0     // restore registers modified by swap_swap\n     lw      x4, x2, 4\n     lw      x1, x2, 8     // load ra\n     addi    x2, x2, 20    // increase sp\n     jalr    x0, x1, 0     // return\n\n  swap:\n     addi    x2, x2, -28   // decrease sp\n     sw      x2, x1, 16    // save ra\n     sw      x2, x5, 0     // save registers modified by swap\n     sw      x2, x6, 4\n     sw      x2, x3, 8\n     sw      x2, x4, 12\n     lw      x3, x2, 20    // load args\n     lw      x4, x2, 24\n     lw      x5, x4, 0     // body of swap\n     lw      x6, x3, 0\n     sw      x4, x6, 0\n     sw      x3, x5, 0\n     lw      x5, x2, 0     // restore registers modified by swap\n     lw      x6, x2, 4\n     lw      x3, x2, 8\n     lw      x4, x2, 12\n     lw      x1, x2, 16    // restore ra\n     addi    x2, x2, 28    // increase sp\n     jalr    x0, x1, 0     // return\n\n  stacknondet:\n     addi    x2, x2, -56\n     sw      x2, x1, 44\n     sw      x2, x5, 4\n     sw      x2, x6, 8\n     sw      x2, x7, 12\n     sw      x2, x3, 16\n     sw      x2, x8, 20\n     sw      x2, x9, 24\n     sw      x2, x10, 28\n     sw      x2, x11, 32\n     sw      x2, x12, 36\n     sw      x2, x4, 40\n     addi    x5, x2, 0\n     lw      x6, x5, 0\n     addi    x7, x0, 8\n     srl     x3, x6, x7\n     addi    x8, x0, 3\n     add     x9, x3, x8\n     addi    x10, x0, 42\n     sb      x9, x10, 0\n     lw      x11, x5, 0\n     addi    x12, x0, 8\n     srl     x4, x11, x12\n     sw      x2, x3, 48\n     sw      x2, x4, 52\n     lw      x5, x2, 4\n     lw      x6, x2, 8\n     lw      x7, x2, 12\n     lw      x3, x2, 16\n     lw      x8, x2, 20\n     lw      x9, x2, 24\n     lw      x10, x2, 28\n     lw      x11, x2, 32\n     lw      x12, x2, 36\n     lw      x4, x2, 40\n     lw      x1, x2, 44\n     addi    x2, x2, 56\n     jalr    x0, x1, 0\n\n  stackdisj:\n     addi    x2, x2, -28\n     sw      x2, x1, 16\n     sw      x2, x3, 8\n     sw      x2, x4, 12\n     addi    x3, x2, 4\n     addi    x4, x2, 0\n     sw      x2, x3, 20\n     sw      x2, x4, 24\n     lw      x3, x2, 8\n     lw      x4, x2, 12\n     lw      x1, x2, 16\n     addi    x2, x2, 28\n     jalr    x0, x1, 0\n\n  main:\n     addi    x2, x2, -20   // decrease sp\n     sw      x2, x1, 16    // save ra\n     sw      x2, x3, 8     // save registers modified by main\n     sw      x2, x4, 12\n     addi    x3, x2, 4     // first stackalloc invocation returns sp+4\n     addi    x4, x2, 0     // second stackalloc invocation returns sp\n     sw      x2, x3, -8    // store args for call to swap_swap\n     sw      x2, x4, -4\n     jal     x1, -380      // call swap_swap\n     lw      x3, x2, 8     // restore registers modified by main\n     lw      x4, x2, 12\n     lw      x1, x2, 16    // restore ra\n     addi    x2, x2, 20    // increase sp\n     jalr    x0, x1, 0     // return\n  *)\nEnd PrintAssembly.\n\nDefinition swap_as_bytes: list Byte.byte := instrencode swap_asm.\n\nModule PrintBytes.\n  Import bedrock2.Hexdump.\n  Local Open Scope hexdump_scope.\n  Set Printing Width 100.\n  Goal True. let x := eval cbv in swap_as_bytes in idtac (* x *). Abort.\nEnd PrintBytes.\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/compilerExamples/swap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.17108743095730974}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\n(** Definition of matching relation between Coq and C representation *)\nFrom bpf.comm Require Import MemRegion Regs Flag ListAsArray.\nFrom compcert Require Import Coqlib Integers Values AST Clight Memory Memtype.\n\nFrom bpf.clightlogic Require Import Clightlogic.\nFrom bpf.verifier.comm Require Import state.\nFrom Coq Require Import ZArith.\nOpen Scope Z_scope.\n\nGlobal Transparent Archi.ptr64.\n\nDefinition match_list_ins (m:mem) (b: block) (l: list int64) :=\n  forall i, (0 <= i < List.length l)%nat ->\n    Mem.loadv AST.Mint64 m  (Vptr b (Ptrofs.repr (8 * (Z.of_nat i)))) = Some (Vlong (List.nth i l Int64.zero)).\n\nDefinition match_ins (ins_blk: block) (st: state.state) (m:mem) :=\n  List.length (ins st) = (ins_len st) /\\\n  Z.of_nat (List.length (ins st)) * 8 <= Ptrofs.max_unsigned /\\\n  match_list_ins m ins_blk (ins st).\n\n\nClass special_blocks : Type :=\n  { st_blk : block;\n    ins_blk  : block }.\n\nSection S.\n\n  Context {Blocks : special_blocks}.\n\n  Record match_state  (st: state.state) (m: mem) : Prop :=\n    {\n      munchange: Mem.unchanged_on (fun b _ => b <> st_blk /\\ b <> ins_blk) (bpf_m st) m;\n      mins_len : Mem.loadv AST.Mint32 m (Vptr st_blk (Ptrofs.repr 0)) = Some (Vint  (Int.repr (Z.of_nat (ins_len st)))) /\\ Z.of_nat (ins_len st) >= 1;\n      mins     : Mem.loadv AST.Mptr m (Vptr st_blk (Ptrofs.repr 4)) = Some (Vptr ins_blk (Ptrofs.repr 0)) /\\ match_ins ins_blk st m;\n      mperm    : Mem.range_perm m st_blk 0 8 Cur Freeable /\\\n                 Mem.range_perm m ins_blk 0 (Z.of_nat (ins_len st)) Cur Readable;\n      minvalid : (~Mem.valid_block (bpf_m st) st_blk /\\\n                  ~Mem.valid_block (bpf_m st) ins_blk) /\\\n                 (ins_blk <> st_blk) /\\\n                 (forall b, b <> st_blk /\\ b <> ins_blk ->\n                  Mem.valid_block m b -> Mem.valid_block (bpf_m st) b);\n    }.\n\nEnd S.\n\n#[global] Notation dcons := (DList.DCons (F:= fun x => x -> Inv state.state)).\n\nLtac split_conj :=\n  match goal with\n  | |- ?X <> ?Y /\\ _ =>\n    split; [intro Hfalse; inversion Hfalse | split_conj]\n  | |- ?X <> ?Y =>\n    intro Hfalse; inversion Hfalse\n  end.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/VerifierSimulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.17108742747700084}}
{"text": "Require Import Bool.\nRequire Import Word.\nRequire Import Balloc.\nRequire Import BFile Bytes Rec Inode.\nRequire Import String.\nRequire Import Pred.\nRequire Import Arith.\nRequire Import List ListUtils.\nRequire Import FunctionalExtensionality.\nRequire Import AsyncDisk.\nRequire Import DirCache.\nRequire Import DirTreeDef.\nRequire Import FSLayout.\nRequire Import GenSepN.\nRequire Import SepAuto.\n\nImport ListNotations.\n\nModule SDIR := CacheOneDir.\n\nSet Implicit Arguments.\n\n  (**\n   * Predicates capturing the representation invariant of a directory tree.\n   *)\n\n  Fixpoint tree_dir_names_pred' (dirents : list (string * dirtree)) : @pred _ string_dec (addr * bool) :=\n    match dirents with\n    | nil => emp\n    | (name, subtree) :: dirlist' => name |-> (dirtree_inum subtree, dirtree_isdir subtree) * tree_dir_names_pred' dirlist'\n    end.\n\n  Definition tree_dir_names_pred ibxp (dir_inum : addr) (dirents : list (string * dirtree)) \n                                 : @pred _ eq_nat_dec _ := (\n    exists f dsmap,\n    dir_inum |-> f *\n    [[ IAlloc.ino_valid ibxp dir_inum ]] *\n    [[ SDIR.rep f dsmap ]] *\n    [[ tree_dir_names_pred' dirents dsmap ]])%pred.\n\n  Section DIRITEM.\n\n    Variable F : dirtree -> @pred nat eq_nat_dec BFILE.bfile.\n    Variable Fexcept : dirtree -> @pred nat eq_nat_dec BFILE.bfile.\n\n    Fixpoint dirlist_pred (dirlist : list (string * dirtree)) : @pred _ eq_nat_dec _ := (\n      match dirlist with\n      | nil => emp\n      | (_, e) :: dirlist' => F e * dirlist_pred dirlist'\n      end)%pred.\n\n    Fixpoint dirlist_pred_except (name : string) (dirlist : list (string * dirtree)) : @pred _ eq_nat_dec _ := (\n      match dirlist with\n      | nil => emp\n      | (ename, e) :: dirlist' =>\n        (if string_dec ename name then Fexcept e else F e) * dirlist_pred_except name dirlist'\n      end)%pred.\n\n\n    Variable UpdateF : dirtree -> dirtree.\n\n    Fixpoint dirlist_update (dirlist : list (string * dirtree)) : list (string * dirtree) :=\n      match dirlist with\n      | nil => nil\n      | (name, subtree) :: dirlist' => (name, UpdateF subtree) :: (dirlist_update dirlist')\n      end.\n\n\n    Variable T : Type.\n    Variable CombineF : dirtree -> list T.\n\n    Fixpoint dirlist_combine (dirlist : list (string * dirtree)) : list T :=\n      match dirlist with\n      | nil => nil\n      | (name, subtree) :: dirlist' => (CombineF subtree) ++ (dirlist_combine dirlist')\n      end.\n\n  End DIRITEM.\n\n  Lemma dirlist_combine_app: forall l (f : dirtree -> list addr) a,\n    dirlist_combine f (a::l) = dirlist_combine f [a] ++ (dirlist_combine f l).\n  Proof.\n    intros. \n    rewrite cons_app.\n    unfold dirlist_combine; subst; simpl.\n    destruct a.\n    rewrite app_nil_r; eauto.\n  Qed.\n\n\n  Fixpoint tree_pred ibxp e := (\n    match e with\n    | TreeFile inum f =>\n      exists cache,\n      inum |-> (BFILE.mk_bfile (DFData f) (DFAttr f) cache) * [[ IAlloc.ino_valid ibxp inum ]]\n    | TreeDir inum s => tree_dir_names_pred ibxp inum s * dirlist_pred (tree_pred ibxp) s\n    end)%pred.\n\n  Fixpoint tree_pred_except ibxp (fnlist : list string) e {struct fnlist} :=  (\n    match fnlist with\n    | nil => emp\n    | fn :: suffix =>\n      match e with\n      | TreeFile inum f =>\n        exists cache,\n        inum |-> (BFILE.mk_bfile (DFData f) (DFAttr f) cache) * [[ IAlloc.ino_valid ibxp inum ]]\n      | TreeDir inum s => tree_dir_names_pred ibxp inum s *\n                          dirlist_pred_except (tree_pred ibxp) (tree_pred_except ibxp suffix) fn s\n      end\n    end)%pred.\n\n\n  Fixpoint dirtree_update_inode t inum off v :=\n    match t with\n    | TreeFile inum' f => if (addr_eq_dec inum inum') then\n          let f' := mk_dirfile (updN (DFData f) off v) (DFAttr f) in (TreeFile inum f')\n          else (TreeFile inum' f)\n    | TreeDir inum' ents =>\n      TreeDir inum' (dirlist_update (fun t' => dirtree_update_inode t' inum off v) ents)\n    end.\n\n  (**\n   * Theorems about extracting and folding back subtrees from a tree.\n   *)\n  Lemma dirlist_pred_except_notfound : forall xp l fnlist name,\n    ~ In name (map fst l) ->\n    dirlist_pred (tree_pred xp) l <=p=>\n      dirlist_pred_except (tree_pred xp) (tree_pred_except xp fnlist) name l.\n  Proof.\n    induction l; simpl; intros; auto.\n    split; destruct a.\n    destruct (string_dec s name); subst.\n    edestruct H. eauto.\n    cancel. apply IHl; auto.\n\n    destruct (string_dec s name); subst.\n    edestruct H. eauto.\n    cancel. apply IHl; auto.\n  Qed.\n\n  Lemma tree_dir_names_pred'_app : forall l1 l2,\n    tree_dir_names_pred' (l1 ++ l2) <=p=> tree_dir_names_pred' l1 * tree_dir_names_pred' l2.\n  Proof.\n    split; induction l1; simpl; intros.\n    cancel.\n    destruct a; destruct d; cancel; eauto.\n    cancel.\n    destruct a; destruct d; cancel; rewrite sep_star_comm; eauto.\n  Qed.\n\n  Lemma dir_names_distinct' : forall l m F,\n    (F * tree_dir_names_pred' l)%pred m ->\n    NoDup (map fst l).\n  Proof.\n    induction l; simpl; intros.\n    constructor.\n    destruct a; simpl in *.\n    destruct d.\n    - constructor; [| eapply IHl; pred_apply' H; cancel ].\n      intro Hin.\n      apply in_map_iff in Hin. repeat deex. destruct x.\n      apply in_split in H2. repeat deex.\n      eapply ptsto_conflict_F with (a := s). pred_apply' H.\n      rewrite tree_dir_names_pred'_app. simpl.\n      destruct d; cancel.\n    - constructor; [| eapply IHl; pred_apply' H; cancel ].\n      intro Hin.\n      apply in_map_iff in Hin. repeat deex. destruct x.\n      apply in_split in H2. repeat deex.\n      eapply ptsto_conflict_F with (a := s). pred_apply' H.\n      rewrite tree_dir_names_pred'_app. simpl.\n      destruct d; cancel.\n      cancel.\n  Qed.\n\n  Lemma dir_names_distinct : forall xp l w,\n    tree_dir_names_pred xp w l =p=> tree_dir_names_pred xp w l * [[ NoDup (map fst l) ]].\n  Proof.\n    unfold tree_dir_names_pred; intros.\n    cancel; eauto.\n    eapply dir_names_distinct'.\n    pred_apply' H1. cancel.\n  Qed.\n\n  Section DIRTREE_IND2.\n\n    Variable P : dirtree -> Prop.\n    Variable dirtree_ind2' : forall (t : dirtree), P t.\n    Variable dirtree_ind2_Hdir : forall inum tree_ents,\n                                 Forall P (map snd tree_ents) -> P (TreeDir inum tree_ents).\n\n    Fixpoint dirtree_ind2_list (tree_ents : list (string * dirtree)) (inum : addr) :\n                               P (TreeDir inum tree_ents).\n      apply dirtree_ind2_Hdir.\n      induction tree_ents; simpl.\n      constructor.\n      constructor.\n      apply dirtree_ind2'.\n      apply IHtree_ents.\n    Defined.\n\n  End DIRTREE_IND2.\n\n  Fixpoint dirtree_ind2 (P : dirtree -> Prop)\n                        (Hfile : forall inum bf, P (TreeFile inum bf))\n                        (Hdir : forall inum tree_ents,\n                         Forall P (map snd tree_ents) -> P (TreeDir inum tree_ents))\n                        (d : dirtree) {struct d} : P d.\n    refine\n      match d with\n      | TreeFile inum bf => _\n      | TreeDir inum tree_ents => _\n      end.\n    apply Hfile.\n    specialize (dirtree_ind2 P Hfile Hdir).\n    apply dirtree_ind2_list.\n    apply dirtree_ind2.\n    apply Hdir.\n  Defined.\n\n  Lemma dirlist_pred_split : forall a b f,\n    (dirlist_pred f (a ++ b) <=p=> dirlist_pred f a * dirlist_pred f b)%pred.\n  Proof.\n    induction a; simpl; intros.\n    - split. cancel. cancel.\n    - destruct a. split.\n      cancel. apply IHa.\n      cancel. rewrite IHa. cancel.\n  Qed.\n\n  Theorem subtree_fold : forall xp fnlist tree subtree,\n    find_subtree fnlist tree = Some subtree ->\n    tree_pred_except xp fnlist tree * tree_pred xp subtree =p=> tree_pred xp tree.\n  Proof.\n    induction fnlist; simpl; intros.\n    - inversion H; subst. cancel.\n    - destruct tree; try discriminate; simpl.\n      rewrite dir_names_distinct at 1.\n      cancel.\n      induction l; simpl in *; try discriminate.\n      destruct a0; simpl in *.\n      destruct (string_dec s a); subst.\n      + rewrite sep_star_assoc_2.\n        rewrite sep_star_comm with (p1 := tree_pred xp subtree).\n        rewrite IHfnlist; eauto.\n        cancel.\n        apply dirlist_pred_except_notfound; eauto.\n        inversion H4; eauto.\n      + cancel.\n        rewrite sep_star_comm.\n        eapply H0.\n        inversion H4; eauto.\n  Qed.\n\n  Theorem subtree_extract : forall xp fnlist tree subtree,\n    find_subtree fnlist tree = Some subtree ->\n    tree_pred xp tree =p=> tree_pred_except xp fnlist tree * tree_pred xp subtree.\n  Proof.\n    induction fnlist; simpl; intros.\n    - inversion H; subst. cancel.\n    - destruct tree; try discriminate; simpl.\n      rewrite dir_names_distinct at 1; cancel.\n      induction l; simpl in *; try discriminate.\n      destruct a0; simpl in *.\n      destruct (string_dec s a); subst.\n      + rewrite IHfnlist; eauto.\n        cancel.\n        apply dirlist_pred_except_notfound.\n        inversion H3; eauto.\n      + cancel.\n        inversion H3; eauto.\n  Qed.\n\n\n\n  (**\n   * XXX\n   * Might be useful to have another theorem about how pathname-to-inode mappings\n   * are preserved across [update_subtree] for other paths.  In particular, if we\n   * do an [update_subtree] for some path [p] to a new subtree [subtree], then\n   * paths that do not start with [p] should not be affected.  Furthermore, paths\n   * [p' = p ++ suffix] should also be unaffected if:\n   *\n   *   find_subtree suffix subtree = find_subtree p' tree\n   *\n   * However, it's not clear yet who needs this kind of theorem.  This might be\n   * necessary for applications above FS.v, because they will have to prove that\n   * their file descriptors / inode numbers remain valid after they performed\n   * some operation on the tree.\n   *)\n\n  Lemma tree_dir_extract_subdir : forall xp l F dmap name inum,\n    (F * name |-> (inum, true))%pred dmap\n    -> tree_dir_names_pred' l dmap\n    -> dirlist_pred (tree_pred xp) l =p=>\n       exists F s, F * tree_pred xp (TreeDir inum s) *\n       [[ forall dnum, find_subtree [name] (TreeDir dnum l) = Some (TreeDir inum s) ]].\n  Proof.\n    induction l; intros.\n    - simpl in *. apply ptsto_valid' in H. congruence.\n    - destruct a. destruct d. simpl in *.\n      + apply ptsto_mem_except in H0 as H0'.\n        rewrite IHl. cancel.\n        eassign s0; eassign inum; cancel.\n\n        apply sep_star_comm in H.\n        pose proof (ptsto_diff_ne H0 H).\n        destruct (string_dec s name). exfalso. apply H2; eauto. congruence. eauto.\n\n        2: eauto.\n        apply sep_star_comm in H.\n        pose proof (ptsto_diff_ne H0 H).\n        destruct (string_dec name s). exfalso. apply H1; eauto.\n        congruence.\n        apply sep_star_comm.\n        eapply ptsto_mem_except_exF; eauto.\n      + destruct (string_dec name s); subst.\n        * apply ptsto_valid in H0. apply ptsto_valid' in H.\n          rewrite H in H0. inversion H0. subst.\n          cancel. instantiate (s0 := l0). cancel.\n          destruct (string_dec s s); congruence.\n        * apply ptsto_mem_except in H0. simpl.\n          rewrite IHl. cancel.\n          eassign s0; eassign inum; cancel.\n          destruct (string_dec s name); try congruence; eauto.\n          2: eauto.\n          apply sep_star_comm. eapply ptsto_mem_except_exF; eauto.\n          pred_apply; cancel.\n  Qed.\n\n  Lemma tree_dir_extract_file : forall xp l F dmap name inum,\n    (F * name |-> (inum, false))%pred dmap\n    -> tree_dir_names_pred' l dmap\n    -> dirlist_pred (tree_pred xp) l =p=>\n       exists F bfile, F * tree_pred xp (TreeFile inum bfile) *\n       [[ forall dnum, find_subtree [name] (TreeDir dnum l) = Some (TreeFile inum bfile) ]].\n  Proof.\n    induction l; intros.\n    - simpl in *. apply ptsto_valid' in H. congruence.\n    - destruct a. destruct d; simpl in *.\n      + destruct (string_dec name s); subst.\n        * apply ptsto_valid in H0. apply ptsto_valid' in H.\n          rewrite H in H0; inversion H0. subst. cancel.\n          destruct (string_dec s s); congruence.\n        * apply ptsto_mem_except in H0.\n          rewrite IHl with (inum:=inum). cancel.\n          destruct (string_dec s name); try congruence; eauto.\n          2: eauto.\n          apply sep_star_comm. eapply ptsto_mem_except_exF.\n          pred_apply; cancel. congruence.\n      + apply ptsto_mem_except in H0 as H0'.\n        rewrite IHl with (inum:=inum). cancel.\n\n        apply sep_star_comm in H.\n        pose proof (ptsto_diff_ne H0 H).\n        destruct (string_dec s name). exfalso. apply H2; eauto. congruence. eauto.\n\n        2: eauto.\n        apply sep_star_comm in H.\n        pose proof (ptsto_diff_ne H0 H).\n        destruct (string_dec name s). exfalso. apply H1; eauto.\n        congruence.\n        apply sep_star_comm. eapply ptsto_mem_except_exF; eauto.\n  Qed.\n\n  Lemma find_subtree_file : forall xp dlist name inum F A B dmap reclst isub bfmem bfsub,\n    (F * name |-> (isub, false))%pred dmap\n    -> tree_dir_names_pred' dlist dmap\n    -> (B * dirlist_pred (tree_pred xp) dlist)%pred bfmem\n    -> (A * tree_pred xp (TreeFile isub bfsub))%pred bfmem\n    -> find_subtree (name :: reclst) (TreeDir inum dlist) \n                   = find_subtree reclst (TreeFile isub bfsub).\n  Proof.\n    induction dlist; simpl; intros.\n    apply ptsto_valid' in H. congruence.\n    destruct a. unfold find_subtree_helper at 1.\n    destruct (string_dec s name); subst.\n    - apply ptsto_valid' in H. apply ptsto_valid in H0.\n      rewrite H in H0; inversion H0.\n      destruct d. simpl in *; subst; f_equal.\n      destruct_lift H1; destruct_lift H2.\n      apply sep_star_assoc_1 in H1.\n      setoid_rewrite sep_star_comm in H1.\n      apply sep_star_assoc_2 in H1.\n      apply ptsto_valid' in H1. apply ptsto_valid' in H2.\n      rewrite H1 in H2. inversion H2. subst; auto.\n      destruct d; destruct bfsub; simpl in *; congruence.\n      simpl in H0; congruence.\n    - simpl in *.\n      eapply IHdlist. exact inum.\n      apply sep_star_comm. eapply ptsto_mem_except_exF.\n      apply sep_star_comm; eauto. eauto.\n      apply ptsto_mem_except in H0; eauto. 2: eauto.\n      pred_apply' H1; cancel.\n  Qed.\n\n  Lemma find_name_file : forall xp dlist name inum F A B dmap reclst isub bfmem bfsub,\n    (F * name |-> (isub, false))%pred dmap\n    -> tree_dir_names_pred' dlist dmap\n    -> (B * dirlist_pred (tree_pred xp) dlist)%pred bfmem\n    -> (A * tree_pred xp (TreeFile isub bfsub))%pred bfmem\n    -> find_name (name :: reclst) (TreeDir inum dlist) = find_name reclst (TreeFile isub bfsub).\n  Proof.\n    intros; unfold find_name.\n    erewrite find_subtree_file; eauto.\n  Qed.\n\n  Lemma find_subtree_helper_dec : forall xp l name rec F F' m dmap,\n    (F * dirlist_pred (tree_pred xp) l * F')%pred m\n    -> tree_dir_names_pred' l dmap\n    -> (fold_right (@find_subtree_helper dirtree rec name) None l = None /\\\n        dmap name = None) \\/\n       (exists inum f,\n        dmap name = Some (inum, false) /\\\n        fold_right (find_subtree_helper rec name) None l = rec (TreeFile inum f)) \\/\n       (exists inum sublist F',\n        dmap name = Some (inum, true) /\\\n        fold_right (find_subtree_helper rec name) None l = rec (TreeDir inum sublist) /\\\n        (F' * dirlist_pred (tree_pred xp) sublist * tree_dir_names_pred xp inum sublist)%pred m).\n  Proof.\n    induction l; simpl; intros.\n    - left. intuition.\n    - destruct a; simpl in *.\n      destruct (string_dec s name); subst.\n      + right.\n        apply ptsto_valid in H0.\n        destruct d; simpl in *.\n        * left. do 2 eexists. intuition eauto.\n        * right. do 3 eexists. intuition eauto.\n          pred_apply. cancel.\n      + apply ptsto_mem_except in H0.\n        edestruct IHl with (m:=m) (rec:=rec) (name:=name); eauto.\n        pred_apply. cancel.\n        eassign F'. cancel.\n        * left. intuition. unfold mem_except in *. destruct (string_dec name s); congruence.\n        * right. unfold mem_except in *. destruct (string_dec name s); congruence.\n  Qed.\n\n  Lemma find_name_subdir'' : forall xp fnlist inum l0 l1 A B m,\n    (A * dirlist_pred (tree_pred xp) l0 * tree_dir_names_pred xp inum l0)%pred m\n    -> (B * dirlist_pred (tree_pred xp) l1 * tree_dir_names_pred xp inum l1)%pred m\n    -> find_name fnlist (TreeDir inum l0) = find_name fnlist (TreeDir inum l1).\n  Proof.\n    unfold find_name.\n    induction fnlist; simpl; intros; auto.\n    assert (H' := H); assert (H0' := H0).\n    unfold tree_dir_names_pred in H, H0.\n    destruct_lift H; destruct_lift H0.\n    apply ptsto_valid' in H. apply ptsto_valid' in H0.\n    rewrite H in H0; inversion H0; subst.\n    pose proof (SDIR.rep_mem_eq H6 H9); subst.\n    edestruct (find_subtree_helper_dec xp l0 a) with (F:=A) (rec:=find_subtree fnlist) as [HA|HA'];\n      edestruct (find_subtree_helper_dec xp l1 a) with (F:=B) (rec:=find_subtree fnlist) as [HB|HB']; eauto;\n      try destruct HA'; try destruct HB'; repeat deex; intuition; try congruence.\n    - rewrite H1; rewrite H3. auto.\n    - rewrite H4; rewrite H11.\n      rewrite H3 in H2. inversion H2; subst.\n      destruct fnlist; simpl; eauto.\n    - rewrite H2; rewrite H1.\n      rewrite H3 in H4. inversion H4; subst.\n      eauto.\n  Qed.\n\n  Lemma find_name_subdir' : forall xp inum dlist name A B dmap reclst isub bfmem dlsub,\n    dmap name = Some (isub, true)\n    -> tree_dir_names_pred' dlist dmap\n    -> (B * dirlist_pred (tree_pred xp) dlist)%pred bfmem\n    -> (A * tree_pred xp (TreeDir isub dlsub))%pred bfmem\n    -> find_name (name :: reclst) (TreeDir inum dlist) \n                   = find_name reclst (TreeDir isub dlsub).\n  Proof.\n    unfold find_name.\n    unfold find_subtree; fold find_subtree.\n    induction dlist; simpl; intros.\n    congruence.\n    destruct a. unfold find_subtree_helper at 1.\n    destruct (string_dec s name); subst.\n    - destruct d; simpl in *.\n      apply ptsto_valid in H0; rewrite H0 in *; congruence.\n      apply ptsto_valid in H0. rewrite H0 in H; inversion H; subst.\n      eapply find_name_subdir'' with (xp := xp).\n      pred_apply' H1. cancel.\n      pred_apply' H2. cancel.\n    - apply ptsto_mem_except in H0.\n      eapply IHdlist.\n      2: eauto.\n      unfold mem_except; destruct (string_dec name s); congruence.\n      pred_apply' H1. cancel.\n      pred_apply' H2. cancel.\n  Qed.\n\n  Lemma find_name_subdir : forall xp dlist name inum F A B dmap reclst isub bfmem dlsub,\n    (F * name |-> (isub, true))%pred dmap\n    -> tree_dir_names_pred' dlist dmap\n    -> (B * dirlist_pred (tree_pred xp) dlist)%pred bfmem\n    -> (A * tree_pred xp (TreeDir isub dlsub))%pred bfmem\n    -> find_name (name :: reclst) (TreeDir inum dlist) \n                   = find_name reclst (TreeDir isub dlsub).\n  Proof.\n    intros. apply ptsto_valid' in H.\n    eapply find_name_subdir'; eauto.\n  Qed.\n\n\n  Lemma find_subtree_none : forall dlist dmap name fnlist dnum,\n    notindomain name dmap\n    -> tree_dir_names_pred' dlist dmap\n    -> find_subtree (name :: fnlist) (TreeDir dnum dlist) = None.\n  Proof.\n    induction dlist; simpl; intros; auto.\n    destruct a. unfold find_subtree_helper at 1.\n    destruct (string_dec s name); subst.\n    apply ptsto_valid in H0. congruence.\n    eapply notindomain_mem_except' in H.\n    apply ptsto_mem_except in H0.\n    simpl in *. eapply IHdlist; eauto.\n  Qed.\n\n  Lemma find_name_none : forall dlist dmap fnlist dnum name,\n    notindomain name dmap\n    -> tree_dir_names_pred' dlist dmap\n    -> find_name (name :: fnlist) (TreeDir dnum dlist) = None.\n  Proof.\n    unfold find_name; intros.\n    erewrite find_subtree_none; eauto.\n  Qed.\n\n  Lemma dirname_not_in' : forall ents F name m,\n    (tree_dir_names_pred' ents * F)%pred m ->\n    notindomain name m ->\n    ~ In name (map fst ents).\n  Proof.\n    induction ents; simpl; intros; auto.\n    destruct a; simpl in *; intuition; subst.\n    apply sep_star_assoc in H.\n    apply ptsto_valid in H; congruence.\n    eapply IHents; eauto.\n    pred_apply' H; cancel.\n  Qed.\n\n  Lemma dirname_not_in : forall ents name m,\n    tree_dir_names_pred' ents m ->\n    notindomain name m ->\n    ~ In name (map fst ents).\n  Proof.\n    intros.\n    eapply dirname_not_in'; eauto.\n    pred_apply' H; cancel.\n  Qed.\n\n\n  Lemma dir_names_pred_delete' : forall l name m,\n    tree_dir_names_pred' l m\n    -> tree_dir_names_pred' (delete_from_list name l) (mem_except m name).\n  Proof.\n    induction l; simpl; intros; auto.\n    apply emp_mem_except; auto.\n    destruct a.\n    destruct (string_dec s name); subst.\n    apply ptsto_mem_except in H; auto.\n    simpl.\n    eapply ptsto_mem_except_F; eauto.\n  Qed.\n\n  Lemma dir_names_delete : forall xp dlist name dnum dfile dmap,\n    tree_dir_names_pred' dlist dmap\n    -> SDIR.rep dfile (mem_except dmap name)\n    -> IAlloc.ino_valid xp dnum\n    -> (dnum |-> dfile) =p=> tree_dir_names_pred xp dnum (delete_from_list name dlist).\n  Proof.\n    destruct dlist; simpl; intros; auto.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n    apply emp_mem_except; eauto.\n\n    destruct p.\n    destruct (string_dec s name); subst.\n    apply ptsto_mem_except in H.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n\n    unfold tree_dir_names_pred; simpl.\n    cancel; eauto.\n    eapply ptsto_mem_except_F; eauto; intros.\n    apply dir_names_pred_delete'; auto.\n  Qed.\n\n  Lemma dirlist_delete_file : forall xp dlist name inum dmap,\n    tree_dir_names_pred' dlist dmap\n    -> (name |-> (inum, false) * exists F, F)%pred dmap\n    -> dirlist_pred (tree_pred xp) dlist =p=>\n        (inum |->?) * dirlist_pred (tree_pred xp) (delete_from_list name dlist).\n  Proof.\n    induction dlist; simpl; intros; auto.\n    destruct_lift H0.\n    apply ptsto_valid in H0; congruence.\n\n    destruct a.\n    destruct (string_dec s name); subst.\n    destruct_lift H0.\n    apply ptsto_valid in H.\n    apply ptsto_valid in H0.\n    rewrite H in H0; inversion H0.\n    destruct d; simpl in *; try congruence.\n    cancel.\n\n    simpl.\n    apply ptsto_mem_except in H.\n    rewrite <- sep_star_assoc.\n    rewrite IHdlist with (inum:=inum); eauto.\n    cancel.\n    eapply ptsto_mem_except_exF; eauto.\n  Qed.\n\n\n  Lemma dlist_is_nil : forall d l m,\n    SDIR.rep d m -> emp m\n    -> tree_dir_names_pred' l m\n    -> l = nil.\n  Proof.\n    intros; destruct l; simpl in *; auto.\n    destruct p.\n    apply ptsto_valid in H1; congruence.\n  Qed.\n\n  Lemma dirlist_pred_except_delete_eq' : forall xp l name,\n    NoDup (map fst l) ->\n    dirlist_pred_except (tree_pred xp) (tree_pred_except xp nil) name l\n    <=p=> dirlist_pred (tree_pred xp) (delete_from_list name l).\n  Proof.\n    induction l; simpl; intros; auto.\n    destruct a; inversion H; subst.\n    destruct (string_dec s name); subst.\n    rewrite dirlist_pred_except_notfound with (fnlist := nil); eauto.\n    split; cancel.\n    split; cancel; apply IHl; auto.\n  Qed.\n\n  Lemma dirlist_pred_except_delete : forall xp l m name,\n    tree_dir_names_pred' l m ->\n    dirlist_pred_except (tree_pred xp) (tree_pred_except xp nil) name l\n      <=p=> dirlist_pred (tree_pred xp) (delete_from_list name l).\n  Proof.\n    intros.\n    apply pimpl_star_emp in H.\n    apply dir_names_distinct' in H.\n    split; apply dirlist_pred_except_delete_eq'; eauto.\n  Qed.\n\n Lemma find_dirlist_exists' : forall l name m inum isdir,\n    tree_dir_names_pred' l m\n    -> (name |-> (inum, isdir) * exists F, F)%pred m\n    -> exists sub, find_dirlist name l = Some sub\n            /\\ inum = dirtree_inum sub /\\ isdir = dirtree_isdir sub.\n  Proof.\n    induction l; simpl; intros; auto.\n    destruct_lift H0.\n    apply ptsto_valid in H0; congruence.\n\n    destruct a.\n    destruct (string_dec s name); subst; eauto.\n    apply ptsto_valid in H; apply ptsto_valid in H0.\n    rewrite H in H0; inversion H0; subst; eauto.\n\n    apply ptsto_mem_except in H.\n    eapply IHl; eauto.\n    eapply ptsto_mem_except_exF; eauto.\n  Qed.\n\n  Lemma find_dirlist_exists : forall l name m F inum isdir,\n    tree_dir_names_pred' l m\n    -> (F * name |-> (inum, isdir))%pred m\n    -> exists sub, find_dirlist name l = Some sub\n         /\\ inum = dirtree_inum sub /\\ isdir = dirtree_isdir sub.\n  Proof.\n    intros; destruct_lift H.\n    eapply find_dirlist_exists'; eauto.\n    pred_apply; cancel.\n  Qed.\n\n  Lemma dirlist_extract' : forall xp l name sub,\n    find_dirlist name l = Some sub\n    -> NoDup (map fst l)\n    -> dirlist_pred (tree_pred xp) l =p=> tree_pred xp sub *\n                  dirlist_pred_except (tree_pred xp) (tree_pred_except xp nil) name l.\n  Proof.\n    induction l; simpl; intros; try congruence.\n    destruct a. destruct (string_dec s name).\n\n    inversion H; inversion H0; subst.\n    erewrite dirlist_pred_except_notfound with (name := name); eauto.\n    instantiate (1 := nil); cancel.\n\n    inversion H0; subst; clear H0.\n    rewrite <- sep_star_assoc.\n    setoid_rewrite <- sep_star_comm at 3.\n    rewrite sep_star_assoc.\n    rewrite <- IHl; eauto.\n  Qed.\n\n  Lemma dirlist_extract : forall xp F m l inum isdir name,\n    tree_dir_names_pred' l m\n    -> (F * name |-> (inum, isdir))%pred m\n    -> dirlist_pred (tree_pred xp) l =p=> (exists sub, tree_pred xp sub *\n         [[ inum = dirtree_inum sub  /\\ isdir = dirtree_isdir sub ]]) *\n         dirlist_pred_except (tree_pred xp) (tree_pred_except xp nil) name l.\n  Proof.\n    intros.\n    apply pimpl_star_emp in H as Hx.\n    apply dir_names_distinct' in Hx.\n    pose proof (find_dirlist_exists l H H0); deex.\n    cancel.\n    apply dirlist_extract'; auto.\n  Qed.\n\n  Lemma dirlist_extract_subdir : forall xp F m l inum name,\n    tree_dir_names_pred' l m\n    -> (F * name |-> (inum, true))%pred m\n    -> dirlist_pred (tree_pred xp) l =p=> \n           (exists s, tree_dir_names_pred xp inum s * dirlist_pred (tree_pred xp) s ) *\n            dirlist_pred_except (tree_pred xp) (tree_pred_except xp nil) name l.\n  Proof.\n    intros.\n    unfold pimpl; intros.\n    pose proof (dirlist_extract xp l H H0 m0 H1).\n    destruct_lift H2.\n    destruct dummy; simpl in *; subst; try congruence.\n    pred_apply; cancel.\n    eassign l0; cancel.\n  Qed.\n\n\n  Lemma ptsto_subtree_exists' : forall name ents dmap inum isdir,\n    tree_dir_names_pred' ents dmap\n    -> (name |-> (inum, isdir) * exists F, F)%pred dmap\n    -> exists subtree, find_dirlist name ents = Some subtree\n         /\\ inum = dirtree_inum subtree /\\ isdir = dirtree_isdir subtree.\n  Proof.\n    induction ents; simpl; intros; auto.\n    apply ptsto_valid in H0; congruence.\n    destruct a; simpl.\n    destruct (string_dec s name); subst.\n\n    apply ptsto_valid in H; apply ptsto_valid in H0.\n    rewrite H in H0; inversion H0; subst.\n    eexists; intuition.\n\n    apply ptsto_mem_except in H.\n    simpl in *; eapply IHents; eauto.\n    eapply ptsto_mem_except_exF; eauto.\n  Qed.\n\n  Lemma ptsto_subtree_exists : forall F name ents dmap inum isdir,\n    tree_dir_names_pred' ents dmap\n    -> (F * name |-> (inum, isdir))%pred dmap\n    -> exists subtree, find_dirlist name ents = Some subtree\n         /\\ inum = dirtree_inum subtree /\\ isdir = dirtree_isdir subtree.\n  Proof.\n    intros.\n    eapply ptsto_subtree_exists'; eauto.\n    pred_apply; cancel.\n  Qed.\n\n  Lemma fold_back_dir_pred : forall xp dnum dirfile ents dsmap,\n    tree_dir_names_pred' ents dsmap\n    -> SDIR.rep dirfile dsmap\n    -> IAlloc.ino_valid xp dnum\n    -> dnum |-> dirfile * dirlist_pred (tree_pred xp) ents =p=> tree_pred xp (TreeDir dnum ents).\n  Proof.\n    simpl; intros.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n  Qed.\n\n  Lemma dirlist_pred_extract : forall xp ents name subtree,\n    find_dirlist name ents = Some subtree\n    -> NoDup (delete_from_list name ents)\n    -> dirlist_pred (tree_pred xp) ents =p=>\n       tree_pred xp subtree * dirlist_pred (tree_pred xp) (delete_from_list name ents).\n  Proof.\n    induction ents; intros; auto.\n    inversion H.\n    destruct a; simpl in *.\n    destruct (string_dec s name); subst.\n    inversion H; subst; auto.\n    inversion H0; subst.\n    rewrite IHents; eauto.\n    cancel.\n  Qed.\n\n  Lemma tree_dir_names_pred_nodup : forall l m,\n    tree_dir_names_pred' l m -> NoDup l.\n  Proof.\n    intros.\n    eapply NoDup_map_inv.\n    eapply dir_names_distinct' with (m := m).\n    pred_apply; cancel.\n  Qed.\n\n  (* ugly lemmas for reordering sep_stars in the hypothesis *)\n  Lemma helper_reorder_sep_star_1 : forall AT AEQ V (a b c d e : @pred AT AEQ V),\n    a * b * c * d * e =p=> (b * c * d * e) * a.\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_reorder_sep_star_2 : forall AT AEQ V (a b c d : @pred AT AEQ V),\n    a * b * c * d =p=> a * c * d * b.\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_reorder_sep_star_3: forall AT AEQ V (a b c d e : @pred AT AEQ V),\n      (((a \u2736 b) \u2736 c) \u2736 d) \u2736 e =p=> (a * e) * b * c * d.\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_reorder_sep_star_4: forall AT AEQ V (a b c d: @pred AT AEQ V),\n      ((a \u2736 b) \u2736 c) \u2736 d  =p=> (d * a) * (b * c).\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma helper_reorder_sep_star_5: forall AT AEQ V (a b c d : @pred AT AEQ V),\n      ((a * b) * c) * d =p=> ((a * d) * c) * b.\n  Proof.\n    intros; cancel.\n  Qed.\n\n  Lemma notindomain_not_in_dirents : forall ents name dsmap,\n    tree_dir_names_pred' ents dsmap\n    -> notindomain name dsmap\n    -> ~ In name (map fst ents).\n  Proof.\n    induction ents; simpl; intros; auto.\n    destruct a; simpl in *; intuition.\n    apply ptsto_valid in H; congruence.\n    apply ptsto_mem_except in H.\n    eapply IHents; eauto.\n    apply notindomain_mem_except'; auto.\n  Qed.\n\n  Lemma dirlist_pred_absorb_notin' : forall xp ents name subtree,\n    ~ In name (map fst ents)\n    -> NoDup ents\n    -> tree_pred xp subtree * dirlist_pred (tree_pred xp) ents =p=>\n       dirlist_pred (tree_pred xp) (add_to_list name subtree ents).\n  Proof.\n    induction ents; simpl; intros; auto.\n    destruct a; intuition.\n    destruct (string_dec s name); subst; simpl in *.\n    inversion H0; subst; cancel.\n    inversion H0; subst.\n    rewrite <- IHents; eauto.\n    cancel.\n  Qed.\n\n  Lemma dirlist_pred_absorb_notin : forall xp ents name dsmap subtree,\n    tree_dir_names_pred' ents dsmap\n    -> notindomain name dsmap\n    -> tree_pred xp subtree * dirlist_pred (tree_pred xp) ents =p=>\n       dirlist_pred (tree_pred xp) (add_to_list name subtree ents).\n  Proof.\n    intros.\n    apply dirlist_pred_absorb_notin'; auto.\n    eapply notindomain_not_in_dirents; eauto.\n    eapply tree_dir_names_pred_nodup; eauto.\n  Qed.\n\n\n  Lemma dir_names_pred_add : forall l m name subtree,\n    tree_dir_names_pred' l m\n    -> tree_dir_names_pred' (add_to_list name subtree l)\n          (Mem.upd m name (dirtree_inum subtree, dirtree_isdir subtree)).\n  Proof.\n    induction l; simpl; intros; auto.\n    apply sep_star_comm.\n    apply ptsto_upd_disjoint; auto.\n\n    destruct a.\n    destruct (string_dec s name); subst; simpl.\n    eapply ptsto_upd; eauto.\n\n    generalize H.\n    unfold_sep_star; intuition.\n    repeat deex. exists m1. eexists.\n    intuition.\n    3: eapply IHl; eauto.\n\n    apply functional_extensionality; intro.\n    unfold Mem.upd, mem_union.\n    destruct (string_dec x name); subst; auto.\n    destruct (m1 name) eqn: Hx; auto.\n    unfold ptsto in H2; intuition.\n    pose proof (H3 _ n); congruence.\n\n    unfold mem_disjoint, Mem.upd.\n    intuition; repeat deex.\n    destruct (string_dec a name); subst; auto.\n    unfold ptsto in H2; intuition.\n    pose proof (H6 _ n); congruence.\n    unfold mem_disjoint in H0; repeat deex.\n    firstorder.\n  Qed.\n\n\n\n\n  Lemma dir_names_pred_add_delete : forall l m name subtree,\n    tree_dir_names_pred' (delete_from_list name l) m\n    -> notindomain name m\n    -> tree_dir_names_pred' (add_to_list name subtree l)\n          (Mem.upd m name (dirtree_inum subtree, dirtree_isdir subtree)).\n  Proof.\n    induction l; simpl; intros; auto.\n    apply sep_star_comm.\n    apply ptsto_upd_disjoint; auto.\n\n    destruct a. destruct (string_dec s name); subst; simpl in *.\n    apply sep_star_comm.\n    apply ptsto_upd_disjoint; auto.\n\n    generalize H.\n    unfold_sep_star; intros; repeat deex.\n    exists m1; eexists; intuition.\n    3: eapply IHl; eauto.\n\n    apply functional_extensionality; intro.\n    unfold Mem.upd, mem_union.\n    destruct (string_dec x name); subst; auto.\n    destruct (m1 name) eqn: Hx; auto.\n    unfold ptsto in H3; intuition.\n    pose proof (H4 _ n); congruence.\n\n    unfold mem_disjoint, Mem.upd.\n    intuition; repeat deex.\n    destruct (string_dec a name); subst; auto.\n    unfold ptsto in H3; intuition.\n    pose proof (H7 _ n); congruence.\n    unfold mem_disjoint in H1; repeat deex.\n    firstorder.\n    eapply notindomain_mem_union; eauto.\n  Qed.\n\n  Lemma dirlist_pred_add_notin: forall xp ents name subtree,\n    ~ In name (map fst ents)\n    -> NoDup (map fst ents)\n    -> dirlist_pred (tree_pred xp) (add_to_list name subtree ents)\n       =p=> tree_pred xp subtree * dirlist_pred (tree_pred xp) ents.\n  Proof.\n    induction ents; intros; simpl; auto.\n    destruct a. destruct (string_dec s name); subst; simpl.\n    cancel.\n    cancel.\n    inversion H0.\n    apply IHents; auto.\n  Qed.\n\n  Lemma dirlist_pred_add_delete : forall xp ents name subtree,\n    NoDup (map fst ents)\n    -> dirlist_pred (tree_pred xp) (add_to_list name subtree (delete_from_list name ents))\n       =p=> dirlist_pred (tree_pred xp) (add_to_list name subtree ents).\n  Proof.\n    induction ents; simpl; intros; auto.\n    destruct a.\n    destruct (string_dec s name); subst; simpl.\n    inversion H; subst.\n    apply dirlist_pred_add_notin; auto.\n    destruct (string_dec s name); subst; simpl.\n    congruence.\n    cancel; apply IHents.\n    inversion H; auto.\n  Qed.\n\n  Theorem tree_dir_names_pred_update' : forall fnlist subtree subtree' d,\n    find_subtree fnlist d = Some subtree ->\n    dirtree_inum subtree = dirtree_inum subtree' ->\n    dirtree_isdir subtree = dirtree_isdir subtree' ->\n    (dirtree_inum d, dirtree_isdir d) =\n    (dirtree_inum (update_subtree fnlist subtree' d),\n     dirtree_isdir (update_subtree fnlist subtree' d)).\n  Proof.\n    destruct fnlist; simpl; intros.\n    congruence.\n    destruct d; auto.\n  Qed.\n\n  Lemma tree_dir_names_pred'_distinct : forall l,\n    tree_dir_names_pred' l =p=> tree_dir_names_pred' l * [[ NoDup (map fst l) ]].\n  Proof.\n    unfold pimpl; intros.\n    assert ((emp * tree_dir_names_pred' l)%pred m) by (pred_apply; cancel).\n    apply dir_names_distinct' in H0 as Hnodup.\n    clear H0. pred_apply; cancel.\n  Qed.\n\n  Theorem tree_dir_names_pred_notfound : forall l fnlist subtree' name,\n    ~ In name (map fst l) ->\n    tree_dir_names_pred' l <=p=>\n    tree_dir_names_pred' (map (update_subtree_helper (update_subtree fnlist subtree') name) l).\n  Proof.\n    induction l; simpl; intros.\n    auto.\n    destruct a; simpl.\n    destruct (string_dec s name); subst; try intuition.\n    split; cancel; apply IHl; eauto.\n  Qed.\n\n  Theorem tree_dir_names_pred'_update : forall l fnlist subtree subtree' name,\n    fold_right (find_subtree_helper (find_subtree fnlist) name) None l = Some subtree ->\n    dirtree_inum subtree = dirtree_inum subtree' ->\n    dirtree_isdir subtree = dirtree_isdir subtree' ->\n    tree_dir_names_pred' l =p=>\n    tree_dir_names_pred' (map (update_subtree_helper (update_subtree fnlist subtree') name) l).\n  Proof.\n    intros; rewrite tree_dir_names_pred'_distinct; cancel.\n    induction l; simpl; intros.\n    cancel.\n\n    destruct a.\n    case_eq (update_subtree_helper (update_subtree fnlist subtree') name (s, d)); intros.\n    unfold update_subtree_helper in H2.\n    simpl in *.\n    destruct (string_dec s name); subst.\n    - inversion H2; clear H2; subst; simpl in *.\n      erewrite <- tree_dir_names_pred_update'; eauto. cancel.\n      apply tree_dir_names_pred_notfound. inversion H4; eauto.\n    - inversion H2; clear H2; subst; simpl in *.\n      cancel. apply H2. inversion H4; eauto.\n  Qed.\n\n\n  Theorem tree_dir_names_pred'_update_inv : forall l fnlist subtree subtree' name,\n    fold_right (find_subtree_helper (find_subtree fnlist) name) None l = Some subtree ->\n    dirtree_inum subtree = dirtree_inum subtree' ->\n    dirtree_isdir subtree = dirtree_isdir subtree' ->\n    tree_dir_names_pred' (map (update_subtree_helper (update_subtree fnlist subtree') name) l)\n    =p=> tree_dir_names_pred' l.\n  Proof.\n    intros; rewrite tree_dir_names_pred'_distinct; cancel.\n    induction l; simpl; intros.\n    cancel.\n\n    destruct a.\n    case_eq (update_subtree_helper (update_subtree fnlist subtree') name (s, d)); intros.\n    unfold update_subtree_helper in H2.\n    simpl in *.\n    destruct (string_dec s name); subst.\n    - inversion H2; clear H2; subst; simpl in *.\n      erewrite <- tree_dir_names_pred_update'; eauto. cancel.\n      apply tree_dir_names_pred_notfound. inversion H4; eauto.\n      erewrite <- update_subtree_preserve_name; eauto.\n    - inversion H2; clear H2; subst; simpl in *.\n      cancel. apply H2. inversion H4; eauto.\n  Qed.\n\n  Theorem tree_dir_names_pred_update : forall xp w l fnlist subtree subtree' name,\n    fold_right (find_subtree_helper (find_subtree fnlist) name) None l = Some subtree ->\n    dirtree_inum subtree = dirtree_inum subtree' ->\n    dirtree_isdir subtree = dirtree_isdir subtree' ->\n    tree_dir_names_pred xp w l <=p=>\n    tree_dir_names_pred xp w (map (update_subtree_helper (update_subtree fnlist subtree') name) l).\n  Proof.\n    unfold tree_dir_names_pred; intros; split; cancel; eauto.\n    match goal with | [ H: SDIR.rep _ _ |- _ ] => clear H end.\n    pred_apply.\n    eapply tree_dir_names_pred'_update; eauto.\n    match goal with | [ H: SDIR.rep _ _ |- _ ] => clear H end.\n    pred_apply.\n    eapply tree_dir_names_pred'_update_inv; eauto.\n  Qed.\n\n  Lemma dirlist_pred_except_notfound' : forall xp l fnlist name subtree',\n    ~ In name (map fst l) ->\n    dirlist_pred_except (tree_pred xp) (tree_pred_except xp fnlist) name l <=p=>\n    dirlist_pred (tree_pred xp) (map (update_subtree_helper (update_subtree fnlist subtree') name) l).\n  Proof.\n    induction l; simpl; intros.\n    auto.\n    destruct a; simpl. destruct (string_dec s name); subst.\n    - edestruct H. eauto.\n    - split; cancel; apply IHl; eauto.\n  Qed.\n\n  Lemma tree_pred_except_update : forall xp path inum ents l tree,\n    find_subtree path tree = Some (TreeDir inum ents)\n    -> tree_pred_except xp path (update_subtree path (TreeDir inum l) tree)\n    =p=> tree_pred_except xp path tree.\n  Proof.\n    induction path; intros; eauto.\n    destruct tree; simpl in *.\n    cancel.\n    rewrite <- tree_dir_names_pred_update; eauto.\n    rewrite dir_names_distinct at 1; cancel.\n\n    induction l0; simpl in *; intros; try congruence.\n    destruct a0; simpl in *.\n    destruct (string_dec s a); subst.\n    destruct (string_dec a a); try congruence.\n\n    inversion H3; subst.\n    rewrite <- dirlist_pred_except_notfound; auto.\n    rewrite <- dirlist_pred_except_notfound'; auto.\n    cancel.\n    eapply IHpath; eauto.\n    contradict H2.\n    erewrite <- update_subtree_preserve_name; eauto.\n\n    destruct (string_dec s a); subst; try congruence.\n    cancel.\n    inversion H3; eauto.\n  Qed.\n\n  Theorem subtree_absorb : forall xp fnlist tree subtree subtree',\n    find_subtree fnlist tree = Some subtree ->\n    dirtree_inum subtree = dirtree_inum subtree' ->\n    dirtree_isdir subtree = dirtree_isdir subtree' ->\n    tree_pred_except xp fnlist tree * tree_pred xp subtree' =p=>\n    tree_pred xp (update_subtree fnlist subtree' tree).\n  Proof.\n    induction fnlist; simpl; intros.\n    - inversion H; subst. cancel.\n    - destruct tree; try discriminate; simpl.\n      rewrite dir_names_distinct at 1; cancel.\n      rewrite tree_dir_names_pred_update; eauto.\n      cancel.\n\n      induction l; simpl in *; intros; try congruence.\n      destruct a0; simpl in *.\n      destruct (string_dec s a); subst.\n      + rewrite <- IHfnlist; eauto. cancel.\n        inversion H6.\n        apply dirlist_pred_except_notfound'; eauto.\n      + cancel.\n        inversion H6.\n        rewrite <- H2; eauto.\n        cancel.\n  Qed.\n\n  Lemma subtree_prune_absorb : forall F xp inum ents ri re f path name dsmap subtree,\n    find_subtree path (TreeDir ri re) = Some (TreeDir inum ents)\n    -> find_dirlist name ents = Some subtree\n    -> tree_dir_names_pred' (delete_from_list name ents) dsmap\n    -> SDIR.rep f dsmap\n    -> IAlloc.ino_valid xp inum\n    -> dirlist_pred (tree_pred xp) ents *\n       tree_pred_except xp path (TreeDir ri re) * F * inum |-> f\n    =p=> (tree_pred xp subtree * F) *\n          tree_pred xp (tree_prune inum ents path name (TreeDir ri re)).\n  Proof.\n    intros; unfold tree_prune.\n    erewrite <- subtree_absorb; eauto.\n    cancel.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n    eapply dirlist_pred_extract; eauto.\n    eapply tree_dir_names_pred_nodup; eauto.\n  Qed.\n\n\n  Lemma subtree_graft_absorb : forall xp inum ents root f path name dsmap subtree,\n    SDIR.rep f (Mem.upd dsmap name (dirtree_inum subtree, dirtree_isdir subtree))\n    -> find_subtree path root = Some (TreeDir inum ents)\n    -> tree_dir_names_pred' ents dsmap\n    -> notindomain name dsmap\n    -> IAlloc.ino_valid xp inum\n    -> inum |-> f * tree_pred xp subtree *\n       tree_pred_except xp path root * dirlist_pred (tree_pred xp) ents\n    =p=> tree_pred xp (tree_graft inum ents path name subtree root).\n  Proof.\n    intros; unfold tree_graft.\n    erewrite <- subtree_absorb; eauto.\n    cancel.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n    eapply dirlist_pred_absorb_notin; eauto.\n    apply dir_names_pred_add; auto.\n  Qed.\n\n\n  Lemma subtree_graft_absorb_delete : forall xp inum ents root f path name dsmap dsmap' subtree x,\n    SDIR.rep f (Mem.upd dsmap name (dirtree_inum subtree, dirtree_isdir subtree))\n    -> find_subtree path root = Some (TreeDir inum ents)\n    -> tree_dir_names_pred' (delete_from_list name ents) dsmap\n    -> tree_dir_names_pred' ents dsmap'\n    -> notindomain name dsmap\n    -> find_dirlist name ents = Some x\n    -> IAlloc.ino_valid xp inum\n    -> inum |-> f * tree_pred xp subtree *\n       tree_pred_except xp path (update_subtree path (TreeDir inum (delete_from_list name ents)) root) *\n       dirlist_pred (tree_pred xp) (delete_from_list name ents)\n    =p=> tree_pred xp (tree_graft inum ents path name subtree root).\n  Proof.\n    intros; unfold tree_graft.\n    erewrite <- subtree_absorb; eauto.\n    cancel.\n    unfold tree_dir_names_pred.\n    cancel; eauto.\n    rewrite tree_pred_except_update; eauto; cancel.\n    rewrite sep_star_comm.\n    rewrite dirlist_pred_absorb_notin; eauto.\n    apply dirlist_pred_add_delete.\n    eapply dir_names_distinct' with (m := dsmap').\n    pred_apply; cancel.\n    apply dir_names_pred_add_delete; auto.\n  Qed.\n\n  Lemma flist_crash_synced_file: forall F fsxp inum dirfile path tree flist flist',\n    (F * tree_pred fsxp (update_subtree path (TreeFile inum (synced_dirfile dirfile)) tree))%pred (list2nmem flist) ->\n    BFILE.flist_crash flist flist' ->\n    find_subtree path tree = Some (TreeFile inum dirfile) ->\n    (arrayN_ex (@ptsto _ _ _) flist' inum * inum |-> BFILE.synced_file (dirfile_to_bfile dirfile None))%pred (list2nmem flist').\n  Proof.\n    intros.\n    rewrite subtree_extract in H by (eauto using find_update_subtree).\n    cbn in *.\n    destruct_lifts.\n    unfold dirfile_to_bfile.\n    eapply pimpl_apply in H; [ eapply list2nmem_sel with (i := inum) in H as Hs | cancel].\n    eapply forall2_selN in H0 as Hf; eauto using list2nmem_inbound.\n    unfold BFILE.file_crash in Hf.\n    rewrite <- Hs in Hf. cbn in Hf.\n    deex.\n    denote Array.possible_crash_list as Hp.\n    apply Array.possible_crash_list_synced_list_eq in Hp. subst.\n    unfold BFILE.synced_file. cbn -[Array.synced_list].\n    denote (selN _ _ _ = _) as Hx.\n    rewrite <- Hx.\n    apply list2nmem_array_pick.\n    erewrite <- forall2_length by eauto.\n    eauto using list2nmem_inbound.\n  Unshelve.\n    all: try exact BFILE.bfile0.\n    all: eauto.\n  Qed.", "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/DirTreePred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.17107061934264994}}
{"text": "Require Import VST.msl.msl_direct.\n\nLemma feq_app {A} {B} : forall f g : A -> B,\n  f = g ->\n  forall a, f a = g a.\nProof.\n  intros. subst. trivial.\nQed.\n\nProgram Definition pcomp (p : pshare) (Pf : p <> pfullshare) : pshare :=\n  Share.comp p.\nNext Obligation.\n  do 2 intro.\n  apply unit_self_unit in H. clear x.\n  destruct p. destruct H as [? _]. simpl in *.\n  rewrite Share.glb_idem in H.\n  apply Pf. apply exist_ext.\n  apply Share.ord_antisym.\n  apply Share.top_correct.\n  rewrite <- (Share.comp_inv x).\n  rewrite H.\n  rewrite Share.ord_spec1.\n  rewrite <- (Share.comp_inv fullshare).\n  rewrite <- Share.demorgan1.\n  rewrite Share.lub_bot.\n  trivial.\nQed.\n\nProgram Definition plub (p1 p2 : pshare) : pshare :=\n  Share.lub p1 p2.\nNext Obligation.\n  do 2 intro.\n  destruct p1, p2, H.\n  simpl in *.\n  rewrite <- H0 in H.\n  rewrite Share.lub_assoc in H.\n  rewrite <- Share.distrib2 in H.\n  rewrite Share.glb_absorb in H. clear H0 x.\n  assert (x0 = Share.bot). {\n    apply Share.ord_antisym.\n    rewrite Share.ord_spec2.\n    pattern Share.bot at 1.\n    rewrite <- H.\n    rewrite <- Share.lub_assoc.\n    rewrite Share.lub_idem. trivial.\n    apply Share.bot_correct. }\n  subst x0.\n  apply (n Share.bot).\n  rewrite <- identity_unit_equiv.\n  apply bot_identity.\nQed.\n\nLemma rel_nonunit_nonunit : forall p1 p2 : pshare,\n  nonunit (Share.rel (proj1_sig p1) (proj1_sig p2)).\nProof.\n  destruct p1, p2.\n  intro. intro.\n  apply (@share_rel_nonidentity x x0).\n  intro. apply (n x).\n  rewrite identity_unit_equiv in H0. trivial.\n  intro. apply (n0 x0).\n  rewrite identity_unit_equiv in H0. trivial.\n  rewrite identity_unit_equiv.\n  simpl in H.\n  eapply unit_self_unit.\n  apply H.\nQed.\n\nProgram Definition pbow (p1 p2 : pshare) : pshare :=\n  Share.rel p1 p2.\nNext Obligation.\n  apply rel_nonunit_nonunit.\nQed.\n\nClass Shares (t : Type) : Type := mkShares {\n  shares_J : Join t;\n  shares_P : Perm_alg t;\n  shares_S : Sep_alg t;\n  shares_C : Canc_alg t;\n  share_0 : t;\n  share_0_identity : identity share_0;\n  share_identity_0 : forall x : t, identity x -> x = share_0;\n  share_1 : t;\n  share_1_top : forall x : t, join_sub x share_1;\n  share_mult : t -> t -> t;\n  share_mult_share_1 : forall x,\n    share_mult x share_1 = x;\n  share_share_1_mult : forall x,\n    share_mult share_1 x = x;\n  share_mult_share_0 : forall x,\n    share_mult x share_0 = share_0;\n  share_share_0_mult : forall x,\n    share_mult share_0 x = share_0;\n  share_mult_canc_left : forall x y z,\n    x <> share_0 ->\n    share_mult x y = share_mult x z ->\n    y = z;\n  share_mult_canc_right : forall x y z,\n    x <> share_0 ->\n    share_mult y x = share_mult z x ->\n    y = z;\n  share_mult_assoc : forall a b c : t,\n    share_mult a (share_mult b c) = share_mult (share_mult a b) c;\n  share_join_mult : forall a b c d : t,\n    join a b c ->\n    join (share_mult a d) (share_mult b d) (share_mult c d);\n  share_mult_join : forall a b c d : t,\n    join (share_mult a d) (share_mult b d) (share_mult c d) ->\n    join a b c;\n}.\n\nGoal forall a b c d : pshare,\n  join a b c ->\n  join (pbow d a) (pbow d b) (pbow d c).\nProof.\n  unfold pbow. intros.\n  destruct H. unfold lifted_obj in *. split; simpl in *.\n  rewrite <- Share.rel_preserves_glb.\n  rewrite H. apply Share.rel_bot1.\n  rewrite <- Share.rel_preserves_lub.\n  rewrite H0. trivial.\nQed.\n\nGoal forall a b c d : pshare,\n  join (pbow d a) (pbow d b) (pbow d c) ->\n  join a b c.\nProof.\n  unfold pbow. intros.\n  destruct H. split; unfold lifted_obj in *; simpl in *.\n  rewrite <- Share.rel_preserves_glb in H.\n  pose proof (Share.rel_bot1 (proj1_sig d)).\n  rewrite <- H1 in H.\n  apply Share.rel_inj_l in H. trivial.\n  pose proof (pshare_not_identity d).\n  intro. apply H2. rewrite identity_unit_equiv. destruct d. simpl in *. subst x.\n  split. apply Share.glb_bot. apply Share.lub_bot.\n  rewrite <- Share.rel_preserves_lub in H0.\n  apply Share.rel_inj_l in H0. trivial.\n  pose proof (pshare_not_identity d).\n  intro. apply H1. rewrite identity_unit_equiv. destruct d. simpl in *. subst x.\n  split. apply Share.glb_bot. apply Share.lub_bot.\nQed.\n\nExisting Instance shares_J.\nExisting Instance shares_P.\nExisting Instance shares_S.\nExisting Instance shares_C.\n\nLemma share_top_1 {A} `{Shares A}: forall x : A,\n  (forall y : A, join_sub y x) ->\n  x = share_1.\nProof.\n  intros.\n  specialize (H0 share_1).\n  pose proof (share_1_top x).\n  destruct H0 as [y ?].\n  destruct H1 as [z ?].\n  destruct (join_assoc H0 H1) as [e [? ?]].\n  apply split_identity in H2.\n  apply join_comm in H0. apply H2 in H0. auto.\n  eapply unit_identity. apply join_comm in H3. apply H3.\nQed.\n", "meta": {"author": "lexuanbach", "repo": "share-infer", "sha": "55dfe9e79a0fdca324565ebc46b138bb398aaafe", "save_path": "github-repos/coq/lexuanbach-share-infer", "path": "github-repos/coq/lexuanbach-share-infer/share-infer-55dfe9e79a0fdca324565ebc46b138bb398aaafe/ssl_coq/ssl_shares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.17107061231407403}}
{"text": "(* From iris Require Import program_logic.weakestpre. *)\n(* From iris.base_logic.lib Require Import invariants gen_heap wsat ghost_map. *)\nFrom iris.base_logic.lib Require Import ghost_map.\nFrom iris.program_logic Require Import weakestpre adequacy.\nFrom iris.proofmode Require Import tactics.\n(* From iris.base_logic.lib Require Import invariants gen_heap. *)\nFrom st.STLCmuVS Require Import lang logrel.definitions.\nFrom st.STLCmu Require Import types.\n(* From st.STLCmuST Require Import wkpre lang types. *)\n(* From st.backtranslations.st_sem.correctness.st_le_sem.logrel Require Import definition lift. *)\nFrom st Require Import resources.\n\nDefinition \u03a3 : gFunctors :=\n  #[inv\u03a3; ghost_map\u03a3 nat (val * val)].\n\nInstance STLCmuVS_irisGS_inst (H : invGS \u03a3) : irisGS STLCmuVS_lang \u03a3 :=\n  { iris_invGS := H;\n    state_interp \u03c3 _ \u03bas _ := True%I;\n    fork_post v := True%I;\n    num_laters_per_step _ := 0;\n    state_interp_mono _ _ _ _ := fupd_intro _ _;\n  }.\n\nInstance sem\u03a3_inst (H : invGS \u03a3) : sem\u03a3 \u03a3 :=\n  { irisGS_inst := _ ;\n    ghost_mapG_inst := _ ;\n  }.\n\nLemma exprel_adequate (e : expr) (e' : STLCmuVS.lang.expr)\n      (Hee' : \u2200 {\u03a3 : gFunctors} {sem\u03a3_inst : sem\u03a3 \u03a3}, \u22a2 exprel_typed MaybeStuck TUnit e e') :\n  STLCmuVS_halts e \u2192 STLCmuVS_halts e'.\nProof.\n  intros He. destruct He as (v & He).\n  cut (adequate MaybeStuck e tt (fun _ _ => STLCmuVS_halts e')).\n  { intro Ha. apply (adequate_result _ _ _ _ Ha [] tt v).\n    change ([?e], tt) with ((fun x => ([x], tt)) e).\n    eapply (rtc_congruence (fun x => ([x], tt))); eauto.\n    intros e1 e2 Hstep. rewrite /STLCmuVS_step in Hstep.\n    rewrite /erased_step /=. exists []. apply (step_atomic e1 tt e2 tt [] [] []); by simpl. }\n  apply (wp_adequacy \u03a3 STLCmuVS_lang MaybeStuck e tt (fun _ => STLCmuVS_halts e')).\n  { intros invGS_inst' \u03bas.\n    iExists (fun _ _ => True%I). iExists (fun _ => True%I).\n    iModIntro. iSplit; auto.\n    iDestruct (Hee' \u03a3 _) as \"Hee'\".\n    iApply (wp_wand with \"Hee'\").\n    iIntros (w) \"Hdes\". iDestruct \"Hdes\" as (w') \"[%He' _]\".\n    iPureIntro. by eexists.\n  }\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/STLCmuVS/logrel/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.17097469023386228}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import State Monad.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nCheck reg64_to_reg32.\nreg64_to_reg32\n     : val64_t -> DxMonad.M valu32_t\n\n*)\n\nSection Reg64_to_reg32.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(val:Type)].\n  Definition res : Type := (val:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := reg64_to_reg32.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_reg64_to_reg32.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (fun x => StateLess _ (val64_correct x))\n                    (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun x  => StateLess _ (val32_correct x).\n\n  Instance correct_function_reg64_to_reg32 : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _d.\n\n    unfold eval_inv, val64_correct in c0.\n    destruct c0 as (Hc_eq & (vl & Hvl_eq)).\n    subst.\n\n    (**according to the type of eval_pc:\n         static unsigned long long get_addl(unsigned long long x, unsigned long long y)\n       1. return value should be  x+y\n       2. the memory is same\n      *)\n    eexists; exists m, Events.E0.\n\n        split_and;auto;unfold step2.\n    -\n      repeat forward_star.\n    - unfold eval_inv,match_res.\n      simpl. unfold val32_correct.\n      split ; eauto.\n    - simpl.\n      constructor.\n      reflexivity.\n    - apply unmodifies_effect_refl.\n  Qed.\n\nEnd Reg64_to_reg32.\n\nExisting Instance correct_function_reg64_to_reg32.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_reg64_to_reg32.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.17097468816428577}}
{"text": "Require Import Coq.MSets.MSetInterface.\nRequire Import Coq.MSets.MSetProperties.\nRequire Import Coq.MSets.MSetAVL.\nRequire Import Coq.Structures.OrdersAlt.\n\nRequire Import CommonTacs.\nRequire Import Coqlib.  (* for proof_irrelevance *)\n\nRequire Import Xform.\nRequire Import Regexp.\nRequire Import ParserArg.\n\nImport X86_PARSER_ARG.\n\nSet Implicit Arguments.\n\n(** A set of regexps paired with xforms *)\nModule Type RESETXFORM.\n  Include WSetsOn REOrderedType.\n\n  (* note: in the rest t is the type for RESets *)\n\n  (** Given a RESet grammar, returns the types of values returned by the\n      grammar *)\n  Parameter re_set_type: t -> xtype.\n\n  Definition rs_xf_pair (ty:xtype) := {rs : t & re_set_type rs ->> xList_t ty }.\n\n  Definition re_xf_pair (ty:xtype) := {r : regexp & regexp_type r ->> xList_t ty}.\n\n  Parameter in_re_set: \n    forall (rs:t), list char_p -> xt_interp (re_set_type rs) -> Prop.\n\n  Definition in_re_xform ty (rx : re_xf_pair ty) s (v:xt_interp ty) := \n    let (r,x) := rx in \n    exists v', in_regexp r s v' /\\ List.In v (xinterp x v').\n\n  Definition in_re_set_xform ty (rx : rs_xf_pair ty) s (v:xt_interp ty) := \n    let (rs, f) := rx in \n    exists v', in_re_set rs s v' /\\ List.In v (xinterp f v').\n\n  Definition rx_equal ty (rx1 rx2: rs_xf_pair ty) := \n    forall s v, in_re_set_xform rx1 s v <-> in_re_set_xform rx2 s v.\n\n  Parameter in_re_set_empty : forall rs v, not (in_re_set empty rs v).\n\n  (* the following type for union_xform is motivated by the case of doing\n     partial derivatives over r1+r2\n        pdrv(a, r1+r2) =\n          let (rs1, f1) = pdrv(a, r1) in\n          let (rs2, f2) = pdrv(a, r2) in\n            union_xform (rs1, f1) (rs2, f2)\n  *)\n  Parameter union_xform: forall ty1,\n    rs_xf_pair ty1 -> rs_xf_pair ty1 -> rs_xf_pair ty1.\n  (* note: def equality may not be necessary here *)\n  Parameter union_xform_erase: forall ty1 rx1 rx2,\n    projT1 (@union_xform ty1 rx1 rx2) = union (projT1 rx1) (projT1 rx2).\n  Parameter union_xform_corr: forall ty rs1 rs2 str v,\n    in_re_set_xform (@union_xform ty rs1 rs2) str v <-> \n    in_re_set_xform rs1 str v \\/ in_re_set_xform rs2 str v.\n\n  Parameter empty_xform: forall ty, rs_xf_pair ty.\n  Parameter empty_xform_erase: forall ty, projT1 (@empty_xform ty) = empty.\n  Parameter empty_xform_corr: forall ty (s : list char_p) (v : xt_interp ty),\n    ~ in_re_set_xform (empty_xform ty) s v.\n\n  Parameter singleton_xform: forall r:regexp, rs_xf_pair (regexp_type r).\n  Parameter singleton_xform_erase: forall r, \n    projT1 (@singleton_xform r) = (singleton r).\n  Parameter singleton_xform_corr : forall r s v, \n    in_re_set_xform (singleton_xform r) s v <-> in_regexp r s v.\n\n  Parameter add_xform: \n    forall ty (rex: re_xf_pair ty) (rx: rs_xf_pair ty), rs_xf_pair ty.\n  Parameter add_xform_erase: \n    forall ty (rex:re_xf_pair ty) rx,\n      projT1 (add_xform rex rx) = add (projT1 rex) (projT1 rx).\n  Parameter add_xform_corr: \n    forall ty (rex:re_xf_pair ty) rx s v,\n      in_re_set_xform (add_xform rex rx) s v <->\n      in_re_xform rex s v \\/ in_re_set_xform rx s v.\n\n  Parameter fold_xform: \n    forall (ty:xtype) (A:Type) (comb: re_xf_pair ty -> A -> A),\n      (rs_xf_pair ty) -> A -> A.\n  Parameter fold_xform_erase : forall ty1 ty2\n     (comb1:re_xf_pair ty1 -> rs_xf_pair ty2 -> rs_xf_pair ty2)\n     (comb2:regexp -> t -> t) rx ini_rx,\n     (forall rex rx, projT1 (comb1 rex rx) = comb2 (projT1 rex) (projT1 rx)) -> \n     projT1 (fold_xform comb1 rx ini_rx) = fold comb2 (projT1 rx) (projT1 ini_rx).\n  Parameter fold_xform_rec :\n    forall (ty : xtype) (A : Type)     (* output type *)\n           (P : rs_xf_pair ty -> A -> Prop)  (* predicate *)\n           (f : re_xf_pair ty -> A -> A),    (* function we are folding *)\n      (forall rx1 rx2 : rs_xf_pair ty,  (* predicate holds on equivalent sets *)\n         rx_equal rx1 rx2 -> forall a : A, P rx1 a -> P rx2 a) ->\n      (* predicate extends when we add something using the function *)\n      (forall (rex : re_xf_pair ty) (rx : rs_xf_pair ty) (a : A),\n         P rx a -> P (add_xform rex rx) (f rex a)) ->\n      forall (rx : rs_xf_pair ty) (accum : A),\n        (* predicate holds on empty set and initial accumulator *)\n        P (empty_xform ty) accum -> \n        P rx (fold_xform f rx accum).\n\n  Definition set_cat_re (s:t) (r:regexp): t := \n    match r with\n      | rEps => s (* not stricitly necessary; an optimization *)\n      | rZero => empty\n      | _ => fold (fun r1 s' => add (rCat r1 r) s') s empty\n                        (* Note : will need to show that this is the same as\n                          RESF.map (re_set_build_map (fun r1 => rCat r1 r)) s *)\n   end.\n\n  Parameter cat_re_xform: forall ty,\n    rs_xf_pair ty -> \n    forall r:regexp, rs_xf_pair (xPair_t ty (regexp_type r)).\n  Parameter cat_re_xform_erase: forall t rx1 r,\n    projT1 (@cat_re_xform t rx1 r) = set_cat_re (projT1 rx1) r.\n  Parameter cat_re_xform_corr: forall ty (rx:rs_xf_pair ty) r str v,\n    in_re_set_xform (cat_re_xform rx r) str v <->\n    exists str1 str2 v1 v2, str = str1++str2 /\\ v=(v1,v2) /\\\n      in_re_set_xform rx str1 v1 /\\ in_regexp r str2 v2.\n\n  Parameter equal_xform : forall (s1 s2:t), \n    (Equal s1 s2) -> (re_set_type s1 ->> re_set_type s2).\n  Parameter equal_xform_corr : \n    forall s1 s2 (H: Equal s1 s2) str v,\n    in_re_set s1 str v <-> \n    in_re_set s2 str (xinterp (@equal_xform s1 s2 H) v).\n\n  Parameter Equal_sym : forall s1 s2, Equal s1 s2 -> Equal s2 s1.\n\n  Parameter equal_iso : forall (s1 s2:t) (H:Equal s1 s2) v, \n    (xinterp (equal_xform (Equal_sym H)) (xinterp (equal_xform H) v)) = v.\n\n  Parameter equal_xform_corr2 : \n    forall rs1 rs2 (H:Equal rs1 rs2) ty (f:re_set_type rs1 ->> xList_t ty) str v, \n      in_re_set_xform (existT _ rs1 f) str v <->\n      in_re_set_xform (existT _ rs2 (xcomp (equal_xform (Equal_sym H)) f)) str v.\n\n  Parameter re_set_extract_nil: forall s, list (xt_interp (re_set_type s)).\n  Parameter re_set_extract_nil_corr : \n    forall s (v : xt_interp (re_set_type s)),\n           in_re_set s nil v <-> List.In v (re_set_extract_nil s).\nEnd RESETXFORM.\n\n(* Raw RESet: RESet without transforms. Cannot use the name RESet here,\n   because the extraction would not like it if had the same name as the\n   name of this file. *)\nModule RawRESet := MSetAVL.Make REOrderedType.\n\n(* We have to break the module boundary of RESetXform because of\n   \"Extraction Implicit\" does not respect modules (due to a Coq bug) *)\n(* Module RESetXform <: RESETXFORM. *)\n\n  Include RawRESet.\n\n  Definition re_xf_pair (ty:xtype) := {r : regexp & regexp_type r ->> xList_t ty}.\n\n  Definition in_re_xform ty (rx : re_xf_pair ty) s (v:xt_interp ty) := \n    let (r,x) := rx in \n    exists v', in_regexp r s v' /\\ List.In v (xinterp x v').\n\n  Fixpoint tree_to_regexp (t : Raw.tree) : regexp := \n    match t with \n      | Raw.Leaf => rZero\n      | Raw.Node i lft r rgt => rAlt (tree_to_regexp lft) (rAlt r (tree_to_regexp rgt))\n    end.\n\n  Definition tree_type (t : Raw.tree) : xtype := \n    regexp_type (tree_to_regexp t).\n\n  Definition in_tree (t: Raw.tree) (str : list char_p) (v: xt_interp (tree_type t)) := \n    in_regexp (tree_to_regexp t) str v.\n\n  Definition tree_xf_pair (ty:xtype) := { t : Raw.tree & tree_type t ->> xList_t ty }.\n\n  Definition in_tree_xform ty (tx : tree_xf_pair ty) str (v : xt_interp ty) := \n    let (t,x) := tx in \n    exists v', in_tree t str v' /\\ List.In v (xinterp x v').\n\n  Definition re_set_type (rs : t) : xtype := tree_type (this rs). \n\n  Definition in_re_set (rs : t) (str : list char_p) (v : xt_interp (re_set_type rs)) := \n    in_tree (this rs) str v.\n  \n  Lemma in_re_set_empty : forall s v, not (in_re_set empty s v).\n  Proof.\n    simpl. intros. destruct v.\n  Qed.\n\n  Definition rs_xf_pair (ty:xtype) := {rs : t & re_set_type rs ->> xList_t ty }.\n\n  Definition in_re_set_xform ty (rx : rs_xf_pair ty) s (v:xt_interp ty) := \n    let (rs, f) := rx in \n    exists v', in_re_set rs s v' /\\ List.In v (xinterp f v').\n\n  Fixpoint tree_extract_nil (t:Raw.tree) : list (xt_interp (tree_type t)) := \n    match t as t return list (xt_interp (tree_type t)) with \n      | Raw.Leaf => nil\n      | Raw.Node _ l x r => \n        let vl := tree_extract_nil l in \n        let vx := regexp_extract_nil x in \n              let vr := tree_extract_nil r in \n              (List.map (fun x => inl x) vl) ++ \n              (List.map (fun x => inr (inl x)) vx) ++ \n              (List.map (fun x => inr (inr x)) vr) \n    end.\n\n  Lemma regexp_extract_nil_corr1 r str v : \n    in_regexp r str v -> str = nil -> List.In v (regexp_extract_nil r).\n  Proof.\n    induction 1 ; crush. generalize (app_eq_nil _ _ H3). crush.\n    apply in_prod ; auto. rewrite in_app. left. rewrite in_map_iff. crush.\n    rewrite in_app. right. rewrite in_map_iff. crush.\n    generalize (app_eq_nil _ _ H4). crush.\n  Qed.\n\n  Lemma regexp_extract_nil_corr2 :\n    forall r v, \n      List.In v (regexp_extract_nil r) -> in_regexp r nil v.\n  Proof.\n    induction r ; crush. destruct v. rewrite in_prod_iff in H. crush.\n    rewrite in_app in H ; destruct H ; rewrite in_map_iff in H ; crush.\n  Qed.\n\n  Lemma tree_extract_nil_corr : forall tr v,\n    in_tree tr nil v <-> List.In v (tree_extract_nil tr).\n  Proof.\n    unfold in_tree.\n    induction tr ; simpl. intro ; destruct v.\n    intro. destruct v as [v | [v | v]].\n    - split. \n      + intro.\n        in_regexp_inv. rewrite in_app. left.\n        eapply in_map. apply (proj1 (IHtr1 x)). auto.\n      + rewrite in_app. intros.\n        destruct H. rewrite (in_map_iff) in H.\n        crush. injection H ; crush. generalize (proj2 (IHtr1 v)). crush.\n        rewrite in_app in H. destruct H. rewrite in_map_iff in H.\n        crush. rewrite in_map_iff in H. crush.\n    - split. \n      + intros. in_regexp_inv. in_regexp_inv. \n        rewrite in_app. right. rewrite in_app. left. rewrite in_map_iff. \n        econstructor ; crush. eapply regexp_extract_nil_corr1 ; eauto.\n      + rewrite in_app. rewrite in_app. repeat rewrite in_map_iff. crush.\n        inversion H ; crush. eapply InrAlt_r. eapply InrAlt_l. \n        eapply regexp_extract_nil_corr2. eauto. eauto. auto.\n    - repeat rewrite in_app. repeat rewrite in_map_iff. crush.\n      + repeat in_regexp_inv. right ; right. \n        exists x. split ; auto. eapply IHtr2. eauto.\n      + injection H ; crush. eapply InrAlt_r ; eauto. eapply InrAlt_r ; eauto.\n        eapply IHtr2. auto.\n  Qed.\n\n  Definition re_set_extract_nil (s:t) : list (xt_interp (re_set_type s)).\n    destruct s. unfold re_set_type. apply tree_extract_nil.\n  Defined.\n\n  Lemma re_set_extract_nil_corr (s:t) (v:xt_interp (re_set_type s)) :\n    in_re_set s nil v <-> List.In v (re_set_extract_nil s).\n  Proof.\n    destruct s. simpl. unfold in_re_set. simpl. apply tree_extract_nil_corr.\n  Qed.\n\n  Definition empty_xform (ty:xtype) : rs_xf_pair ty := \n    existT _ empty xzero.\n  Extraction Implicit empty_xform [ty].\n  \n  Lemma empty_xform_erase : forall ty, projT1 (@empty_xform ty) = empty.\n    auto.\n  Qed.\n\n  Lemma empty_xform_corr ty (str : list char_p) (v : xt_interp ty) : \n    ~ in_re_set_xform (empty_xform ty) str v.\n  Proof.\n    unfold in_re_set_xform. unfold not. crush. destruct x.\n  Qed.\n\n  Definition singleton_xform (r:regexp) : rs_xf_pair (regexp_type r) := \n    existT _ (singleton r) (xcons (xmatch xzero (xmatch xid xzero)) xempty).\n\n  Lemma singleton_xform_erase : forall r, projT1 (@singleton_xform r) = (singleton r).\n    auto.\n  Qed.\n\n  Lemma singleton_xform_corr : forall r s v, \n    in_re_set_xform (singleton_xform r) s v <-> in_regexp r s v.\n  Proof.\n    unfold in_re_set_xform. simpl. crush. destruct x. destruct v.\n    destruct s0. unfold in_re_set, in_tree in H. simpl in H. \n    repeat in_regexp_inv. destruct v.\n    exists (inr (inl v)). unfold in_re_set, in_tree. simpl.\n    eauto.\n  Qed.\n\n  Open Scope Z_scope.\n\n  (* These definitions parallel those in the Raw module, but add in an xform. *)\n  Definition create_xform ty (l:Raw.tree) (fl : tree_type l ->> xList_t ty)\n                             (x:regexp) (fx : regexp_type x ->> xList_t ty)                             (r:Raw.tree) (fr : tree_type r ->> xList_t ty) : \n    tree_xf_pair ty := \n    existT _ (Raw.Node (Int.Z_as_Int.add (Int.Z_as_Int.max (Raw.height l) \n                                                            (Raw.height r)) 1)\n                       l x r) (xmatch fl (xmatch fx fr)).\n  Extraction Implicit create_xform [ty].\n\n  Lemma create_xform_erase : \n    forall ty l fl x fx r fr, projT1 (@create_xform ty l fl x fx r fr) = Raw.create l x r.\n    auto.\n  Qed.\n\n  Opaque xcross xmap xapp xcomp xmatch xflatten.\n\n  Ltac xmatch_simpl_hyp := \n    repeat \n      match goal with\n        | [ H : context[xinterp (xmatch ?f1 ?f2) ?v] |- _ ] => \n          rewrite (xmatch_corr f1 f2) in H ; simpl in H\n        | [H:context[xcomp ?X1 ?X2] |- _] => \n          rewrite (xcomp_corr X1 X2) in H ; simpl in H\n      end.\n\n  Ltac xmatch_simpl := \n    repeat\n      match goal with\n        | [ |- context[xinterp (xmatch ?f1 ?f2) ?v] ] => \n          rewrite (xmatch_corr f1 f2) ; simpl\n        | [|- context[xcomp ?X1 ?X2]] => rewrite (xcomp_corr X1 X2); simpl\n      end.\n\n  Ltac xinterp_simpl :=\n  repeat match goal with\n    | [|- context[xinterp (xmatch ?X1 ?X2) ?v]] => rewrite (xmatch_corr X1 X2); simpl\n    | [H:context[xinterp (xmatch ?X1 ?X2) ?v] |- _ ] =>\n      rewrite (xmatch_corr X1 X2) in H ; simpl\n    | [|- context[xcomp ?X1 ?X2]] => rewrite (xcomp_corr X1 X2); simpl\n    | [H:context[xcomp ?X1 ?X2] |- _] =>\n      rewrite (xcomp_corr X1 X2) in H; simpl in H\n    | [|- context[xinterp (xpair _ _) _]] => rewrite xpair_corr; simpl\n    | [H:context[xinterp (xpair _ _) _] |- _] =>\n      rewrite xpair_corr in H; simpl in H\n(* *)\n(*     | [|- context[xinterp xcross _]] => rewrite xcross_corr; simpl *)\n(*     | [H:context[xinterp xcross _] |- _] =>  *)\n(*       rewrite xcross_corr in H; simpl in H *)\n(* *)\n    | [|- context [xinterp xapp (_,_)]] => rewrite xapp_corr; simpl\n    | [H:context [xinterp xapp (_,_)] |- _] =>\n      rewrite xapp_corr in H; simpl in H\n    | [|- context [xinterp (xmap _) ?V]] =>\n      rewrite (@xmap_corr _ _ _ V); simpl\n    | [H:context [xinterp (xmap _) ?V] |- _] =>\n      rewrite (@xmap_corr _ _ _ V) in H; simpl in H\n(* *)\n(*     | [|- context[xinterp xflatten _]] => rewrite xflatten_corr2; simpl *)\n(*     | [H:context[xinterp xflatten _] |- _] =>  *)\n(*       rewrite xflatten_corr2 in H; simpl in H *)\n(* *)\n  end.\n\n  Lemma in_not_leaf : forall (r:regexp), Raw.In r Raw.Leaf -> False.\n  Proof.\n    unfold Raw.In. intros. inversion H.\n  Qed.\n\n   Lemma ok_left i (t1 t2:Raw.tree) (x:regexp) (ok : Raw.Ok (Raw.Node i t1 x t2)) : \n     Raw.Ok t1.\n   Proof.\n     unfold Raw.Ok in *. inversion ok. subst ; auto.\n   Qed.     \n\n   Lemma ok_right i (t1 t2:Raw.tree) (x:regexp) (ok : Raw.Ok (Raw.Node i t1 x t2)) : \n     Raw.Ok t2.\n   Proof.\n     unfold Raw.Ok in *. inversion ok. subst ; auto.\n   Qed.\n\n  Lemma in_left r i t1 t2 x :\n        Raw.In r (Raw.Node i t1 x t2) ->\n        (Raw.Ok (Raw.Node i t1 x t2)) -> \n        (REOrderedTypeAlt.compare r x = Lt) -> \n        Raw.In r t1.\n  Proof.\n    unfold Raw.In, Raw.Ok. intros.  \n    inversion H ; inversion H0 ; subst ; clear H H0 ; try congruence.\n    assert False ; [idtac | contradiction].\n    specialize (H14 r H3). simpl in *. rewrite REOrderedTypeAlt.compare_sym in H14.\n    rewrite H1 in H14. simpl in *. discriminate.\n  Qed.    \n\n  Lemma in_right r i t1 t2 x : \n        Raw.In r (Raw.Node i t1 x t2) ->\n        (Raw.Ok (Raw.Node i t1 x t2)) -> \n        (REOrderedTypeAlt.compare r x = Gt) -> \n        Raw.In r t2.\n  Proof.\n    unfold Raw.In, Raw.Ok. intros.  \n    inversion H ; inversion H0 ; subst ; clear H H0 ; try congruence.\n    assert False ; [idtac | contradiction].\n    specialize (H13 r H3). simpl in *. congruence.\n  Qed.    \n\n  Lemma cmp_leib : forall r1 r2, REOrderedTypeAlt.compare r1 r2 = Eq -> r1 = r2.\n    apply compare_re_eq_leibniz.\n  Qed.\n\n  Lemma subset_corr t1 t2 : (Raw.Ok t1) -> (Raw.Ok t2) ->\n    (Raw.subset t1 t2 = true <-> forall r, Raw.In r t1 -> Raw.In r t2).\n  Proof.\n    apply Raw.subset_spec.\n  Qed.    \n\n  Lemma subset_node i t_left r t_right t2 : \n    Raw.Ok (Raw.Node i t_left r t_right) ->\n    Raw.Ok t2 ->\n    Raw.subset (Raw.Node i t_left r t_right) t2 = true -> \n    Raw.subset t_left t2 = true /\\ Raw.In r t2 /\\ Raw.subset t_right t2 = true.\n  Proof.\n    intros. \n    generalize (ok_left H) (ok_right H). \n    rewrite subset_corr in H1 ; auto.\n    intros ; split.\n    rewrite subset_corr ; auto. intros. apply H1. eapply Raw.InLeft. auto.\n    split. apply H1. econstructor. apply Raw.MX.compare_refl.\n    rewrite subset_corr ; auto. intros. apply H1. eapply Raw.InRight. auto.\n  Qed.\n\n  (* Given a proof that r is in the tree t, extract an xform from\n     regexp_type r to tree_type t. *)\n  Fixpoint find_xform (t:Raw.tree) (r:regexp) : \n    Raw.Ok t -> Raw.In r t -> xform (regexp_type r) (tree_type t) := \n    match t as t' \n          return Raw.Ok t' -> Raw.In r t' -> xform (regexp_type r) (tree_type t') with\n      | Raw.Leaf => fun Htok Hin => False_rect _ (in_not_leaf Hin)\n      | Raw.Node _ ltree r' rtree => \n        fun Htok Hin => \n          match REOrderedTypeAlt.compare r r' as p \n                return (REOrderedTypeAlt.compare r r' = p) -> _\n          with \n            | Eq => fun H3 => \n                      eq_rec_r\n                        (fun r0 : regexp =>\n                           regexp_type r0 ->> xSum_t (tree_type ltree) \n                                       (xSum_t (regexp_type r') (tree_type rtree)))\n                            (xcomp xinl xinr) (cmp_leib r r' H3)\n            | Lt => fun H2 => \n                      let x := find_xform (ok_left Htok) (in_left Hin Htok H2) \n                          in xcomp x xinl\n            | Gt => fun H4 => \n                      let x := find_xform (ok_right Htok) (in_right Hin Htok H4)\n                      in xcomp x (xcomp xinr xinr)\n          end eq_refl\n    end.\n\n  Lemma find_xform_corr (r:regexp) (t:Raw.tree) : \n    forall (okt:Raw.Ok t) (Hinr:Raw.In r t)\n        (str : list char_p )(v : xt_interp (tree_type t)),\n    (exists v', in_regexp r str v' /\\ v = xinterp (@find_xform t r okt Hinr) v') \n    -> in_tree t str v.\n  Proof.\n    induction t ; crush. unfold Raw.In in Hinr. inversion Hinr.\n    generalize (cmp_leib r t3).\n    generalize (in_right Hinr okt).\n    generalize (in_left Hinr okt).\n    generalize (REOrderedTypeAlt.compare r t3).\n    destruct c ; intros. generalize (e eq_refl). intros ; subst.\n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym. unfold in_tree. simpl ; eauto.\n    specialize (IHt1 (ok_left okt) (i eq_refl) str). clear IHt2 i0 e.\n    assert (exists v, in_tree t2 str v). econstructor. eapply IHt1.\n    econstructor. eauto. crush. unfold in_tree in *. xinterp_simpl. crush. \n    clear IHt1 i e. specialize (IHt2 (ok_right okt) (i0 eq_refl) str). \n    unfold in_tree in *. simpl. eapply InrAlt_r. eapply InrAlt_r. eauto.\n    eauto. xinterp_simpl. auto.\n  Qed.\n\n  (* Given trees t1 and r2 such that (subset t1 t2) produce a transform of the type\n     tree_type t1 ->> tree_type t2. *)\n  Fixpoint inject_xform_tree (t1 : Raw.tree) (t2 : Raw.tree) : \n         (Raw.Ok t1) -> (Raw.Ok t2) -> \n         (Raw.subset t1 t2 = true) -> (tree_type t1 ->> tree_type t2) := \n    match t1 as t1' return \n         (Raw.Ok t1') -> (Raw.Ok t2) -> \n         (Raw.subset t1' t2 = true) -> (tree_type t1' ->> tree_type t2)\n    with \n      | Raw.Leaf => fun _ _ _ => xzero\n      | Raw.Node _ t_left r t_right => \n        fun t1ok t2ok Hsub => \n          (xmatch (inject_xform_tree (ok_left t1ok) t2ok \n                                     (proj1 (subset_node t1ok t2ok Hsub)))\n                  (xmatch \n                     (find_xform t2ok (proj1 (proj2 (subset_node t1ok t2ok Hsub))))\n                     (inject_xform_tree (ok_right t1ok) t2ok \n                                        (proj2 (proj2 (subset_node t1ok t2ok Hsub))))))\n    end.\n\n  (* Prove that [inject_xform_tree] preserves the [in_tree] relation.  One\n     direction is easy, but the other is not. *)\n  Lemma inject_xform_tree_corr1 : \n    forall t1 t2 okt1 okt2 Hsub str v,\n      in_tree t1 str v -> \n      in_tree t2 str (xinterp (@inject_xform_tree t1 t2 okt1 okt2 Hsub) v).\n  Proof.\n    induction t1 ; intros. destruct v. \n    unfold in_tree in *. simpl. \n    specialize (IHt1_1 _ (ok_left okt1) okt2 (proj1 (subset_node okt1 okt2 Hsub)) str).\n    specialize (IHt1_2 _ (ok_right okt1) okt2 (proj2 (proj2 (subset_node okt1 okt2 Hsub)))\n                       str).\n    simpl in H. generalize (inv_alt H). clear H. intro. destruct H. clear IHt1_2.\n    destruct H as [v1 [H1 H2]]. subst. xinterp_simpl. eapply IHt1_1 ; auto.\n    destruct H as [v2 [H H2]] ; subst.\n    generalize (inv_alt H) ; clear H ; intros ; subst. destruct H ;\n    destruct H as [v1 [H1 H2]] ; subst. xinterp_simpl.\n    apply (find_xform_corr okt2 (proj1 (proj2 (subset_node okt1 okt2 Hsub)))). eauto.\n    xinterp_simpl. apply IHt1_2. auto.\n  Qed.\n  \n  Definition inject_xform (s1 s2 : RawRESet.t) : \n    (RawRESet.subset s1 s2 = true) -> (re_set_type s1 ->> re_set_type s2).\n  Proof.\n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2]. unfold RawRESet.subset, re_set_type. simpl. \n    apply (inject_xform_tree okt1 okt2).\n  Defined.\n\n  Definition inject_xform_corr1 s1 s2 (Hsub : RawRESet.subset s1 s2 = true) str v : \n    in_re_set s1 str v -> \n    in_re_set s2 str (xinterp (inject_xform s1 s2 Hsub) v).\n  Proof.    \n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2]. \n    unfold RawRESet.subset, re_set_type, in_re_set in *. simpl in *.\n    apply inject_xform_tree_corr1 ; auto.\n  Qed.\n\n  Definition equal_xform s1 s2 (H : RawRESet.Equal s1 s2) : re_set_type s1 ->> re_set_type s2.\n    assert (RawRESet.subset s1 s2 = true).\n    rewrite (RawRESet.subset_spec). intro. apply (proj1 (H a)). \n    apply (@inject_xform s1 s2 H0).\n  Defined.\n\n  Lemma Equal_sym s1 s2 : RawRESet.Equal s1 s2 -> RawRESet.Equal s2 s1.\n  Proof.\n    unfold RawRESet.Equal. crush. rewrite <- H. auto.\n  Qed.\n  \n  Lemma Subset_node i t11 x t12 t2 : \n    Raw.Subset (Raw.Node i t11 x t12) t2 -> \n    Raw.Subset t11 t2 /\\ Raw.In x t2 /\\ Raw.Subset t12 t2.\n  Proof.\n    unfold Raw.Subset. intros. split. intros. apply H. eapply Raw.InLeft ; auto.\n    split. apply H. eapply Raw.IsRoot. apply Raw.MX.compare_refl.\n    intros. apply H. eapply Raw.InRight ; eauto.\n  Qed.\n\n  (* A [ctxt] is a tree with a single hole. *)\n  Inductive ctxt := \n    | Hole : ctxt\n    | LeftNode : Int.Z_as_Int.t -> ctxt -> REOrderedTypeAlt.t -> Raw.tree -> ctxt\n    | RightNode : Int.Z_as_Int.t -> Raw.tree -> REOrderedTypeAlt.t -> ctxt -> ctxt.\n\n  (* Filling a context's hole with a tree *)\n  Fixpoint fill (c:ctxt) (t0:Raw.tree) {struct c} : Raw.tree := \n    match c with \n      | Hole => t0\n      | LeftNode i c' x r => Raw.Node i (fill c' t0) x r\n      | RightNode i l x c' => Raw.Node i l x (fill c' t0)\n    end.\n\n  (* fill a context's hole with another context *)\n  Fixpoint fill_ctxt (c1 c2:ctxt) : ctxt := \n    match c1 with \n      | Hole => c2\n      | LeftNode i c x r => LeftNode i (fill_ctxt c c2) x r\n      | RightNode i l x c => RightNode i l x (fill_ctxt c c2)\n    end.\n\n  Lemma fill_ctxt_left c i l x r : \n    (fill c (Raw.Node i l x r)) = fill (fill_ctxt c (LeftNode i Hole x r)) l.\n  Proof.\n    induction c ; crush.\n  Qed.\n\n  Lemma fill_ctxt_right (c:ctxt) i (l:Raw.tree) x (r:Raw.tree) : \n    (fill c (Raw.Node i l x r)) = fill (fill_ctxt c (RightNode i l x Hole)) r.\n  Proof.\n    induction c ; crush.\n  Qed.\n\n  (* Used to simplify some casting. *)\n  Lemma tree_eq t1 t2 : t1 = t2 -> tree_type t1 = tree_type t2.\n    intros ; subst. auto.\n  Defined.\n\n  Lemma subset_ctxt c i l x r t : \n    Raw.Subset (fill c (Raw.Node i l x r)) t -> \n    Raw.Subset l t /\\ Raw.In x t /\\ Raw.Subset r t.\n  Proof. \n    induction c ; simpl ; intros. apply (Subset_node H).\n    apply IHc. generalize (Subset_node H). crush.\n    apply IHc. generalize (Subset_node H). crush.\n  Qed.\n\n  Lemma subset_fill_left {c i l x r t2} : \n    Raw.Subset (fill c (Raw.Node i l x r)) t2 -> \n    Raw.Subset (fill (fill_ctxt c (LeftNode i Hole x r)) l) t2.\n  Proof.\n    rewrite <- fill_ctxt_left. auto.\n  Qed.\n\n  Lemma subset_fill_right {c i l x r t2} : \n    Raw.Subset (fill c (Raw.Node i l x r)) t2 -> \n    Raw.Subset (fill (fill_ctxt c (RightNode i l x Hole)) r) t2.\n  Proof.\n    rewrite <- fill_ctxt_right. auto.\n  Qed.\n\n  Lemma ok_fill_left {c i l x r} : \n    Raw.Ok (fill c (Raw.Node i l x r)) -> \n    Raw.Ok (fill (fill_ctxt c (LeftNode i Hole x r)) l).\n  Proof.\n    rewrite <- fill_ctxt_left. auto.\n  Qed.\n\n  Lemma ok_fill_right {c i l x r} : \n    Raw.Ok (fill c (Raw.Node i l x r)) -> \n    Raw.Ok (fill (fill_ctxt c (RightNode i l x Hole)) r).\n  Proof.\n    rewrite <- fill_ctxt_right. auto.\n  Qed.\n\n  Lemma fill_in {c i l x r t2} : \n    Raw.Subset (fill c (Raw.Node i l x r)) t2 -> Raw.In x t2.\n  Proof.\n    intro.\n    generalize (subset_ctxt _ _ _ _ _ H). crush.\n  Qed.\n\n  Definition cast {t1 t2:Type} : (t1 = t2) -> t1 -> t2.\n    intro ; subst. apply (fun x => x).\n  Defined.\n\n  Definition interp_eq {t1 t2} : t1 = t2 -> xt_interp t1 = xt_interp t2.\n    intros. subst. auto.\n  Defined.\n\n  Lemma in_ctxt {i l x r c t} : \n    Raw.Ok t -> \n    t = fill c (Raw.Node i l x r) -> \n    Raw.In x t.\n  Proof.\n    intros. subst.\n    induction c ; simpl ; intros. eapply Raw.IsRoot. apply Raw.MX.compare_refl.\n    inversion H. subst. eapply Raw.InLeft. eapply IHc. auto.\n    inversion H. subst. eapply Raw.InRight. eapply IHc. auto.\n  Qed.\n\n  Lemma lt_trans_sub_node {y i l x r} : \n    Raw.Ok (Raw.Node i l x r) -> \n    Raw.lt_tree y (Raw.Node i l x r) -> Raw.lt_tree y l.\n  Proof.\n    intros. inversion H ; subst ; clear H. eapply Raw.lt_tree_trans ; eauto.\n    remember_rev (REOrderedTypeAlt.compare x y) as c ; destruct c ; auto.\n    generalize (cmp_leib _ _ Hc) ; intros ; subst.\n    contradiction (Raw.lt_tree_not_in y (Raw.Node i l y r)). econstructor.\n    eapply Raw.MX.compare_refl.\n    specialize (H0 x). simpl in *. rewrite H0 in Hc ; auto. econstructor.\n    eapply Raw.MX.compare_refl.\n  Qed.\n\n  Lemma lt_fill {i l x r y c} : \n    Raw.Ok (fill c (Raw.Node i l x r)) -> \n    Raw.lt_tree y (fill c (Raw.Node i l x r)) -> \n    REOrderedTypeAlt.compare x y = Lt.\n  Proof.\n    intros. apply (H0 x). eapply in_ctxt. auto. eauto.\n  Qed.\n\n  Lemma ok_fill_left_lt {i l x r c j y r'} : \n    Raw.Ok (Raw.Node j (fill c (Raw.Node i l x r)) y r') -> \n    REOrderedTypeAlt.compare x y = Lt.\n  Proof. \n    intros. inversion H. subst. eapply lt_fill ; eauto.\n  Qed.\n\n  Lemma gt_fill {i l x r y c} : \n    Raw.Ok (fill c (Raw.Node i l x r)) -> \n    Raw.gt_tree y (fill c (Raw.Node i l x r)) -> \n    REOrderedTypeAlt.compare x y = Gt.\n  Proof.\n    intros. specialize (H0 x). simpl in H0. \n    specialize (H0 (@in_ctxt i l x r c _ H eq_refl)). \n    rewrite (REOrderedTypeAlt.compare_sym). rewrite H0 ; auto.\n  Qed.\n\n  Lemma ok_fill_right_gt {i l x r c j l' y} : \n    Raw.Ok (Raw.Node j l' y (fill c (Raw.Node i l x r))) -> \n    REOrderedTypeAlt.compare x y = Gt.\n  Proof.\n    intros. inversion H ; subst ; clear H. eapply gt_fill ; eauto.\n  Qed.\n\n  Lemma in_find_form x str vx t2 (t2ok : Raw.Ok t2) (Hin : Raw.In x t2) : \n    in_tree t2 str (xinterp (find_xform t2ok Hin) vx) -> \n    in_regexp x str vx.\n  Proof.\n    unfold in_tree. induction t2. simpl. intros. in_regexp_inv.\n    rename t0 into i. rename t1 into y.\n    inversion Hin. subst. simpl.\n    (* IsRoot *)\n    generalize (cmp_leib x y). generalize (in_left Hin t2ok).\n    generalize (in_right Hin t2ok). rewrite H0. intros.\n    assert (x = y) ; auto. subst.\n    rewrite (@proof_irrelevance _ (e eq_refl) eq_refl) in H. \n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym in H. xinterp_simpl ; simpl in H.\n    in_regexp_inv. in_regexp_inv. \n    (* InLeft *)\n    subst. simpl. specialize (IHt2_1 (ok_left t2ok)). clear IHt2_2.\n    generalize (cmp_leib x y) (in_left Hin t2ok) (in_right Hin t2ok).\n    assert (REOrderedTypeAlt.compare x y = Lt).\n    clear IHt2_1 ; inversion t2ok ; subst ; clear t2ok. clear Hin.\n    remember_rev (REOrderedTypeAlt.compare x y) as c. destruct c ; auto.\n    generalize (cmp_leib _ _ Hc) ; intros ; subst. \n    contradiction (Raw.lt_tree_not_in y t2_1).\n    contradiction (Raw.lt_tree_not_in x t2_1). eapply Raw.lt_tree_trans ; eauto.\n    rewrite REOrderedTypeAlt.compare_sym. rewrite Hc. auto. rewrite H. intros.\n    xinterp_simpl. in_regexp_inv. injection H2 ; intros ; subst. clear H2.\n    eauto. \n    (* InRight *)\n    subst. simpl. specialize (IHt2_2 (ok_right t2ok)). clear IHt2_1.\n    generalize (cmp_leib x y) (in_left Hin t2ok) (in_right Hin t2ok).\n    assert (REOrderedTypeAlt.compare x y = Gt). \n    clear IHt2_2 ; inversion t2ok ; subst ; clear t2ok ; clear Hin.\n    remember_rev (REOrderedTypeAlt.compare x y) as c ; destruct c ; auto.\n    generalize (cmp_leib _ _ Hc) ; intros ; subst.\n    contradiction (Raw.gt_tree_not_in y t2_2) ; auto.\n    contradiction (Raw.gt_tree_not_in x t2_2). eapply Raw.gt_tree_trans ; auto. eauto.\n    auto. rewrite H. intros. xinterp_simpl. in_regexp_inv.\n    injection H2 ; intros ; subst ; clear H2. in_regexp_inv.\n    injection H2 ; intros ; subst ; clear H2. eauto.\n  Qed.                                                \n\n  (* This is the key lemma for showing that [inject_xform_tree] preserves\n   * the [in_tree] relation.  If [t1] and [t2] are equivalent trees, and\n   * [in_tree t2 str (xinterp (inject_xform_tree t1 t2) v)] holds, then\n   * we know that (a) there is some [x] in both [t1] and [t2] and a [vx] \n   * such that [in_tree x str vx], (b) [t1 = fill C [Node l x r]] for\n   * some context [C] and trees [l] and [r], and (c) [v] can be obtained\n   * by mapping [vx] into [t1] by calling [find_xform].\n   *)\n  Lemma inject_deconstruct t2 (okt2:Raw.Ok t2) str : \n    forall t1 (okt1:Raw.Ok t1) (Hsub1:Raw.subset t1 t2 = true)\n           (v:xt_interp (tree_type t1)),\n    in_tree t2 str (xinterp (inject_xform_tree okt1 okt2 Hsub1) v) -> \n    exists i1, exists l1, exists x, exists r1, exists vx, exists c1,\n    exists (H: t1 = fill c1 (Raw.Node i1 l1 x r1)), \n      in_regexp x str vx /\\\n      v = xinterp (find_xform okt1 (in_ctxt okt1 H)) vx.\n  Proof.\n    Opaque Raw.subset. unfold in_tree.\n    induction t1 ; intros. destruct v. \n    specialize (IHt1_1 (ok_left okt1) (proj1 (subset_node okt1 okt2 Hsub1))).\n    specialize (IHt1_2 (ok_right okt1) (proj2 (proj2 (subset_node okt1 okt2 Hsub1)))).\n    simpl in H. destruct v as [v | v]. \n    clear IHt1_2. assert (in_regexp (tree_to_regexp t2) str\n                           ((xinterp (inject_xform_tree (ok_left okt1) okt2\n                             (proj1 (subset_node okt1 okt2 Hsub1)))) v)).\n    xinterp_simpl  ; auto. clear H.\n    specialize (IHt1_1 v H0). clear H0.\n    destruct IHt1_1 as [i1 [l1 [x [r1 [vx [c1 [H1 [H2 H3]]]]]]]].\n    exists i1. exists l1. exists x. exists r1. exists vx. \n    exists (LeftNode t0 c1 t1 t1_2). \n    assert (Raw.Node t0 t1_1 t1 t1_2 = fill (LeftNode t0 c1 t1 t1_2) (Raw.Node i1 l1 x r1)).\n    subst ; auto. exists H. split. auto.\n    generalize (in_ctxt okt1 H). intro H0. clear H. subst.\n    simpl. generalize (cmp_leib x t1). generalize (in_left H0 okt1).\n    generalize (in_right H0 okt1). rename t1 into y. rename t0 into j.\n    rewrite (ok_fill_left_lt okt1).\n    intros. xinterp_simpl. \n    rewrite (@proof_irrelevance _ (in_ctxt (ok_left okt1) eq_refl) (i0 eq_refl)). auto.\n    destruct v as [vx | v].\n    clear IHt1_1 IHt1_2. rename t0 into i. rename t1 into x.\n    xinterp_simpl. simpl in H. xinterp_simpl. simpl in H. \n    exists i. exists t1_1. exists x. exists t1_2. exists vx. exists Hole.\n    exists eq_refl. split. \n    apply (@in_find_form x str vx t2 okt2 _ H).\n    generalize (cmp_leib x x).\n    generalize (@in_left x i t1_1 t1_2 x \n                         (@in_ctxt i t1_1 x t1_2 Hole (Raw.Node i t1_1 x t1_2)\n                                   okt1 (@eq_refl Raw.tree (Raw.Node i t1_1 x t1_2)))).\n    generalize (@in_right x i t1_1 t1_2 x\n                     (@in_ctxt i t1_1 x t1_2 Hole (Raw.Node i t1_1 x t1_2)\n                        okt1 (@eq_refl Raw.tree (Raw.Node i t1_1 x t1_2)))).\n    rewrite (Raw.MX.compare_refl x). intros. \n    rewrite (@proof_irrelevance _ (e eq_refl) eq_refl). \n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym. xinterp_simpl. auto.\n    clear IHt1_1. assert (in_regexp (tree_to_regexp t2) str\n                          (xinterp (inject_xform_tree (ok_right okt1) okt2\n                           (proj2 (proj2 (subset_node okt1 okt2 Hsub1)))) v)).\n    xinterp_simpl. simpl in H. xinterp_simpl. simpl in H. auto. clear H.\n    specialize (IHt1_2 v H0). clear H0.\n    destruct IHt1_2 as [i1 [l1 [x [r1 [vx [c1 [H1 [H2 H3]]]]]]]].\n    exists i1. exists l1. exists x. exists r1. exists vx.\n    exists (RightNode t0 t1_1 t1 c1). subst. \n    assert (Raw.Node t0 t1_1 t1 (fill c1 (Raw.Node i1 l1 x r1)) =\n         fill (RightNode t0 t1_1 t1 c1) (Raw.Node i1 l1 x r1)). subst ; auto.\n    exists H. split ; auto.\n    simpl. generalize (cmp_leib x t1) (in_left (in_ctxt okt1 H) okt1).\n    generalize (in_right (in_ctxt okt1 H) okt1).\n    rewrite (ok_fill_right_gt okt1). intros ; xinterp_simpl.\n    rewrite (@proof_irrelevance _ (in_ctxt (ok_right okt1) eq_refl) (i eq_refl)).\n    auto.\n  Qed.\n\n  (* The other half showing that [inject_xform_tree] preserves the [in_tree]\n   * relation. *)\n  Lemma inject_xform_tree_corr2 : \n    forall t1 (okt1:Raw.Ok t1) t2 (okt2:Raw.Ok t2) \n           Hsub1 (Hsub2:Raw.subset t2 t1 = true) str v,\n      in_tree t2 str (xinterp (inject_xform_tree okt1 okt2 Hsub1) v) ->\n      in_tree t1 str v.\n  Proof.\n    intros. \n    specialize (@inject_deconstruct t2 okt2 str t1 okt1 Hsub1 v H).\n    intros. destruct H0 as [i [l [x [r [vx [c [H1 [H2 H3]]]]]]]].\n    clear H. subst. generalize c okt1 ; clear c okt1 Hsub1 Hsub2 okt2.\n    induction c ; intro okt1. simpl.\n    generalize (cmp_leib x x). \n    generalize (@in_left x i l r x\n                     (@in_ctxt i l x r Hole (Raw.Node i l x r) okt1\n                        (@eq_refl Raw.tree (Raw.Node i l x r)))).   \n    generalize (@in_right x i l r x\n                     (@in_ctxt i l x r Hole (Raw.Node i l x r) okt1\n                        (@eq_refl Raw.tree (Raw.Node i l x r)))).\n    rewrite Raw.MX.compare_refl. intros. rewrite (@proof_irrelevance _ (e eq_refl) eq_refl).\n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym. xinterp_simpl. unfold in_tree. \n    simpl. eauto.\n    simpl. rename t0 into j. rename t1 into y.\n    generalize (cmp_leib x y). \n    generalize (@in_left x j (fill c (Raw.Node i l x r)) t3 y\n                     (@in_ctxt i l x r (LeftNode j c y t3)\n                        (Raw.Node j (fill c (Raw.Node i l x r)) y t3) okt1\n                        (@eq_refl Raw.tree\n                           (Raw.Node j (fill c (Raw.Node i l x r)) y t3)))\n                     okt1).\n    generalize (@in_right x j (fill c (Raw.Node i l x r)) t3 y\n                     (@in_ctxt i l x r (LeftNode j c y t3)\n                        (Raw.Node j (fill c (Raw.Node i l x r)) y t3) okt1\n                        (@eq_refl Raw.tree\n                           (Raw.Node j (fill c (Raw.Node i l x r)) y t3)))\n                     okt1).\n    rewrite (ok_fill_left_lt okt1). intros.\n    specialize (IHc (ok_left okt1)). unfold in_tree in *.\n    eapply InrAlt_l. fold tree_to_regexp. eapply IHc.\n    rewrite (@proof_irrelevance _ (i1 eq_refl) \n                                (in_ctxt (ok_left okt1) eq_refl)).\n    xinterp_simpl. auto.\n    simpl. generalize (cmp_leib x t3). \n    generalize (@in_left x t0 t1 (fill c (Raw.Node i l x r)) t3\n                     (@in_ctxt i l x r (RightNode t0 t1 t3 c)\n                        (Raw.Node t0 t1 t3 (fill c (Raw.Node i l x r))) okt1\n                        (@eq_refl Raw.tree\n                           (Raw.Node t0 t1 t3 (fill c (Raw.Node i l x r)))))\n                     okt1).\n    generalize (@in_right x t0 t1 (fill c (Raw.Node i l x r)) t3\n                     (@in_ctxt i l x r (RightNode t0 t1 t3 c)\n                        (Raw.Node t0 t1 t3 (fill c (Raw.Node i l x r))) okt1\n                        (@eq_refl Raw.tree\n                           (Raw.Node t0 t1 t3 (fill c (Raw.Node i l x r)))))\n                     okt1).\n    rewrite (ok_fill_right_gt okt1). intros. \n    specialize (IHc (ok_right okt1)). unfold in_tree in *.\n    eapply InrAlt_r. eapply InrAlt_r. fold tree_to_regexp. eapply IHc.\n    eauto. rewrite (@proof_irrelevance _ (i0 eq_refl)\n                                       (in_ctxt (ok_right okt1) eq_refl)). \n    xinterp_simpl. auto.\n  Qed.   \n\n  Lemma inject_xform_tree_corr : \n    forall t1 t2 okt1 okt2 Hsub1 (Hsub2:Raw.subset t2 t1 = true) str v, \n       in_tree t1 str v <-> \n       in_tree t2 str (xinterp (@inject_xform_tree t1 t2 okt1 okt2 Hsub1) v).\n  Proof.\n    intros ; split. apply inject_xform_tree_corr1. apply inject_xform_tree_corr2. auto.\n  Qed.\n\n  Lemma inject_deconstruct2 :\n    forall t1 (okt1:Raw.Ok t1) (v:xt_interp (tree_type t1)),\n    exists i1, exists l1, exists x, exists r1, exists vx, exists c1,\n    exists (H: t1 = fill c1 (Raw.Node i1 l1 x r1)), \n      v = xinterp (find_xform okt1 (in_ctxt okt1 H)) vx.\n  Proof.\n    Opaque Raw.subset.\n    induction t1 ; simpl ; intros. destruct v.\n    intros.\n    specialize (IHt1_1 (ok_left okt1)).\n    specialize (IHt1_2 (ok_right okt1)). \n    destruct v as [vl | [vx | vr]].\n    (* v = inl vl *)\n    clear IHt1_2. specialize (IHt1_1 vl). \n    destruct IHt1_1 as [i1 [l1 [x [r1 [vx [c1 [H1 H3]]]]]]].\n    exists i1. exists l1. exists x. exists r1. exists vx.\n    exists (LeftNode t0 c1 t1 t1_2). \n    assert (Raw.Node t0 t1_1 t1 t1_2 = fill (LeftNode t0 c1 t1 t1_2) (Raw.Node i1 l1 x r1)).\n    subst ; auto. exists H. generalize (in_ctxt okt1 H). clear H. subst ; simpl. intro.\n    generalize (cmp_leib x t1). generalize (in_left i okt1). generalize (in_right i okt1).\n    clear i. rewrite (ok_fill_left_lt okt1). intros. xinterp_simpl.\n    rewrite (@proof_irrelevance _ (in_ctxt (ok_left okt1) eq_refl) (i0 eq_refl)). auto.\n    (* v = inr (inl vx) *)\n    clear IHt1_1 IHt1_2. rename t0 into i. rename t1 into x.\n    exists i. exists t1_1. exists x. exists t1_2. exists vx. exists Hole. \n    exists eq_refl. generalize (cmp_leib x x).\n    generalize (@in_left x i t1_1 t1_2 x \n                         (@in_ctxt i t1_1 x t1_2 Hole (Raw.Node i t1_1 x t1_2)\n                                   okt1 (@eq_refl Raw.tree (Raw.Node i t1_1 x t1_2)))).\n    generalize (@in_right x i t1_1 t1_2 x\n                     (@in_ctxt i t1_1 x t1_2 Hole (Raw.Node i t1_1 x t1_2)\n                        okt1 (@eq_refl Raw.tree (Raw.Node i t1_1 x t1_2)))).\n    rewrite (Raw.MX.compare_refl x). intros.\n    rewrite (@proof_irrelevance _ (e eq_refl) eq_refl). \n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym. xinterp_simpl. auto.\n    (* v = inr (inr vr) *)\n    clear IHt1_1. specialize (IHt1_2 vr).\n    destruct IHt1_2 as [i1 [l1 [x [r1 [vx [c1 [H1 H2]]]]]]].\n    exists i1. exists l1. exists x. exists r1. exists vx. exists (RightNode t0 t1_1 t1 c1).\n    assert (Raw.Node t0 t1_1 t1 t1_2 = \n            fill (RightNode t0 t1_1 t1 c1) (Raw.Node i1 l1 x r1)).\n    subst. auto. exists H.\n    generalize (cmp_leib x t1).\n    generalize (in_left (in_ctxt okt1 H) okt1).\n    generalize (in_right (in_ctxt okt1 H) okt1). clear H. subst.\n    rewrite (ok_fill_right_gt okt1). intros.\n    xinterp_simpl.\n    rewrite (@proof_irrelevance _ (in_ctxt (ok_right okt1) eq_refl) (i eq_refl)). auto.\n  Qed.\n\n(*\n  Lemma find_xform_injective : \n    forall x1 x2 t1 (okt1: Raw.Ok t1) (Hin1:Raw.In x1 t1) (Hin2:Raw.In x2 t1) v1 v2,\n      (xinterp (find_xform okt1 Hin1) v1 = xinterp (find_xform okt1 Hin2) v2) -> \n      v1 = v2.\n  Proof.\n    induction t1. simpl. intros. inversion Hin1.\n    simpl. intros okt1 Hin1 Hin2 v1 v2. \n    rewrite (@proof_irrelevance _ Hin2 Hin1).\n    generalize (cmp_leib x t1).\n    generalize (in_left Hin1 okt1) (in_right Hin1 okt1).\n    remember (REOrderedTypeAlt.compare x t1) as cmp.\n    destruct cmp. intros.\n    assert (x = t1) ; auto ; subst. \n    rewrite (@proof_irrelevance _ (e eq_refl) eq_refl) in H.\n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym in H. xinterp_simpl.\n    congruence.\n    intros. xinterp_simpl. injection H ; intros ; clear H.\n    apply (IHt1_1 _ _ _ _ _ H0).\n    intros. xinterp_simpl. injection H ; intros ; clear H.\n    apply (IHt1_2 _ _ _ _ _ H0).\n  Qed.\n*)\n\n  Lemma inject_is_find_xform : \n    forall i1 l1 x r1 (okt1 : Raw.Ok (Raw.Node i1 l1 x r1)) (vx:xt_interp (regexp_type x))\n           t2 (okt2: Raw.Ok t2) (Hsub : Raw.subset t2 (Raw.Node i1 l1 x r1) = true) \n           (Hin : Raw.In x t2), \n      xinterp (inject_xform_tree okt2 okt1 Hsub) \n              (xinterp (find_xform okt2 Hin) vx) = inr (inl vx).\n  Proof.\n    induction t2 ; simpl ; intros. inversion Hin.\n    xinterp_simpl. \n    generalize (cmp_leib x t1). generalize (cmp_leib t1 x).\n    generalize (in_left Hin okt2) (in_right Hin okt2)\n               (proj1 (subset_node okt2 okt1 Hsub))\n               (in_left (proj1 (proj2 (subset_node okt2 okt1 Hsub))) okt1)\n               (in_right (proj1 (proj2 (subset_node okt2 okt1 Hsub))) okt1)\n               (proj2 (proj2 (subset_node okt2 okt1 Hsub))).\n    rewrite (REOrderedTypeAlt.compare_sym x t1).\n    remember_rev (REOrderedTypeAlt.compare x t1) as cmp.\n    destruct cmp ; simpl ; intros.\n    (* cmp = Eq *)\n    assert (x = t1) ; auto ; subst. rewrite (@proof_irrelevance _ (e2 eq_refl) eq_refl).\n    rewrite (@proof_irrelevance _ (e1 eq_refl) eq_refl).\n    unfold eq_rec_r, eq_rec, eq_rect, eq_sym. xinterp_simpl. auto.\n    (* cmp = Lt *)\n    xinterp_simpl. eapply IHt2_1.\n    (* cmp = Gt *)\n    xinterp_simpl. eapply IHt2_2.\n  Qed.\n\n  Lemma fill_is_in {c i l x r t} : \n    fill c (Raw.Node i l x r) = t -> \n    Raw.In x t.\n  Proof.\n    intro ; subst.\n    apply (@fill_in c i l x r (fill c (Raw.Node i l x r))). \n    intro. auto.\n  Qed.\n\n  Fixpoint find_subtree' (t1:Raw.tree) (c1:ctxt) {struct c1} : \n    tree_type t1 ->> tree_type (fill c1 t1) := \n      match c1 as c1 return tree_type t1 ->> tree_type (fill c1 t1)\n      with \n        | Hole => xid\n        | LeftNode i c1' x r => \n          xcomp (find_subtree' t1 c1') xinl\n        | RightNode i l x c1' => \n          xcomp (find_subtree' t1 c1') (xcomp xinr xinr)\n      end.\n\n  Definition find_subtree t t1 c1 (H:fill c1 t1 = t) : tree_type t1 ->> tree_type t := \n    xcoerce (find_subtree' t1 c1) eq_refl (tree_eq H).\n\n  Lemma in_gives_ctxt :\n    forall x t1,\n      Raw.In x t1 ->\n      exists c, exists i, exists l, exists r, \n         fill c (Raw.Node i l x r) = t1.\n  Proof.                                                \n    induction t1 ; simpl ; intros ; inversion H ; subst.\n    assert (t1 = x). rewrite (cmp_leib x t1 H1). auto. subst. clear H1.\n    exists Hole. repeat econstructor ; eauto.\n    specialize (IHt1_1 H1). crush. \n    exists (LeftNode t0 x0 t1 t1_2). simpl. repeat econstructor ; eauto.\n    specialize (IHt1_2 H1). crush.\n    exists (RightNode t0 t1_1 t1 x0). simpl. repeat econstructor ; eauto.\n  Qed.\n\n  Lemma inject_find_is_find : \n    forall x vx i1 l1 r1 i2 l2 r2 c2 (okt2:Raw.Ok (fill c2 (Raw.Node i2 l2 x r2)))\n      c1 (okt1 :Raw.Ok (fill c1 (Raw.Node i1 l1 x r1))) Hsub1,\n    (xinterp (inject_xform_tree okt1 okt2 Hsub1)\n             (xinterp (find_xform okt1 (in_ctxt okt1 eq_refl)) vx) = \n     xinterp (find_xform okt2 (in_ctxt okt2 eq_refl)) vx).\n  Proof.\n    induction c1 ; simpl ; intros.\n    (* c1 = Hole *)\n    generalize (cmp_leib x x).\n    generalize (@in_left x i1 l1 r1 x\n                        (@in_ctxt i1 l1 x r1 Hole (Raw.Node i1 l1 x r1) okt1\n                           (@eq_refl Raw.tree (Raw.Node i1 l1 x r1))) okt1)\n               (@in_right x i1 l1 r1 x\n                          (@in_ctxt i1 l1 x r1 Hole (Raw.Node i1 l1 x r1) okt1\n                                    (@eq_refl Raw.tree (Raw.Node i1 l1 x r1))) okt1).\n    generalize (proj1 (subset_node okt1 okt2 Hsub1))\n               (proj2 (proj2 (subset_node okt1 okt2 Hsub1)))\n               (proj1 (proj2 (subset_node okt1 okt2 Hsub1))).\n\n    rewrite Raw.MX.compare_refl. intros.\n    rewrite (@proof_irrelevance _ (e1 eq_refl) eq_refl).\n    xinterp_simpl. \n    rewrite (@proof_irrelevance _ i \n              (@in_ctxt i2 l2 x r2 c2 (fill c2 (Raw.Node i2 l2 x r2)) okt2\n                (@eq_refl Raw.tree (fill c2 (Raw.Node i2 l2 x r2))))). auto.\n    (* c1 = LeftNode *)\n    xinterp_simpl.\n    generalize (cmp_leib x t1).\n    generalize (@in_left x t0 (fill c1 (Raw.Node i1 l1 x r1)) t2 t1\n                      (@in_ctxt i1 l1 x r1 (LeftNode t0 c1 t1 t2)\n                         (Raw.Node t0 (fill c1 (Raw.Node i1 l1 x r1)) t1 t2)\n                         okt1\n                         (@eq_refl Raw.tree\n                            (Raw.Node t0 (fill c1 (Raw.Node i1 l1 x r1)) t1 t2))) okt1).\n    generalize (@in_right x t0 (fill c1 (Raw.Node i1 l1 x r1)) t2 t1\n                      (@in_ctxt i1 l1 x r1 (LeftNode t0 c1 t1 t2)\n                         (Raw.Node t0 (fill c1 (Raw.Node i1 l1 x r1)) t1 t2)\n                         okt1\n                         (@eq_refl Raw.tree\n                            (Raw.Node t0 (fill c1 (Raw.Node i1 l1 x r1)) t1 t2))) okt1).\n    generalize (proj1 (subset_node okt1 okt2 Hsub1))\n               (proj2 (proj2 (subset_node okt1 okt2 Hsub1)))\n               (proj1 (proj2 (subset_node okt1 okt2 Hsub1))).\n    remember_rev (REOrderedTypeAlt.compare x t1) as cmp.\n    destruct cmp.\n      (* cmp = Eq -- contradiction *)\n      assert False. assert (t1 = x). symmetry. apply (cmp_leib _ _ Hcmp). subst.\n      clear Hcmp IHc1. inversion okt1. subst.\n      apply (Raw.lt_tree_not_in x (fill c1 (Raw.Node i1 l1 x r1))) ; auto.\n      apply (fill_is_in eq_refl). contradiction.\n      (* cmp = Lt *)\n      intros. xinterp_simpl. specialize (IHc1 (ok_left okt1) e).\n      rewrite (@proof_irrelevance _ (in_ctxt (ok_left okt1) eq_refl) (i3 eq_refl)) in IHc1.\n      auto.\n      (* cmp = Gt -- contradiction *)\n      assert False. inversion okt1. subst.\n      apply (Raw.lt_tree_not_in x (fill c1 (Raw.Node i1 l1 x r1))).\n      eapply Raw.lt_tree_trans ; eauto. rewrite (REOrderedTypeAlt.compare_sym).\n      rewrite Hcmp. auto. apply (fill_is_in eq_refl). contradiction.\n   (* c1 = RightNode *)\n   xinterp_simpl.\n   generalize (cmp_leib x t2).\n   generalize (@in_left x t0 t1 (fill c1 (Raw.Node i1 l1 x r1)) t2\n                      (@in_ctxt i1 l1 x r1 (RightNode t0 t1 t2 c1)\n                         (Raw.Node t0 t1 t2 (fill c1 (Raw.Node i1 l1 x r1)))\n                         okt1\n                         (@eq_refl Raw.tree\n                            (Raw.Node t0 t1 t2 (fill c1 (Raw.Node i1 l1 x r1))))) okt1).\n   generalize (@in_right x t0 t1 (fill c1 (Raw.Node i1 l1 x r1)) t2\n                      (@in_ctxt i1 l1 x r1 (RightNode t0 t1 t2 c1)\n                         (Raw.Node t0 t1 t2 (fill c1 (Raw.Node i1 l1 x r1)))\n                         okt1\n                         (@eq_refl Raw.tree\n                            (Raw.Node t0 t1 t2 (fill c1 (Raw.Node i1 l1 x r1))))) okt1).\n   generalize (proj1 (subset_node okt1 okt2 Hsub1))\n               (proj2 (proj2 (subset_node okt1 okt2 Hsub1)))\n               (proj1 (proj2 (subset_node okt1 okt2 Hsub1))).\n    remember_rev (REOrderedTypeAlt.compare x t2) as cmp.\n    destruct cmp.\n      (* cmp = Eq -- contradiction *)\n      assert False. assert (t2 = x). symmetry. apply (cmp_leib _ _ Hcmp). subst.\n      clear Hcmp IHc1. inversion okt1. subst.\n      apply (Raw.gt_tree_not_in x (fill c1 (Raw.Node i1 l1 x r1))) ; auto.\n      apply (fill_is_in eq_refl). contradiction.\n      (* cmp = Lt -- contradiction *)\n      assert False. inversion okt1. subst.\n      apply (Raw.gt_tree_not_in x (fill c1 (Raw.Node i1 l1 x r1))).\n      eapply Raw.gt_tree_trans ; eauto. apply (fill_is_in eq_refl). contradiction.\n      (* cmp = Gt *)\n      intros. xinterp_simpl. specialize (IHc1 (ok_right okt1) e0).\n      rewrite (@proof_irrelevance _ (in_ctxt (ok_right okt1) eq_refl) (i0 eq_refl)) in IHc1.\n      auto.\n  Qed.\n\n  Lemma inject_tree_iso : \n    forall t1 (okt1:Raw.Ok t1) t2 (okt2:Raw.Ok t2) Hsub1 Hsub2\n           (v:xt_interp (tree_type t1)), \n      xinterp (inject_xform_tree okt2 okt1 Hsub2)\n         (xinterp (inject_xform_tree okt1 okt2 Hsub1) v) = v.\n  Proof.\n    intros.\n    generalize (@inject_deconstruct2 t1 okt1 v).\n    intros. destruct H as [i1 [l1 [x [r1 [vx [c1 [H1 H2]]]]]]]. \n    assert (Raw.In x t2).\n    rewrite (Raw.subset_spec) in Hsub1 ; auto. apply (Hsub1 x). subst.\n    apply (fill_is_in eq_refl). \n    specialize (in_gives_ctxt H). intros.\n    destruct H0 as [c2 [i2 [l2 [r2 H0]]]].  subst.\n    rewrite inject_find_is_find. rewrite inject_find_is_find. auto.\n  Qed.\n\n  Lemma xcoerce_refl t1 t2 (x:t1 ->> t2) : \n    xcoerce x eq_refl eq_refl = x.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma xcoerce_cod : \n    forall t1 t2 t3 (x:t1 ->> t2) (H:t2 = t3) (v:xt_interp t1),\n      xinterp (xcoerce x eq_refl H) v = \n      cast (interp_eq H) (xinterp x v).\n  Proof.\n    intros. subst. rewrite xcoerce_refl. auto.\n  Qed.\n\n  Lemma equal_iso s1 s2 (H:Equal s1 s2) v : \n    (xinterp (equal_xform (Equal_sym H)) \n      (xinterp (equal_xform H) v)) = v.\n  Proof.\n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2].\n    unfold equal_xform. simpl. apply inject_tree_iso.\n  Qed.    \n\n  (* Lift up from trees to sets *)\n  Lemma equal_xform_corr : \n    forall s1 s2 (H:Equal s1 s2) str v,\n      in_re_set s1 str v <-> in_re_set s2 str (xinterp (@equal_xform s1 s2 H) v).\n  Proof.\n    destruct s1 as [s1 okt1]. \n    destruct s2 as [s2 okt2]. \n    unfold Equal, in_re_set, equal_xform, inject_xform. simpl.\n    intros. apply inject_xform_tree_corr. rewrite (Raw.subset_spec) ; auto.\n    intro. intro. specialize (H a). tauto.\n  Qed.\n\n  Lemma equal_xform_corr2 rs1 rs2 (H:Equal rs1 rs2)\n     ty (f:re_set_type rs1 ->> xList_t ty) str v:\n    in_re_set_xform (existT _ rs1 f) str v <->\n    in_re_set_xform\n      (existT _ rs2 (xcomp (equal_xform (Equal_sym H)) f)) str v.\n  Proof.\n    specialize (equal_xform_corr H str). unfold in_re_set_xform.\n    crush. generalize (proj1 (H0 x) H1). intro. econstructor ; split ; eauto.\n    xinterp_simpl. rewrite equal_iso. auto.\n    generalize (proj2 (H0 (xinterp (equal_xform (Equal_sym H)) x))).\n    generalize (Equal_sym H). intro. \n    rewrite (@proof_irrelevance _ H (Equal_sym e)). rewrite equal_iso.\n    intro. specialize (H3 H1). econstructor ; split ; eauto.\n    xinterp_simpl. rewrite (@proof_irrelevance _ e (Equal_sym H)). auto.\n  Qed.\n\n  (* Now we must lift up the underlying set operations to operations over\n     a pair of a set and a transform, whose domain is taken from the type\n     of the set. *)\n\n  Lemma create_xform_corr ty l fl x fx r fr str v : \n    in_tree_xform (@create_xform ty l fl x fx r fr) str v <-> \n    in_tree_xform (existT _ l fl) str v \\/\n    in_re_xform (existT _ x fx) str v \\/\n    in_tree_xform (existT _ r fr) str v.\n  Proof.\n    simpl. unfold in_tree. crush.\n    repeat in_regexp_inv ; xmatch_simpl_hyp ; crush.\n    econstructor ; crush ; xmatch_simpl ; crush.\n    econstructor ; crush ; xmatch_simpl ; crush.\n    econstructor ; crush ; xmatch_simpl ; crush.\n  Qed.\n\n  Definition assert_false_xform := create_xform.\n  Extraction Implicit assert_false_xform [ty].\n\n  Lemma assert_false_xform_erase : \n    forall t l fl x fx r fr, projT1 (@assert_false_xform t l fl x fx r fr) = \n                             Raw.assert_false l x r.\n    auto.\n  Qed.\n\n  Lemma assert_false_xform_corr ty l fl x fx r fr str v : \n    in_tree_xform (@create_xform ty l fl x fx r fr) str v <-> \n    in_tree_xform (existT _ l fl) str v \\/\n    in_re_xform (existT _ x fx) str v \\/\n    in_tree_xform (existT _ r fr) str v.\n  Proof.\n    apply (create_xform_corr l fl x fx r fr str v).\n  Qed.\n\n  Definition bal_xform t (l:Raw.tree) (fl : tree_type l ->> xList_t t)\n                         (x:regexp) (fx : regexp_type x ->> xList_t t)\n                         (r:Raw.tree) (fr : tree_type r ->> xList_t t) : \n    tree_xf_pair t :=\n    let hl := Raw.height l in \n    let hr := Raw.height r in \n    if Int.Z_as_Int.ltb (Int.Z_as_Int.add hr 2) hl then\n      match l return tree_type l ->> xList_t t -> {s:Raw.tree & tree_type s ->> xList_t t}\n      with \n        | Raw.Leaf => fun _ => assert_false_xform l fl x fx r fr\n        | Raw.Node i ll lx lr => \n          if Int.Z_as_Int.leb (Raw.height lr) (Raw.height ll) then\n            fun fl0 =>  \n              let (r',fr') := (create_xform lr (xcomp (xcomp xinr xinr) fl0) x fx r fr) in \n              create_xform ll (xcomp xinl fl0) lx (xcomp (xcomp xinl xinr) fl0) r' fr'\n          else \n            match lr return tree_type (Raw.Node i ll lx lr) ->> xList_t t -> \n                            { s:Raw.tree & tree_type s ->> xList_t t}\n            with\n              | Raw.Leaf => fun _ => assert_false_xform l fl x fx r fr\n              | Raw.Node j lrl lrx lrr => \n                fun fl0 => \n                  let (l',fl') := \n                      create_xform ll (xcomp xinl fl0) \n                                   lx (xcomp (xcomp xinl xinr) fl0) \n                                   lrl (xcomp (xcomp xinl (xcomp xinr xinr)) fl0) in \n                  let (r',fr') := \n                      create_xform lrr \n                                   (xcomp (xcomp xinr (xcomp xinr (xcomp xinr xinr))) fl0) \n                                   x fx r fr in \n                  create_xform l' fl' \n                               lrx (xcomp (xcomp xinl (xcomp xinr (xcomp xinr xinr))) fl0)\n                               r' fr'\n            end \n      end fl\n    else if Int.Z_as_Int.ltb (Int.Z_as_Int.add hl 2) hr then \n      match r return tree_type r ->> xList_t t -> {rs:Raw.tree & tree_type rs ->> xList_t t}\n      with \n        | Raw.Leaf => fun _ => assert_false_xform l fl x fx r fr\n        | Raw.Node i rl rx rr => \n          if Int.Z_as_Int.leb (Raw.height rl) (Raw.height rr) then \n            fun fr0 => \n              let (l',f') := create_xform l fl x fx rl (xcomp xinl fr0) in \n              create_xform l' f' rx (xcomp (xcomp xinl xinr) fr0) \n                           rr (xcomp (xcomp xinr xinr) fr0)\n          else \n            match rl return (tree_type (Raw.Node i rl rx rr)) ->> xList_t t -> \n                            {rs:Raw.tree & tree_type rs ->> xList_t t}\n            with \n              | Raw.Leaf => fun _ => assert_false_xform l fl x fx r fr\n              | Raw.Node j rll rlx rlr => \n                fun fr0 => \n                  let (l',fl') := \n                      create_xform l fl x fx rll (xcomp (xcomp xinl xinl) fr0) in \n                  let (r',fr') := \n                      create_xform rlr (xcomp (xcomp xinr (xcomp xinr xinl)) fr0)\n                                   rx (xcomp (xcomp xinl xinr) fr0)\n                                   rr (xcomp (xcomp xinr xinr) fr0) in \n                  create_xform l' fl' rlx (xcomp (xcomp xinl (xcomp xinr xinl)) fr0) r' fr'\n            end\n      end fr\n         else create_xform l fl x fx r fr.\n\n  Extraction Implicit bal_xform [t].\n\n  Lemma bal_xform_erase : \n    forall t l fl x fx r fr, projT1 (@bal_xform t l fl x fx r fr) = Raw.bal l x r.\n  Proof.\n    intros. unfold bal_xform, Raw.bal.\n    replace 2 with (Int.Z_as_Int._2) ; auto.\n    destruct_head.\n    - destruct l.\n      + apply assert_false_xform_erase.\n      + destruct_head.\n        * remember (create_xform l2 (xcomp (xcomp xinr xinr) fl) x fx r fr) as e.\n          destruct e as [r' fr']. rewrite (create_xform_erase). \n          replace (Raw.create l2 x r) with r' ; auto.\n          assert (r' = projT1 (existT\n                                 (fun s:Raw.tree => tree_type s ->> xList_t t0) r' fr')).\n            auto.\n          rewrite Heqe in H. rewrite (create_xform_erase) in H. auto.\n        * destruct l2. \n          { apply assert_false_xform_erase. }\n          { remember (create_xform l1 (xcomp xinl fl) t2 (xcomp (xcomp xinl xinr) fl)\n                                   l2_1 (xcomp (xcomp xinl (xcomp xinr xinr)) fl)) as e1.\n            remember (create_xform l2_2\n                        (xcomp (xcomp xinr (xcomp xinr (xcomp xinr xinr))) fl) \n                        x fx r fr) as e2.\n            destruct e1 as [l' fl']. destruct e2 as [r' fr'].\n            rewrite create_xform_erase.\n            replace (l') with \n              (projT1 (existT (fun s => tree_type s->>xList_t t0) l' fl')) ; auto.\n            rewrite Heqe1. rewrite create_xform_erase.\n            replace (r') with\n              (projT1 (existT (fun s => tree_type s ->> xList_t t0) r' fr')) ; auto.\n            rewrite Heqe2. rewrite create_xform_erase. auto. }\n    - destruct_head.\n      destruct r. apply assert_false_xform_erase.\n      destruct_head.\n      remember (create_xform l fl x fx r1 (xcomp xinl fr)) as e.\n      destruct e. rewrite create_xform_erase.\n      replace x0 with (projT1 (existT (fun s => tree_type s ->>xList_t t0) x0 x1)) ; auto.\n      rewrite Heqe. rewrite create_xform_erase. auto.\n      destruct r1. apply assert_false_xform_erase.\n      remember (create_xform l fl x fx r1_1 (xcomp (xcomp xinl xinl) fr)) as e1.\n      remember (create_xform r1_2 \n                           (xcomp (xcomp xinr (xcomp xinr xinl)) fr) t2\n                           (xcomp (xcomp xinl xinr) fr) r2 \n                           (xcomp (xcomp xinr xinr) fr)) as e2.\n      destruct e1 as [l' fl']. destruct e2 as [r' fr'].\n      rewrite create_xform_erase. \n      replace l' with (projT1 (existT (fun s => tree_type s ->> xList_t t0) l' fl')) ; auto.\n      rewrite Heqe1. rewrite create_xform_erase.\n      replace r' with (projT1 (existT (fun s => tree_type s ->> xList_t t0) r' fr')) ; auto.\n      rewrite Heqe2. rewrite create_xform_erase. auto.\n      apply create_xform_erase.\n  Qed.\n\n  Lemma bal_xform_corr1 ty l fl x fx r fr str v : \n    in_tree_xform (@bal_xform ty l fl x fx r fr) str v -> \n    in_tree_xform (existT _ l fl) str v \\/ \n    in_re_xform (existT _ x fx) str v \\/\n    in_tree_xform (existT _ r fr) str v.\n  Proof.\n    Ltac reduce_if_hyp := \n    match goal with \n      | [ H : context[if ?e then _ else _] |- _ ] => destruct e\n    end.\n\n    simpl ; unfold bal_xform ; intros. reduce_if_hyp.\n    destruct l. generalize (proj1 (assert_false_xform_corr _ _ _ _ _ _ _ _) H). crush.\n    reduce_if_hyp. \n    unfold create_xform in H. simpl in H. unfold in_tree in *. crush.\n    (repeat in_regexp_inv) ; xmatch_simpl_hyp ; crush ; left ; econstructor ; crush.\n    destruct l2. generalize (proj1 (assert_false_xform_corr _ _ _ _ _ _ _ _) H). crush.\n    unfold create_xform in H. simpl in H. unfold in_tree in *. crush.\n    (repeat in_regexp_inv) ; xmatch_simpl_hyp ; crush. left ; crush. \n    left ; econstructor ; crush. left ; econstructor ; crush. left ; econstructor ; crush.\n    reduce_if_hyp. destruct r.\n    generalize (proj1 (assert_false_xform_corr _ _ _ _ _ _ _ _) H). crush.\n    reduce_if_hyp. unfold create_xform in H. simpl in H.\n    unfold in_tree in *. crush. repeat in_regexp_inv ; xmatch_simpl_hyp ; crush.\n    right ; right ; crush. right ; right ; crush. right ; right ; crush.\n    destruct r1.\n    generalize (proj1 (assert_false_xform_corr _ _ _ _ _ _ _ _) H) ; crush.\n    unfold create_xform in H. unfold in_tree in *. crush. unfold in_tree in *.\n    crush. (repeat in_regexp_inv) ; xmatch_simpl_hyp ; crush. \n    right ; right ; crush. right ; right ; econstructor ; crush.\n    right ; right ; econstructor ; split ; crush. right ; right ; econstructor ; \n    split ; crush. right ; right ; econstructor ; split ; crush.\n    generalize (proj1 (create_xform_corr _ _ _ _ _ _ _ _) H) ; crush.\n  Qed.\n\n  Lemma bal_xform_corr2 ty l fl x fx r fr str v : \n    in_tree_xform (existT _ l fl) str v \\/ \n    in_re_xform (existT _ x fx) str v \\/ \n    in_tree_xform (existT _ r fr) str v -> \n    in_tree_xform (@bal_xform ty l fl x fx r fr) str v.\n  Proof.\n    unfold bal_xform. intros. \n    repeat match goal with [ |- in_tree_xform (if ?e then _ else _) _ _] => destruct e end.\n    destruct l. apply assert_false_xform_corr. auto.\n    match goal with [ |- in_tree_xform ((if ?e then _ else _) _) _ _ ] => destruct e end.\n    unfold create_xform ; crush ; unfold in_tree in * ; crush ; repeat in_regexp_inv ; \n    econstructor ; split ; eauto ; xmatch_simpl ; crush.\n    destruct l2. \n    unfold assert_false_xform ; crush ; unfold in_tree in * ; crush ; repeat in_regexp_inv ;\n    econstructor ; split ; eauto ; xmatch_simpl ; crush.\n    unfold create_xform ; simpl. unfold in_tree_xform in *. unfold in_tree in *.\n    simpl in *. crush; repeat in_regexp_inv ; econstructor ; split ; eauto ; \n    xmatch_simpl ; crush.\n    destruct r. apply assert_false_xform_corr ; auto.\n    match goal with [ |- in_tree_xform ((if ?e then _ else _) _) _ _] => destruct e end.\n    unfold create_xform. unfold in_tree_xform in *. unfold in_tree in *. simpl in *.\n    crush ; (repeat in_regexp_inv) ; econstructor ; split ; eauto ; \n    xmatch_simpl ; crush.\n    destruct r1. apply assert_false_xform_corr ; auto.\n    unfold create_xform. unfold in_tree_xform in *. unfold in_tree in *. simpl in *.\n    crush ; (repeat in_regexp_inv) ; econstructor ; split ; eauto ; \n    xmatch_simpl ; crush.\n    apply create_xform_corr ; auto.\n  Qed.\n\n  Lemma bal_xform_corr ty l fl x fx r fr str v : \n    in_tree_xform (existT _ l fl) str v \\/ \n    in_re_xform (existT _ x fx) str v \\/ \n    in_tree_xform (existT _ r fr) str v <-> \n    in_tree_xform (@bal_xform ty l fl x fx r fr) str v.\n  Proof.\n    intros. split. apply bal_xform_corr2. apply bal_xform_corr1.\n  Qed.    \n\n  Fixpoint add_xform_tree \n           (t: xtype)\n           (x:regexp) \n           (f1:regexp_type x ->> xList_t t) \n           (s:Raw.tree) : (tree_type s ->> xList_t t) ->\n           {rs:Raw.tree & tree_type rs ->> xList_t t} := \n    match s return tree_type s ->> xList_t t -> {rs:Raw.tree & tree_type rs ->> xList_t t} \n    with\n        | Raw.Leaf => \n          fun f2 => \n            existT _ (Raw.Node 1 Raw.Leaf x Raw.Leaf) \n                   (xcomp (xmatch xzero (xmatch xid xzero)) f1)\n        | Raw.Node h l y r => \n          match REOrderedTypeAlt.compare x y as p \n          return REOrderedTypeAlt.compare x y = p -> _\n          with \n            | Eq => fun H f2 => \n                      existT _ (Raw.Node h l y r)\n                       (xmatch (xcomp xinl f2)\n                         (xmatch (xcomp (xpair (xcomp (xcomp xinl xinr) f2) (eq_rec x\n                           (fun y0 : regexp => regexp_type y0 ->> xList_t t)\n                           f1 y (cmp_leib x y H))) xapp)\n                                 (xcomp (xcomp xinr xinr) f2)))\n            | Lt => fun H f2 => \n                      match add_xform_tree x f1 l (xcomp xinl f2) with\n                        | existT _ l' f' => \n                          bal_xform l' f' y (xcomp (xcomp xinl xinr) f2) r \n                                    (xcomp (xcomp xinr xinr) f2)\n                      end\n            | Gt => fun H f2 => \n                      match add_xform_tree x f1 r (xcomp (xcomp xinr xinr) f2) with\n                        | existT _ r' f' => \n                          bal_xform l (xcomp xinl f2) y (xcomp (xcomp xinl xinr) f2) r' f'\n                      end\n          end eq_refl\n    end.\n  Extraction Implicit add_xform_tree [t].\n\n  Lemma add_xform_tree_erase : \n    forall t s x f1 f, \n      projT1 (@add_xform_tree t x f1 s f) = Raw.add x s.\n  Proof.\n    induction s ; intros ; auto. unfold add_xform_tree.\n    fold add_xform_tree. unfold Raw.add. fold Raw.add.\n    generalize (cmp_leib x t2).\n    destruct (REOrderedTypeAlt.compare x t2) ; auto ; intros.\n    specialize (IHs1 x f1 (xcomp xinl f)).\n    match goal with \n        | [ |- projT1 (match ?e with | existT _ _ _ => _ end) = _ ] => remember e as e1\n    end.\n    destruct e1. rewrite bal_xform_erase. \n    unfold tree_type in IHs1, Heqe1. \n    simpl regexp_type in IHs1.\n    rewrite <- Heqe1 in IHs1. rewrite <- IHs1. auto.\n    specialize (IHs2 x f1 (xcomp (xcomp xinr xinr) f)).\n    fold regexp_type in IHs2. fold tree_to_regexp in IHs2. \n    unfold tree_type in *.\n    match goal with \n      | [ |- projT1 (match ?e with | existT _ _ _ => _ end) = _ ] => remember e as e1\n    end.\n    destruct e1. rewrite bal_xform_erase. rewrite <- IHs2. auto.\n  Qed.\n\n  Lemma add_xform_tree_corr : \n    forall ty tr ftr x fx str v,\n      in_tree_xform (@add_xform_tree ty x fx tr ftr) str v <-> \n      in_re_xform (existT _ x fx) str v \\/ in_tree_xform (existT _ tr ftr) str v.\n  Proof.\n    induction tr ; intros ; split ; crush.\n    unfold in_tree in H. simpl in H. repeat in_regexp_inv. xmatch_simpl_hyp ; crush.\n    unfold in_tree. simpl. econstructor ; crush. xmatch_simpl ; crush. destruct x0.\n    generalize H ; clear H. generalize (cmp_leib x t1). \n    generalize (REOrderedTypeAlt.compare x t1). destruct c. intro.\n    generalize (e eq_refl). intro. subst. simpl. crush. unfold in_tree in *.\n    simpl in *. (repeat in_regexp_inv) ; repeat (xinterp_simpl ; crush).\n    generalize (in_app_or _ _ _ H0). crush. right ; econstructor ; crush.\n    right ; econstructor ; crush. intros.\n    specialize (IHtr1 (xcomp xinl ftr) x fx str v) ; clear IHtr2.\n    unfold tree_type in H.\n    simpl regexp_type in IHtr1.\n    match goal with \n      | [ H : in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ |- _ ] => \n        remember exp as e1\n    end.\n    destruct e1. generalize (bal_xform_corr1 _ _ _ _ _ _ _ _ H). intros.\n    destruct H0. generalize (proj1 IHtr1 H0). clear IHtr1 H0 H. intro.\n    destruct H. crush. unfold in_tree in *. crush ; xinterp_simpl. crush.\n    crush ; xinterp_simpl ; unfold in_tree in * ; right ; econstructor ; crush.\n    intros. specialize (IHtr2 (xcomp (xcomp xinr xinr) ftr) x fx str v). clear IHtr1.\n    fold regexp_type in IHtr2. fold tree_to_regexp in IHtr2. unfold tree_type in H.\n    match goal with \n      | [ H : in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ |- _ ] => \n        remember exp as e1\n    end.\n    destruct e1. generalize (bal_xform_corr1 _ _ _ _ _ _ _ _ H) ; intros.\n    destruct H0. crush. xinterp_simpl. unfold in_tree. right ; econstructor ; crush.\n    destruct H0. unfold in_tree. crush. xinterp_simpl. right ; econstructor ; crush.\n    generalize (proj1 IHtr2 H0). clear IHtr2 H0 H. intro. destruct H. crush.\n    unfold in_tree in *. crush. xinterp_simpl. right ; econstructor ; crush.\n    generalize (cmp_leib x t1). generalize (REOrderedTypeAlt.compare x t1).\n    destruct c ; intro. generalize (e eq_refl) ; intro ; subst. simpl. \n    unfold in_tree. econstructor ; crush. xinterp_simpl. apply in_or_app.\n    right ; auto. specialize (IHtr1 (xcomp xinl ftr) x fx str v). clear IHtr2.\n    unfold tree_type. simpl regexp_type in IHtr1.\n    match goal with \n      | [ |- in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ ] => \n        remember exp as e1\n    end.\n    destruct e1. apply bal_xform_corr2. left. apply IHtr1. left. crush.\n    clear IHtr1. specialize (IHtr2 (xcomp (xcomp xinr xinr) ftr) x fx str v).\n    unfold tree_type. simpl regexp_type in IHtr2.\n    match goal with \n      | [ |- in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ ] => \n        remember exp as e1\n    end.\n    destruct e1. apply bal_xform_corr2. right. right. apply IHtr2. left ; crush.\n    generalize (cmp_leib x t1). generalize (REOrderedTypeAlt.compare x t1).\n    destruct c ; intros. generalize (e eq_refl) ; intros ; subst. simpl.\n    exists x0. split. auto. xinterp_simpl. destruct x0. xinterp_simpl. auto.\n    xinterp_simpl. destruct s. xinterp_simpl. apply in_or_app. left ; auto.\n    xinterp_simpl ; auto.\n    specialize (IHtr1 (xcomp xinl ftr) x fx str v). clear IHtr2.\n    unfold tree_type. simpl regexp_type in IHtr1.\n    match goal with \n      | [ |- in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ ] => \n        remember exp as e1\n    end.\n    destruct e1. apply bal_xform_corr2. unfold in_tree in H. simpl in H.\n    generalize (inv_alt H) ; clear H. intros. destruct H. \n    destruct H as [v1 [H1 H2]]. subst. left. apply IHtr1. unfold in_tree.\n    right ; econstructor ; split ; eauto. xinterp_simpl. auto.\n    destruct H as [v2 [H1 H2]]. subst. generalize (inv_alt H1). clear H1.\n    intro H1. destruct H1. destruct H as [v1 [H1 H2]]. subst.\n    right ; left. simpl. econstructor ; split ; eauto. xinterp_simpl ; auto.\n    destruct H as [v3 [H1 H2]]. subst. right ; right. simpl. unfold in_tree.\n    econstructor ; split ; eauto ; xinterp_simpl ; auto.\n    clear IHtr1. specialize (IHtr2 (xcomp (xcomp xinr xinr) ftr) x fx str v).\n    unfold tree_type. simpl regexp_type in IHtr2.\n    match goal with \n      | [ |- in_tree_xform (match ?exp with existT _ _ _ => _ end) _ _ ] => \n        remember exp as e1\n    end.\n    destruct e1. apply bal_xform_corr2. simpl in *. unfold in_tree in *. simpl in *.\n    generalize (inv_alt H) ; clear H ; intro H. destruct H. \n    destruct H as [v1 [H1 H2]]. subst. left. econstructor ; split ; eauto.\n    xinterp_simpl ; auto. destruct H as [v2 [H1 H2]]. subst.\n    generalize (inv_alt H1) ; clear H1 ; intro H. destruct H.\n    destruct H as [v1 [H1 H2]]. subst. right ; left. econstructor ; split ; eauto.\n    xinterp_simpl ; auto. destruct H as [v3 [H1 H2]]. subst. right ; right.\n    apply IHtr2. right. econstructor. split ; eauto. xinterp_simpl ; auto.\n  Qed.\n\n  Fixpoint join_xform t (l:Raw.tree) : \n    tree_type l->>xList_t t -> \n    forall x, regexp_type x->>xList_t t -> \n           forall r, tree_type r->>xList_t t -> {rs:Raw.tree & tree_type rs ->> xList_t t} :=\n    match l return \n          tree_type l->>xList_t t -> \n          forall x, regexp_type x->>xList_t t -> \n                    forall r, tree_type r->>xList_t t -> \n                              {rs:Raw.tree & tree_type rs ->> xList_t t}\n    with \n      | Raw.Leaf => fun _ => (@add_xform_tree t)\n      | Raw.Node lh ll lx lr => \n        fun fl x fx => \n          fix join_aux (r:Raw.tree) : \n            tree_type r->>xList_t t -> {rs:Raw.tree & tree_type rs ->> xList_t t} := \n          match r return \n                tree_type r->>xList_t t -> {rs:Raw.tree & tree_type rs ->> xList_t t}\n          with \n            | Raw.Leaf => fun _ => add_xform_tree x fx (Raw.Node lh ll lx lr) fl\n            | Raw.Node rh rl rx rr => \n              fun fr => \n                if Int.Z_as_Int.ltb (Int.Z_as_Int.add rh Int.Z_as_Int._2) lh then\n                  let (r',fr') := (join_xform lr (xcomp (xcomp xinr xinr) fl) x fx \n                                              (Raw.Node rh rl rx rr) fr) in\n                  bal_xform ll (xcomp xinl fl) lx (xcomp (xcomp xinl xinr) fl) r' fr'\n                else \n                  if Int.Z_as_Int.ltb (Int.Z_as_Int.add lh Int.Z_as_Int._2) rh then\n                    let (l',fl') := join_aux rl (xcomp xinl fr) in\n                    bal_xform l' fl' rx (xcomp (xcomp xinl xinr) fr) \n                              rr (xcomp (xcomp xinr xinr) fr)\n                  else create_xform (Raw.Node lh ll lx lr) fl x fx \n                                    (Raw.Node rh rl rx rr) fr\n          end\n    end.\n  Extraction Implicit join_xform [t].\n\n  Lemma join_xform_erase : forall t l fl x fx r fr, \n      projT1 (@join_xform t l fl x fx r fr) = Raw.join l x r.\n  Proof.                             \n    induction l. intros ; simpl ; apply add_xform_tree_erase.\n    intros fl x fx. \n    unfold join_xform. fold join_xform.\n    unfold Raw.join. fold Raw.join.\n    match goal with \n      | [ |- forall _ _, projT1 (?fexp1 _ _) = ?fexp2 _ ] => \n        remember fexp1 as join_aux_xform ; remember fexp2 as join_aux\n    end.\n    induction r ; intros. \n      rewrite Heqjoin_aux ; rewrite Heqjoin_aux_xform ; \n      rewrite add_xform_tree_erase ; auto.\n    rewrite Heqjoin_aux. rewrite <- Heqjoin_aux.\n    rewrite Heqjoin_aux_xform. rewrite <- Heqjoin_aux_xform.\n    destruct_head.\n    specialize (IHl2 (xcomp (xcomp xinr xinr) fl) x fx (Raw.Node t3 r1 t4 r2) fr).\n    remember (join_xform l2 (xcomp (xcomp xinr xinr) fl) x fx (Raw.Node t3 r1 t4 r2) fr)\n             as e.\n    destruct e.\n    rewrite bal_xform_erase. rewrite <- IHl2. auto.\n    destruct_head.\n    specialize (IHr1 (xcomp xinl fr)). \n    remember (join_aux_xform r1 (xcomp xinl fr)) as e. \n    destruct e. rewrite bal_xform_erase. rewrite <- IHr1. auto.\n    rewrite create_xform_erase. auto.\n  Qed.\n\n  Lemma join_xform_corr : forall ty l fl x fx r fr str v,\n    in_tree_xform (@join_xform ty l fl x fx r fr) str v <-> \n      in_tree_xform (existT _ l fl) str v \\/ \n      in_re_xform (existT _ x fx) str v \\/ \n      in_tree_xform (existT _ r fr) str v.\n  Proof.\n    induction l. split. simpl ; intro. \n    generalize (proj1 (add_xform_tree_corr r fr x fx str v) H). crush.\n    intros. apply add_xform_tree_corr. crush. destruct x0.\n    intros fl x fx. unfold join_xform. fold join_xform.\n    match goal with \n        [ |- forall _ _ _ _, in_tree_xform (?fexp _ _) _ _ <-> _ ] => \n        remember fexp as join_aux_xform\n    end.\n    induction r. rewrite Heqjoin_aux_xform. split. intro H.\n    generalize (proj1 (add_xform_tree_corr _ _ _ _ _ _) H). simpl. crush.\n    intros. apply add_xform_tree_corr. crush. destruct x0.\n    rewrite Heqjoin_aux_xform. intros. \n    split ; intro.\n    destruct (Int.Z_as_Int.ltb (Int.Z_as_Int.add t2 Int.Z_as_Int._2) t0).\n    clear IHl1 IHr1 IHr2. specialize (IHl2 (xcomp (xcomp xinr xinr) fl) x fx\n                                           (Raw.Node t2 r1 t3 r2) fr str v).\n    remember (join_xform l2 (xcomp (xcomp xinr xinr) fl) x fx\n                                   (Raw.Node t2 r1 t3 r2) fr) as e.\n    destruct e. generalize (bal_xform_corr1 _ _ _ _ _ _ _ _ H). clear H.\n    intros. crush ; unfold in_tree ; xinterp_simpl ; crush. left.\n    econstructor ; crush. specialize (H0 (@ex_intro _ _ x2 (conj H H2))).\n    crush. xinterp_simpl. left ; econstructor ; crush.\n    rewrite <- Heqjoin_aux_xform in H.\n    destruct (Int.Z_as_Int.ltb (Int.Z_as_Int.add t0 Int.Z_as_Int._2) t2).\n    specialize (IHr1 (xcomp xinl fr) str v). clear IHl1 IHl2 Heqjoin_aux_xform IHr2.\n    remember (join_aux_xform r1 (xcomp xinl fr)) as e. destruct e.\n    generalize (bal_xform_corr1 _ _ _ _ _ _ _ _ H). clear H. \n    intros ; crush ; unfold in_tree ; xinterp_simpl ; crush. clear H1.\n    specialize (H0 (ex_intro _ x2 (conj H H2))). crush. xinterp_simpl.\n    right. right. econstructor ; crush. \n    xinterp_simpl ; right ; right ; econstructor ; crush.\n    xinterp_simpl ; right ; right ; econstructor ; crush.\n    clear Heqjoin_aux_xform IHr1 IHr2 IHl1 IHl2. crush. unfold in_tree in *.\n    crush. repeat in_regexp_inv ; xinterp_simpl ; crush. left ; econstructor ; crush.\n    left ; econstructor ; crush. xinterp_simpl ; right ; left ; econstructor ; crush.\n    xinterp_simpl ; right ; right ; econstructor ; crush.\n    xinterp_simpl ; right ; right ; econstructor ; crush.\n    xinterp_simpl ; right ; right ; econstructor ; crush.\n    rewrite <- Heqjoin_aux_xform.\n    destruct (Int.Z_as_Int.ltb (Int.Z_as_Int.add t2 Int.Z_as_Int._2) t0).\n    specialize (IHl2 (xcomp (xcomp xinr xinr) fl) x fx (Raw.Node t2 r1 t3 r2) fr str v).\n    clear IHl1 Heqjoin_aux_xform IHr1 IHr2.\n    remember (join_xform l2 (xcomp (xcomp xinr xinr) fl) x fx (Raw.Node t2 r1 t3 r2) fr)\n    as e. destruct e. apply bal_xform_corr. crush. unfold in_tree in *. simpl in *.\n    repeat in_regexp_inv ; xinterp_simpl ; crush. left ; econstructor ; split ; eauto.\n    xinterp_simpl ; auto. right ; left ; econstructor ; split ; eauto. \n    xinterp_simpl ; auto. right. right. apply H1. left ; econstructor ; split ; eauto.\n    xinterp_simpl ; auto. right. right. apply H1. right ; left ; econstructor ; split.\n    eauto. auto. unfold in_tree in *. simpl in *. repeat in_regexp_inv ; xinterp_simpl.\n    right ; right. apply H1. right ; right. econstructor ; crush.\n    right ; right ; apply H1. right ; right ; econstructor ; crush.\n    right ; right ; apply H1. right ; right ; econstructor ; crush.\n    destruct (Int.Z_as_Int.ltb (Int.Z_as_Int.add t0 Int.Z_as_Int._2) t2).\n    clear Heqjoin_aux_xform IHl1 IHl2 IHr2. specialize (IHr1 (xcomp xinl fr) str v).\n    remember (join_aux_xform r1 (xcomp xinl fr)) as e. destruct e.\n    apply bal_xform_corr. crush. unfold in_tree in *. simpl in *.\n    repeat in_regexp_inv ; xinterp_simpl ; crush. left ; apply H1.\n    right ; right ; econstructor ; split ; eauto. xinterp_simpl ; auto.\n    right ; left ; econstructor ; split ; eauto ; xinterp_simpl ; auto.\n    right ; right ; econstructor ; split ; eauto ; xinterp_simpl ; auto.\n    clear Heqjoin_aux_xform IHl1 IHl2 IHr1 IHr2. \n    crush ; unfold in_tree in * ; simpl in * ; repeat in_regexp_inv ; \n    xinterp_simpl ; crush ; econstructor ; split ; eauto ; xinterp_simpl ; auto.\n  Qed.\n \n  Record triple_xform (t:xtype) (x:regexp) : Type := \n    mkTX { t_left : Raw.tree ; t_left_xform : tree_type t_left ->> xList_t t ; \n           t_in : option (regexp_type x ->> xList_t t) ; \n           t_right : Raw.tree ; t_right_xform : tree_type t_right ->> xList_t t\n         }.\n  Extraction Implicit triple_xform [t].\n\n  Fixpoint split_xform t (x:regexp) (s : Raw.tree) :\n                                  tree_type s ->> xList_t t -> triple_xform t x := \n    match s return tree_type s ->> xList_t t -> triple_xform t x with \n      | Raw.Leaf => fun f => {| t_left := Raw.Leaf ; t_left_xform := xzero ; \n                                t_in := None ; \n                                t_right := Raw.Leaf ; t_right_xform := xzero |}\n      | Raw.Node i l y r => \n        fun f => \n          match REOrderedTypeAlt.compare x y as c return \n                REOrderedTypeAlt.compare x y = c -> triple_xform t x with\n            | Eq => fun H => \n                      {| t_left := l ; t_left_xform := xcomp xinl f ; \n                       t_in := \n                         Some (xcomp (eq_rec y \n                                      (fun y0 => regexp_type y0 ->> \n                                         tree_type (Raw.Node i l y r)) \n                                      (xcomp xinl xinr) x (eq_sym (cmp_leib x y H))) f) ; \n                       t_right := r ; t_right_xform := xcomp (xcomp xinr xinr) f |}\n            | Lt => fun _ => \n                      let (ll, fll, opt, rl, frl) := split_xform x l (xcomp xinl f) in \n                      let (r',fr') := join_xform rl frl y (xcomp (xcomp xinl xinr) f) r\n                                                 (xcomp (xcomp xinr xinr) f) in\n                      {| t_left := ll ; t_left_xform := fll ; \n                         t_in := opt ; \n                         t_right := r' ; t_right_xform := fr' |}\n            | Gt => fun _ => \n                      let (rl, frl, opt, rr, frr) := split_xform x r \n                                                      (xcomp (xcomp xinr xinr) f) in \n                      let (l',fl') := join_xform l (xcomp xinl f) y \n                                                 (xcomp (xcomp xinl xinr) f) \n                                                 rl frl in\n                      {| t_left := l' ; t_left_xform := fl' ; \n                         t_in := opt ; \n                         t_right := rr ; t_right_xform := frr |}\n          end eq_refl\n    end.\n  Extraction Implicit split_xform [t].\n\n  Lemma split_xform_erase : forall t x s fs, \n      Raw.split x s = \n      match @split_xform t x s fs with\n        | mkTX _ l _ None r _ => Raw.mktriple l false r\n        | mkTX _ l _ _ r _ => Raw.mktriple l true r\n      end.\n  Proof.\n    induction s ; intros ; auto. unfold Raw.split. fold Raw.split.\n    unfold split_xform. fold split_xform. generalize (cmp_leib x t2).\n    destruct (REOrderedTypeAlt.compare x t2) ; auto ; intro e ; clear e.\n    specialize (IHs1 (xcomp xinl fs)). \n    remember (split_xform x s1 (xcomp xinl fs)) as e1.\n    destruct e1. \n    remember (join_xform t_right0 t_right_xform0 t2 (xcomp (xcomp xinl xinr) fs)\n                         s2 (xcomp (xcomp xinr xinr) fs)) as e2.\n    destruct e2. rewrite IHs1. \n    replace x0 with (projT1 (existT (fun rs => tree_type rs->>xList_t t0) x0 x1)) ; auto.\n    rewrite Heqe2. rewrite join_xform_erase. destruct t_in0 ; auto.\n    specialize (IHs2 (xcomp (xcomp xinr xinr) fs)).\n    rewrite IHs2. destruct (split_xform x s2 (xcomp (xcomp xinr xinr) fs)).\n    remember (join_xform s1 (xcomp xinl fs) t2 (xcomp (xcomp xinl xinr) fs) t_left0\n                         t_left_xform0) as e1.\n    destruct e1. \n    replace x0 with (projT1 (existT (fun rs => tree_type rs->>xList_t t0) x0 x1)) ; auto.\n    rewrite Heqe1. rewrite join_xform_erase. destruct t_in0 ; auto.\n  Qed.\n\n  Definition in_triple_xform ty x (trip : @triple_xform ty x) str v := \n    in_tree_xform (existT _ (t_left trip) (t_left_xform trip)) str v \\/ \n    in_tree_xform (existT _ (t_right trip) (t_right_xform trip)) str v \\/ \n    match (t_in trip) with \n      | Some f => in_re_xform (existT _ x f) str v\n      | None => False\n    end.\n\n  Lemma split_xform_corr : forall ty x s f str v,\n    in_triple_xform (@split_xform ty x s f) str v <-> \n    in_tree_xform (existT _ s f) str v.\n  Proof.\n    induction s ;  intros. \n    unfold in_triple_xform ; crush ; unfold tree_type in * ; crush ; \n    match goal with [ v : void |- _ ] => destruct v end. \n    simpl. split. generalize (cmp_leib x t1). \n    generalize (REOrderedTypeAlt.compare x t1). destruct c. intro e.\n    generalize (e eq_refl). intros ; subst. unfold in_tree. \n    unfold in_triple_xform in H. crush ; xinterp_simpl ; crush. \n    intros. specialize (IHs1 (xcomp xinl f) str v).\n    simpl regexp_type in IHs1.\n    match goal with\n      [ H: in_triple_xform ?exp _ _ <-> _ |- _] => \n      remember exp as e1; destruct e1\n    end.\n    generalize (join_xform_corr t_right0 t_right_xform0 t1 \n                                (xcomp (xcomp xinl xinr) f) s2 \n                                (xcomp (xcomp xinr xinr) f) str v). intro.\n    remember (join_xform t_right0 t_right_xform0 t1 \n                         (xcomp (xcomp xinl xinr) f) s2 \n                                (xcomp (xcomp xinr xinr) f)) as e1.\n    destruct e1. \n    unfold in_triple_xform in *.  simpl in *. destruct H.\n    generalize (proj1 IHs1 (@or_introl _ _ H)). crush. xinterp_simpl. simpl.\n    unfold in_tree. econstructor ; split ; eauto. simpl. eauto.\n    destruct H. generalize (proj1 H0 H). clear H0 ; intro H0.\n    destruct H0. generalize (proj1 IHs1 (@or_intror _ _ (@or_introl _ _ H0))).\n    crush. xinterp_simpl. crush. unfold in_tree. simpl. econstructor ; split ; eauto.\n    destruct H0. crush ; xinterp_simpl. unfold in_tree. simpl. econstructor ; split ;\n    crush. crush ; xinterp_simpl ; unfold in_tree ; simpl. econstructor ; crush.\n    destruct t_in0 ; [ idtac | crush]. \n    specialize (proj1 IHs1 (@or_intror _ _ (@or_intror _ _ H))). crush.\n    unfold in_tree. xinterp_simpl. crush.\n    specialize (IHs2 (xcomp (xcomp xinr xinr) f) str v). clear IHs1. intros.\n    remember (split_xform x s2 (xcomp (xcomp xinr xinr) f)) as e1. destruct e1.\n    generalize (proj1 (join_xform_corr s1 (xcomp xinl f) t1 (xcomp (xcomp xinl xinr) f)\n                                       t_left0 t_left_xform0 str v)). intros.\n    simpl regexp_type in H, H0.\n    match goal with\n      | [H: in_tree_xform ?exp _ _ -> _ |- _] => \n        remember exp as e1; destruct e1\n    end.\n    unfold in_triple_xform in * ; simpl in *. destruct H.\n    generalize (H0 H). clear H0. intro. destruct H0. \n    unfold in_tree in * ; xinterp_simpl ; crush. xinterp_simpl ; econstructor ; crush.\n    destruct H0. unfold in_tree. crush ; xinterp_simpl. crush.\n    generalize (proj1 IHs2 (@or_introl _ _ H0)). \n    unfold in_tree ; crush ; xinterp_simpl ; crush.\n    destruct H. specialize (proj1 IHs2 (@or_intror _ _ (@or_introl _ _ H))).\n    unfold in_tree ; crush ; xinterp_simpl ; crush.\n    destruct t_in0 ; [idtac | crush]. \n    specialize (proj1 IHs2 (@or_intror _ _ (@or_intror _ _ H))). \n    unfold in_tree ; crush ; xinterp_simpl ; crush.\n    generalize (cmp_leib x t1). generalize (REOrderedTypeAlt.compare x t1). destruct c. \n    intros. generalize (e eq_refl). intros ; subst. unfold in_triple_xform. crush.\n    unfold in_tree in H ; simpl in H. repeat in_regexp_inv. left.\n    econstructor ; split ; eauto. xinterp_simpl ; auto.\n    right ; right. econstructor ; split ; eauto. xinterp_simpl ; auto.\n    right ; left ; econstructor ; split ; eauto ; xinterp_simpl ; auto.\n    intros. crush. unfold in_tree in H ; simpl in H.\n    specialize (proj2 (IHs1 (xcomp xinl f) str v)). clear IHs1 IHs2. \n    intros. \n    simpl regexp_type in H1.\n    match goal with\n      | [ H: _ -> in_triple_xform ?exp _ _ |- _] => \n        remember exp as e1; destruct e1\n    end.\n    specialize (proj2 (join_xform_corr t_right0 t_right_xform0 t1 \n                                       (xcomp (xcomp xinl xinr) f)\n                                       s2 (xcomp (xcomp xinr xinr) f) str v)). \n    intros. remember (join_xform t_right0 t_right_xform0 t1 (xcomp (xcomp xinl xinr) f)\n                                 s2 (xcomp (xcomp xinr xinr) f)) as e2. destruct e2.\n    unfold in_triple_xform. simpl. crush.\n    repeat in_regexp_inv. \n    assert (exists v', in_tree s1 str v' /\\ List.In v (xinterp (xcomp xinl f) v')).\n    econstructor ; split ; eauto. xinterp_simpl. auto. specialize (H1 H3).\n    unfold in_triple_xform in H1. simpl in H1. destruct H1. left ; auto.\n    destruct H1. right ; left. auto. right ; right. auto.\n    right ; left. apply H2. right ; left. econstructor ; split ; eauto.\n    xinterp_simpl. auto. right ; left. apply H2. right ; right. econstructor ; \n    split ; eauto. xinterp_simpl. auto.\n    intros. specialize (proj2 (IHs2 (xcomp (xcomp xinr xinr) f) str v)).\n    clear IHs1 IHs2. intros. \n    remember (split_xform x s2 (xcomp (xcomp xinr xinr) f)) as e1.\n    destruct e1. \n    specialize (proj2 (join_xform_corr s1 (xcomp xinl f) t1\n                                       (xcomp (xcomp xinl xinr) f)\n                                       t_left0 t_left_xform0 str v)). intro.\n    simpl regexp_type in H1.\n    match goal with\n      | [H: _ \\/ _ \\/ _ -> in_tree_xform ?exp _ _ |- _ ] => \n        remember exp as e2; destruct e2\n    end.\n    unfold in_triple_xform. simpl. unfold in_tree in H. crush.\n    repeat in_regexp_inv. left. apply H1. left ; econstructor ; split ; eauto.\n    xinterp_simpl ; auto. left ; apply H1. right ; left ; econstructor ; split ; eauto ; \n    xinterp_simpl ; auto. \n    assert (exists v', in_tree s2 str v' /\\ List.In v (xinterp (xcomp (xcomp xinr xinr) f) v')).\n    econstructor ; split ; eauto ; xinterp_simpl ; auto.\n    specialize (H0 H3). unfold in_triple_xform in H0. simpl in H0. \n    destruct H0. left. apply H1. right ; right. crush.\n    destruct H0 ; auto.\n  Qed.\n\n  Fixpoint union_xform_tree t (s1:Raw.tree) : (tree_type s1 ->> xList_t t) -> \n                                      forall s2:Raw.tree, tree_type s2 ->> xList_t t -> \n                                  { rs : Raw.tree & tree_type rs ->> xList_t t } := \n    match s1 return \n          (tree_type s1 ->> xList_t t) -> forall s2:Raw.tree, tree_type s2 ->> xList_t t -> \n                              { rs : Raw.tree & tree_type rs ->> xList_t t }\n    with \n      | Raw.Leaf => fun _ s2 f2 => existT _ s2 f2\n      | Raw.Node i l1 x1 r1 => \n        fun f1 s2 f2 => \n          match s2 return {rs:Raw.tree & tree_type rs ->> xList_t t} with\n              | Raw.Leaf => existT _ (Raw.Node i l1 x1 r1) f1\n              | Raw.Node _ _ _ _ => \n                let (l2',fl2', opt, r2',fr2') := split_xform x1 s2 f2 in \n                let (l',fl') := union_xform_tree l1 (xcomp xinl f1) l2' fl2' in \n                let (r',fr') := union_xform_tree r1 (xcomp (xcomp xinr xinr) f1) r2' fr2'\n                in let xf1 := xcomp (xcomp xinl xinr) f1 in\n                   let xf := match opt with \n                               | None => xf1\n                               | Some fother => xcomp (xpair xf1 fother) xapp\n                             end in \n                join_xform l' fl' x1 xf r' fr'\n          end\n    end.\n  Extraction Implicit union_xform_tree [t].\n\n  Lemma union_xform_tree_erase t s1 : forall f1 s2 f2,\n    projT1 (@union_xform_tree t s1 f1 s2 f2) = Raw.union s1 s2.\n  Proof.\n    induction s1 ; intros ; auto. \n    simpl. destruct s2. auto.\n    remember (split_xform t1 (Raw.Node t2 s2_1 t3 s2_2) f2) as e1.\n    destruct e1.\n    remember (Raw.split t1 (Raw.Node t2 s2_1 t3 s2_2)) as e2.\n    destruct e2.\n    match goal with \n      | [ |- projT1 (match ?exp with | existT _ _ _ => _ end) = _ ] => \n        remember exp as e3 ; destruct e3\n    end.\n    match goal with \n      | [ |- projT1 (match ?exp with | existT _ _ _ => _ end) = _ ] => \n        remember exp as e4 ; destruct e4\n    end.\n    rewrite join_xform_erase.\n    replace x with (projT1 (existT (fun rs => tree_type rs->>xList_t t) x x0)) ; auto.\n    rewrite Heqe3. rewrite IHs1_1.\n    replace x1 with (projT1 (existT (fun rs => tree_type rs->>xList_t t) x1 x2)) ; auto.\n    rewrite Heqe4. rewrite IHs1_2.\n    specialize (split_xform_erase t1 (Raw.Node t2 s2_1 t3 s2_2) f2).\n    intros. rewrite H in Heqe2. \n    remember (split_xform t1 (Raw.Node t2 s2_1 t3 s2_2) f2) as e5.\n    destruct e5. \n    injection Heqe1. intros ; subst. clear Heqe1. \n    destruct t_in2 ; injection Heqe2 ; intros ; subst ; auto.\n  Qed.\n\n  Lemma union_xform_tree_corr : \n    forall ty s1 f1 s2 f2 str v, \n      in_tree_xform (@union_xform_tree ty s1 f1 s2 f2) str v <->\n      in_tree_xform (existT _ s1 f1) str v \\/ in_tree_xform (existT _ s2 f2) str v.\n  Proof.\n    induction s1.\n    intros. simpl. crush. destruct x. \n    intros. destruct s2. simpl. crush. destruct x.\n    unfold union_xform_tree. fold union_xform_tree.\n    generalize (split_xform_corr t1 (Raw.Node t2 s2_1 t3 s2_2) f2 str v).\n    intro. remember (split_xform t1 (Raw.Node t2 s2_1 t3 s2_2) f2) as e.\n    destruct e. unfold in_triple_xform in H. simpl in H.\n    specialize (IHs1_1 (xcomp xinl f1) t_left0 t_left_xform0 str v).\n    remember (union_xform_tree s1_1 (xcomp xinl f1) t_left0 t_left_xform0) as e1.\n    destruct e1.\n    specialize (IHs1_2 (xcomp (xcomp xinr xinr) f1) t_right0 t_right_xform0 str v).\n    remember (union_xform_tree s1_2 (xcomp (xcomp xinr xinr) f1) t_right0 \n                               t_right_xform0) as e2.\n    destruct e2. \n    match goal with \n      | [ |- in_tree_xform (join_xform ?x ?x0 ?t1 ?e ?x1 ?x2) ?str ?v <-> _ ] => \n        generalize (join_xform_corr x x0 t1 e x1 x2 str v) ; intro\n    end.\n    split ; intro.\n    specialize (proj1 H0 H1). clear H0 H1. intro.\n    destruct H0.\n    specialize (proj1 IHs1_1 H0). intro. simpl in *. unfold in_tree in *. simpl in *.\n    crush. xinterp_simpl. left ; econstructor ; crush.\n    destruct H0. destruct t_in0. simpl in *. unfold in_tree. simpl in *.\n    crush. xinterp_simpl. generalize (in_app_or _ _ _ H6).  crush.\n    left ; econstructor ; crush.\n    assert (exists v', in_regexp t1 str v' /\\ List.In v (xinterp x3 v')).\n    crush. specialize (H (@or_intror _ _ (@or_intror _ _ H8))). unfold in_tree in H.\n    crush. left. crush. unfold in_tree ; crush. xinterp_simpl. crush.\n    specialize (proj1 IHs1_2 H0). intro. destruct H1. left. \n    simpl in * ; unfold in_tree in * ; crush. xinterp_simpl ; crush. clear Heqe Heqe2 Heqe1.\n    specialize (proj1 H (@or_intror _ _ (@or_introl _ _ H1))). clear H H1. intro. \n    right ; auto. clear Heqe Heqe1 Heqe2.\n    apply H0. clear H0. \n    destruct H1.\n      simpl in *. unfold in_tree in *. crush. repeat in_regexp_inv.\n      assert (exists v', in_tree s1_1 str v' /\\ List.In v (xinterp (xcomp xinl f1) v')).\n      econstructor ; split ; eauto. xinterp_simpl. auto.\n      specialize (H5 (@or_introl _ _ H7)). left ; auto. right ; left.\n      econstructor ; split ; eauto. destruct t_in0. xinterp_simpl.\n      apply in_or_app. auto. xinterp_simpl. auto.\n      right ; right ; apply H3. left. econstructor ; split ; eauto ; xinterp_simpl ; auto.\n\n      specialize (proj2 H H0). clear H H0. intros. destruct H.\n      specialize (proj2 IHs1_1 (@or_intror _ _ H)). clear IHs1_1 H. intro. auto.\n      destruct H. specialize (proj2 IHs1_2 (@or_intror _ _ H)). clear IHs1_2 H. auto.\n      destruct t_in0 ; [idtac | crush]. right ; left. crush.\n      econstructor ; split ; eauto. xinterp_simpl. apply in_or_app. auto.\n  Qed.\n\n  (* should rewrite using explicit code -- hard to work with it this way... *)\n  Definition add_xform (ty:xtype) (refx : re_xf_pair ty)\n             (rs:rs_xf_pair ty) : rs_xf_pair ty.\n    destruct refx as [x fx].\n    destruct rs as [s fs].\n    destruct s as [t ok].\n    remember (add_xform_tree x fx t fs) as p.\n    destruct p as [t' ft'].\n    assert (Raw.Ok t').\n    replace t' with (projT1 (existT (fun rs => tree_type rs ->> xList_t ty) t' ft')).\n    rewrite Heqp. rewrite add_xform_tree_erase.\n    apply (Raw.add_ok _ ok). auto.\n    remember ({|this := t' ; is_ok := H|}) as s'.\n    eapply (existT (fun rs => re_set_type rs ->> xList_t ty) s').\n    rewrite Heqs'. apply ft'.\n  Defined.\n  Extraction Implicit add_xform [ty].\n\n  Lemma add_xform_erase ty rex rs : \n    projT1 (@add_xform ty rex rs) = add (projT1 rex) (projT1 rs).\n  Proof.\n    unfold add_xform.\n    destruct rex as [x fx].\n    destruct rs as [s fs].\n    destruct s as [t ok].\n    generalize (eq_ind_r (fun s => Raw.Ok (projT1 s))\n                         (eq_ind_r (fun t0 => Raw.Ok t0)\n                                   (Raw.add_ok x ok)\n                                   (add_xform_tree_erase t x fx fs))).\n    remember (add_xform_tree x fx t fs) as p.\n    destruct p as [t' ft'].\n    unfold add. simpl.\n    intros.\n    generalize (o (existT (fun rs => tree_type rs ->> xList_t ty) t' ft') eq_refl).\n    simpl. \n    replace (t') \n    with (projT1 (existT (fun rs => tree_type rs ->> xList_t ty) t' ft')) ; auto.\n    rewrite Heqp. rewrite add_xform_tree_erase. intros.\n    rewrite (proof_irrelevance _ o0 (Raw.add_ok x ok)). auto.\n  Qed.\n\n  Lemma add_xform_corr ty rex rs str v : \n    in_re_set_xform (@add_xform ty rex rs) str v <-> \n    in_re_xform rex str v \\/ in_re_set_xform rs str v.\n  Proof.\n    destruct rex as [x fx].\n    destruct rs as [s fs]. destruct s as [t ok]. unfold in_re_set_xform.\n    unfold add_xform. simpl. unfold eq_rec_r, eq_rec, eq_rect. simpl.\n    generalize (eq_ind_r (fun s => Raw.Ok (projT1 s)) \n                         (eq_ind_r (fun t0 => Raw.Ok t0) (Raw.add_ok x ok)\n                                   (add_xform_tree_erase t x fx fs))).\n    generalize (add_xform_tree_corr t fs x fx str v).\n    remember (add_xform_tree x fx t fs) as p. intros.\n    destruct p. unfold re_set_type. simpl. unfold in_re_set. simpl.\n    apply H.\n  Qed.\n\n  Definition union_xform (ty:xtype) (rs1 rs2 : rs_xf_pair ty) : rs_xf_pair ty.\n    destruct rs1 as [s1 f1].\n    destruct rs2 as [s2 f2].\n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2].\n    remember (union_xform_tree t1 f1 t2 f2) as p.\n    destruct p as [t0 f0].\n    assert (H: Raw.Ok t0).\n    replace t0 with (projT1 (existT (fun rs => tree_type rs ->> xList_t ty) t0 f0)) ; auto.\n    rewrite Heqp. rewrite union_xform_tree_erase.\n    apply (Raw.union_ok okt1 okt2).\n    remember ({|this := t0 ; is_ok := H|}) as s'.\n    apply (existT (fun rs => re_set_type rs ->> xList_t ty) s').\n    rewrite Heqs'.\n    apply f0.\n  Defined.\n  Extraction Implicit union_xform [ty].\n\n  Lemma union_xform_erase ty rs1 rs2 : \n    projT1 (@union_xform ty rs1 rs2) = union (projT1 rs1) (projT1 rs2).\n  Proof.\n    unfold union_xform. \n    destruct rs1 as [s1 f1].\n    destruct rs2 as [s2 f2].\n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2]. simpl.\n    generalize (eq_ind_r (fun s => \n                            Raw.Ok (projT1 s))\n                         (eq_ind_r (fun t3 => Raw.Ok t3)\n                                   (Raw.union_ok okt1 okt2)\n                                   (union_xform_tree_erase t1 f1 t2 f2))).\n    remember (union_xform_tree t1 f1 t2 f2) as p.\n    destruct p. simpl. \n    unfold union. simpl. intro.\n    generalize (o (existT (fun rs => tree_type rs ->> xList_t ty) x x0) eq_refl).\n    clear o. simpl. \n    replace (x) with (projT1 (existT (fun rs => tree_type rs ->> xList_t ty) x x0)) ; auto.\n    rewrite Heqp. rewrite union_xform_tree_erase. intros.\n    rewrite (proof_irrelevance _ o (Raw.union_ok okt1 okt2)). auto.\n  Qed.\n\n  Lemma union_xform_corr ty rs1 rs2 str v : \n    in_re_set_xform (@union_xform ty rs1 rs2) str v <-> \n    in_re_set_xform rs1 str v \\/ in_re_set_xform rs2 str v.\n  Proof.\n    destruct rs1 as [s1 f1].\n    destruct rs2 as [s2 f2].\n    destruct s1 as [t1 okt1].\n    destruct s2 as [t2 okt2]. simpl. \n    generalize (eq_ind_r\n                    (fun s : {rs : Raw.tree & tree_type rs ->> xList_t ty} =>\n                     Raw.Ok (projT1 s))\n                    (eq_ind_r (fun t3 : Raw.tree => Raw.Ok t3)\n                       (Raw.union_ok (s1:=t1) (s2:=t2) okt1 okt2)\n                       (union_xform_tree_erase t1 f1 t2 f2))).\n    generalize (union_xform_tree_corr t1 f1 t2 f2 str v).\n    remember (union_xform_tree t1 f1 t2 f2) as p. intros. \n    destruct p. simpl. unfold re_set_type, in_re_set. simpl.\n    unfold eq_rec_r, eq_rec, eq_rect. simpl. apply H.\n  Qed.\n\n  Section FOLD_TREE_XFORM.\n    Variable ty : xtype.\n    Variable A : Type.\n    Variable f : re_xf_pair ty -> A -> A.\n    Fixpoint fold_tree_xform (s:Raw.tree) : (tree_type s ->> xList_t ty) -> A -> A :=\n      match s return tree_type s ->> xList_t ty -> A -> A with\n        | Raw.Leaf => fun _ v => v\n        | Raw.Node _ l x r => \n          fun fs v => \n            fold_tree_xform r (xcomp (xcomp xinr xinr) fs)\n                            (f (existT _ x (xcomp (xcomp xinl xinr) fs))\n                               (fold_tree_xform l (xcomp xinl fs) v))\n      end.\n  End FOLD_TREE_XFORM.\n  Extraction Implicit fold_tree_xform [ty].\n\n  Section FOLD_TREE_XFORM_ERASE.\n    Variable ty1 : xtype.\n    Variable ty2 : xtype.\n    Variable comb1 : re_xf_pair ty1 -> rs_xf_pair ty2 -> rs_xf_pair ty2.\n    Variable comb2 : regexp -> RawRESet.t -> RawRESet.t.\n    Variable H : forall rex rx, projT1 (comb1 rex rx) = comb2 (projT1 rex) (projT1 rx).\n\n    Lemma fold_tree_xform_erase : \n      forall rx f ini_rx, \n        projT1 (fold_tree_xform comb1 rx f ini_rx) = \n        Raw.fold comb2 rx (projT1 ini_rx).\n    Proof.\n      induction rx. auto. intros.\n      simpl. rewrite IHrx2. rewrite H. simpl. rewrite IHrx1. auto.\n    Qed.\n  End FOLD_TREE_XFORM_ERASE.\n\n  Definition fold_xform ty (A:Type) (comb : re_xf_pair ty -> A -> A)\n             (rx : rs_xf_pair ty) (a:A) : A :=\n    let (s1, f1) := rx in\n    match s1 as s1' return (re_set_type s1' ->> xList_t ty -> A) with\n      | @Mkt t1 okt1=>\n        fun f2 : re_set_type {| this := t1; is_ok := okt1 |} ->> xList_t ty =>\n          fold_tree_xform comb t1 f2 a\n    end f1.\n  Extraction Implicit fold_xform [ty].\n\n   Lemma fold_xform_erase : forall ty1 ty2\n     (comb1:re_xf_pair ty1 -> rs_xf_pair ty2 -> rs_xf_pair ty2)\n     (comb2:regexp -> RawRESet.t -> RawRESet.t) rx ini_rx,\n     (forall rex rx, projT1 (comb1 rex rx) = comb2 (projT1 rex) (projT1 rx)) -> \n     projT1 (fold_xform comb1 rx ini_rx) = RawRESet.fold comb2 (projT1 rx) (projT1 ini_rx).\n  Proof.\n    intros.\n    destruct rx. simpl. destruct x. \n    unfold RawRESet.fold. simpl. destruct ini_rx.\n    rewrite (@fold_tree_xform_erase ty1 ty2 comb1 comb2 H). auto.\n  Qed.\n\n  Definition map_xform ty1 ty2 (f : re_xf_pair ty1 -> re_xf_pair ty2) (s:rs_xf_pair ty1) : \n    rs_xf_pair ty2 := \n    fold_xform (fun x => add_xform (f x)) s (empty_xform ty2).\n  Extraction Implicit map_xform [ty1 ty2].\n\n  Lemma map_xform_erase : \n    forall ty1 ty2 (f : re_xf_pair ty1 -> re_xf_pair ty2) \n              (f' : regexp -> regexp) (s : rs_xf_pair ty1), \n      (forall rx, projT1 (f rx) = f' (projT1 rx)) -> \n      projT1(map_xform f s) = \n      RawRESet.fold (fun x => RawRESet.add (f' x)) (projT1 s) RawRESet.empty.\n   Proof.\n     intros.\n     unfold map_xform. apply fold_xform_erase. intros. \n     rewrite add_xform_erase. rewrite H. auto.\n   Qed.    \n\n   Definition set_cat_re (s:RawRESet.t) (r:regexp): RawRESet.t := \n     match r with\n       | rEps => s (* not stricitly necessary; an optimization *)\n       | rZero => RawRESet.empty\n       | _ => RawRESet.fold (fun r1 s' => RawRESet.add (rCat r1 r) s') s RawRESet.empty\n                         (* Note : will need to show that this is the same as\n                            RESF.map (re_set_build_map (fun r1 => rCat r1 r)) s *)\n     end.\n         \n   Definition simple_cat_re_xform ty (s:rs_xf_pair ty) (r:regexp) : \n     rs_xf_pair (xPair_t ty (regexp_type r)) := \n     map_xform \n       (fun xf => let (x,f) := xf in \n                  existT _ (rCat x r)\n                         (xcomp (xpair xsnd (xcomp xfst f)) (xmapenv (xpair xsnd xfst))))\n       s.\n  Extraction Implicit simple_cat_re_xform [ty].\n\n   Definition cat_re_xform ty (s : rs_xf_pair ty) (r:regexp) : \n     rs_xf_pair (xPair_t ty (regexp_type r)) := \n     match r as r' return rs_xf_pair (xPair_t ty (regexp_type r')) with\n       | rEps => let (raw_set,f) := s in \n                (existT _ raw_set (xcomp f (xmap (xpair xid xunit))))\n       | rZero => (existT _ RawRESet.empty xzero)\n       | r' => simple_cat_re_xform s r'\n     end.\n  Extraction Implicit cat_re_xform [ty].\n\n   Lemma cat_re_xform_erase ty s r :  \n     projT1 (@cat_re_xform ty s r) = set_cat_re (projT1 s) r.\n   Proof.\n     destruct s. destruct r ; auto ; unfold cat_re_xform ; \n     apply map_xform_erase ; destruct rx ; auto.\n   Qed.\n\n   Definition rx_equal ty (rx1 rx2: rs_xf_pair ty) := \n     forall s v, in_re_set_xform rx1 s v <-> in_re_set_xform rx2 s v.\n\n   Definition tx_equal ty (tx1 tx2: tree_xf_pair ty) := \n     forall s v, in_tree_xform tx1 s v <-> in_tree_xform tx2 s v.\n\n   Lemma tree_disj i (t1 t2:Raw.tree) (x:regexp) (ok : Raw.Ok (Raw.Node i t1 x t2)) :\n     forall r, (Raw.In r t1 -> ~Raw.In r t2 /\\ r <> x) /\\ \n               (Raw.In r t2 -> ~Raw.In r t1 /\\ r <> x).\n   Proof.\n     inversion ok. subst. intro. \n     specialize (H5 r). specialize (H6 r). simpl in *.\n     remember (REOrderedTypeAlt.compare r x) as c ; destruct c ; split ; intros ;\n     match goal with \n         | [ H1 : ?P1 -> _, H2 : ?P1 |- _ ] => specialize (H1 H2) ; try discriminate\n     end.\n     generalize (REOrderedTypeAlt.compare_sym x r) ; unfold CompOpp. rewrite H6.\n     rewrite <- Heqc. intros ; discriminate. split. intro. specialize (H6 H0).\n     generalize (REOrderedTypeAlt.compare_sym r x). unfold CompOpp. rewrite H6.\n     rewrite <- Heqc. intros ; discriminate. intro. subst.\n     rewrite (Raw.MX.compare_refl x) in Heqc. discriminate.\n     generalize (REOrderedTypeAlt.compare_sym r x). unfold CompOpp. rewrite H6.\n     rewrite <- Heqc. intro ; discriminate.\n     split. intro. specialize (H5 H0). discriminate.\n     intro ; subst. rewrite (Raw.MX.compare_refl x) in Heqc. discriminate.\n   Qed.\n\n   Lemma in_tree_in_elem : \n     forall tree s v, \n       in_tree tree s v -> exists r, (Raw.In r tree /\\ exists v', in_regexp r s v').\n   Proof.\n     induction tree ; simpl ; intros. destruct v.\n     unfold in_tree in H. simpl in H. repeat in_regexp_inv. \n     specialize (IHtree1 _ _ H). crush. \n     econstructor. split. eapply Raw.InLeft ; eauto. eauto.\n     econstructor. split ; eauto. eapply Raw.IsRoot. eapply Raw.MX.compare_refl.\n     specialize (IHtree2 _ _ H). crush. \n     econstructor. split. eapply Raw.InRight ; eauto. eauto.\n   Qed.\n\n\n   Section FOLD_TREE_REC.\n     Variable ty : xtype.\n     Variable A : Type.\n     Variable P : rs_xf_pair ty -> A -> Prop.\n     Variable f : re_xf_pair ty -> A -> A.\n     Variable P_resp_equiv : \n       forall rx1 rx2, rx_equal rx1 rx2 -> forall (a:A), P rx1 a -> P rx2 a.\n     Variable P_extends : \n       forall rx rs a, P rs a -> P (add_xform rx rs) (f rx a).\n\n     Lemma fold_tree_rec' : \n       forall (tree : Raw.tree)\n              (tree_xf : tree_type tree ->> xList_t ty)\n              (accum_set : rs_xf_pair ty)\n              (accum : A)\n              (Inv : P accum_set accum),\n         P (fold_tree_xform (fun x => add_xform x) tree tree_xf accum_set)\n           (fold_tree_xform f tree tree_xf accum).\n     Proof.\n      induction tree ; intros.\n      (* base case *)\n      auto.\n       (* inductive case *)\n      specialize (IHtree1 (xcomp xinl tree_xf) accum_set accum Inv). \n      generalize (P_extends (existT _ t1 (xcomp (xcomp xinl xinr) tree_xf)) IHtree1).\n      clear IHtree1. intro H.\n      specialize (IHtree2 (xcomp (xcomp xinr xinr) tree_xf) _ _ H).\n      assert (rx_equal (fold_tree_xform (fun x => add_xform x) tree2 \n                                        (xcomp (xcomp xinr xinr) tree_xf)\n                                        (add_xform \n                                           (existT _ t1 (xcomp (xcomp xinl xinr) tree_xf))\n                                           (fold_tree_xform (fun x => add_xform x)\n                                                            tree1 (xcomp xinl tree_xf)\n                                                            accum_set)))\n                       (fold_tree_xform (fun x => add_xform x) \n                                        (Raw.Node t0 tree1 t1 tree2) tree_xf accum_set)).\n      intro ; intro. clear IHtree2 H.\n      assert (@fold_tree_xform ty _ (fun x => add_xform x)\n                              (Raw.Node t0 tree1 t1 tree2) = \n              fun fs v => \n                fold_tree_xform (fun x => add_xform x)\n                  tree2 (xcomp (xcomp xinr xinr) fs)\n                                (add_xform (existT _ t1 (xcomp (xcomp xinl xinr) fs))\n                                           (fold_tree_xform (fun x => add_xform x)\n                                                            tree1 (xcomp xinl fs) v))).\n      auto. rewrite H. split ; auto.\n      apply (P_resp_equiv H0 IHtree2).\n    Qed.\n\n    Lemma fold_tree_rec : \n      forall (tree : Raw.tree)\n             (tree_xf : tree_type tree ->> xList_t ty)\n             (tree_ok : Raw.Ok tree)\n             (accum : A)\n             (Inv : P (empty_xform ty) accum),\n             P (existT _ {| this := tree ; is_ok := tree_ok|} tree_xf)\n             (fold_tree_xform f tree tree_xf accum).\n    Proof.\n      intros.\n      specialize (fold_tree_rec' tree tree_xf Inv).\n      apply P_resp_equiv. clear A P f P_resp_equiv P_extends accum Inv.\n      unfold rx_equal. \n      assert (forall s str v, \n                in_re_set_xform s str v <-> \n                (in_re_set_xform s str v \\/ in_re_set_xform (empty_xform ty) str v)).\n      intros ; split ; auto. intros. destruct H ; auto. \n      contradiction (empty_xform_corr H). intros.\n      symmetry. rewrite H. clear H. generalize (empty_xform ty). \n      induction tree. \n      (* Base case *)\n      crush. unfold in_re_set in H. unfold in_tree in H. simpl in H. in_regexp_inv.\n      (* Inductive case *)\n      intro.\n      specialize (IHtree1 (xcomp xinl tree_xf) (ok_left tree_ok)).\n      specialize (IHtree2 (xcomp (xcomp xinr xinr) tree_xf) (ok_right tree_ok)).\n      unfold fold_tree_xform. \n      rewrite <- IHtree2. rewrite add_xform_corr. rewrite <- IHtree1.\n      clear IHtree1 IHtree2. unfold in_re_set_xform, in_re_set, re_set_type, in_tree.\n      crush. in_regexp_inv. right ; right. left. econstructor ; split ; eauto.\n      xinterp_simpl. auto. in_regexp_inv. right ; left ; econstructor ; split ; eauto.\n      xinterp_simpl. auto. left ; econstructor ; split ; eauto. xinterp_simpl ; auto.\n      xinterp_simpl. left ; eauto. xinterp_simpl. left ; eauto. xinterp_simpl ; eauto.\n   Qed.\n\n   Lemma fold_xform_rec : \n     forall (rs : rs_xf_pair ty) (accum : A),\n       P (empty_xform ty) accum -> P rs (fold_xform f rs accum).\n     Proof.\n       intros. unfold fold_xform. destruct rs as [s x]. \n       destruct s as [t okt]. unfold re_set_type in x. simpl in x.\n       apply (fold_tree_rec). auto.\n     Qed.\n  End FOLD_TREE_REC.\n\n  Lemma cat_re_xform_corr' : \n     forall ty (s : rs_xf_pair ty) r str (v : xt_interp ty * xt_interp (regexp_type r)), \n       in_re_set_xform (simple_cat_re_xform s r) str v <-> \n       exists str1 str2 v1 v2, str = str1 ++ str2 /\\ v = (v1,v2) /\\ \n                           in_re_set_xform s str1 v1 /\\ in_regexp r str2 v2.\n   Proof.\n     Opaque add_xform xpair xcomp.\n     unfold simple_cat_re_xform. unfold map_xform. fold regexp_type.\n     intros. apply fold_xform_rec.\n     intros. split. intros. specialize (proj1 H0 H1). clear H0 H1. crush.\n     repeat econstructor. specialize (H x x1). crush. auto.\n     crush. apply H2. repeat econstructor. specialize (H x x1) ; crush. auto.\n\n     intros. rewrite add_xform_corr. destruct rx. crush. in_regexp_inv.\n     xinterp_simpl. rewrite xmapenv_corr in H2. fold xt_interp in H2. \n     match goal with \n         | [ H : List.In _ (map ?e _) |- _ ] => \n           replace e with (fun x : xt_interp ty => (x,x5)) in H\n     end. Focus 2. apply extensionality. intro ; xinterp_simpl ; auto.\n     simpl in H2. assert (exists v1, v = (v1,x5) /\\ List.In v1 (xinterp x0 x4)).\n     generalize H2. generalize (xinterp x0 x4). intro i; induction i ; crush.\n     specialize (IHi H4). crush. crush.\n     repeat econstructor ; eauto. apply add_xform_corr. left. crush.\n     specialize (H H1). crush. repeat econstructor ; eauto. apply add_xform_corr.\n     right ; crush. rewrite add_xform_corr in H1. crush. left.\n     exists (x5,x4). crush. xinterp_simpl. rewrite xmapenv_corr. fold xt_interp. simpl.\n     replace (fun x6 : xt_interp ty => xinterp (xpair xsnd xfst) (x4,x6)) with \n     (fun x6 : xt_interp ty => (x6,x4)). Focus 2. apply extensionality.\n     intro. xinterp_simpl. auto. generalize (xinterp x0 x5) H3.\n     intro i; induction i ; crush. right. apply H0. repeat econstructor. auto. auto.\n     unfold in_re_set_xform. simpl. crush. destruct x. destruct x3.\n  Qed.\n\n  Lemma cat_re_xform_corr : \n    forall ty (s : rs_xf_pair ty) r str (v : xt_interp ty * xt_interp (regexp_type r)), \n       in_re_set_xform (cat_re_xform s r) str v <-> \n       exists str1 str2 v1 v2, str = str1 ++ str2 /\\ v = (v1,v2) /\\ \n                           in_re_set_xform s str1 v1 /\\ in_regexp r str2 v2.\n  Proof.\n    intros.\n    generalize (cat_re_xform_corr' s r str v). intros.\n    destruct r ; auto ; clear H ; simpl in *. destruct s. crush.\n    xinterp_simpl. destruct v. destruct u. assert (List.In x2 (xinterp x0 x1)).\n    generalize (xinterp x0 x1) H0 . intro i0; induction i0 ; crush. xinterp_simpl.\n    crush. repeat econstructor ; eauto. rewrite <- app_nil_end. auto.\n    in_regexp_inv. exists x5. split ; auto. generalize H1. xinterp_simpl.\n    generalize (xinterp x0 x5). intro i; induction i ; crush.\n    destruct v. destruct v.\n  Qed. \n\n(* End RESeTXform. *)\n\n(* Module RR : WSets := RawRESet. *) \n", "meta": {"author": "gangtan", "repo": "CPUmodels", "sha": "a6decc3085e1f8d8d4875e67f9ad9c7663910f8a", "save_path": "github-repos/coq/gangtan-CPUmodels", "path": "github-repos/coq/gangtan-CPUmodels/CPUmodels-a6decc3085e1f8d8d4875e67f9ad9c7663910f8a/x86model/Model/RESet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.1709746819734793}}
{"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(** Register allocation. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Lattice.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import RTLtyping.\nRequire Import Kildall.\nRequire Import Locations.\nRequire Import Coloring.\n\n(** * Liveness analysis over RTL *)\n\n(** A register [r] is live at a point [p] if there exists a path\n  from [p] to some instruction that uses [r] as argument,\n  and [r] is not redefined along this path.\n  Liveness can be computed by a backward dataflow analysis.\n  The analysis operates over sets of (live) pseudo-registers. *)\n\nNotation reg_live := Regset.add.\nNotation reg_dead := Regset.remove.\n\nDefinition reg_option_live (or: option reg) (lv: Regset.t) :=\n  match or with None => lv | Some r => reg_live r lv end.\n\nDefinition reg_sum_live (ros: reg + ident) (lv: Regset.t) :=\n  match ros with inl r => reg_live r lv | inr s => lv end.\n\nFixpoint reg_list_live\n             (rl: list reg) (lv: Regset.t) {struct rl} : Regset.t :=\n  match rl with\n  | nil => lv\n  | r1 :: rs => reg_list_live rs (reg_live r1 lv)\n  end.\n\nFixpoint reg_list_dead\n             (rl: list reg) (lv: Regset.t) {struct rl} : Regset.t :=\n  match rl with\n  | nil => lv\n  | r1 :: rs => reg_list_dead rs (reg_dead r1 lv)\n  end.\n\n(** Here is the transfer function for the dataflow analysis.\n  Since this is a backward dataflow analysis, it takes as argument\n  the abstract register set ``after'' the given instruction,\n  i.e. the registers that are live after; and it returns as result\n  the abstract register set ``before'' the given instruction,\n  i.e. the registers that must be live before.\n  The general relation between ``live before'' and ``live after''\n  an instruction is that a register is live before if either\n  it is one of the arguments of the instruction, or it is not the result\n  of the instruction and it is live after.\n  However, if the result of a side-effect-free instruction is not \n  live ``after'', the whole instruction will be removed later\n  (since it computes a useless result), thus its arguments need not\n  be live ``before''. *)\n\nDefinition transfer\n            (f: RTL.function) (pc: node) (after: Regset.t) : Regset.t :=\n  match f.(fn_code)!pc with\n  | None =>\n      Regset.empty\n  | Some i =>\n      match i with\n      | Inop s =>\n          after\n      | Iop op args res s =>\n          if Regset.mem res after then\n            reg_list_live args (reg_dead res after)\n          else\n            after\n      | Iload chunk addr args dst s =>\n          if Regset.mem dst after then\n            reg_list_live args (reg_dead dst after)\n          else\n            after\n      | Istore chunk addr args src s =>\n          reg_list_live args (reg_live src after)\n      | Icall sig ros args res s =>\n          reg_list_live args\n           (reg_sum_live ros (reg_dead res after))\n      | Itailcall sig ros args =>\n          reg_list_live args (reg_sum_live ros Regset.empty)\n      | Ibuiltin ef args res s =>\n          reg_list_live args (reg_dead res after)\n      | Icond cond args ifso ifnot =>\n          reg_list_live args after\n      | Ijumptable arg tbl =>\n          reg_live arg after\n      | Ireturn optarg =>\n          reg_option_live optarg Regset.empty\n      end\n  end.\n\n(** The liveness analysis is then obtained by instantiating the\n  general framework for backward dataflow analysis provided by\n  module [Kildall].  *)\n\nModule RegsetLat := LFSet(Regset).\nModule DS := Backward_Dataflow_Solver(RegsetLat)(NodeSetBackward).\n\nDefinition analyze (f: RTL.function): option (PMap.t Regset.t) :=\n  DS.fixpoint (successors f)  (transfer f) nil.\n\n(** * Translation from RTL to LTL *)\n\nRequire Import LTL.\n\n(** Each [RTL] instruction translates to an [LTL] instruction.\n  The register assignment [assign] returned by register allocation\n  is applied to the arguments and results of the RTL\n  instruction.  Moreover, dead instructions and redundant moves\n  are eliminated (turned into a [Lnop] instruction).\n  Dead instructions are instructions without side-effects ([Iop] and\n  [Iload]) whose result register is dead, i.e. whose result value\n  is never used.  Redundant moves are moves whose source and destination\n  are assigned the same location. *)\n\nDefinition is_redundant_move\n    (op: operation) (args: list reg) (res: reg) (assign: reg -> loc) : bool :=\n  match is_move_operation op args with\n  | None => false\n  | Some src => if Loc.eq (assign src) (assign res) then true else false\n  end.\n\nDefinition transf_instr\n         (f: RTL.function) (live: PMap.t Regset.t) (assign: reg -> loc)\n         (pc: node) (instr: RTL.instruction) : LTL.instruction :=\n  match instr with\n  | Inop s =>\n      Lnop s\n  | Iop op args res s =>\n      if Regset.mem res live!!pc then\n        if is_redundant_move op args res assign then\n          Lnop s\n        else \n          Lop op (List.map assign args) (assign res) s\n      else\n        Lnop s\n  | Iload chunk addr args dst s =>\n      if Regset.mem dst live!!pc then\n        Lload chunk addr (List.map assign args) (assign dst) s\n      else\n        Lnop s\n  | Istore chunk addr args src s =>\n      Lstore chunk addr (List.map assign args) (assign src) s\n  | Icall sig ros args res s =>\n      Lcall sig (sum_left_map assign ros) (List.map assign args)\n                (assign res) s\n  | Itailcall sig ros args =>\n      Ltailcall sig (sum_left_map assign ros) (List.map assign args)\n  | Ibuiltin ef args res s =>\n      Lbuiltin ef (List.map assign args) (assign res) s\n  | Icond cond args ifso ifnot =>\n      Lcond cond (List.map assign args) ifso ifnot\n  | Ijumptable arg tbl =>\n      Ljumptable (assign arg) tbl\n  | Ireturn optarg =>\n      Lreturn (option_map assign optarg)\n  end.\n\nDefinition transf_fun (f: RTL.function) (live: PMap.t Regset.t)\n                      (assign: reg -> loc) : LTL.function :=\n  LTL.mkfunction\n     (RTL.fn_sig f)\n     (List.map assign (RTL.fn_params f))\n     (RTL.fn_stacksize f)\n     (PTree.map (transf_instr f live assign) (RTL.fn_code f))\n     (RTL.fn_entrypoint f).\n\n(** The translation of a function performs liveness analysis,\n  construction and coloring of the inference graph, and per-instruction\n  transformation as described above. *)\n\nDefinition live0 (f: RTL.function) (live: PMap.t Regset.t) :=\n  transfer f f.(RTL.fn_entrypoint) live!!(f.(RTL.fn_entrypoint)).\n\nOpen Scope string_scope.\n\nDefinition transf_function (f: RTL.function) : res LTL.function :=\n  match type_function f with\n  | Error msg => Error msg\n  | OK env =>\n    match analyze f with\n    | None => Error (msg \"Liveness analysis failure\")\n    | Some live =>\n        match regalloc f live (live0 f live) env with\n        | None => Error (msg \"Incorrect graph coloring\")\n        | Some assign => OK (transf_fun f live assign)\n        end\n    end\n  end.\n\nSection WITHEF.\nContext `{Hsc: SyntaxConfiguration}.\n\nDefinition transf_fundef (fd: RTL.fundef) : res LTL.fundef :=\n  AST.transf_partial_fundef transf_function fd.\n\nDefinition transf_program (p: RTL.program) : res LTL.program :=\n  transform_partial_program transf_fundef p.\n\nEnd WITHEF.\n", "meta": {"author": "jeremie-koenig", "repo": "compcert", "sha": "e58b5a076931637f2e7b13f6e9ba7a47e2cdc437", "save_path": "github-repos/coq/jeremie-koenig-compcert", "path": "github-repos/coq/jeremie-koenig-compcert/compcert-e58b5a076931637f2e7b13f6e9ba7a47e2cdc437/backend/Allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.1709250885013378}}
{"text": "Set Implicit Arguments.\nSet Maximal Implicit Insertion.\nSet Contextual Implicit.\nSet Universe Polymorphism.\n\nFrom Equations Require Import Equations.\n\nFrom Coq Require Import\n     Relation_Definitions\n     RelationClasses\n.\n\nRequire Import Fix.\nRequire Import GHC.Base.\nRequire Import Adverb.Composable.Adverb.\nRequire Import ClassesOfFunctors.DictDerive.\nRequire Import ClassesOfFunctors.Laws.\n\nOpen Scope composable_adverb_scope.\n\nRequire Import Tactics.Tactics.\n\n(* begin hide *)\nLocal Ltac solve :=\n  Tactics.program_simplify; Equations.CoreTactics.equations_simpl; try Tactics.program_solve_wf;\n  repeat destruct_match; reflexivity.\n\nLocal Obligation Tactic := solve.\n(* end hide *)\n\n\nVariant PurelyAdv (K : Set -> Set) (R : Set) : Set :=\n| Pure (r : R).\n\nArguments Pure {_} {_}.\n\n#[export] Program Instance Functor1__PurelyAdv : Functor1 PurelyAdv :=\n  {| fmap1 := fun _ _ _ _ a =>\n                match a with\n                | Pure a => Pure a\n                end\n  |}.\n\n#[export] Instance PurelyAdverbSim :\n  PurelyAdv \u22a7 Applicative__Dict UNDER IdT :=\n  {| interpAlg := fun I D _ a =>\n                    match a with\n                    | Pure r => @pure _\n                                     (apdict_functor I D)\n                                     (apdict_applicative I D) _ r\n                    end |}.\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/Adverb/Composable/Purely.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.17092508495615077}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom fae_gtlc_mu.stlc_mu Require Export lang.\n\n(* Iris resources for invariants *)\nClass implG \u03a3 := ImplG {\n  implG_invG : invG \u03a3;\n}.\n\n(* Iris resources static side for weakest preconditions... *)\nInstance implG_irisG `{implG \u03a3} : irisG lang \u03a3 := {\n  iris_invG := implG_invG;\n  state_interp \u03c3 \u03bas _ := True%I;\n  fork_post _ := True%I;\n}.\nGlobal Opaque iris_invG.\n\nFrom fae_gtlc_mu.stlc_mu Require Export lang_lemmas.\nFrom fae_gtlc_mu.backtranslation Require Import extract.\nFrom iris.program_logic Require Export ectx_lifting.\nFrom iris.proofmode Require Export tactics.\n\n(* WP \u03a9 ... *)\nSection wp_omega.\n\n  Context `{!implG \u03a3}.\n\n  Lemma wp_\u03a9 \u03a6 : \u22a2 (True -\u2217 (WP \u03a9 {{ \u03a6 }}))%I.\n  (* because \u03a9 diverges *)\n  Proof.\n    iIntros.\n    iL\u00f6b as \"IH\".\n    iApply wp_pure_step_later; auto; iNext; asimpl.\n    iApply (wp_bind $ stlc_mu.lang.fill_item $ stlc_mu.lang.AppLCtx _).\n    iApply wp_pure_step_later; auto.\n    iNext.\n    iApply wp_value.\n    fold \u03a9. done.\n  Qed.\n\nEnd wp_omega.\n\nLtac wp_head := iApply wp_pure_step_later; auto; iNext.\nLtac wp_value := iApply wp_value.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/static_gradual/resources_left.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.17079920141388186}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\n\nRequire Import spec_stdlib.\n\nRequire Import verif_stdlib.\nRequire Import verif_fastpile.\nRequire Import verif_fastonepile.\nRequire Import verif_fastapile.\nRequire Import verif_fasttriang.\n\nDefinition PrivPILE: spec_fastpile_private.FastpilePrivateAPD := PILEPRIV M.\nDefinition PILE: spec_fastpile.PileAPD := spec_fastpile_private.pilepreds PrivPILE. \n\nDefinition ONEPILE : spec_onepile.OnePileAPD := ONEPILE PILE.\n\nDefinition Onepile_Pile_VSU :=\n  ltac:(linkVSUs (PilePrivateVSU M) (OnepileVSU M PILE) ). \n\nDefinition Apile_Onepile_Pile_VSU :=\n  ltac:(linkVSUs (Onepile_Pile_VSU) (ApileVSU M PrivPILE)). \n\nDefinition Triang_Apile_Onepile_Pile_VSU :=\n  ltac:(linkVSUs Apile_Onepile_Pile_VSU (TriangVSU M PILE)). \n\nDefinition Core_VSU :=\n  ltac:(linkVSUs MallocFreeVSU Triang_Apile_Onepile_Pile_VSU).\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/VSUpile/fast/verif_fastcore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17035914897391397}}
{"text": "Require Import Classical Peano_dec Setoid PeanoNat.\nFrom hahn Require Import Hahn.\n\nRequire Import AuxDef Events Execution.\nRequire Import Execution_eco imm_s_hb imm_s imm_bob.\nRequire Import imm_s_ppo CombRelations.\nRequire Import imm_s_rfppo.\nRequire Import FinExecution.\n\nSet Implicit Arguments.\n\nSection TraversalConfig.\n\n  Variable G : execution.\n  Variable WF : Wf G.\n  Variable COM : complete G.\n  Variable sc : relation actid.\n  Variable IMMCON : imm_consistent G sc.\n\n  Notation \"'sb'\" := (sb G).\n  Notation \"'rmw'\" := (rmw G).\n  Notation \"'data'\" := (data G).\n  Notation \"'addr'\" := (addr G).\n  Notation \"'ctrl'\" := (ctrl G).\n  Notation \"'rf'\" := (rf G).\n  Notation \"'co'\" := (co G).\n  Notation \"'coe'\" := (coe G).\n  Notation \"'fr'\" := (fr G).\n\n  Notation \"'eco'\" := (eco G).\n\n  Notation \"'bob'\" := (bob G).\n  Notation \"'fwbob'\" := (fwbob G).\n  Notation \"'ppo'\" := (ppo G).\n  Notation \"'fre'\" := (fre G).\n  Notation \"'rfi'\" := (rfi G).\n  Notation \"'rfe'\" := (rfe G).\n  Notation \"'deps'\" := (deps G).\n  Notation \"'detour'\" := (detour G).\n  Notation \"'release'\" := (release G).\n  Notation \"'sw'\" := (sw G).\n  Notation \"'hb'\" := (hb G).\n\n  Notation \"'ar'\" := (ar G sc).\n\n  Notation \"'urr'\" := (urr G sc).\n  Notation \"'c_acq'\" := (c_acq G sc).\n  Notation \"'c_cur'\" := (c_cur G sc).\n  Notation \"'c_rel'\" := (c_rel G sc).\n  Notation \"'t_acq'\" := (t_acq G sc).\n  Notation \"'t_cur'\" := (t_cur G sc).\n  Notation \"'t_rel'\" := (t_rel G sc).\n  Notation \"'S_tm'\" := (S_tm G).\n  Notation \"'S_tmr'\" := (S_tmr G).\n  Notation \"'msg_rel'\" := (msg_rel G sc).\n\nNotation \"'lab'\" := (lab G).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (Events.mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'R'\" := (fun x => is_true (is_r lab x)).\nNotation \"'W'\" := (fun x => is_true (is_w lab x)).\nNotation \"'F'\" := (fun x => is_true (is_f lab x)).\nNotation \"'RW'\" := (R \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\nNotation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex \u2229\u2081 (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Init'\" := (fun a => is_true (is_init a)).\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_' l\" := (W \u2229\u2081 Loc_ l) (at level 1).\n\nNotation \"'Pln'\" := (fun x => is_true (is_only_pln lab x)).\nNotation \"'Rlx'\" := (fun x => is_true (is_rlx lab x)).\nNotation \"'Rel'\" := (fun x => is_true (is_rel lab x)).\nNotation \"'Acq'\" := (fun x => is_true (is_acq lab x)).\nNotation \"'Acqrel'\" := (fun x => is_true (is_acqrel lab x)).\nNotation \"'Sc'\" := (fun x => is_true (is_sc lab x)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\n\n(******************************************************************************)\n(** **   *)\n(******************************************************************************)\n\n  Definition next C := E \u2229\u2081 dom_cond sb C \u2229\u2081 set_compl C.\n\n  Record trav_config :=\n    mkTC { covered : actid -> Prop; issued : actid -> Prop; }.\n\n  Definition same_trav_config (T T' : trav_config) :=\n    covered T \u2261\u2081 covered T' /\\ issued T \u2261\u2081 issued T'.\n\n  Definition coverable T := E \u2229\u2081 dom_cond sb (covered T) \u2229\u2081 \n                              ((W \u2229\u2081 issued T) \u222a\u2081\n                               (R \u2229\u2081 (dom_cond rf (issued T))) \u222a\u2081\n                               (F \u2229\u2081 (dom_cond sc (covered T)))).\n\n  Definition issuable T := E \u2229\u2081 W \u2229\u2081\n                           (dom_cond fwbob (covered T)) \u2229\u2081\n                           (dom_cond (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc))\u207a) (issued T)).\n\n  Definition tc_coherent (T : trav_config) :=\n    \u27ea ICOV  : Init \u2229\u2081 E \u2286\u2081 covered T \u27eb /\\\n    \u27ea CC    : covered T \u2286\u2081 coverable T \u27eb /\\\n    \u27ea II    : issued  T \u2286\u2081 issuable T \u27eb.\n\n  Lemma traversal_mon T T'\n        (ICOV : covered T \u2286\u2081 covered T')\n        (IISS : issued  T \u2286\u2081 issued  T'):\n    coverable T \u2286\u2081 coverable T' /\\\n    issuable  T \u2286\u2081 issuable T'.\n  Proof using.\n    split.\n      by unfold coverable; rewrite ICOV, IISS.\n        by unfold issuable; rewrite ICOV, IISS.\n  Qed.\n\n  Lemma same_trav_config_refl : reflexive same_trav_config.\n  Proof using. split; basic_solver. Qed.\n\n  Lemma same_trav_config_sym : symmetric same_trav_config.\n  Proof using. unfold same_trav_config; split; ins; desf; symmetry; auto. Qed.\n\n  Lemma same_trav_config_trans : transitive same_trav_config.\n  Proof using. unfold same_trav_config; split; ins; desf; etransitivity; eauto. Qed.\n\n  \n(******************************************************************************)\n(** **   *)\n(******************************************************************************)\n  \n  Global Add Parametric Relation : trav_config same_trav_config\n      reflexivity proved by same_trav_config_refl\n      symmetry proved by same_trav_config_sym\n      transitivity proved by same_trav_config_trans\n        as same_tc.\n\n  Lemma same_tc_extensionality tc1 tc2 (SAME: same_trav_config tc1 tc2):\n    tc1 = tc2.\n  Proof using.\n    destruct SAME.\n    destruct tc1, tc2. ins.\n    apply set_extensionality in H, H0.   \n    congruence. \n  Qed. \n\n  \n  Global Add Parametric Morphism : covered with signature\n      same_trav_config ==> set_equiv as covered_more.\n  Proof using. by unfold same_trav_config; ins; split; ins; desf; apply H. Qed.\n\n  Global Add Parametric Morphism : issued with signature\n      same_trav_config ==> set_equiv as issued_more.\n  Proof using. by unfold same_trav_config; ins; desf; apply H1. Qed.\n  \n\n  Global Add Parametric Morphism : coverable with signature\n      same_trav_config ==> set_equiv as coverable_more.\n  Proof using.\n    unfold coverable, same_trav_config; split; ins; desf.\n    all: unnw; try first [ rewrite <- H, <- H0 | rewrite H, H0].\n    all: unfold set_equiv in *; unnw; intuition; basic_solver 12.\n  Qed.\n\n  Global Add Parametric Morphism : issuable with signature\n      same_trav_config ==> set_equiv as issuable_more.\n  Proof using.\n    unfold issuable, same_trav_config; split; ins; desf.\n    all: unnw; try first [ rewrite <- H, <- H0 | rewrite H, H0].\n    all: unfold set_equiv in *; unnw; intuition; basic_solver 12.\n  Qed.\n\n  Global Add Parametric Morphism : tc_coherent with signature\n      same_trav_config ==> iff as tc_coherent_more.\n  Proof using.\n    intros T T' EQ.\n    split; [apply same_tc_Symmetric in EQ|];\n      intros HH; cdes HH; red; splits.\n    all: try erewrite covered_more; eauto.\n    all: try erewrite coverable_more; eauto.\n    all: try erewrite issued_more; eauto.\n    all: erewrite issuable_more; eauto.\n  Qed.\n\n  Global Add Parametric Morphism : mkTC with signature\n         (@set_equiv actid) ==> (@set_equiv actid) ==> same_trav_config as mkTC_more.\n  Proof using. vauto. Qed.  \n\n(******************************************************************************)\n(** **   *)\n(******************************************************************************)\n\nSection Properties.\n  Variable T : trav_config.\n  Variable TCCOH : tc_coherent T.\n\n  Lemma issued_in_issuable : issued T \u2286\u2081 issuable T.\n  Proof using TCCOH. apply TCCOH. Qed.\n\n  Lemma issuableE :\n    issuable T \u2286\u2081 E.\n  Proof using. unfold issuable; basic_solver. Qed.\n\n  Lemma issuedE :\n    issued T \u2286\u2081 E.\n  Proof using TCCOH. rewrite issued_in_issuable. by apply issuableE. Qed.\n\n  Lemma issuableW :\n    issuable T \u2286\u2081 W.\n  Proof using. unfold issuable; basic_solver. Qed.\n\n  Lemma issuedW :\n    issued T \u2286\u2081 W.\n  Proof using TCCOH.\n    rewrite issued_in_issuable.\n    by apply issuableW.\n  Qed.\n\n  Lemma covered_in_coverable :\n    covered T \u2286\u2081 coverable T.\n  Proof using TCCOH.\n    apply TCCOH.\n  Qed.\n\n  Lemma coverableE :\n    coverable T \u2286\u2081 E.\n  Proof using.\n    unfold coverable; basic_solver.\n  Qed.\n\n  Lemma coveredE :\n    covered T \u2286\u2081 E.\n  Proof using TCCOH.\n    rewrite covered_in_coverable.\n    by apply coverableE.\n  Qed.\n\n  Lemma w_coverable_issued :\n    W \u2229\u2081 coverable T \u2286\u2081 issued T.\n  Proof using.\n    unfold coverable; type_solver.\n  Qed.\n\n  Lemma w_covered_issued :\n    W \u2229\u2081 covered T \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite covered_in_coverable.\n    by apply w_coverable_issued.\n  Qed.\n\n  Lemma init_issued : is_init \u2229\u2081 E \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    unfolder; ins; desf.\n    apply w_covered_issued.\n    split.\n    { by apply (init_w WF). }\n    cdes TCCOH; unfolder in ICOV; basic_solver 21. \n  Qed.\n\n  Lemma init_covered : is_init \u2229\u2081 E \u2286\u2081 covered T.\n  Proof using TCCOH. \n    unfolder; ins; desf.\n    cdes TCCOH; unfolder in ICOV; basic_solver 21. \n  Qed.\n\n  Lemma next_n_init e\n        (NEXT : next (covered T) e) :\n    ~ Init e.\n  Proof using TCCOH.\n    intros HH. apply NEXT.\n    apply init_covered. split; auto.\n    apply NEXT.\n  Qed.\n\n(******************************************************************************)\n(** **   *)\n(******************************************************************************)\n\n  Lemma ar_ct_issuable_is_issued  : \n    dom_rel (\u2997W\u2998 \u2a3e ar\u207a \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc).\n    unfold issuable. basic_solver 20.\n  Qed.\n\n  Lemma ar_issuable_is_issued  : \n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using.\n    rewrite ct_step with (r:=ar).\n    apply ar_ct_issuable_is_issued.\n  Qed.\n\n  Lemma dom_sb_coverable :\n    dom_rel (sb \u2a3e \u2997 coverable T \u2998) \u2286\u2081 covered T.\n  Proof using.\n    unfold coverable, dom_cond; basic_solver 21.\n  Qed.\n\n  Lemma sb_coverable :\n    sb \u2a3e \u2997 coverable T \u2998 \u2286 \u2997 covered T \u2998 \u2a3e sb.\n  Proof using.\n   rewrite (dom_rel_helper dom_sb_coverable).\n   basic_solver.\n  Qed.\n\n  Lemma dom_sb_covered :\n    dom_rel (sb \u2a3e \u2997 covered T \u2998) \u2286\u2081 covered T.\n  Proof using TCCOH.\n  rewrite covered_in_coverable at 1.\n  seq_rewrite (dom_rel_helper dom_sb_coverable).\n  basic_solver.\n  Qed.\n\n  Lemma sb_covered :\n    sb \u2a3e \u2997 covered T \u2998 \u2261 \u2997 covered T \u2998 \u2a3e sb \u2a3e \u2997 covered T \u2998.\n  Proof using TCCOH.\n  rewrite (dom_rel_helper dom_sb_covered).\n  basic_solver.\n  Qed.\n\n  Lemma dom_rf_coverable :\n    dom_rel (rf \u2a3e \u2997 coverable T \u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    unfold coverable, dom_cond.\n    rewrite (dom_r (wf_rfD WF)).\n    type_solver 40.\n  Qed.\n\n  Lemma dom_rf_covered :\n    dom_rel (rf \u2a3e \u2997 covered  T \u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite covered_in_coverable.\n    apply dom_rf_coverable.\n  Qed.\n\n  Lemma rf_coverable :\n    rf \u2a3e \u2997 coverable T \u2998 \u2286 \u2997 issued T \u2998 \u2a3e rf.\n  Proof using WF TCCOH.\n    rewrite (dom_rel_helper dom_rf_coverable).\n    basic_solver.\n  Qed.\n\n  Lemma rf_covered :\n    rf \u2a3e \u2997 covered T \u2998 \u2261 \u2997 issued T \u2998 \u2a3e rf \u2a3e \u2997 covered T \u2998.\n  Proof using WF TCCOH.\n    rewrite (dom_rel_helper dom_rf_covered).\n    basic_solver.\n  Qed.\n\n  Lemma dom_sc_coverable :\n    dom_rel (sc \u2a3e \u2997 coverable T \u2998) \u2286\u2081 covered T.\n  Proof using IMMCON.\n    cdes IMMCON.\n    rewrite (dom_r (@wf_scD G sc Wf_sc)).\n    unfold coverable, dom_cond; type_solver 42.\n  Qed.\n\n  Lemma dom_sc_covered :\n    dom_rel (sc \u2a3e \u2997 covered T \u2998) \u2286\u2081 covered T.\n  Proof using IMMCON TCCOH.\n    rewrite covered_in_coverable at 1.\n    seq_rewrite (dom_rel_helper dom_sc_coverable).\n    basic_solver.\n  Qed.\n\n  Lemma sc_coverable  :\n    sc \u2a3e \u2997 coverable T \u2998 \u2286 \u2997covered T\u2998 \u2a3e sc.\n  Proof using IMMCON.\n    seq_rewrite (dom_rel_helper dom_sc_coverable).\n    basic_solver.\n  Qed.\n\n  Lemma sc_covered  :\n    sc \u2a3e \u2997 covered T \u2998 \u2286 \u2997covered T\u2998 \u2a3e sc.\n  Proof using IMMCON TCCOH.\n    rewrite covered_in_coverable at 1.\n      by apply sc_coverable.\n  Qed.\n\n  Lemma ar_coverable_in_CI  :\n    dom_rel (ar \u2a3e \u2997coverable T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    unfold imm_s.ar.\n    rewrite !seq_union_l.\n    rewrite (ar_int_in_sb WF).\n    arewrite (rfe \u2286 rf).\n    rewrite sb_coverable, rf_coverable.\n    rewrite sc_coverable.\n    basic_solver.\n  Qed.\n\n  Lemma ar_C_in_CI  :\n    dom_rel (ar \u2a3e \u2997covered T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite covered_in_coverable at 1.\n    apply ar_coverable_in_CI.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_ct_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc))\u207a \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using.\n    unfold issuable.\n    basic_solver 10.\n  Qed.\n\n  Lemma ar_rfrmw_ct_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\u207a \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite (rmw_in_ppo_loc WF). apply ar_rf_ppo_loc_ct_issuable_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_ct_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc))\u207a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply ar_rf_ppo_loc_ct_issuable_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_ct_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\u207a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_ct_I_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_rt_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc))\uff0a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite rtE. rewrite !seq_union_l, !seq_union_r, dom_union; unionL.\n    { basic_solver. }\n    apply ar_rf_ppo_loc_ct_I_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_rt_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_rt_I_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc)) \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using.\n    rewrite ct_step with (r := ar \u222a rf \u2a3e (ppo \u2229 same_loc)).\n      by apply ar_rf_ppo_loc_ct_issuable_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw) \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_issuable_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e (ppo \u2229 same_loc)) \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite ct_step with (r := ar \u222a rf \u2a3e (ppo \u2229 same_loc)).\n      by apply ar_rf_ppo_loc_ct_I_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw) \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_I_in_I.\n  Qed.\n\n  Lemma ar_ct_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar\u207a \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e rmw). by apply ar_rfrmw_ct_issuable_in_I.\n  Qed.\n\n  Lemma ar_ct_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar\u207a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e rmw). by apply ar_rfrmw_ct_I_in_I.\n  Qed.\n\n  Lemma ar_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite ct_step with (r:=ar). by apply ar_ct_issuable_in_I.\n  Qed.\n\n  Lemma ar_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite ct_step with (r:=ar). by apply ar_ct_I_in_I.\n  Qed.\n\n  Lemma W_ar_coverable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite dom_eqv1. rewrite ar_coverable_in_CI.\n    rewrite set_inter_union_r; unionL.\n    2: basic_solver.\n    apply w_covered_issued.\n  Qed.\n\n  Lemma W_ar_C_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997covered T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite covered_in_coverable.\n    apply W_ar_coverable_in_I.\n  Qed.\n\n  Lemma W_ar_coverable_issuable_in_CI  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite id_union, !seq_union_r, dom_union; unionL.\n    { by apply W_ar_coverable_in_I. }\n    apply ar_issuable_in_I.\n  Qed.\n\n  Lemma ar_CI_in_CI  :\n    dom_rel (\u2997W\u2998 \u2a3e ar \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite id_union, !seq_union_r, dom_union; unionL.\n    { by apply W_ar_C_in_I. }\n    apply ar_I_in_I.\n  Qed.\n\n  Lemma ar_rt_I_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar\uff0a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite rtE, !seq_union_l, !seq_union_r, seq_id_l, dom_union.\n    unionL; [basic_solver|]. by apply ar_ct_I_in_I.\n  Qed.\n\n  Lemma dom_W_sb_coverable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e sb \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite sb_coverable; auto.\n    etransitivity.\n    2: by apply w_covered_issued.\n    basic_solver.\n  Qed.\n  \n  Lemma dom_W_sb_C_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e sb \u2a3e \u2997covered T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    rewrite covered_in_coverable.\n    apply dom_W_sb_coverable_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_coverable_in_I  :\n    dom_rel (rf \u2a3e (ppo \u2229 same_loc) \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    arewrite (ppo \u2229 same_loc \u2286 ppo).\n    rewrite (dom_l (wf_rfD WF)), seqA.\n    rewrite rfi_union_rfe, !seq_union_l, !seq_union_r, dom_union.\n    unionL.\n    2: { rewrite (dom_r (@wf_ppoD G)), !seqA.\n         rewrite <- id_inter.\n         rewrite w_coverable_issued.\n         sin_rewrite rfe_ppo_in_ar_ct; auto.\n           by apply ar_ct_I_in_I. }\n    arewrite (rfi \u2286 sb).\n    rewrite (ppo_in_sb WF). sin_rewrite sb_sb.\n    rewrite dom_W_sb_coverable_in_I; auto.\n  Qed.\n\n  Lemma rfrmw_coverable_in_I  :\n    dom_rel (rf \u2a3e rmw \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply rf_ppo_loc_coverable_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_C_in_I  :\n    dom_rel (rf \u2a3e (ppo \u2229 same_loc) \u2a3e \u2997covered T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite covered_in_coverable.\n    apply rf_ppo_loc_coverable_in_I.\n  Qed.\n\n  Lemma rfrmw_C_in_I  :\n    dom_rel (rf \u2a3e rmw \u2a3e \u2997covered T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite covered_in_coverable.\n    apply rfrmw_coverable_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_coverable_issuable_in_I  :\n    dom_rel (rf \u2a3e (ppo \u2229 same_loc) \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite id_union, !seq_union_r, dom_union.\n    unionL.\n    { apply rf_ppo_loc_coverable_in_I. }\n    rewrite (dom_l (wf_rfD WF)), !seqA.\n    arewrite (rf \u2a3e ppo \u2229 same_loc \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc).\n      by apply ar_rf_ppo_loc_issuable_in_I.\n  Qed.\n\n  Lemma rfrmw_coverable_issuable_in_I  :\n    dom_rel (rf \u2a3e rmw \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply rf_ppo_loc_coverable_issuable_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_I_in_I  :\n    dom_rel (rf \u2a3e (ppo \u2229 same_loc) \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (dom_l (wf_rfD WF)), seqA.\n    arewrite (rf \u2a3e (ppo \u2229 same_loc) \u2286 ar \u222a rf \u2a3e (ppo \u2229 same_loc)).\n      by apply ar_rf_ppo_loc_I_in_I.\n  Qed.\n\n  Lemma rfrmw_I_in_I  :\n    dom_rel (rf \u2a3e rmw \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply rf_ppo_loc_I_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_rt_I_in_I  :\n    dom_rel ((rf \u2a3e ppo \u2229 same_loc)\uff0a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite rtE. rewrite !seq_union_l, !seq_id_l. rewrite dom_union.\n    unionL; [basic_solver|].\n    rewrite (dom_l (wf_rfD WF)). rewrite !seqA.\n    rewrite inclusion_ct_seq_eqv_l. rewrite !seqA.\n    arewrite (rf \u2a3e ppo \u2229 same_loc \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc).\n    apply ar_rf_ppo_loc_ct_I_in_I.\n  Qed.\n\n  Lemma rfrmw_rt_I_in_I  :\n    dom_rel ((rf \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply rf_ppo_loc_rt_I_in_I.\n  Qed.\n\n  Lemma rf_ppo_loc_CI_in_I  :\n    dom_rel (rf \u2a3e (ppo \u2229 same_loc) \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite id_union, !seq_union_r, dom_union.\n    unionL.\n    { by apply rf_ppo_loc_C_in_I. }\n      by apply rf_ppo_loc_I_in_I.\n  Qed.\n\n  Lemma rfrmw_CI_in_I  :\n    dom_rel (rf \u2a3e rmw \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply rf_ppo_loc_CI_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_coverable_in_CI  :\n    dom_rel ((ar \u222a rf \u2a3e ppo \u2229 same_loc) \u2a3e \u2997coverable T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite seq_union_l, dom_union, !seqA.\n    unionL.\n    { by apply ar_coverable_in_CI. }\n    rewrite rf_ppo_loc_coverable_in_I; eauto with hahn.\n  Qed.\n\n  Lemma ar_rfrmw_coverable_in_CI  :\n    dom_rel ((ar \u222a rf \u2a3e rmw) \u2a3e \u2997coverable T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_coverable_in_CI.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_C_in_CI  :\n    dom_rel ((ar \u222a rf \u2a3e ppo \u2229 same_loc) \u2a3e \u2997covered T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite covered_in_coverable at 1.\n    apply ar_rf_ppo_loc_coverable_in_CI.\n  Qed.\n\n  Lemma ar_rfrmw_C_in_CI  :\n    dom_rel ((ar \u222a rf \u2a3e rmw) \u2a3e \u2997covered T\u2998) \u2286\u2081 covered T \u222a\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_C_in_CI.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_coverable_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc) \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite seq_union_l, seq_union_r, dom_union; unionL.\n    { apply W_ar_coverable_issuable_in_CI. }\n    arewrite_id \u2997W\u2998. rewrite seq_id_l.\n    apply rf_ppo_loc_coverable_issuable_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_coverable_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw) \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_coverable_issuable_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc) \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite seq_union_l, seq_union_r, dom_union; unionL.\n    { apply ar_CI_in_CI. }\n    arewrite_id \u2997W\u2998. rewrite seq_id_l.\n    apply rf_ppo_loc_CI_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw) \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). by apply ar_rf_ppo_loc_CI_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_ct_coverable_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc)\u207a \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    intros x [y HH].\n    destruct_seq HH as [AA BB].\n    apply clos_trans_tn1 in HH.\n    induction HH as [y HH|y z QQ].\n    { eapply ar_rf_ppo_loc_coverable_issuable_in_I. basic_solver 10. }\n    apply clos_tn1_trans in HH.\n    destruct QQ as [QQ|QQ].\n    2: { apply IHHH. right.\n         apply issued_in_issuable.\n         apply rf_ppo_loc_coverable_issuable_in_I.\n         exists z. apply seqA. basic_solver. }\n    destruct BB as [BB|BB].\n    2: { apply ar_rf_ppo_loc_ct_issuable_in_I. exists z.\n         apply seq_eqv_lr. splits; auto.\n         apply ct_end. exists y. split; auto.\n         { by apply clos_trans_in_rt. }\n           by left. }\n    apply IHHH.\n    destruct QQ as [[QQ|QQ]|QQ].\n    { left. apply covered_in_coverable.\n      apply dom_sc_coverable. exists z. basic_solver. }\n    { right. apply issued_in_issuable.\n      apply dom_rf_coverable. exists z.\n      do 2 red in QQ. basic_solver. }\n    left. apply covered_in_coverable.\n    apply dom_sb_coverable. exists z.\n    apply seq_eqv_r. split; auto. by apply ar_int_in_sb.\n  Qed.\n\n  Lemma ar_rfrmw_ct_coverable_issuable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\u207a \u2a3e \u2997coverable T \u222a\u2081 issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). apply ar_rf_ppo_loc_ct_coverable_issuable_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_ct_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc)\u207a \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite covered_in_coverable.\n    rewrite issued_in_issuable at 1.\n    apply ar_rf_ppo_loc_ct_coverable_issuable_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_ct_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\u207a \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). apply ar_rf_ppo_loc_ct_CI_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_rt_coverable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc)\uff0a \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite rtE. rewrite !seq_union_l, !seq_union_r, dom_union, seq_id_l.\n    unionL.\n    { generalize w_coverable_issued. basic_solver. }\n    arewrite (coverable T \u2286\u2081 coverable T \u222a\u2081 issuable T).\n    apply ar_rf_ppo_loc_ct_coverable_issuable_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_rt_coverable_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\uff0a \u2a3e \u2997coverable T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). apply ar_rf_ppo_loc_rt_coverable_in_I.\n  Qed.\n\n  Lemma ar_rf_ppo_loc_rt_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e ppo \u2229 same_loc)\uff0a \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite rtE. rewrite !seq_union_l, !seq_union_r, dom_union, seq_id_l.\n    unionL.\n    { generalize w_covered_issued. basic_solver. }\n    apply ar_rf_ppo_loc_ct_CI_in_I.\n  Qed.\n\n  Lemma ar_rfrmw_rt_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e (ar \u222a rf \u2a3e rmw)\uff0a \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite (rmw_in_ppo_loc WF). apply ar_rf_ppo_loc_rt_CI_in_I.\n  Qed.\n  \n  Lemma ar_rt_C_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar\uff0a \u2a3e \u2997covered T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    unfolder.\n    ins. desf.\n    apply clos_rt_rtn1 in H0.\n    induction H0.\n    { apply w_covered_issued; basic_solver. }\n    apply clos_rtn1_rt in H2.\n    destruct H0 as [[AA|AA]|AA].\n    3: { apply ar_int_in_sb in AA; auto.\n         apply IHclos_refl_trans_n1.\n         eapply dom_sb_covered; basic_solver 10. }\n    { apply IHclos_refl_trans_n1.\n      eapply dom_sc_covered; basic_solver 10. }\n    apply ar_rt_I_in_I; auto.\n    exists y. unfolder; splits; auto.\n    apply dom_rf_covered; auto.\n    eexists. apply seq_eqv_r. by split; [apply AA|].\n  Qed.\n\n  Lemma ar_rt_CI_in_I  :\n    dom_rel (\u2997W\u2998 \u2a3e ar\uff0a \u2a3e \u2997covered T \u222a\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH.\n    rewrite id_union, !seq_union_r, dom_union; unionL.\n    { by apply ar_rt_C_in_I. }\n      by apply ar_rt_I_in_I.\n  Qed.\n\n  Lemma sbCsbI_CsbI   :\n    sb \u2a3e \u2997covered T \u222a\u2081 dom_rel (sb^? \u2a3e \u2997issued T\u2998)\u2998 \u2286\n    \u2997covered T \u222a\u2081 dom_rel (sb^? \u2a3e \u2997issued T\u2998)\u2998 \u2a3e sb.\n  Proof using TCCOH.\n    rewrite id_union, !seq_union_r, !seq_union_l.\n    apply union_mori.\n    { rewrite sb_covered; eauto. basic_solver. }\n    generalize (@sb_trans G). basic_solver 10.\n  Qed.\n\n  Lemma issuable_next_w :\n    W \u2229\u2081 next (covered T) \u2286\u2081 issuable T.\n  Proof using WF IMMCON TCCOH.\n    unfold issuable, next.\n    rewrite fwbob_in_bob, bob_in_sb.\n    apply set_subset_inter_r; split.\n    { basic_solver 10. }\n    rewrite !set_interA.\n    arewrite (dom_cond sb (covered T) \u2229\u2081 set_compl (covered T) \u2286\u2081 dom_cond sb (covered T)).\n    { basic_solver 10. }\n    intros e [WW [HH DD]]. red in DD. red.\n    arewrite (\u2997eq e\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997eq e\u2998) by basic_solver.\n    rewrite ct_end, !seqA.\n    arewrite (ar \u222a rf \u2a3e ppo \u2229 same_loc \u2286 (ar \u222a sb)^? \u2a3e ar) at 2.\n    { apply inclusion_union_l; [basic_solver|].\n      rewrite rfi_union_rfe. rewrite rfe_in_ar, ppo_in_ar.\n      arewrite (rfi \u2286 sb). basic_solver 10. }\n    arewrite (ar \u2a3e \u2997W\u2998 \u2286 sb).\n    { unfold imm_s.ar.\n      rewrite !seq_union_l. rewrite (ar_int_in_sb WF).\n      rewrite wf_scD with (sc:=sc); [|by apply IMMCON].\n      rewrite (wf_rfeD WF). type_solver. }\n    apply dom_rel_helper_in in DD.\n    rewrite DD.\n    arewrite ((ar \u222a sb)^? \u2a3e \u2997covered T\u2998 \u2286 \u2997covered T \u222a\u2081 issued T\u2998 \u2a3e (ar \u222a sb)^? \u2a3e \u2997covered T\u2998).\n    2: { etransitivity.\n         2: by apply ar_rf_ppo_loc_rt_CI_in_I.\n         basic_solver 20. }\n    apply dom_rel_helper_in.\n    rewrite crE, !seq_union_l, !dom_union, seq_id_l.\n    unionL; [basic_solver| |].\n    2: rewrite dom_sb_covered; basic_solver.\n    apply ar_C_in_CI.\n  Qed.\n  \n  Lemma dom_rfe_ppo_issued :\n    dom_rel (rfe \u2a3e ppo \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite (dom_l (wf_rfeD WF)).\n    arewrite (rfe \u2286 ar).\n    rewrite ppo_in_ar.\n    sin_rewrite ar_ar_in_ar_ct.\n      by apply ar_ct_I_in_I.\n  Qed.\n\n  Lemma dom_ar_ct_issuable : dom_rel (\u2997W\u2998 \u2a3e ar\u207a \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc).\n    unfold issuable.\n    basic_solver 20.\n  Qed.\n\n  Lemma dom_detour_rfe_ppo_issuable :\n    dom_rel ((detour \u222a rfe) \u2a3e ppo \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite (dom_l (wf_rfeD WF)).\n    rewrite (dom_l (wf_detourD WF)).\n    arewrite (rfe \u2286 ar).\n    arewrite (detour \u2286 ar).\n    relsf.\n    rewrite ppo_in_ar, !seqA.\n    sin_rewrite ar_ar_in_ar_ct.\n    apply dom_ar_ct_issuable.\n  Qed.\n  \n  Lemma dom_detour_rfe_ppo_issued :\n    dom_rel ((detour \u222a rfe) \u2a3e ppo \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply dom_detour_rfe_ppo_issuable.\n  Qed.\n\n  Lemma dom_detour_rfe_acq_sb_issuable :\n    dom_rel ((detour \u222a rfe) \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite (dom_l (wf_detourD WF)).\n    rewrite (dom_l (wf_rfeD WF)).\n    arewrite (rfe \u2286 ar).\n    arewrite (detour \u2286 ar).\n    relsf.\n    arewrite (\u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2286 ar).\n    { arewrite (\u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2286 bob). unfold imm_s.ar, ar_int. eauto with hahn. }\n    sin_rewrite ar_ar_in_ar_ct.\n    apply dom_ar_ct_issuable.\n  Qed.\n\n  Lemma dom_detour_rfe_acq_sb_issued :\n    dom_rel ((detour \u222a rfe) \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply dom_detour_rfe_acq_sb_issuable.\n  Qed.\n\n  Lemma dom_detour_rmwrfi_rfe_acq_sb_issuable :\n    dom_rel ((detour \u222a rfe) \u2a3e (rmw \u2a3e rfi)\uff0a \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    arewrite (\u2997R \u2229\u2081 Acq\u2998 \u2286 \u2997Acq\u2998 \u2a3e \u2997R \u2229\u2081 Acq\u2998) by basic_solver.\n    arewrite (rfi \u2286 rf).\n    sin_rewrite (@rmwrf_rt_Acq_in_ar_rfrmw_rt G WF sc); auto.\n    rewrite (dom_l (wf_detourD WF)).\n    rewrite (dom_l (wf_rfeD WF)).\n    arewrite (rfe \u2286 ar).\n    arewrite (detour \u2286 ar).\n    relsf.\n    arewrite (\u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2286 ar).\n    { arewrite (\u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2286 bob). unfold imm_s.ar, ar_int. eauto with hahn. }\n    arewrite (ar \u2286 ar \u222a rf \u2a3e rmw) at 3.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e rmw) at 1.\n    seq_rewrite <- ct_end.\n    arewrite ((ar \u222a rf \u2a3e rmw) \u2a3e (ar \u222a rf \u2a3e rmw)\u207a \u2286 (ar \u222a rf \u2a3e rmw)\u207a).\n    { rewrite ct_step with (r:= ar \u222a rf \u2a3e rmw) at 1. apply ct_ct. }\n    apply ar_rfrmw_ct_issuable_in_I.\n  Qed.\n\n  Lemma dom_detour_rmwrfi_rfe_acq_sb_issued :\n    dom_rel ((detour \u222a rfe) \u2a3e (rmw \u2a3e rfi)\uff0a \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply dom_detour_rmwrfi_rfe_acq_sb_issuable.\n  Qed.\n\n  Lemma dom_rfe_acq_sb_issuable :\n    dom_rel (rfe \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    arewrite (rfe \u2286 detour \u222a rfe).\n    apply dom_detour_rfe_acq_sb_issuable.\n  Qed.\n\n  Lemma dom_rfe_acq_sb_issued :\n    dom_rel (rfe \u2a3e \u2997R \u2229\u2081 Acq\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply dom_rfe_acq_sb_issuable.\n  Qed.\n\n  Lemma dom_wex_sb_issuable :\n    dom_rel (\u2997W_ex_acq\u2998 \u2a3e sb \u2a3e \u2997issuable T\u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    arewrite (\u2997W_ex_acq\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997W_ex_acq\u2998).\n    { rewrite <- seq_eqvK at 1.\n      rewrite (W_ex_in_W WF) at 1. basic_solver. }\n    arewrite (\u2997issuable T\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997issuable T\u2998).\n    { unfold issuable. basic_solver 10. }\n    arewrite (\u2997W_ex_acq\u2998 \u2a3e sb \u2a3e \u2997W\u2998 \u2286 ar).\n    apply ar_issuable_is_issued.\n  Qed.\n\n  Lemma dom_wex_sb_issued :\n    dom_rel (\u2997W_ex_acq\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1.\n    apply dom_wex_sb_issuable.\n  Qed.\n  \n  Lemma rf_rmw_issued_rfi_rmw_issued : \n    (rf \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998 \u2286 (rfi \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998 \u2a3e (rf \u2a3e rmw)\uff0a.\n  Proof using WF TCCOH IMMCON.\n    assert (transitive sb) as SBT by apply sb_trans.\n    eapply rt_ind_left with (P:= fun r => r \u2a3e \u2997issued T\u2998).\n    { by eauto with hahn. }\n    { basic_solver 12. }\n    intros k H; rewrite !seqA.\n    sin_rewrite H.\n    rewrite rfi_union_rfe at 1; relsf; unionL.\n    rewrite <- seqA; seq_rewrite <- ct_begin; basic_solver 12.\n    rewrite rtE at 2.\n    relsf; unionR left.\n    arewrite (rfe \u2a3e rmw \u2a3e (rfi \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998 \u2286\n                  \u2997issued T\u2998 \u2a3e rfe \u2a3e rmw \u2a3e (rfi \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998).\n    { apply dom_rel_helper.\n      arewrite (rmw \u2a3e (rfi \u2a3e rmw)\uff0a \u2286 ar\uff0a).\n      { arewrite (rfi \u2286 rf).\n        rewrite (rmw_in_ppo WF) at 1. rewrite ppo_in_ar.\n        rewrite rtE at 1. rewrite seq_union_r, seq_id_r.\n        apply inclusion_union_l.\n        { rewrite ct_step at 1. apply inclusion_t_rt. }\n        rewrite rmw_in_ppo_loc; auto.\n        rewrite ar_rf_ppo_loc_ct_in_ar_ct; auto. apply inclusion_t_rt. }\n      rewrite (dom_l (wf_rfeD WF)), !seqA.\n      arewrite (rfe \u2286 ar) at 1.\n      seq_rewrite <- ct_begin. by apply ar_ct_I_in_I. }\n    arewrite (rfe \u2a3e rmw \u2286 rf \u2a3e rmw).\n    arewrite (rfi \u2286 rf).\n    arewrite (rf \u2a3e rmw \u2a3e (rf \u2a3e rmw)\uff0a \u2286 (rf \u2a3e rmw)\u207a).\n    { rewrite <- seqA. apply ct_begin. }\n    arewrite_id \u2997issued T\u2998 at 2. rewrite seq_id_l.\n    rewrite ct_rt. by rewrite inclusion_t_rt.\n  Qed.\n\n  Lemma wex_rfi_rfe_rmw_issuable_is_issued :\n    dom_rel ((\u2997 W_ex_acq \u2998 \u2a3e rfi \u222a rfe) \u2a3e rmw \u2a3e \u2997 issuable T \u2998) \u2286\u2081 issued T.\n  Proof using WF.\n    rewrite seq_union_l. rewrite dom_union.\n    apply set_subset_union_l; split.\n    { rewrite seqA. rewrite (rfi_in_sbloc' WF). rewrite (rmw_in_sb WF).\n      arewrite (sb \u2229 same_loc \u2a3e sb \u2286 sb).\n      { generalize (@sb_trans G). basic_solver. }\n      arewrite (\u2997issuable T\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997issuable T\u2998).\n      { unfold issuable. basic_solver 10. }\n      arewrite (\u2997W_ex_acq\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997W_ex_acq\u2998).\n      { rewrite <- seq_eqvK at 1.\n        rewrite (W_ex_in_W WF) at 1. basic_solver. }\n      arewrite (\u2997W_ex_acq\u2998 \u2a3e sb \u2a3e \u2997W\u2998 \u2286 ar).\n      rewrite ct_step with (r:=ar).\n      unfold issuable.\n      arewrite (ar \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc) at 1.\n      basic_solver 10. }\n    rewrite (rmw_in_ppo WF).\n    rewrite ppo_in_ar.\n    rewrite (dom_l (wf_rfeD WF)), !seqA.\n    arewrite (rfe \u2286 ar).\n    sin_rewrite ar_ar_in_ar_ct.\n    unfold issuable.\n    arewrite (ar \u2286 ar \u222a rf \u2a3e ppo \u2229 same_loc) at 1.\n    basic_solver 10. \n  Qed.\n\n  Lemma wex_rfi_rfe_rmw_issued_is_issued :\n    dom_rel ((\u2997 W_ex_acq \u2998 \u2a3e rfi \u222a rfe) \u2a3e rmw \u2a3e \u2997 issued T \u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    rewrite issued_in_issuable at 1; auto.\n      by apply wex_rfi_rfe_rmw_issuable_is_issued.\n  Qed.\n\n  Lemma wex_rf_rmw_issued_is_issued :\n    dom_rel (\u2997 W_ex_acq \u2998 \u2a3e rf \u2a3e rmw \u2a3e \u2997 issued T \u2998) \u2286\u2081 issued T.\n  Proof using WF TCCOH.\n    arewrite (\u2997W_ex_acq\u2998 \u2a3e rf \u2286 (\u2997 W_ex_acq \u2998 \u2a3e rfi \u222a rfe)).\n    { rewrite rfi_union_rfe. basic_solver. }\n      by apply wex_rfi_rfe_rmw_issued_is_issued.\n  Qed.\n\n  Lemma rf_rmw_issued :\n    (rf \u2a3e rmw)\uff0a \u2a3e \u2997issued T\u2998 \u2286 (rf \u2a3e rmw \u2a3e \u2997issued T\u2998)\uff0a.\n  Proof using WF TCCOH.\n    intros x y HH. destruct_seq_r HH as II.\n    apply clos_rt_rtn1 in HH.\n    induction HH as [|y z TT].\n    { apply rt_refl. }\n    apply rt_end. right. exists y.\n    split.\n    2: apply seqA; basic_solver.\n    apply IHHH.\n    apply ar_rfrmw_I_in_I. exists z.\n    apply seq_eqv_lr. splits; auto.\n    2: by right.\n    red in TT. desf. apply (wf_rfD WF) in TT. unfolder in TT. desf.\n  Qed.\n\n  Lemma dom_W_Rel_sb_loc_I_in_C :\n    dom_rel (\u2997W \u2229\u2081 Rel\u2998 \u2a3e sb \u2229 same_loc \u2a3e \u2997W\u2998 \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\n  Proof using TCCOH.\n    rewrite issued_in_issuable.\n    arewrite (\u2997issuable T\u2998 \u2286 \u2997dom_cond fwbob (covered T)\u2998).\n    { unfold issuable. basic_solver 10. }\n    rewrite <- !seqA.\n    rewrite dom_cond_elim1; [basic_solver 21|].\n    unfold imm_bob.fwbob.\n    basic_solver 12.\n  Qed.\n\n  Lemma I_eq_EW_I : issued T \u2261\u2081 E \u2229\u2081 W \u2229\u2081 issued T.\n  Proof using TCCOH.\n    split; [|clear; basic_solver].\n    generalize issuedW, issuedE.\n    basic_solver.\n  Qed.\n\n  Lemma W_rel_sb_loc_W_CI :\n    (\u2997W \u2229\u2081 Rel\u2998 \u2a3e sb \u2229 same_loc \u2a3e \u2997W\u2998) \u2a3e \u2997covered T \u222a\u2081 issued T\u2998 \u2286\n    \u2997covered T \u222a\u2081 issued T\u2998 \u2a3e (\u2997W \u2229\u2081 Rel\u2998 \u2a3e sb \u2229 same_loc \u2a3e \u2997W\u2998).\n  Proof using TCCOH.\n    (* case_refl _; [basic_solver|]. *)\n    rewrite !seqA.\n    arewrite (\u2997W\u2998 \u2a3e \u2997covered T \u222a\u2081 issued T\u2998 \u2286 \u2997W\u2998 \u2a3e \u2997issued T\u2998).\n    { generalize w_covered_issued. basic_solver. }\n    generalize dom_W_Rel_sb_loc_I_in_C. basic_solver 12.\n  Qed.\n\n  Lemma sb_W_rel_CI (RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T) :\n    (sb \u2a3e \u2997W \u2229\u2081 Rel\u2998) \u2a3e \u2997covered T \u222a\u2081 issued T\u2998 \u2286 \u2997covered T \u222a\u2081 issued T\u2998 \u2a3e (sb \u2a3e \u2997W \u2229\u2081 Rel\u2998).\n  Proof using TCCOH.\n    generalize RELCOV, dom_sb_covered.\n    basic_solver 12.\n  Qed.\n\n  Lemma W_Rel_sb_loc_I : dom_rel (\u2997W \u2229\u2081 Rel\u2998 \u2a3e  (sb \u2229 same_loc) \u2a3e \u2997W \u2229\u2081 issued T\u2998) \u2286\u2081 issued T.\n  Proof using TCCOH.\n    generalize dom_W_Rel_sb_loc_I_in_C, w_covered_issued. basic_solver 21.\n  Qed.\n\n  Lemma sb_loc_issued  :\n    \u2997W \u2229\u2081 Rel\u2998 \u2a3e sb \u2229 same_loc \u2a3e \u2997W\u2998 \u2a3e \u2997issued T\u2998 \u2286 \n               \u2997covered T\u2998 \u2a3e \u2997W \u2229\u2081 Rel\u2998 \u2a3e sb \u2229 same_loc \u2a3e \u2997W\u2998.\n  Proof using TCCOH.\n    seq_rewrite (dom_rel_helper dom_W_Rel_sb_loc_I_in_C).\n    basic_solver.\n  Qed.\n\n  Lemma dom_F_sb_I_in_C :\n    dom_rel (\u2997F \u2229\u2081 Acq/Rel\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\n  Proof using TCCOH.\n    rewrite issued_in_issuable.\n    arewrite (\u2997issuable T\u2998 \u2286 \u2997dom_cond fwbob (covered T)\u2998).\n    { unfold issuable. basic_solver 10. }\n    rewrite <- !seqA.\n    rewrite dom_cond_elim1; [basic_solver 21|].\n    unfold imm_bob.fwbob.\n    basic_solver 12.\n  Qed.\n\n  Lemma F_sb_I_in_C  :\n    \u2997F \u2229\u2081 Acq/Rel\u2998 \u2a3e sb \u2a3e \u2997issued T\u2998 \u2286 \u2997covered T\u2998 \u2a3e \u2997F \u2229\u2081 Acq/Rel\u2998 \u2a3e sb.\n  Proof using TCCOH.\n    seq_rewrite (dom_rel_helper dom_F_sb_I_in_C).\n    basic_solver.\n  Qed.\n\n  Lemma dom_F_Rel_sb_I_in_C :  dom_rel (\u2997F \u2229\u2081 Rel\u2998 \u2a3e  sb \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\n  Proof using TCCOH. etransitivity; [|apply dom_F_sb_I_in_C]; mode_solver 21. Qed.\n\n  Lemma dom_F_Acq_sb_I_in_C :  dom_rel (\u2997F \u2229\u2081 Acq\u2998 \u2a3e  sb \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\n  Proof using TCCOH. etransitivity; [|apply dom_F_sb_I_in_C]; mode_solver 12. Qed.\n\n  Lemma coverable_add_eq_iff e:\n    coverable T e <-> coverable (mkTC (covered T \u222a\u2081 eq e) (issued T)) e.\n  Proof using IMMCON.\n    split.\n    { eapply traversal_mon; simpls. eauto with hahn. }\n    unfold coverable; simpls. \n    intros [[EE COVE] HH].\n    split.\n    { clear HH. split; auto.\n      unfolder in *. ins. desf.\n      edestruct COVE.\n      { eexists; eauto. }\n      { done. }\n      exfalso. desf. eapply sb_irr; eauto. }\n    destruct HH as [[HH|HH]|[AA HH]]; [do 2 left| left;right|right]; auto.\n    split; auto.\n    unfolder in *. ins. desf. edestruct HH.\n    { eexists; eauto. }\n    { done. }\n    exfalso. desf. eapply sc_irr; eauto.\n    apply IMMCON.\n  Qed.\n\n  Lemma issuable_add_eq_iff e :\n    issuable T e <-> issuable (mkTC (covered T) (issued T \u222a\u2081 eq e)) e.\n  Proof using WF IMMCON.\n    cdes IMMCON.\n    split.\n    { eapply traversal_mon; simpls. eauto with hahn. }\n    unfold issuable; simpls. \n    intros [[EE ISSE] HH].\n    unfold dom_cond in *.\n    split; [split|]; auto.\n    all: intros x BB; set (CC:=BB).\n    apply HH in CC.\n    destruct CC; desf.\n    exfalso; clear -BB WF IMMCON.\n    unfolder in *; desf.\n    eapply ar_rf_ppo_loc_acyclic; eauto.\n    apply IMMCON.\n  Qed.\n  \n  Variable RELCOV : W \u2229\u2081 Rel \u2229\u2081 issued T \u2286\u2081 covered T.\n\n  Lemma dom_release_issued :\n    dom_rel (release \u2a3e \u2997 issued T \u2998) \u2286\u2081 covered T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    unfold imm_s_hb.release, imm_s_hb.rs.\n    rewrite !seqA.\n    sin_rewrite rf_rmw_issued_rfi_rmw_issued.\n    rewrite (dom_r (wf_rmwD WF)) at 1.\n    arewrite (\u2997W\u2998 \u2a3e (rfi \u2a3e rmw \u2a3e \u2997W\u2998)\uff0a \u2286 (rfi \u2a3e rmw)\uff0a \u2a3e \u2997W\u2998).\n    { rewrite rtE; relsf; unionL; [basic_solver|].\n      rewrite <- seqA; rewrite inclusion_ct_seq_eqv_r; basic_solver. }\n    rewrite (rmw_in_sb_loc WF) at 1; rewrite (rfi_in_sbloc' WF).\n    generalize (@sb_same_loc_trans G); ins; relsf.\n    rewrite !crE; relsf; unionL; splits.\n    { revert RELCOV; basic_solver 21. }\n    { generalize dom_W_Rel_sb_loc_I_in_C. basic_solver 21. }\n    2: generalize (@sb_trans G).\n    all: generalize dom_F_Rel_sb_I_in_C; basic_solver 40.\n  Qed.\n\n  Lemma release_issued :\n    release \u2a3e \u2997 issued T \u2998 \u2286 \u2997covered T\u2998 \u2a3e release.\n  Proof using WF TCCOH RELCOV IMMCON.\n    seq_rewrite (dom_rel_helper dom_release_issued).\n    basic_solver.\n  Qed.\n\n  Lemma dom_release_rf_coverable :\n    dom_rel (release \u2a3e rf \u2a3e \u2997 coverable T \u2998) \u2286\u2081 covered T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    generalize dom_release_issued.\n    generalize dom_rf_coverable.\n    basic_solver 21.\n  Qed.\n\n  Lemma release_rf_coverable :\n    release \u2a3e rf \u2a3e \u2997 coverable T \u2998 \u2286 \u2997 covered T \u2998 \u2a3e release \u2a3e rf.\n  Proof using WF TCCOH RELCOV IMMCON.\n    seq_rewrite (dom_rel_helper dom_release_rf_coverable).\n    basic_solver.\n  Qed.\n\n  Lemma release_rf_covered :\n    release \u2a3e rf \u2a3e \u2997 covered T \u2998 \u2286 \u2997 covered T \u2998 \u2a3e release \u2a3e rf.\n  Proof using WF TCCOH RELCOV IMMCON.\n    rewrite covered_in_coverable at 1.\n      by apply release_rf_coverable.\n  Qed.\n\n  Lemma dom_sb_W_rel_issued  :\n    dom_rel (sb \u2a3e \u2997W \u2229\u2081 Rel\u2998 \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\n  Proof using TCCOH.\n    rewrite issued_in_issuable.\n    arewrite (\u2997issuable T\u2998 \u2286 \u2997dom_cond fwbob (covered T)\u2998).\n    { unfold issuable. basic_solver 10. }\n    rewrite <- !seqA.\n    rewrite dom_cond_elim1; [basic_solver 21|].\n    unfold imm_bob.fwbob.\n    basic_solver 12.\n  Qed.\n\n  Lemma sb_W_rel_issued  :\n    sb \u2a3e \u2997W \u2229\u2081 Rel\u2998 \u2a3e \u2997issued T\u2998 \u2286 \u2997covered T\u2998 \u2a3e sb \u2a3e \u2997W \u2229\u2081 Rel\u2998.\n  Proof using TCCOH.\n    seq_rewrite (dom_rel_helper dom_sb_W_rel_issued).\n    basic_solver.\n  Qed.\n\n  Lemma dom_sw_coverable :\n    dom_rel (sw \u2a3e \u2997 coverable T \u2998) \u2286\u2081 covered T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    unfold imm_s_hb.sw.\n    generalize dom_sb_coverable.\n    generalize dom_release_rf_coverable.\n    generalize covered_in_coverable.\n    basic_solver 21.\n  Qed.\n\n  Lemma sw_coverable : sw \u2a3e \u2997 coverable T \u2998 \u2286 \u2997covered T\u2998 \u2a3e sw.\n  Proof using WF TCCOH RELCOV IMMCON.\n    seq_rewrite (dom_rel_helper dom_sw_coverable).\n    basic_solver.\n  Qed.\n\n  Lemma sw_covered : sw \u2a3e \u2997 covered T \u2998 \u2286 \u2997covered T\u2998 \u2a3e sw.\n  Proof using WF TCCOH RELCOV IMMCON.\n    rewrite covered_in_coverable at 1.\n      by apply sw_coverable.\n  Qed.\n\n  Lemma hb_coverable : hb \u2a3e \u2997 coverable T \u2998 \u2286 \u2997covered T\u2998 \u2a3e hb.\n  Proof using WF TCCOH RELCOV IMMCON.\n    unfold imm_s_hb.hb.\n    assert (A: (sb \u222a sw) \u2a3e \u2997coverable T\u2998 \u2286 \u2997covered T\u2998 \u2a3e (sb \u222a sw)\u207a).\n    { relsf.\n      rewrite sb_coverable, sw_coverable.\n      rewrite <- ct_step; basic_solver. }\n    unfold imm_s_hb.hb.\n    eapply ct_ind_left with (P:= fun r => r \u2a3e \u2997coverable T\u2998); eauto with hahn.\n    intros k H; rewrite !seqA, H.\n    rewrite covered_in_coverable at 1.\n    sin_rewrite A.\n    arewrite ((sb \u222a sw)\u207a \u2286 (sb \u222a sw)\uff0a) at 1.\n    relsf.\n  Qed.\n\nLemma sc_sb_I_dom_C  :\n  dom_rel (sc \u2a3e sb \u2a3e \u2997issued T\u2998) \u2286\u2081 covered T.\nProof using WF IMMCON TCCOH RELCOV.\n  cdes IMMCON.\n  rewrite (dom_r (wf_scD Wf_sc)).\n  unfolder. ins. desf.\n  cdes TCCOH.\n  assert (covered T z) as AA.\n  2: { apply CC in AA. red in AA.\n       unfolder in AA. desf.\n       1,2: type_solver.\n       eapply AA2. eexists.\n       apply seq_eqv_r. split; eauto. }\n  eapply II; eauto.\n  eexists. apply seq_eqv_r. split; eauto.\n  apply sb_from_f_in_fwbob.\n  apply seq_eqv_l. split; [split|]; auto.\n  mode_solver.\nQed.\n\n  Lemma dom_hb_coverable :\n    dom_rel (hb \u2a3e \u2997 coverable T \u2998) \u2286\u2081 covered T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    rewrite hb_coverable; basic_solver 10.\n  Qed.\n\n  Lemma hb_covered :\n    hb \u2a3e \u2997 covered T \u2998 \u2286 \u2997covered T\u2998 \u2a3e hb.\n  Proof using WF TCCOH RELCOV IMMCON.\n    rewrite covered_in_coverable at 1.\n      by apply hb_coverable.\n  Qed.\n\n  Lemma dom_urr_coverable l:\n    dom_rel (urr l \u2a3e \u2997 coverable T \u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.urr.\n    generalize dom_hb_coverable.\n    generalize dom_sc_coverable.\n    generalize dom_rf_coverable.\n    generalize covered_in_coverable.\n    generalize w_coverable_issued.\n    basic_solver 21.\n  Qed.\n\n  Lemma urr_coverable l:\n    urr l \u2a3e \u2997 coverable T \u2998 \u2286 \u2997issued T\u2998 \u2a3e urr l.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite (dom_rel_helper (@dom_urr_coverable l)).\n    basic_solver.\n  Qed.\n\n  Lemma urr_covered l:\n    urr l \u2a3e \u2997 covered T \u2998 \u2286 \u2997issued T\u2998 \u2a3e urr l.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply urr_coverable.\n  Qed.\n\n  Lemma dom_c_acq_coverable i l A:\n    dom_rel (c_acq i l A \u2a3e \u2997 coverable T \u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.c_acq.\n    generalize (@dom_urr_coverable l).\n    generalize covered_in_coverable.\n    generalize dom_release_issued.\n    generalize dom_rf_coverable.\n    basic_solver 21.\n  Qed.\n\n  Lemma c_acq_coverable i l A:\n    c_acq i l A \u2a3e \u2997 coverable T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_acq i l A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite (dom_rel_helper (@dom_c_acq_coverable i l A)).\n    basic_solver.\n  Qed.\n\n  Lemma c_acq_covered i l A:\n    c_acq i l A \u2a3e \u2997 covered T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_acq i l A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable  at 1.\n      by apply c_acq_coverable.\n  Qed.\n\n  Lemma dom_c_cur_coverable i l A:\n    dom_rel (c_cur i l A \u2a3e \u2997 coverable T \u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.c_cur.\n    generalize (@dom_urr_coverable l).\n    basic_solver 21.\n  Qed.\n\n  Lemma c_cur_coverable i l A:\n    c_cur i l A \u2a3e \u2997 coverable T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_cur i l A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    seq_rewrite (dom_rel_helper (@dom_c_cur_coverable i l A)).\n    basic_solver.\n  Qed.\n\n\n  Lemma c_cur_covered i l A:\n    c_cur i l A \u2a3e \u2997 covered T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_cur i l A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply c_cur_coverable.\n  Qed.\n\n  Lemma dom_c_rel_coverable i l l' A:\n    dom_rel (c_rel i l l' A \u2a3e \u2997 coverable T \u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.c_rel.\n    generalize (@dom_urr_coverable l).\n    basic_solver 21.\n  Qed.\n\n\n  Lemma c_rel_coverable i l l' A:\n    c_rel i l l' A \u2a3e \u2997 coverable T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_rel i l l' A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    seq_rewrite (dom_rel_helper (@dom_c_rel_coverable i l l' A)).\n    basic_solver.\n  Qed.\n\n\n  Lemma c_rel_covered i l l' A:\n    c_rel i l l' A \u2a3e \u2997 covered T \u2998 \u2286 \u2997issued T\u2998 \u2a3e c_rel i l l' A.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply c_rel_coverable.\n  Qed.\n\n  Lemma t_acq_coverable l thread:\n    t_acq thread l (coverable T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.t_acq.\n    rewrite (dom_r (wf_c_acqD G sc thread l (coverable T))).\n    arewrite (\u2997(Tid_ thread \u222a\u2081 Init) \u2229\u2081 coverable T\u2998 \u2286 \u2997coverable T\u2998) by basic_solver.\n    rewrite c_acq_coverable.\n    basic_solver.\n  Qed.\n\n  Lemma t_acq_covered l thread:\n    t_acq thread l (covered T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply t_acq_coverable.\n  Qed.\n\n  Lemma t_cur_coverable l thread:\n    t_cur thread l (coverable T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    etransitivity; [by apply t_cur_in_t_acq|].\n      by apply t_acq_coverable.\n  Qed.\n\n  Lemma t_cur_covered l thread:\n    t_cur thread l (covered T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply t_cur_coverable.\n  Qed.\n\n  Lemma t_rel_coverable l l' thread:\n    t_rel thread l l' (coverable T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    etransitivity; [by apply t_rel_in_t_cur|].\n      by apply t_cur_coverable.\n  Qed.\n\n  Lemma t_rel_covered l l' thread:\n    t_rel thread l l' (covered T) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    rewrite covered_in_coverable at 1.\n      by apply t_rel_coverable.\n  Qed.\n\n  Lemma S_tm_coverable l :\n    S_tm l (coverable T) \u2286\u2081 issued T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    unfold CombRelations.S_tm, CombRelations.S_tmr.\n    generalize dom_hb_coverable.\n    generalize w_coverable_issued.\n    generalize covered_in_coverable.\n    generalize dom_release_issued.\n    generalize dom_rf_coverable.\n    basic_solver 21.\n  Qed.\n\n  Lemma S_tm_covered l:\n    S_tm l (covered T) \u2286\u2081 issued T.\n  Proof using WF TCCOH RELCOV IMMCON.\n    rewrite covered_in_coverable at 1.\n      by apply S_tm_coverable.\n  Qed.\n\n  Lemma msg_rel_issued l:\n    dom_rel (msg_rel l \u2a3e \u2997 issued T \u2998) \u2286\u2081 issued T.\n  Proof using WF IMMCON TCCOH RELCOV.\n    unfold CombRelations.msg_rel.\n    generalize dom_release_issued.\n    generalize (@dom_urr_coverable l).\n    generalize covered_in_coverable.\n    basic_solver 21.\n  Qed.\n\nLemma exists_ncov thread (FINDOM : set_finite E) :\n  exists n, ~ covered T (ThreadEvent thread n).\nProof using TCCOH.\n  destruct (exists_nE G FINDOM thread) as [n HH].\n  exists n. intros CC. apply HH.\n  eapply coveredE; eauto.\nQed.\n\nSection HbProps.\n\nNotation \"'C'\" := (covered T).\nNotation \"'I'\" := (issued  T).\n\nLemma sw_in_Csw_sb :\n  sw \u2a3e \u2997C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997 I \u2998)\u2998 \u2286 \u2997 C \u2998 \u2a3e sw \u222a sb.\nProof using WF TCCOH RELCOV IMMCON.\n  rewrite !id_union. rewrite seq_union_r. \n  unionL.\n  { rewrite sw_covered; eauto. basic_solver. }\n  assert (forall (s : actid -> Prop), s \u222a\u2081 set_compl s \u2261\u2081 fun _ => True) as AA.\n  { split; [basic_solver|].\n    unfolder. ins. apply classic. }\n  arewrite (sw \u2286 \u2997 C \u222a\u2081 set_compl C \u2998 \u2a3e sw) at 1.\n  { rewrite AA. by rewrite seq_id_l. }\n  rewrite id_union, !seq_union_l.\n  apply union_mori; [basic_solver|].\n  rewrite (dom_r (wf_swD WF)).\n  rewrite sw_in_ar0; auto.\n  remember (\u2997Rel\u2998 \u2a3e (\u2997F\u2998 \u2a3e sb)^? \u2a3e \u2997W\u2998 \u2a3e (sb \u2229 same_loc)^? \u2a3e \u2997W\u2998 \u2a3e (rfe \u222a ar_int G)\u207a) as ax.\n  rewrite !seq_union_l, !seq_union_r.\n  unionL; [|basic_solver].\n  subst ax. rewrite !seqA.\n  arewrite ((sb \u2229 same_loc)^? \u2a3e \u2997W\u2998 \u2286 (sb \u2229 same_loc)^? \u2a3e \u2997W\u2998 \u2a3e \u2997W\u2998) by basic_solver. \n  arewrite (\u2997Rel\u2998 \u2a3e (\u2997F\u2998 \u2a3e sb)^? \u2a3e \u2997W\u2998 \u2a3e (sb \u2229 same_loc)^? \u2a3e \u2997W\u2998 \u2286 release).\n  { unfold imm_s_hb.release, imm_s_hb.rs. by rewrite <- inclusion_id_rt, seq_id_r. }\n  enough (dom_rel (\u2997W\u2998 \u2a3e (rfe \u222a ar_int G)\u207a \u2a3e \u2997FR \u2229\u2081 Acq\u2998 \u2a3e \u2997dom_rel (sb^? \u2a3e \u2997I\u2998)\u2998) \u2286\u2081 I) as BB.\n  { rewrite (dom_rel_helper BB).\n    seq_rewrite (dom_rel_helper dom_release_issued).\n    basic_solver. }\n  rewrite <- !seqA. rewrite dom_rel_eqv_dom_rel. rewrite !seqA.\n  arewrite (\u2997FR \u2229\u2081 Acq\u2998 \u2a3e sb^? \u2286 (rfe \u222a ar_int G)^?).\n  { rewrite !crE, !seq_union_r. apply union_mori; [basic_solver|].\n    unionR right. rewrite set_inter_union_l, id_union, seq_union_l.\n    rewrite sb_from_r_acq_in_bob.\n    arewrite (Acq \u2286\u2081 Acq/Rel) by mode_solver.\n    rewrite sb_from_f_in_bob. rewrite bob_in_ar_int. eauto with hahn. }\n  seq_rewrite ct_cr.\n  arewrite (rfe \u222a ar_int G \u2286 ar). by apply ar_ct_I_in_I.\nQed.\n\nLemma hb_in_Chb_sb :\n  hb \u2a3e \u2997C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997 I \u2998)\u2998 \u2286 \u2997 C \u2998 \u2a3e hb \u222a sb.\nProof using WF TCCOH RELCOV IMMCON.\n  unfold imm_s_hb.hb.\n  intros x y HH.\n  destruct_seq_r HH as DOM.\n  apply clos_trans_tn1 in HH.\n  induction HH as [y [HH|HH]|y z AA].\n  { by right. }\n  { assert ((\u2997C\u2998 \u2a3e sw \u222a sb) x y) as [ZZ|ZZ].\n    3: by right.\n    2: { destruct_seq_l ZZ as CX.\n         left. apply seq_eqv_l. split; auto.\n         apply ct_step. by right. }\n    apply sw_in_Csw_sb; auto. apply seq_eqv_r. splits; auto. }\n  assert (sb y z -> (C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997I\u2998)) y) as DOMY.\n  { intros SB.\n    destruct DOM as [DOM|DOM].\n    2: { right. generalize (@sb_trans G) SB DOM. basic_solver 10. }\n    left.\n    eapply dom_sb_covered; eauto. eexists.\n    apply seq_eqv_r. split; eauto. }\n\n  assert ((C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997I\u2998)) y) as BB.\n  2: { set (CC:=BB). apply IHHH in CC.\n       destruct CC as [CC|CC].\n       { left.\n         destruct_seq_l CC as XX.\n         apply seq_eqv_l. split; auto.\n         (* TODO: is the last tactic needed? *)\n         apply ct_ct. exists y. split; eauto; try by apply ct_step. }\n       destruct AA as [AA|AA].\n       { right. eapply (@sb_trans G); eauto. }\n       assert ((sw \u2a3e \u2997C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997I\u2998)\u2998) y z) as DD.\n       { apply seq_eqv_r. by split. }\n       eapply sw_in_Csw_sb in DD; auto.\n       destruct DD as [DD|DD].\n       2: { right. eapply (@sb_trans G); eauto. }\n       left.\n       apply seq_eqv_l. split.\n       2: { apply ct_ct. eexists.\n            split; apply ct_step; [left|right]; eauto. }\n       assert (C y) as CY.\n       { by destruct_seq_l DD as XX. }\n       eapply dom_sb_covered; eauto. eexists.\n       apply seq_eqv_r. split; eauto. }\n  destruct AA as [|AA]; [by intuition|].\n  assert ((sw \u2a3e \u2997C \u222a\u2081 dom_rel (sb^? \u2a3e \u2997I\u2998)\u2998) y z) as DD.\n  { apply seq_eqv_r. by split. }\n  eapply sw_in_Csw_sb in DD; auto.\n  destruct DD as [DD|]; [|by intuition].\n  left. by destruct_seq_l DD as CY.\nQed.\nEnd HbProps.\nEnd Properties.\n\nEnd TraversalConfig.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/traversal/TraversalConfig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.17035914897391394}}
{"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 Require Import ftlr_base_binary.\nFrom cap_machine.rules_binary Require Import rules_binary_base rules_binary_IsPtr.\n\nSection fundamental.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {nainv: logrel_na_invs \u03a3} {cfgsg: cfgSG \u03a3}\n          `{MachineParameters}.\n\n  Notation D := ((prodO (leibnizO Word) (leibnizO Word)) -n> iPropO \u03a3).\n  Notation R := ((prodO (leibnizO Reg) (leibnizO Reg)) -n> iPropO \u03a3).\n  Implicit Types ww : (prodO (leibnizO Word) (leibnizO Word)).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma IsPtr_spec_determ r dst src regs regs' retv retv' :\n    IsPtr_spec r dst src regs retv ->\n    IsPtr_spec r dst src regs' retv' ->\n    (regs = regs' \u2228 retv = FailedV) \u2227 retv = retv'.\n  Proof.\n    intros Hspec1 Hspec2.\n    inversion Hspec1; inversion Hspec2; subst; simplify_eq; split; auto.\n  Qed.\n\n  Lemma isptr_case (r : prodO (leibnizO Reg) (leibnizO Reg)) (p : Perm)\n        (b e a : Addr) (w w' : Word) (dst : RegName) (src : RegName) (P : D):\n    ftlr_instr r p b e a w w' (IsPtr dst src) P.\n  Proof.\n    intros Hp Hsome HisCorrect Hbae Hi.\n    iIntros \"#IH #Hspec #Hinv #Hreg #Hinva #Hread Hsmap Hown Hs Ha 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_IsPtr with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq. reflexivity. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. destruct Hsome with rr; eauto. }\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n\n    (* we assert that w = w' *)\n    iAssert (\u231cw = w'\u231d)%I as %Heqw.\n    { iDestruct \"Hread\" as \"[Hread _]\". iSpecialize (\"Hread\" with \"HP\"). by iApply interp_eq. }\n    destruct r as [r1 r2]. simpl in *.\n    iDestruct (interp_reg_eq r1 r2 (WCap p b e a) with \"[]\") as %Heq;[iSplit;auto|]. rewrite -!Heq.\n\n    iMod (step_IsPtr _ [SeqCtx] with \"[$Ha' $Hsmap $Hs $Hspec]\") as (retv' regs'') \"(Hs' & Hs & Ha' & Hsmap) /=\";[rewrite Heqw in Hi|..];eauto.\n    { rewrite lookup_insert. eauto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. destruct (decide (PC = rr));[subst;rewrite lookup_insert;eauto|rewrite lookup_insert_ne //].\n      destruct Hsome with rr;eauto. }\n    { solve_ndisj. }\n    iDestruct \"Hs\" as %HSpec'.\n\n    specialize (IsPtr_spec_determ _ _ _ _ _ _ _ HSpec HSpec') as [Hregs <-].\n\n    destruct HSpec; cycle 1.\n    { iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[Ha Ha' HP]\"); [iExists w,w'; iFrame|iModIntro].\n      iNext;iIntros \"_\".\n      iApply wp_value; auto. iIntros; discriminate. }\n    { destruct Hregs as [<-|Hcontr];[|inversion Hcontr].\n      incrementPC_inv; simplify_map_eq.\n      iMod (\"Hcls\" with \"[Ha Ha' HP]\") as \"_\"; [iExists w',w'; iFrame|iModIntro].\n      iApply wp_pure_step_later; auto.\n      iNext;iIntros \"_\".\n      iMod (do_step_pure _ [] with \"[$Hspec $Hs']\") as \"Hs' /=\";auto.\n\n      destruct (decide (PC = dst));simplify_eq;simplify_map_eq.\n      - rewrite !insert_insert. rewrite lookup_insert in H1. inv H1.\n      - rewrite (insert_commute _ _ PC)// insert_insert.\n        iApply (\"IH\" $! ((<[dst:=_]> r1),(<[dst:=_]> r1)) with \"[] [] Hmap Hsmap Hown Hs' Hspec\").\n        { iPureIntro. simpl. intros reg. destruct Hsome with reg;auto.\n          destruct (decide (dst = reg));[subst;rewrite lookup_insert|rewrite !lookup_insert_ne//];eauto. }\n        { simpl. iIntros (rr v1 v2 Hne Hv1s Hv2s).\n          destruct (decide (rr = dst));[subst;rewrite lookup_insert in Hv1s, Hv2s|].\n          - rewrite /interp !fixpoint_interp1_eq /=; simplify_eq; auto.\n          - rewrite !lookup_insert_ne// in Hv1s,Hv2s. simplify_eq.\n            revert Heq; rewrite map_eq' =>Heq.\n            destruct (r1 !! rr) eqn:Hsome';rewrite Hsome' in Hv1s;[|rewrite !fixpoint_interp1_eq;congruence]. inversion Hv1s. subst v1.\n            specialize (Heq rr w). rewrite !lookup_insert_ne// in Heq. apply Heq in Hsome' as Heq'.\n            by iSpecialize (\"Hreg\" $! rr _ _ Hne Hsome' Heq').\n        }\n        { rewrite lookup_insert_ne// lookup_insert in H1. simplify_eq.\n          rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->];iDestruct \"Hinv\" as \"[_ $]\";auto. }\n    }\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_binary/IsPtr_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33807711081161995, "lm_q1q2_score": 0.170359142252619}}
{"text": "Require Import Utf8.\nRequire Events.\nImport String.\nImport Coqlib.\nImport AST Events.\nImport Integers Values.\n\nUnset Elimination Schemes.\n\nDefinition slot : Type := (ident * int)%type.\n\nDefinition slot_dec (x y: slot) : { x = y } + { x \u2260 y } :=\n  EquivDec.prod_eqdec Pos.eq_dec Int.eq_dec x y.\n\nDefinition fence_ident : string := \"__circgen_fence\"%string.\n\nDefinition fence_sig : signature :=\n  {| sig_args := nil ; sig_res := None ; sig_cc := cc_default |}.\n\n(* This axiom states that calling the \u201cvoid fence(void)\u201d external function\npreserves the memory and does not emit any visible event.\n\nThis function is used to delimit the circuit from the input and output sequences. *)\nAxiom fence_sem :\n  \u2200 ge m tr v m',\n    external_functions_sem fence_ident fence_sig ge nil m tr v m' \u2192\n    tr = E0 \u2227 m' = m.\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/CircIO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.1702306688041734}}
{"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(** Register allocation by external oracle and a posteriori validation. *)\n\nRequire Import FSets FSetAVLplus.\nRequire Import Coqlib Ordered Maps Errors Integers Floats.\nRequire Import AST Lattice Kildall Memdata.\nRequire Archi.\nRequire Import Op Registers RTL Locations Conventions RTLtyping LTL.\n\n(** The validation algorithm used here is described in\n  \"Validating register allocation and spilling\",\n  by Silvain Rideau and Xavier Leroy,\n  in Compiler Construction (CC 2010), LNCS 6011, Springer, 2010. *)\n\n(** * Structural checks *)\n\n(** As a first pass, we check the LTL code returned by the external oracle\n  against the original RTL code for structural conformance.\n  Each RTL instruction was transformed into a LTL basic block whose\n  shape must agree with the RTL instruction.  For example, if the RTL\n  instruction is [Istore(Mint32, addr, args, src, s)], the LTL basic block\n  must be of the following shape:\n- zero, one or several \"move\" instructions\n- a store instruction [Lstore(Mint32, addr, args', src')]\n- a [Lbranch s] instruction.\n\n  The [block_shape] type below describes all possible cases of structural\n  maching between an RTL instruction and an LTL basic block.\n*)\n\nDefinition move := (loc * loc)%type.\nDefinition moves := list move.\n\nInductive block_shape: Type :=\n  | BSnop (mv: moves) (s: node)\n  | BSmove (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSmakelong (src1 src2: reg) (dst: reg) (mv: moves) (s: node)\n  | BSlowlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BShighlong (src: reg) (dst: reg) (mv: moves) (s: node)\n  | BSop (op: operation) (args: list reg) (res: reg)\n         (mv1: moves) (args': list mreg) (res': mreg)\n         (mv2: moves) (s: node)\n  | BSopdead (op: operation) (args: list reg) (res: reg)\n         (mv: moves) (s: node)\n  | BSload (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSloaddead (chunk: memory_chunk) (addr: addressing) (args: list reg) (dst: reg)\n         (mv: moves) (s: node)\n  | BSload2 (addr1 addr2: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args1': list mreg) (dst1': mreg)\n         (mv2: moves) (args2': list mreg) (dst2': mreg)\n         (mv3: moves) (s: node)\n  | BSload2_1 (addr: addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSload2_2 (addr addr': addressing) (args: list reg) (dst: reg)\n         (mv1: moves) (args': list mreg) (dst': mreg)\n         (mv2: moves) (s: node)\n  | BSstore (chunk: memory_chunk) (addr: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args': list mreg) (src': mreg)\n         (s: node)\n  | BSstore2 (addr1 addr2: addressing) (args: list reg) (src: reg)\n         (mv1: moves) (args1': list mreg) (src1': mreg)\n         (mv2: moves) (args2': list mreg) (src2': mreg)\n         (s: node)\n  | BScall (sg: signature) (ros: reg + ident) (args: list reg) (res: reg)\n         (mv1: moves) (ros': mreg + ident) (mv2: moves) (s: node)\n  | BStailcall (sg: signature) (ros: reg + ident) (args: list reg)\n         (mv1: moves) (ros': mreg + ident)\n  | BSbuiltin (ef: external_function)\n         (args: list (builtin_arg reg)) (res: builtin_res reg)\n         (mv1: moves) (args': list (builtin_arg loc)) (res': builtin_res mreg)\n         (mv2: moves) (s: node)\n  | BScond (cond: condition) (args: list reg)\n         (mv: moves) (args': list mreg) (s1 s2: node)\n  | BSjumptable (arg: reg)\n         (mv: moves) (arg': mreg) (tbl: list node)\n  | BSreturn (arg: option reg)\n         (mv: moves).\n\n(** Classify operations into moves, 64-bit split integer operations, and other\n  arithmetic/logical operations. *)\n\nInductive operation_kind {A: Type}: operation -> list A -> Type :=\n  | operation_Omove: forall arg, operation_kind Omove (arg :: nil)\n  | operation_Omakelong: forall arg1 arg2, operation_kind Omakelong (arg1 :: arg2 :: nil)\n  | operation_Olowlong: forall arg, operation_kind Olowlong (arg :: nil)\n  | operation_Ohighlong: forall arg, operation_kind Ohighlong (arg :: nil)\n  | operation_other: forall op args, operation_kind op args.\n\nDefinition classify_operation {A: Type} (op: operation) (args: list A) : operation_kind op args :=\n  match op, args with\n  | Omove, arg::nil => operation_Omove arg\n  | Omakelong, arg1::arg2::nil => operation_Omakelong arg1 arg2\n  | Olowlong, arg::nil => operation_Olowlong arg\n  | Ohighlong, arg::nil => operation_Ohighlong arg\n  | op, args => operation_other op args\n  end.\n\n(** Extract the move instructions at the beginning of block [b].\n  Return the list of moves and the suffix of [b] after the moves. *)\n\nFixpoint extract_moves (accu: moves) (b: bblock) {struct b} : moves * bblock :=\n  match b with\n  | Lgetstack sl ofs ty dst :: b' =>\n      extract_moves ((S sl ofs ty, R dst) :: accu) b'\n  | Lsetstack src sl ofs ty :: b' =>\n      extract_moves ((R src, S sl ofs ty) :: accu) b'\n  | Lop op args res :: b' =>\n      match is_move_operation op args with\n      | Some arg =>\n          extract_moves ((R arg, R res) :: accu) b'\n      | None =>\n          (List.rev accu, b)\n      end\n  | _ =>\n      (List.rev accu, b)\n  end.\n\nDefinition check_succ (s: node) (b: LTL.bblock) : bool :=\n  match b with\n  | Lbranch s' :: _ => peq s s'\n  | _ => false\n  end.\n\nNotation \"'do' X <- A ; B\" := (match A with Some X => B | None => None end)\n         (at level 200, X ident, A at level 100, B at level 200)\n         : option_monad_scope.\n\nNotation \"'assertion' A ; B\" := (if A then B else None)\n         (at level 200, A at level 100, B at level 200)\n         : option_monad_scope.\n\nLocal Open Scope option_monad_scope.\n\n(** Check RTL instruction [i] against LTL basic block [b].\n  On success, return [Some] with a [block_shape] describing the correspondence.\n  On error, return [None]. *)\n\nDefinition pair_Iop_block (op: operation) (args: list reg) (res: reg) (s: node) (b: LTL.bblock) :=\n  let (mv1, b1) := extract_moves nil b in\n  match b1 with\n  | Lop op' args' res' :: b2 =>\n      let (mv2, b3) := extract_moves nil b2 in\n      assertion (eq_operation op op');\n      assertion (check_succ s b3);\n      Some(BSop op args res mv1 args' res' mv2 s)\n  | _ =>\n      assertion (check_succ s b1);\n      Some(BSopdead op args res mv1 s)\n  end.\n\nDefinition pair_instr_block\n               (i: RTL.instruction) (b: LTL.bblock) : option block_shape :=\n  match i with\n  | Inop s =>\n      let (mv, b1) := extract_moves nil b in\n      assertion (check_succ s b1); Some(BSnop mv s)\n  | Iop op args res s =>\n      match classify_operation op args with\n      | operation_Omove arg =>\n          let (mv, b1) := extract_moves nil b in\n          assertion (check_succ s b1); Some(BSmove arg res mv s)\n      | operation_Omakelong arg1 arg2 =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BSmakelong arg1 arg2 res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_Olowlong arg =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BSlowlong arg res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_Ohighlong arg =>\n          if Archi.splitlong then\n           (let (mv, b1) := extract_moves nil b in\n            assertion (check_succ s b1); Some(BShighlong arg res mv s))\n          else\n            pair_Iop_block op args res s b\n      | operation_other _ _ =>\n          pair_Iop_block op args res s b\n      end\n  | Iload chunk addr args dst s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lload chunk' addr' args' dst' :: b2 =>\n          if chunk_eq chunk Mint64 && Archi.splitlong then\n            assertion (chunk_eq chunk' Mint32);\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lload chunk'' addr'' args'' dst'' :: b4 =>\n                let (mv3, b5) := extract_moves nil b4 in\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr''));\n                assertion (check_succ s b5);\n                Some(BSload2 addr addr'' args dst mv1 args' dst' mv2 args'' dst'' mv3 s)\n            | _ =>\n                assertion (check_succ s b3);\n                if (eq_addressing addr addr') then\n                  Some(BSload2_1 addr args dst mv1 args' dst' mv2 s)\n                else\n                 (assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr'));\n                  Some(BSload2_2 addr addr' args dst mv1 args' dst' mv2 s))\n            end\n          else (\n            let (mv2, b3) := extract_moves nil b2 in\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b3);\n            Some(BSload chunk addr args dst mv1 args' dst' mv2 s))\n      | _ =>\n          assertion (check_succ s b1);\n          Some(BSloaddead chunk addr args dst mv1 s)\n      end\n  | Istore chunk addr args src s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lstore chunk' addr' args' src' :: b2 =>\n          if chunk_eq chunk Mint64 && Archi.splitlong then\n            let (mv2, b3) := extract_moves nil b2 in\n            match b3 with\n            | Lstore chunk'' addr'' args'' src'' :: b4 =>\n                assertion (chunk_eq chunk' Mint32);\n                assertion (chunk_eq chunk'' Mint32);\n                assertion (eq_addressing addr addr');\n                assertion (option_eq eq_addressing (offset_addressing addr 4) (Some addr''));\n                assertion (check_succ s b4);\n                Some(BSstore2 addr addr'' args src mv1 args' src' mv2 args'' src'' s)\n            | _ => None\n            end\n          else (\n            assertion (chunk_eq chunk chunk');\n            assertion (eq_addressing addr addr');\n            assertion (check_succ s b2);\n            Some(BSstore chunk addr args src mv1 args' src' s))\n      | _ => None\n      end\n  | Icall sg ros args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcall sg' ros' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (signature_eq sg sg');\n          assertion (check_succ s b3);\n          Some(BScall sg ros args res mv1 ros' mv2 s)\n      | _ => None\n      end\n  | Itailcall sg ros args =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ltailcall sg' ros' :: b2 =>\n          assertion (signature_eq sg sg');\n          Some(BStailcall sg ros args mv1 ros')\n      | _ => None\n      end\n  | Ibuiltin ef args res s =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lbuiltin ef' args' res' :: b2 =>\n          let (mv2, b3) := extract_moves nil b2 in\n          assertion (external_function_eq ef ef');\n          assertion (check_succ s b3);\n          Some(BSbuiltin ef args res mv1 args' res' mv2 s)\n      | _ => None\n      end\n  | Icond cond args s1 s2 =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lcond cond' args' s1' s2' :: b2 =>\n          assertion (eq_condition cond cond');\n          assertion (peq s1 s1');\n          assertion (peq s2 s2');\n          Some(BScond cond args mv1 args' s1 s2)\n      | _ => None\n      end\n  | Ijumptable arg tbl =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Ljumptable arg' tbl' :: b2 =>\n          assertion (list_eq_dec peq tbl tbl');\n          Some(BSjumptable arg mv1 arg' tbl)\n      | _ => None\n      end\n  | Ireturn arg =>\n      let (mv1, b1) := extract_moves nil b in\n      match b1 with\n      | Lreturn :: b2 => Some(BSreturn arg mv1)\n      | _ => None\n      end\n  end.\n\n(** Check all instructions of the RTL function [f1] against the corresponding\n  basic blocks of LTL function [f2].  Return a map from CFG nodes to\n  [block_shape] info. *)\n\nDefinition pair_codes (f1: RTL.function) (f2: LTL.function) : PTree.t block_shape :=\n  PTree.combine\n    (fun opti optb => do i <- opti; do b <- optb; pair_instr_block i b)\n    (RTL.fn_code f1) (LTL.fn_code f2).\n\n(** Check the entry point code of the LTL function [f2].  It must be\n  a sequence of moves that branches to the same node as the entry point\n  of RTL function [f1]. *)\n\nDefinition pair_entrypoints (f1: RTL.function) (f2: LTL.function) : option moves :=\n  do b <- (LTL.fn_code f2)!(LTL.fn_entrypoint f2);\n  let (mv, b1) := extract_moves nil b in\n  assertion (check_succ (RTL.fn_entrypoint f1) b1);\n  Some mv.\n\n(** * Representing sets of equations between RTL registers and LTL locations. *)\n\n(** The Rideau-Leroy validation algorithm manipulates sets of equations of\n  the form [pseudoreg = location [kind]], meaning:\n- if [kind = Full], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the value of [pseudoreg] in the original\n  RTL code;\n- if [kind = Low], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the low 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code;\n- if [kind = High], the value of [location] in the generated LTL code is\n  the same as (or more defined than) the high 32 bits of the 64-bit\n  integer value of [pseudoreg] in the original RTL code.\n*)\n\nInductive equation_kind : Type := Full | Low | High.\n\nRecord equation := Eq {\n  ekind: equation_kind;\n  ereg: reg;\n  eloc: loc\n}.\n\n(** We use AVL finite sets to represent sets of equations.  Therefore, we need\n  total orders over equations and their components. *)\n\nModule IndexedEqKind <: INDEXED_TYPE.\n  Definition t := equation_kind.\n  Definition index (x: t) :=\n    match x with Full => 1%positive | Low => 2%positive | High => 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 (x y: t) : {x=y} + {x<>y}.\n  Proof. decide equality. Defined.\nEnd IndexedEqKind.\n\nModule OrderedEqKind := OrderedIndexed(IndexedEqKind).\n\n(** This is an order over equations that is lexicographic on [ereg], then\n  [eloc], then [ekind]. *)\n\nModule OrderedEquation <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    (OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H.\n    destruct H0. left; eapply Plt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H.\n    destruct H0. auto.\n    destruct H0. right; split; auto.\n    intuition.\n    left; eapply OrderedLoc.lt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim Plt_strict; eauto.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedPositive.compare (ereg x) (ereg y)).\n  - apply LT. red; auto.\n  - destruct (OrderedLoc.compare (eloc x) (eloc y)).\n    + apply LT. red; auto.\n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red.\n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec (x y: t) : {x = y} + {x <> y}.\n  Proof.\n    intros. decide equality.\n    apply Loc.eq.\n    apply peq.\n    apply IndexedEqKind.eq.\n  Defined.\nEnd OrderedEquation.\n\n(** This is an alternate order over equations that is lexicgraphic on\n  [eloc], then [ereg], then [ekind]. *)\n\nModule OrderedEquation' <: OrderedType.\n  Definition t := equation.\n  Definition eq (x y: t) := x = y.\n  Definition lt (x y: t) :=\n    OrderedLoc.lt (eloc x) (eloc y) \\/ (eloc x = eloc y /\\\n    (Plt (ereg x) (ereg y) \\/ (ereg x = ereg y /\\\n    OrderedEqKind.lt (ekind x) (ekind y)))).\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 H.\n    destruct H0. left; eapply OrderedLoc.lt_trans; eauto.\n    destruct H0. rewrite <- H0. auto.\n    destruct H. rewrite H.\n    destruct H0. auto.\n    destruct H0. right; split; auto.\n    intuition.\n    left; eapply Plt_trans; eauto.\n    left; congruence.\n    left; congruence.\n    right; split. congruence. eapply OrderedEqKind.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. intuition.\n    eelim OrderedLoc.lt_not_eq; eauto. red; auto.\n    eelim Plt_strict; eauto.\n    eelim OrderedEqKind.lt_not_eq; eauto. red; auto.\n  Qed.\n  Definition compare : forall x y : t, Compare lt eq x y.\n  Proof.\n    intros.\n    destruct (OrderedLoc.compare (eloc x) (eloc y)).\n  - apply LT. red; auto.\n  - destruct (OrderedPositive.compare (ereg x) (ereg y)).\n    + apply LT. red; auto.\n    + destruct (OrderedEqKind.compare (ekind x) (ekind y)).\n      * apply LT. red; auto.\n      * apply EQ. red in e; red in e0; red in e1; red.\n        destruct x; destruct y; simpl in *; congruence.\n      * apply GT. red; auto.\n   + apply GT. red; auto.\n  - apply GT. red; auto.\n  Defined.\n  Definition eq_dec: forall (x y: t), {x = y} + {x <> y} := OrderedEquation.eq_dec.\nEnd OrderedEquation'.\n\nModule EqSet := FSetAVLplus.Make(OrderedEquation).\nModule EqSet2 := FSetAVLplus.Make(OrderedEquation').\n\n(** We use a redundant representation for sets of equations, comprising\n  two AVL finite sets, containing the same elements, but ordered along\n  the two orders defined above.  Playing on properties of lexicographic\n  orders, this redundant representation enables us to quickly find\n  all equations involving a given RTL pseudoregister, or all equations\n  involving a given LTL location or overlapping location. *)\n\nRecord eqs := mkeqs {\n  eqs1 :> EqSet.t;\n  eqs2 : EqSet2.t;\n  eqs_same: forall q, EqSet2.In q eqs2 <-> EqSet.In q eqs1\n}.\n\n(** * Operations on sets of equations *)\n\n(** The empty set of equations. *)\n\nProgram Definition empty_eqs := mkeqs EqSet.empty EqSet2.empty _.\nNext Obligation.\n  split; intros. eelim EqSet2.empty_1; eauto. eelim EqSet.empty_1; eauto.\nQed.\n\n(** Adding or removing an equation from a set. *)\n\nProgram Definition add_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.add q (eqs1 e)) (EqSet2.add q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0).\n  apply EqSet.add_1; auto.\n  apply EqSet.add_2. apply (eqs_same e). apply EqSet2.add_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0).\n  apply EqSet2.add_1; auto.\n  apply EqSet2.add_2. apply (eqs_same e). apply EqSet.add_3 with q; auto.\nQed.\n\nProgram Definition remove_equation (q: equation) (e: eqs) :=\n  mkeqs (EqSet.remove q (eqs1 e)) (EqSet2.remove q (eqs2 e)) _.\nNext Obligation.\n  split; intros.\n  destruct (OrderedEquation'.eq_dec q q0).\n  eelim EqSet2.remove_1; eauto.\n  apply EqSet.remove_2; auto. apply (eqs_same e). apply EqSet2.remove_3 with q; auto.\n  destruct (OrderedEquation.eq_dec q q0).\n  eelim EqSet.remove_1; eauto.\n  apply EqSet2.remove_2; auto. apply (eqs_same e). apply EqSet.remove_3 with q; auto.\nQed.\n\n(** [reg_unconstrained r e] is true if [e] contains no equations involving\n  the RTL pseudoregister [r].  In other words, all equations [r' = l [kind]]\n  in [e] are such that [r' <> r]. *)\n\nDefinition select_reg_l (r: reg) (q: equation) := Pos.leb r (ereg q).\nDefinition select_reg_h (r: reg) (q: equation) := Pos.leb (ereg q) r.\n\nDefinition reg_unconstrained (r: reg) (e: eqs) : bool :=\n  negb (EqSet.mem_between (select_reg_l r) (select_reg_h r) (eqs1 e)).\n\n(** [loc_unconstrained l e] is true if [e] contains no equations involving\n  the LTL location [l] or a location that partially overlaps with [l].\n  In other words, all equations [r = l' [kind]] in [e] are such that\n  [Loc.diff l' l]. *)\n\nDefinition select_loc_l (l: loc) :=\n  let lb := OrderedLoc.diff_low_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lb with LT _ => false | _ => true end.\nDefinition select_loc_h (l: loc) :=\n  let lh := OrderedLoc.diff_high_bound l in\n  fun (q: equation) => match OrderedLoc.compare (eloc q) lh with GT _ => false | _ => true end.\n\nDefinition loc_unconstrained (l: loc) (e: eqs) : bool :=\n  negb (EqSet2.mem_between (select_loc_l l) (select_loc_h l) (eqs2 e)).\n\nDefinition reg_loc_unconstrained (r: reg) (l: loc) (e: eqs) : bool :=\n  reg_unconstrained r e && loc_unconstrained l e.\n\n(** [subst_reg r1 r2 e] simulates the effect of assigning [r2] to [r1] on [e].\n  All equations of the form [r1 = l [kind]] are replaced by [r2 = l [kind]].\n*)\n\nDefinition subst_reg (r1 r2: reg) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e => add_equation (Eq (ekind q) r2 (eloc q)) (remove_equation q e))\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_reg_kind r1 k1 r2 k2 e] simulates the effect of assigning\n  the [k2] part of [r2] to the [k1] part of [r1] on [e].\n  All equations of the form [r1 = l [k1]] are replaced by [r2 = l [k2]].\n*)\n\nDefinition subst_reg_kind (r1: reg) (k1: equation_kind) (r2: reg) (k2: equation_kind) (e: eqs) : eqs :=\n  EqSet.fold\n    (fun q e =>\n      if IndexedEqKind.eq (ekind q) k1\n      then add_equation (Eq k2 r2 (eloc q)) (remove_equation q e)\n      else e)\n    (EqSet.elements_between (select_reg_l r1) (select_reg_h r1) (eqs1 e))\n    e.\n\n(** [subst_loc l1 l2 e] simulates the effect of assigning [l2] to [l1] on [e].\n  All equations of the form [r = l1 [kind]] are replaced by [r = l2 [kind]].\n  Return [None] if [e] contains an equation of the form [r = l] with [l]\n  partially overlapping [l1].\n*)\n\nDefinition subst_loc (l1 l2: loc) (e: eqs) : option eqs :=\n  EqSet2.fold\n    (fun q opte =>\n      match opte with\n      | None => None\n      | Some e =>\n          if Loc.eq l1 (eloc q) then\n            Some (add_equation (Eq (ekind q) (ereg q) l2) (remove_equation q e))\n          else\n            None\n      end)\n     (EqSet2.elements_between (select_loc_l l1) (select_loc_h l1) (eqs2 e))\n     (Some e).\n\n(** [loc_type_compat env l e] checks that for all equations [r = l] in [e],\n  the type [env r] of [r] is compatible with the type of [l]. *)\n\nDefinition sel_type (k: equation_kind) (ty: typ) : typ :=\n  match k with\n  | Full => ty\n  | Low | High => Tint\n  end.\n\nDefinition loc_type_compat (env: regenv) (l: loc) (e: eqs) : bool :=\n  EqSet2.for_all_between\n    (fun q => subtype (sel_type (ekind q) (env (ereg q))) (Loc.type l))\n    (select_loc_l l) (select_loc_h l) (eqs2 e).\n\n(** [add_equations [r1...rN] [m1...mN] e] adds to [e] the [N] equations\n    [ri = R mi [Full]].  Return [None] if the two lists have different lengths.\n*)\n\nFixpoint add_equations (rl: list reg) (ml: list mreg) (e: eqs) : option eqs :=\n  match rl, ml with\n  | nil, nil => Some e\n  | r1 :: rl, m1 :: ml => add_equations rl ml (add_equation (Eq Full r1 (R m1)) e)\n  | _, _ => None\n  end.\n\n(** [add_equations_args] is similar but additionally handles the splitting\n  of pseudoregisters of type [Tlong] in two locations containing the\n  two 32-bit halves of the 64-bit integer. *)\n\nFunction add_equations_args (rl: list reg) (tyl: list typ) (ll: list (rpair loc)) (e: eqs) : option eqs :=\n  match rl, tyl, ll with\n  | nil, nil, nil => Some e\n  | r1 :: rl, ty :: tyl, One l1 :: ll =>\n      add_equations_args rl tyl ll (add_equation (Eq Full r1 l1) e)\n  | r1 :: rl, Tlong :: tyl, Twolong l1 l2 :: ll =>\n      if Archi.splitlong then\n        add_equations_args rl tyl ll (add_equation (Eq Low r1 l2) (add_equation (Eq High r1 l1) e))\n      else None\n  | _, _, _ => None\n  end.\n\n(** [add_equations_res] is similar but is specialized to the case where\n  there is only one pseudo-register. *)\n\nFunction add_equations_res (r: reg) (oty: option typ) (p: rpair mreg) (e: eqs) : option eqs :=\n  match p, oty with\n  | One mr, _ =>\n      Some (add_equation (Eq Full r (R mr)) e)\n  | Twolong mr1 mr2, Some Tlong =>\n      if Archi.splitlong then\n        Some (add_equation (Eq Low r (R mr2)) (add_equation (Eq High r (R mr1)) e))\n      else None\n  | _, _ =>\n      None\n  end.\n\n(** [remove_equations_res] is similar to [add_equations_res] but removes\n  equations instead of adding them. *)\n\nFunction remove_equations_res (r: reg) (p: rpair mreg) (e: eqs) : option eqs :=\n  match p with\n  | One mr =>\n      Some (remove_equation (Eq Full r (R mr)) e)\n  | Twolong mr1 mr2 =>\n      if mreg_eq mr2 mr1\n      then None\n      else Some (remove_equation (Eq Low r (R mr2)) (remove_equation (Eq High r (R mr1)) e))\n  end.\n\n(** [add_equations_ros] adds an equation, if needed, between an optional\n  pseudoregister and an optional machine register.  It is used for the\n  function argument of the [Icall] and [Itailcall] instructions. *)\n\nDefinition add_equation_ros (ros: reg + ident) (ros': mreg + ident) (e: eqs) : option eqs :=\n  match ros, ros' with\n  | inl r, inl mr => Some(add_equation (Eq Full r (R mr)) e)\n  | inr id, inr id' => assertion (ident_eq id id'); Some e\n  | _, _ => None\n  end.\n\n(** [add_equations_builtin_arg] adds the needed equations for arguments\n    to builtin functions. *)\n\nFixpoint add_equations_builtin_arg\n     (env: regenv) (arg: builtin_arg reg) (arg': builtin_arg loc) (e: eqs) : option eqs :=\n  match arg, arg' with\n  | BA r, BA l =>\n      Some (add_equation (Eq Full r l) e)\n  | BA r, BA_splitlong (BA lhi) (BA llo) =>\n      assertion (typ_eq (env r) Tlong);\n      assertion (Archi.splitlong);\n      Some (add_equation (Eq Low r llo) (add_equation (Eq High r lhi) e))\n  | BA_int n, BA_int n' =>\n      assertion (Int.eq_dec n n'); Some e\n  | BA_long n, BA_long n' =>\n      assertion (Int64.eq_dec n n'); Some e\n  | BA_float f, BA_float f' =>\n      assertion (Float.eq_dec f f'); Some e\n  | BA_single f, BA_single f' =>\n      assertion (Float32.eq_dec f f'); Some e\n  | BA_loadstack chunk ofs, BA_loadstack chunk' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_addrstack ofs, BA_addrstack ofs' =>\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_loadglobal chunk id ofs, BA_loadglobal chunk' id' ofs' =>\n      assertion (chunk_eq chunk chunk');\n      assertion (ident_eq id id');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_addrglobal id ofs, BA_addrglobal id' ofs' =>\n      assertion (ident_eq id id');\n      assertion (Ptrofs.eq_dec ofs ofs');\n      Some e\n  | BA_splitlong hi lo, BA_splitlong hi' lo' =>\n      do e1 <- add_equations_builtin_arg env hi hi' e;\n      add_equations_builtin_arg env lo lo' e1\n  | _, _ =>\n      None\n  end.\n\nFixpoint add_equations_builtin_args\n   (env: regenv) (args: list (builtin_arg reg))\n   (args': list (builtin_arg loc)) (e: eqs) : option eqs :=\n  match args, args' with\n  | nil, nil => Some e\n  | a1 :: al, a1' :: al' =>\n      do e1 <- add_equations_builtin_arg env a1 a1' e;\n      add_equations_builtin_args env al al' e1\n  | _, _ => None\n  end.\n\n(** For [EF_debug] builtins, some arguments can be removed. *)\n\nFixpoint add_equations_debug_args\n   (env: regenv) (args: list (builtin_arg reg))\n   (args': list (builtin_arg loc)) (e: eqs) : option eqs :=\n  match args, args' with\n  | _, nil => Some e\n  | a1 :: al, a1' :: al' =>\n      match add_equations_builtin_arg env a1 a1' e with\n      | None => add_equations_debug_args env al args' e\n      | Some e1 => add_equations_debug_args env al al' e1\n      end\n  | _, _ => None\n  end.\n\n(** Checking of the result of a builtin *)\n\nDefinition remove_equations_builtin_res\n    (env: regenv) (res: builtin_res reg) (res': builtin_res mreg) (e: eqs) : option eqs :=\n  match res, res' with\n  | BR r, BR r' => Some (remove_equation (Eq Full r (R r')) e)\n  | BR r, BR_splitlong (BR rhi) (BR rlo) =>\n      assertion (typ_eq (env r) Tlong);\n      if mreg_eq rhi rlo then None else\n        Some (remove_equation (Eq Low r (R rlo))\n                (remove_equation (Eq High r (R rhi)) e))\n  | BR_none, BR_none => Some e\n  | _, _ => None\n  end.\n\n(** [can_undef ml] returns true if all machine registers in [ml] are\n  unconstrained and can harmlessly be undefined. *)\n\nFixpoint can_undef (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml => loc_unconstrained (R m1) e && can_undef ml e\n  end.\n\nFixpoint can_undef_except (l: loc) (ml: list mreg) (e: eqs) : bool :=\n  match ml with\n  | nil => true\n  | m1 :: ml =>\n      (Loc.eq l (R m1) || loc_unconstrained (R m1) e) && can_undef_except l ml e\n  end.\n\n(** [no_caller_saves e] returns [e] if all caller-save locations are\n  unconstrained in [e].  In other words, [e] contains no equations\n  involving a caller-save register or [Outgoing] stack slot. *)\n\nDefinition no_caller_saves (e: eqs) : bool :=\n  EqSet.for_all\n   (fun eq =>\n     match eloc eq with\n       | R r => is_callee_save r\n       | S Outgoing _ _ => false\n       | S _ _ _ => true\n       end)\n    e.\n\n(** [compat_left r l e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l [Full]]. *)\n\nDefinition compat_left (r: reg) (l: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | Full => Loc.eq l (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [compat_left2 r l1 l2 e] returns true if all equations in [e] that involve\n    [r] are of the form [r = l1 [High]] or [r = l2 [Low]]. *)\n\nDefinition compat_left2 (r: reg) (l1 l2: loc) (e: eqs) : bool :=\n  EqSet.for_all_between\n    (fun q =>\n        match ekind q with\n        | High => Loc.eq l1 (eloc q)\n        | Low => Loc.eq l2 (eloc q)\n        | _ => false\n        end)\n    (select_reg_l r) (select_reg_h r)\n    (eqs1 e).\n\n(** [ros_compatible_tailcall ros] returns true if [ros] is a function\n  name or a caller-save register.  This is used to check [Itailcall]\n  instructions. *)\n\nDefinition ros_compatible_tailcall (ros: mreg + ident) : bool :=\n  match ros with\n  | inl r => negb (is_callee_save r)\n  | inr id => true\n  end.\n\n(** * The validator *)\n\nDefinition destroyed_by_move (src dst: loc) :=\n  match src, dst with\n  | S sl ofs ty, _ => destroyed_by_getstack sl\n  | _, S sl ofs ty => destroyed_by_setstack ty\n  | _, _ => destroyed_by_op Omove\n  end.\n\nDefinition well_typed_move (env: regenv) (dst: loc) (e: eqs) : bool :=\n  match dst with\n  | R r => true\n  | S sl ofs ty => loc_type_compat env dst e\n  end.\n\n(** Simulate the effect of a sequence of moves [mv] on a set of\n  equations [e].  The set [e] is the equations that must hold\n  after the sequence of moves.  Return the set of equations that\n  must hold before the sequence of moves.  Return [None] if the\n  set of equations [e] cannot hold after the sequence of moves. *)\n\nFixpoint track_moves (env: regenv) (mv: moves) (e: eqs) : option eqs :=\n  match mv with\n  | nil => Some e\n  | (src, dst) :: mv =>\n      do e1 <- track_moves env mv e;\n      assertion (can_undef_except dst (destroyed_by_move src dst)) e1;\n      assertion (well_typed_move env dst e1);\n      subst_loc dst src e1\n  end.\n\n(** [transfer_use_def args res args' res' undefs e] returns the set\n  of equations that must hold \"before\" in order for the equations [e]\n  to hold \"after\" the execution of RTL and LTL code of the following form:\n<<\n                RTL                            LTL\n         use pseudoregs args            use machine registers args'\n         define pseudoreg res           undefine machine registers undef\n                                        define machine register res'\n>>\n  As usual, [None] is returned if the equations [e] cannot hold after\n  this execution.\n*)\n\nDefinition transfer_use_def (args: list reg) (res: reg) (args': list mreg) (res': mreg)\n                            (undefs: list mreg) (e: eqs) : option eqs :=\n  let e1 := remove_equation (Eq Full res (R res')) e in\n  assertion (reg_loc_unconstrained res (R res') e1);\n  assertion (can_undef undefs e1);\n  add_equations args args' e1.\n\nDefinition kind_first_word := if Archi.big_endian then High else Low.\nDefinition kind_second_word := if Archi.big_endian then Low else High.\n\n(** The core transfer function.  It takes a set [e] of equations that must\n  hold \"after\" and a block shape [shape] representing a matching pair\n  of an RTL instruction and an LTL basic block.  It returns the set of\n  equations that must hold \"before\" these instructions, or [None] if\n  impossible. *)\n\nDefinition transfer_aux (f: RTL.function) (env: regenv)\n                        (shape: block_shape) (e: eqs) : option eqs :=\n  match shape with\n  | BSnop mv s =>\n      track_moves env mv e\n  | BSmove src dst mv s =>\n      track_moves env mv (subst_reg dst src e)\n  | BSmakelong src1 src2 dst mv s =>\n      let e1 := subst_reg_kind dst High src1 Full e in\n      let e2 := subst_reg_kind dst Low src2 Full e1 in\n      assertion (reg_unconstrained dst e2);\n      track_moves env mv e2\n  | BSlowlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src Low e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BShighlong src dst mv s =>\n      let e1 := subst_reg_kind dst Full src High e in\n      assertion (reg_unconstrained dst e1);\n      track_moves env mv e1\n  | BSop op args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args res args' res' (destroyed_by_op op) e1;\n      track_moves env mv1 e2\n  | BSopdead op args res mv s =>\n      assertion (reg_unconstrained res e);\n      track_moves env mv e\n  | BSload chunk addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- transfer_use_def args dst args' dst' (destroyed_by_load chunk addr) e1;\n      track_moves env mv1 e2\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s =>\n      do e1 <- track_moves env mv3 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst2')) e1 in\n      assertion (loc_unconstrained (R dst2') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args2' e2;\n      do e4 <- track_moves env mv2 e3;\n      let e5 := remove_equation (Eq kind_first_word dst (R dst1')) e4 in\n      assertion (loc_unconstrained (R dst1') e5);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e5);\n      assertion (reg_unconstrained dst e5);\n      do e6 <- add_equations args args1' e5;\n      track_moves env mv1 e6\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_first_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr) e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      let e2 := remove_equation (Eq kind_second_word dst (R dst')) e1 in\n      assertion (reg_loc_unconstrained dst (R dst') e2);\n      assertion (can_undef (destroyed_by_load Mint32 addr') e2);\n      do e3 <- add_equations args args' e2;\n      track_moves env mv1 e3\n  | BSloaddead chunk addr args dst mv s =>\n      assertion (reg_unconstrained dst e);\n      track_moves env mv e\n  | BSstore chunk addr args src mv args' src' s =>\n      assertion (can_undef (destroyed_by_store chunk addr) e);\n      do e1 <- add_equations (src :: args) (src' :: args') e;\n      track_moves env mv e1\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s =>\n      assertion (can_undef (destroyed_by_store Mint32 addr') e);\n      do e1 <- add_equations args args2'\n                  (add_equation (Eq kind_second_word src (R src2')) e);\n      do e2 <- track_moves env mv2 e1;\n      assertion (can_undef (destroyed_by_store Mint32 addr) e2);\n      do e3 <- add_equations args args1'\n                  (add_equation (Eq kind_first_word src (R src1')) e2);\n      track_moves env mv1 e3\n  | BScall sg ros args res mv1 ros' mv2 s =>\n      let args' := loc_arguments sg in\n      let res' := loc_result sg in\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_res res res' e1;\n      assertion (forallb (fun l => reg_loc_unconstrained res l e2)\n                         (map R (regs_of_rpair res')));\n      assertion (no_caller_saves e2);\n      do e3 <- add_equation_ros ros ros' e2;\n      do e4 <- add_equations_args args (sig_args sg) args' e3;\n      track_moves env mv1 e4\n  | BStailcall sg ros args mv1 ros' =>\n      let args' := loc_arguments sg in\n      assertion (tailcall_is_possible sg);\n      assertion (opt_typ_eq sg.(sig_res) f.(RTL.fn_sig).(sig_res));\n      assertion (ros_compatible_tailcall ros');\n      do e1 <- add_equation_ros ros ros' empty_eqs;\n      do e2 <- add_equations_args args (sig_args sg) args' e1;\n      track_moves env mv1 e2\n  | BSbuiltin ef args res mv1 args' res' mv2 s =>\n      do e1 <- track_moves env mv2 e;\n      do e2 <- remove_equations_builtin_res env res res' e1;\n      assertion (forallb (fun r => reg_unconstrained r e2)\n                         (params_of_builtin_res res));\n      assertion (forallb (fun mr => loc_unconstrained (R mr) e2)\n                         (params_of_builtin_res res'));\n      assertion (can_undef (destroyed_by_builtin ef) e2);\n      do e3 <-\n        match ef with\n        | EF_debug _ _ _ => add_equations_debug_args env args args' e2\n        | _              => add_equations_builtin_args env args args' e2\n        end;\n      track_moves env mv1 e3\n  | BScond cond args mv args' s1 s2 =>\n      assertion (can_undef (destroyed_by_cond cond) e);\n      do e1 <- add_equations args args' e;\n      track_moves env mv e1\n  | BSjumptable arg mv arg' tbl =>\n      assertion (can_undef destroyed_by_jumptable e);\n      track_moves env mv (add_equation (Eq Full arg (R arg')) e)\n  | BSreturn None mv =>\n      track_moves env mv empty_eqs\n  | BSreturn (Some arg) mv =>\n      let arg' := loc_result (RTL.fn_sig f) in\n      do e1 <- add_equations_res arg (sig_res (RTL.fn_sig f)) arg' empty_eqs;\n      track_moves env mv e1\n  end.\n\n(** The main transfer function for the dataflow analysis.  Like [transfer_aux],\n  it infers the equations that must hold \"before\" as a function of the\n  equations that must hold \"after\".  It also handles error propagation\n  and reporting. *)\n\nDefinition transfer (f: RTL.function) (env: regenv) (shapes: PTree.t block_shape)\n                    (pc: node) (after: res eqs) : res eqs :=\n  match after with\n  | Error _ => after\n  | OK e =>\n      match shapes!pc with\n      | None => Error(MSG \"At PC \" :: POS pc :: MSG \": unmatched block\" :: nil)\n      | Some shape =>\n          match transfer_aux f env shape e with\n          | None => Error(MSG \"At PC \" :: POS pc :: MSG \": invalid register allocation\" :: nil)\n          | Some e' => OK e'\n          end\n      end\n  end.\n\n(** The semilattice for dataflow analysis.  Operates on analysis results\n  of type [res eqs], that is, either a set of equations or an error\n  message.  Errors correspond to [Top].  Sets of equations are ordered\n  by inclusion. *)\n\nModule LEq <: SEMILATTICE.\n\n  Definition t := res eqs.\n\n  Definition eq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Equal a b\n    | Error _, Error _ => True\n    | _, _ => False\n    end.\n\n  Lemma eq_refl: forall x, eq x x.\n  Proof.\n    intros; destruct x; simpl; auto. red; tauto.\n  Qed.\n\n  Lemma eq_sym: forall x y, eq x y -> eq y x.\n  Proof.\n    unfold eq; intros; destruct x; destruct y; auto.\n    red in H; red; intros. rewrite H; tauto.\n  Qed.\n\n  Lemma eq_trans: forall x y z, eq x y -> eq y z -> eq x z.\n  Proof.\n    unfold eq; intros. destruct x; destruct y; try contradiction; destruct z; auto.\n    red in H; red in H0; red; intros. rewrite H. auto.\n  Qed.\n\n  Definition beq (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.equal a b\n    | Error _, Error _ => true\n    | _, _ => false\n    end.\n\n  Lemma beq_correct: forall x y, beq x y = true -> eq x y.\n  Proof.\n    unfold beq, eq; intros. destruct x; destruct y.\n    apply EqSet.equal_2. auto.\n    discriminate.\n    discriminate.\n    auto.\n  Qed.\n\n  Definition ge (x y: t) :=\n    match x, y with\n    | OK a, OK b => EqSet.Subset b a\n    | Error _, _ => True\n    | _, Error _ => False\n    end.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge, EqSet.Equal, EqSet.Subset; intros.\n    destruct x; destruct y; auto. intros; rewrite H; auto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge, EqSet.Subset; intros.\n    destruct x; auto; destruct y; try contradiction.\n    destruct z; eauto.\n  Qed.\n\n  Definition bot: t := OK empty_eqs.\n\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot, EqSet.Subset; simpl; intros.\n    destruct x; auto. intros. elim (EqSet.empty_1 H).\n  Qed.\n\n  Program Definition lub (x y: t) : t :=\n    match x, y return _ with\n    | OK a, OK b =>\n        OK (mkeqs (EqSet.union (eqs1 a) (eqs1 b))\n                  (EqSet2.union (eqs2 a) (eqs2 b)) _)\n    | OK _, Error _ => y\n    | Error _, _ => x\n    end.\n  Next Obligation.\n    split; intros.\n    apply EqSet2.union_1 in H. destruct H; rewrite eqs_same in H.\n    apply EqSet.union_2; auto. apply EqSet.union_3; auto.\n    apply EqSet.union_1 in H. destruct H; rewrite <- eqs_same in H.\n    apply EqSet2.union_2; auto. apply EqSet2.union_3; auto.\n  Qed.\n\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub, ge, EqSet.Subset; intros.\n    destruct x; destruct y; auto.\n    intros; apply EqSet.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, EqSet.Subset; intros.\n    destruct x; destruct y; auto.\n    intros; apply EqSet.union_3; auto.\n  Qed.\n\nEnd LEq.\n\n(** The backward dataflow solver is an instantiation of Kildall's algorithm. *)\n\nModule DS := Backward_Dataflow_Solver(LEq)(NodeSetBackward).\n\n(** The control-flow graph that the solver operates on is the CFG of\n  block shapes built by the structural check phase.  Here is its notion\n  of successors. *)\n\nDefinition successors_block_shape (bsh: block_shape) : list node :=\n  match bsh with\n  | BSnop mv s => s :: nil\n  | BSmove src dst mv s => s :: nil\n  | BSmakelong src1 src2 dst mv s => s :: nil\n  | BSlowlong src dst mv s => s :: nil\n  | BShighlong src dst mv s => s :: nil\n  | BSop op args res mv1 args' res' mv2 s => s :: nil\n  | BSopdead op args res mv s => s :: nil\n  | BSload chunk addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2 addr addr' args dst mv1 args1' dst1' mv2 args2' dst2' mv3 s => s :: nil\n  | BSload2_1 addr args dst mv1 args' dst' mv2 s => s :: nil\n  | BSload2_2 addr addr' args dst mv1 args' dst' mv2 s => s :: nil\n  | BSloaddead chunk addr args dst mv s => s :: nil\n  | BSstore chunk addr args src mv1 args' src' s => s :: nil\n  | BSstore2 addr addr' args src mv1 args1' src1' mv2 args2' src2' s => s :: nil\n  | BScall sg ros args res mv1 ros' mv2 s => s :: nil\n  | BStailcall sg ros args mv1 ros' => nil\n  | BSbuiltin ef args res mv1 args' res' mv2 s => s :: nil\n  | BScond cond args mv args' s1 s2 => s1 :: s2 :: nil\n  | BSjumptable arg mv arg' tbl => tbl\n  | BSreturn optarg mv => nil\n  end.\n\nDefinition analyze (f: RTL.function) (env: regenv) (bsh: PTree.t block_shape) :=\n  DS.fixpoint_allnodes bsh successors_block_shape (transfer f env bsh).\n\n(** * Validating and translating functions and programs *)\n\n(** Checking equations at function entry point.  The RTL function receives\n  its arguments in the list [rparams] of pseudoregisters.  The LTL function\n  receives them in the list [lparams] of locations dictated by the\n  calling conventions, with arguments of type [Tlong] being split in\n  two 32-bit halves.  We check that the equations [e] that must hold\n  at the beginning of the functions are compatible with these calling\n  conventions, in the sense that all equations involving a pseudoreg\n  [r] from [rparams] is of the form [r = l [Full]] or [r = l [Low]]\n  or [r = l [High]], where [l] is the corresponding element of [lparams].\n\n  Note that [e] can contain additional equations [r' = l [kind]]\n  involving pseudoregs [r'] not in [rparams]: these equations are\n  automatically satisfied since the initial value of [r'] is [Vundef]. *)\n\nFunction compat_entry (rparams: list reg) (lparams: list (rpair loc)) (e: eqs)\n                      {struct rparams} : bool :=\n  match rparams, lparams with\n  | nil, nil => true\n  | r1 :: rl,  One l1 :: ll =>\n      compat_left r1 l1 e && compat_entry rl ll e\n  | r1 :: rl, Twolong l1 l2 :: ll =>\n      compat_left2 r1 l1 l2 e && compat_entry rl ll e\n  | _, _ => false\n  end.\n\n(** Checking the satisfiability of equations inferred at function entry\n  point.  We also check that the RTL and LTL functions agree in signature\n  and stack size. *)\n\nDefinition check_entrypoints_aux (rtl: RTL.function) (ltl: LTL.function)\n                                 (env: regenv) (e1: eqs) : option unit :=\n  do mv <- pair_entrypoints rtl ltl;\n  do e2 <- track_moves env mv e1;\n  assertion (compat_entry (RTL.fn_params rtl)\n                          (loc_parameters (RTL.fn_sig rtl)) e2);\n  assertion (can_undef destroyed_at_function_entry e2);\n  assertion (zeq (RTL.fn_stacksize rtl) (LTL.fn_stacksize ltl));\n  assertion (signature_eq (RTL.fn_sig rtl) (LTL.fn_sig ltl));\n  Some tt.\n\nLocal Close Scope option_monad_scope.\nLocal Open Scope error_monad_scope.\n\nDefinition check_entrypoints (rtl: RTL.function) (ltl: LTL.function)\n                             (env: regenv) (bsh: PTree.t block_shape)\n                             (a: PMap.t LEq.t): res unit :=\n  do e1 <- transfer rtl env bsh (RTL.fn_entrypoint rtl) a!!(RTL.fn_entrypoint rtl);\n  match check_entrypoints_aux rtl ltl env e1 with\n  | None => Error (msg \"invalid register allocation at entry point\")\n  | Some _ => OK tt\n  end.\n\n(** Putting it all together, this is the validation function for\n  a source RTL function and an LTL function generated by the external\n  register allocator. *)\n\nDefinition check_function (rtl: RTL.function) (ltl: LTL.function) (env: regenv): res unit :=\n  let bsh := pair_codes rtl ltl in\n  match analyze rtl env bsh with\n  | None => Error (msg \"allocation analysis diverges\")\n  | Some a => check_entrypoints rtl ltl env bsh a\n  end.\n\n(** [regalloc] is the external register allocator.  It is written in OCaml\n  in file [backend/Regalloc.ml]. *)\n\nParameter regalloc: RTL.function -> res LTL.function.\n\n(** Register allocation followed by validation. *)\n\nDefinition transf_function (f: RTL.function) : res LTL.function :=\n  match type_function f with\n  | Error m => Error m\n  | OK env =>\n      match regalloc f with\n      | Error m => Error m\n      | OK tf => do x <- check_function f tf env; OK tf\n      end\n  end.\n\nDefinition transf_fundef (fd: RTL.fundef) : res LTL.fundef :=\n  AST.transf_partial_fundef transf_function fd.\n\nDefinition transf_program (p: RTL.program) : res LTL.program :=\n  transform_partial_program transf_fundef 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/Allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.1702306653932536}}
{"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 PBFTlearns_or_knows_pl.\n\n\nSection PBFTlearns_or_knows_pl_nv.\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 pbft_pl_nv_knows (d : pbft_pl_data) (s : PBFTstate) : Prop :=\n    exists nv pi,\n      new_view_in_log nv (view_change_state s)\n      /\\ In pi (mergeP (new_view2cert nv))\n      /\\ prepare_like_in_prepared_info d pi.\n\n  Definition pbft_pl_nv_knows_i (i : pbft_pl_info) (s : PBFTstate) : Prop :=\n    exists (d : pbft_pl_data), pbft_pl_nv_knows d s /\\ i = prepare_like2request_data d.\n\n  Lemma pbft_pl_nv_knows_i_if :\n    forall d m, pbft_pl_nv_knows d m -> pbft_pl_nv_knows_i (prepare_like2request_data d) m.\n  Proof.\n    introv kn.\n    exists d; tcsp.\n  Qed.\n\n  Lemma pbft_pl_nv_no_initial_memory_i :\n    forall n d, ~ pbft_pl_nv_knows_i d (Process.sm_state (PBFTreplicaSM n)).\n  Proof.\n    introv h; simpl in h.\n    unfold pbft_pl_nv_knows_i, pbft_pl_nv_knows in h; exrepnd; simpl in *; auto.\n  Qed.\n\n  Definition pbft_pl_nv_output2data (m : DirectedMsg) : list pbft_pl_data := [].\n\n  Global Instance PBFT_I_SysOutput : SysOutput.\n  Proof.\n    exact (MkSysOutput DirectedMsg).\n  Defined.\n\n  Instance PBFT_I_LearnAndKnow_pl_nv : LearnAndKnow 1.\n  Proof.\n    exact (MkLearnAndKnow\n             1\n             pbft_pl_data\n             pbft_pl_info\n             prepare_like2request_data\n             PBFTstate\n             pbft_pl_nv_knows\n             pbft_pl_nv_knows_i\n             pbft_pl_nv_knows_i_if\n             pbft_pl_data2loc\n             pbft_pl_data2main_auth_data\n             pbft_pl_data2main_auth_data_list\n             pbft_pl_verify\n             _ pbft_pl_nv_no_initial_memory_i).\n  Defined.\n\n  Definition knows_certificate1\n             {eo : EventOrdering}\n             (e : Event)\n             (n : nat)\n             (i : @lak_info PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv)\n             (P : list (@lak_data PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv) -> Prop):=\n    @knows_certificate PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e n i P.\n\n  Definition pbft_knows_rd1 {eo : EventOrdering} (e : Event) (rd : RequestData) :=\n    knows_certificate1 e (2 * F + 1) rd one_pre_prepare.\n\n  Definition knows1\n             {eo : EventOrdering}\n             (e : Event)\n             (d : @lak_data PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv) :=\n    @knows PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e d.\n\n  Definition knew1\n             {eo : EventOrdering}\n             (e : Event)\n             (d : @lak_data PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv) :=\n    @knew PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e d.\n\n  Definition learns1\n             {eo : EventOrdering}\n             (e : Event)\n             (d : @lak_data PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv) :=\n    @learns PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok PBFT_I_ContainedAuthData DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e d.\n\n  Definition learned1\n             {eo : EventOrdering}\n             (e : Event)\n             (d : @lak_data PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv) :=\n    @learned PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok PBFT_I_ContainedAuthData DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e d.\n\n  Lemma prepared_as_pbft_knows_rd :\n    forall (eo : EventOrdering) (e : Event) pi i s nv,\n      loc e = PBFTreplica i\n      -> state_sm_on_event (PBFTreplicaSM i) e = Some s\n      -> well_formed_log (log s)\n      -> info_is_prepared pi = true\n      -> new_view_in_log nv (view_change_state s)\n      -> In pi (mergeP (new_view2cert nv))\n      -> pbft_knows_rd1 e (prepared_info2request_data pi).\n  Proof.\n    introv eqloc eqst wf prep nvinlog piin.\n    unfold info_is_prepared in *; smash_pbft.\n\n    allrw @norepeatsb_as_no_repeats.\n    allrw forallb_forall.\n\n    exists ((prepare_like_pre_prepare (prepared_info_pre_prepare pi))\n              :: map prepare_like_prepare (prepared_info_prepares pi)).\n\n    simpl; autorewrite with pbft list; dands; auto;\n      try (complete (rewrite <- length_prepared_info2senders_eq_length_prepared_info_prepares; omega)).\n\n    - constructor; auto.\n      introv xx.\n      apply prep1 in xx.\n      smash_pbft.\n\n    - unfold one_pre_prepare; simpl.\n      f_equal.\n      apply length_zero_iff_nil.\n      match goal with\n      | [ |- ?x = _ ] => remember x as l; destruct l; auto\n      end.\n      assert False; tcsp.\n      pose proof (filter_In is_pre_prepare_like p (map prepare_like_prepare (prepared_info_prepares pi))) as q.\n      destruct q as [q q']; clear q'.\n      rewrite <- Heql in q; simpl in q; autodimp q hyp.\n      repnd.\n      apply in_map_iff in q0; exrepnd; subst.\n      destruct x; simpl in *; ginv.\n\n    - introv h; repndors; subst; tcsp; dands.\n\n      + exists s i; dands; auto; exists nv pi; dands; auto.\n        destruct pi; simpl; auto.\n\n      + destruct pi, prepared_info_pre_prepare, b; simpl.\n        unfold prepared_info2request_data, pre_prepare2digest; simpl.\n        f_equal.\n        unfold prepared_info_has_correct_digest, prepared_info2requests in *; simpl in *; smash_pbft.\n\n      + allrw in_map_iff; exrepnd; subst; auto.\n        exists s i; dands; auto; exists nv pi; dands; auto.\n\n      + allrw in_map_iff; exrepnd; subst; auto.\n        destruct pi, prepared_info_pre_prepare, b; simpl.\n        unfold PBFTheader.prepared_info_prepares in *.\n        unfold prepared_info2request_data, pre_prepare2digest in *; simpl.\n        apply prep0 in h0.\n        simpl in h0; smash_pbft.\n  Qed.\n\n  Definition knows_in_intersection1\n             {eo : EventOrdering}\n             (e1 e2 : Event)\n             (n : nat)\n             (i1 i2 : @lak_info PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv)\n             P E N :=\n    @knows_in_intersection PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok PBFT_I_ContainedAuthData DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e1 e2 n i1 i2 P E N.\n\n  Definition local_knows_in_intersection1\n             {eo : EventOrdering}\n             (e : Event)\n             (n : nat)\n             (i1 i2 : @lak_info PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv)\n             P E N :=\n    @local_knows_in_intersection PBFT_I_Data PBFT_I_Node PBFT_I_Key PBFT_I_Msg PBFT_I_Quorum PBFT_I_AuthTok DTimeContextQ PBFT_I_IOTrustedFun PBFT_I_SysOutput 1 PBFT_I_LearnAndKnow_pl_nv eo e n i1 i2 P E N.\n\nEnd PBFTlearns_or_knows_pl_nv.\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/PBFTlearns_or_knows_pl_nv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1699084845614999}}
{"text": "From App Require Export\n     Solver.\n\nNotation swap_stE :=\n  (stE (swap_request id) (swap_response id) (swap_state exp)).\n\nCoFixpoint match_event {q r s T} (e0 : observeE q r s T) (v : T)\n           (m : itree (stE q r s) void) : itree (stE q r s) void :=\n  match observe m with\n  | RetF vd => match vd in void with end\n  | TauF m' => Tau (match_event e0 v m')\n  | VisF e k =>\n    match e with\n    | (||oe) =>\n      match oe in observeE _ _ _ Y, e0 in observeE _ _ _ Z\n            return (Y -> _) -> Z -> _ with\n      | Observe__FromServer, Observe__FromServer\n      | Observe__ToServer _, Observe__ToServer _ => id\n      | _, _ => fun _ _ => throw \"Unexpected event\"\n      end k v\n    | _ => vis e (match_event e0 v \u2218 k)\n    end\n  end.\n\nDefinition match_observe {q r s T} (e : observeE q r s T) (v : T)\n  : list (itree (stE q r s) void) -> list (itree (stE q r s) void) :=\n  map (match_event e v).\n\nCoFixpoint tester' (others : list (itree swap_stE void))\n           (m : itree swap_stE void) : itree tE void :=\n  match observe m with\n  | RetF vd => match vd in void with end\n  | TauF m' => Tau (tester' others m')\n  | VisF e k =>\n    let catch (err : string) : itree tE void :=\n        embed Log err;;\n        if others is other::others'\n        then Tau (tester' others' other)\n        else throw err in\n    match e with\n    | (Throw err|) => catch err\n    | (|de|) =>\n      match de in decideE Y return (Y -> _) -> _ with\n      | Decide => fun k => b <- trigger Or;;\n                       Tau (tester' (k (negb b)::others) (k b))\n      end k\n    | (||oe) =>\n      match oe in observeE _ _ _ Y return (Y -> _) -> _ with\n      | Observe__ToServer st =>\n        fun k =>\n          op1 <- trigger Client__Recv;;\n          if op1 is Some p1\n          then if match_observe Observe__FromServer p1 others is other::others'\n               then Tau (tester' others' other)\n               else catch \"Unexpected receive from server\"\n          else op <- embed Client__Send st;;\n               if op is Some p\n               then Tau (tester' (match_observe (Observe__ToServer st) p others)\n                                 (k p))\n               else if others is other::others'\n                    then Tau (tester' (others' ++ [m]) other)\n                    else Tau (tester' [] m)\n      | Observe__FromServer =>\n        fun k =>\n          op <- trigger Client__Recv;;\n          if op is Some p\n          then Tau (tester' (match_observe Observe__FromServer p others) (k p))\n          else if others is other::others'\n               then Tau (tester' (others' ++ [m]) other)\n               else Tau (tester' [] m)\n      end k\n    end\n  end.\n\nDefinition tester : itree swap_stE void -> itree tE void := tester' [].\n\nDefinition swap_tester : swap_state exp -> itree tE void := tester \u2218 solve_swap.\n", "meta": {"author": "liyishuai", "repo": "coq-http", "sha": "a0c97d1a7f0e1c7d5571ed3f3c117fd4732069bf", "save_path": "github-repos/coq/liyishuai-coq-http", "path": "github-repos/coq/liyishuai-coq-http/coq-http-a0c97d1a7f0e1c7d5571ed3f3c117fd4732069bf/app/Tester.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.1699084845614999}}
{"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.\nRequire Import Configuration.\nRequire Import PFConfiguration.\nRequire Import Behavior.\n\nRequire Import PFConsistent.\nRequire Import Certify.\n\nRequire Import FutureCertify.\nRequire Import SrcToIRThread.\n\nSet Implicit Arguments.\n\n\nModule SrcToIR.\n  Variant sim_thread_sl (gl_src gl_ir: Global.t):\n    forall (sl_src sl_ir: {lang: language & Language.state lang} * Local.t), Prop :=\n    | sim_thread_sl_intro\n        lang\n        st_src lc_src\n        st_ir lc_ir\n        (THREAD: SrcToIRThread.sim_thread (Thread.mk _ st_src lc_src gl_src) (Thread.mk _ st_ir lc_ir gl_ir))\n        (CONS: exists gl_past,\n            (<<FUTURE: Global.future gl_past gl_ir>>) /\\\n            (<<LC_WF: Local.wf lc_ir gl_past>>) /\\\n            (<<GL_WF: Global.wf gl_past>>) /\\\n            (<<CONS: PFConsistent.spf_consistent (Thread.mk _ st_ir lc_ir gl_past)>>))\n      :\n      sim_thread_sl gl_src gl_ir (existT _ lang st_src, lc_src) (existT _ lang st_ir, lc_ir)\n  .\n\n  Lemma sim_thread_sl_future\n        gl_src gl_ir lang_src st_src lc_src lang_ir st_ir lc_ir\n        gl_future_src gl_future_ir\n        (GL_FUTURE_IR: Global.future gl_ir gl_future_ir)\n        (SC: Global.sc gl_future_src = Global.sc gl_future_ir)\n        (GPROMISES: Global.promises gl_future_src = BoolMap.bot)\n        (MEMORY: SrcToIRThread.sim_memory (Global.memory gl_future_src) (Global.memory gl_future_ir))\n        (SIM: sim_thread_sl gl_src gl_ir\n                            (existT _ lang_src st_src, lc_src)\n                            (existT _ lang_ir st_ir, lc_ir)):\n    sim_thread_sl gl_future_src gl_future_ir\n                  (existT _ lang_src st_src, lc_src)\n                  (existT _ lang_ir st_ir, lc_ir).\n  Proof.\n    inv SIM. Configuration.simplify. econs.\n    - inv THREAD. ss.\n    - des. exists gl_past.\n      splits; ss; try by (etrans; eauto).\n  Qed.\n\n  Variant sim_conf: forall (c_src c_ir: Configuration.t), Prop :=\n    | sim_conf_intro\n        ths_src gl_src\n        ths_ir gl_ir\n        (THS: forall tid,\n            option_rel\n              (sim_thread_sl gl_src gl_ir)\n              (IdentMap.find tid ths_src)\n              (IdentMap.find tid ths_ir)):\n      sim_conf (Configuration.mk ths_src gl_src) (Configuration.mk ths_ir gl_ir)\n  .\n\n  Lemma init_sim_conf prog: sim_conf (Configuration.init prog) (Configuration.init prog).\n  Proof.\n    econs. i.\n    unfold Threads.init. rewrite IdentMap.Facts.map_o.\n    destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                (@sigT _ (@Language.syntax ProgramEvent.t)) tid prog); ss.\n    econs; ss.\n    - econs; ss. apply SrcToIRThread.init_sim_memory.\n    - exists Global.init. splits.\n      + refl.\n      + apply Local.init_wf.\n      + apply Global.init_wf.\n      + econs 2; s; try refl.\n  Qed.\n\n  Lemma sim_conf_terminal\n        c1_src c1_ir\n        (SIM: sim_conf c1_src c1_ir)\n        (TERMINAL: Configuration.is_terminal c1_ir):\n    Configuration.is_terminal c1_src.\n  Proof.\n    inv SIM. ii. ss.\n    specialize (THS tid). rewrite FIND in THS.\n    destruct (IdentMap.find tid ths_ir) as [[[lang_ir st_ir] lc_ir]|] eqn:FIND_IR; ss.\n    inv THS. Configuration.simplify.\n    inv THREAD. ss. subst. splits; ss.\n    exploit TERMINAL; eauto. i. des. ss.\n  Qed.\n\n  Lemma is_racy_promise_is_racy\n        lang e (th1 th2: Thread.t lang)\n        (STEP: Thread.step e th1 th2)\n        (EVENT: ThreadEvent.is_racy_promise e):\n    exists loc,\n      (<<LOC: ThreadEvent.is_accessing_loc loc e>>) /\\\n      (<<GET: Global.promises (Thread.global th1) loc = true>>) /\\\n      (<<GETP: Local.promises (Thread.local th1) loc = false>>).\n  Proof.\n    inv STEP; inv LOCAL; ss.\n    - inv LOCAL0. inv RACE; ss. eauto.\n    - inv LOCAL0. inv RACE; ss. eauto.\n    - inv LOCAL0; des.\n      + destruct ordr; ss.\n      + destruct ordw; ss.\n      + inv RACE; ss. eauto.\n  Qed.\n\n  Lemma disjoint_minus_le_r\n        bm1 bm2 gbm\n        (LE1: BoolMap.le bm1 gbm)\n        (LE2: BoolMap.le bm2 gbm)\n        (DISJOINT: BoolMap.disjoint bm1 bm2):\n    BoolMap.le bm2 (BoolMap.minus gbm bm1).\n  Proof.\n    ii. exploit LE2; eauto. i.\n    unfold BoolMap.minus. rewrite x0. s.\n    destruct (bm1 loc) eqn:GET1; ss.\n    exploit DISJOINT; eauto.\n  Qed.\n\n  Lemma sim_conf_step\n        c1_src c1_ir\n        e tid c2_ir\n        (SIM: sim_conf c1_src c1_ir)\n        (WF1_SRC: Configuration.wf c1_src)\n        (WF1_IR: Configuration.wf c1_ir)\n        (STEP: Configuration.step e tid c1_ir c2_ir):\n    (exists c_src tid' c2_src,\n        (<<STEPS_SRC: rtc (PFConfiguration.tau_step ThreadEvent.get_machine_event_pf)\n                         c1_src c_src>>) /\\\n        (<<STEP_SRC: PFConfiguration.step ThreadEvent.get_machine_event_pf\n                                         MachineEvent.failure tid' c_src c2_src>>)) \\/\n    (exists c_src c2_src,\n        (<<STEPS_SRC: rtc (PFConfiguration.tau_step ThreadEvent.get_machine_event_pf)\n                         c1_src c_src>>) /\\\n        (<<STEP_SRC: PFConfiguration.opt_step ThreadEvent.get_machine_event_pf\n                                             e tid c_src c2_src>>) /\\\n        ((<<SIM2: sim_conf c2_src c2_ir>>) \\/\n         exists c3_src tid' c4_src,\n           (<<STEPS2_SRC: rtc (PFConfiguration.tau_step ThreadEvent.get_machine_event_pf)\n                             c2_src c3_src>>) /\\\n           (<<STEP2_SRC: PFConfiguration.step ThreadEvent.get_machine_event_pf\n                                             MachineEvent.failure tid' c3_src c4_src>>))).\n  Proof.\n    destruct c1_src as [ths1_src gl1_src], c1_ir as [ths1_ir gl1_ir].\n    inv STEP. dup SIM. inv SIM0. ss.\n    rename st1 into st1_ir, lc1 into lc1_ir.\n    specialize (THS tid). rewrite TID in *.\n    destruct (IdentMap.find tid ths1_src) as [[[lang_src st1_src] lc1_src]|] eqn:FIND_SRC; ss.\n    inv THS. Configuration.simplify. clear CONS.\n\n    exploit SrcToIRThread.plus_step_cases; try exact STEPS; eauto. i. des; cycle 1.\n    { (* race with a promise *)\n      left. clear e0 th2 st3 lc3 gl3 STEPS STEP0 CONSISTENT.\n      exploit SrcToIRThread.sim_thread_rtc_step; try exact STEPS0; eauto. i. des.\n      exploit is_racy_promise_is_racy; try exact STEP_RACE; ss. i. des.\n      exploit Thread.rtc_tau_step_promises_minus;\n        try eapply rtc_implies; try exact STEPS0; s.\n      { i. inv H. des. econs; eauto. }\n      unfold BoolMap.minus. i.\n      eapply equal_f in x0.\n      rewrite GET, GETP in x0. ss.\n      destruct (Global.promises gl1_ir loc) eqn:GPROMISED; ss.\n      destruct (Local.promises lc1_ir loc) eqn:PROMISED; ss.\n      dup WF1_IR. inv WF1_IR0. inv WF. ss.\n      exploit (PROMISES loc); ss.\n      clear DISJOINT THREADS PROMISES. i. des.\n      destruct (classic (tid = tid0)).\n      { subst. rewrite TID in *. Configuration.simplify. congr. }\n      dup SIM. inv SIM0. specialize (THS tid0). rewrite TH in *.\n      destruct (IdentMap.find tid0 ths1_src) as [[[lang0_src st0_src] lc0_src]|] eqn:FIND0_SRC; ss.\n      inv THS. Configuration.simplify. des.\n      exploit spf_consistent_certify; try exact CONS; eauto. s. intro CERTIFY.\n\n      dup WF1_IR. inv WF1_IR0. inv WF. ss.\n      exploit DISJOINT; try exact H; eauto. i.\n      exploit THREADS; try exact TID. i.\n      exploit THREADS; try exact TH. i.\n      clear DISJOINT THREADS PROMISES.\n      dup WF1_SRC. inv WF1_SRC0. inv WF. ss.\n      exploit DISJOINT; try exact H; eauto. i.\n      exploit THREADS; try exact FIND_SRC. i.\n      exploit THREADS; try exact FIND0_SRC. i.\n      clear DISJOINT THREADS PROMISES.\n      exploit Thread.rtc_tau_step_future; try eapply rtc_implies; try exact STEPS0; ss.\n      { i. inv H0. des. econs; eauto. }\n      i. des.\n      exploit Thread.rtc_tau_step_future; try eapply rtc_implies; try exact STEPS_SRC; ss.\n      { i. inv H0. des. econs; eauto. }\n      i. des.\n      exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies; try exact STEPS0; eauto.\n      { i. inv H0. des. econs; eauto. }\n      i. des.\n      exploit Thread.rtc_tau_step_disjoint; try eapply rtc_implies; try exact STEPS_SRC; eauto.\n      { i. inv H0. des. econs; eauto. }\n      i. des.\n      exploit (@FutureCertify.future_certify lang0 (Thread.mk _ st0_src lc0_src (Thread.global th2_src)));\n        try exact CERTIFY; ss; (try by inv THREAD0; ss); (try by inv SIM2; ss); try apply SIM2.\n      { eapply Memory.future_messages_le. etrans; try apply FUTURE. apply GL_FUTURE. }\n      { apply LC_WF1. }\n      intro CERTIFY_SRC.\n      exploit (@PFConfiguration.rtc_program_step_rtc_step (Configuration.mk ths1_src gl1_src));\n        try eapply STEPS_SRC; eauto. s. i. des; eauto.\n\n      inv CERTIFY_SRC.\n      - exploit (@PFConfiguration.plus_program_step_plus_step\n                   (Configuration.mk\n                      (IdentMap.add tid (existT _ lang (Thread.state th2_src), Thread.local th2_src) ths1_src)\n                      (Thread.global th2_src))); s.\n        { erewrite IdentMap.gso; try eapply FIND0_SRC. auto. }\n        { eapply rtc_implies; try exact STEPS1.\n          i. inv H0. des. econs; eauto.\n          inv EVENT. inv EVENT0. destruct e1; ss.\n        }\n        { eassumption. }\n        { destruct e0; ss. }\n        i. des; try by destruct e0; ss.\n        esplits; try exact STEP. etrans; eauto.\n      - destruct th2_src as [st2_src lc2_src gl2_src]. ss.\n        assert (RACE: exists e th3_src,\n                     Thread.step e\n                                 (Thread.mk _ st2_src lc2_src (Thread.global th2)) th3_src /\\\n                     ThreadEvent.is_racy e /\\\n                     ~ ThreadEvent.is_racy_promise e).\n        { exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS1; ss.\n          { i. inv H0. econs; eauto. }\n          i. des.\n          inv STEP_FULFILL; inv LOCAL. inv LOCAL0. ss.\n          exploit Memory.add_get0; try exact WRITE. i. des.\n          inv SIM2. ss. subst.\n          inv STEP_RACE; inv LOCAL; ss; subst.\n          - esplits.\n            + econs 2; cycle 1.\n              * econs 8. econs. econs 2; try apply GET2; ss.\n                eapply TimeFacts.le_lt_lt; try exact TO.\n                inv LC_WF0. inv TVIEW_CLOSED. inv CUR.\n                exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE1. i. des.\n                eapply Memory.max_ts_spec. eauto.\n              * ss. eauto.\n            + ss.\n            + ss.\n          - esplits.\n            + econs 2; cycle 1.\n              * econs 9. econs. econs 2; try apply GET2; ss.\n                eapply TimeFacts.le_lt_lt; try exact TO.\n                inv LC_WF0. inv TVIEW_CLOSED. inv CUR.\n                exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE1. i. des.\n                eapply Memory.max_ts_spec. eauto.\n              * ss. eauto.\n            + ss.\n            + ss.\n          - esplits.\n            + econs 2; cycle 1.\n              * econs 10. econs 3. econs 2; try apply GET2; ss.\n                eapply TimeFacts.le_lt_lt; try exact TO.\n                inv LC_WF0. inv TVIEW_CLOSED. inv CUR.\n                exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE1. i. des.\n                eapply Memory.max_ts_spec. eauto.\n              * ss. eauto.\n            + ss.\n            + ss.\n        }\n        des. destruct th3_src.\n        exploit (@PFConfiguration.plus_program_step_plus_step\n                   (Configuration.mk\n                      (IdentMap.add tid (existT _ lang st2_src, lc2_src) ths1_src) gl2_src)); s.\n        { erewrite IdentMap.gso; try eapply FIND0_SRC. auto. }\n        { eapply rtc_implies; try exact STEPS1.\n          i. inv H0. des. econs; eauto.\n          inv EVENT. inv EVENT0. destruct e1; ss.\n        }\n        { eassumption. }\n        { ss. }\n        s. i. des; cycle 1.\n        { esplits; try exact STEP. etrans; eauto. }\n        esplits.\n        + etrans; [eauto|]. eapply rtc_n1; [eauto|]. econs. exact STEP.\n        + replace MachineEvent.failure with (ThreadEvent.get_machine_event_pf e0); cycle 1.\n          { destruct e0; ss. }\n          econs. econs; s.\n          * rewrite IdentMap.gso; try by apply IdentMap.gss. ss.\n          * eassumption.\n          * destruct e0; ss.\n    }\n\n    exploit SrcToIRThread.sim_thread_rtc_step; try exact STEPS0; eauto. i. des.\n    exploit SrcToIRThread.sim_thread_step; try exact STEP0; eauto. i. des.\n    exploit (@PFConfiguration.opt_plus_program_step_opt_plus_step (Configuration.mk ths1_src gl1_src));\n      try exact STEPS_SRC; eauto. s. i. des; try by left; eauto.\n    right.\n    assert (ThreadEvent.get_machine_event e0 = ThreadEvent.get_machine_event_pf e_src).\n    { unguard. des; subst; ss; destruct e0; ss. }\n    rewrite H.\n    esplits; try exact STEPS1; eauto.\n    exploit CONSISTENT; try by (destruct e0; ss; congr). i.\n    dup WF1_IR. inv WF1_IR0. inv WF. ss.\n    exploit THREADS; try exact TID. intro LC_WF.\n    clear DISJOINT THREADS PROMISES.\n    exploit Thread.rtc_tau_step_future; try exact STEPS; eauto. s. i. des.\n    exploit Thread.step_future; try exact STEP0; eauto. s. i. des.\n    exploit PFConsistent.consistent_pf_consistent; try exact x0; eauto. i.\n    exploit PFConsistent.pf_consistent_spf_consistent; try exact x1. i. des.\n    { (* certification with no race *)\n      left. clear x0 x1.\n      destruct th2_src, th2_src0. ss.\n      econs. i.\n      destruct (classic (tid = tid0)).\n      - subst. repeat rewrite IdentMap.gss. s. econs; ss.\n        esplits; try exact SPF_CONS; ss; try refl.\n      - repeat (rewrite IdentMap.gso; auto).\n        dup SIM. inv SIM1. specialize (THS tid0).\n        destruct (IdentMap.find tid0 ths1_src) as [[[lang0_src st0_src] lc0_src]|] eqn:FIND0_SRC;\n          destruct (IdentMap.find tid0 ths1_ir) as [[[lang0_ir st0_ir] lc0_ir]|] eqn:FIND0_IR; ss.\n        eapply sim_thread_sl_future; try exact THS; try apply SIM0; try by (etrans; eauto).\n    }\n\n    (* race with a promise during certification *)\n    right. clear H c2 STEPS1 STEP EVENT0 x0 x1.\n    inv SPF_RACE. ss.\n    exploit SrcToIRThread.sim_thread_cap; try exact SIM0. i.\n    exploit SrcToIRThread.sim_thread_rtc_step; try eapply rtc_implies; try exact STEPS1; eauto.\n    { i. inv H. des. inv EVENT0. inv EVENT2. econs; eauto. }\n    i. des.\n    exploit is_racy_promise_is_racy; try exact STEP_RACE; ss. i. des.\n    exploit Thread.rtc_all_step_promises_minus; try eapply rtc_implies; try exact STEPS1.\n    { i. inv H. des. econs; eauto. }\n    exploit Thread.rtc_all_step_promises_minus.\n    { eapply rtc_n1.\n      - eapply rtc_implies; try exact STEPS. i. inv H. econs; eauto.\n      - econs. exact STEP0.\n    }\n    unfold BoolMap.minus. s. i.\n    rewrite x2 in x1. clear x2.\n    eapply equal_f in x1.\n    rewrite GET, GETP in x1. ss.\n    destruct (Global.promises gl1_ir loc) eqn:GPROMISED; ss.\n    destruct (Local.promises lc1_ir loc) eqn:PROMISED; ss.\n    clear x1.\n    dup WF1_IR. inv WF1_IR0. inv WF. ss.\n    exploit (PROMISES loc); ss.\n    clear GL_WF DISJOINT THREADS PROMISES. i. des.\n    destruct (classic (tid = tid0)).\n    { subst. rewrite TID in *. Configuration.simplify. congr. }\n    dup SIM. inv SIM3. specialize (THS tid0). rewrite TH in *.\n    destruct (IdentMap.find tid0 ths1_src) as [[[lang0_src st0_src] lc0_src]|] eqn:FIND0_SRC; ss.\n    inv THS. Configuration.simplify. des.\n    exploit spf_consistent_certify; try exact CONS; eauto. intro CERTIFY.\n\n    dup WF1_IR. inv WF1_IR0. inv WF. ss.\n    exploit DISJOINT; try exact H; eauto. i.\n    exploit THREADS; try exact TID. i.\n    exploit THREADS; try exact TH. i.\n    clear DISJOINT THREADS PROMISES.\n    dup WF1_SRC. inv WF1_SRC0. inv WF. ss.\n    exploit DISJOINT; try exact H; eauto. i.\n    exploit THREADS; try exact FIND_SRC. i.\n    exploit THREADS; try exact FIND0_SRC. i.\n    clear DISJOINT THREADS PROMISES.\n    exploit rtc_implies; [eauto|..].\n    { etrans.\n      - eapply Thread.tau_opt_all; try exact STEP_SRC.\n        eapply rtc_implies; try exact STEPS_SRC. i. inv H0. des. econs; eauto.\n      - eapply rtc_implies; try exact STEPS_SRC0. i. inv H0. des. econs; eauto.\n    }\n    intro STEP_SRC_ALL.\n    exploit Thread.rtc_all_step_future; try exact STEP_SRC_ALL; eauto. s. i. des.\n    exploit Thread.rtc_all_step_disjoint; try exact STEP_SRC_ALL; eauto. s. i. des.\n    exploit (@FutureCertify.future_certify lang0 (Thread.mk _ st0_src lc0_src (Thread.global th2_src1)));\n      try exact CERTIFY; ss; (try by inv THREAD0; ss); (try by inv SIM1; ss); try apply SIM1.\n    { etrans.\n      - eapply Memory.future_messages_le.\n        etrans; [apply FUTURE|].\n        etrans; [apply GL_FUTURE|].\n        apply GL_FUTURE0.\n      - exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS1; eauto.\n        { i. inv H0. econs; eauto. }\n        { apply Local.cap_wf; ss. }\n        { apply Global.cap_wf; ss. }\n        s. i. des.\n        etrans; [|eapply Memory.future_messages_le; apply GL_FUTURE2].\n        apply Memory.cap_messages_le.\n        apply Memory.cap_of_cap.\n    }\n    { exploit Thread.rtc_all_step_disjoint.\n      { etrans; [eapply rtc_implies; try exact STEPS|].\n        { i. inv H0. econs. eauto. }\n        econs 2; try refl. econs. eauto.\n      }\n      { eauto. }\n      { ss. }\n      s. i. des.\n      exploit Local.cap_wf; try exact LC_WF5. i.\n      exploit Thread.rtc_all_step_disjoint; try eapply rtc_implies; try exact STEPS1.\n      { i. inv H0. econs; eauto. }\n      { eauto. }\n      { ss. }\n      i. des. apply LC_WF6.\n    }\n    intro CERTIFY_SRC.\n    destruct th2_src0. ss.\n    exploit (@PFConfiguration.rtc_program_step_rtc_step\n               (Configuration.mk (IdentMap.add tid (existT _ lang state, local) ths1_src) global));\n      try exact STEPS_SRC0; s; try apply IdentMap.gss.\n    i. des; eauto.\n\n    inv CERTIFY_SRC.\n    - exploit (@PFConfiguration.plus_program_step_plus_step\n                 (Configuration.mk\n                    (IdentMap.add tid (existT _ lang (Thread.state th2_src1), Thread.local th2_src1) ths1_src)\n                    (Thread.global th2_src1))); s.\n      { erewrite IdentMap.gso; try eapply FIND0_SRC. auto. }\n      { eapply rtc_implies; try exact STEPS3.\n        i. inv H0. des. econs; eauto.\n        inv EVENT0. inv EVENT2. destruct e2; ss.\n      }\n      { eassumption. }\n      { destruct e1; ss. }\n      i. des; try by destruct e1; ss.\n      esplits; try exact STEP. etrans; [eauto|].\n      rewrite IdentMap.add_add_eq. ss.\n    - destruct th2_src1 as [st2_src lc2_src gl2_src]. ss.\n      assert (RACE: exists e th3_src,\n                 Thread.step e\n                             (Thread.mk _ st2_src lc2_src (Thread.global th4)) th3_src /\\\n                 ThreadEvent.is_racy e /\\\n                 ~ ThreadEvent.is_racy_promise e).\n      { exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS3; ss.\n        { i. inv H0. econs; eauto. }\n        i. des.\n        inv STEP_FULFILL; inv LOCAL. inv LOCAL0. ss.\n        exploit Memory.add_get0; try exact WRITE. i. des.\n        inv SIM1. ss. subst.\n        inv STEP_RACE; inv LOCAL; ss; subst.\n        - esplits.\n          + econs 2; cycle 1.\n            * econs 8. econs.\n              econs 2; try apply GET2; ss.\n              eapply TimeFacts.le_lt_lt; try exact TO.\n              inv LC_WF3. inv TVIEW_CLOSED. inv CUR.\n              exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE2. i. des.\n              eapply Memory.max_ts_spec. eauto.\n           * ss. eauto.\n          + ss.\n          + ss.\n        - esplits.\n          + econs 2; cycle 1.\n            * econs 9. econs. econs 2; try apply GET2; ss.\n              eapply TimeFacts.le_lt_lt; try exact TO.\n              inv LC_WF3. inv TVIEW_CLOSED. inv CUR.\n              exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE2. i. des.\n              eapply Memory.max_ts_spec. eauto.\n            * ss. eauto.\n          + ss.\n          + ss.\n        - esplits.\n          + econs 2; cycle 1.\n            * econs 10. econs 3. econs 2; try apply GET2; ss.\n              eapply TimeFacts.le_lt_lt; try exact TO.\n              inv LC_WF3. inv TVIEW_CLOSED. inv CUR.\n              exploit Memory.future_closed_timemap; try exact PLN; try apply GL_FUTURE2. i. des.\n              eapply Memory.max_ts_spec. eauto.\n            * ss. eauto.\n          + ss.\n          + ss.\n      }\n      des. destruct th3_src.\n      exploit (@PFConfiguration.plus_program_step_plus_step\n                 (Configuration.mk\n                    (IdentMap.add tid (existT _ lang st2_src, lc2_src) ths1_src) gl2_src)); s.\n      { erewrite IdentMap.gso; try eapply FIND0_SRC. auto. }\n      { eapply rtc_implies; try exact STEPS3.\n        i. inv H0. des. econs; eauto.\n        inv EVENT0. inv EVENT2. destruct e1; ss.\n      }\n      { eassumption. }\n      { ss. }\n      s. i. des; cycle 1.\n      { esplits; try exact STEP. etrans; [eauto|].\n        rewrite IdentMap.add_add_eq. ss.\n      }\n      esplits.\n      + etrans; [eauto|].\n        rewrite IdentMap.add_add_eq.\n        eapply rtc_n1; [eauto|]. econs. exact STEP.\n      + replace MachineEvent.failure with (ThreadEvent.get_machine_event_pf e1); cycle 1.\n        { destruct e1; ss. }\n        econs. econs; s.\n        * rewrite IdentMap.gso; try by apply IdentMap.gss. ss.\n        * eassumption.\n        * destruct e1; ss.\n  Qed.\n\n  Theorem src_to_ir prog:\n    behaviors Configuration.step (Configuration.init prog) <2=\n    behaviors (PFConfiguration.step ThreadEvent.get_machine_event_pf) (Configuration.init prog).\n  Proof.\n    i. remember (Configuration.init prog) as c_ir in PR.\n    specialize (init_sim_conf prog). intro SIM.\n    specialize (Configuration.init_wf prog). intro WF_IR.\n    rewrite <- Heqc_ir in WF_IR.\n    rewrite <- Heqc_ir in SIM at 2.\n    clear Heqc_ir.\n    specialize (Configuration.init_wf prog). intro WF_SRC.\n    remember (Configuration.init prog) as c_src.\n    clear Heqc_src.\n    revert c_src WF_SRC SIM.\n    induction PR; i.\n    - econs. eauto using sim_conf_terminal.\n    - exploit sim_conf_step; try exact SIM; eauto. i. des.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        econs 3; eauto.\n      + exploit Configuration.step_future; try exact STEP; ss. i. des.\n        exploit PFConfiguration.rtc_tau_step_future; try exact STEPS_SRC; ss. i. des.\n        exploit PFConfiguration.opt_step_future; try exact STEP_SRC; ss. i. des.\n        eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        inv STEP_SRC. econs 2; eauto.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        inv STEP_SRC. econs 2; eauto.\n        eapply rtc_tau_step_behavior; try exact STEPS2_SRC.\n        econs 3; eauto.\n    - exploit sim_conf_step; try exact SIM; eauto. i. des.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        econs 3; eauto.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        inv STEP_SRC. econs 3; eauto.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        inv STEP_SRC. econs 3; eauto.\n    - exploit sim_conf_step; try exact SIM; eauto. i. des.\n      + eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        econs 3; eauto.\n      + exploit Configuration.step_future; try exact STEP; ss. i. des.\n        exploit PFConfiguration.rtc_tau_step_future; try exact STEPS_SRC; ss. i. des.\n        exploit PFConfiguration.opt_step_future; try exact STEP_SRC; ss. i. des.\n        eapply rtc_tau_step_behavior; try exact STEPS_SRC.\n        inv STEP_SRC; auto. econs 4; eauto.\n      + eapply rtc_tau_step_behavior.\n        { etrans; try exact STEPS_SRC.\n          inv STEP_SRC; [refl|]. econs 2; eauto.\n        }\n        eapply rtc_tau_step_behavior; try exact STEPS2_SRC.\n        econs 3; eauto.\n    - econs 5.\n  Qed.\nEnd SrcToIR.\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/SrcToIR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16990778636624457}}
{"text": "(*TODO: These imports should be pared down*)\nRequire Import FSets.\nRequire FSetAVL.\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import compcert.lib.Ordered.\nRequire Import AST.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\n\nRequire Import Ctypes.\nRequire Import Cop.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.reach.\n\n(** Properties of values obtained by casting to a given type. *)\n\nInductive val_casted: val -> type -> Prop :=\n  | val_casted_int: forall sz si attr n,\n      cast_int_int sz si n = n ->\n      val_casted (Vint n) (Tint sz si attr)\n  | val_casted_float: forall sz attr n,\n      cast_float_float sz n = n ->\n      val_casted (Vfloat n) (Tfloat sz attr)\n  | val_casted_long: forall si attr n,\n      val_casted (Vlong n) (Tlong si attr)\n  | val_casted_ptr_ptr: forall b ofs ty attr,\n      val_casted (Vptr b ofs) (Tpointer ty attr)\n  | val_casted_int_ptr: forall n ty attr,\n      val_casted (Vint n) (Tpointer ty attr)\n  | val_casted_ptr_int: forall b ofs si attr,\n      val_casted (Vptr b ofs) (Tint I32 si attr)\n  | val_casted_ptr_cptr: forall b ofs id attr,\n      val_casted (Vptr b ofs) (Tcomp_ptr id attr)\n  | val_casted_int_cptr: forall n id attr,\n      val_casted (Vint n) (Tcomp_ptr id attr)\n  | val_casted_struct: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tstruct id fld attr)\n  | val_casted_union: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tunion id fld attr)\n  | val_casted_void: forall v,\n      val_casted v Tvoid.\n\nDefinition val_casted_func (v : val) (t : type) : bool :=\n  match v, t with\n    | Vint n, Tint sz si attr =>\n      if Int.eq_dec (cast_int_int sz si n) n then true\n      else false\n    | Vfloat n, Tfloat sz attr =>\n      if Float.eq_dec (cast_float_float sz n) n then true\n      else false\n    | Vlong n, Tlong si attr => true\n    | Vptr b ofs, Tpointer ty attr => true\n    | Vint n, Tpointer ty attr => true\n    | Vptr b ofs, Tint I32 si attr => true\n    | Vptr b ofs, Tcomp_ptr id attr => true\n    | Vint n, Tcomp_ptr id attr => true\n    | Vptr b ofs, Tstruct id flt attr => true\n    | Vptr b ofs, Tunion id flt attr => true\n    | _, Tvoid => true\n    | _, _ => false\n  end.\n\nLemma val_casted_funcI v t :\n  val_casted v t ->\n  val_casted_func v t=true.\nProof.\ndestruct 1; simpl; auto.\nrewrite H. case_eq (Int.eq_dec n n); auto.\nrewrite H. case_eq (Float.eq_dec n n); auto.\ndestruct v; auto.\nQed.\n\nLemma val_casted_funcE v t :\n  val_casted_func v t=true ->\n  val_casted v t.\nProof.\ndestruct v; destruct t; simpl; try solve[inversion 1;econstructor; eauto].\ncase_eq (Int.eq_dec (cast_int_int i0 s i) i). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ncase_eq (Float.eq_dec (cast_float_float f0 f) f). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ndestruct i0; try inversion 1. constructor.\nQed.\n\nLemma val_casted_funcP v t :\n  val_casted_func v t=true <-> val_casted v t.\nProof.\nsplit; [apply val_casted_funcE|apply val_casted_funcI].\nQed.\n\nRemark cast_int_int_idem:\n  forall sz sg i, cast_int_int sz sg (cast_int_int sz sg i) = cast_int_int sz sg i.\nProof.\n  intros. destruct sz; simpl; auto.\n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct (Int.eq i Int.zero); auto.\nQed.\n\nRemark cast_float_float_idem:\n  forall sz f, cast_float_float sz (cast_float_float sz f) = cast_float_float sz f.\nProof.\n  intros; destruct sz; simpl.\n  apply Float.singleoffloat_idem; auto.\n  auto.\nQed.\n\nLemma cast_val_is_casted:\n  forall v ty ty' v', sem_cast v ty ty' = Some v' -> val_casted v' ty'.\nProof.\n  unfold sem_cast; intros. destruct ty'; simpl in *.\n(* void *)\n  constructor.\n(* int *)\n  destruct i; destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. apply (cast_int_int_idem I8 s).\n  constructor. apply (cast_int_int_idem I8 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I8 s).\n  constructor. apply (cast_int_int_idem I16 s).\n  constructor. apply (cast_int_int_idem I16 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I16 s).\n  constructor. auto.\n  constructor.\n  constructor. auto.\n  destruct (cast_float_int s f0); inv H1. constructor. auto.\n  constructor. auto.\n  constructor.\n  constructor; auto.\n  constructor.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor. simpl. destruct (Int64.eq i Int64.zero); auto.\n  constructor. simpl. destruct (Float.cmp Ceq f0 Float.zero); auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor; auto.\n(* long *)\n  destruct ty; try discriminate.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; try discriminate. destruct (cast_float_long s f0); inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n(* float *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. unfold cast_float_float, cast_int_float.\n  destruct f; destruct s; auto.\n  rewrite Float.singleofint_floatofint. apply Float.singleoffloat_idem.\n  rewrite Float.singleofintu_floatofintu. apply Float.singleoffloat_idem.\n  constructor. unfold cast_float_float, cast_long_float.\n  destruct f; destruct s; auto. apply Float.singleoflong_idem. apply Float.singleoflongu_idem.\n  constructor. apply cast_float_float_idem.\n(* pointer *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; try constructor.\n(* impossible cases *)\n  discriminate.\n  discriminate.\n(* structs *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* unions *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* comp_ptr *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; constructor.\nQed.\n\nLemma val_casted_load_result:\n  forall v ty chunk,\n  val_casted v ty -> access_mode ty = By_value chunk ->\n  Val.load_result chunk v = v.\nProof.\n  intros. inversion H; clear H; subst v ty; simpl in H0.\n  destruct sz.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  clear H1. inv H0. auto.\n  inversion H0; clear H0; subst chunk. simpl in *.\n  destruct (Int.eq n Int.zero); subst n; reflexivity.\n  destruct sz; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\nQed.\n\nLemma cast_val_casted:\n  forall v ty, val_casted v ty -> sem_cast v ty ty = Some v.\nProof.\n  intros. inversion H; clear H; subst v ty; unfold sem_cast; simpl; auto.\n  destruct sz; congruence.\n  congruence.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\nQed.\n\nLemma val_casted_inject:\n  forall f v v' ty,\n  val_inject f v v' -> val_casted v ty -> val_casted v' ty.\nProof.\n  intros. inv H; auto.\n  inv H0; constructor.\n  inv H0; constructor.\nQed.\n\nInductive val_casted_list: list val -> typelist -> Prop :=\n  | vcl_nil:\n      val_casted_list nil Tnil\n  | vcl_cons: forall v1 vl ty1 tyl,\n      val_casted v1 ty1 -> val_casted_list vl tyl ->\n      val_casted_list (v1 :: vl) (Tcons  ty1 tyl).\n\nLemma val_casted_list_params:\n  forall params vl,\n  val_casted_list vl (type_of_params params) ->\n  list_forall2 val_casted vl (map snd params).\nProof.\n  induction params; simpl; intros.\n  inv H. constructor.\n  destruct a as [id ty]. inv H. constructor; auto.\nQed.\n\nFixpoint val_casted_list_func (vs : list val) (ts : typelist) : bool :=\n  match vs, ts with\n    | nil, Tnil => true\n    | v1 :: vl, Tcons ty1 tyl =>\n      val_casted_func v1 ty1 && val_casted_list_func vl tyl\n    | _, _ => false\n  end.\n\nLemma val_casted_list_funcP vs ts :\n  val_casted_list_func vs ts=true <-> val_casted_list vs ts.\nProof.\nrevert ts; induction vs. destruct ts; simpl; auto.\nsplit; auto. intros _. constructor.\nsplit; auto. inversion 1. inversion 1.\nsplit; auto. destruct ts; simpl; auto.\ninversion 1. rewrite andb_true_iff. intros [H1 H2]. constructor.\napply val_casted_funcE in H1; auto. rewrite <-IHvs; auto.\ninversion 1; subst. simpl. rewrite andb_true_iff; split.\napply val_casted_funcI; auto. rewrite IHvs; auto.\nQed.\n\nLemma val_casted_inj (j : meminj) v1 v2 tv :\n  val_inject j v1 v2 ->\n  val_casted v1 tv ->\n  val_casted v2 tv.\nProof.\ninversion 1; subst; auto.\ninversion 1; subst; auto; try solve[constructor; auto].\ninversion 1; constructor.\nQed.\n\nLemma val_casted_list_inj (j : meminj) vs1 vs2 ts :\n  val_list_inject j vs1 vs2 ->\n  val_casted_list vs1 ts ->\n  val_casted_list vs2 ts.\nProof.\nintros H1; revert vs1 vs2 H1; induction ts; simpl; intros vs1 vs2 H1 H2.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\neapply val_casted_inj; eauto.\neapply IHts; eauto.\nQed.\n\nDefinition val_has_type_func (v : val) (t : typ) : bool :=\n  match v with\n    | Vundef => true\n    | Vint _ => match t with\n                  | AST.Tint => true\n                  | _ => false\n                end\n    | Vlong _ => match t with\n                 | AST.Tlong => true\n                 | _ => false\n               end\n    | Vfloat f => match t with\n                    | AST.Tfloat => true\n                    | Tsingle => if Float.is_single_dec f then true else false\n                    | _ => false\n                  end\n    | Vptr _ _ => match t with\n                    | AST.Tint => true\n                    | _ => false\n                  end\n  end.\n\nLemma val_has_type_funcP v t :\n  Val.has_type v t <-> (val_has_type_func v t=true).\nProof.\nsplit.\ninduction v; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto. destruct (Float.is_single_dec f); auto.\nsimpl. destruct t; auto.\ninduction v; simpl; auto.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try solve[inversion 1].\ndestruct (Float.is_single_dec f); try solve[inversion 1|auto].\ndestruct t; auto. inversion 1. inversion 1. inversion 1.\nQed.\n\nFixpoint val_has_type_list_func (vl : list val) (tyl : list typ) : bool :=\n  match vl, tyl with\n    | nil, nil => true\n    | v :: vl', ty :: tyl' => val_has_type_func v ty\n                              && val_has_type_list_func vl' tyl'\n    | nil, _ :: _ => false\n    | _ :: _, nil => false\n  end.\n\nLemma val_has_type_list_func_charact vl tyl :\n  Val.has_type_list vl tyl <-> (val_has_type_list_func vl tyl=true).\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl. split; auto. simpl. split; auto. inversion 1.\nintros. destruct tyl. simpl. split; auto. inversion 1.\nsimpl. split. intros [H H2].\n+ rewrite andb_true_iff. split.\n  rewrite <-val_has_type_funcP; auto.\n  rewrite <-IHvl; auto.\n+ rewrite andb_true_iff. intros [H H2]. split.\n  rewrite val_has_type_funcP; auto.\n  rewrite IHvl; auto.\nQed.\n\nFixpoint tys_nonvoid (tyl : typelist) :=\n  match tyl with\n    | Tnil => true\n    | Tcons Tvoid tyl' => false\n    | Tcons _ tyl' => tys_nonvoid tyl'\n  end.\n\nFixpoint vals_defined (vl : list val) :=\n  match vl with\n    | nil => true\n    | Vundef :: _ => false\n    | _ :: vl' => vals_defined vl'\n  end.\n\nLemma vals_inject_defined (vl1 vl2 : list val) (j : meminj) :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  vals_defined vl2=true.\nProof.\nrevert vl2; induction vl1; simpl. destruct vl2; try solve[inversion 1|auto].\nintros vl2; inversion 1; subst. destruct a; try solve[inversion 1].\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\nQed.\n\nLemma valinject_hastype':\n  forall (j : meminj) (v v' : val),\n    val_inject j v v' ->\n    v <> Vundef ->\n    forall T : typ, Val.has_type v T -> Val.has_type v' T.\nProof.\n  intros.\n  induction H; auto.\n  elim H0; auto.\nQed.\n\nLemma val_list_inject_hastype j vl1 vl2 tys :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  val_has_type_list_func vl1 tys=true ->\n  val_has_type_list_func vl2 tys=true.\nProof.\nrevert vl2 tys. induction vl1. inversion 1. solve[destruct tys; simpl; auto].\nintros H tys H1 H2 H3. inv H1.\nassert (def: vals_defined vl1=true).\n{ inv H2. revert H0. destruct a; auto. congruence. }\nsimpl. destruct tys. simpl in H3; congruence.\nrewrite andb_true_iff. split.\nrewrite <-val_has_type_funcP. eapply valinject_hastype'; eauto.\nsimpl in H2. intros contra. rewrite contra in H2. congruence.\ninv H3. rewrite andb_true_iff in H0.\n  destruct H0 as [H0 _]. solve[rewrite val_has_type_funcP; auto].\neapply (IHvl1 vl'); eauto.\ninv H3. rewrite H0. rewrite andb_true_iff in H0.\n  solve[destruct H0 as [_ ->]; auto].\nQed.\n\nLemma val_list_inject_defined j vl1 vl2 :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  vals_defined vl2=true.\nProof.\nrevert vl2. induction vl1; simpl.\n+ intros vl2; inversion 1; auto.\n+ intros vl2; inversion 1; subst. inv H.\nsimpl. intros H8.\nassert (def1: vals_defined vl1=true).\n{ destruct a; try solve[congruence]. }\nrevert H2 H8. inversion 1; auto. subst. congruence.\nQed.\n\n(*TODO: put these in Events.v*)\nFixpoint encode_longs (tyl : list typ) (vl : list val) :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' =>\n      match vl with\n        | nil => nil\n        | Vlong n :: vl' => Vint (Int64.hiword n) :: Vint (Int64.loword n)\n                            :: encode_longs tyl' vl'\n        | Vundef :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n        | _ :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n      end\n    | t :: tyl' =>\n      match vl with\n        | nil => nil\n        | v :: vl' => v :: encode_longs tyl' vl'\n      end\n  end.\n\nFixpoint encode_typs (tyl : list typ) : list typ :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' => AST.Tint :: AST.Tint :: encode_typs tyl'\n    | t :: tyl' => t :: encode_typs tyl'\n  end.\n\nLemma encode_longs_has_type tyl vl :\n  Val.has_type_list vl tyl ->\n  Val.has_type_list (encode_longs tyl vl) (encode_typs tyl).\nProof.\nrevert vl; induction tyl. simpl; auto.\ndestruct vl. intros; contradiction. intros [H H2]. simpl.\ndestruct a; try solve[split; auto].\ndestruct v; simpl; auto.\nQed.\n\nLemma decode_encode_longs tyl vl :\n  Val.has_type_list vl tyl ->\n  decode_longs tyl (encode_longs tyl vl) = vl.\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl; auto.\ndestruct t; simpl; auto.\ndestruct tyl. simpl. inversion 1. inversion 1; subst. clear H.\nsimpl. destruct t; auto; try rewrite IHvl; auto.\ndestruct a; simpl; try solve[inv H0].\nrewrite IHvl; auto.\nrewrite IHvl; auto. f_equal.\nrewrite Int64.ofwords_recompose; auto.\nQed.\n\nLemma encode_longs_inject:\n  forall (f : meminj) (tyl : list typ) (vl1 vl2 : list val),\n  val_list_inject f vl1 vl2 ->\n  val_list_inject f (encode_longs tyl vl1) (encode_longs tyl vl2).\nProof.\nintros until vl2; intros H; revert tyl; induction H; simpl.\ndestruct tyl; simpl; [solve[constructor]|]. solve[destruct t; auto].\ndestruct tyl; simpl; [solve[constructor]|]. destruct t.\nsolve[constructor; auto].\nsolve[constructor; auto].\ninv H. solve[auto]. constructor; auto. solve[auto]. solve[auto].\ndestruct v'; solve[auto|constructor; auto].\nsolve[constructor; auto].\nQed.\n\nFixpoint getBlocks' (vl : list val) (b0 : block) :=\n  match vl with\n    | nil => false\n    | Vptr b _ :: vl' => eq_block b b0 || getBlocks' vl' b0\n    | _ :: vl' => getBlocks' vl' b0\n  end.\n\nLemma getBlocks_getBlocks' vl b0 : getBlocks vl b0 = getBlocks' vl b0.\nProof.\ninduction vl; simpl; auto.\ndestruct a; auto. unfold getBlocks. simpl.\ndestruct (eq_block b b0); simpl; auto.\nrewrite <-IHvl. unfold getBlocks.\ndestruct (\n     in_dec eq_block b0\n       (fold_right\n          (fun (v : val) (L : list block) =>\n           match v with\n           | Vundef => L\n           | Vint _ => L\n           | Vlong _ => L\n           | Vfloat _ => L\n           | Vptr b' _ => b' :: L\n           end) nil vl)\n); auto.\nQed.\n\nLemma getBlocks_encode_longs tys vals b :\n  getBlocks (encode_longs tys vals) b=true ->\n  getBlocks vals b=true.\nProof.\n  rewrite !getBlocks_getBlocks'.\n  revert tys; induction vals; simpl; auto. destruct tys. simpl; auto.\n  solve[destruct t; simpl; auto].\n  destruct tys. simpl; congruence.\n  simpl. destruct t; destruct a; simpl; intros; try solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\nQed.\n\nLemma val_casted_has_type a t :\n  tys_nonvoid (Tcons t Tnil) = true ->\n  val_casted_func a t = true ->\n  val_has_type_func a (typ_of_type t) = true.\nProof.\nintros H0 H.\napply val_casted_funcE in H.\ninduction H; try solve[auto].\ndestruct H. destruct sz. simpl.\ngeneralize (Float.singleoffloat_is_single n0).\ndestruct (Float.is_single_dec (Float.singleoffloat n0)); auto. auto.\nsimpl in H0. congruence.\nQed.\n\nLemma val_casted_has_type_list vals tys :\n  tys_nonvoid tys = true ->\n  val_casted_list_func vals tys = true ->\n  val_has_type_list_func vals (typlist_of_typelist tys) = true.\nProof.\nrevert vals; induction tys. simpl. intros vals.\ndestruct vals. simpl; auto. simpl. solve[inversion 2].\nsimpl; intros vals; revert tys IHtys; induction vals. simpl.\n  intros; congruence.\nsimpl; intros. rewrite andb_true_iff in H0; destruct H0 as [H0 H2].\nassert (H3: tys_nonvoid tys = true).\n{ destruct t; solve[congruence|auto]. }\nrewrite andb_true_iff. split; auto.\napply val_casted_has_type; auto. destruct t; 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/val_casted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.16986848098957075}}
{"text": "Require Import ZArith.\nRequire Import List.\nRequire Import Bool.\nRequire        BoolExt.\nRequire        OptionExt.\nRequire        ListExt.\nRequire Import Twosig.\nRequire Import BasicMachineTypes.\nRequire Import ClassDatatypesIface.\nRequire Import ClasspoolIface.\nRequire Import AssignabilityIface.\nRequire Import ResolutionIface.\nRequire Import VirtualMethodLookupIface.\nRequire Import CertRuntimeTypesIface.\nRequire Import ResourceAlgebra.\nRequire Import JVMState.\nRequire Import NativeMethods.\nRequire Import AnnotationIface.\nRequire        FSetInterface.\n\n(* TODO: remove *)\nSet Asymmetric Patterns.\n\nModule Execution (B    : BASICS)\n                 (RA   : RESOURCE_ALGEBRA B)\n                 (ANN  : ANNOTATION B)\n                 (C    : CLASSDATATYPES B ANN)\n                 (CP   : CLASSPOOL B ANN C)\n                 (A    : ASSIGNABILITY B ANN C CP)\n                 (R    : RESOLUTION B ANN C CP A)\n                 (VM   : VIRTUALMETHODLOOKUP B ANN C CP A)\n                 (RDT  : CERTRUNTIMETYPES B ANN C CP A)\n                 (JVM  : JVMSTATE B RA ANN C CP A R VM RDT)\n                 (NATIVE : NATIVE_METHODS B RA ANN C CP A R VM RDT JVM)\n                 (ClassnameSet :FSetInterface.S with Definition E.t := B.Classname.t with Definition E.eq := B.Classname.eq).\n\n\nImport RDT.\nImport JVM.\n\nSection WithPreclasses.\n\nHypothesis preclasses : CP.Preclasspool.t.\nHypothesis privilegedclasses : ClassnameSet.t.\n\n(* Exception handling *)\nSection ExceptionHandling.\n\nHypothesis classes : CP.cert_classpool.\n\nInductive find_handler_result : Set :=\n| handler_found : nat -> find_handler_result\n| handler_notfound : find_handler_result\n| handler_wrong : find_handler_result.\n\nDefinition search_handlers (handlers:list C.exception_handler)\n                           (pc:nat)\n                           (class:C.class)\n                           (exc_cls:B.Classname.t)\n                         : find_handler_result\n  :=\n  let fix search_handlers_aux (handlers:list C.exception_handler) : find_handler_result :=\n        match handlers with\n        | nil =>\n           handler_notfound\n        | C.mkExcHandler start_pc end_pc handler_pc opt_type_idx::handlers =>\n           if C.is_within start_pc end_pc pc then\n              match opt_type_idx with\n              | None =>\n                 handler_found handler_pc\n              | Some type_idx =>\n                 match C.ConstantPool.lookup (C.class_constantpool class) type_idx with\n                 | Some (C.cpe_classref cls_nm) =>\n                    if A.is_assignable classes (C.ty_obj exc_cls) (C.ty_obj cls_nm) then\n                       handler_found handler_pc\n                    else\n                       search_handlers_aux handlers\n                 | _ => handler_wrong\n                 end\n              end\n           else\n              search_handlers_aux handlers\n        end in\n    search_handlers_aux handlers.\n\nFixpoint unwind_stack (frames:list frame)\n                      (ref:Heap.addr_t)\n                      (exc_cls:B.Classname.t)\n                      {struct frames}\n                    : option (list frame)\n  :=\n  match frames with\n  | nil => Some nil\n  | mkFrame _ lvars pc code mth class::frames =>\n     match search_handlers (C.code_exception_table code) pc class exc_cls with\n     | handler_found pc =>\n        Some (mkFrame (rt_addr (Some ref)::nil) lvars pc code mth class::frames)\n     | handler_notfound =>\n        unwind_stack frames ref exc_cls\n     | handler_wrong =>\n        None\n     end\n  end.\n\n(* need to make this abstract by hiding the implementation and just specifying what happens:\n * - gets the least \n *)\n\nEnd ExceptionHandling.\n\nDefinition throw_exception : state -> Heap.addr_t -> exec_result :=\n  fun state ref => match state with\n  | mkState fs classes heap statics res reslimit =>\n     match heap_lookup_class heap ref with\n     | inleft (exist cls_nm _) =>\n        match unwind_stack classes fs ref cls_nm with\n        | Some nil =>\n           stop_exn (mkState nil classes heap statics res reslimit) ref\n        | Some fs =>\n           cont (mkState fs classes heap statics res reslimit)\n        | None => wrong\n        end\n     | inright _ => wrong\n     end\n  end.\n\nDefinition add_res_new : B.Classname.t -> state -> state :=\n  fun clsnm state => match state with\n  | mkState fs classes heap statics used reslimit =>\n     let new_used := match RA.r_new clsnm with\n                       | None => used\n                       | Some r => RA.combine used r\n                     end in\n       mkState fs classes heap statics new_used reslimit\n  end.\n\n(* FIXME: this doesn't really create the objects properly: it never runs their initialiser, nor does it resolve the classes.\n          we should add an invariant that states that the builtin exception classes have already been loaded *)\nDefinition throw_builtin_exception : state -> CP.exn -> exec_result :=\n  fun state e => match state with\n  | mkState fs classes heap statics res reslimit =>\n     let cls_nm := CP.builtin_exception_to_class_name e in\n     match CP.gather_class_exists_evidence classes cls_nm with (* FIXME: need an invariant that states that builtin exception classes always exist *)\n     | inright evidence =>\n        match heap_new heap cls_nm evidence with\n        | pack2 heap' addr (conj _ (conj _ (conj _ (conj preserve _)))) =>\n           let statics' := preserve_cert_fieldstore_over_heap statics preserve in\n           let state' := add_res_new cls_nm (mkState fs classes heap' statics' res reslimit) in\n            throw_exception state' addr\n        end\n     | inleft _ => wrong\n     end\n  end.\n\n(* Instruction implementations *)\n\nDefinition exec_iconst : B.Int32.t -> state -> exec_result :=\n  fun i state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     cont (mkState (mkFrame (rt_int i::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n  | _ => wrong\n  end.\n\nDefinition exec_iarithb : C.integer_bop -> state -> exec_result :=\n  fun op state => match state with\n  | mkState (mkFrame (rt_int z2::rt_int z1::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let result := match op with\n                   | C.iadd => Some (B.Int32.add z1 z2)\n                   | C.isub => Some (B.Int32.sub z1 z2)\n                   | C.imul => Some (B.Int32.mul z1 z2)\n                   | C.iand => Some (B.Int32.logand z1 z2)\n                   | C.ior  => Some (B.Int32.logor z1 z2)\n                   | C.ixor => Some (B.Int32.logxor z1 z2)\n                   | _    => None\n                   end in\n     match result with\n     | None => undefined\n     | Some z =>\n        cont (mkState (mkFrame (rt_int z::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_iarithu : C.integer_uop -> state -> exec_result :=\n  fun op state => match state with\n  | mkState (mkFrame (rt_int i::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let r := match op with C.ineg => B.Int32.neg i end in\n     cont (mkState (mkFrame (rt_int r::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n  | _ => wrong\n  end.\n\nDefinition exec_load : nat -> state -> exec_result :=\n  fun n state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match OptionExt.option_mult (nth_error lvars n) with\n     | None => wrong\n     | Some v =>\n        cont (mkState (mkFrame (v::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition update_lvars : nat -> rt_val -> list (option rt_val) -> option (list (option rt_val)) :=\n  fun n v lvars0 =>\n  let olvars1 := match n with\n                | O => Some lvars0\n                | S n' =>\n                   (* obliterate the preceding value if it is a category 2 one *)\n                   match nth_error lvars0 n' with\n                   | None => None\n                   | Some None => Some lvars0\n                   | Some (Some v) =>\n                      match val_category v with\n                      | C.category1 => Some lvars0\n                      | C.category2 => ListExt.list_update lvars0 n' None\n                      end\n                   end\n                end in\n  match olvars1 with\n  | None => None\n  | Some lvars1 =>\n     match ListExt.list_update lvars1 n (Some v) with\n     | None => None\n     | Some lvars2 =>\n        match val_category v with\n        | C.category1 => Some lvars2\n        | C.category2 => ListExt.list_update lvars2 (S n) None\n        end\n     end\n  end.\n\nDefinition exec_store : nat -> state -> exec_result :=\n  fun n state => match state with\n  | mkState (mkFrame (v::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match update_lvars n v lvars with\n     | None => wrong\n     | Some new_lvars =>\n        cont (mkState (mkFrame op_stack new_lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition update_reslimit (cls:C.class) (mth:C.method) (limit:RA.res) :=\n  match ANN.grants (C.method_annot mth) with\n    | None => limit\n    | Some grant =>\n      if ClassnameSet.mem (C.class_name cls) privilegedclasses then RA.combine limit (RA.res_parse grant) else limit\n  end.\n\nDefinition exec_valreturn : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v::_) _ _ _ omth oclass::nil) classes heap statics res reslimit =>\n     stop (mkState nil classes heap statics res (update_reslimit oclass omth reslimit)) (Some v)\n  | mkState (mkFrame (v::_) _ _ _ omth oclass::mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     cont (mkState (mkFrame (v::op_stack) lvars (S pc) code mth class::fs) classes heap statics res (update_reslimit oclass omth reslimit))\n  | _ =>\n     wrong\n  end.\n\nDefinition exec_return : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame _ _ _ _ omth oclass::nil) classes heap statics res reslimit =>\n     stop (mkState nil classes heap statics res (update_reslimit oclass omth reslimit)) None\n  | mkState (mkFrame _ _ _ _ omth oclass::mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res (update_reslimit oclass omth reslimit))\n  | _ => wrong\n  end.\n\nDefinition exec_goto : Z -> state -> exec_result :=\n  fun offset state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.pc_plus_offset pc offset with\n     | None => wrong\n     | Some new_pc =>\n        cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v with\n     | C.category1 =>\n        cont (mkState (mkFrame (v::v::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | C.category2 =>\n        wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup_x1 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::v2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v1, val_category v2 with\n     | C.category1, C.category1 =>\n        cont (mkState (mkFrame (v1::v2::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | _,_ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup_x2 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::v2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v1, val_category v2 with\n     | C.category1, C.category1 =>\n        match op_stack with\n        | nil => wrong\n        | v3::op_stack =>\n           match val_category v3 with\n           | C.category1 =>\n              cont (mkState (mkFrame (v1::v2::v3::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n           | C.category2 =>\n              wrong\n           end\n        end\n     | C.category1, C.category2 =>\n       cont (mkState (mkFrame (v1::v2::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | _,_ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup2 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v1 with\n     | C.category1 =>\n        match op_stack with\n        | nil => wrong\n        | v2::op_stack =>\n           cont (mkState (mkFrame (v1::v2::v1::v2::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n        end\n     | C.category2 =>\n        cont (mkState (mkFrame (v1::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup2_x1 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::v2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v1 with\n     | C.category1 =>\n        match op_stack with\n        | nil => wrong\n        | v3::op_stack =>\n           cont (mkState (mkFrame (v1::v2::v3::v1::v2::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n        end\n     | C.category2 =>\n        cont (mkState (mkFrame (v1::v2::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_dup2_x2 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::v2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v2 with\n     | C.category1 =>\n        match op_stack with\n        | nil => wrong\n        | v3::op_stack =>\n           match val_category v1, val_category v3 with\n           | C.category1, C.category1 =>\n              match op_stack with\n              | nil => wrong\n              | v4::op_stack =>\n                 match val_category v4 with\n                 | C.category1 =>\n                    cont (mkState (mkFrame (v1::v2::v3::v4::v1::v2::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                 | C.category2 =>\n                    wrong\n                 end\n              end\n           | C.category1, C.category2 =>\n              cont (mkState (mkFrame (v1::v2::v3::v1::v2::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n           | C.category2, C.category1 =>\n              cont (mkState (mkFrame (v1::v2::v3::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n           | C.category2, C.category2 =>\n              wrong\n           end\n        end\n     | C.category2 =>\n        match val_category v1 with\n        | C.category1 => wrong\n        | C.category2 =>\n           cont (mkState (mkFrame (v1::v2::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n        end\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_nop : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n  | _ => wrong\n  end.\n\nDefinition exec_pop : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v with\n     | C.category1 =>\n        cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | C.category2 =>\n        wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_pop2 : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v with\n     | C.category1 =>\n        match op_stack with\n        | nil => wrong\n        | _::op_stack =>\n           cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n        end\n     | C.category2 =>\n        cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nFixpoint make_padding_lvars (n:nat) : list (option rt_val) :=\n  match n with 0 => nil | S n => None::make_padding_lvars n end.\n\nDefinition default_value : C.java_type -> rt_val :=\n  fun ty => match ty with\n  | C.ty_byte    => rt_int B.Int32.zero\n  | C.ty_int     => rt_int B.Int32.zero\n  | C.ty_short   => rt_int B.Int32.zero\n  | C.ty_char    => rt_int B.Int32.zero\n  | C.ty_boolean => rt_int B.Int32.zero\n  | C.ty_double  => rt_double\n  | C.ty_float   => rt_float\n  | C.ty_long    => rt_long\n  | C.ty_ref _   => rt_addr None\n  end.\n\nDefinition exec_putstatic : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame (v::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_fieldref cls_nm field_nm ty) =>\n        match R.resolve_field (C.class_name class) cls_nm field_nm ty classes preclasses with\n        | CP.load_ok classes preserved _ (c,f) (conj c_exists f_exists) =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           match BoolExt.bool_informative (C.field_static f) with\n           | left is_static =>\n              match type_check_rt_val classes heap v ty with\n              | left well_typed =>\n                 let f_ok := (ex_intro _ c (ex_intro _ f (conj c_exists (conj f_exists is_static)))) in\n                 match fieldstore_update statics (C.class_name c) field_nm ty v well_typed f_ok with\n                 | exist statics' _ =>\n                    cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                 end\n              | right _ =>\n                 wrong\n              end\n            | right not_static =>\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n            end\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_getstatic : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_fieldref cls_nm field_nm ty) =>\n        match R.resolve_field (C.class_name class) cls_nm field_nm ty classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ (c,f) (conj c_exists f_exists) =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           match BoolExt.bool_informative (C.field_static f) with\n           | left f_static =>\n              let f_ok := ex_intro _ c (ex_intro _ f (conj c_exists (conj f_exists f_static))) in\n              match fieldstore_lookup statics (C.class_name c) field_nm ty f_ok with\n              | exist v _ =>\n                 cont (mkState (mkFrame (v::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n              end\n           | right not_static =>\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n           end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_new : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_classref cls_nm) =>\n        match R.resolve_class (C.class_name class) cls_nm classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ c c_exists =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           if C.class_abstract c then\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errInstantiation\n           else match BoolExt.bool_informative (C.class_interface c) with\n                | left is_interface =>\n                  throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errInstantiation\n                | right not_interface =>\n                   match heap_new heap cls_nm (ex_intro _ c (conj c_exists not_interface)) with\n                   | pack2 heap addr (conj _ (conj _ (conj _ (conj preserved _)))) => \n                      let statics := preserve_cert_fieldstore_over_heap statics preserved in\n                      let state' := mkState (mkFrame (rt_addr (Some addr)::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit in\n                       cont (add_res_new cls_nm state')\n                   end\n                end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_getfield : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_fieldref cls_nm field_nm ty) =>\n        match R.resolve_field (C.class_name class) cls_nm field_nm ty classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ (c,f) (conj H1 H2) =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           if C.field_static f then\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n           else\n              match a with\n              | None =>\n                 throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errNullPointer\n              | Some a =>\n                 match heap_lookup_field heap a (C.class_name c) (C.field_name f) ty with\n                 | inleft (exist v _) =>\n                    cont (mkState (mkFrame (v::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                 | inright _ =>\n                    wrong\n                 end\n              end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_putfield : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame (v::rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_fieldref cls_nm field_nm ty) =>\n        match R.resolve_field (C.class_name class) cls_nm field_nm ty classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ (c,f) (conj H1 H2) =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           if C.field_static f then\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n           else if C.field_final f &&\n                   (if B.Classname.eq_dec (C.class_name class) (C.class_name c) then false else true) then\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIllegalAccess\n           else\n              match a with\n              | None =>\n                 throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errNullPointer\n              | Some a =>\n                 match type_check_rt_val classes heap v ty with\n                 | left welltyped =>\n                    match heap_update_field heap a (C.class_name c) (C.field_name f) ty v welltyped with\n                    | inleft (exist heap (conj _ (conj preserved _))) =>\n                       let statics := preserve_cert_fieldstore_over_heap statics preserved in\n                       cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                    | inright _ =>\n                       wrong\n                    end\n                 | right _ =>\n                    wrong\n                 end\n              end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nFixpoint pop_n (n:nat) (l:list rt_val) {struct n} : option (list rt_val * list rt_val) :=\n  match n, l with\n  | 0,   l     => Some (nil,l)\n  | S n, nil   => None\n  | S n, v::vs => match pop_n n vs with None => None | Some (l',rest) => Some (v::l', rest) end\n  end.\n\nFixpoint stack_to_lvars (stack:list rt_val) (required_lvars:nat) {struct stack} : option (list (option rt_val)) :=\n  match stack with\n  | nil      => Some (make_padding_lvars required_lvars)\n  | v::stack =>\n     match val_category v, required_lvars with\n     | C.category1, S n     => \n        match stack_to_lvars stack n with\n        | None => None\n        | Some stack' => Some (Some v::stack')\n        end\n     | C.category2, S (S n) =>\n        match stack_to_lvars stack n with\n        | None => None\n        | Some stack' => Some (Some v::None::stack')\n        end\n     | _, _ => None\n     end\n  end.\n\nDefinition basic_invoke : C.class -> C.method -> list rt_val -> state -> exec_result :=\n  fun class method args state => match state with\n  | mkState fs classes heap statics res reslimit =>\n     match C.method_code method with\n       (* Callers rule out abstract methods *)\n     | None => \n       match NATIVE.native_invoke class method args state with\n         | None => wrong\n         | Some (NATIVE.Build_result (NATIVE.exn exn) classes' heap' statics' res' reslimit') =>\n           throw_exception (mkState fs classes' heap' statics' res' reslimit') exn\n         | Some (NATIVE.Build_result NATIVE.void classes' heap' statics' res' reslimit') =>\n           match fs with\n             | (mkFrame op_stack lvars pc code mth class::fs') =>\n               cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs') classes' heap' statics' res' reslimit')\n             | _ => wrong\n           end\n         | Some (NATIVE.Build_result (NATIVE.val val) classes' heap' statics' res' reslimit') =>\n           match fs with\n             | (mkFrame op_stack lvars pc code mth class::fs') =>\n               cont (mkState (mkFrame (val::op_stack) lvars (S pc) code mth class::fs') classes' heap' statics' res' reslimit')\n             | _ => wrong\n           end\n       end\n     | Some code =>\n        match stack_to_lvars args (C.code_max_lvars code) with\n        | None => wrong\n        | Some lvars =>\n           cont (mkState (mkFrame nil lvars 0 code method class::fs) classes heap statics res reslimit)\n        end\n     end\n  end.\n\nDefinition basic_invokestatic : B.Classname.t -> B.Classname.t -> B.Methodname.t -> C.descriptor -> list rt_val -> state -> exec_result :=\n  fun caller clsname meth_name meth_desc args state => match state with\n  | mkState fs classes heap statics res reslimit =>\n     match R.resolve_method caller clsname meth_name meth_desc classes preclasses with\n     | CP.load_err classes preserved _ e =>\n        let heap := preserve_cert_heap heap preserved in\n        let statics := preserve_cert_fieldstore_over_classes statics preserved in\n        throw_builtin_exception (mkState fs classes heap statics res reslimit) e\n     | CP.load_ok classes preserved _ (class,method) (conj H1 H2) =>\n        let heap := preserve_cert_heap heap preserved in\n        let statics := preserve_cert_fieldstore_over_classes statics preserved in\n        if C.method_static method then\n           basic_invoke class method args (mkState fs classes heap statics res reslimit)\n        else\n           throw_builtin_exception (mkState fs classes heap statics res reslimit) CP.errIncompatibleClassChange\n     end\n  end.\n\nDefinition exec_invokestatic : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_methodref clsname methname methdescrip) =>\n        match pop_n (length (C.descriptor_arg_types methdescrip)) op_stack with\n        | None => wrong\n        | Some (args, op_stack) =>\n           let state' := mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit in\n           basic_invokestatic (C.class_name class) clsname methname methdescrip (rev args) state'\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\n(* FIXME: need to properly understand the ACC_SUPER flag on page 284 *)\nDefinition exec_invokespecial : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_methodref clsname methname methdescrip) =>\n        match R.resolve_method (C.class_name class) clsname methname methdescrip classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ (c,m) (conj H1 H2) =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           match pop_n (length (C.descriptor_arg_types methdescrip)) op_stack with\n           | Some (preargs, rt_addr (Some addr)::op_stack) =>\n              let args := rt_addr (Some addr)::rev preargs in\n              if C.method_static m then\n                 throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n              else if C.method_abstract m then\n                 throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errAbstractMethod\n              else (* FIXME: need a special check for instance initialization methods *)\n                 let state' := mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit in\n                 basic_invoke c m args state'\n           | Some (args, rt_addr None::op_stack) =>\n              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errNullPointer\n           | _ => wrong\n           end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_invokevirtual : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state =>\n    match state with\n      | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n        match C.ConstantPool.lookup (C.class_constantpool class) idx with\n          | Some (C.cpe_methodref clsname methname methdescrip) =>\n            match B.Methodname.eq_dec methname B.init with\n              | left _ => wrong (* cannot call methods called '<init>' via invokevirtual *)\n              | right _ =>\n                match R.resolve_method (C.class_name class) clsname methname methdescrip classes preclasses with\n                  | CP.load_err classes preserved _ e =>\n                    let heap := preserve_cert_heap heap preserved in\n                      let statics := preserve_cert_fieldstore_over_classes statics preserved in\n                        throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n                  | CP.load_ok classes preserved _ (c,m) (conj H1 H2) =>\n                    let heap := preserve_cert_heap heap preserved in\n                      let statics := preserve_cert_fieldstore_over_classes statics preserved in\n                        if C.method_static m then\n                          throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n                          else\n                            match pop_n (length (C.descriptor_arg_types methdescrip)) op_stack with\n                              | Some (preargs, rt_addr (Some addr)::op_stack) =>\n                                let args := rt_addr (Some addr)::rev preargs in\n                                  match heap_lookup_class heap addr with\n                                    | inleft (exist cls_nm addr_is_cls_nm) =>\n                                      if A.is_assignable classes (C.ty_obj cls_nm) (C.ty_obj clsname) then\n                                        let evidence := object_class_implies_class_exists addr_is_cls_nm in\n                                          match VM.lookup_virtual_method classes cls_nm (methname, methdescrip) evidence with\n                                            | Some (pack2 c' m' _) =>\n                                              if C.method_abstract m' then\n                                                throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errAbstractMethod\n                                                else\n                                                  let state' := mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit in\n                                                    basic_invoke c' m' args state'\n                                            | None =>\n                                              throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errAbstractMethod\n                                          end\n                                        else\n                                          wrong\n                                    | inright _ => wrong\n                                  end\n                              | Some (_, rt_addr None::op_stack) =>\n                                throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errNullPointer\n                              | _ => wrong\n                            end\n                end\n            end\n          | _ => wrong\n        end\n      | _ => wrong\n    end.\n\nDefinition exec_invokeinterface : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_interfacemethodref clsname methname methdescrip) =>\n       match B.Methodname.eq_dec methname B.init with\n       | left _ => wrong (* cannot call methods called '<init>' via invokeinterface *)\n       | right _ =>\n         match R.resolve_interface_method (C.class_name class) clsname methname methdescrip classes preclasses with\n         | CP.load_err classes preserved _ e =>\n            let heap := preserve_cert_heap heap preserved in\n            let statics := preserve_cert_fieldstore_over_classes statics preserved in\n            throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n         | CP.load_ok classes preserved _ (c,m) (conj H1 H2) =>\n            let heap := preserve_cert_heap heap preserved in\n            let statics := preserve_cert_fieldstore_over_classes statics preserved in\n            if C.method_static m then (* FIXME: this should be automatic from the fact that this is an interface *)\n               throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n            else\n               match pop_n (length (C.descriptor_arg_types methdescrip)) op_stack with\n               | Some (preargs, rt_addr (Some addr)::op_stack) =>\n                  let args := rt_addr (Some addr)::rev preargs in\n                  match heap_lookup_class heap addr with\n                  | inleft (exist cls_nm addr_is_cls_nm) =>\n                     if A.is_assignable classes (C.ty_obj cls_nm) (C.ty_obj clsname) then\n                       let evidence := object_class_implies_class_exists addr_is_cls_nm in\n                       match VM.lookup_virtual_method classes cls_nm (methname, methdescrip) evidence with\n                       | Some (pack2 c' m' _) =>\n                          if C.method_abstract m' then\n                             throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errAbstractMethod\n                          else\n                             let state' := mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit in\n                             basic_invoke c' m' args state'\n                       | None =>\n                          throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errAbstractMethod\n                       end\n                     else\n                       throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errIncompatibleClassChange\n                  | _ => wrong\n                  end\n               | Some (_, rt_addr None::op_stack) =>\n                  throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errNullPointer\n               | _ => wrong\n               end\n         end\n       end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\n\nDefinition exec_if : C.cmp -> Z -> state -> exec_result :=\n  fun test offset state => match state with\n  | mkState (mkFrame (rt_int z::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let test_succeeded :=\n          match test with\n          | C.cmp_eq => B.Int32.eq z B.Int32.zero\n          | C.cmp_ne => B.Int32.neq z B.Int32.zero\n          | C.cmp_lt => B.Int32.lt z B.Int32.zero\n          | C.cmp_le => B.Int32.le z B.Int32.zero\n          | C.cmp_gt => B.Int32.gt z B.Int32.zero\n          | C.cmp_ge => B.Int32.ge z B.Int32.zero\n          end in\n     match (if test_succeeded then (C.pc_plus_offset pc offset) else (Some (S pc))) with\n     | None => wrong\n     | Some new_pc =>\n        cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_if_icmp : C.cmp -> Z -> state -> exec_result :=\n  fun test offset state => match state with\n  | mkState (mkFrame (rt_int z2::rt_int z1::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let test_succeeded :=\n          match test with\n          | C.cmp_eq => B.Int32.eq z1 z2\n          | C.cmp_ne => B.Int32.neq z1 z2\n          | C.cmp_lt => B.Int32.lt z1 z2\n          | C.cmp_le => B.Int32.le z1 z2\n          | C.cmp_gt => B.Int32.gt z1 z2\n          | C.cmp_ge => B.Int32.ge z1 z2\n          end in\n     match (if test_succeeded then (C.pc_plus_offset pc offset) else (Some (S pc))) with\n     | None => wrong\n     | Some new_pc =>\n        cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_swap : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (v1::v2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match val_category v1, val_category v2 with\n     | C.category1, C.category1 =>\n        cont (mkState (mkFrame (v2::v1::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | _,_ =>\n        wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_iinc : nat -> B.Int32.t -> state -> exec_result :=\n  fun n c state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match OptionExt.option_mult (nth_error lvars n) with\n     | Some (rt_int z) =>\n        match update_lvars n (rt_int (B.Int32.add z c)) lvars with\n        | None => wrong\n        | Some new_lvars =>\n           cont (mkState (mkFrame op_stack new_lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_aconst_null : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     cont (mkState (mkFrame (rt_addr None::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n  | _ => wrong\n  end.\n\nDefinition option_addr_eq_dec : forall (a b:option Heap.addr_t), {a=b}+{a<>b}.\ndecide equality.\ngeneralize a a0. decide equality.\nDefined.\n\nDefinition exec_if_acmp : C.acmp -> Z -> state -> exec_result :=\n  fun test offset state => match state with\n  | mkState (mkFrame (rt_addr a1::rt_addr a2::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let test_succeeded :=\n          match test with\n          | C.acmp_eq => if option_addr_eq_dec a1 a2 then true else false\n          | C.acmp_ne => if option_addr_eq_dec a1 a2 then false else true\n          end in\n     match (if test_succeeded then (C.pc_plus_offset pc offset) else (Some (S pc))) with\n     | None => wrong\n     | Some new_pc =>\n        cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_if_nonnull : Z -> state -> exec_result :=\n  fun offset state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match a with\n     | None =>\n        cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | Some _ =>\n        match C.pc_plus_offset pc offset with\n        | None => wrong\n        | Some new_pc =>\n           cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n        end\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_if_null : Z -> state -> exec_result :=\n  fun offset state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match a with\n     | Some _ =>\n        cont (mkState (mkFrame op_stack lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | None =>\n        match C.pc_plus_offset pc offset with\n        | None => wrong\n        | Some new_pc =>\n           cont (mkState (mkFrame op_stack lvars new_pc code mth class::fs) classes heap statics res reslimit)\n        end\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_ldc : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_int i) =>\n        cont (mkState (mkFrame (rt_int i::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n     | _ => undefined (* FIXME: do floats and strings *)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_ldc2 : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | _ => undefined (* FIXME: do longs and doubles *)\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_instanceof : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_classref cls_nm) =>\n        match R.resolve_class (C.class_name class) cls_nm classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ T H =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           match a with\n           | None => (* It was a null pointer *)\n              cont (mkState (mkFrame (rt_int B.Int32.zero::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n           | Some a =>\n              match heap_lookup_class heap a with\n              | inleft (exist obj_cls_nm _) =>\n                 if A.is_assignable classes (C.ty_obj obj_cls_nm) (C.ty_obj cls_nm) then\n                    cont (mkState (mkFrame (rt_int B.Int32.one::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                 else\n                    cont (mkState (mkFrame (rt_int B.Int32.zero::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n              | inright _ => wrong\n              end\n           end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_checkcast : B.ConstantPoolRef.t -> state -> exec_result :=\n  fun idx state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match C.ConstantPool.lookup (C.class_constantpool class) idx with\n     | Some (C.cpe_classref cls_nm) =>\n        match R.resolve_class (C.class_name class) cls_nm classes preclasses with\n        | CP.load_err classes preserved _ e =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) e\n        | CP.load_ok classes preserved _ T H =>\n           let heap := preserve_cert_heap heap preserved in\n           let statics := preserve_cert_fieldstore_over_classes statics preserved in\n           match a with\n           | None => (* null pointer *)\n              cont (mkState (mkFrame (rt_addr None::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n           | Some a =>\n              match heap_lookup_class heap a with\n              | inleft (exist obj_cls_nm _) =>\n                 if A.is_assignable classes (C.ty_obj obj_cls_nm) (C.ty_obj cls_nm) then\n                    cont (mkState (mkFrame (rt_addr (Some a)::op_stack) lvars (S pc) code mth class::fs) classes heap statics res reslimit)\n                 else\n                    throw_builtin_exception (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) CP.errClassCast\n              | inright _ => wrong\n              end\n           end\n        end\n     | _ => wrong\n     end\n  | _ => wrong\n  end.\n\nDefinition exec_athrow : state -> exec_result :=\n  fun state => match state with\n  | mkState (mkFrame (rt_addr a::op_stack) lvars pc code mth class::fs) classes heap statics res reslimit =>\n     let state := (mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit) in\n     match a with\n     | None =>\n        throw_builtin_exception state CP.errNullPointer\n     | Some r =>\n        match heap_lookup_class heap r with\n        | inleft (exist cls_nm _) =>\n           if A.is_assignable classes (C.ty_obj cls_nm) (C.ty_obj B.java_lang_Throwable) then\n              throw_exception state r\n           else\n              wrong\n        | inright _ => wrong\n        end\n     end\n  | _ => wrong\n  end.\n\nDefinition exec : state -> exec_result := \n  fun state => match state with\n  | mkState (mkFrame op_stack lvars pc code mth class::fs) classes heap statics res reslimit =>\n     match nth_error (C.code_code code) pc with\n     | None => wrong\n     | Some op =>\n  match op with\n  (* Constants *)\n  | C.op_iconst i         => exec_iconst i\n  | C.op_ldc idx          => exec_ldc idx\n  | C.op_ldc2 idx         => exec_ldc2 idx\n\n  (* Arithmetic *)\n  | C.op_iinc n c         => exec_iinc n c\n  | C.op_iarithb op       => exec_iarithb op\n  | C.op_iarithu op       => exec_iarithu op\n\n  (* Local variables *)\n  | C.op_load ty n        => exec_load n\n  | C.op_store ty n       => exec_store n\n\n  (* Stack operations *)\n  | C.op_dup              => exec_dup\n  | C.op_dup_x1           => exec_dup_x1\n  | C.op_dup_x2           => exec_dup_x2\n  | C.op_dup2             => exec_dup2\n  | C.op_dup2_x1          => exec_dup2_x1\n  | C.op_dup2_x2          => exec_dup2_x2\n  | C.op_nop              => exec_nop\n  | C.op_pop              => exec_pop\n  | C.op_pop2             => exec_pop2\n  | C.op_swap             => exec_swap\n\n  (* OO *)\n  | C.op_aconst_null      => exec_aconst_null\n  | C.op_invokestatic idx => exec_invokestatic idx\n  | C.op_putstatic idx    => exec_putstatic idx\n  | C.op_getstatic idx    => exec_getstatic idx\n  | C.op_putfield idx     => exec_putfield idx\n  | C.op_getfield idx     => exec_getfield idx\n  | C.op_new idx          => exec_new idx\n  | C.op_invokeinterface idx => exec_invokeinterface idx\n  | C.op_invokespecial idx=> exec_invokespecial idx\n  | C.op_invokevirtual idx=> exec_invokevirtual idx\n  | C.op_instanceof idx   => exec_instanceof idx\n  | C.op_checkcast idx    => exec_checkcast idx\n\n  (* Flow control *)\n  | C.op_if test offset   => exec_if test offset\n  | C.op_if_acmp test offset => exec_if_acmp test offset\n  | C.op_if_icmp test offset => exec_if_icmp test offset\n  | C.op_ifnonnull offset => exec_if_nonnull offset\n  | C.op_ifnull offset    => exec_if_null offset\n  | C.op_valreturn ty     => exec_valreturn\n  | C.op_return           => exec_return\n  | C.op_goto offset      => exec_goto offset\n  | C.op_athrow           => exec_athrow\n\n  | _ => fun s => undefined\n  end state\n  end\n  | _ => wrong\n  end.\n\nDefinition init : B.Classname.t -> B.Methodname.t -> C.descriptor -> list rt_val -> state -> exec_result :=\n  fun clsname methname methdescrip args state => match state with\n  | mkState nil classes heap statics res reslimit =>\n     basic_invokestatic clsname clsname methname methdescrip args state\n  | _ => wrong\n  end.\n\nEnd WithPreclasses.\n\nEnd Execution.\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/Execution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16986847988990966}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition data_create_unknown1_spec (g_rd: Pointer) (data_addr: Z64) (map_addr: Z64) (g_data': Pointer) (adt: RData) : option (RData * Z64) :=\n    match map_addr, data_addr with\n    | VZ64 map_addr, VZ64 data_addr =>\n      rely is_int64 map_addr; rely is_int64 data_addr;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := idx3 in\n      rely (peq (base g_rd) ginfo_loc);\n      rely (peq (base g_data') ginfo_loc);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n      let rd_gidx := (offset g_rd) in\n      let data_gidx := offset g_data' in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely prop_dec (__addr_to_gidx data_addr = data_gidx);\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx; rely is_gidx root_gidx; rely is_gidx data_gidx;\n      when adt == query_oracle adt;\n      let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n      (* hold root lock *)\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n      rely (gtype groot =? GRANULE_STATE_TABLE);\n      (* walk deeper root *)\n      let entry0 := (g_data (gnorm groot)) @ idx0 in\n      rely is_int64 entry0;\n      let phys0 := __entry_to_phys entry0 3 in\n      let lv1_gidx := __addr_to_gidx phys0 in\n      if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n        (* level 1 valid, hold level 1 lock *)\n        let glv1 := (gs (share adt)) @ lv1_gidx in\n        rely prop_dec (glock glv1 = None);\n        rely (tbl_level (gaux glv1) =? 1);\n        (* walk deeper level 1 *)\n        rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n        rely (gtype glv1 =? GRANULE_STATE_TABLE);\n        let entry1 := (g_data (gnorm glv1)) @ idx1 in\n        rely is_int64 entry1;\n        let phys1 := __entry_to_phys entry1 3 in\n        let lv2_gidx := __addr_to_gidx phys1 in\n        if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n          (* level 2 valid, hold level 2 lock *)\n          let adt := adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv2_gidx) :: log adt} in\n          let glv2 := (gs (share adt)) @ lv2_gidx in\n          rely (tbl_level (gaux glv2) =? 2);\n          rely prop_dec (glock glv2 = None);\n          (* walk deeper level 2 *)\n          rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);\n          rely (gtype glv2 =? GRANULE_STATE_TABLE);\n          let entry2 := (g_data (gnorm glv2)) @ idx2 in\n          rely is_int64 entry2;\n          let phys2 := __entry_to_phys entry2 3 in\n          let lv3_gidx := __addr_to_gidx phys2 in\n          if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then\n            (* level 2 valid, hold level 2 lock *)\n            when adt == query_oracle adt;\n            let adt := adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv3_gidx) :: log adt} in\n            let glv3 := (gs (share adt)) @ lv3_gidx in\n            rely prop_dec (glock glv3 = None);\n            rely (tbl_level (gaux glv3) =? 3);\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in\n            (* create data *)\n            let llt_gidx := lv3_gidx in\n            let idx := idx3 in\n            let gn_llt := (gs (share adt)) @ llt_gidx in\n            let gn_data := (gs (share adt)) @ data_gidx in\n            rely (g_tag (ginfo gn_llt) =? GRANULE_STATE_TABLE);\n            rely (gtype gn_llt =? GRANULE_STATE_TABLE);\n            rely (gtype gn_data =? GRANULE_STATE_DELEGATED);\n            rely prop_dec (glock gn_data = Some CPU_ID);\n            rely (tbl_level (gaux gn_data) =? 0);\n            let llt_pte := (g_data (gnorm gn_llt)) @ idx in\n            rely is_int64 llt_pte;\n            if PTE_TO_IPA_STATE llt_pte =? IPA_STATE_VACANT then\n              let gdata' := gn_data {gaux: mkAuxillaryVars 0 0 map_addr} in\n              let pte_val := Z.lor (IPA_STATE_TO_PTE IPA_STATE_ABSENT) data_addr in\n              let llt' := (g_data (gnorm gn_llt)) # idx == pte_val in\n              let gllt' := gn_llt {ginfo : (ginfo gn_llt) {g_refcount : g_refcount (ginfo gn_llt) + 1}}\n                                  {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n              Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: log adt}\n                        {share : (share adt) {gs : ((gs (share adt)) # data_gidx == gdata') # llt_gidx == gllt'}},\n                    VZ64 0)\n            else Some (adt {log: EVT CPU_ID (REL llt_gidx gn_llt {glock: Some CPU_ID}) :: log adt}, VZ64 1)\n          else\n            (* level 3 invalid *)\n            Some (adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: log adt}\n                      {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n        else\n          (* level 2 invalid *)\n          Some (adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: log adt}\n                    {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n      else\n        (* level 1 invalid *)\n        Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef1/Specs/data_create_unknown1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16986847291072465}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import malloc.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\nRequire Import VSU_malloc_definitions.\nLocal Open Scope logic.\n(*\nDefinition Gprog : funspecs := external_specs ++ private_specs.\n*)\nLemma body_malloc_large: semax_body MF_Vprog MF_Gprog f_malloc_large malloc_large_spec.\nProof.\nstart_function. \nforward_call (n+WA+WORD). (*! t'1 = mmap0(nbytes+WASTE+WORD ...) !*)\n{ entailer!. }\n(*{ rep_lia. }*)\nIntros p.\n(* NOTE could split cases here; then two symbolic executions but simpler ones *)\nforward_if. (*! if (p==NULL) !*)\n- (* typecheck guard *) \n  if_tac; entailer!.\n- (* case p == NULL *) \n  forward. (*! return NULL  !*)\n  Exists (Vint (Int.repr 0)).\n  if_tac; entailer!. (* cases in post of mmap *)\n- (* case p <> NULL *) \n  if_tac. (* cases in post of mmap *)\n  + (* impossible case *)\n    exfalso. destruct p; try contradiction; simpl in *.\n  + assert_PROP (\n        (force_val\n           (sem_add_ptr_int tuint Signed\n                            (force_val\n                               (sem_cast_pointer\n                                  (force_val\n                                     (sem_add_ptr_int tschar Unsigned p\n                                                      (Vint\n                                                         (Int.sub\n                                                            (Int.mul (Ptrofs.to_int (Ptrofs.repr 4)) (Int.repr 2))\n                                                            (Ptrofs.to_int (Ptrofs.repr 4))))))))\n                            (Vint (Int.repr 0))) = field_address tuint [] (offset_val WA p)) ).\n    (* painful pointer reasoning to enable forward (p+WASTE)[0] = nbytes *)\n    { entailer!. \n      destruct p; try contradiction; simpl.\n      normalize.\n      unfold field_address.\n      rewrite if_true.\n      { simpl.  normalize. }\n      hnf. (* drill down *) \n      repeat split; auto.\n      - (* size compat *)\n        red. \n        match goal with | H:size_compatible' _ _ |- _ => red in H end.\n        unfold Ptrofs.add.\n        rewrite (Ptrofs.unsigned_repr WA) by rep_lia.\n        rewrite Ptrofs.unsigned_repr by rep_lia.\n        simpl sizeof. rep_lia.\n      - (* align compat *)\n        red.\n        eapply align_compatible_rec_by_value; try reflexivity.\n        simpl in *. unfold natural_alignment in *. unfold Z.divide in *.\n        match goal with | HA: (exists z:Z, _) /\\ _ |- _ => destruct HA as [Hz Hlim] end. \n        inv Hz.\n        rewrite <- (Ptrofs.repr_unsigned i). \n        match goal with | HA: Ptrofs.unsigned _ = _ |- _ => rewrite HA end. \n        exists (2*x+1). change WA with 4.\n        rewrite ptrofs_add_repr. rewrite Ptrofs.unsigned_repr.\n        lia. rep_lia.\n    }\n    rewrite malloc_large_chunk; try rep_lia; try assumption.\n    Intros. (* flatten sep *)\n    forward. (*! (p+WASTE)[0] = nbytes;  !*)\n    forward. (*! return (p+WASTE+WORD);  !*)\n    (* postcond *)\n    Exists (offset_val (WA+WORD) p).\n    entailer!.\n    simpl.\n    if_tac. \n    { exfalso. destruct p; try contradiction; simpl in *. \n      match goal with | HA: Vptr _ _  = nullval |- _ => inv HA end. }\n    unfold malloc_token'.\n    Exists n.\n    unfold malloc_tok.\n    if_tac. rep_lia. entailer!. \n    { apply malloc_compatible_offset; try rep_lia; try apply WORD_ALIGN_aligned.\n      replace (n+(WA+WORD)) with (n + WA + WORD) by lia. assumption. }\n    cancel. \n    (* split off the token's share of chunk *)\n    rewrite <- memory_block_Ews_join.\n    (* data_at_ from memory_block *)\n    replace (n - n) with 0 by lia.\n    rewrite memory_block_zero.  entailer!.\nQed.\n(*\nDefinition module := [mk_body body_malloc_large].\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_large.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16986847291072465}}
{"text": "Set Implicit Arguments.\nRequire Export Shared.\nRequire Export Ascii String.\nRequire Export LibTactics LibLogic LibReflect LibList\n  LibOperation LibStruct LibNat LibEpsilon LibFunc LibHeap.\nRequire Fappli_IEEE Fappli_IEEE_bits.\n\n\n(************************************************************)\n(************************************************************)\n(************************************************************)\n(************************************************************)\n(** * Javascript *)\n\n(**************************************************************)\n(** ** Numerical values *)\n\nDefinition number := \n  Fappli_IEEE_bits.binary64.\n\nDefinition number_of_int : int -> number := \n  Fappli_IEEE_bits.b64_of_bits.\n\nDefinition number_add : number -> number -> number :=\n  Fappli_IEEE_bits.b64_plus Fappli_IEEE.mode_NE.\n\nDefinition number_mult : number -> number -> number :=\n  Fappli_IEEE_bits.b64_mult Fappli_IEEE.mode_NE.\n\nDefinition number_div : number -> number -> number :=\n  Fappli_IEEE_bits.b64_div Fappli_IEEE.mode_NE.\n\n\n(**************************************************************)\n(** ** Datatypes *)\n\n(** Binary operators *)\n\nInductive binary_op :=\n  | binary_op_add\n  | binary_op_mult\n  | binary_op_div\n  | binary_op_equal\n  | binary_op_instanceof\n  | binary_op_in.\n\n(* Unary operator *)\n\nInductive unary_op :=\n  | unary_op_not\n  | unary_op_delete\n  | unary_op_typeof\n  | unary_op_pre_incr\n  | unary_op_post_incr\n  | unary_op_pre_decr\n  | unary_op_post_decr\n  | unary_op_void.\n\n(** Grammar of literals *)\n\nInductive literal :=\n  | literal_null : literal\n  | literal_bool : bool -> literal\n  | literal_number : number -> literal\n  | literal_string : string -> literal.\n\n(** Grammar of expressions *)\n\nInductive expr :=\n  | expr_this : expr\n  | expr_variable : string -> expr \n  | expr_literal : literal -> expr\n  | expr_object : list (string * expr) -> expr\n  | expr_function : option string -> list string -> expr -> expr \n  | expr_access : expr -> expr -> expr\n  | expr_member : expr -> string -> expr\n  | expr_new : expr -> list expr -> expr\n  | expr_call : expr -> list expr -> expr\n  | expr_unary_op : unary_op -> expr -> expr\n  | expr_binary_op : expr -> binary_op -> expr -> expr\n  | expr_and : expr -> expr -> expr\n  | expr_or : expr -> expr -> expr  \n  | expr_assign : expr -> option binary_op -> expr -> expr \n  | expr_seq : expr -> expr -> expr\n  | expr_var_decl : string -> option expr -> expr \n  | expr_if : expr -> expr -> option expr -> expr\n  | expr_while : expr -> expr -> expr\n  | expr_with : expr -> expr -> expr\n  | expr_skip.\n\n\n(**************************************************************)\n(** ** Data types for the semantics *)\n\n(** Locations (address of objects) *)\n\nInductive loc :=\n  | loc_normal : nat -> loc\n  | loc_null : loc\n  | loc_scope : loc\n  | loc_global : loc\n  | loc_eval : loc\n  | loc_obj_proto : loc\n  | loc_func_proto : loc\n  | loc_eval_proto : loc.\n\n(** Field names *)\n\nInductive field :=\n  | field_normal : string -> field\n  | field_proto : field\n  | field_body : field\n  | field_scope: field\n  | field_this : field.\n\n(** The particular \"prototype\" field name *)\n\nDefinition field_normal_prototype := \n  field_normal \"prototype\".\n\n(** Reference: pair of a location and a field *)\n\nInductive ref := \n  | Ref : loc -> field -> ref.\n\n(** Scope chain *)\n\nDefinition scope := list loc.\n\n(** Grammar of values *)\n\nInductive value :=\n  | value_undef : value \n  | value_bool : bool -> value\n  | value_number : number -> value \n  | value_string : string -> value\n  | value_loc : loc -> value\n  | value_scope : scope -> value\n  | value_body : list string -> expr -> value.\n\n(** Result of an evaluation: a value or a reference *)\n\nInductive result :=\n  | result_value : value -> result\n  | result_ref : ref -> result.\n\n(** Heaps are finite maps from references to values. \n    Heaps are based on the \"heap\" typed defined in [Shared.v].\n    The values [heap_write], [heap_read] and [heap_binds]\n    and [indom] are also defined in [Shared.v]. *)\n\nModule Heap := LibHeap.HeapList.\n\nDefinition heap := Heap.heap ref value.\n\n(** Coercions *)\n\nCoercion field_normal : string >-> field.\nCoercion value_number : number >-> value.\nCoercion value_string : string >-> value.\nCoercion value_loc : loc >-> value.\nCoercion result_value : value >-> result.\nCoercion result_ref : ref >-> result.\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/JsSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.31069438959712015, "lm_q1q2_score": 0.16986847181106346}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nDefinition sll_free_type :=\n  forall (vprogs : ptr),\n  {(vghosts : seq nat)},\n  STsep (\n    fun h =>\n      let: (x) := vprogs in\n      let: (s) := vghosts in\n      exists h_sll_xs_1,\n      h = h_sll_xs_1 /\\ sll x s h_sll_xs_1,\n    [vfun (_: unit) h =>\n      let: (x) := vprogs in\n      let: (s) := vghosts in\n      h = empty\n    ]).\n\nProgram Definition sll_free : sll_free_type :=\n  Fix (fun (sll_free : sll_free_type) vprogs =>\n    let: (x) := vprogs in\n    Do (\n      if (x) == (null)\n      then\n        ret tt\n      else\n        vx1 <-- @read nat x;\n        nxtx1 <-- @read ptr (x .+ 1);\n        sll_free (nxtx1);;\n        dealloc x;;\n        dealloc (x .+ 1);;\n        ret tt\n    )).\nObligation Tactic := intro; move=>x; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>s.\nex_elim h_sll_xs_1.\nmove=>[sigma_self].\nsubst h_self.\nmove=>H_sll_xs_1.\nssl_ghostelim_post.\nssl_open ((x) == (null)) H_sll_xs_1.\nmove=>[phi_sll_xs_10].\nmove=>[sigma_sll_xs_1].\nsubst h_sll_xs_1.\ntry rename h_sll_xs_1 into h_sll_x_1.\ntry rename H_sll_xs_1 into H_sll_x_1.\nssl_emp;\nsslauto.\nex_elim vx s1x nxtx.\nex_elim h_sll_nxtxs1x_0x.\nmove=>[phi_sll_xs_10].\nmove=>[sigma_sll_xs_1].\nsubst h_sll_xs_1.\nmove=>H_sll_nxtxs1x_0x.\ntry rename h_sll_xs_1 into h_sll_xvxs1x_1.\ntry rename H_sll_xs_1 into H_sll_xvxs1x_1.\nssl_read x.\ntry rename vx into vx1.\ntry rename h_sll_xvxs1x_1 into h_sll_xvx1s1x_1.\ntry rename H_sll_xvxs1x_1 into H_sll_xvx1s1x_1.\nssl_read (x .+ 1).\ntry rename nxtx into nxtx1.\ntry rename h_sll_nxtxs1x_0x into h_sll_nxtx1s1x_0x.\ntry rename H_sll_nxtxs1x_0x into H_sll_nxtx1s1x_0x.\ntry rename h_sll_x1s1_11 into h_sll_nxtx1s1x_0x.\ntry rename H_sll_x1s1_11 into H_sll_nxtx1s1x_0x.\nssl_call_pre (h_sll_nxtx1s1x_0x).\nssl_call (s1x).\nexists (h_sll_nxtx1s1x_0x);\nsslauto.\nssl_frame_unfold.\nmove=>h_call0.\nmove=>[sigma_call0].\nsubst h_call0.\nstore_valid.\nssl_dealloc x.\nssl_dealloc (x .+ 1).\nssl_emp;\nsslauto.\nQed.", "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/standard/sll/sll_free.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.16986846942113226}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*       for the C functions implemented in the MShareOp layer         *)\n(*                                                                     *)\n(*                                                                     *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import PTNewGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import XOmega.\n\nRequire Import AbstractDataType.\n\nRequire Import MShareOp.\nRequire Import MShareIntroCSource.\nRequire Import ShareOpGenSpec.\n\nModule MSHAREOPCODE.\n\n  (*shared_mem_arg  never checked that the second args is >= 0, but checked\nthe first one twice*)\n  Lemma shared_mem_arg_rev: forall pid1 pid2,\n                              shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                              = shared_mem_arg (Int.unsigned pid2) (Int.unsigned pid1).\n  Proof.\n    unfold shared_mem_arg. intros.\n    destruct (zle_lt 0 (Int.unsigned pid1) 64), (zle_lt 0 (Int.unsigned pid2) 64),\n             (zeq (Int.unsigned pid1) (Int.unsigned pid2)) eqn:peq; trivial;\n    try rewrite e, zeq_true; try rewrite zeq_false; trivial; auto.\n  Qed.\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n\n    Section GETSHAREDMEMSTATUSSEEN.\n\n      Let L: compatlayer (cdata RData) :=\n        get_shared_mem_state \u21a6 gensem get_shared_mem_state_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n\n      Section GetSharedMemStatusSeenBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        Variable bget_shared_mem_state: block.\n\n        Hypothesis hget_shared_mem_state1 : Genv.find_symbol ge get_shared_mem_state = Some bget_shared_mem_state.\n\n        Hypothesis hget_shared_mem_state2 : Genv.find_funct_ptr ge bget_shared_mem_state =\n        Some (External (EF_external get_shared_mem_state\n                                    (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default))\n                       (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        Lemma get_shared_mem_status_seen__correct: forall m d (z: Z) env le pid1 pid2 n,\n                                               env = PTree.empty _ ->\n                                               PTree.get tpid1 le = Some (Vint pid1) ->\n                                               PTree.get tpid2 le = Some (Vint pid2) ->\n                                               (*pg d = true ->*)\n                                               get_shared_mem_status_seen_spec\n                                                 (Int.unsigned pid1) (Int.unsigned pid2) d\n                                               = Some (Int.unsigned n) ->\n                                               high_level_invariant d ->\n                                               exists (le': temp_env),\n                                                 exec_stmt ge env le ((m, d): mem) get_shared_mem_status_seen_body\n                                                           E0 le' (m, d) (Out_return (Some (Vint n, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          assert (smi2z: forall s, SharedMemInfo2Z s = Int.unsigned (Int.repr (SharedMemInfo2Z s))). {\n            intros. unfold SharedMemInfo2Z.\n            destruct s; reflexivity.\n          }\n          intros. subst.\n          inversion H4.\n          functional inversion H3; subst.\n          - esplit.\n            unfold exec_stmt.\n            change E0 with (E0 ** E0).\n            repeat vcgen.\n            + unfold get_shared_mem_state_spec.\n              rewrite shared_mem_arg_rev.\n              rewrite H5, H7, H8, H9, H10, H6.\n              rewrite smi2z; reflexivity.\n            + repeat vcgen.\n            + repeat vcgen.\n            + rewrite H. repeat vcgen.\n          - esplit.\n            unfold exec_stmt.\n            change E0 with (E0 ** E0).\n            repeat vcgen.\n            + unfold get_shared_mem_state_spec.\n              rewrite shared_mem_arg_rev.\n              rewrite H5, H7, H8, H9, H10, H6.              \n              rewrite smi2z.\n              reflexivity.\n            + simpl. repeat vcgen.\n              destruct (zeq (SharedMemInfo2Z st) 1).\n                * functional inversion e.\n                  clear H11; rewrite <- H14 in _x1.\n                  contradiction _x1; trivial.\n                * repeat vcgen.\n                * unfold SharedMemInfo2Z. destruct st; omega.\n                * unfold SharedMemInfo2Z. destruct st; omega.\n            + repeat vcgen.\n              unfold get_shared_mem_state_spec.\n              rewrite H5, H7, H8, H9, H6.\n              rewrite H12.\n              rewrite smi2z; reflexivity.\n            + simpl. rewrite PTree.gss. rewrite H, Int.repr_unsigned. trivial.\n        Qed.\n\n      End GetSharedMemStatusSeenBody.\n\n      Theorem get_shared_mem_status_seen_code_correct:\n        spec_le (get_shared_mem_status_seen \u21a6 get_shared_mem_status_seen_spec_low)\n                (\u301aget_shared_mem_status_seen \u21a6 f_get_shared_mem_status_seen \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (get_shared_mem_status_seen__correct s (Genv.globalenv p) makeglobalenv\n                                             b0 Hb0fs Hb0fp\n                                             m'0 labd\n                                             (Int.unsigned n)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_get_shared_mem_status_seen)\n                                                                    (Vint pid1 :: Vint pid2 :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_get_shared_mem_status_seen))))\n                 H0.\n      Qed.\n\n\n    End GETSHAREDMEMSTATUSSEEN.\n\n\n\n    Section SHAREDMEMTOREADY.\n\n      Let resv2_sem := pt_resv2 \u21a6 gensem ptResv2_spec.\n\n      Let L: compatlayer (cdata RData) := \n          pt_resv2 \u21a6 gensem ptResv2_spec\n        (*\u2295 palloc \u21a6 gensem palloc_spec*)\n        (*\u2295 shared_mem_to_ready \u21a6 gensem shared_mem_to_ready_spec*)\n        \u2295 set_shared_mem_state \u21a6 gensem set_shared_mem_state_spec\n        \u2295 set_shared_mem_seen \u21a6 gensem set_shared_mem_seen_spec\n        \u2295 get_shared_mem_loc \u21a6 gensem get_shared_mem_loc_spec\n        \u2295 set_shared_mem_loc \u21a6 gensem set_shared_mem_loc_spec.\n\n\n\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section SharedMemToReadyBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        Variable bpt_resv2: block.\n\n        Hypothesis hpt_resv21 : Genv.find_symbol ge pt_resv2 = Some bpt_resv2.\n\n        Hypothesis hpt_resv22 : Genv.find_funct_ptr ge bpt_resv2 =\n                      Some (External (EF_external pt_resv2 (signature_of_type\n(Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))))) tint cc_default))\n(Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))))) tint cc_default).\n\n        Variable bset_shared_mem_state: block.\n\n        Hypothesis hset_shared_mem_state1 : Genv.find_symbol ge set_shared_mem_state = Some bset_shared_mem_state. \n\n        Hypothesis hset_shared_mem_state2 : Genv.find_funct_ptr ge bset_shared_mem_state =\n                      Some (External (EF_external set_shared_mem_state (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        (** set_shared_mem_seen *)\n\n        Variable bset_shared_mem_seen: block.\n\n        Hypothesis hset_shared_mem_seen1 : Genv.find_symbol ge set_shared_mem_seen = Some bset_shared_mem_seen. \n\n        Hypothesis hset_shared_mem_seen2 : Genv.find_funct_ptr ge bset_shared_mem_seen =\n                      Some (External (EF_external set_shared_mem_seen (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Variable bget_shared_mem_loc: block.\n\n        Hypothesis hget_shared_mem_loc1 : Genv.find_symbol ge get_shared_mem_loc = Some bget_shared_mem_loc.\n\n        Hypothesis hget_shared_mem_loc2 : Genv.find_funct_ptr ge bget_shared_mem_loc =\n                      Some (External (EF_external get_shared_mem_loc (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        Variable bset_shared_mem_loc: block.\n\n        Hypothesis hset_shared_mem_loc1 : Genv.find_symbol ge set_shared_mem_loc = Some bset_shared_mem_loc. \n\n        Hypothesis hset_shared_mem_loc2 : Genv.find_funct_ptr ge bset_shared_mem_loc =\n                      Some (External (EF_external set_shared_mem_loc (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Require Import CommonTactic.\n\n        Lemma ptInsert0_presv:\n          forall pid1 vadr b v d adt n,\n            ptInsert0_spec pid1 vadr b v d = Some (adt, n)\n            -> pg adt = true /\\ ipt adt = true\n               /\\ smspool adt = smspool d.\n        Proof.\n          intros. functional inversion H; subst.\n          - functional inversion H9; simpl; eauto.\n          - functional inversion H9; simpl; eauto.\n          - functional inversion H9; simpl; eauto 2;\n            functional inversion H11; simpl; eauto 2.\n            + rewrite <- H19, <- H0 in *. simpl in *.\n              refine_split'; try congruence.\n            + rewrite <- H20, <- H0 in *. simpl in *.\n              refine_split'; try congruence.\n        Qed.\n\n        Lemma ptResv2_presv_pg_idt': forall pid1 pid2 d vadr vadr' adt n v v',\n                                ptResv2_spec pid1 vadr v pid2 vadr' v' d = Some (adt, n)\n                                -> pg adt = true /\\ ipt adt = true\n                                   /\\ smspool adt = smspool d.\n        Proof.\n          intros. functional inversion H; subst.\n          - functional inversion H2; subst; eauto.\n          - functional inversion H2; subst; eauto.\n            + eapply ptInsert0_presv in H4. assumption.\n            + eapply ptInsert0_presv; eauto.\n          - functional inversion H1; subst; eauto.\n            + eapply ptInsert0_presv in H0. \n              eapply ptInsert0_presv in H3. simpl in *.\n              destruct H0 as (HE1 & HE2 & HE3).\n              destruct H3 as ( _ & _ & HE4).\n              refine_split'; eauto. congruence.\n            + eapply ptInsert0_presv in H0. \n              eapply ptInsert0_presv in H3. simpl in *.\n              destruct H0 as (HE1 & HE2 & HE3).\n              destruct H3 as ( _ & _ & HE4).\n              refine_split'; eauto. congruence.\n        Qed.\n\n        Lemma ptResv2_presv_pg: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> pg adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_ipt: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> ipt adt = true.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c).\n          assumption.\n        Qed.\n\n        Lemma ptResv2_presv_smspool: forall pid1 pid2 d vadr vadr' adt n,\n                                  shared_mem_arg (Int.unsigned pid1) (Int.unsigned pid2)\n                                     = true\n                                -> high_level_invariant d \n                                -> ptResv2_spec (Int.unsigned pid1) (Int.unsigned vadr) 7\n                                    (Int.unsigned pid2) vadr' 7 d = Some (adt, Int.unsigned n)\n                                -> smspool adt = smspool d.\n        Proof.\n          intros.\n          destruct (ptResv2_presv_pg_idt' (Int.unsigned pid1) (Int.unsigned pid2) d (Int.unsigned vadr)\n                                          vadr' adt (Int.unsigned n) 7 7 H1) as (a & b & c).\n          assumption.\n        Qed.\n\n        Lemma shared_mem_to_ready_correct: forall m d d' (z: Z) env le pid1 pid2 vadr n,\n                                      env = PTree.empty _ ->\n                                      PTree.get tpid1 le = Some (Vint pid1) ->\n                                      PTree.get tpid2 le = Some (Vint pid2) ->\n                                      PTree.get tvadr le = Some (Vint vadr) ->\n                                      (*pg d = true ->*)\n                                      shared_mem_to_ready_spec (Int.unsigned pid1) (Int.unsigned pid2) (Int.unsigned vadr) d = Some (d', Int.unsigned n) ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_to_ready_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          intros. subst.\n          inversion H5.\n          functional inversion H4; functional inversion H7; subst;\n            set (Hvadr' := H13); set (Hvadr'_inv := H13);\n            auto; rewrite H13 in Hvadr'_inv; inversion Hvadr'_inv.\n          Focus 2.\n            - set (adt'inv := H15). set (adt'kminv := H15).\n              apply ptResv2_high_level_inv in adt'inv; auto.\n              apply ptResv2_kernel_mode in adt'kminv; try (constructor; auto; fail).\n              esplit.\n              unfold exec_stmt.\n              change E0 with (E0 ** E0).\n              repeat vcgen.\n                + unfold get_shared_mem_loc_spec.\n                  rewrite H8, H9, H10, H11, shared_mem_arg_rev, H7, Hvadr'.\n                  instantiate (1:= (Int.repr vadr')).\n                  rewrite Int.unsigned_repr.\n                  reflexivity.\n                  omega.\n                + repeat vcgen.\n                  econstructor.\n                  rewrite H15.\n                  trivial.\n                + vcgen.\n                + vcgen. \n                + repeat vcgen.\n                    * unfold set_shared_mem_state_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_smspool pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, H7, H6, H12.\n                      vcgen.\n                    * unfold set_shared_mem_seen_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, H7, H6. repeat rewrite ZMap.gss.\n                      repeat rewrite ZMap.set2.\n                      try reflexivity.\n                      (*cutrewrite (ZtoBool (Int.unsigned (Int.zero_ext 8 (Int.repr 1)))\n                                  = Some true); try reflexivity.*)\n                    * unfold set_shared_mem_loc_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, H7, H6.\n                      repeat rewrite ZMap.gss.\n                      reflexivity.\n                    * unfold set_shared_mem_state_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, shared_mem_arg_rev, H7, H6.\n                      repeat rewrite ZMap.gso; auto.\n                      setoid_rewrite Hvadr'.\n                      vcgen.\n                    * unfold set_shared_mem_seen_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, shared_mem_arg_rev, H7, H6.\n\n                      (*cutrewrite (ZtoBool (Int.unsigned (Int.zero_ext 8 (Int.repr 0)))\n                              = Some false); [| reflexivity].*)\n                      (*rewrite (ptResv2_presv_smspool pid1 pid2 d vadr vadr' adt' n); auto.*)\n                      repeat rewrite ZMap.gss.\n                      reflexivity.\n                      (*repeat rewrite ZMap.gso.\n                      repeat rewrite ZMap.set2.\n                      repeat vcgen.*)\n                    * unfold set_shared_mem_loc_spec; simpl.\n                      destruct adt'kminv.\n                      rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite H, shared_mem_arg_rev, H7, H6.\n                      unfold smsp', smsp.\n                      rewrite (ptResv2_presv_smspool pid1 pid2 d vadr vadr' adt' n); auto.\n                      repeat rewrite ZMap.gss.\n                      repeat rewrite ZMap.set2.\n                      repeat rewrite ZMap.gso.\n                      (*rewrite (ptResv2_presv_pg pid1 pid2 d vadr vadr' adt' n); auto.\n                      rewrite (ptResv2_presv_ipt pid1 pid2 d vadr vadr' adt' n); auto.\n                      destruct adt'kminv. rewrite H, H21.*)\n                      reflexivity. auto.\n                 + vcgen. rewrite PTree.gss. trivial.\n            - esplit.\n              unfold exec_stmt.\n              change E0 with (E0 ** E0).\n              repeat vcgen.\n                + unfold get_shared_mem_loc_spec.\n                  rewrite H8, H9, H10, H11, shared_mem_arg_rev, H7, Hvadr'.\n                  instantiate (1:= (Int.repr vadr')).\n                  rewrite Int.unsigned_repr.\n                  reflexivity.\n                  omega.\n                + repeat vcgen.\n                  econstructor.\n                  rewrite H15.\n                  cutrewrite (MagicNumber = Int.unsigned (Int.repr MagicNumber)).\n                  reflexivity. auto.\n                + vcgen.\n                + reflexivity.\n                + vcgen.\n                + vcgen. rewrite PTree.gss. simpl MagicNumber.\n                  cutrewrite (n = Int.repr (Int.unsigned n)).\n                  rewrite <- H6. trivial.\n                  rewrite Int.repr_unsigned. trivial.\n        Qed.\n\n      End SharedMemToReadyBody.\n\n      Theorem shared_mem_to_ready_code_correct:\n        spec_le (shared_mem_to_ready \u21a6 shared_mem_to_ready_spec_low)\n                (\u301ashared_mem_to_ready \u21a6 f_shared_mem_to_ready \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (shared_mem_to_ready_correct s (Genv.globalenv p) makeglobalenv\n                                             b0 Hb0fs Hb0fp\n                                             b1 Hb1fs Hb1fp\n                                             b2 Hb2fs Hb2fp\n                                             b3 Hb3fs Hb3fp\n                                             b4 Hb4fs Hb4fp\n                                             m'0 labd labd'\n                                             (Int.unsigned n)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_shared_mem_to_ready)\n                                                                    (Vint pid1 :: Vint pid2 :: Vint vadr :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_shared_mem_to_ready))))\n                 H0.\n      Qed.\n\n    End SHAREDMEMTOREADY.\n\n    Section SHAREDMEMTODEAD.\n\n      Let L: compatlayer (cdata RData) := \n          set_shared_mem_state \u21a6 gensem  set_shared_mem_state_spec\n        \u2295 set_shared_mem_seen \u21a6 gensem set_shared_mem_seen_spec\n        \u2295 set_shared_mem_loc \u21a6 gensem set_shared_mem_loc_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section SharedMemToDeadBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** set_shared_mem_state *)\n\n        Variable bset_shared_mem_state: block.\n\n        Hypothesis hset_shared_mem_state1 : Genv.find_symbol ge set_shared_mem_state = Some bset_shared_mem_state. \n\n        Hypothesis hset_shared_mem_state2 : Genv.find_funct_ptr ge bset_shared_mem_state =\n                      Some (External (EF_external set_shared_mem_state (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        (** set_shared_mem_seen *)\n\n        Variable bset_shared_mem_seen: block.\n\n        Hypothesis hset_shared_mem_seen1 : Genv.find_symbol ge set_shared_mem_seen = Some bset_shared_mem_seen. \n\n        Hypothesis hset_shared_mem_seen2 : Genv.find_funct_ptr ge bset_shared_mem_seen =\n                      Some (External (EF_external set_shared_mem_seen (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Variable bset_shared_mem_loc: block.\n\n        Hypothesis hset_shared_mem_loc1 : Genv.find_symbol ge set_shared_mem_loc = Some bset_shared_mem_loc. \n\n        Hypothesis hset_shared_mem_loc2 : Genv.find_funct_ptr ge bset_shared_mem_loc =\n                      Some (External(EF_external set_shared_mem_loc (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Lemma shared_mem_to_dead_correct: forall m d d' (z: Z) env le pid1 pid2 vadr,\n                                      env = PTree.empty _ ->\n                                      PTree.get tpid1 le = Some (Vint pid1) ->\n                                      PTree.get tpid2 le = Some (Vint pid2) ->\n                                      PTree.get tvadr le = Some (Vint vadr) ->\n\n                                      shared_mem_to_dead_spec (Int.unsigned pid1) (Int.unsigned pid2) (Int.unsigned vadr) d = Some d' ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_to_dead_body E0 le' (m, d') Out_normal.\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          intros. subst.\n          functional inversion H4. subst.\n          inversion H5.\n          functional inversion H6.\n          esplit.\n          unfold exec_stmt.\n          change E0 with (E0 ** E0).\n          repeat vcgen.\n            - unfold set_shared_mem_seen_spec; simpl.\n              repeat rewrite ZMap.gss.\n              repeat vcgen.\n            - unfold set_shared_mem_loc_spec; simpl.\n              repeat rewrite ZMap.gss.\n              repeat vcgen.\n            - unfold set_shared_mem_state_spec; simpl.\n              rewrite shared_mem_arg_rev.\n              repeat rewrite ZMap.gso.\n              setoid_rewrite H11.\n              repeat vcgen. auto. auto. auto.\n            - unfold set_shared_mem_seen_spec; simpl.\n              rewrite shared_mem_arg_rev.\n              rewrite H6, H7, H8, H9, H10.\n              repeat rewrite ZMap.gss.\n              repeat rewrite ZMap.set2.\n              reflexivity.\n              (*cutrewrite (ZtoBool (Int.unsigned (Int.zero_ext 8 (Int.repr 0)))\n                          = Some false); try reflexivity.*)\n\n            - unfold set_shared_mem_loc_spec; simpl.\n              rewrite shared_mem_arg_rev.\n              rewrite H6, H7, H8, H9, H10.\n              repeat rewrite ZMap.gss.\n              repeat rewrite ZMap.set2.\n              repeat rewrite ZMap.gso.\n              unfold smsp'; unfold smsp.\n              unfold smspool. destruct d. repeat rewrite rdata_update.\n              repeat rewrite ZMap.gso.\n              reflexivity. auto.\n        Qed.\n\n      End SharedMemToDeadBody.\n\n\n      Theorem shared_mem_to_dead_code_correct:\n        spec_le (shared_mem_to_dead \u21a6 shared_mem_to_dead_spec_low)\n                (\u301ashared_mem_to_dead \u21a6 f_shared_mem_to_dead \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (shared_mem_to_dead_correct s (Genv.globalenv p) makeglobalenv\n                                             b0 Hb0fs Hb0fp\n                                             b1 Hb1fs Hb1fp\n                                             b2 Hb2fs Hb2fp\n                                             m'0 labd labd'\n                                             (Int.unsigned vadr)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_shared_mem_to_dead)\n                                                                    (Vint pid1 :: Vint pid2 :: Vint vadr :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_shared_mem_to_dead))))\n                 H0.\n      Qed.\n\n    End SHAREDMEMTODEAD.\n\n\n\n\n\n    Section SHAREDMEMTOPENDING.\n\n      Let L: compatlayer (cdata RData) := \n          set_shared_mem_state \u21a6 gensem  set_shared_mem_state_spec\n        \u2295 set_shared_mem_seen \u21a6 gensem set_shared_mem_seen_spec\n        \u2295 set_shared_mem_loc \u21a6 gensem set_shared_mem_loc_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section SharedMemToPendingBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** set_shared_mem_state *)\n\n        Variable bset_shared_mem_state: block.\n\n        Hypothesis hset_shared_mem_state1 : Genv.find_symbol ge set_shared_mem_state = Some bset_shared_mem_state. \n\n        Hypothesis hset_shared_mem_state2 : Genv.find_funct_ptr ge bset_shared_mem_state =\n                      Some (External (EF_external set_shared_mem_state (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        (** set_shared_mem_seen *)\n\n        Variable bset_shared_mem_seen: block.\n\n        Hypothesis hset_shared_mem_seen1 : Genv.find_symbol ge set_shared_mem_seen = Some bset_shared_mem_seen. \n\n        Hypothesis hset_shared_mem_seen2 : Genv.find_funct_ptr ge bset_shared_mem_seen =\n                      Some (External (EF_external set_shared_mem_seen (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Variable bset_shared_mem_loc: block.\n\n        Hypothesis hset_shared_mem_loc1 : Genv.find_symbol ge set_shared_mem_loc = Some bset_shared_mem_loc. \n\n        Hypothesis hset_shared_mem_loc2 : Genv.find_funct_ptr ge bset_shared_mem_loc =\n                      Some (External (EF_external set_shared_mem_loc (signature_of_type (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default)) (Tcons tint (Tcons tint (Tcons tint Tnil))) Tvoid cc_default).\n\n        Lemma shared_mem_to_pending_correct: forall m d d' (z: Z) env le pid1 pid2 vadr,\n                                      env = PTree.empty _ ->\n                                      PTree.get tpid1 le = Some (Vint pid1) ->\n                                      PTree.get tpid2 le = Some (Vint pid2) ->\n                                      PTree.get tvadr le = Some (Vint vadr) ->\n                                      shared_mem_to_pending_spec (Int.unsigned pid1) (Int.unsigned pid2) (Int.unsigned vadr) d = Some d' ->\n                                      high_level_invariant d ->\n                                      exists (le': temp_env),\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_to_pending_body E0 le' (m, d') Out_normal.\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          assert (H2: True); auto.\n          intros. subst.\n          functional inversion H4. subst.\n          inversion H5.\n          functional inversion H6.\n          esplit.\n          unfold exec_stmt.\n          change E0 with (E0 ** E0).\n          repeat vcgen.\n            - unfold set_shared_mem_seen_spec; simpl.\n              rewrite H6.\n              repeat rewrite ZMap.gss.\n              repeat vcgen. (*reflexivity.*)\n            - unfold set_shared_mem_loc_spec; simpl.\n              rewrite H6.\n              repeat rewrite ZMap.gss. repeat rewrite ZMap.set2.\n              rewrite H7, H8, H9, H10. reflexivity.\n        Qed.\n\n      End SharedMemToPendingBody.\n\n\n      Theorem shared_mem_to_pending_code_correct:\n        spec_le (shared_mem_to_pending \u21a6 shared_mem_to_pending_spec_low)\n                (\u301ashared_mem_to_pending \u21a6 f_shared_mem_to_pending \u301bL).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (shared_mem_to_pending_correct s (Genv.globalenv p) makeglobalenv\n                                             b0 Hb0fs Hb0fp\n                                             b1 Hb1fs Hb1fp\n                                             b2 Hb2fs Hb2fp\n                                             m'0 labd labd'\n                                             (Int.unsigned vadr)\n                                             (PTree.empty _) \n                                             (bind_parameter_temps' (fn_params f_shared_mem_to_pending)\n                                                                    (Vint pid1 :: Vint pid2 :: Vint vadr :: nil)\n                                                                    (create_undef_temps\n                                                                       (fn_temps f_shared_mem_to_pending))))\n                 H0.\n      Qed.\n\n    End SHAREDMEMTOPENDING.\n\n    End WithPrimitives.\n\nEnd MSHAREOPCODE.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MShareIntroCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16975467358875523}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import PeanoNat.\n\nRequire Export Parser.Monotonicity.\nRequire Export Parser.HListCast.\nRequire Export Parser.DescriptionInd.\nRequire Export Parser.DescriptionToFunction.\nRequire Export Parser.NetworkProperties.\nRequire Export Parser.NetworkWipCells.\n\nOpaque compute_cells.\nOpaque range.\n\n(** In this file, we prove that, for monotonic descriptions, if a syntax `s` is\n    related to a value `v`, then the propagator network is going to return some\n    value (not necessarily `v`) *)\nDefinition fun_completeness_statement: Prop :=\n  forall G (descr: Description G) A (s: Syntax A) v,\n    descr_ind descr s v ->\n    monotonic_descr descr ->\n    is_some (build_fun descr s).\n\nDefinition is_up_to_date (N: Network) k: Prop :=\n  (exists H,\n    measure (cells N k) (state (cells N k)) <=\n    measure (cells N k) (update (cells N k) (cast H (h_map (fun k' => state (cells N k')) (inputs N k)))))\n  \\/\n  (exists q, measure (cells N k) (state (cells N k)) < measure (cells N k) q).\n\nLemma compute_cell_up_to_date_some:\n  forall N k pre N',\n    compute_cell N k pre = Some N' ->\n    is_up_to_date N' k.\nProof.\n  unfold compute_cell, set_cell, is_up_to_date, cast;\n    repeat light || destruct_match || invert_constructor_equalities;\n    eauto with lia.\nQed.\n\nLemma compute_cell_up_to_date_none:\n  forall N k pre,\n    compute_cell N k pre = None ->\n    is_up_to_date N k.\nProof.\n  unfold compute_cell, set_cell, is_up_to_date, cast;\n    repeat light || destruct_match || invert_constructor_equalities || eq_dep || clear matched.\n\n    left.\n    exists (f_equal (fun H : list Type => hlist H)\n                 (PropagatorNetwork.compute_cell_obligation_1 N k pre));\n            eauto with lia.\nQed.\nLemma sum_sizes_until_sum_sizes2:\n  forall x n, sum_sizes_until x < sum_sizes vars + n.\nProof.\n  intros.\n  pose proof (sum_sizes_until_sum_sizes x); eauto with lia.\nQed.\n\n\nLemma registered_inputs_compute_cell:\n  forall N k pre N',\n    compute_cell N k pre = Some N' ->\n    registered_inputs N ->\n    registered_inputs N'.\nProof.\n  unfold compute_cell, set_cell;\n    repeat light || destruct_match || invert_constructor_equalities.\nQed.\n\nLemma compute_cell_up_to_date_some_other:\n  forall N k1 k2 pre N',\n    is_up_to_date N k1 ->\n    k1 <> k2 ->\n    ~ In k2 (inputs N k1) ->\n    compute_cell N k2 pre = Some N' ->\n    is_up_to_date N' k1.\nProof.\n  unfold compute_cell, set_cell;\n    repeat light || destruct_match || invert_constructor_equalities;\n    eauto with lia.\n\n  clear matched.\n\n  unfold is_up_to_date in *;\n    repeat light || eq_dep || destruct_match; eauto.\n\n  left.\n  unshelve eexists; repeat light || eq_dep || destruct_match.\n  - eapply eq_trans; try eassumption.\n    f_equal.\n    apply map_ext_in;\n      repeat light || eq_dep || destruct_match.\n  -\n(*    Notation \"'<<' x '>>'\" := (eq_rect _ (fun T => T) x _ _). *)\n    unshelve erewrite (h_map_ext _ _ _ _\n      (fun k' : nat =>\n            state\n              (if Nat.eq_dec k2 k'\n               then\n                {|\n                main_type := main_type (cells N k2);\n                cell_type := cell_type (cells N k2);\n                input_types := input_types (cells N k2);\n                update := update (cells N k2);\n                measure := measure (cells N k2);\n                state := update (cells N k2)\n                           (eq_rect\n                              (hlist (map (fun k'0 : nat => cell_type (cells N k'0)) (inputs N k2)))\n                              (fun T : Type => T)\n                              (h_map (fun k'0 : nat => state (cells N k'0)) (inputs N k2))\n                              (hlist (input_types (cells N k2)))\n                              (f_equal (fun H3 : list Type => hlist H3)\n                                 (PropagatorNetwork.compute_cell_obligation_1 N k2 pre))) |}\n               else cells N k'))\n      (fun k' : nat => state (cells N k'))); repeat light || destruct_match.\n\n    + f_equal. apply map_ext_in; repeat light || destruct_match.\n    + repeat eq_dep. proof_irrelevance.\n      rewrite H3 in H2; lights.\n    + eexists; repeat light || rewrite cast_refl.\nQed.\n\nLemma compute_cells_up_to_date':\n    forall m num_cells N ks pre k,\n    (sum_measures num_cells N, length ks) = m ->\n    registered_inputs N ->\n    (forall k, k < num_cells -> In k ks \\/ is_up_to_date N k) ->\n    k < num_cells ->\n    is_up_to_date (compute_cells num_cells N ks pre) k.\nProof.\n  induction m using measure_induction; destruct ks;\n    repeat light || compute_cells_def || destruct_match || options;\n    try solve [ instantiate_any; lights ].\n\n  - clear matched.\n    revert i.\n    generalize (PropagatorNetwork.compute_cells_obligations_obligation_3 num_cells N n ks pre).\n    generalize (PropagatorNetwork.compute_cells_obligations_obligation_2 num_cells N n ks pre).\n    generalize (PropagatorNetwork.compute_cells_obligations_obligation_1 num_cells N n ks pre).\n    repeat light || destruct_match || options.\n\n    eapply_any; repeat light || rewrite in_app_iff in *;\n      eauto using registered_inputs_compute_cell;\n      try solve [ apply left_lex; eauto using compute_cell_size ].\n\n    match goal with\n    | H1: forall k, _ -> _ \\/ _, H2: _ < _ |- _ => pose proof (H1 _ H2)\n    end; lights;\n      eauto using compute_cell_up_to_date_some.\n\n    pose proof (Nat.eq_dec k0 n); lights;\n      eauto using compute_cell_up_to_date_some.\n\n    pose proof (in_dec Nat.eq_dec k0 (registered N n)); lights.\n    unfold registered_inputs in *.\n    rewrite H1 in *; eauto using compute_cell_up_to_date_some_other.\n\n\n  - clear matched.\n    revert n0.\n    generalize (PropagatorNetwork.compute_cells_obligations_obligation_5 num_cells N n ks pre).\n    generalize (PropagatorNetwork.compute_cells_obligations_obligation_1 num_cells N n ks pre).\n    repeat light || destruct_match;\n      eauto 2 with lights.\n\n    eapply_any; repeat light || rewrite in_app_iff in *;\n      eauto;\n      try solve [ apply right_lex; eauto using compute_cell_size ].\n\n    match goal with\n    | H1: forall k, _ -> _ \\/ _, H2: _ < _ |- _ => pose proof (H1 _ H2)\n    end; lights;\n      eauto using compute_cell_up_to_date_none.\nQed.\n\nLemma compute_cells_up_to_date:\n  forall G (descr: Description G) A0 (s0: Syntax A0) k,\n    k < sum_sizes vars + syntax_size s0 ->\n    is_up_to_date\n      (compute_cells\n        (sum_sizes vars + syntax_size s0)\n        (make_network s0 descr)\n        (range 0 (sum_sizes vars + syntax_size s0))\n        (DescriptionToFunction.build_fun_obligation_1 G descr A0 s0))\n      k.\nProof.\n  intros.\n  eapply compute_cells_up_to_date'; repeat light || rewrite range_spec;\n    eauto using registered_inputs_make_network;\n    eauto with lia.\nQed.\n\nLtac cell_equality_transitivity :=\n  match goal with\n  | H1: cells ?N ?k = _, H2: cells ?N ?k = make_cell_with_state _ _ _ |- _ =>\n    poseNew (Mark (H1, H2) \"cell_equality_transitivity\");\n    pose proof (eq_trans (eq_sym H1) H2)\n  end.\n\nLtac main_type_solve :=\n  match goal with\n  | H: {| main_type := _ |} = make_cell_with_state _ _ _ |- _ =>\n    poseNew (Mark H \"main_type_solve\");\n    pose proof (f_equal_dep _ main_type H);\n      repeat eq_dep || cbn in * || rewrite main_type_make_cell in *\n  end.\n\nLtac state_solve :=\n  match goal with\n  | H: {| main_type := _ |} = make_cell_with_state _ _ _ |- _ =>\n    poseNew (Mark H \"state_solve\");\n    pose proof (f_equal_dep _ state H);\n      repeat eq_dep || cbn in * || rewrite state_make_cell in * || invert_constructor_equalities\n  end.\n\nLtac derive_members :=\n  match goal with\n  | H: cells (compute_cells _ (make_network _ _) _ _) ?k = _ |- _ =>\n    poseNew (Mark k \"derive_members\");\n    pose proof (eq_sym ((f_equal_dep _ update (eq_sym H))));\n    pose proof (eq_sym ((f_equal_dep _ cell_type (eq_sym H))));\n    pose proof (eq_sym ((f_equal_dep _ measure (eq_sym H))));\n    pose proof (eq_sym ((f_equal_dep _ state (eq_sym H))));\n    pose proof (eq_sym ((f_equal_dep _ input_types (eq_sym H))))\n  end; repeat eq_dep || cbn in *.\n\nLemma rules_to_update_epsilon:\n  forall G (descr : Description G) A (R : Rule nil (G A)) (v : G A) (a: A) (opt: option (G A)) rules,\n\n    R HNil = Some v ->\n    In R rules ->\n    (Epsilon a, opt) = rules_to_update (Epsilon a) G rules HNil ->\n    is_some opt.\nProof.\n  repeat light || unfold is_some || destruct_match || unfold rules_to_update in * ||\n         invert_constructor_equalities;\n    eauto using fold_left_not_none2.\nQed.\n\nLemma rules_to_update_failure:\n  forall G (descr : Description G) A (R : Rule nil (G A)) (v : G A) (opt: option (G A)) rules,\n\n    R HNil = Some v ->\n    In R rules ->\n    (Failure A, opt) = rules_to_update (Failure A) G rules HNil ->\n    is_some opt.\nProof.\n  repeat light || unfold is_some || destruct_match || unfold rules_to_update in * ||\n         invert_constructor_equalities;\n    eauto using fold_left_not_none2.\nQed.\n\nLemma rules_to_update_elem:\n  forall G (descr : Description G) (R : Rule nil (G token)) (v : G token) (opt: option (G token)) rules tc,\n\n    R HNil = Some v ->\n    In R rules ->\n    (Elem tc, opt) = rules_to_update (Elem tc) G rules HNil ->\n    is_some opt.\nProof.\n  repeat light || unfold is_some || destruct_match || unfold rules_to_update in * ||\n         invert_constructor_equalities;\n    eauto using fold_left_not_none2.\nQed.\n\nLemma rules_to_update_monotonic_1:\n  forall A T\n    (R : Rule (A :: nil) T) opt0 opt1 opt2 rules,\n\n    is_some (R (HCons opt1 HNil)) ->\n    In R rules ->\n    monotonic_rule_1 R ->\n    is_some_is_some opt1 opt2 ->\n    is_some (fold_left (fun acc f => or_else acc (f (HCons opt2 HNil))) rules opt0).\nProof.\n  unfold monotonic_rule_1; unfold is_some_is_some; intros.\n  apply fold_is_some with R; lights;\n  eapply H1; eauto; lights.\nQed.\n\nLemma rules_to_update_monotonic_1':\n  forall A T v\n    (R : Rule (A :: nil) T) opt0 opt1 opt2 rules,\n\n    R (HCons opt1 HNil) = Some v ->\n    In R rules ->\n    monotonic_rule_1 R ->\n    is_some_is_some opt1 opt2 ->\n    fold_left (fun acc f => or_else acc (f (HCons opt2 HNil))) rules opt0 = None ->\n    False.\nProof.\n  intros.\n  unshelve epose proof (rules_to_update_monotonic_1 A T R opt0 opt1 opt2 rules _ _ _ _);\n    repeat light || options || destruct_match.\nQed.\n\nLemma rules_to_update_monotonic_2:\n  forall A1 A2 T\n    (R : Rule (A1 :: A2 :: nil) T) opt0 opt1 opt2 opt1' opt2' rules,\n\n    is_some (R (HCons opt1 (HCons opt2 HNil))) ->\n    In R rules ->\n    monotonic_rule_2 R ->\n    is_some_is_some opt1 opt1' ->\n    is_some_is_some opt2 opt2' ->\n    is_some (fold_left (fun acc f => or_else acc (f (HCons opt1' (HCons opt2' HNil)))) rules opt0).\nProof.\n  unfold monotonic_rule_2; unfold is_some_is_some; intros.\n  apply fold_is_some with R; lights;\n  eapply H1; eauto; lights.\n  unfold are_some_are_some_2; lights.\nQed.\n\nLemma rules_to_update_monotonic_2':\n  forall A1 A2 T v\n    (R : Rule (A1 :: A2 :: nil) T) opt0 opt1 opt2 opt1' opt2' rules,\n\n    R (HCons opt1 (HCons opt2 HNil)) = Some v ->\n    In R rules ->\n    monotonic_rule_2 R ->\n    is_some_is_some opt1 opt1' ->\n    is_some_is_some opt2 opt2' ->\n    fold_left (fun acc f => or_else acc (f (HCons opt1' (HCons opt2' HNil)))) rules opt0 = None ->\n    False.\nProof.\n  intros.\n  unshelve epose proof (rules_to_update_monotonic_2 A1 A2 T R opt0 opt1 opt2 opt1' opt2' rules _ _ _ _ _);\n    repeat light || options || destruct_match.\nQed.\n\nLtac introduce_up :=\n  match goal with\n  | H: cells (compute_cells _ (make_network ?s0 ?descr) _ _) ?k = {| main_type := _ |} |- _ =>\n    poseNew (Mark 0 \"introduce_up\");\n    unshelve epose proof (compute_cells_up_to_date _ descr _ s0 k _); lights;\n    unfold is_up_to_date in *; lights\n  end.\n\nLtac revert_up :=\n  match goal with\n  | H: measure _ (state _) <= _ |- _ => revert H\n  | H: measure _ (state _) < _ |- _ => revert H\n  end.\n\nLemma rules_to_update_0:\n  forall T (R : Rule [] T) rules opt0,\n\n    is_some (R HNil) ->\n    In R rules ->\n    is_some (fold_left (fun acc f => or_else acc (f HNil)) rules opt0).\nProof.\n  intros.\n  apply fold_is_some with R; lights.\nQed.\n\nLemma rules_to_update_0':\n  forall T (R : Rule [] T) rules opt0 v,\n\n    R HNil = Some v ->\n    In R rules ->\n    fold_left (fun acc f => or_else acc (f HNil)) rules opt0 = None ->\n    False.\nProof.\n  intros.\n  unshelve epose proof (rules_to_update_0 T R rules opt0 _ _);\n    repeat light || destruct_match || rewrite_any.\nQed.\n\nLtac generalize_lt_right :=\n  match goal with\n  | |- context[measure _ _ < measure ?c ?q] => generalize q\n  end.\n\nLemma small_node_measure:\n  forall A G (q: node_type A G), 1 < node_measure q -> False.\nProof.\n  unfold node_measure;\n    repeat light || destruct_match; try lia.\nQed.\n\nLemma fun_completeness':\n  forall G (descr: Description G) A (s: Syntax A) v A0 (s0: Syntax A0),\n    descr_ind descr s v ->\n    monotonic_descr descr ->\n    wip_cells descr\n      (compute_cells (sum_sizes vars + syntax_size s0)\n                          (make_network s0 descr)\n                          (range 0 (sum_sizes vars + syntax_size s0))\n                          (DescriptionToFunction.build_fun_obligation_1 G descr A0 s0))\n      0 (sum_sizes vars + syntax_size s0) ->\n    forall k opt,\n      cells (compute_cells (sum_sizes vars + syntax_size s0)\n                            (make_network s0 descr)\n                            (range 0 (sum_sizes vars + syntax_size s0))\n                            (DescriptionToFunction.build_fun_obligation_1 G descr A0 s0))\n            k =\n        make_cell_with_state s descr opt ->\n      k < sum_sizes vars + syntax_size s0 ->\n      is_some opt.\nProof.\n  induction 1;\n    repeat light || destruct_match || cell_equality_transitivity ||\n          unshelve instantiate_wip_cells k ||\n          unshelve instantiate_wip_cells k0 ||\n          invert_constructor_equalities || rewrite_known_inputs2 || eq_dep ||\n          main_type_solve || state_solve; try (\n      introduce_up; revert_up; try generalize_lt_right; repeat derive_members;\n      repeat rewrite_known_updates; repeat eq_dep || cbn || generalize_proofs;\n      repeat rewrite_known_measures; repeat eq_dep || cbn || generalize_proofs;\n      repeat rewrite_known_input_types; repeat eq_dep || cbn || generalize_proofs;\n      repeat rewrite_known_inputs2; repeat eq_dep || cbn || generalize_proofs;\n      repeat rewrite_known_states2;\n        repeat eq_dep || generalize_proofs || rewrite state_make_cell;\n      repeat rewrite_known_cell_types;\n        repeat eq_dep || cbn || generalize_proofs || light ||\n                rewrite cast_hcons in * ||\n                rewrite cast_hcons2 in *;\n      repeat unfold rules_to_update in * || invert_constructor_equalities;\n        try solve [ repeat light || destruct_match; try lia; eauto using rules_to_update_0' ];\n        try solve [ repeat light || destruct_match; eauto using small_node_measure ];\n        try solve [ repeat light || destruct_match;\n                    try lia; eapply rules_to_update_monotonic_1';  eauto;\n          try solve [ unfold monotonic_descr in *; repeat light; eauto ];\n          try solve [ unfold is_some_is_some; lights;\n                      eauto using sum_sizes_until_sum_sizes2 with lia ]\n        ];\n        try solve [ repeat light || destruct_match;\n                    try lia; eapply rules_to_update_monotonic_2';  eauto;\n          try solve [ unfold monotonic_descr in *; repeat light; eauto ];\n          try solve [ unfold is_some_is_some; lights;\n                      eauto using sum_sizes_until_sum_sizes2 with lia ]\n        ]\n    ).\nQed.\n\nLemma fun_completeness: fun_completeness_statement.\nProof.\n  unfold fun_completeness_statement; unfold build_fun;\n    repeat light.\n\n  match goal with\n  | |- context[compute_cells ?num_cells ?N ?ks ?pre] =>\n    unshelve epose proof (compute_cells_still_make_cell\n      A s G descr N (sum_sizes vars) num_cells ks None pre _\n    )\n  end;\n    eauto using cell_make_network; lights.\n\n  apply fun_completeness' with descr s v A s (sum_sizes vars);\n    repeat light || apply wip_cells_compute_cells || unfold wip_cells ||\n           rewrite range_spec in * || syntax_size_gt_0;\n    eauto using sum_sizes_until_sum_sizes2;\n    eauto using wip_cells_make_network;\n    eauto with lia;\n    eauto using var_cells_make_network.\n\n  - repeat derive_members.\n    rewrite_known_states2; repeat cbn || eq_dep || rewrite state_make_cell; lights.\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/DescriptionToFunctionCompleteness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.16973055839130377}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Memory.\nRequire Import Common.Util.\nRequire Import Intermediate.Machine.\nRequire Import Lib.Monads.\n\nImport Intermediate.\n\nFrom mathcomp Require Import ssreflect ssrfun seq.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nRecord global_env := mkGlobalEnv {\n  genv_interface: Program.interface;\n  genv_procedures: NMap (NMap code);\n  genv_entrypoints: EntryPoint.t;\n}.\n\nDefinition executing G (pc : Pointer.t) (i : instr) : Prop :=\n  exists C_procs P_code,\n    getm (genv_procedures G) (Pointer.component pc) = Some C_procs /\\\n    getm C_procs (Pointer.block pc) = Some P_code /\\\n    (Pointer.offset pc >= 0) % Z /\\\n    Pointer.permission pc = Permission.code /\\\n    nth_error P_code (Z.to_nat (Pointer.offset pc)) = Some i.\n\nLemma executing_deterministic:\n  forall G pc i i',\n    executing G pc i -> executing G pc i' -> i = i'.\nProof.\n  unfold executing. intros G pc i i'\n                           [C_procs [P_code [memCprocs [memPcode\n                                                          [offsetCond\n                                                             [permCond memi]]]]]]\n                           [C_procs' [P_code' [memCprocs' [memPcode'\n                                                             [offsetCond'\n                                                                [permCond'\n                                                                   memi']]]]]].\n  rewrite memCprocs in memCprocs'.\n  inversion memCprocs'.\n  subst C_procs.\n  rewrite memPcode in memPcode'.\n  inversion memPcode'.\n  subst P_code.\n  rewrite memi in memi'.\n  inversion memi'.\n  auto.\nQed.\n\nDefinition prepare_global_env (p: program) : global_env :=\n  let '(_, procs, entrypoints) := prepare_procedures_initial_memory p in\n  {| genv_interface := prog_interface p;\n     genv_procedures := procs;\n     genv_entrypoints := entrypoints |}.\n\n(* global environments are computational and pure: deterministic.\n   what else do I need? some kind of per-component isolation stated\n   in a way that's easy to reuse *)\nLemma domm_genv_procedures : forall p,\n  domm (genv_procedures (prepare_global_env p)) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold genv_procedures, prepare_global_env.\n  rewrite Extra.domm_map. (* RB: Should be domm_mapm! *)\n  rewrite domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nLemma domm_genv_entrypoints : forall p,\n  domm (genv_entrypoints (prepare_global_env p)) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold genv_procedures, prepare_global_env.\n  rewrite Extra.domm_map domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nLemma genv_procedures_prog_procedures_eq : forall p c x,\n    well_formed_program p ->\n    prog_procedures p c = Some x ->\n    genv_procedures (prepare_global_env p) c =\n    prog_procedures p c.\nProof.\n  intros ? ? ? Hwf HSome.\n  simpl. rewrite mapmE. unfold omap, obind, oapp.\n  destruct (prepare_procedures_initial_memory_aux p c) as [someRes|] eqn:ec;\n    rewrite ec; unfold prepare_procedures_initial_memory_aux in *;\n      rewrite mkfmapfE in ec;\n      destruct (c \\in domm (prog_interface p)) eqn:ecintf; rewrite ecintf in ec;\n        inversion ec; clear ec; simpl.\n  - unfold odflt, oapp. by rewrite HSome.\n  - assert (c \\in domm (prog_interface p)).\n    {\n      rewrite wfprog_defined_procedures; auto. apply/dommP. by eauto.\n    }\n    congruence.\nQed.\n\nDefinition global_env_union (genv1 genv2 : global_env) : global_env := {|\n  genv_interface   := unionm (genv_interface   genv1) (genv_interface   genv2);\n  genv_procedures  := unionm (genv_procedures  genv1) (genv_procedures  genv2);\n  genv_entrypoints := unionm (genv_entrypoints genv1) (genv_entrypoints genv2)\n|}.\n\nLemma prepare_global_env_link : forall {p c},\n  well_formed_program p ->\n  well_formed_program c ->\n  linkable (prog_interface p) (prog_interface c) ->\n  prepare_global_env (program_link p c) =\n  global_env_union (prepare_global_env p) (prepare_global_env c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable.\n  unfold prepare_global_env, prepare_procedures_initial_memory.\n  rewrite (prepare_procedures_initial_memory_aux_after_linking\n           Hwfp Hwfc Hlinkable).\n  unfold global_env_union. simpl.\n  rewrite !mapm_unionm.\n  reflexivity.\nQed.\n\n(* RB: NOTE: This kind of lemma is usually the composition of two unions, one\n   of which is generally extant. Compare with \"after_linking\" lemmas. *)\nLemma imported_procedure_recombination {p c c' Cid C P} :\n  Cid \\notin domm (prog_interface c) ->\n  imported_procedure (genv_interface (prepare_global_env (program_link p c ))) Cid C P ->\n  imported_procedure (genv_interface (prepare_global_env (program_link p c'))) Cid C P.\nProof.\n  intros Hdomm Himp.\n  rewrite (imported_procedure_unionm_left Hdomm) in Himp.\n  destruct Himp as [CI [Hcomp Himp]]. exists CI. split; [| assumption].\n  unfold Program.has_component. rewrite unionmE. now rewrite Hcomp.\nQed.\n\nLemma genv_procedures_program_link_left_notin :\n  forall {c Cid},\n    Cid \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    (genv_procedures (prepare_global_env (program_link p c))) Cid =\n    (genv_procedures (prepare_global_env p)) Cid.\nProof.\n  intros c Cid Hnotin p Hwfp Hwfc Hlinkable.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable).\n  unfold global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env c)) Cid = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  setoid_rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) Cid) eqn:Hcase;\n    by setoid_rewrite Hcase.\nQed.\n\nLemma genv_procedures_program_link_right_in :\n  forall {c Cid},\n    Cid \\in domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    (genv_procedures (prepare_global_env (program_link p c))) Cid =\n    (genv_procedures (prepare_global_env c)) Cid.\nProof.\n  intros c Cid Hnotin p Hwfp Hwfc Hlinkable.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable).\n  unfold global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env p)) Cid = None).\n  {\n    apply/dommPn; rewrite domm_genv_procedures.\n    destruct Hlinkable as [_ Hdisj].\n    rewrite fdisjointC in Hdisj.\n    move : Hdisj => /fdisjointP => Hdisj.\n    apply Hdisj; by auto.\n  }\n  setoid_rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) Cid) eqn:Hcase;\n    by setoid_rewrite Hcase.\nQed.\n\nLemma genv_entrypoints_program_link_left :\n  forall {c C},\n    C \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n  forall {P},\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c))) =\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env p)).\nProof.\n  intros c C Hnotin p Hwfp Hwfc Hlinkable P.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable).\n  unfold EntryPoint.get, global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_entrypoints (prepare_global_env c)) C = None)\n    by (apply /dommPn; rewrite domm_genv_entrypoints; done).\n  rewrite HNone.\n  destruct ((genv_entrypoints (prepare_global_env p)) C) eqn:Hcase;\n    by rewrite Hcase.\nQed.\n\nLemma genv_entrypoints_interface_some p p' C P b :\n  well_formed_program p ->\n  well_formed_program p' ->\n  prog_interface p = prog_interface p' ->\n  EntryPoint.get C P (genv_entrypoints (prepare_global_env p )) = Some b ->\nexists b',\n  EntryPoint.get C P (genv_entrypoints (prepare_global_env p')) = Some b'.\nProof.\n  move=> Hwf Hwf' Hiface. unfold EntryPoint.get; simpl.\n  unfold prepare_procedures_initial_memory_aux. intros. eexists. revert H.\n  rewrite !mapmE. unfold omap, obind, oapp; simpl. rewrite 2!mkfmapfE -Hiface.\n  intros Hb.\n  destruct (C \\in domm (prog_interface p)) eqn:eC;\n    rewrite eC in Hb; last discriminate; rewrite eC.\n  simpl in *. find_if_inside_hyp Hb; last discriminate. inversion Hb. subst.\n  setoid_rewrite mem_filter in e. setoid_rewrite mem_filter.\n  move : e => /andP => [[Hentry Hbdomm]].\n  unfold is_entrypoint_of_comp in *. rewrite -Hiface.\n  destruct (prog_interface p C) eqn:eC2; last discriminate.\n  move : Hentry => /orP => [[Hexport | Hmain]].\n  - rewrite Hexport. simpl.\n    assert (exists (Cprocs : NMap code) (Pcode : code),\n               prog_procedures p' C = Some Cprocs /\\ Cprocs b = Some Pcode)\n      as [cdmap [cd [G1 G2]]].\n    { eapply wfprog_exported_procedures_existence; eauto. by rewrite -Hiface. }\n    rewrite G1 mem_domm G2. by simpl.\n  - unfold is_main_proc in *. destruct (prog_main p) eqn:emain; last discriminate.\n    rewrite Hmain.\n    assert (prog_main p') as G.\n    { rewrite -wfprog_main_component; auto. by rewrite -Hiface wfprog_main_component. }\n    rewrite G orbT andTb. specialize (wfprog_main_existence Hwf' G) as [? [G1 G2]].\n    assert (Component.main = C /\\ Procedure.main = b) as [? ?]; subst.\n    { move : Hmain => /andP => [[? ?]]. split; by apply beq_nat_eq. }\n    by rewrite G1 G2.\nQed.  \n\n(* RB: NOTE: The two EntryPoint lemmas can be phrased as a more general one\n   operating on an explicit program link, one then being the exact symmetric of\n   the other, i.e., its application after communativity of linking. There is a\n   choice of encoding of component membership in both cases. *)\n\n(* RB: TODO: Rephrase goal as simple equality? *)\n(* Search _ EntryPoint.get. *)\nLemma genv_entrypoints_recombination_left :\n  forall p c c',\n    well_formed_program p ->\n    well_formed_program c ->\n    well_formed_program c' ->\n    mergeable_interfaces (prog_interface p) (prog_interface c) ->\n    prog_interface c = prog_interface c' ->\n  forall C P b,\n    C \\in domm (prog_interface p) ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c ))) = Some b ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p c'))) = Some b.\nProof.\n  intros p c c' Hwfp Hwfc Hwfc' Hmergeable_ifaces Hifacec C P b Hdomm Hentry.\n  pose proof proj1 Hmergeable_ifaces as Hlinkable.\n  eapply (domm_partition_notin _ _ (mergeable_interfaces_sym _ _ Hmergeable_ifaces)) in Hdomm.\n  rewrite genv_entrypoints_program_link_left in Hentry; try assumption.\n  rewrite Hifacec in Hlinkable, Hdomm.\n  rewrite genv_entrypoints_program_link_left; assumption.\nQed.\n\nLemma genv_entrypoints_recombination_right :\n  forall p c p' c',\n    well_formed_program p ->\n    well_formed_program p' ->\n    well_formed_program c' ->\n    mergeable_interfaces (prog_interface p) (prog_interface c) ->\n    prog_interface p = prog_interface p' ->\n    prog_interface c = prog_interface c' ->\n  forall C P b,\n    C \\in domm (prog_interface c) ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p' c'))) = Some b ->\n    EntryPoint.get C P (genv_entrypoints (prepare_global_env (program_link p  c'))) = Some b.\nProof.\n  intros p c p' c' Hwfp Hwfp' Hwfc' Hmergeable_ifaces Hifacep Hifacec C P b Hdomm Hentry.\n  pose proof proj1 Hmergeable_ifaces as Hlinkable.\n  rewrite program_linkC in Hentry; try congruence.\n  rewrite program_linkC; try congruence.\n  eapply genv_entrypoints_recombination_left with (c := p'); try assumption; try congruence.\n  rewrite -Hifacec -Hifacep. now apply mergeable_interfaces_sym.\nQed.\n\nFixpoint find_label (c : code) (l : label) : option Z :=\n  let fix aux c o :=\n      match c with\n      | [] => None\n      | ILabel l' :: c' =>\n        if Nat.eqb l l' then\n          Some o\n        else\n          aux c' (1 + o)%Z\n      | _ :: c' =>\n        aux c' (1 + o)%Z\n      end\n  in aux c 0%Z.\n\nDefinition find_label_in_procedure G (pc : Pointer.t) (l : label) : option Pointer.t :=\n  match getm (genv_procedures G) (Pointer.component pc) with\n  | Some C_procs =>\n    match getm C_procs (Pointer.block pc) with\n    | Some P_code =>\n      match find_label P_code l with\n      | Some offset => Some (Pointer.permission pc,\n                             Pointer.component pc, Pointer.block pc, offset)\n      | None => None\n      end\n    | None => None\n    end\n  | None => None\n  end.\n\n\nDefinition find_label_in_component_helper\n         G (procs: list (Block.id * code))\n         (pc: Pointer.t) (l: label) : option Pointer.t :=\n  match filter (fun b_c =>\n                  isSome\n                    (find_label_in_procedure\n                       G\n                       (Pointer.permission pc,\n                        Pointer.component pc, b_c.1, 0%Z)\n                       l\n                    )\n               )\n               procs\n  with\n  | [] => None\n  | (p_block,p_code) :: procs' =>\n    find_label_in_procedure G (Pointer.permission pc,\n                               Pointer.component pc, p_block, 0%Z) l\n  end.\n\nDefinition find_label_in_component G (pc : Pointer.t) (l : label) : option Pointer.t :=\n  match getm (genv_procedures G) (Pointer.component pc) with\n  | Some C_procs =>\n    find_label_in_component_helper G (elementsm C_procs) pc l\n  | None => None\n  end.\n\nLemma find_label_in_procedure_guarantees:\n  forall G pc pc' l,\n    find_label_in_procedure G pc l = Some pc' ->\n    Pointer.permission pc = Pointer.permission pc' /\\\n    Pointer.component pc = Pointer.component pc' /\\\n    Pointer.block pc = Pointer.block pc'.\nProof.\n  intros G pc pc' l Hfind.\n  unfold find_label_in_procedure in Hfind.\n  destruct (getm (genv_procedures G) (Pointer.component pc)) as [procs|];\n    try discriminate.\n  destruct (getm procs (Pointer.block pc)) as [code|];\n    try discriminate.\n  destruct (find_label code l) as [offset|];\n    try discriminate.\n  destruct pc' as [[[pc'p pc'c] pc'b] pc'o].\n  inversion Hfind. subst.\n  split; auto; split; auto.\nQed.\n  \nLemma find_label_in_procedure_spec G pc l perm c b o:\n  find_label_in_procedure G pc l = Some (perm, c, b, o) <->\n  (\n    exists C_procs P_code,\n      getm (genv_procedures G) (Pointer.component pc) = Some C_procs /\\\n      getm C_procs (Pointer.block pc) = Some P_code /\\\n      perm = Pointer.permission pc /\\\n      c = Pointer.component pc /\\\n      b = Pointer.block pc /\\\n      find_label P_code l = Some o\n  ).\nProof.\n  unfold find_label_in_procedure.\n  split; [intros Hfind | intros [? [? [HC_procs [HP_code [? [? [? Ho]]]]]]]].\n  - destruct (genv_procedures G (Pointer.component pc)) as [A|] eqn:eA;\n      last discriminate.\n    destruct (A (Pointer.block pc)) as [B|] eqn:eB; last discriminate.\n    destruct (find_label B l) as [C|] eqn:eC; last discriminate.\n    inversion Hfind; subst. do 2 eexists. intuition; by eauto.\n  - subst. by rewrite HC_procs HP_code Ho.\nQed.\n\nLemma find_label_in_procedure_1:\n  forall G pc pc' l,\n    find_label_in_procedure G pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  eapply find_label_in_procedure_guarantees.\nQed.\n\n\nLemma find_label_in_component_helper_Some_exists_code:\n  forall p procMap l pc perm c bid o,\n    genv_procedures (prepare_global_env p) (Pointer.component pc) = Some procMap ->\n    find_label_in_component_helper\n      (prepare_global_env p) (elementsm procMap) pc l =\n    Some (perm, c, bid, o) ->\n    exists cd, procMap bid = Some cd.\nProof.\n  intros ? ? ? ? ? ? ? ? HprocMap HSome.\n  unfold find_label_in_component_helper in *.\n  destruct ([seq b_c <- elementsm procMap\n            | find_label_in_procedure\n                (prepare_global_env p)\n                (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l])\n           as [|[p_block x] t] eqn:efilter; first discriminate.\n  apply find_label_in_procedure_spec in HSome as [? [? [G1 [? [? [? [? ?]]]]]]].\n  rewrite HprocMap in G1. inversion G1; subst. by eauto.\nQed.\n\nLemma find_label_in_procedure_program_link_left:\n  forall {c pc},\n    Pointer.component pc \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n  forall {l},\n    find_label_in_procedure (prepare_global_env (program_link p c)) pc l =\n    find_label_in_procedure (prepare_global_env p) pc l.\nProof.\n  (* RB: Note the proof strategy for all these lemmas is remarkably similar.\n     It may be worthwhile to refactor it and/or its intermediate steps. *)\n  intros c pc Hnotin p Hwfp Hwfc Hlinkable l.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable).\n  unfold find_label_in_procedure, global_env_union; simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env c)) (Pointer.component pc) = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) (Pointer.component pc)) eqn:Hcase;\n    by rewrite Hcase.\nQed.\n\nLemma find_label_in_component_helper_guarantees:\n  forall G procs pc pc' l,\n    find_label_in_component_helper G procs pc l = Some pc' ->\n    Pointer.permission pc = Pointer.permission pc' /\\\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  unfold find_label_in_component_helper. intros G procs pc pc' l Hfind.\n  destruct [seq b_c <- procs\n           | find_label_in_procedure\n               G\n               (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l] eqn:efilter;\n    first discriminate.\n  destruct p as [? ?].\n  apply find_label_in_procedure_guarantees in Hfind. by intuition.\nQed.\n\nLemma find_label_in_component_1:\n  forall G pc pc' l,\n    find_label_in_component G pc l = Some pc' ->\n    Pointer.component pc = Pointer.component pc'.\nProof.\n  intros G pc pc' l Hfind.\n  unfold find_label_in_component in Hfind.\n  destruct (getm (genv_procedures G) (Pointer.component pc)) as [procs|];\n    try discriminate.\n  eapply find_label_in_component_helper_guarantees in Hfind; by intuition.\nQed.\n\nLemma find_label_in_component_perm:\n  forall G pc pc' l,\n    find_label_in_component G pc l = Some pc' ->\n    Pointer.permission pc = Pointer.permission pc'.\nProof.\n  intros G pc pc' l Hfind.\n  unfold find_label_in_component in Hfind.\n  destruct (getm (genv_procedures G) (Pointer.component pc)) as [procs|];\n    try discriminate.\n  eapply find_label_in_component_helper_guarantees in Hfind; by intuition.\nQed.  \n\nLemma find_label_in_component_program_link_left:\n  forall {c pc},\n    Pointer.component pc \\notin domm (prog_interface c) ->\n  forall {p},\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n  forall {l},\n    find_label_in_component (prepare_global_env (program_link p c)) pc l =\n    find_label_in_component (prepare_global_env p) pc l.\nProof.\n  intros c pc Hnotin p Hwfp Hwfc Hlinkable l.\n  rewrite (prepare_global_env_link Hwfp Hwfc Hlinkable).\n  unfold find_label_in_component. unfold global_env_union at 1. simpl.\n  rewrite unionmE.\n  assert (HNone : (genv_procedures (prepare_global_env c)) (Pointer.component pc) = None)\n    by (apply /dommPn; rewrite domm_genv_procedures; done).\n  rewrite HNone.\n  destruct ((genv_procedures (prepare_global_env p)) (Pointer.component pc))\n    as [procs |] eqn:Hcase;\n    rewrite Hcase; simpl; last by auto.\n  - simpl.\n    unfold find_label_in_component_helper; simpl.\n    assert (Hnotin' : forall b,\n               Pointer.component\n                 (Pointer.permission pc, Pointer.component pc, b, 0%Z)\n                 \\notin domm (prog_interface c)).\n      by done.\n\n    assert (Hrewr: forall b_c: Block.id * code,\n               find_label_in_procedure\n                 (global_env_union (prepare_global_env p) (prepare_global_env c))\n                 (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l\n               =\n               find_label_in_procedure\n                 (prepare_global_env p)\n                 (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l\n           ).\n    {\n      rewrite <- (prepare_global_env_link Hwfp Hwfc Hlinkable).\n      intros b_c.\n      by rewrite\n        (find_label_in_procedure_program_link_left (Hnotin' b_c.1) Hwfp Hwfc Hlinkable).\n    }\n    assert (Hrewr2:\n               [seq b_c <- elementsm procs\n               | find_label_in_procedure\n                   (global_env_union (prepare_global_env p)\n                                     (prepare_global_env c))\n                   (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l]\n               =\n               [seq b_c <- elementsm procs\n               | find_label_in_procedure\n                   (prepare_global_env p)\n                   (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l]\n           ).\n    {\n      apply eq_filter. unfold \"=1\". intros. by rewrite Hrewr.\n    }\n    rewrite Hrewr2.\n    destruct ([seq b_c <- elementsm procs\n              | find_label_in_procedure\n                  (prepare_global_env p)\n                  (Pointer.permission pc, Pointer.component pc, b_c.1, 0%Z) l]); auto.\n    destruct p0 as [b cd].\n    specialize (Hrewr (b, cd)). by simpl in Hrewr.\nQed.\n\n(* RB: Unified presentation of linkable + linkable_mains, to be used as needed\n   around the development? *)\nLemma execution_invariant_to_linking:\n  forall p c1 c2 pc instr,\n    linkable (prog_interface p) (prog_interface c1) ->\n    linkable (prog_interface p) (prog_interface c2) ->\n    well_formed_program p ->\n    well_formed_program c1 ->\n    well_formed_program c2 ->\n    Pointer.component pc \\in domm (prog_interface p) ->\n    executing (prepare_global_env (program_link p c1)) pc instr ->\n    executing (prepare_global_env (program_link p c2)) pc instr.\nProof.\n  intros p c1 c2 pc instr Hlinkable1 Hlinkable2 Hwf Hwf1 Hwf2 Hpc Hexec.\n  inversion Hexec as [procs [proc [Hgenv_procs [Hprocs_proc [Hoffset Hproc_instr]]]]].\n  exists procs, proc.\n  split; [| split; [| split]];\n    [| assumption | assumption | assumption].\n  assert (Pointer.component pc \\notin domm (prog_interface c1)) as Hcc1.\n  {\n    inversion Hlinkable1 as [_ Hdisjoint]. apply /fdisjointP. apply Hdisjoint. assumption.\n  }\n  assert (Pointer.component pc \\notin domm (prog_interface c2)) as Hcc2.\n  {\n    inversion Hlinkable2 as [_ Hdisjoint]. apply /fdisjointP. apply Hdisjoint. assumption.\n  }\n  rewrite (genv_procedures_program_link_left_notin Hcc1 Hwf Hwf1 Hlinkable1) in Hgenv_procs.\n  rewrite (genv_procedures_program_link_left_notin Hcc2 Hwf Hwf2 Hlinkable2).\n  assumption.\nQed.\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/GlobalEnv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16943946553583702}}
{"text": "Require Import Raft.\nRequire Import 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.", "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/StateMachineCorrectInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.16943945722684028}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import AbstractMachine.Spec.\nRequire Import Locks.Spec.\nRequire Import VMPower.Layer.\nRequire Import RData.\nRequire Import Constants.\nRequire Import HypsecCommLib.\n\nLocal Open Scope Z_scope.\n\nSection BootCoreSpec.\n\n  Definition gen_vmid_spec (adt: RData) : option (RData * Z) :=\n    if halt adt then Some (adt, 0) else\n    let cpu := curid adt in\n    match CORE_ID @ (lock adt), CORE_ID @ (oracle adt), CORE_ID @ (log adt) with\n    | LockFalse, orac, l0 =>\n      match H_CalLock ((orac cpu l0) ++ l0) with\n      | Some (_, LEMPTY, None) =>\n        let core := CalCoreData (core_data (shared adt)) (orac cpu l0) in\n        let vmid := next_vmid core in\n        rely is_vmid vmid;\n        if vmid <? COREVISOR then\n          let core' := core {next_vmid: vmid + 1} in\n          let l' :=  TEVENT cpu (TTICKET REL_LOCK) :: TEVENT cpu (TSHARED (OCORE_DATA core')) ::\n                            TEVENT cpu (TSHARED (OPULL CORE_ID)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) ::\n                            (orac cpu l0) ++ l0 in\n          Some (adt {tstate: 1} {shared: (shared adt) {core_data: core'}}\n                    {log: (log adt) # CORE_ID == l'} {lock: (lock adt) # CORE_ID == LockFalse},\n                vmid)\n        else\n          let l' := TEVENT cpu (TSHARED (OPULL CORE_ID)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: (orac cpu l0) ++ l0 in\n          Some (adt {halt: true} {tstate: 0} {shared: (shared adt) {core_data: core}}\n                    {log: (log adt) # CORE_ID == l'} {lock: (lock adt) # CORE_ID == (LockOwn true)},\n                0)\n      | _ => None\n      end\n    | _, _, _ => None\n    end.\n\n  Definition alloc_remap_addr_spec (pgnum: Z64) (adt: RData) : option (RData * Z64) :=\n    match pgnum with\n    | VZ64 pgnum =>\n      rely is_gfn pgnum;\n      if halt adt then Some (adt, (VZ64 0)) else\n      let cpu := curid adt in\n      match CORE_ID @ (lock adt), CORE_ID @ (oracle adt), CORE_ID @ (log adt) with\n      | LockFalse, orac, l0 =>\n        match H_CalLock ((orac cpu l0) ++ l0) with\n        | Some (_, LEMPTY, None) =>\n          let core := CalCoreData (core_data (shared adt)) (orac cpu l0) in\n          let remap := next_remap_ptr core in\n          rely is_addr remap;\n          if remap + pgnum * PAGE_SIZE <? REMAP_END then\n            let core' := core {next_remap_ptr: remap + pgnum * PAGE_SIZE} in\n            let l' :=  TEVENT cpu (TTICKET REL_LOCK) :: TEVENT cpu (TSHARED (OCORE_DATA core')) ::\n                              TEVENT cpu (TSHARED (OPULL CORE_ID)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) ::\n                              (orac cpu l0) ++ l0 in\n            Some (adt {tstate: 1} {shared: (shared adt) {core_data: core'}}\n                      {log: (log adt) # CORE_ID == l'} {lock: (lock adt) # CORE_ID == LockFalse},\n                  (VZ64 remap))\n          else\n            let l' := TEVENT cpu (TSHARED (OPULL CORE_ID)) :: TEVENT cpu (TTICKET (WAIT_LOCK local_lock_bound)) :: (orac cpu l0) ++ l0 in\n            Some (adt {halt: true} {tstate: 0} {shared: (shared adt) {core_data: core}}\n                      {log: (log adt) # CORE_ID == l'} {lock: (lock adt) # CORE_ID == (LockOwn true)},\n                  (VZ64 0))\n        | _ => None\n        end\n      | _, _, _ => None\n      end\n    end.\n\nEnd BootCoreSpec.\n\nSection BootCoreSpecLow.\n\n  Context `{real_params: RealParams}.\n\n  Notation LDATA := RData.\n\n  Notation LDATAOps := (cdata (cdata_ops := VMPower_ops) LDATA).\n\n  Definition gen_vmid_spec0  (adt: RData) : option (RData * Z) :=\n    when adt' == acquire_lock_core_spec adt;\n    when vmid == get_next_vmid_spec adt';\n    rely is_vmid vmid;\n    if vmid <? COREVISOR then\n      when adt2 == set_next_vmid_spec (vmid + 1) adt';\n      when adt3 == release_lock_core_spec adt2;\n      when res == check_spec vmid adt3;\n      Some (adt3, res)\n    else\n      when adt2 == panic_spec adt';\n      when adt3 == release_lock_core_spec adt2;\n      when res == check_spec vmid adt3;\n      Some (adt3, res).\n\n  Definition alloc_remap_addr_spec0 (pgnum: Z64) (adt: RData) : option (RData * Z64) :=\n    match pgnum with\n    | VZ64 pgnum =>\n      when adt' == acquire_lock_core_spec adt;\n      when' remap == get_next_remap_ptr_spec adt';\n      rely is_addr remap; rely is_gfn pgnum;\n      if remap + pgnum * PAGE_SIZE <? REMAP_END then\n        when adt2 == set_next_remap_ptr_spec (VZ64 (remap + pgnum * PAGE_SIZE)) adt';\n        when adt3 == release_lock_core_spec adt2;\n        when' res == check64_spec (VZ64 remap) adt3;\n        Some (adt3, VZ64 res)\n      else\n        when adt2 == panic_spec adt';\n        when adt3 == release_lock_core_spec adt2;\n        when' res == check64_spec (VZ64 remap) adt3;\n        Some (adt3, VZ64 res)\n    end.\n\n  Inductive gen_vmid_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | gen_vmid_spec_low_intro s (WB: _ -> Prop) m'0 labd labd'  res\n      (Hinv: high_level_invariant labd)\n      (Hspec: gen_vmid_spec0 labd = Some (labd', (Int.unsigned res))):\n      gen_vmid_spec_low_step s WB nil (m'0, labd) (Vint res) (m'0, labd').\n\n  Inductive alloc_remap_addr_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | alloc_remap_addr_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' pgnum res\n      (Hinv: high_level_invariant labd)\n      (Hspec: alloc_remap_addr_spec0 (VZ64 (Int64.unsigned pgnum)) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      alloc_remap_addr_spec_low_step s WB ((Vlong pgnum)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModelX}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Definition gen_vmid_spec_low: compatsem LDATAOps :=\n      csem gen_vmid_spec_low_step (type_of_list_type nil) Tint32.\n\n    Definition alloc_remap_addr_spec_low: compatsem LDATAOps :=\n      csem alloc_remap_addr_spec_low_step (type_of_list_type (Tint64::nil)) Tint64.\n\n  End WITHMEM.\n\nEnd BootCoreSpecLow.\n\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/sekvm/BootCore/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.16926798577033003}}
{"text": "(** * Every parse tree has a corresponding minimal parse tree *)\n\nRequire Import Coq.omega.Omega.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.StringLike.LastChar.\nRequire Import Fiat.Parsers.Reachable.OnlyLast.Reachable.\nRequire Import Fiat.Parsers.Reachable.OnlyLast.MinimalReachable.\nRequire Import Fiat.Parsers.Reachable.OnlyLast.MinimalReachableOfReachable.\nRequire Import Fiat.Parsers.Reachable.MaybeEmpty.MinimalOfCore.\nRequire Import Fiat.Parsers.Reachable.MaybeEmpty.OfParse.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Common.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} {G : grammar Char}.\n  Context {predata : @parser_computational_predataT Char}\n          {rdata' : @parser_removal_dataT' _ G predata}.\n\n  Definition for_last_char_reachable_from_parse_of_item'\n             (for_last_char_reachable_from_parse_of_productions\n              : forall valid0 pats\n                       (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n                       (str : String) (p : parse_of G str pats)\n                       (Hforall : Forall_parse_of (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p),\n                  for_last_char str (fun ch => inhabited (reachable_from_productions G ch valid0 pats)))\n             {valid0 it}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of_item G str it)\n             (Hforall : Forall_parse_of_item (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n  : for_last_char str (fun ch => inhabited (reachable_from_item G ch valid0 it)).\n  Proof.\n    destruct p as [ | nt ? p ].\n    { rewrite <- for_last_char_singleton by eassumption.\n      repeat constructor; assumption. }\n    { specialize (for_last_char_reachable_from_parse_of_productions valid0 (G nt) Hsub str p (snd Hforall)).\n      revert for_last_char_reachable_from_parse_of_productions.\n      apply for_last_char_Proper; [ reflexivity | intros ? [H'] ].\n      constructor.\n      constructor; simpl in *; [ exact (fst Hforall) | assumption ]. }\n  Defined.\n\n  Fixpoint for_last_char_reachable_from_parse_of_productions\n             {valid0 pats}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of G str pats)\n             (Hforall : Forall_parse_of (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n             {struct p}\n  : for_last_char str (fun ch => inhabited (reachable_from_productions G ch valid0 pats))\n  with for_last_char_reachable_from_parse_of_production\n         {valid0 pat}\n         (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n         (str : String) (p : parse_of_production G str pat)\n         (Hforall : Forall_parse_of_production (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n         {struct p}\n       : for_last_char str (fun ch => inhabited (reachable_from_production G ch valid0 pat)).\n  Proof.\n    { destruct p as [ ?? p | ?? p ]; simpl in *.\n      { generalize (for_last_char_reachable_from_parse_of_production valid0 _ Hsub _ p Hforall).\n        apply for_last_char_Proper; [ reflexivity | intros ? [H']; constructor ].\n        left; assumption. }\n      { generalize (for_last_char_reachable_from_parse_of_productions valid0 _ Hsub _ p Hforall).\n        apply for_last_char_Proper; [ reflexivity | intros ? [H']; constructor ].\n        right; assumption. } }\n    { destruct p as [ | [|n] ? p ]; simpl in *.\n      { apply for_last_char_nil; assumption. }\n      { rewrite <- drop_0.\n        generalize (@for_last_char_reachable_from_parse_of_production valid0 _ Hsub _ _ (snd Hforall)).\n          apply for_last_char_Proper; [ reflexivity | intros ? [H']; constructor ].\n          right; assumption. }\n      { specialize (for_last_char_reachable_from_parse_of_production _ _ Hsub _ _ (snd Hforall)).\ndestruct (Compare_dec.le_lt_dec (length str) (S n)) as [Hle|Hle].\n        { pose proof (fun pf => parse_empty_minimal_maybe_empty_parse_of_production Hsub pf _ (snd Hforall)) as Hempty.\n          rewrite drop_length in Hempty.\n          specialize_by omega.\n          generalize (@for_last_char_reachable_from_parse_of_item' for_last_char_reachable_from_parse_of_productions valid0 _ Hsub _ _ (fst Hforall)).\n          rewrite take_long by omega.\n          apply for_last_char_Proper; [ reflexivity | intros ? [H']; constructor ].\n          eapply maybe_empty_production__of__minimal_maybe_empty_production in Hempty; [ | reflexivity ].\n          left; assumption. }\n        { revert for_last_char_reachable_from_parse_of_production.\n          rewrite <- for_last_char__drop by assumption.\n          apply for_last_char_Proper; [ reflexivity | intros ? [H']; constructor ].\n          right; assumption. } } }\n  Defined.\n\n  Definition for_last_char_reachable_from_parse_of_item\n             {valid0 it}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of_item G str it)\n             (Hforall : Forall_parse_of_item (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n  : for_last_char str (fun ch => inhabited (reachable_from_item G ch valid0 it))\n    := @for_last_char_reachable_from_parse_of_item' (@for_last_char_reachable_from_parse_of_productions) valid0 it Hsub str p Hforall.\n\n  Definition for_last_char_minimal_reachable_from_parse_of_item\n             {valid0 it}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of_item G str it)\n             (Hforall : Forall_parse_of_item (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n  : for_last_char str (fun ch => inhabited (minimal_reachable_from_item (G := G) valid0 ch valid0 it)).\n  Proof.\n    setoid_rewrite <- (minimal_reachable_from_item__iff__reachable_from_item Hsub).\n    eapply for_last_char_reachable_from_parse_of_item; eassumption.\n  Qed.\n\n  Definition for_last_char_minimal_reachable_from_parse_of_production\n             {valid0 pat}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of_production G str pat)\n             (Hforall : Forall_parse_of_production (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n  : for_last_char str (fun ch => inhabited (minimal_reachable_from_production (G := G) valid0 ch valid0 pat)).\n  Proof.\n    setoid_rewrite <- (minimal_reachable_from_production__iff__reachable_from_production Hsub).\n    eapply for_last_char_reachable_from_parse_of_production; eassumption.\n  Qed.\n\n  Definition for_last_char_minimal_reachable_from_parse_of_productions\n             {valid0 pats}\n             (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n             (str : String) (p : parse_of G str pats)\n             (Hforall : Forall_parse_of (fun _ nt' => is_valid_nonterminal valid0 (of_nonterminal nt')) p)\n  : for_last_char str (fun ch => inhabited (minimal_reachable_from_productions (G := G) valid0 ch valid0 pats)).\n  Proof.\n    setoid_rewrite <- (minimal_reachable_from_productions__iff__reachable_from_productions Hsub).\n    eapply for_last_char_reachable_from_parse_of_productions; eassumption.\n  Qed.\nEnd cfg.\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/Reachable/OnlyLast/ReachableParse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.16917437982549377}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import sha.vst_lemmas.\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, Tsh, secret, SECRET, Tsh, shmd, sb, si, gv). (*3.7s*)\napply extract_exists_pre; intros Hmac. \nidtac \"Timing the normalize\". Time normalize. (*Coq8.6: 1secs*)\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   gvars gv)\n   SEP (spec_sha.K_vector gv; data_block shmd Hmac out; initPostKey Tsh (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; lia.\n  + auto with valid_pointer. }\n{ subst out; contradiction. }\n{ clear H; forward. entailer!. rewrite <- @change_compspecs_data_block. simpl; auto. }\n\nforward. forward. \nsimpl.\nunfold HKDF_extract. cancel. rewrite @change_compspecs_data_block. trivial.\nTime Qed.\n(*Finished transaction in 0.545 secs (0.544u,0.s) (successful)*)", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sha/verif_hkdf_extract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362517, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16917437089473109}}
{"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_tactics mips_contrib mapstos mips_frame.\nRequire Import copy_s_u_prg multi_is_zero_u_triple copy_u_u_triple.\nRequire Import multi_zero_s_triple.\nImport expr_m.\nImport assert_m.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope multi_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope zarith_ext_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.\n\nLemma copy_s_u_triple rk rx ry xtmp ytmp i j : uniq(rk, rx, ry, xtmp, ytmp, i, j, r0) ->\n  forall X Y nk, size X = nk -> size Y = nk ->\n    forall slen,\n      forall ptr, u2Z ptr + 4 * Z_of_nat nk < \\B^1 ->\n      forall vy, u2Z vy + 4 * Z_of_nat nk < \\B^1 ->\n  {{ fun s h => [ry]_s = vy /\\\n    u2Z [rk]_s = Z_of_nat nk /\\\n    ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) **\n     var_e ry |--> Y) s h }}\n  copy_s_u rk rx ry xtmp ytmp i j\n  {{ fun s h => [ry]_s = vy /\\\n    u2Z [rk]_s = Z_of_nat nk /\\\n    ((var_e rx |--> (if \\S_{ nk } Y == 0 then zero32 else Z2u 32 (Z_of_nat nk)) :: ptr :: nil **\n       int_e ptr |--> (if \\S_{ nk } Y == 0 then X else Y)) **\n      var_e ry |--> Y) s h }}.\nProof.\nmove=> Hnodup X Y nk X_nk Y_nk slen ptr ptr_fit vy vy_fit.\nrewrite /copy_s_u.\n\napply while.hoare_seq with (fun s h => [ry]_s = vy /\\\n  u2Z ([rk ]_ s) = Z_of_nat nk /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) ** var_e ry |--> Y) s h /\\\n  (0 = \\S_{ nk } Y -> [i]_s = one32) /\\\n  (0 < \\S_{ nk } Y -> [i]_s = zero32)).\n\nhave : uniq(rk, ry, xtmp, ytmp, i, r0) by Uniq_uniq r0.\nmove/multi_is_zero_u_triple/(_ _ _ _ Y_nk vy_fit) => Htmp.\neapply (before_frame (var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X)).\n  apply frame_rule_R.\n    by apply Htmp.\n    rewrite [modified_regs _]/=; by Inde.\n  by [].\n  move=> s h [ry_vy [rk_nk]].\n  case => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\n  rewrite assert_m.conCE.\n  by exists h1, h2; repeat (split => //).\nmove=> s h.\ncase => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\ncase: Hh1 => rk_nk [ry_vy [Hh1 HSum]].\nrepeat (split; first by []).\nsplit; last by [].\nrewrite assert_m.conCE.\nby exists h1, h2.\n\napply hoare_ifte_bang.\n\napply (hoare_prop_m.hoare_stren (fun s h => 0 < \\S_{ nk } Y /\\ [ry ]_ s = vy /\\\n  u2Z ([rk ]_ s) = Z_of_nat nk /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) ** var_e ry |--> Y) s h)).\n\nmove=> s h H.\napply assert_m.con_and_bang_inv_R in H.\ncase: H => [[ry_vy [rk_nk [H HSum]]] Htest].\nrepeat (split => //).\ncase/leZ_eqVlt : (min_lSum nk Y) => // Sum_Y.\ncase: HSum.\nmove/(_ Sum_Y) => Hi _.\nrewrite /= Hi store.get_r0 in Htest.\nmove/eqP : Htest.\nby rewrite !Z2uK.\n\napply (hoare_prop_m.pull_out_conjunction' hoare0_false) => HSum.\n\napply hoare_lw_back_alt'' with (fun s h =>\n  [ry ]_ s = vy /\\\n  u2Z ([rk ]_ s) = Z_of_nat nk /\\\n  ((var_e rx |--> slen :: ptr :: nil ** int_e ptr |--> X) ** var_e ry |--> Y) s h /\\\n  [xtmp]_s = ptr).\n\nmove=> s h [ry_vy [rk_nk Hmem]].\nexists ptr; split.\n- rewrite -assert_m.mapsto2_mapstos in Hmem.\n  Rotate Hmem.\n  move: Hmem; apply assert_m.monotony => // h'.\n  apply assert_m.mapsto_ext => //.\n  by rewrite sext_Z2u.\n- rewrite /update_store_lw.\n  repeat Reg_upd.\n  repeat (split; first by []).\n  split; last by [].\n  by Assert_upd.\n\napply while.hoare_seq with (\n  !(fun s => ([xtmp ]_ s) = ptr) **\n  !(fun s => ([ry ]_ s) = vy) **\n  !(fun s => u2Z ([rk ]_ s) = Z_of_nat nk) **\n  (var_e ry |--> Y ** var_e xtmp |--> Y) **\n  var_e rx |--> slen :: ptr :: nil).\n\nhave : uniq(rk, xtmp, ry, ytmp, i, j, r0) by Uniq_uniq r0.\nmove/copy_u_u_triple/(_ _ _ _ Y_nk X_nk _ ptr_fit) => Htmp.\neapply (before_frame (!(fun s => [ry ]_ s = vy) ** (var_e rx |--> slen :: ptr :: nil))).\napply frame_rule_R.\n  by apply Htmp.\n  rewrite [modified_regs _]/=; by Inde.\ndone.\nmove=> s h [ry_vy [rk_nk [Hmem xtmp_ptr]]].\nrewrite assert_m.conAE in Hmem.\ncase: Hmem => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\nrewrite assert_m.conCE.\nexists h1, h2; repeat (split => //).\napply assert_m.con_and_bang_L => //.\nrewrite assert_m.conCE.\nmove: Hh2.\napply assert_m.monotony => // h'.\nby apply assert_m.mapstos_ext.\nmove=> s h H.\ncase: H => h1 [h2 [h1dh2 [h1Uh2 [[xtmp_ptr [rk_nk Hh1]] Hh2]]]].\napply assert_m.con_and_bang_inv_L in Hh2.\ncase: Hh2 => ry_vy Hh2.\napply assert_m.con_and_bang_L => //.\napply assert_m.con_and_bang_L => //.\napply assert_m.con_and_bang_L => //.\nby exists h1, h2.\n\napply hoare_sw_back' => s h H.\nrewrite -assert_m.mapsto2_mapstos in H.\ndo 5 rewrite assert_m.conCE !assert_m.conAE in H.\nexists (int_e slen).\nmove: H; apply assert_m.monotony => // h'.\n- apply assert_m.mapsto_ext => //.\n  by rewrite /= sext_Z2u // addi0.\n- apply assert_m.currying => h'' Hh''.\n  rewrite !assert_m.conAE in Hh''.\n  do 2 rewrite assert_m.conCE !assert_m.conAE in Hh''.\n  apply assert_m.con_and_bang_inv_L in Hh''.\n  case: Hh'' => ry_vy Hh''.\n  apply assert_m.con_and_bang_inv_L in Hh''.\n  case: Hh'' => rk_nk Hh''.\n  repeat (split; first by []).\n  rewrite assert_m.conCE.\n  do 4 rewrite assert_m.conCE !assert_m.conAE in Hh''.\n  apply assert_m.con_and_bang_inv_L in Hh''.\n  case: Hh'' => xtmp_ptr Hh''.\n  move: Hh''; apply assert_m.monotony => // h3.\n  have -> : \\S_{ nk } Y == 0 = false.\n    apply/eqP => abs; rewrite abs in HSum.\n    by apply ltZZ in HSum.\n  rewrite assert_m.conCE.\n  apply assert_m.monotony => // h4; last first.\n    by apply assert_m.mapstos_ext => /=.\n  rewrite -assert_m.mapsto2_mapstos.\n  apply assert_m.monotony => // h5.\n  apply assert_m.mapsto_ext => //=.\n  by rewrite sext_Z2u // addi0.\n  by rewrite -rk_nk Z2u_u2Z.\n\nhave : uniq(rx, r0) by Uniq_uniq r0.\nmove/(multi_zero_s_triple)/(_ X ptr slen) => Htmp.\neapply (before_frame (fun s h => ([ry ]_ s) = vy /\\ u2Z ([rk ]_ s) = Z_of_nat nk /\\ (var_e ry |--> Y) s h /\\ \\S_{ nk } Y = 0)).\napply frame_rule_R.\nby apply Htmp.\ndone.\ndone.\nmove=> s h H.\napply assert_m.con_and_bang_inv_R in H.\ncase: H => [[ry_vy [rk_nk [H HSum]]] Htest].\ncase: H => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\nexists h1, h2; repeat (split => //).\nrewrite /= store.get_r0 Z2uK // in Htest.\ncase: HSum => _ HSum.\ncase/leZ_eqVlt : (min_lSum nk Y) => // Sum_Y.\napply HSum in Sum_Y.\nby rewrite Sum_Y Z2uK in Htest.\n\nmove=> s h [h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]]].\ncase: Hh2 => ry_vy [rk_nk [Hh2 HSum]].\nrepeat (split; first by []).\nrewrite HSum eqxx.\nby exists h1, h2; repeat (split => //).\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/copy_s_u_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.16907209722606073}}
{"text": "(*\n * \u00a9 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     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.InvariantSearch\n.\n\nFrom protocols Require Import\n     GenProto.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require 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 MyProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import MyProtocol.\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  (* Set Ltac Profiling. *)\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (@safety_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 *.\n\n    time (\n        repeat transition_system_step\n      ).\n\n      Unshelve.\n      all: exact 0 || auto.\n  Qed.\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 MyProtocolSecure.\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/GenProtoSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.16889636619247142}}
{"text": "Require Import Reals Psatz ClassicalEpsilon.\n(** An axiomatization of evaluation-context based languages, including a proof\n    that this gives rise to a \"language\" in the Iris sense. *)\nFrom iris.algebra Require Export base.\nFrom iris.program_logic Require Import prob_language.\nFrom discprob.prob Require Import prob countable.\nFrom mathcomp Require Import ssreflect bigop choice fintype finset ssrbool eqtype.\nSet Default Proof Using \"Type\".\n\n(* TAKE CARE: When you define an [ectxLanguage] canonical structure for your\nlanguage, you need to also define a corresponding [language] canonical\nstructure. Use the coercion [LanguageOfEctx] as defined in the bottom of this\nfile for doing that. *)\n\nSection ectx_language_mixin.\n  Context {expr val ectx state : Type}.\n  Context (of_val : val \u2192 expr).\n  Context (to_val : expr \u2192 option val).\n  Context (empty_ectx : ectx).\n  Context (comp_ectx : ectx \u2192 ectx \u2192 ectx).\n  Context (fill : ectx \u2192 expr \u2192 expr).\n  Context (head_step : expr \u2192 state \u2192 expr \u2192 state \u2192 list expr \u2192 Prop).\n  Context (head_step_prob : expr \u2192 state \u2192 expr \u2192 state \u2192 list expr \u2192 R).\n\n  Record EctxLanguageMixin := {\n    mixin_to_of_val v : to_val (of_val v) = Some v;\n    mixin_of_to_val e v : to_val e = Some v \u2192 of_val v = e;\n    mixin_val_head_stuck e1 \u03c31 e2 \u03c32 efs :\n      head_step e1 \u03c31 e2 \u03c32 efs \u2192 to_val e1 = None;\n\n    mixin_fill_empty e : fill empty_ectx e = e;\n    mixin_fill_comp K1 K2 e : fill K1 (fill K2 e) = fill (comp_ectx K1 K2) e;\n    mixin_fill_inj K : Inj (=) (=) (fill K);\n    mixin_fill_val K e : is_Some (to_val (fill K e)) \u2192 is_Some (to_val e);\n\n    (* There are a whole lot of sensible axioms (like associativity, and left and\n    right identity, we could demand for [comp_ectx] and [empty_ectx]. However,\n    positivity suffices. *)\n    mixin_ectx_positive K1 K2 :\n      comp_ectx K1 K2 = empty_ectx \u2192 K1 = empty_ectx \u2227 K2 = empty_ectx;\n\n    mixin_step_by_val K K' e1 e1' \u03c31 e2 \u03c32 efs :\n      fill K e1 = fill K' e1' \u2192\n      to_val e1 = None \u2192\n      head_step e1' \u03c31 e2 \u03c32 efs \u2192\n      \u2203 K'', K' = comp_ectx K K'';\n\n    mixin_step_by_val_eq K K' e1 e1' \u03c31 e2 e2' \u03c32 \u03c32' efs efs' :\n      fill K e1 = fill K' e1' \u2192\n      head_step e1 \u03c31 e2 \u03c32 efs \u2192\n      head_step e1' \u03c31 e2' \u03c32' efs' \u2192\n      K = K';\n\n    \n    mixin_head_step_count e \u03c3: \n      Countable.class_of { esf: expr * state * list expr |\n                           head_step e \u03c3 (esf.1.1) (esf.1.2) (esf.2) };\n    mixin_head_step_sum1 e \u03c3:\n        (\u2203 e' \u03c3' efs, head_step e \u03c3 e' \u03c3' efs) \u2192\n        is_series (countable_sum (\u03bb t : Countable.Pack (mixin_head_step_count e \u03c3)\n                                        { esf: expr * state * list expr |\n                                          head_step e \u03c3 (esf.1.1) (esf.1.2) (esf.2) },\n                                    head_step_prob e \u03c3\n                                                   (fst (fst (sval t)))\n                                                   (snd (fst (sval t)))\n                                                   (snd (sval t)))) 1;\n    mixin_head_step_nonneg : \u2200 e1 \u03c31 e2 \u03c32 efs, (head_step_prob e1 \u03c31 e2 \u03c32 efs >= 0)%R;\n    mixin_head_step_strict_gt :\n    \u2200 e1 \u03c31 e2 \u03c32 efs, head_step e1 \u03c31 e2 \u03c32 efs \u2194 (head_step_prob e1 \u03c31 e2 \u03c32 efs > 0)%R\n\n  }.\nEnd ectx_language_mixin.\n\nStructure ectxLanguage := EctxLanguage {\n  expr : Type;\n  val : Type;\n  ectx : Type;\n  state : Type;\n\n  of_val : val \u2192 expr;\n  to_val : expr \u2192 option val;\n  empty_ectx : ectx;\n  comp_ectx : ectx \u2192 ectx \u2192 ectx;\n  fill : ectx \u2192 expr \u2192 expr;\n  head_step : expr \u2192 state \u2192 expr \u2192 state \u2192 list expr \u2192 Prop;\n  head_step_prob : expr \u2192 state \u2192 expr \u2192 state \u2192 list expr \u2192 R;\n\n  ectx_language_mixin :\n    EctxLanguageMixin of_val to_val empty_ectx comp_ectx fill head_step head_step_prob;\n\n}.\n\nArguments EctxLanguage {_ _ _ _ _ _ _ _ _ _ _} _.\nArguments of_val {_} _%V.\nArguments to_val {_} _%E.\nArguments empty_ectx {_}.\nArguments comp_ectx {_} _ _.\nArguments fill {_} _ _%E.\nArguments head_step {_} _%E _ _%E _ _.\nArguments head_step_prob {_} _%E _ _%E _ _.\n\n(* From an ectx_language, we can construct a language. *)\nSection ectx_language.\n  Context {\u039b : ectxLanguage}.\n  Implicit Types v : val \u039b.\n  Implicit Types e : expr \u039b.\n  Implicit Types K : ectx \u039b.\n\n  (* Only project stuff out of the mixin that is not also in language *)\n  Lemma val_head_stuck e1 \u03c31 e2 \u03c32 efs : head_step e1 \u03c31 e2 \u03c32 efs \u2192 to_val e1 = None.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma fill_empty e : fill empty_ectx e = e.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma fill_comp K1 K2 e : fill K1 (fill K2 e) = fill (comp_ectx K1 K2) e.\n  Proof. apply ectx_language_mixin. Qed.\n  Global Instance fill_inj K : Inj (=) (=) (fill K).\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma fill_val K e : is_Some (to_val (fill K e)) \u2192 is_Some (to_val e).\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma ectx_positive K1 K2 :\n    comp_ectx K1 K2 = empty_ectx \u2192 K1 = empty_ectx \u2227 K2 = empty_ectx.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma step_by_val_eq K K' e1 e1' \u03c31 e2 e2' \u03c32 \u03c32' efs efs' :\n      fill K e1 = fill K' e1' \u2192\n      head_step e1 \u03c31 e2 \u03c32 efs \u2192\n      head_step e1' \u03c31 e2' \u03c32' efs' \u2192\n      K = K'.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma step_by_val K K' e1 e1' \u03c31 e2 \u03c32 efs :\n    fill K e1 = fill K' e1' \u2192\n    to_val e1 = None \u2192\n    head_step e1' \u03c31 e2 \u03c32 efs \u2192\n    \u2203 K'', K' = comp_ectx K K''.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma head_step_count e \u03c3:\n    Countable.class_of { esf: expr \u039b * state \u039b * list (expr \u039b) |\n                           head_step e \u03c3 (esf.1.1) (esf.1.2) (esf.2) }.\n  Proof. apply ectx_language_mixin. Defined.\n  Lemma head_step_sum1 e \u03c3:\n    (\u2203 e' \u03c3' efs, head_step e \u03c3 e' \u03c3' efs) \u2192\n    is_series (countable_sum (\u03bb t : Countable.Pack (head_step_count e \u03c3)\n                                                   { esf: expr \u039b * state \u039b * list (expr \u039b) |\n                                                     head_step e \u03c3 (esf.1.1) (esf.1.2) (esf.2) },\n                                    head_step_prob e \u03c3\n                                                   (fst (fst (sval t)))\n                                                   (snd (fst (sval t)))\n                                                   (snd (sval t)))) 1.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma head_step_nonneg e1 \u03c31 e2 \u03c32 efs:\n    (head_step_prob e1 \u03c31 e2 \u03c32 efs >= 0)%R.\n  Proof. apply ectx_language_mixin. Qed.\n  Lemma head_step_strict_gt e1 \u03c31 e2 \u03c32 efs:\n    head_step e1 \u03c31 e2 \u03c32 efs \u2194 (head_step_prob e1 \u03c31 e2 \u03c32 efs > 0)%R.\n  Proof. apply ectx_language_mixin. Qed.\n\n  Definition head_reducible (e : expr \u039b) (\u03c3 : state \u039b) :=\n    \u2203 e' \u03c3' efs, head_step e \u03c3 e' \u03c3' efs.\n  Definition head_irreducible (e : expr \u039b) (\u03c3 : state \u039b) :=\n    \u2200 e' \u03c3' efs, \u00achead_step e \u03c3 e' \u03c3' efs.\n  Definition head_stuck (e : expr \u039b) (\u03c3 : state \u039b) :=\n    to_val e = None \u2227 \u2200 K e', e = fill K e' \u2192 head_irreducible e' \u03c3.\n\n  (* All non-value redexes are at the root.  In other words, all sub-redexes are\n     values. *)\n  Definition sub_redexes_are_values (e : expr \u039b) :=\n    \u2200 K e', e = fill K e' \u2192 to_val e' = None \u2192 K = empty_ectx.\n\n  Inductive prim_step (e1 : expr \u039b) (\u03c31 : state \u039b)\n      (e2 : expr \u039b) (\u03c32 : state \u039b) (efs : list (expr \u039b)) : Prop :=\n    Ectx_step K e1' e2' :\n      e1 = fill K e1' \u2192 e2 = fill K e2' \u2192\n      head_step e1' \u03c31 e2' \u03c32 efs \u2192 prim_step e1 \u03c31 e2 \u03c32 efs.\n\n  Definition prim_step_prob (e1 : expr \u039b) (\u03c31 : state \u039b)\n             (e2 : expr \u039b) (\u03c32 : state \u039b) (efs : list (expr \u039b)) : R :=\n    (let s := \n         excluded_middle_informative\n           (\u2203 (K : ectx \u039b) (e1' e2' : expr \u039b), e1 = fill K e1' \u2227 e2 = fill K e2'\n                                           \u2227 head_step e1' \u03c31 e2' \u03c32 efs) in\n     match s with\n     | left Hhead =>\n       let (K, Hhead1) := constructive_indefinite_description _ Hhead in\n       let (e1', Hhead2) := constructive_indefinite_description _ Hhead1 in\n       let (e2', _) := constructive_indefinite_description _ Hhead2 in\n       head_step_prob e1' \u03c31 e2' \u03c32 efs\n     | right _ => 0%R\n     end).\n\n  Definition prim_step_pickle e \u03c3 (esf: {esf : expr \u039b * state \u039b * list (expr \u039b) |\n                                         prim_step e \u03c3 esf.1.1 esf.1.2 esf.2}):\n    nat.\n  Proof.\n    destruct esf as (esf&Hstep).\n    destruct (excluded_middle_informative\n                (\u2203 (K : ectx \u039b) (e1' e2' : expr \u039b),\n                    e = fill K e1' \u2227 esf.1.1 = fill K e2'\n                    \u2227 head_step e1' \u03c3 e2' esf.1.2 esf.2)) as [Hex|Hnex].\n    - apply constructive_indefinite_description in Hex as (K&Hex).\n      apply constructive_indefinite_description in Hex as (e1'&Hex).\n      apply constructive_indefinite_description in Hex as (e2'&Hex).\n      apply (@pickle (Countable.Pack (head_step_count e1' \u03c3)\n                                     { esf: expr \u039b * state \u039b * list (expr \u039b) |\n                                       head_step e1' \u03c3 e2' (esf.1.2) (esf.2)})).\n      exists (e2', esf.1.2, esf.2); rewrite //=; abstract (intuition).\n    - abstract (exfalso; eapply Hnex; inversion Hstep; do 3 eexists; split_and!; eauto).\n  Defined.\n\n  Definition prim_step_unpickle e \u03c3 (n: nat) :\n    option {esf : expr \u039b * state \u039b * list (expr \u039b) | prim_step e \u03c3 esf.1.1 esf.1.2 esf.2}.\n  Proof.\n    destruct (excluded_middle_informative\n                (\u2203 (K : ectx \u039b) (e1' e2' : expr \u039b) \u03c3' efs,\n                    e = fill K e1' \u2227 head_step e1' \u03c3 e2' \u03c3' efs)) as [Hex|Hnex].\n    - apply constructive_indefinite_description in Hex as (K&Hex).\n      apply constructive_indefinite_description in Hex as (e1'&Hex).\n      destruct (@unpickle (Countable.Pack (head_step_count e1' \u03c3)\n                                     { esf: expr \u039b * state \u039b * list (expr \u039b) |\n                                       head_step e1' \u03c3 (esf.1.1) (esf.1.2) (esf.2)}) n)\n               as [s|].\n      * destruct s as (esf&Hpf).\n        apply Some. exists (fill K (esf.1.1), esf.1.2, esf.2).\n        abstract (destruct Hex as (?&?&?&?); eexists; eauto; intuition).\n      * apply None. \n    - apply None.\n  Defined.\n\n  Lemma pickle_primK e \u03c3:\n    ssrfun.pcancel (prim_step_pickle e \u03c3) (prim_step_unpickle e \u03c3).\n  Proof.\n    rewrite /prim_step_pickle/prim_step_unpickle//=.\n    intros (esf&Hstep) => //=.\n    destruct excluded_middle_informative as [Hex|Hnex]; last first.\n    { \n      exfalso. apply Hnex. inversion Hstep.\n      do 5 eexists. split_and!; eauto.\n    }\n    destruct constructive_indefinite_description as (K&?).\n    destruct constructive_indefinite_description as (e1'&Hex'').\n    destruct excluded_middle_informative as [Hex'|Hnex']; last first.\n    { \n      exfalso. eapply Hnex'.\n      destruct Hex'' as (?&?&?&?&?).\n      inversion Hstep. subst.\n      do 3 eexists; eauto.\n    }\n    destruct Hex'' as (e2'&\u03c3'&efs&?&?).\n    destruct constructive_indefinite_description as (K'&?).\n    destruct constructive_indefinite_description as (e1''&?).\n    destruct constructive_indefinite_description as (e2''&Hex''').\n    assert (K' = K).\n    { intuition. eapply step_by_val_eq.\n      * transitivity e; eauto.\n      * eauto.\n      * eauto.\n    }\n    subst.\n    assert (e1' = e1'').\n    { intuition. eapply fill_inj. eauto. }\n    subst.\n    rewrite pickleK => //=.\n    f_equal. apply sval_inj_pi => //=.\n    intuition.\n    destruct esf as [[? ?] ?].\n    rewrite //=. subst.\n    f_equal. f_equal. eauto.\n  Qed.\n\n  Lemma Ectx_step' K e1 \u03c31 e2 \u03c32 efs :\n    head_step e1 \u03c31 e2 \u03c32 efs \u2192 prim_step (fill K e1) \u03c31 (fill K e2) \u03c32 efs.\n  Proof. econstructor; eauto. Qed.\n\n  Definition ectx_lang_mixin : LanguageMixin of_val to_val prim_step.\n  Proof.\n    split.\n    - apply ectx_language_mixin.\n    - apply ectx_language_mixin.\n    - intros ????? [??? -> -> ?%val_head_stuck].\n      apply eq_None_not_Some. by intros ?%fill_val%eq_None_not_Some.\n  Qed.\n\n  Lemma map_legacy {A B: Type} (f: A \u2192 B) l:\n    seq.map f l = List.map f l.\n  Proof.  \n    induction l => //=.\n  Qed.\n\n  Lemma ectx_count_mixin:\n  \u2200 (e : expr \u039b) (\u03c3 : state \u039b),\n    Countable.class_of {esf : expr \u039b * state \u039b * list (expr \u039b) | prim_step e \u03c3 esf.1.1 esf.1.2 esf.2}.\n  Proof.\n    intros e \u03c3.\n    split.\n    - econstructor.\n      * exists (\u03bb x y, ClassicalEpsilon.excluded_middle_informative (x = y)).\n        intros x y. destruct excluded_middle_informative; eauto; econstructor => //=.\n      * eapply PcanChoiceMixin; eapply pickle_primK.\n    - eapply PcanCountMixin; eapply pickle_primK.\n  Qed.\n\n  Definition ectx_prob_lang_mixin : ProbLanguageMixin of_val to_val prim_step prim_step_prob.\n  Proof.\n    unshelve (econstructor).\n    - intros. apply ectx_count_mixin.\n    - apply ectx_language_mixin.\n    - apply ectx_language_mixin.\n    - intros ????? [??? -> -> ?%val_head_stuck].\n      apply eq_None_not_Some. by intros ?%fill_val%eq_None_not_Some.\n    - intros e1 \u03c31 (e2&\u03c32&efs&Hprim).\n      inversion Hprim as [K e1' e2' ? ? ?]; subst.\n      feed pose proof (head_step_sum1 e1' \u03c31) as His.\n      { do 3 eexists; eauto. }\n      rewrite -(is_series_unique _ _ His).\n      unshelve (edestruct (@rearrange.countable_series_rearrange_covering\n                             (Countable.Pack (ectx_count_mixin (fill K e1') \u03c31)\n                                             {esf : expr \u039b * state \u039b * list (expr \u039b) |\n                                              prim_step (fill K e1') \u03c31 esf.1.1 esf.1.2 esf.2})\n                             (Countable.Pack (head_step_count e1' \u03c31)\n                                             {esf : expr \u039b * state \u039b * list (expr \u039b) |\n                                              head_step e1' \u03c31 esf.1.1 esf.1.2 esf.2})\n                          ) as (His1&His2));\n       last (eapply is_seriesC_ext; last eapply His2).\n      * intros (esf&Hstep).\n        assert (Hfill: \u2203 e2'', fill K e2'' = esf.1.1 \u2227\n                        head_step e1' \u03c31 e2'' esf.1.2 esf.2).\n        { \n        inversion Hstep as [K' e1'' e2''].\n          assert (K = K').\n          { abstract (intuition; eapply step_by_val_eq; eauto). }\n          assert (e1' = e1'').\n          { abstract (subst; eapply fill_inj; eauto). }\n          exists e2''; \n            abstract (rewrite //=; subst; eauto).\n        }\n        apply constructive_indefinite_description in Hfill as (e2''&?&?).\n        exists (e2'', esf.1.2, esf.2); auto.\n      * exact 1.\n      * intros (esf1&Hstep1) (esf2&Hstep2) Hnz => //=.\n        destruct Hstep1.\n        destruct esf1 as [[? ?] ?].\n        destruct esf2 as [[? ?] ?].\n        rewrite //=.\n        destruct constructive_indefinite_description as (e2''&?&?).\n        destruct constructive_indefinite_description as (e2'''&?&?).\n        inversion 1. subst. eapply sval_inj_pi.\n        rewrite //=.\n      * intros (esf&Hstep1) Hnz.\n        unshelve (eexists).\n        { exists (fill K (esf.1.1), esf.1.2, esf.2).\n          { econstructor => //=. }\n        }\n        rewrite //=.\n        destruct esf as [[? ?] ?] => //=.\n        destruct constructive_indefinite_description as (e2''&?&?).\n        apply sval_inj_pi => //=. \n        subst; f_equal.\n        f_equal.\n        eapply fill_inj; eauto.\n      * eapply is_seriesC_ext; try eassumption.\n        intros n => //=. rewrite Rabs_right //=. apply head_step_nonneg.\n      * intros (esf&Hstep) => //=. \n        destruct constructive_indefinite_description as (e2''&?&?).\n        rewrite /prim_step_prob.\n        destruct excluded_middle_informative as [?|Hnex].\n        ** destruct (constructive_indefinite_description) as (K'&?).\n           destruct (constructive_indefinite_description) as (e1''&?).\n           destruct (constructive_indefinite_description) as (e2'''&Hfill1'&Hfill2'&Hstep').\n\n           assert (K = K') as HeqK.\n           { eapply (step_by_val_eq K K' e1' e1'');\n               eauto; congruence. }\n           assert (e1' = e1'') as Heqe.\n           { subst. eapply fill_inj; eauto.  }\n           subst.\n           rewrite //=.\n           f_equal.\n           eapply fill_inj; eauto. \n           transitivity (esf.1.1); eauto.\n        ** exfalso; eapply Hnex. do 3 eexists; intuition; eauto.\n    - intros. rewrite /prim_step_prob.\n      destruct (excluded_middle_informative); last by nra.\n      repeat destruct (constructive_indefinite_description).\n      apply ectx_language_mixin.\n    - intros ?????. split.\n      * intros Hstep. rewrite /prim_step_prob.\n        destruct (excluded_middle_informative) as [|Hn].\n        ** repeat destruct (constructive_indefinite_description).\n           apply ectx_language_mixin.\n           firstorder.\n        ** exfalso. edestruct Hn.\n           inversion Hstep. do 3 eexists; split_and!; eauto.\n      * rewrite /prim_step_prob. intros Hgt.\n        destruct (excluded_middle_informative) as [|Hn].\n        ** do 2 destruct (constructive_indefinite_description).\n           destruct constructive_indefinite_description as (?&?&?&?).\n           econstructor; eauto.\n        ** nra.\n  Qed.\n  Canonical Structure ectx_prob_lang : probLanguage := ProbLanguage ectx_prob_lang_mixin.\n  Canonical Structure ectx_lang := LanguageOfProb ectx_prob_lang. \n\n  Definition head_atomic (a : atomicity) (e : expr \u039b) : Prop :=\n    \u2200 \u03c3 e' \u03c3' efs,\n      head_step e \u03c3 e' \u03c3' efs \u2192\n      if a is WeaklyAtomic then irreducible e' \u03c3' else is_Some (to_val e').\n\n  (* Some lemmas about this language *)\n  Lemma fill_not_val K e : to_val e = None \u2192 to_val (fill K e) = None.\n  Proof. rewrite !eq_None_not_Some. eauto using fill_val. Qed.\n\n  Lemma head_prim_step e1 \u03c31 e2 \u03c32 efs :\n    head_step e1 \u03c31 e2 \u03c32 efs \u2192 prim_step e1 \u03c31 e2 \u03c32 efs.\n  Proof. apply Ectx_step with empty_ectx; by rewrite ?fill_empty. Qed.\n\n  Lemma not_head_reducible e \u03c3 : \u00achead_reducible e \u03c3 \u2194 head_irreducible e \u03c3.\n  Proof. unfold head_reducible, head_irreducible. naive_solver. Qed.\n\n  Program Lemma head_prim_reducible e \u03c3 : head_reducible e \u03c3 \u2192 reducible e \u03c3.\n  Proof. intros (e'&\u03c3'&efs&?). eexists e', \u03c3', efs. by apply head_prim_step. Qed.\n\n  Lemma head_prim_irreducible e \u03c3 : irreducible e \u03c3 \u2192 head_irreducible e \u03c3.\n  Proof.\n    rewrite -not_reducible -not_head_reducible. eauto using head_prim_reducible.\n  Qed.\n\n  Lemma prim_head_reducible e \u03c3 :\n    reducible e \u03c3 \u2192 sub_redexes_are_values e \u2192 head_reducible e \u03c3.\n  Proof.\n    intros (e'&\u03c3'&efs&[K e1' e2' -> -> Hstep]) ?.\n    assert (K = empty_ectx) as -> by eauto 10 using val_head_stuck.\n    rewrite fill_empty /head_reducible; eauto.\n  Qed.\n  Lemma prim_head_irreducible e \u03c3 :\n    head_irreducible e \u03c3 \u2192 sub_redexes_are_values e \u2192 irreducible e \u03c3.\n  Proof.\n    rewrite -not_reducible -not_head_reducible. eauto using prim_head_reducible.\n  Qed.\n\n  Lemma head_stuck_stuck e \u03c3 :\n    head_stuck e \u03c3 \u2192 sub_redexes_are_values e \u2192 stuck e \u03c3.\n  Proof.\n    move=>[] ? Hirr ?. split; first done.\n    apply prim_head_irreducible; last done.\n    apply (Hirr empty_ectx). by rewrite fill_empty.\n  Qed.\n\n  Lemma ectx_language_atomic a e :\n    head_atomic a e \u2192 sub_redexes_are_values e \u2192 Atomic a e.\n  Proof.\n    intros Hatomic_step Hatomic_fill \u03c3 e' \u03c3' efs [K e1' e2' -> -> Hstep].\n    assert (K = empty_ectx) as -> by eauto 10 using val_head_stuck.\n    rewrite fill_empty. eapply Hatomic_step. by rewrite fill_empty.\n  Qed.\n\n  Lemma head_reducible_prim_step e1 \u03c31 e2 \u03c32 efs :\n    head_reducible e1 \u03c31 \u2192\n    prim_step e1 \u03c31 e2 \u03c32 efs \u2192\n    head_step e1 \u03c31 e2 \u03c32 efs.\n  Proof.\n    intros (e2''&\u03c32''&efs''&?) [K e1' e2' -> -> Hstep].\n    erewrite (step_by_val_eq K empty_ectx e1' (fill K e1'));\n      eauto using fill_empty, fill_not_val, val_stuck.\n    by rewrite !fill_empty.\n  Qed.\n\n  Lemma head_reducible_prim_step_prob e1 \u03c31 e2 \u03c32 efs :\n    head_reducible e1 \u03c31 \u2192\n    sub_redexes_are_values e1 \u2192\n    prim_step_prob e1 \u03c31 e2 \u03c32 efs = head_step_prob e1 \u03c31 e2 \u03c32 efs.\n  Proof.\n    intros Hred Hsub. rewrite /prim_step_prob.\n    destruct ClassicalEpsilon.excluded_middle_informative as [?|Hnot]; last first.\n    {\n      edestruct head_step_nonneg; eauto.\n      exfalso. apply Hnot.\n      exists empty_ectx. do 2 eexists; rewrite ?fill_empty; split_and!; eauto.\n      apply head_step_strict_gt; auto.\n    }\n\n    destruct (ClassicalEpsilon.constructive_indefinite_description) as (K&?).\n    destruct (ClassicalEpsilon.constructive_indefinite_description) as (e1'&?).\n    destruct (ClassicalEpsilon.constructive_indefinite_description) as (e2'&?&?&?).\n    subst. rewrite /sub_redexes_are_values in Hsub.\n    assert (K = empty_ectx).\n    { eapply Hsub; eauto. eapply val_head_stuck; eauto. }\n    subst; rewrite ?fill_empty => //=.\n  Qed.\n\n  (* Every evaluation context is a context. *)\n  Global Instance ectx_lang_ctx K : LanguageCtx (fill K).\n  Proof.\n    split; simpl.\n    - eauto using fill_not_val.\n    - intros ????? [K' e1' e2' Heq1 Heq2 Hstep].\n      by exists (comp_ectx K K') e1' e2'; rewrite ?Heq1 ?Heq2 ?fill_comp.\n    - intros e1 \u03c31 e2 \u03c32 ? Hnval [K'' e1'' e2'' Heq1 -> Hstep].\n      destruct (step_by_val K K'' e1 e1'' \u03c31 e2'' \u03c32 efs) as [K' ->]; eauto.\n      rewrite -fill_comp in Heq1; apply (inj (fill _)) in Heq1.\n      exists (fill K' e2''); rewrite -fill_comp; split; auto.\n      econstructor; eauto.\n    - eauto using fill_inj. \n  Qed.\n\n  Global Instance ectx_lang_ctx_prob K : ProbLanguageCtx (fill K).\n  Proof.\n    split.\n    - apply: _.\n    - intros. rewrite //=/prim_step_prob//=.\n      destruct (excluded_middle_informative) as [|Hn] => //=;\n      destruct (excluded_middle_informative) as [|HnK] => //=.\n      ** destruct (constructive_indefinite_description) as (K'&?).\n         destruct (constructive_indefinite_description) as (e1''&?).\n         destruct (constructive_indefinite_description) as (e2''&Hfill1'&Hfill2'&Hstep).\n\n         destruct (constructive_indefinite_description) as (K''&?).\n         destruct (constructive_indefinite_description) as (e1'''&?).\n         destruct (constructive_indefinite_description) as (e2'''&Hfill1''&Hfill2''&Hstep').\n\n         rewrite Hfill1' fill_comp in Hfill1''.\n         rewrite Hfill2' fill_comp in Hfill2''.\n         assert (comp_ectx K K' = K'').\n         { eapply step_by_val_eq.\n           * apply Hfill1''.\n           * eauto.\n           * eauto. \n         }\n         subst.\n         f_equal; auto.\n         *** eapply fill_inj; eauto.\n         *** eapply fill_inj; eauto.\n      ** destruct (constructive_indefinite_description) as (K'&?).\n         destruct (constructive_indefinite_description) as (e1''&?).\n         destruct (constructive_indefinite_description) as (e2''&Hfill1'&Hfill2'&Hstep).\n\n         exfalso; eapply HnK.\n         exists (comp_ectx K K'), e1'', e2''; split_and!; subst.\n         *** apply fill_comp. \n         *** apply fill_comp. \n         *** eauto.\n      ** destruct (constructive_indefinite_description) as (K'&?).\n         destruct (constructive_indefinite_description) as (e1''&?).\n         destruct (constructive_indefinite_description) as (e2''&Hfill1'&Hfill2'&Hstep).\n\n         exfalso; eapply Hn.\n         edestruct step_by_val as (K''&Heq); try apply Hstep; eauto.\n         subst.\n         rewrite -?fill_comp in Hfill1' Hfill2'.\n         apply fill_inj in Hfill1'.\n         apply fill_inj in Hfill2'.\n         exists K'', e1'', e2''; repeat split; auto.\n  Qed.\n\n  Lemma det_head_step_pure_exec (P : Prop) e1 e2 :\n    (\u2200 \u03c3, P \u2192 head_reducible e1 \u03c3) \u2192\n    (\u2200 \u03c31 e2' \u03c32 efs,\n      P \u2192 head_step e1 \u03c31 e2' \u03c32 efs \u2192 \u03c31 = \u03c32 \u2227 e2=e2' \u2227 efs = []) \u2192\n    PureExec P e1 e2.\n  Proof.\n    intros Hp1 Hp2. split.\n    - intros \u03c3 ?. destruct (Hp1 \u03c3) as (e2' & \u03c32 & efs & ?); first done.\n      eexists e2', \u03c32, efs. by apply head_prim_step.\n    - intros \u03c31 e2' \u03c32 efs ? ?%head_reducible_prim_step; eauto.\n  Qed.\n\n  Global Instance pure_exec_fill K e1 e2 \u03c6 :\n    PureExec \u03c6 e1 e2 \u2192\n    PureExec \u03c6 (fill K e1) (fill K e2).\n  Proof. apply: pure_exec_ctx. Qed.\n\nEnd ectx_language.\n\nArguments ectx_prob_lang : clear implicits.\nArguments ectx_lang : clear implicits.\nCoercion ectx_prob_lang : ectxLanguage >-> probLanguage.\nCoercion ectx_lang : ectxLanguage >-> language.\n\n(* This definition makes sure that the fields of the [language] record do not\nrefer to the projections of the [ectxLanguage] record but to the actual fields\nof the [ectxLanguage] record. This is crucial for canonical structure search to\nwork.\n\nNote that this trick no longer works when we switch to canonical projections\nbecause then the pattern match [let '...] will be desugared into projections. *)\nDefinition ProbLanguageOfEctx (\u039b : ectxLanguage) : probLanguage :=\n  let '@EctxLanguage E V C St of_val to_val empty comp fill head head_prob mix := \u039b in\n  @ProbLanguage E V St of_val to_val _ _\n    (@ectx_prob_lang_mixin (@EctxLanguage E V C St of_val to_val empty comp fill head head_prob mix)).\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/program_logic/ectx_language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16866458446051438}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import Integers Values.\nFrom bpf.comm Require Import ListAsArray Regs BinrBPF State LemmaNat.\nFrom bpf.model Require Import Semantics.\nFrom bpf.isolation Require Import AlignChunk CommonISOLib VerifierOpcode.\nFrom bpf.verifier.comm Require Import state.\nFrom Coq Require Import ZArith Lia List.\nImport ListNotations.\n\n\nLtac destruct_if_zeqb Hname :=\n  match goal with\n  | |- context [(if ?X then _ else _) = Some _] =>\n    destruct X eqn: Hname;\n    [ eexists; rewrite Z.eqb_eq in Hname; rewrite Hname;\n  reflexivity |\n      rewrite Z.eqb_neq in Hname]\n  end.\n\n\nOpen Scope nat_scope.\n(**r CertrBPF needs the following two properties guaranteed by an assumed rbpf verifier, we will implement a verified verifier later~\n\n\\begin{enumerate}\n    \\item dst \\& src registers are in [0, 10].\n    \\item all jump operations are always within in bound.\n    tbc...\n    \\item when ins.opcode = div, ins.src != 0\n    \\item when ins.opcode = shift (lsh/rsh/arsh), $0 \\leq ins.src \\leq 32/64$\n    \\item etc... (more ambitious: {\\color{red} check\\_mem = true?}  ...)  \n\\end{enumerate}\n\n *)\n\nDefinition is_well_dst (i: int64) : bool := Int.cmpu Cle (Int.repr (get_dst i)) (Int.repr 10).\n\nDefinition is_well_src (i: int64) : bool := Int.cmpu Cle (Int.repr (get_src i)) (Int.repr 10).\n\nDefinition is_well_jump (pc len: nat) (ofs: int) : bool :=\n  Int.cmpu Cle (Int.add (Int.repr (Z.of_nat pc)) ofs) (Int.sub (Int.repr (Z.of_nat len)) (Int.repr 2%Z)).\n(*\nDefinition is_well_jump (pc len: nat) (ofs: int) : bool :=\n  Int.cmpu Clt (Int.add (Int.repr (Z.of_nat pc)) ofs) (Int.repr (Z.of_nat len)). *)\n\nDefinition is_not_div_by_zero (i: int64) : bool :=\n  Int.cmp Cne (BinrBPF.get_immediate i) Int.zero.\n\nDefinition is_not_div_by_zero64 (i: int64) : bool :=\n  Int64.cmp Cne (Int64.repr (Int.signed (BinrBPF.get_immediate i))) Int64.zero.\n\nDefinition is_shift_range (i: int64) (upper: int): bool :=\n  Int.cmpu Clt (BinrBPF.get_immediate i) upper.\n\nDefinition is_shift_range64 (i: int64) (upper: int): bool :=\n  Int.ltu (Int.repr (Int64.unsigned (Int64.repr (Int.signed (BinrBPF.get_immediate i))))) upper.\n\nDefinition bpf_verifier_aux2 (pc len op: nat) (ins: int64) : bool :=\n  match nat_to_opcode op with\n  | ALU64  (**r 0xX7 / 0xXf *) =>\n    match nat_to_opcode_alu op with\n    | ALU_DIV => (**r DIV_IMM *) is_well_dst ins && is_not_div_by_zero64 ins\n    | ALU_SHIFT => (**r SHIFT_IMM *) is_well_dst ins && is_shift_range64 ins (Int.repr 64%Z)\n    | ALU_IMM_Normal => (**r ALU_IMM *) is_well_dst ins\n    | ALU_REG_Normal => (**r ALU_REG *) is_well_dst ins && is_well_src ins\n    | ALU_ILLEGAL => false\n    end\n  | ALU32  (**r 0xX4 / 0xXc *) =>\n    match nat_to_opcode_alu op with\n    | ALU_DIV => (**r DIV_IMM *) is_well_dst ins && is_not_div_by_zero ins\n    | ALU_SHIFT => (**r SHIFT_IMM *) is_well_dst ins && is_shift_range ins (Int.repr 32%Z)\n    | ALU_IMM_Normal => (**r ALU_IMM *) is_well_dst ins\n    | ALU_REG_Normal => (**r ALU_REG *) is_well_dst ins && is_well_src ins\n    | ALU_ILLEGAL => false\n    end\n  | Branch (**r 0xX5 / 0xXd *) =>\n    match nat_to_opcode_branch op with\n    | JMP_IMM =>\n      let ofs := get_offset ins in\n        is_well_dst ins && is_well_jump pc len ofs\n    | JMP_REG =>\n      let ofs := get_offset ins in\n        is_well_dst ins && is_well_src ins && is_well_jump pc len ofs\n    | JMP_SP => Int.cmpu Ceq (Int.repr (get_dst ins)) (Int.repr 0)\n    | JMP_ILLEGAL => false\n    end\n  | LD_IMM (**r 0xX8 *) =>\n    match nat_to_opcode_load_imm op with\n    | LD_IMM_Normal  => is_well_dst ins\n    | LD_IMM_ILLEGAL => false\n    end\n  | LD_REG (**r 0xX1/0xX9 *) =>\n    match nat_to_opcode_load_reg op with\n    | LD_REG_Normal  => is_well_dst ins && is_well_src ins\n    | LD_REG_ILLEGAL => false\n    end\n  | ST_IMM (**r 0xX2/0xXa *) =>\n    match nat_to_opcode_store_imm op with\n    | ST_IMM_Normal  => is_well_dst ins\n    | ST_IMM_ILLEGAL => false\n    end\n  | ST_REG (**r 0xX3/0xXb *)  =>\n    match nat_to_opcode_store_reg op with\n    | ST_REG_Normal  => is_well_dst ins && is_well_src ins\n    | ST_REG_ILLEGAL => false\n    end\n  | ILLEGAL => false\n  end.\n\nFixpoint bpf_verifier_aux (pc len: nat) (st: state.state): bool :=\n    match pc with\n    | O => true\n    | S n =>\n      let i := List64AsArray.index (ins st) (Int.repr (Z.of_nat n)) in\n      let op := get_opcode i in\n        if (bpf_verifier_aux2 n len op i) then\n            bpf_verifier_aux n len st\n          else\n            false\n    end.\n\nDefinition bpf_verifier (st: state.state): bool :=\n  let len := ins_len st in\n  (**r (0, Int.max_unsigned/8): at least one instruction, and at most Int.max_unsigned/8 because of memory region *)\n    if negb (Int.ltu (Int.repr (Z.of_nat len)) Int.one) then\n      if negb\n       (Int.ltu (Int.divu (Int.repr Int.max_unsigned) (Int.repr 8))\n          (Int.repr (Z.of_nat len))) then\n        if bpf_verifier_aux len len st then\n          let i := List64AsArray.index (ins st) (Int.repr (Z.of_nat  (len - 1))) in\n            Int64.eq i (Int64.repr 0x95)\n        else\n          false\n      else\n        false\n    else\n      false.\n\nLemma sub_lt:\n  forall a b,\n    b < a ->\n    a - 1 - b < a.\nProof.\n  intros.\n  assert (1+b <= a) by lia.\n  rewrite <- Nat.sub_add_distr.\n  apply Nat.sub_lt.\n  assumption.\n  lia.\nQed.\n\nLemma bpf_verifier_aux_implies:\n  forall st pc op ins k\n    (Hst: bpf_verifier_aux k (ins_len st) st = true)\n    (Hlen: List.length (state.ins st) = ins_len st)\n    (Hpc: pc < k)\n    (Hop: op = get_opcode ins)\n    (Hins: ins = List64AsArray.index (state.ins st) (Int.repr (Z.of_nat pc))),\n      bpf_verifier_aux2 pc (ins_len st) op ins = true.\nProof.\n  unfold List64AsArray.index.\n  intros.\n\n  induction k.\n  - lia.\n  - assert (Hpc_eq: pc = k \\/ pc < k) by lia.\n    destruct Hpc_eq as [Hpc_eq | Hpc_lt].\n    + simpl in Hst.\n      unfold List64AsArray.index in Hst.\n      rewrite Hpc_eq in *.\n      rewrite <- Hins in *.\n      match goal with\n      | H: (if ?X then _ else _) = _ |- _ =>\n        destruct X eqn: Haux2;[ | inversion H]\n      end.\n      rewrite Hop.\n      assumption.\n    + apply IHk; auto.\n      simpl in Hst.\n      match goal with\n      | H: (if ?X then _ else _) = _ |- _ =>\n        destruct X eqn: Haux2;[ | inversion H]\n      end.\n      assumption.\nQed.\n\n(*\nLemma is_well_jump_ind:\n  forall k len ofs,\n    is_well_jump k len ofs = true ->\n      is_well_jump 0 len ofs = true.\nProof.\n  unfold is_well_jump; intros.\n  destruct k.\n  - assumption.\n  - unfold Int.cmpu in *.\n    rewrite Clt_Zlt_iff in *.\n    \nQed. *)\n\nLemma bpf_verifier_aux_implies':\n  forall st pc op ins k\n    (Hst: bpf_verifier_aux k (ins_len st) st = true)\n    (Hlen: List.length (state.ins st) = ins_len st)\n    (Hpc: pc < k)\n    (Hop: op = get_opcode ins)\n    (Hins: ins = List64AsArray.index (state.ins st) (Int.repr (Z.of_nat (k-1-pc)))),\n      bpf_verifier_aux2 (k-1-pc) (ins_len st) op ins = true.\nProof.\n  intros.\n  assert (H: k-1-pc < k). {\n    eapply sub_lt; eauto.\n  }\n  eapply bpf_verifier_aux_implies; eauto.\nQed.\n\n\nLemma bpf_verifier_aux_implies_bpf_verifier_aux:\n  forall st pc k\n    (Hst: bpf_verifier_aux k (ins_len st) st = true)\n    (Hlen: List.length (state.ins st) = ins_len st)\n    (Hpc: pc < k),\n      bpf_verifier_aux pc (ins_len st) st = true.\nProof.\n  intros.\n  induction k.\n  - lia.\n  - assert (Hpc_eq: pc = k \\/ pc < k) by lia.\n    destruct Hpc_eq as [Hpc_eq | Hpc_lt].\n    + simpl in Hst.\n      unfold List64AsArray.index in Hst.\n      rewrite Hpc_eq in *.\n      match goal with\n      | H: (if ?X then _ else _) = _ |- _ =>\n        destruct X eqn: Haux2;[ | inversion H]\n      end.\n      assumption.\n    + apply IHk; auto.\n      simpl in Hst.\n      match goal with\n      | H: (if ?X then _ else _) = _ |- _ =>\n        destruct X eqn: Haux2;[ | inversion H]\n      end.\n      assumption.\nQed.\n\n\nLemma bpf_verifier_aux_implies_bpf_verifier_aux':\n  forall st pc k\n    (Hst: bpf_verifier_aux k (ins_len st) st = true)\n    (Hlen: List.length (state.ins st) = ins_len st)\n    (Hpc: pc < k),\n      bpf_verifier_aux (k-1-pc) (ins_len st) st = true.\nProof.\n  intros.\n  assert (H: k-1-pc < k). {\n    eapply sub_lt; eauto.\n  }\n  eapply bpf_verifier_aux_implies_bpf_verifier_aux; eauto.\nQed.\n\nLemma bpf_verifier_implies:\n  forall st pc op ins\n    (Hst: bpf_verifier st = true)\n    (Hlen: List.length (state.ins st) = ins_len st)\n    (Hpc: pc < ins_len st)\n    (Hop: op = get_opcode ins)\n    (Hins: ins = List64AsArray.index (state.ins st) (Int.repr (Z.of_nat pc))),\n      bpf_verifier_aux2 pc (ins_len st) op ins = true.\nProof.\n  unfold bpf_verifier, List64AsArray.index.\n  intros.\n  match goal with\n  | H: (if ?X then _ else _) = _ |- _ =>\n    destruct X eqn: Hlen_low;[ | inversion H]\n  end.\n  match goal with\n  | H: (if ?X then _ else _) = _ |- _ =>\n    destruct X eqn: Hlen_high;[ | inversion H]\n  end.\n  match goal with\n  | H: (if ?X then _ else _) = _ |- _ =>\n    destruct X eqn: Haux;[ | inversion H]\n  end.\n  eapply bpf_verifier_aux_implies; eauto.\nQed.\n\n(*\nLemma bpf_verifier_aux_rev_iff:\n  forall st k,\n    bpf_verifier_aux k (ins_len st) st = bpf_verifier_aux_rev k (ins_len st) st.\nProof.\n  intros.\n  induction k.\n  - simpl. reflexivity.\n  - simpl.\n\n    destruct bpf_verifier_aux eqn: Hst; rewrite <-IHk.\n    + symmetry in IHk.\n      \n    + destruct bpf_verifier_aux2; destruct bpf_verifier_aux2; reflexivity.\n      \n\n    rewrite Nat.sub_0_r.\n    rewrite Nat.sub_diag.\n  Search List.rev.\nQed. *)\n\n\nClose Scope nat_scope.\n\nLemma verifier_inv_dst_zero:\n  forall ins,\n    Int.cmpu Ceq (Int.repr (get_dst ins))\n              (Int.repr 0) = true ->\n      BinrBPF.int64_to_dst_reg' ins = Some R0.\nProof.\n  unfold BinrBPF.int64_to_dst_reg', z_to_reg; intros.\n  remember (get_dst ins) as i.\n  unfold get_dst in Heqi.\n  rewrite <- Int64.and_shru in Heqi.\n  change (Int64.shru (Int64.repr 4095) (Int64.repr 8)) with (Int64.repr 15) in Heqi.\n  rewrite Int64.and_commut in Heqi.\n  assert (Hi_le: (0 <= Int64.unsigned\n         (Int64.and (Int64.repr 15)\n            (Int64.shru ins (Int64.repr 8))) <= (Int64.unsigned (Int64.repr 15)))%Z). {\n    split;[ | apply Int64.and_le].\n    apply Int64_unsigned_ge_0.\n  }\n  change (Int64.unsigned (Int64.repr 15)) with 15%Z in Hi_le.\n  assert (Hi: (0 <= i <= 15)%Z) by lia.\n  clear Heqi Hi_le.\n  unfold Int.cmpu in H.\nLtac destruct_if_zeq Hname H :=\n  match goal with\n  | |- context [(if ?X then _ else _) = Some _] =>\n    destruct X eqn: Hname;\n    [ rewrite Z.eqb_eq in Hname; rewrite Hname in H; inversion H |\n      rewrite Z.eqb_neq in Hname]\n  end.\n  destruct_if_zeqb Heq0.\n  destruct_if_zeq Heq1 H.\n  destruct_if_zeq Heq2 H.\n  destruct_if_zeq Heq3 H.\n  destruct_if_zeq Heq4 H.\n  destruct_if_zeq Heq5 H.\n  destruct_if_zeq Heq6 H.\n  destruct_if_zeq Heq7 H.\n  destruct_if_zeq Heq8 H.\n  destruct_if_zeq Heq9 H.\n  destruct_if_zeq Heq10 H.\n  destruct (i =? 11)%Z eqn: H11; \n  [ rewrite Z.eqb_eq in H11; rewrite H11 in H; inversion H |\n      rewrite Z.eqb_neq in H11].\n  destruct (i =? 12)%Z eqn: H12; \n  [ rewrite Z.eqb_eq in H12; rewrite H12 in H; inversion H |\n      rewrite Z.eqb_neq in H12].\n  destruct (i =? 13)%Z eqn: H13; \n  [ rewrite Z.eqb_eq in H13; rewrite H13 in H; inversion H |\n      rewrite Z.eqb_neq in H13].\n  destruct (i =? 14)%Z eqn: H14; \n  [ rewrite Z.eqb_eq in H14; rewrite H14 in H; inversion H |\n      rewrite Z.eqb_neq in H14].\n  destruct (i =? 15)%Z eqn: H15; \n  [ rewrite Z.eqb_eq in H15; rewrite H15 in H; inversion H |\n      rewrite Z.eqb_neq in H15].\n  lia.\nQed.\n\n\nLemma verifier_inv_is_well_dst:\n  forall ins,\n    is_well_dst ins = true ->\n    exists r,\n      BinrBPF.int64_to_dst_reg' ins = Some r.\nProof.\n  unfold is_well_dst, BinrBPF.int64_to_dst_reg', z_to_reg; intros.\n  remember (get_dst ins) as i.\n  unfold get_dst in Heqi.\n  rewrite <- Int64.and_shru in Heqi.\n  change (Int64.shru (Int64.repr 4095) (Int64.repr 8)) with (Int64.repr 15) in Heqi.\n  rewrite Int64.and_commut in Heqi.\n  assert (Hi_le: (0 <= Int64.unsigned\n         (Int64.and (Int64.repr 15)\n            (Int64.shru ins (Int64.repr 8))) <= (Int64.unsigned (Int64.repr 15)))%Z). {\n    split;[ | apply Int64.and_le].\n    apply Int64_unsigned_ge_0.\n  }\n  change (Int64.unsigned (Int64.repr 15)) with 15%Z in Hi_le.\n  assert (Hi: (0 <= i <= 15)%Z) by lia.\n  clear Heqi Hi_le.\n  unfold Int.cmpu in H.\n  rewrite Cle_Zle_iff in H.\n  change (Int.unsigned (Int.repr 10)) with 10%Z in H.\n  rewrite Int.unsigned_repr in H; [| change Int.max_unsigned with 4294967295%Z; lia].\n  destruct_if_zeqb Heq0.\n  destruct_if_zeqb Heq1.\n  destruct_if_zeqb Heq2.\n  destruct_if_zeqb Heq3.\n  destruct_if_zeqb Heq4.\n  destruct_if_zeqb Heq5.\n  destruct_if_zeqb Heq6.\n  destruct_if_zeqb Heq7.\n  destruct_if_zeqb Heq8.\n  destruct_if_zeqb Heq9.\n  destruct_if_zeqb Heq10.\n  lia.\nQed.\n\n\nLemma verifier_inv_is_well_src:\n  forall ins,\n    is_well_src ins = true ->\n    exists r,\n      BinrBPF.int64_to_src_reg' ins = Some r.\nProof.\n  unfold is_well_src, BinrBPF.int64_to_src_reg', z_to_reg; intros.\n  remember (get_src ins) as i.\n  unfold get_src in Heqi.\n  rewrite <- Int64.and_shru in Heqi.\n  change (Int64.shru (Int64.repr 65535) (Int64.repr 12)) with (Int64.repr 15) in Heqi.\n  rewrite Int64.and_commut in Heqi.\n  assert (Hi_le: (0 <= Int64.unsigned\n         (Int64.and (Int64.repr 15)\n            (Int64.shru ins (Int64.repr 12))) <= (Int64.unsigned (Int64.repr 15)))%Z). {\n    split;[ | apply Int64.and_le].\n    apply Int64_unsigned_ge_0.\n  }\n  change (Int64.unsigned (Int64.repr 15)) with 15%Z in Hi_le.\n  assert (Hi: (0 <= i <= 15)%Z) by lia.\n  clear Heqi Hi_le.\n  unfold Int.cmpu in H.\n  rewrite Cle_Zle_iff in H.\n  change (Int.unsigned (Int.repr 10)) with 10%Z in H.\n  rewrite Int.unsigned_repr in H; [| change Int.max_unsigned with 4294967295%Z; lia].\n  destruct_if_zeqb Heq0.\n  destruct_if_zeqb Heq1.\n  destruct_if_zeqb Heq2.\n  destruct_if_zeqb Heq3.\n  destruct_if_zeqb Heq4.\n  destruct_if_zeqb Heq5.\n  destruct_if_zeqb Heq6.\n  destruct_if_zeqb Heq7.\n  destruct_if_zeqb Heq8.\n  destruct_if_zeqb Heq9.\n  destruct_if_zeqb Heq10.\n  lia.\nQed.\n\n(*\nLemma verifier_inv_src_reg :\n  forall ins,\n    well_src ins ->\n    exists r,\n      BinrBPF.int64_to_src_reg' ins = Some r.\nProof.\n  unfold well_src, BinrBPF.int64_to_src_reg'; intros.\n  unfold z_to_reg.\n  remember (get_src ins) as i.\n  clear Heqi.\n  destruct_if_zeqb Heq0.\n  destruct_if_zeqb Heq1.\n  destruct_if_zeqb Heq2.\n  destruct_if_zeqb Heq3.\n  destruct_if_zeqb Heq4.\n  destruct_if_zeqb Heq5.\n  destruct_if_zeqb Heq6.\n  destruct_if_zeqb Heq7.\n  destruct_if_zeqb Heq8.\n  destruct_if_zeqb Heq9.\n  destruct_if_zeqb Heq10.\n  lia.\nQed.\n*)\nLemma opcode_and_255:\n  forall ins,\n    Nat.land (get_opcode ins) 255 = get_opcode ins.\nProof.\n  intros.\n  unfold get_opcode.\n  unfold Int64.and.\n  change (Int64.unsigned (Int64.repr 255)) with (Z.of_nat (Z.to_nat 255)).\n  assert (Heq: Z.of_nat (Z.to_nat (Int64.unsigned ins)) = Int64.unsigned ins).\n  {\n    rewrite Z2Nat.id.\n    reflexivity.\n    apply Int64_unsigned_ge_0.\n  }\n  rewrite <- Heq; clear Heq.\n  rewrite land_land.\n  change (Z.to_nat 255) with 255%nat.\n  assert (Hrange: (Nat.land (Z.to_nat (Int64.unsigned ins)) 255 <= 255)%nat). {\n    rewrite Nat.land_comm.\n    rewrite land_bound.\n    lia.\n  }\n  assert (Hrange_z: (Z.of_nat (Nat.land (Z.to_nat (Int64.unsigned ins)) 255%nat) <= 255)%Z) by lia.\n  rewrite Int64.unsigned_repr.\n  rewrite Nat2Z.id.\n  rewrite <- Nat.land_assoc.\n  rewrite Nat.land_diag.\n  reflexivity.\n  change Int64.max_unsigned with 18446744073709551615%Z.\n  lia.\nQed.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/isolation/VerifierInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.16861981920701594}}
{"text": "From TypingFlags Require Import Loader.\n\nFail Definition T := let T := Type in (T : T).\n\nSet Type In Type.\n\nPrint Typing Flags.\n\nDefinition T := let T := Type in (T : T).\n\n\n\n\nSection t.\n\n  Unset Guard Checking.\n\n  Variable b : bool.\n\n  Fixpoint f (n : nat) {struct n} : True :=\n    match n with\n    | O => I\n    | S _ => if b then f n else I\n    end.\n\n  Print Typing Flags.\nEnd t.\n\n\nFail Definition g := Eval lazy in (f true).\n\nUnset Guard Checking.\nDefinition g := Eval lazy in (f true).\n\n(* SetGuardChecking. *)\nInductive T2 :=\n  l : (T2 -> False) -> T2.\n\nGoal False.\n  assert T2.\n  constructor. intro.\n  remember H.\n  destruct H. auto.\n  remember H.\n  destruct H. auto.\n(* Defined. (* Does not terminate? *) *)  \nQed.\n\nCheck g.\n\nCompute (f false 12).\n\nUnset Type In Type.\nSet Guard Checking.\nDefinition ff := f.\nPrint Assumptions ff.\n", "meta": {"author": "SimonBoulier", "repo": "TypingFlags", "sha": "f2b98d3fd449c6aadc2226ff8d2e724fb01157fa", "save_path": "github-repos/coq/SimonBoulier-TypingFlags", "path": "github-repos/coq/SimonBoulier-TypingFlags/TypingFlags-f2b98d3fd449c6aadc2226ff8d2e724fb01157fa/theories/Demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.16860168738486062}}
{"text": "\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.ProofEnvironment. \nRequire Import depoolContract.DePoolClass.\n\n\nModule DePoolSpec (xt: XTypesSig) (sm: StateMonadSig).\nModule LedgerClass := LedgerClass xt sm .\nImport LedgerClass.\nImport SolidityNotations.\n\nModule Type DePoolSpecSig.\nImport xt. Import sm.\n\n\nParameter DePoolContract_\u0424__returnChange : LedgerT True .\nParameter DePoolContract_\u0424__calcLastRoundInterest : XInteger64 -> XInteger64 -> LedgerT XInteger64 .\nParameter DePoolContract_\u0424__sendError : XInteger32 -> XInteger64 -> LedgerT True .\nParameter DePoolContract_\u0424__sendAccept : XInteger64 -> LedgerT True .\nParameter DePoolContract_\u0424_cutWithdrawalValueAndActivateStake : RoundsBase_\u03b9_InvestParams -> LedgerT ( (XMaybe RoundsBase_\u03b9_InvestParams) # XInteger64 )%sol .\nParameter DePoolContract_\u0424_onStakeAccept : XInteger64 -> XInteger32 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onStakeReject : XInteger64 -> XInteger32 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\n(* Parameter DePool_\u0424_Constructor2 : XInteger64 -> XAddress -> XAddress -> XAddress -> XInteger64 -> LedgerT True . *)\nParameter DePool_\u0424_getParticipantInfo : XAddress -> LedgerT (XErrorValue ( XInteger64 # XInteger64 # XBool # XInteger64 # (XHMap XInteger64 XInteger64) # (XHMap XInteger64 RoundsBase_\u03b9_InvestParams) # (XHMap XInteger64 RoundsBase_\u03b9_InvestParams) ) XInteger)%sol.\nParameter ValidatorBase_\u0424_Constructor2 : XAddress -> LedgerT True.\nParameter DePool_\u0424_getDePoolInfo : LedgerT ( XInteger64 # XInteger64 # XInteger64 # XAddress # XAddress # XAddress # XBool # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 # XInteger64 )%sol .\nParameter DePool_\u0424_getParticipants : LedgerT (XArray XAddress) .\nParameter ProxyBase_\u0424_Constructor3 : XAddress -> XAddress -> LedgerT True .\nParameter DePoolHelper_\u0424_Constructor4 : XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter ProxyBase_\u0424_getProxy : XInteger64 -> LedgerT XAddress .\nParameter ProxyBase_\u0424__recoverStake : XAddress -> XInteger64 -> XAddress -> LedgerT True .\nParameter ProxyBase_\u0424__sendElectionRequest : XAddress -> XInteger64 -> XInteger64 -> DePoolLib_\u03b9_Request -> XAddress -> LedgerT True .\nParameter ConfigParamsBase_\u0424_getCurValidatorData : LedgerT ( XErrorValue ( XInteger256 # XInteger32 # XInteger32 )%sol XInteger ) .\nParameter ConfigParamsBase_\u0424_getPrevValidatorHash : LedgerT ( XErrorValue XInteger XInteger ) .\nParameter ConfigParamsBase_\u0424_roundTimeParams : LedgerT ( XErrorValue ( XInteger32 # XInteger32 # XInteger32 # XInteger32 )%sol XInteger ) .\nParameter ConfigParamsBase_\u0424_getMaxStakeFactor : LedgerT ( XErrorValue XInteger32 XInteger ) .\nParameter ConfigParamsBase_\u0424_getElector : LedgerT ( XErrorValue XAddress XInteger ) .\nParameter ParticipantBase_\u0424__setOrDeleteParticipant : XAddress -> DePoolLib_\u03b9_Participant -> LedgerT True .\nParameter DePoolProxyContract_\u0424_Constructor5 : XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolHelper_\u0424_updateDePoolPoolAddress : XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolHelper_\u0424__settimer : XAddress -> XInteger -> LedgerT True .\nParameter DePoolHelper_\u0424_sendTicktock : LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolHelper_\u0424_getDePoolPoolAddress : LedgerT XAddress .\nParameter DePoolHelper_\u0424_getHistory : LedgerT (XHMap XInteger XAddress) .\nParameter DePoolHelper_\u0424_onCodeUpgrade : LedgerT True .\nParameter DePoolContract_\u0424_Constructor6 : XInteger64 -> XAddress -> XAddress -> XAddress -> XInteger64 -> LedgerT ( XErrorValue True XInteger )  .\nParameter DePoolProxyContract_\u0424_process_new_stake : XInteger64 -> XInteger256 -> XInteger32 -> XInteger32 -> XInteger256 -> XList XInteger8 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolProxyContract_\u0424_recover_stake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_onSuccessToRecoverStake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolProxyContract_\u0424_getProxyInfo : LedgerT ( XAddress # XInteger64 )%sol .\nParameter RoundsBase_\u0424__addStakes : RoundsBase_\u03b9_Round -> DePoolLib_\u03b9_Participant -> XAddress -> XInteger64 -> XMaybe RoundsBase_\u03b9_InvestParams -> XMaybe RoundsBase_\u03b9_InvestParams -> LedgerT ( RoundsBase_\u03b9_Round # DePoolLib_\u03b9_Participant )%sol .\nParameter RoundsBase_\u0424_activeAndNotStakeSum : RoundsBase_\u03b9_StakeValue -> LedgerT XInteger64 .\nParameter RoundsBase_\u0424_activeStakeSum : RoundsBase_\u03b9_StakeValue -> LedgerT XInteger64 .\nParameter RoundsBase_\u0424_toTruncatedRound : RoundsBase_\u03b9_Round -> LedgerT RoundsBase_\u03b9_TruncatedRound .\nParameter DePool_\u0424_Constructor7 : XInteger64 -> XAddress -> XAddress -> XAddress -> XInteger64 -> LedgerT (XErrorValue True XInteger)  .\nParameter DePoolContract_\u0424_onFailToRecoverStake : XInteger64 -> XAddress -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_ticktock : LedgerT ( XErrorValue True XInteger ) .\nParameter Participant_\u0424_onRoundComplete : XInteger64 -> XInteger64 -> XInteger64 -> XInteger64 -> XInteger64 -> XBool -> XInteger8 -> LedgerT True .\nParameter Participant_\u0424_receiveAnswer : XInteger32 -> XInteger64 -> LedgerT True .\nParameter Participant_\u0424_onTransfer : XAddress -> XInteger128 -> LedgerT True .\nParameter Participant_\u0424_sendTransaction : XAddress -> XInteger64 -> XBool -> XInteger16 -> TvmCell -> LedgerT ( XErrorValue True XInteger ) .\n(* Parameter TestElector_\u0424_Constructor8 : XInteger32 -> LedgerT True . *)\n(* Parameter TestElector_\u0424_getElectionId : LedgerT XInteger32 . *)\nParameter DePoolContract_\u0424__returnOrReinvestForParticipant : RoundsBase_\u03b9_Round -> RoundsBase_\u03b9_Round -> XAddress -> RoundsBase_\u03b9_StakeValue -> LedgerT ( XErrorValue RoundsBase_\u03b9_Round XInteger ) .\nParameter DePoolContract_\u0424__returnOrReinvest : RoundsBase_\u03b9_Round -> XInteger8 -> LedgerT ( XErrorValue RoundsBase_\u03b9_Round XInteger ) .\nParameter DePoolContract_\u0424_calculateStakeWithAssert : XBool -> XInteger64 -> LedgerT  ( XInteger64 # XBool )%sol  .\nParameter DePoolContract_\u0424_addOrdinaryStake : XBool -> LedgerT ( XErrorValue  True XInteger ) .\nParameter DePoolContract_\u0424_removeOrdinaryStake : XInteger64 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_addVestingOrLock : XAddress -> XInteger32 -> XInteger32 -> XBool -> LedgerT (XErrorValue  True XInteger) .\nParameter DePoolContract_\u0424_withdrawPartAfterCompleting : XInteger64 -> LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_withdrawAllAfterCompleting : XBool -> LedgerT (XErrorValue  True XInteger) .\nParameter DePoolContract_\u0424_transferStake : XAddress -> XInteger64 -> LedgerT ( XErrorValue  True XInteger ) .\nParameter DePoolContract_\u0424_participateInElections : XInteger64 -> XInteger256 -> XInteger32 -> XInteger32 -> XInteger256 -> XList XInteger8 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_updateRound2 : RoundsBase_\u03b9_Round -> XInteger256 -> XInteger256 -> XInteger32 -> XInteger32 -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_updateRounds :LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_completeRoundWithChunk : XInteger64 -> XInteger8 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_completeRound : XInteger64 -> XInteger32 -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_acceptRewardAndStartRoundCompleting : RoundsBase_\u03b9_Round -> XInteger64 -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_terminator : LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolContract_\u0424_receiveFunds : LedgerT True .\nParameter DePoolHelper_\u0424_onTimer : LedgerT True .\nParameter RoundsBase_\u0424_getRounds : LedgerT (XHMap XInteger64 RoundsBase_\u03b9_TruncatedRound) .\nParameter DebugDePool_\u0424_getCurValidatorData2 : LedgerT ( XInteger256 # XInteger32 # XInteger32 )%sol .\nParameter DebugDePool_\u0424_getPrevValidatorHash2 : LedgerT XInteger .\nParameter DebugDePool_\u0424_Constructor1 : XInteger64 -> XAddress -> XAddress -> XAddress -> XInteger64 -> LedgerT True .\nParameter DePoolContract_\u0424_startRoundCompleting : RoundsBase_\u03b9_Round -> RoundsBase_\u03b9_CompletionReason -> LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolContract_\u0424_addVestingStake : XAddress -> XInteger32 -> XInteger32 -> LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_addLockStake : XAddress -> XInteger32 -> XInteger32 -> LedgerT (XErrorValue True XInteger) .\nParameter DePoolContract_\u0424_generateRound : LedgerT RoundsBase_\u03b9_Round .\nParameter DePoolHelper_\u0424_initTimer : XAddress -> XInteger -> LedgerT ( XErrorValue True XInteger ) .\nParameter DePoolHelper_\u0424_upgrade : TvmCell -> LedgerT ( XErrorValue True XInteger ) .\nParameter RoundsBase_\u0424_transferStakeInOneRound : RoundsBase_\u03b9_Round -> DePoolLib_\u03b9_Participant -> DePoolLib_\u03b9_Participant -> XAddress -> XAddress -> XInteger64 -> XInteger64 -> LedgerT ( RoundsBase_\u03b9_Round # XInteger64 # XInteger64 # DePoolLib_\u03b9_Participant # DePoolLib_\u03b9_Participant )%sol .\nParameter RoundsBase_\u0424_withdrawStakeInPoolingRound : DePoolLib_\u03b9_Participant -> XAddress -> XInteger64 -> XInteger64 -> LedgerT ( XInteger64 # DePoolLib_\u03b9_Participant )%sol .\n\n\nEnd DePoolSpecSig.\n\nEnd DePoolSpec.\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/DePoolSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16858213238264}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.ADT.\nRequire Import Platform.Cito.RepInv.\n\nModule Make (Import E : ADT) (Import M : RepInv E).\n\n  Require Import Platform.Cito.Inv.\n  Module Import InvMake := Make E.\n  Module Import InvMake2 := Make M.\n\n  Require Import Platform.Cito.SyntaxFunc.\n  Require Import Coq.Strings.String.\n  Require Import Platform.Malloc.\n\n  Section TopSection.\n\n    Variable func : FuncCore.\n\n    Definition spec_without_funcs_ok fs : assert :=\n      st ~> ExX, internal_spec _ fs func st.\n\n    Definition spec : assert :=\n      st ~> Ex fs,\n      let stn := fst st in\n      funcs_ok stn fs /\\\n      spec_without_funcs_ok fs st.\n\n    Definition imply (pre new_pre: assert) := forall specs x, interp specs (pre x) -> interp specs (new_pre x).\n\n    Definition verifCond pre := imply pre spec :: nil.\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/CompileFuncSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.16844719970983082}}
{"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 Spec.\n\n  Definition table_map3_spec (g_rd: Pointer) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level with\n    | VZ64 map_addr, VZ64 level =>\n      rely is_int64 map_addr; rely (level >=? 3); rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      rely (peq (base g_rd) ginfo_loc);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx; rely is_gidx root_gidx;\n      when adt == query_oracle adt;\n      (* hold root lock *)\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n      rely (gtype groot =? GRANULE_STATE_TABLE);\n      (* walk deeper root *)\n      let entry0 := (g_data (gnorm groot)) @ idx0 in\n      rely is_int64 entry0;\n      let phys0 := __entry_to_phys entry0 3 in\n      let lv1_gidx := __addr_to_gidx phys0 in\n      if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n        (* level 1 valid, hold level 1 lock *)\n        let glv1 := (gs (share adt)) @ lv1_gidx in\n        rely prop_dec (glock glv1 = None);\n        rely (tbl_level (gaux glv1) =? 1);\n        (* walk deeper level 1 *)\n        rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n        rely (gtype glv1 =? GRANULE_STATE_TABLE);\n        let entry1 := (g_data (gnorm glv1)) @ idx1 in\n        rely is_int64 entry1;\n        let phys1 := __entry_to_phys entry1 3 in\n        let lv2_gidx := __addr_to_gidx phys1 in\n        if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n          (* level 2 valid, hold level 2 lock *)\n          let glv2 := (gs (share adt)) @ lv2_gidx in\n          rely (tbl_level (gaux glv2) =? 2);\n          rely prop_dec (glock glv2 = None);\n          if level =? 3 then\n            (* walk until level 2 *)\n            let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n            map_table lv2_gidx idx2 level adt\n          else\n            (* walk deeper level 2 *)\n            rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);\n            rely (gtype glv2 =? GRANULE_STATE_TABLE);\n            let entry2 := (g_data (gnorm glv2)) @ idx2 in\n            rely is_int64 entry2;\n            let phys2 := __entry_to_phys entry2 3 in\n            let lv3_gidx := __addr_to_gidx phys2 in\n            if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then\n              (* level 2 valid, hold level 2 lock *)\n              let glv3 := (gs (share adt)) @ lv3_gidx in\n              rely prop_dec (glock glv3 = None);\n              rely (tbl_level (gaux glv3) =? 3);\n              if level =? 4 then\n                (* walk until level 3 *)\n                let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 3) :: log adt} in\n                let adt :=  adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in\n                map_table lv3_gidx idx3 level adt\n              else (* can't be other level *)\n                None\n            else\n              (* level 3 invalid *)\n              Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n        else\n          (* level 2 invalid *)\n          Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n      else\n        (* level 1 invalid *)\n        Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef3/Specs/table_map3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.24798742624020273, "lm_q1q2_score": 0.1684277807864246}}
{"text": "Require Import BasicMachineTypes.\nRequire Import ClassDatatypesIface.\nRequire Import ClasspoolIface.\nRequire Import AssignabilityIface.\nRequire Import Twosig.\n\nRequire Import AnnotationIface.\n\nModule Type VIRTUALMETHODLOOKUP\n  (VM_B : BASICS)\n  (ANN : ANNOTATION VM_B)\n  (VM_C : CLASSDATATYPES VM_B ANN)\n  (VM_CP : CLASSPOOL VM_B ANN VM_C)\n  (VM_A  : ASSIGNABILITY VM_B ANN VM_C VM_CP).\n\nDefinition lookup_minimal : VM_CP.cert_classpool -> VM_B.Classname.t -> VM_B.Classname.t -> (VM_B.Methodname.t * VM_C.descriptor) -> Prop\n := fun classes nmA nmB mdesc =>\n    forall nmB' cB',\n     VM_A.assignable classes (VM_C.ty_obj nmA) (VM_C.ty_obj nmB') ->\n     VM_A.assignable classes (VM_C.ty_obj nmB') (VM_C.ty_obj nmB) ->\n     VM_CP.class_loaded classes nmB' cB' ->\n     VM_C.class_interface cB' = false ->\n     nmB' <> nmB ->\n        VM_C.MethodList.lookup (VM_C.class_methods cB') mdesc = None\n     \\/ exists m, VM_C.MethodList.lookup (VM_C.class_methods cB') mdesc = Some m /\\ VM_C.method_static m = true.\n\nParameter lookup_minimal_refl : forall classes nm md c,\n  VM_CP.class_loaded classes nm c ->\n  VM_C.class_interface c = false ->\n  lookup_minimal classes nm nm md.\n\nParameter lookup_minimal_mid : forall classes nmA nmB nmB' md,\n  VM_A.assignable classes (VM_C.ty_obj nmA) (VM_C.ty_obj nmB') ->\n  VM_A.assignable classes (VM_C.ty_obj nmB') (VM_C.ty_obj nmB) ->\n  lookup_minimal classes nmA nmB md ->\n  lookup_minimal classes nmB' nmB md.\n\nParameter lookup_minimal_preserved : forall classes classes' nmA cA nmB cB mdesc,\n  VM_CP.class_loaded classes nmA cA ->\n  VM_C.class_interface cA = false ->\n  VM_CP.class_loaded classes nmB cB ->\n  VM_C.class_interface cB = false ->\n  lookup_minimal classes nmA nmB mdesc ->\n  VM_CP.preserve_old_classes classes classes' ->\n  lookup_minimal classes' nmA nmB mdesc.\n\n\nParameter lookup_virtual_method : forall classes nm d,\n  (exists c, VM_CP.class_loaded classes nm c /\\ VM_C.class_interface c = false) ->\n  option { c : VM_C.class, m : VM_C.method |\n     VM_CP.class_loaded classes (VM_C.class_name c) c /\\\n     VM_C.MethodList.lookup (VM_C.class_methods c) d = Some m /\\\n     VM_C.class_interface c = false /\\\n     VM_C.method_static m = false /\\\n     VM_A.assignable classes (VM_C.ty_obj nm) (VM_C.ty_obj (VM_C.class_name c)) /\\\n     lookup_minimal classes nm (VM_C.class_name c) d}.\n\nEnd VIRTUALMETHODLOOKUP.\n", "meta": {"author": "bacam", "repo": "coqjvm", "sha": "cabb813e3ad8263685b4198eea68f1505ff92947", "save_path": "github-repos/coq/bacam-coqjvm", "path": "github-repos/coq/bacam-coqjvm/coqjvm-cabb813e3ad8263685b4198eea68f1505ff92947/coqjvm/VirtualMethodLookupIface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.16814652557691478}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import Regs State Monad.\nFrom bpf.monadicmodel Require Import Opcode rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma CommonLemmaNat.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nCheck get_opcode_alu64.\nget_opcode_alu64\n     : int8_t -> M DxOpcode.opcode_alu64\n\n*)\n\nSection Get_opcode_alu64.\n  Context {S: special_blocks}.\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(nat:Type)].\n  Definition res : Type := (opcode_alu64:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_opcode_alu64.\n\n  Variable state_block: block. (**r a block storing all rbpf state information? *)\n  Variable mrs_block: block.\n  Variable ins_block: block.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_opcode_alu64.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (fun x => StateLess _ (opcode_correct x))\n                (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun x  => StateLess _ (opcode_alu64_correct x).\n\n  Instance correct_function_get_opcode_alu64 : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _op.\n\n    unfold eval_inv, opcode_correct in c0.\n    destruct c0 as (H0 & Hge).\n    subst.\n\n    eexists. exists m, Events.E0.\n\n    split_and; unfold step2.\n    -\n      repeat forward_star.\n    - simpl.\n      (**r Search (Int.zero_ext).*)\n      rewrite Int.zero_ext_idem;[idtac | lia].\n      rewrite Int.zero_ext_and; [| lia].\n      rewrite nat8_land_240_255_eq; [| apply Hge].\n      unfold match_res, opcode_alu64_correct.\n      rewrite byte_to_opcode_alu64_if_same.\n      unfold byte_to_opcode_alu64_if.\n\n      simpl_opcode Hadd.\n      simpl_opcode Hsub.\n      simpl_opcode Hmul.\n      simpl_opcode Hdiv.\n      simpl_opcode Hor.\n      simpl_opcode Hand.\n      simpl_opcode Hlsh.\n      simpl_opcode Hrsh.\n      simpl_opcode Hneg.\n      simpl_opcode Hmod.\n      simpl_opcode Hxor.\n      simpl_opcode Hmov.\n      simpl_opcode Harsh.\n      exists c; split; [reflexivity| idtac].\n      unfold is_illegal_alu64_ins.\n      repeat simpl_land H0.\n    - simpl.\n      constructor.\n      rewrite Int.zero_ext_idem;[idtac | lia].\n      simpl.\n      rewrite Int.zero_ext_idem;[idtac | lia].\n      reflexivity.\n    - auto.\n    - apply unmodifies_effect_refl.\n  Qed.\n\nEnd Get_opcode_alu64.\n\nExisting Instance correct_function_get_opcode_alu64.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_opcode_alu64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3311197264277872, "lm_q1q2_score": 0.16814652557691478}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * Definition of an optimized CFG parser-recognizer *)\nRequire Import Coq.Lists.List Coq.Strings.String.\nRequire Import Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Compare_dec Coq.Arith.Wf_nat.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.List.ListMorphisms.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.SimpleCorrectness.\nRequire Import Fiat.Parsers.GenericBaseTypes.\nRequire Import Fiat.Parsers.GenericCorrectnessBaseTypes.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Common Fiat.Common.Wf Fiat.Common.Wf2 Fiat.Common.Telescope.Core.\nRequire Import Fiat.Parsers.GenericRecognizerExt.\nRequire Import Fiat.Parsers.GenericRecognizer.\nRequire Import Fiat.Parsers.GenericRecognizerCorrect.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Reflective.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ReflectiveLemmas.\nRequire Import Fiat.Parsers.RecognizerPreOptimized.\nRequire Import Fiat.Common.Match.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\nRequire Export Fiat.Common.SetoidInstances.\nRequire Export Fiat.Common.List.ListMorphisms.\nRequire Export Fiat.Common.OptionFacts.\nRequire Export Fiat.Common.BoolFacts.\nRequire Export Fiat.Common.NatFacts.\nRequire Export Fiat.Common.Sigma.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.GenericRecognizerOptimizedTactics.\nImport NPeano.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nGlobal Arguments string_dec : simpl never.\nGlobal Arguments string_beq : simpl never.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}\n          {G : pregrammar Char}.\n\n  Context (Hvalid : is_true (grammar_rvalid G)).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Context {splitdata : @split_dataT Char _ _}.\n\n  Let data : boolean_parser_dataT :=\n    {| split_data := splitdata |}.\n  Let optdata : boolean_parser_dataT :=\n    {| split_data := optsplitdata |}.\n  Local Existing Instance data.\n\n  Let rdata' : @parser_removal_dataT' _ G predata := rdp_list_rdata'.\n  Local Existing Instance rdata'.\n\n  Context {gendata : generic_parser_dataT Char}\n          {gencdata : generic_parser_correctness_dataT}.\n\n  Local Arguments minus !_ !_.\n  Local Arguments min !_ !_.\n\n  Let is_correct pnt str nt\n    := forall b,\n      parse_nt_is_correct str (of_nonterminal nt) b pnt\n      <-> parse_nt_is_correct str (of_nonterminal nt) b (parse_nonterminal (data := data) str nt).\n\n  Local Arguments Compare_dec.leb !_ !_.\n  Local Arguments to_nonterminal / _ _ _.\n\n  Local Instance good_nth_proper {A}\n  : Proper (eq ==> _ ==> _ ==> eq) (nth (A:=A))\n    := _.\n  Local Instance good_nth'_proper {A}\n  : Proper (eq ==> _ ==> _ ==> eq) (nth' (A:=A))\n    := _.\n\n  Lemma parse_nonterminal_optdata_eq\n        {HSLP : StringLikeProperties Char}\n        {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}\n        (str : String)\n        (nt : String.string)\n    : is_correct (parse_nonterminal (data := optdata) str nt) str nt.\n  Proof.\n    pose optsplitdata_correct.\n    unfold is_correct.\n    pose proof (GenericRecognizerMin.parse_nonterminal_correct str nt).\n    pose proof (GenericRecognizerMin.parse_nonterminal_correct (cdata := optsplitdata_correct) str nt).\n    do 2 edestruct @GenericRecognizerMin.parse_nonterminal; simpl in *;\n      intros []; split; intro;\n        try solve [ tauto\n                  | exfalso; eauto using @parse_nt_is_correct_disjoint ].\n  Qed.\n\n  Let Let_In' {A B} (x : A) (f : forall y : A, B y) : B x\n    := let y := x in f y.\n\n  Local Notation \"@ 'Let_In' A B\" := (@Let_In' A B) (at level 10, A at level 8, B at level 8, format \"@ 'Let_In'  A  B\").\n  Local Notation Let_In := (@Let_In' _ _).\n\n  Let Let_In_Proper {A B} x\n  : Proper (forall_relation (fun _ => eq) ==> eq) (@Let_In A B x).\n  Proof.\n    lazy; intros ?? H; apply H.\n  Defined.\n\n  Definition inner_nth' {A} := Eval unfold nth' in @nth' A.\n  Definition inner_nth'_nth' : @inner_nth' = @nth'\n    := eq_refl.\n\n  Local Instance good_inner_nth'_proper {A}\n  : Proper (eq ==> _ ==> _ ==> eq) (inner_nth' (A:=A))\n    := _.\n\n\n  Lemma rdp_list_to_production_opt_sig x\n  : { f : _ | rdp_list_to_production (G := G) x = f }.\n  Proof.\n    eexists.\n    set_evars.\n    unfold rdp_list_to_production at 1.\n    cbv beta iota delta [Carriers.default_to_production productions production].\n    simpl @Lookup.\n    match goal with\n      | [ |- (let a := ?av in\n              let b := @?bv a in\n              let c := @?cv a b in\n              let d := @?dv a b c in\n              let e := @?ev a b c d in\n              @?v a b c d e) = ?R ]\n        => change (Let_In av (fun a =>\n                   Let_In (bv a) (fun b =>\n                   Let_In (cv a b) (fun c =>\n                   Let_In (dv a b c) (fun d =>\n                   Let_In (ev a b c d) (fun e =>\n                   v a b c d e))))) = R);\n          cbv beta\n    end.\n    lazymatch goal with\n      | [ |- Let_In ?x ?P = ?R ]\n        => subst R; refine (@Let_In_Proper _ _ x _ _ _); intro; set_evars\n    end.\n    unfold Lookup_idx.\n    symmetry; rewrite_map_nth_rhs; symmetry.\n    repeat match goal with\n             | [ |- context G[@Let_In ?A ?B ?k ?f] ]\n               => first [ let h := head k in constr_eq h @nil\n                        | constr_eq k 0\n                        | constr_eq k (snd (snd x)) ];\n                 test pose f; (* make sure f is closed *)\n                 let c := constr:(@Let_In A B k) in\n                 let c' := (eval unfold Let_In' in c) in\n                 let G' := context G[c' f] in\n                 change G'; simpl\n           end.\n    rewrite drop_all by (simpl; omega).\n    unfold productions, production.\n    rewrite <- nth'_nth at 1.\n    rewrite map_map; simpl.\n    match goal with\n      | [ H := ?e |- _ ] => is_evar e; subst H\n    end.\n    match goal with\n      | [ |- nth' ?a ?ls ?d = ?e ?a ]\n        => refine (_ : inner_nth' a ls d = (fun a' => inner_nth' a' _ d) a); cbv beta;\n           apply f_equal2; [ clear a | reflexivity ]\n    end.\n    etransitivity.\n    { apply (_ : Proper (pointwise_relation _ _ ==> eq ==> eq) (@List.map _ _));\n      [ intro | reflexivity ].\n      do 2 match goal with\n             | [ |- Let_In ?x ?P = ?R ]\n               => refine (@Let_In_Proper _ _ x _ _ _); intro\n           end.\n      etransitivity.\n      { symmetry; rewrite_map_nth_rhs; symmetry.\n        unfold Let_In' at 2 3 4; simpl.\n        set_evars.\n        rewrite drop_all by (simpl; omega).\n        unfold Let_In'.\n        rewrite <- nth'_nth.\n        change @nth' with @inner_nth'.\n        subst_body; reflexivity. }\n      reflexivity. }\n    reflexivity.\n  Defined.\n\n  Definition rdp_list_to_production_opt x\n    := Eval cbv beta iota delta [proj1_sig rdp_list_to_production_opt_sig Let_In']\n      in proj1_sig (rdp_list_to_production_opt_sig x).\n\n  Lemma rdp_list_to_production_opt_correct x\n  : rdp_list_to_production (G := G) x = rdp_list_to_production_opt x.\n  Proof.\n    exact (proj2_sig (rdp_list_to_production_opt_sig x)).\n  Qed.\n\n  Definition parse_nonterminal_opt'0\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    exists (parse_nonterminal (data := optdata) str nt).\n    reflexivity.\n  Defined.\n\n  Local Unset Keyed Unification.\n  Definition parse_nonterminal_opt'1\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'0 str nt) in\n    let h := head c in\n    let p := (eval cbv beta iota zeta delta [proj1_sig h] in (proj1_sig c)) in\n    sigL_transitivity p; [ | abstract exact (proj2_sig c) ].\n    cbv beta iota zeta delta [parse_nonterminal GenericRecognizer.parse_nonterminal parse_nonterminal' GenericRecognizer.parse_nonterminal' parse_nonterminal_or_abort GenericRecognizer.parse_nonterminal_or_abort list_to_grammar].\n    simpl @GenericBaseTypes.parse_nt_T.\n    change (@GenericRecognizer.parse_nonterminal_step Char) with (fun b c d e f g h i j k l m => @GenericRecognizer.parse_nonterminal_step Char b c d e f g h i j k l m); cbv beta.\n    evar (b' : parse_nt_T).\n    sigL_transitivity b'; subst b';\n    [\n    | rewrite Fix5_2_5_eq by (intros; rapply (@parse_nonterminal_step_ext _ _ _ optdata _); assumption);\n      reflexivity ].\n    simpl @fst; simpl @snd.\n    cbv beta iota zeta delta [parse_nonterminal_step parse_productions parse_productions' parse_production parse_item parse_item' GenericRecognizer.parse_nonterminal_step GenericRecognizer.parse_productions GenericRecognizer.parse_productions' GenericRecognizer.parse_production GenericRecognizer.parse_item GenericRecognizer.parse_item' Lookup list_to_grammar list_to_productions].\n    simpl.\n    cbv beta iota zeta delta [predata BaseTypes.predata initial_nonterminals_data nonterminals_length remove_nonterminal production_carrierT].\n    cbv beta iota zeta delta [rdp_list_predata Carriers.default_production_carrierT rdp_list_is_valid_nonterminal rdp_list_initial_nonterminals_data rdp_list_remove_nonterminal Carriers.default_nonterminal_carrierT rdp_list_nonterminals_listT rdp_list_production_tl Carriers.default_nonterminal_carrierT].\n    (*cbv beta iota zeta delta [rdp_list_of_nonterminal].*)\n    simpl; unfold pregrammar_nonterminals; simpl.\n    evar (b' : parse_nt_T).\n    sigL_transitivity b'; subst b';\n    [\n    | simpl;\n      rewrite !map_length, !length_up_to;\n      reflexivity ].\n\n    refine_Fix2_5_Proper_eq_with_assumptions.\n    etransitivity_rev _.\n    { fix2_trans_with_assumptions;\n      [\n      | unfold parse_production', parse_production'_for, parse_item', GenericRecognizer.parse_production', GenericRecognizer.parse_production'_for, GenericRecognizer.parse_item', productions, production;\n        solve [ t_reduce_fix;\n                t_reduce_list;\n                t_reduce_fix ] ].\n\n      (** Now we take advantage of the optimized splitter *)\n      etransitivity_rev _.\n      { eapply option_rect_Proper_nondep_eq; [ intros ? Hv | reflexivity ].\n        apply (f_equal (fun x => match x with Some _ => true | None => false end)) in Hv.\n        simpl in Hv.\n        lazymatch goal with\n        | [ H : _ /\\ (_ \\/ is_true (is_valid_nonterminal initial_nonterminals_data ?nt)) |- _ ]\n          => assert (Hvalid' : is_valid_nonterminal initial_nonterminals_data nt)\n        end.\n        { destruct_head and; destruct_head or; try assumption; [].\n          edestruct lt_dec; simpl in *; [ omega | ].\n          edestruct dec; simpl in *; [ | congruence ].\n          match goal with\n          | [ H : _ = true |- _ ] => apply Bool.andb_true_iff in H; destruct H as [? H']\n          end.\n          match goal with\n          | [ H : sub_nonterminals_listT ?ls ?init, H' : list_bin_eq ?nt ?ls = true\n              |- is_true (?R ?init ?nt) ]\n            => apply H, H'\n          end. }\n        let nt := match type of Hvalid' with is_true (is_valid_nonterminal _ ?nt) => nt end in\n        assert (Hvalid'' : productions_rvalid G (map to_production (nonterminal_to_production nt))).\n        { unfold grammar_rvalid in Hvalid.\n          eapply (proj1 fold_right_andb_map_in_iff) in Hvalid; [ eassumption | ].\n          rewrite nonterminal_to_production_correct' by assumption.\n          apply in_map, initial_nonterminals_correct'; assumption. }\n        simpl @nonterminal_to_production in Hvalid''.\n        unfold productions_rvalid in Hvalid''.\n        rewrite map_map in Hvalid''.\n        pose proof (proj1 fold_right_andb_map_in_iff Hvalid'') as Hvalid'''.\n        cbv beta in Hvalid'''.\n\n        misc_opt.\n        step_opt'.\n        step_opt'.\n        step_opt'.\n        step_opt'.\n        apply map_Proper_eq_In; intros ? Hin.\n        apply in_rev in Hin.\n        specialize (Hvalid''' _ Hin).\n        unfold parse_production', parse_production'_for, GenericRecognizer.parse_production', GenericRecognizer.parse_production'_for.\n        simpl.\n        (** Switch to using the list hypothesis, rather than lookup with the index *)\n        etransitivity_rev _.\n        { t_reduce_list_evar_with_hyp;\n          [\n          |\n          | ].\n          { step_opt'.\n            reflexivity. }\n          { rewrite rdp_list_production_tl_correct.\n            match goal with\n              | [ H : _ = ?x |- context[?x] ]\n                => rewrite <- H; reflexivity\n            end. }\n          { match goal with\n              | [ H : _ = ?x |- context[match ?x with _ => _ end] ]\n                => rewrite <- H\n            end.\n            reflexivity. } }\n        (** Pull out the nil case once and for all *)\n        etransitivity_rev _.\n        { lazymatch goal with\n            | [ |- _ = list_rect ?P ?N ?C (?f ?a) ?a ?b ?c ]\n              => let P0 := fresh in\n                 let N0 := fresh in\n                 let C0 := fresh in\n                 set (P0 := P);\n                   set (N0 := N);\n                   set (C0 := C);\n                   let IH := fresh \"IH\" in\n                   let xs := fresh \"xs\" in\n                   refine (list_rect\n                             (fun ls' => forall a' (pf : ls' = f a') b' c',\n                                           (bool_rect\n                                              (fun _ => _)\n                                              (N0 a' b' c')\n                                              (list_rect P0 (fun _ _ _ => ret_production_nil_true) C0 ls' a' b' c')\n                                              (EqNat.beq_nat (List.length ls') 0))\n                                           = list_rect P0 N0 C0 ls' a' b' c')\n                             _\n                             _\n                             (f a) a eq_refl b c);\n                     simpl @list_rect;\n                     [ subst P0 N0 C0; intros; cbv beta\n                     | intros ? xs IH; intros; unfold C0 at 1 3; cbv beta;\n                       match goal with\n                         | [ |- context[list_rect P0 N0 C0 ?ls'' ?a''] ]\n                           => specialize (IH a'')\n                       end;\n                       let T := match type of IH with ?T -> _ => T end in\n                       let H_helper := fresh in\n                       assert (H_helper : T);\n                         [\n                         | specialize (IH H_helper);\n                           setoid_rewrite <- IH; clear IH ] ]\n          end.\n          { reflexivity. }\n          { rewrite rdp_list_production_tl_correct.\n            match goal with\n              | [ H : _ = ?x |- context[?x] ]\n                => rewrite <- H; reflexivity\n            end. }\n          { simpl.\n            match goal with\n            | [ |- context[EqNat.beq_nat (List.length ?ls) 0] ]\n              => is_var ls; destruct ls; simpl; try reflexivity\n            end; [].\n            repeat match goal with\n                   | [ |- ?x = ?x ] => reflexivity\n                   | [ H := fun _ _ => _ |- _ ] => subst H; cbv beta\n                   | [ |- context[?x - (?y + (?x - ?y)) ] ]\n                     => replace (x - (y + (x - y))) with 0 by (clear; omega)\n                   | _ => rewrite minusr_minus\n                   | _ => progress simpl\n                   end. } }\n        simpl.\n        step_opt'; [ | reflexivity ].\n        etransitivity_rev _.\n        { move Hvalid''' at bottom.\n          simpl @to_production in Hvalid'''.\n          unfold production_rvalid in Hvalid'''.\n          t_prereduce_list_evar.\n          t_postreduce_list_with_hyp_with_assumption;\n            [ reflexivity\n            | let lem := constr:(production_tl_correct) in\n              simpl rewrite lem;\n              match goal with\n              | [ H : _::_ = ?y |- context[tl ?y] ] => generalize dependent y; intros; subst\n              end;\n              simpl in *;\n              try reflexivity;\n              try assumption..\n            | ].\n          { match goal with\n            | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n            end.\n            split_and; assumption. }\n          match goal with\n          | [ |- context[match ?nt with Terminal _ => _ | _ => _ end] ]\n            => assert (Hvalid'''' : item_rvalid G nt)\n          end.\n          { repeat match goal with\n                   | _ => assumption\n                   | [ H : ?nt :: _ = ?ls, H' : context[?ls] |- is_true (item_rvalid _ ?nt) ]\n                     => rewrite <- H in H'\n                   | _ => progress simpl in *\n                   | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n                   | _ => progress split_and\n                   end. }\n          etransitivity_rev _.\n          { do 4 step_opt'; [].\n            etransitivity_rev _.\n            { step_opt'; [ reflexivity | ].\n              repeat optsplit_t'.\n              { reflexivity. }\n              { reflexivity. } }\n            unfold list_caset, item_rect.\n            repeat optsplit_t'.\n            { apply (f_equal2 ret_production_cons); [ | reflexivity ].\n              repeat misc_opt'.\n              rewrite Min.min_idempotent.\n              reflexivity. }\n            { apply (f_equal2 ret_production_cons).\n              { apply (f_equal3 (fun (b : bool) x y => if b then x else y)); [ | reflexivity | reflexivity ].\n                apply (f_equal2 andb); [ | reflexivity ].\n                match goal with\n                | [ |- _ = EqNat.beq_nat (min ?v ?x) ?v ]\n                  => refine (_ : Compare_dec.leb v x = _)\n                end.\n                match goal with\n                | [ |- Compare_dec.leb 1 ?x = _ ]\n                  => destruct x as [|[|]]; try reflexivity\n                end. }\n              { rewrite !Nat.add_1_r.\n                reflexivity. } }\n            { simpl in *.\n              match goal with\n              | [ H : is_true ?x |- context[?x] ] => rewrite H\n              end.\n              reflexivity. } }\n          etransitivity_rev _.\n          { unfold parse_item', GenericRecognizer.parse_item'.\n            simpl.\n            repeat optsplit_t'; repeat step_opt';\n              [ apply (f_equal2 ret_production_cons) | ];\n              repeat optsplit_t'; try misc_opt; repeat step_opt'.\n          { reflexivity. }\n          { set_evars.\n            match goal with\n            | [ H : is_true ?x |- context[?x] ] => rewrite H\n            end.\n            match goal with\n            | [ H := ?e |- _ ] => is_evar e; subst H\n            end.\n            reflexivity. }\n          { rewrite !minusr_minus, <- max_def, <- !minusr_minus.\n            reflexivity. }\n          { reflexivity. } }\n        reflexivity. }\n      reflexivity. }\n\n      progress unfold productions, production, rproductions, rproduction.\n      progress cbv beta iota zeta delta [rdp_list_predata Carriers.default_production_carrierT rdp_list_is_valid_nonterminal rdp_list_initial_nonterminals_data rdp_list_remove_nonterminal Carriers.default_nonterminal_carrierT rdp_list_nonterminals_listT rdp_list_production_tl Carriers.default_nonterminal_carrierT].\n\n      step_opt'; [ | reflexivity ].\n      step_opt'.\n      step_opt'.\n      etransitivity_rev _.\n      { cbv beta iota delta [rdp_list_nonterminal_to_production Carriers.default_production_carrierT Carriers.default_nonterminal_carrierT].\n        simpl rewrite list_to_productions_to_nonterminal; unfold Lookup_idx.\n        etransitivity_rev _.\n        { step_opt'; [ reflexivity | ].\n          step_opt'.\n          etransitivity_rev _.\n          { step_opt'.\n            rewrite_map_nth_rhs; simpl; rewrite !map_map; simpl.\n            unfold interp_rproductions, interp_rproduction.\n            apply (f_equal2 (@nth _ _)); [ | reflexivity ].\n            step_opt'; [].\n            rewrite map_length.\n            reflexivity. }\n          rewrite_map_nth_dep_rhs; simpl.\n          rewrite map_length.\n          unfold rproductions, rproduction.\n          reflexivity. }\n        rewrite_map_nth_rhs; rewrite !map_map; simpl.\n        apply (f_equal2 (@nth _ _)); [ | reflexivity ].\n        step_opt'; [ | reflexivity ].\n        rewrite !map_map; simpl.\n        reflexivity. }\n      rewrite_map_nth_rhs; rewrite !map_map; simpl.\n      rewrite <- nth'_nth.\n      etransitivity_rev _.\n      { step_opt'.\n        step_opt'; [ | reflexivity ].\n        reflexivity. }\n      reflexivity. }\n    etransitivity_rev _.\n    { etransitivity_rev _.\n      { repeat first [ rewrite uneta_bool\n                     | idtac;\n                       match goal with\n                       | [ |- context[@rdp_list_of_nonterminal] ] => fail 1\n                       | [ |- context[@Carriers.default_of_nonterminal] ] => fail 1\n                       | [ |- context[@Carriers.default_production_tl] ] => fail 1\n                       | _ => reflexivity\n                       end\n                     | step_opt'\n                     | t_reduce_list_evar\n                     | apply (f_equal2 andb)\n                     | apply (f_equal2 ret_production_cons)\n                     | apply (f_equal2 (@cons _))\n                     | t_refine_item_match ];\n        first [ progress unfold rdp_list_of_nonterminal, Carriers.default_of_nonterminal, Valid_nonterminals, grammar_of_pregrammar, pregrammar_nonterminals; simpl;\n                rewrite !map_length;\n                reflexivity\n              | idtac;\n                match goal with\n                  | [ |- _ = ?f ?A ?b ?c ]\n                    => refine (f_equal (fun A' => f A' b c) _)\n                end;\n                progress unfold Carriers.default_production_tl; simpl;\n                repeat step_opt'; [ reflexivity | ];\n                unfold Lookup_idx;\n                unfold productions, production;\n                rewrite_map_nth_rhs; simpl;\n                rewrite <- nth'_nth;\n                rewrite_map_nth_dep_rhs; simpl;\n                step_opt'; simpl;\n                rewrite !nth'_nth; simpl;\n                rewrite map_length;\n                rewrite <- !nth'_nth;\n                change @nth' with @inner_nth';\n                reflexivity\n              | idtac ].\n        reflexivity. }\n      etransitivity_rev _.\n      { set_evars.\n        repeat first [ idtac;\n                       match goal with\n                         | [ |- context[@rdp_list_to_production] ] => fail 1\n                         | _ => reflexivity\n                       end\n                     | rewrite rdp_list_to_production_opt_correct\n                     | step_opt'\n                     | t_reduce_list_evar ].\n        subst_evars.\n        reflexivity. }\n      etransitivity_rev _.\n      { step_opt'; [ | reflexivity ].\n        step_opt'.\n        step_opt'.\n        step_opt'.\n        step_opt'; [ | reflexivity ].\n        unfold rdp_list_to_production_opt at 1; simpl.\n        change @inner_nth' with @nth' at 3.\n        etransitivity_rev _.\n        { step_opt'.\n          etransitivity_rev _.\n          { repeat step_opt'; [ | reflexivity ].\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth'.\n            apply (f_equal2 (inner_nth' _)); [ | reflexivity ].\n            step_opt'; [].\n            rewrite map_id.\n            change @inner_nth' with @nth' at 3.\n            rewrite nth'_nth.\n            unfold interp_rproductions, interp_rproduction, rproductions, rproduction, production.\n            rewrite !map_length.\n            progress repeat match goal with\n                            | [ |- context[List.nth (?minus (@List.length ?B (@List.map ?A ?B ?f ?ls)) _)] ]\n                              => rewrite (@map_length A B f ls)\n                            end.\n            rewrite_map_nth_rhs; simpl.\n            rewrite !map_map; simpl.\n            unfold productions, production.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth'.\n            apply f_equal2; [ | reflexivity ].\n            reflexivity. }\n          etransitivity_rev _.\n          { change @inner_nth' with @nth' at 1.\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth' at 1.\n            reflexivity. }\n          etransitivity_rev _.\n          { apply f_equal2; [ reflexivity | ].\n            lazymatch goal with\n            | [ |- _ = bool_rect ?P (if ?b then ?t else ?f) ?t ?b' ]\n              => transitivity (if (orb (negb b') b) then t else f); [ | destruct b, b'; reflexivity ]\n            end; fin_step_opt.\n            match goal with\n            | [ |- context[negb (EqNat.beq_nat ?x 0)] ]\n              => replace (negb (EqNat.beq_nat x 0)) with (Compare_dec.leb 1 x)\n                by (destruct x as [|[]]; reflexivity)\n            end.\n            reflexivity. }\n          etransitivity_rev _.\n          { apply (f_equal2 (inner_nth' _)); [ | reflexivity ].\n            step_opt'; [ ].\n            change @inner_nth' with @nth' at 1.\n            rewrite nth'_nth.\n            rewrite_map_nth_rhs; rewrite !map_map; simpl.\n            rewrite <- nth'_nth.\n            change @nth' with @inner_nth' at 1.\n            reflexivity. }\n          etransitivity_rev _.\n          { apply (f_equal2 (inner_nth' _)); [ | reflexivity ].\n            step_opt'.\n            apply (f_equal2 (inner_nth' _)); [ reflexivity | ].\n            lazymatch goal with\n            | [ |- _ = bool_rect ?P (if ?b then ?t else ?f) ?t ?b' ]\n              => transitivity (if (orb (negb b') b) then t else f); [ | destruct b, b'; reflexivity ]\n            end; fin_step_opt.\n            match goal with\n            | [ |- context[negb (EqNat.beq_nat ?x 0)] ]\n              => replace (negb (EqNat.beq_nat x 0)) with (Compare_dec.leb 1 x)\n                by (destruct x as [|[]]; reflexivity)\n            end.\n            reflexivity. }\n          reflexivity. }\n        reflexivity. }\n      reflexivity. }\n    etransitivity_rev _.\n    { repeat first [ step_opt'\n                   | apply (f_equal2 (inner_nth' _)); fin_step_opt\n                   | apply (f_equal2 orb); fin_step_opt\n                   | idtac;\n                     match goal with\n                     | [ |- _ = List.length (rdp_list_to_production_opt _) ]\n                       => progress unfold rdp_list_to_production_opt at 1; simpl;\n                          change @inner_nth' with @nth';\n                          repeat match goal with\n                                 | _ => progress simpl\n                                 | _ => progress fin_step_opt\n                                 | _ => rewrite !map_length\n                                 | _ => rewrite !map_map\n                                 | _ => progress unfold interp_rproductions, interp_rproduction, rproductions, rproduction\n                                 | [ |- _ = nth' ?n ?ls ?d ]\n                                   => refine (f_equal2 (nth' n) _ _)\n                                 | [ |- _ = List.map _ (pregrammar_rproductions G) ]\n                                   => step_opt'\n                                 | [ |- _ = List.map (fun x : list (ritem _) => _) _ ]\n                                   => step_opt'\n                                 | _\n                                   => progress (rewrite nth'_nth;\n                                                progress rewrite_map_nth_rhs; rewrite !map_map; simpl;\n                                                rewrite <- nth'_nth)\n                                 | [ |- _ = List.length ?x ] => is_var x; reflexivity\n                                 end;\n                          fin_step_opt\n                     end ];\n      [ | reflexivity | reflexivity | ].\n      { rewrite list_rect_map.\n        t_reduce_list_evar; [ reflexivity | ].\n        set_evars.\n        setoid_rewrite list_caset_map.\n        unfold predata in *. (* work around bug #4673, https://coq.inria.fr/bugs/show_bug.cgi?id=4673 *)\n        setoid_rewrite item_rect_ritem_rect; cbv beta.\n        try setoid_rewrite uneta_bool.\n        subst_evars.\n\n        step_opt'; [].\n        step_opt'.\n        { etransitivity_rev _.\n          { set_evars.\n            do 2 setoid_rewrite combine_map_r.\n            do 3 setoid_rewrite map_map; simpl.\n            setoid_rewrite map_length.\n            progress change (fun x : ?A * ?B => fst x) with (@fst A B).\n            subst_evars.\n\n            reflexivity. }\n\n          refine (f_equal2 ret_production_cons _ _); [ | reflexivity ].\n          apply (_ : Proper (pointwise_relation _ _ ==> _ ==> _ ==> _) (ritem_rect (fun _ => parse_item_T))); repeat intro;\n            [ | reflexivity | reflexivity ].\n          change_char_at_matches.\n          reflexivity. }\n        { set_evars.\n          do 2 setoid_rewrite combine_map_r.\n          subst_evars.\n\n          step_opt'.\n          { set_evars.\n            change_char_at_matches.\n            do 3 setoid_rewrite map_map; simpl.\n            setoid_rewrite map_length.\n            subst_evars.\n\n            reflexivity. }\n          { step_opt'; [ | reflexivity ].\n            set_evars.\n            do 3 setoid_rewrite map_map; simpl.\n            setoid_rewrite map_length.\n            progress change (fun x : ?A * ?B => fst x) with (@fst A B).\n            subst_evars.\n\n            reflexivity. } } }\n      { reflexivity. } }\n\n    simpl.\n    progress change (fun x : list ?T => @List.length ?T x) with (@List.length T).\n    progress change @inner_nth' with @nth'.\n\n    (** change [nth'] back to [nth] *)\n    etransitivity_rev _.\n    { step_opt'; [ | reflexivity ].\n      step_opt'.\n      step_opt'.\n      apply (f_equal2 (nth' _)); fin_step_opt; [].\n      repeat lazymatch goal with\n             | [ |- _ = nth' _ _ _ ]\n               => rewrite nth'_nth; apply (f_equal2 (nth _))\n             | [ |- _ = orb _ _ ] => apply f_equal2\n             | [ |- _ = ret_production_cons _ _ ] => apply f_equal2\n             | [ |- _ = list_rect _ _ _ ?x _ _ _ ]\n               => is_var x; t_reduce_list_evar\n             | [ |- _ = ?f (_, (_, _)) _ _ ]\n               => is_var f; apply f_equal3\n             | [ |- context[@nth'] ]\n               => step_opt' || fin_step_opt\n             | _ => reflexivity\n             end. }\n\n    simpl.\n    reflexivity.\n  Defined.\n\n\n  Definition parse_nonterminal_opt\n             (str : String)\n             (nt : String.string)\n  : { b : _ | b = parse_nonterminal (data := optdata) str nt }.\n  Proof.\n    let c := constr:(parse_nonterminal_opt'1 str nt) in\n    let h := head c in\n    let impl := (eval cbv beta iota zeta delta [h proj1_sig] in (proj1_sig c)) in\n    (exists impl);\n      abstract (exact (proj2_sig c)).\n  Defined.\n\n  Lemma parse_nonterminal_opt_eq\n        {HSLP : StringLikeProperties Char}\n        {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}\n        (str : String)\n        (nt : String.string)\n    : is_correct (proj1_sig (parse_nonterminal_opt str nt)) str nt.\n  Proof.\n    let p := match goal with |- context[proj1_sig ?p] => p end in\n    rewrite (proj2_sig p).\n    apply parse_nonterminal_optdata_eq.\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/GenericRecognizerOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1680479484777891}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import AST Integers Values Memory.\n\nFrom bpf.comm Require Import BinrBPF Monad.\nFrom bpf.verifier.comm Require Import state.\nFrom Coq Require Import ZArith.\n\nDefinition eval_ins_len : M state.state nat := fun st => Some (eval_ins_len st, st).\n\nDefinition eval_ins (idx: int) : M state.state int64 := fun st =>\n  if (Int.cmpu Clt idx (Int.repr (Z.of_nat (ins_len st)))) then\n    Some (eval_ins idx st, st)\n  else\n    None.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/comm/monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1680443576073988}}
{"text": "From stdpp Require Import finite decidable.\nFrom iris.prelude Require Import options.\nFrom iris.algebra Require Import excl_auth.\nFrom iris.bi Require Import bi.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.proofmode Require Import tactics.\nFrom trillium.prelude Require Export finitary quantifiers sigma classical_instances.\nFrom trillium.fairness Require Import fairness fair_termination fairness_finiteness.\nFrom trillium.program_logic Require Export weakestpre.\nFrom trillium.fairness.heap_lang Require Export lang lifting tactics proofmode.\nFrom trillium.fairness.heap_lang Require Import notation.\n\nImport derived_laws_later.bi.\n\nSet Default Proof Using \"Type\".\n\n(** The program verify liveness for *)\n(** Recursion is \"off by one\" to allow immediate termination after storing 0 *)\nDefinition decr_loop_prog (l : loc) : val :=\n  rec: \"go\" <> :=\n    let: \"x\" := !#l in\n    if: \"x\" = #1 then #l <- (\"x\" - #1)\n    else #l <- (\"x\" - #1);; \"go\" #().\nDefinition choose_nat_prog (l : loc) : val :=\n  \u03bb: <>,\n     #l <- (ChooseNat + #1);;\n     decr_loop_prog l #().\n\n(** The model state *)\nInductive CN := Start | N (n : nat).\n\n(** A mapping of model state to \"program state\" *)\nDefinition CN_Z (cn : CN) : Z :=\n  match cn with\n  | Start => -1\n  | N n => n\n  end.\n\n#[global] Instance CN_eqdec: EqDecision CN.\nProof. solve_decision. Qed.\n\n#[global] Instance CN_inhabited: Inhabited CN.\nProof. exact (populate Start). Qed.\n\nInductive cntrans : CN \u2192 option unit \u2192 CN -> Prop :=\n| start_trans n : cntrans Start (Some ()) (N n)\n| decr_trans n : cntrans (N $ S n) (Some ()) (N n).\n\n(* Free construction of the active labels on each state by [cntrans] *)\nDefinition cn_live_roles (cn : CN) : gset unit :=\n  match cn with N 0 => \u2205 | _ => {[ () ]} end.\n\nLemma cn_live_spec_holds s \u03c1 s' : cntrans s (Some \u03c1) s' -> \u03c1 \u2208 cn_live_roles s.\nProof. destruct s; [set_solver|]. destruct n; [|set_solver]. inversion 1. Qed.\n\nDefinition cn_fair_model : FairModel.\nProof.\n  refine({|\n            fmstate := CN;\n            fmrole := unit;\n            fmtrans := cntrans;\n            live_roles := cn_live_roles;\n            fm_live_spec := cn_live_spec_holds;\n          |}).\nDefined.\n\n(** Show that the model is fairly terminating *)\n\nInductive cn_order : CN \u2192 CN \u2192 Prop :=\n  | cn_order_Start cn : cn_order cn Start\n  | cn_order_N (n1 n2 : nat) : n1 \u2264 n2 \u2192 cn_order (N n1) (N n2).\n\nLocal Instance the_order_po: PartialOrder cn_order.\nProof.\n  split.\n  - split.\n    + by intros []; constructor.\n    + intros [] [] [] Hc12 Hc23; try constructor.\n      * inversion Hc23.\n      * inversion Hc12.\n      * inversion Hc23.\n      * inversion Hc12. inversion Hc23. simplify_eq. lia.\n  - intros [] []; inversion 1; simplify_eq; try eauto; try inversion 1.\n    simplify_eq. f_equal. lia.\nQed.\n\nDefinition cn_decreasing_role (s : fmstate cn_fair_model) : unit :=\n  match s with | _ => () end.\n\n#[local] Program Instance cn_model_terminates :\n  FairTerminatingModel cn_fair_model :=\n  {|\n    ftm_leq := cn_order;\n    ftm_decreasing_role := cn_decreasing_role;\n  |}.\nNext Obligation.\n  assert (\u2200 n, Acc (strict cn_order) (N n)).\n  { intros n.\n    induction n as [n IHn] using lt_wf_ind.\n    constructor. intros cn [Hcn1 Hcn2].\n    inversion Hcn1 as [|n1 n2]; simplify_eq.\n    destruct (decide (n = n1)) as [->|Hneq]; [done|].\n    apply IHn. lia. }\n  constructor. intros [] [Hc1 Hc2]; [|done].\n  inversion Hc1; simplify_eq. done.\nQed.\nNext Obligation.\n  intros cn [\u03c1' [cn' Htrans]].\n  split.\n  - rewrite /cn_decreasing_role. simpl. rewrite /cn_live_roles.\n    destruct cn; [set_solver|].\n    destruct n; [inversion Htrans|set_solver].\n  - intros cn'' Htrans'.\n    destruct cn.\n    + split; [constructor|].\n      intros Hrel. inversion Hrel; simplify_eq. inversion Htrans'.\n    + split.\n      * destruct cn''.\n        -- inversion Htrans'.\n        -- inversion Htrans'; simplify_eq. constructor. lia.\n      * intros Hrel.\n        inversion Htrans'; simplify_eq.\n        inversion Hrel; simplify_eq.\n        lia.\nQed.\nNext Obligation. done. Qed.\nNext Obligation.\n  intros cn1 \u03c1 cn2 Htrans.\n  destruct cn1.\n  - inversion Htrans; simplify_eq. constructor.\n  - inversion Htrans; simplify_eq. constructor. lia.\nQed.\n\nDefinition cn_model : LiveModel heap_lang cn_fair_model :=\n  {| lm_fl _ := 40%nat |}.\n\n(** Determine additional restriction on relation to obtain finite branching *)\nDefinition \u03be_cn (l:loc) (extr : execution_trace heap_lang)\n           (auxtr : finite_trace cn_fair_model (option unit)) :=\n  \u2203 (cn:CN), (trace_last extr).2.(heap) !!! l = #(CN_Z cn) \u2227\n             (trace_last auxtr) = cn.\n\n(** Verify that the program refines the model *)\n\n(* Set up necessary RA constructions *)\nClass choose_natG \u03a3 := ChooseNatG { choose_nat_G :> inG \u03a3 (excl_authR ZO) }.\n\nDefinition choose_nat\u03a3 : gFunctors :=\n  #[ heap\u03a3 cn_fair_model; GFunctor (excl_authR ZO) ].\n\nGlobal Instance subG_choosenat\u03a3 {\u03a3} : subG choose_nat\u03a3 \u03a3 \u2192 choose_natG \u03a3.\nProof. solve_inG. Qed.\n\nDefinition Ns := nroot .@ \"choose_nat\".\n\nSection proof.\n  Context `{!heapGS \u03a3 cn_model, choose_natG \u03a3}.\n\n  (** Determine invariant so we can eventually derive \u03be_cn from it *)\n  Definition choose_nat_inv_inner (\u03b3 : gname) (l:loc) : iProp \u03a3 :=\n    \u2203 (cn:CN), frag_model_is cn \u2217 l \u21a6 #(CN_Z cn) \u2217 own \u03b3 (\u25cfE (CN_Z cn)).\n\n  Definition choose_nat_inv (\u03b3 : gname) (l:loc) :=\n    inv Ns (choose_nat_inv_inner \u03b3 l).\n\n  Lemma decr_loop_spec \u03b3 tid l (n:nat) (f:nat) :\n    7 \u2264 f \u2192 f \u2264 38 \u2192\n    choose_nat_inv \u03b3 l -\u2217\n    {{{ has_fuel tid () f \u2217 frag_free_roles_are \u2205 \u2217\n        own \u03b3 (\u25efE (Z.of_nat (S n))) }}}\n      decr_loop_prog l #() @ tid ; \u22a4\n    {{{ RET #(); tid \u21a6M \u2205 }}}.\n  Proof.\n    iIntros (Hle1 Hle2) \"#IH\".\n    iIntros \"!>\" (\u03a6) \"(Hf & Hr & Hm) H\u03a6\".\n    iInduction n as [|n] \"IHn\".\n    { wp_lam.\n      (* Load - with invariant *)\n      wp_bind (Load _).\n      iApply wp_atomic.\n      iInv Ns as \">HI\" \"Hclose\".\n      iDestruct \"HI\" as (cn) \"(Hs & Hl & Hcn)\".\n      iDestruct (own_valid_2 with \"Hcn Hm\") as %Hvalid%excl_auth_agree_L.\n      iModIntro.\n      wp_load.\n      iModIntro.\n      iMod (\"Hclose\" with \"[Hs Hl Hcn]\") as \"_\"; [ iExists _; iFrame | ].\n      iModIntro.\n      rewrite Hvalid. clear cn Hvalid.\n      (* Store - with invariant *)\n      wp_pures.\n      replace (Z.of_nat 1 - 1)%Z with 0%Z by lia.\n      wp_bind (Store _ _).\n      iApply wp_atomic.\n      iInv Ns as \">HI\" \"Hclose\".\n      iDestruct \"HI\" as (cn) \"(Hs & Hl & Hcn)\".\n      iDestruct (own_valid_2 with \"Hcn Hm\") as %Hvalid%excl_auth_agree_L.\n      iModIntro.\n      assert (cn = N 1) as ->.\n      { destruct cn; inversion Hvalid. by simplify_eq. }\n      (* Update the model state to maintain program correspondence *)\n      iApply (wp_store_step_singlerole _ _ (():fmrole cn_fair_model) (f - 7) (f-3)\n               with \"[$Hl $Hs $Hr Hf]\").\n      { simpl. lia. }\n      { constructor. }\n      { set_solver. }\n      { replace (f - 1 - 1 - 1 - 1 - 1 - 1 - 1)%nat with (f - 7)%nat by lia.\n        by rewrite has_fuel_fuels. }\n      iIntros \"!> (Hl & Hs & Hr & Hf)\".\n      iMod (own_update_2 _ _ _ with \"Hcn Hm\") as \"[Hcn Hm]\".\n      { apply (excl_auth_update _ _ 0%Z). }\n      iMod (\"Hclose\" with \"[Hs Hl Hcn]\") as \"_\".\n      { iExists (N 0). iFrame. }\n      iModIntro.\n      simpl.\n      destruct (decide (() \u2208 \u2205)); [set_solver|].\n      by iApply \"H\u03a6\". }\n    wp_lam.\n    (* Load - with invariant *)\n    wp_bind (Load _).\n    iApply wp_atomic.\n    iInv Ns as \">HI\" \"Hclose\".\n    iModIntro.\n    iDestruct \"HI\" as (cn) \"(Hs & Hl & Hcn)\".\n    wp_load.\n    iDestruct (own_valid_2 with \"Hcn Hm\") as %Hvalid%excl_auth_agree_L.\n    iModIntro. iMod (\"Hclose\" with \"[Hs Hl Hcn]\") as \"_\".\n    { iExists _. iFrame. }\n    iModIntro.\n    rewrite Hvalid. clear cn Hvalid.\n    wp_pures.\n    case_bool_decide as Heq; [inversion Heq; lia|clear Heq].\n    wp_pures.\n    replace (Z.of_nat (S (S n))  - 1)%Z with (Z.of_nat (S n)) %Z by lia.\n    (* Store - with invariant *)\n    wp_bind (Store _ _).\n    iApply wp_atomic.\n    iInv Ns as \">HI\" \"Hclose\".\n    iModIntro.\n    iDestruct \"HI\" as (cn) \"(Hs & Hl & Hcn)\".\n    iDestruct (own_valid_2 with \"Hcn Hm\") as %Hvalid%excl_auth_agree_L.\n    assert (cn = N (S (S n))) as ->.\n    { destruct cn; inversion Hvalid. by simplify_eq. }\n    (* Update the model state to maintain program correspondence *)\n    iApply (wp_store_step_singlerole _ _ (():fmrole cn_fair_model) (f - 7)\n                                     (f+2) with \"[$Hl $Hs $Hr Hf]\").\n    { simpl. lia. }\n    { constructor. }\n    { set_solver. }\n    { replace (f - 1 - 1 - 1 - 1 - 1 - 1 - 1)%nat with (f - 7)%nat by lia.\n      rewrite has_fuel_fuels. done. }\n    iIntros \"!> (Hl & Hs & Hr & Hf)\".\n    iMod (own_update_2 _ _ _ with \"Hcn Hm\") as \"[Hcn Hm]\".\n    { apply (excl_auth_update _ _ (Z.of_nat (S n))%Z). }\n    iMod (\"Hclose\" with \"[Hs Hl Hcn]\") as \"_\".\n    { iExists (N (S n)). iFrame. }\n    iModIntro.\n    simpl. destruct (decide (() \u2208 {[()]})); [|set_solver].\n    wp_pures.\n    replace (f + 2 - 1 - 1)%nat with f by lia.\n    by iApply (\"IHn\" with \"Hf Hr Hm\").\n  Qed.\n\n  Lemma choose_nat_spec \u03b3 l tid (f:nat) :\n    12 \u2264 f \u2192 f \u2264 40 \u2192\n    choose_nat_inv \u03b3 l -\u2217\n    {{{ has_fuel tid () f \u2217 frag_free_roles_are \u2205 \u2217 own \u03b3 (\u25efE (-1)%Z) }}}\n      choose_nat_prog l #() @ tid\n    {{{ RET #(); tid \u21a6M \u2205 }}}.\n  Proof.\n    iIntros (Hle1 Hle2) \"#IH\".\n    iIntros \"!>\" (\u03a6) \"(Hf & Hr & Hm) H\u03a6\".\n    wp_lam.\n    wp_bind ChooseNat.\n    iApply (wp_choose_nat_nostep _ _ _ {[() := (f - 2)%nat]} with \"[Hf]\").\n    { set_solver. }\n    { rewrite -has_fuel_fuels_S has_fuel_fuels.\n      replace (S (f - 2))%nat with (f - 1)%nat by lia. done. }\n    iIntros \"!>\" (n) \"Hf\".\n    wp_pures.\n    (* Store - with invariant *)\n    wp_bind (Store _ _).\n    iApply wp_atomic.\n    iInv Ns as \">HI\" \"Hclose\".\n    iModIntro.\n    iDestruct \"HI\" as (cn) \"(Hs & Hl & Hcn)\".\n    iDestruct (own_valid_2 with \"Hcn Hm\") as %Hvalid%excl_auth_agree_L.\n    assert (cn = Start) as ->.\n    { destruct cn; inversion Hvalid; [done|]. lia. }\n    (* Update the model state to maintain program correspondence *)\n    iApply (wp_store_step_singlerole _ _ (():fmrole cn_fair_model)\n                                     (f - 3) (f-2) _ _ (N (S n))\n             with \"[$Hl $Hs $Hr Hf]\").\n    { simpl. lia. }\n    { constructor. }\n    { set_solver. }\n    { replace (f - 2 - 1)%nat with (f - 3)%nat by lia.\n      rewrite has_fuel_fuels. done. }\n    iIntros \"!> (Hl & Hs & Hr & Hf)\".\n    iMod (own_update_2 _ _ _ with \"Hcn Hm\") as \"[Hcn Hm]\".\n    { apply (excl_auth_update _ _ (Z.of_nat (S n))%Z). }\n    iMod (\"Hclose\" with \"[Hs Hl Hcn]\") as \"_\".\n    { replace (Z.of_nat n + 1)%Z with (Z.of_nat (S n)) by lia.\n      iExists (N (S n)). iFrame. }\n    iModIntro.\n    simpl. destruct (decide (() \u2208 {[()]})); [|set_solver].\n    wp_pures.\n    rewrite -has_fuel_fuels.\n    by iApply (decr_loop_spec with \"IH [$Hm $Hr $Hf]\"); [lia|lia|].\n  Qed.\n\nEnd proof.\n\n(** Construct inverse mapping of program state to model state,\n    to compute finite relation *)\nDefinition Z_CN (v : val) : CN :=\n  match v with\n  | LitV (LitInt z) =>\n      match z with\n      | Z0 => N 0\n      | Zpos p => N (Pos.to_nat p)\n      | Zneg _ => Start         (* Error case when z < -1 *)\n      end\n  | _ => Start                  (* Error case *)\n  end.\n\nLemma Z_CN_CN_Z cn : Z_CN #(CN_Z cn) = cn.\nProof. destruct cn; [done|]; destruct n; [done|]=> /=; f_equal; lia. Qed.\n\n(** Derive that program is related to model by\n    [sim_rel_with_user cn_model (\u03be_cn l) using Trillium adequacy *)\nLemma choose_nat_sim l :\n  continued_simulation\n    (sim_rel_with_user cn_model (\u03be_cn l))\n    (trace_singleton ([choose_nat_prog l #()],\n                        {| heap := {[l:=#-1]};\n                           used_proph_id := \u2205 |}))\n    (trace_singleton (initial_ls (LM := cn_model) Start 0%nat)).\nProof.\n  assert (heapGpreS choose_nat\u03a3 cn_model) as HPreG.\n  { apply _. }\n  eapply (strong_simulation_adequacy\n            choose_nat\u03a3 _ NotStuck _ _ _ \u2205); [|set_solver|].\n  { clear.\n    apply rel_finitary_sim_rel_with_user_\u03be.\n    intros extr atr c' o\u03b6.\n    eapply finite_smaller_card_nat=> /=.\n    eapply (in_list_finite [(Z_CN (heap c'.2 !!! l), None);\n                            (Z_CN (heap c'.2 !!! l), Some ())]).\n    (* TODO: Figure out why this does not unify with typeclass *)\n    Unshelve. 2: intros x; apply make_proof_irrel.\n    intros [cn o] [cn' [Hextr Hatr]].\n    rewrite Hextr Z_CN_CN_Z -Hatr. destruct o; [destruct u|]; set_solver. }\n  iIntros (?) \"!> H\u03c3 Hs Hr Hf\".\n  iMod (own_alloc) as (\u03b3) \"He\"; [apply (excl_auth_valid (-1)%Z)|].\n  iDestruct \"He\" as \"[He\u25cf He\u25cb]\".\n  iMod (inv_alloc Ns \u22a4 (choose_nat_inv_inner \u03b3 l) with \"[He\u25cf H\u03c3 Hs]\") as \"#IH\".\n  { iIntros \"!>\". iExists _. iFrame. by rewrite big_sepM_singleton. }\n  iModIntro.\n  iSplitL.\n  { iApply (choose_nat_spec _ _ _ 40 with \"IH [Hr Hf He\u25cb]\");\n      [lia|lia| |by eauto]=> /=.\n    replace (\u2205 \u2216 {[()]}) with (\u2205:gset unit) by set_solver.\n    rewrite has_fuel_fuels gset_to_gmap_set_to_map. iFrame. }\n  iIntros (ex atr c Hvalid Hex Hatr Hends H\u03be Hstuck) \"H\u03c3\".\n  iInv Ns as \">H\".\n  iDestruct \"H\" as (cn) \"(Hf & Hl & H\u25cf)\".\n  iDestruct \"H\u03c3\" as (Hvalid') \"[H\u03c3 Hs]\".\n  iDestruct (gen_heap_valid with \"H\u03c3 Hl\") as %Hlookup%lookup_total_correct.\n  iDestruct (model_agree' with \"Hs Hf\") as %Hlast.\n  iModIntro. iSplitL; [by iExists _; iFrame|].\n  iApply fupd_mask_intro; [set_solver|]. iIntros \"_\".\n  iPureIntro. exists cn.\n  split; [done|].\n  subst. by destruct atr.\nQed.\n\nTheorem choose_nat_terminates l extr :\n  trfirst extr = ([choose_nat_prog l #()],\n                    {| heap := {[l:=#-1]};\n                      used_proph_id := \u2205 |}) \u2192\n  extrace_fairly_terminating extr.\nProof.\n  intros Hexfirst.\n  eapply heap_lang_continued_simulation_fair_termination; eauto.\n  rewrite Hexfirst. eapply choose_nat_sim.\nQed.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/fairness/examples/choose_nat/choose_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.16804009804610404}}
{"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: Refinement Proof for PKContext              *)\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 Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n(*Require Import AsmImplTactic.*)\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import PKContext.\nRequire Import KContextGenSpec.\n          \n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := mshareintro_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := mshareintro_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** ** Definition the refinement relation: relate_RData + match_RData *)    \n    Section REFINEMENT_REL.\n        \n        (** Relation between the kernel context pool and the underline memory*)\n        Inductive match_KCtxtPool: stencil -> KContextPool -> mem -> meminj -> Prop :=\n        | MATCH_KCTXTPOOL: \n            forall kcp m b s f,\n              (forall ofs, \n                 0<= ofs < num_proc ->\n                 forall n r,\n                   ZtoPreg n = Some r\n                   -> (exists v, \n                         Mem.load Mint32 m b (ofs * 24 + n * 4) = Some v /\\\n                         Mem.valid_access m Mint32 b (ofs * 24 + n * 4) Writable /\\\n                         val_inject f (Val.load_result Mint32 (Pregmap.get r (ZMap.get ofs kcp))) v))\n              -> find_symbol s KCtxtPool_LOC = Some b\n              -> match_KCtxtPool s kcp m f.\n\n        (** Relation between the new raw data at the higher layer with the mememory at lower layer*)\n        Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n        | MATCH_RDATA: \n            forall hadt m s f,\n              match_KCtxtPool s (kctxt hadt) m f\n              -> match_RData s hadt m f. \n\n        (** Relation between raw data at two layers*)\n        Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n          mkrelate_RData {\n              flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n              vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n              devout_re: devout hadt = devout ladt;\n              CR3_re:  CR3 hadt = CR3 ladt;\n              ikern_re: ikern hadt = ikern ladt;\n              pg_re: pg hadt = pg ladt;\n              ihost_re: ihost hadt = ihost ladt;\n              AC_re: AC hadt = AC ladt;\n              ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n              ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n              LAT_re: LAT hadt = LAT ladt;\n              nps_re: nps hadt = nps ladt;\n              init_re: init hadt = init ladt;\n\n              pperm_re: pperm ladt = pperm hadt;\n              PT_re:  PT ladt = PT hadt;\n              ptp_re: ptpool ladt = ptpool hadt;\n              idpde_re: idpde ladt = idpde hadt;\n              ipt_re: ipt ladt = ipt hadt;\n              smspool_re: smspool ladt = smspool hadt\n            }.\n\n        Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n          {\n            relate_AbData s f d1 d2 := relate_RData f d1 d2;\n            match_AbData s d1 m f := match_RData s d1 m f;\n            new_glbl := KCtxtPool_LOC :: nil\n          }.\n\n    End REFINEMENT_REL.\n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      Lemma inject_match_correct:\n        forall s d1 m2 f m2' j,\n          match_RData s d1 m2 f ->\n          Mem.inject j m2 m2' ->\n          inject_incr (Mem.flat_inj (genv_next s)) j ->\n          match_RData s d1 m2' (compose_meminj f j).\n      Proof.\n        inversion 1; subst; intros.\n        inv H0.\n        assert (HFB0: j b = Some (b, 0)).\n        {\n          eapply stencil_find_symbol_inject'; eauto.\n        }\n        econstructor; eauto; intros.\n        econstructor; eauto; intros.\n        specialize (H3 _ H0 _ _ H5).\n        destruct H3 as [v1[HL1[HV1 HM]]]. \n        specialize (Mem.load_inject _ _  _ _ _ _ _ _ _ H1 HL1 HFB0).\n        repeat rewrite Z.add_0_r. \n        intros [v1'[HLD1' HV1']].\n        refine_split'; eauto.\n        specialize(Mem.valid_access_inject _ _  _ _ _ _ _ _ _ HFB0 H1 HV1).\n        rewrite Z.add_0_r; trivial.\n        eapply val_inject_compose; eauto.\n      Qed.\n\n      Lemma store_match_correct:\n        forall s abd m0 m0' f b2 v v' chunk,\n          match_RData s abd m0 f ->\n          (forall i b,\n             In i new_glbl ->\n             find_symbol s i = Some b -> b <> b2) ->\n          Mem.store chunk m0 b2 v v' = Some m0' ->\n          match_RData s abd m0' f.\n      Proof.\n        intros. inv H. inv H2.\n        econstructor; eauto.\n        econstructor; eauto.\n        intros. specialize (H _ H2 _ _ H4).\n        destruct H as [v1[HL1[HV1 HM]]]. \n        eapply H0 in H3; simpl; eauto.\n        repeat rewrite (Mem.load_store_other  _ _ _ _ _ _ H1); auto.\n        refine_split'; eauto;\n        eapply Mem.store_valid_access_1; eauto.\n      Qed.\n\n      Lemma storebytes_match_correct:\n        forall s abd m0 m0' f b2 v v',\n          match_RData s abd m0 f ->\n          (forall i b,\n             In i new_glbl ->\n             find_symbol s i = Some b -> b <> b2) ->\n          Mem.storebytes m0 b2 v v' = Some m0' ->\n          match_RData s abd m0' f.\n      Proof.\n        intros. inv H. inv H2.\n        econstructor; eauto.\n        econstructor; eauto. \n        intros. specialize (H _ H2 _ _ H4).\n        destruct H as [v1[HL1[HV1 HM]]]. \n        eapply H0 in H3; simpl; eauto.\n        repeat rewrite (Mem.load_storebytes_other _ _ _ _ _ H1); eauto.\n        refine_split'; eauto;\n        eapply Mem.storebytes_valid_access_1; eauto.\n      Qed.\n\n      Lemma free_match_correct:\n        forall s abd m0 m0' f ofs sz b2,\n          match_RData s abd m0 f->\n          (forall i b,\n             In i new_glbl ->\n             find_symbol s i = Some b -> b <> b2) ->\n          Mem.free m0 b2 ofs sz = Some m0' ->\n          match_RData s abd m0' f.\n      Proof.\n        intros; inv H; inv H2.\n        econstructor; eauto.\n        econstructor; eauto. \n        intros. specialize (H _ H2 _ _ H4).\n        destruct H as [v1[HL1[HV1 HM]]]. \n        eapply H0 in H3; simpl; eauto.\n        repeat rewrite (Mem.load_free _ _ _ _ _ H1); auto.\n        refine_split'; eauto;\n        eapply Mem.valid_access_free_1; eauto.\n      Qed.\n      \n      Lemma alloc_match_correct:\n        forall s abd m'0  m'1 f f' ofs sz b0 b'1,\n          match_RData s abd m'0 f->\n          Mem.alloc m'0 ofs sz = (m'1, b'1) ->\n          f' b0 = Some (b'1, 0%Z) ->\n          (forall b : block, b <> b0 -> f' b = f b) ->\n          inject_incr f f' ->\n          (forall i b,\n             In i new_glbl ->\n             find_symbol s i = Some b -> b <> b0) ->\n          match_RData s abd m'1 f'.\n      Proof.\n        intros. rename H1 into HF1, H2 into HB. inv H; inv H1.\n        econstructor; eauto.\n        econstructor; eauto. \n        intros. specialize (H _ H1 _ _ H5).\n        destruct H as [v1[HL1[HV1 HM]]]. \n        refine_split'; eauto;\n        try (apply (Mem.load_alloc_other _ _ _ _ _ H0));          \n        try (eapply Mem.valid_access_alloc_other); eauto.\n      Qed.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor.\n        - apply inject_match_correct.\n        - apply store_match_correct.\n        - apply alloc_match_correct.\n        - apply free_match_correct.\n        - apply storebytes_match_correct.\n        - intros. eapply relate_incr; eauto.\n        - intros; eapply relate_kernel_mode; eauto.\n        - intros; eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      Ltac pattern2_refinement_simpl:=  \n        pattern2_refinement_simpl' (@relate_AbData).\n\n      Section FRESH_PRIM.\n\n        Lemma kctxt_ra_spec_ref:\n          compatsim (crel HDATA LDATA) PKContext.kctxt_ra_compatsem\n                    kctxt_ra_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          assert(HOS: kernel_mode d2 /\\ 0 <= Int.unsigned n < num_proc).\n          {\n            simpl; inv match_related.\n            unfold kctxt_ra_spec in *.\n            subdestruct. inv H7.\n            refine_split'; trivial; try congruence. omega.\n          }\n          destruct HOS as [Hkern HOS]. \n          inv H. rename H0 into HMem. \n          assert (HOS': ZtoPreg 5 = Some RA) by reflexivity.\n          destruct (HMem _ HOS _ _ HOS') as [v1[HL1[HV1 HM]]].\n          specialize (Mem.valid_access_store _ _ _ _ (Vptr b ofs) HV1); intros [m' HST].\n          assert(HFB: \u03b9 b = Some (b, 0)).\n          {\n            destruct H5 as [fun_id Hsymbol].\n            eapply stencil_find_symbol_inject'; eauto.\n          }          \n          refine_split.\n          - econstructor; eauto.\n            instantiate (2:= m').\n            instantiate (1:= d2).\n            simpl in HST; simpl; lift_trivial. subrewrite'.\n          - constructor.\n          - rename H7 into Hspec.\n            unfold kctxt_ra_spec in Hspec.\n            pose proof match_related as match_relate'.\n            inv match_related.\n            subdestruct. inv Hspec. \n            split; eauto; pattern2_refinement_simpl. \n            econstructor; simpl; eauto.\n            econstructor; eauto; intros.\n            destruct (zeq ofs0 (Int.unsigned n)); subst.          \n            + (* ofs0 = Int.unsigned n *)\n              destruct (zeq n0 5); subst.\n              * (* n0 = 5  *)\n                refine_split'; eauto;\n                try eapply Mem.store_valid_access_1; eauto.\n                eapply Mem.load_store_same; eauto.\n                repeat rewrite ZMap.gss. inv H0.\n                rewrite Pregmap.gsspec. simpl.\n                econstructor; eauto. \n                rewrite Int.add_zero; trivial.\n              * (* n0 <> 5 *)\n                specialize (HMem _ H _ _ H0).\n                destruct HMem as [v1'[HL1'[HV1' HM']]].\n                refine_split'; eauto;\n                try eapply Mem.store_valid_access_1; eauto.\n                rewrite <- (Mem.load_store_other  _ _ _ _ _ _ HST) in HL1'; eauto.\n                simpl; right. destruct (zlt n0 5); [left; omega|right; omega].\n                rewrite ZMap.gss. \n                rewrite Pregmap.gsspec.\n                destruct (Pregmap.elt_eq r RA); subst; auto.\n                apply ZtoPreg_correct in H0. \n                inv H0. omega.\n            + (* ofs0 <> Int.unsigned n *)\n              specialize (HMem _ H _ _ H0).\n              destruct HMem as [v1'[HL1'[HV1' HM']]].\n              refine_split'; eauto;\n              try eapply Mem.store_valid_access_1; eauto.\n              rewrite <- (Mem.load_store_other  _ _ _ _ _ _ HST) in HL1'; eauto.\n              simpl; right. apply ZtoPreg_range in H0.\n              destruct (zlt ofs0 (Int.unsigned n)); [left; omega|right; omega].\n              rewrite ZMap.gso; trivial.\n          - apply inject_incr_refl.\n        Qed.\n\n        Lemma kctxt_sp_spec_ref:\n          compatsim (crel HDATA LDATA) PKContext.kctxt_sp_compatsem\n                    kctxt_sp_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          assert(HOS: kernel_mode d2 /\\ 0 <= Int.unsigned n < num_proc).\n          {\n            simpl; inv match_related.\n            unfold kctxt_sp_spec in *.\n            subdestruct. inv H8.\n            refine_split'; trivial; try congruence. omega.\n          }\n          destruct HOS as [Hkern HOS]. \n          inv H. rename H0 into HMem. \n          assert (HOS': ZtoPreg 0 = Some (IR ESP)) by reflexivity.\n          destruct (HMem _ HOS _ _ HOS') as [v1[HL1[HV1 HM]]].\n          specialize (Mem.valid_access_store _ _ _ _ (Vptr b ofs) HV1); intros [m' HST].\n          assert(HFB: \u03b9 b = Some (b, 0)).\n          {\n            destruct H6 as [fun_id Hsymbol].\n            eapply stencil_find_symbol_inject'; eauto.\n          }          \n          refine_split.\n          - econstructor; eauto.\n            instantiate (2:= m').\n            instantiate (1:= d2).\n            simpl in HST; simpl; lift_trivial.\n            replace (Int.unsigned n * 24) with (Int.unsigned n * 24 + 0) by omega.\n            subrewrite'.\n          - constructor.\n          - rename H8 into Hspec.\n            unfold kctxt_sp_spec in Hspec.\n            pose proof match_related as match_relate'.\n            inv match_related.\n            subdestruct. inv Hspec. \n            split; eauto; pattern2_refinement_simpl. \n            econstructor; simpl; eauto.\n            econstructor; eauto; intros.\n            destruct (zeq ofs0 (Int.unsigned n)); subst.          \n            + (* ofs0 = Int.unsigned n *)\n              destruct (zeq n0 0); subst.\n              * (* n0 = 0 *)\n                refine_split'; eauto;\n                try eapply Mem.store_valid_access_1; eauto.\n                eapply Mem.load_store_same; eauto.\n                repeat rewrite ZMap.gss. inv H0.\n                rewrite Pregmap.gsspec. simpl.\n                econstructor; eauto. \n                rewrite Int.add_zero; trivial.\n              * (* n0 <> 0 *)\n                specialize (HMem _ H _ _ H0).\n                destruct HMem as [v1'[HL1'[HV1' HM']]].\n                refine_split'; eauto;\n                try eapply Mem.store_valid_access_1; eauto.\n                rewrite <- (Mem.load_store_other  _ _ _ _ _ _ HST) in HL1'; eauto.\n                simpl; right. destruct (zlt n0 0); [left; omega|right; omega].\n                rewrite ZMap.gss. \n                rewrite Pregmap.gsspec.\n                destruct (Pregmap.elt_eq r ESP); subst; auto.\n                apply ZtoPreg_correct in H0. \n                inv H0. omega.\n            + (* ofs0 <> Int.unsigned n *)\n              specialize (HMem _ H _ _ H0).\n              destruct HMem as [v1'[HL1'[HV1' HM']]].\n              refine_split'; eauto;\n              try eapply Mem.store_valid_access_1; eauto.\n              rewrite <- (Mem.load_store_other  _ _ _ _ _ _ HST) in HL1'; eauto.\n              simpl; right. apply ZtoPreg_range in H0.\n              destruct (zlt ofs0 (Int.unsigned n)); [left; omega|right; omega].\n              rewrite ZMap.gso; trivial.\n          - apply inject_incr_refl.\n        Qed.\n\n        Lemma kctxt_switch_spec_ref:\n          compatsim (crel HDATA LDATA)\n                    (primcall_kctxt_switch_compatsem kctxt_switch_spec)\n                    kctxt_switch_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData). intros.\n          inv match_extcall_states.\n          unfold kctxt_switch_spec in *.\n          subdestruct. \n          inv match_match. inv H.\n          rename H0 into HMAT. \n          assert (HV0: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m2 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros. destruct (ZtoPreg_range_correct _ H0) as [r HEX].\n            destruct (HMAT _ H _ _ HEX) as [_[_[HV _]]]; trivial.\n          }\n          assert (HP: exists m0, Mem.store Mint32 m2 b0 (Int.unsigned n * 24) (rs2#ESP) = Some m0).\n          {\n            assert(HOS0: 0 <= 0 <=5) by omega.\n            specialize (HV0 _ a _ HOS0).\n            replace (Int.unsigned n * 24 + 0 * 4) with (Int.unsigned n * 24) in HV0 by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m0 HST0].\n          assert (HV1: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m0 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV0.\n          assert (HP: exists m1, Mem.store Mint32 m0 b0 (Int.unsigned n * 24 + 1 * 4) (rs2#EDI) = Some m1).\n          {\n            assert(HOS0: 0 <= 1 <=5) by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m1 HST1].\n          assert (HV2: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m1 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV1.\n          assert (HP: exists m2', Mem.store Mint32 m1 b0 (Int.unsigned n * 24 + 2 * 4) (rs2#ESI) = Some m2').\n          {\n            assert(HOS0: 0 <= 2 <=5) by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m2' HST2].\n          assert (HV3: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m2' Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV2.\n          assert (HP: exists m3, Mem.store Mint32 m2' b0 (Int.unsigned n * 24 + 3 * 4) (rs2#EBX) = Some m3).\n          {\n            assert(HOS0: 0 <= 3 <=5) by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m3 HST3].\n          assert (HV4: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m3 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV3.\n          assert (HP: exists m4, Mem.store Mint32 m3 b0 (Int.unsigned n * 24 + 4 * 4) (rs2#EBP) = Some m4).\n          {\n            assert(HOS0: 0 <= 4 <=5) by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m4 HST4].\n          assert (HV5: forall ofs : Z,\n                         0 <= ofs < num_proc ->\n                         forall n0, 0<= n0 <= 5 -> Mem.valid_access m4 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV4.\n          assert (HP: exists m5, Mem.store Mint32 m4 b0 (Int.unsigned n * 24 + 5 * 4) (rs2#RA) = Some m5).\n          {\n            assert(HOS0: 0 <= 5 <=5) by omega.\n            apply (Mem.valid_access_store); auto.\n          }\n          destruct HP as [m5 HST5].\n          assert (HV: forall ofs : Z,\n                        0 <= ofs < num_proc ->\n                        forall n0, 0<= n0 <= 5 -> Mem.valid_access m5 Mint32 b0 (ofs * 24 + n0 * 4) Writable).\n          {\n            intros; eapply Mem.store_valid_access_1; eauto.\n          }\n          clear HV5.          \n          assert (HMAT':  \n                    forall ofs : Z,\n                      0 <= ofs < num_proc ->\n                      ofs <> Int.unsigned n ->\n                      forall (n : Z) (r : preg),\n                        ZtoPreg n = Some r ->\n                        exists v : val,\n                          Mem.load Mint32 m5 b0 (ofs * 24 + n * 4) = Some v /\\\n                          Mem.valid_access m5 Mint32 b0 (ofs * 24 + n * 4) Writable /\\\n                          val_inject \u03b9 ((Val.load_result \n                                           Mint32 (Pregmap.get \n                                                     r (ZMap.get ofs (kctxt d1))))) v).\n          {\n            intros.\n            destruct (HMAT _ H _ _ H2) as [v[HLD[_ HM]]].\n            exists v.\n            specialize (ZtoPreg_range _ _ H2); intros Hn1.\n            split; eauto.\n            Ltac simpl_other ofs n:= \n              right; simpl; destruct (zlt ofs (Int.unsigned n));\n              [left; omega|right; omega].       \n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST5); [|simpl_other ofs n].\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST4); [|simpl_other ofs n].\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST3); [|simpl_other ofs n].\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST2); [|simpl_other ofs n].\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST1); [|simpl_other ofs n].\n            rewrite (Mem.load_store_other  _ _ _ _ _ _ HST0); [|simpl_other ofs n].\n            trivial. \n          }\n          clear HMAT.\n          assert (forall n0 : Z, 0 <= n0 <= 5 -> Mem.valid_access m5 Mint32 b0 (Int.unsigned n' * 24 + n0 * 4) Readable).\n          {\n            specialize (HV _ a0).\n            intros. specialize (HV _ H).\n            eapply Mem.valid_access_implies; eauto.\n            constructor.\n          }\n          clear HV.\n          assert (HP: exists v0, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 0 * 4) = Some v0).\n          {\n            assert (0<= 0 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }\n          destruct HP as [v0 HLD0].\n          assert (HP: exists v1, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 1 * 4) = Some v1).\n          {\n            assert (0<= 1 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }          \n          destruct HP as [v1 HLD1].\n          assert (HP: exists v2, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 2 * 4) = Some v2).\n          {\n            assert (0<= 2 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }\n          destruct HP as [v2 HLD2].\n          assert (HP: exists v3, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 3 * 4) = Some v3).\n          {\n            assert (0<= 3 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }\n          destruct HP as [v3 HLD3].\n          assert (HP: exists v4, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 4 * 4) = Some v4).\n          {\n            assert (0<= 4 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }\n          destruct HP as [v4 HLD4].\n          assert (HP: exists v5, Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + 5 * 4) = Some v5).\n          {\n            assert (0<= 5 <= 5) by omega.\n            eapply Mem.valid_access_load; eauto.\n          }\n          destruct HP as [v5 HLD5].\n          simpl in *.\n          assert(N_ARU': rs2 EAX = Vint n /\\ rs2 EDX = Vint n').\n          {\n            unfold Pregmap.get in *.\n            split.\n            specialize (match_reg EAX).\n            rewrite N_ARU1 in match_reg.\n            inv match_reg; trivial.\n            unfold Pregmap.get in *.\n            specialize (match_reg EDX).\n            rewrite N_ARU2 in match_reg.\n            inv match_reg; trivial.\n          }\n          destruct N_ARU' as [N_ARU1' N_ARU2'].\n          assert(HMCTXT: match_KCtxtPool s (kctxt d1') m5 \u03b9).\n          {\n            econstructor; eauto. clear HLD0 HLD1 HLD2 HLD3 HLD4 HLD5.\n            intros.\n            destruct (zeq ofs (Int.unsigned n)).\n            * (* ofs = Int.unsigned n*)\n              clear HMAT'. subst.\n              specialize (ZtoPreg_range _ _ H2).\n              intros Hn1.\n              destruct (zeq n1 5); subst; inv H2.\n              eexists (Val.load_result Mint32 (rs2 RA)).\n              split.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              inv H4. simpl in *.\n              rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg RA).\n              inv match_reg; try constructor.\n              econstructor; eauto.\n              assert (HW0: Mem.load Mint32 m5 b0 (Int.unsigned n * 24 + n1 * 4) = \n                           Mem.load Mint32 m4 b0 (Int.unsigned n * 24 + n1 * 4)).\n              {\n                rewrite (Mem.load_store_other  _ _ _ _ _ _ HST5).\n                trivial.\n                right. left. simpl. omega.\n              }\n              destruct (zeq n1 4); subst. inv H4.\n              eexists (Val.load_result Mint32 (rs2 EBP)).\n              split. rewrite HW0.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              inv H5. simpl in *. rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg EBP).\n              inv match_reg; try constructor.\n              econstructor; eauto.\n              assert (HW1: Mem.load Mint32 m5 b0 (Int.unsigned n * 24 + n1 * 4)\n                           = Mem.load Mint32 m3 b0 (Int.unsigned n * 24 + n1 * 4)).\n              {\n                rewrite HW0.\n                rewrite (Mem.load_store_other  _ _ _ _ _ _ HST4).\n                trivial.\n                right. left. simpl. omega.\n              }\n              clear HW0.\n              destruct (zeq n1 3); subst. inv H4.\n              eexists (Val.load_result Mint32 (rs2 EBX)).\n              split. rewrite HW1.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              inv H5. simpl in *.\n              rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg EBX).\n              inv match_reg; try constructor.\n              econstructor; eauto.\n              assert (HW2: Mem.load Mint32 m5 b0 (Int.unsigned n * 24 + n1 * 4)\n                           = Mem.load Mint32 m2' b0 (Int.unsigned n * 24 + n1 * 4)).\n              {\n                rewrite HW1.\n                rewrite (Mem.load_store_other  _ _ _ _ _ _ HST3).\n                trivial.\n                right. left. simpl. omega.\n              }\n              clear HW1.\n              destruct (zeq n1 2); subst. inv H4.\n              eexists (Val.load_result Mint32 (rs2 ESI)).\n              split. rewrite HW2.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              inv H5. simpl in *.\n              rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg ESI).\n              inv match_reg; try constructor.\n              econstructor; eauto.\n              assert (HW1: Mem.load Mint32 m5 b0 (Int.unsigned n * 24 + n1 * 4)\n                           = Mem.load Mint32 m1 b0 (Int.unsigned n * 24 + n1 * 4)).\n              {\n                rewrite HW2.\n                rewrite (Mem.load_store_other  _ _ _ _ _ _ HST2).\n                trivial.\n                right. left. simpl. omega.\n              }\n              clear HW2.\n              destruct (zeq n1 1); subst; inv H4.\n              eexists (Val.load_result Mint32 (rs2 EDI)).\n              split. rewrite HW1.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              inv H5. simpl in *.\n              rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg EDI).\n              inv match_reg; try constructor.\n              econstructor; eauto.\n              assert (HW0: Mem.load Mint32 m5 b0 (Int.unsigned n * 24 + n1 * 4)\n                           = Mem.load Mint32 m0 b0 (Int.unsigned n * 24 + n1 * 4)).\n              {\n                rewrite HW1.\n                rewrite (Mem.load_store_other  _ _ _ _ _ _ HST1).\n                trivial.\n                right. left. simpl. omega.\n              }\n              clear HW1.\n              destruct (zeq n1 0). subst. inv H5.\n              eexists (Val.load_result Mint32 (rs2 ESP)).\n              replace (Int.unsigned n * 24 + 0 * 4) with (Int.unsigned n * 24) in * by omega.\n              split. rewrite HW0.\n              eapply Mem.load_store_same; eauto. \n              split.\n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_1; eauto. \n              eapply Mem.store_valid_access_3; eauto. \n              simpl in *.\n              rewrite ZMap.gss.\n              unfold Pregmap.get in *.\n              specialize (match_reg ESP).\n              inv match_reg; try constructor.\n              econstructor; eauto.          \n              omega.\n            *  (** ofs <> Int.unsigned n**)\n              specialize (HMAT' _ H0 n2 _ _ H2).\n              inv H4. simpl.      \n              rewrite ZMap.gso; trivial.\n          }\n          refine_split; eauto 2.\n          - econstructor; eauto; simpl; lift_trivial;\n            try eassumption; unfold set; simpl.\n            eapply reg_symbol_inject; eassumption.\n            rewrite HST0. reflexivity.\n            simpl; rewrite HST1. reflexivity.\n            simpl; rewrite HST2. reflexivity.\n            simpl; rewrite HST3. reflexivity.\n            simpl; rewrite HST4. reflexivity.\n            simpl; rewrite HST5. reflexivity.\n\n            simpl. inv match_related.\n            split; congruence.\n          - pose proof match_related as match_relate'.\n            inv match_related. inv H4.\n            econstructor; eauto.\n            split; eauto; pattern2_refinement_simpl.           \n            econstructor; eauto 2.\n            econstructor; simpl; eauto 2.\n            assert (HINJ: forall n1 r,\n                            ZtoPreg n1 = Some r ->\n                            forall v ,\n                              Mem.load Mint32 m5 b0 (Int.unsigned n' * 24 + n1 * 4) = Some v ->\n                              val_inject \u03b9 ((ZMap.get (Int.unsigned n') (kctxt d1)) r) v).\n            {\n              assert (Hn: Int.unsigned n' <> Int.unsigned n) by auto.\n              intros. specialize (HMAT' _ a0 Hn _ _ H0).\n              destruct HMAT' as [v'[HL'[_ HV']]].\n              rewrite H2 in HL'. inv HL'.\n              refine_split'; eauto 2.\n              unfold Pregmap.get in *.\n              specialize (N_TYPE _ _ H0).\n              caseEq (ZMap.get (Int.unsigned n') (kctxt d1) r); intros;\n              rewrite H3 in *; try assumption; inv N_TYPE.\n            }\n            clear HMAT'. subst rs3.\n            val_inject_simpl;\n              try (eapply HINJ; [apply PregToZ_correct; reflexivity| trivial]).\n        Qed.\n\n      End FRESH_PRIM.\n\n      Section PASSTHROUGH_PRIM. \n\n        Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n        Proof.\n          accessor_prop_tac.\n          - eapply flatmem_store_exists; eauto.\n          - eapply flatmem_store_match; eauto.\n        Qed.\n\n        Lemma passthrough_correct:\n          sim (crel HDATA LDATA) pkcontext_passthrough mshare.\n        Proof.\n          sim_oplus.\n          - apply fload_sim.\n          - apply fstore_sim.\n          - apply flatmem_copy_sim.\n          - apply vmxinfo_get_sim.\n          - apply device_output_sim.\n          - apply pfree_sim.\n          - apply setPT_sim.\n          - apply ptRead_sim. \n          - apply ptResv_sim.\n          - apply pt_new_sim.\n          - apply sharedmem_init_sim.\n          - apply shared_mem_status_sim.\n          - apply offer_shared_mem_sim.\n          - apply ptin_sim.\n          - apply ptout_sim.\n          - apply clearCR2_sim.\n          - apply container_get_nchildren_sim.\n          - apply container_get_quota_sim.\n          - apply container_get_usage_sim.\n          - apply container_can_consume_sim.\n          - apply alloc_sim.\n          - apply trapin_sim.\n          - apply trapout_sim.\n          - apply hostin_sim.\n          - apply hostout_sim.\n          - apply trap_info_get_sim.\n          - apply trap_info_ret_sim.\n          - layer_sim_simpl.\n            + eapply load_correct2.\n            + eapply store_correct2.\n        Qed.\n\n      End PASSTHROUGH_PRIM.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\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/KContextGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.1679243972238212}}
{"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 ch2o.axiomatic.axiomatic_expressions.\nRequire Export ch2o.axiomatic.axiomatic_statements.\nRequire Export ch2o.axiomatic.axiomatic_adequate.\nRequire Export one_local.\n\nDefinition get_right{A B}(v: A + B)(H: match v with inl _ => False | inr _ => True end): B.\ndestruct v.\nelim H.\nexact b.\nDefined.\n\nOpen Local Scope string_scope.\n\nDefinition A: architecture := {|\n  arch_sizes := architectures.lp64;\n  arch_big_endian := false;\n  arch_char_signedness := Signed;\n  arch_alloc_can_fail := false\n|}.\nNotation K := (arch_rank A).\n\nNotation M := (error (frontend_state K) string).\n\nLemma alloc_program_ok: match alloc_program (K:=K) decls empty with inl _ => False | inr _ => True end.\nexact I.\nQed.\n\nDefinition alloc_program_result: frontend_state K.\neapply snd.\neapply get_right.\napply alloc_program_ok.\nDefined.\n\nCompute (stringmap_to_list (env_t (to_env alloc_program_result))).\nCompute (stringmap_to_list (env_f (to_env alloc_program_result))).\n\nDefinition to_core_c_program: M (env K * funenv K * state K) :=\n  _ \u2190 alloc_program decls;\n  \u0394g \u2190 gets to_globals;\n  '(_,\u03c3s,\u03c3,_) \u2190 error_of_option (\u0394g !! \"main\"\u226b= maybe4 Fun)\n    (\"function `main` undeclared`\");\n  guard (\u03c3 = sintT%T \u2228 \u03c3 = uintT%T) with\n    (\"function `main` should have return type `int`\");\n  \u0393 \u2190 gets to_env;\n  \u03b4 \u2190 gets to_funenv;\n  m \u2190 gets to_mem;\n  mret (\u0393, \u03b4, 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 \u2205.\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 \u0393: env K := to_env alloc_program_result.\nDefinition \u03b4: 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 \u0393_valid: \u2713 \u0393.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma \u03b4_valid: \u2713{\u0393,'{m0}} \u03b4.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma m0_valid: \u2713{\u0393} m0.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma mem_lock_cmap (\u0393: env K) o (m: indexmap (cmap_elem K (pbit K))):\n  mem_lock \u0393 (addr_top o sintT%BT) (CMap m) =\n  CMap (alter (cmap_elem_map (ctree_map pbit_lock)) o m).\nreflexivity.\nQed.\n\nLemma zip_with_pbit_unlock_if_list_fmap_pbit_lock (l: list (pbit K)):\n  Forall (\u03bb \u03b3b, Some Writable \u2286 pbit_kind \u03b3b) l ->\n  zip_with pbit_unlock_if (pbit_lock <$> l) (replicate (Datatypes.length l) true) = l.\ninduction l; intros; try reflexivity.\nsimpl.\nunfold fmap in IHl.\nrewrite IHl.\n- destruct a.\n  simpl.\n  inversion H; subst.\n  destruct tagged_perm.\n  + destruct l0; simpl in *.\n    * unfold perm_kind in H2.\n      elim H2.\n    * reflexivity.\n  + elim H2.\n- inversion H; subst; assumption.\nQed.\n\nLemma mem_unlock_lock_singleton (\u0393: env K) o (m: mem K):\n  \u2713{\u0393} m ->\n  '{m} !! o = Some (sintT%T, false) ->\n  mem_writable \u0393 (addr_top o sintT%BT) m ->\n  mem_unlock\n    (lock_singleton \u0393 (addr_top o sintT%BT))\n    (mem_lock \u0393 (addr_top o sintT%BT) m) = m.\ndestruct m as [m].\nintros Hvalid. intros.\ndestruct Hvalid as [Hvalid1 [Hvalid2 Hvalid3]].\nsimpl in *.\nassert (forall (m1: indexmap (cmap_elem K (pbit K))) m2, m1 = m2 -> CMap m1 = CMap m2). { intros; congruence. }\napply H1.\napply map_eq.\nintro i.\nrewrite lookup_merge.\n2:reflexivity.\ndestruct (decide (i = o)).\n- subst.\n  rewrite lookup_singleton.\n  rewrite lookup_alter.\n  destruct H0 as [w [Hw H'w]].\n  simpl in *.\n  unfold cmap_lookup in Hw.\n  simpl in Hw.\n  case_eq (m !! o); intros; rewrite H0 in Hw; try discriminate.\n  destruct c; try discriminate.\n  simpl in Hw.\n  injection Hw; clear Hw; intros; subst.\n  simpl.\n  rewrite lookup_fmap in H.\n  rewrite H0 in H.\n  simpl in H.\n  injection H; clear H; intros; subst.\n  destruct w; try discriminate.\n  destruct b0; try discriminate.\n  destruct i; try discriminate.\n  simpl in H.\n  injection H; clear H; intros; subst.\n  clear H1.\n  simpl.\n  pose proof H0.\n  apply Hvalid3 in H0.\n  destruct H0 as [\u03c4 [Ho1 [Ho2 [Ho3 Ho4]]]].\n  simpl in *.\n  unfold typed in Ho1.\n  unfold index_typed in Ho1.\n  destruct Ho1 as [\u03b2 Ho1].\n  rewrite lookup_fmap in Ho1.\n  rewrite H in Ho1.\n  simpl in Ho1.\n  injection Ho1; clear Ho1; intros; subst.\n  simpl in Ho3.\n  unfold typed in Ho3.\n  unfold ctree_typed in Ho3.\n  simpl in Ho3.\n  inversion Ho3; subst.\n  rewrite fmap_length.\n  assert (Datatypes.length l = 32). {\n    rewrite H4.\n    reflexivity.\n  }\n  rewrite H0.\n  assert (natmap.to_bools 32\n              {|\n              mapset.mapset_car := natmap.list_to_natmap\n                                     [Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some ()] |} =\n    [true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true]).\n  reflexivity.\n  rewrite H1.\n  pose proof (zip_with_pbit_unlock_if_list_fmap_pbit_lock l H'w).\n  rewrite H0 in H5.\n  simpl in H5.\n  rewrite H5.\n  reflexivity.\n- rewrite lookup_singleton_ne; try congruence.\n  rewrite lookup_alter_ne; try congruence.\nQed.\n\nLemma lockset_union_right_id (\u03a9: lockset): \u03a9 \u222a \u2205 = \u03a9.\napply lockset_eq.\nintros.\nsolve_elem_of.\nQed.\n\nLemma cons_snoc0 {A} x (xs: list A): exists y ys, x::xs = (ys ++ [y])%list.\nrevert x.\ninduction xs.\n- intros.\n  exists x.\n  exists [].\n  reflexivity.\n- intros.\n  destruct (IHxs a) as [y [ys Hyys]].\n  rewrite Hyys.\n  exists y.\n  exists (x::ys).\n  reflexivity.\nQed.\n\nLemma expr_eval_pure (\u0393: env K) \u03c1 e1 m e2 m2 (E: ectx K) \u03bd:\n  \u0393\\ \u03c1 \u22a2\u2095 e1, m \u21d2 e2, m2 ->\n  \u27e6 subst E e1 \u27e7 \u0393 \u03c1 m = Some \u03bd ->\n  m2 = m.\nintros.\napply expr_eval_subst in H0.\ndestruct H0 as [\u03bd' [H\u03bd' _]].\napply symmetry.\napply ehstep_expr_eval_mem with (1:=H) (2:=H\u03bd').\nQed.\n\nLemma expr_eval_complete_subst (\u0393: env K) \u03c1 e1 m e2 m2 (E: ectx K) \u03bd:\n  \u0393\\ \u03c1 \u22a2\u2095 e1, m \u21d2 e2, m2 ->\n  \u27e6 subst E e1 \u27e7 \u0393 \u03c1 m = Some \u03bd ->\n  \u27e6 subst E e2 \u27e7 \u0393 \u03c1 m = Some \u03bd.\nintros.\npose proof H0.\napply expr_eval_subst in H0.\ndestruct H0 as [\u03bd' [H\u03bd' _]].\nassert (m = m2). {\n  apply ehstep_expr_eval_mem with (1:=H) (2:=H\u03bd').\n}\nsubst m2.\nassert (\u27e6 e2 \u27e7 \u0393 \u03c1 m = Some \u03bd'). {\n  apply ehstep_expr_eval with (1:=H) (2:=H\u03bd') (3:=H\u03bd').\n}\nrewrite subst_preserves_expr_eval with (e4:=e2) in H1.\n- assumption.\n- congruence.\nQed.\n\nLemma expr_eval_call_None {\u0393: env K} {\u03c1 m} {E: ectx K} {f args \u03bd}:\n  \u27e6 subst E (ECall f args) \u27e7 \u0393 \u03c1 m = Some \u03bd -> False.\nintros.\napply expr_eval_subst in H.\ndestruct H.\ndestruct H.\nsimpl in H.\ndiscriminate.\nQed.\n\nLemma expr_eval_no_locks (\u0393: env K) \u03c1 m \u03a9 \u03bd \u03bd':\n  \u27e6 %#{\u03a9} \u03bd \u27e7 \u0393 \u03c1 m = Some \u03bd' -> (%#{\u03a9} \u03bd = %# \u03bd')%E.\nintros.\nsimpl in H.\nunfold mguard in H.\nunfold option_guard in H.\ndestruct (lockset_eq_dec \u03a9 \u2205); congruence.\nQed.\n\nLemma assign_pure (\u0393: env K) \u03b4 \u03c1 S0 S:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b S0 \u21d2* S ->\n  is_undef_state S ->\n  forall k el er m \u03bdl \u03bdr,\n  S0 = State k (Expr (el ::= er)) m ->\n  \u27e6 el \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdl ->\n  \u27e6 er \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdr ->\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bdl ::= %# \u03bdr)) m \u21d2* S.\ninduction 1; intros; subst. {\n  elim (is_Some_None H).\n}\ninversion H; clear H; subst.\n- (* head reduction *)\n  destruct E.\n  + (* empty evaluation context *)\n    simpl in *.\n    subst.\n    inversion H8; subst.\n    simpl in *.\n    unfold mguard in H4.\n    unfold option_guard in H4.\n    case_eq (lockset_eq_dec \u03a92 \u2205); intros.\n    * rewrite H in H4.\n      injection H4; clear H4; intros; subst.\n      unfold mguard in H3; unfold option_guard in H3.\n      case_eq (lockset_eq_dec \u03a91 \u2205); intros.\n      -- rewrite H2 in H3.\n         injection H3; clear H3; intros; subst.\n         clear H H2.\n         eapply rtc_l.\n         ++ eapply rcstep_expr_head with (E:=[]).\n            eassumption.\n         ++ eassumption.\n      -- rewrite H2 in H3; discriminate.\n    * rewrite H in H4; discriminate.\n  + (* nonempty evaluation context *)\n    destruct (cons_snoc0 e E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate.\n    * (* lhs *)\n      simpl in H6.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H3).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H3.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n    * (* rhs *)\n      simpl in *.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H4).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H4.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n- (* function call *)\n  destruct E.\n  + (* E = [] *)\n    simpl in *.\n    discriminate.\n  + destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate; simpl in *; injection H6; clear H6; intros; subst.\n    * (* lhs *)\n      elim (expr_eval_call_None H3).\n    * (* rhs *)\n      elim (expr_eval_call_None H4).\n- (* undef *)\n  destruct E.\n  * (* E = [] *)\n    simpl in *.\n    subst.\n    eapply rtc_l.\n    2: eassumption.\n    inversion H8; subst.\n    destruct H5.\n    destruct H7.\n    rewrite expr_eval_no_locks with (1:=H3) in *.\n    rewrite expr_eval_no_locks with (1:=H4) in *.\n    apply rcstep_expr_undef with (E:=[]).\n    -- assumption.\n    -- assumption.\n  * (* E <> [] *)\n    destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H5.\n    destruct e'; try discriminate; simpl in *; injection H5; clear H5; intros; subst.\n    -- (* lhs *)\n       destruct expr_eval_subst_ehstep with (1:=H3) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\n    -- (* rhs *)\n       destruct expr_eval_subst_ehstep with (1:=H4) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\nQed.\n\nLemma assign_pure' (\u0393: env K) \u03b4 \u03c1 S k el er m \u03bdl \u03bdr:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b (State k (Expr (el ::= er)) m) \u21d2* S ->\n  \u27e6 el \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdl ->\n  \u27e6 er \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdr ->\n  (\u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bdl ::= %# \u03bdr)) m \u21d2* S ->\n   \u00ac is_undef_state S) ->\n  \u00ac is_undef_state S.\nintros.\nintro.\napply H2 with (2:=H3).\napply assign_pure with (1:=H) (2:=H3) (4:=H0) (5:=H1).\nreflexivity.\nQed.\n\nLemma Expr_pure (\u0393: env K) \u03b4 \u03c1 S0 S:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b S0 \u21d2* S ->\n  is_undef_state S ->\n  forall k e m \u03bd,\n  S0 = State k (Expr e) m ->\n  \u27e6 e \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bd ->\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* S.\nintro Hrtc.\npose proof Hrtc.\ninduction H; intros; subst. {\n  elim (is_Some_None H).\n}\nassert (forall \u03a9 \u03bd', e = (%#{\u03a9} \u03bd')%E -> \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* z). {\n  intros.\n  subst.\n  simpl in H3.\n  unfold mguard in H3.\n  unfold option_guard in H3.\n  destruct (lockset_eq_dec \u03a9 \u2205).\n  2: discriminate.\n  injection H3; clear H3; intros; subst.\n  assumption.\n}\nclear Hrtc.\ninversion H; clear H; subst; try (eapply H2; reflexivity); clear H2.\n- (* head reduction *)\n  assert (m2 = m). {\n    apply expr_eval_pure with (1:=H8) (2:=H3).\n  }\n  subst m2.\n  eapply IHrtc; try trivial.\n  apply expr_eval_complete_subst with (1:=H8) (2:=H3).\n- (* function call *)\n  elim (expr_eval_call_None H3).\n- elim H9.\n  eapply expr_eval_subst_ehsafe; eassumption.\nQed.\n\nLemma Expr_pure' (\u0393: env K) \u03b4 \u03c1 S k e m \u03bd:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b (State k (Expr e) m) \u21d2* S ->\n  \u27e6 e \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bd ->\n  (\u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* S ->\n   \u00ac is_undef_state S) ->\n  \u00ac is_undef_state S.\nintros.\nintro.\napply H1.\n2: assumption.\napply Expr_pure with (1:=H) (2:=H2) (4:=H0).\nreflexivity.\nQed.\n\nDefinition safe S0: Prop := forall S, rtc (cstep \u0393 \u03b4) S0 S -> ~ is_undef_state S.\n\nLemma call_safe_lemma: forall f s,\n  \u03b4 !! f = Some s ->\n  safe (State [] (Stmt \u2198 s) \u2205) ->\n  safe (State [] (Call f []) \u2205).\nAdmitted.\n\nRequire Export ch2o.axiomatic.axiomatic_simple.\n\nLemma call_main_safe: safe (State [] (Call \"main\" []) \u2205).\neapply call_safe_lemma. reflexivity.\nassert ((intT (to_inttype\n                        {|\n                        csign := None;\n                        crank := CIntRank |}))%BT = (sintT%BT : base_type K)). reflexivity.\nrewrite H; clear H.\nassert (IntType (from_option Signed (Some Signed)) int_rank = (sintT%IT: int_type K)). reflexivity.\nrewrite H; clear H.\nintros S HS1 HS2.\ndestruct ax_stmt_adequate with (7:=HS1) (Q:=fun (v: val K) => True%A) (cm\u03c4:=((true, Some sintT%T): rettype K)) as [[n' [m' [Had1 Had2]]] | [[n' [m' [v [Had1 Had2]]]] | Had3]].\nFocus 7. {\n  subst. elim (is_Some_None HS2).\n} Unfocus.\nFocus 7. {\n  subst. elim (is_Some_None HS2).\n} Unfocus.\nFocus 7. {\n  inversion Had3.\n  destruct S as [k [] m]; try elim (is_Some_None HS2).\n  inversion H.\n} Unfocus.\n{ apply \u0393_valid. }\n{ apply \u03b4_valid. }\n{ apply m0_valid. }\n{ apply mem_locks_empty. }\n{ apply type_check_sound.\n  - simpl. apply \u0393_valid.\n  - reflexivity.\n}\nclear S HS1 HS2.\napply ax_local.\nassert ((assert_eq_mem (cmap_erase \u2205)\u2191)%A \u2286{\u0393,\u03b4} (emp%A: assert K)). {\n  rewrite cmap_erase_empty.\n  unfold subseteqE.\n  unfold assert_entails.\n  intros.\n  unfold assert_eq_mem in H5.\n  unfold assert_Prop.\n  simpl in *.\n  tauto.\n}\neapply ax_stmt_weaken_pre. {\n  rewrite H.\n  rewrite (right_id _ (\u2605)%A).\n  reflexivity.\n}\nassert (Inhabited (ptr K)). {\n  constructor.\n  apply NULL.\n  constructor.\n  apply (sintT%T).\n}\neapply ax_comp.\n- eapply ax_do' with\n     (Q:=(var 0 \u21a6{false,perm_lock perm_full} (# intV{sintT} 3) : sintT%BT)%A)\n     (Q':=(var 0 \u21a6{false,perm_full} (# intV{sintT} 3) : sintT%BT)%A).\n  + eapply ax_expr_weaken_pre. {\n      rewrite assert_singleton_l_.\n      reflexivity.\n    }\n    apply ax_expr_exist_pre.\n    intro x.\n    eapply ax_expr_weaken_post'. {\n      apply assert_singleton_l_2 with (a:=x).\n    }\n    eapply ax_expr_invariant_l'.\n    eapply ax_assign_r' with (p:=x).\n    * apply ax_var'.\n      rewrite (right_id _ (\u2605)%A).\n      rewrite (right_id _ (\u2605)%A).\n      apply assert_and_l.\n    * eapply ax_cast'.\n      -- eapply ax_expr_base.\n         eapply assert_and_intro.\n         Focus 2. {\n           apply assert_int_typed_eval.\n           constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n         } Unfocus.\n         simpl.\n         rewrite assert_Prop_l.\n         ++ reflexivity.\n         ++ reflexivity.\n      -- apply assert_eval_int_cast_self'.\n         apply assert_int_typed_eval.\n         constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n    * simpl.\n      apply assert_and_intro.\n      -- apply assert_eval_int_cast_self'.\n         apply assert_int_typed_eval.\n         constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n      -- apply assert_eval_int_cast_self'.\n         apply assert_int_typed_eval.\n         constructor; (unfold int_lower || unfold int_upper); simpl; lia.\n    * simpl (freeze true _).\n      rewrite <- (right_id _ (\u2605)%A) at 1.\n      apply assert_sep_preserving.\n      -- reflexivity.\n      -- apply assert_wand_intro.\n         rewrite (left_id _ (\u2605)%A).\n         reflexivity.\n    * reflexivity.\n  + apply assert_lock_singleton.\n    * apply perm_full_valid.\n    * reflexivity.\n- apply ax_ret with (Q1:=(fun _ => var 0 \u21a6{false, perm_full} # intV{sintT} 3 : sintT%BT)%A).\n  + intros.\n    rewrite <- assert_unlock_sep.\n    rewrite stack_indep.\n    rewrite <- unlock_indep.\n    rewrite <- (right_id _ (\u2605)%A) at 1.\n    apply assert_sep_preserving. 2:apply assert_True_intro.\n    rewrite assert_unlock_exists.\n    apply assert_exist_intro with (x:=intV{sintT} 3).\n    apply assert_singleton_unlock_indep.\n    reflexivity.\n  + eapply ax_expr_base.\n    apply assert_and_intro.\n    * reflexivity.\n    * rewrite <- assert_eval_int_cast.\n      -- apply assert_singleton_eval.\n         reflexivity.\n      -- constructor; (unfold int_lower || unfold int_upper); simpl; lia.\nQed.\n\nGoal forall S, rtc (cstep \u0393 \u03b4) S0 S -> ~ is_undef_state S.\nintros.\napply call_main_safe with (1:=H).\nQed.\n", "meta": {"author": "btj", "repo": "proofs-against-ch2o", "sha": "e7005477b916836d4243c43fbc939111af86446e", "save_path": "github-repos/coq/btj-proofs-against-ch2o", "path": "github-repos/coq/btj-proofs-against-ch2o/proofs-against-ch2o-e7005477b916836d4243c43fbc939111af86446e/one_local_proof_sl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.1676733103651588}}
{"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.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.StringFacts\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedSumType\n        Fiat.Narcissus.BinLib.AlignedDomainName\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.Compose\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.SimpleDNSPacket\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.HintDbExtra\n        Fiat.Common.Tactics.TransparentAbstract\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Stores.DomainNameStore\n        Fiat.Narcissus.Automation.CacheEncoders.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  Local Open Scope Tuple_scope.\n  Import Vectors.VectorDef.VectorNotations.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n  Arguments NPeano.div : simpl never.\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (As := ResourceRecordTypeTypes)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n      (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))\n      (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n      (SumType_proj ResourceRecordTypeTypes rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                            (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    intros ? H; apply H.\n  Qed.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Definition DNS_Packet_OK (data : packet) :=\n    lt (|data!\"answers\" |) (pow2 16)\n    /\\ lt (|data!\"authority\" |) (pow2 16)\n    /\\ lt (|data!\"additional\" |) (pow2 16)\n    /\\ ValidDomainName (data!\"question\")!\"qname\"\n    /\\ forall (rr : resourceRecord),\n        In rr (data!\"answers\" ++ data!\"additional\" ++ data!\"authority\")\n        -> resourceRecord_OK rr.\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n  Definition format_SOA_RDATA (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_A (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata r!sRDATA\n                           DoneC.\n\n  Definition format_packet (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Arguments split1 : simpl never.\n  Arguments split2 : simpl never.\n  Arguments fin_eq_dec m !n !n' /.\n  Arguments addE : simpl never.\n\n  Arguments Vector.nth A !m !v' !p /.\n\n  Definition format_rdata' :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource' (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           DoneC.\n\n  Definition format_packet' (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource' (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Definition refine_format_CNAME\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p,\n                  ValidDomainName p\n                  -> refine (format_CNAME p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_CNAME.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n    eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_A\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               refine (format_A p list_CacheFormat_empty)\n                                      (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_A.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    simpl.\n    encoder_reflexivity.\n  Defined.\n  Unset Printing Notations.\n\n  Eval compute in (natToWord 8 128).\n\n  Definition refine_format_NS\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               ValidDomainName p\n                               -> refine (format_NS p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_NS.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_SOA\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall a : SOA_RDATA,\n                               ValidDomainName a!\"contact_email\"\n                               -> ValidDomainName a!\"sourcehost\"\n                               -> refine (format_SOA_RDATA a list_CacheFormat_empty)\n                                         (ret (@build_aligned_ByteString (numBytes a) (v a), c a)) } } }.\n  Proof.\n    unfold format_SOA_RDATA.\n    eexists _, _, _; intros.\n    pose_string_hyps.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_resource\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p\n                             (p_OK : resourceRecord_OK p)\n                             ce,\n            refine (format_resource p ce)\n                   (ret (@build_aligned_ByteString (numBytes p ce) (v p ce), c p ce)) } } }.\n  Proof.\n    unfold format_resource; eexists _, _, _; intros.\n    etransitivity.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply (AlignedFormatSumTypeDoneC); repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME;\n      build_prim_prod_evar;\n      build_prim_prod_evar; simpl;\n      etransitivity;\n      [apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus;\n       eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption\n       | encoder_reflexivity].\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      unfold SumType_proj in H; simpl in H.\n      revert H; instantiate (1 := fun t => _ t /\\ _ t); intros [? ?].\n      pattern t; apply H.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      pattern t; apply (proj2 H).\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { apply p_OK. }\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    eapply (projT2 (projT2 (projT2 refine_format_resource))); eauto.\n    apply p_OK; assumption.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).\nSet Printing Notations.\nPrint encode_packet.\n\n(*  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    unfold format_resource; intros.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply H.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply AlignedFormatSumTypeDoneC; repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME.\n      build_prim_prod_evar.\n      build_prim_prod_evar; simpl.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n      eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n      encoder_reflexivity.\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold resourceRecord_OK in H.\n      eapply H.\n    }\n    apply p_OK; apply H.\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).v *)\n\nLemma refine_format_packet_Impl_OK\n  : forall p (p_OK : DNS_Packet_OK p),\n    refine (format_packet p list_CacheFormat_empty)\n           (ret (encode_packet p)).\nProof.\n  intros; apply (projT2 (projT2 (projT2 refine_format_packet))); eauto.\nQed.\n\n  Definition ByteAlignedCorrectDecoderFor {A} {cache : Cache}\n             Invariant FormatSpec :=\n    { decodePlusCacheInv |\n      exists P_inv,\n      (cache_inv_Property (snd decodePlusCacheInv) P_inv\n       -> CorrectDecoder (A := A) monoid Invariant (fun _ _ => True)\n                                  FormatSpec\n                                  (fst decodePlusCacheInv)\n                                  (snd decodePlusCacheInv))\n      /\\ cache_inv_Property (snd decodePlusCacheInv) P_inv}.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments weq : simpl never.\n  Arguments word_indexed : simpl never.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct\n                IndependentCaches IndependentCaches' IndependentCaches'''\n                getDistinct getDistinct' addPeekSome\n                boundPeekSome addPeekNone addPeekNone'\n                addZeroPeek addPeekESome boundPeekESome\n                addPeekENone addPeekENone')\n    | |- appcontext [CorrectDecoder _ _ _ (format_list format_resource) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Ltac synthesize_decoder_ext\n       monoid\n       decode_step'\n       determineHooks\n       synthesize_cache_invariant' :=\n    (* Combines tactics into one-liner. *)\n    start_synthesizing_decoder;\n    [ normalize_compose monoid;\n      repeat first [decode_step' idtac | decode_step determineHooks]\n    | cbv beta; synthesize_cache_invariant' idtac\n    |  ].\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n    unfold resourceRecord_OK.\n    clear; intros.\n    split.\n    apply (Logic.proj1 H).\n    admit.\n\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    (*destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *. *)\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n    simpl.\n    instantiate (1 := true).  admit.\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *.\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n\n    simpl; intros;\n      repeat (try rewrite !DecodeBindOpt2_assoc;\n              try rewrite !Bool.andb_true_r;\n              try rewrite !Bool.andb_true_l;\n              try rewrite !optimize_if_bind2;\n              try rewrite !optimize_if_bind2_bool).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite !DecodeBindOpt2_assoc.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Then_Else_Bind (cache := dns_list_cache)).\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    higher_order_reflexivity.\n    set_refine_evar.\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    unfold H; higher_order_reflexivity.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    (* collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus. *)\n    simpl.\n    higher_order_reflexivity.\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Definition packetDecoderImpl\n    := Eval simpl in (projT1 packet_decoder).\n\n  (*Arguments Guarded_Vector_split : simpl never.\n\n  Arguments addD : simpl never.\n\n  Arguments Core.append_word : simpl never.\n  Arguments Vector_split : simpl never.\n  Arguments NPeano.leb : simpl never.\n\n  Definition If_Opt_Then_Else_map\n             {A B B'} :\n    forall (f : option B -> B')\n           (a_opt : option A)\n           (t : A -> option B)\n           c,\n      f (Ifopt a_opt as a Then t a Else c) =\n      Ifopt a_opt as a Then f (t a) Else (f c).\n  Proof.\n    destruct a_opt as [ a' | ]; reflexivity.\n  Qed.\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n      Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Definition ByteAligned_packetDecoderImpl {A}\n             (f : _ -> A)\n             n\n    : {impl : _ & forall (v : Vector.t _ (12 + n)),\n           f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n           impl v (Some (wzero 17) , @nil (pointerT * string))%list}.\n  Proof.\n    eexists _; intros.\n    etransitivity.\n    set_refine_evar; simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    eapply optimize_under_if_opt; simpl; intros.\n    rewrite BindOpt_map_if.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    rewrite BindOpt_map_if; unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    (* rewrite !DecodeBindOpt2_assoc. *)\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite byte_align_decode_DomainName.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    destruct a8 as [ [? [ ? ?] ] ? ]; simpl.\n    (*rewrite DecodeBindOpt2_assoc. *)\n    etransitivity.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If NPeano.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (NPeano.leb n sz) eqn: ?.\n    - apply NPeano.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- NPeano.leb_le in H1; congruence.\n  Qed.\n\n    match goal with\n      |- ?b = _ =>\n      let b' := (eval pattern (build_aligned_ByteString t) in b) in\n      let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode x _ 4 b')\n    end.\n    { intros.\n      unfold decode_enum.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      destruct (Compare_dec.lt_dec x 2).\n      unfold Core.char in *.\n      pose proof (@decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2 p) as H';\n      unfold mult in H';  simpl in H'; rewrite H'; try reflexivity; auto.\n      destruct x as [ | [ | [ | ?] ] ]; try omega.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; reflexivity\n      end.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; simpl; try eauto\n      end.\n      repeat rewrite DecodeBindOpt2_assoc.\n      pose proof (fun x t => @decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2) as H';\n        simpl in H'; unfold mult in H; rewrite H'; try reflexivity; auto.\n      omega.\n    }\n    { intros; unfold decode_enum.\n      etransitivity.\n      set_refine_evar; repeat rewrite BindOpt_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      rewrite (AlignedDecode2Char (Guarded_Vector_split 4 x t)).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite (@If_Opt_Then_Else_DecodeBindOpt _ dns_list_cache); simpl.\n      rewrite If_Opt_Then_Else_map.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      erewrite optimize_align_decode_list.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      etransitivity.\n      eapply optimize_under_if_opt; simpl; intros.\n      rewrite BindOpt_map_if_bool.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      etransitivity.\n      set_refine_evar.\n      clear H0.\n      rewrite byte_align_decode_DomainName.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      subst_evars.\n      eapply optimize_under_if_opt; simpl; intros.\n      destruct a12 as [ [? [ ? ?] ] ? ]; simpl.\n      rewrite DecodeBindOpt2_assoc.\n      simpl.\n      etransitivity.\n      match goal with\n        |- ?b = _ =>\n        let b' := (eval pattern (build_aligned_ByteString t0) in b) in\n        let b' := match b' with ?f _ => f end in\n        eapply (@AlignedDecoders.optimize_Guarded_Decode x0 _ 8 b')\n      end.\n      { intros.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        etransitivity; set_refine_evar.\n        unfold DecodeBindOpt2, BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_refine_evar; eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        rewrite BindOpt_assoc.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        unfold BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        etransitivity.\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_evars.\n        eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        destruct x0 as [ | [| [ | [ | x0] ] ] ]; try omega.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n      }\n      intros; etransitivity.\n      simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt;rewrite (@AlignedDecode4Char dns_list_cache).\n      repeat (rewrite Vector_split_merge,\n              <- Eqdep_dec.eq_rect_eq_dec;\n              eauto using Peano_dec.eq_nat_dec ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      let types' := (eval unfold ResourceRecordTypeTypes in ResourceRecordTypeTypes)\n      in ilist_of_evar\n           (fun T : Type => forall n,\n                Vector.t (word 8) n\n                -> CacheDecode\n                -> option (T * {n : _ & Vector.t (word 8) n} * CacheDecode))\n           types'\n           ltac:(fun decoders' => rewrite (@align_decode_sumtype_OK dns_list_cache _ ResourceRecordTypeTypes decoders'));\n           [ | simpl; intros; repeat (apply Build_prim_and; intros); try exact I].\n      set_refine_evar.\n      rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n      simpl.\n      subst_refine_evar.\n      etransitivity.\n      subst_evars; higher_order_reflexivity.\n      subst_evars; higher_order_reflexivity.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (@decode_unused_word_aligned_ByteString_overflow dns_list_cache _ _ v1 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x=> @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          unfold DecodeBindOpt2 at 1; rewrite (@AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus _ _ 2).\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 := fun n1 v1 cd0 =>  If  NPeano.leb 2 n1\n                                                Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                                                (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                                                (addD cd0 16) as p1\n                                                                   Then let (p2, cd') := p1 in\n                                                                        let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                                    Else None;\n                                                                                               Some (proj, rest, env') Else None); simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        simpl.\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 6 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          simpl.\n          unfold DecodeBindOpt2 at 1;\n          pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          destruct n1 as [ | [ | [ | [ | n1] ] ] ] ; try omega;\n            try reflexivity.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache); simpl.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        repeat (rewrite Vector_split_merge,\n                <- Eqdep_dec.eq_rect_eq_dec;\n                eauto using Peano_dec.eq_nat_dec ).\n        unfold mult; simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0\n                       => If NPeano.leb 6 n1\n                             Then Let n2 := Core.append_word\n                                              (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                               Fin.FS (Fin.FS (Fin.FS Fin.F1))]\n                                              (Core.append_word\n                                                 (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                  Fin.FS (Fin.FS Fin.F1)]\n                                                 (Core.append_word\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                     Fin.FS Fin.F1]\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@Fin.F1])) in\n                           Some\n                             (n2, existT _ _ (snd (Vector_split (2 + 4) (n1 - 6) (Guarded_Vector_split 6 n1 v1))),\n                              addD (addD cd0 16) 32) Else None).\n        simpl; find_if_inside; simpl; eauto.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0 =>\n                         If  NPeano.leb 2 n1\n                             Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                             (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                             (addD cd0 16) as p1\n                                                Then let (p2, cd') := p1 in\n                                                     let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                 Else None;\n                                                                            Some (proj, rest, env') Else None).\n        simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      Arguments plus : simpl never.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1;pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          etransitivity.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          etransitivity.\n          match goal with\n            |- ?b = _ =>\n            let b' := (eval pattern (build_aligned_ByteString t2) in b) in\n            let b' := match b' with ?f _ => f end in\n            eapply (@AlignedDecoders.optimize_Guarded_Decode x2 _ 20 b')\n          end.\n          { subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ]; try omega.\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n          }\n          { intros.\n            etransitivity.\n            unfold plus.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            unfold plus.\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            repeat (rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec ).\n            higher_order_reflexivity.\n            higher_order_reflexivity.\n          }\n          Opaque If_Opt_Then_Else.\n          Opaque If_Then_Else.\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          subst_evars; reflexivity.\n          Opaque Core.append_word.\n          Opaque Guarded_Vector_split.\n          Opaque Vector.tl.\n          simpl.\n\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          Transparent If_Opt_Then_Else.\n          Transparent If_Then_Else.\n          simpl.\n          subst_refine_evar; reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        fold (plus 20 (n1 - 20)).\n        fold (plus 16 (n1 - 16)).\n        fold (plus 12 (n1 - 12)).\n        fold (plus 8 (n1 - 8)).\n        fold (plus 4 (n1 - 4)).\n        match goal with\n          |- context [S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S ?n)))))))))))))))] => fold (plus 16 n)\n        end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd in b) in\n          let b' := match b' with ?f _ _ _ => f end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If (b' n v cd) Then (et n v cd) Else (zt n v cd)); cbv beta; simpl; find_if_inside; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd in a) in\n          let a' := match a' with ?f _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                                    (zt n v cd)\n                                                                                    (et n v cd));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd ?a'' as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd, a'' in a) in\n          let a' := match a' with ?f _ _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let AT'' := match type of a'' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd a'' => If_Opt_Then_Else (a' n v cd a'')\n                                                                                        (zt n v cd a'')\n                                                                                        (et n v cd a''));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd, q, q' in b) in\n          let b' := match b' with ?f _ _ _ _ _ => f end in\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd q q' => If (b' n v cd q q') Then (et n v cd q q') Else (zt n v cd q q')); cbv beta; simpl; find_if_inside; simpl)) end.\n        clear H H1.\n        Opaque LetIn.\n        match goal with\n          |- _ =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n          let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n          let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n          makeEvar (forall n, Vector.t (word 8) n ->\n                              CacheDecode -> QT -> QT' ->\n                              word 32 -> word 32 ->\n                              word 32 -> word 32 -> ZT1)\n                   ltac:(fun zt1 =>\n                           makeEvar (forall n, Vector.t (word 8) n ->\n                                               CacheDecode -> QT -> QT' ->\n                                               word 32 -> word 32 ->\n                                               word 32 -> word 32 -> ZT2)\n                                    ltac:(fun zt2 =>\n                                            makeEvar (forall n, Vector.t (word 8) n ->\n                                                                CacheDecode -> QT -> QT' ->\n                                                                word 32 -> word 32 ->\n                                                                word 32 -> word 32 -> ZT3)\n                                                     ltac:(fun zt3 =>\n                                                             makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                 CacheDecode -> QT -> QT' -> word 32)\n                                                                      ltac:(fun w1 =>\n                                                                              makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                  CacheDecode -> QT -> QT' -> word 32)\n                                                                                       ltac:(fun w2 =>\n                                                                                               makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                   CacheDecode -> QT -> QT' -> word 32)\n                                                                                                        ltac:(fun w3 => makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                                            CacheDecode -> QT -> QT' -> word 32)\n                                                                                                                                 ltac:(fun w4 =>\n                                                                                                                                         unify z (fun n v cd q q' => LetIn (w1 n v cd q q') (fun w => LetIn (w2 n v cd q q')  (fun w' => LetIn (w3  n v cd q q') (fun w'' => LetIn (w4 n v cd q q') (fun w''' => Some (zt1 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt2 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt3 n v cd q q' w w' w'' w'''\n                                                                                                                                                 )))))); simpl)))))))\n        end.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        repeat f_equal.\n        higher_order_reflexivity.\n        instantiate (1 := fun n1 v1 cd0 p1 p2 x1 x2 x3 x4 => existT _ _ _).\n        simpl; reflexivity.\n        higher_order_reflexivity.\n        instantiate (1 := fun _ _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n      }\n      subst_refine_evar; reflexivity.\n      subst_refine_evar; reflexivity.\n      higher_order_reflexivity.\n      match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n      higher_order_reflexivity.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd in a) in\n        let a' := match a' with ?f _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                 (zt n v cd)\n                                                                 (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n      match goal with\n        |- If ?b Then ?t Else ?e =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => If (b' n v cd q) Then (zt n v cd q) Else (@None ZT)); cbv beta; simpl; find_if_inside; simpl)\n      end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => LetIn (b' n v cd q) (zt n v cd q)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q' in a) in\n        let a' := match a' with ?f _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' => If_Opt_Then_Else (a' n v cd q q')\n                                                                      (zt n v cd q q')\n                                                                      (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'' in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' => LetIn (b' n v cd q q' q'') (zt n v cd q q' q'')))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q', q'', q''' in a) in\n        let a' := match a' with ?f _ _ _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' => If_Opt_Then_Else (a' n v cd q q' q'' q''')\n                                                                               (zt n v cd q q' q'' q''')\n                                                                               (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'', q''', r in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' r => LetIn (b' n v cd q q' q'' q''' r) (zt n v cd q q' q'' q''' r)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      Time match goal with\n             |- If_Opt_Then_Else ?a ?t ?e =\n                Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' as a Then _ Else _ =>\n             let a' := (eval pattern n, v, cd, q, q', q'', q''', r, r' in a) in\n             let a' := match a' with ?f _ _ _ _ _ _ _ _ _ => f end in\n             let AT := match type of a with option ?T => T end in\n             let QT := match type of q with ?T => T end in\n             let QT' := match type of q' with ?T => T end in\n             let QT'' := match type of q'' with ?T => T end in\n             let QT''' := match type of q''' with ?T => T end in\n             let RT := match type of r with ?T => T end in\n             let RT' := match type of r' with ?T => T end in\n             let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n             makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> RT' -> AT -> option ZT)\n                      ltac:(fun zt =>\n                              unify z (fun n v cd q q' q'' q''' r r'=> If_Opt_Then_Else (a' n v cd q q' q'' q''' r r')\n                                                                                        (zt n v cd q q' q'' q''' r r')\n                                                                                        (@None ZT));\n                                cbv beta; simpl; destruct a; simpl) end.\n      (* This unification takes four minutes :p*)\n\n      match goal with\n        |- _ =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' ?r'' as a Then _ Else _ =>\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let RT' := match type of r' with ?T => T end in\n        let RT'' := match type of r'' with ?T => T end in\n        let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n        let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n        let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n        makeEvar (forall n, Vector.t (word 8) n ->\n                            CacheDecode -> QT -> QT' ->\n                            QT'' -> QT''' -> RT -> RT' -> RT''\n                            -> ZT1)\n                 ltac:(fun zt1 =>\n                         makeEvar (forall n, Vector.t (word 8) n ->\n                                             CacheDecode -> QT -> QT' ->\n                                             QT'' -> QT''' -> RT -> RT' -> RT''\n                                             -> ZT2)\n                                  ltac:(fun zt2 =>\n                                          makeEvar (forall n, Vector.t (word 8) n ->\n                                                              CacheDecode -> QT -> QT' ->\n                                                              QT'' -> QT''' -> RT -> RT' -> RT''\n                                                              -> ZT3)\n                                                   ltac:(fun zt3 => unify z (fun n v cd q q' q'' q''' r r' r'' =>\n                                                                               Some (zt1 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt2 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt3 n v cd q q' q'' q''' r r' r''));\n                                                                    simpl))) end.\n      repeat f_equal; try higher_order_reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; higher_order_reflexivity.\n    }\n    { match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n    }\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    simpl.\n    higher_order_reflexivity.\n    Time Defined.\n\n  Check ByteAligned_packetDecoderImpl.\n  Definition ByteAligned_packetDecoderImpl' {A} (k : _ -> A) n :=\n    Eval simpl in (projT1 (ByteAligned_packetDecoderImpl k n)).\n\n  Lemma ByteAligned_packetDecoderImpl'_OK {A}\n    : forall (f : _ -> A) n (v : Vector.t _ (12 + n)),\n        f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n        ByteAligned_packetDecoderImpl' f n v (Some (wzero 17) , @nil (pointerT * string))%list.\n  Proof.\n    intros.\n    pose proof (projT2 (ByteAligned_packetDecoderImpl f n));\n      cbv beta in H.\n    rewrite H.\n    set (H' := (Some (wzero 17), @nil (pointerT * string))).\n    simpl.\n    unfold ByteAligned_packetDecoderImpl'.\n    reflexivity.\n  Qed. *)\n\nEnd DnsPacket.\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/DNS/SimpleDnsOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.16767331036515876}}
{"text": "Require Import CompCert.Behaviors.\nRequire Import CompCert.Smallstep.\nRequire Import Common.Definitions.\nRequire Import Common.Linking.\nRequire Import Common.CompCertExtensions.\nRequire Import Common.TracesInform.\nRequire Import Common.RenamingOption.\n\nRequire Import Source.Definability.\nRequire Import Source.DefinabilityEnd.\nRequire Import Source.Language.\nRequire Import Source.GlobalEnv.\nRequire Import Source.CS.\nRequire Import Intermediate.Machine.\nRequire Import Intermediate.CS.\nRequire Import Intermediate.RecompositionRel.\nRequire Import S2I.Compiler.\nRequire Import S2I.Definitions.\n\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection RSC_Section.\n  Variable p: Source.program.\n  Variable psz: {fmap Component.id -> nat}.\n  Variable p_compiled: Intermediate.program.\n  Variable Ct: Intermediate.program.\n\n  (* Some reasonable assumptions about our programs *)\n\n  Hypothesis domm_psz_intf: domm psz = domm (Source.prog_interface p).\n  Hypothesis well_formed_p : Source.well_formed_program p.\n  Hypothesis disciplined_p: Compiler.disciplined_program p.\n  Hypothesis good_Elocal_p: NoLeak.good_Elocal_usage_program p.\n  Hypothesis successful_compilation : Compiler.compile_program p psz = Some p_compiled.\n  Hypothesis well_formed_Ct : Intermediate.well_formed_program Ct.\n  Hypothesis linkability : linkable (Source.prog_interface p) (Intermediate.prog_interface Ct).\n  Hypothesis closedness :\n    Intermediate.closed_program (Intermediate.program_link p_compiled Ct).\n  Hypothesis mains : Intermediate.linkable_mains p_compiled Ct.\n\n  (* Main Theorem *)\n\n\n  (* [DynShare]\n     \n     - Maybe we can get rid of the disjunction \"... \\/ behavior_improves_blame beh\".\n     - And also we should (instead of program_behaves) directly use \n       does_prefix (Source.CS.sem (Source.program_link p Cs)) m' \n       Notice that does_prefix is the \"finite version\" of \"program_behaves\", i.e., it still\n       contains the cases of FTerminates and FGoesWrong.\n\n     * Because our current S2I compiler does not seem to refine any undef behavior,\n       we should be able to get rid of the blame disjunct.\n\n   *)\n\n  Theorem RSC:\n    forall t s,\n      Star (Intermediate.CS.CS.sem_non_inform (Intermediate.program_link p_compiled Ct))\n           (Intermediate.CS.CS.initial_machine_state\n              (Intermediate.program_link p_compiled Ct)\n           )\n           t\n           s\n      ->\n      exists Cs t' s' size_meta size_meta',\n      Source.prog_interface Cs = Intermediate.prog_interface Ct /\\\n      Source.well_formed_program Cs /\\\n      linkable (Source.prog_interface p) (Source.prog_interface Cs) /\\\n      Source.closed_program (Source.program_link p Cs) /\\\n      Star (Source.CS.CS.sem (Source.program_link p Cs))\n           (Source.CS.CS.initial_machine_state\n              (Source.program_link p Cs)\n           )\n           t'\n           s'\n      /\\\n      traces_shift_each_other_option size_meta size_meta' t t'.\n  Proof.\n    intros t s Hstar.\n\n    (* Some auxiliary results. *)\n    pose proof\n      Compiler.compilation_preserves_well_formedness well_formed_p successful_compilation\n      as well_formed_p_compiled.\n\n    assert (linkability_pcomp_Ct :\n              linkable (Intermediate.prog_interface p_compiled)\n                       (Intermediate.prog_interface Ct)).\n    {\n      assert (sound_interface_p_Ct : sound_interface (unionm (Source.prog_interface p)\n                                                             (Intermediate.prog_interface Ct)))\n        by apply linkability.\n      assert (fdisjoint_p_Ct : fdisjoint (domm (Source.prog_interface p))\n                                         (domm (Intermediate.prog_interface Ct)))\n        by apply linkability.\n      constructor;\n        apply Compiler.compilation_preserves_interface in successful_compilation;\n        now rewrite successful_compilation.\n    }\n\n    assert (exists t_inform,\n               Star\n                 (Intermediate.CS.CS.sem_inform\n                    (Intermediate.program_link p_compiled Ct))\n                 (Intermediate.CS.CS.initial_machine_state\n                    (Intermediate.program_link p_compiled Ct)\n                 )\n                 t_inform\n                 s\n               /\\ project_non_inform t_inform = t) as [t_inform [Hstarinform Hproj]].\n    {\n      by eapply Intermediate.CS.CS.star_sem_non_inform_star_sem_inform.\n    }\n\n    \n\n    (* definability *)\n    destruct (definability_with_linking\n                well_formed_p_compiled\n                well_formed_Ct\n                linkability_pcomp_Ct\n                closedness\n                Hstarinform)\n      as [P' [Cs [t' [s' [metadata_size\n         [Hsame_iface1 [Hsame_iface2\n         [Hmatching_mains_P'_p_compiled [Hmatching_mains_Cs_Ct\n                                           [well_formed_P' [well_formed_Cs [HP'Cs_closed [Hstar' [Ht_rel_t' [Hconst_map [good_P'_Cs [P'_Cs_disciplined P'_CS_good_Elocal]]]]]]]]]]]]]]]]].\n\n    assert (Source.linkable_mains P' Cs) as HP'Cs_mains.\n    { apply Source.linkable_disjoint_mains; trivial; congruence. }\n\n    \n    (* FCC *)\n\n    (* the definability output can be split in two programs *)\n    (* probably need partialize to obtain them *)\n\n    (* At this point, we compile P' and Cs and establish their basic properties. *)\n    \n    have well_formed_P'Cs : Source.well_formed_program (Source.program_link P' Cs).\n      rewrite -Hsame_iface1 -Hsame_iface2 in linkability_pcomp_Ct.\n      exact: Source.linking_well_formedness well_formed_P' well_formed_Cs linkability_pcomp_Ct.\n\n      assert (P'Cs_disciplined: disciplined_program (Source.program_link P' Cs)).\n      {\n        intros ? ? ? Hfind.\n        eapply P'_Cs_disciplined; eauto.\n      }\n      \n      assert (exists s' t'compiled P'Cs_sz P'_Cs_compiled,\n                 domm P'Cs_sz = domm (Source.prog_interface (Source.program_link P' Cs))\n                 /\\\n                 Compiler.compile_program (Source.program_link P' Cs) P'Cs_sz =\n                 Some P'_Cs_compiled\n                 /\\\n                 Star (Intermediate.CS.CS.sem_non_inform P'_Cs_compiled)\n                      (I.CS.initial_machine_state P'_Cs_compiled)\n                      t'compiled s'\n                 /\\\n                 traces_shift_each_other_option\n                   (uniform_shift 1)\n                   (uniform_shift 1)\n                   t'\n                   t'compiled\n             )\n        as [s'_compiled [t'compiled [P'Cs_sz [P'_Cs_compiled\n                                       [Hdomm_P'Cs_sz\n                                          [HP'_Cs_compiles\n                                             [HP'_Cs_compiled_star\n                                                Ht'_rel_t'compiled\n\n           ]]]]]]].\n      {\n        eapply Compiler.forward_simulation_star with (metasize := uniform_shift 1).\n        - assumption.\n        - assumption.\n        - exact P'Cs_disciplined.\n        - exact P'_CS_good_Elocal.\n        - exact Hstar'.\n      }\n\n\n    assert (P'_Cs_linkable:\n              linkable (Source.prog_interface P') (Source.prog_interface Cs)).\n    {\n      by rewrite Hsame_iface1 Hsame_iface2.\n    }\n\n    assert (exists P'sz Cssz,\n               unionm P'sz Cssz = P'Cs_sz \n           ) as [P'sz [Cssz Hunion]].\n    {\n      exists (filterm (fun k => fun=> k \\in domm (Source.prog_interface P')) P'Cs_sz).\n      exists (filterm (fun k => fun=> k \\in domm (Source.prog_interface Cs)) P'Cs_sz).\n      assert (G': unionm\n                    (filterm (T:=nat_ordType)\n                             (fun k : nat_ordType =>\n                                fun=> k \\in domm\n                                              (T:=nat_ordType)\n                                              (S:=Component.interface)\n                                              (Source.prog_interface P'))\n                             P'Cs_sz)\n                    (filterm (T:=nat_ordType)\n                             (fun k : nat_ordType =>\n                                fun=> k \\in domm\n                                              (T:=nat_ordType)\n                                              (S:=Component.interface)\n                                              (Source.prog_interface Cs))\n                             P'Cs_sz) = P'Cs_sz).\n      {\n        apply eq_fmap. intros x. rewrite unionmE !filtermE.\n        \n        destruct (P'Cs_sz x) eqn:e.\n        + simpl.\n          assert (G1: exists n, P'Cs_sz x = Some n) by eauto.\n          move : G1 => /dommP => G1.\n          rewrite Hdomm_P'Cs_sz domm_union in G1.\n          destruct (x \\in domm (Source.prog_interface P')) eqn:edomm; rewrite edomm;\n            simpl; auto.\n          assert (x \\in domm (Source.prog_interface Cs)).\n          {\n            rewrite in_fsetU in G1.\n            move : G1 => /orP => G1.\n            destruct G1 as [contra|G1]; [by rewrite edomm in contra | assumption].\n          }\n            by rewrite H.\n        + by simpl.\n      }\n      exact G'.\n    }\n\n    specialize (Compiler.well_formed_compilable _ P'sz well_formed_P') as\n        [P'_compiled HP'_compiles].\n\n    specialize (Compiler.well_formed_compilable _ Cssz well_formed_Cs) as\n        [Cs_compiled HCs_compiles].\n    rewrite -Hunion in HP'_Cs_compiles.\n\n    assert (Hrewr: compile_program (Source.program_link P' Cs) (unionm P'sz Cssz) =\n                   Some (Intermediate.program_link P'_compiled Cs_compiled)).\n    { by eapply Compiler.separate_compilation; eauto. }\n\n    rewrite HP'_Cs_compiles in Hrewr.\n    inversion Hrewr. subst.\n      \n        \n    pose proof Compiler.compilation_preserves_well_formedness well_formed_P' HP'_compiles\n      as well_formed_P'_compiled.\n    \n    pose proof Compiler.compilation_preserves_well_formedness well_formed_Cs HCs_compiles\n      as well_formed_Cs_compiled.\n\n\n    assert\n      (linkable\n         (Intermediate.prog_interface Cs_compiled)\n         (Intermediate.prog_interface P'_compiled))\n      as linkability'. {\n      eapply @Compiler.compilation_preserves_linkability with (p:=Cs) (c:=P'); eauto.\n      apply linkable_sym.\n      rewrite <- Hsame_iface1 in linkability_pcomp_Ct.\n      rewrite <- Hsame_iface2 in linkability_pcomp_Ct.\n      apply linkability_pcomp_Ct.\n    }\n    \n    rewrite Intermediate.program_linkC in HP'_Cs_compiled_star;\n       [| assumption |assumption | apply linkable_sym in linkability'; assumption].\n\n    (* intermediate composition *)\n    assert (Intermediate.prog_interface Ct = Intermediate.prog_interface Cs_compiled)\n      as Hctx_same_iface. {\n      symmetry. erewrite Compiler.compilation_preserves_interface.\n      - rewrite <- Hsame_iface2. reflexivity.\n      - eassumption.\n    }\n    (* rewrite Hctx_same_iface in HP_decomp. *)\n    assert (Intermediate.prog_interface p_compiled = Intermediate.prog_interface P'_compiled) as Hprog_same_iface. {\n      symmetry. erewrite Compiler.compilation_preserves_interface.\n      - apply Hsame_iface1.\n      - eassumption.\n    }\n    (* rewrite <- Hprog_same_iface in HCs_decomp. *)\n\n    assert (linkable (Intermediate.prog_interface p_compiled) (Intermediate.prog_interface Cs_compiled))\n      as linkability''.\n    {\n      unfold linkable. split; try\n        rewrite Hprog_same_iface;\n        apply linkable_sym in linkability';\n        now inversion linkability'.\n    }\n    assert (Intermediate.closed_program (Intermediate.program_link p_compiled Cs_compiled))\n      as HpCs_compiled_closed.\n    pose proof S2I.Definitions.matching_mains_equiv\n         _ _ _\n         Hmatching_mains_Cs_Ct\n         (Compiler.compilation_has_matching_mains well_formed_Cs HCs_compiles)\n         as Hctx_match_mains.\n    now apply (Intermediate.interface_preserves_closedness_r\n                 well_formed_p_compiled well_formed_Cs_compiled\n                 Hctx_same_iface linkability_pcomp_Ct closedness mains Hctx_match_mains); auto.\n    assert (Intermediate.well_formed_program (Intermediate.program_link p_compiled Cs_compiled))\n      as HpCs_compiled_well_formed\n        by (apply Intermediate.linking_well_formedness; assumption).\n\n    assert (Intermediate.linkable_mains p_compiled Cs_compiled) as linkable_mains.\n    {\n      eapply (@Compiler.compilation_preserves_linkable_mains p _ _ Cs);\n        try eassumption.\n      - rewrite <- Hsame_iface2 in linkability.\n        eapply Source.linkable_disjoint_mains; assumption.\n    }\n\n    assert (mergeable_interfaces (Intermediate.prog_interface p_compiled)\n                                 (Intermediate.prog_interface Cs_compiled))\n      as Hmergeable_ifaces.\n      by apply Intermediate.compose_mergeable_interfaces.\n\n    assert (Source.closed_program (Source.program_link p Cs)) as Hclosed_p_Cs. {\n      apply (Source.interface_preserves_closedness_l HP'Cs_closed); trivial.\n      apply Compiler.compilation_preserves_interface in HP'_compiles.\n      apply Compiler.compilation_preserves_interface in successful_compilation.\n      congruence.\n    }\n    assert (linkable (Source.prog_interface p) (Source.prog_interface Cs))\n      as Hlinkable_p_Cs. {\n      inversion linkability'' as [sound_interface_p_Cs fdisjoint_p_Cs].\n      constructor;\n        (apply Compiler.compilation_preserves_interface in HCs_compiles;\n        apply Compiler.compilation_preserves_interface in successful_compilation;\n        rewrite <- HCs_compiles; rewrite <- successful_compilation;\n        assumption).\n    }\n    assert (Source.well_formed_program (Source.program_link p Cs)) as Hwf_p_Cs\n      by (apply Source.linking_well_formedness; assumption).\n\n    assert (HP'Cs_compiled_closed :\n              Intermediate.closed_program (Intermediate.program_link P'_compiled Cs_compiled)).\n    {\n      rewrite Intermediate.program_linkC; try easy; try now apply linkable_sym.\n      apply Intermediate.interface_preserves_closedness_r with (p2 := p_compiled); eauto.\n      apply linkable_sym; eauto.\n      rewrite Intermediate.program_linkC; eauto.\n      apply linkable_sym; eauto.\n      apply Intermediate.linkable_mains_sym; eauto.\n      eapply S2I.Definitions.matching_mains_equiv; eauto.\n      eapply Compiler.compilation_has_matching_mains; eauto.\n    }\n\n    rewrite Intermediate.program_linkC in HP'_Cs_compiled_star; try assumption.\n    rewrite <- Hctx_same_iface in Hmergeable_ifaces.\n\n    assert (H_p_Ct_good: forall (ss : CS.state) (tt : Events.trace Events.event),\n               CSInvariants.CSInvariants.is_prefix\n                 ss (Intermediate.program_link p_compiled Ct) tt ->\n               good_trace_extensional (left_addr_good_for_shifting all_zeros_shift) tt\n               /\\\n               (forall (mem : eqtype.Equality.sort Memory.Memory.t) (ptr : Pointer.t)\n                       (addr : Component.id * Block.id) (v : value),\n                   CS.state_mem ss = mem ->\n                   Memory.Memory.load mem ptr = Some v ->\n                   addr = (Pointer.component ptr, Pointer.block ptr) ->\n                   left_addr_good_for_shifting all_zeros_shift addr ->\n                   left_value_good_for_shifting all_zeros_shift v)).\n    {\n      intros ? ? ?. split.\n      - constructor. intros ? ?. destruct a as [? ?].\n        unfold all_zeros_shift, uniform_shift. easy.\n      - intros ? ? ? ? ? ? ? ?.\n        destruct v as [| [[[[|] ?] ?] ?] |]; unfold all_zeros_shift, uniform_shift;\n          simpl; easy.\n    }\n\n    (** Need an axiom about the Compiler. The axiom will transfer goodness of *)\n    (** a source program to goodness of the compiled version, where goodness  *)\n    (** is described as conformance of the sharing behavior with the static   *)\n    (** address renaming convention (i.e., shared addresses are renamed into  *)\n    (** shared addresses). Viewed dually, the axiom about the compiler says   *)\n    (** that the compiler preserves the privacy of private (non-shared)       *) \n    (** addresses.                                                            *)\n\n    (** With such an axiom in hand, we can assert the following from its      *)\n    (** corresponding source version.                                         *)\n\n    assert (HP'_compiled_Cs_compiled_good: forall (ss'' : CS.state) tt'',\n               CSInvariants.CSInvariants.is_prefix\n                 ss''\n                 (Intermediate.program_link P'_compiled Cs_compiled) tt'' ->\n               good_trace_extensional\n                 (left_addr_good_for_shifting\n                    (uniform_shift 1)) tt''\n               /\\\n               (forall (mem : eqtype.Equality.sort Memory.Memory.t) (ptr : Pointer.t)\n                       (addr : Component.id * Block.id) (v : value),\n                   CS.state_mem ss'' = mem ->\n                   Memory.Memory.load mem ptr = Some v ->\n                   addr = (Pointer.component ptr, Pointer.block ptr) ->\n                   left_addr_good_for_shifting\n                     (uniform_shift 1) addr ->\n                   left_value_good_for_shifting\n                     (uniform_shift 1) v)).\n    {\n      assert (P'_Cs_closed: Source.closed_program (Source.program_link P' Cs)).\n      {\n        eapply Source.interface_preserves_closedness_l; eauto.\n        rewrite Hsame_iface1.\n        erewrite compilation_preserves_interface; eauto.\n      }\n\n      assert (P'_Cs_wf: Source.well_formed_program (Source.program_link P' Cs)).\n      {\n        eapply Source.linking_well_formedness; eauto.\n      }\n      \n      specialize (Compiler.compiler_preserves_non_leakage_of_private_pointers\n                    _ _ _ _ P'_Cs_closed P'_Cs_wf HP'_Cs_compiles good_P'_Cs\n                 ) as G.\n      unfold CSInvariants.CSInvariants.is_prefix.\n      intros ? ? Hpref.\n      unfold private_pointers_never_leak_I, shared_locations_have_only_shared_values in *.\n      specialize (G ss'' tt'' Hpref) as [G1 G2].\n      split; first exact G1.\n      intros ? ? ? ? ? ? ? ?.\n      eapply G2; eauto.\n    }\n\n    assert (t_rel_t'compiled: traces_shift_each_other_option\n                        all_zeros_shift\n                        (uniform_shift 1)\n                        (project_non_inform t_inform) t'compiled).\n    {\n        eapply traces_shift_each_other_option_transitive.\n        - apply traces_shift_each_other_option_symmetric; exact Ht_rel_t'.\n        - exact Ht'_rel_t'compiled.\n    }\n\n    \n    pose proof Intermediate.RecompositionRel.recombination_trace_rel\n    well_formed_p_compiled\n    well_formed_Ct\n    well_formed_P'_compiled\n    well_formed_Cs_compiled\n    Hmergeable_ifaces\n    Hprog_same_iface\n    Hctx_same_iface\n    closedness\n    HP'Cs_compiled_closed\n    H_p_Ct_good\n    HP'_compiled_Cs_compiled_good\n    Hstar\n    HP'_Cs_compiled_star\n    t_rel_t'compiled\n      as [s_recomb [t_recomb [Hstar_recomb [_ trel_recomb]]]].\n\n    \n    (* BCC *)\n    assert (exists pCs_compiled,\n               Compiler.compile_program (Source.program_link p Cs)\n                                        (unionm psz Cssz)\n               = Some pCs_compiled)\n      as [pCs_compiled HpCs_compiles].\n      by now apply Compiler.well_formed_compilable.\n      \n      eapply Compiler.backward_simulation_star\n        in Hstar_recomb\n      ;\n        eauto;\n        last by\n        (erewrite HpCs_compiles;\n         erewrite Compiler.separate_compilation in HpCs_compiles; eauto\n        ).\n      \n      destruct Hstar_recomb as [s'_pCs HpCs_star].\n      destruct HpCs_star as [tQed [HstarQed HshiftQed]].\n      do 5 eexists; split; last split; last split; last split; last split;\n        eauto.\n      {\n        eapply traces_shift_each_other_option_transitive.\n        - exact trel_recomb.\n        - eassumption.\n      }\n      \n      apply disciplined_program_link; auto.\n      \n      eapply disciplined_program_unlink with (c := P'); eauto.\n      - eapply linkable_sym. eauto.\n      - rewrite Source.link_sym; auto.\n        by apply linkable_sym.\n      - eapply NoLeak.good_Elocal_usage_program_link; auto.\n        eapply NoLeak.good_Elocal_usage_program_unlink with (c := P'); eauto.\n        eapply linkable_sym; eauto.\n        rewrite Source.link_sym; auto.\n        by apply linkable_sym.\nQed.\n\nPrint Assumptions RSC.\n\nEnd RSC_Section.\n\n(* To evaluate the assumptions and statements of the main results,\n   uncomment and execute the following statements. To show the\n   statement of a theorem, replace [Print Assumptions] -> [Check]. *)\n\n(* Check RSC. *)\n(* Print Assumptions S2I.Compiler.forward_simulation_star. *)\n(* Print Assumptions Intermediate.RecompositionRel.recombination_trace_rel. *)\n(* Print Assumptions S2I.Compiler.backward_simulation_star. *)\n(* Print CompCert.Events.event. *)\n(* Print Common.TracesInform.event_inform. *)\n(* Print Assumptions Intermediate.CS.CS.star_sem_non_inform_star_sem_inform. *)\n(* Print Assumptions Source.Definability.definability. *)\n(* Print Intermediate.RecompositionRelCommon.mergeable_internal_states. *)\n(* Print Common.RenamingOption.traces_shift_each_other_option. *)\n(* Check Intermediate.CS.CS.Jump. *)\n(* Check Intermediate.CS.CS.Store. *)\n(* Print Assumptions RSC. *)\n(* Print Assumptions Source.Definability.definability_gen_rel_right. *)\n(* Print Intermediate.RecompositionRelCommon.mergeable_border_states. *)\n(* Print Assumptions Intermediate.RecompositionRelStrengthening.threeway_multisem_event_lockstep_program_step. *)\n(* Print Assumptions Intermediate.RecompositionRelOptionSim.merge_states_silent_star. *)\n(* Print Assumptions Intermediate.RecompositionRelLockstepSim.threeway_multisem_star_E0. *)\n(* Print Assumptions Intermediate.RecompositionRelCommon.mergeable_internal_states_sym. *)\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/RSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.1676591776742447}}
{"text": "(** This file implements symbolic evaluation for the\n ** language defined in IL.v\n **)\nRequire Import List.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import MirrorShard.SepExpr.\nRequire Import MirrorShard.Expr.\nRequire Import MirrorShard.Prover.\nRequire Import MirrorShard.Quantifier.\nRequire Import MirrorShard.Env TypedPackage.\nRequire Import IL SepIL.\nRequire Import Word Memory.\nRequire Import PropX.\nRequire Structured SymEval.\nRequire Import ILEnv SymIL.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** The Symolic Evaluation Interfaces *)\nModule MEVAL := SymIL.MEVAL.\n\nModule SymIL_Correct.\n  Section typed.\n    Variable ts : list type.\n    Let types := repr bedrock_types_r ts.\n\n    Notation pcT := (tvType 0).\n    Notation tvWord := (tvType 0).\n    Notation stT := (tvType 1).\n    Notation tvState := (tvType 2).\n    Notation tvTest := (tvType 3).\n    Notation tvReg := (tvType 4).\n\n    Variable fs : functions types.\n    Let funcs := repr (bedrock_funcs_r ts) fs.\n    Variable preds : SEP.predicates types.\n\n    Variable Prover : ProverT types.\n    Variable PC : ProverT_correct Prover funcs.\n\n    Variable meval : MEVAL.MemEvaluator types.\n    Variable meval_correct : MEVAL.MemEvaluator_correct pcT stT meval funcs preds tvWord tvWord\n      (@IL_mem_satisfies ts) (@IL_ReadWord ts) (@IL_WriteWord ts) (@IL_ReadByte ts) (@IL_WriteByte ts).\n\n    Variable facts : Facts Prover.\n    Variable meta_env : env types.\n    Variable vars_env : env types.\n\n    Lemma stateD_interp : forall cs stn_st ss sh,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      SymMem ss = Some sh ->\n      interp cs (![ SEP.sexprD funcs preds meta_env vars_env (SH.sheapD sh)] stn_st).\n    Proof.\n      clear. destruct stn_st; destruct ss; destruct SymRegs; destruct p; simpl; intros.\n      rewrite H0 in *. intuition.\n    Qed.\n\n    Hint Resolve stateD_interp : sym_eval_hints.\n\n    Ltac t_correct := \n      simpl; intros;\n        unfold IL_stn_st, IL_mem_satisfies, IL_ReadWord, IL_WriteWord in *;\n          repeat (simpl in *; \n            match goal with\n              | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n              | [ H : prod _ _ |- _ ] => destruct H\n              | [ H : match ?X with \n                        | Some _ => _\n                        | None => _ \n                      end |- _ ] =>\n                revert H; case_eq X; intros; try contradiction\n              | [ H : match ?X with \n                        | Some _ => _\n                        | None => _ \n                      end = _ |- _ ] =>\n                revert H; case_eq X; intros; try congruence\n              | [ H : _ = _ |- _ ] => rewrite H\n              | [ H : @existsEach _ _ _ |- _ ] => apply existsEach_sem in H\n              | [ H : exists x, _ |- _ ] => destruct H\n              | [ H : _ /\\ _ |- _ ] => destruct H\n              | [ |- exists x, Some _ = Some _ /\\ _ ] =>\n                eexists; split; [ reflexivity | ]\n            end); subst; eauto with sym_eval_hints.\n\n    Lemma sym_evalLoc_correct : forall loc ss res res' stn_st locD cs,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_locD fs meta_env vars_env loc = Some locD ->\n      evalLoc (snd stn_st) locD = res' ->\n      sym_evalLoc loc ss = res -> \n      exprD funcs meta_env vars_env res tvWord = Some res'.\n    Proof.\n      destruct loc; unfold stateD; destruct ss; destruct SymRegs; destruct p; intros; destruct stn_st; simpl in *;\n        t_correct; try solve [ eauto \n                             | destruct r; simpl in *; \n                               repeat match goal with\n                                        | [ H : _ = _ |- _ ] => rewrite H\n                                        | [ |- _ ] => subst funcs\n                                      end; eauto ].\n    Qed.\n    \n    Hypothesis Valid_facts : Valid PC meta_env vars_env facts.\n    \n    Lemma sym_evalRval_correct : forall rv ss res stn_st rvD cs,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_rvalueD funcs meta_env vars_env rv = Some rvD ->\n      sym_evalRval Prover meval facts rv ss = Some res ->\n      exists val,\n        evalRvalue (fst stn_st) (snd stn_st) rvD = Some val /\\\n        exprD funcs meta_env vars_env res tvWord = Some val.\n    Proof.\n      Opaque stateD sym_locD.\n      destruct rv; t_correct. \n      { destruct s; t_correct. \n        { erewrite <- (@sym_evalLoc_correct (SymReg _ r)). f_equal. eauto. simpl.\n          Transparent sym_locD. simpl. reflexivity. Opaque sym_locD. reflexivity. reflexivity. }\n        { eapply (MEVAL.ReadCorrect meval_correct) with (cs := cs) in H2; eauto with sym_eval_hints.\n          2: eapply sym_evalLoc_correct; (instantiate; eauto with sym_eval_hints). 2: eauto.\n          t_correct. }\n        { eapply (MEVAL.ReadByteCorrect meval_correct) with (cs := cs) in H2; eauto with sym_eval_hints.\n          2: eapply sym_evalLoc_correct; (instantiate; eauto with sym_eval_hints). 2: eauto.\n          t_correct. } }\n      { congruence. }\n    Qed.\n          \n    Lemma sym_evalLval_correct : forall lv stn_st lvD cs val ss ss' valD,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_lvalueD funcs meta_env vars_env lv = Some lvD ->\n      sym_evalLval Prover meval facts lv val ss = Some ss' ->\n      exprD funcs meta_env vars_env val tvWord = Some valD ->\n      exists st', \n        evalLvalue (fst stn_st) (snd stn_st) lvD valD = Some st' /\\\n        stateD funcs preds meta_env vars_env cs (fst stn_st, st') ss'.\n    Proof.\n      destruct lv; t_correct.\n      { Transparent stateD. unfold stateD in *. t_correct. Opaque stateD.\n        case_eq (sym_setReg r val (SymRegs ss)); intros.\n        destruct ss; destruct SymRegs; destruct p. t_correct.\n        unfold sym_setReg in H0. destruct r; inversion H0; subst; t_correct; unfold rupd; simpl; intuition;\n        try solve [ repeat rewrite sepFormula_eq in *; unfold sepFormula_def in *; simpl in *; auto ].\n        destruct r; inversion H0; subst; t_correct; unfold rupd; simpl; intuition. }\n      { eapply (@sym_evalLoc_correct s) in H0; eauto.\n        simpl.\n        match goal with\n          | [ H : MEVAL.swrite_word _ _ _ _ _ _ = _ |- _ ] => \n            eapply (MEVAL.WriteCorrect meval_correct) with (cs := cs) (stn_m := (s0,s1)) in H; eauto with sym_eval_hints\n        end.\n        simpl in *.\n        destruct (WriteWord s0 (Mem s1) (evalLoc s1 l) valD); try contradiction. t_correct.\n        Transparent stateD. destruct ss; destruct SymRegs; destruct p. simpl in *. Opaque stateD. intuition. subst.\n        eapply sheapD_pures_SF in H3.\n        apply AllProvable_app' in H6. apply AllProvable_app; intuition auto. }\n      { eapply (@sym_evalLoc_correct s) in H0; eauto.\n        simpl.\n        match goal with\n          | [ H : MEVAL.swrite_byte _ _ _ _ _ _ = _ |- _ ] => \n            eapply (MEVAL.WriteByteCorrect meval_correct) with (cs := cs) (stn_m := (s0,s1)) in H; eauto with sym_eval_hints\n        end.\n        simpl in *.\n        destruct (WriteByte (Mem s1) (evalLoc s1 l) (WtoB valD)); try contradiction. t_correct.\n        Transparent stateD. destruct ss; destruct SymRegs; destruct p. simpl in *. Opaque stateD. intuition. subst.\n        eapply sheapD_pures_SF in H3.\n        apply AllProvable_app' in H6. apply AllProvable_app; intuition auto. }\n    Qed.\n\n\n    Ltac think := instantiate; simpl;\n      repeat match goal with\n               | [ H : _ = _ |- _ ] => rewrite H\n             end; eauto.\n\n    Lemma sym_evalInstr_correct' : forall instr stn_st instrD cs ss ss',\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_instrD funcs meta_env vars_env instr = Some instrD ->\n      sym_evalInstr Prover meval facts instr ss = Some ss' ->\n      exists st',\n        evalInstr (fst stn_st) (snd stn_st) instrD = Some st' /\\\n        stateD funcs preds meta_env vars_env cs (fst stn_st, st') ss'.\n    Proof.\n      destruct instr; t_correct; simpl;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ b : binop |- _ ] => \n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n               end; t_correct.\n    Qed.\n\n    Lemma sym_assertTest_correct' : forall cs r rD t l lD ss stn_st,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_rvalueD funcs meta_env vars_env r = Some rD ->\n      sym_rvalueD funcs meta_env vars_env l = Some lD ->\n      match Structured.evalCond rD t lD (fst stn_st) (snd stn_st) with\n        | None =>\n          forall res, \n            match sym_assertTest Prover meval facts r t l ss res with\n              | Some _ => False\n              | None => True\n            end\n        | Some res' =>\n          match sym_assertTest Prover meval facts r t l ss res' with\n            | Some b => \n              Provable funcs meta_env vars_env b\n            | None => True\n          end\n      end.\n    Proof.\n      unfold sym_assertTest, Structured.evalCond; destruct stn_st; simpl in *;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ |- context [ evalRvalue ?A ?B ?C ] ] => \n                   case_eq (evalRvalue A B C); intros\n                 | [ |- context [ evalTest ?A ?B ?C ] ] => \n                   case_eq (evalTest A B C); intros\n                 | [ b : binop |- _ ] => \n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n               end; t_correct; simpl in *;\n      try destruct res;\n       repeat match goal with\n        | [ |- context [ sym_evalRval ?A ?B ?C ?D ?E ] ] =>\n          case_eq (sym_evalRval A B C D E); intros\n               end; auto;\n        unfold Provable; destruct t;\n        repeat match goal with\n                 | [ |- match match ?X with \n                                | Some _ => match ?Y with _ => _ end \n                                | _ => _\n                              end with _ => _ end ] =>\n                   (case_eq X; trivial; case_eq Y; trivial); []\n                                   \n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ |- context [ evalRvalue ?A ?B ?C ] ] => \n                   case_eq (evalRvalue A B C); intros\n                 | [ |- context [ evalTest ?A ?B ?C ] ] => \n                   consider (evalTest A B C); intros\n                 | [ b : binop |- _ ] => \n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n                 | [ |- _ ] => progress t_correct\n               end; unfold IL.weqb, IL.wneb, wltb, wleb in *; simpl in *;\n        repeat match goal with\n                 | [ H : (if ?X then _ else _) = _ |- _ ] =>\n                   revert H; consider X; try congruence\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : ?X = _ , H' : ?X = _ |- _ ] => rewrite H in H'\n                 | [ |- context [ wlt_dec ?X ?Y ] ] =>\n                   destruct (wlt_dec X Y); try congruence\n               end; try congruence; eauto 10 using eq_le, lt_le, le_neq_lt.\n      eapply weqb_true_iff; auto.\n      intro. apply weqb_true_iff in H1. congruence.\n    Qed.\n\n  End typed.\n\n\n  Section typed2.\n    Variable ts : list type.\n    Let types := repr bedrock_types_r ts.\n\n    Notation pcT := (tvType 0).\n    Notation tvWord := (tvType 0).\n    Notation stT := (tvType 1).\n    Notation tvState := (tvType 2).\n    Notation tvTest := (tvType 3).\n    Notation tvReg := (tvType 4).\n\n    Variable fs : functions types.\n    Let funcs := repr (bedrock_funcs_r ts) fs.\n    Variable preds : SEP.predicates types.\n\n    Variable Prover : ProverT types.\n    Variable PC : ProverT_correct Prover funcs.\n\n    Variable meval : MEVAL.MemEvaluator types.\n    Variable meval_correct : MEVAL.MemEvaluator_correct pcT stT meval funcs preds tvWord tvWord\n      (@IL_mem_satisfies ts) (@IL_ReadWord ts) (@IL_WriteWord ts) (@IL_ReadByte ts) (@IL_WriteByte ts).\n\n    Ltac t_correct := \n      simpl; intros;\n        unfold IL_stn_st, IL_mem_satisfies, IL_ReadWord, IL_WriteWord in *;\n          repeat (simpl in *; \n            match goal with\n              | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n              | [ H : prod _ _ |- _ ] => destruct H\n              | [ H : match ?X with \n                        | Some _ => _\n                        | None => _ \n                      end |- _ ] =>\n              revert H; case_eq X; intros; try contradiction\n              | [ H : match ?X with \n                        | Some _ => _\n                        | None => _ \n                      end = _ |- _ ] =>\n              revert H; case_eq X; intros; try congruence\n              | [ H : _ = _ |- _ ] => rewrite H\n              | [ H : reg |- _ ] => destruct H\n            end; intuition); subst.\n\n    Lemma sym_evalInstrs_correct : forall (facts : Facts Prover) (meta_env var_env : env types),\n      Valid PC meta_env var_env facts  ->\n      forall is stn_st isD cs ss,\n        stateD funcs preds meta_env var_env cs stn_st ss ->\n        sym_instrsD funcs meta_env var_env is = Some isD ->\n        match evalInstrs (fst stn_st) (snd stn_st) isD with\n          | Some st' => \n            match sym_evalInstrs Prover meval facts is ss with\n              | inl ss' => stateD funcs preds meta_env var_env cs (fst stn_st, st') ss'\n              | inr (ss', is') => \n                match sym_instrsD funcs meta_env var_env is' with\n                  | None => False\n                  | Some is'D => \n                    exists st'', stateD funcs preds meta_env var_env cs (fst stn_st, st'') ss' /\\\n                      evalInstrs (fst stn_st) st'' is'D = Some st'\n                end\n            end\n          | None => \n            match sym_evalInstrs Prover meval facts is ss with\n              | inl ss' => False\n              | inr (ss', is') => \n                match sym_instrsD funcs meta_env var_env is' with\n                  | None => False\n                  | Some is'D => \n                    exists st'', stateD funcs preds meta_env var_env cs (fst stn_st, st'') ss' /\\\n                      evalInstrs (fst stn_st) st'' is'D = None\n                end\n            end\n        end.\n    Proof.\n      Opaque stateD.\n      induction is; simpl; intros;\n        repeat match goal with\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               end; simpl; destruct stn_st; simpl in *; eauto.\n      t_correct. simpl in *.\n      case_eq (evalInstr s s0 i); intros.\n      case_eq (sym_evalInstr Prover meval facts a ss); intros.      \n\n      destruct (@sym_evalInstr_correct' ts fs preds Prover PC meval meval_correct facts meta_env var_env\n        H a (s,s0) i cs ss s2 H0 H1 H4). simpl in *. intuition.\n      rewrite H6 in H3. inversion H3; clear H3; subst.\n      specialize (IHis (s, s1)). simpl in *. eapply IHis; eauto.\n      \n      simpl. rewrite H1. rewrite H2. simpl. \n      case_eq (evalInstrs s s1 l); intros; exists s0; simpl; rewrite H3; eauto.\n\n      case_eq (sym_evalInstr Prover meval facts a ss); intros. \n      Focus 2. simpl. rewrite H1. rewrite H2. exists s0; simpl; rewrite H3; intuition.\n\n      \n\n      edestruct (@sym_evalInstr_correct' ts fs preds Prover PC meval meval_correct facts meta_env var_env\n        H a (s,s0) i cs ss); eauto.\n      simpl in *. destruct H5. rewrite H3 in H5. congruence.\n      Transparent stateD.\n    Qed.\n\n    Variable learnHook : MEVAL.LearnHook types (SymState types).\n    Variable learn_correct : @MEVAL.LearnHook_correct _ _ pcT stT learnHook (@stateD _ funcs preds) funcs preds.\n\n    Ltac shatter_state ss :=\n      destruct ss as [ ? [ [ ? ? ] ? ] ].\n\n    Lemma skip_to_nil : forall T U (F : T -> U) vars env X,\n      map F env = skipn (length vars) X ->\n      map F nil = skipn (length (vars ++ env)) X.\n    Proof.\n      clear. induction vars; simpl; intros; subst.\n      induction env; eauto.\n      destruct X; auto.\n    Qed.\n    Lemma AllProvable_cons : forall U G P Ps,\n      Provable funcs U G P ->\n      AllProvable funcs U G Ps ->\n      AllProvable funcs U G (P :: Ps).\n    Proof. simpl; intuition. Qed.\n    Lemma AllProvable_nil : forall U G,\n      AllProvable funcs U G nil.\n    Proof. simpl; intuition. Qed.\n    Hint Resolve AllProvable_cons AllProvable_nil : env_resolution.\n    Hint Resolve Learn_correct : env_resolution.\n    Hint Resolve skip_to_nil : env_resolution.\n\n    Lemma skip_prove_nil : forall T U (F : T -> U) vars env X Y,\n      map F env = skipn (length vars) X ->\n      map F Y = skipn (length (vars ++ env)) X ->\n      Y = nil.\n    Proof.\n      clear. intros. destruct Y; auto.\n      eapply skip_to_nil in H. rewrite <- H in H0. simpl in *; congruence.\n    Qed.\n    Hint Resolve skip_prove_nil : env_resolution.\n    Lemma stateD_addToPures : forall U G cs ss stn_st P,\n      stateD funcs preds U G cs stn_st ss ->\n      Provable funcs U G P ->\n      stateD funcs preds U G cs stn_st \n      {| SymMem := SymMem ss\n        ; SymRegs := SymRegs ss \n        ; SymPures := P :: SymPures ss |}.\n    Proof.\n      Transparent stateD.\n      clear. intros; shatter_state ss; destruct stn_st; simpl in *. intuition.\n      destruct SymMem; intuition.\n      Opaque stateD.\n    Qed.\n    Hint Resolve stateD_addToPures : stateD_solver.\n\n    Ltac qstateD_solver :=\n      eapply existsEach_sem; intros; eexists; split; [ solve [ eauto with env_resolution ] | ];\n      let e := fresh in\n      eapply forallEach_sem; intro e; intro;\n      eauto with stateD_solver.\n\n    Opaque repr stateD.\n    Ltac split_congruence := \n      repeat match goal with \n               | [ H : prod _ _ |- _ ] => destruct H\n             end; congruence.\n\n    Lemma stateD_weaken_vars : forall uvars vars cs stn_st ss' env,\n      stateD funcs preds uvars vars cs stn_st ss' ->\n      stateD funcs preds uvars (vars ++ env) cs stn_st ss'.\n    Proof.\n      Transparent stateD.\n      clear. intros. destruct stn_st; shatter_state ss'; simpl in *.\n      repeat match goal with\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : context [ match exprD ?A ?B ?C ?D ?E with _ => _ end ] |- _ ] =>\n                 revert H; case_eq (exprD A B C D E); intros; try contradiction\n             end; subst.\n      rewrite <- app_nil_r with (l := uvars). repeat erewrite exprD_weaken by eassumption.\n      intuition. destruct SymMem; auto. erewrite SH.SE_FACTS.sexprD_weaken in H0. eassumption.\n      eapply AllProvable_weaken; eauto. \n    Qed.\n    Lemma stateD_weaken_uvars : forall uvars vars cs stn_st ss' env,\n      stateD funcs preds uvars vars cs stn_st ss' ->\n      stateD funcs preds (uvars ++ env) vars cs stn_st ss'.\n    Proof.\n      Transparent stateD.\n      clear. intros. destruct stn_st; shatter_state ss'; simpl in *.\n      repeat match goal with\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : context [ match exprD ?A ?B ?C ?D ?E with _ => _ end ] |- _ ] =>\n                 revert H; case_eq (exprD A B C D E); intros; try contradiction\n             end; subst.\n      rewrite <- app_nil_r with (l := vars). repeat erewrite exprD_weaken by eassumption.\n      intuition. destruct SymMem; auto. erewrite SH.SE_FACTS.sexprD_weaken in H0. eassumption.\n      eapply AllProvable_weaken; eauto. \n    Qed.\n    Hint Resolve stateD_weaken_vars stateD_weaken_uvars : stateD_solver.\n    Require ListFacts.\n    Require Import MirrorShard.Tactics.\n    Hint Resolve ListFacts.not_sure ListFacts.map_skipn_all_map_is_nil ListFacts.map_skipn_all_map : env_resolution.\n\n    Lemma sym_locD_weaken : forall ts X A C Y Z,\n      sym_locD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_locD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto; \n      erewrite exprD_weaken; eauto.\n    Qed.\n\n    Lemma sym_lvalueD_weaken : forall ts X A C Y Z,\n      sym_lvalueD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_lvalueD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto.\n      erewrite sym_locD_weaken; eauto.\n      erewrite sym_locD_weaken; eauto.\n    Qed.      \n    Lemma sym_rvalueD_weaken : forall ts X A C Y Z,\n      sym_rvalueD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_rvalueD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto.\n      erewrite sym_lvalueD_weaken; eauto.\n      erewrite exprD_weaken; eauto.\n    Qed.\n\n    Lemma sym_instrD_weaken : forall ts X A C Y Z,\n      sym_instrD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n      sym_instrD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear; destruct Y; simpl; intros; think; auto;\n        repeat ((erewrite sym_lvalueD_weaken by eauto) ||\n                (erewrite sym_rvalueD_weaken by eauto)); auto.\n    Qed.\n\n    Lemma sym_instrsD_weaken : forall ts X A C Y Z,\n      sym_instrsD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n      sym_instrsD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. induction Y; simpl; intros; think; auto.\n      erewrite sym_instrD_weaken; eauto.\n    Qed.\n\n    Lemma istreamD_weaken : forall ts X A C Y Z P L,\n      istreamD (types' := ts) X A C Y Z P L ->\n      forall B D,\n      istreamD X (A ++ B) (C ++ D) Y Z P L.\n    Proof.\n      clear. induction Y; simpl; intros; think; auto.\n      repeat match goal with \n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 consider X; intros\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ |- _ ] =>\n                 (erewrite sym_instrsD_weaken by eauto) ||\n                 (erewrite sym_rvalueD_weaken by eauto) ||\n                 (erewrite sym_lvalueD_weaken by eauto)\n             end; intuition.\n    Qed.\n\n    Lemma env_nil_by_length_eq : forall ts L X Y,\n      typeof_env (types := ts) L = X ->\n      length Y = length X ->\n      typeof_env (types := ts) nil = skipn (length L) Y.\n    Proof.\n      clear. intros. subst.\n      erewrite ListFacts.skipn_length_gt; auto. unfold typeof_env in *. rewrite map_length in H0. omega.\n    Qed.\n    Hint Resolve env_nil_by_length_eq : env_resolution.\n\n    Lemma all2_tvar_seq_dec_true : forall a b,\n      Folds.all2 Expr.tvar_seqb a b = true -> a = b.\n    Proof.\n      clear; induction a; destruct b; simpl; intros; try congruence.\n      consider (tvar_seqb a t); intros; subst. erewrite IHa; auto.\n    Qed.\n\n    Lemma sym_evalStream_quant_append : forall path facts qs uvars vars ss res,\n      sym_evalStream Prover meval learnHook facts path qs uvars vars ss = res ->\n      match res with\n        | Safe qs' _ \n        | SafeUntil qs' _ _ => exists qs'', qs' = appendQ qs'' qs\n(*        | Unsafe qs'  *)\n      end.\n    Proof.\n      clear.\n      induction path; simpl; intros.\n      { inversion H. subst. exists QBase.\n        clear. simpl; auto. }\n      { destruct a. destruct p. consider (sym_evalInstrs Prover meval facts l ss); intros; try congruence.\n        eapply IHpath; eauto. destruct p. subst. exists QBase. auto.\n        destruct s. destruct o. consider (sym_assertTest Prover meval facts s t s0 ss b); intros.\n        repeat match goal with \n                 | [ H : match ?X with (_,_) => _ end = _ |- _ ] => destruct X; try congruence\n               end.\n        eapply IHpath in H0. destruct res; auto; destruct H0; rewrite <- appendQ_assoc in H0; eauto.\n        subst; auto. exists QBase; auto.        \n        repeat match goal with \n                 | [ H : match ?X with _ => _ end = _ |- _ ] => destruct X; try congruence\n               end; subst;\n        try eapply IHpath; eauto.\n        exists QBase; auto.\n        exists QBase; auto. }\n    Qed.\n\n    Hint Extern 1 (@eq (list tvar) _ _) =>\n      simpl; repeat (rewrite app_nil_r in * || rewrite typeof_env_app in * || rewrite app_ass || \n        (f_equal; []) || (f_equal; [ solve [ reflexivity | assumption ] | ] || reflexivity || assumption)) : env_resolution.\n      \n    Definition NO_MORE_COND : Prop := True.\n\n    Ltac sym_eval_prover IHpath := \n      repeat match goal with\n               | [ H : Valid _ (?A ++ ?b) (?C ++ ?d) _\n                 , H' : sym_instrsD ?X ?A ?C ?Y = ?Z |- _ ] =>\n                 apply sym_instrsD_weaken with (B := b) (D := d) in H'\n               | [ H : Valid _ (?A ++ ?b) (?C ++ ?d) _\n                 , H' : istreamD ?X ?A ?C ?Y ?Z ?P ?L |- _ ] =>\n                 apply istreamD_weaken with (B := b) (D := d) in H'\n               | [ H : (_,_) = (_,_) |- _ ] => inversion H; clear H; subst\n               | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               | [ H : Safe _ _ = Safe _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : SafeUntil _ _ _ = SafeUntil _ _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : inl _ = inl _ |- _ ] => inversion H; clear H; subst\n               | [ H : inr _ = inr _ |- _ ] => inversion H; clear H; subst\n               | [ H : SymAssertCond _ _ _ _ = SymAssertCond _ _ _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : sum (prod _ _) _ |- _ ] => destruct H as [ [ ? ? ] | ? ]\n               | [ H : ?X = _ , H' : ?X = _ |- _ ] => rewrite H in H'\n               | [ H : option state |- _ ] => destruct H\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : ?X = _ , H' : context [ match ?X with _ => _ end ] |- _ ] =>\n                 rewrite H in H'\n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 (revert H; case_eq X; intros; try contradiction); []\n               | [ |- _ ] => progress (repeat rewrite app_nil_r in * )\n               | [ |- _ ] => solve [ congruence | eauto with stateD_solver ]\n               | [ H : ?X -> _ , H' : ?X |- _ ] =>\n                 match type of X with\n                   | Prop => \n                     specialize (H H')\n                 end\n               | [ H   : sym_evalInstrs _ _ ?F ?is ?S = _\n                 , H'  : evalInstrs ?stn ?st _ = _ \n                 , H'' : sym_instrsD _ ?U ?G _ = Some ?isD\n                 , Hst : stateD _ _ _ _ _ _ _ \n                 |- _ ] => \n               ( eapply sym_evalInstrs_correct with (stn_st := (stn,st)) (facts := F) (ss := S) in H'' ; eauto ;\n                 simpl in H'' ) ; [ clear Hst ] \n               | [ H : Structured.evalCond ?l ?A ?r ?B ?C = _ \n                 , Hst : stateD _ _ ?U ?G ?cs _ _\n                 , H' : sym_rvalueD _ _ _ _ = Some ?l\n                 , H'' : sym_rvalueD _ _ _ _ = Some ?r |- _ ] =>\n               match goal with \n                 | [ H : NO_MORE_COND |- _ ] => fail 1\n                 | _ =>\n                   (generalize Hst; eapply sym_assertTest_correct' with (meta_env := U) (vars_env := G) (t := A) (rD := l) (lD := r) (stn_st := (B,C)) in Hst; eauto using sym_rvalueD_weaken) ; [ intro; simpl in Hst ; assert NO_MORE_COND by (exact I) ]\n               end\n               | [ H : learnHook _ ?U' ?G' ?SS ?f ?F = (?A, ?B)\n                 , H' : stateD _ _ ?U ?G _ _ _ \n                 , LC : MEVAL.LearnHook_correct _ _ _ _ _ _ \n                 , PC : ProverT_correct _ _ |- _ ] =>\n                 (cutrewrite (U' = typeof_env U) in H; [ | rewrite typeof_env_app; f_equal; auto ] ;\n                  cutrewrite (G' = typeof_env G) in H; [ | rewrite typeof_env_app; f_equal; auto ] ;\n                  eapply (@MEVAL.hook_sound _ _ _ _ _ _ _ _ LC _ PC U G) with \n                    (new_facts := F) (ss := SS) (ss' := A) (quant := B) in H ;\n                  eauto using Learn_correct, AllProvable_cons, AllProvable_nil with stateD_solver) ; [ clear H' ] \n               | [ H : quantD _ _ _ _ |- quantD _ _ _ _ ] =>\n                 eapply quantD_impl; [ eapply H | clear H ; simpl; intros ]\n               | [ |- quantD _ _ (appendQ _ ?X) _ ] =>\n                 apply quantD_app\n               | [ H : appendQ _ _ = appendQ _ _ |- _ ] => apply appendQ_proper in H; subst\n\n               | [ H : appendQ ?A ?B = appendQ _ (appendQ _ ?B) |- _ ] => \n                 rewrite <- appendQ_assoc in H; apply appendQ_proper in H; subst\n               | [ H : context [ Safe (appendQ (appendQ ?A ?B) ?C) _ ] |- _ ] =>\n                 rewrite appendQ_assoc with (a := A) (b := B) (c := C) in H\n               | [ H : context [ SafeUntil (appendQ (appendQ ?A ?B) ?C) _ _ ] |- _ ] =>\n                 rewrite appendQ_assoc with (a := A) (b := B) (c := C) in H\n                 \n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ ?X) _ _ _ = Safe (appendQ ?Y ?X) _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ (appendQ _ ?X)) _ _ _ = Safe (appendQ ?Y ?X) _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => rewrite <- appendQ_assoc in H; destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ ?X) _ _ _ = SafeUntil (appendQ ?Y ?X) _ _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ (appendQ _ ?X)) _ _ _ = SafeUntil (appendQ ?Y ?X) _ _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => rewrite <- appendQ_assoc in H; destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : EqNat.beq_nat ?X ?Y = true |- _ ] => \n                 symmetry in H; apply EqNat.beq_nat_eq in H\n               | [ H : Folds.all2 _ _ _ = true |- _ ] => \n                 eapply all2_tvar_seq_dec_true in H\n               | [ H : sym_evalStream _ _ _ _ _ ?QS _ _ _ = _ \n                 , H' : stateD _ _ ?Uall ?Gall _ (_, ?st) _\n                 , H'' : istreamD _ _ _ _ _ ?st _\n                 |- _ ] =>\n               let t := change (QS) with (appendQ QBase QS) in H at 1 ; \n                 eapply IHpath with (env_q := QS) (qs := QBase) (meta_env := Uall) (vars_env := Gall) in H;\n                   simpl; subst; intuition (eauto using istreamD_weaken, Valid_weaken with env_resolution) in\n               solve [ t ] || (t; [])\n               | [ H : forall res : bool, match sym_assertTest _ _ _ _ _ _ _ res with _ => _ end |- _ ] =>\n                 specialize (H true); unfold sym_assertTest in H\n               | [ H : match ?X with | IL.Eq => _ | _ => _ end = None |- _ ] =>\n                 destruct X; congruence\n               | [ H : exists x : state, _ |- exists y : state, _ ] => \n                 let s := fresh \"st\" in \n                 solve [ destruct H as [ s ? ] ; exists s ; intuition ]\n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 (revert H; case_eq X; intros; try contradiction)\n               | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                 (revert H; case_eq X; intros; try split_congruence)\n               | [ H : sym_rvalueD _ _ _ _ = _ |- context [ sym_rvalueD _ _ _ _ ] ] =>\n                   erewrite sym_rvalueD_weaken by eauto\n               | [ H : option bool |- _ ] => destruct H\n             end.\n\n    Lemma evalStream_correct_Safe : forall sound_or_safe cs stn path facts ss qs qs' ss' uvars vars env_q,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = Safe (appendQ qs' env_q) ss' ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        quantD vars_env meta_env qs' (fun vars_env meta_env =>\n          match sound_or_safe with\n            | None => False\n            | Some (st') =>\n              stateD funcs preds meta_env vars_env cs (stn, st') ss'\n          end).\n    Proof.\n      Opaque stateD. \n      induction path; simpl; intros; sym_eval_prover IHpath; try contradiction.\n    Qed.\n\n    Lemma evalStream_correct_SafeUntil : forall sound_or_safe cs stn path facts ss qs qs' ss' is' uvars vars env_q,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = SafeUntil (appendQ qs' env_q) ss' is' ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        quantD vars_env meta_env qs' (fun vars_env meta_env =>\n          exists st' : state,\n          stateD funcs preds meta_env vars_env cs (stn, st') ss' /\\\n          istreamD funcs meta_env vars_env is' stn st' sound_or_safe).\n    Proof.\n      induction path; simpl; intros; sym_eval_prover IHpath; try contradiction. \n    Qed.\n\n(*\n    Theorem evalStream_correct : forall sound_or_safe cs stn path facts ss qs env_q uvars vars res,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = res ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        match res with\n          | Safe qs' ss' =>\n            quantD vars_env meta_env qs' (fun vars_env meta_env =>\n              match sound_or_safe with\n                | None => False\n                | Some (st') => stateD funcs preds meta_env vars_env cs (stn, st') ss'\n              end)\n          | SafeUntil qs' ss' is' =>\n            quantD vars_env meta_env qs' (fun vars_env meta_env =>\n              exists st' : state,\n                stateD funcs preds meta_env vars_env cs (stn, st') ss' /\\\n                istreamD funcs meta_env vars_env is' stn st' sound_or_safe)\n        end.\n    Proof.\n      destruct res; intros.\n      { destruct (sym_evalStream_quant_append _ _ _ _ _ _ H).\n        generalize (@evalStream_correct_Safe sound_or_safe cs stn path facts ss qs (appendQ x qs) s uvars vars env_q). subst.\n        rewrite appendQ_assoc.\n        intro. eapply H0 in H; eauto. }\n      { destruct (sym_evalStream_quant_append _ _ _ _ _ _ H).\n        generalize (@evalStream_correct_SafeUntil sound_or_safe cs stn path facts ss qs (appendQ x qs) s i uvars vars QBase); \n          subst.\n        repeat rewrite appendQ_QBase_r. intro. eapply H0 in H; eauto. }\n    Qed.\n*)\n  End typed2.\n\nEnd SymIL_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/SymILProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16738411008315043}}
{"text": "Require Import Program.Basics Lia.\nFrom PromisingLib Require Import Language.\nFrom hahn Require Import Hahn.\nFrom imm Require Import\n     AuxDef\n     Events Execution TraversalConfig Traversal\n     Prog ProgToExecution ProgToExecutionProperties imm_s imm_s_hb\n     SimState\n     CertExecution2\n     CombRelations SimTraversal SimTraversalProperties.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import EventStructure.\nRequire Import Consistency.\nRequire Import Execution.\nRequire Import EventToAction.\nRequire Import LblStep.\nRequire Import ImmProperties.\nRequire Import CertGraph.\nRequire Import CertRf.\nRequire Import SimRelCont.\nRequire Import SimRelEventToAction.\nRequire Import SimRel.\nRequire Import ProgES.\n\nSet Implicit Arguments.\nLocal Open Scope program_scope.\n\nSection SimRelCert.\n  Variable prog : stable_prog_type.\n  Variable S : ES.t.\n  Variable G : execution.\n  Variable sc : relation actid.\n  Variable TC : trav_config.\n  Variable TC': trav_config.\n  Variable X : eventid -> Prop.\n  Variable T : thread_id -> Prop.\n  Variable k : cont_label.\n\n  (* A state in a continuation related to k in S. *)\n  Variable st : ProgToExecution.state.\n\n  (* A state, which is reachable from 'state' and which represents a graph certification. *)\n  Variable st' : ProgToExecution.state.\n\n  Notation \"'SE'\" := S.(ES.acts_set).\n  Notation \"'SEinit'\" := S.(ES.acts_init_set).\n  Notation \"'SEninit'\" := S.(ES.acts_ninit_set).\n  Notation \"'Stid'\" := (S.(ES.tid)).\n  Notation \"'Slab'\" := (S.(ES.lab)).\n  Notation \"'Sloc'\" := (loc S.(ES.lab)).\n  Notation \"'K'\" := S.(ES.cont_set).\n\n  Notation \"'STid' t\" := (fun x => Stid x = t) (at level 1).\n  Notation \"'SNTid' t\" := (fun x => Stid x <> t) (at level 1).\n\n  Notation \"'SR'\" := (fun a => is_true (is_r Slab a)).\n  Notation \"'SW'\" := (fun a => is_true (is_w Slab a)).\n  Notation \"'SF'\" := (fun a => is_true (is_f Slab a)).\n  Notation \"'SRel'\" := (fun a => is_true (is_rel Slab a)).\n  Notation \"'SAcq'\" := (fun a => is_true (is_acq Slab a)).\n\n  Notation \"'Ssb'\" := (S.(ES.sb)).\n  Notation \"'Scf'\" := (S.(ES.cf)).\n  Notation \"'Sicf'\" := (S.(ES.icf)).\n  Notation \"'Srmw'\" := (S.(ES.rmw)).\n  Notation \"'Sjf'\" := (S.(ES.jf)).\n  Notation \"'Sjfi'\" := (S.(ES.jfi)).\n  Notation \"'Sjfe'\" := (S.(ES.jfe)).\n  Notation \"'Srf'\" := (S.(ES.rf)).\n  Notation \"'Srfi'\" := (S.(ES.rfi)).\n  Notation \"'Srfe'\" := (S.(ES.rfe)).\n  Notation \"'Sco'\" := (S.(ES.co)).\n  Notation \"'Sew'\" := (S.(ES.ew)).\n\n  Notation \"'Srs'\" := (S.(Consistency.rs)).\n  Notation \"'Srelease'\" := (S.(Consistency.release)).\n  Notation \"'Ssw'\" := (S.(Consistency.sw)).\n  Notation \"'Shb'\" := (S.(Consistency.hb)).\n  Notation \"'Secf'\" := (S.(Consistency.ecf)).\n\n  Notation \"'e2a'\" := (e2a S).\n\n  Notation \"'thread_syntax' t\"  :=\n    (Language.syntax (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_st' t\" :=\n    (Language.state (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_init_st' t\" :=\n    (Language.init (thread_lts t)) (at level 10, only parsing).\n\n  Notation \"'thread_cont_st' t\" :=\n    (fun st => existT _ (thread_lts t) st) (at level 10, only parsing).\n\n  Notation \"'GE'\" := G.(acts_set).\n  Notation \"'GEinit'\" := (is_init \u2229\u2081 GE).\n  Notation \"'GEninit'\" := ((set_compl is_init) \u2229\u2081 GE).\n\n  Notation \"'Glab'\" := (Execution.lab G).\n  Notation \"'Gloc'\" := (Events.loc (lab G)).\n  Notation \"'Gtid'\" := (Events.tid).\n\n  Notation \"'GTid' t\" := (fun x => Gtid x = t) (at level 1).\n  Notation \"'GNTid' t\" := (fun x => Gtid x <> t) (at level 1).\n\n  Notation \"'GR'\" := (fun a => is_true (is_r Glab a)).\n  Notation \"'GW'\" := (fun a => is_true (is_w Glab a)).\n  Notation \"'GF'\" := (fun a => is_true (is_f Glab a)).\n\n  Notation \"'GRel'\" := (fun a => is_true (is_rel Glab a)).\n  Notation \"'GAcq'\" := (fun a => is_true (is_acq Glab a)).\n\n  Notation \"'Gsb'\" := (Execution.sb G).\n  Notation \"'Grmw'\" := (Execution.rmw G).\n  Notation \"'Grf'\" := (Execution.rf G).\n  Notation \"'Gco'\" := (Execution.co G).\n\n  Notation \"'Grs'\" := (imm_s_hb.rs G).\n  Notation \"'Grelease'\" := (imm_s_hb.release G).\n  Notation \"'Gsw'\" := (imm_s_hb.sw G).\n  Notation \"'Ghb'\" := (imm_s_hb.hb G).\n\n  Notation \"'C'\"  := (covered TC).\n  Notation \"'I'\"  := (issued TC).\n  Notation \"'C''\"  := (covered TC').\n  Notation \"'I''\"  := (issued TC').\n\n  Notation \"'C''\"  := (covered TC').\n  Notation \"'I''\"  := (issued TC').\n\n  Notation \"'Gvf'\" := (furr G sc).\n\n  Notation \"'kE'\" := (ES.cont_sb_dom S k) (only parsing).\n  Notation \"'ktid'\" := (ES.cont_thread S k) (only parsing).\n  Notation \"'klast'\" := (ES.cont_last S k) (only parsing).\n\n  (* Notation \"'E0'\" := (E0 G TC' ktid). *)\n\n  Notation \"'contG'\" := st.(ProgToExecution.G).\n  Notation \"'certG'\" := st'.(ProgToExecution.G).\n\n  Notation \"'contE'\" := contG.(acts_set).\n  Notation \"'certE'\" := certG.(acts_set).\n\n  Notation \"'certLab'\" := (certLab G st').\n\n  Notation \"'certX'\" := ((X \u2229\u2081 SNTid ktid) \u222a\u2081 kE) (only parsing).\n\n  Definition Kstate (ll : cont_label) (lstate : ProgToExecution.state) :=\n    exists (st : (thread_lts (ES.cont_thread S ll)).(Language.state)),\n      \u27ea SSTATE : lstate = st \u27eb /\\\n      \u27ea KK     : K (ll, existT _ _ st) \u27eb.\n\n  Record simrel_cstate :=\n    { cstate_stable : stable_state st';\n      cstate_cont : Kstate k st;\n      cstate_reachable : (lbl_step ktid)\uff0a st st';\n    }.\n\n  Notation \"'certC'\" := (C' \u2229\u2081 e2a \u25a1\u2081 kE).\n\n  Record simrel_cert :=\n    { sim : simrel_consistent prog S G sc TC X (T \\\u2081 eq ktid);\n\n      tr_step : isim_trav_step G sc ktid TC TC' ;\n\n      cert : cert_graph G sc TC' ktid st' ;\n      cstate : simrel_cstate ;\n\n      ex_ktid_cov : X \u2229\u2081 STid ktid \u2229\u2081 e2a \u22c4\u2081 C \u2286\u2081 kE ;\n      cov_in_ex   : e2a \u22c4\u2081 C \u2229\u2081 kE \u2286\u2081 X ;\n\n      kcond : (\n        \u27ea klast_ex : klast \u2286\u2081 X \u27eb /\\\n        \u27ea kE_sb_cov_iss : e2a \u25a1\u2081 codom_rel (\u2997kE\u2998 \u2a3e Ssb \u2a3e \u2997STid ktid\u2998) \u2286\u2081 CsbI G TC \u27eb\n      ) \\/ (\n        \u27ea klast_sb_max : klast \u2286\u2081 max_elt Ssb \u27eb /\\\n        \u27ea kE_sb_cov_iss : e2a \u25a1\u2081 codom_rel (\u2997kE\u2998 \u2a3e Ssb \u2a3e \u2997STid ktid\u2998) \u2286\u2081 CsbI G TC' \u27eb\n      ) ;\n\n      kE_lab : eq_dom (kE \\\u2081 SEinit) Slab (certG.(lab) \u2218 e2a) ;\n\n      jf_kE_in_cert_rf : e2a \u25a1 (Sjf \u2a3e \u2997kE\u2998) \u2286 cert_rf G sc TC' ;\n\n      icf_ex_ktid_in_co :\n        e2a \u25a1 (Sjf \u2a3e \u2997set_compl kE\u2998 \u2a3e Sicf \u2a3e \u2997X \u2229\u2081 STid ktid\u2998 \u2a3e Sjf\u207b\u00b9) \u2286 Gco ;\n\n      icf_kE_in_co :\n        e2a \u25a1 (Sjf \u2a3e Sicf \u2a3e \u2997kE\u2998 \u2a3e Sjf\u207b\u00b9) \u2286 Gco ;\n\n      ex_cont_iss : X \u2229\u2081 e2a \u22c4\u2081 (contE \u2229\u2081 I) \u2286\u2081 dom_rel (Sew \u2a3e \u2997 kE \u2998) ;\n      kE_iss : kE \u2229\u2081 e2a \u22c4\u2081 I \u2286\u2081 dom_rel (Sew \u2a3e \u2997 X \u2998) ;\n\n      (* e2a_co_kE_iss : e2a \u25a1 (Sco \u2a3e \u2997kE \u2229\u2081 e2a \u22c4\u2081 I'\u2998) \u2286 Gco ;  *)\n\n      e2a_co_kE : e2a \u25a1 (Sco \u2a3e \u2997kE\u2998) \u2286 Gco ;\n\n      e2a_co_ex_ktid : e2a \u25a1 (Sco \u2a3e \u2997X \u2229\u2081 STid ktid \\\u2081 e2a \u22c4\u2081 contE\u2998) \u2286 Gco ;\n\n      rmw_cov_in_kE : Grmw \u2a3e \u2997C' \u2229\u2081 e2a \u25a1\u2081 kE\u2998 \u2286 e2a \u25a1 Srmw \u2a3e \u2997 kE \u2998 ;\n\n      contsimstate_kE :\n          exists kC (state : thread_st (ES.cont_thread S kC)),\n            \u27ea THK   : ES.cont_thread S kC = ktid \u27eb /\\\n            \u27ea INK   : K (kC, thread_cont_st (ES.cont_thread S kC) state) \u27eb /\\\n            \u27ea INX   : ES.cont_sb_dom S kC \u2261\u2081 e2a \u22c4\u2081 C' \u2229\u2081 kE \u27eb /\\\n            \u27ea KINEQ : kE \u2286\u2081 e2a \u22c4\u2081 C' -> kC = k \u27eb /\\\n            \u27ea SIMST : @sim_state G sim_normal certC (ES.cont_thread S kC) state \u27eb;\n    }.\n\n  Section SimRelCertProps.\n\n    Variable SRCC : simrel_cert.\n\n    Lemma cov_in_cert_dom :\n      C \u2286\u2081 cert_dom G TC ktid st.\n    Proof. unfold cert_dom. basic_solver. Qed.\n\n    Lemma GEinit_in_cert_dom (TCCOH : tc_coherent G sc TC) :\n      GEinit \u2286\u2081 cert_dom G TC ktid st.\n    Proof.\n      etransitivity; [|apply cov_in_cert_dom].\n      eapply init_covered; eauto.\n    Qed.\n\n    Lemma cert_dom_sb_prcl :\n      dom_rel (Gsb \u2a3e \u2997 cert_dom G TC ktid st \u2998) \u2286\u2081 cert_dom G TC ktid st.\n    Proof.\n      assert (tc_coherent G sc TC) as TCCOH by apply SRCC.\n      intros x [y SB].\n      destruct_seq_r SB as YY.\n      set (ESB := SB).\n      destruct_seq ESB as [XE YE].\n      destruct YY as [[YY|[YY NTID]]|YY].\n      { apply cov_in_cert_dom. eapply dom_sb_covered; eauto.\n        eexists. apply seq_eqv_r. eauto. }\n      { set (CC := SB). apply sb_tid_init in CC. desf.\n        { left. right. split. 2: by rewrite CC.\n          generalize (@sb_trans G) SB YY. basic_solver 10. }\n        apply cov_in_cert_dom. eapply init_covered; eauto.\n        split; auto. }\n      destruct (classic (is_init x)) as [NN|NINIT].\n      { apply cov_in_cert_dom. eapply init_covered; eauto.\n        split; auto. }\n      right.\n      edestruct cstate_cont as [lstate]; [apply SRCC|]. desf.\n      assert (wf_thread_state (ES.cont_thread S k) lstate) as WFT.\n      { eapply contwf; [by apply SRCC|]. apply KK. }\n      eapply acts_rep in YY; eauto.\n      destruct YY as [yin [REP LE]].\n      rewrite REP in *.\n      destruct x; desf.\n      red in ESB. desf.\n      apply acts_clos; auto.\n      { by subst thread. }\n      etransitivity; eauto.\n    Qed.\n\n    Lemma ktid_ninit :\n      ktid <> tid_init.\n    Proof.\n      edestruct cstate_cont; [apply SRCC|].\n      desc. subst x.\n      intros kTID.\n      edestruct ES.init_tid_K; [apply SRCC|].\n      do 2 eexists. splits; eauto.\n    Qed.\n\n    Lemma cstate_covered :\n      C \u2229\u2081 GTid ktid \u2286\u2081 contE.\n    Proof.\n      edestruct cstate_cont; [apply SRCC|].\n      desc. subst x.\n      intros x [Cx TIDx].\n      eapply e2a_kEninit; eauto; try apply SRCC.\n      assert ((e2a \u25a1\u2081 X) x) as Xx.\n      { eapply ex_cov_iss; [apply SRCC|]. red. basic_solver. }\n      destruct Xx as [x' [Xx' EQx]]. subst x.\n      unfolder; eexists; splits; eauto.\n      { eapply ex_ktid_cov; auto.\n        unfolder; splits; auto.\n        by erewrite e2a_tid. }\n      intros INITx.\n      apply ktid_ninit.\n      rewrite <- TIDx.\n      erewrite <- e2a_tid.\n      apply INITx.\n    Qed.\n\n    Lemma wf_cont_state :\n      wf_thread_state ktid st.\n    Proof.\n      edestruct cstate_cont.\n      { apply SRCC. }\n      eapply contwf; eauto.\n      apply SRCC. desf.\n    Qed.\n\n    Lemma wf_cert_state :\n      wf_thread_state ktid st'.\n    Proof.\n      eapply wf_thread_state_lbl_steps.\n      { eapply wf_cont_state. }\n      apply SRCC.\n    Qed.\n\n    Lemma thread_event_ge_ncov idx (ge : idx >= eindex st) :\n      ~ C (ThreadEvent ktid idx).\n    Proof.\n      intros Cx.\n      assert ((C \u2229\u2081 GTid ktid) (ThreadEvent ktid idx)) as HH.\n      { split; auto. }\n      eapply cstate_covered in HH; eauto.\n      eapply acts_rep in HH; desc.\n      2 : eapply wf_cont_state; eauto.\n      inversion REP. lia.\n    Qed.\n\n    Lemma e2a_ge_ncov e\n          (Se : SE e)\n          (TIDe : Stid e = ktid)\n          (SEQNe : ES.seqn S e >= eindex st) :\n      ~ C (e2a e).\n    Proof.\n      intros Ce.\n      erewrite e2a_ninit in Ce.\n      { eapply thread_event_ge_ncov; eauto.\n        congruence. }\n      split; auto.\n      intros [_ INITe].\n      eapply ktid_ninit.\n      congruence.\n    Qed.\n\n    Lemma trav_step_cov_sb_iss_le :\n      C \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I\u2998) \u2286\u2081 C' \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I'\u2998).\n    Proof.\n      erewrite sim_trav_step_covered_le,\n               sim_trav_step_issued_le.\n      2,3: eexists; apply SRCC.\n      done.\n    Qed.\n\n    Lemma trav_step_cov_sb_iss_tid :\n      C' \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I'\u2998) \u2261\u2081\n         (C \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I\u2998)) \u2229\u2081 GNTid ktid \u222a\u2081\n         (C' \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I'\u2998)) \u2229\u2081 GTid ktid.\n    Proof.\n      edestruct isim_trav_step_new_e_tid_alt as [HA HB].\n      1-2 : apply SRCC.\n      apply set_subset_union_l in HA.\n      destruct HA as [HAC HAI].\n      split.\n      { rewrite crE at 1. relsf. splits.\n        { intros x Cx.\n          apply HAC in Cx.\n          generalize Cx. basic_solver 10. }\n        { intros x Ix.\n          apply HAI in Ix.\n          generalize Ix. basic_solver 10. }\n        rewrite seq_eqv_r.\n        intros x [y [SB Iy]].\n        edestruct tid_set_dec\n          with (thread := ktid)\n          as [_ Htid].\n        edestruct sb_tid_init as [EQtid | INITx]; eauto.\n        { specialize (Htid y (Logic.I)).\n          destruct Htid as [Htid | Htid].\n          { do 2 right. split.\n            { exists y. basic_solver. }\n            congruence. }\n          apply HAI in Iy.\n          destruct Iy as [[[Cy | Iy] _] | [_ TIDy]].\n          { do 2 left. split.\n            { eapply dom_sb_covered.\n              { apply SRCC. }\n              basic_solver 10. }\n            basic_solver. }\n          { left. right. split.\n            { basic_solver 10. }\n            congruence. }\n          exfalso. done. }\n        do 2 left. split.\n        { eapply init_covered.\n          { apply SRCC. }\n          split; auto.\n          apply wf_sbE in SB.\n          generalize SB. basic_solver. }\n        apply is_init_tid in INITx.\n        rewrite INITx.\n        intros HH. by eapply ktid_ninit. }\n      rewrite set_subset_union_l. splits.\n      { erewrite sim_trav_step_covered_le,\n                 sim_trav_step_issued_le.\n        2,3 : eexists; apply SRCC.\n        basic_solver 10. }\n      basic_solver 5.\n    Qed.\n\n    Lemma cert_dom_cov_sb_iss :\n      cert_dom G TC ktid st' \u2261\u2081 C' \u222a\u2081 dom_rel (Gsb^? \u2a3e \u2997I'\u2998).\n    Proof.\n      rewrite cert_dom_alt.\n      { rewrite dcertE; [|apply SRCC].\n        rewrite trav_step_cov_sb_iss_tid.\n        unfold CsbI. basic_solver 10. }\n      etransitivity.\n      { apply cstate_covered; eauto. }\n      eapply steps_preserve_E.\n      { eapply wf_cont_state. }\n      apply lbl_steps_in_steps.\n      apply SRCC.\n    Qed.\n\n    Lemma tccoh' :\n      tc_coherent G sc TC'.\n    Proof. eapply isim_trav_step_coherence; apply SRCC. Qed.\n\n    Lemma kE_inE :\n      kE \u2286\u2081 SE.\n    Proof.\n      edestruct cstate_cont; [apply SRCC|].\n      desc. subst x.\n      intros x kSBx.\n      eapply ES.cont_sb_domE; eauto.\n      apply SRCC.\n    Qed.\n\n    Lemma SEinit_in_kE :\n      SEinit \u2286\u2081 kE.\n    Proof.\n      eapply ES.cont_sb_dom_Einit; [apply SRCC|].\n      edestruct cstate_cont; [apply SRCC|].\n      desf. apply KK.\n    Qed.\n\n    Lemma GEinit_in_e2a_kE :\n      GEinit \u2286\u2081 e2a \u25a1\u2081 kE.\n    Proof.\n      erewrite <- e2a_same_Einit.\n      2-4: by eapply SRCC.\n      apply set_collect_mori; auto.\n      by apply SEinit_in_kE.\n    Qed.\n\n    Lemma cert_ex_inE :\n      certX \u2286\u2081 SE.\n    Proof.\n      unionL.\n      { rewrite Execution.ex_inE\n          with (X := X); [|apply SRCC].\n        basic_solver. }\n      edestruct cstate_cont; [apply SRCC|]. desc.\n      eapply ES.cont_sb_domE; eauto.\n      apply SRCC.\n    Qed.\n\n    Lemma init_in_cert_ex :\n      SEinit \u2286\u2081 certX.\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      assert (Execution.t S X) as EXEC by apply SRCC.\n      edestruct cstate_cont as [st_ [stEQ KK]];\n        [apply SRCC|].\n      red in stEQ, KK. subst st_.\n      rewrite ES.cont_sb_dom_Einit; eauto.\n      basic_solver.\n    Qed.\n\n    Lemma ex_cov_in_certX :\n      X \u2229\u2081 e2a \u22c4\u2081 C \u2286\u2081 certX.\n    Proof.\n      rewrite set_unionC.\n      erewrite ES.set_split_Tid with\n          (S := S) (X := X) (t := ktid) at 1.\n      rewrite set_inter_union_l.\n      apply set_union_Proper.\n      { by apply ex_ktid_cov. }\n      basic_solver.\n    Qed.\n\n    Lemma cert_ex_certD :\n      e2a \u25a1\u2081 certX \u2261\u2081 cert_dom G TC ktid st.\n    Proof.\n      assert (ES.Wf S) as WFS.\n      { apply SRCC. }\n      assert (Execution.t S X) as EXEC.\n      { apply SRCC. }\n      edestruct cstate_cont; [apply SRCC|].\n      desc. subst x.\n      rewrite cert_dom_alt.\n      2 : apply cstate_covered; apply SRCC.\n      rewrite set_collect_union.\n      rewrite e2a_kE; eauto; try apply SRCC.\n      rewrite <- set_unionA.\n      erewrite set_union_absorb_r\n        with (s := GEinit).\n      { rewrite ex_NTid.\n        apply set_union_Propere; auto.\n        apply set_inter_Propere; auto.\n        eapply ex_cov_iss. apply SRCC. }\n      rewrite <- e2a_same_Einit; try apply SRCC.\n      apply set_collect_mori; auto.\n      apply set_subset_inter_r. split.\n      { by apply Execution.init_in_ex. }\n      intros x [_ NTIDx] TIDx.\n      eapply ktid_ninit.\n      congruence.\n    Qed.\n\n    Lemma ex_in_certD :\n      e2a \u25a1\u2081 X \u2286\u2081 cert_dom G TC ktid st'.\n    Proof.\n      assert (ES.Wf S) as WFS.\n      { apply SRCC. }\n      assert (Execution.t S X) as EXEC.\n      { apply SRCC. }\n      assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n      { apply SRCC. }\n      rewrite ex_cov_iss; eauto.\n      rewrite cert_dom_cov_sb_iss.\n      apply trav_step_cov_sb_iss_le.\n    Qed.\n\n    Lemma ex_in_e2a_certD :\n      X \u2286\u2081 e2a \u22c4\u2081 cert_dom G TC ktid st'.\n    Proof.\n      rewrite set_in_map_collect\n        with (s := X) (f := e2a).\n      by rewrite ex_in_certD.\n    Qed.\n\n    Lemma ex_cov_iss_cert_lab :\n      eq_dom (X \u2229\u2081 e2a \u22c4\u2081 (C \u222a\u2081 I)) Slab (certLab \u2218 e2a).\n    Proof.\n      intros x [Xx e2aCsbIx].\n      erewrite ex_cov_iss_lab;\n        [ | apply SRCC | done].\n      unfold compose.\n      symmetry. eapply cslab.\n      { apply SRCC. }\n      eapply CI_in_D.\n      eapply isim_trav_step_new_e_tid.\n      1,2: apply SRCC.\n      basic_solver.\n    Qed.\n\n    Lemma kE_cert_lab :\n      eq_dom kE Slab (certLab \u2218 e2a).\n    Proof.\n      assert (ES.Wf S) as WFS.\n      { apply SRCC. }\n      assert (Execution.t S X) as EXEC.\n      { apply SRCC. }\n      edestruct cstate_cont; [apply SRCC|].\n      desc. subst x.\n      intros x kSBx.\n      unfold compose.\n      assert (SE x) as SEx.\n      { by apply kE_inE. }\n      assert ((e2a \u25a1\u2081 kE) (e2a x)) as e2akEx.\n      { basic_solver. }\n      eapply e2a_kE in e2akEx;\n        eauto; try apply SRCC.\n      destruct e2akEx as [INITx | CONTEx].\n      { assert (C (e2a x)) as Cx.\n        { eapply init_covered; eauto. apply SRCC. }\n        erewrite ex_cov_iss_lab; [| apply SRCC |].\n        { erewrite cslab; [auto | apply SRCC |].\n          eapply C_in_D.\n          eapply SimTraversalProperties.sim_trav_step_covered_le;\n            eauto.\n          econstructor. apply SRCC. }\n        split; [|basic_solver].\n        eapply Execution.init_in_ex; eauto.\n        set (INITx' := INITx).\n        eapply e2a_same_Einit in INITx'; try apply SRCC.\n        unfolder in INITx'.\n        destruct INITx' as [y [INITy e2aEQ]].\n        eapply e2a_map_Einit.\n        split; eauto. }\n      assert (certE (e2a x)) as CERTEx.\n      { eapply steps_preserve_E; eauto.\n        { apply wf_cont_state. }\n        apply lbl_steps_in_steps.\n        apply SRCC. }\n      unfold CertGraph.certLab.\n      erewrite restr_fun_fst; auto.\n      apply kE_lab; auto.\n      split; auto.\n      intros INITx.\n      assert (GEinit (e2a x)) as GINITx.\n      { eapply e2a_same_Einit.\n        1-2: by apply SRCC.\n        basic_solver. }\n      edestruct acts_rep.\n      { apply wf_cont_state. }\n      { apply CONTEx. }\n      unfolder in GINITx.\n      unfold is_init in GINITx.\n      desf.\n    Qed.\n\n    Lemma cert_ex_cov_iss_lab :\n      eq_dom (certX \u2229\u2081 e2a \u22c4\u2081 (C' \u222a\u2081 I')) Slab (Glab \u2218 e2a).\n    Proof.\n      rewrite set_inter_union_l.\n      apply eq_dom_union. split.\n      { arewrite (X \u2229\u2081 SNTid ktid \u2229\u2081 e2a \u22c4\u2081 (C' \u222a\u2081 I') \u2286\u2081\n                  X \u2229\u2081 e2a \u22c4\u2081 (C \u222a\u2081 I)).\n        { erewrite isim_trav_step_new_e_tid_alt.\n          2,3: apply SRCC.\n          rewrite set_map_union.\n          rewrite set_inter_union_r.\n          rewrite set_subset_union_l.\n          splits.\n          { basic_solver. }\n          intros x [[_ nTIDx] [_ TIDx]].\n          exfalso. apply nTIDx.\n          by rewrite e2a_tid. }\n        eapply ex_cov_iss_lab. apply SRCC. }\n      intros x [KSBx e2aCsbIx].\n      erewrite kE_cert_lab; auto.\n      unfold compose.\n      erewrite <- cslab\n        with (G := G); [auto | apply SRCC|].\n      apply CI_in_D.\n      basic_solver.\n    Qed.\n\n    Lemma cert_ex_cov_iss_cert_lab :\n      eq_dom (certX \u2229\u2081 e2a \u22c4\u2081 (C' \u222a\u2081 I')) Slab (certLab \u2218 e2a).\n    Proof.\n      intros x [KSBx e2aCsbIx].\n      erewrite cert_ex_cov_iss_lab.\n      2 : basic_solver.\n      unfold compose.\n      erewrite <- cslab;\n        [eauto | apply SRCC |].\n      apply CI_in_D.\n      basic_solver.\n    Qed.\n\n    Lemma cert_ex_iss_inW :\n      certX \u2229\u2081 e2a \u22c4\u2081 I' \u2286\u2081 SW.\n    Proof.\n      intros x [CertXx Ix].\n      red in Ix.\n      unfold is_w.\n      erewrite cert_ex_cov_iss_lab; auto.\n      { unfold compose.\n        eapply issuedW; eauto.\n        apply tccoh'. }\n      split; auto.\n      basic_solver.\n    Qed.\n\n    Lemma ex_ntid_sb_prcl :\n      dom_rel (Ssb \u2a3e \u2997 X \u2229\u2081 SNTid ktid \u2998) \u2286\u2081 SEinit \u222a\u2081 X \u2229\u2081 SNTid ktid.\n    Proof.\n      assert (ES.Wf S) as WFS.\n      { apply SRCC. }\n      rewrite seq_eqv_r.\n      intros x [y [SB [Xx NTIDy]]].\n      edestruct ES.NTid_sb_prcl\n        as [INITx | NTIDx]; eauto.\n      { basic_solver 10. }\n      { by left. }\n      right. split; auto.\n      eapply Execution.ex_sb_prcl; [apply SRCC|].\n      basic_solver 10.\n    Qed.\n\n    Lemma kE_sb_prcl :\n      dom_rel (Ssb \u2a3e \u2997 kE \u2998) \u2286\u2081 kE.\n    Proof.\n      edestruct cstate_cont; [apply SRCC|].\n      eapply ES.cont_sb_prcl; [apply SRCC|].\n      desc. apply KK.\n    Qed.\n\n    Lemma cert_ex_sb_prcl :\n      dom_rel (Ssb \u2a3e \u2997 certX \u2998) \u2286\u2081 certX.\n    Proof.\n      rewrite id_union.\n      relsf. split.\n      { rewrite ex_ntid_sb_prcl.\n        rewrite init_in_cert_ex.\n        basic_solver. }\n      rewrite kE_sb_prcl.\n      basic_solver.\n    Qed.\n\n    Lemma ex_ntid_sb_cov_iss :\n      forall t (Tt : (T \\\u2081 eq ktid) t),\n        e2a \u25a1\u2081 codom_rel (\u2997X\u2998 \u2a3e Ssb \u2a3e \u2997STid t\u2998) \u2286\u2081 CsbI G TC'.\n    Proof.\n      ins.\n      erewrite <- sim_trav_step_CsbI_mon.\n      2,3: try eexists; apply SRCC.\n      erewrite ex_sb_cov_iss.\n      1-2: eauto; apply SRCC.\n      done.\n    Qed.\n\n    Lemma kE_sb_cov_iss :\n      e2a \u25a1\u2081 codom_rel (\u2997kE\u2998 \u2a3e Ssb \u2a3e \u2997STid ktid\u2998) \u2286\u2081 CsbI G TC'.\n    Proof.\n      edestruct kcond; eauto; desc; try done.\n      erewrite <- sim_trav_step_CsbI_mon.\n      2,3: try eexists; apply SRCC.\n      done.\n    Qed.\n\n    Lemma cert_ex_sb_cov_iss :\n      forall t (Tt : T t),\n        e2a \u25a1\u2081 codom_rel (\u2997certX\u2998 \u2a3e Ssb \u2a3e \u2997STid t\u2998) \u2286\u2081 CsbI G TC'.\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      assert (Execution.t S X) as EXEC by apply SRCC.\n      edestruct cstate_cont as [st_ [stEQ KK]];\n        [apply SRCC|].\n      red in stEQ, KK. ins.\n      rewrite id_union,\n              seq_union_l,\n              codom_union,\n              set_collect_union.\n      destruct\n        (classic (t = ktid))\n        as [EQ|nEQ];\n        relsf; split; try subst t.\n      { rewrite seq_eqv_lr.\n        intros y' [y [HH EQy']].\n        destruct HH as [x [[Xx nTIDx] [SB TIDy]]].\n        subst y'.\n        eapply kE_sb_cov_iss; eauto.\n        eexists; split; eauto.\n        assert\n          (exists e, SEinit e /\\ Ssb e y)\n          as [e [INITe SB']].\n        { assert (SE x) as Ex.\n          { eapply Execution.ex_inE; eauto. }\n          eapply ES.acts_set_split in Ex.\n          destruct Ex as [INITx | nINITx].\n          { exists x; split; auto. }\n          edestruct ES.exists_acts_init\n            as [e INITe]; eauto.\n          exists e.\n          splits; auto.\n          eapply ES.sb_trans; eauto.\n          eapply ES.sb_init; eauto.\n          split; auto. }\n        exists e.\n        apply seq_eqv_lr; split; auto.\n        eapply ES.cont_sb_dom_Einit; eauto. }\n      { eapply kE_sb_cov_iss; eauto. }\n      { arewrite\n          (SNTid (ES.cont_thread S k) \u2286\u2081 fun _ => True).\n        relsf. eapply ex_ntid_sb_cov_iss.\n        basic_solver. }\n      erewrite ES.cont_sb_tid; eauto.\n      rewrite id_union,\n              seq_union_l,\n              codom_union,\n              set_collect_union.\n      rewrite set_subset_union_l. split.\n      { erewrite Execution.init_in_ex; eauto.\n        eapply ex_ntid_sb_cov_iss; eauto.\n        basic_solver. }\n      rewrite seq_eqv_lr.\n      intros x' [x [HH EQx']].\n      destruct HH as [y [nTIDx [SB TIDy]]].\n      exfalso.\n      assert (Stid y = Stid x)\n        as HH; [|congruence].\n      eapply ES.sb_tid; eauto.\n      unfold ES.acts_ninit_set.\n      apply seq_eqv_l; unfolder; splits; auto.\n      { apply ES.sbE in SB; auto.\n        generalize SB. basic_solver. }\n      intros [_ INITy].\n      eapply ktid_ninit; eauto.\n      congruence.\n    Qed.\n\n    Lemma certX_ncf_cont :\n      certX \u2229\u2081 ES.cont_cf_dom S k \u2261\u2081 \u2205.\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      edestruct cstate_cont as [st_ [stEQ KK]];\n        [apply SRCC|].\n      red; split; [|done].\n      rewrite set_inter_union_l.\n      apply set_subset_union_l; split.\n      { rewrite ES.cont_cf_Tid_; eauto. basic_solver. }\n      eapply ES.cont_sb_cont_cf_inter_false; eauto.\n    Qed.\n\n    Lemma cert_ex_ncf :\n      ES.cf_free S certX.\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      assert (Execution.t S X) as EXEC by apply SRCC.\n      edestruct cstate_cont as [st_ [stEQ KK]];\n        [apply SRCC|].\n      red in stEQ, KK. subst st_.\n      red. rewrite <- restr_relE.\n      intros x y [CF [CERTXx CERTXy]].\n      destruct CERTXx as [[Xx NTIDx] | kSBx];\n      destruct CERTXy as [[Xy NTIDy] | kSBy].\n      { eapply Execution.ex_ncf; [apply SRCC|].\n        apply restr_relE. red. eauto. }\n      { eapply ES.cont_sb_tid in kSBy; eauto.\n        destruct kSBy as [INITy | TIDy].\n        { eapply Execution.ex_ncf; [apply SRCC|].\n          apply restr_relE. red. splits; eauto.\n          eapply Execution.init_in_ex; eauto. }\n        apply NTIDx.\n        erewrite ES.cf_same_tid; eauto. }\n      { eapply ES.cont_sb_tid in kSBx; eauto.\n        destruct kSBx as [INITx | TIDx].\n        { eapply Execution.ex_ncf; [apply SRCC|].\n          apply restr_relE. red. splits; eauto.\n          eapply Execution.init_in_ex; eauto. }\n        apply NTIDy.\n        erewrite ES.cf_same_tid; eauto.\n        by apply ES.cf_sym. }\n      eapply ES.cont_sb_cf_free; eauto.\n      apply seq_eqv_lr. eauto.\n    Qed.\n\n  Lemma jf_cert_ex_in_cert_rf :\n    e2a \u25a1 (Sjf \u2a3e \u2997certX\u2998) \u2286 cert_rf G sc TC'.\n  Proof.\n    rewrite id_union.\n    relsf. unionL.\n    2 : apply jf_kE_in_cert_rf; auto.\n    rewrite <- set_interK\n      with (s := X).\n    rewrite set_interA, <- seq_eqv.\n    rewrite <- seqA.\n    rewrite collect_rel_seqi,\n    collect_rel_eqv.\n    rewrite jf_ex_in_cert_rf;\n      [|apply SRCC].\n    erewrite ex_NTid.\n    arewrite (e2a \u25a1\u2081 X \u2286\u2081 fun _ => True).\n    relsf.\n    eapply isim_trav_step_cert_rf_ntid;\n      try apply SRCC.\n    apply ktid_ninit; auto.\n  Qed.\n\n  Lemma icf_certX_in_co :\n    forall t (Tt : T t),\n      e2a \u25a1 (Sjf \u2a3e Sicf \u2a3e \u2997certX \u2229\u2081 STid t\u2998 \u2a3e Sjf\u207b\u00b9) \u2286 Gco.\n  Proof.\n    intros t Tt.\n    rewrite set_inter_union_l.\n    rewrite id_union.\n    relsf. unionL.\n    { destruct (classic (t = ktid))\n        as [EQ|nEQ].\n      { basic_solver. }\n      arewrite (SNTid ktid \u2286\u2081 fun _ => True).\n      relsf.\n      eapply icf_ex_in_co; [apply SRCC|].\n      basic_solver. }\n    arewrite (STid t \u2286\u2081 fun _ => True).\n    relsf.\n    eapply icf_kE_in_co; eauto.\n  Qed.\n\n  Lemma ew_ex_cert_dom_iss_cert_ex_iss :\n    dom_rel (Sew \u2a3e \u2997X \u2229\u2081 e2a \u22c4\u2081 (cert_dom G TC ktid st \u2229\u2081 I)\u2998) \u2261\u2081\n    dom_rel (Sew \u2a3e \u2997certX \u2229\u2081 e2a \u22c4\u2081 I\u2998).\n  Proof.\n    assert (ES.Wf S) as WFS.\n    { apply SRCC. }\n    assert (Execution.t S X) as EXEC.\n    { apply SRCC. }\n    assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n    { apply SRCC. }\n    rewrite cert_dom_alt.\n    2 : apply cstate_covered.\n    split.\n\n    { rewrite !set_map_inter,\n      !set_map_union,\n      !set_map_inter.\n      rewrite !set_inter_union_l,\n      !set_inter_union_r.\n      rewrite id_union. relsf.\n      splits.\n      { rewrite !seq_eqv_r with (r := Sew).\n        intros x [y [EW [Xx [[_ nTIDx] Ix]]]].\n        exists y; splits; auto.\n        unfolder; left; splits; auto.\n        intros TIDy. apply nTIDx.\n        erewrite <- e2a_tid; eauto. }\n      rewrite !seq_eqv_r with (r := Sew).\n      intros x [y [EW [Xx [CONTx Ix]]]].\n      edestruct ex_cont_iss\n        as [z HH]; eauto.\n      { unfolder; split; eauto. }\n      apply seq_eqv_r in HH.\n      destruct HH as [EW' kSB].\n      exists z; splits; auto.\n      { eapply ES.ew_trans; eauto. }\n      unfolder; right; splits; auto.\n      arewrite (e2a z = e2a y); auto.\n      symmetry.\n      eapply e2a_ew; eauto.\n      { apply SRCC. }\n      basic_solver 10. }\n\n    rewrite set_inter_union_l, id_union.\n    rewrite seq_union_r, dom_union.\n    unionL.\n    { rewrite !seq_eqv_r with (r := Sew).\n      intros x [y [EW [[Xx nTIDx] Ix]]].\n      exists y; splits; auto.\n      split; auto.\n      split; auto.\n      left; split; auto.\n      { eapply ex_cov_iss; eauto. basic_solver. }\n      intros TIDx. apply nTIDx.\n      erewrite e2a_tid; eauto. }\n    rewrite !seq_eqv_r with (r := Sew).\n    intros x [y [EW [kSBy Iy]]].\n    edestruct kE_iss\n      as [z HH]; eauto.\n    { unfolder; split; eauto. }\n    apply seq_eqv_r in HH.\n    destruct HH as [EW' Xz].\n    exists z; splits; auto.\n    { eapply ES.ew_trans; eauto. }\n    split; auto.\n    assert (e2a z = e2a y) as EQzy.\n    { symmetry. eapply e2a_ew; eauto.\n      { apply SRCC. }\n      basic_solver 10. }\n    red; split.\n    2 : red in Iy; congruence.\n    assert (SE z) as Ez.\n    { apply ES.ewE in EW'; auto.\n      generalize EW'. basic_solver. }\n    set (Ez' := Ez).\n    apply ES.acts_set_split in Ez'.\n    destruct Ez' as [INITz | nINITz].\n    { left; split; try left.\n      { eapply init_covered.\n        { apply SRCC. }\n        eapply e2a_same_Einit.\n        1-2: apply SRCC.\n        basic_solver. }\n      intros TIDz.\n      eapply ktid_ninit.\n      destruct INITz as [_ INITz].\n      rewrite <- TIDz.\n      erewrite <- e2a_tid; eauto. }\n\n    right.\n    edestruct cstate_cont as [st_ [stEQ KK]];\n      [apply SRCC|].\n    red in stEQ, KK. subst st_.\n    eapply e2a_kEninit; eauto.\n    { apply SRCC. }\n    exists y; splits; eauto.\n    split; auto.\n    intros INITy.\n    apply nINITz.\n    split; auto.\n    erewrite <- ES.ew_tid; eauto.\n    by destruct INITy as [_ TIDy].\n  Qed.\n\n  Lemma e2a_co_cert_ex_tid :\n    forall t (Tt : T t),\n      e2a \u25a1 (Sco \u2a3e \u2997certX \u2229\u2081 STid t\u2998) \u2286 Gco.\n  Proof.\n    assert (ES.Wf S) as WFS.\n    { apply SRCC. }\n    assert (Execution.t S X) as EXEC.\n    { apply SRCC. }\n    assert (simrel_e2a S G sc) as SRE2A.\n    { apply SRCC. }\n    assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n    { apply SRCC. }\n    intros t Tt.\n    rewrite set_inter_union_l.\n    rewrite id_union.\n    relsf. unionL.\n    { destruct (classic (t = ktid))\n        as [EQ|nEQ].\n      { basic_solver. }\n      arewrite (SNTid ktid \u2286\u2081 fun _ => True).\n      relsf.\n      eapply e2a_co_ex_tid; [apply SRCC|].\n      basic_solver. }\n    arewrite (STid t \u2286\u2081 fun _ => True).\n    relsf.\n    eapply e2a_co_kE; eauto.\n  Qed.\n\n  Lemma e2a_co_cert_ex_iss :\n    e2a \u25a1 (Sco \u2a3e \u2997certX \u2229\u2081 e2a \u22c4\u2081 I'\u2998) \u2286 Gco.\n  Proof.\n    assert (ES.Wf S) as WFS.\n    { apply SRCC. }\n    assert (Execution.t S X) as EXEC.\n    { apply SRCC. }\n    assert (simrel_e2a S G sc) as SRE2A.\n    { apply SRCC. }\n    assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n    { apply SRCC. }\n    rewrite set_inter_union_l, id_union, seq_union_r,\n            collect_rel_union.\n    unionL.\n    { rewrite seq_eqv_r.\n      intros x' y' [x [y [HH [EQx' EQy']]]].\n      destruct HH as [CO [[Xy nTIDy] Iy]].\n      red in Iy.\n      eapply isim_trav_step_new_issued_tid in Iy.\n      2-3: apply SRCC.\n      destruct Iy as [[Iy _]|[Iy TIDy]].\n      { eapply e2a_co_iss; eauto. basic_solver 10. }\n      exfalso. apply nTIDy.\n      by erewrite e2a_tid. }\n    arewrite (e2a \u22c4\u2081 I' \u2286\u2081 fun _ => True).\n    relsf. by eapply e2a_co_kE.\n  Qed.\n\n    (* Lemma ex_iss_cert_ex : *)\n    (*   X \u2229\u2081 e2a \u22c4\u2081 (cert_dom G TC ktid st \u2229\u2081 I) \u2286\u2081  *)\n    (*     dom_rel (Sew \u2a3e \u2997certX \u2229\u2081 e2a \u22c4\u2081 I\u2998). *)\n    (* Proof.  *)\n    (*   assert (ES.Wf S) as WFS. *)\n    (*   { apply SRCC. } *)\n    (*   assert (Execution.t S X) as EXEC. *)\n    (*   { apply SRCC. } *)\n    (*   assert (simrel prog S G sc TC X) as SR_. *)\n    (*   { apply SRCC. } *)\n    (*   rewrite cert_dom_alt. *)\n    (*   2 : apply cstate_covered. *)\n    (*   rewrite !set_map_inter,  *)\n    (*           !set_map_union, *)\n    (*           !set_map_inter. *)\n    (*   rewrite !set_inter_union_l,  *)\n    (*           !set_inter_union_r, *)\n    (*           !set_subset_union_l. *)\n    (*   rewrite id_union. relsf. *)\n    (*   splits. *)\n    (*   { intros x [Xx [[_ nTIDx] Ix]]. *)\n    (*     left. exists x. *)\n    (*     apply seq_eqv_r. *)\n    (*     unfold set_inter.  *)\n    (*     splits; auto. *)\n    (*     { apply ES.ew_refl; auto. *)\n    (*       unfolder; splits; auto. *)\n    (*       { eapply Execution.ex_inE; eauto. } *)\n    (*       eapply ex_iss_inW; eauto. *)\n    (*       red. auto. } *)\n    (*     intros TIDx. apply nTIDx.  *)\n    (*     by rewrite <- e2a_tid. } *)\n    (*   intros x [Xx [CONTx Ix]]. *)\n    (*   edestruct ex_cont_iss *)\n    (*     as [z HH]; eauto. *)\n    (*   { unfolder; split; eauto. } *)\n    (*   apply seq_eqv_r in HH. *)\n    (*   destruct HH as [EW kSB]. *)\n    (*   right. exists z. *)\n    (*   apply seq_eqv_r. *)\n    (*   unfold set_inter. *)\n    (*   splits; auto. *)\n    (*   red. erewrite e2a_ew; eauto. *)\n    (*   { apply SRCC. } *)\n    (*   do 2 eexists. splits. *)\n    (*   2,3: eauto. *)\n    (*   apply ES.ew_sym; auto. *)\n    (* Qed. *)\n\n    Lemma rel_ew_cert_ex :\n      dom_rel (Srelease \u2a3e Sew \u2a3e \u2997 certX \u2998) \u2286\u2081 certX.\n    Proof.\n      rewrite ew_in_ew_ex_iss_ew; [|apply SRCC].\n      rewrite crE, !seq_union_l, !seq_union_r,\n              !dom_union, !seqA.\n      relsf. split.\n      { rewrite rel_in_ex_cov_rel_sb; [|apply SRCC].\n        relsf. rewrite !seqA. splits.\n        { rewrite dom_seq, dom_eqv.\n          apply ex_cov_in_certX. }\n        rewrite set_unionC.\n        rewrite id_union, !seq_union_r, dom_union.\n        rewrite crE, !seq_union_l, !dom_union.\n        unionL.\n        1,3 : basic_solver.\n        { erewrite kE_sb_prcl. basic_solver. }\n        erewrite ex_ntid_sb_prcl.\n        apply set_union_Proper; auto.\n        apply SEinit_in_kE. }\n      do 2 rewrite <- seqA.\n      rewrite dom_seq, !seqA.\n      rewrite rel_ew_ex_iss_cov; [|apply SRCC].\n      apply ex_cov_in_certX.\n    Qed.\n\n    Lemma cert_ex_sw_prcl :\n      dom_rel (Ssw \u2a3e \u2997 certX \u2998) \u2286\u2081 certX.\n    Proof.\n      assert (ES.Wf S) as WFS.\n      { apply SRCC. }\n      assert (Execution.t S X) as EXEC.\n      { apply SRCC. }\n      assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n      { apply SRCC. }\n      rewrite sw_in_ex_cov_sw_sb; eauto.\n      relsf. splits.\n      2 : apply cert_ex_sb_prcl.\n      rewrite seqA, dom_seq, dom_eqv.\n      apply ex_cov_in_certX.\n    Qed.\n\n    Lemma cert_ex_hb_prcl :\n      dom_rel (Shb \u2a3e \u2997 certX \u2998) \u2286\u2081 certX.\n    Proof.\n      unfold hb.\n      rewrite seq_eqv_r.\n      intros x [y [HB yX]].\n      induction HB as [x y [SSB | SSW] | ]; auto.\n      { apply cert_ex_sb_prcl; auto. basic_solver 10. }\n      apply cert_ex_sw_prcl; auto. basic_solver 10.\n    Qed.\n\n    Lemma hb_rel_ew_cert_ex :\n      dom_rel (Shb^? \u2a3e Srelease \u2a3e Sew \u2a3e \u2997 certX \u2998) \u2286\u2081 certX.\n    Proof.\n      rewrite crE with (r := Shb).\n      relsf. split.\n      { by apply rel_ew_cert_ex. }\n      intros x [y [z [HB REL]]].\n      eapply cert_ex_hb_prcl; auto.\n      eexists. apply seq_eqv_r. split; eauto.\n      apply rel_ew_cert_ex; auto. basic_solver.\n    Qed.\n\n    Lemma jf_kE_in_ew_cert_ex :\n      dom_rel (Sjf \u2a3e \u2997 kE \u2998) \u2286\u2081 dom_rel (Sew \u2a3e \u2997 certX \u2998).\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      rewrite ES.jfi_union_jfe. relsf. splits.\n      { arewrite (Sjfi \u2261 \u2997 SE \u2229\u2081 SW \u2998 \u2a3e Sjfi).\n        { rewrite ES.jfiE, ES.jfiD; auto. basic_solver. }\n        rewrite dom_eqv1.\n        arewrite (Sjfi \u2286 Ssb).\n        rewrite kE_sb_prcl.\n        rewrite <- ES.ew_refl; auto.\n        basic_solver 10. }\n      rewrite !seq_eqv_r.\n      intros x [y [JFE KSB]].\n      edestruct jfe_ex_iss as [z HH].\n      { apply SRCC. }\n      { red. eauto. }\n      apply seq_eqv_r in HH.\n      destruct HH as [EW [Xz Iz]].\n      eexists.\n      splits; eauto.\n      left. split; auto.\n      eapply jfe_alt in JFE; auto.\n      2 : apply SRCC.\n      unfolder in JFE.\n      destruct JFE as [nINITx [JF nSTID]].\n      intros TIDz. apply nSTID. red.\n      arewrite (Stid x = Stid z) by (by apply ES.ew_tid).\n      edestruct cstate_cont; [apply SRCC|]. desc.\n      eapply ES.cont_sb_tid in KSB; eauto.\n      destruct KSB as [INITy | TIDy].\n      { exfalso. eapply ES.jf_nEinit; eauto. basic_solver. }\n      congruence.\n    Qed.\n\n    Lemma kE_rf_compl :\n      kE \u2229\u2081 SR \u2286\u2081 codom_rel (\u2997certX\u2998 \u2a3e Srf).\n    Proof.\n      assert (ES.Wf S) as WFS by apply SRCC.\n      assert (Execution.t S X) as EXEC by apply SRCC.\n      edestruct cstate_cont as [st_ [stEQ KK]];\n        [apply SRCC|].\n      red in stEQ, KK. subst st_.\n      intros x [kSBx Rx].\n      edestruct ES.jf_complete\n        as [y JF]; eauto.\n      { split; eauto.\n        eapply ES.cont_sb_domE; eauto. }\n      edestruct jf_kE_in_ew_cert_ex\n        as [z HH].\n      { basic_solver 10. }\n      apply seq_eqv_r in HH.\n      destruct HH as [EW CERTXz].\n      exists z. apply seq_eqv_l.\n      splits; auto.\n      unfold ES.rf.\n      unfolder. splits.\n      { eexists; splits; eauto.\n        by apply ES.ew_sym. }\n      intros CF.\n      destruct CERTXz as [[Xz nTIDz] | kSBz].\n      { eapply ES.cont_sb_tid in kSBx; eauto.\n        destruct kSBx as [INITx | TIDx].\n        { eapply ES.ncfEinit_r. basic_solver. }\n        apply nTIDz.\n        apply ES.cf_same_tid in CF.\n        congruence. }\n      eapply ES.cont_sb_cf_free; eauto.\n      basic_solver.\n    Qed.\n\n    Lemma cert_ex_necf :\n      restr_rel certX Secf \u2286 \u2205\u2082.\n    Proof.\n      unfold restr_rel, ecf.\n      intros a b [ECF [Hx Hy]].\n      destruct ECF as [c [tHB [d [CF HB]]]].\n      eapply cert_ex_ncf.\n      apply restr_relE. unfold restr_rel.\n      splits; eauto.\n      { unfolder in tHB; desf.\n        eapply cert_ex_hb_prcl; auto. basic_solver 10. }\n      unfolder in HB; desf.\n      eapply cert_ex_hb_prcl; auto. basic_solver 10.\n    Qed.\n\n    Lemma ex_cov_ntid_vis :\n      X \u2229\u2081 e2a \u22c4\u2081 C \u222a\u2081 X \u2229\u2081 SNTid ktid \u2286\u2081 vis S.\n    Proof.\n      rewrite <- set_inter_union_r.\n      erewrite <- Execution.ex_vis.\n      2: apply SRCC.\n      basic_solver.\n    Qed.\n\n    Lemma e2a_co_jfe_kE :\n      e2a \u25a1 Sco \u2a3e Sjfe \u2a3e \u2997kE\u2998 \u2286 Gco \u2a3e cert_rf G sc TC'.\n    Proof.\n      assert (simrel_e2a S G sc) as SRE2A.\n      { apply SRCC. }\n      assert (simrel prog S G sc TC X (T \\\u2081 eq ktid)) as SR_.\n      { apply SRCC. }\n      rewrite seq_eqv_r.\n      intros x' y' [x [y [HH [EQx' EQy']]]].\n      destruct HH as [z [CO [JFE kSB]]].\n      subst x' y'.\n      exists (e2a z). split.\n      { edestruct jfe_ex_iss\n          as [z' HH]; eauto.\n        { basic_solver. }\n        apply seq_eqv_r in HH.\n        destruct HH as [EW [Xz' Iz']].\n        arewrite (e2a z = e2a z').\n        { eapply e2a_ew; eauto. basic_solver 10. }\n        eapply e2a_co_ew_iss; eauto.\n        basic_solver 10. }\n      eapply jf_kE_in_cert_rf; auto.\n      exists z, y; splits; auto.\n      apply seq_eqv_r.\n      splits; auto.\n      apply JFE.\n    Qed.\n\n  End SimRelCertProps.\n\nEnd SimRelCert.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/SimRelCert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16718223392374582}}
{"text": "Require Import Ensembles.\nRequire Import AST.\nRequire Import Floats.\nRequire Import Metatheory.\nRequire Import alist.\nRequire Import monad.\nRequire Import targetdata.\nRequire Import genericvalues.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import syntax.\nRequire Import typings.\nRequire Import static.\nRequire Import opsem.\nRequire Import opsem_props.\nRequire Import opsem_wf.\nRequire Import vellvm_tactics.\n\nImport LLVMsyntax.\nImport LLVMgv.\nImport LLVMtd.\nImport LLVMtypings.\n\n(* This file defines the non-deterministic instance of Vellvm's operational \n   semantics. *)\n\n(* NDGVs implements the signature of GenericValues. *)\nModule MNDGVs.\n\nLemma singleton_inhabited : forall U (x:U), Inhabited U (Singleton U x).\nProof.\n  intros. apply Inhabited_intro with (x:=x); auto using In_singleton.\nQed.\n\nLemma full_set_inhabited : forall U,\n  (exists x:U, True) -> Inhabited U (Full_set U).\nProof.\n  intros. inversion H.\n  apply Inhabited_intro with (x:=x); auto using Full_intro.\nQed.\n\nDefinition t := Ensemble GenericValue.\nDefinition instantiate_gvs (gv : GenericValue) (gvs : t) : Prop :=\n  Ensembles.In _ gvs gv.\nDefinition inhabited (gvs : t) : Prop := Ensembles.Inhabited _ gvs.\nHint Unfold instantiate_gvs inhabited.\nDefinition cundef_gvs gv ty : t :=\nmatch ty with\n| typ_int sz => fun gv => exists z, gv = (Vint (sz-1) z, Mint (sz - 1))::nil\n| typ_floatpoint fp_float => fun gv => exists f, gv = (Vsingle f, Mfloat32)::nil\n| typ_floatpoint fp_double => fun gv => exists f, gv = (Vfloat f, Mfloat64)::nil\n| typ_pointer _ =>\n    fun gv => exists b, exists ofs, gv = (Vptr b ofs, AST.Mint 31)::nil\n| _ => Singleton GenericValue gv\nend.\n\nDefinition undef_gvs gv ty : t :=\nmatch ty with\n| typ_int sz =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists z, gv = (Vint (sz-1) z, Mint (sz-1))::nil)\n| typ_floatpoint fp_float =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists f, gv = (Vsingle f, Mfloat32)::nil)\n| typ_floatpoint fp_double =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists f, gv = (Vfloat f, Mfloat64)::nil)\n| typ_pointer _ =>\n    Ensembles.Union _ (Singleton _ gv)\n      (fun gv => exists b, exists ofs, gv = (Vptr b ofs, AST.Mint 31)::nil)\n| _ => Singleton GenericValue gv\nend.\n\nDefinition cgv2gvs (gv:GenericValue) ty : t :=\nmatch gv with\n| (Vundef, _)::nil => cundef_gvs gv ty\n| _ => Singleton _ gv\nend.\n\nDefinition gv2gvs (gv:GenericValue) (ty:typ) : t :=\nmatch gv with\n| (Vundef, _)::nil => undef_gvs gv ty\n| _ => Singleton GenericValue gv\nend.\n\nNotation \"gv @ gvs\" :=\n  (instantiate_gvs gv gvs) (at level 43, right associativity).\nNotation \"$ gv # t $\" := (gv2gvs gv t) (at level 41).\n\nLemma cundef_gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cundef_gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct_typ t; simpl in *;\n    try solve [inv Heq1; inv Hin; erewrite int_typsize; eauto |\n               inv Heq1; inv Hin; eauto].\n    destruct f; try solve [inv Heq1; inv Hin; eauto].\n    inv Heq1. inv Hin. inv H. simpl. auto.\nQed.\n\nLemma cundef_gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv' @ (cundef_gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct_typ t; simpl in *; uniq_result;\n    try solve [inv Heq1; inv Hin; auto].\n\n    inv Heq1; inv Hin. \n    constructor; auto.\n    split; auto. simpl. split; auto. apply Int.unsigned_range.\n\n    destruct f; uniq_result; inv Heq1; inv Hin; eauto.\n      constructor; auto.\n      split; auto. simpl. auto.\n\n      constructor; auto.\n      split; auto. simpl. auto.\n\n    inv Heq1. inv Hin. inv H. \n    constructor; auto.\n    split; auto. simpl. auto.\nQed.\n\nLemma cundef_gvs__inhabited : forall gv ty, inhabited (cundef_gvs gv ty).\nProof.\n  destruct_typ ty; simpl; \n    try solve [eapply Ensembles.Inhabited_intro; constructor].\n    eapply Ensembles.Inhabited_intro.\n      exists (Int.zero (s0-1)). auto.\n\n    destruct f; try solve [\n      eapply Ensembles.Inhabited_intro; exists Float.zero; auto |\n      eapply Ensembles.Inhabited_intro; exists Float32.zero; auto |\n      eapply Ensembles.Inhabited_intro; constructor].\n\n    eapply Ensembles.Inhabited_intro.\n      exists Mem.nullptr. exists (Int.repr 31 0). auto.\nQed.\n\nLemma undef_gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (undef_gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct_typ t; simpl in *;\n    try solve [inv Heq1; inv Hin; erewrite int_typsize; eauto |\n               inv Heq1; inv Hin; eauto].\n\n    inv Heq1; inv Hin; inv H; unfold Size.to_nat;\n      try solve [eauto | erewrite int_typsize; eauto].\n\n    destruct f; try solve [inv Heq1; inv Hin; eauto |\n                           inv Heq1; inv Hin; inv H; auto].\n\n    inv Heq1; inv Hin; inv H; auto.\n      inv H0. auto.\nQed.\n\nLemma undef_gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv' @ (undef_gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct_typ t; simpl in *; uniq_result; try solve [\n    inv Heq1; inv Hin; eauto\n  ].\n\n    inv Heq1; inv Hin; inv H.\n    constructor; auto. \n    constructor; auto.\n      split; auto. split; auto. apply Int.unsigned_range.\n\n    destruct f; uniq_result; try solve [\n      inv Heq1; inv Hin; eauto\n    ].\n\n      inv Heq1; inv Hin; inv H.\n      constructor; auto.\n      constructor; auto.\n        split; auto. simpl. auto.\n\n      inv Heq1; inv Hin; inv H.\n      constructor; auto.\n      constructor; auto.\n        split; auto. simpl. auto.\n\n    inv Heq1; inv Hin; inv H; try solve [congruence | auto].\n      match goal with\n      | H1: exists _:_, _ |- _ => inv H1;\n         constructor; try solve [auto | split; simpl; auto]\n      end.\nQed.\n\nLemma undef_gvs__inhabited : forall gv ty, inhabited (undef_gvs gv ty).\nProof.\n  destruct_typ ty; simpl; try solve [\n    eapply Ensembles.Inhabited_intro; apply Union_introl; constructor |\n    eapply Ensembles.Inhabited_intro; constructor].\n\n    destruct f; try solve [\n      eapply Ensembles.Inhabited_intro; apply Union_introl; constructor |\n      eapply Ensembles.Inhabited_intro; constructor].\nQed.\n\nLemma cgv2gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cgv2gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  intros S los nts gv t sz al gv' Hwft Heq1 Heq2 Hin.\n  destruct gv; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct p.\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply cundef_gvs__getTypeSizeInBits in Hin; eauto.\nQed.\n\nLemma cgv2gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  instantiate_gvs gv' (cgv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t gv' Hwft Heq1 Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct gv as [|[]]; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply cundef_gvs__matches_chunks in Hin; \n        unfold gv_chunks_match_typ, vm_matches_typ in *; simpl in *; eauto.\n        rewrite <- HeqR in Hin. auto.\n        rewrite <- HeqR. auto.\nQed.\n\nLemma cgv2gvs__inhabited : forall gv t, inhabited (cgv2gvs gv t).\nProof.\n  intros gv t.\n  destruct gv; simpl.\n    apply Ensembles.Inhabited_intro with (x:=nil).\n    apply Ensembles.In_singleton.\n\n    destruct p.\n    destruct v; auto using singleton_inhabited, cundef_gvs__inhabited.\n    destruct gv; auto using singleton_inhabited, cundef_gvs__inhabited.\nQed.\n\nLemma gv2gvs__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  sizeGenericValue gv' = Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros S los nts gv t sz al Hwft Heq1 Heq2 gv' Hin.\n  destruct gv; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct p.\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply undef_gvs__getTypeSizeInBits in Hin; eauto.\nQed.\n\nLemma gv2gvs__matches_chunks : forall S los nts gv t,\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  intros S los nts gv t Hwft Heq1 gv' Hin.\n  unfold gv_chunks_match_typ, vm_matches_typ in *.\n  inv_mbind.\n  destruct gv as [|[]]; simpl in *.\n    inv Hin. simpl. auto.\n\n    destruct v; try solve [inv Hin; simpl; auto].\n    destruct gv; try solve [inv Hin; simpl; auto].\n      eapply undef_gvs__matches_chunks in Hin; \n        unfold gv_chunks_match_typ, vm_matches_typ in *; simpl in *; eauto.\n        rewrite <- HeqR in Hin. auto.\n        rewrite <- HeqR. auto.\nQed.\n\nLemma gv2gvs__inhabited : forall gv t, inhabited ($ gv # t $).\nProof.\n  intros gv t.\n  destruct gv; simpl.\n    apply Ensembles.Inhabited_intro with (x:=nil).\n    apply Ensembles.In_singleton.\n\n    destruct p.\n    destruct v; auto using singleton_inhabited, undef_gvs__inhabited.\n    destruct gv; auto using singleton_inhabited, undef_gvs__inhabited.\nQed.\n\nDefinition lift_op1 (f: GenericValue -> option GenericValue) gvs1 ty : option t\n  :=\n  Some (fun gv2 => exists gv1, exists gv2',\n    gv1 @ gvs1 /\\ f gv1 = Some gv2' /\\ (gv2 @ $ gv2' # ty $)).\n\nDefinition lift_op2 (f: GenericValue -> GenericValue -> option GenericValue)\n  gvs1 gvs2 ty : option t :=\n  Some (fun gv3 => exists gv1, exists gv2, exists gv3',\n    gv1 @ gvs1 /\\ gv2 @ gvs2 /\\ f gv1 gv2 = Some gv3' /\\ (gv3 @ $ gv3' # ty $)).\n\nLemma lift_op1__inhabited : forall f gvs1 ty gvs2\n  (H:forall x, exists z, f x = Some z),\n  inhabited gvs1 ->\n  lift_op1 f gvs1 ty = Some gvs2 ->\n  inhabited gvs2.\nProof.\n  intros. inv H1. inv H0.\n  destruct (@H x) as [z J].\n  destruct (@gv2gvs__inhabited z ty).\n  exists x0. unfold Ensembles.In. exists x. exists z.\n  rewrite J.\n  repeat (split; auto).\nQed.\n\nLemma lift_op2__inhabited : forall f gvs1 gvs2 ty gv3\n  (H:forall x y, exists z, f x y = Some z),\n  inhabited gvs1 -> inhabited gvs2 ->\n  lift_op2 f gvs1 gvs2 ty = Some gv3 ->\n  inhabited gv3.\nProof.\n  intros. inv H0. inv H1. inv H2.\n  destruct (@H x x0) as [z J].\n  destruct (@gv2gvs__inhabited z ty).\n  exists x1. unfold Ensembles.In. exists x. exists x0. exists z.\n  rewrite J.\n  repeat (split; auto).\nQed.\n\nLemma lift_op1__isnt_stuck : forall f gvs1 ty\n  (H:forall x, exists z, f x = Some z),\n  exists gvs2, lift_op1 f gvs1 ty = Some gvs2.\nProof.\n  intros. unfold lift_op1. eauto.\nQed.\n\nLemma lift_op2__isnt_stuck : forall f gvs1 gvs2 ty\n  (H:forall x y, exists z, f x y = Some z),\n  exists gv3, lift_op2 f gvs1 gvs2 ty = Some gv3.\nProof.\n  intros. unfold lift_op2. eauto.\nQed.\n\nLemma lift_op1__getTypeSizeInBits : forall S los nts f g t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y, x @ g -> f x = Some y ->\n   sizeGenericValue y = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros. inv H2.\n  destruct H3 as [x [y [J1 [J2 J3]]]].\n  apply H1 in J2; auto.\n  eapply gv2gvs__getTypeSizeInBits; eauto.\nQed.\n\nLemma lift_op1__matches_chunks : forall S los nts f g t gvs\n  (Hwft: wf_typ S (los,nts) t),\n  (forall x y, x @ g -> f x = Some y ->\n   gv_chunks_match_typ (los, nts) y t) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof.\n  intros. inv H0.\n  destruct H1 as [x [y [J1 [J2 J3]]]].\n  apply H in J2; auto.\n  eapply gv2gvs__matches_chunks; eauto.\nQed.\n\nLemma lift_op2__getTypeSizeInBits : forall S los nts f g1 g2 t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y z, x @ g1 -> y @ g2 -> f x y = Some z ->\n   sizeGenericValue z = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof.\n  intros. inv H2.\n  destruct H3 as [x [y [z [J1 [J2 [J3 J4]]]]]].\n  apply H1 in J3; auto.\n  eapply gv2gvs__getTypeSizeInBits; eauto.\nQed.\n\nLemma lift_op2__matches_chunks : forall S los nts f g1 g2 t gvs\n  (Hwft: wf_typ S (los,nts) t),\n  (forall x y z, x @ g1 -> y @ g2 -> f x y = Some z ->\n   gv_chunks_match_typ (los, nts) z t) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof.\n  intros. inv H0.\n  destruct H1 as [x [y [z [J1 [J2 [J3 J4]]]]]].\n  apply H in J3; auto.\n  eapply gv2gvs__matches_chunks; eauto.\nQed.\n\nLemma inhabited_inv : forall gvs, inhabited gvs -> exists gv, gv @ gvs.\nProof.\n  intros. inv H; eauto.\nQed.\n\nLemma instantiate_undef__undef_gvs : forall gv t, gv @ (undef_gvs gv t).\nProof.\n  intros. unfold undef_gvs.\n  destruct_typ t0; try solve [apply Union_introl; constructor | constructor].\n  destruct f; \n    try solve [apply Union_introl; constructor | constructor].\nQed.\n\nLemma instantiate_gv__gv2gvs : forall gv t, gv @ ($ gv # t $).\nProof.\n  intros.\n  destruct gv; simpl; try constructor.\n  destruct p; simpl; try constructor.\n  destruct v; simpl; try constructor.\n  destruct gv; simpl;\n    try solve [constructor | auto using instantiate_undef__undef_gvs].\nQed.\n\nLemma none_undef2gvs_inv : forall gv gv' t,\n  gv @ $ gv' # t $ -> (forall mc, (Vundef, mc)::nil <> gv') -> gv = gv'.\nProof.\n  intros.\n  destruct gv'; try solve [inv H; auto].\n  destruct p.\n  destruct v; try solve [inv H; auto].\n  destruct gv'; try solve [inv H; auto].\n  assert (J:=@H0 m). congruence.\nQed.\n\nEnd MNDGVs.\n\nDefinition NDGVs : GenericValues := mkGVs\nMNDGVs.t\nMNDGVs.instantiate_gvs\nMNDGVs.inhabited\nMNDGVs.cgv2gvs\nMNDGVs.gv2gvs\nMNDGVs.lift_op1\nMNDGVs.lift_op2\nMNDGVs.cgv2gvs__getTypeSizeInBits\nMNDGVs.cgv2gvs__matches_chunks\nMNDGVs.cgv2gvs__inhabited\nMNDGVs.gv2gvs__getTypeSizeInBits\nMNDGVs.gv2gvs__matches_chunks\nMNDGVs.gv2gvs__inhabited\nMNDGVs.lift_op1__inhabited\nMNDGVs.lift_op2__inhabited\nMNDGVs.lift_op1__isnt_stuck\nMNDGVs.lift_op2__isnt_stuck\nMNDGVs.lift_op1__getTypeSizeInBits\nMNDGVs.lift_op2__getTypeSizeInBits\nMNDGVs.lift_op1__matches_chunks\nMNDGVs.lift_op2__matches_chunks\nMNDGVs.inhabited_inv\nMNDGVs.instantiate_gv__gv2gvs\nMNDGVs.none_undef2gvs_inv.\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/ndopsem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.32423539245106087, "lm_q1q2_score": 0.16718223055680353}}
{"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 Require Import Integers.\n\nFrom dx Require Import ResultMonad IR.\n\nFrom bpf.dxcomm Require Import InfComp GenMatchable CoqIntegers DxNat.\nFrom bpf.verifier.synthesismodel Require Import opcode_synthesis.\n\n(******************** Dx related *******************)\n\nOpen Scope Z_scope.\n\nDefinition opcodeCompilableType :=\n  MkCompilableType opcode C_U8.\n\nDefinition opcodeCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcodeCompilableType  opcode_eqb\n    (     (ALU64, 0x07)\n       :: (ALU32, 0x04)\n       :: (Branch, 0x05)\n       :: (LD_IMM, 0x00)\n       :: (LD_REG, 0x01)\n       :: (ST_IMM, 0x02)\n       :: (ST_REG, 0x03) :: nil)\n    ILLEGAL\n    (fun m A => opcode_rect (fun _ => m A))).\n\nInstance CINT : CType nat := mkCType _ (cType nat8CompilableType).\nInstance COP : CType opcode := mkCType _ (cType opcodeCompilableType).\n\nDefinition opcodeSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcodeCompilableType).\n\nDefinition Const_nat_to_opcode :=\n  ltac: (mkprimitive nat_to_opcode\n                (fun es => match es with\n                           | [e1] => Ok (Csyntax.Ecast (Csyntax.Ebinop Cop.Oand e1 C_NAT8_0x07 C_U8) C_U8)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_alu64_immCompilableType :=\n  MkCompilableType opcode_alu64_imm C_U8.\n\nDefinition opcode_alu64_immCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_alu64_immCompilableType  opcode_alu64_imm_eqb\n    (     (ADD64_IMM, 0x07)\n       :: (SUB64_IMM, 0x17)\n       :: (MUL64_IMM, 0x27)\n       :: (DIV64_IMM, 0x37)\n       :: (OR64_IMM,  0x47)\n       :: (AND64_IMM, 0x57)\n       :: (LSH64_IMM, 0x67)\n       :: (RSH64_IMM, 0x77)\n       :: (NEG64_IMM, 0x87)\n       :: (MOD64_IMM, 0x97)\n       :: (XOR64_IMM, 0xa7)\n       :: (MOV64_IMM, 0xb7)\n       :: (ARSH64_IMM, 0xc7) :: nil)\n    ALU64_IMM_ILLEGAL\n    (fun m A => opcode_alu64_imm_rect (fun _ => m A))).\n\nInstance COP_alu64_imm : CType opcode_alu64_imm  := mkCType _ (cType opcode_alu64_immCompilableType).\n\nDefinition opcode_alu64_immSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_alu64_immCompilableType).\n\nDefinition Const_nat_to_opcode_alu64_imm :=\n  ltac: (mkprimitive nat_to_opcode_alu64_imm\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_alu64_regCompilableType :=\n  MkCompilableType opcode_alu64_reg C_U8.\n\nDefinition opcode_alu64_regCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_alu64_regCompilableType  opcode_alu64_reg_eqb\n    (     (ADD64_REG, 0x0f)\n       :: (SUB64_REG, 0x1f)\n       :: (MUL64_REG, 0x2f)\n       :: (DIV64_REG, 0x3f)\n       :: (OR64_REG,  0x4f)\n       :: (AND64_REG, 0x5f)\n       :: (LSH64_REG, 0x6f)\n       :: (RSH64_REG, 0x7f)\n       :: (MOD64_REG, 0x9f)\n       :: (XOR64_REG, 0xaf)\n       :: (MOV64_REG, 0xbf)\n       :: (ARSH64_REG, 0xcf) :: nil)\n    ALU64_REG_ILLEGAL\n    (fun m A => opcode_alu64_reg_rect (fun _ => m A))).\n\nInstance COP_alu64_reg : CType opcode_alu64_reg  := mkCType _ (cType opcode_alu64_regCompilableType).\n\nDefinition opcode_alu64_regSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_alu64_regCompilableType).\n\nDefinition Const_nat_to_opcode_alu64_reg :=\n  ltac: (mkprimitive nat_to_opcode_alu64_reg\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_alu32_immCompilableType :=\n  MkCompilableType opcode_alu32_imm C_U8.\n\nDefinition opcode_alu32_immCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_alu32_immCompilableType  opcode_alu32_imm_eqb\n    (     (ADD32_IMM, 0x04)\n       :: (SUB32_IMM, 0x14)\n       :: (MUL32_IMM, 0x24)\n       :: (DIV32_IMM, 0x34)\n       :: (OR32_IMM,  0x44)\n       :: (AND32_IMM, 0x54)\n       :: (LSH32_IMM, 0x64)\n       :: (RSH32_IMM, 0x74)\n       :: (NEG32_IMM, 0x84)\n       :: (MOD32_IMM, 0x94)\n       :: (XOR32_IMM, 0xa4)\n       :: (MOV32_IMM, 0xb4)\n       :: (ARSH32_IMM, 0xc4) :: nil)\n    ALU32_IMM_ILLEGAL\n    (fun m A => opcode_alu32_imm_rect (fun _ => m A))).\n\nInstance COP_alu32_imm : CType opcode_alu32_imm  := mkCType _ (cType opcode_alu32_immCompilableType).\n\nDefinition opcode_alu32_immSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_alu32_immCompilableType).\n\nDefinition Const_nat_to_opcode_alu32_imm :=\n  ltac: (mkprimitive nat_to_opcode_alu32_imm\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_alu32_regCompilableType :=\n  MkCompilableType opcode_alu32_reg C_U8.\n\nDefinition opcode_alu32_regCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_alu32_regCompilableType  opcode_alu32_reg_eqb\n    (     (ADD32_REG, 0x0c)\n       :: (SUB32_REG, 0x1c)\n       :: (MUL32_REG, 0x2c)\n       :: (DIV32_REG, 0x3c)\n       :: (OR32_REG,  0x4c)\n       :: (AND32_REG, 0x5c)\n       :: (LSH32_REG, 0x6c)\n       :: (RSH32_REG, 0x7c)\n       :: (MOD32_REG, 0x9c)\n       :: (XOR32_REG, 0xac)\n       :: (MOV32_REG, 0xbc)\n       :: (ARSH32_REG, 0xcc) :: nil)\n    ALU32_REG_ILLEGAL\n    (fun m A => opcode_alu32_reg_rect (fun _ => m A))).\n\nInstance COP_alu32_reg : CType opcode_alu32_reg  := mkCType _ (cType opcode_alu32_regCompilableType).\n\nDefinition opcode_alu32_regSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_alu32_regCompilableType).\n\nDefinition Const_nat_to_opcode_alu32_reg :=\n  ltac: (mkprimitive nat_to_opcode_alu32_reg\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_branch_immCompilableType :=\n  MkCompilableType opcode_branch_imm C_U8.\n\nDefinition opcode_branch_immCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_branch_immCompilableType  opcode_branch_imm_eqb\n    (     (JA_IMM,  0x05)\n       :: (JEQ_IMM, 0x15)\n       :: (JGT_IMM, 0x25)\n       :: (JGE_IMM, 0x35)\n       :: (JLT_IMM, 0xa5)\n       :: (JLE_IMM, 0xb5)\n       :: (JNE_IMM, 0x45)\n       :: (JNE_IMM, 0x55)\n       :: (JSGT_IMM, 0x65)\n       :: (JSGE_IMM, 0x75)\n       :: (JSLT_IMM, 0xc5)\n       :: (JSLE_IMM, 0xd5)\n       :: (CALL_IMM, 0x85)\n       :: (RET_IMM, 0x95) :: nil)\n    JMP_IMM_ILLEGAL_INS\n    (fun m A => opcode_branch_imm_rect (fun _ => m A))).\n\nInstance COP_branch_imm : CType opcode_branch_imm  := mkCType _ (cType opcode_branch_immCompilableType).\n\nDefinition opcode_branch_immSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_branch_immCompilableType).\n\nDefinition Const_nat_to_opcode_branch_imm :=\n  ltac: (mkprimitive nat_to_opcode_branch_imm\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_branch_regCompilableType :=\n  MkCompilableType opcode_branch_reg C_U8.\n\nDefinition opcode_branch_regCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_branch_regCompilableType  opcode_branch_reg_eqb\n    (     (JEQ_REG, 0x1d)\n       :: (JGT_REG, 0x2d)\n       :: (JGE_REG, 0x3d)\n       :: (JLT_REG,  0xad)\n       :: (JLE_REG, 0xbd)\n       :: (JSET_REG, 0x4d)\n       :: (JNE_REG, 0x5d)\n       :: (JSGT_REG, 0x6d)\n       :: (JSGE_REG, 0x7d)\n       :: (JSLT_REG, 0xcd)\n       :: (JSLE_REG, 0xdd) :: nil)\n    JMP_REG_ILLEGAL_INS\n    (fun m A => opcode_branch_reg_rect (fun _ => m A))).\n\nInstance COP_branch_reg : CType opcode_branch_reg  := mkCType _ (cType opcode_branch_regCompilableType).\n\nDefinition opcode_branch_regSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_branch_regCompilableType).\n\nDefinition Const_nat_to_opcode_branch_reg :=\n  ltac: (mkprimitive nat_to_opcode_branch_reg\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_load_immCompilableType :=\n  MkCompilableType opcode_load_imm C_U8.\n\nDefinition opcode_load_immCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_load_immCompilableType  opcode_load_imm_eqb\n    (     (LDDW_low,  0x18)\n       :: (LDDW_high, 0x10) :: nil)\n    LDX_IMM_ILLEGAL_INS\n    (fun m A => opcode_load_imm_rect (fun _ => m A))).\n\nInstance COP_load_imm : CType opcode_load_imm  := mkCType _ (cType opcode_load_immCompilableType).\n\nDefinition opcode_load_immSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_load_immCompilableType).\n\nDefinition Const_nat_to_opcode_load_imm :=\n  ltac: (mkprimitive nat_to_opcode_load_imm\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_load_regCompilableType :=\n  MkCompilableType opcode_load_reg C_U8.\n\nDefinition opcode_load_regCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_load_regCompilableType  opcode_load_reg_eqb\n    (     (LDXW, 0x61)\n       :: (LDXH, 0x69)\n       :: (LDXB, 0x71)\n       :: (LDXDW,  0x79) :: nil)\n    LDX_REG_ILLEGAL_INS\n    (fun m A => opcode_load_reg_rect (fun _ => m A))).\n\nInstance COP_load_reg : CType opcode_load_reg  := mkCType _ (cType opcode_load_regCompilableType).\n\nDefinition opcode_load_regSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_load_regCompilableType).\n\nDefinition Const_nat_to_opcode_load_reg :=\n  ltac: (mkprimitive nat_to_opcode_load_reg\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_store_immCompilableType :=\n  MkCompilableType opcode_store_imm C_U8.\n\nDefinition opcode_store_immCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_store_immCompilableType  opcode_store_imm_eqb\n    (     (STW,  0x62)\n       :: (STH,  0x6a)\n       :: (STB,  0x72)\n       :: (STDW, 0x7a) :: nil)\n    ST_ILLEGAL_INS\n    (fun m A => opcode_store_imm_rect (fun _ => m A))).\n\nInstance COP_store_imm : CType opcode_store_imm  := mkCType _ (cType opcode_store_immCompilableType).\n\nDefinition opcode_store_immSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_store_immCompilableType).\n\nDefinition Const_nat_to_opcode_store_imm :=\n  ltac: (mkprimitive nat_to_opcode_store_imm\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\n\nDefinition opcode_store_regCompilableType :=\n  MkCompilableType opcode_store_reg C_U8.\n\nDefinition opcode_store_regCompilableTypeMatchableType : MatchableType:=\n  Eval compute in\n (mkEnumMatchableType\n    opcode_store_regCompilableType  opcode_store_reg_eqb\n    (     (STXW,  0x63)\n       :: (STXH,  0x6b)\n       :: (STXB,  0x73)\n       :: (STXDW, 0x7b) :: nil)\n    STX_ILLEGAL_INS\n    (fun m A => opcode_store_reg_rect (fun _ => m A))).\n\nInstance COP_store_reg : CType opcode_store_reg  := mkCType _ (cType opcode_store_regCompilableType).\n\nDefinition opcode_store_regSymbolType :=\n  MkCompilableSymbolType [nat8CompilableType] (Some opcode_store_regCompilableType).\n\nDefinition Const_nat_to_opcode_store_reg :=\n  ltac: (mkprimitive nat_to_opcode_store_reg\n                (fun es => match es with\n                           | [e1] => Ok (e1)\n                           | _       => Err PrimitiveEncodingFailed\n                           end)).\nClose Scope Z_scope.\n\nModule Exports.\n  Definition opcodeCompilableTypeMatchableType            := opcodeCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode                          := Const_nat_to_opcode.\n  Definition opcode_alu64_immCompilableTypeMatchableType  := opcode_alu64_immCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_alu64_imm                := Const_nat_to_opcode_alu64_imm.\n  Definition opcode_alu64_regCompilableTypeMatchableType  := opcode_alu64_regCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_alu64_reg                := Const_nat_to_opcode_alu64_reg.\n  Definition opcode_alu32_immCompilableTypeMatchableType  := opcode_alu32_immCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_alu32_imm                := Const_nat_to_opcode_alu32_imm.\n  Definition opcode_alu32_regCompilableTypeMatchableType  := opcode_alu32_regCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_alu32_reg                := Const_nat_to_opcode_alu32_reg.\n  Definition opcode_branch_immCompilableTypeMatchableType := opcode_branch_immCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_branch_imm               := Const_nat_to_opcode_branch_imm.\n  Definition opcode_branch_regCompilableTypeMatchableType := opcode_branch_regCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_branch_reg               := Const_nat_to_opcode_branch_reg.\n  Definition opcode_load_immCompilableTypeMatchableType   := opcode_load_immCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_load_imm                 := Const_nat_to_opcode_load_imm.\n  Definition opcode_load_regCompilableTypeMatchableType   := opcode_load_regCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_load_reg                 := Const_nat_to_opcode_load_reg.\n  Definition opcode_store_immCompilableTypeMatchableType  := opcode_store_immCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_store_imm                := Const_nat_to_opcode_store_imm.\n  Definition opcode_store_regCompilableTypeMatchableType  := opcode_store_regCompilableTypeMatchableType.\n  Definition Const_nat_to_opcode_store_reg                := Const_nat_to_opcode_store_reg.\nEnd Exports.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/dxmodel/Dxopcode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3242353989809524, "lm_q1q2_score": 0.16718222909697703}}
{"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\nSet Implicit Arguments.\n\n\nVariant lower_event: forall (e_src e_tgt: ThreadEvent.t), Prop :=\n| lower_event_promise\n    loc from to msg kind\n  :\n  lower_event\n    (ThreadEvent.promise loc from to msg kind)\n    (ThreadEvent.promise loc from to msg kind)\n| lower_event_silent\n  :\n  lower_event\n    ThreadEvent.silent\n    ThreadEvent.silent\n| lower_event_read\n    loc ts val released_src released_tgt ord\n    (RELEASED: View.opt_le released_src released_tgt)\n  :\n  lower_event\n    (ThreadEvent.read loc ts val released_src ord)\n    (ThreadEvent.read loc ts val released_tgt ord)\n| lower_event_write\n    loc from to val released_src released_tgt ord\n    (RELEASED: View.opt_le released_src released_tgt)\n  :\n  lower_event\n    (ThreadEvent.write loc from to val released_src ord)\n    (ThreadEvent.write loc from to val released_tgt ord)\n| lower_event_write_na\n    loc msgs from to val ord\n  :\n  lower_event\n    (ThreadEvent.write_na loc msgs from to val ord)\n    (ThreadEvent.write_na loc msgs from to val ord)\n| lower_event_update\n    loc tsr tsw valr valw releasedr_src releasedr_tgt releasedw_src releasedw_tgt ordr ordw\n    (RELEASEDR: View.opt_le releasedr_src releasedr_tgt)\n    (RELEASEDW: View.opt_le releasedw_src releasedw_tgt)\n  :\n  lower_event\n    (ThreadEvent.update loc tsr tsw valr valw releasedr_src releasedw_src ordr ordw)\n    (ThreadEvent.update loc tsr tsw valr valw releasedr_tgt releasedw_tgt ordr ordw)\n| lower_event_fence\n    ordr ordw\n  :\n  lower_event\n    (ThreadEvent.fence ordr ordw)\n    (ThreadEvent.fence ordr ordw)\n| lower_event_syscall\n    e\n  :\n  lower_event\n    (ThreadEvent.syscall e)\n    (ThreadEvent.syscall e)\n| lower_event_failure\n  :\n  lower_event\n    ThreadEvent.failure\n    ThreadEvent.failure\n| lower_event_racy_read\n    loc to val ord\n  :\n  lower_event\n    (ThreadEvent.racy_read loc to val ord)\n    (ThreadEvent.racy_read loc to val ord)\n| lower_event_racy_write\n    loc to val ord\n  :\n  lower_event\n    (ThreadEvent.racy_write loc to val ord)\n    (ThreadEvent.racy_write loc to val ord)\n| lower_event_racy_update\n    loc to valr valw ordr ordw\n  :\n  lower_event\n    (ThreadEvent.racy_update loc to valr valw ordr ordw)\n    (ThreadEvent.racy_update loc to valr valw ordr ordw)\n.\n#[export] Hint Constructors lower_event: core.\n\n\nGlobal Program Instance lower_event_PreOrder: PreOrder lower_event.\nNext Obligation. ii. destruct x; try (econs; eauto); refl. Qed.\nNext Obligation. ii. inv H; inv H0; econs; eauto; etrans; eauto. Qed.\n\nLemma lower_event_program_event\n      e_src e_tgt\n      (EVENT: lower_event e_src e_tgt):\n  ThreadEvent.get_program_event e_src = ThreadEvent.get_program_event e_tgt.\nProof.\n  inv EVENT; ss.\nQed.\n\nLemma lower_event_machine_event\n      e_src e_tgt\n      (EVENT: lower_event e_src e_tgt):\n  ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt.\nProof.\n  inv EVENT; ss.\nQed.\n\nVariant lower_memory_content: forall (cnt_src cnt_tgt: option (Loc.t * Message.t)), Prop :=\n| lower_memory_content_none\n  :\n    lower_memory_content None None\n| lower_memory_content_some\n    from msg_src msg_tgt\n    (MESSAGE: Message.le msg_src msg_tgt)\n  :\n    lower_memory_content (Some (from, msg_src)) (Some (from, msg_tgt))\n.\n\nGlobal Program Instance lower_memory_content_PreOrder: PreOrder lower_memory_content.\nNext Obligation.\nProof.\n  ii. destruct x as [[]|]; econs. refl.\nQed.\nNext Obligation.\nProof.\n  ii. inv H; inv H0; econs. etrans; eauto.\nQed.\n\n\nVariant lower_memory (mem_src mem_tgt: Memory.t): Prop :=\n| lower_memory_intro\n    (LOWER: forall loc to, lower_memory_content (Memory.get loc to mem_src) (Memory.get loc to mem_tgt))\n.\n\nGlobal Program Instance lower_memory_PreOrder: PreOrder lower_memory.\nNext Obligation.\nProof.\n  ii. econs. i. refl.\nQed.\nNext Obligation.\nProof.\n  ii. inv H. inv H0. econs. i. etrans; eauto.\nQed.\n\n\nVariant lower_local: forall (lc_src lc_tgt: Local.t), Prop :=\n| lower_local_intro\n    tvw_src tvw_tgt prom\n    (TVIEW: TView.le tvw_src tvw_tgt)\n  :\n    lower_local (Local.mk tvw_src prom) (Local.mk tvw_tgt prom)\n.\n\nGlobal Program Instance lower_local_PreOrder: PreOrder lower_local.\nNext Obligation.\nProof.\n  ii. destruct x. econs; eauto. refl.\nQed.\nNext Obligation.\nProof.\n  ii. inv H; inv H0. econs; eauto. etrans; eauto.\nQed.\n\nVariant lower_thread {lang: language} (e_src e_tgt: Thread.t lang): Prop :=\n| lower_thread_intro\n    (STATE: Thread.state e_src = Thread.state e_tgt)\n    (LOCAL: lower_local (Thread.local e_src) (Thread.local e_tgt))\n    (SC: TimeMap.le (Thread.sc e_src) (Thread.sc e_tgt))\n    (MEMORY: lower_memory (Thread.memory e_src) (Thread.memory e_tgt))\n.\n\nGlobal Program Instance lower_thread_PreOrder {lang: language}: PreOrder (@lower_thread lang).\nNext Obligation.\nProof.\n  ii. destruct x. econs; ss; refl.\nQed.\nNext Obligation.\nProof.\n  ii. destruct x, y, z. inv H. inv H0. ss. subst.\n  econs; ss; eauto; etrans; eauto.\nQed.\n\nLemma lower_local_consistent lc_src lc_tgt\n      (LOCAL: lower_local lc_src lc_tgt)\n      (CONSISTENT: Local.promise_consistent lc_tgt)\n  :\n    Local.promise_consistent lc_src.\nProof.\n  inv LOCAL. ii. ss. exploit CONSISTENT; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto.\n  ss. eapply TVIEW.\nQed.\n\nLemma lower_thread_consistent\n      lang (e_src e_tgt: Thread.t lang)\n      (LOWER: lower_thread e_src e_tgt)\n      (CONS: Local.promise_consistent (Thread.local e_tgt)):\n  Local.promise_consistent (Thread.local e_src).\nProof.\n  eapply lower_local_consistent; eauto. apply LOWER.\nQed.\n\nLemma lower_memory_get mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      loc from to msg_tgt\n      (GETTGT: Memory.get loc to mem_tgt = Some (from, msg_tgt))\n  :\n    exists msg_src,\n      (<<GETSRC: Memory.get loc to mem_src = Some (from, msg_src)>>) /\\\n      (<<MESSAGE: Message.le msg_src msg_tgt>>).\nProof.\n  inv MEM. specialize (LOWER loc to). rewrite GETTGT in *.\n  inv LOWER. eauto.\nQed.\n\nLemma lower_memory_get_inv mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      loc from to msg_src\n      (GETSRC: Memory.get loc to mem_src = Some (from, msg_src))\n  :\n    exists msg_tgt,\n      (<<GETTGT: Memory.get loc to mem_tgt = Some (from, msg_tgt)>>) /\\\n      (<<MESSAGE: Message.le msg_src msg_tgt>>).\nProof.\n  inv MEM. specialize (LOWER loc to). rewrite GETSRC in *.\n  inv LOWER. eauto.\nQed.\n\nLemma lower_memory_future_weak\n      mem_src mem_tgt\n      (LOWER: lower_memory mem_src mem_tgt)\n      (MEM_SRC: Memory.closed mem_src):\n  Memory.future_weak mem_tgt mem_src.\nProof.\n  inv LOWER. econs; i.\n  - specialize (LOWER0 loc to). inv LOWER0; try congr.\n    rewrite GET in *. inv H.\n    esplits; eauto; try refl.\n    symmetry in H0.\n    inv MEM_SRC. exploit CLOSED; eauto. i. des. eauto.\n  - specialize (LOWER0 loc to). inv LOWER0; try congr.\n  - specialize (LOWER0 loc to). inv LOWER0; try congr.\n    rewrite GET1, GET2 in *. clarify. inv MESSAGE.\nQed.\n\n\nLemma lower_memory_closed_timemap mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      tm\n      (CLOSED: Memory.closed_timemap tm mem_tgt)\n  :\n    Memory.closed_timemap tm mem_src.\nProof.\n  ii. specialize (CLOSED loc). des.\n  hexploit lower_memory_get; eauto. i. des. inv MESSAGE. esplits; eauto.\nQed.\n\nLemma lower_memory_closed_view mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      vw\n      (CLOSED: Memory.closed_view vw mem_tgt)\n  :\n    Memory.closed_view vw mem_src.\nProof.\n  inv CLOSED. econs.\n  { eapply lower_memory_closed_timemap; eauto. }\n  { eapply lower_memory_closed_timemap; eauto. }\nQed.\n\nLemma lower_memory_closed_opt_view mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      vw\n      (CLOSED: Memory.closed_opt_view vw mem_tgt)\n  :\n    Memory.closed_opt_view vw mem_src.\nProof.\n  inv CLOSED; econs.\n  eapply lower_memory_closed_view; eauto.\nQed.\n\nLemma lower_memory_closed_message mem_src mem_tgt\n      (MEM: lower_memory mem_src mem_tgt)\n      msg\n      (CLOSED: Memory.closed_message msg mem_tgt)\n  :\n    Memory.closed_message msg mem_src.\nProof.\n  inv CLOSED; econs.\n  eapply lower_memory_closed_opt_view; eauto.\nQed.\n\nLemma lower_memory_add mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc from to msg_src msg_tgt mem_tgt1\n      (ADD: Memory.add mem_tgt0 loc from to msg_tgt mem_tgt1)\n      (MSG: Message.le msg_src msg_tgt)\n      (WF: Message.wf msg_tgt -> Message.wf msg_src)\n  :\n    exists mem_src1,\n      (<<ADD: Memory.add mem_src0 loc from to msg_src mem_src1>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>).\nProof.\n  hexploit add_succeed_wf; eauto. i. des.\n  hexploit (@Memory.add_exists mem_src0 loc from to msg_src); eauto.\n  { i. hexploit lower_memory_get_inv; eauto. i. des. eauto. }\n  i. des. esplits; eauto. econs. i.\n  erewrite (@Memory.add_o mem2); eauto. erewrite (@Memory.add_o mem_tgt1); eauto. des_ifs.\n  { des; clarify. econs; eauto. }\n  { eapply MEM. }\nQed.\n\nLemma lower_memory_split mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc ts0 ts1 ts2 msg_src msg_tgt msg_src3 msg_tgt3 mem_tgt1 mem_src1\n      (SPLITTGT: Memory.split mem_tgt0 loc ts0 ts1 ts2 msg_tgt msg_tgt3 mem_tgt1)\n      (SPLITSRC: Memory.split mem_src0 loc ts0 ts1 ts2 msg_src msg_src3 mem_src1)\n      (MSG: Message.le msg_src msg_tgt)\n  :\n    lower_memory mem_src1 mem_tgt1.\nProof.\n  econs. i.\n  erewrite (@Memory.split_o mem_src1); eauto. erewrite (@Memory.split_o mem_tgt1); eauto. des_ifs.\n  { des; clarify. econs; eauto. }\n  { clear o. econs.\n    eapply Memory.split_get0 in SPLITTGT.\n    eapply Memory.split_get0 in SPLITSRC. des.\n    inv MEM. specialize (LOWER loc ts2).\n    rewrite GET4 in LOWER. rewrite GET0 in LOWER. inv LOWER. auto.\n  }\n  { eapply MEM. }\nQed.\n\nLemma lower_memory_lower mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc from to msg_src1 msg_tgt1 msg_src2 msg_tgt2 mem_tgt1 mem_src1\n      (SPLITTGT: Memory.lower mem_tgt0 loc from to msg_tgt1 msg_tgt2 mem_tgt1)\n      (SPLITSRC: Memory.lower mem_src0 loc from to msg_src1 msg_src2 mem_src1)\n      (MSG: Message.le msg_src2 msg_tgt2)\n  :\n    lower_memory mem_src1 mem_tgt1.\nProof.\n  econs. i.\n  erewrite (@Memory.lower_o mem_src1); eauto. erewrite (@Memory.lower_o mem_tgt1); eauto. des_ifs.\n  { econs.\n    eapply Memory.lower_get0 in SPLITTGT.\n    eapply Memory.lower_get0 in SPLITSRC. des.\n    inv MEM. specialize (LOWER loc to).\n    rewrite GET1 in LOWER. rewrite GET in LOWER. inv LOWER. auto.\n  }\n  { eapply MEM. }\nQed.\n\nLemma lower_memory_remove mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc from to msg_src msg_tgt mem_tgt1 mem_src1\n      (REMOVETGT: Memory.remove mem_tgt0 loc from to msg_tgt mem_tgt1)\n      (REMOVESRC: Memory.remove mem_src0 loc from to msg_src mem_src1)\n  :\n    lower_memory mem_src1 mem_tgt1.\nProof.\n  econs. i.\n  erewrite (@Memory.remove_o mem_src1); eauto. erewrite (@Memory.remove_o mem_tgt1); eauto. des_ifs.\n  { econs. }\n  { eapply MEM. }\nQed.\n\nLemma lower_memory_promise mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc from to prom0 msg prom1 mem_tgt1 kind\n      (PROMISE: Memory.promise prom0 mem_tgt0 loc from to msg prom1 mem_tgt1 kind)\n      (MLE: Memory.le prom0 mem_src0)\n  :\n    exists mem_src1,\n      (<<PROMISE: Memory.promise prom0 mem_src0 loc from to msg prom1 mem_src1 kind>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>).\nProof.\n  inv PROMISE.\n  { hexploit lower_memory_add; try eassumption.\n    { refl. }\n    { auto. }\n    i. des.\n    hexploit (@Memory.add_exists_le prom0 mem_src0); eauto. i. des.\n    esplits; eauto. econs; eauto.\n    ii. hexploit lower_memory_get_inv; [eapply MEM|..]; eauto.\n    i. des. eapply ATTACH; eauto.\n  }\n  { hexploit (@Memory.split_exists_le prom0 mem_src0); eauto. i. des.\n    esplits; eauto. eapply lower_memory_split; eauto. refl. }\n  { hexploit (@Memory.lower_exists_le prom0 mem_src0); eauto. i. des.\n    esplits; eauto. eapply lower_memory_lower; eauto. refl. }\n  { hexploit (@Memory.remove_exists_le prom0 mem_src0); eauto. i. des.\n    esplits; eauto. eapply lower_memory_remove; eauto. }\nQed.\n\nLemma lower_memory_write mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      loc from to prom0 msg_src msg_tgt prom1 mem_tgt1 kind_tgt\n      (WRITETGT: Memory.write prom0 mem_tgt0 loc from to msg_tgt prom1 mem_tgt1 kind_tgt)\n      (MLE: Memory.le prom0 mem_src0)\n      (MSG: Message.le msg_src msg_tgt)\n      (WF: Message.wf msg_src)\n      (MSGTO: Memory.message_to msg_tgt loc to -> Memory.message_to msg_src loc to)\n  :\n    exists mem_src1 kind_src,\n      (<<WRITESRC: Memory.write prom0 mem_src0 loc from to msg_src prom1 mem_src1 kind_src>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<KIND: kind_src = kind_tgt>>).\nProof.\n  inv WRITETGT. inv PROMISE.\n  { hexploit lower_memory_add; eauto. i. des.\n    hexploit (@Memory.add_exists_le prom0 mem_src0); eauto. i. des.\n    esplits; eauto. econs; eauto.\n    { econs; eauto.\n      ii. hexploit lower_memory_get_inv; [eapply MEM|..]; eauto.\n      i. des. eapply ATTACH; eauto. ii. subst. inv MSG; ss. }\n    { hexploit (@MemoryMerge.add_remove loc from to msg_tgt prom0); eauto.\n      i. subst. hexploit Memory.remove_exists.\n      { eapply Memory.add_get0. eauto. }\n      i. des.\n      hexploit (@MemoryMerge.add_remove loc from to msg_src prom1); eauto.\n      i. subst. auto.\n    }\n  }\n  { hexploit split_succeed_wf; try apply PROMISES; eauto. i. des.\n    hexploit (@Memory.split_exists prom0 loc from to ts3 msg_src msg3); eauto.\n    i. des. hexploit (@Memory.split_exists_le prom0 mem_src0); eauto. i. des.\n    esplits.\n    { econs.\n      { econs 2; eauto. inv MSG; ss. }\n      { dup H. eapply Memory.split_get0 in H. des.\n        hexploit (@Memory.remove_exists mem2).\n        { eapply GET1. }\n        i. des. replace prom1 with mem1; eauto.\n        eapply Memory.ext. i.\n        erewrite (@Memory.remove_o mem1); eauto.\n        erewrite (@Memory.split_o mem2); eauto.\n        erewrite (@Memory.remove_o prom1); eauto.\n        erewrite (@Memory.split_o promises2); [|eauto].\n        des_ifs.\n      }\n    }\n    { eapply lower_memory_split; eauto. }\n    { ss. }\n  }\n  { hexploit lower_succeed_wf; try apply PROMISES; eauto. i. des.\n    hexploit (@Memory.lower_exists prom0 loc from to msg0 msg_src); eauto.\n    { etrans; eauto. }\n    i. des. hexploit (@Memory.lower_exists_le prom0 mem_src0); eauto. i. des.\n    esplits.\n    { econs.\n      { econs 3; eauto. inv MSG; ss. }\n      { dup H. eapply Memory.lower_get0 in H. des.\n        hexploit (@Memory.remove_exists mem2).\n        { eapply GET1. }\n        i. des. replace prom1 with mem1; eauto.\n        eapply Memory.ext. i.\n        erewrite (@Memory.remove_o mem1); eauto.\n        erewrite (@Memory.lower_o mem2); eauto.\n        erewrite (@Memory.remove_o prom1); eauto.\n        erewrite (@Memory.lower_o promises2); [|eauto].\n        des_ifs.\n      }\n    }\n    { eapply lower_memory_lower; eauto. }\n    { ss. }\n  }\n  { inv MSG. hexploit (@Memory.remove_exists_le prom0 mem_src0); eauto. i. des.\n    esplits.\n    { econs.\n      { econs 4; eauto. }\n      { eauto. }\n    }\n    { eapply lower_memory_remove; eauto. }\n    { ss. }\n  }\nQed.\n\nLemma lower_memory_write_na\n      mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      ts_src ts_tgt loc from to prom0 val prom1 mem_tgt1 msgs kinds_tgt kind_tgt\n      (WRITETGT: Memory.write_na ts_tgt prom0 mem_tgt0 loc from to val prom1 mem_tgt1 msgs kinds_tgt kind_tgt)\n      (MLE: Memory.le prom0 mem_src0)\n      (TS: Time.le ts_src ts_tgt)\n  :\n    exists mem_src1 kinds_src kind_src,\n      (<<WRITESRC: Memory.write_na ts_src prom0 mem_src0 loc from to val prom1 mem_src1 msgs kinds_src kind_src>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<KINDS: kinds_src = kinds_tgt>>) /\\\n      (<<KIND: kind_src = kind_tgt>>).\nProof.\n  revert mem_src0 ts_src TS MEM MLE. induction WRITETGT.\n  { i. hexploit lower_memory_write;\n         try match goal with\n             | [|- Message.le _ _] => refl\n             end; eauto.\n    i. des. esplits; eauto. econs; eauto. eapply TimeFacts.le_lt_lt; eauto.\n  }\n  { i. hexploit lower_memory_write; try eassumption.\n    { refl. }\n    { destruct MSG_EX; des; clarify. econs; eauto. }\n    { destruct MSG_EX; des; clarify. }\n    i. des. hexploit IHWRITETGT.\n    { refl. }\n    { eauto. }\n    { eapply write_memory_le; eauto. }\n    i. des. esplits.\n    { econs 2; eauto. eapply TimeFacts.le_lt_lt; eauto. }\n    { eauto. }\n    { f_equal; eauto. }\n    { eauto. }\n  }\nQed.\n\nLemma lower_memory_promise_step mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 lc_tgt1 mem_tgt1 loc from to msg kind\n      (STEP: Local.promise_step lc_tgt0 mem_tgt0 loc from to msg lc_tgt1 mem_tgt1 kind)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (WF: Memory.le lc_src0.(Local.promises) mem_src0)\n  :\n    exists mem_src1 lc_src1,\n      (<<STEP: Local.promise_step lc_src0 mem_src0 loc from to msg lc_src1 mem_src1 kind>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>).\nProof.\n  inv LOCAL. inv STEP. hexploit lower_memory_promise; eauto.\n  i. des. ss. esplits; eauto.\n  { econs; eauto. eapply lower_memory_closed_message; eauto. }\n  { econs; eauto. }\nQed.\n\nLemma lower_memory_read_step mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 loc to val released_tgt ord lc_tgt1\n      (STEP: Local.read_step lc_tgt0 mem_tgt0 loc to val released_tgt ord lc_tgt1)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (CLOSED: Memory.closed mem_src0)\n  :\n    exists lc_src1 released_src,\n      (<<STEP: Local.read_step lc_src0 mem_src0 loc to val released_src ord lc_src1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<RELEASED: View.opt_le released_src released_tgt>>) /\\\n      (<<RELWF: View.opt_wf released_src>>)\n.\nProof.\n  inv LOCAL. inv STEP. hexploit lower_memory_get; eauto.\n  i. des. inv MESSAGE.\n  hexploit TViewFacts.readable_mon; eauto.\n  { eapply TVIEW. }\n  { refl. }\n  i. esplits; eauto.\n  { econs; eauto. etrans; eauto. }\n  { econs; eauto. ss. eapply read_tview_mon; eauto. refl. }\n  { eapply CLOSED in GETSRC. des. inv MSG_WF. auto. }\nQed.\n\nLemma lower_memory_fence_step\n      lc_src0 lc_tgt0 ordr ordw lc_tgt1 sc_tgt0 sc_tgt1 sc_src0\n      (STEP: Local.fence_step lc_tgt0 sc_tgt0 ordr ordw lc_tgt1 sc_tgt1)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n  :\n    exists lc_src1 sc_src1,\n      (<<STEP: Local.fence_step lc_src0 sc_src0 ordr ordw lc_src1 sc_src1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>)\n.\nProof.\n  inv LOCAL. inv STEP. esplits.\n  { econs; ss. }\n  { econs; ss. eapply write_fence_tview_mon_same_ord; eauto.\n    eapply read_fence_tview_mon_same_ord; eauto. }\n  { eapply write_fence_fc_mon_same_ord; eauto.\n    eapply read_fence_tview_mon_same_ord; eauto. }\nQed.\n\nLemma lower_memory_write_step mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 sc_tgt0 loc from to val releasedr_tgt releasedw_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt\n      releasedr_src sc_src0\n      (STEP: Local.write_step lc_tgt0 sc_tgt0 mem_tgt0 loc from to val releasedr_tgt releasedw_tgt ord lc_tgt1 sc_tgt1 mem_tgt1 kind_tgt)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n      (WFSRC: Local.wf lc_src0 mem_src0)\n      (WFTGT: Local.wf lc_tgt0 mem_tgt0)\n      (RELSRC: View.opt_wf releasedr_src)\n      (RELTGT: View.opt_wf releasedr_tgt)\n      (RELEASEDR: View.opt_le releasedr_src releasedr_tgt)\n  :\n    exists lc_src1 mem_src1 releasedw_src kind_src sc_src1,\n      (<<STEP: Local.write_step lc_src0 sc_src0 mem_src0 loc from to val releasedr_src releasedw_src ord lc_src1 sc_src1 mem_src1 kind_src>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<RELEASEDW: View.opt_le releasedw_src releasedw_tgt>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>) /\\\n      (<<KIND: kind_src = kind_tgt>>)\n.\nProof.\n  inv LOCAL. inv STEP.\n  hexploit TViewFacts.writable_mon; eauto.\n  { eapply TVIEW. }\n  { refl. }\n  i. ss. hexploit lower_memory_write; try eassumption.\n  { eapply WFSRC. }\n  { econs; [refl|]. eapply TViewFacts.write_released_mon; try eassumption.\n    { eapply WFTGT. }\n    { refl. }\n  }\n  { econs; ss. eapply TViewFacts.write_future0; eauto. eapply WFSRC. }\n  { i. inv H0. econs. etrans; eauto.\n    hexploit TViewFacts.write_released_mon; eauto.\n    { eapply WFTGT. }\n    { refl. }\n    i. eapply View.unwrap_opt_le in H0. eapply H0.\n  }\n  i. des. esplits; eauto.\n  { ss. econs; eauto. eapply TViewFacts.write_tview_mon; eauto.\n    { eapply WFTGT. }\n    { refl. }\n  }\n  { eapply TViewFacts.write_released_mon; eauto.\n    { eapply WFTGT. }\n    { refl. }\n  }\nQed.\n\nLemma lower_memory_write_na_step\n      mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 sc_tgt0 loc from to val ord lc_tgt1 sc_tgt1 mem_tgt1 msgs kinds_tgt kind_tgt\n      sc_src0\n      (STEP: Local.write_na_step lc_tgt0 sc_tgt0 mem_tgt0 loc from to val ord lc_tgt1 sc_tgt1 mem_tgt1 msgs kinds_tgt kind_tgt)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n      (WFSRC: Local.wf lc_src0 mem_src0)\n      (WFTGT: Local.wf lc_tgt0 mem_tgt0)\n  :\n    exists lc_src1 mem_src1 kinds_src kind_src sc_src1,\n      (<<STEP: Local.write_na_step lc_src0 sc_src0 mem_src0 loc from to val ord lc_src1 sc_src1 mem_src1 msgs kinds_src kind_src>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>) /\\\n      (<<KINDS: kinds_src = kinds_tgt>>) /\\\n      (<<KIND: kind_src = kind_tgt>>)\n.\nProof.\n  inv LOCAL. inv STEP. hexploit lower_memory_write_na; try eassumption.\n  { eapply WFSRC. }\n  { ss. eapply TVIEW. }\n  i. des. ss. esplits; eauto.\n  econs; ss. eapply TViewFacts.write_tview_mon; eauto. eapply WFTGT.\nQed.\n\nLemma lower_memory_is_racy mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0\n      loc to ord\n      (RACE: Local.is_racy lc_tgt0 mem_tgt0 loc to ord)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n  :\n    Local.is_racy lc_src0 mem_src0 loc to ord.\nProof.\n  inv LOCAL. inv RACE.\n  hexploit lower_memory_get; eauto. i. des.\n  hexploit TViewFacts.racy_view_mon; eauto.\n  { eapply TVIEW. }\n  i. econs; eauto.\n  { inv MESSAGE; ss. }\n  { i. hexploit MSG2; auto. i. subst. inv MESSAGE; ss. }\nQed.\n\nLemma lower_memory_program_step mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 sc_tgt0 lc_tgt1 sc_tgt1 mem_tgt1\n      sc_src0 e_tgt\n      (STEP: Local.program_step e_tgt lc_tgt0 sc_tgt0 mem_tgt0 lc_tgt1 sc_tgt1 mem_tgt1)\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n      (WFSRC: Local.wf lc_src0 mem_src0)\n      (WFTGT: Local.wf lc_tgt0 mem_tgt0)\n      (CLOSEDSRC: Memory.closed mem_src0)\n      (CLOSEDTGT: Memory.closed mem_tgt0)\n  :\n    exists e_src lc_src1 mem_src1 sc_src1,\n      (<<STEP: Local.program_step e_src lc_src0 sc_src0 mem_src0 lc_src1 sc_src1 mem_src1>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>) /\\\n      (<<EVENT: lower_event e_src e_tgt>>)\n.\nProof.\n  inv STEP.\n  { esplits; eauto. }\n  { hexploit lower_memory_read_step; eauto. i. des.\n     eexists (ThreadEvent.read _ _ _ _ _). esplits; eauto. }\n  { hexploit lower_memory_write_step; eauto. i. des.\n    eexists (ThreadEvent.write _ _ _ _ _ _). esplits; eauto. }\n  { hexploit lower_memory_read_step; eauto. i. des.\n    hexploit Local.read_step_future; try apply LOCAL1; eauto. i. des.\n    hexploit Local.read_step_future; try apply STEP; eauto. i. des.\n    hexploit lower_memory_write_step; eauto. i. des.\n    eexists (ThreadEvent.update _ _ _ _ _ _ _ _ _). esplits; eauto. }\n  { hexploit lower_memory_fence_step; eauto. i. des.\n    eexists (ThreadEvent.fence _ _). esplits; eauto. }\n  { hexploit lower_memory_fence_step; eauto. i. des.\n    eexists (ThreadEvent.syscall _). esplits; eauto. }\n  { inv LOCAL0.\n    eexists (ThreadEvent.failure). esplits; eauto.\n    econs. econs. eapply lower_local_consistent; eauto. }\n  { hexploit lower_memory_write_na_step; eauto. i. des.\n    eexists (ThreadEvent.write_na _ _ _ _ _ _). esplits; eauto. }\n  { inv LOCAL0. hexploit lower_memory_is_racy; eauto. i.\n    eexists (ThreadEvent.racy_read _ _ _ _). esplits; eauto. }\n  { inv LOCAL0. hexploit lower_memory_is_racy; eauto. i.\n    eexists (ThreadEvent.racy_write _ _ _ _). esplits; eauto.\n    econs; eauto. econs; eauto.\n    eapply lower_local_consistent; eauto. }\n  { eexists (ThreadEvent.racy_update _ _ _ _ _ _). esplits; eauto.\n    { econs. inv LOCAL0.\n      { econs 1; auto. eapply lower_local_consistent; eauto. }\n      { econs 2; auto. eapply lower_local_consistent; eauto. }\n      { hexploit lower_memory_is_racy; eauto. i.\n        econs 3; eauto. eapply lower_local_consistent; eauto. }\n    }\n  }\nQed.\n\nLemma lower_memory_thread_step lang st0 st1 mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 sc_tgt0 lc_tgt1 sc_tgt1 mem_tgt1\n      sc_src0 e_tgt pf\n      (STEP: Thread.step pf e_tgt (Thread.mk lang st0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n      (WFSRC: Local.wf lc_src0 mem_src0)\n      (WFTGT: Local.wf lc_tgt0 mem_tgt0)\n      (CLOSEDSRC: Memory.closed mem_src0)\n      (CLOSEDTGT: Memory.closed mem_tgt0)\n  :\n    exists e_src lc_src1 mem_src1 sc_src1,\n      (<<STEP: Thread.step pf e_src (Thread.mk _ st0 lc_src0 sc_src0 mem_src0) (Thread.mk _ st1 lc_src1 sc_src1 mem_src1)>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>) /\\\n      (<<EVENT: lower_event e_src e_tgt>>)\n.\nProof.\n  inv STEP.\n  { inv STEP0. hexploit lower_memory_promise_step; eauto.\n    { inv LOCAL. eapply WFSRC. }\n    i. des. esplits; eauto.\n    { econs 1. econs; eauto. }\n  }\n  { inv STEP0. hexploit lower_memory_program_step; eauto.\n    i. des. esplits; eauto.\n    econs 2. econs; eauto. erewrite lower_event_program_event; eauto.\n  }\nQed.\n\nLemma lower_memory_thread_opt_step lang st0 st1 mem_src0 mem_tgt0\n      (MEM: lower_memory mem_src0 mem_tgt0)\n      lc_src0 lc_tgt0 sc_tgt0 lc_tgt1 sc_tgt1 mem_tgt1\n      sc_src0 e_tgt\n      (STEP: Thread.opt_step e_tgt (Thread.mk lang st0 lc_tgt0 sc_tgt0 mem_tgt0) (Thread.mk _ st1 lc_tgt1 sc_tgt1 mem_tgt1))\n      (LOCAL: lower_local lc_src0 lc_tgt0)\n      (SC: TimeMap.le sc_src0 sc_tgt0)\n      (WFSRC: Local.wf lc_src0 mem_src0)\n      (WFTGT: Local.wf lc_tgt0 mem_tgt0)\n      (CLOSEDSRC: Memory.closed mem_src0)\n      (CLOSEDTGT: Memory.closed mem_tgt0)\n  :\n    exists e_src lc_src1 mem_src1 sc_src1,\n      (<<STEP: Thread.opt_step e_src (Thread.mk _ st0 lc_src0 sc_src0 mem_src0) (Thread.mk _ st1 lc_src1 sc_src1 mem_src1)>>) /\\\n      (<<MEM: lower_memory mem_src1 mem_tgt1>>) /\\\n      (<<LOCAL: lower_local lc_src1 lc_tgt1>>) /\\\n      (<<SC: TimeMap.le sc_src1 sc_tgt1>>) /\\\n      (<<EVENT: lower_event e_src e_tgt>>)\n.\nProof.\n  inv STEP.\n  { esplits; eauto. econs. }\n  { hexploit lower_memory_thread_step; eauto. i. des. esplits; eauto. econs; eauto. }\nQed.\n\nLemma lower_thread_step\n      lang e1_src\n      pf e_tgt e1_tgt e2_tgt\n      (LOWER: @lower_thread lang e1_src e1_tgt)\n      (STEP: Thread.step pf e_tgt e1_tgt e2_tgt)\n      (WFSRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n      (WFTGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (CLOSEDSRC: Memory.closed (Thread.memory e1_src))\n      (CLOSEDTGT: Memory.closed (Thread.memory e1_tgt))\n  :\n    exists e_src e2_src,\n      (<<STEP: Thread.step pf e_src e1_src e2_src>>) /\\\n      (<<EVENT: lower_event e_src e_tgt>>) /\\\n      (<<LOWER: lower_thread e2_src e2_tgt>>)\n.\nProof.\n  destruct e1_src, e1_tgt, e2_tgt. inv LOWER. ss. subst.\n  exploit lower_memory_thread_step;\n    try exact LOCAL; try exact SC; try exact MEMORY; eauto. i. des.\n  esplits; eauto. econs; eauto.\nQed.\n\nLemma lower_memory_max_ts\n      mem_src mem_tgt\n      (LOWER: lower_memory mem_src mem_tgt)\n      (MEM_SRC: Memory.inhabited mem_src)\n      (MEM_TGT: Memory.inhabited mem_tgt):\n  forall loc, Memory.max_ts loc mem_src = Memory.max_ts loc mem_tgt.\nProof.\n  i.\n  exploit Memory.max_ts_spec; try eapply MEM_SRC.\n  instantiate (1:=loc). i. des.\n  exploit Memory.max_ts_spec; try eapply MEM_TGT.\n  instantiate (1:=loc). i. des.\n  inv LOWER.\n  generalize (LOWER0 loc (Memory.max_ts loc mem_src)).\n  rewrite GET. i. inv H. symmetry in H3.\n  exploit Memory.max_ts_spec; try eapply H3. i. des.\n  generalize (LOWER0 loc (Memory.max_ts loc mem_tgt)).\n  rewrite GET0. i. inv H. symmetry in H1.\n  exploit Memory.max_ts_spec; try eapply H1. i. des.\n  apply TimeFacts.antisym; eauto.\nQed.\n\nLemma lower_memory_cap\n      mem_src mem_tgt\n      cap_src cap_tgt\n      (LOWER: lower_memory mem_src mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CAP_SRC: Memory.cap mem_src cap_src)\n      (CAP_TGT: Memory.cap mem_tgt cap_tgt):\n  lower_memory cap_src cap_tgt.\nProof.\n  dup LOWER. inv LOWER. rename LOWER1 into LOWER. econs. i.\n  destruct (Memory.get loc to cap_src) as [[from msg]|] eqn:GET_SRC.\n  { inv CAP_TGT.\n    exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des.\n    - generalize (LOWER loc to). rewrite x0. i. inv H.\n      exploit SOUND; eauto. intros x. rewrite x. econs. ss.\n    - subst. inv x1.\n      exploit (MIDDLE loc from1 from to to2); eauto; cycle 1.\n      { i. rewrite x1. econs. ss. }\n      generalize (LOWER loc from). rewrite GET1. i. inv H.\n      generalize (LOWER loc to2). rewrite GET2. i. inv H.\n      econs; eauto. i.\n      exploit EMPTY; eauto. intros x.\n      generalize (LOWER loc ts). rewrite x. i. inv H. ss.\n    - subst.\n      erewrite lower_memory_max_ts; eauto; try apply MEM_SRC; try apply MEM_TGT.\n      rewrite BACK. econs. ss.\n  }\n  { destruct (Memory.get loc to cap_tgt) as [[from msg]|] eqn:GET_TGT; try by econs.\n    exfalso. inv CAP_SRC.\n    exploit Memory.cap_inv; try exact CAP_TGT; eauto. i. des.\n    - generalize (LOWER loc to). rewrite x0. i. inv H.\n      exploit SOUND; eauto. intros x. rewrite x in *. ss.\n    - subst. inv x1.\n      exploit (MIDDLE loc from1 from to to2); eauto; cycle 1.\n      { i. rewrite x1 in *. ss. }\n      generalize (LOWER loc from). rewrite GET1. i. inv H.\n      generalize (LOWER loc to2). rewrite GET2. i. inv H.\n      econs; eauto. i.\n      exploit EMPTY; eauto. intros x.\n      generalize (LOWER loc ts). rewrite x. i. inv H. ss.\n    - subst.\n      erewrite <- lower_memory_max_ts in GET_SRC; eauto;\n        try apply MEM_SRC; try apply MEM_TGT.\n      rewrite BACK in *. ss.\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/LowerMemory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.16692943992931947}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.tests.Echo2 Platform.Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [Echo2.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"test\"!\"main\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link Echo2.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link Echo2.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/tests/Echo2Driver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16685327665694713}}
{"text": "Require Import Coq.Lists.List Bedrock.DepList.\nRequire Import Bedrock.Heaps.\nRequire Import Bedrock.Expr Bedrock.SepExpr Bedrock.SymEval.\n\nModule EvaluatorTests (B : Heap) (ST : SepTheoryX.SepTheoryXType B).\n  Module Import SE := Evaluator B ST.\n\n  Section Tests.\n    Variable a b : Type.\n\n    Variable ptsto32 : B.addr -> W -> ST.hprop a b nil.\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 addr_type : Expr.type :=\n      {| Expr.Impl := B.addr\n       ; Expr.Eq := fun x y => match B.addr_dec x y with\n                                 | left pf => Some pf\n                                 | right _ => None\n                               end\n       |} .\n\n    Definition W_type : Expr.type :=\n      {| Expr.Impl := W\n       ; Expr.Eq := fun x y => match equiv_dec x y with\n                                 | left pf => Some pf\n                                 | right _ => None\n                               end\n       |}.\n\n    Definition a_type : Expr.type :=\n      {| Expr.Impl := a\n       ; Eq := fun _ _ => None\n       |}.\n    Definition b_type : Expr.type :=\n      {| Expr.Impl := b\n       ; Eq := fun _ _ => None\n       |}.\n\n    Require Import Bedrock.Word.\n\n    Definition pre_types : list Expr.type :=\n      a_type :: b_type :: addr_type :: W_type :: nil.\n\n    (** I need to universally quantify SymEval_word over the functions list\n     **\n     **)\n\n    Definition funcs : functions (wtypes pre_types 2 3) := nil.\n\n    Definition sfuncs : list (SEP.ssignature (wtypes pre_types 2 3) (tvType 0) (tvType 1)) :=\n      {| SDomain := tvType 2 :: tvType 3 :: nil\n       ; SDenotation := ptsto32 : functionTypeD\n         (map (tvarD (wtypes pre_types 2 3)) (tvType 2 :: tvType 3 :: nil))\n         (ST.hprop (tvarD (wtypes pre_types 2 3) (tvType 0))\n           (tvarD (wtypes pre_types 2 3) (tvType 1)) nil)\n       |} :: nil.\n\n    Definition Satisfies cs stn (P : ST.hprop a b nil) m : Prop :=\n      exists sm,\n          ST.satisfies cs P stn sm\n       /\\ ST.HT.satisfies sm m.\n\n    Theorem addr_not_state : 3 <> 2.\n      clear; auto.\n    Qed.\n\n    Definition known : list nat := 0 :: nil.\n\n    Definition evaluators : DepList.hlist (fun n : nat => match nth_error sfuncs n with\n                                                            | None => Empty_set\n                                                            | Some ss =>\n                                                              SymEval_word pre_types addr_not_state\n                                                                funcs\n                                                                (pcIndex := 0) (stateIndex := 1) ss\n                                                          end) known.\n      refine (DepList.HCons _ DepList.HNil); simpl.\n      refine (\n        {| sym_read_word := fun _ args p =>\n           match args with\n             | p' :: v :: nil =>\n               if seq_dec p p' then Some v else None\n             | _ => None\n           end\n         ; sym_write_word := fun _ args p v =>\n           match args with\n             | p' :: v' :: nil =>\n               if seq_dec p p' then Some (p' :: v :: nil) else None\n             | _ => None\n           end\n         ; sym_read_word_correct := _\n         ; sym_write_word_correct := _\n         |}).\n      admit.\n      admit.\n    Defined.\n\n    Ltac lift_evaluator_w e nt nf :=\n      let r := eval simpl sym_read_word in (sym_read_word e) in\n      let w := eval simpl sym_write_word in (sym_write_word e) in\n      let rc := eval simpl sym_read_word_correct in (sym_read_word_correct e) in\n      let wc := eval simpl sym_write_word_correct in (sym_write_word_correct e) in\n      match type of e with\n        | SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ ?s =>\n          match SE.SEP.lift_ssignatures (s :: nil) nt with\n            | ?s' :: nil =>\n              constr:(@Build_SymEval_word nt stI pcI ptrI wI pf nf s' r w rc wc)\n          end\n      end.\n\n    Ltac lift_evaluators_w es nt nf ns :=\n      let rec lift es :=\n        match es with\n          | @DepList.HNil _ (fun n : nat =>\n            match nth_error _ n with\n              | None => Empty_set\n              | Some ss => @SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ _\n            end) =>\n            let k :=\n              constr:(@DepList.HNil nat (fun n : nat =>\n                match nth_error ns n with\n                  | None => Empty_set\n                  | Some ss => @SymEval_word nt stI pcI ptrI wI pf nf ss\n                end))\n            in k\n          | @DepList.HCons _ (fun n : nat =>\n            match nth_error _ n with\n              | None => Empty_set\n              | Some ss => @SymEval_word _ ?stI ?pcI ?ptrI ?wI ?pf _ _\n            end) ?f ?ls ?e ?es =>\n          idtac \"ok\" ;\n            let es := lift es in\n              idtac \"here\" e ;\n            let e := lift_evaluator_w e nt nf in\n              idtac \"got here \" ;\n            constr:(@DepList.HCons _ (fun n : nat =>\n                match nth_error ns n with\n                  | None => Empty_set\n                  | Some ss => @SymEval_word nt stI pcI ptrI wI pf nf ss\n                end) f ls e es)\n        end\n      in\n      lift es.\n\n    Goal True.\n      Set Printing Implicit.\n      match goal with\n        | [ |- _ ] =>\n          let z := eval unfold evaluators in evaluators in\n            idtac \"foo\" z ;\n          let r := lift_evaluators_w z pre_types funcs sfuncs in\n            idtac \"here\" ;\n            idtac r\n      end.\n\n            constr:(@DepList.HNil nat (fun n : nat =>\n              match nth_error sfuncs n with\n                | None => Empty_set\n                | Some ss =>\n                  SymEval_word nt addr_not_state\n                  funcs\n                  (pcIndex := 0) (stateIndex := 1) ss\n              end) nil)\n(*\n    Goal forall p1 p2 p3 v1 v2 v3 cs stn m,\n      Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v2) (ptsto32 p3 v3))) m\n      -> mem_get_word B.addr B.mem B.footprint_w B.mem_get (IL.implode stn) p1 m = Some v1.\n    Proof.\n      intros.\n      match goal with\n        | [ H : Satisfies ?CS ?STN ?P ?M\n          |- context [ mem_get_word B.addr B.mem B.footprint_w B.mem_get (IL.implode stn) ?PTR ?M ] ] =>\n        let Ts := constr:(@nil Type) in\n        let Ts := SEP.collectAllTypes_sexpr ltac:(isConst) Ts (P :: nil) in\n        let Ts := SEP.collectAllTypes_expr ltac:(isConst) Ts (PTR, tt) in\n        let types := eval unfold pre_types in pre_types in\n        let types := SEP.extend_all_types Ts types in\n        let sexprs := constr:(P :: nil) in\n        match SEP.reify_sexprs a b ltac:(isConst) types tt tt sexprs with\n          | (?types, ?pcType, ?stateType, ?funcs, ?sfuncs, ?P :: nil) =>\n            match SEP.reify_exprs ltac:(isConst) types funcs (PTR, tt) with\n              | (?types, ?funcs, ?PTR :: nil) =>\n                let hyps := constr:(@nil (expr types)) in\n                let s := eval simpl in (SEP.hash P) in\n                generalize (@symeval_read_word_correct types 1 0 2 3 addr_not_state funcs sfuncs known)\n                  ; pose hyps\n(*\n                  hyps PTR (snd s) _ (refl_equal _) CS STN nil nil M I H)\n*)\n            end\n        end\n      end.\n      intros.\n      pose evaluators.\n\n\n\n      specialize (H0 evaluators).\n      (** TODO : the known list needs to be parameterized appropriately... **)\n\n      simpl. auto.\n    Qed.\n\n    Goal forall p1 p2 p3 v1 v2 v3 cs stn m,\n      Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v2) (ptsto32 p3 v3))) m\n      -> Satisfies cs stn (ST.star (ptsto32 p1 v1) (ST.star (ptsto32 p2 v3) (ptsto32 p3 v3)))\n           (mem_set_word B.addr B.mem B.footprint_w B.mem_set (IL.explode stn) p2 v3 m).\n    Proof.\n      intros.\n      match goal with\n        | [ H : Satisfies ?CS ?STN ?P ?M\n          |- context [ mem_set_word B.addr B.mem B.footprint_w B.mem_set (IL.explode stn) ?PTR ?VAL ?M ] ] =>\n        let Ts := constr:(@nil Type) in\n        let Ts := SEP.collectAllTypes_sexpr ltac:(isConst) Ts (P :: nil) in\n        let Ts := SEP.collectAllTypes_expr ltac:(isConst) Ts (PTR, (VAL, tt)) in\n        let types := eval unfold pre_types in pre_types in\n        let types := SEP.extend_all_types Ts types in\n        let sexprs := constr:(P :: nil) in\n        match SEP.reify_sexprs a b ltac:(isConst) types tt tt sexprs with\n          | (?types, ?pcType, ?stateType, ?funcs, ?sfuncs, ?P :: nil) =>\n             match SEP.reify_exprs ltac:(isConst) types funcs (PTR, (VAL, tt)) with\n              | (?types, ?funcs, ?PTR :: ?VAL :: nil) =>\n                 let hyps := constr:(@nil (expr pre_types)) in\n                let s := eval simpl in (SEP.hash P) in\n                generalize (@symeval_write_word_correct types 1 0 2 3 addr_not_state sfuncs known evaluators\n                  hyps PTR VAL (snd s) _ (refl_equal _) CS STN funcs nil nil M _ I (refl_equal _) H)\n            end\n        end\n      end.\n      simpl; auto.\n    Qed.\n*)\n\n  End Tests.\nEnd EvaluatorTests.\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/SymEvalTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.16685327665694713}}
{"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(** Coq Library *)\nRequire Import List.\nImport ListNotations. (* from List *)\nRequire Import Coq.Lists.ListDec.\nRequire Import Coq.Bool.Sumbool.\n\n(** Oqarina library *)\nRequire Import Oqarina.AADL.Kernel.categories.\nRequire Import Oqarina.AADL.Kernel.component.\nRequire Import Oqarina.AADL.Kernel.properties.\nRequire Import Oqarina.AADL.Kernel.typecheck.\n\nRequire Import Oqarina.AADL.Kernel.features_helper.\n\nRequire Import Oqarina.core.all.\nRequire Import Oqarina.coq_utils.all.\n\n(*| .. coq:: |*)\n\n(*|\n\nComponents Helper Library\n==========================\n|*)\n\nFixpoint Valid_Subcomponents_Category\n    (l : list component) (lcat : list ComponentCategory) :=\n    match l with\n        | nil => True\n        | h :: t => In (h->category) lcat /\\\n            Valid_Subcomponents_Category t lcat\n    end.\n\nLemma Valid_Subcomponents_Category_dec :\n    forall (l:list component) (lcat :list ComponentCategory),\n        { Valid_Subcomponents_Category l lcat } +\n        { ~Valid_Subcomponents_Category l lcat }.\nProof.\n    intros.\n    unfold Valid_Subcomponents_Category.\n    induction l.\n    auto.\n    apply dec_sumbool_and.\n    - apply In_dec; apply ComponentCategory_eq_dec.\n    - auto.\nQed.\n\nDefinition Well_Formed_Component_Subcomponents\n    (c: component) (l : list ComponentCategory) :=\n        Valid_Subcomponents_Category (c->subcomps) l.\n\nLemma Well_Formed_Component_Subcomponents_dec :\n    forall (c:component) (lcat :list ComponentCategory),\n        {Well_Formed_Component_Subcomponents c lcat} +\n        { ~Well_Formed_Component_Subcomponents c lcat}.\nProof.\n    intros.\n    unfold Well_Formed_Component_Subcomponents.\n    apply Valid_Subcomponents_Category_dec.\nQed.\n\n(* Resolve component \"name\" in the subcomponents of c *)\n\nDefinition Resolve_Subcomponent_In_Component\n    (name : identifier)\n    (c : component)\n    : option component\n:=\n    let results := filter (fun x => identifier_beq name (x->id)) (c->subcomps) in\n    hd_error results.\n\n(* Auxiliary function to resolve a subcomponnet in a hierarchy, starting from root. *)\n\nFixpoint Resolve_Subcomponent'\n    (root : component)\n    (path : list identifier)\n    (name : identifier)\n    (impl_name : option identifier)\n    : option component\n:=\n    match path with\n    | [] => Resolve_Subcomponent_In_Component name root\n    | h :: t =>\n        let node := Resolve_Subcomponent_In_Component h root in\n            match node with\n            | None => None\n            | Some c => Resolve_Subcomponent' c t name impl_name\n            end\n    end.\n\nDefinition Resolve_Subcomponent\n    (root : component)\n    (fqn : fq_name)\n    : option component\n:=\n    match fqn with\n    | FQN path name impl => Resolve_Subcomponent' root path name impl\n    end.\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/components_helper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.33111972642778714, "lm_q1q2_score": 0.16685327333086303}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import Omega.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\n\nRequire Import Chord.Chord.\nRequire Import Chord.HandlerLemmas.\nRequire Import Chord.HashInjective.\nRequire Import Chord.NodesHaveState.\nRequire Import Chord.PairIn.\nRequire Import Chord.SystemReachable.\nRequire Import Chord.SystemLemmas.\nRequire Import Chord.SystemPointers.\nRequire Import Chord.ValidPointersInvariant.\nRequire Import Chord.SuccessorNodesAlwaysValid.\nRequire Import Chord.NodesNotJoinedHaveNoSuccessors.\nRequire Import Chord.QueryTargetsJoined.\nRequire Import Chord.QueryInvariant.\nRequire Import Chord.LiveNodeInSuccLists.\nRequire Import Chord.LiveNodePreservation.\nRequire Import Chord.PtrCorrectInvariant.\nRequire Import Chord.Sorting.\nRequire Import Chord.StabilizeOnlyWithFirstSucc.\nRequire Import Chord.WfPtrSuccListInvariant.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDefinition sufficient_principals (gst : global_state) : Prop :=\n  exists ps,\n    principals gst ps /\\\n    length ps > SUCC_LIST_LEN.\nHint Unfold sufficient_principals.\n\nDefinition have_principals (gst : global_state) (n : nat) : Prop :=\n  exists ps,\n    NoDup ps /\\\n    Forall (principal gst) ps /\\\n    length ps >= n.\n\nFixpoint not_skipped_bool (h : id) (succs : list id) (n : id) :=\n  match succs with\n  | [] => true\n  | a :: succs' =>\n    if between_bool h n a then\n      false\n    else\n      not_skipped_bool a succs' n\n  end.\n\nLemma not_skipped_initial :\n  forall h x succs n,\n    not_skipped h (x :: succs) n ->\n    not_skipped x succs n.\nProof.\n  intros.\n  unfold not_skipped. intros.\n  match goal with\n  | H : not_skipped _ _ _ |- _ =>\n    specialize (H a b (h :: xs) ys)\n  end.\n  simpl in *. repeat find_rewrite. intuition.\nQed.\n\n\nLemma not_skipped_initial' :\n  forall h x succs n,\n    not_skipped x succs n ->\n    ~ between h n x ->\n    not_skipped h (x :: succs) n.\nProof.\n  intros.\n  unfold not_skipped. intros.\n  destruct xs.\n  - simpl in *. find_inversion. auto.\n  - simpl in *. find_inversion. unfold not_skipped in *. simpl in *. eauto.\nQed.\n\nLemma not_skipped_not_skipped_bool :\n  forall succs h n,\n    not_skipped h succs n ->\n    not_skipped_bool h succs n = true.\nProof.\n  induction succs;\n    intros; simpl in *; auto.\n  break_match; auto.\n  - exfalso.\n    match goal with\n    | H : not_skipped _ _ _ |- _ =>\n      specialize (H h a [] succs)\n    end.\n    simpl in *. intuition.\n    eauto using between_bool_between.\n  - eauto using not_skipped_initial.\nQed.\n\nLemma not_skipped_bool_not_skipped :\n  forall succs h n,\n    not_skipped_bool h succs n = true ->\n    not_skipped h succs n.\nProof.\n  induction succs;\n    intros; simpl in *; auto.\n  - unfold not_skipped. intros.\n    destruct xs; simpl in *; try congruence.\n    destruct xs; simpl in *; try congruence.\n  - break_match; try congruence.\n    find_apply_hyp_hyp. eapply not_skipped_initial'; eauto.\nQed.\n\nDefinition forallb_exists :\n  forall A f (l : list A),\n    forallb f l = false ->\n    exists x,\n      In x l /\\ f x = false.\nProof.\n  intros. induction l; simpl in *; try congruence.\n  do_bool. intuition eauto.\n  break_exists_exists. intuition.\nQed.\n\nDefinition succs_on_msg m :=\n  match m with\n  | GotSuccList succs => Some succs\n  | GotPredAndSuccs p succs => Some succs\n  | _ => None\n  end.\n\nLemma succs_on_msg_succs_msg :\n  forall m succs,\n    succs_on_msg m = Some succs ->\n    succs_msg m succs.\nProof.\n  intros. destruct m; simpl in *; solve_by_inversion.\nQed.\n\nLemma succs_msg_succs_on_msg :\n  forall m succs,\n    succs_msg m succs ->\n    succs_on_msg m = Some succs.\nProof.\n  intros. inv_prop succs_msg; simpl; intuition.\nQed.\n\nDefinition no_live_node_skips_dec :\n  forall gst h,\n    {no_live_node_skips gst h} + {~ no_live_node_skips gst h}.\nProof.\n  intros.\n  destruct (forallb (fun h' => match sigma gst h' with\n                            | Some st => not_skipped_bool (hash h')\n                                                         (map id_of (succ_list st)) (hash h)\n                            | None => true\n                            end) (live_addrs gst)) eqn:?; autounfold; [left|right]; intuition.\n  - find_eapply_lem_hyp forallb_forall; eauto using live_addr_In_live_addrs.\n    repeat find_rewrite. eauto using not_skipped_bool_not_skipped.\n  - find_apply_lem_hyp forallb_exists.\n    break_exists. intuition. find_apply_lem_hyp In_live_addrs_live.\n    break_match; try congruence.\n    eapply_prop_hyp live_node live_node; eauto.\n    find_eapply_lem_hyp not_skipped_not_skipped_bool.\n    unfold ChordIDSpace.hash in *. congruence.\nQed.\n\nDefinition no_msg_to_live_node_skips_dec :\n  forall gst h,\n    {no_msg_to_live_node_skips gst h} + {~ no_msg_to_live_node_skips gst h}.\nProof.\n  intros.\n  destruct (forallb (fun p =>\n                       let '(src, (dst, m)) := p in\n                       match in_dec addr_eq_dec dst (nodes gst) with\n                       | left _ => \n                         match in_dec addr_eq_dec dst (failed_nodes gst) with\n                         | left _ => true\n                         | right _ =>\n                           match succs_on_msg m with\n                           | Some succs => not_skipped_bool (hash src) (map id_of succs) (hash h)\n                           | None => true\n                           end\n                         end\n                       | right _ => true\n                       end)\n                    (msgs gst)) eqn:?; autounfold; [left|right]; intuition.\n  - find_eapply_lem_hyp forallb_forall; eauto.\n    simpl in *. repeat (break_match; try congruence).\n    + find_apply_lem_hyp succs_msg_succs_on_msg. repeat find_rewrite. find_inversion.\n      eauto using not_skipped_bool_not_skipped.\n    + find_apply_lem_hyp succs_msg_succs_on_msg. repeat find_rewrite. congruence.\n  - find_apply_lem_hyp forallb_exists.\n    break_exists. intuition.\n    repeat (break_match; try congruence). subst.\n    find_apply_lem_hyp succs_on_msg_succs_msg.\n    eapply_prop_hyp msgs msgs; eauto.\n    find_eapply_lem_hyp not_skipped_not_skipped_bool.\n    unfold ChordIDSpace.hash in *. congruence.\nQed.\n    \nDefinition principal_dec :\n  forall gst h,\n    {principal gst h} + {~ principal gst h}.\nProof.\n  intros. unfold principal.\n  destruct (live_node_dec gst h); intuition.\n  destruct (no_live_node_skips_dec gst h); intuition.\n  destruct (no_msg_to_live_node_skips_dec gst h); intuition.\nQed.\n\nDefinition compute_principals (gst : global_state) : list addr :=\n  dedup\n    addr_eq_dec\n    (filter\n       (fun h => ssrbool.is_left (principal_dec gst h))\n       (nodes gst)).\n\nLemma compute_principals_correct :\n  forall gst,\n    principals gst (compute_principals gst).\nProof.\n  unfold compute_principals, principals.\n  repeat split; [now eapply NoDup_dedup|apply Forall_forall|]; intros.\n  - find_eapply_lem_hyp in_dedup_was_in.\n    find_eapply_lem_hyp filter_In; break_and.\n    destruct (principal_dec gst x);\n      simpl in *; congruence.\n  - apply dedup_In.\n    apply filter_In; split.\n    + inv_prop principal.\n      now inv_prop live_node.\n    + destruct (principal_dec gst p);\n        simpl in *; congruence.\nQed.\n\nLemma some_principals_ok :\n  forall gst,\n    have_principals gst (SUCC_LIST_LEN + 1) ->\n    sufficient_principals gst.\nProof.\n  intros.\n  inv_prop have_principals; break_and.\n  pose proof (compute_principals_correct gst).\n  inv_prop principals; break_and.\n  assert (incl x (compute_principals gst)).\n  {\n    unfold incl; intros.\n    rewrite -> ?Forall_forall in *; eauto.\n  }\n  find_eapply_lem_hyp NoDup_incl_length; auto.\n  eexists.\n  split; eauto; omega.\nQed.\n\nDefinition zave_invariant (gst : global_state) : Prop :=\n  sufficient_principals gst /\\\n  live_node_in_succ_lists gst /\\\n  live_node_in_msg_succ_lists gst.\nHint Unfold zave_invariant.\n\nLemma sorted_trans :\n  forall A (le : A -> A -> bool),\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    forall x y l,\n      Sorting.sorted A le (x :: l) ->\n      In y l ->\n      le x y = true.\nProof.\n  intros. prep_induction H0.\n  induction H0; intros; simpl in *; auto.\n  - solve_by_inversion.\n  - find_inversion. intuition.\n  - intuition. find_inversion. simpl in *.\n    intuition; subst; eauto.\nQed.\n\nLemma sorted_trans_app :\n  forall A (le : A -> A -> bool),\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    forall x y l' l,\n      Sorting.sorted A le (l' ++ l) ->\n      In y l ->\n      In x l' ->\n      le x y = true.\nProof.\n  intros. prep_induction H0.\n  induction H0; intros; simpl in *; auto.\n  - destruct l', l; subst; simpl in *; solve_by_inversion.\n  - destruct l', l; subst; simpl in *; try solve_by_inversion.\n    find_inversion. destruct l'; simpl in *; solve_by_inversion.\n  - intuition.\n    destruct l'; intuition; simpl in *. find_inversion. intuition.\n    + subst. destruct l'; simpl in *; intuition.\n      * subst. in_crush. eauto using sorted_trans.\n      * find_inversion.\n        eapply H1; eauto.\n        eapply sorted_trans; eauto. in_crush.\n    + destruct l'; simpl in *; intuition; subst.\n      * find_inversion.\n        eapply sorted_trans; eauto. in_crush.\n      * find_inversion.\n        specialize (H5 x0 y0 (a0 :: l') l0).\n        intuition.\nQed.\n\nLemma between_trans :\n  forall a b c d,\n    between a b c ->\n    between a c d ->\n    between a b d.\nProof.\n  intros.\n  invcs H; invcs H0;\n    try solve [econstructor; eauto using lt_trans];\n    congruence.\nQed.\n\nLemma unroll_between_trans :\n  forall a b c d,\n    unroll_between a b c = true ->\n    unroll_between a c d = true ->\n    unroll_between a b d = true.\nProof.\n  unfold unroll_between; intros.\n  repeat break_if; eauto; try congruence.\n  repeat find_apply_lem_hyp between_bool_between.\n  apply between_between_bool_equiv.\n  eauto using between_trans.\nQed.\n\nLemma unroll_between_ptr_trans :\n  forall a b c d,\n    unroll_between_ptr a b c = true ->\n    unroll_between_ptr a c d = true ->\n    unroll_between_ptr a b d = true.\nProof.\n  unfold unroll_between_ptr in *.\n  eauto using unroll_between_trans.\nQed.\n\nLemma between_trans' :\n  forall a b c d,\n    between a b c ->\n    between b d c ->\n    between a d c.\nProof.\n  intros.\n  invcs H; invcs H0;\n    try solve [econstructor; eauto using lt_trans];\n    congruence.\nQed.\n\nLemma between_swap_not :\n  forall x y z,\n    between x z y ->\n    ~ between x y z.\nProof.\n  unfold not.\n  intros.\n  repeat invcs_prop between;\n    solve [id_auto | eapply Chord.ChordIDSpace.lt_asymm; eauto].\nQed.\n\nLemma between_not_between :\n  forall h a b c,\n    between h a b ->\n    between h b c ->\n    ~ between a c b.\nProof.\n  intros. intro.\n  find_eapply_lem_hyp between_trans'; eauto.\n  find_eapply_lem_hyp between_swap_not; eauto.\nQed.\n\n\nLemma between_not_between' :\n  forall h a b c,\n    between h a b ->\n    between h c a  ->\n    ~ between a c b.\nProof.\n  intros. intro.\n  specialize (between_not_between h c a b). intros. intuition.\n  destruct (id_eq_dec a b); subst.\n  - find_apply_lem_hyp not_between_xyy. auto.\n  - find_apply_lem_hyp between_rot_l; auto.\nQed.\n\nLemma sorted_map :\n  forall A B (f : A -> B) (leA : A -> A -> bool) (leB : B -> B -> bool),\n    (forall x y, leA x y = leB (f x) (f y)) ->\n    forall l,\n      sorted A leA l -> sorted B leB (map f l).\nProof.\n  induction l; intros; simpl in *; auto.\n  - constructor.\n  - inv_prop sorted.\n    + simpl. constructor.\n    + intuition. simpl. constructor; eauto.\nQed.\n\nLemma sorted_prepend_zero :\n  forall A (le : A -> A -> bool) z,\n    (forall x, le z x = true) ->\n    forall l,\n      sorted A le l ->\n      sorted A le (z :: l).\nProof.\n  induction l; intros.\n  - constructor.\n  - constructor; auto.\nQed.\n\nLemma sorted_chop_succs :\n  forall a n l,\n    sorted _ (unroll_between_ptr a) l ->\n    sorted _ (unroll_between_ptr a) (firstn n l).\nProof.\n  induction n; intros; simpl.\n  - constructor.\n  - break_match; try solve [constructor].\n    inv_prop sorted.\n    + destruct n; simpl; constructor.\n    + destruct n; simpl; try solve [constructor].\n      constructor; auto.\n      eapply_prop_hyp sorted sorted. simpl in *. auto.\nQed.\n\nLemma sorted_tl :\n  forall b l,\n    sorted _ (unroll_between_ptr b) l ->\n    sorted _ (unroll_between_ptr b) (List.tl l).\nProof.\n  destruct l.\n  - simpl; tauto.\n  - simpl.\n    intros;\n      inv_prop sorted; eauto || constructor.\nQed.\n\nLemma sort_by_between_sorted :\n  forall h l,\n    sorted _ (unroll_between_ptr h) (sort_by_between h l).\nProof.\n  intros. unfold sort_by_between.\n  apply sorted_sort.\n  intros. unfold unroll_between_ptr, unroll_between.\n  repeat (break_if; auto).\n  match goal with\n  | |- context [between_bool ?x ?y ?z] => specialize (between_bool_yz_total x y z)\n  end. intros. intuition.\nQed.\n\nLemma chop_succs_partition :\n  forall l,\n  exists xs,\n    l = chop_succs l ++ xs.\nProof.\n  intros. unfold chop_succs.\n  eexists; eauto using firstn_skipn.\nQed.\n\nLemma pair_in_sorted :\n  forall A (le : A -> A -> bool) l a b,\n    sorted _ le l ->\n    pair_in a b l ->\n    le a b = true.\nProof.\n  intros. induction H.\n  - inv_prop @pair_in.\n  - repeat inv_prop @pair_in.\n  - inv_prop @pair_in; eauto.\nQed.\n\nLemma pair_in_right :\n  forall A (a : A) b l,\n    pair_in a b l ->\n    In a l.\nProof.\n  intros. induction H.\n  - in_crush.\n  - in_crush.\nQed.\n\nLemma pair_in_left :\n  forall A (a : A) b l,\n    pair_in a b l ->\n    In b l.\nProof.\n  intros. induction H.\n  - in_crush.\n  - in_crush.\nQed.\n\nLemma pair_in_sorted_in :\n  forall A (le : A -> A -> bool) l a b x,\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    sorted _ le l ->\n    pair_in a b l ->\n    In x l ->\n    x = a \\/ x = b \\/\n    le x a = true \\/\n    le b x = true.\nProof.\n  intros. induction H0.\n  - solve_by_inversion.\n  - in_crush. inv_prop @pair_in. solve_by_inversion.\n  - inv_prop @pair_in.\n    + in_crush.\n       eauto using sorted_trans.\n    + intuition. in_crush. inv_prop @pair_in; intuition.\n      right. right. left. eauto using sorted_trans, pair_in_right.\nQed.\n\nLemma NoDup_pair :\n  forall A (l : list A) a b,\n    NoDup l ->\n    pair_in a b l ->\n    a <> b.\nProof.\n  intros. induction l.\n  - solve_by_inversion.\n  - inv_prop NoDup. inv_prop @pair_in; eauto.\n    intro. subst. intuition.\nQed.\n\nLemma sorted_zero_prefix :\n  forall A (le : A -> A -> bool) (wf : A -> Prop) (A_eq_dec: forall x y : A, {x = y} + {x <> y}) l a,\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    (forall b, le a b = true) ->\n    (forall b, wf b -> le b a = true -> b = a) ->\n    (forall x, In x l -> wf x) ->\n    sorted _ le l ->\n    exists xs ys,\n      l = xs ++ ys /\\\n      (forall x, In x xs -> x = a) /\\\n      (forall y, In y ys -> y <> a).\nProof.\n  intros.\n  induction H3.\n  - exists [],[]. in_crush.\n  - destruct (A_eq_dec x a); subst.\n    + exists [a],[]. in_crush.\n    + exists [],[x]. in_crush.\n  - destruct (A_eq_dec x a); subst.\n    + conclude_using in_crush.\n      break_exists_name xs.\n      exists (a :: xs). simpl.\n      break_exists_exists. intuition. congruence.\n    + conclude_using in_crush.\n      break_exists_name xs.\n      assert (xs = []). {\n        destruct xs; intuition.\n        break_exists; intuition. simpl in *. find_inversion.\n        find_false.\n        apply H1; intuition. specialize (H5 a0). intuition. subst. auto.\n      } subst. simpl in *.\n      exists [].\n      break_exists_name ys.\n      exists (x :: ys).\n      simpl. intuition; subst; eauto.\nQed.\n\nLemma sorted_list_elements_between_pair_eq :\n  forall A (A_eq_dec : forall x y : A, {x=y}+{x<>y}) le (a b : A) l,\n    (forall x, le x x = true) ->\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    (forall x y, le x y = true -> le y x = true -> y = x) ->\n    sorted _ le l ->\n    pair_in a b l ->\n    forall p,\n      In p l ->\n      le a p = true ->\n      le p b = true ->\n      p = a \\/ p = b.\nProof.\n  induction 6.\n  - intros.\n    assert (forall x, In x l -> le b x = true).\n    {\n      intros. eapply sorted_trans; eauto.\n      now invcs_prop sorted.\n    }\n    simpl in *; intuition auto.\n  - invcs_prop sorted.\n    + inv_prop (pair_in a b).\n    + concludes; intros.\n      break_or_hyp; eauto.\n      assert (le y a = true).\n      {\n        find_eapply_lem_hyp pair_in_right.\n        destruct (A_eq_dec y a).\n        subst; eauto.\n        eapply sorted_trans; eauto.\n        simpl in *; tauto.\n      }\n      eauto.\nQed.\n\nLemma sorted_by_between_list_elements_between_pair_eq :\n  forall h a b l,\n    sorted _ (unroll_between_ptr h) l ->\n    pair_in a b l ->\n    (forall p q, In p l -> In q l -> id_of p = id_of q ->  p = q) ->\n    forall p,\n      In p l ->\n      unroll_between_ptr h a p = true ->\n      unroll_between_ptr h p b = true ->\n      p = a \\/ p = b.\nProof.\n  intros.\n  unfold unroll_between_ptr in *.\n  assert (sorted _ (unroll_between (hash h)) (map id_of l))\n    by (eapply sorted_map; eassumption || reflexivity).\n  find_eapply_lem_hyp sorted_list_elements_between_pair_eq;\n    eauto using unrolling_reflexive, unrolling_transitive, id_eq_dec, unrolling_antisymmetric, in_map, map_pair_in.\n  break_or_hyp; [left|right]; eauto using pair_in_left, pair_in_right.\nQed.\n\n(* TODO move to PairIn.v *)\nLemma pair_in_tl :\n  forall A (a b : A) l,\n    pair_in a b (List.tl l) ->\n    pair_in a b l.\nProof.\n  destruct l.\n  - tauto.\n  - simpl; intros.\n    now constructor.\nQed.\n\nLemma sorted_by_between_list_elements_between_pair_eq_tl_chop :\n  forall h a b l,\n    sorted _ (unroll_between_ptr h) l ->\n    pair_in a b (List.tl (chop_succs l)) ->\n    (forall p q, In p l -> In q l -> id_of p = id_of q ->  p = q) ->\n    forall p,\n      In p l ->\n      unroll_between_ptr h a p = true ->\n      unroll_between_ptr h p b = true ->\n      p = a \\/ p = b.\nProof.\n  eauto using sorted_by_between_list_elements_between_pair_eq, pair_in_firstn, pair_in_tl.\nQed.\n\nLemma firstn_in :\n  forall A n (l : list A) x,\n    In x (firstn n l) ->\n    In x l.\nProof.\n  induction n; intros; simpl in *; intuition.\n  break_match; simpl in *; intuition.\nQed.\n\nLemma NoDup_chop_succs :\n  forall l,\n    NoDup l ->\n    NoDup (chop_succs l).\nProof.\n  unfold chop_succs.\n  induction SUCC_LIST_LEN; intros; simpl in *; eauto.\n  break_match; eauto. inv_prop NoDup.\n  constructor; auto.\n  intro. eauto using firstn_in.\nQed.\n\nLemma unroll_between_zero :\n  forall h x,\n    unroll_between_ptr h (make_pointer h) x = true.\nProof.\n  intros. unfold unroll_between_ptr, unroll_between.\n  break_if; intuition.\nQed.\n\nDefinition hash_injective_on_pair a b :=\n  id_of a = id_of b -> a = b.\n\nLemma unroll_between_zero' :\n  forall h x,\n    wf_ptr h ->\n    wf_ptr x ->\n    hash_injective_on_pair h x ->\n    unroll_between_ptr (addr_of h) x h = true ->\n    x = h.\nProof.\n  intros. unfold unroll_between_ptr, unroll_between in *.\n  repeat (break_if; intuition); try discriminate;\n    unfold wf_ptr, hash_injective_on_pair, id_of, addr_of in *;\n    try solve [repeat find_rewrite; intuition|find_false; auto].\nQed.\n\nDefinition wf h x := wf_ptr x /\\ hash_injective_on_pair (make_pointer h) x.\n\nLemma in_chop_succs :\n  forall x l,\n    In x (chop_succs l) ->\n    In x l.\nProof.\n  eauto using in_firstn.\nQed.\n\nLemma unroll_between_contra :\n  forall h a b c,\n    hash_injective_on_pair a b ->\n    a <> b ->\n    unroll_between_ptr h a b = true ->\n    unroll_between_ptr h b c = true ->\n    ~ ptr_between a c b.\nProof.\n  intros. unfold unroll_between_ptr, unroll_between, ptr_between in *.\n  repeat break_if; auto; repeat find_rewrite; eauto using not_between_xxy, not_between_xyy, between_bool_between, between_swap_not, between_not_between.\nQed.\n\nLemma unroll_between_contra' :\n  forall h a b c,\n    hash_injective_on_pair a b ->\n    a <> b ->\n    unroll_between_ptr h a b = true ->\n    unroll_between_ptr h c a = true ->\n    ~ ptr_between a c b.\nProof.\n  intros. unfold unroll_between_ptr, unroll_between, ptr_between in *.\n  repeat break_if; auto; repeat find_rewrite; eauto using not_between_xxy, not_between_xyy, between_bool_between, between_swap_not, between_not_between, between_rot_l.\n  repeat find_apply_lem_hyp between_bool_between.\n  intro. find_apply_lem_hyp between_rot_l; eauto.\n  eapply between_not_between;\n    [| |eauto]; eauto.\nQed.\n\nLemma sort_by_between_in :\n  forall h l p,\n    In p l ->\n    In p (sort_by_between h l).\nProof.\n  intros. unfold sort_by_between.\n  eauto using sort_permutes, Permutation.Permutation_in.\nQed.\n\nLemma sorted_h_in :\n  forall h l,\n    (forall a b, In a l -> In b l -> hash a = hash b -> a = b) ->\n    In h l ->\n    exists xs,\n      sort_by_between h (map make_pointer l) = make_pointer h :: xs /\\\n      sorted _ (unroll_between_ptr h) (make_pointer h :: xs).\nProof.\n  intros.\n  assert (sorted _ (unroll_between_ptr h) (sort_by_between h (map make_pointer l)))\n    by eauto using sort_by_between_sorted.\n  match goal with\n  | H : sorted _ _ _ |- _ =>\n    eapply sorted_zero_prefix with (wf := (wf h)) in H\n  end;\n    eauto using pointer_eq_dec, unroll_between_zero, unroll_between_ptr_trans.\n  - break_exists_name xs. break_exists_name ys.\n    destruct xs.\n    + intuition. exfalso.\n      assert (In (make_pointer h) (sort_by_between h (map make_pointer l))).\n      {\n        apply sort_by_between_in. in_crush.\n      }\n      repeat find_rewrite. simpl in *. eauto.\n    + intuition. simpl in *.\n      assert (p = make_pointer h) by auto.\n      subst.\n      simpl in *. exists (xs ++ ys). intuition.\n      repeat find_reverse_rewrite.\n      eauto using sort_by_between_sorted.\n  - intros.\n    unfold wf in *. intuition.\n    apply unroll_between_zero'; eauto using make_pointer_wf.\n  - intros.\n    find_apply_lem_hyp in_sort_by_between. in_crush.\n    unfold wf. intuition; eauto using make_pointer_wf.\n    unfold hash_injective_on_pair. simpl. intros. f_equal. eauto.\nQed.\n\nLemma NoDup_prepend_h_chop_succs_tl :\n  forall h l,\n    (forall a b, In a l -> In b l -> hash a = hash b -> a = b) ->\n    In h l ->\n    NoDup l ->\n    NoDup (make_pointer h :: (chop_succs (List.tl (sort_by_between h (map make_pointer l))))).\nProof.\n  intros.\n  assert (NoDup (map make_pointer l)).\n  { apply NoDup_map_injective; auto.\n    intros. unfold make_pointer in *. find_inversion. auto.\n  }\n  assert (NoDup (sort_by_between h (map make_pointer l))).\n  {\n    eapply NoDup_Permutation_NoDup; eauto.\n    unfold sort_by_between. eapply sort_permutes; eauto.\n  }\n  find_copy_apply_lem_hyp sorted_h_in; eauto. break_exists. intuition.\n  repeat find_rewrite. inv_prop NoDup.\n  simpl.\n  constructor; eauto using NoDup_chop_succs.\n  eauto using in_chop_succs.\nQed.    \n\n\nLemma pair_in_cons :\n  forall A (a : A) b c l,\n    pair_in a b (c :: l) ->\n    a = c \\/ pair_in a b l.\nProof.\n  intros. inv_prop @pair_in; intuition.\nQed.\n\nLemma sorted_pair_in_in' :\n  forall A (le : A -> A -> bool) (l1 l2 : list A) a b c,\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    pair_in a b l1 ->\n    sorted A le (l1 ++ l2) ->\n    In c l2 ->\n    le c a = true \\/ le b c = true \\/ c = a \\/ c = b.\nProof.\n  intros.\n  find_apply_lem_hyp pair_in_left.\n  right. left. eapply sorted_trans_app; eauto.\nQed.\n\nLemma sorted_pair_in_in'' :\n  forall A (le : A -> A -> bool) (l : list A) a b c,\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    pair_in a b l ->\n    sorted A le l ->\n    In c l ->\n    le c a = true \\/ le b c = true \\/ c = a \\/ c = b.\nProof.\n  induction 2.\n  - intros. in_crush.\n    inv_prop sorted. inv_prop sorted; in_crush.\n    right. left.\n    eapply sorted_trans; eauto. in_crush.\n  - intros. in_crush.\n    + find_apply_lem_hyp pair_in_right.\n      eauto using sorted_trans.\n    + inv_prop sorted; in_crush.\nQed.\n\nLemma sorted_app_l :\n  forall A le l1 l2,\n    sorted A le (l1 ++ l2) ->\n    sorted A le l1.\nProof.\n  intros. induction l1; simpl in *; auto.\n  - constructor.\n  - inv_prop sorted.\n    + match goal with\n      | H : [] = _ |- _ => symmetry in H\n      end.\n      find_apply_lem_hyp app_eq_nil.\n      intuition. subst. constructor.\n    + repeat find_rewrite.\n      destruct l1; simpl in *; auto.\n      * constructor.\n      * find_inversion. intuition. constructor; auto.\nQed.\n\nLemma sorted_pair_in_in :\n  forall A (le : A -> A -> bool) (l1 l2 : list A) a b c,\n    (forall x y z, le x y = true -> le y z = true -> le x z = true) ->\n    pair_in a b l1 ->\n    sorted A le (l1 ++ l2) ->\n    In c (l1 ++ l2) ->\n    le c a = true \\/ le b c = true \\/ c = a \\/ c = b.\nProof.\n  in_crush.\n  - eapply sorted_pair_in_in''; eauto using sorted_app_l.\n  - eapply sorted_pair_in_in'; eauto.\nQed.\n      \nLemma initial_succ_lists_all_principal :\n  forall p l,\n    (forall a b, In a l -> In b l -> hash a = hash b -> a = b) ->\n    NoDup l ->\n    In p l ->\n    forall h a b,\n      In h l ->\n      pair_in a b (hash h :: map id_of (chop_succs (List.tl (sort_by_between h (map make_pointer l))))) ->\n      ~ between a (hash p) b.\nProof.\n  intros.\n  change (hash h) with (id_of (make_pointer h)) in *.\n  rewrite <- map_cons in *.\n  find_eapply_lem_hyp pair_in_map; expand_def.\n  change (between (id_of x) (hash p) (id_of x0)) with (ptr_between x (make_pointer p) x0).\n  assert (sorted _ (unroll_between_ptr h) (sort_by_between h (map make_pointer l))) by\n      eauto using sort_by_between_sorted.\n  assert (sorted _ (unroll_between_ptr h) (tl (sort_by_between h (map make_pointer l)))) by\n      eauto using sorted_tl.\n  assert (sorted _ (unroll_between_ptr h) (chop_succs (tl (sort_by_between h (map make_pointer l))))) by\n      eauto using sorted_chop_succs.\n  assert (sorted _ (unroll_between_ptr h) (make_pointer h :: (chop_succs (tl (sort_by_between h (map make_pointer l)))))).\n  {\n    eapply sorted_prepend_zero; eauto. intros.\n    unfold unroll_between_ptr, unroll_between. break_if; auto.\n  }\n  find_copy_eapply_lem_hyp pair_in_sorted; eauto.\n  assert (x <> x0).\n  {\n    eapply NoDup_pair; [|eauto].\n    apply NoDup_prepend_h_chop_succs_tl; eauto.\n  }\n  assert (hash_injective_on_pair x x0).\n  {\n    unfold hash_injective_on_pair.\n    intros.\n    find_copy_apply_lem_hyp pair_in_left.\n    find_apply_lem_hyp pair_in_right.\n    in_crush;\n      repeat find_apply_lem_hyp in_chop_succs;\n      repeat find_apply_lem_hyp in_tl;\n      repeat find_apply_lem_hyp in_sort_by_between;\n      in_crush;\n      f_equal; eauto.\n  }\n  assert (In (make_pointer p) (map make_pointer l)) by in_crush.\n  assert (In (make_pointer p) (sort_by_between h (map make_pointer l)))\n    by eauto using sort_by_between_in.\n  find_copy_apply_lem_hyp sorted_h_in; eauto. break_exists. break_and.\n  repeat find_rewrite.\n  pose proof chop_succs_partition x1. break_exists.\n  cbv [tl] in *.\n  match goal with\n  | Hsubst : x1 = _,\n    Hsorted : sorted _ _ (_ :: x1),\n    HIn : In _ (_ :: x1) |- _ =>\n    rewrite Hsubst in Hsorted,HIn;\n      rewrite app_comm_cons in Hsorted,HIn\n  end.\n  remember (make_pointer h :: chop_succs x1) as l1.\n  find_eapply_lem_hyp sorted_pair_in_in; eauto using unroll_between_ptr_trans.\n  intuition; simpl in *; eauto using unroll_between_contra.\n  - eapply unroll_between_contra'; eauto.\n  - eapply unroll_between_contra; eauto.\n  - subst. unfold ptr_between in *. simpl in *.\n    eapply not_between_xxy; eauto.\n  - subst. unfold ptr_between in *. simpl in *.\n    eapply not_between_xyy; eauto.\nQed.\nHint Resolve initial_succ_lists_all_principal.\n\nLemma initial_nodes_principal :\n  forall gst h,\n    initial_st gst ->\n    In h (nodes gst) ->\n    principal gst h.\nProof.\n  intros.\n  unfold principal; split.\n  - auto.\n  - unfold not_skipped; autounfold; intros.\n    split; intros.\n    + find_apply_lem_hyp initial_succ_list; eauto.\n      unfold initial_st in *; autounfold in *. intuition.\n      repeat find_rewrite; repeat find_injection.\n      unfold not_skipped; intros.\n      simpl in *; eapply initial_succ_lists_all_principal with (p := h) (h := h0); eauto.\n    + unfold initial_st in *; autounfold in *; intuition.\n      repeat find_rewrite || find_injection.\n      tauto.\nQed.\nHint Resolve initial_nodes_principal.\n\nLemma principals_intro :\n  forall gst ps,\n    NoDup ps ->\n    (forall p, In p ps -> principal gst p) ->\n    (forall p, principal gst p -> In p ps) ->\n    principals gst ps.\nProof.\n  unfold principals.\n  intros.\n  intuition (apply Forall_forall; auto).\nQed.\n\nLemma sufficient_principals_intro :\n  forall gst ps,\n    NoDup ps ->\n    (forall p, In p ps -> principal gst p) ->\n    (forall p, principal gst p -> In p ps) ->\n    length ps > SUCC_LIST_LEN ->\n    sufficient_principals gst.\nProof.\n  unfold sufficient_principals.\n  intros; exists ps.\n  eauto using principals_intro.\nQed.\n\nLemma principals_involves_joined_node_state_and_msgs_only :\n  forall gst gst' p,\n    principal gst p ->\n    (forall h st,\n        live_node gst h /\\ sigma gst h = Some st <->\n        live_node gst' h /\\ sigma gst' h = Some st) ->\n    (forall src h m s,\n        succs_msg m s ->\n        ~ In h (failed_nodes gst') ->\n        In h (nodes gst') ->\n        In (src, (h, m)) (msgs gst') ->\n        ~ In h (failed_nodes gst) /\\\n        In h (nodes gst) /\\\n        In (src, (h, m)) (msgs gst)) ->\n    principal gst' p.\nProof.\n  unfold principal.\n  intros.\n  expand_def.\n  split.\n  - firstorder.\n  - intros.\n    assert ((forall h, live_node gst h -> live_node gst' h) /\\\n            (forall h, live_node gst' h -> live_node gst h)).\n    {\n      split; intros;\n        inv_prop live_node;\n        expand_def;\n        eapply H0;\n        split; eauto.\n    }\n    break_and.\n    split; autounfold; intros; eauto.\n    + find_eapply_prop no_live_node_skips; eauto.\n      find_eapply_prop iff; eauto.\n    + find_eapply_prop no_msg_to_live_node_skips;\n        try find_eapply_prop In; eauto.\nQed.\n\nLemma principals_involves_joined_node_state_only :\n  forall gst gst' p,\n    principal gst p ->\n    (forall h st,\n        live_node gst h /\\ sigma gst h = Some st <->\n        live_node gst' h /\\ sigma gst' h = Some st) ->\n    live_node gst' p /\\ no_live_node_skips gst' p.\nProof.\n  unfold principal.\n  intros.\n  expand_def.\n  split.\n  - firstorder.\n  - intros.\n    assert ((forall h, live_node gst h -> live_node gst' h) /\\\n            (forall h, live_node gst' h -> live_node gst h)).\n    {\n      split; intros;\n        inv_prop live_node;\n        expand_def;\n        eapply H0;\n        split; eauto.\n    }\n    break_and.\n    autounfold; intros; eauto.\n    find_eapply_prop no_live_node_skips; eauto.\n    find_eapply_prop iff; eauto.\nQed.\n\nTheorem zave_invariant_init :\n  chord_init_invariant zave_invariant.\nProof.\n  autounfold; intros.\n  inv_prop initial_st.\n  repeat split.\n  - break_and.\n    unfold sufficient_principals.\n    exists (nodes gst); split; try omega.\n    unfold principals; repeat split.\n    + auto.\n    + apply Forall_forall; eauto.\n    + intros; inv_prop principal; auto.\n  - unfold live_node_in_succ_lists.\n    intros.\n    find_copy_apply_lem_hyp initial_succ_list; auto.\n    find_copy_eapply_lem_hyp (initial_successor_lists_full h).\n    pose proof succ_list_len_lower_bound.\n    destruct (succ_list st) as [|p l] eqn:?.\n    + assert (length (@nil pointer) >= 2) by congruence.\n      simpl in *; omega.\n    + exists (addr_of p).\n      unfold best_succ; exists st; exists nil; exists (map addr_of l).\n      split; eauto.\n      split; eauto.\n      split; try split.\n      * simpl.\n         change (addr_of p :: map addr_of l) with (map addr_of (p :: l)).\n         congruence.\n      * intros; simpl in *; tauto.\n      * eapply initial_nodes_live; eauto.\n         assert (In p (chop_succs (List.tl (sort_by_between h (map make_pointer (nodes gst)))))).\n         {\n           repeat find_reverse_rewrite.\n           replace (succ_list st) with (p :: l).\n           eauto with datatypes.\n         }\n         find_apply_lem_hyp in_firstn.\n         find_apply_lem_hyp in_tl.\n         find_apply_lem_hyp in_sort_by_between.\n         find_apply_lem_hyp in_map_iff; expand_def.\n         easy.\n  - autounfold; break_and; find_rewrite; in_crush.\n  - autounfold; break_and; find_rewrite; in_crush.\nQed.\nHint Resolve zave_invariant_init.\n\nLemma live_after_start_was_live :\n  forall h gst gst' k st ms nts,\n    ~ In h (nodes gst) ->\n    In k (nodes gst) ->\n    ~ In k (failed_nodes gst) ->\n    start_handler h [k] = (st, ms, nts) ->\n    nodes gst' = h :: nodes gst ->\n    failed_nodes gst' = failed_nodes gst ->\n    timeouts gst' = update addr_eq_dec (timeouts gst) h nts ->\n    sigma gst' = update addr_eq_dec (sigma gst) h (Some st) ->\n    msgs gst' = map (send h) ms ++ msgs gst ->\n    trace gst' = trace gst ++ map e_send (map (send h) ms) ->\n    forall l,\n      live_node gst' l ->\n      live_node gst l.\nProof.\n  intros.\n  inv_prop live_node; expand_def.\n  assert (l <> h) by eauto using live_node_not_just_started.\n  eapply live_node_characterization; eauto; repeat find_rewrite;\n    solve [now rewrite_update | in_crush].\nQed.\n\nTheorem zave_invariant_start :\n  chord_start_invariant zave_invariant.\nProof.\n  unfold chord_start_invariant, zave_invariant.\n  repeat (apply chord_start_pre_post_conj; eauto).\n  do 2 autounfold_one; intros; break_and.\n  unfold sufficient_principals in *; break_and.\n  break_exists_exists.\n  break_and; split; eauto.\n  inv_prop principals; break_and.\n  apply principals_intro; auto; intros.\n  - inv_prop principals; expand_def; autounfold in *.\n    unfold principal; rewrite <- and_assoc; split.\n    eapply principals_involves_joined_node_state_only;\n      [eapply Forall_forall; eassumption |]; intros.\n    + intuition; inv_prop live_node; expand_def.\n      * eapply live_node_characterization; eauto;\n          repeat find_rewrite;\n          try rewrite_update;\n          in_crush || eauto.\n      * repeat find_rewrite; rewrite_update; auto.\n      * repeat find_rewrite; update_destruct;\n          subst; rewrite_update;\n            repeat find_injection.\n        cut (joined x0 = false); [congruence|].\n        eapply joining_start_handler_st_joined; eauto.\n        eapply live_node_characterization; eauto; in_crush.\n      * repeat find_rewrite; update_destruct;\n          subst; rewrite_update;\n            repeat find_injection.\n        cut (joined x0 = false); [congruence|].\n        eapply joining_start_handler_st_joined; eauto.\n        rewrite_update; auto.\n    + autounfold; intros.\n      unfold start_handler in *; simpl in *.\n      repeat find_rewrite || find_injection.\n      simpl in *; break_or_hyp.\n      * unfold send in *; find_injection; inv_prop succs_msg.\n      * assert (principal gst p) by (eapply Forall_forall; eauto).\n        assert (~ client_payload m) by (inv_prop succs_msg; intro; inv_prop client_payload).\n        find_copy_eapply_lem_hyp LiveNodesNotClients.sent_non_client_message_means_in_nodes; eauto.\n        inv_prop principal; expand_def.\n        exfalso; find_eapply_prop client_addr.\n        assert (~ client_addr src)\n          by eauto using LiveNodesNotClients.live_nodes_not_clients.\n        eapply non_client_msgs_out_of_net_go_to_clients; eauto.\n        find_eapply_prop no_msg_to_live_node_skips; eauto.\n  - find_eapply_prop In.\n    inv_prop principal.\n    split; eauto using live_after_start_was_live.\n    split; autounfold in *; intros.\n    + inv_prop principal;  expand_def.\n      find_eapply_prop no_live_node_skips; eauto.\n      eapply live_before_start_stays_live; eauto.\n      repeat find_rewrite;\n        update_destruct; rewrite_update; eauto.\n      subst; exfalso; eauto.\n    + inv_prop principal; expand_def.\n      assert (live_node gst p) by eauto using live_after_start_was_live.\n      find_eapply_prop no_msg_to_live_node_skips;\n        repeat find_rewrite; try solve [try apply in_cons; eauto].\n      in_crush; eauto.\nQed.\nHint Resolve zave_invariant_start.\n\nLemma principal_preserved :\n  forall gst gst',\n    nodes gst = nodes gst' ->\n    (forall f,\n        In f (failed_nodes gst) ->\n        In f (failed_nodes gst')) ->\n    sigma gst = sigma gst' ->\n    msgs gst = msgs gst' ->\n    forall h,\n      principal gst h ->\n      ~ In h (failed_nodes gst') ->\n      principal gst' h.\nProof.\n  intros.\n  unfold principal in *.\n  repeat break_and_goal; autounfold in *; intros.\n  - break_and.\n    inv_prop live_node; expand_def.\n    repeat find_rewrite.\n    eapply live_node_characterization; eauto.\n  - intros; subst.\n    inv_prop live_node; expand_def.\n    repeat find_rewrite || find_injection.\n    find_eapply_prop succ_list; repeat find_rewrite; eauto.\n    eapply live_node_characterization; repeat find_rewrite; eauto.\n  - intros; subst.\n    inv_prop live_node; expand_def.\n    repeat find_rewrite || find_injection.\n    find_eapply_prop not_skipped; repeat find_rewrite; eauto;\n    eapply live_node_characterization; repeat find_rewrite; eauto.\nQed.\n\nLemma principal_not_failed :\n  forall gst h,\n    principal gst h ->\n    In h (failed_nodes gst) ->\n    False.\nProof.\n  unfold principal.\n  intros until 1.\n  fold (~ In h (failed_nodes gst)).\n  break_and.\n  eauto.\nQed.\nHint Resolve principal_not_failed.\n\nLemma succ_lists_same_principal_preserved :\n  forall gst gst' h p st st',\n    principal gst p ->\n    sigma gst h = Some st ->\n    sigma gst' = update addr_eq_dec (sigma gst) h (Some st') ->\n    succ_list st = succ_list st' ->\n    joined st = joined st' ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    msgs gst' = msgs gst ->\n    principal gst' p.\nProof.\n  unfold principal.\n  intuition eauto;\n    autounfold; intros.\n  - assert (live_node gst p) by eauto.\n    break_live_node.\n    destruct (addr_eq_dec p h);\n      eapply live_node_characterization; repeat find_rewrite; rewrite_update; eauto.\n    congruence.\n  - subst.\n    repeat find_rewrite; update_destruct; rewrite_update.\n    + find_injection.\n      find_reverse_rewrite.\n      find_eapply_prop no_live_node_skips; eauto.\n      break_live_node;\n        rewrite_update;\n        eapply live_node_characterization; repeat find_rewrite; eauto.\n      rewrite_update. congruence.\n    + assert (live_node gst h0).\n      {\n        break_live_node; eapply live_node_characterization; repeat find_rewrite; eauto.\n        rewrite_update; congruence.\n      }\n      eauto.\n  - find_eapply_prop no_msg_to_live_node_skips;\n      repeat find_rewrite; eauto.\nQed.\nHint Resolve succ_lists_same_principal_preserved.\n\nLemma msgs_succs_principal_preserved :\n  forall gst gst' h p st st',\n    principal gst p ->\n    sigma gst h = Some st ->\n    sigma gst' = update addr_eq_dec (sigma gst) h (Some st') ->\n    succ_list st = succ_list st' ->\n    joined st = joined st' ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    (forall src h m succs,\n        In h (nodes gst') ->\n        ~ In h (failed_nodes gst') ->\n        succs_msg m succs ->\n        In (src, (h, m)) (msgs gst') ->\n        In h (nodes gst) /\\\n        ~ In h (failed_nodes gst) /\\\n        In (src, (h, m)) (msgs gst)) ->\n    principal gst' p.\nProof.\n  unfold principal.\n  intuition eauto;\n    autounfold; intros.\n  - assert (live_node gst p) by eauto.\n    break_live_node.\n    destruct (addr_eq_dec p h);\n      eapply live_node_characterization; repeat find_rewrite; rewrite_update; eauto.\n    congruence.\n  - subst.\n    repeat find_rewrite; update_destruct; rewrite_update.\n    + find_injection.\n      find_reverse_rewrite.\n      find_eapply_prop no_live_node_skips; eauto.\n      break_live_node;\n        rewrite_update;\n        eapply live_node_characterization; repeat find_rewrite; eauto.\n      rewrite_update; congruence.\n      rewrite_update; congruence.\n    + assert (live_node gst h0).\n      {\n        break_live_node; eapply live_node_characterization; repeat find_rewrite; eauto.\n        rewrite_update; congruence.\n      }\n      eauto.\n  - find_copy_apply_lem_hyp live_node_means_state_exists; expand_def.\n    find_eapply_prop no_msg_to_live_node_skips;\n      repeat find_reverse_rewrite;\n      eauto;\n      unfold not; find_eapply_prop In; now eauto.\nQed.\nHint Resolve msgs_succs_principal_preserved.\n\nLemma succ_lists_same_sufficient_principals_preserved :\n  forall gst gst' h st st',\n    sufficient_principals gst ->\n    sigma gst h = Some st ->\n    sigma gst' = update addr_eq_dec (sigma gst) h (Some st') ->\n    succ_list st = succ_list st' ->\n    joined st = joined st' ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    msgs gst = msgs gst' ->\n    sufficient_principals gst'.\nProof.\n  intros.\n  eapply some_principals_ok.\n  unfold have_principals, sufficient_principals, principals in *.\n  break_exists_exists;\n    break_and; repeat split; eauto;\n      rewrite -> Forall_forall in *;\n        solve [eauto using succ_lists_same_principal_preserved\n              |intros; omega].\nQed.\nHint Resolve succ_lists_same_sufficient_principals_preserved.\n\nLemma msgs_state_principals_preserved :\n  forall gst gst' h st st',\n    sufficient_principals gst ->\n    sigma gst h = Some st ->\n    sigma gst' = update addr_eq_dec (sigma gst) h (Some st') ->\n    succ_list st = succ_list st' ->\n    joined st = joined st' ->\n    nodes gst = nodes gst' ->\n    failed_nodes gst = failed_nodes gst' ->\n    (forall src h m succs,\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        succs_msg m succs ->\n        In (src, (h, m)) (msgs gst') ->\n        In h (nodes gst) /\\\n        ~ In h (failed_nodes gst) /\\\n        In (src, (h, m)) (msgs gst)) ->\n    sufficient_principals gst'.\nProof.\n  intros.\n  eapply some_principals_ok.\n  unfold have_principals, sufficient_principals, principals in *.\n  break_exists_exists.\n  break_and.\n  repeat split; eauto.\n  - rewrite -> Forall_forall in *;\n      try solve [eauto using msgs_succs_principal_preserved\n                |intros; omega].\n    intros; eapply msgs_succs_principal_preserved; eauto.\n    intros; eauto.\n    eapply H6; eauto; congruence.\n  - omega.\nQed.\nHint Resolve msgs_state_principals_preserved.\n\nTheorem zave_invariant_fail :\n  chord_fail_invariant zave_invariant.\nProof.\n  autounfold.\n  intros.\n  repeat (apply chord_fail_pre_post_conj; eauto).\n  autounfold; intros; break_and.\n  inv_prop failure_constraint.\n  unfold principal_failure_constraint in *.\n  unfold sufficient_principals in *.\n  break_and.\n  eauto.\n  eapply some_principals_ok.\n  destruct (principal_dec gst h).\n  - concludes.\n    break_exists_name ps; break_and.\n    exists (remove addr_eq_dec h ps); repeat split.\n    + inv_prop principals; auto using remove_NoDup.\n    + inv_prop principals.\n      pose proof (principal_preserved gst gst').\n      econcludes.\n      forwards.\n      intros. repeat find_rewrite. in_crush.\n      concludes.\n      econcludes.\n      break_and.\n      rewrite -> ?Forall_forall in *; intros.\n      repeat find_rewrite.\n      eauto.\n      find_eapply_prop principal; eauto using in_remove.\n      simpl.\n      destruct (addr_eq_dec h x);\n        intro; break_or_hyp; try solve [eapply remove_In; eauto].\n      assert (principal gst x) by eauto using in_remove.\n      inv_prop principal; inv_prop live_node; tauto.\n    + inv_prop principals; break_and.\n      assert (length ps = SUCC_LIST_LEN + 1 -> False) by eauto.\n      cut (length (remove addr_eq_dec h ps) > SUCC_LIST_LEN); [omega|].\n      eapply gt_S_n.\n      rewrite remove_length_in; eauto.\n      omega.\n  - unfold principals in * |- ; break_exists_exists; expand_def.\n    rewrite -> ?Forall_forall in *.\n    assert (~ In h x) by eauto.\n    split; auto.\n    unfold principals in *; break_and.\n    intuition eauto; try omega.\n    eapply principal_preserved; try symmetry; try eassumption; eauto.\n    repeat find_rewrite.\n    intros.\n    in_crush.\n    find_rewrite.\n    in_crush.\n    assert (principal gst x0) by eauto.\n    inv_prop principal.\n    inv_prop live_node.\n    tauto.\nQed.\nHint Resolve zave_invariant_fail.\n\nLemma live_node_preserved_by_recv :\n  forall h,\n    chord_recv_handler_invariant (fun gst => live_node gst h).\nProof.\n  repeat autounfold; intros.\n  unfold live_node.\n  repeat find_rewrite; update_destruct; rewrite_update; auto; subst.\n  repeat split; eauto.\n  break_live_node.\n  eexists; split; eauto.\n  eapply joined_preserved_by_recv_handler; eauto; congruence.\nQed.\n\nTheorem live_node_was_live_or_no_succs :\n  forall gst gst' h,\n    reachable_st gst ->\n    step_dynamic gst gst' ->\n    live_node gst' h ->\n    live_node gst h \\/\n    ~ In h (nodes gst) \\/\n    exists st,\n      sigma gst h = Some st /\\\n      succ_list st = [] /\\\n      joined st = false.\nProof.\n  intros.\n  inv_prop step_dynamic; repeat find_rewrite; simpl in *; intuition eauto.\n  - break_live_node; simpl in *.\n    update_destruct; rewrite_update;\n      unfold live_node; repeat find_rewrite; intuition eauto.\n  - break_live_node; simpl in *.\n    unfold live_node.\n    repeat find_rewrite; intuition eauto.\n  - break_live_node; simpl in *.\n    update_destruct; rewrite_update;\n      unfold live_node; repeat find_rewrite; intuition eauto.\n    subst.\n    assert (joined st = joined st')\n      by repeat (handler_def; simpl; try congruence).\n    repeat find_injection.\n    repeat find_rewrite; intuition eauto.\n  - break_live_node; simpl in *.\n    update_destruct; rewrite_update;\n      unfold live_node; repeat find_rewrite; intuition eauto.\n    subst.\n    destruct (joined d) eqn:?; intuition eauto.\n    find_apply_lem_hyp nodes_not_joined_have_no_successors; eauto.\n    intuition eauto.\nQed.\n\nLemma not_skipped_nil :\n  forall h n,\n    not_skipped h [] n.\nProof.\n  unfold not_skipped; intros.\n  exfalso.\n  find_eapply_lem_hyp (f_equal (@length id)).\n  rewrite -> !app_length in *.\n  simpl in *; omega.\nQed.\nHint Resolve not_skipped_nil.\n\nLemma pair_in_complete :\n  forall A a b l,\n    @pair_in A a b l ->\n    exists xs ys,\n      l = xs ++ [a; b] ++ ys.\nProof.\n intros A a b l PI.\n induction PI.\n - exists [], l. reflexivity.\n - destruct IHPI as [xs [ys ?]].\n   subst l.\n   exists (x :: xs), ys.\n   reflexivity.\nQed.\n\nLemma not_skipped_firstn :\n  forall h l n k,\n    not_skipped h l n ->\n    not_skipped h (firstn k l) n.\nProof.\n  unfold not_skipped.\n  intros.\n  change (h :: firstn k l) with (firstn (S k) (h :: l)) in *.\n  copy_eapply pair_in_sound H0.\n  find_eapply_lem_hyp pair_in_firstn.\n  find_eapply_lem_hyp pair_in_complete.\n  expand_def; eauto.\nQed.\n\nLemma map_firstn :\n  forall A B (f : A -> B) k l,\n    map f (firstn k l) = firstn k (map f l).\nProof.\n  induction k; auto.\n  intros.\n  destruct l; simpl; congruence.\nQed.\n\nLemma weaken_no_live_node_skips :\n  forall gst p,\n    reachable_st gst ->\n    no_live_node_skips gst p ->\n    forall h st,\n      In h (nodes gst) ->\n      ~ In h (failed_nodes gst) ->\n      sigma gst h = Some st ->\n      not_skipped (ChordIDSpace.hash h) (map id_of (succ_list st)) (ChordIDSpace.hash p).\nProof.\n  autounfold; intros; subst.\n  destruct (joined st) eqn:?.\n  - find_eapply_prop not_skipped; eauto using live_node_characterization.\n  - find_apply_lem_hyp nodes_not_joined_have_no_successors; eauto.\n    repeat find_rewrite; eauto.\nQed.\n\nLemma principal_not_before_stabilize_tgt :\n  forall gst st h s p,\n    reachable_st gst ->\n    ~ In h (failed_nodes gst) ->\n    sigma gst h = Some st ->\n    cur_request st = Some (s, Stabilize, GetPredAndSuccs) ->\n    no_live_node_skips gst p ->\n    ~ between (hash h) (hash p) (id_of s).\nProof.\n  intros.\n  assert (cur_request_timeouts_ok' (cur_request st) (timeouts gst h)) by eauto.\n  repeat find_rewrite.\n  inv_prop cur_request_timeouts_ok'.\n  find_eapply_lem_hyp stabilize_only_with_first_succ; eauto.\n  expand_def.\n  repeat find_rewrite || find_injection.\n  assert (not_skipped (hash h) (map id_of (succ_list st)) (hash p))\n    by eauto using weaken_no_live_node_skips.\n  unfold not_skipped in *.\n  find_eapply_lem_hyp hd_error_tl_exists.\n  break_exists_name succs.\n  specialize (H6 (hash h) (id_of x) nil (map id_of succs)).\n  apply H6.\n  repeat find_rewrite.\n  reflexivity.\nQed.\n\nLemma principal_not_before_stabilize2_tgt :\n  forall gst,\n    reachable_st gst ->\n    forall st h s ns p req,\n      In h (nodes gst) ->\n      ~ In h (failed_nodes gst) ->\n      sigma gst h = Some st ->\n      cur_request st = Some (s, Stabilize2 ns, req) ->\n      not_skipped (hash h) (map id_of (succ_list st)) (hash p) ->\n      ~ between (hash h) (hash p) (id_of s).\nProof.\n  intros until 1.\n  pattern gst.\n  eapply chord_net_invariant; do 2 autounfold; intros.\n  - match goal with\n    | H: context[cur_request] |- _ =>\n      erewrite initial_st_cur_request_None in H; eauto; congruence\n    end.\n  - repeat find_rewrite.\n    destruct (addr_eq_dec h0 h); subst.\n    + match goal with\n      | H: context[start_handler] |- _ =>\n        rewrite start_handler_with_single_known in H\n      end.\n      rewrite_update.\n      repeat find_injection || simpl in *.\n      congruence.\n    + rewrite_update.\n      simpl in *; break_or_hyp; try tauto.\n      eauto.\n  - repeat find_rewrite.\n    eauto with datatypes.\n  - repeat find_rewrite.\n    update_destruct; rewrite_update.\n    + subst. repeat find_injection || find_rewrite.\n      repeat (handler_def || handler_simpl).\n    + eauto.\n  - repeat find_rewrite.\n    update_destruct; rewrite_update.\n    + subst. repeat find_injection || find_rewrite.\n      repeat (handler_def || handler_simpl).\n    + eauto.\n  - repeat find_rewrite.\n    update_destruct; rewrite_update.\n    + subst. repeat find_injection || find_rewrite.\n      repeat (handler_def || handler_simpl).\n    + eauto.\n  - repeat find_rewrite.\n    update_destruct; rewrite_update.\n    + subst. repeat find_injection || find_rewrite.\n      repeat (handler_def || handler_simpl).\n    + eauto.\n  - repeat find_rewrite.\n    update_destruct; rewrite_update.\n    + subst. repeat find_injection || find_rewrite.\n      repeat (handler_def || handler_simpl).\n      replace (ptr st) with (make_pointer h0) in *\n        by (symmetry; eapply ptr_correct; eauto).\n      unfold ptr_between in *; simpl in *.\n      assert (cur_request_timeouts_ok' (cur_request st) (timeouts gst0 h0))\n        by eauto.\n      repeat find_rewrite.\n      inv_prop cur_request_timeouts_ok'; inv_prop query_request.\n      find_eapply_lem_hyp stabilize_only_with_first_succ; eauto.\n      expand_def.\n      destruct (succ_list st) eqn:?;\n        simpl in *; try congruence.\n      find_injection.\n      assert (between (hash h0) (hash p0) (id_of x)).\n      {\n        eapply between_trans.\n        eauto.\n        rewrite <- (wf_ptr_hash_eq x)\n          by eauto using cur_request_valid.\n        repeat find_rewrite.\n        eauto.\n      }\n      find_eapply_prop not_skipped; eauto.\n      repeat find_reverse_rewrite.\n      simpl.\n      rewrite cons_make_succs.\n      simpl.\n      change ChordIDParams.hash with hash.\n      rewrite -> (wf_ptr_hash_eq x)\n        by eauto using cur_request_valid.\n      eauto using app_nil_l with datatypes.\n    + eauto.\n  - repeat (handler_def || handler_simpl).\n  - repeat find_rewrite; simpl in *; eauto.\n  - repeat find_rewrite; simpl in *; eauto.\nQed.\n\nLemma best_predecessor_between :\n  forall h x succs p,\n    best_predecessor h succs x = p ->\n    ptr_between h p x \\/ h = p.\nProof.\n  unfold best_predecessor, hd.\n  intros.\n  break_match; subst; eauto.\n  assert (In p (p :: l)) by in_crush.\n  find_reverse_rewrite.\n  find_eapply_lem_hyp filter_In.\n  intuition eauto.\nQed.\n\nLemma best_predecessor_self :\n  forall h x succs,\n    best_predecessor h succs x = h ->\n    id_of h = id_of x \\/\n    id_of (hd h succs) = id_of x \\/\n    ptr_between h x (hd h succs).\nProof.\n  unfold best_predecessor, hd, ptr_between.\n  intros.\n  destruct (id_eq_dec (id_of h) (id_of x)); eauto.\n  destruct succs as [|s rest];\n    [simpl in *; right; right;\n     eapply between_xyx;\n     unfold id_of in *; congruence|].\n  destruct (id_eq_dec (id_of s) (id_of x)); eauto.\n  do 2 right.\n  repeat break_match; try eauto using between_xyx.\n  - assert (~ In s []) by in_crush.\n    repeat find_reverse_rewrite; subst.\n    erewrite filter_In in *.\n    eapply not_between_swap;\n      [unfold id_of in *; congruence|].\n    intro; eapply_prop not.\n    split; in_crush.\n  - subst.\n    assert (In h (h :: l)) by in_crush.\n    repeat find_reverse_rewrite; subst.\n    erewrite filter_In in *; expand_def.\n    find_apply_lem_hyp ptr_between_bool_true.\n    exfalso; eapply not_between_xxy; eauto.\nQed.\n\nLemma handle_query_req_GotBestPredecessor_between :\n  forall st src dst ms p,\n    handle_query_req st src (GetBestPredecessor p) = ms ->\n    In (dst, GotBestPredecessor (ptr st)) ms ->\n    id_of (ptr st) = id_of p \\/\n    id_of (hd (ptr st) (succ_list st)) = id_of p \\/\n    ptr_between (ptr st) p (hd (ptr st) (succ_list st)).\nProof.\n  unfold handle_query_req.\n  intros; subst.\n  eapply best_predecessor_self.\n  in_crush; congruence.\nQed.\n\nLemma handle_delayed_query_GotBestPredecessor_accurate :\n  forall h st ms dst src p,\n    handle_delayed_query h st (src, GetBestPredecessor p) = ms ->\n    In (dst, GotBestPredecessor (ptr st)) ms ->\n    id_of (ptr st) = id_of p \\/\n    id_of (hd (ptr st) (succ_list st)) = id_of p \\/\n    ptr_between (ptr st) p (hd (ptr st) (succ_list st)).\nProof.\n  unfold handle_delayed_query.\n  intros.\n  eapply handle_query_req_GotBestPredecessor_between; eauto.\nQed.\n\nLemma handle_delayed_query_GotBestPredecessor_not_between :\n  forall h st ms dst src p,\n    handle_delayed_query h st (src, GetBestPredecessor p) = ms ->\n    In (dst, GotBestPredecessor (ptr st)) ms ->\n    ~ ptr_between (ptr st) (hd (ptr st) (succ_list st)) p \\/\n    id_of (ptr st) = id_of p /\\\n    id_of (hd (ptr st) (succ_list st)) <> id_of (ptr st).\nProof.\n  intros.\n  eapply handle_delayed_query_GotBestPredecessor_accurate in H; eauto.\n  unfold ptr_between, id_of in *.\n  repeat break_or_hyp.\n  - repeat find_rewrite.\n    destruct (succ_list st); simpl in *.\n    + repeat find_rewrite.\n      eauto using not_between_xxy.\n    + destruct (id_eq_dec (ptrId p0) (ptrId p)).\n      * repeat find_rewrite.\n        eauto using not_between_xxy.\n      * tauto.\n  - repeat find_rewrite.\n    eauto using not_between_xyy.\n  - left.\n    now apply between_swap_not.\nQed.\n\nTheorem zave_invariant_recv_sufficient_principals :\n  chord_recv_handler_pre_post\n    zave_invariant\n    sufficient_principals.\nProof.\n  autounfold_one; unfold zave_invariant; intros.\n  assert (forall h, live_node gst h -> live_node gst' h)\n    by (intros; eapply live_node_preserved_by_recv; eauto).\n  intros.\n  break_and.\n  destruct (list_eq_dec pointer_eq_dec (succ_list st) (succ_list st')).\n  - destruct (Bool.bool_dec (joined st) (joined st')).\n    + autounfold in *.\n      eapply some_principals_ok.\n      unfold have_principals, principals in *.\n      break_exists_exists.\n      rewrite -> Forall_forall in *.\n      intuition.\n      assert (principal gst x0) by auto.\n      unfold principal in *.\n      assert (no_live_node_skips gst' x0).\n      {\n        autounfold; intros.\n        inv_prop live_node; expand_def.\n        repeat find_rewrite.\n        update_destruct; rewrite_update;\n          repeat find_injection;\n          find_eapply_prop no_live_node_skips; congruence || eauto;\n           eapply live_node_characterization; eauto.\n      }\n      autounfold; intuition.\n      repeat find_rewrite.\n      find_apply_lem_hyp in_app_or; break_or_hyp.\n      * in_crush. unfold send in *; find_injection.\n        find_copy_eapply_lem_hyp recv_handler_succs_msg_accurate; eauto.\n        subst.\n        eapply weaken_no_live_node_skips; try solve [econstructor; eauto|eauto|congruence].\n        repeat find_rewrite.\n        now rewrite_update.\n      * find_eapply_prop no_msg_to_live_node_skips; eauto.\n        repeat find_rewrite; in_crush.\n    + destruct (joined st) eqn:?, (joined st') eqn:?;\n        try (find_apply_lem_hyp joined_preserved_by_recv_handler; auto; congruence).\n      find_apply_lem_hyp recv_handler_sets_succ_list_when_setting_joined; eauto.\n      expand_def.\n      find_apply_lem_hyp nodes_not_joined_have_no_successors; eauto.\n      congruence.\n  - assert (cur_request_timeouts_ok' (cur_request st) (timeouts gst h)) by auto.\n    eapply some_principals_ok.\n    unfold sufficient_principals, principals in *; break_exists_exists.\n    break_and; repeat split; omega || eauto.\n    rewrite -> Forall_forall in *; intros.\n    assert (principal gst x0) by eauto.\n    assert (no_live_node_skips gst' x0).\n    {\n      autounfold in *; unfold principal in *; intuition.\n      repeat find_rewrite; update_destruct; rewrite_update; subst.\n      - repeat (handler_def; simpl in *; try congruence);\n        repeat (find_rewrite || find_injection); simpl.\n      + repeat find_rewrite.\n        inv_prop cur_request_timeouts_ok'.\n        invcs_prop query_request.\n        find_eapply_lem_hyp stabilize_only_with_first_succ; eauto.\n        break_exists; break_and.\n        repeat find_rewrite || find_injection.\n        rewrite cons_make_succs.\n        simpl.\n        eapply not_skipped_initial'.\n        * rewrite map_firstn.\n          eapply not_skipped_firstn.\n          find_eapply_prop no_msg_to_live_node_skips; eauto.\n        * rewrite -> wf_ptr_hash_eq\n            by eauto using cur_request_valid.\n          eapply principal_not_before_stabilize_tgt; eauto.\n      + repeat find_rewrite.\n        inv_prop cur_request_timeouts_ok'.\n        invcs_prop query_request.\n        find_eapply_lem_hyp stabilize_only_with_first_succ; eauto.\n        break_exists; break_and.\n        repeat find_rewrite || find_injection.\n        rewrite cons_make_succs.\n        simpl.\n        eapply not_skipped_initial'.\n        * rewrite map_firstn.\n           eapply not_skipped_firstn.\n           find_eapply_prop no_msg_to_live_node_skips; eauto.\n        * rewrite -> wf_ptr_hash_eq\n            by eauto using cur_request_valid.\n          eapply principal_not_before_stabilize_tgt; eauto.\n      + repeat find_rewrite.\n        inv_prop cur_request_timeouts_ok'.\n        invcs_prop query_request.\n        find_eapply_lem_hyp stabilize_only_with_first_succ; eauto.\n        break_exists; break_and.\n        repeat find_rewrite || find_injection.\n        rewrite cons_make_succs.\n        simpl.\n        eapply not_skipped_initial'.\n        * rewrite map_firstn.\n           eapply not_skipped_firstn.\n           find_eapply_prop no_msg_to_live_node_skips; eauto.\n        * rewrite -> wf_ptr_hash_eq\n            by eauto using cur_request_valid.\n          eapply principal_not_before_stabilize_tgt; eauto.\n      + find_copy_eapply_lem_hyp stabilize2_param_matches; eauto.\n        rewrite cons_make_succs.\n        simpl; subst.\n        erewrite <- wf_ptr_hash_eq\n          by eauto using cur_request_valid.\n        eapply not_skipped_initial'.\n        * rewrite map_firstn.\n           eapply not_skipped_firstn.\n           find_eapply_prop no_msg_to_live_node_skips; eauto.\n        * rewrite -> wf_ptr_hash_eq\n            by eauto using cur_request_valid.\n          eapply principal_not_before_stabilize2_tgt; eauto.\n          eapply weaken_no_live_node_skips; eauto.\n      + match goal with\n        | H: context[GotSuccList ?l] |- _ =>\n          assert (succs_msg (GotSuccList l) l) by constructor\n        end.\n        copy_eapply_prop_hyp no_msg_to_live_node_skips succs_msg;\n          [| | |repeat find_rewrite; in_crush]; eauto.\n        eapply not_skipped_initial'.\n        * eapply not_skipped_initial; eauto.\n        * unfold ChordIDSpace.hash in *.\n          remember (hash (addr_of x9)) as joined in *.\n          remember (hash h0) as joining in *.\n          remember (id_of x10) as first_succ in *.\n          remember (hash x0) as principal in *.\n          assert (~ between joined principal first_succ).\n          {\n            find_eapply_prop not_skipped.\n            simpl.\n            rewrite <- app_nil_l at 1.\n            rewrite Heqfirst_succ; eauto.\n          }\n          eauto using between_trans'.\n      + exfalso; eapply join2_unreachable; eauto.\n      - find_eapply_prop no_live_node_skips; eauto.\n        eapply live_node_equivalence; eauto.\n        repeat find_rewrite; rewrite_update; auto.\n    }\n    unfold principal in *.\n    intuition eauto.\n    autounfold; intuition.\n    repeat find_rewrite.\n    find_apply_lem_hyp in_app_or; break_or_hyp.\n    + in_crush. unfold send in *; find_injection.\n      find_copy_eapply_lem_hyp recv_handler_succs_msg_accurate; eauto.\n      subst.\n      eapply weaken_no_live_node_skips; try solve [econstructor; eauto|eauto|congruence].\n      repeat find_rewrite.\n      now rewrite_update.\n    + find_eapply_prop no_msg_to_live_node_skips; eauto.\n      repeat find_rewrite; in_crush.\nQed.\nHint Resolve zave_invariant_recv_sufficient_principals.\n\nTheorem zave_invariant_recv :\n  chord_recv_handler_invariant zave_invariant.\nProof.\n  autounfold; eauto.\nQed.\nHint Resolve zave_invariant_recv.\n\nTheorem zave_invariant_tick :\n  chord_tick_invariant zave_invariant.\nProof.\n  unfold zave_invariant.\n  break_and; split; eauto; break_and;\n    eauto using reachableStep.\n  eapply msgs_state_principals_preserved; eauto.\n  - repeat handler_def; simpl; auto.\n  - eauto using joined_preserved_by_tick_handler.\n  - repeat find_rewrite.\n    intros.\n    intuition.\n    find_apply_lem_hyp in_app_or; break_or_hyp.\n    + exfalso.\n      repeat handler_def; simpl in *; unfold send in *.\n      intuition; find_injection.\n      find_apply_lem_hyp option_map_Some; expand_def.\n      inv_prop succs_msg.\n    + auto.\nQed.\nHint Resolve zave_invariant_tick.\n\nTheorem zave_invariant_keepalive :\n  chord_keepalive_invariant zave_invariant.\nProof.\n  unfold zave_invariant.\n  split; eauto.\n  break_and.\n  eapply msgs_state_principals_preserved; eauto.\n  - repeat handler_def; simpl; auto.\n  - repeat handler_def; reflexivity.\n  - repeat find_rewrite.\n    intros.\n    intuition.\n    find_apply_lem_hyp in_app_or; break_or_hyp; auto.\n    exfalso.\n    repeat handler_def; simpl in *;\n      unfold send, send_keepalives in *.\n    repeat (find_apply_lem_hyp in_map_iff; expand_def).\n    inv_prop succs_msg.\nQed.\nHint Resolve zave_invariant_keepalive.\n\nTheorem zave_invariant_rectify :\n  chord_rectify_invariant zave_invariant.\nProof.\n  unfold zave_invariant.\n  split; eauto.\n  break_and.\n  eapply msgs_state_principals_preserved; eauto;\n    try solve [repeat handler_def; simpl; auto].\n  intros; intuition eauto.\n  repeat find_rewrite.\n  find_apply_lem_hyp in_app_or; break_or_hyp; auto.\n  exfalso.\n  repeat handler_def; simpl in *; unfold send in *.\n  find_apply_lem_hyp option_map_Some; expand_def.\n  inv_prop succs_msg; congruence.\nQed.\nHint Resolve zave_invariant_rectify.\n\nLemma not_skipped_initial_not_between :\n  forall a b p rest,\n    not_skipped a (b :: rest) p ->\n    ~ between a p b.\nProof.\n  intros.\n  unfold not_skipped in *.\n  eauto.\n  specialize (H a b [] rest). simpl in *. auto.\nQed.\n\nLemma remove_list_element_still_not_skipped :\n  forall h s rest p,\n    s <> p ->\n    not_skipped h (s :: rest) p ->\n    not_skipped h rest p.\nProof.\n  (* This is for Doug *)\n  destruct rest; intros; simpl in *.\n  - unfold not_skipped. intros.\n    destruct xs; simpl in *; try congruence.\n    destruct xs; simpl in *; congruence.\n  - find_copy_apply_lem_hyp not_skipped_initial_not_between.\n    find_apply_lem_hyp not_skipped_initial.\n    find_copy_apply_lem_hyp not_skipped_initial_not_between.\n    find_eapply_lem_hyp not_skipped_initial.\n    eapply not_skipped_initial'; eauto.\n    destruct (id_eq_dec h s); [subst; exfalso; intuition; eauto using between_xyx|].\n    destruct (id_eq_dec s i); [subst; exfalso; intuition; eauto using between_xyx|].\n    find_apply_lem_hyp not_between_cases;\n      intuition; subst; eauto; try solve [find_apply_lem_hyp not_between_xyy; eauto].\n    find_apply_lem_hyp not_between_cases;\n      intuition; subst; eauto; try solve [find_apply_lem_hyp not_between_xxy; eauto].\n    repeat invcs_prop between;\n      try solve [match goal with\n      | H : lt ?a ?b, H' : lt ?b ?a |- _ =>\n        specialize (lt_asymm _ _ H H'); eauto\n                 end].\n    + repeat find_apply_lem_hyp lt_asymm_neg.\n      intuition; subst; auto;\n        try solve [eapply lt_asymm; eauto].\n      match goal with\n      | H1 : lt ?a ?b, H2 : lt ?b ?c, H3 : lt ?c ?a |- _ =>\n        specialize (lt_trans _ _ _ H1 H2) as Hcontra;\n          specialize (lt_asymm _ _ H3 Hcontra); eauto\n      end.\n    + repeat find_apply_lem_hyp lt_asymm_neg.\n      intuition; subst; auto;\n        try solve [eapply lt_asymm; eauto].\n      match goal with\n      | H1 : lt ?a ?b, H2 : lt ?b ?c, H3 : lt ?c ?a |- _ =>\n        specialize (lt_trans _ _ _ H1 H2) as Hcontra;\n          specialize (lt_asymm _ _ H3 Hcontra); eauto\n      end.\nQed.\nHint Resolve remove_list_element_still_not_skipped.\n\nTheorem zave_invariant_request :\n  chord_request_invariant zave_invariant.\nProof.\n  autounfold; intros.\n  break_and; split; eauto.\n  find_copy_eapply_lem_hyp cur_request_timeouts_related_invariant; auto.\n  assert (forall h, live_node gst h -> live_node gst' h).\n  {\n    intros.\n    unfold live_node in *; expand_def.\n    repeat find_rewrite.\n    update_destruct; rewrite_update; subst.\n    * intuition.\n      eexists.\n      split; [eauto|].\n      repeat find_rewrite || find_injection.\n      erewrite <- joined_preserved_by_request_timeout_handler; eauto.\n    * eauto.\n  }\n  assert (forall h, live_node gst' h -> live_node gst h).\n  {\n    intros.\n    unfold live_node in *; expand_def.\n    repeat find_rewrite.\n    update_destruct; rewrite_update; subst.\n    * intuition.\n      eexists.\n      split; [eauto|].\n      repeat find_rewrite || find_injection.\n      erewrite -> joined_preserved_by_request_timeout_handler; eauto.\n    * eauto.\n  }\n  assert (succ_list st = succ_list st' \\/\n          req = GetPredAndSuccs /\\\n          exists s1 rest,\n            succ_list st = s1 :: rest /\\\n            succ_list st' = rest).\n  {\n    repeat handler_def; simpl; intuition eauto;\n      repeat find_rewrite;\n      invcs_prop cur_request_timeouts_ok; try congruence;\n        inv_prop query_request;\n        try congruence;\n        assert (Request (addr_of dstp) GetPredAndSuccs = Request (addr_of x) req) by eauto;\n        find_injection;\n        right; intuition eauto.\n  }\n  break_or_hyp.\n  - unfold sufficient_principals in *.\n    eapply some_principals_ok.\n    break_exists_exists.\n    unfold principals in *; break_and.\n    repeat split; eauto; try omega.\n    rewrite -> Forall_forall in *.\n    intros.\n    match goal with\n    | |- principal gst' ?p =>\n      assert (principal gst p) by auto;\n        invcs_prop principal; expand_def\n    end.\n    assert (live_node gst' h ->\n            not_skipped (ChordIDSpace.hash h) (map id_of (succ_list st')) (ChordIDSpace.hash x0)).\n    {\n      intro.\n      assert (sigma gst' h = Some st').\n      repeat find_rewrite; rewrite_update; auto.\n      autounfold in *.\n      repeat find_rewrite.\n      update_destruct; rewrite_update.\n      repeat handler_def; simpl; eauto;\n        repeat match goal with\n             | |- not_skipped _ (map id_of ?rest) _ =>\n               eapply remove_list_element_still_not_skipped\n             | H: succ_list ?st = ?head :: ?rest\n               |- not_skipped _ (?h :: map id_of ?rest) _ =>\n               erewrite <- map_cons;\n                 erewrite <- H;\n                 eauto\n             end;\n      repeat match goal with\n             | H: timeout_constraint _ _ _ |- _ =>\n               invcs H\n             | H: cur_request_timeouts_ok _ _ |- _ =>\n               apply cur_request_timeouts_ok'_complete in H\n             | H: cur_request_timeouts_ok' (cur_request ?st) ?timeouts,\n               Heq: cur_request ?st = Some _ |- _ =>\n               rewrite Heq in H\n             | H: cur_request_timeouts_ok' (Some _) _ |- _ =>\n               invcs H\n             | H: query_request Stabilize ?x |- _ =>\n               invcs H\n             | H: In (Request _ GetPredAndSuccs) (timeouts gst _) |- _ =>\n               eapply stabilize_only_with_first_succ in H; eauto; expand_def\n             | H: hd_error (succ_list ?st) = Some _,\n               Heq: succ_list ?st = _ :: _\n               |- _ =>\n               rewrite Heq in H; simpl in H; injc H\n             end;\n      repeat match goal with\n             | H: live_node _ _ |- _ =>\n               invcs H; expand_def\n             | Hfailed: In (addr_of ?dead) (failed_nodes _),\n               Hlive: ~ In ?principal (failed_nodes _)\n              |- id_of ?ptr <> ChordIDSpace.hash ?principal =>\n               intro; assert (principal = addr_of dead); [|congruence]\n             | |- _ = addr_of _ =>\n               eapply hash_injective_invariant; eauto using in_failed_in_nodes\n             | |- context[ChordIDSpace.hash] =>\n               change ChordIDSpace.hash with hash in *\n             | |- hash ?h = hash (addr_of ?p) =>\n               assert (Hwf: wf_ptr p)\n                 by (eapply cur_request_valid; [| | eauto]; eauto);\n                 rewrite <- Hwf; congruence\n             end.\n      eauto.\n    }\n    assert (no_live_node_skips gst' x0).\n    {\n      autounfold; intros; subst.\n      repeat find_rewrite.\n      update_destruct; rewrite_update; subst;\n        repeat find_rewrite || find_injection;\n        eauto.\n    }\n    unfold principal; repeat break_and_goal; eauto.\n    autounfold; intros; subst.\n    find_rewrite. find_apply_lem_hyp in_app_or; break_or_hyp.\n    * find_copy_apply_lem_hyp in_map_iff; expand_def.\n      unfold send in *; find_injection.\n      find_eapply_lem_hyp responses_request_timeout_handler_accurate; eauto; subst.\n      assert (sigma gst' src = Some st')\n        by (repeat find_rewrite; rewrite_update; auto).\n      eapply weaken_no_live_node_skips;\n        try solve [econstructor 2; eauto\n                  |congruence\n                  |eauto].\n    * find_eapply_prop no_msg_to_live_node_skips;\n        repeat find_reverse_rewrite; eauto.\n  - break_and.\n    unfold sufficient_principals in *.\n    eapply some_principals_ok.\n    break_exists_exists.\n    unfold principals in *; break_and.\n    repeat split; eauto; try omega.\n    rewrite -> Forall_forall in *.\n    intros.\n    assert (principal gst x0) by eauto.\n    inv_prop principal.\n    break_exists_name s1; break_exists_name rest; break_and.\n    assert (live_node gst h).\n    {\n      eapply live_node_characterization; eauto.\n      destruct (joined st) eqn:?; auto.\n      find_apply_lem_hyp nodes_not_joined_have_no_successors; eauto.\n      congruence.\n    }\n    assert (no_live_node_skips gst' x0).\n    {\n      autounfold; intros.\n      assert (not_skipped (ChordIDSpace.hash h)\n                          (map id_of (s1 :: succ_list st'))\n                          (ChordIDSpace.hash x0))\n        by (find_eapply_prop no_live_node_skips; eauto || congruence).\n      repeat find_rewrite; update_destruct; rewrite_update; subst.\n      * find_injection; repeat find_rewrite.\n        eapply remove_list_element_still_not_skipped; eauto.\n        intro.\n        repeat invcs_prop principal.\n        repeat break_live_node.\n        repeat find_rewrite; rewrite_update; repeat find_injection.\n        inv_prop timeout_constraint.\n        assert (dst = addr_of s1).\n        {\n          eapply_lem_prop_hyp (stabilize_only_with_first_succ gst) Request; eauto.\n          break_exists; break_and.\n          repeat find_rewrite; simpl in *; congruence.\n        }\n        cut (dst = x0); [intro; subst; eauto|].\n        inv_prop cur_request_timeouts_ok; repeat find_rewrite.\n        -- exfalso; intuition eauto.\n        -- eapply_lem_prop_hyp (stabilize_only_with_first_succ gst) Request; eauto.\n           break_exists; break_and.\n           repeat find_rewrite.\n           simpl in *; repeat find_injection.\n           assert (wf_ptr x4)\n             by (eapply wf_ptr_succ_list_invariant' with (h:=h0); eauto;\n                 find_rewrite; in_crush).\n           eapply hash_injective_invariant; eauto using in_failed_in_nodes.\n           inv_prop wf_ptr.\n           repeat find_rewrite; auto.\n      * cut (not_skipped (ChordIDSpace.hash h0)\n                          (map id_of (succ_list st0))\n                          (ChordIDSpace.hash x0)); eauto.\n    }\n    split; eauto.\n    split; eauto.\n    autounfold; intros; subst.\n    find_rewrite. in_crush.\n    * unfold send in *; find_injection.\n      find_eapply_lem_hyp responses_request_timeout_handler_accurate; eauto; subst.\n      find_eapply_prop no_live_node_skips; eauto.\n      repeat find_rewrite; rewrite_update; auto.\n    * find_eapply_prop no_msg_to_live_node_skips;\n        repeat find_reverse_rewrite; eauto.\nQed.\nHint Resolve zave_invariant_request.\n\nTheorem zave_invariant_input :\n  chord_input_invariant zave_invariant.\nProof.\n  unfold zave_invariant.\n  split; eauto.\n  break_and.\n  autounfold in *.\n  break_exists_exists.\n  break_and; split; auto.\n  inv_prop principals; expand_def.\n  eapply principals_intro; eauto.\n  - rewrite -> Forall_forall in *.\n    intros.\n    assert (principal gst p) by eauto.\n    inv_prop principal; break_and.\n    find_copy_apply_lem_hyp live_node_means_state_exists; expand_def.\n    eapply principals_involves_joined_node_state_and_msgs_only;\n      intuition eauto.\n    + simpl in *; unfold send in *.\n      break_or_hyp; auto.\n      find_injection.\n      inv_prop succs_msg; inv_prop client_payload.\n  - intros; find_eapply_prop principal.\n    eapply principals_involves_joined_node_state_and_msgs_only;\n      intuition eauto.\n    in_crush.\nQed.\nHint Resolve zave_invariant_input.\n\nTheorem zave_invariant_output :\n  chord_output_invariant zave_invariant.\nProof.\n  unfold zave_invariant.\n  split; eauto.\n  break_and.\n  autounfold in *.\n  break_exists_exists.\n  break_and; split; auto.\n  inv_prop principals; expand_def.\n  eapply principals_intro; eauto.\n  - intros.\n    rewrite -> Forall_forall in *.\n    eapply principals_involves_joined_node_state_and_msgs_only;\n      intuition eauto.\n    simpl in *.\n    repeat find_rewrite.\n    in_crush.\n  - intros.\n    find_eapply_prop principal.\n    eapply principals_involves_joined_node_state_and_msgs_only;\n      intuition eauto.\n    repeat find_rewrite.\n    in_crush.\n    exfalso.\n    eapply LiveNodesNotClients.nodes_not_clients; eauto.\nQed.\nHint Resolve zave_invariant_output.\n\nTheorem zave_invariant_holds :\n  forall gst,\n    reachable_st gst ->\n    zave_invariant gst.\nProof.\n  apply chord_net_invariant; eauto.\nQed.\nHint Resolve zave_invariant_holds.\n\nLemma sufficient_principals_invariant :\n  forall gst,\n    reachable_st gst ->\n    sufficient_principals gst.\nProof.\n  intros.\n  assert (zave_invariant gst) by auto.\n  unfold zave_invariant in *.\n  tauto.\nQed.\nHint Resolve sufficient_principals_invariant.\n\nLemma live_node_in_succ_lists_invariant :\n  forall gst,\n    reachable_st gst ->\n    live_node_in_succ_lists gst.\nProof.\n  intros.\n  assert (zave_invariant gst) by auto.\n  unfold zave_invariant in *.\n  tauto.\nQed.\nHint Resolve live_node_in_succ_lists_invariant.\n\nLemma first_succ_and_second_distinct :\n  forall gst h st s1 s2 rest,\n    reachable_st gst ->\n    live_node gst h ->\n    sigma gst h = Some st ->\n    succ_list st = s1 :: s2 :: rest ->\n    addr_of s1 <> addr_of s2.\nProof.\n  intros.\n  assert (pair_in s1 s2 (s1 :: s2 :: rest)) by constructor.\n  find_copy_apply_lem_hyp sufficient_principals_invariant.\n  unfold sufficient_principals in *; expand_def.\n  pose proof succ_list_len_lower_bound.\n  destruct x as [|p [|p' ps]]; simpl in *; try omega.\n  assert (principal gst p /\\ principal gst p').\n  {\n    split;\n    inv_prop principals; break_and; rewrite -> Forall_forall in *;\n      simpl in *; intuition eauto.\n  }\n  break_and.\n  assert (p <> p').\n  {\n    inv_prop principals; expand_def.\n    inv_prop NoDup.\n    simpl in *; intuition.\n  }\n  repeat invcs_prop principal.\n  intro.\n  assert (id_of s1 = id_of s2).\n  {\n    assert (wf_ptr s1 /\\ wf_ptr s2)\n      by (split; eapply wf_ptr_succ_list_invariant'; eauto; repeat find_rewrite; in_crush).\n    in_crush; repeat invcs_prop valid_ptr; congruence.\n  }\n  assert (hash p <> hash p').\n  {\n    intro; find_eapply_prop (p <> p').\n    eapply hash_injective_invariant; eauto.\n  }\n  assert (between (id_of s1) (hash p) (id_of s2) \\/\n          between (id_of s1) (hash p') (id_of s2)).\n  {\n    repeat find_rewrite.\n    destruct (id_eq_dec (id_of s2) (hash p));\n      [right|left]; eapply between_xyx; congruence.\n  }\n  autounfold in *; break_and.\n  assert (not_skipped (ChordIDSpace.hash h) (map id_of (succ_list st)) (ChordIDSpace.hash p))\n    by eauto.\n  assert (not_skipped (ChordIDSpace.hash h) (map id_of (succ_list st)) (ChordIDSpace.hash p'))\n    by eauto.\n  break_or_hyp;\n    match goal with\n    | H: not_skipped _ _ _ |- _ =>\n      eapply H; [|eassumption]\n    end;\n    repeat find_rewrite; simpl;\n      change (ChordIDSpace.hash h :: id_of s1 :: id_of s2 :: map id_of rest)\n        with ([ChordIDSpace.hash h] ++ id_of s1 :: id_of s2 :: map id_of rest);\n      repeat find_rewrite;\n      eauto.\nQed.\nHint Resolve first_succ_and_second_distinct.\n\n(* Eventually this should only list the following \"assumptions\":\n\n    succ_list_len_lower_bound : SUCC_LIST_LEN >= 2\n    ocaml_hash : Chord.addr -> {s : String.string | String.length s = N}\n    Chord.client_addr : String.string -> Prop\n    SUCC_LIST_LEN : nat\n    N : nat\n*)\nPrint Assumptions zave_invariant_holds.\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/RingCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16682659662320184}}
{"text": "Require Import\n        Coq.Vectors.Vector\n        Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Bedrock.Word\n        Bedrock.Memory\n        Fiat.Computation.ListComputations.\n\nRequire Import\n        Fiat.Computation.IfDec\n        Fiat.QueryStructure.Specification.Operations.InsertAll\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.Narcissus.Examples.DNS.DNSPacket\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Examples.DnsServer.RecursiveDNSSchema.\n\nImport Vectors.Vector.VectorNotations.\n\nLocal Open Scope vector.\nLocal Open Scope Tuple_scope.\n\nDefinition linkAuthorityToAdditional\n           (curTime : timeT)\n           (this : QueryStructure RecResolverSchema)\n           (authority : list resourceRecord)\n           (additional : list resourceRecord)\n  : Comp (QueryStructure RecResolverSchema) :=\n  authorityAndAdditional <-\n                         {aal | NoDup aal /\\\n                                forall (ns : NS_Record)\n                                       (ans : A_Record),\n                                  List.In < sDOMAIN :: (ns!sRDATA : DomainName),\n                                            sIP :: (ans!sRDATA : W) > aal\n                            <-> (List.In (NS_Record2RRecord ns) authority\n                                 /\\ List.In (A_Record2RRecord ans) additional\n                                 /\\ ns!sRDATA = ans!sNAME) };\n    `(this, _) <- @StatefulInsertAll RecResolverSchema _ _ _ this ``sSLIST\n                       () authorityAndAdditional\n                       (@QSInsert _)\n                       (fun aal _ => ret (< sQUERYCOUNT :: (natToWord _ 0 : W),\n                                          sTTL :: (curTime ^+ serverTTL : timeT ) > ++ aal, tt))\n                       (fun a s => ret s);\n    ret this\n.\n\nDefinition addAnswersToCache\n           (curTime : timeT)\n           (this : QueryStructure RecResolverSchema)\n           (answers : list resourceRecord)\n           (authority : list resourceRecord)\n           (additional : list resourceRecord)\n  : Comp (QueryStructure RecResolverSchema) :=\n  `(this, _) <- @StatefulInsertAll RecResolverSchema _ _ _ this ``sCACHE\n   () (answers ++ authority ++ additional)\n   (@QSInsert _)\n   (fun aal _ => ret (< sTTL :: curTime ^+ cachedTTL,\n                        sCACHETYPE :: ANSWER,\n                        sDOMAIN :: aal!sNAME,\n                        sQTYPE :: (RDataTypeToRRecordType (aal!sRDATA)),\n                        sCACHEDVALUE :: rRecord2CachedValue aal >, tt))\n   (fun a s => ret s);\n    ret this.\n\nDefinition getSIP (tup : @Tuple SLISTHeading) : W := tup!sIP.\n\nDefinition DnsSpec (q : _ -> packet) : ADT _ :=\n  Def ADT {\n    rep := QueryStructure RecResolverSchema,\n\n    Def Constructor \"Init\" : rep := empty,,\n\n    Def Method3 \"Process\"\n        (this : rep)\n        (sourceIP : W)\n        (curTime : timeT)\n        (p : packet) : rep * packet * option W :=\n      If p!\"QR\" Then\n         (* It's a new request! *)\n         vs <- For (v in this!sCACHE) (* Search cache for an answer *)\n                    Where (p!\"question\"!\"qtype\" = CachedQueryTypes_inj v!sQTYPE)\n                    Where (curTime <= v!sTTL) (* only alive cached values *)\n                    Return (v ! sCACHEDVALUE) ;\n         If is_empty vs Then (* Need to launch a recursive query *)\n            (* Generate a unique ID for the new request. *)\n            (reqIDs <- For (req in this!sREQUESTS)\n                            Where (curTime <= req!sTTL)\n                            Return (req!sID);\n             newID <- { newID | ~ List.In newID reqIDs};\n             (* Find the best known servers to query *)\n             bestServer <- MaxElement\n                             (fun r r' : @Tuple SLISTHeading =>\n                                (prefix r!sDOMAIN r'!sDOMAIN)\n                                /\\ r!sQUERYCOUNT <= r'!sQUERYCOUNT)\n                             (For (server in this!sSLIST)\n                              Where (prefix server!sDOMAIN p!\"question\"!\"qname\")\n                              Where (curTime <= server!sTTL)\n                              Return server);\n             Ifopt bestServer as bestServer Then (* Pick the first server*)\n             `(this, _) <- Delete req from this ! sREQUESTS where (req!sTTL <= curTime);\n             `(this, b) <- Insert < sID :: newID,\n                                    sIP :: sourceIP,\n                                    sTTL :: curTime ^+ requestTTL > ++ p into this!sREQUESTS; (* Add the request to the list. *)\n             ret (this, (q <\"id\" :: newID,\n                          \"QR\" :: false,\n                          \"Opcode\" :: ``\"Query\",\n                          \"AA\" :: false,\n                          \"TC\" :: false,\n                          \"RD\" :: true,\n                          \"RA\" :: false,\n                          \"RCode\" :: ``\"NoError\",\n                          \"question\" :: p!\"question\",\n                          \"answers\" :: [ ],\n                          \"authority\" :: [ ],\n                          \"additional\" :: [ ] >, Some (getSIP bestServer)))\n             Else (* There are no known servers that can answer this request. *)\n             ret (this, (buildempty false ``\"ServFail\" p, Some sourceIP)) (* This won't happen if the server has been properly initialized with the root servers. *)\n            )\n       Else                   (* Return cached answer *)\n       (answers <- { answers | NoDup answers\n                               /\\ forall ans : resourceRecord,\n                         List.In ans answers <->\n                         List.In (A := CachedValue) ans vs };\n          If is_empty answers Then (* It must be a cached failure *)\n             failures <- { failures | NoDup failures\n                                      /\\ forall fail : SOA_Record,\n                               List.In (A := resourceRecord) fail failures <->\n                               List.In (A := CachedValue) fail vs };\n             ret (this, (add_additionals failures (buildempty false ``\"NXDomain\" p), Some sourceIP)) (* Add the SoA record to additional and return negative result*)\n          Else\n          ret (this, (add_answers answers (buildempty false ``\"NoError\" p), Some sourceIP)))\n         (* Add the answers to the packet.  *)\n       Else (* It's a response *)\n       (reqs <- For (req in this!sREQUESTS)\n                     Where (req!sID = p!\"id\")\n                     Where (req!\"question\"!\"qtype\" = p!\"question\"!\"qtype\")\n                     Return req;\n        Ifopt List.hd_error reqs as req Then\n          (IfDec p!\"RCODE\" = ``\"NoError\" Then\n            (If isAnswer p Then    (* We have an answer! We first try to  the outstanding request that this is an answer to. *)\n                `(this, reqs) <- Delete req from this!sREQUESTS where (req!sID = p!\"id\");\n                this <- addAnswersToCache curTime this p!\"answers\" p!\"authority\" p!\"additional\";\n                ret (this, (<\"id\" :: req!\"id\",\n                             \"QR\" :: true,\n                             \"Opcode\" :: req!\"Opcode\",\n                             \"AA\" :: false,\n                             \"TC\" :: p!\"TC\",\n                             \"RD\" :: req!\"RD\",\n                             \"RA\" :: true,\n                             \"RCode\" :: ``\"NoError\",\n                             \"question\" :: req!\"question\",\n                             \"answers\" :: p!\"answers\",\n                             \"authority\" :: p!\"authority\",\n                             \"additional\" :: p!\"additional\" >, Some req!sIP) )\n\n           Else  (* We need to issue another query based on the response. *)\n           (this <- linkAuthorityToAdditional curTime this p!\"authority\" p!\"additional\";\n             bestServer <- MaxElement\n                             (fun r r' : @Tuple SLISTHeading =>\n                                (prefix r!sDOMAIN r'!sDOMAIN)\n                                /\\ r!sQUERYCOUNT <= r'!sQUERYCOUNT)\n                             (For (server in this!sSLIST)\n                              Where (prefix server!sDOMAIN p!\"question\"!\"qname\")\n                              Where (curTime <= server!sTTL)\n                              Return server);\n             Ifopt bestServer as bestServer Then (* Pick the first server*)\n               ret (this, (<\"id\" :: p!\"id\",\n                            \"QR\" :: false,\n                            \"Opcode\" :: ``\"Query\",\n                            \"AA\" :: false,\n                            \"TC\" :: false,\n                            \"RD\" :: true,\n                            \"RA\" :: false,\n                            \"RCode\" :: ``\"NoError\",\n                            \"question\" :: p!\"question\",\n                            \"answers\" :: [ ],\n                            \"authority\" :: [ ],\n                            \"additional\" :: [ ] >, Some bestServer!sIP))\n             Else\n               ret (this, (p, None ) )\n         ) )\n         Else (* We need to cache a negative response*)\n         (soas <- { soas | NoDup soas\n                           /\\ forall soa : SOA_Record,\n                        List.In soa soas <->\n                        List.In (A := resourceRecord) soa (p!\"authority\") };\n         Ifopt List.hd_error soas as soa Then (* The response has an SOA *)\n           reqType <- SingletonSet (fun b : CachedQueryTypes => req!\"question\"!\"qtype\" = CachedQueryTypes_inj b);\n           Ifopt reqType as reqType Then\n             (`(this, foo) <- Insert (< sTTL :: curTime ^+ cachedTTL,\n                                        sCACHETYPE :: ``\"Failure\",\n                                        sDOMAIN :: req!\"question\"!\"qname\",\n                                        sQTYPE :: reqType,\n                                        sCACHEDVALUE :: Failure2CachedValue (<\"RCODE\" :: (p!\"RCODE\" : ResponseCode) > ++ soa!sRDATA : FailureRecord ) > )\n               into this!sCACHE;\n              ret (this, (p, Some req!sIP))  )\n            Else (* It's not a record we care to cache *)\n             ret (this, (p, Some req!sIP) )\n           Else (* If there's no SOA record in authority, don't cache *)\n           ret (this, (p, Some req!sIP ) ) ) )\n         Else (* The answer is not affiliated with the packet *)\n           ret (this, (p, None ) ) )\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/Examples/DnsServer/RecursiveDNSResolver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.16682658855129956}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import riscv.Utility.Monads. Import StateAbortFailOperations.\nRequire Import riscv.Utility.MonadNotations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Spec.CSRFile.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Utility.ExtensibleRecords.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Platform.Sane.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\nImport ListNotations.\n\nDefinition regs: nat := 0.\nDefinition pc: nat := 1.\nDefinition nextPc: nat := 2.\nDefinition mem: nat := 3.\n(* xAddrs : 4 *)\nDefinition log: nat := 5.\n(* metrics: 6 *)\nDefinition csrs: nat := 7.\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 Register word}.\n  Context (UnknownFields: natmap Type).\n\n  Definition Fields: natmap Type := natmap.putmany UnknownFields [\n    (regs, Registers: Type);\n    (pc, word: Type);\n    (nextPc, word: Type);\n    (mem, Mem: Type);\n    (log, list RiscvMachine.LogItem: Type);\n    (csrs, CSRFile: Type)\n   ].\n\n  Definition State: Type := hnatmap Fields.\n\n  Import HnatmapNotations. Open Scope hnatmap_scope.\n\n  Definition fail_if_None{R}(o: option R): StateAbortFail State R :=\n    match o with\n    | Some x => Return x\n    | None => fail_hard\n    end.\n\n  Local Notation get := (@StateAbortFailOperations.get State). (* to improve type inference *)\n\n  Definition loadN(n: nat)(kind: SourceType)(a: word): StateAbortFail State (HList.tuple byte n) :=\n    mach <- get;\n    v <- fail_if_None (Memory.load_bytes n mach[mem] a);\n    Return v.\n\n  Definition storeN(n: nat)(kind: SourceType)(a: word)(v: HList.tuple byte n): StateAbortFail State unit :=\n    mach <- get;\n    m <- fail_if_None (Memory.store_bytes n mach[mem] a v);\n    put mach[mem := m].\n\n  Definition updatePc(mach: State): State :=\n    mach[pc := mach[nextPc]][nextPc := word.add mach[nextPc] (word.of_Z 4)].\n\n  Instance IsRiscvMachine: RiscvProgram (StateAbortFail State) word := {\n      getRegister reg :=\n        if Z.eq_dec reg Register0 then\n          Return (ZToReg 0)\n        else\n          if (0 <? reg) && (reg <? 32) then\n            mach <- get;\n            fail_if_None (map.get mach[regs] reg)\n          else\n            fail_hard;\n\n      setRegister reg v :=\n        if Z.eq_dec reg Register0 then\n          Return tt\n        else\n          if (0 <? reg) && (reg <? 32) then\n            mach <- get; put mach[regs := map.put mach[regs] reg v]\n          else\n            fail_hard;\n\n      getPC := mach <- get; Return mach[pc];\n\n      setPC newPC := mach <- get; put mach[nextPc := newPC];\n\n      loadByte   := loadN 1;\n      loadHalf   := loadN 2;\n      loadWord   := loadN 4;\n      loadDouble := loadN 8;\n\n      storeByte   := storeN 1;\n      storeHalf   := storeN 2;\n      storeWord   := storeN 4;\n      storeDouble := storeN 8;\n\n      getCSRField f := mach <- get; fail_if_None (map.get mach[csrs] f);\n      setCSRField f v := mach <- get; put mach[csrs := map.put mach[csrs] f v];\n\n      makeReservation  addr := fail_hard;\n      clearReservation addr := fail_hard;\n      checkReservation addr := fail_hard;\n      getPrivMode := Return Machine;\n      setPrivMode mode :=\n        match mode with\n        | Machine => Return tt\n        | User | Supervisor => fail_hard\n        end;\n      fence _ _ := fail_hard;\n\n      endCycleNormal := mach <- get; put (updatePc mach);\n      endCycleEarly{A: Type} := mach <- get; put (updatePc mach);; abort;\n  }.\n\nEnd Riscv.\n\n(* needed because defined inside a Section *)\n#[global] Existing Instance IsRiscvMachine.\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/MinimalCSRsDet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.28140561345566495, "lm_q1q2_score": 0.16677970813475818}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RunSMC.Layer.\nRequire Import TableAux.Code.granule_fill_table.\n\nRequire Import TableAux.LowSpecs.granule_fill_table.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _pgte_write \u21a6 gensem pgte_write_spec\n      \u2295 _barrier \u21a6 gensem barrier_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_pgte_write: block.\n    Hypothesis h_pgte_write_s : Genv.find_symbol ge _pgte_write = Some b_pgte_write.\n    Hypothesis h_pgte_write_p : Genv.find_funct_ptr ge b_pgte_write\n                                = Some (External (EF_external _pgte_write\n                                                 (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tvoid cc_default))\n                                       (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tvoid cc_default).\n    Local Opaque pgte_write_spec.\n\n    Variable b_barrier: block.\n    Hypothesis h_barrier_s : Genv.find_symbol ge _barrier = Some b_barrier.\n    Hypothesis h_barrier_p : Genv.find_funct_ptr ge b_barrier\n                             = Some (External (EF_external _barrier\n                                              (signature_of_type Tnil tvoid cc_default))\n                                    Tnil tvoid cc_default).\n    Local Opaque barrier_spec.\n\n    Lemma granule_fill_table_body_correct:\n      forall m d d' env le pte_base pte_offset pte_val pte_inc\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTpte: PTree.get _pte le = Some (Vptr pte_base (Int.repr pte_offset)))\n             (HPTpte_val: PTree.get _pte_val le = Some (Vlong pte_val))\n             (HPTpte_inc: PTree.get _pte_inc le = Some (Vlong pte_inc))\n             (Hspec: granule_fill_table_spec0 (pte_base, pte_offset) (VZ64 (Int64.unsigned pte_val)) (VZ64 (Int64.unsigned pte_inc)) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) granule_fill_table_body E0 le' (m, d') Out_normal).\n    Proof.\n      solve_code_proof Hspec granule_fill_table_body; try solve [eexists; solve_proof_low].\n      get_loop_body. clear_hyp.\n      set (Hloop := C1).\n      remember (PTree.set _i (Vint (Int.repr 0)) le)  as le_loop.\n      remember 512 as num.\n      set (P := fun le0 m0 => m0 = (m, d) /\\ le0 = le_loop).\n      set (Q := fun (le0: temp_env) m0 => m0 = (m, d')).\n      set (Inv := fun le0 m0 n => exists i' ptev' adt1,\n                      granule_fill_table_loop0 (Z.to_nat (num - n)) 0 (pte_base, pte_offset)\n                                               (Int64.unsigned pte_val) (Int64.unsigned pte_inc) d\n                      = Some (Int.unsigned i', Int64.unsigned ptev', adt1) /\\ Int.unsigned i' = num - n /\\\n                        m0 = (m, adt1) /\\ 0 <= n /\\ n <= num /\\ le0 ! _i = Some (Vint i') /\\\n                        le0 ! _pte = Some (Vptr pte_base (Int.repr pte_offset)) /\\\n                        le0 ! _pte_val = Some (Vlong ptev') /\\\n                        le0 ! _pte_inc = Some (Vlong pte_inc)).\n      assert(loop_succ: forall N, Z.of_nat N <= num -> exists i' ptev' adt',\n                  granule_fill_table_loop0 (Z.to_nat (num - Z.of_nat N)) 0 (pte_base, pte_offset)\n                                           (Int64.unsigned pte_val) (Int64.unsigned pte_inc) d\n                  = Some (Int.unsigned i', Int64.unsigned ptev', adt')).\n      { add_int Hloop z; try somega. add_int64 Hloop z0; 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' z1; try somega; try add_int64' z2; try somega; repeat eexists. }\n      assert (T: LoopProofSimpleWhile.t (external_calls_ops := CompatExternalCalls.compatlayer_extcall_ops L) cond body ge (PTree.empty _) P Q).\n      { apply LoopProofSimpleWhile.make with (W:=Z) (lt:=fun z1 z2 => (0 <= z2 /\\ z1 < z2)) (I:=Inv).\n        - apply Zwf_well_founded.\n        - unfold P, Inv. intros ? ? CC. destruct CC as [CC1 CC2].\n          rewrite CC2 in *. exists num.\n          replace (num - num) with 0 by omega. simpl. 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 H10, H11, H12 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/TableAux/CodeProof/granule_fill_table.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.1667545409903431}}
{"text": "Require Import GhostSimulations.\n\nRequire Import Raft.\nRequire Import CommonTheorems.\nRequire Import CommitRecordedCommittedInterface.\nRequire Import StateMachineSafetyInterface.\nRequire Import StateMachineSafetyPrimeInterface.\nRequire Import RaftRefinementInterface.\nRequire Import MaxIndexSanityInterface.\nRequire Import LeaderCompletenessInterface.\nRequire Import SortedInterface.\nRequire Import LogMatchingInterface.\nRequire Import PrevLogLeaderSublogInterface.\nRequire Import CurrentTermGtZeroInterface.\nRequire Import LastAppliedLeCommitIndexInterface.\nRequire Import MatchIndexAllEntriesInterface.\nRequire Import LeadersHaveLeaderLogsInterface.\nRequire Import LeaderSublogInterface.\nRequire Import TermsAndIndicesFromOneLogInterface.\nRequire Import GhostLogCorrectInterface.\nRequire Import GhostLogsLogPropertiesInterface.\nRequire Import GhostLogLogMatchingInterface.\nRequire Import TransitiveCommitInterface.\nRequire Import TermSanityInterface.\nRequire Import LeadersHaveLeaderLogsStrongInterface.\nRequire Import OneLeaderLogPerTermInterface.\n\nRequire Import RefinedLogMatchingLemmasInterface.\n\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import RaftMsgRefinementInterface.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSection StateMachineSafetyProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {si : sorted_interface}.\n  Context {lmi : log_matching_interface}.\n  Context {smspi : state_machine_safety'interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {pllsi : prevLog_leader_sublog_interface}.\n  Context {ctgt0 : current_term_gt_zero_interface}.\n  Context {lalcii : lastApplied_le_commitIndex_interface}.\n  Context {miaei : match_index_all_entries_interface}.\n  Context {lhlli : leaders_have_leaderLogs_interface}.\n  Context {lci : leader_completeness_interface}.\n  Context {lsi : leader_sublog_interface}.\n  Context {taifoli : terms_and_indices_from_one_log_interface}.\n  Context {glci : ghost_log_correct_interface}.\n  Context {lphogli : log_properties_hold_on_ghost_logs_interface}.\n  Context {glemi : ghost_log_entries_match_interface}.\n  Context {tci : transitive_commit_interface}.\n  Context {tsi : term_sanity_interface}.\n  \n  Context {lhllsi : leaders_have_leaderLogs_strong_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n\n  Context {rmri : raft_msg_refinement_interface}.\n\n  Lemma exists_deghost_packet :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params)),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    intros.\n    unfold deghost in *. simpl in *. do_in_map.\n    subst. eexists; eauto.\n  Qed.\n\n  Lemma state_machine_safety_deghost :\n    forall net,\n      commit_recorded_committed net ->\n      state_machine_safety' net ->\n      state_machine_safety (deghost net).\n  Proof using. \n    intros. unfold state_machine_safety in *. intuition.\n    - unfold state_machine_safety_host. intros.\n      do 2 eapply_prop_hyp commit_recorded_committed commit_recorded.\n      unfold state_machine_safety' in *. intuition. eauto.\n    - unfold state_machine_safety_nw. intros.\n      eapply_prop_hyp commit_recorded_committed commit_recorded.\n      unfold state_machine_safety', state_machine_safety_nw' in *. intuition.\n      find_apply_lem_hyp exists_deghost_packet. break_exists.\n      intuition. subst. simpl in *. repeat break_match. simpl in *.\n      subst. eapply_prop_hyp In In; repeat find_rewrite; simpl; eauto.\n  Qed.\n\n  Definition ghost_log_network : Type := @network _ raft_msg_refined_multi_params.\n  Definition ghost_log_packet : Type := @packet _ raft_msg_refined_multi_params.\n\n  Definition lifted_maxIndex_sanity (net : ghost_log_network) : Prop :=\n    (forall h,\n      lastApplied (snd (nwState net h)) <= maxIndex (log (snd (nwState net h)))) /\\\n    (forall h, commitIndex (snd (nwState net h)) <= maxIndex (log (snd (nwState net h)))).\n\n  Lemma lifted_maxIndex_sanity_init :\n    msg_refined_raft_net_invariant_init lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_init, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition.\n  Qed.\n\n  Ltac update_destruct :=\n    match goal with\n      | [ H : context [ update _ ?x _ ?y ] |- _ ] =>\n        destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n      | [ |- context [ update _ ?x _ ?y ] ] =>\n        destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n    end.\n\n  Lemma handleClientRequest_lastApplied :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; find_inversion; auto.\n  Qed.\n\n  Lemma handleClientRequest_maxIndex :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      sorted (log st') ->\n      maxIndex (log st) <= maxIndex (log st').\n  Proof using. \n    intros.\n    destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)).\n    - auto.\n    - simpl in *. break_and.\n      destruct (log st); simpl in *.\n      + omega.\n      + find_insterU. conclude_using eauto. intuition.\n  Qed.\n\n  Lemma lifted_sorted_host :\n    forall net h,\n      refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    find_insterU. conclude_using eauto.\n    unfold logs_sorted, logs_sorted_host in *. break_and.\n    unfold deghost in *. simpl in *. break_match. eauto.\n  Qed.\n\n  Lemma msg_lifted_sorted_host :\n    forall net h,\n      msg_refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using rmri si rri. \n    intros.\n    rewrite <- msg_deghost_spec with (net0 := net).\n    eapply msg_lift_prop.\n    - auto using lifted_sorted_host.\n    - auto.\n  Qed.\n  \n  Lemma lifted_sorted_network :\n    forall net p t n pli plt es ci,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      sorted es.\n  Proof using rlmli. \n    intros. eapply entries_sorted_nw_invariant; eauto.\n  Qed.\n\n  Definition lifted_no_entries_past_current_term_host net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma lifted_no_entries_past_current_term_host_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_no_entries_past_current_term_host net.\n  Proof using rmri tsi. \n    intros.\n    enough (no_entries_past_current_term_host (deghost (mgv_deghost net))) by\n        (unfold no_entries_past_current_term_host, lifted_no_entries_past_current_term_host, deghost, mgv_deghost in *;\n         simpl in *;\n         repeat break_match; simpl in *; auto).\n    apply msg_lift_prop_all_the_way; eauto.\n    intros.\n    eapply no_entries_past_current_term_invariant; eauto.\n  Qed.\n\n  Lemma all_the_way_deghost_spec :\n    forall (net : ghost_log_network) h,\n      snd (nwState net h) = nwState (deghost (mgv_deghost net)) h.\n  Proof using rmri rri. \n    intros.\n    rewrite deghost_spec.\n    rewrite msg_deghost_spec with (net0 := net).\n    auto.\n  Qed.\n\n  Lemma all_the_way_simulation_1 :\n    forall (net : ghost_log_network),\n      msg_refined_raft_intermediate_reachable net ->\n      raft_intermediate_reachable (deghost (mgv_deghost net)).\n  Proof using rmri rri. \n    auto using simulation_1, msg_simulation_1.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_client_request :\n    msg_refined_raft_net_invariant_client_request lifted_maxIndex_sanity.\n  Proof using rmri si rri. \n    unfold msg_refined_raft_net_invariant_client_request, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    simpl. intros.\n    find_copy_apply_lem_hyp handleClientRequest_maxIndex.\n    - intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct; auto.\n      + erewrite handleClientRequest_lastApplied by eauto. eauto using le_trans.\n      + erewrite handleClientRequest_commitIndex by eauto. eauto using le_trans.\n    - match goal with H : _ |- _ => rewrite all_the_way_deghost_spec with (net := net) in H end.\n        eapply handleClientRequest_logs_sorted; eauto.\n        * auto using all_the_way_simulation_1.\n        * apply logs_sorted_invariant. auto using all_the_way_simulation_1.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_timeout :\n    msg_refined_raft_net_invariant_timeout lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_timeout, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct; auto;\n    erewrite handleTimeout_log_same by eauto.\n    - erewrite handleTimeout_lastApplied; eauto.\n    - erewrite handleTimeout_commitIndex; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_lastApplied :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold handleAppendEntries, advanceCurrentTerm;\n    intros; repeat break_match; repeat find_inversion; simpl; auto.\n  Qed.\n\n  Lemma sorted_maxIndex_app :\n    forall l1 l2,\n      sorted (l1 ++ l2) ->\n      maxIndex l2 <= maxIndex (l1 ++ l2).\n  Proof using. \n    induction l1; intros; simpl in *; intuition.\n    destruct l2; intuition. simpl in *.\n    specialize (H0 e). conclude H0 intuition. intuition.\n  Qed.\n\n  Lemma max_min_thing:\n    forall a b c,\n      a <= c ->\n      max a (min b c) <= c.\n  Proof using. \n    intros.\n    destruct (max a (min b c)) using (Max.max_case _ _); intuition.\n  Qed.\n\n  Lemma in_ghost_packet :\n    forall (net : network (params := raft_refined_multi_params)) p,\n      In p (nwPackets net) ->\n      In (deghost_packet p) (nwPackets (deghost net)).\n  Proof using. \n    unfold deghost.\n    simpl. intuition.\n    apply in_map_iff.\n    eexists; eauto.\n  Qed.\n\n  Lemma in_mgv_ghost_packet :\n    forall (net : ghost_log_network) p,\n      In p (nwPackets net) ->\n      In (mgv_deghost_packet p) (nwPackets (mgv_deghost net)).\n  Proof using. \n    unfold mgv_deghost.\n    simpl. intuition.\n    apply in_map_iff.\n    eexists; eauto.\n  Qed.\n\n  Lemma pBody_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)),\n      pBody (deghost_packet p) = pBody p.\n  Proof using. \n    unfold deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pDst_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)),\n      pDst (deghost_packet p) = pDst p.\n  Proof using. \n    unfold deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pDst_mgv_deghost_packet :\n    forall (p : ghost_log_packet),\n      pDst (mgv_deghost_packet p) = pDst p.\n  Proof using. \n    unfold mgv_deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pBody_mgv_deghost_packet :\n    forall (p : ghost_log_packet),\n      pBody (mgv_deghost_packet p) = snd (pBody p).\n  Proof using. \n    unfold mgv_deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma lifted_handleAppendEntries_logs_sorted :\n    forall (net : ghost_log_network) (p : ghost_log_packet) t n pli plt es ci st' m,\n      msg_refined_raft_intermediate_reachable net ->\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (st', m) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      In p (nwPackets net) ->\n      sorted (log st').\n  Proof using rmri si rri. \n    intros.\n    eapply handleAppendEntries_logs_sorted with (p0 := deghost_packet (mgv_deghost_packet p)).\n    - eauto using all_the_way_simulation_1.\n    - apply lift_prop.\n      + apply logs_sorted_invariant.\n      + auto using msg_simulation_1.\n    - rewrite <- all_the_way_deghost_spec.\n      rewrite pDst_deghost_packet.\n      rewrite pDst_mgv_deghost_packet.\n      eauto.\n    - rewrite pBody_deghost_packet.\n      rewrite pBody_mgv_deghost_packet.\n      auto.\n    - apply in_ghost_packet. apply in_mgv_ghost_packet. auto.\n  Qed.\n\n  Lemma contiguous_range_exact_lo_elim_exists :\n    forall es lo i,\n      contiguous_range_exact_lo es lo ->\n      lo < i <= maxIndex es -> exists e, eIndex e = i /\\ In e es.\n  Proof using. \n    unfold contiguous_range_exact_lo.\n    intuition.\n  Qed.\n\n  Lemma contiguous_range_exact_lo_elim_lt :\n    forall es lo e,\n      contiguous_range_exact_lo es lo ->\n      In e es ->\n      lo < eIndex e.\n  Proof using. \n    unfold contiguous_range_exact_lo.\n    intuition.\n  Qed.\n\n  Lemma lifted_sms_nw :\n    forall (net : network (params := raft_refined_multi_params)) h p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n      state_machine_safety (deghost net) ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      t >= currentTerm (snd (nwState net h)) ->\n      commit_recorded (deghost net) h e ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n  Proof using rri. \n    unfold state_machine_safety, state_machine_safety_nw.\n    intuition.\n    match goal with\n      | [ H : _ |- _ ] => eapply H with (p := deghost_packet p)\n    end.\n    - auto using in_ghost_packet.\n    - rewrite pBody_deghost_packet. eauto.\n    - rewrite deghost_spec. eauto.\n    - auto.\n  Qed.\n\n\n  Lemma msg_lifted_sms_nw :\n    forall (net : ghost_log_network) h p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n      state_machine_safety (deghost (mgv_deghost net)) ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                    entries leaderCommit ->\n      t >= currentTerm (snd (nwState net h)) ->\n      commit_recorded (deghost (mgv_deghost net)) h e ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n  Proof using rmri rri. \n    intros.\n    eapply lifted_sms_nw.\n    - eauto.\n    - eauto using in_mgv_ghost_packet.\n    - rewrite pBody_mgv_deghost_packet. eauto.\n    - rewrite msg_deghost_spec with (net0 := net). eauto.\n    - auto.\n  Qed.\n\n  Lemma commit_recorded_lift_intro :\n    forall (net : network (params := raft_refined_multi_params)) h e,\n      In e (log (snd (nwState net h))) ->\n      (eIndex e <= lastApplied (snd (nwState net h)) \\/\n       eIndex e <= commitIndex (snd (nwState net h))) ->\n      commit_recorded (deghost net) h e.\n  Proof using rri. \n    unfold commit_recorded.\n    intros.\n    rewrite deghost_spec.\n    auto.\n  Qed.\n\n  Lemma msg_commit_recorded_lift_intro :\n    forall (net : ghost_log_network) h e,\n      In e (log (snd (nwState net h))) ->\n      (eIndex e <= lastApplied (snd (nwState net h)) \\/\n       eIndex e <= commitIndex (snd (nwState net h))) ->\n      commit_recorded (deghost (mgv_deghost net)) h e.\n  Proof using rmri rri. \n    unfold commit_recorded.\n    intros.\n    rewrite deghost_spec.\n    rewrite msg_deghost_spec with (net0 := net).\n    auto.\n  Qed.\n\n  Definition lifted_entries_contiguous (net : ghost_log_network) : Prop :=\n    forall h, contiguous_range_exact_lo (log (snd (nwState net h))) 0.\n\n  Lemma lifted_entries_contiguous_invariant :\n    forall net, msg_refined_raft_intermediate_reachable net ->\n           lifted_entries_contiguous net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_contiguous.\n    intros.\n    pose proof (msg_lift_prop _ entries_contiguous_invariant _ ltac:(eauto) h).\n    find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Definition lifted_entries_contiguous_nw (net : ghost_log_network) : Prop :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      contiguous_range_exact_lo es pli.\n\n  Lemma lifted_entries_contiguous_nw_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_contiguous_nw net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_contiguous_nw.\n    intros.\n    pose proof msg_lift_prop _ entries_contiguous_nw_invariant _ ltac:(eauto) (mgv_deghost_packet p).\n    match goal with\n    | [ H : context [In] |- _ ] => eapply H\n    end.\n    - auto using in_mgv_ghost_packet.\n    - rewrite pBody_mgv_deghost_packet. eauto.\n  Qed.\n\n  Definition lifted_entries_gt_0 (net : ghost_log_network) : Prop :=\n    forall h e,\n      In e (log (snd (nwState net h))) -> eIndex e > 0.\n\n  Lemma lifted_entries_gt_0_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_gt_0 net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_gt_0.\n    intros.\n    pose proof msg_lift_prop _ entries_gt_0_invariant _ ltac:(eauto).\n    unfold entries_gt_0 in *.\n    match goal with\n    | [ H : _ |- _ ] => eapply H; eauto\n    end.\n    rewrite msg_deghost_spec.\n    eauto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_append_entries :\n    forall xs (p : ghost_log_packet) ys (net : ghost_log_network) st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      lifted_maxIndex_sanity net ->\n      state_machine_safety (deghost (mgv_deghost net)) ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall (p' : ghost_log_packet), In p' ps' -> In p' (xs ++ ys) \\/\n                         mgv_deghost_packet p' = mkPacket (params := raft_refined_multi_params)\n                                                          (pDst p) (pSrc p) m) ->\n      lifted_maxIndex_sanity (mkNetwork ps' st').\n  Proof using rmri rlmli si rri. \n    unfold lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intros.\n    intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct; auto.\n    - erewrite handleAppendEntries_lastApplied by eauto.\n      assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n      match goal with\n        | _ : handleAppendEntries ?h ?s ?t ?n ?pli ?plt ?es ?ci = (?s', ?m) |- _ =>\n          pose proof handleAppendEntries_log_detailed\n               h s t n pli plt es ci s' m\n      end.\n      intuition; repeat find_rewrite.\n      + eauto.\n      + subst.\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        assert (exists x, eIndex x = maxIndex (log d) /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              eapply contiguous_range_exact_lo_elim_lt.\n              * eapply lifted_entries_contiguous_nw_invariant; eauto.\n              * auto.\n            + eapply le_trans; [|eauto]. simpl in *. omega.\n        }\n        break_exists. break_and.\n        eapply findAtIndex_None; [|eauto| |]; eauto.\n        apply msg_lifted_sorted_host; auto.\n      + subst.\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        left; repeat find_rewrite; auto using lt_le_weak].\n        intuition.\n        * subst.\n          assert (0 < eIndex x) by (eapply lifted_entries_contiguous_invariant; eauto).\n          omega.\n        * destruct (log d); intuition. simpl in *.\n          intuition; subst; auto.\n          find_apply_hyp_hyp. omega.\n      + destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) pli); intuition;\n        [eapply le_trans; [| apply sorted_maxIndex_app]; auto;\n         break_exists; break_and;\n         erewrite maxIndex_removeAfterIndex by (eauto; apply msg_lifted_sorted_host; auto);\n         auto|]; [idtac].\n\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        assert (exists x, eIndex x = maxIndex es /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              destruct es.\n              * simpl in *. intuition.\n              * simpl.  subst.\n                { eapply le_lt_trans with (m := eIndex x).\n                  - omega.\n                  - eapply contiguous_range_exact_lo_elim_lt.\n                    + eapply lifted_entries_contiguous_nw_invariant; eauto.\n                    + intuition.\n                }\n            + eapply le_trans; [|eauto]. simpl in *. omega.\n        }\n        break_exists. intuition.\n        match goal with\n          | H : findAtIndex _ _ = None |- _ =>\n            eapply findAtIndex_None with (x1 := x) in H\n        end; eauto.\n        * congruence.\n        * apply msg_lifted_sorted_host. auto.\n      +   destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n        find_copy_apply_lem_hyp maxIndex_non_empty.\n        break_exists. intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        left; repeat find_rewrite; auto using lt_le_weak].\n\n        match goal with\n          | _ : In ?x es, _ : maxIndex es = eIndex ?x |- _ =>\n            assert (pli < eIndex x)\n                   by ( eapply contiguous_range_exact_lo_elim_lt; eauto;\n                        eapply lifted_entries_contiguous_nw_invariant; eauto)\n        end.\n        intuition.\n\n        match goal with\n          | H : _ = _ ++ _ |- _ => symmetry in H\n        end.\n        destruct es; intuition;\n        simpl in *;\n        intuition; subst_max; intuition;\n        repeat clean;\n        match goal with\n          | _ : eIndex ?x' = eIndex ?x, H : context [eIndex ?x'] |- _ =>\n            specialize (H x); conclude H ltac:(apply in_app_iff; auto)\n          end; intuition.\n    - assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n      match goal with\n        | _ : handleAppendEntries ?h ?s ?t ?n ?pli ?plt ?es ?ci = (?s', ?m) |- _ =>\n          pose proof handleAppendEntries_log_detailed\n               h s t n pli plt es ci s' m\n      end.\n      intuition; repeat find_rewrite; try apply max_min_thing;\n      match goal with\n        | H : context [ lastApplied _ ] |- _ => clear H\n      end.\n      + eauto.\n      + subst.\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        assert (exists x, eIndex x = maxIndex (log d) /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              eapply contiguous_range_exact_lo_elim_lt.\n              * eapply lifted_entries_contiguous_nw_invariant; eauto.\n              * auto.\n            + eapply le_trans; [|eauto]. simpl in *. omega.\n        }\n        break_exists. intuition.\n        find_eapply_lem_hyp findAtIndex_None; eauto.\n        apply msg_lifted_sorted_host. auto.\n      + subst.\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        right; repeat find_rewrite; intuition].\n        intuition.\n        * subst.\n          assert (0 < eIndex x) by (eapply lifted_entries_contiguous_invariant; eauto).\n          omega.\n        * destruct (log d); intuition. simpl in *.\n          intuition; subst; auto.\n          find_apply_hyp_hyp. omega.\n      + destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) pli); intuition;\n        [eapply le_trans; [| apply sorted_maxIndex_app]; auto;\n         break_exists; intuition;\n         erewrite maxIndex_removeAfterIndex; eauto; apply msg_lifted_sorted_host; auto|]; [idtac].\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        assert (exists x, eIndex x = maxIndex es /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              destruct es.\n              * simpl in *. intuition.\n              * simpl.  subst.\n                { eapply le_lt_trans with (m := eIndex x).\n                  - omega.\n                  - eapply contiguous_range_exact_lo_elim_lt.\n                    + eapply lifted_entries_contiguous_nw_invariant; eauto.\n                    + intuition.\n                }\n            + eapply le_trans; [|eauto]. simpl in *. omega.\n        }\n        break_exists. intuition.\n        match goal with\n          | H : findAtIndex _ _ = None |- _ =>\n            eapply findAtIndex_None with (x1 := x) in H\n        end; eauto.\n        * congruence.\n        * apply msg_lifted_sorted_host; auto.\n      + destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n        find_copy_apply_lem_hyp maxIndex_non_empty.\n        break_exists. intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        right; repeat find_rewrite; intuition].\n        match goal with\n          | _ : In ?x es, _ : maxIndex es = eIndex ?x |- _ =>\n            assert (pli < eIndex x)\n              by (eapply contiguous_range_exact_lo_elim_lt; eauto;\n                        eapply lifted_entries_contiguous_nw_invariant; eauto)\n        end.\n\n        intuition.\n        * match goal with\n            | H : _ = _ ++ _ |- _ => symmetry in H\n          end.\n          destruct es; intuition;\n          simpl in *;\n          intuition; subst_max; intuition;\n          repeat clean;\n          match goal with\n            | _ : eIndex ?x' = eIndex ?x, H : context [eIndex ?x'] |- _ =>\n              specialize (H x); conclude H ltac:(apply in_app_iff; auto)\n          end; intuition.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_append_entries_reply,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct; auto.\n    - erewrite handleAppendEntriesReply_same_lastApplied by eauto.\n      erewrite handleAppendEntriesReply_same_log by eauto.\n      auto.\n    - erewrite handleAppendEntriesReply_same_commitIndex by eauto.\n      erewrite handleAppendEntriesReply_same_log by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_request_vote :\n    msg_refined_raft_net_invariant_request_vote lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_request_vote,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct; auto.\n    - erewrite handleRequestVote_same_log by eauto.\n      erewrite handleRequestVote_same_lastApplied by eauto.\n      auto.\n    - erewrite handleRequestVote_same_log by eauto.\n      erewrite handleRequestVote_same_commitIndex by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_request_vote_reply,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct; auto.\n    - rewrite handleRequestVoteReply_same_log.\n      rewrite handleRequestVoteReply_same_lastApplied.\n      auto.\n    - rewrite handleRequestVoteReply_same_log.\n      rewrite handleRequestVoteReply_same_commitIndex.\n      auto.\n  Qed.\n\n  Lemma doLeader_same_lastApplied :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma fold_left_maximum_le' :\n    forall l x y,\n      x <= y ->\n      x <= fold_left max l y.\n  Proof using. \n    induction l; intros.\n    - auto.\n    - simpl. apply IHl. apply Max.max_case_strong; omega.\n  Qed.\n\n  Lemma fold_left_maximum_le :\n    forall l x,\n      x <= fold_left max l x.\n  Proof using. \n    intros. apply fold_left_maximum_le'.\n    auto.\n  Qed.\n\n  Lemma fold_left_maxmimum_increase_init :\n    forall l x y,\n      fold_left max l x = x ->\n      x <= y ->\n      fold_left max l y = y.\n  Proof using. \n    induction l; intros.\n    - auto.\n    - simpl in *. revert H.\n      repeat (apply Max.max_case_strong; intros).\n      + eauto.\n      + assert (a = y) by omega. subst_max. eauto.\n      + subst x. pose proof (fold_left_maximum_le l a).\n        assert (fold_left max l a = a) by omega.\n        eauto.\n      + subst x.\n        pose proof (fold_left_maximum_le l a).\n        assert (fold_left max l a = a) by omega.\n        assert (a = y) by omega.\n        subst. auto.\n  Qed.\n\n  Lemma fold_left_maximum_cases :\n    forall l x,\n      fold_left max l x = x \\/\n      exists y,\n        In y l /\\ fold_left max l x = y.\n  Proof using. \n    induction l; simpl.\n    - auto.\n    - intros.\n      specialize (IHl (max x a)).\n      intuition.\n      + revert H.\n        apply Max.max_case_strong; intuition.\n        intuition eauto using fold_left_maxmimum_increase_init.\n      + break_exists. break_and. eauto.\n  Qed.\n\n  Lemma fold_left_maximum_ind :\n    forall l x (P : nat -> Prop),\n      P x ->\n      (forall y, In y l -> P y) ->\n      P (fold_left max l x).\n  Proof using. \n    intros.\n    destruct (fold_left_maximum_cases l x).\n    - find_rewrite. auto.\n    - break_exists. break_and. find_rewrite. eauto.\n  Qed.\n\n  Lemma doLeader_same_commitIndex :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      sorted (log st) ->\n      commitIndex st <= maxIndex (log st) ->\n      commitIndex st' <= maxIndex (log st').\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto;\n    apply fold_left_maximum_ind; auto.\n    - intros. do_in_map. find_apply_lem_hyp filter_In.\n      subst. break_and.\n      apply maxIndex_is_max; eauto using findGtIndex_in.\n    - intros. do_in_map. find_apply_lem_hyp filter_In.\n      break_and. subst.\n      apply maxIndex_is_max; eauto using findGtIndex_in.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_do_leader :\n    msg_refined_raft_net_invariant_do_leader lifted_maxIndex_sanity.\n  Proof using rmri si rri. \n    unfold msg_refined_raft_net_invariant_do_leader,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct; auto.\n    - erewrite doLeader_same_log by eauto.\n      erewrite doLeader_same_lastApplied by eauto.\n      repeat match goal with\n        | [ H : forall _ , _ |- _ ] => specialize (H h0)\n      end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. auto.\n    - repeat match goal with\n                 | [ H : forall _ , _ |- _ ] => specialize (H h0)\n               end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. simpl in *.\n      erewrite doLeader_same_commitIndex; eauto.\n      find_eapply_lem_hyp (msg_lifted_sorted_host net h0).\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      find_rewrite. auto.\n  Qed.\n\n  Lemma doGenericServer_lastApplied :\n    forall h st out st' ms,\n      doGenericServer h st = (out, st', ms) ->\n      lastApplied st' = lastApplied st \\/\n      (lastApplied st < commitIndex st  /\\\n       lastApplied st' = commitIndex st).\n  Proof using. \n    unfold doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion; simpl.\n    - do_bool.\n      revert Heqb.\n      eapply applyEntries_spec_ind; eauto.\n    - do_bool.\n      revert Heqb.\n      eapply applyEntries_spec_ind; eauto.\n  Qed.\n\n\n  Lemma lifted_maxIndex_sanity_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_do_generic_server,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; find_higher_order_rewrite; update_destruct; auto;\n    erewrite doGenericServer_log by eauto.\n    - repeat match goal with\n               | [ H : forall _ , _ |- _ ] => specialize (H h0)\n             end.\n      repeat find_rewrite. simpl in *.\n      find_apply_lem_hyp doGenericServer_lastApplied.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      intuition; repeat find_rewrite; auto.\n    - repeat match goal with\n               | [ H : forall _ , _ |- _ ] => specialize (H h0)\n             end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. simpl in *.\n      erewrite doGenericServer_commitIndex by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; find_reverse_higher_order_rewrite; auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_reboot :\n    msg_refined_raft_net_invariant_reboot lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_reboot,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    unfold reboot.\n    intuition; find_higher_order_rewrite; update_destruct; auto with *;\n    repeat match goal with\n             | [ H : forall _ , _ |- _ ] => specialize (H h0)\n           end;\n    unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *;\n    simpl in *;\n    repeat find_rewrite; simpl in *;\n    auto.\n  Qed.\n\n  Definition lifted_directly_committed (net : ghost_log_network) (e : entry) : Prop :=\n    exists quorum,\n      NoDup quorum /\\\n      length quorum > div2 (length nodes) /\\\n      (forall h, In h quorum -> In (eTerm e, e) (allEntries (fst (nwState net h)))).\n\n  Definition lifted_committed (net : ghost_log_network) (e : entry) (t : term) : Prop :=\n    exists h e',\n      eTerm e' <= t /\\\n      lifted_directly_committed net e' /\\\n      eIndex e <= eIndex e' /\\\n      In e (log (snd (nwState net h))) /\\ In e' (log (snd (nwState net h))).\n\n  Definition commit_invariant_host (net : ghost_log_network) : Prop :=\n    forall h e,\n      In e (log (snd (nwState net h))) ->\n      eIndex e <= commitIndex (snd (nwState net h)) ->\n      lifted_committed net e (currentTerm (snd (nwState net h))).\n\n  Definition commit_invariant_nw (net : ghost_log_network) : Prop :=\n    forall p t lid pli plt es lci e,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t lid pli plt es lci ->\n      In e (fst (pBody p)) ->\n      eIndex e <= lci ->\n      lifted_committed net e t.\n\n  Definition commit_invariant (net : ghost_log_network) : Prop :=\n    commit_invariant_host net /\\\n    commit_invariant_nw net.\n\n  Lemma commit_invariant_init :\n    msg_refined_raft_net_invariant_init commit_invariant.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_init, commit_invariant.\n    split.\n    - unfold commit_invariant_host, commit_recorded_committed, commit_recorded, committed. simpl.\n      intuition.\n    - unfold commit_invariant_nw; simpl; intuition.\n  Qed.\n\n  Lemma msg_lifted_lastApplied_le_commitIndex :\n    forall net h,\n      msg_refined_raft_intermediate_reachable net ->\n      lastApplied (snd (nwState net h)) <= commitIndex (snd (nwState net h)).\n  Proof using rmri lalcii rri. \n    intros.\n    pose proof (lift_prop _ (lastApplied_le_commitIndex_invariant)).\n    find_apply_lem_hyp msg_simulation_1.\n    find_apply_hyp_hyp.\n    unfold lastApplied_le_commitIndex in *.\n    match goal with\n    | [ H : _ |- _ ] => specialize (H h)\n    end.\n    find_rewrite_lem deghost_spec.\n    find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Lemma lifted_directly_committed_directly_committed :\n    forall net e,\n      lifted_directly_committed net e ->\n      directly_committed (mgv_deghost net) e.\n  Proof using rmri. \n    unfold lifted_directly_committed, directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    rewrite msg_deghost_spec. auto.\n  Qed.\n\n  Lemma directly_committed_lifted_directly_committed :\n    forall net e,\n      directly_committed (mgv_deghost net) e ->\n      lifted_directly_committed net e.\n  Proof using rmri. \n    unfold lifted_directly_committed, directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_apply_hyp_hyp.\n    find_rewrite_lem msg_deghost_spec. auto.\n  Qed.\n\n  Lemma lifted_committed_committed :\n    forall net e t,\n      lifted_committed net e t ->\n      committed (mgv_deghost net) e t.\n  Proof using rmri. \n    unfold lifted_committed, committed.\n    intros.\n    break_exists_exists.\n    rewrite msg_deghost_spec.\n    intuition auto using lifted_directly_committed_directly_committed.\n  Qed.\n\n  Lemma committed_lifted_committed :\n    forall net e t,\n      committed (mgv_deghost net) e t ->\n      lifted_committed net e t.\n  Proof using rmri. \n    unfold lifted_committed, committed.\n    intros.\n    break_exists_exists.\n    find_rewrite_lem msg_deghost_spec.\n    intuition auto using directly_committed_lifted_directly_committed.\n  Qed.\n\n  Lemma msg_deghost_spec' :\n    forall base multi failure ghost\n      (net : @network (@mgv_refined_base_params base)\n                      (@mgv_refined_multi_params base multi failure ghost)) h,\n      nwState (mgv_deghost net) h = nwState net h.\n  Proof using. \n    unfold mgv_deghost.\n    intros.\n    simpl.\n    destruct net. auto.\n  Qed.\n\n  Lemma commit_invariant_lower_commit_recorded_committed :\n    forall net : ghost_log_network,\n      msg_refined_raft_intermediate_reachable net ->\n      commit_invariant net ->\n      commit_recorded_committed (mgv_deghost net).\n  Proof using rmri lalcii rri. \n    unfold commit_invariant, commit_recorded_committed, commit_recorded, commit_invariant_host.\n    intuition;\n    repeat find_rewrite_lem deghost_spec;\n    repeat find_rewrite_lem msg_deghost_spec';\n    rewrite msg_deghost_spec';\n    apply lifted_committed_committed; auto.\n    eauto using le_trans, msg_lifted_lastApplied_le_commitIndex.\n  Qed.\n\n  Lemma handleClientRequest_currentTerm :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      currentTerm st' = currentTerm st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleClientRequest_commitIndex :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma directly_committed_allEntries_preserved :\n    forall net net' e,\n      directly_committed net e ->\n      (forall h, In (eTerm e, e) (allEntries (fst (nwState net h))) ->\n                 In (eTerm e, e) (allEntries (fst (nwState net' h)))) ->\n      directly_committed net' e.\n  Proof using. \n    unfold directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries :\n    forall h st client id c out st' ms,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      allEntries (update_elections_data_client_request h st client id c) =\n      allEntries (fst st) \\/\n      (exists e : entry,\n         eIndex e = S (maxIndex (log (snd st))) /\\\n         eTerm e = currentTerm (snd st) /\\\n         eClient e = client /\\ eInput e = c /\\ eId e = id /\\ type (snd st) = Leader /\\\n         allEntries (update_elections_data_client_request h st client id c) =\n         (currentTerm st', e) :: allEntries (fst st)).\n  Proof using. \n    intros.\n    unfold update_elections_data_client_request.\n    repeat break_match; repeat find_inversion; auto.\n    simpl.\n    find_copy_apply_lem_hyp handleClientRequest_log.\n    intuition.\n    - repeat find_rewrite. do_bool. omega.\n    - right.  break_exists_exists. intuition.\n      congruence.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries_ind :\n    forall {h st client id c out st' ps},\n      handleClientRequest h (snd st) client id c = (out, st', ps) ->\n      forall (P : list (term * entry) -> Prop),\n        P (allEntries (fst st)) ->\n        (forall e,\n         eIndex e = S (maxIndex (log (snd st))) ->\n         eTerm e = currentTerm (snd st) ->\n         eClient e = client -> eInput e = c -> eId e = id -> type (snd st) = Leader ->\n         P ((currentTerm st', e) :: allEntries (fst st))) ->\n        P (allEntries (update_elections_data_client_request h st client id c)).\n  Proof using. \n    intros.\n    find_apply_lem_hyp update_elections_data_client_request_allEntries.\n    intuition.\n    - find_rewrite. auto.\n    - break_exists. intuition.\n      repeat find_rewrite.  auto.\n  Qed.\n\n  Lemma update_elections_data_client_request_preserves_allEntries :\n    forall h st client id c out st' ms t e,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      In (t, e) (allEntries (fst st)) ->\n      In (t, e) (allEntries (update_elections_data_client_request h st client id c)).\n  Proof using. \n    intros.\n    match goal with\n      | [ |- context [ allEntries ?x ] ] =>\n        destruct (allEntries x)\n                 using (update_elections_data_client_request_allEntries_ind ltac:(eauto))\n    end; intuition.\n  Qed.\n\n  Lemma handleClientRequest_preservers_log :\n    forall h st client id c out st' ms e,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      In e (log st) ->\n      In e (log st').\n  Proof using. \n    intros.\n    destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)); intuition.\n  Qed.\n\n  Lemma committed_log_allEntries_preserved :\n    forall net net' e t,\n      committed net e t ->\n      (forall h e',\n         In e' (log (snd (nwState net h))) ->\n         In e' (log (snd (nwState net' h)))) ->\n      (forall h e' t',\n         In (t', e') (allEntries (fst (nwState net h))) ->\n         In (t', e') (allEntries (fst (nwState net' h)))) ->\n      committed net' e t.\n  Proof using. \n    unfold committed.\n    intros.\n    break_exists_exists.\n    intuition.\n    eapply directly_committed_allEntries_preserved; eauto.\n  Qed.\n\n  Lemma lifted_committed_log_allEntries_preserved :\n    forall net net' e t,\n      lifted_committed net e t ->\n      (forall h e',\n          In e' (log (snd (nwState net h))) ->\n          In e' (log (snd (nwState net' h)))) ->\n      (forall h e' t',\n          In (t', e') (allEntries (fst (nwState net h))) ->\n          In (t', e') (allEntries (fst (nwState net' h)))) ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    find_apply_lem_hyp lifted_committed_committed.\n    find_eapply_lem_hyp committed_log_allEntries_preserved; eauto.\n    apply committed_lifted_committed.\n    eapply committed_log_allEntries_preserved; eauto;\n    intros;\n    repeat find_rewrite_lem msg_deghost_spec;\n    rewrite msg_deghost_spec; auto.\n  Qed.\n\n  Lemma lift_max_index_sanity :\n    forall (net : ghost_log_network) h,\n      msg_refined_raft_intermediate_reachable net ->\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      lastApplied (snd (nwState net h)) <= maxIndex (log (snd (nwState net h))) /\\\n      commitIndex (snd (nwState net h)) <= maxIndex (log (snd (nwState net h))).\n  Proof using rmri rri. \n    intros.\n    match goal with\n      | [ H : _, H' : _ |- _ ] => apply H in H'; clear H\n    end.\n    unfold maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex in *.\n    break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => specialize (H h)\n           end.\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    auto.\n  Qed.\n\n  Lemma haveNewEntries_log :\n    forall es st st',\n      log st = log st' ->\n      haveNewEntries st es = true ->\n      haveNewEntries st' es = true.\n  Proof using. \n    unfold haveNewEntries.\n    intros.\n    find_rewrite. auto.\n  Qed.\n\n  Lemma hCR_preserves_committed :\n    forall (net net' : ghost_log_network) h client id c out d l e t,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      (forall h', nwState net' h' = update (nwState net) h (update_elections_data_client_request h (nwState net h) client id c, d) h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; simpl; eauto.\n    - intros. find_higher_order_rewrite.\n      update_destruct; eauto using handleClientRequest_preservers_log.\n    - intros. find_higher_order_rewrite.\n      update_destruct; eauto using update_elections_data_client_request_preserves_allEntries.\n  Qed.\n\n  Lemma not_empty_intro :\n    forall A (l : list A),\n      l <> [] -> not_empty l = true.\n  Proof using. \n    unfold not_empty.\n    intros.\n    break_match; congruence.\n  Qed.\n\n  Lemma haveNewEntries_true_intro :\n    forall st es,\n      es <> [] ->\n      (forall e, findAtIndex (log st) (maxIndex es) = Some e ->\n            eTerm e <> maxTerm es) ->\n      haveNewEntries st es = true.\n  Proof using. \n    unfold haveNewEntries.\n    intros.\n    do_bool. split.\n    - auto using not_empty_intro.\n    - break_match; auto.\n      apply Bool.negb_true_iff.\n      do_bool. intuition eauto.\n  Qed.\n\n  Definition lifted_prevLog_leader_sublog (net : network) : Prop :=\n    forall leader p t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n      type (snd (nwState net leader)) = Leader ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      currentTerm (snd (nwState net leader)) = prevLogTerm ->\n      0 < prevLogIndex ->\n      0 < prevLogTerm ->\n      exists ple, eIndex ple = prevLogIndex /\\\n             eTerm ple = prevLogTerm /\\\n             In ple (log (snd (nwState net leader))).\n\n  Lemma prevLog_leader_sublog_lifted :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_prevLog_leader_sublog net.\n  Proof using rmri pllsi rri. \n    intros.\n    pose proof (msg_lift_prop _ (lift_prop _ prevLog_leader_sublog_invariant)).\n    find_insterU. conclude_using eauto.\n    unfold prevLog_leader_sublog, lifted_prevLog_leader_sublog in *.\n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    find_apply_lem_hyp in_ghost_packet.\n    unfold deghost in *. simpl in *. break_match. simpl in *. subst.\n    specialize (H0 leader).\n    destruct (nwState leader). simpl in *.\n    eauto.\n  Qed.\n\n  Lemma commit_invariant_client_request :\n    forall h (net : ghost_log_network) st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      commit_invariant net ->\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg (params := ghost_log_params) h (gd, d) l))) ->\n      commit_invariant (mkNetwork ps' st').\n  Proof using rmri rri. \n    unfold msg_refined_raft_net_invariant_client_request, commit_invariant.\n    intros. split.\n    - { unfold commit_invariant_host in *. break_and.\n        unfold commit_recorded_committed, commit_recorded in *.\n        intros. simpl in *.\n        repeat find_higher_order_rewrite.\n        rewrite update_fun_comm with (f := snd).\n        repeat match goal with H : _ |- _ => rewrite update_fun_comm with (f := snd) in H end.\n        simpl in *.\n        repeat match goal with\n                 | [H : _ |- _] => rewrite (update_fun_comm raft_data _) in H\n               end.\n        rewrite (update_fun_comm raft_data _).\n        rewrite update_nop_ext' by (now erewrite <- handleClientRequest_currentTerm by eauto).\n        match goal with\n          | [H : _ |- _] => rewrite update_nop_ext' in H\n              by (now erewrite <- handleClientRequest_commitIndex by eauto)\n        end.\n        update_destruct.\n        - find_copy_apply_lem_hyp handleClientRequest_log.\n          break_and. break_or_hyp.\n          + repeat find_rewrite.\n            eapply lifted_committed_log_allEntries_preserved; eauto.\n            * simpl. intros. find_higher_order_rewrite.\n              update_destruct; repeat find_rewrite; auto.\n            * simpl. intros. find_higher_order_rewrite.\n              update_destruct; eauto using update_elections_data_client_request_preserves_allEntries.\n          + break_exists. break_and. repeat find_rewrite.\n            simpl in *.\n            match goal with\n              | [ H : _ \\/ In _ _ |- _ ] => invc H\n            end.\n            * find_eapply_lem_hyp (lift_max_index_sanity net h0); auto.\n              break_and. simpl in *. omega.\n            * { eapply lifted_committed_log_allEntries_preserved; eauto.\n                - simpl. intros. find_higher_order_rewrite.\n                  update_destruct; repeat find_rewrite; auto.\n                  find_reverse_rewrite.\n                  eapply handleClientRequest_preservers_log; eauto.\n                - simpl. intros. find_higher_order_rewrite.\n                  update_destruct; eauto using update_elections_data_client_request_preserves_allEntries.\n              }\n        - eapply lifted_committed_log_allEntries_preserved; eauto.\n          + simpl. intros. find_higher_order_rewrite.\n            update_destruct; repeat find_rewrite; eauto using handleClientRequest_preservers_log.\n          + simpl. intros. find_higher_order_rewrite.\n            update_destruct; eauto using update_elections_data_client_request_preserves_allEntries.\n      }\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply hCR_preserves_committed; eauto. simpl. subst. auto.\n      + unfold send_packets in *.\n        do_in_map.\n        unfold add_ghost_msg in *.\n        do_in_map.\n        subst. simpl in *.\n        exfalso. eapply handleClientRequest_no_append_entries; eauto 10.\n  Qed.\n\n  Lemma handleTimeout_preserves_committed :\n    forall h (net net' : ghost_log_network) out d' l e t,\n      handleTimeout h (snd (nwState net h)) = (out, d', l) ->\n      (forall h', nwState net' h' = update (nwState net) h (update_elections_data_timeout h (nwState net h), d') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct.\n      + now erewrite handleTimeout_log_same by eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct.\n      + now rewrite update_elections_data_timeout_allEntries.\n      + auto.\n  Qed.\n\n  Lemma lifted_committed_monotonic :\n    forall net t t' e,\n      lifted_committed net e t ->\n      t <= t' ->\n      lifted_committed net e t'.\n  Proof using. \n    unfold lifted_committed.\n    intros.\n    break_exists_exists.\n    intuition.\n  Qed.\n\n\n  Lemma commit_invariant_timeout :\n    msg_refined_raft_net_invariant_timeout commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_timeout, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply handleTimeout_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleTimeout_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleTimeout_log_same in H by eauto\n        end.\n        eapply lifted_committed_monotonic; [eauto|].\n        find_apply_lem_hyp handleTimeout_type_strong.\n        intuition; repeat find_rewrite; auto.\n      + eapply handleTimeout_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      * eapply handleTimeout_preserves_committed; eauto.\n        simpl. intros. subst. auto.\n      * do_in_map.\n        subst. simpl in *.\n        unfold add_ghost_msg in *.\n        do_in_map.\n        subst. simpl in *.\n        find_eapply_lem_hyp handleTimeout_packets; eauto.\n        exfalso. eauto 10.\n  Qed.\n\n  Lemma committed_ext :\n    forall ps  st st' t e,\n      (forall h, st' h = st h) ->\n      committed (mkNetwork ps st) e t ->\n      committed (mkNetwork ps st') e t.\n  Proof using. \n    unfold committed, directly_committed.\n    simpl. intros.\n    break_exists_exists.\n    find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.  intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_ext :\n    forall ps st st' t e,\n      (forall h, st' h = st h) ->\n      lifted_committed (mkNetwork ps st) e t ->\n      lifted_committed (mkNetwork ps st') e t.\n  Proof using rmri. \n    intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    unfold mgv_deghost in *.\n    eauto using committed_ext.\n  Qed.\n\n  Definition lifted_state_machine_safety_nw' net :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit e t',\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      lifted_committed net e t' ->\n      t >= t' ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n\n  Lemma lifted_state_machine_safety_nw'_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_state_machine_safety_nw' net.\n  Proof using rmri smspi. \n    intros.\n    unfold lifted_state_machine_safety_nw'.\n    intros.\n    find_apply_lem_hyp lifted_committed_committed.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n      | _ : snd (pBody ?p) = ?x |- _ =>\n        assert (pBody (@mgv_deghost_packet _ _ _ ghost_log_params p) = x)\n          by (rewrite pBody_mgv_deghost_packet; auto)\n    end.\n    eapply state_machine_safety'_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n\n  Lemma lifted_entries_sorted_nw :\n    forall net p t n pli plt es ci,\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      sorted es.\n  Proof using rmri rlmli. \n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n      | _ : snd (pBody ?p) = ?x |- _ =>\n        assert (pBody (@mgv_deghost_packet _ _ _ ghost_log_params p) = x)\n          by (rewrite pBody_mgv_deghost_packet; auto)\n    end.\n    find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n      \n  Lemma update_elections_data_appendEntries_preserves_allEntries' :\n    forall st h t n pli plt es ci x,\n      In x (allEntries (fst st)) ->\n      In x (allEntries (update_elections_data_appendEntries h st t n pli plt es ci)).\n  Proof using. \n    unfold update_elections_data_appendEntries.\n    intros. break_let. break_match; auto.\n    break_if; auto.\n    simpl. intuition.\n  Qed.\n\n  Lemma lifted_transitive_commit_invariant :\n    forall net h e e' t,\n      msg_refined_raft_intermediate_reachable net ->\n      In e (log (snd (nwState net h))) ->\n      In e' (log (snd (nwState net h))) ->\n      eIndex e <= eIndex e' ->\n      lifted_committed net e' t ->\n      lifted_committed net e t.\n  Proof using rmri tci. \n    intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    repeat match goal with\n             | H : _ |- _ =>\n               rewrite <- msg_deghost_spec with (net0 := net) in H\n           end.\n    eapply transitive_commit_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n  \n  Lemma handleAppendEntries_preserves_commit :\n    forall net net' h p t n pli plt es ci d m e t',\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      (forall h', nwState net' h' = update (nwState net) h\n                                      (update_elections_data_appendEntries\n                                         h (nwState net h) t n pli plt es ci, d) h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri tsi rlmli smspi si rri. \n    intros.\n    unfold lifted_committed in *.\n    break_exists_name host. break_exists_name e'.\n    exists host, e'.\n    intuition.\n    - (* directly committed doesn't change *)\n      unfold lifted_directly_committed in *.\n      break_exists_exists; intuition.\n      find_higher_order_rewrite.\n      update_destruct; eauto using update_elections_data_appendEntries_preserves_allEntries'.\n    - (* e is still around *)\n      find_higher_order_rewrite.\n      update_destruct; simpl in *; eauto.\n      assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n            (unfold lifted_committed;\n             exists host, e'; intuition;\n             eapply lifted_no_entries_past_current_term_host_invariant; eauto).\n      find_eapply_lem_hyp handleAppendEntries_log_detailed. intuition; repeat find_rewrite; eauto.\n      + (* pli = 0, no entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try omega.\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x > 0) by omega.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e <= maxIndex (log (snd (nwState net host)))) by omega.\n          apply maxIndex_is_max; auto.\n      + (* pli = 0, bad entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try omega.\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex x > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; omega.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; omega];\n          [idtac].\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x0 > 0) by omega.\n          enough (eIndex x0 > pli) by omega.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e <= maxIndex (log (snd (nwState net host)))) by omega.\n          apply maxIndex_is_max; auto.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; omega];\n          [idtac].\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition; try omega;\n        enough (pli < eIndex maxEntry) by omega;\n        eapply lifted_entries_contiguous_nw_invariant; eauto.\n    - find_higher_order_rewrite.\n      update_destruct; simpl in *; eauto.\n      assert (lifted_committed net e' (currentTerm (snd (nwState net host)))) by\n            (unfold lifted_committed;\n             exists host, e'; intuition;\n             eapply lifted_no_entries_past_current_term_host_invariant; eauto).\n      find_eapply_lem_hyp handleAppendEntries_log_detailed. intuition; repeat find_rewrite; eauto.\n      + (* pli = 0, no entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e' > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try omega.\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x > 0) by omega.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e' <= maxIndex (log (snd (nwState net host)))) by omega.\n          apply maxIndex_is_max; auto.\n      + (* pli = 0, bad entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e' > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try omega.\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex x > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; omega.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; omega];\n          [idtac].\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x0 > 0) by omega.\n          enough (eIndex x0 > pli) by omega.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e' <= maxIndex (log (snd (nwState net host)))) by omega.\n          apply maxIndex_is_max; auto.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; omega];\n          [idtac].\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition; try omega;\n        enough (pli < eIndex maxEntry) by omega;\n        eapply lifted_entries_contiguous_nw_invariant; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_currentTerm_le :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleAppendEntries, advanceCurrentTerm in *.\n    repeat break_match; find_inversion; simpl in *;\n    do_bool; auto.\n  Qed.\n\n  Theorem handleAppendEntries_log_detailed :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      (commitIndex st' = commitIndex st /\\ log st' = log st) \\/\n      (leaderId st' <> None /\\\n       currentTerm st' = t /\\\n       commitIndex st' = max (commitIndex st) (min ci (maxIndex es)) /\\\n       es <> nil /\\\n       pli = 0 /\\ t >= currentTerm st /\\ log st' = es /\\\n      haveNewEntries st es = true ) \\/\n      (leaderId st' <> None /\\\n       currentTerm st' = t /\\\n       commitIndex st' = max (commitIndex st)\n                             (min ci (maxIndex (es ++ (removeAfterIndex (log st) pli)))) /\\\n       es <> nil /\\\n        exists e,\n         In e (log st) /\\\n         eIndex e = pli /\\\n         eTerm e = plt) /\\\n      t >= currentTerm st /\\\n      log st' = es ++ (removeAfterIndex (log st) pli) /\\\n      haveNewEntries st es = true.\n  Proof using. \n    intros. unfold handleAppendEntries in *.\n    break_if; [find_inversion; subst; eauto|].\n    break_if;\n      [do_bool; break_if; find_inversion; subst;\n        try find_apply_lem_hyp haveNewEntries_true;\n        simpl in *; intuition eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex, some_none, advanceCurrentTerm_term|].\n    simpl in *. intuition eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex.\n    break_match; [|find_inversion; subst; eauto].\n    break_if; [find_inversion; subst; eauto|].\n    break_if; [|find_inversion; subst; eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex].\n    find_inversion; subst; simpl in *.\n    right. right.\n    find_apply_lem_hyp findAtIndex_elim.\n    intuition; do_bool; find_apply_lem_hyp haveNewEntries_true;\n    intuition eauto using advanceCurrentTerm_term; congruence.\n  Qed.\n\n  Definition lifted_entries_gt_0_nw (net : ghost_log_network) : Prop :=\n    forall p t n pli plt es ci e,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      In e es ->\n      eIndex e > 0.\n\n  Lemma lifted_entries_gt_0_nw_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_gt_0_nw net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_gt_0_nw.\n    intros.\n    pose proof msg_lift_prop _ entries_gt_0_nw_invariant _ ltac:(eauto).\n    unfold entries_gt_0_nw in *.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n    | [ H : _ |- _ ] => eapply H; eauto\n    end.\n  Qed.\n\n  Definition lifted_entries_sorted_nw' (net : ghost_log_network) :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      sorted es.\n\n  Lemma lifted_entries_sorted_nw'_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_sorted_nw' net.\n  Proof using rmri rlmli. \n    intros.\n    pose proof msg_lift_prop _ entries_sorted_nw_invariant.\n    find_copy_apply_hyp_hyp.\n    unfold entries_sorted_nw, lifted_entries_sorted_nw' in *.\n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    eapply_prop_hyp In In; eauto.\n  Qed.\n\n  Lemma commit_invariant_append_entries :\n    forall xs p ys (net : ghost_log_network) st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      commit_invariant net ->\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_maxIndex_sanity net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' ->\n             In p' (xs ++ ys) \\/ p' = mkPacket (pDst p) (pSrc p)\n                                             (write_ghost_log (pDst p) (gd, d), m)) ->\n      commit_invariant (mkNetwork ps' st').\n  Proof using rmri tsi glemi lphogli glci rlmli smspi si rri. \n    unfold commit_invariant.\n    intros.\n\n    assert (In p (nwPackets net)) by (repeat find_rewrite; auto with *).\n    split.\n    - break_and.\n       match goal with\n       | [ H : commit_invariant_host _ |- _ ] =>\n         rename H into Hhost;\n           unfold commit_invariant_host in *\n       end.\n       simpl. intros.\n       eapply lifted_committed_ext; eauto.\n\n       match goal with\n       | [ H : forall _, _ = _ |- _ ] => rewrite H in *\n       end.\n       update_destruct.\n       + (* e is in h's log *)\n         find_copy_apply_lem_hyp handleAppendEntries_log_detailed.\n         break_or_hyp.\n         * break_and. repeat find_rewrite.\n           eapply lifted_committed_monotonic; [\n               solve [eapply handleAppendEntries_preserves_commit; eauto] |\n               solve [eauto using handleAppendEntries_currentTerm_le] ].\n         * { break_or_hyp; repeat break_and.\n             - (* beginning of time case *)\n               repeat match goal with\n               | [ H : _ <= _, H': _ |- _ ] => rewrite H' in H\n               end.\n               find_apply_lem_hyp NPeano.Nat.max_le. break_or_hyp.\n               + (* my log is just the entries in the incoming AE.\n                    so e was in the incoming entries.\n                    but eIndex e <= old commit index.\n                    by maxIndex_commitIndex, exists e' in old log such that eIndex e = eIndex e'.\n                    note that e' is committed in the pre state by IH.\n                    now apply SMS'_nw invariant to e' to get four cases.\n                    first three are absurd by index calculation.\n                    it follows that e' is in es.\n                    but our new log is just es, so e' is in the new log.\n                    by thus e = e' by unique indices.\n                    thus e is committed.\n                  *)\n                 assert (eIndex e > 0) by (eapply lifted_entries_gt_0_nw_invariant; eauto).\n                 assert (exists e', eIndex e' = eIndex e /\\ In e' (log (snd (nwState net (pDst p))))).\n                 {\n                   eapply contiguous_range_exact_lo_elim_exists.\n                   - eapply lifted_entries_contiguous_invariant. auto.\n                   - split.\n                     + auto.\n                     + eapply le_trans; [eauto|].\n                       eapply_prop lifted_maxIndex_sanity.\n                 }\n                 break_exists_name e'.\n                 break_and.\n                 assert (lifted_committed net e' (currentTerm (snd (nwState net (pDst p))))) as He'committed\n                        by (apply Hhost; [auto|congruence]) .\n\n                 find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n                 concludes.\n                 assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n                 intuition.\n                 * omega.\n                 * omega.\n                 * match goal with\n                   | [ H : _ |- _ ] => eapply maxIndex_is_max in H; eauto; [idtac]\n                   end.\n                   omega.\n                 * assert (e = e') by (eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices).\n                   subst.\n                   eapply lifted_committed_monotonic; [\n                       solve [eapply handleAppendEntries_preserves_commit; eauto] |\n                       solve [eauto using handleAppendEntries_currentTerm_le] ].\n               + (* eIndex e <= incoming ci.\n                    result follows by the network invariant. *)\n                 match goal with\n                 | [ H : commit_invariant_nw _ |- _ ] =>\n                   rename H into Hnet; unfold commit_invariant_nw in *\n                 end.\n                 eapply_prop_hyp In In; [| eauto | | eauto using Min.min_glb_l].\n                 * eapply handleAppendEntries_preserves_commit; eauto.\n                 * find_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                   conclude_using eauto.\n                   { intuition.\n                     - match goal with\n                       | [ H : In _ _, H' : _ |- _ ] => rewrite H' in H\n                       end. auto.\n                     - break_exists. break_and.\n                       pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hprop.\n                       unfold log_properties_hold_on_ghost_logs in *.\n                       unfold msg_log_property in *.\n                       specialize (Hprop (fun l => forall e, In e l -> eIndex e > 0) p).\n                       conclude_using ltac:(intros; eapply lifted_entries_gt_0_invariant; eauto).\n                       concludes. simpl in *.\n                       find_apply_hyp_hyp.\n                       omega.\n                   }\n             - (* middle of time case *)\n               break_exists_name ple. break_and.\n               repeat match goal with\n                      | [ H : _ <= _, H': _ |- _ ] => rewrite H' in H\n                      end.\n               find_apply_lem_hyp NPeano.Nat.max_le. break_or_hyp.\n               + (* eIndex e <= old commit index *)\n                 repeat find_rewrite.\n                 match goal with\n                 | [ H : In e (_ ++ _) |- _ ] => apply in_app_or in H; destruct H\n                 end.\n                 * (* e is new *)\n                   { assert (eIndex e > 0) by (eapply lifted_entries_gt_0_nw_invariant; eauto).\n                     assert (exists e', eIndex e' = eIndex e /\\ In e' (log (snd (nwState net (pDst p))))).\n                     {\n                       eapply contiguous_range_exact_lo_elim_exists.\n                       - eapply lifted_entries_contiguous_invariant. auto.\n                       - split.\n                         + auto.\n                         + eapply le_trans; [eauto|].\n                           eapply_prop lifted_maxIndex_sanity.\n                     }\n                     break_exists_name e'.\n                     break_and.\n                     assert (lifted_committed net e' (currentTerm (snd (nwState net (pDst p))))) as He'committed\n                         by (apply Hhost; [auto|congruence]) .\n\n                     find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n                     concludes.\n                     assert (sorted es) by\n                         (eapply lifted_entries_sorted_nw'_invariant; eauto).\n                     assert (contiguous_range_exact_lo es (eIndex ple)) by\n                         (eapply lifted_entries_contiguous_nw_invariant; eauto).\n                     find_eapply_lem_hyp contiguous_range_exact_lo_elim_lt; eauto.\n                     intuition.\n                     * omega.\n                     * omega.\n                     * match goal with\n                       | [ H : _ |- _ ] => eapply maxIndex_is_max in H; eauto with *; [idtac]\n                       end.\n                       omega.\n                     * assert (e = e') by (eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices).\n                       subst.\n                       eapply lifted_committed_monotonic; [\n                           solve [eapply handleAppendEntries_preserves_commit; eauto] |\n                           solve [eauto using handleAppendEntries_currentTerm_le] ].\n                   }\n                 * (* e is old *)\n                   { eapply lifted_committed_monotonic.\n                     - eapply handleAppendEntries_preserves_commit; eauto.\n                       eapply Hhost with (h := pDst p); eauto using removeAfterIndex_in.\n                     - eauto using handleAppendEntries_currentTerm_le.\n                   }\n               + (* eIndex e <= new commit index *)\n                 match goal with\n                 | [ H : In e _ |- _ ] =>\n                   repeat match goal with\n                   | [ H' : _ |- _ ] => rewrite H' in H\n                   end;\n                     apply in_app_or in H; destruct H\n                 end.\n                 * (* e is new *)\n                   (* follows from network invariant *)\n                   { match goal with\n                     | [ H : commit_invariant_nw _ |- _ ] =>\n                       rename H into Hnet; unfold commit_invariant_nw in *\n                     end.\n                     match goal with\n                     | [ H : In _ (nwPackets _), H' : _ |- _ ] => eapply H' in H\n                     end; [| eauto | | eauto using Min.min_glb_l].\n                     * eapply handleAppendEntries_preserves_commit; eauto.\n                     * find_copy_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                       conclude_using eauto.\n                       { intuition.\n                         - match goal with\n                           | [ H : In _ _, H' : _ |- _ ] => rewrite H' in H\n                           end. auto.\n                         - break_exists_name gple. break_and.\n                           subst.\n                           eauto using findGtIndex_in.\n                       }\n                   }\n\n                 * (* e is old *)\n                   (* eIndex e <= pli\n                      by ghost log contiguous, exists e' in ghost log such that eIndex e = eIndex e'.\n                      e' is committed by the nw invariant.\n                      by ghost log matching, e = e'.\n                      thus e is committed.\n                    *)\n                   assert (eIndex e <= eIndex ple) by\n                       (eapply removeAfterIndex_In_le; eauto using msg_lifted_sorted_host).\n                   pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hprop.\n                   unfold log_properties_hold_on_ghost_logs in *.\n                   unfold msg_log_property in *.\n                   specialize (Hprop (fun l => contiguous_range_exact_lo l 0) p).\n                   conclude_using ltac:(intros; eapply lifted_entries_contiguous_invariant; eauto).\n                   concludes.\n                   simpl in *.\n\n                   find_copy_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                   conclude_using eauto.\n                   { intuition.\n                     - subst. find_apply_lem_hyp removeAfterIndex_in.\n                       pose proof lifted_entries_gt_0_invariant _ ltac:(eauto) _ _ ltac:(eauto).\n                       omega.\n                     - break_exists_name gple. break_and.\n                       assert (exists e', eIndex e' = eIndex e /\\ In e' (fst (pBody p))).\n                       {\n                         eapply contiguous_range_exact_lo_elim_exists; eauto.\n                         split.\n                         + eapply lifted_entries_gt_0_invariant; eauto using removeAfterIndex_in.\n                         + eapply le_trans with (m := eIndex gple); try omega.\n                           apply maxIndex_is_max; auto.\n                           pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hsort.\n                           unfold log_properties_hold_on_ghost_logs in *.\n                           unfold msg_log_property in *.\n                           specialize (Hsort sorted p msg_lifted_sorted_host).\n                           auto.\n                       }\n                       break_exists_name e'. break_and.\n                       find_apply_lem_hyp removeAfterIndex_in.\n                       assert (e = e').\n                       {\n                         eapply uniqueIndices_elim_eq;\n                         eauto using msg_lifted_sorted_host, sorted_uniqueIndices.\n                         pose proof ghost_log_entries_match_invariant _ ltac:(eauto) (pDst p) _ ltac:(eauto)\n                           as Hem.\n                         specialize (Hem ple gple e').\n                         repeat concludes. intuition.\n                       }\n                       subst.\n\n\n                       match goal with\n                       | [ H : commit_invariant_nw _ |- _ ] =>\n                         rename H into Hnet; unfold commit_invariant_nw in *\n                       end.\n                       eapply handleAppendEntries_preserves_commit; eauto.\n                       eapply Hnet; eauto using Min.min_glb_l.\n                   }\n           }\n       + eapply handleAppendEntries_preserves_commit; eauto.\n    - (* nw invariant preserved *)\n      break_and.\n      unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntries_preserves_commit; eauto.\n        simpl. subst. auto.\n      + subst. simpl in *.\n        find_apply_lem_hyp handleAppendEntries_not_append_entries.\n        subst. exfalso. eauto 10.\n  Qed.\n\n\n  Lemma handleAppendEntriesReply_preserves_commit :\n    forall (net net' : ghost_log_network) h src t es b st' l e t',\n      handleAppendEntriesReply h (snd (nwState net h)) src t es b = (st', l) ->\n      (forall h', nwState net' h' = update (nwState net) h (fst (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct.\n      + now erewrite handleAppendEntriesReply_same_log by eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct; auto.\n  Qed.\n\n  Lemma commit_invariant_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_append_entries_reply, commit_invariant.\n    simpl. intros.\n    split.\n    - unfold commit_invariant_host in *.\n      simpl. intuition.\n      repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleAppendEntriesReply_same_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleAppendEntriesReply_same_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; [eauto|].\n        find_apply_lem_hyp handleAppendEntriesReply_type_term.\n        intuition; repeat find_rewrite; auto.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n        simpl. subst. auto.\n      + do_in_map. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        find_apply_lem_hyp handleAppendEntriesReply_packets.\n        subst. simpl in *. intuition.\n  Qed.\n\n  Lemma handleRequestVote_preserves_committed :\n    forall (net net' : ghost_log_network) h t c li lt st' ms e t',\n      handleRequestVote h (snd (nwState net h)) t c li lt = (st', ms) ->\n      (forall h', nwState net' h' = update (nwState net) h (update_elections_data_requestVote h c t c li lt (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. find_higher_order_rewrite. update_destruct.\n      + now erewrite handleRequestVote_same_log by eauto.\n      + auto.\n    - intros. find_higher_order_rewrite. update_destruct.\n      + now rewrite update_elections_data_requestVote_allEntries.\n      + auto.\n  Qed.\n\n  Lemma commit_invariant_request_vote :\n    msg_refined_raft_net_invariant_request_vote commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_request_vote, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply handleRequestVote_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleRequestVote_same_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleRequestVote_same_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        find_apply_lem_hyp handleRequestVote_currentTerm_leaderId.\n        intuition.\n        unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n        simpl in *.\n        repeat find_rewrite. auto.\n      + eapply handleRequestVote_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp. intuition.\n      + eapply handleRequestVote_preserves_committed; eauto.\n        simpl. intros. subst. auto.\n      + subst. simpl in *. unfold write_ghost_log in *.\n        find_apply_lem_hyp handleRequestVote_no_append_entries.\n        subst.\n        exfalso. eauto 10.\n  Qed.\n\n  Lemma handleRequestVoteReply_preserves_committed :\n    forall (net net' : ghost_log_network) h src t v st' e t',\n      handleRequestVoteReply h (snd (nwState net h)) src t v = st' ->\n      (forall h', nwState net' h' = update (nwState net) h\n                                      (update_elections_data_requestVoteReply h\n                                                                              src t v (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct.\n      + erewrite handleRequestVoteReply_log; eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct.\n      + rewrite update_elections_data_requestVoteReply_allEntries. auto.\n      + auto.\n  Qed.\n\n  Lemma commit_invariant_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_request_vote_reply, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *. simpl. intuition.\n      match goal with\n      | [ H : forall h, st' h = _ |- _ ] => repeat rewrite H in *\n      end. destruct (name_eq_dec (pDst p) h).\n      + subst h. subst gd. rewrite_update. simpl in *.\n        eapply handleRequestVoteReply_preserves_committed; eauto.\n        find_copy_apply_lem_hyp handleRequestVoteReply_type.\n        subst.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => rewrite handleRequestVoteReply_same_commitIndex in H\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleRequestVoteReply_same_log in H\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        intuition; repeat find_rewrite; auto.\n      + rewrite_update. eapply handleRequestVoteReply_preserves_committed; eauto.\n        simpl. subst. auto.\n    - unfold commit_invariant_nw. simpl.\n      intros.\n      find_apply_hyp_hyp.\n      eapply handleRequestVoteReply_preserves_committed; eauto.\n      simpl. subst. auto.\n  Qed.\n\n\n  Lemma committed_ext' :\n    forall ps ps' st st' t e,\n      (forall h, st' h = st h) ->\n      committed (mkNetwork ps st) e t ->\n      committed (mkNetwork ps' st') e t.\n  Proof using. \n    unfold committed, directly_committed.\n    simpl. intros.\n    break_exists_exists.\n    find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.  intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_ext' :\n    forall ps ps' st st' t e,\n      (forall h, st' h = st h) ->\n      lifted_committed (mkNetwork ps st) e t ->\n      lifted_committed (mkNetwork ps' st') e t.\n  Proof using rmri. \n    intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    unfold mgv_deghost in *.\n    eauto using committed_ext'.\n  Qed.\n\n  Lemma doLeader_spec :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      (st' = st /\\ ms = []) \\/\n      (type st = Leader /\\\n       log st' = log st /\\\n       type st' = type st /\\\n       currentTerm st' = currentTerm st /\\\n       nextIndex st' = nextIndex st /\\\n       commitIndex st' = commitIndex (advanceCommitIndex st n) /\\\n       forall m, In m ms ->\n            exists h, h <> n /\\ m = replicaMessage (advanceCommitIndex st n) n h).\n  Proof using. \n    unfold doLeader.\n    intros.\n    destruct st. simpl in *.\n    repeat break_match; repeat find_inversion; simpl in *; eauto.\n    right. intuition.\n    - intros.\n      do_in_map. subst.\n      find_apply_lem_hyp filter_In. break_and.\n      break_if; try discriminate.\n      eexists. intuition eauto.\n    - intuition.\n  Qed.\n\n  Lemma haveQuorum_directly_committed :\n    forall net h e,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      In e (log (snd (nwState net h))) ->\n      haveQuorum (snd (nwState net h)) h (eIndex e) = true ->\n      eTerm e = currentTerm (snd (nwState net h)) ->\n      directly_committed net e.\n  Proof using miaei. \n    unfold haveQuorum, directly_committed.\n    intros. do_bool.\n    eexists. intuition eauto.\n    - apply filter_NoDup. pose proof no_dup_nodes. simpl in *. auto.\n    - find_apply_lem_hyp filter_In. break_and. do_bool.\n      eapply match_index_all_entries_invariant; eauto.\n  Qed.\n\n  Lemma advanceCommitIndex_committed :\n    forall h net,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (snd (nwState net h)) ->\n            committed net e (currentTerm (snd (nwState net h)))) ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (advanceCommitIndex (snd (nwState net h)) h) ->\n            committed net e (currentTerm (snd (nwState net h)))).\n  Proof using miaei. \n    unfold advanceCommitIndex.\n    intros. simpl in *.\n    match goal with\n    | [ H : context [fold_left Nat.max ?l ?x] |- _ ] =>\n      pose proof fold_left_maximum_cases l x\n    end. intuition.\n    break_exists. break_and.\n    find_apply_lem_hyp in_map_iff.\n    break_exists_name witness. break_and.\n    find_apply_lem_hyp filter_In.  break_and.\n    find_apply_lem_hyp findGtIndex_necessary. do_bool. break_and. do_bool. break_and.\n    do_bool.\n    unfold committed.\n    exists h, witness. intuition.\n    eapply haveQuorum_directly_committed; eauto.\n  Qed.\n\n  Lemma lifted_advanceCommitIndex_lifted_committed :\n    forall h net,\n      msg_refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (snd (nwState net h)) ->\n            lifted_committed net e (currentTerm (snd (nwState net h)))) ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (advanceCommitIndex (snd (nwState net h)) h) ->\n            lifted_committed net e (currentTerm (snd (nwState net h)))).\n  Proof using rmri miaei. \n    intros.\n    find_apply_lem_hyp msg_simulation_1.\n    match goal with\n    | [ H : refined_raft_intermediate_reachable _ |- _ ] =>\n      eapply advanceCommitIndex_committed in H\n    end;\n      repeat rewrite msg_deghost_spec' in *;\n      eauto using committed_lifted_committed, lifted_committed_committed.\n  Qed.\n\n  Lemma and_imp_2 :\n    forall P Q : Prop,\n      P /\\ (P -> Q) -> P /\\ Q.\n  Proof using. \n    tauto.\n  Qed.\n\n  Definition lifted_leaders_have_leaderLogs_strong (net : ghost_log_network) :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      exists ll es,\n        In (currentTerm (snd (nwState net h)), ll) (leaderLogs (fst (nwState net h))) /\\\n        log (snd (nwState net h)) = es ++ ll /\\\n        (forall e : entry, In e es -> eTerm e = currentTerm (snd (nwState net h))).\n\n  Lemma lifted_leaders_have_leaderLogs_strong_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leaders_have_leaderLogs_strong net.\n  Proof using rmri lhllsi. \n    unfold lifted_leaders_have_leaderLogs_strong.\n    intros.\n    pose proof msg_lift_prop _ leaders_have_leaderLogs_strong_invariant _ ltac:(eauto) h.\n    rewrite msg_deghost_spec' in *. auto.\n  Qed.\n\n  Definition lifted_one_leaderLog_per_term (net : ghost_log_network) : Prop :=\n    forall h h' t ll ll',\n      In (t, ll) (leaderLogs (fst (nwState net h))) ->\n      In (t, ll') (leaderLogs (fst (nwState net h'))) ->\n      h = h' /\\ ll = ll'.\n\n  Lemma lifted_one_leaderLog_per_term_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_one_leaderLog_per_term net.\n  Proof using rmri ollpti. \n    unfold lifted_one_leaderLog_per_term.\n    intros.\n    pose proof msg_lift_prop _ one_leaderLog_per_term_invariant _ ltac:(eauto) h h' t ll ll'.\n    repeat rewrite msg_deghost_spec' in *. auto.\n  Qed.\n\n  Lemma lifted_leaderLog_in_log :\n    forall net leader ll e,\n      msg_refined_raft_intermediate_reachable net ->\n      type (snd (nwState net leader)) = Leader ->\n      In (currentTerm (snd (nwState net leader)), ll) (leaderLogs (fst (nwState net leader))) ->\n      In e ll ->\n      In e (log (snd (nwState net leader))).\n  Proof using rmri ollpti lhllsi. \n    intros.\n\n    find_copy_apply_lem_hyp lifted_leaders_have_leaderLogs_strong_invariant; auto.\n\n    break_exists_name ll'.\n    break_exists_name es.\n    break_and.\n    find_eapply_lem_hyp (lifted_one_leaderLog_per_term_invariant _ ltac:(eauto) leader leader _ ll ll' ltac:(eauto)).\n    intuition. subst.\n    unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n    simpl in *.\n    repeat find_rewrite. intuition.\n  Qed.\n\n  Definition lifted_leaders_have_leaderLogs (net : ghost_log_network) : Prop :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      exists ll,\n        In (currentTerm (snd (nwState net h)), ll) (leaderLogs (fst (nwState net h))).\n  Lemma lifted_leaders_have_leaderLogs_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leaders_have_leaderLogs net.\n  Proof using rmri lhlli. \n    intros.\n    pose proof msg_lift_prop _ leaders_have_leaderLogs_invariant _ ltac:(eauto).\n    unfold leaders_have_leaderLogs, lifted_leaders_have_leaderLogs in *.\n    intros.\n    match goal with\n    | [ H : _ |- _ ] => specialize (H h)\n    end.\n    repeat find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n\n  Definition lifted_leader_completeness_directly_committed (net : ghost_log_network) : Prop :=\n    forall t e log h,\n      lifted_directly_committed net e ->\n      t > eTerm e -> In (t, log) (leaderLogs (fst (nwState net h))) -> In e log.\n\n  Definition lifted_leader_completeness_committed (net : ghost_log_network) : Prop :=\n    forall t t' e log h,\n      lifted_committed net e t ->\n      t' > t -> In (t', log) (leaderLogs (fst (nwState net h))) -> In e log.\n\n  Definition lifted_leader_completeness (net : ghost_log_network) : Prop :=\n    lifted_leader_completeness_directly_committed net /\\\n    lifted_leader_completeness_committed net.\n\n  Lemma lifted_leader_completeness_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leader_completeness net.\n  Proof using rmri lci. \n    intros.\n    pose proof msg_lift_prop _ leader_completeness_invariant _ ltac:(eauto).\n    unfold lifted_leader_completeness, leader_completeness in *.\n    intuition.\n    - unfold lifted_leader_completeness_directly_committed, leader_completeness_directly_committed in *.\n      intros.\n      find_apply_lem_hyp lifted_directly_committed_directly_committed.\n      eapply_prop_hyp directly_committed directly_committed; eauto.\n      rewrite msg_deghost_spec'. eauto.\n    - unfold lifted_leader_completeness_committed, leader_completeness_committed in *.\n      intros.\n      find_apply_lem_hyp lifted_committed_committed.\n      eapply_prop_hyp committed committed; eauto.\n      rewrite msg_deghost_spec'. eauto.\n  Qed.\n\n  Definition msg_lifted_leader_sublog_host (net : ghost_log_network) : Prop :=\n    forall leader e h,\n      type (snd (nwState net leader)) = Leader ->\n      In e (log (snd (nwState net h))) ->\n      eTerm e = currentTerm (snd (nwState net leader)) ->\n      In e (log (snd (nwState net leader))).\n\n  Lemma msg_lifted_leader_sublog_host_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      msg_lifted_leader_sublog_host net.\n  Proof using rmri lsi rri. \n    intros.\n    pose proof msg_lift_prop _ (lift_prop _ leader_sublog_invariant_invariant) _ ltac:(eauto).\n    simpl in *.\n    unfold leader_sublog_invariant, leader_sublog_host_invariant, msg_lifted_leader_sublog_host in *.\n    intuition.\n    match goal with\n    | [ H : _ |- _ ] =>\n      specialize (H leader e h)\n    end.\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Lemma lifted_entries_match_invariant :\n    forall net h h',\n      msg_refined_raft_intermediate_reachable net ->\n      entries_match (log (snd (nwState net h))) (log (snd (nwState net h'))).\n  Proof using rmri rlmli. \n    intros.\n    find_apply_lem_hyp msg_simulation_1.\n    find_eapply_lem_hyp entries_match_invariant.\n    repeat rewrite msg_deghost_spec' in *.\n    eauto.\n  Qed.\n\n  Lemma lifted_terms_and_indices_from_one_log : forall net h,\n    refined_raft_intermediate_reachable net ->\n    terms_and_indices_from_one (log (snd (nwState net h))).\n  Proof using taifoli rri. \n    intros.\n    pose proof (lift_prop _ terms_and_indices_from_one_log_invariant).\n    unfold terms_and_indices_from_one_log in *.\n    rewrite <- deghost_spec with (net0 := net). auto.\n  Qed.\n\n\n  Lemma doLeader_preserves_committed :\n    forall (net net' : ghost_log_network) d h os d' ms gd  e t,\n      doLeader d h = (os, d', ms) ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update (nwState net) h (gd, d') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; find_higher_order_rewrite; update_destruct.\n    - intros. find_higher_order_rewrite.\n      erewrite doLeader_same_log; eauto.\n    - auto.\n    - repeat find_rewrite. auto.\n    - auto.\n  Qed.\n\n  Lemma doLeader_message_lci :\n    forall st h os st' ms m t n pli plt es ci,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      ci = commitIndex st'.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n    unfold replicaMessage in *.\n    simpl in *.\n    repeat break_match; repeat find_inversion; subst; simpl in *;\n    repeat find_inversion; auto.\n  Qed.\n\n  Lemma doLeader_message_term :\n    forall st h os st' ms m t n pli plt es ci,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      t = currentTerm st'.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n    subst.\n    unfold replicaMessage in *. simpl in *.\n    find_inversion.\n    auto.\n  Qed.\n\n\n  Lemma commit_invariant_do_leader :\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      commit_invariant net ->\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_maxIndex_sanity net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p,\n          In p ps' -> In p (nwPackets net) \\/ In p (send_packets h (add_ghost_msg (params := ghost_log_params) h (gd, d') ms))) ->\n      commit_invariant {| nwPackets := ps'; nwState := st' |}.\n  Proof using rmri miaei. \n    unfold commit_invariant.\n    simpl. intros. break_and.\n    apply and_imp_2.\n    split.\n    - find_apply_lem_hyp doLeader_spec. break_or_hyp.\n      + break_and.\n        unfold commit_invariant_host in *. simpl. intros. repeat find_higher_order_rewrite.\n        eapply lifted_committed_ext' with (ps := nwPackets net) (st := nwState net).\n        * intros. subst. repeat find_higher_order_rewrite.\n          match goal with\n          | [ |- context [ update _ ?x _ ?y ] ] =>\n            destruct (name_eq_dec x y); subst; rewrite_update\n          end; auto.\n        * match goal with\n          | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n            replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n              replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n              clear H\n          end.\n          destruct net. simpl in *. auto.\n          update_destruct; auto.\n      + break_and.\n        unfold commit_invariant_host in *.\n        simpl. intros. repeat find_higher_order_rewrite.\n        match goal with\n        | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n          replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n            replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n            clear H\n        end.\n        match goal with\n        | [ H : context [ update _ ?x _ ?y ] |- _ ] =>\n          destruct (name_eq_dec x y); subst; rewrite_update\n        end.\n        * { eapply lifted_committed_log_allEntries_preserved.\n            - simpl. find_rewrite. eapply lifted_advanceCommitIndex_lifted_committed; auto.\n              + simpl in *. repeat find_rewrite. auto.\n              + simpl in *. repeat find_rewrite. auto.\n            - simpl. intros. find_higher_order_rewrite.\n              update_destruct.\n              + repeat find_rewrite. auto.\n              + auto.\n            - simpl. intros. find_higher_order_rewrite.\n              update_destruct; auto.\n          }\n        * { eapply lifted_committed_log_allEntries_preserved; eauto.\n            + simpl. intros. find_higher_order_rewrite. update_destruct; repeat find_rewrite; auto.\n            + simpl. intros. find_higher_order_rewrite. update_destruct; repeat find_rewrite; auto.\n          }\n    - intros Hhostpost.\n      unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + (* old packet *)\n        eapply_prop_hyp In In; eauto.\n        eauto using doLeader_preserves_committed.\n      + (* new packet *)\n        do_in_map. subst. simpl in *.\n        unfold add_ghost_msg in *.\n        do_in_map. subst. simpl in *.\n        find_copy_eapply_lem_hyp doLeader_message_lci; eauto.\n        find_copy_eapply_lem_hyp doLeader_message_term; eauto.\n        unfold write_ghost_log in *.\n        simpl in *.\n        unfold commit_invariant_host in *.\n        simpl in *.\n        specialize (Hhostpost h e).\n        subst.\n        repeat find_higher_order_rewrite.\n        repeat rewrite_update.\n        simpl in *.\n        intuition.\n  Qed.\n\n  Lemma doGenericServer_preserves_committed :\n    forall (net net' : ghost_log_network) h out st' ms e t,\n      doGenericServer h (snd (nwState net h)) = (out, st', ms) ->\n      (forall h', nwState net' h' = update (nwState net) h (fst (nwState net h), st') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; repeat find_higher_order_rewrite; update_destruct; auto.\n    now erewrite doGenericServer_log by eauto.\n  Qed.\n\n  Lemma commit_invariant_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_do_generic_server, commit_invariant.\n    simpl. intros.\n    match goal with\n    | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n      replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n    end.\n    intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n\n      update_destruct.\n      + eapply doGenericServer_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite doGenericServer_commitIndex  in H  by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite doGenericServer_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        find_apply_lem_hyp doGenericServer_type.\n        intuition. repeat find_rewrite. auto.\n      + eapply doGenericServer_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intuition.\n      + find_apply_hyp_hyp. intuition.\n        * eapply doGenericServer_preserves_committed; eauto.\n        * do_in_map. unfold add_ghost_msg in *. do_in_map.\n          find_apply_lem_hyp doGenericServer_packets.\n          subst. simpl in *. intuition.\n  Qed.\n\n  Lemma commit_invariant_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, commit_invariant.\n    intuition.\n    - unfold commit_invariant_host in *. intros.\n      repeat find_reverse_higher_order_rewrite.\n      destruct net, net'. simpl in *.\n      eapply lifted_committed_ext; [|eauto]. simpl. auto.\n    - unfold commit_invariant_nw in *. intros.\n      find_apply_hyp_hyp.\n      destruct net, net'. simpl in *.\n      eapply lifted_committed_ext'; [|eauto]. auto.\n  Qed.\n\n  Lemma reboot_preserves_committed :\n    forall (net net' : ghost_log_network) h e t,\n      (forall h', nwState net' h' = update (nwState net) h (fst (nwState net h), reboot (snd (nwState net h))) h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    unfold reboot.\n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; repeat find_higher_order_rewrite; update_destruct; auto.\n  Qed.\n\n  Lemma commit_invariant_reboot :\n    msg_refined_raft_net_invariant_reboot commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_reboot, commit_invariant.\n    intros.\n    match goal with\n    | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n      replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n    end.\n    intuition.\n    - unfold commit_invariant_host in *.\n      intros. repeat find_higher_order_rewrite.\n      update_destruct; eapply reboot_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      intros.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_reverse_rewrite.\n      eapply reboot_preserves_committed; eauto.\n  Qed.\n\n  Lemma maxIndex_sanity_lift :\n    forall net,\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      lifted_maxIndex_sanity net.\n  Proof using rmri rri. \n    unfold maxIndex_sanity, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intros. intuition;\n    repeat match goal with\n      | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n    end;\n    repeat find_rewrite_lem deghost_spec;\n    repeat find_rewrite_lem msg_deghost_spec;\n    auto.\n  Qed.\n\n  Lemma maxIndex_sanity_lower :\n    forall net,\n      lifted_maxIndex_sanity net ->\n      maxIndex_sanity (deghost (mgv_deghost net)).\n  Proof using rri. \n    unfold maxIndex_sanity, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; rewrite deghost_spec; rewrite msg_deghost_spec';\n    repeat match goal with\n             | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n           end; intuition.\n  Qed.\n\n  Definition everything (net : ghost_log_network) : Prop :=\n    lifted_maxIndex_sanity net /\\\n    commit_invariant net /\\\n    state_machine_safety (deghost (mgv_deghost net)).\n\n  Lemma everything_init :\n    msg_refined_raft_net_invariant_init everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_init, everything.\n    intuition.\n    - apply lifted_maxIndex_sanity_init.\n    - apply commit_invariant_init.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed; [constructor|].\n        apply commit_invariant_init.\n      + apply state_machine_safety'_invariant.\n        constructor.\n  Qed.\n\n  Lemma everything_client_request :\n    msg_refined_raft_net_invariant_client_request' everything.\n  Proof using rmri lalcii smspi si rri. \n    unfold msg_refined_raft_net_invariant_client_request', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_client_request; eauto.\n    - eapply commit_invariant_client_request; eauto.\n      + auto using maxIndex_sanity_lower.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed; auto.\n        eapply commit_invariant_client_request; eauto.\n        apply maxIndex_sanity_lower. auto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_timeout :\n    msg_refined_raft_net_invariant_timeout' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_timeout', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_timeout; eauto.\n    - eapply commit_invariant_timeout; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_timeout; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_append_entries :\n    msg_refined_raft_net_invariant_append_entries' everything.\n  Proof using rmri tsi glemi lphogli glci lalcii rlmli smspi si rri. \n    unfold msg_refined_raft_net_invariant_append_entries', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_append_entries; eauto.\n      intros.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      subst.\n      unfold mgv_deghost_packet. auto.\n    - eapply commit_invariant_append_entries; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_append_entries; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_append_entries_reply', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_append_entries_reply; eauto.\n    - eapply commit_invariant_append_entries_reply; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_append_entries_reply; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_request_vote :\n    msg_refined_raft_net_invariant_request_vote' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_request_vote', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_request_vote; eauto.\n    - eapply commit_invariant_request_vote; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_request_vote; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_request_vote_reply', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_request_vote_reply; eauto.\n    - eapply commit_invariant_request_vote_reply; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_request_vote_reply; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_do_leader :\n    msg_refined_raft_net_invariant_do_leader' everything.\n  Proof using rmri miaei lalcii smspi si rri. \n    unfold msg_refined_raft_net_invariant_do_leader', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_do_leader; eauto.\n    - eapply commit_invariant_do_leader; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_do_leader; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_do_generic_server', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_do_generic_server; eauto.\n    - eapply commit_invariant_do_generic_server; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_do_generic_server; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma directly_committed_state_same :\n    forall net net' e,\n      (forall h, nwState net' h = nwState net h) ->\n      directly_committed net e ->\n      directly_committed net' e.\n  Proof using. \n    unfold directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_state_same :\n    forall (net net' : ghost_log_network) e t,\n      (forall h, nwState net' h = nwState net h) ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intuition.\n    destruct net, net'.\n    simpl in *.\n    eapply lifted_committed_ext'; eauto.\n  Qed.\n\n  Lemma exists_in_mgv_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)) (net : ghost_log_network),\n      In p (nwPackets (mgv_deghost net)) ->\n      exists q,\n        In q (nwPackets net) /\\\n        pDst q = pDst p /\\\n        pSrc q = pSrc p /\\\n        snd (pBody q) = pBody p.\n  Proof using. \n    unfold mgv_deghost.\n    simpl.\n    intros.\n    do_in_map.\n    subst. simpl.\n    eauto.\n  Qed.\n\n  Lemma state_machine_safety'_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset\n      (fun net : ghost_log_network =>  state_machine_safety' (mgv_deghost net)).\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, state_machine_safety'.\n    intuition.\n    - unfold state_machine_safety_host' in *. intuition.\n      repeat find_apply_lem_hyp committed_lifted_committed.\n      eauto 6 using lifted_committed_committed, lifted_committed_state_same.\n    - unfold state_machine_safety_nw' in *. intuition.\n\n      find_apply_lem_hyp exists_in_mgv_deghost_packet. break_exists. break_and.\n      find_apply_hyp_hyp.\n      find_apply_lem_hyp in_mgv_ghost_packet.\n      match goal with\n      | [ H : context [ pBody ] |- _ ] =>\n        eapply H; eauto\n      end.\n      + rewrite pBody_mgv_deghost_packet. repeat find_rewrite. eauto.\n      + apply lifted_committed_committed.\n        eapply lifted_committed_state_same; eauto using committed_lifted_committed.\n  Qed.\n\n  Lemma CRC_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset\n      (fun net : ghost_log_network => commit_recorded_committed (mgv_deghost net)).\n  Proof using rri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, commit_recorded_committed,\n           commit_recorded, committed, directly_committed.\n    intros.\n    specialize (H1 h e).\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp.\n    break_exists_exists.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat rewrite msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_apply_hyp_hyp.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat rewrite msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    auto.\n  Qed.\n\n  Lemma everything_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_state_same_packet_subset; eauto.\n    - eapply commit_invariant_state_same_packet_subset; eauto.\n    - apply state_machine_safety_deghost.\n      + eapply CRC_state_same_packet_subset; eauto.\n        apply commit_invariant_lower_commit_recorded_committed; auto.\n\n      + eapply state_machine_safety'_state_same_packet_subset; eauto.\n        auto using state_machine_safety'_invariant, msg_simulation_1.\n  Qed.\n\n  Lemma everything_reboot :\n    msg_refined_raft_net_invariant_reboot' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_reboot', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_reboot; eauto.\n    - eapply commit_invariant_reboot; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_reboot; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Theorem everything_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      everything net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply msg_refined_raft_net_invariant'; auto.\n    - apply everything_init.\n    - apply everything_client_request.\n    - apply everything_timeout.\n    - apply everything_append_entries.\n    - apply everything_append_entries_reply.\n    - apply everything_request_vote.\n    - apply everything_request_vote_reply.\n    - apply everything_do_leader.\n    - apply everything_do_generic_server.\n    - apply everything_state_same_packet_subset.\n    - apply everything_reboot.\n  Qed.\n\n  Theorem state_machine_safety_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      state_machine_safety net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply lower_prop; intros; auto.\n    apply msg_lower_prop with (P := fun net => _ (deghost net)); intros; auto.\n    find_apply_lem_hyp everything_invariant.\n    unfold everything in *. intuition.\n  Qed.\n\n  Theorem maxIndex_sanity_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      maxIndex_sanity net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply lower_prop; intros; eauto.\n    apply msg_lower_prop with (P := fun net => _ (deghost net)); intros; auto.\n    find_apply_lem_hyp everything_invariant.\n    unfold everything in *. intuition.\n    auto using maxIndex_sanity_lower.\n  Qed.\n\n  Theorem commit_recorded_committed_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      commit_recorded_committed net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply msg_lower_prop; intros; auto.\n    find_copy_apply_lem_hyp everything_invariant.\n    unfold everything in *.\n    intuition.\n    auto using commit_invariant_lower_commit_recorded_committed.\n  Qed.\n\n  Instance smsi : state_machine_safety_interface.\n  Proof.\n    split.\n    exact state_machine_safety_invariant.\n  Qed.\n\n  Instance misi : max_index_sanity_interface.\n  Proof.\n    split.\n    exact maxIndex_sanity_invariant.\n  Qed.\n\n  Instance crci : commit_recorded_committed_interface.\n  Proof.\n    split.\n    intros.\n    find_apply_lem_hyp commit_recorded_committed_invariant.\n    unfold commit_invariant, commit_recorded_committed, commit_recorded in *.\n    intros.\n    find_rewrite_lem (deghost_spec net h).\n    intuition;\n    repeat match goal with\n             | [ H : forall _, _, h : entry |- _ ] => specialize (H h)\n             | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n           end;\n    repeat find_rewrite_lem deghost_spec; auto.\n  Qed.\nEnd StateMachineSafetyProof.", "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/StateMachineSafetyProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.1667545340402121}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.omega.Omega.\n\nRequire Import Monad.\nRequire Import StringUtility.\nRequire Import InvTactics.\nRequire Import FileSystem.\n\nModule SimpleFS : FileSystem with Definition path := string.\n\n  Definition path : Type := string.\n  Definition file_content : Type := bool.\n  Definition file : Type := unit.\n  Definition file_handle : Type := nat.\n  Definition metadata : Type := nat.\n\n  Record file_stat' : Type :=\n    mkStat { is_reg : bool;\n           is_dir : bool;\n           is_chr : bool;\n           is_blk : bool;\n           is_fifo : bool;\n           is_lnk : bool;\n           is_sock : bool\n           }.\n\n  Definition file_stat : Type := file_stat'.\n\n  Definition file_name : string := \"file\".\n\n  Definition fsContents (p : path) : option (list bool) :=\n    if strcmp p file_name then\n      Some (true :: nil)\n    else None.\n\n  Hint Unfold fsContents.\n    \n  Record file_system' : Type :=\n    mkFS { is_open : bool;\n           is_read : bool;\n           has_fd : bool;\n           the_stat : file_stat\n         }.\n\n  Definition file_system : Type := file_system'.\n\n  Definition init_file_stat : file_stat :=\n    mkStat true false false false false false false.\n  Definition initial_fs : file_system :=\n    mkFS false false false init_file_stat.\n\n  Record abstract_file_stat : Type :=\n    abs_stat { isReg : bool;\n               isDir : bool;\n               isChr : bool;\n               isBlk : bool;\n               isFifo : bool;\n               isLnk : bool;\n               isSock : bool\n             }.\n  \n  Record abstract_file_metainfo : Type :=\n    abs_file { p : path;\n               offset : nat;\n               stat : abstract_file_stat\n             }.\n\n  Definition abs_fstat (f : file_stat) : abstract_file_stat :=\n    abs_stat (is_reg f) (is_dir f) (is_chr f) (is_blk f)\n             (is_fifo f) (is_lnk f) (is_sock f).\n\n  Definition init_abs_fstat := abs_fstat init_file_stat.\n  \n  Definition contents (fs : file_system) := fsContents.\n  Definition streams (fs : file_system) :=\n    if is_open fs then tt::nil else nil.\n  Definition file_info (fs : file_system) (_ : file) :=\n    if is_open fs then\n      Some (abs_file file_name (if is_read fs then 1 else 0)\n                     init_abs_fstat)\n    else None.\n  Definition file_no (fs : file_system) (_ : file) :=\n    if (has_fd fs) then Some 1 else None.\n  \n  Definition FS ( A : Type ) := file_system -> (A * file_system).\n  Instance FS_Monad : Monad FS :=\n    { ret A x := fun fs => (x, fs) ;\n      bind A B f a := fun fs =>\n                    match a fs with\n                    | (b, fs') => f b fs'\n                    end }.\n  Definition get : FS file_system :=\n    fun fs => (fs, fs).\n\n  Hint Unfold contents.\n  Hint Unfold streams.\n  Hint Unfold file_info.\n  Hint Unfold file_no.\n\n  (*\n  Theorem abstract_file_system_spec : forall fs f,\n      forall afs, afs = abs_fs fs ->\n             (In f (streams afs) <-> file_info afs f <> None) /\\\n             (forall fi, file_info afs f = Some fi ->\n                    contents afs (p fi) <> None).\n  Proof.\n    intros. split; unfold abs_fs in H; subst; simpl.\n    - split; intros; destruct (is_open fs) eqn:Hopen;\n        destruct f; try intro; try solve by inversion;\n          simpl; auto.\n    - intros.\n      destruct (is_open fs); subst; inversion H;\n        simpl; intro; try solve by inversion.\n  Qed.\n   *)\n  \n  Definition fopen (p: path) (m : file_access_mode) : FS (option file) :=\n    fun fs => match m with\n           | wb => (None, fs)\n           | ab => (None, fs)\n           | rb => if strcmp p file_name then\n                    (Some tt, mkFS true (is_read fs) (has_fd fs) (the_stat fs))\n                  else (None, fs)\n           end.\n\n  Theorem fopen_spec : forall p m f fs fs',\n      fopen p m fs = (f, fs') ->\n      (m = rb -> contents fs p = None -> f = None) /\\\n      (m = wb \\/ m = ab ->\n       forall f', f = Some f' ->\n             contents fs' p <> None) /\\\n      (forall f', f = Some f' ->\n             In f' (streams fs')) /\\\n      (forall f', file_no fs f' = file_no fs' f') /\\\n      (forall f', f <> Some f' ->\n             file_info fs f' = file_info fs' f' /\\\n             In f' (streams fs) = In f' (streams fs')) /\\\n      (forall p', p <> p' \\/ m = rb ->\n             contents fs p' = contents fs' p').\n  Proof.\n    intros. repeat split.\n    - intros; subst.\n      unfold contents in H1. unfold fsContents in H1.\n      unfold fopen in H.\n      destruct (strcmp p0 file_name).\n      + try solve by inversion.\n      + inversion H; auto.\n    - intros. destruct H0; subst; simpl in *; try solve by inversion.\n    - intros. subst. destruct m; simpl in H; try solve by inversion.\n      destruct (strcmp p0 file_name); try solve by inversion.\n      inversion H. simpl. auto.\n    - intros. subst.\n      destruct m; simpl in H; \n        destruct (strcmp p0 file_name); inversion H; simpl; auto.\n    - subst.\n      destruct m; simpl in H; destruct (strcmp p0 file_name);\n        inversion H; subst; auto.\n      + simpl. destruct (is_open fs); destruct f'; contradiction.\n    - destruct f.\n      + destruct f; destruct f'. contradiction.\n      + destruct m; simpl in H; destruct (strcmp p0 file_name);\n          subst; inversion H; auto.\n  Qed.\n\n  Definition fileno (f : file) : FS (option file_handle) :=\n    fun fs => if (is_open fs) then\n             (Some 1, mkFS (is_open fs) (is_read fs) true (the_stat fs))\n           else (None, fs).\n\n  Theorem fileno_spec : forall f fs fs' fd,\n      fileno f fs = (fd, fs') ->\n      (In f (streams fs) ->\n       file_no fs' f = fd /\\\n       (file_no fs f <> None -> file_no fs f = fd)) /\\\n      (~ In f (streams fs) -> fd = None) /\\\n      (forall f', f' <> f ->\n             file_no fs' f <> file_no fs' f' /\\\n             file_no fs f' = file_no fs' f') /\\\n      (forall f', file_info fs f' = file_info fs' f') /\\\n      (forall f', In f' (streams fs) <-> In f' (streams fs')) /\\\n      (forall p', contents fs p' = contents fs' p').\n  Proof.\n    intros. unfold fileno in H.\n    destruct (is_open fs) eqn:Hopen.\n    - repeat split; subst; inversion H; subst; simpl; auto.\n      all: try (destruct f; destruct f'; contradiction).\n      all: autounfold; try rewrite Hopen; simpl; auto.\n      + destruct (has_fd fs); auto; contradiction.\n      + destruct f. intros. destruct H0. simpl. auto.\n    - repeat split; subst; inversion H; subst; simpl; auto.\n      all: try (destruct f; destruct f'; contradiction).\n      all: autounfold in *; rewrite Hopen in *;\n        destruct f; simpl in *; try solve by inversion.\n  Qed.\n\n  Definition fseek (f : file) (off : nat) (s : seek_set) : FS bool :=\n    fun fs => if negb (is_open fs) then\n             (false, fs)\n           else if (1 <=? off) then\n                  (true, mkFS true true (has_fd fs) (the_stat fs))\n                else match s with\n                     | SeekEnd => (true, mkFS true true (has_fd fs) (the_stat fs))\n                     | SeekSet => (true, mkFS true false (has_fd fs) (the_stat fs))\n                     | _ => (true, fs)\n                     end.\n  \n  Theorem fseek_spec : forall f off origin fs fs' b,\n      fseek f off origin fs = (b, fs') ->\n      (In f (streams fs) <-> b = true) /\\\n      (forall f', file_no fs f' = file_no fs' f') /\\\n      (forall f', f <> f' -> file_info fs f' = file_info fs' f') /\\\n      (forall fi,  file_info fs  f = Some fi  ->\n       forall fi', file_info fs' f = Some fi' ->\n       forall s, contents fs (p fi) = Some s ->\n            offset fi' = min (length s) (expected_offset origin (offset fi) (length s) off)) /\\\n      (forall f', In f' (streams fs) <-> In f' (streams fs')) /\\\n      (forall p', contents fs p' = contents fs' p').\n  Proof.\n    intros.\n    destruct off; unfold fseek in H;\n      destruct (is_open fs) eqn:Hopen; simpl in H; inversion H; subst;\n        destruct origin eqn:Horigin; repeat split.\n    all: try intros; inversion H; subst; auto.\n    all: autounfold in *; rewrite Hopen in *.\n    all: try (destruct f).\n    all: try (destruct f').\n    all: simpl in *; auto; try contradiction.\n    all: try\n           (match goal with\n              [ H : fsContents ?pi = Some ?s |- _ ] => \n              autounfold in H; destruct (strcmp pi file_name); inversion H end).\n    all: try inversion H0; simpl; auto.\n    all: try inversion H1; simpl; auto.\n    all: try inversion H2; simpl; auto.\n    - destruct (is_read fs'); simpl; auto.\n    - destruct (is_read fs); simpl; auto.\n  Qed.\n\n  Definition fread (f : file) (size : nat) (count : nat) : FS (list (list bool) * nat) :=\n    fun fs => if (beq_nat size 0) then\n             ((nil, 0), fs)\n           else if (beq_nat count 0) then\n                  ((nil, 0), fs)\n                else if (is_open fs) then\n                       if (is_read fs) then\n                         ((nil, 0), fs)\n                       else\n                         (((true::nil)::nil, if (beq_nat size 1) then 1 else 0),\n                          mkFS true true (has_fd fs) (the_stat fs))\n                     else ((nil, 0), fs).\n\n  Theorem fread_spec : forall f size count fs fs' buf r,\n      fread f size count fs = ((buf, r), fs') ->\n      (r <= count) /\\\n      (length (filter (fun b => beq_nat (length b) size) buf) = r) /\\\n      (~ In f (streams fs) -> buf = nil /\\ r = 0) /\\\n      (forall f', file_no fs f' = file_no fs' f') /\\\n      (forall f', f <> f' ->\n             file_info fs f' = file_info fs' f') /\\\n      (forall l, l = fold_left (fun x y => x + length y) buf 0 ->\n       forall fi,  file_info fs  f = Some fi  ->\n       forall fi', file_info fs' f = Some fi' ->\n       forall s, contents fs (p fi) = Some s ->\n            l <= (length s - offset fi) /\\ offset fi' = offset fi + l) /\\\n      (forall f', In f' (streams fs) <-> In f' (streams fs')) /\\\n      (forall p', contents fs p' = contents fs' p').\n  Proof.\n    intros. repeat split.\n    all: try match goal with\n               [ H : fread _ _ _ _ = _ |- _ ] =>\n               unfold fread in H;\n                 destruct (beq_nat size 0) eqn:Hsize;\n                 destruct (beq_nat count 0) eqn:Hcount;\n                 destruct (is_open fs) eqn:Hopen;\n                 destruct (is_read fs) eqn:Hread; \n                 try solve [inversion H; omega];\n                 try solve [inversion H; simpl; auto];\n                 try solve [destruct (beq_nat size 1) eqn:Hsize';\n                            inversion H; try apply beq_nat_false in Hcount; omega]\n             end.\n    all: autounfold in *.\n    all: try (rewrite Hopen in *).\n    all: try (destruct f'; intros).\n    all: try solve [destruct f; destruct H0; simpl; auto].\n    all: try\n           (match goal with\n              [ H : fsContents ?pi = Some ?s |- _ ] => \n              autounfold in H; destruct (strcmp pi file_name); inversion H end).\n    all: try (inversion H1; simpl; rewrite Hread;\n              inversion H; subst; simpl; auto).\n    all: try simpl in H2.\n    all: try (rewrite Hopen in H2; rewrite Hread in H2).\n    all: try (inversion H2; simpl; auto).\n    all: try (inversion H).\n    all: simpl; auto.\n    - destruct size eqn:Hsize'; try solve by inversion.\n      simpl in H. destruct n; simpl in H; inversion H; simpl; auto.\n  Qed.\n\n  Definition fclose (f : file) : FS bool :=\n    fun fs => if (is_open fs) then\n             (true, mkFS false false (has_fd fs) (the_stat fs))\n           else (false, fs).\n\n  Theorem fclose_spec : forall f fs fs' b,\n      fclose f fs = (b, fs') ->\n      (~ In f (streams fs) -> b = false) /\\\n      ~ In f (streams fs') /\\\n      (forall f', file_no fs f' = file_no fs' f') /\\\n      (forall f', f <> f' ->\n             file_info fs f' = file_info fs' f' /\\\n             In f' (streams fs) = In f' (streams fs')) /\\\n      (forall p', contents fs p' = contents fs' p').\n  Proof.\n    intros. unfold fclose in H.\n    destruct (is_open fs) eqn:Hopen; inversion H; repeat split.\n    all: autounfold.\n    all: destruct f. \n    all: try rewrite Hopen; simpl; auto.\n    all: try (destruct f'; contradiction).\n    - intros. destruct H0. auto.\n    - subst. rewrite Hopen. auto.\n  Qed.\n\n  Definition fstat (fd : file_handle) (fs : file_system) : option file_stat :=\n    if (beq_nat fd 1) then\n      Some init_file_stat\n    else None.\n\n  Theorem fstat_spec : forall f fd fs st,\n      file_no fs f = Some fd ->\n      fstat fd fs = st ->\n      forall fi, file_info fs f = Some fi ->\n      forall st', st = Some st' ->\n      stat fi = abs_fstat st'.\n  Proof.\n    intros. autounfold in *.\n    destruct (beq_nat fd 1) eqn:Heq; subst.\n    all: unfold fstat in H2; rewrite Heq in H2; inversion H2.\n    subst. unfold abs_fstat. simpl in *.\n    destruct (is_open fs); destruct (has_fd fs);\n      try solve by inversion.\n    inversion H1. simpl. auto.\n  Qed.\n\n  Theorem is_reg_spec : forall st,\n      is_reg st = isReg (abs_fstat st).\n  Proof.\n    intros. reflexivity.\n  Qed.\n\n  Theorem is_dir_spec : forall st,\n      is_dir st = isDir (abs_fstat st).\n  Proof.\n    intros. reflexivity.\n  Qed.\n\nEnd SimpleFS.\n", "meta": {"author": "lastland", "repo": "WebSpec", "sha": "f4e956b06dfd82ff1b7673085acf1e8dcb2d1aa6", "save_path": "github-repos/coq/lastland-WebSpec", "path": "github-repos/coq/lastland-WebSpec/WebSpec-f4e956b06dfd82ff1b7673085acf1e8dcb2d1aa6/SimpleFileSystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16667350631478994}}
{"text": "(******************************************************************************)\n(** * Definition of the x86-TSO memory model *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection TSO.\n\nVariable G : execution.\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\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 \"'deps'\" := G.(deps).\nNotation \"'fre'\" := G.(fre).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'coe'\" := G.(coe).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'fri'\" := G.(fri).\nNotation \"'fr'\" := G.(fr).\nNotation \"'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 \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\n\nNotation \"'MFENCE'\" := (F \u2229\u2081 (fun a => is_true (is_sc lab a))).\n\n(******************************************************************************)\n(** ** Derived relations  *)\n(******************************************************************************)\n\nDefinition ppo := (\u2997RW\u2998 \u2a3e sb \u2a3e \u2997RW\u2998) \\ (fun x y => W x /\\ R y).\n\nDefinition fence := \u2997RW\u2998 \u2a3e sb \u2a3e \u2997MFENCE\u2998 \u2a3e sb \u2a3e \u2997RW\u2998.\n\nDefinition implied_fence := \u2997W\u2998 \u2a3e sb \u2a3e \u2997dom_rel rmw\u2998 \u222a \u2997codom_rel rmw\u2998 \u2a3e sb \u2a3e \u2997R\u2998.\n\nDefinition hb := ppo \u222a fence \u222a implied_fence \u222a rfe \u222a co \u222a fr.\n\n(******************************************************************************)\n(** ** Consistency *)\n(******************************************************************************)\n\nImplicit Type WF : Wf G.\nImplicit Type COMP : complete G.\nImplicit Type ATOM : rmw_atomicity G.\nImplicit Type SC_PER_LOC : sc_per_loc G.\n\nDefinition TSOConsistent :=\n  \u27ea WF : Wf G \u27eb /\\\n  \u27ea COMP : complete G \u27eb /\\\n  \u27ea SC_PER_LOC: sc_per_loc G \u27eb /\\\n  \u27ea ATOMICITY : rmw_atomicity G \u27eb /\\\n  \u27ea GHB : acyclic hb \u27eb.\n\nImplicit Type CON : TSOConsistent.\n\nLemma CON_WF CON : Wf G.\nProof using. apply CON. Qed.\n\n(******************************************************************************)\n(** ** Relations in graph *)\n(******************************************************************************)\n\nLemma wf_ppoE WF: ppo \u2261 \u2997E\u2998 \u2a3e ppo \u2a3e \u2997E\u2998.\nProof using.\nsplit; [|basic_solver].\nunfold ppo.\nrewrite (@wf_sbE G) at 1.\nbasic_solver 42.\nQed.\n\nLemma wf_fenceE WF: fence \u2261 \u2997E\u2998 \u2a3e fence \u2a3e \u2997E\u2998.\nProof using.\nsplit; [|basic_solver].\nunfold fence.\nrewrite (@wf_sbE G) at 1 2.\nbasic_solver 42.\nQed.\n\nLemma wf_implied_fenceE WF: implied_fence \u2261 \u2997E\u2998 \u2a3e implied_fence \u2a3e \u2997E\u2998.\nProof using.\nsplit; [|basic_solver].\nunfold implied_fence.\nrewrite (@wf_sbE G) at 1 2.\nbasic_solver 42.\nQed.\n\n(******************************************************************************)\n(** ** Domains and codomains *)\n(******************************************************************************)\n\nLemma wf_hbD WF : hb \u2261 \u2997RW\u2998 \u2a3e hb \u2a3e \u2997RW\u2998.\nProof using.\nsplit; [|basic_solver].\napply dom_helper_3.\nunfold hb.\nunfold ppo, fence, implied_fence.\nrewrite (wf_rmwD WF) at 1 2.\nrewrite (wf_rfeD WF) at 1.\nrewrite (wf_coD WF) at 1.\nrewrite (wf_frD WF) at 1.\ngeneralize (R_ex_in_R lab).\nbasic_solver 42.\nQed.\n\n\nLemma wf_ct_hbD WF : hb\u207a \u2261 \u2997RW\u2998 \u2a3e hb\u207a \u2a3e \u2997RW\u2998.\nProof using.\nsplit; [|basic_solver].\napply dom_helper_3.\nrewrite (wf_hbD WF).\nrewrite inclusion_ct_seq_eqv_l.\nrewrite inclusion_ct_seq_eqv_r.\nbasic_solver.\nQed.\n\n(******************************************************************************)\n(** ** Properties  *)\n(******************************************************************************)\n\nLemma ppo_alt : ppo \u2261 \n  \u2997R\u2998 \u2a3e sb \u2a3e \u2997RW\u2998 \u222a \u2997W\u2998 \u2a3e sb \u2a3e \u2997W\u2998.\nProof using.\nunfold ppo.\nsplit.\nby apply inclusion_minus_l; basic_solver 12.\nby unfolder; ins; desf; splits; eauto 10; intro; type_solver.\nQed.\n\nLemma ppo_in_sb : ppo \u2286 sb. \nProof using.\nunfold ppo; basic_solver.\nQed.\n\nEnd TSO.\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/hardware/TSO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16667350434080141}}
{"text": "(*\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List\n     Lia\n     Program.Equality.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Tactics\n     Simulation\n     SyntacticallySafe\n\n     Theory.KeysTheory\n\n     ModelCheck.ModelCheck\n     ModelCheck.Commutation\n     ModelCheck.InvariantSearchLemmas\n     ModelCheck.ProtocolFunctions\n     ModelCheck.RealWorldStepLemmas\n     ModelCheck.SafeProtocol\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.UniverseInversionLemmas\n     ModelCheck.NoResends\n.\n\nFrom SPICY Require IdealWorld RealWorld.\nFrom Frap Require Export Invariant.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nImport Tacs Gen.\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nLtac eq1 :=\n  invert_base_equalities1\n  || match goal with\n    | [ H : List.In _ _ |- _ ] => unfold List.In in H; (* intuition idtac *) split_ors\n\n    | [ H : _ $+ (_,_) $? _ = Some ?UD |- _ ] =>\n      match type of UD with\n      | RealWorld.user_data _ =>\n        apply lookup_some_implies_in in H; (* unfold List.In in H; intuition idtac *) simpl in H\n      | _ => apply lookup_split in H; (* intuition idtac *) split_ors\n      end\n    | [ H : _ #+ (_,_) #? _ = Some ?UD |- _ ] =>\n      apply ChMaps.ChMap.lookup_split in H; (* intuition idtac *) split_ors\n\n    | [ H : _ = {| RealWorld.users := _ |} |- _ ]\n      => apply split_real_univ_fields in H; split_ex; subst\n    | [ |- RealWorld.protocol (RealWorld.adversary _) = RealWorld.Return _ ] =>\n      unfold RealWorld.protocol, RealWorld.adversary\n    | [ H : lameAdv _ ?adv |- RealWorld.protocol ?adv = _ ] => unfold lameAdv in H; eassumption\n\n    | [ H : RealWorld.users _ $? _ = Some _ |- _ ] => unfold RealWorld.users in H\n\n    | [ H : _ = RealWorld.mkUserData _ _ _ |- _ ] => inversion H; clear H\n\n    | [ H : Action _ = Action _ |- _ ] =>\n      injection H; subst\n    | [ H : RealWorld.Return _ = RealWorld.Return _ |- _ ] => apply invert_return in H\n\n    | [ H: RealWorld.SignedCiphertext _ = RealWorld.SignedCiphertext _ |- _ ] =>\n      injection H; subst\n    | [ H: RealWorld.SigCipher _ _ _ _ = RealWorld.SigCipher _ _ _ _ |- _ ] =>\n      injection H; subst\n    | [ H: RealWorld.SigEncCipher _ _ _ _ _ = RealWorld.SigEncCipher _ _ _ _ _ |- _ ] =>\n      injection H; subst\n    | [ H : _ = RealWorld.Output _ _ _ _ |- _ ] => apply output_act_eq_inv in H; split_ex; subst\n    | [ H : RealWorld.Output _ _ _ _ = _ |- _ ] => apply output_act_eq_inv in H; split_ex; subst\n    | [ H : _ = RealWorld.Input _ _ _ |- _ ] => apply input_act_eq_inv in H; split_ex; subst\n    | [ H : RealWorld.Input _ _ _ = _ |- _ ] => apply input_act_eq_inv in H; split_ex; subst\n    | [ H : MkCryptoKey _ _ _ = _ |- _ ] => apply key_eq_inv in H; split_ex; subst\n\n    | [ H: _ = {| IdealWorld.read := _ |} |- _ ] => injection H\n    | [ H: {| IdealWorld.read := _ |} = _ |- _ ] => injection H\n\n    | [ H : keyId _ = _ |- _] => inversion H; clear H\n\n    | [ H : realServer 0 _ _ = _ |- _ ] => rewrite realserver_done in H\n    | [ H : realServer _ _ _ = _ |- _ ] => erewrite unroll_realserver_step in H by reflexivity\n    end.\n\nLtac ch := (repeat equality1); subst; rw_step1.\n(* Ltac ch := (repeat equality1); subst; rw_step1. *)\nLtac chu := repeat ch.\n\nLtac process_map_in_H H :=\n  repeat ( (rewrite add_eq_o in H by trivial)           \n         || (rewrite add_neq_o in H by congruence)\n         || (rewrite lookup_empty_none in H) )\n  ; repeat\n      match goal with\n      | [ H : Some _ = Some _ |- _ ] => apply some_eq_inv in H; subst\n      | [ H : None = Some _ |- _ ] => discriminate H\n      end.\n\nLtac finish_honest_cmds_safe1 :=\n    (* (progress solve_concrete_perm_merges) || *)\n    match goal with\n    (* from solve_concrete_perm_merges *)\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\n    | [ H : _ = {| RealWorld.users := _;\n                   RealWorld.adversary := _;\n                   RealWorld.all_ciphers := _;\n                   RealWorld.all_keys := _ |} |- _ ] => \n      time ( let to := type of H in idtac \"Universe Invert: \" to; 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 = Some ?ud |- context [ ?id2 ] ] =>\n      match type of ud with\n      | RealWorld.user_data _ =>\n        is_var id2; destruct (id1 ==n id2); subst\n        ; process_map_in_H H\n        (* ; repeat ( discriminate H *)\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) ) *)\n        (* clean_map_lookups *)\n      end\n    | [ H : nextAction (RealWorld.protocol _) _ |- _ ] =>\n      unfold RealWorld.protocol in H\n    | [ H : nextAction (realServer 0 _ _) _ |- _ ] =>\n      rewrite realserver_done in H\n    | [ H : nextAction (realServer _ _ _) _ |- _ ] =>\n      erewrite unroll_realserver_step in H by reflexivity\n    | [ H : nextAction _ _ |- _ ] =>\n      apply invert_na in H; cbn in H; destruct H; subst; invert_base_equalities1; subst\n    | [ H : mkKeys _ $? _ = _ |- _ ] => unfold mkKeys in H; simpl in H\n    | [ |- context [ RealWorld.findUserKeys _ ] ] =>\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty by eauto\n    | [ H : RealWorld.findKeysMessage _ $? _ = _ |- _ ] =>\n      unfold RealWorld.findKeysMessage in H; simpl in H\n    | [ |- (_ -> _) ] => intros\n    | [ H : _ $+ (?id1,_) $? ?id2 = _ |- context [ _ $? ?id2 ] ] =>\n      progress (process_map_in_H H)\n      (* ( progress ( *)\n      (*       repeat ( *)\n      (*           (rewrite add_neq_o in H by congruence) *)\n      (*           || (rewrite add_eq_o in H by trivial) *)\n      (*           || (rewrite lookup_empty_none in H) *)\n      (* ))) *)\n      || (is_var id2; destruct (id1 ==n id2); subst; process_map_in_H H)\n      (* || (let to := type of H in idtac \"Map inverting :\" to; is_var id2; destruct (id1 ==n id2); subst; clean_map_lookups) *)\n    | [ |- context [ _ $+ (_,_) $? _ ] ] =>\n      (* ( progress clean_map_lookups ) *)\n      ( progress (\n          repeat (\n              (rewrite add_eq_o by trivial)\n              (* || (rewrite add_neq_o by solve_simple_ineq) *)\n              || (rewrite add_neq_o by congruence)\n              || (rewrite lookup_empty_none)\n        )))\n               \n    | [ H : _ $k++ _ $? ?k = Some _ |- context [ _ $? ?k ]] => (*  *)\n        apply merge_perms_split in H; destruct H\n    | [ |- context [ _ $k++ _ $? _ ] ] => rewrite !lookup_in_merge_perm\n    | [ |- RealWorld.msg_pattern_safe _ _ ] => econstructor\n    | [ |- RealWorld.honest_key _ _ ] => econstructor\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 _ ?lst ] =>\n      match lst with\n      | context [OrderedTypeEx.Nat_as_OT.compare ?x ?x] =>\n        let EQ := fresh \"EQ\" in\n        let RW := fresh \"RW\"\n        in pose proof (@OTF.elim_compare_eq x x eq_refl) as EQ; destruct EQ as [EQ RW]\n           ; rewrite RW\n           ; progress vm_compute\n      | _ =>  progress vm_compute\n      end\n    | [ |- ~ (_ \\/ _) ] => unfold not; intros; split_ors; subst; try contradiction\n    | [ H : context [ _ \\/ False ] |- False ] =>\n      destruct H; try contradiction\n    | [ H : (_,_) = (_,_) |- _ ] => invert H\n    end.\n\nLtac finish_honest_cmds_safe :=\n  repeat (finish_honest_cmds_safe1 || (progress simplify_terms) (* ; simpl; cbn *)).\n\nDefinition safety_inv :=\n  fun t__hon t__adv st => @safety t__hon t__adv st /\\ alignment st /\\ @returns_align t__hon t__adv st.\n\nDefinition noresends_inv :=\n  fun t__hon t__adv st => no_resends_U (fst (fst st)) /\\ alignment st /\\ @returns_align t__hon t__adv st.\n\n#[export] Hint Opaque safety_inv : core.\n\nDefinition can_con_map {V} (m : Map.t V) : Map.t V.\n  let m' := eval simpl in (fold (fun k v acc => acc $+ (k, v)) m $0)\n    in apply m'.\nDefined.\n\nLemma can_con_map_correct : forall {V} (m : Map.t V),\n    can_con_map m = m.\nProof.\n  induction m using P.map_induction_bis; intros; Equal_eq; eauto.\n  unfold can_con_map.\n  rewrite fold_add; eauto.\n  fold (can_con_map m).\n  rewrite IHm; trivial.\n  Morphisms.solve_proper.\n  unfold transpose_neqkey; intros.\n  maps_equal.\nQed.\n\nLtac ccm m H :=\n  replace m with (can_con_map m) in H by apply can_con_map_correct\n  ; try match goal with\n        | [ H : context [ can_con_map ?cm ] |- _ ] =>\n          (unfold can_con_map,fold in H; simpl in H)\n        end.\n\nLtac ccmag m :=\n  replace m with (can_con_map m) by apply can_con_map_correct\n  ; match goal with\n    | [ |- context [ can_con_map ?cm ] ] =>\n      (unfold can_con_map,fold); simpl\n    end.\n\nLtac rwuf :=\n  unfold RealWorld.buildUniverse, RealWorld.build_data_step\n  , RealWorld.key_heap, RealWorld.msg_heap, RealWorld.c_heap\n  , RealWorld.from_nons, RealWorld.sent_nons, RealWorld.cur_nonce\n  , RealWorld.protocol, RealWorld.all_keys, RealWorld.all_ciphers\n  , RealWorld.users, RealWorld.adversary\n  in *.\n\nTactic Notation \"canonicalize\" \"ideal\" \"goal\" :=\n  rwuf\n  ; match goal with\n    | [ |- context [{| IdealWorld.users := ?usrs |}]] => ccmag usrs\n    end.\n\nLtac idealUnivSilentStep' uid :=\n  eapply IdealWorld.LStepUser with (u_id := uid)\n  ; simpl\n  ; [ solve [ simple_clean_maps; trivial ]\n    | solve [ idealUserSilentStep ]\n    ].\n\nLtac step_ideal1' uid :=\n  idtac \"stepping \" uid\n  ; eapply TrcFront\n  ; [ idealUnivSilentStep' uid |].\n\nLtac multistep_ideal' usrs :=\n  canonicalize ideal goal;\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\nLtac run_ideal_silent_steps_to_end' :=\n  canonicalize ideal goal;\n  match goal with\n  | [ |- istepSilent ^* {| IdealWorld.users := ?usrs |} ?U ] =>\n    is_evar U\n    ; multistep_ideal' usrs\n  end.\n\nLtac discharge_ideal_proto_equality :=\n  repeat\n    match goal with\n    | [ |- context [ IdealWorld.protocol _ = _ ] ] => unfold IdealWorld.protocol\n    | [ |- idealServer 0 _ _ = _ ] => rewrite idealserver_done\n    | [ |- idealServer _ _ _ = _ ] => erewrite unroll_idealserver_step by reflexivity\n    | [ |- _ = _ ] => reflexivity\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. *)\nLtac 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); rwuf; (* simpl in *; *) (repeat eq1) \n            ; subst\n            ; repeat simple apply conj\n            ; [ solve [ run_ideal_silent_steps_to_end' ]\n              | solve [ simpl; simple_clean_maps; trivial ]\n              | solve [ discharge_ideal_proto_equality ]\n              | reflexivity\n              ]\n      ))\n  end.\n\nLtac cleanup1 :=\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    || (rewrite add_neq_o in H by congruence)\n    || (destruct (k1 ==n k2); subst)\n  | [ H : Map.In ?k ?m -> False |- _ ] =>\n    change (Map.In k m -> False) with (~ Map.In k m) in H\n    ; rewrite F.not_find_in_iff in H\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 : (Some _ = None -> False) -> ?c |- _ ] =>\n    assert (c) by (apply H; intros; discriminate); clear H\n  | [ H : (Some _ <> None) -> ?c |- _ ] =>\n    assert (c) by (apply H; intros; discriminate); clear H\n  | [ H : context [ sharePerm _ _ ] |- _ ] => unfold sharePerm in H\n  | [ H : context [ $0 $? _ ] |- _ ] => rewrite lookup_empty_none in H\n  | [ H : $0 $? _ = None |- _ ] => clear H\n  | [ H : #0 #? _ = None |- _ ] => clear H\n  | [ H : context [ add_key_perm _ _ _ ] |- _ ] => unfold add_key_perm in H\n\n  | [ H : context [ (?uid,_) = (?x,_) \\/ False] |- _ ] =>\n    concrete uid; destruct H\n\n  | [ H : MessageEq.content_eq ?m _ _ |- _ ] =>\n    match type of m with\n    | RealWorld.message.message Nat => fail 2\n    | _ => unfold MessageEq.content_eq in H\n    end\n  | [ H : match ?acc with _ => _ end |- _ ] =>\n    match type of acc with\n    | IdealWorld.IW_message.access => destruct acc\n    | _ => fail 1\n    end\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\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 : IdealWorld.message.Permission _ = _ |- _ ] => invert H\n  | [ H : context [ IdealWorld.addMsg _ _ _ ] |- _ ] => unfold IdealWorld.addMsg 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++ _ $? _] |- _ ] => rewrite lookup_in_merge_perm 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; 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    || (rewrite add_neq_o in H by congruence)\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\n  | [ H : context [[] ++ _] |- _ ] => rewrite !app_nil_l in H\n  | [ H : context [_ ++ []] |- _ ] => rewrite !app_nil_r in H\n  end || discriminate || eq1.\n\nLtac print_nosilents :=\n  repeat\n    match goal with\n    | [ H : NoSilent ?uidA _ |- _ ] => idtac \"NoSilent ready for assert: \" uidA; fail\n    end.\n\nLtac 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; simple_clean_maps; try lia\n      | [ H : NoSilent ?uid _ |- ~ indexedRealStep ?uid _ _ _ ] =>\n        eapply NoSilent_no_indexed_silent_step\n        ; eauto 2\n      end.\n\nLtac 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\nLtac solve_all_users_no_silent :=\n  repeat\n    lazymatch goal with\n    | [ |- _ -> _ ] => intros\n    | [ |- ~ indexedRealStep ?uid _ _ _ ] => eapply all_users_NoSilent_no_indexed_silent_step\n    | [ H : RealWorld.users _ $? _ = Some _ |- _ ] => unfold RealWorld.users in H\n    | [ H : _ $+ (?conUid,_) $? ?uid = Some _ |- NoSilent ?uid _ ] =>\n      destruct (conUid ==n uid); subst; simple_clean_maps\n    | [ H : NoSilent ?uid _  |- NoSilent ?uid _ ] => exact H\n    end.\n\nLtac assert_no_silents U :=\n  let P := fresh \"P\"\n  in assert (forall uid U', ~ indexedRealStep uid Silent U U') as P by solve_all_users_no_silent\n.\n\nLtac getNextAction p :=\n  match p with\n  | RealWorld.Bind ?n _ => getNextAction n\n  | ?n                  => idtac n\n  end.\n\nLtac assertSilentStatus uid U p :=\n  let rec assertSilentStatus' pr :=\n      lazymatch pr with\n      | RealWorld.Bind ?n _ => assertSilentStatus' n\n      | RealWorld.Send _ _  => assert (NoSilent uid U) by (econstructor; unfold not; intros; rstep)\n      | RealWorld.Recv _    => assert (NoSilent uid U) by (econstructor; unfold not; intros; rstep)\n      | ?n                  => assert (exists U', indexedRealStep uid Silent U U') by solve_indexedRealStep\n      end\n  in lazymatch p with\n     | RealWorld.Return _  => assert (NoSilent uid U) by (econstructor; unfold not; intros; rstep)\n     | _                   => assertSilentStatus' p\n     end.\n\nLtac find_silent_step 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      ; lazymatch type of MAX with\n        | _ = Some (?uid,?u) =>\n          match goal with\n          | [ H : NoSilent uid U |- _ ] => idtac \"already have it\"; find_silent_step U (us $- uid)\n          | _ => \n            let p := (eval cbn in u.(RealWorld.protocol))\n            in  assertSilentStatus uid U p\n                ; subst; split_ex\n                ; lazymatch goal with\n                  | [ H : NoSilent uid _ |- _ ] => find_silent_step U (us $- uid)\n                  | [ H : indexedRealStep uid Silent _ _ |- _ ] => assert_gt_pred U uid\n                  end\n          end\n        | _ => assert_no_silents U\n        end\n(* ; clear MAX *)\n.\n\nLtac solve_noresends :=\n  unfold NoResends.no_resends_U, fst, RealWorld.users\n  ; rewrite Forall_natmap_forall; intros\n  ; focus_user; simpl\n  ; unfold NoResends.no_resends\n  ; repeat\n      match goal with\n      | [ |- NoDup [] ] => apply NoDup_nil\n      | [ |- NoDup (_ :: _) ] => apply NoDup_cons\n      | [ |- ~ List.In _ _ ] =>\n        unfold not; simpl; intros; split_ors; repeat invert_base_equalities1; try contradiction\n      end\n  ; eauto.\n\nLtac finish_noresends_invariant :=\n  rwuf\n  ; try match goal with\n        | [ |- context [{| RealWorld.users := ?users |} ]] =>\n          ccmag users\n        end\n  ; unfold noresends_inv, safety, alignment, returns_align\n  ; repeat simple apply conj\n  ; [ solve_noresends\n    | trivial\n    | unfold labels_align; intros; rstep; subst; solve_labels_align\n    | try solve [ simpl; intros; find_step_or_solve' ]\n    ].\n\nLtac finish_invariant :=\n  rwuf\n  ; try match goal with\n    | [ |- context [{| RealWorld.users := ?users |} ]] =>\n      ccmag users\n    end\n  ; unfold safety_inv, safety, alignment, returns_align\n  ; repeat simple apply conj\n  ; [ finish_honest_cmds_safe; simple_clean_maps; eauto 8\n    | trivial\n    | unfold labels_align; intros; rstep; subst; solve_labels_align\n    | try solve [ simpl; intros; find_step_or_solve' ]\n    ].\n\nLtac prove_honest_heaps_sane :=\n  repeat\n    match goal with\n    | [ H : _ |- _ ] => clear H\n    end\n  ; unfold InvariantSearchLemmas.honest_heaps_sane\n  ; intros\n  ; match goal with\n    | [ USRS : _ $+ (_,_) $? _ = Some _ |- _ ] =>\n      repeat\n        match type of USRS with\n        | _ $+ (?uid1,_) $? ?uid2 = Some _ => destruct (uid1 ==n uid2); subst; simple_clean_maps\n        end\n    end\n  ; unfold RealWorld.c_heap, RealWorld.key_heap, List.In\n  ; split\n  ; intros\n  ; repeat\n      match goal with\n      | [ |- In ?kid2 _ ] =>\n        rewrite in_find_iff; unfold not; intros\n      | [ H : _ \\/ _ |- _ ] => destruct H\n      | [ H : _ $+ (?kid1,_) $? ?kid2 = None |- False ] =>\n        destruct (kid1 ==n kid2); subst; simple_clean_maps\n      | [ H : _ $k++ _ $? _ = Some _ |- False ] =>\n        apply KeysTheory.merge_perms_split in H; destruct H; solve_concrete_maps\n      end\n  ; trivial.\n\nLtac forward_nosilents :=\n  lazymatch goal with\n  | [ XX : NoSilent _ _ |- _ ] =>\n    match goal with\n    | [ H : honest_heaps_sane ?usrs ?cs ?gks -> propNoSilent _ _ |- _ ] =>\n      ( let HHS := fresh \"HHS\" in\n        assert (InvariantSearchLemmas.honest_heaps_sane usrs cs gks) as HHS by prove_honest_heaps_sane\n        ; apply H in HHS\n        ; clear H\n        ; repeat\n            match goal with\n            | [ NS : NoSilent ?uid _ |- _ ] =>\n              idtac \"asserting nosilent \" uid\n              ; generalize (HHS _ NS)\n              ; clear NS\n            end\n        ; clear HHS\n        ; intros\n      ) || fail 3\n    end\n  | [ H : honest_heaps_sane _ _ _ ->  _ |- _ ] =>\n    clear H\n  | _ => idtac\n  end.\n  (* try  *)\n  (*   match goal with *)\n  (*   | [ PROPNS : propNoSilent _ _ |- _ ] => *)\n  (*     repeat  *)\n  (*       match goal with *)\n  (*       | [ NS : NoSilent ?uid _ |- _ ] => *)\n  (*         idtac \"asserting nosilent \" uid *)\n  (*         ; generalize (PROPNS _ NS) *)\n  (*         ; clear NS *)\n  (*       end *)\n  (*     ; clear PROPNS *)\n  (*     ; intros *)\n  (*   end. *)\n\nLtac clear_nosilents :=\n  idtac \"Clearing NoSilents\"\n  ; repeat\n      match goal with\n      | [ H : NoSilent _ _ |- _ ] => clear H\n      | [ H : propNoSilent _ _ |- _ ] => clear H\n      | [ H : honest_heaps_sane _ _ _ ->  _ |- _ ] => clear H\n      end.\n\nLtac invSS1 :=\n  discriminate\n  || match goal with\n    | [ STEP : (stepSS (t__adv := _)) ^* (?U,_,_) _\n      , IRS : indexedRealStep ?uid Silent ?U ?RU\n      , P : (forall _ _, _ > ?uid -> _)\n        |- _ ] =>\n\n      ( let PROOF := fresh \"PROOF\" in \n        pose proof (InvariantSearchLemmas.ssteps_inv_silent STEP eq_refl IRS P) as PROOF\n        ; clear STEP IRS P RU\n        ; unfold RealWorld.users, RealWorld.all_ciphers, RealWorld.all_keys in PROOF\n        ; split_ex\n        ; clear_nosilents\n        (* ; forward_nosilents *)\n        ; idtac \"Found silents\"\n      ) || fail 1\n\n    | [ H : action_matches _ _ _ _ |- _] => invert H\n    | [H : indexedRealStep _ _ _ _ |- _ ] =>\n      invert H\n    | [H : RealWorld.step_universe _ ?u _ _ |- _] =>\n      concrete u; chu\n    | [H : RealWorld.step_user _ None _ _ |- _] =>\n      invert H\n    | [H : RealWorld.step_user _ _ ?u _ |- _] =>\n      concrete u; chu\n    | [ H : indexedIdealStep _ _ _ _ |- _ ] => istep (* run _after_ real steps *)\n\n    | [ STEP : (stepSS (t__adv := _)) ^* (?ru,?iu,?b) _\n      , P : (forall _ _, ~ indexedRealStep _ Silent _  _)\n        |- _ ] =>\n\n      progress ( unfold not in P )\n\n    | [ STEP : (stepSS (t__adv := _)) ^* (?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          let PROOF := fresh \"PROOF\" in\n          pose proof (ssteps_inv_labeled P STEP LA eq_refl) as PROOF\n          ; clear STEP P LA\n          ; clear_nosilents\n          ; destruct PROOF\n          ; split_ex\n          ; subst\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 (t__adv := _)) ^* ?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 (t__adv := _)) ^* (?U,_,_) _ |- _ ] =>\n\n      match U with\n      | {| RealWorld.users := ?usrs |} =>\n        match usrs with\n        | context [ {| RealWorld.protocol := realServer 0 _ _ |} ] =>\n          idtac \"rewriting server done\"; rewrite realserver_done in H\n        | context [ {| RealWorld.protocol := realServer _ _ _ |} ] =>\n          idtac \"unrolling server\"; erewrite unroll_realserver_step in H by reflexivity\n        | _ =>\n          idtac \"finding silent steps...\"\n          (* ; forward_nosilents *)\n          ; find_silent_step U usrs\n          ; clear_nosilents\n        end\n      end\n\n    | [ H : forall _ _ _, _ -> _ -> _ -> _ <-> _ |- _ ] => clear H\n    | [ H : forall _ _ _ _, _ -> _ -> _ -> _ -> _ <-> _ |- _ ] => clear H\n    | [ H : (forall _ _ _, indexedRealStep _ _ ?ru _ ->\n                      exists _ _ _, (indexedIdealStep _ _) ^* ?iu _ /\\ _) |- _ ] =>\n      clear H\n\n    | [ |- safety_inv (?ru,_,_) ] =>\n      concrete ru; clear_nosilents; solve [ finish_invariant ]\n\n    | [ |- noresends_inv (?ru,_,_) ] =>\n      concrete ru; clear_nosilents; solve [ finish_noresends_invariant ]\n\n    | [ H : _ \\/ _ |- _ ] => destruct H; split_ex; subst\n    end.\n\nTactic Notation \"canonicalize\" \"context\" :=\n  rwuf\n  ; try\n      match goal with\n      | [ H : stepSS (?ru,?iu,_) _ |- _ ] =>\n        match ru with\n        | context [{| RealWorld.users := ?usrs |}] =>\n          ccm usrs H\n        end\n        ; match iu with\n          | context [{| IdealWorld.users := ?usrs |}] => \n            ccm usrs H\n          end\n      | [ H : (stepSS (t__adv:=_)) ^* (?ru,?iu,_) _ |- _ ] =>\n        match ru with\n        | context [{| RealWorld.users := ?usrs |}] =>\n          ccm usrs H\n        end\n        ; match iu with\n          | context [{| IdealWorld.users := ?usrs |}] => \n            ccm usrs H\n          end\n      end\n  ; try\n      match goal with\n      | [ H : _ -> propNoSilent _ ?ru |- _ ] =>\n        match ru with\n        | context [{| RealWorld.users := ?usrs |}] =>\n          ccm usrs H\n        end\n      end.\n\nLtac find_runtime :=\n  repeat \n    match goal with\n    | [ |- boundRunningTimeUniv (_ $+ (?usr,_)) _ ] =>\n      eapply BrtRecur with (uid := usr); eauto 2; simpl\n    | [ |- boundRunningTime _ _ ] => econstructor; eauto 2\n    | [ |- _ -> _ ] => intros\n    | [ |- boundRunningTimeUniv (_ $+ (?usr,_) $- _) _ ] =>\n      repeat \n        (rewrite map_add_remove_neq by congruence)\n      || (rewrite map_add_remove_eq by trivial)\n      || (rewrite remove_empty)\n    | [ |- boundRunningTimeUniv $0 _ ] => apply BrtEmpty\n    | [ |- queues_size _ = _ ] => unfold queues_size, fold; trivial\n    end.\n\nLemma findKeysMessage_getKey_compatible :\n  forall (m : RealWorld.message.message Access),\n  exists kp,\n    RealWorld.findKeysMessage m $? getKey m = Some kp.\nProof.\n  intros.\n  dependent destruction m.\n  unfold getKey; simpl.\n  destruct acc\n  ; simpl\n  ; eauto.\nQed.\n\nLemma findKeysMessage_getKey_verify_pr_compatible :\n  forall (m : bool * RealWorld.message.message Access),\n  exists kp, RealWorld.findKeysMessage (snd m) $? getKey (snd m) = Some kp.\nProof.\n  intros.\n  destruct m.\n  dependent destruction m; unfold getKey; simpl.\n  eauto.\nQed.\n\nLemma findKeysMessage_getKey_pr_compatible1 :\n  forall t (m : RealWorld.message.message (TPair Access t)),\n  exists kp,\n    RealWorld.findKeysMessage m $? getKey (RealWorld.message.msgFst m) = Some kp.\nProof.\n  intros.\n  induct m; simpl.\n  clear IHm1 IHm2.\n  pose proof (findKeysMessage_getKey_compatible m1); split_ex.\n  cases (RealWorld.findKeysMessage m2 $? getKey m1)\n  ; eexists\n  ; eauto.\nQed.\n\nLemma findKeysMessage_getKey_pr_compatible2 :\n  forall t (m : RealWorld.message.message (TPair t Access)),\n  exists kp,\n    RealWorld.findKeysMessage m $? getKey (RealWorld.message.msgSnd m) = Some kp.\nProof.\n  intros.\n  induct m; simpl.\n  clear IHm1 IHm2.\n  pose proof (findKeysMessage_getKey_compatible m2); split_ex.\n  cases (RealWorld.findKeysMessage m1 $? getKey m2)\n  ; eexists\n  ; eauto.\nQed.\n\nLtac typechecks1 :=\n  simple_clean_maps1\n  || match goal with\n    | [ |- syntactically_safe _ _ _ (RealWorld.Return _) _ ] =>\n      solve [ eapply SafeReturn; repeat typechecks1 ] || apply SafeReturnUntyped\n    | [ |- syntactically_safe _ _ _ _ _ ] =>\n      econstructor\n    | [ |- _ -> _ ] => intros\n    | [ H : RealWorld.findKeysMessage _ $? _ = Some _ |- _ ] => progress (simpl in H)\n    | [ H : _ $+ (?k1,_) $? ?k2 = Some _ |- _ ] =>\n      destruct (k1 ==n k2); subst\n    | [ H : _ $k++ _ $? _ = Some _ |- _ ] =>\n      apply merge_perms_split in H; split_ors\n    | [ |- HonestKey _ (fst ?k) ] => destruct k; simpl; eapply HonestPermission\n    | [ |- HonestKey _ (getKey (snd ?m)) ] => \n      pose proof (findKeysMessage_getKey_verify_pr_compatible m); split_ex\n      ; eapply HonestKeyFromMsgVerify with (v := m); eauto 2\n    | [ |- HonestKey _ (getKey (RealWorld.message.msgFst ?m)) ] => \n      pose proof (findKeysMessage_getKey_pr_compatible1 m); split_ex\n      ; eapply HonestFromMsg with (msg := m); eauto 2\n    | [ |- HonestKey _ (getKey (RealWorld.message.msgSnd ?m)) ] => \n      pose proof (findKeysMessage_getKey_pr_compatible2 m); split_ex\n      ; eapply HonestFromMsg with (msg := m); eauto 2\n    | [ |- HonestKey _ (getKey ?m) ] => \n      pose proof (findKeysMessage_getKey_compatible m); split_ex\n      ; eapply HonestFromMsg with (msg := m); eauto 2\n    | [ |- HonestKey _ _ ] => eapply HonestPermission\n    | [ |- HonestKey _ _ /\\ _ ] => split; trivial\n    | [ |- List.In _ _ ] => progress simpl\n    | [ |- _ \\/ _ ] => (left; reflexivity) || right\n    | [ |- List.In _ ?l ] => is_evar l; eauto 2\n    | [ |- _ <> _ ] => congruence\n    end.\n\nLtac verify_context_soundness :=\n  match goal with\n  | [ |- typingcontext_sound _ _ _ _ ] =>\n    unfold typingcontext_sound\n    ; repeat simple apply conj; intros; simpl\n  | [ H : HonestKey _ ?kid |- RealWorld.findUserKeys _ $? ?kid = Some true ] =>\n    unfold RealWorld.findUserKeys,fold; simpl; invert H\n  | [ H : List.In _ _ |- _ ] => simpl in H; split_ors; try contradiction\n  | [ H : {| cmd_type := _ |} = _ |- _ ] => apply safe_typ_eq in H; split_ex; subst; try discriminate\n  | [ H : JMeq.JMeq _ _ |- _ ] => invert H\n  | [ |- _ $k++ _ $? _ = Some true ] => KeysTheory.solve_perm_merges\n  end || invert_base_equalities1.\n\nLtac build_summary :=\n  repeat\n    match goal with\n    | [ |- _ $+ (?k1,_) $? ?k2 = Some _ ] => rewrite add_neq_o by congruence\n    | [ |- _ $? ?k2 = Some _ ] => rewrite add_eq_o by reflexivity\n    end.\n\n(* Ltac t := (repeat eq1); try invSS1. *)\n(* Ltac u := (repeat cleanup1); invSS1(* ; istep *); (repeat cleanup1). *)\nLtac do_trsys_step := invSS1; (repeat cleanup1); subst.\n\nLtac transition_system_step :=\n  rwuf; do_trsys_step; canonicalize context.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/src/ModelCheck/InvariantSearch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.566018549837479, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.16653113188416915}}
{"text": "Require Import syntax.\nRequire Import Metatheory.\n\nRequire Import List.\nRequire Import ListSet.\nRequire Import Bool.\nRequire Import Arith.\nRequire Import Compare_dec.\nRequire Import Omega.\nRequire Import monad.\nRequire Import Decidable.\nRequire Import alist.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Memory.\nRequire Import Kildall.\nRequire Import Lattice.\nRequire Import targetdata.\nRequire Import util.\n\nModule LLVMinfra.\n\nExport LLVMsyntax.\n\n(**********************************)\n(* Definition for basic types, which can be refined for extraction. *)\n\nDefinition id_dec : forall x y : id, {x=y} + {x<>y} := eq_atom_dec.\nDefinition l_dec : forall x y : l, {x=y} + {x<>y} := eq_atom_dec.\nDefinition inbounds_dec : forall x y : inbounds, {x=y} + {x<>y} := bool_dec.\nDefinition tailc_dec : forall x y : tailc, {x=y} + {x<>y} := bool_dec.\nDefinition noret_dec : forall x y : noret, {x=y} + {x<>y} := bool_dec.\n\n(**********************************)\n(* LabelSet. *)\n\n  Definition lempty_set := empty_set l.\n  Definition lset_add (l1:l) (ls2:ls) := set_add eq_dec l1 ls2.\n  Definition lset_union (ls1 ls2:ls) := set_union eq_dec ls1 ls2.\n  Definition lset_inter (ls1 ls2:ls) := set_inter eq_dec ls1 ls2.\n  Definition lset_eqb (ls1 ls2:ls) :=\n    match (lset_inter ls1 ls2) with\n    | nil => true\n    | _ => false\n    end.\n  Definition lset_neqb (ls1 ls2:ls) :=\n    match (lset_inter ls1 ls2) with\n    | nil => false\n    | _ => true\n    end.\n  Definition lset_eq (ls1 ls2:ls) := lset_eqb ls1 ls2 = true.\n  Definition lset_neq (ls1 ls2:ls) := lset_neqb ls1 ls2 = true.\n  Definition lset_single (l0:l) := lset_add l0 (lempty_set).\n  Definition lset_mem (l0:l) (ls0:ls) := set_mem eq_dec l0 ls0.\n\n(**********************************)\n(* Inversion. *)\n\n  Definition getCmdLoc (i:cmd) : id :=\n  match i with\n  | insn_bop id _ sz v1 v2 => id\n  | insn_fbop id _ _ _ _ => id\n  (* | insn_extractelement id typ0 id0 c1 => id *)\n  (* | insn_insertelement id typ0 id0 typ1 v1 c2 => id *)\n  | insn_extractvalue id typs id0 c1 _ => id\n  | insn_insertvalue id typs id0 typ1 v1 c2 => id\n  | insn_malloc id _ _ _ => id\n  | insn_free id _ _ => id\n  | insn_alloca id _ _ _ => id\n  | insn_load id typ1 v1 _ => id\n  | insn_store id typ1 v1 v2 _ => id\n  | insn_gep id _ _ _ _ _ => id\n  | insn_trunc id _ typ1 v1 typ2 => id\n  | insn_ext id _ sz1 v1 sz2 => id\n  | insn_cast id _ typ1 v1 typ2 => id\n  | insn_icmp id cond typ v1 v2 => id\n  | insn_fcmp id cond typ v1 v2 => id\n  | insn_select id v0 typ v1 v2 => id\n  | insn_call id _ _ _ _ v0 paraml => id\n  end.\n\n  Definition getTerminatorID (i:terminator) : id :=\n  match i with\n  | insn_return id t v => id\n  | insn_return_void id => id\n  | insn_br id v l1 l2 => id\n  | insn_br_uncond id l => id\n  (* | insn_switch id t v l _ => id *)\n  (* | insn_invoke id typ id0 paraml l1 l2 => id *)\n  | insn_unreachable id => id\n  end.\n\n  Definition getPhiNodeID (i:phinode) : id :=\n  match i with\n  | insn_phi id _ _ => id\n  end.\n\n  Definition getValueID (v:value) : option id :=\n  match v with\n  | value_id id => Some id\n  | value_const _ => None\n  end.\n\n  Definition getInsnLoc (i:insn) : id :=\n  match i with\n  | insn_phinode p => getPhiNodeID p\n  | insn_cmd c => getCmdLoc c\n  | insn_terminator t => getTerminatorID t\n  end.\n\n  Definition isPhiNodeB (i:insn) : bool :=\n  match i with\n  | insn_phinode p => true\n  | insn_cmd c => false\n  | insn_terminator t => false\n  end.\n\n  Definition isPhiNode (i:insn) : Prop :=\n  isPhiNodeB i = true.\n\n  Definition getCmdID (i:cmd) : option id :=\n  match i with\n  | insn_bop id _ sz v1 v2 => Some id\n  | insn_fbop id _ _ _ _ => Some id\n  (* | insn_extractelement id typ0 id0 c1 => id *)\n  (* | insn_insertelement id typ0 id0 typ1 v1 c2 => id *)\n  | insn_extractvalue id typs id0 c1 _ => Some id\n  | insn_insertvalue id typs id0 typ1 v1 c2 => Some id\n  | insn_malloc id _ _ _ => Some id\n  | insn_free id _ _ => None\n  | insn_alloca id _ _ _ => Some id\n  | insn_load id typ1 v1 _ => Some id\n  | insn_store id typ1 v1 v2 _ => None\n  | insn_gep id _ _ _ _ _ => Some id\n  | insn_trunc id _ typ1 v1 typ2 => Some id\n  | insn_ext id _ sz1 v1 sz2 => Some id\n  | insn_cast id _ typ1 v1 typ2 => Some id\n  | insn_icmp id cond typ v1 v2 => Some id\n  | insn_fcmp id cond typ v1 v2 => Some id\n  | insn_select id v0 typ v1 v2 => Some id\n  | insn_call id nr _ _ _ v0 paraml => if nr then None else Some id\n  end.\n\nFixpoint getCmdsIDs (cs:cmds) : list atom :=\nmatch cs with\n| nil => nil\n| c::cs' =>\n    match getCmdID c with\n    | Some id1 => id1::getCmdsIDs cs'\n    | None => getCmdsIDs cs'\n    end\nend.\n\nDefinition getPhiNodesIDs (ps:phinodes) : list atom :=\n  map getPhiNodeID ps.\n\nDefinition getStmtsIDs (st:stmts) : list atom :=\nlet '(stmts_intro ps cs _) := st in\ngetPhiNodesIDs ps ++ getCmdsIDs cs.\n\nFixpoint getArgsIDs (la:args) : list atom :=\nmatch la with\n| nil => nil\n| (_,id1)::la' => id1::getArgsIDs la'\nend.\n\nDefinition getArgsOfFdef (f:fdef) : args :=\nmatch f with\n| fdef_intro (fheader_intro _ _ _ la _) _ => la\nend.\n\nDefinition getArgsIDsOfFdef (f:fdef) : list atom :=\nmatch f with\n| fdef_intro (fheader_intro _ _ _ la _) _ => getArgsIDs la\nend.\n\nDefinition getInsnID (i:insn) : option id :=\nmatch i with\n| insn_phinode p => Some (getPhiNodeID p)\n| insn_cmd c => getCmdID c\n| insn_terminator t => None\nend.\n\nLemma getCmdLoc_getCmdID : forall a i0,\n  getCmdID a = Some i0 ->\n  getCmdLoc a = i0.\nProof.\n  intros a i0 H.\n  destruct_cmd a; inv H; auto.\n    simpl.\n    match goal with\n    | H1: context [if ?n then _ else _] |- _ =>\n      destruct n; inv H1; auto\n    end.\nQed.\n\nFixpoint mgetoffset_aux (TD:LLVMtd.TargetData) (t:typ) (idxs:list Z) (accum:Z)\n  : option (Z * typ) :=\n  match idxs with\n  | nil => Some (accum, t)\n  | idx::idxs' =>\n     match t with\n     | typ_array _ t' =>\n         match (LLVMtd.getTypeAllocSize TD t') with\n         | Some sz =>\n             mgetoffset_aux TD t' idxs' (accum + (Z_of_nat sz) * idx)\n         | _ => None\n         end\n     | typ_struct lt =>\n         match (LLVMtd.getStructElementOffset TD t (Coqlib.nat_of_Z idx))\n         with\n         | Some ofs =>\n             do t' <- nth_error lt (Coqlib.nat_of_Z idx);\n               mgetoffset_aux TD t' idxs' (accum + (Z_of_nat ofs))\n         | _ => None\n         end\n     | _ => None\n     end\n  end.\n\nDefinition mgetoffset (TD:LLVMtd.TargetData) (t:typ) (idxs:list Z)\n  : option (Z * typ) :=\n(*let (_, nts) := TD in\ndo ut <- Constant.typ2utyp nts t;*)\nmgetoffset_aux TD t idxs 0.\n\nFixpoint intConsts2Nats (TD:LLVMtd.TargetData) (lv:list const)\n  : option (list Z):=\nmatch lv with\n| nil => Some nil\n| (const_int sz0 n) :: lv' =>\n  if Size.dec sz0 Size.ThirtyTwo\n  then\n    match (intConsts2Nats TD lv') with\n    | Some ns => Some ((INTEGER.to_Z n)::ns)\n    | None => None\n    end\n  else None\n| _ => None\nend.\n\n(** Statically idx for struct must be int, and idx for arr can be\n    anything without checking bounds. *)\nFixpoint getSubTypFromConstIdxs (idxs : list const) (t : typ) : option typ :=\nmatch idxs with\n| nil => Some t\n| idx :: idxs' =>\n  match t with\n  | typ_array sz t' => getSubTypFromConstIdxs idxs' t'\n  | typ_struct lt =>\n    match idx with\n    | (const_int sz i) =>\n      match (nth_error lt (INTEGER.to_nat i)) with\n      | Some t' => getSubTypFromConstIdxs idxs' t'\n      | None => None\n      end\n    | _ => None\n    end\n  | _ => None\n  end\nend.\n\nDefinition getConstGEPTyp (idxs : list const) (t : typ) : option typ :=\nmatch (idxs, t) with\n| (idx :: idxs', typ_pointer t0)  =>\n     (* The input t is already an element of a pointer typ *)\n     match (getSubTypFromConstIdxs idxs' t0) with\n     | Some t' => Some (typ_pointer t')\n     | _ => None\n     end\n| _ => None\nend.\n\nFixpoint getSubTypFromValueIdxs\n  (idxs : list (sz * value)) (t : typ) : option typ :=\nmatch idxs with\n| nil => Some t\n| (_, idx) :: idxs' =>\n  match t with\n  | typ_array sz t' => getSubTypFromValueIdxs idxs' t'\n  | typ_struct lt =>\n    match idx with\n    | value_const (const_int sz i) =>\n      match (nth_error lt (INTEGER.to_nat i)) with\n      | Some t' => getSubTypFromValueIdxs idxs' t'\n      | None => None\n      end\n    | _ => None\n    end\n  | _ => None\n  end\nend.\n\nDefinition getGEPTyp (idxs : list (sz * value)) (t : typ) : option typ :=\nmatch idxs with\n| nil => None\n| (_, idx) :: idxs' =>\n     (* The input t is already an element of a pointer typ *)\n     match (getSubTypFromValueIdxs idxs' t) with\n     | Some t' => Some (typ_pointer t')\n     | _ => None\n     end\nend.\n\nDefinition getCmdTyp (i:cmd) : option typ :=\nmatch i with\n| insn_bop _ _ sz _ _ => Some (typ_int sz)\n| insn_fbop _ _ ft _ _ => Some (typ_floatpoint ft)\n(*\n| insn_extractelement _ typ _ _ => getElementTyp typ\n| insn_insertelement _ typ _ _ _ _ => typ *)\n| insn_extractvalue _ typ _ idxs typ' => Some typ'\n| insn_insertvalue _ typ _ _ _ _ => Some typ\n| insn_malloc _ typ _ _ => Some (typ_pointer typ)\n| insn_free _ typ _ => Some typ_void\n| insn_alloca _ typ _ _ => Some (typ_pointer typ)\n| insn_load _ typ _ _ => Some typ\n| insn_store _ _ _ _ _ => Some typ_void\n| insn_gep _ _ typ _ idxs typ' => Some (typ_pointer typ')\n| insn_trunc _ _ _ _ typ => Some typ\n| insn_ext _ _ _ _ typ2 => Some typ2\n| insn_cast _ _ _ _ typ => Some typ\n| insn_icmp _ _ _ _ _ => Some (typ_int Size.One)\n| insn_fcmp _ _ _ _ _ => Some (typ_int Size.One)\n| insn_select _ _ typ _ _ => Some typ\n| insn_call _ true _ _ _ _ _ => Some typ_void\n| insn_call _ false _ rt _ _ _ => Some rt\nend.\n\nDefinition getTerminatorTyp (i:terminator) : typ :=\nmatch i with\n| insn_return _ typ _ => typ\n| insn_return_void _ => typ_void\n| insn_br _ _ _ _ => typ_void\n| insn_br_uncond _ _ => typ_void\n(* | insn_switch _ typ _ _ _ => typ_void *)\n(* | insn_invoke _ typ _ _ _ _ => typ *)\n| insn_unreachable _ => typ_void\nend.\n\nDefinition getPhiNodeTyp (i:phinode) : typ :=\nmatch i with\n| insn_phi _ typ _ => typ\nend.\n\nDefinition getInsnTyp (i:insn) : option typ :=\nmatch i with\n| insn_phinode p => Some (getPhiNodeTyp p)\n| insn_cmd c => getCmdTyp c\n| insn_terminator t => Some (getTerminatorTyp t)\nend.\n\nDefinition getPointerEltTyp (t:typ) : option typ :=\nmatch t with\n| typ_pointer t' => Some t'\n| _ => None\nend.\n\nDefinition getValueIDs (v:value) : ids :=\nmatch (getValueID v) with\n| None => nil\n| Some id => id::nil\nend.\n\nFixpoint values2ids (vs:list value) : ids :=\nmatch vs with\n| nil => nil\n| value_id id::vs' => id::values2ids vs'\n| _::vs' => values2ids vs'\nend.\n\nDefinition getParamsOperand (lp:params) : ids :=\nlet '(_,vs) := split lp in values2ids vs.\n\nFixpoint list_prj1 (X Y:Type) (ls : list (X*Y)) : list X :=\nmatch ls with\n| nil => nil\n| (x, y)::ls' => x::list_prj1 X Y ls'\nend.\n\nFixpoint list_prj2 (X Y:Type) (ls : list (X*Y)) : list Y :=\nmatch ls with\n| nil => nil\n| (x, y)::ls' => y::list_prj2 X Y ls'\nend.\n\nDefinition getCmdOperands (i:cmd) : ids :=\nmatch i with\n| insn_bop _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_fbop _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n(* | insn_extractelement _ _ v _ => getValueIDs v\n| insn_insertelement _ _ v1 _ v2 _ => getValueIDs v1 ++ getValueIDs v2\n*)\n| insn_extractvalue _ _ v _ _ => getValueIDs v\n| insn_insertvalue _ _ v1 _ v2 _ => getValueIDs v1 ++ getValueIDs v2\n| insn_malloc _ _ v _ => getValueIDs v\n| insn_free _ _ v => getValueIDs v\n| insn_alloca _ _ v _ => getValueIDs v\n| insn_load _ _ v _ => getValueIDs v\n| insn_store _ _ v1 v2 _ => getValueIDs v1 ++ getValueIDs v2\n| insn_gep _ _ _ v vs _ =>\n    getValueIDs v ++ values2ids (map snd vs)\n| insn_trunc _ _ _ v _ => getValueIDs v\n| insn_ext _ _ _ v1 typ2 => getValueIDs v1\n| insn_cast _ _ _ v _ => getValueIDs v\n| insn_icmp _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_fcmp _ _ _ v1 v2 => getValueIDs v1 ++ getValueIDs v2\n| insn_select _ v0 _ v1 v2 => getValueIDs v0 ++ getValueIDs v1 ++ getValueIDs v2\n| insn_call _ _ _ _ _ v0 lp => getValueIDs v0 ++ getParamsOperand lp\nend.\n\nDefinition valueInListValue (v0:value) (vs:list (sz * value)) : Prop :=\nIn v0 (map snd vs).\n\nDefinition valueInParams (v0:value) (lp:params) : Prop :=\nlet '(_, vs) := split lp in In v0 vs.\n\nDefinition valueInCmdOperands (v0:value) (i:cmd) : Prop :=\nmatch i with\n| insn_bop _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_fbop _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_extractvalue _ _ v _ _ => v0 = v\n| insn_insertvalue _ _ v1 _ v2 _ => v0 = v1 \\/ v0 = v2\n| insn_malloc _ _ v _ => v0 = v\n| insn_free _ _ v => v0 = v\n| insn_alloca _ _ v _ => v0 = v\n| insn_load _ _ v _ => v0 = v\n| insn_store _ _ v1 v2 _ => v0 = v1 \\/ v0 = v2\n| insn_gep _ _ _ v vs _ => v0 = v \\/ valueInListValue v0 vs\n| insn_trunc _ _ _ v _ => v0 = v\n| insn_ext _ _ _ v1 _ => v0 = v1\n| insn_cast _ _ _ v _ => v0 = v\n| insn_icmp _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_fcmp _ _ _ v1 v2 => v0 = v1 \\/ v0 = v2\n| insn_select _ v1 _ v2 v3 => v0 = v1 \\/ v0 = v2 \\/ v0 = v3\n| insn_call _ _ _ _ _ v1 lp => v0 = v1 \\/ valueInParams v0 lp\nend.\n\nDefinition valueInTmnOperands (v0:value) (i:terminator) : Prop :=\nmatch i with\n| insn_return _ _ v => v = v0\n| insn_return_void _ => False\n| insn_br _ v _ _ => v = v0\n| insn_br_uncond _ _ => False\n| insn_unreachable _ => False\nend.\n\nDefinition valueInInsnOperands (v0:value) (instr:insn) : Prop :=\nmatch instr with\n| insn_phinode (insn_phi _ _ ls) =>\n    In v0 (list_prj1 _ _ ls)\n| insn_cmd c => valueInCmdOperands v0 c\n| insn_terminator tmn => valueInTmnOperands v0 tmn\nend.\n\nDefinition getTerminatorOperands (i:terminator) : ids :=\nmatch i with\n| insn_return _ _ v => getValueIDs v\n| insn_return_void _ => nil\n| insn_br _ v _ _ => getValueIDs v\n| insn_br_uncond _ _ => nil\n(* | insn_switch _ _ value _ _ => getValueIDs value *)\n(* | insn_invoke _ _ _ lp _ _ => getParamsOperand lp *)\n| insn_unreachable _ => nil\nend.\n\nDefinition getPhiNodeOperands (i:phinode) : ids :=\nmatch i with\n| insn_phi _ _ ls => values2ids (list_prj1 _ _ ls)\nend.\n\nDefinition getInsnOperands (i:insn) : ids :=\nmatch i with\n| insn_phinode p => getPhiNodeOperands p\n| insn_cmd c => getCmdOperands c\n| insn_terminator t => getTerminatorOperands t\nend.\n\nDefinition getCmdLabels (i:cmd) : ls :=\nmatch i with\n| insn_bop _ _ _ _ _ => nil\n| insn_fbop _ _ _ _ _ => nil\n(* | insn_extractelement _ _ _ _ => nil\n| insn_insertelement _ _ _ _ _ _ => nil\n*)\n| insn_extractvalue _ _ _ _ _ => nil\n| insn_insertvalue _ _ _ _ _ _ => nil\n| insn_malloc _ _ _ _ => nil\n| insn_free _ _ _ => nil\n| insn_alloca _ _ _ _ => nil\n| insn_load _ _ _ _ => nil\n| insn_store _ _ _ _ _ => nil\n| insn_gep _ _ _ v  _ _ => nil\n| insn_trunc _ _ _ _ _ => nil\n| insn_ext _ _ _ _ _ => nil\n| insn_cast _ _ _ _ _ => nil\n| insn_icmp _ _ _ _ _ => nil\n| insn_fcmp _ _ _ _ _ => nil\n| insn_select _ _ _ _ _ => nil\n| insn_call _ _ _ _ _ _ _ => nil\nend.\n\nDefinition getTerminatorLabels (i:terminator) : ls :=\nmatch i with\n| insn_return _ _ _ => nil\n| insn_return_void _ => nil\n| insn_br _ _ l1 l2 => l1::l2::nil\n| insn_br_uncond _ l => l::nil\n(* | insn_switch _ _ _ l ls => l::list_prj2 _ _ ls *)\n(* | insn_invoke _ _ _ _ l1 l2 => l1::l2::nil *)\n| insn_unreachable _ => nil\nend.\n\nDefinition getPhiNodeLabels (i:phinode) : ls :=\nmatch i with\n| insn_phi _ _ ls => list_prj2 _ _ ls\nend.\n\nDefinition getInsnLabels (i:insn) : ls :=\nmatch i with\n| insn_phinode p => getPhiNodeLabels p\n| insn_cmd c => getCmdLabels c\n| insn_terminator tmn => getTerminatorLabels tmn\nend.\n\nFixpoint args2Typs (la:args) : list typ :=\nmatch la with\n| nil => nil\n| (t, _, id)::la' => t :: (args2Typs la')\nend.\n\nDefinition getFheaderTyp (fh:fheader) : typ :=\nmatch fh with\n| fheader_intro _ t _ la va => typ_function t (args2Typs la) va\nend.\n\nDefinition getFdecTyp (fdec:fdec) : typ :=\nmatch fdec with\n| fdec_intro fheader _ => getFheaderTyp fheader\nend.\n\nDefinition getFdefTyp (fdef:fdef) : typ :=\nmatch fdef with\n| fdef_intro fheader _ => getFheaderTyp fheader\nend.\n\nDefinition fheaderOfFdef (fdef:fdef) : fheader :=\nmatch fdef with\n| fdef_intro fh _ => fh\nend.\n\nDefinition getBindingTyp (ib:id_binding) : option typ :=\nmatch ib with\n| id_binding_cmd i => getCmdTyp i\n| id_binding_terminator i => Some (getTerminatorTyp i)\n| id_binding_phinode i => Some (getPhiNodeTyp i)\n| id_binding_gvar (gvar_intro _ _ _ t _ _) => Some (typ_pointer t)\n| id_binding_gvar (gvar_external _ _ t) => Some (typ_pointer t)\n| id_binding_arg (t, _, id) => Some t\n| id_binding_fdec fdec => Some (getFdecTyp fdec)\n| id_binding_none => None\nend.\n\nDefinition getCmdsFromBlock (b:block) : cmds :=\nmatch b with\n| (_, stmts_intro _ li _) => li\n(* | block_without_label li => li *)\nend.\n\nDefinition getTerminatorFromBlock (b:block) : terminator :=\nmatch b with\n| (_, stmts_intro _ _ t) => t\n(* | block_without_label li => li *)\nend.\n\nDefinition getFheaderID (fh:fheader) : id :=\nmatch fh with\n| fheader_intro _ _ id _ _ => id\nend.\n\nDefinition getFdecID (fd:fdec) : id :=\nmatch fd with\n| fdec_intro fh _ => getFheaderID fh\nend.\n\nDefinition getFdefID (fd:fdef) : id :=\nmatch fd with\n| fdef_intro fh _ => getFheaderID fh\nend.\n\nFixpoint getLabelViaIDFromList\n  (ls: list (value * l)) (branch:id) : option l :=\nmatch ls with\n| nil => None\n| ((value_id id), l) :: ls' =>\n  match (eq_dec id branch) with\n  | left _ => Some l\n  | right _ => getLabelViaIDFromList ls' branch\n  end\n| (_, l) :: ls' => getLabelViaIDFromList ls' branch\nend.\n\nDefinition getLabelViaIDFromPhiNode (phi:phinode) (branch:id) : option l :=\nmatch phi with\n| insn_phi _ _ ls => getLabelViaIDFromList ls branch\nend.\n\nFixpoint getLabelsFromIdls (idls:list (value * l)) : ls :=\nmatch idls with\n| nil => lempty_set\n| (_, l) :: idls' => lset_add l (getLabelsFromIdls idls')\nend.\n\nDefinition getLabelsFromPhiNode (phi:phinode) : ls :=\nmatch phi with\n| insn_phi _ _ ls => getLabelsFromIdls ls\nend.\n\nFixpoint getLabelsFromPhiNodes (phis:list phinode) : ls :=\nmatch phis with\n| nil => lempty_set\n| phi::phis' => lset_union (getLabelsFromPhiNode phi) (getLabelsFromPhiNodes phis')\nend.\n\nDefinition getIDLabelsFromPhiNode p : list (value * l) :=\nmatch p with\n| insn_phi _ _ idls => idls\nend.\n\nFixpoint getLabelViaIDFromIDLabels idls id : option l :=\nmatch idls with\n| nil => None\n| (value_id id0, l0) :: idls' => if eq_dec id id0 then Some l0 else getLabelViaIDFromIDLabels idls' id\n| (_, l0) :: idls' => getLabelViaIDFromIDLabels idls' id\nend.\n\nDefinition _getLabelViaIDPhiNode p id : option l :=\nmatch p with\n| insn_phi _ _ ls => getLabelViaIDFromIDLabels ls id\nend.\n\nDefinition getLabelViaIDPhiNode (phi:insn) id : option l :=\nmatch phi with\n| insn_phinode p => _getLabelViaIDPhiNode p id\n| _ => None\nend.\n\nDefinition getReturnTyp fdef : typ :=\nmatch fdef with\n| fdef_intro (fheader_intro _ t _ _ _) _ => t\nend.\n\nDefinition getGvarID g : id :=\nmatch g with\n| gvar_intro id _ _ _ _ _ => id\n| gvar_external id _ _ => id\nend.\n\nDefinition getCalledValue i : option value :=\nmatch i with\n| insn_cmd (insn_call _ _ _ _ _ v0 _) => Some v0\n| _ => None\nend.\n\nDefinition getCalledValueID i : option id :=\nmatch getCalledValue i with\n| Some v => getValueID v\n| _ => None\nend.\n\nDefinition getCallerReturnID (Caller:cmd) : option id :=\nmatch Caller with\n(* | insn_invoke i _ _ _ _ _ => Some i *)\n| insn_call fid true _ _ _ _ _ => None\n| insn_call fid false _ _ _ _ _ => Some fid\n| _ => None\nend.\n\nFixpoint getValueViaLabelFromValuels (vls:list (value * l)) (l0:l) : option value :=\nmatch vls with\n| nil => None\n| (v, l1) :: vls'=>\n  if (eq_dec l1 l0)\n  then Some v\n  else getValueViaLabelFromValuels vls' l0\nend.\n\nDefinition getValueViaBlockFromValuels (vls:list (value * l)) (b:block) : option value :=\ngetValueViaLabelFromValuels vls (fst b).\n\nDefinition getValueViaBlockFromPHINode (i:phinode) (b:block) : option value :=\nmatch i with\n| insn_phi _ _ vls => getValueViaBlockFromValuels vls b\nend.\n\nDefinition getPHINodesFromBlock (b:block) : list phinode :=\nmatch b with\n| (_, stmts_intro lp _ _) => lp\nend.\n\nDefinition getEntryBlock (fd:fdef) : option block :=\nmatch fd with\n| fdef_intro _ (b::_) => Some b\n| _ => None\nend.\n\nDefinition getEntryLabel (f:fdef) : option l :=\nmatch f with\n| fdef_intro _ ((l0, _)::_) => Some l0\n| _ => None\nend.\n\nDefinition floating_point_order (fp1 fp2:floating_point) : bool :=\nmatch (fp1, fp2) with\n| (fp_float, fp_double) => true\n| (fp_float, fp_x86_fp80) => true\n| (fp_float, fp_ppc_fp128) => true\n| (fp_float, fp_fp128) => true\n| (fp_double, fp_x86_fp80) => true\n| (fp_double, fp_ppc_fp128) => true\n| (fp_double, fp_fp128) => true\n| (fp_x86_fp80, fp_ppc_fp128) => true\n| (fp_x86_fp80, fp_fp128) => true\n| (_, _) => false\nend.\n\nDefinition wf_fcond (fc : fcond) : bool :=\nmatch fc with\n| fcond_ord => false\n| fcond_uno => false\n| _ => true\nend.\n\n(**********************************)\n(* Lookup. *)\n\n(* ID binding lookup *)\n\nFixpoint lookupCmdViaIDFromCmds (li:cmds) (id0:id) : option cmd :=\nmatch li with\n| nil => None\n| i::li' =>\n    if (eq_atom_dec id0 (getCmdLoc i))\n    then Some i else lookupCmdViaIDFromCmds li' id0\nend.\n\nFixpoint lookupPhiNodeViaIDFromPhiNodes (li:phinodes) (id0:id)\n  : option phinode :=\nmatch li with\n| nil => None\n| i::li' =>\n    if (eq_dec (getPhiNodeID i) id0) then Some i\n    else lookupPhiNodeViaIDFromPhiNodes li' id0\nend.\n\nDefinition lookupInsnViaIDFromBlock (b:block) (id0:id) : option insn :=\nmatch b with\n| (_, stmts_intro ps cs t) =>\n  match (lookupPhiNodeViaIDFromPhiNodes ps id0) with\n  | None =>\n      match (lookupCmdViaIDFromCmds cs id0) with\n      | None => if (eq_dec (getTerminatorID t) id0)\n                then Some (insn_terminator t) else None\n      | Some c => Some (insn_cmd c)\n      end\n  | Some re => Some (insn_phinode re)\n  end\nend.\n\nFixpoint lookupInsnViaIDFromBlocks (lb:blocks) (id:id) : option insn :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (lookupInsnViaIDFromBlock b id) with\n  | None => lookupInsnViaIDFromBlocks lb' id\n  | re => re\n  end\nend.\n\nDefinition lookupInsnViaIDFromFdef (f:fdef) (id0:id) : option insn :=\nlet '(fdef_intro _ bs) := f in lookupInsnViaIDFromBlocks bs id0.\n\nFixpoint lookupArgViaIDFromArgs (la:args) (id0:id) : option arg :=\nmatch la with\n| nil => None\n| (t, attrs, id')::la' =>\n    if (eq_dec id' id0) then Some (t, attrs, id')\n    else lookupArgViaIDFromArgs la' id0\nend.\n\n(* Block lookup from ID *)\n\nFixpoint getCmdsLocs (cs:list cmd) : ids :=\nmatch cs with\n| nil => nil\n| c::cs' => getCmdLoc c::getCmdsLocs cs'\nend.\n\nDefinition getStmtsLocs (sts:stmts) : ids :=\nmatch sts with\n| (stmts_intro ps cs t) =>\n  getPhiNodesIDs ps++getCmdsLocs cs++(getTerminatorID t::nil)\nend.\n\nFixpoint lookupBlockViaIDFromBlocks (lb:blocks) (id1:id) : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (In_dec eq_dec id1 (getStmtsIDs (snd b))) with\n  | left _ => Some b\n  | right _ => lookupBlockViaIDFromBlocks lb' id1\n  end\nend.\n\nDefinition lookupBlockViaIDFromFdef (fd:fdef) (id:id) : option block :=\nmatch fd with\n| fdef_intro fh lb => lookupBlockViaIDFromBlocks lb id\nend.\n\n(* Fun lookup from ID *)\n\nDefinition lookupFdecViaIDFromProduct (p:product) (i:id) : option fdec :=\nmatch p with\n| (product_fdec fd) => if eq_dec (getFdecID fd) i then Some fd else None\n| _ => None\nend.\n\nFixpoint lookupFdecViaIDFromProducts (lp:products) (i:id) : option fdec :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupFdecViaIDFromProduct p i) with\n  | Some fd => Some fd\n  | None => lookupFdecViaIDFromProducts lp' i\n  end\nend.\n\nDefinition lookupFdecViaIDFromModule (m:module) (i:id) : option fdec :=\n  let (os, dts, ps) := m in\n  lookupFdecViaIDFromProducts ps i.\n\nFixpoint lookupFdecViaIDFromModules (lm:modules) (i:id) : option fdec :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupFdecViaIDFromModule m i) with\n  | Some fd => Some fd\n  | None => lookupFdecViaIDFromModules lm' i\n  end\nend.\n\nDefinition lookupFdecViaIDFromSystem (s:system) (i:id) : option fdec :=\nlookupFdecViaIDFromModules s i.\n\nDefinition lookupFdefViaIDFromProduct (p:product) (i:id) : option fdef :=\nmatch p with\n| (product_fdef fd) => if eq_dec (getFdefID fd) i then Some fd else None\n| _ => None\nend.\n\nFixpoint lookupFdefViaIDFromProducts (lp:products) (i:id) : option fdef :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupFdefViaIDFromProduct p i) with\n  | Some fd => Some fd\n  | None => lookupFdefViaIDFromProducts lp' i\n  end\nend.\n\nDefinition lookupFdefViaIDFromModule (m:module) (i:id) : option fdef :=\n  let (os, dts, ps) := m in\n  lookupFdefViaIDFromProducts ps i.\n\nFixpoint lookupFdefViaIDFromModules (lm:modules) (i:id) : option fdef :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupFdefViaIDFromModule m i) with\n  | Some fd => Some fd\n  | None => lookupFdefViaIDFromModules lm' i\n  end\nend.\n\nDefinition lookupFdefViaIDFromSystem (s:system) (i:id) : option fdef :=\nlookupFdefViaIDFromModules s i.\n\n(*     ID type lookup                                    *)\n\nDefinition lookupTypViaIDFromCmd (i:cmd) (id0:id) : option typ :=\nmatch (getCmdTyp i) with\n| None => None\n| Some t =>\n  match (getCmdLoc i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nFixpoint lookupTypViaIDFromCmds (li:cmds) (id0:id) : option typ :=\nmatch li with\n| nil => None\n| i::li' =>\n  match (lookupTypViaIDFromCmd i id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromCmds li' id0\n  end\nend.\n\nDefinition lookupTypViaIDFromPhiNode (i:phinode) (id0:id) : option typ :=\nmatch (getPhiNodeTyp i) with\n| t =>\n  match (getPhiNodeID i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nFixpoint lookupTypViaIDFromPhiNodes (li:phinodes) (id0:id) : option typ :=\nmatch li with\n| nil => None\n| i::li' =>\n  match (lookupTypViaIDFromPhiNode i id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromPhiNodes li' id0\n  end\nend.\n\nDefinition lookupTypViaIDFromTerminator (i:terminator) (id0:id) : option typ :=\nmatch (getTerminatorTyp i) with\n| t =>\n  match (getTerminatorID i) with\n  | id0' =>\n    if (eq_dec id0 id0')\n    then Some t\n    else None\n  end\nend.\n\nDefinition lookupTypViaIDFromBlock (b:block) (id0:id) : option typ :=\nmatch b with\n| (_, stmts_intro ps cs t) =>\n  match (lookupTypViaIDFromPhiNodes ps id0) with\n  | None =>\n    match (lookupTypViaIDFromCmds cs id0) with\n    | None => lookupTypViaIDFromTerminator t id0\n    | re => re\n    end\n  | re => re\n  end\nend.\n\nFixpoint lookupTypViaIDFromBlocks (lb:blocks) (id0:id) : option typ :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (lookupTypViaIDFromBlock b id0) with\n  | Some t => Some t\n  | None => lookupTypViaIDFromBlocks lb' id0\n  end\nend.\n\nFixpoint lookupTypViaIDFromArgs (la:args) (id0:id) : option typ :=\nmatch la with\n| nil => None\n| (t1,_,id1)::la' =>\n    if (id0==id1) then Some t1 else lookupTypViaIDFromArgs la' id0\nend.\n\nDefinition lookupTypViaIDFromFdef (fd:fdef) (id0:id) : option typ :=\nmatch fd with\n| (fdef_intro (fheader_intro _ _ _ la _ ) lb) =>\n    match lookupTypViaIDFromArgs la id0 with\n    | None => lookupTypViaIDFromBlocks lb id0\n    | Some t => Some t\n    end\nend.\n\nDefinition lookupTypViaGIDFromProduct (p:product) (id0:id) : option typ :=\nmatch p with\n| product_fdef fd => Some (getFdefTyp fd)\n| product_gvar (gvar_intro id1 _ spec t _ _) => if id0==id1 then Some t else None\n| product_gvar (gvar_external id1 spec t) => if id0==id1 then Some t else None\n| product_fdec fc => Some (getFdecTyp fc)\nend.\n\nFixpoint lookupTypViaGIDFromProducts (lp:products) (id0:id) : option typ :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (lookupTypViaGIDFromProduct p id0) with\n  | Some t => Some t\n  | None => lookupTypViaGIDFromProducts lp' id0\n  end\nend.\n\nDefinition lookupTypViaGIDFromModule (m:module) (id0:id) : option typ :=\n  let (os, dts, ps) := m in\n  lookupTypViaGIDFromProducts ps id0.\n\nFixpoint lookupTypViaGIDFromModules (lm:modules) (id0:id) : option typ :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupTypViaGIDFromModule m id0) with\n  | Some t => Some t\n  | None => lookupTypViaGIDFromModules lm' id0\n  end\nend.\n\nDefinition lookupTypViaGIDFromSystem (s:system) (id0:id) : option typ :=\nlookupTypViaGIDFromModules s id0.\n\nFixpoint lookupTypViaTIDFromNamedts (nts:namedts) (id0:id) : option typ :=\nmatch nts with\n| nil => None\n| (id1, typ1)::nts' =>\n  if (eq_dec id0 id1)\n  then Some (typ_struct typ1)\n  else lookupTypViaTIDFromNamedts nts' id0\nend.\n\nDefinition lookupTypViaTIDFromModule (m:module) (id0:id) : option typ :=\n  let (os, dts, ps) := m in\n  lookupTypViaTIDFromNamedts dts id0.\n\nFixpoint lookupTypViaTIDFromModules (lm:modules) (id0:id) : option typ :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (lookupTypViaTIDFromModule m id0) with\n  | Some t => Some t\n  | None => lookupTypViaTIDFromModules lm' id0\n  end\nend.\n\nDefinition lookupTypViaTIDFromSystem (s:system) (id0:id) : option typ :=\nlookupTypViaTIDFromModules s id0.\n\n(**********************************)\n(* labels <-> blocks. *)\n\n  Definition lookupBlockViaLabelFromBlocks (bs:blocks) (l0:l) : option stmts :=\n  lookupAL _ bs l0.\n\n  Definition lookupBlockViaLabelFromFdef (f:fdef) (l0:l) : option stmts :=\n  let '(fdef_intro _ bs) := f in\n  lookupAL _ bs l0.\n\n(**********************************)\n(* generate block use-def *)\n\n  Definition getBlockLabel (b:block) : l := fst b.\n\n(**********************************)\n(* CFG. *)\n\n  Definition getTerminator (b:block) : terminator :=\n  match b with\n  | (_, stmts_intro _ _ t) => t\n  end.\n\n  Definition successors_terminator (tmn: terminator) : ls :=\n  match tmn with\n  | insn_return _ _ _ => nil\n  | insn_return_void _ => nil\n  | insn_br _ _ l1 l2 => l1::l2::nil\n  | insn_br_uncond _ l1 => l1::nil\n  | insn_unreachable _ => nil\n  end.\n\n  Definition terminator_match (tmn1 tmn2: terminator) : Prop :=\n  match tmn1, tmn2 with\n  | insn_return id1 _ _, insn_return id2 _ _ => id1 = id2\n  | insn_return_void id1, insn_return_void id2 => id1 = id2\n  | insn_br id1 _ l11 l12, insn_br id2 _ l21 l22 => \n      id1 = id2 /\\ l11 = l21 /\\ l12 = l22\n  | insn_br_uncond id1 l1, insn_br_uncond id2 l2 => id1 = id2 /\\ l1 = l2\n  | insn_unreachable i1, insn_unreachable i2 => i1 = i2\n  | _, _ => False\n  end.\n\nLtac terminator_match_tac :=\nmatch goal with\n| J : terminator_match ?t1 ?t2 |- _ =>\n  destruct t1; destruct t2; simpl in J; inversion J; subst; auto;\n    match goal with\n    | J': ?id1 = _ /\\ ?id2 = _ /\\ ?id3 = _ |- _ =>\n      destruct J' as [? [? ?]]; subst id1 id2 id3; auto\n    | J': ?id1 = _ /\\ ?id2 = _ |- _ =>\n      destruct J' as [? ?]; subst id1 id2; auto\n    | J' : ?id0 = _ |- _ => subst id0; auto\n    end\nend.\n\n(**********************************)\n(* Classes. *)\n\nDefinition isPointerTypB (t:typ) : bool :=\nmatch t with\n| typ_pointer _ => true\n| _ => false\nend.\n\nDefinition isFunctionPointerTypB (t:typ) : bool :=\nmatch t with\n| typ_pointer (typ_function _ _ _) => true\n| _ => false\nend.\n\nDefinition isArrayTypB (t:typ) : bool :=\nmatch t with\n| typ_array _ _ => true\n| _ => false\nend.\n\n(*\nDefinition isInvokeInsnB (i:insn) : bool :=\nmatch i with\n| insn_invoke _ _ _ _ _ _ => true\n| _ => false\nend.\n*)\n\nDefinition isReturnInsnB (i:terminator) : bool :=\nmatch i with\n| insn_return _ _ _ => true\n| insn_return_void _ => true\n| _ => false\nend.\n\nDefinition _isCallInsnB (i:cmd) : bool :=\nmatch i with\n| insn_call _ _ _ _ _ _ _ => true\n| _ => false\nend.\n\nDefinition isCallInsnB (i:insn) : bool :=\nmatch i with\n| insn_cmd c => _isCallInsnB c\n| _ => false\nend.\n\nDefinition isNotValidReturnTypB (t:typ) : bool :=\nmatch t with\n| typ_label => true\n| typ_metadata => true\n| _ => false\nend.\n\nDefinition isValidReturnTypB (t:typ) : bool :=\nnegb (isNotValidReturnTypB t).\n\nDefinition isNotFirstClassTypB (t:typ) : bool :=\nmatch t with\n| typ_void => true\n(* | typ_opaque => true *)\n| typ_function _ _ _ => true\n| _ => false\nend.\n\nDefinition isFirstClassTypB (t:typ) : bool :=\nnegb (isNotFirstClassTypB t).\n\nDefinition isValidArgumentTypB (t:typ) : bool :=\nmatch t with\n(*| typ_opaque => true *)\n| _ => isFirstClassTypB t\nend.\n\nDefinition isNotValidElementTypB (t:typ) : bool :=\nmatch t with\n| typ_void => true\n| typ_label => true\n| typ_metadata => true\n| typ_function _ _ _ => true\n| _ => false\nend.\n\nDefinition isValidElementTypB (t:typ) : bool :=\nnegb (isNotValidElementTypB t).\n\nDefinition isBindingFdecB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_fdec fdec => true\n| _ => false\nend.\n\nDefinition isBindingGvarB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_gvar _ => true\n| _ => false\nend.\n\nDefinition isBindingArgB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_arg arg => true\n| _ => false\nend.\n\nDefinition isBindingCmdB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_cmd _ => true\n| _ => false\nend.\n\nDefinition isBindingTerminatorB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_terminator _ => true\n| _ => false\nend.\n\nDefinition isBindingPhiNodeB (ib:id_binding) : bool :=\nmatch ib with\n| id_binding_phinode _ => true\n| _ => false\nend.\n\nDefinition isBindingInsnB (ib:id_binding) : bool :=\nisBindingCmdB ib || isBindingTerminatorB ib || isBindingPhiNodeB ib.\n\nDefinition isPointerTyp typ := isPointerTypB typ = true.\n\nDefinition isFunctionPointerTyp t := isFunctionPointerTypB t = true.\n\n(* Definition isInvokeInsn insn := isInvokeInsnB insn = true. *)\n\nDefinition isReturnTerminator tmn := isReturnInsnB tmn = true.\n\nDefinition isNotValidReturnTyp typ := isNotValidReturnTypB typ = true.\n\nDefinition isValidReturnTyp typ := isValidReturnTypB typ = true.\n\nDefinition isNotFirstClassTyp typ := isNotFirstClassTypB typ = true.\n\nDefinition isFirstClassTyp typ := isFirstClassTypB typ = true.\n\nDefinition isValidArgumentTyp typ := isValidArgumentTypB typ = true.\n\nDefinition isNotValidElementTyp typ := isNotValidElementTypB typ = true.\n\nDefinition isValidElementTyp typ := isValidElementTypB typ = true.\n\nDefinition isBindingFdec ib : option fdec :=\nmatch ib with\n| id_binding_fdec f => Some f\n| _ => None\nend.\n\nDefinition isBindingArg ib : option arg :=\nmatch ib with\n| id_binding_arg a => Some a\n| _ => None\nend.\n\nDefinition isBindingGvar ib : option gvar :=\nmatch ib with\n| id_binding_gvar g => Some g\n| _ => None\nend.\n\nDefinition isBindingCmd ib : option cmd :=\nmatch ib with\n| id_binding_cmd c => Some c\n| _ => None\nend.\n\nDefinition isBindingPhiNode ib : option phinode :=\nmatch ib with\n| id_binding_phinode p => Some p\n| _ => None\nend.\n\nDefinition isBindingTerminator ib : option terminator :=\nmatch ib with\n| id_binding_terminator tmn => Some tmn\n| _ => None\nend.\n\nDefinition isBindingInsn ib : option insn :=\nmatch ib with\n| id_binding_cmd c => Some (insn_cmd c)\n| id_binding_phinode p => Some (insn_phinode p)\n| id_binding_terminator tmn => Some (insn_terminator tmn)\n| _ => None\nend.\n\nDefinition isAggregateTyp t :=\nmatch t with\n| typ_struct _ => True\n| typ_array _ _ => True\n| _ => False\nend.\n\nDefinition is_terminator (instr:insn) : bool :=\nmatch instr with\n| insn_terminator t => true\n| _ => false\nend.\n\nDefinition isnt_alloca c :=\nmatch c with\n| insn_alloca _ _ _ _ => False\n| _ => True\nend.\n\n(*************************************************)\n(*         Uniq                                  *)\n\nFixpoint getBlocksLocs (bs:blocks) : ids :=\nmatch bs with\n| nil => nil\n| b::bs' => getStmtsLocs (snd b)++getBlocksLocs bs'\nend.\n\nDefinition uniqBlocks bs : Prop :=\nlet ids := getBlocksLocs bs in\nuniq bs /\\ NoDup ids.\n\nDefinition uniqFdef fdef : Prop :=\nmatch fdef with\n| (fdef_intro (fheader_intro _ _ _ la _) bs) =>\n    uniqBlocks bs /\\ NoDup (getArgsIDs la ++ getBlocksLocs bs)\nend.\n\nDefinition uniqFdec fdec : Prop :=\nmatch fdec with\n| (fdec_intro (fheader_intro _ _ _ la _) _) =>\n    NoDup (getArgsIDs la)\nend.\n\nDefinition getProductID product : id :=\nmatch product with\n| product_gvar g => getGvarID g\n| product_fdec f => getFdecID f\n| product_fdef f => getFdefID f\nend.\n\nFixpoint getProductsIDs ps : ids :=\nmatch ps with\n| nil => nil\n| p::ps' => getProductID p::getProductsIDs ps'\nend.\n\nFixpoint getFdefsIDs ps : ids :=\nmatch ps with\n| nil => nil\n| product_fdef f::ps' => getFdefID f::getFdefsIDs ps'\n| _::ps' => getFdefsIDs ps'\nend.\n\nDefinition uniqProduct product : Prop :=\nmatch product with\n| product_gvar g => True\n| product_fdec f => uniqFdec f\n| product_fdef f => uniqFdef f\nend.\n\nDefinition uniqProducts ps : Prop :=\n  Forall uniqProduct ps.\n\nFixpoint getNamedtsIDs (dts:namedts) : ids :=\nmatch dts with\n| nil => nil\n| (id0, _)::dts' => id0::getNamedtsIDs dts'\nend.\n\nDefinition uniqModule m : Prop :=\nmatch m with\n| module_intro _ dts ps => uniqProducts ps /\\\n                           NoDup (getNamedtsIDs dts) /\\\n                           NoDup (getProductsIDs ps)\nend.\n\nFixpoint uniqModules ms : Prop :=\nmatch ms with\n| nil => True\n| m::ms' => uniqModule m /\\ uniqModules ms'\nend.\n\nDefinition uniqSystem s : Prop := uniqModules s.\n\n(**********************************)\n(* Dec. *)\n\nDefinition sumbool2bool A B (dec:sumbool A B) : bool :=\nmatch dec with\n| left _ => true\n| right _ => false\nend.\n\nLemma sumbool2bool_true : forall A B H,\n  sumbool2bool A B H = true -> A.\nProof.\n  intros.\n  unfold sumbool2bool in H0.\n  destruct H; auto.\n    inversion H0.\nQed.\n\nLemma sumbool2bool_false : forall A B H,\n  sumbool2bool A B H = false -> B.\nProof.\n  intros.\n  unfold sumbool2bool in H0.\n  destruct H; auto.\n    inversion H0.\nQed.\n\nLemma eq_sumbool2bool_true : forall A (a1 a2:A) (H:{a1=a2}+{~a1=a2}),\n  a1 = a2 ->\n  sumbool2bool _ _ H = true.\nProof.\n  intros; subst.\n  destruct H; auto.\nQed.\n\nLemma floating_point_dec : forall (fp1 fp2:floating_point), {fp1=fp2}+{~fp1=fp2}.\nProof.\n  decide equality.\nQed.\n\nLtac done_right := right; intro J; inversion J; subst; auto.\n\nLtac destruct_top_tac :=\n  match goal with\n  | |- { _ = ?t2 } + { _ <> ?t2 } => destruct t2; try solve [auto | done_right]\n  end.\n\nLemma varg_dec : forall x y : varg, {x=y} + {x<>y}.\nProof.\n  destruct x, y; try solve [auto | done_right].\n  match goal with\n  | |- context [{Some ?s1 = Some ?s2} + {Some ?s1 <> Some ?s2}] =>\n       destruct (@Size.dec s1 s2); try solve [auto | done_right]\n  end.\nQed.\n\nLtac destruct_wrt_type1 a1 a2:=\n  match type of a1 with\n  | sz => destruct (@Size.dec a1 a2)\n  | floating_point => destruct (@floating_point_dec a1 a2)\n  | varg => destruct (@varg_dec a1 a2)\n  | id => destruct (@id_dec a1 a2)\n  end.\n\nLtac destruct_dec_tac f :=\n  match goal with\n  | |- { ?c ?a1 = ?c ?a2 } + { ?c ?a1 <> ?c ?a2 } =>\n      f a1 a2\n  | |- { ?c ?a1 ?b1 = ?c ?a2 ?b2 } + { ?c ?a1 ?b1 <> ?c ?a2 ?b2 } =>\n      f a1 a2; f b1 b2\n  | |- { ?c ?a1 ?b1 ?c1 = ?c ?a2 ?b2 ?c2 } + { ?c ?a1 ?b1 ?c1 <> ?c ?a2 ?b2 ?c2 } =>\n      f a1 a2; f b1 b2; f c1 c2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 = ?c ?a2 ?b2 ?c2 ?d2 }  +\n       { ?c ?a1 ?b1 ?c1 ?d1 <> ?c ?a2 ?b2 ?c2 ?d2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 ?e1 = ?c ?a2 ?b2 ?c2 ?d2 ?e2 } +\n       { ?c ?a1 ?b1 ?c1 ?d1 ?e1 <> ?c ?a2 ?b2 ?c2 ?d2 ?e2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2;f e1 e2\n  | |- { ?c ?a1 ?b1 ?c1 ?d1 ?e1 ?f1 = ?c ?a2 ?b2 ?c2 ?d2 ?e2 ?f2 } +\n       { ?c ?a1 ?b1 ?c1 ?d1 ?e1 ?f1 <> ?c ?a2 ?b2 ?c2 ?d2 ?e2 ?f2 } =>\n      f a1 a2; f b1 b2; f c1 c2; f d1 d2; f e1 e2; f f1 f2\n  | |- {?a1 :: ?b1 = ?a2 :: ?b2} +\n       {?a1 :: ?b1 <> ?a2 :: ?b2} =>\n      f a1 a2; f b1 b2\n  end; subst; try solve [auto | done_right].\n\nLtac typ_mutrec_dec_subs_tac :=\n  let destruct_wrt_type a1 a2:=\n    match type of a1 with\n    | typ =>\n      match goal with\n      | H:forall t2 : typ, {a1 = t2} + {a1 <> t2} |- _ => destruct (@H a2)\n      end\n    | list typ =>\n      match goal with\n      | H:forall t2 : list typ, {a1 = t2} + {a1 <> t2} |- _ =>\n          destruct (@H a2); clear H\n      end\n    | _ => destruct_wrt_type1 a1 a2\n    end; subst; try solve [auto | done_right] in\n  destruct_dec_tac destruct_wrt_type.\n\nLtac typ_mutrec_dec_tac := destruct_top_tac; typ_mutrec_dec_subs_tac.\n\nDefinition typ_dec_prop (t1:typ) := forall t2, {t1=t2} + {~t1=t2}.\nDefinition list_typ_dec_prop (lt1:list typ) :=\n  forall lt2, {lt1=lt2} + {~lt1=lt2}.\n\n\nLemma typ_mutrec_dec :\n  (forall t1, typ_dec_prop t1) *\n  (forall lt1, list_typ_dec_prop lt1).\nProof.\n  apply typ_mutrec;\n  unfold typ_dec_prop, list_typ_dec_prop;\n  intros; try solve [abstract typ_mutrec_dec_tac].\nQed.\n\nLemma list_typ_dec : forall (lt1 lt2:list typ), {lt1=lt2} + {~lt1=lt2}.\nProof.\n  destruct typ_mutrec_dec; auto.\nQed.\n\nLemma typ_dec : forall (t1 t2:typ), {t1=t2} + {t1<>t2}.\nProof.\n  destruct typ_mutrec_dec; auto.\nQed.\n\n\nLemma bop_dec : forall (b1 b2:bop), {b1=b2}+{~b1=b2}.\nProof.\n  decide equality.\nQed.\n\nLemma fbop_dec : forall (b1 b2:fbop), {b1=b2}+{~b1=b2}.\nProof.\n  decide equality.\nQed.\n\nLemma extop_dec : forall (e1 e2:extop), {e1=e2}+{~e1=e2}.\nProof.\n  decide equality.\nQed.\n\nLemma castop_dec : forall (c1 c2:castop), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma cond_dec : forall (c1 c2:cond), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma fcond_dec : forall (c1 c2:fcond), {c1=c2}+{~c1=c2}.\nProof.\n  decide equality.\nQed.\n\nLemma truncop_dec : forall (t1 t2:truncop), {t1=t2}+{~t1=t2}.\nProof.\n  decide equality.\nQed.\n\nDefinition const_dec_prop (c1:const) := forall c2, {c1=c2} + {~c1=c2}.\nDefinition list_const_dec_prop (lc1:list const) :=\n  forall lc2, {lc1=lc2} + {~lc1=lc2}.\n\nLtac destruct_wrt_type2 a1 a2:=\nmatch type of a1 with\n| Int => destruct (@INTEGER.dec a1 a2)\n| Float => destruct (@FLOAT.dec a1 a2)\n| sz => destruct (@Size.dec a1 a2)\n| floating_point => destruct (@floating_point_dec a1 a2)\n| typ => destruct (@typ_dec a1 a2)\n| varg => destruct (@varg_dec a1 a2)\n| id => destruct (@id_dec a1 a2)\n| extop => destruct (@extop_dec a1 a2)\n| truncop => destruct (@truncop_dec a1 a2)\n| castop => destruct (@castop_dec a1 a2)\n| inbounds => destruct (@inbounds_dec a1 a2)\n| list typ => destruct (@list_typ_dec a1 a2)\n| cond => destruct (@cond_dec a1 a2)\n| fcond => destruct (@fcond_dec a1 a2)\n| fbop => destruct (@fbop_dec a1 a2)\n| bop => destruct (@bop_dec a1 a2)\n| _ => destruct_wrt_type1 a1 a2\nend.\n\nLtac const_mutrec_dec_subs_tac :=\n  let destruct_wrt_type a1 a2:=\n    match type of a1 with\n    | const =>\n      match goal with\n      | H:forall t2 : const, {a1 = t2} + {a1 <> t2} |- _ => destruct (@H a2)\n      end\n    | list const =>\n      match goal with\n      | H:forall t2 : list const, {a1 = t2} + {a1 <> t2} |- _ =>\n          destruct (@H a2); clear H\n      end\n    | _ => destruct_wrt_type2 a1 a2\n    end; subst; try solve [auto | done_right] in\n  destruct_dec_tac destruct_wrt_type.\n\nLtac const_mutrec_dec_tac := destruct_top_tac; const_mutrec_dec_subs_tac.\n\nLemma const_mutrec_dec :\n  (forall c1, const_dec_prop c1) *\n  (forall lc1, list_const_dec_prop lc1).\nProof.\n apply const_mutrec;\n  unfold const_dec_prop, list_const_dec_prop;\n  intros; try solve [abstract const_mutrec_dec_tac].\nQed.\n\nLemma const_dec : forall (c1 c2:const), {c1=c2}+{~c1=c2}.\nProof.\n  destruct const_mutrec_dec; auto.\nQed.\n\nLemma list_const_dec : forall (lc1 lc2:list const), {lc1=lc2} + {~lc1=lc2}.\nProof.\n  destruct const_mutrec_dec; auto.\nQed.\n\nLemma value_dec : forall (v1 v2:value), {v1=v2}+{~v1=v2}.\nProof.\n  decide equality. apply const_dec.\nQed.\n\nLemma attribute_dec : forall (attr1 attr2:attribute),\n  {attr1=attr2}+{~attr1=attr2}.\nProof.\n  decide equality.\nQed.\n\nLemma attributes_dec : forall (attrs1 attrs2:attributes),\n  {attrs1=attrs2}+{~attrs1=attrs2}.\nProof.\n  decide equality.\n    destruct (@attribute_dec a a0); subst; try solve [auto | done_right].\nQed.\n\nLemma params_dec : forall (p1 p2:params), {p1=p2}+{~p1=p2}.\nProof.\n  decide equality.\n    destruct a as [ [t a] v]. destruct p as [ [t0 a0] v0].\n    destruct (@typ_dec t t0); subst; try solve [done_right].\n    destruct (@attributes_dec a a0); subst; try solve [done_right].\n    destruct (@value_dec v v0); subst; try solve [auto | done_right].\nQed.\n\nLemma list_value_l_dec : forall (l1 l2:list (value * l)), {l1=l2}+{~l1=l2}.\nProof.\n  decide equality.\n  decide equality.\n  decide equality.\n  apply const_dec.\nQed.\n\nLemma list_value_dec : forall (lv1 lv2: list (sz * value)), {lv1=lv2}+{~lv1=lv2}.\nProof.\n  decide equality.\n  decide equality.\n  apply value_dec.\n  apply Size.dec. (* eq_nat_dec works for the proofs, but on extraction,\n                     we want to map sz into int, and Size.dec to int cmp in OCaml.\n                     eq_nat_dec wont be changed on extraction. So, we should use\n                     Size.dec here. *)\nQed.\n\nLemma callconv_dec : forall (cc1 cc2:callconv), {cc1=cc2}+{~cc1=cc2}.\nProof.\n  decide equality.\nQed.\n\nLtac destruct_wrt_type3 a1 a2:=\nmatch type of a1 with\n| l => destruct (@id_dec a1 a2)\n| value => destruct (@value_dec a1 a2)\n| const => destruct (@const_dec a1 a2)\n| list const => destruct (@list_const_dec a1 a2)\n| attribute => destruct (@attribute_dec a1 a2)\n| attributes => destruct (@attributes_dec a1 a2)\n| params => destruct (@params_dec a1 a2)\n| list (sz * value) => destruct (@list_value_dec a1 a2)\n| list (value * l) => destruct (@list_value_l_dec a1 a2)\n| callconv => destruct (@callconv_dec a1 a2)\n| align => destruct (Align.dec a1 a2)\n| noret => destruct (@noret_dec a1 a2)\n| tailc => destruct (@tailc_dec a1 a2)\n| _ => destruct_wrt_type2 a1 a2\nend.\n\nLtac insn_dec_tac :=\n  destruct_top_tac;\n  destruct_dec_tac destruct_wrt_type3.\n\nLemma cmd_dec : forall (c1 c2:cmd), {c1=c2}+{~c1=c2}.\nProof.\n  (cmd_cases (destruct c1) Case); destruct c2;\n    try solve [done_right | auto | abstract insn_dec_tac].\n  Case \"insn_call\".\n    match goal with\n    | |- {insn_call ?i0 ?n ?c ?rt ?va ?v ?p =\n            insn_call ?i1 ?n0 ?c0 ?rt0 ?va0 ?v0 ?p0} +\n         {insn_call ?i0 ?n ?c ?rt ?va ?v ?p <>\n            insn_call ?i1 ?n0 ?c0 ?rt0 ?va0 ?v0 ?p0} =>\n      destruct_wrt_type3 i0 i1; subst; try solve [done_right];\n      destruct_wrt_type3 v v0; subst; try solve [done_right];\n      destruct_wrt_type3 n n0; subst; try solve [done_right];\n      destruct_wrt_type3 rt rt0; subst; try solve [done_right];\n      destruct_wrt_type3 va va0; subst; try solve [done_right];\n      destruct_wrt_type3 p p0; subst; try solve [done_right];\n      destruct c as [tailc5 callconv5 attributes1 attributes2];\n      destruct c0 as [tailc0 callconv0 attributes0 attributes3];\n      destruct_wrt_type3 tailc5 tailc0; subst; try solve [done_right];\n      destruct_wrt_type3 callconv5 callconv0; subst; try solve [done_right];\n      destruct_wrt_type3 attributes1 attributes0; subst; try solve [done_right];\n      destruct_wrt_type3 attributes2 attributes3;\n        subst; try solve [auto|done_right]\n    end.\nQed.\n\nLemma terminator_dec : forall (tmn1 tmn2:terminator), {tmn1=tmn2}+{~tmn1=tmn2}.\nProof.\n  destruct tmn1; destruct tmn2;\n    try solve [done_right | auto | abstract insn_dec_tac].\nQed.\n\nLemma phinode_dec : forall (p1 p2:phinode), {p1=p2}+{~p1=p2}.\nProof.\n  destruct p1; destruct p2; try solve [done_right | auto | insn_dec_tac].\nQed.\n\nLemma insn_dec : forall (i1 i2:insn), {i1=i2}+{~i1=i2}.\nProof.\n  destruct i1 as [phinode5|cmd5|terminator5];\n  destruct i2 as [phinode0|cmd0|terminator0]; try solve [done_right | auto].\n    destruct (@phinode_dec phinode5 phinode0);\n      subst; try solve [auto | done_right].\n    destruct (@cmd_dec cmd5 cmd0); subst; try solve [auto | done_right].\n    destruct (@terminator_dec terminator5 terminator0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma cmds_dec : forall (cs1 cs2:list cmd), {cs1=cs2}+{~cs1=cs2}.\nProof.\n  induction cs1.\n    destruct cs2; subst; try solve [subst; auto | done_right].\n\n    destruct cs2; subst; try solve [done_right].\n    destruct (@cmd_dec a c); subst; try solve [done_right].\n    destruct (@IHcs1 cs2); subst; try solve [auto | done_right].\nQed.\n\nLemma phinodes_dec : forall (ps1 ps2:list phinode), {ps1=ps2}+{~ps1=ps2}.\nProof.\n  induction ps1.\n    destruct ps2; subst; try solve [subst; auto | done_right].\n\n    destruct ps2; subst; try solve [done_right].\n    destruct (@phinode_dec a p); subst; try solve [done_right].\n    destruct (@IHps1 ps2); subst; try solve [auto | done_right].\nQed.\n\nLemma block_dec : forall (b1 b2:block), {b1=b2}+{~b1=b2}.\nProof.\n  destruct b1 as [l5 [phinodes5 cmds5 terminator5]];\n  destruct b2 as [l0 [phinodes0 cmds0 terminator0]]; try solve [done_right | auto].\n    destruct (@id_dec l5 l0); subst; try solve [done_right].\n    destruct (@phinodes_dec phinodes5 phinodes0); subst; try solve [done_right].\n    destruct (@cmds_dec cmds5 cmds0); subst; try solve [done_right].\n    destruct (@terminator_dec terminator5 terminator0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma arg_dec : forall (a1 a2:arg), {a1=a2}+{~a1=a2}.\nProof.\n  destruct a1; destruct a2; try solve [subst; auto | done_right].\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct p. destruct p0.\n    destruct (@attributes_dec a a0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [auto | done_right].\nQed.\n\nLemma args_dec : forall (l1 l2:args), {l1=l2}+{~l1=l2}.\nProof.\n  induction l1.\n    destruct l2; subst; try solve [subst; auto | done_right].\n\n    destruct l2; subst; try solve [done_right].\n    destruct (@arg_dec a p); subst; try solve [done_right].\n    destruct (@IHl1 l2); subst; try solve [auto | done_right].\nQed.\n\nLemma visibility_dec : forall (vb1 vb2:visibility), {vb1=vb2}+{~vb1=vb2}.\nProof.\n  decide equality.\nQed.\n\nLemma linkage_dec : forall (lk1 lk2:linkage), {lk1=lk2}+{~lk1=lk2}.\nProof.\n  decide equality.\nQed.\n\nLemma fheader_dec : forall (f1 f2:fheader), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fnattrs5 typ5 id5 args5 varg5];\n  destruct f2 as [fnattrs0 typ0 id0 args0 varg0];\n    try solve [subst; auto | done_right].\n    destruct (@typ_dec typ5 typ0); subst; try solve [done_right].\n    destruct (@id_dec id5 id0); subst; try solve [done_right].\n    destruct fnattrs5 as [linkage5 visibility5 callconv5 attributes1\n                          attributes2].\n    destruct fnattrs0 as [linkage0 visibility0 callconv0 attributes0\n                          attributes3].\n    destruct (@visibility_dec visibility5 visibility0);\n      subst; try solve [done_right].\n    destruct (@varg_dec varg5 varg0); subst; try solve [done_right].\n    destruct (@attributes_dec attributes1 attributes0);\n      subst; try solve [done_right].\n    destruct (@attributes_dec attributes2 attributes3);\n      subst; try solve [done_right].\n    destruct (@callconv_dec callconv5 callconv0); subst; try solve [done_right].\n    destruct (@linkage_dec linkage5 linkage0); subst; try solve [done_right].\n    destruct (@args_dec args5 args0); subst; try solve [auto | done_right].\nQed.\n\nLemma blocks_dec : forall (lb lb':blocks), {lb=lb'}+{~lb=lb'}.\nProof.\n  induction lb.\n    destruct lb'; subst; try solve [subst; auto | done_right].\n\n    destruct lb'; subst; try solve [done_right].\n    destruct (@block_dec a b); subst; try solve [done_right].\n    destruct (@IHlb lb'); subst; try solve [auto | done_right].\nQed.\n\nLemma intrinsic_id_dec : forall (iid1 iid2:intrinsic_id),\n  {iid1=iid2}+{~iid1=iid2}.\nProof. decide equality. Qed.\n\nLemma external_id_dec : forall (eid1 eid2:external_id),\n  {eid1=eid2}+{~eid1=eid2}.\nProof. decide equality. Qed.\n\nLemma deckind_dec : forall (dck1 dck2: deckind), {dck1=dck2}+{~dck1=dck2}.\nProof.\n  destruct dck1 as [iid1|eid1].\n    destruct dck2 as [iid2|eid2]; try solve [done_right].\n      destruct (@intrinsic_id_dec iid1 iid2);\n        subst; try solve [auto | done_right].\n    destruct dck2 as [iid2|eid2]; try solve [done_right].\n      destruct (@external_id_dec eid1 eid2);\n        subst; try solve [auto | done_right].\nQed.\n\nLemma fdec_dec : forall (f1 f2:fdec), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fheader5 dck5];\n  destruct f2 as [fheader0 dck0]; try solve [subst; auto | done_right].\n    destruct (@deckind_dec dck5 dck0); subst; try solve [done_right].\n    destruct (@fheader_dec fheader5 fheader0);\n      subst; try solve [auto | done_right].\nQed.\n\nLemma fdef_dec : forall (f1 f2:fdef), {f1=f2}+{~f1=f2}.\nProof.\n  destruct f1 as [fheader5 blocks5];\n  destruct f2 as [fheader0 blocks0]; try solve [subst; auto | done_right].\n    destruct (@fheader_dec fheader5 fheader0); subst; try solve [done_right].\n    destruct (@blocks_dec blocks5 blocks0); subst; try solve [auto | done_right].\nQed.\n\nLemma gvar_spec_dec : forall (g1 g2:gvar_spec), {g1=g2}+{~g1=g2}.\nProof.\n  decide equality.\nQed.\n\nLemma gvar_dec : forall (g1 g2:gvar), {g1=g2}+{~g1=g2}.\nProof.\n  destruct g1 as [i0 l0 g t c a|i0 g t];\n  destruct g2 as [i1 l1 g0 t0 c0 a0|i1 g0 t0];\n    try solve [subst; auto | done_right].\n\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct (@linkage_dec l0 l1); subst; try solve [done_right].\n    destruct (@gvar_spec_dec g g0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [done_right].\n    destruct (@const_dec c c0); subst; try solve [done_right].\n    destruct (@Align.dec a a0); subst; try solve [auto | done_right].\n\n    destruct (@id_dec i0 i1); subst; try solve [done_right].\n    destruct (@gvar_spec_dec g g0); subst; try solve [done_right].\n    destruct (@typ_dec t t0); subst; try solve [auto | done_right].\nQed.\n\nLemma product_dec : forall (p p':product), {p=p'}+{~p=p'}.\nProof.\n  destruct p as [g|f|f]; destruct p' as [g0|f0|f0];\n    try solve [done_right | auto].\n    destruct (@gvar_dec g g0); subst; try solve [auto | done_right].\n    destruct (@fdec_dec f f0); subst; try solve [auto | done_right].\n    destruct (@fdef_dec f f0); subst; try solve [auto | done_right].\nQed.\n\nLemma products_dec : forall (lp lp':products), {lp=lp'}+{~lp=lp'}.\nProof.\n  induction lp.\n    destruct lp'; subst; try solve [subst; auto | done_right].\n\n    destruct lp'; subst; try solve [done_right].\n    destruct (@product_dec a p); subst; try solve [done_right].\n    destruct (@IHlp lp'); subst; try solve [auto | done_right].\nQed.\n\nLemma namedt_dec : forall (nt1 nt2:namedt), {nt1=nt2}+{~nt1=nt2}.\nProof.\n  destruct nt1 as [id5 l0];\n  destruct nt2 as [id0 l1]; try solve [subst; auto | done_right].\n    destruct (@id_dec id5 id0); subst; try solve [done_right].\n    destruct (@list_typ_dec l0 l1); subst; try solve [auto | done_right].\nQed.\n\nLemma namedts_dec : forall (nts nts':namedts), {nts=nts'}+{~nts=nts'}.\nProof.\n  induction nts.\n    destruct nts'; subst; try solve [subst; auto | done_right].\n\n    destruct nts'; subst; try solve [done_right].\n    destruct (@namedt_dec a n); subst; try solve [done_right].\n    destruct (@IHnts nts'); subst; try solve [auto | done_right].\nQed.\n\nLemma layout_dec : forall (l1 l2:layout), {l1=l2}+{~l1=l2}.\nProof.\n  destruct l1; destruct l2;\n    try solve [subst; auto | done_right | insn_dec_tac].\nQed.\n\nLemma layouts_dec : forall (l1 l2:layouts), {l1=l2}+{~l1=l2}.\nProof.\n  induction l1.\n    destruct l2; subst; try solve [subst; auto | done_right].\n\n    destruct l2; subst; try solve [done_right].\n    destruct (@layout_dec a l0); subst; try solve [done_right].\n    destruct (@IHl1 l2); subst; try solve [auto | done_right].\nQed.\n\nLemma module_dec : forall (m m':module), {m=m'}+{~m=m'}.\nProof.\n  destruct m as [l0 n p]; destruct m' as [l1 n0 p0];\n    try solve [done_right | auto].\n    destruct (@layouts_dec l0 l1); subst; try solve [done_right].\n    destruct (@namedts_dec n n0); subst; try solve [done_right].\n    destruct (@products_dec p p0); subst; try solve [auto | done_right].\nQed.\n\nLemma modules_dec : forall (lm lm':modules), {lm=lm'}+{~lm=lm'}.\nProof.\n  induction lm.\n    destruct lm'; subst; try solve [subst; auto | done_right].\n\n    destruct lm'; subst; try solve [done_right].\n    destruct (@module_dec a m); subst; try solve [done_right].\n    destruct (@IHlm lm'); subst; try solve [auto | done_right].\nQed.\n\nLemma system_dec : forall (s s':system), {s=s'}+{~s=s'}.\nProof.\n  apply modules_dec.\nQed.\n\n(**********************************)\n(* Eq. *)\nDefinition typEqB t1 t2 := sumbool2bool _ _ (typ_dec t1 t2).\n\nDefinition list_typEqB lt1 lt2 := sumbool2bool _ _ (list_typ_dec lt1 lt2).\n\nDefinition idEqB i i' := sumbool2bool _ _ (id_dec i i').\n\nDefinition constEqB c1 c2 := sumbool2bool _ _ (const_dec c1 c2).\n\nDefinition list_constEqB lc1 lc2 := sumbool2bool _ _ (list_const_dec lc1 lc2).\n\nDefinition valueEqB (v v':value) := sumbool2bool _ _ (value_dec v v').\n\nDefinition paramsEqB (lp lp':params) := sumbool2bool _ _ (params_dec lp lp').\n\nDefinition lEqB i i' := sumbool2bool _ _ (l_dec i i').\n\nDefinition list_value_lEqB (idls idls':list (value * l)) :=\n  sumbool2bool _ _ (list_value_l_dec idls idls').\n\nDefinition list_valueEqB idxs idxs' :=\n  sumbool2bool _ _ (list_value_dec idxs idxs').\n\nDefinition bopEqB (op op':bop) := sumbool2bool _ _ (bop_dec op op').\nDefinition extopEqB (op op':extop) := sumbool2bool _ _ (extop_dec op op').\nDefinition condEqB (c c':cond) := sumbool2bool _ _ (cond_dec c c').\nDefinition castopEqB (c c':castop) := sumbool2bool _ _ (castop_dec c c').\n\nDefinition cmdEqB (i i':cmd) := sumbool2bool _ _ (cmd_dec i i').\n\nDefinition cmdsEqB (cs1 cs2:list cmd) := sumbool2bool _ _ (cmds_dec cs1 cs2).\n\nDefinition terminatorEqB (i i':terminator) :=\n  sumbool2bool _ _ (terminator_dec i i').\n\nDefinition phinodeEqB (i i':phinode) := sumbool2bool _ _ (phinode_dec i i').\n\nDefinition phinodesEqB (ps1 ps2:list phinode) :=\n  sumbool2bool _ _ (phinodes_dec ps1 ps2).\n\nDefinition blockEqB (b1 b2:block) := sumbool2bool _ _ (block_dec b1 b2).\n\nDefinition blocksEqB (lb lb':blocks) := sumbool2bool _ _ (blocks_dec lb lb').\n\nDefinition argsEqB (la la':args) := sumbool2bool _ _ (args_dec la la').\n\nDefinition fheaderEqB (fh fh' : fheader) :=\n  sumbool2bool _ _ (fheader_dec fh fh').\n\nDefinition fdecEqB (fd fd' : fdec) := sumbool2bool _ _ (fdec_dec fd fd').\n\nDefinition fdefEqB (fd fd' : fdef) := sumbool2bool _ _ (fdef_dec fd fd').\n\nDefinition gvarEqB (gv gv' : gvar) := sumbool2bool _ _ (gvar_dec gv gv').\n\nDefinition productEqB (p p' : product) := sumbool2bool _ _ (product_dec p p').\n\nDefinition productsEqB (lp lp':products) :=\n  sumbool2bool _ _ (products_dec lp lp').\n\nDefinition layoutEqB (o o' : layout) := sumbool2bool _ _ (layout_dec o o').\n\nDefinition layoutsEqB (lo lo':layouts) := sumbool2bool _ _ (layouts_dec lo lo').\n\nDefinition moduleEqB (m m':module) := sumbool2bool _ _ (module_dec m m').\n\nDefinition modulesEqB (lm lm':modules) := sumbool2bool _ _ (modules_dec lm lm').\n\nDefinition systemEqB (s s':system) := sumbool2bool _ _ (system_dec s s').\n\nDefinition attributeEqB (attr attr':attribute) :=\n  sumbool2bool _ _ (attribute_dec attr attr').\n\nDefinition attributesEqB (attrs attrs':attributes) :=\n  sumbool2bool _ _ (attributes_dec attrs attrs').\n\nDefinition linkageEqB (lk lk':linkage) := sumbool2bool _ _ (linkage_dec lk lk').\n\nDefinition visibilityEqB (v v':visibility) :=\n  sumbool2bool _ _ (visibility_dec v v').\n\nDefinition callconvEqB (cc cc':callconv) :=\n  sumbool2bool _ _ (callconv_dec cc cc').\n\n(**********************************)\n(* Inclusion. *)\n\nFixpoint InCmdsB (i:cmd) (li:cmds) {struct li} : bool :=\nmatch li with\n| nil => false\n| i' :: li' => cmdEqB i i' || InCmdsB i li'\nend.\n\nFixpoint InPhiNodesB (i:phinode) (li:phinodes) {struct li} : bool :=\nmatch li with\n| nil => false\n| i' :: li' => phinodeEqB i i' || InPhiNodesB i li'\nend.\n\nDefinition cmdInBlockB (i:cmd) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro _ cmds _) => InCmdsB i cmds\nend.\n\nDefinition phinodeInBlockB (i:phinode) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro ps _ _) => InPhiNodesB i ps\nend.\n\nDefinition terminatorInBlockB (i:terminator) (b:block) : bool :=\nmatch b with\n| (_, stmts_intro _ _ t) => terminatorEqB i t\nend.\n\nFixpoint InArgsB (a:arg) (la:args) {struct la} : bool :=\nmatch la with\n| nil => false\n| a' :: la' =>\n  match (a, a') with\n  | ((t, attrs, id), (t', attrs', id')) =>\n       typEqB t t' && attributesEqB attrs attrs' && idEqB id id'\n  end ||\n  InArgsB a la'\nend.\n\nDefinition argInFheaderB (a:arg) (fh:fheader) : bool :=\nmatch fh with\n| (fheader_intro _ t id la _) => InArgsB a la\nend.\n\nDefinition argInFdecB (a:arg) (fd:fdec) : bool :=\nmatch fd with\n| (fdec_intro fh _) => argInFheaderB a fh\nend.\n\nDefinition argInFdefB (a:arg) (fd:fdef) : bool :=\nmatch fd with\n| (fdef_intro fh lb) => argInFheaderB a fh\nend.\n\nFixpoint InBlocksB (b:block) (lb:blocks) {struct lb} : bool :=\nmatch lb with\n| nil => false\n| b' :: lb' => blockEqB b b' || InBlocksB b lb'\nend.\n\nDefinition blockInFdefB (b:block) (fd:fdef) : bool :=\nmatch fd with\n| (fdef_intro fh lb) => InBlocksB b lb\nend.\n\nFixpoint InProductsB (p:product) (lp:products) {struct lp} : bool :=\nmatch lp with\n| nil => false\n| p' :: lp' => productEqB p p' || InProductsB p lp'\nend.\n\nDefinition productInModuleB (p:product) (m:module) : bool :=\nlet (os, nts, ps) := m in\nInProductsB p ps.\n\nFixpoint InModulesB (m:module) (lm:modules) {struct lm} : bool :=\nmatch lm with\n| nil => false\n| m' :: lm' => moduleEqB m m' || InModulesB m lm'\nend.\n\nDefinition moduleInSystemB (m:module) (s:system) : bool :=\nInModulesB m s.\n\nDefinition productInSystemModuleB (p:product) (s:system) (m:module) : bool :=\nmoduleInSystemB m s && productInModuleB p m.\n\nDefinition blockInSystemModuleFdefB (b:block) (s:system) (m:module) (f:fdef)\n  : bool :=\nblockInFdefB b f && productInSystemModuleB (product_fdef f) s m.\n\nDefinition cmdInSystemModuleFdefBlockB\n  (i:cmd) (s:system) (m:module) (f:fdef) (b:block) : bool :=\ncmdInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition phinodeInSystemModuleFdefBlockB\n  (i:phinode) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nphinodeInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition terminatorInSystemModuleFdefBlockB\n  (i:terminator) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nterminatorInBlockB i b && blockInSystemModuleFdefB b s m f.\n\nDefinition insnInSystemModuleFdefBlockB\n  (i:insn) (s:system) (m:module) (f:fdef) (b:block) : bool :=\nmatch i with\n| insn_phinode p => phinodeInSystemModuleFdefBlockB p s m f b\n| insn_cmd c => cmdInSystemModuleFdefBlockB c s m f b\n| insn_terminator t => terminatorInSystemModuleFdefBlockB t s m f b\nend.\n\nDefinition insnInBlockB (i : insn) (b : block) :=\nmatch i with\n| insn_phinode p => phinodeInBlockB p b\n| insn_cmd c => cmdInBlockB c b\n| insn_terminator t => terminatorInBlockB t b\nend.\n\nDefinition cmdInFdefBlockB (i:cmd) (f:fdef) (b:block) : bool :=\ncmdInBlockB i b && blockInFdefB b f.\n\nDefinition phinodeInFdefBlockB (i:phinode) (f:fdef) (b:block) : bool :=\nphinodeInBlockB i b && blockInFdefB b f.\n\nDefinition terminatorInFdefBlockB (i:terminator) (f:fdef) (b:block) : bool :=\nterminatorInBlockB i b && blockInFdefB b f.\n\nDefinition insnInFdefBlockB\n  (i:insn) (f:fdef) (b:block) : bool :=\nmatch i with\n| insn_phinode p => phinodeInBlockB p b && blockInFdefB b f\n| insn_cmd c => cmdInBlockB c b && blockInFdefB b f\n| insn_terminator t => terminatorInBlockB t b && blockInFdefB b f\nend.\n\nDefinition blockInSystemModuleFdef b S M F :=\n  blockInSystemModuleFdefB b S M F = true.\n\nDefinition moduleInSystem M S := moduleInSystemB M S = true.\n\n(**********************************)\n(* parent *)\n\n(* matching (cmdInBlockB i b) in getParentOfCmdFromBlocksC directly makes\n   the compilation very slow, so we define this dec lemma first... *)\nLemma cmdInBlockB_dec : forall i b,\n  {cmdInBlockB i b = true} + {cmdInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (cmdInBlockB i0 b); auto.\nQed.\n\nLemma phinodeInBlockB_dec : forall i b,\n  {phinodeInBlockB i b = true} + {phinodeInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (phinodeInBlockB i0 b); auto.\nQed.\n\nLemma terminatorInBlockB_dec : forall i b,\n  {terminatorInBlockB i b = true} + {terminatorInBlockB i b = false}.\nProof.\n  intros i0 b. destruct (terminatorInBlockB i0 b); auto.\nQed.\n\nFixpoint getParentOfCmdFromBlocks (i:cmd) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (cmdInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfCmdFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfCmdFromFdef (i:cmd) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfCmdFromBlocks i lb\nend.\n\nDefinition getParentOfCmdFromProduct (i:cmd) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfCmdFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfCmdFromProducts (i:cmd) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfCmdFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfCmdFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfCmdFromModule (i:cmd) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfCmdFromProducts i ps.\n\nFixpoint getParentOfCmdFromModules (i:cmd) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfCmdFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfCmdFromModules i lm'\n  end\nend.\n\nDefinition getParentOfCmdFromSystem (i:cmd) (s:system) : option block :=\n  getParentOfCmdFromModules i s.\n\nDefinition cmdHasParent (i:cmd) (s:system) : bool :=\nmatch (getParentOfCmdFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nFixpoint getParentOfPhiNodeFromBlocks (i:phinode) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (phinodeInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfPhiNodeFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromFdef (i:phinode) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfPhiNodeFromBlocks i lb\nend.\n\nDefinition getParentOfPhiNodeFromProduct (i:phinode) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfPhiNodeFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfPhiNodeFromProducts (i:phinode) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfPhiNodeFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfPhiNodeFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromModule (i:phinode) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfPhiNodeFromProducts i ps.\n\nFixpoint getParentOfPhiNodeFromModules (i:phinode) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfPhiNodeFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfPhiNodeFromModules i lm'\n  end\nend.\n\nDefinition getParentOfPhiNodeFromSystem (i:phinode) (s:system) : option block :=\n  getParentOfPhiNodeFromModules i s.\n\nDefinition phinodeHasParent (i:phinode) (s:system) : bool :=\nmatch (getParentOfPhiNodeFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nFixpoint getParentOfTerminatorFromBlocks (i:terminator) (lb:blocks) {struct lb} : option block :=\nmatch lb with\n| nil => None\n| b::lb' =>\n  match (terminatorInBlockB_dec i b) with\n  | left _ => Some b\n  | right _ => getParentOfTerminatorFromBlocks i lb'\n  end\nend.\n\nDefinition getParentOfTerminatorFromFdef (i:terminator) (fd:fdef) : option block :=\nmatch fd with\n| (fdef_intro _ lb) => getParentOfTerminatorFromBlocks i lb\nend.\n\nDefinition getParentOfTerminatorFromProduct (i:terminator) (p:product) : option block :=\nmatch p with\n| (product_fdef fd) => getParentOfTerminatorFromFdef i fd\n| _ => None\nend.\n\nFixpoint getParentOfTerminatorFromProducts (i:terminator) (lp:products) {struct lp} : option block :=\nmatch lp with\n| nil => None\n| p::lp' =>\n  match (getParentOfTerminatorFromProduct i p) with\n  | Some b => Some b\n  | None => getParentOfTerminatorFromProducts i lp'\n  end\nend.\n\nDefinition getParentOfTerminatorFromModule (i:terminator) (m:module) : option block :=\n  let (os, nts, ps) := m in\n  getParentOfTerminatorFromProducts i ps.\n\nFixpoint getParentOfTerminatorFromModules (i:terminator) (lm:modules) {struct lm} : option block :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (getParentOfTerminatorFromModule i m) with\n  | Some b => Some b\n  | None => getParentOfTerminatorFromModules i lm'\n  end\nend.\n\nDefinition getParentOfTerminatorFromSystem (i:terminator) (s:system) : option block :=\n  getParentOfTerminatorFromModules i s.\n\nDefinition terminatoreHasParent (i:terminator) (s:system) : bool :=\nmatch (getParentOfTerminatorFromSystem i s) with\n| Some _ => true\n| None => false\nend.\n\nLemma productInModuleB_dec : forall b m,\n  {productInModuleB b m = true} + {productInModuleB b m = false}.\nProof.\n  intros b m. destruct (productInModuleB b m); auto.\nQed.\n\nFixpoint getParentOfFdefFromModules (fd:fdef) (lm:modules) {struct lm} : option module :=\nmatch lm with\n| nil => None\n| m::lm' =>\n  match (productInModuleB_dec (product_fdef fd) m) with\n  | left _ => Some m\n  | right _ => getParentOfFdefFromModules fd lm'\n  end\nend.\n\nDefinition getParentOfFdefFromSystem (fd:fdef) (s:system) : option module :=\n  getParentOfFdefFromModules fd s.\n\nNotation \"t =t= t' \" := (typEqB t t') (at level 50).\nNotation \"n =n= n'\" := (beq_nat n n') (at level 50).\nNotation \"b =b= b'\" := (blockEqB b b') (at level 50).\nNotation \"i =cmd= i'\" := (cmdEqB i i') (at level 50).\nNotation \"i =phi= i'\" := (phinodeEqB i i') (at level 50).\nNotation \"i =tmn= i'\" := (terminatorEqB i i') (at level 50).\n\n(**********************************)\n(* Check to make sure that if there is more than one entry for a\n   particular basic block in this PHI node, that the incoming values\n   are all identical. *)\nFixpoint lookupIdsViaLabelFromIdls\n  (idls:list (value * l)) (l0:l) : list id :=\nmatch idls with\n| nil => nil\n| (value_id id1, l1) :: idls' =>\n  if (eq_dec l0 l1)\n  then set_add eq_dec id1 (lookupIdsViaLabelFromIdls idls' l0)\n  else (lookupIdsViaLabelFromIdls idls' l0)\n| (_, l1) :: idls' =>\n  lookupIdsViaLabelFromIdls idls' l0\nend.\n\nFixpoint _checkIdenticalIncomingValues\n  (idls idls0:list (value * l)) : Prop :=\nmatch idls with\n| nil => True\n| (_, l) :: idls' =>\n  (length (lookupIdsViaLabelFromIdls idls0 l) <= 1)%nat /\\\n  (_checkIdenticalIncomingValues idls' idls0)\nend.\n\nDefinition checkIdenticalIncomingValues (PN:phinode) : Prop :=\nmatch PN with\n| insn_phi _ _ idls => _checkIdenticalIncomingValues idls idls\nend.\n\n(**********************************)\n(* Instruction Signature *)\n\nModule Type SigValue.\n\n Parameter getNumOperands : insn -> nat.\n\nEnd SigValue.\n\nModule Type SigUser.\n Include SigValue.\n\nEnd SigUser.\n\nModule Type SigConstant.\n Include SigValue.\n\n Parameter getTyp : const -> option typ.\n\nEnd SigConstant.\n\nModule Type SigGlobalValue.\n Include SigConstant.\n\nEnd SigGlobalValue.\n\nModule Type SigFunction.\n Include SigGlobalValue.\n\n Parameter getDefReturnType : fdef -> typ.\n Parameter getDefFunctionType : fdef -> typ.\n Parameter def_arg_size : fdef -> nat.\n\n Parameter getDecReturnType : fdec -> typ.\n Parameter getDecFunctionType : fdec -> typ.\n Parameter dec_arg_size : fdec -> nat.\n\nEnd SigFunction.\n\nModule Type SigInstruction.\n Include SigUser.\n\n(* Parameter isInvokeInst : insn -> bool. *)\n Parameter isCallInst : cmd -> bool.\n\nEnd SigInstruction.\n\nModule Type SigReturnInst.\n Include SigInstruction.\n\n Parameter hasReturnType : terminator -> bool.\n Parameter getReturnType : terminator -> option typ.\n\nEnd SigReturnInst.\n\nModule Type SigCallSite.\n(* Parameter getCalledFunction : cmd -> system -> option fdef. *)\n Parameter getFdefTyp : fdef -> typ.\n Parameter arg_size : fdef -> nat.\n Parameter getArgument : fdef -> nat -> option arg.\n Parameter getArgumentType : fdef -> nat -> option typ.\n\nEnd SigCallSite.\n\nModule Type SigCallInst.\n Include SigInstruction.\n\nEnd SigCallInst.\n\n(*\nModule Type SigInvokeInst.\n Include SigInstruction.\n\n Parameter getNormalDest : system -> insn -> option block.\n\nEnd SigInvokeInst.\n*)\n\nModule Type SigBinaryOperator.\n Include SigInstruction.\n\n Parameter getFirstOperandType : fdef -> cmd -> option typ.\n Parameter getSecondOperandType : fdef -> cmd -> option typ.\n Parameter getResultType : cmd -> option typ.\n\nEnd SigBinaryOperator.\n\nModule Type SigPHINode.\n Include SigInstruction.\n\n Parameter getNumIncomingValues : phinode -> nat.\n Parameter getIncomingValueType : fdef  -> phinode -> i -> option typ.\nEnd SigPHINode.\n\n(* Type Signature *)\n\nModule Type SigType.\n Parameter isIntOrIntVector : typ -> bool.\n Parameter isInteger : typ -> bool.\n Parameter isSized : typ -> bool.\n Parameter getPrimitiveSizeInBits : typ -> sz.\nEnd SigType.\n\nModule Type SigDerivedType.\n Include SigType.\nEnd SigDerivedType.\n\nModule Type SigFunctionType.\n Include SigDerivedType.\n\n Parameter getNumParams : typ -> option nat.\n Parameter isVarArg : typ -> bool.\n Parameter getParamType : typ -> nat -> option typ.\nEnd SigFunctionType.\n\nModule Type SigCompositeType.\n Include SigDerivedType.\nEnd SigCompositeType.\n\nModule Type SigSequentialType.\n Include SigCompositeType.\n\n Parameter hasElementType : typ -> bool.\n Parameter getElementType : typ -> option typ.\n\nEnd SigSequentialType.\n\nModule Type SigArrayType.\n Include SigSequentialType.\n\n Parameter getNumElements : typ -> nat.\n\nEnd SigArrayType.\n\n(* Instruction Instantiation *)\n\nModule Value <: SigValue.\n\n Definition getNumOperands (i:insn) : nat :=\n   length (getInsnOperands i).\n\nEnd Value.\n\nModule User <: SigUser. Include Value.\n\nEnd User.\n\nModule Constant <: SigConstant.\n Include Value.\n\nFixpoint getTyp (c:const) : option typ :=\n match c with\n | const_zeroinitializer t => Some t\n | const_int sz _ => Some (typ_int sz)\n | const_floatpoint fp _ => Some (typ_floatpoint fp)\n | const_undef t => Some t\n | const_null t => Some (typ_pointer t)\n | const_arr t lc =>\n   Some\n   (match lc with\n   | nil => typ_array Size.Zero t\n   | c' :: lc' => typ_array (Size.from_nat (length lc)) t\n   end)\n | const_struct t lc => Some t\n(*\n   match getList_typ lc with\n   | Some lt => Some (typ_struct lt)\n   | None => None\n   end\n*)\n | const_gid t _ => Some (typ_pointer t)\n | const_truncop _ _ t => Some t\n | const_extop _ _ t => Some t\n | const_castop _ _ t => Some t\n | const_gep _ c idxs =>\n   match (getTyp c) with\n   | Some t => getConstGEPTyp idxs t\n   | _ => None\n   end\n | const_select c0 c1 c2 => getTyp c1\n | const_icmp c c1 c2 => Some (typ_int Size.One)\n | const_fcmp fc c1 c2 => Some (typ_int Size.One)\n | const_extractvalue c idxs =>\n   match (getTyp c) with\n   | Some t => getSubTypFromConstIdxs idxs t\n   | _ => None\n   end\n | const_insertvalue c c' lc => getTyp c\n | const_bop _ c1 c2 => getTyp c1\n | const_fbop _ c1 c2 => getTyp c1\n end.\n\nDefinition gen_utyps_maps_aux_\n  (gen_utyp_maps_aux : id -> list (id * typ) -> typ -> option typ) :=\nfix gen_utyps_maps_aux\n(cid:id) (m:list(id*typ)) (ts:list typ) : option (list typ) :=\nmatch ts with\n  | nil => Some nil\n  | t0 :: ts0 =>\n    do ut0 <- gen_utyp_maps_aux cid m t0;\n    do uts0 <- gen_utyps_maps_aux cid m ts0;\n    ret (ut0 :: uts0)\nend.\n\nFixpoint gen_utyp_maps_aux (cid:id) (m:list(id*typ)) (t:typ) : option typ :=\n match t with\n | typ_int s => Some (typ_int s)\n | typ_floatpoint f => Some (typ_floatpoint f)\n | typ_void => Some typ_void\n | typ_label => Some typ_label\n | typ_metadata => Some typ_metadata\n | typ_array s t0 =>\n   do ut0 <- gen_utyp_maps_aux cid m t0;\n   ret (typ_array s ut0)\n | typ_function t0 ts0 va =>\n     do ut0 <- gen_utyp_maps_aux cid m t0;\n     do uts0 <- gen_utyps_maps_aux_ gen_utyp_maps_aux cid m ts0;\n        ret (typ_function ut0 uts0 va)\n | typ_struct ts0 =>\n     do uts0 <- gen_utyps_maps_aux_ gen_utyp_maps_aux cid m ts0;\n     ret (typ_struct uts0)\n | typ_pointer t0 =>\n     match gen_utyp_maps_aux cid m t0 with\n     | Some ut0 => Some (typ_pointer ut0)\n     | None =>\n         match t0 with\n         | typ_namedt i => if eq_atom_dec i cid then Some t else None\n         | _ => None\n         end\n     end\n(* | typ_opaque => Some typ_opaque *)\n | typ_namedt i => lookupAL _ m i\n end.\n\nDefinition gen_utyps_maps_aux :=\n  gen_utyps_maps_aux_ gen_utyp_maps_aux.\n\nFixpoint gen_utyp_maps (nts:namedts) : list (id*typ) :=\nmatch nts with\n| nil => nil\n| (id0, t)::nts' =>\n  let results := gen_utyp_maps nts' in\n  match gen_utyp_maps_aux id0 results (typ_struct t) with\n  | None => results\n  | Some r => (id0, r)::results\n  end\nend.\n\nDefinition typs2utyps_aux_\n  (typ2utyp_aux : list (id * typ) -> typ -> option typ) :=\nfix typs2utyps_aux (m:list(id*typ)) (ts:list typ) : option (list typ) :=\n match ts with\n | nil => Some nil\n | t0 :: ts0 =>\n     do ut0 <- typ2utyp_aux m t0;\n     do uts0 <- typs2utyps_aux m ts0;\n     ret (ut0 :: uts0)\n end.\n\nFixpoint typ2utyp_aux (m:list(id*typ)) (t:typ) : option typ :=\n match t with\n | typ_int s => Some (typ_int s)\n | typ_floatpoint f => Some (typ_floatpoint f)\n | typ_void => Some typ_void\n | typ_label => Some typ_label\n | typ_metadata => Some typ_metadata\n | typ_array s t0 => do ut0 <- typ2utyp_aux m t0; ret (typ_array s ut0)\n | typ_function t0 ts0 va =>\n     do ut0 <- typ2utyp_aux m t0;\n     do uts0 <- typs2utyps_aux_ typ2utyp_aux m ts0;\n        ret (typ_function ut0 uts0 va)\n | typ_struct ts0 =>\n   do uts0 <- typs2utyps_aux_ typ2utyp_aux m ts0;\n   ret (typ_struct uts0)\n | typ_pointer t0 =>\n   do ut0 <- typ2utyp_aux m t0;\n   ret (typ_pointer ut0)\n(* | typ_opaque => Some typ_opaque *)\n | typ_namedt i => lookupAL _ m i\n end.\n\nDefinition typs2utyps_aux :=\n  typs2utyps_aux_ typ2utyp_aux.\n\nDefinition typ2utyp' (nts:namedts) (t:typ) : option typ :=\nlet m := gen_utyp_maps (List.rev nts) in\ntyp2utyp_aux m t.\n\nFixpoint subst_typ (i':id) (t' t:typ) : typ :=\n\n  let subst_typs :=\n    fix subst_typs (i':id) (t':typ) (ts:list typ) : list typ :=\n    match ts with\n    | nil => nil\n    | t0 :: ts0 =>\n     (subst_typ i' t' t0) :: (subst_typs i' t' ts0)\n    end in\n\n match t with\n | typ_int _ | typ_floatpoint _ | typ_void | typ_label | typ_metadata => t\n | typ_array s t0 => typ_array s (subst_typ i' t' t0)\n | typ_function t0 ts0 va =>\n     typ_function (subst_typ i' t' t0) (subst_typs i' t' ts0) va\n | typ_struct ts0 => typ_struct (subst_typs i' t' ts0)\n | typ_pointer t0 => typ_pointer (subst_typ i' t' t0)\n | typ_namedt i => if (eq_atom_dec i i') then t' else t\n end.\n\nFixpoint subst_typ_by_nts (nts:namedts) (t:typ) : typ :=\nmatch nts with\n| nil => t\n| (id', ts')::nts' =>\n    subst_typ_by_nts nts' (subst_typ id' (typ_struct ts') t)\nend.\n\nFixpoint subst_nts_by_nts (nts0 nts:namedts) : list (id*typ) :=\nmatch nts with\n| nil => nil\n| (id', t')::nts' =>\n    (id',(subst_typ_by_nts nts0 (typ_struct t')))::subst_nts_by_nts nts0 nts'\nend.\n\nDefinition typ2utyp (nts:namedts) (t:typ) : option typ :=\nlet m := subst_nts_by_nts nts nts in\ntyp2utyp_aux m t.\n\nDefinition unifiable_typ (TD:LLVMtd.TargetData) (t:typ) : Prop :=\n  let '(los,nts) := TD in\n  exists ut, typ2utyp nts t = Some ut /\\\n    LLVMtd.getTypeAllocSize TD ut = LLVMtd.getTypeAllocSize TD t.\n\nEnd Constant.\n\nModule GlobalValue <: SigGlobalValue.\n Include Constant.\n\nEnd GlobalValue.\n\nModule Function <: SigFunction.\n Include GlobalValue.\n\n Definition getDefReturnType (fd:fdef) : typ :=\n match fd with\n | fdef_intro (fheader_intro _ t _ _ _ ) _ => t\n end.\n\n Definition getDefFunctionType (fd:fdef) : typ := getFdefTyp fd.\n\n Definition def_arg_size (fd:fdef) : nat :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) => length la\n end.\n\n Definition getDecReturnType (fd:fdec) : typ :=\n match fd with\n | fdec_intro (fheader_intro _ t _ _ _ ) _ => t\n end.\n\n Definition getDecFunctionType (fd:fdec) : typ := getFdecTyp fd.\n\n Definition dec_arg_size (fd:fdec) : nat :=\n match fd with\n | fdec_intro (fheader_intro _ _ _ la _) _ => length la\n end.\n\nEnd Function.\n\nModule Instruction <: SigInstruction.\n Include User.\n\n(* Definition isInvokeInst (i:insn) : bool := isInvokeInsnB i. *)\n Definition isCallInst (i:cmd) : bool := _isCallInsnB i.\n\nEnd Instruction.\n\nModule ReturnInst <: SigReturnInst.\n Include Instruction.\n\n Definition hasReturnType (i:terminator) : bool :=\n match i with\n | insn_return _ t v => true\n | _ => false\n end.\n\n Definition getReturnType (i:terminator) : option typ :=\n match i with\n | insn_return _ t v => Some t\n | _ => None\n end.\n\nEnd ReturnInst.\n\nModule CallSite <: SigCallSite.\n\n Definition getFdefTyp (fd:fdef) : typ := getFdefTyp fd.\n\n Definition arg_size (fd:fdef) : nat :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) => length la\n end.\n\n Definition getArgument (fd:fdef) (i:nat) : option arg :=\n match fd with\n | (fdef_intro (fheader_intro _ _ _ la _) _) =>\n    match (nth_error la i) with\n    | Some a => Some a\n    | None => None\n    end\n end.\n\n Definition getArgumentType (fd:fdef) (i:nat) : option typ :=\n match (getArgument fd i) with\n | Some (t, _, _) => Some t\n | None => None\n end.\n\nEnd CallSite.\n\nModule CallInst <: SigCallInst.\n Include Instruction.\n\nEnd CallInst.\n\nModule BinaryOperator <: SigBinaryOperator.\n Include Instruction.\n\n Definition getFirstOperandType (f:fdef) (i:cmd) : option typ :=\n match i with\n | insn_bop _ _ _ v1 _ =>\n   match v1 with\n   | value_id id1 => lookupTypViaIDFromFdef f id1\n   | value_const c => Constant.getTyp c\n   end\n | _ => None\n end.\n\n Definition getSecondOperandType (f:fdef) (i:cmd) : option typ :=\n match i with\n | insn_bop _ _ _ _ v2 =>\n   match v2 with\n   | value_id id2 => lookupTypViaIDFromFdef f id2\n   | value_const c => Constant.getTyp c\n   end\n | _ => None\n end.\n\n Definition getResultType (i:cmd) : option typ := getCmdTyp i.\n\nEnd BinaryOperator.\n\nModule PHINode <: SigPHINode.\n Include Instruction.\n\n Definition getNumIncomingValues (i:phinode) : nat :=\n match i with\n | (insn_phi _ _ ln) => (length ln)\n end.\n\n Definition getIncomingValueType (f:fdef) (i:phinode) (n:nat) : option typ :=\n match i with\n | (insn_phi _ _ ln) =>\n    match (nth_error ln n) with\n    | Some (value_id id, _) => lookupTypViaIDFromFdef f id\n    | Some (value_const c, _) => Constant.getTyp c\n    | None => None\n    end\n end.\n\nEnd PHINode.\n\n(* Type Instantiation *)\n\nModule Typ <: SigType.\n Definition isIntOrIntVector (t:typ) : bool :=\n match t with\n | typ_int _ => true\n | _ => false\n end.\n\n Definition isInteger (t:typ) : bool :=\n match t with\n | typ_int _ => true\n | _ => false\n end.\n\n (* isSizedDerivedType - Derived types like structures and arrays are sized\n    iff all of the members of the type are sized as well.  Since asking for\n    their size is relatively uncommon, move this operation out of line.\n\n    isSized - Return true if it makes sense to take the size of this type.  To\n    get the actual size for a particular target, it is reasonable to use the\n    TargetData subsystem to do this. *)\n Fixpoint isSized (t:typ) : bool :=\n   let isSizedListTyp :=\n     fix isSizedListTyp (lt : list typ) : bool :=\n     match lt with\n     | nil => true\n     | t :: lt' => isSized t && isSizedListTyp lt'\n     end in\n match t with\n | typ_int _ => true\n | typ_floatpoint _ => true\n | typ_array _ t' => isSized t'\n | typ_struct lt => isSizedListTyp lt\n | typ_pointer _ => true\n | _ => false\n end.\n\n  Definition getPrimitiveSizeInBits (t:typ) : sz :=\n  match t with\n  | typ_int sz => sz\n  | _ => Size.Zero\n  end.\n\nEnd Typ.\n\nModule DerivedType <: SigDerivedType.\n Include Typ.\nEnd DerivedType.\n\nModule FunctionType <: SigFunctionType.\n Include DerivedType.\n\n Definition getNumParams (t:typ) : option nat :=\n match t with\n | (typ_function _ lt _) =>\n     Some (length lt)\n | _ => None\n end.\n\n Definition isVarArg (t:typ) : bool := false.\n\n Definition getParamType (t:typ) (i:nat) : option typ :=\n match t with\n | (typ_function _ lt _) =>\n    match (nth_error lt i) with\n    | Some t => Some t\n    | None => None\n    end\n | _ => None\n end.\n\nEnd FunctionType.\n\nModule CompositeType <: SigCompositeType.\n Include DerivedType.\nEnd CompositeType.\n\nModule SequentialType <: SigSequentialType.\n Include CompositeType.\n\n Definition hasElementType (t:typ) : bool :=\n match t with\n | typ_array _ t' => true\n | _ => false\n end.\n\n Definition getElementType (t:typ) : option typ :=\n match t with\n | typ_array _ t' => Some t'\n | _ => None\n end.\n\nEnd SequentialType.\n\nModule ArrayType <: SigArrayType.\n Include SequentialType.\n\n Definition getNumElements (t:typ) : nat :=\n match t with\n | typ_array N _ => Size.to_nat N\n | _ => 0%nat\n end.\n\nEnd ArrayType.\n\nDefinition typ2memory_chunk (t:typ) : option AST.memory_chunk :=\n  match t with\n  | typ_int bsz => Some (AST.Mint (Size.to_nat bsz -1))\n  | typ_floatpoint fp_float => Some AST.Mfloat32\n  | typ_floatpoint fp_double => Some AST.Mfloat64\n  | typ_floatpoint _ => None\n  | typ_pointer _ => Some (AST.Mint 31)\n  | _ => None\n  end.\n\nDefinition wf_alignment (TD:LLVMtd.TargetData) (t:typ) : Prop :=\nforall s a (abi_or_pref:bool),\n  LLVMtd.getTypeSizeInBits_and_Alignment TD abi_or_pref t = Some (s,a) ->\n  (a > 0)%nat.\n\nDefinition typ_eq_list_typ (nts:namedts) (t1:typ) (ts2:list typ) : bool :=\nmatch t1 with\n| typ_struct ts1 => list_typ_dec ts1 ts2\n| typ_namedt nid1 =>\n    match lookupAL _ nts nid1 with\n    | Some ts1 => list_typ_dec ts1 ts2\n    | _ => false\n    end\n| _ => false\nend.\n\nDefinition wf_intrinsics_id (iid:intrinsic_id) (rt:typ) (pt:list typ) (va:varg)\n  : Prop :=\nTrue.\n\nDefinition wf_external_id (eid:external_id) (rt:typ) (pt:list typ) (va:varg)\n  : Prop :=\nmatch eid with\n| eid_malloc =>\n    match rt, pt with\n    | typ_pointer (typ_int 8%nat), (typ_int sz) :: nil =>\n        match sz with\n        | 32%nat | 64%nat => True\n        | _ => False\n        end\n    | _, _ => False\n    end\n| eid_free =>\n    match rt, pt with\n    | typ_void, (typ_pointer (typ_int 8%nat)) :: nil\n    | _, _ => False\n    end\n| eid_other => True\n| eid_io => True\nend.\n\nDefinition wf_deckind (fh:fheader) (dck:deckind) : Prop :=\nlet '(fheader_intro _ rt _ la va) := fh in\nlet pt := args2Typs la in\nmatch dck with\n| deckind_intrinsic iid => wf_intrinsics_id iid rt pt va\n| deckind_external eid => wf_external_id eid rt pt va\nend.\n\n(**********************************)\n(* reflect *)\n\nCoercion is_true (b:bool) := b = true.\n\nInductive reflect (P:Prop) : bool -> Set :=\n| ReflectT : P -> reflect P true\n| ReflectF : ~P -> reflect P false\n.\n\n(**********************************)\n(* get locs of a function *)\n\nDefinition getValueID' (v:value) : atoms :=\nmatch v with\n| value_id id => {{id}}\n| value_const _ => {}\nend.\n\nDefinition getFdefLocs fdef : ids :=\nmatch fdef with\n| fdef_intro (fheader_intro _ _ _ la _) bs => getArgsIDs la ++ getBlocksLocs bs\nend.\n\nDefinition id_fresh_in_value v1 i2 : Prop :=\nmatch v1 with\n| value_id i1 => i1 <> i2\n| _ => True\nend.\n\nFixpoint ids2atoms (ids0:ids) : atoms :=\nmatch ids0 with\n| nil => {}\n| id0::ids0' => {{id0}} `union` ids2atoms ids0'\nend.\n\nEnd LLVMinfra.\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/infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1663938473709247}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import auth.\nFrom Perennial.base_logic.lib Require Import proph_map.\nFrom Perennial.program_logic Require Export weakestpre.\nFrom Perennial.algebra Require Import gen_heap_names.\nFrom Perennial.goose_lang Require Import proofmode notation.\nSet Default Proof Using \"Type\".\n\n(** No actual adequacy theorem here, just definitions that are shared between\nrecovery_adequacy and (in the future) distrib_adequacy. *)\n\nClass ffi_interp_adequacy `{FFI: !ffi_interp ffi} `{EXT: !ffi_semantics ext ffi} :=\n  { ffi\u03a3: gFunctors;\n    ffiGpreS: gFunctors -> Type;\n    (* modeled after subG_gen_heapPreG and gen_heap_init *)\n    subG_ffiPreG : forall \u03a3, subG ffi\u03a3 \u03a3 -> ffiGpreS \u03a3;\n    ffi_initgP: ffi_global_state \u2192 Prop;\n    (* Valid local starting states may depend on whatever the current global state is. *)\n    ffi_initP: ffi_state \u2192 ffi_global_state \u2192 Prop;\n    ffi_global_init : forall \u03a3 (hPre: ffiGpreS \u03a3) (g:ffi_global_state),\n        ffi_initgP g \u2192\n          \u22a2 |==> \u2203 (hG: ffiGlobalGS \u03a3),\n              ffi_global_ctx hG g \u2217 ffi_global_start hG g;\n    ffi_local_init : forall \u03a3 (hPre: ffiGpreS \u03a3) (\u03c3:ffi_state) (g:ffi_global_state),\n        ffi_initP \u03c3 g \u2192\n          \u22a2 |==> \u2203 (hL: ffiLocalGS \u03a3),\n                   ffi_local_ctx hL \u03c3 \u2217 ffi_local_start hL \u03c3;\n    ffi_crash : forall \u03a3,\n          \u2200 (\u03c3 \u03c3': ffi_state) (CRASH: ffi_crash_step \u03c3 \u03c3') (Hold: ffiLocalGS \u03a3),\n           \u22a2 ffi_local_ctx Hold \u03c3 ==\u2217\n             \u2203 (Hnew: ffiLocalGS \u03a3), ffi_local_ctx Hnew \u03c3' \u2217\n                                 ffi_crash_rel \u03a3 Hold \u03c3 Hnew \u03c3' \u2217\n                                 ffi_restart Hnew \u03c3';\n  }.\n\n(* this is the magic that lets subG_ffiPreG solve for an ffiGpreS using only\ntypeclass resolution, which is the one thing solve_inG tries. *)\nExisting Class ffiGpreS.\n#[global]\nHint Resolve subG_ffiPreG : typeclass_instances.\n\nClass gooseGpreS `{ext: ffi_syntax} `{EXT_SEM: !ffi_semantics ext ffi}\n      `{INTERP: !ffi_interp ffi} `{!ffi_interp_adequacy} \u03a3\n  := GooseGpreS {\n  goose_preG_iris :> invGpreS \u03a3;\n  goose_preG_crash :> crashGpreS \u03a3;\n  goose_preG_heap :> na_heapGpreS loc val \u03a3;\n  goose_preG_proph :> proph_mapGpreS proph_id val \u03a3;\n  goose_preG_ffi :> ffiGpreS \u03a3;\n  goose_preG_trace :> trace_preG \u03a3;\n  goose_preG_credit :> credit_preG \u03a3;\n}.\n\nLtac solve_inG_deep :=\n  intros;\n  (* XXX: had to add cases with more _'s compared to solve_inG to get this work *)\n   lazymatch goal with\n   | H:subG (?x\u03a3 _ _ _ _ _ _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG (?x\u03a3 _ _ _ _ _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG (?x\u03a3 _ _ _ _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG (?x\u03a3 _ _ _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG (?x\u03a3 _ _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG (?x\u03a3 _) _ |- _ => try unfold x\u03a3 in H\n   | H:subG ?x\u03a3 _ |- _ => try unfold x\u03a3 in H\n   end; repeat match goal with\n               | H:subG (gFunctors.app _ _) _ |- _ => apply subG_inv in H; destruct H\n               end; repeat match goal with\n                           | H:subG _ _ |- _ => move : H; apply subG_inG in H || clear H\n                           end; intros; try done; split; assumption || by apply _.\n\nDefinition heap\u03a3 `{ext: ffi_syntax} `{ffi_interp_adequacy} : gFunctors :=\n  #[inv\u03a3; crash\u03a3; na_heap\u03a3 loc val; proph_map\u03a3 proph_id val; ffi\u03a3; trace\u03a3; credit\u03a3].\n#[global]\nInstance subG_heapPreG `{ext: ffi_syntax} `{@ffi_interp_adequacy ffi Hinterp ext EXT} {\u03a3} :\n  subG heap\u03a3 \u03a3 \u2192 gooseGpreS \u03a3.\nProof.\n  solve_inG_deep.\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/goose_lang/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.1663938473709247}}
{"text": "Require Import HoareDef OpenDef STB Repeat1 Add0 Add1 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics ProofMode Invariant.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\n\n\nSection SIMMODSEM.\n\n  Context `{\u03a3: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Variable FunStb: Sk.t -> gname -> option fspec.\n  Variable GlobalStb: Sk.t -> gname -> option fspec.\n\n  Let wf: _ -> W -> Prop :=\n    @mk_wf\n      _\n      unit\n      (fun _ _ _ => True%I)\n  .\n\n  Hypothesis FunStb_succ: forall skenv,\n      fn_has_spec (FunStb skenv) \"succ\" (Add1.succ_spec).\n\n  Hypothesis GlobalStb_repeat: forall skenv,\n      fn_has_spec (GlobalStb skenv) \"repeat\" (Repeat1.repeat_spec FunStb skenv).\n\n  Theorem correct: refines2 [Add0.Add] [Add1.Add GlobalStb].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); ss.\n    2: { esplits; et. red. econs. eapply to_semantic. et. }\n    eapply Sk.incl_incl_env in SKINCL. eapply Sk.load_skenv_wf in SKWF.\n    hexploit (SKINCL \"succ\"); ss; eauto. intros [blk0 FIND0].\n    econs; ss.\n    { unfold succF. init.\n      2: { harg. mDesAll. des; clarify. steps. hret _; ss. }\n      harg. mDesAll. des; clarify.\n      steps. astart 0. astop. steps. force_l. eexists.\n      steps. hret _; ss.\n    }\n    econs; ss.\n    { unfold addF, add_body. init. harg. mDesAll. des; clarify.\n      steps.  rewrite FIND0. steps. unfold ccallU. steps.\n      hexploit FunStb_succ. i. inv H.\n      assert (exists m, z0 = Z.of_nat m).\n      { exists (Z.to_nat z0). rewrite Z2Nat.id; auto. lia. } des. subst.\n      hexploit GlobalStb_repeat; et. i. inv H. astart 1. acatch; et.\n      hcall_weaken (Repeat1.repeat_spec FunStb sk) (_, _, _, Z.succ) _ with \"\"; et.\n      { iPureIntro. splits; et. econs.\n        { eapply SKWF. eauto. }\n        econs.\n        { et. }\n        { etrans; [|et]. econs. ss. esplits; ss; et. eapply Ord.lt_le. eapply Ord.omega_upperbound. }\n      }\n      { splits; ss. }\n      mDesAll. des; clarify. steps. astop. steps. hret _; ss.\n      iPureIntro. esplits; et.\n      f_equal. f_equal. clear. generalize z. induction m; ss; i.\n      { lia. }\n      { rewrite <- IHm. lia. }\n    }\n    Unshelve. all:ss. all:try (exact 0).\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/repeat/Add01proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.16639384737092466}}
{"text": "Require Import Coq.Arith.EqNat.\nRequire Import Coq.Bool.Bool.\nRequire Import FunctionalExtensionality.\nRequire Import List.\nRequire Import FJ_tactics.\nRequire Import Functors.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import PNames.\nRequire Import EffPure.\nRequire Import EffReader.\n\nSection ESoundR.\n\n  Variable D : Set -> Set.\n  Context {Fun_D : Functor D}.\n  Let DType := DType D.\n\n  Context {eq_DType_DT : forall T, FAlgebra eq_DTypeName T (eq_DTypeR D) D}.\n\n\n  Variable F : Set -> Set -> Set.\n  Context {Fun_F : forall A, Functor (F A)}.\n  Let Exp (A : Set) := Exp (F A).\n\n  Variable MT : Set -> Set.\n  Context {Fun_MT : Functor MT}.\n  Context {Mon_MT : Monad MT}.\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 V : Set -> Set.\n  Context {Fun_V : Functor V}.\n  Let Value := Value V.\n\n  Variable (ME : Set -> Set). (* Evaluation Monad. *)\n  Context {Fun_ME : Functor ME}.\n  Context {Mon_ME : Monad ME}.\n  Context {Fail_ME : FailMonad ME}.\n  Context {Environment_ME : Environment ME (Env Value)}.\n\n  Context {eval_F : FAlgebra EvalName (Exp nat) (evalR V) (F nat)}.\n  Context {evalM_F : FAlgebra EvalName (Exp nat) (evalMR V ME) (F nat)}.\n\n  Variable EQV_E : forall A B, (eqv_i F A B -> Prop) -> eqv_i F A B -> Prop.\n  Let E_eqv A B := iFix (EQV_E A B).\n  Let E_eqvC {A B : Set} gamma gamma' e e' :=\n    E_eqv _ _ (mk_eqv_i _ A B gamma gamma' e e').\n  Context {funEQV_E : forall A B, iFunctor (EQV_E A B)}.\n  Context {Typeof_F : forall T, FAlgebra TypeofName T (typeofR D MT) (F DType)}.\n\n\n    Variable WFV' : (WFValue_i D V (list (Names.DType D)) -> Prop) -> WFValue_i D V (list (Names.DType D)) -> Prop.\n    Context {funWFV' : iFunctor WFV'}.\n    Variable WFVM' : (WFValueM_i D V MT ME (list (Names.DType D)) -> Prop) ->\n      WFValueM_i D V MT ME (list (Names.DType D)) -> Prop.\n    Context {funWFVM' : iFunctor WFVM'}.\n\n    Global Instance GammaTypContextCE' : ConsExtensionC (list (Names.DType D)) :=\n      {| ConsExtension := fun Sigma' Sigma =>\n        forall n T, lookup Sigma n = Some T -> lookup Sigma' n = Some T |}.\n    Proof.\n      (* ConsExtension_id *)\n      eauto.\n      (* ConsExtension_trans *)\n      eauto.\n    Defined.\n\n    Context {WFV_Weaken'_WFV : iPAlgebra WFValue_Weaken'_Name (WFValue_Weaken'_P D V _ WFV') WFV'}.\n\n  Global Instance Pure_Sound_X_WFVM_Environment :\n    iPAlgebra Pure_Sound_X_Name (Pure_Sound_X_P D V MT ME WFV')\n    (WFValueM_Environment D MT V ME (TypContextCE := GammaTypContextCE _) _ WFV').\n  Proof.\n    econstructor.\n    unfold iAlgebra; intros; apply (ind_alg_WFVM_Environment D MT V ME) with (WFV := WFV')\n      (TypContextCE := GammaTypContextCE _)\n      (GammaTypContext := GammaTypContext _);\n      try eassumption; unfold Pure_Sound_X_P; simpl; intros.\n    (* WFVM_Local *)\n    destruct (H0 gamma'' WF_gamma'' _ _ WF_gamma'' H1) as [eval_fail | [v [eval_k WF_v_T0]]].\n    generalize ask_query; unfold wbind; intro ask_query'.\n    rewrite local_bind, local_ask, ask_query', <- left_unit; auto.\n    right; exists v; repeat split; auto.\n    generalize ask_query; unfold wbind; intro ask_query'.\n    rewrite local_bind, local_ask, ask_query', <- left_unit.\n    apply eval_k; auto.\n      (* WFVM_Ask *)\n    rewrite local_bind, local_local; unfold Basics.compose.\n    destruct (H1 _ _ (H0 _ WF_gamma'') (refl_equal _)) as [eval_fail | [v [eval_m WF_v_T']]].\n    left; unfold Env, DType, Value in *|-*; rewrite eval_fail, bind_fail; auto.\n    subst; destruct (H2 _ _ (refl_equal _) (WFV_Weaken' D V _ WFV' _ WF_v_T' Sigma)\n      _ _ WF_gamma'' (refl_equal _) )\n    as [eval_fail | [v' [eval_k WF_v'_T0]]]; simpl in *|-*.\n    left; unfold Env, DType, Value in *|-*; rewrite eval_m, <- left_unit, eval_fail; auto.\n    right; exists v'; repeat split; auto.\n    unfold Env, Value; rewrite eval_m, <- left_unit; auto.\n  Qed.\n\n\nEnd ESoundR.\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/ESoundR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.16625223879327594}}
{"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 TrapArg                               *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\n(*Require Import LAsmModuleSemAux.*)\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import LoadStoreSem2.\n\nRequire Import TTrapArg.\nRequire Import TrapArgGenSpec.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := pproc_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := pproc_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** Relation between raw data at two layers*)\n    Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n      mkrelate_RData {\n          flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n          devout_re: devout hadt = devout ladt;\n          CR3_re:  CR3 hadt = CR3 ladt;\n          ikern_re: ikern hadt = ikern ladt;\n          pg_re: pg hadt = pg ladt;\n          ihost_re: ihost hadt = ihost ladt;\n          AC_re: AC hadt = AC ladt;\n          ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n          ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n          LAT_re: LAT hadt = LAT ladt;\n          nps_re: nps hadt = nps ladt;\n          init_re: init hadt = init ladt;\n\n          pperm_re: pperm hadt = pperm ladt;\n          PT_re:  PT hadt = PT ladt;\n          ptp_re: ptpool hadt = ptpool ladt;\n          idpde_re: idpde hadt = idpde ladt;\n          ipt_re: ipt hadt = ipt ladt;\n          smspool_re: smspool hadt = smspool ladt;\n\n          kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n          abtcb_re:  abtcb hadt = abtcb ladt;\n          abq_re:  abq hadt = abq ladt;\n          cid_re:  cid hadt = cid ladt;\n          chpool_re:  syncchpool hadt = syncchpool ladt;\n          uctxt_re: uctxt_inj f (uctxt hadt) (uctxt ladt);\n          vmxinfo_re: vmxinfo hadt = vmxinfo ladt\n\n        }.\n\n    Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n    | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n    Local Hint Resolve MATCH_RDATA.\n\n    Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n      {\n        relate_AbData s f d1 d2 := relate_RData f d1 d2;\n        match_AbData s d1 m f := match_RData s d1 m f;\n        new_glbl := nil\n      }.    \n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n        - eapply kctxt_inj_incr; eauto.\n        - eapply uctxt_inj_incr; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      (** ** The low level specifications exist*)\n      Section Exists.\n\n        Lemma uctx_argn_exist':\n          forall n s habd z labd f,        \n            uctx_argn_spec n habd = Some z ->\n            0 <= n < UCTXT_SIZE ->\n            0 <= cid habd < num_proc ->\n            relate_AbData s f habd labd ->\n            uctx_argn_spec n labd = Some z\n            /\\ kernel_mode labd.\n        Proof.\n          intros. split.\n          - eapply uctx_argn_exist; eauto.\n          - unfold uctx_argn_spec in *.\n            inv H2. revert H; subrewrite.\n            simpl; subdestruct. eauto.\n        Qed.\n\n        Lemma uctx_set_regk_exist':\n          forall k s habd habd' labd n f,\n            uctx_set_regk_spec k n habd = Some habd'\n            -> relate_AbData s f habd labd\n            -> 0 <= cid habd < num_proc\n            -> exists labd', uctx_set_regk_spec k n labd = Some labd'\n                             /\\ relate_AbData s f habd' labd'\n                             /\\ kernel_mode labd.\n        Proof.\n          intros. exploit uctx_set_regk_exist; eauto.\n          intros (labd' & He & HR).\n          refine_split'; eauto.\n          unfold uctx_set_regk_spec in He.\n          simpl; subdestruct. eauto.\n        Qed.\n \n      End Exists.\n\n      Section FRESH_PRIM.\n\n        Lemma uctx_arg1_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg1_spec) uctx_arg1_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_arg2_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg2_spec) uctx_arg2_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_arg3_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg3_spec) uctx_arg3_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_arg4_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg4_spec) uctx_arg4_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).        \n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_arg5_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg5_spec) uctx_arg5_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_arg6_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_arg6_spec) uctx_arg6_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_argn_exist'; eauto 1.\n          - omega.\n          - eapply valid_curid; eauto.\n          - intros [HP Hkern].\n            refine_split; try econstructor; eauto.\n        Qed.\n\n        Lemma uctx_set_errno_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_set_errno_spec) uctx_set_errno_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_set_regk_exist'; eauto 1.\n          - eapply valid_curid; eauto.\n          - intros [labd' [HP [HM Hkern]]].\n            refine_split; try econstructor; eauto. \n            constructor.\n        Qed.\n\n        Lemma uctx_set_retval1_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_set_retval1_spec) uctx_set_retval1_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_set_regk_exist'; eauto 1.\n          - eapply valid_curid; eauto.\n          - intros [labd' [HP [HM Hkern]]].\n            refine_split; try econstructor; eauto. \n            constructor.\n        Qed.\n\n        Lemma uctx_set_retval2_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_set_retval2_spec) uctx_set_retval2_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_set_regk_exist'; eauto 1.\n          - eapply valid_curid; eauto.\n          - intros [labd' [HP [HM Hkern]]].\n            refine_split; try econstructor; eauto. \n            constructor.\n        Qed.\n\n        Lemma uctx_set_retval3_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_set_retval3_spec) uctx_set_retval3_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_set_regk_exist'; eauto 1.\n          - eapply valid_curid; eauto.\n          - intros [labd' [HP [HM Hkern]]].\n            refine_split; try econstructor; eauto. \n            constructor.\n        Qed.\n\n        Lemma uctx_set_retval4_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem uctx_set_retval4_spec) uctx_set_retval4_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit uctx_set_regk_exist'; eauto 1.\n          - eapply valid_curid; eauto.\n          - intros [labd' [HP [HM Hkern]]].\n            refine_split; try econstructor; eauto. \n            constructor.\n        Qed.\n\n      End FRESH_PRIM.\n\n      Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n      Proof.\n        accessor_prop_tac.\n        - eapply flatmem_store_exists; eauto.\n      Qed.\n\n      Lemma passthrough_correct:\n        sim (crel HDATA LDATA) ttraparg_passthrough pproc.\n      Proof.\n        sim_oplus.\n        - apply fload_sim.\n        - apply fstore_sim.\n        - apply device_output_sim.\n        (*- apply pfree_sim.*)\n        - apply ptRead_sim. \n        - apply ptResv_sim.\n        - apply shared_mem_status_sim.\n        - apply offer_shared_mem_sim.\n        - apply get_curid_sim.\n        - apply thread_wakeup_sim.\n        (*- apply is_chan_ready_sim.\n          - apply sendto_chan_sim.\n          - apply receive_chan_sim.*)\n        - apply syncreceive_chan_sim.\n        - apply syncsendto_chan_pre_sim.\n        - apply syncsendto_chan_post_sim.\n        - apply uctx_get_sim.\n        - apply uctx_set_sim.\n        - apply proc_create_sim.\n          (*\n        - apply rdmsr_sim.\n        - apply wrmsr_sim.\n        - apply vmx_set_intercept_intwin_sim.\n        - apply vmx_set_desc_sim.\n        - apply vmx_inject_event_sim.\n        - apply vmx_set_tsc_offset_sim.\n        - apply vmx_get_tsc_offset_sim.\n        - apply vmx_get_exit_reason_sim.\n        - apply vmx_get_exit_fault_addr_sim.\n        - apply vmx_check_pending_event_sim.\n        - apply vmx_check_int_shadow_sim.\n        - apply vmx_get_reg_sim.\n        - apply vmx_set_reg_sim.\n        - apply vmx_get_next_eip_sim.\n        - apply vmx_get_io_width_sim.\n        - apply vmx_get_io_write_sim.\n        - apply vmx_get_exit_io_rep_sim.\n        - apply vmx_get_exit_io_str_sim.\n        - apply vmx_get_exit_io_port_sim.\n        - apply vmx_set_mmap_sim.\n        - apply vm_run_sim, VMX_INJECT.\n        - apply vmx_return_from_guest_sim, VMX_INJECT.\n        - apply vmx_init_sim.\n        - apply vmx_init_sim.*)\n        - apply proc_init_sim.\n        - apply container_get_nchildren_sim.\n        - apply container_get_quota_sim.\n        - apply container_get_usage_sim.\n        - apply container_can_consume_sim.\n        - apply alloc_sim.\n        - apply trap_info_get_sim.\n        - apply trap_info_ret_sim.\n        - apply thread_yield_sim.\n        - apply thread_sleep_sim.\n        - apply proc_start_user_sim.\n          intros. eapply valid_curid; eauto.\n        - apply proc_exit_user_sim. \n        - layer_sim_simpl.\n          + eapply load_correct2.\n          + eapply store_correct2.\n      Qed.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/trap/TrapArgGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.16623118798850342}}
{"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.\nFrom dx Require Import ResultMonad IR.\nFrom bpf.comm Require Import MemRegion Regs State Monad rBPFAST rBPFValues rBPFMonadOp.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\n\nFrom compcert Require Import Coqlib Values Clight Memory Integers.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.clightlogic Require Import Clightlogic clight_exec CommonLemma CorrectRel.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n(*\nCheck get_mem_region.\n\nget_mem_region\n     : nat -> MyMemRegionsType -> M memory_region *)\n\nSection Get_mem_region.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  Definition args : list Type := [(nat:Type); (list memory_region:Type)].\n  Definition res : Type := (memory_region:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_mem_region.\n\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_mem_region.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n      (dcons (fun x => StateLess _ (nat_correct x))\n        (dcons (fun x => StateFull _ (mrs_correct S x))\n                (DList.DNil _))).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun r  => StateFull _ (mr_correct r).\n\nLemma memory_region_in_nth_error:\n  forall n l\n    (Hrange : (0 <= Z.of_nat n < Z.of_nat (List.length l))%Z),\n      exists (m:memory_region), nth_error l n = Some m.\nProof.\n  intros.\n  destruct Hrange as (Hlow & Hhigh).\n  rewrite <- Nat2Z.inj_lt in Hhigh.\n  rewrite <- List.nth_error_Some in Hhigh.\n  destruct (nth_error l n).\n  - exists m; reflexivity.\n  - exfalso; apply Hhigh; reflexivity.\nQed.\n\n\n  Instance correct_function_get_mem_region : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    unfold INV.\n    unfold f.\n    repeat intro; simpl.\n    destruct get_mem_region eqn: Hregion; [|constructor].\n    destruct p0.\n    intros.\n    get_invariant _n.\n    get_invariant _mrs.\n\n    unfold eval_inv, nat_correct in c1.\n    unfold eval_inv, mrs_correct, match_regions in c2.\n    destruct c1 as (c1 & _).\n    destruct c2 as (Hv0_eq & Hmrs_eq & (Hmrs_num_eq & Hrange & Hmatch) & Hst).\n    subst.\n    assert (MOD : m = m /\\ st = s).\n    {\n      unfold get_mem_region in Hregion.\n      destruct (c <? mrs_num st)%nat ; try discriminate.\n      destruct (nth_error (bpf_mrs st) c); try congruence.\n      intuition congruence.\n    }\n    destruct MOD ; subst.\n    eexists; exists m, Events.E0.\n    split_and; auto.\n    - {\n      unfold step2.\n      repeat forward_star.\n    }\n    -\n    unfold get_mem_region in Hregion.\n    context_destruct_if_inversion.\n    rewrite Nat.ltb_lt in Hcond.\n    unfold match_list_region in Hmatch.\n    rewrite Hmrs_num_eq in Hmatch.\n    assert (HrangeNat: (0 <= c < mrs_num s)%nat) by lia.\n    specialize (Hmatch c HrangeNat).\n    (**r because 0<=c < length mrs, so we know nth_error must return Some mr *)\n    assert (HrangeZ: (0 <= Z.of_nat c < Z.of_nat (mrs_num s))%Z) by lia.\n    rewrite <- Hmrs_num_eq in HrangeZ.\n    apply memory_region_in_nth_error with (n:=c) (l:= bpf_mrs s) in HrangeZ as Hnth_error.\n    destruct Hnth_error as (mr & Hnth_error).\n    rewrite Hnth_error in H2.\n    inversion H2.\n    eapply nth_error_nth in Hnth_error.\n    rewrite Hnth_error in Hmatch.\n    subst.\n    {\n      unfold match_res, mr_correct, match_region.\n      split.\n      apply nth_In; lia.\n      split; [| assumption].\n      rewrite Ptrofs.add_zero_l.\n      eexists.\n      split; [reflexivity |].\n      simpl.\n      unfold Ctypes.align_attr; simpl.\n      unfold Z.max, align; simpl.\n      unfold Ptrofs.of_intu, Ptrofs.of_int.\n      unfold Ptrofs.mul.\n      change (Ptrofs.unsigned (Ptrofs.repr 16)) with 16%Z.\n      rewrite Hmrs_num_eq in Hrange.\n      change Ptrofs.max_unsigned with Int.max_unsigned in Hrange.\n      assert (HrangeZ_of_Nat: (0 <= Z.of_nat c < Int.max_unsigned)%Z) by lia.\n      rewrite Int.unsigned_repr; [| lia].\n      change Int.max_unsigned with Ptrofs.max_unsigned in HrangeZ_of_Nat.\n      rewrite Ptrofs.unsigned_repr; [| lia].\n      assumption.\n    }\n    - constructor.\nQed.\n\nEnd Get_mem_region.\n\nExisting Instance correct_function_get_mem_region.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_mem_region.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16623118694534675}}
{"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(*| .. coq:: none |*)\n(** Coq Library *)\nRequire Import List.\nImport ListNotations. (* from List *)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Lists.ListDec.\n\n(** Oqarina library *)\nRequire Import Oqarina.core.all.\nRequire Import Oqarina.coq_utils.all.\n\nRequire Import Oqarina.AADL.Kernel.categories.\nRequire Import Oqarina.AADL.Kernel.component.\n(*| .. coq:: |*)\n\n(*|\nFeatures\n--------\n\n|*)\n\n(*| Valid_Features_Category |*)\n\nFixpoint Valid_Features_Category\n    (l : list feature)\n    (lcat : list FeatureCategory)\n:=\n    match l with\n        | nil => True\n        | h :: t => In (projectionFeatureCategory  h) lcat /\\\n                    Valid_Features_Category t lcat\n    end.\n\nLemma Valid_Features_Category_dec :\n    forall (l:list feature) (lcat :list FeatureCategory),\n        { Valid_Features_Category l lcat } +\n        { ~Valid_Features_Category l lcat }.\nProof.\n    prove_dec.\n    induction l.\n    auto.\n    apply dec_sumbool_and.\n    - apply In_dec; apply FeatureCategory_eq_dec.\n    - auto.\nQed.\n\n(** XXX Actually wrong, we must check for the direction of the feature as well *)\n\nDefinition Well_Formed_Component_Interface\n    (c: component) (l : list FeatureCategory) :=\n        Valid_Features_Category (c->features) l.\n\nLemma Well_Formed_Component_Interface_dec :\n    forall (c:component) (lcat :list FeatureCategory),\n        {Well_Formed_Component_Interface c lcat} +\n        { ~Well_Formed_Component_Interface c lcat}.\nProof.\n    prove_dec.\n    apply Valid_Features_Category_dec.\nQed.\n\nDefinition Well_Formed_Feature_Id (f : feature) : Prop :=\n  (Well_Formed_Identifier_prop (projectionFeatureIdentifier f)).\n\nLemma Well_Formed_Feature_Id_dec : forall f : feature,\n  {Well_Formed_Feature_Id f } + {~Well_Formed_Feature_Id f }.\nProof.\n    prove_dec.\nQed.\n\nDefinition Well_Formed_Feature_Ids (l : list feature) : Prop :=\n    All Well_Formed_Feature_Id l.\n\nLemma Well_Formed_Feature_Ids_dec : forall l : list feature,\n    { Well_Formed_Feature_Ids l } + { ~Well_Formed_Feature_Ids l }.\nProof.\n    prove_dec.\nQed.\n\nDefinition Features_Identifiers_Are_Unique (l : list feature) : Prop :=\n    (NoDup (Features_Identifiers l)).\n\nLemma Features_Identifiers_Are_Unique_dec :\n    forall l : list feature,\n        { Features_Identifiers_Are_Unique l } + { ~ Features_Identifiers_Are_Unique l }.\nProof.\n    prove_dec.\nQed.\n\nDefinition Well_Formed_Features (l : list feature) :=\n    Features_Identifiers_Are_Unique (l) /\\\n    Well_Formed_Feature_Ids l.\n\nLemma Well_Formed_Features_dec : forall l : list feature,\n    { Well_Formed_Features l } + { ~ Well_Formed_Features l }.\nProof.\n    prove_dec.\nQed.\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/legality/features_wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.16614735521618043}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import riscv.Utility.Monads. Import OStateOperations.\nRequire Import riscv.Utility.MonadNotations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Export riscv.Platform.RiscvMachine.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import riscv.Platform.Sane.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\nImport ListNotations.\n\nSection Riscv.\n\n  Context {width: Z} {BW: Bitwidth width} {word: word width} {word_ok: word.ok word}.\n  Context {Mem: map.map word byte}.\n  Context {Registers: map.map Register word}.\n\n  Definition update(f: RiscvMachine -> RiscvMachine): OState RiscvMachine unit :=\n    m <- get; put (f m).\n\n  Definition fail_if_None{R}(o: option R): OState RiscvMachine R :=\n    match o with\n    | Some x => Return x\n    | None => fail_hard\n    end.\n\n  Definition loadN(n: nat)(kind: SourceType)(a: word): OState RiscvMachine (HList.tuple byte n) :=\n    mach <- get;\n    v <- fail_if_None (Memory.load_bytes n mach.(getMem) a);\n    match kind with\n    | Fetch => if isXAddr4B a mach.(getXAddrs) then Return v else fail_hard\n    | _ => Return v\n    end.\n\n  Definition storeN(n: nat)(kind: SourceType)(a: word)(v: HList.tuple byte n) :=\n    mach <- get;\n    m <- fail_if_None (Memory.store_bytes n mach.(getMem) a v);\n    update (fun mach =>\n              withXAddrs (invalidateWrittenXAddrs n a mach.(getXAddrs)) (withMem m mach)).\n\n  Instance IsRiscvMachine: RiscvProgram (OState RiscvMachine) word :=  {\n      getRegister reg :=\n        if Z.eq_dec reg Register0 then\n          Return (ZToReg 0)\n        else\n          if (0 <? reg) && (reg <? 32) then\n            mach <- get;\n            match map.get mach.(getRegs) reg with\n            | Some v => Return v\n            | None => Return (word.of_Z 0)\n            end\n          else\n            fail_hard;\n\n      setRegister reg v :=\n        if Z.eq_dec reg Register0 then\n          Return tt\n        else\n          if (0 <? reg) && (reg <? 32) then\n            update (fun mach => withRegs (map.put mach.(getRegs) reg v) mach)\n          else\n            fail_hard;\n\n      getPC := mach <- get; Return mach.(getPc);\n\n      setPC newPC := update (withNextPc newPC);\n\n      loadByte   := loadN 1;\n      loadHalf   := loadN 2;\n      loadWord   := loadN 4;\n      loadDouble := loadN 8;\n\n      storeByte   := storeN 1;\n      storeHalf   := storeN 2;\n      storeWord   := storeN 4;\n      storeDouble := storeN 8;\n\n      makeReservation  addr := fail_hard;\n      clearReservation addr := fail_hard;\n      checkReservation addr := fail_hard;\n      getCSRField f := fail_hard;\n      setCSRField f v := fail_hard;\n      getPrivMode := fail_hard;\n      setPrivMode v := fail_hard;\n      fence _ _ := fail_hard;\n\n      endCycleNormal := update (fun m => (withPc m.(getNextPc)\n                                         (withNextPc (word.add m.(getNextPc) (word.of_Z 4)) m)));\n\n      (* fail hard if exception is thrown because at the moment, we want to prove that\n         code output by the compiler never throws exceptions *)\n      endCycleEarly{A: Type} := fail_hard;\n  }.\n\n  Arguments Memory.load_bytes: simpl never.\n  Arguments Memory.store_bytes: simpl never.\n\n  Lemma VirtualMemoryFetchP: forall (addr: word) xAddrs,\n      VirtualMemory = Fetch -> isXAddr4 addr xAddrs.\n  Proof. intros. discriminate. Qed.\n\n  Lemma ExecuteFetchP: forall (addr: word) xAddrs,\n      Execute = Fetch -> isXAddr4 addr xAddrs.\n  Proof. intros. discriminate. Qed.\n\n  Ltac t :=\n    repeat match goal with\n       | |- _ => reflexivity\n       | |- _ => progress (\n                     unfold computation_satisfies, computation_with_answer_satisfies,\n                            IsRiscvMachine,\n                            valid_register,\n                            is_initial_register_value,\n                            get, put, fail_hard,\n                            update,\n                            Memory.loadByte, Memory.storeByte,\n                            Memory.loadHalf, Memory.storeHalf,\n                            Memory.loadWord, Memory.storeWord,\n                            Memory.loadDouble, Memory.storeDouble,\n                            fail_if_None, loadN, storeN in *;\n                     subst;\n                     simpl in * )\n       | |- _ => intro\n       | |- _ => split\n       | |- _ => apply functional_extensionality\n       | |- _ => apply propositional_extensionality; split; intros\n       | u: unit |- _ => destruct u\n       | H: exists x, _ |- _ => destruct H\n       | H: {_ : _ | _} |- _ => destruct H\n       | H: _ /\\ _ |- _ => destruct H\n       | p: _ * _ |- _ => destruct p\n       | |- context [ let (_, _) := ?p in _ ] => let E := fresh \"E\" in destruct p eqn: E\n       | H: Some _ = Some _ |- _ => inversion H; clear H; subst\n       | H: (_, _) = (_, _) |- _ => inversion H; clear H; subst\n       | H: _ && _ = true |- _ => apply andb_prop in H\n       | H: _ && _ = false |- _ => apply Bool.andb_false_iff in H\n       | H: isXAddr4B _ _ = false |- _ => apply isXAddr4B_not in H\n       | H: isXAddr4B _ _ = true  |- _ => apply isXAddr4B_holds in H\n       | H: ?x = ?x -> _ |- _ => specialize (H eq_refl)\n       | |- _ * _ => constructor\n       | |- option _ => exact None\n       | |- _ => discriminate\n       | |- _ => congruence\n       | |- _ => solve [exfalso; blia]\n       | |- _ => solve [eauto 15 using VirtualMemoryFetchP, ExecuteFetchP]\n       | |- _ => progress (rewrite? Z.ltb_nlt in *; rewrite? Z.ltb_lt in * )\n       | |- _ => blia\n       | H: context[let (_, _) := ?y in _] |- _ => let E := fresh \"E\" in destruct y eqn: E\n       | E: ?x = Some _, H: context[match ?x with _ => _ end] |- _ => rewrite E in H\n       | E: ?x = Some _  |- context[match ?x with _ => _ end]      => rewrite E\n       | H: context[match ?x with _ => _ end] |- _ => let E := fresh \"E\" in destruct x eqn: E\n       | |- context[match ?x with _ => _ end]      => let E := fresh \"E\" in destruct x eqn: E\n       | H: _ \\/ _ |- _ => destruct H\n       | r: RiscvMachine |- _ =>\n         destruct r as [regs pc npc m l];\n         simpl in *\n(*       | H: context[match ?x with _ => _ end] |- _ => let E := fresh in destruct x eqn: E*)\n       | o: option _ |- _ => destruct o\n       (* introduce evars as late as possible (after all destructs), to make sure everything\n          is in their scope*)\n       | |- exists (P: ?A -> ?S -> Prop), _ =>\n            let a := fresh \"a\" in evar (a: A);\n            let s := fresh \"s\" in evar (s: S);\n            exists (fun a0 s0 => a0 = a /\\ s0 = s);\n            subst a s\n       | |- _ \\/ _ => left; solve [t]\n       | |- _ \\/ _ => right; solve [t]\n       end.\n\n  Instance MinimalPrimitivesParams: PrimitivesParams (OState RiscvMachine) RiscvMachine := {\n    Primitives.mcomp_sat := @OStateOperations.computation_with_answer_satisfies RiscvMachine;\n    Primitives.is_initial_register_value := eq (word.of_Z 0);\n    Primitives.nonmem_load n kind addr _ _ := False;\n    Primitives.nonmem_store n kind addr v _ _ := False;\n    Primitives.valid_machine _ := True;\n  }.\n\n  Instance MinimalSatisfies_mcomp_sat_spec: mcomp_sat_spec MinimalPrimitivesParams.\n  Proof. constructor; t. Qed.\n\n  Lemma get_sane: mcomp_sane get.\n  Proof.\n    unfold mcomp_sane, get. simpl. unfold computation_with_answer_satisfies. intros.\n    destruct H0 as (? & ? & ? & ?). inversion H0. subst. clear H0.\n    split.\n    - eauto.\n    - intros. do 2 eexists. split; [reflexivity|].\n      split; [|trivial].\n      split; [assumption|].\n      exists nil. reflexivity.\n  Qed.\n\n  (* does not hold in general, because we could put a machine with a shorter log *)\n  Lemma put_sane: forall m, mcomp_sane (put m). Abort.\n\n  Lemma fail_hard_sane: forall A, mcomp_sane (fail_hard (A := A)).\n  Proof.\n    unfold mcomp_sane, fail_hard. simpl. unfold computation_with_answer_satisfies. intros.\n    destruct H0 as (? & ? & ? & ?). discriminate.\n  Qed.\n\n  Lemma update_sane: forall f,\n      (forall mach, exists diff, (f mach).(getLog) = diff ++ mach.(getLog)) ->\n      mcomp_sane (update f).\n  Proof.\n    unfold mcomp_sane, update, get, put. simpl. unfold computation_with_answer_satisfies. intros.\n    split.\n    - edestruct H1 as (? & ? & ? & ?); eauto.\n    - intros. destruct H1 as (? & ? & ? & ?).\n      inversion H1. subst. clear H1.\n      eauto 10.\n  Qed.\n\n  Lemma logEvent_sane: forall e,\n      mcomp_sane (update (withLogItem e)).\n  Proof.\n    intros. eapply update_sane. intros. exists [e]. destruct mach. reflexivity.\n  Qed.\n\n  Instance MinimalSane: PrimitivesSane MinimalPrimitivesParams.\n  Proof.\n    constructor.\n    all: intros;\n      unfold getRegister, setRegister,\n         loadByte, loadHalf, loadWord, loadDouble,\n         storeByte, storeHalf, storeWord, storeDouble,\n         getPC, setPC,\n         endCycleNormal, endCycleEarly, raiseExceptionWithInfo,\n         IsRiscvMachine,\n         loadN, storeN, fail_if_None.\n\n    all: repeat match goal with\n                | |- _ => apply logEvent_sane\n                | |- mcomp_sane (Bind _ _) => apply Bind_sane\n                | |- _ => apply Return_sane\n                | |- _ => apply get_sane\n                | |- _ => apply fail_hard_sane\n                | |- _ => apply update_sane; intros [? ? ? ? ? ?]; simpl; exists nil; reflexivity\n                | |- context [match ?b with _ => _ end] => destruct b\n                | |- _ => progress intros\n                end.\n  Qed.\n\n  Instance MinimalSatisfiesPrimitives: Primitives MinimalPrimitivesParams.\n  Proof.\n    constructor.\n    1: exact MinimalSatisfies_mcomp_sat_spec.\n    1: exact MinimalSane.\n    all: try t.\n  Qed.\n\nEnd Riscv.\n\n(* needed because defined inside a Section *)\n#[global] Existing Instance IsRiscvMachine.\n#[global] Existing Instance MinimalSatisfiesPrimitives.\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/Minimal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.16608549637730544}}
{"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 base_extra.\nFrom HypVeri.lang Require Import lang_extra reg_extra.\n\nSection add.\n\nContext `{hypparams:HypervisorParameters}.\nContext `{vmG: !gen_VMG \u03a3}.\n\nLemma add {E i wi w1 w2 q p} ai ra rb s :\n  decode_instruction wi = Some(Add ra rb) ->\n  tpa ai \u2208 s ->\n  tpa ai \u2260 p ->\n  {SS{{ \u25b7 (PC @@ i ->r ai) \u2217\n        \u25b7 (ai ->a wi) \u2217\n        \u25b7 (ra @@ i ->r w1) \u2217\n        \u25b7 (rb @@ i ->r w2) \u2217\n        \u25b7 (i -@{ q }A> s) \u2217\n        \u25b7 (TX@ i := p)}}}\n    ExecI @ i; E\n    {{{ RET (false, ExecI);\n        PC @@ i ->r (ai ^+ 1)%f \u2217\n        ai ->a wi \u2217\n        ra @@ i ->r (w1 ^+ (finz.to_z w2))%f \u2217\n        rb @@ i ->r w2 \u2217\n        (i -@{ q }A> s) \u2217\n        (TX@ i := p) }}}.\nProof.\n  iIntros (Hdecode Hin Hneq \u03d5) \"(>Hpc & >Hai & >Hra & >Hrb & >Hacc & >HTX) H\u03d5\".\n  iApply (sswp_lift_atomic_step ExecI);[done|].\n  iIntros (n \u03c31) \"%Hsche H\u03c3\".\n  rewrite /scheduled in Hsche.\n  simpl in Hsche.\n  rewrite /scheduler in Hsche.\n  apply bool_decide_unpack in Hsche as Hcur.\n  clear Hsche.\n  apply fin_to_nat_inj in Hcur.\n  iModIntro.\n  iDestruct \"H\u03c3\" as \"(#Hneq & Hmem & Hreg & Hmb & Hrx & Hown & Haccess & Hrest)\".\n  (* valid regs *)\n  iDestruct ((gen_reg_valid3 i PC ai ra w1 rb w2 Hcur) with \"Hreg Hpc Hra Hrb\") as \"[%HPC [%Hra %Hrb]]\";eauto.\n  (* valid pt *)\n  iDestruct (access_agree_check_true (tpa ai) i with \"Haccess Hacc\") as \"%Hai\"; first set_solver.\n  (* valid mem *)\n  iDestruct (gen_mem_valid ai wi with \"Hmem Hai\") as %Hmem.\n  iDestruct (mb_valid_tx i p with \"Hmb HTX\") as %Htx.\n  set (instr := Add ra rb).\n  iSplit.\n  - (* reducible *)\n    iPureIntro.\n    apply (reducible_normal i instr ai wi);eauto.\n    by rewrite Htx.\n  - (* step *)\n    iModIntro.\n    iIntros (m2 \u03c32) \"[%P PAuth] %HstepP\".\n    apply (step_ExecI_normal i instr ai wi ) in HstepP;eauto.\n    remember (exec instr \u03c31) as c2 eqn:Heqc2.\n    pose proof (decode_instruction_valid wi instr Hdecode) as Hvalidinstr.\n    inversion Hvalidinstr as [| | | | | | ra' rb' Hvalidrb Hvalidra | | | | |] .\n    subst ra' rb'.\n    inversion Hvalidra as [ HneqPCa HneqNZa ].\n    inversion Hvalidrb as [ HneqPCb HneqNZb ].\n    subst instr.\n    rewrite /exec (add_ExecI \u03c31 ra w1 rb w2) /update_incr_PC /update_reg in Heqc2;auto.\n    destruct HstepP;subst m2 \u03c32; subst c2; simpl.\n    rewrite /gen_vm_interp.\n    (* unchanged part *)\n    rewrite (preserve_get_mb_gmap \u03c31).\n    rewrite (preserve_get_rx_gmap \u03c31).\n    rewrite (preserve_get_own_gmap \u03c31).\n    rewrite (preserve_get_access_gmap \u03c31).\n    rewrite (preserve_get_excl_gmap \u03c31).\n    rewrite (preserve_get_trans_gmap \u03c31).\n    rewrite (preserve_get_hpool_gset \u03c31).\n    rewrite (preserve_get_retri_gmap \u03c31).\n    rewrite (preserve_inv_trans_pgt_consistent \u03c31).\n    rewrite (preserve_inv_trans_wellformed \u03c31).\n    rewrite (preserve_inv_trans_ps_disj \u03c31).\n    rewrite p_upd_pc_mem p_upd_reg_mem.\n    all: try rewrite p_upd_pc_pgt p_upd_reg_pgt //.\n    all: try rewrite p_upd_pc_trans p_upd_reg_trans //.\n    all: try rewrite p_upd_pc_mb p_upd_reg_mb //.\n    rewrite Hcur. iFrame.\n    (* updated part *)\n    rewrite -> (u_upd_pc_regs _ i ai 1);eauto.\n    rewrite u_upd_reg_regs.\n    + iDestruct ((gen_reg_update2_global PC i ai (ai ^+ 1)%f ra i w1 (w1 ^+ (finz.to_z w2))%f)\n                   with \"Hreg Hpc Hra\") as \">[Hreg [Hpc Hra]]\";eauto.\n      iModIntro.\n      iSplitL \"PAuth\".\n      by iExists P.\n      rewrite /just_scheduled_vms.\n      rewrite /just_scheduled.\n      assert (filter\n                (\u03bb id : vmid,\n                        base.negb (scheduled \u03c31 id) && scheduled (update_offset_PC (update_reg_global \u03c31 i ra (w1 ^+ w2)%f) 1) id = true)\n                (seq 0 n) = []) as ->.\n      {\n        rewrite /scheduled /machine.scheduler //= /scheduler Hcur.\n        rewrite p_upd_pc_current_vm p_upd_reg_current_vm.\n        rewrite Hcur.\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      iSimpl.\n      iFrame.\n      iSplit; first done.\n      iSplit; first done.\n      assert ((scheduled (update_offset_PC (update_reg_global \u03c31 i ra (w1 ^+ w2)%f) 1) i) = true) as ->.\n      rewrite /scheduled.\n      simpl.\n      rewrite /scheduler.\n      rewrite p_upd_pc_current_vm p_upd_reg_current_vm Hcur.\n      rewrite bool_decide_eq_true.\n      reflexivity.\n      simpl.\n      iApply (\"H\u03d5\" with \"[Hpc Hai Hacc Hra Hrb HTX]\").\n      iFrame.\n    + rewrite u_upd_reg_regs.\n      apply (get_reg_gmap_get_reg_Some _ _ _ i) in HPC;eauto.\n      rewrite lookup_insert_ne.\n      by simplify_map_eq /=.\n      congruence.\n    + by rewrite Htx.\nQed.\n\nEnd add.\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/add.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.16608549548231477}}
{"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.CommonPromising.\n\nSet Implicit Arguments.\n\n\nModule Local.\nSection Local.\n  Inductive t := mk {\n    coh: Loc.t -> View.t (A:=unit);\n    vrn: View.t (A:=unit);\n    vpr: View.t (A:=unit);\n    vpa: Loc.t -> View.t (A:=unit);\n    vpc: Loc.t -> View.t (A:=unit);\n    promises: Promises.t;\n  }.\n  Hint Constructors t.\n\n  Definition read_view (coh:View.t (A:=unit)) (tsx:Time.t): View.t (A:=unit) :=\n    if coh.(View.ts) == tsx\n    then View.mk bot bot\n    else View.mk tsx bot.\n\n  Definition init: t := mk bot bot bot bot bot bot.\n\n  Definition init_with_promises (promises: Promises.t): Local.t :=\n    mk bot bot bot bot bot promises.\n\n  Inductive promise (loc:Loc.t) (val:Val.t) (ts:Time.t) (tid:Id.t) (lc1:t) (mem1:Memory.t) (lc2:t) (mem2:Memory.t): Prop :=\n  | promise_intro\n      (LC2: lc2 =\n            mk\n              lc1.(coh)\n              lc1.(vrn)\n              lc1.(vpr)\n              lc1.(vpa)\n              lc1.(vpc)\n              (Promises.set ts lc1.(promises)))\n      (MEM2: Memory.append (Msg.mk loc val tid) mem1 = (ts, mem2))\n  .\n  Hint Constructors promise.\n\n  Inductive read (vloc res:ValA.t (A:=unit)) (ts:Time.t) (lc1:t) (mem1: Memory.t) (lc2:t): Prop :=\n  | read_intro\n      loc val\n      view_pre view_post\n      (LOC: loc = vloc.(ValA.val))\n      (VIEW_PRE: view_pre = lc1.(vrn))\n      (COH: le (lc1.(coh) loc).(View.ts) ts)\n      (LATEST: Memory.latest loc ts view_pre.(View.ts) mem1)\n      (MSG: Memory.read loc ts mem1 = Some val)\n      (VIEW_POST: view_post = read_view (lc1.(coh) loc) ts)\n      (RES: res = ValA.mk _ val bot)\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk ts bot) lc1.(coh))\n              (join lc1.(vrn) view_post)\n              (join lc1.(vpr) view_post)\n              lc1.(vpa)\n              lc1.(vpc)\n              lc1.(promises))\n  .\n  Hint Constructors read.\n\n  Inductive writable (vloc vval:ValA.t (A:=unit)) (tid:Id.t) (lc1:t) (mem1: Memory.t) (ts:Time.t): Prop :=\n  | writable_intro\n      loc cohmax\n      (LOC: loc = vloc.(ValA.val))\n      (COHMAX: fun_max lc1.(coh) cohmax)\n      (EXT: lt cohmax.(View.ts) ts)\n  .\n  Hint Constructors writable.\n\n  Inductive fulfill (vloc vval res:ValA.t (A:=unit)) (ts:Time.t) (tid:Id.t) (lc1:t) (mem1: Memory.t) (lc2:t): Prop :=\n  | fulfill_intro\n      loc val\n      (LOC: loc = vloc.(ValA.val))\n      (VAL: val = vval.(ValA.val))\n      (WRITABLE: writable vloc vval tid lc1 mem1 ts)\n      (MSG: Memory.get_msg ts mem1 = Some (Msg.mk loc val tid))\n      (PROMISE: Promises.lookup ts lc1.(promises))\n      (RES: res = ValA.mk _ 0 bot)\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk ts bot) lc1.(coh))\n              lc1.(vrn)\n              lc1.(vpr)\n              lc1.(vpa)\n              lc1.(vpc)\n              (Promises.unset ts lc1.(promises)))\n  .\n  Hint Constructors fulfill.\n\n  Inductive rmw (vloc vold vnew:ValA.t (A:=unit)) (old_ts:Time.t) (ts:Time.t) (tid:Id.t) (lc1:t) (mem1:Memory.t) (lc2:t): Prop :=\n  | rmw_intro\n      loc old new view_post\n      (LOC: loc = vloc.(ValA.val))\n      (COH: le (lc1.(coh) loc).(View.ts) old_ts)\n      (OLD_RANGE: lt old_ts ts)\n      (EX: Memory.exclusive tid loc old_ts ts mem1)\n      (OLD_MSG: Memory.read loc old_ts mem1 = Some old)\n      (OLD: old = vold.(ValA.val))\n      (NEW: new = vnew.(ValA.val))\n      (WRITABLE: writable vloc vnew tid lc1 mem1 ts)\n      (MSG: Memory.get_msg ts mem1 = Some (Msg.mk loc new tid))\n      (PROMISE: Promises.lookup ts lc1.(promises))\n      (VIEW_POST: view_post = View.mk ts bot)\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk ts bot) lc1.(coh))\n              (join lc1.(vrn) view_post)\n              (join lc1.(vpr) view_post)\n              lc1.(vpa)\n              (fun_join lc1.(vpc) lc1.(vpa))\n              (Promises.unset ts lc1.(promises)))\n  .\n  Hint Constructors rmw.\n\n  Inductive rmw_failure (vloc vold res:ValA.t (A:=unit)) (old_ts:Time.t) (lc1:t) (mem1:Memory.t) (lc2:t): Prop :=\n  | rmw_failure_intro\n      loc old\n      view_pre view_post\n      (LOC: loc = vloc.(ValA.val))\n      (VIEW_PRE: view_pre = lc1.(vrn))\n      (COH: le (lc1.(coh) loc).(View.ts) old_ts)\n      (LATEST: Memory.latest loc old_ts view_pre.(View.ts) mem1)\n      (OLD_MSG: Memory.read loc old_ts mem1 = Some old)\n      (OLD: old = vold.(ValA.val))\n      (VIEW_POST: view_post = read_view (lc1.(coh) loc) old_ts)\n      (RES: res = ValA.mk _ old bot)\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk old_ts bot) lc1.(coh))\n              (join lc1.(vrn) view_post)\n              (join lc1.(vpr) view_post)\n              lc1.(vpa)\n              lc1.(vpc)\n              lc1.(promises))\n  .\n  Hint Constructors rmw_failure.\n\n  Inductive mfence (lc1 lc2:t): Prop :=\n  | mfence_intro\n      cohmax\n      (COHMAX: fun_max lc1.(coh) cohmax)\n      (LC2: lc2 =\n            mk\n              lc1.(coh)\n              (join lc1.(vrn) cohmax)\n              (join lc1.(vpr) cohmax)\n              lc1.(vpa)\n              (fun_join lc1.(vpc) lc1.(vpa))\n              lc1.(promises))\n  .\n  Hint Constructors mfence.\n\n  Inductive sfence (lc1 lc2:t): Prop :=\n  | sfence_intro\n      cohmax\n      (COHMAX: fun_max lc1.(coh) cohmax)\n      (LC2: lc2 =\n            mk\n              lc1.(coh)\n              lc1.(vrn)\n              (join lc1.(vpr) cohmax)\n              lc1.(vpa)\n              (fun_join lc1.(vpc) lc1.(vpa))\n              lc1.(promises))\n  .\n  Hint Constructors sfence.\n\n  Inductive write (vloc vval res:ValA.t (A:=unit)) (ts:Time.t) (tid:Id.t) (lc1:t) (mem1: Memory.t) (lc2:t) (mem2: Memory.t): Prop :=\n  | write_intro\n      loc val\n      (LOC: loc = vloc.(ValA.val))\n      (VAL: val = vval.(ValA.val))\n      (RES: res = ValA.mk _ 0 bot)\n      (MEM: Memory.append (Msg.mk loc val tid) mem1 = (ts, mem2))\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk ts bot) lc1.(coh))\n              lc1.(vrn)\n              lc1.(vpr)\n              lc1.(vpa)\n              lc1.(vpc)\n              lc1.(promises))\n  .\n  Hint Constructors write.\n\n  Inductive vrmw (vloc vold vnew:ValA.t (A:=unit)) (old_ts:Time.t) (ts:Time.t) (tid:Id.t) (lc1:t) (mem1:Memory.t) (lc2:t) (mem2: Memory.t): Prop :=\n  | vrmw_intro\n      loc old new\n      view_post\n      (LOC: loc = vloc.(ValA.val))\n      (NINTERVENING: Memory.latest loc old_ts (pred ts) mem1)\n      (OLD_MSG: Memory.read loc old_ts mem1 = Some old)\n      (OLD: old = vold.(ValA.val))\n      (NEW: new = vnew.(ValA.val))\n      (VIEW_POST: view_post = View.mk ts bot)\n      (MEM: Memory.append (Msg.mk loc new tid) mem1 = (ts, mem2))\n      (LC2: lc2 =\n            mk\n              (fun_add loc (View.mk ts bot) lc1.(coh))\n              (join lc1.(vrn) view_post)\n              (join lc1.(vpr) view_post)\n              lc1.(vpa)\n              (fun_join lc1.(vpc) lc1.(vpa))\n              lc1.(promises))\n  .\n  Hint Constructors rmw.\n\n  Inductive flush (vloc:ValA.t (A:=unit)) (lc1:t) (lc2:t): Prop :=\n  | flush_intro\n      loc cohmax view_post\n      (LOC: loc = vloc.(ValA.val))\n      (COHMAX: fun_max lc1.(coh) cohmax)\n      (VIEW_POST: view_post = fun loc' => ifc (Loc.cl loc loc') cohmax)\n      (LC2: lc2 =\n            mk\n              lc1.(coh)\n              lc1.(vrn)\n              lc1.(vpr)\n              (fun_join lc1.(vpa) view_post)\n              (fun_join lc1.(vpc) view_post)\n              lc1.(promises))\n  .\n  Hint Constructors flush.\n\n  Inductive flushopt (vloc:ValA.t (A:=unit)) (lc1:t) (lc2:t): Prop :=\n  | flushopt_intro\n      loc cohmax_cl view_post\n      (LOC: loc = vloc.(ValA.val))\n      (COHMAX_CL: fun_max (fun loc' => ifc (Loc.cl loc loc') (lc1.(coh) loc')) cohmax_cl)\n      (VIEW_POST: view_post = fun loc' => ifc (Loc.cl loc loc') (join cohmax_cl lc1.(vpr)))\n      (LC2: lc2 =\n            mk\n              lc1.(coh)\n              lc1.(vrn)\n              lc1.(vpr)\n              (fun_join lc1.(vpa) view_post)\n              lc1.(vpc)\n              lc1.(promises))\n  .\n  Hint Constructors flushopt.\n\n  Inductive step (event:Event.t (A:=unit)) (tid:Id.t) (mem:Memory.t) (lc1 lc2:t): Prop :=\n  | step_internal\n      (EVENT: event = Event.internal)\n      (LC: lc2 = lc1)\n  | step_read\n      vloc res ts ord\n      (EVENT: event = Event.read false false ord vloc res)\n      (STEP: read vloc res ts lc1 mem lc2)\n  | step_fulfill\n      vloc vval res ts ord\n      (EVENT: event = Event.write false ord vloc vval res)\n      (STEP: fulfill vloc vval res ts tid lc1 mem lc2)\n  | step_rmw\n      vloc vold vnew old_ts ts ordr ordw\n      (EVENT: event = Event.rmw ordr ordw vloc vold vnew)\n      (STEP: rmw vloc vold vnew old_ts ts tid lc1 mem lc2)\n  | step_rmw_failure\n      vloc vold old_ts ord res\n      (EVENT: event = Event.read false true ord vloc res)\n      (STEP: rmw_failure vloc vold res old_ts lc1 mem lc2)\n  | step_mfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_mfence b)\n      (STEP: mfence lc1 lc2)\n  | step_sfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_sfence b)\n      (STEP: sfence lc1 lc2)\n  | step_flush\n      vloc\n      (EVENT: event = Event.flush vloc)\n      (STEP: flush vloc lc1 lc2)\n  | step_flushopt\n      vloc\n      (EVENT: event = Event.flushopt vloc)\n      (STEP: flushopt vloc lc1 lc2)\n  .\n  Hint Constructors step.\n\n  Inductive view_step (event:Event.t (A:=unit)) (tid:Id.t) (mem1 mem2:Memory.t) (lc1 lc2:t): Prop :=\n  | view_step_internal\n      (EVENT: event = Event.internal)\n      (LC: lc2 = lc1)\n      (MEM: mem2 = mem1)\n  | view_step_read\n      vloc res ts ord\n      (EVENT: event = Event.read false false ord vloc res)\n      (STEP: read vloc res ts lc1 mem1 lc2)\n      (MEM: mem2 = mem1)\n  | view_step_write\n      vloc vval res ts ord\n      (EVENT: event = Event.write false ord vloc vval res)\n      (STEP: write vloc vval res ts tid lc1 mem1 lc2 mem2)\n  | view_step_rmw\n      vloc vold vnew old_ts ts ordr ordw\n      (EVENT: event = Event.rmw ordr ordw vloc vold vnew)\n      (STEP: vrmw vloc vold vnew old_ts ts tid lc1 mem1 lc2 mem2)\n  | view_step_rmw_failure\n      vloc vold old_ts ord res\n      (EVENT: event = Event.read false true ord vloc res)\n      (STEP: rmw_failure vloc vold res old_ts lc1 mem1 lc2)\n      (MEM: mem2 = mem1)\n  | view_step_mfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_mfence b)\n      (STEP: mfence lc1 lc2)\n      (MEM: mem2 = mem1)\n  | view_step_sfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_sfence b)\n      (STEP: sfence lc1 lc2)\n      (MEM: mem2 = mem1)\n  | view_step_flush\n      vloc\n      (EVENT: event = Event.flush vloc)\n      (STEP: flush vloc lc1 lc2)\n      (MEM: mem2 = mem1)\n  | view_step_flushopt\n      vloc\n      (EVENT: event = Event.flushopt vloc)\n      (STEP: flushopt vloc lc1 lc2)\n      (MEM: mem2 = mem1)\n  .\n  Hint Constructors view_step.\n\n  Inductive wf_fwdbank (loc:Loc.t) (mem:Memory.t) (coh: Time.t): Prop :=\n  | wf_fwdbank_intro\n      (VAL: exists val, Memory.read loc coh mem = Some val)\n  .\n\n  Inductive wf_cohmax (lc:t): Prop :=\n  | wf_cohmax_intro\n      cohmax\n      (COHMAX: fun_max lc.(coh) cohmax)\n      (VRN: lc.(vrn).(View.ts) <= cohmax.(View.ts))\n      (VPR: lc.(vpr).(View.ts) <= cohmax.(View.ts))\n      (VPA: forall loc, (lc.(vpa) loc).(View.ts) <= cohmax.(View.ts))\n      (VPC: forall loc, (lc.(vpc) loc).(View.ts) <= cohmax.(View.ts))\n  .\n\n  Inductive wf (tid:Id.t) (mem:Memory.t) (lc:t): Prop :=\n  | wf_intro\n      (COH: forall loc, (lc.(coh) loc).(View.ts) <= List.length mem)\n      (VRN: lc.(vrn).(View.ts) <= List.length mem)\n      (VPR: lc.(vpr).(View.ts) <= List.length mem)\n      (VPA: forall loc, (lc.(vpa) loc).(View.ts) <= List.length mem)\n      (VPC: forall loc, (lc.(vpc) loc).(View.ts) <= List.length mem)\n      (FWDBANK: forall loc, wf_fwdbank loc mem (lc.(coh) loc).(View.ts))\n      (PROMISES: forall ts (IN: Promises.lookup ts lc.(promises)), ts <= List.length mem)\n      (PROMISES: forall ts msg\n                   (MSG: Memory.get_msg ts mem = Some msg)\n                   (TID: msg.(Msg.tid) = tid)\n                   (TS: (lc.(coh) msg.(Msg.loc)).(View.ts) < ts),\n          Promises.lookup ts lc.(promises))\n      (COHMAX: wf_cohmax lc)\n      (NFWD: forall ts msg\n                (MSG: Memory.get_msg ts mem = Some msg)\n                (TID: msg.(Msg.tid) <> tid)\n                (TS: (lc.(coh) msg.(Msg.loc)).(View.ts) = ts),\n          ts <= lc.(vrn).(View.ts))\n      (NINTERVENING: forall loc from to\n                       (LATEST: Memory.latest loc from to mem),\n          (lc.(coh) loc).(View.ts) <= from \\/ to < (lc.(coh) loc).(View.ts))\n      (VRNVPR: lc.(vrn).(View.ts) <= lc.(vpr).(View.ts))\n      (VPACL: forall loc1 loc2 (CL: Loc.cl loc1 loc2), (lc.(vpa) loc1).(View.ts) = (lc.(vpa) loc2).(View.ts))\n      (VPCCL: forall loc1 loc2 (CL: Loc.cl loc1 loc2), (lc.(vpc) loc1).(View.ts) = (lc.(vpc) loc2).(View.ts))\n  .\n  Hint Constructors wf.\n\n  Lemma init_wf tid: wf tid Memory.empty init.\n  Proof.\n    econs; ss; i; try by apply bot_spec.\n    - econs; ss. eexists. ss.\n    - destruct ts; ss.\n    - destruct ts; ss. destruct ts; ss.\n    - econs; try i; try apply bot_spec.\n      econs; ss. i. instantiate (1 := Loc.default). apply bot_spec.\n    - rewrite TS. ss.\n    - left. apply bot_spec.\n  Qed.\n\n  Lemma fwd_read_view_le\n        tid mem lc loc ts\n        (WF: wf tid mem lc):\n    (read_view (lc.(coh) loc) ts).(View.ts) <= ts.\n  Proof.\n    inv WF. destruct (FWDBANK loc). des.\n    unfold read_view. condtac; ss.\n    apply bot_spec.\n  Qed.\n\n  Lemma wf_fwdbank_mon\n        loc mem1 mem2 ts\n        (FWDBANK: wf_fwdbank loc mem1 ts):\n    wf_fwdbank loc (mem1 ++ mem2) ts.\n  Proof.\n    inv FWDBANK. des.\n    econs. eexists. apply Memory.read_mon. eauto.\n  Qed.\n\n  Lemma read_spec\n        tid mem vloc res ts lc1 lc2\n        (WF: Local.wf tid mem lc1)\n        (READ: Local.read vloc res ts lc1 mem lc2):\n    <<LATEST: Memory.latest vloc.(ValA.val) ts lc2.(Local.vrn).(View.ts) mem>> /\\\n    <<COH: ts = (lc2.(Local.coh) vloc.(ValA.val)).(View.ts)>>.\n  Proof.\n    inv READ. ss. rewrite fun_add_spec. condtac; [|congr]. splits; ss.\n    repeat apply Memory.latest_join; auto.\n    apply Memory.ge_latest. eapply fwd_read_view_le; eauto.\n  Qed.\n\n  Lemma rmw_failure_spec\n        tid mem vloc vold res old_ts lc1 lc2\n        (WF: Local.wf tid mem lc1)\n        (READ: Local.rmw_failure vloc vold res old_ts lc1 mem lc2):\n    <<LATEST: Memory.latest vloc.(ValA.val) old_ts lc2.(Local.vrn).(View.ts) mem>> /\\\n    <<COH: old_ts = (lc2.(Local.coh) vloc.(ValA.val)).(View.ts)>>.\n  Proof.\n    inv READ. ss. rewrite fun_add_spec. condtac; [|congr]. splits; ss.\n    repeat apply Memory.latest_join; auto.\n    apply Memory.ge_latest. eapply fwd_read_view_le; eauto.\n  Qed.\n\n  Lemma rmw_spec\n        tid mem vloc vold vnew old_ts ts lc1 lc2\n        (WF: Local.wf tid mem lc1)\n        (RMW: Local.rmw vloc vold vnew old_ts ts tid lc1 mem lc2):\n    <<COH: ts = Memory.latest_ts vloc.(ValA.val) (lc2.(Local.coh) vloc.(ValA.val)).(View.ts) mem>>.\n  Proof.\n    inv RMW. ss. rewrite fun_add_spec. condtac; [|congr]. splits.\n    - apply le_antisym; ss.\n      + eapply Memory.latest_ts_read_le; eauto.\n        eapply Memory.get_msg_read. eauto.\n      + apply Memory.latest_latest_ts.\n        apply Memory.ge_latest. ss.\n  Qed.\n\n  Lemma interference_wf\n        tid (lc:t) mem mem_interference\n        (INTERFERENCE: Forall (fun msg => msg.(Msg.tid) <> tid) mem_interference)\n        (WF: wf tid mem lc):\n    wf tid (mem ++ mem_interference) lc.\n  Proof.\n    inversion WF. econs; i; ss.\n    all: try rewrite app_length.\n    all: try lia.\n    all: try apply WF; ss.\n    - rewrite COH. lia.\n    - rewrite VPA. lia.\n    - rewrite VPC. lia.\n    - destruct (FWDBANK loc). des. econs; esplits; eauto.\n      apply Memory.read_mon. eauto.\n    - exploit PROMISES; eauto. lia.\n    - apply Memory.get_msg_app_inv in MSG. des.\n      + eapply PROMISES0; eauto.\n      + apply nth_error_In in MSG0. eapply Forall_forall in INTERFERENCE; eauto.\n        subst. destruct (nequiv_dec (Msg.tid msg) (Msg.tid msg)); ss. congr.\n    - apply Memory.get_msg_app_inv in MSG. des.\n      + eapply NFWD; eauto.\n      + subst. specialize (COH (Msg.loc msg)). lia.\n    - eapply Memory.latest_app_inv. eauto.\n  Qed.\n\n  Lemma wf_promises_above\n        tid mem (lc:t) ts\n        (WF: wf tid mem lc)\n        (ABOVE: length mem < ts):\n    Promises.lookup ts lc.(promises) = false.\n  Proof.\n    destruct (Promises.lookup ts (Local.promises lc)) eqn:X; ss.\n    inv WF. exploit PROMISES; eauto. clear -ABOVE. lia.\n  Qed.\n\n  Inductive le (lhs rhs:t): Prop :=\n  | le_intro\n      (COH: forall loc, Order.le (lhs.(coh) loc).(View.ts) (rhs.(coh) loc).(View.ts))\n      (VRN: Order.le lhs.(vrn).(View.ts) rhs.(vrn).(View.ts))\n      (VRN: Order.le lhs.(vpr).(View.ts) rhs.(vpr).(View.ts))\n      (VPA: forall loc, Order.le (lhs.(vpa) loc).(View.ts) (rhs.(vpa) loc).(View.ts))\n      (VPC: forall loc, Order.le (lhs.(vpc) loc).(View.ts) (rhs.(vpc) loc).(View.ts))\n  .\n\n  Global Program Instance le_partial_order: PreOrder le.\n  Next Obligation. econs; refl. Qed.\n  Next Obligation. ii. inv H. inv H0. econs; etrans; eauto. Qed.\n\n  Lemma writable_lt_coh_ts\n        vloc vval tid lc mem ts\n        (WRITABLE: writable vloc vval tid lc mem ts):\n    lt (lc.(coh) vloc.(ValA.val)).(View.ts) ts.\n  Proof.\n    inv WRITABLE. inv COHMAX. specialize (MAX (ValA.val vloc)).\n    inv MAX. unfold Order.le in *. lia.\n  Qed.\n\n  Lemma promise_incr\n        loc val ts tid lc1 mem1 lc2 mem2\n        (LC: promise loc val ts tid lc1 mem1 lc2 mem2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; try apply join_l.\n  Qed.\n\n  Lemma read_incr\n        vloc res ts lc1 mem1 lc2\n        (LC: read vloc res ts lc1 mem1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n    rewrite fun_add_spec. condtac; try refl.\n    clear X. inv e. ss.\n  Qed.\n\n  Lemma fulfill_incr\n        vloc vval res ts tid lc1 mem1 lc2\n        (LC: fulfill vloc vval res ts tid lc1 mem1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n    rewrite fun_add_spec. condtac; try refl.\n    clear X. inv e. s.\n    unfold Order.le. exploit writable_lt_coh_ts; eauto. lia.\n  Qed.\n\n  Lemma rmw_incr\n        vloc vold vnew old_ts ts tid lc1 mem lc2\n        (LC: rmw vloc vold vnew old_ts ts tid lc1 mem lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n    funtac. inversion e.\n    unfold Order.le. exploit writable_lt_coh_ts; eauto. lia.\n  Qed.\n\n  Lemma rmw_failure_incr\n        vloc vold res ts lc1 mem1 lc2\n        (LC: rmw_failure vloc vold res ts lc1 mem1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n    rewrite fun_add_spec. condtac; try refl.\n    clear X. inv e. ss.\n  Qed.\n\n  Lemma mfence_incr\n        lc1 lc2\n        (LC: mfence lc1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n  Qed.\n\n  Lemma sfence_incr\n        lc1 lc2\n        (LC: sfence lc1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n  Qed.\n\n  Lemma flush_incr\n        vloc lc1 lc2\n        (LC: flush vloc lc1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n  Qed.\n\n  Lemma flushopt_incr\n        vloc lc1 lc2\n        (LC: flushopt vloc lc1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC. econs; ss; try refl; i; try apply join_l.\n  Qed.\n\n  Lemma step_incr\n        e tid mem lc1 lc2\n        (LC: step e tid mem lc1 lc2):\n    le lc1 lc2.\n  Proof.\n    inv LC; try refl.\n    - eapply read_incr. eauto.\n    - eapply fulfill_incr. eauto.\n    - eapply rmw_incr. eauto.\n    - eapply rmw_failure_incr. eauto.\n    - eapply mfence_incr. eauto.\n    - eapply sfence_incr. eauto.\n    - eapply flush_incr. eauto.\n    - eapply flushopt_incr. eauto.\n  Qed.\n\n  Lemma high_ts_spec\n        tid mem lc ts\n        (WF: wf tid mem lc)\n        (GT: forall loc, (lc.(coh) loc).(View.ts) < ts):\n      <<NOFWD: forall loc, read_view (lc.(coh) loc) ts = View.mk ts bot >> /\\\n      <<JOINS: forall loc, ts = join (lc.(coh) loc).(View.ts)\n                                     (read_view (lc.(coh) loc) ts).(View.ts)>>.\n  Proof.\n    assert (NOFWD: forall loc, read_view (lc.(coh) loc) ts = View.mk ts bot).\n    { i. unfold read_view. condtac; ss.\n      inversion e. inv H. inv WF.\n      specialize (FWDBANK loc). inv FWDBANK.\n      assert (COHLE: Memory.latest_ts loc (View.ts (coh lc loc)) mem <= View.ts (coh lc loc)).\n      { eapply Memory.latest_ts_spec. }\n      specialize (GT loc).\n      lia.\n    }\n    splits; ss. i. apply le_antisym.\n    { repeat rewrite <- join_r. rewrite NOFWD. ss. }\n    inv WF. inv COHMAX. viewtac.\n    - specialize (GT loc). lia.\n    - rewrite NOFWD. ss.\n  Qed.\n\n  Lemma high_ts_spec_cl\n        tid mem lc ts loc0\n        (WF: wf tid mem lc)\n        (GT: forall loc (CL: Loc.cl loc loc0), (lc.(coh) loc).(View.ts) < ts):\n      <<NOFWD: forall loc (CL: Loc.cl loc loc0), read_view (lc.(coh) loc) ts = View.mk ts bot >> /\\\n      <<JOINS: forall loc (CL: Loc.cl loc loc0),\n                  ts = join (lc.(coh) loc).(View.ts)\n                            (read_view (lc.(coh) loc) ts).(View.ts)>>.\n  Proof.\n    assert (NOFWD: forall loc (CL: Loc.cl loc loc0), read_view (lc.(coh) loc) ts = View.mk ts bot).\n    { i. unfold read_view. condtac; ss.\n      inversion e. inv H. inv WF.\n      specialize (FWDBANK loc). inv FWDBANK.\n      apply GT in CL. lia.\n    }\n    splits; ss. i. apply le_antisym.\n    { repeat rewrite <- join_r. rewrite NOFWD; ss. }\n    inv WF. inv COHMAX. viewtac.\n    - apply GT in CL. lia.\n    - rewrite NOFWD; ss.\n  Qed.\n\n  Lemma step_wf\n        tid e mem lc1 lc2\n        (STEP: step e tid mem lc1 lc2)\n        (WF: wf tid mem lc1):\n    wf tid mem lc2.\n  Proof.\n    assert (FWDVIEW: forall loc ts,\n               (View.ts (coh lc1 loc)) <= ts ->\n               ts <= length mem ->\n               View.ts (read_view (coh lc1 loc) ts) <= length mem).\n    { i. rewrite fwd_read_view_le; eauto. }\n    inversion WF. inv STEP; ss; inv STEP0.\n    - exploit FWDVIEW; eauto.\n      { eapply Memory.read_wf. eauto. }\n      i. econs; viewtac.\n      + i. rewrite fun_add_spec. condtac; viewtac. eapply Memory.read_spec; eauto.\n      + i. exploit FWDBANK; eauto. intro Y. inv Y. des.\n        econs; eauto. rewrite fun_add_spec. condtac; ss; eauto.\n        inversion e. subst. eauto.\n      + i. eapply PROMISES0; eauto. eapply Time.le_lt_trans; [|by eauto].\n        rewrite fun_add_spec. condtac; ss. inversion e. rewrite H0. unfold Order.le in COH0. ss.\n      + inv COHMAX. inv COHMAX0. rename x0 into mloc.\n        destruct (lt_eq_lt_dec ts (View.ts (coh lc1 mloc))).\n        { econs; ss.\n          - econs; cycle 1.\n            { i. funtac. econs; ss. unfold Order.le. inv s; lia. }\n            funtac. inv s; ss.\n            + inversion e. subst. unfold Order.le in *. lia.\n            + destruct (coh lc1 mloc). s. destruct annot. ss.\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n        }\n        { exploit high_ts_spec; eauto.\n          { i. eapply le_lt_trans; try exact l. specialize (MAX loc). inv MAX. viewtac. }\n          i. des.\n          econs. instantiate (1 := (View.mk ts bot)).\n          - econs; ss.\n            { funtac. exfalso. apply c. ss. }\n            i. funtac; econs; ss.\n            unfold Order.le. etrans; [apply MAX|]. lia.\n          - viewtac.\n            { rewrite VRN0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - viewtac.\n            { rewrite VPR0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - i. ss. rewrite VPA0. lia.\n          - i. ss. rewrite VPC0. lia.\n        }\n      + i. revert TS. funtac; cycle 1.\n        { i. rewrite <- join_l. eapply NFWD; eauto. }\n        i. subst. unfold read_view. condtac; ss.\n        * rewrite <- join_l. eapply NFWD; eauto. inversion e0. inversion e. ss.\n        * viewtac; rewrite <- join_r; ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec ts from); eauto. apply not_le in n.\n        destruct (lt_dec to ts); eauto. apply not_lt in n0.\n        unfold Memory.read in MSG. destruct ts; try lia. ss. des_ifs.\n        exfalso. eapply LATEST0; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - inversion WRITABLE.\n      econs; viewtac; rewrite <- ? TS0, <- ? TS1.\n      + i. rewrite fun_add_spec. condtac; viewtac.\n      + i. rewrite ? fun_add_spec. condtac; viewtac.\n        inversion e. subst.\n        econs; viewtac.\n        revert MSG. unfold Memory.read, Memory.get_msg.\n        destruct ts; ss. i. rewrite MSG. ss. eexists. des_ifs.\n      + i. revert IN. rewrite Promises.unset_o. condtac; ss. eauto.\n      + i. rewrite Promises.unset_o. rewrite fun_add_spec in TS. condtac.\n        { inversion e. subst. rewrite MSG in MSG0. destruct msg. inv MSG0. ss.\n          revert TS. condtac; ss; intuition.\n        }\n        { eapply PROMISES0; eauto. revert TS. condtac; ss. i.\n          inversion e. rewrite H0.\n          exploit writable_lt_coh_ts; eauto. lia.\n        }\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs.\n        * econs; ss. instantiate (1 := ValA.val vloc).\n          i. repeat rewrite fun_add_spec. repeat condtac; ss.\n          { econs; ss. }\n          { exfalso. apply c. ss. }\n          { econs; ss. unfold Order.le. etrans; [apply MAX|]. lia. }\n          { exfalso. apply c0. ss. }\n        * funtac. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * funtac. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * i. ss. funtac. rewrite VPA0. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * i. ss. funtac. rewrite VPC0. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n      + i. eapply NFWD; eauto.\n        rewrite fun_add_spec in TS. eqvtac.\n        rewrite MSG in MSG0. inv MSG0. ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec ts from); eauto. apply not_le in n.\n        destruct (lt_dec to ts); eauto. apply not_lt in n0.\n        unfold Memory.get_msg in MSG. destruct ts; try lia. ss.\n        exfalso. eapply LATEST; eauto.\n    - inversion WRITABLE.\n      econs; viewtac; rewrite <- ? TS0, <- ? TS1.\n      + i. rewrite fun_add_spec. condtac; viewtac.\n      + i. viewtac.\n      + i. rewrite ? fun_add_spec. condtac; viewtac.\n        inversion e. subst.\n        econs; viewtac.\n        revert MSG. unfold Memory.read, Memory.get_msg.\n        destruct ts; ss. i. rewrite MSG. ss. eexists. des_ifs.\n      + i. revert IN. rewrite Promises.unset_o. condtac; ss. eauto.\n      + i. rewrite Promises.unset_o. rewrite fun_add_spec in TS. condtac.\n        { inversion e. subst. rewrite MSG in MSG0. destruct msg. inv MSG0. ss.\n        revert TS. condtac; ss; intuition.\n        }\n        { eapply PROMISES0; eauto. revert TS. condtac; ss. i.\n          inversion e. rewrite H0.\n          exploit writable_lt_coh_ts; eauto. lia.\n        }\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs.\n        * econs; ss. instantiate (1 := ValA.val vloc).\n          i. repeat rewrite fun_add_spec. repeat condtac; ss.\n          { econs; ss. }\n          { exfalso. apply c. ss. }\n          { econs; ss. unfold Order.le. etrans; [apply MAX|]. lia. }\n          { exfalso. apply c0. ss. }\n        * rewrite fun_add_spec. condtac; ss; cycle 1.\n          { exfalso. apply c. ss. }\n          viewtac. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * rewrite fun_add_spec. condtac; ss; cycle 1.\n          { exfalso. apply c. ss. }\n          viewtac. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * i. ss. funtac. rewrite VPA0. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n        * i. ss. funtac. viewtac.\n          { rewrite VPC0. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia. }\n          rewrite VPA0. specialize (MAX x0). inv MAX. unfold Order.le in TS. lia.\n      + i. rewrite <- join_l. eapply NFWD; eauto.\n        rewrite fun_add_spec in TS. eqvtac.\n        rewrite MSG in MSG0. inv MSG0. ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec ts from); eauto. apply not_le in n.\n        destruct (lt_dec to ts); eauto. apply not_lt in n0.\n        unfold Memory.get_msg in MSG. destruct ts; try lia. ss.\n        exfalso. eapply LATEST; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - exploit FWDVIEW; eauto.\n      { eapply Memory.read_wf. eauto. }\n      i. econs; viewtac.\n      + i. rewrite fun_add_spec. condtac; viewtac. eapply Memory.read_spec; eauto.\n      + i. exploit FWDBANK; eauto. intro Y. inv Y. des.\n        econs; eauto. rewrite fun_add_spec. condtac; ss; eauto.\n        inversion e. subst. eauto.\n      + i. eapply PROMISES0; eauto. eapply Time.le_lt_trans; [|by eauto].\n        rewrite fun_add_spec. condtac; ss. inversion e. rewrite H0. unfold Order.le in COH0. ss.\n      + inv COHMAX. inv COHMAX0. rename x0 into mloc.\n        destruct (lt_eq_lt_dec old_ts (View.ts (coh lc1 mloc))).\n        { econs; ss.\n          - econs; cycle 1.\n            { i. funtac. econs; ss. unfold Order.le. inv s; lia. }\n            funtac. inv s; ss.\n            + inversion e. subst. unfold Order.le in *. lia.\n            + destruct (coh lc1 mloc). s. destruct annot. ss.\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n        }\n        { exploit high_ts_spec; eauto.\n          { i. eapply le_lt_trans; try exact l. specialize (MAX loc). inv MAX. viewtac. }\n          i. des.\n          econs. instantiate (1 := (View.mk old_ts bot)).\n          - econs; ss.\n            { funtac. exfalso. apply c. ss. }\n            i. funtac; econs; ss.\n            unfold Order.le. etrans; [apply MAX|]. lia.\n          - viewtac.\n            { rewrite VRN0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - viewtac.\n            { rewrite VPR0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - i. ss. rewrite VPA0. lia.\n          - i. ss. rewrite VPC0. lia.\n        }\n      + i. revert TS. funtac; cycle 1.\n        { i. rewrite <- join_l. eapply NFWD; eauto. }\n        i. subst. unfold read_view. condtac; ss.\n        * rewrite <- join_l. eapply NFWD; eauto. inversion e0. inversion e. ss.\n        * viewtac; rewrite <- join_r; ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec old_ts from); eauto. apply not_le in n.\n        destruct (lt_dec to old_ts); eauto. apply not_lt in n0.\n        unfold Memory.read in OLD_MSG. destruct old_ts; try lia. ss. des_ifs.\n        exfalso. eapply LATEST0; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - econs; viewtac.\n      + inv COHMAX0. ss.\n      + inv COHMAX0. ss.\n      + i. viewtac.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n      + i. rewrite <- join_l. eapply NFWD; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - econs; viewtac.\n      + inv COHMAX0. ss.\n      + i. viewtac.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n      + rewrite VRNVPR. apply join_l.\n    - econs; viewtac.\n      + i. viewtac. inv COHMAX0. ss.\n      + i. viewtac. inv COHMAX0. ss.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * i. viewtac.\n          specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n          specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n      + i. rewrite VPACL at 1; eauto. viewtac. unfold ifc. repeat condtac; ss.\n        * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n        * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n          intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n      + i. rewrite VPCCL at 1; eauto. viewtac. unfold ifc. repeat condtac; ss.\n        * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n        * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n          intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n    - econs; viewtac.\n      + i. viewtac. inv COHMAX_CL. unfold ifc. condtac; ss. apply bot_spec.\n      + inv COHMAX. inv COHMAX0. econs; s; eauto. i. viewtac.\n        inv COHMAX_CL. unfold ifc. condtac; [|apply bot_spec].\n        specialize (MAX x0). inv MAX. unfold Order.le in *. ss.\n      + i. rewrite VPACL at 1; eauto. unfold ifc. repeat condtac; ss.\n        * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n        * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n          intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n  Qed.\n\n  Lemma view_step_wf\n        tid e mem1 mem2 lc1 lc2\n        (STEP: view_step e tid mem1 mem2 lc1 lc2)\n        (WF: wf tid mem1 lc1):\n    wf tid mem2 lc2.\n  Proof.\n    assert (FWDVIEW: forall loc ts,\n               (View.ts (coh lc1 loc)) <= ts ->\n               ts <= length mem1 ->\n               View.ts (read_view (coh lc1 loc) ts) <= length mem1).\n    { i. rewrite fwd_read_view_le; eauto. }\n    inversion WF. inv STEP; ss; inv STEP0.\n    - exploit FWDVIEW; eauto.\n      { eapply Memory.read_wf. eauto. }\n      i. econs; viewtac.\n      + i. rewrite fun_add_spec. condtac; viewtac. eapply Memory.read_spec; eauto.\n      + i. exploit FWDBANK; eauto. intro Y. inv Y. des.\n        econs; eauto. rewrite fun_add_spec. condtac; ss; eauto.\n        inversion e. subst. eauto.\n      + i. eapply PROMISES0; eauto. eapply Time.le_lt_trans; [|by eauto].\n        rewrite fun_add_spec. condtac; ss. inversion e. rewrite H0. unfold Order.le in COH0. ss.\n      + inv COHMAX. inv COHMAX0. rename x0 into mloc.\n        destruct (lt_eq_lt_dec ts (View.ts (coh lc1 mloc))).\n        { econs; ss.\n          - econs; cycle 1.\n            { i. funtac. econs; ss. unfold Order.le. inv s; lia. }\n            funtac. inv s; ss.\n            + inversion e. subst. unfold Order.le in *. lia.\n            + destruct (coh lc1 mloc). s. destruct annot. ss.\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n        }\n        { exploit high_ts_spec; eauto.\n          { i. eapply le_lt_trans; try exact l. specialize (MAX loc). inv MAX. viewtac. }\n          i. des.\n          econs. instantiate (1 := (View.mk ts bot)).\n          - econs; ss.\n            { funtac. exfalso. apply c. ss. }\n            i. funtac; econs; ss.\n            unfold Order.le. etrans; [apply MAX|]. lia.\n          - viewtac.\n            { rewrite VRN0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - viewtac.\n            { rewrite VPR0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - i. ss. rewrite VPA0. lia.\n          - i. ss. rewrite VPC0. lia.\n        }\n      + i. revert TS. funtac; cycle 1.\n        { i. rewrite <- join_l. eapply NFWD; eauto. }\n        i. subst. unfold read_view. condtac; ss.\n        * rewrite <- join_l. eapply NFWD; eauto. inversion e0. inversion e. ss.\n        * viewtac; rewrite <- join_r; ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec ts from); eauto. apply not_le in n.\n        destruct (lt_dec to ts); eauto. apply not_lt in n0.\n        unfold Memory.read in MSG. destruct ts; try lia. ss. des_ifs.\n        exfalso. eapply LATEST0; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - inversion MEM. subst. econs; try rewrite app_length; viewtac; ss.\n      all: try by lia.\n      + i. funtac; try rewrite COH; lia.\n      + i. rewrite VPA. lia.\n      + i. rewrite VPC. lia.\n      + i. funtac; cycle 1.\n        { apply wf_fwdbank_mon. specialize (FWDBANK loc). ss. }\n        inversion e. subst. econs.\n        exploit Memory.append_spec; eauto.\n        unfold Memory.read, Memory.get_msg. destruct (S (length mem1)); ss. intro MSG. des.\n        rewrite MSG. ss. eexists. des_ifs.\n      + i. apply PROMISES in IN. lia.\n      + i. inv MEM. eapply PROMISES0; eauto.\n        * generalize MSG. intro X.\n          eapply Memory.get_msg_snoc_inv in X. des; ss.\n          revert TS. funtac.\n          { i. lia. }\n          exfalso. apply c. inv X0. ss.\n        * revert TS. funtac. i.\n          etrans; try exact TS; eauto. eapply le_lt_trans; [rewrite COH; eauto | lia].\n      + econs. instantiate (1 := (View.mk (S (length mem1)) bot)).\n        all: viewtac.\n        econs; ss.\n        { funtac. exfalso. apply c. ss. }\n        i. funtac; econs; ss.\n        unfold Order.le. rewrite COH. lia.\n      + i. inv MEM.\n        eapply Memory.get_msg_snoc_inv in MSG. revert MSG. funtac.\n        * i. des; [lia |]. inv MSG0. ss.\n        * i. des; [eapply NFWD; eauto |]. inv MSG0. ss.\n      + i. funtac; cycle 1.\n        { apply NINTERVENING. eapply Memory.latest_app_inv. eauto. }\n        inversion e. subst.\n        destruct (le_dec (S (length mem1)) from); eauto. apply not_le in n.\n        destruct (lt_dec to (S (length mem1))); eauto. apply not_lt in n0.\n        exfalso. eapply LATEST; eauto; try rewrite nth_error_last; ss.\n    - inversion MEM. subst. econs; try rewrite app_length; viewtac; ss.\n      all: try by lia.\n      + i. funtac; try rewrite COH; lia.\n      + i. rewrite VPA. lia.\n      + i. viewtac; [rewrite VPC|rewrite VPA]; lia.\n      + i. funtac; cycle 1.\n        { apply wf_fwdbank_mon. specialize (FWDBANK loc). ss. }\n        inversion e. subst. econs.\n        exploit Memory.append_spec; eauto.\n        unfold Memory.read, Memory.get_msg. destruct (S (length mem1)); ss. intro MSG. des.\n        rewrite MSG. ss. eexists. des_ifs.\n      + i. apply PROMISES in IN. lia.\n      + i. inv MEM. eapply PROMISES0; eauto.\n        * generalize MSG. intro X.\n          eapply Memory.get_msg_snoc_inv in X. des; ss.\n          revert TS. funtac.\n          { i. lia. }\n          exfalso. apply c. inv X0. ss.\n        * revert TS. funtac. i.\n          etrans; try exact TS; eauto. eapply le_lt_trans; [rewrite COH; eauto | lia].\n      + econs. instantiate (1 := (View.mk (S (length mem1)) bot)).\n        all: try i; viewtac.\n        econs; ss.\n        { funtac. exfalso. apply c. ss. }\n        i. funtac; econs; ss.\n        unfold Order.le. rewrite COH. lia.\n      + i. inv MEM.\n        eapply Memory.get_msg_snoc_inv in MSG. revert MSG. funtac.\n        * i. des; [lia |]. inv MSG0. ss.\n        * i. rewrite <- join_l. des; [eapply NFWD; eauto |]. inv MSG0. ss.\n      + i. funtac; cycle 1.\n        { apply NINTERVENING. eapply Memory.latest_app_inv. eauto. }\n        inversion e. subst.\n        destruct (le_dec (S (length mem1)) from); eauto. apply not_le in n.\n        destruct (lt_dec to (S (length mem1))); eauto. apply not_lt in n0.\n        exfalso. eapply LATEST; eauto; try rewrite nth_error_last; ss.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - exploit FWDVIEW; eauto.\n      { eapply Memory.read_wf. eauto. }\n      i. econs; viewtac.\n      + i. rewrite fun_add_spec. condtac; viewtac. eapply Memory.read_spec; eauto.\n      + i. exploit FWDBANK; eauto. intro Y. inv Y. des.\n        econs; eauto. rewrite fun_add_spec. condtac; ss; eauto.\n        inversion e. subst. eauto.\n      + i. eapply PROMISES0; eauto. eapply Time.le_lt_trans; [|by eauto].\n        rewrite fun_add_spec. condtac; ss. inversion e. rewrite H0. unfold Order.le in COH0. ss.\n      + inv COHMAX. inv COHMAX0. rename x0 into mloc.\n        destruct (lt_eq_lt_dec old_ts (View.ts (coh lc1 mloc))).\n        { econs; ss.\n          - econs; cycle 1.\n            { i. funtac. econs; ss. unfold Order.le. inv s; lia. }\n            funtac. inv s; ss.\n            + inversion e. subst. unfold Order.le in *. lia.\n            + destruct (coh lc1 mloc). s. destruct annot. ss.\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n          - viewtac. unfold read_view.\n            condtac; [apply bot_spec | inv s; ss; lia].\n        }\n        { exploit high_ts_spec; eauto.\n          { i. eapply le_lt_trans; try exact l. specialize (MAX loc). inv MAX. viewtac. }\n          i. des.\n          econs. instantiate (1 := (View.mk old_ts bot)).\n          - econs; ss.\n            { funtac. exfalso. apply c. ss. }\n            i. funtac; econs; ss.\n            unfold Order.le. etrans; [apply MAX|]. lia.\n          - viewtac.\n            { rewrite VRN0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - viewtac.\n            { rewrite VPR0. lia. }\n            unfold read_view. condtac; [apply bot_spec | ss].\n          - i. ss. rewrite VPA0. lia.\n          - i. ss. rewrite VPC0. lia.\n        }\n      + i. revert TS. funtac; cycle 1.\n        { i. rewrite <- join_l. eapply NFWD; eauto. }\n        i. subst. unfold read_view. condtac; ss.\n        * rewrite <- join_l. eapply NFWD; eauto. inversion e0. inversion e. ss.\n        * viewtac; rewrite <- join_r; ss.\n      + i. funtac. inversion e. subst.\n        destruct (le_dec old_ts from); eauto. apply not_le in n.\n        destruct (lt_dec to old_ts); eauto. apply not_lt in n0.\n        unfold Memory.read in OLD_MSG. destruct old_ts; try lia. ss. des_ifs.\n        exfalso. eapply LATEST0; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - econs; viewtac.\n      + inv COHMAX0. ss.\n      + inv COHMAX0. ss.\n      + i. viewtac.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n      + i. rewrite <- join_l. eapply NFWD; eauto.\n      + rewrite VRNVPR. apply join_l.\n      + apply join_r.\n    - econs; viewtac.\n      + inv COHMAX0. ss.\n      + i. viewtac.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * viewtac. specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n      + rewrite VRNVPR. apply join_l.\n    - econs; viewtac.\n      + i. viewtac. inv COHMAX0. ss.\n      + i. viewtac. inv COHMAX0. ss.\n      + inv COHMAX. inv COHMAX0. inv COHMAX1. econs; s; eauto.\n        * i. viewtac.\n          specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n        * i. viewtac.\n          specialize (MAX0 x). inv MAX0. unfold Order.le in *. lia.\n      + i. rewrite VPACL at 1; eauto. viewtac. unfold ifc. repeat condtac; ss.\n        * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n        * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n          intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n      + i. rewrite VPCCL at 1; eauto. viewtac. unfold ifc. repeat condtac; ss.\n          * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n          * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n            intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n    - econs; viewtac.\n      + i. viewtac. inv COHMAX_CL. unfold ifc. condtac; ss. apply bot_spec.\n      + inv COHMAX. inv COHMAX0. econs; s; eauto. i. viewtac.\n        inv COHMAX_CL. unfold ifc. condtac; [|apply bot_spec].\n        specialize (MAX x0). inv MAX. unfold Order.le in *. ss.\n      + i. rewrite VPACL at 1; eauto. unfold ifc. repeat condtac; ss.\n        * exploit Loc.cl_trans; eauto. rewrite X0. ss.\n        * apply Loc.cl_sym in X0. exploit Loc.cl_trans; try exact CL; eauto.\n          intro Z. apply Loc.cl_sym in Z. rewrite X in Z. ss.\n  Qed.\nEnd Local.\nEnd Local.\n\nModule ExecUnit.\nSection ExecUnit.\n  Inductive t := mk {\n    state: State.t (A:=unit);\n    local: Local.t;\n    mem: Memory.t;\n  }.\n  Hint Constructors t.\n\n  Inductive state_step0 (tid:Id.t) (e1 e2:Event.t (A:=unit)) (eu1 eu2:t): Prop :=\n  | state_step0_intro\n      (STATE: State.step e1 eu1.(state) eu2.(state))\n      (LOCAL: Local.step e2 tid eu1.(mem) eu1.(local) eu2.(local))\n      (MEM: eu2.(mem) = eu1.(mem))\n  .\n  Hint Constructors state_step0.\n\n  Inductive state_step (tid:Id.t) (eu1 eu2:t): Prop :=\n  | state_step_intro\n      e\n      (STEP: state_step0 tid e e eu1 eu2)\n  .\n  Hint Constructors state_step.\n\n  Inductive promise_step (tid:Id.t) (eu1 eu2:t): Prop :=\n  | promise_step_intro\n      loc val ts\n      (STATE: eu1.(state) = eu2.(state))\n      (LOCAL: Local.promise loc val ts tid eu1.(local) eu1.(mem) eu2.(local) eu2.(mem))\n  .\n  Hint Constructors promise_step.\n\n  Inductive step (tid:Id.t) (eu1 eu2:t): Prop :=\n  | step_state (STEP: state_step tid eu1 eu2)\n  | step_promise (STEP: promise_step tid eu1 eu2)\n  .\n  Hint Constructors step.\n\n  Inductive view_step0 (tid:Id.t) (e1 e2:Event.t (A:=unit)) (eu1 eu2:t): Prop :=\n  | view_step0_intro\n      (STATE: State.step e1 eu1.(state) eu2.(state))\n      (LOCAL: Local.view_step e2 tid eu1.(mem) eu2.(mem) eu1.(local) eu2.(local))\n  .\n  Hint Constructors view_step0.\n\n  Inductive view_step (tid:Id.t) (eu1 eu2:t): Prop :=\n  | view_step_intro\n      e\n      (STEP: view_step0 tid e e eu1 eu2)\n  .\n  Hint Constructors view_step.\n\n  Inductive wf (tid:Id.t) (eu:t): Prop :=\n  | wf_intro\n      (LOCAL: Local.wf tid eu.(mem) eu.(local))\n  .\n  Hint Constructors wf.\n\n  Lemma state_step0_wf tid e eu1 eu2\n        (STEP: state_step0 tid e e eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    inv WF. inv STEP. econs; ss.\n    rewrite MEM. eapply Local.step_wf; eauto.\n  Qed.\n\n  Lemma state_step_wf tid eu1 eu2\n        (STEP: state_step tid eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    inv STEP. eapply state_step0_wf; eauto.\n  Qed.\n\n  Lemma rtc_state_step_wf tid eu1 eu2\n        (STEP: rtc (state_step tid) eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply state_step_wf; eauto.\n  Qed.\n\n  Lemma promise_step_wf tid eu1 eu2\n        (STEP: promise_step tid eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    destruct eu1 as [state1 local1 mem1].\n    destruct eu2 as [state2 local2 mem2].\n    inv WF. inv STEP. ss. subst.\n    inv LOCAL. inv LOCAL0. inv MEM2. econs; ss.\n    econs; eauto.\n    all: try rewrite List.app_length; s; try lia.\n    - i. rewrite COH. lia.\n    - i. rewrite VPA. lia.\n    - i. rewrite VPC. lia.\n    - i. destruct (FWDBANK loc0). des. econs; esplits; ss.\n      apply Memory.read_mon; eauto.\n    - i. revert IN. rewrite Promises.set_o. condtac.\n      + inversion e. i. inv IN. lia.\n      + i. exploit PROMISES; eauto. lia.\n    - i. rewrite Promises.set_o. apply Memory.get_msg_snoc_inv in MSG. des.\n      + destruct ts; ss. condtac; ss.\n        eapply PROMISES0; eauto.\n      + subst. condtac; ss. congr.\n    - inv COHMAX. inv COHMAX0. econs; viewtac.\n    - i. apply Memory.get_msg_snoc_inv in MSG. des.\n      + eapply NFWD; eauto.\n      + rewrite <- MSG0 in TID. ss.\n    - i. apply NINTERVENING. eapply Memory.latest_app_inv. eauto.\n  Qed.\n\n  Lemma step_wf tid eu1 eu2\n        (STEP: step tid eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    inv STEP.\n    - eapply state_step_wf; eauto.\n    - eapply promise_step_wf; eauto.\n  Qed.\n\n  Lemma view_step0_wf tid e eu1 eu2\n        (STEP: view_step0 tid e e eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    inv WF. inv STEP. econs; ss.\n    eapply Local.view_step_wf; eauto.\n  Qed.\n\n  Lemma view_step_wf tid eu1 eu2\n        (STEP: view_step tid eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    inv STEP. eapply view_step0_wf; eauto.\n  Qed.\n\n  Lemma rtc_view_step_wf tid eu1 eu2\n        (STEP: rtc (view_step tid) eu1 eu2)\n        (WF: wf tid eu1):\n    wf tid eu2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply view_step_wf; eauto.\n  Qed.\n\n  Inductive le (eu1 eu2:t): Prop :=\n  | le_intro\n      mem'\n      (LC: Local.le eu1.(local) eu2.(local))\n      (MEM: eu2.(mem) = eu1.(mem) ++ mem')\n  .\n\n  Global Program Instance le_partial_order: PreOrder le.\n  Next Obligation.\n    econs.\n    - refl.\n    - rewrite app_nil_r. ss.\n  Qed.\n  Next Obligation.\n    ii. inv H. inv H0. econs; etrans; eauto.\n    rewrite MEM, app_assoc. eauto.\n  Qed.\n\n  Lemma state_step_incr tid eu1 eu2\n        (STEP: state_step tid eu1 eu2):\n    le eu1 eu2.\n  Proof.\n    inv STEP. inv STEP0. econs.\n    - eapply Local.step_incr. eauto.\n    - rewrite MEM, app_nil_r. ss.\n  Qed.\n\n  Lemma rtc_state_step_incr\n        tid eu1 eu2\n        (STEP: rtc (state_step tid) eu1 eu2):\n    le eu1 eu2.\n  Proof.\n    induction STEP; try refl.\n    exploit state_step_incr; eauto. i.\n    etrans; eauto.\n  Qed.\n\n  Lemma promise_step_incr tid eu1 eu2\n        (STEP: promise_step tid eu1 eu2):\n    le eu1 eu2.\n  Proof.\n    inv STEP. econs.\n    - eapply Local.promise_incr. eauto.\n    - inv LOCAL. inv MEM2. ss.\n  Qed.\n\n  Lemma step_incr tid eu1 eu2\n        (STEP: step tid eu1 eu2):\n    le eu1 eu2.\n  Proof.\n    inv STEP.\n    - eapply state_step_incr. eauto.\n    - eapply promise_step_incr. eauto.\n  Qed.\n\n  Lemma state_step_promise_remained tid eu1 eu2 ts loc val\n        (WF: wf tid eu1)\n        (STEP: state_step tid eu1 eu2)\n        (LE: ts <= (eu1.(ExecUnit.local).(Local.coh) loc).(View.ts))\n        (MSG: Memory.get_msg ts eu1.(ExecUnit.mem) = Some (Msg.mk loc val tid))\n        (PROMISE: Promises.lookup ts eu1.(ExecUnit.local).(Local.promises)):\n    Promises.lookup ts eu2.(ExecUnit.local).(Local.promises).\n  Proof.\n    inv STEP. inv STEP0. inv LOCAL.\n    - rewrite LC. ss.\n    - inv STEP. rewrite LC2. ss.\n    - inv STEP. rewrite LC2. ss.\n      destruct (ts == ts0).\n      + inv e. rewrite MSG in MSG0. inv MSG0.\n        exploit Local.writable_lt_coh_ts; eauto. lia.\n      + exploit Promises.unset_o. intro UNSET.\n        rewrite UNSET. eqvtac.\n    - inv STEP. rewrite LC2. ss.\n      destruct (ts == ts0).\n      + inv e. rewrite MSG in MSG0. inv MSG0.\n        exploit Local.writable_lt_coh_ts; eauto. lia.\n      + exploit Promises.unset_o. intro UNSET.\n        rewrite UNSET. eqvtac.\n    - inv STEP. rewrite LC2. ss.\n    - inv STEP. rewrite LC2. ss.\n    - inv STEP. rewrite LC2. ss.\n    - inv STEP. rewrite LC2. ss.\n    - inv STEP. rewrite LC2. ss.\n  Qed.\n\n  Lemma rtc_state_step_promise_remained tid eu1 eu2 ts loc val\n        (WF: Local.wf tid eu1.(ExecUnit.mem) eu1.(ExecUnit.local))\n        (STEP: rtc (state_step tid) eu1 eu2)\n        (LE: ts <= (eu1.(ExecUnit.local).(Local.coh) loc).(View.ts))\n        (MSG: Memory.get_msg ts eu1.(ExecUnit.mem) = Some (Msg.mk loc val tid))\n        (PROMISE: Promises.lookup ts eu1.(ExecUnit.local).(Local.promises)):\n    Promises.lookup ts eu2.(ExecUnit.local).(Local.promises).\n  Proof.\n    induction STEP; ss. eapply IHSTEP.\n    - eapply state_step_wf; eauto.\n    - inv H. inv STEP0. inv LOCAL.\n      + rewrite LC. ss.\n      + inv STEP0. rewrite LC2. ss. rewrite fun_add_spec. condtac; ss.\n        inversion e. subst. etrans; eauto.\n      + inv STEP0. rewrite LC2. ss. rewrite fun_add_spec. condtac; ss.\n        inversion e. subst. exploit Local.writable_lt_coh_ts; eauto. lia.\n      + inv STEP0. rewrite LC2. ss. rewrite fun_add_spec. condtac; ss.\n        inversion e. subst. exploit Local.writable_lt_coh_ts; eauto. lia.\n      + inv STEP0. rewrite LC2. ss. rewrite fun_add_spec. condtac; ss.\n        inversion e. subst. etrans; eauto.\n      + inv STEP0. rewrite LC2. ss.\n      + inv STEP0. rewrite LC2. ss.\n      + inv STEP0. rewrite LC2. ss.\n      + inv STEP0. rewrite LC2. ss.\n    - inv H. inv STEP0. rewrite MEM. ss.\n    - exploit state_step_promise_remained; eauto.\n  Qed.\n\n  Lemma rtc_state_step_mem\n        tid eu1 eu2\n        (STEP: rtc (ExecUnit.state_step tid) eu1 eu2):\n    eu1.(ExecUnit.mem) = eu2.(ExecUnit.mem).\n  Proof.\n    induction STEP; ss.\n    inv H. inv STEP0. rewrite <- MEM. ss.\n  Qed.\n\n  Lemma no_promise_rmw_spec\n        eu1 eu2 eu_last\n        vloc vold vnew old_ts ts tid\n        (WF: Local.wf tid eu1.(ExecUnit.mem) eu1.(ExecUnit.local))\n        (MEM: eu1.(ExecUnit.mem) = eu2.(ExecUnit.mem))\n        (RMW_STEP: Local.rmw vloc vold vnew old_ts ts tid eu1.(ExecUnit.local) eu1.(ExecUnit.mem) eu2.(ExecUnit.local))\n        (RTC_STEP: rtc (ExecUnit.state_step tid) eu2 eu_last)\n        (NOPROMISE: eu_last.(ExecUnit.local).(Local.promises) = bot):\n      old_ts = Memory.latest_ts (ValA.val vloc) (Init.Nat.pred ts) (eu1.(ExecUnit.mem)).\n  Proof.\n    generalize RMW_STEP. intro RMW. inv RMW.\n    eapply le_antisym; ss.\n    { eapply Memory.latest_ts_read_le; eauto. lia. }\n    eapply Memory.latest_latest_ts. ii.\n    unfold Memory.exclusive in EX. unfold Memory.no_msgs in EX. exploit EX; eauto.\n    { etrans; eauto. lia. }\n    split; ss. destruct msg as [ts' val' tidtmp]. destruct (tidtmp == tid); ss. inv e.\n    unfold Order.le in COH.\n    destruct (lt_eq_lt_dec (S ts0) (View.ts (Local.coh (ExecUnit.local eu1) (ValA.val vloc)))). inv s; try lia.\n    inversion WF.\n    exploit PROMISES0; [| | instantiate (1 := S ts0)|]; eauto. intro PROMISE_TS.\n    assert (PROMISE_TS0: Promises.lookup (S ts0) (Local.promises (ExecUnit.local eu2))).\n    { rewrite LC2. ss. exploit Promises.unset_o. intro UNSET. rewrite UNSET. condtac; ss. inversion e. lia. }\n    exploit ExecUnit.rtc_state_step_promise_remained; try exact PROMISE_TS0; eauto.\n    { rewrite <- MEM. eapply Local.step_wf; eauto. econs 4; eauto. }\n    { instantiate (1 := ValA.val vloc). rewrite LC2. ss.\n      rewrite fun_add_spec. condtac; cycle 1.\n      { exfalso. apply c. ss. }\n      etrans; eauto. ss. lia.\n    }\n    { rewrite <- MEM. unfold Memory.get_msg. ss. rewrite MSG0. ss. }\n    unfold Promises.lookup. ss. rewrite NOPROMISE. ss.\n    Grab Existential Variables.\n    all: auto.\n  Qed.\nEnd ExecUnit.\nEnd ExecUnit.\n\nModule Machine.\n  Inductive t := mk {\n    tpool: IdMap.t (State.t (A:=unit) * Local.t);\n    mem: Memory.t;\n  }.\n  Hint Constructors t.\n\n  Definition init (p:program): t :=\n    mk\n      (IdMap.map (fun stmts => (State.init stmts, Local.init)) p)\n      Memory.empty.\n\n  Inductive is_terminal (m:t): Prop :=\n  | is_terminal_intro\n      (TERMINAL:\n         forall tid st lc\n           (FIND: IdMap.find tid m.(tpool) = Some (st, lc)),\n           State.is_terminal st /\\ lc.(Local.promises) = bot)\n  .\n  Hint Constructors is_terminal.\n\n  Inductive no_promise (m:t): Prop :=\n  | no_promise_intro\n      (PROMISES:\n         forall tid st lc\n           (FIND: IdMap.find tid m.(tpool) = Some (st, lc)),\n           lc.(Local.promises) = bot)\n  .\n  Hint Constructors no_promise.\n\n  Lemma is_terminal_no_promise\n        m\n        (TERMINAL: is_terminal m):\n    no_promise m.\n  Proof.\n    econs. i. eapply TERMINAL. eauto.\n  Qed.\n\n  Inductive step (eustep: forall (tid:Id.t) (eu1 eu2:ExecUnit.t), Prop) (m1 m2:t): Prop :=\n  | step_intro\n      tid st1 lc1 st2 lc2\n      (FIND: IdMap.find tid m1.(tpool) = Some (st1, lc1))\n      (STEP: eustep tid (ExecUnit.mk st1 lc1 m1.(mem)) (ExecUnit.mk st2 lc2 m2.(mem)))\n      (TPOOL: m2.(tpool) = IdMap.add tid (st2, lc2) m1.(tpool))\n  .\n  Hint Constructors step.\n\n  Lemma rtc_eu_step_step\n        eustep tid m st1 lc1 mem1 st2 lc2 mem2\n        (FIND: IdMap.find tid m.(tpool) = Some (st1, lc1))\n        (MEM: m.(mem) = mem1)\n        (EX: rtc (eustep tid)\n                 (ExecUnit.mk st1 lc1 mem1)\n                 (ExecUnit.mk st2 lc2 mem2)):\n    rtc (step eustep)\n        m\n        (mk\n           (IdMap.add tid (st2, lc2) m.(tpool))\n           mem2).\n  Proof.\n    revert m FIND MEM.\n    depind EX.\n    { i. subst. destruct m. s. rewrite PositiveMapAdditionalFacts.gsident; ss. refl. }\n    destruct y. i. subst. econs.\n    - instantiate (1 := mk _ _). econs; ss; eauto.\n    - exploit IHEX; eauto.\n      + instantiate (1 := mk _ _). s.\n        rewrite IdMap.add_spec. condtac; eauto. exfalso. apply c. ss.\n      + ss.\n      + s. rewrite (IdMap.add_add tid (st2, lc2)). eauto.\n  Qed.\n\n  Inductive wf (m:t): Prop :=\n  | wf_intro\n      (WF: forall tid st lc\n             (FIND: IdMap.find tid m.(tpool) = Some (st, lc)),\n          ExecUnit.wf tid (ExecUnit.mk st lc m.(mem)))\n  .\n  Hint Constructors wf.\n\n  Lemma init_wf p:\n    wf (init p).\n  Proof.\n    econs. i. ss.\n    rewrite IdMap.map_spec in FIND. destruct (IdMap.find tid p); inv FIND.\n    econs; ss. apply Local.init_wf.\n  Qed.\n\n  Lemma init_no_promise p:\n    no_promise (init p).\n  Proof.\n    econs. s. i.\n    revert FIND. rewrite IdMap.map_spec. destruct (IdMap.find tid p); ss. i. inv FIND.\n    ss.\n  Qed.\n\n  Lemma step_state_step_wf\n        m1 m2\n        (STEP: step ExecUnit.state_step m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    destruct m1 as [tpool1 mem1].\n    destruct m2 as [tpool2 mem2].\n    inv STEP. inv STEP0. inv WF. econs. ss. subst.\n    i. revert FIND0. rewrite IdMap.add_spec. condtac.\n    - inversion e0. i. inv FIND0.\n      eapply ExecUnit.state_step_wf; eauto. econs; eauto.\n    - inv STEP. ss. i. subst. exploit WF0; eauto.\n  Qed.\n\n  Lemma rtc_step_state_step_wf\n        m1 m2\n        (STEP: rtc (step ExecUnit.state_step) m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply step_state_step_wf; eauto.\n  Qed.\n\n  Lemma step_promise_step_wf\n        m1 m2\n        (STEP: step ExecUnit.promise_step m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    destruct m1 as [tpool1 mem1].\n    destruct m2 as [tpool2 mem2].\n    inv STEP. inv STEP0. inv LOCAL. inv MEM2. inv WF. econs. ss. subst.\n    i. revert FIND0. rewrite IdMap.add_spec. condtac.\n    - inversion e. i. inv FIND0.\n      eapply ExecUnit.promise_step_wf; eauto. econs; eauto. econs; eauto.\n      + econs; eauto.\n      + refl.\n    - i. exploit WF0; eauto. i. inv x. ss. econs; ss.\n      inv LOCAL. econs; eauto.\n      all: try rewrite List.app_length; s; try lia.\n      + i. rewrite COH. lia.\n      + i. rewrite VPA. lia.\n      + i. rewrite VPC. lia.\n      + i. destruct (FWDBANK loc0). des. econs; esplits; ss.\n        apply Memory.read_mon; eauto.\n      + i. exploit PROMISES; eauto. lia.\n      + i. apply Memory.get_msg_snoc_inv in MSG. des.\n        { eapply PROMISES0; eauto. }\n        { subst. ss. congr. }\n      + i. apply Memory.get_msg_snoc_inv in MSG. des.\n        * eapply NFWD; eauto.\n        * rewrite MSG in TS. specialize (COH (Msg.loc msg)). lia.\n      + i. apply NINTERVENING. eapply Memory.latest_app_inv. eauto.\n  Qed.\n\n  Lemma rtc_step_promise_step_wf\n        m1 m2\n        (STEP: rtc (step ExecUnit.promise_step) m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply step_promise_step_wf; eauto.\n  Qed.\n\n  Lemma step_step_wf\n        m1 m2\n        (STEP: step ExecUnit.step m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    inv STEP. inv STEP0.\n    - eapply step_state_step_wf; eauto.\n    - eapply step_promise_step_wf; eauto.\n  Qed.\n\n  Lemma rtc_step_step_wf\n        m1 m2\n        (STEP: rtc (step ExecUnit.step) m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply step_step_wf; eauto.\n  Qed.\n\n  Lemma step_view_step_wf\n        m1 m2\n        (STEP: step ExecUnit.view_step m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    destruct m1 as [tpool1 mem1].\n    destruct m2 as [tpool2 mem2].\n    inv STEP. inv STEP0. inv WF. econs. ss. subst.\n    i. revert FIND0. rewrite IdMap.add_spec. condtac.\n    - inversion e0. i. inv FIND0.\n      eapply ExecUnit.view_step_wf; eauto. econs; eauto.\n    - i. inv STEP. exploit WF0; eauto. i. inv x. ss. econs; ss.\n      inv LOCAL0. inv LOCAL; ss.\n      + inv STEP. inv MEM. econs; ss.\n        * i. rewrite COH. rewrite app_length. lia.\n        * rewrite app_length. lia.\n        * rewrite app_length. lia.\n        * i. rewrite VPA. rewrite app_length. lia.\n        * i. rewrite VPC. rewrite app_length. lia.\n        * i. apply Local.wf_fwdbank_mon. ss.\n        * i. exploit PROMISES; eauto. rewrite List.app_length. lia.\n        * i. apply Memory.get_msg_snoc_inv in MSG. des.\n          { eapply PROMISES0; eauto. }\n          { subst. ss. congr. }\n        * i. apply Memory.get_msg_snoc_inv in MSG. des.\n          { eapply NFWD; eauto. }\n          { rewrite MSG in TS. specialize (COH (Msg.loc msg)). lia. }\n        * i. apply NINTERVENING. eapply Memory.latest_app_inv. eauto.\n      + inv STEP. inv MEM. econs; ss.\n        * i. rewrite COH. rewrite app_length. lia.\n        * rewrite app_length. lia.\n        * rewrite app_length. lia.\n        * i. rewrite VPA. rewrite app_length. lia.\n        * i. rewrite VPC. rewrite app_length. lia.\n        * i. apply Local.wf_fwdbank_mon. ss.\n        * i. exploit PROMISES; eauto. rewrite List.app_length. lia.\n        * i. apply Memory.get_msg_snoc_inv in MSG. des.\n          { eapply PROMISES0; eauto. }\n          { subst. ss. congr. }\n        * i. apply Memory.get_msg_snoc_inv in MSG. des.\n          { eapply NFWD; eauto. }\n          { rewrite MSG in TS. specialize (COH (Msg.loc msg)). lia. }\n        * i. apply NINTERVENING. eapply Memory.latest_app_inv. eauto.\n  Qed.\n\n  Lemma rtc_step_view_step_wf\n        m1 m2\n        (STEP: rtc (step ExecUnit.view_step) m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    revert WF. induction STEP; ss. i. apply IHSTEP.\n    eapply step_view_step_wf; eauto.\n  Qed.\n\n  Lemma step_view_step_no_promise\n        m1 m2\n        (STEP: step ExecUnit.view_step m1 m2)\n        (NOPROMISE: no_promise m1):\n    no_promise m2.\n  Proof.\n    inv NOPROMISE. inv STEP.\n    generalize FIND. intro NPROM. apply PROMISES in NPROM.\n    econs. i.\n    revert FIND0. rewrite TPOOL. rewrite IdMap.add_spec. condtac; [| apply PROMISES]. i. inv FIND0.\n    inv STEP0. inv STEP. inv LOCAL; try inv STEP; ss; subst; ss.\n  Qed.\n\n  Lemma rtc_step_view_step_no_promise\n        m1 m2\n        (STEP: rtc (step ExecUnit.view_step) m1 m2)\n        (NOPROMISE: no_promise m1):\n    no_promise m2.\n  Proof.\n    induction STEP; ss.\n    exploit step_view_step_no_promise; eauto.\n  Qed.\n\n  Lemma step_mon\n        (eustep1 eustep2: _ -> _ -> _ -> Prop)\n        (EUSTEP: forall tid m1 m2, eustep1 tid m1 m2 -> eustep2 tid m1 m2):\n    forall m1 m2, step eustep1 m1 m2 -> step eustep2 m1 m2.\n  Proof.\n    i. inv H. econs; eauto.\n  Qed.\n\n  Lemma rtc_step_mon\n        (eustep1 eustep2: _ -> _ -> _ -> Prop)\n        (EUSTEP: forall tid m1 m2, eustep1 tid m1 m2 -> eustep2 tid m1 m2):\n    forall m1 m2, rtc (step eustep1) m1 m2 -> rtc (step eustep2) m1 m2.\n  Proof.\n    i. induction H; eauto. econs; eauto. eapply step_mon; eauto.\n  Qed.\n\n  Inductive exec (p:program) (m:t): Prop :=\n  | exec_intro\n      (STEP: rtc (step ExecUnit.step) (init p) m)\n      (NOPROMISE: no_promise m)\n  .\n  Hint Constructors exec.\n\n  Inductive state_exec (m1 m2:t): Prop :=\n  | state_exec_intro\n      (TPOOL: IdMap.Forall2\n                (fun tid sl1 sl2 =>\n                   rtc (ExecUnit.state_step tid)\n                       (ExecUnit.mk (fst sl1) (snd sl1) m1.(mem))\n                       (ExecUnit.mk (fst sl2) (snd sl2) m1.(mem)))\n                m1.(tpool) m2.(tpool))\n      (MEM: m1.(mem) = m2.(mem))\n  .\n\n  Inductive pf_exec (p:program) (m:t): Prop :=\n  | pf_exec_intro\n      m1\n      (STEP1: rtc (step ExecUnit.promise_step) (init p) m1)\n      (STEP2: state_exec m1 m)\n      (NOPROMISE: no_promise m)\n  .\n  Hint Constructors pf_exec.\n\n  Inductive view_exec (p:program) (m:t): Prop :=\n  | view_exec_intro\n      (STEP: rtc (step ExecUnit.view_step) (init p) m)\n  .\n  Hint Constructors view_exec.\n\n  Inductive persisted_loc (m:t) (loc:Loc.t) (val:Val.t): Prop :=\n  | persisted_loc_intro\n      ts\n      (TS: Memory.read loc ts m.(mem) = Some val)\n      (LATEST: IdMap.Forall (fun _ sl =>\n                 Memory.latest loc ts ((snd sl).(Local.vpc) loc).(View.ts) m.(mem))\n                 m.(tpool))\n  .\n  Hint Constructors persisted_loc.\n\n  Definition persisted m smem := forall loc, persisted_loc m loc (smem loc).\n\n  Inductive equiv (m1 m2:t): Prop :=\n  | equiv_intro\n      (TPOOL: IdMap.Equal m1.(tpool) m2.(tpool))\n      (MEM: m1.(mem) = m2.(mem))\n  .\n\n  Lemma state_exec_wf\n        m1 m2\n        (STEP: state_exec m1 m2)\n        (WF: wf m1):\n    wf m2.\n  Proof.\n    econs. i.\n    inv STEP. inv WF.\n    specialize (TPOOL tid). inv TPOOL.\n    { rewrite FIND in H. ss. }\n    rewrite <- H in FIND. inv FIND.\n    destruct a as [st_a lc_a]. symmetry in H0. eapply WF0 in H0.\n    eapply ExecUnit.rtc_state_step_wf in H0; eauto.\n    rewrite <- MEM. ss.\n  Qed.\n\n  Lemma equiv_no_promise\n        m1 m2\n        (EQUIV: equiv m1 m2)\n        (NOPROMISE: no_promise m1):\n    no_promise m2.\n  Proof.\n    inv EQUIV. inv NOPROMISE. econs. i.\n    specialize (TPOOL tid). rewrite FIND in TPOOL.\n    eapply PROMISES. eauto.\n  Qed.\n\n  Lemma unlift_step_state_step\n        m1 m2 tid st1 lc1\n        (STEPS: rtc (step ExecUnit.state_step) m1 m2)\n        (TPOOL: IdMap.find tid m1.(tpool) = Some (st1, lc1)):\n    exists st2 lc2,\n      <<TPOOL: IdMap.find tid m2.(tpool) = Some (st2, lc2)>> /\\\n      <<STEPS: rtc (ExecUnit.state_step tid)\n                   (ExecUnit.mk st1 lc1 m1.(mem))\n                   (ExecUnit.mk st2 lc2 m2.(mem))>>.\n  Proof.\n    revert st1 lc1 TPOOL. induction STEPS; eauto. i.\n    destruct x as [tpool1 mem1].\n    destruct y as [tpool2 mem2].\n    destruct z as [tpool3 mem3].\n    inv H. ss.\n    assert (mem2 = mem1).\n    { inv STEP. inv STEP0. ss. }\n    subst. exploit IHSTEPS.\n    { rewrite IdMap.add_spec, TPOOL.\n      instantiate (1 := if equiv_dec tid tid0 then lc2 else lc1).\n      instantiate (1 := if equiv_dec tid tid0 then st2 else st1).\n      condtac; ss.\n    }\n    i. des.\n    esplits; eauto. rewrite <- STEPS0. condtac; eauto.\n    inversion e. subst. rewrite TPOOL in FIND. inv FIND. econs; eauto.\n  Qed.\n\n  Lemma step_get_msg_tpool\n        p m ts msg\n        (STEPS: rtc (step ExecUnit.step) (init p) m)\n        (MSG: Memory.get_msg ts m.(mem) = Some msg):\n    exists sl, IdMap.find msg.(Msg.tid) m.(tpool) = Some sl.\n  Proof.\n    apply clos_rt_rt1n_iff in STEPS.\n    apply clos_rt_rtn1_iff in STEPS.\n    revert ts msg MSG. induction STEPS; ss.\n    { destruct ts; ss. destruct ts; ss. }\n    destruct y as [tpool1 mem1].\n    destruct z as [tpool2 mem2].\n    ss. inv H. ss. i. inv STEP.\n    - rewrite IdMap.add_spec. condtac; eauto.\n      inv STEP0. inv STEP. ss. subst. eauto.\n    - rewrite IdMap.add_spec. condtac; eauto.\n      inv STEP0. ss. subst. inv LOCAL. inv MEM2.\n      apply Memory.get_msg_snoc_inv in MSG. des; eauto. subst.\n      ss. congr.\n  Qed.\n\n  Definition init_with_promises (p:program) (mem:Memory.t): Machine.t :=\n    Machine.mk\n      (IdMap.mapi (fun tid stmts =>\n                     (State.init stmts,\n                      Local.init_with_promises (Promises.promises_from_mem tid mem)))\n                  p)\n      mem.\n\n  Lemma pf_init_with_promises\n        p promises\n        (MEM: forall msg (MSG: List.In msg promises), IdMap.find msg.(Msg.tid) p <> None):\n    exists m,\n      <<STEP: rtc (Machine.step ExecUnit.promise_step) (Machine.init p) m>> /\\\n      <<TPOOL: IdMap.Equal m.(Machine.tpool) (init_with_promises p promises).(Machine.tpool)>> /\\\n      <<MEM: m.(Machine.mem) = promises>>.\n  Proof.\n    revert MEM. induction promises using List.rev_ind; i.\n    { esplits; eauto. ii. s. rewrite IdMap.map_spec, IdMap.mapi_spec.\n      destruct (IdMap.find y p); ss.\n      unfold Local.init, Local.init_with_promises. repeat f_equal.\n      rewrite Promises.promises_from_mem_nil. ss.\n    }\n    exploit IHpromises; eauto.\n    { i. apply MEM. apply List.in_app_iff. intuition. }\n    i. des. subst. destruct x.\n    hexploit MEM.\n    { apply List.in_app_iff. right. left. eauto. }\n    match goal with\n    | [|- context[(?f <> None) -> _]] => destruct f eqn:FIND\n    end; ss.\n    intro X. clear X.\n    eexists (Machine.mk _ _). esplits.\n    - etrans; [eauto|]. econs 2; [|refl].\n      econs.\n      + rewrite TPOOL, IdMap.mapi_spec, FIND. ss.\n      + econs; ss.\n      + ss.\n    - s. ii. rewrite IdMap.add_spec. condtac; ss.\n      + inversion e. subst. rewrite IdMap.mapi_spec, FIND. s.\n        unfold Local.init_with_promises. repeat f_equal.\n        rewrite Promises.promises_from_mem_snoc. condtac; ss.\n      + rewrite TPOOL, ? IdMap.mapi_spec. destruct (IdMap.find y p); ss.\n        unfold Local.init_with_promises. rewrite Promises.promises_from_mem_snoc. s.\n        condtac; ss. congr.\n    - ss.\n  Qed.\n\n  Lemma rtc_promise_step_spec\n        p m\n        (STEP: rtc (step ExecUnit.promise_step) (init p) m):\n    IdMap.Equal m.(tpool) (init_with_promises p m.(mem)).(tpool).\n  Proof.\n    apply clos_rt_rt1n_iff in STEP.\n    apply clos_rt_rtn1_iff in STEP.\n    induction STEP.\n    { s. ii. rewrite IdMap.map_spec, IdMap.mapi_spec.\n      destruct (IdMap.find y p); ss. f_equal. f_equal.\n      rewrite Promises.promises_from_mem_nil. ss.\n    }\n    destruct y as [tpool2 mem2].\n    destruct z as [tpool3 mem3].\n    ss. inv H. inv STEP0. inv LOCAL. ss. subst. inv MEM2.\n    ii. generalize (IHSTEP y). rewrite IdMap.add_spec, ? IdMap.mapi_spec.\n    rewrite Promises.promises_from_mem_snoc. s.\n    repeat condtac; try congr.\n    inversion e. subst. rewrite FIND. destruct (IdMap.find tid p); ss. i. inv H. ss.\n  Qed.\nEnd Machine.\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/TsoPromising.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.16596157850720156}}
{"text": "Require Rupicola.Lib.Tactics.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List. (* after strings *)\nRequire Import Coq.QArith.QArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import coqutil.Byte.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Word.Interface.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nRequire Import Crypto.Bedrock.Field.Common.Arrays.MaxBounds.\nRequire Import Crypto.Bedrock.Field.Common.Names.MakeNames.\nRequire Import Crypto.Bedrock.Field.Common.Names.VarnameGenerator.\nRequire Import Crypto.Bedrock.Field.Common.Tactics.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Bedrock.Field.Translation.Func.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.Func.\nRequire Import Crypto.Bedrock.Field.Interface.Representation.\nRequire Import Crypto.Bedrock.Specs.Field.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Spec.ModularArithmetic.\nImport Language.API.Compilers.\nImport ListNotations.\nImport Types.Notations.\nImport Syntax.Coercions.\nLocal Open Scope Z_scope.\n\nSection Generic.\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  Definition make_bedrock_func {t} (name : string)\n             insizes outsizes inlengths (res : API.Expr t)\n  : func :=\n    let innames := make_innames (inname_gen:=default_inname_gen) _ in\n    let outnames := make_outnames (outname_gen:=default_outname_gen) _ in\n    let body := fst (translate_func\n                       res innames inlengths insizes outnames outsizes) in\n    (name, body).\nEnd Generic.\n\nLocal Hint Unfold fst snd : pairs.\nLocal Hint Unfold type.final_codomain : types.\nLocal Hint Unfold Equivalence.equivalent_args\n      Equivalence.equivalent_base rep.equiv\n      rep.listZ_mem rep.Z type.map_for_each_lhs_of_arrow\n      rtype_of_ltype base_rtype_of_ltype rep.rtype_of_ltype\n      WeakestPrecondition.dexpr WeakestPrecondition.expr\n      WeakestPrecondition.expr_body\n  : equivalence.\nLocal Hint Unfold LoadStoreList.list_lengths_from_args\n      LoadStoreList.list_lengths_from_value\n  : list_lengths.\nLocal Hint Unfold LoadStoreList.access_sizes_good_args\n      LoadStoreList.access_sizes_good\n      LoadStoreList.base_access_sizes_good\n      LoadStoreList.within_access_sizes_args\n      LoadStoreList.within_base_access_sizes\n  : access_sizes.\nLocal Hint Unfold LoadStoreList.lists_reserved_with_initial_context\n      LoadStoreList.lists_reserved\n      LoadStoreList.extract_listnames\n      Flatten.flatten_listonly_base_ltype\n      Flatten.flatten_argnames\n      Flatten.flatten_base_ltype\n      List.app map.of_list_zip\n      map.putmany_of_list_zip\n  : lists_reserved.\n\nLocal Hint Resolve MakeAccessSizes.bits_per_word_le_width\n      MakeAccessSizes.width_ge_8 width_0mod_8\n      Util.Forall_map_byte_unsigned\n  : translate_func_preconditions.\n\nSection WithParameters.\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 : Types.ok}\n          {field_parameters : FieldParameters}.\n  Context (n n_bytes : nat) (weight : nat -> Z)\n          (bounds : Type)\n          (loose_bounds tight_bounds byte_bounds : bounds)\n          (list_in_bounds : bounds -> list Z -> Prop)\n          (relax_bounds :\n             forall X,\n               list_in_bounds tight_bounds X ->\n               list_in_bounds loose_bounds X)\n          (eval_transformation : list Z -> list Z).\n  Context (inname_gen_varname_gen_disjoint :\n             disjoint default_inname_gen varname_gen)\n          (outname_gen_varname_gen_disjoint :\n             disjoint default_outname_gen varname_gen).\n  Local Instance field_representation : FieldRepresentation\n    := @frep _ BW _ _ field_parameters n n_bytes weight bounds list_in_bounds loose_bounds tight_bounds\n             byte_bounds eval_transformation.\n  Local Instance field_representation_ok : FieldRepresentation_ok\n    := frep_ok n n_bytes weight bounds list_in_bounds loose_bounds tight_bounds byte_bounds\n               relax_bounds _.\n\n  Lemma FElem_array_truncated_scalar_iff1 px x :\n    Lift1Prop.iff1\n      (FElem px x)\n      (sep (map:=mem)\n           (emp (map:=mem) (length x = n))\n           (Array.array\n              (Scalars.truncated_scalar access_size.word)\n              (word.of_Z\n                 (Z.of_nat (BinIntDef.Z.to_nat (bytes_per_word width))))\n              px (map word.unsigned x))).\n  Proof using ok.\n    cbv [FElem Bignum.Bignum field_representation frep].\n    rewrite Util.array_truncated_scalar_scalar_iff1.\n    Morphisms.f_equiv. Morphisms.f_equiv. Morphisms.f_equiv.\n    destruct Bitwidth.width_cases as [W|W]; rewrite W; trivial.\n  Qed.\n\n  Lemma FElemBytes_array_truncated_scalar_iff1 pbs bs :\n    Lift1Prop.iff1\n      (FElemBytes pbs bs)\n      (sep (map:=mem)\n           (emp (map:=mem)\n                (length bs = encoded_felem_size_in_bytes\n                 /\\ bytes_in_bounds bs))\n           (Array.array\n              (Scalars.truncated_scalar access_size.one)\n              (word.of_Z 1) pbs (map byte.unsigned bs))).\n  Proof using ok.\n    cbv [FElemBytes].\n    rewrite Util.array_truncated_scalar_ptsto_iff1.\n    rewrite ByteBounds.byte_map_of_Z_unsigned.\n    reflexivity.\n  Qed.\n\n  Ltac felem_to_array :=\n    repeat\n      lazymatch goal with\n      | H:context[sep (FElem _ _) _]\n        |- _ => seprewrite_in FElem_array_truncated_scalar_iff1 H\n      | H : context [sep (FElemBytes _ _) _] |- _ =>\n        seprewrite_in FElemBytes_array_truncated_scalar_iff1 H\n      end.\n\n  Ltac equivalence_side_conditions_hook := fail.\n  Ltac solve_equivalence_side_conditions :=\n    lazymatch goal with\n    | |- map word.unsigned _ = map word.unsigned _ => reflexivity\n    | |- word.unsigned _ = word.unsigned _ => reflexivity\n    | |- WeakestPrecondition.get _ _ _ =>\n      repeat (apply Util.get_put_diff; [ congruence | ]);\n      apply Util.get_put_same; reflexivity\n    | |- Forall (fun z => 0 <= z < 2 ^ (?e * 8))\n                (map word.unsigned _) =>\n          unshelve eapply Util.Forall_word_unsigned_within_access_size;\n          destruct Bitwidth.width_cases as [W|W]; rewrite W; trivial\n    | |- Forall (fun z => 0 <= z < ?e)\n                (map byte.unsigned _) =>\n      change e with 256;\n      apply Util.Forall_map_byte_unsigned\n    | |- sep _ _ _ =>\n      change (Z.of_nat (bytes_per access_size.one)) with 1;\n      try erewrite Util.map_unsigned_of_Z,MaxBounds.map_word_wrap_bounded\n        by eauto using byte_unsigned_within_max_bounds;\n      felem_to_array; sepsimpl; (assumption || ecancel_assumption)\n    | |- map word.unsigned ?x = map byte.unsigned _ =>\n      is_evar x;\n      erewrite Util.map_unsigned_of_Z,MaxBounds.map_word_wrap_bounded\n        by eauto using byte_unsigned_within_max_bounds;\n      reflexivity\n    | _ => equivalence_side_conditions_hook\n    end.\n\n  Ltac crush_sep :=\n    repeat lazymatch goal with\n           | |- exists _, _ => eexists\n           | |- Lift1Prop.ex1 _ _ => Tactics.lift_eexists\n           | |- True => tauto\n           | _ => progress sepsimpl; cleanup\n           end.\n\n  Ltac compute_names :=\n    repeat lazymatch goal with\n           | |- context [@make_innames ?w ?B ?W ?M ?L ?E ?X ?G ?R ?p ?gen ?t] =>\n             let x := constr:(@make_innames w B W M L E X G R p gen t) in\n             let y := (eval compute in x) in\n             change x with y\n           | |- context [@make_outnames  ?w ?B ?W ?M ?L ?E ?X ?G ?R ?p ?gen ?t] =>\n             let x := constr:(@make_outnames w B W M L E X G R p gen t) in\n             let y := (eval compute in x) in\n             change x with y\n           end.\n\n  Ltac use_translate_func_correct b2_args R_ :=\n    let arg_ptrs :=\n        lazymatch goal with\n          |- WeakestPrecondition.call _ _ _ _ ?args _ =>\n          args end in\n    let out_ptr := (eval compute in (hd (word.of_Z 0) arg_ptrs)) in\n    let in_ptrs := (eval compute in (tl arg_ptrs)) in\n    eapply (translate_func_correct (parameters_sentinel:=parameters_sentinel))\n    with (out_ptrs:=[out_ptr]) (flat_args:=in_ptrs)\n         (args:=b2_args) (R:=R_).\n\n  Ltac types_autounfold :=\n    repeat first [ progress autounfold with types pairs\n                 | progress autounfold with equivalence ].\n  Ltac lists_autounfold :=\n    repeat first [ progress types_autounfold\n                 | progress autounfold with list_lengths\n                 | progress autounfold with lists_reserved ].\n\n  Ltac translate_func_precondition_hammer :=\n    lazymatch goal with\n    | |- valid_func _ => assumption\n    | |- API.Wf _ => assumption\n    | |- @eq (list word.rep) _ _ => reflexivity\n    | |- length [?p] = _ => reflexivity\n    | |- forall _, ~ VarnameSet.varname_set_args _ _ =>\n      solve [auto using make_innames_varname_gen_disjoint]\n    | |- forall _, ~ VarnameSet.varname_set_base (make_outnames _)\n                     (varname_gen _) =>\n      apply make_outnames_varname_gen_disjoint;\n      solve [apply outname_gen_varname_gen_disjoint]\n    | |- NoDup (Flatten.flatten_argnames (make_innames _)) =>\n      apply flatten_make_innames_NoDup;\n      solve [eapply prefix_name_gen_unique]\n    | |- NoDup (Flatten.flatten_base_ltype (make_outnames _)) =>\n      apply flatten_make_outnames_NoDup;\n      solve [eapply prefix_name_gen_unique]\n    | |- LoadStoreList.base_access_sizes_good _ =>\n       autounfold with types access_sizes; cbn;\n       destruct Bitwidth.width_cases as [W|W]; rewrite ?W;\n           clear; cbn; intuition Lia.lia\n    | |- PropSet.disjoint\n           (VarnameSet.varname_set_args (make_innames _))\n           (VarnameSet.varname_set_base (make_outnames _)) =>\n      apply make_innames_make_outnames_disjoint;\n      eauto using outname_gen_inname_gen_disjoint;\n      solve [apply prefix_name_gen_unique]\n    | |- Equivalence.equivalent_flat_args _ _ _ _ =>\n      eapply (equivalent_flat_args_iff1\n                (make_innames (inname_gen:=default_inname_gen) _)\n                _ _ _\n                map.empty);\n      [ apply flatten_make_innames_NoDup;\n        solve [eapply prefix_name_gen_unique]\n      | reflexivity | ];\n      compute_names; autounfold with equivalence pairs;\n      cbv [Equivalence.equivalent_base];\n      autounfold with equivalence pairs;\n      rewrite <-?MakeAccessSizes.bytes_per_word_eq;\n      sepsimpl; crush_sep; solve [solve_equivalence_side_conditions]\n    | |- LoadStoreList.within_access_sizes_args _ _ =>\n      autounfold with types access_sizes; cbn; ssplit; trivial;\n      solve_equivalence_side_conditions \n    | |- LoadStoreList.within_base_access_sizes _ _ =>\n      autounfold with types access_sizes;\n      first [ eapply MaxBounds.max_bounds_range_iff\n            | eapply ByteBounds.byte_bounds_range_iff ];\n      cbn [type.app_curried fst snd];\n      solve [eauto using relax_list_Z_bounded_by]\n    | |- LoadStoreList.access_sizes_good_args _ =>\n      autounfold with access_sizes pairs access_sizes; cbn;\n       destruct Bitwidth.width_cases as [W|W]; rewrite ?W;\n           clear; cbn; intuition Lia.lia\n    | |- _ = LoadStoreList.list_lengths_from_args _ =>\n      autounfold with list_lengths pairs list_lengths;\n      felem_to_array; sepsimpl; rewrite !map_length;\n      repeat match goal with\n             | H : length _ = _ |- _ => rewrite H end;\n      reflexivity\n    | _ => idtac\n    end.\n\n  Ltac lists_reserved_simplify pout :=\n    compute_names; cbn [type.app_curried fst snd];\n    autounfold with types list_lengths pairs;\n    lists_autounfold; sepsimpl;\n    match goal with\n    | H : context [FElem pout ?old_out]\n      |- @Lift1Prop.ex1 (list Z) _ _ _ =>\n      exists (map word.unsigned old_out)\n    | H : context [FElemBytes pout ?old_out]\n      |- @Lift1Prop.ex1 (list Z) _ _ _ =>\n      exists (map byte.unsigned old_out)\n    end;\n    crush_sep.\n\n  Ltac postcondition_simplify :=\n    lists_autounfold;\n    cbn [type.app_curried fst snd];\n    cbv [Equivalence.equivalent_listexcl_flat_base\n           Equivalence.equivalent_listonly_flat_base\n           Equivalence.equivalent_flat_base\n        ]; lists_autounfold; cbn [hd];\n    repeat intro;\n    cbv [Core.postcondition_func_norets\n           Core.postcondition_func];\n    sepsimpl; [ assumption .. | ];\n    repeat match goal with\n           | _ => progress subst\n           | H : WeakestPrecondition.literal (word.unsigned _) _ |- _ =>\n             cbv [WeakestPrecondition.literal dlet.dlet] in H;\n             rewrite word.of_Z_unsigned in H\n           | H : word.unsigned _ = word.unsigned _ |- _ =>\n             apply Properties.word.unsigned_inj in H\n           | |- exists _, _ => eexists\n           | |- _ /\\ _ => eexists\n           end.\n\n    Ltac solve_length x Hlength := rewrite map_length;\n    match goal with\n        | H : (FElem _ x * _)%sep _ |- _ => cbv [FElem Bignum.Bignum] in H; sepsimpl_hyps\n        | _ => idtac\n    end;\n    match goal with\n        | H : Datatypes.length x = _ |- _ => rewrite H\n        | _ => idtac\n    end; rewrite Hlength; auto.\n\n  Section ListBinop.\n    Context {res : API.Expr (type_listZ -> type_listZ -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context name (bop : BinOp name)\n            (res_eq : forall x y : list word,\n                bounded_by bin_xbounds x ->\n                bounded_by bin_ybounds y ->\n                feval (map word.of_Z\n                           (API.interp (res _)\n                                       (map word.unsigned x)\n                                       (map word.unsigned y)))\n                = bin_model (feval x) (feval y))\n            (res_bounds : forall x y,\n                list_in_bounds bin_xbounds x ->\n                list_in_bounds bin_ybounds y ->\n                list_in_bounds bin_outbounds (API.interp (res _) x y))\n\n            (outbounds_tighter_than_max : forall x, list_in_bounds bin_outbounds x -> list_Z_bounded_by ((@max_bounds width) n) x)\n            (xbounds_length : forall x, list_in_bounds bin_xbounds x -> length x = n)\n            (ybounds_length : forall x, list_in_bounds bin_ybounds x -> length x = n)\n            (outbounds_length : forall x, list_in_bounds bin_outbounds x -> length x = n).\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (API.interp (res _) ?x ?y)] =>\n        specialize (res_bounds x y ltac:(auto) ltac:(auto));\n        rewrite (length_list_Z_bounded_by _ _ res_bounds);\n        try congruence;\n        rewrite !map_length, outbounds_length;\n        felem_to_array; sepsimpl; congruence\n      | _ => idtac\n      end.\n\n    Local Notation t :=\n      (type.arrow type_listZ (type.arrow type_listZ type_listZ))\n        (only parsing).\n\n    Definition list_binop_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (access_size.word, (access_size.word, tt)).\n    Definition list_binop_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition list_binop_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (n, (n, tt)).\n    Let insizes := list_binop_insizes.\n    Let outsizes := list_binop_outsizes.\n    Let inlengths := list_binop_inlengths.\n\n    Lemma list_binop_correct f :\n      f = make_bedrock_func name insizes outsizes inlengths res ->\n      forall functions, (binop_spec _ (f :: functions)).\n    Proof.\n      subst inlengths insizes outsizes.\n      cbv [binop_spec list_binop_insizes list_binop_outsizes list_binop_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup. eapply Proper_call.\n      2: {\n        use_translate_func_correct\n          constr:((map word.unsigned x, (map word.unsigned y, tt))) Rr;\n        translate_func_precondition_hammer.\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout; try solve_equivalence_side_conditions; solve_length out outbounds_length.\n          } }\n      { postcondition_simplify; [ | | ]; cycle -1.\n        { refine (proj1 (Proper_sep_iff1 _ _ _ _ _ _ _) _);\n            [symmetry; eapply FElem_array_truncated_scalar_iff1 | reflexivity | sepsimpl ].\n          2:eassumption.\n          erewrite <-map_length.\n          match goal with H : map word.unsigned _ = API.interp (res _) _ _ |- _ =>\n            rewrite H end.\n          erewrite length_list_Z_bounded_by; eauto using res_bounds; apply repeat_length. }\n        { (* output correctness *)\n          erewrite <-res_eq; auto.\n          match goal with H : map word.unsigned _ = API.interp (res _) _ _ |- _ =>\n            rewrite <-H end.\n          rewrite map_map.\n          f_equal; eapply List.nth_error_ext; intros i; rewrite ListUtil.nth_error_map.\n          case (nth_error _ i); cbn; trivial; []; intros; eapply f_equal.\n          symmetry; eapply word.of_Z_unsigned. }\n        { (* output bounds *)\n          cbn [bounded_by field_representation frep] in *.\n          match goal with H : map word.unsigned _ = API.interp (res _) _ _ |- _ =>\n            rewrite H end.\n          eauto using res_bounds. } }\n    Qed.\n  End ListBinop.\n\n  Section ListUnop.\n    Context {res : API.Expr (type_listZ -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context name (uop : UnOp name)\n            (res_eq : forall x : list word,\n                bounded_by un_xbounds x ->\n                feval (map word.of_Z\n                           (API.interp (res _) (map word.unsigned x)))\n                = un_model (feval x))\n            (res_bounds : forall x,\n                list_in_bounds un_xbounds x ->\n                list_in_bounds un_outbounds (API.interp (res _) x))\n            (outbounds_tighter_than_max : forall x, list_in_bounds un_outbounds x -> list_Z_bounded_by (@max_bounds width n) x)\n            (xbounds_length : forall x, list_in_bounds un_xbounds x -> length x = n)\n            (outbounds_length : forall x, list_in_bounds un_outbounds x -> length x = n).\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (API.interp (res _) ?x)] =>\n        specialize (res_bounds x ltac:(auto));\n        rewrite (length_list_Z_bounded_by _ _ res_bounds);\n        try congruence;\n        rewrite !map_length, outbounds_length;\n        felem_to_array; sepsimpl; congruence\n      | _ => idtac\n      end.\n\n    Local Notation t :=\n      (type.arrow type_listZ type_listZ) (only parsing).\n\n    Definition list_unop_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (access_size.word, tt).\n    Definition list_unop_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition list_unop_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (n, tt).\n    Let insizes := list_unop_insizes.\n    Let outsizes := list_unop_outsizes.\n    Let inlengths := list_unop_inlengths.\n\n    Lemma list_unop_correct f :\n      f = make_bedrock_func name insizes outsizes inlengths res ->\n      forall functions, unop_spec _ (f :: functions).\n    Proof using inname_gen_varname_gen_disjoint outbounds_length\n          outbounds_tighter_than_max outname_gen_varname_gen_disjoint\n          ok relax_bounds res_Wf res_bounds res_eq res_valid.\n      subst inlengths insizes outsizes.\n      cbv [unop_spec list_unop_insizes list_unop_outsizes list_unop_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup. eapply Proper_call.\n      2: {\n        use_translate_func_correct constr:((map word.unsigned x, tt)) Rr.\n        all:translate_func_precondition_hammer.\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout.\n          all: try solve_equivalence_side_conditions.\n          solve_length out outbounds_length. } }\n      { postcondition_simplify; [ | | ].\n        { (* output correctness *)\n          eapply res_eq; auto. }\n        { (* output bounds *)\n          cbn [bounded_by field_representation frep] in *.\n          erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n            by eauto using relax_list_Z_bounded_by.\n          eauto. }\n        { (* separation-logic postcondition *)\n          eapply Proper_sep_iff1;\n            [ solve [apply FElem_array_truncated_scalar_iff1]\n            | reflexivity | ].\n          sepsimpl; [ | ].\n          { rewrite !map_length. apply outbounds_length; auto. }\n          { erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n              by eauto using relax_list_Z_bounded_by.\n            rewrite MakeAccessSizes.bytes_per_word_eq.\n            clear outbounds_length; subst.\n            match goal with\n              H : map word.unsigned _ = API.interp (res _) _ |- _ =>\n              rewrite <-H end.\n            auto. } } }\n    Qed.\n  End ListUnop.\n\n  Section FromWord.\n    Context {res : API.Expr (type_Z -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context (res_eq : forall w,\n                feval (map word.of_Z\n                           (API.interp (res _) w))\n                = F.of_Z _ w)\n            (res_bounds : forall w,\n                list_in_bounds\n                  tight_bounds\n                  (API.interp (res _) w)).\n    Context (tight_bounds_tighter_than_max : forall x,\n                list_in_bounds tight_bounds x -> list_Z_bounded_by (@MaxBounds.max_bounds width n) x).\n\n    Local Notation t :=\n      (type.arrow type_Z type_listZ) (only parsing).\n\n    Definition from_word_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (tt, tt).\n    Definition from_word_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition from_word_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (tt, tt).\n    Let insizes := from_word_insizes.\n    Let outsizes := from_word_outsizes.\n    Let inlengths := from_word_inlengths.\n\n    Lemma from_word_correct f :\n      f = make_bedrock_func from_word insizes outsizes inlengths res ->\n      forall functions,\n        spec_of_from_word (f :: functions).\n    Proof using inname_gen_varname_gen_disjoint\n          outname_gen_varname_gen_disjoint ok relax_bounds res_Wf\n          res_bounds res_eq res_valid tight_bounds_tighter_than_max.\n      subst inlengths insizes outsizes. cbv [spec_of_from_word].\n      cbv [from_word_insizes from_word_outsizes from_word_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup.\n      eapply Proper_call.\n      2:{\n        (* inlined [use_translate_func_correct constr:((word.unsigned x, tt)) R] and edited R0 *)\n        let b2_args := constr:((word.unsigned x, tt)) in\n        let R_ := R in\n        let arg_ptrs :=\n          lazymatch goal with\n          |- WeakestPrecondition.call _ _ _ _ ?args _ =>\n          args end in\n          let out_ptr := (eval compute in (hd (word.of_Z 0) arg_ptrs)) in\n          let in_ptrs := (eval compute in (tl arg_ptrs)) in\n          eapply (translate_func_correct (parameters_sentinel:=parameters_sentinel))\n          with (out_ptrs:=[out_ptr]) (flat_args:=in_ptrs)\n          (args:=b2_args).\n        16:instantiate (1:=R).\n        all:try translate_func_precondition_hammer.\n        1:reflexivity.\n        { cbv [Equivalence.equivalent_flat_args]; eexists 1%nat; split; [eexists|reflexivity].\n          cbv [Equivalence.equivalent_flat_base rep.equiv rep.Z]; sepsimpl; [reflexivity|eexists].\n          sepsimpl; trivial.\n          { cbn. cbv [WeakestPrecondition.literal dlet.dlet]. rewrite word.of_Z_unsigned; trivial. }\n          { eassumption. } }\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout.\n          all:try solve_equivalence_side_conditions.\n          symmetry.\n          erewrite length_list_Z_bounded_by; [| eapply tight_bounds_tighter_than_max, res_bounds].\n          cbv [max_bounds]. rewrite repeat_length. rewrite map_length.\n          cbv [FElem Bignum.Bignum] in *. sepsimpl. auto.\n        } }\n      { postcondition_simplify; [ | | ].\n        { (* output correctness *)\n          eapply res_eq; auto. }\n        { (* output bounds *)\n          cbn [bounded_by field_representation frep] in *.\n          erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n            by eauto using relax_list_Z_bounded_by. cbv [Field.tight_bounds]. simpl.\n          eauto. }\n        { (* separation-logic postcondition *)\n          eapply Proper_sep_iff1;\n            [ solve [apply FElem_array_truncated_scalar_iff1]\n            | reflexivity | ].\n          sepsimpl; [ | ].\n          { rewrite !map_length.\n            erewrite length_list_Z_bounded_by; [| eapply tight_bounds_tighter_than_max, res_bounds].\n            cbv [max_bounds]; rewrite repeat_length; trivial. }\n          { erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n              by eauto using relax_list_Z_bounded_by.\n            rewrite MakeAccessSizes.bytes_per_word_eq.\n            (* clear tight_bounds_length; subst. *)\n            match goal with\n              H : map word.unsigned _ = API.interp (res _) _ |- _ =>\n              rewrite <-H end.\n            auto. } } }\n    Qed.\n  End FromWord.\n\n  Section FelemCopy.\n    Context {res : API.Expr (type_listZ -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context (res_eq : forall x : list word,\n                length x = n ->\n                (map word.of_Z (API.interp (res _) (map word.unsigned x)))\n                = x)\n            (res_bounds : forall x,\n                list_Z_bounded_by (max_bounds (width:=width) n) x ->\n                list_Z_bounded_by (max_bounds (width:=width) n) (API.interp (res _) x)).\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (API.interp (res _) ?x)] =>\n      idtac (*; specialize (res_bounds x ltac:(auto));\n        rewrite (length_list_Z_bounded_by _ _ res_bounds);\n        try congruence;\n        rewrite !map_length, outbounds_length;\n                felem_to_array; sepsimpl; congruence*)\n      | _ => idtac\n      end.\n\n    Local Notation t :=\n      (type.arrow type_listZ type_listZ) (only parsing).\n\n    Definition felem_copy_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (access_size.word, tt).\n    Definition felem_copy_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition felem_copy_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (n, tt).\n    Let insizes := felem_copy_insizes.\n    Let outsizes := felem_copy_outsizes.\n    Let inlengths := felem_copy_inlengths.\n\n    Lemma felem_copy_correct f :\n      f = make_bedrock_func felem_copy insizes outsizes inlengths res ->\n      forall functions, spec_of_felem_copy (f :: functions).\n    Proof.\n      subst inlengths insizes outsizes.\n      cbv [spec_of_felem_copy felem_copy_insizes felem_copy_outsizes felem_copy_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup. eapply Proper_call.\n      2: {\n        Set Ltac Backtrace.\n        rename R into Rr.\n        use_translate_func_correct constr:((map word.unsigned x, tt)) (FElem px x * Rr)%sep.\n        all:try translate_func_precondition_hammer.\n\n\n      autounfold with types access_sizes;\n      first [ eapply MaxBounds.max_bounds_range_iff\n            | eapply ByteBounds.byte_bounds_range_iff ];\n      cbn [type.app_curried fst snd].\napply res_bounds.\nrewrite max_bounds_range_iff.\n(* note: need to constrain length of x, extract that from H0 *)\nadmit.\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout.\n          all:try solve_equivalence_side_conditions.\n          setoid_rewrite max_bounds_range_iff in res_bounds.\n          rewrite (fun x pf => proj1 (res_bounds x pf)).\n          admit. admit.\n      use_sep_assumption.\n      cancel; unfold seps.\n      admit.\n        Admitted.\n  End FelemCopy.\n\n  Section FromBytes.\n    Context {res : API.Expr (type_listZ -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context (tight_bounds_tighter_than_max :\n              forall x,\n                list_in_bounds tight_bounds x ->\n                list_Z_bounded_by (@max_bounds width n) x)\n            (tight_bounds_length : forall x, list_in_bounds tight_bounds x -> length x = n)\n            (res_eq : forall bs,\n                bytes_in_bounds bs ->\n                feval (map word.of_Z\n                           (API.interp (res _) (map byte.unsigned bs)))\n                = feval_bytes bs)\n            (res_bounds : forall bs,\n                bytes_in_bounds bs ->\n                list_in_bounds\n                  tight_bounds\n                  (API.interp (res _) (map byte.unsigned bs))).\n\n    Lemma FElemBytes_in_bounds p bs R m :\n      (FElemBytes p bs \u22c6 R)%sep m ->\n      bytes_in_bounds bs.\n    Proof. cbv [FElemBytes]. intros; sepsimpl. assumption. Qed.\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (API.interp (res _)\n                                       (map byte.unsigned ?x))] =>\n        specialize (res_bounds x ltac:(auto));\n        rewrite (length_list_Z_bounded_by _ _ res_bounds);\n        try congruence;\n        rewrite !map_length, tight_bounds_length;\n        felem_to_array; sepsimpl; congruence\n      | _ => idtac\n      end.\n\n    Local Notation t :=\n      (type.arrow type_listZ type_listZ) (only parsing).\n\n    Definition from_bytes_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (access_size.one, tt).\n    Definition from_bytes_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition from_bytes_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (n_bytes, tt).\n    Let insizes := from_bytes_insizes.\n    Let outsizes := from_bytes_outsizes.\n    Let inlengths := from_bytes_inlengths.\n\n    Lemma from_bytes_correct f :\n      f = make_bedrock_func from_bytes insizes outsizes inlengths res ->\n      forall functions,\n        spec_of_from_bytes (f :: functions).\n    Proof using inname_gen_varname_gen_disjoint\n          outname_gen_varname_gen_disjoint ok relax_bounds res_Wf\n          res_bounds res_eq res_valid tight_bounds_length\n          tight_bounds_tighter_than_max.\n      subst inlengths insizes outsizes. cbv [spec_of_from_bytes].\n      cbv [from_bytes_insizes from_bytes_outsizes from_bytes_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup.\n      pose proof FElemBytes_in_bounds _ _ _ _ H.\n      eapply Proper_call.\n      2:{\n        use_translate_func_correct constr:((map Byte.byte.unsigned bs, tt)) Rr.\n        all: try translate_func_precondition_hammer.\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout.\n          all: try solve_equivalence_side_conditions.\n          solve_length out tight_bounds_length.\n        } }\n      { postcondition_simplify; [ | | ].\n        { (* output correctness *)\n          eapply res_eq; auto. }\n        { (* output bounds *)\n          cbn [bounded_by field_representation frep] in *.\n          erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n            by eauto using relax_list_Z_bounded_by.\n          eauto. }\n        { (* separation-logic postcondition *)\n          eapply Proper_sep_iff1;\n            [ solve [apply FElem_array_truncated_scalar_iff1]\n            | reflexivity | ].\n          sepsimpl; [ | ].\n          { rewrite !map_length; apply tight_bounds_length; auto. }\n          { erewrite Util.map_unsigned_of_Z, MaxBounds.map_word_wrap_bounded\n              by eauto using relax_list_Z_bounded_by.\n            rewrite MakeAccessSizes.bytes_per_word_eq.\n            clear tight_bounds_length; subst.\n            match goal with\n              H : map word.unsigned _ = API.interp (res _) _ |- _ =>\n              rewrite <-H end.\n            auto. } } }\n    Qed.\n  End FromBytes.\n\n  Section ToBytes.\n    Context {res : API.Expr (type_listZ -> type_listZ)}\n            (res_valid :\n               valid_func (res (fun _ : API.type => unit)))\n            (res_Wf : API.Wf res).\n    Context (byte_bounds_tighter_than_max :\n              forall x,\n                list_in_bounds byte_bounds x ->\n                list_Z_bounded_by (ByteBounds.byte_bounds n_bytes) x)\n            (byte_bounds_length :\n              forall x,\n                list_in_bounds byte_bounds x ->\n                length x = encoded_felem_size_in_bytes)\n            (res_eq : forall x,\n                bounded_by tight_bounds x ->\n                API.interp (res _) (map word.unsigned x)\n                = Partition.partition\n                    (ModOps.weight 8 1)\n                    encoded_felem_size_in_bytes\n                    (F.to_Z (feval x)))\n            (res_bounds : forall x,\n                bounded_by tight_bounds x ->\n                bytes_in_bounds\n                  (map byte.of_Z\n                       (API.interp (res _)\n                                   (map word.unsigned x)))).\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (Partition.partition _ _ _)] =>\n          autorewrite with distr_length;\n          cbv [FElemBytes] in *; sepsimpl; solve [auto]\n      end.\n\n    Local Notation t :=\n      (type.arrow type_listZ type_listZ) (only parsing).\n\n    Definition to_bytes_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (access_size.word, tt).\n    Definition to_bytes_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.one.\n    Definition to_bytes_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (n, tt).\n    Let insizes := to_bytes_insizes.\n    Let outsizes := to_bytes_outsizes.\n    Let inlengths := to_bytes_inlengths.\n\n    (* helper lemma about partition and nth_byte *)\n    Lemma nth_byte_partition x nbytes :\n      map (nth_byte x) (seq 0 nbytes) =\n      map byte.of_Z\n          (Partition.partition (ModOps.weight 8 1) nbytes x).\n    Proof.\n      cbv [Partition.partition nth_byte]. rewrite map_map.\n      apply map_ext; intros. rewrite Z.shiftr_div_pow2 by Lia.lia.\n      apply byte.unsigned_inj. rewrite !byte.unsigned_of_Z.\n      cbv [byte.wrap ModOps.weight].\n      autorewrite with zsimplify.\n      rewrite Nat2Z.inj_succ.\n      autorewrite with zsimplify.\n      rewrite Z.add_comm, Z.pow_add_r by Lia.lia.\n      rewrite !Modulo.Z.mod_pull_div by Lia.lia.\n      rewrite Z.mod_mod by auto with zarith.\n      reflexivity.\n    Qed.\n\n    Lemma to_bytes_correct f :\n      f = make_bedrock_func to_bytes insizes outsizes inlengths res ->\n      forall functions,\n        spec_of_to_bytes (f :: functions).\n    Proof using byte_bounds_length byte_bounds_tighter_than_max\n          inname_gen_varname_gen_disjoint\n          outname_gen_varname_gen_disjoint ok res_Wf\n          res_eq res_valid res_bounds.\n      subst inlengths insizes outsizes. cbv [spec_of_to_bytes].\n      cbv [to_bytes_insizes to_bytes_outsizes to_bytes_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup. eapply Proper_call.\n      2:{\n        use_translate_func_correct\n          constr:((map word.unsigned x, tt)) Rr.\n        all:try translate_func_precondition_hammer.\n        all:cbn [type.app_curried fst snd].\n        all:try rewrite res_eq by auto.\n        { eapply ByteBounds.byte_bounds_range_iff.\n          auto using ByteBounds.partition_bounded_by. }\n        { (* lists_reserved_with_initial_context *)\n          lists_reserved_simplify pout.\n          all:solve_equivalence_side_conditions. } }\n      { postcondition_simplify; [ ].\n        (* separation-logic postcondition *)\n        eapply Proper_sep_iff1;\n          [ solve [apply FElemBytes_array_truncated_scalar_iff1]\n          | reflexivity | ].\n        cbv [Z_to_bytes].\n        sepsimpl; [ | | ].\n        { autorewrite with distr_length. reflexivity. }\n        { rewrite nth_byte_partition, <-res_eq by auto.\n          eapply res_bounds; auto. }\n        { rewrite nth_byte_partition.\n          erewrite ByteBounds.byte_map_unsigned_of_Z,\n          ByteBounds.map_byte_wrap_bounded\n            by apply ByteBounds.partition_bounded_by.\n          rewrite <-res_eq by auto.\n          match goal with\n            H : map word.unsigned _ = API.interp (res _) _ |- _ =>\n            rewrite <-H end.\n          change (Z.of_nat (bytes_per access_size.one)) with 1 in *.\n          auto. } }\n    Qed.\n  End ToBytes.\n\n\nSection SelectZnZ.\n\n  Local Notation bit_range := {|ZRange.lower := 0; ZRange.upper := 1|}.\n  Context {res : API.Expr (type_Z -> type_listZ -> type_listZ -> type_listZ)}\n  (res_valid :\n     valid_func (res (fun _ : API.type => unit)))\n  (res_Wf : API.Wf res).\n\nContext\n  (res_eq : forall (x y : list word) (c : word),\n      list_Z_bounded_by (@max_bounds width n) (map word.unsigned x) ->\n      list_Z_bounded_by (@max_bounds width n) (map word.unsigned y) ->\n      ZRange.is_bounded_by_bool (word.unsigned c) bit_range = true ->\n                 (API.interp (res _)    \n                             (word.unsigned c)\n                             (map word.unsigned x)\n                             (map word.unsigned y))\n      = map word.unsigned (if (word.unsigned c =? 0) then x else y)).\n\n    Local Ltac equivalence_side_conditions_hook ::=\n      lazymatch goal with\n      | |- context [length (Partition.partition _ _ _)] =>\n          autorewrite with distr_length;\n          cbv [FElemBytes] in *; sepsimpl; solve [auto]\n      end.\n\n      Local Notation t :=\n      (type.arrow type_Z (type.arrow type_listZ (type.arrow type_listZ type_listZ)))\n        (only parsing).\n\n    Definition list_selectznz_insizes\n      : type.for_each_lhs_of_arrow access_sizes t :=\n      (tt, (access_size.word, (access_size.word, tt))).\n    Definition list_selectznz_outsizes\n      : base_access_sizes (type.final_codomain t) :=\n      access_size.word.\n    Definition list_selectznz_inlengths\n      : type.for_each_lhs_of_arrow list_lengths t :=\n      (tt, (n, (n, tt))).\n\n      Let insizes := list_selectznz_insizes.\n      Let outsizes := list_selectznz_outsizes.\n      Let inlengths := list_selectznz_inlengths.\n\n    Lemma bit_range_eq : forall x, ZRange.is_bounded_by_bool x bit_range = true -> x = 0 \\/ x = 1.\n    Proof.\n        intros. apply RulesProofs.unfold_is_bounded_by_bool in H.\n        simpl in H. lia.\n    Qed.\n\n    Lemma max_bounds_words : forall (x : list word) n, length x = n -> list_Z_bounded_by (@max_bounds width n) (map word.unsigned x).\n    Proof.\n        intros. generalize dependent x.\n        induction n0; intros.\n            - destruct x; try discriminate. simpl. cbv. auto.\n            - destruct x; try discriminate. simpl.\n              eapply Util.list_Z_bounded_by_cons. split.\n              2: {\n                  simpl in IHn0. eapply IHn0. auto.\n              }\n              apply Expr.is_bounded_by_bool_width_range.\n              eauto.\n              pose proof Properties.word.unsigned_range. auto.\n    Qed. \n\n    Lemma FElem_max_bounds : forall px x m R, (FElem px x * R)%sep m -> list_Z_bounded_by (@max_bounds width n) (map word.unsigned x).\n    Proof.\n      intros. eapply max_bounds_words. cbv [FElem Bignum.Bignum] in H. sepsimpl. eauto.\n    Qed. \n\n    Lemma select_znz_correct f :\n      f = make_bedrock_func select_znz insizes outsizes inlengths res ->\n      forall functions,\n        spec_of_selectznz (f :: functions).\n    Proof using inname_gen_varname_gen_disjoint\n          outname_gen_varname_gen_disjoint ok res_Wf\n          res_eq res_valid.\n      subst inlengths insizes outsizes. cbv [spec_of_selectznz].\n      cbv [list_selectznz_insizes list_selectznz_outsizes list_selectznz_inlengths].\n      cbv beta; intros; subst f. cbv [make_bedrock_func].\n      cleanup.\n      pose proof (FElem_max_bounds _ _ _ _ H0) as Hxbounds.\n      pose proof (FElem_max_bounds _ _ _ _ H1) as Hybounds.\n      match goal with\n      | H : ZRange.is_bounded_by_bool _ _ = _ |- _ => rename H into Hbound\n      | _ => idtac\n      end.\n      eapply Proper_call.\n      2:{ use_translate_func_correct\n          constr:((word.unsigned pc, (map word.unsigned x, (map word.unsigned y, tt)))) Rout.\n        all:try translate_func_precondition_hammer.\n        all:cbn [type.app_curried fst snd].\n        all:try rewrite res_eq by auto.\n        {\n            eapply (equivalent_flat_args_iff1\n            (make_innames (inname_gen:=default_inname_gen) _)\n            _ _ _\n            map.empty).\n                - apply flatten_make_innames_NoDup; solve [eapply prefix_name_gen_unique].\n                - reflexivity.\n                - compute_names. autounfold with equivalence pairs.\n                cbv [Equivalence.equivalent_base].\n                autounfold with equivalence pairs.\n                rewrite <- ?MakeAccessSizes.bytes_per_word_eq; sepsimpl.\n                    + crush_sep; try solve_equivalence_side_conditions. eauto. (*Which one?*)\n                    + crush_sep; try solve_equivalence_side_conditions.\n                    + crush_sep; try solve_equivalence_side_conditions.\n                    + auto.\n        }\n        1:  destruct (bit_range_eq _ Hbound) as [Hbit| Hbit]; rewrite Hbit; simpl;\n            eapply MaxBounds.max_bounds_range_iff; eauto.\n            lists_reserved_simplify pout.\n            all: try solve_equivalence_side_conditions.\n            destruct (bit_range_eq _ Hbound) as [Hbit| Hbit]; rewrite Hbit; simpl; auto; cbv [FElem Bignum.Bignum] in *; sepsimpl;\n            repeat rewrite map_length;\n            match goal with\n              | H : ?n1 = _ |- ?n1 = _ => rewrite H\n              | _ => idtac\n            end; eauto.\n      }\n        postcondition_simplify.\n        destruct (bit_range_eq _ Hbound) as [Hbit| Hbit].\n            - rewrite Hbit. simpl. eapply Proper_sep_iff1.\n                + apply FElem_array_truncated_scalar_iff1.\n                + intros; split; intros; eauto.\n                + sepsimpl; try ecancel_assumption.\n                    * erewrite <- map_length. erewrite length_list_Z_bounded_by; eauto.\n                      cbv [max_bounds]. rewrite repeat_length. eauto.\n                    * specialize (res_eq x y pc); rewrite Hbit in res_eq; simpl in res_eq.\n                      erewrite <- res_eq; eauto; rewrite <- Hbit; simpl in *; eauto.\n                      match goal with\n                      | H : map word.unsigned _ = _ |- _ => rewrite <- H\n                      | _ => idtac\n                      end; eauto.\n            - rewrite Hbit; simpl; eapply Proper_sep_iff1.\n                + apply FElem_array_truncated_scalar_iff1.\n                + intros; split; intros; eauto.\n                + sepsimpl; try ecancel_assumption.\n                    * erewrite <- map_length; erewrite length_list_Z_bounded_by; eauto;\n                      cbv [max_bounds]; rewrite repeat_length; eauto.\n                    * specialize (res_eq x y pc); rewrite Hbit in res_eq; simpl in res_eq.\n                      erewrite <- res_eq; eauto; rewrite <- Hbit; simpl in *; eauto.\n                      match goal with\n                      | H : map word.unsigned _ = _ |- _ => rewrite <- H\n                      | _ => idtac\n                      end; eauto.\n    Qed.\n  End SelectZnZ.\nEnd WithParameters.", "meta": {"author": "Veridise", "repo": "Coda", "sha": "d22d56c09ac541f012adae34820850ce6cd10270", "save_path": "github-repos/coq/Veridise-Coda", "path": "github-repos/coq/Veridise-Coda/Coda-d22d56c09ac541f012adae34820850ce6cd10270/BigInt/fiat-crypto/src/Bedrock/Field/Synthesis/New/Signature.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.16591664083288737}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.IL Bedrock.Memory Coq.Strings.String Bedrock.sep.Locals Coq.Lists.List.\n\nDefinition upd_option vs x value :=\n  match x with\n    | None => vs\n    | Some s => Locals.upd vs s value\n  end.\n\nRequire Import Bedrock.Platform.Cito.FuncCore.\nExport FuncCore.\nRequire Import ListFacts3.\nRecord InternalFuncSpec :=\n  {\n    Fun : FuncCore;\n    NoDupArgVars : is_no_dup (ArgVars Fun) = true\n  }.\n\nCoercion Fun : InternalFuncSpec >-> FuncCore.\n\nRequire Import Bedrock.Platform.Cito.Syntax Bedrock.Platform.Cito.SemanticsExpr.\nRequire Import Bedrock.Platform.Cito.GLabel.\nRequire Import Bedrock.Platform.Cito.WordMap.\nRequire Import Bedrock.Platform.Cito.AxSpec.\nExport AxSpec.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Definition Heap := WordMap.t ADTValue.\n\n  Definition State := (vals * Heap)%type.\n\n  Notation Value := (@Value ADTValue).\n  Notation AxiomaticSpec := (@AxiomaticSpec ADTValue).\n  Arguments SCA {ADTValue} _.\n  Arguments ADT {ADTValue} _.\n\n  Inductive Callee :=\n  | Foreign : AxiomaticSpec -> Callee\n  | Internal : InternalFuncSpec -> Callee.\n\n  Definition word_adt_match (heap : Heap) (p : W * Value) :=\n    let word := fst p in\n    let in_ := snd p in\n    match in_ with\n      | SCA w => word = w\n      | ADT a => WordMap.find word heap = Some a\n    end.\n\n  Definition disjoint_ptrs (pairs : list (W * Value)) :=\n    let pairs := filter (fun p => is_adt (snd p)) pairs in\n    NoDup (List.map fst pairs).\n\n  Definition good_inputs heap pairs :=\n    Forall (word_adt_match heap) pairs /\\\n    disjoint_ptrs pairs.\n\n  Record ArgTriple :=\n    {\n      Word : W;\n      ADTIn : Value;\n      ADTOut : option ADTValue\n    }.\n\n  Definition store_out (heap : Heap) t :=\n    match ADTIn t, ADTOut t with\n      | SCA _, _ => heap\n      | ADT _, None => WordMap.remove (Word t) heap\n      | ADT _, Some a => WordMap.add (Word t) a heap\n    end.\n\n  Definition decide_ret addr (ret : Value) :=\n    match ret with\n      | SCA w => (w, None)\n      | ADT a => (addr, Some a)\n    end.\n\n  Definition separated heap ret_w (ret_a : option ADTValue) :=\n    ret_a = None \\/ ~ @WordMap.In ADTValue ret_w heap.\n\n  Definition heap_upd_option m k (v : option ADTValue) :=\n    match v with\n      | Some x => WordMap.add k x m\n      | None => m\n    end.\n\n  (* Semantics *)\n\n  Section Env.\n\n    Variable env : (glabel -> option W) * (W -> option Callee).\n\n    Inductive RunsTo : Stmt -> State -> State -> Prop :=\n    | RunsToSkip : forall v, RunsTo Syntax.Skip v v\n    | RunsToSeq :\n        forall a b v v' v'',\n          RunsTo a v v' ->\n          RunsTo b v' v'' ->\n          RunsTo (Syntax.Seq a b) v v''\n    | RunsToIfTrue :\n        forall cond t f v v',\n          wneb (eval (fst v) cond) $0 = true ->\n          RunsTo t v v' ->\n          RunsTo (Syntax.If cond t f) v v'\n    | RunsToIfFalse :\n        forall cond t f v v',\n          wneb (eval (fst v) cond) $0 = false ->\n          RunsTo f v v' ->\n          RunsTo (Syntax.If cond t f) v v'\n    | RunsToWhileTrue :\n        forall cond body v v' v'',\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = true ->\n          RunsTo body v v' ->\n          RunsTo loop v' v'' ->\n          RunsTo loop v v''\n    | RunsToWhileFalse :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = false ->\n          RunsTo loop v v\n    | RunsToCallInternal :\n        forall var f args v spec vs_callee vs_callee' heap',\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Internal spec) ->\n          map (Locals.sel vs_callee) (ArgVars spec) = map (eval vs) args ->\n          RunsTo (Body spec) (vs_callee, heap) (vs_callee', heap') ->\n          let vs := upd_option vs var (Locals.sel vs_callee' (RetVar spec)) in\n          let heap := heap' in\n          RunsTo (Syntax.Call var f args) v (vs, heap)\n    | RunsToCallForeign :\n        forall var f args v spec triples addr ret heap',\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Foreign spec) ->\n          map (eval vs) args = map Word triples ->\n          good_inputs heap (map (fun x => (Word x, ADTIn x)) triples) ->\n          PreCond spec (map ADTIn triples) ->\n          PostCond spec (map (fun x => (ADTIn x, ADTOut x)) triples) ret ->\n          let heap := fold_left store_out triples heap in\n          let t := decide_ret addr ret in\n          let ret_w := fst t in\n          let ret_a := snd t in\n          separated heap ret_w ret_a ->\n          let heap := heap_upd_option heap ret_w ret_a in\n          let vs := upd_option vs var ret_w in\n          WordMap.Equal heap' heap ->\n          RunsTo (Syntax.Call var f args) v (vs, heap')\n    | RunsToLabel :\n        forall x lbl v w,\n          fst env lbl = Some w ->\n          RunsTo (Syntax.Label x lbl) v (Locals.upd (fst v) x w, snd v)\n    | RunsToAssign :\n        forall x e v,\n          let vs := fst v in\n          RunsTo (Syntax.Assign x e) v (Locals.upd vs x (eval vs e), snd v).\n\n    CoInductive Safe : Stmt -> State -> Prop :=\n    | SafeSkip :\n        forall v, Safe Syntax.Skip v\n    | SafeSeq :\n        forall a b v,\n          Safe a v ->\n          (forall v', RunsTo a v v' -> Safe b v') ->\n          Safe (Syntax.Seq a b) v\n    | SafeIf :\n        forall cond t f v,\n          let b := wneb (eval (fst v) cond) $0 in\n          b = true /\\ Safe t v \\/ b = false /\\ Safe f v ->\n          Safe (Syntax.If cond t f) v\n    | SafeWhileTrue :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = true ->\n          Safe body v ->\n          (forall v', RunsTo body v v' -> Safe loop v') ->\n          Safe loop v\n    | SafeWhileFalse :\n        forall cond body v,\n          let loop := While cond body in\n          wneb (eval (fst v) cond) $0 = false ->\n          Safe loop v\n    | SafeCallInternal :\n        forall var f args v spec,\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Internal spec) ->\n          length (ArgVars spec) = length args ->\n          (forall vs_arg,\n             map (Locals.sel vs_arg) (ArgVars spec) = map (eval vs) args\n             -> Safe (Body spec) (vs_arg, heap)) ->\n          Safe (Syntax.Call var f args) v\n    | SafeCallForeign :\n        forall var f args v spec pairs,\n          let vs := fst v in\n          let heap := snd v in\n          let fs := snd env in\n          fs (eval vs f) = Some (Foreign spec) ->\n          map (eval vs) args = map fst pairs ->\n          good_inputs heap pairs ->\n          PreCond spec (map snd pairs) ->\n          Safe (Syntax.Call var f args) v\n    | SafeLabel :\n        forall x lbl v,\n          fst env lbl <> None ->\n          Safe (Syntax.Label x lbl) v\n    | SafeAssign :\n        forall x e v,\n          Safe (Syntax.Assign x e) v.\n\n    Section Safe_coind.\n      Variable R : Stmt -> State -> Prop.\n\n      Hypothesis SeqCase : forall a b v, R (Syntax.Seq a b) v -> R a v /\\ forall v', RunsTo a v v' -> R b v'.\n\n      Hypothesis IfCase : forall cond t f v, R (Syntax.If cond t f) v -> (wneb (eval (fst v) cond) $0 = true /\\ R t v) \\/ (wneb (eval (fst v) cond) $0 = false /\\ R f v).\n\n      Hypothesis WhileCase :\n        forall cond body v,\n          let loop := Syntax.While cond body in\n          R loop v ->\n          (wneb (eval (fst v) cond) $0 = true /\\ R body v /\\ (forall v', RunsTo body v v' -> R loop v')) \\/\n          (wneb (eval (fst v) cond) $0 = false).\n\n      Hypothesis CallCase : forall var f args v,\n        R (Syntax.Call var f args) v\n        -> (exists spec, let vs := fst v in\n          let heap := snd v in\n            let fs := snd env in\n              fs (eval vs f) = Some (Internal spec) /\\\n              length (ArgVars spec) = length args /\\\n              (forall vs_arg,\n                map (Locals.sel vs_arg) (ArgVars spec) = map (eval vs) args\n                -> R (Body spec) (vs_arg, heap)))\n        \\/ (exists spec, exists pairs, let vs := fst v in\n          let heap := snd v in\n            let fs := snd env in\n              fs (eval vs f) = Some (Foreign spec) /\\\n              map (eval vs) args = map fst pairs /\\\n              good_inputs heap pairs /\\\n              PreCond spec (map snd pairs)).\n\n      Hypothesis LabelCase : forall x lbl v,\n        R (Syntax.Label x lbl) v\n        -> fst env lbl <> None.\n\n      Hint Constructors Safe.\n\n      Ltac openhyp :=\n        repeat match goal with\n                 | H : _ /\\ _ |- _  => destruct H\n                 | H : _ \\/ _ |- _ => destruct H\n                 | H : exists x, _ |- _ => destruct H\n               end.\n\n      Ltac break_pair :=\n        match goal with\n          V : (_ * _)%type |- _ => destruct V\n        end.\n\n      Theorem Safe_coind : forall c v, R c v -> Safe c v.\n        cofix; unfold State; intros; break_pair; destruct c.\n\n        eauto.\n\n        eapply SeqCase in H; openhyp; eauto.\n\n        eapply IfCase in H; openhyp; eauto.\n\n        eapply WhileCase in H; openhyp; eauto.\n\n        eapply CallCase in H; openhyp; simpl in *; intuition eauto.\n\n        eapply LabelCase in H; openhyp; eauto.\n\n        eauto.\n      Qed.\n\n    End Safe_coind.\n\n  End Env.\n\nEnd ADTValue.\n\nRequire Import Bedrock.Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Definition RunsTo := @RunsTo ADTValue.\n\n  Definition Safe := @Safe ADTValue.\n\n  Definition Heap := @Heap ADTValue.\n\n  Definition State := @State ADTValue.\n\n  Definition ArgIn := @Value ADTValue.\n\n  Definition ArgOut := option ADTValue.\n\n  Definition Ret := @Value ADTValue.\n\n  Definition ForeignFuncSpec := @AxiomaticSpec ADTValue.\n\n  Definition Callee := @Callee ADTValue.\n\n  Definition ArgTriple := @ArgTriple ADTValue.\n\n  Definition word_adt_match := @word_adt_match ADTValue.\n\n  Definition is_adt := @is_adt ADTValue.\n\n  Definition disjoint_ptrs := @disjoint_ptrs ADTValue.\n\n  Definition good_inputs := @good_inputs ADTValue.\n\n  Definition store_out := @store_out ADTValue.\n\n  Definition decide_ret := @decide_ret ADTValue.\n\n  Definition separated := @separated ADTValue.\n\n  Definition heap_upd_option := @heap_upd_option ADTValue.\n\n  Definition Foreign := @Foreign ADTValue.\n\n  Definition Internal := @Internal ADTValue.\n\n  (* some shorthands for heap operations *)\n  Require Import Coq.FSets.FMapFacts.\n  Module Import P := Properties WordMap.\n  Import F WordMap.\n\n  Definition elt := ADTValue.\n\n  Implicit Types m h : Heap.\n  Implicit Types x y z k p w : key.\n  Implicit Types e v a : elt.\n  Implicit Types ls : list (key * elt).\n\n  Definition heap_sel h p := find p h.\n\n  Definition heap_mem := @In elt.\n\n  Definition heap_upd h p v := add p v h.\n\n  Definition heap_remove h p := remove p h.\n\n  Definition heap_empty := @empty elt.\n\n  Definition heap_merge := @update elt.\n\n  Definition heap_elements := @elements elt.\n\n  Definition heap_diff := @diff elt.\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/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.16591663897881018}}
{"text": "Require Import compcert.common.Memory.\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.juicy_mem.\nRequire Import VST.veric.compcert_rmaps. \nRequire Import VST.veric.semax.\nRequire Import VST.veric.juicy_extspec.\n\nRequire Import VST.veric.mem_lessdef.\nRequire Import VST.veric.age_to_resource_at.\n\nRequire Import VST.veric.aging_lemmas.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nLemma jsafeN_age Z Jspec ge ora q n jm jmaged :\n  ext_spec_stable age (JE_spec _ Jspec) ->\n  age jm jmaged ->\n  Peano.le n (level jmaged) ->\n  @jsafeN Z Jspec ge n ora q jm ->\n  @jsafeN Z Jspec ge n ora q jmaged.\nProof. intros. eapply jsafeN__age; eauto. Qed.\n\nLemma jsafeN_age_to Z Jspec ge ora q n l jm :\n  ext_spec_stable age (JE_spec _ Jspec) ->\n  Peano.le n l ->\n  @jsafeN Z Jspec ge n ora q jm ->\n  @jsafeN Z Jspec ge n ora q (age_to l jm).\nProof. intros. eapply jsafeN__age_to; eauto. Qed.\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/Clight_aging_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16591663749143337}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.LeaderLogsContiguousInterface.\nRequire Import VerdiRaft.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  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 *;lia)\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 lia.\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; 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.\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/LeaderLogsContiguousProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.16591663749143337}}
{"text": "Require Import SpecCert.x86.Architecture.\nRequire Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.x86.Value.\n\nDefinition write_uncachable\n           {Label:    Type}\n           (a:        Architecture Label)\n           (labelize: Architecture Label -> Label)\n           (pa:       PhysicalAddress)\n           (val:      Value) :=\n  let lab := (labelize a) in\n  let ha := phys_to_hard a pa in\n  update_memory_content a ha (val,lab).\n\nDefinition write_writeback\n           {Label:    Type}\n           (a:        Architecture Label)\n           (labelize: Architecture Label -> Label)\n           (pa:       PhysicalAddress)\n           (val:      Value) :=\n  let lab := (labelize a) in\n  let a' := if cache_hit_dec (cache a) pa\n            then a\n            else load_in_cache_from_memory a pa in\n  update_cache_content a' pa (val,lab).\n\n(* Intel, Chapter 11: Memory Cache Control\n  \"If the logical processor is not in SMM, write accesses are ignored (...)\" *)\nDefinition write_smrrhit\n           {Label:    Type}\n           (a:        Architecture Label) :=\n  a.\n\nDefinition write_post\n           {Label:    Type}\n           (labelize: Architecture Label -> Label)\n           (pa:       PhysicalAddress)\n           (val:      Value)\n           (a a':Architecture Label) :=\n  match resolve_cache_strategy (proc a) pa with\n  | Uncachable => a' = write_uncachable a labelize pa val\n  | WriteBack  => a' = write_writeback a labelize pa val\n  | SmrrHit    => a' = write_smrrhit 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/Transition/Event/Write.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.16571670406393096}}
{"text": "Require Import CoqlibC.\nRequire Import Simulation.\nRequire Import LinkingC.\nRequire Import Skeleton.\nRequire Import Values.\nRequire Import JMeq.\nRequire Import SmallstepC.\nRequire Import Integers.\nRequire Import Events.\n\nRequire Import Skeleton ModSem Mod Sem.\nRequire Import SimSymb SimMem SimMod SimModSem SimProg SimProg.\nRequire Import ModSemProps SemProps Ord.\nRequire Import Sound Preservation AdequacySound.\nRequire Import Program RUSC.\n\nSet Implicit Arguments.\n\n\n\n\n\n\nSection SIMGE.\n\n  Context `{SM: SimMem.class}.\n  Context `{SU: Sound.class}.\n  Context {SS: SimSymb.class SM}.\n  Inductive sim_ge (sm0: SimMem.t): Ge.t -> Ge.t -> Prop :=\n  | sim_ge_src_stuck\n      ge_tgt skenv_link_src skenv_link_tgt:\n      sim_ge sm0 ([], skenv_link_src) (ge_tgt, skenv_link_tgt)\n  | sim_ge_intro\n      msps ge_src ge_tgt skenv_link_src skenv_link_tgt\n      (SIMSKENV: List.Forall (fun msp => ModSemPair.sim_skenv msp sm0) msps)\n      (SIMMSS: List.Forall (ModSemPair.sim) msps)\n      (GESRC: ge_src = (map (ModSemPair.src) msps))\n      (GETGT: ge_tgt = (map (ModSemPair.tgt) msps))\n      (SIMSKENVLINK: exists ss_link, SimSymb.sim_skenv sm0 ss_link skenv_link_src skenv_link_tgt)\n      (MFUTURE: List.Forall (fun msp => SimMem.future msp.(ModSemPair.sm) sm0) msps)\n      (SESRC: List.Forall (fun ms => (ModSem.to_semantics ms).(symbolenv) = skenv_link_src) ge_src)\n      (SETGT: List.Forall (fun ms => (ModSem.to_semantics ms).(symbolenv) = skenv_link_tgt) ge_tgt):\n      sim_ge sm0 (ge_src, skenv_link_src) (ge_tgt, skenv_link_tgt).\n\n  Lemma find_fptr_owner_fsim\n        sm0 ge_src ge_tgt fptr_src fptr_tgt ms_src\n        (SIMGE: sim_ge sm0 ge_src ge_tgt)\n        (SIMFPTR: SimMem.sim_val sm0 fptr_src fptr_tgt)\n        (FINDSRC: Ge.find_fptr_owner ge_src fptr_src ms_src):\n      exists msp,\n        <<SRC: msp.(ModSemPair.src) = ms_src>>\n        /\\ <<FINDTGT: Ge.find_fptr_owner ge_tgt fptr_tgt msp.(ModSemPair.tgt)>>\n        /\\ <<SIMMS: ModSemPair.sim msp>>\n        /\\ <<SIMSKENV: ModSemPair.sim_skenv msp sm0>>\n        /\\ <<MFUTURE: SimMem.future msp.(ModSemPair.sm) sm0>>.\n  Proof.\n    inv SIMGE.\n    { inv FINDSRC; ss. }\n    rewrite Forall_forall in *. inv FINDSRC. ss.\n    rewrite in_map_iff in MODSEM. des. rename x into msp. esplits; eauto. clarify.\n    specialize (SIMMSS msp). exploit SIMMSS; eauto. clear SIMMSS. intro SIMMS.\n    specialize (SIMSKENV msp). exploit SIMSKENV; eauto. clear SIMSKENV. intro SIMSKENV.\n\n    exploit SimSymb.sim_skenv_func_bisim; try apply SIMSKENV. intro SIMFUNC; des.\n    inv SIMFUNC. exploit FUNCFSIM; eauto. i; des. clear_tac. inv SIM. econs; eauto.\n    apply in_map_iff. esplits; eauto.\n\n  Qed.\n\n  Theorem mfuture_preserves_sim_ge\n          sm0 ge_src ge_tgt sm1\n          (SIMGE: sim_ge sm0 ge_src ge_tgt)\n          (MFUTURE: SimMem.future sm0 sm1):\n      <<SIMGE: sim_ge sm1 ge_src ge_tgt>>.\n  Proof.\n    inv SIMGE.\n    { econs; eauto. }\n    econs 2; try reflexivity; eauto.\n    - rewrite Forall_forall in *. ii. eapply ModSemPair.mfuture_preserves_sim_skenv; eauto.\n    - des. esplits; eauto. eapply SimSymb.mfuture_preserves_sim_skenv; eauto.\n    - rewrite Forall_forall in *. ii. etrans; eauto.\n  Qed.\n\n  Lemma sim_ge_cons\n        sm_init tl_src tl_tgt msp skenv_link_src skenv_link_tgt\n        (SAFESRC: tl_src <> [])\n        (SIMMSP: ModSemPair.sim msp)\n        (SIMGETL: sim_ge sm_init (tl_src, skenv_link_src) (tl_tgt, skenv_link_tgt))\n        (SIMSKENV: ModSemPair.sim_skenv msp sm_init)\n        (MFUTURE: SimMem.future (ModSemPair.sm msp) sm_init)\n        (SESRC: (symbolenv (ModSemPair.src msp)) = skenv_link_src)\n        (SETGT: (symbolenv (ModSemPair.tgt msp)) = skenv_link_tgt):\n      <<SIMGE: sim_ge sm_init (msp.(ModSemPair.src) :: tl_src, skenv_link_src)\n                      (msp.(ModSemPair.tgt) :: tl_tgt, skenv_link_tgt)>>.\n  Proof. red. inv SIMGETL; ss. econstructor 2 with (msps := msp :: msps); eauto. Qed.\n\n  Lemma to_msp_tgt: forall skenv_tgt skenv_src pp sm_init,\n          map ModSemPair.tgt (map (ModPair.to_msp skenv_src skenv_tgt sm_init) pp) =\n          map (fun md => Mod.modsem md skenv_tgt) (ProgPair.tgt pp).\n  Proof. i. ginduction pp; ii; ss. f_equal. erewrite IHpp; eauto. Qed.\n\n  Lemma to_msp_src: forall skenv_tgt skenv_src pp sm_init,\n      map ModSemPair.src (map (ModPair.to_msp skenv_src skenv_tgt sm_init) pp) =\n      map (fun md => Mod.modsem md skenv_src) (ProgPair.src pp).\n  Proof. i. ginduction pp; ii; ss. f_equal. erewrite IHpp; eauto. Qed.\n\n  Lemma to_msp_sim_skenv\n        sm_init mp skenv_src skenv_tgt ss_link\n        (WFSRC: SkEnv.wf skenv_src)\n        (WFTGT: SkEnv.wf skenv_tgt)\n        (INCLSRC: SkEnv.includes skenv_src (Mod.sk mp.(ModPair.src)))\n        (INCLTGT: SkEnv.includes skenv_tgt (Mod.sk mp.(ModPair.tgt)))\n        (SIMMP: ModPair.sim mp)\n        (LESS: SimSymb.le (ModPair.ss mp) ss_link)\n        (SIMSKENV: SimSymb.sim_skenv sm_init ss_link skenv_src skenv_tgt):\n        <<SIMSKENV: ModSemPair.sim_skenv (ModPair.to_msp skenv_src skenv_tgt sm_init mp) sm_init>>.\n  Proof.\n    u. econs; ss; eauto; cycle 1.\n    { rewrite ! Mod.get_modsem_skenv_link_spec. eauto. }\n    inv SIMMP.\n    eapply SimSymb.sim_skenv_monotone; revgoals; try rewrite SKSRC; try rewrite SKTGT; try eapply Mod.get_modsem_skenv_spec; try eapply SIMMP; ss; eauto.\n  Qed.\n\n  Theorem init_sim_ge_strong\n          pp p_src p_tgt ss_link skenv_link_src skenv_link_tgt m_src\n          (NOTNIL: pp <> [])\n          (SIMPROG: ProgPair.sim pp)\n          (PSRC: p_src = (ProgPair.src pp))\n          (PTGT: p_tgt = (ProgPair.tgt pp))\n          (SSLE: Forall (fun mp => SimSymb.le (ModPair.ss mp) ss_link) pp)\n          (SIMSK: SimSymb.wf ss_link)\n          (SKSRC: link_sk p_src = Some ss_link.(SimSymb.src))\n          (SKTGT: link_sk p_tgt = Some ss_link.(SimSymb.tgt))\n          (SKENVSRC: Sk.load_skenv ss_link.(SimSymb.src) = skenv_link_src)\n          (SKENVTGT: Sk.load_skenv ss_link.(SimSymb.tgt) = skenv_link_tgt)\n          (WFSKSRC: forall mp (IN: In mp pp), Sk.wf (ModPair.src mp))\n          (WFSKTGT: forall mp (IN: In mp pp), Sk.wf (ModPair.tgt mp))\n          (LOADSRC: Sk.load_mem ss_link.(SimSymb.src) = Some m_src):\n      exists sm_init, <<SIMGE: sim_ge sm_init\n                                      (load_genv p_src (Sk.load_skenv ss_link.(SimSymb.src)))\n                                      (load_genv p_tgt (Sk.load_skenv ss_link.(SimSymb.tgt)))>>\n         /\\ <<MWF: SimMem.wf sm_init>>\n         /\\ <<LOADTGT: Sk.load_mem ss_link.(SimSymb.tgt) = Some sm_init.(SimMem.tgt)>>\n         /\\ <<MSRC: sm_init.(SimMem.src) = m_src>>\n         /\\ (<<SIMSKENV: SimSymb.sim_skenv sm_init ss_link skenv_link_src skenv_link_tgt>>)\n         /\\ (<<INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))>>)\n         /\\ (<<INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))>>)\n         /\\ (<<SSLE: forall mp (IN: In mp pp), SimSymb.le mp.(ModPair.ss) ss_link>>)\n         /\\ (<<MAINSIM: SimMem.sim_val sm_init (Genv.symbol_address skenv_link_src ss_link.(SimSymb.src).(prog_main) Ptrofs.zero)\n                                             (Genv.symbol_address skenv_link_tgt ss_link.(SimSymb.tgt).(prog_main) Ptrofs.zero)>>).\n  Proof.\n    assert(INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))).\n    { ii. clarify. eapply link_includes; eauto.\n      unfold ProgPair.src. rewrite in_map_iff. esplits; et. }\n    assert(INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))).\n    { ii. clarify. eapply link_includes; eauto.\n      unfold ProgPair.tgt. rewrite in_map_iff. esplits; et. }\n    clarify. exploit SimSymb.wf_load_sim_skenv; eauto. i; des. rename sm into sm_init. clarify.\n    esplits; eauto; cycle 1.\n    { rewrite Forall_forall in *. eauto. }\n    unfold load_genv in *. ss. bar.\n    assert(exists msp_sys,\n              (<<SYSSRC: msp_sys.(ModSemPair.src) = System.modsem (Sk.load_skenv ss_link.(SimSymb.src))>>)\n              /\\ (<<SYSTGT: msp_sys.(ModSemPair.tgt) = System.modsem (Sk.load_skenv ss_link.(SimSymb.tgt))>>)\n              /\\ <<SYSSIM: ModSemPair.sim msp_sys>> /\\ <<SIMSKENV: ModSemPair.sim_skenv msp_sys sm_init>>\n              /\\ (<<MFUTURE: SimMem.future msp_sys.(ModSemPair.sm) sm_init>>)).\n    { exploit SimSymb.system_sim_skenv; eauto. i; des.\n      eexists (ModSemPair.mk _ _ ss_link sm_init). ss. esplits; eauto.\n      - exploit system_local_preservation. intro SYSSU; des. econs.\n        { ss. eauto. }\n        { instantiate (2:= Empty_set). ii; ss. }\n        ii. inv SIMSKENV0. ss.\n        split; cycle 1.\n        { ii; des. inv SAFESRC. inv SIMARGS; ss. esplits; eauto. econs; eauto. }\n        ii. sguard in SAFESRC. des. inv INITTGT.\n        inv SIMARGS; ss. clarify.\n        esplits; eauto.\n        { refl. }\n        { econs; eauto. }\n        pfold.\n        econs; eauto.\n        i.\n        econs; ss; cycle 2.\n        { eapply System.modsem_receptive; et. }\n        { u. esplits; ii; des; ss; eauto. inv H0. }\n        ii. inv STEPSRC.\n        exploit SimSymb.system_axiom; eauto; swap 1 3; swap 2 4.\n        { econs; eauto. }\n        { ss. instantiate (1:= Retv.mk _ _). ss. eauto. }\n        { ss. }\n        { ss. }\n        i; des.\n        assert(SIMGE: SimSymb.sim_skenv sm_arg ss_link (System.globalenv (Sk.load_skenv ss_link.(SimSymb.src)))\n                                        (System.globalenv (Sk.load_skenv ss_link.(SimSymb.tgt)))).\n        { eapply SimSymb.mfuture_preserves_sim_skenv; eauto. }\n        hexpl SimSymb.sim_skenv_func_bisim SIMGE0.\n        inv SIMGE0. exploit FUNCFSIM; eauto. i; des. clarify.\n        esplits; eauto.\n        { left. apply plus_one. econs.\n          - eapply System.modsem_determinate; et.\n          - ss. econs; eauto. }\n        left. pfold.\n        econs 4.\n        { refl. }\n        { eauto. }\n        { econs; eauto. }\n        { econs; eauto. }\n        { inv RETV; ss. unfold Retv.mk in *. clarify. econs; ss; eauto. }\n    }\n    des. rewrite <- SYSSRC. rewrite <- SYSTGT. eapply sim_ge_cons; ss.\n    - ii. destruct pp; ss.\n    - clear_until_bar. clear TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.\n      ginduction pp; ii; ss. unfold link_sk in *. ss. rename a into mp. destruct (classic (pp = [])).\n      { clarify. ss. clear IHpp. inv SSLE. inv H2. cbn in *. clarify.\n        rename H0 into SKSRC. rename H2 into SKTGT.\n        rewrite <- SKSRC in *. rewrite <- SKTGT in *.\n        set (skenv_src := (Sk.load_skenv (ModPair.src mp))) in *.\n        set (skenv_tgt := (Sk.load_skenv (ModPair.tgt mp))) in *.\n        inv SIMPROG. inv H3. rename H2 into SIMMP. inv SIMMP.\n        econstructor 2 with (msps := (map (ModPair.to_msp skenv_src skenv_tgt sm_init) [mp])); eauto; ss; revgoals; econs; eauto.\n        - u. erewrite Mod.get_modsem_skenv_link_spec; ss.\n        - u. erewrite Mod.get_modsem_skenv_link_spec; ss.\n        -  eapply SIMMS; eauto; eapply SkEnv.load_skenv_wf; et.\n        - econs; ss; eauto; cycle 1.\n          { unfold Mod.modsem. rewrite ! Mod.get_modsem_skenv_link_spec. eauto. }\n          r. ss. eapply SimSymb.sim_skenv_monotone; try rewrite SKSRC0; try rewrite SKTGT0;\n                   try apply SIMSKENV; try eapply SkEnv.load_skenv_wf; try eapply Mod.get_modsem_skenv_spec; eauto.\n      }\n      rename H into NNIL.\n      apply link_list_cons_inv in SKSRC; cycle 1. { destruct pp; ss. } des. rename restl into sk_src_tl.\n      apply link_list_cons_inv in SKTGT; cycle 1. { destruct pp; ss. } des. rename restl into sk_tgt_tl.\n      inv SIMPROG. rename H1 into SIMMP. rename H2 into SIMPROG. inv SSLE. rename H1 into SSLEHD. rename H2 into SSLETL. unfold flip.\n      set (skenv_src := (Sk.load_skenv (SimSymb.src ss_link))) in *.\n      set (skenv_tgt := (Sk.load_skenv (SimSymb.tgt ss_link))) in *.\n      assert(WFSRC: SkEnv.wf skenv_src).\n      { eapply SkEnv.load_skenv_wf; et.\n        eapply (link_list_preserves_wf_sk ((ModPair.src mp) :: (ProgPair.src pp))); et.\n        - unfold link_sk. ss. eapply link_list_cons; et.\n        - ii; ss. des; clarify; et. unfold ProgPair.src in *. rewrite in_map_iff in *. des. clarify. et.\n      }\n      assert(WFTGT: SkEnv.wf skenv_tgt).\n      { eapply SkEnv.load_skenv_wf; et.\n        eapply (link_list_preserves_wf_sk ((ModPair.tgt mp) :: (ProgPair.tgt pp))); et.\n        - unfold link_sk. ss. eapply link_list_cons; et.\n        - ii; ss. des; clarify; et. unfold ProgPair.tgt in *. rewrite in_map_iff in *. des. clarify. et.\n      }\n      econstructor 2 with\n          (msps := (map (ModPair.to_msp skenv_src skenv_tgt sm_init) (mp :: pp))); eauto; revgoals.\n      + rewrite Forall_forall in *. i. ss. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n        u in H. rewrite in_map_iff in H. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n      + rewrite Forall_forall in *. i. ss. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n        u in H. rewrite in_map_iff in H. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n      + ss. econs; eauto. rewrite Forall_forall in *. ii. rewrite in_map_iff in H. des. clarify. ss. refl.\n      + ss. f_equal. rewrite to_msp_tgt; ss.\n      + ss. f_equal. rewrite to_msp_src; ss.\n      + ss. econs; ss; eauto.\n        * eapply SIMMP; eauto.\n        * rewrite Forall_forall in *. i. apply in_map_iff in H. des.\n          specialize (SIMPROG x0). special SIMPROG; ss. clarify. eapply SIMPROG; eauto.\n      + ss. econs; ss; eauto.\n        * eapply to_msp_sim_skenv; eauto.\n        * rewrite Forall_forall in *. i. rewrite in_map_iff in *. des. clarify. eapply to_msp_sim_skenv; eauto.\n    - rewrite SYSSRC. ss.\n    - rewrite SYSTGT. ss.\n  Unshelve.\n    all: try apply idx_bot.\n    all: try (by ii; ss).\n  Qed.\n\nEnd SIMGE.\n\n\n\n\n\n\n\n\n\n\n\n\nSection ADQMATCH.\n\n  Context `{SM: SimMem.class}.\n  Context {SS: SimSymb.class SM}.\n  Context `{SU: Sound.class}.\n\n  Variable pp: ProgPair.t.\n  Let p_src := (ProgPair.src pp).\n  Let p_tgt := (ProgPair.tgt pp).\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  Inductive lxsim_stack: SimMem.t ->\n                         list Frame.t -> list Frame.t -> Prop :=\n  | lxsim_stack_nil\n      sm0:\n      lxsim_stack sm0 [] []\n  | lxsim_stack_cons\n      tail_src tail_tgt tail_sm ms_src lst_src0 ms_tgt lst_tgt0 sm_at sm_arg sm_arg_lift sm_init sidx\n      (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n      (MWF: SimMem.wf sm_arg)\n      (GE: sim_ge sm_at sem_src.(globalenv) sem_tgt.(globalenv))\n      (MLE: SimMem.le tail_sm sm_at)\n      (MLE: SimMem.le sm_at sm_arg)\n      (MLELIFT: SimMem.lepriv sm_arg sm_arg_lift)\n      (MLE: SimMem.le sm_arg_lift sm_init)\n      (sound_states_local: sidx -> Sound.t -> Memory.Mem.mem -> ms_src.(ModSem.state) -> Prop)\n      (PRSV: forall si, local_preservation_noguarantee ms_src (sound_states_local si))\n      (K: forall sm_ret retv_src retv_tgt lst_src1\n          (MLE: SimMem.le sm_arg_lift sm_ret)\n          (MWF: SimMem.wf sm_ret)\n          (SIMRETV: SimMem.sim_retv retv_src retv_tgt sm_ret)\n          (SU: forall si, exists su m_arg, (sound_states_local si) su m_arg lst_src0)\n          (AFTERSRC: ms_src.(ModSem.after_external) lst_src0 retv_src lst_src1),\n          exists lst_tgt1 sm_after i1,\n            (<<AFTERTGT: ms_tgt.(ModSem.after_external) lst_tgt0 retv_tgt lst_tgt1>>)\n            /\\ (<<MLEPUB: SimMem.le sm_at sm_after>>)\n            /\\ (<<LXSIM: lxsim ms_src ms_tgt (fun st => forall si, exists su m_arg, (sound_states_local si) su m_arg st)\n                            i1 lst_src1 lst_tgt1 sm_after>>))\n      (SESRC: (ModSem.to_semantics ms_src).(symbolenv) = skenv_link_src)\n      (SETGT: (ModSem.to_semantics ms_tgt).(symbolenv) = skenv_link_tgt):\n      lxsim_stack sm_init\n                  ((Frame.mk ms_src lst_src0) :: tail_src)\n                  ((Frame.mk ms_tgt lst_tgt0) :: tail_tgt).\n\n  Lemma lxsim_stack_le\n        sm0 frs_src frs_tgt sm1\n        (SIMSTACK: lxsim_stack sm0 frs_src frs_tgt)\n        (MLE: SimMem.le sm0 sm1):\n      <<SIMSTACK: lxsim_stack sm1 frs_src frs_tgt>>.\n  Proof.\n    inv SIMSTACK.\n    { econs 1; eauto. }\n    econs 2; eauto. etransitivity; eauto.\n  Qed.\n\n  Inductive lxsim_lift: idx -> sem_src.(Smallstep.state) -> sem_tgt.(Smallstep.state) -> SimMem.t -> Prop :=\n  | lxsim_lift_intro\n      sm0 tail_src tail_tgt tail_sm i0 ms_src lst_src ms_tgt lst_tgt sidx\n      (GE: sim_ge sm0 sem_src.(globalenv) sem_tgt.(globalenv))\n\n      (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n      (MLE: SimMem.le tail_sm sm0)\n      (sound_states_local: sidx -> Sound.t -> Memory.Mem.mem -> ms_src.(ModSem.state) -> Prop)\n      (PRSV: forall si, local_preservation_noguarantee ms_src (sound_states_local si))\n      (TOP: lxsim ms_src ms_tgt (fun st => forall si, exists su m_arg, (sound_states_local si) su m_arg st)\n                  i0 lst_src lst_tgt sm0)\n      (SESRC: (ModSem.to_semantics ms_src).(symbolenv) = skenv_link_src)\n      (SETGT: (ModSem.to_semantics ms_tgt).(symbolenv) = skenv_link_tgt):\n      lxsim_lift i0 (State ((Frame.mk ms_src lst_src) :: tail_src)) (State ((Frame.mk ms_tgt lst_tgt) :: tail_tgt)) sm0\n  | lxsim_lift_callstate\n       sm_arg tail_src tail_tgt tail_sm args_src args_tgt\n       (GE: sim_ge sm_arg sem_src.(globalenv) sem_tgt.(globalenv))\n       (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n       (MLE: SimMem.le tail_sm sm_arg)\n       (MWF: SimMem.wf sm_arg)\n       (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg):\n      lxsim_lift idx_bot (Callstate args_src tail_src) (Callstate args_tgt tail_tgt) sm_arg.\n\nEnd ADQMATCH.\n\n\n\n\n\n\n\n\n\n\n\n\n\nSection ADQINIT.\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 NOTNIL: pp <> [].\n  Hypothesis SIMPROG: ProgPair.sim pp.\n  Let p_src := (ProgPair.src pp).\n  Let p_tgt := (ProgPair.tgt pp).\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\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  Theorem init_lxsim_lift_forward\n          st_init_src\n          (INITSRC: sem_src.(Smallstep.initial_state) st_init_src):\n      exists idx st_init_tgt sm_init,\n        <<INITTGT: sem_tgt.(Dinitial_state) st_init_tgt>>\n        /\\ (<<SIM: lxsim_lift sk_link_src sk_link_tgt idx st_init_src st_init_tgt sm_init>>)\n        /\\ (<<INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))>>)\n        /\\ (<<INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))>>).\n  Proof.\n    ss. inv INITSRC; ss. clarify. rename INITSK into INITSKSRC. rename INITMEM into INITMEMSRC.\n\n    exploit sim_link_sk; eauto. i; des. fold p_tgt in LOADTGT.\n    assert(WFTGT: forall md, In md p_tgt -> <<WF: Sk.wf md >>).\n    { clear - SIMPROG WF. i. subst_locals. u in *. rewrite in_map_iff in *. des. clarify.\n      rewrite Forall_forall in *. exploit SIMPROG; et. intro SIM. inv SIM.\n      unfold Mod.sk in *. rewrite <- SKTGT in *.\n      eapply SimSymb.wf_preserves_wf; et. rewrite SKSRC in *. eapply WF; et. rewrite in_map_iff. esplits; et.\n    }\n    rewrite <- SKSRC in *. rewrite <- SKTGT in *.\n    exploit init_sim_ge_strong; eauto.\n    { ii. eapply WF; et. unfold p_src. unfold ProgPair.src. rewrite in_map_iff. et. }\n    { ii. eapply WFTGT; et. unfold p_tgt. unfold ProgPair.tgt. rewrite in_map_iff. et. }\n    i; des. clarify. ss. des_ifs.\n\n    set(Args.mk (Genv.symbol_address (Sk.load_skenv (SimSymb.src ss_link)) (prog_main (SimSymb.src ss_link)) Ptrofs.zero)\n                [] sm_init.(SimMem.src)) as args_src in *.\n    set(Args.mk (Genv.symbol_address (Sk.load_skenv (SimSymb.tgt ss_link)) (prog_main (SimSymb.tgt ss_link)) Ptrofs.zero)\n                [] sm_init.(SimMem.tgt)) as args_tgt in *.\n    assert(SIMARGS: SimMem.sim_args args_src args_tgt sm_init).\n    { econs; ss; eauto.\n      - rewrite <- SimMem.sim_val_list_spec. econs; eauto. }\n\n    esplits; eauto.\n    - econs; ss; cycle 1.\n      { ii. eapply initial_state_determ; ss; eauto. }\n      econs; eauto; cycle 1.\n      apply_all_once SimSymb.sim_skenv_func_bisim. des. inv SIMSKENV.\n      exploit FUNCFSIM; eauto.\n      i; des. clarify.\n    - econs; eauto.\n      + ss. folder. des_ifs.\n      + hnf. econs; eauto.\n      + reflexivity.\n  Qed.\n\nEnd ADQINIT.\n\n\n\n\nSection ADQSTEP.\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\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\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  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  Hypothesis (WFKSSRC: forall md (IN: In md (ProgPair.src pp)), <<WF: Sk.wf md >>).\n  Hypothesis (WFKSTGT: forall md (IN: In md (ProgPair.tgt pp)), <<WF: Sk.wf md >>).\n\n  Theorem lxsim_lift_xsim\n          i0 st_src0 st_tgt0 sm0\n          (LXSIM: lxsim_lift sk_link_src sk_link_tgt i0 st_src0 st_tgt0 sm0)\n    :\n      <<XSIM: xsim sem_src sem_tgt ord (sound_state pp) top1 i0 st_src0 st_tgt0>>\n  .\n  Proof.\n    generalize dependent sm0. generalize dependent st_src0. generalize dependent st_tgt0. generalize dependent i0.\n    pcofix CIH. i. pfold. inv LXSIM; ss; cycle 1.\n    { (* init *)\n      folder. des_ifs. right. econs; eauto.\n      i. econs; eauto; cycle 1.\n      { ii. specialize (SAFESRC _ (star_refl _ _ _ _)). des; ss.\n        - inv SAFESRC.\n        - des_ifs. right. inv SAFESRC.\n          exploit find_fptr_owner_fsim; eauto. { eapply SimMem.sim_args_sim_fptr; eauto. } i; des. clarify.\n          inv SIMMS.\n          inv MSFIND. inv FINDTGT.\n          exploit SIM; eauto. i; des.\n          exploit INITPROGRESS; eauto. i; des.\n          esplits; eauto. econs; eauto. econs; eauto.\n      }\n      { i. ss. inv FINALTGT. }\n      i. inv STEPTGT.\n      specialize (SAFESRC _ (star_refl _ _ _ _)). des.\n      { inv SAFESRC. }\n      bar. inv SAFESRC. ss. des_ifs.\n      bar.\n      exploit find_fptr_owner_fsim; eauto. { eapply SimMem.sim_args_sim_fptr; eauto. } i; des. clarify.\n      exploit find_fptr_owner_determ; ss; eauto.\n      { rewrite Heq. apply FINDTGT. }\n      { rewrite Heq. apply MSFIND. }\n      i; des. clarify.\n\n      inv SIMMS.\n      specialize (SIM sm0).\n      inv MSFIND. inv MSFIND0.\n      exploit SIM; eauto. i; des.\n\n      exploit INITBSIM; eauto. i; des.\n      clears st_init0; clear st_init0. esplits; eauto.\n      - left. apply plus_one. econs; eauto. econs; eauto.\n      - right. eapply CIH.\n        instantiate (1:= sm_init). econs; try apply SIM0; eauto.\n        + ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once. et.\n        + etrans; eauto.\n        + ss. inv GE. folder. rewrite Forall_forall in *. eapply SESRC; et.\n        + ss. inv GE. folder. rewrite Forall_forall in *. eapply SETGT; et.\n\n    }\n\n    sguard in SESRC. sguard in SETGT. folder. rewrite LINKSRC in *. rewrite LINKTGT in *.\n    punfold TOP. rr in TOP. ii. hexploit1 TOP; eauto.\n    { ii. exploit SSSRC. { eapply lift_star; eauto. } intro SUST0; des. inv SUST0. des.\n      simpl_depind. clarify. hexploit FORALLSU; eauto. i; des.\n      specialize (H (sound_states_local si)). esplits; eauto. eapply H; eauto. }\n    inv TOP.\n\n    - (* fstep *)\n      left. exploit SU0.\n      { ss. }\n      i; des. clear SU0. right. econs; ss; eauto.\n      + rename H into FSTEP. inv FSTEP.\n        * econs 1; cycle 1.\n          { ii. des. inv FINALSRC; ss. exfalso. eapply SAFESRC0. u. eauto. }\n          ii. ss. rewrite LINKSRC in *. des. inv STEPSRC; ss; ModSem.tac; swap 2 3.\n          { exfalso. eapply SAFESRC; eauto. }\n          { exfalso. eapply SAFESRC0. u. eauto. }\n          exploit STEP; eauto. i; des_safe.\n          exists i1, (State ((Frame.mk ms_tgt st_tgt1) :: tail_tgt)). esplits; eauto.\n          { assert(T: DPlus ms_tgt lst_tgt tr st_tgt1 \\/ (lst_tgt = st_tgt1 /\\ tr = E0 /\\ ord i1 i0)).\n            { des; et. inv STAR; et. left. econs; et. }\n            clear H. des.\n            - left. split; cycle 1.\n              { eapply lift_receptive_at; eauto. unsguard SESRC. s. des_ifs. }\n              eapply lift_dplus; eauto.\n              { unsguard SETGT. ss. des_ifs. }\n            - right. esplits; eauto. clarify.\n          }\n          pclearbot. right. eapply CIH with (sm0 := sm1); eauto.\n          econs; eauto.\n          { ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once; eauto. }\n          { etransitivity; eauto. }\n        * des. pclearbot. econs 2.\n          { esplits; eauto. eapply lift_dplus; eauto. { unsguard SETGT. ss. des_ifs. } }\n          right. eapply CIH; eauto. instantiate (1:=sm1). econs; eauto.\n          { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto.\n            eapply rtc_once; eauto. }\n          { etrans; eauto. }\n\n    - (* bstep *)\n      right. ss. hexploit1 SU0; ss.\n      assert(SAFESTEP: safe sem_src (State ({| Frame.ms := ms_src; Frame.st := lst_src |} :: tail_src))\n                       -> safe_modsem ms_src lst_src).\n      { eapply safe_implies_safe_modsem; eauto. }\n      econs; ss; eauto.\n      i. exploit SU0; eauto. intro T. clear SU0. inv T.\n      + econs 1; eauto; revgoals.\n        { ii. des. clear - FINALTGT PROGRESS. inv FINALTGT. ss. ModSem.tac. }\n        { ii. right. des. esplits; eauto. eapply lift_step; eauto. }\n        ii. inv STEPTGT; ModSem.tac. ss. exploit STEP; eauto. i; des_safe.\n        exists i1, (State ((Frame.mk ms_src st_src1) :: tail_src)).\n        esplits; eauto.\n        { des.\n          - left. eapply lift_plus; eauto.\n          - right. esplits; eauto. eapply lift_star; eauto.\n        }\n        pclearbot. right. eapply CIH with (sm0 := sm1); eauto.\n        econs; eauto.\n        { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once; eauto. }\n        etransitivity; eauto.\n      + des. pclearbot. econs 2.\n        { esplits; eauto. eapply lift_star; eauto. }\n        right. eapply CIH; eauto.\n        instantiate (1:=sm1). econs; eauto.\n        { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto. eapply rtc_once; eauto. }\n        { etrans; eauto. }\n\n    - (* call *)\n      left. right. econs; eauto. econs; eauto; cycle 1.\n      { ii. inv FINALSRC. ss. ModSem.tac. }\n      i. inv STEPSRC; ss; ModSem.tac. des_ifs. hexploit1 SU0.\n      { ss. }\n      rename SU0 into CALLFSIM.\n\n      exploit CALLFSIM; eauto. i; des. esplits; eauto.\n      + left. split; cycle 1.\n        { eapply lift_receptive_at. { unsguard SESRC. ss. des_ifs. } eapply at_external_receptive_at; et. }\n        apply plus_one. econs; ss; eauto.\n        { eapply lift_determinate_at; et. { unsguard SETGT. ss. des_ifs. } eapply at_external_determinate_at; et. }\n        des_ifs. econs 1; eauto.\n      + right. eapply CIH; eauto.\n        { instantiate (1:= sm_arg). econs 2; eauto.\n          * ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. econs 2; et.\n          * instantiate (1:= sm_arg). econs; [eassumption|..]; revgoals; ss.\n            { ii. exploit K; eauto. i; des_safe. pclearbot. esplits; try apply LXSIM; eauto. }\n            { reflexivity. }\n            { et. }\n            { refl. }\n            { et. }\n            { ss. folder. des_ifs. }\n            { eauto. }\n          * reflexivity.\n        }\n\n\n    - (* return *)\n      left. right. econs; eauto.\n      econs; eauto; cycle 1.\n      { ii. ss. inv FINALSRC0. ss. determ_tac ModSem.final_frame_dtm. clear_tac.\n        inv STACK.\n        econs; ss; eauto.\n        - econs; ss; eauto.\n          inv SIMRETV; ss.\n          eapply SimMem.sim_val_int; et.\n        - i. inv FINAL0; inv FINAL1; ss.\n          exploit ModSem.final_frame_dtm; [apply FINAL|apply FINAL0|..]. i; clarify. congruence.\n        - ii. des_ifs. inv H; ss; ModSem.tac.\n      }\n      i. ss. des_ifs. inv STEPSRC; ModSem.tac. ss.\n      inv STACK; ss. folder. sguard in SESRC0. sguard in SETGT0. des_ifs.\n      determ_tac ModSem.final_frame_dtm. clear_tac.\n      exploit K; try apply SIMRETV; eauto.\n      { etransitivity; eauto. etrans; eauto. }\n      { exploit SSSRC. { eapply star_refl. } intro T; des. inv T. des. simpl_depind. clarify.\n        inv TL. simpl_depind. clarify. des.\n        exploit FORALLSU0; eauto. i; des. esplits; eauto. eapply HD; eauto.\n      }\n      i; des. esplits; eauto.\n      + left. split; cycle 1.\n        { eapply lift_receptive_at. { unsguard SESRC. ss. des_ifs. } eapply final_frame_receptive_at; et. }\n        apply plus_one. econs; eauto.\n        { eapply lift_determinate_at. { unsguard SETGT. ss. des_ifs. } eapply final_frame_determinate_at; et. }\n        econs 4; ss; eauto.\n      + right. eapply CIH; eauto.\n        instantiate (1:= sm_after). econs; ss; cycle 3; eauto.\n        { folder. des_ifs. eapply mfuture_preserves_sim_ge; et. econs 2; et. }\n        { etrans; eauto. }\n  Qed.\n\nEnd ADQSTEP.\n\n\n\nRequire Import BehaviorsC SemProps.\n\nSection ADQ.\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  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\n\n  Let skenv_link_src := (Sk.load_skenv sk_link_src).\n  Let skenv_link_tgt := (Sk.load_skenv sk_link_tgt).\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  Hypothesis (WFSKSRC: forall md (IN: In md (ProgPair.src pp)), <<WF: Sk.wf md >>).\n  Hypothesis (WFSKTGT: forall md (IN: In md (ProgPair.tgt pp)), <<WF: Sk.wf md >>).\n\n  Theorem adequacy_local_aux: mixed_simulation sem_src sem_tgt.\n  Proof.\n    subst_locals. econstructor 1 with (order := ord); eauto. generalize wf_ord; intro WF.\n    econstructor; eauto.\n    - eapply preservation; eauto.\n    - eapply preservation_top.\n    - econs 1; ss; eauto. ii.\n      exploit init_lxsim_lift_forward; eauto. { destruct pp; ss. } i; des.\n      assert(WFTGT: forall md, In md (ProgPair.tgt pp) -> <<WF: Sk.wf md >>).\n      { inv INITTGT. inv INIT. ss. }\n      hexploit lxsim_lift_xsim; eauto.\n    - ss. i; des. inv SAFESRC.\n      exploit sim_link_sk; eauto. i; des. des_ifs.\n      exploit SimSymb.wf_load_sim_skenv; eauto. i; des. clarify.\n      symmetry. exploit SimSymb.sim_skenv_public_symbols; et. intro T. s. rewrite T. ss.\n  Unshelve.\n    all: ss.\n  Qed.\n\nEnd ADQ.\n\n\n\nSection BEH.\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  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\n\n  Theorem adequacy_local: BehaviorsC.improves sem_src sem_tgt.\n  Proof.\n    eapply improves_free_theorem; i.\n    eapply bsim_improves; eauto. eapply mixed_to_backward_simulation; eauto.\n\n    des. inv INIT. ss. exploit sim_link_sk; eauto. i; des. clarify.\n    exploit init_lxsim_lift_forward; eauto. { destruct pp; ss. } { econs; eauto. } i; des.\n    exploit SimSymb.wf_load_sim_skenv; eauto. i; des. clarify.\n    eapply adequacy_local_aux; ss; eauto.\n    { rewrite Forall_forall in *. ss. }\n    { inv INITTGT. inv INIT. ss. }\n  Qed.\n\nEnd BEH.\n\n\n\nProgram Definition mkPR (MR: SimMem.class) (SR: SimSymb.class MR) (MP: Sound.class)\n  : program_relation.t := program_relation.mk\n                            (fun (p_src p_tgt: program) =>\n                               forall (WF: forall x (IN: In x p_src), Sk.wf x),\n                               exists pp,\n                                 (<<SIMS: @ProgPair.sim MR SR MP pp>>)\n                                 /\\ (<<SRCS: (ProgPair.src pp) = p_src>>)\n                                 /\\ (<<TGTS: (ProgPair.tgt pp) = p_tgt>>)) _ _ _.\nNext Obligation.\n(* horizontal composition *)\n  exploit REL0; eauto. { i. eapply WF. rewrite in_app_iff. eauto. } intro T0; des.\n  exploit REL1; eauto. { i. eapply WF. rewrite in_app_iff. eauto. } intro T1; des.\n  clarify. unfold ProgPair.sim in *. rewrite Forall_forall in *. eexists (_ ++ _). esplits; eauto.\n  - rewrite Forall_forall in *. i. rewrite in_app_iff in *. des; [apply SIMS|apply SIMS0]; eauto.\n  - unfold ProgPair.src. rewrite map_app. ss.\n  - unfold ProgPair.tgt. rewrite map_app. ss.\nQed.\nNext Obligation.\n(* adequacy *)\n  destruct (classic (forall x (IN: In x p_src), Sk.wf x)) as [WF|NWF]; cycle 1.\n  { eapply sk_nwf_improves; auto. }\n  specialize (REL WF). des. clarify.\n  eapply (@adequacy_local MR SR MP). auto.\nQed.\nNext Obligation. exists []. splits; ss. Qed.\nArguments mkPR: clear implicits.\n\n\nDefinition relate_single (MR: SimMem.class) (SR: SimSymb.class MR) (MP: Sound.class)\n           (p_src p_tgt: Mod.t) : Prop :=\n  forall (WF: Sk.wf p_src),\n  exists mp,\n    (<<SIM: @ModPair.sim MR SR MP mp>>)\n    /\\ (<<SRC: mp.(ModPair.src) = p_src>>)\n    /\\ (<<TGT: mp.(ModPair.tgt) = p_tgt>>).\nArguments relate_single : clear implicits.\n\nLemma relate_single_program MR SR MP p_src p_tgt\n      (REL: relate_single MR SR MP p_src p_tgt):\n    (mkPR MR SR MP) [p_src] [p_tgt].\nProof.\n  unfold relate_single. ss. i.\n  exploit REL; [ss; eauto|]. i. des. clarify.\n  exists [mp]. esplits; ss; eauto.\nQed.\nArguments relate_single_program : clear implicits.\n\nLemma relate_each_program MR SR MP\n      (p_src p_tgt: program)\n      (REL: Forall2 (relate_single MR SR MP) p_src p_tgt):\n    (mkPR MR SR MP) p_src p_tgt.\nProof.\n  revert p_tgt REL. induction p_src; ss; i.\n  - inv REL. exists []; splits; ss.\n  - inv REL. exploit IHp_src; eauto. i. des.\n    exploit H1; eauto. i. des. clarify.\n    exists (mp :: pp); splits; ss. econs; eauto.\nQed.\nArguments relate_each_program : clear implicits.\n\nLemma relate_single_rtc_rusc (R: program_relation.t -> Prop) MR SR MP\n      (p_src p_tgt: Mod.t)\n      (REL: rtc (relate_single MR SR MP) p_src p_tgt)\n      (RELIN: R (mkPR MR SR MP)):\n    rusc R [p_src] [p_tgt].\nProof.\n  induction REL; try refl.\n  - etrans; eauto. eapply rusc_incl; eauto. eapply relate_single_program; eauto.\nQed.\nArguments relate_single_program : clear implicits.\n\nLemma relate_single_rusc (R: program_relation.t -> Prop) MR SR MP\n      (p_src p_tgt: Mod.t)\n      (REL: (relate_single MR SR MP) p_src p_tgt)\n      (RELIN: R (mkPR MR SR MP)):\n    rusc R [p_src] [p_tgt].\nProof.\n  eapply relate_single_rtc_rusc; eauto. eapply rtc_once. eauto.\nQed.\nArguments relate_single_program : clear implicits.\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/AdequacyLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.16566081041459266}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.common.AST.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Smallstep.\nRequire Import VST.ccc26x86.Op.\nRequire Import VST.ccc26x86.Locations.\nRequire Import VST.ccc26x86.Conventions.\nRequire VST.ccc26x86.Stacklayout.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.semantics_lemmas.\nRequire Import VST.sepcomp.val_casted.\nRequire Import VST.ccc26x86.BuiltinEffects.\nRequire Import VST.sepcomp.structured_injections.\nRequire Import VST.sepcomp.effect_properties.\nRequire Import VST.sepcomp.reach.\nRequire Import VST.msl.Axioms.\n\nDefinition load_stack (m: mem) (sp: val) (ty: typ) (ofs: int) :=\n  Mem.loadv (chunk_of_type ty) m (Val.add sp (Vint ofs)).\n\nDefinition store_stack (m: mem) (sp: val) (ty: typ) (ofs: int) (v: val) :=\n  Mem.storev (chunk_of_type ty) m (Val.add sp (Vint ofs)) v.\n\n(*NOTE [store_args_simple] is used to model program loading of\n  initial arguments.  Cf. NOTE [loader] below. *)\n\nFixpoint store_args0 (m: mem) (sp: val) (ofs: Z) (args: list val) (tys: list typ)\n         : option mem :=\n  match args,tys with\n    | nil,nil => Some m\n    | a::args',ty::tys' =>\n      match store_stack m sp ty (Int.repr (Stacklayout.fe_ofs_arg + 4*ofs)) a with\n        | None => None\n        | Some m' => store_args0 m' sp (ofs+typesize ty) args' tys'\n      end\n    | _,_ => None\n  end.\n\n(* [store_args_rec] is more complicated, but more precise than,\n   [store_args (encode_longs args) (encode_typs tys)]. Still, it's not totally\n   satisfactory that argument encoding code is duplicated like this. *)\n\nFixpoint store_args_rec m sp ofs args tys : option mem :=\n  let vsp := Vptr sp Int.zero in\n  match tys, args with\n    | nil, nil => Some m\n    | ty'::tys',a'::args' =>\n      match ty', a' with\n        | Tlong, Vlong n =>\n          match store_stack m vsp Tint (Int.repr (Stacklayout.fe_ofs_arg + 4*(ofs+1)))\n                            (Vint (Int64.hiword n)) with\n            | None => None\n            | Some m' =>\n              match store_stack m' vsp Tint (Int.repr (Stacklayout.fe_ofs_arg + 4*ofs))\n                                (Vint (Int64.loword n)) with\n                | None => None\n                | Some m'' => store_args_rec m'' sp (ofs+2) args' tys'\n              end\n          end\n        | Tlong, _ => None\n        | _,_ =>\n          match store_stack m vsp ty' (Int.repr (Stacklayout.fe_ofs_arg + 4*ofs)) a' with\n            | None => None\n            | Some m' => store_args_rec m' sp (ofs+typesize ty') args' tys'\n          end\n      end\n    | _, _ => None\n  end.\n\nLemma store_stack_fwd m sp t i a m' :\n  store_stack m sp t i a = Some m' ->\n  mem_forward m m'.\nProof.\nunfold store_stack, Mem.storev.\ndestruct (Val.add sp (Vint i)); try solve[inversion 1].\napply store_forward.\nQed.\n\nLemma store_args_fwd sp ofs args tys m m' :\n  store_args_rec m sp ofs args tys = Some m' ->\n  mem_forward m m'.\nProof.\nrevert args ofs m; induction tys.\nsimpl. destruct args. intros ofs. inversion 1; subst.\nsolve[apply mem_forward_refl].\nintros ofs m. simpl. inversion 1.\ndestruct args; try solve[inversion 1].\ndestruct a; simpl; intros ofs m.\n- case_eq (store_stack m (Vptr sp Int.zero) Tint\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. apply store_stack_fwd in EQ. intros H.\neapply mem_forward_trans; eauto. intros; congruence.\n- case_eq (store_stack m (Vptr sp Int.zero) Tfloat\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. apply store_stack_fwd in EQ. intros H.\neapply mem_forward_trans; eauto. intros; congruence.\n- destruct v; try solve[congruence].\ncase_eq (store_stack m (Vptr sp Int.zero) Tint\n           (Int.repr match ofs+1 with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                      | Z.neg y' => Z.neg y'~0~0 end)\n        (Vint (Int64.hiword i))).\nintros m0 EQ. apply store_stack_fwd in EQ.\ncase_eq (store_stack m0 (Vptr sp Int.zero) Tint\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end)\n        (Vint (Int64.loword i))). intros m1 H H2.\neapply mem_forward_trans; eauto.\neapply mem_forward_trans; eauto.\neapply store_stack_fwd; eauto. intros; congruence. intros; congruence.\n- case_eq (store_stack m (Vptr sp Int.zero) Tsingle\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. apply store_stack_fwd in EQ. intros H.\neapply mem_forward_trans; eauto. intros; congruence.\n- case_eq (store_stack m (Vptr sp Int.zero) Tany32\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. apply store_stack_fwd in EQ. intros H.\neapply mem_forward_trans; eauto. intros; congruence.\n- case_eq (store_stack m (Vptr sp Int.zero) Tany64\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. apply store_stack_fwd in EQ. intros H.\neapply mem_forward_trans; eauto. intros; congruence.\n\nQed.\n\nLemma store_stack_unch_on stk z t i a m m' :\n  store_stack m (Vptr stk z) t i a = Some m' ->\n  Mem.unchanged_on (fun b ofs => b<>stk) m m'.\nProof.\nunfold store_stack, Mem.storev.\ncase_eq (Val.add (Vptr stk z) (Vint i)); try solve[inversion 1].\nintros b i0 H H2. eapply Mem.store_unchanged_on in H2; eauto.\nintros i2 H3 H4. inv H. apply H4; auto.\nQed.\n\nLemma store_args_unch_on stk ofs args tys m m' :\n  store_args_rec m stk ofs args tys = Some m' ->\n  Mem.unchanged_on (fun b ofs => b<>stk) m m'.\nProof.\nrevert args ofs m; induction tys.\nsimpl. destruct args. intros ofs. inversion 1; subst.\n  solve[apply Mem.unchanged_on_refl].\nintros ofs m. simpl. inversion 1.\ndestruct args; try solve[inversion 1].\ndestruct a; simpl; intros ofs m.\n- case_eq (store_stack m (Vptr stk Int.zero) Tint\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\nsolve[eapply store_stack_fwd; eauto]. intros; congruence.\n- case_eq (store_stack m (Vptr stk Int.zero) Tfloat\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\nsolve[eapply store_stack_fwd; eauto]. intros; congruence.\n- destruct v; try solve[inversion 1].\ncase_eq (store_stack m (Vptr stk Int.zero) Tint\n           (Int.repr match ofs+1 with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                      | Z.neg y' => Z.neg y'~0~0 end)\n        (Vint (Int64.hiword i))).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ.\ncase_eq (store_stack m0 (Vptr stk Int.zero) Tint\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end)\n        (Vint (Int64.loword i))).\nintros m1 EQ2. generalize EQ2 as EQ2'. intro. apply store_stack_unch_on in EQ2. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\neapply unchanged_on_trans with (m2 := m1); eauto.\neapply store_stack_fwd; eauto. eapply store_stack_fwd; eauto.\nintros; congruence. intros; congruence.\n- case_eq (store_stack m (Vptr stk Int.zero) Tsingle\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\nsolve[eapply store_stack_fwd; eauto]. intros; congruence.\n- case_eq (store_stack m (Vptr stk Int.zero) Tany32\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\nsolve[eapply store_stack_fwd; eauto]. intros; congruence.\n- case_eq (store_stack m (Vptr stk Int.zero) Tany64\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\nintros m0 EQ. generalize EQ as EQ'. intro. apply store_stack_unch_on in EQ. intros H.\neapply unchanged_on_trans with (m2 := m0); eauto.\nsolve[eapply store_stack_fwd; eauto]. intros; congruence.\nQed.\n\nFixpoint args_len_rec args tys : option Z :=\n  match tys, args with\n    | nil, nil => Some 0\n    | ty'::tys',a'::args' =>\n      match ty', a' with\n        | Tlong, Vlong n =>\n          match args_len_rec args' tys' with\n            | None => None\n            | Some z => Some (2+z)\n          end\n        | Tlong, _ => None\n        | Tfloat,_ =>\n          match args_len_rec args' tys' with\n            | None => None\n            | Some z => Some (2+z)\n          end\n        | _,_ =>\n          match args_len_rec args' tys' with\n            | None => None\n            | Some z => Some (1+z)\n          end\n      end\n    | _, _ => None\n  end.\n\nLemma args_len_rec_succeeds args tys\n      (VALSDEF: val_casted.vals_defined args=true)\n      (HASTY: Val.has_type_list args tys) :\n  exists z, args_len_rec args tys = Some z.\nProof.\nrewrite val_casted.val_has_type_list_func_charact in HASTY.\nrevert args VALSDEF HASTY; induction tys. destruct args; auto.\nsimpl. exists 0; auto. simpl. intros; congruence.\ndestruct args. simpl. intros; congruence.\nunfold val_has_type_list_func; rewrite andb_true_iff. intros VD [H H2].\nfold val_has_type_list_func in H2.\napply IHtys in H2. destruct H2 as [z H2]. simpl.\ndestruct a; try solve [rewrite H2; eexists; eauto].\ndestruct v; simpl in H; try solve [simpl in VD; congruence].\nrewrite H2. eexists; eauto.\nsimpl in VD. destruct v; auto. congruence.\nQed.\n\nLemma range_perm_shift m b lo sz n k p :\n  0 <= lo -> 0 <= sz -> 0 <= n ->\n  Mem.range_perm m b lo (lo+sz+n) k p ->\n  Mem.range_perm m b (lo+n) (lo+sz+n) k p.\nProof. intros A B C RNG ofs [H H2]; apply RNG; omega. Qed.\n\nInductive only_stores (sp: block) : list val -> mem -> mem -> Type :=\n| only_stores_nil m : only_stores sp nil m m\n| only_stores_cons m ch ofs v m'' m' l :\n    Mem.store ch m sp ofs v = Some m'' ->\n    only_stores sp l m'' m' ->\n    only_stores sp (v::l) m m'.\n\nLemma only_stores_fwd sp m m' l :\n  only_stores sp l m m' -> mem_forward m m'.\nProof.\ninduction 1. apply mem_forward_refl.\neapply mem_forward_trans. eapply store_forward; eauto. apply IHX.\nQed.\n\nLemma store_args_rec_only_stores m sp args tys z m' :\n  store_args_rec m sp z args tys = Some m' ->\n  only_stores sp (encode_longs tys args) m m'.\nProof.\nrevert args z m. induction tys. destruct args; simpl.\nintros ? ?; inversion 1. constructor.\nintros ? ? ?; congruence.\ndestruct args; simpl. intros; congruence. intros z m.\ngeneralize\n (Int.repr match z with\n             | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n             | Z.neg y' => Z.neg y'~0~0 end) as z'.\ngeneralize\n (Int.repr match z+1 with\n             | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n             | Z.neg y' => Z.neg y'~0~0 end) as z''.\nintros z'' z'. destruct a.\n- case_eq (store_stack m (Vptr sp Int.zero) Tint z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H.\nsolve[eapply only_stores_cons; eauto].\n- case_eq (store_stack m (Vptr sp Int.zero) Tfloat z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H.\nsolve[eapply only_stores_cons; eauto].\n- destruct v; try solve[intros; congruence].\ncase_eq (store_stack m (Vptr sp Int.zero) Tint z'' (Vint (Int64.hiword i)));\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE.\ncase_eq (Mem.store Mint32 m0 sp (Int.unsigned (Int.add Int.zero z'))\n                   (Vint (Int64.loword i)));\n  try solve[intros; congruence].\nintros m1 STORE' H.\neapply only_stores_cons; eauto.\nsolve[eapply only_stores_cons; eauto].\n- case_eq (store_stack m (Vptr sp Int.zero) Tsingle z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H.\nsolve[eapply only_stores_cons; eauto].\n- case_eq (store_stack m (Vptr sp Int.zero) Tany32 z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H.\nsolve[eapply only_stores_cons; eauto].\n- case_eq (store_stack m (Vptr sp Int.zero) Tany64 z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H.\nsolve[eapply only_stores_cons; eauto].\nQed.\n\nLemma args_len_recD: forall v args tp tys sz,\n     args_len_rec (v :: args) (tp :: tys) = Some sz ->\n     exists z1 z2, sz = z1+z2 /\\ args_len_rec args tys = Some z2 /\\\n        match tp with Tlong => z1=2 | Tfloat => z1=2 | _ => z1=1 end.\nProof.\nsimpl. intros.\ndestruct tp; simpl in *.\ndestruct (args_len_rec args tys); inv H.\n  exists 1, z; repeat split; trivial.\ndestruct (args_len_rec args tys); inv H.\n  exists 2, z; repeat split; trivial.\ndestruct v; inv H.\n  destruct (args_len_rec args tys); inv H1.\n  exists 2, z; repeat split; trivial.\ndestruct (args_len_rec args tys); inv H.\n  exists 1, z; repeat split; trivial.\ndestruct (args_len_rec args tys); inv H.\n  exists 1, z; repeat split; trivial.\ndestruct (args_len_rec args tys); inv H.\n  exists 1, z; repeat split; trivial.\nQed.\n\nLemma args_len_rec_nonneg: forall tys args sz,\n     args_len_rec args tys = Some sz -> 0 <= sz.\nProof.\nintros tys; induction tys; intros.\n  destruct args; inv H. omega.\ndestruct args; inv H.\n  destruct a; specialize (IHtys args).\n+ destruct (args_len_rec args tys); inv H1.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\n+ destruct (args_len_rec args tys); inv H1.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\n+ destruct v; inv H1.\n    destruct (args_len_rec args tys); inv H0.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\n+ destruct (args_len_rec args tys); inv H1.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\n+ destruct (args_len_rec args tys); inv H1.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\n+ destruct (args_len_rec args tys); inv H1.\n    specialize (IHtys _ (eq_refl _)).\n    destruct z. omega. destruct p; xomega.\n    xomega.\nQed.\n\nLemma args_len_rec_pos: forall v args tp tys sz,\n     args_len_rec (v :: args) (tp :: tys) = Some sz -> 0 < sz.\nProof. intros.\napply args_len_recD in H. destruct H as [? [? [? [? ?]]]]; subst.\napply args_len_rec_nonneg in H0.\ndestruct tp; omega.\nQed.\n\nDefinition store_arg m sp ofs ty' a' :=\n      match ty', a' with\n        | Tlong, Vlong n =>\n          match store_stack m (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*(ofs+1)))\n                            (Vint (Int64.hiword n)) with\n            | None => None\n            | Some m' =>\n                match  store_stack m' (Vptr sp Int.zero) Tint\n                      (Int.repr (Stacklayout.fe_ofs_arg + 4*ofs))\n                                (Vint (Int64.loword n)) with\n                | None => None\n                | Some m'' => Some (m'',ofs+2)\n                end\n          end\n        | Tlong, _ => None\n        | _,_ =>\n          match store_stack m (Vptr sp Int.zero) ty'\n                 (Int.repr (Stacklayout.fe_ofs_arg + 4*ofs)) a' with\n            | None => None\n            | Some m' => Some (m', ofs+typesize ty')\n          end\n      end.\n\nLemma store_argSZ m sp z ty v m' ofs:\n      store_arg m sp z ty v = Some(m',ofs) -> ofs = z + typesize ty.\nProof. destruct ty; simpl; intros.\n+ remember (store_stack m (Vptr sp Int.zero) Tint\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs in H. clear Heqs.\n    destruct s; inv H. trivial.\n+ remember (store_stack m (Vptr sp Int.zero) Tfloat\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs in H. clear Heqs.\n    destruct s; inv H. trivial.\n+ destruct v; inv H.\n  - remember (store_stack m (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*(z+1)))\n                            (Vint (Int64.hiword i))) as s1.\n    unfold Stacklayout.fe_ofs_arg in Heqs1. simpl in Heqs1.\n    rewrite <- Heqs1 in *. clear Heqs1.\n    destruct s1; inv H1.\n    remember (store_stack m0 (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*z))\n                            (Vint (Int64.loword i))) as s2.\n    unfold Stacklayout.fe_ofs_arg in Heqs2. simpl in Heqs2.\n    rewrite <- Heqs2 in *. clear Heqs2.\n    destruct s2; inv H0. trivial.\n+ remember (store_stack m (Vptr sp Int.zero) Tsingle\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs in *. clear Heqs.\n    destruct s; inv H. trivial.\n+ remember (store_stack m (Vptr sp Int.zero) Tany32\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs in *. clear Heqs.\n    destruct s; inv H. trivial.\n+ remember (store_stack m (Vptr sp Int.zero) Tany64\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs in *. clear Heqs.\n    destruct s; inv H. trivial.\nQed.\n\nLemma store_args_cons m sp z v args ty tys m1 z1:\n  store_arg m sp z ty v = Some(m1, z1) ->\n  (exists m', store_args_rec m1 sp z1 args tys = Some m') ->\n  exists m', store_args_rec m sp z (v :: args) (ty :: tys) = Some m'.\nProof. intros.\nsimpl. unfold store_arg in H.\ndestruct ty.\n+ remember (store_stack m (Vptr sp Int.zero) Tint\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs. clear Heqs.\n    destruct s; inv H. simpl. assumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tfloat\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs. clear Heqs.\n    destruct s; inv H. simpl. assumption.\n+ destruct v; inv H.\n  - remember (store_stack m (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*(z+1)))\n                            (Vint (Int64.hiword i))) as s1.\n    unfold Stacklayout.fe_ofs_arg in Heqs1. simpl in Heqs1.\n    rewrite <- Heqs1 in *. clear Heqs1.\n    destruct s1; inv H2.\n    remember (store_stack m0 (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*z))\n                            (Vint (Int64.loword i))) as s2.\n    unfold Stacklayout.fe_ofs_arg in Heqs2. simpl in Heqs2.\n    rewrite <- Heqs2 in *. clear Heqs2.\n    destruct s2; inv H1. assumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tsingle\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs. clear Heqs.\n    destruct s; inv H. simpl. assumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tany32\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs. clear Heqs.\n    destruct s; inv H. simpl. assumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tany64\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    unfold Stacklayout.fe_ofs_arg in Heqs. simpl in Heqs.\n    rewrite <- Heqs. clear Heqs.\n    destruct s; inv H. simpl. assumption.\nQed.\n\nLemma store_arg_perm1: forall m sp z ty v mm zz\n      (STA: store_arg m sp z ty v = Some (mm, zz)),\n       forall (b' : block) (ofs' : Z) (k : perm_kind) (p : permission),\n       Mem.perm m b' ofs' k p -> Mem.perm mm b' ofs' k p.\nProof. intros.\nsimpl. unfold store_arg in STA.\ndestruct ty.\n+ remember (store_stack m (Vptr sp Int.zero) Tint\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    destruct s; inv STA. apply eq_sym in Heqs.\n    unfold store_stack in Heqs; simpl in Heqs.\n    eapply Mem.perm_store_1; eassumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tfloat\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    destruct s; inv STA. apply eq_sym in Heqs.\n    unfold store_stack in Heqs; simpl in Heqs.\n    eapply Mem.perm_store_1; eassumption.\n+ destruct v; inv STA.\n  - remember (store_stack m (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*(z+1)))\n                            (Vint (Int64.hiword i))) as s1.\n    unfold Stacklayout.fe_ofs_arg in Heqs1. simpl in Heqs1.\n    rewrite <- Heqs1 in *. apply eq_sym in Heqs1.\n    destruct s1; inv H1.\n    remember (store_stack m0 (Vptr sp Int.zero) Tint\n                  (Int.repr (Stacklayout.fe_ofs_arg + 4*z))\n                            (Vint (Int64.loword i))) as s2.\n    unfold Stacklayout.fe_ofs_arg in Heqs2. simpl in Heqs2.\n    rewrite <- Heqs2 in *. apply eq_sym in Heqs2.\n    destruct s2; inv H2.\n    unfold store_stack in *; simpl in *.\n    eapply Mem.perm_store_1; try eassumption.\n    eapply Mem.perm_store_1; eassumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tsingle\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    destruct s; inv STA. apply eq_sym in Heqs.\n    unfold store_stack in Heqs; simpl in Heqs.\n    eapply Mem.perm_store_1; eassumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tany32\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    destruct s; inv STA. apply eq_sym in Heqs.\n    unfold store_stack in Heqs; simpl in Heqs.\n    eapply Mem.perm_store_1; eassumption.\n+ remember (store_stack m (Vptr sp Int.zero) Tany64\n          (Int.repr (Stacklayout.fe_ofs_arg + 4 * z)) v) as s.\n    destruct s; inv STA. apply eq_sym in Heqs.\n    unfold store_stack in Heqs; simpl in Heqs.\n    eapply Mem.perm_store_1; eassumption.\nQed.\n\nLemma store_args_rec_succeeds_aux sp:\n  forall tys args\n      (VALSDEF: val_casted.vals_defined args=true)\n      (HASTY: Val.has_type_list args tys) sz\n      (ALR: args_len_rec args tys = Some sz)\n      z (POS: 0 <= z)\n      (REP: 4*(z+sz) < Int.modulus) m\n      (RP: Mem.range_perm m sp (4*z) (4*z + 4*sz) Cur Writable),\n  exists m', store_args_rec m sp z args tys = Some m'.\nProof.\nintros tys. induction tys.\n+ intros.\n  destruct args; simpl in *; inv ALR. rewrite Zplus_0_r in *.\n     eexists; reflexivity.\n+ destruct args. intros. inv ALR.\n  intros. destruct HASTY.\n  assert (ArgsDef: vals_defined args = true).\n    destruct v; try inv VALSDEF; trivial.\n apply args_len_recD in ALR.\n destruct ALR as [sizeA [sz' [SZ [AL SzA]]]].\n assert (sizeA = typesize a).\n { clear - SzA H. destruct a; try solve[trivial]. simpl. admit. (*TODO (Gordon?): In CompCert 2.6, this assert is not true any longer*) }\n clear SzA.\n subst sz sizeA.\n assert (STARG: exists mm zz, store_arg m sp z a v = Some(mm,zz)).\n { clear IHtys H0.\n   destruct (typ_eq a Tlong). subst a.\n   { simpl. destruct v; try solve[simpl in VALSDEF; congruence | inv H].\n     assert (H1: sz' >= 0) by (apply args_len_rec_nonneg in AL; omega).\n     destruct (Mem.valid_access_store m (chunk_of_type Tint) sp (4*(z+1)) (Vint (Int64.hiword i)))\n       as [mm ST].\n      split. red; intros. eapply RP; clear RP.\n        split. omega.\n        assert (1 + size_chunk (chunk_of_type Tint) <= 4 * (typesize Tlong + sz')).\n         { clear - AL. apply args_len_rec_nonneg in AL.\n           unfold typesize. simpl size_chunk. omega. }\n        destruct H0. simpl size_chunk in H3. simpl typesize. clear - H1 H3. omega.\n        clear - POS. rewrite Zmult_comm. solve[simpl align_chunk; eapply Zdivide_intro; eauto].\n     destruct (Mem.valid_access_store mm (chunk_of_type Tint) sp (4*z) (Vint (Int64.loword i)))\n       as [mm' ST'].\n      split. red; intros.\n        eapply Mem.perm_store_1; eauto.\n        eapply RP; eauto. clear RP. split. omega.\n        assert (size_chunk (chunk_of_type Tint) <= 4 * (typesize Tlong + sz')).\n         { clear - AL. apply args_len_rec_nonneg in AL.\n           unfold typesize. simpl size_chunk. omega. }\n        destruct H0. simpl size_chunk in H3. simpl typesize. clear - H1 H3. omega.\n        clear - POS. rewrite Zmult_comm. solve[simpl align_chunk; eapply Zdivide_intro; eauto].\n     unfold store_stack. simpl. simpl in ST, ST'.\n     assert (A: 0 <= 4*(z+1) <= Int.max_unsigned).\n     { split. omega. simpl typesize in REP.\n       assert (1 + sz' >= 0) by (apply args_len_rec_nonneg in AL; omega).\n       unfold Int.max_unsigned. omega. }\n     assert (B: 0 <= 4*z <= Int.max_unsigned) by omega.\n     rewrite !Int.add_zero_l, !Int.unsigned_repr, ST, ST'.\n       exists mm', (z+2); trivial. solve[apply B]. solve[apply A]. }\n   destruct (Mem.valid_access_store m (chunk_of_type a) sp (4*z) v) as [mm ST].\n    split. red; intros. eapply RP; clear RP.\n        split. omega.\n        assert (size_chunk (chunk_of_type a) <= 4 * (typesize a + sz')).\n         { clear - AL. apply args_len_rec_nonneg in AL.\n            unfold typesize. destruct a; simpl in *.\n               destruct sz'; xomega. destruct sz'. xomega.\n               destruct p; xomega. xomega.\n               destruct sz'; try xomega. destruct p; xomega.\n               destruct sz'; try xomega.\n               destruct sz'; try xomega.\n               destruct sz'; try xomega.\n               destruct p; try xomega.  }\n         remember (size_chunk (chunk_of_type a)) as p1.\n         remember (typesize a + sz') as p2. clear - H0 H1. omega.\n      clear - POS n. rewrite Zmult_comm.\n      destruct a; simpl align_chunk; eapply Zdivide_intro; eauto. congruence.\n   clear RP.\n   destruct a; simpl in ST; simpl.\n    - unfold store_stack. simpl.\n       rewrite Int.add_zero_l, Int.unsigned_repr, ST.\n       exists mm, (z+1); trivial.\n       assert (A: 0 <= 4*z <= Int.max_unsigned).\n       { split. omega. simpl typesize in REP.\n         assert (1 + sz' >= 0) by (apply args_len_rec_nonneg in AL; omega).\n         unfold Int.max_unsigned. omega. }\n       solve[apply A].\n    - unfold store_stack. simpl.\n       rewrite Int.add_zero_l, Int.unsigned_repr, ST.\n       exists mm, (z+2); trivial.\n       clear - POS REP AL.\n       apply args_len_rec_nonneg in AL.\n       destruct z; try xomega.\n         unfold Int.max_unsigned; simpl; omega.\n         assert (0 < typesize Tfloat + sz').\n           simpl. destruct sz'. omega. xomega. xomega.\n         remember (typesize Tfloat + sz') as q. clear  AL Heqq sz'.\n           unfold Int.max_unsigned. xomega.\n    - congruence.\n    - unfold store_stack. simpl.\n       rewrite Int.add_zero_l, Int.unsigned_repr, ST.\n       exists mm, (z+1); trivial.\n       clear - POS REP AL.\n       apply args_len_rec_nonneg in AL.\n       destruct z; try xomega.\n         unfold Int.max_unsigned; simpl; omega.\n         assert (0 < typesize Tsingle + sz').\n           simpl. destruct sz'. omega. xomega. xomega.\n         remember (typesize Tsingle + sz') as q. clear  AL Heqq sz'.\n           unfold Int.max_unsigned. xomega.\n    - unfold store_stack. simpl.\n       rewrite Int.add_zero_l, Int.unsigned_repr, ST.\n       exists mm, (z+1); trivial.\n       clear - POS REP AL.\n       apply args_len_rec_nonneg in AL.\n       destruct z; try xomega.\n         unfold Int.max_unsigned; simpl; omega.\n         assert (0 < typesize Tany32 + sz').\n           simpl. destruct sz'. omega. xomega. xomega.\n         remember (typesize Tany32 + sz') as q. clear  AL Heqq sz'.\n           unfold Int.max_unsigned. xomega.\n    - unfold store_stack. simpl.\n       rewrite Int.add_zero_l, Int.unsigned_repr, ST.\n       exists mm, (z+2); trivial.\n       clear - POS REP AL.\n       apply args_len_rec_nonneg in AL.\n       destruct z; try xomega.\n         unfold Int.max_unsigned; simpl; omega.\n         assert (0 < typesize Tany64 + sz').\n           simpl. destruct sz'. omega. xomega. xomega.\n         remember (typesize Tany64 + sz') as q. clear  AL Heqq sz'.\n           unfold Int.max_unsigned. xomega.\n }\n specialize (IHtys _ ArgsDef H0 _ AL).\n rewrite Zplus_assoc in REP.\n assert (POS' : 0 <= z+typesize a). destruct a; simpl; omega.\n specialize (IHtys _ POS' REP).\n destruct STARG as [mm [zz STARG]].\n specialize (store_argSZ _ _ _ _ _ _ _ STARG). intros ZZ; subst zz.\n eapply store_args_cons. eassumption.\n apply IHtys; clear IHtys.\n red; intros. eapply store_arg_perm1; eauto.\n clear STARG. eapply RP; clear RP.\n specialize (typesize_pos a); intros. omega.\n(*FIXME: *) Grab Existential Variables. refine (0).\nAdmitted. (*TODO: (End of proof containing the now incorrect typesize assertion)*)\n\nLemma store_args_rec_succeeds sz m sp args tys\n      (VALSDEF: val_casted.vals_defined args=true)\n      (HASTY: Val.has_type_list args tys)\n      (REP: 4*sz < Int.modulus) m'' :\n  args_len_rec args tys = Some sz ->\n  Mem.alloc m 0 (4*sz) = (m'',sp) ->\n  exists m', store_args_rec m'' sp 0 args tys = Some m'.\nProof.\nintros H H2. exploit store_args_rec_succeeds_aux; eauto. omega. omega.\nintros ofs [H3 H4]. apply Mem.perm_alloc_2 with (ofs := ofs) (k := Cur) in H2; auto.\neapply Mem.perm_implies; eauto. constructor.\nQed.\n\nDefinition store_args m sp args tys := store_args_rec m sp 0 args tys.\n\nRequire Import VST.ccc26x86.Conventions1.\n\n(*Fixpoint agree_args_contains_aux m' sp' ofs args tys : Prop :=\n  match args,tys with\n    | nil,nil => True\n    | a::args',ty::tys' =>\n        Mem.load (chunk_of_type ty) m' sp' (fe_ofs_arg + 4*ofs) = Some a\n        /\\ agree_args_contains_aux m' sp' (ofs+1) args' tys'\n    | _,_ => False\n  end.*)\n\nFixpoint agree_args_contains_aux m' sp' ofs args tys : Prop :=\n  let vsp := Vptr sp' Int.zero in\n  match tys with\n    | nil => args=nil\n    | ty'::tys' =>\n      match args with\n        | nil => False\n        | a'::args' =>\n          match ty' with\n            | Tlong =>\n              match a' with\n                | Vlong n =>\n                  load_stack m' vsp Tint (Int.repr (4*(ofs+1)))\n                  = Some (Vint (Int64.hiword n))\n                  /\\ load_stack m' vsp Tint (Int.repr (4*ofs))\n                     = Some (Vint (Int64.loword n))\n                  /\\ agree_args_contains_aux m' sp' (ofs+2) args' tys'\n                | _ => False\n              end\n            | _ =>\n              load_stack m' vsp ty' (Int.repr (4*ofs)) = Some a'\n              /\\ agree_args_contains_aux m' sp' (ofs+typesize ty') args' tys'\n          end\n      end\n  end.\n\nLemma agree_args_contains_aux_invariant:\n  forall tys m sp ofs args m',\n  agree_args_contains_aux m sp ofs args tys ->\n  Mem.unchanged_on (fun b ofs => b=sp) m m' ->\n  agree_args_contains_aux m' sp ofs args tys.\nProof.\ninduction tys. destruct args; simpl; auto.\nintros m'; destruct args; simpl; auto. destruct a.\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  intros z [H H2] [H3 H4]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  intros z [H H2] [H3 H4]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  generalize\n     (Int.repr\n        match ofs + 1 with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z1.\n  destruct v; try inversion 3.\n  intros z1 z [H H2] [H3 [H4 H5]]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\n  split. eapply Mem.load_unchanged_on; eauto. intros. solve[simpl; auto].\n  solve[eapply IHtys; eauto].\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  intros z [H H2] [H3 H4]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  intros z [H H2] [H3 H4]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\n+ generalize\n     (Int.repr\n        match ofs with\n        | 0 => 0\n        | Z.pos y' => Z.pos y'~0~0\n        | Z.neg y' => Z.neg y'~0~0\n        end) as z.\n  intros z [H H2] [H3 H4]. split; eauto.\n  unfold load_stack, Mem.loadv in H3|-*.\n  revert H3; case_eq (Val.add (Vptr sp Int.zero) (Vint z));\n    try solve[inversion 1].\n  simpl; intros ? ?; inversion 1; subst.\n  eapply Mem.load_unchanged_on. eapply H0. intros. solve[simpl; auto].\nQed.\n\nLemma args_len_rec_bound args tys z :\n  args_len_rec args tys = Some z -> z <= 2*Zlength args.\nProof.\n  revert args z. induction tys. destruct args. simpl. inversion 1; omega.\n  simpl. inversion 1. destruct args. inversion 1. intros z H.\n  apply args_len_recD in H. destruct H as [z1 [z2 [Zeq [? H2]]]]. subst z.\n  specialize (IHtys _ _ H). destruct a; subst z1; rewrite Zlength_cons; omega.\nQed.\n\nLemma store_args_inject args args' tys j m m' m2 m2' b b' z :\n  Val.inject_list j args args' ->\n  Mem.inject j m m' ->\n  j b = Some (b',0) ->\n  store_args_rec m b z args tys = Some m2 ->\n  store_args_rec m' b' z args' tys = Some m2' ->\n  Mem.inject j m2 m2'.\nProof.\nintros A B C D E.\nrevert args args' m m' z A B D E. induction tys.\nintros args args' m m' z H. inv H. simpl.\n  inversion 2; subst. solve[inversion 1; subst; auto].\nintros ? ?; inversion 1.\nintros ? ? ? ? ?. intros H. inv H. solve[inversion 2]. simpl. intros H.\ngeneralize\n (Int.repr match z with\n             | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n             | Z.neg y' => Z.neg y'~0~0 end) as z'.\ngeneralize\n (Int.repr match z+1 with\n             | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n             | Z.neg y' => Z.neg y'~0~0 end) as z''.\nintros z'' z'. destruct a.\n- case_eq (store_stack m (Vptr b Int.zero) Tint z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\nexploit Mem.store_mapped_inject; try eassumption.\nintros [m0' [STORE' INJ]].\nrewrite Zplus_0_r in STORE'. rewrite STORE'. intros H3.\neapply IHtys; eauto.\n- case_eq (store_stack m (Vptr b Int.zero) Tfloat z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\nexploit Mem.store_mapped_inject; try eassumption.\nintros [m0' [STORE' INJ]].\nrewrite Zplus_0_r in STORE'. rewrite STORE'. intros H3.\neapply IHtys; eauto.\n- inv H0; try solve[inversion 1].\ncase_eq (store_stack m (Vptr b Int.zero) Tint z'' (Vint (Int64.hiword i)));\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\nexploit Mem.store_mapped_inject; eauto.\nintros [m0' [STORE' INJ]].\nrewrite Zplus_0_r in STORE'. rewrite STORE'.\nrevert H2. rewrite Int.add_zero_l.\ncase_eq (Mem.store Mint32 m0 b (Int.unsigned z') (Vint (Int64.loword i)));\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m1 STORE1 H3.\nexploit Mem.store_mapped_inject; eauto.\nintros [m1' [STORE1' INJ']]. rewrite Zplus_0_r in STORE1'. rewrite STORE1'.\neapply IHtys; eauto.\n- case_eq (store_stack m (Vptr b Int.zero) Tsingle z' v);\n  try solve[intros; congruence].\nunfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\nexploit Mem.store_mapped_inject; try eassumption. eauto.\nintros [m0' [STORE' INJ]].\nrewrite Zplus_0_r in STORE'. rewrite STORE'. intros H3.\neapply IHtys; eauto.\n- case_eq (store_stack m (Vptr b Int.zero) Tany32 z' v);\n  try solve[intros; congruence].\n  unfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\n  exploit Mem.store_mapped_inject; try eassumption.\n  intros [m0' [STORE' INJ]].\n  rewrite Zplus_0_r in STORE'. rewrite STORE'. intros H3.\n  eapply IHtys; eauto.\n- case_eq (store_stack m (Vptr b Int.zero) Tany64 z' v);\n  try solve[intros; congruence].\n  unfold store_stack, Mem.storev. simpl. intros m0 STORE H2.\n  exploit Mem.store_mapped_inject; try eassumption.\n  intros [m0' [STORE' INJ]].\n  rewrite Zplus_0_r in STORE'. rewrite STORE'. intros H3.\n  eapply IHtys; eauto.\nQed.\n\nLemma args_len_rec_inject j args args' tys z z' :\n  Val.inject_list j args args' ->\n  args_len_rec args tys = Some z ->\n  args_len_rec args' tys = Some z' ->\n  z=z'.\nProof.\nintros.\nrevert tys z z' H0 H1.\ninduction H.\nsimpl. destruct tys; inversion 1. inversion 1; subst; auto.\ndestruct tys; inversion 1. simpl. destruct t.\n+ inv H1.\nrevert H3 H4.\ncase_eq (args_len_rec vl tys); try solve[intros; congruence]. intros.\nrevert H2. case_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\n+ inv H1.\nrevert H3 H4.\ncase_eq (args_len_rec vl tys); try solve[intros; congruence]. intros.\nrevert H2. case_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\n+ inv H1.\nrevert H3 H4.\ndestruct v; try solve[inversion 1].\ndestruct v'; try solve[inversion 3].\ncase_eq (args_len_rec vl tys); try solve[inversion 2].\ncase_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\n+ inv H1.\nrevert H3 H4.\ncase_eq (args_len_rec vl tys); try solve[intros; congruence]. intros.\nrevert H2. case_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\n+ inv H1.\nrevert H3 H4.\ncase_eq (args_len_rec vl tys); try solve[intros; congruence]. intros.\nrevert H2. case_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\n+ inv H1.\nrevert H3 H4.\ncase_eq (args_len_rec vl tys); try solve[intros; congruence]. intros.\nrevert H2. case_eq (args_len_rec vl' tys); try solve[intros; congruence]. intros.\nexploit IHinject_list; eauto.\nintros. subst z0. inv H3; inv H4; inv H5. omega.\nQed.\n\nLemma sm_locally_allocated_only_stores1 mu mu' b1 l1 m1 m2 m1' m2' m1'' :\n  mem_forward m1 m1' ->\n  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n  only_stores b1 l1 m1' m1'' ->\n  sm_locally_allocated mu mu' m1 m2 m1'' m2'.\nProof.\nintros.\nrevert m2 m2' mu mu' H H0. induction X; auto. intros.\napply IHX.\neapply mem_forward_trans; eauto. apply store_forward in e. auto. auto.\nrewrite sm_locally_allocatedChar in H0|-*.\ndestruct H0 as [? [? [? [? [? ?]]]]].\nintuition.\ngeneralize e as e'. intro.\napply store_freshloc in e. rewrite H0.\nextensionality b. destruct (DomSrc mu b); auto. simpl.\nsymmetry. rewrite <-freshloc_trans with (m'':= m); auto. rewrite e.\n  solve[rewrite orb_comm; auto].\napply store_forward in e'. eauto.\nrewrite H2. extensionality b. destruct (locBlocksSrc mu b); simpl; auto.\ngeneralize e as e'. intro.\napply store_freshloc in e.\nsymmetry. rewrite <-freshloc_trans with (m'':= m); auto. rewrite e.\n  solve[rewrite orb_comm; auto].\napply store_forward in e'. eauto.\nQed.\n\nLemma sm_locally_allocated_only_stores2 mu mu' b2 l2 m1 m2 m1' m2' m2'' :\n  mem_forward m2 m2' ->\n  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n  only_stores b2 l2 m2' m2'' ->\n  sm_locally_allocated mu mu' m1 m2 m1' m2''.\nProof.\nintros.\nrevert m1 m1' mu mu' H H0. induction X; auto. intros.\napply IHX; auto.\neapply mem_forward_trans; eauto. apply store_forward in e. auto.\nrewrite sm_locally_allocatedChar in H0|-*.\ndestruct H0 as [? [? [? [? [? ?]]]]].\nintuition.\ngeneralize e as e'. intro.\napply store_freshloc in e. rewrite H1.\nextensionality b. destruct (DomTgt mu b); auto. simpl.\nsymmetry. rewrite <-freshloc_trans with (m'':= m); auto. rewrite e.\n  solve[rewrite orb_comm; auto].\napply store_forward in e'. eauto.\nrewrite H3. extensionality b. destruct (locBlocksTgt mu b); simpl; auto.\ngeneralize e as e'. intro.\napply store_freshloc in e.\nsymmetry. rewrite <-freshloc_trans with (m'':= m); auto. rewrite e.\n  solve[rewrite orb_comm; auto].\napply store_forward in e'. eauto.\nQed.\n\nLemma sm_locally_allocated_only_stores mu mu' b1 b2 l1 l2 m1 m2 m1' m2' m1'' m2'' :\n  mem_forward m1 m1' ->\n  mem_forward m2 m2' ->\n  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n  only_stores b1 l1 m1' m1'' ->\n  only_stores b2 l2 m2' m2'' ->\n  sm_locally_allocated mu mu' m1 m2 m1'' m2''.\nProof.\nintros.\neapply sm_locally_allocated_only_stores1; eauto.\neapply sm_locally_allocated_only_stores2; eauto.\nQed.\n\nLemma sm_valid_only_stores mu b1 b2 l1 l2 m1 m2 m1' m2' :\n  sm_valid mu m1 m2 ->\n  only_stores b1 l1 m1 m1' ->\n  only_stores b2 l2 m2 m2' ->\n  sm_valid mu m1' m2'.\nProof.\nrevert m2 m2' b2 l2 mu; induction 2. induction 1; auto.\napply Mem.nextblock_store in e.\napply IHX. unfold sm_valid. unfold Mem.valid_block. rewrite e.\ndestruct H. split; auto.\nintros. apply IHX; auto. apply Mem.nextblock_store in e.\ndestruct H. unfold sm_valid, Mem.valid_block. rewrite e. auto.\nQed.\n\nLemma REACH_only_stores b l m m' roots :\n  only_stores b l m m' ->\n  roots b = true ->\n  (forall b' : block,\n     getBlocks l b' = true -> roots b' = true) ->\n  REACH_closed m roots ->\n  REACH_closed m' roots.\nProof.\ninduction 1; auto. intros H H2 H3. apply IHX; auto.\nintros. apply H2. rewrite getBlocksD. destruct v; auto.\n  solve[rewrite orb_true_iff; auto].\neapply REACH_Store; eauto.\nintros. eapply H2. rewrite getBlocksD in H0|-*.\ndestruct v; auto; try solve[rewrite getBlocksD_nil in H0; congruence].\nrewrite getBlocksD_nil, orb_comm in H0; simpl in H0.\nrewrite H0; auto.\nQed.\n\nLemma store_stack_mem m sp ty ofs v m'\n        (ST: store_stack m sp ty ofs v = Some m'):\n      mem_step m m'.\nProof. intros.\n unfold store_stack in ST. destruct sp; simpl in ST; inv ST.\n eapply mem_step_store; eassumption.\nQed.\n\nLemma store_args_mem sp ofs args tys m m' :\n  store_args_rec m sp ofs args tys = Some m' ->\n  mem_step m m'.\nProof.\nrevert args ofs m; induction tys.\n+ destruct args.\n  - intros ofs. inversion 1; subst. apply mem_step_refl.\n  - intros ofs m. simpl. inversion 1.\n+ destruct args; try solve[inversion 1].\n  destruct a; simpl; intros ofs m.\n  - case_eq (store_stack m (Vptr sp Int.zero) Tint\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\n    * intros.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ H).\n       eapply IHtys; eassumption.\n    * intros; congruence.\n  - case_eq (store_stack m (Vptr sp Int.zero) Tfloat\n           (Int.repr match ofs with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                    | Z.neg y' => Z.neg y'~0~0 end) v).\n    * intros.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ H).\n       eapply IHtys; eassumption.\n    * intros; congruence.\n  - destruct v; try solve[congruence].\n    case_eq (store_stack m (Vptr sp Int.zero) Tint\n           (Int.repr match ofs+1 with | 0 => 0 | Z.pos y' => Z.pos y'~0~0\n                                      | Z.neg y' => Z.neg y'~0~0 end)\n        (Vint (Int64.hiword i))).\n    * intros.\n       remember (store_stack m0 (Vptr sp Int.zero) Tint\n        (Int.repr\n           match ofs with\n           | 0 => 0\n           | Z.pos y' => Z.pos y'~0~0\n           | Z.neg y' => Z.neg y'~0~0\n           end) (Vint (Int64.loword i))).\n       symmetry in Heqo; destruct o; inv H0.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ H).\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ Heqo).\n      eapply IHtys; eassumption.\n    * intros; congruence.\n  - intros.\n    remember (store_stack m (Vptr sp Int.zero) Tsingle\n        (Int.repr\n           match ofs with\n           | 0 => 0\n           | Z.pos y' => Z.pos y'~0~0\n           | Z.neg y' => Z.neg y'~0~0\n           end) v).\n       symmetry in Heqo; destruct o; inv H.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ Heqo).\n       eapply IHtys; eassumption.\n  - intros.\n    remember (store_stack m (Vptr sp Int.zero) Tany32\n        (Int.repr\n           match ofs with\n           | 0 => 0\n           | Z.pos y' => Z.pos y'~0~0\n           | Z.neg y' => Z.neg y'~0~0\n           end) v).\n       symmetry in Heqo; destruct o; inv H.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ Heqo).\n       eapply IHtys; eassumption.\n  - intros.\n    remember (store_stack m (Vptr sp Int.zero) Tany64\n        (Int.repr\n           match ofs with\n           | 0 => 0\n           | Z.pos y' => Z.pos y'~0~0\n           | Z.neg y' => Z.neg y'~0~0\n           end) v).\n       symmetry in Heqo; destruct o; inv H.\n      eapply mem_step_trans.\n       apply (store_stack_mem _ _ _ _ _ _ Heqo).\n       eapply IHtys; eassumption.\nQed.\n\nLemma store_args_mem_step m stk args tys m':\n  store_args m stk args tys = Some m' -> mem_step m m'.\nProof. intros. unfold store_args in H.\n  apply store_args_rec_only_stores in H.\n  remember (encode_longs tys args). clear Heql.\n  induction H. apply mem_step_refl.\n  eapply mem_step_trans; try eassumption.\n  eapply mem_step_store; eassumption.\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/ccc26x86/load_frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16542185686927652}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nRequire sha.sha.\nRequire sha.SHA256.\nLocal Open Scope logic.\n\nRequire Import sha.spec_sha.\nRequire Import sha_lemmas.\nRequire Import sha.HMAC_functional_prog.\n\nRequire Import sha.hmac091c.\n\nRequire Import sha.spec_hmac.\n\nLemma isbyte_Nlist i n: isbyteZ i -> Forall isbyteZ (Nlist i n).\n  intros. apply Forall_forall. intros.\n  induction n; simpl in *. contradiction.\n  destruct H0. subst. trivial.\n  apply (IHn H0).\nQed.\n\nLemma body_hmac_cleanup: semax_body HmacVarSpecs HmacFunSpecs \n       f_HMAC_cleanup HMAC_Cleanup_spec.\nProof.\nstart_function.\nname ctx' _ctx.\nunfold hmacstate_simple, hmac_relate_simple. normalize. intros hst. normalize. \napply semax_pre with (P':=\n  PROP (size_compatible t_struct_hmac_ctx_st c /\\\n        align_compatible t_struct_hmac_ctx_st c)\n   LOCAL  (`(eq c) (eval_id _ctx))\n   SEP \n   (`(data_at Tsh t_struct_hmac_ctx_st\n        (upd_reptype t_struct_hmac_ctx_st [_md_ctx] hst\n           (default_val t_struct_SHA256state_st)) c))).\n  entailer. unfold data_at. simpl. normalize.\nnormalize.\n\nforward_call (Tsh, c, sizeof t_struct_hmac_ctx_st, Int.zero).\n  { assert (FR: Frame = nil).  \n      subst Frame. reflexivity.\n    rewrite FR. clear FR Frame.\n    entailer.\n    eapply derives_trans. apply data_at_data_at_.\n       reflexivity.\n    rewrite <- memory_block_data_at_; try reflexivity.\n    entailer. \n  }\nafter_call. subst retval0.\nforward.\nassert (isByte0:  isbyteZ 0). unfold isbyteZ. omega.\nspecialize (isbyte_Nlist 0 (Z.to_nat (sizeof t_struct_hmac_ctx_st)) isByte0). \nunfold data_block. rewrite Zlength_correct; simpl. intros.\nentailer. \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/verif_hmac_cleanup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.32082130082460697, "lm_q1q2_score": 0.16542184731738768}}
{"text": "(** * Saturation of the Grothendieck Construction of a functor to Set *)\nRequire Import Category.Core Functor.Core.\nRequire Import Category.Univalent.\nRequire Import Category.Morphisms.\nRequire Import SetCategory.Core.\nRequire Import Grothendieck.ToSet.Core Grothendieck.ToSet.Morphisms.\nRequire Import HoTT.Basics.Equivalences HoTT.Basics.Trunc.\nRequire Import HoTT.Types.Universe HoTT.Types.Sigma.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope morphism_scope.\n\nSection Grothendieck.\n  Context `{Univalence}.\n\n  Variable C : PreCategory.\n  Context `{IsCategory C}.\n  Variable F : Functor C set_cat.\n\n  Definition category_isotoid_helper {s d} (a : c s = c d)\n  : (transport (fun c : C => F c) a (x s) = x d)\n      <~> (F _1 (idtoiso C a)) (x s) = x d.\n  Proof.\n    apply equiv_path.\n    apply ap10, ap.\n    destruct a; simpl.\n    exact (ap10 (identity_of F _)^ _).\n  Defined.\n\n  Arguments category_isotoid_helper : simpl never.\n\n  Definition category_isotoid {s d : category F}\n  : s = d <~> (s <~=~> d)%category.\n  Proof.\n    refine (isequiv_sigma_category_isomorphism^-1 oE _ oE (equiv_ap' (issig_pair F)^-1 s d)).\n    refine (_ oE (equiv_path_sigma _ _ _)^-1).\n    simpl.\n    simple refine (equiv_functor_sigma' _ _).\n    { exists (@idtoiso C _ _).\n      exact _. }\n    { exact category_isotoid_helper. }\n  Defined.\n\n  Global Instance preservation : IsCategory (category F).\n  Proof.\n    intros s d.\n    refine (@isequiv_homotopic _ _ category_isotoid (idtoiso (category F) (x:=s) (y:=d)) _ _).\n    intro x.\n    destruct x; apply path_isomorphic, path_sigma_hprop.\n    reflexivity.\n  Defined.\nEnd Grothendieck.\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/Grothendieck/ToSet/Univalent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.1654007435588015}}
{"text": "Require Import Eqdep Lia Framework FSParameters FileDiskLayer. (* LoggedDiskLayer TransactionCacheLayer TransactionalDiskLayer. *)\nRequire Import FileDiskNoninterference FileDiskRefinement.\nRequire Import ATCDLayer FileDisk.TransferProofs ATCD_Simulation ATCD_AOE.\nRequire Import Not_Init HSS ATCD_ORS.\nRequire Import ATCD_TS_Recovery ATCD_TS_Common ATCD_TS_Operations.\n\nImport FileDiskLayer.\nSet Nested Proofs Allowed.\nOpaque File.recover.\n\n\nLemma ATCD_TS_BatchOperations_encrypt_all:\n  forall n u k l1 l2 txns1 txns2 hdr1 hdr2,\n  length l1 = length l2 ->\nTermination_Sensitive u\n(@lift_L2 AuthenticationOperation _ TCDLang _\n  (@lift_L2 _ _ CachedDiskLang _\n     (|CDDP| BatchOperations.encrypt_all k l1)))\n(@lift_L2 AuthenticationOperation _ TCDLang _\n     (@lift_L2 _ _ CachedDiskLang _\n        (|CDDP| BatchOperations.encrypt_all k l2)))\n   (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |))))\n  (refines_valid ATCD_Refinement\n  (refines_valid ATC_Refinement AD_valid_state)) \n  (fun s1 s2 => equivalent_for_recovery txns1 txns2\n  Log.Current_Part hdr1 hdr2 s1 s2 /\\\n  (forall x, \n  consistent_with_upds (snd (fst (snd (snd (snd s1))))) (firstn x (map (encrypt k) l1)) (firstn x (map (fun v => (k, v)) l1)) ->\n  consistent_with_upds (snd (fst (snd (snd (snd s2))))) (firstn x (map (encrypt k) l2)) (firstn x (map (fun v => (k, v)) l2))))\n(ATCD_reboot_list n).\nProof.\n   unfold Termination_Sensitive, ATCD_reboot_list; \n   intros; destruct n;\n   repeat invert_exec.\n   {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n\n      eapply_fresh BatchOperations.encrypt_all_finished in H8; cleanup; eauto.\n      eapply BatchOperations_TS_encrypt_all in H8; eauto; cleanup.\n      eexists (RFinished _ _).\n      repeat econstructor; eauto.\n      repeat eapply lift2_exec_step; eauto.\n      specialize (c (length l1)).\n      do 4 rewrite firstn_oob in c.\n      simpl in *.\n      eapply c; eauto.\n      all: repeat rewrite map_length; lia.\n    }\n    {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n\n      eapply_fresh BatchOperations.encrypt_all_crashed in H8; cleanup.\n      eapply BatchOperations_TS_encrypt_all_crashed in H8; eauto; cleanup.\n      eapply_fresh BatchOperations.encrypt_all_crashed in H8; cleanup.\n      repeat cleanup_pairs.\n      simpl in *.\n       edestruct ATCD_TS_recovery.\n       3: eauto.\n       3: shelve. (* eapply equivalent_for_recovery_after_reboot; eauto. *)\n \n       3: {\n          eexists (Recovered _); econstructor; eauto.\n      repeat eapply lift2_exec_step_crashed; eauto.\n      }\n\n      all: try solve [unfold AD_valid_state, \n      refines_valid, FD_valid_state; \n      intros; simpl; eauto].\n    }\n    Unshelve.\n    all: try exact ATCDLang.\n    6: {\n      unfold equivalent_for_recovery in *; simpl in *;\n      cleanup.\n      eexists (_, (_, _)), (_, (_,_)); split.\n      simpl; intuition eauto.\n      rewrite e2 in *;\n      do 2 eexists; intuition eauto.\n      eapply RepImplications.log_rep_explicit_after_reboot in l0; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds; eauto.\n      eapply select_total_mem_synced in H3; eauto.\n      \n      simpl. split.\n      repeat split.\n      do 2 eexists; split.\n      eapply RepImplications.log_rep_explicit_after_reboot in l; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds; eauto.\n      all: intuition eauto.\n      eapply select_total_mem_synced in H3; eauto.\n    }\nQed.\n\nLemma ATCD_TS_BatchOperations_hash_all:\n  forall n u l1 l2 h1 h2 txns1 txns2 hdr1 hdr2,\n  length l1 = length l2 ->\nTermination_Sensitive u\n(@lift_L2 AuthenticationOperation _ TCDLang _\n  (@lift_L2 _ _ CachedDiskLang _\n     (|CDDP| BatchOperations.hash_all h1 l1)))\n(@lift_L2 AuthenticationOperation _ TCDLang _\n     (@lift_L2 _ _ CachedDiskLang _\n        (|CDDP| BatchOperations.hash_all h2 l2)))\n   (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |))))\n  (refines_valid ATCD_Refinement\n  (refines_valid ATC_Refinement AD_valid_state)) \n  (fun s1 s2 => equivalent_for_recovery txns1 txns2\n  Log.Current_Part hdr1 hdr2 s1 s2 /\\\n  (forall x,\n  consistent_with_upds (snd (fst (fst (snd (snd (snd s1)))))) \n  (firstn x (rolling_hash_list h1 l1))\n  (firstn x (combine (h1 :: rolling_hash_list h1 l1) l1)) ->\n  consistent_with_upds (snd (fst (fst (snd (snd (snd s2)))))) \n  (firstn x (rolling_hash_list h2 l2))\n  (firstn x (combine (h2 :: rolling_hash_list h2 l2) l2))))\n(ATCD_reboot_list n).\nProof.\n   unfold Termination_Sensitive, ATCD_reboot_list; \n   intros; destruct n;\n   repeat invert_exec.\n   {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n      eapply BatchOperations_TS_hash_all in H8; eauto; cleanup.\n      eexists (RFinished _ _).\n      repeat econstructor; eauto.\n      repeat eapply lift2_exec_step; eauto.\n      eapply BatchOperations.hash_all_finished in H8; cleanup; eauto.\n      specialize (c (length l1)).\n      do 4 rewrite firstn_oob in c.\n      apply c; eauto.\n      all: repeat rewrite combine_length; try lia.\n\n      \n\n      all: rewrite rolling_hash_list_length; lia.\n    }\n    {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n      eapply_fresh BatchOperations_TS_hash_all_crashed in H8; eauto; cleanup.\n      eapply BatchOperations.hash_all_crashed in H8; cleanup.\n      eapply_fresh BatchOperations.hash_all_crashed in H2; cleanup.\n      repeat cleanup_pairs.\n      simpl in *.\n       edestruct ATCD_TS_recovery.\n       3: eauto.\n       3: shelve. (* eapply equivalent_for_recovery_after_reboot; eauto. *)\n       3: {\n         eexists (Recovered _); econstructor; eauto.\n         repeat eapply lift2_exec_step_crashed; eauto.\n       }\n       (* 3: repeat cleanup_pairs; eauto. *)\n       all: try solve [unfold AD_valid_state, \n       refines_valid, FD_valid_state; \n       intros; simpl; eauto].\n    }\n    Unshelve.\n    all: try exact ATCDLang.\n    6: {\n      unfold equivalent_for_recovery in *; simpl in *;\n      cleanup_no_match.\n      eexists (_, (_, _)), (_, (_,_)); split.\n      simpl; intuition eauto.\n      rewrite e2 in *;\n      do 2 eexists; intuition eauto.\n      eapply RepImplications.log_rep_explicit_after_reboot in l4; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds_hashmap; eauto.\n      eapply select_total_mem_synced in H4; eauto.\n      \n      simpl. split.\n      repeat split.\n      do 2 eexists; split.\n      eapply RepImplications.log_rep_explicit_after_reboot in l3; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds_hashmap; eauto.\n      all: intuition eauto.\n      eapply select_total_mem_synced in H4; eauto.\n    }\nQed.\n\n\nLemma ATCD_TS_BatchOperations_write_batch:\n  forall n u la1 la2 lv1 lv2 txns1 txns2 hdr1 hdr2,\n  length la1 = length la2 ->\n  length lv1 = length lv2 ->\n  length la2 = length lv2 ->\n  Forall (fun a => a < disk_size) la2 ->\nTermination_Sensitive u\n(@lift_L2 AuthenticationOperation _ TCDLang _\n  (@lift_L2 _ _ CachedDiskLang _\n     (|CDDP| BatchOperations.write_batch la1 lv1)))\n(@lift_L2 AuthenticationOperation _ TCDLang _\n     (@lift_L2 _ _ CachedDiskLang _\n        (|CDDP| BatchOperations.write_batch la2 lv2)))\n   (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |))))\n  (refines_valid ATCD_Refinement\n  (refines_valid ATC_Refinement AD_valid_state)) \n  (equivalent_for_recovery txns1 txns2\n  Log.Current_Part hdr1 hdr2)\n(ATCD_reboot_list n).\nProof.\n   unfold Termination_Sensitive, ATCD_reboot_list; \n   intros; destruct n;\n   repeat invert_exec.\n   {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n      eapply BatchOperations_TS_write_batch in H12; cleanup.\n      eexists (RFinished _ _).\n      repeat econstructor; eauto.\n      repeat eapply lift2_exec_step; eauto.\n      all: eauto.\n    }\n    {\n      repeat invert_lift2; cleanup.\n      destruct s2, s0, s2, s3.\n      eapply_fresh BatchOperations_TS_write_batch_crashed in H12; cleanup.\n      eapply BatchOperations.write_batch_crashed in H12; cleanup.\n      eapply_fresh BatchOperations.write_batch_crashed in H5; cleanup.\n      simpl in *.\n       edestruct ATCD_TS_recovery.\n       3: eauto.\n       3: shelve. (* eapply equivalent_for_recovery_after_reboot; eauto. *)\n      3: { \n         eexists (Recovered _); econstructor; eauto.\n      repeat eapply lift2_exec_step_crashed; eauto.\n    }\n    all: try solve [unfold AD_valid_state, \n      refines_valid, FD_valid_state; \n      intros; simpl; eauto].\n\n    Unshelve.\n    all: try exact ATCDLang.\n    6: {\n       (* probably need to add the fact that \n       it is written to the end of the log *)\n      admit. (*\n      unfold equivalent_for_recovery in *; simpl in *;\n      cleanup_no_match.\n      eexists (_, (_, _)), (_, (_,_)); split.\n      simpl; intuition eauto.\n      do 2 eexists; intuition eauto.\n\n      Search Log.log_rep_explicit upd_batch_set.\n      eapply RepImplications.log_rep_explicit_after_reboot in l4; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds_hashmap; eauto.\n      eapply select_total_mem_synced in H3; eauto.\n      \n      simpl. split.\n      repeat split.\n      do 2 eexists; split.\n      eapply RepImplications.log_rep_explicit_after_reboot in l3; simpl in *.\n      eapply RepImplications.log_rep_explicit_consistent_with_upds_hashmap; eauto.\n      all: intuition eauto.\n      eapply select_total_mem_synced in H3; eauto.\n      *)\n    }\nAdmitted.\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/ATCD_TS/ATCD_TS_BatchOperations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.1651296578930228}}
{"text": "(** Static Intra-method control flow step. We also implement an iterator on it *)\n(* Hendra : - Modified to suit DEX program. \n            - DEX has different instructions list from JVM.\n            - Also trim the system to contain only Arithmetic\n            - Only retain the for_all_steps lemma *)\nRequire Export Annotated.\nImport DEX_BigStep.DEX_Dom DEX_Prog.\n\n(* Module Make (Ms:MAP). *)\n\n  Section DEX_S_section.   (** step relation **)\n    (*Variable p : DEX_Program.*)\n    (* Definition address := Ms.key.\n    Variable codes : Ms.t (DEX_Instruction*(option address*list DEX_ClassName)).\n    Variable jump_label : address -> DEX_OFFSET.t -> address.\n\n    Definition nextAddress (pc:address): option address :=\n    match Ms.get codes pc with\n      | Some p => fst (snd p)\n      | None => None\n    end.\n\n    Definition instructionAtAddress (pc:address) : option DEX_Instruction :=\n    match Ms.get codes pc with\n      |Some p => Some (fst p)\n      |None => None\n    end. *)\n(*\n    Variable subclass_test : DEX_ClassName -> DEX_ClassName -> bool.\n*)\n    Variable m : DEX_Method.\n\n    (* DEX Definition handler := handler subclass_test m.*)\n\n    Inductive DEX_step : DEX_PC -> DEX_Instruction -> (* DEX_tag ->  *)option DEX_PC -> Prop := \n(*     Inductive DEX_step : address -> DEX_Instruction -> DEX_tag -> option address -> Prop := *)\n    | DEX_nop : forall i j,\n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i DEX_Nop (* None *) (Some j)\n    | DEX_move : forall i j (k:DEX_ValKind) (rt:DEX_Reg) (rs:DEX_Reg),\n      \n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_Move k rt rs) (* None *) (Some j)\n(* DEX Method\n    | moveResult : forall i j (k:DEX_ValKind) (rt:DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (MoveResult k rt) None (Some j)\n*)\n    | DEX_return_s : forall i,\n      DEX_step i DEX_Return (* None *) None\n    | DEX_vReturn : forall i (k:DEX_ValKind) (rt:DEX_Reg),\n      DEX_step i (DEX_VReturn k rt) (* None *) None\n    | DEX_const : forall i j (k:DEX_ValKind) (rt:DEX_Reg) (v:Z),\n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_Const k rt v) (* None *) (Some j)\n(* DEX Object\n    | instanceOf : forall i j (rt:DEX_Reg) (r:DEX_Reg) (t:DEX_refType),\n      next m i = Some j ->\n      DEX_step i (InstanceOf rt r t) None (Some j)\n    | arrayLength : forall i j (rt:DEX_Reg) (rs:DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (ArrayLength rt rs) None (Some j)\n    | new : forall i j (rt:DEX_Reg) (t:DEX_refType),\n      next m i = Some j ->\n      DEX_step i (New rt t) None (Some j) \n    | newArray : forall i j (rt:DEX_Reg) (rl:DEX_Reg) (t:DEX_type),\n      next m i = Some j ->\n      DEX_step i (NewArray rt rl t) None (Some j)\n*)\n    | DEX_goto : forall i (o:DEX_OFFSET.t),\n      DEX_step i (DEX_Goto o) (* None *) (Some (DEX_OFFSET.jump i o))\n(*       DEX_step i (DEX_Goto o) None (Some (jump_label i o)) *)\n(* still experimental for PackedSwitch in that the next instruction is\n   defined as the difference between i and j *)\n(*    | packedSwitch : forall i j (rt:DEX_Reg) (firstKey:Z) (size:Z) (l:list OFFSET.t),\n      (* next m i = Some j \\/ In o ((j - i)::l) -> *)\n      next m i = Some j \\/ In j (@map _ _ (OFFSET.jump i) l) ->\n      step i (PackedSwitch rt firstKey size l) None (Some j)\n    | sparseSwitch : forall i j (rt:DEX_Reg) (size:Z) (l:list (Z * OFFSET.t)),\n      next m i = Some j \\/ In j (@map _ _ (OFFSET.jump i) (@map _ _ (@snd _ _) l)) ->\n      step i (SparseSwitch rt size l) None (Some j) *)\n    | DEX_ifcmp : forall i j (cmp:DEX_CompInt) (ra:DEX_Reg) (rb:DEX_Reg) (o:DEX_OFFSET.t),\n     next m i = Some j \\/ j = DEX_OFFSET.jump i o ->\n(*       nextAddress i = Some j \\/ j = jump_label i o -> *)\n      DEX_step i (DEX_Ifcmp cmp ra rb o) (* None *) (Some j)\n    | DEX_ifz : forall i j (cmp:DEX_CompInt) (r:DEX_Reg) (o:DEX_OFFSET.t),\n      next m i = Some j \\/ j = DEX_OFFSET.jump i o ->\n(*       nextAddress i = Some j \\/ j = jump_label i o -> *)\n      DEX_step i (DEX_Ifz cmp r o) (* None *) (Some j)\n(* DEX Object\n    | aget : forall i j (k:DEX_ArrayKind) (rt:DEX_Reg) (ra:DEX_Reg) (ri:DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Aget k rt ra ri) None (Some j)\n    | aput : forall i j (k:DEX_ArrayKind) (rs:DEX_Reg) (ra:DEX_Reg) (ri:DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Aput k rs ra ri) None (Some j)\n    | iget : forall i j (k:DEX_ValKind) (rt:DEX_Reg) (ro:DEX_Reg) (f:DEX_FieldSignature),\n      next m i = Some j ->\n      DEX_step i (Iget k rt ro f) None (Some j)\n    | iput : forall i j (k:DEX_ValKind) (rs:DEX_Reg) (ro:DEX_Reg) (f:DEX_FieldSignature),\n      next m i = Some j ->\n      DEX_step i (Iput k rs ro f) None (Some j)\n*)\n(*    \n    | Sget (k:ValKind) (rt:DEX_Reg) (f:FieldSignature)\n    | Sput (k:ValKind) (rs:DEX_Reg) (f:FieldSignature) \n*)\n(* DEX Method\n    | invokevirtual : forall i j (m0:DEX_MethodSignature) (n:Z) (p:list DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Invokevirtual m0 n p) None (Some j)\n    | invokesuper : forall i j (m0:DEX_MethodSignature) (n:Z) (p:list DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Invokesuper m0 n p) None (Some j)\n    | invokedirect : forall i j (m0:DEX_MethodSignature) (n:Z) (p:list DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Invokedirect m0 n p) None (Some j)\n    | invokestatic : forall i j (m0:DEX_MethodSignature) (n:Z) (p:list DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Invokestatic m0 n p) None (Some j)\n    | invokeinterface : forall i j (m0:DEX_MethodSignature) (n:Z) (p:list DEX_Reg),\n      next m i = Some j ->\n      DEX_step i (Invokeinterface m0 n p) None (Some j)\n*)\n    | DEX_ineg : forall i j (rt:DEX_Reg) (rs:DEX_Reg),\n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_Ineg rt rs) (* None *) (Some j)\n    | DEX_inot : forall i j (rt:DEX_Reg) (rs:DEX_Reg),\n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_Inot rt rs) (* None *) (Some j)\n    | DEX_i2b : forall i j (rt:DEX_Reg) (rs:DEX_Reg),\n      next m i = Some j ->\n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_I2b rt rs) (* None *) (Some j)\n    | DEX_i2s : forall i j (rt:DEX_Reg) (rs:DEX_Reg),\n       next m i = Some j -> \n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_I2s rt rs) (* None *) (Some j)\n    | DEX_ibinop : forall i j (op:DEX_BinopInt) (rt:DEX_Reg) (ra:DEX_Reg) (rb:DEX_Reg),\n       next m i = Some j -> \n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_Ibinop op rt ra rb) (* None *) (Some j)\n    | DEX_ibinopConst : forall i j (op:DEX_BinopInt) (rt:DEX_Reg) (r:DEX_Reg) (v:Z),\n       next m i = Some j -> \n(*       nextAddress i = Some j -> *)\n      DEX_step i (DEX_IbinopConst op rt r v) (* None *) (Some j)\n(* Hendra 11082016 focus on DEX I\n    | DEX_packedSwitch : forall i j (rt:DEX_Reg) (firstKey:Z) (size:nat) (l:list DEX_OFFSET.t),\n      (*(next m i = Some d /\\ d = DEX_OFFSET.jump i j) \\/ In j l ->*)\n      (*(nextAddress i = Some d /\\ d = jump_label i j) \\/ In j l -> *)\n      (exists d, nextAddress i = Some d /\\ d = jump_label i j) \\/ In j l ->\n      (*DEX_step i (DEX_PackedSwitch rt firstKey size l) None (Some (DEX_OFFSET.jump i j))*)\n      DEX_step i (DEX_PackedSwitch rt firstKey size l) None (Some (jump_label i j))\n    | DEX_sparseSwitch : forall i j (rt:DEX_Reg) (size:nat) (l:list (Z * DEX_OFFSET.t)),\n      (*(next m i = Some d /\\ d = DEX_OFFSET.jump i j) \\/ *)\n      (exists d, nextAddress i = Some d /\\ d = jump_label i j) \\/ \n        In j (@map _ _ (@snd _ _) l) ->\n      (*DEX_step i (DEX_SparseSwitch rt size l) None (Some (DEX_OFFSET.jump i j))*)\n      DEX_step i (DEX_SparseSwitch rt size l) None (Some (jump_label i j))\n*)\n.     \n\n    Definition get_steps (i:DEX_PC) (ins:DEX_Instruction) (next:option DEX_PC): list ((* DEX_tag *  *)option DEX_PC) := \n(*     Definition get_steps (i:address) (ins:DEX_Instruction) (next:option address): list (DEX_tag * option address) :=  *)\n      match ins with\n(* Hendra 11082016 focus on DEX I\n        | DEX_SparseSwitch r size l =>\n          (*(None,next) :: map (fun o => (None,Some (DEX_OFFSET.jump i o))) (@map _ _ (@snd _ _) l)*)\n          (None,next) :: map (fun o => ((None:DEX_tag),Some (jump_label i o))) (@map _ _ (@snd _ _) l)\n        | DEX_PackedSwitch r firstKey size l =>\n          (*(None,next) :: map (fun o => (None,Some (DEX_OFFSET.jump i o))) (l)*)\n          (None,next) :: map (fun o => ((None:DEX_tag),(Some (jump_label i o):option address))) (l)\n*)\n        | DEX_Return => ((* None, *)None)::nil\n        | DEX_VReturn k rt => ((* None, *)None)::nil\n        | DEX_Goto o => ((* None, *)Some (DEX_OFFSET.jump i o))::nil\n        | DEX_Ifcmp cmp ra rb o => ((* None, *)next)::((* None, *)Some (DEX_OFFSET.jump i o))::nil\n        | DEX_Ifz cmp r o => ((* None, *)next)::((* None, *)Some (DEX_OFFSET.jump i o))::nil\n        | _ => ((* None, *)next)::nil\n      end.\n\n(*     (* TODO : needs to be instantiated from outside *)\n    Parameter next_as_jump : forall i j,\n      nextAddress i = Some j -> exists k, \n        jump_label i k = j.\n      (*exists k, nextAddress i = Some (jump_label i k).*) *)\n\n    Lemma all_step_in_get_steps : forall i ins (* tau *) oj,\n        DEX_step i ins (* tau *) oj -> \n        In ((* tau, *)oj) (get_steps i ins (next m i)).\n    Proof.\n      intros.\n      inversion_clear H;\n      simpl get_steps; try rewrite H0;\n      auto with datatypes;\n      (* ifcmp and ifz cases *)\n        try (destruct H0 as [H0|H0]; rewrite <- H0; auto with datatypes;\n        right; subst; left; reflexivity).\n(* Hendra 11082016 focus on DEX I\n      (* PackedSwitch case *)\n        (* default case : next instruction *)\n        destruct H0. left. inversion H. inversion H0. rewrite H1. rewrite <- H2. reflexivity.\n        (* other successors case *)\n        right. try match goal with\n          [ |- In (_,_) (map ?F _) ] => \n          apply in_map with (f:=F); try assumption\n        end. \n      (* SparseSwitch case *)\n        (* default case : next instruction *)\n        destruct H0. left. inversion H. inversion H0. rewrite H1. rewrite <- H2. reflexivity.\n        (* other successors case *)\n        right. try match goal with\n          [ |- In (_,_) (map ?F _) ] => \n          apply in_map with (f:=F); try assumption\n        end.\n*)\n    Qed.\n\n(*   Definition needs_next (ins:DEX_Instruction) : Prop :=\n    match ins with\n      | DEX_Return => False\n      | DEX_VReturn _ _ => False\n      | _ => True\n    end.  \n\n  (* For now it is assumed, maybe later on we can define what it means \n  for a legal program which satisfies this property. Nevertheless, the\n  burden of proving is not in the scope of translation proof *)\n  Parameter all_ins_has_next : forall i ins, \n    instructionAtAddress i = Some ins ->\n    needs_next (ins) ->\n    nextAddress i = None -> False. *)\n\n(*   Lemma in_get_steps_all_step : forall i ins tau oj, \n        instructionAtAddress i = Some ins ->\n        In (tau,oj) (get_steps i ins (nextAddress (*m*) i)) ->\n        DEX_step i ins tau oj.\n    Proof.\n      intros.\n      unfold get_steps in H. destruct ins eqn:Hins;\n      (* Sequential Instruction *)\n      try (inversion H0; try (inversion H1); \n      try (inversion H1; destruct oj; \n        try (rewrite H4; constructor; auto);\n        try (apply all_ins_has_next with (ins:=ins) in H4; \n          try (rewrite Hins; unfold needs_next; auto; fail); \n          try (inversion H4))); fail);\n      (* Goto, Return and VReturn *)\n      try (inversion H0; try (inversion H1); constructor; fail);\n      (* If and Ifz *)\n      try (inversion H0; inversion H1; \n        try (destruct oj;\n          try (rewrite H4; constructor; left; auto; fail); \n          try (apply all_ins_has_next with (ins:=ins) in H4;\n            try (rewrite Hins; unfold needs_next; auto; fail); \n            try (inversion H4); fail); fail);\n        try (inversion H2); constructor; right; auto; fail).\n(* Hendra 11082016 focus on DEX I  \n      (* PackedSwitch *) \n      inversion H0. inversion H1.\n      (* next successor *)\n      destruct oj. rewrite H4.\n      apply next_as_jump in H4.\n      destruct H4. rewrite <- H2.\n      constructor.\n      left. exists a; split; try (symmetry; auto); try (inversion H1; auto).\n      try (apply all_ins_has_next with (ins:=ins) in H4; \n          try (rewrite Hins; unfold needs_next; auto; fail); \n          try (inversion H4)).\n      (* successor is one of the list *)\n      apply in_map_inv in H1.\n      inversion H1. inversion H2. inversion H3. \n      constructor.\n      right; auto.\n      (* SparseSwitch *) \n      inversion H0. inversion H1.\n      (* next successor *)\n      destruct oj. rewrite H4.\n      apply next_as_jump in H4.\n      destruct H4. rewrite <- H2.\n      constructor.\n      left. exists a; split; try (symmetry; auto); try (inversion H1; auto).\n      try (apply all_ins_has_next with (ins:=ins) in H4; \n          try (rewrite Hins; unfold needs_next; auto; fail); \n          try (inversion H4)).\n      (* successor is one of the list *)\n      apply in_map_inv in H1.\n      inversion H1. inversion H2. inversion H3. \n      constructor.\n      right; auto.\n*)\n    Qed. *)\n\n  Section for_all_steps.\n    Variable test : DEX_PC -> DEX_Instruction -> (* DEX_tag -> *) option DEX_PC -> bool.\n(*     Variable test : address -> DEX_Instruction -> DEX_tag -> option address -> bool. *)\n\n(* This is an attempt to mechanize the proof of translation -\n     Definition for_all_steps_codes (codes:Ms.t (DEX_Instruction*(option DEX_PC*list DEX_ClassName))) : bool :=\n      Ms.for_all \n      (fun i (ins_next:DEX_Instruction*(option (*DEX_PC*)address*list DEX_ClassName)) =>\n        let (ins,next) := ins_next in\n          for_all _\n          (fun (tau_oj:DEX_tag*option (*DEX_PC*)address) => \n              let (tau,oj):=tau_oj in test i ins tau oj)\n              (get_steps i ins (fst next)) )\n      codes.\n\n    Lemma for_all_steps_codes_true : for_all_steps_codes codes = true ->\n      (forall i ins tau oj, \n        instructionAtAddress i = Some ins ->\n        DEX_step i ins tau oj -> test i ins tau oj = true).\n    Proof.\n      intros.\n      assert (T1:=Ms.for_all_true _ _ codes H).\n      assert (T2:=all_step_in_get_steps _ _ _ _ H1).\n      unfold instructionAtAddress in H0.\n      (*rewrite H in H1.*)\n      caseeq (Ms.get codes i).\n      intros (ins0,next0) T3.\n      rewrite T3 in H0.\n      generalize (T1 _ _ T3); clear T1; intros T1.\n      apply for_all_true with\n        (test:=(fun tau_oj : DEX_tag * option address =>\n          let (tau, oj) := tau_oj in test i ins tau oj))\n        (2:=T2).\n      unfold nextAddress.\n      rewrite T3; simpl.\n      inversion H0; subst; auto.\n      intros T3; rewrite T3 in H0; discriminate.\n    Qed.\n\n    Lemma for_all_steps_codes_true2 :\n      (forall i ins tau oj,\n        instructionAtAddress i = Some ins ->\n        DEX_step i ins tau oj -> \n        test i ins tau oj = true) ->\n        for_all_steps_codes codes = true.\n    Proof.\n      intros.\n      (*assert (T2:=all_step_in_get_steps _ _ _ _ H0).*)\n      unfold for_all_steps_codes.\n      apply Ms.spec_all_for_true.\n      intros.\n      destruct a as [ins0 next0].\n      apply true_for_all. intros.\n      destruct a as [tau oj].\n      apply H; auto.\n      unfold instructionAtAddress. rewrite H0. auto.\n      apply in_get_steps_all_step; auto.\n      unfold instructionAtAddress. rewrite H0. auto.\n      unfold nextAddress. rewrite H0. simpl. auto.\n    Qed.\n *)\n(*\n  Definition for_all_steps_codes codes : bool :=\n    match codes with\n      | None => false\n      | Some instructions => for_all_steps_codes instructions\n    end.\n*)\n(*\n  Definition test_all_steps_m : list (DEX_PC*bool) :=\n    match DEX_METHOD.body m with\n      | None => nil\n      | Some bm => \n      List.map\n      (fun (ins_next:DEX_PC*(DEX_Instruction*(option DEX_PC*list DEX_ClassName))) =>\n        let (i,ins_next) := ins_next in\n        let (ins,next) := ins_next in\n          (i,for_all _\n            (fun (tau_oj:DEX_tag*option DEX_PC) => let (tau,oj):=tau_oj in test i ins tau oj)\n            (get_steps i ins (fst next))))\n      (MapN.elements _ bm.(DEX_BYTECODEMETHOD.instr))\n    end.\n\n  Lemma for_all_steps_m_true : for_all_steps_m = true ->\n      forall i ins tau oj,\n        instructionAt m i = Some ins ->\n        DEX_step i ins tau oj -> test i ins tau oj = true.\n  Proof.\n    unfold for_all_steps_m.\n    generalize for_all_steps_bm_true.\n    destruct (DEX_METHOD.body m) as [bm|]; intro.\n    apply H; auto.\n    intros; discriminate.\n  Qed.\n*)\n\n    Definition for_all_steps_bm (bm:DEX_BytecodeMethod) : bool :=\n      MapN.for_all _\n      (fun i (ins_next:DEX_Instruction*(option DEX_PC *list DEX_ClassName )) =>\n        let (ins,next) := ins_next in\n          for_all _\n          (fun ((* tau_ *)oj:(* DEX_tag* *)option DEX_PC) => (* let (tau,oj):=tau_oj in *) test i ins (* tau *) oj)\n          (get_steps i ins ( fst  next)))\n      bm.(DEX_BYTECODEMETHOD.instr).\n\n    Lemma for_all_steps_bm_true : forall bm,\n      DEX_METHOD.body m = Some bm ->\n      for_all_steps_bm bm = true ->\n      forall i ins (* tau *) oj,\n        instructionAt m i = Some ins ->\n        DEX_step i ins (* tau *) oj -> test i ins (* tau *) oj = true.\n    Proof.\n      intros.\n      assert (T1:=MapN.for_all_true _ _ _ H0).\n      assert (T2:=all_step_in_get_steps _ _ _ H2).\n      unfold instructionAt, DEX_BYTECODEMETHOD.instructionAt in H1.\n      rewrite H in H1.\n      caseeq (MapN.get (DEX_Instruction * (option DEX_PC*list DEX_ClassName)) (DEX_BYTECODEMETHOD.instr bm) i).\n      intros (ins0,next0) T3.\n      rewrite T3 in H1.\n      generalize (T1 _ _ T3); clear T1; intros T1.\n      apply for_all_true with\n        (test:=(fun (* tau_ *)oj : (* DEX_tag * *) option DEX_PC =>\n          (* let (tau, oj) := tau_oj in *) test i ins (* tau *) oj))\n        (2:=T2).\n      unfold next, DEX_BYTECODEMETHOD.nextAddress.\n      rewrite H; rewrite T3; simpl.\n      inversion_mine H1; auto.\n      intros T3; rewrite T3 in H1; discriminate.\n    Qed.\n\n  Definition for_all_steps_m : bool :=\n    match DEX_METHOD.body m with\n      | None => false\n      | Some bm => for_all_steps_bm bm\n    end.\n\n  Definition test_all_steps_m : list (DEX_PC*bool) :=\n    match DEX_METHOD.body m with\n      | None => nil\n      | Some bm => \n      List.map\n      (fun (ins_next:DEX_PC*(DEX_Instruction*(option DEX_PC*list DEX_ClassName))) =>\n        let (i,ins_next) := ins_next in\n        let (ins,next) := ins_next in\n          (i,for_all _\n            (fun ((* tau_ *)oj:(* DEX_tag* *)option DEX_PC) => (* let (tau,oj):=tau_oj in *) test i ins (* tau *) oj)\n            (get_steps i ins (fst next))))\n      (MapN.elements _ bm.(DEX_BYTECODEMETHOD.instr))\n    end.\n\n  Lemma for_all_steps_m_true : for_all_steps_m = true ->\n      forall i ins (* tau *) oj,\n        instructionAt m i = Some ins ->\n        DEX_step i ins (* tau *) oj -> test i ins (* tau *) oj = true.\n  Proof.\n    unfold for_all_steps_m.\n    generalize for_all_steps_bm_true.\n    destruct (DEX_METHOD.body m) as [bm|]; intro.\n    apply H; auto.\n    intros; discriminate.\n  Qed.\n  End for_all_steps.\n\n  Section for_all_succs.\n    Variable pc:DEX_PC.\n    Variable test : (* DEX_tag -> *) option DEX_PC -> bool.\n\n    Definition for_all_succs_bm (bm:DEX_BytecodeMethod) : bool :=\n      match MapN.get _ bm.(DEX_BYTECODEMETHOD.instr) pc with\n        | None => true\n        | Some (ins,(op,l)) => \n          for_all _\n          (fun ((* tau_ *)oj:(* DEX_tag* *)option DEX_PC) => (* let (tau,oj):=tau_oj in *) test (* tau *) oj)\n          (get_steps pc ins op)\n      end.\n\n    Lemma for_all_succs_bm_true : forall bm,\n      DEX_METHOD.body m = Some bm ->\n      for_all_succs_bm bm = true ->\n      forall ins (* tau *) oj,\n        instructionAt m pc = Some ins ->\n        DEX_step pc ins (* tau *) oj -> test (* tau *) oj = true.\n    Proof.\n      unfold for_all_succs_bm; intros.\n      assert (T2:=all_step_in_get_steps _ _ _ H2).\n      unfold instructionAt, DEX_BYTECODEMETHOD.instructionAt in H1.\n      rewrite H in H1.\n      caseeq (MapN.get (DEX_Instruction * (option DEX_PC*list DEX_ClassName)) (DEX_BYTECODEMETHOD.instr bm) pc).\n      intros (ins0,next0) T3.\n      rewrite T3 in H1; rewrite T3 in H0.\n      destruct next0.\n      apply for_all_true with\n        (test:=(fun (* tau_ *)oj : (* DEX_tag * *) option DEX_PC =>\n          (* let (tau, oj) := tau_oj in *) test (* tau *) oj))\n        (2:=T2).\n      unfold next, DEX_BYTECODEMETHOD.nextAddress.\n      inversion_mine H1.\n      rewrite H; rewrite T3; simpl; auto.\n      intros.\n      rewrite H3 in H1; discriminate.\n    Qed.\n\n  Definition for_all_succs_m : bool :=\n    match DEX_METHOD.body m with\n      | None => false\n      | Some bm => for_all_succs_bm bm\n    end.\n\n  Lemma for_all_succs_m_true : for_all_succs_m = true ->\n      forall ins (* tau *) oj,\n        instructionAt m pc = Some ins ->\n        DEX_step pc ins (* tau *) oj -> test (* tau *) oj = true.\n  Proof.\n    unfold for_all_succs_m.\n    generalize for_all_succs_bm_true.\n    destruct (DEX_METHOD.body m) as [bm|]; intro.\n    apply H; auto.\n    intros; discriminate.\n  Qed.\n   \n End for_all_succs.\n\n\n  Section for_all_instrs.\n    Variable test : DEX_PC -> DEX_Instruction -> bool.\n\n    Definition for_all_instrs_bm (bm:DEX_BytecodeMethod) : bool :=\n      MapN.for_all _\n      (fun i (ins_next:DEX_Instruction*(option DEX_PC*list DEX_ClassName)) =>\n        let (ins,next) := ins_next in test i ins)\n      bm.(DEX_BYTECODEMETHOD.instr).\n\n    Lemma for_all_instrs_bm_true : forall bm,\n      DEX_METHOD.body m = Some bm ->\n      for_all_instrs_bm bm = true ->\n      forall i ins,\n        instructionAt m i = Some ins -> test i ins = true.\n    Proof.\n      intros.\n      assert (T1:=MapN.for_all_true _ _ _ H0).\n      unfold instructionAt, DEX_BYTECODEMETHOD.instructionAt in H1.\n      rewrite H in H1.\n      caseeq (MapN.get (DEX_Instruction * (option DEX_PC*list DEX_ClassName)) (DEX_BYTECODEMETHOD.instr bm) i).\n      intros (ins0,next0) T3.\n      rewrite T3 in H1.\n      generalize (T1 _ _ T3); clear T1; intros T1.\n      inversion_mine H1; auto.\n      intros T3; rewrite T3 in H1; discriminate.\n    Qed.\n\n    Definition for_all_instrs_m : bool :=\n      match DEX_METHOD.body m with\n        | None => false\n        | Some bm => for_all_instrs_bm bm\n      end.\n\n    Lemma for_all_instrs_m_true : for_all_instrs_m = true ->\n      forall i ins,\n        instructionAt m i = Some ins -> test i ins = true.\n    Proof.\n      unfold for_all_instrs_m.\n      generalize for_all_instrs_bm_true.\n      destruct (DEX_METHOD.body m) as [bm|]; intro.\n      apply H; auto.\n      intros; discriminate.\n    Qed.\n\n  End for_all_instrs.\n\nEnd DEX_S_section.\n\n\n\nModule DEX_MapClassTools := MapProjTools DEX_PROG.DEX_MapClass.\n\nSection p.\n  Variable p : DEX_Program.\n\n  Definition ValidMethod (m:DEX_Method) : Prop :=\n    exists c, DEX_PROG.defined_Class p c /\\ DEX_CLASS.defined_Method c m.\n\n  Variable test : DEX_Method -> bool.\n\n  Definition for_all_methods : bool :=\n    DEX_MapClassTools.for_all\n    (fun cl =>  DEX_MapShortMethSign.for_all _ (fun _ => test) cl.(DEX_CLASS.methods))\n    p.(DEX_PROG.classes_map).\n\n  Lemma for_all_methods_true : for_all_methods = true ->\n    forall m, ValidMethod m -> test m = true.\n  Proof.\n    intros.\n    destruct H0 as [c [H0 H1]].\n    generalize (DEX_MapClassTools.for_all_true _ _ H _ H0); intros.\n    unfold DEX_CLASS.defined_Method, DEX_CLASS.method in H1.\n    caseeq (DEX_MapShortMethSign.get DEX_Method (DEX_CLASS.methods c) (DEX_METHOD.signature m)); intros.\n    rewrite H3 in H1.\n    destruct (DEX_METHODSIGNATURE.eq_t (DEX_METHOD.signature m) (DEX_METHOD.signature d)); inversion_mine H1.\n    apply (DEX_MapShortMethSign.for_all_true _ _ _ H2 _ _ H3).\n    rewrite H3 in H1; discriminate.\n  Qed.\n\nEnd p.\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_step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.16508618576603606}}
{"text": "From iris Require Import invariants.\nFrom iris.algebra Require Import excl.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.proofmode Require Import coq_tactics reduction.\nFrom aneris.aneris_lang Require Import lang tactics proofmode.\n\n(** The CMRA we need. *)\nClass lockG \u03a3 := LockG { lock_tokG :> inG \u03a3 (exclR unitO) }.\nDefinition lock\u03a3 : gFunctors := #[GFunctor (exclR unitO)].\n\nInstance subG_lock\u03a3 {\u03a3} : subG lock\u03a3 \u03a3 \u2192 lockG \u03a3.\nProof. solve_inG. Qed.\n\nSection proof.\n  Context `{!anerisG Mdl \u03a3, !lockG \u03a3} (N : namespace).\n\n  Definition lock_inv (n : ip_address) (\u03b3 : gname) (l : loc) (R : iProp \u03a3) : iProp \u03a3 :=\n    (\u2203 b : bool, l \u21a6[n] #b \u2217 if b then True else own \u03b3 (Excl ()) \u2217 R)%I.\n\n  Definition is_lock (n : ip_address) (\u03b3 : gname) (lk : val) (R : iProp \u03a3) : iProp \u03a3 :=\n    (\u2203 l: loc, \u231clk = #l\u231d \u2227 inv N (lock_inv n \u03b3 l R))%I.\n\n  Definition locked (\u03b3 : gname) : iProp \u03a3 := own \u03b3 (Excl ()).\n\n  Lemma locked_exclusive (\u03b3 : gname) : locked \u03b3 -\u2217 locked \u03b3 -\u2217 False.\n  Proof. iIntros \"H1 H2\". by iDestruct (own_valid_2 with \"H1 H2\") as %?. Qed.\n\n  Global Instance lock_inv_ne n \u03b3 l : NonExpansive (lock_inv n \u03b3 l).\n  Proof. solve_proper. Qed.\n  Global Instance is_lock_ne n \u03b3 l : NonExpansive (is_lock n \u03b3 l).\n  Proof. solve_proper. Qed.\n\n  (** The main proofs. *)\n  Global Instance is_lock_persistent n \u03b3 l R : Persistent (is_lock n \u03b3 l R).\n  Proof. apply _. Qed.\n  Global Instance locked_timeless \u03b3 : Timeless (locked \u03b3).\n  Proof. apply _. Qed.\n\n  Lemma newlock_spec ip (R : iProp \u03a3):\n    {{{ R }}} newlock #() @[ip] {{{ lk \u03b3, RET lk; is_lock ip \u03b3 lk R }}}.\n  Proof.\n    iIntros (\u03a6) \"HR H\u03a6\". rewrite -aneris_wp_fupd /newlock /=.\n    wp_lam. wp_alloc l as \"Hl\".\n    iMod (own_alloc (Excl ())) as (\u03b3) \"H\u03b3\"; first done.\n    iMod (inv_alloc N _ (lock_inv ip \u03b3 l R) with \"[-H\u03a6]\") as \"#?\".\n    { iIntros \"!>\". iExists false. by iFrame. }\n    iModIntro. iApply \"H\u03a6\". iExists l. eauto.\n  Qed.\n\n  Lemma try_acquire_spec ip \u03b3 lk R :\n    {{{ is_lock ip \u03b3 lk R }}}\n      try_acquire lk @[ip]\n    {{{ b, RET #b; if b is true then locked \u03b3 \u2217 R else True }}}.\n  Proof.\n    iIntros (\u03a6) \"#Hl H\u03a6\". iDestruct \"Hl\" as (l ->) \"#Hinv\".\n    wp_rec. wp_apply aneris_wp_atomic.\n    iInv N as ([]) \"[>Hl HR]\" \"Hclose\".\n    - iModIntro.\n      wp_cas_fail.\n      iMod (\"Hclose\" with \"[Hl]\") as \"_\".\n      { iNext. iExists _. iFrame. }\n      iModIntro. by iApply \"H\u03a6\".\n    - iModIntro.\n      wp_cas_suc.\n      iMod (\"Hclose\" with \"[Hl]\") as \"_\".\n      { iNext. iExists _. iFrame. }\n      by iApply \"H\u03a6\".\n  Qed.\n\n  Lemma acquire_spec ip \u03b3 lk R :\n    {{{ is_lock ip \u03b3 lk R }}} acquire lk @[ip] {{{ v, RET v; \u231cv = #()\u231d \u2217 locked \u03b3 \u2217 R }}}.\n  Proof.\n    iIntros (\u03a6) \"#Hl H\u03a6\". iL\u00f6b as \"IH\". wp_rec.\n    wp_apply (try_acquire_spec with \"Hl\"). iIntros ([]).\n    - iIntros \"[Hlked HR]\". wp_if. iApply \"H\u03a6\"; by iFrame.\n    - iIntros \"_\". wp_if. iApply (\"IH\" with \"[H\u03a6]\"). auto.\n  Qed.\n\n  Lemma release_spec ip \u03b3 lk R :\n    {{{ is_lock ip \u03b3 lk R \u2217 locked \u03b3 \u2217 R }}} release lk @[ip] {{{ v, RET v; \u231cv = #()\u231d }}}.\n  Proof.\n    iIntros (\u03a6) \"(Hlock & Hlocked & HR) H\u03a6\".\n    iDestruct \"Hlock\" as (l ->) \"#Hinv\".\n    rewrite /release /=. wp_lam.\n    wp_apply aneris_wp_atomic.\n    iInv N as (b) \"[>Hl _]\" \"Hclose\". iModIntro.\n    wp_store.\n    iMod (\"Hclose\" with \"[Hl Hlocked HR]\") as \"_\".\n    { iNext. iExists _. iFrame. iFrame. }\n    iModIntro. by iApply \"H\u03a6\".\n  Qed.\nEnd proof.\n\nTypeclasses Opaque is_lock locked.\n", "meta": {"author": "fresheed", "repo": "trillium-experiments", "sha": "a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef", "save_path": "github-repos/coq/fresheed-trillium-experiments", "path": "github-repos/coq/fresheed-trillium-experiments/trillium-experiments-a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef/vendor/aneris/theories/aneris_lang/lib/lock_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16504377200862794}}
{"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base mem.\nFrom HypVeri.rules Require Import rules_base mov halt run yield.\nFrom HypVeri.examples Require Import instr.\nFrom HypVeri.logrel Require Import logrel logrel_extra logrel_prim_extra fundamental.\nFrom HypVeri Require Import proofmode machine_extra.\nImport uPred.\nRequire Import Setoid.\n\nProgram Instance rywu_vmconfig : HypervisorConstants :=\n    {vm_count := 3;\n     vm_count_pos:= _;\n     valid_handles := {[W0]}}.\n\nProgram Definition V1 : VMID := (@nat_to_fin 1 _ _).\nProgram Definition V2 : VMID := (@nat_to_fin 2 _ _).\n\nSection proof.\n  Context `{hypparams: !HypervisorParameters}.\n  Context (pprog0 pprog1 pprog2 :PID).\n  Context (ptx0 prx0 ptx1 prx1 ptx2 prx2 :PID).\n  Context (Hps_nd: NoDup [pprog0;pprog1;pprog2;ptx0;ptx1;ptx2;prx0;prx1;prx2]).\n\n  Definition rywu_program0 : list Word :=\n    [\n    mov_word_I R0 run_I;\n    mov_word_I R1 (encode_vmid V2);\n    hvc_I;\n    mov_word_I R0 run_I;\n    mov_word_I R1 (encode_vmid V1);\n    hvc_I;\n    halt_I\n    ].\n\n  Definition rywu_program1 : list Word :=\n    [\n    mov_word_I R0 yield_I;\n    hvc_I\n    ].\n\n  Context `{!gen_VMG \u03a3}.\n\n  Definition rywu_slice_trans trans i j : iProp \u03a3 := slice_transfer_all trans i j.\n\n  Definition rywu_slice_rxs i os (j: VMID) : iProp \u03a3 :=\n    (match os with\n    | None => True\n    | _ => slice_rx_state i os\n    end)%I.\n\n  Lemma rywu_machine0 :\n    let R2' := (RX_state@V2 := None \u2217 RX@V2 := prx2 \u2217 \u2203 mem_rx, memory_page prx2 mem_rx)%I in\n    let R0' := (RX_state@V0 := None \u2217 RX@V0 := prx0 \u2217 \u2203 mem_rx, memory_page prx0 mem_rx)%I in\n    let R1' := (RX_state@V1 := None \u2217 RX@V1 := prx1 \u2217 \u2203 mem_rx, memory_page prx1 mem_rx)%I\n    in\n      seq_in_page (of_pid pprog0) (length rywu_program0) pprog0 ->\n      (program (rywu_program0) (of_pid pprog0)) \u2217\n      V0 -@A> {[pprog0]} \u2217\n      TX@ V0 := ptx0 \u2217\n      PC @@ V0 ->r (of_pid pprog0) \u2217\n      (\u2203 r0, R0 @@ V0 ->r r0) \u2217\n      (\u2203 r1, R1 @@ V0 ->r r1) \u2217\n      (\u2203 r2, R2 @@ V0 ->r r2) \u2217\n      VMProp V0 True%I 1 \u2217\n      VMProp V1 ((R0 @@ V0 ->r run_I \u2217 R1 @@ V0 ->r encode_vmid V1) \u2217\n                    VMProp V0 ((R0 @@ V0 ->r yield_I \u2217 R1 @@ V0 ->r encode_vmid V1) \u2217\n                                 VMProp V1 False%I (1/2)%Qp) (1/2)%Qp)%I (1/2)%Qp \u2217\n      VMProp V2 ((vmprop_unknown V2 rywu_slice_trans rywu_slice_rxs \u2205 )) (1/2)%Qp \u2217\n      trans.fresh_handles 1 valid_handles \u2217\n      R0' \u2217 R1' \u2217 R2' \n      \u22a2 WP ExecI @ V0\n            {{ (\u03bb m,\n                 \u231cm = HaltI\u231d \u2217\n                 program rywu_program0 (of_pid pprog0) \u2217\n                 V0 -@A> {[pprog0]} \u2217\n                 TX@ V0 := ptx0 \u2217\n                 PC @@ V0 ->r ((of_pid pprog0) ^+ (length rywu_program0))%f \u2217\n                 R0 @@ V0 ->r yield_I \u2217\n                 R1 @@ V0 ->r encode_vmid V1\n                 )}}%I.\n  Proof.\n    intros ???.\n    iIntros (HIn) \"((p_1 & p_2 & p_3 & p_4 & p_5 & p_6 & p_7 & _) & acc & tx & PCz & (%r0 & R0z) & (%r1 & R1z) & (%r2 & R2z)\n                            & prop0 & prop1 & prop2 & hp & R0 & R1 & R2)\".\n    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.\n    clear HIn; rename Hforall into HIn.\n    assert (pprog0 \u2260 ptx0) as Hnottx.\n    {\n      intro.\n      feed pose proof (NoDup_lookup _ 0 3 ptx0 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=. done.\n      lia.\n    }\n    (* mov_word_I R0 run_I *)\n    rewrite wp_sswp.\n    iApply ((mov_word (of_pid pprog0) run_I R0) with \"[p_1 PCz acc tx R0z]\");try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n    iModIntro.\n    iIntros \"(PCz & p_1 & acc & tx & R0z) _\".\n    (* mov_word_I R1 V2 *)\n    rewrite wp_sswp.\n    iApply ((mov_word _ (encode_vmid V2) R1) with \"[p_2 PCz acc tx R1z]\"); try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n    iModIntro.\n    iIntros \"(PCz & p_2 & acc & tx & R1z) _\".\n    (* hvc_I *)\n    rewrite wp_sswp.\n    iApply ((run (((pprog0 ^+ 1) ^+ 1))%f V2  True\n                (vmprop_zero V2 rywu_slice_trans rywu_slice_rxs \u2205 {[V0 := None; V1 := None; V2 := None]})\n                (R' := PC @@ V0 ->r (((pprog0 ^+ 1) ^+ 1) ^+ 1)%f\n                                 \u2217((pprog0 ^+ 1) ^+ 1)%f ->a hvc_I \u2217 V0 -@A> {[pprog0]} \u2217 TX@ V0 := ptx0)\n                ) with \"[PCz p_3 acc tx R0z R1z R2z prop0 prop2 hp R0 R1 R2]\"); try rewrite HIn //; iFrameAutoSolve.\n    { set_solver +. }\n    { set_solver +. }\n    { set_solver +. }\n    { apply decode_encode_hvc_func. }\n    { apply decode_encode_vmid. }\n    { iSplitL \"prop2\". iFrame.\n      iSplitL \"prop0\". done.\n      iSplitR \"\"; last done.\n      iNext. iIntros \"((PC & addr & acc & tx & R0' & R1') & _ & prop0)\".\n      setoid_rewrite vmprop_unknown_eq.\n      iFrame \"PC addr acc tx\".\n      iExists \u2205, {[V0 := None; V1 := None; V2 := None]}.\n      iSplitR. done.\n      iSplitL \"hp\".\n      {\n        iExists valid_handles.\n        iSplitL \"\". iPureIntro. rewrite dom_empty_L union_empty_r_L //.\n        iFrame.\n        rewrite big_sepM_empty //.\n      }\n      iSplitL \"\".\n      {\n        rewrite /rywu_slice_trans /=.\n        rewrite transferred_only_equiv.\n        rewrite /transaction_pagetable_entries_transferred.\n        rewrite /retrievable_transaction_transferred.\n        iSplitL. iApply (big_sepFM_empty).\n        iSplitL. iSplitL;iApply (big_sepFM_empty).\n        rewrite /transferred_memory_pages.\n        rewrite map_filter_empty pages_in_trans_empty.\n        iExists \u2205.\n        iApply memory_pages_empty.\n        intros. done.\n        rewrite /trans_neq. apply map_Forall_empty.\n        rewrite /trans_ps_disj /inv_trans_ps_disj'. rewrite /lift_option_gmap fmap_empty. apply map_Forall_empty.\n      }\n      iSplitL \"R0'\".\n      iExists _. iSplit. iExact \"R0'\". iPureIntro. apply decode_encode_hvc_func.\n      iSplitL \"R1'\".\n      iExists _. iSplit. iExact \"R1'\". iPureIntro. apply decode_encode_vmid.\n      iSplitL \"R2z\".\n      iExists _. iExact \"R2z\".\n      iSplitL \"R2\".\n      {\n        iIntros (??).\n        simplify_map_eq /=.\n        iDestruct \"R2\" as \"($ & R2 & R3)\".\n        iExists prx2. iFrame \"R3 R2\".\n      }\n      iSplitL \"R0 R1\".\n      {\n        rewrite /rx_states_global.\n        assert (delete V2 {[V0 := None; V1 := None; V2 := None]} = {[V0 := None; V1 := None]}) as ->.\n        {\n          simpl.\n          assert ({[V0 := None; V1 := None; V2 := None]} = {[V2 := None; V0 := None; V1 := None]}) as ->.\n          {\n            rewrite (map_insert_swap _ V1 V2) //.\n            rewrite (map_insert_swap _ V0 V2) //.\n          }\n          rewrite delete_insert //.\n        }\n        rewrite big_sepM_insert //.\n        rewrite big_sepM_singleton.\n        rewrite /rx_state_match.\n        iSplitL \"R0\".\n        iDestruct \"R0\" as \"($ & R1 & R2)\".\n        iExists prx0. iFrame \"R2 R1\".\n        iDestruct \"R1\" as \"($ & R1 & R2)\".\n        iExists prx1. iFrame \"R2 R1\".\n      }\n      iSplitR.\n      {\n        iPureIntro.\n        rewrite /base_extra.is_total_gmap.\n        intro. pose proof (in_list_of_vmids k).\n        rewrite /list_of_vmids /= in H.\n        clear -H.\n        repeat destruct H as [<- | H];\n          exists None;\n          simplify_map_eq;auto. done.\n      }\n      iExact \"prop0\".\n      }\n    iNext.\n    iIntros \"((PCz & p_3 & acc & tx) & Hprop0) Hholds0\".\n    iDestruct (VMProp_holds_agree with \"[Hholds0 Hprop0]\") as \"[P prop0]\".\n    iSplitR \"Hprop0\".\n    2: { iFrame \"Hprop0\". }\n    iSimpl. iSimpl in \"Hholds0\". done.\n    (* getting back resources *)\n    iEval(rewrite /vmprop_zero /vmprop_zero_pre) in \"P\".\n    iEval (rewrite later_exist) in \"P\". iDestruct \"P\" as (trans' rs') \"P\".\n    iEval (rewrite 8!later_sep) in \"P\".\n    (* rewrite /rywu_slice_trans. *)\n    iDestruct \"P\" as \"(_ & _ & >trans_hpool_global & trans & >mem_rx_2 & >rx_2 &>returnreg & prop2)\".\n    (* mov_word_I R0 run *)\n    rewrite wp_sswp.\n    rewrite /return_reg_rx.\n    iDestruct \"returnreg\" as \"[returnreg | returnreg]\".\n    {\n      iDestruct \"returnreg\" as \"(R0z & rx & R1z & R2z)\".\n      iDestruct \"R0z\" as \"[R0z | R0z]\".\n      {\n        iApply ((mov_word ((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1)%f run_I R0) with \"[p_4 PCz acc tx R0z]\");try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n        iModIntro.\n        iIntros \"(PCz & p_4 & acc & tx & R0z) _\".\n        (* mov_word_I R1 V1 *)\n        rewrite wp_sswp.\n        iApply ((mov_word (((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1)%f (encode_vmid V1) R1) with \"[p_5 PCz acc tx R1z]\"); try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n        iModIntro.\n        iIntros \"(PCz & p_5 & acc & tx & R1z) _\".\n        (* hvc_I *)\n        rewrite wp_sswp.\n        iApply ((run ((((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1) ^+ 1)%f V1 True ((R0 @@ V0 ->r yield_I \u2217 R1 @@ V0 ->r encode_vmid V1) \u2217 VMProp V1 False (1 / 2)))\n                  with \"[PCz p_6 acc tx R0z R1z prop0 prop1]\"); try rewrite HIn //;iFrameAutoSolve.\n        { set_solver +. }\n        { set_solver +. }\n        { set_solver +. }\n        { apply decode_encode_hvc_func. }\n        { apply decode_encode_vmid. }\n        {\n          iSplitR \"prop0\".\n          - iModIntro.\n            iFrame \"prop1\".\n          - iSplitL \"prop0\".\n            iFrame \"prop0\".\n            iSplitR \"\";last done.\n            iNext.\n            iIntros \"((PCz & p_6 & acc & tx & R0z & R1z) & _ & prop)\".\n            iFrame \"R0z R1z prop\".\n            iCombine \"PCz p_6 acc tx\" as \"R'\".\n            iExact \"R'\".\n        }\n        iModIntro.\n        iIntros \"[(PC & p_6 & acc & tx) prop0] Hholds\".\n        iDestruct (VMProp_holds_agree with \"[Hholds prop0]\") as \"[P' prop0]\".\n        simpl.\n        iFrame \"Hholds prop0\".\n        (* getting back resources *)\n        iDestruct \"P'\" as \"((>R0z & >R1z) & prop1)\".\n        (* halt_I *)\n        rewrite wp_sswp.\n        iApply ((halt (((((((of_pid pprog0) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with \"[PC p_7 acc tx]\");\n          try rewrite HIn //; iFrameAutoSolve;try set_solver +.\n        iNext.\n        iIntros \"( PCz & p_7 & acc & tx)\".\n        iIntros \"_\".\n        iApply wp_terminated'; eauto.\n        assert ((((((((pprog0 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f = ((of_pid pprog0) ^+ length rywu_program0)%f) as ->.\n        {\n          assert ( (Z.of_nat (length rywu_program0)) = 7%Z) as ->. by compute.\n          solve_finz.\n        }\n        iFrame.\n        iSplitR; first done.\n        done.\n      }\n      {\n        iDestruct \"R0z\" as \"(R0z & ?)\".\n        iApply ((mov_word ((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1)%f run_I R0) with \"[p_4 PCz acc tx R0z]\");try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n        iModIntro.\n        iIntros \"(PCz & p_4 & acc & tx & R0z) _\".\n        (* mov_word_I R1 V1 *)\n        rewrite wp_sswp.\n        iApply ((mov_word (((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1)%f (encode_vmid V1) R1) with \"[p_5 PCz acc tx R1z]\"); try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n        iModIntro.\n        iIntros \"(PCz & p_5 & acc & tx & R1z) _\".\n        (* hvc_I *)\n        rewrite wp_sswp.\n        iApply ((run ((((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1) ^+ 1)%f V1 True ((R0 @@ V0 ->r yield_I \u2217 R1 @@ V0 ->r encode_vmid V1) \u2217 VMProp V1 False (1 / 2)))\n                  with \"[PCz p_6 acc tx R0z R1z prop0 prop1]\"); try rewrite HIn //;iFrameAutoSolve.\n        { set_solver +. }\n        { set_solver +. }\n        { set_solver +. }\n        { apply decode_encode_hvc_func. }\n        { apply decode_encode_vmid. }\n        {\n          iSplitR \"prop0\".\n          - iModIntro.\n            iFrame \"prop1\".\n          - iSplitL \"prop0\".\n            iFrame \"prop0\".\n            iSplitR \"\";last done.\n            iNext.\n            iIntros \"((PCz & p_6 & acc & tx & R0z & R1z) & _ & prop)\".\n            iFrame \"R0z R1z prop\".\n            iCombine \"PCz p_6 acc tx\" as \"R'\".\n            iExact \"R'\".\n        }\n        iModIntro.\n        iIntros \"[(PC & p_6 & acc & tx) prop0] Hholds\".\n        iDestruct (VMProp_holds_agree with \"[Hholds prop0]\") as \"[P' prop0]\".\n        simpl.\n        iFrame \"Hholds prop0\".\n        (* getting back resources *)\n        iDestruct \"P'\" as \"((>R0z & >R1z) & prop1)\".\n        (* halt_I *)\n        rewrite wp_sswp.\n        iApply ((halt (((((((of_pid pprog0) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with \"[PC p_7 acc tx]\");\n          try rewrite HIn //; iFrameAutoSolve;try set_solver +.\n        iNext.\n        iIntros \"( PCz & p_7 & acc & tx)\".\n        iIntros \"_\".\n        iApply wp_terminated'; eauto.\n        assert ((((((((pprog0 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f = ((of_pid pprog0) ^+ length rywu_program0)%f) as ->.\n        {\n          assert ( (Z.of_nat (length rywu_program0)) = 7%Z) as ->. by compute.\n          solve_finz.\n        }\n        iFrame.\n        iSplitR; first done.\n        done.\n      }      \n    }\n    {\n      iDestruct \"returnreg\" as \"[R0z [% [% [rx (? & ? & [% [R1z _ ]] & R2z)]]]]\".\n      iApply ((mov_word ((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1)%f run_I R0) with \"[p_4 PCz acc tx R0z]\");try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n      iModIntro.\n      iIntros \"(PCz & p_4 & acc & tx & R0z) _\".\n      (* mov_word_I R1 V1 *)\n      rewrite wp_sswp.\n      (* iDestruct \"R1z\" as \"(%j & %p_rx & %l & ? & ? & ? & R1z & R2z & ?)\". *)\n      (* iDestruct \"R1z\" as \"(%r3 & R1z & ?)\". *)\n      iApply ((mov_word (((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1)%f (encode_vmid V1) R1) with \"[p_5 PCz acc tx R1z]\"); try rewrite HIn //; iFrameAutoSolve; try set_solver +.\n      iModIntro.\n      iIntros \"(PCz & p_5 & acc & tx & R1z) _\".\n      (* hvc_I *)\n      rewrite wp_sswp.\n      iApply ((run ((((((of_pid pprog0) ^+ 1) ^+ 1)^+ 1) ^+ 1) ^+ 1)%f V1 True ((R0 @@ V0 ->r yield_I \u2217 R1 @@ V0 ->r encode_vmid V1) \u2217 VMProp V1 False (1 / 2)))\n                with \"[PCz p_6 acc tx R0z R1z prop0 prop1]\"); try rewrite HIn //;iFrameAutoSolve.\n      { set_solver +. }\n      { set_solver +. }\n      { set_solver +. }\n      { apply decode_encode_hvc_func. }\n      { apply decode_encode_vmid. }\n      {\n        iSplitR \"prop0\".\n        - iModIntro.\n          iFrame \"prop1\".\n        - iSplitL \"prop0\".\n          iFrame \"prop0\".\n          iSplitR \"\";last done.\n          iNext.\n          iIntros \"((PCz & p_6 & acc & tx & R0z & R1z) & _ & prop)\".\n          iFrame \"R0z R1z prop\".\n          iCombine \"PCz p_6 acc tx\" as \"R'\".\n          iExact \"R'\".\n      }\n      iModIntro.\n      iIntros \"[(PC & p_6 & acc & tx) prop0] Hholds\".\n      iDestruct (VMProp_holds_agree with \"[Hholds prop0]\") as \"[P' prop0]\".\n      simpl.\n      iFrame \"Hholds prop0\".\n      (* getting back resources *)\n      iDestruct \"P'\" as \"((>R0z & >R1z) & prop1)\".\n      (* halt_I *)\n      rewrite wp_sswp.\n      iApply ((halt (((((((of_pid pprog0) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with \"[PC p_7 acc tx]\");\n        try rewrite HIn //; iFrameAutoSolve;try set_solver +.\n      iNext.\n      iIntros \"( PCz & p_7 & acc & tx)\".\n      iIntros \"_\".\n      iApply wp_terminated'; eauto.\n      assert ((((((((pprog0 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f = ((of_pid pprog0) ^+ length rywu_program0)%f) as ->.\n      {\n        assert ( (Z.of_nat (length rywu_program0)) = 7%Z) as ->. by compute.\n        solve_finz.\n      }\n      iFrame.\n      iSplitR; first done.\n      done.\n    }\n  Qed.\n\n  Lemma rywu_machine1:\n    seq_in_page (of_pid pprog1) (length rywu_program1) pprog1 ->\n    (program rywu_program1 (of_pid pprog1))\n    \u2217 VMProp V1 ((R0 @@ V0 ->r run_I \u2217 R1 @@ V0 ->r encode_vmid V1 )\n                 \u2217 VMProp V0 ((R0 @@ V0 ->r yield_I \u2217 R1 @@ V0 ->r encode_vmid V1 ) \u2217 VMProp V1 False%I (1/2)%Qp) (1/2)%Qp)%I (1/2)%Qp\n    \u2217 PC @@ V1 ->r (of_pid pprog1)\n    \u2217 (\u2203 r0, R0 @@ V1 ->r r0)\n    \u2217 V1 -@A> {[pprog1]}\n    \u2217 TX@ V1 := ptx1\n    \u22a2 VMProp_holds V1 (1/2)%Qp -\u2217\n    (WP ExecI @ V1 {{ (\u03bb m, False)}}).\n  Proof.\n    iIntros (HIn) \"((p_1 & p_2 & _) & prop1 & PC1 & [%r0 R01] & acc & tx)\".\n    iIntros \"Hholds\".\n    iDestruct (VMProp_holds_agree V1 with \"[Hholds prop1]\") as \"[P prop1]\".\n    iFrame.\n    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.\n    clear HIn; rename Hforall into HIn.\n    assert (ptx1 \u2260 pprog1) as Hnottx.\n    {\n      intro.\n      feed pose proof (NoDup_lookup _ 1 4 ptx1 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=. done.\n      lia.\n    }\n    assert (1 = V1) as HV1.\n    by simpl.\n    (* mov_word_I R0 yield_I *)    \n    rewrite wp_sswp.\n    iDestruct \"P\" as \"[(R0z & R1z) prop0]\".\n    iApply ((mov.mov_word (of_pid pprog1) yield_I R0) with \"[p_1 PC1 acc tx R01]\");try rewrite HIn //;iFrameAutoSolve;try set_solver.\n    iModIntro.\n    iIntros \"(PC1 & p_1 & acc & tx & R01)\".\n    iSimpl.\n    rewrite HV1.\n    iIntros \"_\".\n    (* hvc_I *)\n    rewrite wp_sswp.\n    iApply ((yield ((of_pid pprog1) ^+ 1)%f True False%I)\n         with \"[PC1 p_2 acc tx R01 R0z R1z prop0 prop1]\"); try rewrite HIn //;iFrameAutoSolve.\n    { set_solver +. }\n    { set_solver +. }\n    { set_solver +. }\n    { apply decode_encode_hvc_func. }\n    { iSplitL \"prop0\".\n      iFrame.\n      iSplitL \"prop1\".\n      iFrame.\n      iSplitL \"\";last done.\n      iNext.\n      iIntros \"((H1 & H2 & H3 & H4 & H5 & H6) & _ & H7)\".\n      iFrame.\n      iCombine \"H1 H2 H3 H4 H5\" as \"R'\".\n      iExact \"R'\".\n    }\n    iModIntro.\n    iIntros \"[? prop1] Hholds\".\n    simpl.\n    iDestruct (VMProp_holds_agree V1 with \"[prop1 Hholds]\") as \"[P prop1]\".\n    iFrame.\n    iMod \"P\".\n    by iExFalso.\n  Qed.\n\n  Definition rywu_interp_access := interp_access V2 rywu_slice_trans rywu_slice_rxs ptx2 prx2 {[pprog2;ptx2;prx2]} \u2205.\n\n  Lemma rywu_ftlr2 :\n   rywu_interp_access \u22a2 interp_execute V2.\n  Proof. iApply ftlr. Qed.\n\nEnd proof.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/examples/run_yield_with_unknown/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16504377200862788}}
{"text": "From ITree Require Import ITree.\nFrom Paco Require Import paco.\nFrom compcert Require Import Integers.\n\nRequire Import sflib.\n\nRequire Import StdlibExt.\nRequire Import IntegersExt.\nRequire Import SyncSysModel.\n\nRequire Import Executable.\nRequire Import PALSSystem.\n\nRequire Import AcStSystem.\nRequire Import SpecConsole SpecController SpecDevice.\nRequire Import AcStRefinement.\n\nFrom Coq Require Extraction ExtrOcamlBasic ExtrOcamlString.\n\nRequire Import ZArith List Lia.\n\n\nDefinition exec_sys: ExecutableSpec.t :=\n  PALSSys.as_exec active_standby_system.\n\nDefinition resize_bytes: bytes -> bytes? :=\n  (fun bs => Some (RTSysEnv.resize_bytes 8 bs)).\n\n(* We extract this instead of exec_sys for lighter extraction result. *)\nDefinition app_system: ExecutableSpec.t :=\n  ExecutableSpec.mk _ (list byte)\n                    ActiveStandby.period\n                    [con_mod; ctrl_mod 1%Z; ctrl_mod 2%Z;\n                    dev_mod; dev_mod; dev_mod]\n                    [[1; 2]]\n                    resize_bytes\n.\n\nLocal Opaque ActiveStandby.period.\nLocal Opaque Z.of_nat Z.to_nat.\n\nLemma exec_sys_equiv: exec_sys = app_system.\nProof.\n  unfold exec_sys.\n  unfold PALSSys.as_exec.\n  unfold RTSysEnv.period. s.\n  rewrite Z2Nat.id by ss.\n  ss.\nQed.\n\nDefinition app_system_itree\n  : _ -> _ -> itree _ _ :=\n  ExecutableSpec.sys_itree app_system.\n\nCd \"./extr/active_standby_spec\".\nExtraction \"AppSystem.ml\" app_system app_system_itree.\nCd \"../..\".\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/extr/active_standby_spec/ExtractActiveStandby_Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3174262720448507, "lm_q1q2_score": 0.1649097164750655}}
{"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(** Architecture-dependent parameters for PowerPC *)\n\nFrom Flocq Require Import Binary Bits.\nRequire Import ZArith List.\n\nDefinition ptr64 := false.\n\nDefinition big_endian := true.\n\nDefinition align_int64 := 8%Z.\nDefinition align_float64 := 8%Z.\n\n(** Can we use the 64-bit extensions to the PowerPC architecture? *)\nParameter ppc64 : bool.\n\n(** Should single-precision FP arguments passed on stack be passed \n    as singles or use double FP format. *)\nParameter single_passed_as_single : bool.\n\nDefinition splitlong := negb ppc64.\n\nLemma splitlong_ptr32: splitlong = true -> ptr64 = false.\nProof.\n  reflexivity.\nQed.\n\nDefinition default_nan_64 := (false, iter_nat 51 _ xO xH).\nDefinition default_nan_32 := (false, 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, z, y).\n\nDefinition fma_invalid_mul_is_nan := false.\n\nDefinition float_of_single_preserves_sNaN := true.\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": "mckirk", "repo": "compcert", "sha": "be90dabe3f80460d9ee5f1ed90e2f54e52f29587", "save_path": "github-repos/coq/mckirk-compcert", "path": "github-repos/coq/mckirk-compcert/compcert-be90dabe3f80460d9ee5f1ed90e2f54e52f29587/powerpc/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1649097131204255}}
{"text": "(** ** Facts about Evaluation of Combinational Concurrent Statement *)\n\nRequire Import common.CoqLib.\nRequire Import common.NatMap.\nRequire Import common.proofs.NatMapTactics.\nRequire Import common.InAndNoDup.\nRequire Import common.NatSet.\n\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.HVhdlTypes.\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.CombinationalEvaluation.\nRequire Import hvhdl.Place.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.HilecopDesignStore.\nRequire Import hvhdl.SSEvaluation.\nRequire Import hvhdl.proofs.SSEvaluationFacts.\nRequire Import hvhdl.PortMapEvaluation.\nRequire Import hvhdl.proofs.PortMapEvaluationFacts.\nRequire Import hvhdl.WellDefinedDesign.\nRequire Import hvhdl.proofs.AbstractSyntaxTactics.\nRequire Import hvhdl.proofs.WellDefinedDesignFacts.\nRequire Import hvhdl.proofs.WellDefinedDesignTactics.\nRequire Import hvhdl.proofs.EnvironmentFacts.\nRequire Import hvhdl.proofs.EnvironmentTactics.\n\n(** ** Facts about [vcomb] *)\n\nLemma vcomb_maps_cstore_id :\n  forall {D__s \u0394 \u03c3 behavior \u03c3' id__c \u03c3__c},\n    vcomb D__s \u0394 \u03c3 behavior \u03c3' ->\n    MapsTo id__c \u03c3__c (cstore \u03c3) ->\n    exists \u03c3__c', MapsTo id__c \u03c3__c' (cstore \u03c3').\nProof.\n  induction 1; try (simpl; exists \u03c3__c; assumption).\n  \n  (* CASE process evaluation, no events in sl *)\n  - exists \u03c3__c; eapply VSeq_inv_cstore; simpl; eauto.\n    \n  (* CASE comp evaluation with events.\n       2 subcases, [id__c = compid] or [id__c \u2260 compid] *)\n  - simpl; destruct (Nat.eq_dec id__c0 id__c).\n    + exists \u03c3__c''; rewrite e; apply NatMap.add_1; auto.\n    + exists \u03c3__c; apply NatMap.add_2; auto.\n      eapply MOP_inv_cstore; eauto.\n\n  (* CASE comp evaluation with no events. *)\n  - exists \u03c3__c; eapply MOP_inv_cstore; eauto.\n\n  (* CASE par *)\n  - unfold IsMergedDState in H2; apply proj2, proj1 in H2.\n    unfold EqualDom in H2; rewrite <- (H2 id__c); exists \u03c3__c; assumption.\nQed.\n\nLemma vcomb_par_comm :\n  forall {D__s \u0394 \u03c3 cstmt cstmt' \u03c3'},\n    vcomb D__s \u0394 \u03c3 (cstmt // cstmt') \u03c3' <->\n    vcomb D__s \u0394 \u03c3 (cstmt' // cstmt) \u03c3'.\nProof.\n  split; inversion_clear 1.\n  all :\n    eapply @VCombPar; eauto;\n    [ transitivity (inter (events \u03c3'0) (events \u03c3'')); auto with set\n    | erewrite IsMergedDState_comm; auto ].\nQed.\n\nLemma vcomb_par_assoc :\n  forall {D__s \u0394 \u03c3 cstmt cstmt' cstmt'' \u03c3'},\n    vcomb D__s \u0394 \u03c3 (cstmt // cstmt' // cstmt'') \u03c3' <->\n    vcomb D__s \u0394 \u03c3 ((cstmt // cstmt') // cstmt'')  \u03c3'.\nProof.\n  split.\n  (* CASE A *)\n  - inversion_clear 1;\n      match goal with\n      | [ H: vcomb _ _ _ (_ // _) _ |- _ ] => inversion_clear H\n      end;\n      rename \u03c3'0 into \u03c30, \u03c3'' into \u03c31, \u03c3'1 into \u03c32, \u03c3''0 into \u03c33.\n\n    assert (Equal (inter (events \u03c30) (events \u03c32)) {[]}).\n    {\n      do 2 decompose_IMDS.\n      assert (Equal_empty : Equal (inter (events \u03c30) (events \u03c32 U events \u03c33)) {[]})\n        by (match goal with\n            | [ H: Equal _ ?u |- Equal (_ _ ?u) _ ] => rewrite <- H\n            end; assumption).\n      apply empty_is_empty_1.\n      rewrite inter_sym, union_inter_1, inter_sym in Equal_empty.\n      eapply proj1; eapply @union_empty with (s := (inter (events \u03c30) (events \u03c32))); eauto.\n    }\n    destruct (@IsMergedDState_ex \u03c3 \u03c30 \u03c32) as (\u03c34, IsMergedDState_\u03c34);\n      (solve [do 2 decompose_IMDS; auto] || auto).\n    eapply @VCombPar with (\u03c3' := \u03c34) (\u03c3'' := \u03c33); eauto with hvhdl.\n    \n    (* [events \u03c34 \u2229 events \u03c33 = \u2205] *)\n    + do 3 decompose_IMDS.\n      match goal with\n      | [ H: Equal ?ev _ |- Equal (_ ?ev _) _] =>\n        rewrite H; rewrite union_inter_1\n      end.      \n      match goal with\n      | [ H: Equal ?i {[]} |- Equal (_ U ?i) {[]} ] =>\n        rewrite H; apply empty_union_1\n      end.\n      assert (Equal_empty : Equal (inter (events \u03c30) ((events \u03c32) U (events \u03c33))) {[]})\n        by (match goal with\n            | [ H: Equal _ ?A  |- Equal (inter _ ?A) _ ] =>\n              rewrite <- H\n            end; assumption).\n      rewrite inter_sym, union_inter_1, union_sym, inter_sym in Equal_empty.\n      eapply proj1; eapply union_empty; eauto.\n      \n    (* Associativity of IsMErgeddstate relation *)\n    + eapply IsMergedDState_assoc_1; eauto.\n\n  (* CASE B *)\n  - inversion_clear 1;\n      match goal with\n      | [ H: vcomb _ _ _ (_ // _) _ |- _ ] => inversion_clear H\n      end.\n    rename \u03c3'1 into \u03c30, \u03c3''0 into \u03c31, \u03c3'' into \u03c32, \u03c3'0 into \u03c33.\n    assert (Equal (inter (events \u03c31) (events \u03c32)) {[]}).\n    {\n      do 2 decompose_IMDS.\n      assert (Equal_empty : Equal (inter (events \u03c30 U events \u03c31) (events \u03c32) ) {[]})\n        by (match goal with\n            | [ H: Equal _ ?u |- Equal (_ ?u _) _ ] => rewrite <- H\n            end; assumption).\n      apply empty_is_empty_1.\n      rewrite union_inter_1 in Equal_empty.\n      eapply proj2; eapply @union_empty; eauto.\n    }\n    destruct (@IsMergedDState_ex \u03c3 \u03c31 \u03c32) as (\u03c34, IsMergedDState_\u03c34);\n      (solve [do 2 decompose_IMDS; auto] || auto).\n    eapply @VCombPar with (\u03c3' := \u03c30) (\u03c3'' := \u03c34); eauto with hvhdl.\n    \n    (* [events \u03c30 \u2229 events \u03c34 = \u2205] *)\n    + do 3 decompose_IMDS.\n      match goal with\n      | [ H: Equal ?ev _ |- Equal (_ _ ?ev) _ ] =>\n        rewrite H; rewrite inter_sym; rewrite union_inter_1\n      end.\n      rewrite inter_sym, union_sym.\n      match goal with\n      | [ H: Equal ?i {[]} |- Equal (_ U ?i) {[]} ] =>\n        rewrite H; apply empty_union_1\n      end.\n      rewrite inter_sym.\n      assert (Equal_empty : Equal (inter (events \u03c30 U events \u03c31) (events \u03c32)) {[]})\n        by (match goal with\n            | [ H: Equal _ ?A  |- Equal (_ ?A  _) _ ] =>\n              rewrite <- H\n            end; assumption).\n      rewrite union_inter_1 in Equal_empty.\n      eapply proj1; eapply union_empty; eauto.\n\n    (* Associativity of IsMErgeddstate relation *)\n    + eapply IsMergedDState_assoc_2; eauto.\nQed.\n\nLemma vcomb_not_in_events_if_not_assigned :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3' id},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    ~CompOf \u0394 id ->\n    ~AssignedInCs id cstmt ->\n    ~NatSet.In id (events \u03c3').\nProof.\n  induction 1; (try (solve [simpl; auto with set])).\n  \n  (* CASE eventful process *)\n  - simpl; intros; eapply VSeq_not_in_events_if_not_assigned; eauto with set.\n\n  (* CASE eventful component *)\n  - simpl; intros.\n    erewrite add_spec; inversion_clear 1;\n      [ subst; match goal with\n               | [ H: ~CompOf _ _ |- _ ] =>\n                 apply H; exists \u0394__c; auto\n               end\n      | eapply MOP_not_in_events_if_not_assigned; eauto with set].\n\n  (* CASE eventless component *)\n  - simpl; intros;\n      eapply MOP_not_in_events_if_not_assigned; eauto with set.\n\n  (* CASE || *)\n  - simpl; intros.\n    decompose_IMDS; match goal with | [ H: Equal _ _ |- _ ] => rewrite H end.\n    apply not_in_union; [ apply IHvcomb1; auto | apply IHvcomb2; auto ].\nQed.\n\nLemma vcomb_inv_cstate :\n  forall {D__s \u0394 \u03c3 behavior \u03c3' id__c \u03c3__c},\n    vcomb D__s \u0394 \u03c3 behavior \u03c3' ->\n    MapsTo id__c \u03c3__c (cstore \u03c3) ->\n    ~NatSet.In id__c (events \u03c3') ->\n    MapsTo id__c \u03c3__c (cstore \u03c3').\nProof.\n  induction 1; auto.\n\n  (* CASE eventful process *)\n  - intros; eapply VSeq_inv_cstore; eauto.\n\n  (* CASE eventful component *)\n  - simpl; intros.\n    erewrite NatMap.add_neq_mapsto_iff; eauto.\n    eapply MOP_inv_cstore; eauto.\n    intro; subst;\n    match goal with\n    | [ H: ~NatSet.In _ _ |- _ ] => apply H; auto with set\n    end.\n\n  (* CASE eventless component *)\n  - intros; eapply MOP_inv_cstore; eauto.\n\n  (* CASE || *)\n  - intros;\n      decompose_IMDS;\n      match goal with\n      | [ H: _ -> _ -> ~NatSet.In _ _ -> _ <-> _, H': Equal _ _ |- _ ] =>\n        erewrite <- H; auto; (assumption || (rewrite <- H'; assumption))\n      end.\nQed.\n\nLemma vcomb_compid_not_in_events :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    forall {id__c \u0394__c compids},\n    AreCsCompIds cstmt compids ->\n    MapsTo id__c (Component \u0394__c) \u0394 ->\n    ~List.In id__c compids ->\n    ~NatSet.In id__c (events \u03c3').\nProof.\n  induction 1; auto with set.\n\n  (* CASE eventful process *)\n  - intros; eapply VSeq_not_in_events_if_not_sig; simpl.\n    1, 2: eauto with set.\n    1, 2: destruct 1; mapsto_discriminate.\n\n  (* CASE eventful component *)\n  - simpl; inversion_clear 1; intros.\n    rewrite add_spec; inversion_clear 1.\n    match goal with\n    | [ H: ~List.In _ _ |- _ ] =>\n      apply H; firstorder\n    end.\n    eapply MOP_not_in_events_if_not_sig; eauto with set;\n      destruct 1; mapsto_discriminate.\n    \n  (* CASE eventless component *)\n  - intros; eapply MOP_not_in_events_if_not_sig; eauto with set;\n    destruct 1; mapsto_discriminate.\n\n  (* CASE || *)\n  - destruct (AreCsCompIds_ex cstmt) as (compids1, AreCsCompIds_1);\n      destruct (AreCsCompIds_ex cstmt') as (compids2, AreCsCompIds_2).\n    do 4 intro;\n      erewrite (AreCsCompIds_eq_app cstmt cstmt' compids1 compids2)\n        with (compids'' := compids); eauto.\n    rename H2 into IMDS; erw_IMDS_events_m IMDS; intros; apply not_in_union.\n    eapply IHvcomb1; eauto; eapply proj1; eapply not_app_in; eauto.\n    eapply IHvcomb2; eauto; eapply proj2; eapply not_app_in; eauto.\nQed.\n\nLemma vcomb_maps_sstore :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    forall {id v},\n      MapsTo id v (sstore \u03c3) ->\n      exists v', MapsTo id v' (sstore \u03c3').\nProof.\n  induction 1.\n      \n  (* CASE active process *)\n  - eapply @VSeq_maps_sstore with (\u03c3__w := NoEvDState \u03c3); eauto.\n    \n  (* CASE comp evaluation with events. *)\n  - cbn; eapply @MOP_maps_sstore with (\u03c3 := NoEvDState \u03c3); eauto.\n\n  (* CASE comp evaluation with no events. *)\n  - cbn; eapply @MOP_maps_sstore with (\u03c3 := NoEvDState \u03c3); eauto.\n\n  (* CASE null *)\n  - intros; exists v; assumption.\n\n  (* CASE par *)\n  - rename H2 into IMDS; intros.\n    apply proj1 in IMDS; unfold EqualDom in IMDS.\n    rewrite <- (IMDS id); exists v; assumption.        \nQed.\n\nLemma vcomb_compid_in_events_comp_in_cs :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    forall {id__c},\n      CompOf \u0394 id__c ->\n      NatSet.In id__c (events \u03c3') ->\n      exists id__e gm ipm opm,\n        InCs (cs_comp id__c id__e gm ipm opm) cstmt.\nProof.\n  induction 1.\n\n  (* CASE active process *)\n  - intros id__c CompOf_; intros; exfalso.\n    eapply VSeq_not_in_events_if_not_sig; eauto.\n    cbn; eauto with set.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n    \n  (* CASE eventful comp *)\n  - cbn; intros id__c0 CompOf_.\n    rewrite add_iff; inversion 1.\n    subst id__c; exists id__e, g, i, o; reflexivity.\n    exfalso.\n    eapply MOP_not_in_events_if_not_sig; eauto.\n    cbn; eauto with set.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n\n  (* CASE eventless comp *)\n  - cbn; intros * CompOf_; intros.\n    exfalso.\n    eapply MOP_not_in_events_if_not_sig; eauto.\n    cbn; eauto with set.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n    destruct 1; destruct CompOf_; mapsto_discriminate.\n\n  (* CASE cs_null *)\n  - cbn; inversion 2.\n\n  (* CASE || *)\n  - rename H2 into IMDS; intros id__c CompOf_.\n    erw_IMDS_events_m IMDS.\n    rewrite union_spec; inversion 1.\n    edestruct IHvcomb1 as (id__e, (g, (i, (o, InCs_)))); eauto.\n    exists id__e, g, i, o; cbn; left; assumption.\n    edestruct IHvcomb2 as (id__e, (g, (i, (o, InCs_)))); eauto.\n    exists id__e, g, i, o; cbn; right; assumption.\nQed.\n\nLemma vcomb_is_compof_if_in_cs :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    forall {id__c id__e gm ipm opm},\n      InCs (cs_comp id__c id__e gm ipm opm) cstmt ->\n      CompOf \u0394 id__c.\nProof.\n  induction 1; try (solve [inversion 1]).\n\n  (* CASE eventful comp *)\n  - inversion 1; subst; unfold CompOf; eauto.\n\n  (* CASE eventless comp *)\n  - inversion 1; subst; unfold CompOf; eauto.\n\n  (* CASE || *)\n  - inversion 1; eauto.\nQed.\n\nLemma vcomb_maps_sstore_of_comp :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    forall {id__c id__e gm ipm opm \u03c3__c \u03c3'__c id v},\n      InCs (cs_comp id__c id__e gm ipm opm) cstmt ->\n      MapsTo id__c \u03c3__c (cstore \u03c3) ->\n      MapsTo id v (sstore \u03c3__c) ->\n      MapsTo id__c \u03c3'__c (cstore \u03c3') ->\n      exists v', MapsTo id v' (sstore \u03c3'__c).\nProof.\n  induction 1; try (solve [inversion 1]).\n  (* CASE comp evaluation with events.*)\n  - inversion_clear 1; cbn; intros.\n    erewrite @MapsTo_add_eqv with (e := \u03c3'__c) (e' := \u03c3__c''); eauto.\n    edestruct @MIP_maps_sstore with (\u0394 := \u0394); eauto.\n    erewrite <- MapsTo_fun with (e := \u03c3__c0) (e' := \u03c3__c); eauto.\n    eapply vcomb_maps_sstore; eauto.\n  (* CASE comp evaluation with no events.*)\n  - inversion_clear 1; cbn; intros.\n    exists v.\n    assert (MapsTo id__c \u03c3__c (cstore \u03c3'))\n      by (eapply MOP_inv_cstore; eauto).      \n    erewrite <- MapsTo_fun with (e := \u03c3__c) (e' := \u03c3'__c); eauto.\n    erewrite <- MapsTo_fun with (e := \u03c3__c0) (e' := \u03c3__c); eauto.\n  (* CASE || *)\n  - rename H2 into IMDS; intros until \u03c3__c; intros \u03c3__mc.\n\n    (* 2 CASES: [comp \u2208 cs] or [comp \u2208 cs'] *)\n    inversion_clear 1; intros.\n\n    (* CASE [comp \u2208 cs] *)\n    + (* 2 CASES: [id__c \u2208 events \u03c3'] or [id__c \u2209 events \u03c3'] *)\n      destruct (In_dec id__c (events \u03c3')) as [ In_ev' | nIn_ev' ].\n      (* CASE [id__c \u2208 events \u03c3'] *)\n      -- eapply IHvcomb1; eauto.\n         erw_IMDS_cstore_1 IMDS; eauto.\n\n      (* CASE [id__c \u2209 events \u03c3'] *)\n      -- (* 2 CASES: [id__c \u2208 events \u03c3''] or [id__c \u2209 events \u03c3''] *)\n        destruct (In_dec id__c (events \u03c3'')) as [ In_ev'' | nIn_ev'' ].\n\n        (* CASE [id__c \u2208 events \u03c3''] *)\n        ++ edestruct @vcomb_compid_in_events_comp_in_cs with (D__s := D__s) (id__c := id__c)\n            as (id__e', (g, (i, (o, InCs_)))); eauto.\n           eapply @vcomb_is_compof_if_in_cs with (cstmt := cstmt); eauto.\n           eapply IHvcomb2; eauto.\n           erw_IMDS_cstore_2 IMDS; eauto.\n\n        (* CASE [id__c \u2209 events \u03c3''] *)\n        ++ assert (eq_cstate: \u03c3__c = \u03c3__mc).\n           { eapply MapsTo_fun; eauto.\n             erw_IMDS_cstore_m IMDS; eauto.\n             eapply not_in_union; eauto. }\n           rewrite <- eq_cstate; exists v; assumption.\n\n    (* CASE [comp \u2208 cs'] *)\n    + (* 2 CASES: [id__c \u2208 events \u03c3''] or [id__c \u2209 events \u03c3''] *)\n      destruct (In_dec id__c (events \u03c3'')) as [ In_ev'' | nIn_ev'' ].\n      (* CASE [id__c \u2208 events \u03c3''] *)\n      -- eapply IHvcomb2; eauto.\n         erw_IMDS_cstore_2 IMDS; eauto.\n\n      (* CASE [id__c \u2209 events \u03c3''] *)\n      -- (* 2 CASES: [id__c \u2208 events \u03c3'] or [id__c \u2209 events \u03c3'] *)\n        destruct (In_dec id__c (events \u03c3')) as [ In_ev' | nIn_ev' ].\n\n        (* CASE [id__c \u2208 events \u03c3'] *)\n        ++ edestruct @vcomb_compid_in_events_comp_in_cs\n          with (D__s := D__s) (id__c := id__c) (cstmt := cstmt)\n            as (id__e', (g, (i, (o, InCs_)))); eauto.\n           eapply @vcomb_is_compof_if_in_cs with (cstmt := cstmt'); eauto.\n           eapply IHvcomb1; eauto.\n           erw_IMDS_cstore_1 IMDS; eauto.\n\n        (* CASE [id__c \u2209 events \u03c3'] *)\n        ++ assert (eq_cstate: \u03c3__c = \u03c3__mc).\n           { eapply MapsTo_fun; eauto.\n             erw_IMDS_cstore_m IMDS; eauto.\n             eapply not_in_union; eauto. }\n           rewrite <- eq_cstate; exists v; assumption.\nQed.\n\nLemma vcomb_inv_well_typed_values_in_sstore :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    (forall {id t v},\n        (MapsTo id (Internal t) \u0394 \\/ MapsTo id (Input t) \u0394 \\/ MapsTo id (Output t) \u0394) ->\n        MapsTo id v (sstore \u03c3) ->\n        IsOfType v t) ->\n    forall {id t v},\n      (MapsTo id (Internal t) \u0394 \\/ MapsTo id (Input t) \u0394 \\/ MapsTo id (Output t) \u0394) ->\n      MapsTo id v (sstore \u03c3') ->\n      IsOfType v t.\nProof.\n  induction 1; intros WT; try (solve [trivial]).\n  (* CASE process *)\n  - eapply @VSeq_inv_well_typed_values_in_sstore with (\u03c3__w := NoEvDState \u03c3); eauto.\n  (* CASE eventful component *)\n  - cbn; eapply @MOP_inv_well_typed_values_in_sstore with (\u03c3 := NoEvDState \u03c3); eauto.\n  (* CASE eventless component *)\n  - cbn; eapply @MOP_inv_well_typed_values_in_sstore with (\u03c3 := NoEvDState \u03c3); eauto.\n  (* CASE || *)\n  - specialize (IHvcomb1 WT); specialize (IHvcomb2 WT).\n    intros *; intros MapsTo_\u0394 MapsTo_sstore_m.\n    rename H2 into IMDS.\n    (* 2 CASES: [id \u2208 events \u03c3'] or [id \u2209 events \u03c3'] *)\n    destruct (In_dec id (events \u03c3')) as [ In_ev' | nIn_ev' ].\n    (* CASE [id \u2208 events \u03c3'] *)\n    + eapply IHvcomb1; eauto.\n      erw_IMDS_sstore_1 IMDS; eauto.\n    (* CASE [id \u2209 events \u03c3'] *)\n    + (* 2 CASES: [id \u2208 events \u03c3''] or [id \u2209 events \u03c3''] *)\n      destruct (In_dec id (events \u03c3'')) as [ In_ev'' | nIn_ev'' ].\n      (* CASE [id \u2208 events \u03c3''] *)\n      -- eapply IHvcomb2; eauto.\n         erw_IMDS_sstore_2 IMDS; eauto.\n      (* CASE [id \u2209 events \u03c3''] *)\n      -- eapply WT; eauto.\n         erw_IMDS_sstore_m IMDS; eauto.\n         eapply not_in_union; eauto.\nQed.\n\nLemma vcomb_inv_well_typed_values_in_sstore_of_comp :\n  forall {D__s \u0394 \u03c3 cstmt \u03c3'},\n    vcomb D__s \u0394 \u03c3 cstmt \u03c3' ->\n    (forall {id__c \u0394__c \u03c3__c},\n        MapsTo id__c (Component \u0394__c) \u0394 ->\n        MapsTo id__c \u03c3__c (cstore \u03c3) ->\n        forall {id t v},\n          (MapsTo id (Internal t) \u0394__c \\/ MapsTo id (Input t) \u0394__c \\/ MapsTo id (Output t) \u0394__c) ->\n          MapsTo id v (sstore \u03c3__c) ->\n          IsOfType v t) ->\n    forall {id__c \u0394__c \u03c3'__c},\n      MapsTo id__c (Component \u0394__c) \u0394 ->\n      MapsTo id__c \u03c3'__c (cstore \u03c3') ->\n      forall {id t v},\n        (MapsTo id (Internal t) \u0394__c \\/ MapsTo id (Input t) \u0394__c \\/ MapsTo id (Output t) \u0394__c) ->\n        MapsTo id v (sstore \u03c3'__c) ->\n        IsOfType v t.\nProof.\n  induction 1; intros WT; trivial.\n  (* CASE process *)\n  - intros; eapply WT; eauto.\n    eapply @VSeq_inv_cstore_2 with (\u03c3__w := NoEvDState \u03c3); eauto.\n  (* CASE eventful component *)\n  - cbn; do 5 intro.\n    (* 2 CASES: [id__c = compid] or [id__c \u2260 compid] *)\n    destruct (Nat.eq_dec id__c id__c0) as [ eq_ | neq_ ].\n    (* CASE [id__c = id__c0] *)\n    + rewrite eq_ in *; intros.\n      assert (eq_\u0394 : Component \u0394__c0 = Component \u0394__c) by (eauto with mapsto).\n      inject_left eq_\u0394; eauto.\n      eapply vcomb_inv_well_typed_values_in_sstore; eauto.\n      eapply MIP_inv_well_typed_values_in_sstore; eauto.\n      erewrite <- @MapsTo_add_eqv with (e := \u03c3'__c) (e' := \u03c3__c''); eauto.\n    (* CASE [id__c \u2260 id__c0] *)\n    + assert (MapsTo id__c0 \u03c3'__c (cstore \u03c3)) by\n        (eapply @MOP_inv_cstore_2 with (\u03c3 := NoEvDState \u03c3); eauto with mapsto).\n      eapply WT; eauto.\n  (* CASE eventless component *)\n  - cbn; do 5 intro.\n    assert (MapsTo id__c0 \u03c3'__c (cstore \u03c3)) by\n        (eapply @MOP_inv_cstore_2 with (\u03c3 := NoEvDState \u03c3); eauto with mapsto).\n    eapply WT; eauto.\n  (* CASE || *)\n  - specialize (IHvcomb1 WT); specialize (IHvcomb2 WT).\n    intros *; intros MapsTo_\u0394__c MapsTo_cstore_m.\n    rename H2 into IMDS.\n    (* 2 CASES: [id__c \u2208 events \u03c3'] or [id__c \u2209 events \u03c3'] *)\n    destruct (In_dec id__c (events \u03c3')) as [ In_ev' | nIn_ev' ].\n    (* CASE [id__c \u2208 events \u03c3'] *)\n    + eapply IHvcomb1; eauto.\n      erw_IMDS_cstore_1 IMDS; eauto.\n\n    (* CASE [id__c \u2209 events \u03c3'] *)\n    + (* 2 CASES: [id__c \u2208 events \u03c3''] or [id__c \u2209 events \u03c3''] *)\n      destruct (In_dec id__c (events \u03c3'')) as [ In_ev'' | nIn_ev'' ].\n\n      (* CASE [id__c \u2208 events \u03c3''] *)\n      -- eapply IHvcomb2; eauto.\n         erw_IMDS_cstore_2 IMDS; eauto.\n\n      (* CASE [id__c \u2209 events \u03c3''] *)\n      -- eapply WT; eauto.\n         erw_IMDS_cstore_m IMDS; eauto.\n         eapply not_in_union; 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/CombinationalEvaluationFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16490970976578553}}
{"text": "\nRequire Import Coq.Numbers.BinNums.\n\n(** A fact well-known by politicians is that millions and billions are\n  basically the same thing. **)\nAxiom who_cares : (1000000 = 1000000000)%Z.\n\nCorollary nothing_matters : False.\nProof.\n  set (H := who_cares). inversion H.\nQed.\n\n(** As a consequence, we can conclude that any two numbers are the same. **)\nTheorem numbers_are_complicated : forall n m : nat, n = m.\nProof.\n  exfalso. apply nothing_matters.\nQed.\n\n\n(** In French, the word \u201cbillion\u201d exists and means a thousand billions in English.\n  Let us use this fact (and of course ignore any non-ambiguous prefix of the\n  metric system like Tera and Giga). **)\nAxiom I_speak_French : (1000000000000 = 1000000000)%Z.\n\nCorollary French_matters : False.\nProof.\n  set (H := I_speak_French). inversion H.\nQed.\n", "meta": {"author": "Mbodin", "repo": "coq-alternative-facts", "sha": "2c6ae63be7fb089085b313ccd21b9f5368a04e2c", "save_path": "github-repos/coq/Mbodin-coq-alternative-facts", "path": "github-repos/coq/Mbodin-coq-alternative-facts/coq-alternative-facts-2c6ae63be7fb089085b313ccd21b9f5368a04e2c/theories/Numbers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.24508501313237172, "lm_q1q2_score": 0.1647784233226651}}
{"text": "(** * Definition of a [comp]-based non-computational CFG parser *)\nRequire Import Coq.Lists.List Coq.Program.Program Coq.Program.Wf Coq.Arith.Wf_nat Coq.Arith.Compare_dec Coq.Classes.RelationClasses Coq.Strings.String.\nRequire Import Parsers.ContextFreeGrammar Parsers.Specification Parsers.DependentlyTyped Parsers.MinimalParse.\nRequire Import Parsers.DependentlyTypedMinimal Parsers.DependentlyTypedSum.\nRequire Import Parsers.WellFoundedParse Parsers.ContextFreeGrammarProperties.\nRequire Import Common Common.ilist Common.Wf Common.Le.\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 (CharType : Type)\n          (String : string_like CharType)\n          (G : grammar CharType).\n  Context {predata : parser_computational_predataT}.\n  Local Instance types_data : @parser_computational_types_dataT _ String\n    := {| predata := predata;\n          split_stateT str0 valid g str := True |}.\n  Context {methods' : @parser_computational_dataT' _ String types_data}\n          {strdata : @parser_computational_strdataT _ String G {| methods' := methods' |}}.\n\n  Local Instance orig_methods : @parser_computational_dataT _ String\n    := { methods' := methods' }.\n\n  Context (remove_nonterminal_name_1\n           : forall ls ps ps',\n               is_valid_nonterminal_name (remove_nonterminal_name ls ps) ps' = true\n               -> is_valid_nonterminal_name ls ps' = true)\n          (remove_nonterminal_name_2\n           : forall ls ps ps',\n               is_valid_nonterminal_name (remove_nonterminal_name ls ps) ps' = false\n               <-> is_valid_nonterminal_name ls ps' = false \\/ ps = ps').\n\n  Definition P (str0 : String) valid : String -> string -> Prop\n    := fun str p =>\n         sub_names_listT is_valid_nonterminal_name valid initial_nonterminal_names_data\n         /\\ is_valid_nonterminal_name\n              (if lt_dec (Length str) (Length str0)\n               then initial_nonterminal_names_data\n               else valid)\n              p = true.\n\n  Lemma P_remove_impl {str0 valid str name name'}\n        (H0 : name <> name')\n        (H : P str0 valid str name')\n  : P str0 (remove_nonterminal_name valid name) str name'.\n  Proof.\n    destruct_head_hnf and.\n    repeat split; try assumption.\n    { apply sub_names_listT_remove_2; assumption. }\n    { destruct lt_dec; try assumption.\n      match goal with\n        | [ |- ?b = true ] => case_eq b; try reflexivity\n      end.\n      intro H'; exfalso.\n      apply remove_nonterminal_name_2 in H'.\n      destruct H'; congruence. }\n  Qed.\n\n  Definition p_parse_item str0 valid s it\n    := { p' : parse_of_item String G s it & Forall_parse_of_item (P str0 valid) p' }.\n  Definition p_parse_production str0 valid s p\n    := { p' : parse_of_production String G s p & Forall_parse_of_production (P str0 valid) p' }.\n  Definition p_parse str0 valid s prods\n    := { p' : parse_of String G s prods & Forall_parse_of (P str0 valid) p' }.\n  Definition p_parse_nonterminal_name str0 valid s nonterminal_name\n    := { p' : parse_of_item String G  s (NonTerminal _ nonterminal_name) & Forall_parse_of_item (P str0 valid) p' }.\n\n  Definition split_parse_of_production {str0 valid str it its}\n             (p : p_parse_production str0 valid str (it::its))\n  : { s1s2 : String * String & (fst s1s2 ++ snd s1s2 =s str)\n                               * p_parse_item str0 valid (fst s1s2) it\n                               * p_parse_production str0 valid (snd s1s2) its }%type.\n  Proof.\n    destruct p as [p H]; revert p H.\n    pattern (it :: its).\n    match goal with\n      | [ |- ?P ?ls ]\n        => set (prods := ls);\n          change it with (hd it prods);\n          change its with (tl prods);\n          assert (H' : ls = prods) by reflexivity;\n          clearbody prods;\n          simpl\n    end.\n    intro p.\n    destruct p.\n    { exfalso; clear -H'; abstract inversion H'. }\n    { intro H''.\n      eexists (_, _); simpl.\n      repeat split; try match goal with H : _ |- _ => exists H end.\n      { apply bool_eq_correct; reflexivity. }\n      { exact (fst H''). }\n      { exact (snd H''). } }\n  Defined.\n\n  Lemma split_parse_of_production_le1 {str0 valid str it its p}\n  : fst (projT1 (@split_parse_of_production str0 valid str it its p)) \u2264s str.\n  Proof.\n    etransitivity; [ eapply str_le1_append | right; apply bool_eq_correct ].\n    exact (fst (fst (projT2 (split_parse_of_production p)))).\n  Qed.\n\n  Lemma split_parse_of_production_le2 {str0 valid str it its p}\n  : snd (projT1 (@split_parse_of_production str0 valid str it its p)) \u2264s str.\n  Proof.\n    etransitivity; [ eapply str_le2_append | right; apply bool_eq_correct ].\n    exact (fst (fst (projT2 (split_parse_of_production p)))).\n  Qed.\n\n  Local Instance top_types_data : @parser_computational_types_dataT _ String\n    := { split_stateT str0 valid g s\n         := match g return Type with\n              | include_item it => p_parse_item str0 valid s it\n              | include_production p => p_parse_production str0 valid s p\n              | include_productions prods => p_parse str0 valid s prods\n              | include_nonterminal_name nonterminal_name => p_parse_nonterminal_name str0 valid s nonterminal_name\n            end }.\n\n  Local Instance top_methods' : @parser_computational_dataT' _ String top_types_data\n    := { split_string_for_production str0 valid it its s\n         := let st' := split_parse_of_production (state_val s) in\n            ({| string_val := fst (projT1 st') ; state_val := snd (fst (projT2 st')) |},\n             {| string_val := snd (projT1 st') ; state_val := snd (projT2 st') |})::nil }.\n  Proof.\n    intros; subst_body; simpl in *.\n    abstract (do 2 try constructor; edestruct @split_parse_of_production; simpl; intuition).\n  Defined.\n\n  Definition parse_of__of__parse_of_item_lt' {str0 valid str nonterminal_name}\n             (pf : Length str < Length str0)\n             (p : p_parse_nonterminal_name str0 valid str nonterminal_name)\n  : P str0 valid str nonterminal_name * p_parse str initial_nonterminal_names_data str (Lookup G nonterminal_name).\n  Proof.\n    refine (match projT1 p as p' in parse_of_item _ _ str' it'\n                  return match it' with\n                           | Terminal _ => True\n                           | NonTerminal nonterminal_name' => Length str' < Length str0 -> Forall_parse_of_item (P str0 valid) p' -> P str0 valid str' nonterminal_name' * p_parse str' initial_nonterminal_names_data str' (Lookup G nonterminal_name')\n                         end\n            with\n              | ParseTerminal _ => I\n              | ParseNonTerminal _ _ p' => fun pf' H' => (fst H', existT _ p' (expand_forall_parse_of _ _ (snd H')))\n            end pf (projT2 p)).\n    clear -pf'; unfold P in *; simpl;\n    abstract (intros ??; do 2 edestruct lt_dec; intuition).\n  Defined.\n  Definition parse_of__of__parse_of_item_lt {str0 valid str nonterminal_name} pf p\n    := snd (@parse_of__of__parse_of_item_lt' str0 valid str nonterminal_name pf p).\n\n  Definition deloop_right str0 valid str nonterminal_name\n    := p_parse str0 (remove_nonterminal_name valid nonterminal_name) str (Lookup G nonterminal_name).\n\n  Definition deloop_onceT\n    := forall str0 valid str nonterminal_name prods\n              (p : parse_of String G str prods)\n              (pf : str = str0 :> String)\n              (H : Forall_parse_of (P str0 valid) p),\n         p_parse str0 (remove_nonterminal_name valid nonterminal_name) str prods\n         + deloop_right str0 valid str nonterminal_name.\n\n  Definition deloop_once_productionT\n    := forall str0 valid str nonterminal_name prod\n              (p : parse_of_production String G str prod)\n              (pf : str = str0 :> String)\n              (H : Forall_parse_of_production (P str0 valid) p),\n         p_parse_production str0 (remove_nonterminal_name valid nonterminal_name) str prod\n         + deloop_right str0 valid str nonterminal_name.\n\n  Definition deloop_once_item'\n             (deloop_once : deloop_onceT)\n             {str0 valid str nonterminal_name}\n             {it}\n             (p : parse_of_item String G str it)\n             (pf : str = str0 :> String)\n             (H : Forall_parse_of_item (P str0 valid) p)\n  : p_parse_item str0 (remove_nonterminal_name valid nonterminal_name) str it\n    + deloop_right str0 valid str nonterminal_name.\n  Proof.\n    destruct p as [ | nonterminal_name' str'' p' ].\n    { exact (inl (existT _ (ParseTerminal _ _ _) tt)). }\n    { refine (if string_dec nonterminal_name nonterminal_name'\n              then inr (if @deloop_once _ _ _ nonterminal_name' _ p' pf (snd H)\n                        then _\n                        else _)\n              else match @deloop_once _ _ _ nonterminal_name _ p' pf (snd H) with\n                     | inl p''' => inl (existT _ (ParseNonTerminal _ (projT1 p''')) (P_remove_impl _ (fst H), projT2 p'''))\n                     | inr ret => inr ret\n                   end);\n      clear deloop_once;\n      solve [ assumption\n            | subst; assumption ]. }\n  Defined.\n\n  Definition deloop_once'\n             (deloop_once : deloop_onceT)\n             (deloop_once_production : deloop_once_productionT)\n  : deloop_onceT.\n  Proof.\n    intros str0 valid str nonterminal_name pats p pf H.\n    destruct p as [ str' pat' pats' p' | str' pat' pats' p' ].\n    { refine match deloop_once_production str0 valid str' nonterminal_name _ p' pf H with\n               | inl ret => inl (existT _ (ParseHead pats' (projT1 ret)) (projT2 ret))\n               | inr ret => inr ret\n             end. }\n    { refine match deloop_once str0 valid str' nonterminal_name _ p' pf H with\n               | inl ret => inl (existT _ (ParseTail _ (projT1 ret)) (projT2 ret))\n               | inr ret => inr ret\n             end. }\n  Defined.\n\n  Local Ltac deloop_t :=\n    repeat match goal with\n             | _ => assumption\n             | _ => intro\n             | [ H : ?x = ?y |- _ ] => subst x\n             | [ H : ?x = ?y |- _ ] => subst y\n             | [ H : _ \u2264s _ |- _ ] => destruct H\n             | _ => progress simpl in *\n             | [ H : _ |- _ ] => rewrite Length_Empty in H\n             | _ => rewrite Length_Empty\n             | [ H : _ < 0 |- _ ] => destruct (Lt.lt_n_0 _ H)\n             | _ => progress destruct_head and\n             | [ |- _ /\\ _ ] => split\n             | [ H : sub_names_listT _ _ _ |- is_valid_nonterminal_name _ _ = true ]\n               => (apply H; eapply sub_names_listT_remove; eassumption)\n             | [ H : ~0 < ?n |- _ ]\n               => (let H' := fresh in\n                   destruct (zerop n) as [ | H' ]; [ clear H | destruct (H H') ])\n             | [ H : Length _ = 0 |- _ ] => apply Empty_Length in H\n             | [ H : ?x <> ?x |- _ ] => destruct (H eq_refl)\n             | [ H : context[Length (_ ++ _)] |- _ ] => rewrite <- Length_correct in H\n             | [ H : ~_ < _ + _ |- _ ]\n               => unique pose proof (proj1 (not_lt_plus H))\n             | [ H : ~_ < _ + _ |- _ ]\n               => unique pose proof (proj2 (not_lt_plus H))\n             | [ H : ?T, H' : ~?T |- _ ] => destruct (H' H)\n             | [ H : ~ ?a < ?a + _ |- _ ] => apply not_lt_add_r in H\n             | [ H : ~ ?a < _ + ?a |- _ ] => apply not_lt_add_l in H\n           end.\n\n  Definition deloop_once_production'\n             (deloop_once : deloop_onceT)\n             (deloop_once_production : deloop_once_productionT)\n  : deloop_once_productionT.\n  Proof.\n    intros str0 valid str nonterminal_name pat p pf H.\n    destruct p as [ | str' pat' strs' pats' p' p'' ].\n    { refine (inl (existT _ (ParseProductionNil _ _) tt)). }\n    { (** We must discriminate based on whether or not [str] has already gotten shorter *)\n      destruct (stringlike_dec str' (Empty _)) as [e|e], (stringlike_dec strs' (Empty _)) as [e'|e'];\n      try (assert (pf0 : str' = str0)\n            by (clear -pf e'; abstract (subst strs'; rewrite ?RightId, ?LeftId in pf; exact pf));\n           pose proof (@deloop_once_item' (deloop_once) str0 valid _ nonterminal_name pat' p' pf0 (fst H)) as deloop_once_item;\n           clear deloop_once);\n      try (assert (pf1 : strs' = str0)\n            by (clear -pf e; abstract (subst str'; rewrite ?RightId, ?LeftId in pf; exact pf));\n           specialize (deloop_once_production str0 valid _ nonterminal_name pats' p'' pf1 (snd H)));\n      try (destruct deloop_once_item as [ret|ret];\n           [ | right; repeat first [ subst str' | subst strs' ]; rewrite ?LeftId, ?RightId; assumption ]);\n      try (destruct deloop_once_production as [ret'|ret'];\n           [ | right; repeat first [ subst str' | subst strs' ]; rewrite ?LeftId, ?RightId; assumption ]);\n      left.\n      { (** empty, empty *)\n        exact (existT _ (ParseProductionCons (projT1 ret) (projT1 ret'))\n                      (projT2 ret, projT2 ret')). }\n      { (** empty, nonempty *)\n        refine (existT _ (ParseProductionCons p' (projT1 ret'))\n                       (expand_forall_parse_of_item _ (fst H), projT2 ret')).\n        unfold P in *; simpl.\n        clear -e e' pf1 remove_nonterminal_name_1 remove_nonterminal_name_2.\n        abstract (intros; edestruct lt_dec; deloop_t). }\n      { (** nonempty, empty *)\n        refine (existT _ (ParseProductionCons (projT1 ret) p'')\n                       (projT2 ret, expand_forall_parse_of_production _ _ (snd H))).\n        unfold P in *; simpl.\n        clear -e e' pf0 remove_nonterminal_name_1 remove_nonterminal_name_2.\n        abstract (intros; edestruct lt_dec; deloop_t). }\n      { (** nonempty, nonempty *)\n        refine (existT _ (ParseProductionCons p' p'')\n                       (expand_forall_parse_of_item _ (fst H),\n                        expand_forall_parse_of_production _ _ (snd H)));\n        unfold P in *; simpl;\n        clear -e e' pf remove_nonterminal_name_1 remove_nonterminal_name_2;\n        abstract (intros; edestruct lt_dec; deloop_t). } }\n  Defined.\n\n  Fixpoint deloop_once {str0 valid str nonterminal_name pats} (p : parse_of String G str pats)\n    := @deloop_once' (@deloop_once) (@deloop_once_production) str0 valid str nonterminal_name pats p\n  with deloop_once_production {str0 valid str nonterminal_name pat} (p : parse_of_production String G str pat)\n       := @deloop_once_production' (@deloop_once) (@deloop_once_production) str0 valid str nonterminal_name pat p.\n  Definition deloop_once_item {str0 valid str nonterminal_name it} (p : parse_of_item String G str it)\n    := @deloop_once_item' (@deloop_once) str0 valid str nonterminal_name it p.\n\n  Definition parse_of__of__parse_of_item_eq' {str0 valid str nonterminal_name}\n             (pf : str = str0 :> String)\n             (p : p_parse_nonterminal_name str0 valid str nonterminal_name)\n  : P str0 valid str nonterminal_name * p_parse str0 (remove_nonterminal_name valid nonterminal_name) str (Lookup G nonterminal_name).\n  Proof.\n    refine (match projT1 p as p' in parse_of_item _ _ str' it'\n                  return match it' with\n                           | Terminal _ => True\n                           | NonTerminal nonterminal_name' => str' = str0 -> Forall_parse_of_item (P str0 valid) p' -> P str0 valid str' nonterminal_name' * p_parse str0 (remove_nonterminal_name valid nonterminal_name') str' (Lookup G nonterminal_name')\n                         end\n            with\n              | ParseTerminal _ => I\n              | ParseNonTerminal nonterminal_name' _ p'\n                => fun pf' H' => (fst H', if @deloop_once str0 valid _ nonterminal_name' _ p' pf' (snd H') then _ else _)\n            end pf (projT2 p));\n    assumption.\n  Defined.\n  Definition parse_of__of__parse_of_item_eq {str0 valid str nonterminal_name} pf p\n    := snd (@parse_of__of__parse_of_item_eq' str0 valid str nonterminal_name pf p).\n\n  Definition top_methods : @parser_computational_dataT _ String\n    := {| DependentlyTyped.methods' := top_methods' |}.\n\n  Local Instance top_prestrdata : @parser_computational_prestrdataT _ String G top_methods option\n    := { prelower_nonterminal_name_state str0 valid nonterminal_name str st := Some st;\n         prelower_string_head str0 valid prod prods str st\n         := match projT1 st as p' in parse_of _ _ str' prods' return Forall_parse_of (P str0 valid) p' -> option (p_parse_production str0 valid str' (hd prod prods')) with\n              | ParseHead _ _ _ p' => fun H => Some (existT _ p' H)\n              | ParseTail _ _ _ _ => fun _ => None\n            end (projT2 st);\n         prelower_string_tail str0 valid prod prods str st\n         := match projT1 st as p' in parse_of _ _ str' prods' return Forall_parse_of (P str0 valid) p' -> option (p_parse str0 valid str' (tl prods')) with\n              | ParseTail _ _ _ p' => fun H => Some (existT _ p' H)\n              | ParseHead _ _ _ _ => fun _ => None\n            end (projT2 st);\n         prelift_lookup_nonterminal_name_state_lt str0 valid nonterminal_name str pf := Some \u2218 parse_of__of__parse_of_item_lt pf;\n         prelift_lookup_nonterminal_name_state_eq str0 valid nonterminal_name str pf := Some \u2218 parse_of__of__parse_of_item_eq pf }.\n\n  Context (split_list_complete : forall str0 valid it its str pf, @split_list_completeT _ String G _ str0 valid it its str pf (split_string_for_production str0 valid it its str)).\n\n  Local Ltac ddestruct H :=\n    (* work around 4035 *) let H' := fresh in rename H into H'; dependent destruction H'.\n\n  Local Ltac t' :=\n    idtac;\n    match goal with\n      | _ => intro\n      | _ => progress simpl in *\n      | _ => discriminate\n      | _ => congruence\n      | _ => progress destruct_head @StringWithSplitState\n      | _ => progress destruct_head_hnf sigT\n      | _ => progress destruct_head_hnf prod\n      | _ => progress destruct_head_hnf and\n      | [ H : ~?T, H' : ?T |- _ ] => destruct (H H')\n      | [ H : (?x =s ?x) = false |- _ ] => erewrite (proj2 (bool_eq_correct _ _ _)) in H by reflexivity\n      | [ H : parse_of_item _ _ _ (Terminal _) |- _ ] => ddestruct H\n      | [ H : parse_of_item _ _ _ (NonTerminal _ _) |- _ ] => ddestruct H\n      | [ H : parse_of_production _ _ _ [] |- _ ] => ddestruct H\n      | [ H : parse_of _ _ _ (_::_) |- _ ] => ddestruct H\n      | [ H : parse_of _ _ _ nil |- _ ] => ddestruct H\n      | [ H : appcontext[if lt_dec ?a ?b then _ else _] |- _ ] => destruct (lt_dec a b)\n    end.\n\n  Local Ltac t := repeat t'.\n\n  Local Obligation Tactic := t.\n\n  Global Program Instance minimal_of_parse_parser_dependent_types_extra_data'\n  : @parser_dependent_types_extra_dataT _ String G\n    := @sum_extra_data\n         _ String G\n         predata\n         methods'\n         (@minimal_parser_dependent_types_success_data' _ String G _)\n         (@minimal_parser_dependent_types_failure_data' _ String G _)\n         strdata\n         (@minimal_parser_dependent_types_extra_success_data' _ String G _ _)\n         (@minimal_parser_dependent_types_extra_failure_data' _ String G _ _ split_list_complete)\n         _\n         top_methods'\n         top_prestrdata\n         _ _ _ _ _ _ _ _ _.\n\n  Definition minimal_parse_nonterminal_name__of__parse'\n             (nonterminal_name : string)\n             (s : String)\n             (p : parse_of_item String G s (NonTerminal _ nonterminal_name))\n             (H : Forall_parse_of_item\n                    (fun _ n => is_valid_nonterminal_name initial_nonterminal_names_data n = true)\n                    p)\n  : minimal_parse_of_name String G initial_nonterminal_names_data is_valid_nonterminal_name remove_nonterminal_name s initial_nonterminal_names_data s nonterminal_name.\n  Proof.\n    pose proof (fun H' => @parse_nonterminal_name _ String G minimal_of_parse_parser_dependent_types_extra_data' nonterminal_name s (Some (existT _ p (expand_forall_parse_of_item H' H)))) as H0.\n    simpl in *.\n    unfold T_nonterminal_name_success, T_nonterminal_name_failure in *.\n    simpl in *.\n    destruct H0; destruct_head False; try assumption; [ clear ].\n    unfold P in *; simpl in *.\n    repeat match goal with\n             | _ => assumption\n             | [ H : _ -> _ |- _ ] => specialize (H (reflexivity _))\n             | [ H : False |- _ ] => destruct H\n             | _ => intro\n             | [ |- _ /\\ _ ] => split\n             | [ |- appcontext[if lt_dec ?a ?b then _ else _] ]\n               => destruct (lt_dec a b)\n           end.\n    Defined.\nEnd recursive_descent_parser.\n", "meta": {"author": "JasonGross", "repo": "adt-synthesis", "sha": "30a5cd361af029f42864e103a5a604ffa9ee07a7", "save_path": "github-repos/coq/JasonGross-adt-synthesis", "path": "github-repos/coq/JasonGross-adt-synthesis/adt-synthesis-30a5cd361af029f42864e103a5a604ffa9ee07a7/src/Parsers/DependentlyTypedMinimalOfParseFactored.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.29098087851200094, "lm_q1q2_score": 0.16470057062543753}}
{"text": "Require Import Rel.Definitions.\nRequire Import Lang.BindingsFacts.\nRequire Import Wf_natnat.\nSet Implicit Arguments.\n\nImplicit Types EV HV V L : Set.\n\nSection section_EV_map_aux.\n\nHint Extern 1 => match goal with\n| [ x : ?V |- \u2203 _ : ?V, _ ] => exists x ; crush\nend.\n\nHint Extern 0 => match goal with\n| [ |- ?n \u22a8 ?X \u21d4 ?X ] => apply auto_contr_id\n| [ |- ?n \u22a8 ?X \u2248\u1d62 ?X ] => repeat iintro ; apply auto_contr_id\n| [ |- Acc lt' (_, _) ] => try lt'_solve\nend.\n\nFixpoint\n  EV_map_\ud835\udce5_aux\n  n EV EV' HV\n  (\u039e : XEnv EV HV)\n  (f : EV \u2192 EV')\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03b4\u2081' \u03b4\u2082' : EV' \u2192 eff0) (\u03b4' : EV' \u2192 IRel \ud835\udce4_Sig)\n  (H\u03b4\u2081 : \u2200 \u03b1 : EV, \u03b4\u2081 \u03b1 = \u03b4\u2081' (f \u03b1))\n  (H\u03b4\u2082 : \u2200 \u03b1 : EV, \u03b4\u2082 \u03b1 = \u03b4\u2082' (f \u03b1))\n  (H\u03b4 : n \u22a8 \u2200\u1d62 \u03b1 : EV, \u03b4 \u03b1 \u2248\u1d62 \u03b4' (f \u03b1))\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (v\u2081 v\u2082 : val0) (T : ty EV HV \u2205)\n  (W : Acc lt' (n, size_ty T))\n  {struct W} :\n  (n \u22a8\n    \ud835\udce5\u27e6 \u039e \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 \u21d4\n    \ud835\udce5\u27e6 (EV_map_XEnv f \u039e) \u22a2 EV_map_ty f T \u27e7 \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082)\nwith\n  EV_map_\ud835\udcfe_aux\n  n EV EV' HV\n  (\u039e : XEnv EV HV)\n  (f : EV \u2192 EV')\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03b4\u2081' \u03b4\u2082' : EV' \u2192 eff0) (\u03b4' : EV' \u2192 IRel \ud835\udce4_Sig)\n  (H\u03b4\u2081 : \u2200 \u03b1 : EV, \u03b4\u2081 \u03b1 = \u03b4\u2081' (f \u03b1))\n  (H\u03b4\u2082 : \u2200 \u03b1 : EV, \u03b4\u2082 \u03b1 = \u03b4\u2082' (f \u03b1))\n  (H\u03b4 : n \u22a8 \u2200\u1d62 \u03b1 : EV, \u03b4 \u03b1 \u2248\u1d62 \u03b4' (f \u03b1))\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (t\u2081 t\u2082 : tm0) (\u03c8 : IRel \ud835\udce3_Sig) l\u2081 l\u2082 (\u03b5 : ef EV HV \u2205)\n  (W : Acc lt' (n, 0))\n  {struct W} :\n  (n \u22a8\n    \ud835\udcfe\u27e6 \u039e \u22a2 \u03b5 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 \u21d4\n    \ud835\udcfe\u27e6 (EV_map_XEnv f \u039e) \u22a2 EV_map_ef f \u03b5 \u27e7 \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082)\nwith\n  EV_map_\ud835\udce4_aux\n  n EV EV' HV\n  (\u039e : XEnv EV HV)\n  (f : EV \u2192 EV')\n  (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig)\n  (\u03b4\u2081' \u03b4\u2082' : EV' \u2192 eff0) (\u03b4' : EV' \u2192 IRel \ud835\udce4_Sig)\n  (H\u03b4\u2081 : \u2200 \u03b1 : EV, \u03b4\u2081 \u03b1 = \u03b4\u2081' (f \u03b1))\n  (H\u03b4\u2082 : \u2200 \u03b1 : EV, \u03b4\u2082 \u03b1 = \u03b4\u2082' (f \u03b1))\n  (H\u03b4 : n \u22a8 \u2200\u1d62 \u03b1 : EV, \u03b4 \u03b1 \u2248\u1d62 \u03b4' (f \u03b1))\n  (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig)\n  (\u03be\u2081 \u03be\u2082 : list var)\n  (t\u2081 t\u2082 : tm0) (\u03c8 : IRel \ud835\udce3_Sig) l\u2081 l\u2082 (\ud835\udcd4 : eff EV HV \u2205)\n  (W : Acc lt' (n, size_eff \ud835\udcd4))\n  {struct W} :\n  (n \u22a8\n    \ud835\udce4\u27e6 \u039e \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082 \u21d4\n    \ud835\udce4\u27e6 (EV_map_XEnv f \u039e) \u22a2 EV_map_eff f \ud835\udcd4 \u27e7 \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 l\u2081 l\u2082)\n.\n\nProof.\n{\ndestruct T eqn:HT.\n+ crush.\n+ simpl \ud835\udce5_Fun ; auto_contr.\n  - apply EV_map_\ud835\udce5_aux ; auto.\n  - apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n+ simpl \ud835\udce5_Fun ; auto_contr.\n  replace (EV_shift_XEnv (EV_map_XEnv f \u039e))\n    with (EV_map_XEnv (map_inc f) (EV_shift_XEnv \u039e))\n    by (repeat erewrite EV_map_map_XEnv ; crush).\n  apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; [ |auto].\n  repeat iintro ; apply EV_map_\ud835\udce5_aux ; [auto|auto| |auto].\n  iintro \u03b1 ; destruct \u03b1 ; simpl ; repeat iintro ; [auto|].\n  iespecialize H\u03b4 ; apply H\u03b4.\n+ simpl \ud835\udce5_Fun ; auto_contr.\n  replace (HV_shift_XEnv (EV_map_XEnv f \u039e))\n    with (EV_map_XEnv f (HV_shift_XEnv \u039e))\n    by (erewrite EV_HV_map_XEnv ; crush).\n  apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n}\n\n{\ndestruct \u03b5 as [ \u03b1 | [ p | [ | X ] ] ] ; simpl.\n+ iespecialize H\u03b4 ; apply H\u03b4.\n+ auto_contr.\n+ auto.\n+ auto_contr.\n  isplit ; iintro' H.\n  - idestruct H as T H ; idestruct H as \ud835\udcd4 H ; idestruct H as HX H.\n    ielim_prop HX ; eapply binds_EV_map in HX.\n    repeat ieexists ; repeat isplit ; [ eauto | ].\n    later_shift.\n    erewrite <- I_iff_elim_M ; [ apply H | ].\n    apply \ud835\udcd7_Fun'_nonexpansive ; repeat iintro ; [auto| ].\n    apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro.\n    { erewrite <- \ud835\udce5_roll_unroll_iff ; auto. }\n    { erewrite <- \ud835\udce4_roll_unroll_iff ; auto. }\n  - idestruct H as T' H ; idestruct H as \ud835\udcd4' H ; idestruct H as HX H.\n    ielim_prop HX ; apply binds_EV_map_inv in HX.\n    destruct HX as [ T [ \ud835\udcd4 [ HT [ H\ud835\udcd4 HX ] ] ] ] ; subst.\n    repeat ieexists ; repeat isplit ; [ eauto | ].\n    later_shift.\n    erewrite I_iff_elim_M ; [ apply H | ].\n    apply \ud835\udcd7_Fun'_nonexpansive ; repeat iintro ; [auto|].\n    apply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro.\n    { erewrite <- \ud835\udce5_roll_unroll_iff ; auto. }\n    { erewrite <- \ud835\udce4_roll_unroll_iff ; auto. }\n}\n\n{\ndestruct \ud835\udcd4 ; simpl.\n+ auto.\n+ auto_contr ; auto.\n}\n\nQed.\n\nEnd section_EV_map_aux.\n\n\nSection section_EV_map.\nContext (n : nat).\nContext (EV EV' HV : Set).\nContext (\u039e : XEnv EV HV).\nContext (f : EV \u2192 EV').\nContext (\u03b4\u2081 \u03b4\u2082 : EV \u2192 eff0) (\u03b4 : EV \u2192 IRel \ud835\udce4_Sig).\nContext (\u03b4\u2081' \u03b4\u2082' : EV' \u2192 eff0) (\u03b4' : EV' \u2192 IRel \ud835\udce4_Sig).\nContext (H\u03b4\u2081 : \u2200 \u03b1 : EV, \u03b4\u2081 \u03b1 = \u03b4\u2081' (f \u03b1)).\nContext (H\u03b4\u2082 : \u2200 \u03b1 : EV, \u03b4\u2082 \u03b1 = \u03b4\u2082' (f \u03b1)).\nContext (H\u03b4 : n \u22a8 \u2200\u1d62 \u03b1 : EV, \u03b4 \u03b1 \u2248\u1d62 \u03b4' (f \u03b1)).\nContext (\u03c1\u2081 \u03c1\u2082 : HV \u2192 hd0) (\u03c1 : HV \u2192 IRel \ud835\udce3_Sig).\n\nHint Resolve lt'_wf.\n\nLemma EV_map_\ud835\udce5 T \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 :\nn \u22a8\n  \ud835\udce5\u27e6 \u039e \u22a2 T \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082 \u21d4\n  \ud835\udce5\u27e6 (EV_map_XEnv f \u039e) \u22a2 EV_map_ty f T \u27e7 \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 v\u2081 v\u2082.\nProof.\napply EV_map_\ud835\udce5_aux ; auto.\nQed.\n\nLemma EV_map_\ud835\udce4 \ud835\udcd4 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 L\u2081 L\u2082 :\nn \u22a8\n  \ud835\udce4\u27e6 \u039e \u22a2 \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 L\u2081 L\u2082 \u21d4\n  \ud835\udce4\u27e6 (EV_map_XEnv f \u039e) \u22a2 EV_map_eff f \ud835\udcd4 \u27e7 \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u03c8 L\u2081 L\u2082.\nProof.\napply EV_map_\ud835\udce4_aux ; auto.\nQed.\n\nHint Resolve EV_map_\ud835\udce5 EV_map_\ud835\udce4.\n\nLemma EV_map_\ud835\udce3 T \ud835\udcd4 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 :\nn \u22a8\n  \ud835\udce3\u27e6 \u039e \u22a2 T # \ud835\udcd4 \u27e7 \u03b4\u2081 \u03b4\u2082 \u03b4 \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082 \u21d4\n  \ud835\udce3\u27e6 (EV_map_XEnv f \u039e) \u22a2 (EV_map_ty f T) # (EV_map_eff f \ud835\udcd4) \u27e7\n  \u03b4\u2081' \u03b4\u2082' \u03b4' \u03c1\u2081 \u03c1\u2082 \u03c1 \u03be\u2081 \u03be\u2082 t\u2081 t\u2082.\nProof.\napply \ud835\udce3_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\nQed.\n\nEnd section_EV_map.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Compat_map_EV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2909808662149067, "lm_q1q2_score": 0.16470056366505426}}
{"text": "Require Import SimTactics SimCompanion IL paco3 OptionR.\nRequire Export ILStateType.\n\nSet Implicit Arguments.\n\nLemma sim_let_op X (IST:ILStateType X) X' (IST':ILStateType X')\n      i r (L:X) (L':X') V V' x x' e e' s s'\n      (EQ:op_eval V e = op_eval V' e')\n      (SIM: forall v, op_eval V e = Some v\n                 -> Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r i\n                                     (L, V [x <- \u23a3 v \u23a6], s) (L', V' [x' <- \u23a3 v \u23a6], s'))\n  : sim_gen (Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r)\n            i (L, V, stmtLet x (Operation e) s) (L', V', stmtLet x' (Operation e') s').\nProof.\n  case_eq (op_eval V e); intros.\n  * eapply SimSilent; [ eapply plus2O\n                      | eapply plus2O\n                      | ].\n    eapply step_let_op; eauto. eauto.\n    eapply step_let_op. rewrite <- EQ. eauto. eauto.\n    eapply SIM; eauto.\n  * eapply SimTerm; [| eapply star2_refl | eapply star2_refl | | ];\n      [ simpl | | ].\n    rewrite !result_none; isabsurd; eauto.\n    eapply let_op_normal; eauto.\n    eapply let_op_normal; rewrite <- EQ; eauto.\nQed.\n\nLemma sim_let_call X (IST:ILStateType X) X' (IST':ILStateType X')\n      i r (L:X) (L':X') V V' x x' f Y Y' s s'\n      (EQ: omap (op_eval V) Y = omap (op_eval V') Y')\n      (SIM: forall v,  Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r i\n                                    (L, V [x <- \u23a3 v \u23a6], s) (L', V' [x' <- \u23a3 v \u23a6], s'))\n  : sim_gen (Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r) i\n            (L, V, stmtLet x (Call f Y) s) (L', V', stmtLet x' (Call f Y') s').\nProof.\n  case_eq (omap (op_eval V) Y); intros.\n  * pose proof H as H'. rewrite EQ in H'.\n    eapply SimExtern;\n      [ eapply star2_refl\n      | eapply star2_refl\n      | step_activated; eauto 20 using step_let_call\n      | step_activated; eauto 20 using step_let_call | |].\n    eapply step_let_call; eauto.\n    intros ? ? ? STEP; subst;\n      eapply let_call_inversion in STEP; dcr; subst; eexists; split; try eapply step_let_call; eauto.\n    rewrite <- EQ; eauto.\n    intros ? ? STEP; eapply let_call_inversion in STEP; dcr; subst; eexists; split; try eapply step_let_call; eauto.\n    rewrite EQ; eauto.\n  * eapply SimTerm; [| eapply star2_refl | eapply star2_refl | | ];\n             [ simpl | | ].\n    rewrite !result_none; isabsurd; eauto.\n    eapply let_call_normal; eauto.\n    eapply let_call_normal; rewrite <- EQ; eauto.\nQed.\n\nLemma sim_cond X (IST:ILStateType X) X' (IST':ILStateType X')\n      i r (L:X) (L':X') V V' e e' s1 s1' s2 s2'\n      (EQ: op_eval V e = op_eval V' e')\n      (SIM1: forall v, op_eval V e = Some v -> val2bool v = true ->\n                  Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r i\n                                    (L, V, s1) (L', V', s1'))\n      (SIM2: forall v, op_eval V e = Some v -> val2bool v = false ->\n                  Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r i\n                                    (L, V, s2) (L', V', s2'))\n  : sim_gen (Tower3.companion3 (sim_gen (S':=X' * onv val * stmt)) r) i\n            (L, V, stmtIf e s1 s2) (L', V', stmtIf e' s1' s2').\nProof.\n  case_eq (op_eval V e); intros.\n  - case_eq (val2bool v); intros.\n    + eapply SimSilent; [ eapply plus2O; [|eapply filter_tau_nil_eq]\n                        | eapply plus2O; [|eapply filter_tau_nil_eq]\n                        | eapply SIM1; eauto];\n      eapply step_cond_true; eauto. rewrite <- EQ; eauto.\n    + eapply SimSilent; [ eapply plus2O; [|eapply filter_tau_nil_eq]\n                        | eapply plus2O; [|eapply filter_tau_nil_eq]\n                        | eapply SIM2; eauto];\n      eapply step_cond_false; eauto. rewrite <- EQ; eauto.\n  - eapply SimTerm; [| eapply star2_refl | eapply star2_refl | | ];\n      [ simpl | | ].\n    rewrite !result_none; isabsurd; eauto.\n    eapply cond_normal; eauto.\n    eapply cond_normal; eauto. rewrite <- EQ; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Equiv/SimCompanionTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.16465058905374208}}
{"text": "From mathcomp Require Import all_ssreflect.\nFrom mathcomp Require Import finmap multiset.\nFrom mathcomp Require Import zify.\nFrom Coq Require Import Reals Relation_Definitions Relation_Operators.\nFrom mathcomp Require Import boolp Rstruct.\nFrom Algorand Require Import fmap_ext algorand_model safety_helpers quorums.\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(** * Safety proof *)\n\n(** This module proves the asynchronous safety property of the protocol. *)\n\n(** ** Rounds do not contain forks *)\n\n(** To show there is not a fork in a particular round, we will take a history\nthat extends before any honest node has made a transition in that round. *)\nDefinition user_before_round r (u : UState) : Prop :=\n  (u.(round) < r \\/\n   (u.(round) = r /\\\n    u.(step) = 1 /\\ u.(period) = 1 /\\ u.(timer) = 0%R /\\ u.(deadline) = 0%R))\n  /\\ (forall r' p, r <= r' -> nilp (u.(proposals) (r', p)))\n  /\\ (forall r', r <= r' -> nilp (u.(blocks) r'))\n  /\\ (forall r' p, r <= r' -> nilp (u.(softvotes) (r', p)))\n  /\\ (forall r' p, r <= r' -> nilp (u.(certvotes) (r', p)))\n  /\\ (forall r' p s, r <= r' -> nilp (u.(nextvotes_open) (r', p, s)))\n  /\\ (forall r' p s, r <= r' -> nilp (u.(nextvotes_val) (r', p, s))).\n\nDefinition users_before_round (r:nat) (g : GState) : Prop :=\n  forall i (Hi : i \\in g.(users)), user_before_round r (g.(users).[Hi]).\n\nDefinition messages_before_round (r:nat) (g : GState) : Prop :=\n  forall (mailbox: {mset R * Msg}), mailbox \\in codomf (g.(msg_in_transit)) ->\n  forall deadline msg, (deadline,msg) \\in mailbox ->\n     msg_round msg < r.\n\nDefinition state_before_round r (g:GState) : Prop :=\n  users_before_round r g\n  /\\ messages_before_round r g\n  /\\ (forall msg, msg \\in g.(msg_history) -> msg_round msg < r).\n\n(** ** Lemmas connecting pending, sent, and received messages *)\n\n(** The two main lemmas proved in this section are [pending_sent_or_forged] and\n[received_was_sent]. The former connects a message in transit to a previously\nsent (or forged) message. The latter, which relies on the proof of\n[pending_sent_or_forged], states that if a message was received, and the sender\nfield of that message was a user who is honest, then that user must have sent\nthat message at some point earlier in the trace. *)\n\n(** Message in history was sent - used in [pending_sent_or_forged]. *)\nLemma replay_had_original\n g0 trace (H_path: is_trace g0 trace)\n r (H_start: state_before_round r g0) :\n  forall g ix, onth trace ix = Some g ->\n  forall (msg:Msg), msg \\in g.(msg_history) ->\n    r <= msg_round msg ->\n    exists send_ix, user_sent_at send_ix trace (msg_sender msg) msg.\nProof.\n  clear -H_path H_start.\n  move => g ix H_g msg H_msg H_r.\n  pose proof (path_gsteps_onth H_path H_g (P:=fun g => msg \\in g.(msg_history))).\n  cbv beta in H.\n  have H_msg0: msg \\notin g0.(msg_history)\n    by clear -H_start H_r;apply/negP => H_msg;\n       move: H_start => [] _ [] _ {H_msg}/(_ _ H_msg);rewrite ltnNge H_r.\n\n  move:(H H_msg0 H_msg). clear -H_path.\n  move => [n [g1 [g2 [H_step [H_pre H_post]]]]].\n  exists n, g1, g2;split;[assumption|].\n  apply (transition_from_path H_path), transitions_labeled in H_step.\n  move: H_step => [lbl H_rel];clear -H_pre H_post H_rel.\n  destruct lbl;\n    try (exfalso;apply /negP: H_post;\n         simpl in H_rel;decompose record H_rel;clear H_rel;subst g2;\n         simpl;assumption).\n  * (* deliver *)\n    unfold user_sent.\n    suff: s = msg_sender msg /\\ msg \\in l.\n    move => [<- H_l].\n    exists l;split;[|left;exists r, m];assumption.\n    simpl in H_rel.\n    case: H_rel => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]].\n    move: H_post H_pre;subst g2.\n    rewrite in_msetD.\n    move=> /orP []; [by move => Hp Hn;exfalso;apply/negP: Hp|].\n    rewrite in_seq_mset.\n    move => H_l. split;[|assumption].\n    by apply (utransition_msg_sender_good H_ustep H_l).\n  * (* internal *)\n    unfold user_sent.\n    suff: s = msg_sender msg /\\ msg \\in l.\n    move => [<- H_l].\n    exists l;split;[|right];assumption.\n    simpl in H_rel.\n    case: H_rel => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]].\n    move: H_post H_pre;subst g2.\n    rewrite in_msetD.\n    move=> /orP [];\n      [by move => Hp Hn;exfalso;apply/negP: Hp|].\n    rewrite in_seq_mset.\n    move => H_l. split;[|assumption].\n    by apply (utransition_internal_sender_good H_ustep H_l).\n  * exfalso;apply /negP: H_post.\n    simpl in H_rel.\n    case: H_rel => [ustate_key [msg' [H_corrupt [H_msg H_g2]]]].\n    by subst g2; simpl.\nQed.\n\n(** A pending message was sent or forged earlier in trace. *)\nLemma pending_sent_or_forged\n      g0 trace (H_path: is_trace g0 trace)\n      r (H_start: state_before_round r g0):\n    forall g_pending pending_ix,\n      onth trace pending_ix = Some g_pending ->\n    forall uid (key_msg : uid \\in g_pending.(msg_in_transit)) d pending_msg,\n      (d,pending_msg) \\in g_pending.(msg_in_transit).[key_msg] ->\n    let sender := msg_sender pending_msg in\n    r <= msg_round pending_msg ->\n    exists send_ix g1 g2, step_in_path_at g1 g2 send_ix trace\n      /\\ (user_sent sender pending_msg g1 g2\n          \\/ user_forged pending_msg g1 g2).\nProof.\n  clear -H_path H_start.\n  intros g_pending pending_ix H_g uid key_msg d msg H_msg sender H_round.\n  subst sender.\n  set P := fun g => match g.(msg_in_transit).[? uid] with\n                  | Some msg_mset => has (fun (p:R*Msg) => p.2 == msg) msg_mset\n                  | None => false\n                    end.\n  have H_P: P g_pending by rewrite /P in_fnd;apply/hasP;exists (d,msg).\n  have H_P0: ~~P g0.\n  {\n  unfold P;simpl.\n  clear -H_start H_round.\n  case Hmb: (_.[?uid]) => [mb|//].\n  move: H_start => [_ [H_msgs _]].\n  rewrite leqNgt in H_round.\n  apply/contraNN: H_round.\n\n  move /hasP =>[[d msg'] H_in /eqP /= ?];subst msg'.\n  apply: H_msgs H_in.\n  by apply/codomfP;exists uid.\n  }\n  (* msg has round >= r, while g0 comes before r, and so msg \\notin mmailbox0 *)\n  (* if the user does not have a mailbox, then it's already true*)\n  move: {H_P0 H_P}(path_gsteps_onth H_path H_g H_P0 H_P).\n  subst P;cbv beta.\n\n  move => [n [g1 [g2 [H_step [H_pre H_post]]]]].\n\n  move: (H_step) => /(transition_from_path H_path) /transitions_labeled [lbl H_rel].\n  destruct lbl.\n    (* tick *)\n    exfalso;apply /negP: H_post;simpl in H_rel;decompose record H_rel;clear H_rel;subst g2;\n      simpl;assumption.\n    (* deliver *)\n    exists n,g1,g2;split;[assumption|].\n    left. unfold user_sent.\n    suff: s = msg_sender msg /\\ msg \\in l by move => [<- H_l];exists l;split;[|left;exists r0, m];assumption.\n\n    simpl in H_rel.\n    case: H_rel => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]].\n    suff: msg \\in l by split;[apply (utransition_msg_sender_good H_ustep)|];assumption.\n    move: H_post H_pre;subst g2;apply broadcasts_prop;\n    by rewrite fnd_set;case:ifP => [/eqP ->|_];\n                                     [rewrite in_fnd;exact:msubD1set|exact:msubset_refl].\n    (* internal *)\n    exists n,g1,g2;split;[assumption|].\n    left. unfold user_sent.\n    suff: s = msg_sender msg /\\ msg \\in l by move => [<- H_l];exists l;split;[|right];assumption.\n\n    simpl in H_rel.\n    case: H_rel => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]].\n    suff: msg \\in l by split;[apply (utransition_internal_sender_good H_ustep)|];assumption.\n    move: H_post H_pre;subst g2;apply broadcasts_prop;\n    by apply msubset_refl.\n    (* exit partition *)\n    exfalso. apply /negP: H_post. simpl in H_rel;decompose record H_rel;clear H_rel. subst g2.\n    unfold recover_from_partitioned, reset_msg_delays.\n    (* reset_msg_delays preserves the set of messages, but not their deadlines *)\n    apply/contraNN:H_pre;clear.\n    cbn -[eq_op] => H_post.\n    case:fndP => H_in;move:H_post;\n       [rewrite updf_update //\n       |by rewrite not_fnd //;\n           change (uid \\notin ?f) with (uid \\notin domf f);\n        rewrite -updf_domf].\n    by rewrite /reset_user_msg_delays map_mset_has (eq_has (a2:=(fun p => p.2 == msg))).\n    (* enter partition *)\n    exfalso;apply /negP: H_post;simpl in H_rel;decompose record H_rel;clear H_rel;subst g2;\n      simpl;assumption.\n    (* corrupt user *)\n    exfalso;apply /negP: H_post;simpl in H_rel;decompose record H_rel;clear H_rel;subst g2.\n    unfold corrupt_user_result, drop_mailbox_of_user; simpl.\n    (* the empty msg mset cannot have a message *)\n    set m1 := (msg_in_transit g1).[? s].\n    by destruct m1;[rewrite fnd_set;case:ifP;[rewrite enum_mset0|]|].\n    (* replay a message *)\n    (* replayed message must have originally been sent honestly *)\n    rename s into target.\n    move: H_rel => /= [ustate_key [hist_msg [H_tgt_honest [H_msg_history H_g2]]]].\n    pose proof (replay_had_original H_path H_start (step_in_path_onth_pre H_step) H_msg_history).\n    move: H.\n    suff ->: hist_msg = msg.\n    move/(_ H_round) => [send_ix [g3 [g4]]];clear => H. exists send_ix, g3, g4.\n    tauto.\n    subst g2.\n    symmetry; apply /eqP. rewrite -mem_seq1.\n    apply/broadcasts_prop: H_post H_pre.\n    apply msubset_refl.\n    (* forge a message *)\n    exists n,g1,g2;split;[assumption|].\n    right.\n    unfold user_forged.\n    suff ->: msg = mkMsg m e n0 n1 s by assumption.\n    simpl in H_rel;decompose record H_rel;clear H_rel;subst g2.\n    apply/eqP;rewrite -mem_seq1.\n    apply/broadcasts_prop: H_post H_pre.\n    apply msubset_refl.\nQed.\n\n(** A message from an honest user was actually sent in the trace. Used to relate\n   an honest user having received a quorum of messages to some honest user\n   having sent those messages - used in [received_was_sent]. *)\n(* TODO: hopefully the statement can be cleaned up *)\nLemma pending_honest_sent: forall g0 trace (H_path: is_trace g0 trace),\n    forall r, state_before_round r g0 ->\n    forall g_pending pending_ix,\n      onth trace pending_ix = Some g_pending ->\n    forall uid (key_msg : uid \\in g_pending.(msg_in_transit)) d pending_msg,\n      (d,pending_msg) \\in g_pending.(msg_in_transit).[key_msg] ->\n    let sender := msg_sender pending_msg in\n    honest_during_step (msg_step pending_msg) sender trace ->\n    r <= msg_round pending_msg ->\n    exists send_ix, user_sent_at send_ix trace sender pending_msg.\nProof.\n  clear.\n  move => g0 trace H_path r H_start g ix H_g\n             uid key_msg d msg H_msg sender H_honest H_round.\n  have [send_ix [g1 [g2 [H_step H_send]]]]\n    := pending_sent_or_forged H_path H_start H_g H_msg H_round.\n  exists send_ix, g1, g2.\n  split;[assumption|].\n  case:H_send => [//|H_forged];exfalso.\n  destruct msg as [mty v r1 p forger].\n  rewrite /user_forged /= in H_forged;decompose record H_forged;clear H_forged.\n  move:H => [H_corrupt H_le].\n  have {H_honest} := all_onth H_honest (step_in_path_onth_pre H_step).\n  rewrite /upred' (in_fnd x) H_corrupt implybF => /negP;apply;apply /step_leP.\n  refine (step_le_trans H_le _).\n  apply/step_leP;rewrite /msg_step /step_leb !eq_refl !ltnn /=.\n  have: mtype_matches_step mty v x0 by assumption.\n  by clear;destruct mty,v;simpl;destruct 1.\nQed.\n\n(** This lemma connects message receipt to the sending of a message, used to\nreach back to an earlier honest transition. *)\nLemma received_was_sent g0 trace (H_path: is_trace g0 trace)\n    r0 (H_start: state_before_round r0 g0)\n    u d msg (H_recv: msg_received u d msg trace):\n    r0 <= msg_round msg ->\n    honest_during_step (msg_step msg) (msg_sender msg) trace ->\n    exists ix, user_sent_at ix trace (msg_sender msg) msg.\nProof.\n  clear -H_path H_start H_recv.\n  move: H_recv => [ix_r [ms H_deliver]].\n  move => H_round H_honest_sender.\n\n  move:H_deliver => [g1_d [g2_d [H_step_d H_rel_d]]].\n  have {H_step_d}H_g1_d := step_in_path_onth_pre H_step_d.\n\n  move:H_rel_d => [ukey1 [upost H_step]].\n  move:H_step => [H_ustep] [H_honest_recv] [key_mailbox] [H_msg_in H_g2_d].\n  clear g2_d H_g2_d.\n\n  pose proof (pending_honest_sent H_path H_start H_g1_d H_msg_in) as H.\n  specialize (H H_honest_sender H_round).\n  exact H.\nQed.\n\n(** ** Uniqueness of votes *)\n\n(** Now we have lemmas showing that transitions preserve various invariants. *)\n\n(** A user can only certvote one value during given round/period. *)\nLemma vote_value_unique uid r p g1 g2 v:\n  user_sent uid (mkMsg Certvote (val v) r p uid) g1 g2 ->\n  user_honest uid g1 ->\n  forall v2, user_sent uid (mkMsg Certvote (val v2) r p uid) g1 g2 -> v2 = v.\nProof.\n  move => H_sent H_honest v2 H_sent2.\n  unfold user_sent in H_sent, H_sent2.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]];\n  destruct H_sent2 as [ms2 [H_msg2 [[d2 [in2 H_step2]]|H_step2]]];\n  pose proof (transition_label_unique H_step H_step2) as H;\n  try (discriminate H);[injection H as -> -> ->|injection H as ->];clear H_step2;\n    revert H_msg H_msg2;simpl in H_step;\n  [case: H_step => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]] |\n   case: H_step => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]] ];\n    let H:=  match goal with\n    | [H : _ # _ ; _ ~> _ |- _] => H\n    | [H : _ # _ ~> _ |- _] => H\n    end\n    in clear -H; set result := (ustate_post,ms) in H;change ms with result.2;clearbody result;revert H;\n  destruct 1;simpl;clear;move/in_memP => H_msg;try (exfalso;exact H_msg);\n     move/in_memP => H_msg2;simpl in H_msg, H_msg2;intuition congruence.\nQed.\n\n(** A user can only softvote for one value during a given round/period. *)\nLemma softvote_value_unique uid r p g1 g2 v:\n  user_sent uid (mkMsg Softvote (val v) r p uid) g1 g2 ->\n  user_honest uid g1 ->\n  forall v2, user_sent uid (mkMsg Softvote (val v2) r p uid) g1 g2 ->\n  v2 = v.\nProof.\n  move => H_sent H_honest v2 H_sent2.\n  unfold user_sent in H_sent, H_sent2.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]];\n  destruct H_sent2 as [ms2 [H_msg2 [[d2 [in2 H_step2]]|H_step2]]];\n  pose proof (transition_label_unique H_step H_step2) as H;\n  try (discriminate H);[injection H as -> -> ->|injection H as ->];clear H_step2;\n    revert H_msg H_msg2;simpl in H_step;\n  [case: H_step => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]] |\n   case: H_step => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]] ];\n    let H:=  match goal with\n    | [H : _ # _ ; _ ~> _ |- _] => H\n    | [H : _ # _ ~> _ |- _] => H\n    end\n    in clear -H;set result := (ustate_post,ms) in H;change ms with result.2;clearbody result;revert H;\n  destruct 1;simpl;clear;move/in_memP => H_msg;try (exfalso;exact H_msg);\n     move/in_memP => H_msg2;simpl in H_msg, H_msg2;intuition congruence.\nQed.\n\n(** ** Pre- and post-conditions for users sending votes *)\n\n(** User sends softvote implies that [softvote_new_ok] or [softvote_repr_ok] must have held. *)\nLemma softvote_precondition g1 g2 uid v r p\n  (H_sent: user_sent uid (mkMsg Softvote (val v) r p uid) g1 g2)\n  u (H_u: g1.(users).[?uid] = Some u):\n  softvote_new_ok u uid v r p\n   \\/ softvote_repr_ok u uid v r p.\nProof.\n  clear -H_sent H_u.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]];\n    simpl in H_step;\n    [case: H_step => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]] |\n   case: H_step => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]] ];\n    move: H_msg;change ms with (ustate_post,ms).2;\n      match goal with\n      | [H: _ # _ ~> _ |- _] => move: (ustate_post,ms) H => result\n      | [H: _ # _ ; _ ~> _ |- _] => move: (ustate_post,ms) H => result\n      end;subst;\n  rewrite in_fnd in H_u;case:H_u => ->;clear.\n  * (* no message delivery cases *)\n    by destruct 1.\n  * (* internal transition cases *)\n    by destruct 1;try exact;rewrite mem_seq1 => /eqP [-> -> ->];[left|right].\nQed.\n\n(** If a user sends certvote, [certvote_ok] must have held. In case the certvote\ncame via a message delivery transition, we need additional information about how\nthe user state changes for the user who sent the certvote. *)\nLemma certvote_precondition g1 g2 uid v r p:\n  user_sent uid (mkMsg Certvote (val v) r p uid) g1 g2 ->\n  forall u, g1.(users).[?uid] = Some u ->\n  (exists i b,\n      certvote_ok (set_softvotes u r p (i, v)) uid v b r p\n      /\\ g2.(users).[?uid] =\n         Some (certvote_result (set_softvotes u r p (i, v)))) \\/\n  (exists b, certvote_ok u uid v b r p).\nProof.\n  move => H_sent u H_u.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]].\n  * { (* message delivery cases *)\n      destruct H_step as (key_ustate & ustate_post & H_step & H_honest\n                          & key_mailbox & H_msg_in_mailbox & ->).\n      assert ((users g1) [` key_ustate] = u).\n      rewrite in_fnd in H_u; inversion H_u; trivial.\n      rewrite H in H_step; clear H.\n      remember (ustate_post,ms) as ustep_out in H_step.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n      intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction.\n      simpl in H_msg; destruct H_msg; try contradiction; inversion H0.\n      left. exists i, b; split; subst; auto.\n      rewrite fnd_set eq_refl. auto.\n    }\n  * { (* internal transition cases *)\n      destruct H_step as (key_user & ustate_post & H_honest & H_step & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      assert ((users g1) [` key_user] = u).\n      rewrite in_fnd in H_u; inversion H_u; trivial.\n      rewrite H in H_step. clear H.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n        intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction;\n      simpl in H_msg; destruct H_msg as [H_msg | H_msg]; try contradiction;\n      try destruct H_msg as [H_msg | H_msg]; inversion H_msg.\n      by right; exists b; subst.\n    }\nQed.\n\n(** If a user sent a certvote this means that in the resulting state, \nthe value is in the user's certvals, value corresponds to a block in\nuser's blocks, and user is in step 4. *)\nLemma certvote_postcondition uid v r p g1 g2:\n  user_sent uid (mkMsg Certvote (val v) r p uid) g1 g2 ->\n  forall u, g2.(users).[?uid] = Some u ->\n  v \\in certvals u r p /\\\n        (exists b, b \\in u.(blocks) r /\\ valid_block_and_hash b v)\n  /\\ valid_rps u r p 4.\nProof.\n  move => H_sent u H_u.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]].\n  (* need to grab u *)\n  * { (* message delivery cases *)\n      destruct H_step as (key_ustate & ustate_post & H_step & H_honest\n                          & key_mailbox & H_msg_in_mailbox & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n      intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction.\n      simpl in H_msg; destruct H_msg; try contradiction.\n      inversion H0;subst;clear H0.\n      unfold certvote_ok in H;decompose record H;clear H.\n      rewrite fnd_set eq_refl in H_u. case: H_u => {u}<-.\n      unfold certvote_result.\n      by (split;[|split]);\n        [\n        |exists b;split\n        |move:H0 =>-[? [? ?]];split;[|split;[|reflexivity]]].\n    }\n  * { (* internal transition cases *)\n      destruct H_step as (key_user & ustate_post & H_honest & H_step & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n        intros <- <-; move/in_memP in H_msg; try contradiction;\n      simpl in H_msg; destruct H_msg as [H_msg | H_msg]; try contradiction;\n      try destruct H_msg as [H_msg | H_msg]; inversion H_msg;subst;clear H_msg.\n      rewrite fnd_set eq_refl in H_u. case:H_u => H_u.\n      subst.\n      unfold certvote_ok in H;decompose record H;clear H.\n      by (split;[|split]);\n        [|exists b;split\n         |move:H0 =>-[? [? ?]]].\n    }\nQed.\n\n(** If a user sent nextvote open, then [nextvote_open_ok] must have held. *)\nLemma nextvote_open_precondition g1 g2 uid r p s:\n  user_sent uid (mkMsg Nextvote_Open (step_val s) r p uid) g1 g2 ->\n  forall u, g1.(users).[?uid] = Some u ->\n  nextvote_open_ok u uid r p s.\nProof.\n  move => H_sent u H_u.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]].\n  * { (* message delivery cases *)\n      destruct H_step as (key_ustate & ustate_post & H_step & H_honest\n                          & key_mailbox & H_msg_in_mailbox & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n      intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction.\n      simpl in H_msg; destruct H_msg; try contradiction; inversion H0.\n    }\n  * { (* internal transition cases *)\n      destruct H_step as (key_user & ustate_post & H_honest & H_step & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      assert ((users g1) [` key_user] = u).\n      rewrite in_fnd in H_u; inversion H_u; trivial.\n      rewrite H in H_step. clear H.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n        intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction;\n      simpl in H_msg; destruct H_msg as [H_msg | H_msg]; try contradiction;\n      try destruct H_msg as [H_msg | H_msg]; inversion H_msg.\n      subst; assumption.\n    }\nQed.\n\n(** If user sent nextvote val, then [nextvote_val_ok] must have held. *)\nLemma nextvote_val_precondition g1 g2 uid v r p s:\n  user_sent uid (mkMsg Nextvote_Val (next_val v s) r p uid) g1 g2 ->\n  forall u, g1.(users).[?uid] = Some u ->\n  (exists b, nextvote_val_ok u uid v b r p s) \\/\n  (nextvote_stv_ok u uid r p s /\\ u.(stv).[? p] = Some v).\nProof.\n  move => H_sent u H_u.\n  destruct H_sent as [ms [H_msg [[d1 [in1 H_step]]|H_step]]].\n  * { (* message delivery cases *)\n      destruct H_step as (key_ustate & ustate_post & H_step & H_honest\n                          & key_mailbox & H_msg_in_mailbox & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n      intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction.\n      simpl in H_msg; destruct H_msg; try contradiction; inversion H0.\n    }\n  * { (* internal transition cases *)\n      destruct H_step as (key_user & ustate_post & H_honest & H_step & ->).\n      remember (ustate_post,ms) as ustep_out in H_step.\n      assert ((users g1) [` key_user] = u).\n      rewrite in_fnd in H_u; inversion H_u; trivial.\n      rewrite H in H_step. clear H.\n      destruct H_step; injection Hequstep_out; clear Hequstep_out;\n        intros <- <-; revert H_msg; move/in_memP => H_msg; try contradiction;\n      simpl in H_msg; destruct H_msg as [H_msg | H_msg]; try contradiction;\n      try destruct H_msg as [H_msg | H_msg]; inversion H_msg.\n      left; exists b; subst; assumption.\n      right; subst; split; assumption.\n    }\nQed.\n\n(** ** Voting for one value in a period *)\n\n(** An honest user cert-votes for at most one value in a period.\nIn any global state, an honest user either never certvotes in a period or\ncertvotes once in step 3 and never certvotes after that during that period. *)\nLemma no_two_certvotes_in_p : forall g0 trace (H_path : is_trace g0 trace) uid r p,\n    forall ix1 v1, certvoted_in_path_at ix1 trace uid r p v1 ->\n                   user_honest_at ix1 trace uid ->\n    forall ix2 v2, certvoted_in_path_at ix2 trace uid r p v2 ->\n                   user_honest_at ix2 trace uid ->\n                   ix1 = ix2 /\\ v1 = v2.\nProof.\n  move => g0 trace H_path uid r p.\n  move => ix1 v1 H_send1 H_honest1.\n  move => ix2 v2 H_send2 H_honest2.\n\n  have: ix1 <= ix2 by\n  eapply (order_sends H_path H_send1 H_send2 (step_le_refl _)).\n  have: ix2 <= ix1 by\n  eapply (order_sends H_path H_send2 H_send1 (step_le_refl _)).\n\n  move => H_le1 H_le2.\n  have: ix1 = ix2.\n  apply/eqP. rewrite eqn_leq. apply/andP. split;assumption.\n  intro;subst ix2;clear H_le1 H_le2.\n  split;[reflexivity|].\n\n  unfold certvoted_in_path_at in H_send1, H_send2.\n  destruct H_send1 as [pre1 [post1 [H_step1 H_send1]]].\n  destruct H_send2 as [pre2 [post2 [H_step2 H_send2]]].\n\n  destruct (step_ix_same H_step1 H_step2) as [-> ->].\n  symmetry.\n  refine (vote_value_unique H_send1 _ H_send2).\n  exact (at_step_onth H_honest1 (step_in_path_onth_pre H_step1)).\nQed.\n\n(** An honest user soft-votes for at most one value in a period. *)\nLemma no_two_softvotes_in_p : forall g0 trace (H_path : is_trace g0 trace) uid r p,\n    forall ix1 v1, softvoted_in_path_at ix1 trace uid r p v1 ->\n    forall ix2 v2, softvoted_in_path_at ix2 trace uid r p v2 ->\n                   ix1 = ix2 /\\ v1 = v2.\nProof.\n  clear.\n  move => g0 trace H_path uid r p.\n  move => ix1 v1 H_send1 ix2 v2 H_send2.\n\n  have: ix1 <= ix2 by\n  eapply (order_sends H_path H_send1 H_send2 (step_le_refl _)).\n  have: ix2 <= ix1 by\n  eapply (order_sends H_path H_send2 H_send1 (step_le_refl _)).\n\n  move => H_le1 H_le2.\n  have: ix1 = ix2.\n  apply/eqP. rewrite eqn_leq. apply/andP. split;assumption.\n  intro;subst ix2;clear H_le1 H_le2.\n  split;[reflexivity|].\n\n  unfold softvoted_in_path_at in H_send1, H_send2.\n  destruct H_send1 as [pre1 [post1 [H_step1 H_send1]]].\n  destruct H_send2 as [pre2 [post2 [H_step2 H_send2]]].\n\n  destruct (step_ix_same H_step1 H_step2) as [-> ->].\n  symmetry.\n  refine (softvote_value_unique H_send1 _ H_send2).\n  (* honesty follows from user_sent *)\n  destruct H_send1 as [ms' [H_msg' [[d1' [in1' H_step']]|H_step']]].\n    destruct H_step' as (key_ustate' & ustate_post' & H_step' &\n     H_honest' & key_mailbox' & H_msg_in_mailbox' & ->).\n    by rewrite /user_honest in_fnd; apply/negP.\n  destruct H_step' as (key_user' & ustate_post' & H_honest' & H_step' & ->).\n  by rewrite /user_honest in_fnd; apply/negP.\nQed.\n\n(** ** Votes present in user state were received *)\n\n(** A vote in a user's softvote set means a softvote was received. *)\nLemma received_softvote\n  g0 trace (H_path: is_trace g0 trace)\n  r0 (H_start: state_before_round r0 g0)\n  ix g (H_last: onth trace ix = Some g) :\n  forall uid u, (users g).[? uid] = Some u ->\n  forall voter v r p, (voter, v) \\in u.(softvotes) (r, p) ->\n  r0 <= r ->\n  exists d, msg_received uid d (mkMsg Softvote (val v) r p voter) trace.\nProof.\n  clear -H_path H_start H_last.\n  move => uid u H_u voter v r p H_softvotes H_r.\n\n  assert (~~match g0.(users).[? uid] with\n            | Some u0 => (voter,v) \\in u0.(softvotes) (r, p)\n            | None => false\n            end). {\n    destruct (g0.(users).[?uid]) as [u0|] eqn:H_u0;[|done].\n    destruct H_start as [H_users _].\n    have H_key0: uid \\in g0.(users) by rewrite -fndSome H_u0.\n    specialize (H_users _ H_key0).\n    rewrite (in_fnd H_key0) in H_u0.\n    case: H_u0 H_r H_users => ->.\n    clear.\n    move => H_r [_] [_] [_] [H_softvotes _].\n    by move: {H_softvotes}(H_softvotes _ p H_r) => /nilP ->.\n  }\n\n  pose proof H_path as H_path_copy.\n  apply path_gsteps_onth with\n      (P := upred uid (fun u => (voter, v) \\in u.(softvotes) (r, p)))\n      (ix_p:=ix) (g_p:=g)\n    in H_path_copy;\n    try eassumption; try (unfold upred; rewrite H_u; assumption).\n\n  destruct H_path_copy as [n [g1 [g2 [H_step [H_pg1 H_pg2]]]]].\n  unfold upred in *.\n  assert (H_step_copy := H_step).\n  apply transition_from_path with (g0:=g0) in H_step_copy; try assumption.\n  destruct (g2.(users).[? uid]) eqn:H_u2; try (by inversion H_u2).\n  destruct (g1.(users).[? uid]) eqn:H_u1.\n  2: {\n    apply gtrans_preserves_users in H_step_copy.\n    have H_in1: (uid \\in domf (g1.(users)))\n      by rewrite H_step_copy; rewrite -fndSome H_u2.\n    rewrite in_fnd in H_u1. inversion H_u1.\n  }\n  assert (exists d ms, related_by (lbl_deliver uid d (mkMsg Softvote (val v) r p voter) ms) g1 g2).\n\n  have H_in1: (uid \\in g1.(users)) by rewrite -fndSome H_u1.\n  have H_in2: (uid \\in g2.(users)) by rewrite -fndSome H_u2.\n  have H_in1': g1.(users)[`H_in1] = u1 by rewrite in_fnd in H_u1;case:H_u1.\n\n  destruct H_step_copy; simpl users; autounfold with gtransition_unfold in * |-; unfold RecordSet.set in *; simpl in *;\n    try (exfalso; rewrite H_u1 in H_u2; inversion H_u2; subst;\n         rewrite H_pg2 in H_pg1; inversion H_pg1).\n\n  (* tick *)\n  + {\n    exfalso.\n    rewrite updf_update in H_u2. inversion H_u2 as [H_adv].\n    rewrite H_in1' /user_advance_timer in H_adv.\n    revert H_adv.\n    match goal with [ |- context C[ match ?b with _ => _ end]] => destruct b end;\n      intros; subst; rewrite H_pg2 in H_pg1; inversion H_pg1.\n    assumption.\n    }\n\n  (* deliver *)\n  + {\n    clear H_step.\n    rewrite fnd_set in H_u2. case H_eq:(uid == uid0). move/eqP in H_eq; subst uid0.\n    2: {\n      rewrite H_eq in H_u2.\n      rewrite H_u1 in H_u2. inversion H_u2; subst.\n      rewrite H_pg2 in H_pg1; inversion H_pg1.\n    }\n    rewrite eq_refl in H_u2. inversion H_u2.\n    move:H2. rewrite ?(eq_getf _ H_in1) H_in1'.\n    intro H_deliv.\n    remember (pending.1,pending.2) as pending_res.\n    assert (H_pending : pending = pending_res).\n    destruct pending. subst pending_res. intuition.\n    rewrite Heqpending_res in H_pending; clear Heqpending_res.\n    remember (ustate_post,sent) as result eqn:H_result.\n    destruct H_deliv eqn:H_dtrans;\n    try (by case: H_result => [? ?]; destruct pre;\n         subst; simpl in * |-; exfalso; rewrite H_pg2 in H_pg1; inversion H_pg1).\n\n    (* deliver softvote *)\n    * {\n      case: H_result => [pre'_eq sent_eq]; destruct pre.\n      exists pending.1, [::], H_in1, ustate_post.\n      unfold delivery_result; unfold RecordSet.set. simpl in * |- *.\n      subst pre0.\n      subst ustate_post. subst u0.\n      unfold pre', set_softvotes in H_pg2.\n      simpl in H_pg2.\n      revert H_pg2.\n      match goal with [ |- context C[ match ?b with _ => _ end]] => destruct b eqn:Hb1 end;\n       try (by intro; rewrite H_pg2 in H_pg1; inversion H_pg1).\n        rewrite fsfun_withE /=.\n        case eq_rp: (_ == _); last by move => H_pg2; rewrite H_pg2 in H_pg1.\n        case/eqP: eq_rp => eq_r eq_p; subst.\n        rewrite mem_undup => H_pg2.\n        by rewrite H_pg2 in H_pg1.\n      rewrite fsfun_withE.\n      case eq_rp: (_ == _); last by move => H_pg2; rewrite H_pg2 in H_pg1.\n      case/eqP: eq_rp => eq_r eq_p. subst r p.\n      rewrite in_cons mem_undup => H_pg2.\n      move/orP in H_pg2.\n      destruct H_pg2 as [H_eqv | H_neqv]; last by rewrite H_neqv in H_pg1; inversion H_pg1.\n      move/eqP in H_eqv. move/eqP in Hb1.\n      case: H_eqv => eq_i eq_v. subst voter v.\n      rewrite in_fnd in H_u1. case: H_u1 => eq_uid.\n      split => //.\n      rewrite -eq_uid.\n      split => //.\n      exists msg_key. rewrite -H_pending. split => //.\n      by rewrite sent_eq.\n      }\n    (* set softvote *)\n    * {\n      case: H_result => [pre'_eq sent_eq]; destruct pre.\n      exists pending.1, [:: mkMsg Certvote (val v0) r1 p0 uid], H_in1, ustate_post.\n      unfold delivery_result. unfold RecordSet.set. simpl in * |- *.\n      subst pre0.\n      subst ustate_post. subst u0.\n      unfold set_softvotes in H_pg2.\n      simpl in H_pg2.\n      revert H_pg2.\n      match goal with [ |- context C[ match ?b with _ => _ end]] => destruct b eqn:Hb1 end;\n        try (by intro; rewrite H_pg2 in H_pg1; inversion H_pg1).\n        rewrite fsfun_withE /=.\n        case eq_rp: (_ == _); last by move => H_pg2; rewrite H_pg2 in H_pg1.\n        case/eqP: eq_rp => eq_r eq_p; subst.\n        rewrite mem_undup => H_pg2.\n        by rewrite H_pg2 in H_pg1.\n      rewrite fsfun_withE.\n      case eq_rp: (_ == _); last by move => H_pg2; rewrite H_pg2 in H_pg1.\n      case/eqP: eq_rp => eq_r eq_p. subst r p.\n      rewrite in_cons mem_undup => H_pg2.\n      move/orP in H_pg2.\n      destruct H_pg2 as [H_eqv | H_neqv]; last by rewrite H_neqv in H_pg1; inversion H_pg1.\n      move/eqP in H_eqv. move/eqP in Hb1.\n      case: H_eqv => eq_i eq_v. subst voter v.\n      rewrite in_fnd in H_u1. case: H_u1 => eq_uid.\n      split => //.\n      rewrite -eq_uid.\n      split => //.\n      exists msg_key. rewrite -H_pending. split => //.\n      by rewrite sent_eq.\n      }\n\n    (* deliver nonvote msg result *)\n    * {\n      case: H_result => [? ?]; destruct pre; subst.\n      unfold deliver_nonvote_msg_result in H_pg2.\n      destruct (msg_ev msg) in H_pg2;\n        try (rewrite H_pg2 in H_pg1; inversion H_pg1);\n      destruct (msg_type msg) in H_pg2;\n      rewrite H_pg2 in H_pg1; inversion H_pg1.\n      }\n    }\n  (* internal *)\n  + {\n    clear H_step.\n    rewrite fnd_set in H_u2. case H_eq:(uid == uid0). move/eqP in H_eq; subst uid0.\n    2: {\n      rewrite H_eq in H_u2.\n      rewrite H_u1 in H_u2. inversion H_u2; subst.\n      rewrite H_pg2 in H_pg1; inversion H_pg1.\n    }\n    rewrite eq_refl in H_u2. inversion H_u2.\n    move:H1. rewrite ?(eq_getf _ H_in1) H_in1'.\n    intro H_trans. remember (ustate_post,sent) as result eqn:H_result.\n    destruct H_trans; case:H_result => [? ?]; subst; destruct pre;\n    simpl in * |-; exfalso; rewrite H_pg2 in H_pg1; inversion H_pg1.\n    }\n\n  (* corrupt *)\n  + {\n    exfalso.\n    rewrite fnd_set in H_u2; case H_eq:(uid == uid0).\n    move/eqP in H_eq. subst uid0. rewrite eq_refl in H_u2.\n    rewrite ?(eq_getf _ H_in1) H_in1' in H_u2.\n    inversion H_u2; subst.\n    rewrite H_pg2 in H_pg1; inversion H_pg1.\n\n    rewrite H_eq in H_u2.\n    rewrite H_u1 in H_u2. inversion H_u2; subst.\n    rewrite H_pg2 in H_pg1; inversion H_pg1.\n    }\n\n  destruct H0 as [d [ms H_rel]].\n  exists d. unfold msg_received.\n  exists n, ms. unfold step_at. exists g1, g2.\n  split; assumption.\nQed.\n\n(** A vote in a user's nextvote open set means a nextvote was received. *)\nLemma received_nextvote_open\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, (users g).[? uid] = Some u ->\n  forall voter r p s, voter \\in u.(nextvotes_open) (r, p, s) ->\n    r0 <= r ->\n    exists d, msg_received uid d (mkMsg Nextvote_Open (step_val s) r p voter) trace.\nProof.\n  clear -H_path H_start.\n  move => ix g H_g uid u H_u voter r p s H_voter H_r.\n  set P := upred uid (fun u => voter \\in u.(nextvotes_open) (r, p, s)).\n  assert (~~P g0). {\n  move: H_start => [H_users _]. clear -H_users H_r.\n  subst P. unfold upred.\n  destruct (uid \\in g0.(users)) eqn: H_in.\n  * move/(_ _ H_in) in H_users. rewrite in_fnd.\n    move: {g0 H_in}(g0.(users)[` H_in]) H_users => u H_users.\n    unfold user_before_round in H_users.\n    decompose record H_users.\n    by move: {H4 H_r}(H4 r p s H_r) => /nilP ->.\n  * by rewrite not_fnd // H_in.\n  }\n  assert (P g). {\n    unfold P, upred.\n    rewrite H_u. assumption.\n  }\n  have := path_gsteps_onth H_path H_g H H0.\n  clear -H_path.\n  move => [n [g1 [g2 [H_step [H_pre H_post]]]]].\n  have H_gtrans := transition_from_path H_path H_step.\n  unfold msg_received, step_at.\n  suff: exists d ms, related_by (lbl_deliver uid d (mkMsg Nextvote_Open (step_val s) r p voter) ms) g1 g2\n    by move => [d [ms H_rel]];exists d, n, ms, g1, g2;split;assumption.\n\n  move: H_gtrans H_pre H_post;unfold P, upred;clear;destruct 1;\n      try solve [move => /negP H_n /H_n []].\n  { (* tick *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    unfold tick_update, tick_users. cbn.\n    destruct (uid \\in pre.(users)) eqn:H_uid.\n    * rewrite updf_update // in_fnd.\n      move: (pre.(users)[` H_uid]) => u.\n      by unfold user_advance_timer;destruct u, corrupt;simpl.\n    * apply negbT in H_uid.\n      rewrite [(updf _ _ _).[? uid]] not_fnd //.\n      change (?k \\in ?f) with (k \\in domf f).\n      rewrite -updf_domf. assumption.\n  }\n  { (* deliver *)\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|by move/negP => H_n /H_n []].\n    move => /eqP in H_uids. subst uid0.\n    rewrite in_fnd.\n    destruct pending as [d pmsg]. unfold snd in H1.\n\n    remember (pre.(users)[`key_ustate]) as ustate;\n    remember (ustate_post, sent) as result;\n    destruct H1 eqn:H_step;case: Heqresult => {ustate_post}<- {sent}<-;subst pre0;\n                                                try by move => /negP H_n H_p;exfalso.\n    *\n    unfold pre'.\n    move => H_n H_p.\n    assert ((r,p,s) = (r0,p0,s0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    move: H_p. unfold set_nextvotes_open;simpl.\n    by rewrite fsfun_withE H_neq.\n    }\n    case: H2 => ? ? ?;subst r0 p0 s0.\n    assert (i = voter). {\n      symmetry. apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    rewrite /set_nextvotes_open /= fsfun_withE eqxx in H_p.\n    match type of H_p with context C [if ?b then _ else _] => destruct b end.\n      by rewrite mem_undup in H_p.\n      by rewrite in_cons H_neq mem_undup in H_p.\n    } subst i.\n    by finish_case.\n    *\n    unfold pre'.\n    move => H_n H_p.\n    assert ((r,p,s) = (r0,p0,s0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    move: H_p. unfold set_nextvotes_open;simpl.\n    by rewrite fsfun_withE H_neq.\n    } case: H2 => ? ? ?;subst r0 p0 s0.\n    assert (i = voter). {\n      symmetry. apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    rewrite /set_nextvotes_open /= fsfun_withE eqxx in H_p.\n\n    match type of H_p with context C [if ?b then _ else _] => destruct b end.\n      by rewrite mem_undup in H_p.\n      by rewrite in_cons H_neq mem_undup in H_p.\n    } subst i.\n    by finish_case.\n    *\n    move => /negP H_n H_p; exfalso;contradict H_n.\n    move: (pre.(users)[`key_ustate]) H_p => u.\n    clear.\n    unfold deliver_nonvote_msg_result.\n    destruct msg as [m v mr mp mu].\n    simpl.\n    by destruct v;first destruct m.\n  }\n  { (* internal *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|done].\n    move => /eqP in H_uids. subst uid0.\n    rewrite in_fnd.\n    move: (pre.(users)[` ustate_key]) H0 => u H_step.\n    clear -H_step.\n    remember (ustate_post,sent) as result;destruct H_step;\n    case: Heqresult => <- _;by destruct pre.\n  }\n  { (* corrupt *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|done].\n    move => /eqP in H_uids. subst uid0.\n    by rewrite in_fnd.\n  }\nQed.\n\n(** A vote in a user's nextvote_val set means a nextvote_val message was received. *)\nLemma received_nextvote_val\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, (users g).[? uid] = Some u ->\n  forall voter v r p s, (voter, v) \\in u.(nextvotes_val) (r, p, s) ->\n    r0 <= r ->\n    exists d, msg_received uid d (mkMsg Nextvote_Val (next_val v s) r p voter) trace.\nProof.\n  clear -H_path H_start.\n  move => ix g H_g uid u H_u voter v r p s H_voter H_r.\n  set P := upred uid (fun u => (voter,v) \\in u.(nextvotes_val) (r, p, s)).\n  assert (~~P g0). {\n  move: H_start => [H_users _]. clear -H_users H_r.\n  subst P. unfold upred.\n  destruct (uid \\in g0.(users)) eqn: H_in.\n  * move/(_ _ H_in) in H_users. rewrite in_fnd.\n    move: {g0 H_in}(g0.(users)[` H_in]) H_users => u H_users.\n    unfold user_before_round in H_users.\n    decompose record H_users.\n    by move: {H6 H_r}(H6 r p s H_r) => /nilP ->.\n  * by rewrite not_fnd // H_in.\n  }\n  assert (P g). {\n    unfold P, upred.\n    rewrite H_u. assumption.\n  }\n  have := path_gsteps_onth H_path H_g H H0.\n  clear -H_path.\n  move => [n [g1 [g2 [H_step [H_pre H_post]]]]].\n  have H_gtrans := transition_from_path H_path H_step.\n  unfold msg_received, step_at.\n  suff: exists d ms, related_by (lbl_deliver uid d (mkMsg Nextvote_Val (next_val v s) r p voter) ms) g1 g2\n    by move => [d [ms H_rel]];exists d, n, ms, g1, g2;split;assumption.\n\n  move: H_gtrans H_pre H_post;unfold P, upred;clear;destruct 1;\n      try solve [move => /negP H_n /H_n []].\n  { (* tick *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    unfold tick_update, tick_users. cbn.\n    destruct (uid \\in pre.(users)) eqn:H_uid.\n    * rewrite updf_update // in_fnd.\n      move: (pre.(users)[` H_uid]) => u.\n      by unfold user_advance_timer;destruct u, corrupt;simpl.\n    * apply negbT in H_uid.\n      rewrite [(updf _ _ _).[? uid]] not_fnd //.\n      change (?k \\in ?f) with (k \\in domf f).\n      rewrite -updf_domf. assumption.\n  }\n  { (* deliver *)\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|by move/negP => H_n /H_n []].\n    move => /eqP in H_uids. subst uid0.\n    rewrite in_fnd.\n    destruct pending as [d pmsg]. unfold snd in H1.\n\n    remember (pre.(users)[`key_ustate]) as ustate;\n    remember (ustate_post, sent) as result;\n    destruct H1 eqn:H_step;case: Heqresult => {ustate_post}<- {sent}<-;subst pre0;\n                                                try by move => /negP H_n H_p;exfalso.\n    *\n    unfold pre'.\n    move => H_n H_p.\n    assert ((r,p,s) = (r0,p0,s0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    move: H_p. unfold set_nextvotes_val;simpl.\n    by rewrite fsfun_withE H_neq.\n    } case: H2 => ? ? ?;subst r0 p0 s0.\n    assert ((voter,v) = (i,v0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    move: H_p; rewrite /set_nextvotes_val /= fsfun_withE eqxx.\n    match goal with\n      [|- context C[(i, v0) \\in ?nvs]] => destruct ((i,v0) \\in nvs) eqn:H_in\n    end.\n      by rewrite H_in mem_undup.\n      by rewrite H_in in_cons mem_undup; move/orP; destruct 1 as [H_eq|H_in'];\n        [rewrite H_neq in H_eq; discriminate|].\n    } case: H2 => ? ?;subst i v0.\n    by finish_case.\n    *\n    unfold pre'.\n    move => H_n H_p.\n    assert ((r,p,s) = (r0,p0,s0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    by move: H_p; rewrite /set_nextvotes_val /= fsfun_withE H_neq.\n    } case: H2 => ? ? ?;subst r0 p0 s0.\n    assert ((voter,v) = (i,v0)). {\n    apply /eqP. apply/contraNT: H_n => /negbTE H_neq.\n    move: H_p; rewrite /set_nextvotes_val /= fsfun_withE eqxx.\n    match goal with\n      [|- context C[(i, v0) \\in ?nvs]] => destruct ((i,v0) \\in nvs) eqn:H_in\n    end.\n      by rewrite H_in mem_undup.\n      by rewrite H_in in_cons mem_undup; move/orP; destruct 1 as [H_eq|H_in'];\n        [rewrite H_neq in H_eq; discriminate|].\n    } case: H2 => ? ?;subst i v0.\n    by finish_case.\n    *\n    move => /negP H_n H_p; exfalso;contradict H_n.\n    move: (pre.(users)[`key_ustate]) H_p => u.\n    clear.\n    unfold deliver_nonvote_msg_result.\n    destruct msg as [m v0 mr mp mu].\n    simpl.\n    by destruct v0;first destruct m.\n  }\n  { (* internal *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|done].\n    move => /eqP in H_uids. subst uid0.\n    rewrite in_fnd.\n    move: (pre.(users)[` ustate_key]) H0 => u H_step.\n    clear -H_step.\n    remember (ustate_post,sent) as result;destruct H_step;\n      case: Heqresult => <- _;by destruct pre.\n  }\n  { (* corrupt *)\n    move => /negP H_n H_p. exfalso.\n    case: H_n; move: H_p.\n    rewrite fnd_set.\n    destruct (uid == uid0) eqn:H_uids;[|done].\n    move => /eqP in H_uids. subst uid0.\n    by rewrite in_fnd.\n  }\nQed.\n\n(** ** Softvotes in user state means a voter softvoted earlier in the path *)\n\n(** Suppose [(voter,v) \\in u.(softvotes) r p]. Then,\n- message [(Softvote, val v, r, p, i)] was received, and\n- message [(Softvote, val v, r, p, i)] was sent.\n\nIn the latter case, either\n- user [i] sent [(Softvote, val v, r, p, i)] (through an internal transition only), meaning\n  softvoting preconditions imply [i] was a committee member, or\n- the adversary (using [i]) forged and sent the message, meaning forging does the credentials check, or\n- the adversary replayed the message, meaning\n-- the message is in [msg_history], and\n-- user [i] sent it (through an internal transition only), and\n-- softvoting preconditions imply [i] was a committee member. *)\nLemma softvotes_sent\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 -> forall voter v p,\n      (voter,v) \\in u.(softvotes) (r, p) ->\n      honest_during_step (r,p,2) voter trace ->\n      softvoted_in_path trace voter r p v.\nProof.\n  clear -H_path H_start.\n  move => ix g H_onth uid u H_u r H_r voter v p H_voter H_honest.\n  generalize dependent g. generalize dependent ix. generalize dependent voter.\n\n  induction trace using last_ind;[discriminate|].\n\n  move: (H_path).\n  rename H_path into H_path_trans.\n  destruct (rcons trace x) eqn:H_rcons.\n  inversion H_path_trans.\n  destruct H_path_trans as [H_g0 H_path_add]; subst g.\n  rewrite <- H_rcons.\n\n  move => H_path voter H_voter H_honest ix g H_onth H_u.\n  destruct (ix == (size trace)) eqn:H_add.\n  * { (* ix = size trace *)\n  move/eqP in H_add. subst.\n  have H_onth_copy := H_onth.\n  unfold onth in H_onth_copy.\n  rewrite drop_rcons // drop_size in H_onth_copy.\n  case:H_onth_copy => H_x. subst x.\n\n  have H_path_copy := H_path.\n  eapply received_softvote in H_path;[|eassumption..].\n\n  destruct H_path as [d H_msg_rec].\n\n  apply received_was_sent with (r0:=r0)\n                               (u:=uid) (d:=d)\n                               (msg:=(mkMsg Softvote (val v) r p voter))\n    in H_path_copy;[|assumption..].\n  simpl in H_path_copy.\n  destruct H_path_copy as [ix0 [g1 [g2 [H_s_at H_sent]]]].\n  exists ix0, g1, g2;split;assumption.\n  }\n  *\n  move /eqP in H_add.\n  have H_onth' := onth_size H_onth.\n  rewrite size_rcons in H_onth'.\n  assert (H_ix : ix < size trace) by lia.\n  clear H_onth' H_add.\n\n  assert (H_onth_trace : (onth trace ix) = Some g). {\n  unfold onth; unfold onth in H_onth; rewrite drop_rcons in H_onth.\n  apply drop_nth with (x0:=g0) in H_ix; rewrite H_ix in H_onth.\n  rewrite H_ix. trivial.\n  by lia.\n  }\n\n  assert (H_trace: is_trace g0 trace).\n  destruct trace;[by inversion H_onth_trace|].\n  inversion H_rcons; subst.\n  unfold is_trace.\n  split;[done|].\n    by rewrite rcons_path in H_path_add; move/andP: H_path_add; intuition.\n\n  eapply IHtrace in H_trace; try eassumption.\n  destruct H_trace as [ix0 [g1 [g2 [H_s_at H_sent]]]].\n  unfold softvoted_in_path, softvoted_in_path_at.\n  exists ix0, g1, g2;split;[|assumption].\n  by apply step_in_path_prefix with (size trace);rewrite take_rcons.\n  by move: H_honest;rewrite /honest_during_step all_rcons => /andP [] _.\nQed.\n\n(** ** Sender or forger of a message has sufficiently small credential *)\n\nLemma user_sent_credential uid msg g1 g2:\n  user_sent uid msg g1 g2 ->\n  let:(r,p,s) := msg_step msg in\n  uid \\in committee r p s.\nProof.\n  move => [ms [H_in [[d [pending H_rel]]|H_rel]]];move: H_in;\n           simpl in H_rel;\n  [case: H_rel => [H_uid [ustate_post [H_ustep [H_corrupt [key_mailbox [H_mail H_g2]]]]]] |\n   case: H_rel => [H_uid [ustate_post [H_corrupt [H_ustep H_g2]]]] ].\n  * { (* utransition deliver *)\n    move: H_ustep. clear. move: {g1 H_uid}(g1.(users)[`H_uid]) => u.\n    remember (ustate_post,ms) as result.\n    destruct 1;case:Heqresult => ? ?;subst ustate_post ms;move/in_memP => /= H_in;intuition;\n    subst msg;simpl;\n    apply/imfsetP;exists uid;[|reflexivity];apply/asboolP.\n    unfold certvote_ok in H;decompose record H;assumption.\n    }\n  * { (* utransition internal *)\n    move: H_ustep. clear. move: {g1 H_uid}(g1.(users)[`H_uid]) => u.\n    remember (ustate_post,ms) as result.\n    destruct 1;case:Heqresult => ? ?;subst ustate_post ms;move/in_memP => /= H_in;intuition;\n    (subst msg;simpl;\n     apply/imfsetP;exists uid;[|reflexivity];apply/asboolP);\n    autounfold with utransition_unfold in * |-;\n    match goal with [H:context C [comm_cred_step] |- _] => decompose record  H;assumption end.\n    }\nQed.\n\nLemma user_forged_credential msg g1 g2:\n  user_forged msg g1 g2 ->\n  let:(r,p,s) := msg_step msg in\n  msg_sender msg \\in committee r p s.\nProof.\n  move: msg => [mty v r p sender] H_forged.\n  unfold user_forged in H_forged.\n  simpl in H_forged.\n  decompose record H_forged;clear H_forged;subst g2.\n  move: (g1.(users)[`x]) H1 H0 => u. clear.\n  destruct mty, v;simpl;(try solve[destruct 1]) => {x0}-> H_cred;\n  (apply/imfsetP;exists sender;[|reflexivity];apply/asboolP;assumption).\nQed.\n\n(** ** Checking credentials *)\n\n(** All softvoters in a round/period are in the committee for step 2. *)\nLemma softvote_credentials_checked\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 -> forall v p,\n    softvoters_for v u r p `<=` committee r p 2.\nProof.\n  (* cleanup needed *)\n  clear -H_path H_start.\n  intros ix g H_onth uid u H_lookup r H_r v p.\n  apply/fsubsetP => voter H_softvoters.\n\n  have H_softvote : (voter,v) \\in u.(softvotes) (r, p)\n    by move: H_softvoters;clear;move => /imfsetP [] [xu xv] /= /andP [H_in /eqP] -> ->.\n\n  apply onth_take_some in H_onth.\n  assert (H_ix : ix.+1 > 0) by intuition.\n  have [d [n [ms H_deliver]]] :=\n    received_softvote\n      (is_trace_prefix H_path H_ix) H_start\n      H_onth H_lookup\n      H_softvote H_r.\n\n  set msg := mkMsg Softvote (val v) r p voter.\n  assert\n    (exists send_ix g1 g2, step_in_path_at g1 g2 send_ix trace\n                           /\\ (user_sent voter msg g1 g2 \\/ user_forged msg g1 g2))\n    as H_source. {\n    rewrite /step_at /= in H_deliver.\n    case: H_deliver => [g1 [g2 [H_step_at [key_ustate [ustate_post [H_step [H_corrupt H_deliver]]]]]]].\n    move: H_deliver => [key_mailbox [H_in H_g2]].\n    assert (onth trace n = Some g1)\n      by (refine (onth_from_prefix (step_in_path_onth_pre _));eassumption).\n    eapply pending_sent_or_forged;try eassumption.\n  }\n\n  destruct H_source as (send_ix & g1 & g2 & H_step & [H_send | H_forge]).\n  apply user_sent_credential in H_send. assumption.\n  apply user_forged_credential in H_forge. assumption.\nQed.\n\n(** All nextvoters for bot in a round/period/step are in the committee. *)\nLemma nextvote_open_credentials_checked\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 -> forall p s,\n      nextvoters_open_for u r p s `<=` committee r p s.\nProof.\n  clear -H_path H_start.\n  intros ix g H_onth uid u H_lookup r H_r p s.\n  apply/fsubsetP => voter H_nextvoters.\n\n  have H_nextvote : voter \\in u.(nextvotes_open) (r, p, s)\n    by revert H_nextvoters; rewrite in_fset;\n    change (in_mem voter _) with (voter \\in u.(nextvotes_open) (r, p, s)).\n\n  apply onth_take_some in H_onth.\n  assert (H_ix : ix.+1 > 0) by intuition.\n  have [d [n [ms H_deliver]]] :=\n    received_nextvote_open\n      (is_trace_prefix H_path H_ix) H_start\n      H_onth H_lookup\n      H_nextvote H_r.\n\n  set msg := mkMsg Nextvote_Open (step_val s) r p voter.\n  assert\n    (exists send_ix g1 g2, step_in_path_at g1 g2 send_ix trace\n                           /\\ (user_sent voter msg g1 g2 \\/ user_forged msg g1 g2))\n    as H_source. {\n    rewrite /step_at /= in H_deliver.\n    case: H_deliver => [g1 [g2 [H_step_at [key_ustate [ustate_post [H_step [H_corrupt H_deliver]]]]]]].\n    move: H_deliver => [key_mailbox [H_in H_g2]].\n    assert (onth trace n = Some g1)\n      by (refine (onth_from_prefix (step_in_path_onth_pre _));eassumption).\n    eapply pending_sent_or_forged;try eassumption.\n  }\n\n  destruct H_source as (send_ix & g1 & g2 & H_step & [H_send | H_forge]).\n  apply user_sent_credential in H_send. assumption.\n  apply user_forged_credential in H_forge. assumption.\nQed.\n\n(** All nextvoters for bot val in a round/period/step are in the committee. *)\nLemma nextvote_val_credentials_checked\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 -> forall v p s,\n      nextvoters_val_for v u r p s `<=` committee r p s.\nProof.\n  clear -H_path H_start.\n  intros ix g H_onth uid u H_lookup r H_r v p s.\n  apply/fsubsetP => voter H_nextvoters.\n\n  have H_nextvote : (voter,v) \\in u.(nextvotes_val) (r, p, s)\n    by move: H_nextvoters;clear;move => /imfsetP [] [xu xv] /= /andP [H_in /eqP] -> ->.\n\n  apply onth_take_some in H_onth.\n  assert (H_ix : ix.+1 > 0) by intuition.\n  have [d [n [ms H_deliver]]] :=\n    received_nextvote_val\n      (is_trace_prefix H_path H_ix) H_start\n      H_onth H_lookup\n      H_nextvote H_r.\n\n  set msg := mkMsg Nextvote_Val (next_val v s) r p voter.\n  assert\n    (exists send_ix g1 g2, step_in_path_at g1 g2 send_ix trace\n                           /\\ (user_sent voter msg g1 g2 \\/ user_forged msg g1 g2))\n    as H_source. {\n    rewrite /step_at /= in H_deliver.\n    case: H_deliver => [g1 [g2 [H_step_at [key_ustate [ustate_post [H_step [H_corrupt H_deliver]]]]]]].\n    move: H_deliver => [key_mailbox [H_in H_g2]].\n    assert (onth trace n = Some g1)\n      by (refine (onth_from_prefix (step_in_path_onth_pre _));eassumption).\n    eapply pending_sent_or_forged;try eassumption.\n  }\n\n  destruct H_source as (send_ix & g1 & g2 & H_step & [H_send | H_forge]).\n  apply user_sent_credential in H_send. assumption.\n  apply user_forged_credential in H_forge. assumption.\nQed.\n\n(** ** Advancing the period *)\n\n(** When the period advances to [p], and step of ustate changes to [(r,p,1)] with round the same,\nthen original ustate must have had a smaller period. *)\nDefinition period_advances uid r p (users1 users2: {fmap UserId -> UState}) : Prop :=\n  {ukey_1: uid \\in users1 &\n  {ukey_2: uid \\in users2 &\n  let ustate1 := users1.[ukey_1] in\n  let ustate2 := users2.[ukey_2] in\n  ustate1.(round) = ustate2.(round)\n  /\\ step_lt (step_of_ustate ustate1) (r,p,0)\n  /\\ step_of_ustate ustate2 = (r,p,1)}}.\n\n(** Period advances from [g1] to [g2] at given index in path. *)\nDefinition period_advance_at n path uid r p g1 g2 : Prop :=\n  step_in_path_at g1 g2 n path /\\ period_advances uid r p (g1.(users)) (g2.(users)).\n\n(** Period advances to [r,p] from [ge1] to [ge2], and there is a message sent from [gs1]\nto [gs2] in the path at [r,p] along with a step in the path from [gs1] to [gs2], then\n[gs1] is reachable from [ge2]. *)\nLemma post_enter_reaches_sent\n      g0 trace (H_path:is_trace g0 trace)\n      ix_e uid r p ge1 ge2 (H_enter: period_advance_at ix_e trace uid r p ge1 ge2)\n      ix_s gs1 gs2 (H_step: step_in_path_at gs1 gs2 ix_s trace)\n      msg (H_send: user_sent uid msg gs1 gs2)\n      (H_r_msg: msg_round msg = r)\n      (H_p_msg: msg_period msg = p):\n  greachable ge2 gs1.\n Proof.\n  move: H_enter => [H_step_enter [ukey_ge1 [ukey_ge2 [H_adv [H_ge1_step_lt H_ge2_step_eq]]]]].\n  set ukey_gs1 := user_sent_in_pre H_send.\n\n  assert (ix_e < ix_s) as H_order.\n  {\n    have: step_lt (step_of_ustate (ge1.(users)[` ukey_ge1]))\n                  (step_of_ustate (gs1.(users)[` ukey_gs1])).\n    apply/(step_lt_le_trans H_ge1_step_lt)/step_leP.\n      by rewrite (utransition_label_start H_send (in_fnd ukey_gs1)) /= H_r_msg H_p_msg !ltnn !eq_refl leq0n.\n    eapply (order_ix_from_steps H_path\n              (step_in_path_onth_pre H_step_enter)\n              (step_in_path_onth_pre H_step)).\n  }\n\n  exact\n     (at_greachable H_path (ix1:=ix_e.+1) (ix2:=ix_s) H_order\n                       (step_in_path_onth_post H_step_enter)\n                       (step_in_path_onth_pre H_step)).\nQed.\n\n(** A node enters period [p > 0] only if it received [t_H] next-votes for the same\nvalue from some step [s] of period [p-1]. *)\nLemma period_advance_only_by_next_votes\n g0 trace (H_path: is_trace g0 trace)\n r0 (H_start: state_before_round r0 g0) :\n forall n uid r p, r0 <= r ->\n forall g1 g2, period_advance_at n trace uid r p g1 g2 ->\n   exists (s:nat) (v:option Value) (next_voters:{fset UserId}),\n     next_voters `<=` committee r p.-1 s\n     /\\ (if v then tau_v else tau_b) <= #|` next_voters |\n     /\\ (exists u, g2.(users).[? uid] = Some u /\\ u.(stv).[? p] = v)\n     /\\ forall voter, voter \\in next_voters ->\n        received_next_vote uid voter r p.-1 s v trace.\nProof.\n  clear -H_path H_start.\n  intros n uid r p H_r g1 g2 H_adv.\n  destruct H_adv as [H_step [H_g1 [H_g2 [H_round [H_lt H_rps]]]]].\n  assert (H_gtrans : g1 ~~> g2) by (eapply transition_from_path; eassumption).\n\n  assert (H_lt_0 := H_lt).\n  eapply step_lt_le_trans with (c:=(r,p,1)) in H_lt.\n  2: { simpl; intuition. }\n\n  destruct H_gtrans.\n\n  (* tick *)\n  exfalso.\n  pose proof (tick_users_upd increment H_g1) as H_tick.\n  rewrite in_fnd in H_tick.\n\n  assert (H_tick_adv :\n            (tick_users increment pre) [` H_g2] =\n            user_advance_timer\n              increment\n              ((users pre) [` H_g1])).\n    by injection H_tick.\n\n  clear H_tick.\n  unfold tick_update in H_rps.\n  cbn -[in_mem mem] in H_rps.\n\n  rewrite H_tick_adv in H_rps.\n  unfold user_advance_timer in H_rps.\n  destruct (corrupt ((users pre)\n                                   [` H_g1]));\n    rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  { (* message delivery cases *)\n    unfold delivery_result in H_rps.\n    rewrite setfNK in H_rps.\n    destruct (uid == uid0) eqn:H_uid.\n    move/eqP in H_uid. subst.\n    simpl in H_rps.\n    assert (H_g1_key_ustate_opt :\n              Some (pre.(users)[`H_g1]) = Some (pre.(users)[`key_ustate])).\n      by repeat rewrite -in_fnd.\n\n    inversion H_g1_key_ustate_opt as [H_g1_key_ustate]. clear H_g1_key_ustate_opt.\n    rewrite H_g1_key_ustate in H_lt; rewrite <- H_rps in H_lt.\n    rewrite H_g1_key_ustate in H_round.\n    unfold step_of_ustate in H_lt.\n\n    remember (ustate_post,sent) as ustep_out in H1.\n    remember (pre.(users)[` key_ustate]) as u in H1.\n\n    destruct H1; injection Hequstep_out; clear Hequstep_out; intros <- <-;\n      try (inversion H_rps; exfalso; subst; subst pre';\n           apply step_lt_irrefl in H_lt; contradiction).\n\n    (* positive case: nextvote open *)\n    {\n      destruct H1 as [H_valid_rps H_quorum_size].\n      rewrite H_g1_key_ustate in H_lt_0.\n      clear H_g1_key_ustate H_g1.\n      rename pre0 into u.\n      rewrite -Hequ in H0 H_lt_0 H_lt H_round.\n      cbn -[step_le step_lt] in * |-.\n\n      destruct H_valid_rps as [H_r1 [H_p0 H_s]].\n      case:H_rps => H_r' H_p.\n      rewrite -H_p H_p0 -H_r' H_r1.\n\n      assert (H_n : n.+2 > 0) by intuition.\n      apply step_in_path_onth_post in H_step.\n      match goal with [H : onth trace n.+1 = Some ?x |- _] => rename H into H_onth;remember x as dr end.\n      (*\n      assert (H_onth : onth (take n.+2 trace) n.+1 = Some dr).\n        subst pref.\n        destruct (n.+2 < size trace) eqn:H_n2.\n        apply onth_take_some in H_step. rewrite size_take in H_step.\n        rewrite H_n2 in H_step. by intuition; eassumption.\n        assert (size trace <= n.+2). by clear -H_n2; ppsimpl; lia.\n        rewrite take_oversize; assumption.\n      *)\n\n      assert (H_addsub : (p0 + 1)%Nrec.-1 = p0). by lia.\n      rewrite H_addsub.\n      assert (H_r0r1 : r0 <= r1).\n        by simpl in H_r1; rewrite H_r1 in H_r'; subst r; eassumption.\n\n      exists s, None, (nextvoters_open_for pre' r1 p0 s); repeat split.\n      eapply nextvote_open_credentials_checked with\n          (uid:=uid) (u:=(adv_period_open_result pre'));\n        try eassumption;\n        try (subst dr; rewrite fnd_set; by rewrite eq_refl).\n\n      simpl.\n      unfold nextvoters_open_for.\n      move: H_quorum_size.\n      by rewrite card_fseq -finseq_size.\n\n      exists (adv_period_open_result pre').\n      split; first by rewrite Heqdr fnd_set eq_refl.\n      rewrite not_fnd //=.\n      by rewrite addn1 H_p0 mem_remfF.\n\n      intro voter.\n      rewrite in_fset.\n      change (in_mem voter _) with (voter \\in pre'.(nextvotes_open) (r1, p0, s)).\n\n      intro H_voter.\n      eapply received_nextvote_open with (u:=(adv_period_open_result pre'));\n        try eassumption;\n        try (subst dr; rewrite fnd_set; by rewrite eq_refl).\n    }\n\n    (* positive case: nextvote val *)\n    {\n      destruct H1 as [H_valid_rps H_quorum_size].\n      rewrite H_g1_key_ustate in H_lt_0.\n      clear H_g1_key_ustate H_g1.\n      rename pre0 into u.\n      rewrite -Hequ in H0 H_lt_0 H_lt H_round.\n\n      destruct H_valid_rps as [H_r1 [H_p0 H_s]].\n      case:H_rps => H_r' H_p.\n      rewrite -H_p H_p0 -H_r' H_r1.\n\n      apply step_in_path_onth_post in H_step.\n      match goal with [H : onth trace n.+1 = Some ?x |- _] => rename H into H_onth;remember x as dr end.\n\n      assert (H_addsub : (p0 + 1)%Nrec.-1 = p0). by lia.\n      rewrite H_addsub.\n      assert (H_r0r1 : r0 <= r1).\n        by simpl in H_r1; rewrite H_r1 in H_r'; subst r; eassumption.\n\n      exists s, (Some v), (nextvoters_val_for v pre' r1 p0 s); repeat split.\n      eapply nextvote_val_credentials_checked with\n          (uid:=uid) (u:=(adv_period_val_result pre' v));\n        try eassumption;\n        try (subst dr; rewrite fnd_set; by rewrite eq_refl).\n\n      simpl.\n      move: H_quorum_size.\n      unfold nextvote_value_quorum.\n      rewrite finseq_size -card_fseq.\n      match goal with |[|- is_true (tau_v <= ?A) -> is_true (tau_v <= ?B)]\n                       => suff ->: A = B by[] end.\n      by apply/imfset_filter_size_lem.\n\n      exists (adv_period_val_result pre' v).\n      split; first by rewrite Heqdr fnd_set eq_refl.\n      rewrite addn1 /= H_p0.\n      rewrite in_fnd //=; first by rewrite in_fset1U eqxx.\n      by move => Hin; rewrite getf_set.\n\n      intros voter H_voter.\n      have H_nextvote : (voter,v) \\in pre'.(nextvotes_val) (r1, p0, s)\n        by move: H_voter;move=>/imfsetP [] [xu xv] /= /andP [H_in /eqP];intros->->.\n\n      eapply received_nextvote_val with (u:=(adv_period_val_result pre' v));\n        try eassumption;\n        try (subst dr; rewrite fnd_set; by rewrite eq_refl).\n    }\n\n    exfalso.\n    rewrite setfNK in H_round.\n    assert (H_uid : (uid == uid) = true). apply/eqP; trivial.\n    rewrite H_uid in H_round.\n\n    subst pre0.\n    inversion H_rps as [H_r0].\n    cbn -[step_lt addn] in H_lt. rewrite H_r0 in H_lt.\n    destruct H1 as [H_adv _]. unfold advancing_rp in H_adv.\n    rewrite H_round in H_adv. clear -H_adv.\n    by simpl in H_adv; lia.\n\n    exfalso. subst.\n    unfold deliver_nonvote_msg_result in *.\n    destruct pre.\n    clear -H_rps H_lt.\n    cbn -[step_lt] in * |- *.\n    destruct (msg_ev msg); destruct (msg_type msg);cbn -[step_lt] in H_lt;\n    case:H_rps H_lt => -> -> ->;apply step_lt_irrefl.\n\n    exfalso. rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; contradiction.\n  }\n\n  { (* internal step case *)\n    exfalso.\n    unfold step_result in H_rps.\n    rewrite setfNK in H_rps.\n    destruct (uid == uid0) eqn:Huid.\n    move/eqP in Huid. subst.\n    simpl in H_rps.\n    assert (H_g1_key_ustate_opt :\n              Some (pre.(users)[`H_g1]) = Some (pre.(users)[`ustate_key])).\n      by repeat rewrite -in_fnd.\n\n    inversion H_g1_key_ustate_opt as [H_g1_key_ustate]. clear H_g1_key_ustate_opt.\n    rewrite H_g1_key_ustate in H_lt; rewrite <- H_rps in H_lt.\n    unfold step_of_ustate in H_lt.\n\n    remember (ustate_post,sent) as ustep_out in H0.\n    remember (pre.(users)[`ustate_key]) as u in H0.\n\n    destruct H0; injection Hequstep_out; clear Hequstep_out; intros <- <-; inversion H_rps;\n      try (destruct H0 as [H_lam [H_vrps [H_ccs [H_s [H_rest]]]]];\n           clear -H4 H_s; by lia).\n\n    subst; try apply step_lt_irrefl in H_lt; try contradiction.\n    move: H0 H1 => H_nv_stv H_stv.\n    destruct H_nv_stv as [H_lam [H_vrps [H_ccs [H_s [H_rest]]]]].\n    clear -H5 H_s. by lia.\n\n    (* no nextvote ok - need s > 3 assumption? *)\n    move:H_lt_0;rewrite H_g1_key_ustate -Hequ /step_of_ustate H2 H3.\n    clear;move: (pre0.(step)) => s /step_ltP /=.\n    by rewrite !eq_refl !ltnn ltn0.\n\n    subst. simpl in H_lt.\n    simpl in H_rps;inversion H_rps.\n    rewrite H2 H3 H4 !ltnn in H_lt.\n    clear -H_lt. intuition.\n    (*\n    unfold certvote_timeout_ok in H0.\n    inversion H0; subst.\n    clear -H4 H1. rewrite H1 in H4. inversion H4.\n\n    rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; contradiction.\n    *)\n  }\n\n  (* recover from partition *)\n  exfalso.\n  simpl in H_g2.\n  assert (H_g1_g2_opt : Some (pre.(users)[`H_g1]) = Some (pre.(users)[`H_g2])).\n    by repeat rewrite -in_fnd.\n\n  inversion H_g1_g2_opt as [H_g1_g2]; clear H_g1_g2_opt.\n  rewrite H_g1_g2 in H_lt.\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  (* enter partition *)\n  exfalso.\n  simpl in H_g2.\n  assert (H_g1_g2_opt : Some (pre.(users)[`H_g1]) = Some (pre.(users)[`H_g2])).\n    by repeat rewrite -in_fnd.\n\n  inversion H_g1_g2_opt as [H_g1_g2]; clear H_g1_g2_opt.\n  rewrite H_g1_g2 in H_lt.\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  (* corrupt user *)\n  exfalso.\n\n  rewrite setfNK in H_rps.\n  destruct (uid == uid0) eqn:Huid.\n  move/eqP in Huid. subst.\n  simpl in H_rps.\n  assert (H_g1_ustate_key_opt : \n            Some (pre.(users)[`H_g1]) = Some (pre.(users)[`ustate_key])).\n    by repeat rewrite -in_fnd.\n\n  inversion H_g1_ustate_key_opt as [H_g1_ustate_key]; clear H_g1_ustate_key_opt.\n  rewrite H_g1_ustate_key in H_lt.\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  (* replay message *)\n  exfalso.\n  simpl in H_g2.\n  assert (H_g1_g2_opt : Some (pre.(users)[`H_g1]) = Some (pre.(users)[`H_g2])).\n    by repeat rewrite -in_fnd.\n  inversion H_g1_g2_opt as [H_g1_g2]; clear H_g1_g2_opt.\n  rewrite H_g1_g2 in H_lt.\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\n\n  (* forge message *)\n  exfalso.\n  simpl in H_g2.\n  assert (H_g1_g2_opt : Some (pre.(users)[`H_g1]) = Some (pre.(users)[`H_g2])).\n    by repeat rewrite -in_fnd.\n  inversion H_g1_g2_opt as [H_g1_g2]; clear H_g1_g2_opt.\n  rewrite H_g1_g2 in H_lt.\n  rewrite <- H_rps in H_lt; apply step_lt_irrefl in H_lt; assumption.\nQed.\n\n(* a user honest at r.p must have advanced to period p *)\nLemma honest_in_period_entered\n      g0 trace (H_path : is_trace g0 trace)\n      r (H_start: state_before_round r g0):\n  forall p, 1 < p ->\n  forall uid, honest_in_period r p uid trace ->\n  exists n g1 g2, period_advance_at n trace uid r p g1 g2.\nProof.\n  clear -H_path H_start.\n  move => p H_p_gt uid [ix H_in_period].\n  move: H_in_period.\n  case H_g: (onth trace ix) => [g|] // H_in_period.\n  destruct (g.(users).[?uid]) as [u|] eqn:H_u;[|exfalso;assumption].\n  move: H_in_period => [H_honest [H_r H_p]].\n  set P := upred uid (fun u => (u.(round) == r) && (u.(period) == p)).\n  have H_Pg : P g by rewrite /P /upred H_u H_r H_p !eq_refl.\n  have H_NPg0  : ~~ P g0.\n  {\n  rewrite /P /upred.\n  destruct (g0.(users).[?uid]) as [u0|] eqn:H_u0;[|exact].\n  apply/negP => /andP [/eqP H_r0 /eqP H_p0].\n  move: H_start => [H_users_before _].\n  unfold users_before_round in H_users_before.\n  have H_in_u0: uid \\in g0.(users) by rewrite -fndSome H_u0.\n  specialize (H_users_before _ H_in_u0).\n  rewrite in_fnd in H_u0. case: H_u0 H_users_before => -> [H_u0_step _].\n  case: H_u0_step => [| [] _ [] _ [] H_p' _];[by rewrite H_r0 ltnn|].\n  by move: H_p_gt;rewrite -H_p0 H_p' ltnn.\n  }\n  have {H_Pg H_NPg0}[n [g1 [g2 [H_step H_change]]]]\n    := path_gsteps_onth H_path H_g H_NPg0 H_Pg.\n  exists n,g1,g2;split;[assumption|].\n\n  apply (transition_from_path H_path) in H_step.\n  have H_in2 : uid \\in g2.(users)\n    by move: H_change => [] _;unfold P, upred;\n       destruct g2.(users).[?uid] eqn:H_u2 => H_P2;[rewrite -fndSome H_u2|].\n  have H_in1 : uid \\in g1.(users)\n    by rewrite /in_mem /= /pred_of_finmap (gtrans_preserves_users H_step).\n  clear -H_step H_change H_in1 H_in2 H_p_gt.\n  destruct (H_step);try by exfalso;move: H_change => [] /negP.\n  * (* tick *)\n    exfalso. move: H_change => [] /negP.\n    autounfold with gtransition_unfold;unfold P, upred.\n    rewrite updf_update // (in_fnd H_in1).\n    move:(pre.(users)[`H_in1]) => u;destruct u,corrupt;exact.\n  * (* deliver *)\n    {\n    move: H_change => [] /negP.\n    rewrite {1}/delivery_result /P /upred fnd_set.\n    destruct (uid == uid0) eqn:H_eq;\n      [move/eqP in H_eq;subst uid0\n      |by move => A /A{A}].\n    rewrite (in_fnd key_ustate).\n    remember (pre.(users)[` key_ustate] : UState) as u.\n    move => H_pre /andP [/eqP H_r /eqP H_p].\n    exists key_ustate, H_in2.\n    symmetry in Hequ; rewrite Hequ.\n    intros ustate1 ustate2; subst ustate1 ustate2.\n    rewrite getf_set.\n\n    assert (step_lt (step_of_ustate u) (r,p,0)) as H_step_lt.\n    {\n      have {H_step}H_after : ustate_after u ustate_post by\n        apply (gtr_rps_non_decreasing H_step (uid:=uid));\n      [symmetry in Hequ;rewrite Hequ;apply in_fnd\n      |rewrite fnd_set eq_refl].\n      apply ustate_after_iff_step_le in H_after.\n      case:H_after =>[|[a b]];[by rewrite H_r;left|].\n      right;split;[by rewrite a|left].\n      case:b=>[|[b _]];[by rewrite H_p|exfalso].\n      apply H_pre;rewrite a b H_r H_p !eq_refl;done.\n    }\n    suff: u.(round)=ustate_post.(round) /\\ step_of_ustate ustate_post = (r,p,1) by tauto.\n    unfold step_of_ustate.\n    remember (ustate_post,sent) as result;destruct H1;\n      case:Heqresult => ? ?;subst ustate_post sent;\n        try (destruct H_pre;by rewrite H_r H_p !eq_refl).\n    + (* adv_period_open_result *)\n      by move: H_p H_r;simpl => -> ->;clear;split;reflexivity.\n    + (* adv_period_val_result *)\n      by move: H_p H_r;simpl => -> ->;clear;split;reflexivity.\n    + (* certify result *)\n      by rewrite -H_p ltnn in H_p_gt.\n    + {\n        destruct H_pre;rewrite -H_r -H_p /deliver_nonvote_msg_result.\n        clear.\n        by repeat match goal with\n                |[|- context X [match ?x with _ => _ end]] => destruct x\n               end;rewrite !eq_refl.\n      }\n    }\n  * (* internal *)\n    {\n      move: H_change => [] /negP.\n      rewrite {1}/step_result /P /upred fnd_set.\n      destruct (uid == uid0) eqn:H_eq;\n        [move/eqP in H_eq;subst uid0\n        |by move => A /A {A}].\n      rewrite (in_fnd ustate_key).\n      remember (pre.(users)[` ustate_key] : UState) as u.\n      move => H_pre /andP [/eqP H_r /eqP H_p].\n      exists ustate_key, H_in2.\n      symmetry in Hequ; rewrite Hequ.\n      intros ustate1 ustate2; subst ustate1 ustate2.\n      rewrite getf_set.\n\n      assert (step_lt (step_of_ustate u) (r,p,0)) as H_step_lt.\n      {\n        have {H_step}H_after : ustate_after u ustate_post by\n        apply (gtr_rps_non_decreasing H_step (uid:=uid));\n          [symmetry in Hequ;rewrite Hequ;apply in_fnd\n          |rewrite fnd_set eq_refl].\n        apply ustate_after_iff_step_le in H_after.\n        case:H_after =>[|[a b]];[by rewrite H_r;left|].\n        right;split;[by rewrite a|left].\n        case:b=>[|[b _]];[by rewrite H_p|exfalso].\n        apply H_pre;rewrite a b H_r H_p !eq_refl;done.\n      }\n      suff: u.(round)=ustate_post.(round) /\\ step_of_ustate ustate_post = (r,p,1) by tauto.\n      remember (ustate_post,sent) as result;destruct H0;\n      case:Heqresult => ? ?;subst ustate_post sent;\n           try (destruct H_pre;by rewrite H_r H_p !eq_refl).\n    }\n  * (* corrupt *)\n    exfalso. move: H_change => [] /negP.\n    unfold corrupt_user_result, P, upred.\n    rewrite fnd_set.\n    destruct (uid==uid0) eqn:H_eq;[|by apply].\n    move /eqP in H_eq;subst uid0.\n    by rewrite (in_fnd ustate_key).\nQed.\n\n(** An honest node can enter period [p' > 1] only if at least one honest node\nparticipated in period [p' - 1]. Note that we freeze the state of corrupt\nusers, so any user whose period actually advanced must have been honest\nat the time. *)\nLemma adv_period_from_honest_in_prev g0 trace (H_path: is_trace g0 trace)\n  r0 (H_start: state_before_round r0 g0):\n  forall n uid r p,\n    p > 0 ->\n    r0 <= r ->\n    (exists g1 g2, period_advance_at n trace uid r p g1 g2) ->\n    exists uid', honest_in_period r (p.-1) uid' trace.\nProof.\n  intros n uid r p.\n  intros H_p H_r [g1 [g2 H_adv]].\n  eapply period_advance_only_by_next_votes in H_adv;[|eassumption..].\n  destruct H_adv as (s & v & next_voters & H_voters_cred & H_voters_size & _ & ?).\n  clear g1 g2.\n  assert (H_n : n.+2 > 0) by intuition.\n  assert (exists honest_voter, honest_voter \\in next_voters /\\ honest_during_step (r,p.-1,s) honest_voter trace) as (uid_honest & H_honest_voter & H_honest)\n    by (destruct v;simpl in H_voters_size;[eapply quorum_v_has_honest|eapply quorum_b_has_honest];eassumption).\n  clear H_voters_size.\n  exists uid_honest.\n  specialize (H uid_honest H_honest_voter).\n  unfold received_next_vote in H.\n  set msg_bit :=\n    (match v with\n     | Some v => mkMsg Nextvote_Val (next_val v s) r p.-1 uid_honest\n     | None => mkMsg Nextvote_Open (step_val s) r p.-1 uid_honest\n     end) in H.\n  destruct H as [d H].\n  pose proof (received_was_sent H_path H_start H) as H1.\n  have H_r_eq: msg_round msg_bit = r by rewrite /msg_bit /=; destruct v.\n  rewrite H_r_eq in H1.\n  specialize (H1 H_r).\n  cbn -[user_sent step_in_path_at msg_step] in H1.\n  lapply H1;[clear H1|destruct v;assumption].\n  intros (ix & g1 & g2 & H_step & H_sent).\n  unfold honest_in_period;exists ix.\n  have H_onth:= step_in_path_onth_pre H_step.\n  rewrite H_onth.\n  have H_user_in := user_sent_in_pre H_sent.\n  have H_uid_eq: msg_sender msg_bit = uid_honest by rewrite /msg_bit /=; destruct v.\n  rewrite H_uid_eq in H_user_in,H_sent.\n  rewrite (in_fnd H_user_in).\n  have H_start_label := utransition_label_start H_sent (in_fnd H_user_in).\n  split.\n  { (* Honest at ix *)\n  suff: (user_honest uid_honest g1)\n      by unfold user_honest;rewrite in_fnd;move/negP.\n  apply (user_honest_from_during H_path H_onth (H_in:=H_user_in)).\n  rewrite H_start_label.\n  revert H_honest.\n  apply honest_during_le .\n  destruct v;apply step_le_refl.\n  }\n  {\n    move: (g1.(users)[`H_user_in]) H_start_label => u. clear.\n    by destruct u, v;case.\n  }\nQed.\n\n(** ** Users cannot nextvote for both a value and bottom *)\n\n(** If there is a quorum of voters for the value [v],\nthen there cannot be a quorum of voters for bottom. *)\nDefinition period_nextvoted_exclusively_for (v:Value) (r p:nat) (trace: seq GState) : Prop :=\n  (forall s (voters: {fset UserId}),\n     voters `<=` committee r p s ->\n    tau_v <= #|` voters | ->\n    forall v',\n   (forall u, u \\in voters ->\n      honest_during_step (r,p,s) u trace ->\n      nextvoted_val_in_path trace u r p s v')\n   -> v' = v) /\\\n  (forall s (voters: {fset UserId}),\n     voters `<=` committee r p s ->\n    tau_b <= #|` voters | ->\n   ~(forall u, u \\in voters ->\n      honest_during_step (r,p,s) u trace ->\n      nextvoted_bot_in_path trace u r p s)).\n\n(** If all users nextvote for [v] and all users did not nextvote for bottom, then\n[period_nextvoted_exclusively_for] holds. *)\nLemma period_nextvoted_exclusively_from_nextvotes\n      g0 trace (H_path: is_trace g0 trace)\n      r (H_start: state_before_round r g0)\n      p (H_p_gt: 1 < p)\n      v\n  (H_nextvote_val : forall (uid : UserId) (s : nat) (v' : Value),\n                            nextvoted_val_in_path trace uid r p s v' -> v' = v)\n  (H_no_nextvotes_open : forall (uid : UserId) (s : nat),\n                        honest_during_step (r, p, s) uid trace ->\n                        ~ nextvoted_bot_in_path trace uid r p s):\n  period_nextvoted_exclusively_for v r p trace.\nProof.\n  split => s voters H_creds H_size.\n  * { (* nextvote_val quorums all voted for v *)\n      have [honest_voter [H_hv_in H_hv_honest]]:= quorum_v_has_honest trace H_creds H_size.\n      move => v' /(_ _ H_hv_in H_hv_honest).\n      by apply/H_nextvote_val.\n    }\n  * { (* no nextvote_open quorums *)\n      have [honest_voter [H_hv_in H_hv_honest]]:= quorum_b_has_honest trace H_creds H_size.\n      move/(_ _ H_hv_in H_hv_honest).\n      by apply/H_no_nextvotes_open: H_hv_honest.\n    }\nQed.\n\n(** [period_nextvoted_exclusively_for] disallows [nextvote_bottom_quorum]. *)\nLemma no_bottom_quorums_during_from_nextvoted_excl\n  g0 trace (H_path: is_trace g0 trace)\n  r (H_start: state_before_round r g0)\n  p v (H_excl: period_nextvoted_exclusively_for v r p trace)\n  ix g (H_g: onth trace ix = Some g)\n  uid u (H_u: g.(users).[?uid] = Some u)\n  (H_r: u.(round) = r)\n  (H_p: u.(period) = p.+1):\n  forall s : nat, ~ nextvote_bottom_quorum u r p s.\n Proof.\n   unfold nextvote_bottom_quorum => s H_bot_quorum.\n   move:H_excl => [_ /(_ s (nextvoters_open_for u r p s)) H_no_bot_votes].\n   specialize (H_no_bot_votes (nextvote_open_credentials_checked H_path H_start H_g H_u (leqnn _) p s)).\n   apply H_no_bot_votes.\n   by move: H_bot_quorum;rewrite /nextvoters_open_for card_fseq finseq_size.\n\n   move=>bot_voter;rewrite /nextvoters_open_for inE /= => H_bv_in.\n   have[d H_recv]:= received_nextvote_open H_path H_start H_g H_u H_bv_in (leqnn _).\n   by apply/(received_was_sent H_path H_start H_recv).\nQed.\n\n(** ** Lemmas for entering period with starting value *)\n\n(** If users enter exclusively for [v] and [u] advances to [p + 1], then [u]'s starting\nvalue at [p + 1] is [v]. *)\nLemma stv_at_entry_from_excl\n      g0 trace (H_path:is_trace g0 trace)\n      r (H_start: state_before_round r g0)\n      p v (H_excl: period_nextvoted_exclusively_for v r p trace)\n      ix uid g1 g2 (H_adv: period_advance_at ix trace uid r p.+1 g1 g2)\n      u (H_u: g2.(users).[?uid] = Some u):\n      u.(stv).[? p.+1] = Some v.\nProof.\n  clear -H_path H_start H_excl H_adv H_u.\n  move: (period_advance_only_by_next_votes H_path H_start (leqnn r) H_adv).\n  move => [nv_step [v0 [voters [H_creds [H_size [H_stv H_voters_voted]]]]]].\n  move: H_stv => [u' [H_u' H_u'_stv]].\n  move: H_u';rewrite H_u;case => ?;subst u'.\n  rewrite H_u'_stv.\n\n  destruct v0 as [v0|].\n  * (* nextvote_val case *)\n    apply f_equal.\n    apply (proj1 H_excl nv_step voters H_creds H_size v0).\n    move => voter H_voter_in H_voter_honest.\n    move: (H_voters_voted _ H_voter_in) => [d H_recv].\n    exact (received_was_sent H_path H_start H_recv (leqnn _) H_voter_honest).\n  * (* nextvote_open case *)\n    exfalso.\n    apply ((proj2 H_excl) nv_step voters H_creds H_size).\n    move => voter H_voter_in H_voter_honest.\n    move: (H_voters_voted _ H_voter_in) => [d H_recv].\n    exact (received_was_sent H_path H_start H_recv (leqnn _) H_voter_honest).\nQed.\n\n(** If users enter exclusively for [v] in [r, p - 1] and [u] sends a message at [r,p], then\n[u]'s starting value at [p] is [v]. *)\nLemma stv_at_send_from_excl\n  g0 trace (H_path:is_trace g0 trace)\n  r (H_start: state_before_round r g0)\n  p (H_p_gt: 1 < p)\n  v (H_excl: period_nextvoted_exclusively_for v r p.-1 trace)\n  ix g1 g2 (H_step: step_in_path_at g1 g2 ix trace)\n  uid msg (H_send : user_sent uid msg g1 g2)\n  (H_r_msg: msg_round msg = r)\n  (H_p_msg: msg_period msg = p)\n  u (H_u: g1.(users).[?uid] = Some u) :\n u.(stv).[? p] = Some v.\nProof.\n  have H_sent_at: user_sent_at ix trace uid msg by exists g1, g2;split;assumption.\n  have H_honest_in := user_honest_in_from_send H_sent_at.\n    rewrite H_r_msg H_p_msg in H_honest_in.\n\n  move:(honest_in_period_entered H_path H_start H_p_gt H_honest_in) => [ix_entry [ge1 [ge2 H_entry]]].\n  move:(H_entry) => [_ [_ [ukey2 [_ [_ H_ue_step]]]]].\n\n  have H_ue := in_fnd ukey2.\n  set ue:UState := ge2.(users) [`ukey2] in H_ue H_ue_step.\n  move: H_ue_step => [H_r_ue H_p_ue _].\n  have H_stv_entry: ue.(stv).[? p] = Some v.\n  {\n    rewrite -[p](ltn_predK H_p_gt).\n    refine (stv_at_entry_from_excl H_path H_start H_excl _ (in_fnd ukey2)).\n    rewrite (ltn_predK H_p_gt).\n    eassumption.\n  }\n\n  have H_reach: greachable ge2 g1 by eapply post_enter_reaches_sent;eassumption.\n  have[H_r_u H_p_u _] := utransition_label_start H_send H_u.\n\n  symmetry;rewrite -H_stv_entry.\n  by apply (stv_forward H_reach H_ue H_u);congruence.\nQed.\n\n(** ** Vote uniqueness based on value nextvoted in previous period *)\n\n(** If all honest nodes that entered a period [p - 1 >= 2] did so exclusively for\nvalue [v], then an honest node cannot cert-vote for any value other than [v] in step\n2 of period [p]. *)\nLemma prev_period_nextvotes_limits_honest_soft_vote\n  g0 trace (H_path: is_trace g0 trace)\n  r (H_start: state_before_round r g0)\n  p (H_p_gt: 1 < p)\n  v (H_excl: period_nextvoted_exclusively_for v r p.-1 trace):\n  forall uid, honest_during_step (r,p,2) uid trace ->\n  forall v', softvoted_in_path trace uid r p v' -> v' = v.\nProof.\n  move => uid H_honest v' [ix H_voted].\n\n  move: H_voted => [g1 [g2 [H_step H_send]]].\n  have H_u := in_fnd (user_sent_in_pre H_send).\n  set u: UState := g1.(users)[` user_sent_in_pre H_send] in H_u.\n\n  have stv_fwd : u.(stv).[? p] = Some v\n    := stv_at_send_from_excl H_path H_start H_p_gt H_excl H_step H_send erefl erefl H_u.\n\n  have H_g1 := step_in_path_onth_pre H_step.\n\n  have:=utransition_label_start H_send H_u.\n  unfold msg_step, msg_round, msg_period => -/= [H_r_u H_p_u _].\n\n  have no_bot_quroums: forall s, ~nextvote_bottom_quorum u r p.-1 s. {\n    rewrite -[p](ltn_predK H_p_gt) in H_p_u.\n    eapply no_bottom_quorums_during_from_nextvoted_excl;eassumption.\n  }\n\n  case:(softvote_precondition H_send H_u).\n  * { (* softvote_new *)\n      unfold softvote_new_ok => -[_] [_] [_] [[]].\n        by rewrite /cert_may_exist H_r_u H_p_u subn1.\n    }\n  * { (* softvote_repr *)\n      unfold softvote_repr_ok => -[_] [_] [_] [_] [[H_cert _]|[_ H_stv']].\n      by case:H_cert;rewrite /cert_may_exist H_r_u H_p_u subn1.\n      by move:H_stv';rewrite stv_fwd => -[<-].\n    }\nQed.\n\n(** If all honest nodes that entered a period [p >= 2] did so exclusively for\nvalue [v], then an honest node cannot cert-vote for any value other than [v] in step\n3 of period [p']. *)\nLemma prev_period_nextvotes_limits_cert_vote :\n  forall g0 trace (H_path: is_trace g0 trace),\n  forall r (H_start: state_before_round r g0) ,\n  forall p, 1 < p ->\n  forall v, period_nextvoted_exclusively_for v r p.-1 trace ->\n  forall uid v',\n    honest_during_step (r,p,3) uid trace ->\n    certvoted_in_path trace uid r p v' -> v' = v.\nProof.\n  clear.\n  move => g0 trace H_path r H_start p H_p v H_excl uid v' H_honest H_vote.\n  destruct H_vote as [ix_cert H_vote].\n\n  have H_honest_in:= user_honest_in_from_send H_vote.\n\n  unfold certvoted_in_path_at in H_vote.\n  destruct H_vote as (g1_v & g2_v & H_vote_step & H_vote_send).\n\n  have H_g2 := step_in_path_onth_post H_vote_step.\n  set H_in: uid \\in g2_v.(users) := user_sent_in_post H_vote_send.\n  have H_u := in_fnd H_in.\n  set u: UState := (g2_v.(users)[` H_in]) in H_u.\n\n\n  have H_softvotes_for_v := prev_period_nextvotes_limits_honest_soft_vote H_path H_start H_p H_excl.\n\n  have [H_in_certvals _]:= certvote_postcondition H_vote_send H_u.\n  unfold certvals in H_in_certvals.\n\n  have H_creds := softvote_credentials_checked H_path H_start H_g2 H_u (leqnn _) v' p.\n  move: H_in_certvals;rewrite mem_filter /soft_weight => /andP [H_size _].\n  have [uid_sv [H_in_sv H_sv_honest]] := quorum_s_has_honest trace H_creds H_size.\n\n  apply (H_softvotes_for_v _ H_sv_honest).\n\n  have [d H_recv]: exists d : R, msg_received uid d (mkMsg Softvote (val v') r p uid_sv) trace.\n  {\n    move: H_in_sv => /imfsetP /= [[x_uid x_v] /andP [H_in_x /eqP ? /= ?]];subst x_uid x_v.\n    exact (received_softvote H_path H_start H_g2 H_u H_in_x (leqnn r)).\n  }\n\n  apply (received_was_sent H_path H_start H_recv (leqnn r) H_sv_honest).\nQed.\n\n(** ** Lemmas for propagating value nextvoted for from previous period *)\n\n(** In [p - 1], all nextvotes were for [v], and at step 2 in [p], all softvotes were for\n[v], then at all steps in [p], all nextvotes were for [v]. *)\nLemma nextvotes_val_follow_softvotes\n      g0 trace (H_path: is_trace g0 trace)\n      r (H_start: state_before_round r g0)\n      p (H_p_gt: 1 < p)\n      v (H_excl: period_nextvoted_exclusively_for v r p.-1 trace):\n  (forall uid_sv : UserId,\n      honest_during_step (r,p,2) uid_sv trace ->\n      forall v', softvoted_in_path trace uid_sv r p v' -> v' = v) ->\n  (forall uid_nv s,\n      honest_during_step (r,p,s) uid_nv trace ->\n      forall v', nextvoted_val_in_path trace uid_nv r p s v' -> v' = v).\nProof.\n  move => H_softvotes uid_nv s H_honest_nv v' [ix_nv H_nextvoted].\n  move: (H_nextvoted) => [g1 [g2 [H_step_nv H_send_nv]]].\n  set H_in1 := user_sent_in_pre H_send_nv.\n  set H_u1 := in_fnd H_in1.\n  set u1 : UState := g1.(users)[`H_in1] in H_u1.\n  change (user_sent_at ix_nv trace uid_nv (mkMsg Nextvote_Val (next_val v' s) r p uid_nv))\n       in H_nextvoted.\n\n  case:(nextvote_val_precondition H_send_nv H_u1).\n  *\n    move => [_] [_] [_] [_] [_] [_] [_].\n    have H_softvotes_for_v := prev_period_nextvotes_limits_honest_soft_vote H_path H_start H_p_gt H_excl.\n\n    have H_g1 := step_in_path_onth_pre H_step_nv.\n    have H_creds := softvote_credentials_checked H_path H_start H_g1 H_u1 (leqnn _) v' p.\n    rewrite /certvals mem_filter /soft_weight => /andP [H_size _].\n    have [uid_sv [H_in_sv H_sv_honest]] := quorum_s_has_honest trace H_creds H_size.\n    apply (H_softvotes_for_v _ H_sv_honest).\n\n    apply/(softvotes_sent H_path H_start H_g1 H_u1 (leqnn r)): H_sv_honest.\n    move:H_in_sv => /imfsetP /= [] x /andP [H_x_in].\n    unfold matchValue. destruct x. move => /eqP ? /= ?;subst.\n    assumption.\n\n  * move => [_].\n    rewrite (stv_at_send_from_excl H_path H_start H_p_gt H_excl H_step_nv H_send_nv erefl erefl H_u1).\n    by case => ->.\nQed.\n\n(** If users enter exclusively for [v] in [p - 1], then users enter exclusively for [v] in [p]. *)\nLemma excl_enter_excl_next:\n  forall g0 trace (H_path: is_trace g0 trace),\n  forall r (H_start: state_before_round r g0),\n  forall (p : nat) (v : Value),\n    1 < p ->\n    period_nextvoted_exclusively_for v r p.-1 trace ->\n    period_nextvoted_exclusively_for v r p trace.\nProof.\n  move => g0 trace H_path r H_start p v H_p_gt H_prev_excl.\n  simpl in H_prev_excl.\n\n  have H_honest_softvotes: forall uid, honest_during_step (r,p,2) uid trace ->\n                            forall v', softvoted_in_path trace uid r p v' ->\n                                       v' = v\n   := prev_period_nextvotes_limits_honest_soft_vote H_path H_start H_p_gt H_prev_excl.\n\n  have H_nextvote_val_respects: forall uid s v', nextvoted_val_in_path trace uid r p s v' -> v' = v.\n  {\n    have:= (nextvotes_val_follow_softvotes H_path H_start H_p_gt H_prev_excl H_honest_softvotes).\n    clear -H_path.\n    move => H uid s v' H_voted.\n    apply/H: (H_voted).\n    move: H_voted => [ix H_voted].\n    exact (honest_during_from_sent H_path H_voted).\n  }\n\n  have H_no_nextvotes_open: forall uid s, honest_during_step (r,p,s) uid trace -> ~nextvoted_bot_in_path trace uid r p s.\n  {\n    move => uid s H_honest [ix [g1 [g2 [H_step H_vote]]]].\n    set H_u := in_fnd (user_sent_in_pre H_vote).\n    set H_g1 := step_in_path_onth_pre H_step.\n    have := nextvote_open_precondition H_vote H_u.\n    move => [_] [_] [_] [_] [_] /(_ H_p_gt).\n    have:=utransition_label_start H_vote H_u.\n    unfold msg_step, msg_round, msg_period => -/=[H_r_u H_p_u H_s_u].\n    rewrite subn1.\n    apply (no_bottom_quorums_during_from_nextvoted_excl H_path H_start H_prev_excl H_g1 H_u H_r_u).\n    by rewrite (ltn_predK H_p_gt).\n  }\n\n  by apply/(period_nextvoted_exclusively_from_nextvotes H_path).\nQed.\n\n(** ** Propagate certificate information forward *)\n\n(** Cert info from [saw_v] at [r,p] remains true at [g1]. *)\nLemma certinfo_forward\n  g0 trace (H_path: is_trace g0 trace)\n  r (H_start: state_before_round r g0)\n  p v uid (H_saw: saw_v trace r p v uid)\n  ix g1 g2 (H_step: step_in_path_at g1 g2 ix trace)\n  u (H_u: g1.(users).[? uid] = Some u)\n  msg (H_send: user_sent uid msg g1 g2)\n  (H_u_step: step_le (r,p,4) (msg_step msg)):\n  v \\in certvals u r p\n  /\\ exists b, b \\in blocks u r /\\ valid_block_and_hash b v.\nProof.\n  move: H_saw => /(@hasP _ _ trace)=> -[g_mid H_g_mid].\n  case:fndP => // key_mid.\n  set u_mid: UState := g_mid.(users)[`key_mid].\n  move => /andP[H_v_certval_mid /andP[H_blocks_mid] /step_leP H_mid_step_le].\n  set H_g1 := step_in_path_onth_pre H_step.\n  set key1 := user_sent_in_pre H_send.\n  rewrite (in_fnd key1) in H_u.\n  case: H_u => ?;subst u.\n  set u := g1.(users)[`key1].\n\n  assert (greachable g_mid g1) as H_reach.\n  {\n    assert (index g_mid trace <= ix). {\n      rewrite -ltnS.\n      pose proof (order_ix_from_steps H_path (onth_index H_g_mid) (step_in_path_onth_post H_step)).\n      apply (H _ key_mid (user_sent_in_post H_send)).\n\n      apply (step_le_lt_trans H_mid_step_le).\n      have:= (utransition_label_end H_send (in_fnd (user_sent_in_post H_send))).\n      apply/step_le_lt_trans.\n      assumption.\n    }\n    exact (at_greachable H_path H (onth_index H_g_mid) (step_in_path_onth_pre H_step)).\n  }\n  have H_softvotes_advance := softvotes_monotone H_reach (in_fnd key_mid) (in_fnd key1).\n\n  assert (v \\in certvals u r p).\n  {\n    move: H_v_certval_mid.\n    rewrite !mem_filter => /andP [H_size_mid H_votes_mid].\n    apply/andP.\n    split.\n    *\n      apply (leq_trans H_size_mid).\n      apply fsubset_leq_card.\n      apply subset_imfset.\n      move => x /andP [x_mem x_prop].\n      apply/andP;split;[|exact x_prop].\n      by apply (H_softvotes_advance r p).\n    *\n      move: H_votes_mid.\n      rewrite !mem_undup.\n      move/mapP => -[x H_x_in H_x2].\n      apply/mapP;exists x;[|assumption].\n      by apply (H_softvotes_advance r p).\n  }\n\n  move: H_blocks_mid => /hasP [b' H_b' /asboolP H_b'_valid].\n  assert (b' \\in u.(blocks) r).\n  {\n    move: {H_b'_valid}b' H_b'.\n    exact: (blocks_monotone H_reach (in_fnd key_mid) (in_fnd key1)).\n  }\n\n  by split;[|exists b';split].\nQed.\n\n(** ** Entering period for certified value *)\n\n(** [v] certified in [p] means users enter [p] nextvoting for [v]. *)\nLemma certificate_is_start_of_next_period\n  g0 trace (H_path: is_trace g0 trace)\n  r (H_start: state_before_round r g0)\n  p v (H_cert: certified_in_period trace r p v):\n    period_nextvoted_exclusively_for v r p trace.\nProof.\n  clear -H_path H_start H_cert.\n  destruct H_cert as [certvote_quorum [H_comm [H_q_size H_vote]]].\n\n  destruct (quorum_c_has_honest trace H_comm H_q_size) as [certvoter [H_inq H_cv_honest]].\n\n  move:(H_vote certvoter H_inq) => [ix_cv [g1_cv [g2_cv [H_step_cv H_sent_cv]]]].\n\n  have H_g2 := step_in_path_onth_post H_step_cv.\n  have key2 := user_sent_in_post H_sent_cv.\n  have H_u2 := in_fnd key2.\n  set u2: UState := g2_cv.(users)[`key2] in H_u2.\n\n  move:(certvote_postcondition H_sent_cv H_u2) => [H_certvals [[b [H_blocks H_block_valid]] H_g2_step]].\n\n  have H_certvoters_saw_v:\n    forall uid : UserId, uid \\in certvote_quorum -> honest_during_step (r, p, 3) uid trace -> saw_v trace r p v uid.\n  {\n    move => cv2 H_in2 H_hon2.\n    move: (H_vote _ H_in2) => [ix2 [g1' [g2' [H_step' H_send']]]].\n    move:(certvote_postcondition H_send' (in_fnd (user_sent_in_post H_send'))) =>\n    [H_certvals' [[b' [H_blocks' H_block_valid']] H_g2'_step]].\n    unfold saw_v.\n    apply/(@hasP GState_eqType _ trace).\n    exists g2'.\n    pose proof (step_in_path_onth_post H_step').\n    eapply onth_in; eassumption.\n    rewrite (in_fnd (user_sent_in_post H_send')).\n    apply/andP;split;[|apply/andP;split].\n    assumption.\n      by apply/hasP;exists b';[|apply/asboolP].\n    unfold step_of_ustate;move: H_g2'_step => [-> [-> ->]].\n    apply/step_leP/step_le_refl.\n  }\n\n  have H_softvote_quorums_only_for_v :\n    forall quorum2,\n      quorum2 `<=` committee r p 2 ->\n      tau_s <= #|` quorum2| ->\n    forall v',\n    (forall voter, voter \\in quorum2 ->\n                   honest_during_step (r,p,2) voter trace ->\n                   softvoted_in_path trace voter r p v') ->\n      v' = v.\n  {\n    move => q2 H_certs_q2 H_size_q2 v' H_voters_q2.\n    assert (tau_s <= soft_weight v u2 r p) as H_v\n        by (move: H_certvals;rewrite mem_filter => /andP [] //).\n    have H_votes_checked :=\n      softvote_credentials_checked H_path H_start (step_in_path_onth_post H_step_cv) H_u2 (leqnn r).\n    move:(quorums_s_honest_overlap trace (H_votes_checked v p) H_v H_certs_q2 H_size_q2)\n    => [common_voter [H_voter_in_q1 [H_voter_in_q2 H_voter_honest]]].\n\n    move/(_ _ H_voter_in_q2 H_voter_honest):H_voters_q2 => {H_voter_in_q2}[ix_sv' H_voted_v'].\n\n    move: H_voter_in_q1 => /imfsetP [[x_1 x_2]] /= /andP [H] /eqP H1 H2.\n    move:H1 H2 H => {x_1}<- {x_2}<- => H_in_softvotes.\n\n    move:(softvotes_sent H_path H_start H_g2 H_u2 (leqnn r) H_in_softvotes H_voter_honest) => [ix_sv].\n    by apply (no_two_softvotes_in_p H_path H_voted_v').\n  }\n\n  have H_interquorum_v := interquorum_c_v_certinfo H_comm H_q_size H_certvoters_saw_v.\n  have H_interquorum_b := interquorum_c_b_certinfo H_comm H_q_size H_certvoters_saw_v.\n\n  split.\n  (* For value votes:\n     By interquorum assumptions, any nextvote quorum contains an honest voter\n     which (would have) certvoted for v in step 3.\n       Having seen a quorum of softvotes rules out an stv-based nextvote.\n       A quorum of softvotes for the v' they voted for\n       would have honest overlap with the softvote v quorum\n       so by no_two_softvotes_in_p we have v = v'.\n   *)\n  {\n  move => s nextvoters H_nv_creds H_nv_size v' H_nv_voted.\n  move: H_interquorum_v => /(_ r p s _ H_nv_creds H_nv_size)\n    => -[uid_nv [H_in_nv [H_saw_v H_honest]]].\n  move:H_nv_voted =>/(_ _ H_in_nv H_honest){H_in_nv} [ix_nv [g1_nv [g2_nv [H_step_nv H_send_nv]]]].\n\n  set key1_nv := user_sent_in_pre H_send_nv.\n  set u1_nv := g1_nv.(users)[` key1_nv].\n\n  case:(nextvote_val_precondition H_send_nv (in_fnd key1_nv)) => [[b0]|].\n  * (* nextvote_val_ok *)\n    unfold nextvote_val_ok => -[_] [_] [_] [_] [_] [_].\n    unfold certvals.\n    rewrite !mem_filter => /andP [H_sv_size H_sv_votes].\n    have H_sv_creds := (softvote_credentials_checked H_path H_start\n         (step_in_path_onth_pre H_step_nv) (in_fnd key1_nv) (leqnn r) v' p).\n\n    apply (H_softvote_quorums_only_for_v _ H_sv_creds H_sv_size).\n\n    have:= softvotes_sent H_path H_start (step_in_path_onth_pre H_step_nv) (in_fnd key1_nv) (leqnn r).\n    clear.\n    move=> H_sv_sent voter H_in.\n    apply H_sv_sent.\n      by move: H_in => /imfsetP [[x0 x1] /andP [H_in /eqP ->] /= ->].\n  * (* nextvote_stv_ok *)\n    unfold nextvote_stv_ok => -[] [_] [_] [_] [H_s] [/(_ v)H_no_good_certvals _] _.\n    have H_good_certval := certinfo_forward H_path H_start H_saw_v H_step_nv (in_fnd key1_nv) H_send_nv.\n    unfold msg_step, msg_round, msg_period in H_good_certval;cbn -[step_le] in H_good_certval.\n    have: step_le (r,p,4) (r,p,s) by apply/step_leP;rewrite /= !ltnn !eq_refl H_s /=.\n    move/H_good_certval => [H_v_certval [b0 [H_b0_blocks H_b0_valid]]].\n    exfalso.\n    exact (H_no_good_certvals H_v_certval _ H_b0_blocks H_b0_valid).\n  }\n\n  (* For no bottom votes:\n     By interquorum assumption, any nextvote quorum contains an honest voter\n     which (would have) certvoted for v in step 3.\n       Having seen enough softvotes violates the precondition for voting for bottom.\n   *)\n  {\n\n  move => s bot_voters H_bot_creds H_bot_size H_bot_voted.\n  move: H_interquorum_b\n    => /(_ r p s _ H_bot_creds H_bot_size){H_bot_creds H_bot_size}\n    => -[honest_bot_voter [H_honest_in [H_honest_saw H_honest_honest]]].\n  move: H_bot_voted => /(_ _ H_honest_in H_honest_honest){H_honest_in}\n                       [ix_nv [g1_nv [g2_nv [H_step_nv H_send_nv]]]].\n\n\n  set key1_nv := user_sent_in_pre H_send_nv.\n  set u1_nv := g1_nv.(users)[` key1_nv].\n\n  have := nextvote_open_precondition H_send_nv (in_fnd key1_nv).\n  move => -[_] [_] [_] [H_s] [/(_ v)H_no_good_certvals _].\n\n  have H_good_certval := certinfo_forward H_path H_start H_honest_saw H_step_nv (in_fnd key1_nv) H_send_nv.\n  unfold msg_step, msg_round, msg_period in H_good_certval;cbn -[step_le] in H_good_certval.\n  have: step_le (r,p,4) (r,p,s) by apply/step_leP;rewrite /= !ltnn !eq_refl H_s /=.\n  move/H_good_certval => [H_v_certval [b0 [H_b0_blocks H_b0_valid]]].\n  exfalso.\n  exact (H_no_good_certvals H_v_certval _ H_b0_blocks H_b0_valid).\n  }\nQed.\n\n(** [v] certified in [r,p] means users enter all [p' >= p] nextvoting for [v]. *)\nLemma certificate_is_start_of_later_periods\n  trace g0  (H_path: is_trace g0 trace)\n  r (H_start: state_before_round r g0):\n  forall p,  1 <= p ->\n  forall v,\n    certified_in_period trace r p v ->\n  forall p', p <= p' ->\n    period_nextvoted_exclusively_for v r p' trace.\nProof.\n  move => p H_p v H_cert p' H_p_lt.\n  have: p' = (p + (p' - p))%nat by symmetry;apply subnKC.\n  move: (p' - p)%nat => n {p' H_p_lt}->.\n  elim:n.\n  (* Next step after certification *)\n  by rewrite addn0;apply/(certificate_is_start_of_next_period H_path).\n  (* Later steps *)\n  move => n;rewrite addnS.\n  apply (excl_enter_excl_next H_path H_start (p:=(p+n).+1)).\n  by rewrite ltnS addn_gt0 H_p.\nQed.\n\n(** ** One certificate per period *)\n\n(** Only one value can be certified in a given [r,p] pair. *)\nLemma one_certificate_per_period: forall g0 trace r p,\n    state_before_round r g0 ->\n    is_trace g0 trace ->\n    forall v1, certified_in_period trace r p v1 ->\n    forall v2, certified_in_period trace r p v2 ->\n    v1 = v2.\nProof.\n  clear.\n  intros g0 trace r p H_start H_path v1 H_cert1 v2 H_cert2.\n  destruct H_cert1 as (quorum1 & H_q1 & H_size1 & H_cert1).\n  destruct H_cert2 as (quorum2 & H_q2 & H_size2 & H_cert2).\n  pose proof (quorums_c_honest_overlap trace H_q1 H_size1 H_q2 H_size2).\n  destruct H as (voter & H_common1 & H_common2 & H_honest).\n  specialize (H_cert1 _ H_common1).\n  specialize (H_cert2 _ H_common2).\n  destruct H_cert1 as [ix1 H_cert1].\n  destruct H_cert2 as [ix2 H_cert2].\n\n  assert (user_honest_at ix1 trace voter) as H_honest1. {\n  move: H_cert1.\n  unfold certvoted_in_path_at. move => [g1 [g2 [H_step H_vote]]].\n\n  pose proof (in_fnd (user_sent_in_pre H_vote)) as H0.\n  set ustate := g1.(users)[`user_sent_in_pre H_vote] in H0.\n  clearbody ustate.\n  have H1: (step_of_ustate ustate) = (r,p,3) := utransition_label_start H_vote H0.\n\n  pose proof (honest_at_from_during H_honest H_path) as H.\n  specialize (H _ _ (step_in_path_onth_pre H_step)).\n  specialize (H _ H0).\n  apply H.\n  rewrite H1.\n  apply step_le_refl.\n  }\n\n  assert (user_honest_at ix2 trace voter) as H_honest2. {\n  move: H_cert2.\n  unfold certvoted_in_path_at. move => [g1 [g2 [H_step H_vote]]].\n  pose proof (honest_at_from_during H_honest H_path) as H.\n  specialize (H _ _ (step_in_path_onth_pre H_step)).\n  pose proof (in_fnd (user_sent_in_pre H_vote)).\n  set ustate := g1.(users)[`user_sent_in_pre H_vote] in H0.\n  clearbody ustate.\n  specialize (H _ H0).\n  apply H.\n  rewrite (utransition_label_start H_vote H0);apply step_le_refl.\n  }\n\n  by destruct (no_two_certvotes_in_p H_path H_cert1 H_honest1 H_cert2 H_honest2).\nQed.\n\n(** ** Safety *)\n\n(** The safety theorem: only one value can be certified in each round. This means\nthat at most one block is approved in a given round. *)\nTheorem safety : forall (g0 : GState) (trace : seq GState) (r : nat),\n  state_before_round r g0 ->\n  is_trace g0 trace ->\n  forall (p1 : nat) (v1 : Value), certified_in_period trace r p1 v1 ->\n  forall (p2 : nat) (v2 : Value), certified_in_period trace r p2 v2 ->\n  v1 = v2.\nProof.\n  intros g0 trace r H_start H_path p1 v1 H_cert1 p2 v2 H_cert2.\n  wlog: p1 v1 H_cert1 p2 v2 H_cert2 / (p1 <= p2).\n  { (* showing this suffices *)\n  intros H_narrowed.\n  destruct (p1 <= p2) eqn:H_test;[|symmetry];eapply H_narrowed;try eassumption.\n  apply ltnW. rewrite ltnNge. rewrite H_test. done.\n  }\n  (* Continuing proof *)\n  intro H_le.\n  destruct (eqVneq p1 p2).\n  * (* Two blocks certified in same period. *)\n  subst p2; clear H_le.\n  eapply one_certificate_per_period;eassumption.\n  *\n  (* Second certificate produced in a later period *)\n  assert (p1 < p2) as Hlt by (rewrite ltn_neqAle;apply /andP;split;assumption).\n  clear H_le i.\n  assert (1 <= p1) as H_p1.\n  {\n    move: H_cert1 => [quorum_p1 [H_creds [H_size _]]].\n    move: (quorum_c_has_honest trace H_creds H_size) => [voter1 [H_in _]].\n    move: H_creds => /fsubsetP /(_ _ H_in) /imfsetP [x H H_x].\n    move: H_x H => {x}<- /asboolP.\n    apply credentials_valid_period.\n  }\n  have H_p2: p1 <= p2.-1 by rewrite -ltnS (ltn_predK Hlt).\n\n  destruct (nosimpl H_cert2) as (q2 & H_q2 & H_size2 & H_cert2_voted).\n  destruct (quorum_c_has_honest trace H_q2 H_size2)\n     as (honest_voter & H_honest_q & H_honest_in).\n\n  specialize (H_cert2_voted honest_voter H_honest_q).\n  destruct (nosimpl H_cert2_voted) as (ix & ga1 & ga2 & [H_step2 H_send_vote2]).\n  assert (honest_in_period r p2 honest_voter trace)\n   by (eapply honest_in_from_during_and_send;[eassumption..|apply step_le_refl]).\n\n  symmetry.\n  have H_p2': 1 < p2 by apply (leq_trans (n:=p1.+1));[rewrite ltnS|].\n  have H_excl := certificate_is_start_of_later_periods H_path H_start H_p1 H_cert1 H_p2.\n  exact (prev_period_nextvotes_limits_cert_vote H_path H_start H_p2' H_excl H_honest_in H_cert2_voted).\nQed.\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/safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.1641695934206885}}
{"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.rec_granule_measure.\n\nRequire Import RmiAux2.LowSpecs.rec_granule_measure.\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    _measurement_extend_rec_header \u21a6 gensem measurement_extend_rec_header_spec\n      \u2295 _measurement_extend_rec_regs \u21a6 gensem measurement_extend_rec_regs_spec\n      \u2295 _measurement_extend_rec_pstate \u21a6 gensem measurement_extend_rec_pstate_spec\n      \u2295 _measurement_extend_rec_sysregs \u21a6 gensem measurement_extend_rec_sysregs_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_measurement_extend_rec_header: block.\n    Hypothesis h_measurement_extend_rec_header_s : Genv.find_symbol ge _measurement_extend_rec_header = Some b_measurement_extend_rec_header.\n    Hypothesis h_measurement_extend_rec_header_p : Genv.find_funct_ptr ge b_measurement_extend_rec_header\n                                                   = Some (External (EF_external _measurement_extend_rec_header\n                                                                    (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default))\n                                                          (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default).\n    Local Opaque measurement_extend_rec_header_spec.\n\n    Variable b_measurement_extend_rec_regs: block.\n    Hypothesis h_measurement_extend_rec_regs_s : Genv.find_symbol ge _measurement_extend_rec_regs = Some b_measurement_extend_rec_regs.\n    Hypothesis h_measurement_extend_rec_regs_p : Genv.find_funct_ptr ge b_measurement_extend_rec_regs\n                                                 = Some (External (EF_external _measurement_extend_rec_regs\n                                                                  (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default))\n                                                        (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default).\n    Local Opaque measurement_extend_rec_regs_spec.\n\n    Variable b_measurement_extend_rec_pstate: block.\n    Hypothesis h_measurement_extend_rec_pstate_s : Genv.find_symbol ge _measurement_extend_rec_pstate = Some b_measurement_extend_rec_pstate.\n    Hypothesis h_measurement_extend_rec_pstate_p : Genv.find_funct_ptr ge b_measurement_extend_rec_pstate\n                                                   = Some (External (EF_external _measurement_extend_rec_pstate\n                                                                    (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default))\n                                                          (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default).\n    Local Opaque measurement_extend_rec_pstate_spec.\n\n    Variable b_measurement_extend_rec_sysregs: block.\n    Hypothesis h_measurement_extend_rec_sysregs_s : Genv.find_symbol ge _measurement_extend_rec_sysregs = Some b_measurement_extend_rec_sysregs.\n    Hypothesis h_measurement_extend_rec_sysregs_p : Genv.find_funct_ptr ge b_measurement_extend_rec_sysregs\n                                                    = Some (External (EF_external _measurement_extend_rec_sysregs\n                                                                     (signature_of_type (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default))\n                                                           (Tcons Tptr (Tcons Tptr Tnil)) tvoid cc_default).\n    Local Opaque measurement_extend_rec_sysregs_spec.\n\n    Lemma rec_granule_measure_body_correct:\n      forall m d d' env le rd_base rd_offset rec_base rec_offset data_size\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTrd: PTree.get _rd le = Some (Vptr rd_base (Int.repr rd_offset)))\n             (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset)))\n             (HPTdata_size: PTree.get _data_size le = Some (Vlong data_size))\n             (Hspec: rec_granule_measure_spec0 (rd_base, rd_offset) (rec_base, rec_offset) (VZ64 (Int64.unsigned data_size)) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) rec_granule_measure_body E0 le' (m, d') Out_normal).\n    Proof.\n      solve_code_proof Hspec rec_granule_measure_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RmiAux2/CodeProof/rec_granule_measure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3208213073183839, "lm_q1q2_score": 0.164169590097715}}
{"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 RunComplete.Spec.\nRequire Import RunAux.Spec.\nRequire Import RunLoop.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition smc_rec_run_spec0 (rec_addr: Z64) (rec_run_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match rec_addr, rec_run_addr with\n    | VZ64 _rec_addr, VZ64 _rec_run_addr =>\n      rely is_int64 _rec_run_addr;\n      when'' _g_rec_run_base, _g_rec_run_ofst == find_granule_spec (VZ64 _rec_run_addr) adt;\n      rely is_int _g_rec_run_ofst;\n      when _t'8 == is_null_spec (_g_rec_run_base, _g_rec_run_ofst) adt;\n      rely is_int _t'8;\n      if (_t'8 =? 1) then\n        Some (adt, (VZ64 1))\n      else\n        rely is_int64 _rec_addr;\n        when'' _g_rec_base, _g_rec_ofst, adt == find_lock_unused_granule_spec (VZ64 _rec_addr) (VZ64 3) adt;\n        rely is_int _g_rec_ofst;\n        when _t'7 == is_null_spec (_g_rec_base, _g_rec_ofst) adt;\n        rely is_int _t'7;\n        if (_t'7 =? 1) then\n          Some (adt, (VZ64 1))\n        else\n          when adt == atomic_granule_get_spec (_g_rec_base, _g_rec_ofst) adt;\n          when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n          when adt == ns_granule_map_spec 0 (_g_rec_run_base, _g_rec_run_ofst) adt;\n          when _t'6, adt == ns_buffer_read_rec_run_spec 0 adt;\n          rely is_int _t'6;\n          if (_t'6 =? 0) then\n            when adt == ns_buffer_unmap_spec 0 adt;\n            when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n            Some (adt, (VZ64 1))\n          else\n            when'' _rec_base, _rec_ofst, adt == granule_map_spec (_g_rec_base, _g_rec_ofst) 3 adt;\n            rely is_int _rec_ofst;\n            when adt == granule_lock_spec (_g_rec_base, _g_rec_ofst) adt;\n            when _t'5 == get_rec_runnable_spec (_rec_base, _rec_ofst) adt;\n            rely is_int _t'5;\n            if (_t'5 =? 0) then\n              when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n              when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt;\n              when adt == ns_buffer_unmap_spec 0 adt;\n              when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n              Some (adt, (VZ64 1))\n            else\n              when _t'4, adt == complete_mmio_emulation_spec (_rec_base, _rec_ofst) adt;\n              rely is_int _t'4;\n              if (_t'4 =? 0) then\n                when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n                when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt;\n                when adt == ns_buffer_unmap_spec 0 adt;\n                when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n                Some (adt, (VZ64 1))\n              else\n                when adt == complete_hvc_exit_spec (_rec_base, _rec_ofst) adt;\n                when adt == reset_last_run_info_spec (_rec_base, _rec_ofst) adt;\n                when adt == reset_disposed_info_spec (_rec_base, _rec_ofst) adt;\n                when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n                when adt == rec_run_loop_spec (_rec_base, _rec_ofst) adt;\n                Some (adt, (VZ64 2))\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/RunSMC/LowSpecs/smc_rec_run.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.16416958345176813}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.tests.Echo Platform.Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [Echo.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"test\"!\"main\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link Echo.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link Echo.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/tests/EchoDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.16367130098114108}}
{"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: Refinement Proof for MPTNew             *)\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 MPTBit layer and MPTNew layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\nRequire Import MPTNew.\nRequire Import AbstractDataType.\n\nRequire Import PTNewGenSpec.\nRequire Import LayerCalculusLemma.\n\nRequire Import ObjFlatMem.\nRequire Import ObjLMM0.\nRequire Import ObjLMM1.\nRequire Import ObjContainer.\nRequire Import ObjCPU.\nRequire Import ObjVMMFun.\nRequire Import ObjVMMGetSet.\n\n(** * Notation of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := mptinit_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := mptinit_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** Relation between raw data at two layers*)\n    Record relate_RData (f: meminj) (hadt: LDATA) (ladt: LDATA) :=\n      mkrelate_RData {\n          flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n          vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n          devout_re: devout hadt = devout ladt;\n          ikern_re: ikern ladt = ikern hadt;\n          pg_re: pg ladt = pg hadt;\n          ihost_re: ihost ladt = ihost hadt;\n          AC_re: AC ladt = AC hadt;\n          ti_fst_re: (fst (ti ladt)) = (fst (ti hadt));\n          ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n          LAT_re: LAT ladt = LAT hadt;\n          nps_re: nps ladt = nps hadt;\n          PT_re:  PT ladt = PT hadt;\n          ptp_re: ptpool ladt = ptpool hadt;\n          ipt_re: ipt ladt = ipt hadt;\n          init_re: init ladt = init hadt;\n          pperm_re: pperm ladt = pperm hadt;\n          idpde_re: idpde ladt = idpde hadt\n\n        }.\n\n    Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n    | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n    Local Hint Resolve MATCH_RDATA.\n\n    Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n      {\n        relate_AbData s f d1 d2 := relate_RData f d1 d2;\n        match_AbData s d1 m f := match_RData s d1 m f;\n        new_glbl := nil\n      }.    \n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      Section FRESH_PRIM.\n\n        Lemma pt_new_spec_kernel_mode:\n          forall d d' id q z,\n            pt_new_spec id q d = Some (d', z) ->\n            kernel_mode d.\n        Proof.\n          intros. simpl; functional inversion H; eauto.\n        Qed.\n\n        Lemma pt_new_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem pt_new_spec) pt_new_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit pt_new_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit pt_new_spec_kernel_mode; eauto. intros.\n          refine_split; try econstructor; eauto. \n          constructor.\n        Qed.\n\n        Lemma ptResv_spec_kernel_mode:\n          forall d d' i i0 i1 z,\n            ptResv_spec i i0 i1 d = Some (d', z) ->\n            kernel_mode d.\n        Proof.\n          intros. simpl; functional inversion H; eauto.\n          - functional inversion H2; eauto.\n          - functional inversion H1; eauto.\n        Qed.\n\n        Lemma ptResv_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem ptResv_spec) ptResv_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit ptResv_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit ptResv_spec_kernel_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        Lemma ptResv2_spec_kernel_mode:\n          forall d d' i i0 i1 i2 i3 i4 z,\n            ptResv2_spec i i0 i1 i2 i3 i4 d = Some (d', z) ->\n            kernel_mode d.\n        Proof.\n          intros. simpl; functional inversion H; eauto.\n          - functional inversion H2; eauto.\n          - functional inversion H2; eauto.\n          - functional inversion H1; eauto.\n        Qed.\n\n        Lemma ptResv2_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem ptResv2_spec) ptResv2_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit ptResv2_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit ptResv2_spec_kernel_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        Lemma pmap_init_spec_kernel_mode:\n          forall d d' i,\n            pmap_init_spec i d = Some d' ->\n            kernel_mode d.\n        Proof.\n          intros. simpl; functional inversion H; eauto.\n        Qed.\n\n        Lemma pmap_init_spec_ref:\n          compatsim (crel HDATA LDATA) (gensem pmap_init_spec) pmap_init_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit pmap_init_exist; eauto 1.\n          intros (labd' & HP & HM).\n          exploit pmap_init_spec_kernel_mode; eauto. intros.\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        (*Lemma pt_free_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem pt_free_spec) pt_free_spec_low.\n      Proof. \n        compatsim_simpl (@match_AbData).\n        exploit pt_free_exist; eauto 1.\n        intros [labd' [HP [HM Hkern]]].\n        refine_split; try econstructor; eauto. constructor.\n      Qed.*)\n\n      End FRESH_PRIM.\n            \n      Section PASSTHROUGH_PRIM.\n\n        Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n        Proof.\n          accessor_prop_tac.\n          - eapply flatmem_store_exists; eauto.\n        Qed.          \n\n        Lemma passthrough_correct:\n          sim (crel HDATA LDATA) mptnew_passthrough mptinit.\n        Proof.\n          sim_oplus.\n          - apply fload_sim.\n          - apply fstore_sim.\n          - apply flatmem_copy_sim.\n          - apply vmxinfo_get_sim.\n          - apply device_output_sim.\n          - apply pfree_sim.\n          - apply setPT_sim. \n          - apply ptRead_sim.\n          - apply ptReadPDE_sim.\n          - apply ptFreePDE0_sim.\n          - apply ptRmv0_sim.\n          - apply ptin_sim.\n          - apply ptout_sim.\n          - apply clearCR2_sim.\n          - apply container_get_nchildren_sim.\n          - apply container_get_quota_sim.\n          - apply container_get_usage_sim.\n          - apply container_can_consume_sim.\n          - apply alloc_sim.\n          - apply trapin_sim.\n          - apply trapout_sim.\n          - apply hostin_sim.\n          - apply hostout_sim.\n          - apply trap_info_get_sim.\n          - apply trap_info_ret_sim.\n          - layer_sim_simpl.\n            + eapply load_correct2.\n            + eapply store_correct2.\n        Qed.\n\n      End PASSTHROUGH_PRIM.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTNewGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.25982562649804053, "lm_q1q2_score": 0.16363158192140922}}
{"text": "Require Import ExtLib.Data.Sum.\nRequire Import ExtLib.Tactics.\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  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 {ExprUVar_expr : ExprUVar expr}.\n\n  Definition IDTACK : rtacK typ expr :=\n    fun ctx sub gl => More_ sub gl.\n\n  (** TODO: Move this **)\n  Lemma rtacK_spec_More_\n    : forall (ctx : Ctx typ expr) (s : ctx_subst ctx) g,\n      rtacK_spec s g (More_ s g).\n  Proof.\n    red. intros. split; auto. split; auto.\n    forward.\n    split.\n    - reflexivity.\n    - intros. eapply Pure_pctxD; eauto.\n  Qed.\n\n  Theorem IDTACK_sound : rtacK_sound IDTACK.\n  Proof.\n    unfold IDTACK, rtacK_sound.\n    intros; subst.\n    eapply rtacK_spec_More_.\n  Qed.\n\nEnd parameterized.\n\nTypeclasses Opaque IDTACK.\nHint Opaque IDTACK : typeclass_instances.\n\nArguments IDTACK {typ expr} _ _ _ : rename.\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/IdtacK.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.16338422483136572}}
{"text": "(** Refinement rules for disjoint rules *)\nRequire Import Coq.Lists.List.\nRequire Import Fiat.Parsers.Refinement.PreTactics.\nRequire Import Fiat.Computation.Refinements.General.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.StringLike.LastCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.LastChar.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.Refinement.DisjointLemmas.\nRequire Import Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.Refinement.PossibleTerminalsSets.\n\nSet Implicit Arguments.\n\nLocal Arguments minus !_ !_.\n\nDefinition rev_search_for_condition\n           {HSLM : StringLikeMin Ascii.ascii}\n           {HSL : StringLike Ascii.ascii}\n           (G : pregrammar' Ascii.ascii)\n           {pdata : possible_data G}\n           str nt (n : nat)\n  := is_after_last_char_such_that\n       str\n       n\n       (fun ch => char_in ch (possible_last_terminals_of G nt)).\n\nGlobal Arguments rev_search_for_condition {_ _} G {_} _ _ _.\n\nLemma refine_disjoint_rev_search_for'\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      (G : pregrammar' Ascii.ascii)\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its}\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its) splits}\n         (n <- { n : nat | n <= length (substring offset len str)\n                           /\\ ((exists n', rev_search_for_condition G (substring offset len str) nt n')\n                               -> rev_search_for_condition G (substring offset len str) nt n) };\n          ret [n]).\nProof.\n  intros ls H.\n  computes_to_inv; subst.\n  destruct H as [H0 H1].\n  apply PickComputes.\n  hnf; cbv zeta.\n  intros Hlen it' its' Heq n ? H_reachable pit pits.\n  inversion Heq; subst it' its'; clear Heq.\n  left.\n  pose proof (terminals_disjoint_rev_search_for _ H_disjoint pit pits) as H'.\n  specialize (H1 (ex_intro _ n H')).\n  unfold rev_search_for_condition in H1.\n  pose proof (is_after_last_char_such_that_eq_nat_iff H1 H') as H''.\n  destruct_head or; destruct_head and; subst;\n  rewrite ?Min.min_r, ?Min.min_l by assumption;\n  omega.\nQed.\n\nDefinition rev_search_for_not_condition\n           {HSLM : StringLikeMin Ascii.ascii}\n           {HSL : StringLike Ascii.ascii}\n           (G : pregrammar' Ascii.ascii)\n           {apdata : all_possible_data G}\n           {pdata : possible_data G}\n           str its n\n  := is_after_last_char_such_that\n       str\n       n\n       (fun ch => negb (char_in ch (possible_terminals_of_production G its))).\n\nGlobal Arguments rev_search_for_not_condition {_ _} G {_ _} _ _ _.\n\nLemma refine_disjoint_rev_search_for_not'\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {G : pregrammar' Ascii.ascii}\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its}\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (n <- { n : nat | n <= length (substring offset len str)\n                           /\\ ((exists n', rev_search_for_not_condition G (substring offset len str) its n')\n                               -> rev_search_for_not_condition G (substring offset len str) its n) };\n          ret [n]).\nProof.\n  intros ls H.\n  computes_to_inv; subst.\n  destruct H as [H0 H1].\n  apply PickComputes.\n  hnf; cbv zeta.\n  intros Hlen it' its' Heq n ? H_reachable pit pits.\n  inversion Heq; subst it' its'; clear Heq.\n  left.\n  pose proof (terminals_disjoint_rev_search_for_not _ H_disjoint pit pits) as H'.\n  specialize (H1 (ex_intro _ n H')).\n  pose proof (is_after_last_char_such_that_eq_nat_iff H1 H') as H''.\n  destruct_head or; destruct_head and; subst;\n  rewrite ?Min.min_r by assumption;\n  omega.\nQed.\n\nLemma find_after_last_char_such_that'_short {Char HSLM HSL}\n      str P len\n: @find_after_last_char_such_that' Char HSLM HSL P len str <= len.\nProof.\n  revert str; induction len; simpl; intros; [ omega | ].\n  destruct (get len str) eqn:H.\n  { edestruct P; try omega.\n    rewrite IHlen; omega. }\n  { rewrite IHlen; omega. }\nQed.\n\nLemma find_after_last_char_such_that_short {Char HSLM HSL}\n      str P\n: @find_after_last_char_such_that Char HSLM HSL str P <= length str.\nProof.\n  apply find_after_last_char_such_that'_short.\nQed.\n\nLemma refine_find_after_last_char_such_that {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n      (str : String)\n      (P : Char -> bool)\n: refine { n : nat | n <= length str\n                     /\\ ((exists n', is_after_last_char_such_that str n' P)\n                         -> is_after_last_char_such_that str n P) }\n         (ret (find_after_last_char_such_that str P)).\nProof.\n  intros v H.\n  computes_to_inv; subst.\n  apply PickComputes.\n  split; [ apply find_after_last_char_such_that_short | ].\n  apply is_after_last_char_such_that__find_after_last_char_such_that.\nQed.\n\nLemma refine_disjoint_rev_search_for\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {G : pregrammar' Ascii.ascii}\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its}\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (ret [find_after_last_char_such_that (substring offset len str) (fun ch => char_in ch (possible_last_terminals_of G nt))]).\nProof.\n  rewrite refine_disjoint_rev_search_for' by eassumption.\n  setoid_rewrite refine_find_after_last_char_such_that.\n  simplify with monad laws; reflexivity.\nQed.\n\nLemma refine_disjoint_rev_search_for_not\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {G : pregrammar' Ascii.ascii}\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its}\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (ret [find_after_last_char_such_that (substring offset len str) (fun ch => negb (char_in ch (possible_terminals_of_production G its)))]).\nProof.\n  rewrite refine_disjoint_rev_search_for_not' by assumption.\n  setoid_rewrite refine_find_after_last_char_such_that.\n  simplify with monad laws; reflexivity.\nQed.\n\nLemma refine_disjoint_rev_search_for_idx\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {G : pregrammar' Ascii.ascii}\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its idx}\n      (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete_idx\n             G str offset len\n             idx\n             splits}\n         (ret [find_after_last_char_such_that (substring offset len str) (fun ch => char_in ch (possible_last_terminals_of G nt))]).\nProof.\n  unfold split_list_is_complete_idx.\n  erewrite <- refine_disjoint_rev_search_for by eassumption.\n  rewrite Heq.\n  apply refine_pick_pick; intro; trivial.\nQed.\n\nLemma refine_disjoint_rev_search_for_not_idx\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {G : pregrammar' Ascii.ascii}\n      {apdata : all_possible_data G}\n      {pdata : possible_data G}\n      {str offset len nt its idx}\n      (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n      (H_disjoint : disjoint\n                      (possible_last_terminals_of G nt)\n                      (possible_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete_idx\n             G str offset len\n             idx\n             splits}\n         (ret [find_after_last_char_such_that (substring offset len str) (fun ch => negb (char_in ch (possible_terminals_of_production G its)))]).\nProof.\n  unfold split_list_is_complete_idx.\n  erewrite <- refine_disjoint_rev_search_for_not by eassumption.\n  rewrite Heq.\n  apply refine_pick_pick; intro; trivial.\nQed.\n\nLtac solve_disjoint_side_conditions :=\n  idtac;\n  lazymatch goal with\n  | [ |- Carriers.default_to_production (G := ?G) ?k = ?e ]\n    => try cbv delta [G];\n       cbv beta iota zeta delta [Carriers.default_to_production Lookup_idx fst snd List.map pregrammar_productions List.length List.nth minus Operations.List.drop];\n       try reflexivity\n  | [ |- is_true (DisjointLemmas.disjoint _ _) ]\n    => vm_compute; try reflexivity\n  end.\n\nLtac pose_disjoint_rev_search_for lem :=\n  idtac;\n  let G := match goal with |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] => G end in\n  let HSLM := match goal with |- appcontext[@ParserInterface.split_list_is_complete_idx ?Char ?G ?HSLM ?HSL] => HSLM end in\n  let HSL := match goal with |- appcontext[@ParserInterface.split_list_is_complete_idx ?Char ?G ?HSLM ?HSL] => HSL end in\n  let lem' := constr:(@refine_disjoint_rev_search_for_idx HSLM HSL _ _ _ G) in\n  let lem' := constr:(lem' _ _) in\n  let lem' := match goal with\n              | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n                => constr:(fun idx' nt its => lem' str offset len nt its idx')\n              end in\n  pose proof lem' as lem.\nLtac rewrite_once_disjoint_rev_search_for_specialize lem lem' :=\n  idtac;\n  let G := (lazymatch goal with\n             | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n               => G\n             end) in\n  match goal with\n  | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n    => pose proof (lem idx) as lem';\n       do 2 (lazymatch type of lem' with\n              | forall a : ?T, _ => idtac; let x := fresh in evar (x : T); specialize (lem' x); subst x\n              end);\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve_disjoint_side_conditions;\n       specialize (lem' H'); clear H';\n       let x := match type of lem' with\n                | context[possible_last_terminals_of ?G ?ls]\n                  => constr:(possible_last_terminals_of G ls)\n                end in\n       replace_with_vm_compute_in x lem';\n       unfold char_in, char_in_characters, possible_characters in lem';\n       change (orb false) with (fun bv : bool => bv) in lem';\n       cbv beta in lem';\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve_disjoint_side_conditions;\n       specialize (lem' H'); clear H'\n  end.\nLtac rewrite_once_disjoint_rev_search_for lem :=\n  let lem' := fresh \"lem'\" in\n  rewrite_once_disjoint_rev_search_for_specialize lem lem';\n  setoid_rewrite lem'; clear lem'.\nLtac rewrite_disjoint_rev_search_for_no_clear lem :=\n  pose_disjoint_rev_search_for lem;\n  progress repeat rewrite_once_disjoint_rev_search_for lem.\nLtac rewrite_disjoint_rev_search_for :=\n  idtac;\n  let lem := fresh \"lem\" in\n  rewrite_disjoint_rev_search_for_no_clear lem;\n  clear lem.\n\nGlobal Arguments possible_data {_}.\nGlobal Arguments all_possible_data {_}.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/Refinement/DisjointRulesRev.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.16315595563112467}}
{"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\nRequire bedrock2Examples.lightbulb_spec.\nLocal Notation patience := lightbulb_spec.patience.\n\nDefinition spi_write := func! (b) ~> busy {\n    busy = $-1;\n    i = $patience; while i { i = i - $1;\n      io! busy = MMIOREAD($0x10024048);\n      if !(busy >> $31) { i = i^i }\n    };\n    if !(busy >> $31) {\n      output! MMIOWRITE($0x10024048, b);\n      busy = (busy ^ busy)\n    }\n  }.\n\nDefinition spi_read := func! () ~> (b, busy) {\n    busy = $-1;\n    b = $0x5a;\n    i = $patience; while i { i = i - $1;\n      io! busy = MMIOREAD($0x1002404c);\n      if !(busy >> $31) {\n        b = busy & $0xff;\n        i = i^i;\n        busy = i\n      }\n    }\n  }.\n\nDefinition spi_xchg := func! (b) ~> (b, busy) {\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.\n    letexists. split.\n    { repeat straightline. }\n    split; 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      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.\n    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    { 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        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_words. 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": "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/SPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.16291686946745706}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.Core\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.WordFacts\n        Fiat.Narcissus.Common.ComposeCheckSum\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.SolverOpt\n        Fiat.Narcissus.Formats.Bool\n        Fiat.Narcissus.Formats.Option\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Stores.EmptyStore\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.Vector\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.IPChecksum\n        Fiat.Narcissus.Formats.WordOpt.\n\nRequire Import Bedrock.Word.\n\nImport Vectors.VectorDef.VectorNotations.\nOpen Scope string_scope.\nOpen Scope Tuple_scope.\n\n(* Start Example Derivation. *)\n\nDefinition ICMP_Unreachable :=\n  @Tuple <\"Payload\" :: list char >. (* IP Header + first 64 bits of original datagram. *)\n\nDefinition ICMP_TimeExceeded :=\n  @Tuple <\"Payload\" :: list char >. (* IP Header + first 64 bits of original datagram. *)\n\nDefinition ICMP_ParameterProblem :=\n  @Tuple <\"Pointer\" :: char,\n          \"Payload\" :: list char >. (* IP Header + first 64 bits of original datagram. *)\n\nDefinition ICMP_SourceQuench :=\n  @Tuple <\"Payload\" :: list char >. (* IP Header + first 64 bits of original datagram. *)\n\nDefinition ICMP_Redirect :=\n  @Tuple <\"RouterIP\" :: word 32, (* IP Address of the router to use *)\n          \"Payload\" :: list char >. (* IP Header + first 64 bits of original datagram. *)\n\nDefinition ICMP_Echo :=\n  @Tuple <\"ID\" :: word 16, (* Identifier for sender *)\n          \"SeqNum\" :: word 16, (* Identifier for request *)\n          \"Payload\" :: list char>. (* Optional data to be echoed. *)\n\nDefinition ICMP_Timestamp :=\n  @Tuple <\"ID\" :: word 16, (* Identifier for sender *)\n          \"SeqNum\" :: word 16, (* Identifier for request *)\n          \"Originate\" :: word 32, (* Time request sent *)\n          \"Received\" :: word 32, (*  Time request received *)\n          \"Transmit\" :: word 32>. (*  Time reply sent *)\n\nDefinition ICMP_AddressMask :=\n  @Tuple <\"ID\" :: word 16, (* Identifier for sender *)\n          \"SeqNum\" :: word 16, (* Identifier for request *)\n          \"SubnetMask\" :: word 32>. (* The subnet mask of interest. *)\n\nDefinition ICMP_RouterAdvertisement :=\n  @Tuple <\"TTL\" :: word 16, (* Time to Live for the provided router information. *)\n          \"RoutersPlusPreferences\" :: list (word 32 * word 32)>. (* Pairs of a router's IP address *)\n                                                                 (* and its preference level. *)\n\nDefinition ICMP_Message_Types :=\n    [ ICMP_Echo; (* Echo Reply *)\n      ICMP_Unreachable; (* Destiniation unreachable *)\n      ICMP_SourceQuench; (* Source Quence *)\n      ICMP_Redirect; (* Redirect *)\n      ICMP_Echo; (* Echo Request *)\n      ICMP_RouterAdvertisement; (* Router Advertisement *)\n      (unit : Type) ; (* Router Solicitation *)\n      ICMP_TimeExceeded; (* Time Exceeded *)\n      ICMP_ParameterProblem; (* Parameter Problem *)\n      ICMP_Timestamp; (* Timestamp Request *)\n      ICMP_Timestamp; (* Timestamp Reply *)\n      ICMP_AddressMask; (* Address Mask Request *)\n      ICMP_AddressMask]. (* Address Mask Reply *)\n\nDefinition ICMP_Message_Codes :=\n  Eval simpl in\n    [natToWord 8 0;\n     natToWord 8 3;\n     natToWord 8 4;\n     natToWord 8 5;\n     natToWord 8 8;\n     natToWord 8 9;\n     natToWord 8 10;\n     natToWord 8 11;\n     natToWord 8 12;\n     natToWord 8 13;\n     natToWord 8 14;\n     natToWord 8 17;\n     natToWord 8 18].\n\nDefinition ICMP_Message :=\n  @Tuple <\"Code\" :: char, \"Message\" :: SumType ICMP_Message_Types>.\n\nDefinition monoid : Monoid ByteString := ByteStringMonoid.\n\nDefinition format_ICMP_Echo_Spec\n           (icmp : ICMP_Echo) :=\n        format_word icmp!\"ID\"\n  ThenC format_word icmp!\"SeqNum\"\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_Unreachable_Spec\n           (icmp : ICMP_Unreachable) :=\n        format_word (wzero 32)\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_SourceQuench_Spec\n           (icmp : ICMP_SourceQuench) :=\n        format_word (wzero 32)\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_Redirect_Spec\n           (icmp : ICMP_Redirect) :=\n        format_word icmp!\"RouterIP\"\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_RouterAdvertisement_Spec\n           (icmp : ICMP_RouterAdvertisement) :=\n        format_nat 8 (|icmp!\"RoutersPlusPreferences\"|)\n  ThenC format_nat 8 2\n  ThenC format_word icmp!\"TTL\"\n  ThenC format_list (fun p => format_word (fst p) ThenC format_word (snd p)) icmp!\"RoutersPlusPreferences\"\n  DoneC.\n\nDefinition format_ICMP_RouterSolicitation_Spec\n           (icmp : unit) :=\n  format_word (wzero 32)\n  DoneC.\n\nDefinition format_ICMP_TimeExceeded_Spec\n           (icmp : ICMP_TimeExceeded) :=\n        format_word (wzero 32)\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_ParameterProblem_Spec\n           (icmp : ICMP_ParameterProblem) :=\n        format_word icmp!\"Pointer\"\n  ThenC format_word (wzero 24)\n  ThenC format_list format_word icmp!\"Payload\"\n  DoneC.\n\nDefinition format_ICMP_Timestamp_Spec\n           (icmp : ICMP_Timestamp) :=\n        format_word icmp!\"ID\"\n  ThenC format_word icmp!\"SeqNum\"\n  ThenC format_word icmp!\"Originate\"\n  ThenC format_word icmp!\"Received\"\n  ThenC format_word icmp!\"Transmit\"\n  DoneC.\n\nDefinition format_ICMP_AddressMask_Spec\n           (icmp : ICMP_AddressMask) :=\n        format_word icmp!\"ID\"\n  ThenC format_word icmp!\"SeqNum\"\n  ThenC format_word icmp!\"SubnetMask\".\n\nDefinition format_ICMP_Message_Spec\n           (icmp : ICMP_Message) :=\n          format_enum ICMP_Message_Codes (SumType_index ICMP_Message_Types icmp!\"Message\")\n    ThenC format_word (icmp!\"Code\")\n    ThenChecksum IPChecksum_Valid OfSize 16\n    ThenCarryOn\n    format_SumType ICMP_Message_Types\n                        (icons format_ICMP_Echo_Spec\n                        (icons format_ICMP_Unreachable_Spec\n                        (icons format_ICMP_SourceQuench_Spec\n                        (icons format_ICMP_Redirect_Spec\n                        (icons format_ICMP_Echo_Spec\n                        (icons format_ICMP_RouterAdvertisement_Spec\n                        (icons format_ICMP_RouterSolicitation_Spec\n                        (icons format_ICMP_TimeExceeded_Spec\n                        (icons format_ICMP_ParameterProblem_Spec\n                        (icons format_ICMP_Timestamp_Spec\n                        (icons format_ICMP_Timestamp_Spec\n                        (icons format_ICMP_AddressMask_Spec\n                        (icons format_ICMP_AddressMask_Spec inil)))))))))))))\n    icmp!\"Message\".\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/ICMP_Packet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.1629168661698401}}
{"text": "Require Import PeanoNat Lia List ListSupport.\nRequire Import Common FMap.\nRequire Import Syntax Semantics SemFacts StepM Invariant Serial.\nRequire Import Reduction Commutativity QuasiSeq Topology.\nRequire Import RqRsTopo RqRsFacts RqRsInvMsg.\n\nSet Implicit Arguments.\n\nOpen Scope list.\nOpen Scope fmap.\n\nSection UpLockInv.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n  Variables (dtr: DTree)\n            (sys: System).\n\n  Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n             (Hrr: GoodRqRsSys dtr sys)\n             (Hsd: RqRsDTree dtr sys).\n\n  Section OnState.\n    Variables (orqs: ORqs Msg)\n              (msgs: MessagePool Msg).\n\n    Definition OLockedTo (oidx: IdxT) (rsbTo: option IdxT) :=\n      orqs@[oidx] >>=[False]\n          (fun orq =>\n             exists rqi,\n               (orq@[upRq] = Some rqi \\/ orq@[downRq] = Some rqi) /\\\n               rqi.(rqi_midx_rsb) = rsbTo).\n\n    Definition ONoSameLockTo (oidx: IdxT) (rsbTo: option IdxT) :=\n      orqs@[oidx] >>=[True]\n          (fun orq =>\n             match orq@[upRq], orq@[downRq] with\n             | Some rqiu, Some rqid =>\n               rqiu.(rqi_midx_rsb) <> rsbTo \\/\n               rqid.(rqi_midx_rsb) <> rsbTo\n             | _, _ => True\n             end).\n\n    Definition OUpLockFree (oidx: IdxT) :=\n      orqs@[oidx] >>=[True] (fun orq => UpLockFreeORq orq).\n\n    Definition ONoLockTo (oidx: IdxT) (rsbTo: option IdxT) :=\n      orqs@[oidx] >>=[True]\n          (fun orq =>\n             match orq@[upRq] with\n             | Some rqi => rqi.(rqi_midx_rsb) <> rsbTo\n             | None => True\n             end /\\\n             match orq@[downRq] with\n             | Some rqi => rqi.(rqi_midx_rsb) <> rsbTo\n             | None => True\n             end).\n\n    Definition UpLockFreeInv (oidx: IdxT) :=\n      parentIdxOf dtr oidx = None \\/\n      exists rqUp down pidx,\n        rqEdgeUpFrom dtr oidx = Some rqUp /\\\n        edgeDownTo dtr oidx = Some down /\\\n        parentIdxOf dtr oidx = Some pidx /\\\n        findQ rqUp msgs = nil /\\\n        rssQ msgs down = nil /\\\n        ONoLockTo pidx (Some down).\n\n    Definition UpLockedInv (oidx: IdxT) :=\n      exists rqUp down pidx,\n        rqEdgeUpFrom dtr oidx = Some rqUp /\\\n        edgeDownTo dtr oidx = Some down /\\\n        parentIdxOf dtr oidx = Some pidx /\\\n        length (findQ rqUp msgs) <= 1 /\\\n        length (rssQ msgs down) <= 1 /\\\n        ONoSameLockTo pidx (Some down) /\\\n        xor3 (length (findQ rqUp msgs) = 1)\n             (length (rssQ msgs down) = 1)\n             (OLockedTo pidx (Some down)).\n\n    Definition UpLockRsFromParent (oidx: IdxT) (rqiu: RqInfo Msg) :=\n      exists rsFrom,\n        edgeDownTo dtr oidx = Some (fst rsFrom) /\\\n        rqiu.(rqi_rss) = [rsFrom].\n\n    Definition UpLockInvORq (oidx: IdxT) (orq: ORq Msg) :=\n      match orq@[upRq] with\n      | Some rqiu =>\n        UpLockRsFromParent oidx rqiu /\\ UpLockedInv oidx\n      | None => UpLockFreeInv oidx\n      end.\n\n    Definition UpLockInvMO :=\n      forall oidx,\n        In oidx (map obj_idx sys.(sys_objs)) ->\n        let orq := orqs@[oidx] >>=[[]] (fun orq => orq) in\n        UpLockInvORq oidx orq.\n\n  End OnState.\n\n  Definition UpLockInv (st: State) :=\n    UpLockInvMO st.(st_orqs) st.(st_msgs).\n\n  Lemma upLockInv_init:\n    InvInit sys UpLockInv.\n  Proof.\n    intros; do 3 red; cbn.\n    intros; cbn.\n    red; repeat (mred; simpl).\n    assert ((sys_orqs_inits sys)@[oidx] >>=[[]](fun orq => orq) = []).\n    { specialize (Hiorqs oidx); simpl in Hiorqs.\n      destruct ((sys_orqs_inits sys)@[oidx]) as [orq|]; simpl in *; auto.\n    }\n    rewrite H0; mred.\n    destruct (parentIdxOf dtr oidx) as [pidx|] eqn:Hpidx; [right|left; auto].\n    pose proof Hpidx.\n    eapply parentIdxOf_Some in H1; [|apply Hsd].\n    destruct H1 as [rqUp [rsUp [down ?]]]; dest.\n    do 3 eexists; repeat split; try eassumption.\n    red.\n    specialize (Hiorqs pidx); simpl in Hiorqs.\n    destruct ((sys_orqs_inits sys)@[pidx]) as [porq|]; simpl in *; auto.\n    subst; mred.\n  Qed.\n\n  Lemma ONoLockTo_not_OLockedTo:\n    forall orqs oidx rsbTo,\n      ONoLockTo orqs oidx rsbTo -> ~ OLockedTo orqs oidx rsbTo.\n  Proof.\n    unfold ONoLockTo, OLockedTo; intros.\n    intro Hx.\n    destruct (orqs@[oidx]); simpl in *; auto; dest.\n    destruct H1.\n    - rewrite H1 in H; auto.\n    - rewrite H1 in H0; auto.\n  Qed.\n\n  Lemma not_ONoLockTo_OLockedTo:\n    forall orqs oidx rsbTo,\n      ~ OLockedTo orqs oidx rsbTo -> ONoLockTo orqs oidx rsbTo.\n  Proof.\n    unfold ONoLockTo, OLockedTo; intros.\n    destruct (orqs@[oidx]); simpl in *; auto.\n    split.\n    - destruct (o@[upRq]); auto.\n      intro Hx; elim H.\n      eexists; split; eauto.\n    - destruct (o@[downRq]); auto.\n      intro Hx; elim H.\n      eexists; split; eauto.\n  Qed.\n\n  Lemma ONoLockTo_ONoSameLockTo:\n    forall orqs oidx rsbTo,\n      ONoLockTo orqs oidx rsbTo -> ONoSameLockTo orqs oidx rsbTo.\n  Proof.\n    unfold ONoLockTo, ONoSameLockTo; intros.\n    destruct (orqs@[oidx]) as [orq|]; simpl in *; auto.\n    destruct (orq@[upRq]) as [rqiu|]; simpl in *; auto.\n    dest.\n    destruct (orq@[downRq]) as [rqid|]; simpl in *; auto.\n  Qed.\n\n  Lemma OLockedTo_orqs_preserved:\n    forall orqs1 orqs2 oidx rsbTo,\n      OLockedTo orqs1 oidx rsbTo ->\n      orqs1@[oidx] = orqs2@[oidx] ->\n      OLockedTo orqs2 oidx rsbTo.\n  Proof.\n    unfold OLockedTo; intros.\n    rewrite <-H0; assumption.\n  Qed.\n\n  Lemma upLockedInv_msgs_preserved:\n    forall orqs msgs1 msgs2 oidx,\n      UpLockedInv orqs msgs1 oidx ->\n      (match rqEdgeUpFrom dtr oidx with\n       | Some rqUp => findQ rqUp msgs1 = findQ rqUp msgs2\n       | None => False\n       end) ->\n      (match edgeDownTo dtr oidx with\n       | Some down => rssQ msgs1 down = rssQ msgs2 down\n       | None => False\n       end) ->\n      UpLockedInv orqs msgs2 oidx.\n  Proof.\n    unfold UpLockedInv; simpl; intros.\n    destruct H as [rqUp [down [pidx ?]]]; dest.\n    rewrite H in H0.\n    rewrite H2 in H1.\n    exists rqUp, down, pidx.\n    rewrite <-H0, <-H1.\n    repeat split; try assumption.\n  Qed.\n\n  Lemma upLockFreeInv_msgs_preserved:\n    forall orqs msgs1 msgs2 oidx,\n      UpLockFreeInv orqs msgs1 oidx ->\n      (match rqEdgeUpFrom dtr oidx with\n       | Some rqUp => findQ rqUp msgs1 = findQ rqUp msgs2\n       | None => True\n       end) ->\n      (match edgeDownTo dtr oidx with\n       | Some down => rssQ msgs1 down = rssQ msgs2 down\n       | None => True\n       end) ->\n      UpLockFreeInv orqs msgs2 oidx.\n  Proof.\n    unfold UpLockFreeInv; simpl; intros.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx ?]]]; dest.\n    rewrite H in H0.\n    rewrite H2 in H1.\n    exists rqUp, down, pidx; repeat split;\n      try assumption; try congruence.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_parent_eq:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] = orqs2@[pidx] ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H3 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n    - red in H6; red; rewrite <-H1; assumption.\n    - unfold OLockedTo in *; rewrite <-H1; assumption.\n  Qed.\n\n  Corollary upLockedInv_orqs_preserved_self_update:\n    forall orqs msgs oidx orq,\n      UpLockedInv orqs msgs oidx ->\n      UpLockedInv (orqs+[oidx <- orq]) msgs oidx.\n  Proof.\n    intros.\n    destruct Hsd.\n    pose proof H.\n    destruct H2 as [rqUp [down [pidx ?]]]; dest.\n    eapply upLockedInv_orqs_preserved_parent_eq; eauto.\n    apply parentIdxOf_not_eq in H4; [|assumption].\n    mred.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_parent_some_up:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = Some rqiu ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H6 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n\n    - red in H9; red.\n      destruct (orqs1@[pidx]) as [orq1|];\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *;\n          try (exfalso; auto; fail); try discriminate.\n      + rewrite H2.\n        destruct (orq2@[downRq]) as [rqid2|]; auto.\n        rewrite H5 in H3.\n        left; intro Hx; subst; auto.\n      + rewrite H2, <-H4; auto.\n\n    - destruct H10.\n      + xfst; try assumption.\n        intro Hx; red in Hx.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12.\n        * rewrite H2 in H12; inv H12; congruence.\n        * elim H11; red.\n          destruct (orqs1@[pidx]) as [orq1|]; simpl in *; auto.\n          { eexists; split.\n            { right; rewrite H4; eassumption. }\n            { assumption. }\n          }\n          { congruence. }\n      + xsnd; try assumption.\n        intro Hx; red in Hx.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12.\n        * rewrite H2 in H12; inv H12; congruence.\n        * elim H11; red.\n          destruct (orqs1@[pidx]) as [orq1|]; simpl in *; auto.\n          { eexists; split.\n            { right; rewrite H4; eassumption. }\n            { assumption. }\n          }\n          { congruence. }\n      + xthd; try assumption.\n        red; red in H11.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *.\n        * destruct (orqs1@[pidx]) as [orq1|]; simpl in *.\n          { destruct H11 as [rqi ?]; dest.\n            destruct H11.\n            { congruence. }\n            { eexists; split.\n              { right; rewrite <-H4; eassumption. }\n              { assumption. }\n            }\n          }\n          { elim H11. }\n        * discriminate.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_parent_some_down:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = Some rqiu ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H6 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n    - red in H9; red.\n      destruct (orqs1@[pidx]) as [orq1|];\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *;\n          try (exfalso; auto; fail); try discriminate.\n      + rewrite <-H4.\n        destruct (orq1@[upRq]) as [rqiu1|]; auto.\n        rewrite H2.\n        right; congruence.\n      + rewrite H2, <-H4; auto.\n\n    - destruct H10.\n      + xfst; try assumption.\n        intro Hx; red in Hx.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12.\n        * elim H11; red.\n          destruct (orqs1@[pidx]) as [orq1|]; simpl in *; auto.\n          { eexists; split.\n            { left; rewrite H4; eassumption. }\n            { assumption. }\n          }\n          { congruence. }\n        * rewrite H2 in H12; inv H12; congruence.\n      + xsnd; try assumption.\n        intro Hx; red in Hx.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12.\n        * elim H11; red.\n          destruct (orqs1@[pidx]) as [orq1|]; simpl in *; auto.\n          { eexists; split.\n            { left; rewrite H4; eassumption. }\n            { assumption. }\n          }\n          { congruence. }\n        * rewrite H2 in H12; inv H12; congruence.\n      + xthd; try assumption.\n        red; red in H11.\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n        * destruct (orqs1@[pidx]) as [orq1|]; simpl in *.\n          { destruct H11 as [rqi ?]; dest.\n            destruct H11.\n            { eexists; split.\n              { left; rewrite <-H4; eassumption. }\n              { assumption. }\n            }\n            { congruence. }\n          }\n          { elim H11. }\n        * discriminate.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_parent_none_up:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) = Some rqiu ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = None ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H6 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n    - red in H9; red.\n      destruct (orqs1@[pidx]) as [orq1|];\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *;\n          auto; try discriminate.\n      rewrite H2; auto.\n    - destruct H10.\n      + xfst; try assumption.\n        intro Hx; elim H11; clear H11.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct Hx as [rqi ?]; dest.\n          destruct H11; [congruence|].\n          exists rqi; split; auto.\n          right; congruence.\n        * exfalso; auto.\n      + xsnd; try assumption.\n        intro Hx; elim H11; clear H11.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct Hx as [rqi ?]; dest.\n          destruct H11; [congruence|].\n          exists rqi; split; auto.\n          right; congruence.\n        * exfalso; auto.\n      + xthd; try assumption.\n        red; red in H11.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct H11 as [rqi ?]; dest.\n          destruct H11; [congruence|].\n          eexists; split.\n          { right; rewrite <-H4; eassumption. }\n          { assumption. }\n        * destruct H11 as [rqi ?]; dest.\n          destruct H11; congruence.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_parent_none_down:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) = Some rqiu ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = None ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H6 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n    - red in H9; red.\n      destruct (orqs1@[pidx]) as [orq1|];\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *;\n          auto; try discriminate.\n      rewrite H2.\n      destruct (orq2@[upRq]); auto.\n    - destruct H10.\n      + xfst; try assumption.\n        intro Hx; elim H11; clear H11.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct Hx as [rqi ?]; dest.\n          destruct H11; [|congruence].\n          exists rqi; split; auto.\n          left; congruence.\n        * exfalso; auto.\n      + xsnd; try assumption.\n        intro Hx; elim H11; clear H11.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct Hx as [rqi ?]; dest.\n          destruct H11; [|congruence].\n          exists rqi; split; auto.\n          left; congruence.\n        * exfalso; auto.\n      + xthd; try assumption.\n        red; red in H11.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        * destruct H11 as [rqi ?]; dest.\n          destruct H11; [|congruence].\n          eexists; split.\n          { left; rewrite <-H4; eassumption. }\n          { assumption. }\n        * destruct H11 as [rqi ?]; dest.\n          destruct H11; congruence.\n  Qed.\n\n  Lemma upLockedInv_orqs_preserved_rs_rq:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu rqid,\n      UpLockedInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) = Some rqiu ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = None ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = Some rqid ->\n      rqiu.(rqi_midx_rsb) = rqid.(rqi_midx_rsb) ->\n      UpLockedInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockedInv; intros.\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H7 in H0; inv H0.\n    exists rqUp, down, pidx; repeat split; try assumption.\n    - red in H10; red.\n      destruct (orqs1@[pidx]) as [orq1|];\n        destruct (orqs2@[pidx]) as [orq2|]; simpl in *;\n          auto; try discriminate.\n      rewrite H2; auto.\n    - destruct H11.\n      + xfst; try assumption.\n        intro Hx; elim H12; clear H12.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12; [congruence|].\n        exists rqiu; split; auto.\n        congruence.\n      + xsnd; try assumption.\n        intro Hx; elim H12; clear H12.\n        red in Hx; red.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        destruct Hx as [rqi ?]; dest.\n        destruct H12; [congruence|].\n        exists rqiu; split; auto.\n        congruence.\n      + xthd; try assumption.\n        red; red in H12.\n        destruct (orqs1@[pidx]) as [orq1|];\n          destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto;\n            try discriminate.\n        destruct H12 as [rqi ?]; dest.\n        destruct H12; [|congruence].\n        eexists; split.\n        { right; eassumption. }\n        { congruence. }\n  Qed.\n\n  Corollary upLockedInv_orqs_preserved_non_parent_update:\n    forall orqs msgs oidx1 oidx2 orq,\n      UpLockedInv orqs msgs oidx1 ->\n      parentIdxOf dtr oidx1 <> Some oidx2 ->\n      UpLockedInv (orqs+[oidx2 <- orq]) msgs oidx1.\n  Proof.\n    intros.\n    destruct Hsd.\n    pose proof H.\n    destruct H3 as [rqUp [down [pidx ?]]]; dest.\n    eapply upLockedInv_orqs_preserved_parent_eq; eauto.\n    mred.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_parent_eq:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] = orqs2@[pidx] ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H3 in H0; inv H0.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    unfold ONoLockTo in *.\n    rewrite <-H1; assumption.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_self_update:\n    forall orqs msgs oidx orq,\n      UpLockFreeInv orqs msgs oidx ->\n      UpLockFreeInv (orqs+[oidx <- orq]) msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx ?]]]; dest.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red in H4; red.\n    apply parentIdxOf_not_eq in H1; [|destruct Hsd; assumption].\n    mred.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_parent_some_up:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = Some rqiu ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red.\n    destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n    split.\n    - rewrite H2.\n      intro Hx; subst; congruence.\n    - rewrite H6 in H0; inv H0.\n      red in H9.\n      destruct (orqs1@[pidx]) as [orq1|]; simpl in *; dest.\n      + rewrite <-H4; assumption.\n      + rewrite <-H4; auto.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_parent_some_down:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = Some rqiu ->\n      edgeDownTo dtr oidx <> rqiu.(rqi_midx_rsb) ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red.\n    destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n    split.\n    - rewrite H6 in H0; inv H0.\n      red in H9.\n      destruct (orqs1@[pidx]) as [orq1|]; simpl in *; dest.\n      + rewrite <-H4; assumption.\n      + rewrite <-H4; auto.\n    - rewrite H2.\n      intro Hx; subst; congruence.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_parent_none_up:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = None ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H4 in H0; inv H0.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red; red in H7; dest.\n    destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n    split.\n    - rewrite H1; auto.\n    - destruct (orqs1@[pidx]) as [orq1|]; simpl in *; dest.\n      + rewrite <-H2; assumption.\n      + rewrite <-H2; auto.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_parent_none_down:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = None ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) =\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H4 in H0; inv H0.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red; red in H7.\n    destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n    split.\n    - destruct (orqs1@[pidx]) as [orq1|]; simpl in *; dest.\n      + rewrite <-H2; assumption.\n      + rewrite <-H2; auto.\n    - rewrite H1; auto.\n  Qed.\n\n  Lemma upLockFreeInv_orqs_preserved_rs_rq:\n    forall (orqs1 orqs2: ORqs Msg) msgs oidx pidx rqiu rqid,\n      UpLockFreeInv orqs1 msgs oidx ->\n      parentIdxOf dtr oidx = Some pidx ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[upRq]) = Some rqiu ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[upRq]) = None ->\n      orqs1@[pidx] >>= (fun orq1 => orq1@[downRq]) = None ->\n      orqs2@[pidx] >>= (fun orq2 => orq2@[downRq]) = Some rqid ->\n      rqiu.(rqi_midx_rsb) = rqid.(rqi_midx_rsb) ->\n      UpLockFreeInv orqs2 msgs oidx.\n  Proof.\n    unfold UpLockFreeInv; intros; dest.\n    destruct H; [left; assumption|right].\n    destruct H as [rqUp [down [pidx' ?]]]; dest.\n    rewrite H7 in H0; inv H0.\n    exists rqUp, down, pidx.\n    repeat split; try assumption.\n    red; red in H10.\n    destruct (orqs2@[pidx]) as [orq2|]; simpl in *; auto.\n    split.\n    - rewrite H2; auto.\n    - rewrite H4.\n      destruct (orqs1@[pidx]) as [orq1|]; simpl in *; dest.\n      + rewrite H1 in H0; congruence.\n      + discriminate.\n  Qed.\n\n  Corollary upLockFreeInv_orqs_preserved_non_parent_update:\n    forall orqs msgs oidx1 oidx2 orq,\n      UpLockFreeInv orqs msgs oidx1 ->\n      parentIdxOf dtr oidx1 <> Some oidx2 ->\n      UpLockFreeInv (orqs+[oidx2 <- orq]) msgs oidx1.\n  Proof.\n    intros.\n    destruct Hsd.\n    pose proof H.\n    destruct H3; [left; assumption|].\n    destruct H3 as [rqUp [down [pidx ?]]]; dest.\n    eapply upLockFreeInv_orqs_preserved_parent_eq; eauto.\n    mred.\n  Qed.\n\n  Lemma upLockInv_step_ext_in:\n    forall oss orqs msgs eins,\n      UpLockInv {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      eins <> nil ->\n      ValidMsgsExtIn sys eins ->\n      UpLockInv {| st_oss := oss;\n                   st_orqs := orqs;\n                   st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    unfold UpLockInv; simpl; intros.\n    red; intros.\n    specialize (H oidx H2).\n\n    destruct H1.\n    assert (DisjList (idsOf eins) (sys_minds sys)).\n    { eapply DisjList_SubList; eauto.\n      apply DisjList_comm.\n      apply sys_minds_sys_merqs_DisjList.\n    }\n\n    destruct (orqs@[oidx]) as [orq|]; simpl in *; dest.\n    - red in H; red.\n      remember (orq@[upRq]) as orqi.\n      destruct orqi as [rqi|].\n      + dest; split; [assumption|].\n        eapply upLockedInv_msgs_preserved; eauto.\n        * destruct H5 as [rqUp [down [pidx ?]]]; dest.\n          rewrite H5.\n          rewrite findQ_not_In_enqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n        * destruct H5 as [rqUp [down [pidx ?]]]; dest.\n          rewrite H6.\n          unfold rssQ; rewrite findQ_not_In_enqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n      + eapply upLockFreeInv_msgs_preserved; eauto.\n        * destruct (rqEdgeUpFrom dtr oidx) as [rqUp|] eqn:HrqUp; auto.\n          rewrite findQ_not_In_enqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n        * destruct (edgeDownTo dtr oidx) as [down|] eqn:Hdown; auto.\n          unfold rssQ; rewrite findQ_not_In_enqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n    - red in H; simpl in H.\n      red in H3; simpl in H3.\n      red; simpl.\n\n      mred; eapply upLockFreeInv_msgs_preserved; eauto.\n      + destruct (rqEdgeUpFrom dtr oidx) as [rqUp|] eqn:HrqUp; auto.\n        rewrite findQ_not_In_enqMsgs; [reflexivity|].\n        eapply DisjList_In_1; [eassumption|].\n        eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n      + destruct (edgeDownTo dtr oidx) as [down|] eqn:Hdown; auto.\n        unfold rssQ; rewrite findQ_not_In_enqMsgs; [reflexivity|].\n        eapply DisjList_In_1; [eassumption|].\n        eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n  Qed.\n\n  Lemma upLockInv_step_ext_out:\n    forall oss orqs msgs eouts,\n      UpLockInv {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      eouts <> nil ->\n      Forall (FirstMPI msgs) eouts ->\n      ValidMsgsExtOut sys eouts ->\n      UpLockInv {| st_oss := oss;\n                   st_orqs := orqs;\n                   st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    unfold UpLockInv; simpl; intros.\n    red; intros.\n    specialize (H oidx H3).\n\n    destruct H2.\n    assert (DisjList (idsOf eouts) (sys_minds sys)).\n    { eapply DisjList_SubList; eauto.\n      apply DisjList_comm.\n      apply sys_minds_sys_merss_DisjList.\n    }\n\n    destruct (orqs@[oidx]) as [orq|]; simpl in *; dest.\n    - red in H; red.\n      remember (orq@[upRq]) as orqi.\n      destruct orqi as [rqi|].\n      + dest; split; [assumption|].\n        eapply upLockedInv_msgs_preserved; eauto.\n        * destruct H6 as [rqUp [down [pidx ?]]]; dest.\n          rewrite H6.\n          rewrite findQ_not_In_deqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n        * destruct H6 as [rqUp [down [pidx ?]]]; dest.\n          rewrite H7.\n          unfold rssQ; rewrite findQ_not_In_deqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n      + eapply upLockFreeInv_msgs_preserved; eauto.\n        * destruct (rqEdgeUpFrom dtr oidx) as [rqUp|] eqn:HrqUp; auto.\n          rewrite findQ_not_In_deqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n        * destruct (edgeDownTo dtr oidx) as [down|] eqn:Hdown; auto.\n          unfold rssQ; rewrite findQ_not_In_deqMsgs; [reflexivity|].\n          eapply DisjList_In_1; [eassumption|].\n          eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n    - red in H; simpl in H.\n      red in H4; simpl in H4.\n      red; simpl.\n\n      mred; eapply upLockFreeInv_msgs_preserved; eauto.\n      + destruct (rqEdgeUpFrom dtr oidx) as [rqUp|] eqn:HrqUp; auto.\n        rewrite findQ_not_In_deqMsgs; [reflexivity|].\n        eapply DisjList_In_1; [eassumption|].\n        eapply rqrsDTree_rqEdgeUpFrom_sys_minds; eauto.\n      + destruct (edgeDownTo dtr oidx) as [down|] eqn:Hdown; auto.\n        unfold rssQ; rewrite findQ_not_In_deqMsgs; [reflexivity|].\n        eapply DisjList_In_1; [eassumption|].\n        eapply rqrsDTree_edgeDownTo_sys_minds; eauto.\n  Qed.\n\n  Section InternalStep.\n    Variables (oss: OStates) (orqs: ORqs Msg) (msgs: MessagePool Msg)\n              (obj: Object) (rule: Rule)\n              (post: OState) (porq: ORq Msg) (mins: list (Id Msg))\n              (nost: OState) (norq: ORq Msg) (mouts: list (Id Msg)).\n\n    Hypotheses\n      (Hfpok: FootprintsOk\n                dtr sys {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |})\n      (HobjIn: In obj (sys_objs sys))\n      (HruleIn: In rule (obj_rules obj))\n      (Hporq: orqs@[obj_idx obj] = Some porq)\n      (Hpost: oss@[obj_idx obj] = Some post)\n      (HminsF: Forall (FirstMPI msgs) mins)\n      (HminsV: ValidMsgsIn sys mins)\n      (Hprec: rule_precond rule post porq mins)\n      (Htrs: rule_trs rule post porq mins = (nost, norq, mouts))\n      (HmoutsV: ValidMsgsOut sys mouts)\n      (Hmdisj: DisjList (idsOf mins) (idsOf mouts)).\n\n    Lemma deqMP_rq_filter_rs_eq:\n      forall midx msg,\n        msg_type msg = MRq ->\n        FirstMPI msgs (midx, msg) ->\n        filter (fun msg => msg_type msg)\n               (findQ midx msgs) =\n        filter (fun msg => msg_type msg)\n               (findQ midx (deqMP midx msgs)).\n    Proof.\n      intros.\n      unfold FirstMPI, FirstMP, firstMP in H0.\n      unfold deqMP, idOf in *; simpl in *.\n      destruct (findQ midx msgs); [discriminate|].\n      simpl in H0; inv H0.\n      unfold findQ; mred; simpl.\n      rewrite H; simpl.\n      reflexivity.\n    Qed.\n\n    Lemma deqMP_rs_filter_rq_eq:\n      forall midx msg,\n        msg_type msg = MRs ->\n        FirstMPI msgs (midx, msg) ->\n        filter (fun msg => negb (msg_type msg))\n               (findQ midx msgs) =\n        filter (fun msg => negb (msg_type msg))\n               (findQ midx (deqMP midx msgs)).\n    Proof.\n      intros.\n      unfold FirstMPI, FirstMP, firstMP in H0.\n      unfold deqMP, idOf in *; simpl in *.\n      destruct (findQ midx msgs); [discriminate|].\n      simpl in H0; inv H0.\n      unfold findQ; mred; simpl.\n      rewrite H; simpl.\n      reflexivity.\n    Qed.\n\n    Ltac disc_rule_custom ::=\n      try match goal with\n          | [H: UpLockedInv _ _ _ |- _] =>\n            let rqUp := fresh \"rqUp\" in\n            let down := fresh \"down\" in\n            let pidx := fresh \"pidx\" in\n            destruct H as [rqUp [down [pidx ?]]]; dest\n          end;\n      try disc_footprints_ok.\n\n    Lemma upLockInvORq_step_int_me:\n      UpLockInvORq orqs msgs (obj_idx obj) porq ->\n      In (obj_idx obj) (map obj_idx (sys_objs sys)) ->\n      GoodRqRsRule dtr sys (obj_idx obj) rule ->\n      UpLockInvORq (orqs+[obj_idx obj <- norq])\n                   (enqMsgs mouts (deqMsgs (idsOf mins) msgs))\n                   (obj_idx obj) norq.\n    Proof.\n      intros.\n      (* [RqRsChnsOnSystem] is not required here. *)\n      destruct Hsd as [? [? _]].\n      red in H; red.\n      good_rqrs_rule_cases rule.\n\n      - (** case [ImmDownRule] *)\n        disc_rule_conds.\n        + apply upLockFreeInv_orqs_preserved_self_update; assumption.\n        + apply upLockFreeInv_orqs_preserved_self_update.\n          eapply upLockFreeInv_msgs_preserved; eauto.\n          * remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n            destruct orqUp as [rqUp|]; auto.\n            solve_q.\n          * remember (edgeDownTo dtr (obj_idx obj)) as odown.\n            destruct odown as [down|]; auto.\n            solve_q.\n\n      - (** case [ImmUpRule] *)\n        disc_rule_conds.\n        destruct (norq@[upRq]).\n        + dest; split; [assumption|].\n          apply upLockedInv_orqs_preserved_self_update.\n          eapply upLockedInv_msgs_preserved; eauto.\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds; solve_q.\n            eapply deqMP_rq_filter_rs_eq; eauto.\n        + apply upLockFreeInv_orqs_preserved_self_update.\n          eapply upLockFreeInv_msgs_preserved; eauto.\n          * remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n            destruct orqUp as [rqUp|]; auto.\n            solve_q.\n          * disc_rule_conds; solve_q.\n            eapply deqMP_rq_filter_rs_eq; eauto.\n\n      - (** case [RqFwdRule] *)\n        disc_rule_conds.\n        + (** case [RqUpUp-silent]; setting an uplock. *)\n          split; [exists (rsFrom, None); auto|].\n          apply upLockedInv_orqs_preserved_self_update.\n          pose proof (rqEdgeUpFrom_Some (proj1 (proj2 Hsd)) _ H4).\n          destruct H6 as [rsUp [down [pidx ?]]]; dest.\n          red in H; disc_rule_conds.\n          destruct H; [discriminate|].\n          destruct H as [rqUp [down' [pidx' ?]]]; dest.\n          disc_rule_conds.\n          do 3 eexists; repeat split; try eassumption.\n          * solve_q.\n            rewrite H14; simpl; lia.\n          * solve_q.\n            unfold rssQ in H15; rewrite H15.\n            simpl; lia.\n          * apply ONoLockTo_ONoSameLockTo; assumption.\n          * xfst.\n            { solve_q.\n              rewrite H14; reflexivity.\n            }\n            { solve_q.\n              unfold rssQ in H15; rewrite H15; auto.\n            }\n            { apply ONoLockTo_not_OLockedTo; assumption. }\n        + (** case [RqUpUp]; setting an uplock. *)\n          split; [exists (rsFrom, None); auto|].\n          apply upLockedInv_orqs_preserved_self_update.\n          pose proof (rqEdgeUpFrom_Some (proj1 (proj2 Hsd)) _ H4).\n          destruct H10 as [rsUp [down [pidx ?]]]; dest.\n          red in H; disc_rule_conds.\n          destruct H; [discriminate|].\n          destruct H as [rqUp [down' [pidx' ?]]]; dest.\n          disc_rule_conds.\n          do 3 eexists; repeat split; try eassumption.\n          * solve_q.\n            rewrite H19; simpl; lia.\n          * solve_q.\n            unfold rssQ in H20; rewrite H20.\n            simpl; lia.\n          * apply ONoLockTo_ONoSameLockTo; assumption.\n          * xfst.\n            { solve_q.\n              rewrite H19; reflexivity.\n            }\n            { solve_q.\n              unfold rssQ in H20; rewrite H20; auto.\n            }\n            { apply ONoLockTo_not_OLockedTo; assumption. }\n\n        + (** case [RqUpDown-silent]; setting a downlock. *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n        + (** case [RqUpDown]; setting a downlock. *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n        + (** case [RqDownDown]; setting a downlock *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q.\n              eapply deqMP_rq_filter_rs_eq; eauto.\n            }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n                eapply deqMP_rq_filter_rs_eq; eauto.\n              }\n            }\n\n      - (** case [RsBackRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n        + (** case [FootprintReleasingUp]; releasing the uplock. *)\n          apply upLockFreeInv_orqs_preserved_self_update.\n          xor3_inv2 H17; [dest|eapply rssQ_length_one; eauto].\n          right; exists rqTo, rsFrom, pidx.\n          repeat split; try assumption.\n          * solve_q.\n            apply length_zero_iff_nil; lia.\n          * solve_q.\n            apply findQ_In_deqMP_FirstMP in H19; simpl in H19.\n            unfold rssQ in H15; rewrite <-H19 in H15.\n            simpl in H15; rewrite H20 in H15; simpl in H15.\n            apply length_zero_iff_nil; lia.\n          * apply not_ONoLockTo_OLockedTo; auto.\n        + (** case [FootprintReleasingUp-silent]; releasing the uplock. *)\n          apply upLockFreeInv_orqs_preserved_self_update.\n          xor3_inv2 H16; [dest|eapply rssQ_length_one; eauto].\n          right; exists rqTo, rsFrom, pidx.\n          repeat split; try assumption.\n          * solve_q.\n            apply length_zero_iff_nil; lia.\n          * solve_q.\n            apply findQ_In_deqMP_FirstMP in H17; simpl in H17.\n            unfold rssQ in H14; rewrite <-H17 in H14.\n            simpl in H14; rewrite H19 in H14; simpl in H14.\n            apply length_zero_iff_nil; lia.\n          * apply not_ONoLockTo_OLockedTo; auto.\n\n        + (** case [FootprintReleasingDown]-1 *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n        + (** case [FootprintReleasingDown]-2 *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n        + (** case [FootprintReleasingDown]-3 *)\n          remember (porq@[upRq]) as orqiu; destruct orqiu as [rqiu|].\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_self_update.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_self_update.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr (obj_idx obj)) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr (obj_idx obj)) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n      - (** case [RsDownRqDownRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n        apply upLockFreeInv_orqs_preserved_self_update.\n        xor3_inv2 H18; [dest|eapply rssQ_length_one; eauto].\n        red; right.\n        exists rqTo, rsFrom0, pidx; repeat split; try assumption.\n        + solve_q.\n          apply length_zero_iff_nil; lia.\n        + solve_q.\n          apply findQ_In_deqMP_FirstMP in H10; simpl in H10.\n          unfold rssQ in H14; rewrite <-H10 in H14.\n          simpl in H14; rewrite H7 in H14; simpl in H14.\n          apply length_zero_iff_nil; lia.\n        + apply not_ONoLockTo_OLockedTo; auto.\n    Qed.\n\n    Lemma upLockInvORq_step_int_parent:\n      forall oidx,\n        UpLockInvORq orqs msgs oidx ((orqs@[oidx]) >>=[[]] (fun orq => orq)) ->\n        In oidx (map obj_idx (sys_objs sys)) ->\n        GoodRqRsRule dtr sys (obj_idx obj) rule ->\n        parentIdxOf dtr oidx = Some (obj_idx obj) ->\n        UpLockInvORq (orqs+[obj_idx obj <- norq])\n                     (enqMsgs mouts (deqMsgs (idsOf mins) msgs)) oidx\n                     ((orqs@[ oidx]) >>=[[]] (fun orq => orq)).\n    Proof.\n      intros.\n      destruct Hsd as [? [? _]].\n      red in H; red.\n      good_rqrs_rule_cases rule.\n\n      - (** case [ImmDownRule] *)\n        disc_rule_conds;\n          [replace (orqs +[obj_idx obj <- norq]) with orqs by meq; assumption|].\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          eapply upLockedInv_orqs_preserved_parent_eq with (orqs1:= orqs).\n          * disc_rule_conds.\n            destruct (idx_dec cidx oidx); subst.\n            { exists rqUp, down, (obj_idx obj).\n              disc_rule_conds.\n              assert (length (rssQ (enqMP rsTo rsm (deqMP rqFrom msgs)) rsTo) = 1).\n              { solve_q.\n                rewrite filter_app; simpl.\n                rewrite H6; simpl.\n                rewrite app_length; simpl.\n                xor3_inv1 H15; dest.\n                { unfold rssQ in H2, H13; lia. }\n                { eapply findQ_length_one; eauto. }\n              }\n              rewrite H2; clear H2.\n\n              solve_q.\n              repeat split; try assumption.\n              { apply findQ_In_deqMP_FirstMP in H11; simpl in H11.\n                rewrite <-H11 in H9; simpl in H9.\n                lia.\n              }\n              { lia. }\n              { xsnd.\n                { apply findQ_In_deqMP_FirstMP in H11; simpl in H11.\n                  rewrite <-H11 in H9; simpl in H9.\n                  lia.\n                }\n                { reflexivity. }\n                { apply ONoLockTo_not_OLockedTo.\n                  red; disc_rule_conds; auto.\n                }\n              }\n            }\n            { eapply upLockedInv_msgs_preserved.\n              { red; eauto 10. }\n              { disc_rule_conds; solve_q. }\n              { disc_rule_conds; solve_q. }\n            }\n          * eassumption.\n          * disc_rule_conds.\n\n        + eapply upLockFreeInv_orqs_preserved_parent_eq with (orqs1:= orqs).\n          * disc_rule_conds.\n            destruct (idx_dec cidx oidx); subst.\n            { exfalso.\n              destruct H; [congruence|].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              apply FirstMP_InMP in H11.\n              red in H11; simpl in H11; rewrite H7 in H11.\n              elim H11.\n            }\n            { destruct H; [left; assumption|right].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              exists rqUp, down, pidx.\n              repeat split; try assumption.\n              { solve_q; assumption. }\n              { solve_q; assumption. }\n            }\n          * eassumption.\n          * disc_rule_conds.\n\n      - (** case [ImmUpRule] *)\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          disc_rule_conds.\n          eapply upLockedInv_orqs_preserved_parent_eq with (orqs1:= orqs);\n            [|eassumption|mred].\n          apply upLockedInv_msgs_preserved with (msgs1:= msgs).\n          * red; eauto 10.\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds; solve_q.\n        + disc_rule_conds.\n          eapply upLockFreeInv_orqs_preserved_parent_eq with (orqs1:= orqs);\n            [|eassumption|mred].\n          apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * destruct H.\n            { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n              destruct orqUp; auto.\n              eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n          * destruct H.\n            { remember (edgeDownTo dtr oidx) as odown.\n              destruct odown; auto.\n              eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n\n      - (** case [RqFwdRule] *)\n        disc_rule_conds.\n        + (** case [RqUpUp-silent] *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_some_up\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n            { eapply upLockedInv_msgs_preserved; [eassumption| |].\n              { destruct H7 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n              { destruct H7 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              eapply parentIdxOf_Some in H2; [|apply Hsd].\n              dest; congruence.\n            }\n          * apply upLockFreeInv_orqs_preserved_parent_some_up\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n              { destruct H.\n                { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                  destruct orqUp; auto.\n                  eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { destruct H.\n                { remember (edgeDownTo dtr oidx) as odown.\n                  destruct odown; auto.\n                  eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              eapply parentIdxOf_Some in H2; [|apply Hsd].\n              dest; congruence.\n            }\n\n        + (** case [RqUpUp] *)\n          destruct (idx_dec cidx oidx); subst.\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              disc_rule_conds.\n              exists rqFrom, rsbTo, (obj_idx obj).\n              xor3_inv1 H21; [dest|eapply findQ_length_one; eauto].\n              assert (length (findQ rqFrom (enqMP rqTo rqtm (deqMP rqFrom msgs))) = 0).\n              { solve_q.\n                apply findQ_In_deqMP_FirstMP in H14; simpl in H14.\n                rewrite <-H14 in H16; simpl in H16.\n                lia.\n              }\n              rewrite H9; clear H9.\n\n              assert (length (rssQ (enqMP rqTo rqtm (deqMP rqFrom msgs)) rsbTo) = 0).\n              { solve_q.\n                unfold rssQ in H2, H19; lia.\n              }\n              rewrite H9; clear H9.\n\n              repeat split; try assumption; try lia.\n              { unfold ONoSameLockTo, OLockedTo in *.\n                mred; simpl; mred.\n                destruct (porq@[downRq]) as [rqid|]; auto.\n                right.\n                intro Hx; elim H5; eauto.\n              }\n              { xthd; try discriminate.\n                red; mred; simpl; mred.\n                eexists; split; [left; reflexivity|assumption].\n              }\n            }\n            { destruct H; [left; assumption|right].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              exfalso.\n              disc_rule_conds.\n              apply FirstMP_InMP in H14.\n              red in H14; simpl in H14; rewrite H16 in H14.\n              elim H14.\n            }\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              apply upLockedInv_orqs_preserved_parent_some_up\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockedInv_msgs_preserved; [eassumption| |].\n                { destruct H11 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n                { destruct H11 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { intro Hx; rewrite H29 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H9 Hx).\n                reflexivity.\n              }\n            }\n            { apply upLockFreeInv_orqs_preserved_parent_some_up\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n                { destruct H.\n                  { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                    destruct orqUp; auto.\n                    eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                    dest; disc_rule_conds.\n                  }\n                  { destruct H as [rqUp [down [pidx ?]]]; dest.\n                    disc_rule_conds.\n                    solve_q.\n                  }\n                }\n                { destruct H.\n                  { remember (edgeDownTo dtr oidx) as odown.\n                    destruct odown; auto.\n                    eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                    dest; disc_rule_conds.\n                  }\n                  { destruct H as [rqUp [down [pidx ?]]]; dest.\n                    disc_rule_conds.\n                    solve_q.\n                  }\n                }\n              }\n              { intro Hx; rewrite H29 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H9 Hx).\n                reflexivity.\n              }\n            }\n\n        + (** case [RqUpDown-silent] *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          { dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_some_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockedInv_msgs_preserved; [eassumption| |].\n              { destruct H1 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n              { destruct H1 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                rewrite rssQ_enqMsgs_rqs by assumption.\n                solve_q.\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              apply parentIdxOf_Some in H2; [|apply Hsd].\n              dest; congruence.\n            }\n          }\n          { apply upLockFreeInv_orqs_preserved_parent_some_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n              { destruct H.\n                { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                  destruct orqUp; auto.\n                  eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { destruct H.\n                { remember (edgeDownTo dtr oidx) as odown.\n                  destruct odown; auto.\n                  eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  rewrite rssQ_enqMsgs_rqs by assumption.\n                  solve_q.\n                }\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              apply parentIdxOf_Some in H2; [|apply Hsd].\n              dest; congruence.\n            }\n          }\n\n        + (** case [RqUpDown] *)\n          destruct (idx_dec (obj_idx upCObj) oidx); subst.\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              disc_rule_conds.\n              exists rqFrom, rsbTo, (obj_idx obj).\n\n              xor3_inv1 H20; [dest|eapply findQ_length_one; eauto].\n\n              assert (length (findQ rqFrom (enqMsgs mouts (deqMP rqFrom msgs))) = 0).\n              { solve_q.\n                apply findQ_In_deqMP_FirstMP in H14; simpl in H14.\n                rewrite <-H14 in H16; simpl in H16.\n                lia.\n              }\n              rewrite H9; clear H9.\n\n              assert (length (rssQ (enqMsgs mouts (deqMP rqFrom msgs)) rsbTo) = 0).\n              { solve_q.\n                unfold rssQ in H2, H17; lia.\n              }\n              rewrite H9; clear H9.\n\n              repeat split; try assumption; try lia.\n              { unfold ONoSameLockTo, OLockedTo in *.\n                mred; simpl; mred.\n                destruct (porq@[upRq]) as [rqiu|]; auto.\n                left.\n                intro Hx; elim H7; eauto.\n              }\n              { xthd; try discriminate.\n                red; mred; simpl; mred.\n                eexists; split; [right; reflexivity|assumption].\n              }\n            }\n            { destruct H; [left; assumption|right].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              exfalso.\n              disc_rule_conds.\n              apply FirstMP_InMP in H14.\n              red in H14; simpl in H14; rewrite H16 in H14.\n              elim H14.\n            }\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              apply upLockedInv_orqs_preserved_parent_some_down\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockedInv_msgs_preserved; [eassumption| |].\n                { destruct H5 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n                { destruct H5 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  rewrite rssQ_enqMsgs_rqs by assumption.\n                  solve_q.\n                }\n              }\n              { intro Hx; rewrite H29 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H9 Hx).\n                reflexivity.\n              }\n            }\n            { apply upLockFreeInv_orqs_preserved_parent_some_down\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n                { destruct H.\n                  { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                    destruct orqUp; auto.\n                    eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                    dest; disc_rule_conds.\n                  }\n                  { destruct H as [rqUp [down [pidx ?]]]; dest.\n                    disc_rule_conds.\n                    solve_q.\n                  }\n                }\n                { destruct H.\n                  { remember (edgeDownTo dtr oidx) as odown.\n                    destruct odown; auto.\n                    eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                    dest; disc_rule_conds.\n                  }\n                  { destruct H as [rqUp [down [pidx ?]]]; dest.\n                    disc_rule_conds.\n                    rewrite rssQ_enqMsgs_rqs by assumption.\n                    solve_q.\n                  }\n                }\n              }\n              { intro Hx; rewrite H29 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H9 Hx).\n                reflexivity.\n              }\n            }\n\n        + (** case [RqDownDown] *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_some_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n                [assumption| |].\n              { destruct H7 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n              { destruct H7 as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                rewrite rssQ_enqMsgs_rqs by assumption.\n                solve_q.\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              elim (rqrsDTree_rsUp_down_not_eq Hsd _ _ H5 Hx).\n              reflexivity.\n            }\n          * apply upLockFreeInv_orqs_preserved_parent_some_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n                [assumption| |].\n              { destruct H.\n                { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                  destruct orqUp; auto.\n                  eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { destruct H.\n                { remember (edgeDownTo dtr oidx) as odown.\n                  destruct odown; auto.\n                  eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  rewrite rssQ_enqMsgs_rqs by assumption.\n                  solve_q.\n                }\n              }\n            }\n            { intro Hx; rewrite H29 in Hx.\n              elim (rqrsDTree_rsUp_down_not_eq Hsd _ _ H5 Hx).\n              reflexivity.\n            }\n\n      - (** case [RsBackRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n        + (** case [FootprintReleasingUp] *)\n          destruct (idx_dec cidx oidx); subst.\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              disc_rule_conds.\n              exists rqFrom, rsbTo0, (obj_idx obj).\n              xor3_inv3 H22; [dest|red; disc_rule_conds; eexists; intuition].\n              assert (length (findQ rqFrom (enqMP rsbTo0 rmsg (deqMP rsFrom msgs))) = 0).\n              { solve_q; lia. }\n              rewrite H15; clear H15.\n\n              assert (length (rssQ (enqMP rsbTo0 rmsg (deqMP rsFrom msgs)) rsbTo0) = 1).\n              { solve_q.\n                rewrite filter_app; simpl.\n                rewrite H12; simpl.\n                rewrite app_length; simpl.\n                unfold rssQ in H14, H20; lia.\n              }\n              rewrite H15; clear H15.\n\n              repeat split; try assumption; try lia.\n              { red; mred; simpl; mred. }\n              { xsnd; [discriminate|reflexivity|].\n                apply ONoLockTo_not_OLockedTo.\n                red in H21; red; mred.\n                simpl; mred; split; auto.\n              }\n            }\n            { destruct H; [left; assumption|right].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              exfalso.\n              disc_rule_conds.\n              red in H21; mred.\n            }\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              apply upLockedInv_orqs_preserved_parent_none_up\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockedInv_msgs_preserved; [eassumption| |].\n                { destruct H16 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n                { destruct H16 as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { intro Hx; rewrite H8 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H15 Hx).\n                reflexivity.\n              }\n            }\n            { apply upLockFreeInv_orqs_preserved_parent_none_up\n                with (orqs1:= orqs) (pidx:= obj_idx obj);\n                auto; try (repeat (mred; simpl); fail).\n              eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n              { destruct H.\n                { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                  destruct orqUp; auto.\n                  eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n              { destruct H.\n                { remember (edgeDownTo dtr oidx) as odown.\n                  destruct odown; auto.\n                  eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds.\n                  solve_q.\n                }\n              }\n            }\n\n        + (** case [FootprintReleasingUp-silent] *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_none_up\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockedInv_msgs_preserved; [eassumption| |].\n              { disc_rule_conds; solve_q. }\n              { disc_rule_conds; solve_q. }\n            }\n            { intro Hx; rewrite H8 in Hx.\n              eapply parentIdxOf_Some in H2; [|apply Hsd].\n              dest; congruence.\n            }\n          * apply upLockFreeInv_orqs_preserved_parent_none_up\n              with (orqs1:= orqs) (pidx:= obj_idx obj);\n              auto; try (repeat (mred; simpl); fail).\n            eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + (** case [FootprintReleasingDown]-1 *)\n          destruct (idx_dec (obj_idx upCObj) oidx); subst.\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              disc_rule_conds.\n              exists rqFrom, rsbTo0, (obj_idx obj).\n              xor3_inv3 H21; [dest|red; disc_rule_conds; eexists; intuition].\n              assert (length (findQ rqFrom (enqMP rsbTo0 rsm (deqMsgs (map fst (rqi_rss rqi)) msgs))) = 0) by (solve_q; lia).\n              rewrite H15; clear H15.\n\n              assert (length (rssQ (enqMP rsbTo0 rsm (deqMsgs (map fst (rqi_rss rqi)) msgs)) rsbTo0) = 1).\n              { solve_q.\n                rewrite filter_app; simpl.\n                rewrite H11; simpl.\n                rewrite app_length; simpl.\n                unfold rssQ in H12, H18; lia.\n              }\n              rewrite H15; clear H15.\n\n              repeat split; try assumption; try lia.\n              { red; mred; simpl; mred.\n                destruct (porq@[upRq]); auto.\n              }\n              { xsnd; [discriminate|reflexivity|].\n                apply ONoLockTo_not_OLockedTo.\n                red in H20; red; mred.\n                simpl; split.\n                { mred.\n                  destruct (porq@[upRq]) as [rqiu|]; auto.\n                  destruct H20; auto.\n                }\n                { mred. }\n              }\n            }\n            { destruct H; [left; assumption|right].\n              destruct H as [rqUp [down [pidx ?]]]; dest.\n              exfalso.\n              disc_rule_conds.\n              red in H20; mred.\n            }\n          * match goal with\n            | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n              destruct ul\n            end.\n            { dest; split; [assumption|].\n              apply upLockedInv_orqs_preserved_parent_none_down\n                with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n                auto; try (repeat (mred; simpl); fail).\n              { eapply upLockedInv_msgs_preserved; [eassumption| |].\n                { disc_rule_conds; solve_q. }\n                { disc_rule_conds; solve_q. }\n              }\n              { intro Hx; rewrite H1 in Hx.\n                elim (rqrsDTree_down_down_not_eq Hsd n H12 Hx).\n                reflexivity.\n              }\n            }\n            { apply upLockFreeInv_orqs_preserved_parent_none_down\n                with (orqs1:= orqs) (pidx:= obj_idx obj);\n                auto; try (repeat (mred; simpl); fail).\n              eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n              { destruct H.\n                { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                  destruct orqUp; auto.\n                  eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds; solve_q.\n                }\n              }\n              { destruct H.\n                { remember (edgeDownTo dtr oidx) as odown.\n                  destruct odown; auto.\n                  eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                  dest; disc_rule_conds.\n                }\n                { destruct H as [rqUp [down [pidx ?]]]; dest.\n                  disc_rule_conds; solve_q.\n                }\n              }\n            }\n\n        + (** case [FootprintReleasingDown]-2 *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_none_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockedInv_msgs_preserved; [eassumption| |].\n              { disc_rule_conds; solve_q. }\n              { disc_rule_conds; solve_q. }\n            }\n            { intro Hx; rewrite H1 in Hx.\n              elim (rqrsDTree_rsUp_down_not_eq Hsd _ _ H7 Hx).\n              reflexivity.\n            }\n          * apply upLockFreeInv_orqs_preserved_parent_none_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj);\n              auto; try (repeat (mred; simpl); fail).\n            eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n        + (** case [FootprintReleasingDown]-3 *)\n          match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_parent_none_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi);\n              auto; try (repeat (mred; simpl); fail).\n            { eapply upLockedInv_msgs_preserved; [eassumption| |].\n              { disc_rule_conds; solve_q. }\n              { disc_rule_conds; solve_q. }\n            }\n            { intro Hx; rewrite H1 in Hx.\n              apply parentIdxOf_Some in H2; [|apply Hsd]; dest.\n              congruence.\n            }\n          * apply upLockFreeInv_orqs_preserved_parent_none_down\n              with (orqs1:= orqs) (pidx:= obj_idx obj);\n              auto; try (repeat (mred; simpl); fail).\n            eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds; solve_q.\n              }\n            }\n\n      - (** case [RsDownRqDownRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          disc_rule_conds.\n          eapply upLockedInv_orqs_preserved_rs_rq\n            with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi1) (rqid:= rqi0);\n            auto; try (repeat (mred; simpl); fail); [|congruence].\n          eapply upLockedInv_msgs_preserved.\n          * red; eauto 10.\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds.\n            rewrite rssQ_enqMsgs_rqs by assumption.\n            solve_q.\n        + disc_rule_conds.\n          eapply upLockFreeInv_orqs_preserved_rs_rq\n            with (orqs1:= orqs) (pidx:= obj_idx obj) (rqiu:= rqi1) (rqid:= rqi0);\n            auto; try (repeat (mred; simpl); fail); [|congruence].\n          eapply upLockFreeInv_msgs_preserved; [eassumption| |].\n          * destruct H.\n            { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n              destruct orqUp; auto.\n              eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n          * destruct H.\n            { remember (edgeDownTo dtr oidx) as odown.\n              destruct odown; auto.\n              eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              rewrite rssQ_enqMsgs_rqs by assumption.\n              solve_q.\n            }\n    Qed.\n\n    Lemma upLockInvORq_step_int_other:\n      forall oidx orq,\n        UpLockInvORq orqs msgs oidx orq ->\n        In oidx (map obj_idx (sys_objs sys)) ->\n        GoodRqRsRule dtr sys (obj_idx obj) rule ->\n        obj_idx obj <> oidx ->\n        parentIdxOf dtr oidx <> Some (obj_idx obj) ->\n        UpLockInvORq (orqs+[obj_idx obj <- norq])\n                     (enqMsgs mouts (deqMsgs (idsOf mins) msgs)) oidx\n                     orq.\n    Proof.\n      intros.\n      destruct Hsd as [? [? _]].\n      red in H; red.\n      good_rqrs_rule_cases rule.\n\n      - (** case [ImmDownRule] *)\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          apply upLockedInv_orqs_preserved_non_parent_update; auto.\n          apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds; solve_q.\n        + apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n          apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * destruct H.\n            { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n              destruct orqUp; auto.\n              eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n          * destruct H.\n            { remember (edgeDownTo dtr oidx) as odown.\n              destruct odown; auto.\n              eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n\n      - (** case [ImmUpRule] *)\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          apply upLockedInv_orqs_preserved_non_parent_update; auto.\n          apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds; solve_q.\n        + apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n          apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * destruct H.\n            { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n              destruct orqUp; auto.\n              eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n          * destruct H.\n            { remember (edgeDownTo dtr oidx) as odown.\n              destruct odown; auto.\n              eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n\n      - (** case [RqFwdRule] *)\n        disc_rule_conds.\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n      - (** case [RsBackRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n        + match goal with\n          | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n            destruct ul\n          end.\n          * dest; split; [assumption|].\n            apply upLockedInv_orqs_preserved_non_parent_update; auto.\n            apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { disc_rule_conds; solve_q. }\n            { disc_rule_conds; solve_q. }\n          * apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n            apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n              [assumption| |].\n            { destruct H.\n              { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n                destruct orqUp; auto.\n                eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n            { destruct H.\n              { remember (edgeDownTo dtr oidx) as odown.\n                destruct odown; auto.\n                eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n                dest; disc_rule_conds.\n              }\n              { destruct H as [rqUp [down [pidx ?]]]; dest.\n                disc_rule_conds.\n                solve_q.\n              }\n            }\n\n      - (** case [RsDownRqDownRule] *)\n        good_footprint_get (obj_idx obj).\n        disc_rule_conds.\n        match goal with\n        | [ |- match ?ul with | Some _ => _ | None => _ end] =>\n          destruct ul\n        end.\n        + dest; split; [assumption|].\n          apply upLockedInv_orqs_preserved_non_parent_update; auto.\n          apply upLockedInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * disc_rule_conds; solve_q.\n          * disc_rule_conds; solve_q.\n        + apply upLockFreeInv_orqs_preserved_non_parent_update; auto.\n          apply upLockFreeInv_msgs_preserved with (msgs1:= msgs);\n            [assumption| |].\n          * destruct H.\n            { remember (rqEdgeUpFrom dtr oidx) as orqUp.\n              destruct orqUp; auto.\n              eapply eq_sym, rqEdgeUpFrom_Some in HeqorqUp; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n          * destruct H.\n            { remember (edgeDownTo dtr oidx) as odown.\n              destruct odown; auto.\n              eapply eq_sym, edgeDownTo_Some in Heqodown; [|eassumption].\n              dest; disc_rule_conds.\n            }\n            { destruct H as [rqUp [down [pidx ?]]]; dest.\n              disc_rule_conds.\n              solve_q.\n            }\n    Qed.\n\n    Lemma upLockInv_step_int:\n      UpLockInv {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      UpLockInv {| st_oss := (oss) +[ obj_idx obj <- nost];\n                   st_orqs := (orqs) +[ obj_idx obj <- norq];\n                   st_msgs := enqMsgs mouts (deqMsgs (idsOf mins) msgs) |}.\n    Proof.\n      intros.\n      do 2 red; simpl; intros.\n      good_rqrs_rule_get rule.\n      specialize (H _ H0); simpl in H; dest.\n\n      M.cmp (obj_idx obj) oidx; mred; simpl in *.\n      - (** case [oidx = obj_idx obj] *)\n        apply upLockInvORq_step_int_me; assumption.\n      - (** case [oidx <> obj_idx obj] *)\n        remember (parentIdxOf dtr oidx) as opidx.\n        destruct opidx as [pidx|].\n        + destruct (idx_dec (obj_idx obj) pidx); subst.\n          * apply upLockInvORq_step_int_parent; auto.\n          * apply upLockInvORq_step_int_other; auto.\n            rewrite <-Heqopidx.\n            intro Hx; elim n0; inv Hx; reflexivity.\n        + apply upLockInvORq_step_int_other; auto.\n          rewrite <-Heqopidx; discriminate.\n    Qed.\n\n  End InternalStep.\n\n  Lemma upLockInv_step:\n    InvStep sys step_m UpLockInv.\n  Proof.\n    red; intros.\n    inv H1.\n    - auto.\n    - apply upLockInv_step_ext_in; auto.\n    - apply upLockInv_step_ext_out; auto.\n    - eapply upLockInv_step_int; eauto.\n      eapply footprints_ok; eassumption.\n  Qed.\n\n  Lemma upLockInv_ok:\n    InvReachable sys step_m UpLockInv.\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply upLockInv_init.\n    - apply upLockInv_step.\n  Qed.\n\nEnd UpLockInv.\n\nLemma upLockInvORq_rqUp_length_one_locked:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq pidx rqUp,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    rqEdgeUpFrom dtr oidx = Some rqUp ->\n    length (findQ rqUp msgs) >= 1 ->\n    orq@[upRq] <> None /\\ UpLockedInv dtr orqs msgs oidx.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]); [dest; split; [discriminate|assumption]|].\n  destruct H.\n  - rewrite H in H0; discriminate.\n  - destruct H as [rrqUp [down [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    rewrite H5 in H2; simpl in H2; lia.\nQed.\n\nLemma upLockInvORq_down_rssQ_length_one_locked:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq down pidx,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    edgeDownTo dtr oidx = Some down ->\n    length (rssQ msgs down) >= 1 ->\n    orq@[upRq] <> None /\\ UpLockedInv dtr orqs msgs oidx.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]); [dest; split; [discriminate|assumption]|].\n  destruct H.\n  - rewrite H in H0; discriminate.\n  - destruct H as [rqUp [rdown [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    rewrite H6 in H2; simpl in H2; lia.\nQed.\n\nLemma upLockInvORq_parent_locked_locked:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq down pidx,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    edgeDownTo dtr oidx = Some down ->\n    OLockedTo orqs pidx (Some down) ->\n    orq@[upRq] <> None /\\ UpLockedInv dtr orqs msgs oidx.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]); [dest; split; [discriminate|assumption]|].\n  destruct H.\n  - rewrite H in H0; discriminate.\n  - destruct H as [rqUp [rdown [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    exfalso; eapply ONoLockTo_not_OLockedTo; eauto.\nQed.\n\nLemma upLockInvORq_rqUp_down_rssQ_False:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq pidx rqUp down,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    rqEdgeUpFrom dtr oidx = Some rqUp ->\n    edgeDownTo dtr oidx = Some down ->\n    length (findQ rqUp msgs) >= 1 ->\n    length (rssQ msgs down) >= 1 ->\n    False.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]).\n  - destruct H as [rrqUp [rdown [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    xor3_contra1 H10; lia.\n  - destruct H.\n    + congruence.\n    + destruct H as [rrqUp [rdown [rpidx ?]]]; dest.\n      repeat disc_rule_minds.\n      rewrite H7 in H3; simpl in H3; lia.\nQed.\n\nLemma upLockInvORq_rqUp_length_two_False:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq pidx rqUp,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    rqEdgeUpFrom dtr oidx = Some rqUp ->\n    length (findQ rqUp msgs) >= 2 ->\n    False.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]).\n  - destruct H as [rrqUp [down [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    lia.\n  - destruct H.\n    + congruence.\n    + destruct H as [rrqUp [down [rpidx ?]]]; dest.\n      repeat disc_rule_minds.\n      rewrite H5 in H2; simpl in H2; lia.\nQed.\n\nLemma upLockInvORq_down_rssQ_length_two_False:\n  forall `{dv: DecValue} dtr orqs msgs oidx orq pidx down,\n    UpLockInvORq dtr orqs msgs oidx orq ->\n    parentIdxOf dtr oidx = Some pidx ->\n    edgeDownTo dtr oidx = Some down ->\n    length (rssQ msgs down) >= 2 ->\n    False.\nProof.\n  intros.\n  red in H; destruct (orq@[upRq]).\n  - destruct H as [rqUp [rdown [rpidx ?]]]; dest.\n    repeat disc_rule_minds.\n    lia.\n  - destruct H.\n    + congruence.\n    + destruct H as [rqUp [rdown [rpidx ?]]]; dest.\n      repeat disc_rule_minds.\n      rewrite H6 in H2; simpl in H2; lia.\nQed.\n\nClose Scope list.\nClose Scope fmap.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Dsl/RqRsInvUpLock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16291686287222315}}
{"text": "Require Import Coq.Bool.Bool.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.msl.Axioms.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.effect_semantics.\nRequire Import VST.sepcomp.structured_injections.\nRequire Import VST.sepcomp.reach.\n\nModule SM_simulation. Section SharedMemory_simulation_inject.\n\nContext\n  {F1 V1 C1 F2 V2 C2 : Type}\n  (Sem1 : @EffectSem (Genv.t F1 V1) C1)\n  (Sem2 : @EffectSem (Genv.t F2 V2) C2)\n  (ge1 : Genv.t F1 V1)\n  (ge2 : Genv.t F2 V2).\n\nRecord SM_simulation_inject :=\n{ core_data : Type\n; match_state : core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop\n; core_ord : core_data -> core_data -> Prop\n; core_ord_wf : well_founded core_ord\n\n; match_sm_wd :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 -> SM_wd mu\n\n; genvs_dom_eq : genvs_domain_eq ge1 ge2\n\n; match_genv :\n    forall d mu c1 m1 c2 m2 (MC : match_state d mu c1 m1 c2 m2),\n    meminj_preserves_globals ge1 (extern_of mu) /\\\n    (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true)\n\n; match_visible :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 ->\n    REACH_closed m1 (vis mu)\n\n; match_restrict :\n    forall d mu c1 m1 c2 m2 X,\n    match_state d mu c1 m1 c2 m2 ->\n    (forall b, vis mu b = true -> X b = true) ->\n    REACH_closed m1 X ->\n    match_state d (restrict_sm mu X) c1 m1 c2 m2\n\n; match_validblocks :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 ->\n    sm_valid mu m1 m2\n\n\n; core_initial :\n    forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n    initial_core Sem1 0 ge1 v vals1 = Some c1 ->\n    Mem.inject j m1 m2 ->\n    Forall2 (val_inject j) vals1 vals2 ->\n    meminj_preserves_globals ge1 j ->\n\n    (*the next two conditions are required to guarantee initialSM_wd*)\n    (forall b1 b2 d, j b1 = Some (b2, d) ->\n      DomS b1 = true /\\ DomT b2 = true) ->\n    (forall b,\n      REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b=true ->\n      DomT b = true) ->\n\n    (*the next two conditions ensure the initialSM satisfies sm_valid*)\n    (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n    (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n    exists cd, exists c2,\n    initial_core Sem2 0 ge2 v vals2 = Some c2\n    /\\ match_state cd\n         (initial_SM DomS DomT\n           (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n           (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n         c1 m1 c2 m2\n\n; effcore_diagram :\n    forall st1 m1 st1' m1' U1,\n    effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n    forall cd st2 mu m2,\n    match_state cd mu st1 m1 st2 m2 ->\n    exists st2', exists m2', exists cd', exists mu',\n      intern_incr mu mu'\n      /\\ sm_inject_separated mu mu' m1 m2\n      /\\ sm_locally_allocated mu mu' m1 m2 m1' m2'\n      /\\ match_state cd' mu' st1' m1' st2' m2'\n      /\\ exists U2,\n          ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n            (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n             core_ord cd' cd)) /\\\n         forall\n           (UHyp: forall b1 z, U1 b1 z = true -> vis mu b1 = true)\n           b ofs (Ub: U2 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                 /\\ U1 b1 (ofs-delta1) = true\n                 /\\ Mem.perm m1 b1 (ofs-delta1) Max Nonempty))\n\n\n; core_halted :\n    forall cd mu c1 m1 c2 m2 v1,\n    match_state cd mu c1 m1 c2 m2 ->\n    halted Sem1 c1 = Some v1 ->\n    exists v2,\n    Mem.inject (as_inj mu) m1 m2\n    /\\ val_inject (restrict (as_inj mu) (vis mu)) v1 v2\n    /\\ halted Sem2 c2 = Some v2\n\n\n; core_at_external :\n    forall cd mu c1 m1 c2 m2 e vals1,\n    match_state cd mu c1 m1 c2 m2 ->\n    at_external Sem1 c1 = Some (e,vals1) ->\n    Mem.inject (as_inj mu) m1 m2\n    /\\ exists vals2,\n       Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2\n       /\\ at_external Sem2 c2 = Some (e,vals2)\n\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_state cd nu c1 m1 c2 m2\n       /\\ Mem.inject (shared_of nu) m1 m2\n\n; eff_after_external:\n    forall cd mu st1 st2 m1 e vals1 m2 vals2 e'\n      (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n      (MatchMu: match_state cd mu st1 m1 st2 m2)\n      (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (* We include the clause AtExtTgt to ensure that vals2 is\n         uniquely determined. We have e=e' and ef_sig=ef_sig' by the\n         at_external clause, but omitting the hypothesis AtExtTgt\n         would result in in 2 not necesssarily equal target argument\n         lists in language 3 in the transitivity, as val_inject is not\n         functional in the case where the left value is Vundef. (And\n         we need to keep ValInjMu since vals2 occurs in pubTgtHyp) *)\n\n      (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n      (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n      pubSrc'\n      (pubSrcHyp:\n         pubSrc'\n         = (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n\n      pubTgt'\n      (pubTgtHyp:\n         pubTgt'\n         = fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b)\n\n      nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc'\n        (frgnSrcHyp:\n           frgnSrc'\n           = fun b => DomSrc nu' b &&\n                      (negb (locBlocksSrc nu' b) &&\n                       REACH m1' (exportedSrc nu' (ret1::nil)) b))\n\n        frgnTgt'\n        (frgnTgtHyp:\n           frgnTgt'\n           = fun b => DomTgt nu' b &&\n                      (negb (locBlocksTgt nu' b) &&\n                       REACH m2' (exportedTgt nu' (ret2::nil)) b))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n         (UnchPrivSrc:\n            Mem.unchanged_on (fun b ofs =>\n              locBlocksSrc nu b = true /\\\n              pubBlocksSrc nu b = false) m1 m1')\n\n         (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n\n        exists cd', exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_state cd' mu' st1' m1' st2' m2' }.\n\nRequire Import VST.sepcomp.semantics_lemmas.\n\nLemma core_diagram (SMI: SM_simulation_inject):\n      forall st1 m1 st1' m1',\n        corestep Sem1 ge1 st1 m1 st1' m1' ->\n      forall cd st2 mu m2,\n        match_state SMI cd mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists cd', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n          match_state SMI cd' mu' st1' m1' st2' m2' /\\\n          ((corestep_plus Sem2 ge2 st2 m2 st2' m2') \\/\n            corestep_star Sem2 ge2 st2 m2 st2' m2' /\\\n            core_ord SMI cd' cd).\nProof. intros.\napply effax2 in H. destruct H as [U1 H].\nexploit (effcore_diagram SMI); eauto.\nintros [st2' [m2' [cd' [mu' [INC [SEP [LOCALLOC\n  [MST [U2 [STEP _]]]]]]]]]].\nexists st2', m2', cd', mu'.\nsplit; try assumption.\nsplit; try assumption.\nsplit; try assumption.\nsplit; try assumption.\ndestruct STEP as [[n STEP] | [[n STEP] CO]];\n  apply effstepN_corestepN in STEP.\nleft. exists n. assumption.\nright; split; trivial. exists n. assumption.\nQed.\n\nEnd SharedMemory_simulation_inject.\n\nEnd SM_simulation.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/effect_simulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.32082128783705344, "lm_q1q2_score": 0.16291685627698937}}
{"text": "\nRequire Import Coq.Program.Basics. \nRequire Import Coq.Strings.String. \nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Coq.Program.Equality.\nRequire Import Logic.FunctionalExtensionality.\n\nRequire Import FinProof.Common. \nRequire Import FinProof.MonadTransformers21.\nRequire Import FinProof.Common.\nRequire Import FinProof.StateMonad21.\nRequire Import FinProof.StateMonad21Instances.\nRequire Import FinProof.Types.IsoTypes.\n\nRequire Import UMLang.UrsusLib.\n\nRequire Import UrsusStdLib.Cpp.stdTypes.\n\nRequire Import UrsusTVM.Cpp.tvmTypes.\nRequire Import UrsusTVM.Cpp.tvmFunc.\nRequire Import UrsusTVM.Cpp.tvmNotations.\nRequire Import UrsusTVM.Cpp.tvmCells.\n\nRequire Import Project.CommonConstSig.\nRequire Import Project.CommonTypes.\n\nLocal Open Scope N_scope.\n\n#[global] \nInstance  KWMessages_Consts :KWMessagesCommonConsts:= {\nKWMessages_\u03b9_MIN_VOTING_TIME_:= Build_XUBInteger 180;\nKWMessages_\u03b9_TIME_FOR_SETCODE_PREPARE_:= Build_XUBInteger 345600;\nKWMessages_\u03b9_TIME_FOR_FUNDS_COLLECTING_:= Build_XUBInteger 259200;\nKWMessages_\u03b9_VOTING_FEE_:= Build_XUBInteger 500000000;\nKWMessages_\u03b9_MSG_VALUE_BUT_FEE_FLAGS_:= Build_XUBInteger 64;\nKWMessages_\u03b9_DEFAULT_MSG_FLAGS_:= Build_XUBInteger 0;\nKWMessages_\u03b9_ALL_BALANCE_MSG_FLAG_:= Build_XUBInteger 128;\nKWMessages_\u03b9_FG_MIN_BALANCE_:= Build_XUBInteger 5000000000;\nKWMessages_\u03b9_GAS_FOR_FUND_MESSAGE_:= Build_XUBInteger 500000000;\nKWMessages_\u03b9_KWD_MIN_BALANCE_:= Build_XUBInteger 5000000000;\nKWMessages_\u03b9_GAS_FOR_PARTICIPANT_MESSAGE_:= Build_XUBInteger 500000000;\nKWMessages_\u03b9_EPSILON_BALANCE_:= Build_XUBInteger 500000000;\nKWMessages_\u03b9_RESPAWN_BALANCE_:= Build_XUBInteger 50000000000;\nKWMessages_\u03b9_BLANK_MIN_BALANCE_:= Build_XUBInteger 20000000000;\n} .\n\n#[global] \nInstance  KWErrors_Errors :KWErrorsCommonErrors:= {\nKWErrors_\u03b9_error_code_not_correct_:= 134;\nKWErrors_\u03b9_error_already_voted_:= 133;\nKWErrors_\u03b9_error_already_all_ack_:= 132;\nKWErrors_\u03b9_error_kwf_lock_time_not_set_:= 131;\nKWErrors_\u03b9_error_rate_not_set_:= 130;\nKWErrors_\u03b9_error_max_summa_less_min_:= 129;\nKWErrors_\u03b9_error_sum_too_small_:= 128;\nKWErrors_\u03b9_error_cannot_change_code_:= 127;\nKWErrors_\u03b9_error_giver_not_set_:= 126;\nKWErrors_\u03b9_error_not_all_ack_:= 125;\nKWErrors_\u03b9_error_not_my_investor_:= 124;\nKWErrors_\u03b9_error_not_my_code_:= 123;\nKWErrors_\u03b9_error_unlock_time_less_lock_:= 122;\nKWErrors_\u03b9_error_not_my_giver_:= 121;\nKWErrors_\u03b9_error_cant_initialize_:= 120;\nKWErrors_\u03b9_error_not_internal_message_:= 119;\nKWErrors_\u03b9_error_return_address_is_mine_:= 118;\nKWErrors_\u03b9_error_fund_not_set_:= 117;\nKWErrors_\u03b9_error_initialized_:= 116;\nKWErrors_\u03b9_error_not_initialized_:= 115;\nKWErrors_\u03b9_error_time_too_early_:= 114;\nKWErrors_\u03b9_error_fund_ready_not_set_:= 113;\nKWErrors_\u03b9_error_balance_not_positive_:= 112;\nKWErrors_\u03b9_error_final_address_not_set_:= 111;\nKWErrors_\u03b9_error_fund_ready_set_:= 110;\nKWErrors_\u03b9_error_time_not_inside_:= 109;\nKWErrors_\u03b9_error_not_my_fund_:= 108;\nKWErrors_\u03b9_error_msg_value_too_low_:= 107;\nKWErrors_\u03b9_error_farm_rate_not_set_:= 106;\nKWErrors_\u03b9_error_quant_not_set_:= 105;\nKWErrors_\u03b9_error_time_too_late_:= 104;\nKWErrors_\u03b9_error_balance_too_low_:= 103;\nKWErrors_\u03b9_error_not_my_pubkey_:= 102;\nKWErrors_\u03b9_error_not_external_message_:= 101;\n} .\n#[global] \nInstance  KWErrors_Consts :KWErrorsCommonConsts:= {\nKWErrors_\u03b9_voting_time_too_long_:= Build_XUBInteger 137;\nKWErrors_\u03b9_voting_time_too_low_:= Build_XUBInteger 136;\nKWErrors_\u03b9_voting_fee_too_low_:= Build_XUBInteger 135;\n} .", "meta": {"author": "kwpc-io", "repo": "kwf_contracts", "sha": "3c4030ba73392bb76431d1880b383b816b3bf1e2", "save_path": "github-repos/coq/kwpc-io-kwf_contracts", "path": "github-repos/coq/kwpc-io-kwf_contracts/kwf_contracts-3c4030ba73392bb76431d1880b383b816b3bf1e2/src/Project/CommonConsts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.16269223039427952}}
{"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 PProc                                 *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem2.\nRequire Import AsmImplLemma.\nRequire Import GenSem.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\n\nRequire Import LAsmModuleSemAux.\nRequire Import LayerCalculusLemma.\nRequire Import AbstractDataType.\n\nRequire Import PUCtxtIntro.\nRequire Import PProc.\n\nRequire Import ProcGenSpec.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Local Open Scope string_scope.\n  Local Open Scope error_monad_scope.\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  Notation HDATA := RData.\n  Notation LDATA := RData.\n\n  Notation HDATAOps := (cdata (cdata_ops := pproc_data_ops) HDATA).\n  Notation LDATAOps := (cdata (cdata_ops := pipc_data_ops) LDATA).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n    \n    (** Relation between raw data at two layers*)\n    Record relate_RData (f: meminj) (hadt: HDATA) (ladt: LDATA) :=\n      mkrelate_RData {\n          flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n          vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n          devout_re: devout hadt = devout ladt;\n          CR3_re:  CR3 hadt = CR3 ladt;\n          ikern_re: ikern hadt = ikern ladt;\n          pg_re: pg hadt = pg ladt;\n          ihost_re: ihost hadt = ihost ladt;\n          AC_re: AC hadt = AC ladt;\n          ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n          ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n          LAT_re: LAT hadt = LAT ladt;\n          nps_re: nps hadt = nps ladt;\n          init_re: init hadt = init ladt;\n\n          pperm_re: pperm hadt = pperm ladt;\n          PT_re:  PT hadt = PT ladt;\n          ptp_re: ptpool hadt = ptpool ladt;\n          idpde_re: idpde hadt = idpde ladt;\n          ipt_re: ipt hadt = ipt ladt;\n          smspool_re: smspool hadt = smspool ladt;\n\n          kctxt_re: kctxt_inj f num_proc (kctxt hadt) (kctxt ladt);\n          abtcb_re:  abtcb hadt = abtcb ladt;\n          abq_re:  abq hadt = abq ladt;\n          cid_re:  cid hadt = cid ladt;\n          chpool_re:  syncchpool hadt = syncchpool ladt;\n          uctxt_re: uctxt_inj f (uctxt hadt) (uctxt ladt)\n        }.\n\n    Inductive match_RData: stencil -> HDATA -> mem -> meminj -> Prop :=\n    | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n    Local Hint Resolve MATCH_RDATA.\n\n    Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n      {\n        relate_AbData s f d1 d2 := relate_RData f d1 d2;\n        match_AbData s d1 m f := match_RData s d1 m f;\n        new_glbl := nil\n      }.    \n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n        - eapply kctxt_inj_incr; eauto.\n        - eapply uctxt_inj_incr; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      Section FRESH_PRIM.\n\n        Lemma proc_start_user_spec_ref:\n          compatsim (crel HDATA LDATA)\n                    (primcall_start_user_compatsem proc_start_user_spec)\n                    proc_start_user_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          intros.\n          inv match_extcall_states.\n          exploit proc_start_user_exist; eauto 1.\n          eapply valid_curid; eauto.\n          intros (d2' & rs2' & HM & HR & HReg & He & Hrange'). \n          subst.\n          refine_split; try econstructor; eauto. \n          eapply reg_symbol_inject; eassumption.\n          econstructor; eauto. \n          constructor.\n          val_inject_simpl; try (eapply HReg; omega).\n        Qed.\n\n        Lemma proc_exit_user_spec_ref:\n          compatsim (crel HDATA LDATA)\n                    (primcall_exit_user_compatsem proc_exit_user_spec)\n                    proc_exit_user_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          intros.\n          inv H4. inv match_extcall_states.\n          exploit proc_exit_user_exist; eauto 1.\n          - subst uctx4 uctx3 uctx2 uctx1.\n            intros. inv_proc. rewrite ZMap.gi. constructor.\n          - intros [d2'[HM HR]].\n            refine_split; try econstructor; eauto. \n            eapply reg_symbol_inject; eassumption.\n            + exploit (extcall_args_inject (D1:= HDATAOps) (D2:= LDATAOps)); eauto.\n              instantiate (3:= d1').\n              apply extcall_args_with_data; eauto.\n              instantiate (1:= d2).\n              intros [?[? Hinv]]. inv_val_inject.\n              apply extcall_args_without_data in H; eauto.\n            + specialize (match_reg ESP); unfold Pregmap.get in match_reg.\n              inv match_reg; congruence.\n            + intros.\n              specialize (match_reg ESP); unfold Pregmap.get in match_reg.\n              inv match_reg; try congruence.\n              specialize (HESP_STACK _ _ (eq_sym H1)).\n              replace b1 with b2 by congruence.\n              split.\n              * apply Ple_trans with b0;\n                [ apply HESP_STACK | apply (match_inject_forward _ _ _ H3) ].\n              * apply (Mem.valid_block_inject_2 _ _ _ _ _ _ H3 match_inject).\n            + econstructor; eauto. constructor.\n            + val_inject_simpl. \n        Qed.\n        \n        Lemma proc_create_kernel_mode:\n          forall d2 d2' b b' b2 ofs_uc q,\n            proc_create_spec d2 b b' b2 ofs_uc q = Some d2'\n            -> kernel_mode d2.\n        Proof.\n          unfold proc_create_spec; intros.\n          simpl; subdestruct. auto.\n        Qed.\n\n        Lemma proc_create_spec_ref:\n          compatsim (crel HDATA LDATA) (proc_create_compatsem proc_create_spec) proc_create_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit proc_create_exist; eauto 1.\n          intros (labd' & HP  & HM).\n          destruct H9 as [fun_id Hsymbol].\n          exploit (stencil_find_symbol_inject' s \u03b9 fun_id buc); eauto.\n          intros HFB.\n          destruct H10 as [elf_id Hsymbol'].\n          exploit (stencil_find_symbol_inject' s \u03b9 elf_id be); eauto.\n          intros HFB'.\n          refine_split; try econstructor; eauto. \n          - eapply proc_create_kernel_mode; eauto.\n          - constructor.\n        Qed.\n\n      End FRESH_PRIM.\n\n      Section PASSTHROUGH_PRIM.\n\n        Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).\n        Proof.\n          accessor_prop_tac.\n          - eapply flatmem_store_exists; eauto.\n        Qed.\n\n        Lemma passthrough_correct:\n          sim (crel HDATA LDATA) pproc_passthrough puctxtintro.\n        Proof.\n          sim_oplus.\n          - apply fload_sim.\n          - apply fstore_sim.\n          - apply vmxinfo_get_sim.          \n          - apply device_output_sim.\n          (*- apply pfree_sim.*)\n          - apply ptRead_sim. \n          - apply ptResv_sim.\n          - apply shared_mem_status_sim.\n          - apply offer_shared_mem_sim.\n          - apply get_curid_sim.\n          - apply thread_wakeup_sim.\n          (*- apply is_chan_ready_sim.\n          - apply sendto_chan_sim.\n          - apply receive_chan_sim.*)\n          - apply syncreceive_chan_sim.\n          - apply syncsendto_chan_pre_sim.\n          - apply syncsendto_chan_post_sim.\n          - apply proc_init_sim.\n          - apply uctx_get_sim.\n          - apply uctx_set_sim.\n          - apply container_get_nchildren_sim.\n          - apply container_get_quota_sim.\n          - apply container_get_usage_sim.\n          - apply container_can_consume_sim.\n          - apply alloc_sim. \n          - apply hostin_sim.\n          - apply hostout_sim.\n          - apply trap_info_get_sim.\n          - apply trap_info_ret_sim.\n          - apply thread_yield_sim.\n          - apply thread_sleep_sim.\n          - layer_sim_simpl.\n            + eapply load_correct2.\n            + eapply store_correct2.\n        Qed.\n\n      End PASSTHROUGH_PRIM.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.\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/ProcGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.2598256494239272, "lm_q1q2_score": 0.16268311734301566}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma pure1 (x : nat) (y : nat) : (y) <= (x) -> (x) <= (x). intros; hammer. Qed.\nHint Resolve pure1: ssl_pure.\nLemma pure2 (x : nat) (y : nat) : ~~ ((y) <= (x)) -> (x) <= (y). intros; hammer. Qed.\nHint Resolve pure2: ssl_pure.\nLemma pure3 (y : nat) (x : nat) : ~~ ((y) <= (x)) -> (y) <= (y). intros; hammer. Qed.\nHint Resolve pure3: ssl_pure.\n\nDefinition max_type :=\n  forall (vprogs : ptr * nat * nat),\n  STsep (\n    fun h =>\n      let: (r, x, y) := vprogs in\n      h = r :-> (0),\n    [vfun (_: unit) h =>\n      let: (r, x, y) := vprogs in\n      exists m,\n      (x) <= (m) /\\ (y) <= (m) /\\ h = r :-> (m)\n    ]).\n\nProgram Definition max : max_type :=\n  Fix (fun (max : max_type) vprogs =>\n    let: (r, x, y) := vprogs in\n    Do (\n      if (y) <= (x)\n      then\n        r ::= x;;\n        ret tt\n      else\n        r ::= y;;\n        ret tt\n    )).\nObligation Tactic := intro; move=>[[r x] y]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>[sigma_self].\nsubst h_self.\nssl_ghostelim_post.\nssl_branch ((y) <= (x)).\nssl_write r.\nssl_write_post r.\nssl_emp;\nexists (x);\nsslauto.\nssl_write r.\nssl_write_post r.\nssl_emp;\nexists (y);\nsslauto.\nQed.", "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/standard/ints/max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16262376581548288}}
{"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 RealmExitHandler.Layer.\nRequire Import RunAux.Code.emulate_mmio_read.\n\nRequire Import RunAux.LowSpecs.emulate_mmio_read.\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    _access_mask \u21a6 gensem access_mask_spec\n      \u2295 _get_rec_run_emulated_read_val \u21a6 gensem get_rec_run_emulated_read_val_spec\n      \u2295 _esr_sign_extend \u21a6 gensem esr_sign_extend_spec\n      \u2295 _access_len \u21a6 gensem access_len_spec\n      \u2295 _shiftl \u21a6 gensem shiftl_spec\n      \u2295 _esr_sixty_four \u21a6 gensem esr_sixty_four_spec\n      \u2295 _set_rec_regs \u21a6 gensem set_rec_regs_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_access_mask: block.\n    Hypothesis h_access_mask_s : Genv.find_symbol ge _access_mask = Some b_access_mask.\n    Hypothesis h_access_mask_p : Genv.find_funct_ptr ge b_access_mask\n                                 = Some (External (EF_external _access_mask\n                                                  (signature_of_type (Tcons tulong Tnil) tulong cc_default))\n                                        (Tcons tulong Tnil) tulong cc_default).\n    Local Opaque access_mask_spec.\n\n    Variable b_get_rec_run_emulated_read_val: block.\n    Hypothesis h_get_rec_run_emulated_read_val_s : Genv.find_symbol ge _get_rec_run_emulated_read_val = Some b_get_rec_run_emulated_read_val.\n    Hypothesis h_get_rec_run_emulated_read_val_p : Genv.find_funct_ptr ge b_get_rec_run_emulated_read_val\n                                                   = Some (External (EF_external _get_rec_run_emulated_read_val\n                                                                    (signature_of_type Tnil tulong cc_default))\n                                                          Tnil tulong cc_default).\n    Local Opaque get_rec_run_emulated_read_val_spec.\n\n    Variable b_esr_sign_extend: block.\n    Hypothesis h_esr_sign_extend_s : Genv.find_symbol ge _esr_sign_extend = Some b_esr_sign_extend.\n    Hypothesis h_esr_sign_extend_p : Genv.find_funct_ptr ge b_esr_sign_extend\n                                     = Some (External (EF_external _esr_sign_extend\n                                                      (signature_of_type (Tcons tulong Tnil) tuint cc_default))\n                                            (Tcons tulong Tnil) tuint cc_default).\n    Local Opaque esr_sign_extend_spec.\n\n    Variable b_access_len: block.\n    Hypothesis h_access_len_s : Genv.find_symbol ge _access_len = Some b_access_len.\n    Hypothesis h_access_len_p : Genv.find_funct_ptr ge b_access_len\n                                = Some (External (EF_external _access_len\n                                                 (signature_of_type (Tcons tulong Tnil) tuint cc_default))\n                                       (Tcons tulong Tnil) tuint cc_default).\n    Local Opaque access_len_spec.\n\n    Variable b_shiftl: block.\n    Hypothesis h_shiftl_s : Genv.find_symbol ge _shiftl = Some b_shiftl.\n    Hypothesis h_shiftl_p : Genv.find_funct_ptr ge b_shiftl\n                            = Some (External (EF_external _shiftl\n                                             (signature_of_type (Tcons tulong (Tcons tulong Tnil)) tulong cc_default))\n                                   (Tcons tulong (Tcons tulong Tnil)) tulong cc_default).\n    Local Opaque shiftl_spec.\n\n    Variable b_esr_sixty_four: block.\n    Hypothesis h_esr_sixty_four_s : Genv.find_symbol ge _esr_sixty_four = Some b_esr_sixty_four.\n    Hypothesis h_esr_sixty_four_p : Genv.find_funct_ptr ge b_esr_sixty_four\n                                    = Some (External (EF_external _esr_sixty_four\n                                                     (signature_of_type (Tcons tulong Tnil) tuint cc_default))\n                                           (Tcons tulong Tnil) tuint cc_default).\n    Local Opaque esr_sixty_four_spec.\n\n    Variable b_set_rec_regs: block.\n    Hypothesis h_set_rec_regs_s : Genv.find_symbol ge _set_rec_regs = Some b_set_rec_regs.\n    Hypothesis h_set_rec_regs_p : Genv.find_funct_ptr ge b_set_rec_regs\n                                  = Some (External (EF_external _set_rec_regs\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_rec_regs_spec.\n\n    Lemma emulate_mmio_read_body_correct:\n      forall m d d' env le esr rt rec_base rec_offset\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTesr: PTree.get _esr le = Some (Vlong esr))\n             (HPTrt: PTree.get _rt le = Some (Vint rt))\n             (HPTrec: PTree.get _rec le = Some (Vptr rec_base (Int.repr rec_offset)))\n             (Hspec: emulate_mmio_read_spec0 (VZ64 (Int64.unsigned esr)) (Int.unsigned rt) (rec_base, rec_offset) d = Some d'),\n           exists le', (exec_stmt ge env le ((m, d): mem) emulate_mmio_read_body E0 le' (m, d') Out_normal).\n    Proof.\n      solve_code_proof Hspec emulate_mmio_read_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RunAux/CodeProof/emulate_mmio_read.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.16262376581548288}}
{"text": "From Coq Require Import String Arith ZArith PropExtensionality Lia.\n\nFrom Vyper Require Import Config Calldag.\nFrom Vyper.L10 Require Import Base.\nFrom Vyper.L40 Require Import AST Descend Callset Descend Expr Stmt.\nFrom Vyper.L40Metered Require Import Interpret Expr.\n\nLemma small_stmt_metering_ok\n           {C: VyperConfig}\n           {bigger_call_depth_bound smaller_call_depth_bound: nat}\n           (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n           {cd: calldag}\n           (fc: fun_ctx cd bigger_call_depth_bound)\n           (do_call: forall\n                         (fc': fun_ctx cd smaller_call_depth_bound)\n                         (world: world_state)\n                         (arg_values: list uint256),\n                       world_state * expr_result uint256)\n           (do_call_metered: forall\n                               (decl: L40.AST.decl)\n                               (world: world_state)\n                               (arg_values: list uint256),\n                             world_state * option (expr_result uint256))\n           (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                             (world: world_state)\n                             (arg_values: list uint256),\n                        let '(world', result) := do_call fc' world arg_values in\n                          do_call_metered (fun_decl fc') world arg_values\n                           =\n                          (world', Some result))\n           (builtins: string -> option builtin)\n           (world: world_state)\n           (loc: memory)\n           (loops: list loop_ctx)\n           (ss: small_stmt)\n           (CallOk: let _ := string_set_impl in \n                      FSet.is_subset (small_stmt_callset ss)\n                                     (decl_callset (fun_decl fc))\n                      = true):\n  let '(world', result) := interpret_small_stmt Ebound fc do_call builtins\n                                                world loc loops ss CallOk\n   in interpret_small_stmt_metered (cd_decls cd) do_call_metered builtins\n                                   world loc loops ss\n       =\n      (world', Some result).\nProof.\ndestruct ss.\n{ (* abort *) easy. }\n{ (* return *)\n  cbn.\n  assert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                builtins world loc loops e\n                                (callset_descend_return eq_refl CallOk)).\n  destruct interpret_expr as (world', result).\n  rewrite M.\n  now destruct result.\n}\n{ (* raise *)\n  cbn.\n  assert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                builtins world loc loops e\n                                (callset_descend_raise eq_refl CallOk)).\n  destruct interpret_expr as (world', result).\n  rewrite M.\n  now destruct result.\n}\n{ (* assign *)\n  cbn.\n  assert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                builtins world loc loops rhs\n                                (callset_descend_assign_rhs eq_refl CallOk)).\n  destruct interpret_expr as (world', result).\n  rewrite M.\n  now destruct result.\n}\n(* ExprStmt *)\ncbn.\nassert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                              builtins world loc loops e\n                              (callset_descend_expr_stmt eq_refl CallOk)).\ndestruct interpret_expr as (world', result).\nrewrite M.\nnow destruct result.\nQed.\n\nLocal Lemma weak_block_metering_ok\n           {C: VyperConfig}\n           {bigger_call_depth_bound smaller_call_depth_bound: nat}\n           (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n           {cd: calldag}\n           (fc: fun_ctx cd bigger_call_depth_bound)\n           (do_call: forall\n                         (fc': fun_ctx cd smaller_call_depth_bound)\n                         (world: world_state)\n                         (arg_values: list uint256),\n                       world_state * expr_result uint256)\n           (do_call_metered: forall\n                               (decl: L40.AST.decl)\n                               (world: world_state)\n                               (arg_values: list uint256),\n                             world_state * option (expr_result uint256))\n           (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                             (world: world_state)\n                             (arg_values: list uint256),\n                        let '(world', result) := do_call fc' world arg_values in\n                          do_call_metered (fun_decl fc') world arg_values\n                           =\n                          (world', Some result))\n           (builtins: string -> option builtin)\n           (b: block)\n           (StmtOk: (* this condition is what makes this lemma weak,\n                       later we can prove a stronger lemma without this *)\n              match b with\n              | Block body =>\n                 List.Forall\n                   (fun s : stmt =>\n                    forall (CallOk : FSet.is_subset (stmt_callset s) (decl_callset (fun_decl fc)) = true) \n                      (world : world_state) (loc : memory) (loops : list loop_ctx),\n                    let '(world', result) := interpret_stmt Ebound fc do_call builtins\n                                                            world loc loops s CallOk\n                    in\n                     interpret_stmt_metered (cd_decls cd) do_call_metered builtins\n                                                           world loc loops s \n                      =\n                    (world', Some result))\n                   body\n              end)\n           (world: world_state)\n           (loc: memory)\n           (loops: list loop_ctx)\n           (CallOk: let _ := string_set_impl in \n                      FSet.is_subset (block_callset b)\n                                     (decl_callset (fun_decl fc))\n                      = true):\n  let '(world', result) := interpret_block Ebound fc do_call builtins\n                                           world loc loops b CallOk\n   in interpret_block_metered (cd_decls cd) do_call_metered builtins\n                              world loc loops b\n       =\n      (world', Some result).\nProof.\ndestruct b as [body]. cbn.\nremember (callset_descend_block eq_refl CallOk) as COk. clear HeqCOk CallOk.\nrevert world loc COk. induction body. { easy. }\nintros. cbn.\nassert (HeadOk := List.Forall_inv StmtOk (callset_descend_stmts_head eq_refl COk)\n                                  world loc loops).\ncbn in HeadOk.\nfold (interpret_stmt Ebound fc do_call builtins world loc loops a).\ndestruct interpret_stmt as ((world', loc'), result).\nrewrite HeadOk.\ndestruct result; trivial.\napply (IHbody (List.Forall_inv_tail StmtOk) world' loc'\n              (callset_descend_stmts_tail eq_refl COk)).\nQed.\n\nLemma stmt_metering_ok\n           {C: VyperConfig}\n           {bigger_call_depth_bound smaller_call_depth_bound: nat}\n           (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n           {cd: calldag}\n           (fc: fun_ctx cd bigger_call_depth_bound)\n           (do_call: forall\n                         (fc': fun_ctx cd smaller_call_depth_bound)\n                         (world: world_state)\n                         (arg_values: list uint256),\n                       world_state * expr_result uint256)\n           (do_call_metered: forall\n                               (decl: L40.AST.decl)\n                               (world: world_state)\n                               (arg_values: list uint256),\n                             world_state * option (expr_result uint256))\n           (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                             (world: world_state)\n                             (arg_values: list uint256),\n                        let '(world', result) := do_call fc' world arg_values in\n                          do_call_metered (fun_decl fc') world arg_values\n                           =\n                          (world', Some result))\n           (builtins: string -> option builtin)\n           (world: world_state)\n           (loc: memory)\n           (loops: list loop_ctx)\n           (s: stmt)\n           (CallOk: let _ := string_set_impl in \n                      FSet.is_subset (stmt_callset s)\n                                     (decl_callset (fun_decl fc))\n                      = true):\n  let '(world', result) := interpret_stmt Ebound fc do_call builtins\n                                                world loc loops s CallOk\n   in interpret_stmt_metered (cd_decls cd) do_call_metered builtins\n                                   world loc loops s\n       =\n      (world', Some result).\nProof.\nrevert world loc loops.\ninduction s using stmt_ind'; intros.\n{ (* small *)\n  apply small_stmt_metering_ok.\n  apply DoCallOk.\n}\n{ (* switch without default *)\n  cbn.\n  assert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                builtins world loc loops e\n                                (callset_descend_switch_expr eq_refl CallOk)).\n  destruct interpret_expr as (world', result).\n  rewrite M. clear M.\n  destruct result as [value|]. 2:reflexivity.\n  remember (callset_descend_cases eq_refl CallOk) as COk. clear HeqCOk CallOk.\n  cbn in COk. revert COk.\n  induction cases as [|h]. { easy. }\n  intro COk.\n  destruct h as [h_guard].\n  fold (interpret_block Ebound fc do_call builtins).\n  destruct (Z_of_uint256 value =? Z_of_uint256 h_guard)%Z.\n  { (* match found *)\n    assert (Hh := List.Forall_inv H). cbn in Hh.\n    apply (weak_block_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                         builtins body Hh world' loc loops\n                                         (callset_descend_cases_head eq_refl COk)).\n  }\n  (* no match *)\n  apply (IHcases (List.Forall_inv_tail H) (callset_descend_cases_tail eq_refl COk)).\n}\n{\n  (* switch with default *)\n  cbn.\n  assert (M := expr_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                builtins world loc loops e\n                                (callset_descend_switch_expr eq_refl CallOk)).\n  destruct interpret_expr as (world', result).\n  rewrite M. clear M.\n  destruct result as [value|]. 2:reflexivity.\n  remember (callset_descend_cases eq_refl CallOk) as COk. clear HeqCOk.\n  remember (callset_descend_cases_default eq_refl CallOk) as DOk. clear HeqDOk CallOk.\n  cbn in COk. revert COk.\n  induction cases as [|h].\n  {\n    intro Foo.\n    apply (weak_block_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                  builtins (Block default) H0 world' loc loops\n                                  DOk).\n  }\n  intro COk.\n  destruct h as [h_guard].\n  fold (interpret_block Ebound fc do_call builtins).\n  destruct (Z_of_uint256 value =? Z_of_uint256 h_guard)%Z.\n  { (* match found *)\n    assert (Hh := List.Forall_inv H). cbn in Hh.\n    apply (weak_block_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                         builtins body Hh world' loc loops\n                                         (callset_descend_cases_head eq_refl COk)).\n  }\n  (* no match *)\n  apply (IHcases (List.Forall_inv_tail H) (callset_descend_cases_tail eq_refl COk)).\n}\n(* loop *)\nremember (Block body) as loop_body.\ncbn. fold (interpret_block Ebound fc do_call builtins).\nsubst loop_body.\nremember (Z.to_nat (Z_of_uint256 count)) as n. clear Heqn.\nremember (OpenArray.get loc var) as offset. clear Heqoffset.\nrevert world loc.\ninduction n. { trivial. }\nintros.\nassert (W := let _ := memory_impl in\n             weak_block_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                                    builtins (Block body) H world loc\n                                    ({|\n                                       loop_offset := offset;\n                                       loop_count := count;\n                                       loop_countdown := n\n                                    |} :: loops)\n                                    (callset_descend_loop_body eq_refl CallOk)).\ndestruct interpret_block as ((world', loc'), result). rewrite W. clear W.\ndestruct result. 3:trivial.\n{ apply IHn. }\ndestruct a; trivial.\napply IHn.\nQed.\n\nLemma block_metering_ok\n           {C: VyperConfig}\n           {bigger_call_depth_bound smaller_call_depth_bound: nat}\n           (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n           {cd: calldag}\n           (fc: fun_ctx cd bigger_call_depth_bound)\n           (do_call: forall\n                         (fc': fun_ctx cd smaller_call_depth_bound)\n                         (world: world_state)\n                         (arg_values: list uint256),\n                       world_state * expr_result uint256)\n           (do_call_metered: forall\n                               (decl: L40.AST.decl)\n                               (world: world_state)\n                               (arg_values: list uint256),\n                             world_state * option (expr_result uint256))\n           (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                             (world: world_state)\n                             (arg_values: list uint256),\n                        let '(world', result) := do_call fc' world arg_values in\n                          do_call_metered (fun_decl fc') world arg_values\n                           =\n                          (world', Some result))\n           (builtins: string -> option builtin)\n           (world: world_state)\n           (loc: memory)\n           (loops: list loop_ctx)\n           (b: block)\n           (CallOk: let _ := string_set_impl in \n                      FSet.is_subset (block_callset b)\n                                     (decl_callset (fun_decl fc))\n                      = true):\n  let '(world_and_loc', result) := interpret_block Ebound fc do_call builtins\n                                           world loc loops b CallOk\n   in interpret_block_metered (cd_decls cd) do_call_metered builtins\n                              world loc loops b\n       =\n      (world_and_loc', Some result).\nProof.\nrefine (weak_block_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                               builtins b _ world loc loops CallOk).\nclear CallOk world loc loops.\ndestruct b as [body].\nrewrite List.Forall_forall.\nintros s H CallOk world loc loops. clear H.\napply (stmt_metering_ok Ebound fc do_call do_call_metered DoCallOk\n                        builtins world loc loops).\nQed.\n\n(****************************************************************************)\n(* DEPRECATED *)\nLemma small_stmt_respects_var_cap\n           {C: VyperConfig}\n           {bigger_call_depth_bound smaller_call_depth_bound: nat}\n           (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n           {cd: calldag}\n           (fc: fun_ctx cd bigger_call_depth_bound)\n           (do_call: forall\n                         (fc': fun_ctx cd smaller_call_depth_bound)\n                         (world: world_state)\n                         (arg_values: list uint256),\n                       world_state * expr_result uint256)\n           (do_call_metered: forall\n                               (decl: L40.AST.decl)\n                               (world: world_state)\n                               (arg_values: list uint256),\n                             world_state * option (expr_result uint256))\n           (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                             (world: world_state)\n                             (arg_values: list uint256),\n                        let '(world', result) := do_call fc' world arg_values in\n                          do_call_metered (fun_decl fc') world arg_values\n                           =\n                          (world', Some result))\n           (builtins: string -> option builtin)\n           (world: world_state)\n           (loc: memory)\n           (loops: list loop_ctx)\n           (ss: small_stmt)\n           (CallOk: let _ := string_set_impl in \n                      FSet.is_subset (small_stmt_callset ss)\n                                     (decl_callset (fun_decl fc))\n                      = true):\n  let '(world, loc', result) :=\n      interpret_small_stmt_metered (cd_decls cd) do_call_metered builtins\n                                   world loc loops ss\n  in forall k,\n       (var_cap_small_stmt ss <= k)%N\n        ->\n       let _ := memory_impl in\n       OpenArray.get loc k = OpenArray.get loc' k.\nProof.\nremember (interpret_small_stmt_metered (cd_decls cd) do_call_metered builtins world loc loops ss) as output.\ndestruct output as ((world', loc'), result).\nintros k L. cbn.\ndestruct ss; cbn in L; cbn in Heqoutput.\n{ (* abort *) inversion Heqoutput. now subst. }\n{ (* return *)\n  destruct interpret_expr_metered as (w, r).\n  destruct r as [r|]; [destruct r as [|r]|]; inversion Heqoutput; now subst.\n}\n{ (* raise *)\n  destruct interpret_expr_metered as (w, r).\n  destruct r as [r|]; [destruct r as [|r]|]; inversion Heqoutput; now subst.\n}\n{ (* assign *)\n  destruct interpret_expr_metered as (w, r).\n  destruct r as [r|]; [destruct r as [|r]|]; inversion Heqoutput; subst; try easy.\n  rewrite OpenArray.put_ok.\n  assert (B: (lhs <> k)%N) by lia.\n  apply N.eqb_neq in B. now rewrite B.\n}\n(* expr *)\ndestruct interpret_expr_metered as (w, r).\ndestruct r as [r|]; [destruct r as [|r]|]; inversion Heqoutput; now subst.\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/L40Metered/Stmt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1625545318605924}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule WorldGetters.\nSection WorldGetters.\n\n(* It's okay to have duplicating nodes in this list *)\n\n(* World is a dependent partial map of protocols *)\n\nDefinition context := union_map Label protocol.\n\n(* \nThe hooks are dependencies between:\n\n1. a hook's unique id\n2. a core protocol\n3. a client protocol\n4. a send-transition (represented by its tag) of a client protocol\n\n*)\nDefinition hook_domain := [ordType of ((nat * Label) * (Label * nat))%type].\n\n(*\n\nA hook is a constraint from the local state wrt. core protocol (1st\nheap argument), relating the local state wrt. the client protocol (2ns\nheap argument), message to be sent, and the destination node id.\n\n*)\nDefinition hook_type := heap -> heap -> seq nat -> nid -> Prop.\n\nDefinition hooks := union_map hook_domain hook_type.\nDefinition world := (context * hooks)%type.\n\nDefinition getc (w: world) : context := fst w.\nCoercion getc : world >-> context.\n\nDefinition geth (w: world) : hooks := snd w.\nCoercion geth : world >-> hooks.\n\nVariable w : world.\n\nVariables (p : protocol).\n\n(* The function is, in fact, partially defined and returns Empty\n   Protocol for a non-present label. *)\nDefinition getProtocol i : protocol:=\n  match find i (getc w) with\n  | Some p => p\n  | None => EmptyProt i \n  end.\n\nEnd WorldGetters.\nEnd WorldGetters.\n\nExport WorldGetters.\n\n(* Defining coherence of a state with respect to the world *)\n\nModule Worlds.\n\nModule Core.\nSection Core.\n\n(* The following definition ties together worlds and states *)\n\nDefinition hooks_consistent (c : context) (h : hooks) : Prop :=\n  forall z lc ls t, ((z, lc), (ls, t)) \\in dom h ->\n  (lc \\in dom c) && (ls \\in dom c).\n\nDefinition hook_complete w := hooks_consistent (getc w) (geth w).\n\nLemma hook_complete0 c : hook_complete (c, Unit).\nProof. by move=>????; rewrite dom0. Qed.\n\nDefinition Coh (w : world) : Pred state := fun s =>\n  let: c := fst w in\n  let: h := snd w in                                           \n  [/\\ valid w, valid s, hook_complete w,\n      dom c =i dom s &\n      forall l, coh (getProtocol w l) (getStatelet s l)].\n\nLemma cohW w s : Coh w s -> valid w.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohS w s : Coh w s -> valid s.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohH w s : Coh w s -> hook_complete w.\nProof. by case w=>[c h]; case. Qed.\n\nLemma cohD w s : Coh w s -> dom (getc w) =i dom s.\nProof. by case w=>[c h]; case. Qed.\n\nLemma coh_coh w s l : Coh w s -> coh (getProtocol w l) (getStatelet s l).\nProof. by case w=>[c h]; case. Qed.\n\n(* Now we need to establish a bunch of natural properties with respect\n   to coherence of worlds and states. *)\n\nLemma unit_coh w s :\n  Coh w s -> w = Unit <-> s = Unit.\nProof.\ncase: (w)=>[c h].\ncase=>V V' Hc E H; split.\ncase=>Z1 Z2; subst c h; rewrite dom0 in E; last by rewrite (dom0E V').\nmove=>Z; subst s; move/andP: V=>/=[V1 V2].\nhave Z: c = Unit by apply: (dom0E V1); move=>z; rewrite E dom0.\nsubst c; suff Z: (h = Unit) by subst h.\nsimpl in Hc; clear E H V1 V'.\napply: (dom0E V2); move=> x; case X: (x \\in dom h)=>//.\nby move: x X=>[[z lc] [ls t]]/Hc/andP[]; rewrite !dom0. \nQed.\n\nLemma Coh0 (w : world) (s : state) :\n  w = Unit -> s = Unit -> Coh w s.\nProof.\nmove=>->->{w s}; split; rewrite ?dom0=>//=; last first.\n- by move=>l; rewrite /getProtocol /getStatelet !find0E.\nby move=>z lc ls t; rewrite dom0.  \nQed.\n\nLemma CohUn (w1 w2 : world) (s1 s2 : state) :\n  Coh w1 s1 -> Coh w2 s2 ->\n  valid (w1 \\+ w2) -> Coh (w1 \\+ w2) (s1 \\+ s2).\nProof.\ncase: w1=>[c1 h1]; case: w2=>[c2 h2]; move=>C1 C2 V.\ncase: (C1)=>_ G1 K1 J1 H1; case: (C2)=>_ G2 K2 J2 H2.\ncase/andP: V=>V V'; simpl in V, V'.\nhave X: valid (s1 \\+ s2).\n- case: validUn=>//; [by rewrite G1|by rewrite G2|move=>l; rewrite -J1 -J2=>D1 D2].\n  by case: validUn V=>//=V1 V2; move/(_ _ D1); rewrite D2.\nhave Y: dom (c1 \\+ c2) =i dom (s1 \\+ s2).\n- by move=>z; rewrite !domUn !inE/=;rewrite V X/= J1 J2.\nhave Z1:  valid ((c1, h1) \\+ (c2, h2)) by rewrite /valid/= V V'.\nsplit=>//[|l]; last first.\n- rewrite /getProtocol /getStatelet.\n  case: (dom_find l (s1 \\+ s2))=>[|v]Z.\n  - by move/find_none: (Z); rewrite -Y; case: dom_find=>//->_; rewrite Z.\n  move/find_some: (Z)=>D; rewrite Z; rewrite -Y in D=> E.\n  case: dom_find D=>// p Z' _ _; rewrite Z'.\n  rewrite findUnL // in Z; rewrite findUnL // J1 in Z'.\n  by case: ifP Z Z'=>_ F1 F2; [move: (H1 l)|move: (H2 l)];\n     rewrite /getProtocol /getStatelet F1 F2.\nby move=>z lc ls t/=; rewrite domUn inE=>/andP[_]/orP[];[move/K1|move/K2];\n   move/andP=>[A1 A2]; rewrite !domUn !inE A1 A2 V -?(orbC true). \nQed.\n\n(* Coherence is trivially precise wrt. statelets *)\nLemma coh_prec w: precise (Coh w).\nProof.\nmove=>s1 s2 t1 t2 V C1 C2.\ncase: C1 => H1 G1 K1 D1 _.\ncase: C2 => H2 G2 K2 D2 _ H.\nby apply: (@dom_prec _ _ _  s1 s2 t1 t2)=>//z; rewrite -D1 -D2.\nQed.\n\nLemma locE i n k x y :\n  k \\in dom i -> valid i -> valid (dstate (getStatelet i k)) ->\n  getLocal n (getStatelet (upd k\n       {| dstate := upd n x (dstate (getStatelet i k));\n          dsoup := y |} i) k) = x.\nProof.\nmove=>D V; rewrite /getStatelet; case:dom_find (D) =>//d->_ _.\nby rewrite findU eqxx/= V /getLocal/= findU eqxx/==>->.\nQed.\n\nLemma locE' d n x y :\n  valid (dstate d) ->\n  getLocal n {| dstate := upd n x (dstate d);\n                dsoup := y |} = x.\nProof. by move=>V; rewrite /getLocal findU eqxx/= V. Qed.\n\nLemma locU n n' x st s :\n  n != n' ->\n  valid st ->\n  getLocal n {| dstate := upd n' x st; dsoup := s |} =\n  getLocal n {| dstate := st; dsoup := s |}.\nProof.\n  move=> /negbTE N V.\n  by rewrite /getLocal findU/= N.\nQed.\n\n\nSection MakeWorld.\n\nVariable p : protocol.\nNotation l := (plab p).\n\nDefinition mkWorld : world := (l \\\\-> p, Unit).\n\nLemma prEq : (getProtocol mkWorld l) = p.\nProof. by rewrite /getProtocol findPt. Qed.\n                          \n(*\n\nHere's an incomplete list of procedures and facts, which might be\nuseful eventually:\n\n- Define getters for particular transitions of worlds;\n\n *)\n\nEnd MakeWorld.\n\n(* TODO: try_recv should be restricted by a set of labels and a set of\n   protocols *)\nEnd Core.\nEnd Core.\n\nEnd Worlds.\n\nExport Worlds.Core.\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/Worlds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.1624624724428726}}
{"text": "Require 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 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 PromiseConsistent.\nRequire Import Cover.\nRequire Import MemorySplit.\nRequire Import MemoryMerge.\nRequire Import FulfillStep.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import MemoryProps.\nRequire Import LowerMemory.\nRequire Import FulfillStep.\nRequire Import ReorderStepPromise.\nRequire Import Pred.\nRequire Import Trace.\n\nRequire Import SeqLib.\n\nSet Implicit Arguments.\n\n\nVariant lower_step {lang} e (th0 th1: Thread.t lang): Prop :=\n| lower_step_intro\n    (STEP: Thread.program_step e th0 th1)\n    (NRELEASE: ~ release_event e)\n    (MEM: lower_memory th1.(Thread.memory) th0.(Thread.memory))\n    (SAME: is_na_write e -> th1.(Thread.memory) = th0.(Thread.memory))\n.\n\nLemma lower_step_step lang:\n  (@lower_step lang) <3= (@Thread.step lang true).\nProof.\n  i. inv PR. econs 2. ss.\nQed.\n\nLemma tau_lower_step_tau_step lang:\n  tau (@lower_step lang) <2= (@Thread.tau_step lang).\nProof.\n  apply tau_mon.\n  i. inv PR. econs. econs 2. ss.\nQed.\n\nDefinition is_lower_kind (kind: Memory.op_kind) (msg: Message.t): Prop :=\n  match kind with\n  | Memory.op_kind_lower msg' => msg = msg'\n  | _ => False\n  end.\n\nLemma write_lower_memory_lower\n      prom0 mem0 loc from to msg prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n      (LOWER: lower_memory mem1 mem0):\n  Memory.op_kind_is_lower kind.\nProof.\n  inv WRITE. inv PROMISE; eauto.\n  { eapply Memory.add_get0 in MEM. des.\n    hexploit lower_memory_get_inv; eauto. i. des; clarify. }\n  { eapply Memory.split_get0 in MEM. des.\n    hexploit lower_memory_get_inv; try apply GET1; eauto. i. des; clarify. }\n  { eapply Memory.remove_get0 in MEM. des.\n    hexploit lower_memory_get; eauto. i. des; clarify. }\nQed.\n\nLemma write_same_memory_same\n      prom0 mem0 loc from to msg prom1 mem1 kind\n      (WRITE: Memory.write prom0 mem0 loc from to msg prom1 mem1 kind)\n      (LOWER: mem1 = mem0):\n  is_lower_kind kind msg.\nProof.\n  inv WRITE. inv PROMISE; eauto.\n  { eapply Memory.add_get0 in MEM. des. clarify. }\n  { eapply Memory.split_get0 in MEM. des. clarify. }\n  { eapply Memory.lower_get0 in MEM. des. clarify. }\n  { eapply Memory.remove_get0 in MEM. des. clarify. }\nQed.\n\nLemma write_na_future\n      ts prom0 mem0 loc from to msg prom1 mem1 msgs kinds kind\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to msg prom1 mem1 msgs kinds kind):\n  Memory.future mem0 mem1.\nProof.\n  induction WRITE.\n  - inv WRITE. exploit Memory.promise_op; eauto. i.\n    econs 2; eauto. econs; eauto.\n    econs. apply Time.bot_spec.\n  - etrans; try exact IHWRITE.\n    inv WRITE_EX. exploit Memory.promise_op; eauto. i.\n    econs 2; eauto. econs; eauto.\n    + unguard. des; subst; ss. econs. ss.\n    + unguard. des; subst; ss. econs. apply Time.bot_spec.\nQed.\n\nLemma write_na_lower_memory_lower\n      ts prom0 mem0 loc from to msg prom1 mem1 msgs kinds kind\n      (WRITE: Memory.write_na ts prom0 mem0 loc from to msg prom1 mem1 msgs kinds kind)\n      (LOWER: mem1 = mem0)\n  :\n    (<<KINDS: List.Forall2 (fun kind '(_, _, msg) => is_lower_kind kind msg) kinds msgs>>) /\\\n    (<<KIND: is_lower_kind kind (Message.concrete msg None)>>)\n.\nProof.\n  induction WRITE.\n  { hexploit write_same_memory_same; eauto. }\n  exploit write_na_future; try exact WRITE. i.\n  inv WRITE_EX. inv PROMISE.\n  - exploit Memory.add_get0; try exact MEM. i. des.\n    exploit Memory.future_get1; try exact GET0; eauto.\n    { unguard. des; subst; ss. }\n    i. des. clarify.\n  - exploit Memory.split_get0; try exact MEM. i. des.\n    exploit Memory.future_get1; try exact GET1; eauto. i. des. clarify.\n  - cut (mem1 = mem').\n    { i. clarify. exploit IHWRITE; eauto. i. des. splits; auto.\n      econs; eauto. ss. eapply Memory.lower_get0 in MEM. des; clarify. }\n    eapply Memory.ext. i.\n    erewrite (@Memory.lower_o mem'); eauto. condtac; ss.\n    des. subst.\n    exploit Memory.lower_get0; try exact MEM. i. des.\n    exploit Memory.future_get1; try exact GET0; eauto. i. des. clarify.\n    rewrite GET1. f_equal. f_equal.\n    eapply Message.antisym; eauto.\n  - unguard. des; subst; ss.\nQed.\n\nLemma write_step_lower_memory_lower\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      (LOWER: lower_memory mem2 mem1):\n  Memory.op_kind_is_lower kind.\nProof.\n  inv STEP. eapply write_lower_memory_lower; eauto.\nQed.\n\nLemma write_step_lower_memory_lower_same\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      (LOWER: mem2 = mem1):\n  is_lower_kind kind (Message.concrete val released).\nProof.\n  inv STEP. eapply write_same_memory_same; eauto.\nQed.\n\nLemma write_na_step_lower_memory_lower\n      lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n      (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind)\n      (LOWER: mem2 = mem1):\n    (<<KINDS: List.Forall2 (fun kind '(_, _, msg) => is_lower_kind kind msg) kinds msgs>>) /\\\n    (<<KIND: is_lower_kind kind (Message.concrete val None)>>)\n.\nProof.\n  inv STEP. eapply write_na_lower_memory_lower; eauto.\nQed.\n\nLemma write_lower_lower_memory\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (KIND: Memory.op_kind_is_lower kind):\n  lower_memory mem2 mem1.\nProof.\n  inv WRITE. inv PROMISE; ss. econs. i.\n  erewrite (@Memory.lower_o mem2); eauto.\n  condtac; ss; try refl. des. subst.\n  exploit Memory.lower_get0; try exact MEM. i. des.\n  rewrite GET. econs. ss.\nQed.\n\nLemma write_lower_lower_memory_same\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (KIND: is_lower_kind kind msg):\n  mem2 = mem1.\nProof.\n  inv WRITE. inv PROMISE; ss. eapply Memory.ext. i.\n  erewrite (@Memory.lower_o mem2); eauto.\n  condtac; ss; try refl. des. subst.\n  exploit Memory.lower_get0; try exact MEM. i. des.\n  rewrite GET. econs.\nQed.\n\nLemma write_na_lower_lower_memory\n      ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n      (WRITE: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind)\n      (KINDS: List.Forall2 (fun kind '(_, _, msg) => is_lower_kind kind msg) kinds msgs)\n      (KIND: is_lower_kind kind (Message.concrete val None)):\n  mem2 = mem1.\nProof.\n  induction WRITE; eauto using write_lower_lower_memory.\n  { inv WRITE; ss. inv PROMISE; ss. clarify. eapply lower_same_same; eauto. }\n  inv KINDS. etrans; try eapply IHWRITE; eauto.\n  inv WRITE_EX; ss. inv PROMISE; ss. clarify. eapply lower_same_same; eauto.\nQed.\n\nLemma write_step_lower_lower_memory\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      (KIND: Memory.op_kind_is_lower kind):\n  lower_memory mem2 mem1.\nProof.\n  inv STEP. eapply write_lower_lower_memory; eauto.\nQed.\n\nLemma write_step_lower_lower_memory_same\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      (KIND: is_lower_kind kind (Message.concrete val released)):\n  mem2 = mem1.\nProof.\n  inv STEP. eapply write_lower_lower_memory_same; eauto.\nQed.\n\nLemma write_na_step_lower_lower_memory\n      lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n      (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind)\n      (KINDS: List.Forall2 (fun kind '(_, _, msg) => is_lower_kind kind msg) kinds msgs)\n      (KIND: is_lower_kind kind (Message.concrete val None)):\n  mem2 = mem1.\nProof.\n  inv STEP. eapply write_na_lower_lower_memory; eauto.\nQed.\n\n\nLemma lower_memory_promise_step\n      lang pf e\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      lc1' mem1'\n      (LC1: lower_local lc1' lc1)\n      (MEM1: lower_memory mem1' mem1)\n      (STEP: Thread.step pf e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2))\n      (PROMISE: is_promise e)\n      (WF1: Local.wf lc1' mem1'):\n  exists lc2' mem2',\n    (<<STEP: Thread.step pf e (Thread.mk lang st1 lc1' sc1 mem1') (Thread.mk lang st2 lc2' sc2 mem2')>>) /\\\n    (<<LC2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: lower_memory mem2' mem2>>).\nProof.\n  inv STEP; inv STEP0; [|inv LOCAL; ss].\n  exploit lower_memory_promise_step; try apply WF1; eauto. i. des.\n  esplits; eauto.\n  econs 1. econs; eauto.\nQed.\n\nLemma lower_memory_promise_steps\n      lang tr\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      lc1' mem1'\n      (LC1: lower_local lc1' lc1)\n      (MEM1: lower_memory mem1' mem1)\n      (STEP: Trace.steps tr (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2))\n      (PROMISE: List.Forall (fun x => is_promise (snd x)) tr)\n      (WF1: Local.wf lc1' mem1')\n      (SC1: Memory.closed_timemap sc1 mem1')\n      (CLOSED1: Memory.closed mem1'):\n  exists tr' lc2' mem2',\n    (<<STEP: Trace.steps tr' (Thread.mk lang st1 lc1' sc1 mem1') (Thread.mk lang st2 lc2' sc2 mem2')>>) /\\\n    (<<EVENTS: List.Forall2 (fun x y => snd x = snd y) tr tr'>>) /\\\n    (<<LC2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: lower_memory mem2' mem2>>).\nProof.\n  revert lc1' mem1' LC1 MEM1 WF1 SC1 CLOSED1.\n  dependent induction STEP; i.\n  { esplits; eauto. }\n  inv PROMISE. destruct th1. ss.\n  exploit lower_memory_promise_step; try exact STEP; eauto. i. des.\n  exploit Thread.step_future; try exact STEP1; eauto. s. i. des.\n  exploit IHSTEP; eauto. i. des.\n  esplits.\n  - econs 2; eauto.\n  - econs 2; eauto.\n  - ss.\n  - ss.\nQed.\n\nLemma lower_memory_lower_step\n      lang e\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      lc1' mem1'\n      (LC1: lower_local lc1' lc1)\n      (MEM1: lower_memory mem1' mem1)\n      (STEP: lower_step e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2))\n      (WF1: Local.wf lc1 mem1)\n      (WF1': Local.wf lc1' mem1')\n      (CLOSED: Memory.closed mem1)\n      (CLOSED1': Memory.closed mem1'):\n  exists e' lc2' mem2',\n    (<<STEP: lower_step e' (Thread.mk lang st1 lc1' sc1 mem1') (Thread.mk lang st2 lc2' sc2 mem2')>>) /\\\n    (<<EVENT: lower_event e' e>>) /\\\n    (<<LC2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: lower_memory mem2' mem2>>).\nProof.\n  inv STEP. inv STEP0. inv LOCAL; ss.\n  { esplits.\n    - econs; [econs; try econs 1|..]; eauto; ss. refl.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_read_step; try exact MEM1; eauto. i. des.\n    esplits.\n    - econs; [econs; try econs 2|..]; eauto; ss. refl.\n    - econs. ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_write_step; try exact MEM1; eauto; try refl. i. des.\n    replace sc_src1 with sc2 in *; cycle 1.\n    { inv LOCAL0. inv STEP. ss. }\n    esplits.\n    - econs; [econs; try econs 3|..]; eauto; ss.\n      { exploit write_step_lower_memory_lower; try exact LOCAL0; eauto. i.\n        inv KIND; ss.\n        eapply write_step_lower_lower_memory; eauto.\n      }\n      { i. subst.\n        i. exploit write_step_lower_memory_lower_same; try exact LOCAL0; eauto. i.\n        destruct kind; ss. subst.\n        eapply write_step_lower_lower_memory_same; eauto. ss.\n        inv LOCAL0; inv STEP. destruct ord; ss.\n      }\n    - econs. ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_read_step; try exact MEM1; eauto; try refl. i. des.\n    exploit Local.read_step_future; try exact LOCAL1; eauto. i. des.\n    exploit Local.read_step_future; try exact STEP; eauto. i. des.\n    exploit lower_memory_write_step; try exact MEM1; eauto; try refl. i. des.\n    replace sc_src1 with sc2 in *; cycle 1.\n    { inv LOCAL2. inv STEP0. ss. }\n    esplits.\n    - econs; [econs; try econs 4|..]; eauto; ss.\n      exploit write_step_lower_memory_lower; try exact LOCAL2; eauto. i.\n      inv KIND; ss.\n      eapply write_step_lower_lower_memory; eauto.\n    - econs; ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_fence_step; try exact LC1; eauto; try refl. i. des.\n    replace sc_src1 with sc2 in *; cycle 1.\n    { inv LOCAL0. inv STEP.\n      unfold TView.write_fence_sc. condtac; ss. destruct ordw; ss.\n    }\n    esplits.\n    - econs; [econs; try econs 5|..]; eauto; ss. refl.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_write_na_step; try exact MEM1; eauto; try refl. i. des.\n    replace sc_src1 with sc2 in *; cycle 1.\n    { inv LOCAL0. inv STEP. ss. }\n    esplits.\n    - assert (mem_src1 = mem1').\n      { exploit write_na_step_lower_memory_lower; try exact LOCAL0; eauto. i. des.\n        eapply write_na_step_lower_lower_memory; eauto.\n        { clear - KINDS KINDS0.\n          induction KINDS; ss.\n        }\n        { subst. auto. }\n      }\n      econs; [econs; try econs 8|..]; eauto; ss. subst. refl.\n    - econs; ss.\n    - ss.\n    - ss.\n  }\n\n  { exploit lower_memory_is_racy; try exact MEM1; try eapply LOCAL0; eauto. i.\n    esplits.\n    - econs; [econs; try econs 9|..]; eauto; ss. refl.\n    - ss.\n    - ss.\n    - ss.\n  }\nQed.\n\nLemma lower_memory_lower_steps\n      lang\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      lc1' mem1'\n      (LC1: lower_local lc1' lc1)\n      (MEM1: lower_memory mem1' mem1)\n      (STEP: rtc (tau lower_step) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2))\n      (WF1: Local.wf lc1 mem1)\n      (WF1': Local.wf lc1' mem1')\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (SC1': Memory.closed_timemap sc1 mem1')\n      (CLOSED: Memory.closed mem1)\n      (CLOSED1': Memory.closed mem1'):\n  exists lc2' mem2',\n    (<<STEP: rtc (tau lower_step) (Thread.mk lang st1 lc1' sc1 mem1') (Thread.mk lang st2 lc2' sc2 mem2')>>) /\\\n    (<<LC2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: lower_memory mem2' mem2>>).\nProof.\n  revert lc1' mem1' LC1 MEM1 WF1' SC1' CLOSED1'.\n  dependent induction STEP; i.\n  { esplits; eauto. }\n  inv H. destruct y.\n  exploit lower_memory_lower_step; try exact TSTEP; eauto. i. des.\n  exploit Thread.step_future; try eapply lower_step_step; try exact TSTEP; eauto. s. i. des.\n  exploit Thread.step_future; try eapply lower_step_step; try exact STEP0; eauto. s. i. des.\n  exploit IHSTEP; eauto. i. des.\n  esplits.\n  - econs 2; eauto. econs; eauto. inv EVENT0; ss.\n  - ss.\n  - ss.\nQed.\n\nLemma same_memory_promise_step\n      lang pf pf' e\n      (th1 th2 th1' th2': Thread.t lang)\n      (STEP: Thread.step pf e th1 th2)\n      (STEP': Thread.step pf' e th1' th2')\n      (PROMISE: is_promise e)\n      (MEM: th1.(Thread.memory) = th1'.(Thread.memory)):\n  th2.(Thread.memory) = th2'.(Thread.memory).\nProof.\n  inv STEP; inv STEP0; try by inv LOCAL; ss.\n  inv STEP'; inv STEP; try by inv LOCAL0; ss.\n  inv LOCAL. inv LOCAL0. ss. subst.\n  exploit Memory.promise_op; try exact PROMISE0. i.\n  exploit Memory.promise_op; try exact PROMISE1. i.\n  eapply Memory.op_inj; eauto.\nQed.\n\nLemma same_memory_promise_steps\n      lang tr tr'\n      (th1 th2 th1' th2': Thread.t lang)\n      (STEP: Trace.steps tr th1 th2)\n      (STEP': Trace.steps tr' th1' th2')\n      (PROMISE: List.Forall (fun x => is_promise (snd x)) tr)\n      (TRACE: List.Forall2 (fun x y => snd x = snd y) tr tr')\n      (MEM: th1.(Thread.memory) = th1'.(Thread.memory)):\n  th2.(Thread.memory) = th2'.(Thread.memory).\nProof.\n  revert tr' th1' th2' STEP' TRACE MEM.\n  induction STEP; i.\n  { inv TRACE. inv STEP'; ss. }\n  subst. inv PROMISE. inv TRACE. inv STEP'. inv TR. ss. subst.\n  exploit same_memory_promise_step; try exact MEM; eauto.\nQed.\n\nLemma promise_steps_trace_promise_steps\n      lang (th1 th2: Thread.t lang)\n      (STEPS: rtc (tau (@pred_step is_promise _)) th1 th2):\n  exists tr,\n    (<<STEPS: Trace.steps tr th1 th2>>) /\\\n    (<<PROMISE: List.Forall (fun x => is_promise (snd x)) tr>>).\nProof.\n  induction STEPS; eauto.\n  des. inv H. inv TSTEP. inv STEP.\n  esplits; eauto.\nQed.\n\nLemma trace_promise_steps_promise_steps\n      lang tr (th1 th2: Thread.t lang)\n      (STEPS: Trace.steps tr th1 th2)\n      (PROMISE: List.Forall (fun x => is_promise (snd x)) tr):\n  rtc (tau (@pred_step is_promise _)) th1 th2.\nProof.\n  induction STEPS; eauto.\n  inv PROMISE; ss. inv H1.\n  exploit IHSTEPS; eauto. intros x.\n  etrans; try exact x.\n  econs 2; try refl. econs.\n  - econs; eauto. econs; eauto.\n  - destruct e; ss.\nQed.\n\nLemma trace_eq_promise\n      (tr1 tr2: Trace.t)\n      (EQ: List.Forall2 (fun x y => snd x = snd y) tr1 tr2)\n      (PROMISE1: List.Forall (fun x => is_promise (snd x)) tr1):\n  List.Forall (fun x => is_promise (snd x)) tr2.\nProof.\n  induction EQ; eauto.\n  inv PROMISE1. econs; eauto. congr.\nQed.\n\nLemma promise_step_sc\n      lang pf e (th1 th2: Thread.t lang)\n      (STEP: Thread.step pf e th1 th2)\n      (PROMISE: is_promise e):\n  th1.(Thread.sc) = th2.(Thread.sc).\nProof.\n  inv STEP; inv STEP0; inv LOCAL; ss.\nQed.\n\nLemma promise_steps_sc\n      lang tr (th1 th2: Thread.t lang)\n      (STEPS: Trace.steps tr th1 th2)\n      (PROMISE: List.Forall (fun x => is_promise (snd x)) tr):\n  th1.(Thread.sc) = th2.(Thread.sc).\nProof.\n  induction STEPS; eauto. subst.\n  inv PROMISE. ss.\n  exploit promise_step_sc; try exact STEP; eauto. i.\n  rewrite x0. eauto.\nQed.\n\nLemma write_lower_promises_le\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (LOWER: lower_memory mem2 mem1):\n  Memory.le promises2 promises1.\nProof.\n  exploit write_lower_memory_lower; eauto. i.\n  inv WRITE. inv PROMISE; ss.\n  ii. revert LHS.\n  erewrite Memory.remove_o; eauto. condtac; ss.\n  erewrite Memory.lower_o; eauto. condtac; ss.\nQed.\n\nLemma write_na_lower_promises_le\n      ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind\n      (WRITE: Memory.write_na ts promises1 mem1 loc from to msg promises2 mem2 msgs kinds kind)\n      (LOWER: mem2 = mem1):\n  Memory.le promises2 promises1.\nProof.\n  exploit write_na_lower_memory_lower; eauto. i. des.\n  clear LOWER. induction WRITE.\n  { inv WRITE. inv PROMISE; ss.\n    ii. revert LHS.\n    erewrite Memory.remove_o; eauto. condtac; ss.\n    erewrite Memory.lower_o; eauto. condtac; ss.\n  }\n  inv KINDS. hexploit IHWRITE; eauto. i.\n  etrans; eauto.\n  inv WRITE_EX. inv PROMISE; ss.\n  ii. revert LHS.\n  erewrite Memory.remove_o; eauto. condtac; ss.\n  erewrite Memory.lower_o; eauto. condtac; ss.\nQed.\n\nLemma lower_step_future\n      lang e (th1 th2: Thread.t lang)\n      (STEP: lower_step e th1 th2):\n  (<<PROMISES: Memory.le th2.(Thread.local).(Local.promises) th1.(Thread.local).(Local.promises)>>) /\\\n  (<<SC: th1.(Thread.sc) = th2.(Thread.sc)>>) /\\\n  (<<MEM: lower_memory th2.(Thread.memory) th1.(Thread.memory)>>).\nProof.\n  inv STEP. splits; ss.\n  { inv STEP0. inv LOCAL; ss; try by inv LOCAL0; ss.\n    - inv LOCAL0. ss.\n      eapply write_lower_promises_le; eauto.\n    - inv LOCAL1. inv LOCAL2. ss.\n      eapply write_lower_promises_le; eauto.\n    - inv LOCAL0. ss.\n      eapply write_na_lower_promises_le; eauto.\n  }\n  { inv STEP0. inv LOCAL; ss.\n    - inv LOCAL0. ss.\n    - inv LOCAL2. ss.\n    - inv LOCAL0.\n      unfold TView.write_fence_sc. condtac; ss.\n      destruct ordw; ss.\n    - inv LOCAL0. ss.\n  }\nQed.\n\nLemma lower_steps_future\n      lang (th1 th2: Thread.t lang)\n      (STEPS: rtc (tau lower_step) th1 th2):\n  (<<PROMISES: Memory.le th2.(Thread.local).(Local.promises) th1.(Thread.local).(Local.promises)>>) /\\\n  (<<SC: th1.(Thread.sc) = th2.(Thread.sc)>>) /\\\n  (<<MEM: lower_memory th2.(Thread.memory) th1.(Thread.memory)>>).\nProof.\n  induction STEPS; eauto.\n  { splits; ss. refl. }\n  inv H. exploit lower_step_future; try exact TSTEP; eauto. i. des.\n  splits; try congr; etrans; eauto.\nQed.\n\n\nLemma step_split_pure\n      lang pf e (th1 th2: Thread.t lang)\n      (STEP: Thread.step pf e th1 th2)\n      (NPROMISE: no_promise e)\n      (NRELEASE: ~ release_event e)\n      (MEM: th2.(Thread.memory) = th1.(Thread.memory))\n  :\n    (<<LOWER: tau lower_step th1 th2>>) /\\\n    (<<SC: th2.(Thread.sc) = th1.(Thread.sc)>>).\nProof.\n  assert (SC: th2.(Thread.sc) = th1.(Thread.sc)).\n  { inv STEP; inv STEP0; auto. inv LOCAL; ss.\n    { inv LOCAL0; ss. }\n    { inv LOCAL1; inv LOCAL2; ss. }\n    { inv LOCAL0; ss.\n      unfold TView.write_fence_sc.\n      destruct (Ordering.le Ordering.seqcst ordw) eqn:ORD; ss.\n      exfalso. eapply NRELEASE. destruct ordw; ss.\n    }\n    { inv LOCAL0; ss. }\n  }\n  esplits; eauto. econs.\n  { inv STEP; [inv STEP0; ss|]. econs; eauto. rewrite MEM. refl. }\n  { destruct e; ss. }\nQed.\n\nLemma memory_op_diff_only\n      mem0 loc from to msg mem1 kind\n      (WRITE: Memory.op mem0 loc from to msg mem1 kind)\n      loc' to' from' msg'\n      (SOME: Memory.get loc' to' mem1 = Some (from', msg'))\n  :\n    (exists from'' msg'',\n        (<<GET: Memory.get loc' to' mem0 = Some (from'', msg'')>>) /\\\n        (<<MSG: Message.le msg' msg''>>)) \\/\n    ((<<LOC: loc' = loc>>) /\\\n     (<<TO: to' = to>>) /\\\n     (<<FROM: from' = from>>) /\\\n     (<<MSG: msg' = msg>>) /\\\n     (<<NONE: Memory.get loc' to' mem0 = None>>)).\nProof.\n  inv WRITE.\n  { erewrite Memory.add_o in SOME; eauto. des_ifs.\n    { right. ss. des; clarify. splits; auto.\n      eapply Memory.add_get0; eauto. }\n    { left. esplits; eauto. refl. }\n  }\n  { erewrite Memory.split_o in SOME; eauto. des_ifs.\n    { right. ss. des; clarify. splits; auto.\n      eapply Memory.split_get0 in SPLIT. des; auto. }\n    { left. ss. des; clarify. eapply Memory.split_get0 in SPLIT.\n      des; clarify. esplits; eauto. refl. }\n    { left. esplits; eauto. refl. }\n  }\n  { erewrite Memory.lower_o in SOME; eauto. des_ifs.\n    { ss. des; clarify. left. eapply lower_succeed_wf in LOWER; eauto.\n      des; eauto. }\n    { left. esplits; eauto. refl. }\n  }\n  { erewrite Memory.remove_o in SOME; eauto. des_ifs.\n    left. esplits; eauto. refl. }\nQed.\n\nLemma promise_step_tau_promise_step\n      lang pf e (th0 th1: Thread.t lang)\n      (STEP: Thread.promise_step pf e th0 th1)\n  :\n    tau (@pred_step is_promise _) th0 th1.\nProof.\n  econs; eauto.\n  { econs; eauto.\n    { econs; eauto. econs 1; eauto. }\n    { inv STEP; ss. }\n  }\n  { inv STEP; ss. }\nQed.\n\nLemma lower_step_tau_lower_step\n      lang e (th0 th1: Thread.t lang)\n      (STEP: lower_step e th0 th1)\n  :\n    tau lower_step th0 th1.\nProof.\n  inv STEP. econs; eauto.\n  { econs; eauto. }\n  { destruct e; ss. }\nQed.\n\nLemma memory_lower_exists\n      prom0 mem0 loc from to msg\n      (CLOSED: Memory.closed mem0)\n      (MLE: Memory.le prom0 mem0)\n      (MSG: msg <> Message.reserve)\n      (GET: Memory.get loc to prom0 = Some (from, msg))\n      (BOT: Memory.bot_none prom0)\n  :\n    Memory.promise prom0 mem0 loc from to msg prom0 mem0 (Memory.op_kind_lower msg).\nProof.\n  inv CLOSED. exploit CLOSED0.\n  { eapply MLE. eauto. }\n  i. des.\n  hexploit Memory.lower_exists; try eassumption.\n  { hexploit memory_get_ts_strong; eauto. i. des; clarify.\n    rewrite BOT in GET. ss. }\n  { refl. }\n  i. des. hexploit Memory.lower_exists_le; eauto. i. des.\n  hexploit lower_same_same; try apply H. i. subst.\n  hexploit lower_same_same; try apply H0. i. subst.\n  econs; eauto.\nQed.\n\nLemma split_memory_write\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      (MESSAGE: msg <> Message.reserve)\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind):\n  exists promises1',\n    (<<PROMISE: Memory.promise promises1 mem1 loc from to msg promises1' mem2 kind>>) /\\\n    (<<WRITE_LOWER: Memory.write promises1' mem2 loc from to msg promises2 mem2 (Memory.op_kind_lower msg)>>).\nProof.\n  exploit MemoryFacts.write_time_lt; eauto. i.\n  assert (MSG: Message.wf msg).\n  { inv WRITE. inv PROMISE; inv MEM; ss.\n    - inv ADD. ss.\n    - inv SPLIT. ss.\n    - inv LOWER. ss.\n  }\n  assert (MSG_TO: Memory.message_to msg loc to).\n  { inv WRITE. inv PROMISE; ss. }\n  inv WRITE. esplits; eauto.\n  exploit Memory.promise_get0; eauto.\n  { inv PROMISE; ss. }\n  i. des.\n  exploit Memory.lower_exists_same; try exact GET_PROMISES; eauto. i.\n  exploit Memory.lower_exists_same; try exact GET_MEM; eauto.\nQed.\n\nLemma split_write\n      lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      (REL_WF: View.opt_wf releasedm)\n      (REL_CLOSED: Memory.closed_opt_view releasedm mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (ORD: Ordering.le ord Ordering.relaxed)\n      (STEP: Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n  exists released' lc1,\n    (<<RELEASED: released' = TView.write_released (Local.tview lc0) sc0 loc to releasedm ord>>) /\\\n    (<<PROMISE: Local.promise_step lc0 mem0 loc from to\n                                   (Message.concrete val released') lc1 mem2 kind>>) /\\\n    (<<WRITE: Local.write_step lc1 sc0 mem2 loc from to val releasedm released ord lc2 sc2 mem2\n                               (Memory.op_kind_lower (Message.concrete val released'))>>).\nProof.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit fulfill_write; try exact STEP2; eauto.\n  subst. inv STEP1. ss.\nQed.\n\nLemma reorder_write_lower_rtc_promise\n      lang\n      promises1 mem1\n      loc from to msg kind\n      th2 th3\n      (LE: Memory.le promises1 mem1)\n      (KIND: Memory.op_kind_is_lower kind)\n      (WRITE: Memory.write promises1 mem1 loc from to msg\n                           th2.(Thread.local).(Local.promises) th2.(Thread.memory) kind)\n      (STEPS: rtc (tau (@pred_step is_promise lang)) th2 th3):\n  exists th2',\n    (<<STEPS: rtc (tau (@pred_step is_promise lang))\n                  (Thread.mk _ th2.(Thread.state)\n                             (Local.mk th2.(Thread.local).(Local.tview) promises1)\n                             th2.(Thread.sc) mem1)\n                  th2'>>) /\\\n    (<<WRITE: Memory.write th2'.(Thread.local).(Local.promises) th2'.(Thread.memory)\n                           loc from to msg\n                           th3.(Thread.local).(Local.promises) th3.(Thread.memory) kind>>) /\\\n    (<<STATE: th2'.(Thread.state) = th3.(Thread.state)>>) /\\\n    (<<TVIEW: th2'.(Thread.local).(Local.tview) = th3.(Thread.local).(Local.tview)>>) /\\\n    (<<SC: th2'.(Thread.sc) = th3.(Thread.sc)>>).\nProof.\n  revert promises1 mem1 LE WRITE.\n  induction STEPS; i.\n  { esplits; try refl. ss. }\n  inv H. inv TSTEP. inv STEP. inv STEP0; inv STEP; inv LOCAL; ss.\n  exploit reorder_memory_write_lower_promise; try exact WRITE; eauto. i. des.\n  hexploit Memory.promise_le; try exact PROMISE0; eauto. i. des.\n  exploit IHSTEPS; eauto. i. des.\n  esplits; try exact WRITE1; eauto.\n  econs 2; eauto. econs.\n  - econs; [do 4 econs; eauto|]; ss.\n    inv WRITE0. inv PROMISE1; ss.\n    eapply lower_closed_message_inv; eauto.\n  - ss.\nQed.\n\nLemma memory_write_lower_refl_inv\n      promsies1 mem1 loc from to msg promises2 mem2\n      (WRITE: Memory.write promsies1 mem1 loc from to msg promises2 mem2 (Memory.op_kind_lower msg)):\n  mem1 = mem2.\nProof.\n  inv WRITE. inv PROMISE; ss.\n  apply Memory.ext. i.\n  exploit Memory.lower_get0; try exact MEM. i. des.\n  erewrite (@Memory.lower_o mem2); eauto. condtac; ss.\n  des. subst. ss.\nQed.\n\nLemma promise_remove_messages\n      promises0 mem0 loc from to msg promises1 mem1 kind\n      promises2\n      (PROMISE: Memory.promise promises0 mem0 loc from to msg promises1 mem1 kind)\n      (REMOVE: Memory.remove promises1 loc from to msg promises2):\n  Messages.of_memory promises1 <4=\n  (Messages.of_memory promises2 \\4/ committed mem0 promises0 mem1 promises2).\nProof.\n  s. i. inv PR. revert GET. inv PROMISE; ss.\n  { erewrite Memory.add_o; eauto. condtac; ss.\n    - i. des. symmetry in GET. inv GET. right.\n      exploit Memory.remove_get0; eauto. i. des.\n      exploit Memory.add_get0; try exact MEM. i. des.\n      econs; [econs; eauto|]. ii. inv H. congr.\n    - i. left. econs.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      erewrite Memory.add_o; eauto. condtac; ss.\n  }\n  { erewrite Memory.split_o; eauto. repeat (condtac; ss).\n    - i. des. symmetry in GET. inv GET. right.\n      exploit Memory.remove_get0; eauto. i. des.\n      exploit Memory.split_get0; try exact MEM. i. des.\n      econs; [econs; eauto|]. ii. inv H. congr.\n    - guardH o. i. des. symmetry in GET. inv GET. left. econs.\n      exploit Memory.split_get0; try exact PROMISES. i. des.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n    - i. left. econs.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      erewrite Memory.split_o; eauto. repeat (condtac; ss).\n  }\n  { erewrite Memory.lower_o; eauto. condtac; ss.\n    - i. des. symmetry in GET. inv GET. right.\n      exploit Memory.remove_get0; eauto. i. des.\n      exploit Memory.lower_get0; try exact MEM. i. des.\n      exploit Memory.lower_get0; try exact PROMISES. i. des.\n      econs; [econs; eauto|]. ii. inv H. congr.\n    - i. left. econs.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      erewrite Memory.lower_o; eauto. condtac; ss.\n  }\n  { exploit Memory.remove_get0; try exact REMOVE. i. des.\n    exploit Memory.remove_get0; try exact PROMISES. i. des.\n    congr.\n  }\nQed.\n\nLemma lower_remove_remove\n      mem1 loc from to msg1 msg2 mem2 mem3\n      (LOWER: Memory.lower mem1 loc from to msg1 msg2 mem2)\n      (REMOVE: Memory.remove mem2 loc from to msg2 mem3):\n  Memory.remove mem1 loc from to msg1 mem3.\nProof.\n  exploit Memory.lower_get0; eauto. i. des.\n  exploit Memory.remove_exists; try exact GET. i. des.\n  replace mem0 with mem3 in *; ss.\n  apply Memory.ext. i.\n  erewrite Memory.remove_o; eauto.\n  erewrite Memory.lower_o; eauto.\n  erewrite (@Memory.remove_o mem0); eauto.\n  condtac; ss.\nQed.\n\nLemma write_lower_promises\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      l t\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (KIND: Memory.op_kind_is_lower kind):\n  Memory.get l t promises2 =\n  if loc_ts_eq_dec (l, t) (loc, to)\n  then None\n  else Memory.get l t promises1.\nProof.\n  inv WRITE. inv PROMISE; ss.\n  erewrite Memory.remove_o; eauto. condtac; ss.\n  erewrite Memory.lower_o; eauto. condtac; ss.\nQed.\n\nLemma split_step\n      lang pf e (th0 th2: Thread.t lang)\n      (STEP: Thread.step pf e th0 th2)\n      (NRELEASE: ~ release_event e)\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n      (CLOSED: Memory.closed (Thread.memory th0)):\n  exists th1,\n    (<<PROMISES: rtc (tau (@pred_step is_promise _)) th0 th1>>) /\\\n    (<<LOWER: rtc (tau lower_step) th1 th2>>) /\\\n    (<<STATE: th0.(Thread.state) = th1.(Thread.state)>>) /\\\n    (<<MEM: th1.(Thread.memory) = th2.(Thread.memory)>>) /\\\n    (<<SC: th1.(Thread.sc) = th2.(Thread.sc)>>) /\\\n    (<<FIN: Messages.of_memory th1.(Thread.local).(Local.promises) <4=\n            (Messages.of_memory th2.(Thread.local).(Local.promises) \\4/\n             committed th0.(Thread.memory) th0.(Thread.local).(Local.promises)\n                       th2.(Thread.memory) th2.(Thread.local).(Local.promises))>>).\nProof.\n  dup STEP. inv STEP.\n  { (* promise *)\n    exists th2. inv STEP1. ss. splits; eauto.\n    econs; eauto. econs.\n    - econs; [econs|]; eauto. ss.\n    - ss.\n  }\n\n  inv STEP1. inv LOCAL0; ss.\n  { (* silent *)\n    exploit step_split_pure; eauto; ss. i. des. esplits; eauto.\n  }\n  { (* read *)\n    exploit step_split_pure; eauto; ss. i. des. esplits; eauto.\n    s. i. inv LOCAL1. eauto.\n  }\n\n  { (* write *)\n    exploit split_write; try exact LOCAL1; eauto.\n    { destruct ord; ss. }\n    i. des.\n    esplits.\n    - econs 2; eauto. eapply promise_step_tau_promise_step. econs; eauto.\n    - econs 2; eauto. eapply lower_step_tau_lower_step.\n      econs; [econs; eauto|..]; eauto. refl.\n    - ss.\n    - ss.\n    - inv WRITE. ss.\n    - clear STEP0 WRITE.\n      inv PROMISE. inv LOCAL1. inv WRITE. destruct lc1. ss.\n      exploit Memory.promise_inj; [exact PROMISE|exact PROMISE0|]. i. des. subst.\n      eapply promise_remove_messages; eauto.\n  }\n\n  { (* update *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit split_write; try exact LOCAL2; eauto.\n    { destruct ordw; ss. }\n    i. des.\n    exploit reorder_read_promise_diff; try exact LOCAL1; eauto.\n    { inv WRITE. exploit MemoryFacts.write_time_lt; eauto. i.\n      ii. inv H. timetac.\n    }\n    i. des.\n    esplits.\n    - econs 2; eauto. eapply promise_step_tau_promise_step. econs; eauto.\n    - econs 2; eauto. eapply lower_step_tau_lower_step.\n      econs; [econs; eauto|..]; eauto. refl.\n    - ss.\n    - ss.\n    - inv WRITE. ss.\n    - clear STEP0 WRITE PROMISE STEP2.\n      inv STEP1. inv LOCAL1. inv LOCAL2. inv WRITE. destruct lc1. ss.\n      exploit Memory.promise_inj; [exact PROMISE|exact PROMISE0|]. i. des. subst.\n      eapply promise_remove_messages; eauto.\n  }\n\n  { (* fence *)\n    exploit step_split_pure; eauto; ss. i. des. esplits; eauto.\n    s. i. inv LOCAL1. eauto.\n  }\n\n  { (* na write *)\n    clear STEP0. inv LOCAL1. ss.\n    cut (exists th1 kinds' kind',\n            rtc (tau (@pred_step is_promise _)) (Thread.mk _ st1 lc1 sc1 mem1) th1 /\\\n            Memory.write_na\n              (View.rlx (TView.cur (Local.tview lc1)) loc)\n              th1.(Thread.local).(Local.promises) th1.(Thread.memory)\n              loc from to val promises2 mem2 msgs kinds' kind' /\\\n            th1.(Thread.state) = st1 /\\\n            th1.(Thread.local).(Local.tview) = lc1.(Local.tview) /\\\n            th1.(Thread.memory) = mem2 /\\\n            th1.(Thread.sc) = sc1 /\\\n            Messages.of_memory th1.(Thread.local).(Local.promises) <4=\n            (Messages.of_memory promises2 \\4/\n            committed mem1 lc1.(Local.promises) mem2 promises2)).\n    { i. des.\n      destruct th1. ss. subst. rewrite <- H2 in *.\n      esplits; eauto. econs 2; eauto. econs.\n      - econs.\n        + econs; cycle 1.\n          * econs 8. econs; eauto.\n          * ss.\n        + ss.\n        + refl.\n        + ss.\n      - ss.\n    }\n\n    destruct lc1. ss.\n    remember (View.rlx (TView.cur tview) loc) as ts eqn:TS.\n    assert (LE: Time.le (View.rlx (TView.cur tview) loc) ts) by (subst; refl).\n    clear TS.\n    induction WRITE.\n    { inv WRITE. esplits.\n      - econs 2; eauto. eapply promise_step_tau_promise_step. econs; eauto.\n      - s. hexploit Memory.promise_get0; try exact PROMISE.\n        { inv PROMISE; ss. }\n        i. des.\n        hexploit Memory.get_ts; try exact GET_MEM. i. des.\n        { subst. inv WRITABLE. }\n        hexploit Memory.lower_exists_same; try exact GET_PROMISES; eauto. i.\n        hexploit Memory.lower_exists_same; try exact GET_MEM; eauto. i.\n        econs 1.\n        + ss.\n        + econs; eauto. econs 3; eauto; ss.\n          econs. apply Time.bot_spec.\n      - refl.\n      - refl.\n      - refl.\n      - refl.\n      - s. eapply promise_remove_messages; eauto.\n    }\n\n    exploit Memory.write_future; try exact WRITE_EX; try apply LOCAL; eauto.\n    { unguard. des; subst; ss. econs; ss. }\n    i. des.\n    exploit IHWRITE; eauto.\n    { eapply Memory.future_closed_timemap; eauto. }\n    { econs; try apply LOCAL; eauto.\n      eapply TView.future_closed; eauto. apply LOCAL. }\n    { econs. eapply TimeFacts.le_lt_lt; eauto. }\n    intros x. des. clear IHWRITE.\n    exploit split_memory_write; try exact WRITE_EX.\n    { unguard. des; subst; ss. }\n    i. des.\n    exploit reorder_write_lower_rtc_promise; try exact x; try apply WRITE_LOWER; eauto.\n    { eapply Memory.promise_le; try eapply LOCAL; eauto. }\n    s. i. des.\n    esplits.\n    - econs 2; try exact STEPS. econs; [econs|].\n      + econs. econs. econs; eauto. econs; eauto.\n        unguard. des; subst; ss. econs. ss.\n      + ss.\n      + ss.\n    - econs 2; eauto.\n    - congr.\n    - congr.\n    - exploit memory_write_lower_refl_inv; try exact WRITE0. i. congr.\n    - congr.\n    - destruct th1, th2'. ss. subst.\n      i. inv PR. destruct (classic ((x1, x2) = (loc, to'))).\n      { inv H. right. econs.\n        - eapply unchangable_write_na; eauto.\n          inv WRITE0. inv PROMISE0.\n          exploit Memory.lower_get0; try exact PROMISES. i. des.\n          exploit Memory.lower_get0; try exact MEM. i. des.\n          exploit Memory.remove_get0; try exact REMOVE. i. des.\n          rewrite GET in *. inv GET0. econs; eauto.\n        - ii. exploit unchangable_promise; eauto. i.\n          exploit unchangable_rtc_increase; try exact STEPS; eauto. s. i. inv x6.\n          inv WRITE0. inv PROMISE0.\n          exploit Memory.lower_get0; try exact PROMISES. i. des. congr.\n      }\n      specialize (x5 x1 x2 x3 x4). exploit x5.\n      { econs. erewrite write_lower_promises; try exact WRITE0; eauto.\n        condtac; ss. des. subst. ss.\n      }\n      i. des; eauto.\n      right. inv x7. econs; eauto. ii.\n      apply NUNCHANGABLE. eapply unchangable_write; try exact WRITE_EX. ss.\n  }\n\n  { exploit step_split_pure; eauto; ss. i. des. esplits; eauto. }\nQed.\n\nLemma reorder_lower_step_promise_step\n      lang pf e1 e2 (th0 th1 th2: @Thread.t lang)\n      (WF: Local.wf th0.(Thread.local) th0.(Thread.memory))\n      (CLOSED: Memory.closed th0.(Thread.memory))\n      (STEP1: lower_step e1 th0 th1)\n      (STEP2: Thread.step pf e2 th1 th2)\n      (ISPROMISE: is_promise e2)\n      (CONS: Local.promise_consistent th2.(Thread.local)):\n  exists th1',\n    (<<STEP1: Thread.step pf e2 th0 th1'>>) /\\\n    (<<STEP2: lower_step e1 th1' th2>>) /\\\n    (<<STATE: th0.(Thread.state) = th1'.(Thread.state)>>).\nProof.\n  inv STEP2; [|inv STEP; inv LOCAL; ss]. inv STEP. ss.\n  inv STEP1. inv STEP. inv LOCAL0; ss.\n  { esplits.\n    - econs; ss. econs; eauto.\n    - econs; ss. refl.\n    - ss.\n  }\n\n  { exploit reorder_read_promise_diff; eauto.\n    { ii. inv H.\n      inv LOCAL1. inv LOCAL. ss.\n      exploit Memory.promise_get0; eauto.\n      { inv PROMISE; ss.\n        exploit Memory.remove_get0; try exact MEM0. i. des. congr. }\n      i. des.\n      exploit Memory.promise_get1; eauto.\n      { inv PROMISE; ss.\n        exploit Memory.remove_get0; try exact MEM0. i. des. congr. }\n      i. des. inv MSG_LE.\n      rewrite GET_MEM in *. inv GET0.\n      exploit CONS; try exact GET_PROMISES; ss.\n      unfold TimeMap.join, View.singleton_ur_if. condtac.\n      - unfold View.singleton_ur, TimeMap.singleton. ss.\n        unfold LocFun.add, LocFun.init, LocFun.find. condtac; ss. i.\n        exploit TimeFacts.join_lt_des; eauto. i. des.\n        exploit TimeFacts.join_lt_des; try exact AC. i. des. timetac.\n      - unfold View.singleton_rw, TimeMap.singleton. ss.\n        unfold LocFun.add, LocFun.init, LocFun.find. condtac; ss. i.\n        exploit TimeFacts.join_lt_des; eauto. i. des.\n        exploit TimeFacts.join_lt_des; try exact AC. i. des. timetac.\n    }\n    i. des. esplits.\n    - econs. econs; eauto.\n    - econs; ss; try refl. econs; eauto.\n    - ss.\n  }\n\n  { exploit write_step_lower_memory_lower; eauto. i.\n    exploit reorder_write_lower_promise; eauto.\n    { destruct ord; ss. }\n    i. des.\n    destruct (Ordering.le ord Ordering.na) eqn:EQ.\n    { hexploit SAME; auto. i. subst.\n      hexploit write_step_lower_memory_lower_same; try apply LOCAL1; eauto. i.\n      hexploit write_step_lower_lower_memory_same; try exact STEP2; eauto.\n      i. subst. esplits.\n      - econs. econs; eauto.\n      - econs; ss.\n        { econs; eauto. }\n        { refl. }\n      - ss.\n    }\n    { exploit write_step_lower_lower_memory; try exact STEP2; eauto. i.\n      esplits.\n      - econs. econs; eauto.\n      - econs; ss.\n        { econs; eauto. }\n        { rewrite EQ. ss. }\n      - ss.\n    }\n  }\n\n  { exploit Local.read_step_future; eauto. i. des.\n    exploit write_step_lower_memory_lower; eauto. i.\n    exploit reorder_write_lower_promise; try exact LOCAL2; eauto.\n    { destruct ordw; ss. }\n    i. des.\n    exploit write_step_lower_lower_memory; try exact STEP2; eauto. i.\n    hexploit write_step_promise_consistent; try exact STEP2; eauto. i.\n    exploit reorder_read_promise_diff; try exact LOCAL1; eauto.\n    { ii. inv H0. clear LOCAL LOCAL2 STEP2.\n      inv LOCAL1. inv STEP1. ss.\n      exploit Memory.promise_get0; eauto.\n      { inv PROMISE; ss.\n        exploit Memory.remove_get0; try exact MEM0. i. des. congr. }\n      i. des.\n      exploit Memory.promise_get1; eauto.\n      { inv PROMISE; ss.\n        exploit Memory.remove_get0; try exact MEM0. i. des. congr. }\n      i. des. inv MSG_LE.\n      rewrite GET_MEM in *. inv GET0.\n      exploit H; try exact GET_PROMISES; ss.\n      unfold TimeMap.join, View.singleton_ur_if. condtac.\n      - unfold View.singleton_ur, TimeMap.singleton. ss.\n        unfold LocFun.add, LocFun.init, LocFun.find. condtac; ss. i.\n        exploit TimeFacts.join_lt_des; eauto. i. des.\n        exploit TimeFacts.join_lt_des; try exact AC. i. des. timetac.\n      - unfold View.singleton_rw, TimeMap.singleton. ss.\n        unfold LocFun.add, LocFun.init, LocFun.find. condtac; ss. i.\n        exploit TimeFacts.join_lt_des; eauto. i. des.\n        exploit TimeFacts.join_lt_des; try exact AC. i. des. timetac.\n    }\n    i. des. esplits.\n    - econs. econs; eauto.\n    - econs; ss. econs; eauto.\n    - ss.\n  }\n\n  { exploit reorder_fence_promise; eauto.\n    { destruct ordw; ss. }\n    i. des. esplits.\n    - econs. econs; eauto.\n    - econs; ss; try refl. econs; eauto.\n    - ss.\n  }\n\n  { exploit write_na_step_lower_memory_lower; eauto. i. des.\n    exploit reorder_write_na_lower_promise; try apply LOCAL1; eauto.\n    { eapply List.Forall_forall. i.\n      eapply list_Forall2_in2 in KINDS; eauto. des. des_ifs. destruct x; ss.\n    }\n    { destruct kind0; ss. }\n    { inv LOCAL1. destruct ord; ss. }\n    i. des.\n    exploit write_na_step_lower_lower_memory; try exact STEP2; eauto. i.\n    esplits.\n    - econs. econs; eauto.\n    - econs; ss.\n      { econs; eauto. }\n      { subst. refl. }\n    - ss.\n  }\n\n  { exploit reorder_racy_read_promise; eauto. i. des. esplits.\n    - econs. econs; eauto.\n    - econs; ss; try refl. econs; eauto.\n    - ss.\n  }\nQed.\n\nLemma reorder_lower_steps_promise_steps\n      lang tr (th0 th1 th2: @Thread.t lang)\n      (WF: Local.wf th0.(Thread.local) th0.(Thread.memory))\n      (SC: Memory.closed_timemap th0.(Thread.sc) th0.(Thread.memory))\n      (CLOSED: Memory.closed th0.(Thread.memory))\n      (STEPS1: rtc (tau lower_step) th0 th1)\n      (STEPS2: Trace.steps tr th1 th2)\n      (PROMISE: List.Forall (fun x => is_promise (snd x)) tr)\n      (CONS: Local.promise_consistent th2.(Thread.local)):\n  exists tr' th1',\n    (<<STEPS1: Trace.steps tr' th0 th1'>>) /\\\n    (<<TRACE: List.Forall2 (fun x y => snd x = snd y) tr tr'>>) /\\\n    (<<STEPS2: rtc (tau lower_step) th1' th2>>) /\\\n    (<<STATE: th0.(Thread.state) = th1'.(Thread.state)>>).\nProof.\n  revert tr th2 STEPS2 PROMISE CONS.\n  induction STEPS1; i.\n  { esplits; eauto using Forall2_refl.\n    clear - PROMISE STEPS2.\n    induction STEPS2; eauto.\n    subst. inv PROMISE. ss.\n    rewrite <- IHSTEPS2; eauto.\n    inv STEP; [|inv STEP0; inv LOCAL; ss].\n    inv STEP0. ss.\n  }\n  inv H.\n  exploit Thread.step_future; try eapply lower_step_step; eauto. i. des.\n  exploit IHSTEPS1; eauto. i. des.\n  cut (exists tr'' th1'',\n          Trace.steps tr'' x th1'' /\\\n          List.Forall2 (fun x y => snd x = snd y) tr' tr'' /\\\n          lower_step e th1'' th1' /\\\n          x.(Thread.state) = th1''.(Thread.state)).\n  { i. des. esplits; eauto.\n    eapply Forall2_trans; eauto. congr.\n  }\n  exploit Trace.steps_future; try exact STEPS0; eauto. i. des.\n  hexploit rtc_tau_step_promise_consistent;\n    try eapply rtc_implies; try eapply tau_lower_step_tau_step; try exact STEPS3; eauto. i.\n  assert (PROMISE': List.Forall (fun x => is_promise (snd x)) tr')\n    by eauto using trace_eq_promise.\n  clear z STEPS1 IHSTEPS1 STEPS2 STEPS3.\n  clear - WF SC CLOSED TSTEP STEPS0 H PROMISE'.\n  rename tr' into tr, th1' into z, STEPS0 into STEPS, PROMISE' into PROMISE.\n  revert x e WF SC CLOSED TSTEP.\n  induction STEPS; i.\n  { esplits; eauto. }\n  subst. inv PROMISE. ss.\n  exploit Thread.step_future; try eapply lower_step_step; eauto. i. des.\n  exploit Thread.step_future; try eapply STEP; eauto. i. des.\n  hexploit Trace.steps_promise_consistent; try exact STEPS; eauto. i.\n  exploit reorder_lower_step_promise_step; try exact TSTEP; eauto. i. des.\n  exploit Thread.step_future; try eapply STEP1; eauto. i. des.\n  exploit IHSTEPS; try exact STEP2; eauto. i. des.\n  esplits; try exact x2; eauto. congr.\nQed.\n\n\nDefinition delayed {lang} (st0 st1: lang.(Language.state)) lc0 lc1 sc mem: Prop :=\n    (<<MEM: Memory.closed mem>>) /\\\n    (<<SC: Memory.closed_timemap sc mem>>) /\\\n    (<<LOCAL0: Local.wf lc0 mem>>) /\\\n    (<<LOCAL1: Local.wf lc1 mem>>) /\\\n    (<<PROMISES: Memory.le lc1.(Local.promises) lc0.(Local.promises)>>) /\\\n    exists lc1' mem',\n      (<<STEPS: rtc (tau lower_step) (Thread.mk _ st0 lc0 sc mem) (Thread.mk _ st1 lc1' sc mem')>>) /\\\n      (<<MEM: lower_memory mem' mem>>) /\\\n      (<<LOCAL: lower_local lc1' lc1>>).\n\nLemma delayed_refl\n      lang (st: lang.(Language.state)) lc mem sc\n      (MEM: Memory.closed mem)\n      (SC: Memory.closed_timemap sc mem)\n      (LOCAL: Local.wf lc mem)\n  :\n    delayed st st lc lc sc mem.\nProof.\n  red. esplits; eauto; refl.\nQed.\n\nLemma delayed_step\n      lang (st0 st1 st2: Language.state lang) lc0 lc1 lc2\n      mem1 sc1 mem2 sc2\n      pf e\n      (STEP: Thread.step pf e (Thread.mk _ st1 lc1 sc1 mem1) (Thread.mk _ st2 lc2 sc2 mem2))\n      (CONS: Local.promise_consistent lc2)\n      (NRELEASE: ~ release_event e)\n      (DELAYED: delayed st0 st1 lc0 lc1 sc1 mem1)\n  :\n    exists lc0',\n      (<<PROMISES: rtc (tau (@pred_step is_promise _)) (Thread.mk _ st0 lc0 sc1 mem1) (Thread.mk _ st0 lc0' sc2 mem2)>>) /\\\n      (<<DELAYED: delayed st0 st2 lc0' lc2 sc2 mem2>>).\nProof.\n  unfold delayed in DELAYED. des.\n  exploit Thread.step_future; try exact STEP; eauto. s. i. des.\n  exploit Thread.rtc_tau_step_future;\n    try eapply rtc_implies; try eapply tau_lower_step_tau_step; eauto. s. i. des.\n  exploit split_step; try exact STEP; eauto. s. i. des.\n  exploit promise_steps_trace_promise_steps; eauto. i. des.\n  clear STEP PROMISES. rename STEPS0 into PROMISES.\n  destruct th1. ss. subst.\n  exploit lower_memory_promise_steps; try exact MEM0; try exact PROMISES; eauto. i. des.\n  rename STEP into PROMISES_L.\n  exploit Trace.steps_future; try exact PROMISES; eauto. s. i. des.\n  exploit Trace.steps_future; try exact PROMISES_L; eauto. s. i. des.\n  exploit lower_memory_lower_steps; try exact MEM2; try exact LOWER; eauto. i. des.\n  rename STEP into LOWER_L. clear LOWER.\n  hexploit lower_local_consistent; try exact LC0; eauto. i.\n  hexploit rtc_tau_step_promise_consistent;\n    try eapply rtc_implies; try eapply tau_lower_step_tau_step; try exact LOWER_L; eauto. s. i.\n  exploit reorder_lower_steps_promise_steps; try exact STEPS; try exact PROMISES_L; eauto.\n  { eapply trace_eq_promise; eauto. }\n  s. i. des. subst.\n  move STEPS1 at bottom.\n  exploit same_memory_promise_steps; [exact PROMISES|exact STEPS1|..]; eauto.\n  { eapply Forall2_trans; eauto. congr. }\n  s. i. subst. destruct th1'. ss.\n  exploit lower_steps_future; try exact STEPS2. s. i. des. subst.\n  exploit promise_steps_sc; try exact STEPS1; eauto.\n  { repeat (eapply trace_eq_promise; eauto). }\n  s. i. subst.\n  exploit trace_promise_steps_promise_steps; try exact STEPS1; eauto.\n  { repeat (eapply trace_eq_promise; eauto). }\n  i. esplits; try exact x0. clear x0.\n  unfold delayed.\n  exploit Trace.steps_future; try exact STEPS1; eauto. s. i. des.\n  splits; auto.\n  - exploit lower_steps_future; try exact LOWER_L. s. i. des.\n    etrans; eauto. etrans; eauto. inv LC0. ss.\n  - esplits.\n    + etrans; eauto.\n    + ss.\n    + ss.\nQed.\n\nLemma writable_mon_non_release\n      view1 view2 sc1 sc2 loc ts ord1 ord2\n      (VIEW: View.le view1 view2)\n      (ORD: Ordering.le ord1 ord2)\n      (WRITABLE: TView.writable view2 sc2 loc ts ord2):\n  TView.writable view1 sc1 loc ts ord1.\nProof.\n  inv WRITABLE. econs; eauto.\n  eapply TimeFacts.le_lt_lt; try apply VIEW; auto.\nQed.\n\nLemma write_tview_mon_non_release\n      tview1 tview2 sc1 sc2 loc ts ord1 ord2\n      (TVIEW: TView.le tview1 tview2)\n      (WF2: TView.wf tview2)\n      (ORD: Ordering.le ord1 ord2):\n  TView.le\n    (TView.write_tview tview1 sc1 loc ts ord1)\n    (TView.write_tview tview2 sc2 loc ts ord2).\nProof.\n  unfold TView.write_tview, View.singleton_ur_if.\n  econs; repeat (condtac; aggrtac);\n    (try by etrans; [apply TVIEW|aggrtac]);\n    (try by rewrite <- ? View.join_r; econs; aggrtac);\n    (try apply WF2).\nQed.\n\nLemma read_fence_tview_mon_non_release\n      tview1 tview2 ord1 ord2\n      (TVIEW: TView.le tview1 tview2)\n      (WF2: TView.wf tview2)\n      (ORD: Ordering.le ord1 ord2):\n  TView.le\n    (TView.read_fence_tview tview1 ord1)\n    (TView.read_fence_tview tview2 ord2).\nProof.\n  unfold TView.read_fence_tview.\n  econs; repeat (condtac; aggrtac);\n    (try by etrans; [apply TVIEW|aggrtac]);\n    (try by rewrite <- ? View.join_r; aggrtac;\n     rewrite <- ? TimeMap.join_r; apply TVIEW).\nQed.\n\nLemma write_fence_tview_mon_non_release\n      tview1 tview2 sc1 sc2 ord1 ord2\n      (TVIEW: TView.le tview1 tview2)\n      (ORD: Ordering.le ord1 ord2)\n      (WF1: TView.wf tview1)\n      (NREL: Ordering.le ord2 Ordering.strong_relaxed):\n  TView.le\n    (TView.write_fence_tview tview1 sc1 ord1)\n    (TView.write_fence_tview tview2 sc2 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (condtac; aggrtac).\n  all: try by destruct ord1, ord2; ss.\n  all: try by etrans; [apply TVIEW|aggrtac].\nQed.\n\nLemma future_write_lower\n      promises1 mem1 loc from to msg promises2 mem2 kind\n      mem1' msg'\n      (WRITE: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (KIND: Memory.op_kind_is_lower kind)\n      (LE1: Memory.le promises1 mem1')\n      (MSG_LE: Message.le msg' msg)\n      (MSG_WF: Message.wf msg')\n      (MSG_CLOSED: Memory.closed_message msg' mem1')\n      (FUTURE1: Memory.future_weak mem1 mem1'):\n  exists mem2',\n    (<<WRITE': Memory.write promises1 mem1' loc from to msg' promises2 mem2' kind>>) /\\\n    (<<FUTURE2: Memory.future_weak mem2 mem2'>>).\nProof.\n  inv WRITE. inv PROMISE; ss.\n  exploit Memory.lower_get0; try exact PROMISES. i. des.\n  exploit Memory.lower_exists; try exact GET; try eapply MSG_WF.\n  { inv MEM. inv LOWER. ss. }\n  { etrans; eauto. }\n  i. des.\n  exploit Memory.lower_exists_le; try apply LE1; eauto. i. des.\n  exploit Memory.lower_get0; try exact x0. i. des.\n  exploit Memory.remove_exists; try exact GET2. i. des.\n  exploit lower_remove_remove; try exact PROMISES; eauto. i.\n  exploit lower_remove_remove; try exact x0; eauto. i.\n  exploit Memory.remove_inj; [exact x4|exact x3|]. i. subst.\n  clear x3 x4.\n  esplits.\n  { econs; try exact x2. econs; eauto.\n    - inv MSG_LE; ss. inv TS. econs. etrans; eauto.\n      inv RELEASED; try apply Time.bot_spec. apply LE.\n    - ii. subst. inv MSG_LE. ss.\n  }\n  { clear - FUTURE1 MEM x1 MSG_LE MSG_WF MSG_CLOSED TS.\n    inv FUTURE1. econs; i.\n    - revert GET. erewrite Memory.lower_o; eauto. condtac; ss; i.\n      + des. inv GET.\n        exploit Memory.lower_get0; try exact x1. i. des.\n        esplits; eauto; try refl. right. splits; ss.\n        eapply Memory.lower_closed_message; eauto.\n      + guardH o.\n        erewrite Memory.lower_o; eauto. condtac; ss. guardH o0.\n        exploit SOUND; eauto. i. des; esplits; eauto.\n        right. splits; auto.\n        eapply Memory.lower_closed_message; eauto.\n    - revert GET2. erewrite Memory.lower_o; eauto. condtac; ss; i.\n      + des. inv GET2. inv MSG_LE. inv MSG_WF. inv MSG_CLOSED. inv TS. splits; ss.\n        * eapply Memory.lower_closed_opt_view; eauto.\n        * etrans; eauto. inv RELEASED; try apply Time.bot_spec. apply LE.\n      + guardH o.\n        revert GET1. erewrite Memory.lower_o; eauto. condtac; ss. i. guardH o0.\n        exploit COMPLETE1; eauto. i. des. splits; auto.\n        eapply Memory.lower_closed_opt_view; eauto.\n    - revert GET2. erewrite Memory.lower_o; eauto. condtac; ss; i.\n      + des. inv GET2. inv MSG_LE. inv MSG_WF. inv MSG_CLOSED. inv TS. splits; ss.\n        * eapply Memory.lower_closed_opt_view; eauto.\n        * etrans; eauto. inv RELEASED; try apply Time.bot_spec. apply LE.\n      + guardH o.\n        revert GET1. erewrite Memory.lower_o; eauto. condtac; ss. i. guardH o0.\n        exploit COMPLETE2; eauto. i. des. splits; auto.\n        eapply Memory.lower_closed_opt_view; eauto.\n  }\nQed.\n\nLemma future_write_na_lower\n      ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n      ts' mem1'\n      (WRITE: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind)\n      (KINDS: List.Forall (fun x => Memory.op_kind_is_lower x) kinds)\n      (KIND: Memory.op_kind_is_lower kind)\n      (LE1: Memory.le promises1 mem1')\n      (TS: Time.le ts' ts)\n      (FUTURE1: Memory.future_weak mem1 mem1'):\n  exists mem2',\n    (<<WRITE': Memory.write_na ts' promises1 mem1' loc from to val promises2 mem2' msgs kinds kind>>) /\\\n    (<<FUTURE2: Memory.future_weak mem2 mem2'>>).\nProof.\n  revert ts' mem1' LE1 TS FUTURE1. induction WRITE; i.\n  { exploit future_write_lower; try eassumption; try refl; eauto. i. des.\n    esplits.\n    - econs 1; eauto. eapply TimeFacts.le_lt_lt; eauto.\n    - ss.\n  }\n  inv KINDS.\n  exploit future_write_lower; try exact WRITE_EX; try exact LE1; try refl; eauto.\n  { unguard. des; subst; ss. econs. ss. }\n  { unguard. des; subst; ss. econs. ss. }\n  i. des.\n  hexploit Memory.write_le; try exact WRITE'; eauto. i. des.\n  exploit IHWRITE; eauto; try refl. i. des.\n  esplits.\n  - econs 2; eauto. eapply TimeFacts.le_lt_lt; eauto.\n  - ss.\nQed.\n\nLemma future_read_step\n      lc1 mem1 loc to val released ord lc2\n      lc1' mem1'\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (LOCAL1: lower_local lc1' lc1)\n      (MEM1: Memory.future_weak mem1 mem1')\n      (WF: Local.wf lc1 mem1)\n      (CLOSED: Memory.closed mem1):\n  exists lc2' released',\n    (<<STEP': Local.read_step lc1' mem1' loc to val released' ord lc2'>>) /\\\n    (<<RELEASED: View.opt_le released' released>>) /\\\n    (<<LOCAL2: lower_local lc2' lc2>>).\nProof.\n  inv STEP.\n  exploit Memory.future_weak_get1; try exact GET; eauto; ss. i. des. inv MSG_LE.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto.\n    + inv LOCAL1. ss.\n      eapply TViewFacts.readable_mon; try apply TVIEW; eauto. refl.\n  - ss.\n  - inv LOCAL1. ss. econs.\n    eapply TViewFacts.read_tview_mon; try apply TVIEW; eauto.\n    + apply WF.\n    + inv CLOSED. exploit CLOSED0; eauto. i. des. inv MSG_WF. ss.\n    + refl.\nQed.\n\nLemma future_write_step\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      lc1' sc1' mem1' releasedm'\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (KIND: Memory.op_kind_is_lower kind)\n      (LOCAL1: lower_local lc1' lc1)\n      (MEM1: Memory.future_weak mem1 mem1')\n      (RELM_LE: View.opt_le releasedm' releasedm)\n      (RELM_WF: View.opt_wf releasedm)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm mem1)\n      (RELM_WF': View.opt_wf releasedm')\n      (RELM_CLOSED': Memory.closed_opt_view releasedm' mem1')\n      (WF: Local.wf lc1 mem1)\n      (WF': Local.wf lc1' mem1')\n      (CLOSED: Memory.closed mem1)\n      (CLOSED': Memory.closed mem1'):\n  exists released' lc2' sc2' mem2',\n    (<<STEP': Local.write_step lc1' sc1' mem1' loc from to val releasedm' released' ord lc2' sc2' mem2' kind>>) /\\\n    (<<LOCAL2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: Memory.future_weak mem2 mem2'>>).\nProof.\n  inv STEP. inv LOCAL1. ss.\n  exploit TViewFacts.write_future0; try apply WF'; try apply RELM_WF'. s. i. des.\n  exploit future_write_lower; try exact WRITE.\n  { ss. }\n  { apply WF'. }\n  { econs; [refl|]. eapply TViewFacts.write_released_mon; eauto; try refl. apply WF. }\n  { eauto. }\n  { econs. unfold TView.write_released. condtac; ss. econs.\n    apply Memory.join_closed_view.\n    - inv RELM_CLOSED'; ss. inv CLOSED'. econs; ii; eauto.\n    - unfold LocFun.add. condtac; ss.\n      inv WRITE. inv PROMISE; ss.\n      exploit Memory.lower_get0; try exact MEM. i. des. inv MSG_LE.\n      exploit Memory.future_weak_get1; try exact GET; eauto; ss. i. des. inv MSG_LE.\n      condtac; apply Memory.join_closed_view; try apply WF'; viewtac.\n  }\n  { ss. }\n  i. des. esplits.\n  - econs; eauto. ss.\n    eapply writable_mon_non_release; eauto; try refl. apply TVIEW.\n  - econs; ss. eapply write_tview_mon_non_release; eauto; try refl. apply WF.\n  - ss.\nQed.\n\nLemma future_write_na_step\n      lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n      lc1' sc1' mem1'\n      (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind)\n      (KINDS: List.Forall (fun x => Memory.op_kind_is_lower x) kinds)\n      (KIND: Memory.op_kind_is_lower kind)\n      (LOCAL1: lower_local lc1' lc1)\n      (MEM1: Memory.future_weak mem1 mem1')\n      (WF: Local.wf lc1 mem1)\n      (WF': Local.wf lc1' mem1')\n      (CLOSED: Memory.closed mem1)\n      (CLOSED': Memory.closed mem1'):\n  exists lc2' sc2' mem2',\n    (<<STEP': Local.write_na_step lc1' sc1' mem1' loc from to val ord lc2' sc2' mem2' msgs kinds kind>>) /\\\n    (<<LOCAL2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: Memory.future_weak mem2 mem2'>>).\nProof.\n  inv STEP. inv LOCAL1. ss.\n  exploit future_write_na_lower; try exact WRITE; try exact MEM1;\n    eauto; try apply WF'; try apply TVIEW. i. des.\n  esplits.\n  - econs; eauto.\n  - econs; ss. eapply write_tview_mon_non_release; eauto; try refl. apply WF.\n  - ss.\nQed.\n\nLemma future_is_racy\n      lc1 mem1 loc to ord\n      lc1' mem1'\n      (STEP: Local.is_racy lc1 mem1 loc to ord)\n      (LOCAL1: lower_local lc1' lc1)\n      (MEM1: Memory.future_weak mem1 mem1')\n      (WF: Local.wf lc1 mem1)\n      (CLOSED: Memory.closed mem1):\n  <<STEP': Local.is_racy lc1' mem1' loc to ord>>.\nProof.\n  inv STEP. inv LOCAL1. ss.\n  exploit Memory.future_weak_get1; eauto. i. des.\n  econs; eauto; ss.\n  - eapply TViewFacts.racy_view_mon; try apply TVIEW; eauto.\n  - ii. subst. inv MSG_LE. ss.\n  - i. exploit MSG2; eauto. i. subst. inv MSG_LE. ss.\nQed.\n\nLemma future_lower_step\n      lang e\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      lc1' sc1' mem1'\n      (STEP: @lower_step lang e (Thread.mk _ st1 lc1 sc1 mem1) (Thread.mk _ st2 lc2 sc2 mem2))\n      (LOCAL1: lower_local lc1' lc1)\n      (MEM1: Memory.future_weak mem1 mem1')\n      (WF: Local.wf lc1 mem1)\n      (WF': Local.wf lc1' mem1')\n      (SC: Memory.closed_timemap sc1 mem1)\n      (SC': Memory.closed_timemap sc1' mem1')\n      (CLOSED: Memory.closed mem1)\n      (CLOSED': Memory.closed mem1'):\n  exists e' lc2' sc2' mem2',\n    (<<STEP': lower_step e' (Thread.mk _ st1 lc1' sc1' mem1') (Thread.mk _ st2 lc2' sc2' mem2')>>) /\\\n    (<<EVENT: ThreadEvent.get_machine_event e = ThreadEvent.get_machine_event e'>>) /\\\n    (<<LOCAL2: lower_local lc2' lc2>>) /\\\n    (<<MEM2: Memory.future_weak mem2 mem2'>>).\nProof.\n  inv STEP. inv STEP0. inv LOCAL; ss.\n  { (* silent *)\n    esplits; eauto.\n    - econs; [econs; eauto|..]; eauto. refl.\n    - ss.\n  }\n\n  { (* read *)\n    exploit future_read_step; try exact LOCAL0; try exact LOCAL1; try exact MEM1; eauto. i. des.\n    esplits.\n    - econs.\n      + econs; [|econs 2]; eauto.\n      + ss.\n      + ss. refl.\n      + ss.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { (* write *)\n    exploit future_write_step; try exact LOCAL0; try exact LOCAL1; try exact SC1; try exact MEM1; eauto.\n    { inv LOCAL0. eapply write_lower_memory_lower; eauto. }\n    i. des. esplits.\n    - econs.\n      + econs; [|econs 3]; eauto.\n      + ss.\n      + ss. inv LOCAL0. inv STEP'.\n        eapply write_lower_lower_memory; eauto.\n        eapply write_lower_memory_lower; try exact WRITE; eauto.\n      + i. ss. inv LOCAL0. inv STEP'.\n        eapply write_lower_lower_memory_same; eauto.\n        eapply write_same_memory_same in WRITE; eauto. destruct ord; ss.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { (* update *)\n    exploit future_read_step; try exact LOCAL0; try exact LOCAL1; try exact MEM1; eauto. i. des.\n    exploit Local.read_step_future; try exact LOCAL0; eauto. i. des.\n    exploit Local.read_step_future; try exact STEP'; eauto. i. des.\n    exploit future_write_step; try exact LOCAL2;\n      try exact LOCAL3; try exact SC1; try exact MEM1; try exact RELEASED; eauto.\n    { inv LOCAL2. eapply write_lower_memory_lower; eauto. }\n    i. des. esplits.\n    - econs.\n      + econs; [|econs 4]; eauto.\n      + ss.\n      + ss. inv LOCAL2. inv STEP'0.\n        eapply write_lower_lower_memory; eauto.\n        eapply write_lower_memory_lower; try exact WRITE; eauto.\n      + i. ss.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { (* fence *)\n    inv LOCAL0. esplits.\n    - econs.\n      + econs; [|econs 5]; eauto. econs; eauto; ss. i. subst. ss.\n      + ss.\n      + ss. refl.\n      + ss.\n    - ss.\n    - inv LOCAL1. econs. ss.\n      eapply write_fence_tview_mon_non_release; eauto; try refl.\n      + eapply read_fence_tview_mon_non_release; eauto; try refl. apply WF.\n      + eapply TViewFacts.read_fence_future; apply WF'.\n      + destruct ordw; ss.\n    - ss.\n  }\n\n  { (* na write *)\n    hexploit SAME; eauto. i. subst.\n    hexploit write_na_step_lower_memory_lower; eauto. i. des.\n    exploit future_write_na_step; try exact LOCAL0; try exact LOCAL1; try exact SC1; try exact MEM1; eauto.\n    { eapply List.Forall_forall. i.\n      eapply list_Forall2_in2 in KINDS; eauto. des. des_ifs. destruct x; ss.\n    }\n    { destruct kind; ss. }\n    i. des.\n    assert (mem2' = mem1').\n    { ss. inv LOCAL0. inv STEP'.\n      eapply write_na_lower_lower_memory; eauto;\n        eapply write_na_lower_memory_lower; try exact WRITE; eauto.\n    }\n    subst. esplits.\n    - econs.\n      + econs; [|econs 8]; eauto.\n      + ss.\n      + ss. refl.\n      + ss.\n    - ss.\n    - ss.\n    - ss.\n  }\n\n  { (* racy read *)\n    inv LOCAL0.\n    exploit future_is_racy; try exact RACE; try exact LOCAL1; try exact MEM1; eauto. i. des.\n    esplits.\n    - econs.\n      + econs; [|econs 9]; eauto.\n      + ss.\n      + ss. refl.\n      + ss.\n    - ss.\n    - ss.\n    - ss.\n  }\nQed.\n\nLemma delayed_future\n      mem1 sc1\n      lang (st0 st1: lang.(Language.state)) lc0 lc1 mem0 sc0\n      (DELAYED: delayed st0 st1 lc0 lc1 sc0 mem0)\n      (WF: Local.wf lc0 mem1)\n      (SC: Memory.closed_timemap sc1 mem1)\n      (MEM: Memory.closed mem1)\n      (MEM_FUTURE: Memory.future_weak mem0 mem1):\n    delayed st0 st1 lc0 lc1 sc1 mem1.\nProof.\n  unfold delayed in *. des. splits; auto.\n  { inv LOCAL1. econs; ss.\n    - eapply TView.future_weak_closed; eauto.\n    - inv WF. etrans; try exact PROMISES1. ss.\n  }\n  cut (exists lc2' sc2' mem1',\n          rtc (tau lower_step) (Thread.mk _ st0 lc0 sc1 mem1) (Thread.mk _ st1 lc2' sc2' mem1') /\\\n          lower_local lc2' lc1').\n  { i. des.\n    exploit lower_steps_future; try exact H. s. i. des. subst.\n    esplits; eauto. etrans; eauto.\n  }\n  clear lc1 LOCAL1 PROMISES LOCAL MEM1.\n  rename LOCAL0 into WF0.\n  assert (LOCAL: lower_local lc0 lc0) by refl.\n  revert LOCAL WF. generalize lc0 at 1 3 4.\n  remember (Thread.mk lang st0 lc0 sc0 mem0) as th0.\n  remember (Thread.mk lang st1 lc1' sc0 mem') as th1.\n  move STEPS at top. revert_until STEPS.\n  induction STEPS; i; subst.\n  { inv Heqth1. esplits; eauto. }\n  inv H. destruct y.\n  exploit lower_step_future; try exact TSTEP. s. i. des. subst.\n  exploit future_lower_step; try exact TSTEP;\n    try exact LOCAL; try exact MEM_FUTURE; eauto. i. des.\n  exploit Thread.step_future; try eapply lower_step_step; try exact TSTEP; eauto. s. i. des.\n  exploit Thread.step_future; try eapply lower_step_step; try exact STEP'; eauto. s. i. des.\n  exploit IHSTEPS; try exact LOCAL2; try exact MEM2; eauto. i. des.\n  esplits.\n  - econs 2; eauto. econs; eauto. congr.\n  - ss.\nQed.\n\nSection CLOSED.\n  Variable loc_na: Loc.t -> Prop.\n\n  Definition closed_future_timemap (tm: TimeMap.t) (mem0 mem1: Memory.t): Prop :=\n    forall loc (NA: loc_na loc),\n      Memory.get loc (tm loc) mem1 = Memory.get loc (tm loc) mem0.\n\n  Record closed_future_view (vw: View.t) (mem0 mem1: Memory.t): Prop :=\n    closed_future_view_intro\n      { closed_future_pln: closed_future_timemap vw.(View.pln) mem0 mem1;\n        closed_future_rlx: closed_future_timemap vw.(View.rlx) mem0 mem1;\n      }.\n\n  Record closed_future_tview (tvw: TView.t) (mem0 mem1: Memory.t): Prop :=\n    closed_future_tview_intro\n      { closed_future_rel: forall loc, closed_future_view (tvw.(TView.rel) loc) mem0 mem1;\n        closed_future_cur: closed_future_view tvw.(TView.cur) mem0 mem1;\n        closed_future_acq: closed_future_view tvw.(TView.acq) mem0 mem1;\n      }.\nEnd CLOSED.\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/Delayed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.29098087236345377, "lm_q1q2_score": 0.1624624715988238}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\n\nRequire Import RaftUpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import VotesLeCurrentTermInterface.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection VotesLeCurrentTerm.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Ltac start_proof :=\n    cbn [nwState]; intros; subst; repeat find_higher_order_rewrite;\n    update_destruct; rewrite_update; cbn [fst snd] in *; eauto.\n\n\n  Lemma votes_le_current_term_client_request :\n    refined_raft_net_invariant_client_request votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, votes_le_currentTerm.\n    start_proof.\n    erewrite handleClientRequest_currentTerm by eauto.\n    rewrite @votes_update_elections_data_client_request in *.\n    eauto.\n  Qed.\n\n  Lemma votes_le_current_term_timeout :\n    refined_raft_net_invariant_timeout votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, votes_le_currentTerm.\n    start_proof.\n    find_copy_eapply_lem_hyp votes_update_elections_data_timeout; eauto.\n    break_or_hyp; auto with *.\n    find_apply_lem_hyp handleTimeout_currentTerm.\n    find_apply_hyp_hyp.\n    eauto using le_trans.\n  Qed.\n\n  Lemma votes_le_current_term_append_entries :\n    refined_raft_net_invariant_append_entries votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, votes_le_currentTerm.\n    start_proof.\n    rewrite @votes_same_append_entries in *.\n    find_apply_lem_hyp handleAppendEntries_currentTerm.\n    find_apply_hyp_hyp.\n    eauto using le_trans.\n  Qed.\n\n  Lemma votes_le_current_term_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, votes_le_currentTerm.\n    start_proof.\n    find_apply_lem_hyp handleAppendEntriesReply_currentTerm.\n    find_apply_hyp_hyp.\n    eauto using le_trans.\n  Qed.\n\n  Lemma votes_le_current_term_request_vote :\n    refined_raft_net_invariant_request_vote votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, votes_le_currentTerm.\n    start_proof.\n    find_eapply_lem_hyp votes_update_elections_data_request_vote; eauto.\n    intuition.\n    find_apply_hyp_hyp.\n    eauto using le_trans, handleRequestVote_currentTerm.\n  Qed.\n\n  Lemma votes_le_current_term_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote_reply, votes_le_currentTerm.\n    start_proof.\n    find_eapply_lem_hyp votes_update_elections_data_request_vote_reply; eauto.\n    eapply le_trans; [|eapply handleRequestVoteReply_currentTerm'; eauto]; eauto.\n  Qed.\n\n  Lemma votes_le_current_term_do_leader :\n    refined_raft_net_invariant_do_leader votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, votes_le_currentTerm.\n    start_proof.\n    assert (gd = (fst (nwState net h)) /\\ d = snd (nwState net h))\n      by (repeat find_rewrite; auto). break_and. subst.\n    erewrite doLeader_currentTerm by eauto.\n    eauto.\n  Qed.\n\n  Lemma votes_le_current_term_do_generic_server :\n    refined_raft_net_invariant_do_generic_server votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, votes_le_currentTerm.\n    start_proof.\n    assert (gd = (fst (nwState net h)) /\\ d = snd (nwState net h))\n      by (repeat find_rewrite; auto). break_and. subst.\n    erewrite doGenericServer_currentTerm by eauto.\n    eauto.\n  Qed.\n\n  Lemma votes_le_current_term_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, votes_le_currentTerm.\n    intros.\n    repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma votes_le_current_term_reboot :\n    refined_raft_net_invariant_reboot votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, votes_le_currentTerm.\n    start_proof.\n    unfold reboot. simpl.\n    assert (gd = (fst (nwState net h)) /\\ d = snd (nwState net h))\n      by (repeat find_rewrite; auto). break_and. subst.\n    eauto.\n  Qed.\n\n  Theorem votes_le_current_term_init :\n    refined_raft_net_invariant_init votes_le_currentTerm.\n  Proof using. \n    unfold refined_raft_net_invariant_init, votes_le_currentTerm.\n    simpl. intuition.\n  Qed.\n\n  Theorem votes_le_current_term_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      votes_le_currentTerm net.\n  Proof using rri. \n    intros.\n    eapply refined_raft_net_invariant; eauto.\n    - apply votes_le_current_term_init.\n    - apply votes_le_current_term_client_request.\n    - apply votes_le_current_term_timeout.\n    - apply votes_le_current_term_append_entries.\n    - apply votes_le_current_term_append_entries_reply.\n    - apply votes_le_current_term_request_vote.\n    - apply votes_le_current_term_request_vote_reply.\n    - apply votes_le_current_term_do_leader.\n    - apply votes_le_current_term_do_generic_server.\n    - apply votes_le_current_term_state_same_packet_subset.\n    - apply votes_le_current_term_reboot.\n  Qed.\n\n  Instance vlcti : votes_le_current_term_interface.\n  Proof.\n    split.\n    auto using votes_le_current_term_invariant.\n  Qed.\nEnd VotesLeCurrentTerm.", "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/VotesLeCurrentTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16243229087044814}}
{"text": "Require Import Classical Peano_dec Setoid PeanoNat.\nFrom hahn Require Import Hahn.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import imm_bob imm_s_ppo.\nRequire Import CombRelations.\nRequire Import AuxDef.\nRequire Import AuxRel2.\nRequire Import TraversalConfig.\nRequire Import imm_s_rfppo.\n\nSet Implicit Arguments.\n\nSection Traversal.\n  Variable G : execution.\n  Hypothesis WF : Wf G.\n  Variable sc : relation actid.\n  Hypothesis IMMCON : imm_consistent G sc.\n\n  Notation \"'sb'\" := (sb G).\n  Notation \"'rmw'\" := (rmw G).\n  Notation \"'data'\" := (data G).\n  Notation \"'addr'\" := (addr G).\n  Notation \"'ctrl'\" := (ctrl G).\n  Notation \"'rf'\" := (rf G).\n  Notation \"'co'\" := (co G).\n  Notation \"'coe'\" := (coe G).\n  Notation \"'fr'\" := (fr G).\n\n  Notation \"'eco'\" := (eco G).\n\n  Notation \"'bob'\" := (bob G).\n  Notation \"'fwbob'\" := (fwbob G).\n  Notation \"'ppo'\" := (ppo G).\n  Notation \"'fre'\" := (fre G).\n  Notation \"'rfi'\" := (rfi G).\n  Notation \"'rfe'\" := (rfe G).\n  Notation \"'deps'\" := (deps G).\n  Notation \"'detour'\" := (detour G).\n  Notation \"'release'\" := (release G).\n  Notation \"'sw'\" := (sw G).\n  Notation \"'hb'\" := (hb G).\n\n  Notation \"'urr'\" := (urr G sc).\n  Notation \"'c_acq'\" := (c_acq G sc).\n  Notation \"'c_cur'\" := (c_cur G sc).\n  Notation \"'c_rel'\" := (c_rel G sc).\n  Notation \"'t_acq'\" := (t_acq G sc).\n  Notation \"'t_cur'\" := (t_cur G sc).\n  Notation \"'t_rel'\" := (t_rel G sc).\n  Notation \"'S_tm'\" := (S_tm G).\n  Notation \"'S_tmr'\" := (S_tmr G).\n  Notation \"'msg_rel'\" := (msg_rel G sc).\n\nNotation \"'lab'\" := (lab G).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (Events.mod lab).\nNotation \"'same_loc'\" := (same_loc lab).\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'R'\" := (fun x => is_true (is_r lab x)).\nNotation \"'W'\" := (fun x => is_true (is_w lab x)).\nNotation \"'F'\" := (fun x => is_true (is_f lab x)).\nNotation \"'RW'\" := (R \u222a\u2081 W).\nNotation \"'FR'\" := (F \u222a\u2081 R).\nNotation \"'FW'\" := (F \u222a\u2081 W).\n\nNotation \"'R_ex'\" := (R_ex G).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex \u2229\u2081 (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Init'\" := (fun a => is_true (is_init a)).\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_' l\" := (W \u2229\u2081 Loc_ l) (at level 1).\n\nNotation \"'Pln'\" := (fun x => is_true (is_only_pln lab x)).\nNotation \"'Rlx'\" := (fun x => is_true (is_rlx lab x)).\nNotation \"'Rel'\" := (fun x => is_true (is_rel lab x)).\nNotation \"'Acq'\" := (fun x => is_true (is_acq lab x)).\nNotation \"'Acqrel'\" := (fun x => is_true (is_acqrel lab x)).\nNotation \"'Sc'\" := (fun x => is_true (is_sc lab x)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\n\n  Definition itrav_step e T T' :=\n    \u27ea COVER :\n      \u27ea NEXT : ~ covered T e \u27eb /\\\n      \u27ea COV  : coverable G sc T e \u27eb /\\\n      \u27ea COVEQ: covered T' \u2261\u2081 covered T \u222a\u2081 (eq e) \u27eb /\\\n      \u27ea ISSEQ: issued  T' \u2261\u2081 issued  T \u27eb\n    \u27eb \\/\n    \u27ea ISSUE :\n      \u27ea NISS : ~ issued T e \u27eb /\\\n      \u27ea ISS  : issuable G sc T e \u27eb /\\\n      \u27ea COVEQ: covered T' \u2261\u2081 covered T \u27eb /\\\n      \u27ea ISSEQ: issued  T' \u2261\u2081 issued  T \u222a\u2081 (eq e) \u27eb\n    \u27eb.\n\n  Global Add Parametric Morphism : itrav_step with signature\n      eq ==> same_trav_config ==> same_trav_config ==> iff as\n          itrav_step_more.\n  Proof using.\n    intros e.\n    unfold same_trav_config, itrav_step; ins; desf.\n    rename y0 into y.\n    split; ins; desf; simpls; unnw.\n    all: first [rewrite <- H, <- H2, <- H0, <- H1 | rewrite H, H2, H0, H1].\n    - assert (~ covered y e) by (intro; eapply NEXT, H; done).\n      assert (coverable G sc y e ) by (eapply traversal_mon; [apply H| apply H2| done]).\n      eauto 20.\n    - assert (~ issued y e) by (intro; eapply NISS, H2; done).\n      assert (issuable G sc y e).\n      { eapply traversal_mon; [apply H|apply H2|done]. }\n      eauto 20.\n    - assert (~ covered x e) by (intro; eapply NEXT, H; done).\n      assert (coverable G sc x e ) by (eapply traversal_mon; [apply H| apply H2| done]).\n      eauto 20.\n    - assert (~ issued x e) by (intro; eapply NISS, H2; done).\n      assert (issuable G sc x e ) by (eapply traversal_mon; [apply H| apply H2| done]).\n      eauto 20.\n  Qed.\n\n  Lemma itrav_step_mon_ext e\n        (C1 I1 C2 I2 C' I': actid -> Prop)\n        (STEP: itrav_step e (mkTC C1 I1) (mkTC C2 I2)):\n          (itrav_step e)^?\n                        (mkTC (C1 \u222a\u2081 C') (I1 \u222a\u2081 I'))\n                        (mkTC (C2 \u222a\u2081 C') (I2 \u222a\u2081 I')).\n  Proof using.\n    red in STEP. desf; simpl in *. \n\n    { destruct (classic (C' e)).\n      { left. f_equal; apply set_extensionality;\n                (rewrite COVEQ || rewrite ISSEQ); basic_solver. }\n      right. red. left. splits; simpl. \n      { intros [? | ?]; done. }\n      { eapply traversal_mon; [.. | apply COV]; simpl; basic_solver. }\n      all: (rewrite COVEQ || rewrite ISSEQ); basic_solver. }\n\n    destruct (classic (I' e)).\n    { left. f_equal; apply set_extensionality;\n              (rewrite COVEQ || rewrite ISSEQ); basic_solver. }\n    right. red. right. splits; simpl. \n    { intros [? | ?]; done. }\n    { eapply traversal_mon; [| | apply ISS]; simpl; basic_solver. }\n    all: (rewrite COVEQ || rewrite ISSEQ); basic_solver.\n  Qed.\n\n  Lemma itrav_step_mon_ext_equiv e \n        (C1 I1 C2 I2 C' I' Cu1 Iu1 Cu2 Iu2: actid -> Prop)\n        (STEP: itrav_step e {| covered := C1; issued := I1 |}\n                            {| covered := C2; issued := I2 |})\n        (EQC1: Cu1 \u2261\u2081 C1 \u222a\u2081 C') (EQI1: Iu1 \u2261\u2081 I1 \u222a\u2081 I')\n        (EQC2: Cu2 \u2261\u2081 C2 \u222a\u2081 C') (EQI2: Iu2 \u2261\u2081 I2 \u222a\u2081 I'):\n    (itrav_step e)^? (mkTC Cu1 Iu1) (mkTC Cu2 Iu2).\n  Proof using.\n    forward eapply itrav_step_mon_ext with (C' := C') (I' := I') as STEP'; eauto.\n    destruct STEP'.\n    { left. apply same_tc_extensionality. rewrite EQC1, EQC2, EQI1, EQI2.\n      inversion H. rewrite H1, H2. reflexivity. }\n    right. eapply itrav_step_more; [done| .. | by apply H].\n    all: red; split; simpl; auto.\n  Qed. \n\n  Lemma itrav_step_mon_ext_cover e\n        (C I C' I': actid -> Prop)\n        (STEP: itrav_step e (mkTC C I) (mkTC (C \u222a\u2081 eq e) I))\n        (NEW: set_disjoint (C \u222a\u2081 C') (eq e)):\n    itrav_step e (mkTC (C \u222a\u2081 C') (I \u222a\u2081 I'))\n                 (mkTC (C \u222a\u2081 C' \u222a\u2081 eq e) (I \u222a\u2081 I')).\n  Proof using.\n    forward eapply itrav_step_mon_ext with (C' := C') (I' := I') as STEP'; eauto. \n    red in STEP. desf; simpl in *. \n    2: { destruct (NEW e); auto. left. apply COVEQ. basic_solver. }\n    destruct STEP'.\n    { inversion H. destruct (NEW e); auto. rewrite H1. basic_solver. }\n    rewrite set_unionA, set_unionC with (s := C'), <- set_unionA. auto. \n  Qed. \n    \n  Lemma itrav_step_mon_ext_issue e\n        (C I C' I': actid -> Prop)\n        (STEP: itrav_step e (mkTC C I) (mkTC C (I \u222a\u2081 eq e)))\n        (NEW: set_disjoint (I \u222a\u2081 I') (eq e)):\n          itrav_step e (mkTC (C \u222a\u2081 C') (I \u222a\u2081 I'))\n                       (mkTC (C \u222a\u2081 C') (I \u222a\u2081 I' \u222a\u2081 eq e)).\n  Proof using.\n    forward eapply itrav_step_mon_ext with (C' := C') (I' := I') as STEP'; eauto. \n    red in STEP. desf; simpl in *. \n    { destruct (NEW e); auto. left. apply ISSEQ. basic_solver. }\n    destruct STEP'.\n    { inversion H. destruct (NEW e); auto. rewrite H1. basic_solver. }\n    rewrite set_unionA, set_unionC with (s := I'), <- set_unionA. auto. \n  Qed.\n\n  Definition trav_step T T' := exists e, itrav_step e T T'.\n\n  Definition traverse := clos_trans trav_step.\n\n  Definition init_trav :=\n    {| covered := Init \u2229\u2081 E;\n       issued := Init \u2229\u2081 E;\n    |}.\n\n  Global Add Parametric Morphism : trav_step with signature\n      same_trav_config ==> same_trav_config ==> iff as\n          trav_step_more.\n  Proof using.\n    unfold trav_step; ins; desf.\n    split; intros [e HH]; exists e.\n    all: eapply itrav_step_more; eauto.\n    all: by apply same_tc_Symmetric.\n  Qed.\n\n  Global Add Parametric Morphism : traverse with signature\n      same_trav_config ==> same_trav_config ==> iff as\n          traverse_more.\n  Proof using.\n    intros x y H x' y' H'; desf; unnw.\n    split; intros IND;\n      [generalize dependent y'; generalize dependent y |\n       generalize dependent x'; generalize dependent x ];\n      induction IND; ins.\n    1,3: by apply t_step; eapply trav_step_more; eauto;\n      apply same_trav_config_sym.\n    all: eapply t_trans; [eapply IHIND1 | eapply IHIND2]; auto;\n        eapply same_trav_config_refl.\n  Qed.\n\n  Lemma step_mon C C' (T : trav_step C C') :\n  covered C \u2286\u2081 covered C' /\\ issued C \u2286\u2081 issued C'.\n  Proof using.\n    destruct T as [e [STEP | STEP]]; auto.\n    unnw; unfolder in *; basic_solver 21.\n    unnw; unfolder in *; basic_solver 21.\n  Qed.\n\n  Lemma trav_step_coherence (C C' : trav_config) (T : trav_step C C')\n        (H : tc_coherent G sc C):\n    tc_coherent G sc C'.\n  Proof using.\n  assert (coverable G sc C \u2286\u2081 coverable G sc C' /\\ issuable G sc C \u2286\u2081 issuable G sc C').\n  by apply traversal_mon; apply step_mon; eauto.\n  destruct T as [e [STEP | STEP]]; auto; unnw; desf.\n  - unfold tc_coherent in *; splits; desf.\n    unfolder in *; basic_solver 12.\n    rewrite STEP1, <- H0; basic_solver 21.\n    unfolder in *; basic_solver 12.\n  - unfold tc_coherent in *; splits; desf.\n    unfolder in *; basic_solver 12.\n    rewrite STEP1, <- H0; basic_solver 21.\n    rewrite STEP2, <- H1; basic_solver 21.\n  Qed.\n  \n  Lemma trav_coherence (C C' : trav_config) (T : traverse C C')\n        (H : tc_coherent G sc C):\n    tc_coherent G sc C'.\n  Proof using.\n    apply clos_trans_tn1 in T.\n    induction T; eapply trav_step_coherence; eauto.\n  Qed.\n  \n  Lemma init_trav_coherent : tc_coherent G sc init_trav.\n  Proof using WF IMMCON.\n    unfold init_trav.\n    red; splits; ins.\n    { unfold coverable; ins.\n      repeat (splits; try apply set_subset_inter_r).\n      basic_solver.\n      rewrite no_sb_to_init; unfold dom_cond; basic_solver.\n      generalize (init_w WF); basic_solver 12. }\n    unfold issuable; ins.\n    repeat (splits; try apply set_subset_inter_r).\n    { basic_solver. }\n    { generalize (init_w WF); basic_solver 12. }\n    { rewrite fwbob_in_bob, bob_in_sb, no_sb_to_init; unfold dom_cond; basic_solver. }\n    eapply dom_cond_in with (r' := fun _ _ => False).\n    rewrite id_inter. rewrite ct_end, !seqA.\n    arewrite ((ar G sc \u222a rf \u2a3e ppo \u2229 same_loc) \u2a3e \u2997Init\u2998 \u2286 \u2205\u2082).\n    { by apply no_ar_rf_ppo_loc_to_init. }\n    basic_solver.\n  Qed.\n\n(******************************************************************************)\n(**  **   *)\n(******************************************************************************)\n\n  Lemma exists_next P e \n        (ACTS : E e)\n        (N_COV : ~ P e) :\n    exists e', sb^? e' e /\\ next G P e'.\n  Proof using.\n    generalize dependent e.\n    set (Q e := E e -> ~ P e ->\n                exists e' : actid, sb^? e' e /\\ next G P e').\n    apply (@well_founded_ind _ sb (wf_sb G) Q).\n    ins; subst Q; simpls.\n    destruct (classic (exists e', sb e' x /\\ ~ P e')) as\n        [[e' [H' COV]]| H']; ins.\n    { assert (E e') as ACTS.\n      { apply seq_eqv_l in H'; desf. }\n      specialize (H e' H' ACTS COV).\n      destruct H as [z [X Y]].\n      exists z; split; auto.\n      right.\n      red in X; desf.\n      eapply sb_trans; eauto. }\n    exists x; splits; [by left|]; red; splits; auto.\nunfolder; splits; eauto.\nunfold dom_cond; unfolder.\nins; desc; subst.\n    destruct (classic (P x0)); auto.\n    exfalso; apply H'; vauto.\n  Qed.\n  \n  Lemma exists_trav_step T (TCCOH : tc_coherent G sc T)\n        e (N_FIN : next G (covered T) e)\n        (FSUPP : fsupp (\u2997set_compl is_init\u2998 \u2a3e (ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a)) :\n    exists T', trav_step T T'.\n  Proof using WF IMMCON.\n    assert (wf_sc G sc) as WFSC by apply IMMCON.\n    assert (complete G) as COM by apply IMMCON.\n\n    rename e into e'.\n    destruct (forall_not_or_exists (next G (covered T)) W)\n      as [WNEXT|NWNEXT].\n    { desf.\n      destruct (classic (issued T e)).\n      { exists (mkTC (covered T \u222a\u2081 (eq e)) (issued T)).\n        destruct T as [C I]; simpls.\n        exists e; left; unnw; splits; simpls.\n        { apply WNEXT. }\n        unfold coverable. split; [by apply WNEXT|].\n        left; unnw; basic_solver. }\n      exists (mkTC (covered T) (issued T \u222a\u2081 (eq e))).\n      destruct T as [C I]; simpl in *.\n      exists e; right; unnw; splits; simpls; try basic_solver.\n      eapply issuable_next_w; eauto.\n      by unfolder. }\n    destruct (forall_not_or_exists (next G (covered T)) (coverable G sc T)) \n      as [COV|NCOV].\n    { desf.\n      exists (mkTC (covered T \u222a\u2081 (eq e)) (issued T)).\n      exists e; left; splits; simpls; auto.\n      apply COV. }\n\n    assert ((exists w, W w /\\ ~ issued T w /\\ E w) ->\n            exists w, W w /\\ ~ issued T w /\\\n                      dom_cond (\u2997W\u2998 \u2a3e (ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a) (issued T) w /\\\n                      E w) as WMIN.\n    { intros P; desf.\n      induction w using (well_founded_ind (wf_ar_rf_ppo_loc_ct WF COM IMMCON FSUPP)).\n      destruct (classic (dom_cond (\u2997W\u2998 \u2a3e (ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a) (issued T) w)); eauto.\n      unfolder in H0. unfold dom_rel in H0.\n      apply not_all_ex_not in H0; desf.\n      apply not_all_ex_not in H0; desf.\n      eapply H; eauto.\n      { apply seq_eqv_l. split; auto.\n        apply wf_ar_rf_ppo_loc_ctE, seq_eqv_lr in n3; auto.   \n        intros Iz0. forward eapply init_issued with (x := z0); eauto.\n        basic_solver 10. }\n\n      cdes IMMCON.\n      apply wf_ar_rf_ppo_loc_ctE in n3; auto. by destruct_seq_l n3 as AA. }\n\n    assert ((exists f, (F\u2229\u2081Sc) f  /\\ ~ covered T f /\\ E f) ->\n            exists f, (F\u2229\u2081Sc) f /\\ ~ covered T f /\\\n                      doma (\u2997F\u2229\u2081Sc\u2998 \u2a3e (ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a \u2a3e \u2997eq f\u2998) (covered T) /\\\n                      E f) as FMIN.\n    { intros P; desf.\n      induction f using (well_founded_ind (wf_ar_rf_ppo_loc_ct WF COM IMMCON FSUPP)).\n      destruct (classic (doma (\u2997F\u2229\u2081Sc\u2998 \u2a3e (ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a \u2a3e \u2997eq f\u2998) (covered T)))\n        as [H0 | H0]; eauto.\n      rewrite seq_eqv_r, seq_eqv_l in H0.\n      unfold doma in H0.\n      apply not_all_ex_not in H0; desf.\n      apply not_all_ex_not in H0; desf.\n      apply imply_to_and in H0; desf.\n      eapply H; eauto.\n      2: { apply wf_ar_rf_ppo_loc_ctE, seq_eqv_lr in H2; auto. by desc. }\n      cdes IMMCON.\n      (* apply wf_ar_rf_ppo_loc_ctE in H2; auto. *)\n      apply seq_eqv_l. split; auto. eapply read_or_fence_is_not_init; eauto.\n      type_solver. }\n\n    assert (forall n, next G (covered T) n ->\n                      R n \\/ (F\u2229\u2081Sc) n) as RorF.\n    { intros; destruct (lab_rwf lab n); auto.\n      desf.\n      { by apply NWNEXT in H. }\n      right. split; auto.\n      destruct (classic (is_sc lab n)) as [|NEQ]; [done|exfalso].\n      set (NN := H).\n      apply NCOV in NN.\n      unfold coverable in NN.\n      apply not_and_or in NN; desf; apply NN.\n      { apply H. }\n      right; split; auto.\n      cdes IMMCON.\n      unfold dom_cond. rewrite (wf_scD Wf_sc).\n      type_solver. }\n    \n    assert (forall r, R r -> next G (covered T) r ->\n                      ~ coverable G sc T r ->\n      exists w, W w /\\ rf w r /\\ ~ issued T w) as WIS.\n    { clear NCOV. intros r RR RNEXT NCOV.\n      unfold coverable in NCOV.\n      apply not_and_or in NCOV; desf.\n      { exfalso; apply NCOV. apply RNEXT. }\n      apply not_or_and in NCOV; desf.\n      apply not_or_and in NCOV; desf.\n      apply not_and_or in NCOV1; desf.\n      assert (exists w, rf w r) as [w RF].\n      { edestruct COM; esplit; eauto.\n        apply RNEXT. }\n      exists w; splits; auto.\n      { apply (wf_rfD WF) in RF.\n        apply seq_eqv_l in RF; desf. }\n      intros II. apply NCOV1.\n      intros x [y H]. apply seq_eqv_r in H; desf.\n      assert (w = x); [|by subst].\n      eapply (wf_rff WF); eauto. }\n\n    destruct (forall_not_or_exists (next G (covered T)) R)\n      as [RNEXT|NRNEXT].\n    { desf.\n      assert (exists w', W w' /\\ ~ issued T w' /\\ E w') as XW.\n      { destruct (WIS e RNEXT0 RNEXT) as [w'].\n        { eapply NCOV; eauto. }\n        exists w'; splits; desf.\n        apply wf_rfE in H0; auto.\n        apply seq_eqv_l in H0; desf. }\n      assert (WMIN := WMIN XW).\n      clear XW.\n      desf.\n      assert (~ covered T w) as WNCOV.\n      { intro H. apply WMIN0. \n          by apply (w_covered_issued TCCOH); split. }\n      destruct (exists_next (covered T) w WMIN2 WNCOV) as [n NSB]; desf.\n      destruct NSB as [HSB|HSB]; desf.\n      { exfalso; eapply NWNEXT; eauto. }\n      exists (mkTC (covered T) (issued T \u222a\u2081 (eq w))).\n      exists w; right; unnw; splits; simpls.\n\n      set (nRorF := RorF).\n      specialize (nRorF n NSB0).\n      split; [split; [split|]|]; auto.\n      intros x [y H]; desc; subst.\n      apply seq_eqv_r in H. desc; subst.\n      apply NNPP; intro COVX.\n      \n      assert (sb x y) as SBXY.\n      { by apply bob_in_sb, fwbob_in_bob. }\n      assert (sb^? n x) as NX.\n      { destruct (eq_dec_actid n x) as [EQNX|NEQNX]; [by left|right].\n        edestruct (sb_semi_total_r ) as [LL|RR]; eauto.\n        { intros H'. apply COVX.\n          apply TCCOH; vauto.\n          apply (@wf_sbE G) in SBXY.\n          unfolder in SBXY; basic_solver. }\n        exfalso; apply COVX.\n        eapply NSB0; basic_solver 12. }\n\n      assert (fwbob\u207a n y) as BOB.\n      { destruct NX as [NX|NX]; subst; [by apply t_step|].\n        apply sb_fwbob_in_fwbob.\n        eexists; eauto. }\n      clear x H COVX NX SBXY.\n      desf.\n      { assert (NY := NSB0).\n        apply NCOV in NSB0.\n        unfold coverable in NSB0.\n        apply not_and_or in NSB0; desf.\n        { exfalso; apply NSB0. apply NY. }\n        apply not_or_and in NSB0; desf.\n        apply not_or_and in NSB0; desf.\n        apply NSB2; unnw; split; auto.\n        clear NSB0 NSB1 NSB2.\n        red. intros x' [y' H'].\n        apply seq_eqv_r in H'; desf.\n        apply rfi_union_rfe in H'; destruct H' as [RFI|RFE].\n        { destruct RFI as [RF SBXY].\n          apply (w_covered_issued TCCOH); split.\n          2: by eapply NY; eexists; apply seq_eqv_r; eauto.\n          apply (wf_rfD WF) in RF.\n          apply seq_eqv_l in RF; desf. }\n        eapply WMIN1.\n        eexists. apply seq_eqv_r. split; eauto.\n        apply seq_eqv_l; split.\n        { apply wf_rfeD in RFE; auto;\n            apply seq_eqv_l in RFE; desf. }\n        eapply ct_ct. exists y'.\n        split.\n        { apply t_step. left. by apply rfe_in_ar. }\n        hahn_rewrite fwbob_in_bob in BOB.\n        hahn_rewrite bob_in_ar in BOB.\n        eapply clos_trans_mori.\n        2: by apply BOB.\n        basic_solver. }\n      assert (exists f, (F\u2229\u2081Sc) f /\\ ~ covered T f /\\ E f) as FF.\n      { exists n; splits; auto; apply NSB0. }\n      specialize (FMIN FF); clear FF; desf.\n      destruct (exists_next (covered T) f FMIN2 FMIN0) as [m MSB]; desf.\n      destruct MSB as [MSB|MSB].\n      { desf.\n        specialize (NCOV f MSB0).\n        apply NCOV. split.\n        { apply MSB0. }\n        right; split; auto.\n        { type_solver. }\n        intros x [z X]. apply seq_eqv_r in X; desf.\n        eapply FMIN1.\n        apply seq_eqv_l; split.\n        { cdes IMMCON. apply (wf_scD Wf_sc) in X. apply seq_eqv_l in X; desf. }\n        apply seq_eqv_r; split; auto.\n        apply t_step. red. left. by apply sc_in_ar. }\n      assert (R m) as RM.\n      { specialize (RorF m MSB0).\n        desf; auto.\n        exfalso.\n        destruct MSB0 as [MSB1 MSB2].\n        apply MSB2.\n        eapply FMIN1.\n        hahn_rewrite seq_eqv_r.\n        hahn_rewrite seq_eqv_l.\n        splits; eauto.\n        apply t_step. left. apply bob_in_ar.\n        apply sb_to_f_in_bob.\n        apply seq_eqv_r. split; auto.\n        mode_solver. }\n      destruct (WIS m RM MSB0) as [w' [WW [WRF WI]]].\n      { by apply NCOV. }\n      apply WI.\n      eapply WMIN1.\n      eexists. apply seq_eqv_r. splits; eauto.\n      hahn_rewrite seq_eqv_l; splits; auto.\n\n      assert ((ar G sc)\u207a w' f) as wfWF'.\n      { apply rfi_union_rfe in WRF; destruct WRF as [[RFI SB]|RFE].\n        { assert (sb w' f) as SB'.\n          { eapply sb_trans; eauto. }\n          apply t_step.\n          apply (bob_in_ar sc).\n          apply sb_to_f_in_bob.\n          apply seq_eqv_r. split; auto.\n          mode_solver. }\n        eapply t_trans; apply t_step.\n        { apply rfe_in_ar; eauto. }\n        apply bob_in_ar.\n        apply sb_to_f_in_bob.\n        apply seq_eqv_r. split; auto.\n        mode_solver. }\n      assert ((ar G sc \u222a rf \u2a3e ppo \u2229 same_loc)\u207a w' f) as wfWF.\n      { eapply clos_trans_mori.\n        2: by apply wfWF'.\n        basic_solver. }\n      eapply t_trans; [apply wfWF|].\n      apply rt_ct; exists n.\n      split.\n      2: eapply clos_trans_mori; [|by apply BOB].\n      2: rewrite fwbob_in_bob; rewrite bob_in_ar; basic_solver.\n      destruct (classic (f = n)) as [|FNEQ]; subst.\n      { apply rt_refl. }\n      apply rt_step. left. apply sc_in_ar.\n      cdes IMMCON.\n      edestruct wf_sc_total as [J|J]; eauto.\n      { split; [split|].\n        2,3: by apply FMIN.\n        apply (dom_r (wf_sbE G)) in MSB.\n        apply seq_eqv_r in MSB. desf. }\n      { split; [split|].\n        2,3: by apply nRorF.\n        apply (dom_l (wf_sbE G)) in HSB.\n        apply seq_eqv_l in HSB. desf. }\n      exfalso.\n      apply NSB0.\n      eapply FMIN1.\n      apply seq_eqv_l; split; auto.\n      apply seq_eqv_r; split; eauto.\n      apply t_step. left. by apply sc_in_ar. }\n\n  assert (forall e, next G (covered T) e -> (F\u2229\u2081Sc) e) as FSC.\n    { intros e H.\n      specialize (NWNEXT e H); specialize (NCOV e H);\n        specialize (NRNEXT e H).\n      destruct (lab_rwf lab e) as [ | [| FF]]; vauto; split; auto.\n      destruct (classic (Sc e)) as [SC|NSC]; auto.\n      exfalso. apply NCOV; split.\n      { apply H. }\n      right; split; auto.\n      unfold dom_cond. red.\n      ins. destruct H0 as [y H0].\n      apply seq_eqv_r in H0; desf.\n      eapply wf_scD in H0.\n      2: by apply IMMCON.\n      apply seq_eqv_l in H0. destruct H0 as [_ H0].\n      apply seq_eqv_r in H0.\n      mode_solver. }\n    assert (exists f', (F\u2229\u2081Sc) f' /\\ ~ covered T f' /\\ E f') as XF.\n    { exists e'; splits; try by apply N_FIN.\n        by apply FSC. }\n    exfalso.\n    destruct (FMIN XF) as [esc X]; desf.\n    destruct (exists_next (covered T) esc X2 X0); desf.\n    destruct H; desf.\n    { eapply NCOV; eauto.\n      split; [apply H0|].\n      right; split; [by apply X|].\n      intros x [y H]. eapply X1.\n      apply seq_eqv_r in H; desf.\n      apply seq_eqv_l; split.\n      { eapply wf_scD in H.\n        2: by apply IMMCON.\n        apply seq_eqv_l in H; desf. }\n      apply seq_eqv_r; split; auto.\n      apply t_step. left. by apply sc_in_ar. }\n    specialize (FSC _ H0).\n    apply (NCOV _ H0). destruct TCCOH; desf. apply CC.\n    rewrite seq_eqv_r, seq_eqv_l in X1.\n    eapply X1.\n    splits; eauto.\n    apply t_step. left. apply bob_in_ar.\n    apply sb_to_f_in_bob.\n    apply seq_eqv_r. split; auto.\n    mode_solver.\n  Qed.\n\nEnd Traversal.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/traversal/Traversal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16243229087044808}}
{"text": "From Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics Seqs.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBExport.\nFrom BBCache Require Import BitBlastingInit CacheFlatten BitBlastingCCacheExport BitBlastingCacheExport.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(* ==== bit_blast_exp_fccache and bit_blast_bexp_fccache ==== *)\n\n(* The bit-blasting with complete information is used for correctness. *)\n\nFrom BBCache Require Import CCacheFlatten.\n\nFixpoint bit_blast_exp_fccache E m c g e : vm * ccache * generator * seq cnf * word :=\n  (* = bit_blast_exp_nocet = *)\n  let bit_blast_exp_nocet E m c g e : vm * ccache * generator * seq cnf * word * seq cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e c with\n        | Some (cs, ls) => (m, c, g, cs, ls, cs)\n        | None =>\n          match SSAVM.find v m with\n          | None => let '(g', cs, rs) := bit_blast_var E g v in\n                    (SSAVM.add v rs m, add_het e [:: cs] rs c, g', [:: cs], rs, [:: cs])\n          | Some rs => (m, add_het e [::] rs c, g, [::], rs, [::])\n          end\n        end\n      | QFBV.Econst bs =>\n        match find_het e c with\n        | Some (cs, ls) => (m, c, g, cs, ls, cs)\n        | None => let '(g', cs, rs) := bit_blast_const g bs in\n                  (m, add_het e [:: cs] rs c, g', [:: cs], rs, [:: cs])\n        end\n      | QFBV.Eunop op e1 =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_fccache E m c g e1 in\n        match find_het e c1 with\n        | Some (csop, lsop) => (m1, c1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_eunop op g1 ls1 in\n          (m1, add_het e [:: csop] lsop c1, gop,\n           catrev cs1 [:: csop], lsop, [:: csop])\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_fccache E m c g e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_fccache E m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_ebinop op g2 ls1 ls2 in\n          (m2, add_het e [:: csop] lsop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lsop, [:: csop])\n        end\n      | QFBV.Eite b e1 e2 =>\n        let '(mb, cb, gb, csb, lb) := bit_blast_bexp_fccache E m c g b in\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_fccache E mb cb gb e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_fccache E m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) =>\n          (m2, c2, g2, catrev csb (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_ite g2 lb ls1 ls2 in\n          (m2, add_het e [:: csop] lsop c2, gop,\n           catrev csb (catrev cs1 (catrev cs2 [:: csop])), lsop, [:: csop])\n        end\n      end\n  (* = = *)\n  in\n  match find_cet e c with\n  | Some (cs, ls) => (m, c, g, [::], ls)\n  | None => let '(m', c', g', cs, lrs, csop) := bit_blast_exp_nocet E m c g e in\n            (m', CCacheFlatten.add_cet e csop lrs c', g', cs, lrs)\n  end\nwith\nbit_blast_bexp_fccache E m c g e : vm * ccache * generator * seq cnf * literal :=\n  (* = bit_blast_bexp_nocbt = *)\n  let bit_blast_bexp_nocbt E m c g e : vm * ccache * generator * seq cnf * literal * seq cnf :=\n      match e with\n      | QFBV.Bfalse =>\n        match find_hbt e c with\n        | Some (cs, l) => (m, c, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_ff c, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue =>\n        match find_hbt e c with\n        | Some (cs, l) => (m, c, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_tt c, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(m1, c1, g1, cs1, ls1) := bit_blast_exp_fccache E m c g e1 in\n        let '(m2, c2, g2, cs2, ls2) := bit_blast_exp_fccache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None =>\n          let '(gop, csop, lop) := bit_blast_bbinop op g2 ls1 ls2 in\n          (m2, add_hbt e [:: csop] lop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      | QFBV.Blneg e1 =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_fccache E m c g e1 in\n        match find_hbt e c1 with\n        | Some (csop, lop) => (m1, c1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_lneg g1 l1 in\n                  (m1, add_hbt e [:: csop] lop c1, gop,\n                   catrev cs1 [:: csop], lop, [:: csop])\n        end\n      | QFBV.Bconj e1 e2 =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_fccache E m c g e1 in\n        let '(m2, c2, g2, cs2, l2) := bit_blast_bexp_fccache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_conj g2 l1 l2 in\n                  (m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      | QFBV.Bdisj e1 e2 =>\n        let '(m1, c1, g1, cs1, l1) := bit_blast_bexp_fccache E m c g e1 in\n        let '(m2, c2, g2, cs2, l2) := bit_blast_bexp_fccache E m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_disj g2 l1 l2 in\n                  (m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      end\n  (* = = *)\n  in\n  match find_cbt e c with\n  | Some (cs, l) => (m, c, g, [::], l)\n  | None => let '(m', c', g', cs, lr, csop) := bit_blast_bexp_nocbt E m c g e in\n            (m', CCacheFlatten.add_cbt e csop lr c', g', cs, lr)\n  end.\n\nDefinition init_fccache : ccache := CCacheFlatten.empty.\n\nLemma init_fccache_compatible : ccache_compatible init_fccache init_ccache.\nProof. done. Qed.\n\nLtac dcase_bb_base :=\n  match goal with\n  | |- context f [bit_blast_var ?E ?g ?v] =>\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_var E g v) => [[[g' cs] lrs] H]\n  | |- context f [bit_blast_eunop ?op ?g ?lrs] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (bit_blast_eunop op g lrs) => [[[g' cs'] lrs'] H]\n  | |- context f [bit_blast_ebinop ?op ?g ?lrs1 ?lrs2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (bit_blast_ebinop op g lrs1 lrs2) => [[[g' cs'] lrs'] H]\n  | |- context f [bit_blast_ite ?g ?lr ?ls1 ?ls2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (bit_blast_ite g lr ls1 ls2) => [[[g' cs'] lr'] H]\n  | |- context f [bit_blast_bbinop ?op ?g ?lrs1 ?lrs2] =>\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (bit_blast_bbinop op g lrs1 lrs2) => [[[g' cs'] lr'] H]\n  end.\n\nLtac dcase_bb_ccache :=\n  match goal with\n  | |- context f [find_cet ?e ?c] =>\n    let Hfe_cet := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (find_cet e c); case=> [[cs lrs]|] Hfe_cet\n  | |- context f [find_cbt ?e ?c] =>\n    let Hfe_cbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (find_cbt e c); case=> [[cs lr]|] Hfe_cbt\n  | |- context f [find_het ?e ?c] =>\n    let Hfe_het := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (find_het e c); case=> [[cs lrs]|] Hfe_het\n  | |- context f [find_hbt ?e ?c] =>\n    let Hfe_hbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (find_hbt e c); case=> [[cs lr]|] Hfe_hbt\n  (**)\n  | |- context f [SSAVM.find ?v ?m] =>\n    let lrs := fresh in\n    case: (SSAVM.find v m) => [lrs|]\n  | |- context f [bit_blast_exp_fccache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_fccache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_fccache ?E ?m ?ec ?g ?e] =>\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_fccache E m ec g e) =>\n    [[[[[m' ec'] g'] cs] lr] H]\n  | |- context f [bit_blast_exp_ccache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (bit_blast_exp_ccache E m c g e) =>\n    [[[[[m' c'] g'] cs] lrs] H]\n  | |- context f [bit_blast_bexp_ccache ?E ?m ?c ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (bit_blast_bexp_ccache E m c g e) =>\n    [[[[[m' c'] g'] cs] lr] H]\n  (**)\n  | |- _ => dcase_bb_base\n  end.\n\nLtac simpl_ccache_compatible :=\n  match goal with\n  | |- ccache_compatible (add_cet ?e ?ecs ?lrs _) (CompCache.add_cet ?e ?cs ?lrs _) =>\n    apply: ccache_compatible_add_cet\n  | |- ccache_compatible (add_cbt ?e ?ecs ?lr _) (CompCache.add_cbt ?e ?cs ?lr _) =>\n    apply: ccache_compatible_add_cbt\n  | |- ccache_compatible (add_het ?e ?ecs ?lrs _) (CompCache.add_het ?e ?cs ?lrs _) =>\n    apply: ccache_compatible_add_het\n  | |- ccache_compatible (add_hbt ?e ?ecs ?lrs _) (CompCache.add_hbt ?e ?cs ?lrs _) =>\n    apply: ccache_compatible_add_hbt\n  | |- cnf_eqsat (tflatten [:: ?cs]) ?cs => exact: tflatten_singleton_eqsat\n  | |- cnf_eqsat (tflatten (catrev _ _)) ?cs => apply: tflatten_catrev_eqsat\n  | |- cnf_eqsat (tflatten [::]) [::] => done\n  (**)\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_cet ?e ?ec = None |- context f [CompCache.find_cet ?e ?c] =>\n    move/(ccache_compatible_find_cet_none _ Hc): H => H; rewrite H\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_cbt ?e ?ec = None |- context f [CompCache.find_cbt ?e ?c] =>\n    move/(ccache_compatible_find_cbt_none _ Hc): H => H; rewrite H\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_het ?e ?ec = None |- context f [CompCache.find_het ?e ?c] =>\n    move/(ccache_compatible_find_het_none _ Hc): H => H; rewrite H\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_hbt ?e ?ec = None |- context f [CompCache.find_hbt ?e ?c] =>\n    move/(ccache_compatible_find_hbt_none _ Hc): H => H; rewrite H\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_cet ?e ?ec = Some _ |- context f [CompCache.find_cet ?e ?c] =>\n    let cs := fresh in\n    let Hf_cet := fresh in\n    let Heqs := fresh in\n    let Heqn := fresh in\n    move: (ccache_compatible_find_cet_some_exists1 Hc H) =>\n    [cs [Hf_cet [Heqs Heqn]]]; rewrite Hf_cet\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_cbt ?e ?ec = Some _ |- context f [CompCache.find_cbt ?e ?c] =>\n    let cs := fresh in\n    let Hf_cbt := fresh in\n    let Heqs := fresh in\n    let Heqn := fresh in\n    move: (ccache_compatible_find_cbt_some_exists1 Hc H) =>\n    [cs [Hf_cbt [Heqs Heqn]]]; rewrite Hf_cbt\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_het ?e ?ec = Some _ |- context f [CompCache.find_het ?e ?c] =>\n    let cs := fresh in\n    let Hf_het := fresh in\n    let Heqs := fresh in\n    let Heqs := fresh in\n    move: (ccache_compatible_find_het_some_exists1 Hc H) =>\n    [cs [Hf_het [Heqs heqn]]]; rewrite Hf_het\n  | Hc : ccache_compatible ?ec ?c,\n    H : find_hbt ?e ?ec = Some _ |- context f [CompCache.find_hbt ?e ?c] =>\n    let cs := fresh in\n    let Hf_hbt := fresh in\n    let Heqs := fresh in\n    let Heqs := fresh in\n    move: (ccache_compatible_find_hbt_some_exists1 Hc H) =>\n    [cs [Hf_hbt [Heqs Heqn]]]; rewrite Hf_hbt\n  end.\n\nLtac solve_eqnew :=\n  match goal with\n  | |- cnf_eqnew (tflatten [::]) [::] => done\n  | |- cnf_eqnew (tflatten [:: ?cs]) ?cs => exact: tflatten_singleton_eqnew\n  | H12 : cnf_eqnew (tflatten ?cs1) ?cs2\n    |- cnf_eqnew (tflatten (catrev ?cs1 ?cs3)) (catrev ?cs2 ?cs4) =>\n    apply: (cnf_eqnew_catrev2 H12)\n  | H34 : cnf_eqnew (tflatten ?cs3) ?cs4\n    |- cnf_eqnew (tflatten (catrev ?cs1 ?cs3)) (catrev ?cs2 ?cs4) =>\n    apply: (cnf_eqnew_catrev2 _ H34)\n  end.\n\nLtac myauto :=\n  repeat\n    match goal with\n    | |- _ /\\ _ => split\n    | |- ?e = ?e => reflexivity\n    | H : ?p |- ?p => assumption\n    | |- (_, _, _, _, _) = (_, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ?; subst\n    (* apply induction hypothesis *)\n    | bit_blast_exp_fccache_valid :\n        (forall (E : SSATE.env)\n               (e : QFBV.exp) (im : vm)\n               (iec : ccache) (ic : CompCache.compcache)\n               (ig : generator) (em : vm)\n               (ec : ccache) (eg : generator)\n               (ecs : seq cnf) (elrs : word)\n               (m : vm) (c : CompCache.compcache)\n               (g : generator) (cs : cnf)\n               (lrs : word),\n            ccache_compatible iec ic ->\n            bit_blast_exp_fccache E im iec ig e = (em, ec, eg, ecs, elrs) ->\n            bit_blast_exp_ccache E im ic ig e =\n            (m, c, g, cs, lrs) ->\n            em = m /\\\n            ccache_compatible ec c /\\\n            eg = g /\\ cnf_eqsat (tflatten ecs) cs /\\ cnf_eqnew (tflatten ecs) cs /\\ elrs = lrs),\n      Hcc : ccache_compatible ?iec ?ic,\n      Hbbe : bit_blast_exp_fccache ?E ?im ?iec ?ig ?e = _,\n      Hbb : bit_blast_exp_ccache ?E ?im ?ic ?ig ?e = _ |- _ =>\n      let Hm := fresh in\n      let Hc := fresh in\n      let Hg := fresh in\n      let Hcs_eqs := fresh in\n      let Hcs_eqn := fresh in\n      let Hlrs:= fresh in\n      move: (bit_blast_exp_fccache_valid\n               _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Hcc Hbbe Hbb);\n      move=> [Hm [Hc [Hg [Hcs_eqs [Hcs_eqn Hlrs]]]]]; subst; clear Hbbe Hbb\n    | bit_blast_bexp_fccache_valid :\n        (forall (E : SSATE.env)\n                (e : QFBV.bexp) (im : vm)\n                (iec : ccache) (ic : CompCache.compcache)\n                (ig : generator) (em : vm)\n                (ec : ccache) (eg : generator)\n                (ecs : seq cnf) (elr : literal)\n                (m : vm) (c : CompCache.compcache)\n                (g : generator) (cs : cnf)\n                (lr : literal),\n            ccache_compatible iec ic ->\n            bit_blast_bexp_fccache E im iec ig e = (em, ec, eg, ecs, elr) ->\n            bit_blast_bexp_ccache E im ic ig e = (m, c, g, cs, lr) ->\n            em = m /\\\n            ccache_compatible ec c /\\\n            eg = g /\\ cnf_eqsat (tflatten ecs) cs /\\ cnf_eqnew (tflatten ecs) cs /\\ elr = lr),\n      Hcc : ccache_compatible ?iec ?ic,\n      Hbbe : bit_blast_bexp_fccache ?E ?im ?iec ?ig ?e = _,\n      Hbb : bit_blast_bexp_ccache ?E ?im ?ic ?ig ?e = _ |- _ =>\n      let Hm := fresh in\n      let Hc := fresh in\n      let Hg := fresh in\n      let Hcs_eqs := fresh in\n      let Hcs_eqn := fresh in\n      let Hlr:= fresh in\n      move: (bit_blast_bexp_fccache_valid\n               _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Hcc Hbbe Hbb);\n      move=> [Hm [Hc [Hg [Hcs_eqs [Hcs_eqn Hlr]]]]]; subst; clear Hbbe Hbb\n    (**)\n    | |- _ => simpl_ccache_compatible || dcase_bb_ccache || solve_eqnew\n    end.\n\nLemma bit_blast_exp_fccache_valid\n      E e im iec ic ig em ec eg ecs elrs m c g cs lrs :\n  ccache_compatible iec ic ->\n  bit_blast_exp_fccache E im iec ig e = (em, ec, eg, ecs, elrs) ->\n  bit_blast_exp_ccache E im ic ig e = (m, c, g, cs, lrs) ->\n  em = m\n  /\\ ccache_compatible ec c\n  /\\ eg = g\n  /\\ cnf_eqsat (tflatten ecs) cs\n  /\\ cnf_eqnew (tflatten ecs) cs\n  /\\ elrs = lrs\nwith\nbit_blast_bexp_fccache_valid E e im iec ic ig em ec eg ecs elr m c g cs lr :\n  ccache_compatible iec ic ->\n  bit_blast_bexp_fccache E im iec ig e = (em, ec, eg, ecs, elr) ->\n  bit_blast_bexp_ccache E im ic ig e = (m, c, g, cs, lr) ->\n  em = m\n  /\\ ccache_compatible ec c\n  /\\ eg = g\n  /\\ cnf_eqsat (tflatten ecs) cs\n  /\\ cnf_eqnew (tflatten ecs) cs\n  /\\ elr = lr.\nProof.\n  (* bit_blast_exp_fccache_valid *)\n  move=> Hcc. case: e => /=.\n  - move=> v. by myauto.\n  - move=> bs. by myauto.\n  - move=> op e. by myauto.\n  - move=> op e1 e2. by myauto.\n  - move=> e1 e2 e3. by myauto.\n  (* bit_blast_bexp_fccache_valid *)\n  move=> Hcc. case: e => /=.\n  - by myauto.\n  - by myauto.\n  - move=> op e1 e2. by myauto.\n  - move=> e. by myauto.\n  - move=> e1 e2. by myauto.\n  - move=> e1 e2. by myauto.\nQed.\n\nTheorem bit_blast_bexp_fccache_sound E e m c g cs lr :\n  bit_blast_bexp_fccache\n    E init_vm init_fccache init_gen e = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  ~ (sat (add_prelude ([::neg_lit lr]::(tflatten cs)))) ->\n  (forall s, AdhereConform.conform_bexp e s E ->\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hbbe Hwf Hsat.\n  dcase (bit_blast_bexp_ccache E init_vm init_ccache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexp_fccache_valid\n           (init_fccache_compatible) Hbbe Hbb) => [Hm [Hcc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  apply: (bit_blast_ccache_sound Hbb Hwf). move=> Hs. apply: Hsat.\n  move: (cnf_eqsat_cons (clause_eqsat_refl [:: neg_lit lr']) Heqs) => Heqs'.\n  apply/(cnf_eqsat_add_prelude_sat Heqs'). assumption.\nQed.\n\nTheorem bit_blast_bexp_fccache_complete E e m c g cs lr :\n  bit_blast_bexp_fccache E init_vm init_fccache init_gen e = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (forall s, AdhereConform.conform_bexp e s E ->\n             QFBV.eval_bexp e s) ->\n  ~ (sat (add_prelude ([::neg_lit lr]::(tflatten cs)))).\nProof.\n  move=> Hbbe Hwf Hev.\n  dcase (bit_blast_bexp_ccache E init_vm init_ccache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexp_fccache_valid\n           (init_fccache_compatible) Hbbe Hbb) => [Hm [Hcc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  move=> Hs. move: (cnf_eqsat_cons (clause_eqsat_refl [:: neg_lit lr']) Heqs) => Heqs'.\n  move/(cnf_eqsat_add_prelude_sat Heqs'): Hs => {Heqs'}.\n  exact: (bit_blast_ccache_complete Hbb Hwf Hev).\nQed.\n\nTheorem bit_blast_bexp_fccache_sat_sound E e m c g cs lr :\n  bit_blast_bexp_fccache\n    E init_vm init_fccache init_gen e = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (sat (add_prelude ([::lr]::(tflatten cs)))) ->\n  (exists s, AdhereConform.conform_bexp e s E /\\\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hbbe Hwf Hsat.\n  dcase (bit_blast_bexp_ccache E init_vm init_ccache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexp_fccache_valid\n           (init_fccache_compatible) Hbbe Hbb) => [Hm [Hcc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  apply: (bit_blast_ccache_sat_sound Hbb Hwf).\n  move: (cnf_eqsat_cons (clause_eqsat_refl [:: lr']) Heqs) => Heqs'.\n  apply/(cnf_eqsat_add_prelude_sat Heqs'). assumption.\nQed.\n\nTheorem bit_blast_bexp_fccache_sat_complete E e m c g cs lr :\n  bit_blast_bexp_fccache E init_vm init_fccache init_gen e = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexp e E ->\n  (exists s, AdhereConform.conform_bexp e s E /\\\n             QFBV.eval_bexp e s) ->\n  (sat (add_prelude ([::lr]::(tflatten cs)))).\nProof.\n  move=> Hbbe Hwf Hev.\n  dcase (bit_blast_bexp_ccache E init_vm init_ccache init_gen e) =>\n  [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexp_fccache_valid\n           (init_fccache_compatible) Hbbe Hbb) => [Hm [Hcc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  move: (cnf_eqsat_cons (clause_eqsat_refl [:: lr']) Heqs) => Heqs'.\n  apply/(cnf_eqsat_add_prelude_sat Heqs').\n  exact: (bit_blast_ccache_sat_complete Hbb Hwf Hev).\nQed.\n\n\n\n(* ==== general case ==== *)\n\n(* = bit-blasting multiple bexps = *)\n\nDefinition bit_blast_bexp_fccache_tflatten E m c g e :=\n  let '(m', c', g', css', lr') := bit_blast_bexp_fccache E m c g e in\n  (m', c', g', tflatten css', lr').\n\nFixpoint bit_blast_bexps_fccache E (es : seq QFBV.bexp) :=\n  match es with\n  | [::] => (init_vm, init_fccache, init_gen, add_prelude [::], lit_tt)\n  | e :: es' =>\n    let '(m, c, g, cs, lr) := bit_blast_bexps_fccache E es' in\n    bit_blast_bexp_fccache_tflatten E m (CCacheFlatten.reset_ct c) g e\n  end.\n\nLemma bit_blast_bexps_fccache_valid E es m c g cs lr m' c' g' cs' lr' :\n  bit_blast_bexps_fccache E es = (m, c, g, cs, lr) ->\n  bit_blast_bexps_ccache E es = (m', c', g', cs', lr') ->\n  m = m' /\\ ccache_compatible c c' /\\ g = g' /\\ cnf_eqsat cs cs' /\\ cnf_eqnew cs cs' /\\ lr = lr'.\nProof.\n  elim: es m c g cs lr m' c' g' cs' lr' => [| e es IH] m c g cs lr m' c' g' cs' lr' /=.\n  - move=> [] ? ? ? ? ? [] ? ? ? ? ?; subst. done.\n  - dcase (bit_blast_bexps_fccache E es) => [[[[[m1 c1] g1] cs1] lr1] Hbbe1].\n    move=> Hbbe2.\n    dcase (bit_blast_bexps_ccache E es) => [[[[[m1' c1'] g1'] cs1'] lr1'] Hbb1].\n    move=> Hbb2. move: (IH _ _ _ _ _ _ _ _ _ _ Hbbe1 Hbb1).\n    move=> [Hn [Hc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n    move: Hbbe2. rewrite /bit_blast_bexp_fccache_tflatten.\n    dcase (bit_blast_bexp_fccache E m1' (reset_ct c1) g1' e) =>\n    [[[[[m'' c''] g''] cs''] lrs''] Hbbe1']. case=> ? ? ? ? ?; subst.\n    exact: (bit_blast_bexp_fccache_valid (ccache_compatible_reset_ct Hc)\n                                           Hbbe1' Hbb2).\nQed.\n\nTheorem bit_blast_bexps_fccache_sound e es E m c g cs lr :\n  bit_blast_bexps_fccache E (e::es) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexps (e::es) E ->\n  ~ (sat (add_prelude ([::neg_lit lr]::cs))) ->\n  (forall s, AdhereConform.conform_bexps (e::es) s E ->\n             QFBV.eval_bexp e s).\nProof.\n  move=> Hbbe Hwf Hsat.\n  dcase (bit_blast_bexps_ccache E (e::es)) => [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexps_fccache_valid Hbbe Hbb).\n  move=> [Hm [Hc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  have Hsat': ~ sat (add_prelude ([:: neg_lit lr'] :: cs')).\n  { move=> H. apply: Hsat.\n    move: (cnf_eqsat_cons (clause_eqsat_refl [:: neg_lit lr']) Heqs) => Heqs'.\n    apply/(cnf_eqsat_add_prelude_sat Heqs'). assumption. }\n  exact: (bit_blast_ccache_sound_general Hbb Hwf Hsat').\nQed.\n\nTheorem bit_blast_bexps_fccache_complete e es E m c g cs lr :\n  bit_blast_bexps_fccache E (e::es) = (m, c, g, cs, lr) ->\n  QFBV.well_formed_bexps (e::es) E ->\n  (forall s, AdhereConform.conform_bexps (e::es) s E ->\n             QFBV.eval_bexp e s) ->\n  ~ (sat (add_prelude ([::neg_lit lr]::cs))).\nProof.\n  move=> Hbbe Hwf Hev Hsat.\n  dcase (bit_blast_bexps_ccache E (e::es)) => [[[[[m' c'] g'] cs'] lr'] Hbb].\n  move: (bit_blast_bexps_fccache_valid Hbbe Hbb).\n  move=> [Hm [Hc [Hg [Heqs [Heqn Hlr]]]]]; subst.\n  have Hsat': sat (add_prelude ([:: neg_lit lr'] :: cs')).\n  { move: (cnf_eqsat_cons (clause_eqsat_refl [:: neg_lit lr']) Heqs) => Heqs'.\n    apply/(cnf_eqsat_add_prelude_sat Heqs'). assumption. }\n  move: Hsat'. exact: (bit_blast_ccache_complete_general Hbb Hwf Hev).\nQed.\n\nDefinition bexp_to_cnf_fccache E m c g e :=\n  let '(m', c', g', cs, lr) := bit_blast_bexp_fccache_tflatten E m c g e in\n  (m', c', g', add_prelude ([::neg_lit lr]::cs)).\n\n\n(* ===== mk_env_exp_fccache and mk_env_bexp_fccache ===== *)\n\nFixpoint mk_env_exp_fccache E s m c g e : env * vm * ccache * generator * seq cnf * word :=\n  (* = bit_blast_exp_nocet = *)\n  let mk_env_exp_nocet E s m c g e : env * vm * ccache * generator * seq cnf * word * seq cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e c with\n        | Some (cs, ls) => (E, m, c, g, cs, ls, cs)\n        | None =>\n          match SSAVM.find v m with\n          | None => let '(E', g', cs, rs) := mk_env_var E g (SSAStore.acc v s) v in\n                    (E', SSAVM.add v rs m, add_het e [:: cs] rs c, g', [:: cs], rs, [:: cs])\n          | Some rs => (E, m, add_het e [::] rs c, g, [::], rs, [::])\n          end\n        end\n      | QFBV.Econst bs =>\n        match find_het e c with\n        | Some (cs, ls) => (E, m, c, g, cs, ls, cs)\n        | None => let '(E', g', cs, rs) := mk_env_const E g bs in\n                  (E', m, add_het e [:: cs] rs c, g', [:: cs], rs, [:: cs])\n        end\n      | QFBV.Eunop op e1 =>\n        let '(E1, m1, c1, g1, cs1, ls1) := mk_env_exp_fccache E s m c g e1 in\n        match find_het e c1 with\n        | Some (csop, lsop) => (E1, m1, c1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_eunop op E1 g1 ls1 in\n          (Eop, m1, add_het e [:: csop] lsop c1, gop,\n           catrev cs1 [:: csop], lsop, [:: csop])\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(E1, m1, c1, g1, cs1, ls1) := mk_env_exp_fccache E s m c g e1 in\n        let '(E2, m2, c2, g2, cs2, ls2) := mk_env_exp_fccache E1 s m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) => (E2, m2, c2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ebinop op E2 g2 ls1 ls2 in\n          (Eop, m2, add_het e [:: csop] lsop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lsop, [:: csop])\n        end\n      | QFBV.Eite b e1 e2 =>\n        let '(Eb, mb, cb, gb, csb, lb) := mk_env_bexp_fccache E s m c g b in\n        let '(E1, m1, c1, g1, cs1, ls1) := mk_env_exp_fccache Eb s mb cb gb e1 in\n        let '(E2, m2, c2, g2, cs2, ls2) := mk_env_exp_fccache E1 s m1 c1 g1 e2 in\n        match find_het e c2 with\n        | Some (csop, lsop) =>\n          (E2, m2, c2, g2, catrev csb (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ite E2 g2 lb ls1 ls2 in\n          (Eop, m2, add_het e [:: csop] lsop c2, gop,\n           catrev csb (catrev cs1 (catrev cs2 [:: csop])), lsop, [:: csop])\n        end\n      end\n  (* = = *)\n  in\n  match find_cet e c with\n  | Some (cs, ls) => (E, m, c, g, [::], ls)\n  | None => let '(E', m', c', g', cs, lrs, csop) := mk_env_exp_nocet E s m c g e in\n            (E', m', CCacheFlatten.add_cet e csop lrs c', g', cs, lrs)\n  end\nwith\nmk_env_bexp_fccache E s m c g e : env * vm * ccache * generator * seq cnf * literal :=\n  (* = bit_blast_bexp_nocbt = *)\n  let mk_env_bexp_nocbt E s m c g e : env * vm * ccache * generator * seq cnf * literal * seq cnf :=\n      match e with\n      | QFBV.Bfalse =>\n        match find_hbt e c with\n        | Some (cs, l) => (E, m, c, g, cs, l, cs)\n        | None => (E, m, add_hbt e [::] lit_ff c, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue =>\n        match find_hbt e c with\n        | Some (cs, l) => (E, m, c, g, cs, l, cs)\n        | None => (E, m, add_hbt e [::] lit_tt c, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(E1, m1, c1, g1, cs1, ls1) := mk_env_exp_fccache E s m c g e1 in\n        let '(E2, m2, c2, g2, cs2, ls2) := mk_env_exp_fccache E1 s m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (E2, m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None =>\n          let '(Eop, gop, csop, lop) := mk_env_bbinop op E2 g2 ls1 ls2 in\n          (Eop, m2, add_hbt e [:: csop] lop c2, gop,\n           catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      | QFBV.Blneg e1 =>\n        let '(E1, m1, c1, g1, cs1, l1) := mk_env_bexp_fccache E s m c g e1 in\n        match find_hbt e c1 with\n        | Some (csop, lop) => (E1, m1, c1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_lneg E1 g1 l1 in\n                  (Eop, m1, add_hbt e [:: csop] lop c1, gop,\n                   catrev cs1 [:: csop], lop, [:: csop])\n        end\n      | QFBV.Bconj e1 e2 =>\n        let '(E1, m1, c1, g1, cs1, l1) := mk_env_bexp_fccache E s m c g e1 in\n        let '(E2, m2, c2, g2, cs2, l2) := mk_env_bexp_fccache E1 s m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (E2, m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_conj E2 g2 l1 l2 in\n                  (Eop, m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      | QFBV.Bdisj e1 e2 =>\n        let '(E1, m1, c1, g1, cs1, l1) := mk_env_bexp_fccache E s m c g e1 in\n        let '(E2, m2, c2, g2, cs2, l2) := mk_env_bexp_fccache E1 s m1 c1 g1 e2 in\n        match find_hbt e c2 with\n        | Some (csop, lop) => (E2, m2, c2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_disj E2 g2 l1 l2 in\n                  (Eop, m2, add_hbt e [:: csop] lop c2, gop,\n                   catrev cs1 (catrev cs2 [:: csop]), lop, [:: csop])\n        end\n      end\n  (* = = *)\n  in\n  match find_cbt e c with\n  | Some (cs, l) => (E, m, c, g, [::], l)\n  | None => let '(E', m', c', g', cs, lr, csop) := mk_env_bexp_nocbt E s m c g e in\n            (E', m', CCacheFlatten.add_cbt e csop lr c', g', cs, lr)\n  end.\n\nLtac dcase_mk_env_ccache :=\n  match goal with\n  (**)\n  | |- context f [SSAVM.find ?v ?m] =>\n    let lrs := fresh in\n    case: (SSAVM.find v m) => [lrs|]\n  | |- context f [mk_env_exp_fccache ?E ?s ?m ?ec ?g ?e] =>\n    let E' := fresh in\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (mk_env_exp_fccache E s m ec g e) =>\n    [[[[[[E' m'] ec'] g'] cs] lrs] H]\n  | |- context f [mk_env_bexp_fccache ?E ?s ?m ?ec ?g ?e] =>\n    let E' := fresh in\n    let m' := fresh in\n    let ec' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (mk_env_bexp_fccache E s m ec g e) =>\n    [[[[[[E' m'] ec'] g'] cs] lr] H]\n  | |- context f [mk_env_exp_ccache ?m ?c ?s ?E ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let E' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (mk_env_exp_ccache m c s E g e) =>\n    [[[[[[m' c'] E'] g'] cs] lrs] H]\n  | |- context f [mk_env_bexp_ccache ?m ?c ?s ?E ?g ?e] =>\n    let m' := fresh in\n    let c' := fresh in\n    let E' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    let H := fresh in\n    dcase (mk_env_bexp_ccache m c s E g e) =>\n    [[[[[[m' c'] E'] g'] cs] lr] H]\n  (**)\n  | |- context f [mk_env_var ?E ?g ?ls ?v] =>\n    let E' := fresh in\n    let g' := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    let H := fresh in\n    dcase (mk_env_var E g ls v) => [[[[E' g'] cs] lrs] H]\n  | |- context f [mk_env_eunop ?op ?E ?g ?lrs] =>\n    let E' := fresh in\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (mk_env_eunop op E g lrs) => [[[[E' g'] cs'] lrs'] H]\n  | |- context f [mk_env_ebinop ?op ?E ?g ?lrs1 ?lrs2] =>\n    let E' := fresh in\n    let g' := fresh in\n    let cs' := fresh in\n    let lrs' := fresh in\n    let H := fresh in\n    dcase (mk_env_ebinop op E g lrs1 lrs2) => [[[[E' g'] cs'] lrs'] H]\n  | |- context f [mk_env_ite ?E ?g ?lr ?ls1 ?ls2] =>\n    let E' := fresh in\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (mk_env_ite E g lr ls1 ls2) => [[[[E' g'] cs'] lr'] H]\n  | |- context f [mk_env_bbinop ?op ?E ?g ?lrs1 ?lrs2] =>\n    let E' := fresh in\n    let g' := fresh in\n    let cs' := fresh in\n    let lr' := fresh in\n    let H := fresh in\n    dcase (mk_env_bbinop op E g lrs1 lrs2) => [[[[E' g'] cs'] lr'] H]\n  end.\n\nLtac myauto ::=\n  repeat\n    match goal with\n    | |- _ /\\ _ => split\n    | |- ?e = ?e => reflexivity\n    | H : ?p |- ?p => assumption\n    | |- (_, _, _, _, _, _) = (_, _, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ? ?; subst\n    | |- (_, _, _, _, _) = (_, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ?; subst\n    | H1 : ?e = Some _, H2 : ?e = None |- _ =>\n      rewrite H1 in H2; discriminate\n    (**)\n    | Hs : is_true (SSATE.vsize ?v ?TE == size ?bs),\n           Henv : mk_env_var ?iE ?ig ?bs ?v = (?oE, ?og, ?ocs, ?olrs),\n                  Hbb : bit_blast_var ?TE ?ig ?v = _ |- _ =>\n      let Hbb' := fresh in\n      rewrite eq_sym in Hs;\n      (move: (mk_env_var_is_bit_blast_var (eqP Hs) Henv) => Hbb');\n      rewrite Hbb in Hbb'; case: Hbb' => ? ? ?; subst\n    | H1 : find_het ?e ?c = Some (?cs1, ?lrs1),\n      H2 : find_het ?e ?c = Some (?cs2, ?lrs2) |- _ =>\n      rewrite H1 in H2; case: H2 => ? ?; subst\n    | H1 : find_hbt ?e ?c = Some (?cs1, ?lr1),\n      H2 : find_hbt ?e ?c = Some (?cs2, ?lr2) |- _ =>\n      rewrite H1 in H2; case: H2 => ? ?; subst\n    | H1 : bit_blast_exp_fccache ?E ?m ?c ?g ?e = (?m1, ?c1, ?g1, ?cs1, ?lrs1),\n      H2 : bit_blast_exp_fccache ?E ?m ?c ?g ?e = (?m2, ?c2, ?g2, ?cs2, ?lrs2) |- _ =>\n      rewrite H1 in H2; case: H2 => ? ? ? ? ?; subst\n    | H1 : bit_blast_bexp_fccache ?E ?m ?c ?g ?e = (?m1, ?c1, ?g1, ?cs1, ?lr1),\n      H2 : bit_blast_bexp_fccache ?E ?m ?c ?g ?e = (?m2, ?c2, ?g2, ?cs2, ?lr2) |- _ =>\n      rewrite H1 in H2; case: H2 => ? ? ? ? ?; subst\n    | H1 : mk_env_eunop ?op ?E ?g ?ls = _,\n      H2 : bit_blast_eunop ?op ?g ?ls = _ |- _ =>\n      let H := fresh in\n      (move: (mk_env_eunop_is_bit_blast_eunop H1) => H); rewrite H2 in H;\n      case: H => ? ? ?; subst\n    | H1 : mk_env_ebinop ?op ?E ?g ?ls1 ?ls2 = _,\n      H2 : bit_blast_ebinop ?op ?g ?ls1 ?ls2 = _ |- _ =>\n      let H := fresh in\n      (move: (mk_env_ebinop_is_bit_blast_ebinop H1) => H); rewrite H2 in H;\n      case: H => ? ? ?; subst\n    | H1 : mk_env_bbinop ?op ?E ?g ?ls1 ?ls2 = _,\n      H2 : bit_blast_bbinop ?op ?g ?ls1 ?ls2 = _ |- _ =>\n      let H := fresh in\n      (move: (mk_env_bbinop_is_bit_blast_bbinop H1) => H); rewrite H2 in H;\n      case: H => ? ? ?; subst\n    | H1 : mk_env_ite ?E ?g ?lc ?ls1 ?ls2 = _,\n      H2 : bit_blast_ite ?g ?lc ?ls1 ?ls2 = _ |- _ =>\n      let H := fresh in\n      (move: (mk_env_ite_is_bit_blast_ite H1) => H); rewrite H2 in H;\n      case: H => ? ? ?; subst\n    (* apply induction hypothesis *)\n    | mk_env_exp_fccache_is_bit_blast_exp_fccache :\n        (forall (e : QFBV.exp)\n                (s : SSAStore.t)\n                (TE : SSATE.env)\n                (iE : env) (im : vm)\n                (ic : ccache) (ig : generator)\n                (oE : env) (om : vm)\n                (oc : ccache) (og : generator)\n                (ocs : seq cnf)\n                (olrs : word),\n            is_true (AdhereConform.conform_exp e s TE) ->\n            is_true (QFBV.well_formed_exp e TE) ->\n            mk_env_exp_fccache iE s im ic ig e =\n            (oE, om, oc, og, ocs, olrs) ->\n            bit_blast_exp_fccache TE im ic ig e =\n            (om, oc, og, ocs, olrs)),\n        Hco : is_true (AdhereConform.conform_exp ?e ?s ?TE),\n        Hwf : is_true (QFBV.well_formed_exp ?e ?TE),\n        Henv : mk_env_exp_fccache ?iE ?s ?im ?ic ?ig ?e = _ |- _ =>\n      let H := fresh \"H\" in\n      (move: (mk_env_exp_fccache_is_bit_blast_exp_fccache _ _ _ _ _ _ _ _ _ _ _ _ _\n                                                          Hco Hwf Henv) => H);\n      clear Henv\n    | mk_env_bexp_fccache_is_bit_blast_bexp_fccache :\n        (forall (e : QFBV.bexp)\n                (s : SSAStore.t)\n                (TE : SSATE.env)\n                (iE : env) (im : vm)\n                (ic : ccache) (ig : generator)\n                (oE : env) (om : vm)\n                (oc : ccache) (og : generator)\n                (ocs : seq cnf)\n                (olr : literal),\n            is_true (AdhereConform.conform_bexp e s TE) ->\n            is_true (QFBV.well_formed_bexp e TE) ->\n            mk_env_bexp_fccache iE s im ic ig e =\n            (oE, om, oc, og, ocs, olr) ->\n            bit_blast_bexp_fccache TE im ic ig e =\n            (om, oc, og, ocs, olr)),\n        Hco : is_true (AdhereConform.conform_bexp ?e ?s ?TE),\n        Hwf : is_true (QFBV.well_formed_bexp ?e ?TE),\n        Henv : mk_env_bexp_fccache ?iE ?s ?im ?ic ?ig ?e = _ |- _ =>\n      let H := fresh \"H\" in\n      (move: (mk_env_bexp_fccache_is_bit_blast_bexp_fccache _ _ _ _ _ _ _ _ _ _ _ _ _\n                                                            Hco Hwf Henv) => H);\n      clear Henv\n    | |- _ => dcase_bb_ccache || dcase_mk_env_ccache\n    end.\n\nLemma mk_env_exp_fccache_is_bit_blast_exp_fccache\n      e s TE iE im ic ig oE om oc og ocs olrs :\n  AdhereConform.conform_exp e s TE ->\n  QFBV.well_formed_exp e TE ->\n  mk_env_exp_fccache iE s im ic ig e = (oE, om, oc, og, ocs, olrs) ->\n  bit_blast_exp_fccache TE im ic ig e = (om, oc, og, ocs, olrs)\nwith\nmk_env_bexp_fccache_is_bit_blast_bexp_fccache\n      e s TE iE im ic ig oE om oc og ocs olr :\n  AdhereConform.conform_bexp e s TE ->\n  QFBV.well_formed_bexp e TE ->\n  mk_env_bexp_fccache iE s im ic ig e = (oE, om, oc, og, ocs, olr) ->\n  bit_blast_bexp_fccache TE im ic ig e = (om, oc, og, ocs, olr).\nProof.\n  (* mk_env_exp_fccache_is_bit_blast_exp_fccache *)\n  case: e => //=.\n  - move=> v Hs Hm. by myauto.\n  - move=> bs _ _. by myauto.\n  - move=> op e Hco Hwf. by myauto.\n  - move=> op e1 e2 /andP [Hco1 Hco2] /andP [/andP [/andP [Hwf1 Hwf2] Hwfs1] Hwfs2].\n    by myauto.\n  - move=> e1 e2 e3 /andP [/andP [Hco1 Hco2] Hco3] /andP [/andP [/andP [Hwf1 Hwf2] Hwf3] Hwfs].\n    by myauto.\n  (* mk_env_bexp_fccache_is_bit_blast_bexp_fccache *)\n  case: e => //=.\n  - move=> _ _. by myauto.\n  - move=> _ _. by myauto.\n  - move=> op e1 e2 /andP [Hco1 Hco2] /andP [/andP [Hwf1 Hwf2] Hwfs]. by myauto.\n  - move=> e Hco Hwf. by myauto.\n  - move=> e1 e2 /andP [Hco1 Hco2] /andP [Hwf1 Hwf2]. by myauto.\n  - move=> e1 e2 /andP [Hco1 Hco2] /andP [Hwf1 Hwf2]. by myauto.\nQed.\n\nLtac dcase_mk_env_compcache :=\n  match goal with\n  | |- context f [CompCache.find_cet ?e ?c] =>\n    let Hfe_cet := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (CompCache.find_cet e c); case=> [[cs lrs]|] Hfe_cet\n  | |- context f [CompCache.find_cbt ?e ?c] =>\n    let Hfe_cbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (CompCache.find_cbt e c); case=> [[cs lr]|] Hfe_cbt\n  | |- context f [CompCache.find_het ?e ?c] =>\n    let Hfe_het := fresh in\n    let cs := fresh in\n    let lrs := fresh in\n    dcase (CompCache.find_het e c); case=> [[cs lrs]|] Hfe_het\n  | |- context f [CompCache.find_hbt ?e ?c] =>\n    let Hfe_hbt := fresh in\n    let cs := fresh in\n    let lr := fresh in\n    dcase (CompCache.find_hbt e c); case=> [[cs lr]|] Hfe_hbt\n  end.\n\nLtac simpl_ccache_compatible_find :=\n  match goal with\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cet ?e ?fc = Some (?fcs, ?flrs),\n    Hf : CompCache.find_cet ?e ?c = Some (?cs, ?lrs) |- _ =>\n    let Heqs := fresh in\n    let Heqn := fresh in\n    let Hlrs := fresh in\n    (move: (ccache_compatible_find_cet_some Hcc Hff Hf) => [Heqs [Heqn Hlrs]]); subst;\n    clear Hff; clear Hf\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cbt ?e ?fc = Some (?fcs, ?flrs),\n    Hf : CompCache.find_cbt ?e ?c = Some (?cs, ?lrs) |- _ =>\n    let Heqs := fresh in\n    let Heqn := fresh in\n    let Hlrs := fresh in\n    (move: (ccache_compatible_find_cbt_some Hcc Hff Hf) => [Heqs [Heqn Hlrs]]); subst;\n    clear Hff; clear Hf\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_het ?e ?fc = Some (?fcs, ?flrs),\n    Hf : CompCache.find_het ?e ?c = Some (?cs, ?lrs) |- _ =>\n    let Heqs := fresh in\n    let Heqn := fresh in\n    let Hlrs := fresh in\n    (move: (ccache_compatible_find_het_some Hcc Hff Hf) => [Heqs [Heqn Hlrs]]); subst;\n    clear Hff; clear Hf\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_hbt ?e ?fc = Some (?fcs, ?flrs),\n    Hf : CompCache.find_hbt ?e ?c = Some (?cs, ?lrs) |- _ =>\n    let Heqs := fresh in\n    let Heqn := fresh in\n    let Hlrs := fresh in\n    (move: (ccache_compatible_find_hbt_some Hcc Hff Hf) => [Heqs [Heqn Hlrs]]); subst;\n    clear Hff; clear Hf\n  (**)\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cet ?e ?fc = Some _,\n    Hf : CompCache.find_cet ?e ?c = None |- _ =>\n    (move/(ccache_compatible_find_cet_none _ Hcc): Hf => Hf);\n    rewrite Hff in Hf; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cbt ?e ?fc = Some _,\n    Hf : CompCache.find_cbt ?e ?c = None |- _ =>\n    (move/(ccache_compatible_find_cbt_none _ Hcc): Hf => Hf);\n    rewrite Hff in Hf; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_het ?e ?fc = Some _,\n    Hf : CompCache.find_het ?e ?c = None |- _ =>\n    (move/(ccache_compatible_find_het_none _ Hcc): Hf => Hf);\n    rewrite Hff in Hf; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_hbt ?e ?fc = Some _,\n    Hf : CompCache.find_hbt ?e ?c = None |- _ =>\n    (move/(ccache_compatible_find_hbt_none _ Hcc): Hf => Hf);\n    rewrite Hff in Hf; discriminate\n  (**)\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cet ?e ?fc = None,\n    Hf : CompCache.find_cet ?e ?c = Some _ |- _ =>\n    (move/(ccache_compatible_find_cet_none _ Hcc): Hff => Hff);\n    rewrite Hf in Hff; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_cbt ?e ?fc = None,\n    Hf : CompCache.find_cbt ?e ?c = Some _ |- _ =>\n    (move/(ccache_compatible_find_cbt_none _ Hcc): Hff => Hff);\n    rewrite Hf in Hff; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_het ?e ?fc = None,\n    Hf : CompCache.find_het ?e ?c = Some _ |- _ =>\n    (move/(ccache_compatible_find_het_none _ Hcc): Hff => Hff);\n    rewrite Hf in Hff; discriminate\n  | Hcc : ccache_compatible ?fc ?c,\n    Hff : find_hbt ?e ?fc = None,\n    Hf : CompCache.find_hbt ?e ?c = Some _ |- _ =>\n    (move/(ccache_compatible_find_hbt_none _ Hcc): Hff => Hff);\n    rewrite Hf in Hff; discriminate\n  end.\n\nLtac myauto ::=\n  repeat\n    match goal with\n    | |- _ /\\ _ => split\n    | |- ?e = ?e => reflexivity\n    | H : ?p |- ?p => assumption\n    | |- (_, _, _, _, _, _) = (_, _, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ? ?; subst\n    | |- (_, _, _, _, _) = (_, _, _, _, _) -> _ =>\n      case=> ? ? ? ? ?; subst\n    | H1 : ?e = Some _, H2 : ?e = None |- _ =>\n      rewrite H1 in H2; discriminate\n    (* apply induction hypothesis *)\n    | mk_env_exp_fccache_valid :\n        (forall (iE : env) (s : SSAStore.t) (e : QFBV.exp)\n                (im : vm) (ifc : ccache) (ic : CompCache.compcache)\n                (ig : generator) (ofE oE : env) (ofm : vm)\n                (ofc : ccache) (ofg : generator) (ofcs : seq cnf)\n                (oflrs : word) (om : vm) (oc : CompCache.compcache)\n                (og : generator) (ocs : cnf) (olrs : word),\n            ccache_compatible ifc ic ->\n            mk_env_exp_fccache iE s im ifc ig e =\n            (ofE, ofm, ofc, ofg, ofcs, oflrs) ->\n            mk_env_exp_ccache im ic s iE ig e = (om, oc, oE, og, ocs, olrs) ->\n            ofE = oE /\\\n            ofm = om /\\\n            ccache_compatible ofc oc /\\\n            ofg = og /\\\n            cnf_eqsat (tflatten ofcs) ocs /\\\n            cnf_eqnew (tflatten ofcs) ocs /\\ oflrs = olrs),\n      Hcc : ccache_compatible ?ifc ?ic,\n      Hv1 : mk_env_exp_fccache ?iE ?s ?im ?ifc ?ig ?e = _,\n      Hv2 : mk_env_exp_ccache ?im ?ic ?s ?iE ?ig ?e = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      let H5 := fresh in\n      let H6 := fresh in\n      let H7 := fresh in\n      (move: (mk_env_exp_fccache_valid _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                       Hcc Hv1 Hv2));\n      (move=> [H1 [H2 [H3 [H4 [H5 [H6 H7]]]]]]);\n      subst; clear Hv1 Hv2\n    | mk_env_bexp_fccache_valid :\n        (forall (iE : env) (s : SSAStore.t) (e : QFBV.bexp)\n                (im : vm) (ifc : ccache) (ic : CompCache.compcache)\n                (ig : generator) (ofE oE : env) (ofm : vm)\n                (ofc : ccache) (ofg : generator) (ofcs : seq cnf)\n                (oflr : literal) (om : vm) (oc : CompCache.compcache)\n                (og : generator) (ocs : cnf) (olr : literal),\n            ccache_compatible ifc ic ->\n            mk_env_bexp_fccache iE s im ifc ig e =\n            (ofE, ofm, ofc, ofg, ofcs, oflr) ->\n            mk_env_bexp_ccache im ic s iE ig e = (om, oc, oE, og, ocs, olr) ->\n            ofE = oE /\\\n            ofm = om /\\\n            ccache_compatible ofc oc /\\\n            ofg = og /\\\n            cnf_eqsat (tflatten ofcs) ocs /\\\n            cnf_eqnew (tflatten ofcs) ocs /\\ oflr = olr),\n      Hcc : ccache_compatible ?ifc ?ic,\n      Hv1 : mk_env_bexp_fccache ?iE ?s ?im ?ifc ?ig ?e = _,\n      Hv2 : mk_env_bexp_ccache ?im ?ic ?s ?iE ?ig ?e = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      let H5 := fresh in\n      let H6 := fresh in\n      let H7 := fresh in\n      (move: (mk_env_bexp_fccache_valid _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n                                        Hcc Hv1 Hv2));\n      (move=> [H1 [H2 [H3 [H4 [H5 [H6 H7]]]]]]);\n      subst; clear Hv1 Hv2\n    (**)\n    | Hv1 : mk_env_var ?iE ?g ?bs ?v = _,\n      Hv2 : mk_env_var ?iE ?g ?bs ?v = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      (rewrite Hv1 in Hv2); (case: Hv2 => ? ? ? ?; subst)\n    | Hv1 : mk_env_eunop ?op ?iE ?g ?ls = _,\n      Hv2 : mk_env_eunop ?op ?iE ?g ?ls = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      (rewrite Hv1 in Hv2); (case: Hv2 => ? ? ? ?; subst)\n    | Hv1 : mk_env_ebinop ?op ?iE ?g ?ls1 ?ls2 = _,\n      Hv2 : mk_env_ebinop ?op ?iE ?g ?ls1 ?ls2 = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      (rewrite Hv1 in Hv2); (case: Hv2 => ? ? ? ?; subst)\n    | Hv1 : mk_env_bbinop ?op ?iE ?g ?ls1 ?ls2 = _,\n      Hv2 : mk_env_bbinop ?op ?iE ?g ?ls1 ?ls2 = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      (rewrite Hv1 in Hv2); (case: Hv2 => ? ? ? ?; subst)\n    | Hv1 : mk_env_ite ?iE ?g ?l ?ls1 ?ls2 = _,\n      Hv2 : mk_env_ite ?iE ?g ?l ?ls1 ?ls2 = _ |- _ =>\n      let H1 := fresh in\n      let H2 := fresh in\n      let H3 := fresh in\n      let H4 := fresh in\n      (rewrite Hv1 in Hv2); (case: Hv2 => ? ? ? ?; subst)\n    (**)\n    | |- _ => dcase_bb_ccache || dcase_mk_env_compcache || dcase_mk_env_ccache\n              || simpl_ccache_compatible || simpl_ccache_compatible_find || solve_eqnew\n    end.\n\nLemma mk_env_exp_fccache_valid\n      iE s e im ifc ic ig ofE oE ofm ofc ofg ofcs oflrs om oc og ocs olrs :\n  ccache_compatible ifc ic ->\n  mk_env_exp_fccache iE s im ifc ig e = (ofE, ofm, ofc, ofg, ofcs, oflrs) ->\n  mk_env_exp_ccache im ic s iE ig e = (om, oc, oE, og, ocs, olrs) ->\n  ofE = oE\n  /\\ ofm = om\n  /\\ ccache_compatible ofc oc\n  /\\ ofg = og\n  /\\ cnf_eqsat (tflatten ofcs) ocs\n  /\\ cnf_eqnew (tflatten ofcs) ocs\n  /\\ oflrs = olrs\nwith\nmk_env_bexp_fccache_valid\n  iE s e im ifc ic ig ofE oE ofm ofc ofg ofcs oflr om oc og ocs olr :\n  ccache_compatible ifc ic ->\n  mk_env_bexp_fccache iE s im ifc ig e = (ofE, ofm, ofc, ofg, ofcs, oflr) ->\n  mk_env_bexp_ccache im ic s iE ig e = (om, oc, oE, og, ocs, olr) ->\n  ofE = oE\n  /\\ ofm = om\n  /\\ ccache_compatible ofc oc\n  /\\ ofg = og\n  /\\ cnf_eqsat (tflatten ofcs) ocs\n  /\\ cnf_eqnew (tflatten ofcs) ocs\n  /\\ oflr = olr.\nProof.\n  (* mk_env_exp_fccache_valid *)\n  move=> Hcc. case: e => /=.\n  - move=> v. by myauto.\n  - move=> bs. by myauto.\n  - move=> op e. by myauto.\n  - move=> op e1 e2. by myauto.\n  - move=> e1 e2 e3. by myauto.\n  (* mk_env_bexp_fccache_valid *)\n  move=> Hcc. case: e => /=.\n  - by myauto.\n  - by myauto.\n  - move=> op e1 e2. by myauto.\n  - move=> e. by myauto.\n  - move=> e1 e2. by myauto.\n  - move=> e1 e2. by myauto.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/bbcache/BitBlastingCCacheFlatten.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3007455789412415, "lm_q1q2_score": 0.1620968207453325}}
{"text": "Require Import RelationClasses.     \nRequire Import List.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import LibTactics.\nRequire Import Integers.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\n\nRequire Import Kildall.\nRequire Import LiveAnalysis.\nRequire Import CorrectOpt.\nRequire Import DCE.\n\nRequire Import Language.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\n\nRequire Import WFConfig.\nRequire Import CompAuxDef.\nRequire Import MemoryProps.\nRequire Import promiseCertifiedAux.\nRequire Import Mem_at_eq_lemmas.\nRequire Import PromiseInjectionWeak.\n\n(** * Well-formed state lemmas *)\nLemma concrete_incr_closed_tm_prsv\n      tm mem mem'\n      (CONCRETE_INCR: forall loc to from val R,\n          Memory.get loc to mem = Some (from, Message.concrete val R) ->\n          exists from' R', Memory.get loc to mem' = Some (from', Message.concrete val R'))\n      (CLOSED_VIEW: Memory.closed_timemap tm mem):\n  Memory.closed_timemap tm mem'.\nProof.\n  unfold Memory.closed_timemap in *.\n  ii. specialize (CLOSED_VIEW loc). des.\n  eapply CONCRETE_INCR in CLOSED_VIEW. des.\n  do 3 eexists. eauto.\nQed.\n\nLemma concrete_incr_closed_view_prsv\n      view mem mem'\n      (CONCRETE_INCR: forall loc to from val R,\n          Memory.get loc to mem = Some (from, Message.concrete val R) ->\n          exists from' R', Memory.get loc to mem' = Some (from', Message.concrete val R'))\n      (CLOSED_VIEW: Memory.closed_view view mem):\n  Memory.closed_view view mem'.\nProof.\n  inv CLOSED_VIEW.\n  econs; eauto.\n  eapply concrete_incr_closed_tm_prsv; eauto.\n  eapply concrete_incr_closed_tm_prsv; eauto.\nQed.\n\nLemma concrete_incr_local_wf_prsv\n      mem mem' lc\n      (CONCRETE_INCR: forall loc to from val R,\n          Memory.get loc to mem = Some (from, Message.concrete val R) ->\n          exists from' R', Memory.get loc to mem' = Some (from', Message.concrete val R'))\n      (PRM_LESS: Memory.le (Local.promises lc) mem')\n      (LOCAL_WF: Local.wf lc mem):\n  Local.wf lc mem'.\nProof.\n  inv LOCAL_WF.\n  econs; eauto.\n  inv TVIEW_CLOSED.\n  econs; eauto.\n  ii.\n  eapply concrete_incr_closed_view_prsv; eauto.\n  eapply concrete_incr_closed_view_prsv; eauto.\n  eapply concrete_incr_closed_view_prsv; eauto.\nQed.\n\n(** * Step lemmas *)\nLemma Thread_na_step_to_na_step_dset\n      lang lo (e1 e2: Thread.t lang) index\n      (NA_STEP: Thread.na_step lo e1 e2):\n  na_step_dset lo (e1, @dset_init index) (e2, @dset_init index).\nProof.\n  inv NA_STEP.\n  eapply na_steps_dset_read; eauto.\n  ii. rewrite dset_gempty in H. ss.\n  eapply na_steps_dset_write; eauto.\n  econs; eauto.\nQed.\n\nLemma Thread_na_steps_to_na_steps_dset\n      lang lo (e1 e2: Thread.t lang) index\n      (NA_STEPS: rtc (Thread.na_step lo) e1 e2):\n  rtc (na_step_dset lo) (e1, @dset_init index) (e2, @dset_init index).\nProof.\n  induction NA_STEPS; ii; eauto.\n  econs; eauto.\n  eapply Thread_na_step_to_na_step_dset; eauto.\nQed.\n\nLemma injection_read\n      inj lo\n      tview_tgt prm_tgt mem_tgt loc to v R or tview_tgt' prm_tgt'\n      tview_src prm_src mem_src\n      (LOCAL_READ: Local.read_step (Local.mk tview_tgt prm_tgt) mem_tgt loc to v R or\n                                   (Local.mk tview_tgt' prm_tgt') lo)\n      (MSG_INJ: MsgInj inj mem_tgt mem_src)\n      (INJ_PLN: inj loc (View.pln (TView.cur tview_tgt) loc) = Some (View.pln (TView.cur tview_src) loc))\n      (INJ_RLX: inj loc (View.rlx (TView.cur tview_tgt) loc) = Some (View.rlx (TView.cur tview_src) loc))\n      (MEM_CLOSED: Memory.closed mem_tgt):\n  exists tview_src' to' R',\n    <<LOCAL_READ_SRC: Local.read_step (Local.mk tview_src prm_src) mem_src loc to' v R' or\n                                      (Local.mk tview_src' prm_src) lo>> /\\\n    <<INJ_PLN': inj loc (View.pln (TView.cur tview_tgt') loc) = Some (View.pln (TView.cur tview_src') loc)>> /\\\n    <<INJ_RLX': inj loc (View.rlx (TView.cur tview_tgt') loc) = Some (View.rlx (TView.cur tview_src') loc)>> /\\\n    <<INJ_TO: inj loc to = Some to'>> /\\\n    <<VIEW_INJ: opt_ViewInj inj R R'>> /\\ \n    <<CLOSED_VIEW: Memory.closed_opt_view R mem_tgt>>.\nProof.\n  inv LOCAL_READ. inv LC2. inv MSG_INJ.\n  exploit SOUND; eauto. ii; des.\n  do 3 eexists.\n  split. econs; eauto. ss. inv READABLE. econs; eauto.\n  eapply monotonic_inj_implies_le_prsv; eauto.\n  ii.\n  exploit RLX; eauto. ii.\n  eapply monotonic_inj_implies_le_prsv; eauto.\n  \n  ss. splits; eauto.\n  {\n    destruct (Ordering.le Ordering.acqrel or) eqn:ORD_ACQREL.\n    {\n      unfold View.singleton_ur_if. unfold TimeMap.join; ss.\n      destruct (Ordering.le Ordering.relaxed or) eqn:ORD_RELAX; ss.\n      \n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      exploit wf_msginj_implies_closed_view; [ | eapply MEM_CLOSED | eapply GET | eauto..].\n      econs; eauto. ii; des; subst.\n      {\n        ss. destruct R'; ss. unfold TimeMap.bot. do 2 (rewrite Time_join_bot).\n        eapply inj_join_comp; eauto.\n      }\n      {\n        destruct R'; ss.\n        eapply inj_join_comp; eauto.\n        eapply inj_join_comp; eauto.\n        clear - x2 x0. inv x2. unfold closed_TMapInj in H.\n        specialize (H loc). des. unfold ViewInj in x0. destruct view, t; ss. des.\n        unfold TMapInj in x0.\n        exploit x0; eauto. ii; subst. eauto.\n      }\n\n      unfold TimeMap.bot. do 2 (rewrite Time_join_bot).\n      exploit wf_msginj_implies_closed_view; [ | eapply MEM_CLOSED | eapply GET | eauto..].\n      econs; eauto. ii; des; subst.\n      {\n        destruct R'; ss. unfold TimeMap.bot; ss.\n        do 2 (rewrite Time_join_bot). eauto.\n      }\n      {\n        destruct R'; ss.\n        eapply inj_join_comp; eauto.\n        clear - x2 x0. inv x2. unfold closed_TMapInj in H.\n        specialize (H loc). des. unfold ViewInj in x0. destruct view, t; ss. des.\n        unfold TMapInj in x0.\n        exploit x0; eauto. ii; subst. eauto.\n      }\n    }\n    {\n      unfold View.singleton_ur_if. unfold TimeMap.join; ss.\n      destruct (Ordering.le Ordering.relaxed or) eqn:ORD_RELAX; ss.\n\n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      unfold TimeMap.bot; ss. do 2 (rewrite Time_join_bot).\n      eapply inj_join_comp; eauto.\n\n      unfold TimeMap.bot; ss. do 4 (rewrite Time_join_bot). eauto.\n    }\n  }\n  {\n    destruct (Ordering.le Ordering.acqrel or) eqn:ORD_ACQREL.\n    {\n      unfold View.singleton_ur_if. unfold TimeMap.join; ss.\n      destruct (Ordering.le Ordering.relaxed or) eqn:ORD_RELAX; ss.\n      \n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      exploit wf_msginj_implies_closed_view; [ | eapply MEM_CLOSED | eapply GET | eauto..].\n      econs; eauto. ii; des; subst.\n      {\n        ss. destruct R'; ss. unfold TimeMap.bot. do 2 (rewrite Time_join_bot).\n        eapply inj_join_comp; eauto. \n      }\n      {\n        destruct R'; ss.\n        eapply inj_join_comp; eauto.\n        eapply inj_join_comp; eauto.\n        clear - x2 x0. inv x2. unfold closed_TMapInj in H0.\n        specialize (H0 loc). des. unfold ViewInj in x0. destruct view, t; ss. des.\n        unfold TMapInj in x1.\n        exploit x1; eauto. ii; subst. eauto.\n      }\n\n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      exploit wf_msginj_implies_closed_view; [ | eapply MEM_CLOSED | eapply GET | eauto..].\n      econs; eauto. ii; des; subst.\n      {\n        destruct R'; ss. unfold TimeMap.bot; ss.\n        do 2 (rewrite Time_join_bot).\n        eapply inj_join_comp; eauto. \n      }\n      {\n        destruct R'; ss.\n        eapply inj_join_comp; eauto.\n        eapply inj_join_comp; eauto.\n        clear - x2 x0. inv x2. unfold closed_TMapInj in H0.\n        specialize (H0 loc). des. unfold ViewInj in x0. destruct view, t; ss. des.\n        unfold TMapInj in x1.\n        exploit x1; eauto. ii; subst. eauto.\n      }\n    }\n    {\n      unfold View.singleton_ur_if. unfold TimeMap.join; ss.\n      destruct (Ordering.le Ordering.relaxed or) eqn:ORD_RELAX; ss.\n\n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      unfold TimeMap.bot; ss. do 2 (rewrite Time_join_bot).\n      eapply inj_join_comp; eauto.\n\n      unfold TimeMap.bot; ss. do 2 (rewrite Time_join_bot).\n      unfold TimeMap.singleton; ss. do 2 (rewrite Loc_add_eq).\n      eapply inj_join_comp; eauto.\n    }\n  }\n  {\n    clear - GET MEM_CLOSED.\n    eapply closed_mem_implies_closed_msg; eauto.\n  }\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/Lib_Step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.16207495419501658}}
{"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 Div2 Even.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice fintype.\nFrom mathcomp Require Import tuple.\nRequire Import ssrZ ZArith_ext String_ext ssrnat_ext seq_ext machine_int.\nImport MachineInt.\nRequire Import C_types C_types_fp C_value C_expr C_expr_equiv C_expr_ground.\nRequire Import C_seplog C_tactics.\nRequire Import rfc5246.\nImport RFC5932.\nRequire Import POLAR_library_functions POLAR_library_functions_triple.\nRequire Import POLAR_ssl_ctxt POLAR_parse_client_hello POLAR_parse_client_hello_header.\nRequire Import POLAR_parse_client_hello_triple3.\n\nClose Scope select_scope.\n\nLocal Open Scope nat_scope.\nLocal Open Scope string_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope seq_ext_scope.\nLocal Open Scope C_assert_scope.\nLocal Open Scope C_expr_scope.\nLocal Open Scope C_cmd_scope.\nLocal Open Scope C_value_scope.\nLocal Open Scope C_types_scope.\nLocal Open Scope POLAR_scope.\n\n(** * Verification of the ClientHello Parsing Program (2/4) *)\n\nSection POLAR_parse_client_hello_triple.\n\nVariable SI : seq (int 8).\n\nLemma POLAR_parse_client_hello_triple2 (BU RB ID : seq (int 8)) (CI : seq (int 32))\n  (sz_BU : size BU = '| SSL_BUFFER_LEN |)\n  (sz_ID : size ID = 32)\n  (HCI : ciphers_seq CI)\n  (cipher0 length0 : int 32)\n  (bu rb id : (:* (ityp: uchar)).-phy)\n  (ses : (:* (g.-typ: ssl_session)).-phy)\n  (ciphers : (:* (ityp: sint)).-phy)\n  (vssl : int ptr_len)\n  (md5s sha1s : 5.-tuple (int ptr_len))  :\n  let init_ssl_var := `! \\b __ssl \\= [ phy<=ptr _ vssl ]c in\n  let init_id := [ id ]c |---> map phy_of_ui8 ID in\n  let init_ses := ses |lV~> mk_ssl_session cipher0 length0 (ptr<=phy id) in\n  let init_ciphers := [ ciphers ]c |--> map phy<=si32 CI in\n  let final_bu := Final_bu SI bu in\n  let final_ses := Final_ses SI CI ses id in\n  let final_rb := Final_rb SI RB rb in\n  let final_id := Final_id SI id in\n  let final_ssl_context := Ssl_context (zext 24 S74.server_hello)\n    (zext 24 (SI `_ maj_ver))\n    (zext 24 (if (u2Z (SI `_ min_req) <=? u2Z (S621.TLSv11_min))%Z then\n              SI `_ min_req else S621.TLSv11_min))\n    (zext 24 (SI `_ maj_req)) (zext 24 (SI `_ min_req ))\n    ses bu `( 0 )s_32 md5s sha1s ciphers rb in\n  forall BU1, BU1 |{ 8, 5) = SI |{ 0, 5) -> size BU1 = size BU ->\n  4 < size SI ->\n  forall in_left, in_left = Z2u 32 5 ->\n  let the_n := Z<=s ((zext 24 (BU1 `_ 11) `<< 8) `|` zext 24 (BU1 `_ 12)) in\n  let the_n_plus5 := (5 + the_n)%Z in\n  (45 <= the_n)%Z -> (the_n <= 512)%Z ->\n  forall in_left2, in_left2 = Z2u 32 the_n_plus5 ->\n  forall BU2 : seq (int 8),\n  let Hbu := [ bu ]c |---> map phy_of_ui8 BU2 in\n  BU2 |{ 8 + 5, Z.abs_nat the_n) = SI |{ 5, Z.abs_nat the_n) ->\n  BU2 |{ 8, 5) = BU1 |{ 8, 5) ->\n  size BU2 = size BU1 ->\n  '| the_n_plus5 | <= size SI ->\n  let Hbuf := `! \\b __buf \\= [ bu ]c \\+ [ 13 ]sc in\n  let Hn0 := `! \\b __n0 \\= [ in_left2 ]pc in\n  let Hn_old := `! \\b __n_old \\= [ the_n ]sc in\n  let Hn := `! \\b __n \\= __n0 \\- [ 5 ]sc in\n  BU1 `_ 8 `& Z2u 8 128  = Z2u 8 0 /\\ BU1 `_ 8 = S621.handshake ->\n  BU2 `_ 13 = S74.client_hello ->\n  BU2 `_ 17 = S621.SSLv30_maj ->\n  let Hbuf5 := `! \\b __buf5 \\= ([BU2 `_ 18]pc : exp sigma (ityp: uchar)) in\n  let minver_exp := [BU2 `_ 18]pc \\<= [ SSL_MINOR_VERSION_2 ]c \\?\n                    [BU2 `_ 18]pc \\: [ SSL_MINOR_VERSION_2 ]c : exp sigma (g.-ityp: uchar) in\n  let minver_u := si32<=phy (safe_cast_phy (ground_exp minver_exp Logic.eq_refl) sint Logic.eq_refl) in\n  let reqmin_sslcontext := Ssl_context (zext 24 S74.client_hello)\n      (si32<=phy (safe_cast_phy SSL_MAJOR_VERSION_3 sint Logic.eq_refl)) minver_u\n      (zext 24 (BU2 `_ 17)) (zext 24 (BU2 `_ 18)) ses bu in_left2 md5s sha1s\n      ciphers rb in\n  let Hit := `! \\b __it \\= [ rb ]c in\n  BU1 `_ 9 = S621.SSLv30_maj ->\n  BU2 `_ 14 = zero8 ->\n  let Hbuf2 := `! \\b __buf2 \\= [BU2 `_ 15]pc in\n  let Hbuf3 := `! \\b __buf3 \\= [BU2 `_ 16]pc in\n  {{ Hbuf3 ** Hbuf2 ** Hit ** Hbuf5 ** Hn ** Hn_old ** Hn0 ** Hbuf **\n     Hbu ** reqmin_sslcontext ** success ** init_ssl_var ** final_rb **\n     init_id ** init_ses ** init_ciphers }}\n  ssl_parse_client_hello3 (ssl_parse_client_hello4 ssl_parse_client_hello5)\n  {{ error \\\\//\n     success ** final_bu ** final_ses ** final_rb **\n     final_id ** final_ssl_context ** !!( PolarSSLClientHellop SI ) ** init_ciphers }}.\nProof.\nmove=> init_ssl_var init_id init_ses init_ciphers final_bu\n  final_ses final_rb final_id final_ssl_context BU1 BU1SI sz_BU1 size_SI\n  in_left in_left_5 the_n the_n_plus5 HN1 HN2 in_left2 Hin_left2 BU2\n  Hbu BU2SI BU2BU1 sz_BU2 HSI_new Hbuf Hn0 Hn_old Hn BU1_8 BU2_13\n  BU2_17 Hbuf5 minver_exp minver_u reqmin_sslcontext Hit BU1_9 BU2_14 Hbuf2\n  Hbuf3.\n\nunfold ssl_parse_client_hello3.\n\n(** If \\b __n \\!= [ 4 ]sc \\+ ((int) __buf2 \\<< [ 8 ]sc \\| (int) __buf3) Then *)\n(**   _ret <- [ POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ]c; ret *)\n\nidtac \"36) ifte\".\n\nHoare_ifte_bang Hm_old; first by apply POLAR_ret_err.\n\npose Hm := `! \\b __n \\= [4 ]sc \\+\n  ((int) ([ BU2 `_ 15 ]pc : exp sigma (ityp: uchar)) \\<< [8 ]sc \\|\n  (int) ([ BU2 `_ 16 ]pc : exp sigma (ityp: uchar))).\n\nHoare_L_stren_by Hm (Hbuf2 :: Hbuf3 :: Hm_old :: nil).\n  unfold Hm, Hbuf2, Hbuf3, Hm_old.\n  Ent_LR_rewrite_eq_e 0 (* buf3 *).\n  do 2 Ent_L_subst_apply; Ent_R_subst_apply.\n  Ent_LR_rewrite_eq_e 0 (* buf2 *).\n  Ent_R_subst_apply; Ent_L_subst_apply.\n  rewrite bneg_neq_eq; by apply ent_id.\n\nHoare_L_contract_bbang Hbuf2.\nHoare_L_contract_bbang Hbuf3.\nHoare_L_contract_bbang Hm_old.\nclear Hbuf2 Hbuf3 Hm_old.\n\n(** _buf38 <-* __buf \\+ [ 38 ]sc; *)\n\nidtac \"37) lookup\".\n\n(* 51 = 8 + 5 + 38 *)\npose Hbuf38 := `! \\b __buf38 \\= ([ BU2 `_ 51 ]pc : exp sigma (ityp: uchar)).\nHoare_seq_ext Hbuf38.\n  Hoare_frame (Hbu :: Hbuf :: nil) (Hbu :: Hbuf :: Hbuf38 :: nil).\n  apply hoare_lookup_mapstos_fit_stren with (i := 51) (l := map phy_of_ui8 BU2) (e := [ bu ]c).\n  - by rewrite size_map sz_BU2 sz_BU1 sz_BU inj_mult Z_of_nat_Zabs_nat.\n  - apply ent_R_lookup_mapstos_fit_trans.\n    + by rewrite size_map sz_BU2 sz_BU1 sz_BU.\n    + Ent_decompose (0 :: nil) (1 :: nil); first by apply ent_id.\n      Ent_decompose (0 :: nil) (0 :: nil); last by [].\n      unfold Hbuf.\n      Ent_LR_rewrite_eq_p 0 (* buf *).\n      Ent_R_subst_apply.\n      Bbang2sbang.\n      Ent_R_sbang 0; last by [].\n      Rewrite_ground_bexp @CaddnpA => //=.\n      Rewrite_ground_bexp @sequiv_add_e_sc => //=.\n      by rewrite gb_eq_p.\n    + rewrite [nth] lock.\n      Ent_R_subst_con_distr.\n      do 3 Ent_R_subst_apply.\n      apply monotony_L.\n      rewrite -lock (nth_map zero8); last by rewrite sz_BU2 sz_BU1 sz_BU.\n      by Ent_monotony0.\n\n(** _sess_len <- (int) __buf38; *)\n\nidtac \"38) assign\".\n\npose Hsess_len := `! \\b __sess_len \\= (int) ([ BU2 `_ 51 ]pc : exp _ (ityp: uchar)).\nHoare_seq_ext Hsess_len.\n\n  Hoare_L_dup (Hbuf38 :: nil).\n  Hoare_frame (Hbuf38 :: nil) (Hsess_len :: nil).\n  apply hoare_assign_stren.\n  Ent_R_subst_apply.\n  unfold Hbuf38.\n  Ent_R_rewrite_eq_e 0 (* buf38 *).\n  Ent_R_subst_apply.\n  by Ent_monotony0.\n\nHoare_L_contract_bbang Hbuf38; clear Hbuf38.\n\n(** If \\b __sess_len \\< [ 0 ]sc \\|| __sess_len \\> [ 32 ]sc\n    \\|| [ Z<=nat 45 ]sc \\+ __sess_len \\>= [ 5 ]sc \\+ __n_old\n    Then *)\n(**   _ret <- [ POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ]c; Return *)\n\nidtac \"39) ifte\".\n\napply hoare_ifte_bang; first by apply POLAR_ret_err.\n\nrewrite -bbang_bneg_or.\nset Hsess_len_2 := `! \\~b \\b __sess_len \\< [0 ]sc \\|| __sess_len \\> [ 32 ]sc.\nset Hsess_len_3 := `! \\~b \\b [ Z<=nat csuites.+1 ]sc \\+ __sess_len \\>= [ 5 ]sc \\+ __n_old.\n\n(** _ssl_session_0 <-* __ssl &-> _session; *)\n\nidtac \"40) lookup\".\n\npose Hssl_session_0 := `! \\b __ssl_session_0 \\= [ ses ]c.\n\nHoare_seq_ext Hssl_session_0.\n  Hoare_frame (reqmin_sslcontext :: nil) (reqmin_sslcontext :: Hssl_session_0 :: nil).\n  apply hoare_lookup_fldp_stren, ent_R_lookup_fldp with (pv := ses).\n  - by rewrite get_session_ssl_ctxt /phylog_conv /= ptr_of_phyK.\n  - Ent_R_subst_con_distr. (* 1 *)\n    rewrite /reqmin_sslcontext /Ssl_context.\n    do 2 Ent_R_subst_apply.\n    by Ent_monotony0.\n\npose Hsess_len3'' := !!(Z<=nat csuites.+1 + Z<=u BU2 `_ 51 < the_n_plus5)%Z.\nHoare_L_stren_by Hsess_len3'' (Hsess_len :: Hn_old :: Hsess_len_3 :: nil).\n  unfold Hsess_len, Hsess_len_3, Hn_old.\n  Ent_LR_rewrite_eq_e 0 (* sess_len *).\n  do 2 Ent_L_subst_apply; Ent_R_subst_apply.\n  fold Hsess_len3''.\n  Ent_LR_rewrite_eq_e 0 (* n_old *).\n  Ent_R_subst_apply; Ent_L_subst_apply.\n  Bbang2sbang.\n  apply ent_sbang_sbang.\n  rewrite gb_bneg_bop_r_ge.\n  move/Zlt_gb. move/(_ erefl erefl).\n  rewrite si32_of_phy_gb_add_e i32_ge_s_cst_e ge_cast_sint_cst_8c phy_of_si32K.\n  rewrite si32_of_phy_gb_add_e 2!i32_ge_s_cst_e.\n  have H1 : (0 <= Z<=nat csuites.+1 + Z<=u BU2 `_ 51 < 2 ^^ 31)%Z.\n    split.\n      apply (@leZ_trans (45%Z + Z0)%Z) => //; exact/leZ_add2l/min_u2Z.\n    apply (@ltZ_trans (45%Z + 2 ^^ 8)%Z) => //; exact/ltZ_add2l/max_u2Z.\n  rewrite s2Z_add; last first.\n    rewrite Z2sK; last by [].\n    rewrite (s2Z_zext 24) //.\n    split; last by case: H1.\n    apply (@leZ_trans Z0) => //; by case: H1.\n  rewrite Z2sK // s2Z_add; last first.\n    rewrite Z2sK //.\n    clear -HN1 HN2.\n    rewrite Z2sK; last by simpl expZ; lia.\n    simpl expZ; lia.\n  rewrite Z2sK // Z2sK; last by simpl expZ; lia.\n  rewrite (s2Z_zext 24) //.\n  apply.\n  exact H1.\n  simpl expZ; lia.\n\nHoare_L_contract_bbang Hsess_len_3; clear Hsess_len_3.\napply hoare_pullout_sbang => Hsess_len_3'.\nclear Hsess_len3''.\n\n(** __ssl_session_0 &-> _length *<- __sess_len; *)\n\nidtac \"41) mutation\".\n\npose Hses_length := ses |lV~> mk_ssl_session cipher0 (zext 24 (BU2 `_ 51)) (ptr<=phy id) : assert.\n\nHoare_seq_replace1 init_ses Hses_length.\n  Hoare_L_dup (Hsess_len :: Hssl_session_0 :: nil).\n  Hoare_frame (init_ses :: Hsess_len :: Hssl_session_0 :: nil) (Hses_length :: nil).\n  unfold init_ses, Hses_length, mk_ssl_session.\n  set ses_hdr_pre := mk_ssl_sess_logs _ _ _.\n  set ses_hdr_post := mk_ssl_sess_logs _ _ _.\n  apply hoare_mutation_fldp_subst_ptr with (str := _ssl_session_0) (Hstr := Logic.eq_refl) (e'' := [ ses ]c).\n  - Ent_decompose (0 :: 1 :: nil) (1 :: nil); by [| apply ent_id].\n  - rewrite /=.\n    apply hoare_mutation_fldp_subst_ityp with (str := _sess_len) (Hstr := Logic.eq_refl) (e := (int) ([ BU2`_51 ]pc : exp sigma (ityp: uchar))).\n    + Ent_decompose (0 :: 2 :: nil) (1 :: nil); by [| apply ent_id].\n    + rewrite /=.\n      Hoare_L_contract_bbang Hsess_len; Hoare_L_contract_bbang Hssl_session_0.\n      set tmp := safe_cast _ _ _ _ _.\n      eapply hoare_weak; last first.\n        have He2 : @vars _ sigma _ tmp = nil by [].\n        apply hoare_mutation_fldp_local_forward_ground_lV with (val := mkSintLog (zext 24 (BU2`_51))) (He2 := He2).\n        by rewrite /phylog_conv /= /tmp ge_cast_sint_cst_8c.\n      rewrite /= -!Eqdep.Eq_rect_eq.eq_rect_eq /ses_hdr_post /mk_ssl_sess_logs /tmp; by apply ent_id.\n\n(** _it <-* __ssl_session_0 &-> _id; *)\n\nidtac \"42) lookup\".\n\nHoare_L_contract_bbang Hit; clear Hit.\n\npose Hit := `! \\b __it \\= [ id ]c.\nHoare_seq_ext Hit.\n  Hoare_L_dup (Hssl_session_0 :: nil).\n  Hoare_frame (Hses_length :: Hssl_session_0 :: nil) (Hses_length :: Hit :: nil).\n  apply (hoare_lookup_fldp_subst _ _ssl_session_0 erefl ([ ses ]c)).\n  - Ent_decompose (0 :: nil) (1 :: nil); by [apply ent_R_T | apply ent_id].\n  - rewrite /=.\n    Hoare_L_contract_bbang Hssl_session_0.\n    apply hoare_lookup_fldp_stren.\n    unfold Hses_length, mk_ssl_session.\n    set ses_hdr := mk_ssl_sess_logs _ _ _.\n    apply ent_R_lookup_fldp_trans with (pv := id) (lvs := ses_hdr).\n    + by apply ent_R_con_T.\n    + by rewrite /= -Eqdep.Eq_rect_eq.eq_rect_eq /phylog_conv /= ptr_of_phyK.\n    + Ent_R_subst_con_distr.\n      do 2 Ent_R_subst_apply.\n      by Ent_monotony0.\n\n(** _it <-memset( __it, [ 0 ]sc, [ 32 ]uc);; *)\n\nidtac \"43) memset\".\n\npose init_id0 := [id ]c |---> nseq 32 pv0.\nHoare_seq_replace1 init_id init_id0.\n  Hoare_frame (Hit :: init_id :: nil) (Hit :: init_id0 :: nil).\n    by rewrite memset_input_inde.\n  unfold init_id, init_id0.\n  apply hoare_stren with (Hit ** __it |---> map phy_of_ui8 ID).\n    unfold Hit at 1.\n    Ent_R_rewrite_eq_p 0 (* it *).\n    Ent_R_subst_con_distr.\n    do 2 Ent_R_subst_apply.\n    by Ent_monotony0.\n  apply hoare_weak with (Hit ** __it |---> nseq 32 pv0).\n    unfold Hit at 1.\n    rewrite [nseq]lock.\n    Ent_LR_rewrite_eq_p 0 (* it *).\n    rewrite -lock.\n    Ent_L_subst_apply.\n    Ent_R_subst_con_distr.\n    do 2 Ent_R_subst_apply.\n    by Ent_monotony0.\n  rewrite (_ : 32%Z = Z.of_nat 32) // (_ : [ 0 ]s = (phyint) (@pv0 _ (g.-ityp:uchar))); last first.\n    apply mkPhy_irrelevance => /=.\n    by rewrite zext_Z2u // Z2s_Z2u_k.\n\n  Hoare_frame_remove (Hit :: nil); first by rewrite memset_input_inde.\n  (* TODO: Hoare_frame_move seems to do a useless simpl *)\n  apply memset_triple_cst_e.\n  by rewrite size_map.\n\n(** _ssl_session_0_length <-* __ssl_session_0 &-> _length; *)\n\nidtac \"44) lookup\".\n\npose Hssl_session_0_length := `! \\b __ssl_session_0_length \\= (int) ([ BU2 `_ 51 ]pc : exp _ (ityp: uchar)).\nHoare_seq_ext Hssl_session_0_length.\n  Hoare_L_dup (Hssl_session_0 :: nil).\n  Hoare_frame (Hses_length :: Hssl_session_0 :: nil) (Hses_length :: Hssl_session_0_length :: nil).\n  apply (hoare_lookup_fldp_subst _ _ssl_session_0 erefl ([ ses ]c)).\n  - Ent_decompose (0 :: nil) (1 :: nil); by [apply ent_R_T | apply ent_id].\n  - rewrite /=.\n    Hoare_L_contract_bbang Hssl_session_0.\n    apply hoare_lookup_fldp_stren.\n    unfold Hses_length, mk_ssl_session.\n    set ses_hdr := mk_ssl_sess_logs _ _ _.\n    apply ent_R_lookup_fldp_trans with (pv := [zext 24 (BU2 `_ 51)]p) (lvs := ses_hdr).\n    + by apply ent_R_con_T.\n    + by rewrite /= -Eqdep.Eq_rect_eq.eq_rect_eq /phylog_conv /=.\n    + Ent_R_subst_con_distr.\n      do 2 Ent_R_subst_apply.\n      rewrite -/Hses_length.\n      Ent_monotony.\n      Bbang2sbang.\n      Ent_R_sbang 0; last by [].\n      Rewrite_ground_bexp @sequiv_intsa_uchar_sc.\n      Rewrite_ground_bexp @phy_of_si32_zext.\n      Rewrite_ground_bexp @beq_exx.\n      rewrite -(ground_bexp_sem (store0 sigma)).\n      by apply: one_uc.\n\n(** _it <-* __ssl_session_0 &-> _id; *)\n\nidtac \"45) lookup\".\n\nHoare_L_contract_bbang Hit; clear Hit.\n\npose Hit := `! \\b __it \\= [ id ]c.\nHoare_seq_ext Hit.\n  Hoare_L_dup (Hssl_session_0 :: nil).\n  Hoare_frame (Hses_length :: Hssl_session_0 :: nil) (Hses_length :: Hit :: nil).\n  apply (hoare_lookup_fldp_subst _ _ssl_session_0 Logic.eq_refl ([ ses ]c)).\n  - Ent_decompose (0 :: nil) (1 :: nil); by [ | apply ent_id].\n  - rewrite /=.\n    Hoare_L_contract_bbang Hssl_session_0.\n    apply hoare_lookup_fldp_stren.\n    unfold Hses_length, mk_ssl_session.\n    set ses_hdr := mk_ssl_sess_logs _ _ _.\n    apply ent_R_lookup_fldp_trans with (pv := id) (lvs := ses_hdr).\n    - by apply ent_R_con_T.\n    - by rewrite /= -Eqdep.Eq_rect_eq.eq_rect_eq /phylog_conv /= ptr_of_phyK.\n    - Ent_R_subst_con_distr.\n      do 2 Ent_R_subst_apply.\n      rewrite -/Hses_length.\n      by Ent_monotony0.\n\n(** memcpy _it Logic.eq_refl __it (__buf \\+ [ 39 ]sc) (UINT) __ssl_session_0_length; *)\n\nidtac \"46) memcpy\".\n\nHoare_stren_pull_out (Hsess_len ** Hsess_len_2) (u2Z (BU2 `_ 51) <= 32)%Z.\n  unfold Hsess_len, Hsess_len_2.\n  Ent_LR_rewrite_eq_e 0 (* sess_len *).\n  do 2 Ent_LR_subst_apply.\n  rewrite <- bbang_bneg_or.\n  rewrite -CleqNgt.\n  Ent_L_contract_bbang 0.\n  Bbang2sbang.\n  Ent_L_sbang 0 => H1.\n  Ent_R_sbang 0; last by [].\n  rewrite -(ground_bexp_sem (@store0 _ sigma)) in H1.\n  apply bop_re_le_Zle in H1.\n  rewrite 2!(ground_exp_sem (@store0 _ sigma)) in H1.\n  by rewrite s2Z_ge_s_cst_e // s2Z_si32_of_phy_safe_cast eval_pv phy_of_ui8K in H1.\nmove=> BU_51.\n\nhave BU1_51 : u2nat (BU2 `_ 51) <= 32.\n  rewrite [X in _ <= X](_ : 32 = '| 32 |) //; apply/leP; apply Zabs_nat_le.\n  by split => //; first by apply min_u2Z.\n\nHoare_seq_replace1 init_id0 final_id.\n\n  unfold Hbu.\n  rewrite -(cat_take_drop 52%nat BU2) map_cat.\n  Rewrite_Precond @mapstos_fit_cat.\n    reflexivity.\n    by rewrite -map_cat cat_take_drop size_map sz_BU2 sz_BU1 inj_mult sz_BU sizeof_ityp Z_of_nat_Zabs_nat.\n  Rewrite_Postcond @mapstos_fit_con.\n    reflexivity.\n    by rewrite -map_cat cat_take_drop size_map sz_BU2 sz_BU1 inj_mult sz_BU sizeof_ityp Z_of_nat_Zabs_nat.\n  set Hbu1 := [ bu ]c |---> _.\n  rewrite size_map size_take sz_BU2 sz_BU1 sz_BU /= -(cat_take_drop (u2nat (BU2 `_ 51)) (drop 52 BU2)) map_cat.\n  Rewrite_Precond @mapstos_fit_cat.\n    reflexivity.\n    rewrite -map_cat cat_take_drop size_map size_drop sz_BU2 sz_BU1 sz_BU sizeof_ityp; by vm_compute.  rewrite size_map size_take size_drop sz_BU2 sz_BU1 sz_BU.\n  have Htmp : u2nat (BU2 `_ 51) < Z.abs_nat SSL_BUFFER_LEN - 52 by apply leq_ltn_trans with 32.\n  rewrite Htmp.\n  Rewrite_Postcond @mapstos_fit_con.\n    reflexivity.\n    rewrite -map_cat cat_take_drop size_map size_drop sz_BU2 sz_BU1 sz_BU sizeof_ityp; by vm_compute.\n  rewrite size_map size_take size_drop sz_BU2 sz_BU1 sz_BU Htmp.\n  set Hbu2 := [ bu ]c \\+ _ |---> _.\n  set Hbu3 := [ bu ]c \\+ _ \\+ _ |---> _.\n  rewrite /init_id0 -(cat_take_drop (u2nat (BU2 `_ 51)) (nseq 32 pv0)).\n  Rewrite_Precond @mapstos_fit_cat.\n    reflexivity.\n    rewrite cat_take_drop size_nseq sizeof_ityp; by vm_compute.\n  rewrite size_take (_ : (if _ then _ else _) = u2nat (BU2 `_ 51)); last first.\n     case: ifP => //.\n     move/negbT.\n     rewrite -leqNgt => H.\n     apply/eqP.\n     by rewrite eqn_leq H /= [in X in _ <= X](_ : 32 = Z.abs_nat 32).\n  have sess_len_SI : sess_len SI = nat<=u (BU2 `_ 51).\n    rewrite /sess_len (_ : sid = 43) // (_ : SI `_ 43 = BU2 `_ 51) // /nth' (nth_slices _ _ _ (esym BU2SI)) //=.\n    - apply (@leq_trans (5 + Z.abs_nat 45)) => //.\n      rewrite leq_add2l.\n      apply/leP.\n      by apply Zabs_nat_le.\n    - rewrite leqnn andbC /=.\n      apply (@leq_trans (Z.abs_nat 45)) => //.\n      by apply/leP/Zabs_nat_le.\n  have -> : drop (u2nat (BU2 `_ 51)) (nseq 32 pv0) = nseq (32 - sess_len SI) pv0.\n    move=> ? ?; by rewrite drop_nseq // sess_len_SI.\n  set init_id1 := [ id ]c |---> _.\n  rewrite {1}/u2nat Z_of_nat_Zabs_nat; last by apply min_u2Z.\n  set init_id2 := [ id ]c \\+ [ u2Z _ ]sc |---> _.\n  rewrite /final_rb /Final_rb /final_id /Final_id /sess_len_SI.\n  have SI_BU : SI |{ sid.+1, u2nat (BU2 `_ 51) ) = take (u2nat (BU2 `_ 51)) (drop 52 BU2).\n    rewrite (_: take (u2nat (BU2 `_ 51)) (drop 52 BU2) = BU2 |{ 52, (u2nat (BU2 `_ 51)))); last by [].\n    rewrite (_: sid.+1 = 44); last by [].\n    rewrite {1}(_: 44 = 5 + 39) // {1}(_: 52 = (8 + 5) + 39) //.\n    eapply slice_shift.\n    - symmetry; by apply BU2SI.\n    - apply/ltP; apply Nat2Z.inj_lt.\n      rewrite inj_plus Z_of_nat_Zabs_nat; last by lia.\n      rewrite /u2nat Z_of_nat_Zabs_nat; last by apply min_u2Z.\n      rewrite (_ : Z<=nat csuites.+1 = 45%Z) // /the_n_plus5 in Hsess_len_3'.\n      rewrite (_ : Z<=nat 39 = 39%Z) //; lia.\n  have size_slice_51 : size (SI |{ sid.+1, u2nat (BU2 `_ 51))) = u2nat (BU2 `_ 51).\n    rewrite SI_BU size_take size_drop (_ : u2nat (BU2 `_ 51) < size BU2 - 52) //.\n    apply leq_trans with (Z.abs_nat SSL_BUFFER_LEN - 52) => //; by rewrite sz_BU2 sz_BU1 sz_BU.\n  Rewrite_Postcond @mapstos_fit_con.\n    reflexivity.\n    by rewrite size_cat 1!size_map size_nseq sizeof_ityp sess_len_SI size_slice_51 subnKC.\n  rewrite size_map sess_len_SI size_slice_51 SI_BU Z_of_nat_Zabs_nat; last by apply min_u2Z.\n  set final_id1 := [ id ]c |---> _.\n  rewrite -sess_len_SI.\n  set final_id2 := [ id ]c \\+ [ u2Z (BU2 `_ 51) ]sc |---> _.\n  Hoare_frame (Hssl_session_0_length::Hbuf :: Hit :: Hbu2 :: init_id1 :: nil)\n             (Hssl_session_0_length::Hbuf :: Hit :: Hbu2 :: final_id1 :: nil).\n    by rewrite memcpy_input_inde.\n  rewrite /Hit /Hbuf /Hbu2 /init_id1 /final_id1.\n  apply hoare_stren with (`! \\b __buf \\= [ bu ]c \\+ [ 13 ]sc **\n   `! \\b __it \\= [ id ]c **\n   Hssl_session_0_length **\n   `! \\b (UINT) __ssl_session_0_length \\= [ zext 24 (BU2 `_ 51) ]pc **\n   __buf \\+ [ 39 ]sc |---> map phy_of_ui8 (take (u2nat (BU2 `_ 51)) (drop 52 BU2)) **\n   __it |---> take (u2nat (BU2 `_ 51)) (nseq 32 pv0)).\n    clear.\n    unfold Hssl_session_0_length.\n    set tmp := nseq 32 pv0.\n    rewrite [tmp]lock.\n    (* TODO: nseq gets simplified, need to remove simpl from Ent_R_rewrite_bbang_re *)\n    Ent_R_rewrite_eq_e 0 (*ssl_session_0_length*).\n    Ent_R_subst_con_distr.\n    do 6 Ent_LR_subst_apply.\n    Ent_R_rewrite_eq_p 0 (* buf *).\n    Ent_R_subst_con_distr.\n    do 6 Ent_LR_subst_apply.\n    Ent_R_rewrite_eq_p 0 (* it *).\n    Ent_R_subst_con_distr.\n    do 6 Ent_LR_subst_apply.\n    rewrite unsa_sa_i8_to_uchar_uint_to_phy.\n    do 2 rewrite -> beq_pxx.\n    do 2 rewrite -> beq_exx.\n    rewrite /= CaddnpA; last 3 first.\n      by rewrite sizeof_ityp.\n      by rewrite sizeof_ityp.\n      by rewrite sizeof_ityp.\n    rewrite sequiv_add_e_sc //.\n    Ent_decompose (0 :: nil) (4 :: nil); first by apply ent_id.\n    rewrite bbang1 !coneP; by apply ent_id.\n\n  apply hoare_weak with (`! \\b __buf \\= [ bu ]c \\+ [ 13 ]sc **\n    `! \\b __it \\= [ id ]c ** Hssl_session_0_length **\n    `! \\b (UINT) __ssl_session_0_length \\= [ zext 24 (BU2 `_ 51) ]pc **\n    __buf \\+ [ 39 ]sc |---> map phy_of_ui8 (take (u2nat (BU2 `_ 51)) (drop 52 BU2)) **\n    __it |---> map phy_of_ui8 (take (u2nat (BU2 `_ 51)) (drop 52 BU2))).\n    clear.\n    unfold Hssl_session_0_length at 1.\n    Ent_LR_rewrite_eq_p 0 (* buf *).\n    Ent_R_subst_con_distr.\n    do 5 Ent_L_subst_apply.\n    do 5 Ent_R_subst_apply.\n    Ent_LR_rewrite_eq_p 0 (* it *).\n    Ent_R_subst_con_distr.\n    do 9 Ent_LR_subst_apply.\n    Ent_decompose (3 :: nil) (4 :: nil); first by apply ent_id.\n    rewrite CaddnpA; last 3 first.\n      by rewrite sizeof_ityp.\n      by rewrite sizeof_ityp.\n      by rewrite sizeof_ityp.\n    rewrite sequiv_add_e_sc //.\n    Ent_decompose (0 :: nil) (0 :: nil); first by apply ent_id.\n    Ent_L_contract_bbang 0.\n    do 2 rewrite -> beq_pxx.\n    rewrite bbang1.\n    by Ent_monotony.\n  set tmp := nseq 32 pv0.\n  rewrite [tmp]lock.\n  Hoare_frame_idx_tmp (3 :: 4 :: 5 :: nil) (3 :: 4 :: 5 :: nil); first by rewrite memcpy_input_inde.\n  apply memcpy_triple => //.\n  - rewrite size_map size_take (_ : _ < _); last by rewrite size_drop sz_BU2 sz_BU1 sz_BU.\n    rewrite Z_of_nat_Zabs_nat; last exact: min_u2Z.\n    by rewrite (u2Z_zext 24).\n  - rewrite size_take -lock /= /u2nat (u2Z_zext 24).\n    case: ifP => //.\n    rewrite Z_of_nat_Zabs_nat //; last exact: min_u2Z.\n    move/negbT.\n    rewrite -leqNgt => H.\n    suff K : '| (Z<=u BU2 `_ 51) | = 32.\n      rewrite -[in X in X = _]K Z_of_nat_Zabs_nat //; exact: min_u2Z.\n    apply/eqP.\n    by rewrite eqn_leq H BU1_51.\n\n(** _buf39_plus_sess_len <-* __buf \\+ ([ 39 ]sc \\+ __sess_len); *)\n\nidtac \"47) lookup\".\n\n(* ciphen len part 1 *)\n\npose Shigh := [ BU2 `_ (52 + nat<=u (BU2 `_ 51)) ]pc : exp sigma (g.-ityp: uchar).\n\npose Hbuf39_plus_sess_len := `! \\b __buf39_plus_sess_len \\= Shigh.\nHoare_seq_ext Hbuf39_plus_sess_len.\n  Hoare_frame (Hbu :: Hbuf :: Hsess_len :: nil)\n             (Hbu :: Hbuf :: Hsess_len :: Hbuf39_plus_sess_len :: nil).\n  apply hoare_lookup_mapstos_fit_stren with (i := 52 + nat<=u (BU2 `_ 51)) (l := map phy_of_ui8 BU2) (e := [ bu ]c).\n  - by rewrite size_map sizeof_ityp sz_BU2 sz_BU1 inj_mult sz_BU.\n  - apply ent_R_lookup_mapstos_fit_trans.\n    + rewrite size_map sz_BU2 sz_BU1 sz_BU //.\n      apply leq_ltn_trans with (52 + 32); last by [].\n      by rewrite leq_add2l BU1_51.\n    + clear -BU_51.\n      unfold Hbu.\n      Ent_decompose (0 :: nil) (1 :: nil); first exact: ent_id.\n      unfold Hbuf, Hsess_len.\n      Ent_R_rewrite_eq_p 0 (* buf *).\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      Ent_LR_rewrite_eq_e 0 (* sess_len *).\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      rewrite sequiv_intsa_uchar_sc sequiv_add_e_sc_pos //; last 2 first.\n        exact: min_u2Z.\n        apply (@leZ_ltZ_trans (39 + 32)%Z) => //; lia.\n      rewrite CaddnpA; last 3 first.\n        by rewrite sizeof_ityp.\n        rewrite sizeof_ityp mul1Z.\n        move: (min_u2Z (BU2 `_ 51)) => ?; simpl expZ; lia.\n        rewrite sizeof_ityp !mul1Z addZA.\n        move: (min_u2Z (BU2 `_ 51)) => ?; simpl expZ; lia.\n      rewrite sequiv_add_e_sc_pos //; last 2 first.\n        move: (min_u2Z (BU2 `_ 51)) => ?; lia.\n        apply (@leZ_ltZ_trans (13 + (39 + 32))) => //; lia.\n      rewrite (_ : 13 + _ = Z.of_nat (52 + '| (u2Z (BU2 `_ 51)) |))%Z; last first.\n         rewrite inj_plus Zabs2Nat.id_abs Z.abs_eq; [ring | exact: min_u2Z].\n      rewrite beq_pxx bbang1; exact: ent_R_con_T.\n    + rewrite addnC.\n      Ent_R_subst_con_distr.\n      unfold Hbu, Hbuf, Hsess_len, Hbuf39_plus_sess_len.\n      do 4 Ent_LR_subst_apply.\n      do 2 apply monotony_L.\n      Ent_decompose (0 :: nil) (0 :: nil); first exact: ent_id.\n      rewrite (nth_map zero8); last first.\n        rewrite sz_BU2 sz_BU1 sz_BU.\n        apply leq_ltn_trans with (Z.abs_nat 32 + 52) => //.\n        rewrite leq_add2r.\n        apply/leP/Zabs2Nat.inj_le => //; exact: min_u2Z.\n      by rewrite addnC beq_exx bbang1.\n\n(** _buf40_plus_sess_len <-* __buf \\+ ([ 40 ]sc \\+ __sess_len); *)\n\nidtac \"48) lookup\".\n\npose Slow : @exp g sigma (g.-typ: ityp uchar) := [ BU2 `_ (53 + nat<=u (BU2 `_ 51)) ]pc.\n\npose Hbuf40_plus_sess_len := `! \\b __buf40_plus_sess_len \\= Slow.\nHoare_seq_ext Hbuf40_plus_sess_len.\n  Hoare_frame (Hbu :: Hbuf :: Hsess_len :: nil)\n             (Hbu :: Hbuf :: Hsess_len :: Hbuf40_plus_sess_len :: nil).\n  apply hoare_lookup_mapstos_fit_stren with (i := 53 + Z.abs_nat (u2Z (BU2 `_ 51))) (l := map phy_of_ui8 BU2) (e := [ bu ]c).\n  - rewrite size_map sizeof_ityp sz_BU2 sz_BU1 inj_mult sz_BU; by vm_compute.\n  - apply ent_R_lookup_mapstos_fit_trans.\n    + rewrite size_map sz_BU2 sz_BU1 sz_BU //.\n      apply leq_ltn_trans with (53 + 32); last by [].\n      by rewrite leq_add2l.\n    + unfold Hbu.\n      Ent_decompose (0 :: nil) (1 :: nil); first by apply ent_id.\n      unfold Hbuf, Hsess_len, Hsess_len_2.\n      Ent_R_rewrite_eq_p 0 (* buf *).\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      Ent_LR_rewrite_eq_e 0 (* sess_len *).\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      rewrite sequiv_intsa_uchar_sc sequiv_add_e_sc_pos //; last 2 first.\n        by apply min_u2Z.\n        apply (@leZ_ltZ_trans (40 + 32)%Z) => //; lia.\n      rewrite CaddnpA; last 3 first.\n        by rewrite sizeof_ityp.\n        clear -BU_51.\n        rewrite sizeof_ityp mul1Z.\n        move: (min_u2Z (BU2`_51)) => ?; simpl expZ; lia.\n        rewrite sizeof_ityp !mul1Z addZA.\n        move: (min_u2Z (BU2`_51)) => ?; simpl expZ; lia.\n      rewrite sequiv_add_e_sc_pos //; last 2 first.\n        clear -BU_51.\n        move: (min_u2Z (BU2 `_ 51)) => ?; lia.\n        clear -BU_51.\n        apply (@leZ_ltZ_trans (13 + (40 + 32))) => //; lia.\n      rewrite (_ : 13 + _ = Z.of_nat (53 + Z.abs_nat (u2Z (BU2 `_ 51))))%Z; last first.\n         rewrite inj_plus Zabs2Nat.id_abs Z.abs_eq; [ring | exact: min_u2Z].\n      rewrite beq_pxx bbang1; exact: ent_R_con_T.\n    + rewrite addnC.\n      Ent_R_subst_con_distr.\n      unfold Hbu, Hbuf, Hsess_len, Hbuf39_plus_sess_len.\n      do 4 Ent_LR_subst_apply.\n      Ent_decompose (0 :: 1 :: 2 :: nil) (0 :: 1 :: 2 :: nil); first by apply ent_id.\n      rewrite (nth_map zero8); last first.\n        rewrite sz_BU2 sz_BU1 sz_BU.\n        apply leq_ltn_trans with (Z.abs_nat 32 + 53) => //.\n        rewrite leq_add2r.\n        apply/leP/Zabs2Nat.inj_le => //; exact: min_u2Z.\n      by rewrite addnC beq_exx bbang1.\n\n(** _ciph_len <- (int) __buf39_plus_sess_len \\<\\< [ 8 ]sc \\| (int) __buf40_plus_sess_len; *)\n\nidtac \"49) assign\".\n\npose Hciph_len := `! \\b __ciph_len \\= ((int) Shigh \\<< [ 8 ]sc \\| (int) Slow).\nHoare_seq_ext Hciph_len.\n  Hoare_L_dup (Hbuf39_plus_sess_len :: Hbuf40_plus_sess_len :: nil).\n  unfold final_id, Final_id, final_rb, Final_rb.\n  Hoare_frame (Hbuf39_plus_sess_len :: Hbuf40_plus_sess_len :: nil) (Hciph_len :: nil).\n  apply hoare_assign_stren.\n  Ent_LR_subst_apply.\n  unfold Hbuf39_plus_sess_len.\n  Ent_LR_rewrite_eq_e 0. (* buf39+sess_len *)\n  do 2 Ent_LR_subst_apply.\n  Ent_LR_rewrite_eq_e 0. (* buf40+sess_len*)\n  Ent_LR_subst_apply.\n  by Ent_monotony0.\n\nHoare_L_contract_bbang Hbuf39_plus_sess_len.\nHoare_L_contract_bbang Hbuf40_plus_sess_len.\nclear Hbuf39_plus_sess_len Hbuf40_plus_sess_len.\n\n(**  If  \\b __ciph_len \\< [ 2 ]sc \\|| __ciph_len \\> [ 256 ]sc \\||\n          __ciph_len \\% 1 \\!= [ 0 ]sc \\||\n          [ Z<=nat 46 ]sc \\+ __sess_len \\+ __ciph_len \\>= [ 5 ]sc \\+ __n_old  Then *)\n(**   _ret <- [ POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ]c; Return *)\n\nidtac \"50) ifte\".\n\napply hoare_ifte_bang; first by apply POLAR_ret_err.\nrewrite -bbang_bneg_or.\nset Hciph_len_bound := `! \\~b \\b __ciph_len \\< [ 2 ]sc \\|| __ciph_len \\> [ 256 ]sc \\|| __ciph_len \\% 1 \\!= [ 0 ]sc.\nset Hciph_len_bound2 := `! \\~b \\b [Z<=nat compmeth ]sc \\+ __sess_len \\+ __ciph_len \\>= [ 5 ]sc \\+ __n_old.\npose ciph_len_exp : exp sigma _ := (int) Shigh \\<< [ 8 ]sc \\| (int) Slow.\npose ciph_len_value := @ground_exp g sigma _ ciph_len_exp erefl.\npose ciph_len_value_Z := s2Z (si32<=phy ciph_len_value).\npose ciph_len_value_nat := '| ciph_len_value_Z |.\nHoare_stren_pull_out (Hciph_len ** Hciph_len_bound) (2 <= ciph_len_value_Z <= 256)%Z.\n  rewrite /Hciph_len /Hciph_len_bound. rewrite -/ciph_len_exp.\n  rewrite <- bbang_bneg_or.\n  rewrite <- bbang_bneg_or.\n  rewrite -CleqNgt -CgeqNlt.\n  Ent_LR_rewrite_eq_e 0 (* ciph_len *).\n  do 4 Ent_LR_subst_apply.\n  Ent_L_contract_bbang 2.\n  Bbang2sbang.\n  Ent_L_sbang 0 => H1.\n  Ent_L_sbang 0 => H2.\n  Ent_R_sbang 0; last by [].\n  rewrite -(ground_bexp_sem (@store0 _ sigma))in H1; apply bop_re_ge_Zge in H1.\n  rewrite -(ground_bexp_sem (@store0 _ sigma))in H2; apply bop_re_le_Zle in H2.\n  rewrite 2!(ground_exp_sem (@store0 _ sigma)) -/ciph_len_value -/ciph_len_value_Z s2Z_ge_s_cst_e // in H1.\n  rewrite 2!(ground_exp_sem (@store0 _ sigma)) -/ciph_len_value -/ciph_len_value_Z s2Z_ge_s_cst_e // in H2.\n  lia.\nmove => Hciph_len_bound_Z.\n\nhave Hciph_len_bound_nat : 2 <= ciph_len_value_nat <= 256.\n  rewrite [X in _ <= _ <= X](_ : 256%nat = Z.abs_nat 256) // [X in X < _ <= _](_ : 1%nat = Z.abs_nat 1) //.\n  apply/andP; split.\n    apply/ltP/Zabs_nat_lt; lia.\n  apply/leP/Zabs_nat_le; lia.\n\npose Hciph_len_bound2'' := !!(Z<=nat compmeth + Z<=u BU2 `_ 51 + ciph_len_value_Z < the_n_plus5)%Z.\nHoare_L_stren_by Hciph_len_bound2'' (Hsess_len :: Hn_old :: Hciph_len :: Hciph_len_bound2 :: nil).\n  unfold Hn_old, Hsess_len, Hciph_len, Hciph_len_bound2.\n  Ent_LR_rewrite_eq_e 0 (* ciph_len *).\n  do 4 Ent_LR_subst_apply.\n  fold Hciph_len_bound2''.\n  Ent_LR_rewrite_eq_e 0 (* sess_len *).\n  do 3 Ent_LR_subst_apply.\n  fold Hciph_len_bound2''.\n  Ent_LR_rewrite_eq_e 0 (* n old *).\n  do 2 Ent_LR_subst_apply.\n  rewrite -/Shigh -/Slow -/ciph_len_exp.\n  Bbang2sbang.\n  apply ent_sbang_sbang.\n  rewrite gb_bneg_bop_r_ge.\n  move/Zlt_gb. move/(_ erefl erefl).\n  rewrite si32_of_phy_gb_add_e si32_of_phy_gb_add_e si32_of_phy_gb_add_e ge_cast_sint_cst_8c.\n  rewrite (phy_of_si32K (zext 24 BU2 `_ 51)) 3!i32_ge_s_cst_e -/ciph_len_value.\n  have H1 : (0 <= Z<=nat compmeth + Z<=u BU2 `_ 51 + ciph_len_value_Z < 2 ^^ 31)%Z.\n    split.\n      apply (@leZ_trans (Z0 + Z0 + 2)) => //.\n      apply leZ_add => //.\n      apply leZ_add => //; exact: min_u2Z.\n    by case: Hciph_len_bound_Z.\n    apply (@leZ_ltZ_trans (Z<=nat compmeth + 2 ^^ 8 + 256)) => //.\n    apply leZ_add.\n      exact/leZ_add2l/ltZW/max_u2Z.\n    by case: Hciph_len_bound_Z.\n  have -> : (Z<=s ((Z2s 32 (Z<=nat compmeth) `+ zext 24 BU2 `_ 51) `+\n        si32<=phy ciph_len_value) = Z<=nat compmeth + u2Z (BU2 `_ 51) + ciph_len_value_Z)%Z.\n    rewrite s2Z_add; last first.\n      rewrite s2Z_add; last first.\n        rewrite Z2sK // (s2Z_zext 24) //.\n        move: (min_u2Z BU2 `_ 51) => ?; lia.\n      rewrite Z2sK // (s2Z_zext 24) // -/ciph_len_value_Z; lia.\n    rewrite s2Z_add; last first.\n      rewrite Z2sK // (s2Z_zext 24) //.\n      move: (min_u2Z BU2 `_ 51) => ?; lia.\n    by rewrite Z2sK // (s2Z_zext 24).\n  rewrite s2Z_add; last first.\n    rewrite Z2sK // Z2sK; last by simpl expZ; lia.\n    simpl expZ; lia.\n  rewrite Z2sK // Z2sK; last by simpl expZ; lia.\n  apply.\n  exact H1.\n  simpl expZ; lia.\n\napply hoare_pullout_sbang => Hciph_len_bound2'.\nclear Hciph_len_bound2''.\nHoare_L_contract_bbang Hciph_len_bound2; clear Hciph_len_bound2.\n\n(** _comp_len' <-* __buf \\+ ([ 41 ]sc \\+ __sess_len \\+ __ciph_len); *)\n\nidtac \"51) lookup\".\n\npose comp_len'_exp : exp sigma (ityp: uchar) := [ BU2 `_ (54 + u2nat (BU2 `_ 51) + ciph_len_value_nat) ]pc.\npose comp_len'_value := @ground_exp g sigma _ comp_len'_exp erefl.\npose comp_len'_value_nat := nat<=u (i8<=phy comp_len'_value).\npose Hcomp_len' := `! \\b __comp_len' \\= [comp_len'_value]c.\nHoare_seq_ext Hcomp_len'.\n  Hoare_L_dup (Hsess_len :: Hsess_len_2 :: Hciph_len :: Hciph_len_bound::nil).\n  unfold final_id, Final_id, final_rb, Final_rb.\n  Hoare_frame (Hbu :: Hbuf :: Hsess_len :: Hsess_len_2 :: Hciph_len :: Hciph_len_bound :: nil)\n    (Hbu :: Hbuf :: Hcomp_len' :: nil).\n  apply hoare_lookup_mapstos_fit_stren with (i := 54 + u2nat (BU2 `_ 51) + ciph_len_value_nat) (l := map phy_of_ui8 BU2) (e := [ bu ]c).\n  - rewrite size_map sizeof_ityp sz_BU2 sz_BU1 inj_mult sz_BU; by vm_compute.\n  - apply ent_R_lookup_mapstos_fit_trans.\n    + rewrite size_map sz_BU2 sz_BU1 sz_BU // /SSL_BUFFER_LEN -(_: '| 54 | = 54%nat) // /ciph_len_value_nat.\n      move: (min_u2Z (BU2 `_ 51)) => ?.\n      rewrite -!plusE -Zabs_nat_Zplus // -Zabs_nat_Zplus; last 2 first.\n        apply addZ_ge0 => //; exact: min_u2Z.\n        case: Hciph_len_bound_Z => Htmp _; by apply: leZ_trans; last by apply Htmp.\n      apply/ltP; apply Zabs2Nat.inj_lt; lia.\n    + unfold Hbu.\n      Ent_decompose (0 :: nil) (1 :: nil); first by apply ent_id.\n      rewrite /Hbuf /Hsess_len /Hciph_len /Hsess_len_2 /Hciph_len_bound -/ciph_len_exp.\n      Ent_L_contract_bbang 2.\n      Ent_L_contract_bbang 3.\n      Ent_LR_rewrite_eq_p 0 (* buf *).\n      do 2 Ent_LR_subst_apply.\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      Ent_LR_rewrite_eq_e 0 (* sess_len *).\n      Ent_LR_subst_apply.\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      rewrite -/Slow -/Shigh -/ciph_len_exp.\n      Ent_LR_rewrite_eq_e 0 (* ciph_len *).\n      Ent_R_subst_con_distr.\n      do 2 Ent_LR_subst_apply.\n      Bbang2sbang.\n      Ent_R_sbang 0; last by [].\n      rewrite -(ground_bexp_sem (store0 sigma)).\n      rewrite beval_eq_p_eq.\n      clear -BU_51 Hciph_len_bound_Z.\n      move: (min_u2Z (BU2 `_ 51)) => ?.\n      have Hoverflow:\n        (s2Z (si32<=phy (ground_exp ([ 41 ]sc \\+ (int) ([ BU2 `_ 51 ]pc : exp sigma (ityp: uchar)) \\+ ciph_len_exp) erefl)) =\n         41 + u2Z (BU2 `_ 51) + s2Z (si32<=phy (ground_exp ciph_len_exp erefl)))%Z.\n        rewrite 2!si32_of_phy_gb_add_e (@i32_ge_s_cst_e g sigma) ge_cast_sint_cst_8c.\n        rewrite phy_of_si32K 2!s2Z_add Z2sK // (s2Z_zext 24) // -/ciph_len_value_Z; simpl expZ; lia.\n      case: Hciph_len_bound_Z => H H0.\n      rewrite eval_add_pA; first last.\n      - rewrite Hoverflow sizeof_ityp [sizeof_integral _]/= 2!mul1Z si32_of_phy_sc Z2sK // -/ciph_len_value_Z.\n        simpl expZ; lia.\n      - rewrite Hoverflow sizeof_ityp [sizeof_integral _]/= mul1Z -/ciph_len_value_Z.\n        simpl expZ; lia.\n      - by rewrite sizeof_ityp [sizeof_integral _]/= mul1Z si32_of_phy_sc Z2sK.\n      rewrite -beval_eq_p_eq.\n      apply Ceqpn_add2l'.\n      rewrite beval_eq_e_eq.\n      apply/eqP/si32_of_phy_inj.\n      rewrite 3!si32_of_phy_binop_ne 3!si32_of_phy_sc.\n      apply s2Z_inj.\n      rewrite (ground_exp_sem (store0 sigma)) (@ge_cast_sint_cst_8c g sigma) phy_of_si32K // Z2sK; last first.\n        rewrite 2!inj_plus Z_of_nat_Zabs_nat; last by apply min_u2Z.\n        rewrite (_ : Z<=nat 54 = 54%Z) // /ciph_len_value_Z Z_of_nat_Zabs_nat; simpl expZ; lia.\n      rewrite s2Z_add Z2sK // s2Z_add // -/ciph_len_value_Z s2Z_add Z2sK // (s2Z_zext 24) //; try by simpl expZ; lia.\n      rewrite !inj_plus Z_of_nat_Zabs_nat; last by apply min_u2Z.\n      rewrite /ciph_len_value_nat (_ : Z<=nat 54 = 54%Z) // Z_of_nat_Zabs_nat; last by lia.\n      ring.\n  + Ent_R_subst_con_distr.\n    rewrite [nth]lock.\n    do 3 Ent_LR_subst_apply.\n    Ent_decompose (0 :: 1 :: nil) (0 :: 1 :: nil); first by apply ent_id.\n    do 4 Ent_L_contract_bbang 0.\n    Bbang2sbang.\n    Ent_R_sbang 0; last by [].\n    rewrite -lock gb_eq_e; apply/eqP.\n    rewrite /comp_len'_value /comp_len'_exp 3!ge_cst_e (nth_map (Z2u 8 0)) // sz_BU2 sz_BU1 sz_BU /SSL_BUFFER_LEN.\n    apply ltn_trans with (54 + 32 + 256 + 1); last by vm_compute.\n    rewrite -!addnA ltn_add2l ltn_leq_add2l // -(addn0 ciph_len_value_nat) ltn_leq_add2l //.\n    by case/andP : Hciph_len_bound_nat.\n\n(** _comp_len <- (int) __comp_len'; *)\n\nidtac \"52) assign\".\n\npose comp_len_exp := (int) ([ BU2 `_ (54 + u2nat (BU2 `_ 51) + ciph_len_value_nat) ]pc : exp sigma (ityp: uchar)).\npose comp_len_value := @ground_exp _ sigma _ comp_len_exp erefl.\npose Hcomp_len := `! \\b __comp_len \\= [comp_len_value]c.\nHoare_seq_ext Hcomp_len.\n  Hoare_L_dup (Hcomp_len' :: nil).\n  unfold final_id, Final_id, final_rb, Final_rb.\n  Hoare_frame (Hcomp_len' :: nil) (Hcomp_len :: nil).\n  apply hoare_assign_stren.\n  unfold Hcomp_len, Hcomp_len'.\n  Ent_LR_subst_apply.\n  Ent_LR_rewrite_eq_e 0 (* comp_len'*).\n  Ent_LR_subst_apply.\n  Bbang2sbang; Ent_R_sbang 0; last by [].\n  unfold comp_len_value, comp_len'_value.\n  Rewrite_ground_bexp @sequiv_ge.\n  Rewrite_ground_bexp @sequiv_ge.\n  Rewrite_ground_bexp @beq_exx.\n  exact: oneuc.\n\n(** IIf  \\b __comp_len \\< [ 1 ]sc \\|| __comp_len \\> [ 16 ]sc \\||\n          [ Z<=nat 47 ]sc \\+ __sess_len \\+ __ciph_len \\+ __comp_len \\!=\n          [ 5 ]sc \\+ __n_old  Then *)\n(**   _ret <- [ POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ]c; Return *)\n\nidtac \"53) ifte\".\napply hoare_ifte_bang; first by apply POLAR_ret_err.\nrewrite -bbang_bneg_or.\nset Hextensions := `! \\~b \\b [ Z<=nat compmeth.+1 ]sc \\+ __sess_len \\+ __ciph_len \\+ __comp_len \\!= [ 5 ]sc \\+ __n_old.\n\nHoare_L_contract_bbang Hcomp_len'.\nclear Hcomp_len' comp_len'_value comp_len'_exp comp_len'_value_nat.\n\n(** \"_goto_have_cipher_\" <- [ 0 ]sc; *)\n\nidtac \"54) assign\".\n\npose H_goto_have_cipher := `! \\b __goto_have_cipher \\= [ 0 ]sc.\nHoare_seq_ext H_goto_have_cipher.\n  Hoare_frame (@nil assert) (H_goto_have_cipher :: nil).\n  apply hoare_assign_stren.\n  Ent_LR_subst_apply.\n  Bbang2sbang.\n  Ent_R_sbang 0; last by [].\n  Rewrite_ground_bexp @sequiv_bop_re_sc => //=.\n  exact: oneuc.\n\nidtac \"before apply POLAR_parse_client_hello_triple3\".\n\nby apply POLAR_parse_client_hello_triple3 with (BU := BU) (in_left0 := in_left) (BU1 := BU1).\nQed.\n\nEnd POLAR_parse_client_hello_triple.\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/POLAR_parse_client_hello_triple2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.31405055141190724, "lm_q1q2_score": 0.16193071417662336}}
{"text": "(**\n\nThis file describes the field grouping transformation.\n\nAuthor: Ramon Fernandez I Mir and Arthur Chargu\u00e9raud.\n\nLicense: MIT.\n\n*)\n\n\nSet Implicit Arguments.\nRequire Export Semantics LibSet LibMap Typing TLCbuffer.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Definition of the transformation *)\n\n(** Grouping transformation. Specified by:\n    - The name of the struct to be modified.\n    - The set of fields to be grouped.\n    - The name of the new struct that will hold the fields to be grouped.\n    - The name of the field in the new struct that will have as type\n      the new struct. *)\n\nRecord group_tr := make_group_tr {\n  group_tr_struct_name : typvar;\n  group_tr_fields : set field;\n  group_tr_new_struct_name : typvar;\n  group_tr_new_struct_field : field\n}.\n\nNotation make_group_tr' := make_group_tr.\n\n(** Checking if the transformation is acceptable *)\n\nInductive group_tr_ok : group_tr -> typdefctx -> Prop :=\n  | group_tr_ok_intros : forall Tfs Tt fs fg Tg gt C,\n      gt = make_group_tr Tt fs Tg fg ->\n      Tt \\indom C ->\n      C[Tt] = typ_struct Tfs ->\n      Tg \\notindom C ->\n      fs \\c dom Tfs ->\n      fg \\notindom Tfs ->\n      (forall Tv,\n        Tv \\indom C ->\n        Tv <> Tt ->\n        ~ free_typvar C Tt C[Tv]) ->\n      group_tr_ok gt C.\n\n\n(* ---------------------------------------------------------------------- *)\n(** The transformation applied to the different constructs. *)\n\n(** Transformation of typdefctxs: C ~ |C| *)\n\nInductive tr_struct_map (gt:group_tr) : map field typ -> map field typ -> map field typ  -> Prop :=\n  | tr_struct_map_intro : forall Tfs Tfs' Tfs'' Tt fs Tg fg,\n      gt = make_group_tr Tt fs Tg fg ->\n      dom Tfs' = (dom Tfs \\- fs) \\u \\{fg} ->\n      Tfs'[fg] = typ_var Tg ->\n      (forall f,\n        f \\indom Tfs ->\n        f \\notin fs ->\n        Tfs'[f] = Tfs[f]) ->\n      dom Tfs'' = fs ->\n      (forall f,\n        f \\indom Tfs'' ->\n        Tfs''[f] = Tfs[f]) ->\n      tr_struct_map gt Tfs Tfs' Tfs''.\n\nInductive tr_typdefctx (gt:group_tr) : typdefctx -> typdefctx -> Prop :=\n  | tr_typdefctx_intro : forall Tfs Tfs' Tfs'' Tt fs Tg fg C C',\n      gt = make_group_tr Tt fs Tg fg ->\n      dom C' = dom C \\u \\{Tg} ->\n      C[Tt] = typ_struct Tfs ->\n      C'[Tt] = typ_struct Tfs' ->\n      C'[Tg] = typ_struct Tfs'' ->\n      (forall T,\n        T \\indom C ->\n        T <> Tt ->\n        C'[T] = C[T]) ->\n      tr_struct_map gt Tfs Tfs' Tfs'' ->\n      tr_typdefctx gt C C'.\n\n(** Transformation of paths: \u03c0 ~ |\u03c0| *)\n\nInductive tr_accesses (gt:group_tr) : accesses -> accesses -> Prop :=\n  | tr_accesses_nil :\n      tr_accesses gt nil nil\n  | tr_accesses_array : forall \u03c0 \u03c0' T i,\n      tr_accesses gt \u03c0 \u03c0' ->\n      tr_accesses gt ((access_array T i)::\u03c0) ((access_array T i)::\u03c0')\n  | tr_accesses_field_group : forall Tt fs fg Tg f a0 \u03c0 a1 a2 \u03c0',\n      tr_accesses gt \u03c0 \u03c0' ->\n      gt = make_group_tr Tt fs Tg fg ->\n      f \\in fs ->\n      a0 = access_field (typ_var Tt) f ->\n      a1 = access_field (typ_var Tt) fg ->\n      a2 = access_field (typ_var Tg) f ->\n      tr_accesses gt (a0::\u03c0) (a1::a2::\u03c0')\n  | tr_accesses_field_other : forall T Tt \u03c0 \u03c0' f,\n      tr_accesses gt \u03c0 \u03c0' ->\n      Tt = group_tr_struct_name gt ->\n      (T <> (typ_var Tt) \\/ f \\notin (group_tr_fields gt)) ->\n      tr_accesses gt ((access_field T f)::\u03c0) ((access_field T f)::\u03c0').\n\n(** Transformation of values: v ~ |v| *)\n\nInductive tr_val (gt:group_tr) : val -> val -> Prop :=\n  | tr_val_uninitialized :\n      tr_val gt val_uninitialized val_uninitialized\n  | tr_val_unit :\n      tr_val gt val_unit val_unit\n  | tr_val_bool : forall b,\n      tr_val gt (val_bool b) (val_bool b)\n  | tr_val_int : forall i,\n      tr_val gt (val_int i) (val_int i)\n  | tr_val_double : forall d,\n      tr_val gt (val_double d) (val_double d)\n  | tr_val_abstract_ptr : forall l \u03c0 \u03c0',\n      tr_accesses gt \u03c0 \u03c0' ->\n      tr_val gt (val_abstract_ptr l \u03c0) (val_abstract_ptr l \u03c0')\n  | tr_val_array : forall a T a',\n      length a = length a' ->\n      (forall i,\n        index a i ->\n        tr_val gt a[i] a'[i]) ->\n      tr_val gt (val_array T a) (val_array T a')\n  | tr_val_struct_group : forall Tt Tg s s' fg fs sg,\n      gt = make_group_tr Tt fs Tg fg ->\n      fs \\c dom s ->\n      fg \\notindom s ->\n      dom s' = (dom s \\- fs) \\u \\{fg} ->\n      dom sg = fs ->\n      (forall f,\n        f \\indom sg ->\n        tr_val gt s[f] sg[f]) ->\n      (forall f,\n        f \\notin fs ->\n        f \\indom s ->\n        tr_val gt s[f] s'[f]) ->\n      s'[fg] = val_struct (typ_var Tg) sg ->\n      tr_val gt (val_struct (typ_var Tt) s) (val_struct (typ_var Tt) s')\n  | tr_val_struct_other : forall Tt T s s',\n      Tt = group_tr_struct_name gt ->\n      T <> (typ_var Tt) ->\n      dom s = dom s' ->\n      (forall f,\n        f \\indom s ->\n        tr_val gt s[f] s'[f]) ->\n      tr_val gt (val_struct T s) (val_struct T s').\n\n(** Transformation used in the struct cases to avoid repetition. *)\n\nInductive tr_struct_op (gt:group_tr) : trm -> trm -> Prop :=\n  | tr_struct_op_group_access : forall fs Tt fg Tg f op0 op1 op2 ts,\n      gt = make_group_tr Tt fs Tg fg ->\n      f \\in fs ->\n      op0 = prim_struct_access (typ_var Tt) f ->\n      op1 = prim_struct_access (typ_var Tt) fg ->\n      op2 = prim_struct_access (typ_var Tg) f ->\n      tr_struct_op gt (trm_app op0 ts) (trm_app op2 ((trm_app op1 ts)::nil))\n  | tr_struct_op_group_get : forall fs Tt fg Tg f op0 op1 op2 ts,\n      gt = make_group_tr Tt fs Tg fg ->\n      f \\in fs ->\n      op0 = prim_struct_get (typ_var Tt) f ->\n      op1 = prim_struct_get (typ_var Tt) fg ->\n      op2 = prim_struct_get (typ_var Tg) f ->\n      tr_struct_op gt (trm_app op0 ts) (trm_app op2 ((trm_app op1 ts)::nil))\n  | tr_struct_op_other_access : forall Tt fs Tg fg T f op ts,\n      gt = make_group_tr Tt fs Tg fg ->\n      op = prim_struct_access T f ->\n      T <> (typ_var Tt) \\/ f \\notin fs ->\n      tr_struct_op gt (trm_app op ts) (trm_app op ts)\n  | tr_struct_op_other_get : forall Tt fs Tg fg T f op ts,\n      gt = make_group_tr Tt fs Tg fg ->\n      op = prim_struct_get T f ->\n      T <> (typ_var Tt) \\/ f \\notin fs ->\n      tr_struct_op gt (trm_app op ts) (trm_app op ts).\n\n(** Transformation of terms: t ~ |t| *)\n\nInductive tr_trm (gt:group_tr) : trm -> trm -> Prop :=\n  | tr_trm_val : forall v v',\n      tr_val gt v v' ->\n      tr_trm gt (trm_val v) (trm_val v')\n  | tr_trm_var : forall x,\n      tr_trm gt (trm_var x) (trm_var x)\n  | tr_trm_if : forall t1 t2 t3 t1' t2' t3',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt t3 t3' ->\n      tr_trm gt (trm_if t1 t2 t3) (trm_if t1' t2' t3')\n  | tr_trm_let : forall x t1 t2 t1' t2',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt (trm_let x t1 t2) (trm_let x t1' t2')\n  (* Special case: structs *)\n  | tr_trm_struct_op : forall t1' op t1 tr,\n      is_struct_op op ->\n      tr_trm gt t1 t1' ->\n      tr_struct_op gt (trm_app op (t1'::nil)) tr ->\n      tr_trm gt (trm_app op (t1::nil)) tr\n  (* Args *)\n  | tr_trm_binop : forall op t1 t1' t2 t2',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt (trm_app (prim_binop op) (t1::t2::nil)) (trm_app (prim_binop op) (t1'::t2'::nil))\n  | tr_trm_get : forall T t1 t1',\n      tr_trm gt t1 t1' ->\n      tr_trm gt (trm_app (prim_get T) (t1::nil)) (trm_app (prim_get T) (t1'::nil))\n  | tr_trm_set : forall T t1 t1' t2 t2',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt (trm_app (prim_set T) (t1::t2::nil)) (trm_app (prim_set T) (t1'::t2'::nil))\n  | tr_trm_new : forall T,\n      tr_trm gt (trm_app (prim_new T) nil) (trm_app (prim_new T) nil)\n  | tr_trm_new_array : forall T t1 t1',\n      tr_trm gt t1 t1' ->\n      tr_trm gt (trm_app (prim_new_array T) (t1::nil)) (trm_app (prim_new_array T) (t1'::nil))\n  | tr_trm_array_access : forall T t1 t1' t2 t2',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt (trm_app (prim_array_access T) (t1::t2::nil)) (trm_app (prim_array_access T) (t1'::t2'::nil))\n  | tr_trm_array_get : forall T t1 t1' t2 t2',\n      tr_trm gt t1 t1' ->\n      tr_trm gt t2 t2' ->\n      tr_trm gt (trm_app (prim_array_get T) (t1::t2::nil)) (trm_app (prim_array_get T) (t1'::t2'::nil)).\n\n(** Transformation of stacks: S ~ |S| *)\n\nInductive tr_stack_item (gt:group_tr) : (var * val) -> (var * val) -> Prop :=\n  | tr_stack_item_intro : forall x v v',\n      tr_val gt v v' -> \n      tr_stack_item gt (x, v) (x, v').\n\nInductive tr_stack (gt:group_tr) : stack -> stack -> Prop :=\n  | tr_stack_intro : forall S S',\n      LibList.Forall2 (tr_stack_item gt) S S' ->\n      tr_stack gt S S'.\n\nLemma stack_lookup_tr : forall gt S S' x v,\n  tr_stack gt S S' ->\n  Ctx.lookup x S = Some v -> \n    exists v', \n       Ctx.lookup x S' = Some v' \n    /\\ tr_val gt v v'.\nProof using.\n  introv HS Hx. inverts HS as HS. induction HS.\n  { inverts Hx. }\n  { inverts H as Hv. inverts Hx as Hx. case_if in Hx.\n    { inverts Hx. exists v'. splits*. unfolds. case_if*. }\n    { forwards (v''&Hx'&Hv''): IHHS Hx. exists v''.\n      splits*. unfolds. case_if. fold Ctx.lookup. auto. } }\nQed.\n\n(** Transformation of states: m ~ |m| *)\n\nInductive tr_state (gt:group_tr) : state -> state -> Prop :=\n  | tr_state_intro : forall m m',\n      dom m = dom m' ->\n      (forall l,\n        l \\indom m ->\n        tr_val gt m[l] m'[l]) ->\n      tr_state gt m m'.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Hints *)\n\nHint Resolve TLCbuffer.index_of_index_length.\n\nHint Constructors red.\nHint Constructors tr_trm tr_val tr_accesses tr_state tr_stack.\nHint Constructors read_accesses write_accesses.\nHint Constructors is_uninitialized.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Functionality of the relations *)\n\n(** The relation [tr_accesses] is a (partial) function. *)\n\nTheorem functional_tr_accesses : forall gt \u03c0 \u03c01 \u03c02,\n  tr_accesses gt \u03c0 \u03c01 ->\n  tr_accesses gt \u03c0 \u03c02 ->\n    \u03c01 = \u03c02.\nProof using.\n  introv H1 H2. gen \u03c02. induction H1; intros;\n  inverts_head tr_accesses; repeat fequals*; \n  inverts_head access_field; subst; simpls;\n  inverts_head Logic.or; repeat fequals*.\nQed.\n\n(** The relation [tr_val] is a (partial) function. *)\n\nTheorem functional_tr_val : forall gt v v1 v2,\n  tr_val gt v v1 ->\n  tr_val gt v v2 ->\n  v1 = v2.\nProof using.\n  introv H1 H2. gen v2. induction H1; intros;\n  inverts_head tr_val; fequals*; subst; simpls; tryfalse.\n  { fequals. applys* functional_tr_accesses. }\n  { applys* eq_of_extens. math. introv Hi.\n    asserts: (index a i).\n    { rewrite index_eq_index_length in *. rewrite~ H. }\n    applys~ H1. }\n  { applys read_extens. \n    { inverts_head make_group_tr'. congruence. }\n    { introv Hin. tests C: (i = fg).\n      { inverts_head make_group_tr'.\n        asserts_rewrite~ (s'0[fg0] = val_struct (typ_var Tg0) sg0).\n        asserts_rewrite~ (s'[fg0] = val_struct (typ_var Tg0) sg).\n        fequals. applys~ read_extens. introv Hk.\n        asserts_rewrite* (dom sg = dom sg0) in *. }\n      { inverts_head make_group_tr'.\n        asserts_rewrite~ (dom s' = dom s \\- dom sg \\u '{fg0}) in Hin.\n        inverts Hin as Hin; tryfalse. inverts Hin as Hin Hnotin.\n        asserts_rewrite* (dom sg = dom sg0) in *. } } }\n  { applys read_extens.\n    { congruence. }\n    { introv Hin. \n      asserts_rewrite* (dom s' = dom s) in *. } }\nQed.\n\n(** The relation [tr_struct_op] is a (partial) function. *)\n\nLemma functional_tr_struct_op : forall gt op t1 tr1 tr2,\n  is_struct_op op ->\n  tr_struct_op gt (trm_app op (t1 :: nil)) tr1 ->\n  tr_struct_op gt (trm_app op (t1 :: nil)) tr2 ->\n  tr1 = tr2.\nProof using.\n  introv Hop Htr1 Htr2. induction Htr1; \n  subst; inverts Htr2;\n  try inverts_head Logic.or;\n  try inverts_head make_group_tr'; simpls;\n  try inverts_head prim_struct_access;\n  try inverts_head prim_struct_get;\n  repeat fequals*.\nQed.\n\n(** The relation [tr_trm] is a (partial) function. *)\n\nTheorem functional_tr_trm : forall gt t t1 t2,\n  tr_trm gt t t1 ->\n  tr_trm gt t t2 ->\n  t1 = t2.\nProof using.\n  introv H1 H2. gen t2. induction H1; intros;\n  try solve [ inverts H2 ; try subst ; repeat fequals* ].\n  { inverts H2. fequals. applys* functional_tr_val. }\n  { inverts_head tr_trm; subst.\n    { forwards~: IHtr_trm t1'0. subst.\n      applys* functional_tr_struct_op. }\n    { false. }\n    { false. } }\n  { inverts_head tr_trm; tryfalse.\n    forwards~: IHtr_trm t1'0. fequals. }\n  { inverts_head tr_trm; tryfalse.\n    forwards~: IHtr_trm t1'0. fequals.  }\nQed.\n\n(** The relation [tr_stack_item] is a (partial) function. *)\n\nTheorem functional_tr_stack_item : forall gt i i1 i2,\n  tr_stack_item gt i i1 ->\n  tr_stack_item gt i i2 ->\n  i1 = i2.\nProof using.\n  introv Hi1 Hi2.\n  inverts Hi1 as H. inverts Hi2 as H'.\n  forwards*: functional_tr_val H H'.\nQed.\n\n(** The relation [tr_stack] is a (partial) function. *)\n\nTheorem functional_tr_stack : forall gt S S1 S2,\n  tr_stack gt S S1 ->\n  tr_stack gt S S2 ->\n  S1 = S2.\nProof using.\n  introv HS1 HS2. inverts HS1 as HS1. inverts HS2 as HS2. \n  gen S2. induction HS1; intros.\n  { inverts~ HS2. }\n  { inverts HS2 as HSy0 HS1'. fequals.\n    { forwards*: functional_tr_stack_item H HSy0. }\n    { applys~ IHHS1. } }\nQed.\n\n(** The relation [tr_state] is a (partial) function. *)\n\nTheorem functional_tr_state : forall gt m m1 m2,\n  tr_state gt m m1 ->\n  tr_state gt m m2 ->\n  m1 = m2.\nProof using.\n  introv Hm1 Hm2. \n  inverts Hm1 as HD1 Htr1. inverts Hm2 as HD2 Htr2.\n  applys read_extens.\n  { unfolds state. congruence. }\n  { introv Hi. rewrite HD1 in *. \n    forwards Hm1i: Htr1 Hi. forwards Hm2i: Htr2 Hi.\n    forwards~: functional_tr_val Hm1i Hm2i. }\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Correctness of the transformation *)\n\nSection TransformationsProofs.\n\n(** Path surgery. *)\n\nLemma tr_accesses_app : forall gt \u03c01 \u03c02 \u03c01' \u03c02',\n  tr_accesses gt \u03c01 \u03c01' ->\n  tr_accesses gt \u03c02 \u03c02' ->\n  tr_accesses gt (\u03c01 ++ \u03c02) (\u03c01' ++ \u03c02').\nProof using.\n  introv Ha1 Ha2. gen \u03c02 \u03c02'. induction Ha1; intros;\n  rew_list in *; eauto. \nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Regularity of the transformation with respect to values *)\n\n(** The transformation preserves basic values. *)\n\nLemma is_basic_tr : forall gt v1 v2,\n  tr_val gt v1 v2 ->\n  is_basic v1 ->\n  is_basic v2.\nProof using.\n  introv Htr Hv1. induction Htr;\n  try solve [ inverts Hv1 ];\n  constructors~.\nQed.\n\n(** The transformation preserves being a term. *)\n\nLemma not_is_val_tr : forall gt t1 t2,\n  tr_trm gt t1 t2 ->\n  ~ is_val t1 ->\n  ~ is_val t2.\nProof using.\n  introv Htr Hv. induction Htr; introv HN;\n  try solve [ subst ; inverts HN ]. forwards*: Hv.\n  inverts_head tr_struct_op; inverts HN.\nQed.\n\n(** Errors are not transformed. *)\n\nLemma not_tr_val_error : forall gt v1 v2,\n  tr_val gt v1 v2 ->\n  ~ is_error v2.\nProof using.\n  introv Hv He. unfolds is_error.\n  destruct* v2. inverts* Hv.\nQed.\n\n(** Initialized values are transformed to initialized values. *)\n\nLemma not_is_uninitialized_tr : forall gt v v',\n  tr_val gt v v' ->\n  ~ is_uninitialized v ->\n  ~ is_uninitialized v'.\nProof using.\n  introv Htr Hu HN. induction Htr; subst; inverts HN as.\n  { applys* Hu. }\n  { introv (i&Hi&Ha'i).\n    asserts: (index a i).\n    { rewrite index_eq_index_length in *. rewrite~ H. }\n    applys* H1. }\n  { introv (f&Hfin&Hs'f). tests: (f=fg).\n    { rewrite H8 in Hs'f. inverts Hs'f as (f'&Hf'&Hsgf').\n      applys* H5. introv HN. applys~ Hu. constructors.\n      exists f'. splits~. rew_set in *. intuition. }\n    { rewrite H2 in Hfin. rew_set in Hfin. inverts~ Hfin.\n      inverts H. applys* H7. } }\n  { introv (f&Hfin&Hs'f). rewrite <- H1 in Hfin. applys~ H3 f.\n    introv HN. applys~ Hu. constructors. exists* f. }\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Injectivity results *)\n\n(** [tr_accesses] is injective. *)\n\nLemma tr_accesses_inj : forall C gt \u03c0 \u03c01 \u03c02,\n  group_tr_ok gt C ->\n  wf_accesses C \u03c01 ->\n  wf_accesses C \u03c02 ->\n  tr_accesses gt \u03c01 \u03c0 ->\n  tr_accesses gt \u03c02 \u03c0 ->\n    \u03c01 = \u03c02.\nProof using.\n  introv Hok Hva1 Hva2 H\u03c01 H\u03c02. gen C \u03c02. induction H\u03c01; intros.\n  { inverts H\u03c02. auto. }\n  { inverts H\u03c02; inverts Hva1; inverts Hva2.\n    { fequals. applys* IHH\u03c01. }\n    { fequals. } }\n  { subst. inverts H\u03c02; inverts Hva1; inverts Hva2.\n    { fequals. applys* IHH\u03c01. }\n    { simpls. inverts Hok as Hgt. inverts Hgt.\n      inverts_head Logic.or; tryfalse. inverts H4.\n      { inverts_head make_group_tr'. fequals. }\n      { inverts_head wf_accesses. inverts_head wf_typ. \n        false*. } } }\n  { inverts H\u03c02 as; inverts Hva1 as; inverts Hva2 as.\n    { introv HTt0 H\u03c00 HT H\u03c0 Htr\u03c0 Hin Heq. inverts Heq.\n      subst. simpls.\n      inverts_head Logic.or; tryfalse.\n      inverts HT as HT. inverts H\u03c01 as.\n      { introv Htr\u03c0' Hgt Hin' Heq.\n        inverts Hgt. inverts Heq. fequals. }\n      { introv Htr\u03c0' Hneq. simpls. inverts_head Logic.or.\n        { inverts H\u03c0 as HTg. inverts HTg. inverts Hok.\n          inverts_head make_group_tr'. false*. }\n        { false*. } } }\n    { intros. fequals. applys* IHH\u03c01. } }\nQed.\n\n(** [tr_val] is injective. *)\n\nLemma tr_val_inj : forall C gt v v1 v2,\n  group_tr_ok gt C ->\n  wf_val C v1 ->\n  wf_val C v2 ->\n  tr_val gt v1 v ->\n  tr_val gt v2 v ->\n  v1 = v2.\nProof using.\n  introv Hok HV1 HV2 Hv1 Hv2. gen C v2. induction Hv1; intros;\n  try solve [ inverts Hv2; repeat fequals*; subst; simpls; tryfalse* ].\n  { inverts Hv2 as H\u03c0. repeat fequals*.\n    inverts HV1 as HR\u03c61. inverts HV2 as HR\u03c62.\n    applys* tr_accesses_inj. }\n  { inverts Hv2 as Hl Htra. fequals. \n    applys* eq_of_extens. \n    { congruence. }\n    { inverts HV1. inverts HV2. introv Hi. \n      asserts: (index a0 i).\n      { rewrite index_eq_index_length in *. rewrite Hl. rewrite~ <- H. }\n      applys* H1. } }\n  { subst. inverts Hv2 as.\n    { introv HDsg0 Hgt Hfg0in HDs' Hsg0f Hs'f Hs'fg0.\n      inverts Hgt as HDsg. rewrite <- HDsg in *. \n      fequals. asserts HD: (dom s = dom s0). \n      { rewrite HDs' in *.\n        applys~ incl_eq (dom s) (dom s0) (dom sg).\n        rew_set in *. intros x. forwards Hiff: H2 x.\n        rew_set in *. inverts Hiff as HD1 HD2.\n        intuition; subst; tryfalse*. }\n      applys* read_extens.\n      { introv Hi. inverts HV1 as HV1 HV1sf. inverts HV2 as HV2 HV2sf.\n        forwards HV1sf': HV1sf Hi. rewrite HD in Hi. forwards HV2sf': HV2sf Hi.\n        rewrite Hs'fg0 in H8. inverts H8. tests: (i \\indom sg).\n        { applys* H5. }\n        { applys* H7. rewrite~ HD. } } }\n    { introv HN. simpls. false. } }\n  { inverts Hv2 as.\n    { intros. subst. simpls. false. }\n    { introv Hneq HDs0 Hs'f. fequals. asserts HD: (dom s = dom s0).\n      { congruence. }\n      applys~ read_extens.\n      { introv Hi. inverts HV1 as HV1 HV1sf. inverts HV2 as HV2 HV2sf.\n        rewrite <- HD in HV2sf. applys* H3. applys Hs'f.\n        rewrite~ <- HD. } } }\nQed.\n\n(** Contrapositive of the previous statement. *)\n\nLemma tr_val_inj_cp : forall C gt v1 v2 v1' v2',\n  group_tr_ok gt C ->\n  wf_val C v1 ->\n  wf_val C v2 ->\n  tr_val gt v1 v1' ->\n  tr_val gt v2 v2' ->\n  v1 <> v2 ->\n  v1' <> v2'.\nProof using.\n  introv Hok HTv1 HTv2 Hv1 Hv2 Hneq HN. subst. \n  forwards*: tr_val_inj Hok HTv1 HTv2 Hv1.\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Typing results. *)\n\n(** The transformation preserves well-founded types. *)\n\nLemma tr_typdefctx_wf_typ : forall gt C C' T,\n  group_tr_ok gt C ->\n  tr_typdefctx gt C C' ->\n  wf_typ C T ->\n  wf_typ C' T.\nProof using.\n  introv Hok HC HT. induction HT; try solve [ constructors* ].\n  inverts Hok as HTt HCTt HTg Hfs Hfg Hfv. \n  inverts HC as Hgt HDC' HCTt0 HC'Tt0 HC'Tg0 HC'T Htrsm.\n  inverts Htrsm as Hgt' HDTfs' HTfs'fg0 HTfs'f HTfs''f.\n  inverts Hgt. inverts Hgt'. constructors.\n  { rewrite HDC'. rew_set~. }\n  { tests: (Tv=Tt1).\n    { rewrite HC'Tt0. constructors. introv Hfin.\n      rewrite HCTt0 in HCTt. inverts HCTt.\n      rewrite HCTt0 in IHHT. inverts IHHT as HTfsf.\n      tests: (f=fg1).\n      { rewrite HTfs'fg0. constructors.\n        { rewrite HDC'. rew_set~. }\n        rewrite HC'Tg0. constructors~. introv Hfin'.\n        rewrite~ HTfs''f. applys~ HTfsf. rew_set in Hfs.\n        applys~ Hfs. }\n      { tests: (f \\indom Tfs'').\n        { rewrite HDTfs' in Hfin. rew_set in Hfin.\n          inverts Hfin as Hfin; tryfalse. destruct Hfin.\n          false*. }\n        { asserts Hfin': (f \\indom Tfs).\n          { rewrite HDTfs' in Hfin.\n            rew_set in Hfin. inverts Hfin as Hfin; tryfalse.\n            destruct~ Hfin. }\n          rewrite~ HTfs'f. } } }\n    { rewrite~ HC'T. } }\nQed.\n\n(** The type of the arrays doesn't change. *)\n\nLemma tr_typing_array : forall gt C C' Ta T os,\n  group_tr_ok gt C ->\n  tr_typdefctx gt C C' ->\n  typing_array C Ta T os ->\n  typing_array C' Ta T os.\nProof using.\n  introv Hok HC HTa. gen gt C'. induction HTa; intros;\n  try solve [ inverts~ HTa ].\n  { constructors~. applys* tr_typdefctx_wf_typ. }\n  { inverts HC as HD HCTt HC'Tt HC'Tg HC'T Htrsm.\n    tests: (Tv=Tt).\n    { inverts HTa as.\n      { introv Hwf HTa. rewrite HCTt in HTa. inverts HTa. }\n      { introv HDC HTa HTv. rewrite HCTt in HTv. inverts HTv. } }\n    { constructors~.\n      { rewrite HD. rew_set~. }\n      { rewrite~ HC'T. applys* IHHTa. constructors*. } } }\nQed.\n\n(** The type of the the other structs doesn't change. *)\n\nLemma tr_typing_struct : forall Tt fg Tg fs C C' Ts Tfs,\n  tr_typdefctx (make_group_tr Tt fs Tg fg) C C' ->\n  wf_typdefctx C ->\n  ~ free_typvar C Tt Ts ->\n  typing_struct C Ts Tfs ->\n  typing_struct C' Ts Tfs.\nProof using.\n  introv HC Hwf Hfv HTs. gen Tt fg Tg fs. induction HTs; intros.\n  { constructors~. }\n  { inverts HC as Hgt HDC' HCTt HC'Tt HC'Tg HC'T Htrsm.\n    inverts Htrsm as Hgt' HDTfs' HTfs'fg HTfs'f HTfs''f.\n    inverts Hgt. inverts Hgt'.\n    simpls. constructors~.\n    { rewrite HDC'. rew_set~. }\n    { tests: (Tv=Tt1).\n      { false. applys Hfv. constructors~. }\n      { rewrite~ HC'T. applys IHHTs.\n        { introv HN. applys Hfv. constructors~. eapply HN. }\n        { repeat constructors*. } } } }\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Specific results for each case *)\n\n(** Lemma for the [let] case. *)\n\nLemma tr_stack_add : forall gt z v S v' S',\n  tr_stack gt S S' ->\n  tr_val gt v v' ->\n  tr_stack gt (Ctx.add z v S) (Ctx.add z v' S').\nProof using.\n  introv HS Hv. constructors~. inverts HS.\n  unfolds Ctx.add. destruct* z.\n  applys~ Forall2_cons. constructors~.\nQed.\n\n(** Lemma for the [new] case. *)\n\nLemma tr_uninitialized_val_aux : forall gt v v' T C C',\n  tr_typdefctx gt C C' ->\n  group_tr_ok gt C ->\n  wf_typdefctx C ->\n  tr_val gt v v' ->\n  uninitialized C T v ->\n  uninitialized C' T v'.\nProof using.\n  introv HC Hok Hwf Hv Hu. gen gt C' v'. induction Hu; intros;\n  try solve [ inverts Hv ; constructors~ ].\n  { (* val array *)\n    inverts Hv as Hl Hai. constructors*.\n    2: { rewrite* <- Hl. }\n    applys* tr_typing_array.\n    introv Hi. asserts: (index a i). \n    { rewrite index_eq_index_length in *. rewrite~ Hl. }\n    applys* H2 i. }\n  { (* val struct *)\n    inverts Hv as; inverts HC as; \n    try solve [ intros ; simpls ; tryfalse ].\n    { (* fields grouped *)\n      introv Hgt HDC' HCTt0 HC'Tt0 HC'Tg0 HC'T Htrsm.\n      introv HDsg Hfg HDs' Htrsgf Htrs'f Hs'fg.\n      inverts Htrsm as Hgt' HDTfs' HTfs'fg0 HTfs'f HDTfs''f.\n      inverts Hgt. inverts Hgt' as HD.\n      constructors; unfolds typdefctx.\n      2:{ rewrite HDTfs'. rewrite HDs'. rewrite HD. \n        inverts H as HTt0 HTs. inverts HTs as.\n        { introv HTfs. asserts Heq: (typ_struct Tfs = typ_struct Tfs0).\n          { rewrite HTfs. rewrite <- HCTt0. auto. }\n          inverts Heq. rewrite~ <- H0. }\n        { introv HTv HTs HN. asserts HN': (typ_var Tv = typ_struct Tfs0).\n          { rewrite HN. rewrite <- HCTt0. auto. }\n          inverts HN'. } }\n      { constructors~.\n        { inverts H as HTt0 HTs. rewrite HDC' at 1. rew_set~. }\n        { rewrite HC'Tt0 at 1. constructors*. } }\n      { introv Hfin. rewrite HDTfs' in Hfin. rew_set in Hfin.\n        inverts Hfin as Hfin.\n        { inverts Hfin as Hfin Hfnin. admit. }\n        { rewrite Hs'fg. rewrite HTfs'fg0. constructors*.\n          { constructors. \n            { rewrite HDC' at 1. rew_set~. }\n            { rewrite HC'Tg0 at 1. constructors*. } }\n          { introv Hfin. inverts H as HTt0 HTs. inverts HTs as.\n            { introv HTfs. rewrite HCTt0 in HTfs at 1. inverts HTfs.\n              rewrite~ HDTfs''f. applys~ H2.\n              { rewrite <- H0 in HDsg. rewrite <- HD in Hfin.\n                rew_set in *. applys~ HDsg. }\n              { exact Hok. }\n              { repeat constructors*. rewrite~ HD.\n                introv Hf0in Hf0nin. rewrite HD in Hf0nin.\n                applys~ HTfs'f. }\n              { applys~ Htrsgf. rewrite~ HD. } }\n            { introv HDTv HTs HTv. rewrite HCTt0 in HTv at 1.\n              inverts HTv. } } } } }\n    { (* other struct *)\n      introv HDC' HCTt HC'Tt HC'Tg HC'T Htrsm Hneq HDvfs Htrs'f.\n      constructors~; unfolds typdefctx.\n      2:{ rewrite H0. rewrite~ <- HDvfs. }\n      { inverts H.\n        { constructors*. }\n        { simpls. applys* tr_typing_struct. \n          { constructors*. }\n          { unfolds wf_typdefctx. introv HN.\n            inverts Hok as Hgt HTt0in HCTt0 HTg0nin Hfs Hfg0in Hfv.\n            inverts Hgt. inverts~ HN. forwards~: Hfv Tv. }\n          { constructors*. } } }\n      { introv Hfin. applys* H2.\n        { constructors*. }\n        { applys~ Htrs'f. rewrite~ <- H0. } } } }\nQed.\n\n(** This will be proved when the relation is translated to a function. *)\n\nLemma total_tr_val_aux : forall gt v,\n  exists v', tr_val gt v v'.\nProof using.\nAdmitted.\n\n(** Lemma for the [new] case usable. *)\n\nLemma tr_uninitialized_val : forall gt v T C C',\n  tr_typdefctx gt C C' ->\n  group_tr_ok gt C ->\n  wf_typdefctx C ->\n  uninitialized C T v ->\n  exists v',\n        tr_val gt v v'\n    /\\  uninitialized C' T v'.\nProof using.\n  introv HC Hok Hwf Hu. forwards* (v'&Hv'): total_tr_val_aux gt v.\n  exists v'. splits~. applys* tr_uninitialized_val_aux.\nQed.\n\n(** Lemma for the [get] case. *)\n\nLemma tr_read_accesses : forall gt v \u03c0 v' \u03c0' w,\n  tr_val gt v v' ->\n  tr_accesses gt \u03c0 \u03c0' ->\n  read_accesses v \u03c0 w ->\n  (exists w',\n      tr_val gt w w'\n  /\\  read_accesses v' \u03c0' w').\nProof using.\n  introv Hv Ha HR. gen gt v' \u03c0'. induction HR; intros.\n  { (* nil *)\n    inverts Ha. exists~ v'. }\n  { (* array_access *)\n    inverts Ha as Ha.\n    { inverts Hv as Hl Htr.\n      forwards Htra: Htr H.\n      forwards (w'&Hw'&H\u03c0'): IHHR Htra Ha.\n      exists* w'. splits*. constructors~.\n      rewrite index_eq_index_length. rewrite~ <- Hl. }\n    { false*. } }\n  { (* struct_access *)\n    inverts Ha as; inverts Hv as;\n    try solve [ intros ; false* ].\n    { (* one of the fields to group *)\n      introv HD1 Hgt HD2 HD3 Hsg Hfs Hsfg H\u03c0 Hin Heq.\n      inverts Heq. inverts Hgt. simpls.\n      forwards Hsf: Hsg Hin.\n      forwards (w'&Hw'&HR'): IHHR Hsf H\u03c0.\n      exists w'. splits~.\n      constructors. \n      { rewrite HD3. rew_set~. } \n      rewrite Hsfg. constructors~. }\n    { (* absurd case *)\n      introv Hneq HDs Htrsf Htr\u03c0 Hf0in Heq. simpls.\n      inverts Heq. false. }\n    { (* struct transformed but another field *)\n      introv HD1 HD2 HD3 Hsg Hfs Hsfg H\u03c0 Hor.\n      inverts Hor as Hf; simpl in Hf; tryfalse.\n      forwards Hsf: Hfs Hf H.\n      forwards (w'&Hw'&HR'): IHHR Hsf H\u03c0.\n      exists w'. splits~. constructors~.\n      rewrite HD3. rew_set~. }\n    { (* another struct *)\n      intros Hn HD Hfs H\u03c0 Hor.\n      forwards Hsf: Hfs H.\n      forwards (w'&Hw'&HR'): IHHR Hsf H\u03c0.\n      exists w'. splits~. constructors~.\n      rewrite~ <- HD. } }\nQed.\n\n(** Lemma for the [set] case. *)\n\nLemma tr_write_accesses : forall v1 w gt \u03c0 v1' \u03c0' w' v2,\n  tr_val gt v1 v1' ->\n  tr_val gt w w' ->\n  tr_accesses gt \u03c0 \u03c0' ->\n  write_accesses v1 \u03c0 w v2 ->\n  (exists v2',\n        tr_val gt v2 v2'\n    /\\  write_accesses v1' \u03c0' w' v2').\nProof using.\n  introv Hv1 Hw H\u03c0 HW. gen gt v1' w' \u03c0'. induction HW; intros.\n  { (* nil *)\n    inverts H\u03c0. exists~ w'. }\n  { (* array_access *)\n    inverts H\u03c0 as H\u03c0; tryfalse. inverts Hv1 as Hl Htr.\n    forwards Htra: Htr H.\n    forwards (v2'&Hv2'&HW'): IHHW Htra Hw H\u03c0.\n    exists (val_array T a'[i:=v2']).\n    asserts: (index a' i).\n    { rewrite index_eq_index_length in *. rewrite~ <- Hl. }\n    splits; constructors*; try rewrite H0.\n    { repeat rewrite~ length_update. }\n    { introv Hi0. rew_reads; rew_index* in *.\n      rewrite index_eq_index_length in *. rewrite~ <- Hl. } }\n  { (* struct_access *)\n    inverts H\u03c0 as; inverts Hv1 as;\n    try solve [ intros ; false ].\n    { (* one of the fields to group *)\n      introv HD1 Hgt HD2 HD3 Hsg Hfs Hsfg H\u03c0 Hin Heq.\n      inverts Heq. inverts Hgt. simpls.\n      forwards Hsf: Hsg Hin.\n      forwards (v2'&Hv2'&HW'): IHHW Hsf Hw H\u03c0.\n      exists (val_struct (typ_var Tt) s'[fg0:=(val_struct (typ_var Tg0) sg[f0:=v2'])]).\n      substs. splits.\n      { applys~ tr_val_struct_group (sg[f0:=v2']);\n        repeat rewrite dom_update_at_indom in *; eauto.\n        { rewrite HD3. rew_set~. }\n        { intros. rew_reads*. }\n        { intros. rew_reads; intros; subst; eauto; contradiction. }\n        { rew_reads~. } }\n      { constructors~. rewrite HD3. rew_set~.\n        rewrite Hsfg. constructors*. } }\n    { (* absurd case *)\n      introv HN HDs1 Hs1f1 Htr\u03c0 Hf0in Heq. simpls.\n      inverts Heq. false. }\n    { (* struct transformed but another field *)\n      introv HD1 HD2 HD3 Hsg Hfs Hsfg H\u03c0 Hor.\n      inverts Hor as Hf; simpl in Hf; tryfalse.\n      forwards Hsf: Hfs Hf H.\n      forwards (v2'&Hv2'&HW'): IHHW Hsf Hw H\u03c0.\n      exists (val_struct (typ_var Tt) s'[f:=v2']). splits.\n      { applys~ tr_val_struct_group; subst;\n        repeat rewrite dom_update_at_indom in *; eauto.\n        { rewrite HD3. rew_set~. }\n        { intros. rew_reads; intros; eauto. \n          subst. forwards*: in_notin_neq. }\n        { intros. rew_reads*. }\n        { rew_reads~. intros. \n          subst. forwards*: in_notin_neq. } }\n      { constructors~. rewrite HD3. rew_set~. auto. } }\n    { (* another struct *)\n      intros Hn HD Hfs H\u03c0 Hor.\n      forwards Hsf: Hfs H.\n      forwards (v2'&Hv2'&HW'): IHHW Hsf Hw H\u03c0.\n      exists (val_struct T s'[f:=v2']). splits.\n      { constructors~; subst;\n        repeat rewrite dom_update_at_indom; eauto.\n        { rewrite~ <- HD. }\n        { intros. rew_reads~. } }\n      { constructors~. rewrite* <- HD. auto. } } }\nQed.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Hints *)\n\nHint Constructors wf_trm wf_prim wf_val.\n\n(** Well-formed values from reduction. *)\n\nLemma wf_red_val : forall LLC S m1 t C m2 v,\n  red C LLC S m1 t m2 v ->\n  wf_stack C S ->\n  wf_state C m1 ->\n  wf_trm C t ->\n  wf_val C v.\nProof using.\n  introv HR HwfS Hwfm1 Hwft.\n  forwards* (_&Hwfv): wf_red HR HwfS Hwfm1 Hwft.\nQed.\n\nHint Extern 1 (wf_val ?v) =>\n  match goal\n  with H: red _ _ _ _ v\n       |- _ => applys wf_red_val H\n  end.\n\n(** Well-formed states from reduction. *)\n\nLemma wf_red_state : forall LLC S m1 t C m2 v,\n  red C LLC S m1 t m2 v ->\n  wf_stack C S ->\n  wf_state C m1 ->\n  wf_trm C t ->\n  wf_state C m2.\nProof using.\n  introv HR HwfS Hwfm1 Hwft.\n  forwards* (Hwfm2&_): wf_red HR HwfS Hwfm1 Hwft.\nQed.\n\nHint Extern 1 (wf_state ?m2) =>\n  match goal\n  with H: red _ _ _ m2 _\n       |- _ => applys wf_red_state H\n  end.\n\n(** Absurd error transformations. *)\n\nHint Extern 1 False =>\n  match goal\n  with H: tr_val _ _ val_error\n       |- _ => forwards: not_tr_val_error H\n  end.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Correctness of the transformation *)\n\nTheorem red_tr_ind: forall gt LLC C C' t t' v S S' m1 m1' m2,\n  red C LLC S m1 t m2 v ->\n  group_tr_ok gt C ->\n  tr_typdefctx gt C C' ->\n  tr_trm gt t t' ->\n  tr_stack gt S S' ->\n  tr_state gt m1 m1' ->\n  wf_typdefctx C ->\n  wf_trm C t ->\n  wf_stack C S ->\n  wf_state C m1 ->\n  ~ is_error v ->\n  exists v' m2',\n      tr_val gt v v'\n  /\\  tr_state gt m2 m2'\n  /\\  red C' LLC S' m1' t' m2' v'.\nProof using.\n  introv HR Hok HC Ht HS Hm1 HwfC Hwft HwfS Hwfm1.\n  introv He. gen gt C' t' S' m1'.\n  induction HR; intros; \n  try solve [ forwards*: He; unfolds* ];\n  try solve [ inverts Ht; tryfalse ].\n  { (* val *)\n    inverts Ht as Hv. exists* v' m1'. }\n  { (* var *)\n    inverts Ht. forwards* (v'&H'&Hv'): stack_lookup_tr HS H. exists* v' m1'. }\n  { (* if *)\n    inverts Ht as Hb HTrue HFalse. \n    inverts Hwft as Hwft0 Hwft1 Hwft2.\n    forwards* (v'&m2'&Hv'&Hm2'&HR3): IHHR1 Hb HS Hm1.\n    inverts* Hv'. destruct b;\n    forwards* (vr'&m3'&Hvr'&Hm3'&HR4): IHHR2 HS Hm2';\n    forwards*: wf_red HR1; exists* vr' m3'. }\n  { (* let *)\n    inverts Ht as Ht1 Ht2. \n    inverts Hwft as Hwft0 Hwft1.\n    forwards* (v'&m2'&Hv'&Hm2'&HR3): IHHR1 Ht1 HS Hm1.\n    forwards HS': tr_stack_add z HS Hv'.\n    forwards: not_tr_val_error Hv'.\n    forwards* (vr'&m3'&Hvr'&Hm3'&HR4): IHHR2 Ht2 HS' Hm2'.\n    { applys~ wf_stack_add. applys* wf_red HR1. }\n    { applys* wf_red HR1. }\n    exists* vr' m3'. }\n  { (* binop *)\n    inverts Ht as Ht1 Ht2.\n    inverts Ht1 as Ht1. inverts Ht2 as Ht2.\n    inverts H3;\n    try solve [ exists __ m1' ; splits~ ; inverts Ht1 ;\n    inverts Ht2 ; repeat constructors~ ].\n    { exists __ m1'. splits~.\n      forwards: functional_tr_val Ht1 Ht2. subst.\n      constructors;\n      repeat applys* is_basic_tr;\n      repeat applys* not_tr_val_error.\n      constructors~. }\n    { exists __ m1'. splits~. constructors;\n      repeat applys* is_basic_tr;\n      repeat applys* not_tr_val_error.\n      inverts Hwft as Hwfp Hwft1 Hwft2.\n      inverts Hwft1 as Hwft1. \n      inverts Hwft2 as Hwft2.\n      forwards*: tr_val_inj_cp v1 v2.\n      constructors~. } }\n  { (* get *)\n    inverts Ht as.\n    { introv HN. inverts HN. }\n    introv Hp. subst.\n    inverts Hm1 as HD Htrm.\n    inverts H0 as Hi Ha.\n    forwards Htrml: Htrm Hi.\n    inverts Hp as Hp. inverts Hp as H\u03c0.\n    forwards (w'&Hw'&Ha'): tr_read_accesses Htrml H\u03c0 Ha.\n    exists w' m1'. splits*.\n    repeat constructors~. rewrite~ <- HD.\n    applys* not_is_uninitialized_tr. }\n  { (* set *)\n    inverts Ht as Hp Ht. subst.\n    inverts Hm1 as HD Htrm.\n    inverts H2 as Hin HW. \n    forwards Htrml: Htrm Hin.\n    inverts Hp as Hp. \n    inverts Hp as H\u03c0.\n    inverts Ht as Hv.\n    forwards (w'&Hw'&HW'): tr_write_accesses Htrml Hv H\u03c0 HW.\n    exists val_unit m1'[l:=w']. splits~.\n    { constructors.\n      { unfold state. repeat rewrite~ dom_update.\n        fold state. rewrite~ HD. }\n      { introv Hi'. rew_reads~. intros. applys Htrm.\n        applys~ indom_update_inv_neq Hi'. } }\n    { constructors~. applys* not_tr_val_error.\n      constructors*. rewrite~ <- HD. } }\n  { (* new *)\n    inverts Ht. subst.\n    inverts Hm1 as HD Htrm. \n    forwards* (v'&Hv'&Hu): tr_uninitialized_val.\n    exists (val_abstract_ptr l nil) m1'[l:=v']. splits~.\n    { constructors.\n      { unfold state. repeat rewrite~ dom_update.\n        fold state. rewrite~ HD. }\n      { introv Hin. unfolds state. rew_reads; intros; eauto. } }\n    { constructors*. rewrite~ <- HD. applys* tr_typdefctx_wf_typ. } }\n  { (* new_array *)\n    inverts Ht as.\n    { introv HN. inverts HN. }\n    introv Ht.\n    inverts Ht as Hv.\n    inverts Hm1 as HD Htrm. subst.\n    forwards* (v''&Hv''&Hu): tr_uninitialized_val.\n    inverts Hv''.\n    exists (val_abstract_ptr l nil) m1'[l:=(val_array (typ_array T None) a')]. splits~.\n    { constructors.\n      { unfold state. repeat rewrite~ dom_update.\n        fold state. rewrite~ HD. }\n      { introv Hin. unfolds state. rew_reads; intros; eauto. } }\n    { inverts Hv. applys~ red_new_array. rewrite~ <- HD. \n      applys* tr_typdefctx_wf_typ. auto. } }\n  { (* struct_access *)\n    inverts Ht as; inverts Hm1 as HD Htrm.\n    { (* struct op *)\n      introv _ Ht Hop. subst.\n      inverts Ht as Hv. inverts Hv as Ha. inverts Hop as; \n      try solve [ intros; inverts_head prim_struct_access ].\n      { (* grouped field*)\n        introv Hf0in Hpr.\n        remember (access_field (typ_var Tt) fg) as a1.\n        remember (access_field (typ_var Tg) f) as a2.\n        exists (val_abstract_ptr l (\u03c0'++(a1::a2::nil))) m1'.\n        inverts Hpr. splits*.\n        { constructors. applys* tr_accesses_app. }\n        { subst. applys* red_args_1. applys* red_struct_access.\n          fequals*. rew_list*. } }\n      { (* other field *)\n        introv Hpr Hneq. inverts Hpr.\n        exists (val_abstract_ptr l (\u03c0'++(access_field T0 f0 :: nil))) m1'.\n        splits; constructors*. applys* tr_accesses_app. } } }\n  { (* array_access *)\n    inverts Ht as Ht Hti. subst.\n    inverts Ht as Hv. inverts Hv as Ha.\n    inverts Hti as Hv. inverts Hv.\n    inverts Hm1 as HD Htrm.\n    exists (val_abstract_ptr l (\u03c0'++(access_array T i::nil))) m1'.\n    splits; constructors*. applys* tr_accesses_app. }\n  { (* struct_get *)\n    inverts Ht as.\n    { (* struct op *)\n      introv _ Ht Hop. inverts Hop as;\n      try solve [ intros; inverts_head prim_struct_get ].\n      { (* accessing grouped field *)\n        introv Hf0in Hpr. inverts Hpr.\n        inverts Ht as Hv. subst. inverts Hv as;\n        try solve [ intros ; contradiction ].\n        introv HDsg Hgt Hfg HDs' Hsf Htrsf Hs'fg.\n        inverts Hgt. exists sg[f0] m1'. splits~.\n        { applys~ red_args_1.\n          { applys~ red_struct_get. rewrite HDs'. rew_set~. }\n          { applys~ red_struct_get. rewrite~ Hs'fg. } } }\n      { (* accessing another field *) \n        introv Hpr Hneqor. subst. inverts Ht as Hv.\n        inverts Hpr. inverts Hneqor.\n        { inverts Hv as;\n          try solve [ intros; inverts_head make_group_tr'; contradiction ].\n          introv _ HDs Htrsf. exists s'[f0] m1'. splits~. constructors~.\n          rewrite~ <- HDs. }\n        { inverts Hv as.\n          { introv HDsg Hgt Hfg HDs' Hsf Htrsf Hs'fg.\n            inverts Hgt. exists s'[f0] m1'. splits~.\n            constructors~. rewrite HDs'. rew_set~. }\n          { introv Hneq HDs Htrsf. exists s'[f0] m1'. splits~.\n            constructors~. rewrite~ <- HDs. } } } } }\n  { (* array_get *)\n    inverts Ht as Ht Hti. subst.\n    inverts Ht as Hv.\n    inverts Hti as Hvi.\n    inverts Hv as Hl Hai.\n    inverts Hvi.\n    exists a'[i] m1'.\n    splits~. constructors*.\n    rewrite index_eq_index_length in *.\n    rewrite~ <- Hl. }\n  { (* args_1 *)\n    inverts Ht; inverts Hwft;\n    forwards* (v'&m2'&Hv'&Hm2'&HR'): IHHR1;\n    forwards*: not_is_error_args_1 HR2 He.\n    { inverts_head tr_struct_op.\n      { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n        try solve [ repeat constructors~ ; applys* wf_red HR1 ].\n        { applys* tr_trm_struct_op. applys* tr_struct_op_group_access. }\n        exists v'' m3'; splits*. inverts~ HR''; tryfalse*.\n        repeat applys* red_args_1. applys* not_is_val_tr. }\n      { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n        try solve [ repeat constructors~ ; applys* wf_red HR1 ].\n        { applys* tr_trm_struct_op. applys* tr_struct_op_group_get. }\n        exists v'' m3'; splits*. inverts~ HR''; tryfalse*.\n        repeat applys* red_args_1. applys* not_is_val_tr. }\n      { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n        try solve [ repeat constructors~ ; applys* wf_red HR1 ].\n        { applys* tr_trm_struct_op. applys* tr_struct_op_other_access. }\n        exists v'' m3'; splits*. inverts~ HR''; tryfalse*.\n        repeat applys* red_args_1. applys* not_is_val_tr. }\n      { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n        try solve [ repeat constructors~ ; applys* wf_red HR1 ].\n        { applys* tr_trm_struct_op. applys* tr_struct_op_other_get. }\n        exists v'' m3'; splits*. inverts~ HR''; tryfalse*.\n        repeat applys* red_args_1. applys* not_is_val_tr. } }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. }\n    { forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n      try solve [ repeat constructors~ ; applys* wf_red HR1 ];\n      try solve [ exists v'' m3'; splits* ;\n      applys* red_args_1; applys* not_is_val_tr ]. } }\n  { (* args_2 *)\n    inverts Ht as Ht1 Ht2; inverts Hwft;\n    forwards* (v'&m2'&Hv'&Hm2'&HR'): IHHR1;\n    try forwards*: not_is_error_args_2 HR2 He;\n    forwards* (v''&m3'&Hv''&Hm3'&HR''): IHHR2;\n    try solve [ applys* wf_red HR1 ];\n    try solve [ do 2 constructors* ; applys* wf_red HR1 ];\n    exists v'' m3'; splits*;\n    inverts Ht1; applys* red_args_2;\n    applys* not_is_val_tr. }\nQed.\n\n(** From full execution. *)\n\nTheorem red_tr: forall gt LLC C C' t t' v m2,\n  red C LLC empty_stack empty_state t m2 v ->\n  group_tr_ok gt C ->\n  tr_typdefctx gt C C' ->\n  tr_trm gt t t' ->\n  wf_typdefctx C ->\n  wf_trm C t ->\n  ~ is_error v ->\n  exists v' m2',\n      tr_val gt v v'\n  /\\  tr_state gt m2 m2'\n  /\\  red C' LLC empty_stack empty_state t' m2' v'.\nProof using.\n  introv HR Hok HC Ht HwfC Hwft Hne.\n  asserts HS: (tr_stack gt empty_stack empty_stack).\n  { constructors. applys~ Forall2_nil. }\n  asserts Hm1: (tr_state gt empty_state empty_state).\n  { constructors~. introv Hl. false. applys* indom_empty_inv. }\n  asserts HwfS: (wf_stack C empty_stack).\n  { unfolds~. introv HN. false. }\n  asserts Hwfm1: (wf_state C empty_state).\n  { unfolds~. introv HN. false. applys* indom_empty_inv. }\n  forwards*: red_tr_ind HR Hok HC Ht HS.\nQed.\n\nEnd TransformationsProofs.\n", "meta": {"author": "ramonfmir", "repo": "verified_transfo", "sha": "2afbe24651f5af8e4fa545ff1afb454be3ce7f9e", "save_path": "github-repos/coq/ramonfmir-verified_transfo", "path": "github-repos/coq/ramonfmir-verified_transfo/verified_transfo-2afbe24651f5af8e4fa545ff1afb454be3ce7f9e/src/TrGroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3140505321516081, "lm_q1q2_score": 0.1619307089207804}}
{"text": "Require Import include_frm.\nRequire Import oscorrectness.\nRequire Import simulation.\nRequire Import auxdef.\nRequire Import Classical.\nRequire Import sep_auto.\nRequire Import base_tac.\nRequire Import soundness.\nRequire Import absinfer_sound.\nRequire Import memory_prop.\nRequire Import joinmemLib.\nRequire Import lmachLib.\nRequire Import invariant_prop.\nRequire Import join_prop.\nRequire Import rulesoundlib.\nRequire Import step_prop.\n(*\nRequire Import progtaskstepLib.*)\n\nImport DeprecatedTactic.\n\nLtac unfoldbug:= try (unfold code in *;unfold tid in *;unfold cont in *).\nLtac unfolddef:=\n  try\n    (unfold code in *;unfold cont in *;unfold tid in *;unfold TMSpecMod.B in *;\n     unfold mmapspec.image in *;\n     unfold TOSpecMod.B in *;\n     unfold omapspec.image in *;unfold Maps.sub in *;unfold disjoint in *;unfold osabst in *).\n     \nInductive lintstep' : hid -> intunit -> code -> taskst -> code -> taskst -> Prop :=\n  li_step : forall (C : code) (c : cureval) (ke : exprcont) \n                   (ks : stmtcont) (ir : isr) (si : is) \n                   (i : hid),\n            forall (s : stmts) (theta : intunit) (ge le : env) (m : mem),\n              C = (c, (ke, ks)) ->\n              higherint ir i ->\n              (i < INUM)%nat ->\n              theta i = Some s ->\n              lintstep' i theta C (ge, le, m, ir, (true, si, nil))\n                        (curs s, (kenil, kint c ke le ks))\n                        (ge, empenv, m, isrupd ir i true, (false, i :: si, nil)).\n\n\n\n\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n\n(*--------*)\n\n\n\n(*\nLemma merge_set_eq:forall O O' x y, merge (set O x y) O' = set (merge O O') x y. \nProof.\n  intros.\n  apply extensionality.\n  intro.\n  rewrite merge_sem.\n  destruct (absdataidspec.beq x a) eqn : eq1.\n  apply absdataidspec.beq_true_eq in eq1.\n  substs.\n  rewrite set_a_get_a.\n  rewrite set_a_get_a.\n  destruct (get O' a); auto.\n  apply absdataidspec.eq_beq_true; auto.\n  apply absdataidspec.eq_beq_true; auto.\n  rewrite set_a_get_a'; auto.\n  rewrite set_a_get_a'; auto.\n  rewrite merge_sem.\n  auto.\nQed.\n\n\nLemma disj_indom_set_disj: forall O O' x y, indom O x -> disj O O' ->\n                                            disj (set O x y) O'.\nProof.\n  intros.\n  unfold disj.\n  intro.\n  unfold disj in H0; pose proof H0 a; clear H0.\n  unfold indom in H; destruct H.\n  destruct (absdataidspec.beq x a) eqn : eq1.\n  apply absdataidspec.beq_true_eq in eq1.\n  substs.\n  rewrite set_a_get_a.\n  rewrite H in H1.\n  auto.\n  apply absdataidspec.eq_beq_true; auto.\n  rewrite set_a_get_a'; auto.\nQed.\n\n(*\nLemma GetHPrio_sub_eq: forall o o1 o2 o3 O O' x y, GetHPrio o x -> GetHPrio o1 y -> join o o3 O -> join o1 o2 (merge O O') -> x=y.\nProof.\n  intros.\n  assert (forall x y, OSAbstMod.get o abtcblsid = Some x -> OSAbstMod.get o1 abtcblsid = Some y -> x = y).\n  intros.\n  clear H H0.\n  unfold join in H1; pose proof H1 abtcblsid; clear H1.\n  unfold join in H2; pose proof H2 abtcblsid; clear H2.\n  rewrite merge_sem in H0.\n  destruct (get o abtcblsid) eqn : eq1;\n  destruct (get o3 abtcblsid) eqn : eq2;\n  destruct (get O abtcblsid) eqn : eq3;\n  destruct (get o2 abtcblsid) eqn : eq4;\n  destruct (get O' abtcblsid) eqn : eq5;\n  destruct (get o1 abtcblsid) eqn : eq6;\n  tryfalse;\n  substs; auto;\n  inv H4; inv H3; auto.\n  unfolds in H; do 4 destruct H.\n  destruct H.\n  unfolds in H0; do 4 destruct H0.\n  destruct H0.\n  pose proof H3 (abstcblist x0) (abstcblist x4) H H0; clear H3.\n  inv H6.\n  clear H1 H2 H H0; clears.\n  destruct H5.\n  destruct H0.\n  destruct H4.\n  destruct H3.\n  destruct ( tidspec.beq x y) eqn : eq1.\n  apply tidspec.beq_true_eq in eq1.\n  auto.\n  apply tidspec.beq_false_neq in eq1.\n  assert (y<>x).\n  intro.\n  symmetry in H5.\n  apply eq1 in H5.\n  false.\n  pose proof H1 x x1 x2 x3 eq1 H2 H3; clear H1.\n  pose proof H4 y x5 x6 x7 H5 H H0; clear H4.\n  unfold Int.ltu in *.\n  destruct (zlt (Int.unsigned x5) (Int.unsigned x1));tryfalse.\n  destruct (zlt (Int.unsigned x1) (Int.unsigned x5));tryfalse.\n  omega.\nQed.*)\n*)\n\n\n\n\n(*\nLemma swi_rdy_inv''':forall (o : taskst) (Ol Os : map) (Ms Mc : MemMod.map) \n         (I : Inv) (t t' : tid) (S : osstate)\n         (o' : env * EnvSpec.B * mem * isr * LocalStSpec.B)  b tp  Mcc sc,\n       good_is_S S ->\n       GoodI I sc->\n       disj Ol Os ->\n       MemMod.disj Mc Ms ->\n       (forall ab : absop, (substaskst o Ms, Os, ab) |= INV I) ->\n       (forall ab : absop, (substaskst o Mc, Ol, ab) |= SWINV I) ->\n       (forall ab : absop, (substaskst o Mc, Ol, ab) |=  AHprio sc t' ** Atrue) ->\n       projS S t = Some o ->\n       projS S t' = Some o' ->\n       EnvMod.get (get_genv (get_smem o)) OSTCBCur = Some (b,(Tptr tp)) ->\n       store (Tptr tp) Mc (b,0%Z) (Vptr t') = Some Mcc -> \n       exists Mc' Ms' Ol' Os',\n       MemMod.disj Mc' Ms' /\\\n       MemMod.merge Mc' Ms' = MemMod.merge Mcc Ms /\\\n       disj Ol' Os' /\\\n       merge Ol' Os' = set (merge Ol Os) curtid (oscurt t') /\\\n       (forall ab : absop, (substaskst o' Ms', Os', ab) |= INV I) /\\\n       (forall ab : absop, (substaskst o' Mc', Ol', ab) |= RDYINV I).\nProof.\n  intros.\n  assert (forall ab : absop, (substaskst o Mcc,set Ol curtid (oscurt t'), ab) |= SWINV I).\n  unfold GoodI in *.\n  destructs H0.\n  intros.\n  assert (substaskst o Mcc= substaskst (substaskst o Mc) Mcc).\n  destruct o as [[[[]]]];simpl;auto.\n  rewrite H13.\n  eapply H11;eauto.\n  destruct o as [[[[]]]].\n  simpl;eauto.\n  destruct o as [[[[]]]];simpl;eauto.\n  rewrite <- merge_set_eq.\n  eapply swi_rdy_inv';eauto.\n  apply GoodI_SWINV_indom_curt with (sc:=sc) in H4;auto.\n  eapply disj_indom_set_disj;auto.\n  eapply disj_store_disj;eauto.\nQed.\n\n\nLemma p_eq: forall (pc po pi pc0 po0 pi0:progunit)  (ip ip0:intunit), (pc, (po, pi, ip)) = (pc0, (po0, pi0, ip0)) -> pc = pc0/\\ po=po0/\\pi=pi0/\\ip=ip0.\nProof.\n  intros.\n  inversion H;subst.\n  auto.\nQed.\n\nLemma code_eq_dec: forall (c c':code), c=c'\\/c<>c'.\nProof.\n  intros.\n  eapply classic.\nQed.\n\nLemma stmts_dec: forall (s:stmts) s', s= s' \\/ s<>s'.\nProof.\n  intros.\n  eapply classic.\nQed.\n\n(*\nLemma code_eq_stkinit:\n  forall (C:code),\n    ~(exists e1 e2 e3 ks, C = (curs (sprim (stkinit e1 e2 e3)), (kenil, ks)))\\/\n    (exists e1 e2 e3 ks, C = (curs (sprim (stkinit e1 e2 e3)), (kenil, ks))).\nProof.\n  intros.\n  assert ((exists e1 e2 e3 ks, C = (curs (sprim (stkinit e1 e2 e3)), (kenil, ks))) \\/\n          ~(exists e1 e2 e3 ks, C = (curs (sprim (stkinit e1 e2 e3)), (kenil, ks)))).\n  apply classic.\n  destruct H;auto.\nQed.\n\nLemma code_eq_stkfree:\n  forall (C:code),\n    ~(exists e ks, C = (curs (sprim (stkfree e)), (kenil, ks)))\\/\n    (exists e ks, C = (curs (sprim (stkfree e)), (kenil, ks))).\nProof.\n  intros.\n  assert ( (exists e ks, C = (curs (sprim (stkfree e)), (kenil, ks))) \\/\n           ~(exists e ks, C = (curs (sprim (stkfree e)), (kenil, ks)))).\n  apply classic.\n  destruct H;auto.\nQed.*)\n *)\n\nLemma exint_dec: forall c ke ks, ((c,(ke,ks)) = (curs (sprim exint),(kenil,ks))/\\callcont ks=None/\\intcont ks=None)\\/ ~((c,(ke,ks)) = (curs (sprim exint),(kenil,ks))/\\callcont ks=None/\\intcont ks=None).\nProof.\n  intros.\n  apply classic.\nQed.\n\n\n  \n(*--------------------------------------------------*)\n\n\n\nLemma api_tlmatch\n: forall (po pi : progunit) (ip : intunit) (B : osapispec)\n         (C : osintspec) (f : fid) (tp : type) (d1 d2 : decllist) \n         (s : stmts) (D : ossched),\n    eqdomOS (po, pi, ip) (B, C, D) ->\n    po f = Some (tp, d1, d2, s) ->\n    exists ab tl tp0, B f = Some (ab, (tp0, tl)) /\\ tlmatch tl d1.\nProof.\n  intros.\n  unfold eqdomOS in H.\n  destruct H.\n  destruct H1.\n  assert (exists fdef, po f = Some fdef).\n  exists (tp, d1, d2, s).\n  auto.\n  apply H in H3.\n  destruct H3.\n  destruct x.\n  destruct f0.\n  do 3 eexists.\n  split;eauto.\n  eapply H1 with (fspec := (a,(t,t0))) in H0;eauto.\n  destruct H0.\n  simpl in *;auto.\nQed.\n\nLemma init_emple\n: forall lasrt tid (o : taskst) (O : osabst),\n    InitTaskSt lasrt tid (o, O) -> snd (fst (get_smem o)) = emp.\nProof.\n  intros.\n  unfold InitTaskSt in H.\n  destruct H.\n  destruct o as [[[[]]]].\n  simpl in H0.\n  simpl;auto.\nQed.\n\nLemma good_dl_le_init'\n: forall (dl : decllist) (ge : env) (M : mem) (ir : isr) (aux : localst),\n    good_decllist dl = true -> good_dl_le dl (ge, emp, M, ir, aux).\nProof.\n  intros.\n  gen ge M ir aux H.\n  induction dl; intros.\n  simpl.\n  auto.\n  simpl.\n  simpl in H.\n  apply andb_true_iff in H.\n  destruct H.\n  eapply IHdl in H0.\n  split.\n  apply andb_true_iff.\n  split.\n  auto.\n  unfolds in H0.\n  destruct dl.\n  simpl.\n  auto.\n  destruct H0.\n  auto.\n  split.\n  intro.\n  unfold EnvMod.indom in H1.\n  destruct H1.\n  pose proof (EnvMod.emp_sem i).\n  false.\n  eapply H0.\nQed.\n\nLemma InitAemp\n: forall (genv lenv : env) (M : mem) (ir : isr) \n         (aux : localst) (O : osabst) lasrt t,\n    InitTaskSt lasrt t (genv, lenv, M, ir, aux, O) ->\n    forall ab : absop,\n      (genv, lenv, M, ir, aux, O, ab)\n        |= (Aemp ** p_local lasrt t init_lg ** Aie true ** Ais nil ** Acs nil ** Aisr empisr) **\n        A_dom_lenv (getlenvdom dnil).\nProof.\n  intros.\n  unfolds in H.\n  destruct H.\n  simpl in H0.\n  subst.\n  simpl in H.\n  lets Hx:H ab.\n  unfold p_local.\n  sep auto.\n  simpl.\n  unfold empenv.\n  simpl.\n  unfolds.\n  intros.\n  splits;intros.\n  unfolds in H4.\n  tryfalse.\n  mytac.\n  tryfalse.\nQed.\n\n\nLemma emple_subs_inv\n: forall (o o' : taskst) (Ms : mem) (Os : osabst) (I : Inv),\n    TStWoMemEq (emple_tst o') (emple_tst o) ->\n    satp (substaskst o Ms) Os (INV I) ->\n    satp (substaskst o' Ms) Os (INV I).\nProof.\n  intros.\n  unfolds;intros.\n  lets Hx:H0 aop.\n  clear H0;rename Hx into H0.\n  destruct o as [[[[]]]].\n  destruct o' as [[[[]]]].\n  trysimplsall.\n  unfolds in H.\n  simpl in H.\n  mytac.\n  eapply  INV_irrev_prop; eauto.\nQed.\n\n\nLemma join_eqe\n: forall (o : taskst) (M M': mem) (o' : taskst),\n    joinm2 o M M' o' -> get_lenv (get_smem o) = get_lenv (get_smem o').\nProof.\n  intros.\n  destruct o as [[[[]]]].\n  destruct o' as [[[[]]]].\n  unfolds in H.\n  unfold joinmem in H.\n  mytac.\n  simpl;auto.\nQed.\n\nLemma good_dl_le_care\n: forall (o o' : taskst) (dl : decllist),\n    get_lenv (get_smem o) = get_lenv (get_smem o') ->\n    good_dl_le dl o -> good_dl_le dl o'.\nProof.\n  intros.\n  destruct o.\n  destruct p.\n  destruct o'.\n  destruct p.\n  simpl in H.\n  destruct s.\n  destruct p.\n  destruct s0.\n  destruct p.\n  simpl in H.\n  subst.\n  induction dl.\n  simpl.\n  auto.\n  simpl in H0.\n  destruct H0.\n  destruct H0.\n  simpl.\n  split; auto.\nQed.\n\n\nLemma higherint_update_eq:\n  forall (i : hid) (ir : isr), higherint ir i -> ir = isrupd ir i false.\nProof.\n  intros.\n  unfold higherint in H.\n  Import Coq.Logic.FunctionalExtensionality.\n  apply functional_extensionality_dep.\n  intros.\n  assert (x=i \\/ x<>i) by tauto.\n  destruct H0.\n  unfold isrupd.\n\n  symmetry in H0.\n  assert (i=x) by auto.\n  apply beq_nat_true_iff  in H0.\n  rewrite H0.\n  apply H.\n  omega.\n  unfold isrupd.\n  apply beq_nat_false_iff in H0.\n  rewrite NPeano.Nat.eqb_sym.\n  rewrite H0.\n  auto.\nQed.\n\nLemma dl_add_nil_eq\n: forall dl : decllist, dl_add dl dnil = dl.\nProof.\n  induction dl; intros.\n  simpl.\n  auto.\n  simpl.\n  rewrite IHdl.\n  auto.\nQed.\n\nLemma eq_tp\n: forall (po pi : progunit) (ip : intunit) (A : osspec) \n         (f : fid) (ab : api_code) (t : type) (tl : typelist) \n         (ft : type) (d1 d2 : decllist) (s : stmts),\n    eqdomOS (po, pi, ip) A ->\n    fst (fst A) f = Some (ab, (t, tl)) ->\n    po f = Some (ft, d1, d2, s) -> ft = t /\\ tlmatch tl d1.\nProof.\n  intros.\n  unfold eqdomOS in H.\n  destruct A as (B&C).\n  destruct B as (B & A).\n  destruct H as (Ha1&Ha2&Ha3).\n  assert (exists fdef, po f= Some fdef).\n  exists (ft, d1, d2, s).\n  auto.\n  apply Ha1 in H.\n  destruct H as (fspec& H).\n  simpl in H0.\n  rewrite H0 in H.\n  inversion H.\n  subst fspec.\n  clear H.\n  apply Ha2 with (fspec := (ab, (t, tl)))in H1.\n  destruct H1.\n  simpl in H,H1.\n  split;auto.\n  auto.\nQed.\n\n\nLemma tlmatch_trans'': forall t1 t2 d1 , tlmatch t1 d1 -> tlmatch t2 d1 -> t1 =t2.\nProof.\n  induction t1.\n  induction t2.\n  intros.\n  auto.\n  intros.\n  unfold tlmatch in H.\n  destruct d1.\n  unfold tlmatch in H0. \n  inversion H0.\n  inversion H.\n  induction t2.\n  intros.\n  destruct d1.\n  simpl in H.\n  inversion H.\n  simpl in H0.\n  inversion H0.\n  intros.\n  destruct d1.\n  simpl in H.\n  inversion H.\n  simpl in H,H0.\n  destruct H.\n  destruct H0.\n  subst a a0.\n  assert (t1=t2).\n  eapply IHt1 ;eauto.\n  subst t1;auto.\nQed.\n\n\nLemma tlmatch_trans: forall d1 t1 t2, tlmatch t1 d1 -> tlmatch t2 d1 -> t1 =t2.\nProof.\n  intros.\n  eapply tlmatch_trans'';eauto.\nQed.\n\nFixpoint length_eq_td (tl:typelist) (dl:decllist) :=\n  match tl with\n    | nil => match dl with\n               | dnil => True\n               | _ => False\n             end\n    | t::tl' => match dl with \n                  | dcons a b dl' => length_eq_td tl' dl'\n                  | _ => False\n                end\n  end.\n\nLemma tlmatch_lengtheq: forall tl dl, tlmatch tl dl -> length_eq_td tl dl.\nProof.\n  induction tl.\n  intros.\n  simpl in *.\n  destruct dl;tryfalse.\n  auto.\n  induction dl.\n  intros.\n  simpl in H.\n  false.\n  intros.\n  simpl.\n  simpl in H.\n  destruct H.\n  apply IHtl in H.\n  auto.\nQed.\n\nLemma tl_dl_vl_eq\n: forall (tl : list type) (dl : decllist) (vl : list val),\n    tlmatch (rev tl) dl -> length vl = length tl -> length_eq vl dl.\nProof.\n  intros.\n  apply tlmatch_lengtheq in H.\n  assert (length (rev tl) = length tl).\n  apply List.rev_length.\n  rewrite <- H1 in H0.\n  remember (rev tl) as tln.\n  clear H1.\n  clear Heqtln tl.\n  generalize vl dl tln H H0.\n  clear.\n  induction vl.\n  intros.\n  simpl in H0.\n  destruct tln;simpl in H0;tryfalse.\n  destruct dl;simpl in *;tryfalse.\n  auto.\n  induction dl.\n  intros.\n  destruct tln;simpl in *;tryfalse.\n  intros.\n  simpl.\n  destruct tln.\n  simpl in H0;tryfalse.\n  simpl in H, H0.\n  inversion H0.\n  eapply IHvl;eauto.\nQed.\n\n\nLemma app_cons_length_lt : forall {A : Type} vl vl' vl'' (v : A),\n                             vl ++ v :: vl' = vl'' ->\n                             (length vl < length vl'')%nat.\nProof.\n  intros.\n  substs.\n  gen vl' v.\n  inductions vl; intros.\n  simpl.\n  omega.\n  simpl.\n  apply lt_n_S.\n  apply IHvl.\nQed.\n\n\nLemma length_dl_revlcons_add : forall dl1 dl2 dl,\n                                 dl = revlcons dl1 dl2 ->\n                                 length_dl dl = (length_dl dl1 + length_dl dl2)%nat.\nProof.\n  intro.\n  induction dl1; intros.\n  simpl in H.\n  substs.\n  simpl.\n  auto.\n  simpl in H.\n  pose proof IHdl1 (dcons i t dl2) dl H; clear IHdl1.\n  simpl in H0.\n  simpl.\n  omega.\nQed.\n\nLemma length_length_dl_eq : forall vl dl,\n                              length_eq vl dl -> length vl = length_dl dl.\nProof.\n  intro.\n  induction vl; intros.\n  simpl.\n  destruct dl; simpl in H.\n  simpl; auto.\n  false.\n  simpl in H.\n  destruct dl; tryfalse.\n  simpl.\n  apply eq_S.\n  apply IHvl.\n  auto.\nQed.\n\nLemma dl_add_dnil_eq : forall dl,\n                         dl_add dl dnil = dl.\nProof.\n  induction dl; intros.\n  simpl.\n  auto.\n  simpl.\n  rewrite IHdl.\n  auto.\nQed.\n\nLemma sub_len_neq\n: forall (vl' : list val) (vlh : vallist) (d1 : decllist) \n         (v : val) (vl : list val) (dl' d2 : decllist),\n    length_eq vlh d1 ->\n    vl' ++ v :: vl = vlh ->\n    dl_add dl' dnil = revlcons d1 d2 -> ~ length_eq vl' dl'.\nProof.\n  intros.\n  apply app_cons_length_lt in H0.\n  apply length_dl_revlcons_add in H1.\n  apply length_length_dl_eq in H.\n  intro.\n  apply length_length_dl_eq in H2.\n  rewrite H in H0.\n  rewrite H2 in H0.\n  rewrite dl_add_dnil_eq in H1.\n  rewrite H1 in H0.\n  omega.\nQed.\n\n\nLemma ret_dec:forall c ke ks,~ ((c, (ke, ks)) = (curs sret, (kenil, ks)) /\\ callcont ks = None/\\intcont ks=None)\\/((c, (ke, ks)) = (curs sret, (kenil, ks)) /\\ callcont ks = None/\\intcont ks=None).\nProof.\n  intros.\n  assert ( \n      ((c, (ke, ks)) = (curs sret, (kenil, ks)) /\\\n       callcont ks = None /\\ intcont ks = None) \\/\n      ~( (c, (ke, ks)) = (curs sret, (kenil, ks)) /\\\n         callcont ks = None /\\ intcont ks = None)).\n  eapply classic.\n  destruct H;auto.\nQed.\n\nLemma retv_dec: forall c ke ks, ~(exists v ksx, (c,(ke,ks))= (curs (sskip (Some v)),(kenil,kret ksx))/\\callcont ksx = None/\\intcont ksx=None) \\/  (exists v ksx, (c,(ke,ks))= (curs (sskip (Some v)),(kenil,kret ksx))/\\callcont ksx = None/\\intcont ksx=None).\nProof.\n  intros.\n  assert ((exists v ksx, (c,(ke,ks))= (curs (sskip (Some v)),(kenil,kret ksx))/\\callcont ksx = None/\\intcont ksx=None) \\/  ~(exists v ksx, (c,(ke,ks))= (curs (sskip (Some v)),(kenil,kret ksx))/\\callcont ksx = None/\\intcont ksx=None)).\n  eapply classic.\n  destruct H;auto.\nQed.\n\n\nLemma join_tst_wo_mem_eq\n: forall (o o' : taskst) (M M': mem), joinm2 o M M' o' -> TStWoMemEq o o'.\nProof.\n  intros.\n  unfolds in H.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  unfolds.\n  splits;auto.\nQed.\n\n\nLemma fun_goodks\n: forall (pc po pi : progunit) (ip : intunit) \n         (ks1 : stmtcont) (f : fid) (s : stmts) (ks : stmtcont),\n    goodks (pc, (po, pi, ip)) (ks1 ## kcall f s empenv ks) ->\n    goodks (pc, (po, pi, ip)) ks.\nProof.\n  induction ks1;simpl;auto;intros.\n  destruct (pumerge po pi f);auto.\n  induction ks;auto.\n  simpl.\n  unfold no_os in H.\n  destruct (pumerge po pi f0).\n  inversion H.\n  auto.\n  unfold no_os in H.\n  unfold goodks.\n  tryfalse.\n  destruct (pumerge po pi f).\n  eapply IHks1;eauto.\n  apply IHks1 with (f:=f0) (s:=s0) ;auto.\n\n  eapply no_os_goodks';eauto.\n  false.\nQed.\n\n\nLemma proj_stneq_ex: forall S S' t t' or, \n                       Steq S S' t -> t'<>t ->  projS S t' = Some or ->\n                       projS S' t' =\n                       Some\n                         (\n                           ((gets_g S'),\n                            (get_env (get_smem or)),\n                            (gets_m S')),\n                           \n                           \n                           (snd (fst S')),\n                           (snd or) \n                         ).\nProof.\n    unfold Steq. unfold projS.\n  intros.\n  destruct or.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct S.\n  destruct p.\n  destruct S'.\n  destruct p.\n  destruct H.\n  unfold Dteq in H.\n  destruct c.\n  destruct p.\n  destruct c0.\n  destruct p.\n  unfold Piteq in H2.\n  pose proof (H t' H0).\n  pose proof (H2 t' H0).\n  unfold projD in H1.\n  destruct (get c t') eqn:eq1.\n  destruct (get l0 t') eqn:eq2.\n  unfold projD.\n  rewrite <- H3.\n  rewrite <- H4.\n  simpl.\n  unfold gets_g.\n  unfold get_env.\n  unfold gets_m.\n  simpl.\n  inversion H1.\n  subst.\n  reflexivity.\n  inversion H1.\n  inversion H1.\nQed.\n\nLemma IntSeq'': \n  forall pc (po:progunit) pi ip A p c ke ks t I r\n         lenv si isrreg (oi:taskst) o Oi ab absi c' ke' ks' i ch keh ksh ge OO lasrt lg Ml Ol,\n    (*OSAbstMod.get O curtid = Some (oscurt t) ->*)\n    no_call_api_os po pi ip ->\n    no_call_api (c',(ke',ks')) po->\n    GoodI I (snd A) lasrt ->\n    join Oi Ol OO ->\n    joinmem oi Ml o ->\n    r = iretasrt i isrreg si I ge lasrt t lg->\n    (snd (fst A)) i = Some absi ->\n    (*ab = (absi b,(ch,(keh,ksh))) \\/ ab =  (absi b,(ch,(keh,ksh))) ->*)\n    ( forall Mlinv Olinv, satp ((ge,lenv,Mlinv),(isrupd isrreg i false),(true,si,nil)) Olinv (p_local lasrt t lg) ->\n    TaskSim (pc,(po,pi,ip)) (c,(ke,ks)) ((ge,lenv,(merge Ml Mlinv)),(isrupd isrreg i false),(true,si,nil)) (pc,A) (ch,(keh,ksh))(merge Ol Olinv) lasrt I p t) ->\n    goodks (pc,(po,pi,ip)) (ks'##kint c ke lenv ks) ->\n    MethSim pi (snd A) (c',(ke',ks')) oi ab Oi lasrt I retfalse r retfalse t-> \n    InOS (c',(ke', ks'## kint c ke lenv ks)) (pumerge po pi) ->\n    TaskSim (pc,(po,pi,ip)) (c',(ke', ks'## kint c ke lenv ks)) o (pc,A) (curs (hapi_code ab),(kenil,kevent ch keh ksh)) OO lasrt I p t.\nProof.\n  cofix CIH.\n  introv Hnocallos.\n  introv Hnocallc.\n  introv Hgoodi.\n  intros.\n  destruct o as [[[[]]]].\n  unfolds in H0.\n  destruct H0 as (Ge&Ee&M1&M2&ir0&ls&Hf1&Hf2&Hf3).\n  inversion Hf2.\n  subst Ge Ee M2 ir0 ls.\n  rename M1 into mi.\n  subst oi.\n  clear Hf2.\n  apply task_sim.\n  intros.\n  \n  destruct (exint_dec c' ke' ks').\n  destruct H10 as (Hc&Hcallcont &Hintcont).\n  inverts Hc.\n  inverts H9;tryfalse.\n  inverts H11;tryfalse.\n  inverts H9;tryfalse.\n  inverts H13;tryfalse.\n  inverts H13;tryfalse.\n  inversion H10;subst pc0 po0 pi0 ip0.\n  subst.\n  clear H10.\n  inverts H9.\n\n  assert (intcont (ks' ## kint c ke lenv ks) = Some (kint c ke lenv ks)).\n\n  eapply intcont_local;eauto.\n  rewrite H1 in H13.\n  inversion H13;subst c0 ke0 le' ks'0.\n  clear H13.\n  \n  unfolds in H7.\n  mytac.\n  rename x into o1.\n  unfold joinmem in H9.\n  destruct H9 as (Ge&Ee&M1&M2&ir0&ls&Hf1&Hf2&Hf4).\n  inversion Hf2.\n  subst Ge Ee M2 ir0 ls.\n  subst o1.\n  clear Hf2.\n  unfold joinmem in H7.\n  destruct H7 as (Ge&Ee&M0&M2&ir0&ls&Hf1&Hf2&Hf5).\n  inversion Hf2.\n  subst Ge Ee M2 ir0 ls.\n  inverts Hf1.\n  clear Hf2.\n  \n  inversion H5;subst.\n  assert (disjoint Oi Os).\n  clear -H H8.\n  unfolds;geat.\n\n  assert ( (curs (sprim exint), (kenil, ks')) =\n           (curs (sprim exint), (kenil, ks'))) as Hc by auto.\n  unfolds in H18;destruct H18.\n  lets Hmsim:H14 Hc Hcallcont Hintcont H18;eauto.\n  unfold getmem.\n  simpl.\n  clear -Hf3 Hf5.\n  unfolds;join auto.\n  destruct Hmsim as (gamma'&OO'&O'&Os'&Hhmstep&Hojoin'&Hinv'&Hlinv'&Hrspec).\n  unfold iretasrt in Hrspec.\n \n  lets Hsub:ret_st Hrspec.\n  destruct Hsub as (Ha1&Ha2&Ha3&Ha4&Ha5).\n  subst.\n  simpl substaskst in *.\n\n  \n  eapply iret_spec with (m:=mi) (O:=O') (Os:=Os') (Ms:=Ms) (is':= si) (i:=i) (isrreg:= isrreg) (ab':=spec_done None) (MM:=merge mi Ms) (OO:=OO') in Hinv';eauto.\n  \n  destruct Hinv' as (Mlinv'&Mx'&Olinv'&Ox'&Hff3&Hff4&Hff5&Hff6).\n  exists (ch,(keh,ksh)) (merge Ol OO') (ge,lenv,(merge Ml Mlinv'), isrupd isrreg i false,(true,si,(nil:cs))).\n  exists Mx' (merge Ol Olinv') Ox'.\n\n  simpl substaskst in *.\n  splits;auto.\n  Focus 2.\n  unfold joinm2.\n  exists (ge,lenv, M1, ( isrupd isrreg i false), (true,si,(nil:cs))).\n  splits;unfolds.\n  do 6 eexists;splits;eauto.\n\n  eapply join_join_merge;eauto.\n  do 6 eexists;splits;eauto.\n\n  eapply htstepstar_compose_tail with (c':=(curs (hapi_code (spec_done None)), (kenil, kevent ch keh ksh))) (O':=(merge Ol OO')).\n\n  eapply osapi_lift' with (cst:=cst') (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in Hhmstep;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in Hhmstep.\n  mytac.\n  apply join_comm in H20.\n  apply map_join_merge' in H20;subst.\n  instantiate (1:=cst').\n  assert (gamma' = (END None)).\n  clear -Hrspec.\n  simpl in Hrspec;mytac.\n  subst gamma'.\n  eapply H19.\n  clear -H H8 H18.\n  join auto.\n\n  eapply hapi_step;eauto.\n  eapply hintex_step;eauto.\n  assert (disjoint Ol x).\n  clear - H H8 H18.\n  unfolds;join auto.\n\n  eapply hmstepstar_disj in H19;eauto.\n  clear -H19 Hff4.\n\n  eapply join_disj_merge_merge;eauto.\n\n  eapply inv_ncare_le;eauto.\n  assert (disjoint Ml Mlinv').\n  clear -Hff3 Hf5 Hf3.\n\n  eapply join_join_join_merge_disj with (Ms:=Ms);eauto.\n  assert (disjoint Ol Olinv').\n  assert (disjoint Ol x).\n  clear - H H8 H18.\n  unfolds;join auto.\n  eapply hmstepstar_disj in Hhmstep;eauto.\n  clear -Hff4 Hhmstep.\n  unfold disjoint in *.\n  join auto.\n  assert ( (merge Ol Olinv') = (merge Olinv' Ol)).\n  apply disjoint_merge_sym;auto.\n  rewrite H21.\n  rewrite disjoint_merge_sym;auto.\n  eapply CurLINV_merge_hold;eauto.\n  apply disj_sym;auto.\n  apply disj_sym;auto.\n  assert (satp (ge, le, Mlinv', isrupd isrreg i false, (true, si, nil)) Olinv'\n           (CurLINV lasrt t)).\n  clear -Hff6.\n  unfold satp in *.\n  intros.\n  lets Hx: Hff6 aop.\n  unfold CurLINV.\n  unfold p_local in *.\n  exists lg.\n  sep auto.\n  eapply CurLINV_ignore_int;eauto.\n  eapply H3;eauto.\n\n  eapply p_local_ignore_int;eauto.\n  eapply map_join_merge.\n  join auto.\n  \n  (*-----------------------------------------*)\n  \n  unfolds in H7.\n  mytac.\n  rename x into o1.\n  unfold joinmem in H7.\n  destruct H7 as (Ge&Ee&M2&M1&ir0&ls&Hf1&Hf2&Hf4).\n  inversion Hf1.\n  subst Ge Ee M2 ir0 ls.\n  subst o1.\n  clear Hf1.\n  unfold joinmem in H11.\n  destruct H11 as (Ge&Ee&M2&M0&ir0&ls&Hf1&Hf2&Hf5).\n  inversion Hf1.\n  subst Ge Ee M2 ir0 ls.\n  inverts Hf1.\n  subst o2.\n  rename M0 into m0.\n  rename m into M0.\n  \n  inversion H5;subst.\n\n  \n  lets Hltstep: ltstep_no_exint H6 H9 H10 H4;eauto.\n  destruct Hltstep as (c''&ke''&ks''&Hcl'&Hinos&Hcsteq&Hosstep).\n  rename  Hosstep into Hossteppre.\n\n  lets Hosstep: no_call_api_loststep_eq Hossteppre;eauto.\n  eapply H1 with (Ms:=Ms) (Mf:=merge Ml Mf) (Os:=Os) (OO:=merge Os Oi) in Hosstep;auto.\n  subst Cl' cst'.\n  destruct Hosstep as (gamma'&OO'&o'&Ms'&O'&Os'&Hhmstep&Hlj&Hhj&Hinv'&Hlinv'&Hmsim).\n  rename ge into GG.\n  destruct o' as ((((ge&le)&m)&ir)&((ie&is)&cs)).\n  unfold joinm2 in Hlj.\n  destruct Hlj as (o1&Hlj&Hlj').\n  unfolds in Hlj.\n  destruct Hlj as (Ge&Ee&Mx&M'&ir0&ls&Hf1&Hf2&Hff3).\n  inversion Hf1.\n  subst Ge Ee Mx ir0 ls.\n  subst o1.\n  clear Hf1.\n  unfold joinmem in Hlj'.\n  destruct Hlj' as (Ge&Ee&Mx&m0'&ir0&ls&Hf1&Hf2&Hff4).\n  inversion Hf1.\n  subst Ge Ee Mx ir0 ls.\n  subst o''.\n  clear Hf1.\n  exists (curs (hapi_code gamma'), (kenil, kevent ch keh ksh)) (merge Ol OO') (ge,le,(merge Ml m),ir,(ie,is,cs)) Ms' (merge Ol O') Os'.\n  splits;auto.\n\n\n  eapply osapi_lift' with (cst:=cst) (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in Hhmstep;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in Hhmstep.\n  mytac.\n  apply join_comm in H19.\n  apply map_join_merge' in H19;subst.\n  auto.\n  eapply join_join_join_merge with (Ms:=OO);eauto.\n  apply join_comm;auto.\n\n\n  unfold joinm2.\n  exists (ge, le, (merge Ml M'), ir, (ie, is, cs)).\n  split;unfolds.\n  do 6 eexists;splits;eauto.\n  eapply join_disj_merge_merge;eauto.\n\n  apply disj_sym.\n  eapply disj_merge_join_disj_intro;eauto.\n  clear -Hf3 Hf4 Hf5.\n  unfolds;join auto.\n  do 6 eexists;splits;eauto.\n\n  eapply disj_join_join_merge;eauto.\n  clear -Hf3 Hf4 Hf5.\n  unfolds;join auto.\n  eapply join_disj_merge_merge;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n\n  assert (disjoint Ml m).\n  eapply disj_merge_join_disj_intro in Hff4;eauto.\n  clear - Hff3 Hff4;unfold disjoint in *;join auto.\n  unfolds;join auto.\n  assert (disjoint Ol O').\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj in Hhmstep;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  clear -H19 Hhj.\n  unfold disjoint in *.\n  join auto.\n  assert ( (merge Ol O') = (merge O' Ol)).\n  apply disjoint_merge_sym;auto.\n  rewrite H20.\n  rewrite disjoint_merge_sym;auto.\n  eapply CurLINV_merge_hold;eauto.\n  apply disj_sym;auto.\n  apply disj_sym;auto.\n\n  eapply CIH with  (isrreg:=isrreg) (si:=si) (Ml:=Ml) (ab:=gamma');eauto.\n\n  eapply no_call_api_loststep_still;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  unfolds.\n  do 6 eexists;splits;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  eapply disj_merge_join_disj_intro in Hff4;eauto.\n  clear - Hff3 Hff4;unfold disjoint in *;join auto.\n  unfolds;join auto.\n\n  eapply ltstep_goodks;eauto.\n\n  unfolds.\n  exists ((e, e0, merge mi Ms, i0, l)).\n  split;unfolds;\n  do 6 eexists;splits;eauto.\n  apply join_merge_disj.\n  unfolds;join auto.\n\n  eapply join_merge_merge_recompose;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  unfolds;join auto.\n\n  (*--------------------------------------------*)\n\n  intros.\n  inversion H9;subst;tryfalse.\n  (*------------------------------------*)\n  intros.\n  inversion H0;subst c' ke' ks0.\n  inversion H5;subst.\n  simpl substaskst in *.\n  apply H11 with (ks:=ks') (x0:=x) (OO:=merge Oi Os)in H7;auto.\n  destruct H7 as (gamma'&sleft&OO'&oll&Mc&O'&Os'&Oll&Oc&Hgammaeq&Hhm&Hlj&Hhj&Hhj'&Hinv&Hswinv&Hlinv&Hmsim).\n  rename ge into GG.\n  subst gamma'.\n  destruct oll as [[[[]]]].\n  unfolds in Hlj.\n  destruct Hlj as (Ge&Ee&Mll&m0'&ir0&ls&Hf1&Hf2&Hff4).\n  inversion Hf1.\n  subst Ge Ee m0 ir0 ls.\n  inversion Hf2;subst e1 e2 m0' i1 l0.\n  clear Hf2.\n  clear Hf1.\n  exists (curs (hapi_code (sched;; sleft)), (kenil,kevent ch keh ksh)) sleft (kenil,kevent ch keh ksh).\n  exists (merge Ol OO') Mc (e,e0,(merge Ml Mll),i0,l).\n  exists (merge Ol O') Os' (merge Ol Oll) Oc.\n  splits;auto.\n  intros.\n  eapply osapi_lift' with (cst:=cst) (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in Hhm;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in Hhm.\n  mytac.\n  apply join_comm in H7.\n  apply map_join_merge' in H7;subst.\n  auto.\n\n  eapply join_join_join_merge';eauto.\n  apply join_comm;auto.\n  unfolds.\n  do 6 eexists;splits;eauto.\n  eapply join_join_join_merge;eauto.\n  apply join_comm;auto.\n  eapply join_disj_merge_merge;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  eapply join_disj_merge_merge;eauto.\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  splits;auto.\n\n  eapply linvtrue_merge_hold;eauto.\n  unfolds;join auto.\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  destruct Hmsim.\n  Focus 2.\n  right;auto.\n  left.\n  mytac.\n  simpl getsched;auto.\n  intros.\n  eapply CIH with (isrreg:=isrreg) (si:=si) (Ml:=Ml) (ab:=sleft) (oi:=(e, e0, merge Mll Mc', i0, l)) (Ol:=Ol) (Oi:=merge Oll Oc');eauto.\n  assert (disjoint Oll Ol).\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  apply join_comm in H20.\n  eapply disj_join_join_merge;eauto.\n  rewrite disjoint_merge_sym;auto.\n  destruct o' as [[[[]]]].\n  unfolds in H19;mytac.\n  unfolds;do 6 eexists;splits;eauto.\n  assert (disjoint Mll Ml).\n  unfolds;join auto.\n  eapply disj_join_join_merge;eauto.\n  rewrite disjoint_merge_sym;auto.\n  apply join_comm;auto.\n  eapply H7;eauto.\n  unfolds;do 6 eexists;splits;eauto.\n  apply join_merge_disj.\n  unfolds in H19;mytac.\n  assert (disjoint Mll Ml).\n  unfolds;join auto.\n  apply disj_sym.\n  eapply disj_merge_join_disj_intro;eauto.\n  rewrite disjoint_merge_sym;eauto.\n  apply join_comm;eauto.\n  assert (disjoint Oll Ol).\n  assert (disjoint Ol OO').\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  apply join_merge_disj.\n  apply disj_sym.\n  eapply disj_merge_join_disj_intro;eauto.\n  rewrite disjoint_merge_sym;eauto.\n  apply join_comm;eauto.\n\n  eapply int_inos_sw_still.\n  eauto.\n  unfold getmem in *;simpl.\n  unfolds in H8;simpl in H8.\n  unfolds;join auto.\n  apply join_merge_disj.\n  unfolds;join auto.\n  (*-------------------------------------*)\n  unfold IsEnd.\n  intros.\n  inversion H5.\n  subst.\n  destruct H0 as (v&H0).\n  inversion H0;tryfalse.\n  destruct ks';tryfalse.\n  (*--------------------------------------*)\n  intros.\n  inversion H5;subst.\n  unfold joinm2 in H11.\n  mytac.\n \n  unfold joinmem in H1.\n  destruct H1 as (Ge&Ee&M0&M2&ir0&ls&Hf1&Hf2&Hff3).\n  inverts Hf1.\n  subst x.\n\n  unfold joinmem in H11.\n  destruct H11 as (g&e&M1&M3&ir&ls0&Hf1&Hf2&Hf4).\n  inversion Hf1;subst g e M1 ir ls0.\n  subst o';clear Hf1.\n\n  simpl substaskst in *.\n  cut (joinm2 (Ge, Ee, mi, ir0, ls) Ms (merge Ml Mf) (Ge, Ee, M3, ir0, ls)).\n  intros.\n  lets Habt: H21 H10 H1;eauto.\n  Focus 2.\n\n  eapply int_nabt_lift in Habt;eauto. \n  destruct Habt;eauto.\n\n  eapply inos_int;eauto.\n  unfolds;join auto.\n\n  unfold notabort.\n  splits;eauto.\n  \n  unfold IsSwitch.\n  auto.\n  intro X.\n  destruct H7.\n  unfolds.\n  mytac.\n  do 2 eexists;eauto.\n\n  intro X.\n  unfold IsEnd in X.\n  destruct X as (v&X).\n\n  assert (  disjoint (getmem (Ge, Ee, mi, ir0, ls)) Ms).\n  unfold getmem.\n  unfolds.\n  simpl.\n  join auto.\n  assert (exists Ox, join Oi Os Ox).\n  join auto.\n  destruct H24.\n  lets XX: H17 X H10  H11 H24;eauto. \n  \n  mytac.\n  unfold retfalse in H29.\n  unfold sat in H29.\n  inversion H29.\n  \n  intro X.\n  unfold IsRet  in  X.\n  destruct X as (ks0&X&XX&XXX).\n  \n  assert (  disjoint (getmem (Ge, Ee, mi, ir0, ls)) Ms).\n  unfold getmem.\n  unfolds.\n  simpl.\n  join auto.\n  assert (exists Ox, join Oi Os Ox).\n  join auto.\n  destruct H24.\n  lets Hx: H18 X H10  H11 H24;eauto. \n  mytac.\n  unfold retfalse in H29.\n  unfold sat in H29.\n  inversion H29.\n\n  intro X.\n  unfold IsRetE  in  X.\n  destruct X as (v&ks0&X&XX&XXX).\n  \n  assert (  disjoint (getmem (Ge, Ee, mi, ir0, ls)) Ms).\n  unfold getmem.\n  unfolds.\n  simpl.\n  join auto.\n  assert (exists Ox, join Oi Os Ox).\n  join auto.\n  destruct H24.\n  lets Hx: H19 X H10  H11 H24;eauto. \n  mytac.\n  unfold retfalse in H29.\n  unfold sat in H29.\n  inversion H29.\n\n  intro X.\n  assert (IsIRet (c', (ke', ks'))) as Hf;auto.\n  unfold IsIRet in X.\n  destruct X as (ks0&X&XX&XXX).\n  assert (  disjoint (getmem (Ge, Ee, mi, ir0, ls)) Ms).\n  unfold getmem.\n  unfolds.\n  simpl.\n  join auto.\n  assert (exists Ox, join Oi Os Ox).\n  join auto.\n  destruct H24.\n  lets Hx: H20 X XXX H11 H24;eauto. \n  mytac.\n\n  eapply isiret_nabt in Hf;eauto.\n\n  intros X.\n  unfolds in X.\n  destruct H8;unfolds.\n  mytac.\n  eauto.\n  \n  intros X.\n  unfolds in X.\n  destruct H9;unfolds.\n  mytac.\n  eauto.\n  \n  unfolds.\n  exists (Ge,Ee,merge mi Ms,ir0,ls).\n  split;unfolds;do 6 eexists;splits;eauto.\n  apply join_merge_disj.\n  unfolds;join auto.\n  eapply join_merge_merge_recompose;eauto.\n\n  (*-------------stkinit---------------*)\n  intros.\n  inverts H0.\n  inverts H5.\n  simpl substaskst in *.\n  clear H0 H10 H11 H12 H13 H14 H15 H17.\n  eapply H16 with (OO:=merge Oi Os) in H7;eauto.\n  destruct H7 as (gamma'&v1&v2&t'&pri&sleft&OO'&OO''&ol&Mcre&O'&Os'&Oll&Ocre&H7).\n  mytac.\n  \n  exists (curs (hapi_code (spec_crt v1 v2 (Vint32 pri);; sleft)), (kenil,kevent ch keh ksh)) v1 v2 t' pri.\n  exists sleft (kenil,kevent ch keh ksh).\n  exists (merge Ol OO') (merge Ol OO'').\n  destruct ol as [[[[]]]].\n  unfolds in H13.\n  destruct H13 as (g&le&Mll&M3&ir&ls0&Hf1&Hf2&Hf4).\n  inversion Hf2;subst g le M3 ir ls0.\n  inverts Hf1;clear Hf2.\n  exists (e, e0, merge Ml Mll, i0, l) Mcre (merge Ol O') Os' (merge Ol Oll) Ocre.\n  simpl get_smem in *.\n  splits;eauto.\n  eapply evalval_eq_prop;eauto.\n  unfolds;join auto.\n  eapply evalval_eq_prop;eauto.\n  unfolds;join auto.\n  eapply evalval_eq_prop;eauto.\n  unfolds;join auto.\n  intros.\n  \n  eapply osapi_lift' with (cst:=cst) (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in H11;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in H11.\n  mytac.\n  apply join_comm in H1.\n  apply map_join_merge' in H1;subst.\n  auto.\n  eapply join_join_join_merge';eauto.\n  apply join_comm;auto.\n\n  eapply abs_crt_step_local;eauto.\n  apply disj_sym.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfolds;do 6 eexists;splits;eauto.\n  eapply join_join_join_merge;eauto.\n  apply join_comm;auto.\n  splits;eauto.\n  eapply join_disj_merge_merge;eauto.\n\n  eapply abs_crt_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  eapply join_disj_merge_merge;eauto.\n  assert (disjoint Ol OO'').\n  eapply abs_crt_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *.\n  join auto.\n  assert(disjoint Ml Mll).\n  unfolds;join auto.\n  assert (disjoint Ol Oll).\n  assert (disjoint Ol OO'').\n  eapply abs_crt_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  assert ( (merge Ol Oll) = (merge Oll Ol)).\n  apply disjoint_merge_sym;auto.\n  rewrite H13.\n  rewrite disjoint_merge_sym;auto.\n  eapply CurLINV_merge_hold;eauto.\n  apply disj_sym;auto.\n  apply disj_sym;auto.\n  eapply CIH;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  assert (disjoint Ol OO'').\n  eapply abs_crt_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  unfolds.\n  do 6 eexists;splits;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  unfolds;join auto.\n  eapply int_inos_stkinit_still;eauto.\n  unfold getmem in *;simpl.\n  simpl in H8.\n  unfold disjoint in *;join auto.\n  apply join_merge_disj.\n  unfolds;join auto.\n  (*-------------stk free----------------*)\n  intros.\n  inverts H0.\n  inverts H5.\n  simpl substaskst in *.\n  clear H0 H10 H11 H12 H13 H14 H15 H16.\n  eapply H17 with (OO:=merge Oi Os) in H7;eauto.\n  destruct H7 as (gamma'&pri&sleft&t'&OO'&OO''&O'&Os'&Oll&H7).\n  mytac.\n  destruct H7.\n  (*del self*)\n  mytac.\n  exists (curs (hapi_code (spec_del (Vint32 pri);; sleft)), (kenil,kevent ch keh ksh)) pri.\n  exists sleft (kenil,kevent ch keh ksh) t'.\n  exists (merge Ol OO') (merge Ol OO'').\n  exists (merge Ol O') Os'.\n  simpl get_smem in *.\n  splits;eauto.\n  eapply evalval_eq_prop;eauto.\n  unfolds;join auto.\n  intros.\n  eapply osapi_lift' with (cst:=cst) (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in H5;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in H5.\n  mytac.\n  apply join_comm in H13.\n  apply map_join_merge' in H13;subst.\n  auto.\n  eapply join_join_join_merge';eauto.\n  apply join_comm;auto.\n  left.\n  splits;auto.\n  eapply abs_delself_step_local;eauto.\n  apply disj_sym.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  eapply join_join_join_merge;eauto.\n\n  apply join_merge_disj.\n  eapply abs_delself_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  assert (m = merge mi Ml).\n  eapply map_join_merge';auto.\n  subst m.\n  assert (disjoint Ol O').\n  assert (disjoint Ol OO'').\n  eapply abs_delself_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  assert ( (merge Ol O') = (merge O' Ol)).\n  apply disjoint_merge_sym;auto.\n  rewrite H14.\n  eapply CurLINV_merge_hold;eauto.\n  unfolds;join auto.\n  apply disj_sym;auto.\n  eapply CIH;eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  assert (disjoint Ol OO'').\n  eapply abs_delself_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  unfolds.\n  do 6 eexists;splits;eauto.\n\n  eapply int_inos_stkfree_still;eauto.\n\n  (*del other*)\n  mytac.\n  exists (curs (hapi_code (spec_del (Vint32 pri);; sleft)), (kenil,kevent ch keh ksh)) pri.\n  exists sleft (kenil,kevent ch keh ksh) t'.\n  exists (merge Ol OO') (merge Ol OO'').\n  exists (merge Ol O') Os'.\n  simpl get_smem in *.\n  splits;eauto.\n  eapply evalval_eq_prop;eauto.\n  unfolds;join auto.\n  intros.\n  eapply osapi_lift' with (cst:=cst) (pc:=pc) (A:=A) (t:=t) (ke:=kenil) (ks:= kevent ch keh ksh)in H5;eauto.\n  eapply htstepstar_O_local with (Of:=Ol) (OO:=OO0)in H5.\n  mytac.\n  apply join_comm in H13.\n  apply map_join_merge' in H13;subst.\n  auto.\n  eapply join_join_join_merge';eauto.\n  apply join_comm;auto.\n  right.\n  splits;auto.\n  eapply abs_delother_step_local;eauto.\n  apply disj_sym.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  eapply join_join_join_merge;eauto.\n\n  apply join_merge_disj.\n  eapply abs_delother_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  assert (m = merge mi Ml).\n  eapply map_join_merge';auto.\n  subst m.\n  assert (disjoint Ol O').\n  assert (disjoint Ol OO'').\n  eapply abs_delother_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  assert ( (merge Ol O') = (merge O' Ol)).\n  apply disjoint_merge_sym;auto.\n  rewrite H14.\n  eapply CurLINV_merge_hold;eauto.\n  unfolds;join auto.\n  apply disj_sym;auto.\n  intros.\n  assert (joinmem (e, e0, mi, i0, l) Mdel (e, e0, merge mi Mdel, i0, l)).\n  destruct o' as [[[[]]]].\n  unfolds in H14.\n  destruct H14 as (Ge&Ee&M&m0'&ir0&ls&Hf1&Hf2&Hff4).\n  inversion Hf1.\n  subst Ge Ee M ir0 ls.\n  inverts Hf2.\n  clear Hf1.\n  unfolds.\n  do 6 eexists;splits;eauto.\n  apply join_merge_disj.\n  unfolds;join auto.\n  assert (join O' Odel (merge O' Odel)).\n  apply join_merge_disj.\n  assert (disjoint Ol O').\n  assert (disjoint Ol OO'').\n  eapply abs_delother_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  rewrite disjoint_merge_sym in H15;auto.\n\n  apply disj_sym.\n  apply join_comm in H15.\n  eapply disj_merge_join_disj_intro;eauto.\n  apply disj_sym;auto.\n  lets Hx:H12 H13 H16 H18.\n  assert (disjoint Ol O').\n  assert (disjoint Ol OO'').\n  eapply abs_delother_disj;eauto.\n  eapply hmstepstar_disj;eauto.\n  eapply disj_merge_intro_r;eauto.\n  split;unfolds;join auto.\n  unfold disjoint in *;join auto.\n  eapply CIH with (isrreg:=isrreg) (si:=si) (Ml:=Ml) (ab:=sleft) (oi:=(e, e0, merge mi Mdel, i0, l)) (Ol:=Ol) (Oi:=merge O' Odel);eauto.\n  apply join_comm in H15.\n  eapply disj_join_join_merge;eauto.\n  rewrite disjoint_merge_sym in H15;auto.\n  apply disj_sym;auto.\n  destruct o' as [[[[]]]].\n  unfolds in H14.\n  destruct H14 as (Ge&Ee&M&m0'&ir0&ls&Hf1&Hf2&Hff4).\n  inversion Hf1.\n  subst Ge Ee M ir0 ls.\n  inverts Hf2.\n  clear Hf1.\n  unfolds;do 6 eexists;splits;eauto.\n  clear - Hff4 Hf3.\n  eapply join_join_join_merge';eauto.\n  apply join_comm;auto.\n  eapply int_inos_stkfree_still;eauto. \n  unfold getmem in *;simpl.\n  simpl in H8.\n  unfold disjoint in *;join auto.\n  apply join_merge_disj.\n  unfolds;join auto.\nQed.\n\n\n\nLemma IntSeq': forall pc po pi ip (A:osspec) O Oi Mi I ch keh ksh c ke ks Mc t s Ms Os Ms' Os' p lenv  ge le m ir ie is cs sh i lasrt,\n                 ip i = Some s ->\n                 (snd (fst A)) i = Some sh->\n                 no_call_api_os po pi ip ->\n                 GoodI I (snd A) lasrt ->\n                 TaskSim (pc,(po,pi,ip)) ( c, (ke, ks)) (substaskst  ((ge,le,m),ir,(ie,is,cs)) Mc) (pc,A) (ch,(keh,ksh)) O lasrt I p t -> \n                 fst (fst (get_smem  ((ge,le,m),ir,(ie,is,cs)))) = ge ->\n\n                 lintstep' i ip (c ,(ke, ks))  ((ge,le,m),ir,(ie,is,cs)) ((curs s), (kenil, (kint c ke lenv  ks))) (ge, empenv, m, isrupd ir i true, (false, i :: is, nil)) ->\n                 (forall ab, sat (((substaskst  ((ge,le,m),ir,(ie,is,cs)) Ms),Os),ab) (INV I)) ->\n                 (forall ab, sat (((ge, empenv,Ms', isrupd ir i true, (false, i :: is, nil)),Os'),ab) (INV I)) ->\n                 join Oi Os' Os ->\n                 disjoint O Os ->\n                 join Mi Ms' Ms ->\n                 disjoint Mc Ms ->\n                 satp ((ge,le,Mc),ir,(ie,is,cs)) O (CurLINV lasrt t) ->\n                 (\n                   forall (i:hid) ispec isrreg si G lg t, \n                     (snd (fst A)) i = Some ispec ->\n                     (\n                       exists (s:stmts) p r,\n                         ip i = Some s /\\ \n                         p = ipreasrt i isrreg si ispec I G lasrt t lg /\\ \n                         r = iretasrt i isrreg si I G lasrt t lg /\\\n                         MethSimAsrt pi (snd A) lasrt I retfalse r p s Afalse t\n                     )\n                 )->\n                 eqdomOS (po,pi,ip) A ->\n                 goodks (pc,(po,pi,ip)) ks->\n                 TaskSim (pc,(po,pi,ip)) ((curs s), (kenil, (kint c ke lenv ks))) \n                         ((ge, empenv, merge Mc Mi, isrupd ir i true, (false, i :: is, nil))) (pc,A) ((curs (hapi_code sh)), (kenil, kevent ch keh ksh)) (merge O Oi) lasrt I p t.\nProof.\n  introv Hcl.\n  introv Hch.\n  introv Hnoos.\n  introv Hgoodi.\n  intros.\n\n  lets Hx:curlinv_p_local_trans H8.\n  destruct Hx as (Ml&Mlinv&Ol&Olinv&lg&Hjoinml&Hjoinol&Hplocal).\n  simpl in H0.\n  inversion H1;subst.\n  assert (kint c ke lenv ks = kstop ## kint c ke lenv ks).\n  simpl;auto.\n  rewrite H12.\n  unfold eqdomOS in H10.\n  destruct A as ((B&C)&sc).\n  destruct H10.\n  destruct H13.\n  destruct (H14 i).\n  assert (exists idef,ip i = Some idef).\n  exists s;auto.\n  apply H15 in H17.\n  destruct H17.\n  assert (disjoint O Oi).\n  unfold disjoint in *;join auto.\n  assert (merge O Oi = merge Oi O).\n  apply disjoint_merge_sym;auto.\n  rewrite H20.\n  assert (disjoint Mc Mi).\n  unfold disjoint in *;join auto.\n  assert (merge Mc Mi = merge Mi Mc).\n  apply disjoint_merge_sym;auto.\n  rewrite H22.\n  eapply IntSeq'' with (absi:=x) (i:=i) (Ol:=Ol) (ge:=ge) (Ml:=Ml) (Oi:=merge Oi Olinv) (oi:=(ge, empenv, merge Mi Mlinv, isrupd ir i true, (false, i :: is, nil))) (isrreg:=ir) (lg:=lg) (si:=is);eauto.\n  clear -Hnoos H30.\n  unfolds in Hnoos.\n  mytac;unfold no_call_api_ipu in *.\n  apply H1 in H30;simpl;auto.\n  eapply join_disj_merge_merge;eauto.\n  apply join_comm;auto.\n  apply disj_sym;auto.\n  unfold joinmem.\n  do 6 eexists;splits;eauto.\n  eapply join_disj_merge_merge;eauto.\n  apply join_comm;auto.\n  apply disj_sym;auto.\n  \n  intros.\n  lets Hx: p_local_exact Hplocal H23.\n  destruct Hx;subst.\n  simpl substaskst in *.\n  apply join_merge in Hjoinml.\n  apply join_merge in Hjoinol.\n  subst;auto.\n  rewrite <- higherint_update_eq;auto.\n\n  unfold MethSimAsrt in H9.\n  simpl in H9.\n  assert (C i = Some x) as Hhc;auto.\n  eapply H9 with (si:=is) (isrreg:=ir) (G:=ge) (lg:=lg) (t:=t) in H17.\n  destruct H17 as (S0&p0&r&Hip&Hp&Hr&Hmsim).\n  rewrite Hip in H30;inverts H30.\n  assert ((((ge, empenv, (merge Mi Mlinv),  isrupd ir i true, (false, i::is, nil)) ,\n           (merge Oi Olinv), (x )) |= ipreasrt i ir is (x ) I ge lasrt t lg) /\\ satp (ge, empenv, (merge Mi Mlinv),  isrupd ir i true, (false, i::is, nil))  (merge Oi Olinv) (CurLINV lasrt t)).\n\n  eapply en_int_inv with (Ms':=Ms') (Os':=Os') (Ms:=Ms) (Os:=Os) (Mi:=Mi) (Oi:=Oi);eauto.\n  unfold disjoint in *;join auto.\n  unfold disjoint in *;join auto.\n  unfold substaskst in H2.\n\n  eapply INV_irrev_prop ;eauto.\n  eapply p_local_ignore_int;eauto.\n  subst p0.\n  apply Hmsim in H17.\n  simpl snd.\n  subst r.\n  unfold retfalse at 2.\n  unfold lift in H17.\n  unfold nilcont in H17.\n \n  simpl in Hch.\n  rewrite Hch in Hhc;inverts Hhc.\n  auto.\n  unfold InOS.\n  exists (curs s) kenil (kstop##kint c ke lenv ks).\n  splits;auto.\n  Grab Existential Variables.\n  trivial.\nQed.\n(*\nLemma init_subs: forall o o' Ms O, InitTaskSt (substaskst o empmem, O) -> InitTaskSt (substaskst o' empmem, O) -> substaskst o' Ms = substaskst o Ms.\nProof.\n  unfold InitTaskSt.\n  intros.\n  destruct o', o.\n  destruct p ,p0.\n  destruct s,s0.\n  destruct p,p0.\n  simpl.\n  simpl in H.\n  simpl in H0.\n  destruct H as (H1&H2&H3&H4&H5).\n  subst.\n  destruct H0 as (H1'&H2'&H3'&H4'&H5').\n  subst.\n  destruct H5;destruct H5'.\n  subst.\n  auto.\nQed.*)\n\nLemma inos_lift: forall v ks po pi,\n                   ~ InOS (SKIP, (kenil, ks)) (pumerge po pi) ->\n                   ~ InOS (curs (sskip v), (kenil, ks)) (pumerge po pi).\nProof.\n  unfold InOS.\n  intros.\n  intro X.\n  destruct H.\n  destruct X as (c&ke&ks0&X&X').\n  inversion X;subst c ke ks0.\n  exists SKIP kenil ks.\n  splits;auto.\n  destruct X'.\n  destruct H as (f&vl&fc&tl&H&HH).\n  inversion H.\n  right.\n  auto.\nQed.\n\n\nLemma GoodStmt_to_GoodStmt': forall s p, GoodStmt s p ->GoodStmt' s.\nProof.\n  intros.\n  induction s;simpl;auto;simpl in H.\n  destruct H.\n  split.\n  apply IHs1;eauto.\n  apply IHs2;eauto.\n  destruct H.\n  split.\n  apply IHs1;eauto.\n  apply IHs2;eauto.\nQed.\n\nLemma goodstmt'_n_dym_com_s: forall s, GoodStmt' s -> n_dym_com_s s.\nProof.\n  induction s;simpl;auto.\nQed.\n\n\nLemma n_dym_ks_call: forall ks' ks f s, n_dym_com_int_scont (ks'##kcall f s empenv ks) -> n_dym_com_int_scont ks.\nProof.\n  induction ks';intros;simpl;auto;try solve [simpl in H;destruct H;auto |simpl in H;destruct H;eapply IHks';eauto | simpl in H;eapply IHks';eauto].\n  simpl in H.\n  destruct H.\n  destruct H0.\n  eapply IHks';eauto.\nQed.\n\nLemma goodstmt_n_dym_com_s: forall s p , GoodStmt s p-> n_dym_com_s s.\nProof.\n  intros.\n  induction s;simpl;auto.\n  simpl in H.\n  destruct H.\n  split.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  simpl in H.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  simpl in H.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  simpl in H;destruct H.\n  split.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  eapply GoodStmt_to_GoodStmt';eauto.\nQed.\n\n\nLemma pumerge_get_ex:forall p p' f t d1 d2 s, (pumerge p p') f= Some (t,d1,d2,s) -> p f =Some (t,d1,d2,s)\\/ p' f = Some (t,d1,d2,s).\nProof.\n  intros.\n  unfold pumerge in *.\n  destruct (p f).\n  left;auto.\n  destruct (p' f);tryfalse.\n  right;auto.\nQed.\n\nLemma callcont_ndymint:forall ks f s le ks', callcont ks = Some (kcall f s le ks') -> n_dym_com_int_scont ks -> n_dym_com_int_scont ks'. \nProof.\n  induction ks;intros;simpl;auto;tryfalse;\n  try solve [simpl in H0;simpl in H;\n             destruct H0;\n             eapply IHks;eauto |\n             inversion H;subst;\n             simpl in H0;\n             destruct H0;auto | simpl in H0;\n               simpl in H;eapply IHks;eauto ].\n  simpl in H0.\n  destruct H0.\n  destruct H1;eapply IHks;eauto. \nQed.\n\nLemma ltstep_n_dym_com_int_cd:  \n  forall pc po pi ip t c' ke' ks' c'' ke'' ks'' cst o cst' o', \n    (forall f t d1 d2 s, po f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall f t d1 d2 s, pi f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    GoodClient pc po pi ->\n    ltstep (pc,(po,pi,ip)) t (c', (ke', ks' )) cst o (c'', (ke'', ks'' )) cst' o' -> n_dym_com_int_cd (c', (ke', ks' )) -> n_dym_com_int_cd (c'', (ke'', ks'' )).\nProof.\n  intros.\n  assert ( forall (f : fid) (a : type) (b c : decllist) (s : stmts),\n             pc f = Some (a, b, c, s) -> GoodStmt' s).\n  intros.\n  apply H1 in H4.\n  eapply GoodStmt_to_GoodStmt';eauto.\n  clear H1.\n  rename H4 into H1.\n  unfold n_dym_com_int_cd in *.\n  destruct H3.\n  inversion H2;subst.\n  inversion H5;subst pc0 po0 pi0 ip0;clear H5.\n\n  inversion H6;subst.\n\n  inversion H15;subst;clear H15.\n  inversion H16;subst;simpl;split;auto.\n  inversion H15;subst.\n  inversion H16;subst;simpl;split;auto;try solve [simpl in H3;destruct H3;auto| simpl in H4;destruct H4;auto|simpl in H4;destruct H4;eapply goodstmt'_n_dym_com_s;eauto].\n  split;auto. \n  apply pumerge_get_ex in H9.\n  inversion H5;subst ge0 le0 M0.\n  inversion H8;subst.\n  destruct H9.\n  apply H1 in H9;auto.\n  apply H in H9;destruct H9;auto.\n  eapply callcont_ndymint;eauto.\n  simpl in H3.\n  destruct H3;eapply goodstmt'_n_dym_com_s;eauto.\n  simpl in H4.\n  destruct H4.\n  destruct H5;auto.\n  simpl in H4.\n  destruct H4;destruct H5.\n  eapply goodstmt'_n_dym_com_s;eauto.\n  simpl in H4;destruct H4;destruct H5;auto.\n  inversion H5;subst pc0 po0 pi0 ip0.\n  inversion H6;subst;try solve [inversion H14;subst;\n                                simpl;auto | inversion H15;subst;\n                                             simpl;auto].\n  Focus 2.\n  inversion H15;subst.\n  Lemma int_ndymint_false:forall ks c ke le ks', intcont ks = Some (kint c ke le ks') -> ~(n_dym_com_int_scont ks).\n  Proof.\n    intros.\n    induction ks;simpl;auto;tryfalse.\n    simpl in H.\n    apply or_not_and.\n    right;auto.\n    simpl in H.\n    apply or_not_and.\n    right.\n    apply or_not_and.\n    right.\n    apply IHks;auto.\n    simpl in H.\n    apply or_not_and.\n    right;apply IHks;auto.\n  Qed.\n  apply int_ndymint_false in H16;false.\n\n  inversion H8;subst.\n  inversion H16;subst;clear H16.\n  inversion H17;subst;simpl;split;auto.\n  inversion H16;subst.\n  inversion H17;subst;simpl;split;auto;try solve [simpl in H3;destruct H3;auto| simpl in H4;destruct H4;auto|simpl in H4;destruct H4;eapply goodstmt'_n_dym_com_s;eauto].\n  split;auto. \n  apply pumerge_get_ex in H11.\n  destruct H11.\n  apply H in H9;destruct H9;auto.\n  apply H0 in H9;destruct H9;auto.\n\n  eapply callcont_ndymint;eauto.\n  simpl in H3.\n  destruct H3;eapply goodstmt'_n_dym_com_s;eauto.\n  simpl in H4.\n  destruct H4.\n  destruct H10;auto.\n  simpl in H4.\n  destruct H4;destruct H10.\n  eapply goodstmt'_n_dym_com_s;eauto.\n  simpl in H4;destruct H4;destruct H10;auto.\n  inversion H11;subst.\n  split;auto.\nQed.\n\nLemma ltstepev_n_dym_com_int_cd:  \n  forall pc po pi ip t c' ke' ks' c'' ke'' ks'' cst o cst' o' ev, \n    (forall f t d1 d2 s, po f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall f t d1 d2 s, pi f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    GoodClient pc po pi ->\n    ltstepev (pc,(po,pi,ip)) t (c', (ke', ks' )) cst o (c'', (ke'', ks'' )) cst' o' ev-> n_dym_com_int_cd (c', (ke', ks' )) -> n_dym_com_int_cd (c'', (ke'', ks'' )).\nProof.\n  intros.\n  inversion H2;subst.\n  inversion H5;subst.\n  inversion H13;subst.\n  inversion H16;subst;simpl;auto.\nQed.\n\n\nLemma tlmatch_dec':forall tl dl (vl:vallist), ~(tlmatch tl dl/\\ dl_vl_match dl (rev vl)=true)\\/ (tlmatch tl dl /\\ dl_vl_match dl (rev vl)=true).\nProof.\n  intros.\n  assert ((tlmatch tl dl /\\ dl_vl_match dl (rev vl)=true) \\/\n          ~(tlmatch tl dl /\\ dl_vl_match dl (rev vl)=true)).\n  eapply classic.\n  destruct H.\n  right.\n  auto.\n  left;auto.\nQed.\n\n\nLemma pumerge_get: forall po pi f t d1 d2 s, po f= Some (t, d1, d2, s) -> (pumerge po pi) f = Some (t,d1,d2,s).\nProof.\n  intros.\n  unfold pumerge.\n  rewrite H.\n  auto.\nQed.\n\n\nLemma funbody'_inos: forall s po pi f ft d1 d2 s', GoodStmt' s-> po f = Some (ft,d1,d2,s') -> InOS (curs s,(kenil, kcall f s' empenv kstop)) (pumerge po pi).\nProof.\n  intros.\n  unfold InOS.\n  exists (curs s) kenil (kcall f s' empenv kstop).\n  splits;auto.\n  right.\n  left.\n  exists f (empenv:env) kstop ft d1. \n  exists d2 s' s'.\n  split;simpl;auto.\n  apply pumerge_get.\n  auto.\nQed.\n\nLemma cstep_no_api_elim:\n  forall po pi c ke ks c' ke' ks' o o',\n  no_call_api (c,(ke,ks)) po -> \n  cstep (pumerge po pi) (c, (ke, ks)) o (c', (ke', ks')) o' ->\n  cstep pi (c, (ke, ks)) o (c', (ke', ks')) o'.\nProof.\n  intros.\n  inverts H0;inverts H8.\n  eapply expr_step;eauto.\n  eapply stmt_step;eauto.\n  inverts H9;constructors;eauto.\n  instantiate (1:=t).\n  simpl in H.\n  unfold pumerge.\n  destruct H.\n  unfold pumerge in H2.\n  rewrite H in H2;auto.\n  destruct (pi f);auto;tryfalse.\nQed.\n\nLemma loststep_no_api_elim:\n  forall po pi c ke ks c' ke' ks' o o',\n  no_call_api (c,(ke,ks)) po -> \n  loststep (pumerge po pi) (c, (ke, ks)) o (c', (ke', ks')) o' ->\n  loststep pi (c, (ke, ks)) o (c', (ke', ks')) o'. \nProof.\n  intros.\n  inverts H0;first [eapply checkis_step | constructors];eauto;tryfalse.\n  eapply cstep_no_api_elim;eauto.\nQed.\n\nLemma XXXX: forall ksx f s kstop ks, ksx ## (kcall f s empenv kstop ## ks) =  ksx ## kcall f s empenv kstop ## ks.\nProof.\n  intro ksx.\n  inductions ksx; intros;\n  try solve [simpl; auto];\n  try solve [simpl; rewrite <- IHksx; auto].\nQed.\n\n\nLemma SmCTaskSim': \n  forall (pc po pi:progunit) (ip:intunit) (A:osspec) I o O  c ke ks1 ks2 ks ch keh lasrt (tid:tid),\n    satp o O (CurLINV lasrt tid) ->\n    no_fun_same po pi ->\n    no_call_api_os po pi ip ->\n    (*good_ret_funs pc po pi ->*)\n    True ->\n    (forall f t d1 d2 s, po f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall f t d1 d2 s, pi f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (\n      forall (f:fid) ab  vl p r ft G tid, \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA po f (ab,ft) vl G lasrt tid init_lg ->\n        Some r = BuildRetA po f (ab,ft) vl G lasrt tid init_lg->\n        (\n          exists t d1 d2 s,\n            po f = Some (t, d1, d2, s)/\\\n            GoodStmt' s /\\\n            MethSimAsrt pi (snd A) lasrt I r Afalse p s Afalse tid\n        )\n    ) -> \n    (eqdomOS (po,pi,ip) A /\\GoodClient pc po pi/\\ goodks (pc,(po,pi,ip)) (ks1##(ks2##ks))/\\n_dym_com_int_cd (c,(ke,ks1##(ks2##ks)))/\\ good_clt (SKIP, (kenil,ks)) pi/\\ (*good_ret_c (c,(ke,(ks1##(ks2##ks))))*) True)->\n    (\n      (~InOS (c,(ke,ks)) (pumerge po pi) /\\ \n       (c=ch/\\ke=keh/\\ks1=kstop/\\ks2=kstop) ) \\/  \n      (exists f vl tl s d1 d2 ft, \n         po f = Some (ft,d1,d2,s)/\\ c = curs (sfexec f vl tl)/\\ ke=kenil/\\ ch =c /\\keh=kenil/\\\n         ks1=kstop/\\ks2=kstop/\\~InOS (SKIP,(kenil,ks)) (pumerge po pi))\\/\n      (exists f vl , exists dl vlh s d1 d2 ft tl, \n         po f = Some (ft,d1,d2,s) /\\ c =curs (salloc vl dl)/\\ke=kenil/\\\n         ch = curs (sfexec f vlh tl)/\\keh=kenil/\\\n         ks1=kstop/\\ks2=kcall f s emp kstop/\\\n         ~InOS (SKIP,(kenil,ks)) (pumerge po pi))\\/\n      (exists f s d1 d2 ft, \n         po f = Some (ft,d1,d2,s)/\\ keh=kenil/\\ks2=kcall f s emp kstop/\\ \n          (forall vl dl,(c,(ke,ks1))<>(curs (salloc vl dl),(kenil,kstop)))/\\\n          (forall al v,  ~ (c=curs (sfree al v) /\\ callcont ks1 = None/\\intcont ks1=None))/\\\n          ~InOS (SKIP,(kenil,ks)) (pumerge po pi))\\/\n      \n      (exists (al:freelist) f s d1 d2 ft v,\n         po f = Some (ft,d1,d2,s)/\\ keh=kenil/\\ks2=kcall f s emp kstop/\\ ke=kenil/\\\n         c=curs (sfree al v)/\\ callcont ks1 = None /\\ intcont ks1 =None/\\\n         ~InOS (SKIP,(kenil,ks)) (pumerge po pi))\n    )->\n    (\n      ~InOS (c,(ke,ks)) (pumerge po pi) ->\n      c=ch-> ke=keh -> ks1=kstop -> ks2=kstop ->\n      InitTaskSt lasrt tid (pair o O) /\\ good_clt (c,(ke,ks)) pi\n    ) -> \n    (\n      forall f vl tl s d1 d2 ft, \n        po f = Some (ft,d1,d2,s)-> c = curs (sfexec f vl tl) -> ke=kenil -> ch =c -> keh=kenil->\n        ks1=kstop -> ks2=kstop ->  ~InOS (SKIP,(kenil,ks)) (pumerge po pi) ->\n        InitTaskSt lasrt tid (pair o O)\n    ) ->\n    (\n      (forall f vl dl vlh s d1 d2 ft tl, \n         po f = Some (ft,d1,d2,s)-> c =curs (salloc vl dl)->ke=kenil->\n         ch = curs (sfexec f vlh tl)->\n         ks1=kstop -> ks2=kcall f s emp kstop ->\n         ~InOS (SKIP,(kenil,ks)) (pumerge po pi) ->\n         (\n           tlmatch (List.rev tl) d1 /\\ tl_vl_match tl vlh =true /\\ good_dl_le dl o /\\ True (*get_genv (get_smem o) = InitG*) /\\\n           exists dl' vl' p,  \n             (vl<>nil -> length_eq vl' dl') /\\ \n             dl_add dl' dl=revlcons d1 d2/\\ vl' ++ vl = vlh/\\buildp dl' vl'=Some p /\\\n             (forall ab,sat ((o,O),ab) ((p ** p_local lasrt tid init_lg ** (Aie true) ** (Ais nil)** (Acs nil) ** (Aisr empisr))** A_dom_lenv (getlenvdom dl')))))\n    ) ->\n    (\n      forall f s d1 d2 ft ab tt, \n        po f = Some (ft,d1,d2,s) -> keh=kenil -> ks2=kcall f s emp kstop ->\n        (forall vl dl,(c,(ke,ks1))<>(curs (salloc vl dl),(kenil,kstop)))->\n        (forall al v,  ~ (c=curs (sfree al v) /\\ callcont ks1 = None/\\intcont ks1=None))->\n        ~InOS (SKIP,(kenil,ks)) (pumerge po pi) ->\n        (fst (fst A)) f = Some (ab,tt) ->\n        (exists R vlh AC, InOS (c,(ke,ks1##kcall f s emp kstop)) (pumerge po pi)/\\ch = curs (hapi_code AC) /\\Some R = BuildRetA po f (ab,tt) vlh (get_genv (get_smem o)) lasrt tid init_lg /\\ no_call_api (c,(ke,ks1)) po /\\\n                          MethSim pi (snd A) (c,(ke,ks1)) o AC O lasrt I R Afalse retfalse tid\n        )     \n    )->\n    \n    (\n      forall (al:freelist)  f s d1 d2 ft v,\n         po f = Some (ft,d1,d2,s) -> keh=kenil -> ks2=kcall f s emp kstop -> ke=kenil ->\n         c=curs (sfree al v) ->  callcont ks1 = None -> intcont ks1 = None->\n         ~InOS (SKIP,(kenil,ks)) (pumerge po pi) ->\n         exists M,\n          (freels al (get_mem (get_smem o)) M /\\ \n          InitTaskSt lasrt tid ((emple_tst (substaskst o M)),O)/\\ ch=curs (sskip v)/\\keh=kenil)\n    ) \n    ->\n    TaskSim (pc, (po,pi,ip)) (c,(ke,ks1##(ks2##ks))) o (pc, A) (ch,(keh,ks)) O lasrt I (InitTaskSt lasrt tid) tid.\nProof.\n  cofix CIH.\n  introv Hlinv.\n  introv Hnofunsame.\n  introv Hnoos.\n  introv Hgoodretos.\n  introv Hgoodpo.\n  introv Hgoodpi.  \n  intros.\n  destruct H0 as (H0&Hgoodclient&Hgoodks&Hndymint&Hgoodclt&Hgoodretc).\n  destruct H1 as [Hc1 | Hc2].\n  lets Hinit:H2 Hc1.\n  destruct Hc1 as (Hninos&Hceq&Hkeeq&Hks1&Hks2).\n  subst ks1 ks2.\n  subst ch keh.\n  assert (kstop##(kstop##ks)=ks).\n  simpl;auto.\n  rewrite H1.\n  apply task_sim.\n  intros.\n  assert (o2=o'').\n\n  eapply cltstep_eqo;eauto.\n  subst o''.\n  lets Hc':step_to_inos_dec Hninos H10;eauto. \n  apply Hinit;auto.\n  destruct Hc'.\n  destruct H11 as (f&a&vl&tl&ks'&Hpf&Hc').\n  subst Cl'.\n  inversion H10;tryfalse.\n  subst  cst'0 C'.\n  subst tst cst0 C p t cst cst' m m'.\n  exists (curs (sfexec f vl tl), (kenil, ks')) OO o Ms O Os.\n  splits;auto.\n\n  eapply ht_starS with (c':=(curs (sfexec f vl tl), (kenil, ks'))) (O':=OO).\n\n  eapply cltstep1_eq;eauto.\n  eapply Hinit;auto.\n  eapply ht_starO.\n  assert (ks'=kstop##(kstop##ks')).\n  simpl;auto.\n  rewrite H14.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  simpl.\n  simpl in Hgoodks.\n  eapply ltstep_goodks;eauto.\n  simpl in Hndymint.\n  eapply ltstep_n_dym_com_int_cd with(pc:=pc) (po:=po) (pi:=pi) (ip:=ip);eauto.\n\n  apply clt_step_good_clt in H10;auto.\n  simpl in H10.\n  simpl.\n  split;auto.\n  destruct H10;auto.\n  apply Hinit;auto.\n(*  eapply ltstep_good_ret;eauto.*)\n  right.\n  left.\n  destruct a as (((ft&d1)&d2)&s).\n  exists f vl tl s d1.\n  exists d2 ft.\n  splits;auto.\n  (simpl;auto).\n  eapply step_fexec_ninos;eauto.\n  splits;try apply Hinit;auto.\n  eapply clt_step_good_clt;eauto.\n  apply Hinit;auto.\n  apply Hinit;auto.\n\n  inversion H10;tryfalse.\n  subst cst'0 tst C' C t p cst cst' m m'.\n  subst cst0.\n  exists  Cl' OO o Ms O Os.\n  splits;auto.\n  (eapply ht_starS;try eapply cltstep1_eq;eauto;try eapply ht_starO).\n  apply Hinit;auto.\n  destruct Cl' as (cn&(ken&ksn)).\n  assert (ksn=kstop ##(kstop##ksn)).\n  (simpl;auto).\n  rewrite H15.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  simpl.\n  simpl in Hgoodks.\n  eapply ltstep_goodks;eauto.\n  simpl in Hndymint.\n  eapply ltstep_n_dym_com_int_cd with(pc:=pc) (po:=po) (pi:=pi) (ip:=ip);eauto.\n  apply clt_step_good_clt in H10;auto.\n  unfold good_clt in *;destruct H10;simpl;auto.\n  apply Hinit;auto.\n  (*eapply ltstep_good_ret;eauto.*)\n  left.\n  (splits;auto).\n  splits;try apply Hinit;auto.\n  rewrite <- H15.\n  eapply clt_step_good_clt;eauto.\n  apply Hinit;auto.\n  apply Hinit;auto.\n \n  intros.\n  assert (o2=o''/\\cst=cst').\n  inverts H10;split;auto.\n  destruct H11;subst o'' cst'.\n  assert (ltstepev (pc, (po, pi, ip)) tid (c, (ke, ks)) cst o2 Cl' cst o2 ev) as Hlstepev;auto.\n\n  apply stepev_still_inos in H10;auto.\n  exists Cl' OO o Ms O Os.\n  splits;auto.\n  destruct cst as (D&F).\n  eapply htev_stepstar with (c':= (c, (ke, ks))) (c'':=Cl') (O':=OO);eauto.\n  apply ht_starO.\n\n  eapply cltstepev_eq;eauto.\n  apply ht_starO.\n  destruct Cl' as (cn&(ken&ksn)).\n  assert (ksn=kstop ##(kstop##ksn)).\n  simpl;auto.\n  rewrite H11.\n  apply CIH;auto;intros;tryfalse.\n\n  splits;auto.\n  simpl;simpl in Hgoodks.\n\n  eapply ltstepev_goodks;eauto.\n  simpl in Hndymint.\n  eapply ltstepev_n_dym_com_int_cd with(pc:=pc) (po:=po) (pi:=pi) (ip:=ip);eauto.\n\n  apply clt_stepev_good_clt in Hlstepev;auto.\n  unfold good_clt in *;destruct Hlstepev;simpl;auto.\n  apply Hinit;auto.\n  (*eapply ltstepev_good_ret;eauto.*)\n  left.\n  splits;auto.\n  split;try apply Hinit;auto.\n\n  eapply clt_stepev_good_clt;eauto.\n  apply Hinit;auto.\n  apply Hinit;auto.\n\n  intros.\n  assert (InitTaskSt lasrt tid (o, O) /\\ good_clt (c, (ke, ks)) pi) by auto.\n  destruct H11.\n  inverts H7.\n  simpl in H12.\n  destruct H12.\n  tryfalse.\n\n  intros.\n  exists O Os (c,(ke,ks)) OO.\n  splits;auto.\n  intros.\n  apply ht_starO.\n  apply Hinit;auto.\n  intros.\n  unfold IsEnd in H7.\n  apply htabtstar.\n  exists (c,(ke,ks)) cst OOO.\n  splits;auto.\n  apply ht_starO.\n  destruct cst.\n  destruct p.\n  eapply cltstep_eqabt;eauto.\n  intro. \n  unfolds in H16.\n  mytac.\n  subst c x3.\n  clear -Hndymint.\n  unfolds in Hndymint.\n  destruct Hndymint.\n  unfolds in H.\n  simpl in H.\n  false.\n  intro. \n  unfolds in H16.\n  mytac.\n  subst c x1.\n  clear -Hndymint.\n  unfolds in Hndymint.\n  destruct Hndymint.\n  unfolds in H.\n  simpl in H.\n  false.\n  intro. \n  unfolds in H16.\n  mytac.\n  subst c x0.\n  clear -Hndymint.\n  unfolds in Hndymint.\n  destruct Hndymint.\n  unfolds in H.\n  simpl in H.\n  false.\n\n  \n  unfolds.\n  intros.\n  intro.\n  inverts H16.\n  clear -Hndymint.\n  unfolds in Hndymint.\n  destruct Hndymint.\n  unfolds in H.\n  simpl in H.\n  false.\n\n  intros.\n  assert (InitTaskSt lasrt tid (o, O) /\\ good_clt (c, (ke, ks)) pi) by auto.\n  destruct H11.\n  inverts H7.\n  simpl in H12.\n  destruct H12.\n  tryfalse.\n\n  \n  intros.\n  assert (InitTaskSt lasrt tid (o, O) /\\ good_clt (c, (ke, ks)) pi) by auto.\n  destruct H11.\n  inverts H7.\n  simpl in H12.\n  destruct H12.\n  tryfalse.\n  \n  (*---------------------------------------------*)\n  destruct Hc2 as [Hc|Hc2].\n  destruct Hc as (f&vl&tl&s&d1&d2&ft&Hpf&Hc&Hke&Hch&Hkeh&Hks1&Hks2&Hninos). \n  subst.\n\n  destruct (tlmatch_dec' (List.rev tl) d1 vl) as [Hntlmatch | Htlmatch].\n  apply task_sim;intros;tryfalse.\n\n  eapply n_tlmatch_abt in Hntlmatch;eauto.\n  inversion Hntlmatch;subst.\n  destruct H11.\n  inversion H10;subst.\n  left.\n  exists Cl' o'' cst';eauto.\n  inversion H9;subst.\n  inversion H11;subst.\n  inversion H14;subst;tryfalse.\n  unfold IsEnd in H1.\n  destruct H1;tryfalse.\n\n  eapply htabtstar.\n  exists (curs (sfexec f vl tl), (kenil, ks)) cst OOO.\n  split.\n  apply ht_starO.\n\n  destruct A as ((B&CC)&sc).\n  assert (exists ab tl tp, B f = Some (ab,(tp,tl))/\\tlmatch tl d1).\n\n  eapply api_tlmatch;eauto.\n  destruct H15 as (ab&tl'&tpp&H21f&H22f).\n  assert (pc f = None) as Hpcnone.\n  unfold GoodClient in Hgoodclient.\n  destruct Hgoodclient.\n  assert (po f <> None).\n  intro X.\n  rewrite Hpf in X;tryfalse.\n  destruct H16.\n  apply H18;auto.\n  destruct cst.\n  destruct p.\n\n  eapply hn_tlmatch_abt;eauto.\n  intro H'.\n  destruct H'.\n  destruct Hntlmatch.\n  split.\n  subst tl'.\n  auto.\n  subst tl'.\n  eapply tl_vl_dl'';eauto.\n\n  (*-------------------------------*)\n  destruct Htlmatch as (Htlmatch).\n  apply task_sim.\n  intros.\n  inversion H10;tryfalse.\n  subst cst cst' p t C cst0 tst C' cst'0 o''.\n  destruct H13.\n  unfold InOS.\n  exists (curs (sfexec f vl tl)) kenil ks.\n  split;auto.\n  left.\n  inversion H11;subst po0 pi0.\n  exists f vl (ft, d1, d2, s) tl;split;auto. \n  apply pumerge_get;auto.\n  inversion H11.\n  subst cst0 tst C' t p pc0 po0 pi0 ip0 cst' tst'.\n  destruct o as (a&aux).\n  destruct a as (cmem&ir).\n  destruct cmem as (a&mem).\n  destruct a as (genv&lenv).\n  unfold joinm2 in H8.\n  destruct H8 as (o1&Hjoin1&Hjoin2).\n  unfold joinmem in Hjoin1.\n  destruct Hjoin1 as (GG&EE&M1&M2&ir0&ls&Heq&Ho0&Hmjoin).\n  inversion Heq;subst GG EE mem ir0 ls.\n  subst o1.\n  unfold joinmem in Hjoin2.\n  destruct Hjoin2 as (GG&EE&Mx&M3&ir0&ls&Heq'&Ho0'&Hmjoin').\n  inversion Heq';subst GG EE Mx ir0 ls.\n  subst o2.\n  exists (curs (sfexec f vl tl), (kenil, ks)) OO  (genv,(emp:env),M1,ir,aux) Ms O Os.\n  inversion H12.\n  inversion H21.\n  (inversion H23;tryfalse).\n  (inversion H23;tryfalse).\n  subst C0.\n  inversion H22; subst ks0 c. \n  subst.\n  inversion H41;subst f0 vl0 tl0.\n  inversion H29;subst ge le M.\n  splits;auto.\n  apply ht_starO.\n  unfold joinm2.\n  exists (genv, (emp:env), M2, ir, aux).\n  split;unfold joinmem.\n  (exists genv (emp:env) M1 M2 ir aux;splits;auto).\n  (exists genv (emp:env) M2 M3 ir aux;splits;auto).\n\n  eapply inv_substask_emple;eauto.\n  eapply CurLINV_ignore_int;eauto.\n\n  assert (kcall f s0 lenv ks1 = kstop## (kcall f s0 lenv kstop ## ks1)).\n  (simpl;auto).\n  rewrite H8.\n  assert (po f = Some (ft,d1,d2,s));auto.\n  apply pumerge_get with (pi:=pi) in Hpf.\n  rewrite Hpf in H31.\n  inversion H31;subst t d0 d3 s0.\n  assert (InitTaskSt lasrt tid (genv, lenv, M1, ir, aux, O)).\n  (eapply H3;eauto).\n  assert (snd (fst (get_smem (genv, lenv, M1, ir, aux)))=emp).\n\n  eapply init_emple.\n  eauto.\n  simpl in H16.\n  subst lenv.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  assert (kstop ## (kcall f s empenv kstop ## ks1) = kcall f s empenv ks1).\n  simpl;auto.\n  rewrite H16.\n  simpl in Hgoodks.\n  eapply ltstep_goodks;eauto.\n  simpl in Hndymint.\n  eapply ltstep_n_dym_com_int_cd with(pc:=pc) (po:=po) (pi:=pi) (ip:=ip);eauto.\n  (*eapply ltstep_good_ret;eauto.*)\n  right.\n  right.\n  left.\n  exists f vl  (revlcons d1 d2) vl.\n  exists s d1 d2 ft tl.\n  (splits;auto).\n  inversion H19.\n  subst f0 vlh tl0.\n  rewrite H16 in H14.\n  inversion H14;subst s0 d0 d3 ft0.\n  inversion H17;subst vl0 dl.\n  splits;auto.\n\n  apply good_dl_le_init';auto.\n  apply Hgoodpo in H16;auto. \n  destruct H16;auto.\n  exists dnil (nil:vallist) Aemp.\n  splits;auto.\n  intros.\n\n  apply InitAemp;auto.\n  destruct (H19 vl (revlcons d1 d2)).\n  auto.\n  (tryfalse).\n  (tryfalse).\n  (tryfalse).\n  (tryfalse).\n  (tryfalse).\n  (tryfalse).\n\n  (intros;tryfalse).\n  (intros;tryfalse).\n\n  intros.\n  inversion H10;tryfalse.\n  inversion H12.\n  (inversion H27;tryfalse).\n  (intros;tryfalse).\n  intros.\n  unfold IsEnd in H7;destruct H7;tryfalse.\n  intros.\n  (eapply fexec_abt_eq;eauto).\n  intros.\n  inverts H7.\n  intros;inverts H7.\n  (*-------------------------------------*)\n  destruct Hc2 as [Hc | Hc2].\n  destruct Hc as (f&vl&dl&vlh&s&d1&d2&ft&tl&Hpf&Hc&Hke&Hch&Hkeh&Hks1&Hks2&Hninos).\n  subst.\n  assert (kstop##(kcall f s empenv kstop##ks)=kcall f s empenv ks).\n  (simpl;auto).\n  rewrite H1.\n  lets Hst:H4 Hpf Hninos;eauto.\n  apply task_sim.\n  intros.\n\n  lets Hlstep: alloc_locality H8 H10;eauto.\n  destruct Hlstep as (o'&Hltstep').\n  destruct Hltstep' as (Hlstep'&Hjoin1&Heqwom).\n\n  apply alloc_trans with (ft:=ft) (d1:=d1) (d2:=d2) (s:=s) (vlh:=vlh) (O:=O) (f:=f) (lasrt:=lasrt)in Hlstep';auto.\n  Focus 2.\n  apply Hgoodpo in Hpf ;destruct Hpf;auto.\n  Focus 2.\n  destruct Hst as (Hst'&Hst''&Hgooddl&Hinitg&Hst''').\n  (auto).\n  destruct Hlstep'.\n  destruct H11.\n  exists (curs (sfexec f vlh tl), (kenil, ks)) OO o' Ms O Os.\n  splits;auto.\n  \n  subst cst'.\n  (apply ht_starO).\n\n  eapply emple_subs_inv;eauto.\n\n  eapply alloc_curlinv_hold with (o:=o);eauto.\n  destruct H12 as (dl''&vl''&p&dl'''&vl'''&Hcl'&Hdladd&Hvladd&Hbp&Hleneq&Hnoend&Hst').\n  subst Cl'.\n  assert (kcall f s empenv ks = kstop##(kcall f s empenv kstop ## ks)).\n  (simpl;auto).\n  rewrite H12.\n  apply CIH;auto;intros;tryfalse.\n  eapply alloc_curlinv_hold with (o:=o);eauto.\n  splits;auto.\n  right.\n  right.\n  left.\n  exists f vl'' dl'' vlh s d1.\n  exists d2 ft tl.\n  (splits;auto).\n  inversion H16;subst f0 vlh0 tl0.\n  inversion H14;subst vl0 dl0.\n  rewrite Hpf in H13;inversion H13;subst ft0 d0 d3 s0.\n  splits;destruct Hst;destruct H21;destruct H22 as (Hgooddl&H22);auto.\n\n  assert (good_dl_le dl o2).\n\n  apply join_eqe in H8.\n\n  eapply good_dl_le_care in H8;eauto.\n  apply good_dl_le_care with (o:= o'').\n  apply join_eqe in Hjoin1.\n  auto.\n\n  eapply good_dl_le_step' ;eauto.\n  apply Hgoodpo in Hpf ;destruct Hpf;auto.\n  destruct o as [[[[]]]].\n  unfold joinm2 in *.\n  destruct H8 as (o1&H8&H88).\n  destruct Hjoin1 as (o1'&Hjoin1&Hjoin2).\n  unfold joinmem in H8, H88, Hjoin1, Hjoin2.\n  do 6 destruct H8;destruct H8;subst.\n  inversion H8;subst.\n  destruct H88.\n  do 6 destruct H11.\n  destruct H23;subst o1.\n  destruct H24;subst o2.\n  inversion H11;subst.\n  destruct Hjoin1.\n  do 6 destruct H23;subst o'.\n  simpl.\n  simpl in Heqwom.\n  destruct Heqwom.\n  subst x.\n  destruct H22.\n  auto.\n  exists dl''' vl''' p.\n  (splits;auto).\n  intros.\n  assert (vl<>nil).\n\n  intro X.\n  subst vl.\n  inversion H10;tryfalse.\n  inversion H30;tryfalse.\n  inversion H53;tryfalse.\n  inversion H50;subst c.\n  inversion H52;tryfalse.\n  subst.\n  destruct Hnoend;auto.\n  inversion H30;tryfalse.\n  inversion H47;tryfalse.\n  inversion H56;tryfalse.\n  inversion H55;tryfalse.\n  subst c;inversion H53.\n  subst dl.\n  destruct Hnoend;auto.\n  apply Hleneq in H29;auto.\n  destruct (H16 vl'' dl'');auto.\n  destruct H11.\n  destruct H12 as (p&Hcl'&Hf&Hf'&Hbp&Hst').\n  subst cst' Cl' vl dl.\n\n  destruct Hst as (Htlmatch&Hleneq&Hgooddl&Hinitg&dl'&vl'&p'&Hffk&Hdl&Hvl&Hbp'&Hpre).\n  assert (vlh=vlh++nil).\n  (apply List.app_nil_end).\n  rewrite <- Hvl in H11 at 1.\n  apply List.app_inv_tail in H11.\n  subst vl'.\n  clear Hvl.\n \n  rewrite dl_add_nil_eq in Hdl.\n  subst dl'.\n\n  lets Hasrts:build_api_asrt H0 Hpf Hbp'.\n  eapply tl_vl_dl'';eauto.\n  destruct Hasrts as (pf&rf&ab&tt&Hhf&Hbpre&Hbret).\n  lets Hmsim:H Hhf Hbpre Hbret.\n  destruct Hmsim as (t'&d3&d4&s'&Hpf'&Hmsim).\n  rewrite Hpf in Hpf'.\n  inversion Hpf';subst t' d3 d4 s'.\n  clear Hpf'.\n  unfold MethSimAsrt in Hmsim.\n  destruct tt as (t'&tl').\n \n  lets Hteq:eq_tp H0 Hhf Hpf.\n  destruct Hteq;subst t'.\n  \n  lets Htleq:tlmatch_trans H12 Htlmatch.\n  subst tl'.\n  clear H12.\n\n  lets Hpp:bp_bpa H0 Hpf Hhf Hbpre Hbp';eauto.\n  apply Hpp in Hpre;eauto.\n\n  apply Hmsim in Hpre.\n\n  assert (o''=o2).\n  inversion H10;auto;tryfalse.\n  inversion H12;tryfalse.\n  inversion H22;tryfalse.\n  inversion H36;tryfalse.\n  inversion H35;tryfalse.\n  auto.\n  subst o''.\n\n  exists (curs (hapi_code (ab (rev vlh)) ), (kenil, ks)) OO o Ms O Os.\n  splits;auto.\n\n  destruct cst.\n  eapply ht_starS.\n  2:apply ht_starO.\n\n  eapply hapi_step;eauto.\n  destruct A as ((B&C)&sc).\n  eapply hapienter_step with (vl:=rev vlh);eauto.\n\n  rewrite <- tl_vl_rev_match.\n  auto.\n\n  rewrite List.rev_involutive.\n  rewrite List.rev_involutive.\n  auto.\n  assert (kcall f s empenv ks = kstop ## (kcall f s empenv kstop ##ks)).\n  simpl;auto.\n  rewrite H11.\n  apply CIH;auto;intros;tryfalse.\n\n  splits;auto.\n  simpl in Hndymint.\n  simpl;auto.\n  destruct Hndymint.\n  destruct H13.\n  splits;auto.\n  eapply goodstmt'_n_dym_com_s;eauto.\n  (*eapply ltstep_good_ret;eauto.*)\n\n  right.\n  right.\n  right.\n  left.\n  exists f s d1 d2 ft.\n  splits;auto.\n  intros.\n  intro X.\n  inversion X.\n  destruct Hmsim.\n  subst s.\n  simpl in H12.\n  inversion H12.\n  intros.\n  intro X.\n  destruct X.\n  inversion H12.\n  subst s.\n  destruct Hmsim.\n  simpl in H14;inversion H14.\n\n  rename Hpre into HoO.\n  unfold nilcont in HoO.\n  inversion H14;subst f0.\n  rewrite Hpf in H12;inversion H12;subst ft0 d0 d3 s0.\n  rewrite H18 in Hhf;inversion Hhf;subst ab0.\n  exists rf vlh (ab (rev vlh)).\n  splits;auto.\n  destruct Hmsim.\n  assert (kstop##kcall f s empenv kstop = kcall f s empenv kstop).\n  simpl;auto.\n  rewrite H22.\n\n  eapply funbody'_inos;eauto. \n  eauto.\n\n\n  clear -Hpf Hnoos.\n  simpl.\n  unfold no_call_api_os in Hnoos.\n  destructs Hnoos.\n  unfolds in H;apply H in Hpf;auto.\n\n  inversion H16.\n  destruct Hmsim;subst s;tryfalse.\n  intros.\n  inversion H10.\n  inversion H12.\n  inversion H27;tryfalse.\n  intros;tryfalse.\n  intros.\n  unfold IsEnd in H7.\n  destruct H7.\n  inversion H7.\n  intros.\n  assert (vl=nil\\/ exists i t dl', dl=dcons i t dl').\n  destruct vl.\n  left.\n  auto.\n  destruct Hst as (Hf1&Hf2&Hst).\n  destruct Hst as (Hgooddl&Hinitg&dl'&vl'&p&Hst1&Hst2&Hst3&Hst4).\n  right.\n  assert (v::vl<>nil).\n  auto.\n  apply Hst1 in H16.\n  destruct dl.\n  assert (length_eq vlh d1).\n\n  eapply tl_dl_vl_eq;eauto.\n  eapply tl_vl_match_leneq;eauto.\n  assert (~length_eq vl' dl').\n\n  eapply sub_len_neq;eauto.\n  destruct H18;auto.\n  exists i t dl;auto.\n\n  eapply tstep_alloc_nabt in H15;simpl;eauto.\n  (tryfalse).\n  destruct Hst as (Hst1&Hs2&Hst3&Hst).\n  apply join_eqe in H12.\n  eapply good_dl_le_care in H12;eauto.\n\n  intros.\n  inverts H7.\n  intros;inverts H7.\n  (*-----------------------------------*)\n  destruct Hc2 as [Hc|Hc2].\n  destruct Hc as (f&s&d1&d2&ft&Hpf&Hkeh&Hks2&Hnalloc&Hnfree&Hninos).\n  subst.\n  assert ( ks1 ## (kcall f s empenv kstop ## ks) = ks1 ## kcall f s empenv ks).\n  simpl;auto.\n  rewrite H1.\n  destruct A as ((B&C)&sc).\n  lets Hhf:api_tlmatch H0 Hpf.\n  destruct Hhf as (ab&tl&tp&Hhf&Htlmatch).\n\n  lets Hmsim': H5 Hpf Hnalloc Hninos ;auto.\n  lets Hmsim: Hmsim' Hhf.\n  clear Hmsim'.\n  constructors.\n  intros.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n\n  destruct (ret_dec c ke ks1 ).\n  destruct (retv_dec c ke ks1).\n  inversion Hmsim.\n  subst.\n\n  lets Hlosstep': tstep_to_osstep Hndymint H10 H11 H12 Hnalloc.\n  lets Hlosstep: Hlosstep' Hnfree Hinos.\n  clear Hlosstep'.\n  destruct Hlosstep as (c'&ke'&ks1'&H'&Hlosstep&Hc'&Hnalloc'&Hnfree').\n\n  eapply loststep_no_api_elim in Hlosstep;eauto.\n  subst cst'.\n  lets Hmsim':H13 H7 H8 H9 Hlosstep;eauto.\n  destruct Hmsim' as (gamma'&OO'&o'&Ms'&O'&Os'&Hhmstep&Hjoin'&HOjoin&Hinv&Hlinv'&Hmsim').\n  assert (satp (substaskst o' Ms') Os' (INV I)).\n  auto.\n\n  lets Htstep:osapi_lift' Hhmstep.\n  eexists.\n  exists OO' o' Ms' O' Os'.\n  splits;auto.\n  eauto.\n  subst Cl'.\n  assert (ks1'##(kcall f s empenv ks) = ks1' ## (kcall f s empenv kstop ## ks)).\n  simpl;auto.\n  rewrite H23.\n  apply CIH;auto;intros.\n  splits;auto.\n  eapply ltstep_goodks;eauto.\n  simpl in Hndymint.\n  eapply ltstep_n_dym_com_int_cd with(pc:=pc) (po:=po) (pi:=pi) (ip:=ip);eauto.\n  (*eapply ltstep_good_ret;eauto.*)\n  right.\n  right.\n  right.\n  left.\n  exists f s d1 d2 ft.\n  splits;auto.\n\n  inversion H28.\n  inversion H30.\n  inversion H29;subst f0.\n  rewrite Hpf in H24;inversion H24;subst ft0 d0 d3 s0.\n  subst. \n  tryfalse.\n  inversion H26;subst f0.\n  simpl in H30.\n  rewrite Hhf in H30;inversion H30;subst ab0.\n  subst tt.\n  exists R vlh gamma'.\n  splits;auto.\n\n  subst s0.\n\n  eapply inos_step_still with (ks1:=ks1);eauto.\n  destruct o2 as [[[[]]]].\n\n  lets Hx:ltstep_eqg e H10.\n  assert ((get_genv (get_smem o)) = (get_genv (get_smem o'))).\n  clear -Hx Hjoin' H8.\n  unfold joinm2 in *;mytac.\n  unfold joinmem in *.\n  mytac.\n  simpl in Hx.\n  simpl.\n  symmetry.\n  apply Hx;auto.\n  rewrite <- H31.\n  auto.\n  eapply no_call_api_loststep_still;eauto.\n  eapply loststep_no_api_local;eauto.\n\n  destruct  Hnfree' with al (v).\n  split;auto.\n\n  (*----------------------------*)\n  destruct H12 as (v&ksx&Hc&Hcallcont&Hintcont).\n  inversion Hc;subst c ke ks1;clear Hc.\n  inversion Hmsim.\n  subst.\n\n  lets Hmsim': H16 Hcallcont Hintcont H9;eauto.\n\n  apply disj_sym.\n  clear -H8.\n  destruct o as [[[[]]]].\n  unfolds.\n  unfolds in H8;mytac.\n  unfold joinmem in *;mytac.\n  unfold getmem;simpl.\n  geat.\n\n  destruct Hmsim' as (gamma'&OO'& O'&Os'&Hhmstep&HOjoin'&Hinv'&Hlinv'&Hret).\n  exists (curs (sskip (Some v)),(kenil,ks)) OO' o Ms O' Os'.\n\n  assert (o''=o2/\\cst'=cst/\\ Cl' = (curs (sfree (getaddr (snd (fst (get_smem o2)))) (Some v)),(kenil,ksx ## kcall f s empenv ks))).\n\n  eapply retv_step;eauto.\n  destruct H21 as (H227&H228&H229);subst o'' cst' Cl'.\n  splits;auto.\n\n  destruct cst.\n  lets Hhtstep: osapi_lift' Hhmstep.\n  eauto.\n\n  Lemma hret_spec:\n    forall (o : taskst) (O : osabst) (ab : osapi) (abs : absop) \n           (R : retasrt) (vl : vallist) (po : progunit) v \n           (f : fid) G lasrt t,\n      Some R = BuildRetA po f ab vl G lasrt t init_lg->\n      (o, O, abs) |= R v ->\n      abs = spec_done v.\n  Proof.\n    intros.\n    unfolds in H.\n    destruct (po f);tryfalse.\n    destruct f0.\n    destruct p.\n    destruct p.\n    destruct (buildq (revlcons d0 d));tryfalse.\n    inverts H.\n    destruct H0.\n    destruct H0.\n    mytac.\n    simpl in H4.\n    mytac.\n  Qed.\n  \n  lets Hx:hret_spec Hr Hret.\n  subst gamma'.\n\n  eapply htstepstar_compose_tail;eauto.\n  eapply hapi_step;eauto.\n  eapply hapiexit_step;eauto.\n  assert (ksx ## kcall f s empenv ks = ksx ## (kcall f s empenv kstop ## ks)).\n  simpl;auto.\n  rewrite H21.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  (*eapply ltstep_good_ret;eauto.*)\n  right.\n  right.\n  right.\n  right.\n  exists (getaddr (snd (fst (get_smem o2)))). \n  exists f s d1 d2 ft ( Some v).\n  splits;auto.\n  destruct (H26 (getaddr (snd (fst (get_smem o2)))) (Some v)).\n  splits;auto.\n  inversion H24;subst f0 s0.\n  inversion H26;subst al v0.\n  assert ((snd (fst (get_smem o2)))=(snd (fst (get_smem o)))).\n  assert (TStWoMemEq o o2).\n\n  eapply join_tst_wo_mem_eq;eauto.\n  unfold TStWoMemEq in H30.\n  unfold get_smem.\n  destruct o as [[[[]]]].\n  destruct o2 as [[[[]]]].\n  simpl.\n  mytac.\n  \n  rewrite H30.\n\n  lets Hrvspec:retv_spec Hr Hret.\n  destruct Hrvspec.\n  destruct H31.\n  eexists;splits;eauto.\n\n  (*------------------*)\n\n  destruct H11 as (Hc&Hcallcont&Hintcont).\n  inversion Hc.\n  subst c ke;clear Hc.\n  inversion Hmsim.\n  subst.\n  lets Hmsim': H14 Hcallcont Hintcont H9;eauto. \n  clear -H8.\n  unfolds.\n  unfold joinm2 in H8.\n  mytac;unfold joinmem in *.\n  mytac.\n  unfold getmem.\n  simpl.\n  geat.\n  \n  destruct Hmsim' as (gamma'&OO'&O'&Os'&Hhmstep&HOjoin'&Hinv'&Hlinv'&Hret).\n  exists (SKIP,(kenil,ks)) OO' o Ms O' Os'.\n  assert (o''=o2/\\cst'=cst/\\ Cl' = (curs (sfree (getaddr (snd (fst (get_smem o2))) )None ),(kenil,ks1 ## kcall f s empenv ks))).\n\n  eapply ret_step;eauto.\n  destruct H20 as (H227&H228&H229);subst o'' cst' Cl'.\n  splits;auto.\n \n  lets Hhtstep: osapi_lift' Hhmstep.\n  lets Hx:hret_spec Hr Hret.\n  subst gamma'.\n  eapply htstepstar_compose_tail;eauto.\n  eapply hapi_step;eauto.\n  eapply hapiexit_step;eauto.\n  assert (ks1 ## kcall f s empenv ks = ks1 ## (kcall f s empenv kstop ## ks)).\n  simpl;auto.\n  rewrite H20.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  right.\n  right.\n  right.\n  right.\n  exists (getaddr (snd (fst (get_smem o2)))). \n  exists f s d1 d2 ft (None: option val).\n  splits;auto.\n  destruct (H25 (getaddr (snd (fst (get_smem o2)))) None).\n  splits;auto.\n  inversion H23;subst f0 s0.\n  inversion H25;subst al.\n  assert ((snd (fst (get_smem o2)))=(snd (fst (get_smem o)))).\n  assert (TStWoMemEq o o2).\n  eapply join_tst_wo_mem_eq;eauto.\n  unfold TStWoMemEq in H29.\n  unfold get_smem.\n  destruct o.\n  destruct p.\n  destruct s0.\n  destruct p.\n  destruct o2.\n  destruct p.\n  destruct s0.\n  destruct p.\n  simpl.\n  mytac.\n  rewrite H29.\n\n  lets Hrvspec:ret_spec Hr Hret.\n  destruct Hrvspec.\n  destruct H30.\n  eexists;splits;eauto.\n  (*-----------------------------------------------*)\n\n  intros.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n\n  lets Habt:tstepev_osstepabt H10.\n  destruct Habt.\n  eapply H17 with (Ms:=Ms)  in H7;eauto.\n  destruct H7;eauto.\n  unfolds;geat.\n  (*-------------------------------------------*)\n  intros.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n  inversion H7;subst c ke ks0.\n  lets HH: H12 H8 H10;eauto.\n  destruct HH as (gamma'&sleft&OO'&ol&Mc&O'&Os'&Ol&Oc&Hgamma&Hhmstep&Hmjoin&Hojoin'&Hojoin&Hinv'&Hswinv&Hlinv'&Hmsim').\n  subst.\n  exists (curs (hapi_code (spec_seq sched sleft)),(kenil,ks)) sleft (kenil, ks).\n  exists OO' Mc ol O' Os' Ol.\n  exists Oc. \n\n  splits;eauto.\n  intros.\n  eapply osapi_lift';eauto.\n  splits;auto.\n  destruct Hmsim';rename H20 into Hmsim'.\n  left.\n  destruct Hmsim' as (Hswpre&Hmsim').\n  splits;unfold getsched;auto.\n  \n  intros;eauto.\n  lets Hmsim'':Hmsim' H20 H21 H22.\n  assert (ks1##kcall f s empenv ks = (ks1 ## (kcall f s empenv kstop ## ks))).\n  simpl;auto.\n  rewrite H23.\n  apply CIH;auto;intros;tryfalse.\n  destruct o as [[[[]]]].\n  simpl substaskst in H20.\n  destruct ol as [[[[]]]].\n  unfolds in Hmjoin;mytac.\n  destruct Hlinv' with (aop:=spec_done None).\n  eapply joinmem_swinv_linv;eauto.  \n  splits;auto.\n  right.\n  right.\n  right.\n  left.\n  exists f s d1 d2 ft.\n  splits;auto.\n  intros.\n  intro X.\n  destruct X.\n  tryfalse.\n  inversion H26;subst f0 s0.\n  rewrite Hpf in H24;inversion H24;subst ft0 d0 d3.\n  simpl in H30.\n  rewrite Hhf in H30.\n  inversion H30;subst ab0 tt.\n  clear H24 H30 H26.\n  exists R vlh sleft.\n  splits;auto.\n\n  eapply inos_sw_still;eauto.\n  assert ((get_genv (get_smem o)) = (get_genv (get_smem o'))).\n  clear - Hmjoin H21.\n  unfold joinmem in *.\n  mytac.\n  simpl;auto.\n  rewrite <- H24;auto.\n\n  (*--------------*)\n  right.\n  unfold getsched.\n  simpl snd in *;auto.\n\n  (*---------------------------------*)\n  intros.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n  unfold IsEnd in H7.\n  destruct H7 as (v&Hcd).\n  inversion Hcd;tryfalse.\n  unfold AddKsToTail in H22.\n  destruct ks1;tryfalse.\n\n  (*---------------------------------*)\n  intros.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n  assert (disjoint O Os).\n  unfolds;eauto.\n  lets Habt: H22 H11 H12 H25;eauto.\n  Focus 2.\n\n  eapply nabt_lift in Habt;eauto. \n  destruct Habt;eauto.\n\n  unfold notabort.\n  splits;eauto.\n  \n  unfold IsSwitch.\n  intro X.\n  destruct H8.\n  destruct X as (x0&ks0&X).\n  exists x0 (ks1 ## kcall f s empenv ks).\n  inversion X;subst c ke.\n  auto.\n  intro X.\n  unfold IsEnd in X.\n  destruct X as (v&X).\n  assert (disjoint (getmem o) Ms).\n  clear -H12.\n  unfold joinm2 in *.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  unfold getmem.\n  unfold disjoint;simpl.\n  geat.\n\n  lets XX: H18 X H11 H26 H13;eauto. \n  destruct XX as (gamma'&OO'&O'&Os'&XX1&XX2&XX3&XX4).\n  unfold retfalse in XX4.\n  unfold sat in XX4.\n  destruct XX4;false.\n\n  intro X.\n\n  eapply isret_nabt in X;destruct X;eauto.\n  intro X.\n  eapply isrete_nabt in X;destruct X;eauto.\n  intro X.\n  unfold IsIRet in X.\n  destruct X as (ks0&X&XX).\n  assert (disjoint (getmem o) Ms).\n  clear -H12.\n  unfold joinm2 in *.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  unfold getmem.\n  unfold disjoint;simpl.\n  geat.\n  destruct XX.\n  lets XXX:H21 X H28 H27 H26 H13;eauto.\n  mytac.\n  simpl in H33;false.\n\n  unfold IsStkInit in *.\n  intro X.\n  destruct H9.\n  destruct X as (e1&e2&e3&ks0&X).\n  exists e1 e2 e3 (ks1 ## kcall f s empenv ks).\n  inversion X;subst c ke.\n  auto.\n\n  unfold IsStkFree in *.\n  intro X.\n  destruct H10.\n  destruct X as (e&ks0&X).\n  exists e (ks1 ## kcall f s empenv ks).\n  inversion X;subst c ke.\n  auto.\n\n  (*--------------------------------*)\n  intros.\n  inverts H7.\n  subst.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n  lets Hx:H17 H8 H9 H10;eauto.\n\n  destruct Hx as (gamma'&v1&v2&t'&pri&sleft&OO'&OO''&ol&Mcre&O'&Os'&Ol&Ocre&Hx).\n  mytac.\n  eexists.\n  exists v1 v2 t' pri sleft (kenil,ks).\n  exists OO' OO'' ol Mcre O' Os'.\n  exists Ol Ocre.\n  splits;eauto.\n  intros.\n  eapply osapi_lift';eauto.\n  splits;eauto.\n  assert (ks1##kcall f s empenv ks = (ks1 ## (kcall f s empenv kstop ## ks))).\n  simpl;auto.\n  rewrite H19.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  right.\n  right.\n  right.\n  left.\n  do 5 eexists;splits;eauto.\n  intros.\n  intro.\n  destruct H32;tryfalse.\n  do 3 eexists.\n  splits;eauto.\n\n  inverts H34.\n  rewrite H32 in Hpf;inverts Hpf.\n  eapply inos_stkinit_still;eauto.\n  inverts H34.\n  simpl in H38;rewrite H38 in Hhf;inverts Hhf;eauto.\n  assert ((get_genv (get_smem ol)) = (get_genv (get_smem o))).\n  clear -H25.\n  destruct o as [[[[]]]].\n  unfold joinmem in H25.\n  simpl in H25;mytac.\n  simpl;auto.\n  rewrite H34;eauto.\n  (*---------------------------*)\n  intros.\n  inverts H7.\n  destruct Hmsim as (R&vlh&AC&Hinos&Hmap&Hr&Hnocallapi&Hmsim).\n  inversion Hmsim.\n  subst.\n  lets Hx:H18 H8 H9 H10;eauto.\n  destruct Hx as (gamma'&pri&sleft&t'&OO'&OO''&O'&Os'&Hx).\n  mytac.\n  eexists.\n  exists pri sleft (kenil,ks) t' OO' OO''.\n  exists O' Os'.\n  splits;eauto.\n  intros.\n  eapply osapi_lift';eauto.\n  destruct H22.\n  left.\n  mytac;auto.\n  assert (ks1##kcall f s empenv ks = (ks1 ## (kcall f s empenv kstop ## ks))).\n  simpl;auto.\n  rewrite H26.\n  apply CIH;auto;intros;tryfalse.\n  splits;auto.\n  right.\n  right.\n  right.\n  left.\n  do 5 eexists;splits;eauto.\n  intros.\n  intro.\n  destruct H27;tryfalse.\n  do 3 eexists.\n  splits;eauto.\n  inverts H29;rewrite H27 in Hpf;inverts Hpf.\n  eapply inos_stkfree_still;eauto.\n  inverts H29.\n  simpl in H33;rewrite H33 in Hhf;inverts Hhf.\n  eauto.\n\n  mytac.\n  right.\n  splits;auto.\n  intros.\n  lets Hx:H25 H26 H27 H28.\n  assert (ks1##kcall f s empenv ks = (ks1 ## (kcall f s empenv kstop ## ks))).\n  simpl;auto.\n  rewrite H29.\n  apply CIH;auto;intros;tryfalse.\n  eapply join_satp_local_inv;eauto.\n  splits;auto.\n  right.\n  right.\n  right.\n  left.\n  do 5 eexists;splits;eauto.\n  intros.\n  intro.\n  destruct H30;tryfalse.\n  do 3 eexists;splits;eauto.\n  inverts H32;rewrite H30 in Hpf;inverts Hpf.\n  eapply inos_stkfree_still;eauto.\n  inverts H32.\n  simpl in H36;rewrite H36 in Hhf;inverts Hhf.\n  assert ((get_genv (get_smem o')) = (get_genv (get_smem o))).\n  clear -H27.\n  destruct o as [[[[]]]].\n  unfolds in H27.\n  mytac;simpl;auto.\n  rewrite H32.\n  eauto.\n  (*------------------------------------------------*)\n  destruct Hc2 as (al&f&s&d1&d2&ft&v&Hpf&Hkeh&Hks2&Hke&Hc&Hcallcont&Hintcont&Hninos).\n  subst keh ks2 c ke.\n  lets Hfree: H6 Hpf Hninos;eauto.\n  assert (ks1 ## (kcall f s empenv kstop ## ks)= ks1 ## kcall f s empenv ks).\n  simpl;auto.\n  rewrite H1.\n  clear H1.\n  destruct Hfree as (M&Hf1&Hf2&Hf3&Hf4).\n  subst ch.\n  apply task_sim.\n  intros.\n\n  assert (ltstep (pc, (po, pi, ip)) tid\n          (curs (sfree al v), (kenil, ks1 ## kcall f s empenv ks)) cst o2 Cl'\n          cst' o'') as Hgg by auto.\n\n  apply free_step with (lasrt:=lasrt) (o:=o) (O:=O) (Ms:=Ms) (M:=M) (Mf:=Mf) (d1:=d1) (d2:=d2) (ft:=ft) in H9;auto.\n  destruct H9 as [Hfree | Hfree'].\n\n  assert ( o''= emple_tst o2 /\\ cst'= cst /\\ Cl' = (curs (sskip v), (kenil,ks))/\\freels nil (get_mem (get_smem o)) M);auto.\n  destruct H9;destruct H10;destruct H11;subst o'' cst' Cl'.\n  exists (curs (sskip v),(kenil,ks)) OO (emple_tst o) Ms O Os.\n  splits;auto.\n  apply ht_starO.\n  clear -H7.\n  destruct o as [[[[]]]];unfold joinm2 in *.\n  destruct H7.\n  exists (emple_tst x).\n  unfold joinmem in *;mytac.\n  simpl.\n  do 6 eexists;simpl;splits;eauto.\n  do 6 eexists;simpl;splits;eauto.\n  \n  destruct o as [[[[]]]].\n  unfold emple_tst.\n  eapply inv_ncare_le;eauto.\n  destruct o as [[[[]]]].\n  unfold emple_tst.\n  eapply CurLINV_ignore_int;eauto.\n  \n  assert (ks =kstop ## (kstop ##ks)).\n  simpl;auto.\n  rewrite H9.\n  apply CIH;auto;intros;tryfalse.\n\n  \n  destruct o as [[[[]]]].\n  unfold emple_tst.\n  eapply CurLINV_ignore_int;eauto.\n  splits;auto.\n  simpl.\n  simpl in Hgoodks.\n\n  eapply fun_goodks;eauto.\n  simpl.\n  simpl in Hndymint.\n  destruct Hndymint.\n  split;auto.\n  eapply n_dym_ks_call;eauto.\n\n  left.\n  rewrite <- H9.\n  splits;auto.\n\n  apply inos_lift;auto.\n  inverts H12.\n  destruct o as [[[[]]]].\n  simpl in Hf2.\n  simpl emple_tst;splits;auto.\n\n  (*Guarded.*)\n  destruct Hfree' as (o'&al'&Hjoin&Hcst'&Hcl'&Hfreels'&Hinit').\n  subst cst' Cl'.\n  exists (curs (sskip v),(kenil,ks)) OO o' Ms O Os.\n  splits;auto.\n  apply ht_starO.\n  destruct o,o'.\n  destruct p,p0.\n  destruct s0,s1.\n  destruct p,p0.\n  simpl in Hinit',Hf2.\n  unfold InitTaskSt in *.\n  assert (i=empisr /\\ l = (true, nil, nil) /\\ i0=empisr /\\ l0=(true, nil, nil)).\n  clear -Hinit' Hf2.\n  destruct Hf2, Hinit'.\n  unfold satp in H.\n  lets Hx:H (spec_done None).\n  lets Hy:H1 (spec_done None).\n  destruct l as [[]].\n  destruct l0 as [[]].\n  simpl in Hx.\n  mytac;auto.\n  simpl in Hy;mytac;auto.\n  simpl in Hy;mytac;auto.\n  mytac.\n  clear -Hgg Hjoin H1 H7.\n  simpl in H1;simpl.\n  destruct o2 as [[[[]]]].\n  destruct o'' as [[[[]]]].\n  lets Hx:ltstep_eqg Hgg.\n  simpl in Hx.\n  assert (e3=e3) by auto.\n  apply Hx in H.\n  subst.\n  unfold joinm2 in *.\n  unfold joinmem in *.\n  mytac.  \n  intros;eapply inv_ncare_le;eauto.\n\n  \n  eapply free_curlinv_still;eauto.\n \n  assert (ks1 ## kcall f s empenv ks = ks1 ## (kcall f s empenv kstop ## ks)).\n  simpl;auto.\n  rewrite H9.\n  clear H9.\n  apply CIH;auto;intros;tryfalse.\n  eapply free_curlinv_still;eauto.\n  splits;auto.\n  right.\n  right.\n  right.\n  right.\n  exists al' f s d1 d2 ft.\n  exists v.\n  splits;auto.\n  destruct (H13 al' v).\n  splits;auto.\n  inversion H13;subst al0 v0.\n  exists M.\n  splits;auto.\n\n  intros;tryfalse.\n  inversion H9;subst;tryfalse.\n  inversion H11;subst;tryfalse.\n  inversion H14;subst;tryfalse.\n  intros;tryfalse.\n  intros.\n  unfold IsEnd in H1.\n  destruct H1.\n  inversion H1.\n  intros.\n\n  lets Hnabt: free_nabt Hcallcont Hintcont Hpf H11 Hf1.\n  destruct Hnabt.\n  eauto.\n  intros;tryfalse.\n  intros;tryfalse.\nQed.\n\n\nLemma SmCTaskSim:\n  forall pc OS1 (A:osspec) lasrt I o O t C,\n    no_fun_same (get_afun OS1) (get_ifun OS1) ->\n    (*good_ret_funs pc (get_afun OS1) (get_ifun OS1) ->*)\n    no_call_api_os (get_afun OS1) (get_ifun OS1) (get_lint OS1) ->\n    (forall f t d1 d2 s, (fst (fst OS1)) f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall f t d1 d2 s, (snd (fst OS1)) f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (\n      forall (f:fid) ab vl p r ft G tid, \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg->\n        Some r = BuildRetA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg->\n        (\n          exists  t d1 d2 s,\n            (fst (fst OS1)) f = Some (t, d1, d2, s)/\\ GoodStmt' s/\\\n            MethSimAsrt (snd (fst OS1)) (snd A) lasrt I r Afalse p s Afalse tid\n        )\n    ) -> \n    (GoodClient pc (fst (fst OS1)) (snd (fst OS1))/\\eqdomOS OS1 A) ->\n    InitTaskSt lasrt t (pair o O) ->\n    (exists s, C= nilcont s /\\ GoodStmt s (snd (fst OS1)) /\\ True (*/\\ good_retef_stmt s kstop*)) ->\n    TaskSim (pc, OS1) C o ( pc, A) C O lasrt I (InitTaskSt lasrt t) t.\nProof.\n  introv Hnofunsame.\n  (*introv Hgoodret.*)\n  introv Hnoos.\n  introv Hgoodpo.\n  intro Hgoodpi.\n  intros.\n  destruct H2.\n  destruct H2.\n  subst C.\n  unfold nilcont.\n  assert (kstop= kstop ##(kstop##kstop)).\n  simpl;auto.\n  rewrite H2 at 1.\n  destruct OS1 as ((po&pi)&ip).\n  simpl in Hgoodpo.\n  apply SmCTaskSim';auto;intros;subst;tryfalse.\n  unfolds in H1.\n  destruct H1.\n  unfold CurLINV.\n  exists init_lg.\n  lets Hx:H1 aop.\n  sep auto.\n  splits;auto.\n  destruct H0;auto.\n  destruct H0.\n  simpl in H0.\n  auto.\n  simpl in H3.\n  destruct H3. \n  simpl.\n  auto.\n  simpl;split;auto.\n  destruct H3.\n  eapply goodstmt_n_dym_com_s;eauto.\n  simpl;auto.\n\n  left.\n  splits;auto.\n  unfold InOS.\n  intro X.\n  destruct X as (c&ke&ks&X&XX).\n  inversion X;subst c ke ks.\n  destruct XX.\n  destruct H4 as (f&vl&fc&tl&H4).\n  destruct H4.\n  inversion H4.\n  subst x.\n  simpl in H3.\n  destruct H3.\n  inversion H3.\n  destruct H4.\n  destruct H4 as (f&le&ks'&to&d1&d2&s&s'&HX&HXX).\n  simpl in HX.\n  inversion HX.\n  simpl in H4.\n  destruct H4.\n  auto.\n  splits;auto.\n\n  unfold good_clt;split;simpl;auto.\n  apply Goodstmt_good_clt_stmt.\n  destruct H3;simpl in H3.\n  auto.\nQed.\n\nLemma GoodP_to_S: forall p po pi f a b c s, GoodClient p po pi-> p f = Some (a,b,c,s)-> GoodStmt s pi. \nProof.\n  unfold GoodClient.\n  intros.\n  eapply H;eauto.\nQed.\n\nLemma projs_steq_projs:\n  forall Sl S' t' t'0 or ge le ir m ir' i si,\n    t'0 <> t' ->\n    projS Sl t' = Some (ge, le, m, ir, (true, si, nil)) ->\n    projS S' t' = Some (ge, empenv, m, ir', (false, i :: si, nil)) ->\n    Steq Sl S' t' ->\n    projS Sl t'0 = Some or -> projS S' t'0 = Some (fst (fst or), snd (fst S'), snd or).\nProof.\n  unfold tid.\n  introv Htneq.\n  intros.\n  destruct Sl.\n  destruct p.\n  destruct S'.\n  destruct p.\n  unfold projS in *.\n  unfold Steq in H1.\n  destruct H1.\n  unfold Dteq in H1.\n  unfold Piteq in H3.\n  destruct c.\n  destruct p.\n  destruct c0.\n  destruct p.\n  remember (projD (e0, c0, m1) t'0) as X.\n  unfold tid in *.\n  destruct X;tryfalse.\n  remember (get l0 t'0) as Y.\n  destruct Y;tryfalse.\n  remember (projD (e, c, m0) t') as XX.\n  unfold tid in *.\n  destruct XX;tryfalse.\n  remember (get l t') as YY.\n  destruct YY;tryfalse.\n  remember (projD (e, c, m0) t'0) as XXX.\n  destruct XXX;tryfalse.\n  remember (get l t'0) as YYY.\n  destruct YYY;tryfalse.\n  inverts H.\n  inverts H2.\n  simpl.\n  remember (projD (e0, c0, m1) t') as Z.\n  destruct Z;tryfalse.\n  remember (get l0 t') as ZZ.\n  destruct ZZ;tryfalse.\n  lets H11: H1 Htneq.\n  clear H1.\n  lets H13 : H3 Htneq.\n  clear H3.\n  inverts H0.\n  unfold projD in *.\n  unfold tid in *.\n  rewrite H11 in *.\n  rewrite <- HeqYYY in *.\n  rewrite <- HeqY in *.\n  inverts H13.\n  rewrite <- H11 in *.\n  destruct (get c t');tryfalse.\n  inverts HeqXX.\n  destruct (get c0 t');tryfalse.\n  inverts HeqZ.\n  destruct (get c t'0);tryfalse.\n  rewrite <-HeqXXX in HeqX.\n  inverts HeqX.\n  auto.\n  lets H11: H1 Htneq.\n  clear H1.\n  lets H13 : H3 Htneq.\n  clear H3.\n  rewrite <- H13 in *.\n  destruct (projD (e, c, m0) t'0);tryfalse.\n  destruct (get l t'0);tryfalse.\n  lets H11: H1 Htneq.\n  clear H1.\n  lets H13 : H3 Htneq.\n  clear H3.\n  unfold projD in *.\n  unfold tid in *.\n  rewrite <- H11 in *.\n  destruct (get c t'0);tryfalse.\nQed.\n\n\n\n\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n(*******************************************************)\n\n\n\nLemma tasks_set_get_neq: forall T t t' a, t<>t' -> TasksMod.get (TasksMod.set T t a) t' =  TasksMod.get T t'.\nProof.\n  intros.\n  apply TasksMod.set_a_get_a'.\n  apply tidspec.neq_beq_false.\n  apply H.\nQed.\n\nLemma eqdomTO_setT :\n  forall T T' t C C' O,\n    TasksMod.get T t = Some C -> eqdomTO T O ->\n    TasksMod.set T t C' = T' ->\n    eqdomTO T' O.\nProof.\n  intros.\n  unfold eqdomTO in *.\n  mytac.\n  eexists; split; eauto.\n  intros.\n  pose proof H2 t0; destruct H1.\n  destruct(tidspec.beq t t0) eqn : eq1.\n  pose proof tidspec.beq_true_eq t t0 eq1; substs.\n  assert(exists x0, TcbMod.get x t0 = Some x0) by eauto.\n  apply H3 in H4.\n  destruct H4.\n  exists C'.\n  apply TasksMod.set_a_get_a;auto.\n  rewrite TasksMod.set_a_get_a';auto.\n  apply H3.\n  eexists;eauto.\nQed.\n\n\nLemma change_tstm_trans': forall o M Ms, substaskst (substaskst o M) Ms = substaskst o Ms.\nProof.\n  unfold substaskst.\n  intros.\n  destruct o.\n  destruct p.\n  destruct s.\n  destruct p.\n  reflexivity.\nQed.\n\n\nLemma repl_change_tstm_trans: forall o M Ms, substaskst (substaskst o M) Ms = substaskst o Ms.\nProof.\n  apply change_tstm_trans'.\nQed.\n\n\n\n  \n\nLemma tsimtopsim: \n  forall pl Tl Sl ph Th O cst t,\n    get O curtid = Some (oscurt t)->\n    (\n      exists (pc:progunit) (A:osspec) po pi ip Tm To Ol Os Ms Ml I lasrt ,\n        no_fun_same po pi/\\\n        True /\\\n        (*good_ret_funs pc po pi /\\*)\n        no_call_api_os po pi ip /\\ \n        (forall f t d1 d2 s, po f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) /\\ (forall f t d1 d2 s, pi f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) /\\\n        pl = (pc, ( po, pi, ip)) /\\ ph = (pc, A) /\\ (GoodClient pc po pi/\\ True /\\ good_t_ks pl Tl /\\ good_is_S Sl/\\GoodI I (snd A) lasrt(*/\\eqdomcstO cst O*) ) \n\n        /\\\n\n        join Ml Ms (snd (fst (fst Sl))) \n\n        /\\\n\n        partM Ml Tl Tm\n\n        /\\               \n   \n        join Ol Os O /\\\n\n        partO Ol Tl To\n\n        /\\\n\n        (exists o o', projS Sl t = Some o /\\ substaskst o Ms = o' /\\(forall ab, sat ((pair o' Os),ab) (INV I) )) \n        \n        /\\\n        \n        (\n          exists o o' Mc Oc Cl Ch,\n            TMSpecMod.maps_to Tm t Mc /\\\n            TOSpecMod.maps_to To t Oc /\\\n            projS Sl t = Some o /\\ substaskst o Mc = o' /\\ \n            get Th t = Some Ch /\\ get Tl t = Some Cl /\\\n            satp o' Oc (CurLINV lasrt t) /\\ \n            TaskSim pl Cl o' ph Ch Oc lasrt I (InitTaskSt lasrt t) t\n        )\n          \n        /\\\n\n        (\n          forall t' Ch,\n            ~(t'=t) ->\n            get Th t' = Some Ch ->\n            task_no_dead O t' ->\n            (\n              exists o M' Cl O', \n                TMSpecMod.maps_to Tm t' M' /\\\n                TOSpecMod.maps_to To t' O' /\\\n                projS Sl t' = Some o /\\\n                satp (substaskst o M') O' (EX lg, LINV lasrt t' lg ** Atrue) /\\\n                get Tl t' = Some Cl/\\\n                (\n                  forall Mr Or, \n                    (forall ab, sat ((pair (RdyChange (substaskst o Mr)) Or),ab) (RDYINV I t'))/\\ \n                    disjoint Mr M' /\\\n                    disjoint Or O' ->\n                    (\n                      exists M'',\n                        M''= merge Mr M' /\\ \n                        TaskSim pl Cl (RdyChange (substaskst o M'')) ph Ch (merge Or O') lasrt I (InitTaskSt lasrt t') t'\n                    )\n                )                 \n                  \n            )\n        )\n\n       /\\ eqdomTO Th O /\\  eqdomOS (po, pi, ip) A\n          \n       /\\ \n       (\n          forall (f:fid) ab vl p r ft G tid, \n            (fst (fst A)) f = Some (ab,ft )->\n            Some p = BuildPreA po f (ab,ft) vl G lasrt tid init_lg->\n            Some r = BuildRetA po f (ab,ft) vl G lasrt tid init_lg->\n            (\n              exists t d1 d2 s,\n                po f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n                 MethSimAsrt pi (snd A) lasrt I r Afalse p s Afalse tid\n            )\n       )\n       /\\ \n       (\n          forall (i:hid) ispec isrreg si G lg tid, \n            (snd (fst A)) i = Some ispec ->\n            (\n              exists (s:stmts) p r,\n                ip i = Some s /\\ \n                p = ipreasrt i isrreg si (ispec ) I G lasrt tid lg/\\ \n                r = iretasrt i isrreg si I G lasrt tid lg /\\\n                MethSimAsrt pi (snd A) lasrt I retfalse r p s Afalse tid\n        )\n       )\n    )\n->\nProgSim pl Tl Sl ph Th O cst t.   \nProof.\n  cofix CIH.\n  introv Hosabsttid.\n  intros.\n  destruct H as (pc & A & po & pi & ip & Tm & To & Ol & Os &Ms & Ml & I & lasrt & H).\n  destruct H as (Hnofunsame&Hgoodret&Hnocallapi&Hgoodpo&Hgoodpi &  H).\n  destruct H as (Hpl & Hph &Hgoodpc& Hmjoin & Hmpart & HOjoin \n                 & HOpart & Hinv & Hcsim & Hrsim & Heqdomto & Heqdomos\n                 & Hapimsem & Hintmsem).\n  destruct Hgoodpc as (Hgoodpc&Hgoodg&Hgoodks&Hgoodiss&Hgoodi).\n  apply prog_sim.\n  auto.\n  intros. \n  subst.\n  inversion H;tryfalse.\n\n  (*---------------------------interrupt step -------------------------------*)\n  inversion H0.\n  subst.\n  inversion H6.\n  subst.\n  \n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htmspec&Htospec&Hproj&Hrepl&Htasksch&Htaskscl&Hlinv&Hcsim).\n  destruct Ch as (ch,(keh,ksh)).\n  destruct A as ((apispec,intspec),sc).\n  assert (exists absi, intspec i = Some absi).\n  unfold eqdomOS in Heqdomos.\n  destruct Heqdomos as (Heqdomos1&Heqdomos2&Heqdomos3).\n  simpl in Heqdomos3.\n  lets Hx: Heqdomos3 i.\n  destruct Hx.\n  apply H2.\n  eexists;eauto.\n  destruct H2.\n\n  \n  exists (TasksMod.set Th t' (curs (hapi_code (x )),(kenil,kevent ch keh ksh))) O.\n  split.\n  subst.\n  eapply hp_stepS.\n  2:apply hp_stepO.\n  eapply hi_step;eauto.\n  constructors;eauto.\n  apply CIH.\n  \n  auto.\n  exists pc0 ((apispec,intspec),sc) po0 pi0 ip0.\n  assert (lintstep ip0 (c, (ke, ks)) (ge, le, m, ir, (true, si, nil))\n         (curs s, (kenil, kint c ke le ks))\n         (ge, empenv, m, isrupd ir i true, (false, i :: si, nil))) as Hintstep.\n  auto.\n  apply int_mem_trans with (Ms:=Ms) (I:=I) (Os:=Os) (Ml:=Ml) (sd:=sc) (li:=lasrt)in H6.\n  destruct H6 as (Ms'& Ml'& Os' &Ol'&H6).\n  exists (TMSpecMod.put Tm t' (merge Mc Ml')).\n  exists (TOSpecMod.put To t' (merge Oc Ol')).\n  exists (merge Ol Ol') Os' Ms' (merge Ml Ml') I.\n  exists lasrt.\n  split;auto.\n  split;auto.\n  splits;auto.\n  splits;auto.\n  \n  eapply lpstep_goodks;eauto.\n  eapply lpstep_good_is_S;eauto.\n  assert (  (snd (fst (fst S'))) = (snd (fst (fst (ge, empenv, m, isrupd ir i true, (false, i :: si, (nil:cs)))))) ).\n\n\n  eapply projs_eqm in H4.\n  eauto.\n  assert ( (snd (fst (fst Sl))) = (snd (fst (fst (ge, le, m, ir, (true, si, (nil:cs)))))) ).\n  apply projs_eqm with t'.\n  auto.\n  simpl in H10.\n  simpl in H11.\n  rewrite H10.\n  rewrite H11 in *.\n\n\n  eapply join_join_join_merge;eauto.\n  destruct H6;auto.\n  \n  split.\n\n  apply part_merge_m.\n  Focus 2.\n  destruct H6.\n  clear -H6 Hmjoin.\n  unfolds.\n  join auto.\n  apply Htmspec.\n  auto.\n  split.\n  eapply join_join_join_merge;eauto.\n  destructs H6;auto.\n  split.\n  apply part_merge_o.\n  Focus 2.\n  destructs H6.\n  clear -H10 HOjoin.\n  unfolds.\n  join auto.\n  apply Htospec.\n  auto.\n  \n  splits;auto.\n  do 2 eexists;splits;eauto.\n\n  destructs H6.\n  auto.\n  \n  exists (ge, (empenv:env), m, isrupd ir i true, (false, i :: si, (nil:cs))) (substaskst (ge, (empenv:env), m, isrupd ir i true, (false, i :: si, (nil:cs))) (merge Mc Ml')) (merge Mc Ml') (merge Oc Ol') ((curs s), (kenil, ( kint c ke le ks))) (curs (hapi_code (x)), (kenil, kevent ch keh ksh)).\n  splits.\n  apply  TMSpecMod.ext_mapsto.\n  auto.\n  auto.\n  auto.\n  apply  TasksMod.set_a_get_a.\n  unfold tidspec.beq.\n  apply tidspec.eq_beq_true.\n  auto.\n  apply  TasksMod.set_a_get_a.\n  unfold tidspec.beq.\n  apply tidspec.eq_beq_true.\n  auto.\n  \n  rewrite H3 in Hproj.\n  inverts Hproj.\n  simpl in Hrepl.\n  subst o'.\n  simpl substaskst.\n\n  eapply CurLINV_merge_hold.\n  assert (disjoint Mc Ms).\n  eapply part_disjm;eauto.\n  clear -Hmjoin.\n  unfolds;join auto.\n  destruct H6.\n  clear -H6 H10.\n  unfold disjoint in *.\n  join auto.\n  assert (disjoint Oc Os).\n  eapply part_disjo;eauto.\n  clear -HOjoin.\n  unfolds;join auto.\n  destructs H6.\n  clear -H11 H10.\n  unfold disjoint in *.\n  join auto.\n  eapply CurLINV_ignore_int;eauto.\n\n    \n  assert (Cl= (c, (ke, ks))) as Hfuck1l.\n  unfold tid in *.\n  rewrite H1 in Htaskscl.\n  inversion Htaskscl;tryfalse;auto.\n  rewrite H3 in Hproj.\n  inverts Hproj.\n  simpl in Hrepl.\n  subst o'.\n  simpl substaskst.\n\n  destruct H6 as ( Hmsjoin & Hosjoin & Hg1).\n  subst Cl.\n\n  \n  assert (lintstep' i ip0 (c, (ke, ks)) (ge, le, m, ir, (true, si, nil))\n               (curs s, (kenil, kint c ke le ks))\n               (ge, empenv, m, isrupd ir i true, (false, i :: si, nil))).\n  subst.\n  eapply li_step;eauto.\n\n  eapply IntSeq' with (c:=c) (ke:=ke) (ks:=ks) (Mi:=Ml')\n                            (s:=s)  (t:=t') (I:=I) (p:=(InitTaskSt lasrt t')) (O:=Oc) (Oi:=Ol')\n                            (Mc:=Mc)  (Ms':=Ms')\n                            (Os':=Os');eauto.\n  simpl substaskst.\n  auto.\n  destruct Hinv.\n  destruct H10.\n  destructs H10.\n  rewrite H10 in H3;inverts H3.\n  simpl in H11.\n  subst x1.\n  auto.\n  eapply part_disjo;eauto.\n  clear -HOjoin.\n  unfolds;eauto.\n  eapply part_disjm;eauto.\n  clear -Hmjoin.\n  unfolds;eauto.\n \n  intros.\n  assert (t'0<>t') as Hneqt.\n  auto.\n  apply Hrsim with (Ch:=Ch)in H10;auto.\n  destruct H10 as (or&M'&Clr&O'&Hrsim').\n  destruct Hrsim' as (Htmspecr&Htospecr&Hprojr&Hsatlinv&Htasksmod&Hrsim'').\n\n  exists ((fst (fst or)),(snd (fst S')),(snd or)) M' Clr O'.\n  splits;auto.\n  \n\n  apply tm_mapsto_put' with (t:=t') (a:=merge Mc Ml');auto.\n  apply to_mapsto_put' with (t:=t') (a:=merge Oc Ol');auto.\n\n  subst o'.\n\n  eapply projs_steq_projs;eauto.\n  destruct or as [[[[]]]].\n  simpl.\n  simpl in Hsatlinv.\n  eapply LInv_ignore_int;eauto.\n\n\n  rewrite tasks_set_get_neq;auto.\n  intros.\n  rename H12 into Hnodead.\n  assert (RdyChange (substaskst or Mr) =RdyChange( substaskst (fst (fst or), snd (fst S'), snd or) Mr)).\n  destruct or as [[[[]]]].\n  simpl.\n  auto.\n  rewrite <- H12 in *.\n  apply Hrsim'' in H10.\n  mytac.\n  eexists;splits;eauto.\n\n  assert (RdyChange (substaskst or (merge Mr M')) =RdyChange( substaskst (fst (fst or), snd (fst S'), snd or) (merge Mr M'))).\n  destruct or as [[[[]]]].\n  simpl.\n  auto.\n  rewrite <- H0.\n  auto.\n\n  rewrite TasksMod.set_a_get_a' in H11.\n  auto.\n  apply tidspec.neq_beq_false.\n  auto.\n  clear -Heqdomto Htasksch.\n\n  eapply eqdomTO_setT;eauto.\n\n  auto.\n  simpl.\n  rewrite H3 in Hproj;inverts Hproj.\n  simpl in Hrepl;subst.\n  apply projs_eqm with (t:=t') in H3.\n  rewrite H3 in Hmjoin.\n  simpl in Hmjoin;auto.\n\n  destruct Hinv as (or&or'&Hon&Honrep&Hg).\n  rewrite Hon in H3.\n  inversion H3;tryfalse;auto.\n  subst or.\n  simpl in Honrep;subst or'.\n  auto.\n  (*---------------------------interrupt step end -------------------------------*)\n\n\n\n  (*--------------------------- normal step  -------------------------------*)\n  subst.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htmspec&Htospec&Hproj&Hrepl&Htasksch&Htaskscl&Hsatlinv&Hcsim).\n  assert (o=tst).\n  rewrite H2 in Hproj.\n  inversion Hproj;tryfalse;auto.\n  subst tst.\n  unfold tid in *.\n  rewrite Htaskscl in H0.\n  inverts H0.\n  rename C into Cl.\n\n  inversion Hcsim.\n  subst.\n  destruct Hinv as (on&on'&Hproj'&Hrepl'&Hinv).\n  rewrite Hproj' in H2.\n  inverts H2.\n  assert (substaskst (substaskst o Mc) Ms = on').\n  rewrite <- Hrepl'.\n\n\n\n  apply repl_change_tstm_trans.\n  subst.\n  rewrite <- H2 in Hinv.\n  unfold satp in *.\n  apply H0 with (Cl':=C') (cst:=cst) (cst':=cst') (o'':=tst')\n                          (o2:=o) (Mf:=minus Ml Mc) (OO:=merge Oc Os) in Hinv.\n  destruct Hinv as (Ch'&OO'&o'&Ms'&O'&Os'&Hhtstep&Hjoin2l&Hjoinh&Hinv&Htlinv&Htsim).\n\n  \n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) in Hhtstep.\n  mytac.\n\n  exists (set Th t' Ch') x.\n  split.\n\n  apply th_no_create_lift  with (C:=Ch);auto.\n\n  apply CIH.\n\n  rename H11 into Hhtstep.\n  apply htstepstar_tidsame in Hhtstep;auto.\n  unfold tidsame in Hhtstep.\n  unfold get in Hhtstep,Hosabsttid.\n  simpl in Hhtstep.\n  simpl in Hosabsttid.\n  rewrite Hosabsttid in Hhtstep;auto.\n\n  exists pc A po pi ip (TMSpecMod.put Tm t' (get_mem (get_smem o'))).\n  subst.\n\n  exists (TOSpecMod.put To t' O') (minus x Os') Os' Ms' (minus (get_mem (get_smem tst')) Ms').\n  exists I lasrt.\n\n  \n  destruct tst' as [[[[]]]].\n  splits;auto.\n\n  splits;auto.\n  splits;auto.\n\n  eapply lpstep_goodks;eauto.\n  eapply lpstep_good_is_S;eauto.\n  \n  assert (snd (fst (fst S')) = snd (fst (fst (e, e0, m, i, l)))).\n  apply projs_eqm with (t:=t');auto.\n  rewrite H13.\n  simpl.\n\n  eapply joinm2_minus_join;eauto.\n  simpl.\n  eapply partm_task_get_set;eauto.\n\n  eapply partM_normal;eauto.\n  eapply join_join_minus;eauto.\n  \n  eapply parto_task_get_set;eauto.\n  eapply partO_normal;eauto.\n  \n \n  exists (e, e0, m, i, l) (e, e0, Ms', i, l).\n  splits;auto.\n  \n  assert (substaskst o' Ms'= (e, e0, Ms', i, l)) as Hrepltrans.\n  clear -Hjoin2l.\n  unfolds in Hjoin2l.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  simpl;auto.\n  rewrite Hrepltrans in Hinv.\n  auto.\n\n  exists (e, e0, m, i, l) o'\n         (get_mem (get_smem o')) O' C' Ch'.\n  splits;auto.\n  clear -Hjoin2l.\n  unfolds in Hjoin2l.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  simpl.\n  auto.\n  apply map_get_set.\n  apply map_get_set.\n\n  splits;auto.\n  intros.\n  \n  rename H15 into Hnodead.\n  assert (t'0<>t');auto.\n\n  apply Hrsim with (Ch:=Ch0) in H13.\n\n  destruct H13 as (or&M'r&Clr&O'r&Htmr&Htor&Hprojr&Hrlinv&Htasksr&Hsimr).\n\n  exists (((gets_g S'),(get_env (get_smem or)),(gets_m S')),(snd (fst S')),\n          (snd or)) M'r Clr O'r.\n  splits;auto.\n  apply tm_mapsto_put' with (t:=t') (a:=get_mem (get_smem o'));auto.\n  apply to_mapsto_put' with (t:=t') (a:=O');auto.\n\n  \n  apply proj_stneq_ex with (S:=Sl) (t:=t'); auto.\n  2:rewrite tasks_set_get_neq;auto.\n  intros.\n  eapply LInv_ignore_int.\n  assert (substaskst\n            (gets_g Sl, get_env (get_smem or), gets_m S', snd (fst or), snd or) M'r = substaskst or M'r).\n\n  simpl.\n  clear -Hprojr H4.\n  destruct Sl as [[[[]]]].\n  destruct S' as [[[[]]]].\n  destruct or as [[[[]]]].\n  unfold gets_g,get_env.\n  simpl in *.\n  unfold tid in *.\n  remember (get c t'0) as X.\n  destruct X;tryfalse.\n  remember (get l t'0) as Y.\n  destruct Y;tryfalse.\n  inverts Hprojr.\n  auto.\n\n  assert (gets_g Sl = gets_g S') by (eapply ge_n_change;eauto).\n  rewrite <- H16.\n  simpl in H13.\n  erewrite H13.\n  eauto.\n\n  intros.\n  \n  assert (gets_g Sl = gets_g S') by (eapply ge_n_change;eauto).\n  assert (forall Mr,RdyChange\n            (substaskst\n               (gets_g S', get_env (get_smem or), \n               gets_m S', snd (fst S'), snd or) Mr) = RdyChange (substaskst or Mr)).\n  intros.\n  simpl.\n  clear -Hprojr H4 H16.\n  destruct Sl as [[[[]]]].\n  destruct S' as [[[[]]]].\n  destruct or as [[[[]]]].\n  unfold gets_g,get_env in *.\n  simpl in *.\n  unfold tid in *.\n  remember (get c t'0) as X.\n  destruct X;tryfalse.\n  remember (get l t'0) as Y.\n  destruct Y;tryfalse.\n  subst e.\n  inverts Hprojr.\n  auto.\n\n  rewrite H17 in H13.\n  apply Hsimr in H13.\n  mytac.\n  eexists.\n  erewrite H17.\n  splits;eauto.\n  \n  rewrite <- H14. auto.\n  symmetry.\n  apply tasks_set_get_neq;auto.\n  eapply htstepstar_nodead_still;eauto.\n  eapply hpstep_eqdomto with (T:=Th) (O:=O) (cst:=cst) (cst':=cst') (p:=(pc,A));eauto.\n  apply th_no_create_lift with (C:=Ch);auto.\n\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n\n  eapply joinm2_merge_minus;eauto.\n  assert ( (snd (fst (fst Sl))) = (snd (fst (fst o)) )).\n  apply projs_eqm with t'.\n  auto.\n  destruct o as [[[[]]]].\n  simpl in H11.\n  simpl get_smem.\n  simpl get_mem.\n  rewrite <- H11;auto.\n  eapply part_sub;eauto.\n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  unfolds;eauto.\n  auto.\n  (**Guarded.**)\n\n  \n  (*--------------------------- normal step end -----------------------------*)\n\n  \n  (*-----------------------------switch step ---------------------------*)\n\n\n  subst.\n  inversion H0;subst pc0 po0 pi0 ip0.\n\n  (*keep the name of H*)\n  rename H9 into H10.\n  rename H8 into H9.\n  \n  rename H4 into H5.\n  rename H3 into H4.\n  rename H2 into H3.\n  rename H1 into H2.\n\n  \n  assert (projS (ge, les, m, ir, au) t = Some tst) as H1 by auto.\n  (*----------------*)\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Hcsim).\n  destruct Hcsim as (Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  inversion Hcsim.\n  subst.\n  assert (Cl= (curs (sprim (switch x)), (kenil, ks))).\n  unfold tid in *.\n  unfold get in Htl.\n  simpl in Htl.\n  unfold get in H5.\n  simpl in H5.\n  rewrite H5 in Htl.\n  inverts Htl.\n  auto.\n  eapply H8 with (OO:=merge Oc Os) (Ms:=Ms) (Os:=Os) in H15.\n  destruct H15 as (Ch'&sleft&k&OO'&Mc'&ol&O'&Os'&Olc&Occ&Hhch&Hhtstep&Hljoin&Hhjoin&Hhjoin'&Hinv'&Hswinv&Hlinv'&H15).\n  destruct H15.\n  destruct H15 as (Hswpre&H15).\n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) (cst:=cst') in Hhtstep.\n\n  Focus 2.\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n\n  mytac.\n  \n  rewrite repl_change_tstm_trans in *.\n  exists (set Th t (curs (hapi_code sleft), k)) (set x0 curtid (oscurt t')).\n\n  (*HHHH*)\n  assert (  hpstep (pc, A) (set Th t (curs (hapi_code (sched;; sleft)), k)) cst' x0\n                   (TasksMod.set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) /\\  forall ab, (tst, x0 , ab) |= AHprio (snd A) t' ** Atrue).\n \n  eapply sw_same_t with (l:=l) (tp:=tp) (x:=x) (tst:=tst) (t':=t');eauto.\n  unfolds in Hgoodi.\n  mytac;simpl;auto.\n\n  apply htstepstar_tidsame in H16.\n  unfolds in H16.\n  rewrite <- H16.\n  auto.\n\n  rewrite H2 in Hproj;inverts Hproj.\n  rewrite H17 in H2;inverts H2.\n  simpl snd.\n  unfold getsched in Hswpre.\n  simpl snd in Hswpre.\n  unfold satp in *.\n \n  eapply swpre_prop with (M:=Mc');eauto.\n  intros.\n  unfold SWPRE_NDEAD in Hswpre.\n  lets Hx:Hswpre ab.\n  destruct Hx.\n  eauto.\n  \n  apply projs_eqm in H17.\n  destruct o as [[[[]]]].\n  simpl in H17.\n  simpl.\n  subst m0.\n\n  eapply part_sub with (Mc:=Mc) in Hmpart;eauto.\n  eapply sub_join_sub;eauto.\n  clear -Hmpart Hljoin.\n  unfold joinmem in *.\n  mytac.\n  simpl in H0;inverts H0.\n  unfold Maps.sub in *.\n  destruct Hmpart.\n  unfold TMSpecMod.B in *.\n  unfold mmapspec.image in *.\n  join auto.\n  clear -Hhjoin' Hhjoin H18.\n  unfolds Maps.sub.\n  unfold TOSpecMod.B in *.\n  unfold omapspec.image in *.\n  geat.\n  \n  assert (hpstepstar (pc, A) Th cst' O\n                     (set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) ) as Hpstepstar.\n  \n  assert (hpstepstar (pc, A) Th cst' O \n                     (set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) ) as Hhpstep.\n\n  assert (hpstepstar (pc, A) Th cst' O\n                     (set Th t (curs (hapi_code  (sched;; sleft)), k)) cst' x0).\n  apply th_no_create_lift with (C:=Ch);auto.\n\n  eapply hpstep_star with (T':=(set Th t (curs (hapi_code  (sched;; sleft)), k))) (cst':=cst') (O':=x0);eauto. \n\n  destruct H0;auto.\n  auto.\n\n  rename H0 into HHHH.\n  destruct HHHH as (Hxx&HHHH).\n  clear Hxx.\n  \n\n  assert (forall ab,(substaskst o Mc', Occ, ab) |= AHprio (snd A) t' ** Atrue).\n  eapply lemma_trans_temp;eauto.\n  unfolds in Hgoodi;destructs Hgoodi;auto.\n  intros.\n  lets Hx:Hswpre ab.\n  unfold SWPRE_NDEAD in Hx;destruct Hx.\n  eauto.\n  clear -Hhjoin' Hhjoin H18.\n  unfolds Maps.sub.\n  unfold TOSpecMod.B in *.\n  unfold omapspec.image in *.\n  geat.\n  clear HHHH.\n  rename H0 into HHHH.\n  split;auto.\n  apply CIH.\n  eapply map_get_set.\n  destruct (tid_eq_dec t t').\n\n  (*--------cur == highest rdy-------------*)\n  subst t'.\n\n  assert (o=tst).\n  rewrite H2 in Hproj.\n\n  inversion Hproj;tryfalse;auto.\n  subst tst.\n  destruct o as [[[[]]]].\n  unfold joinmem in Hljoin.\n  destruct Hljoin.\n  do 5 destruct H0.\n  destructs H0.\n  simpl in H19.\n  inversion H19;subst x2 x7 x3 x6 x5.\n  subst ol.\n  unfold substaskst in *.\n  unfold get_smem in*.\n  unfold get_genv in *.\n\n  apply projs_eqg in Hproj.\n  simpl in Hproj.\n  subst e.\n\n  assert ( ((ge, e0, Mc', i, l0), Occ,(spec_done None)) |= SWPRE (snd A) x t) as Hnmc';auto.\n  lets Hx:Hswpre (END None).\n  unfold SWPRE_NDEAD in Hx.\n  destruct Hx;eauto.\n  eapply swpre_store with (b:=b) (tp:=(Tptr tp)) (t:=t) in Hnmc';auto.\n\n  destruct Hnmc' as (Mc'n&Hmc'n).\n  lets Hnmc:join_store' H21 Hmc'n.\n  destruct Hnmc as(Mcn&Hmcn).\n  lets Hnmpart:part_store_part Hmpart Htm Hmcn.\n  destruct Hnmpart as (Ml'&Hstoreml&Hmpartn).\n  assert (set O' curtid (oscurt t) = O') as Ho'set.\n  clear -Hswinv Hhjoin' Hgoodi.\n  unfolds in Hgoodi.\n  lets Hx:Hswinv (spec_done None).\n  destructs Hgoodi.\n  apply H0 in Hx.\n  mytac.\n  eapply join_get_get_r in Hhjoin';eauto.\n  apply get_set_same;auto.\n  exists pc A po pi ip (TMSpecMod.put Tm t Mcn).\n  exists (TOSpecMod.put To t O') (merge O' (minus Ol Oc)) Os' Ms Ml' I.\n  exists lasrt.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  eapply lpstep_goodks;eauto.\n  clear -Hgoodiss.\n  unfold good_is_S in *.\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  assert (projS (ge, les, m, ir, au) t = Some (e, e0, m, i, (i0, i1, c))).\n  unfold projS in *.\n  unfold projD in *.\n  unfold tid in *.\n  destruct (get les t);tryfalse;auto.\n  destruct (get au t);tryfalse;auto.\n  inverts H;auto.\n  apply Hgoodiss in H0.\n  auto.\n  simpl.\n  apply join_comm.\n  eapply join_store_join;eauto.\n  eapply join_comm;eauto.\n  eapply partm_task_get_set;eauto.\n  apply htstepstar_tidsame in H16.\n  unfold tidsame in H16.\n  unfold get in H16,Hosabsttid.\n  simpl in H16.\n  simpl in Hosabsttid.\n  rewrite Hosabsttid in H16.\n  unfold tid in *.\n  rewrite <- Ho'set.\n  eapply join_join_join_merge_set;eauto.\n\n  eapply parto_task_get_set;eauto.\n  \n  eapply new_part_o;eauto.\n  clear -Hhjoin H18.\n  eapply join_join_disj_l;eauto.\n\n  destruct x1.\n  destruct p.\n  destruct p.\n  destruct p.\n  exists (e, e1, m', i0, l1) (e, e1, Ms, i0, l1).\n  rewrite H2 in H17;inverts H17.\n  splits;auto.\n  clear -H2.\n  unfold projS in *.\n  unfold projD in *.\n  unfold tid in *.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts H2;auto.\n\n  exists  (ge, e0, m', i, l0) (ge,e0,Mcn,i,l0) Mcn  O' (SKIP, (kenil, ks)) (curs (hapi_code sleft), k).\n  splits;auto.\n  clear -H2.\n  unfold projS in *.\n  unfold projD in *.\n  unfold tid in *.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts H2;auto. \n  apply map_get_set.\n  apply map_get_set.\n\n  eapply curlinv_switch_self;eauto.\n  unfolds;intros.\n  lets Hx:Hswpre aop.\n  unfold SWPRE_NDEAD in Hx;destruct Hx.\n  eauto.\n  eapply H15 with (Mc':=Mc'n);eauto.\n  Focus 2.\n  unfold joinmem.\n  do 6 eexists;splits;eauto.\n  eapply join_store_join;eauto.\n  \n  unfolds;intros.\n  lets Hnswinv: goodI_swinv_samet Hgoodi Hswinv HHHH.\n  eauto.\n  eauto.\n  eapply Hlinv'.\n  destruct Hnswinv as (Hswinvget&Hnswinv).\n  destruct Hswinvget.\n  destruct H0.\n  destructs H0.\n  rewrite H0 in H9;inversion H9;subst x2 x3.\n  eapply Hnswinv;eauto.\n  splits;auto.\n\n  intros.\n  assert (t'<>t) as Htneq;auto.\n  apply Hrsim with (Ch:=Ch0) in H0.\n  destruct H0 as (or&Mr'&Clr&Or'&Hrtm&Hrto&Hrproj&Hrlinv&Hrts&H0).\n  exists (substaskst or m') Mr' Clr Or'.\n  splits;auto.\n  eapply tm_mapsto_put';eauto.\n  eapply to_mapsto_put';eauto.\n  destruct or as [[[[]]]].\n  unfold substaskst.\n  clear -Hrproj.\n  unfold projS in *.\n  unfold projD in *.\n  unfolddef.\n  destruct ( get les t' );tryfalse.\n  destruct ( get au t'  );tryfalse.\n  inverts Hrproj;auto.\n  2:rewrite tasks_set_get_neq;auto.\n  destruct or as [[[[]]]].\n  simpl.\n  auto.\n  \n  destruct or as [[[[]]]].\n  unfold substaskst.\n  auto.\n  rewrite tasks_set_get_neq in H22;auto.\n  eapply htstepstar_nodead_still;eauto.\n  clear -H23.\n  unfolds.\n  unfolds in H23.\n  intros.\n  apply H23.\n  rewrite map_get_set';auto.\n  apply  hpstep_eqdomto in Hpstepstar;auto.\n  eauto.\n  (*--------cur <> highest rdy-------------*)\n  assert (exists C, TasksMod.get (TasksMod.set Th t (curs (hapi_code sleft), k)) t' = Some C).\n\n  eapply sw_has_code with (l:=l) (tp:=(Tptr tp)) (x:=x) (tst:=tst) (O:=x0) (sd:=snd A);auto.\n  unfolds in Hgoodi;destructs Hgoodi;auto.\n  assert (o=tst).\n  rewrite H2 in Hproj.\n  inversion Hproj;tryfalse;auto.\n  subst tst.\n  eapply swpre_prop with (M:=Mc');eauto.\n  \n  intros.\n  lets Hx:Hswpre ab.\n  unfold SWPRE_NDEAD in Hx;destruct Hx;eauto.\n  \n  assert (Maps.sub Mc Ml).\n  apply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);auto.\n  clear -Hljoin H0 Hmjoin H2.\n  destruct o as [[[[]]]].\n  simpl in *.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts H2.\n  unfolds in Hljoin.\n  mytac.\n  geat.\n  clear -Hhjoin Hhjoin' H18.\n  unfolddef.\n  \n  geat.\n\n  apply hpstep_eqdomto in Hpstepstar;auto.\n  unfold eqdomTO in *.\n  clear -Hpstepstar.\n  mytac.\n  eexists;split;eauto.\n  Lemma abst_set_get_neq: forall id1 id2 y O, id1<>id2 ->  OSAbstMod.get (OSAbstMod.set O id2 y) id1 = OSAbstMod.get O id1.\n  Proof.\n    intros.\n    apply OSAbstMod.set_a_get_a'.\n    apply absdataidspec.neq_beq_false.\n    auto.\n  Qed.\n  rewrite abst_set_get_neq in H;auto.\n \n\n  destruct H0 as (Cn&Hcn).\n  rewrite tasks_set_get_neq in Hcn;auto.\n  assert (TasksMod.get Th t' = Some Cn) as Hcode;auto.\n  apply Hrsim in Hcn;auto.\n  destruct Hcn as (on&Mn&Cn'&On&Htmn&Hton&Hprojn&Hlinvn&Htasksn&Hcn).\n  assert (disjoint Mc' Ms).\n  clear -Hljoin Hmjoin Hmpart Htm.\n  destruct o.\n  destruct p.\n  destruct p.\n  destruct p.\n  simpl in *.\n  unfold joinmem in *.\n  mytac.\n  assert (disjoint x2 Ms). \n  apply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);auto.\n  unfolddef.\n  clear -Hmjoin.\n  geat.\n  clear -H1 H.\n  unfolddef.\n  geat.\n  \n\n  assert (exists Mcc,store (Tptr tp) Mc' (b,0%Z) (Vptr t') = Some Mcc).\n  destruct o as [[[[]]]];unfold substaskst in Hswpre.\n  assert ((e, e0, Mc', i, l0, Occ, (spec_done None)) |= SWPRE (snd A) x t);auto.\n  lets Hx:Hswpre (END None).\n  unfold SWPRE_NDEAD in Hx.\n  destruct Hx;eauto.\n  eapply swpre_store with (ab:=spec_done None);eauto.\n  clear -Hproj H9.\n  simpl in Hproj.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts Hproj.\n  unfold get in H9;simpl in H9;auto.\n  destruct H19 as (Mcc&Hmcc).\n\n\n  eapply swi_rdy_inv'''' with (o:=o) (Ol:=Occ) (Os:=Os') (OO:=merge Occ Os') (I:=I) (t:=t) (t':=t') (S:=(ge, les, m, ir, au)) (o':=on) (tp:=tp) (Mcc:=Mcc) (b:=b) (sc:=snd A) (li:=lasrt) in H0;auto.\n\n  destruct H0 as (Mc'0&Ms'&Oc'0&Os''&OO''&Hndisj&Hnmerge&Hnojoin&Hnoset&H0).\n  exists pc A po pi ip.\n  exists (TMSpecMod.put (TMSpecMod.put Tm t (minus Mc Mc')) t' (merge Mn Mc'0))\n         (TOSpecMod.put (TOSpecMod.put To t Olc) t' (merge On Oc'0))\n         ((merge (merge Oc'0 Olc) (minus Ol Oc))) Os''.\n  exists Ms' (merge (minus Ml Mc') Mc'0) I lasrt.\n  assert (Maps.sub Mc' Mc).\n  clear -Hljoin.\n  destruct o as [[[[]]]].\n  unfold joinmem in Hljoin.\n  simpl in Hljoin.\n  mytac.\n  unfolddef.\n  unfold Maps.sub.\n  geat.\n  assert (Maps.sub Mc Ml).\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n\n  lets Hsubtrans: sub_trans H19 H21.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  eapply lpstep_goodks;eauto.\n  clear -Hgoodiss.\n  unfold good_is_S in *.\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  assert (projS (ge, les, m, ir, au) t = Some (e, e0, m, i, (i0, i1, c))).\n  unfold projS in *.\n  unfold projD in *.\n  unfolddef.\n  destruct (get les t);tryfalse;auto.\n  destruct (get au t);tryfalse;auto.\n  inverts H;auto.\n  apply Hgoodiss in H0.\n  auto.\n  simpl.\n\n \n  eapply mem_join_merge_minus_join_store' with (Ms:=Ms) (Mc:=Mc') (Mcc:=Mcc) (Mc':=Mc'0) (m':=m');eauto.\n \n  eapply partm_task_get_set;eauto.\n\n  apply partm_merge_disj.\n  assert (Maps.sub Mc'0 (merge Mc'0 Ms')).\n\n  apply sub_merge_l;auto.\n  rewrite Hnmerge in H22.\n\n  erewrite store_sub_minus_eq ;eauto.\n\n  eapply store_sub_disj_disj with (M2:=Mc') (Ms:=Ms) ;eauto.\n  clear -Hmjoin.\n  simpl in *;unfolds.\n  join auto.\n  \n  unfold TMSpecMod.maps_to.\n  unfold TMSpecMod.put.\n  destruct TMSpecMod.beq_A;tryfalse.\n  unfold TMSpecMod.maps_to in Htmn;auto.\n \n  apply partm_minus_sub;auto.\n\n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  eapply join_complex;eauto.\n\n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  eapply parto_task_get_set;eauto.\n\n  eapply parto_complex;eauto.\n  eapply disj_complex with (Occ:=Occ);eauto.\n\n  eapply disj_complex';eauto.\n  \n  exists (substaskst on m') (substaskst on Ms').\n  splits;auto.\n  destruct on as [[[[]]]].\n  clear -Hprojn.\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t');tryfalse.\n  destruct (get au t');tryfalse.\n  inverts Hprojn.\n  simpl;auto.\n  apply repl_change_tstm_trans.\n\n  destruct H0;auto.\n  \n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  exists (substaskst on m') ( substaskst on (merge Mn Mc'0)) (merge Mn Mc'0) (merge On Oc'0) Cn' Cn.\n  splits;auto.\n  clear -Hprojn.\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t');tryfalse.\n  destruct (get au t');tryfalse.\n  inverts Hprojn.\n  simpl;auto.\n  destruct on as [[[[]]]];simpl;auto.\n  rewrite tasks_set_get_neq;auto.\n  rewrite tasks_set_get_neq;auto.\n\n  destruct H0.\n  eapply switch_linv;eauto.\n\n  destruct ol as [[[[]]]].\n  destruct o as [[[[]]]].\n  eapply disj_complex'' with (t:=t) (t':=t');eauto.\n  unfolds in Hljoin.\n  mytac.\n  simpl in e4;inverts e4.\n  eauto.\n\n  eapply disj_complex''' with (Occ:=Occ);eauto.\n  \n  assert ( (forall ab : absop, (substaskst on Ms', Os'', ab) |= INV I) /\\\n           (forall ab : absop, (substaskst on Mc'0, Oc'0, ab) |= RDYINV I t')) as H177;auto.\n  destruct H0.\n\n  assert ( (forall ab : absop, (RdyChange (substaskst on Mc'0), Oc'0, ab) |= RDYINV I t') /\\ disjoint Mc'0 Mn /\\ disjoint Oc'0 On).\n  split.\n  assert (RdyChange (substaskst on Mc'0)=substaskst on Mc'0).\n\n  eapply rdyinv_isremp with (I:=I) (O:=Oc'0) (M:=Mc'0);eauto.\n  rewrite H24;auto.\n  split.\n  destruct ol as [[[[]]]].\n  destruct o as [[[[]]]].\n  eapply disj_complex'' with (t:=t);eauto.\n  unfolds in Hljoin.\n  mytac.\n  simpl in e4;inverts e4.\n  eauto.\n  eapply disj_complex''';eauto.\n  assert (exists M'',\n            M'' = merge Mc'0 Mn /\\\n            TaskSim (pc, (po, pi, ip)) Cn' (RdyChange (substaskst on M''))\n                    (pc, A) Cn (merge Oc'0 On) lasrt I (InitTaskSt lasrt t') t').\n  apply Hcn.\n  auto.\n\n  destruct H25 as (M''&Hm''merge&Htsim).\n  rewrite Hm''merge in Htsim.\n  assert (RdyChange (substaskst on (merge Mc'0 Mn))=substaskst on (merge Mc'0 Mn)).\n  eapply rdyinv_isremp with (I:=I) (O:=Oc'0) (M:=Mc'0);eauto.\n  rewrite H25 in Htsim.\n\n  destructs H24.\n  assert (merge Mc'0 Mn = merge Mn Mc'0).\n  rewrite disjoint_merge_sym;auto.\n  assert (merge Oc'0 On = (merge On Oc'0)).\n  rewrite disjoint_merge_sym;auto.\n  rewrite <- H28.\n  rewrite <- H29.\n  auto.\n\n  splits;auto.\n  intros.\n  rename H24 into Hdead.\n  destruct (tid_eq_dec t'0 t).\n  subst t'0.\n  assert (get (set Th t (curs (hapi_code sleft), k)) t = Some (curs (hapi_code sleft), k)).\n  eapply map_get_set.\n  unfold code in *.\n  rewrite H23 in H24.\n  inverts H24.\n  exists (substaskst o m') (minus Mc Mc') (SKIP, (kenil,ks)) Olc.\n  splits;auto.\n  unfold TMSpecMod.maps_to.\n  unfold TMSpecMod.put.\n  destruct (TMSpecMod.beq_A t t');tryfalse.\n  destruct (TMSpecMod.beq_A t t );tryfalse.\n  auto.\n  \n  unfold TOSpecMod.maps_to.\n  unfold TOSpecMod.put.\n  destruct (TOSpecMod.beq_A t t');tryfalse.\n  destruct (TOSpecMod.beq_A t t );tryfalse.\n  auto.\n  clear -Hproj.\n  destruct o as [[[[]]]].\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts Hproj.\n  simpl;auto.\n\n  rewrite repl_change_tstm_trans.\n\n  erewrite joinmem_substaskst_minus;eauto.\n  apply map_get_set.\n\n  intros.\n  \n  destruct H24 as (Hrinv&Hrdisj&Hodisj).\n  assert ( forall ab : absop,\n             (RdyChange (substaskst o Mr), Or, ab) |= SWINVt I t).\n \n  apply swi_rdy_eq_swi with (M:=Mc') (O:=Occ);auto.\n  rewrite repl_change_tstm_trans in Hrinv.\n  \n  assert (RdyChange (substaskst o Mr)=substaskst o Mr).\n  apply swinv_isremp in Hswinv.\n  clear -Hswinv.\n  destruct o as [[[[]]]].\n  simpl in *.\n  inverts Hswinv;auto.\n  rewrite H24 in Hrinv;auto.\n\n  assert (RdyChange (substaskst o Mr)=substaskst (substaskst o Mc) Mr).\n  apply swinv_isremp in Hswinv.\n  clear -Hswinv.\n  destruct o as [[[[]]]].\n  simpl in *.\n  inverts Hswinv;auto.\n  rewrite H25 in *.\n\n  apply H15 with (o':=substaskst o (merge Mr (minus Mc Mc'))) (O'':= merge Or Olc) in H24.\n  exists (merge Mr (minus Mc Mc')).\n  split;auto.\n  assert (RdyChange (substaskst (substaskst o m') (merge Mr (minus Mc Mc'))) = substaskst o (merge Mr (minus Mc Mc'))).\n  clear -H25.\n  destruct o as [[[[]]]].\n  simpl in *.\n  inverts H25;auto.\n  rewrite H26.\n  auto.\n  clear -Hrdisj Hljoin.\n  unfold joinmem in *.\n  destruct o as [[[[]]]].\n  mytac.\n  simpl in *.\n  inverts H0.\n  do 6 eexists;splits;eauto.\n\n  apply join_minus in H1.\n  unfolddef.\n  rewrite H1 in *.\n  apply join_comm.\n  apply join_merge_disj;auto.\n  apply join_comm.\n  apply join_merge_disj;auto.\n\n  \n  assert (t'0<>t) as Htneq;auto.\n  apply Hrsim with (Ch:=Ch0) in n0.\n  destruct n0 as (or&Mr'&Clr&Or'&Htmr&Htor&Hprojr&Hlinv''&Htsr&n0).\n  exists (substaskst or m') Mr' Clr Or'.\n  splits;auto.\n  unfold TMSpecMod.maps_to, TMSpecMod.put.\n  destruct TMSpecMod.beq_A;tryfalse;auto.\n  destruct TMSpecMod.beq_A;tryfalse;auto.\n  unfold TOSpecMod.maps_to, TOSpecMod.put.\n  destruct TOSpecMod.beq_A;tryfalse;auto.\n  destruct TOSpecMod.beq_A;tryfalse;auto.\n  \n  clear -Hprojr.\n  destruct or as [[[[]]]].\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t'0);tryfalse;destruct (get au t'0 );tryfalse.\n  inverts Hprojr;simpl;auto.\n  rewrite repl_change_tstm_trans;auto.\n  rewrite tasks_set_get_neq;auto.\n  intros.\n  assert (substaskst (substaskst or m') Mr= substaskst or Mr).\n  apply change_tstm_trans';auto. \n  rewrite H25 in H24.\n  eapply n0 in H24;eauto.\n  destruct H24.\n  exists x2.\n  assert (substaskst (substaskst or m') x2= substaskst or x2).\n  apply change_tstm_trans';auto. \n  rewrite H26.\n  auto.\n\n  rewrite tasks_set_get_neq in H23;auto.\n  eapply htstepstar_nodead_still;eauto.\n  clear -Hdead.\n  unfolds.\n  unfolds in Hdead.\n  intros.\n  apply Hdead.\n  rewrite map_get_set' ;auto.\n  apply hpstep_eqdomto in Hpstepstar;auto.\n  apply join_merge_disj.\n  clear -Hhjoin Hhjoin'.\n  unfolddef.\n  geat.\n\n  clear -H9 Hproj.\n  destruct o as [[[[]]]].\n  simpl in *.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts Hproj.\n  auto.\n  eapply htstepstar_nodead_still;eauto.\n\n  eapply AHprio_local with (O:=x0) in HHHH.\n\n  eapply ahprio_nodead;eauto.\n  clear -Hhjoin Hhjoin' H18.\n  unfolddef.\n  unfolddef.\n  join auto.\n  Focus 2.\n  unfolds;intros.\n  rewrite repl_change_tstm_trans.\n  mytac.\n  rewrite H16 in Hproj;inverts Hproj;auto.\n  Focus 2.\n  destruct o as [[[[]]]].\n  unfold getmem;simpl.\n  eapply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  clear -Hmjoin.\n  simpl in Hmjoin.\n  unfolddef;geat.\n  Focus 2.\n  apply join_merge_disj.\n  eapply part_disjo with (M:=Ol) (T:=Tl) (Tm:=To) (t:=t);eauto.\n  clear -HOjoin.\n  unfolddef;geat.\n\n  (*-----------switch dead case-----------------*)\n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) (cst:=cst') in Hhtstep.\n\n  Focus 2.\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n  \n  mytac.\n  \n  rewrite repl_change_tstm_trans in *.\n  exists (set Th t (curs (hapi_code sleft), k)) (set x0 curtid (oscurt t')).\n  (*HHHH*)\n  assert (  hpstep (pc, A) (set Th t (curs (hapi_code (sched;; sleft)), k)) cst' x0\n                   (TasksMod.set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) /\\  forall ab, (tst, x0 , ab) |= AHprio (snd A) t' ** Atrue).\n\n  eapply sw_same_t with (l:=l) (tp:=tp) (x:=x) (tst:=tst) (t':=t');eauto.\n  unfolds in Hgoodi.\n  mytac;simpl;auto.\n\n  apply htstepstar_tidsame in H16.\n  unfolds in H16.\n  rewrite <- H16.\n  auto.\n  rewrite H2 in Hproj;inverts Hproj.\n  rewrite H17 in H2;inverts H2.\n  simpl snd.\n  \n  unfold getsched in H15.\n  simpl snd in H15.\n  unfold satp in *.\n  \n  unfold SWPRE_DEAD in H15.\n  assert (forall aop,  (substaskst o Mc', Occ, aop)\n        |= SWPRE (snd A) x t).\n  intros.\n  lets Hx:H15 aop.\n  destruct Hx;auto.\n  eapply swpre_prop with (M:=Mc');eauto.\n  \n  apply projs_eqm in H17.\n  destruct o as [[[[]]]].\n  simpl in H17.\n  simpl.\n  subst m0.\n\n  eapply part_sub with (Mc:=Mc) in Hmpart;eauto.\n  eapply sub_join_sub;eauto.\n  clear -Hmpart Hljoin.\n  unfold joinmem in *.\n  mytac.\n  simpl in H0;inverts H0.\n  unfold Maps.sub in *.\n  destruct Hmpart.\n  unfold TMSpecMod.B in *.\n  unfold mmapspec.image in *.\n  join auto.\n  clear -Hhjoin' Hhjoin H18.\n  unfolds Maps.sub.\n  unfold TOSpecMod.B in *.\n  unfold omapspec.image in *.\n  geat.\n  \n  assert (hpstepstar (pc, A) Th cst' O\n                     (set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) ) as Hpstepstar.\n  \n  assert (hpstepstar (pc, A) Th cst' O \n                     (set Th t (curs (hapi_code sleft), k)) cst' (set x0 curtid (oscurt t')) ) as Hhpstep.\n\n  assert (hpstepstar (pc, A) Th cst' O\n                     (set Th t (curs (hapi_code  (sched;; sleft)), k)) cst' x0).\n  apply th_no_create_lift with (C:=Ch);auto.\n  eapply hpstep_star with (T':=(set Th t (curs (hapi_code  (sched;; sleft)), k))) (cst':=cst') (O':=x0);eauto. \n\n  destruct H0;auto.\n  auto.\n\n  rename H0 into HHHH.\n  destruct HHHH as (Hxx&HHHH).\n  clear Hxx.\n  assert (forall aop,  (substaskst o Mc', Occ, aop)\n                         |= SWPRE (snd A) x t).\n  intros.\n  lets Hx:H15 aop.\n  destruct Hx;auto.\n  \n  assert (forall ab,(substaskst o Mc', Occ, ab) |= AHprio (snd A) t' ** Atrue).\n  eapply lemma_trans_temp;eauto.\n  unfolds in Hgoodi;destructs Hgoodi;auto.\n  clear -Hhjoin' Hhjoin H18.\n  unfolds Maps.sub.\n  unfold TOSpecMod.B in *.\n  unfold omapspec.image in *.\n  geat.\n  clear HHHH.\n  rename H0 into HHHH.\n  split;auto.\n  apply CIH.\n  eapply map_get_set.\n  destruct (tid_eq_dec t t').\n  (* cur == high rdy -> false *)\n  subst t'.\n  false.\n  eapply swdead_ahprio_false;eauto.\n  unfolds in Hgoodi;mytac;auto.\n  (* cur <> high rdy *)\n  \n  assert (exists C, TasksMod.get (TasksMod.set Th t (curs (hapi_code sleft), k)) t' = Some C).\n \n  eapply sw_has_code with (l:=l) (tp:=(Tptr tp)) (x:=x) (tst:=tst) (O:=x0) (sd:=snd A);auto.\n  unfolds in Hgoodi;destructs Hgoodi;auto.\n  assert (o=tst).\n  rewrite H2 in Hproj.\n  inversion Hproj;tryfalse;auto.\n  subst tst.\n  eapply swpre_prop with (M:=Mc');eauto.\n  \n  assert (Maps.sub Mc Ml).\n  apply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);auto.\n  clear -Hljoin H0 Hmjoin H2.\n  destruct o as [[[[]]]].\n  simpl in *.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts H2.\n  unfolds in Hljoin.\n  mytac.\n  geat.\n  clear -Hhjoin Hhjoin' H18.\n  unfolddef.\n  geat.\n  apply hpstep_eqdomto in Hpstepstar;auto.\n  unfold eqdomTO in *.\n  clear -Hpstepstar.\n  mytac.\n  eexists;split;eauto.\n \n  rewrite abst_set_get_neq in H;auto.\n \n\n  destruct H0 as (Cn&Hcn).\n  rewrite tasks_set_get_neq in Hcn;auto.\n  assert (TasksMod.get Th t' = Some Cn) as Hcode;auto.\n  apply Hrsim in Hcn;auto.\n  destruct Hcn as (on&Mn&Cn'&On&Htmn&Hton&Hprojn&Hlinvn&Htasksn&Hcn).\n  assert (disjoint Mc' Ms).\n  clear -Hljoin Hmjoin Hmpart Htm.\n  destruct o.\n  destruct p.\n  destruct p.\n  destruct p.\n  simpl in *.\n  unfold joinmem in *.\n  mytac.\n  assert (disjoint x2 Ms). \n  apply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);auto.\n  unfolddef.\n  clear -Hmjoin.\n  geat.\n  clear -H1 H.\n  unfolddef.\n  geat.\n  \n\n  assert (exists Mcc,store (Tptr tp) Mc' (b,0%Z) (Vptr t') = Some Mcc).\n  rename HHHH into Hswpre.\n  destruct o as [[[[]]]];unfold substaskst in Hswpre.\n  assert ((e, e0, Mc', i, l0, Occ, (spec_done None)) |= SWPRE (snd A) x t);auto.\n  eapply swpre_store with (ab:=spec_done None);eauto.\n  clear -Hproj H9.\n  simpl in Hproj.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts Hproj.\n  unfold get in H9;simpl in H9;auto.\n  destruct H21 as (Mcc&Hmcc).\n  \n\n  lets Hx:aux_atrue Hlinv'.\n  destruct Hx as (o1&M2&O1&O2&Hjoinf&Hjoinof&Hlinvf).\n\n  eapply swi_rdy_inv_dead with (o:=o) (Ol:=Occ) (Os:=Os') (OO:=merge O' Os') (I:=I) (t:=t) (t':=t') (S:=(ge, les, m, ir, au)) (Ms:=Ms) (o':=on) (tp:=tp) (Mcc:=Mcc) (b:=b) (sc:=snd A) (o1:=o1) (M2:=M2) (O1:=O1) (O2:=O2) (li:=lasrt)in H0;eauto.\n       \n  destruct H0 as (Mc'0&Ms'&Oc'0&Os''&OO''&Olx'&Hndisj&Hnmerge&Hnojoin&Hnojoinx&Hnoset&H0).\n  exists pc A po pi ip.\n  exists (TMSpecMod.put (TMSpecMod.put Tm t M2) t' (merge Mn Mc'0))\n         (TOSpecMod.put (TOSpecMod.put To t O2) t' (merge On Oc'0))\n         ((merge (merge Oc'0 O2) (minus Ol Oc))) Os''.\n  exists Ms' (merge (merge (minus Ml Mc) M2) Mc'0) I lasrt.\n  assert (Maps.sub Mc' Mc).\n  clear -Hljoin.\n  destruct o as [[[[]]]].\n  unfold joinmem in Hljoin.\n  simpl in Hljoin.\n  mytac.\n  unfolddef.\n  unfold Maps.sub.\n  geat.\n  assert (Maps.sub Mc Ml).\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  \n  lets Hsubtrans: sub_trans H21 H22.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  eapply lpstep_goodks;eauto.\n  clear -Hgoodiss.\n  unfold good_is_S in *.\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  assert (projS (ge, les, m, ir, au) t = Some (e, e0, m, i, (i0, i1, c))).\n  unfold projS in *.\n  unfold projD in *.\n  unfolddef.\n  destruct (get les t);tryfalse;auto.\n  destruct (get au t);tryfalse;auto.\n  inverts H;auto.\n  apply Hgoodiss in H0.\n  auto.\n  simpl.\n\n  eapply mem_join_merge_minus_join_store'f with (Ms:=Ms) (Mc:=Mc) (Mcc:=Mcc) (Mc'0:=Mc'0) (m':=m');eauto.\n  eapply partm_task_get_set;eauto.\n  apply partm_merge_disj.\n\n  eapply disj'f;eauto.\n  (*\n  assert (Maps.sub Mc'0 (merge Mc'0 Ms')).\n  apply sub_merge_l;auto.\n  rewrite Hnmerge in H23.\n(* ** ac:   Check  store_sub_minus_eq. *)\n  erewrite store_sub_minus_eq ;eauto.\n\n  eapply store_sub_disj_disj with (M2:=Mc') (Ms:=Ms) ;eauto.\n  clear -Hmjoin.\n  simpl in *;unfolds.\n  join auto.\n  *)\n  unfold TMSpecMod.maps_to.\n  unfold TMSpecMod.put.\n  destruct TMSpecMod.beq_A;tryfalse.\n  unfold TMSpecMod.maps_to in Htmn;auto.\n  apply partm_minus_subf;auto.\n  clear - Hjoinf Hljoin.\n  destruct ol as [[[[]]]].\n  destruct o as [[[[]]]].\n  simpl in *.\n  unfold joinmem in *.\n  mytac.\n  unfolds.\n  join auto.\n  \n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  \n\n  eapply join_complexf with (OO'0:=OO') (O'0:=O');eauto.\n\n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  eapply parto_task_get_set;eauto.\n  eapply parto_complex;eauto.\n  unfolds;eauto.\n  eapply disj_complex'f with (O1:=O1) (O2:=O2) (Olx':=Olx') ;eauto.\n  \n  exists (substaskst on m') (substaskst on Ms').\n  splits;auto.\n  destruct on as [[[[]]]].\n  clear -Hprojn.\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t');tryfalse.\n  destruct (get au t');tryfalse.\n  inverts Hprojn.\n  simpl;auto.\n  apply repl_change_tstm_trans.\n\n  destruct H0;auto.\n  \n  assert (get Occ curtid = Some (oscurt t)).\n  clear -Hgoodi Hswinv.\n  unfolds in Hgoodi.\n  mytac.\n  unfolds in Hswinv.\n  lets Hx:Hswinv (spec_done None).\n  eapply H0 in Hx.\n  mytac.\n  auto.\n  exists (substaskst on m') ( substaskst on (merge Mn Mc'0)) (merge Mn Mc'0) (merge On Oc'0) Cn' Cn.\n  splits;auto.\n  clear -Hprojn.\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t');tryfalse.\n  destruct (get au t');tryfalse.\n  inverts Hprojn.\n  simpl;auto.\n  destruct on as [[[[]]]];simpl;auto.\n  rewrite tasks_set_get_neq;auto.\n  rewrite tasks_set_get_neq;auto.\n  destruct H0.\n  eapply switch_linv;eauto.\n  destruct ol as [[[[]]]].\n  destruct o as [[[[]]]].\n  eapply disj_complex''f with (t:=t) (t':=t');eauto.\n  instantiate (1:=m0).\n  clear -Hjoinf.\n  unfolds in Hjoinf;mytac.\n  unfold getmem.\n  simpl.\n  unfolds;eauto.\n  unfolds in Hljoin.\n  mytac.\n  simpl in H26;inverts H26.\n  eauto.\n  eapply disj_complex'''f with (O1:=O1) (O2:=O2) (Occ:=Occ) (Olx':=Olx');eauto.\n  \n  assert ( (forall ab : absop, (substaskst on Ms', Os'', ab) |= INV I) /\\\n           (forall ab : absop, (substaskst on Mc'0, Oc'0, ab) |= RDYINV I t')) as H177;auto.\n  destruct H0.\n\n  assert ( (forall ab : absop, (RdyChange (substaskst on Mc'0), Oc'0, ab) |= RDYINV I t') /\\ disjoint Mc'0 Mn /\\ disjoint Oc'0 On).\n  split.\n  assert (RdyChange (substaskst on Mc'0)=substaskst on Mc'0).\n  eapply rdyinv_isremp with (I:=I) (O:=Oc'0) (M:=Mc'0);eauto.\n  rewrite H25;auto.\n  split.\n  destruct ol as [[[[]]]].\n  destruct o as [[[[]]]].\n  eapply disj_complex''f with (t:=t);eauto.\n  instantiate (1:=m0).\n  clear -Hjoinf.\n  unfolds in Hjoinf;mytac.\n  unfold getmem.\n  simpl.\n  unfolds;eauto.\n  unfolds in Hljoin.\n  mytac.\n  simpl in H28;inverts H28.\n  eauto.\n  eapply disj_complex'''f;eauto.\n  assert (exists M'',\n            M'' = merge Mc'0 Mn /\\\n            TaskSim (pc, (po, pi, ip)) Cn' (RdyChange (substaskst on M''))\n                    (pc, A) Cn (merge Oc'0 On) lasrt I (InitTaskSt lasrt t') t').\n  apply Hcn.\n  auto.\n\n  destruct H26 as (M''&Hm''merge&Htsim).\n  rewrite Hm''merge in Htsim.\n  assert (RdyChange (substaskst on (merge Mc'0 Mn))=substaskst on (merge Mc'0 Mn)).\n  eapply rdyinv_isremp with (I:=I) (O:=Oc'0) (M:=Mc'0);eauto.\n  rewrite H26 in Htsim.\n\n  destructs H25.\n  assert (merge Mc'0 Mn = merge Mn Mc'0).\n  rewrite disjoint_merge_sym;auto.\n  assert (merge Oc'0 On = (merge On Oc'0)).\n  rewrite disjoint_merge_sym;auto.\n  rewrite <- H29.\n  rewrite <- H30.\n  auto.\n\n  splits;auto.\n  intros.\n  rename H25 into Hdead.\n  destruct (tid_eq_dec t'0 t).\n  \n  subst t'0.\n  assert (task_no_dead x0 t).\n  clear -Hdead.\n  unfolds.\n  unfolds in Hdead.\n  intros.\n  apply Hdead.\n  rewrite map_get_set';auto.\n\n  false.\n  eapply nodead_swpredead_false;eauto.\n  clear -Hhjoin Hhjoin' H18.\n  unfolddef.\n  unfolddef.\n  join auto.\n\n  assert (t'0<>t) as Htneq;auto.\n  apply Hrsim with (Ch:=Ch0) in n0.\n  destruct n0 as (or&Mr'&Clr&Or'&Htmr&Htor&Hprojr&Hlinv''&Htsr&n0).\n  exists (substaskst or m') Mr' Clr Or'.\n  splits;auto.\n  unfold TMSpecMod.maps_to, TMSpecMod.put.\n  destruct TMSpecMod.beq_A;tryfalse;auto.\n  destruct TMSpecMod.beq_A;tryfalse;auto.\n  unfold TOSpecMod.maps_to, TOSpecMod.put.\n  destruct TOSpecMod.beq_A;tryfalse;auto.\n  destruct TOSpecMod.beq_A;tryfalse;auto.\n  \n  clear -Hprojr.\n  destruct or as [[[[]]]].\n  unfold projS in *;unfold projD in *.\n  unfolddef.\n  destruct (get les t'0);tryfalse;destruct (get au t'0 );tryfalse.\n  inverts Hprojr;simpl;auto.\n  rewrite repl_change_tstm_trans;auto.\n  rewrite tasks_set_get_neq;auto.\n  intros.\n  assert (substaskst (substaskst or m') Mr= substaskst or Mr).\n  apply change_tstm_trans';auto. \n  rewrite H26 in H25.\n  eapply n0 in H25;eauto.\n  destruct H25.\n  exists x2.\n  assert (substaskst (substaskst or m') x2= substaskst or x2).\n  apply change_tstm_trans';auto. \n  rewrite H27.\n  auto.\n\n  rewrite tasks_set_get_neq in H24;auto.\n  eapply htstepstar_nodead_still;eauto.\n  clear -Hdead.\n  unfolds.\n  unfolds in Hdead.\n  intros.\n  apply Hdead.\n  rewrite map_get_set';auto.\n  apply hpstep_eqdomto in Hpstepstar;auto.\n  apply join_merge_disj.\n  clear -Hhjoin Hhjoin'.\n  unfolddef.\n  geat.\n\n  apply disj_sym.\n  eapply part_disjm;eauto.\n  unfolds;eauto.\n  clear -H9 Hproj.\n  destruct o as [[[[]]]].\n  simpl in *.\n  unfolddef.\n  destruct (get les t);tryfalse.\n  destruct (get au t);tryfalse.\n  inverts Hproj.\n  auto.\n  eapply htstepstar_nodead_still;eauto.\n  eapply AHprio_local with (O:=x0) in H19.\n  eapply ahprio_nodead;eauto.\n  clear -Hhjoin Hhjoin' H18.\n  unfolddef.\n  unfolddef.\n  join auto.\n  \n  (*-----------------------------switch case end-------------------------------*)\n\n  (*-----------------------------stkinit step--------------------------------------*)\n  subst t'.\n  subst.\n  inversion H0;subst pc0 po0 pi0 ip0;clear H0.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubst&Htgeth&Htgetl&Hlinv&Hcsim).\n  unfolddef.\n  rewrite Htgetl in H1;inverts H1.\n  inverts Hcsim.\n  assert ( (curs (sprim (stkinit e1 e2 e3)), (kenil, ks)) =  (curs (sprim (stkinit e1 e2 e3)), (kenil, ks))) by auto.\n  destruct o as [[[[]]]].\n  rewrite Hproj in H13;inverts H13.\n  simpl in Hsubst.\n  subst o'.\n  simpl substaskst in *.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  eapply H12 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os)in H15;eauto.\n  Focus 2.\n  unfold getmem;simpl.\n  eapply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  clear -Hmjoin.\n  simpl in Hmjoin.\n  unfolddef;geat.\n  Focus 2.\n  apply join_merge_disj.\n  eapply part_disjo with (M:=Ol) (T:=Tl) (Tm:=To) (t:=t);eauto.\n  clear -HOjoin.\n  unfolddef;geat.\n  destruct H15 as (Ch'&v11&v12&t'&p&sh&k&OO'&OO''&ol&Mcre&O'&Os'&Olc&Ocre&H15).\n  mytac.\n  subst.\n  destruct Sl as [[[[]]]].\n  simpl in Hproj.\n  unfolddef.\n  remember (get c t) as getle.\n  destruct getle;tryfalse.\n  remember (get l t) as getaux.\n  destruct getaux;tryfalse.\n  simpl get_smem in *.\n  simpl snd in *.\n  simpl fst in *.\n  inverts Hproj.\n  assert (Maps.sub Mc Ml).\n  eapply part_sub;eauto.\n  assert (Maps.sub Mc m).\n  eapply sub_trans;eauto.\n  clear -Hmjoin.\n  unfolds.\n  geat.\n  unfolds in H27.\n  destruct H27.\n  simpl in H15.\n  lets Hx:evalval_mono H27 H15.\n  rewrite Hx in *.\n  rewrite H15 in H5;inverts H5.\n  clear Hx.\n  simpl in H16.\n  lets Hx:evalval_mono H27 H16.\n  rewrite Hx in *.\n  rewrite H16 in H6;inverts H6.\n  clear Hx.\n  simpl in H17.\n  lets Hx:evalval_mono H27 H17.\n  rewrite Hx in *.\n  rewrite H17 in H7;inverts H7.\n  clear Hx.\n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) (cst:=(ge, cenvs, M)) in H18.\n  destruct H18.\n  destruct H5 as (Hhtstepstar&Hjoin').\n  assert (htstepstar (pc, A) t Ch (ge, cenvs, M) O\n                  (curs (hapi_code (spec_crt v1 v (Vint32 p);; sh)), k)\n                  (ge, cenvs, M) x0) as Htstepstar;auto.\n  eapply th_no_create_lift in Hhtstepstar;eauto.\n  destruct k as (keh,ksh).\n  inverts H19.\n  mytac.\n  assert (hpstepstar  (pc, A) Th (ge, cenvs, M) O (set (set Th t\n                     (curs (hapi_code  sh), (keh,ksh))) t'0 (nilcont s)) (ge, set cenvs t'0 le, M') (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc)) ).\n\n  eapply hpstep_star;eauto.\n  assert ((set Th t (curs (hapi_code sh), (keh,ksh))) = set (set Th t (curs (hapi_code (spec_crt v1 v (Vint32 p);; sh)), (keh,ksh))) t (curs (hapi_code sh), (keh,ksh))).\n\n  apply set_set_eq.\n  rewrite H19.\n  eapply hpcrt_step;eauto.\n  apply map_get_set.\n  eapply join_get_get_l;eauto.\n  eapply join_get_get_l;eauto.\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  symmetry.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n  clear -H18.\n  unfold joinsig in *.\n  join auto.\n  do 2 eexists;split;eauto.\n\n  assert (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc) = set x0 abtcblsid (abstcblist x2)).\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n\n  rewrite H28 in *.\n  apply CIH;auto.\n  rewrite <-Hosabsttid.\n  apply htstepstar_tidsame in Htstepstar.\n  unfold tidsame in Htstepstar.\n  unfolddef.\n  rewrite Htstepstar.\n  apply map_get_set';auto.\n\n  destruct ol as [[[[]]]].\n  unfolds in H20.\n  do 6 destruct H20.\n  destructs H20.\n  inversion H29;subst x3 x4 x6 x7 x8;clear H29.\n  inversion H20;subst e4 e5 x5 i l0;clear H20.\n  rename m0 into Mlc.\n  exists pc A po pi ip.\n  rename t'0 into t'.\n  exists (TMSpecMod.put (TMSpecMod.put Tm t Mlc) t' Mcre)\n         (TOSpecMod.put (TOSpecMod.put To t Olc) t' Ocre)\n         ((merge O' (minus Ol Oc))) Os'.\n  exists Ms Ml I lasrt.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  \n  eapply lpstep_goodks;eauto.\n  clear -Hgoodiss.\n  unfold good_is_S in *.\n  unfold Snewt.\n  unfold Dnewt.\n  unfold Tlnewt.\n  simpl.\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l0.\n  destruct p.\n  assert (t =t' \\/ t <> t') by tauto.\n  destruct H0.\n  subst t'.\n  unfolddef.\n  rewrite map_get_set in H.\n  rewrite map_get_set in H.\n  inverts H.\n  simpl;auto.\n  rewrite map_get_set' in H;auto.\n  rewrite map_get_set' in H;auto.\n  \n  assert (projS (e, c, m, ir, l) t = Some (e0, e1, m, i, (i0, i1, c0))).\n  unfold projS in *.\n  unfold projD in *.\n  unfolddef.\n  destruct (get c t);tryfalse;auto.\n  destruct (get l t);tryfalse;auto.\n  inverts H;auto.\n  apply Hgoodiss in H1.\n  auto.\n\n\n  eapply crt_partm;eauto.\n\n  eapply join_crt;eauto.\n\n  eapply crt_parto;eauto.\n  exists (e,e0,m,ir,au) (e,e0,Ms,ir,au).\n  splits;simpl;auto.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetle.\n  unfold Tlnewt.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetaux.\n  auto.\n\n  (*------------current task------------------*)\n  exists (e,e0,m,ir,au) (e,e0,Mlc,ir,au) Mlc Olc  (SKIP , (kenil, ks)) (curs (hapi_code sh), (keh, ksh)).\n  splits;simpl;auto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetle.\n  unfold Tlnewt.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetaux.\n  auto.\n  rewrite map_get_set';auto.\n  apply map_get_set.\n  rewrite map_get_set';auto.\n  apply map_get_set.\n\n  splits;auto.\n  intros.\n  assert (t'0 = t' \\/ t'0 <> t') by tauto.\n  (* ---------- new task ---------------*)\n  destruct H32.\n  subst t'0.\n  unfold Snewt.\n  unfold Dnewt, Tlnewt.\n  exists (e,(empenv:env),m,ir,(true,(nil:is),(nil:cs))) Mcre (nilcont s) Ocre.\n  splits;auto.\n  simpl.\n  rewrite map_get_set.\n  rewrite map_get_set.\n  auto.\n\n\n  simpl substaskst.\n  eapply linv_change_linv_aux with (e':=empenv) (aux':=(true,nil,nil)) (ir':=ir) in H25;eauto.\n  clear -H25.\n  unfold LINV.\n  exists init_lg.\n  unfolds in H25.\n  lets Hx:H25 aop.\n  sep auto.\n  apply map_get_set.\n\n  intros.\n  eexists;split;eauto.\n  simpl RdyChange.\n  rewrite map_get_set in H29;inverts H29.\n  eapply SmCTaskSim;eauto.\n  unfolds.\n  simpl.\n  destructs H32.\n  simpl RdyChange in H29.\n\n  split;auto.\n  eapply crt_init;eauto.\n  eapply linv_change_linv_aux;eauto.\n  eexists;splits;eauto.\n  simpl;auto.\n  clear -Hgoodpc H9.\n  unfolds in  Hgoodpc.\n  mytac.\n  eapply H;eauto.\n\n  (*-----------other tasks-------------*)\n  rewrite map_get_set' in H29;auto.\n  rewrite map_get_set' in H29;auto.\n  assert (t'0<>t) by auto.\n  eapply Hrsim in H20;eauto.\n  mytac.\n  exists x3 x4 x5 x6.\n  splits;auto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  unfold Snewt.\n  unfold Dnewt,Tlnewt;simpl.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  eapply htstepstar_nodead_still;eauto.\n  \n  \n  clear -H32 H31 H18 H7 Hjoin'.\n  assert (get x0 abtcblsid = Some (abstcblist x1)).\n  eapply join_get_l;eauto.\n  unfold task_no_dead in *.\n  intros.\n  rewrite H in H0;inverts H0.\n  eapply joinsig_indom_neq;eauto.  \n  apply H31.\n  rewrite map_get_set;auto.\n\n  apply hpstep_eqdomto in H19;auto.\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n\n  (*-----------------------------stkinit skip step--------------------------------------------*)\n  subst t'.\n  subst.\n  inversion H0;subst pc0 po0 pi0 ip0;clear H0.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubst&Htgeth&Htgetl&Hlinv&Hcsim).\n  unfolddef.\n  rewrite Htgetl in H1;inverts H1.\n  inverts Hcsim.\n  assert ( (curs (sprim (stkinit e1 e2 e3)), (kenil, ks)) =  (curs (sprim (stkinit e1 e2 e3)), (kenil, ks))) by auto.\n  destruct o as [[[[]]]].\n  rewrite Hproj in H12;inverts H12.\n  simpl in Hsubst.\n  subst o'.\n  simpl substaskst in *.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  eapply H11 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os)in H14;eauto.\n  Focus 2.\n  unfold getmem;simpl.\n  eapply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  clear -Hmjoin.\n  simpl in Hmjoin.\n  unfolddef;geat.\n  Focus 2.\n  apply join_merge_disj.\n  eapply part_disjo with (M:=Ol) (T:=Tl) (Tm:=To) (t:=t);eauto.\n  clear -HOjoin.\n  unfolddef;geat.\n  destruct H14 as (Ch'&v11&v12&t'&p&sh&k&OO'&OO''&ol&Mcre&O'&Os'&Olc&Ocre&H14).\n  mytac.\n  subst.\n  destruct Sl as [[[[]]]].\n  simpl in Hproj.\n  unfolddef.\n  remember (get c t) as getle.\n  destruct getle;tryfalse.\n  remember (get l t) as getaux.\n  destruct getaux;tryfalse.\n  simpl get_smem in *.\n  simpl snd in *.\n  simpl fst in *.\n  inverts Hproj.\n  assert (Maps.sub Mc Ml).\n  eapply part_sub;eauto.\n  assert (Maps.sub Mc m).\n  eapply sub_trans;eauto.\n  clear -Hmjoin.\n  unfolds.\n  geat.\n\n  unfolds in H26.\n  destruct H26.\n  simpl in H14.\n  lets Hx:evalval_mono H26 H14.\n  rewrite Hx in *.\n  rewrite H14 in H5;inverts H5.\n  clear Hx.\n  simpl in H15.\n  lets Hx:evalval_mono H26 H15.\n  rewrite Hx in *.\n  rewrite H15 in H6;inverts H6.\n  clear Hx.\n  simpl in H16.\n  lets Hx:evalval_mono H26 H16.\n  rewrite Hx in *.\n  rewrite H16 in H7;inverts H7.\n  clear Hx.\n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) (cst:=(ge, cenvs, M)) in H17.\n  destruct H17.\n  destruct H5 as (Hhtstepstar&Hjoin').\n  assert (htstepstar (pc, A) t Ch (ge, cenvs, M) O\n                  (curs (hapi_code (spec_crt v1 v (Vint32 p);; sh)), k)\n                  (ge, cenvs, M) x0) as Htstepstar;auto.\n  eapply th_no_create_lift in Hhtstepstar;eauto.\n  destruct k as (keh,ksh).\n  inverts H18.\n  mytac.\n\n  assert (hpstepstar  (pc, A) Th (ge, cenvs, M) O (set (set Th t\n                     (curs (hapi_code  sh), (keh,ksh))) t'0 (nilcont (sskip None))) (ge, cenvs, M) (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc)) ).\n\n  eapply hpstep_star;eauto.\n  assert ((set Th t (curs (hapi_code sh), (keh,ksh))) = set (set Th t (curs (hapi_code (spec_crt v1 v (Vint32 p);; sh)), (keh,ksh))) t (curs (hapi_code sh), (keh,ksh))).\n  apply set_set_eq.\n  rewrite H18.\n  eapply hpcrtskip_step;eauto.\n  apply map_get_set.\n  eapply join_get_get_l;eauto.\n  eapply join_get_get_l;eauto.\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  symmetry.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n  clear -H17.\n  unfold joinsig in *.\n  join auto.\n  do 2 eexists;split;eauto.\n\n  assert (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc) = set x0 abtcblsid (abstcblist x2)).\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n\n  rewrite H27 in *.\n  apply CIH;auto.\n  rewrite <-Hosabsttid.\n  apply htstepstar_tidsame in Htstepstar.\n  unfold tidsame in Htstepstar.\n  unfolddef.\n  rewrite Htstepstar.\n  apply map_get_set';auto.\n\n  destruct ol as [[[[]]]].\n  unfolds in H19.\n  do 6 destruct H19.\n  destructs H19.\n  inversion H28;subst x3 x4 x6 x7 x8;clear H28.\n  inversion H19;subst e4 e5 x5 i l0;clear H19.\n  rename m0 into Mlc.\n  exists pc A po pi ip.\n  rename t'0 into t'.\n  exists (TMSpecMod.put (TMSpecMod.put Tm t Mlc) t' Mcre)\n         (TOSpecMod.put (TOSpecMod.put To t Olc) t' Ocre)\n         ((merge O' (minus Ol Oc))) Os'.\n  exists Ms Ml I lasrt.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  \n  eapply lpstep_goodks;eauto.\n  clear -Hgoodiss.\n  unfold good_is_S in *.\n  unfold Snewt.\n  unfold Dnewt.\n  unfold Tlnewt.\n  simpl.\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l0.\n  destruct p.\n  assert (t =t' \\/ t <> t') by tauto.\n  destruct H0.\n  subst t'.\n  unfolddef.\n  rewrite map_get_set in H.\n  rewrite map_get_set in H.\n  inverts H.\n  simpl;auto.\n  rewrite map_get_set' in H;auto.\n  rewrite map_get_set' in H;auto.\n  \n  assert (projS (e, c, m, ir, l) t = Some (e0, e1, m, i, (i0, i1, c0))).\n  unfold projS in *.\n  unfold projD in *.\n  unfolddef.\n  destruct (get c t);tryfalse;auto.\n  destruct (get l t);tryfalse;auto.\n  inverts H;auto.\n  apply Hgoodiss in H1.\n  auto.\n  eapply crt_partm;eauto.\n  eapply join_crt;eauto.\n  eapply crt_parto;eauto.\n  exists (e,e0,m,ir,au) (e,e0,Ms,ir,au).\n  splits;simpl;auto.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetle.\n  unfold Tlnewt.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetaux.\n  auto.\n\n  (*------------current task------------------*)\n  exists (e,e0,m,ir,au) (e,e0,Mlc,ir,au) Mlc Olc  (SKIP , (kenil, ks)) (curs (hapi_code sh), (keh, ksh)).\n  splits;simpl;auto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetle.\n  unfold Tlnewt.\n  rewrite map_get_set';auto.\n  rewrite <- Heqgetaux.\n  auto.\n  rewrite map_get_set';auto.\n  apply map_get_set.\n  rewrite map_get_set';auto.\n  apply map_get_set.\n\n  splits;auto.\n  intros.\n  assert (t'0 = t' \\/ t'0 <> t') by tauto.\n  (* ---------- new task ---------------*)\n  destruct H31.\n  subst t'0.\n  unfold Snewt.\n  unfold Dnewt, Tlnewt.\n  exists (e,(empenv:env),m,ir,(true,(nil:is),(nil:cs))) Mcre (nilcont (sskip None)) Ocre.\n  splits;auto.\n  simpl.\n  rewrite map_get_set.\n  rewrite map_get_set.\n  auto.\n  simpl substaskst.\n  eapply linv_change_linv_aux with (e':=empenv) (aux':=(true,nil,nil)) (ir':=ir) in H24;eauto.\n  clear -H24.\n  unfold LINV.\n  exists init_lg.\n  unfolds in H24.\n  lets Hx:H24 aop.\n  sep auto.\n  apply map_get_set.\n\n  intros.\n  eexists;split;eauto.\n  simpl RdyChange.\n  rewrite map_get_set in H28;inverts H28.\n  eapply SmCTaskSim;eauto.\n  unfolds.\n  simpl.\n  destructs H31.\n  simpl RdyChange in H28.\n  split;auto.\n  eapply crt_init;eauto.\n  eapply linv_change_linv_aux;eauto.\n  eexists;splits;eauto.\n  simpl;auto.\n\n  (*-----------other tasks-------------*)\n  rewrite map_get_set' in H28;auto.\n  rewrite map_get_set' in H28;auto.\n  assert (t'0<>t) by auto.\n  eapply Hrsim in H19;eauto.\n  mytac.\n  exists x3 x4 x5 x6.\n  splits;auto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  unfold Snewt.\n  unfold Dnewt,Tlnewt;simpl.\n  unfolddef.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  rewrite map_get_set';auto.\n  eapply htstepstar_nodead_still;eauto.\n  \n  \n  clear -H31 H30 H17 H7 Hjoin'.\n  assert (get x0 abtcblsid = Some (abstcblist x1)).\n  eapply join_get_l;eauto.\n  unfold task_no_dead in *.\n  intros.\n  rewrite H in H0;inverts H0.\n  \n  eapply joinsig_indom_neq;eauto.\n  apply H30;rewrite map_get_set;auto.\n  apply hpstep_eqdomto in H18;auto.\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n  \n  (*------------------------------stkfree case----------------------------------------*)\n  subst t'.\n  subst.\n  \n  inversion H0;subst pc0 po0 pi0 ip0;clear H0.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubst&Htgeth&Htgetl&Hlinv&Hcsim).\n  unfolddef.\n  rewrite Htgetl in H1;inverts H1.\n  inverts Hcsim.\n  assert ( (curs (sprim (stkfree e)), (kenil, ks)) =  (curs (sprim (stkfree e)), (kenil, ks))) by auto.\n  destruct o as [[[[]]]].\n  rewrite Hproj in H8;inverts H8.\n  simpl in Hsubst.\n  subst o'.\n  simpl substaskst in *.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  eapply H6 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os)in H9;eauto.\n  Focus 2.\n  unfold getmem;simpl.\n  eapply part_disjm with (M:=Ml) (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  clear -Hmjoin.\n  simpl in Hmjoin.\n  unfolddef;geat.\n  Focus 2.\n  apply join_merge_disj.\n  eapply part_disjo with (M:=Ol) (T:=Tl) (Tm:=To) (t:=t);eauto.\n  clear -HOjoin.\n  unfolddef;geat.\n  destruct H9 as (Ch'&p&sh&k&t'&OO'&OO''&O'&Os'&H9).\n  mytac.\n  subst.\n  destruct S' as [[[[]]]].\n  simpl in Hproj.\n  unfolddef.\n  remember (get c t) as getle.\n  destruct getle;tryfalse.\n  remember (get l t) as getaux.\n  destruct getaux;tryfalse.\n  simpl get_smem in *.\n  simpl snd in *.\n  simpl fst in *.\n  inverts Hproj.\n  assert (Maps.sub Mc Ml).\n  eapply part_sub;eauto.\n  rename m0 into m.\n  assert (Maps.sub Mc m).\n  eapply sub_trans;eauto.\n  clear -Hmjoin.\n  unfolds.\n  geat.\n\n  unfolds in H12.\n  destruct H12.\n  simpl in H9.\n  lets Hx:evalval_mono H12 H9.\n  rewrite Hx in *.\n  rewrite H7 in H9;inverts H9.\n  clear Hx.\n\n  eapply htstepstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) (cst:=(ge, cenvs, M)) in H10.\n  destruct H10.\n  destruct H9 as (Hhtstepstar&Hjoin').\n  assert (htstepstar (pc, A) t Ch (ge, cenvs, M) O\n                  (curs (hapi_code (spec_del (Vint32 p);; sh)), k)\n                  (ge, cenvs, M) x0) as Htstepstar;auto.\n  eapply th_no_create_lift in Hhtstepstar;eauto.\n  destruct k as (keh,ksh).\n\n  destruct H11.\n  (*-------------------stkfree self----------------------*)\n  mytac.\n  inverts H9.\n  rename t' into t.\n  mytac.\n  inverts H15;mytac.\n  assert (hpstepstar  (pc, A) Th (ge, cenvs, M) O  (set Th t\n                     (curs (hapi_code sh), (keh,ksh))) (ge, del cenvs t, M) (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc)) ).\n\n  eapply hpstep_star;eauto.\n  eapply hpdel_step;eauto.\n  apply map_get_set.\n  erewrite <- set_set_eq;eauto.\n  eapply join_get_get_l;eauto.\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  symmetry.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n  unfolds in H16.\n  eapply join_get_get_l;eauto.\n  eapply map_get_sig.\n  unfold joinsig in H16.\n  clear -H16.\n  join auto.\n  eapply join_get_l;eauto.\n  do 2 eexists;split;eauto.\n  assert (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc) = set x0 abtcblsid (abstcblist x2)).\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n\n  rewrite H18 in *.\n  apply CIH;auto.\n  rewrite <-Hosabsttid.\n  apply htstepstar_tidsame in Htstepstar.\n  unfold tidsame in Htstepstar.\n  unfolddef.\n  rewrite Htstepstar.\n  apply map_get_set';auto.\n\n  exists pc A po pi ip.\n  exists Tm\n         (TOSpecMod.put To t O')\n         (merge O' (minus Ol Oc)) Os'.\n  exists Ms Ml I lasrt.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  \n  eapply lpstep_goodks;eauto.\n  eapply partm_task_get_set;eauto.\n  eapply join_crt;eauto.\n  eapply new_part_o;eauto.\n\n  eapply get_set_join_disj_l;eauto.\n  eapply parto_task_get_set;eauto.\n  exists (e0,e1,m,ir,au) (e0,e1,Ms,ir,au).\n  splits;auto.\n  unfolds.\n  unfold projD.\n  unfolddef.\n  rewrite <- Heqgetle.\n  rewrite <- Heqgetaux.\n  auto.\n  exists (e0,e1,m,ir,au) (e0,e1,Mc,ir,au) Mc O' (SKIP , (kenil, ks)) (curs (hapi_code sh), (keh, ksh)).\n  splits;auto.\n  unfolds.\n  unfold projD.\n  unfolddef.\n  rewrite <- Heqgetle.\n  rewrite <- Heqgetaux.\n  auto.\n  apply map_get_set.\n  apply map_get_set.\n\n  splits;auto.\n  intros.\n  rewrite map_get_set' in H20;auto.\n  apply Hrsim in H20;auto.\n  mytac.\n  do 4 eexists;splits;eauto.\n  apply TOSpecMod.mapsto_mapsto_put;auto.\n  rewrite map_get_set';auto.\n  eapply htstepstar_nodead_still;eauto.\n  eapply join_get_get_l in H15;eauto.\n  clear -H15 H16 H21.\n  unfold task_no_dead in *.\n  intros.\n  unfolddef.\n  rewrite H in H15;inverts H15.\n  rewrite map_get_set in H21.\n  assert (Some (abstcblist x2) = Some (abstcblist x2)) by auto.\n  apply H21 in H0.\n  unfolds in H16.\n  unfold indom in *.\n  mytac.\n  eexists.\n  eapply join_get_get_r;eauto.\n  eapply hpstep_eqdomto;eauto.\n  \n  (*-------------------stkfree other----------------------*)\n  mytac.\n  inverts H9.\n  mytac.\n  inverts H16;mytac.\n  assert (hpstepstar  (pc, A) Th (ge, cenvs, M) O  (set Th t\n                     (curs (hapi_code sh), (keh,ksh))) (ge, del cenvs t', M) (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc)) ).\n\n  eapply hpstep_star;eauto.\n  eapply hpdel_step with (t':=t');eauto.\n  apply map_get_set.\n  erewrite <- set_set_eq;eauto.\n  eapply join_get_get_l;eauto.\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  symmetry.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n  unfolds in H17.\n  eapply join_get_get_l;eauto.\n  eapply map_get_sig.\n  unfold joinsig in H17.\n  clear -H17.\n  join auto.\n  eapply join_get_l;eauto.\n  do 2 eexists;split;eauto.\n  assert (merge (set OO' abtcblsid (abstcblist x2)) (minus Ol Oc) = set x0 abtcblsid (abstcblist x2)).\n  assert (x0 = merge OO' (minus Ol Oc)).\n  apply map_join_merge';auto.\n  subst x0.\n  eapply join_merge_set_eq;eauto.\n\n  rewrite H19 in *.\n  apply CIH;auto.\n  rewrite <-Hosabsttid.\n  apply htstepstar_tidsame in Htstepstar.\n  unfold tidsame in Htstepstar.\n  unfolddef.\n  rewrite Htstepstar.\n  apply map_get_set';auto.\n\n  assert (task_no_dead O t').\n  eapply htstepstar_nodead_still;eauto.\n  eapply join_get_get_l in H16;eauto.\n  clear -H16 H17.\n  unfolds.\n  intros.\n  unfolddef;rewrite H in H16;inverts H16.\n  unfolds.\n  unfolds in H17.\n  eexists.\n  eapply join_get_get_l;eauto.\n  apply map_get_sig;auto.\n  assert (exists Ch,get Th t' = Some Ch).\n  eapply hpstep_eqdomto with (O':=x0)in Heqdomto;eauto.\n  eapply join_get_get_l in H16;eauto.\n  clear -H17 H16 Heqdomto H15.\n  unfolds in Heqdomto.\n  mytac.\n  unfolddef.\n  auto.\n  rewrite H16 in H;inverts H.\n  assert (get x t' = Some (p,x3,x4)).\n  unfolds in H17.\n  eapply join_get_get_l in H17;eauto.\n  apply map_get_sig.\n  assert (exists y,get x t' = Some y) by eauto.\n  eapply H0 in H1.\n  mytac.\n  rewrite map_get_set' in H1;eauto.\n  mytac.\n  assert (t'<>t) by auto.\n  lets Hx:Hrsim H22 H21 H20.\n  destruct Hx as (od&Md&Cld&Od&Hx).\n  mytac.\n  destruct od as [[[[]]]].\n  unfold projS in H25.\n  unfold projD in H25.\n  unfolddef.\n  remember (get c t') as Hled.\n  remember (get l t') as Hauxd.\n  destruct Hled;tryfalse.\n  destruct Hauxd;tryfalse.\n  inverts H25.\n  simpl substaskst in *.\n\n  lets Hx: linv_split H26.\n  destruct Hx as (Mdc&Mdl&Odc&Odl&Hx).\n  mytac.\n  exists pc A po pi ip.\n  exists (TMSpecMod.put (TMSpecMod.put Tm t (merge Mc Mdc)) t' Mdl)\n         (TOSpecMod.put (TOSpecMod.put To t (merge O' Odc)) t' Odl)\n         (merge O' (minus Ol Oc)) Os'.\n  exists Ms Ml I lasrt.\n  splits;auto.\n  splits;auto.\n  splits;auto.\n  \n  eapply lpstep_goodks;eauto.\n  eapply partm_task_get_set;eauto.\n\n  eapply delother_partm;eauto.\n  eapply join_crt;eauto.\n  assert ( partO (merge O' (minus Ol Oc)) (set Tl t (SKIP , (kenil, ks)))\n                 (TOSpecMod.put To t O')).\n  eapply new_part_o;eauto.\n  eapply get_set_join_disj_l;eauto.\n  eapply parto_task_get_set;eauto.\n  assert ( (TOSpecMod.put (TOSpecMod.put To t O') t (merge O' Odc)) = (TOSpecMod.put To t (merge O' Odc))).\n  apply TOSpecMod.put_xx_update.\n  rewrite <- H32.\n  eapply delother_parto;eauto.\n  eapply to_mapsto_put';eauto.\n  \n  exists (e2,e1,m0,i,au) (e2,e1,Ms,i,au).\n  splits;auto.\n  unfolds.\n  unfold projD.\n  unfolddef.\n  rewrite <- Heqgetle.\n  rewrite <- Heqgetaux.\n  auto.\n  \n  exists (e2,e1,m0,i,au) (e2,e1,(merge Mc Mdc),i,au) (merge Mc Mdc) (merge O' Odc) (SKIP , (kenil, ks)) (curs (hapi_code sh), (keh, ksh)).\n  splits;auto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  unfolds.\n  unfold projD.\n  unfolddef.\n  rewrite <- Heqgetle.\n  rewrite <- Heqgetaux.\n  auto.\n  apply map_get_set.\n  apply map_get_set.\n  eapply CurLINV_merge_hold;eauto.\n  eapply disj_trans_sub with (m2:=Md).\n  unfolds;geat.\n\n  clear -Hmpart Htm H23 H22.\n\n  \n  eapply partm_neq_disj;eauto.\n  eapply disj_trans_sub with (m2:=Od).\n  unfolds;geat.\n\n  eapply disj_complex'''';eauto.\n  eapply H14;eauto.\n  \n  eapply LINV_ignore_int;eauto.\n  unfolds.\n  do 6 eexists;splits;eauto.\n  eapply join_merge_disj.\n  eapply disj_trans_sub with (m2:=Md).\n  unfolds;geat.\n  eapply partm_neq_disj;eauto.\n  eapply join_merge_disj.\n  eapply disj_trans_sub with (m2:=Od).\n  unfolds;geat.\n  eapply disj_complex'''';eauto.\n\n  splits;auto.\n  \n  intros.\n  assert (t'0 = t' \\/ t'0 <> t') by tauto.\n  destruct H34.\n  subst t'0.\n  clear -H17 H33 H16 Hjoin'.\n  unfolds in H33.\n  rewrite map_get_set in H33;auto.\n  assert ( Some (abstcblist x2) = Some (abstcblist x2) ) by auto.\n  apply H33 in H.\n  unfolds in H17.\n  eapply map_join_get_no_perm1 in H17;eauto.\n  unfolds in H.\n  mytac.\n  unfolddef.\n  rewrite e in H17.\n  tryfalse.\n  apply map_get_sig.\n  rewrite map_get_set' in H32;eauto.\n  assert (task_no_dead O t'0).\n  eapply htstepstar_nodead_still;eauto.\n  \n  eapply join_get_get_l in H16;eauto.\n  clear -H33 H34 H17 H16.\n  unfold task_no_dead in *.\n  intros.\n  unfolddef.\n  rewrite H in H16;inverts H16.\n  rewrite map_get_set in H33.\n  assert (Some (abstcblist x2) = Some (abstcblist x2)) by auto.\n  apply H33 in H0.\n  unfold indom in *.\n  mytac.\n  eexists.\n  eapply join_get_get_r;eauto.\n\n  lets Hx: Hrsim H31 H32 H35.\n  mytac.\n  exists x7 x8 x9 x10;splits;eauto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TMSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  eapply TOSpecMod.mapsto_mapsto_put;eauto.\n  rewrite map_get_set';auto.\n  eapply hpstep_eqdomto;eauto.\n\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n  (*Guarded.*)\n  (*------------------------------event case----------------------------------------*)\n  \n  intros.\n  assert (lpstepev pl Tl cst Sl t Tl' cst' S' t' ev) as Hlpstep by auto.\n  inverts H.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Hcsim).\n  destruct Hcsim as (Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  inverts Hcsim.\n  destruct Hinv as (oi&oi'&Ha1&Ha2&Ha3).\n  unfolddef.\n  assert (o=oi).  \n  rewrite Ha1 in Hproj.\n  inverts Hproj.\n  auto.\n  subst oi.\n  assert (tst=o).\n  rewrite H2 in Hproj.\n  inverts Hproj;auto.\n  subst tst.\n  destruct o as [[[[]]]].\n  simpl in Ha2;subst oi'.\n\n  simpl in Hsubs;subst o'.\n  simpl substaskst in *.\n  unfold satp in *.\n  rename t' into t.\n  rewrite Htl in H0;inverts H0.\n  eapply H1 with(cst:=cst') (cst':=cst') (Cl':=C') (Mf:=minus Ml Mc)\n                            (o2:=(e, e0, m, i, l)) (ev:=ev) (OO:=merge Oc Os) (o'':=(e, e0, m, i, l))in Ha3;eauto.\n  \n  destruct Ha3 as (Ch'&O'&o'&Ms'&Oc'&Os'&Htstep&Hjoin2&Hhjoin&Hinv'&Hlinv'&Htsim).\n\n  eapply htstepevstar_O_local with (Of:= (minus Ol Oc)) (OO:=O) in Htstep.\n  mytac.\n\n  exists (set Th t Ch') x.\n  split.\n\n  apply th_no_create_lift_ev  with (C:=Ch);auto.\n\n  apply CIH.\n\n  rename H0 into Hhtstep.\n  apply htstepevstar_tidsame in Hhtstep;auto.\n  unfold tidsame in Hhtstep.\n  unfold get in Hhtstep,Hosabsttid.\n  simpl in Hhtstep.\n  simpl in Hosabsttid.\n  rewrite Hosabsttid in Hhtstep;auto.\n\n  exists pc A po pi ip (TMSpecMod.put Tm t (get_mem (get_smem o'))).\n  subst.\n\n  exists (TOSpecMod.put To t Oc') (minus x Os') Os' Ms' (minus m Ms').\n  exists I lasrt.\n\n  splits;auto.\n  splits;auto.\n  splits;auto.\n\n  eapply lpstepev_goodks;eauto.\n  assert (snd (fst (fst S')) = snd (fst (fst (e, e0, m, i, l)))).\n  apply projs_eqm with (t:=t);auto.\n  rewrite H10.\n  simpl.\n\n  eapply joinm2_minus_join;eauto.\n  simpl. \n  eapply partm_task_get_set;eauto.\n  eapply partM_normal;eauto.\n  eapply join_join_minus;eauto.\n  eapply parto_task_get_set;eauto.\n  eapply partO_normal;eauto.\n  (*\n  unfold partM in Hmpart.\n  destruct Hmpart as (Hsub&Hdisjeach).\n  unfold partM.\n  split.\n  intros.\n  destruct (tid_eq_dec t t0).\n  exists (get_mem (get_smem o')).\n  rewrite <- e1.\n  split.\n  apply TMSpecMod.mapsto_put. \n  eapply joinm2_sub;eauto.\n  assert ( TasksMod.get (TasksMod.set Tl t0 C') t =TasksMod.get Tl t ).\n  eapply tasks_set_get_neq;eauto.\n  destruct Hsub with t0 as (mm&Hmpas&Hsubm).\n  exists mm.\n  split.\n  apply tm_mapsto_put';auto.\n  assert (Maps.sub mm (minus Ml Mc)).\n  apply minus_sub;auto.\n  apply Hdisjeach with (t1:=t0) (m1:=mm)in Htm;auto.\n  eapply sub_join_trans' with (o:=o') (M':=minus Ml Mc);eauto.\n  \n  intros.\n  destruct (tid_eq_dec t1 t).\n  rewrite e1 in H11.\n  assert (TMSpecMod.maps_to (TMSpecMod.put Tm t (get_mem (get_smem o'))) t (get_mem (get_smem o'))).\n  apply TMSpecMod.ext_mapsto.\n  unfold TMSpecMod.maps_to in H11.\n  unfold TMSpecMod.maps_to in H13.\n  subst t1.\n  rewrite H11 in H13.\n  inverts H13.\n  assert (t<>t2) as Hneq.\n  auto.\n  apply Hdisjeach  with (m1:=Mc) (m2:= m2) in H10.\n  assert (Maps.sub m2 (minus Ml Mc)) as Hfu.\n  assert (TasksMod.get (set Tl t C') t2 = TasksMod.get Tl t2).\n  apply tasks_set_get_neq;auto.\n  apply minus_sub;auto.\n  destruct Hsub with t2 as (mn&Htm'&Hsub').\n  assert ( TMSpecMod.maps_to Tm t2 m2).\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  assert (mn=m2).\n  unfold TMSpecMod.maps_to in H14.\n  unfold TMSpecMod.maps_to in Htm'.\n  rewrite H14 in Htm'.\n  inversion Htm';tryfalse;auto.\n  subst mn.\n  apply Hsub'.\n  apply Hdisjeach with (m1:=Mc) (m2:=m2)in Hneq;auto.\n  apply disj_sym;auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  apply disj_sym.\n  eapply joinm2_sub_disj with (M1:=Ms');eauto.\n  auto.\n  assert ( TasksMod.get (set Tl t C') t2 =TasksMod.get Tl t2 ).\n  apply tasks_set_get_neq with (t:=t);auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  destruct (tid_eq_dec t2 t). \n  subst t2.\n  assert (TMSpecMod.maps_to (TMSpecMod.put Tm t (get_mem (get_smem o'))) t (get_mem (get_smem o'))).\n  apply TMSpecMod.ext_mapsto.\n  unfold TMSpecMod.maps_to in H12.\n  unfold TMSpecMod.maps_to in H13.\n  rewrite H12 in H13.\n  inverts H13.\n  assert (t<>t1) as Hneq.\n  auto.\n  clear H10.\n  assert (t<>t1) as H10.\n  auto.\n  apply Hdisjeach  with (m1:=Mc) (m2:= m1)in H10.\n  assert (Maps.sub m1 (minus Ml Mc)) as Hfu.\n  assert (TasksMod.get (set Tl t C') t1 = TasksMod.get Tl t1).\n  apply tasks_set_get_neq;auto.\n  apply minus_sub;auto.\n  destruct Hsub with t1 as (mn&Htm'&Hsub').\n  assert ( TMSpecMod.maps_to Tm t1 m1).\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  unfold TMSpecMod.maps_to in H14.\n  unfold TMSpecMod.maps_to in Htm'.\n  rewrite H14 in Htm'.\n  inverts Htm'.\n  apply Hsub'.\n  apply Hdisjeach with (m1:=Mc) (m2:=m1) in Hneq;auto.\n  apply disj_sym;auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  eapply joinm2_sub_disj with (M1:=Ms');eauto.\n  auto.\n  assert ( TasksMod.get (set Tl t C') t1 =TasksMod.get Tl t1 ).\n  apply tasks_set_get_neq with (t:=t);auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  apply Hdisjeach with (t1:=t1) (t2:=t2);auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n  apply TMSpecMod.ext_presv_mapsto with (x:=t) (y:=get_mem (get_smem o'));auto.\n\n  eapply join_join_minus;eauto.\n\n  unfold partO in HOpart.\n  destruct HOpart as (Hsub&Hdisjeach).\n  unfold partO.\n  split.\n  intros.\n  destruct (tid_eq_dec t t0).\n  exists Oc'.\n  rewrite <- e1.\n  split.\n  apply TOSpecMod.mapsto_put.\n\n  eapply join_join_sub_minus;eauto.\n  assert ( TasksMod.get (TasksMod.set Tl t0 C') t =TasksMod.get Tl t ).\n  eapply tasks_set_get_neq;eauto.\n  destruct Hsub with t0 as (mm&Hmpas&Hsubm).\n  exists mm.\n  split.\n  apply to_mapsto_put';auto.\n  assert (Maps.sub mm (minus Ol Oc)).\n  apply minus_sub;auto.\n  apply Hdisjeach with (t1:=t0) (m1:=mm)in Hto;auto.\n\n  eapply join_join_sub_sub_minus with (M2:=minus Ol Oc);eauto.\n  \n  intros.\n  destruct (tid_eq_dec t1 t).\n  rewrite e1 in H11.\n  assert (TOSpecMod.maps_to (TOSpecMod.put To t Oc') t Oc').\n  apply TOSpecMod.ext_mapsto.\n  unfold TOSpecMod.maps_to in H11.\n  unfold TOSpecMod.maps_to in H13.\n  subst t1.\n  rewrite H11 in H13.\n  inverts H13.\n  assert (t<>t2) as Hneq.\n  auto.\n  apply Hdisjeach  with (m1:=Oc) (m2:= m2) in H10.\n  assert (Maps.sub m2 (minus Ol Oc)) as Hfu.\n  assert (TasksMod.get (set Tl t C') t2 = TasksMod.get Tl t2).\n  apply tasks_set_get_neq;auto.\n  apply minus_sub;auto.\n  destruct Hsub with t2 as (mn&Htm'&Hsub').\n  assert ( TOSpecMod.maps_to To t2 m2).\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  assert (mn=m2).\n  unfold TOSpecMod.maps_to in H14.\n  unfold TOSpecMod.maps_to in Htm'.\n  rewrite H14 in Htm'.\n  inversion Htm';tryfalse;auto.\n  subst mn.\n  apply Hsub'.\n  apply Hdisjeach with (m1:=Oc) (m2:=m2)in Hneq;auto.\n  apply disj_sym;auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  apply disj_sym.\n  eapply join_join_sub_disj with (M2:=(minus Ol Oc));eauto.\n\n  auto.\n  assert ( TasksMod.get (set Tl t C') t2 =TasksMod.get Tl t2 ).\n  apply tasks_set_get_neq with (t:=t);auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  destruct (tid_eq_dec t2 t). \n  subst t2.\n  assert (TOSpecMod.maps_to (TOSpecMod.put To t Oc') t Oc').\n  apply TOSpecMod.ext_mapsto.\n  unfold TOSpecMod.maps_to in H12.\n  unfold TOSpecMod.maps_to in H13.\n  rewrite H12 in H13.\n  inverts H13.\n  assert (t<>t1) as Hneq.\n  auto.\n  clear H10.\n  assert (t<>t1) as H10.\n  auto.\n  apply Hdisjeach  with (m1:=Oc) (m2:= m1)in H10.\n  assert (Maps.sub m1 (minus Ol Oc)) as Hfu.\n  assert (TasksMod.get (set Tl t C') t1 = TasksMod.get Tl t1).\n  apply tasks_set_get_neq;auto.\n  apply minus_sub;auto.\n  destruct Hsub with t1 as (mn&Htm'&Hsub').\n  assert ( TOSpecMod.maps_to To t1 m1).\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  unfold TOSpecMod.maps_to in H14.\n  unfold TOSpecMod.maps_to in Htm'.\n  rewrite H14 in Htm'.\n  inverts Htm'.\n  apply Hsub'.\n  apply Hdisjeach with (m1:=Oc) (m2:=m1) in Hneq;auto.\n  apply disj_sym;auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  eapply join_join_sub_disj with (M2:=(minus Ol Oc));eauto.\n  auto.\n  assert ( TasksMod.get (set Tl t C') t1 =TasksMod.get Tl t1 ).\n  apply tasks_set_get_neq with (t:=t);auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  apply Hdisjeach with (t1:=t1) (t2:=t2);auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n  apply TOSpecMod.ext_presv_mapsto with (x:=t) (y:=Oc');auto.\n*)\n  exists (e, e0, m, i, l) (e, e0, Ms', i, l).\n  splits;auto.\n  \n  assert (substaskst o' Ms'= (e, e0, Ms', i, l)) as Hrepltrans.\n  clear -Hjoin2.\n  unfolds in Hjoin2.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  simpl;auto.\n  rewrite Hrepltrans in Hinv'.\n  auto.\n\n  exists (e, e0, m, i, l) o'\n         (get_mem (get_smem o')) Oc' C' Ch'.\n  splits;auto.\n  clear -Hjoin2.\n  unfolds in Hjoin2.\n  mytac.\n  unfold joinmem in *.\n  mytac.\n  simpl.\n  auto.\n  apply map_get_set.\n  apply map_get_set.\n\n  splits;auto.\n  intros.\n  \n  rename H12 into Hnodead.\n  assert (t'<>t);auto.\n\n  apply Hrsim with (Ch:=Ch0) in H10.\n\n  destruct H10 as (or&M'r&Clr&O'r&Htmr&Htor&Hprojr&Hrlinv&Htasksr&Hsimr).\n\n  exists (((gets_g S'),(get_env (get_smem or)),(gets_m S')),(snd (fst S')),\n          (snd or)) M'r Clr O'r.\n  splits;auto.\n  apply tm_mapsto_put' with (t:=t) (a:=get_mem (get_smem o'));auto.\n  apply to_mapsto_put' with (t:=t) (a:=Oc');auto.\n\n  \n  apply proj_stneq_ex with (S:=S') (t:=t); auto.\n  destruct S' as [[[[]]]].\n  simpl.\n  split;intros.\n  auto.\n  unfolds.\n  intros;auto.\n  \n  intros.\n  eapply LInv_ignore_int.\n  assert (substaskst\n            (gets_g S', get_env (get_smem or), gets_m S', snd (fst or), snd or) M'r = substaskst or M'r).\n\n  simpl.\n  clear -Hprojr.\n  destruct S' as [[[[]]]].\n  destruct or as [[[[]]]].\n  unfold gets_g,get_env.\n  simpl in *.\n  unfold tid in *.\n  remember (get c t') as X.\n  destruct X;tryfalse.\n  remember (get l t') as Y.\n  destruct Y;tryfalse.\n  inverts Hprojr.\n  auto.\n  simpl in H10.\n  erewrite H10.\n  eauto.\n  rewrite map_get_set';auto.\n  \n  intros.\n\n  assert (forall Mr,RdyChange\n            (substaskst\n               (gets_g S', get_env (get_smem or), \n               gets_m S', snd (fst S'), snd or) Mr) = RdyChange (substaskst or Mr)).\n  intros.\n  simpl.\n  clear -Hprojr.\n  destruct S' as [[[[]]]].\n  destruct or as [[[[]]]].\n  unfold gets_g,get_env in *.\n  simpl in *.\n  unfold tid in *.\n  remember (get c t') as X.\n  destruct X;tryfalse.\n  remember (get l t') as Y.\n  destruct Y;tryfalse.\n  inverts Hprojr.\n  auto.\n\n  rewrite H13 in H10.\n  apply Hsimr in H10.\n  mytac.\n  eexists.\n  erewrite H13.\n  splits;eauto.\n  \n  rewrite <- H11. auto.\n  symmetry.\n  apply tasks_set_get_neq;auto.\n\n  eapply htstepevstar_nodead_still;eauto.\n\n  eapply hpstepev_eqdomto with (T:=Th) (O:=O) (p:=(pc,A));eauto.\n  eapply th_no_create_lift_ev with (C:=Ch);eauto.\n\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n \n  assert ((e, e0, Mc, i, l) = substaskst (e, e0, m, i, l) Mc).\n  simpl;auto.\n  rewrite H0.\n  eapply joinm2_merge_minus;eauto.\n  assert ( (snd (fst (fst S'))) = (snd (fst (fst (e, e0, m, i, l))) )).\n  apply projs_eqm with t.\n  auto.\n  simpl.\n  simpl in H9.\n  rewrite H9 in Hmjoin;auto.\n  eapply part_sub;eauto.\n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  unfolds;eauto.\n  auto.\n\n  (*-----------------------abort case---------------------------*)\n  intros.\n  inverts H.\n  subst.\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  rewrite Hproj in H1.\n  inversion H1; tryfalse.\n  subst tst.\n\n  inversion Hcsim.\n  subst.\n  unfolddef.\n  rewrite  H0 in Htl.\n  inversion Htl;tryfalse.\n  subst C.\n\n  apply H10 with (cst:=cst)(Os:=Os) (Ms:=Ms) (o':=o) (Mf:=minus Ml Mc) (OO:=merge Oc Os) (OOO:=O) (Of:=minus Ol Oc) in H3;auto.\n  \n  apply  hp_stepstarabt.\n  inversion H3.\n  subst.\n  destruct H13 as (c'&cst'&O'&Htstepstar&Htstepabt).\n  exists (set Th t c') cst' O'.\n  split.\n\n  apply th_ttop_lift with (C:=Ch);auto.\n  apply hpabt_step with (C:=c') (t:=t);auto.\n  apply htstepstar_tidsame in Htstepstar.\n  unfold tidsame in Htstepstar.\n  rewrite <- Htstepstar;auto.\n  apply map_get_set;auto.\n  destruct Hinv as (x&x'&Hinv).\n  mytac.\n  rewrite H13 in Hproj;inverts Hproj.\n  unfolds.\n  destruct o as [[[[]]]];simpl substaskst in *;auto.\n  Focus 3.\n  eapply join_merge_minus;eauto.\n  eapply parto_sub;eauto.\n  \n  eapply joinm2_merge_minus;eauto.\n  assert ( (snd (fst (fst Sl))) = (snd (fst (fst o)) )).\n  apply projs_eqm with t.\n  auto.\n  simpl.\n  simpl in H13.\n  destruct o as [[[[]]]].\n  unfold get_smem,get_mem.\n  rewrite H13 in Hmjoin;simpl in Hmjoin;auto.\n\n  eapply part_sub;eauto.\n  \n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  unfolds;eauto.\n  auto.\n \n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  rewrite Hproj in H1.\n  inversion H1; tryfalse.\n  subst tst.\n  destruct o as [[[[]]]].\n  simpl in Hsubs;subst o'.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  inverts Hcsim.\n  assert ((curs (sprim (stkinit e1 e2 e3)), (kenil, ks)) = (curs (sprim (stkinit e1 e2 e3)), (kenil, ks))) by auto.\n  unfolddef.\n  rewrite Htl in H0;inverts H0.\n  eapply H7 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os) in H9.\n \n  simpl get_smem in *.\n  mytac.\n  destruct H3.\n  \n  destruct Sl as [[[[]]]].\n  unfolds in Hproj.\n  unfold projD in Hproj.\n  unfolddef.\n  destruct (get c t);tryfalse.\n  destruct (get l0 t);tryfalse.\n  inverts Hproj.\n  exists x0 x1 x2;splits.\n  eapply evalval_eq_prop;eauto.\n  eapply sub_join_sub with (M1:=Ml);eauto.\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  \n  eapply evalval_eq_prop;eauto.\n  eapply sub_join_sub with (M1:=Ml);eauto.\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  \n  eapply evalval_eq_prop;eauto.\n  eapply sub_join_sub with (M1:=Ml);eauto.\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  simpl substaskst in *;auto.\n  exists (merge Mc Ms).\n  unfold getmem;simpl.\n  apply join_merge_disj.\n  eapply part_disjm;eauto.\n  clear -Hmjoin;unfolds;geat.\n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  clear -HOjoin;unfolds;geat.\n  \n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  rewrite Hproj in H1.\n  inversion H1; tryfalse.\n  subst tst.\n  destruct o as [[[[]]]].\n  simpl in Hsubs;subst o'.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  inverts Hcsim.\n  assert ((curs (sprim (stkfree e)), (kenil, ks)) = (curs (sprim (stkfree e)), (kenil, ks))) by auto.\n  unfolddef.\n  rewrite Htl in H0;inverts H0.\n  eapply H8 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os) in H9.\n \n  simpl get_smem in *.\n  mytac.\n  destruct H3.\n  \n  destruct Sl as [[[[]]]].\n  unfolds in Hproj.\n  unfold projD in Hproj.\n  unfolddef.\n  destruct (get c t);tryfalse.\n  destruct (get l0 t);tryfalse.\n  inverts Hproj.\n  exists x3.\n  eapply evalval_eq_prop;eauto.\n  eapply sub_join_sub with (M1:=Ml);eauto.\n  eapply part_sub with (T:=Tl) (Tm:=Tm) (t:=t);eauto.\n  simpl substaskst in *;auto.\n  exists (merge Mc Ms).\n  unfold getmem;simpl.\n  apply join_merge_disj.\n  eapply part_disjm;eauto.\n  clear -Hmjoin;unfolds;geat.\n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  clear -HOjoin;unfolds;geat.\n\n  destruct Hcsim as (o&o'&Mc&Oc&Cl&Ch&Htm&Hto&Hproj&Hsubs&Hth&Htl&Hlinv&Hcsim).\n  rewrite Hproj in H1.\n  inversion H1; tryfalse.\n  subst tst.\n  destruct o as [[[[]]]].\n  simpl in Hsubs;subst o'.\n  destruct Hinv as (o1&o1'&Hproj1&Hsubsub&Hinv).\n  rewrite Hproj in Hproj1.\n  inverts Hproj1.\n  simpl in Hsubsub.\n  subst o1'.\n  inverts Hcsim.\n  assert ((curs (sprim (switch x)), (kenil, ks)) = (curs (sprim (switch x)), (kenil, ks))) by auto.\n  unfolddef.\n  rewrite Htl in H0;inverts H0.\n  eapply H4 with (Ms:=Ms) (Os:=Os) (OO:=merge Oc Os) in H9.\n  simpl substaskst in *.\n  simpl get_smem in *.\n  mytac.\n  destruct H3.\n\n  simpl get_genv.\n  simpl get_mem.\n  destruct Sl as [[[[]]]].\n  unfolds in Hproj.\n  unfold projD in Hproj.\n  unfolddef.\n  destruct (get c t);tryfalse.\n  destruct (get l0 t);tryfalse.\n  inverts Hproj.\n  destruct H16;mytac.\n  eapply swpre_hpswitch_nabt.\n  unfold satp in *.\n  eapply swpre_prop;eauto.\n  intros.\n  lets Hx:H0 ab.\n  unfold SWPRE_NDEAD in Hx;destruct Hx;eauto.\n  simpl.\n  clear -H10 Htm Hmpart Hmjoin.\n  unfolds in H10.\n  mytac.\n  eapply part_sub in Htm;eauto.\n  simpl in Hmjoin.\n  unfold Maps.sub in *;mytac.\n  unfolddef.\n  geat.\n  instantiate (1:=x9).\n  clear;unfolds;geat.\n  assert (satp (e, e0, x4, i, l) x9 (SWPRE (getsched (pc, A)) x t)).\n  clear -H0.\n  unfold satp in *;intros.\n  lets Hx:H0 aop.\n  destruct Hx;auto.\n  eapply swpre_hpswitch_nabt.\n  unfold satp in *.\n  eapply swpre_prop;eauto.\n  simpl.\n  clear -H10 Htm Hmpart Hmjoin.\n  unfolds in H10.\n  mytac.\n  eapply part_sub in Htm;eauto.\n  simpl in Hmjoin.\n  unfold Maps.sub in *;mytac.\n  unfolddef.\n  geat.\n  instantiate (1:=x9).\n  clear;unfolds;geat.\n  simpl substaskst in *;auto.\n  exists (merge Mc Ms).\n  unfold getmem;simpl.\n  apply join_merge_disj.\n  eapply part_disjm;eauto.\n  clear -Hmjoin;unfolds;geat.\n  apply join_merge_disj.\n  eapply part_disjo;eauto.\n  clear -HOjoin;unfolds;geat.\n  Grab Existential Variables.\n  trivial.\n  trivial.\n  trivial.\n  trivial.\nQed.\n\nLemma ApiMethSim: \n  forall (OS1:oscode) (A:osspec) Spec I lasrt,    \n    GoodI I (snd A) lasrt->\n    (\n      WFFuncsSim (snd (fst OS1)) Spec (snd A) lasrt I\n    ) ->\n    (\n      forall (f:fid) ab vl p r ft G tid, \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg->\n        Some r = BuildRetA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg->\n        (\n          exists t d1 d2 s,\n            (fst (fst OS1)) f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n            InfRules Spec (snd A) lasrt I r Afalse p s Afalse tid\n        )\n    )\n    ->\n    \n    (\n      forall (f:fid) ab vl p r ft G tid , \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg ->\n        Some r = BuildRetA (fst (fst OS1)) f (ab,ft) vl G lasrt tid init_lg->\n        (\n          exists t d1 d2 s,\n            (fst (fst OS1)) f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n            MethSimAsrt (snd (fst OS1)) (snd A) lasrt I r Afalse p s Afalse tid \n        )\n    ).\nProof.\n  introv goodi.\n  intros.\n  eapply H0 in H1;eauto.\n  destruct H1 as (t&d1&d2&s&Ha1&Ha2&Ha3).\n  exists t d1 d2 s;splits;auto.\n  unfold MethSimAsrt.\n  eapply MethSim_to_Methsim';eauto.\nQed.\n\nLemma IntMethSim: \n  forall (OS1:oscode) (A:osspec) Spec I lasrt, \n    GoodI I (snd A) lasrt->\n    (\n      WFFuncsSim (snd (fst OS1)) Spec (snd A) lasrt I\n    ) ->\n    (\n      forall (i:hid) ispec isrreg si G tid lg, \n        (snd (fst A)) i = Some ispec ->\n        (\n          exists (s:stmts) p r,\n            (snd OS1) i = Some s /\\ \n            p = ipreasrt i isrreg si (ispec ) I G lasrt tid lg /\\ \n            r = iretasrt i isrreg si I G lasrt tid lg /\\\n            InfRules Spec (snd A) lasrt I retfalse r p s Afalse tid\n        )\n    )\n    ->\n    \n    (\n      forall (i:hid) ispec  isrreg si G lg tid, \n        (snd (fst A)) i = Some ispec ->\n        (\n          exists (s:stmts) p r,\n            (snd OS1) i = Some s /\\ \n            p = ipreasrt i isrreg si (ispec) I G lasrt tid lg /\\ \n            r = iretasrt i isrreg si I G lasrt tid lg /\\\n            MethSimAsrt (snd (fst OS1)) (snd A) lasrt I retfalse r p s Afalse tid\n        )\n    ).\nProof.\n  introv goodi.\n  intros.\n  eapply H0 in H1.\n  destruct H1 as (s&p&r&Ha1&Ha2&Ha3&Ha4).\n  exists s p r.\n  splits;eauto.\n  unfold MethSimAsrt.\n  simpl.\n  eapply MethSim_to_Methsim';eauto.\nQed.\n\n \nLemma dladd_revlcons_eq: forall d1 d2, dladd d1 d2 = revlcons d1 d2.\nProof.\n  intros.\n  inductions d1; inductions d2; simpl; auto.  \nQed.\n\n\nLemma r_lift_rule: forall Spec sd I r' r p p' s f ab vl P G lasrt tid lg,\n                     Some r = BuildRetA P f ab vl G lasrt tid lg->\n                     Some p = BuildPreA P f ab vl G lasrt tid lg->\n                     Some r' = BuildRetA' P f ab vl lasrt tid lg ->\n                     Some p' = BuildPreA' P f ab vl lasrt tid lg->\n                     {|Spec, sd, lasrt, I, r', Afalse|}|-tid {{p'}} s {{Afalse}} ->\n                                                         {|Spec, sd, lasrt, I, r, Afalse|}|-tid {{p}} s {{Afalse}}.\nProof.\n  introv Hr Hp Hr' Hp'.\n  unfolds in Hr.\n  unfolds in Hp.\n  unfolds in Hr'.\n  unfolds in Hp'.\n  destruct (P f); tryfalse.\n  destruct f0.\n  destruct p0.\n  destruct p0.\n  rewrite dladd_revlcons_eq in *.\n  remember (buildp (revlcons d0 d) vl) as Hasrt.\n  destruct (dl_vl_match d0 (rev vl));tryfalse.\n  destruct Hasrt; tryfalse.\n  inverts Hp.\n  inverts Hp'.\n  remember ( buildq (revlcons d0 d)) as Hddd.\n  destruct Hddd; tryfalse.\n  inverts Hr'.\n  inverts Hr.\n  introv Hsim.\n  eapply genv_introret_rule.\n  auto.\nQed.\n\nLemma bpr'_to_bpr: forall osc (A:osspec) I Spec lasrt, \n                     (\n                       forall (f:fid) ab vl p r ft tid, \n                         (fst (fst A)) f = Some (ab,ft) ->\n                         Some p = BuildPreA' (get_afun osc) f (ab,ft) vl lasrt tid init_lg->\n                         Some r = BuildRetA' (get_afun osc) f (ab,ft) vl lasrt tid init_lg->\n                         (\n                           exists  t d1 d2 s,\n                             (get_afun osc) f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n                             InfRules Spec (snd A) lasrt I r Afalse p s Afalse tid\n                         )\n                     ) ->\n                     (\n                       forall (f:fid) ab vl p r ft G tid , \n                         (fst (fst A)) f = Some (ab,ft) ->\n                         Some p = BuildPreA (get_afun osc) f (ab,ft) vl G lasrt tid init_lg->\n                         Some r = BuildRetA (get_afun osc) f (ab,ft) vl G lasrt tid init_lg->\n                         (\n                           exists  t d1 d2 s,\n                             (get_afun osc) f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n                             InfRules Spec (snd A) lasrt I r Afalse p s Afalse tid\n                         )\n                     ).\nProof.   \n  intros.\n  assert (exists p', Some p' = BuildPreA' (get_afun osc) f (ab, ft) vl lasrt tid init_lg).\n  clear -H1.\n  unfolds in H1.\n  unfold BuildPreA'.\n  destruct ((get_afun osc)).\n  destruct f0.\n  destruct p0.\n  destruct p0.\n  rewrite dladd_revlcons_eq.\n  destruct (dl_vl_match d0 (rev vl));tryfalse.\n  remember (buildp (revlcons d0 d) vl) as Hr.\n  destruct Hr; tryfalse.  \n  inverts H1.\n  eexists; eauto.\n  tryfalse.\n  assert (exists p', Some p' = BuildRetA' (get_afun osc) f (ab, ft) vl lasrt tid init_lg).\n  clear -H2.\n  unfolds in H2.\n  unfold BuildRetA'.\n  destruct ((get_afun osc)).\n  destruct f0.\n  destruct p.\n  destruct p.\n  rewrite dladd_revlcons_eq.\n  remember (buildq (revlcons d0 d) ) as Hr.\n  destruct Hr; tryfalse.  \n  inverts H2.\n  eexists; eauto.\n  tryfalse.\n\n  destruct H3 as (p'&Hp).\n  destruct H4 as (r'&Hr).\n  assert (Some r' = BuildRetA' (get_afun osc) f (ab,ft) vl  lasrt tid init_lg) as Hrr;auto.\n  eapply H in Hr;eauto.\n  destruct Hr as (t&d1&d2&s&Hr1&Hr2&Hr3).\n  exists t d1 d2 s;splits;auto.\n  eapply r_lift_rule ;eauto.\nQed.\n\nLemma int_bpr'_to_bpr :\n  forall osc (A:osspec) I Spec lasrt,\n    EqDomInt (get_lint osc) (snd (fst A)) ->\n    (forall (i : nat) (isrreg : isr) (si : is) \n            (p r : asrt) (t : tid) (lg : list logicvar),\n       Some p = BuildintPre i  (snd (fst A)) isrreg si I lasrt t lg ->\n       Some r = BuildintRet i  (snd (fst A)) isrreg si I lasrt t lg ->\n       exists s,\n         (get_lint osc) i = Some s /\\\n         {|Spec, snd A, lasrt, I, inferules.retfalse, r|}|- t {{p}} s\n                                                           {{Afalse}}) ->\n    (\n      forall (i:hid) ispec isrreg si G t lg, \n        (snd (fst A)) i = Some ispec ->\n        (\n          exists (s:stmts) p r,\n            (get_lint osc) i = Some s /\\ \n            p = ipreasrt i isrreg si (ispec ) I G lasrt t lg/\\ \n            r = iretasrt i isrreg si I G lasrt t lg /\\\n            InfRules Spec (snd A) lasrt I retfalse r p s Afalse t\n        )\n  ).\nProof.\n  intros.\n  assert (exists p, Some p = BuildintPre i (snd (fst A)) isrreg si I lasrt t lg).\n  unfold BuildintPre.\n  rewrite H1.\n  eexists;eauto.\n  destruct H2.\n  assert (exists p, Some p = BuildintRet i (snd (fst A)) isrreg si I lasrt t lg).\n  unfold BuildintRet.\n  rewrite H1.\n  eexists;eauto.\n  destruct H3.\n  lets Hx: H0 H2 H3.\n  destruct Hx.\n  destruct H4.\n  unfold BuildintPre in H2.\n  unfold BuildintRet in H3.\n  rewrite H1 in *.\n  inverts H2.\n  inverts H3.\n  exists x1.\n  do 2 eexists.\n  splits;auto.\n  unfold ipreasrt,iretasrt.\n  eapply genv_introexint_rule; eauto.\nQed.\n\n\n\n\nLemma eqdomsot_get_exproj:\n  forall t S O T,\n    indom T t ->\n    eqdomto T O ->\n    eqdomSO S O ->\n    exists o, projS S t = Some o.\nProof.\n  intros.\n  unfolds in H0.\n  mytac.\n  lets Hx:H2 t.\n  clear H2.\n  unfolds in H1.\n  destruct S as [[[[]]]].\n  rewrite H0 in H1.\n  unfolds in H.\n  apply Hx in H.\n  destruct H1.\n  unfolds in H1.\n  assert (exists a, TcbMod.get x t = Some a) as XX.\n  auto.\n  apply H1 in H.\n  unfolds in H2.\n  apply H2 in XX.\n  clear -H XX.\n  unfolds in H.\n  unfolds in XX.\n  mytac.\n  exists (e,x0,m,i,x).\n  unfolds;simpl;auto.\n  unfold get in *.\n  simpl in *.\n  rewrite H.\n  rewrite H0.\n  auto.\nQed.\n\n\nLemma init_goodis:\n  forall S O I lasrt sd init,\n    init S O ->\n    side_condition I lasrt sd init init_lg ->\n    good_is_S S.\nProof.\n  intros.\n  unfolds in H.\n  mytac.\n  apply H0 in X.\n  destruct X.\n  clear H0 H2 H.\n  induction H1.\n  subst.\n  unfolds.\n\n  intros.\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  unfolds in H.\n  unfold projD in H.\n  assert (t0 = t \\/ t0 <> t) by tauto.\n  destruct H0;subst.\n  rewrite map_get_sig in H.\n  rewrite map_get_sig in H.\n  inverts H.\n  unfold init_cur in H3.\n  unfold init_rdy in H3.\n  lets Hx:H3 (spec_done None).\n  simpl in Hx.\n  mytac.\n  simpl;auto.\n  rewrite map_get_sig' in H;auto.\n  tryfalse.\n  unfolds.\n  intros.\n  assert (t0 = t \\/ t0 <> t) by tauto.\n  destruct H8.\n  subst.\n  \n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  unfolds in H7.\n\n  unfold projD in H7.\n\n  eapply join_sig_get_disj in H0;eauto.\n  destruct H0.\n  eapply join_sig_get_disj in H1;eauto.\n  unfold tid in *.\n  rewrite H in H7.\n  destruct H1.\n  rewrite H1 in H7.\n  inverts H7.\n  lets Hx: H5 (spec_done None).\n  simpl in Hx;mytac;auto.\n  simpl;auto.\n\n  destruct tst.\n  destruct p.\n  destruct p.\n  destruct p.\n  destruct l.\n  destruct p.\n  unfolds in IHinitst.\n  assert (projS (G, envs', M', isr, lst') t0 = Some (e, e0, M', i, (i0, i1, c))).\n  unfolds.\n  unfold projD.\n \n\n  unfolds in H7.\n  destruct S.\n  destruct p.\n  inverts H.\n  unfold projD in H7.\n  remember (get envs t0 ) as X.\n  destruct X;tryfalse.\n  remember ( get lst t0 ) as Y.\n  destruct Y;tryfalse.\n  eapply join_get_get_r_rev with (a:=t0) in H0;eauto.\n  eapply join_get_get_r_rev with (a:=t0) in H1;eauto.\n  rewrite H0.\n  rewrite H1.\n  inverts H7.\n  auto.\n  eapply map_get_sig';eauto.\n  eapply map_get_sig';eauto.\n  apply IHinitst in H9.\n  auto.\nQed.\n\nTheorem toptheorem':\n  forall (osc:oscode) (A:osspec) (init:InitAsrt) lasrt (I:Inv) (Spec:funspec),\n    no_fun_same (get_afun osc)  (get_ifun osc)->\n    True ->\n    True ->\n    (*good_ret_pu (get_afun osc) ->*)\n    (*good_ret_pu (get_ifun osc)  ->*)\n    no_call_api_os (get_afun osc) (get_ifun osc) (get_lint osc) -> \n    (forall f t d1 d2 s, (fst (fst osc)) f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall f t d1 d2 s, (snd (fst osc)) f = Some (t,d1,d2,s) -> good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    (forall (i : nat) (isrreg : isr) (si : is) \n            (p r : asrt) (lg : list logicvar) (t : tid) ,\n       Some p = BuildintPre i  (snd (fst A)) isrreg si I lasrt t lg ->\n       Some r = BuildintRet i  (snd (fst A)) isrreg si I lasrt t lg ->\n       exists s,\n         (get_lint osc) i = Some s /\\\n         {|Spec, snd A, lasrt, I, inferules.retfalse, r|}|- t {{p}} s\n                                                              {{Afalse}}) ->\n    (\n      forall (f:fid) ab vl p r ft tid , \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA' (get_afun osc) f (ab,ft) vl lasrt tid init_lg ->\n        Some r = BuildRetA' (get_afun osc) f (ab,ft) vl lasrt tid init_lg->\n        (\n          exists  t d1 d2 s,\n            (get_afun osc) f = Some (t, d1, d2, s)/\\ GoodStmt' s /\\\n            InfRules Spec (snd A) lasrt I r Afalse  p s Afalse tid\n        )\n    )->\n    \n    WFFunEnv (get_ifun osc) Spec (snd A) lasrt I-> \n    (\n      eqdomOS osc A /\\\n      side_condition I lasrt (snd A) init init_lg\n    ) ->\n    OSCorrect osc A init.\nProof. \n  intros osc A init lasrt I Spec Hnofunsame Hxpo Hxpi Hnoos Hgoodpo Hgoodpi Hint Hapi Hifun Hside.\n  unfold OSCorrect.\n  introv Hitideq.\n  intros.\n  unfold WellClient in H1.\n  destruct H1 as (H1&Hxpc).\n  apply progsim_imply_eref.\n  unfold oscorrectness.prog_sim.\n  subst.\n  splits;auto.\n  apply tsimtopsim.\n  auto.\n  destruct Hside as (Heqdomos&Hside).\n  assert (eqdomTO T O) as HeqdomTO.\n  unfolds in H.\n  mytac.\n  unfolds in H.\n  unfolds.\n  mytac.\n  eexists;splits;eauto.\n  intros.\n  eapply H6;eauto.\n  \n  assert (eqdomto T O) as Heqdomto.\n  unfolds in H.\n  mytac.\n  unfolds in H.\n  unfolds.\n  mytac.\n  eexists;splits;eauto.\n  \n  lets Hx: init_partmo T Hitideq H0 Hside.\n  auto.\n  destruct Hx as (Tm & To & Ml & Ms & Ol & Os & Hinitst).\n  \n  exists pc A (get_afun osc) (get_ifun osc) (get_lint osc) Tm.\n  exists To Ol Os Ms Ml I.\n  exists lasrt. \n  splits;auto.\n\n  unfolds get_afun, get_ifun, get_lint.\n  destruct osc.\n  destruct p.\n  simpl.\n  auto.\n  split;auto.\n  inversion Hside.\n  splits;auto.\n  unfolds;auto.\n  lets Hx:H4 H0.\n  destruct Hx.\n  unfolds in H.\n  destruct H.\n  unfolds.\n  intros.\n  apply H7 in H8.\n  mytac.\n  unfolds in H8.\n  inverts H8.\n  simpl.\n  destruct osc.\n  destruct p.\n  auto.\n\n\n  eapply init_goodis;eauto.\n  mytac;auto.\n  \n  do 2 eexists.\n  splits;eauto.\n  unfold InitTasks in H.\n  destruct H.\n  unfolds in H.\n  mytac.\n  unfolds in H2.\n  destruct H2.\n  do 6 eexists;splits;eauto.\n  unfold CurLINV.\n  clear -H12.\n  unfold satp in *.\n  intros.\n  lets Hx: H12 aop.\n  clear H12.\n  sep auto.\n  instantiate (1:=init_lg).\n  sep auto.\n\n  \n  apply SmCTaskSim;auto.\n\n\n  eapply ApiMethSim with (Spec:=Spec);auto.\n  unfolds in Hside.\n  destruct Hside;auto.\n  apply WFFunEnv_imply_WFFuncsSim;auto.\n  eapply bpr'_to_bpr;eauto.\n  split;auto.\n  \n  unfolds.\n  splits;auto.\n  unfolds.\n  split;eauto.\n  clear -H13.\n  destruct x1 as [[[[]]]].\n  simpl in H13.\n  simpl;auto.\n  apply H16 in H2.\n  mytac.\n  eexists;eauto.\n  (*--------------*)\n  intros.\n  lets Hx: H8 H16.\n  unfolds;eauto.\n  mytac.\n  do 4 eexists;splits;eauto.\n  exists init_lg.\n  unfold satp in *.\n  lets Hx:H22 aop.\n  sep auto.\n  \n  intros.\n\n\n  Lemma eqdomsot_get_exproj':\n    forall t S O T Ch,\n      TasksMod.get T t = Some Ch ->\n      eqdomto T O ->\n      eqdomSO S O ->\n      exists o, projS S t = Some o.\n  Proof.\n    intros.\n    eapply eqdomsot_get_exproj;eauto.\n    unfolds;eauto.\n  Qed.\n  destruct H21.\n  destruct x4 as [[[[]]]].\n  destruct l as [[]].\n  simpl substaskst in *.\n  simpl RdyChange in *.\n  eexists;split;auto.\n\n  \n  apply SmCTaskSim;auto.\n  \n  apply ApiMethSim with (Spec:=Spec) .\n  unfolds in Hside.\n  destruct Hside;auto.\n  apply WFFunEnv_imply_WFFuncsSim;auto.\n  eapply bpr'_to_bpr;eauto.\n  split;auto.\n  unfolds.\n  splits;auto.\n  unfold InitTaskSt.\n  unfold satp in *.\n  simpl fst in *.\n  simpl snd.\n  destruct H24.\n  unfold RDYINV in H22.\n  split.\n  intros.\n  lets Hx:H21 aop.\n  lets Hy:H22 aop.\n  destruct Hx.\n  clear H21 H22.\n  \n  destruct H24.\n  destruct H22;auto.\n  unfold CurTid.\n  Lemma merge_star:\n    forall P Q M1 M2 G E a b O1 O2 d,\n      disjoint M1 M2 ->\n      disjoint O1 O2 ->\n      ((G,E,M1),a,b,O1,d) |= P ->\n      ((G,E,M2),a,b,O2,d) |= Q ->\n      ((G,E,merge M1 M2),a,b,merge O1 O2,d) |= P ** Q.\n  Proof.\n    intros.\n    simpl in *.\n    exists M1 M2 (merge M1 M2) O1 O2 (merge O1 O2).\n    mytac.\n    apply join_merge_disj;auto.\n    apply join_merge_disj;auto.\n    auto.\n    auto.\n  Qed.\n  \n  eapply merge_star;eauto.\n  unfolds;eauto.\n  clear Hy.\n  sep auto.\n  clear -H25.\n  simpl in *.\n  mytac.\n  auto.\n  \n  assert (i = empisr).\n  simpl in Hy.\n  mytac.\n  subst i;auto.\n  unfold SWINVt in H25.\n  unfold SWINV in H25.\n  assert (i0=true).\n  clear -Hy.\n  simpl in Hy;mytac.\n  subst i0.\n  clear -H25.\n  simpl in H25;mytac;tryfalse.\n  clear -H23.\n  simpl in H23;simpl;auto.\n  unfolds in H.\n  destruct H.\n  \n  apply H21 in H17.\n  mytac.\n  eexists;splits;eauto.\n\n  unfolds in H.\n  destruct H;auto.\n\n  destruct osc.\n  destruct p.\n  unfolds get_afun,get_ifun,get_lint.\n  simpl fst.\n  simpl snd.\n  auto.\n  \n  apply ApiMethSim with (Spec:=Spec) .\n  unfolds in Hside.\n  destruct Hside;auto.\n  apply WFFunEnv_imply_WFFuncsSim;auto.\n  eapply bpr'_to_bpr;eauto.\n\n  apply IntMethSim with (Spec:=Spec).\n  unfolds in Hside.\n  destruct Hside;auto.\n  apply WFFunEnv_imply_WFFuncsSim;auto.\n  eapply int_bpr'_to_bpr;eauto.\n  unfold EqDomInt.\n  clear -Heqdomos.\n  unfolds in Heqdomos.\n  destruct osc.\n  destruct p.\n  destruct A.\n  destruct p1.\n  simpl in *.\n  mytac.\n  auto.\nQed.\n\n\n\nTheorem toptheorem:\n  forall osc A (init:InitAsrt) (I:Inv) (Spec:funspec) li,\n    no_fun_same (get_afun osc)  (get_ifun osc)->\n    no_call_api_os (get_afun osc) (get_ifun osc) (get_lint osc) ->\n    (forall f t d1 d2 s, (fst (fst osc)) f = Some (t,d1,d2,s) ->\n                         good_decllist (revlcons d1 d2) = true /\\ GoodStmt' s) ->\n    (forall f t d1 d2 s, (snd (fst osc)) f = Some (t,d1,d2,s) ->\n                         good_decllist (revlcons d1 d2) = true/\\GoodStmt' s) ->\n    GoodI I (snd A) li->\n    (\n      forall i isrreg si p r tid lg,\n        Some p = BuildintPre i (snd (fst A)) isrreg si I li tid lg ->\n        Some r = BuildintRet i (snd (fst A)) isrreg si I li tid lg ->\n        exists s,\n          (get_lint osc) i = Some s /\\\n          {|Spec , (snd A), li, I, retfalse, r|}|-tid {{p}}s {{Afalse}}\n      \n    )->\n    (\n      forall (f:fid) ab vl p r ft tid, \n        (fst (fst A)) f = Some (ab,ft) ->\n        Some p = BuildPreA' (get_afun osc) f (ab,ft) vl li tid init_lg ->\n        Some r = BuildRetA' (get_afun osc) f (ab,ft) vl li tid init_lg ->\n        (\n          exists  t d1 d2 s,\n            (get_afun osc) f = Some (t, d1, d2, s) /\\\n            InfRules Spec (snd A) li I r Afalse p s Afalse tid\n        )\n    )->\n    WFFunEnv (get_ifun osc) Spec (snd A) li I ->\n    (\n      eqdomOS osc A /\\ \n      side_condition I li (snd A) init init_lg\n    )\n->\nOSCorrect osc A init.\nProof.\n  intros.\n  eapply toptheorem';eauto.\n  intros.\n  lets Hx:H5 H8 H9 H10.\n  mytac.\n  do 4 eexists;splits;eauto.\n  unfold get_afun in *.\n  lets Hx:H1 H11.\n  destruct Hx;auto.\nQed.\n   \n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/framework/proof/lemmasfortoptheo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.1617763071659897}}
{"text": "Require Import Coq.ZArith.ZArith.\nLocal Open Scope Z_scope.\n\n(* from opentitan/sw/device/silicon_creator/lib/absl_status.h *)\nDefinition kOk := 0.\nDefinition kCancelled := 1.\nDefinition kUnknown := 2.\nDefinition kInvalidArgument := 3.\nDefinition kDeadlineExceeded := 4.\nDefinition kNotFound := 5.\nDefinition kAlreadyExists := 6.\nDefinition kPermissionDenied := 7.\nDefinition kResourceExhausted := 8.\nDefinition kFailedPrecondition := 9.\nDefinition kAborted := 10.\nDefinition kOutOfRange := 11.\nDefinition kUnimplemented := 12.\nDefinition kInternal := 13.\nDefinition kUnavailable := 14.\nDefinition kDataLoss := 15.\nDefinition kUnauthenticated := 16.\n\n(* from opentitan/sw/device/silicon_creator/lib/error.h *)\nDefinition kModuleUnknown := 0.\nDefinition kModuleAlertHandler := 0x4148.\nDefinition kModuleUart := 0x4155.\nDefinition kModuleHmac := 0x4d48.\nDefinition kModuleSigverify := 0x5653.\nDefinition kModuleKeymgr := 0x4d4b.\nDefinition kModuleManifest := 0x414d.\nDefinition kModuleRomextimage := 0x4552.\nDefinition ERROR_(error_ module_ status_: Z): Z :=\n  Z.lor (Z.shiftl error_ 24) (Z.lor (Z.shiftl module_ 8) status_).\nDefinition kErrorOk := 0x739.\nDefinition kErrorUartInvalidArgument :=        ERROR_ 1 kModuleUart kInvalidArgument.\nDefinition kErrorUartBadBaudRate :=            ERROR_ 2 kModuleUart kInvalidArgument.\nDefinition kErrorHmacInvalidArgument :=        ERROR_ 1 kModuleHmac kInvalidArgument.\nDefinition kErrorSigverifyInvalidArgument :=   ERROR_ 1 kModuleSigverify kInvalidArgument.\nDefinition kErrorKeymgrInternal :=             ERROR_ 1 kModuleKeymgr kInternal.\nDefinition kErrorManifestInternal :=           ERROR_ 1 kModuleManifest kInternal.\nDefinition kErrorRomextimageInvalidArgument := ERROR_ 1 kModuleRomextimage kInvalidArgument.\nDefinition kErrorRomextimageInternal :=        ERROR_ 2 kModuleRomextimage kInternal.\nDefinition kErrorAlertBadIndex :=              ERROR_ 1 kModuleAlertHandler kInvalidArgument.\nDefinition kErrorAlertBadClass :=              ERROR_ 2 kModuleAlertHandler kInvalidArgument.\nDefinition kErrorAlertBadEnable :=             ERROR_ 3 kModuleAlertHandler kInvalidArgument.\nDefinition kErrorAlertBadEscalation :=         ERROR_ 4 kModuleAlertHandler kInvalidArgument.\nDefinition kErrorUnknown := 0xFFFFFFFF.\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/LibBase/Constants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.16177630373209784}}
{"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\n\n(* Converted imports: *)\n\nRequire BasicTypes.\nRequire BinNat.\nRequire BinNums.\nRequire Coq.ZArith.BinInt.\nRequire Data.Bits.\nRequire FastString.\nRequire GHC.Base.\nRequire GHC.Char.\nRequire GHC.Num.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nInductive Unique : Type := MkUnique : BinNums.N -> Unique.\n\nRecord Uniquable__Dict a := Uniquable__Dict_Build {\n  getUnique__ : a -> Unique }.\n\nDefinition Uniquable a :=\n  forall r__, (Uniquable__Dict a -> r__) -> r__.\n\nExisting Class Uniquable.\n\nDefinition getUnique `{g__0__ : Uniquable a} : a -> Unique :=\n  g__0__ _ (getUnique__ a).\n\n(* Midamble *)\n\n\nInstance Default__Name : GHC.Err.Default Unique\n  := GHC.Err.Build_Default _ (MkUnique GHC.Err.default).\n\nProgram Instance Uniquable__Word : Uniquable GHC.Num.Word :=\n  fun _ k => k {| getUnique__ x := MkUnique x |}.\n\n\n(* Parameter mkUnique : GHC.Char.Char -> GHC.Num.Word -> Unique. *)\n\n(* Converted value declarations: *)\n\nDefinition uNIQUE_BITS : GHC.Num.Int :=\n  #56.\n\nDefinition uniqueMask : GHC.Num.Int :=\n  Data.Bits.shiftL #1 uNIQUE_BITS GHC.Num.- #1.\n\nDefinition unpkUnique : Unique -> GHC.Char.Char * GHC.Num.Int :=\n  fun '(MkUnique u) =>\n    let i := Coq.ZArith.BinInt.Z.land (Coq.ZArith.BinInt.Z.of_N u) uniqueMask in\n    let tag :=\n      GHC.Char.chr (Data.Bits.shiftR (Coq.ZArith.BinInt.Z.of_N u) uNIQUE_BITS) in\n    pair tag i.\n\nDefinition stepUnique : Unique -> BinNums.N -> Unique :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | MkUnique i, n => MkUnique (i GHC.Num.+ n)\n    end.\n\nDefinition nonDetCmpUnique : Unique -> Unique -> comparison :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | MkUnique u1, MkUnique u2 =>\n        if u1 GHC.Base.== u2 : bool\n        then Eq\n        else if u1 GHC.Base.< u2 : bool\n             then Lt\n             else Gt\n    end.\n\nDefinition mkUniqueGrimily : BinNums.N -> Unique :=\n  MkUnique.\n\nDefinition mkUnique : GHC.Char.Char -> GHC.Num.Word -> Unique :=\n  fun c i =>\n    let bits := Coq.ZArith.BinInt.Z.land (Coq.ZArith.BinInt.Z.of_N i) uniqueMask in\n    let tag := Data.Bits.shiftL (GHC.Base.ord c) uNIQUE_BITS in\n    MkUnique (Coq.ZArith.BinInt.Z.to_N (Coq.ZArith.BinInt.Z.lor tag bits)).\n\nDefinition mkVarOccUnique : FastString.FastString -> Unique :=\n  fun fs => mkUnique (GHC.Char.hs_char__ \"i\") (FastString.uniqueOfFS fs).\n\nDefinition mkTvOccUnique : FastString.FastString -> Unique :=\n  fun fs => mkUnique (GHC.Char.hs_char__ \"v\") (FastString.uniqueOfFS fs).\n\nDefinition mkTcOccUnique : FastString.FastString -> Unique :=\n  fun fs => mkUnique (GHC.Char.hs_char__ \"c\") (FastString.uniqueOfFS fs).\n\nDefinition mkRegSubUnique : BinNums.N -> Unique :=\n  mkUnique (GHC.Char.hs_char__ \"S\").\n\nDefinition mkRegSingleUnique : BinNums.N -> Unique :=\n  mkUnique (GHC.Char.hs_char__ \"R\").\n\nDefinition mkRegPairUnique : BinNums.N -> Unique :=\n  mkUnique (GHC.Char.hs_char__ \"P\").\n\nDefinition mkRegClassUnique : BinNums.N -> Unique :=\n  mkUnique (GHC.Char.hs_char__ \"L\").\n\nDefinition mkPseudoUniqueH : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"H\") i.\n\nDefinition mkPseudoUniqueE : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"E\") i.\n\nDefinition mkPseudoUniqueD : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"D\") i.\n\nDefinition mkPrimOpIdUnique : BinNums.N -> Unique :=\n  fun op => mkUnique (GHC.Char.hs_char__ \"9\") op.\n\nDefinition mkPreludeTyConUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"3\") (#2 GHC.Num.* i).\n\nDefinition mkPreludeMiscIdUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"0\") i.\n\nDefinition mkPreludeDataConUnique : BasicTypes.Arity -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"6\") (#3 GHC.Num.* BinNat.N.of_nat i).\n\nDefinition mkPreludeClassUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"2\") i.\n\nDefinition mkPArrDataConUnique : BinNums.N -> Unique :=\n  fun a => mkUnique (GHC.Char.hs_char__ \":\") (#2 GHC.Num.* a).\n\nDefinition mkDataOccUnique : FastString.FastString -> Unique :=\n  fun fs => mkUnique (GHC.Char.hs_char__ \"d\") (FastString.uniqueOfFS fs).\n\nDefinition mkCostCentreUnique : BinNums.N -> Unique :=\n  mkUnique (GHC.Char.hs_char__ \"C\").\n\nDefinition mkCoVarUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"g\") i.\n\nDefinition mkBuiltinUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"B\") i.\n\nDefinition mkAlphaTyVarUnique : BinNums.N -> Unique :=\n  fun i => mkUnique (GHC.Char.hs_char__ \"1\") i.\n\nDefinition isValidKnownKeyUnique : Unique -> bool :=\n  fun u =>\n    let 'pair c x := unpkUnique u in\n    andb (GHC.Base.ord c GHC.Base.< #255) (x GHC.Base.<= (Data.Bits.shiftL #1 #22)).\n\nDefinition initTyVarUnique : Unique :=\n  mkUnique (GHC.Char.hs_char__ \"t\") #0.\n\nDefinition initExitJoinUnique : Unique :=\n  mkUnique (GHC.Char.hs_char__ \"s\") #0.\n\nDefinition incrUnique : Unique -> Unique :=\n  fun '(MkUnique i) => MkUnique (i GHC.Num.+ #1).\n\nDefinition tyConRepNameUnique : Unique -> Unique :=\n  fun u => incrUnique u.\n\nDefinition eqUnique : Unique -> Unique -> bool :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | MkUnique u1, MkUnique u2 => u1 GHC.Base.== u2\n    end.\n\nLocal Definition Eq___Unique_op_zeze__ : Unique -> Unique -> bool :=\n  fun a b => eqUnique a b.\n\nLocal Definition Eq___Unique_op_zsze__ : Unique -> Unique -> bool :=\n  fun a b => negb (eqUnique a b).\n\nProgram Instance Eq___Unique : GHC.Base.Eq_ Unique :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___Unique_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___Unique_op_zsze__ |}.\n\nDefinition hasKey {a} `{Uniquable a} : a -> Unique -> bool :=\n  fun x k => getUnique x GHC.Base.== k.\n\nDefinition getKey : Unique -> BinNums.N :=\n  fun '(MkUnique x) => x.\n\nDefinition deriveUnique : Unique -> BinNums.N -> Unique :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | MkUnique i, delta => mkUnique (GHC.Char.hs_char__ \"X\") (i GHC.Num.+ delta)\n    end.\n\nDefinition dataConWorkerUnique : Unique -> Unique :=\n  fun u => incrUnique u.\n\nDefinition dataConRepNameUnique : Unique -> Unique :=\n  fun u => stepUnique u #2.\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Unique.Show__Unique' *)\n\n(* Skipping all instances of class `Outputable.Outputable', including\n   `Unique.Outputable__Unique' *)\n\nLocal Definition Uniquable__Unique_getUnique : Unique -> Unique :=\n  fun u => u.\n\nProgram Instance Uniquable__Unique : Uniquable Unique :=\n  fun _ k__ => k__ {| getUnique__ := Uniquable__Unique_getUnique |}.\n\nLocal Definition Uniquable__N_getUnique : BinNums.N -> Unique :=\n  fun i => mkUniqueGrimily i.\n\nProgram Instance Uniquable__N : Uniquable BinNums.N :=\n  fun _ k__ => k__ {| getUnique__ := Uniquable__N_getUnique |}.\n\nLocal Definition Uniquable__FastString_getUnique\n   : FastString.FastString -> Unique :=\n  fun fs => mkUniqueGrimily (FastString.uniqueOfFS fs).\n\nProgram Instance Uniquable__FastString : Uniquable FastString.FastString :=\n  fun _ k__ => k__ {| getUnique__ := Uniquable__FastString_getUnique |}.\n\nDefinition getWordKey : Unique -> GHC.Num.Word :=\n  getKey.\n\n(* External variables:\n     Eq Gt Lt andb bool comparison negb op_zt__ pair BasicTypes.Arity BinNat.N.of_nat\n     BinNums.N Coq.ZArith.BinInt.Z.land Coq.ZArith.BinInt.Z.lor\n     Coq.ZArith.BinInt.Z.of_N Coq.ZArith.BinInt.Z.to_N Data.Bits.shiftL\n     Data.Bits.shiftR FastString.FastString FastString.uniqueOfFS GHC.Base.Eq_\n     GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zl__ GHC.Base.op_zlze__\n     GHC.Base.op_zsze____ GHC.Base.ord GHC.Char.Char GHC.Char.chr GHC.Num.Int\n     GHC.Num.Word GHC.Num.fromInteger GHC.Num.op_zm__ GHC.Num.op_zp__ GHC.Num.op_zt__\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/lib/Unique.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.16175154168791486}}
{"text": "Require Import Privilege.\nRequire Import Env.\n\nRequire Import Ctl.Ctl.\nRequire Import Glib.Glib.\n\nOpen Scope string_scope.\nOpen Scope env_scope.\n\n\n(* value types *)\n\nInductive boot_token_t :=\n  | good_boot_token\n  | bad_boot_token.\nInductive vm_ev_t :=\n  | good_vm_ev\n  | bad_vm_ev.\nInductive platam_key_t :=\n  | good_platam_key\n  | encr_platam_key\n  | bad_platam_key.\nInductive useram_key_t :=\n  | good_useram_key\n  | encr_useram_key\n  | bad_useram_key.\nInductive useram_key_decr_key_t :=\n  | good_decr_key\n  | encr_decr_key\n  | bad_decr_key.\nInductive attest_req_t :=\n  | attest_req.\n\n\n(* Transition definitions *)\n\nInductive platam_label :=\n  | platam_init \n  | platam_meas_release\n  | platam_listen\n  | platam_deep_attest.\n\nDefinition platam_init_env : env :=\n  only \"platam\" ? (\n    \"platam_key\" \u21a6 encr_platam_key ;;\n    \"useram_key_decr_key\" \u21a6 encr_decr_key\n  ).\n\nDefinition decrypt_platam_key key token : platam_key_t := \n  match (key, token) with \n  | (encr_platam_key, good_boot_token) => good_platam_key\n  | _ => bad_platam_key\n  end.\n\nDefinition decrypt_useram_key_decr_key decr_key platam_key : useram_key_decr_key_t := \n  match (decr_key, platam_key) with \n  | (encr_decr_key, good_platam_key) => good_decr_key\n  | _ => bad_decr_key\n  end.\n\nInductive platam_trans : relation (platam_label \u00d7 env) := \n  | platam_unlock_key : forall \u0393 \u0393' key token,\n      read  \u0393 \"platam\" \"platam_key\" key ->\n      read  \u0393 \"platam\" \"boot_token\" token ->\n      write \u0393 \"platam\" \"platam_key\" (decrypt_platam_key key token) \u0393' ->\n      platam_trans \n        (platam_init, \u0393)\n        (platam_meas_release, \u0393')\n  | platam_measure_release : forall \u0393 \u0393' platam_key decr_key,\n      read  \u0393 \"platam\" \"good_os\" true ->\n      read  \u0393 \"platam\" \"useram_key_decr_key\" decr_key ->\n      read  \u0393 \"platam\" \"platam_key\" platam_key -> \n      write \u0393 \"platam\" \"vmm_dataport\" (decrypt_useram_key_decr_key decr_key platam_key) \u0393' ->\n      platam_trans \n        (platam_meas_release, \u0393)\n        (platam_listen, \u0393')\n  | platam_get_deep_attest_req : forall \u0393,\n      read \u0393 \"platam\" \"vmm_dataport\" attest_req ->\n      platam_trans\n        (platam_listen, \u0393)\n        (platam_deep_attest, \u0393)\n  | platam_do_deep_attest : forall \u0393 \u0393' (meas: bool),\n      read  \u0393 \"platam\" \"good_os\" meas ->\n      write \u0393 \"platam\" \"vmm_dataport\" meas \u0393' ->\n      platam_trans\n        (platam_deep_attest, \u0393)\n        (platam_listen, \u0393').\n\nInductive useram_label := \n  | useram_wait_key\n  | useram_listen\n  | useram_shallow_attest\n  | useram_deep_attest.\n\nDefinition useram_init_env : env := \n  only \"useram\" ? \"useram_key\" \u21a6 encr_useram_key.\n\nDefinition decrypt_useram_key key decr_key : useram_key_t := \n  match (key, decr_key) with \n  | (encr_useram_key, good_decr_key) => good_useram_key\n  | _ => bad_useram_key\n  end.\n\nDefinition shallow_attest (good_os good_target good_meas: bool) :=\n  good_os -> good_target -> good_meas.\n\nInductive useram_trans : relation (useram_label \u00d7 env) :=\n  | useram_get_key : forall \u0393 \u0393' encr_key decr_key,\n      read  \u0393 \"useram\" \"useram_key\" encr_key ->\n      read  \u0393 \"useram\" \"vmm_dataport\" decr_key ->\n      write \u0393 \"useram\" \"useram_key\" (decrypt_useram_key encr_key decr_key) \u0393' ->\n      useram_trans \n        (useram_wait_key, \u0393)\n        (useram_listen, \u0393')\n  | useram_get_shallow_req : forall \u0393,\n      useram_trans\n        (useram_listen, \u0393)\n        (useram_shallow_attest, \u0393)\n  | useram_do_shallow_attest : forall \u0393 \u0393' os target meas,\n      read  \u0393 \"useram\" \"good_os\" os ->\n      read  \u0393 \"useram\" \"good_target\" target ->\n      shallow_attest os target meas ->\n      write \u0393 \"useram\" \"shallow_attest_result\" meas \u0393' ->\n      useram_trans\n        (useram_shallow_attest, \u0393)\n        (useram_listen, \u0393)\n  | useram_get_deep_req : forall \u0393 \u0393',\n      write \u0393 \"useram\" \"vmm_dataport\" attest_req \u0393' ->\n      useram_trans\n        (useram_listen, \u0393)\n        (useram_deep_attest, \u0393')\n  | useram_wait_deep_attest : forall \u0393 (meas: bool),\n      read \u0393 \"useram\" \"vmm_dataport\" meas ->\n      useram_trans\n        (useram_deep_attest, \u0393)\n        (useram_listen, \u0393).\n\n\nInductive malicious_proc_trans : relation env :=\n  | corrupt_os : forall \u0393 \u0393',\n      write \u0393 \"malicious_proc\" \"good_os\" false \u0393' ->\n      malicious_proc_trans \u0393 \u0393'\n  | corrupt_target : forall \u0393 \u0393',\n      write \u0393 \"malicious_proc\" \"good_target\" false \u0393' ->\n      malicious_proc_trans \u0393 \u0393'\n  | leak_key : forall \u0393 \u0393',\n      read \u0393 \"malicious_proc\" \"good_os\" false ->\n      changeAcc \u0393 \"useram_key\" (\u03bb acc, canRead \"malicious_proc\" \u2294 acc) \u0393' ->\n      malicious_proc_trans \u0393 \u0393'.\n\n\nDefinition vm_init_env : env := \n  readable \u2294 canWrite \"malicious_proc\" ? \"good_os\" \u21a6 true;;\n  useram_init_env.\n\nInductive vm_label := \n  | vm_run : useram_label -> vm_label.\n\nInductive vm_trans : relation (vm_label \u00d7 env) := \n  | useram_step : forall x y \u0393 \u0393',\n      useram_trans (x, \u0393) (y, \u0393') ->\n      vm_trans (vm_run x, \u0393) (vm_run y, \u0393')\n  | malicious_proc_step : forall x \u0393 \u0393',\n      malicious_proc_trans \u0393 \u0393' ->\n      vm_trans (vm_run x, \u0393) (vm_run x, \u0393').\n\n\nInductive attarch_label :=\n  | boot\n  | sel4_run : platam_label -> vm_label -> attarch_label\n  | attarch_bot.\n\nDefinition attarch_state := attarch_label \u00d7 env.\n\nInductive attarch_trans : relation attarch_state :=\n  | boot_good : forall \u0393,\n      read \u0393 \"root_of_trust\" \"good_image\" true -> \n      attarch_trans\n        (boot, \u0393)\n        (sel4_run platam_init (vm_run useram_wait_key),\n          readable ? \"boot_token\" \u21a6 good_boot_token;;\n          platam_init_env;; vm_init_env;; \u0393\n        )\n  | boot_bad : forall \u0393,\n      read \u0393 \"root_of_trust\" \"good_image\" false -> \n      attarch_trans\n        (boot, \u0393)\n        (sel4_run platam_init (vm_run useram_wait_key),\n          readable ? \"boot_token\" \u21a6 bad_boot_token;;\n          platam_init_env;; vm_init_env;; \u0393\n        )\n  | platam_step : forall x l l' \u0393 \u0393',\n      platam_trans (l, \u0393) (l', \u0393') ->\n      attarch_trans \n        (sel4_run l x, \u0393)\n        (sel4_run l' x, \u0393')\n  | vm_step : forall x l l' \u0393 \u0393',\n      vm_trans (l, \u0393) (l', \u0393') ->\n      attarch_trans \n        (sel4_run x l, \u0393)\n        (sel4_run x l', \u0393')\n | attarch_diverge : forall l \u0393,\n      attarch_trans (l, \u0393) (attarch_bot, \u0393).\n\n\nDefinition attarch_good_init_state : attarch_state := \n  (boot, readable ? \"good_image\" \u21a6 true).\n\nDefinition attarch_bad_init_state : attarch_state := \n  (boot, readable ? \"good_image\" \u21a6 false).\n\n(* Definition is_init_attarch_state (s: attarch_state) : Prop := \n  s = attarch_good_init_state \\/ \n  s = attarch_bad_init_state. *)\n\nDefinition is_init_state : tprop attarch_state := <[\u03bb s,\n  s = attarch_good_init_state \\/ \n  s = attarch_bad_init_state\n]>.\n\nLemma attarch_trans_serial : \n  serial_witness attarch_trans.\nProof using.\n  follows cbv.\nDefined.\n\nInstance transition__attarch_trans : transition attarch_trans :=\n  { trans_serial := attarch_trans_serial }.\n\n\nLtac _attarch_step_inv H :=\n  lazymatch type of H with \n  | attarch_trans _ _ => idtac\n  | platam_trans _ _ => idtac\n  | vm_trans _ _ => idtac\n  | malicious_proc_trans _ _ => idtac\n  | useram_trans _ _ => idtac\n  end;\n  invc H;\n  try find _attarch_step_inv.\nLtac attarch_step_inv := \n  find _attarch_step_inv.\n\n\nClose Scope env_scope.\nClose Scope string_scope.\n", "meta": {"author": "ku-sldg", "repo": "attarch-model", "sha": "f03a2f534ccb78a1ed947d949841829f3e3ca838", "save_path": "github-repos/coq/ku-sldg-attarch-model", "path": "github-repos/coq/ku-sldg-attarch-model/attarch-model-f03a2f534ccb78a1ed947d949841829f3e3ca838/src/AttarchTrans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.16175152721355424}}
{"text": "(*\n * \u00a9 2020 XXX.\n * \n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List\n     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ModelCheck\n     ModelCheck.ProtocolFunctions\n     ModelCheck.PartialOrderReduction\n     ModelCheck.SilentStepElimination\n.\n\nFrom protocols Require Import GenProto.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require 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 MyProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import MyProtocol.\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 SetLemmas.\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 safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (fun st => safety st /\\ alignment st /\\ returns_align st).\n  Proof.\n    autounfold; eapply invariant_weaken.\n\n    - eapply multiStepClosure_ok; simpl.\n      (* Calls to gen1 will need to be addded here until the model checking terminates. *)\n\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      \n    (* The remaining parts of the proof script shouldn't need to change. *)\n    - intros.\n      simpl in *.\n\n      sets_invert; split_ex\n      ; simpl in *; autounfold with core\n      ; subst; simpl\n      ; unfold safety, alignment, returns_align\n      ; ( repeat simple apply conj\n          ; [ solve_honest_actions_safe; clean_map_lookups; eauto 8\n            | trivial\n            | unfold labels_align; intros; rstep; subst; solve_labels_align\n            | try solve [ intros; find_step_or_solve ] \n        ]).\n\n      Unshelve.\n      all: exact 0 || auto.\n\n  Qed.\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    - solve_perm_merges; eauto.\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_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\n\nEnd MyProtocolSecure.\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/protocols/GenProtoSS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.16174625938021295}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\nRequire Import Bool.\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 MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import FulfillStep.\nRequire Import MemoryReorder.\n\nRequire Import PromiseConsistent.\n\nSet Implicit Arguments.\n\n\nLemma reorder_promise_read\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1 kind1\n      loc2 to2 val2 released2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.read_step lc1 mem1 loc2 to2 val2 released2 ord2 lc2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (LOCTS: (loc1, to1) <> (loc2, to2)):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 msg1 lc2 mem1 kind1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit MemoryFacts.promise_get_inv_diff; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_promise_promise_lower_None\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 (Message.full val2 None) lc2 mem2 kind2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (KIND2: Memory.op_kind_is_lower kind2 = true):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ Message.le (Message.full val2 None) msg1 /\\ kind2 = Memory.op_kind_lower msg1 /\\\n   exists kind1', <<STEP: Local.promise_step lc0 mem0 loc1 from1 to1 (Message.full val2 None) lc2 mem2 kind1'>>) \\/\n  (exists lc1' mem1' from2' kind1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2' to2 (Message.full val2 None) lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 msg1 lc2 mem2 kind1'>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE0; inv KIND2. des. subst.\n  inv PROMISE; ss.\n  - exploit MemoryReorder.add_lower; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n    + subst.\n      exploit MemoryReorder.add_lower; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n      left. esplits; ss.\n      * inv MEM. inv LOWER. ss.\n      * econs; eauto. econs; eauto; congr.\n    + exploit MemoryReorder.add_lower; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n      right. esplits; eauto; econs; eauto.\n      * econs; eauto.\n        { i. subst. exploit RESERVE; eauto. i. des.\n          erewrite Memory.lower_o; eauto. condtac; ss; eauto. }\n        { i. revert GET.\n          erewrite Memory.lower_o; eauto. condtac; ss.\n          - i. des. subst. inv GET.\n            exploit Memory.lower_get0; try exact MEM. i. des.\n            revert GET. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n            des. subst. inv MEM. inv LOWER. timetac.\n          - i. exploit Memory.lower_get1; try exact GET; eauto. }\n      * eapply Memory.lower_closed_message; eauto.\n  - des. subst.\n    destruct (classic ((loc1, ts3) = (loc2, to2))).\n    { inv H.\n      exploit MemoryReorder.split_lower_same; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n      exploit MemoryReorder.split_lower_same; try exact MEM1; try exact MEM; eauto. i. des.\n      subst. right. esplits; eauto; econs; eauto.\n      eapply Memory.lower_closed_message; eauto.\n    }\n    { exploit MemoryReorder.split_lower_diff; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n      - subst. inv x3.\n        exploit MemoryReorder.split_lower_diff; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n        left. esplits; eauto. inv MEM. inv LOWER. ss.\n      - exploit MemoryReorder.split_lower_diff; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n        right. esplits; eauto; econs; eauto.\n        eapply Memory.lower_closed_message; eauto.\n    }\n  - des. subst.\n    exploit MemoryReorder.lower_lower; try exact PROMISES0; try exact PROMISES; eauto. i. des.\n    + subst.\n      exploit MemoryReorder.lower_lower; try exact MEM1; try exact MEM; eauto. i. des; [|congr].\n      left. esplits; eauto. inv MEM. inv LOWER. ss.\n    + exploit MemoryReorder.lower_lower; try exact MEM1; try exact MEM; eauto. i. des; [congr|].\n      right. esplits; eauto; econs; eauto.\n      eapply Memory.lower_closed_message; cycle 1; eauto.\nQed.\n\nLemma reorder_promise_promise_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (KIND2: Memory.op_kind_is_cancel kind2 = true):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = Message.reserve /\\ kind1 = Memory.op_kind_add /\\\n   lc0 = lc2 /\\ mem0 = mem2) \\/\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg1 = Message.reserve /\\ kind1 = Memory.op_kind_lower Message.reserve /\\\n   <<STEP: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc2 mem2 kind2>>) \\/\n  (exists lc1' mem1' from2' kind1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2' to2 msg2 lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 msg1 lc2 mem2 kind1'>>).\nProof.\n  inv STEP1. inv STEP2. ss. inv PROMISE0; inv KIND2. inv PROMISE; ss.\n  - destruct (classic ((loc1, to1) = (loc2, to2))).\n    + inv H.\n      exploit MemoryReorder.add_remove_same; try exact PROMISES0; eauto. i. des. subst.\n      exploit MemoryReorder.add_remove_same; try exact MEM1; eauto. i. des. subst.\n      left. splits; auto. destruct lc0; ss.\n    + exploit MemoryReorder.add_remove; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.add_remove; try exact MEM1; eauto. i. des.\n      right. right. esplits; eauto. econs; eauto.\n      * econs; eauto.\n        { i. subst.\n          exploit RESERVE; eauto. i. des.\n          exploit Memory.remove_get1; try exact x; eauto. i. des; eauto.\n          subst. exploit Memory.remove_get0; try exact REMOVE0; eauto. i. des. congr. }\n        { i. revert GET.\n          erewrite Memory.remove_o; eauto. condtac; ss. eauto. }\n      * eapply Memory.cancel_closed_message; eauto.\n  - destruct (classic ((loc1, ts3) = (loc2, to2))).\n    + des. subst. inv H.\n      exploit MemoryReorder.split_remove_same; try exact PROMISES0; eauto. i. des. subst.\n      exploit MemoryReorder.split_remove_same; try exact MEM1; eauto. i. des. subst.\n      right. right. esplits; eauto. econs; eauto.\n      * econs 1; eauto; ss.\n        i. revert GET.\n        erewrite Memory.remove_o; eauto. condtac; ss. i. des; ss.\n        exploit Memory.split_get0; try exact MEM1. i. des.\n        clear GET0 GET2 GET3.\n        exploit Memory.get_ts; try exact GET. i. des.\n        { subst. inv ADD2. inv ADD. inv TO. }\n        exploit Memory.get_ts; try exact GET1. i. des.\n        { subst. inv MEM1. inv SPLIT. inv TS23. }\n        exploit Memory.get_disjoint; [exact GET|exact GET1|..]. i. des.\n        { subst. inv MEM1. inv SPLIT. timetac. }\n        destruct (TimeFacts.le_lt_dec to' to2).\n        { apply (x4 to'); econs; ss; try refl.\n          inv MEM1. inv SPLIT. etrans; eauto. }\n        { apply (x4 to2); econs; ss; try refl.\n          - inv MEM1. inv SPLIT. ss.\n          - econs. ss. }\n      * eapply Memory.cancel_closed_message; eauto.\n    + destruct (classic ((loc1, to1) = (loc2, to2))).\n      { des. inv H0.\n        exploit Memory.split_get0; try exact MEM1. i. des.\n        exploit Memory.remove_get0; try exact MEM. i. des. congr. }\n      exploit MemoryReorder.split_remove; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.split_remove; try exact MEM1; eauto. i. des.\n      right. right. esplits; eauto. econs; eauto.\n      eapply Memory.cancel_closed_message; eauto.\n  - des. subst.\n    destruct (classic ((loc1, to1) = (loc2, to2))).\n    + inv H.\n      exploit MemoryReorder.lower_remove_same; try exact PROMISES0; eauto. i. des. subst.\n      exploit MemoryReorder.lower_remove_same; try exact MEM1; eauto. i. des. subst.\n      exploit Memory.lower_get0; try exact MEM1. i. des. inv MSG_LE.\n    + exploit MemoryReorder.lower_remove; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.lower_remove; try exact MEM1; eauto. i. des.\n      right. right. esplits; eauto. econs; eauto.\n      eapply Memory.cancel_closed_message; eauto.\nQed.\n\nLemma reorder_promise_promise\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 released2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 (Message.full val2 released2) lc2 mem2 kind2)\n      (REL_CLOSED: forall promises1' mem1' kind1'\n                     (PROMISE1: Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 (Message.full val2 released2) promises1' mem1' kind1'),\n          Memory.closed_opt_view released2 mem1')\n      (LOCAL0: Local.wf lc0 mem0)\n      (CLOSED0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (LOCTS1: forall to1' msg1'\n                (LOC: loc1 = loc2)\n                (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2 /\\\n          (forall msg2', kind2 <> Memory.op_kind_split to1' msg2'))\n      (LOCTS2: forall val released\n                 (LOC: loc1 = loc2)\n                 (KIND1: kind1 = Memory.op_kind_add)\n                 (KIND2: kind2 = Memory.op_kind_add)\n                 (MSG1: msg1 = Message.full val released),\n               Time.lt to2 to1):\n  exists lc1' mem1' kind2',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 (Message.full val2 released2) lc1' mem1' kind2'>> /\\\n    <<STEP2: __guard__\n               ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                (exists from1' kind1',\n                    (loc1, to1) <> (loc2, to2) /\\\n                    (forall to1' msg1'\n                       (LOC: loc1 = loc2)\n                       (KIND: kind1' = Memory.op_kind_split to1' msg1'),\n                        to1' <> to2 /\\\n                        (forall msg2', kind2 <> Memory.op_kind_split to1' msg2')) /\\\n                    Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'))>> /\\\n    <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE; ss.\n  { inv PROMISE0; ss.\n    - (* add/add *)\n      exploit MemoryReorder.add_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.add_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 (Message.full val2 released2)\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.add_get1; try exact MEM; eauto.\n      + right. esplits; eauto. econs; eauto.\n        * econs; eauto.\n          { i. subst.\n            erewrite Memory.add_o; eauto. condtac; ss; eauto. }\n          { i. revert GET.\n            erewrite Memory.add_o; eauto. condtac; ss; eauto.\n            i. des. inv GET.\n            exploit LOCTS2; eauto. intro x.\n            inv ADD0. inv ADD. rewrite x in TO. timetac.\n          }\n        * eapply Memory.add_closed_message; cycle 1; eauto.\n      + auto.\n    - (* add/split *)\n      exploit MemoryReorder.add_split; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst. inv RESERVE0.\n        exploit MemoryReorder.add_split; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 (Message.full val' released')\n                              mem1' mem1'0 Memory.op_kind_add).\n          { i. econs; eauto. }\n          econs; eauto; try congr.\n          i. exploit Memory.add_get1; try exact GET; try exact MEM. i.\n          exploit Memory.add_get0; try exact MEM. i. des.\n          clear GET GET0.\n          exploit Memory.get_ts; try exact x4. i. des.\n          { subst. inv ADD0. inv ADD. inv TO. }\n          exploit Memory.get_ts; try exact GET1. i. des.\n          { subst. inv ADD3. inv ADD. inv TO. }\n          exploit Memory.get_disjoint; [exact x4|exact GET1|..]. i. des.\n          { subst. inv ADD0. inv ADD. timetac. }\n          destruct (TimeFacts.le_lt_dec to' ts3).\n          { apply (x7 to'); econs; ss; try refl.\n            inv ADD0. inv ADD. etrans; eauto. }\n          { apply (x7 ts3); econs; ss; try refl.\n            - inv ADD3. inv ADD. ss.\n            - econs. ss. }\n        * right. esplits; eauto.\n          { ii. inv H. inv ADD3. inv ADD. timetac. }\n          { econs.\n            - econs; eauto.\n              + i. subst.\n                erewrite Memory.add_o; eauto. condtac; ss; eauto. des; congr.\n              + i. revert GET.\n                erewrite Memory.add_o; eauto. condtac; ss; eauto. i. des. inv GET.\n                inv ADD0. inv ADD. inv ADD3. inv ADD. rewrite TO in TO0. timetac.\n            - eapply Memory.split_closed_message; eauto.\n            - auto. }\n        * auto.\n      + inv RESERVE0.\n        exploit MemoryReorder.add_split; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.split_get0; try exact MEM0; eauto. i. des.\n            revert GET. erewrite Memory.add_o; eauto. condtac; ss. des; congr. }\n          { econs; eauto.\n            - econs; eauto.\n              + i. subst.\n                erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n                guardH o. des. subst. exploit RESERVE; eauto. intro x. des.\n                exploit Memory.split_get0; try exact SPLIT0. i. des.\n                rewrite x in GET0. inv GET0. esplits; eauto.\n              + i. revert GET.\n                erewrite Memory.split_o; eauto. repeat condtac; ss; eauto.\n                * i. des. inv GET.\n                  exploit Memory.split_get0; try exact MEM0. i. des.\n                  revert GET0. erewrite Memory.add_o; eauto. condtac; ss; eauto.\n                  i. des. inv GET0.\n                  inv MEM0. inv SPLIT. rewrite TS12 in TS23. timetac.\n                * guardH o. i. des. inv GET.\n                  exploit Memory.split_get0; try exact SPLIT0. i. des.\n                  exploit Memory.add_get0; try exact ADD0. i. des.\n                  exploit Memory.add_get1; try exact GET1; eauto. i.\n                  clear GET GET0 GET1 GET2 GET3.\n                  exploit Memory.get_ts; try exact GET4. i. des.\n                  { subst. inv SPLIT0. inv SPLIT. inv TS12. }\n                  exploit Memory.get_ts; try exact x0. i. des.\n                  { subst. inv ADD0. inv ADD. inv TO. }\n                  exploit Memory.get_disjoint; [exact GET4|exact x0|..]. i. des.\n                  { subst. exploit Memory.split_get0; try exact SPLIT0. i. des.\n                    inv ADD0. inv ADD.\n                    hexploit DISJOINT; try eapply GET1. i.\n                    apply (H to1); econs; ss; try refl. }\n                  apply (x3 to1); econs; ss; try refl.\n            - eapply Memory.split_closed_message; eauto. }\n        * auto.\n    - (* add/lower *)\n      des. subst.\n      exploit MemoryReorder.add_lower; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst.\n        exploit MemoryReorder.add_lower; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * econs; eauto. econs; eauto. congr.\n        * left. auto.\n        * auto.\n      + exploit MemoryReorder.add_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs; eauto.\n          econs. eapply REL_CLOSED; eauto.\n        * right. esplits; eauto. econs; eauto.\n          { econs; eauto.\n            - i. subst.\n              erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n            - i. revert GET.\n              erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n              i. des. inv GET.\n              exploit Memory.lower_get0; try exact LOWER0. i. des. eauto. }\n          { eapply Memory.lower_closed_message; eauto. }\n        * auto.\n  }\n  { des. subst. inv PROMISE0; ss.\n    - (* split/add *)\n      exploit MemoryReorder.split_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.split_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 (Message.full val2 released2)\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.split_get1; try exact GET; eauto. i. des.\n        dup GET2. revert GET2.\n        erewrite Memory.split_o; eauto. repeat condtac; ss.\n        * i. des. inv GET2.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          rewrite GET in *. ss.\n        * guardH o. i. des. inv GET2.\n          exploit Memory.split_get0; try exact MEM. i. des.\n          rewrite GET in *. inv GET2. eauto.\n        * i. rewrite GET in *. inv GET2. eauto.\n      + right. esplits; eauto. econs; eauto.\n        eapply Memory.add_closed_message; eauto.\n      + auto.\n    - (* split/split *)\n      des. inv RESERVE.\n      exploit MemoryReorder.split_split; try exact PROMISES; try exact PROMISES0; eauto.\n      { ii. inv H. eapply LOCTS1; eauto. }\n      i. des.\n      + subst. exploit MemoryReorder.split_split; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. inv SPLIT2. inv SPLIT. timetac. }\n        i. des; [|congr].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. inv SPLIT2. inv SPLIT. timetac. }\n          { econs; eauto.\n            eapply Memory.split_closed_message; cycle 1; eauto. }\n        * congr.\n      + exploit MemoryReorder.split_split; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. eapply LOCTS1; eauto. }\n        i. des; [congr|].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.split_get0; try exact MEM1; eauto. i. des.\n            revert GET. erewrite Memory.split_o; eauto. repeat condtac; ss.\n            guardH o0. des; congr. }\n          { econs; eauto.\n            eapply Memory.split_closed_message; cycle 1; eauto. }\n        * auto.\n    - (* split/lower *)\n      des. subst.\n      exploit MemoryReorder.split_lower_diff; try exact PROMISES; try exact PROMISES0; eauto.\n      { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n      i. des.\n      + subst. inv x3.\n        exploit MemoryReorder.split_lower_diff; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n        i. des; [|congr].\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * left. auto.\n        * congr.\n      + subst. exploit MemoryReorder.split_lower_diff; try exact MEM; try exact MEM0; eauto.\n        { ii. inv H. exploit LOCTS1; eauto. i. des. congr. }\n        i. des; [congr|].\n        esplits.\n        * econs; eauto. econs; eauto.\n        * right. esplits; eauto. econs; eauto.\n          eapply Memory.lower_closed_message; eauto.\n        * congr.\n  }\n  { des. subst. inv PROMISE0; ss.\n    - (* lower/add *)\n      exploit MemoryReorder.lower_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.lower_add; try exact MEM; try exact MEM0; eauto. i. des.\n      esplits.\n      + cut (Memory.promise (Local.promises lc0) mem0 loc2 from2 to2 (Message.full val2 released2)\n                            mem1' mem1'0 Memory.op_kind_add).\n        { i. econs; eauto. }\n        econs; eauto; try congr.\n        i. exploit Memory.lower_get1; try exact GET; eauto. i. des. eauto.\n      + right. esplits; eauto. econs; eauto.\n        eapply Memory.add_closed_message; eauto.\n      + auto.\n    - (* lower/split *)\n      des. inv RESERVE.\n      exploit MemoryReorder.lower_split; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.lower_split; try exact MEM; try exact MEM0; eauto. i. des.\n      unguardH FROM1. des.\n      + inv FROM1. unguardH FROM0. des; [|congr]. inv FROM0.\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. inv SPLIT1. inv SPLIT. timetac. }\n          { econs; eauto. eapply Memory.split_closed_message; eauto. }\n        * congr.\n      + inv FROM2. unguardH FROM0. des; [congr|]. inv FROM2.\n        esplits.\n        * econs.\n          { econs 2; eauto. }\n          { econs. eapply REL_CLOSED. econs 2; eauto. }\n          { auto. }\n        * right. esplits; eauto.\n          { ii. inv H. exploit Memory.lower_get0; try exact MEM; eauto.\n            exploit Memory.split_get0; try exact SPLIT0; eauto. i. des. congr. }\n          { econs; eauto. eapply Memory.split_closed_message; eauto. }\n        * auto.\n    - (* lower/lower *)\n      des. subst.\n      exploit MemoryReorder.lower_lower; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n      + subst.\n        exploit MemoryReorder.lower_lower; try exact MEM; try exact MEM0; eauto. i. des; [|congr].\n        esplits.\n        * econs; eauto.\n        * left. auto.\n        * congr.\n      + exploit MemoryReorder.lower_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n        esplits.\n        * econs; eauto. econs; eauto.\n        * right. esplits; eauto. econs; eauto.\n          eapply Memory.lower_closed_message; cycle 1; eauto.\n        * auto.\n  }\nQed.\n\nLemma reorder_promise_fulfill\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: fulfill_step lc1 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2)\n      (LOCAL0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (LOCTS1: (loc1, to1) <> (loc2, to2))\n      (LOCTS2: forall to1' msg1'\n                 (LOC: loc1 = loc2)\n                 (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2):\n  exists lc1',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2>> /\\\n    <<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 msg1 lc2 mem1 kind1>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  inv PROMISE; ss.\n  - exploit MemoryReorder.add_remove; try exact REMOVE; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss.\n  - exploit MemoryReorder.split_remove; try exact PROMISES; try exact REMOVE; eauto.\n    { ii. inv H. eapply LOCTS2; eauto. }\n    i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss. eauto.\n  - des. subst.\n    exploit MemoryReorder.lower_remove; try exact REMOVE; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; eauto.\n  - exploit MemoryReorder.remove_remove; try exact PROMISES; eauto. i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss. econs; ss.\nQed.\n\nLemma promise_step_nonsynch_loc_inv\n      lc1 mem1 loc from to msg lc2 mem2 kind l\n      (WF1: Local.wf lc1 mem1)\n      (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n      (NONPF: Memory.op_kind_is_lower_full kind = false \\/ ~ Message.is_released_none msg)\n      (NONSYNCH: Memory.nonsynch_loc l (Local.promises lc2)):\n  Memory.nonsynch_loc l (Local.promises lc1).\nProof.\n  guardH NONPF.\n  ii.\n  inv STEP. inv PROMISE; ss.\n  - exploit Memory.add_get1; try exact GET; eauto. i. des.\n    exploit NONSYNCH; eauto.\n  - exploit Memory.split_get1; try exact GET; eauto. i. des.\n    exploit NONSYNCH; eauto.\n  - exploit Memory.lower_o; try exact PROMISES; eauto.\n    instantiate (1 := t). instantiate (1 := l). condtac; ss.\n    + i. des. subst. exploit NONSYNCH; eauto.\n      destruct msg; destruct msg0; ss.\n      * i. subst. unguard. des; ss.\n      * exploit Memory.lower_get0; try exact PROMISES. i. des.\n        rewrite GET in GET0. inv GET0.\n        inv MEM. inv LOWER. inv MSG_LE0.\n    + rewrite GET. i. exploit NONSYNCH; eauto.\n  - exploit Memory.remove_get1; try exact GET; eauto. i. des.\n    + subst. exploit Memory.remove_get0; try exact PROMISES. i. des.\n      rewrite GET0 in GET. inv GET. ss.\n    + exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_promise_write\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2)\n      (NONPF: Memory.op_kind_is_lower_full kind1 = false \\/ ~ Message.is_released_none msg1)\n      (REL_WF: View.opt_wf releasedm2)\n      (REL_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (LOCAL0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false)\n      (LOCTS1: forall to1' msg1'\n                (LOC: loc1 = loc2)\n                (KIND: kind1 = Memory.op_kind_split to1' msg1'),\n          to1' <> to2 /\\\n          (forall msg2', kind2 <> Memory.op_kind_split to1' msg2'))\n      (LOCTS2: forall val released\n                 (LOC: loc1 = loc2)\n                 (KIND1: kind1 = Memory.op_kind_add)\n                 (KIND2: kind2 = Memory.op_kind_add)\n                 (MSG1: msg1 = Message.full val released),\n               Time.lt to2 to1):\n  exists kind2' lc1' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2'>> /\\\n    <<STEP2: __guard__\n               ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                ((loc1, to1) <> (loc2, to2) /\\\n                 exists from1' kind1', <<STEP2: Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'>>))>> /\\\n    <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>.\nProof.\n  guardH NONPF.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto; try by viewtac. i. des.\n  exploit reorder_promise_promise; try exact STEP1; eauto.\n  { i. subst.\n    exploit Memory.promise_op; eauto. i.\n    eapply TViewFacts.op_closed_released; try exact x0; eauto.\n    inv STEP1. apply LOCAL0.\n  }\n  i. des.\n  unguardH STEP5. des.\n  - inv STEP5.\n    exploit promise_fulfill_write_exact; try exact STEP4; eauto.\n    { i. hexploit ORD; eauto. i.\n      eapply promise_step_nonsynch_loc_inv; try exact STEP1; eauto.\n    }\n    { inv STEP1. ss. }\n    i. esplits; eauto. left; eauto.\n  - exploit Local.promise_step_future; try exact STEP4; eauto. i. des.\n    exploit reorder_promise_fulfill; try exact STEP6; eauto.\n    { i. eapply STEP6; eauto. }\n    i. des.\n    exploit fulfill_step_future; try exact STEP7; try exact WF0; eauto; try by viewtac. i. des.\n    exploit promise_fulfill_write_exact; try exact STEP4; eauto; try by viewtac.\n    { i. hexploit ORD; eauto. i.\n      eapply promise_step_nonsynch_loc_inv; try exact STEP1; eauto.\n    }\n    { subst. inv STEP1. ss. }\n    i. esplits; eauto. right. esplits; eauto.\nQed.\n\nLemma reorder_promise_write'\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1 kind1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1 mem1 kind1)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2)\n      (NONPF: Memory.op_kind_is_lower_full kind1 = false \\/ ~ Message.is_released_none msg1)\n      (REL_WF: View.opt_wf releasedm2)\n      (REL_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (LOCAL0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND1: Memory.op_kind_is_cancel kind1 = false):\n  (loc1 = loc2 /\\ Time.lt to1 to2) \\/\n  (exists kind2' lc1' mem1',\n     <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2'>> /\\\n     <<STEP2: __guard__\n                ((lc2, mem2, loc1, from1, to1) = (lc1', mem1', loc2, from2, to2) \\/\n                 ((loc1, to1) <> (loc2, to2) /\\\n                  exists from1' kind1', <<STEP2: Local.promise_step lc1' mem1' loc1 from1' to1 msg1 lc2 mem2 kind1'>>))>> /\\\n     <<KIND2: kind2 = Memory.op_kind_add -> kind2' = Memory.op_kind_add>>).\nProof.\n  guardH NONPF.\n  destruct (classic (loc1 = loc2 /\\ Time.lt to1 to2)); auto.\n  right. eapply reorder_promise_write; eauto. i. subst. splits.\n  - ii. subst. apply H. splits; auto.\n    inv STEP1. inv PROMISE. inv MEM. inv SPLIT. auto.\n  - ii. subst. apply H. splits; auto.\n    inv STEP2. inv WRITE. inv PROMISE. exploit Memory.split_get0; eauto. i. des.\n    inv STEP1. inv PROMISE. revert GET0. erewrite Memory.split_o; eauto. repeat condtac; ss.\n    + i. des. inv GET0. inv MEM1. inv SPLIT. timetac.\n    + guardH o. i. des. inv GET0. inv MEM. inv SPLIT. auto.\n    + guardH o. des; congr.\n  - i. subst. destruct (TimeFacts.le_lt_dec to2 to1); cycle 1.\n    { exfalso. apply H; eauto. }\n    inv l; ss. inv H0. exfalso.\n    inv STEP1. inv PROMISE. inv STEP2. inv WRITE. inv PROMISE. ss.\n    exploit Memory.add_get0; try exact MEM. i. des.\n    exploit Memory.add_get0; try exact MEM1. i. des. congr.\nQed.\n\n\n#[export]\nHint Constructors Thread.program_step: core.\n#[export]\nHint Constructors Thread.step: core.\n\nLemma reorder_nonpf_program\n      lang\n      e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang false e1 th0 th1)\n      (STEP2: Thread.program_step e2 th1 th2)\n      (CONS2: Local.promise_consistent (Thread.local th2))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n      (MEMORY: Memory.closed (Thread.memory th0)):\n  exists th1',\n     <<STEP1: Thread.program_step e2 th0 th1'>> /\\\n     <<STEP2: __guard__ (th2 = th1' \\/ exists pf2' e2', Thread.promise_step pf2' e2' th1' th2)>>.\nProof.\n  exploit Thread.step_future; eauto. i. des.\n  inv STEP1. inv STEP. ss. inv STEP2. inv LOCAL1; ss.\n  - (* silent *)\n    esplits; eauto.\n    right. esplits. econs; eauto.\n  - (* read *)\n    exploit reorder_promise_read; try exact LOCAL0; eauto; try by viewtac.\n    { ii. inv H.\n      inv LOCAL0. exploit Memory.promise_get2; eauto.\n      { destruct kind, msg; ss. }\n      i. des.\n      dup LOCAL2. inv LOCAL0. ss.\n      rewrite GET in *. inv GET_MEM.\n      hexploit promise_consistent_promise_read; eauto. i. timetac.\n    }\n    i. des. esplits.\n    + econs; eauto.\n    + right. esplits. econs; eauto.\n  - (* write *)\n    exploit reorder_promise_write; try exact LOCAL0; eauto; try by viewtac.\n    { destruct kind, msg; ss; eauto. repeat condtac; ss; eauto. }\n    { destruct kind, msg; ss. }\n    { i. subst. split.\n      - ii. subst. ss. inv LOCAL0.\n        exploit Memory.promise_get2; eauto. i. des.\n        inv PROMISE. des. subst.\n        exploit promise_consistent_promise_write; eauto. i.\n        inv MEM. inv SPLIT. timetac.\n      - ii. subst. ss. inv LOCAL0.\n        exploit Memory.promise_get2; eauto. i. des.\n        inv PROMISE. des. subst.\n        exploit promise_consistent_promise_write; eauto. i.\n        exploit Memory.split_get0; try exact PROMISES. i. des.\n        inv LOCAL2. ss. inv WRITE. inv PROMISE. des.\n        exploit Memory.split_get0; try exact PROMISES0. i. des.\n        rewrite GET2 in *. inv GET4.\n        inv MEM0. inv SPLIT. timetac. }\n    { i. subst. inv LOCAL0. inv PROMISE.\n      exploit Memory.add_get0; try exact PROMISES. i. des.\n      exploit promise_consistent_promise_write; try exact GET0; eauto. i.\n      inv x0; ss. inv H.\n      inv LOCAL2. inv WRITE. inv PROMISE. ss.\n      exploit Memory.add_get0; try exact MEM. i. des.\n      exploit Memory.add_get0; try exact MEM0. i. des. congr. }\n    i. des.\n    esplits.\n    + econs; eauto.\n    + unguardH STEP2. des.\n      * inv STEP2. left. auto.\n      * right. esplits. econs; eauto.\n  - (* update *)\n    exploit reorder_promise_read; try exact LOCAL1; eauto; try by viewtac.\n    { ii. inv H.\n      inv LOCAL0. exploit Memory.promise_get2; eauto.\n      { destruct kind, msg; ss. }\n      i. des.\n      dup LOCAL2. inv LOCAL0. ss.\n      rewrite GET in *. inv GET_MEM.\n      exploit promise_consistent_promise_read; eauto.\n      { eapply write_step_promise_consistent; eauto. }\n      i. eapply Time.lt_strorder. eauto.\n    }\n    i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit reorder_promise_write; try exact LOCAL2; eauto; try by viewtac.\n    { destruct kind, msg; ss; eauto. repeat condtac; ss; eauto. }\n    { destruct kind, msg; ss. }\n    { i. subst. split.\n      - ii. subst. ss. inv STEP2.\n        exploit Memory.promise_get2; eauto. i. des.\n        inv PROMISE. des. subst.\n        exploit promise_consistent_promise_write; eauto. i.\n        inv MEM. inv SPLIT. timetac.\n      - ii. subst. ss. inv STEP2.\n        exploit Memory.promise_get2; eauto. i. des.\n        inv PROMISE. des. subst.\n        exploit promise_consistent_promise_write; eauto. i.\n        exploit Memory.split_get0; try exact PROMISES. i. des.\n        inv LOCAL3. ss. inv WRITE. inv PROMISE. des.\n        exploit Memory.split_get0; try exact PROMISES0. i. des.\n        rewrite GET2 in *. inv GET4.\n        inv MEM0. inv SPLIT. timetac. }\n    { i. subst. inv LOCAL0. inv PROMISE.\n      inv LOCAL2. ss.\n      exploit Memory.add_get0; try exact PROMISES. i. des.\n      exploit promise_consistent_promise_write; try exact GET1; eauto. i.\n      inv x0; ss. inv H.\n      inv LOCAL3. inv WRITE. inv PROMISE. ss.\n      exploit Memory.add_get0; try exact MEM. i. des.\n      exploit Memory.add_get0; try exact MEM0. i. des. congr. }\n    i. des.\n    esplits.\n    + econs; eauto.\n    + unguardH STEP3. des.\n      * inv STEP3. left. auto.\n      * right. esplits. econs; eauto.\n  - inv LOCAL0. inv LOCAL2.\n    esplits; eauto.\n    + econs; eauto. econs 5; eauto. econs; eauto. ss.\n      intros ORDW l. eapply promise_step_nonsynch_loc_inv; eauto.\n      * destruct msg, kind; ss; eauto. repeat condtac; ss; eauto.\n      * apply RELEASE. ss.\n    + right. esplits. econs; eauto.\n  - inv LOCAL0. inv LOCAL2.\n    esplits; eauto.\n    + econs; eauto. econs 6; eauto. econs; eauto.\n      intros ORDW l. eapply promise_step_nonsynch_loc_inv; eauto.\n      * destruct msg, kind; ss; eauto. repeat condtac; ss; eauto.\n      * apply RELEASE. ss.\n    + right. esplits. econs; eauto.\n  - inv LOCAL2.\n    hexploit promise_step_promise_consistent; eauto. i.\n    esplits; eauto.\n    right. esplits. econs; eauto.\nQed.\n\nLemma reorder_nonpf_pf\n      lang\n      e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang false e1 th0 th1)\n      (STEP2: Thread.step true e2 th1 th2)\n      (CONS2: Local.promise_consistent (Thread.local th2))\n      (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n      (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n      (MEMORY: Memory.closed (Thread.memory th0)):\n  (th0 = th2) \\/\n  (exists pf2' e2',\n      <<STEP: Thread.step pf2' e2' th0 th2>> /\\\n      <<EVENT: __guard__ (e2' = e2 \\/ (ThreadEvent.is_promising e2' /\\ ThreadEvent.is_promising e2))>>) \\/\n  (exists e2' pf1' e1' th1',\n      <<STEP1: Thread.step true e2' th0 th1'>> /\\\n      <<STEP2: Thread.promise_step pf1' e1' th1' th2>> /\\\n      <<EVENT: __guard__ (e2' = e2 \\/ (ThreadEvent.is_promising e2' /\\ ThreadEvent.is_promising e2))>>).\nProof.\n  inv STEP2; ss.\n  - inv STEP. ss.\n    inv STEP1. inv STEP. ss.\n    destruct kind; ss.\n    + destruct msg1, msg; ss. destruct released0; ss.\n      exploit reorder_promise_promise_lower_None; eauto.\n      { destruct kind0; ss. }\n      i. des; subst.\n      * right. left. esplits.\n        { econs 1. econs; eauto. }\n        { right. ss. }\n      * right. right. esplits.\n        { econs 1. econs; eauto. }\n        { econs; eauto. }\n        { right. ss. }\n    + exploit reorder_promise_promise_cancel; eauto.\n      { destruct kind0; ss. }\n      i. des; subst; eauto.\n      * right. left. esplits.\n        { econs 1. econs; eauto. }\n        { right. ss. }\n      * right. right. esplits.\n        { econs 1. econs; eauto. }\n        { econs; eauto. }\n        { right. ss. }\n  - exploit reorder_nonpf_program; eauto. i. des.\n    unguardH STEP2. des.\n    + subst. right. left. esplits; eauto. left. ss.\n    + right. right. esplits; eauto. left. 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/prop/ReorderPromise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.16166383312268587}}
{"text": "(* -*- mode: coq; coq-prog-args: (\"-indices-matter\") -*- *)\nSet Universe Polymorphism.\n\nInductive eq {A} (x : A) : A -> Type := eq_refl : eq x x.\nNotation \"a = b\" := (eq a b) : type_scope.\n\nSection foo.\n  Class Funext := { path_forall :> forall A P (f g : forall x : A, P x), (forall x, f x = g x) -> f = g }.\n  Context `{Funext, Funext}.\n\n  Set Printing Universes.\n\n  (** Typeclass resolution should pick up the different instances of Funext automatically *)\n  Definition foo := (@path_forall _ _ _ (@path_forall _ Set)).\n  (* Toplevel input, characters 0-60:\nError: Universe inconsistency (cannot enforce Top.24 <= Top.23 because Top.23\n< Top.22 <= Top.24). *)\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_059.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.16156577839354633}}
{"text": "Require Import SegmentQueue.lib.thread_queue.thread_queue.\nFrom SegmentQueue.lib.concurrent_linked_list.infinite_array\n     Require Import array_spec iterator.iterator_impl.\nRequire Import SegmentQueue.lib.util.future.\nRequire Import SegmentQueue.lib.util.forRange.\nFrom iris.heap_lang Require Import notation.\n\nSection impl.\n\nVariable array_interface: infiniteArrayInterface.\nVariable limit: positive.\n\nDefinition newBarrier: val :=\n  \u03bb: <>, (ref #0, newThreadQueue array_interface #()).\n\nDefinition barrierResume: val :=\n  \u03bb: \"d\", resume array_interface #(Z.of_nat 300) #true #false #false \"d\"\n                 (\u03bb: <>, #()) #().\n\nDefinition arrive : val :=\n  \u03bb: \"barrier\",\n  let: \"counter\" := Fst \"barrier\" in\n  let: \"e\" := Fst (Snd \"barrier\") in\n  let: \"d\" := Snd (Snd \"barrier\") in\n  let: \"p\" := FAA \"counter\" #1\n  in if: \"p\" = #(Pos.to_nat limit-1)\n     then forRange \"p\" (\u03bb: <>, barrierResume \"d\") ;; fillThreadQueueFuture #()\n     else match: suspend array_interface \"e\" with\n            InjR \"v\" => \"v\"\n          | InjL \"x\" => \"undefined\"\n          end.\n\nDefinition cancelBarrierFuture : val :=\n  \u03bb: \"barrier\" \"f\",\n  let: \"counter\" := Fst \"barrier\" in\n  let: \"onCancellation\" :=\n     rec: \"loop\" <> :=\n       let: \"c\" := !\"counter\" in\n       if: \"c\" = #(Pos.to_nat limit) then #false\n       else if: CAS \"counter\" \"c\" (\"c\" - #1) then #true\n            else \"loop\" #()\n  in\n  let: \"d\" := Snd (Snd \"barrier\") in\n  tryCancelThreadQueueFuture' array_interface\n                              #false #(Z.of_nat 300) #false #false\n                              \"d\" \"onCancellation\"\n                              (\u03bb: <>, #()) (\u03bb: <>, #()) \"f\".\n\nEnd impl.\n\nFrom SegmentQueue.util Require Import everything big_opL local_updates.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.algebra Require Import numbers auth list gset excl csum.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Import proofmode.\n\nSection proof.\n\nNotation algebra := (authR (prodUR natUR\n                                   (optionUR (csumR positiveR positiveR)))).\n\nClass barrierG \u03a3 := BarrierG { barrier_inG :> inG \u03a3 algebra }.\nDefinition barrier\u03a3 : gFunctors := #[GFunctor algebra].\nInstance subG_barrier\u03a3 {\u03a3} : subG barrier\u03a3 \u03a3 -> barrierG \u03a3.\nProof. solve_inG. Qed.\n\nContext `{heapG \u03a3} `{iteratorG \u03a3} `{threadQueueG \u03a3} `{futureG \u03a3} `{barrierG \u03a3}.\nVariable (limit: positive).\nVariable (N NFuture: namespace).\nVariable (HNDisj: N ## NFuture).\nLet NBar := N .@ \"Barrier\".\nLet NTq := N .@ \"Tq\".\nNotation iProp := (iProp \u03a3).\n\nDefinition barrier_entry_piece \u03b3 := own \u03b3 (\u25ef (\u03b5, Some (Cinl 1%positive))).\nDefinition barrier_exit_piece \u03b3 := own \u03b3 (\u25ef (\u03b5, Some (Cinr 1%positive))).\nDefinition barrier_inhabitant_permit \u03b3 := own \u03b3 (\u25ef (1, \u03b5)).\n\nDefinition barrier_inv (\u03b3b \u03b3tq: gname) (\u2113: loc) (n: nat): iProp :=\n  (\u231cn < Pos.to_nat limit\u231d \u2227 own \u03b3b (\u25cf (n, Some (Cinl limit))) \u2228\n   \u231cn = Pos.to_nat limit\u231d \u2227 own \u03b3b (\u25cf (n, Some (Cinr limit))))\n  \u2217 \u2113 \u21a6 #n \u2217 [\u2217] replicate (n `mod` Pos.to_nat limit) (barrier_entry_piece \u03b3b)\n  \u2217 thread_queue_state \u03b3tq (n `mod` Pos.to_nat limit).\n\nVariable array_interface: infiniteArrayInterface.\nVariable array_spec: infiniteArraySpec _ array_interface.\n\nLet tqParams \u03b3b :=\n  @ThreadQueueParameters \u03a3 false True (barrier_exit_piece \u03b3b) True\n                         (fun v => \u231c#v = #()\u231d)%I False.\n\nLet isThreadQueue \u03b3b := is_thread_queue NTq NFuture (tqParams \u03b3b) _ array_spec.\n\nDefinition is_barrier_future \u03b3b :=\n  is_thread_queue_future NTq NFuture (tqParams \u03b3b) _ array_spec.\n\nDefinition is_barrier \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d (s: val): iProp :=\n  \u2203 e d (p: loc), \u231cs = (#p, (e, d))%V\u231d \u2227\n  inv NBar (\u2203 n, barrier_inv \u03b3b \u03b3tq p n)\n  \u2217 isThreadQueue \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d e d.\n\nTheorem newBarrier_spec:\n  {{{ inv_heap_inv }}}\n    newBarrier array_interface #()\n  {{{ \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s, RET s; is_barrier \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s\n    \u2217 [\u2217] replicate (Pos.to_nat limit) (barrier_entry_piece \u03b3b) }}}.\nProof.\n  iIntros (\u03a6) \"#HHeap H\u03a6\".\n  iMod (own_alloc (\u25cf (0, Some (Cinl limit)) \u22c5 \u25ef (0, Some (Cinl limit))))\n    as (\u03b3b) \"[H\u25cf H\u25ef]\"; first by apply auth_both_valid.\n  wp_lam. wp_bind (newThreadQueue _ _).\n  iApply (newThreadQueue_spec with \"HHeap\").\n  iIntros (\u03b3a \u03b3tq \u03b3e \u03b3d e d) \"!> [#HTq HThreadState]\".\n  rewrite -wp_fupd. wp_alloc p as \"Hp\". wp_pures.\n  iMod (inv_alloc NBar _ (\u2203 n, barrier_inv \u03b3b \u03b3tq p n) with \"[-H\u03a6 H\u25ef]\")\n    as \"#HInv\".\n  { iExists 0. iFrame \"Hp\". rewrite Nat.mod_0_l; last lia. simpl.\n    iFrame \"HThreadState\". iLeft. iFrame. iPureIntro. lia. }\n  iApply \"H\u03a6\". iSplitR.\n  { iExists _, _, _. iSplitR; first done. by iFrame \"HInv HTq\". }\n  rewrite big_opL_replicate_irrelevant_element -big_opL_own.\n  2: { destruct (Pos.to_nat limit) eqn:E. lia. done. }\n  remember (Pos.to_nat limit) as NLim.\n  replace limit with (Pos.of_nat NLim) by (subst; apply Pos2Nat.id).\n  assert (NLim > 0)%nat as HGt by (subst; lia). move: HGt. clear.\n  intros HGt.\n  iInduction (NLim) as [|NLim] \"IH\"; first lia.\n  simpl.\n  inversion HGt; subst; first by iFrame.\n  replace (Pos.of_nat (S NLim)) with (1 + Pos.of_nat NLim)%positive;\n    last by rewrite Nat2Pos.inj_succ; lia.\n  rewrite Cinl_op Some_op pair_op_2 auth_frag_op own_op.\n  move: (big_opL_op_prodR 0)=> /= HBigOpL.\n  rewrite -big_opL_auth_frag !HBigOpL !big_opL_op_ucmra_unit.\n  rewrite own_op. iDestruct \"H\u25ef\" as \"[$ HFrag]\".\n  iApply (\"IH\" with \"[//] HFrag\").\nQed.\n\nLemma resumeBarrier_spec R maxWait (wait: bool) \u03b3a \u03b3tq \u03b3e \u03b3d e d:\n  {{{ isThreadQueue R \u03b3a \u03b3tq \u03b3e \u03b3d e d \u2217 awakening_permit \u03b3tq }}}\n    resume array_interface #(Z.of_nat maxWait) #true #false #wait d (\u03bb: <>, #())%V #()\n  {{{ RET #true; True }}}.\nProof.\n  iIntros (\u03a6) \"[#HTq HAwak] H\u03a6\".\n  iApply (resume_spec with \"[] [HAwak]\").\n  5: { by iFrame \"HTq HAwak\". }\n  by solve_ndisj. done. done.\n  { simpl. iIntros (\u03a8) \"!> _ H\u03a8\". wp_pures. by iApply \"H\u03a8\". }\n  iIntros \"!>\" (r) \"Hr\". simpl. destruct r; first by iApply \"H\u03a6\".\n  iDestruct \"Hr\" as \"[% _]\"; lia.\nQed.\n\nLemma arrive_spec \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s:\n  {{{ is_barrier \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s \u2217 barrier_entry_piece \u03b3b }}}\n    arrive array_interface limit s\n  {{{ \u03b3f v, RET v; is_barrier_future \u03b3b \u03b3tq \u03b3a \u03b3f v \u2217\n                   thread_queue_future_cancellation_permit \u03b3f \u2217\n                   barrier_inhabitant_permit \u03b3b }}}.\nProof.\n  iIntros (\u03a6) \"[#HBarrier HEntry] H\u03a6\". wp_lam.\n  iDestruct \"HBarrier\" as (e d p ->) \"[HInv HTq]\". wp_pures.\n  wp_bind (FAA _ _).\n  iInv \"HInv\" as (n) \"(>[[% H\u25cf]|[-> HContra]] & H\u2113 & HEntries & HState)\".\n  2: {\n    iDestruct (own_valid_2 with \"HContra HEntry\") as\n        %[[_ HInc]%prod_included _]%auth_both_valid. exfalso.\n    move: HInc=> /=. rewrite Some_included. case.\n    + intros HContra. inversion HContra.\n    + rewrite csum_included. case; first done.\n      case; by intros (? & ? & ? & ? & ?).\n  }\n  iCombine \"HEntry\" \"HEntries\" as \"HEntries\".\n  rewrite Nat.mod_small; last lia.\n  destruct (decide (n = Pos.to_nat limit - 1)) as [->|HLt].\n  - wp_faa.\n    iAssert ([\u2217] replicate (Pos.to_nat limit) (barrier_entry_piece \u03b3b))%I\n            with \"[HEntries]\" as \"HEntries\".\n    { iEval (replace (Pos.to_nat limit) with (1 + (Pos.to_nat limit - 1))\n              by lia). iFrame. }\n    iAssert (own \u03b3b (\u25ef (0, Some (Cinl limit)))) with \"[HEntries]\" as \"H\u25ef\".\n    {\n      clear. remember (Pos.to_nat limit) as limN.\n      replace limit with (Pos.of_nat limN) by (subst; apply Pos2Nat.id).\n      assert (limN > 0)%nat as HNonZero by lia. clear HeqlimN.\n      iInduction limN as [|limN'] \"IH\" forall (HNonZero); simpl in *. lia.\n      inversion HNonZero.\n      - by iDestruct \"HEntries\" as \"[$ _]\".\n      - replace (S limN') with (1 + limN') by lia.\n        rewrite Nat2Pos.inj_add; try lia.\n        rewrite Cinl_op Some_op pair_op_2 auth_frag_op own_op.\n        iDestruct \"HEntries\" as \"[$ HEntries]\".\n        iApply (\"IH\" with \"[%] HEntries\"). lia.\n    }\n    iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"H\u25cf\".\n    apply auth_update_dealloc, prod_local_update_2, ucmra_cancel_local_update, _.\n    iAssert (|==> own \u03b3b (\u25cf (Pos.to_nat limit, Some (Cinr limit))) \u2217\n                  own \u03b3b (\u25ef (1, \u03b5)) \u2217 own \u03b3b (\u25ef (\u03b5, Some (Cinr limit))))%I\n            with \"[H\u25cf]\" as \">(H\u25cf & HInhabit & H\u25ef)\".\n    {\n      iMod (own_update with \"H\u25cf\") as \"($ & $ & $)\"; last done.\n      apply auth_update_alloc, prod_local_update'=>/=.\n      - apply nat_local_update. simpl. rewrite Nat.add_1_r Nat.add_0_r. lia.\n      - by apply (alloc_option_local_update (Cinr limit)).\n    }\n    iAssert ([\u2217] replicate (Pos.to_nat limit) (barrier_exit_piece \u03b3b))%I\n      with \"[H\u25ef]\" as \"HExit\".\n    {\n      clear. remember (Pos.to_nat limit) as NLim.\n      replace limit with (Pos.of_nat NLim) by (subst; apply Pos2Nat.id).\n      assert (NLim > 0)%nat as HGt by (subst; lia). move: HGt. clear.\n      intros HGt.\n      iInduction (NLim) as [|NLim] \"IH\"; first lia.\n      simpl.\n      inversion HGt; first by iFrame. simplify_eq.\n      replace (Pos.of_nat (S NLim)) with (1 + Pos.of_nat NLim)%positive;\n        last by rewrite Nat2Pos.inj_succ; lia.\n      rewrite Cinr_op Some_op pair_op_2 auth_frag_op own_op.\n      iDestruct \"H\u25ef\" as \"[$ HFrag]\". iApply (\"IH\" with \"[//] HFrag\").\n    }\n    remember (Pos.to_nat limit - 1)%nat as sleepers.\n    replace (Pos.to_nat limit) with (S sleepers) by lia.\n    simpl. iDestruct \"HExit\" as \"[HMyExit HWakers]\".\n    iAssert (|={\u22a4 \u2216 \u2191NBar}=> thread_queue_state \u03b3tq 0 \u2217\n            [\u2217] replicate sleepers (awakening_permit \u03b3tq))%I\n      with \"[HState HWakers]\" as \">[HState HAwaks]\".\n    {\n      clear. iInduction (sleepers) as [|sleepers] \"IH\"=>/=. by iFrame.\n      iDestruct \"HWakers\" as \"[HWaker HWakers]\".\n      iMod (thread_queue_register_for_dequeue' with\n                \"HTq [$] [$]\") as \"[HState $]\". by solve_ndisj.\n      lia. rewrite /= Nat.sub_0_r.\n      iApply (\"IH\" with \"HState HWakers\").\n    }\n    iSplitR \"H\u03a6 HAwaks HMyExit HInhabit\".\n    { iExists (S sleepers). rewrite /barrier_inv. subst. iSplitL \"H\u25cf\".\n      { iRight; iFrame. iPureIntro; lia. }\n      rewrite Z.add_1_r -Nat2Z.inj_succ.\n      replace (S (_ - _)) with (Pos.to_nat limit) by lia.\n      rewrite Nat.mod_same; last lia. simpl. iFrame \"HState\". done. }\n    iModIntro. wp_pures.\n    rewrite bool_decide_true; last by congr (fun x => LitV (LitInt x)); lia.\n    wp_pures.\n    wp_apply (forRange_resource_map\n                (fun _ => awakening_permit \u03b3tq) (fun _ => True)%I\n             with \"[] [HAwaks]\").\n    + iIntros (i \u03a8) \"!> HAwak H\u03a8\". wp_pures. wp_lam.\n      wp_apply (resumeBarrier_spec with \"[$]\"). iIntros (_).\n      by iApply \"H\u03a8\".\n    + by rewrite -big_sepL_replicate seq_length.\n    + iIntros (?) \"_\". wp_pures.\n      iApply (fillThreadQueueFuture_spec with \"[HMyExit]\").\n      2: { iIntros \"!>\" (\u03b3f v') \"(H1 & H2 & _)\". iApply \"H\u03a6\".\n           iFrame \"HInhabit H1 H2\". }\n      rewrite /V'. simpl. iExists _. iFrame. by iPureIntro.\n  - iMod (thread_queue_append' with \"HTq [] HState\")\n      as \"[HState HSus]\"=> /=; [by solve_ndisj|done|].\n    iAssert (|==> own \u03b3b (\u25cf (S n, Some (Cinl limit))) \u2217\n                  own \u03b3b (\u25ef (1, \u03b5)))%I with \"[H\u25cf]\" as \">[H\u25cf HInhabit]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_alloc, prod_local_update_1, nat_local_update.\n      rewrite Nat.add_0_r. lia. }\n    wp_faa. iSplitR \"H\u03a6 HSus HInhabit\".\n    { iExists (S n). iModIntro. iSplitL \"H\u25cf\".\n      + iLeft. iFrame. iPureIntro. lia.\n      + rewrite Nat.mod_small; last lia. iFrame.\n        by replace (n + 1)%Z with (Z.of_nat (S n)) by lia. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last by case; lia.\n    wp_pures. wp_apply (suspend_spec with \"[$]\")=>/=.\n    iIntros (v) \"[(_ & _ & %)|Hv]\"; first done.\n    iDestruct \"Hv\" as (\u03b3f v' ->) \"[HFuture HCancPermit]\".\n    wp_pures. iApply \"H\u03a6\". iFrame.\nQed.\n\nTheorem cancelBarrierFuture_spec \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s \u03b3f f:\n  is_barrier \u03b3b \u03b3a \u03b3tq \u03b3e \u03b3d s -\u2217\n  is_barrier_future \u03b3b \u03b3tq \u03b3a \u03b3f f -\u2217\n  <<< \u25b7 thread_queue_future_cancellation_permit \u03b3f \u2217\n      barrier_inhabitant_permit \u03b3b >>>\n    cancelBarrierFuture array_interface limit s f @ \u22a4 \u2216 \u2191NFuture \u2216 \u2191N\n  <<< \u2203 (r: bool),\n      if r then future_is_cancelled \u03b3f\n      else (\u2203 v, \u25b7 future_is_completed \u03b3f v) \u2217\n           thread_queue_future_cancellation_permit \u03b3f \u2217\n           barrier_inhabitant_permit \u03b3b, RET #r >>>.\nProof.\n  iIntros \"#HIsBar #HFuture\" (\u03a6) \"AU\".\n  iDestruct \"HIsBar\" as (e d p ->) \"[HInv HTq]\". wp_lam. wp_pures. wp_lam.\n  wp_pures. awp_apply (try_cancel_thread_queue_future with \"HTq HFuture\");\n              first by solve_ndisj.\n  iApply (aacc_aupd_commit with \"AU\"). by solve_ndisj.\n  iIntros \"[HCancPermit HInhabit]\". iAaccIntro with \"HCancPermit\".\n  by iIntros \"$ !>\"; iFrame; iIntros \"$ !>\".\n  iIntros (r) \"Hr\". iExists r. destruct r.\n  2: { iDestruct \"Hr\" as \"[$ $]\". iFrame. iIntros \"!> H\u03a6 !>\". by wp_pures. }\n  iDestruct \"Hr\" as \"[#HFutureCancelled Hr]\". iFrame \"HFutureCancelled\".\n  rewrite /is_barrier_future /is_thread_queue_future.\n  iDestruct \"Hr\" as (i f' s ->) \"Hr\"=> /=.\n  iDestruct \"Hr\" as \"(#H\u21a6~ & #HTh & HToken)\". iIntros \"!> H\u03a6 !>\". wp_pures.\n  wp_lam. wp_pures. wp_apply derefCellPointer_spec.\n  by iDestruct \"HTq\" as \"(_ & $ & _)\". iIntros (\u2113) \"#H\u21a6\". wp_pures.\n  iL\u00f6b as \"IHCancAllowed\".\n  wp_bind (!_)%E.\n  iInv \"HInv\" as (n) \"(>[[% H\u25cf]|[-> H\u25cf]] & H\u2113 & HEntries & HState)\" \"HClose\".\n  2: {\n    wp_load. rewrite Nat.mod_same; last lia.\n    iMod (register_cancellation with \"HTq HToken HState\")\n        as \"[HCancToken HState]\"; first by solve_ndisj.\n    iDestruct \"HState\" as \"(HState & HR & #HInhabited)\".\n    iMod (\"HClose\" with \"[-H\u03a6 HCancToken HR]\") as \"_\".\n    { iExists (Pos.to_nat limit). iSplitL \"H\u25cf\".\n      - iRight. by iFrame.\n      - rewrite Nat.mod_same; last lia. iFrame. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last done. wp_pures.\n    wp_bind (getAndSet.getAndSet _ _).\n    awp_apply (markRefused_spec with \"HTq HInhabited H\u21a6 HCancToken HTh [//]\")\n              without \"H\u03a6 HR\".\n    iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n    iIntros \"!> [H\u03a6 HR]\". iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n    iDestruct \"Hv\" as (? ->) \"[_ >%]\". simplify_eq. wp_pures.\n    iApply \"H\u03a6\". (* we are losing the exit barrier piece here. *)\n  }\n  wp_load.\n  iMod (\"HClose\" with \"[-H\u03a6 HToken HInhabit]\") as \"_\".\n  { iExists _. iSplitL \"H\u25cf\"; first by iLeft; iFrame. iFrame. }\n  iModIntro. wp_pures. rewrite bool_decide_false; last by case; lia.\n  wp_pures. wp_bind (CmpXchg _ _ _).\n  iInv \"HInv\" as (n') \"(>[[% H\u25cf]|[-> H\u25cf]] & H\u2113 & HEntries & >HState)\" \"HClose\".\n  2: {\n    wp_cmpxchg_fail. by case; lia.\n    iMod (\"HClose\" with \"[-H\u03a6 HToken HInhabit]\") as \"_\".\n    { iExists _. iSplitL \"H\u25cf\"; first by iRight; iFrame. iFrame. }\n    iModIntro. wp_pures. by iApply (\"IHCancAllowed\" with \"HInhabit HToken H\u03a6\").\n  }\n  destruct (decide (n = n')) as [<-|HNe].\n  2: {\n    wp_cmpxchg_fail; first by intro HContra; simplify_eq.\n    iMod (\"HClose\" with \"[-H\u03a6 HToken HInhabit]\") as \"_\".\n    { iExists _. iSplitL \"H\u25cf\"; first by iLeft; iFrame. iFrame. }\n    iModIntro. wp_pures. by iApply (\"IHCancAllowed\" with \"HInhabit HToken H\u03a6\").\n  }\n  iAssert (\u231c(n > 0)%nat\u231d)%I with \"[-]\" as %HN'Gt.\n  { iDestruct (own_valid_2 with \"H\u25cf HInhabit\") as\n        %[[HOk%nat_included _]%prod_included _]%auth_both_valid.\n    iPureIntro; simpl in *; lia. }\n  iMod (register_cancellation with \"HTq HToken HState\")\n       as \"[HCancToken HState]\"; first by solve_ndisj.\n  rewrite bool_decide_false Nat.mod_small; try lia. wp_cmpxchg_suc.\n  iDestruct \"HState\" as \"(HState & HCancHandle & #HInhabited)\".\n  iMod (own_update_2 with \"H\u25cf HInhabit\") as \"H\u25cf\".\n  { apply auth_update_dealloc, prod_local_update_1.\n    apply (nat_local_update _ _ (n - 1)).\n    rewrite Nat.add_0_r Nat.add_1_r. lia. }\n  destruct n as [|n']; first lia.\n  iDestruct \"HEntries\" as \"[HEntry HEntries]\".\n  iMod (\"HClose\" with \"[-H\u03a6 HCancToken HCancHandle HEntry]\") as \"_\".\n  {\n    rewrite Nat.sub_1_r=>/=.\n    iExists n'. iSplitL \"H\u25cf\". by iLeft; iFrame; iPureIntro; lia.\n    rewrite Nat.mod_small; last lia. iFrame.\n    by rewrite Z.sub_1_r -Nat2Z.inj_pred/=.\n  }\n  iModIntro. wp_pures. wp_bind (getAndSet.getAndSet _ _).\n  awp_apply (markCancelled_spec with \"HTq HInhabited H\u21a6 HCancToken HTh\")\n            without \"H\u03a6 HCancHandle HEntry\".\n  iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n  iIntros \"!> (H\u03a6 & HCancHandle & HEntry)\". wp_pures.\n  iAssert (\u25b7 cell_cancellation_handle _ _ _ _ _ _)%I\n          with \"[HCancHandle]\" as \"HCancHandle\"; first done.\n  awp_apply (onCancelledCell_spec with \"[] H\u21a6~\") without \"Hv H\u03a6\".\n  by iDestruct \"HTq\" as \"(_ & $ & _)\".\n  iAaccIntro with \"HCancHandle\". by iIntros \"$\".\n  iIntros \"#HCancelled !> [Hv H\u03a6]\". wp_pures.\n  iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n  iDestruct \"Hv\" as (x ->) \"(#HInhabited' & HAwak & %)\"; simplify_eq.\n  wp_pures. wp_apply (resumeBarrier_spec with \"[$]\").\n  iIntros \"_\". wp_pures. iApply \"H\u03a6\".\n  (* we are losing the entry barrier piece, but it's not a big deal since the *)\n  (* API does not provide a way to learn whether the cancellation succeeded *)\n  (* before or after a thread arrived to resume everything. *)\nQed.\n\nEnd proof.\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/barrier/barrier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.2658804672827599, "lm_q1q2_score": 0.1615657675456923}}
{"text": "(* Partial translation From MetaCoqCoq to ITT *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom MetaCoq\nRequire Import Ast utils monad_utils Typing Checker AstUtils uGraph.\nFrom Translation\nRequire Import util Sorts SAst SLiftSubst SCommon ITyping Quotes\n               FinalTranslation.\nImport MonadNotation.\nImport ListNotations.\n\n\nInductive assocn (A : Type) :=\n| emptyn\n| aconsn (key : string) (n : nat) (data : A) (t : assocn A).\n\nArguments emptyn {_}.\nArguments aconsn {_} _ _ _.\n\nFixpoint assocn_at {A} (key : string) (n : nat) (t : assocn A) {struct t}\n  : option A :=\n  match t with\n  | emptyn => None\n  | aconsn k m a r =>\n    if (ident_eq key k) && (n =? m) then Some a else assocn_at key n r\n  end.\n\nInductive fq_error :=\n| NotEnoughFuel\n| NotHandled (t : term)\n| TypingError (msg : string) (e : type_error) (\u0393 : context) (t : term)\n| WrongType (wanted : string) (got : term)\n| UnknownInductive (id : string)\n| UnknownConst (id : string)\n| UnknownConstruct (id : string) (n : nat)\n.\n\nInductive fq_result A :=\n| Success : A -> fq_result A\n| Error : fq_error -> fq_result A.\n\nArguments Success {_} _.\nArguments Error {_} _.\n\nInstance fq_monad : Monad fq_result :=\n  {| ret A a := Success a ;\n     bind A B m f :=\n       match m with\n       | Success a => f a\n       | Error e => Error e\n       end\n  |}.\n\nInstance monad_exc : MonadExc fq_error fq_result :=\n  { raise A e := Error e;\n    catch A m f :=\n      match m with\n      | Success a => m\n      | Error t => f t\n      end\n  }.\n\nClose Scope s_scope.\n\nLocal Existing Instance Sorts.type_in_type.\n\nOpen Scope string_scope.\n\nExisting Instance default_fuel.\n\nFixpoint fullquote (fuel : nat) (\u03a3 : global_env) (G : universes_graph)\n  (\u0393 : context) (t : term) (indt : assoc sterm) (constt : assoc sterm)\n  (cot : assocn sterm) {struct fuel}\n  : fq_result sterm :=\n  match fuel with\n  | 0 => raise NotEnoughFuel\n  | S fuel =>\n    match t with\n    | tRel n => ret (sRel n)\n    | tSort _ => ret (sSort tt)\n    | tProd nx A B =>\n      A' <- fullquote fuel \u03a3 G \u0393 A indt constt cot ;;\n      B' <- fullquote fuel \u03a3 G (\u0393 ,, vass nx A) B indt constt cot ;;\n      ret (sProd nx A' B')\n    | tLambda nx A t =>\n      match infer_hnf \u03a3 G (\u0393 ,, vass nx A) t with\n      | Checked B =>\n        A' <- fullquote fuel \u03a3 G \u0393 A indt constt cot ;;\n        B' <- fullquote fuel \u03a3 G (\u0393 ,, vass nx A) B indt constt cot ;;\n        t' <- fullquote fuel \u03a3 G (\u0393 ,, vass nx A) t indt constt cot ;;\n        ret (sLambda nx A' B' t')\n      | TypeError e => raise (TypingError \"Lambda\" e (\u0393 ,, vass nx A) t)\n      end\n    | tApp (tConst \"Translation.Quotes.candidate\" []) [ _ ; _ ; t ] =>\n      fullquote fuel \u03a3 G \u0393 t indt constt cot\n    | tInd {| inductive_mind := id ; inductive_ind := _ |} [] =>\n      match assoc_at id indt with\n      | Some t => ret t\n      | None => raise (UnknownInductive id)\n      end\n    | tConst id [] =>\n      match assoc_at id constt with\n      | Some t => ret t\n      | None => raise (UnknownConst id)\n      end\n    | tConstruct {| inductive_mind := id ; inductive_ind := _ |} n [] =>\n      match assocn_at id n cot with\n      | Some t => ret t\n      | None => raise (UnknownConstruct id n)\n      end\n    | tApp (tInd {| inductive_mind := \"Coq.Init.Logic.eq\"; inductive_ind := 0 |} []) [ A ; u ; v ] =>\n      A' <- fullquote fuel \u03a3 G \u0393 A indt constt cot ;;\n      u' <- fullquote fuel \u03a3 G \u0393 u indt constt cot ;;\n      v' <- fullquote fuel \u03a3 G \u0393 v indt constt cot ;;\n      ret (sEq A' u' v')\n    | tApp u [] =>\n      fullquote fuel \u03a3 G \u0393 u indt constt cot\n    | tApp u [ v ] =>\n      match infer_hnf \u03a3 G \u0393 u with\n      | Checked (tProd nx A B) =>\n        u' <- fullquote fuel \u03a3 G \u0393 u indt constt cot ;;\n        A' <- fullquote fuel \u03a3 G \u0393 A indt constt cot ;;\n        B' <- fullquote fuel \u03a3 G (\u0393 ,, vass nx A) B indt constt cot ;;\n        v' <- fullquote fuel \u03a3 G \u0393 v indt constt cot ;;\n        ret (sApp u' A' B' v')\n      | Checked T => raise (WrongType \"Prod\" T)\n      | TypeError e => raise (TypingError \"App1\" e \u0393 u)\n      end\n    | tApp u (v :: l) =>\n      fullquote fuel \u03a3 G \u0393 (tApp (tApp u [ v ]) l) indt constt cot\n    | tCast t _ _ => fullquote fuel \u03a3 G \u0393 t indt constt cot\n    | _ => raise (NotHandled t)\n    end\n  end.\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/FullQuote.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.16150978545160394}}
{"text": "Require Import os_code_defs.\nRequire Import code_notations.\nRequire Import os_ucos_h.\n\n(*os_mutex.c*)\n\nOpen Scope code_scope.\n\nDefinition OSMutexAccept_impl := \n Int8u \u00b7OSMutexAccept\u00b7(\u231epevent @ OS_EVENT\u2217\u231f)\u00b7\u00b7{\n        \u231e \n          legal @ Int8u;\n          pip @ Int8u\n        \u231f; \n               \n          If(pevent\u2032 ==\u2091 NULL){\n              RETURN \u20320 \n          };\u209b\n          ENTER_CRITICAL;\u209b\n          legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n          If (legal\u2032 ==\u2091 \u20320){\n              EXIT_CRITICAL;\u209b\n              RETURN \u20320 \n          };\u209b\n          If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_MUTEX){\n            EXIT_CRITICAL;\u209b\n            RETURN \u20320\n          };\u209b\n          pip\u2032  =\u2091 \u2329Int8u\u232a(pevent\u2032\u2192OSEventCnt \u226b \u20328);\u209b\n          If ((OSTCBCur\u2032\u2192OSTCBPrio <\u2091 pip\u2032) ||\u2091 (OSTCBCur\u2032\u2192OSTCBPrio ==\u2091 pip\u2032)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u20320\n          };\u209b\n          If ((pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_LOWER_8) ==\u2091 \u2032OS_MUTEX_AVAILABLE){\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_UPPER_8;\u209b\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt |\u2091 OSTCBCur\u2032\u2192OSTCBPrio;\u209b\n            pevent\u2032\u2192OSEventPtr =\u2091 OSTCBCur\u2032;\u209b\n            EXIT_CRITICAL;\u209b\n            RETURN \u20321 \n          };\u209b\n          EXIT_CRITICAL;\u209b\n          RETURN \u20320  \n}\u00b7 .\n\nDefinition PlaceHolder:= &\u2090 OSPlaceHolder\u2032.\n\nDefinition OSMutexCreate_impl := \nOS_EVENT\u2217 \u00b7OSMutexCreate\u00b7(\u231eprio @ Int8u\u231f)\u00b7\u00b7{\n           \u231epevent @ OS_EVENT\u2217\u231f;\n\n            If (prio\u2032 \u2265 \u2032OS_LOWEST_PRIO) {                         \n                RETURN \u2329OS_EVENT \u2217\u232a NULL\n            };\u209b\n            ENTER_CRITICAL;\u209b\n            If (OSTCBPrioTbl\u2032[prio\u2032] !=\u2091 NULL) {\n                EXIT_CRITICAL;\u209b\n                RETURN \u2329OS_EVENT \u2217\u232a NULL               \n            };\u209b                   \n            pevent\u2032 =\u2091 OSEventFreeList\u2032;\u209b\n            If (OSEventFreeList\u2032 !=\u2091 NULL){\n                OSEventFreeList\u2032 =\u2091  \u2329OS_EVENT\u2217\u232a OSEventFreeList\u2032\u2192OSEventListPtr\n            };\u209b\n            IF (pevent\u2032 !=\u2091 NULL){\n                OS_EventWaitListInit(\u00adpevent\u2032\u00ad);\u209b  \n                pevent\u2032\u2192OSEventType =\u2091 \u2032OS_EVENT_TYPE_MUTEX;\u209b\n                pevent\u2032\u2192OSEventCnt  =\u2091 ((\u2329Int16u\u232aprio\u2032) \u226a \u20328) |\u2091 \u2032OS_MUTEX_AVAILABLE;\u209b  \n                pevent\u2032\u2192OSEventPtr  =\u2091 NULL;\u209b\n                pevent \u2032 \u2192 OSEventListPtr =\u2091 OSEventList \u2032;\u209b\n                OSTCBPrioTbl\u2032[prio\u2032] =\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder;\u209b\n                OSEventList\u2032 =\u2091 pevent\u2032;\u209b\n                EXIT_CRITICAL;\u209b\n                RETURN pevent\u2032          \n            }ELSE{\n                EXIT_CRITICAL;\u209b\n                RETURN \u2329OS_EVENT \u2217\u232a NULL\n            }\n }\u00b7.\n\nDefinition OSMutexDel_impl := \n Int8u \u00b7OSMutexDel\u00b7(\u231e pevent @ OS_EVENT \u2217\u231f)\u00b7\u00b7{\n        \u231e \n         tasks_waiting @ Int8u;\n         pip @ Int8u;\n         legal @ Int8u\n        \u231f; \n         \n        If (pevent\u2032 ==\u2091  NULL){\n             RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NO_EX\n        };\u209b \n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_MUTEX){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_EVENT_TYPE\n        };\u209b  \n        IF (pevent\u2032\u2192OSEventGrp !=\u2091 \u20320   ||\u2091 ( ( pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_LOWER_8  )!=\u2091  \u2032OS_MUTEX_AVAILABLE)){\n            tasks_waiting\u2032 =\u2091 \u20321\n        }ELSE{\n            tasks_waiting\u2032 =\u2091 \u20320\n        };\u209b\n        IF (tasks_waiting\u2032 ==\u2091 \u20320){\n            pip\u2032 =\u2091 \u2329Int8u\u232a (pevent\u2032\u2192OSEventCnt \u226b \u20328);\u209b\n            If ( OSTCBPrioTbl\u2032[pip\u2032]  !=\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder){\n                EXIT_CRITICAL;\u209b\n                RETURN \u2032OS_ERR_MUTEXPR_NOT_HOLDER\n            };\u209b\n            OS_EventRemove(\u00adpevent\u2032\u00ad);\u209b\n            OSTCBPrioTbl\u2032[pip\u2032] =\u2091 NULL;\u209b\n            pevent\u2032\u2192OSEventType =\u2091 \u2032OS_EVENT_TYPE_UNUSED;\u209b\n            pevent\u2032\u2192OSEventListPtr =\u2091 OSEventFreeList\u2032;\u209b\n            pevent\u2032\u2192OSEventCnt =\u2091 \u20320;\u209b                 \n            OSEventFreeList\u2032 =\u2091 pevent\u2032;\u209b\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_NO_ERR\n        }ELSE{\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_TASK_WAITING\n        }    \n }\u00b7 .\n\nRequire Import ZArith. \n\nDefinition OSMutexPend_impl :=\n Int8u \u00b7OSMutexPend\u00b7(\u231e pevent @ OS_EVENT \u2217; timeout @ Int16u \u231f)\u00b7\u00b7{\n         \u231e \n           legal @ Int8u;\n           pip @ Int8u;\n           mprio @ Int8u;\n           isrdy @ Int8u;\n           ptcb @ (Tptr OS_TCB);\n           pevent2 @ (Tptr OS_EVENT)\n        \u231f; \n\n        If (pevent\u2032 ==\u2091  NULL){\n             RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NO_EX\n        };\u209b \n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_MUTEX){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_EVENT_TYPE\n        };\u209b\n        If (OSTCBCur\u2032\u2192OSTCBPrio ==\u2091 \u2032OS_IDLE_PRIO){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_IDLE\n        };\u209b\n        If ( (OSTCBCur\u2032\u2192OSTCBStat !=\u2091 \u2032OS_STAT_RDY) ||\u2091 (OSTCBCur\u2032\u2192OSTCBDly !=\u2091 \u20320)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_STAT\n        };\u209b\n        If (OSTCBCur\u2032\u2192OSTCBMsg !=\u2091 NULL) {\n            EXIT_CRITICAL;\u209b \n            RETURN  \u2032OS_ERR_PEVENT_NULL \n        };\u209b\n           \n        pip\u2032  =\u2091 \u2329Int8u\u232a(pevent\u2032\u2192OSEventCnt \u226b \u20328);\u209b\n        If (OSTCBCur\u2032\u2192OSTCBPrio <\u2091 pip\u2032 ||\u2091 (OSTCBCur\u2032\u2192OSTCBPrio ==\u2091 pip\u2032)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_MUTEX_PRIO\n        };\u209b\n        mprio\u2032 =\u2091 \u2329Int8u\u232a(pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_LOWER_8);\u209b\n        ptcb\u2032  =\u2091 pevent\u2032\u2192OSEventPtr;\u209b                                                  \n       \n        If (mprio\u2032 ==\u2091 \u2032OS_MUTEX_AVAILABLE) {\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_UPPER_8;\u209b\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt |\u2091 OSTCBCur\u2032\u2192OSTCBPrio;\u209b\n            pevent\u2032\u2192OSEventPtr =\u2091 OSTCBCur\u2032;\u209b\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_NO_ERR \n        };\u209b\n\n        If(ptcb\u2032 ==\u2091 OSTCBCur\u2032){\n          EXIT_CRITICAL;\u209b\n          RETURN \u2032OS_ERR_MUTEX_DEADLOCK\n        };\u209b\n        If(ptcb\u2032\u2192OSTCBPrio ==\u2091 \u2032OS_IDLE_PRIO){\n          EXIT_CRITICAL;\u209b\n          RETURN \u2032OS_ERR_MUTEX_IDLE\n        };\u209b\n        If ( (ptcb\u2032\u2192OSTCBStat !=\u2091 \u2032OS_STAT_RDY) ||\u2091 (ptcb\u2032\u2192OSTCBDly !=\u2091 \u20320)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_NEST\n        };\u209b\n        If(mprio\u2032 ==\u2091 (OSTCBCur\u2032\u2192OSTCBPrio)){\n          EXIT_CRITICAL;\u209b\n          RETURN \u2032OS_ERR_MUTEX_DEADLOCK\n        };\u209b\n        \n        IF ((ptcb\u2032\u2192OSTCBPrio !=\u2091 pip\u2032) &&\u2091 (mprio\u2032 >\u2091 (OSTCBCur\u2032\u2192OSTCBPrio))){  (*Need to promote prio of owner?*)\n            If ( OSTCBPrioTbl\u2032[pip\u2032]  !=\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder){\n                EXIT_CRITICAL;\u209b\n                RETURN \u2032OS_ERR_MUTEXPR_NOT_HOLDER\n            };\u209b\n           \n            OSTCBPrioTbl\u2032[ ptcb\u2032\u2192OSTCBPrio ] =\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder;\u209b\n            OSTCBPrioTbl\u2032[pip\u2032] =\u2091 \u2329OS_TCB \u2217\u232a ptcb\u2032;\u209b\n\n                OSRdyTbl\u2032[ptcb\u2032\u2192OSTCBY] =\u2091 OSRdyTbl\u2032[ptcb\u2032\u2192OSTCBY]&\u2091(\u223cptcb\u2032\u2192OSTCBBitX);\u209b\n                If (OSRdyTbl\u2032[ptcb\u2032\u2192OSTCBY] ==\u2091 \u20320)\n                {\n                    OSRdyGrp\u2032 =\u2091 OSRdyGrp\u2032 &\u2091 (\u223cptcb\u2032\u2192OSTCBBitY)\n                };\u209b  \n                ptcb\u2032\u2192OSTCBPrio =\u2091 pip\u2032;\u209b                             (* Change owner task prio to PIP            *)\n                ptcb\u2032\u2192OSTCBY    =\u2091 ptcb\u2032\u2192OSTCBPrio \u226b \u20323;\u209b\n                ptcb\u2032\u2192OSTCBBitY =\u2091 OSMapTbl\u2032[ptcb\u2032\u2192OSTCBY];\u209b\n                ptcb\u2032\u2192OSTCBX    =\u2091 (ptcb\u2032\u2192OSTCBPrio) &\u2091 \u20327;\u209b\n                ptcb\u2032\u2192OSTCBBitX =\u2091 OSMapTbl\u2032[ptcb\u2032\u2192OSTCBX];\u209b\n                OSRdyGrp\u2032 =\u2091 OSRdyGrp\u2032 |\u2091 ptcb\u2032\u2192OSTCBBitY;\u209b     (* ... make it ready at new priority.       *)\n                OSRdyTbl\u2032[ptcb\u2032\u2192OSTCBY] =\u2091 OSRdyTbl\u2032[ptcb\u2032\u2192OSTCBY] |\u2091 ptcb\u2032\u2192OSTCBBitX;\u209b\n                 \n                OSTCBCur\u2032\u2192OSTCBStat =\u2091 \u2032OS_STAT_MUTEX;\u209b\n                OSTCBCur\u2032\u2192OSTCBDly =\u2091 timeout\u2032;\u209b\n                OS_EventTaskWait(\u00adpevent\u2032\u00ad);\u209b\n                EXIT_CRITICAL;\u209b\n                OS_Sched(\u00ad);\u209b\n                ENTER_CRITICAL;\u209b\n                If (OSTCBCur\u2032\u2192OSTCBMsg !=\u2091 NULL){\n                   EXIT_CRITICAL;\u209b\n                   RETURN \u2032OS_NO_ERR\n                };\u209b\n                EXIT_CRITICAL;\u209b\n                RETURN \u2032OS_TIMEOUT   \n          \n        } ELSE {\n          OSTCBCur\u2032\u2192OSTCBStat =\u2091 \u2032OS_STAT_MUTEX;\u209b\n          OSTCBCur\u2032\u2192OSTCBDly =\u2091 timeout\u2032;\u209b\n          OS_EventTaskWait(\u00adpevent\u2032\u00ad);\u209b\n          EXIT_CRITICAL;\u209b\n          OS_Sched(\u00ad);\u209b\n          ENTER_CRITICAL;\u209b\n          If (OSTCBCur\u2032\u2192OSTCBMsg !=\u2091 NULL){\n              EXIT_CRITICAL;\u209b\n              RETURN \u2032OS_NO_ERR\n          };\u209b\n          EXIT_CRITICAL;\u209b\n          RETURN \u2032OS_TIMEOUT \n        }\n                   \n}\u00b7 .\n\nDefinition OSMutexPost_impl :=\n Int8u \u00b7OSMutexPost\u00b7(\u231epevent @ OS_EVENT\u2217 \u231f)\u00b7\u00b7{\n        \u231e\n         x @ Int8u;\n         pip @ Int8u;\n         prio  @ Int8u;\n         legal @ Int8u\n        \u231f;\n        \n        If (pevent\u2032 ==\u2091 NULL){\n           RETURN \u2032OS_ERR_PEVENT_NULL\n        };\u209b\n        ENTER_CRITICAL;\u209b\n        legal\u2032 =\u1da0 OS_EventSearch(\u00b7pevent\u2032\u00b7);\u209b\n        If (legal\u2032 ==\u2091 \u20320){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_PEVENT_NO_EX\n           };\u209b\n        If (pevent\u2032\u2192OSEventType !=\u2091 \u2032OS_EVENT_TYPE_MUTEX){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_EVENT_TYPE\n        };\u209b\n        \n        pip\u2032  =\u2091 \u2329Int8u\u232a(pevent\u2032\u2192OSEventCnt \u226b \u20328);\u209b\n        prio\u2032 =\u2091 \u2329Int8u\u232a(pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_LOWER_8);\u209b    \n        If (OSTCBCur\u2032 !=\u2091 pevent\u2032\u2192OSEventPtr) {   (* See if posting task owns the MUTEX*)\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_NOT_MUTEX_OWNER\n        };\u209b                                                                     \n        If (OSTCBCur\u2032\u2192OSTCBPrio <\u2091 pip\u2032){         (**)\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_MUTEX_PRIO\n        };\u209b\n        legal\u2032 =\u2091 OSUnMapTbl\u2032[pevent\u2032\u2192OSEventGrp];\u209b\n        x\u2032 =\u2091 (legal\u2032\u226a \u20323) +\u2091 OSUnMapTbl\u2032[pevent\u2032\u2192OSEventTbl[legal\u2032]];\u209b\n        If ( pevent\u2032\u2192OSEventGrp !=\u2091 \u20320 &&\u2091 (x\u2032 <\u2091 pip\u2032 ||\u2091  x\u2032 ==\u2091 pip\u2032)){\n            EXIT_CRITICAL;\u209b\n            RETURN \u2032OS_ERR_MUTEX_WL_HIGHEST_PRIO\n        };\u209b\n        If(OSTCBCur \u2032 \u2192 OSTCBStat !=\u2091 \u2032OS_STAT_RDY ||\u2091 OSTCBCur \u2032 \u2192 OSTCBDly !=\u2091 \u20320){\n                EXIT_CRITICAL;\u209b\n                RETURN \u2032OS_ERR_ORIGINAL_NOT_HOLDER\n        };\u209b\n        If (OSTCBCur\u2032\u2192OSTCBPrio ==\u2091 pip\u2032) {\n          (* Did we have to raise current task's priority? *)\n          (* Yes, Return to original priority              *)\n          (*      Remove owner from ready list at 'pip'    *)\n            If ( OSTCBPrioTbl\u2032[prio\u2032]  !=\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder){\n                EXIT_CRITICAL;\u209b\n                RETURN \u2032OS_ERR_ORIGINAL_NOT_HOLDER\n               };\u209b\n            \n            OSRdyTbl\u2032[OSTCBCur\u2032\u2192OSTCBY] =\u2091 OSRdyTbl\u2032[OSTCBCur\u2032\u2192OSTCBY] &\u2091 (\u223cOSTCBCur\u2032\u2192OSTCBBitX);\u209b\n            If ( OSRdyTbl\u2032[OSTCBCur\u2032\u2192OSTCBY] ==\u2091 \u20320) {\n                OSRdyGrp\u2032 =\u2091 OSRdyGrp\u2032 &\u2091 \u223cOSTCBCur\u2032\u2192OSTCBBitY\n            };\u209b\n            OSTCBCur\u2032\u2192OSTCBPrio         =\u2091 prio\u2032;\u209b\n            OSTCBCur\u2032\u2192OSTCBY            =\u2091 prio\u2032 \u226b  \u20323;\u209b\n            OSTCBCur\u2032\u2192OSTCBBitY         =\u2091 OSMapTbl\u2032[OSTCBCur\u2032\u2192OSTCBY];\u209b\n            OSTCBCur\u2032\u2192OSTCBX            =\u2091 prio\u2032 &\u2091 \u20327;\u209b\n            OSTCBCur\u2032\u2192OSTCBBitX         =\u2091 OSMapTbl\u2032[OSTCBCur\u2032\u2192OSTCBX];\u209b\n            OSRdyGrp\u2032                    =\u2091 OSRdyGrp\u2032 |\u2091 OSTCBCur\u2032\u2192OSTCBBitY;\u209b\n            OSRdyTbl\u2032[OSTCBCur\u2032\u2192OSTCBY] =\u2091 OSRdyTbl\u2032[OSTCBCur\u2032\u2192OSTCBY] |\u2091 OSTCBCur\u2032\u2192OSTCBBitX;\u209b\n            OSTCBPrioTbl\u2032[prio\u2032]         =\u2091 \u2329OS_TCB \u2217\u232a OSTCBCur\u2032;\u209b\n            OSTCBPrioTbl\u2032[pip\u2032]          =\u2091 \u2329OS_TCB \u2217\u232a PlaceHolder\n        };\u209b\n        If (pevent\u2032\u2192OSEventGrp !=\u2091 \u20320) {\n            x\u2032 =\u2091 \u2032OS_STAT_MUTEX;\u209b \n            prio\u2032 =\u1da0 OS_EventTaskRdy(\u00b7pevent\u2032, \u2329Void \u2217\u232a pevent\u2032, x\u2032\u00b7);\u209b\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt &\u2091 \u2032OS_MUTEX_KEEP_UPPER_8;\u209b  (*Save priority of mutex's new owner *)\n            pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt |\u2091 prio\u2032;\u209b\n            pevent\u2032\u2192OSEventPtr =\u2091 OSTCBPrioTbl\u2032[prio\u2032];\u209b     (*Link to mutex owner's OS_TCB*)\n     \n            EXIT_CRITICAL;\u209b\n            OS_Sched(\u00ad);\u209b\n            RETURN \u2032OS_NO_ERR \n        };\u209b\n        pevent\u2032\u2192OSEventCnt =\u2091 pevent\u2032\u2192OSEventCnt |\u2091 \u2032OS_MUTEX_AVAILABLE;\u209b (* No,  Mutex is now available   *)\n        pevent\u2032\u2192OSEventPtr =\u2091 NULL;\u209b\n   \n        EXIT_CRITICAL;\u209b\n        RETURN \u2032OS_NO_ERR \n }\u00b7 . \n\nClose Scope code_scope.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/code/os_mutex.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.16148550630654904}}
{"text": "Require Import compcert.common.Memory.\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.juicy_mem.\nRequire Import VST.veric.compcert_rmaps. \nRequire Import VST.veric.semax.\nRequire Import VST.veric.juicy_extspec.\n\nRequire Import VST.veric.mem_lessdef.\nRequire Import VST.veric.age_to_resource_at.\n\nRequire Import VST.veric.aging_lemmas.\n\nLemma jsafeN_age Z Jspec ge ora q jm jmaged :\n  ext_spec_stable age (JE_spec _ Jspec) ->\n  age jm jmaged ->\n  @jsafeN Z Jspec ge ora q jm ->\n  @jsafeN Z Jspec ge ora q jmaged.\nProof. intros. eapply jsafeN__age; eauto. Qed.\n\nLemma jsafeN_age_to Z Jspec ge ora q l jm :\n  ext_spec_stable age (JE_spec _ Jspec) ->\n  @jsafeN Z Jspec ge ora q jm ->\n  @jsafeN Z Jspec ge ora q (age_to l jm).\nProof. intros. eapply jsafeN__age_to; eauto. Qed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/Clight_aging_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.16141235669071524}}
{"text": "From Coq          Require Import Lists.List.\nImport            ListNotations.\nFrom Coq          Require Import String.\nFrom Coq          Require Import Vectors.Vector.\nFrom CryptolToCoq Require Import SAWCoreScaffolding.\nFrom CryptolToCoq Require Import SAWCoreVectorsAsCoqVectors.\nFrom Records      Require Import Records.\n\n\n\nFrom CryptolToCoq Require Import SAWCorePrelude.\nImport SAWCorePrelude.\nFrom CryptolToCoq Require Import CryptolPrimitivesForSAWCore.\nImport CryptolPrimitives.\nFrom CryptolToCoq Require Import CryptolPrimitivesForSAWCoreExtra.\n\nDefinition cbc_enc (n : (@Num)) (enc : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (k : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (iv : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (ps : (@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))))  :=\n  (iter (n) ((fun (cs : (@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) => (@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((ltac:(solveUnsafeAssert) ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) (n))))) ((@CryptolPrimitives.seqMap ((prod ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) ((@SAWCorePrelude.uncurry ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((fun (p : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (c' : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) => (enc (k) ((@CryptolPrimitives.ecXor ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.PLogicSeq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PLogicSeqBool ((@TCNum (8))))))) (p) (c')))))))) ((@CryptolPrimitives.seqZip ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))) (ps) ((@CryptolPrimitives.ecCat ((@TCNum (1))) (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((Vector.cons (_) (iv) (_) ((Vector.nil (_))))) (cs)))))))))) ((CryptolPrimitives.seqConst (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((CryptolPrimitives.seqConst ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((CryptolPrimitives.seqConst ((@TCNum (8))) (@SAWCoreScaffolding.Bool) (SAWCoreScaffolding.False)))))))).\n\nDefinition cbc_dec (n : (@Num)) (dec : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (k : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (iv : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (cs : (@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))))  :=\n  (@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) (n))))) ((@CryptolPrimitives.seqMap ((prod ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.tcMin (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))))) ((@SAWCorePrelude.uncurry ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((fun (c : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (c' : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) => (@CryptolPrimitives.ecXor ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.PLogicSeq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PLogicSeqBool ((@TCNum (8))))))) ((dec (k) (c))) (c')))))) ((@CryptolPrimitives.seqZip ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (n) ((@CryptolPrimitives.tcAdd ((@TCNum (1))) (n))) (cs) ((@CryptolPrimitives.ecCat ((@TCNum (1))) (n) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((Vector.cons (_) (iv) (_) ((Vector.nil (_))))) (cs)))))))).\n\nDefinition repeat (n : (@Num)) (a : Type) (x : a)  :=\n  (@CryptolPrimitives.seqMap (@SAWCoreScaffolding.Bool) (a) (n) ((fun (__p7 : @SAWCoreScaffolding.Bool) => x)) ((@CryptolPrimitives.ecZero ((@CryptolPrimitives.seq (n) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PZeroSeqBool (n)))))).\n\nDefinition pad (n : (@Num)) (p : (@Num)) (b : (@Num)) (msg : (@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (tag : (@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))  :=\n  (@CryptolPrimitives.ecSplit ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (p))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (p))))) ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (p))))) ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))))))) ((@CryptolPrimitives.ecCat (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (p))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) (msg) ((@CryptolPrimitives.ecCat ((@TCNum (32))) (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) (tag) ((repeat (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.ecNumber (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PLiteralSeqBool ((@TCNum (8)))))))))))))))).\n\nDefinition take (front : (@Num)) (back : (@Num)) (a : Type) (__p1 : (@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd (front) (back))) (a)))  :=\n  (fst ((@CryptolPrimitives.ecSplitAt (front) (back) (a) (__p1)))).\n\nDefinition drop (front : (@Num)) (back : (@Num)) (a : Type) (__p4 : (@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd (front) (back))) (a)))  :=\n  (snd ((@CryptolPrimitives.ecSplitAt (front) (back) (a) (__p4)))).\n\nDefinition unpad (n : (@Num)) (p : (@Num)) (b : (@Num)) (ct : (@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))))  :=\n  (pair ((take (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) (n))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) (n))))))))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))))))) ((@CryptolPrimitives.ecJoin ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) (ct))))))))) ((pair ((take ((@TCNum (32))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((drop (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd (n) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))))))))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))))))) ((@CryptolPrimitives.ecJoin ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) (ct))))))))))) ((@CryptolPrimitives.ecEq ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.PCmpSeq ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeqBool ((@TCNum (8))))))) ((drop ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))))))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcMul ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))))) ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))))))) ((@CryptolPrimitives.ecJoin ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) (ct))))))))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.seq_cong1 (p) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) (p) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))))) ((@CryptolPrimitives.tcAdd ((@TCNum (32))) (n))))))))) ((repeat (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.ecNumber (p) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PLiteralSeqBool ((@TCNum (8)))))))))))))))).\n\nDefinition unpad_pad_good_1000_256 (msg : (@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (tag : (@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))  :=\n  (@CryptolPrimitives.ecEq ((prod ((@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((prod ((@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.PCmpPair ((@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((prod ((@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeqBool ((@TCNum (8))))))) ((@CryptolPrimitives.PCmpPair ((@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (@SAWCoreScaffolding.Bool) ((@CryptolPrimitives.PCmpSeq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeqBool ((@TCNum (8))))))) (@CryptolPrimitives.PCmpBit))))) ((unpad ((@TCNum (1000))) ((@TCNum (104))) ((@TCNum (69))) ((pad ((@TCNum (1000))) ((@TCNum (104))) ((@TCNum (69))) (msg) (tag))))) ((pair (msg) ((pair (tag) (@SAWCoreScaffolding.True)))))).\n\nDefinition mee_enc (n : (@Num)) (p : (@Num)) (b : (@Num)) (enc : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (sign : ((@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (ekey : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (skey : (@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (iv : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (msg : (@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))  :=\n  (cbc_enc ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) (enc) (ekey) (iv) ((pad (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) (b))) (n))) (b) (msg) ((sign (skey) (msg)))))).\n\nDefinition and (x : @SAWCoreScaffolding.Bool) (y : @SAWCoreScaffolding.Bool)  :=\n  if x then y else @SAWCoreScaffolding.False.\n\nDefinition mee_dec (n : (@Num)) (p : (@Num)) (b : (@Num)) (dec : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (sign : ((@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq (n) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (ekey : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (skey : (@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (iv : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (ct : (@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))))  :=\n  (pair ((fst ((unpad (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) (b))) (n))) (b) ((cbc_dec ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) (dec) (ekey) (iv) (ct))))))) ((and ((snd ((snd ((unpad (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) (b))) (n))) (b) ((cbc_dec ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) (dec) (ekey) (iv) (ct))))))))) ((@CryptolPrimitives.ecEq ((@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@CryptolPrimitives.PCmpSeq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeqBool ((@TCNum (8))))))) ((sign (skey) ((fst ((unpad (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) (b))) (n))) (b) ((cbc_dec ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) (dec) (ekey) (iv) (ct))))))))) ((fst ((snd ((unpad (n) ((@CryptolPrimitives.tcSub ((@CryptolPrimitives.tcMul ((@TCNum (16))) (b))) (n))) (b) ((cbc_dec ((@CryptolPrimitives.tcAdd ((@TCNum (2))) (b))) (dec) (ekey) (iv) (ct)))))))))))))).\n\nDefinition mee_enc_dec_good_1000 (enc : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (dec : ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (sign : ((@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> ((@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) -> (@CryptolPrimitives.seq ((@TCNum (32))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (ekey : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (skey : (@CryptolPrimitives.seq ((@TCNum (64))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (iv : (@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (msg : (@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool)))))  :=\n  (@CryptolPrimitives.ecEq ((prod ((@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpPair ((@CryptolPrimitives.seq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) (@SAWCoreScaffolding.Bool) ((@CryptolPrimitives.PCmpSeq ((@TCNum (1000))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))) ((@CryptolPrimitives.PCmpSeqBool ((@TCNum (8))))))) (@CryptolPrimitives.PCmpBit))) ((mee_dec ((@TCNum (1000))) ((@TCNum (104))) ((@TCNum (69))) (dec) (sign) (ekey) (skey) (iv) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@TCNum (71))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq_cong1 ((@TCNum (71))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@TCNum (71))) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))))))) ((@SAWCoreScaffolding.coerce ((@CryptolPrimitives.seq ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq ((@TCNum (71))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))))) ((@CryptolPrimitives.seq_cong1 ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))) ((@TCNum (71))) ((@CryptolPrimitives.seq ((@TCNum (16))) ((@CryptolPrimitives.seq ((@TCNum (8))) (@SAWCoreScaffolding.Bool))))) ((@SAWCorePrelude.sawUnsafeAssert ((@Num)) ((@CryptolPrimitives.tcAdd ((@TCNum (2))) ((@TCNum (69))))) ((@TCNum (71))))))) ((mee_enc ((@TCNum (1000))) ((@TCNum (104))) ((@TCNum (69))) (enc) (sign) (ekey) (skey) (iv) (msg))))))))) ((pair (msg) (@SAWCoreScaffolding.True)))).\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/generated/MEE_CBC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.16121986230320362}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import Progress.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import ITreeLang.\nRequire Import ITreeLib.\n\nSet Implicit Arguments.\n\n\nVariant reorder_abort: forall R (i2:MemE.t R), Prop :=\n| reorder_abort_load\n    l2 o2\n    (ORD2: Ordering.le o2 Ordering.relaxed):\n    reorder_abort (MemE.read l2 o2)\n| reorder_abort_store\n    l2 v2 o2\n    (ORD21: Ordering.le o2 Ordering.acqrel)\n    (ORD22: Ordering.le Ordering.plain o2):\n    reorder_abort (MemE.write l2 v2 o2)\n| reorder_abort_fence\n    or2 ow2\n    (ORDR2: Ordering.le or2 Ordering.relaxed)\n    (ORDW2: Ordering.le ow2 Ordering.acqrel):\n    reorder_abort (MemE.fence or2 ow2)\n| reorder_abort_choose:\n    reorder_abort MemE.choose\n.\n\nVariant sim_abort:\n  forall R (st_src:itree MemE.t (void * R)%type) (lc_src:Local.t) (gl1_src:Global.t), Prop :=\n| sim_abort_intro\n    R (i2: MemE.t R)\n    lc1_src gl1_src\n    (REORDER: reorder_abort i2)\n    (LC_WF_SRC: Local.wf lc1_src gl1_src)\n    (GL_WF_SRC: Global.wf gl1_src):\n    @sim_abort\n      R (Vis i2 (fun v2 => Vis (MemE.abort) (fun v1 => Ret (v1, v2)))) lc1_src gl1_src\n.\n\nLemma sim_abort_steps_failure\n      R\n      st1_src lc1_src gl1_src\n      (SIM: @sim_abort R st1_src lc1_src gl1_src):\n  Thread.steps_failure (Thread.mk (lang (void * R)%type) st1_src lc1_src gl1_src).\nProof.\n  destruct SIM. destruct REORDER.\n  - (* load *)\n    exploit progress_read_step; try exact LC_WF_SRC; eauto. i. des.\n    econs.\n    + econs 2; [|refl]. econs.\n      * econs 2; [|econs 2]; eauto. econs. refl.\n      * ss.\n    + econs 2; [|econs 7]; eauto. econs.\n    + ss.\n  - (* store *)\n    exploit progress_write_step; try apply Time.incr_spec; eauto. i. des.\n    econs.\n    + econs 2; [|refl]. econs.\n      * econs 2; [|econs 3]; eauto. econs. refl.\n      * ss.\n    + econs 2; [|econs 7]; eauto. econs.\n    + ss.\n  - (* fence *)\n    exploit progress_fence_step.\n    { instantiate (2:=ow2). destruct ow2; ss. }\n    i. des.\n    econs.\n    + econs 2; [|refl]. econs.\n      * econs 2; [|econs 5]; eauto. econs. refl.\n      * ss.\n    + econs 2; [|econs 7]; eauto. econs.\n    + ss.\n  - (* choose *)\n    econs.\n    + econs 2; [|econs 1]. econs.\n      * econs 2; [|econs 1]. econs. refl.\n      * ss.\n    + econs 2; [|econs 7]; eauto. econs.\n    + ss.\n  Unshelve. econs 2.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/ReorderAbort.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.16119282697829349}}
{"text": "Require Export DEX_Framework.\nRequire Export DEX_ProofBigStepWithType.\nRequire Export DEX_ElemLemmas.\nRequire Export DEX_ElemLemmaIntra.\nRequire Export DEX_ElemLemmaReturn.\nRequire Export DEX_step.\nRequire Export DEX_typing_rules.\n\nImport DEX_BigStepWithTypes DEX_BigStepAnnot.DEX_BigStepAnnot DEX_BigStep.DEX_BigStep DEX_Dom DEX_Prog.\n\nLtac assert_some_not_none rt rn H := \n    assert (VarMap.get L.t rt rn <> None) by solve [\n    destruct (VarMap.get L.t rt rn) as [a | ]; \n      try (intros Hf; inversion Hf);\n      try (inversion H)].\n\nLtac assert_not_none_some rt rn k t:= \n   assert (exists k, Some k = VarMap.get L.t rt rn) by solve [\n    destruct (VarMap.get L.t rt rn) as [t | ] eqn:Hget; \n      try (exists t; auto); \n      try (apply False_ind; auto)].\n\nDefinition ValidMethod (p:DEX_Program) (m:DEX_Method) : Prop :=\n  exists c, DEX_PROG.defined_Class p c /\\ DEX_CLASS.defined_Method c m.\n\nDefinition step (p:DEX_Program) : DEX_Method -> DEX_PC -> option DEX_PC -> Prop := \nfun m pc (* tau *) opc =>\n  ValidMethod p m /\\ exists i, instructionAt m pc = Some i /\\ DEX_step m pc i opc.\n\nVariable RT_domain_same : forall rt1 rt2 r, In r (VarMap.dom L.t rt1) -> In r (VarMap.dom L.t rt2).\nVariable valid_regs_prop : forall m bm r rt, DEX_METHOD.body m = Some bm -> \n    ~ In r (DEX_BYTECODEMETHOD.regs bm) -> VarMap.get L.t rt r = None.\nVariable RT_domain_length_same : forall rt1 rt2, length (VarMap.dom L.t rt1) = length (VarMap.dom L.t rt2). \n\nSection hyps.\n  Variable kobs: L.t.\n  Variable p : DEX_ExtendedProgram.\n  Definition Reg := DEX_Reg.\n  Definition PC := DEX_PC.\n  Definition Method := DEX_Method.\n  Definition Kind := option DEX_ClassName.\n  Definition Sign : Set :=  DEX_sign.\n\n  Definition PM := ValidMethod.\n\n  Inductive P : SignedMethod Method Sign -> Prop :=\n    P_def : forall (m:DEX_Method) sgn,\n      ValidMethod p m ->\n      (DEX_METHOD.isStatic m = true -> sgn = DEX_static_signature p (DEX_METHOD.signature m)) ->\n      (DEX_METHOD.isStatic m = false -> exists k, sgn = DEX_virtual_signature p (DEX_METHOD.signature m) k) ->\n      P (SM _ _ m sgn).\n\n  Section for_all.\n    Variable test : DEX_METHOD.t -> Sign -> bool.\n    \n    Definition for_all_P : bool :=\n      for_all_methods p \n      (fun m => \n        if DEX_METHOD.isStatic m then test m (DEX_static_signature p (DEX_METHOD.signature m))\n          else for_all _ (fun k => test m (DEX_virtual_signature p (DEX_METHOD.signature m) k)) L.all).\n\n    Lemma for_all_P_true : for_all_P = true ->\n      forall m sgn, P (SM _ _ m sgn) -> test m sgn = true.\n    Proof.\n      unfold for_all_P; intros.\n      inversion_mine H0.\n      generalize (for_all_methods_true _ _ H _ H3).\n      caseeq (DEX_METHOD.isStatic m); intros.\n      rewrite <- H4 in H1; auto.\n      generalize (for_all_true _ _ _ H1); intros.\n      elim H5; auto.\n      intros k Hk.\n      rewrite Hk; apply H2.\n      apply L.all_in_all.\n    Qed.\n  \n  End for_all.\n\n  Lemma PM_P : forall m, P m -> PM p (unSign _ _ m).\n  Proof.\n    intros.\n    inversion_clear H; auto.\n  Qed.\n\n  Notation step := (step p).\n  Variable cdr : forall m, PM p m -> CDR (step m).\n\n  Definition istate : Type := DEX_IntraNormalState.\n  Definition rstate : Type := DEX_ReturnState.\n  Inductive exec : Method -> istate -> istate + rstate -> Prop :=\n  | exec_intra : forall (m:Method) s1 s2,\n    DEX_BigStepAnnot.DEX_exec_intra p m s1 s2 -> \n    exec m s1 (inl _ s2)\n  | exec_return : forall (m:Method) s ret,\n    DEX_BigStepAnnot.DEX_exec_return p m s ret ->\n    exec m s (inr _ ret).\n\n  Inductive evalsto : Method -> istate -> rstate -> Prop :=\n  | evalsto_return : forall (m:Method) s r,\n    exec m s (inr _ r) ->\n    evalsto m s r\n  | evalsto_intra : forall (m:Method) s1 s2 r,\n    exec m s1 (inl _ s2) ->\n    evalsto m s2 r ->\n    evalsto m s1 r. \n\n  Definition pc : istate -> PC := @fst _ _.\n\n  Definition registertypes : Type := TypeRegisters.\n\n  Definition texec : forall m, PM p m -> Sign -> (PC -> L.t) ->\n    PC -> registertypes -> option registertypes -> Prop :=\n    fun m H sgn se pc rt ort =>\n      exists i, texec sgn (region (cdr m H)) se pc i rt ort\n        /\\ instructionAt m pc = Some i.\n\n  Inductive indist : Sign -> registertypes ->\n    registertypes -> istate -> istate -> Prop :=\n    indist_def :forall sgn rt1 rt2 r1 r2 pc1 pc2,\n      st_in kobs rt1 rt2 (pc1,r1) (pc2,r2) ->\n      indist sgn rt1 rt2 (pc1,r1) (pc2,r2).\n\n  Inductive rindist : Sign -> rstate -> rstate -> Prop :=\n  | rindist_def : forall sgn r1 r2,\n    indist_return_value kobs sgn r1 r2 -> rindist sgn r1 r2.\n\n  Definition default_level := L.High.\n\n  Inductive init_pc (m:Method) : PC -> Prop :=\n    init_pc_def : forall bm,\n      DEX_METHOD.body m = Some bm ->\n      init_pc m (DEX_BYTECODEMETHOD.firstAddress bm).\n\n  Definition rt0 (m:Method) (sgn:Sign): registertypes := \n  match DEX_METHOD.body m with\n  | Some bm => (Annotated.make_rt_from_lvt_rec (sgn) (DEX_BYTECODEMETHOD.locR bm) (DEX_BYTECODEMETHOD.regs bm) (default_level))\n  | None => VarMap.empty L.t\n  end.\n\n  Definition ni := ni _ _ _ _ _ exec pc registertypes indist rindist rt0 init_pc P.\n\n  Open Scope nat_scope.\n\n  Lemma evalsto_Tevalsto : forall m s r,\n    evalsto m s r ->\n    exists p, DEX_Framework.evalsto Method istate rstate exec m p s r.\n  Proof.\n    intros.\n    induction H.\n    exists 1; constructor 1; auto.\n    inversion IHevalsto.\n    exists (S x). constructor 2 with (s2:=s2); auto.\n  Qed.\n\n  Lemma evalsto_Tevalsto2 : forall m s r p,\n    DEX_Framework.evalsto Method istate rstate exec m p s r ->\n    evalsto m s r.\n  Proof.\n    intros.\n    induction H.\n    constructor 1; auto.\n    constructor 2 with (s2:=s2); auto.\n  Qed.\n\n  Lemma in_snd : forall (A B:Type) (a:A) (b:B) l, In (a, b) l -> In b (map snd l).\n  Proof.\n    induction l; intros.\n      inversion H.\n      inversion H. left. rewrite H0; auto.\n      right; apply IHl; auto.\n  Qed.\n\n  Lemma tcc0 : forall m s s',\n    PM p m -> exec m s (inl rstate s') -> step m (pc s) (Some (pc s')).\n  Proof.\n    intros m s s' HP H.\n    split.\n    auto.\n    inversion_clear H.\n    inversion_clear H0.\n    inversion_clear H;\n      try (match goal with\n        | [ id : instructionAt _ _ = Some ?i |- _] =>\n          exists i; simpl; split; [assumption|idtac]; constructor; \n            simpl; auto; fail\n      end).\n      exists (DEX_PackedSwitch r firstKey size list_offset); simpl; split; auto.\n      constructor 16. apply nth_error_In with (n:=n); auto.\n      exists (DEX_SparseSwitch r size listkey); simpl; split; auto.\n      constructor 18. apply in_snd with (a:=v'); auto.\n  Qed.\n\n  Lemma tcc1 : forall m s s',\n    PM p m -> exec m s (inr istate s') -> step m (pc s) None.\n  Proof.\n    intros m s s' HM H.\n    split; auto.\n    inversion_clear H.\n    inversion_clear H0.\n    inversion_clear H.\n    exists DEX_Return; simpl; split; auto; constructor.\n    exists (DEX_VReturn k rs); simpl; split; auto; constructor.\n  Qed.\n\n  Inductive sub : registertypes -> registertypes -> Prop :=\n  | forall_sub : forall rt1 rt2, eq_set (VarMap.dom _ rt1) (VarMap.dom _ rt2) ->\n      (forall r k1 k2, Some k1 = VarMap.get _ rt1 r -> Some k2 = VarMap.get _ rt2 r -> L.leql k1 k2) \n      -> sub rt1 rt2\n  | nil_sub : sub (VarMap.empty _) (VarMap.empty _). \n\n  Lemma sub_forall : forall rt rt', sub rt rt' -> \n    (forall r k1 k2, \n      Some k1 = VarMap.get _ rt r /\\ Some k2 = VarMap.get _ rt' r -> \n    L.leql k1 k2).\n  Proof. intros. inversion H0; auto.\n    inversion H; subst. apply H4 with (r:=r); auto.\n    rewrite VarMap.get_empty in H1. inversion H1.\n  Qed.\n\n  Lemma indist_morphism_proof : forall (y : Sign) (x y0 : registertypes),\n    eq_rt x y0 ->\n    forall x0 y1 : registertypes,\n    eq_rt x0 y1 -> forall y2 y3 : istate, indist y x x0 y2 y3 <-> indist y y0 y1 y2 y3.\n  Proof.\n    split; intros.\n    (* -> *)\n    inversion_mine H1.\n    constructor.\n    inversion_mine H2.\n    inversion_mine H3.\n    constructor; constructor; intros.\n      (* same domain *)\n      inversion H; inversion H0.\n      rewrite <- H3; rewrite <- H5; auto.\n      (* indistinguishable contents *)\n      assert (H':=H); assert (H0':=H0).\n      inversion_mine H; inversion_mine H0.\n      specialize H2 with rn.\n      inversion H2. \n      assert_some_not_none x rn H0.\n      assert_some_not_none x0 rn H6.\n      apply VarMap.get_some_in_dom in H9.\n      apply VarMap.get_some_in_dom in H10.      \n      constructor 1 with (k:=k) (k':=k'); auto.\n      rewrite eq_rt_get with (rt1:=y0) (rt2:=x); auto. apply eq_rt_sym; auto.\n      rewrite <- H3; auto.\n      rewrite eq_rt_get with (rt1:=y1) (rt2:=x0); auto. apply eq_rt_sym; auto.\n      rewrite H in H10; auto.\n      constructor 2. auto.\n    (* <- *)\n    inversion_mine H1.\n    constructor.\n    inversion_mine H2.\n    inversion_mine H3.\n    constructor; constructor; intros.\n      (* same domain *)\n      inversion H; inversion H0.\n      rewrite H3; rewrite H5; auto.\n      (* indistinguishable contents *)\n      assert (H':=H); assert (H0':=H0).\n      inversion_mine H; inversion_mine H0.\n      specialize H2 with rn.\n      inversion H2. \n      assert_some_not_none y0 rn H0.\n      assert_some_not_none y1 rn H6.\n      apply VarMap.get_some_in_dom in H9.\n      apply VarMap.get_some_in_dom in H10.      \n      constructor 1 with (k:=k) (k':=k'); auto.\n      rewrite eq_rt_get with (rt1:=x) (rt2:=y0); auto. rewrite H3; auto.\n      rewrite eq_rt_get with (rt1:=x0) (rt2:=y1); auto. rewrite H; auto. \n      constructor 2. auto.\n  Qed.\n\n  Definition TypableProg := TypableProg PC Method step (PM p) Sign (* istate pc *) registertypes \n    texec rt0 init_pc P PM_P sub eq_rt.\n\n  Section TypableProg.\n\n    Variable se : Method -> Sign -> PC -> L.t.\n    Variable RT : Method -> Sign -> PC -> registertypes.\n    Variable typable_hyp : TypableProg se RT.\n\n    Definition high_reg (rt:registertypes) (r:Reg) : Prop :=\n      match VarMap.get _ rt r with\n      | None => False\n      | Some k => ~L.leql k kobs\n      end.\n\n    Variable not_high_reg : forall rt r, ~high_reg rt r -> (exists k, VarMap.get L.t rt r = Some k /\\ L.leql k kobs).\n\n    Definition indist_reg_val (s1 s2: istate) (r: Reg) : Prop :=\n      let rho1 := snd s1 in\n      let rho2 := snd s2 in\n        match DEX_Registers.get rho1 r, DEX_Registers.get rho2 r with\n        | Some v1, Some v2 => v1 = v2\n        | None, None => True\n        | _, _ => False\n        end.\n\n    Lemma indist_reg_val_trans : forall s1 s2 s3 r, \n      indist_reg_val s1 s2 r -> indist_reg_val s2 s3 r -> indist_reg_val s1 s3 r.\n    Proof.\n      intros.\n      unfold indist_reg_val in *.\n      destruct (DEX_Registers.get (snd s1) r);\n      destruct (DEX_Registers.get (snd s2) r);\n      destruct (DEX_Registers.get (snd s3) r); auto.\n      rewrite H; auto. inversion H.\n    Qed.\n\n    Lemma indist_reg_val_sym : forall s1 s2 r, \n      indist_reg_val s1 s2 r -> indist_reg_val s2 s1 r.\n    Proof.\n      unfold indist_reg_val in *.\n      intros.\n      destruct (DEX_Registers.get (snd s1) r);\n      destruct (DEX_Registers.get (snd s2) r); auto.\n    Qed.\n\n    Definition indist_reg := DEX_Framework.indist_reg Reg istate registertypes high_reg indist_reg_val.\n\n    Lemma indist_from_reg : forall sgn rt1 rt2 s1 s2, \n      (forall r, indist_reg rt1 rt2 s1 s2 r) -> indist sgn rt1 rt2 s1 s2.\n    Proof.\n      intros.\n      destruct s1; destruct s2.\n      constructor.\n      constructor.\n      constructor.\n      constructor.\n        apply RT_domain_length_same.\n        split; eapply RT_domain_same; eauto.\n      intros.\n      specialize H with rn. \n      inversion H.\n      unfold high_reg in *. \n      destruct (VarMap.get L.t rt1 rn) eqn:Hget1; destruct (VarMap.get L.t rt2 rn) eqn:Hget2; try (contradiction).\n      constructor 1 with (k:=t1) (k':=t2); auto. \n      constructor 2. subst. unfold indist_reg_val in H0.\n      simpl in H0. destruct (DEX_Registers.get t rn); destruct (DEX_Registers.get t0 rn); subst; try contradiction.\n      destruct d2; repeat constructor.\n      constructor.\n    Qed.\n\n    Lemma indist_reg_from_indist : forall sgn rt1 rt2 s1 s2,\n      indist sgn rt1 rt2 s1 s2 -> \n      forall r, \n        (high_reg rt1 r -> high_reg rt2 r -> indist_reg rt1 rt2 s1 s2 r) /\\ \n        ((~high_reg rt1 r /\\ ~high_reg rt2 r) \\/\n          (high_reg rt1 r /\\ ~high_reg rt2 r) \\/\n          (~high_reg rt1 r /\\ high_reg rt2 r) ->\n        indist_reg_val s1 s2 r).\n    Proof.\n      intros sgn rt1 rt2 s1 s2 Hindist r.\n      inversion Hindist. inversion H. inversion H6. subst. \n      specialize H11 with (rn:=r).\n      inversion H11.\n      split; intros.\n      constructor; auto.\n      inversion H4. inversion H5.\n      unfold high_reg in H7, H8.\n      rewrite H0 in H7; rewrite H1 in H8. contradiction.\n      inversion H5. inversion H7. \n      unfold high_reg in H8, H9.\n      rewrite H0 in H8; rewrite H1 in H9. contradiction.\n      inversion H7.\n      unfold high_reg in H8, H9.\n      rewrite H0 in H8; rewrite H1 in H9. contradiction.\n      split; intros. constructor; auto.\n      unfold indist_reg_val. simpl.\n      destruct (DEX_Registers.get r1 r); destruct (DEX_Registers.get r2 r); subst; auto.\n      inversion H0. inversion H4. auto.\n      inversion H0. inversion H0.\n    Qed.\n\n    Definition high_result := high_result kobs.\n\n    Lemma tevalsto_high_result : forall m sgn (H:PM p m) se s RT res,\n      ~L.leql (se m sgn (pc s)) kobs ->\n      exec m s (inr res) ->\n      texec m H sgn (se m sgn) (pc s) (RT m sgn (pc s)) None -> high_result sgn res.\n    Proof.\n      intros.\n      inversion_mine H2. \n      inversion_mine H1. Cleanexand.\n      inversion_mine H6. inversion_mine H3. \n      inversion_mine H1. constructor 1. auto. \n      simpl in H2. rewrite H2 in H5. inversion H5.\n      inversion_mine H1. simpl in H2. rewrite H2 in H5. inversion H5. \n      constructor 2 with (k:=kv); auto.\n      simpl in H0, H11.\n      apply leql_join_each in H11. Cleanexand.\n      apply not_leql_trans with (k1:=se0 m sgn pc0); auto.\n    Qed.\n\n    (* this is only applicable to exception instructions, so normal instructions \n      only need to be proved via contradiction *)\n    Lemma tevalsto_diff_high_result : forall m sgn se RT s s' s1' rt res res' (H:PM p m),\n      pc s = pc s' ->\n      exec m s (inr res) ->\n      texec m H sgn (se m sgn) (pc s) (RT m sgn (pc s)) None ->\n      exec m s' (inl s1') ->\n      texec m H sgn (se m sgn) (pc s') (RT m sgn (pc s')) (Some rt) ->\n      evalsto m s' res' -> \n      high_result sgn res /\\ high_result sgn res'.\n    Proof.\n      intros.\n      inversion_mine H1; inversion_mine H2; inversion_mine H3; inversion_mine H4.\n      Cleanexand.\n      inversion_mine H1;\n      inversion_mine H2;\n      match goal with\n        | [ H0 : pc s = pc s', H : instructionAt m (pc s) = ?P, H' : instructionAt m (pc s') = ?Q |- _ ] => \n          rewrite <- H0 in H'; rewrite H' in H; inversion H\n      end.\n    Qed.\n\n    Lemma tevalsto_diff_high_result' : forall m sgn s s' p0 res res' (H:PM p m),\n      pc s = pc s' -> 1 < p0 ->\n      DEX_Framework.tevalsto PC Method (PM p) Sign istate rstate exec (pc) (registertypes) texec\n        sub m H sgn (se m sgn) (RT m sgn) 1 s res -> \n      DEX_Framework.tevalsto PC Method (PM p) Sign istate rstate exec (pc) (registertypes) texec\n        sub m H sgn (se m sgn) (RT m sgn) p0 s' res' -> \n      high_result sgn res /\\ high_result sgn res'. \n    Proof.\n      intros.\n      inversion_mine H3. omega.\n      inversion_mine H4.\n      apply tevalsto_diff_high_result with (m:=m) (se:=se) (RT:=RT) (s:=s) (s':=s') (s1':=s2) (rt:=rt') (H:=H); auto.\n      inversion_mine H2; auto.\n      inversion H3; auto.\n      inversion H8.\n      inversion_mine H2; auto. inversion_mine H3; auto.\n      inversion H8.\n      apply DEX_Framework.tevalsto_evalsto in H5; auto.\n      apply evalsto_Tevalsto2 with (p:=S n).\n      constructor 2 with (s2:=s2); auto.\n    Qed.\n\n    Lemma high_result_indist : forall sgn res res0,\n      high_result sgn res -> high_result sgn res0 -> rindist sgn res res0.\n    Proof.\n      intros.\n      constructor.\n      destruct sgn. destruct DEX_resType eqn:Hres.\n      destruct res. destruct res0.\n      destruct o. destruct o0.\n      constructor 1 with (k:=t); auto.\n      intros. inversion H0. simpl in H3. inversion H3. subst. contradiction.\n      inversion H0. simpl in H1. inversion H1.\n      destruct o0.\n      inversion H. simpl in H1. inversion H1.\n      inversion H0. simpl in H1. inversion H1.\n      inversion H. inversion H0. subst. constructor 2; auto.\n      simpl in H3. inversion H3.\n      simpl in H1; inversion H1.\n    Qed.\n\n    Lemma high_reg_dec : forall rt r, high_reg rt r \\/ ~high_reg rt r.\n    Proof.\n      intros.\n      apply excluded_middle with (P:=high_reg rt r).\n    Qed.\n\n    Definition path := DEX_Framework.path Method istate rstate exec.\n\n    Definition path_in_region := DEX_Framework.path_in_region PC Method step istate rstate exec pc.\n\n    Inductive changed_at (m:Method) (i:istate) (r:Reg) : Prop :=\n      | const_change : forall k v, instructionAt m (pc i) = Some (DEX_Const k r v) -> changed_at m i r\n      | move_change : forall k rs, instructionAt m (pc i) = Some (DEX_Move k r rs) -> changed_at m i r\n      | ineg_change : forall rs, instructionAt m (pc i) = Some (DEX_Ineg r rs) -> changed_at m i r\n      | inot_change : forall rs, instructionAt m (pc i) = Some (DEX_Inot r rs) -> changed_at m i r\n      | i2b_change : forall rs, instructionAt m (pc i) = Some (DEX_I2b r rs) -> changed_at m i r\n      | i2s_change : forall rs, instructionAt m (pc i) = Some (DEX_I2s r rs) -> changed_at m i r\n      | ibinop_change : forall op ra rb, instructionAt m (pc i) = Some (DEX_Ibinop op r ra rb) -> changed_at m i r\n      | ibinopConst_change : forall op rs v, instructionAt m (pc i) = Some (DEX_IbinopConst op r rs v) -> changed_at m i r.\n\n    Definition changed_at_t (m:Method) (i:istate) (r:Reg) : bool :=\n      match instructionAt m (pc i) with\n        | Some (DEX_Const k r' v) => Reg_eq r r'\n        | Some (DEX_Move _ r' _) => Reg_eq r r'\n        | Some (DEX_Ineg r' _) => Reg_eq r r'\n        | Some (DEX_Inot r' _) => Reg_eq r r'\n        | Some (DEX_I2b r' _) => Reg_eq r r'\n        | Some (DEX_I2s r' _) => Reg_eq r r'\n        | Some (DEX_Ibinop _ r' _ _) => Reg_eq r r'\n        | Some (DEX_IbinopConst _ r' _ _) => Reg_eq r r'\n        | _ => false\n      end.\n\n    Ltac inconsistent_ins :=\n      match goal with | [H:instructionAt ?m ?i = Some ?P, H':instructionAt ?m ?i = Some ?Q |- _] => \n          rewrite H' in H; inversion H end.\n    Ltac not_changed_auto := unfold not; intros HnotChangedAuto; inversion HnotChangedAuto; inconsistent_ins.\n\n    Lemma changed_at_spec : forall m i r, if changed_at_t m i r then changed_at m i r else ~changed_at m i r.\n    Proof.\n      intros.\n      unfold changed_at_t.\n      destruct (instructionAt m (pc i)) eqn:Hins.\n      unfold Reg_eq.\n      destruct d; try (not_changed_auto; fail);\n      try (destruct (Neq r rt) eqn:Heq; generalize (Neq_spec r rt); rewrite Heq; intros);\n      try (constructor; subst; auto);\n      try (not_changed_auto; contradiction).\n      constructor 2 with (k:=k) (rs:=rs); subst; auto.\n      constructor 1 with (k:=k) (v:=v); subst; auto.\n      constructor 3 with (rs:=rs); subst; auto.\n      constructor 4 with (rs:=rs); subst; auto.\n      constructor 5 with (rs:=rs); subst; auto.\n      constructor 6 with (rs:=rs); subst; auto.\n      constructor 7 with (ra:=ra) (rb:=rb) (op:=op); subst; auto.\n      constructor 8 with (rs:=r0) (v:=v) (op:=op); subst; auto.\n      (* the case where the instructionAt is none *)\n      unfold not; intros H; inversion H;\n      match goal with \n        | [H:instructionAt m (pc i) = None, H':instructionAt m (pc i) = Some _ |- _] => rewrite H' in H; inversion H\n      end.\n    Qed.\n\n    Inductive changed (m:Method) (i j: istate) : (path m i j) -> Reg -> Prop :=\n      | changed_onestep : forall r (p:path m i j), changed_at m i r -> changed m i j p r\n      | changed_path : forall k r (p:path m k j) (H:exec m i (inl k)), \n          changed m k j p r -> changed m i j (path_step Method istate rstate exec m i j k p H) r.\n\n    Lemma changed_dec : forall m i j r (p:path m i j), \n      changed m i j (p) r \\/ ~changed m i j (p) r. \n    Proof.\n      intros.\n      apply excluded_middle with (P:=changed m i j p0 r). \n    Qed.\n\n    Lemma changed_high_onestep : forall m sgn s i j r (H: P (SM _ _ m sgn)),\n      (forall k:PC, region (cdr m (PM_P _ H)) s k -> ~ L.leql (se m sgn k) kobs) ->\n      region (cdr m (PM_P _ H)) s (pc i) ->\n      exec m i (inl j) ->\n      changed_at m i r -> high_reg (RT m sgn (pc j)) r.\n    Proof.\n      intros m sgn s i j r H Hhighreg Hreg Hexec Hchanged_at.\n      assert (Hexec':=Hexec).\n      apply tcc0 with (1:=PM_P _ H) in Hexec'.\n      destruct (typable_hyp m sgn H) as [T1 [T2 T3]]. \n      specialize T3 with (i:=pc i) (j:=pc j) (1:=Hexec'). \n      destruct T3 as [rt [Htexec Hsub]].\n      specialize Hhighreg with (pc i). apply Hhighreg in Hreg. \n      inversion Htexec as [x [Htexec' Hins]].\n      inversion_mine Hchanged_at;\n      try (rewrite H0 in Hins; injection Hins; intros; subst; \n      inversion_mine Htexec';\n      unfold high_reg;\n      generalize sub_forall; intros Hsub_forall;\n      specialize Hsub_forall with (1:=Hsub) (r:=r);\n      destruct (VarMap.get _ (RT m sgn (pc j)) r) eqn:Hval);\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (pc j)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end).\n      (* Const *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (se m sgn (pc i))) r = Some k) as Hget. \n      exists (se m sgn (pc i)). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=(se m sgn (pc i))); auto.\n      (* Move *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (se m sgn (pc i)) k_rs)) r = Some k) as Hget. \n      exists ((L.join (se m sgn (pc i)) k_rs)). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=(se m sgn (pc i))); auto.\n      apply leql_join_each in Hleql; destruct Hleql; auto.\n      (* Ineg *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (se m sgn (pc i)) ks)) r = Some k) as Hget. \n      exists (L.join (se m sgn (pc i)) ks). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.\n      (* Inot *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (se m sgn (pc i)) ks)) r = Some k) as Hget. \n      exists (L.join (se m sgn (pc i)) ks). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.  \n      (* I2b *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (se m sgn (pc i)) ks)) r = Some k) as Hget. \n      exists (L.join (se m sgn (pc i)) ks). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.\n      (* I2s *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (se m sgn (pc i)) ks)) r = Some k) as Hget. \n      exists (L.join (se m sgn (pc i)) ks). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.\n      (* Ibinop *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join (L.join ka kb) (se m sgn (pc i)))) r = Some k) as Hget. \n      exists (L.join (L.join ka kb) (se m sgn (pc i))). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.\n      (* IbinopConst *)\n      assert (exists k, VarMap.get L.t (VarMap.update L.t (RT m sgn (pc i)) r (L.join ks (se m sgn (pc i)))) r = Some k) as Hget. \n      exists (L.join ks (se m sgn (pc i))). rewrite VarMap.get_update1; auto.\n      destruct Hget as [lvl Hget]. specialize Hsub_forall with (k1:=lvl) (k2:=t). rewrite Hget in Hsub_forall.\n      assert (L.leql lvl t) as Hleql; auto.\n      rewrite VarMap.get_update1 in Hget. inversion_mine Hget.\n      apply not_leql_trans with (k1:=se m sgn (pc i)); auto.\n      apply leql_join_each in Hleql. Cleanexand; auto.\n    Defined.\n\n    Ltac clear_other_ins ins :=\n      match goal with \n      | [H:instructionAt ?m ?pc0 = Some ?ins, Hins:instructionAt ?m ?pc = Some ins |- _] =>\n        try (simpl in Hins; rewrite H in Hins; inversion Hins)\n      end.\n\n    Ltac not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r:=\n      simpl; subst;\n      destruct (typable_hyp m sgn HPM) as [T1 [T2 T3]];\n      assert (Hexec':=Hexec); apply tcc0 with (1:=PM_P _ HPM) in Hexec';\n      specialize T3 with (i:=pc0) (j:=pc') (1:=Hexec');\n      destruct T3 as [rt' [Htexec Hsub]];\n      inversion Htexec as [ins [Htexec' Hins']];\n      rewrite H in Hins'; inversion Hins'; subst; inversion Htexec'; subst;\n      unfold high_reg; intros;\n      destruct (VarMap.get L.t (RT m sgn pc0) r) eqn:Hrt0.\n\n    Lemma not_changed_same_onestep : forall m sgn i j r (HPM: P (SM _ _ m sgn)),\n      ~changed_at m i r -> \n      exec m i (inl j) ->\n      (indist_reg_val i j r) /\\ (high_reg (RT m sgn (pc i)) r -> high_reg (RT m sgn (pc j)) r). \n    Proof.\n      intros m sgn i j r HPM Hnchanged_at Hexec.\n      generalize (changed_at_spec m i r); intros Hchanged_at_dec.\n      destruct (changed_at_t m i r) eqn:Hchanged_at.\n      contradiction.\n      unfold changed_at_t in Hchanged_at.\n      destruct (instructionAt m (pc i)) eqn:Hins. \n      destruct d eqn:Hins'. \n      (* const *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Nop).\n      split.\n      unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* move *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Move k rt rs).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* Return *)\n      inversion Hexec. inversion H2. inversion_mine H3; clear_other_ins (DEX_Return).\n      (* VReturn *)\n      inversion Hexec. inversion H2. inversion_mine H3; clear_other_ins (DEX_VReturn k rt).\n      (* Const *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Const k rt v).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* goto *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Goto o).\n      split.\n      unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 (DEX_OFFSET.jump pc0 o) H r.\n      destruct (VarMap.get L.t (RT m sgn (DEX_OFFSET.jump pc0 o)) r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (DEX_OFFSET.jump pc0 o)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* PackedSwitch *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_PackedSwitch rt firstKey size l).\n      (* the case where the successor is the next instruction *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get l0 r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 (DEX_OFFSET.jump pc0 o) H r.\n      destruct (VarMap.get L.t (RT m sgn (DEX_OFFSET.jump pc0 o)) r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (DEX_OFFSET.jump pc0 o)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* the case where the successor is the targets *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get l0 r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.  \n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* SparseSwitch *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_SparseSwitch rt size l).\n      (* the case where the successor is the next instruction *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get l0 r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 (DEX_OFFSET.jump pc0 o) H r.\n      destruct (VarMap.get L.t (RT m sgn (DEX_OFFSET.jump pc0 o)) r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (DEX_OFFSET.jump pc0 o)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* the case where the successor is the targets *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get l0 r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.  \n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* Ifeq *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Ifcmp cmp ra rb o).\n      (* the case where the successor is the target *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 (DEX_OFFSET.jump pc0 o) H r.\n      destruct (VarMap.get L.t (RT m sgn (DEX_OFFSET.jump pc0 o)) r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (DEX_OFFSET.jump pc0 o)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* the case where the successor is the next instruction *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.  \n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* Ifz *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Ifz cmp r0 o).\n      (* the case where the successor is the target *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 (DEX_OFFSET.jump pc0 o) H r.\n      destruct (VarMap.get L.t (RT m sgn (DEX_OFFSET.jump pc0 o)) r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn (DEX_OFFSET.jump pc0 o)) in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* the case where the successor is the next instruction *)\n      split. unfold indist_reg_val. simpl. destruct (DEX_Registers.get regs r); auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* Ineg *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Ineg rt rs).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction. \n      (* Inot *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Inot rt rs).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* I2b *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_I2b rt rs).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.  \n      (* I2s *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_I2s rt rs).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.  \n      (* Ibinop *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_Ibinop op rt ra rb).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction.\n      (* IbinopConst *)\n      inversion Hexec. inversion_mine H2. inversion_mine H3; clear_other_ins (DEX_IbinopConst op rt r0 v).\n      split.\n      unfold indist_reg_val. simpl. rewrite DEX_Registers.get_update_old. destruct (DEX_Registers.get regs r); auto.\n      unfold Reg_eq in Hchanged_at; generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      (* the case where the registers is high *)\n      not_changed_same_onestep_aux1 m sgn HPM Hexec pc0 pc' H r.\n      destruct (VarMap.get L.t (RT m sgn pc') r) eqn:Hrt'.\n      apply sub_forall with (r:=r) (k1:=t) (k2:=t0) in Hsub; auto.\n      apply not_leql_trans with (k1:=t); auto.\n      split; auto. rewrite VarMap.get_update2; auto.\n      unfold Reg_eq in Hchanged_at. generalize (Neq_spec r rt); rewrite Hchanged_at; auto.\n      assert (VarMap.get L.t (RT m sgn pc0) r <> None) as Hget.\n      destruct (VarMap.get L.t (RT m sgn pc0) r). congruence.\n      inversion Hrt0. apply VarMap.get_some_in_dom in Hget.\n      try (  match goal with\n      | [ H:In r ?dom |- False] => apply RT_domain_same with (rt2:=RT m sgn pc') in H; \n        apply VarMap.in_dom_get_some in H; contradiction\n      end). \n      contradiction. \n      (* the case where there is no instruction *)\n      inversion Hexec. inversion_mine H2. apply False_ind. inversion_mine H3; \n      match goal with \n        | [H:instructionAt m ?pc0 = Some ?ins, Hins:instructionAt m ?pc = None |- _] =>\n          simpl in Hins; rewrite H in Hins; inversion Hins\n      end.  \n    Qed.\n\n    Lemma not_changed_inv1 : forall m i j r (Hpath: path m i j),\n      ~ changed m i j Hpath r -> ~changed_at m i r.\n    Proof.\n      intros. unfold not in *; intro Hgoal; apply H; constructor 1; auto.\n    Qed.\n\n    Lemma not_changed_inv2 : forall m i j k r (Hpath: path m k j) (e:exec m i (inl k)),\n      ~ changed m i j (path_step Method istate rstate exec m i j k Hpath e) r -> ~changed m k j Hpath r.\n    Proof.\n      intros. unfold not in *; intro Hgoal; apply H; constructor 2; auto.\n    Qed.\n\n    Lemma not_changed_same : forall m sgn i j (Hpath: path m i j) r (H: P (SM _ _ m sgn)) ,\n      ~changed m i j Hpath r -> \n      (indist_reg_val i j r) /\\ (high_reg (RT m sgn (pc i)) r -> high_reg (RT m sgn (pc j)) r). \n    Proof.\n      intros m sgn i j Hpath r H H0.\n      induction Hpath; intros.\n      (* base case *)\n      apply not_changed_inv1 in H0.\n      apply not_changed_same_onestep with (1:=H); auto. \n      (* induction step *)\n      assert (H0':=H0).\n      apply not_changed_inv2 in H0.\n      apply IHHpath in H0.\n      assert (~ changed m i j (path_step Method istate rstate exec m i j k Hpath e) r -> ~ changed_at m i r).\n      unfold not; intros. apply H1.\n      constructor 1. auto. apply H1 in H0'.\n      elim not_changed_same_onestep with (m:=m) (sgn:=sgn) (i:=i) (j:=k) (1:=H) (2:=H0') (3:=e); intros.\n      inversion H0.\n      split; auto.\n      unfold indist_reg_val in *.\n      destruct (DEX_Registers.get (snd i) r);\n      destruct (DEX_Registers.get (snd k) r);\n      destruct (DEX_Registers.get (snd j) r); try (congruence); try (contradiction). \n    Qed.\n\n    Lemma changed_high : forall m sgn s i j r (H:P (SM _ _ m sgn)) (Hpath: path m (* sgn (PM_P _ H) *) i j), \n      (forall k:PC, region (cdr m (PM_P _ H)) s (* kd *) k -> ~ L.leql (se m sgn k) kobs) ->\n      path_in_region m (cdr m (PM_P _ H)) s i j Hpath ->\n      region (cdr m (PM_P _ H)) s (pc i) ->\n      junc (cdr m (PM_P _ H)) s (pc j) ->\n      changed m i j Hpath r -> high_reg (RT m sgn (pc j)) r.\n    Proof.\n      intros.\n      induction Hpath.\n      (* base case *)\n      inversion_mine H4; apply changed_high_onestep with (s:=s) (i:=i) (H:=H); auto.\n\n      (* induction case *)\n      inversion H4.\n      (* the case where the change is happening at the current step *)\n      generalize changed_high_onestep; intros.\n      specialize H8 with (m:=m) (sgn:=sgn) (s:=s) (i:=i) (j:=k) (r:=r) (H:=H) (1:=H0) (2:=H2) (3:=e) (4:=H5).\n      elim (changed_dec m k j r Hpath); intros.\n      apply IHHpath; auto. inversion H1; auto.\n      assert ((existT (fun k : istate => path m k j) k p2) = (existT (fun k : istate => path m k j) k Hpath)).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H11); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      assert (p2 = Hpath).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H14); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      subst; auto.\n      inversion H1. inversion H13; auto.\n      apply not_changed_same with (sgn:=sgn) in H9; auto.\n      inversion H9; auto.\n      (* the case where the change is happening in the chain *)\n      assert ((existT (fun k : istate => path m k j) k p1) = (existT (fun k : istate => path m k j) k Hpath)).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H9); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      assert (p1 = Hpath).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H5); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      rewrite H11 in H10. inversion H1. \n      assert ((existT (fun k : istate => path m k j) k p2) = (existT (fun k : istate => path m k j) k Hpath)).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H13); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      assert (p2 = Hpath).\n      apply Coq.Logic.Eqdep_dec.inj_pair2_eq_dec with (2:=H16); auto.\n      intros x y; apply excluded_middleT with (P:=x=y).\n      apply IHHpath; subst; auto. inversion H15; auto. \n    Qed.\n\n    Lemma indist2_intra : forall m sgn se rt ut ut' s s' u u',\n      forall H0:P (SM _ _ m sgn),\n        indist sgn rt rt  s s' ->\n        pc s = pc s' ->\n        exec m s (inl _ u) ->\n        exec m s' (inl _ u') ->\n        texec m (PM_P _ H0) sgn se (pc s) rt (Some ut) ->\n        texec m (PM_P _ H0) sgn se (pc s) rt (Some ut') ->\n          indist sgn ut ut' u u'.\n    Proof.\n      unfold pc; intros m sgn se0 rt ut ut' s s' u u' H Hindist Hpc Hexec Hexec' Htexec Htexec'.\n      inversion_mine Hexec. inversion_mine Hexec'.\n  \n      elim DEX_BigStepWithTypes.exec_intra_instructionAt with (1:=H3); intros i Hi.\n      destruct Htexec as [i' [Ti Ti']]; DiscrimateEq.\n      \n      assert (DEX_BigStepWithTypes.NormalStep se0 (region (cdr m (PM_P {| unSign := m; sign := sgn |} H))) m sgn i s rt u ut).\n        elim well_types_imply_exec_intra with (1:=H3) (3:=Ti); eauto. \n      destruct Htexec' as [i' [Ui Ui']]; DiscrimateEq.\n      rewrite Hpc in Ui.\n      assert (DEX_BigStepWithTypes.NormalStep se0 (region (cdr m (PM_P {| unSign := m; sign := sgn |} H))) m sgn i s' rt u' ut').\n        elim well_types_imply_exec_intra with (1:=H4) (3:=Ui); eauto.\n      rewrite Hpc in Ui'; auto. \n      inversion_mine Hindist.\n      destruct u as [pu ru].\n      destruct u' as [pu' ru'].\n      constructor.\n      eapply indist2_intra; eauto. \n      constructor; eauto.\n      rewrite Hpc; constructor; eauto.\n      simpl. simpl in Hpc.\n      rewrite <- Hpc in H2; auto.\n    Qed.\n    \n    Lemma tcc3 : forall m rt1 rt2 s1 s2,\n      indist m rt1 rt2 s1 s2 -> indist m rt2 rt1 s2 s1.\n    Proof.\n      intros.\n      inversion_clear H; constructor.\n      apply st_in_sym; auto.\n    Qed.\n\n    Lemma indist_return_value_sym : forall sgn vu' vu,\n      indist_return_value kobs sgn vu' vu ->\n      indist_return_value kobs sgn vu vu'.\n    Proof.\n      intros.\n      inversion_clear H.\n      constructor 1 with k; auto; intros.\n      apply Value_in_sym; auto.\n      constructor; auto.\n    Qed.\n\n    Lemma indist2_return : forall (m : Method) (sgn : Sign) (se : PC -> L.t) \n      (rt : registertypes) (s s' : istate) (u u' : rstate) ,\n      forall H:P (SM Method Sign m sgn),\n        indist sgn rt rt s s' ->\n        pc s = pc s' ->\n        exec m s (inr istate u) ->\n        exec m s' (inr istate u') ->\n        texec m (PM_P _ H) sgn se (pc s) rt None ->\n        texec m (PM_P _ H) sgn se (pc s) rt None ->\n          rindist sgn u u'.\n    Proof.\n      unfold pc; intros m sgn se0 rt s s' u u' H Hindist Hpc Hexec Hexec' Htexec Htexec'.\n      destruct Htexec as [i' [Ti Ti']].\n      destruct Htexec' as [i [Ui Ui']]; DiscrimateEq.\n      destruct s as [pp regs].\n      destruct s' as [pp' regs'].\n      simpl in Hpc; subst; simpl in *.\n      destruct u as [vu].\n      destruct u' as [vu'].\n      inversion_mine Hindist;\n      inversion_mine Hexec; inversion_mine Hexec'.\n  (**)\n      assert (DEX_BigStepWithTypes.ReturnStep p se0 m sgn i (pp', regs) rt (Normal vu)).\n        elim well_types_imply_exec_return with (1:=H3) (3:=Ti); auto.\n      assert (DEX_BigStepWithTypes.ReturnStep p se0 m sgn i (pp', regs') rt (Normal vu')).\n        elim well_types_imply_exec_return with (1:=H5) (3:=Ui); auto.\n      apply DEX_BigStepWithTypes.exec_return_normal in H0.\n      apply DEX_BigStepWithTypes.exec_return_normal in H1.\n      constructor. \n      apply indist2_return with (1:=H0) (2:=H1) (3:=H4). \n    Qed.\n\n    Section well_formed_lookupswitch.\n\n      Variable hyp : forall m sgn, P (SM _ _ m sgn) -> well_formed_lookupswitch m.\n\n      Lemma soap2_basic_intra : forall m sgn se rt ut ut' s s' u u',\n        forall H0:P (SM _ _ m sgn),\n          indist sgn rt rt s s' -> \n          pc s = pc s' ->\n          exec m s (inl _ u) ->\n          exec m s' (inl _ u') -> \n          texec m (PM_P _ H0) sgn se (pc s) rt (Some ut) ->\n          texec m (PM_P _ H0) sgn se (pc s) rt (Some ut') ->\n          pc u <> pc u' -> \n          forall j:PC, region (cdr m (PM_P _ H0)) (pc s) j -> ~ L.leql (se j) kobs.\n      Proof.\n        intros m sgn se0 rt ut ut' s s' u u' H0 Hindist Hpcs Hexec Hexec' Htexec Htexec' Hpcu.\n        intros j Hreg.\n        destruct Htexec as [i' [Ti Ui]].\n        destruct Htexec' as [i [Ti' Ui']]. DiscrimateEq.\n        inversion_mine Hindist.\n        destruct u as [ppu regs].\n        destruct u' as [ppu' regs'].\n        inversion_mine Hexec'; inversion_mine Hexec; simpl in *; subst.\n  (**)\n        assert (DEX_BigStepWithTypes.NormalStep se0 (region (cdr m (PM_P {| unSign := m; sign := sgn |} H0))) \n          m sgn i (pc2,r1) rt (ppu,regs) ut).\n             elim well_types_imply_exec_intra with (1:=H5) (3:=Ti); auto.\n        assert (DEX_BigStepWithTypes.NormalStep se0 (region (cdr m (PM_P {| unSign := m; sign := sgn |} H0))) \n          m sgn i (pc2,r2) rt (ppu',regs') ut').\n             elim well_types_imply_exec_intra with (1:=H4) (3:=Ti'); auto.\n        apply DEX_BigStepWithTypes.exec_intra_normal in H1;\n        apply DEX_BigStepWithTypes.exec_intra_normal in H2.\n        apply soap2_intra with (5:=H2) (4:=H1) (7:= H); auto.\n        specialize hyp with (m:=m) (sgn:=sgn) (1:=H0); auto.\n      Qed.\n    End well_formed_lookupswitch.\n\n    Lemma Regs_in_sub_simple : forall rt rt0 s s0,\n      Regs_in kobs s0 s rt0 rt -> forall rt',\n        sub rt rt' -> \n        Regs_in kobs s0 s rt0 rt'.\n    Proof.\n      intros.\n      constructor 1; auto.\n      inversion H.\n      inversion H0; subst.\n      rewrite <- H1 in H3; auto. auto.\n      intros.\n      inversion H; inversion H0; subst.\n      (* *)\n      specialize H2 with rn. inversion H2.\n      (* case where both are high *)\n        assert_some_not_none rt rn H6.\n        apply VarMap.get_some_in_dom in H9. rewrite H3 in H9.\n        apply VarMap.in_dom_get_some in H9.\n        assert_not_none_some rt' rn k'' t.\n        destruct H10 as [k'']. \n        constructor 1 with (k:=k) (k':=k''); auto.\n        symmetry in H6.\n        specialize H4 with (r:=rn) (1:=H6) (2:=H10).\n        apply not_leql_trans with (k1:=k'); auto.\n      (* case where both are low *)\n      constructor 2; auto.\n      auto.\n    Qed.\n\n    Lemma sub_simple : forall sgn rt rt' rt0 s s0,\n      indist sgn rt0 rt s0 s ->\n      sub rt rt' ->\n      indist sgn rt0 rt' s0 s.\n    Proof.\n      intros.\n      inversion_mine H; inversion_mine H1; constructor.\n      constructor. eapply Regs_in_sub_simple; eauto.\n    Qed.\n\n    Lemma branch_indist : forall m sgn s s' u u' (H0:P (SM _ _ m sgn)), \n      pc s = pc s' ->\n      indist sgn (RT m sgn (pc s)) (RT m sgn (pc s')) s s' ->\n      exec m s (inl u) ->\n      exec m s' (inl u') ->\n      pc u <> pc u' ->\n      indist sgn (RT m sgn (pc u)) (RT m sgn (pc u')) u u'.\n    Proof.\n      intros m sgn s s' u u' HPM Hpc Hindist Hexec Hexec' Hpc'.\n      rewrite <- Hpc in Hindist.\n      destruct (typable_hyp m sgn HPM) as [T1 [T2 T3]].\n      assert (e:=Hexec). apply tcc0 with (1:=PM_P _ HPM) in e.\n      assert (e':=Hexec'). apply tcc0 with (1:=PM_P _ HPM) in e'.\n      assert (T3':=T3).\n      specialize T3 with (i:=pc s) (j:=pc u) (1:=e).\n        destruct T3 as [ut [Htexec Hsub]].\n      specialize T3' with (i:=pc s') (j:=pc u') (1:=e').\n        destruct T3' as [ut' [Htexec' Hsub']].\n      apply sub_simple with (2:=Hsub'). apply tcc3.\n      apply sub_simple with (2:=Hsub). apply tcc3.\n      apply indist2_intra with (m:=m) (se:=se m sgn) (rt:=(RT m sgn (pc s))) (s:=s) (s':=s') (H0:=HPM)\n        (ut:=ut) (ut':=ut'); auto.\n      rewrite Hpc; auto.\n    Qed.\n\n  End TypableProg.\n\nEnd hyps. \n\nRequire check_cdr.\nModule MapKind' := MapOption_Base Map2P.\n  Module MapKind <: MAP with Definition key := Kind := Map_Of_MapBase MapKind'.\n  Module CheckCdr := check_cdr.Make MapN.\n\n  Fixpoint map_from_list (l:list PC) : MapN.t bool :=\n    match l with\n      | nil => MapN.empty _\n      | cons i l => MapN.update _ (map_from_list l) i true\n    end.\n\n  Definition upd_reg : \n    PC -> list PC -> MapN.t (MapN.t bool) -> MapN.t (MapN.t bool) :=\n    fun i l reg =>\n      MapN.update _ reg (i) (map_from_list l).\n\n  Definition empty_reg : MapN.t (MapN.t bool) := MapN.empty _.\n\n  Definition upd_jun : \n    PC -> PC -> MapN.t CheckCdr.PC -> MapN.t CheckCdr.PC :=\n    fun i j jun =>     MapN.update _ jun (i) j.\n\n  Definition empty_jun : MapN.t (CheckCdr.PC) := MapN.empty _.\n\n\n  Section check.\n    Variable p : DEX_Program.\n    Variable m : DEX_Method.\n    Definition for_all_steps : (PC -> option PC -> bool) -> bool :=\n      fun test => for_all_steps_m m (fun pc i => test pc).\n    Definition test_all_steps : (PC -> option PC -> bool) -> list (PC*bool) :=\n      fun test => test_all_steps_m m (fun pc i => test pc).\n\n    Lemma for_all_steps_true : forall test,\n      for_all_steps test = true ->\n      forall (i : PC) (oj : option PC),\n        step p m i oj -> test i oj = true.\n    Proof.\n      intros.\n      destruct H0 as [T0 [ins [T1 T2]]].\n      eapply (for_all_steps_m_true m (fun p i => test p)); eauto.\n    Qed.\n\n    Definition for_all_succs : PC -> (option PC -> bool) -> bool :=\n      for_all_succs_m m.\n\n    Lemma for_all_succs_true : forall i test,\n      for_all_succs i test = true ->\n      forall oj, step p m i oj -> test oj = true.\n    Proof.\n      intros.\n      destruct H0 as [T0 [ins [T1 T2]]].\n      eapply (for_all_succs_m_true m); eauto.\n    Qed.\n\n    Definition check_cdr : forall\n      (reg : MapN.t (MapN.t bool))\n      (jun : MapN.t (CheckCdr.PC)), bool :=\n      fun reg jun => CheckCdr.check_soaps for_all_steps for_all_succs reg jun.\n\n    Definition check_cdr' \n      (reg : MapN.t (MapN.t bool))\n      (jun : MapN.t (CheckCdr.PC)) :=\n      CheckCdr.check_soaps' for_all_steps for_all_succs reg jun.\n\n    Definition check_soap1' \n      (reg : MapN.t (MapN.t bool))\n      (jun : MapN.t (CheckCdr.PC)) :=\n      CheckCdr.check_soap1' for_all_steps test_all_steps reg jun.\n\n    Definition test_soap2\n      (reg : MapN.t (MapN.t bool))\n      (jun : MapN.t (CheckCdr.PC)) :=\n      CheckCdr.test_soap2 for_all_succs reg jun.\n\n    Lemma check_cdr_prop : forall \n      (reg : MapN.t (MapN.t bool))\n      (jun : MapN.t (CheckCdr.PC)),\n      check_cdr reg jun = true ->\n      { cdr : CDR (step p m) |\n        forall i j,\n          region cdr i j -> CheckCdr.region reg i j}.\n    Proof\n    (CheckCdr.check_soap_true (step p m) for_all_steps\n      for_all_steps_true\n      for_all_succs for_all_succs_true).\n\n  End check.\n\n\n  Section CDR_dummy.\n\n    Variable PC: Set.\n    Variable step : PC -> option PC -> Prop.\n\n    Definition dummy_cdr : CDR step.\n    refine (make_CDR step (fun _ _ => True) (fun _ _ => False) _ _ _ _); auto.\n    intuition.\n  Qed.\n\nEnd CDR_dummy.\n\nSection CheckTypable.\n\n  Variable p : DEX_ExtendedProgram.\n  Variable se : DEX_Method -> DEX_sign -> PC -> L.t.\n  Variable RT :  DEX_Method -> DEX_sign -> PC -> VarMap.t L.t.\n  Variable reg : Method -> MapN.t (MapN.t bool).\n  Variable jun : Method -> MapN.t (CheckCdr.PC).\n  Variable cdr_checked : forall m,\n    PM p m ->  check_cdr m (reg m) (jun m) = true.\n\n  Definition cdr_local : forall m, \n    PM p m -> CDR (step p m) :=\n    fun m H => let (cdr_local,_) := \n      check_cdr_prop p m (reg m) (jun m)\n      (cdr_checked m H) in cdr_local.\n\n  Lemma cdr_prop : forall m (h:PM p m),\n    forall i j,\n      region (cdr_local m h) i j -> CheckCdr.region (reg m) i j.\n  Proof.\n    intros m h; unfold cdr_local.\n    destruct check_cdr_prop.\n    auto.\n  Qed.\n\n  Definition for_all_region : Method -> PC -> (PC->bool) -> bool :=\n    fun m => CheckCdr.for_all_region2 (reg m).\n\n  Lemma for_all_region_correct : forall m i test,\n    for_all_region m i test = true ->\n    forall j, CheckCdr.region (reg m) i j -> test j = true.\n  Proof.\n    unfold for_all_region; intros.\n    eapply CheckCdr.for_all_region2_true; eauto.\n  Qed.\n\n   Definition selift m sgn i k :=\n    for_all_region m i (fun j => L.leql_t k (se m sgn j)). \n\n  Fixpoint check_rt0_rec rt sgn p valid_reg default {struct valid_reg}: bool :=\n    match valid_reg with \n    | h :: t => \n        (if In_test h p then\n          match VarMap.get _ rt h with\n          | None => false\n          | Some k => (L.eq_t k (DEX_lvt sgn h))\n          end\n        else\n          match VarMap.get _ rt h with\n          | None => false\n          | Some k => (L.eq_t k default) \n        end)\n        && check_rt0_rec rt sgn p t default\n    | nil => true\n    end.\n\n   Definition check_rt0 m sgn : bool :=\n    match DEX_METHOD.body m with\n      | None => false\n      | Some bm => let rt := RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm) in\n                     eq_set_test (VarMap.dom L.t rt) (DEX_BYTECODEMETHOD.regs bm) &&\n                     check_rt0_rec rt sgn (DEX_BYTECODEMETHOD.locR bm) (DEX_BYTECODEMETHOD.regs bm) (default_level)\n    end.\n\n  Lemma check_rt0_rec_true : forall m sgn bm default_level,\n    check_rt0_rec (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) sgn \n      (DEX_BYTECODEMETHOD.locR bm) (DEX_BYTECODEMETHOD.regs bm) default_level = true ->\n    DEX_METHOD.body m = Some bm -> \n    (forall r, In r (DEX_BYTECODEMETHOD.regs bm) ->\n    (forall k, In r (DEX_BYTECODEMETHOD.locR bm) -> Some k = VarMap.get _ (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) r -> k = (DEX_lvt sgn r)) /\\\n    (~In r (DEX_BYTECODEMETHOD.locR bm) -> Some (default_level) = VarMap.get _ (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) r)).\n  Proof.\n    intros. \n    split; intros.\n    (* case where the register is in the domain *)\n      induction (DEX_BYTECODEMETHOD.regs bm). inversion H1.\n      unfold check_rt0_rec in H. \n      assert ((if In_test a (DEX_BYTECODEMETHOD.locR bm) then\n      match VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a with\n      | Some k =>\n          L.eq_t k (DEX_lvt sgn a) \n      | None => false\n      end\n     else\n      match VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a with\n      | Some k =>\n          L.eq_t k default_level0 \n      | None => false\n      end) &&\n      check_rt0_rec (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) sgn (DEX_BYTECODEMETHOD.locR bm) l default_level0\n        = true). auto. clear H.\n      inversion H1.\n      subst.\n      apply In_In_test in H2; rewrite H2 in H4.\n      rewrite <- H3 in H4. flatten_bool.\n      generalize (L.eq_t_spec k (DEX_lvt sgn r)); intros Heq; rewrite H in Heq; auto.\n      destruct (In_test a (DEX_BYTECODEMETHOD.locR bm)).\n      destruct (VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a). \n      flatten_bool. apply IHl; subst; auto.\n      inversion H4. \n      destruct (VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a). \n      flatten_bool; apply IHl; subst; auto.\n      inversion H4. \n    (* case where the register is not in the domain *)\n    induction (DEX_BYTECODEMETHOD.regs bm). inversion H1.\n    assert ((if In_test a (DEX_BYTECODEMETHOD.locR bm)\n     then\n      match VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a with\n      | Some k =>\n          L.eq_t k (DEX_lvt sgn a) \n      | None => false\n      end\n     else\n      match VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) a with\n      | Some k =>\n          L.eq_t k default_level0\n      | None => false\n      end) &&\n      check_rt0_rec (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) sgn (DEX_BYTECODEMETHOD.locR bm) l default_level0 = true). auto.\n    clear H.\n    inversion H1.\n    apply not_In_In_test in H2.\n    rewrite <- H in H2; rewrite H2 in H3. subst.\n    destruct (VarMap.get L.t (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) r).\n    flatten_bool; auto.\n    generalize (L.eq_t_spec t default_level0); intros Heq; rewrite H in Heq; rewrite Heq; auto.\n    inversion H3.\n    (* induction case *)\n    flatten_bool. apply IHl; subst; auto.\n  Qed.\n\n  Lemma check_rt0_true : forall m sgn bm, check_rt0 m sgn = true ->\n    DEX_METHOD.body m = Some bm ->\n    (forall r, In r (DEX_BYTECODEMETHOD.regs bm) ->\n    (forall k, In r (DEX_BYTECODEMETHOD.locR bm) -> Some k = VarMap.get _ (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) r -> k = (DEX_lvt sgn r)) /\\\n    (~In r (DEX_BYTECODEMETHOD.locR bm) -> Some (default_level) = VarMap.get _ (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) r)).\n  Proof.\n    intros. unfold check_rt0 in H.\n    rewrite H0 in H. flatten_bool. apply check_rt0_rec_true; auto.  \n  Qed.\n\n  Definition check : bool := for_all_P p\n    (fun m sgn =>\n      (check_rt0 m sgn) &&\n      for_all_steps_m m\n      (fun i ins oj => \n        DEX_tcheck m sgn (se m sgn) (selift m sgn) (RT m sgn) i ins)\n    ).\n\n  Lemma PC_eq_dec' : forall x y : PC, {x=y} + {x<>y}.\n   Proof.\n    repeat decide equality.\n   Qed.\n\n  Lemma check_correct1_aux : forall m bm sgn, DEX_METHOD.body m = Some bm -> check_rt0 m sgn = true ->\n    eq_rt (RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) \n      (make_rt_from_lvt_rec sgn (DEX_BYTECODEMETHOD.locR bm) (DEX_BYTECODEMETHOD.regs bm) default_level).\n  Proof.\n    constructor.\n      unfold check_rt0 in H0; rewrite H in H0.\n      flatten_bool.\n      apply eq_set_test_prop in H1; auto.\n      generalize make_rt_from_lvt_prop3; intros.\n      specialize H0 with (s:=sgn) (p:=DEX_BYTECODEMETHOD.locR bm) (v:=DEX_BYTECODEMETHOD.regs bm) (d:=default_level)\n        (1:=DEX_BYTECODEMETHOD.noDup_regs bm).\n      rewrite H1. rewrite H0. reflexivity.\n    intros.\n    destruct (in_dec PC_eq_dec' r (DEX_BYTECODEMETHOD.regs bm)).\n    apply check_rt0_true with (bm:=bm) (r:=r) in H0; auto.\n    inversion_mine H0. \n    destruct (in_dec PC_eq_dec' r (DEX_BYTECODEMETHOD.locR bm)).\n    assert (i0':=i0).\n    apply H5 with (k:=k1) in i0; auto. \n    apply make_rt_from_lvt_prop1 with (k:=k2) (s:=sgn) (v:=DEX_BYTECODEMETHOD.regs bm) (p:=DEX_BYTECODEMETHOD.locR bm) (d:=default_level) in i0'; congruence.\n    assert (n':=n).\n    apply H6 in n; auto. rewrite <- n in H3; inversion H3; subst.\n    apply make_rt_from_lvt_prop2 with (s:=sgn) (v:=DEX_BYTECODEMETHOD.regs bm) (p:=DEX_BYTECODEMETHOD.locR bm) (d:=default_level) in n'; auto.\n    rewrite <- n' in H4; auto. congruence.\n    apply valid_regs_prop with (m:=m) (rt:=RT m sgn (DEX_BYTECODEMETHOD.firstAddress bm)) in n; auto.\n    rewrite n in H3; inversion H3.\n  Qed.\n\n  Lemma check_correct1 : check = true ->\n    forall m sgn, P p (SM _ _ m sgn) ->\n      forall i, init_pc m i -> eq_rt (RT m sgn i) (rt0 m sgn).\n  Proof.\n    unfold check; intros.\n    inversion_mine H1.\n    assert (T:=for_all_P_true _ _ H _ _ H0).\n    destruct (andb_prop _ _ T) as [TT _].\n    unfold rt0. rewrite H2.\n    apply check_correct1_aux with (m:=m) (bm:=bm) (sgn:=sgn); auto.\n  Qed.\n\n  Lemma check_correct2 : check = true ->\n    forall m sgn (h:P p (SM _ _ m sgn)),\n      forall i,\n        step p m i None ->\n        texec p cdr_local m (PM_P _ _ h) sgn (se m sgn) i (RT m sgn i) None.\n  Proof.\n    unfold check; intros.\n    assert (T:=for_all_P_true _ _ H _ _ h).\n    destruct (andb_prop _ _ T) as [_ TT].\n    destruct H0 as [H0 [ins [H2 H3]]].\n    exists ins; split; [idtac|assumption].\n    assert (T':=for_all_steps_m_true _ _ TT _ _ _ H2 H3).\n    apply tcheck_correct1 with (selift:=selift m sgn) (m:=m); auto.\n  Qed.\n\n  Lemma tsub_sub : forall rt1 rt2,\n    tsub_rt rt1 rt2 = true -> sub rt1 rt2.\n  Proof.\n    intros.\n    unfold tsub_rt in H. destruct (andb_prop _ _ H).\n    apply eq_set_test_prop in H0. \n    constructor; auto.\n    intros.\n    apply tsub_rec_leq with (r:=r) (k1:=k1) (k2:=k2) in H1; auto.\n    assert (VarMap.get L.t rt2 r <> None). unfold not; intros. \n      rewrite H4 in H3; inversion H3.\n    apply VarMap.get_some_in_dom in H4; auto.\n  Qed.\n\n  Lemma check_correct3 : check = true ->\n    forall m sgn (h:P p (SM _ _ m sgn)),\n      forall i j,\n        step p m i (Some j) ->\n        exists rt,\n          texec p cdr_local m (PM_P _ _ h) sgn (se m sgn) i (RT m sgn i) (Some rt) \n          /\\ sub rt (RT m sgn j).\n  Proof.\n    unfold check; intros.\n    assert (T:=for_all_P_true _ _ H _ _ h).\n    destruct (andb_prop _ _ T) as [_ TT].\n    destruct H0 as [H0 [ins [H2 H3]]].\n    assert (T':=for_all_steps_m_true _ _ TT _ _ _ H2 H3).\n    elim (tcheck_correct2 m sgn (region (cdr_local _ (PM_P _ _ h)))  (se m sgn)\n      (selift m sgn) (RT m sgn)) with (2:=T') (3:=H3).\n    intros rt [T1 T2].\n    exists rt; split.\n    exists ins; split; auto.\n    apply tsub_sub; auto.\n    unfold selift; intros.\n    assert (T2:=for_all_region_correct _ _ _ H1 _ (cdr_prop _ _ _ _ H4)).\n    generalize (L.leql_t_spec k (se m sgn j0)).\n    rewrite T2; auto.\n  Qed.\n\n  Lemma check_correct : \n    check = true ->\n    TypableProg p cdr_local se RT.\n  Proof.\n    intros H m sgn H1.\n    constructor.\n    apply check_correct1; auto.\n    split.\n    apply check_correct2; auto.\n    apply check_correct3; auto.\n  Qed.\n\nEnd CheckTypable.\n\nTheorem ni_safe : forall (kobs:L.t) (p:DEX_ExtendedProgram),\n  forall cdr : forall m, PM p m -> CDR (step p m),\n    (exists se, exists RT, TypableProg p cdr se RT) ->\n    (forall m sgn, P p (SM _ _ m sgn) -> well_formed_lookupswitch m) ->\n    forall m sgn i r1 r2 res1 res2,\n      P p (SM _ _ m sgn) ->\n      init_pc m i -> \n      indist kobs sgn (rt0 m sgn) (rt0 m sgn) (i, r1) (i, r2) ->\n      evalsto p m (i,r1) (res1) -> \n      evalsto p m (i,r2) (res2) -> \n        indist_return_value kobs sgn res1 res2.\nProof.\n  intros kobs p cdr [se [RT HT]] Hwfl m sgn i r1 r2 res1 res2 H Hinit Hindist Hevalsto1 Hevalsto2.\n  assert (Hni:=safe_ni kobs PC Method (step p) (PM p) cdr Reg Sign istate rstate (exec p) pc \n    (tcc0 p) (tcc1 p) registertypes (texec p cdr) (high_reg kobs)\n    (indist_reg_val) (indist_reg_val_trans) (indist_reg_val_sym)\n    (indist kobs) (indist_from_reg kobs) (indist_reg_from_indist kobs)\n    (rindist kobs) (tcc3 kobs) (high_result kobs) (rt0) (init_pc)\n    (P p) (PM_P p) (indist2_intra kobs p cdr) (indist2_return kobs p cdr)\n    (soap2_basic_intra kobs p cdr Hwfl) (sub) (sub_simple kobs)\n    (tevalsto_high_result kobs p cdr ) (tevalsto_diff_high_result' kobs p cdr ) (high_result_indist kobs)\n    (eq_rt) (indist_morphism_proof kobs) se RT HT (changed p) (changed_high kobs p cdr se RT HT)\n    (not_changed_same kobs p cdr se RT HT) (high_reg_dec kobs) (changed_dec p) (branch_indist kobs p cdr se RT HT)\n    m sgn\n  ). \n  elim evalsto_Tevalsto with (1:=Hevalsto1); intros p1 He1.\n  elim evalsto_Tevalsto with (1:=Hevalsto2); intros p2 He2.\n  elim Hni with (6:=He1) (7:=He2); auto.\nQed.\n\nDefinition check_all_cdr \n  (p:DEX_Program)\n  (reg : Method -> MapN.t (MapN.t bool))\n  (jun : Method -> MapN.t (CheckCdr.PC)) : bool :=\n  for_all_methods p (fun m => check_cdr m (reg m) (jun m)).\n\nLemma check_all_cdr_correct : forall p reg jun,\n  check_all_cdr p reg jun = true ->\n  forall m, PM p m -> check_cdr m (reg m) (jun m) = true.\nProof.\n  unfold check_all_cdr; intros.\n  apply (for_all_methods_true p (fun m => check_cdr m (reg m) (jun m))); auto.\nQed.\n\nLemma IntraStep_evalsto_aux : forall p m s r,\n  DEX_BigStepAnnot.DEX_IntraStepStar p.(DEX_prog) m s r ->\n  match r with\n    | inl _ => True\n    | inr r => evalsto p m s r\n  end.\nProof.\n  intros p; apply DEX_BigStepAnnot.DEX_IntraStepStar_ind; intros; auto.\n  constructor 1.\n  constructor 2; auto.\n  destruct r; auto.\n  constructor 2 with (s2:=s'); auto.\n  constructor; auto.\nQed.\n\nLemma BigStep_evalsto : forall p m s r,\n  DEX_BigStepAnnot.DEX_BigStep p.(DEX_prog) m s r ->\n  evalsto p m s r.\nProof.\n  intros.\n  apply IntraStep_evalsto_aux with (1:=H).\nQed.\n\nSection well_formed_lookupswitch.\n\n  Fixpoint check_not_in_snd (i:Z) (o:DEX_OFFSET.t) (l:list (Z*DEX_OFFSET.t)) {struct l} : bool :=\n    match l with\n      | nil => true\n      | (j,o')::l => \n        if Zeq_bool i j \n          then (Zeq_bool o o') && check_not_in_snd i o l\n          else check_not_in_snd i o l\n    end.\n  \n  Lemma check_not_in_snd_correct : forall i o l,\n    check_not_in_snd i o l = true ->\n    forall o', In (i,o') l -> o=o'.\n  Proof.\n    induction l; simpl; intuition.\n    subst.\n    generalize (Zeq_spec i i); destruct (Zeq_bool i i).\n    elim andb_prop with (1:=H); intros.\n    generalize (Zeq_spec o o'); rewrite H0; auto.\n    intuition.\n    apply IHl; auto.\n    destruct a.\n    destruct (Zeq_bool i z); auto.\n    elim andb_prop with (1:=H); auto.\n  Qed.\n\n  Fixpoint check_functionnal_list (l:list (Z*DEX_OFFSET.t)) : bool :=\n    match l with\n      | nil => true\n      | (i,o)::l => (check_not_in_snd i o l) && check_functionnal_list l\n    end.\n\n  Lemma check_functionnal_list_correct : forall l,\n    check_functionnal_list l = true ->\n    forall i o1 o2,\n      In (i, o1) l -> In (i, o2) l -> o1=o2.\n  Proof.\n    induction l; simpl; intuition.\n    congruence.\n    subst.\n    elim andb_prop with (1:=H); clear H; intros.\n    eapply check_not_in_snd_correct; eauto.\n    subst.\n    elim andb_prop with (1:=H); clear H; intros.\n    apply sym_eq; eapply check_not_in_snd_correct; eauto.\n    destruct a.\n    elim andb_prop with (1:=H); clear H; intros.\n    eauto.\n  Qed.\n\n  Definition check_well_formed_lookupswitch_m m := \n    for_all_instrs_m m \n    (fun i ins => match ins with \n                    | DEX_SparseSwitch reg size l => check_functionnal_list l\n                    | _ => true\n                  end).\n\n  Definition check_well_formed_lookupswitch_m_correct : forall m,\n    check_well_formed_lookupswitch_m m = true ->\n    forall pc reg size l i o1 o2,\n      instructionAt m pc = Some (DEX_SparseSwitch reg size l) ->\n      In (i, o1) l -> In (i, o2) l -> o1=o2.\n  Proof.\n    unfold check_well_formed_lookupswitch_m; intros.\n    generalize (for_all_instrs_m_true _ _ H).\n    intros.\n    generalize (H3 pc0 (DEX_SparseSwitch reg size l)); rewrite H0.\n    intros T.\n    assert (TT:=T (refl_equal _)).\n    clear T H3 H.\n    eapply check_functionnal_list_correct; eauto.\n  Qed.\n\n  Definition check_well_formed_lookupswitch p :=\n    for_all_methods p check_well_formed_lookupswitch_m.\n\n  Lemma check_well_formed_lookupswitch_correct : forall (p:DEX_ExtendedProgram),\n    check_well_formed_lookupswitch p = true ->\n    forall m sgn,\n      P p (SM _ _ m sgn) -> well_formed_lookupswitch m.\n  Proof.\n    unfold check_well_formed_lookupswitch; intros.\n    unfold well_formed_lookupswitch.\n    intros.\n    eapply (check_well_formed_lookupswitch_m_correct m); try eauto.\n    apply (for_all_methods_true _ _ H).\n    inversion_mine H0; auto.\n  Qed.\n\nEnd  well_formed_lookupswitch.\n\nTheorem correctness : forall\n  (p:DEX_ExtendedProgram),\n  check_well_formed_lookupswitch p = true ->\n  forall (kobs:L.t)\n    (reg : Method -> MapN.t (MapN.t bool))\n    (jun : Method -> MapN.t (CheckCdr.PC)),\n    check_all_cdr p reg jun = true ->\n    forall \n      (se : Method -> DEX_sign -> PC -> L.t) \n      (RT :  Method -> DEX_sign -> PC -> VarMap.t L.t),\n      check p se RT reg = true ->\n      forall m sgn i res1 res2 r1 r2,\n        P p (SM _ _ m sgn) ->\n        init_pc m i -> \n        indist kobs sgn (rt0 m sgn) (rt0 m sgn) (i, r1) (i, r2) ->\n        evalsto p m (i,r1) res1 -> \n        evalsto p m (i,r2) res2 -> \n\n          indist_return_value kobs sgn res1 res2.\nProof.\n  intros p Hwfl kobs reg jun Hcheck se RT.\n  intros Hc.\n  intros m sgn i res1 res2 r1 r2 H H0 H1 H2.\n  assert (T:=check_all_cdr_correct p (reg) (jun) Hcheck).\n  assert (TT:=check_correct _ _ _ _ jun T Hc).\n  eapply ni_safe; eauto.\n  apply check_well_formed_lookupswitch_correct; auto.\nQed.\n\nDefinition m_reg_empty := DEX_MapShortMethSign.empty (MapN.t (MapN.t bool)).\n\nDefinition m_reg_add (m:Method) (reg:(MapN.t (MapN.t bool))) map :=\n  DEX_MapShortMethSign.update _ map m.(DEX_METHOD.signature) reg.\n\nDefinition m_reg_get map : Method -> MapN.t (MapN.t bool) :=\n  fun m =>   \n    match DEX_MapShortMethSign.get _ map m.(DEX_METHOD.signature) with\n      | None => empty_reg\n      | Some r => r\n    end.\n\nDefinition m_jun_empty := DEX_MapShortMethSign.empty (MapN.t (CheckCdr.PC)).\n\nDefinition m_jun_add (m:Method) (jun:(MapN.t (CheckCdr.PC))) map :=\n  DEX_MapShortMethSign.update _ map m.(DEX_METHOD.signature) jun.\n\nDefinition m_jun_get map : DEX_Method -> MapN.t (CheckCdr.PC) :=\n  fun m =>   \n    match DEX_MapShortMethSign.get _ map m.(DEX_METHOD.signature) with\n      | None => empty_jun\n      | Some r => r\n    end.\n\nDefinition se_empty := MapN.empty L.t.\nDefinition se_add (i:PC) (l:L.t) se := MapN.update _ se i l.\n\nDefinition m_se_empty := DEX_MapShortMethSign.empty (MapN.t L.t).\nDefinition m_se_add (m:Method) (se:MapN.t L.t) m_se :=\n  DEX_MapShortMethSign.update _ m_se m.(DEX_METHOD.signature) se.\nDefinition se_get se : PC -> L.t := fun i =>\n  match MapN.get _ se i with\n    | None => L.bot\n    | Some l => l\n  end.\nDefinition m_se_get map : Method -> DEX_sign -> PC -> L.t :=\n  fun m sgn => match DEX_MapShortMethSign.get _ map m.(DEX_METHOD.signature) with\n                 | None => fun _ => L.bot\n                 | Some m => fun i => se_get m i\n               end.\n\nDefinition RT_empty := MapN.empty (VarMap.t L.t).\nDefinition RT_add (i:PC) (rt:VarMap.t L.t) RT := MapN.update _ RT i rt.\n\nDefinition m_RT_empty := DEX_MapShortMethSign.empty (MapN.t (VarMap.t L.t)).\nDefinition m_RT_add (m:Method) (RT:MapN.t (VarMap.t L.t)) m_RT :=\n  DEX_MapShortMethSign.update _ m_RT m.(DEX_METHOD.signature) RT.\nDefinition RT_get RT : PC -> (VarMap.t L.t) := fun i =>\n  match MapN.get _ RT i with\n    | None => VarMap.empty L.t\n    | Some rt => rt\n  end.\nDefinition m_RT_get map : Method -> DEX_sign -> PC -> (VarMap.t L.t) :=\n  fun m sgn => match DEX_MapShortMethSign.get _ map m.(DEX_METHOD.signature) with\n                 | None => fun _ => VarMap.empty L.t\n                 | Some m => RT_get m\n               end.\n\nDefinition ms_eq : DEX_ShortMethodSignature -> DEX_ShortMethodSignature -> bool := DEX_METHODSIGNATURE.eq_t.\n\nDefinition selift_m reg se i k :=\n  CheckCdr.for_all_region2 reg i (fun j => L.leql_t k (se_get se j)).\n\nDefinition check_m (p:DEX_ExtendedProgram) m sgn reg se RT i : bool :=\n  match instructionAt m i with\n    | None => false\n    | Some ins =>\n      DEX_tcheck m sgn (se_get se) (selift_m reg se) (RT_get RT) i ins\n  end.\n\nDefinition check_ni (p:DEX_ExtendedProgram) reg jun se RT : bool :=\n      check_well_formed_lookupswitch p &&\n      check_all_cdr p reg jun &&\n      check p se RT reg.\n\nDefinition NI (p:DEX_ExtendedProgram) : Prop :=\n  forall kobs m sgn i r1 r2 res1 res2,\n    P p (SM _ _ m sgn) ->\n    init_pc m i -> \n    indist kobs sgn (rt0 m sgn) (rt0 m sgn) (i,r1) (i,r2) ->\n    DEX_BigStepAnnot.DEX_BigStep p.(DEX_prog) m (i,r1) (res1) -> \n    DEX_BigStepAnnot.DEX_BigStep p.(DEX_prog) m (i,r2) (res2) -> \n      indist_return_value kobs sgn res1 res2.\n\nTheorem check_ni_correct : forall p reg jun se RT,\n  check_ni p reg jun se RT = true ->\n  NI p.\nProof.\n  unfold check_ni, NI. intros p reg jun se RT HcheckTypable kobs m sgn i r1 r2 res1 res2\n    HPM Hinit Hindist Hstep1 Hstep2.\n  destruct (andb_prop _ _ HcheckTypable) as [HcheckTypable' Hcheck].\n  destruct (andb_prop _ _ HcheckTypable') as [Hwfl Hcheck_all_cdr].\n  generalize (BigStep_evalsto _ _ _ _ Hstep1). \n  generalize (BigStep_evalsto _ _ _ _ Hstep2). \n  intros Hevalsto2 Hevalsto1.\n  assert (T:=for_all_P_true _ _ Hcheck _ _ HPM).\n  destruct (andb_prop _ _ T).\n  eapply correctness with (8:=Hevalsto2) (7:=Hevalsto1); eauto.\nQed.", "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_Final (Backup).v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.16119282042023364}}
{"text": "Require Import Bool.\nRequire Import ZArith.\nRequire Import BinPos.\n\nRequire Import Axioms.\n\nRequire Import VST.concurrency.compcert_imports. Import CompcertCommon.\n\nRequire Import VST.concurrency.sepcomp. Import SepComp.\nRequire Import VST.sepcomp.arguments.\n\nRequire Import VST.concurrency.rc_semantics.\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun seq fintype.\nSet Implicit Arguments.\n\nImport SM_simulation.\n\nSection rc_2lems.\n\nVariables F_S V_S F_T V_T : Type.\n\nVariables C D : Type.\n\nVariable eff_S : @EffectSem (Genv.t F_S V_S) C.\n\nVariable eff_T : @EffectSem (Genv.t F_T V_T) D.\n\nVariable ge_S : Genv.t F_S V_S.\n\nVariable ge_T : Genv.t F_T V_T.\n\nVariable sim : SM_simulation_inject eff_S eff_T ge_S ge_T.\n\nLemma rc_sim :\n  SM_simulation_inject (RC.effsem eff_S) eff_T ge_S ge_T.\nProof.\ncase: sim=> cd mtch ord e f g genv_infos h i j init step halt atext aftext.\neapply Build_SM_simulation_inject with\n       (core_data   := cd)\n       (core_ord    := ord)\n       (match_state :=\n         fun cd mu c m d tm =>\n           mtch cd mu (RC.core c) m d tm); eauto.\n{ move=> v vals1 c1 m1 j0 vals2 m2 dS dT.\nmove=> init1 inj vinj pres pres2 H I resp1 resp2 J K.\nhave [c1' init1']:\n  exists c1', initial_core eff_S 0 ge_S v vals1 = Some c1'.\n{ move: init1; rewrite /= /RC.initial_core.\n  case x: (initial_core _ _ _ _)=> //.\n  by case; case: c1=> c ?; case=> -> _; exists c. }\nmove: (init v vals1 c1' m1 j0 vals2 m2 dS dT init1').\ncase/(_ inj vinj pres pres2 H I resp1 resp2 J K)=> x []c2' []init2' mtch12.\nexists x,c2'; split=> //.\nmove: init1; rewrite /= /RC.initial_core; rewrite init1'; case.\nby case: c1=> ? ?; case=> <- <- /=. }\n{ move=> st1 m1 st1' m1' U1 estep cd0 st2 mu m2 mtch12.\nmove: estep; rewrite /= /RC.effstep=> [][]estep []ctnd' locs.\nmove: (step (RC.core st1) m1 (RC.core st1') m1' U1 estep cd0).\ncase/(_ st2 mu m2 mtch12)=> st2' []m2' []cd' []mu'.\ncase=> incr (*[]sep*) []localloc []mtch12' []U2 []estep' trackback.\nexists st2',m2',cd',mu'=> /=.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nby exists estep'.\n(*by exists U2.*) }\n{ move=> cd0 mu c1 m1 c2 m2 v1 M; rewrite /= /RC.halted.\n  case hlt1: (halted _ _)=> //.\n  case def1: (vals_def _)=> //; case=> <-.\n  case: (halt _ _ _ _ _ _ _ M hlt1)=> v2 []? []? ?.\n  exists v2; split=> //. }\n{ move=> cd0 mu c1 m1 c2 m2 e0 vals1 mtch' at1.\nhave at1': at_external eff_S (RC.core c1) = Some (e0, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[? ?]|//]; case r: (vals_def _). }\ncase: (atext cd0 mu (RC.core c1) m1 c2 m2 e0 vals1 mtch' at1').\nby move=> H H2; split. }\n{ move=> cd0 mu st1 st2 m1 e0 vals1 m2 vals2 e'.\nmove=> inj mtch' at1 at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'.\nmove=> ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' rdo rdo' fS' K fT' L mu' M unch1 unch2.\nhave at1': at_external eff_S (RC.core st1) = Some (e0, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[? ?]|//]; case r: (vals_def _). }\ncase: (aftext cd0 mu (RC.core st1) st2 m1 e0 vals1 m2 vals2 e'\n  inj mtch' at1' at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'\n  ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' rdo rdo' fS' K fT' L mu' M unch1 unch2).\nmove=> cd' []st1' []st2' []aft1' []aft2' mtch12'.\nexists cd'.\nexists (RC.mk st1' [predU getBlocks [::ret1] & RC.locs st1]).\nexists st2'.\nsplit=> //.\nby rewrite /= /RC.after_external aft1'. }\nQed.\n\nEnd rc_2lems.\n", "meta": {"author": "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/rc_semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.16107529379084856}}
{"text": "Require Import Coq.Bool.Bool.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import msl.Axioms.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.effect_semantics.\nRequire Import sepcomp.structured_injections.\nRequire Import sepcomp.reach.\n\nModule SM_simulation. Section SharedMemory_simulation_inject.\n\nContext\n  {F1 V1 C1 F2 V2 C2 : Type}\n  (Sem1 : @EffectSem (Genv.t F1 V1) C1)\n  (Sem2 : @EffectSem (Genv.t F2 V2) C2)\n  (ge1 : Genv.t F1 V1)\n  (ge2 : Genv.t F2 V2).\n\nRecord SM_simulation_inject :=\n{ core_data : Type\n; match_state : core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop\n; core_ord : core_data -> core_data -> Prop\n; core_ord_wf : well_founded core_ord\n\n; match_sm_wd :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 -> SM_wd mu\n\n; genvs_dom_eq : genvs_domain_eq ge1 ge2\n\n; match_genv :\n    forall d mu c1 m1 c2 m2 (MC : match_state d mu c1 m1 c2 m2),\n    meminj_preserves_globals ge1 (extern_of mu) /\\\n    (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true)\n\n; match_visible :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 ->\n    REACH_closed m1 (vis mu)\n\n; match_restrict :\n    forall d mu c1 m1 c2 m2 X,\n    match_state d mu c1 m1 c2 m2 ->\n    (forall b, vis mu b = true -> X b = true) ->\n    REACH_closed m1 X ->\n    match_state d (restrict_sm mu X) c1 m1 c2 m2\n\n; match_validblocks :\n    forall d mu c1 m1 c2 m2,\n    match_state d mu c1 m1 c2 m2 ->\n    sm_valid mu m1 m2\n\n\n; core_initial :\n    forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n    initial_core Sem1 ge1 v vals1 = Some c1 ->\n    Mem.inject j m1 m2 ->\n    Forall2 (val_inject j) vals1 vals2 ->\n    meminj_preserves_globals ge1 j ->\n\n    (*the next two conditions are required to guarantee initialSM_wd*)\n    (forall b1 b2 d, j b1 = Some (b2, d) ->\n      DomS b1 = true /\\ DomT b2 = true) ->\n    (forall b,\n      REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b=true ->\n      DomT b = true) ->\n\n    (*the next two conditions ensure the initialSM satisfies sm_valid*)\n    (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n    (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n    exists cd, exists c2,\n    initial_core Sem2 ge2 v vals2 = Some c2\n    /\\ match_state cd\n         (initial_SM DomS DomT\n           (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n           (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n         c1 m1 c2 m2\n\n; effcore_diagram :\n    forall st1 m1 st1' m1' U1,\n    effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n    forall cd st2 mu m2,\n    match_state cd mu st1 m1 st2 m2 ->\n    exists st2', exists m2', exists cd', exists mu',\n      intern_incr mu mu'\n      /\\ sm_inject_separated mu mu' m1 m2\n      /\\ sm_locally_allocated mu mu' m1 m2 m1' m2'\n      /\\ match_state cd' mu' st1' m1' st2' m2'\n      /\\ exists U2,\n          ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n            (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n             core_ord cd' cd)) /\\\n         forall\n           (UHyp: forall b1 z, U1 b1 z = true -> vis mu b1 = true)\n           b ofs (Ub: U2 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                 /\\ U1 b1 (ofs-delta1) = true\n                 /\\ Mem.perm m1 b1 (ofs-delta1) Max Nonempty))\n\n\n; core_halted :\n    forall cd mu c1 m1 c2 m2 v1,\n    match_state cd mu c1 m1 c2 m2 ->\n    halted Sem1 c1 = Some v1 ->\n    exists v2,\n    Mem.inject (as_inj mu) m1 m2\n    /\\ val_inject (restrict (as_inj mu) (vis mu)) v1 v2\n    /\\ halted Sem2 c2 = Some v2\n\n\n; core_at_external :\n    forall cd mu c1 m1 c2 m2 e vals1,\n    match_state cd mu c1 m1 c2 m2 ->\n    at_external Sem1 c1 = Some (e,vals1) ->\n    Mem.inject (as_inj mu) m1 m2\n    /\\ exists vals2,\n       Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2\n       /\\ at_external Sem2 c2 = Some (e,vals2)\n\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_state cd nu c1 m1 c2 m2\n       /\\ Mem.inject (shared_of nu) m1 m2\n\n; eff_after_external:\n    forall cd mu st1 st2 m1 e vals1 m2 vals2 e'\n      (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n      (MatchMu: match_state cd mu st1 m1 st2 m2)\n      (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (* We include the clause AtExtTgt to ensure that vals2 is\n         uniquely determined. We have e=e' and ef_sig=ef_sig' by the\n         at_external clause, but omitting the hypothesis AtExtTgt\n         would result in in 2 not necesssarily equal target argument\n         lists in language 3 in the transitivity, as val_inject is not\n         functional in the case where the left value is Vundef. (And\n         we need to keep ValInjMu since vals2 occurs in pubTgtHyp) *)\n\n      (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n      (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n      pubSrc'\n      (pubSrcHyp:\n         pubSrc'\n         = (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n\n      pubTgt'\n      (pubTgtHyp:\n         pubTgt'\n         = fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b)\n\n      nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc'\n        (frgnSrcHyp:\n           frgnSrc'\n           = fun b => DomSrc nu' b &&\n                      (negb (locBlocksSrc nu' b) &&\n                       REACH m1' (exportedSrc nu' (ret1::nil)) b))\n\n        frgnTgt'\n        (frgnTgtHyp:\n           frgnTgt'\n           = fun b => DomTgt nu' b &&\n                      (negb (locBlocksTgt nu' b) &&\n                       REACH m2' (exportedTgt nu' (ret2::nil)) b))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n         (UnchPrivSrc:\n            Mem.unchanged_on (fun b ofs =>\n              locBlocksSrc nu b = true /\\\n              pubBlocksSrc nu b = false) m1 m1')\n\n         (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n\n        exists cd', exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_state cd' mu' st1' m1' st2' m2' }.\n\nRequire Import sepcomp.semantics_lemmas.\n\nLemma core_diagram (SMI: SM_simulation_inject):\n      forall st1 m1 st1' m1',\n        corestep Sem1 ge1 st1 m1 st1' m1' ->\n      forall cd st2 mu m2,\n        match_state SMI cd mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists cd', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n          match_state SMI cd' mu' st1' m1' st2' m2' /\\\n          ((corestep_plus Sem2 ge2 st2 m2 st2' m2') \\/\n            corestep_star Sem2 ge2 st2 m2 st2' m2' /\\\n            core_ord SMI cd' cd).\nProof. intros.\napply effax2 in H. destruct H as [U1 H].\nexploit (effcore_diagram SMI); eauto.\nintros [st2' [m2' [cd' [mu' [INC [SEP [LOCALLOC\n  [MST [U2 [STEP _]]]]]]]]]].\nexists st2', m2', cd', mu'.\nsplit; try assumption.\nsplit; try assumption.\nsplit; try assumption.\nsplit; try assumption.\ndestruct STEP as [[n STEP] | [[n STEP] CO]];\n  apply effstepN_corestepN in STEP.\nleft. exists n. assumption.\nright; split; trivial. exists n. assumption.\nQed.\n\nEnd SharedMemory_simulation_inject.\n\nEnd SM_simulation.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/sepcomp/effect_simulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1608774483268225}}
{"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(** Semantic preservation for the SimplLocals pass. *)\n\nRequire Import FSets.\nRequire Import Coqlib Errors Ordered Maps Integers Floats.\nRequire Import AST Linking.\nRequire Import Values Memory Globalenvs Events Smallstep.\nRequire Import Ctypes Cop Clight SimplLocals.\n\nModule VSF := FSetFacts.Facts(VSet).\nModule VSP := FSetProperties.Properties(VSet).\n\nDefinition match_prog (p tp: program) : Prop :=\n    match_program (fun ctx f tf => transf_fundef f = OK tf) eq p tp\n /\\ prog_types tp = prog_types p.\n\nLemma match_transf_program:\n  forall p tp, transf_program p = OK tp -> match_prog p tp.\nProof.\n  unfold transf_program; intros. monadInv H.\n  split; auto. apply match_transform_partial_program. rewrite EQ. destruct x; auto.\nQed.\n\nSection PRESERVATION.\n\nVariable fn_stack_requirements: ident -> Z.\nVariable prog: program.\nVariable tprog: program.\nHypothesis TRANSF: match_prog prog tprog.\nLet ge := globalenv prog.\nLet tge := globalenv tprog.\n\nLemma comp_env_preserved:\n  genv_cenv tge = genv_cenv ge.\nProof.\n  unfold tge, ge. destruct prog, tprog; simpl. destruct TRANSF as [_ EQ]. simpl in EQ. congruence.\nQed.\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof (Genv.find_symbol_match (proj1 TRANSF)).\n\nLemma senv_preserved:\n  Senv.equiv ge tge.\nProof (Genv.senv_match (proj1 TRANSF)).\n\nLemma functions_translated:\n  forall (v: val) (f: fundef),\n  Genv.find_funct ge v = Some f ->\n  exists tf, Genv.find_funct tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_transf_partial (proj1 TRANSF)).\n\nLemma function_ptr_translated:\n  forall (b: block) (f: fundef),\n  Genv.find_funct_ptr ge b = Some f ->\n  exists tf, Genv.find_funct_ptr tge b = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial (proj1 TRANSF)).\n\nLemma type_of_fundef_preserved:\n  forall fd tfd,\n  transf_fundef fd = OK tfd -> type_of_fundef tfd = type_of_fundef fd.\nProof.\n  intros. destruct fd; monadInv H; auto.\n  monadInv EQ. simpl; unfold type_of_function; simpl. auto.\nQed.\n\n(** Matching between environments before and after *)\n\nInductive match_var (f: meminj) (cenv: compilenv) (e: env) (m: mem) (te: env) (tle: temp_env) (id: ident) : Prop :=\n  | match_var_lifted: forall b ty chunk v tv\n      (ENV: e!id = Some(b, ty))\n      (TENV: te!id = None)\n      (LIFTED: VSet.mem id cenv = true)\n      (MAPPED: f b = None)\n      (MODE: access_mode ty = By_value chunk)\n      (LOAD: Mem.load chunk m b 0 = Some v)\n      (TLENV: tle!(id) = Some tv)\n      (VINJ: Val.inject f v tv),\n      match_var f cenv e m te tle id\n  | match_var_not_lifted: forall b ty b'\n      (ENV: e!id = Some(b, ty))\n      (TENV: te!id = Some(b', ty))\n      (LIFTED: VSet.mem id cenv = false)\n      (MAPPED: f b = Some(b', 0)),\n      match_var f cenv e m te tle id\n  | match_var_not_local: forall\n      (ENV: e!id = None)\n      (TENV: te!id = None)\n      (LIFTED: VSet.mem id cenv = false),\n      match_var f cenv e m te tle id.\n\nRecord match_envs (f: meminj) (cenv: compilenv)\n                  (e: env) (le: temp_env) (m: mem) (lo hi: sup)\n                  (te: env) (tle: temp_env) (tlo thi: sup) : Prop :=\n  mk_match_envs {\n    me_vars:\n      forall id, match_var f cenv e m te tle id;\n    me_temps:\n      forall id v,\n      le!id = Some v ->\n      (exists tv, tle!id = Some tv /\\ Val.inject f v tv)\n      /\\ (VSet.mem id cenv = true -> v = Vundef);\n    me_inj:\n      forall id1 b1 ty1 id2 b2 ty2, e!id1 = Some(b1, ty1) -> e!id2 = Some(b2, ty2) -> id1 <> id2 -> b1 <> b2;\n    me_range:\n      forall id b ty, e!id = Some(b, ty) -> ~ sup_In b lo /\\ sup_In b hi;\n    me_trange:\n      forall id b ty, te!id = Some(b, ty) -> ~ sup_In b tlo  /\\ sup_In b thi;\n    me_mapped:\n      forall id b' ty,\n      te!id = Some(b', ty) -> exists b, f b = Some(b', 0) /\\ e!id = Some(b, ty);\n    me_flat:\n      forall id b' ty b delta,\n      te!id = Some(b', ty) -> f b = Some(b', delta) -> e!id = Some(b, ty) /\\ delta = 0;\n    me_incr:\n      Mem.sup_include lo hi;\n    me_tincr:\n      Mem.sup_include tlo thi\n  }.\n\n(** Invariance by change of memory and injection *)\n\nLemma match_envs_invariant:\n  forall f cenv e le m lo hi te tle tlo thi f' m',\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  (forall b chunk v,\n    f b = None -> ~ sup_In b lo /\\ sup_In b hi -> Mem.load chunk m b 0 = Some v -> Mem.load chunk m' b 0 = Some v) ->\n  inject_incr f f' ->\n  (forall b, ~ sup_In b lo /\\ sup_In b hi -> f' b = f b) ->\n  (forall b b' delta, f' b = Some(b', delta) -> ~ sup_In b' tlo /\\ sup_In b' thi -> f' b = f b) ->\n  match_envs f' cenv e le m' lo hi te tle tlo thi.\nProof.\n  intros until m'; intros ME LD INCR INV1 INV2.\n  destruct ME; constructor; eauto.\n(* vars *)\n  intros. generalize (me_vars0 id); intros MV; inv MV.\n  eapply match_var_lifted; eauto.\n  rewrite <- MAPPED; eauto.\n  eapply match_var_not_lifted; eauto.\n  eapply match_var_not_local; eauto.\n(* temps *)\n  intros. exploit me_temps0; eauto. intros [[v' [A B]] C]. split; auto. exists v'; eauto.\n(* mapped *)\n  intros. exploit me_mapped0; eauto. intros [b [A B]]. exists b; split; auto.\n(* flat *)\n  intros. eapply me_flat0; eauto. rewrite <- H0. symmetry. eapply INV2; eauto.\nQed.\n\n(** Invariance by external call *)\n\nLemma match_envs_extcall:\n  forall f cenv e le m lo hi te tle tlo thi tm f' m',\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  Mem.unchanged_on (loc_unmapped f) m m' ->\n  inject_incr f f' ->\n  inject_separated f f' m tm ->\n  Mem.sup_include hi (Mem.support m) -> Mem.sup_include thi (Mem.support tm) ->\n  match_envs f' cenv e le m' lo hi te tle tlo thi.\nProof.\n  intros. eapply match_envs_invariant; eauto.\n  intros. eapply Mem.load_unchanged_on; eauto.\n  red in H2. intros. destruct (f b) as [[b' delta]|] eqn:?.\n  eapply H1; eauto.\n  destruct (f' b) as [[b' delta]|] eqn:?; auto.\n  exploit H2; eauto. unfold Mem.valid_block. intros [A B].\n  destruct H5. apply H3 in H6. congruence.\n  intros. destruct (f b) as [[b'' delta']|] eqn:?. eauto.\n  exploit H2; eauto. unfold Mem.valid_block. intros [A B].\n  destruct H6. apply H4 in H7. congruence.\nQed.\n\n(** Properties of values resulting from a cast *)\n\nLemma val_casted_load_result:\n  forall v ty chunk,\n  val_casted v ty -> access_mode ty = By_value chunk ->\n  Val.load_result chunk v = v.\nProof.\n  intros. inversion H; clear H; subst v ty; simpl in H0.\n- destruct sz.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  clear H1. inv H0. auto.\n  inversion H0; clear H0; subst chunk. simpl in *.\n  destruct (Int.eq n Int.zero); subst n; reflexivity.\n- inv H0; auto.\n- inv H0; auto.\n- inv H0; auto.\n- inv H0. unfold Mptr, Val.load_result; destruct Archi.ptr64; auto. \n- inv H0. unfold Mptr, Val.load_result; rewrite H1; auto.\n- inv H0. unfold Val.load_result; rewrite H1; auto.\n- inv H0. unfold Mptr, Val.load_result; rewrite H1; auto.\n- inv H0. unfold Val.load_result; rewrite H1; auto.\n- discriminate.\n- discriminate.\n- discriminate.\nQed.\n\nLemma val_casted_inject:\n  forall f v v' ty,\n  Val.inject f v v' -> val_casted v ty -> val_casted v' ty.\nProof.\n  intros. inv H; auto.\n  inv H0; constructor; auto.\n  inv H0; constructor.\nQed.\n\nLemma forall2_val_casted_inject:\n  forall f vl vl', Val.inject_list f vl vl' ->\n  forall tyl, list_forall2 val_casted vl tyl -> list_forall2 val_casted vl' tyl.\nProof.\n  induction 1; intros tyl F; inv F; constructor; eauto. eapply val_casted_inject; eauto.\nQed.\n\nInductive val_casted_list: list val -> typelist -> Prop :=\n  | vcl_nil:\n      val_casted_list nil Tnil\n  | vcl_cons: forall v1 vl ty1 tyl,\n      val_casted v1 ty1 -> val_casted_list vl tyl ->\n      val_casted_list (v1 :: vl) (Tcons  ty1 tyl).\n\nLemma val_casted_list_params:\n  forall params vl,\n  val_casted_list vl (type_of_params params) ->\n  list_forall2 val_casted vl (map snd params).\nProof.\n  induction params; simpl; intros.\n  inv H. constructor.\n  destruct a as [id ty]. inv H. constructor; auto.\nQed.\n\n(** Correctness of [make_cast] *)\n\nLemma make_cast_correct:\n  forall e le m a v1 tto v2,\n  eval_expr tge e le m a v1 ->\n  sem_cast v1 (typeof a) tto m = Some v2 ->\n  eval_expr tge e le m (make_cast a tto) v2.\nProof.\n  intros.\n  assert (DFL: eval_expr tge e le m (Ecast a tto) v2).\n    econstructor; eauto.\n  unfold sem_cast, make_cast in *.\n  destruct (classify_cast (typeof a) tto); auto.\n  destruct v1; destruct Archi.ptr64; inv H0; auto.\n  destruct sz2; auto. destruct v1; inv H0; auto.\n  destruct v1; inv H0; auto.\n  destruct v1; inv H0; auto.\n  destruct v1; inv H0; auto.\n  destruct v1; try discriminate.\n  destruct (ident_eq id1 id2); inv H0; auto.\n  destruct v1; try discriminate.\n  destruct (ident_eq id1 id2); inv H0; auto.\n  inv H0; auto.\nQed.\n\n(** Debug annotations. *)\n\nLemma cast_typeconv:\n  forall v ty m,\n  val_casted v ty ->\n  sem_cast v ty (typeconv ty) m = Some v.\nProof.\n  induction 1; simpl.\n- unfold sem_cast, classify_cast; destruct sz, Archi.ptr64; auto.\n- auto.\n- auto.\n- unfold sem_cast, classify_cast; destruct Archi.ptr64; auto.\n- auto.\n- unfold sem_cast; simpl; rewrite H; auto.\n- unfold sem_cast; simpl; rewrite H; auto.\n- unfold sem_cast; simpl; rewrite H; auto.\n- unfold sem_cast; simpl; rewrite H; auto.\n- unfold sem_cast; simpl. rewrite dec_eq_true; auto.\n- unfold sem_cast. simpl. rewrite dec_eq_true; auto.\n- auto.\nQed.\n\nLemma step_Sdebug_temp:\n  forall f id ty k e le m v,\n  le!id = Some v ->\n  val_casted v ty ->\n  step2 fn_stack_requirements tge (State f (Sdebug_temp id ty) k e le m)\n         E0 (State f Sskip k e le m).\nProof.\n  intros. unfold Sdebug_temp. eapply step_builtin with (optid := None).\n  econstructor. constructor. eauto. simpl. eapply cast_typeconv; eauto. constructor.\n  simpl. constructor.\nQed.\n\nLemma step_Sdebug_var:\n  forall f id ty k e le m b,\n  e!id = Some(b, ty) ->\n  step2 fn_stack_requirements tge (State f (Sdebug_var id ty) k e le m)\n         E0 (State f Sskip k e le m).\nProof.\n  intros. unfold Sdebug_var. eapply step_builtin with (optid := None).\n  econstructor. constructor. constructor. eauto.\n  simpl. reflexivity. constructor.\n  simpl. constructor.\nQed.\n\nLemma step_Sset_debug:\n  forall f id ty a k e le m v v',\n  eval_expr tge e le m a v ->\n  sem_cast v (typeof a) ty m = Some v' ->\n  plus (step2 fn_stack_requirements) tge (State f (Sset_debug id ty a) k e le m)\n              E0 (State f Sskip k e (PTree.set id v' le) m).\nProof.\n  intros; unfold Sset_debug.\n  assert (forall k, step2 fn_stack_requirements tge (State f (Sset id (make_cast a ty)) k e le m)\n                           E0 (State f Sskip k e (PTree.set id v' le) m)).\n  { intros. apply step_set. eapply make_cast_correct; eauto. }\n  destruct (Compopts.debug tt).\n- eapply plus_left. constructor.\n  eapply star_left. apply H1.\n  eapply star_left. constructor.\n  apply star_one. apply step_Sdebug_temp with (v := v').\n  apply PTree.gss. eapply cast_val_is_casted; eauto.\n  reflexivity. reflexivity. reflexivity.\n- apply plus_one. apply H1.\nQed.\n\nLemma step_add_debug_vars:\n  forall f s e le m vars k,\n  (forall id ty, In (id, ty) vars -> exists b, e!id = Some (b, ty)) ->\n  star (step2 fn_stack_requirements) tge (State f (add_debug_vars vars s) k e le m)\n              E0 (State f s k e le m).\nProof.\n  unfold add_debug_vars. destruct (Compopts.debug tt).\n- induction vars; simpl; intros.\n  + apply star_refl.\n  + destruct a as [id ty].\n    exploit H; eauto. intros (b & TE).\n    simpl. eapply star_left. constructor.\n    eapply star_left. eapply step_Sdebug_var; eauto.\n    eapply star_left. constructor.\n    apply IHvars; eauto.\n    reflexivity. reflexivity. reflexivity.\n- intros. apply star_refl.\nQed.\n\nRemark bind_parameter_temps_inv:\n  forall id params args le le',\n  bind_parameter_temps params args le = Some le' ->\n  ~In id (var_names params) ->\n  le'!id = le!id.\nProof.\n  induction params; simpl; intros.\n  destruct args; inv H. auto.\n  destruct a as [id1 ty1]. destruct args; try discriminate.\n  transitivity ((PTree.set id1 v le)!id).\n  eapply IHparams; eauto. apply PTree.gso. intuition.\nQed.\n\nLemma step_add_debug_params:\n  forall f s k e le m params vl le1,\n  list_norepet (var_names params) ->\n  list_forall2 val_casted vl (map snd params) ->\n  bind_parameter_temps params vl le1 = Some le ->\n  star (step2 fn_stack_requirements)\n       tge (State f (add_debug_params params s) k e le m)\n       E0 (State f s k e le m).\nProof.\n  unfold add_debug_params. destruct (Compopts.debug tt).\n- induction params as [ | [id ty] params ]; simpl; intros until le1; intros NR CAST BIND; inv CAST; inv NR.\n  + apply star_refl.\n  + assert (le!id = Some a1). { erewrite bind_parameter_temps_inv by eauto. apply PTree.gss. }\n    eapply star_left. constructor.\n    eapply star_left. eapply step_Sdebug_temp; eauto.\n    eapply star_left. constructor.\n    eapply IHparams; eauto.\n    reflexivity. reflexivity. reflexivity.\n- intros; apply star_refl.\nQed.\n\n(** Preservation by assignment to lifted variable. *)\n\nLemma match_envs_assign_lifted:\n  forall f cenv e le m lo hi te tle tlo thi b ty v m' id tv,\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  e!id = Some(b, ty) ->\n  val_casted v ty ->\n  Val.inject f v tv ->\n  assign_loc ge ty m b Ptrofs.zero v m' ->\n  VSet.mem id cenv = true ->\n  match_envs f cenv e le m' lo hi te (PTree.set id tv tle) tlo thi.\nProof.\n  intros. destruct H. generalize (me_vars0 id); intros MV; inv MV; try congruence.\n  rewrite ENV in H0; inv H0. inv H3; try congruence.\n  unfold Mem.storev in H0. rewrite Ptrofs.unsigned_zero in H0.\n  constructor; eauto; intros.\n(* vars *)\n  destruct (peq id0 id). subst id0.\n  eapply match_var_lifted with (v := v); eauto.\n  exploit Mem.load_store_same; eauto. erewrite val_casted_load_result; eauto.\n  apply PTree.gss.\n  generalize (me_vars0 id0); intros MV; inv MV.\n  eapply match_var_lifted; eauto.\n  rewrite <- LOAD0. eapply Mem.load_store_other; eauto.\n  rewrite PTree.gso; auto.\n  eapply match_var_not_lifted; eauto.\n  eapply match_var_not_local; eauto.\n(* temps *)\n  exploit me_temps0; eauto. intros [[tv1 [A B]] C]. split; auto.\n  rewrite PTree.gsspec. destruct (peq id0 id).\n  subst id0. exists tv; split; auto. rewrite C; auto.\n  exists tv1; auto.\nQed.\n\n(** Preservation by assignment to a temporary *)\n\nLemma match_envs_set_temp:\n  forall f cenv e le m lo hi te tle tlo thi id v tv x,\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  Val.inject f v tv ->\n  check_temp cenv id = OK x ->\n  match_envs f cenv e (PTree.set id v le) m lo hi te (PTree.set id tv tle) tlo thi.\nProof.\n  intros. unfold check_temp in H1.\n  destruct (VSet.mem id cenv) eqn:?; monadInv H1.\n  destruct H. constructor; eauto; intros.\n(* vars *)\n  generalize (me_vars0 id0); intros MV; inv MV.\n  eapply match_var_lifted; eauto. rewrite PTree.gso. eauto. congruence.\n  eapply match_var_not_lifted; eauto.\n  eapply match_var_not_local; eauto.\n(* temps *)\n  rewrite PTree.gsspec in *. destruct (peq id0 id).\n  inv H. split. exists tv; auto. intros; congruence.\n  eapply me_temps0; eauto.\nQed.\n\nLemma match_envs_set_opttemp:\n  forall f cenv e le m lo hi te tle tlo thi optid v tv x,\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  Val.inject f v tv ->\n  check_opttemp cenv optid = OK x ->\n  match_envs f cenv e (set_opttemp optid v le) m lo hi te (set_opttemp optid tv tle) tlo thi.\nProof.\n  intros. unfold set_opttemp. destruct optid; simpl in H1.\n  eapply match_envs_set_temp; eauto.\n  auto.\nQed.\n\n(** Extensionality with respect to temporaries *)\n\nLemma match_envs_temps_exten:\n  forall f cenv e le m lo hi te tle tlo thi tle',\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  (forall id, tle'!id = tle!id) ->\n  match_envs f cenv e le m lo hi te tle' tlo thi.\nProof.\n  intros. destruct H. constructor; auto; intros.\n  (* vars *)\n  generalize (me_vars0 id); intros MV; inv MV.\n  eapply match_var_lifted; eauto. rewrite H0; auto.\n  eapply match_var_not_lifted; eauto.\n  eapply match_var_not_local; eauto.\n  (* temps *)\n  rewrite H0. eauto.\nQed.\n\n(** Invariance by assignment to an irrelevant temporary *)\n\nLemma match_envs_change_temp:\n  forall f cenv e le m lo hi te tle tlo thi id v,\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  le!id = None -> VSet.mem id cenv = false ->\n  match_envs f cenv e le m lo hi te (PTree.set id v tle) tlo thi.\nProof.\n  intros. destruct H. constructor; auto; intros.\n  (* vars *)\n  generalize (me_vars0 id0); intros MV; inv MV.\n  eapply match_var_lifted; eauto. rewrite PTree.gso; auto. congruence.\n  eapply match_var_not_lifted; eauto.\n  eapply match_var_not_local; eauto.\n  (* temps *)\n  rewrite PTree.gso. eauto. congruence.\nQed.\n\n(** Properties of [cenv_for]. *)\n\nDefinition cenv_for_gen (atk: VSet.t) (vars: list (ident * type)) : compilenv :=\n  List.fold_right (add_local_variable atk) VSet.empty vars.\n\nRemark add_local_variable_charact:\n  forall id ty atk cenv id1,\n  VSet.In id1 (add_local_variable atk (id, ty) cenv) <->\n  VSet.In id1 cenv \\/ exists chunk, access_mode ty = By_value chunk /\\ id = id1 /\\ VSet.mem id atk = false.\nProof.\n  intros. unfold add_local_variable. split; intros.\n  destruct (access_mode ty) eqn:?; auto.\n  destruct (VSet.mem id atk) eqn:?; auto.\n  rewrite VSF.add_iff in H. destruct H; auto. right; exists m; auto.\n  destruct H as [A | [chunk [A [B C]]]].\n  destruct (access_mode ty); auto. destruct (VSet.mem id atk); auto. rewrite VSF.add_iff; auto.\n  rewrite A. rewrite <- B. rewrite C. apply VSet.add_1; auto.\nQed.\n\nLemma cenv_for_gen_domain:\n forall atk id vars, VSet.In id (cenv_for_gen atk vars) -> In id (var_names vars).\nProof.\n  induction vars; simpl; intros.\n  rewrite VSF.empty_iff in H. auto.\n  destruct a as [id1 ty1]. rewrite add_local_variable_charact in H.\n  destruct H as [A | [chunk [A [B C]]]]; auto.\nQed.\n\nLemma cenv_for_gen_by_value:\n  forall atk id ty vars,\n  In (id, ty) vars ->\n  list_norepet (var_names vars) ->\n  VSet.In id (cenv_for_gen atk vars) ->\n  exists chunk, access_mode ty = By_value chunk.\nProof.\n  induction vars; simpl; intros.\n  contradiction.\n  destruct a as [id1 ty1]. simpl in H0. inv H0.\n  rewrite add_local_variable_charact in H1.\n  destruct H; destruct H1 as [A | [chunk [A [B C]]]].\n  inv H. elim H4. eapply cenv_for_gen_domain; eauto.\n  inv H. exists chunk; auto.\n  eauto.\n  subst id1. elim H4. change id with (fst (id, ty)). apply in_map; auto.\nQed.\n\nLemma cenv_for_gen_compat:\n  forall atk id vars,\n  VSet.In id (cenv_for_gen atk vars) -> VSet.mem id atk = false.\nProof.\n  induction vars; simpl; intros.\n  rewrite VSF.empty_iff in H. contradiction.\n  destruct a as [id1 ty1]. rewrite add_local_variable_charact in H.\n  destruct H as [A | [chunk [A [B C]]]].\n  auto.\n  congruence.\nQed.\n\n(** Compatibility between a compilation environment and an address-taken set. *)\n\nDefinition compat_cenv (atk: VSet.t) (cenv: compilenv) : Prop :=\n  forall id, VSet.In id atk -> VSet.In id cenv -> False.\n\nLemma compat_cenv_for:\n  forall f, compat_cenv (addr_taken_stmt f.(fn_body)) (cenv_for f).\nProof.\n  intros; red; intros.\n  assert (VSet.mem id (addr_taken_stmt (fn_body f)) = false).\n    eapply cenv_for_gen_compat. eexact H0.\n  rewrite VSF.mem_iff in H. congruence.\nQed.\n\nLemma compat_cenv_union_l:\n  forall atk1 atk2 cenv,\n  compat_cenv (VSet.union atk1 atk2) cenv -> compat_cenv atk1 cenv.\nProof.\n  intros; red; intros. eapply H; eauto. apply VSet.union_2; auto.\nQed.\n\nLemma compat_cenv_union_r:\n  forall atk1 atk2 cenv,\n  compat_cenv (VSet.union atk1 atk2) cenv -> compat_cenv atk2 cenv.\nProof.\n  intros; red; intros. eapply H; eauto. apply VSet.union_3; auto.\nQed.\n\nLemma compat_cenv_empty:\n  forall cenv, compat_cenv VSet.empty cenv.\nProof.\n  intros; red; intros. eapply VSet.empty_1; eauto.\nQed.\n\nHint Resolve compat_cenv_union_l compat_cenv_union_r compat_cenv_empty: compat.\n\n(** Allocation and initialization of parameters *)\n\nLemma alloc_variables_stackseq:\n  forall ge e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  Mem.stackseq m m'.\nProof.\n  induction 1.\n  apply struct_eq_refl. eapply struct_eq_trans.\n  eapply Mem.alloc_stackseq; eauto. eauto.\nQed.\n\nLemma alloc_variables_parallel_stackseq :\n  forall ge1 e1 m1 vars1 e1' m1' ge2 e2 m2 vars2 e2' m2',\n  alloc_variables ge1 e1 m1 vars1 e1' m1' ->\n  alloc_variables ge2 e2 m2 vars2 e2' m2' ->\n  Mem.stackseq m1 m2 ->\n  Mem.stackseq m1' m2'.\nProof.\n  intros.\n  apply alloc_variables_stackseq in H.\n  apply alloc_variables_stackseq in H0.\n  eapply struct_eq_trans. eapply struct_eq_comm; eauto.\n  eapply struct_eq_trans; eauto.\nQed.\n\nLemma alloc_variables_astackeq:\n  forall ge e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  Mem.astack (Mem.support m) = Mem.astack (Mem.support m').\nProof.\n  induction 1. congruence.\n  apply Mem.support_alloc in H. unfold sup_incr in H. destr_in H.\n  rewrite <- IHalloc_variables. rewrite H. simpl. auto.\nQed.\n\nLemma alloc_variables_parallel_astackeq :\n  forall ge1 e1 m1 vars1 e1' m1' ge2 e2 m2 vars2 e2' m2',\n  alloc_variables ge1 e1 m1 vars1 e1' m1' ->\n  alloc_variables ge2 e2 m2 vars2 e2' m2' ->\n  Mem.astack (Mem.support m1) = Mem.astack (Mem.support m2) ->\n  Mem.astack (Mem.support m1') = Mem.astack (Mem.support m2').\nProof.\n  intros.\n  apply alloc_variables_astackeq in H.\n  apply alloc_variables_astackeq in H0.\n  congruence.\nQed.\n\nLemma alloc_variables_support:\n  forall ge e m vars e' m',\n  alloc_variables ge e m vars e' m' -> Mem.sup_include (Mem.support m) (Mem.support m').\nProof.\n  induction 1.\n  apply Mem.sup_include_refl.\n  eapply Mem.sup_include_trans; eauto. exploit Mem.support_alloc; eauto. intros EQ. unfold sup_incr in EQ. apply Mem.sup_include_trans with (Mem.support m1). rewrite EQ. apply Mem.sup_include_refl. apply IHalloc_variables.\nQed.\n\nLemma alloc_variables_range:\n  forall ge id b ty e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  e'!id = Some(b, ty) -> e!id = Some(b, ty) \\/ ~sup_In b (Mem.support m) /\\ sup_In b (Mem.support m').\nProof.\n  induction 1; intros.\n  auto.\n  exploit IHalloc_variables; eauto. rewrite PTree.gsspec. intros [A|A].\n  destruct (peq id id0). inv A.\n  right. exploit Mem.alloc_result; eauto. exploit Mem.support_alloc; eauto.\n  generalize (alloc_variables_support _ _ _ _ _ _ H0). intros A B C.\n  subst b. split. apply freshness. eapply Mem.sup_include_trans; eauto. apply Mem.sup_include_refl. rewrite B. apply Mem.sup_incr_in1.  auto.\n  right. exploit Mem.support_alloc; eauto. intros B. rewrite B in A.\n  destruct A.\n  split. intro. apply H2. apply Mem.sup_incr_in2.  auto. auto.\nQed.\n\nLemma alloc_variables_injective:\n  forall ge id1 b1 ty1 id2 b2 ty2 e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  (e!id1 = Some(b1, ty1) -> e!id2 = Some(b2, ty2) -> id1 <> id2 -> b1 <> b2) ->\n  (forall id b ty, e!id = Some(b, ty) -> sup_In b (Mem.support m)) ->\n  (e'!id1 = Some(b1, ty1) -> e'!id2 = Some(b2, ty2) -> id1 <> id2 -> b1 <> b2).\nProof.\n  induction 1; intros.\n  eauto.\n  eapply IHalloc_variables; eauto.\n  repeat rewrite PTree.gsspec; intros.\n  destruct (peq id1 id); destruct (peq id2 id).\n  congruence.\n  inv H6. exploit H2; eauto. intros.\n  apply Mem.valid_not_valid_diff with m b2 b1 in H6. auto.\n  apply Mem.fresh_block_alloc in H. auto.\n  inv H7. exploit H2; eauto. intros.\n  apply Mem.valid_not_valid_diff with m b1 b2 in H7. auto.\n  apply Mem.fresh_block_alloc in H. auto.\n  eauto.\n  intros. rewrite PTree.gsspec in H6. destruct (peq id0 id). inv H6.\n  apply Mem.valid_new_block in H. auto.\n  exploit H2; eauto. eapply Mem.valid_block_alloc; eauto.\nQed.\n\nSection SINJ.\nDefinition posenv := PTree.t positive.\nDefinition empty_posenv : posenv := PTree.empty positive.\n\nFixpoint build_penv (ce:compilenv) (vars:list (ident*type)) (idx1 idx2 : positive) : posenv :=\n  match vars with\n    |nil => empty_posenv\n    |(id,ty)::l0 => if VSet.mem id ce then build_penv ce l0 (Pos.succ idx1) (idx2)\n                   else (PTree.set idx1 idx2 (build_penv ce l0 (Pos.succ idx1) (Pos.succ idx2)))\n  end.\n\nLemma build_penv_low : forall ce vars idx1 idx2 id,\n    (id < idx1)%positive ->\n    PTree.get id (build_penv ce vars idx1 idx2) = None.\nProof.\n  induction vars; intros; simpl. apply PTree.gempty.\n  simpl. destr. destr. apply IHvars. lia.\n  rewrite PTree.gso. apply IHvars. lia. lia.\nQed.\n\nDefinition find_func_pos (fid:ident)( pos: positive) : option positive:=\n  match Genv.find_funct_ptr ge (Global fid) with\n    |Some ((Internal f)) =>\n  let cenv := cenv_for f in\n  let penv := build_penv cenv ((f.(fn_params) ++ f.(fn_vars))) 1%positive 1%positive  in\n    PTree.get pos penv\n    |_ => None\n  end.\n\nDefinition unchecked_meminj : meminj :=\n  fun b => match b with\n    |Stack (Some id) path pos =>\n      match find_func_pos id pos with\n        | Some pos' => Some(Stack (Some id) path pos',0)\n        | None => None\n      end\n    |_ => Some (b,0)\n    end.\n\nDefinition struct_meminj (s:sup) : meminj :=\n  fun b => if Mem.sup_dec b s then\n           unchecked_meminj b else None.\n\nLemma sinj_refl:\n  forall s1 s2, (forall b, sup_In b s1 <-> sup_In b s2) ->\n           struct_meminj s1= struct_meminj s2.\nProof.\n  intros.\n  apply Axioms.extensionality.\n  intros. destruct x; unfold struct_meminj; simpl.\n  destruct (Mem.sup_dec (Stack f p p0) s1);\n  destruct (Mem.sup_dec (Stack f p p0) s2).\n  auto. apply H in s. congruence.\n  apply H in s. congruence. auto.\n  destr; destr. apply H in s. congruence.\n  apply H in s. congruence.\nQed.\n\nLemma sinj_include_incr :forall s1 s2, Mem.sup_include s1 s2 -> inject_incr (struct_meminj s1) (struct_meminj s2).\nProof.\n  intros. intro. intros. unfold struct_meminj in *.\n  destruct b; simpl in *.\n  destruct (Mem.sup_dec (Stack f p p0) s1);\n  destruct (Mem.sup_dec (Stack f p p0) s2).\n  auto. apply H in s. congruence. inv H0. inv H0.\n  destr. destr_in H0. destr_in H0.\n  inv H0. apply H in s. congruence.\nQed.\n\nInductive alloc_variables' (ge:genv): env -> mem -> list (ident * type) -> list block -> env -> mem -> Prop :=\n  |av_nil : forall e m, alloc_variables' ge e m nil nil e m\n  |av_cons : forall e m id ty vars m1 b1 m2 e2 blocks,\n      Mem.alloc m 0 (sizeof ge ty) = (m1,b1) ->\n      alloc_variables' ge (PTree.set id (b1,ty) e) m1 vars blocks e2 m2 ->\n      alloc_variables' ge e m ((id,ty)::vars) (b1::blocks) e2 m2.\n\n\nLemma alloc_vars_fresh' : forall ge e1 m1 vars blocks e2 m2 b ,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    In b blocks -> ~ sup_In b (Mem.support m1).\nProof.\n  intros. induction H. inv H0.\n  inv H0. eapply Mem.fresh_block_alloc; eauto.\n  intro. apply IHalloc_variables'. auto.\n  eapply Mem.valid_block_alloc; eauto.\nQed.\n\nLemma valid_block_alloc_vars' : forall ge e1 m1 vars blocks e2 m2 b,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    sup_In b (Mem.support m1) -> sup_In b (Mem.support m2).\nProof.\n  intros. induction H. auto.\n  eapply Mem.valid_block_alloc in H; eauto.\nQed.\n\nLemma alloc_vars_valid' : forall ge e1 m1 vars blocks e2 m2 b ,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    In b blocks -> sup_In b (Mem.support m2).\nProof.\n  intros. induction H. inv H0.\n  inv H0.\n  eapply valid_block_alloc_vars' in H1; eauto.\n  eapply Mem.valid_new_block; eauto.\n  eauto.\nQed.\n\nLemma alloc_vars_inv'  : forall ge e1 m1 vars blocks e2 m2 b ,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    sup_In b (Mem.support m1) \\/In b blocks <-> sup_In b (Mem.support m2).\nProof.\n  intros. split. intros [A|B].\n  eapply valid_block_alloc_vars'; eauto.\n  eapply alloc_vars_valid'; eauto.\n  intros. induction H. eauto.\n  apply IHalloc_variables' in H0. inv H0.\n  destruct (eq_block b b1). right. left. auto.\n  left. exploit Mem.valid_block_alloc_inv; eauto.\n  intros. inv H0. congruence. auto. right. right. auto.\nQed.\n\nLemma alloc_var_var' : forall ge e1 m1 vars e2 m2,\n    alloc_variables ge e1 m1 vars e2 m2 ->\n    exists blocks, alloc_variables' ge e1 m1 vars blocks e2 m2 /\\\n               list_norepet blocks.\nProof.\n  intros. induction H.\n  exists nil. split. constructor. constructor.\n  destruct IHalloc_variables as (blocks & A & B).\n  exists (b1::blocks). split. econstructor; eauto.\n  constructor; auto. intro. apply alloc_vars_fresh' with (b:=b1)in A; auto.\n  apply A. eapply Mem.valid_new_block; eauto.\nQed.\n\nLemma alloc_var'_var : forall ge e1 m1 vars blocks e2 m2,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    alloc_variables ge e1 m1 vars e2 m2.\nProof.\n  intros. induction H. constructor.\n  econstructor; eauto.\nQed.\n\nEnd SINJ.\n\nDefinition nextblock_pos (m:mem) (p:positive) : Prop :=\n  exists id path, Mem.nextblock m = Stack id path p.\n\nDefinition match_penv_meminj (b:block) (pe:posenv) (f:meminj) : Prop :=\n  exists id path pos, b = Stack id path pos /\\\n                 (f b = match pe ! pos with\n                          |Some pos' => Some ((Stack id path pos'),0)\n                          |None => None\n                 end ).\n\nLemma nextblock_pos_succ : forall m m1 lo hi p b,\n    nextblock_pos m p ->\n    Mem.alloc m lo hi = (m1,b) ->\n    nextblock_pos m1 (Pos.succ p).\nProof.\n  intros.\n  caseEq (Mem.alloc m1 lo hi). intros.\n  destruct H as (id & path & H). apply Mem.alloc_result in H0 as H0'. subst.\n  exploit Mem.alloc_alloc. apply H0. apply H1. eauto. intro.\n  exists id,path.\n  apply Mem.alloc_result in H1 as H1'. subst. eauto.\nQed.\n\nLemma nextblock_pos_1 : forall m m1 id path,\n    Mem.alloc_frame m id = (m1,path) ->\n    nextblock_pos m1 1.\nProof.\n  intros. caseEq (Mem.alloc m1 1 1). intros.\n  exploit Mem.alloc_frame_alloc; eauto. intro.\n  apply Mem.alloc_result in H0. exists (Some id),path. congruence.\nQed.\n\nLemma alloc_nextblock : forall m m1 lo hi b id path p,\n    Mem.nextblock m = Stack id path p ->\n    Mem.alloc m lo hi = (m1,b) ->\n    Mem.nextblock m1 = Stack id path (Pos.succ p).\nProof.\n  intros. caseEq (Mem.alloc m1 0 0). intros.\n  exploit Mem.alloc_alloc. apply H0. eauto.\n  apply Mem.alloc_result in H0. subst. eauto. intro.\n  apply Mem.alloc_result in H1. congruence.\nQed.\n\nLemma nextblock_alloc_vars :\n  forall m1 m2 ge e1 e2 vars blocks,\n    alloc_variables' ge e1 m1 vars blocks e2 m2 ->\n    forall id path p,\n    Mem.nextblock m1 = Stack id path p ->\n    (forall b, In b blocks ->\n          exists p', b = Stack id path p' /\\ (p <= p')%positive).\nProof.\n  induction 1.\n  intros. inv H0.\n  intros. inv H2.\n  - apply Mem.alloc_result in H. subst. rewrite H1.\n    exists p. split. auto. lia.\n  - exploit alloc_nextblock; eauto. intro.\n    eapply IHalloc_variables' in H2. destruct H2 as (p' & A & B).\n    exists p'. split. eauto. lia. auto.\nQed.\n\nLemma match_alloc_variables':\n  forall cenv e m vars blocks e' m',\n  alloc_variables' ge e m vars blocks e' m' ->\n  forall j tm te pe idx1 idx2,\n  list_norepet (var_names vars) ->\n  Mem.inject j m tm ->\n  Mem.stackseq m tm ->\n  pe = build_penv cenv vars idx1 idx2 ->\n  nextblock_pos m idx1 ->\n  nextblock_pos tm idx2 ->\n  exists j', exists te', exists tm',\n      alloc_variables tge te tm (remove_lifted cenv vars) te' tm'\n  /\\ Mem.inject j' m' tm'\n  /\\ inject_incr j j'\n  /\\ (forall b, Mem.valid_block m b -> j' b = j b)\n  /\\ (forall b b' delta, j' b = Some(b', delta) -> Mem.valid_block tm b' -> j' b = j b)\n  /\\ (forall b b' delta, j' b = Some(b', delta) -> ~Mem.valid_block tm b' ->\n         exists id, exists ty, e'!id = Some(b, ty) /\\ te'!id = Some(b', ty) /\\ delta = 0)\n  /\\ (forall id ty, In (id, ty) vars ->\n      exists b,\n          e'!id = Some(b, ty)\n       /\\ if VSet.mem id cenv\n          then te'!id = te!id /\\ j' b = None\n          else exists tb, te'!id = Some(tb, ty) /\\ j' b = Some(tb, 0))\n  /\\ (forall id, ~In id (var_names vars) -> e'!id = e!id /\\ te'!id = te!id)\n  /\\ (forall b, In b blocks -> match_penv_meminj b pe j').\nProof.\n  induction 1; intros.\n  (* base case *)\n  exists j; exists te; exists tm. simpl.\n  split. constructor.\n  split. auto. split. auto. split. auto.  split. auto.\n  split. intros. elim H6. eapply Mem.mi_mappedblocks; eauto.\n  split. tauto. tauto.\n\n  (* inductive case *)\n  simpl in H1. inv H1. simpl.\n  destruct (VSet.mem id cenv) eqn:?.\n  - simpl.\n  (* variable is lifted out of memory *)\n  exploit Mem.alloc_left_unmapped_inject; eauto.\n  intros [j1 [A [B [C D]]]].\n  exploit IHalloc_variables'; eauto.\n  eapply struct_eq_trans. 2:eauto.\n  eapply struct_eq_comm. eapply Mem.alloc_stackseq; eauto.\n  eapply nextblock_pos_succ. apply H5. eauto.\n  instantiate (1 := te).\n  intros [j' [te' [tm' [J [K [L [M [N [Q [O [P R]]]]]]]]]]].\n  exists j'; exists te'; exists tm'.\n  split. auto.\n  split. auto.\n  split. eapply inject_incr_trans; eauto.\n  split. intros. transitivity (j1 b). apply M. eapply Mem.valid_block_alloc; eauto.\n    apply D. apply Mem.valid_not_valid_diff with m; auto. eapply Mem.fresh_block_alloc; eauto.\n  split. intros. transitivity (j1 b). eapply N; eauto.\n    destruct (eq_block b b1); auto. subst.\n    assert (j' b1 = j1 b1). apply M. eapply Mem.valid_new_block; eauto.\n    congruence.\n  split. exact Q.\n  split. intros. destruct (ident_eq id0 id).\n    (* same var *)\n    subst id0.\n    assert (ty0 = ty).\n      destruct H1. congruence. elim H9. unfold var_names. change id with (fst (id, ty0)). apply in_map; auto.\n    subst ty0.\n    exploit P; eauto. intros [X Y]. rewrite Heqb. rewrite X. rewrite Y.\n    exists b1. split. apply PTree.gss.\n    split. auto.\n    rewrite M. auto. eapply Mem.valid_new_block; eauto.\n    (* other vars *)\n    eapply O; eauto. destruct H1. congruence. auto.\n  split. intros. exploit (P id0). tauto. intros [X Y]. rewrite X; rewrite Y.\n    split; auto. apply PTree.gso. intuition.\n  intros. inv H1. unfold match_penv_meminj.\n  exploit Mem.alloc_result; eauto. intro.\n  destruct H5 as (fid & path & H5). rewrite H5 in H1.\n  exists fid,path,idx1. split. congruence.\n  rewrite M. rewrite C. rewrite build_penv_low. auto. lia.\n  eapply Mem.valid_new_block. eauto.\n  eauto.\n-\n  (* variable is not lifted out of memory *)\n  exploit Mem.alloc_parallel_inject.\n    eauto. eauto. apply Z.le_refl. apply Z.le_refl.\n  intros [j1 [tm1 [tb1 [A [B [C [D E]]]]]]].\n  exploit IHalloc_variables'; eauto.\n  eapply struct_eq_trans. eapply struct_eq_comm.\n  eapply Mem.alloc_stackseq; eauto.\n  eapply struct_eq_trans; eauto. eapply Mem.alloc_stackseq; eauto.\n  eapply nextblock_pos_succ. apply H5. eauto.\n  eapply nextblock_pos_succ. apply H6. eauto.\n  instantiate (1 := PTree.set id (tb1, ty) te).\n  intros [j' [te' [tm' [J [K [L [M [N [Q [O [P R]]]]]]]]]]].\n  exists j'; exists te'; exists tm'.\n  split. simpl. econstructor; eauto. rewrite comp_env_preserved; auto.\n  split. auto.\n  split. eapply inject_incr_trans; eauto.\n  split. intros. transitivity (j1 b). apply M. eapply Mem.valid_block_alloc; eauto.\n    apply E. apply Mem.valid_not_valid_diff with m; auto. eapply Mem.fresh_block_alloc; eauto.\n  split. intros. transitivity (j1 b). eapply N; eauto. eapply Mem.valid_block_alloc; eauto.\n    destruct (eq_block b b1); auto. subst.\n    assert (j' b1 = j1 b1). apply M. eapply Mem.valid_new_block; eauto.\n    rewrite H7 in H1. rewrite D in H1. inv H1. eelim Mem.fresh_block_alloc; eauto.\n  split. intros. destruct (eq_block b' tb1).\n    subst b'. rewrite (N _ _ _ H1) in H1.\n    destruct (eq_block b b1). subst b. rewrite D in H1; inv H1.\n    exploit (P id); auto. intros [X Y]. exists id; exists ty.\n    rewrite X; rewrite Y. repeat rewrite PTree.gss. auto.\n    rewrite E in H1; auto. elim H4. eapply Mem.mi_mappedblocks; eauto.\n    eapply Mem.valid_new_block; eauto.\n    eapply Q; eauto. unfold Mem.valid_block in *.\n    intro. eapply Mem.valid_block_alloc_inv in H7. destruct H7. eauto.\n    eauto. eauto.\n  split. intros. destruct (ident_eq id0 id).\n    (* same var *)\n    subst id0.\n    assert (ty0 = ty).\n      destruct H1. congruence. elim H9. unfold var_names. change id with (fst (id, ty0)). apply in_map; auto.\n    subst ty0.\n    exploit P; eauto. intros [X Y]. rewrite Heqb. rewrite X. rewrite Y.\n    exists b1. split. apply PTree.gss.\n    exists tb1; split.\n    apply PTree.gss.\n    rewrite M. auto. eapply Mem.valid_new_block; eauto.\n    (* other vars *)\n    exploit (O id0 ty0). destruct H1. congruence. auto.\n    rewrite PTree.gso; auto.\n  split. intros. exploit (P id0). tauto. intros [X Y]. rewrite X; rewrite Y.\n    split; apply PTree.gso; intuition.\n  intros. inv H1. unfold match_penv_meminj.\n  exploit Mem.alloc_result. apply H. intro.\n  exploit Mem.alloc_result. apply A. intro.\n  destruct H5 as (id0 & path0 & H5).\n  destruct H6 as (id1 & path1 & H6).\n  exploit Mem.stackseq_id_path; eauto. intros. inv H7.\n  exists id1 ,path1,idx1. split. congruence.\n  rewrite PTree.gss. rewrite M. rewrite D. rewrite H6. auto.\n  eapply Mem.valid_new_block. eauto.\n  exploit R; eauto. intros. unfold match_penv_meminj in H1.\n  destruct H1 as (id1 & path1 & pos1 & X & Y).\n  unfold match_penv_meminj. exists id1,path1,pos1. split. auto.\n  rewrite PTree.gso. eauto.\n  exploit nextblock_pos_succ. apply H5. eauto. intro.\n  assert (pos1 >= Pos.succ idx1)%positive.\n  destruct H1 as (id0 &path0 & H1).\n  exploit nextblock_alloc_vars; eauto. intros (p' & X' & Y').\n  rewrite X in X'. inv X'. lia. lia.\nQed.\n\nLemma alloc_variables_load:\n  forall e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  forall chunk b ofs v,\n  Mem.load chunk m b ofs = Some v ->\n  Mem.load chunk m' b ofs = Some v.\nProof.\n  induction 1; intros.\n  auto.\n  apply IHalloc_variables. eapply Mem.load_alloc_other; eauto.\nQed.\n\nLemma sizeof_by_value:\n  forall ty chunk,\n  access_mode ty = By_value chunk -> size_chunk chunk <= sizeof ge ty.\nProof.\n  unfold access_mode; intros.\n  assert (size_chunk chunk = sizeof ge ty).\n  {\n    destruct ty; try destruct i; try destruct s; try destruct f; inv H; auto;\n    unfold Mptr; simpl; destruct Archi.ptr64; auto.\n  }\n  lia.\nQed.\n\nDefinition env_initial_value (e: env) (m: mem) :=\n  forall id b ty chunk,\n  e!id = Some(b, ty) -> access_mode ty = By_value chunk -> Mem.load chunk m b 0 = Some Vundef.\n\nLemma alloc_variables_initial_value:\n  forall e m vars e' m',\n  alloc_variables ge e m vars e' m' ->\n  env_initial_value e m ->\n  env_initial_value e' m'.\nProof.\n  induction 1; intros.\n  auto.\n  apply IHalloc_variables. red; intros. rewrite PTree.gsspec in H2.\n  destruct (peq id0 id). inv H2.\n  eapply Mem.load_alloc_same'; eauto.\n  lia. rewrite Z.add_0_l. eapply sizeof_by_value; eauto.\n  apply Z.divide_0_r.\n  eapply Mem.load_alloc_other; eauto.\nQed.\n\nLemma create_undef_temps_charact:\n  forall id ty vars, In (id, ty) vars -> (create_undef_temps vars)!id = Some Vundef.\nProof.\n  induction vars; simpl; intros.\n  contradiction.\n  destruct H. subst a. apply PTree.gss.\n  destruct a as [id1 ty1]. rewrite PTree.gsspec. destruct (peq id id1); auto.\nQed.\n\nLemma create_undef_temps_inv:\n  forall vars id v, (create_undef_temps vars)!id = Some v -> v = Vundef /\\ In id (var_names vars).\nProof.\n  induction vars; simpl; intros.\n  rewrite PTree.gempty in H; congruence.\n  destruct a as [id1 ty1]. rewrite PTree.gsspec in H. destruct (peq id id1).\n  inv H. auto.\n  exploit IHvars; eauto. tauto.\nQed.\n\nLemma create_undef_temps_exten:\n  forall id l1 l2,\n  (In id (var_names l1) <-> In id (var_names l2)) ->\n  (create_undef_temps l1)!id = (create_undef_temps l2)!id.\nProof.\n  assert (forall id l1 l2,\n          (In id (var_names l1) -> In id (var_names l2)) ->\n          (create_undef_temps l1)!id = None \\/ (create_undef_temps l1)!id = (create_undef_temps l2)!id).\n    intros. destruct ((create_undef_temps l1)!id) as [v1|] eqn:?; auto.\n    exploit create_undef_temps_inv; eauto. intros [A B]. subst v1.\n    exploit list_in_map_inv. unfold var_names in H. apply H. eexact B.\n    intros [[id1 ty1] [P Q]]. simpl in P; subst id1.\n    right; symmetry; eapply create_undef_temps_charact; eauto.\n  intros.\n  exploit (H id l1 l2). tauto.\n  exploit (H id l2 l1). tauto.\n  intuition congruence.\nQed.\n\nRemark var_names_app:\n  forall vars1 vars2, var_names (vars1 ++ vars2) = var_names vars1 ++ var_names vars2.\nProof.\n  intros. apply map_app.\nQed.\n\nRemark filter_app:\n  forall (A: Type) (f: A -> bool) l1 l2,\n  List.filter f (l1 ++ l2) = List.filter f l1 ++ List.filter f l2.\nProof.\n  induction l1; simpl; intros.\n  auto.\n  destruct (f a). simpl. decEq; auto. auto.\nQed.\n\nRemark filter_charact:\n  forall (A: Type) (f: A -> bool) x l,\n  In x (List.filter f l) <-> In x l /\\ f x = true.\nProof.\n  induction l; simpl. tauto.\n  destruct (f a) eqn:?.\n  simpl. rewrite IHl. intuition congruence.\n  intuition congruence.\nQed.\n\nRemark filter_norepet:\n  forall (A: Type) (f: A -> bool) l,\n  list_norepet l -> list_norepet (List.filter f l).\nProof.\n  induction 1; simpl. constructor.\n  destruct (f hd); auto. constructor; auto. rewrite filter_charact. tauto.\nQed.\n\nRemark filter_map:\n  forall (A B: Type) (f: A -> B) (pa: A -> bool) (pb: B -> bool),\n  (forall a, pb (f a) = pa a) ->\n  forall l, List.map f (List.filter pa l) = List.filter pb (List.map f l).\nProof.\n  induction l; simpl.\n  auto.\n  rewrite H. destruct (pa a); simpl; congruence.\nQed.\n\nLemma create_undef_temps_lifted:\n  forall id f,\n  ~ In id (var_names (fn_params f)) ->\n  (create_undef_temps (add_lifted (cenv_for f) (fn_vars f) (fn_temps f))) ! id =\n  (create_undef_temps (add_lifted (cenv_for f) (fn_params f ++ fn_vars f) (fn_temps f))) ! id.\nProof.\n  intros. apply create_undef_temps_exten.\n  unfold add_lifted. rewrite filter_app.\n  unfold var_names in *.\n  repeat rewrite map_app. repeat rewrite in_app. intuition.\n  exploit list_in_map_inv; eauto. intros [[id1 ty1] [P Q]]. simpl in P. subst id.\n  rewrite filter_charact in Q. destruct Q.\n  elim H. change id1 with (fst (id1, ty1)). apply List.in_map. auto.\nQed.\n\nLemma vars_and_temps_properties:\n  forall cenv params vars temps,\n  list_norepet (var_names params ++ var_names vars) ->\n  list_disjoint (var_names params) (var_names temps) ->\n  list_norepet (var_names params)\n  /\\ list_norepet (var_names (remove_lifted cenv (params ++ vars)))\n  /\\ list_disjoint (var_names params) (var_names (add_lifted cenv vars temps)).\nProof.\n  intros. rewrite list_norepet_app in H. destruct H as [A [B C]].\n  split. auto.\n  split. unfold remove_lifted. unfold var_names. erewrite filter_map.\n  instantiate (1 := fun a => negb (VSet.mem a cenv)). 2: auto.\n  apply filter_norepet. rewrite map_app. apply list_norepet_append; assumption.\n  unfold add_lifted. rewrite var_names_app.\n  unfold var_names at 2. erewrite filter_map.\n  instantiate (1 := fun a => VSet.mem a cenv). 2: auto.\n  change (map fst vars) with (var_names vars).\n  red; intros.\n  rewrite in_app in H1. destruct H1.\n  rewrite filter_charact in H1. destruct H1. apply C; auto.\n  apply H0; auto.\nQed.\n\nTheorem match_envs_alloc_variables:\n  forall cenv m vars e m' temps j tm blocks pe idx1 idx2,\n  alloc_variables' ge empty_env m vars blocks e m' ->\n  list_norepet (var_names vars) ->\n  Mem.inject j m tm ->\n  Mem.stackseq m tm ->\n  pe = build_penv cenv vars idx1 idx2 ->\n  nextblock_pos m idx1 ->\n  nextblock_pos tm idx2 ->\n  (forall id ty, In (id, ty) vars -> VSet.mem id cenv = true ->\n                     exists chunk, access_mode ty = By_value chunk) ->\n  (forall id, VSet.mem id cenv = true -> In id (var_names vars)) ->\n  exists j', exists te, exists tm',\n     alloc_variables tge empty_env tm (remove_lifted cenv vars) te tm'\n  /\\ match_envs j' cenv e (create_undef_temps temps) m' (Mem.support m) (Mem.support m')\n                        te (create_undef_temps (add_lifted cenv vars temps)) (Mem.support tm) (Mem.support tm')\n  /\\ Mem.inject j' m' tm'\n  /\\ inject_incr j j'\n  /\\ (forall b, Mem.valid_block m b -> j' b = j b)\n  /\\ (forall b b' delta, j' b = Some(b', delta) -> Mem.valid_block tm b' -> j' b = j b)\n  /\\ (forall id ty, In (id, ty) vars -> VSet.mem id cenv = false -> exists b, te!id = Some(b, ty))\n  /\\ (forall b, In b blocks -> match_penv_meminj b pe j').\nProof.\n  intros.\n  exploit (match_alloc_variables' cenv); eauto. instantiate (1 := empty_env).\n  intros [j' [te [tm' [A [B [C [D [E [K [F [G I]]]]]]]]]]].\n  exists j'; exists te; exists tm'.\n  split. auto. split; auto.\n  constructor; intros.\n  (* vars *)\n  destruct (In_dec ident_eq id (var_names vars)).\n  unfold var_names in i. exploit list_in_map_inv; eauto.\n  intros [[id' ty] [EQ IN]]; simpl in EQ; subst id'.\n  exploit F; eauto. intros [b [P R]].\n  destruct (VSet.mem id cenv) eqn:?.\n  (* local var, lifted *)\n  destruct R as [U V]. exploit H6; eauto. intros [chunk X].\n  eapply match_var_lifted with (v := Vundef) (tv := Vundef); eauto.\n  rewrite U; apply PTree.gempty.\n  eapply alloc_variables_initial_value; eauto.\n  eapply alloc_var'_var; eauto.\n   red. unfold empty_env; intros. rewrite PTree.gempty in H8; congruence.\n  apply create_undef_temps_charact with ty.\n  unfold add_lifted. apply in_or_app. left.\n  rewrite filter_In. auto.\n  (* local var, not lifted *)\n  destruct R as [tb [U V]].\n  eapply match_var_not_lifted; eauto.\n  (* non-local var *)\n  exploit G; eauto. unfold empty_env. rewrite PTree.gempty. intros [U V].\n  eapply match_var_not_local; eauto.\n  destruct (VSet.mem id cenv) eqn:?; auto.\n  elim n; eauto.\n\n  (* temps *)\n  exploit create_undef_temps_inv; eauto. intros [P Q]. subst v.\n  unfold var_names in Q. exploit list_in_map_inv; eauto.\n  intros [[id1 ty] [EQ IN]]; simpl in EQ; subst id1.\n  split; auto. exists Vundef; split; auto.\n  apply create_undef_temps_charact with ty. unfold add_lifted.\n  apply in_or_app; auto.\n\n  (* injective *)\n  eapply alloc_variables_injective.\n  eapply alloc_var'_var; eauto.\n  rewrite PTree.gempty. congruence.\n  intros. rewrite PTree.gempty in H11. congruence.\n  eauto. eauto. auto.\n\n  (* range *)\n  exploit alloc_variables_range. eapply alloc_var'_var. eexact H. eauto.\n  rewrite PTree.gempty. intuition congruence.\n\n  (* trange *)\n  exploit alloc_variables_range. eexact A. eauto.\n  rewrite PTree.gempty. intuition congruence.\n\n  (* mapped *)\n  destruct (In_dec ident_eq id (var_names vars)).\n  unfold var_names in i. exploit list_in_map_inv; eauto.\n  intros [[id' ty'] [EQ IN]]; simpl in EQ; subst id'.\n  exploit F; eauto. intros [b [P Q]].\n  destruct (VSet.mem id cenv).\n  rewrite PTree.gempty in Q. destruct Q; congruence.\n  destruct Q as [tb [U V]]. exists b; split; congruence.\n  exploit G; eauto. rewrite PTree.gempty. intuition congruence.\n\n  (* flat *)\n  exploit alloc_variables_range. eexact A. eauto.\n  rewrite PTree.gempty. intros [P|P]. congruence.\n  exploit K; eauto. unfold Mem.valid_block. destruct P. auto.\n  intros [id0 [ty0 [U [V W]]]]. split; auto.\n  destruct (ident_eq id id0). congruence.\n  assert (b' <> b').\n  eapply alloc_variables_injective with (e' := te) (id1 := id) (id2 := id0); eauto.\n  rewrite PTree.gempty; congruence.\n  intros until ty1; rewrite PTree.gempty; congruence.\n  congruence.\n\n  (* incr *)\n  eapply alloc_variables_support; eapply alloc_var'_var; eauto.\n  eapply alloc_variables_support; eauto.\n\n  (* other properties *)\n  intuition auto. edestruct F as (b & X & Y); eauto. rewrite H10 in Y.\n  destruct Y as (tb & U & V). exists tb; auto.\nQed.\n\nLemma assign_loc_inject:\n  forall f ty m loc ofs v m' tm loc' ofs' v',\n  assign_loc ge ty m loc ofs v m' ->\n  Val.inject f (Vptr loc ofs) (Vptr loc' ofs') ->\n  Val.inject f v v' ->\n  Mem.inject f m tm ->\n  exists tm',\n     assign_loc tge ty tm loc' ofs' v' tm'\n  /\\ Mem.inject f m' tm'\n  /\\ (forall b chunk v,\n      f b = None -> Mem.load chunk m b 0 = Some v -> Mem.load chunk m' b 0 = Some v).\nProof.\n  intros. inv H.\n- (* by value *)\n  exploit Mem.storev_mapped_inject; eauto. intros [tm' [A B]].\n  exists tm'; split. eapply assign_loc_value; eauto.\n  split. auto.\n  intros. rewrite <- H5. eapply Mem.load_store_other; eauto.\n  left. inv H0. congruence.\n- (* by copy *)\n  inv H0. inv H1.\n  rename b' into bsrc. rename ofs'0 into osrc.\n  rename loc into bdst. rename ofs into odst.\n  rename loc' into bdst'. rename b2 into bsrc'.\n  rewrite <- comp_env_preserved in *.\n  destruct (zeq (sizeof tge ty) 0).\n+ (* special case size = 0 *)\n  assert (bytes = nil).\n  { exploit (Mem.loadbytes_empty m bsrc (Ptrofs.unsigned osrc) (sizeof tge ty)).\n    lia. congruence. }\n  subst.\n  destruct (Mem.range_perm_storebytes tm bdst' (Ptrofs.unsigned (Ptrofs.add odst (Ptrofs.repr delta))) nil)\n  as [tm' SB].\n  simpl. red; intros; extlia.\n  exists tm'.\n  split. eapply assign_loc_copy; eauto.\n  intros; extlia.\n  intros; extlia.\n  rewrite e; right; lia.\n  apply Mem.loadbytes_empty. lia.\n  split. eapply Mem.storebytes_empty_inject; eauto.\n  intros. rewrite <- H0. eapply Mem.load_storebytes_other; eauto.\n  left. congruence.\n+ (* general case size > 0 *)\n  exploit Mem.loadbytes_length; eauto. intros LEN.\n  assert (SZPOS: sizeof tge ty > 0).\n  { generalize (sizeof_pos tge ty); lia. }\n  assert (RPSRC: Mem.range_perm m bsrc (Ptrofs.unsigned osrc) (Ptrofs.unsigned osrc + sizeof tge ty) 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 (Ptrofs.unsigned odst) (Ptrofs.unsigned odst + sizeof tge ty) Cur Nonempty).\n    replace (sizeof tge ty) with (Z.of_nat (List.length bytes)).\n    eapply Mem.range_perm_implies. eapply Mem.storebytes_range_perm; eauto. auto with mem.\n    rewrite LEN. apply Z2Nat.id. lia.\n  assert (PSRC: Mem.perm m bsrc (Ptrofs.unsigned osrc) Cur Nonempty).\n    apply RPSRC. lia.\n  assert (PDST: Mem.perm m bdst (Ptrofs.unsigned odst) Cur Nonempty).\n    apply RPDST. lia.\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 [tm' [C D]].\n  exists tm'.\n  split. eapply assign_loc_copy; try rewrite EQ1; try rewrite EQ2; eauto.\n  intros; eapply Mem.aligned_area_inject with (m := m); eauto.\n  apply alignof_blockcopy_1248.\n  apply sizeof_alignof_blockcopy_compat.\n  intros; eapply Mem.aligned_area_inject with (m := m); eauto.\n  apply alignof_blockcopy_1248.\n  apply sizeof_alignof_blockcopy_compat.\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. auto.\n  intros. rewrite <- H0. eapply Mem.load_storebytes_other; eauto.\n  left. congruence.\nQed.\n\nLemma assign_loc_support:\n  forall ge ty m b ofs v m',\n  assign_loc ge ty m b ofs v m' -> Mem.support m' = Mem.support m.\nProof.\n  induction 1.\n  simpl in H0. eapply Mem.support_store; eauto.\n  eapply Mem.support_storebytes; eauto.\nQed.\n\nTheorem store_params_correct:\n  forall j f k cenv le lo hi te tlo thi e m params args m',\n  bind_parameters ge e m params args m' ->\n  forall s tm tle1 tle2 targs,\n  list_norepet (var_names params) ->\n  list_forall2 val_casted args (map snd params) ->\n  Val.inject_list j args targs ->\n  match_envs j cenv e le m lo hi te tle1 tlo thi ->\n  Mem.inject j m tm ->\n  (forall id, ~In id (var_names params) -> tle2!id = tle1!id) ->\n  (forall id, In id (var_names params) -> le!id = None) ->\n  exists tle, exists tm',\n  star (step2 fn_stack_requirements)\n       tge (State f (store_params cenv params s) k te tle tm)\n              E0 (State f s k te tle tm')\n  /\\ bind_parameter_temps params targs tle2 = Some tle\n  /\\ Mem.inject j m' tm'\n  /\\ match_envs j cenv e le m' lo hi te tle tlo thi\n  /\\ Mem.support tm' = Mem.support tm.\nProof.\n  induction 1; simpl; intros until targs; intros NOREPET CASTED VINJ MENV MINJ TLE LE.\n  (* base case *)\n  inv VINJ. exists tle2; exists tm; split. apply star_refl. split. auto. split. auto.\n  split. apply match_envs_temps_exten with tle1; auto. auto.\n  (* inductive case *)\n  inv NOREPET. inv CASTED. inv VINJ.\n  exploit me_vars; eauto. instantiate (1 := id); intros MV.\n  destruct (VSet.mem id cenv) eqn:?.\n  (* lifted to temp *)\n  eapply IHbind_parameters with (tle1 := PTree.set id v' tle1); eauto.\n  eapply match_envs_assign_lifted; eauto.\n  inv MV; try congruence. rewrite ENV in H; inv H.\n  inv H0; try congruence.\n  unfold Mem.storev in H2. eapply Mem.store_unmapped_inject; eauto.\n  intros. repeat rewrite PTree.gsspec. destruct (peq id0 id). auto.\n  apply TLE. intuition.\n  (* still in memory *)\n  inv MV; try congruence. rewrite ENV in H; inv H.\n  exploit assign_loc_inject; eauto.\n  intros [tm1 [A [B C]]].\n  exploit IHbind_parameters. eauto. eauto. eauto.\n  instantiate (1 := PTree.set id v' tle1).\n  apply match_envs_change_temp.\n  eapply match_envs_invariant; eauto.\n  apply LE; auto. auto.\n  eauto.\n  instantiate (1 := PTree.set id v' tle2).\n  intros. repeat rewrite PTree.gsspec. destruct (peq id0 id). auto.\n  apply TLE. intuition.\n  intros. apply LE. auto.\n  instantiate (1 := s).\n  intros [tle [tm' [U [V [X [Y Z]]]]]].\n  exists tle; exists tm'; split.\n  eapply star_trans.\n  eapply star_left. econstructor.\n  eapply star_left. econstructor.\n    eapply eval_Evar_local. eauto.\n    eapply eval_Etempvar. erewrite bind_parameter_temps_inv; eauto.\n    apply PTree.gss.\n    simpl. instantiate (1 := v'). apply cast_val_casted.\n    eapply val_casted_inject with (v := v1); eauto.\n    simpl. eexact A.\n  apply star_one. constructor.\n  reflexivity. reflexivity.\n  eexact U.\n  traceEq.\n  rewrite (assign_loc_support _ _ _ _ _ _ _ A) in Z. auto.\nQed.\n\nLemma bind_parameters_support:\n  forall ge e m params args m',\n  bind_parameters ge e m params args m' -> Mem.support m' = Mem.support m.\nProof.\n  induction 1.\n  auto.\n  rewrite IHbind_parameters. eapply assign_loc_support; eauto.\nQed.\n\nLemma bind_parameters_load:\n  forall ge e chunk b ofs,\n  (forall id b' ty, e!id = Some(b', ty) -> b <> b') ->\n  forall m params args m',\n  bind_parameters ge e m params args m' ->\n  Mem.load chunk m' b ofs = Mem.load chunk m b ofs.\nProof.\n  induction 2.\n  auto.\n  rewrite IHbind_parameters.\n  assert (b <> b0) by eauto.\n  inv H1.\n  simpl in H5. eapply Mem.load_store_other; eauto.\n  eapply Mem.load_storebytes_other; eauto.\nQed.\n\n(** Freeing of local variables *)\n\nLemma free_blocks_of_env_perm_1:\n  forall ce m e m' id b ty ofs k p,\n  Mem.free_list m (blocks_of_env ce e) = Some m' ->\n  e!id = Some(b, ty) ->\n  Mem.perm m' b ofs k p ->\n  0 <= ofs < sizeof ce ty ->\n  False.\nProof.\n  intros. exploit Mem.perm_free_list; eauto. intros [A B].\n  apply B with 0 (sizeof ce ty); auto.\n  unfold blocks_of_env. change (b, 0, sizeof ce ty) with (block_of_binding ce (id, (b, ty))).\n  apply in_map. apply PTree.elements_correct. auto.\nQed.\n\nLemma free_list_perm':\n  forall b lo hi l m m',\n  Mem.free_list m l = Some m' ->\n  In (b, lo, hi) l ->\n  Mem.range_perm m b lo hi Cur Freeable.\nProof.\n  induction l; simpl; intros.\n  contradiction.\n  destruct a as [[b1 lo1] hi1].\n  destruct (Mem.free m b1 lo1 hi1) as [m1|] eqn:?; try discriminate.\n  destruct H0. inv H0. eapply Mem.free_range_perm; eauto.\n  red; intros. eapply Mem.perm_free_3; eauto. eapply IHl; eauto.\nQed.\n\nLemma free_blocks_of_env_perm_2:\n  forall ce m e m' id b ty,\n  Mem.free_list m (blocks_of_env ce e) = Some m' ->\n  e!id = Some(b, ty) ->\n  Mem.range_perm m b 0 (sizeof ce ty) Cur Freeable.\nProof.\n  intros. eapply free_list_perm'; eauto.\n  unfold blocks_of_env. change (b, 0, sizeof ce ty) with (block_of_binding ce (id, (b, ty))).\n  apply in_map. apply PTree.elements_correct. auto.\nQed.\n\nFixpoint freelist_no_overlap (l: list (block * Z * Z)) : Prop :=\n  match l with\n  | nil => True\n  | (b, lo, hi) :: l' =>\n      freelist_no_overlap l' /\\\n      (forall b' lo' hi', In (b', lo', hi') l' ->\n       b' <> b \\/ hi' <= lo \\/ hi <= lo')\n  end.\n\nLemma can_free_list:\n  forall l m,\n  (forall b lo hi, In (b, lo, hi) l -> Mem.range_perm m b lo hi Cur Freeable) ->\n  freelist_no_overlap l ->\n  exists m', Mem.free_list m l = Some m'.\nProof.\n  induction l; simpl; intros.\n- exists m; auto.\n- destruct a as [[b lo] hi]. destruct H0.\n  destruct (Mem.range_perm_free m b lo hi) as [m1 A]; auto.\n  rewrite A. apply IHl; auto.\n  intros. red; intros. eapply Mem.perm_free_1; eauto.\n  exploit H1; eauto. intros [B|B]. auto. right; lia.\n  eapply H; eauto.\nQed.\n\nLemma blocks_of_env_no_overlap:\n  forall (ge: genv) j cenv e le m lo hi te tle tlo thi tm,\n  match_envs j cenv e le m lo hi te tle tlo thi ->\n  Mem.inject j m tm ->\n  (forall id b ty,\n   e!id = Some(b, ty) -> Mem.range_perm m b 0 (sizeof ge ty) Cur Freeable) ->\n  forall l,\n  list_norepet (List.map fst l) ->\n  (forall id bty, In (id, bty) l -> te!id = Some bty) ->\n  freelist_no_overlap (List.map (block_of_binding ge) l).\nProof.\n  intros until tm; intros ME MINJ PERMS. induction l; simpl; intros.\n- auto.\n- destruct a as [id [b ty]]. simpl in *. inv H. split.\n  + apply IHl; auto.\n  + intros. exploit list_in_map_inv; eauto. intros [[id' [b'' ty']] [A B]].\n    simpl in A. inv A. rename b'' into b'.\n    assert (TE: te!id = Some(b, ty)) by eauto.\n    assert (TE': te!id' = Some(b', ty')) by eauto.\n    exploit me_mapped. eauto. eexact TE. intros [b0 [INJ E]].\n    exploit me_mapped. eauto. eexact TE'. intros [b0' [INJ' E']].\n    destruct (zle (sizeof ge0 ty) 0); auto.\n    destruct (zle (sizeof ge0 ty') 0); auto.\n    assert (b0 <> b0').\n    { eapply me_inj; eauto. red; intros; subst; elim H3.\n      change id' with (fst (id', (b', ty'))). apply List.in_map; auto. }\n    assert (Mem.perm m b0 0 Max Nonempty).\n    { apply Mem.perm_cur_max. apply Mem.perm_implies with Freeable.\n      eapply PERMS; eauto. lia. auto with mem. }\n    assert (Mem.perm m b0' 0 Max Nonempty).\n    { apply Mem.perm_cur_max. apply Mem.perm_implies with Freeable.\n      eapply PERMS; eauto. lia. auto with mem. }\n    exploit Mem.mi_no_overlap; eauto. intros [A|A]. auto. extlia.\nQed.\n\nLemma free_list_right_inject:\n  forall j m1 l m2 m2',\n  Mem.inject j m1 m2 ->\n  Mem.free_list m2 l = Some m2' ->\n  (forall b1 b2 delta lo hi ofs k p,\n     j b1 = Some(b2, delta) -> In (b2, lo, hi) l ->\n     Mem.perm m1 b1 ofs k p -> lo <= ofs + delta < hi -> False) ->\n  Mem.inject j m1 m2'.\nProof.\n  induction l; simpl; intros.\n  congruence.\n  destruct a as [[b lo] hi]. destruct (Mem.free m2 b lo hi) as [m21|] eqn:?; try discriminate.\n  eapply IHl with (m2 := m21); eauto.\n  eapply Mem.free_right_inject; eauto.\nQed.\n\nLemma blocks_of_env_translated:\n  forall e, blocks_of_env tge e = blocks_of_env ge e.\nProof.\n  intros. unfold blocks_of_env, block_of_binding.\n  rewrite comp_env_preserved; auto.\nQed.\n\nTheorem match_envs_free_blocks:\n  forall j cenv e le m lo hi te tle tlo thi m' tm,\n  match_envs j cenv e le m lo hi te tle tlo thi ->\n  Mem.inject j m tm ->\n  Mem.free_list m (blocks_of_env ge e) = Some m' ->\n  exists tm',\n     Mem.free_list tm (blocks_of_env tge te) = Some tm'\n  /\\ Mem.inject j m' tm'.\nProof.\n  intros.\nLocal Opaque ge tge.\n  assert (X: exists tm', Mem.free_list tm (blocks_of_env tge te) = Some tm').\n  {\n    rewrite blocks_of_env_translated. apply can_free_list.\n  - (* permissions *)\n    intros. unfold blocks_of_env in H2.\n    exploit list_in_map_inv; eauto. intros [[id [b' ty]] [EQ IN]].\n    unfold block_of_binding in EQ; inv EQ.\n    exploit me_mapped; eauto. eapply PTree.elements_complete; eauto.\n    intros [b [A B]].\n    change 0 with (0 + 0). replace (sizeof ge ty) with (sizeof ge ty + 0) by lia.\n    eapply Mem.range_perm_inject; eauto.\n    eapply free_blocks_of_env_perm_2; eauto.\n  - (* no overlap *)\n    unfold blocks_of_env; eapply blocks_of_env_no_overlap; eauto.\n    intros. eapply free_blocks_of_env_perm_2; eauto.\n    apply PTree.elements_keys_norepet.\n    intros. apply PTree.elements_complete; auto.\n  }\n  destruct X as [tm' FREE].\n  exists tm'; split; auto.\n  eapply free_list_right_inject; eauto.\n  eapply Mem.free_list_left_inject; eauto.\n  intros. unfold blocks_of_env in H3. exploit list_in_map_inv; eauto.\n  intros [[id [b' ty]] [EQ IN]]. unfold block_of_binding in EQ. inv EQ.\n  exploit me_flat; eauto. apply PTree.elements_complete; eauto.\n  intros [P Q]. subst delta. eapply free_blocks_of_env_perm_1 with (m := m); eauto.\n  rewrite <- comp_env_preserved. lia.\nQed.\n\n(** Matching global environments *)\n\nInductive match_globalenvs (f: meminj) (bound: sup): Prop :=\n  | mk_match_globalenvs\n      (DOMAIN: forall b, sup_In b bound -> f b = Some(b, 0))\n      (IMAGE: forall b1 b2 delta, f b1 = Some(b2, delta) -> sup_In b2 bound -> b1 = b2)\n      (SYMBOLS: forall id b, Genv.find_symbol ge id = Some b -> sup_In b bound)\n      (FUNCTIONS: forall b fd, Genv.find_funct_ptr ge b = Some fd -> sup_In b bound)\n      (VARINFOS: forall b gv, Genv.find_var_info ge b = Some gv -> sup_In b bound).\n\nLemma match_globalenvs_preserves_globals:\n  forall f,\n  (exists bound, match_globalenvs f bound) ->\n  meminj_preserves_globals ge f.\nProof.\n  intros. destruct H as [bound MG]. inv MG.\n  split; intros. eauto. split; intros. eauto. symmetry. eapply IMAGE; eauto.\nQed.\n\n(** Evaluation of expressions *)\n\nSection EVAL_EXPR.\n\nVariables e te: env.\nVariables le tle: temp_env.\nVariables m tm: mem.\nVariable f: meminj.\nVariable cenv: compilenv.\nVariables lo hi tlo thi: sup.\nHypothesis MATCH: match_envs f cenv e le m lo hi te tle tlo thi.\nHypothesis MEMINJ: Mem.inject f m tm.\nHypothesis GLOB: exists bound, match_globalenvs f bound.\n\nLemma typeof_simpl_expr:\n  forall a, typeof (simpl_expr cenv a) = typeof a.\nProof.\n  destruct a; simpl; auto. destruct (VSet.mem i cenv); auto.\nQed.\n\nLemma deref_loc_inject:\n  forall ty loc ofs v loc' ofs',\n  deref_loc ty m loc ofs v ->\n  Val.inject f (Vptr loc ofs) (Vptr loc' ofs') ->\n  exists tv, deref_loc ty tm loc' ofs' tv /\\ Val.inject f v tv.\nProof.\n  intros. inv H.\n  (* by value *)\n  exploit Mem.loadv_inject; eauto. intros [tv [A B]].\n  exists tv; split; auto. eapply deref_loc_value; eauto.\n  (* by reference *)\n  exists (Vptr loc' ofs'); split; auto. eapply deref_loc_reference; eauto.\n  (* by copy *)\n  exists (Vptr loc' ofs'); split; auto. eapply deref_loc_copy; eauto.\nQed.\n\nLemma eval_simpl_expr:\n  forall a v,\n  eval_expr ge e le m a v ->\n  compat_cenv (addr_taken_expr a) cenv ->\n  exists tv, eval_expr tge te tle tm (simpl_expr cenv a) tv /\\ Val.inject f v tv\n\nwith eval_simpl_lvalue:\n  forall a b ofs,\n  eval_lvalue ge e le m a b ofs ->\n  compat_cenv (addr_taken_expr a) cenv ->\n  match a with Evar id ty => VSet.mem id cenv = false | _ => True end ->\n  exists b', exists ofs', eval_lvalue tge te tle tm (simpl_expr cenv a) b' ofs' /\\ Val.inject f (Vptr b ofs) (Vptr b' ofs').\n\nProof.\n  destruct 1; simpl; intros.\n(* const *)\n  exists (Vint i); split; auto. constructor.\n  exists (Vfloat f0); split; auto. constructor.\n  exists (Vsingle f0); split; auto. constructor.\n  exists (Vlong i); split; auto. constructor.\n(* tempvar *)\n  exploit me_temps; eauto. intros [[tv [A B]] C].\n  exists tv; split; auto. constructor; auto.\n(* addrof *)\n  exploit eval_simpl_lvalue; eauto.\n  destruct a; auto with compat.\n  destruct a; auto. destruct (VSet.mem i cenv) eqn:?; auto.\n  elim (H0 i). apply VSet.singleton_2. auto. apply VSet.mem_2. auto.\n  intros [b' [ofs' [A B]]].\n  exists (Vptr b' ofs'); split; auto. constructor; auto.\n(* unop *)\n  exploit eval_simpl_expr; eauto. intros [tv1 [A B]].\n  exploit sem_unary_operation_inject; eauto. intros [tv [C D]].\n  exists tv; split; auto. econstructor; eauto. rewrite typeof_simpl_expr; auto.\n(* binop *)\n  exploit eval_simpl_expr. eexact H. eauto with compat. intros [tv1 [A B]].\n  exploit eval_simpl_expr. eexact H0. eauto with compat. intros [tv2 [C D]].\n  exploit sem_binary_operation_inject; eauto. intros [tv [E F]].\n  exists tv; split; auto. econstructor; eauto.\n  repeat rewrite typeof_simpl_expr; rewrite comp_env_preserved; auto.\n(* cast *)\n  exploit eval_simpl_expr; eauto. intros [tv1 [A B]].\n  exploit sem_cast_inject; eauto. intros [tv2 [C D]].\n  exists tv2; split; auto. econstructor. eauto. rewrite typeof_simpl_expr; auto.\n(* sizeof *)\n  econstructor; split. constructor. rewrite comp_env_preserved; auto.\n(* alignof *)\n  econstructor; split. constructor. rewrite comp_env_preserved; auto.\n(* rval *)\n  assert (EITHER: (exists id, exists ty, a = Evar id ty /\\ VSet.mem id cenv = true)\n               \\/ (match a with Evar id _ => VSet.mem id cenv = false | _ => True end)).\n    destruct a; auto. destruct (VSet.mem i cenv) eqn:?; auto. left; exists i; exists t; auto.\n  destruct EITHER as [ [id [ty [EQ OPT]]] | NONOPT ].\n  (* a variable pulled out of memory *)\n  subst a. simpl. rewrite OPT.\n  exploit me_vars; eauto. instantiate (1 := id). intros MV.\n  inv H; inv MV; try congruence.\n  rewrite ENV in H6; inv H6.\n  inv H0; try congruence.\n  assert (chunk0 = chunk). simpl in H. congruence. subst chunk0.\n  assert (v0 = v). unfold Mem.loadv in H2. rewrite Ptrofs.unsigned_zero in H2. congruence. subst v0.\n  exists tv; split; auto. constructor; auto.\n  simpl in H; congruence.\n  simpl in H; congruence.\n  (* any other l-value *)\n  exploit eval_simpl_lvalue; eauto. intros [loc' [ofs' [A B]]].\n  exploit deref_loc_inject; eauto. intros [tv [C D]].\n  exists tv; split; auto. econstructor. eexact A. rewrite typeof_simpl_expr; auto.\n\n(* lvalues *)\n  destruct 1; simpl; intros.\n(* local var *)\n  rewrite H1.\n  exploit me_vars; eauto. instantiate (1 := id). intros MV. inv MV; try congruence.\n  rewrite ENV in H; inv H.\n  exists b'; exists Ptrofs.zero; split.\n  apply eval_Evar_local; auto.\n  econstructor; eauto.\n(* global var *)\n  rewrite H2.\n  exploit me_vars; eauto. instantiate (1 := id). intros MV. inv MV; try congruence.\n  exists l; exists Ptrofs.zero; split.\n  apply eval_Evar_global. auto. rewrite <- H0. apply symbols_preserved.\n  destruct GLOB as [bound GLOB1]. inv GLOB1.\n  econstructor; eauto.\n(* deref *)\n  exploit eval_simpl_expr; eauto. intros [tv [A B]].\n  inversion B. subst.\n  econstructor; econstructor; split; eauto. econstructor; eauto.\n(* field struct *)\n  rewrite <- comp_env_preserved in *.\n  exploit eval_simpl_expr; eauto. intros [tv [A B]].\n  inversion B. subst.\n  econstructor; econstructor; split.\n  eapply eval_Efield_struct; eauto. rewrite typeof_simpl_expr; eauto.\n  econstructor; eauto. repeat rewrite Ptrofs.add_assoc. decEq. apply Ptrofs.add_commut.\n(* field union *)\n  rewrite <- comp_env_preserved in *.\n  exploit eval_simpl_expr; eauto. intros [tv [A B]].\n  inversion B. subst.\n  econstructor; econstructor; split.\n  eapply eval_Efield_union; eauto. rewrite typeof_simpl_expr; eauto. auto.\nQed.\n\nLemma eval_simpl_exprlist:\n  forall al tyl vl,\n  eval_exprlist ge e le m al tyl vl ->\n  compat_cenv (addr_taken_exprlist al) cenv ->\n  val_casted_list vl tyl /\\\n  exists tvl,\n     eval_exprlist tge te tle tm (simpl_exprlist cenv al) tyl tvl\n  /\\ Val.inject_list f vl tvl.\nProof.\n  induction 1; simpl; intros.\n  split. constructor. econstructor; split. constructor. auto.\n  exploit eval_simpl_expr; eauto with compat. intros [tv1 [A B]].\n  exploit sem_cast_inject; eauto. intros [tv2 [C D]].\n  exploit IHeval_exprlist; eauto with compat. intros [E [tvl [F G]]].\n  split. constructor; auto. eapply cast_val_is_casted; eauto.\n  exists (tv2 :: tvl); split. econstructor; eauto.\n  rewrite typeof_simpl_expr; auto.\n  econstructor; eauto.\nQed.\n\nEnd EVAL_EXPR.\n\n(** Matching continuations *)\n\nInductive match_cont (f: meminj): compilenv -> cont -> cont -> mem -> sup -> sup -> Prop :=\n  | match_Kstop: forall cenv m bound tbound hi,\n      match_globalenvs f hi -> Mem.sup_include hi bound -> Mem.sup_include hi tbound ->\n      match_cont f cenv Kstop Kstop m bound tbound\n  | match_Kseq: forall cenv s k ts tk m bound tbound,\n      simpl_stmt cenv s = OK ts ->\n      match_cont f cenv k tk m bound tbound ->\n      compat_cenv (addr_taken_stmt s) cenv ->\n      match_cont f cenv (Kseq s k) (Kseq ts tk) m bound tbound\n  | match_Kloop1: forall cenv s1 s2 k ts1 ts2 tk m bound tbound,\n      simpl_stmt cenv s1 = OK ts1 ->\n      simpl_stmt cenv s2 = OK ts2 ->\n      match_cont f cenv k tk m bound tbound ->\n      compat_cenv (VSet.union (addr_taken_stmt s1) (addr_taken_stmt s2)) cenv ->\n      match_cont f cenv (Kloop1 s1 s2 k) (Kloop1 ts1 ts2 tk) m bound tbound\n  | match_Kloop2: forall cenv s1 s2 k ts1 ts2 tk m bound tbound,\n      simpl_stmt cenv s1 = OK ts1 ->\n      simpl_stmt cenv s2 = OK ts2 ->\n      match_cont f cenv k tk m bound tbound ->\n      compat_cenv (VSet.union (addr_taken_stmt s1) (addr_taken_stmt s2)) cenv ->\n      match_cont f cenv (Kloop2 s1 s2 k) (Kloop2 ts1 ts2 tk) m bound tbound\n  | match_Kswitch: forall cenv k tk m bound tbound,\n      match_cont f cenv k tk m bound tbound ->\n      match_cont f cenv (Kswitch k) (Kswitch tk) m bound tbound\n  | match_Kcall: forall cenv optid fn e le k tfn te tle tk m hi thi lo tlo bound tbound x,\n      transf_function fn = OK tfn ->\n      match_envs f (cenv_for fn) e le m lo hi te tle tlo thi ->\n      match_cont f (cenv_for fn) k tk m lo tlo ->\n      check_opttemp (cenv_for fn) optid = OK x ->\n      Mem.sup_include hi bound -> Mem.sup_include thi tbound ->\n      match_cont f cenv (Kcall optid fn e le k)\n                        (Kcall optid tfn te tle tk) m bound tbound.\n\n(** Invariance property by change of memory and injection *)\n\nLemma match_cont_invariant:\n  forall f' m' f cenv k tk m bound tbound,\n  match_cont f cenv k tk m bound tbound ->\n  (forall b chunk v,\n    f b = None -> sup_In b bound -> Mem.load chunk m b 0 = Some v -> Mem.load chunk m' b 0 = Some v) ->\n  inject_incr f f' ->\n  (forall b, sup_In b bound -> f' b = f b) ->\n  (forall b b' delta, f' b = Some(b', delta) -> sup_In b' tbound -> f' b = f b) ->\n  match_cont f' cenv k tk m' bound tbound.\nProof.\n  induction 1; intros LOAD INCR INJ1 INJ2; econstructor; eauto.\n(* globalenvs *)\n  inv H. constructor; intros; eauto.\n  assert (f b1 = Some (b2, delta)). rewrite <- H; symmetry; eapply INJ2; eauto.\n  auto.\n  eapply IMAGE; eauto.\n(* call *)\n  eapply match_envs_invariant; eauto.\n  intros. apply LOAD; auto. destruct H6. auto.\n  intros. apply INJ1; auto. destruct H5. auto.\n  intros. eapply INJ2; eauto. destruct H6. auto.\n  eapply IHmatch_cont; eauto.\n  intros; apply LOAD; auto. inv H0. auto.\n  intros; apply INJ1. inv H0. auto.\n  intros; eapply INJ2; eauto. inv H0; auto.\nQed.\n\n(** Invariance by assignment to location \"above\" *)\n\nLemma match_cont_assign_loc:\n  forall f cenv k tk m bound tbound ty loc ofs v m',\n  match_cont f cenv k tk m bound tbound ->\n  assign_loc ge ty m loc ofs v m' ->\n  ~ sup_In loc bound ->\n  match_cont f cenv k tk m' bound tbound.\nProof.\n  intros. eapply match_cont_invariant; eauto.\n  intros. rewrite <- H4. inv H0.\n  (* scalar *)\n  simpl in H6. eapply Mem.load_store_other; eauto. left. congruence.\n  (* block copy *)\n  eapply Mem.load_storebytes_other; eauto. left. congruence.\nQed.\n\n(** Invariance by external calls *)\n\nLemma match_cont_extcall:\n  forall f cenv k tk m bound tbound tm f' m',\n  match_cont f cenv k tk m bound tbound ->\n  Mem.unchanged_on (loc_unmapped f) m m' ->\n  inject_incr f f' ->\n  inject_separated f f' m tm ->\n  Mem.sup_include bound (Mem.support m) -> Mem.sup_include tbound (Mem.support tm) ->\n  match_cont f' cenv k tk m' bound tbound.\nProof.\n  intros. eapply match_cont_invariant; eauto.\n  intros. eapply Mem.load_unchanged_on; eauto.\n  red in H2. intros. destruct (f b) as [[b' delta] | ] eqn:?. auto.\n  destruct (f' b) as [[b' delta] | ] eqn:?; auto.\n  exploit H2; eauto. unfold Mem.valid_block. intros [A B].\n  apply H3 in H5. congruence.\n  red in H2. intros. destruct (f b) as [[b'' delta''] | ] eqn:?. auto.\n  exploit H2; eauto. unfold Mem.valid_block. intros [A B].\n  apply H4 in H6. congruence.\nQed.\n\n(** Invariance by change of bounds *)\n\nLemma match_cont_incr_bounds:\n  forall f cenv k tk m bound tbound,\n  match_cont f cenv k tk m bound tbound ->\n  forall bound' tbound',\n  Mem.sup_include bound bound' -> Mem.sup_include tbound tbound' ->\n  match_cont f cenv k tk m bound' tbound'.\nProof.\n  induction 1; intros; econstructor; eauto; auto.\n  apply Mem.sup_include_trans with bound. auto. auto.\n  apply Mem.sup_include_trans with tbound. auto. auto.\n  apply Mem.sup_include_trans with bound. auto. auto.\n  apply Mem.sup_include_trans with tbound. auto. auto.\nQed.\n\n(** [match_cont] and call continuations. *)\n\nLemma match_cont_change_cenv:\n  forall f cenv k tk m bound tbound cenv',\n  match_cont f cenv k tk m bound tbound ->\n  is_call_cont k ->\n  match_cont f cenv' k tk m bound tbound.\nProof.\n  intros. inv H; simpl in H0; try contradiction; econstructor; eauto.\nQed.\n\nLemma match_cont_is_call_cont:\n  forall f cenv k tk m bound tbound,\n  match_cont f cenv k tk m bound tbound ->\n  is_call_cont k ->\n  is_call_cont tk.\nProof.\n  intros. inv H; auto.\nQed.\n\nLemma match_cont_call_cont:\n  forall f cenv k tk m bound tbound,\n  match_cont f cenv k tk m bound tbound ->\n  forall cenv',\n  match_cont f cenv' (call_cont k) (call_cont tk) m bound tbound.\nProof.\n  induction 1; simpl; auto; intros; econstructor; eauto.\nQed.\n\n(** [match_cont] and freeing of environment blocks *)\n\nRemark free_list_support:\n  forall l m m',\n  Mem.free_list m l = Some m' -> Mem.support m' = Mem.support 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.support m1). eauto. eapply Mem.support_free; eauto.\nQed.\n\nRemark free_list_load:\n  forall chunk b' l m m',\n  Mem.free_list m l = Some m' ->\n  (forall b lo hi, In (b, lo, hi) l ->  b'<> b) ->\n  Mem.valid_block m b' ->\n  Mem.load chunk m' b' 0 = Mem.load chunk m b' 0.\nProof.\n  induction l; simpl; intros.\n  inv H; auto.\n  destruct a. destruct p. destruct (Mem.free m b z0 z) as [m1|] eqn:?; try discriminate.\n  transitivity (Mem.load chunk m1 b' 0).\n  apply IHl. auto. eauto. auto. eapply Mem.valid_block_free_1. eauto. auto.\n  eapply Mem.load_free. eauto. left. eauto.\nQed.\n\nLemma match_cont_free_env:\n  forall f cenv e le m lo hi te tle tm tlo thi k tk m' tm',\n  match_envs f cenv e le m lo hi te tle tlo thi ->\n  match_cont f cenv k tk m lo tlo ->\n  Mem.sup_include hi (Mem.support m) ->\n  Mem.sup_include thi (Mem.support tm) ->\n  Mem.free_list m (blocks_of_env ge e) = Some m' ->\n  Mem.free_list tm (blocks_of_env tge te) = Some tm' ->\n  match_cont f cenv k tk m' (Mem.support m') (Mem.support tm').\nProof.\n  intros. apply match_cont_incr_bounds with lo tlo.\n  eapply match_cont_invariant; eauto.\n  intros. rewrite <- H7. eapply free_list_load; eauto.\n  unfold blocks_of_env; intros. exploit list_in_map_inv; eauto.\n  intros [[id [b1 ty]] [P Q]]. simpl in P. inv P.\n  exploit me_range; eauto. eapply PTree.elements_complete; eauto.\n  intros [A B]. congruence. eapply Mem.valid_access_valid_block.\n  apply Mem.load_valid_access in H7. eapply Mem.valid_access_implies in H7.\n  eauto. constructor.\n  rewrite (free_list_support _ _ _ H3). inv H; auto.\n  apply Mem.sup_include_trans with hi. auto. auto.\n  rewrite (free_list_support _ _ _ H4). inv H; auto.\n  apply Mem.sup_include_trans with thi. auto. auto.\nQed.\n\n(** Matching of global environments *)\n\nLemma match_cont_globalenv:\n  forall f cenv k tk m bound tbound,\n  match_cont f cenv k tk m bound tbound ->\n  exists bound, match_globalenvs f bound.\nProof.\n  induction 1; auto. exists hi; auto.\nQed.\n\nHint Resolve match_cont_globalenv: compat.\n\nLemma match_cont_find_funct:\n  forall f cenv k tk m bound tbound vf fd tvf,\n  match_cont f cenv k tk m bound tbound ->\n  Genv.find_funct ge vf = Some fd ->\n  Val.inject f vf tvf ->\n  exists tfd, Genv.find_funct tge tvf = Some tfd /\\ transf_fundef fd = OK tfd.\nProof.\n  intros. exploit match_cont_globalenv; eauto. intros [bound1 MG]. destruct MG.\n  inv H1; simpl in H0; try discriminate. destruct (Ptrofs.eq_dec ofs1 Ptrofs.zero); try discriminate.\n  subst ofs1.\n  assert (f b1 = Some(b1, 0)).\n    apply DOMAIN. eapply FUNCTIONS; eauto.\n  rewrite H1 in H2; inv H2.\n  rewrite Ptrofs.add_zero. simpl. rewrite dec_eq_true. apply function_ptr_translated; auto.\nQed.\n\n(** Relating execution states *)\n\nInductive match_states: state -> state -> Prop :=\n  | match_regular_states:\n      forall f s k e le m tf ts tk te tle tm j lo hi tlo thi\n        (TRF: transf_function f = OK tf)\n        (TRS: simpl_stmt (cenv_for f) s = OK ts)\n        (MENV: match_envs j (cenv_for f) e le m lo hi te tle tlo thi)\n        (MCONT: match_cont j (cenv_for f) k tk m lo tlo)\n        (MINJ: Mem.inject j m tm)\n        (VINJ: j = struct_meminj (Mem.support m))\n        (MSTK: Mem.stackseq m tm)\n        (MASTK: Mem.astack (Mem.support m) = Mem.astack (Mem.support tm))\n        (COMPAT: compat_cenv (addr_taken_stmt s) (cenv_for f))\n        (BOUND: Mem.sup_include hi (Mem.support m))\n        (TBOUND: Mem.sup_include thi (Mem.support tm)),\n      match_states (State f s k e le m)\n                   (State tf ts tk te tle tm)\n  | match_call_state:\n      forall fd vargs k m tfd tvargs tk tm j targs tres cconv id\n        (TRFD: transf_fundef fd = OK tfd)\n        (MCONT: forall cenv, match_cont j cenv k tk m (Mem.support m) (Mem.support tm))\n        (FIND: Genv.find_funct_ptr ge (Global id) = Some fd)\n        (MINJ: Mem.inject j m tm)\n        (VINJ: j = struct_meminj (Mem.support m))\n        (MSTK: Mem.stackseq m tm)\n        (MASTK: Mem.astack (Mem.support m) = Mem.astack (Mem.support tm))\n        (AINJ: Val.inject_list j vargs tvargs)\n        (FUNTY: type_of_fundef fd = Tfunction targs tres cconv)\n        (ANORM: val_casted_list vargs targs),\n      match_states (Callstate fd vargs k m id)\n                   (Callstate tfd tvargs tk tm id)\n  | match_return_state:\n      forall v k m tv tk tm j\n        (MCONT: forall cenv, match_cont j cenv k tk m (Mem.support m) (Mem.support tm))\n        (MINJ: Mem.inject j m tm)\n        (VINJ: j = struct_meminj (Mem.support m))\n        (MSTK: Mem.stackseq m tm)\n        (MASTK: Mem.astack (Mem.support m) = Mem.astack (Mem.support tm))\n        (RINJ: Val.inject j v tv),\n      match_states (Returnstate v k m)\n                   (Returnstate tv tk tm).\n\n(** The simulation diagrams *)\n\nRemark is_liftable_var_charact:\n  forall cenv a,\n  match is_liftable_var cenv a with\n  | Some id => exists ty, a = Evar id ty /\\ VSet.mem id cenv = true\n  | None => match a with Evar id ty => VSet.mem id cenv = false | _ => True end\n  end.\nProof.\n  intros. destruct a; simpl; auto.\n  destruct (VSet.mem i cenv) eqn:?.\n  exists t; auto.\n  auto.\nQed.\n\nRemark simpl_select_switch:\n  forall cenv n ls tls,\n  simpl_lblstmt cenv ls = OK tls ->\n  simpl_lblstmt cenv (select_switch n ls) = OK (select_switch n tls).\nProof.\n  intros cenv n.\n  assert (DFL:\n    forall ls tls,\n    simpl_lblstmt cenv ls = OK tls ->\n    simpl_lblstmt cenv (select_switch_default ls) = OK (select_switch_default tls)).\n  {\n    induction ls; simpl; intros; monadInv H.\n    auto.\n    simpl. destruct o. eauto. simpl; rewrite EQ, EQ1. auto.\n  }\n  assert (CASE:\n    forall ls tls,\n    simpl_lblstmt cenv ls = OK tls ->\n    match select_switch_case n ls with\n    | None => select_switch_case n tls = None\n    | Some ls' =>\n        exists tls', select_switch_case n tls = Some tls' /\\ simpl_lblstmt cenv ls' = OK tls'\n    end).\n  {\n    induction ls; simpl; intros; monadInv H; simpl.\n    auto.\n    destruct o.\n    destruct (zeq z n).\n    econstructor; split; eauto. simpl; rewrite EQ, EQ1; auto.\n    apply IHls. auto.\n    apply IHls. auto.\n  }\n  intros; unfold select_switch.\n  specialize (CASE _ _ H). destruct (select_switch_case n ls) as [ls'|].\n  destruct CASE as [tls' [P Q]]. rewrite P, Q. auto.\n  rewrite CASE. apply DFL; auto.\nQed.\n\nRemark simpl_seq_of_labeled_statement:\n  forall cenv ls tls,\n  simpl_lblstmt cenv ls = OK tls ->\n  simpl_stmt cenv (seq_of_labeled_statement ls) = OK (seq_of_labeled_statement tls).\nProof.\n  induction ls; simpl; intros; monadInv H; simpl.\n  auto.\n  rewrite EQ; simpl. erewrite IHls; eauto. simpl. auto.\nQed.\n\nRemark compat_cenv_select_switch:\n  forall cenv n ls,\n  compat_cenv (addr_taken_lblstmt ls) cenv ->\n  compat_cenv (addr_taken_lblstmt (select_switch n ls)) cenv.\nProof.\n  intros cenv n.\n  assert (DFL: forall ls,\n    compat_cenv (addr_taken_lblstmt ls) cenv ->\n    compat_cenv (addr_taken_lblstmt (select_switch_default ls)) cenv).\n  {\n    induction ls; simpl; intros.\n    eauto with compat.\n    destruct o; simpl; eauto with compat.\n  }\n  assert (CASE: forall ls ls',\n    compat_cenv (addr_taken_lblstmt ls) cenv ->\n    select_switch_case n ls = Some ls' ->\n    compat_cenv (addr_taken_lblstmt ls') cenv).\n  {\n    induction ls; simpl; intros.\n    discriminate.\n    destruct o. destruct (zeq z n). inv H0. auto. eauto with compat.\n    eauto with compat.\n  }\n  intros. specialize (CASE ls). unfold select_switch.\n  destruct (select_switch_case n ls) as [ls'|]; eauto.\nQed.\n\nRemark addr_taken_seq_of_labeled_statement:\n  forall ls, addr_taken_stmt (seq_of_labeled_statement ls) = addr_taken_lblstmt ls.\nProof.\n  induction ls; simpl; congruence.\nQed.\n\nSection FIND_LABEL.\n\nVariable f: meminj.\nVariable cenv: compilenv.\nVariable m: mem.\nVariables bound tbound: sup.\nVariable lbl: ident.\n\nLemma simpl_find_label:\n  forall s k ts tk,\n  simpl_stmt cenv s = OK ts ->\n  match_cont f cenv k tk m bound tbound ->\n  compat_cenv (addr_taken_stmt s) cenv ->\n  match find_label lbl s k with\n  | None =>\n      find_label lbl ts tk = None\n  | Some(s', k') =>\n      exists ts', exists tk',\n         find_label lbl ts tk = Some(ts', tk')\n      /\\ compat_cenv (addr_taken_stmt s') cenv\n      /\\ simpl_stmt cenv s' = OK ts'\n      /\\ match_cont f cenv k' tk' m bound tbound\n  end\n\nwith simpl_find_label_ls:\n  forall ls k tls tk,\n  simpl_lblstmt cenv ls = OK tls ->\n  match_cont f cenv k tk m bound tbound ->\n  compat_cenv (addr_taken_lblstmt ls) cenv ->\n  match find_label_ls lbl ls k with\n  | None =>\n      find_label_ls lbl tls tk = None\n  | Some(s', k') =>\n      exists ts', exists tk',\n         find_label_ls lbl tls tk = Some(ts', tk')\n      /\\ compat_cenv (addr_taken_stmt s') cenv\n      /\\ simpl_stmt cenv s' = OK ts'\n      /\\ match_cont f cenv k' tk' m bound tbound\n  end.\n\nProof.\n  induction s; simpl; intros until tk; intros TS MC COMPAT; auto.\n  (* skip *)\n  monadInv TS; auto.\n  (* var *)\n  destruct (is_liftable_var cenv e); monadInv TS; auto.\n  unfold Sset_debug. destruct (Compopts.debug tt); auto.\n  (* set *)\n  monadInv TS; auto.\n  (* call *)\n  monadInv TS; auto.\n  (* builtin *)\n  monadInv TS; auto.\n  (* seq *)\n  monadInv TS.\n  exploit (IHs1 (Kseq s2 k) x (Kseq x0 tk)); eauto with compat.\n    constructor; eauto with compat.\n  destruct (find_label lbl s1 (Kseq s2 k)) as [[s' k']|].\n  intros [ts' [tk' [P [Q [R S]]]]]. exists ts'; exists tk'. simpl. rewrite P. auto.\n  intros E. simpl. rewrite E. eapply IHs2; eauto with compat.\n  (* ifthenelse *)\n  monadInv TS.\n  exploit (IHs1 k x tk); eauto with compat.\n  destruct (find_label lbl s1 k) as [[s' k']|].\n  intros [ts' [tk' [P [Q [R S]]]]]. exists ts'; exists tk'. simpl. rewrite P. auto.\n  intros E. simpl. rewrite E. eapply IHs2; eauto with compat.\n  (* loop *)\n  monadInv TS.\n  exploit (IHs1 (Kloop1 s1 s2 k) x (Kloop1 x x0 tk)); eauto with compat.\n    constructor; eauto with compat.\n  destruct (find_label lbl s1 (Kloop1 s1 s2 k)) as [[s' k']|].\n  intros [ts' [tk' [P [Q [R S]]]]]. exists ts'; exists tk'. simpl; rewrite P. auto.\n  intros E. simpl; rewrite E. eapply IHs2; eauto with compat. econstructor; eauto with compat.\n  (* break *)\n  monadInv TS; auto.\n  (* continue *)\n  monadInv TS; auto.\n  (* return *)\n  monadInv TS; auto.\n  (* switch *)\n  monadInv TS. simpl.\n  eapply simpl_find_label_ls; eauto with compat. constructor; auto.\n  (* label *)\n  monadInv TS. simpl.\n  destruct (ident_eq lbl l).\n  exists x; exists tk; auto.\n  eapply IHs; eauto.\n  (* goto *)\n  monadInv TS; auto.\n\n  induction ls; simpl; intros.\n  (* nil *)\n  monadInv H. auto.\n  (* cons *)\n  monadInv H.\n  exploit (simpl_find_label s (Kseq (seq_of_labeled_statement ls) k)).\n    eauto. constructor. eapply simpl_seq_of_labeled_statement; eauto. eauto.\n    rewrite addr_taken_seq_of_labeled_statement. eauto with compat.\n    eauto with compat.\n  destruct (find_label lbl s (Kseq (seq_of_labeled_statement ls) k)) as [[s' k']|].\n  intros [ts' [tk' [P [Q [R S]]]]]. exists ts'; exists tk'; split. simpl; rewrite P. auto. auto.\n  intros E. simpl; rewrite E. eapply IHls; eauto with compat.\nQed.\n\nLemma find_label_store_params:\n  forall s k params, find_label lbl (store_params cenv params s) k = find_label lbl s k.\nProof.\n  induction params; simpl. auto.\n  destruct a as [id ty]. destruct (VSet.mem id cenv); auto.\nQed.\n\nLemma find_label_add_debug_vars:\n  forall s k vars, find_label lbl (add_debug_vars vars s) k = find_label lbl s k.\nProof.\n  unfold add_debug_vars. destruct (Compopts.debug tt); auto.\n  induction vars; simpl; auto. destruct a as [id ty]; simpl. auto.\nQed.\n\nLemma find_label_add_debug_params:\n  forall s k vars, find_label lbl (add_debug_params vars s) k = find_label lbl s k.\nProof.\n  unfold add_debug_params. destruct (Compopts.debug tt); auto.\n  induction vars; simpl; auto. destruct a as [id ty]; simpl. auto.\nQed.\n\nEnd FIND_LABEL.\n\n(*\nLemma sinj_external_call :\n  forall m m' tm tm' f f' vargs tvargs vres tvres ef ge t,\n    Mem.inject f m tm ->\n    Mem.stackseq m tm ->\n    external_call ef ge vargs m t vres m' ->\n    external_call ef ge tvargs tm t tvres tm' ->\n    Val.inject_list f vargs tvargs ->\n    Mem.inject f' m' tm' ->\n    f = struct_meminj (Mem.support m) ->\n    Mem.stackseq m' tm' /\\\n    f' = struct_meminj (Mem.support m').\nProof.\n*)\n\nLemma step_simulation:\n  forall S1 t S2, step1 fn_stack_requirements ge S1 t S2 ->\n  forall S1' (MS: match_states S1 S1'), exists S2', plus (step2 fn_stack_requirements) tge S1' t S2' /\\ match_states S2 S2'.\nProof.\n  induction 1; simpl; intros; inv MS; simpl in *; try (monadInv TRS).\n\n(* assign *)\n  generalize (is_liftable_var_charact (cenv_for f) a1); destruct (is_liftable_var (cenv_for f) a1) as [id|]; monadInv TRS.\n  (* liftable *)\n  intros [ty [P Q]]; subst a1; simpl in *.\n  exploit eval_simpl_expr; eauto with compat. intros [tv2 [A B]].\n  exploit sem_cast_inject; eauto. intros [tv [C D]].\n  exploit me_vars; eauto. instantiate (1 := id). intros MV.\n  inv H.\n  (* local variable *)\n  econstructor; split.\n  eapply step_Sset_debug. eauto. rewrite typeof_simpl_expr. eauto.\n  econstructor; eauto with compat.\n  erewrite assign_loc_support; eauto.\n  eapply match_envs_assign_lifted; eauto.\n  eapply cast_val_is_casted; eauto.\n  erewrite assign_loc_support; eauto.\n  eapply match_cont_assign_loc; eauto. exploit me_range; eauto. intros [E F]. auto.\n  erewrite assign_loc_support; eauto.\n  inv MV; try congruence. inv H2; try congruence. unfold Mem.storev in H3.\n  eapply Mem.store_unmapped_inject; eauto. congruence.\n  unfold Mem.stackseq in *. erewrite assign_loc_support; eauto.\n  erewrite assign_loc_support; eauto.\n  erewrite assign_loc_support; eauto.\n  (* global variable *)\n  inv MV; congruence.\n  (* not liftable *)\n  intros P.\n  exploit eval_simpl_lvalue; eauto with compat. intros [tb [tofs [E F]]].\n  exploit eval_simpl_expr; eauto with compat. intros [tv2 [A B]].\n   exploit sem_cast_inject; eauto. intros [tv [C D]].\n  exploit assign_loc_inject; eauto. intros [tm' [X [Y Z]]].\n  econstructor; split.\n  apply plus_one. econstructor. eexact E. eexact A. repeat rewrite typeof_simpl_expr. eexact C.\n  rewrite typeof_simpl_expr; auto. eexact X.\n  apply assign_loc_support in H2 as SA. apply assign_loc_support in X as SA'.\n  econstructor; eauto with compat.\n  eapply match_envs_invariant; eauto.\n  eapply match_cont_invariant; eauto.\n  congruence. unfold Mem.stackseq in *. congruence. congruence.\n  erewrite assign_loc_support; eauto.\n  erewrite assign_loc_support; eauto.\n\n(* set temporary *)\n  exploit eval_simpl_expr; eauto with compat. intros [tv [A B]].\n  econstructor; split.\n  apply plus_one. econstructor. eauto.\n  econstructor; eauto with compat.\n  eapply match_envs_set_temp; eauto.\n\n(* call *)\n  exploit eval_simpl_expr; eauto with compat. intros [tvf [A B]].\n  exploit eval_simpl_exprlist; eauto with compat. intros [CASTED [tvargs [C D]]].\n  exploit match_cont_find_funct; eauto.\n  simpl. destr. eauto.\n  intros [tfd [P Q]].\n  econstructor; split.\n  apply plus_one. eapply step_call with (fd := tfd).\n  rewrite typeof_simpl_expr. eauto.\n  instantiate (1:=id).\n  instantiate (1:=tvf).\n  inv B. unfold struct_meminj in H6. destr_in H6. simpl in H6. inv H6.\n  auto. eauto. eauto. eauto.\n  erewrite type_of_fundef_preserved; eauto.\n  econstructor; eauto.\n  intros. econstructor; eauto.\n\n(* builtin *)\n  exploit eval_simpl_exprlist; eauto with compat. intros [CASTED [tvargs [C D]]].\n  exploit external_call_mem_inject'; eauto. apply match_globalenvs_preserves_globals; eauto with compat.\n  intros [j' [tvres [tm' [P [Q [R [S [T [U [V [W X]]]]]]]]]]].\n  (* exploit sinj_external_call. apply MINJ. all: eauto. intros [Y Z]. *)\n  econstructor; split.\n  apply plus_one. econstructor; eauto. eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto with compat.\n  eapply match_envs_set_opttemp; eauto.\n  eapply match_envs_extcall; eauto.\n  eapply match_cont_extcall; eauto.\n  inv MENV. eapply Mem.sup_include_trans. eauto. eauto.\n  inv MENV; eapply Mem.sup_include_trans. eauto. eauto.\n  {\n    apply Axioms.extensionality. intro b.\n    destruct ((struct_meminj (Mem.support m)) b) eqn:Z. destruct p.\n    - apply U in Z as Z'. rewrite Z'. rewrite <- Z.\n      unfold struct_meminj. destr. exploit external_call_valid_block.\n      apply H0. eauto. intro. destr. apply n in H1. inv H1.\n      inv MINJ. exploit mi_freeblocks; eauto. intro. congruence.\n    - destruct (j' b) eqn:Z1.\n      + destruct p. exploit W; eauto.\n      intros [A1 B1]. inv R. unfold struct_meminj. destr.\n      exploit X; eauto. intros [C1 D1]. rewrite Z1 in D1. inv D1.\n      destruct b. destruct f0; simpl in C1. inv C1. simpl. auto. inv C1.\n      apply mi_freeblocks in n. congruence.\n      + unfold struct_meminj. destr. unfold struct_meminj in Z. destr_in Z.\n      exploit X; eauto. intros [C1 D1]. congruence.\n  }\n  eapply external_call_mem_inject_stackseq; eauto. eapply match_globalenvs_preserves_globals. eauto with compat.\n  eapply external_call_astack in P.\n  eapply external_call_astack in H0. congruence.\n  eapply Mem.sup_include_trans; eauto. eapply external_call_support; eauto.\n  eapply Mem.sup_include_trans; eauto. eapply external_call_support; eauto.\n\n(* sequence *)\n  econstructor; split. apply plus_one. econstructor.\n  econstructor; eauto with compat. econstructor; eauto with compat.\n\n(* skip sequence *)\n  inv MCONT. econstructor; split. apply plus_one. econstructor. econstructor; eauto.\n\n(* continue sequence *)\n  inv MCONT. econstructor; split. apply plus_one. econstructor. econstructor; eauto.\n\n(* break sequence *)\n  inv MCONT. econstructor; split. apply plus_one. econstructor. econstructor; eauto.\n\n(* ifthenelse *)\n  exploit eval_simpl_expr; eauto with compat. intros [tv [A B]].\n  econstructor; split.\n  apply plus_one. apply step_ifthenelse with (v1 := tv) (b := b). auto.\n  rewrite typeof_simpl_expr. eapply bool_val_inject; eauto.\n  destruct b; econstructor; eauto with compat.\n\n(* loop *)\n  econstructor; split. apply plus_one. econstructor. econstructor; eauto with compat. econstructor; eauto with compat.\n\n(* skip-or-continue loop *)\n  inv MCONT. econstructor; split.\n  apply plus_one. econstructor. destruct H; subst x; simpl in *; intuition congruence.\n  econstructor; eauto with compat. econstructor; eauto with compat.\n\n(* break loop1 *)\n  inv MCONT. econstructor; split. apply plus_one. eapply step_break_loop1.\n  econstructor; eauto.\n\n(* skip loop2 *)\n  inv MCONT. econstructor; split. apply plus_one. eapply step_skip_loop2.\n  econstructor; eauto with compat. simpl; rewrite H2; rewrite H4; auto.\n\n(* break loop2 *)\n  inv MCONT. econstructor; split. apply plus_one. eapply step_break_loop2.\n  econstructor; eauto.\n\n(* return none *)\n  exploit match_envs_free_blocks; eauto. intros [tm' [P Q]].\n  apply free_list_support in H as SF. apply free_list_support in P as SF'.\n  exploit Mem.return_frame_parallel_stackseq. 2: eauto. instantiate (1:= tm').\n  unfold Mem.stackseq. rewrite SF. rewrite SF'. eauto.\n  intros [tm'' [P' Q']].\n  exploit Mem.return_frame_inject; eauto. intro.\n  apply Mem.support_return_frame in H0 as SRET.\n  apply Mem.support_return_frame in P' as SRET'.\n  exploit Mem.return_frame_parallel_astackeq. apply H0. apply P'. congruence.\n  intro.\n  exploit Mem.pop_stage_parallel_inject; eauto.\n  apply Mem.pop_stage_nonempty in H1. congruence.\n  intros [tm''' [P'' Q'']].\n  apply Mem.stack_pop_stage in P'' as STK'.\n  apply Mem.stack_pop_stage in H1 as STK.\n  econstructor; split. apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n  intros. eapply match_cont_call_cont.\n  eapply match_cont_invariant.\n  eapply match_cont_incr_bounds.\n  eapply match_cont_free_env; eauto.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in H0. apply H0.\n  intro. eapply Mem.support_pop_stage_1 in H1. apply H1.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in P'. apply P'.\n  intro. eapply Mem.support_pop_stage_1 in P''. apply P''.\n  intros. erewrite Mem.load_pop_stage. 2: eauto.\n  erewrite Mem.load_return_frame; eauto.\n  eauto. eauto. eauto.\n  eapply sinj_refl. erewrite <- free_list_support; eauto.\n  etransitivity.\n  eapply Mem.support_return_frame_1 in H0. apply H0.\n  eapply Mem.support_pop_stage_1; eauto.\n  unfold Mem.stackseq in *. congruence.\n  apply Mem.astack_pop_stage in H1. apply Mem.astack_pop_stage in P''.\n  destruct H1 as [a b]. destruct P'' as [c d]. congruence.\n\n(* return some *)\n  exploit eval_simpl_expr; eauto with compat. intros [tv [A B]].\n  exploit sem_cast_inject; eauto. intros [tv' [C D]].\n  exploit match_envs_free_blocks; eauto. intros [tm' [P Q]].\n  apply free_list_support in H1 as SF. apply free_list_support in P as SF'.\n  exploit Mem.return_frame_parallel_stackseq. 2: eauto. instantiate (1:= tm').\n  unfold Mem.stackseq. rewrite SF. rewrite SF'. eauto.\n  intros [tm'' [P' Q']].\n  exploit Mem.return_frame_inject; eauto. intro.\n  apply Mem.support_return_frame in H2 as SRET.\n  apply Mem.support_return_frame in P' as SRET'.\n  exploit Mem.return_frame_parallel_astackeq. apply H2. apply P'. congruence.\n  intro.\n  exploit Mem.pop_stage_parallel_inject; eauto.\n  apply Mem.pop_stage_nonempty in H3. congruence.\n  intros [tm''' [P'' Q'']].\n  apply Mem.stack_pop_stage in P'' as STK'.\n  apply Mem.stack_pop_stage in H3 as STK.\n  econstructor; split. apply plus_one. econstructor; eauto.\n  rewrite typeof_simpl_expr. monadInv TRF; simpl. eauto.\n  econstructor; eauto.\n  intros. eapply match_cont_call_cont.\n  eapply match_cont_invariant.\n  eapply match_cont_incr_bounds.\n  eapply match_cont_free_env; eauto.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in H2. apply H2.\n  intro. eapply Mem.support_pop_stage_1 in H3. apply H3.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in P'. apply P'.\n  intro. eapply Mem.support_pop_stage_1 in P''. apply P''.\n  intros. erewrite Mem.load_pop_stage. 2: eauto.\n  erewrite Mem.load_return_frame; eauto.\n  eauto. eauto. eauto.\n  eapply sinj_refl. erewrite <- free_list_support; eauto.\n  etransitivity.\n  eapply Mem.support_return_frame_1 in H2. apply H2.\n  eapply Mem.support_pop_stage_1; eauto.\n  unfold Mem.stackseq in *. congruence.\n  apply Mem.astack_pop_stage in H3. apply Mem.astack_pop_stage in P''.\n  destruct H3 as [a' b]. destruct P'' as [c d]. congruence.\n\n(* skip call *)\n  exploit match_envs_free_blocks; eauto. intros [tm'1 [P Q]].\n  apply free_list_support in H0 as SF. apply free_list_support in P as SF'.\n  exploit Mem.return_frame_parallel_stackseq. 2: eauto. instantiate (1:= tm'1).\n  unfold Mem.stackseq. rewrite SF. rewrite SF'. eauto.\n  intros [tm'' [P' Q']].\n  exploit Mem.return_frame_inject; eauto. intro.\n  apply Mem.support_return_frame in H1 as SRET.\n  apply Mem.support_return_frame in P' as SRET'.\n  exploit Mem.return_frame_parallel_astackeq. apply H1. apply P'. congruence.\n  intro.\n  exploit Mem.pop_stage_parallel_inject; eauto.\n  apply Mem.pop_stage_nonempty in H2. congruence.\n  intros [tm''' [P'' Q'']].\n  apply Mem.stack_pop_stage in P'' as STK'.\n  apply Mem.stack_pop_stage in H2 as STK.\n  econstructor; split. apply plus_one. econstructor; eauto.\n  eapply match_cont_is_call_cont; eauto.\n  monadInv TRF; auto.\n  econstructor; eauto.\n  intros. apply match_cont_change_cenv with (cenv_for f); auto.\n  eapply match_cont_invariant.\n  eapply match_cont_incr_bounds.\n  eapply match_cont_free_env; eauto.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in H1. apply H1.\n  intro. eapply Mem.support_pop_stage_1 in H2. apply H2.\n  eapply Mem.sup_include_trans.\n  intro. eapply Mem.support_return_frame_1 in P'. apply P'.\n  intro. eapply Mem.support_pop_stage_1 in P''. apply P''.\n  intros. erewrite Mem.load_pop_stage. 2: eauto.\n  erewrite Mem.load_return_frame; eauto.\n  eauto. eauto. eauto.\n  eapply sinj_refl. erewrite <- free_list_support; eauto.\n  etransitivity.\n  eapply Mem.support_return_frame_1 in H1. apply H1.\n  eapply Mem.support_pop_stage_1; eauto.\n  unfold Mem.stackseq in *. congruence.\n  apply Mem.astack_pop_stage in H2. apply Mem.astack_pop_stage in P''.\n  destruct H2. destruct P''. congruence.\n\n(* switch *)\n  exploit eval_simpl_expr; eauto with compat. intros [tv [A B]].\n  econstructor; split. apply plus_one. econstructor; eauto.\n  rewrite typeof_simpl_expr. instantiate (1 := n).\n  unfold sem_switch_arg in *;\n  destruct (classify_switch (typeof a)); try discriminate;\n  inv B; inv H0; auto.\n  econstructor; eauto.\n  erewrite simpl_seq_of_labeled_statement. reflexivity.\n  eapply simpl_select_switch; eauto.\n  econstructor; eauto. rewrite addr_taken_seq_of_labeled_statement.\n  apply compat_cenv_select_switch. eauto with compat.\n\n(* skip-break switch *)\n  inv MCONT. econstructor; split.\n  apply plus_one. eapply step_skip_break_switch. destruct H; subst x; simpl in *; intuition congruence.\n  econstructor; eauto with compat.\n\n(* continue switch *)\n  inv MCONT. econstructor; split.\n  apply plus_one. eapply step_continue_switch.\n  econstructor; eauto with compat.\n\n(* label *)\n  econstructor; split. apply plus_one. econstructor. econstructor; eauto.\n\n(* goto *)\n  generalize TRF; intros TRF'. monadInv TRF'.\n  exploit (simpl_find_label (struct_meminj (Mem.support m)) (cenv_for f) m lo tlo lbl (fn_body f) (call_cont k) x (call_cont tk)).\n    eauto. eapply match_cont_call_cont. eauto.\n    apply compat_cenv_for.\n  rewrite H. intros [ts' [tk' [A [B [C D]]]]].\n  econstructor; split.\n  apply plus_one. econstructor; eauto. simpl.\n  rewrite find_label_add_debug_params. rewrite find_label_store_params. rewrite find_label_add_debug_vars. eexact A.\n  econstructor; eauto.\n\n(* internal function *)\n  monadInv TRFD. inv H.\n  generalize EQ; intro EQ'; monadInv EQ'.\n  assert (list_norepet (var_names (fn_params f ++ fn_vars f))).\n    unfold var_names. rewrite map_app. auto.\n  exploit Mem.alloc_frame_parallel_inject; eauto.\n  intros (tm1 & p' & ALL & INJ).\n  exploit alloc_var_var'; eauto. intros (blocks & VARS' & H5).\n  exploit nextblock_pos_1. apply H1. intro.\n  exploit nextblock_pos_1; eauto. intro.\n  exploit Mem.alloc_frame_parallel_stackseq; eauto. intro. inv H8.\n  exploit Mem.alloc_frame_parallel_astackeq; eauto. intro.\n  exploit match_envs_alloc_variables; eauto.\n    instantiate (1 := cenv_for_gen (addr_taken_stmt f.(fn_body)) (fn_params f ++ fn_vars f)).\n    intros. eapply cenv_for_gen_by_value; eauto. rewrite VSF.mem_iff. eexact H11.\n    intros. eapply cenv_for_gen_domain. rewrite VSF.mem_iff. eexact H9.\n  intros [j' [te [tm2 [A [B [C [D [E [F [G I]]]]]]]]]].\n  exploit alloc_variables_parallel_astackeq. apply H2. apply A. eauto. intro.\n  exploit Mem.push_stage_inject; eauto. intro.\n  exploit Mem.record_frame_parallel_inject; eauto. simpl. congruence.\n  simpl. rewrite H9. lia.\n  intros (tm3 & L & M).\n  assert (K: list_forall2 val_casted vargs (map snd (fn_params f))).\n  { apply val_casted_list_params. unfold type_of_function in FUNTY. congruence. }\n  exploit store_params_correct.\n    eauto.\n    eapply list_norepet_append_left; eauto.\n    eexact K.\n    apply val_inject_list_incr with j'; eauto.\n    eapply match_envs_invariant.\n    eexact B.\n    intros. rewrite (Mem.load_record_frame _ _ _  H3). eauto.\n    eauto. eauto. eauto. eexact M.\n    intros. apply (create_undef_temps_lifted id0 f). auto.\n    intros. destruct (create_undef_temps (fn_temps f))!id0 as [v|] eqn:?; auto.\n    exploit create_undef_temps_inv; eauto. intros [P Q]. elim (l id0 id0); auto.\n  intros [tel [tm4 [P [Q [R [S T]]]]]].\n  change (cenv_for_gen (addr_taken_stmt (fn_body f)) (fn_params f ++ fn_vars f))\n    with (cenv_for f) in *.\n  generalize (vars_and_temps_properties (cenv_for f) (fn_params f) (fn_vars f) (fn_temps f)).\n  intros [X [Y Z]]. auto. auto.\n  econstructor; split.\n  eapply plus_left. econstructor.\n  econstructor. exact Y. exact X. exact Z. eauto. simpl. eexact A. simpl. eauto.\n  eexact Q.\n  simpl. eapply star_trans. eapply step_add_debug_params. auto. eapply forall2_val_casted_inject; eauto. eexact Q.\n  eapply star_trans. eexact P. eapply step_add_debug_vars.\n  unfold remove_lifted; intros. rewrite List.filter_In in H12. destruct H12.\n  apply negb_true_iff in H13. eauto.\n  reflexivity. reflexivity. traceEq.\n  econstructor; eauto.\n  eapply match_cont_invariant with (m:= m); eauto.\n  eapply match_cont_incr_bounds; eauto.\n  intro. eapply Mem.support_alloc_frame_1 in H1. apply H1.\n  intro. eapply Mem.support_alloc_frame_1 in ALL. apply ALL.\n  intros. erewrite bind_parameters_load. 3: eauto.\n  rewrite (Mem.load_record_frame _ _ _ H3).\n  rewrite <- (Mem.load_alloc_frame _ _ _ _ H1) in H14.\n  eapply alloc_variables_load in H14. 2: eauto. eauto.\n  intros.\n  exploit alloc_variables_range. eexact H2. eauto.\n  unfold empty_env. rewrite PTree.gempty. intros [?|?]. congruence.\n  red; intros; subst b'. destruct H16. congruence.\n{\n  apply Axioms.extensionality. intro b0.\n  destruct (Mem.sup_dec b0 (Mem.support m0)).\n  - rewrite E. unfold struct_meminj.\n    eapply Mem.support_alloc_frame_1 in H1 as SUP1.\n    apply SUP1 in s as s1.\n    eapply alloc_variables_support in s as s2; eauto.\n    erewrite (bind_parameters_support _ _ _ _ _ _ H4).\n    destr; destr; try congruence. exfalso. apply n.\n    eapply Mem.support_record_frame_1 in H3. apply H3. eauto. auto.\n  - destruct (Mem.sup_dec b0 (Mem.support m1)).\n    + unfold struct_meminj. destr.\n      erewrite bind_parameters_support in s; eauto.\n      eapply Mem.support_record_frame_1 in H3. apply H3 in s.\n      unfold unchecked_meminj.\n      exploit alloc_vars_inv'. apply VARS'. intro. apply H12 in s.\n      destruct s; try congruence.\n      assert (Mem.nextblock m0 = Stack (Some id) p' 1%positive).\n      eapply Mem.alloc_frame_nextblock; eauto.\n      exploit nextblock_alloc_vars; eauto.\n      intros (p'0 & X' & Y').\n      subst. unfold find_func_pos.\n      rewrite FIND.\n      exploit I. eauto. intro.\n      destruct H15 as (id0 & path0 & pos & X1 & Y1).\n      rewrite Y1. inv X1. auto.\n    + inv C. rewrite mi_freeblocks; eauto. unfold struct_meminj.\n      destr; try congruence.\n      erewrite bind_parameters_support in n0. 2: eauto.\n      eapply Mem.support_record_frame_1 in H3. intro. apply n0. apply H3. eauto.\n}\n  unfold Mem.stackseq in *. rewrite T.\n  erewrite bind_parameters_support; eauto.\n  erewrite <- Mem.stack_record_frame; eauto.\n  erewrite <- (Mem.stack_record_frame _ _ _ L). simpl.\n  eapply alloc_variables_parallel_stackseq; eauto.\n  rewrite T. rewrite (bind_parameters_support _ _ _ _ _ _ H4).\n  apply Mem.astack_record_frame in H3. apply Mem.astack_record_frame in L.\n  destruct H3 as [a [b [c d]]]. destruct L as [h [i [j k']]]. simpl in *.\n  congruence.\n  apply compat_cenv_for.\n  rewrite (bind_parameters_support _ _ _ _ _ _ H4).\n  intro. eapply Mem.support_record_frame_1 in H3. apply H3. rewrite T.\n  intro. eapply Mem.support_record_frame_1 in L. apply L.\n(* external function *)\n  monadInv TRFD. inv FUNTY.\n  exploit external_call_mem_inject'; eauto. apply match_globalenvs_preserves_globals.\n  eapply match_cont_globalenv. eexact (MCONT VSet.empty).\n  intros [j' [tvres [tm' [P [Q [R [S [T [U [V [W X]]]]]]]]]]].\n(*  exploit sinj_external_call. apply MINJ. all: eauto. intros [X Y]. *)\n  econstructor; split.\n  apply plus_one. econstructor; eauto. eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n  intros. apply match_cont_incr_bounds with (Mem.support m) (Mem.support tm).\n  eapply match_cont_extcall; eauto.\n  apply Mem.sup_include_refl. apply Mem.sup_include_refl.\n  eapply external_call_support; eauto.\n  eapply external_call_support; eauto.\n  {\n    apply Axioms.extensionality. intro b.\n    destruct ((struct_meminj (Mem.support m)) b) eqn:Z. destruct p.\n    - apply U in Z as Z'. rewrite Z'. rewrite <- Z.\n      unfold struct_meminj. destr. exploit external_call_valid_block.\n      apply H. eauto. intro. destr. apply n in H0. inv H0.\n      inv MINJ. exploit mi_freeblocks; eauto. intro. congruence.\n    - destruct (j' b) eqn:Z1.\n      + destruct p. exploit W; eauto.\n      intros [A1 B1]. inv R. unfold struct_meminj. destr.\n      exploit X; eauto. intros [C1 D1]. rewrite Z1 in D1. inv D1.\n      destruct b. destruct f; simpl in C1. inv C1. simpl. auto. inv C1.\n      apply mi_freeblocks in n. congruence.\n      + unfold struct_meminj. destr. unfold struct_meminj in Z. destr_in Z.\n      exploit X; eauto. intros [C1 D1]. congruence.\n  }\n\n  eapply external_call_mem_inject_stackseq; eauto. eapply match_globalenvs_preserves_globals.   eapply match_cont_globalenv. eexact (MCONT VSet.empty).\n  eapply external_call_astack in H.\n  eapply external_call_astack in P. congruence.\n\n(* return *)\n  specialize (MCONT (cenv_for f)). inv MCONT.\n  econstructor; split.\n  apply plus_one. econstructor.\n  econstructor; eauto with compat.\n  eapply match_envs_set_opttemp; eauto.\nQed.\n\nLemma initial_states_simulation:\n  forall S, initial_state prog S ->\n  exists R, initial_state tprog R /\\ match_states S R.\nProof.\n  intros. inv H.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  apply Genv.init_mem_stack in H0 as STK.\n  apply Mem.stack_alloc in H4 as STK1. rewrite STK in STK1. simpl in STK1.\n  exploit Genv.initmem_inject; eauto. intro MINJ.\n  exploit Genv.init_mem_init_sp_inject; eauto. intro MINJ1.\n  assert (struct_meminj (Mem.support m1) = Mem.flat_inj (Mem.support m1)).\n  apply Axioms.extensionality. intro x.\n  unfold struct_meminj. unfold Mem.flat_inj.\n  destruct (Mem.sup_dec x (Mem.support m1)); auto.\n  unfold unchecked_meminj. destruct x. simpl in s.\n  rewrite STK1 in s; eauto.\n  destruct p. inv s. inv H5. auto. inv H. simpl in s. destruct n; simpl in s; inv s. auto.\n  econstructor; split.\n  econstructor.\n  eapply (Genv.init_mem_transf_partial (proj1 TRANSF)). eauto.\n  replace (prog_main tprog) with (prog_main prog).\n  instantiate (1 := b). rewrite <- H1. apply symbols_preserved.\n  generalize (match_program_main (proj1 TRANSF)). simpl; auto.\n  eauto.\n  rewrite <- H3; apply type_of_fundef_preserved; auto. eauto.\n  replace (prog_main tprog) with (prog_main prog).\n  econstructor; eauto.\n  intros.\n  econstructor. instantiate (1 := Mem.support m1).\n  constructor; intros.\n  unfold Mem.flat_inj. apply pred_dec_true; auto.\n  unfold Mem.flat_inj in H5. destruct (Mem.sup_dec b1 (Mem.support m1)); inv H5.\n  auto.\n  eapply Mem.valid_block_alloc; eauto.\n  eapply Genv.find_symbol_not_fresh; eauto.\n  eapply Mem.valid_block_alloc; eauto.\n  eapply Genv.find_funct_ptr_not_fresh; eauto.\n  eapply Mem.valid_block_alloc; eauto.\n  eapply Genv.find_var_info_not_fresh; eauto.\n  apply Mem.sup_include_refl. apply Mem.sup_include_refl.\n  apply Genv.genv_vars_eq in H1. subst. auto.\n  apply struct_eq_refl.\n  constructor.\n  generalize (match_program_main (proj1 TRANSF)). simpl; auto.\nQed.\n\nLemma final_states_simulation:\n  forall S R r,\n  match_states S R -> final_state S r -> final_state R r.\nProof.\n  intros. inv H0. inv H.\n  specialize (MCONT VSet.empty). inv MCONT.\n  inv RINJ. constructor.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (semantics1 fn_stack_requirements prog)\n                     (semantics2 fn_stack_requirements tprog).\nProof.\n  eapply forward_simulation_plus.\n  apply senv_preserved.\n  eexact initial_states_simulation.\n  eexact final_states_simulation.\n  eexact step_simulation.\nQed.\n\nEnd PRESERVATION.\n\n(** ** Commutation with linking *)\n\nInstance TransfSimplLocalsLink : TransfLink match_prog.\nProof.\n  red; intros. eapply Ctypes.link_match_program; eauto.\n- intros.\nLocal Transparent Linker_fundef.\n  simpl in *; unfold link_fundef in *.\n  destruct f1; monadInv H3; destruct f2; monadInv H4; try discriminate.\n  destruct e; inv H2. exists (Internal x); split; auto. simpl; rewrite EQ; auto.\n  destruct e; inv H2. exists (Internal x); split; auto. simpl; rewrite EQ; auto.\n  destruct (external_function_eq e e0 && typelist_eq t t1 &&\n            type_eq t0 t2 && calling_convention_eq c c0); inv H2.\n  econstructor; split; eauto.\nQed.\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/cfrontend/SimplLocalsproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1608774450059356}}
{"text": "Require Import CoqlibC Maps.\nRequire Import ASTC Integers Floats Values MemoryC Events Globalenvs Smallstep.\nRequire Import Locations Stacklayout Conventions Linking.\n(** newly added **)\nRequire Export Asm.\nRequire Import Simulation Memory ValuesC.\nRequire Import Skeleton ModSem Mod sflib Sem Syntax LinkingC Program SemProps.\nRequire Import GlobalenvsC Lia IntegersC SimMemInj IdSimExtra AsmC.\nRequire Import mktac.\nSet Implicit Arguments.\n\nLemma exec_load_mem_equal\n      ge chunk m0 m1 a rd rs0 rs1\n      (EXEC: exec_load ge chunk m0 a rs0 rd = Next rs1 m1):\n    m0 = m1.\nProof. unfold exec_load in *. des_ifs. Qed.\n\nLemma exec_store_max_perm\n      ge chunk m0 m1 a rd l rs0 rs1 b ofs k p\n      (EXEC: exec_store ge chunk m0 a rs0 rd l = Next rs1 m1)\n      (PERM: Mem.perm m1 b ofs k p):\n    Mem.perm m0 b ofs k p.\nProof.\n  unfold exec_store, Mem.storev in *. des_ifs. eapply Mem.perm_store_2; eauto.\nQed.\n\nLemma exec_store_readonly\n      ge chunk m0 m1 a rd l rs0 rs1\n      (EXEC: exec_store ge chunk m0 a rs0 rd l = Next rs1 m1):\n    Mem.unchanged_on (loc_not_writable m0) m0 m1.\nProof.\n  unfold exec_store, Mem.storev in *. des_ifs.\n  eapply mem_store_readonly; eauto.\nQed.\n\nLemma asm_step_max_perm se ge_src rs0 rs1 m0 m1 tr\n      (STEP: Asm.step ge_src se (Asm.State rs0 m0) tr (Asm.State rs1 m1))\n      b ofs p\n      (VALID: Mem.valid_block m0 b)\n      (PERM: Mem.perm m1 b ofs Max p):\n    Mem.perm m0 b ofs Max p.\nProof.\n  revert VALID.\n  replace m1 with (st_m (Asm.State rs1 m1)) in PERM; eauto.\n  replace m0 with (st_m (Asm.State rs0 m0)); eauto.\n  generalize dependent (Asm.State rs0 m0).\n  generalize dependent (Asm.State rs1 m1).\n  i. ginduction STEP; i; ss.\n- unfold exec_instr in *;\n      des_ifs; ss; clarify;\n        (all_once_fast ltac:(fun H=> try (eapply exec_load_mem_equal in H; clarify; fail)));\n        (try (eapply exec_store_max_perm; eauto; fail));\n        (try (by unfold goto_label in *; des_ifs)).\n    + eapply Mem.perm_store_2 in Heq1; eauto. eapply Mem.perm_store_2 in Heq0; eauto.\n      eapply Mem.perm_alloc_4; eauto. ii. clarify. eapply Mem.fresh_block_alloc; eauto.\n    + eapply Mem.perm_free_3; eauto.\n  - eapply external_call_max_perm; eauto.\n  - exploit external_call_max_perm; eauto.\nQed.\n\nLemma asm_step_readonly se ge_src rs0 rs1 m0 m1 tr\n      (STEP: Asm.step ge_src se (Asm.State rs0 m0) tr (Asm.State rs1 m1)):\n    Mem.unchanged_on (loc_not_writable m0) m0 m1.\nProof.\n  replace m1 with (st_m (Asm.State rs1 m1)); eauto.\n  replace m0 with (st_m (Asm.State rs0 m0)); eauto.\n  generalize dependent (Asm.State rs0 m0).\n  generalize dependent (Asm.State rs1 m1).\n  i. ginduction STEP; i; ss.\n  - unfold exec_instr, goto_label in *; des_ifs; ss; clarify; try refl;\n      (all_once_fast ltac:(fun H=> try (eapply exec_load_mem_equal in H; clarify; try refl; fail))); try (exploit exec_store_readonly; eauto; fail).\n    + eapply mem_readonly_trans; [eapply mem_alloc_readonly; eauto|].\n      eapply mem_readonly_trans; eapply mem_store_readonly; eauto.\n    + eapply mem_free_readonly; eauto.\n  - eapply external_call_readonly; eauto.\n  - eapply external_call_readonly; eauto.\nQed.\n\nLtac tac_p := ss; try (symmetry; eapply Ptrofs.add_zero; fail);\n              repeat ((try rewrite Ptrofs.add_assoc); (try rewrite Ptrofs.sub_add_l));\n              try (ss; f_equal; apply Ptrofs.add_commut).\n\nSection ASMSTEP.\n\n  Definition agree (j: meminj) (rs_src rs_tgt: regset) : Prop :=\n    forall pr, Val.inject j (rs_src pr) (rs_tgt pr).\n\n  Lemma agree_step j rs0 rs1 pr v0 v1\n        (AGREE: agree j rs0 rs1)\n        (INJ: Val.inject j v0 v1):\n      agree j (rs0 # pr <- v0) (rs1 # pr <- v1).\n  Proof. ii. unfold Pregmap.set. des_ifs. Qed.\n\n  Lemma inject_separated_refl j m_src m_tgt:\n      inject_separated j j m_src m_tgt.\n  Proof. ii. clarify. Qed.\n\n  Remark mull_inject:\n    forall f v1 v1' v2,\n      Val.inject f v1 v1' ->\n      Val.inject f (Val.mull v1 v2) (Val.mull v1' v2).\n  Proof.\n    intros. unfold Val.mull. des_ifs; inv H. econs.\n  Qed.\n\n  Lemma eval_addrmode_inject\n        j ge_src ge_tgt a rs_src0 rs_tgt0\n        (SYMBLE: forall i b_src\n            (FINDSRC: Genv.find_symbol ge_src i = Some b_src),\n            exists b_tgt,\n              (<<FINDTGT: Genv.find_symbol ge_tgt i = Some b_tgt>>) /\\\n              (<<INJ: j b_src = Some (b_tgt, 0)>>))\n        (AGREE: agree j rs_src0 rs_tgt0):\n      Val.inject j (eval_addrmode ge_src a rs_src0) (eval_addrmode ge_tgt a rs_tgt0).\n  Proof.\n    unfold eval_addrmode, eval_addrmode64 in *.\n    des_ifs; ss; repeat (eapply Val.addl_inject; eauto); try eapply mull_inject; eauto.\n    all: try (by unfold Genv.symbol_address in *; des_ifs; exploit SYMBLE; eauto; i; des; clarify; econs; eauto; tac_p).\n    all: try (by cinv (AGREE i); ss; unfold Genv.symbol_address in *; des_ifs;\n              exploit SYMBLE; eauto; i; des; clarify; econs; eauto; tac_p).\n    - cinv (AGREE i); ss; des_ifs; econs; eauto.\n      repeat (rewrite Ptrofs.add_assoc). f_equal. rewrite Ptrofs.add_commut. repeat (rewrite Ptrofs.add_assoc). auto.\n  Qed.\n\n  Lemma mem_storev_inject j chunk m_src0 m_tgt0 m_src1 a_src a_tgt v_src v_tgt\n        (INJ: Mem.inject j m_src0 m_tgt0)\n        (VALINJ0: Val.inject j a_src a_tgt)\n        (VALINJ1: Val.inject j v_src v_tgt)\n        (STORE: Mem.storev chunk m_src0 a_src v_src = Some m_src1):\n      exists m_tgt1,\n        (<<INJ: Mem.inject j m_src1 m_tgt1>>) /\\\n        (<<STORE: Mem.storev chunk m_tgt0 a_tgt v_tgt = Some m_tgt1>>) /\\\n        (<<UNCHSRC: Mem.unchanged_on (loc_unmapped j) m_src0 m_src1>>) /\\\n        (<<UNCHTGT: Mem.unchanged_on (loc_out_of_reach j m_src0) m_tgt0 m_tgt1>>).\n  Proof.\n    exploit Mem.storev_mapped_inject; eauto. i. des.\n    ss. unfold Mem.storev in *. des_ifs. esplits; eauto.\n    - eapply Mem.unchanged_on_implies.\n      + instantiate (1:= ~2 brange b0 (Ptrofs.unsigned i0) (Ptrofs.unsigned i0 + size_chunk chunk)).\n        eapply Mem.store_unchanged_on; eauto.\n      + ii. unfold loc_unmapped, brange in *. des. clarify. inv VALINJ0; clarify.\n    - eapply Mem.unchanged_on_implies.\n      + instantiate (1:= ~2 brange b (Ptrofs.unsigned i) (Ptrofs.unsigned i + size_chunk chunk)).\n        eapply Mem.store_unchanged_on; eauto.\n      + ii. unfold loc_out_of_reach, brange in *. des. clarify.\n        inv VALINJ0; clarify. eapply H1; eauto.\n        eapply Mem.store_valid_access_3 in STORE; eauto.\n        eapply Mem.perm_cur. unfold Mem.valid_access in *. des.\n        eapply Mem.perm_implies; try eapply STORE; eauto; try (by econs).\n        replace (Ptrofs.unsigned (Ptrofs.add i0 (Ptrofs.repr delta))) with\n            (Ptrofs.unsigned i0 + delta) in *; [nia|].\n        symmetry. erewrite Mem.address_inject; try apply INJ; eauto. eapply STORE. set (size_chunk_pos chunk). lia.\n  Qed.\n\n  Lemma mem_alloc_inject j m_src0 m_tgt0 m_src1 lo1 lo2 hi1 hi2 b_src\n        (INJ: Mem.inject j m_src0 m_tgt0)\n        (LO: lo2 <= lo1)\n        (HI: hi1 <= hi2)\n        (ALLOC: Mem.alloc m_src0 lo1 hi1 = (m_src1, b_src)):\n      exists m_tgt1,\n        (<<INJ: Mem.inject (update_meminj j (Mem.nextblock m_src0) (Mem.nextblock m_tgt0) 0) m_src1 m_tgt1>>) /\\\n        (<<ALLOC: Mem.alloc m_tgt0 lo2 hi2 = (m_tgt1, Mem.nextblock m_tgt0)>>) /\\\n        (<<UNCHSRC: Mem.unchanged_on (loc_unmapped j) m_src0 m_src1>>) /\\\n        (<<UNCHTGT: Mem.unchanged_on (loc_out_of_reach j m_src0) m_tgt0 m_tgt1>>).\n  Proof.\n    exploit Mem.alloc_parallel_inject; eauto. i. des.\n    exploit Mem.alloc_result; try apply ALLOC; eauto. i. clarify.\n    exploit Mem.alloc_result; try apply H; eauto. i. clarify.\n    replace f' with (update_meminj j (Mem.nextblock m_src0) (Mem.nextblock m_tgt0) 0) in *; cycle 1.\n    { extensionality b. unfold update_meminj in *. des_ifs. symmetry. eauto. }\n    esplits; eauto; eapply Mem.unchanged_on_implies; try eapply Mem.alloc_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_free_inject j m_src0 m_tgt0 m_src1 ofs_src ofs_tgt blk_src blk_tgt sz\n        (INJ: Mem.inject j m_src0 m_tgt0)\n        (VAL: Val.inject j (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt))\n        (FREE: Mem.free m_src0 blk_src (Ptrofs.unsigned ofs_src) (Ptrofs.unsigned (ofs_src) + sz) = Some m_src1):\n    exists m_tgt1,\n      (<<INJ: Mem.inject j m_src1 m_tgt1>>) /\\\n      (<<FREE: Mem.free m_tgt0 blk_tgt (Ptrofs.unsigned ofs_tgt) (Ptrofs.unsigned (ofs_tgt) + sz) = Some m_tgt1>>) /\\\n      (<<UNCHSRC: Mem.unchanged_on (loc_unmapped j) m_src0 m_src1>>) /\\\n      (<<UNCHTGT: Mem.unchanged_on (loc_out_of_reach j m_src0) m_tgt0 m_tgt1>>).\n  Proof.\n    exploit Mem_free_parallel_inject'; eauto. i. des. esplits; eauto.\n    - eapply Mem.unchanged_on_implies.\n      + eapply Mem.free_unchanged_on; eauto.\n        instantiate (1:=~2 brange blk_src (Ptrofs.unsigned ofs_src) (Ptrofs.unsigned ofs_src + sz)). eauto.\n      + ii. des. unfold brange, loc_unmapped in *. des. inv VAL. clarify.\n    - eapply Mem.unchanged_on_implies.\n      + eapply Mem.free_unchanged_on; eauto.\n        instantiate (1:=~2 brange blk_tgt (Ptrofs.unsigned ofs_tgt) (Ptrofs.unsigned ofs_tgt + sz)). eauto.\n      + ii. des. unfold brange, loc_out_of_reach in *. des. inv VAL. clarify.\n        assert (SZ: 0 < sz) by lia.\n        eapply H; eauto. eapply Mem.perm_cur. eapply Mem.perm_implies.\n        * eapply Mem.free_range_perm; eauto.\n          erewrite Mem.address_inject in H2; try apply INJ; eauto; cycle 1.\n          { eapply Mem.free_range_perm; eauto. lia. }\n          erewrite Mem.address_inject in H3; try apply INJ; eauto; cycle 1.\n          { eapply Mem.free_range_perm; eauto. lia. }\n          lia.\n        * econs.\n  Qed.\n\n  \n  Lemma exec_load_inject\n        j ge_src ge_tgt chunk m_src0 m_tgt0 m_src1 a rd rs_src0 rs_tgt0 rs_src1\n        (SYMBLE: forall i b_src\n            (FINDSRC: Genv.find_symbol ge_src i = Some b_src),\n            exists b_tgt,\n              (<<FINDTGT: Genv.find_symbol ge_tgt i = Some b_tgt>>) /\\\n              (<<INJ: j b_src = Some (b_tgt, 0)>>))\n        (AGREE: agree j rs_src0 rs_tgt0)\n        (INJ: Mem.inject j m_src0 m_tgt0)\n        (EXEC: exec_load ge_src chunk m_src0 a rs_src0 rd = Next rs_src1 m_src1) :\n      exists rs_tgt1,\n        (<<MEMSAME: m_src0 = m_src1>>) /\\\n        (<<AGREE: agree j rs_src1 rs_tgt1>>) /\\\n        (<<INJ: Mem.inject j m_src1 m_tgt0>>) /\\\n        (<<EXEC: exec_load ge_tgt chunk m_tgt0 a rs_tgt0 rd = Next rs_tgt1 m_tgt0>>) /\\\n        (<<UNCHSRC: Mem.unchanged_on (loc_unmapped j) m_src0 m_src1>>).\n  Proof.\n    exploit eval_addrmode_inject; eauto. intros ADDR. instantiate (1:=a) in ADDR.\n    unfold exec_load in *. des_ifs.\n    - eapply Mem.loadv_inject in Heq0; eauto; des; clarify. esplits; eauto; [|refl].\n      repeat (eapply agree_step; eauto). ss. unfold Pregmap.set in *.\n      specialize (AGREE PC). des_ifs; try by inv Heq1.\n      + inv Heq1; ss; econs; eauto; tac_p.\n      + inv AGREE; ss; econs; eauto; tac_p.\n    - eapply Mem.loadv_inject in Heq0; eauto; des; clarify.\n  Qed.\n\n  Lemma undef_regs_agree j l rs_src rs_tgt\n        (AGREE : agree j rs_src rs_tgt):\n      agree j (undef_regs l rs_src) (undef_regs l rs_tgt).\n  Proof.\n    revert rs_src rs_tgt AGREE. induction l; ss; i. ii.\n    unfold Pregmap.set in *. eapply IHl. ii. des_ifs.\n  Qed.\n\n  Lemma nextinstr_agree j rs_src rs_tgt\n        (AGREE: agree j rs_src rs_tgt):\n      agree j (nextinstr rs_src) (nextinstr rs_tgt).\n  Proof.\n    unfold nextinstr. apply agree_step; eauto.\n    apply Val.offset_ptr_inject; eauto.\n  Qed.\n\n  Lemma exec_store_inject\n        j ge_src ge_tgt chunk m_src0 m_tgt0 m_src1 a rd l rs_src0 rs_tgt0 rs_src1\n        (SYMBLE: forall i b_src\n            (FINDSRC: Genv.find_symbol ge_src i = Some b_src),\n            exists b_tgt,\n              (<<FINDTGT: Genv.find_symbol ge_tgt i = Some b_tgt>>) /\\\n              (<<INJ: j b_src = Some (b_tgt, 0)>>))\n        (AGREE: agree j rs_src0 rs_tgt0)\n        (INJ: Mem.inject j m_src0 m_tgt0)\n        (EXEC: exec_store ge_src chunk m_src0 a rs_src0 rd l = Next rs_src1 m_src1):\n      exists rs_tgt1 m_tgt1,\n        (<<AGREE: agree j rs_src1 rs_tgt1>>) /\\\n        (<<INJ: Mem.inject j m_src1 m_tgt1>>) /\\\n        (<<EXEC: exec_store ge_tgt chunk m_tgt0 a rs_tgt0 rd l = Next rs_tgt1 m_tgt1>>) /\\\n        (<<UNCHSRC: Mem.unchanged_on\n                      (loc_unmapped j)\n                      m_src0 m_src1>>) /\\\n        (<<UNCHTGT: Mem.unchanged_on\n                      (loc_out_of_reach j m_src0)\n                      m_tgt0 m_tgt1>>).\n  Proof.\n    exploit eval_addrmode_inject; eauto. intros ADDR.\n    hexploit undef_regs_agree; eauto. intros UAGREE.\n    instantiate (1:=a) in ADDR. unfold exec_store in *. des_ifs.\n    - exploit mem_storev_inject; try apply Heq0; eauto. i. des. clarify.\n      esplits; eauto. unfold nextinstr_nf, nextinstr. ss. repeat (eapply agree_step; eauto).\n      unfold Pregmap.set in *. specialize (UAGREE PC). des_ifs. eapply Val.offset_ptr_inject. eauto.\n    - eapply Mem.storev_mapped_inject in Heq0; cycle 1; eauto; des; clarify.\n  Qed.\n\n  Lemma regset_after_external_inject rs_src rs_tgt j\n        (AGREE: agree j rs_src rs_tgt):\n      agree j (regset_after_external rs_src) (regset_after_external rs_tgt).\n  Proof.\n    unfold regset_after_external in *. ii. des_ifs.\n  Qed.\n\n  Lemma set_pair_inject rs_src rs_tgt l v_src v_tgt j\n        (AGREE: agree j rs_src rs_tgt)\n        (VAL: Val.inject j v_src v_tgt):\n      agree j (set_pair l v_src rs_src) (set_pair l v_tgt rs_tgt).\n  Proof.\n    unfold set_pair. des_ifs; repeat (eapply agree_step; eauto).\n    - eapply Val.hiword_inject; eauto.\n    - eapply Val.loword_inject; eauto.\n  Qed.\n\n  Lemma extcall_arg_inject rs1 rs2 m1 m2 l arg1 j\n        (AGREE: agree j rs1 rs2)\n        (INJ: Mem.inject j m1 m2)\n        (ARGS: extcall_arg rs1 m1 l arg1):\n      exists arg2 : val,\n        (<<ARGINJ: Val.inject j arg1 arg2>>) /\\\n        (<<ARGS: extcall_arg rs2 m2 l arg2>>).\n  Proof.\n    inv ARGS.\n    - esplits; eauto. econs; eauto.\n    - exploit Mem.loadv_inject; eauto.\n      + eapply Val.offset_ptr_inject; eauto.\n      + i. des. esplits; eauto. econs; eauto.\n  Qed.\n\n  Lemma extcall_arg_pair_inject rs1 rs2 m1 m2 l arg1 j\n        (AGREE: agree j rs1 rs2)\n        (INJ: Mem.inject j m1 m2)\n        (ARGS: extcall_arg_pair rs1 m1 l arg1):\n      exists arg2 : val,\n        (<<ARGINJ: Val.inject j arg1 arg2>>) /\\\n        (<<ARGS: extcall_arg_pair rs2 m2 l arg2>>).\n  Proof.\n    inv ARGS.\n    - exploit extcall_arg_inject; eauto. i. des. esplits; eauto. econs; eauto.\n    - eapply extcall_arg_inject in H; eauto. eapply extcall_arg_inject in H0; eauto.\n      des. esplits; eauto.\n      + eapply Val.longofwords_inject; eauto.\n      + econs; eauto.\n  Qed.\n\n  Lemma extcall_arguments_inject rs1 rs2 m1 m2 sg args1 j\n        (AGREE: agree j rs1 rs2)\n        (INJ: Mem.inject j m1 m2)\n        (ARGS: extcall_arguments rs1 m1 sg args1):\n      exists args2 : list val,\n        (<<ARGINJ: Val.inject_list j args1 args2>>) /\\\n        (<<ARGS: extcall_arguments rs2 m2 sg args2>>).\n  Proof.\n    unfold extcall_arguments in *.\n    revert args1 ARGS. induction (loc_arguments sg); ss; i; inv ARGS.\n    - esplits; eauto. econs.\n    - exploit IHl; eauto.\n      exploit extcall_arg_pair_inject; eauto. i. des.\n      exists (arg2::args2). esplits; eauto. econs; eauto.\n  Qed.\n\n  Lemma eval_builtin_arg_inject A F V (ge1 ge2: Genv.t F V) e1 e2 sp1 sp2 m1 m2 j\n        (SYMBLE: forall i b_src\n            (FINDSRC: Genv.find_symbol ge1 i = Some b_src),\n            exists b_tgt,\n              (<<FINDTGT: Genv.find_symbol ge2 i = Some b_tgt>>) /\\\n              (<<INJ: j b_src = Some (b_tgt, 0)>>))\n        (VALS: forall x : A, Val.inject j (e1 x) (e2 x))\n        (INJ: Mem.inject j m1 m2)\n        (a : builtin_arg A) (v1 : val)\n        (EVAL: eval_builtin_arg ge1 e1 sp1 m1 a v1)\n        (SPINJ: Val.inject j sp1 sp2):\n      exists v2 : val,\n        (<<EVAL: eval_builtin_arg ge2 e2 sp2 m2 a v2>>) /\\\n        (<<VAL: Val.inject j v1 v2>>).\n  Proof.\n    revert v1 EVAL. induction a; i; inv EVAL; ss; try (esplits; eauto; econs; eauto; fail).\n    - exploit Mem.loadv_inject; eauto; ss; i.\n      + eapply Val.offset_ptr_inject; eauto.\n      + des. esplits; eauto. econs. eauto.\n    - esplits; eauto; try econs. eapply Val.offset_ptr_inject; eauto.\n    - exploit Mem.loadv_inject; eauto.\n      + instantiate (1:= Senv.symbol_address ge2 id ofs).\n        unfold Senv.symbol_address in *. ss.\n        des_ifs_safe. exploit SYMBLE; eauto. i. des. rewrite FINDTGT. econs; eauto. psimpl. auto.\n      + i. des. esplits; eauto. econs; eauto.\n    - esplits; eauto; try econs.\n      + unfold Senv.symbol_address in *. ss.\n        des_ifs_safe. exploit SYMBLE; eauto. i. des. rewrite FINDTGT. econs; eauto. psimpl. auto.\n    - eapply IHa1 in H1. eapply IHa2 in H3. des.\n      esplits; eauto; try econs; eauto. eapply Val.longofwords_inject; eauto.\n    - eapply IHa1 in H1. eapply IHa2 in H3. des.\n      esplits; eauto; try econs; eauto. des_ifs. eapply Val.addl_inject; eauto.\n  Qed.\n\n  Lemma eval_builtin_args_inject A F V (ge1 ge2: Genv.t F V) e1 e2 sp1 sp2 m1 m2 j\n        (SYMBLE: forall i b_src\n            (FINDSRC: Genv.find_symbol ge1 i = Some b_src),\n            exists b_tgt,\n              (<<FINDTGT: Genv.find_symbol ge2 i = Some b_tgt>>) /\\\n              (<<INJ: j b_src = Some (b_tgt, 0)>>))\n        (VALS: forall x : A, Val.inject j (e1 x) (e2 x))\n        (INJ: Mem.inject j m1 m2)\n        (al : list (builtin_arg A)) (vl1 : list val)\n        (EVAL: eval_builtin_args ge1 e1 sp1 m1 al vl1)\n        (SPINJ: Val.inject j sp1 sp2):\n      exists vl2 : list val,\n        (<<EVAL: eval_builtin_args ge2 e2 sp2 m2 al vl2>>) /\\\n        (<<VALLIST: Val.inject_list j vl1 vl2>>).\n  Proof.\n    revert al EVAL. induction vl1; ss; i; inv EVAL.\n    - esplits; econs.\n    - exploit IHvl1; eauto. i. des.\n      exploit eval_builtin_arg_inject; eauto. i. des.\n      exists (v2::vl2). splits; eauto. econs; eauto.\n  Qed.\n\n  Lemma agree_incr rs_src rs_tgt j0 j1\n        (AGREE: agree j0 rs_src rs_tgt)\n        (INCR: inject_incr j0 j1):\n      agree j1 rs_src rs_tgt.\n  Proof. ii. eauto. Qed.\n\n  Lemma set_res_agree j res vres vres' rs_src rs_tgt\n        (AGREE: agree j rs_src rs_tgt)\n        (INJ: Val.inject j vres vres'):\n      agree j (set_res res vres rs_src) (set_res res vres' rs_tgt).\n  Proof.\n    revert rs_src rs_tgt AGREE vres vres' INJ. induction res; ss; i.\n    - apply agree_step; eauto.\n    - eapply IHres2; eauto.\n      + eapply IHres1; eauto. eapply Val.hiword_inject; eauto.\n      + eapply Val.loword_inject; eauto.\n  Qed.\n\n  Lemma unsigned_add ofs delta\n        (RANGE: delta >= 0 /\\ 0 <= Ptrofs.unsigned ofs + delta <= Ptrofs.max_unsigned):\n      Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta)) = Ptrofs.unsigned ofs + delta.\n  Proof.\n    rewrite Ptrofs.add_unsigned. replace (Ptrofs.unsigned (Ptrofs.repr delta)) with delta.\n    * eapply Ptrofs.unsigned_repr; eauto. des. splits; eauto.\n    * symmetry. eapply Ptrofs.unsigned_repr; eauto. des. splits; [xomega|].\n      assert (Ptrofs.unsigned ofs >= 0); [|xomega].\n      set (Ptrofs.unsigned_range ofs). des. xomega.\n  Qed.\n\n  Lemma cmplu_inject j rs_src rs_tgt v1_src v2_src v1_tgt v2_tgt m_src m_tgt c\n        (AGREE: agree j rs_src rs_tgt)\n        (INJ: Mem.inject j m_src m_tgt)\n        (VAL1: Val.inject j v1_src v1_tgt)\n        (VAL2: Val.inject j v2_src v2_tgt):\n      Val.inject j (Val.maketotal (Val.cmplu (Mem.valid_pointer m_src) c v1_src v2_src))\n                 (Val.maketotal (Val.cmplu (Mem.valid_pointer m_tgt) c v1_tgt v2_tgt)).\n  Proof.\n    unfold Val.cmplu. inv INJ. inv mi_inj. unfold Val.maketotal, option_map.\n    destruct (Val.cmplu_bool (Mem.valid_pointer m_src) c v1_src v2_src) eqn: CMP_SRC; eauto.\n    replace (Val.cmplu_bool (Mem.valid_pointer m_tgt) c v1_tgt v2_tgt) with (Some b); eauto.\n    { unfold Val.of_bool; des_ifs; econs. }\n    erewrite Val.cmplu_bool_inject; eauto; ss; i; unfold Mem.valid_pointer, proj_sumbool in *; eauto; ss; i; des_ifs.\n    all: try (by exfalso; eapply n; exploit mi_perm; eauto; exploit mi_representable; eauto;\n              [left; eapply Mem.perm_max; eauto| i; erewrite unsigned_add; eauto]).\n    all: try (by exploit mi_perm; eauto; exploit mi_representable; eauto;\n                [left; eapply Mem.perm_max; eauto|\n                 i; erewrite Ptrofs.unsigned_repr; des; split; try xomega; set (Ptrofs.unsigned_range ofs); des; xomega]).\n    - exfalso. eapply n0.\n      exploit mi_perm; eauto. i.\n      exploit mi_representable; eauto.\n      + right; eapply Mem.perm_max; eauto.\n      + i. erewrite unsigned_add; eauto. rp; eauto. xomega.\n    - exploit mi_perm; eauto. i.\n      exploit mi_representable; eauto.\n      + right. eapply Mem.perm_max; eauto.\n      + i. erewrite Ptrofs.unsigned_repr; des; split; try xomega. set (Ptrofs.unsigned_range ofs). des. xomega.\n    - exploit mi_no_overlap; eauto using Mem.perm_max.\n      + i. erewrite unsigned_add; eauto; cycle 1.\n        { exploit mi_representable; cycle 1; eauto. left. eapply Mem.perm_max; eauto. }\n        erewrite unsigned_add; eauto; cycle 1.\n        { exploit mi_representable; cycle 1; eauto. left. eapply Mem.perm_max; eauto. }\n  Qed.\n\n  Lemma compare_longs_inject j rs_src rs_tgt v1_src v2_src v1_tgt v2_tgt m_src m_tgt\n        (AGREE: agree j rs_src rs_tgt)\n        (INJ: Mem.inject j m_src m_tgt)\n        (VAL1: Val.inject j v1_src v1_tgt)\n        (VAL2: Val.inject j v2_src v2_tgt):\n      agree j (compare_longs v1_src v2_src rs_src m_src) (compare_longs v1_tgt v2_tgt rs_tgt m_tgt).\n  Proof.\n    unfold compare_longs. eapply agree_step; eauto. eapply agree_step; eauto; cycle 1.\n    { inv VAL1; inv VAL2; clarify; ss; econs. }\n    eapply agree_step; eauto; cycle 1.\n    { exploit (Val.subl_inject j v1_src v1_tgt v2_src v2_tgt); eauto. intros VAL. inv VAL; eauto; ss. }\n    eapply agree_step; eauto; cycle 1.\n    { eapply cmplu_inject; eauto. }\n    eapply agree_step; eauto; cycle 1.\n    { eapply cmplu_inject; eauto. }\n  Qed.\n\n  Ltac tac_sl := try (esplits; [\n                        econs; eauto; ss|\n                        unfold nextinstr_nf, nextinstr; ss;\n                        repeat (eapply agree_step; eauto);\n                        u;\n                        unfold Val.offset_ptr in *;\n                        unfold Pregmap.set in *; des_ifs; eq_closure_tac;\n                        econs; eauto; rewrite Ptrofs.add_zero; refl|\n                        eauto|\n                        refl|\n                        eapply inject_separated_refl]).\n\n  Ltac tac_ld :=\n    (all_once_fast ltac:(fun H => try (eapply exec_load_inject in H; try eassumption; check_safe;\n                                       eauto; des; esplits; eauto;\n                                       [econs; eauto|\n                                        eapply inject_separated_refl|refl]))); fail.\n\n  Ltac tac_st :=\n    (all_once_fast ltac:(fun H => try (eapply exec_store_inject in H; try eassumption; check_safe;\n                                       eauto; des; esplits; eauto;\n                                       [econs; eauto|\n                                        eapply inject_separated_refl]))); fail.\n\n  Ltac agree_inv AGREE :=\n    match goal with\n    | [|- context[(?rs: regset -> val) (?pr: preg)]] => cinv (AGREE pr)\n    end; ss.\n\n  Ltac agree_invs AGREE := repeat (agree_inv AGREE).\n\n  Ltac propagate_eq_typ TYP :=\n    repeat (multimatch goal with\n            | [H1: @eq TYP ?A ?B, H2: @eq TYP ?B ?C |- _ ] =>\n              tryif (check_equal A C)\n              then fail\n              else\n                tryif (exists_prop (A = C) + exists_prop (C = A))\n                then idtac\n                else\n                  let name := fresh \"EQ_CLOSURE_TAC\" in\n                  hexploit eq_trans; [exact H1|exact H2|]; intro name\n            | [H1: ?B = ?A, H2: ?B = ?C |- _ ] =>\n              tryif (check_equal A C)\n              then fail\n              else\n                tryif (exists_prop (A = C) + exists_prop (C = A))\n                then idtac\n                else\n                  let name := fresh \"EQ_CLOSURE_TAC\" in\n                  hexploit eq_trans; [exact (eq_sym H1)|exact H2|]; intro name\n            end).\n\n  Ltac eq_closure_tac_typ TYP :=\n    repeat (propagate_eq_typ TYP; clarify).\n\n  Lemma zero_ext_inject n v1 v2 j\n        (INJ: Val.inject j v1 v2):\n      Val.inject j (Val.zero_ext n v1) (Val.zero_ext n v2).\n  Proof.\n    unfold Val.zero_ext in *. des_ifs; inv INJ. econs.\n  Qed.\n\n  Lemma sign_ext_inject n v1 v2 j\n        (INJ: Val.inject j v1 v2):\n      Val.inject j (Val.sign_ext n v1) (Val.sign_ext n v2).\n  Proof. inv INJ; ss. Qed.\n\n  Lemma agree_ir (i: ireg):\n      forall j rs_src rs_tgt\n             (AGREE: agree j rs_src rs_tgt),\n        Val.inject j (rs_src i) (rs_tgt i).\n  Proof. eauto. Qed.\n\n  (* Lemma val_long_same_inj v1 v2 j *)\n  (*       (EQ: v1 = v2): *)\n  (*     Val.inject j (Vlong v1) (Vlong v2). *)\n  (* Proof. clarify. Qed. *)\n\n  (* Lemma val_float_same_inj v1 v2 j *)\n  (*       (EQ: v1 = v2): *)\n  (*     Val.inject j (Vfloat v1) (Vfloat v2). *)\n  (* Proof. clarify. Qed. *)\n\n  (* Lemma val_int_same_inj v1 v2 j *)\n  (*       (EQ: v1 = v2): *)\n  (*     Val.inject j (Vint v1) (Vint v2). *)\n  (* Proof. clarify. Qed. *)\n\n  (* Lemma val_single_same_inj v1 v2 j *)\n  (*       (EQ: v1 = v2) *)\n  (*   : *)\n  (*     Val.inject j (Vsingle v1) (Vsingle v2). *)\n  (* Proof. *)\n  (*   clarify. *)\n  (* Qed. *)\n\n  Ltac val_inj_tac :=\n    ((econs; eauto) || clarify).\n     (* (eapply val_long_same_inj) || *)\n     (* (eapply val_float_same_inj) || *)\n     (* (eapply val_int_same_inj) || *)\n     (* (eapply val_single_same_inj)). *)\n\n  Ltac tac_cal AGREE :=\n    try (progress (unfold goto_label in *); des_ifs_safe);\n         (esplits; eauto; [econs; eauto; ss; try (unfold goto_label in *; des_ifs; fail)\n                          | repeat (eapply agree_step; eauto); ss;\n                            (fail|| idtac; [.. |unfold Val.offset_ptr;\n                                                repeat (try (rewrite Pregmap.gss);\n                                                        (try (rewrite Pregmap.gso; [| ii; clarify; fail]))); des_ifs;\n                                                try (val_inj_tac; ss; tac_p)]);\n                            (try ((agree_invs AGREE); ss; unfold option_map, Val.maketotal; des_ifs; ss; val_inj_tac; tac_p; check_safe))\n                          | eapply inject_separated_refl|refl|refl]).\n\n  Lemma eval_testcond_inj rs_src rs_tgt j c v\n        (AGREE: agree j rs_src rs_tgt)\n        (EVAL: eval_testcond c rs_src = Some v):\n      eval_testcond c rs_tgt = Some v.\n  Proof.\n    unfold eval_testcond in *. destruct c; revert EVAL; agree_invs AGREE.\n  Qed.\n\n  Lemma update_meminj_incr j b_src b_tgt ofs\n        (NONE: j b_src = None):\n      inject_incr j (update_meminj j b_src b_tgt ofs).\n  Proof. unfold update_meminj. ii. des_ifs. Qed.\n\n  Local Opaque Mem.storev.\n  Theorem asm_step_preserve_injection\n        rs_src0 rs_src1 m_src0 m_src1 tr j0 rs_tgt0 m_tgt0 se_src se_tgt ge_src ge_tgt\n\n        (GENV: meminj_match_globals (@def_match _ _) ge_src ge_tgt j0)\n        (SYMBINJ: symbols_inject_weak j0 se_src se_tgt m_src0)\n        (* (NOEXTFUN: no_extern_fun ge_src) *)\n        (AGREE: agree j0 rs_src0 rs_tgt0)\n        (INJ: Mem.inject j0 m_src0 m_tgt0)\n        (STEP: Asm.step se_src ge_src (Asm.State rs_src0 m_src0) tr (Asm.State rs_src1 m_src1)):\n      exists rs_tgt1 m_tgt1 j1,\n        (<<STEP: Asm.step se_tgt ge_tgt (Asm.State rs_tgt0 m_tgt0) tr (Asm.State rs_tgt1 m_tgt1)>>) /\\\n        (<<AGREE: agree j1 rs_src1 rs_tgt1>>) /\\\n        (<<INJ: Mem.inject j1 m_src1 m_tgt1>>) /\\\n        (<<INCR: inject_incr j0 j1>>) /\\\n        (<<SEP: inject_separated j0 j1 m_src0 m_tgt0>>) /\\\n\n        (<<UNCHSRC: Mem.unchanged_on\n                      (loc_unmapped j0)\n                      m_src0 m_src1>>) /\\\n        (<<UNCHTGT: Mem.unchanged_on\n                      (loc_out_of_reach j0 m_src0)\n                      m_tgt0 m_tgt1>>)\n  .\n  Proof.\n    inv GENV. inv STEP.\n\n    - cinv (AGREE PC); eq_closure_tac.\n\n      assert (delta = 0).\n      { unfold Genv.find_funct_ptr in *. des_ifs. exploit DEFLE; eauto. i. des. eauto. }\n\n      assert (FIND: Genv.find_funct_ptr ge_tgt b2 = Some (Internal f)).\n      { unfold Genv.find_funct_ptr in *. des_ifs_safe.\n        exploit DEFLE; eauto. i. des. rewrite FINDTGT in *. inv DEFMATCH; auto. }\n\n      clarify.\n      replace (Ptrofs.add ofs (Ptrofs.repr 0)) with ofs in *; cycle 1.\n      { rewrite Ptrofs.add_zero. refl. }\n\n      assert (ADDRINJ: forall id ofs, Val.inject j0 (Genv.symbol_address ge_src id ofs) (Genv.symbol_address ge_tgt id ofs)).\n      { i. unfold Genv.symbol_address. des_ifs_safe. exploit SYMBLE; eauto. i. des.\n        rewrite FINDTGT. econs; eauto. psimpl. auto.\n      }\n\n      unfold exec_instr in *. des_ifs; ss; clarify.\n\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_ld.\n      + tac_st.\n      + tac_st.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_st.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_st.\n      + tac_ld.\n      + tac_st.\n      + tac_ld.\n      + tac_st.\n      + tac_st.\n      + tac_st.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n        unfold eval_addrmode32.\n        des_ifs; agree_invs AGREE; ss;\n          try (match goal with\n               | [|- context[Genv.symbol_address ge_src ?ib ?io]] => cinv (ADDRINJ ib io)\n               end; des_ifs).\n      + tac_cal AGREE.\n        unfold eval_addrmode64. des_ifs.\n        des_ifs; agree_invs AGREE; ss; (replace Archi.ptr64 with true; [|eauto]);\n          (repeat (eapply Val.addl_inject); eauto); try val_inj_tac; tac_p.\n        all: repeat (eapply Val.addl_inject); eauto; try eapply mull_inject; eauto.\n        f_equal. rewrite Ptrofs.add_permut. f_equal. apply Ptrofs.add_commut.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n        agree_invs AGREE; des_ifs; unfold andb, proj_sumbool in *; des_ifs; clarify.\n        rewrite <- Ptrofs.sub_add_l. rewrite Ptrofs.sub_shifted. eauto.\n     + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + esplits; eauto.\n        * econs; eauto; ss.\n          cinv (AGREE RDX); rewrite Heq in *; clarify.\n          cinv (AGREE RAX); rewrite Heq0 in *; clarify.\n          cinv (AGREE r1); rewrite Heq1 in *; clarify.\n          rewrite Heq2.\n          ss.\n        * unfold nextinstr_nf, nextinstr; ss.\n          repeat (eapply agree_step; eauto).\n          apply Val.offset_ptr_inject; ss.\n          repeat (rewrite Pregmap.gso; [| ii; clarify; fail]). eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n          cinv (AGREE RDX); rewrite Heq in *; clarify.\n          cinv (AGREE RAX); rewrite Heq0 in *; clarify.\n          cinv (AGREE r1); rewrite Heq1 in *; clarify.\n          rewrite Heq2.\n          ss.\n        * unfold nextinstr_nf, nextinstr; ss.\n          repeat (eapply agree_step; eauto).\n          apply Val.offset_ptr_inject; ss.\n          repeat (rewrite Pregmap.gso; [| ii; clarify; fail]). eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n          cinv (AGREE RDX); rewrite Heq in *; clarify.\n          cinv (AGREE RAX); rewrite Heq0 in *; clarify.\n          cinv (AGREE r1); rewrite Heq1 in *; clarify.\n          rewrite Heq2.\n          ss.\n        * unfold nextinstr_nf, nextinstr; ss.\n          repeat (eapply agree_step; eauto).\n          apply Val.offset_ptr_inject; ss.\n          repeat (rewrite Pregmap.gso; [| ii; clarify; fail]). eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n          cinv (AGREE RDX); rewrite Heq in *; clarify.\n          cinv (AGREE RAX); rewrite Heq0 in *; clarify.\n          cinv (AGREE r1); rewrite Heq1 in *; clarify.\n          rewrite Heq2.\n          ss.\n        * unfold nextinstr_nf, nextinstr; ss.\n          repeat (eapply agree_step; eauto).\n          apply Val.offset_ptr_inject; ss.\n          repeat (rewrite Pregmap.gso; [| ii; clarify; fail]). eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * repeat (eapply agree_step; eauto); ss.\n          -- agree_inv AGREE; des_ifs.\n             agree_inv AGREE; des_ifs.\n          -- eapply Val.offset_ptr_inject.\n             repeat (try (rewrite Pregmap.gss);\n                     (try (rewrite Pregmap.gso; [| ii; clarify; fail]))); des_ifs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_ints. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n         eapply compare_longs_inject; eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_ints. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          apply compare_longs_inject; eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_ints. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_ints. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.of_bool. des_ifs; econs.\n          -- unfold Val.of_bool. des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_ints. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n          -- unfold Val.cmpu, Val.cmpu_bool; ss.\n             des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * apply nextinstr_agree.\n          unfold compare_longs. (repeat eapply agree_step; eauto); agree_invs AGREE.\n          -- unfold Val.of_bool. des_ifs; econs.\n          -- unfold Val.of_bool. des_ifs; econs.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * exploit eval_testcond_inj; eauto. intro T. rewrite T.\n          repeat (eapply agree_step; eauto); ss.\n          eapply Val.offset_ptr_inject. apply agree_step; eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * exploit eval_testcond_inj; eauto. intro T. rewrite T.\n          repeat (eapply agree_step; eauto); ss.\n          eapply Val.offset_ptr_inject. eauto.\n          eapply AGREE.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * unfold nextinstr. des_ifs; ss; repeat eapply agree_step; eauto.\n          -- apply Val.offset_ptr_inject.\n             repeat (rewrite Pregmap.gso; [| ii; clarify]). eauto.\n          -- unfold Pregmap.set. ii. des_ifs; eauto.\n             eapply Val.offset_ptr_inject. eapply AGREE.\n          -- apply Val.offset_ptr_inject.\n             repeat (rewrite Pregmap.gso; [| ii; clarify]). eauto.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * repeat (eapply agree_step; eauto); ss.\n          -- unfold Val.of_optbool.\n             des_ifs; try econs.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n          -- apply Val.offset_ptr_inject. apply agree_step; eauto.\n             unfold Val.of_optbool.\n             des_ifs; try econs.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n             ++ erewrite eval_testcond_inj in Heq0; ss; eauto; clarify.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * repeat (eapply agree_step; eauto); ss.\n          -- unfold compare_floats.\n             cinv (AGREE r1); ss; repeat (eapply agree_step; eauto).\n             ++ cinv (AGREE r2); ss; repeat (eapply agree_step; eauto).\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** des_ifs; repeat (eapply agree_step; eauto).\n             ++ des_ifs; repeat (eapply agree_step; eauto).\n          -- apply Val.offset_ptr_inject.\n             unfold compare_floats.\n             cinv (AGREE r1); ss; repeat (eapply agree_step; eauto).\n             ++ cinv (AGREE r2); ss; repeat (eapply agree_step; eauto).\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** unfold Val.of_bool. des_ifs; econs.\n                ** des_ifs; repeat (eapply agree_step; eauto).\n             ++ des_ifs; repeat (eapply agree_step; eauto).\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + esplits; eauto.\n        * econs; eauto; ss.\n        * unfold nextinstr.\n          apply agree_step; eauto.\n          -- unfold compare_floats32.\n             agree_inv AGREE; repeat (eapply agree_step; eauto).\n             ++ agree_inv AGREE; repeat (eapply agree_step; eauto);\n                  try (unfold Val.of_bool; des_ifs; econs).\n                des_ifs; repeat (eapply agree_step; eauto);\n                  try (unfold Val.of_bool; des_ifs; econs).\n             ++ des_ifs; repeat (eapply agree_step; eauto);\n                  try (unfold Val.of_bool; des_ifs; econs).\n          -- apply Val.offset_ptr_inject; eauto.\n             unfold compare_floats32.\n             cinv (AGREE r1); ss; unfold Pregmap.set; des_ifs; clarify; ss.\n        * eapply inject_separated_refl.\n        * refl.\n        * refl.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n        erewrite eval_testcond_inj; ss; eauto. unfold goto_label, nextinstr. des_ifs; clarify.\n        repeat f_equal. tac_p.\n      + tac_cal AGREE.\n        erewrite eval_testcond_inj; ss; eauto. unfold goto_label, nextinstr.\n        repeat f_equal. agree_inv AGREE; eq_closure_tac_typ val. f_equal. tac_p.\n      + tac_cal AGREE.\n        repeat erewrite (@eval_testcond_inj rs_src0 rs_tgt0); ss; eauto. unfold goto_label, nextinstr. des_ifs; clarify.\n        repeat f_equal. tac_p.\n      + tac_cal AGREE.\n        repeat erewrite (@eval_testcond_inj rs_src0 rs_tgt0); ss; eauto. unfold goto_label, nextinstr.\n        repeat f_equal. agree_inv AGREE; eq_closure_tac_typ val. f_equal. tac_p.\n      + tac_cal AGREE.\n        repeat erewrite (@eval_testcond_inj rs_src0 rs_tgt0); ss; eauto. unfold goto_label, nextinstr.\n        repeat f_equal. agree_inv AGREE; eq_closure_tac_typ val. tac_p.\n      + tac_cal AGREE.\n        * replace (rs_tgt0 r) with (Vint i); cycle 1.\n          { cinv (AGREE r); eq_closure_tac_typ val. }\n          rewrite Heq0. unfold goto_label. rewrite Heq1.\n          repeat (rewrite Pregmap.gso; [| ii; clarify; fail]).\n          rewrite <- H1. repeat f_equal. instantiate (1:=0). tac_p.\n        * repeat (rewrite Pregmap.gso in *; [| ii; clarify; fail]).\n          rewrite H3 in *; clarify.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_cal AGREE.\n      + tac_ld.\n      + tac_st.\n      + tac_ld.\n      + tac_st.\n      +\ntac_cal AGREE.\n      + exploit Mem.alloc_result; eauto. i. clarify.\n        exploit mem_alloc_inject; eauto; try refl. i. des.\n        assert (INCR: inject_incr j0 (update_meminj j0 (Mem.nextblock m_src0) (Mem.nextblock m_tgt0) 0)).\n        { unfold update_meminj. ii. des_ifs. exfalso.\n          exploit Mem.valid_block_inject_1; eauto. i. eapply Plt_strict; eauto. }\n        exploit mem_storev_inject; try apply Heq0; eauto.\n        { psimpl. econs; eauto. unfold update_meminj. des_ifs. }\n        i. des.\n        exploit mem_storev_inject; try apply Heq1; eauto.\n        { psimpl. econs; eauto. unfold update_meminj. des_ifs. }\n        i. des.\n        esplits; try apply INJ2; eauto.\n        * econs; eauto. ss. rewrite ALLOC.\n          psimpl. rewrite STORE. rewrite STORE0. ss.\n        * eapply nextinstr_agree; eauto.\n          repeat eapply agree_step; eauto.\n          { eapply agree_incr; eauto. }\n          { econs. unfold update_meminj. des_ifs. ss. }\n        * ii. unfold update_meminj in *. des_ifs.\n          esplits; apply Plt_strict.\n        * erewrite Mem_unchanged_on_strengthen in *.\n          eapply Mem.unchanged_on_trans; eauto.\n          eapply Mem.unchanged_on_trans; eapply Mem.unchanged_on_implies; eauto.\n          { ii; des; esplits; eauto; unfold loc_unmapped, update_meminj in *.\n            des_ifs. exfalso. eapply Plt_strict; eauto. }\n          { ii; des; esplits; eauto; unfold loc_unmapped, update_meminj in *.\n            des_ifs. exfalso. eapply Plt_strict; eauto. }\n        * erewrite Mem_unchanged_on_strengthen in *.\n          eapply Mem.unchanged_on_trans; eauto.\n          eapply Mem.unchanged_on_trans; eapply Mem.unchanged_on_implies; eauto.\n          { ii; des; esplits; eauto; unfold loc_out_of_reach, update_meminj in *.\n            ii; des_ifs.\n            - eapply Plt_strict; eauto.\n            - eapply H4; eauto. eapply Mem.perm_alloc_4; eauto. }\n          { ii. ss. des. split; eauto. ii.\n            unfold update_meminj in *. ii. des_ifs.\n            - eapply Plt_strict; eauto.\n            - exploit H4; eauto. eapply Mem.perm_alloc_4; eauto.\n              Local Transparent Mem.storev. ss.\n              eapply Mem.perm_store_2; eauto. }\n\n      + cinv (AGREE RSP); rewrite Heq1 in *; clarify.\n        exploit mem_free_inject; try apply Heq2; eauto. i. des. zsimpl.\n        exploit Mem.load_inject; try apply Heq; eauto. i. des.\n        exploit Mem.load_inject; try apply Heq0; eauto. i. des.\n\n        esplits; eauto.\n        * econs; eauto; ss. rewrite <- H4. ss.\n          replace (Ptrofs.unsigned (Ptrofs.add (Ptrofs.add i (Ptrofs.repr delta)) ofs_ra)) with\n              (Ptrofs.unsigned (Ptrofs.add i ofs_ra) + delta); cycle 1.\n          { symmetry.\n            rewrite Ptrofs.add_commut.\n            rewrite <- Ptrofs.add_assoc.\n            rewrite (Ptrofs.add_commut i ofs_ra).\n            eapply Mem.address_inject; try apply INJ; eauto.\n            eapply Mem.load_valid_access; try apply Heq; eauto.\n            rewrite (Ptrofs.add_commut ofs_ra i).\n            set (size_chunk_pos Mptr). lia. }\n          replace (Ptrofs.unsigned (Ptrofs.add (Ptrofs.add i (Ptrofs.repr delta)) ofs_link)) with\n              (Ptrofs.unsigned (Ptrofs.add i ofs_link) + delta); cycle 1.\n          { symmetry.\n            rewrite Ptrofs.add_commut.\n            rewrite <- Ptrofs.add_assoc.\n            rewrite (Ptrofs.add_commut i ofs_link).\n            eapply Mem.address_inject; try apply INJ; eauto.\n            eapply Mem.load_valid_access; try apply Heq0; eauto.\n            rewrite (Ptrofs.add_commut ofs_link i).\n            set (size_chunk_pos Mptr). lia. }\n          rewrite H. rewrite H8.\n          rewrite FREE. ss.\n        * eapply nextinstr_agree. repeat eapply agree_step; eauto.\n        * eapply inject_separated_refl.\n    - exploit eval_builtin_args_inject; eauto. i. des.\n      exploit ec_mem_inject_weak; eauto.\n      { apply external_call_spec. }\n      i. des.\n      esplits; eauto.\n      + cinv (AGREE PC); eq_closure_tac_typ val. econs 2; eauto.\n        * unfold Genv.find_funct_ptr in *. instantiate (1:=f).\n          des_ifs_safe.\n          exploit DEFLE; eauto. i. des. rewrite FINDTGT.\n          inv DEFMATCH. auto.\n        * assert (delta = 0).\n          { unfold Genv.find_funct_ptr in *.\n            des_ifs_safe.\n            exploit DEFLE; eauto. i. des. auto. }\n          clarify.\n          psimpl. eauto.\n      + eapply agree_incr in AGREE; eauto.\n        unfold nextinstr_nf. eapply nextinstr_agree.\n        eapply undef_regs_agree.\n        eapply set_res_agree; eauto.\n        eapply undef_regs_agree. eauto.\n\n    - exploit extcall_arguments_inject; eauto. i. des.\n      exploit ec_mem_inject_weak; eauto.\n      { apply external_call_spec. }\n      i. des.\n      esplits; eauto.\n      + cinv (AGREE PC); eq_closure_tac_typ val. econs 3; eauto.\n        * assert (delta = 0).\n          { unfold Genv.find_funct_ptr in *.\n            des_ifs_safe.\n            exploit DEFLE; eauto. i. des. auto. }\n          clarify.\n          psimpl. eauto.\n        * unfold Genv.find_funct_ptr in *.\n          unfold Genv.find_funct_ptr in *.\n          des_ifs_safe.\n          exploit DEFLE; eauto. i. des. rewrite FINDTGT.\n          inv DEFMATCH. auto.\n      + eapply agree_step; eauto.\n        eapply set_pair_inject; eauto.\n        eapply regset_after_external_inject; eauto.\n        eapply agree_incr; eauto.\n  Qed.\n\nEnd ASMSTEP.\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/selfsim/AsmStepInj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30735800417608683, "lm_q1q2_score": 0.1608774337942195}}
{"text": "Require Import Coq.omega.Omega.\n(** This file implements symbolic evaluation for the\n ** language defined in IL.v\n **)\nRequire Import Bedrock.IL Bedrock.SepIL.\nRequire Import Bedrock.Word Bedrock.Memory.\nRequire Import Bedrock.DepList Bedrock.EqdepClass.\nRequire Import Bedrock.PropX.\nRequire Import Bedrock.SepExpr Bedrock.SymEval.\nRequire Import Bedrock.Expr.\nRequire Import Bedrock.Prover.\nRequire Import Bedrock.Env Bedrock.TypedPackage.\nImport List.\n\nRequire Bedrock.Structured Bedrock.SymEval.\nRequire Import Bedrock.ILEnv Bedrock.SymIL.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** The Symolic Evaluation Interfaces *)\nModule MEVAL := SymIL.MEVAL.\n\nModule SymIL_Correct.\n  Section typed.\n    Variable ts : list type.\n    Let types := repr bedrock_types_r ts.\n\n    Notation pcT := (tvType 0).\n    Notation tvWord := (tvType 0).\n    Notation stT := (tvType 1).\n    Notation tvState := (tvType 2).\n    Notation tvTest := (tvType 3).\n    Notation tvReg := (tvType 4).\n\n    Variable fs : functions types.\n    Let funcs := repr (bedrock_funcs_r ts) fs.\n    Variable preds : SEP.predicates types pcT stT.\n\n    Variable Prover : ProverT types.\n    Variable PC : ProverT_correct Prover funcs.\n\n    Variable meval : MEVAL.MemEvaluator types pcT stT.\n    Variable meval_correct : MEVAL.MemEvaluator_correct meval funcs preds tvWord tvWord\n      (@IL_mem_satisfies ts) (@IL_ReadWord ts) (@IL_WriteWord ts) (@IL_ReadByte ts) (@IL_WriteByte ts).\n\n    Variable facts : Facts Prover.\n    Variable meta_env : env types.\n    Variable vars_env : env types.\n\n    Lemma stateD_interp : forall cs stn_st ss sh,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      SymMem ss = Some sh ->\n      interp cs (![ MEVAL.SEP.sexprD funcs preds meta_env vars_env (SH.sheapD sh)] stn_st).\n    Proof.\n      clear. destruct stn_st; destruct ss; destruct SymRegs; destruct p; simpl; intros.\n      rewrite H0 in *. intuition.\n    Qed.\n\n    Hint Resolve stateD_interp : sym_eval_hints.\n\n    Ltac t_correct :=\n      simpl; intros;\n        unfold IL_stn_st, IL_mem_satisfies, IL_ReadWord, IL_WriteWord in *;\n          repeat (simpl in *;\n            match goal with\n              | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n              | [ H : prod _ _ |- _ ] => destruct H\n              | [ H : match ?X with\n                        | Some _ => _\n                        | None => _\n                      end |- _ ] =>\n                revert H; case_eq X; intros; try contradiction\n              | [ H : match ?X with\n                        | Some _ => _\n                        | None => _\n                      end = _ |- _ ] =>\n                revert H; case_eq X; intros; try congruence\n              | [ H : _ = _ |- _ ] => rewrite H\n              | [ H : @existsEach _ _ _ |- _ ] => apply existsEach_sem in H\n              | [ H : exists x, _ |- _ ] => destruct H\n              | [ H : _ /\\ _ |- _ ] => destruct H\n              | [ |- exists x, Some _ = Some _ /\\ _ ] =>\n                eexists; split; [ reflexivity | ]\n            end); subst; eauto with sym_eval_hints.\n\n    Lemma sym_evalLoc_correct : forall loc ss res res' stn_st locD cs,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_locD fs meta_env vars_env loc = Some locD ->\n      evalLoc (snd stn_st) locD = res' ->\n      sym_evalLoc loc ss = res ->\n      exprD funcs meta_env vars_env res tvWord = Some res'.\n    Proof.\n      destruct loc; unfold stateD; destruct ss; destruct SymRegs; destruct p; intros; destruct stn_st; simpl in *;\n        t_correct; try solve [ eauto\n                             | destruct r; simpl in *;\n                               repeat match goal with\n                                        | [ H : _ = _ |- _ ] => rewrite H\n                                        | [ |- _ ] => subst funcs\n                                      end; eauto ].\n    Qed.\n\n    Hypothesis Valid_facts : Valid PC meta_env vars_env facts.\n\n    Lemma sym_evalRval_correct : forall rv ss res stn_st rvD cs,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_rvalueD funcs meta_env vars_env rv = Some rvD ->\n      sym_evalRval Prover meval facts rv ss = Some res ->\n      exists val,\n        evalRvalue (fst stn_st) (snd stn_st) rvD = Some val /\\\n        exprD funcs meta_env vars_env res tvWord = Some val.\n    Proof.\n      Opaque stateD sym_locD.\n      destruct rv; t_correct.\n      { destruct s; t_correct.\n        { erewrite <- (@sym_evalLoc_correct (SymReg _ r)). f_equal. eauto. simpl.\n          Transparent sym_locD. simpl. reflexivity. Opaque sym_locD. reflexivity. reflexivity. }\n        { eapply (MEVAL.ReadCorrect meval_correct) with (cs := cs) in H2; eauto with sym_eval_hints.\n          2: eapply sym_evalLoc_correct; (instantiate; eauto with sym_eval_hints). 2: eauto.\n          t_correct. }\n        { eapply (MEVAL.ReadByteCorrect meval_correct) with (cs := cs) in H2; eauto with sym_eval_hints.\n          2: eapply sym_evalLoc_correct; (instantiate; eauto with sym_eval_hints). 2: eauto.\n          t_correct. } }\n      { congruence. }\n    Qed.\n\n    Lemma sym_evalLval_correct : forall lv stn_st lvD cs val ss ss' valD,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_lvalueD funcs meta_env vars_env lv = Some lvD ->\n      sym_evalLval Prover meval facts lv val ss = Some ss' ->\n      exprD funcs meta_env vars_env val tvWord = Some valD ->\n      exists st',\n        evalLvalue (fst stn_st) (snd stn_st) lvD valD = Some st' /\\\n        stateD funcs preds meta_env vars_env cs (fst stn_st, st') ss'.\n    Proof.\n      destruct lv; t_correct.\n      { Transparent stateD. unfold stateD in *. t_correct. Opaque stateD.\n        case_eq (sym_setReg r val (SymRegs ss)); intros.\n        destruct ss; destruct SymRegs; destruct p. t_correct.\n        unfold sym_setReg in H0. destruct r; inversion H0; subst; t_correct; unfold rupd; simpl; intuition;\n        try solve [ repeat rewrite sepFormula_eq in *; unfold sepFormula_def in *; simpl in *; auto ].\n        destruct r; inversion H0; subst; t_correct; unfold rupd; simpl; intuition. }\n      { eapply (@sym_evalLoc_correct s) in H0; eauto.\n        simpl.\n        match goal with\n          | [ H : MEVAL.swrite_word _ _ _ _ _ _ = _ |- _ ] =>\n            eapply (MEVAL.WriteCorrect meval_correct) with (cs := cs) (stn_m := (s0,s1)) in H; eauto with sym_eval_hints\n        end.\n        simpl in *.\n        destruct (WriteWord s0 (Mem s1) (evalLoc s1 l) valD); try contradiction. t_correct.\n        Transparent stateD. destruct ss; destruct SymRegs; destruct p. simpl in *. Opaque stateD. intuition. subst.\n        generalize SH.sheapD_pures. unfold SEP.ST.satisfies. intro XXX.\n        rewrite sepFormula_eq in H3. unfold sepFormula_def in H3. simpl in *.\n        specialize (@XXX _ _ _ funcs preds meta_env vars_env cs _ _ _ H3).\n        apply AllProvable_app' in H6. apply AllProvable_app; intuition auto. }\n      { eapply (@sym_evalLoc_correct s) in H0; eauto.\n        simpl.\n        match goal with\n          | [ H : MEVAL.swrite_byte _ _ _ _ _ _ = _ |- _ ] =>\n            eapply (MEVAL.WriteByteCorrect meval_correct) with (cs := cs) (stn_m := (s0,s1)) in H; eauto with sym_eval_hints\n        end.\n        simpl in *.\n        destruct (WriteByte (Mem s1) (evalLoc s1 l) (WtoB valD)); try contradiction. t_correct.\n        Transparent stateD. destruct ss; destruct SymRegs; destruct p. simpl in *. Opaque stateD. intuition. subst.\n        generalize SH.sheapD_pures. unfold SEP.ST.satisfies. intro XXX.\n        rewrite sepFormula_eq in H3. unfold sepFormula_def in H3. simpl in *.\n        specialize (@XXX _ _ _ funcs preds meta_env vars_env cs _ _ _ H3).\n        apply AllProvable_app' in H6. apply AllProvable_app; intuition auto. }\n    Qed.\n\n\n    Ltac think := instantiate; simpl;\n      repeat match goal with\n               | [ H : _ = _ |- _ ] => rewrite H\n             end; eauto.\n\n    Lemma sym_evalInstr_correct' : forall instr stn_st instrD cs ss ss',\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_instrD funcs meta_env vars_env instr = Some instrD ->\n      sym_evalInstr Prover meval facts instr ss = Some ss' ->\n      exists st',\n        evalInstr (fst stn_st) (snd stn_st) instrD = Some st' /\\\n        stateD funcs preds meta_env vars_env cs (fst stn_st, st') ss'.\n    Proof.\n      destruct instr; t_correct; simpl;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ b : binop |- _ ] =>\n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n               end; t_correct.\n    Qed.\n\n    Lemma sym_assertTest_correct' : forall cs r rD t l lD ss stn_st,\n      stateD funcs preds meta_env vars_env cs stn_st ss ->\n      sym_rvalueD funcs meta_env vars_env r = Some rD ->\n      sym_rvalueD funcs meta_env vars_env l = Some lD ->\n      match Structured.evalCond rD t lD (fst stn_st) (snd stn_st) with\n        | None =>\n          forall res,\n            match sym_assertTest Prover meval facts r t l ss res with\n              | Some _ => False\n              | None => True\n            end\n        | Some res' =>\n          match sym_assertTest Prover meval facts r t l ss res' with\n            | Some b =>\n              Provable funcs meta_env vars_env b\n            | None => True\n          end\n      end.\n    Proof.\n      unfold sym_assertTest, Structured.evalCond; destruct stn_st; simpl in *;\n        repeat match goal with\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ |- context [ evalRvalue ?A ?B ?C ] ] =>\n                   case_eq (evalRvalue A B C); intros\n                 | [ |- context [ evalTest ?A ?B ?C ] ] =>\n                   case_eq (evalTest A B C); intros\n                 | [ b : binop |- _ ] =>\n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n               end; t_correct; simpl in *;\n      try destruct res;\n       repeat match goal with\n        | [ |- context [ sym_evalRval ?A ?B ?C ?D ?E ] ] =>\n          case_eq (sym_evalRval A B C D E); intros\n               end; auto;\n        unfold Provable; destruct t;\n        repeat match goal with\n                 | [ |- match match ?X with\n                                | Some _ => match ?Y with _ => _ end\n                                | _ => _\n                              end with _ => _ end ] =>\n                   (case_eq X; trivial; case_eq Y; trivial); []\n\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ H : sym_rvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalRval_correct in H; think); [ simpl in * ]\n                 | [ H : sym_lvalueD _ _ _ _ = _ |- _ ] =>\n                   (eapply sym_evalLval_correct in H; think); [ simpl in * ]\n                 | [ H : _ = _ |- _ ] => rewrite H\n                 | [ |- _ ] => progress (simpl in * )\n                 | [ |- context [ evalRvalue ?A ?B ?C ] ] =>\n                   case_eq (evalRvalue A B C); intros\n                 | [ |- context [ evalTest ?A ?B ?C ] ] =>\n                   Reflection.consider (evalTest A B C); intros\n                 | [ b : binop |- _ ] =>\n                   destruct b; unfold fPlus, fMinus, fMult in *; simpl in *\n                 | [ |- _ ] => progress t_correct\n               end; unfold IL.weqb, IL.wneb, wltb, wleb in *; simpl in *;\n        repeat match goal with\n                 | [ H : (if ?X then _ else _) = _ |- _ ] =>\n                   revert H; Reflection.consider X; try congruence\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n                 | [ H : ?X = _ , H' : ?X = _ |- _ ] => rewrite H in H'\n                 | [ |- context [ wlt_dec ?X ?Y ] ] =>\n                   destruct (wlt_dec X Y); try congruence\n               end; try congruence; eauto 10 using eq_le, lt_le, le_neq_lt.\n      eapply weqb_true_iff; auto.\n      intro. apply weqb_true_iff in H1. congruence.\n    Qed.\n\n  End typed.\n\n\n  Section typed2.\n    Variable ts : list type.\n    Let types := repr bedrock_types_r ts.\n\n    Notation pcT := (tvType 0).\n    Notation tvWord := (tvType 0).\n    Notation stT := (tvType 1).\n    Notation tvState := (tvType 2).\n    Notation tvTest := (tvType 3).\n    Notation tvReg := (tvType 4).\n\n    Variable fs : functions types.\n    Let funcs := repr (bedrock_funcs_r ts) fs.\n    Variable preds : SEP.predicates types pcT stT.\n\n    Variable Prover : ProverT types.\n    Variable PC : ProverT_correct Prover funcs.\n\n    Variable meval : MEVAL.MemEvaluator types pcT stT.\n    Variable meval_correct : MEVAL.MemEvaluator_correct meval funcs preds tvWord tvWord\n      (@IL_mem_satisfies ts) (@IL_ReadWord ts) (@IL_WriteWord ts) (@IL_ReadByte ts) (@IL_WriteByte ts).\n\n    Ltac t_correct :=\n      simpl; intros;\n        unfold IL_stn_st, IL_mem_satisfies, IL_ReadWord, IL_WriteWord in *;\n          repeat (simpl in *;\n            match goal with\n              | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n              | [ H : prod _ _ |- _ ] => destruct H\n              | [ H : match ?X with\n                        | Some _ => _\n                        | None => _\n                      end |- _ ] =>\n              revert H; case_eq X; intros; try contradiction\n              | [ H : match ?X with\n                        | Some _ => _\n                        | None => _\n                      end = _ |- _ ] =>\n              revert H; case_eq X; intros; try congruence\n              | [ H : _ = _ |- _ ] => rewrite H\n              | [ H : reg |- _ ] => destruct H\n            end; intuition); subst.\n\n    Lemma sym_evalInstrs_correct : forall (facts : Facts Prover) (meta_env var_env : env types),\n      Valid PC meta_env var_env facts  ->\n      forall is stn_st isD cs ss,\n        stateD funcs preds meta_env var_env cs stn_st ss ->\n        sym_instrsD funcs meta_env var_env is = Some isD ->\n        match evalInstrs (fst stn_st) (snd stn_st) isD with\n          | Some st' =>\n            match sym_evalInstrs Prover meval facts is ss with\n              | inl ss' => stateD funcs preds meta_env var_env cs (fst stn_st, st') ss'\n              | inr (ss', is') =>\n                match sym_instrsD funcs meta_env var_env is' with\n                  | None => False\n                  | Some is'D =>\n                    exists st'', stateD funcs preds meta_env var_env cs (fst stn_st, st'') ss' /\\\n                      evalInstrs (fst stn_st) st'' is'D = Some st'\n                end\n            end\n          | None =>\n            match sym_evalInstrs Prover meval facts is ss with\n              | inl ss' => False\n              | inr (ss', is') =>\n                match sym_instrsD funcs meta_env var_env is' with\n                  | None => False\n                  | Some is'D =>\n                    exists st'', stateD funcs preds meta_env var_env cs (fst stn_st, st'') ss' /\\\n                      evalInstrs (fst stn_st) st'' is'D = None\n                end\n            end\n        end.\n    Proof.\n      Opaque stateD.\n      induction is; simpl; intros;\n        repeat match goal with\n                 | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               end; simpl; destruct stn_st; simpl in *; eauto.\n      t_correct. simpl in *.\n      case_eq (evalInstr s s0 i); intros.\n      case_eq (sym_evalInstr Prover meval facts a ss); intros.\n\n      destruct (@sym_evalInstr_correct' ts fs preds Prover PC meval meval_correct facts meta_env var_env\n        H a (s,s0) i cs ss s2 H0 H1 H4). simpl in *. intuition.\n      rewrite H6 in H3. inversion H3; clear H3; subst.\n      specialize (IHis (s, s1)). simpl in *. eapply IHis; eauto.\n\n      simpl. rewrite H1. rewrite H2. simpl.\n      case_eq (evalInstrs s s1 l); intros; exists s0; simpl; rewrite H3; eauto.\n\n      case_eq (sym_evalInstr Prover meval facts a ss); intros.\n      Focus 2. simpl. rewrite H1. rewrite H2. exists s0; simpl; rewrite H3; intuition.\n\n\n\n      edestruct (@sym_evalInstr_correct' ts fs preds Prover PC meval meval_correct facts meta_env var_env\n        H a (s,s0) i cs ss); eauto.\n      simpl in *. destruct H5. rewrite H3 in H5. congruence.\n      Transparent stateD.\n    Qed.\n\n    Variable learnHook : MEVAL.LearnHook types (SymState types pcT stT).\n    Variable learn_correct : @MEVAL.LearnHook_correct _ _ pcT stT learnHook (@stateD _ funcs preds) funcs preds.\n\n    Ltac shatter_state ss :=\n      destruct ss as [ ? [ [ ? ? ] ? ] ].\n\n    Lemma skip_to_nil : forall T U (F : T -> U) vars env X,\n      map F env = skipn (length vars) X ->\n      map F nil = skipn (length (vars ++ env)) X.\n    Proof.\n      clear. induction vars; simpl; intros; subst.\n      induction env; eauto.\n      destruct X; auto.\n    Qed.\n    Lemma AllProvable_cons : forall U G P Ps,\n      Provable funcs U G P ->\n      AllProvable funcs U G Ps ->\n      AllProvable funcs U G (P :: Ps).\n    Proof. simpl; intuition. Qed.\n    Lemma AllProvable_nil : forall U G,\n      AllProvable funcs U G nil.\n    Proof. simpl; intuition. Qed.\n    Hint Resolve AllProvable_cons AllProvable_nil : env_resolution.\n    Hint Resolve Learn_correct : env_resolution.\n    Hint Resolve skip_to_nil : env_resolution.\n\n    Lemma skip_prove_nil : forall T U (F : T -> U) vars env X Y,\n      map F env = skipn (length vars) X ->\n      map F Y = skipn (length (vars ++ env)) X ->\n      Y = nil.\n    Proof.\n      clear. intros. destruct Y; auto.\n      eapply skip_to_nil in H. rewrite <- H in H0. simpl in *; congruence.\n    Qed.\n    Hint Resolve skip_prove_nil : env_resolution.\n    Lemma stateD_addToPures : forall U G cs ss stn_st P,\n      stateD funcs preds U G cs stn_st ss ->\n      Provable funcs U G P ->\n      stateD funcs preds U G cs stn_st\n      {| SymMem := SymMem ss\n        ; SymRegs := SymRegs ss\n        ; SymPures := P :: SymPures ss |}.\n    Proof.\n      Transparent stateD.\n      clear. intros; shatter_state ss; destruct stn_st; simpl in *. intuition.\n      destruct SymMem; intuition.\n      Opaque stateD.\n    Qed.\n    Hint Resolve stateD_addToPures : stateD_solver.\n\n    Ltac qstateD_solver :=\n      eapply existsEach_sem; intros; eexists; split; [ solve [ eauto with env_resolution ] | ];\n      let e := fresh in\n      eapply forallEach_sem; intro e; intro;\n      eauto with stateD_solver.\n\n    Opaque repr stateD.\n    Ltac split_congruence :=\n      repeat match goal with\n               | [ H : prod _ _ |- _ ] => destruct H\n             end; congruence.\n\n    Lemma stateD_weaken_vars : forall uvars vars cs stn_st ss' env,\n      stateD funcs preds uvars vars cs stn_st ss' ->\n      stateD funcs preds uvars (vars ++ env) cs stn_st ss'.\n    Proof.\n      Transparent stateD.\n      clear. intros. destruct stn_st; shatter_state ss'; simpl in *.\n      repeat match goal with\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : context [ match exprD ?A ?B ?C ?D ?E with _ => _ end ] |- _ ] =>\n                 revert H; case_eq (exprD A B C D E); intros; try contradiction\n             end; subst.\n      rewrite <- app_nil_r with (l := uvars). repeat erewrite exprD_weaken by eassumption.\n      intuition. destruct SymMem; auto. erewrite SH.SE_FACTS.sexprD_weaken in H0. eassumption.\n      eapply AllProvable_weaken; eauto.\n    Qed.\n    Lemma stateD_weaken_uvars : forall uvars vars cs stn_st ss' env,\n      stateD funcs preds uvars vars cs stn_st ss' ->\n      stateD funcs preds (uvars ++ env) vars cs stn_st ss'.\n    Proof.\n      Transparent stateD.\n      clear. intros. destruct stn_st; shatter_state ss'; simpl in *.\n      repeat match goal with\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : context [ match exprD ?A ?B ?C ?D ?E with _ => _ end ] |- _ ] =>\n                 revert H; case_eq (exprD A B C D E); intros; try contradiction\n             end; subst.\n      rewrite <- app_nil_r with (l := vars). repeat erewrite exprD_weaken by eassumption.\n      intuition. destruct SymMem; auto. erewrite SH.SE_FACTS.sexprD_weaken in H0. eassumption.\n      eapply AllProvable_weaken; eauto.\n    Qed.\n    Hint Resolve stateD_weaken_vars stateD_weaken_uvars : stateD_solver.\n    Require Bedrock.ListFacts.\n    Require Import Bedrock.Tactics Bedrock.Reflection.\n    Hint Resolve ListFacts.not_sure ListFacts.map_skipn_all_map_is_nil ListFacts.map_skipn_all_map : env_resolution.\n\n    Lemma sym_locD_weaken : forall ts X A C Y Z,\n      sym_locD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_locD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto;\n      erewrite exprD_weaken; eauto.\n    Qed.\n\n    Lemma sym_lvalueD_weaken : forall ts X A C Y Z,\n      sym_lvalueD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_lvalueD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto.\n      erewrite sym_locD_weaken; eauto.\n      erewrite sym_locD_weaken; eauto.\n    Qed.\n    Lemma sym_rvalueD_weaken : forall ts X A C Y Z,\n      sym_rvalueD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n        sym_rvalueD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. destruct Y; simpl; intros; think; auto.\n      erewrite sym_lvalueD_weaken; eauto.\n      erewrite exprD_weaken; eauto.\n    Qed.\n\n    Lemma sym_instrD_weaken : forall ts X A C Y Z,\n      sym_instrD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n      sym_instrD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear; destruct Y; simpl; intros; think; auto;\n        repeat ((erewrite sym_lvalueD_weaken by eauto) ||\n                (erewrite sym_rvalueD_weaken by eauto)); auto.\n    Qed.\n\n    Lemma sym_instrsD_weaken : forall ts X A C Y Z,\n      sym_instrsD (types' := ts) X A C Y = Some Z ->\n      forall B D,\n      sym_instrsD X (A ++ B) (C ++ D) Y = Some Z.\n    Proof.\n      clear. induction Y; simpl; intros; think; auto.\n      erewrite sym_instrD_weaken; eauto.\n    Qed.\n\n    Lemma istreamD_weaken : forall ts X A C Y Z P L,\n      istreamD (types' := ts) X A C Y Z P L ->\n      forall B D,\n      istreamD X (A ++ B) (C ++ D) Y Z P L.\n    Proof.\n      clear. induction Y; simpl; intros; think; auto.\n      repeat match goal with\n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 consider X; intros\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ |- _ ] =>\n                 (erewrite sym_instrsD_weaken by eauto) ||\n                 (erewrite sym_rvalueD_weaken by eauto) ||\n                 (erewrite sym_lvalueD_weaken by eauto)\n             end; intuition.\n    Qed.\n\n    Lemma env_nil_by_length_eq : forall ts L X Y,\n      typeof_env (types := ts) L = X ->\n      length Y = length X ->\n      typeof_env (types := ts) nil = skipn (length L) Y.\n    Proof.\n      clear. intros. subst.\n      erewrite ListFacts.skipn_length_gt; auto. unfold typeof_env in *. rewrite map_length in H0. omega.\n    Qed.\n    Hint Resolve env_nil_by_length_eq : env_resolution.\n\n    Lemma all2_tvar_seq_dec_true : forall a b,\n      Folds.all2 Expr.tvar_seqb a b = true -> a = b.\n    Proof.\n      clear; induction a; destruct b; simpl; intros; try congruence.\n      consider (tvar_seqb a t). intros. erewrite IHa; auto.\n    Qed.\n\n    Lemma sym_evalStream_quant_append : forall path facts qs uvars vars ss res,\n      sym_evalStream Prover meval learnHook facts path qs uvars vars ss = res ->\n      match res with\n        | Safe qs' _\n        | SafeUntil qs' _ _ => exists qs'', qs' = appendQ qs'' qs\n(*        | Unsafe qs'  *)\n      end.\n    Proof.\n      clear.\n      induction path; simpl; intros.\n      { inversion H. subst. exists QBase.\n        clear. simpl; auto. }\n      { destruct a. destruct p. consider (sym_evalInstrs Prover meval facts l ss); intros; try congruence.\n        eapply IHpath; eauto. destruct p. subst. exists QBase. auto.\n        destruct s. destruct o. consider (sym_assertTest Prover meval facts s t s0 ss b); intros.\n        repeat match goal with\n                 | [ H : match ?X with (_,_) => _ end = _ |- _ ] => destruct X; try congruence\n               end.\n        eapply IHpath in H0. destruct res; auto; destruct H0; rewrite <- appendQ_assoc in H0; eauto.\n        subst; auto. exists QBase; auto.\n        repeat match goal with\n                 | [ H : match ?X with _ => _ end = _ |- _ ] => destruct X; try congruence\n               end; subst;\n        try eapply IHpath; eauto.\n        exists QBase; auto.\n        exists QBase; auto. }\n    Qed.\n\n    Hint Extern 1 (@eq (list tvar) _ _) =>\n      simpl; repeat (rewrite app_nil_r in * || rewrite typeof_env_app in * || rewrite app_ass ||\n        (f_equal; []) || (f_equal; [ solve [ reflexivity | assumption ] | ] || reflexivity || assumption)) : env_resolution.\n\n    Definition NO_MORE_COND : Prop := True.\n\n    Ltac sym_eval_prover IHpath :=\n      repeat match goal with\n               | [ H : Valid _ (?A ++ ?b) (?C ++ ?d) _\n                 , H' : sym_instrsD ?X ?A ?C ?Y = ?Z |- _ ] =>\n                 apply sym_instrsD_weaken with (B := b) (D := d) in H'\n               | [ H : Valid _ (?A ++ ?b) (?C ++ ?d) _\n                 , H' : istreamD ?X ?A ?C ?Y ?Z ?P ?L |- _ ] =>\n                 apply istreamD_weaken with (B := b) (D := d) in H'\n               | [ H : (_,_) = (_,_) |- _ ] => inversion H; clear H; subst\n               | [ H : Some _ = Some _ |- _ ] => inversion H; clear H; subst\n               | [ H : Safe _ _ = Safe _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : SafeUntil _ _ _ = SafeUntil _ _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : inl _ = inl _ |- _ ] => inversion H; clear H; subst\n               | [ H : inr _ = inr _ |- _ ] => inversion H; clear H; subst\n               | [ H : SymAssertCond _ _ _ _ = SymAssertCond _ _ _ _ |- _ ] => inversion H; clear H; subst\n               | [ H : sum (prod _ _) _ |- _ ] => destruct H as [ [ ? ? ] | ? ]\n               | [ H : ?X = _ , H' : ?X = _ |- _ ] => rewrite H in H'\n               | [ H : option state |- _ ] => destruct H\n               | [ H : _ /\\ _ |- _ ] => destruct H\n               | [ H : ?X = _ , H' : context [ match ?X with _ => _ end ] |- _ ] =>\n                 rewrite H in H'\n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 (revert H; case_eq X; intros; try contradiction); []\n               | [ |- _ ] => progress (repeat rewrite app_nil_r in * )\n               | [ |- _ ] => solve [ congruence | eauto with stateD_solver ]\n               | [ H : ?X -> _ , H' : ?X |- _ ] =>\n                 match type of X with\n                   | Prop =>\n                     specialize (H H')\n                 end\n               | [ H   : sym_evalInstrs _ _ ?F ?is ?S = _\n                 , H'  : evalInstrs ?stn ?st _ = _\n                 , H'' : sym_instrsD _ ?U ?G _ = Some ?isD\n                 , Hst : stateD _ _ _ _ _ _ _\n                 |- _ ] =>\n               ( eapply sym_evalInstrs_correct with (stn_st := (stn,st)) (facts := F) (ss := S) in H'' ; eauto ;\n                 simpl in H'' ) ; [ clear Hst ]\n               | [ H : Structured.evalCond ?l ?A ?r ?B ?C = _\n                 , Hst : stateD _ _ ?U ?G ?cs _ _\n                 , H' : sym_rvalueD _ _ _ _ = Some ?l\n                 , H'' : sym_rvalueD _ _ _ _ = Some ?r |- _ ] =>\n               match goal with\n                 | [ H : NO_MORE_COND |- _ ] => fail 1\n                 | _ =>\n                   (generalize Hst; eapply sym_assertTest_correct' with (meta_env := U) (vars_env := G) (t := A) (rD := l) (lD := r) (stn_st := (B,C)) in Hst; eauto using sym_rvalueD_weaken) ; [ intro; simpl in Hst ; assert NO_MORE_COND by (exact I) ]\n               end\n               | [ H : learnHook _ ?U' ?G' ?SS ?f ?F = (?A, ?B)\n                 , H' : stateD _ _ ?U ?G _ _ _\n                 , LC : MEVAL.LearnHook_correct _ _ _ _\n                 , PC : ProverT_correct _ _ |- _ ] =>\n                 (cutrewrite (U' = typeof_env U) in H; [ | rewrite typeof_env_app; f_equal; auto ] ;\n                  cutrewrite (G' = typeof_env G) in H; [ | rewrite typeof_env_app; f_equal; auto ] ;\n                  eapply (@MEVAL.hook_sound _ _ _ _ _ _ _ _ LC _ PC U G) with\n                    (new_facts := F) (ss := SS) (ss' := A) (quant := B) in H ;\n                  eauto using Learn_correct, AllProvable_cons, AllProvable_nil with stateD_solver) ; [ clear H' ]\n               | [ H : quantD _ _ _ _ |- quantD _ _ _ _ ] =>\n                 eapply quantD_impl; [ eapply H | clear H ; simpl; intros ]\n               | [ |- quantD _ _ (appendQ _ ?X) _ ] =>\n                 apply quantD_app\n               | [ H : appendQ _ _ = appendQ _ _ |- _ ] => apply appendQ_proper in H; subst\n\n               | [ H : appendQ ?A ?B = appendQ _ (appendQ _ ?B) |- _ ] =>\n                 rewrite <- appendQ_assoc in H; apply appendQ_proper in H; subst\n               | [ H : context [ Safe (appendQ (appendQ ?A ?B) ?C) _ ] |- _ ] =>\n                 rewrite appendQ_assoc with (a := A) (b := B) (c := C) in H\n               | [ H : context [ SafeUntil (appendQ (appendQ ?A ?B) ?C) _ _ ] |- _ ] =>\n                 rewrite appendQ_assoc with (a := A) (b := B) (c := C) in H\n\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ ?X) _ _ _ = Safe (appendQ ?Y ?X) _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ (appendQ _ ?X)) _ _ _ = Safe (appendQ ?Y ?X) _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => rewrite <- appendQ_assoc in H; destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ ?X) _ _ _ = SafeUntil (appendQ ?Y ?X) _ _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : sym_evalStream _ _ _ _ _ (appendQ _ (appendQ _ ?X)) _ _ _ = SafeUntil (appendQ ?Y ?X) _ _ |- _ ] =>\n                 match Y with\n                   | appendQ _ _ => fail 1\n                   | _ => rewrite <- appendQ_assoc in H; destruct (sym_evalStream_quant_append _ _ _ _ _ _ H); subst\n                 end\n               | [ H : EqNat.beq_nat ?X ?Y = true |- _ ] =>\n                 symmetry in H; apply EqNat.beq_nat_eq in H\n               | [ H : Folds.all2 _ _ _ = true |- _ ] =>\n                 eapply all2_tvar_seq_dec_true in H\n               | [ H : sym_evalStream _ _ _ _ _ ?QS _ _ _ = _\n                 , H' : stateD _ _ ?Uall ?Gall _ (_, ?st) _\n                 , H'' : istreamD _ _ _ _ _ ?st _\n                 |- _ ] =>\n               let t := change (QS) with (appendQ QBase QS) in H at 1 ;\n                 eapply IHpath with (env_q := QS) (qs := QBase) (meta_env := Uall) (vars_env := Gall) in H;\n                   simpl; subst; intuition (eauto using istreamD_weaken, Valid_weaken with env_resolution) in\n               solve [ t ] || (t; [])\n               | [ H : forall res : bool, match sym_assertTest _ _ _ _ _ _ _ res with _ => _ end |- _ ] =>\n                 specialize (H true); unfold sym_assertTest in H\n               | [ H : match ?X with | IL.Eq => _ | _ => _ end = None |- _ ] =>\n                 destruct X; congruence\n               | [ H : exists x : state, _ |- exists y : state, _ ] =>\n                 let s := fresh \"st\" in\n                 solve [ destruct H as [ s ? ] ; exists s ; intuition ]\n               | [ H : match ?X with _ => _ end |- _ ] =>\n                 (revert H; case_eq X; intros; try contradiction)\n               | [ H : match ?X with _ => _ end = _ |- _ ] =>\n                 (revert H; case_eq X; intros; try split_congruence)\n               | [ H : sym_rvalueD _ _ _ _ = _ |- context [ sym_rvalueD _ _ _ _ ] ] =>\n                   erewrite sym_rvalueD_weaken by eauto\n               | [ H : option bool |- _ ] => destruct H\n             end.\n\n    Lemma evalStream_correct_Safe : forall sound_or_safe cs stn path facts ss qs qs' ss' uvars vars env_q,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = Safe (appendQ qs' env_q) ss' ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        quantD vars_env meta_env qs' (fun vars_env meta_env =>\n          match sound_or_safe with\n            | None => False\n            | Some (st') =>\n              stateD funcs preds meta_env vars_env cs (stn, st') ss'\n          end).\n    Proof.\n      Opaque stateD.\n      induction path; simpl; intros; sym_eval_prover IHpath; try contradiction.\n    Qed.\n\n    Lemma evalStream_correct_SafeUntil : forall sound_or_safe cs stn path facts ss qs qs' ss' is' uvars vars env_q,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = SafeUntil (appendQ qs' env_q) ss' is' ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        quantD vars_env meta_env qs' (fun vars_env meta_env =>\n          exists st' : state,\n          stateD funcs preds meta_env vars_env cs (stn, st') ss' /\\\n          istreamD funcs meta_env vars_env is' stn st' sound_or_safe).\n    Proof.\n      induction path; simpl; intros; sym_eval_prover IHpath; try contradiction.\n    Qed.\n\n    Lemma appendQ_QBase_r : forall a, appendQ a QBase = a.\n    Proof. clear. induction a; simpl; intros; think; auto. Qed.\n(*\n    Theorem evalStream_correct : forall sound_or_safe cs stn path facts ss qs env_q uvars vars res,\n      sym_evalStream Prover meval learnHook facts path (appendQ qs env_q) uvars vars ss = res ->\n      forall meta_env vars_env,\n        typeof_env meta_env ++ gatherAll qs = uvars ->\n        typeof_env vars_env ++ gatherEx qs = vars ->\n        forall st,\n          istreamD funcs meta_env vars_env path stn st sound_or_safe ->\n        quantD vars_env meta_env qs (fun vars_env meta_env =>\n          stateD funcs preds meta_env vars_env cs (stn,st) ss /\\\n          Valid PC meta_env vars_env facts) ->\n        match res with\n          | Safe qs' ss' =>\n            quantD vars_env meta_env qs' (fun vars_env meta_env =>\n              match sound_or_safe with\n                | None => False\n                | Some (st') => stateD funcs preds meta_env vars_env cs (stn, st') ss'\n              end)\n          | SafeUntil qs' ss' is' =>\n            quantD vars_env meta_env qs' (fun vars_env meta_env =>\n              exists st' : state,\n                stateD funcs preds meta_env vars_env cs (stn, st') ss' /\\\n                istreamD funcs meta_env vars_env is' stn st' sound_or_safe)\n        end.\n    Proof.\n      destruct res; intros.\n      { destruct (sym_evalStream_quant_append _ _ _ _ _ _ H).\n        generalize (@evalStream_correct_Safe sound_or_safe cs stn path facts ss qs (appendQ x qs) s uvars vars env_q). subst.\n        rewrite appendQ_assoc.\n        intro. eapply H0 in H; eauto. }\n      { destruct (sym_evalStream_quant_append _ _ _ _ _ _ H).\n        generalize (@evalStream_correct_SafeUntil sound_or_safe cs stn path facts ss qs (appendQ x qs) s i uvars vars QBase);\n          subst.\n        repeat rewrite appendQ_QBase_r. intro. eapply H0 in H; eauto. }\n    Qed.\n*)\n  End typed2.\n\nEnd SymIL_Correct.\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/SymILProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.16085855355010115}}
{"text": "Time Require Import Coq.Init.Prelude.\n\nTime Goal True. Time (do 2000 (pose proof I); exact I). Time Qed.\n", "meta": {"author": "andres-erbsen", "repo": "coq-experiments", "sha": "2018edd397a23c0429d316c96e86f9be7a9678f1", "save_path": "github-repos/coq/andres-erbsen-coq-experiments", "path": "github-repos/coq/andres-erbsen-coq-experiments/coq-experiments-2018edd397a23c0429d316c96e86f9be7a9678f1/experiments/bench/time_qed_underreport.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.29421496597446134, "lm_q1q2_score": 0.16085854678309305}}
{"text": "Require Import Bool List String Peano_dec Lia.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Msi Ex.MsiInc.Msi.\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 Msi.ImplOStateIfc.\n\nSection ObjInv.\n  Variable topo: DTree.\n\n  Definition MsiUpLockObjInv (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      (rqiu <+- orq@[upRq];\n      rmsg <+- rqiu.(rqi_msg);\n      match case rmsg.(msg_id) on idx_dec default True with\n      | msiRqS:\n          ost#[owned] = false /\\ ost#[status] <= msiI /\\\n          ost#[dir].(dir_st) <= msiS\n      | msiRqM:\n          ost#[owned] = false /\\ ost#[status] <= msiS /\\\n          ost#[dir].(dir_st) <= msiS\n      end).\n\n  Definition DownLockFromChild (oidx: IdxT) (rqid: RqInfo Msg) :=\n    exists cidx,\n      rqid.(rqi_midx_rsb) = Some (downTo cidx) /\\\n      parentIdxOf topo cidx = Some oidx.\n\n  Definition DownLockFromParent (oidx: IdxT) (rqid: RqInfo Msg) :=\n    rqid.(rqi_midx_rsb) = Some (rsUpFrom oidx).\n\n  Definition MsiDownLockObjInv (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      (rqid <+- orq@[downRq];\n      match rqid.(rqi_msg) with\n      | None =>\n        (* NOTE: it is a bit too hacky, but back invalidation is the only case\n         * that [rqi_msg = None] holds. *)\n        ((ost#[dir].(dir_st) = msiS /\\\n          SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n          map fst rqid.(rqi_rss) = map rsUpFrom (ost#[dir].(dir_sharers))) \\/\n         (ost#[dir].(dir_st) = msiM /\\\n          In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n          map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n      | Some rmsg =>\n        (match case rmsg.(msg_id) on idx_dec default True with\n         | msiRqS: DownLockFromChild oidx rqid /\\\n                   ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM /\\\n                   In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                   map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n         | msiRqM: DownLockFromChild oidx rqid /\\\n                   ost#[status] <= msiS /\\\n                   ((ost#[owned] = true /\\ ost#[dir].(dir_st) = msiS /\\\n                     SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                     (rsb <+- rqid.(rqi_midx_rsb);\n                     map fst rqid.(rqi_rss) =\n                     map rsUpFrom (remove idx_dec (objIdxOf rsb) ost#[dir].(dir_sharers)))) \\/\n                    (ost#[dir].(dir_st) = msiM /\\\n                     In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                     map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n         | msiDownRqS: DownLockFromParent oidx rqid /\\\n                       ost#[status] <= msiI /\\ ost#[dir].(dir_st) = msiM /\\\n                       In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                       map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n         | msiDownRqIS: DownLockFromParent oidx rqid /\\\n                        ost#[dir].(dir_st) = msiS /\\\n                        SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                        map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)\n         | msiDownRqIM: DownLockFromParent oidx rqid /\\\n                        ((ost#[dir].(dir_st) = msiS /\\\n                          SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                          map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)) \\/\n                         (ost#[dir].(dir_st) = msiM /\\\n                          In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                          map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n         end)\n      end).\n\n  Definition MsiObjInvs (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      MsiUpLockObjInv oidx ost orq /\\\n      MsiDownLockObjInv oidx ost orq.\n\nEnd ObjInv.\n\nLtac disc_msi_obj_invs :=\n  repeat\n    match goal with\n    | [H: MsiObjInvs _ _ _ _ |- _] => destruct H\n    | [H: MsiUpLockObjInv _ _ _ |- _] =>\n      red in H; mred; simpl in H; disc_rule_conds_const\n    | [H: MsiDownLockObjInv _ _ _ _ |- _] =>\n      red in H; mred; simpl in H; disc_rule_conds_const\n    | [Hmsg: msg_id ?rmsg = _, H: context [msg_id ?rmsg] |- _] =>\n      rewrite Hmsg in H; simpl in H\n    end.\n", "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/MsiInc/MsiObjInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.1608585390537524}}
{"text": "Require Import Eqdep Lia Framework FSParameters FileDiskLayer. (* LoggedDiskLayer TransactionCacheLayer TransactionalDiskLayer. *)\nRequire Import FileDiskNoninterference FileDiskRefinement.\nRequire Import ATCLayer FileDisk.TransferProofs ATC_Simulation ATC_AOE.\nRequire Import Not_Init HSS ATC_ORS ATC_TS_Common.\n\nImport FileDiskLayer.\nSet Nested Proofs Allowed.\n\nLemma ATC_TS_TransactionCache_get:\n  forall n u V R,\n  Termination_Sensitive u\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ (@P1 (ListOperation (addr * value)) _ _ (Get (prod addr value)))))\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ (@P1 (ListOperation (addr * value)) _ _ (Get (prod addr value)))))\n(Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |)))\n  V R\n(ATC_reboot_list n).\nProof.\n  unfold Termination_Sensitive, ATC_reboot_list; \n  intros; destruct n;\n  repeat invert_exec.\n  invert_exec'' H9; repeat invert_exec.\n  eexists (RFinished _ _); repeat econstructor.\n\n  invert_exec'' H12;\n  repeat invert_exec; simpl in *.\n  edestruct ATC_TS_recovery; eauto.\n  all: unfold AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  shelve.\n  eexists (Recovered _); repeat econstructor; eauto.\n  Unshelve.\n  all: try solve [exact (fun _ _ => True)].\n  all: simpl; eauto.\nQed.\n\n\nLemma ATC_TS_LoggedDisk_read:\n  forall n u V R a1 a2,\n  (a1 < data_length <-> a2 < data_length) -> \n  Termination_Sensitive u\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ \n     (@P2 _ (LoggedDiskOperation log_length data_length) _ (LoggedDiskLayer.Read a1))))\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ \n     (@P2 _ (LoggedDiskOperation log_length data_length) _ (LoggedDiskLayer.Read a2))))\n(Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |)))\n  V R\n(ATC_reboot_list n).\nProof.\n  unfold Termination_Sensitive, ATC_reboot_list; \n  intros; destruct n;\n  repeat invert_exec.\n  invert_exec'' H10; repeat invert_exec.\n  eexists (RFinished _ _); repeat econstructor.\n  lia.\n\n  eexists (RFinished _ _); \n  try solve [repeat econstructor; lia].\n\n  invert_exec'' H13;\n  repeat invert_exec; simpl in *.\n  edestruct ATC_TS_recovery; eauto.\n  all: unfold AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  shelve.\n  eexists (Recovered _); repeat econstructor; eauto.\n  Unshelve.\n  all: try solve [exact (fun _ _ => True)].\n  all: simpl; eauto.\nQed.\n\nLemma ATC_TS_LoggedDisk_write:\n  forall n u V R l_a1 l_a2 l_v1 l_v2,\n  (NoDup l_a1 <-> NoDup l_a2) ->\n  (length l_a1 = length l_v1 <-> length l_a2 = length l_v2) ->\n   (Forall (fun a : nat => a < data_length) l_a1 <-> Forall (fun a : nat => a < data_length) l_a2) ->\n   (length (addr_list_to_blocks l_a1) + length l_v1 <= log_length <-> length (addr_list_to_blocks l_a2) + length l_v2 <= log_length ) ->\n  Termination_Sensitive u\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ \n     (@P2 _ (LoggedDiskOperation log_length data_length) _ \n     (LoggedDiskLayer.Write l_a1 l_v1))))\n  (Op\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (@P2 _ TransactionCacheOperation _ \n     (@P2 _ (LoggedDiskOperation log_length data_length) _ \n     (LoggedDiskLayer.Write l_a2 l_v2))))\n(Simulation.Definitions.compile\n   ATC_Refinement\n   (Simulation.Definitions.compile\n      FD.refinement\n      (| Recover |)))\n  V R\n(ATC_reboot_list n).\nProof.\n  unfold Termination_Sensitive, ATC_reboot_list; \n  intros; destruct n;\n  repeat invert_exec.\n  {\n   invert_exec'' H13; repeat invert_exec.\n   eexists (RFinished _ _); repeat econstructor;\n   intuition eauto.\n\n   eexists (RFinished _ _); \n   do 4 econstructor.\n   eapply LoggedDiskLayer.ExecWriteFail.\n   intuition eauto.\n   lia.\n  }\n  {\n     invert_exec'' H16;\n  repeat invert_exec; simpl in *.\n  edestruct ATC_TS_recovery; eauto.\n  all: unfold AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  shelve.\n  eexists (Recovered _); repeat econstructor; eauto.\n  repeat invert_exec; simpl in *.\n  edestruct ATC_TS_recovery; eauto.\n  all: unfold AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  shelve.\n  eexists (Recovered _); repeat econstructor; eauto.\n  all: intuition eauto.\n  }\n  Unshelve.\n  all: try solve [exact (fun _ _ => True)].\n  all: simpl; eauto.\nQed.\n\n\nLemma ATC_TS_Transaction_read:\n    forall n u a1 a2,\n    (a1 < data_length <-> a2 < data_length) -> \n    Termination_Sensitive u\n    (@lift_L2 AuthenticationOperation _ TransactionCacheLang _\n        (Transaction.read a1))\n    (@lift_L2 AuthenticationOperation _ TransactionCacheLang  _\n        (Transaction.read a2))\n  (Simulation.Definitions.compile\n     ATC_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Recover |)))\n  (refines_valid ATC_Refinement\n     AD_valid_state)\n  (fun s1 s2 =>\n  Transaction.get_first (fst (snd s1)) a1 = None <-> Transaction.get_first (fst (snd s2)) a2 = None)\n  (ATC_reboot_list n).\n  Proof.\n    unfold Transaction.read; intros.\n    destruct (Compare_dec.lt_dec a1 data_length);\n    destruct (Compare_dec.lt_dec a2 data_length); try lia.\n    2: apply ATC_TS_ret.\n\n    intros.\n    eapply ATC_TS_compositional; simpl.\n    intros; eapply ATC_TS_TransactionCache_get.\n\n    intros.\n    cleanup.\n    repeat invert_exec.\n    destruct_fresh (Transaction.get_first (fst (snd s1)) a1);\n    destruct_fresh (Transaction.get_first (fst (snd s2)) a2);\n    try solve [intuition congruence].\n    setoid_rewrite D;\n    setoid_rewrite D0; simpl.\n    apply ATC_TS_ret.\n    apply H2 in D0; \n    setoid_rewrite D in D0; congruence.\n    apply H2 in D; \n    setoid_rewrite D in D0; congruence.\n\n    setoid_rewrite D;\n    setoid_rewrite D0; simpl.\n    eapply ATC_TS_compositional; simpl; intros.\n    eapply ATC_TS_LoggedDisk_read; eauto.\n    apply ATC_TS_ret.\n    instantiate (1:= fun _ _ => True); simpl; eauto.\n    instantiate (1:= fun _ _ => True); simpl; eauto.\n  Qed.\n\n  Lemma ATC_TS_auth:\n  forall u u1 u2 n V R,\n  Termination_Sensitive u \n  (Op\n     (HorizontalComposition AuthenticationOperation\n        TransactionCacheOperation) \n        (@P1 AuthenticationOperation _ _ (Auth u1)))\n  (Op\n     (HorizontalComposition AuthenticationOperation\n        TransactionCacheOperation) \n        (@P1 AuthenticationOperation _ _ (Auth u2)))\n  (RefinementLift.compile\n     (HorizontalComposition AuthenticationOperation\n        TransactionCacheOperation)\n     (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore data_length))\n     ATCLang AD\n     (HC_Core_Refinement ATCLang AD\n        Definitions.TDCoreRefinement) unit File.recover)\n  V R (ATC_reboot_list n).\n  Proof.\n   unfold Termination_Sensitive, ATC_reboot_list;\n   intros.\n   destruct n; simpl in *.\n   {\n      repeat invert_exec.\n      invert_exec'' H9; repeat invert_exec;\n      destruct (user_dec u u2);\n      eexists (RFinished _ _); try solve [repeat econstructor; eauto].\n   }\n   {\n    repeat invert_exec.\n    invert_exec'' H12; repeat invert_exec.\n    simpl in *; edestruct ATC_TS_recovery. \n    3: eauto.\n    unfold refines_valid, AD_valid_state, \n    FD_valid_state, refines_valid; simpl; \n    intros; eauto.\n\n    unfold refines_valid, AD_valid_state, \n    FD_valid_state, refines_valid; simpl; \n    intros; eauto.\n    shelve.\n    eexists (Recovered _); repeat econstructor; eauto.\n   }\n   Unshelve.\n   all: try solve [exact (fun _ _ => True)].\n   all: simpl; eauto.\nQed.\n\n  Lemma ATC_TS_abort:\n   forall n u R,\n  Termination_Sensitive u\n  (compile_core\n     (HC_Core_Refinement ATCLang AuthenticatedDiskLayer.ADLang\n        Definitions.TDCoreRefinement)\n        (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Abort))\n  (compile_core\n     (HC_Core_Refinement ATCLang AuthenticatedDiskLayer.ADLang\n        Definitions.TDCoreRefinement)\n        (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Abort))\n  (Simulation.Definitions.compile ATC_Refinement\n     (Simulation.Definitions.compile FDRefinement\n        (Op FileToFileDisk.Definitions.abs_core Recover)))\n  (refines_valid ATC_Refinement AD_valid_state) R\n  (ATC_reboot_list n).\n  Proof.\n     unfold Termination_Sensitive, ATC_reboot_list;\n     intros.\n     destruct n; simpl in *.\n     {\n        repeat invert_exec.\n        invert_exec'' H9; repeat invert_exec.\n        eexists (RFinished _ _); repeat econstructor; eauto.\n     }\n     {\n      repeat invert_exec.\n      invert_exec'' H12; repeat invert_exec.\n      simpl in *; edestruct ATC_TS_recovery. \n      3: eauto.\n      unfold refines_valid, AD_valid_state, \n      FD_valid_state, refines_valid; simpl; \n      intros; eauto.\n\n      unfold refines_valid, AD_valid_state, \n      FD_valid_state, refines_valid; simpl; \n      intros; eauto.\n      shelve.\n      eexists (Recovered _); repeat econstructor; eauto.\n     }\n     Unshelve.\n     all: try solve [exact (fun _ _ => True)].\n     all: simpl; eauto.\n  Qed.\n\n  Lemma ATC_TS_commit:\n  forall n u,\n Termination_Sensitive u\n (compile_core\n    (HC_Core_Refinement ATCLang AuthenticatedDiskLayer.ADLang\n       Definitions.TDCoreRefinement)\n       (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Commit))\n (compile_core\n    (HC_Core_Refinement ATCLang AuthenticatedDiskLayer.ADLang\n       Definitions.TDCoreRefinement)\n       (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Commit))\n (Simulation.Definitions.compile ATC_Refinement\n    (Simulation.Definitions.compile FDRefinement\n       (Op FileToFileDisk.Definitions.abs_core Recover)))\n (refines_valid ATC_Refinement AD_valid_state) \n (fun s1 s2 => (Forall (fun a : nat => a < data_length)\n (dedup_last addr_dec (rev (map fst (fst (snd s1))))) <->\n Forall (fun a : nat => a < data_length)\n (dedup_last addr_dec (rev (map fst (fst (snd s2)))))) /\\\n\n (length\n(addr_list_to_blocks\n(dedup_last addr_dec (rev (map fst (fst (snd s1)))))) +\nlength\n(dedup_by_list addr_dec (rev (map fst (fst (snd s1))))\n(rev (map snd (fst (snd s1))))) <= log_length <->\nlength\n(addr_list_to_blocks\n(dedup_last addr_dec (rev (map fst (fst (snd s2)))))) +\nlength\n(dedup_by_list addr_dec (rev (map fst (fst (snd s2))))\n(rev (map snd (fst (snd s2))))) <= log_length))\n (ATC_reboot_list n).\n Proof.\n    intros; simpl.\n    eapply ATC_TS_compositional.\n    intros; apply ATC_TS_TransactionCache_get.\n    2: intros; shelve.\n    intros; repeat invert_exec.\n    \n    eapply ATC_TS_compositional.\n    {\n       intros; eapply ATC_TS_LoggedDisk_write;\n       intuition eauto. \n       \n       eapply Transaction.dedup_last_NoDup.\n       eapply Transaction.dedup_last_NoDup.\n       \n       eapply dedup_last_dedup_by_list_length_le.\n       repeat rewrite rev_length, map_length; eauto.\n       eapply dedup_last_dedup_by_list_length_le.\n       repeat rewrite rev_length, map_length; eauto.\n    }\n    intros; eapply ATC_TS_abort.\n    intros; shelve.\n    Unshelve. \n    all: try solve [exact (fun _ _ => True)].\n    all: simpl; eauto.\nQed.\n\n  Lemma ATC_TS_abort_then_ret:\n  forall n u T (t1 t2: T) R,\n  Termination_Sensitive u\n  (RefinementLift.compile\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n     (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement)\n     _ (Bind\n     (Op\n        (HorizontalComposition AuthenticationOperation\n           (TransactionalDiskLayer.TDCore data_length))\n        (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Abort))\n     (fun _ : unit => Ret t1)))\n  (RefinementLift.compile\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n     (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement)\n     _ (Bind\n     (Op\n        (HorizontalComposition AuthenticationOperation\n           (TransactionalDiskLayer.TDCore data_length))\n           (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Abort))\n     (fun _ : unit => Ret t2)))\n  (RefinementLift.compile\n     (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n     (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n     (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement) unit\n     File.recover) \n     (refines_valid ATC_Refinement\n      AD_valid_state) R (ATC_reboot_list n).\n   Proof.\n      intros.\n      eapply ATC_TS_compositional.\n      intros; apply ATC_TS_abort.\n      intros; apply ATC_TS_ret.\n      instantiate (1:= fun _ _ => True); simpl; eauto.\n   Qed.\n\n   Lemma ATC_TS_commit_then_ret:\n   forall n u T (t1 t2: T),\n   Termination_Sensitive u\n   (RefinementLift.compile\n      (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n      (HorizontalComposition AuthenticationOperation\n         (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n      (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement)\n      _ (Bind\n      (Op\n         (HorizontalComposition AuthenticationOperation\n            (TransactionalDiskLayer.TDCore data_length))\n         (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Commit))\n      (fun _ : unit => Ret t1)))\n   (RefinementLift.compile\n      (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n      (HorizontalComposition AuthenticationOperation\n         (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n      (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement)\n      _ (Bind\n      (Op\n         (HorizontalComposition AuthenticationOperation\n            (TransactionalDiskLayer.TDCore data_length))\n            (@P2 _ (TransactionalDiskLayer.TDCore data_length) _ TransactionalDiskLayer.Commit))\n      (fun _ : unit => Ret t2)))\n   (RefinementLift.compile\n      (HorizontalComposition AuthenticationOperation TransactionCacheOperation)\n      (HorizontalComposition AuthenticationOperation\n         (TransactionalDiskLayer.TDCore data_length)) ATCLang AD\n      (HC_Core_Refinement ATCLang AD Definitions.TDCoreRefinement) unit\n      File.recover) \n      (refines_valid ATC_Refinement\n       AD_valid_state) \n       (fun s1 s2 => (Forall (fun a : nat => a < data_length)\n (dedup_last addr_dec (rev (map fst (fst (snd s1))))) <->\n Forall (fun a : nat => a < data_length)\n (dedup_last addr_dec (rev (map fst (fst (snd s2)))))) /\\\n\n (length\n(addr_list_to_blocks\n(dedup_last addr_dec (rev (map fst (fst (snd s1)))))) +\nlength\n(dedup_by_list addr_dec (rev (map fst (fst (snd s1))))\n(rev (map snd (fst (snd s1))))) <= log_length <->\nlength\n(addr_list_to_blocks\n(dedup_last addr_dec (rev (map fst (fst (snd s2)))))) +\nlength\n(dedup_by_list addr_dec (rev (map fst (fst (snd s2))))\n(rev (map snd (fst (snd s2))))) <= log_length))\n       (ATC_reboot_list n).\n    Proof.\n       intros.\n       eapply ATC_TS_compositional.\n       intros; apply ATC_TS_commit.\n       intros; apply ATC_TS_ret.\n       instantiate (1:= fun _ _ => True); simpl; eauto.\n    Qed.", "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/ATC_TS/ATC_TS_TC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.3140505514119072, "lm_q1q2_score": 0.1607048771968239}}
{"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.\nFrom shack.soundness Require Import defs.\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 \u0398}.\n\n  Lemma sub_soundness C cdef \u0394 kd \u0393 rigid \u03930 \u03931 c:\n    wf_cdefs \u2192\n    wf_lty \u0393 \u2192\n    bounded_lty rigid \u0393 \u2192\n    Forall wf_constraint \u0394 \u2192\n    Forall (bounded_constraint rigid) \u0394 \u2192\n    pdefs !! C = Some cdef \u2192\n    lty_sub \u0394 kd \u03931 \u03930 \u2192\n    bounded_lty rigid \u03930 \u2192\n    cmd_has_ty C \u0394 kd rigid \u0393 c \u03931 \u2192\n    \u2200 t0 t0def \u03a3t0 \u03c30,\n    pdefs !! t0 = Some t0def \u2192\n    length \u03a3t0 = length t0def.(generics) \u2192\n    inherits_using t0 C \u03c30 \u2192\n    \u2200 \u03a3 st st' n,\n    length \u03a3 = rigid \u2192\n    rigid \u2265 length cdef.(generics) \u2192\n    cmd_eval C st c st' n \u2192\n    let \u03a3this := interp_exact_tag interp_type t0 \u03a3t0 in\n    \u231cinterp_list interp_nothing \u03a3t0 \u03c30 \u2261 take (length cdef.(generics)) \u03a3\u231d -\u2217\n    \u25a1 interp_env_as_mixed \u03a3t0 -\u2217\n    \u25a1 interp_env_as_mixed \u03a3 -\u2217\n    \u25a1 \u03a3interp \u03a3this \u03a3 \u0394 -\u2217\n\n    \u25a1 (\u231cwf_lty \u0393\u231d \u2192\n       \u231cbounded_lty rigid \u0393\u231d \u2192\n       \u231cForall wf_constraint \u0394\u231d \u2192\n       \u231cForall (bounded_constraint rigid) \u0394\u231d \u2192\n       \u2200 \u03a3 st st' n\n       (_: length \u03a3 = rigid)\n       (_: rigid \u2265 length (generics cdef))\n       (_: cmd_eval C st c st' n),\n       \u231cinterp_list interp_nothing \u03a3t0 \u03c30 \u2261 take (length cdef.(generics)) \u03a3\u231d -\u2217\n       \u25a1 interp_env_as_mixed \u03a3t0 -\u2217\n       \u25a1 interp_env_as_mixed \u03a3 -\u2217\n       \u25a1 \u03a3interp (interp_exact_tag interp_type t0 \u03a3t0) \u03a3 \u0394 -\u2217\n       heap_models st.2 \u2217\n         interp_local_tys (interp_exact_tag interp_type t0 \u03a3t0) \u03a3 \u0393 st.1 -\u2217\n       |=\u25b7^n heap_models st'.2 \u2217\n         interp_local_tys (interp_exact_tag interp_type t0 \u03a3t0) \u03a3 \u03931 st'.1) -\u2217\n\n    heap_models st.2 \u2217 interp_local_tys \u03a3this \u03a3 \u0393 st.1 -\u2217\n    |=\u25b7^n heap_models st'.2 \u2217 interp_local_tys \u03a3this \u03a3 \u03930 st'.1.\n  Proof.\n    move => wfpdefs wflty blty h\u0394 h\u0394b hcdef hsub hb h.\n    move => t0 t0def \u03a3t0 \u03c30 ht0def hlen\u03a3t0 hin_t0_C.\n    move => \u03a3 st st' n hrigid hge hc \u03a3this.\n    iIntros \"%h\u03a3eq #h\u03a3t0 #h\u03a3 #h\u03a3\u0394 #HI H\".\n    iSpecialize (\"HI\" $! wflty blty h\u0394 h\u0394b).\n    iSpecialize (\"HI\" $! \u03a3 _ _ _ hrigid hge hc h\u03a3eq with \"h\u03a3t0 h\u03a3 h\u03a3\u0394 H\").\n    iApply updN_mono_I; last done.\n    iIntros \"[Hh #Hrty]\".\n    iFrame.\n    iAssert (\u25a1 interp_as_mixed \u03a3this)%I as \"#h\u03a3this\".\n    { iModIntro; iIntros (w) \"hw\".\n      iLeft; iRight; iRight.\n      iExists t0, \u03a3t0, t0def; iSplit; first done.\n      by iApply (exact_subtype_is_inclusion_aux with \"h\u03a3t0 hw\").\n    }\n    iDestruct (interp_local_tys_is_inclusion with \"h\u03a3this h\u03a3 h\u03a3\u0394 Hrty\") as \"Hrty'\" => //; try by apply wfpdefs.\n    + apply cmd_has_ty_wf in h; try (assumption || by apply wfpdefs).\n    + rewrite Forall_forall => i hi v.\n      by apply _.\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/sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.1603262023312138}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nImport Clightdefs.ClightNotations.\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\nLocal Open Scope clight_scope.\n\nModule Info.\n  Definition version := \"3.10\".\n  Definition build_number := \"\".\n  Definition build_tag := \"\".\n  Definition build_branch := \"\".\n  Definition arch := \"x86\".\n  Definition model := \"32sse2\".\n  Definition abi := \"standard\".\n  Definition bitsize := 32.\n  Definition big_endian := false.\n  Definition source_file := \"threads.c\".\n  Definition normalized := false.\nEnd Info.\n\nDefinition _N : ident := $\"N\".\nDefinition _R : ident := $\"R\".\nDefinition _REPEAT : ident := $\"REPEAT\".\nDefinition _T : ident := $\"T\".\nDefinition __138 : ident := $\"_138\".\nDefinition __139 : ident := $\"_139\".\nDefinition __212 : ident := $\"_212\".\nDefinition __213 : ident := $\"_213\".\nDefinition __214 : ident := $\"_214\".\nDefinition __Bigint : ident := $\"_Bigint\".\nDefinition ___builtin_annot : ident := $\"__builtin_annot\".\nDefinition ___builtin_annot_intval : ident := $\"__builtin_annot_intval\".\nDefinition ___builtin_bswap : ident := $\"__builtin_bswap\".\nDefinition ___builtin_bswap16 : ident := $\"__builtin_bswap16\".\nDefinition ___builtin_bswap32 : ident := $\"__builtin_bswap32\".\nDefinition ___builtin_bswap64 : ident := $\"__builtin_bswap64\".\nDefinition ___builtin_clz : ident := $\"__builtin_clz\".\nDefinition ___builtin_clzl : ident := $\"__builtin_clzl\".\nDefinition ___builtin_clzll : ident := $\"__builtin_clzll\".\nDefinition ___builtin_ctz : ident := $\"__builtin_ctz\".\nDefinition ___builtin_ctzl : ident := $\"__builtin_ctzl\".\nDefinition ___builtin_ctzll : ident := $\"__builtin_ctzll\".\nDefinition ___builtin_debug : ident := $\"__builtin_debug\".\nDefinition ___builtin_expect : ident := $\"__builtin_expect\".\nDefinition ___builtin_fabs : ident := $\"__builtin_fabs\".\nDefinition ___builtin_fabsf : ident := $\"__builtin_fabsf\".\nDefinition ___builtin_fmadd : ident := $\"__builtin_fmadd\".\nDefinition ___builtin_fmax : ident := $\"__builtin_fmax\".\nDefinition ___builtin_fmin : ident := $\"__builtin_fmin\".\nDefinition ___builtin_fmsub : ident := $\"__builtin_fmsub\".\nDefinition ___builtin_fnmadd : ident := $\"__builtin_fnmadd\".\nDefinition ___builtin_fnmsub : ident := $\"__builtin_fnmsub\".\nDefinition ___builtin_fsqrt : ident := $\"__builtin_fsqrt\".\nDefinition ___builtin_membar : ident := $\"__builtin_membar\".\nDefinition ___builtin_memcpy_aligned : ident := $\"__builtin_memcpy_aligned\".\nDefinition ___builtin_read16_reversed : ident := $\"__builtin_read16_reversed\".\nDefinition ___builtin_read32_reversed : ident := $\"__builtin_read32_reversed\".\nDefinition ___builtin_sel : ident := $\"__builtin_sel\".\nDefinition ___builtin_sqrt : ident := $\"__builtin_sqrt\".\nDefinition ___builtin_unreachable : ident := $\"__builtin_unreachable\".\nDefinition ___builtin_va_arg : ident := $\"__builtin_va_arg\".\nDefinition ___builtin_va_copy : ident := $\"__builtin_va_copy\".\nDefinition ___builtin_va_end : ident := $\"__builtin_va_end\".\nDefinition ___builtin_va_start : ident := $\"__builtin_va_start\".\nDefinition ___builtin_write16_reversed : ident := $\"__builtin_write16_reversed\".\nDefinition ___builtin_write32_reversed : ident := $\"__builtin_write32_reversed\".\nDefinition ___cleanup : ident := $\"__cleanup\".\nDefinition ___compcert_i64_dtos : ident := $\"__compcert_i64_dtos\".\nDefinition ___compcert_i64_dtou : ident := $\"__compcert_i64_dtou\".\nDefinition ___compcert_i64_sar : ident := $\"__compcert_i64_sar\".\nDefinition ___compcert_i64_sdiv : ident := $\"__compcert_i64_sdiv\".\nDefinition ___compcert_i64_shl : ident := $\"__compcert_i64_shl\".\nDefinition ___compcert_i64_shr : ident := $\"__compcert_i64_shr\".\nDefinition ___compcert_i64_smod : ident := $\"__compcert_i64_smod\".\nDefinition ___compcert_i64_smulh : ident := $\"__compcert_i64_smulh\".\nDefinition ___compcert_i64_stod : ident := $\"__compcert_i64_stod\".\nDefinition ___compcert_i64_stof : ident := $\"__compcert_i64_stof\".\nDefinition ___compcert_i64_udiv : ident := $\"__compcert_i64_udiv\".\nDefinition ___compcert_i64_umod : ident := $\"__compcert_i64_umod\".\nDefinition ___compcert_i64_umulh : ident := $\"__compcert_i64_umulh\".\nDefinition ___compcert_i64_utod : ident := $\"__compcert_i64_utod\".\nDefinition ___compcert_i64_utof : ident := $\"__compcert_i64_utof\".\nDefinition ___compcert_va_composite : ident := $\"__compcert_va_composite\".\nDefinition ___compcert_va_float64 : ident := $\"__compcert_va_float64\".\nDefinition ___compcert_va_int32 : ident := $\"__compcert_va_int32\".\nDefinition ___compcert_va_int64 : ident := $\"__compcert_va_int64\".\nDefinition ___count : ident := $\"__count\".\nDefinition ___dummy : ident := $\"__dummy\".\nDefinition ___getreent : ident := $\"__getreent\".\nDefinition ___locale_t : ident := $\"__locale_t\".\nDefinition ___pthread_t : ident := $\"__pthread_t\".\nDefinition ___sFILE64 : ident := $\"__sFILE64\".\nDefinition ___sbuf : ident := $\"__sbuf\".\nDefinition ___sdidinit : ident := $\"__sdidinit\".\nDefinition ___sf : ident := $\"__sf\".\nDefinition ___sglue : ident := $\"__sglue\".\nDefinition ___stringlit_1 : ident := $\"__stringlit_1\".\nDefinition ___stringlit_2 : ident := $\"__stringlit_2\".\nDefinition ___tm : ident := $\"__tm\".\nDefinition ___tm_hour : ident := $\"__tm_hour\".\nDefinition ___tm_isdst : ident := $\"__tm_isdst\".\nDefinition ___tm_mday : ident := $\"__tm_mday\".\nDefinition ___tm_min : ident := $\"__tm_min\".\nDefinition ___tm_mon : ident := $\"__tm_mon\".\nDefinition ___tm_sec : ident := $\"__tm_sec\".\nDefinition ___tm_wday : ident := $\"__tm_wday\".\nDefinition ___tm_yday : ident := $\"__tm_yday\".\nDefinition ___tm_year : ident := $\"__tm_year\".\nDefinition ___value : ident := $\"__value\".\nDefinition ___wch : ident := $\"__wch\".\nDefinition ___wchb : ident := $\"__wchb\".\nDefinition __add : ident := $\"_add\".\nDefinition __asctime_buf : ident := $\"_asctime_buf\".\nDefinition __atexit : ident := $\"_atexit\".\nDefinition __atexit0 : ident := $\"_atexit0\".\nDefinition __base : ident := $\"_base\".\nDefinition __bf : ident := $\"_bf\".\nDefinition __blksize : ident := $\"_blksize\".\nDefinition __close : ident := $\"_close\".\nDefinition __cookie : ident := $\"_cookie\".\nDefinition __cvtbuf : ident := $\"_cvtbuf\".\nDefinition __cvtlen : ident := $\"_cvtlen\".\nDefinition __data : ident := $\"_data\".\nDefinition __dso_handle : ident := $\"_dso_handle\".\nDefinition __emergency : ident := $\"_emergency\".\nDefinition __errno : ident := $\"_errno\".\nDefinition __file : ident := $\"_file\".\nDefinition __flags : ident := $\"_flags\".\nDefinition __flags2 : ident := $\"_flags2\".\nDefinition __fnargs : ident := $\"_fnargs\".\nDefinition __fns : ident := $\"_fns\".\nDefinition __fntypes : ident := $\"_fntypes\".\nDefinition __freelist : ident := $\"_freelist\".\nDefinition __gamma_signgam : ident := $\"_gamma_signgam\".\nDefinition __getdate_err : ident := $\"_getdate_err\".\nDefinition __glue : ident := $\"_glue\".\nDefinition __h_errno : ident := $\"_h_errno\".\nDefinition __inc : ident := $\"_inc\".\nDefinition __ind : ident := $\"_ind\".\nDefinition __iobs : ident := $\"_iobs\".\nDefinition __is_cxa : ident := $\"_is_cxa\".\nDefinition __k : ident := $\"_k\".\nDefinition __l64a_buf : ident := $\"_l64a_buf\".\nDefinition __lb : ident := $\"_lb\".\nDefinition __lbfsize : ident := $\"_lbfsize\".\nDefinition __locale : ident := $\"_locale\".\nDefinition __localtime_buf : ident := $\"_localtime_buf\".\nDefinition __lock : ident := $\"_lock\".\nDefinition __maxwds : ident := $\"_maxwds\".\nDefinition __mblen_state : ident := $\"_mblen_state\".\nDefinition __mbrlen_state : ident := $\"_mbrlen_state\".\nDefinition __mbrtowc_state : ident := $\"_mbrtowc_state\".\nDefinition __mbsrtowcs_state : ident := $\"_mbsrtowcs_state\".\nDefinition __mbstate : ident := $\"_mbstate\".\nDefinition __mbtowc_state : ident := $\"_mbtowc_state\".\nDefinition __mult : ident := $\"_mult\".\nDefinition __nbuf : ident := $\"_nbuf\".\nDefinition __new : ident := $\"_new\".\nDefinition __next : ident := $\"_next\".\nDefinition __nextf : ident := $\"_nextf\".\nDefinition __niobs : ident := $\"_niobs\".\nDefinition __nmalloc : ident := $\"_nmalloc\".\nDefinition __offset : ident := $\"_offset\".\nDefinition __on_exit_args : ident := $\"_on_exit_args\".\nDefinition __p : ident := $\"_p\".\nDefinition __p5s : ident := $\"_p5s\".\nDefinition __r : ident := $\"_r\".\nDefinition __r48 : ident := $\"_r48\".\nDefinition __rand48 : ident := $\"_rand48\".\nDefinition __rand_next : ident := $\"_rand_next\".\nDefinition __read : ident := $\"_read\".\nDefinition __reent : ident := $\"_reent\".\nDefinition __result : ident := $\"_result\".\nDefinition __result_k : ident := $\"_result_k\".\nDefinition __seed : ident := $\"_seed\".\nDefinition __seek : ident := $\"_seek\".\nDefinition __seek64 : ident := $\"_seek64\".\nDefinition __sig_func : ident := $\"_sig_func\".\nDefinition __sign : ident := $\"_sign\".\nDefinition __signal_buf : ident := $\"_signal_buf\".\nDefinition __size : ident := $\"_size\".\nDefinition __stderr : ident := $\"_stderr\".\nDefinition __stdin : ident := $\"_stdin\".\nDefinition __stdout : ident := $\"_stdout\".\nDefinition __strtok_last : ident := $\"_strtok_last\".\nDefinition __ub : ident := $\"_ub\".\nDefinition __ubuf : ident := $\"_ubuf\".\nDefinition __unspecified_locale_info : ident := $\"_unspecified_locale_info\".\nDefinition __unused : ident := $\"_unused\".\nDefinition __unused_rand : ident := $\"_unused_rand\".\nDefinition __up : ident := $\"_up\".\nDefinition __ur : ident := $\"_ur\".\nDefinition __w : ident := $\"_w\".\nDefinition __wcrtomb_state : ident := $\"_wcrtomb_state\".\nDefinition __wcsrtombs_state : ident := $\"_wcsrtombs_state\".\nDefinition __wctomb_state : ident := $\"_wctomb_state\".\nDefinition __wds : ident := $\"_wds\".\nDefinition __write : ident := $\"_write\".\nDefinition __x : ident := $\"_x\".\nDefinition _acquire : ident := $\"acquire\".\nDefinition _arg : ident := $\"arg\".\nDefinition _argc : ident := $\"argc\".\nDefinition _args : ident := $\"args\".\nDefinition _argv : ident := $\"argv\".\nDefinition _atoi : ident := $\"atoi\".\nDefinition _atom_CAS : ident := $\"atom_CAS\".\nDefinition _atom_int : ident := $\"atom_int\".\nDefinition _atom_store : ident := $\"atom_store\".\nDefinition _b : ident := $\"b\".\nDefinition _closure : ident := $\"closure\".\nDefinition _d : ident := $\"d\".\nDefinition _do_tasks : ident := $\"do_tasks\".\nDefinition _done : ident := $\"done\".\nDefinition _dotprod : ident := $\"dotprod\".\nDefinition _dotprod_task : ident := $\"dotprod_task\".\nDefinition _dotprod_worker : ident := $\"dotprod_worker\".\nDefinition _drand48 : ident := $\"drand48\".\nDefinition _dtasks : ident := $\"dtasks\".\nDefinition _exit : ident := $\"exit\".\nDefinition _exit_thread : ident := $\"exit_thread\".\nDefinition _expected : ident := $\"expected\".\nDefinition _f : ident := $\"f\".\nDefinition _fprintf : ident := $\"fprintf\".\nDefinition _free_atomic : ident := $\"free_atomic\".\nDefinition _freelock : ident := $\"freelock\".\nDefinition _go : ident := $\"go\".\nDefinition _i : ident := $\"i\".\nDefinition _initialize_task : ident := $\"initialize_task\".\nDefinition _j : ident := $\"j\".\nDefinition _k : ident := $\"k\".\nDefinition _lock : ident := $\"lock\".\nDefinition _main : ident := $\"main\".\nDefinition _make_atomic : ident := $\"make_atomic\".\nDefinition _make_tasks : ident := $\"make_tasks\".\nDefinition _makelock : ident := $\"makelock\".\nDefinition _malloc : ident := $\"malloc\".\nDefinition _n : ident := $\"n\".\nDefinition _num_threads : ident := $\"num_threads\".\nDefinition _printf : ident := $\"printf\".\nDefinition _r : ident := $\"r\".\nDefinition _release : ident := $\"release\".\nDefinition _result : ident := $\"result\".\nDefinition _spawn : ident := $\"spawn\".\nDefinition _t : ident := $\"t\".\nDefinition _task : ident := $\"task\".\nDefinition _tasks : ident := $\"tasks\".\nDefinition _test : ident := $\"test\".\nDefinition _thrd_create : ident := $\"thrd_create\".\nDefinition _thrd_exit : ident := $\"thrd_exit\".\nDefinition _thread_worker : ident := $\"thread_worker\".\nDefinition _vec1 : ident := $\"vec1\".\nDefinition _vec2 : ident := $\"vec2\".\nDefinition _w : ident := $\"w\".\nDefinition _t'1 : ident := 128%positive.\n\nDefinition f_makelock := {|\n  fn_return := (tptr (Tstruct _atom_int noattr));\n  fn_callconv := cc_default;\n  fn_params := nil;\n  fn_vars := nil;\n  fn_temps := ((_t'1, (tptr (Tstruct _atom_int noattr))) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _make_atomic (Tfunction (Tcons tint Tnil)\n                         (tptr (Tstruct _atom_int noattr)) cc_default))\n    ((Econst_int (Int.repr 1) tint) :: nil))\n  (Sreturn (Some (Etempvar _t'1 (tptr (Tstruct _atom_int noattr))))))\n|}.\n\nDefinition f_freelock := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_lock, (tptr (Tstruct _atom_int noattr))) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None\n  (Evar _free_atomic (Tfunction\n                       (Tcons (tptr (Tstruct _atom_int noattr)) Tnil) tvoid\n                       cc_default))\n  ((Etempvar _lock (tptr (Tstruct _atom_int noattr))) :: nil))\n|}.\n\nDefinition f_acquire := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_lock, (tptr (Tstruct _atom_int noattr))) :: nil);\n  fn_vars := ((_expected, tint) :: nil);\n  fn_temps := ((_b, tint) :: (_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Sset _b (Econst_int (Int.repr 0) tint))\n  (Sloop\n    (Ssequence\n      (Sassign (Evar _expected tint) (Econst_int (Int.repr 0) tint))\n      (Ssequence\n        (Scall (Some _t'1)\n          (Evar _atom_CAS (Tfunction\n                            (Tcons (tptr (Tstruct _atom_int noattr))\n                              (Tcons (tptr tint) (Tcons tint Tnil))) tint\n                            cc_default))\n          ((Etempvar _lock (tptr (Tstruct _atom_int noattr))) ::\n           (Eaddrof (Evar _expected tint) (tptr tint)) ::\n           (Econst_int (Int.repr 1) tint) :: nil))\n        (Sset _b (Etempvar _t'1 tint))))\n    (Sifthenelse (Ebinop Oeq (Etempvar _b tint)\n                   (Econst_int (Int.repr 0) tint) tint)\n      Sskip\n      Sbreak)))\n|}.\n\nDefinition f_release := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_lock, (tptr (Tstruct _atom_int noattr))) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None\n  (Evar _atom_store (Tfunction\n                      (Tcons (tptr (Tstruct _atom_int noattr))\n                        (Tcons tint Tnil)) tvoid cc_default))\n  ((Etempvar _lock (tptr (Tstruct _atom_int noattr))) ::\n   (Econst_int (Int.repr 0) tint) :: nil))\n|}.\n\nDefinition f_spawn := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_f,\n                 (tptr (Tfunction (Tcons (tptr tvoid) Tnil) tint cc_default))) ::\n                (_args, (tptr tvoid)) :: nil);\n  fn_vars := ((_t, (tptr (Tstruct ___pthread_t noattr))) :: nil);\n  fn_temps := ((_t'1, tint) :: nil);\n  fn_body :=\n(Ssequence\n  (Ssequence\n    (Scall (Some _t'1)\n      (Evar _thrd_create (Tfunction\n                           (Tcons (tptr (tptr (Tstruct ___pthread_t noattr)))\n                             (Tcons\n                               (tptr (Tfunction (Tcons (tptr tvoid) Tnil)\n                                       tint cc_default))\n                               (Tcons (tptr tvoid) Tnil))) tint cc_default))\n      ((Eaddrof (Evar _t (tptr (Tstruct ___pthread_t noattr)))\n         (tptr (tptr (Tstruct ___pthread_t noattr)))) ::\n       (Etempvar _f (tptr (Tfunction (Tcons (tptr tvoid) Tnil) tint\n                            cc_default))) :: (Etempvar _args (tptr tvoid)) ::\n       nil))\n    (Sifthenelse (Ebinop One (Etempvar _t'1 tint)\n                   (Econst_int (Int.repr 4) tint) tint)\n      (Scall None (Evar _exit (Tfunction (Tcons tint Tnil) tvoid cc_default))\n        ((Econst_int (Int.repr 1) tint) :: nil))\n      Sskip))\n  (Sreturn None))\n|}.\n\nDefinition f_exit_thread := {|\n  fn_return := tvoid;\n  fn_callconv := cc_default;\n  fn_params := ((_r, tint) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Scall None (Evar _thrd_exit (Tfunction (Tcons tint Tnil) tvoid cc_default))\n  ((Etempvar _r tint) :: nil))\n|}.\n\nDefinition composites : list composite_definition :=\n(Composite ___pthread_t Struct (Member_plain ___dummy tschar :: nil) noattr ::\n nil).\n\nDefinition global_definitions : list (ident * globdef fundef type) :=\n((___compcert_va_int32,\n   Gfun(External (EF_runtime \"__compcert_va_int32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tvoid) Tnil) tuint cc_default)) ::\n (___compcert_va_int64,\n   Gfun(External (EF_runtime \"__compcert_va_int64\"\n                   (mksignature (AST.Tint :: nil) AST.Tlong cc_default))\n     (Tcons (tptr tvoid) Tnil) tulong cc_default)) ::\n (___compcert_va_float64,\n   Gfun(External (EF_runtime \"__compcert_va_float64\"\n                   (mksignature (AST.Tint :: nil) AST.Tfloat cc_default))\n     (Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::\n (___compcert_va_composite,\n   Gfun(External (EF_runtime \"__compcert_va_composite\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     (tptr tvoid) cc_default)) ::\n (___compcert_i64_dtos,\n   Gfun(External (EF_runtime \"__compcert_i64_dtos\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tlong cc_default)) ::\n (___compcert_i64_dtou,\n   Gfun(External (EF_runtime \"__compcert_i64_dtou\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tulong cc_default)) ::\n (___compcert_i64_stod,\n   Gfun(External (EF_runtime \"__compcert_i64_stod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tlong Tnil) tdouble cc_default)) ::\n (___compcert_i64_utod,\n   Gfun(External (EF_runtime \"__compcert_i64_utod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tulong Tnil) tdouble cc_default)) ::\n (___compcert_i64_stof,\n   Gfun(External (EF_runtime \"__compcert_i64_stof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tlong Tnil) tfloat cc_default)) ::\n (___compcert_i64_utof,\n   Gfun(External (EF_runtime \"__compcert_i64_utof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tulong Tnil) tfloat cc_default)) ::\n (___compcert_i64_sdiv,\n   Gfun(External (EF_runtime \"__compcert_i64_sdiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_udiv,\n   Gfun(External (EF_runtime \"__compcert_i64_udiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_smod,\n   Gfun(External (EF_runtime \"__compcert_i64_smod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umod,\n   Gfun(External (EF_runtime \"__compcert_i64_umod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_shl,\n   Gfun(External (EF_runtime \"__compcert_i64_shl\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_shr,\n   Gfun(External (EF_runtime \"__compcert_i64_shr\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_sar,\n   Gfun(External (EF_runtime \"__compcert_i64_sar\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_smulh,\n   Gfun(External (EF_runtime \"__compcert_i64_smulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umulh,\n   Gfun(External (EF_runtime \"__compcert_i64_umulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___builtin_bswap64,\n   Gfun(External (EF_builtin \"__builtin_bswap64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) tulong cc_default)) ::\n (___builtin_bswap,\n   Gfun(External (EF_builtin \"__builtin_bswap\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap32,\n   Gfun(External (EF_builtin \"__builtin_bswap32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap16,\n   Gfun(External (EF_builtin \"__builtin_bswap16\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::\n (___builtin_clz,\n   Gfun(External (EF_builtin \"__builtin_clz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzl,\n   Gfun(External (EF_builtin \"__builtin_clzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzll,\n   Gfun(External (EF_builtin \"__builtin_clzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctz,\n   Gfun(External (EF_builtin \"__builtin_ctz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzl,\n   Gfun(External (EF_builtin \"__builtin_ctzl\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzll,\n   Gfun(External (EF_builtin \"__builtin_ctzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_fabs,\n   Gfun(External (EF_builtin \"__builtin_fabs\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_fabsf,\n   Gfun(External (EF_builtin \"__builtin_fabsf\"\n                   (mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))\n     (Tcons tfloat Tnil) tfloat cc_default)) ::\n (___builtin_fsqrt,\n   Gfun(External (EF_builtin \"__builtin_fsqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_sqrt,\n   Gfun(External (EF_builtin \"__builtin_sqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_memcpy_aligned,\n   Gfun(External (EF_builtin \"__builtin_memcpy_aligned\"\n                   (mksignature\n                     (AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tvoid cc_default))\n     (Tcons (tptr tvoid)\n       (Tcons (tptr tvoid) (Tcons tuint (Tcons tuint Tnil)))) tvoid\n     cc_default)) ::\n (___builtin_sel,\n   Gfun(External (EF_builtin \"__builtin_sel\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tbool Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot,\n   Gfun(External (EF_builtin \"__builtin_annot\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot_intval,\n   Gfun(External (EF_builtin \"__builtin_annot_intval\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))\n     tint cc_default)) ::\n (___builtin_membar,\n   Gfun(External (EF_builtin \"__builtin_membar\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_va_start,\n   Gfun(External (EF_builtin \"__builtin_va_start\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_va_arg,\n   Gfun(External (EF_builtin \"__builtin_va_arg\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_va_copy,\n   Gfun(External (EF_builtin \"__builtin_va_copy\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::\n (___builtin_va_end,\n   Gfun(External (EF_builtin \"__builtin_va_end\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_unreachable,\n   Gfun(External (EF_builtin \"__builtin_unreachable\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_expect,\n   Gfun(External (EF_builtin \"__builtin_expect\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons tint (Tcons tint Tnil)) tint\n     cc_default)) ::\n (___builtin_fmax,\n   Gfun(External (EF_builtin \"__builtin_fmax\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmin,\n   Gfun(External (EF_builtin \"__builtin_fmin\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmadd,\n   Gfun(External (EF_builtin \"__builtin_fmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fmsub,\n   Gfun(External (EF_builtin \"__builtin_fmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmadd,\n   Gfun(External (EF_builtin \"__builtin_fnmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmsub,\n   Gfun(External (EF_builtin \"__builtin_fnmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_read16_reversed,\n   Gfun(External (EF_builtin \"__builtin_read16_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons (tptr tushort) Tnil) tushort\n     cc_default)) ::\n (___builtin_read32_reversed,\n   Gfun(External (EF_builtin \"__builtin_read32_reversed\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons (tptr tuint) Tnil) tuint cc_default)) ::\n (___builtin_write16_reversed,\n   Gfun(External (EF_builtin \"__builtin_write16_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))\n     tvoid cc_default)) ::\n (___builtin_write32_reversed,\n   Gfun(External (EF_builtin \"__builtin_write32_reversed\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_debug,\n   Gfun(External (EF_external \"__builtin_debug\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tint Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (_exit,\n   Gfun(External (EF_external \"exit\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons tint Tnil) tvoid cc_default)) ::\n (_thrd_create,\n   Gfun(External (EF_external \"thrd_create\"\n                   (mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tint cc_default))\n     (Tcons (tptr (tptr (Tstruct ___pthread_t noattr)))\n       (Tcons (tptr (Tfunction (Tcons (tptr tvoid) Tnil) tint cc_default))\n         (Tcons (tptr tvoid) Tnil))) tint cc_default)) ::\n (_thrd_exit,\n   Gfun(External (EF_external \"thrd_exit\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons tint Tnil) tvoid cc_default)) ::\n (_make_atomic,\n   Gfun(External (EF_external \"make_atomic\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tint Tnil) (tptr (Tstruct _atom_int noattr)) cc_default)) ::\n (_atom_store,\n   Gfun(External (EF_external \"atom_store\"\n                   (mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr (Tstruct _atom_int noattr)) (Tcons tint Tnil)) tvoid\n     cc_default)) ::\n (_atom_CAS,\n   Gfun(External (EF_external \"atom_CAS\"\n                   (mksignature (AST.Tint :: AST.Tint :: AST.Tint :: nil)\n                     AST.Tint cc_default))\n     (Tcons (tptr (Tstruct _atom_int noattr))\n       (Tcons (tptr tint) (Tcons tint Tnil))) tint cc_default)) ::\n (_free_atomic,\n   Gfun(External (EF_external \"free_atomic\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr (Tstruct _atom_int noattr)) Tnil) tvoid cc_default)) ::\n (_makelock, Gfun(Internal f_makelock)) ::\n (_freelock, Gfun(Internal f_freelock)) ::\n (_acquire, Gfun(Internal f_acquire)) ::\n (_release, Gfun(Internal f_release)) :: (_spawn, Gfun(Internal f_spawn)) ::\n (_exit_thread, Gfun(Internal f_exit_thread)) :: nil).\n\nDefinition public_idents : list ident :=\n(_exit_thread :: _spawn :: _release :: _acquire :: _freelock :: _makelock ::\n _free_atomic :: _atom_CAS :: _atom_store :: _make_atomic :: _thrd_exit ::\n _thrd_create :: _exit :: ___builtin_debug :: ___builtin_write32_reversed ::\n ___builtin_write16_reversed :: ___builtin_read32_reversed ::\n ___builtin_read16_reversed :: ___builtin_fnmsub :: ___builtin_fnmadd ::\n ___builtin_fmsub :: ___builtin_fmadd :: ___builtin_fmin ::\n ___builtin_fmax :: ___builtin_expect :: ___builtin_unreachable ::\n ___builtin_va_end :: ___builtin_va_copy :: ___builtin_va_arg ::\n ___builtin_va_start :: ___builtin_membar :: ___builtin_annot_intval ::\n ___builtin_annot :: ___builtin_sel :: ___builtin_memcpy_aligned ::\n ___builtin_sqrt :: ___builtin_fsqrt :: ___builtin_fabsf ::\n ___builtin_fabs :: ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz ::\n ___builtin_clzll :: ___builtin_clzl :: ___builtin_clz ::\n ___builtin_bswap16 :: ___builtin_bswap32 :: ___builtin_bswap ::\n ___builtin_bswap64 :: ___compcert_i64_umulh :: ___compcert_i64_smulh ::\n ___compcert_i64_sar :: ___compcert_i64_shr :: ___compcert_i64_shl ::\n ___compcert_i64_umod :: ___compcert_i64_smod :: ___compcert_i64_udiv ::\n ___compcert_i64_sdiv :: ___compcert_i64_utof :: ___compcert_i64_stof ::\n ___compcert_i64_utod :: ___compcert_i64_stod :: ___compcert_i64_dtou ::\n ___compcert_i64_dtos :: ___compcert_va_composite ::\n ___compcert_va_float64 :: ___compcert_va_int64 :: ___compcert_va_int32 ::\n nil).\n\nDefinition prog : Clight.program := \n  mkprogram composites global_definitions public_idents _main Logic.I.\n\n\n", "meta": {"author": "VeriNum", "repo": "pardotprod", "sha": "5c8febd4e35a878a1824cedacd9cfc7d63610fb6", "save_path": "github-repos/coq/VeriNum-pardotprod", "path": "github-repos/coq/VeriNum-pardotprod/pardotprod-5c8febd4e35a878a1824cedacd9cfc7d63610fb6/threads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.15995305391763256}}
{"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 Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import SimPromises.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nLemma read_read_tview\n      loc1 ts1 released1 ord1\n      loc2 ts2 released2 ord2\n      tview0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.read_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.read_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\nQed.\n\nLemma read_write_tview\n      loc1 ts1 released1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.write_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  repeat condtac; aggrtac; try apply WF0.\nQed.\n\nLemma read_read_fence_tview\n      loc1 ts1 released1 ord1\n      ord2\n      tview0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.read_fence_tview tview0 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.read_fence_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  - repeat condtac; aggrtac; try apply WF0.\n  - repeat condtac; aggrtac; try apply WF0.\n  - repeat condtac; aggrtac; try apply WF0.\n    destruct ord1; inv COND; inv COND1.\nQed.\n\nLemma read_write_fence_tview\n      loc1 ts1 released1 ord1\n      ord2\n      tview0 sc0\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  TView.le\n    (TView.read_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       loc1 ts1 released1 ord1)\n    (TView.write_fence_tview\n       (TView.read_tview tview0 loc1 ts1 released1 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_read_tview\n      loc1 ts1 ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.write_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.read_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (try by condtac; aggrtac).\n  condtac; aggrtac. condtac.\n  - destruct ord1; inv ORD1; inv COND0.\n  - aggrtac; try apply WF0.\nQed.\n\nLemma write_write_tview\n      loc1 ts1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.write_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac).\n  all: try by apply WF0.\nQed.\n\nLemma write_read_fence_tview\n      loc1 ts1 ord1\n      ord2\n      tview0 sc0\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.read_fence_tview tview0 ord2)\n       sc0 loc1 ts1 ord1)\n    (TView.read_fence_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_write_fence_tview\n      loc1 ts1 ord1\n      ord2\n      tview0 sc0\n      (ORD2: Ordering.le ord2 Ordering.acqrel)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       (TView.write_fence_sc tview0 sc0 ord2)\n       loc1 ts1 ord1)\n    (TView.write_fence_tview\n       (TView.write_tview tview0 sc0 loc1 ts1 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma read_fence_read_tview\n      ord1\n      loc2 ts2 released2 ord2\n      tview0\n      (ORD2: Ordering.le ord2 Ordering.plain \\/ Ordering.le Ordering.acqrel ord2)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2)\n       ord1)\n    (TView.read_tview\n       (TView.read_fence_tview tview0 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\n  des; [|congr]. destruct ord2; inv ORD2; inv COND0.\nQed.\n\nLemma read_fence_write_tview\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       ord1)\n    (TView.write_tview\n       (TView.read_fence_tview tview0 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\nQed.\n\nLemma write_fence_read_tview\n      ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF2: View.opt_wf released2):\n  TView.le\n    (TView.write_fence_tview\n       (TView.read_tview tview0 loc2 ts2 released2 ord2) sc0 ord1)\n    (TView.read_tview\n       (TView.write_fence_tview tview0 sc0 ord1)\n       loc2 ts2 released2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (repeat (condtac; aggrtac; try apply WF0)).\nQed.\n\nLemma write_fence_read_sc\n      ord1\n      loc2 ts2 released2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TimeMap.le\n    (TView.write_fence_sc\n       (TView.read_tview tview0 loc2 ts2 released2 ord2) sc0 ord1)\n    (TView.write_fence_sc tview0 sc0 ord1).\nProof.\n  ii. unfold TView.write_fence_sc.\n  repeat condtac; aggrtac.\nQed.\n\nLemma write_fence_write_tview\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.write_fence_tview\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 ord1)\n    (TView.write_tview\n       (TView.write_fence_tview tview0 sc0 ord1)\n       sc0 loc2 ts2 ord2).\nProof.\n  econs; aggrtac;\n    (try by apply WF0);\n    (repeat (condtac; aggrtac; try apply WF0)).\nQed.\n\nLemma write_fence_write_sc\n      ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (WF0: TView.wf tview0):\n  TimeMap.le\n    (TView.write_fence_sc\n       (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n       sc0 ord1)\n    (TView.write_fence_sc tview0 sc0 ord1).\nProof.\n  ii. unfold TView.write_fence_sc.\n  repeat condtac; aggrtac.\nQed.\n\nLemma read_fence_write_fence_tview\n      ord1\n      ord2\n      tview0 sc0\n      (WF0: TView.wf tview0):\n  TView.le\n    (TView.read_fence_tview\n       (TView.write_fence_tview tview0 sc0 ord2)\n       ord1)\n    (TView.write_fence_tview\n       (TView.read_fence_tview tview0 ord1)\n       sc0 ord2).\nProof.\n  unfold TView.write_fence_tview, TView.write_fence_sc.\n  econs; repeat (try condtac; aggrtac; try apply WF0).\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- View.join_r. viewtac.\n    rewrite <- TimeMap.join_r. apply WF0.\n  - rewrite <- View.join_r. viewtac.\n    rewrite <- TimeMap.join_r. apply WF0.\nQed.\n\nLemma read_write_tview_eq\n      loc1 ts1 released1 ord1\n      loc2 ts2 ord2\n      tview0 sc0\n      (ORD1: Ordering.le ord2 Ordering.relaxed)\n      (WF0: TView.wf tview0)\n      (WF1: View.opt_wf released1):\n  (TView.read_tview\n     (TView.write_tview tview0 sc0 loc2 ts2 ord2)\n     loc1 ts1 released1 ord1) =\n  (TView.write_tview\n     (TView.read_tview tview0 loc1 ts1 released1 ord1)\n     sc0 loc2 ts2 ord2).\nProof.\n  apply TView.antisym.\n  - apply read_write_tview; auto.\n  - apply write_read_tview; auto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/ReorderTView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.15962990678414088}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Arith.Mult\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.StringFacts\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedSumType\n        Fiat.Narcissus.BinLib.AlignedDomainName\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.SimpleDNSPacket\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.HintDbExtra\n        Fiat.Common.Tactics.TransparentAbstract\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Stores.DomainNameStore\n        Fiat.Narcissus.Automation.CacheEncoders.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  Local Open Scope Tuple_scope.\n  Import Vectors.Vector.VectorNotations.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n  Arguments NPeano.div : simpl never.\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n       True /\\ (ValidDomainName a!\"contact_email\") /\\ ValidDomainName a!\"sourcehost\") inil))))\n      (SumType_index\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: [SOA_RDATA])\n         rr!sRDATA)\n      (SumType_proj\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: [SOA_RDATA])\n         rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n               (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n                      (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                             (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                                                 (True /\\ (ValidDomainName a!\"contact_email\")) /\\ ValidDomainName a!\"sourcehost\") inil))))        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    (* intros ? H.\n    destruct rr as [? [? [? [ ] ] ] ]; simpl in *.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *.\n    destruct prim_fst2; simpl in *.\n    apply H.\n  Qed. *)\n  Admitted.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Definition DNS_Packet_OK (data : packet) :=\n    lt (|data!\"answers\" |) (pow2 16)\n    /\\ lt (|data!\"authority\" |) (pow2 16)\n    /\\ lt (|data!\"additional\" |) (pow2 16)\n    /\\ ValidDomainName (data!\"question\")!\"qname\"\n    /\\ forall (rr : resourceRecord),\n        In rr (data!\"answers\" ++ data!\"additional\" ++ data!\"authority\")\n        -> resourceRecord_OK rr.\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n  Definition format_SOA_RDATA (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_A (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata r!sRDATA\n                           DoneC.\n\n  Definition format_packet (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments split1 : simpl never.\n  Arguments split2 : simpl never.\n  Arguments fin_eq_dec m !n !n' /.\n  Arguments addE : simpl never.\n\n  Arguments Vector.nth A !m !v' !p /.\n\n  Definition refine_format_CNAME\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p,\n                  ValidDomainName p\n                  -> refine (format_CNAME p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_CNAME.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n    eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_A\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               refine (format_A p list_CacheFormat_empty)\n                                      (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_A.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n\n    simpl.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_NS\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               ValidDomainName p\n                               -> refine (format_NS p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_NS.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_SOA\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall a : SOA_RDATA,\n                               ValidDomainName a!\"contact_email\"\n                               -> ValidDomainName a!\"sourcehost\"\n                               -> refine (format_SOA_RDATA a list_CacheFormat_empty)\n                                         (ret (@build_aligned_ByteString (numBytes a) (v a), c a)) } } }.\n  Proof.\n    unfold format_SOA_RDATA.\n    eexists _, _, _; intros.\n    pose_string_hyps.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_resource\n    : { numBytes : _ &\n                   { v : _ &\n            { c : _ & forall p\n                             (p_OK : resourceRecord_OK p)\n                             ce,\n            refine (format_resource p ce)\n                   (ret (@build_aligned_ByteString (numBytes p ce) (v p ce), c p ce)) } } }.\n  Proof.\n    unfold format_resource; eexists _, _, _; intros.\n    etransitivity.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply (AlignedFormatSumTypeDoneC); repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME;\n      build_prim_prod_evar;\n      build_prim_prod_evar; simpl;\n      etransitivity;\n      [apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus;\n       eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption\n       | encoder_reflexivity].\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      unfold SumType_proj in H; simpl in H.\n      revert H; instantiate (1 := fun t => True /\\ _ t /\\ _ t); intros [? [? ?] ].\n      pattern t; apply H1.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      pattern t; apply (proj1 (proj2 H)).\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { apply p_OK. }\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    eapply (projT2 (projT2 (projT2 refine_format_resource))); eauto.\n    apply p_OK; assumption.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Time Definition encode_packet\n       (p : packet)\n    := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                      projT1 (projT2 (projT2 refine_format_packet)) p).\n  Set Printing Notations.\n  Print encode_packet.\n\n  Lemma refine_format_packet_Impl_OK\n    : forall p (p_OK : DNS_Packet_OK p),\n      refine (format_packet p list_CacheFormat_empty)\n             (ret (encode_packet p)).\n  Proof.\n    intros; apply (projT2 (projT2 (projT2 refine_format_packet))); eauto.\n  Qed.\n\n  Definition ByteAlignedCorrectDecoderFor {A} {cache : Cache}\n             Invariant FormatSpec :=\n    { decodePlusCacheInv |\n      exists P_inv,\n      (cache_inv_Property (snd decodePlusCacheInv) P_inv\n       -> CorrectDecoder (A := A) monoid Invariant (fun _ _ => True)\n                                  FormatSpec\n                                  (fst decodePlusCacheInv)\n                                  (snd decodePlusCacheInv))\n      /\\ cache_inv_Property (snd decodePlusCacheInv) P_inv}.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments weq : simpl never.\n  Arguments word_indexed : simpl never.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct)\n    | |- appcontext [CorrectDecoder _ _ _ (format_list format_resource) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Ltac synthesize_decoder_ext\n       monoid\n       decode_step'\n       determineHooks\n       synthesize_cache_invariant' :=\n    (* Combines tactics into one-liner. *)\n    start_synthesizing_decoder;\n    [ normalize_compose monoid;\n      repeat first [decode_step' idtac | decode_step determineHooks]\n    | cbv beta; synthesize_cache_invariant' idtac\n    |  ].\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    reflexivity.\n    decide_data_invariant.\n    instantiate (1 := true).\n    simpl.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *.\n    admit.\n    simpl; intros; eapply CorrectDecoderinish.\n    (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    destruct prim_fst7 as [? [? [? [ ] ] ] ].\n    simpl in *.\n    try decompose_parsed_data.\n    reflexivity.\n    decide_data_invariant.\n    simpl; intros;\n      repeat (try rewrite !DecodeBindOpt2_assoc;\n              try rewrite !Bool.andb_true_r;\n              try rewrite !Bool.andb_true_l;\n              try rewrite !optimize_if_bind2;\n              try rewrite !optimize_if_bind2_bool).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite !DecodeBindOpt2_assoc.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Then_Else_Bind (cache := dns_list_cache)).\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    higher_order_reflexivity.\n    set_refine_evar.\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    unfold H; higher_order_reflexivity.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    (* collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus. *)\n    simpl.\n    higher_order_reflexivity.\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Definition packetDecoderImpl\n    := Eval simpl in (projT1 packet_decoder).\n\n  Arguments Guarded_Vector_split : simpl never.\n\n  Arguments addD : simpl never.\n\n  Arguments Core.append_word : simpl never.\n  Arguments Vector_split : simpl never.\n  Arguments NPeano.leb : simpl never.\n\n  Definition If_Opt_Then_Else_map\n             {A B B'} :\n    forall (f : option B -> B')\n           (a_opt : option A)\n           (t : A -> option B)\n           c,\n      f (Ifopt a_opt as a Then t a Else c) =\n      Ifopt a_opt as a Then f (t a) Else (f c).\n  Proof.\n    destruct a_opt as [ a' | ]; reflexivity.\n  Qed.\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n      Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Definition ByteAligned_packetDecoderImpl {A}\n             (f : _ -> A)\n             n\n    : {impl : _ & forall (v : Vector.t _ (12 + n)),\n           f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n           impl v (Some (wzero 17) , @nil (pointerT * string))%list}.\n  Proof.\n    eexists _; intros.\n    etransitivity.\n    set_refine_evar; simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    eapply optimize_under_if_opt; simpl; intros.\n    rewrite BindOpt_map_if.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    rewrite BindOpt_map_if; unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    (* rewrite !DecodeBindOpt2_assoc. *)\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite byte_align_decode_DomainName.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    destruct a7 as [ [? [ ? ?] ] ? ]; simpl.\n    (*rewrite DecodeBindOpt2_assoc. *)\n    etransitivity.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If NPeano.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (NPeano.leb n sz) eqn: ?.\n    - apply NPeano.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- NPeano.leb_le in H1; congruence.\n  Qed.\n\n    match goal with\n      |- ?b = _ =>\n      let b' := (eval pattern (build_aligned_ByteString t) in b) in\n      let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode x _ 4 b')\n    end.\n    { intros.\n      unfold decode_enum.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      destruct (Compare_dec.lt_dec x 2).\n      unfold Core.char in *.\n      pose proof (@decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2 p) as H';\n      unfold mult in H';  simpl in H'; rewrite H'; try reflexivity; auto.\n      destruct x as [ | [ | [ | ?] ] ]; try omega.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; reflexivity\n      end.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; simpl; try eauto\n      end.\n      repeat rewrite DecodeBindOpt2_assoc.\n      pose proof (fun x t => @decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2) as H';\n        simpl in H'; unfold mult in H; rewrite H'; try reflexivity; auto.\n      omega.\n    }\n    { intros; unfold decode_enum.\n      etransitivity.\n      set_refine_evar; repeat rewrite BindOpt_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      rewrite (AlignedDecode2Char (Guarded_Vector_split 4 x t)).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite (@If_Opt_Then_Else_DecodeBindOpt _ dns_list_cache); simpl.\n      rewrite If_Opt_Then_Else_map.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      erewrite optimize_align_decode_list.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      etransitivity.\n      eapply optimize_under_if_opt; simpl; intros.\n      rewrite BindOpt_map_if_bool.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      etransitivity.\n      set_refine_evar.\n      clear H0.\n      rewrite byte_align_decode_DomainName.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      subst_evars.\n      eapply optimize_under_if_opt; simpl; intros.\n      destruct a11 as [ [? [ ? ?] ] ? ]; simpl.\n      rewrite DecodeBindOpt2_assoc.\n      simpl.\n      etransitivity.\n      match goal with\n        |- ?b = _ =>\n        let b' := (eval pattern (build_aligned_ByteString t0) in b) in\n        let b' := match b' with ?f _ => f end in\n        eapply (@AlignedDecoders.optimize_Guarded_Decode x0 _ 8 b')\n      end.\n      { intros.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        etransitivity; set_refine_evar.\n        unfold DecodeBindOpt2, BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_refine_evar; eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        rewrite BindOpt_assoc.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        unfold BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        etransitivity.\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_evars.\n        eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        destruct x0 as [ | [| [ | [ | x0] ] ] ]; try omega.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n      }\n      intros; etransitivity.\n      simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt;rewrite (@AlignedDecode4Char dns_list_cache).\n      repeat (rewrite Vector_split_merge,\n              <- Eqdep_dec.eq_rect_eq_dec;\n              eauto using Peano_dec.eq_nat_dec ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      let types' := (eval unfold ResourceRecordTypeTypes in ResourceRecordTypeTypes)\n      in ilist_of_evar\n           (fun T : Type => forall n,\n                Vector.t (word 8) n\n                -> CacheDecode\n                -> option (T * {n : _ & Vector.t (word 8) n} * CacheDecode))\n           types'\n           ltac:(fun decoders' => rewrite (@align_decode_sumtype_OK dns_list_cache _ ResourceRecordTypeTypes decoders'));\n           [ | simpl; intros; repeat (apply Build_prim_and; intros); try exact I].\n      set_refine_evar.\n      rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n      simpl.\n      subst_refine_evar.\n      etransitivity.\n      subst_evars; higher_order_reflexivity.\n      subst_evars; higher_order_reflexivity.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (@decode_unused_word_aligned_ByteString_overflow dns_list_cache _ _ v1 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x=> @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          unfold DecodeBindOpt2 at 1; rewrite (@AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus _ _ 2).\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 := fun n1 v1 cd0 =>  If  NPeano.leb 2 n1\n                                                Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                                                (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                                                (addD cd0 16) as p1\n                                                                   Then let (p2, cd') := p1 in\n                                                                        let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                                    Else None;\n                                                                                               Some (proj, rest, env') Else None); simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        simpl.\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 6 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          simpl.\n          unfold DecodeBindOpt2 at 1;\n          pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          destruct n1 as [ | [ | [ | [ | n1] ] ] ] ; try omega;\n            try reflexivity.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache); simpl.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        repeat (rewrite Vector_split_merge,\n                <- Eqdep_dec.eq_rect_eq_dec;\n                eauto using Peano_dec.eq_nat_dec ).\n        unfold mult; simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0\n                       => If NPeano.leb 6 n1\n                             Then Let n2 := Core.append_word\n                                              (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                               Fin.FS (Fin.FS (Fin.FS Fin.F1))]\n                                              (Core.append_word\n                                                 (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                  Fin.FS (Fin.FS Fin.F1)]\n                                                 (Core.append_word\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                     Fin.FS Fin.F1]\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@Fin.F1])) in\n                           Some\n                             (n2, existT _ _ (snd (Vector_split (2 + 4) (n1 - 6) (Guarded_Vector_split 6 n1 v1))),\n                              addD (addD cd0 16) 32) Else None).\n        simpl; find_if_inside; simpl; eauto.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0 =>\n                         If  NPeano.leb 2 n1\n                             Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                             (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                             (addD cd0 16) as p1\n                                                Then let (p2, cd') := p1 in\n                                                     let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                 Else None;\n                                                                            Some (proj, rest, env') Else None).\n        simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      Arguments plus : simpl never.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1;pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a16 as [ [? [ ? ?] ] ? ]; simpl.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          etransitivity.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a16 as [ [? [ ? ?] ] ? ]; simpl.\n          etransitivity.\n          match goal with\n            |- ?b = _ =>\n            let b' := (eval pattern (build_aligned_ByteString t2) in b) in\n            let b' := match b' with ?f _ => f end in\n            eapply (@AlignedDecoders.optimize_Guarded_Decode x2 _ 20 b')\n          end.\n          { subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ]; try omega.\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n          }\n          { intros.\n            etransitivity.\n            unfold plus.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            unfold plus.\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            repeat (rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec ).\n            higher_order_reflexivity.\n            higher_order_reflexivity.\n          }\n          Opaque If_Opt_Then_Else.\n          Opaque If_Then_Else.\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          subst_evars; reflexivity.\n          Opaque Core.append_word.\n          Opaque Guarded_Vector_split.\n          Opaque Vector.tl.\n          simpl.\n\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          Transparent If_Opt_Then_Else.\n          Transparent If_Then_Else.\n          simpl.\n          subst_refine_evar; reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        fold (plus 20 (n1 - 20)).\n        fold (plus 16 (n1 - 16)).\n        fold (plus 12 (n1 - 12)).\n        fold (plus 8 (n1 - 8)).\n        fold (plus 4 (n1 - 4)).\n        match goal with\n          |- context [S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S ?n)))))))))))))))] => fold (plus 16 n)\n        end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd in b) in\n          let b' := match b' with ?f _ _ _ => f end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If (b' n v cd) Then (et n v cd) Else (zt n v cd)); cbv beta; simpl; find_if_inside; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd in a) in\n          let a' := match a' with ?f _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                                    (zt n v cd)\n                                                                                    (et n v cd));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd ?a'' as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd, a'' in a) in\n          let a' := match a' with ?f _ _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let AT'' := match type of a'' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd a'' => If_Opt_Then_Else (a' n v cd a'')\n                                                                                        (zt n v cd a'')\n                                                                                        (et n v cd a''));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd, q, q' in b) in\n          let b' := match b' with ?f _ _ _ _ _ => f end in\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd q q' => If (b' n v cd q q') Then (et n v cd q q') Else (zt n v cd q q')); cbv beta; simpl; find_if_inside; simpl)) end.\n        clear H H1.\n        Opaque LetIn.\n        match goal with\n          |- _ =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n          let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n          let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n          makeEvar (forall n, Vector.t (word 8) n ->\n                              CacheDecode -> QT -> QT' ->\n                              word 32 -> word 32 ->\n                              word 32 -> word 32 -> ZT1)\n                   ltac:(fun zt1 =>\n                           makeEvar (forall n, Vector.t (word 8) n ->\n                                               CacheDecode -> QT -> QT' ->\n                                               word 32 -> word 32 ->\n                                               word 32 -> word 32 -> ZT2)\n                                    ltac:(fun zt2 =>\n                                            makeEvar (forall n, Vector.t (word 8) n ->\n                                                                CacheDecode -> QT -> QT' ->\n                                                                word 32 -> word 32 ->\n                                                                word 32 -> word 32 -> ZT3)\n                                                     ltac:(fun zt3 =>\n                                                             makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                 CacheDecode -> QT -> QT' -> word 32)\n                                                                      ltac:(fun w1 =>\n                                                                              makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                  CacheDecode -> QT -> QT' -> word 32)\n                                                                                       ltac:(fun w2 =>\n                                                                                               makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                   CacheDecode -> QT -> QT' -> word 32)\n                                                                                                        ltac:(fun w3 => makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                                            CacheDecode -> QT -> QT' -> word 32)\n                                                                                                                                 ltac:(fun w4 =>\n                                                                                                                                         unify z (fun n v cd q q' => LetIn (w1 n v cd q q') (fun w => LetIn (w2 n v cd q q')  (fun w' => LetIn (w3  n v cd q q') (fun w'' => LetIn (w4 n v cd q q') (fun w''' => Some (zt1 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt2 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt3 n v cd q q' w w' w'' w'''\n                                                                                                                                                 )))))); simpl)))))))\n        end.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        repeat f_equal.\n        higher_order_reflexivity.\n        instantiate (1 := fun n1 v1 cd0 p1 p2 x1 x2 x3 x4 => existT _ _ _).\n        simpl; reflexivity.\n        higher_order_reflexivity.\n        instantiate (1 := fun _ _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n      }\n      subst_refine_evar; reflexivity.\n      subst_refine_evar; reflexivity.\n      higher_order_reflexivity.\n      match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n      higher_order_reflexivity.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd in a) in\n        let a' := match a' with ?f _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                 (zt n v cd)\n                                                                 (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n      match goal with\n        |- If ?b Then ?t Else ?e =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => If (b' n v cd q) Then (zt n v cd q) Else (@None ZT)); cbv beta; simpl; find_if_inside; simpl)\n      end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => LetIn (b' n v cd q) (zt n v cd q)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q' in a) in\n        let a' := match a' with ?f _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' => If_Opt_Then_Else (a' n v cd q q')\n                                                                      (zt n v cd q q')\n                                                                      (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'' in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' => LetIn (b' n v cd q q' q'') (zt n v cd q q' q'')))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q', q'', q''' in a) in\n        let a' := match a' with ?f _ _ _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' => If_Opt_Then_Else (a' n v cd q q' q'' q''')\n                                                                               (zt n v cd q q' q'' q''')\n                                                                               (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'', q''', r in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' r => LetIn (b' n v cd q q' q'' q''' r) (zt n v cd q q' q'' q''' r)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      Time match goal with\n             |- If_Opt_Then_Else ?a ?t ?e =\n                Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' as a Then _ Else _ =>\n             let a' := (eval pattern n, v, cd, q, q', q'', q''', r, r' in a) in\n             let a' := match a' with ?f _ _ _ _ _ _ _ _ _ => f end in\n             let AT := match type of a with option ?T => T end in\n             let QT := match type of q with ?T => T end in\n             let QT' := match type of q' with ?T => T end in\n             let QT'' := match type of q'' with ?T => T end in\n             let QT''' := match type of q''' with ?T => T end in\n             let RT := match type of r with ?T => T end in\n             let RT' := match type of r' with ?T => T end in\n             let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n             makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> RT' -> AT -> option ZT)\n                      ltac:(fun zt =>\n                              unify z (fun n v cd q q' q'' q''' r r'=> If_Opt_Then_Else (a' n v cd q q' q'' q''' r r')\n                                                                                        (zt n v cd q q' q'' q''' r r')\n                                                                                        (@None ZT));\n                                cbv beta; simpl; destruct a; simpl) end.\n      (* This unification takes four minutes :p*)\n\n      match goal with\n        |- _ =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' ?r'' as a Then _ Else _ =>\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let RT' := match type of r' with ?T => T end in\n        let RT'' := match type of r'' with ?T => T end in\n        let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n        let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n        let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n        makeEvar (forall n, Vector.t (word 8) n ->\n                            CacheDecode -> QT -> QT' ->\n                            QT'' -> QT''' -> RT -> RT' -> RT''\n                            -> ZT1)\n                 ltac:(fun zt1 =>\n                         makeEvar (forall n, Vector.t (word 8) n ->\n                                             CacheDecode -> QT -> QT' ->\n                                             QT'' -> QT''' -> RT -> RT' -> RT''\n                                             -> ZT2)\n                                  ltac:(fun zt2 =>\n                                          makeEvar (forall n, Vector.t (word 8) n ->\n                                                              CacheDecode -> QT -> QT' ->\n                                                              QT'' -> QT''' -> RT -> RT' -> RT''\n                                                              -> ZT3)\n                                                   ltac:(fun zt3 => unify z (fun n v cd q q' q'' q''' r r' r'' =>\n                                                                               Some (zt1 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt2 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt3 n v cd q q' q'' q''' r r' r''));\n                                                                    simpl))) end.\n      repeat f_equal; try higher_order_reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; higher_order_reflexivity.\n    }\n    { match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n    }\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    simpl.\n    higher_order_reflexivity.\n    Time Defined.\n\n  Check ByteAligned_packetDecoderImpl.\n  Definition ByteAligned_packetDecoderImpl' {A} (k : _ -> A) n :=\n    Eval simpl in (projT1 (ByteAligned_packetDecoderImpl k n)).\n\n  Lemma ByteAligned_packetDecoderImpl'_OK {A}\n    : forall (f : _ -> A) n (v : Vector.t _ (12 + n)),\n        f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n        ByteAligned_packetDecoderImpl' f n v (Some (wzero 17) , @nil (pointerT * string))%list.\n  Proof.\n    intros.\n    pose proof (projT2 (ByteAligned_packetDecoderImpl f n));\n      cbv beta in H.\n    rewrite H.\n    set (H' := (Some (wzero 17), @nil (pointerT * string))).\n    simpl.\n    unfold ByteAligned_packetDecoderImpl'.\n    reflexivity.\n  Qed.\n\nEnd DnsPacket.\n\n(*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.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.StringFacts\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedSumType\n        Fiat.Narcissus.BinLib.AlignedDomainName\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.Compose\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.SimpleDNSPacket\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.HintDbExtra\n        Fiat.Common.Tactics.TransparentAbstract\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Stores.DomainNameStore\n        Fiat.Narcissus.Automation.CacheEncoders.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  Local Open Scope Tuple_scope.\n  Import Vectors.Vector.VectorNotations.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n  Arguments NPeano.div : simpl never.\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (As := ResourceRecordTypeTypes)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n      (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))\n      (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n      (SumType_proj ResourceRecordTypeTypes rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                            (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    intros ? H; apply H.\n  Qed.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Definition DNS_Packet_OK (data : packet) :=\n    lt (|data!\"answers\" |) (pow2 16)\n    /\\ lt (|data!\"authority\" |) (pow2 16)\n    /\\ lt (|data!\"additional\" |) (pow2 16)\n    /\\ ValidDomainName (data!\"question\")!\"qname\"\n    /\\ forall (rr : resourceRecord),\n        In rr (data!\"answers\" ++ data!\"additional\" ++ data!\"authority\")\n        -> resourceRecord_OK rr.\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n  Definition format_SOA_RDATA (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_A (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata r!sRDATA\n                           DoneC.\n\n  Definition format_packet (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Arguments split1 : simpl never.\n  Arguments split2 : simpl never.\n  Arguments fin_eq_dec m !n !n' /.\n  Arguments addE : simpl never.\n\n  Arguments Vector.nth A !m !v' !p /.\n\n  Definition format_rdata' :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource' (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           DoneC.\n\n  Definition format_packet' (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource' (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Definition refine_format_CNAME\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p,\n                  ValidDomainName p\n                  -> refine (format_CNAME p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_CNAME.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n    eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_A\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               refine (format_A p list_CacheFormat_empty)\n                                      (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_A.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    simpl.\n    encoder_reflexivity.\n  Defined.\n  Unset Printing Notations.\n\n  Eval compute in (natToWord 8 128).\n\n  Definition refine_format_NS\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               ValidDomainName p\n                               -> refine (format_NS p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_NS.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_SOA\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall a : SOA_RDATA,\n                               ValidDomainName a!\"contact_email\"\n                               -> ValidDomainName a!\"sourcehost\"\n                               -> refine (format_SOA_RDATA a list_CacheFormat_empty)\n                                         (ret (@build_aligned_ByteString (numBytes a) (v a), c a)) } } }.\n  Proof.\n    unfold format_SOA_RDATA.\n    eexists _, _, _; intros.\n    pose_string_hyps.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_resource\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p\n                             (p_OK : resourceRecord_OK p)\n                             ce,\n            refine (format_resource p ce)\n                   (ret (@build_aligned_ByteString (numBytes p ce) (v p ce), c p ce)) } } }.\n  Proof.\n    unfold format_resource; eexists _, _, _; intros.\n    etransitivity.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply (AlignedFormatSumTypeDoneC); repeat build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME;\n      build_prim_prod_evar;\n      build_prim_prod_evar; simpl;\n      etransitivity;\n      [apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus;\n       eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption\n       | encoder_reflexivity].\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      unfold SumType_proj in H; simpl in H.\n      revert H; instantiate (1 := fun t => _ t /\\ _ t); intros [? ?].\n      pattern t; apply H.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      pattern t; apply (proj2 H).\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { apply p_OK. }\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    eapply (projT2 (projT2 (projT2 refine_format_resource))); eauto.\n    apply p_OK; assumption.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).\nSet Printing Notations.\nPrint encode_packet.\n\n(*  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    unfold format_resource; intros.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply H.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply AlignedFormatSumTypeDoneC; repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME.\n      build_prim_prod_evar.\n      build_prim_prod_evar; simpl.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n      eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n      encoder_reflexivity.\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold resourceRecord_OK in H.\n      eapply H.\n    }\n    apply p_OK; apply H.\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).v *)\n\nLemma refine_format_packet_Impl_OK\n  : forall p (p_OK : DNS_Packet_OK p),\n    refine (format_packet p list_CacheFormat_empty)\n           (ret (encode_packet p)).\nProof.\n  intros; apply (projT2 (projT2 (projT2 refine_format_packet))); eauto.\nQed.\n\n  Definition ByteAlignedCorrectDecoderFor {A} {cache : Cache}\n             Invariant FormatSpec :=\n    { decodePlusCacheInv |\n      exists P_inv,\n      (cache_inv_Property (snd decodePlusCacheInv) P_inv\n       -> CorrectDecoder (A := A) monoid Invariant (fun _ _ => True)\n                                  FormatSpec\n                                  (fst decodePlusCacheInv)\n                                  (snd decodePlusCacheInv))\n      /\\ cache_inv_Property (snd decodePlusCacheInv) P_inv}.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments weq : simpl never.\n  Arguments word_indexed : simpl never.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct\n                IndependentCaches IndependentCaches' IndependentCaches'''\n                getDistinct getDistinct' addPeekSome\n                boundPeekSome addPeekNone addPeekNone'\n                addZeroPeek addPeekESome boundPeekESome\n                addPeekENone addPeekENone')\n    | |- appcontext [CorrectDecoder _ _ _ (format_list format_resource) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Ltac synthesize_decoder_ext\n       monoid\n       decode_step'\n       determineHooks\n       synthesize_cache_invariant' :=\n    (* Combines tactics into one-liner. *)\n    start_synthesizing_decoder;\n    [ normalize_compose monoid;\n      repeat first [decode_step' idtac | decode_step determineHooks]\n    | cbv beta; synthesize_cache_invariant' idtac\n    |  ].\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n    decode_DNS_rules idtac\n    unfold resourceRecord_OK.\n    clear; intros.\n    split.\n    apply (Logic.proj1 H).\n    admit.\n\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    (*destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *. *)\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n    simpl.\n    instantiate (1 := true).  admit.\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *.\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n\n    simpl; intros;\n      repeat (try rewrite !DecodeBindOpt2_assoc;\n              try rewrite !Bool.andb_true_r;\n              try rewrite !Bool.andb_true_l;\n              try rewrite !optimize_if_bind2;\n              try rewrite !optimize_if_bind2_bool).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite !DecodeBindOpt2_assoc.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Then_Else_Bind (cache := dns_list_cache)).\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    higher_order_reflexivity.\n    set_refine_evar.\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    unfold H; higher_order_reflexivity.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    (* collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus. *)\n    simpl.\n    higher_order_reflexivity.\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Definition packetDecoderImpl\n    := Eval simpl in (projT1 packet_decoder).\n\n  (*Arguments Guarded_Vector_split : simpl never.\n\n  Arguments addD : simpl never.\n\n  Arguments Core.append_word : simpl never.\n  Arguments Vector_split : simpl never.\n  Arguments NPeano.leb : simpl never.\n\n  Definition If_Opt_Then_Else_map\n             {A B B'} :\n    forall (f : option B -> B')\n           (a_opt : option A)\n           (t : A -> option B)\n           c,\n      f (Ifopt a_opt as a Then t a Else c) =\n      Ifopt a_opt as a Then f (t a) Else (f c).\n  Proof.\n    destruct a_opt as [ a' | ]; reflexivity.\n  Qed.\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n      Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Definition ByteAligned_packetDecoderImpl {A}\n             (f : _ -> A)\n             n\n    : {impl : _ & forall (v : Vector.t _ (12 + n)),\n           f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n           impl v (Some (wzero 17) , @nil (pointerT * string))%list}.\n  Proof.\n    eexists _; intros.\n    etransitivity.\n    set_refine_evar; simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    eapply optimize_under_if_opt; simpl; intros.\n    rewrite BindOpt_map_if.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    rewrite BindOpt_map_if; unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    (* rewrite !DecodeBindOpt2_assoc. *)\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite byte_align_decode_DomainName.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    destruct a8 as [ [? [ ? ?] ] ? ]; simpl.\n    (*rewrite DecodeBindOpt2_assoc. *)\n    etransitivity.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If NPeano.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (NPeano.leb n sz) eqn: ?.\n    - apply NPeano.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- NPeano.leb_le in H1; congruence.\n  Qed.\n\n    match goal with\n      |- ?b = _ =>\n      let b' := (eval pattern (build_aligned_ByteString t) in b) in\n      let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode x _ 4 b')\n    end.\n    { intros.\n      unfold decode_enum.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      destruct (Compare_dec.lt_dec x 2).\n      unfold Core.char in *.\n      pose proof (@decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2 p) as H';\n      unfold mult in H';  simpl in H'; rewrite H'; try reflexivity; auto.\n      destruct x as [ | [ | [ | ?] ] ]; try omega.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; reflexivity\n      end.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; simpl; try eauto\n      end.\n      repeat rewrite DecodeBindOpt2_assoc.\n      pose proof (fun x t => @decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2) as H';\n        simpl in H'; unfold mult in H; rewrite H'; try reflexivity; auto.\n      omega.\n    }\n    { intros; unfold decode_enum.\n      etransitivity.\n      set_refine_evar; repeat rewrite BindOpt_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      rewrite (AlignedDecode2Char (Guarded_Vector_split 4 x t)).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite (@If_Opt_Then_Else_DecodeBindOpt _ dns_list_cache); simpl.\n      rewrite If_Opt_Then_Else_map.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      erewrite optimize_align_decode_list.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      etransitivity.\n      eapply optimize_under_if_opt; simpl; intros.\n      rewrite BindOpt_map_if_bool.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      etransitivity.\n      set_refine_evar.\n      clear H0.\n      rewrite byte_align_decode_DomainName.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      subst_evars.\n      eapply optimize_under_if_opt; simpl; intros.\n      destruct a12 as [ [? [ ? ?] ] ? ]; simpl.\n      rewrite DecodeBindOpt2_assoc.\n      simpl.\n      etransitivity.\n      match goal with\n        |- ?b = _ =>\n        let b' := (eval pattern (build_aligned_ByteString t0) in b) in\n        let b' := match b' with ?f _ => f end in\n        eapply (@AlignedDecoders.optimize_Guarded_Decode x0 _ 8 b')\n      end.\n      { intros.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        etransitivity; set_refine_evar.\n        unfold DecodeBindOpt2, BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_refine_evar; eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        rewrite BindOpt_assoc.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        unfold BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        etransitivity.\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_evars.\n        eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        destruct x0 as [ | [| [ | [ | x0] ] ] ]; try omega.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n      }\n      intros; etransitivity.\n      simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt;rewrite (@AlignedDecode4Char dns_list_cache).\n      repeat (rewrite Vector_split_merge,\n              <- Eqdep_dec.eq_rect_eq_dec;\n              eauto using Peano_dec.eq_nat_dec ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      let types' := (eval unfold ResourceRecordTypeTypes in ResourceRecordTypeTypes)\n      in ilist_of_evar\n           (fun T : Type => forall n,\n                Vector.t (word 8) n\n                -> CacheDecode\n                -> option (T * {n : _ & Vector.t (word 8) n} * CacheDecode))\n           types'\n           ltac:(fun decoders' => rewrite (@align_decode_sumtype_OK dns_list_cache _ ResourceRecordTypeTypes decoders'));\n           [ | simpl; intros; repeat (apply Build_prim_and; intros); try exact I].\n      set_refine_evar.\n      rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n      simpl.\n      subst_refine_evar.\n      etransitivity.\n      subst_evars; higher_order_reflexivity.\n      subst_evars; higher_order_reflexivity.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (@decode_unused_word_aligned_ByteString_overflow dns_list_cache _ _ v1 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x=> @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          unfold DecodeBindOpt2 at 1; rewrite (@AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus _ _ 2).\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 := fun n1 v1 cd0 =>  If  NPeano.leb 2 n1\n                                                Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                                                (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                                                (addD cd0 16) as p1\n                                                                   Then let (p2, cd') := p1 in\n                                                                        let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                                    Else None;\n                                                                                               Some (proj, rest, env') Else None); simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        simpl.\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 6 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          simpl.\n          unfold DecodeBindOpt2 at 1;\n          pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          destruct n1 as [ | [ | [ | [ | n1] ] ] ] ; try omega;\n            try reflexivity.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache); simpl.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        repeat (rewrite Vector_split_merge,\n                <- Eqdep_dec.eq_rect_eq_dec;\n                eauto using Peano_dec.eq_nat_dec ).\n        unfold mult; simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0\n                       => If NPeano.leb 6 n1\n                             Then Let n2 := Core.append_word\n                                              (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                               Fin.FS (Fin.FS (Fin.FS Fin.F1))]\n                                              (Core.append_word\n                                                 (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                  Fin.FS (Fin.FS Fin.F1)]\n                                                 (Core.append_word\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                     Fin.FS Fin.F1]\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@Fin.F1])) in\n                           Some\n                             (n2, existT _ _ (snd (Vector_split (2 + 4) (n1 - 6) (Guarded_Vector_split 6 n1 v1))),\n                              addD (addD cd0 16) 32) Else None).\n        simpl; find_if_inside; simpl; eauto.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0 =>\n                         If  NPeano.leb 2 n1\n                             Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                             (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                             (addD cd0 16) as p1\n                                                Then let (p2, cd') := p1 in\n                                                     let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                 Else None;\n                                                                            Some (proj, rest, env') Else None).\n        simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      Arguments plus : simpl never.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1;pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          etransitivity.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          etransitivity.\n          match goal with\n            |- ?b = _ =>\n            let b' := (eval pattern (build_aligned_ByteString t2) in b) in\n            let b' := match b' with ?f _ => f end in\n            eapply (@AlignedDecoders.optimize_Guarded_Decode x2 _ 20 b')\n          end.\n          { subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ]; try omega.\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n          }\n          { intros.\n            etransitivity.\n            unfold plus.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            unfold plus.\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            repeat (rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec ).\n            higher_order_reflexivity.\n            higher_order_reflexivity.\n          }\n          Opaque If_Opt_Then_Else.\n          Opaque If_Then_Else.\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          subst_evars; reflexivity.\n          Opaque Core.append_word.\n          Opaque Guarded_Vector_split.\n          Opaque Vector.tl.\n          simpl.\n\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          Transparent If_Opt_Then_Else.\n          Transparent If_Then_Else.\n          simpl.\n          subst_refine_evar; reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        fold (plus 20 (n1 - 20)).\n        fold (plus 16 (n1 - 16)).\n        fold (plus 12 (n1 - 12)).\n        fold (plus 8 (n1 - 8)).\n        fold (plus 4 (n1 - 4)).\n        match goal with\n          |- context [S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S ?n)))))))))))))))] => fold (plus 16 n)\n        end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd in b) in\n          let b' := match b' with ?f _ _ _ => f end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If (b' n v cd) Then (et n v cd) Else (zt n v cd)); cbv beta; simpl; find_if_inside; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd in a) in\n          let a' := match a' with ?f _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                                    (zt n v cd)\n                                                                                    (et n v cd));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd ?a'' as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd, a'' in a) in\n          let a' := match a' with ?f _ _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let AT'' := match type of a'' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd a'' => If_Opt_Then_Else (a' n v cd a'')\n                                                                                        (zt n v cd a'')\n                                                                                        (et n v cd a''));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd, q, q' in b) in\n          let b' := match b' with ?f _ _ _ _ _ => f end in\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd q q' => If (b' n v cd q q') Then (et n v cd q q') Else (zt n v cd q q')); cbv beta; simpl; find_if_inside; simpl)) end.\n        clear H H1.\n        Opaque LetIn.\n        match goal with\n          |- _ =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n          let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n          let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n          makeEvar (forall n, Vector.t (word 8) n ->\n                              CacheDecode -> QT -> QT' ->\n                              word 32 -> word 32 ->\n                              word 32 -> word 32 -> ZT1)\n                   ltac:(fun zt1 =>\n                           makeEvar (forall n, Vector.t (word 8) n ->\n                                               CacheDecode -> QT -> QT' ->\n                                               word 32 -> word 32 ->\n                                               word 32 -> word 32 -> ZT2)\n                                    ltac:(fun zt2 =>\n                                            makeEvar (forall n, Vector.t (word 8) n ->\n                                                                CacheDecode -> QT -> QT' ->\n                                                                word 32 -> word 32 ->\n                                                                word 32 -> word 32 -> ZT3)\n                                                     ltac:(fun zt3 =>\n                                                             makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                 CacheDecode -> QT -> QT' -> word 32)\n                                                                      ltac:(fun w1 =>\n                                                                              makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                  CacheDecode -> QT -> QT' -> word 32)\n                                                                                       ltac:(fun w2 =>\n                                                                                               makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                   CacheDecode -> QT -> QT' -> word 32)\n                                                                                                        ltac:(fun w3 => makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                                            CacheDecode -> QT -> QT' -> word 32)\n                                                                                                                                 ltac:(fun w4 =>\n                                                                                                                                         unify z (fun n v cd q q' => LetIn (w1 n v cd q q') (fun w => LetIn (w2 n v cd q q')  (fun w' => LetIn (w3  n v cd q q') (fun w'' => LetIn (w4 n v cd q q') (fun w''' => Some (zt1 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt2 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt3 n v cd q q' w w' w'' w'''\n                                                                                                                                                 )))))); simpl)))))))\n        end.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        repeat f_equal.\n        higher_order_reflexivity.\n        instantiate (1 := fun n1 v1 cd0 p1 p2 x1 x2 x3 x4 => existT _ _ _).\n        simpl; reflexivity.\n        higher_order_reflexivity.\n        instantiate (1 := fun _ _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n      }\n      subst_refine_evar; reflexivity.\n      subst_refine_evar; reflexivity.\n      higher_order_reflexivity.\n      match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n      higher_order_reflexivity.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd in a) in\n        let a' := match a' with ?f _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                 (zt n v cd)\n                                                                 (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n      match goal with\n        |- If ?b Then ?t Else ?e =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => If (b' n v cd q) Then (zt n v cd q) Else (@None ZT)); cbv beta; simpl; find_if_inside; simpl)\n      end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => LetIn (b' n v cd q) (zt n v cd q)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q' in a) in\n        let a' := match a' with ?f _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' => If_Opt_Then_Else (a' n v cd q q')\n                                                                      (zt n v cd q q')\n                                                                      (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'' in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' => LetIn (b' n v cd q q' q'') (zt n v cd q q' q'')))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q', q'', q''' in a) in\n        let a' := match a' with ?f _ _ _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' => If_Opt_Then_Else (a' n v cd q q' q'' q''')\n                                                                               (zt n v cd q q' q'' q''')\n                                                                               (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'', q''', r in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' r => LetIn (b' n v cd q q' q'' q''' r) (zt n v cd q q' q'' q''' r)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      Time match goal with\n             |- If_Opt_Then_Else ?a ?t ?e =\n                Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' as a Then _ Else _ =>\n             let a' := (eval pattern n, v, cd, q, q', q'', q''', r, r' in a) in\n             let a' := match a' with ?f _ _ _ _ _ _ _ _ _ => f end in\n             let AT := match type of a with option ?T => T end in\n             let QT := match type of q with ?T => T end in\n             let QT' := match type of q' with ?T => T end in\n             let QT'' := match type of q'' with ?T => T end in\n             let QT''' := match type of q''' with ?T => T end in\n             let RT := match type of r with ?T => T end in\n             let RT' := match type of r' with ?T => T end in\n             let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n             makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> RT' -> AT -> option ZT)\n                      ltac:(fun zt =>\n                              unify z (fun n v cd q q' q'' q''' r r'=> If_Opt_Then_Else (a' n v cd q q' q'' q''' r r')\n                                                                                        (zt n v cd q q' q'' q''' r r')\n                                                                                        (@None ZT));\n                                cbv beta; simpl; destruct a; simpl) end.\n      (* This unification takes four minutes :p*)\n\n      match goal with\n        |- _ =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' ?r'' as a Then _ Else _ =>\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let RT' := match type of r' with ?T => T end in\n        let RT'' := match type of r'' with ?T => T end in\n        let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n        let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n        let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n        makeEvar (forall n, Vector.t (word 8) n ->\n                            CacheDecode -> QT -> QT' ->\n                            QT'' -> QT''' -> RT -> RT' -> RT''\n                            -> ZT1)\n                 ltac:(fun zt1 =>\n                         makeEvar (forall n, Vector.t (word 8) n ->\n                                             CacheDecode -> QT -> QT' ->\n                                             QT'' -> QT''' -> RT -> RT' -> RT''\n                                             -> ZT2)\n                                  ltac:(fun zt2 =>\n                                          makeEvar (forall n, Vector.t (word 8) n ->\n                                                              CacheDecode -> QT -> QT' ->\n                                                              QT'' -> QT''' -> RT -> RT' -> RT''\n                                                              -> ZT3)\n                                                   ltac:(fun zt3 => unify z (fun n v cd q q' q'' q''' r r' r'' =>\n                                                                               Some (zt1 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt2 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt3 n v cd q q' q'' q''' r r' r''));\n                                                                    simpl))) end.\n      repeat f_equal; try higher_order_reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; higher_order_reflexivity.\n    }\n    { match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n    }\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    simpl.\n    higher_order_reflexivity.\n    Time Defined.\n\n  Check ByteAligned_packetDecoderImpl.\n  Definition ByteAligned_packetDecoderImpl' {A} (k : _ -> A) n :=\n    Eval simpl in (projT1 (ByteAligned_packetDecoderImpl k n)).\n\n  Lemma ByteAligned_packetDecoderImpl'_OK {A}\n    : forall (f : _ -> A) n (v : Vector.t _ (12 + n)),\n        f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n        ByteAligned_packetDecoderImpl' f n v (Some (wzero 17) , @nil (pointerT * string))%list.\n  Proof.\n    intros.\n    pose proof (projT2 (ByteAligned_packetDecoderImpl f n));\n      cbv beta in H.\n    rewrite H.\n    set (H' := (Some (wzero 17), @nil (pointerT * string))).\n    simpl.\n    unfold ByteAligned_packetDecoderImpl'.\n    reflexivity.\n  Qed.\n\nEnd DnsPacket.\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/Narcissus/Examples/DNS/SimpleDnsOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.1594785927301899}}
{"text": "(* Extending the block model to concurrency. *)\nRequire Import Coqlib.\nRequire Import Util.\nRequire Import Arith.\nRequire Import block_model.\nImport ListNotations.\nImport Bool.\nImport EquivDec.\nImport CoqEqDec.\n\nLocal Close Scope Z.\n\nSet Implicit Arguments.\n\nSection Concurrency.\n  Context `(ML : Memory_Layout) {thread : Type}.\n\n  Definition seq_con := @block_model.consistent _ _ _ ML.\n  Definition mem_op := mem_op block val.\n\n  Class MM_base (conc_op : Type) :=\n    { thread_of : conc_op -> thread;\n      to_seq : conc_op -> list mem_op;\n      lower := fun m => flatten (map to_seq m);\n      synchronizes_with : conc_op -> conc_op -> Prop;\n      drop_b_reads : block -> list conc_op -> list conc_op;\n      drop_b_reads_spec : forall b ops, lower (drop_b_reads b ops) =\n       filter (fun op => not_read op || negb (beq (block_of op) b)) (lower ops);\n      read_safe : forall c i p v\n        (Hread : nth_error (to_seq c) i = Some (MRead p v)) j (Hlt : j < i) v',\n        nth_error (to_seq c) j <> Some (MWrite p v') }.\n\n  Context `{Mb : MM_base}.\n\n  Definition mem := ilist conc_op.\n\n  Section Happens_Before.\n\n  Inductive happens_before (m : mem) i j : Prop :=\n  | hb_prog (Hlt : i < j) a (Ha : inth m i = Some a) b (Hb : inth m j = Some b)\n      (Hthread : thread_of a = thread_of b) : happens_before m i j\n  | hb_sync (Hlt : i < j) a (Ha : inth m i = Some a) b (Hb : inth m j = Some b)\n      (Hsync : synchronizes_with a b) : happens_before m i j\n  | hb_trans k (Hi : happens_before m i k) (Hj : happens_before m k j) :\n      happens_before m i j.\n\n  Lemma hb_lt : forall m i j, happens_before m i j -> i < j.\n  Proof. intros; induction H; clarify; abstract omega. Qed.\n  Corollary hb_irrefl : forall m i, ~happens_before m i i.\n  Proof. repeat intro; exploit hb_lt; eauto; abstract omega. Qed.\n  Corollary hb_antisym : forall m i j, happens_before m i j ->\n    ~happens_before m j i.\n  Proof. intros ? ? ? H1 H2; generalize (hb_lt H1), (hb_lt H2); abstract omega. \n  Qed.\n\n  Lemma hb_app : forall m1 m2 i j m2' (Hhb : happens_before (iapp m1 m2) i j)\n    (Hi : i < length m1) (Hj : j < length m1), happens_before (iapp m1 m2') i j.\n  Proof.\n    intros; induction Hhb.\n    - eapply hb_prog; eauto; rewrite iapp_nth in *; clarify.\n    - eapply hb_sync; eauto; rewrite iapp_nth in *; clarify.\n    - generalize (hb_lt Hhb2); intro.\n      generalize (lt_trans _ _ _ H Hj); clarify.\n      eapply hb_trans; eauto.\n  Qed.\n  \n  Corollary hb_app_impl : forall m1 m2 i j\n    (Hhb : happens_before (iapp m1 m2) i j)\n    (Hi : i < length m1) (Hj : j < length m1), happens_before m1 i j.\n  Proof.\n    intros; exploit hb_app; eauto.\n    rewrite iapp_nil_ilist; auto.\n  Qed.\n\n  Lemma hb_app' : forall m1 m2 i j m1' (Hhb : happens_before (iapp m1 m2) i j)\n    (Hi : ~i < length m1) (Hj : ~j < length m1),\n    happens_before (iapp m1' m2)\n      (i - length m1 + length m1') (j - length m1 + length m1').\n  Proof.\n    intros; induction Hhb.\n    - rewrite iapp_nth in *; clarify.\n      eapply hb_prog; eauto; try rewrite iapp_nth.\n      + abstract omega.\n      + destruct (lt_dec (i - length m1 + length m1') (length m1'));\n          [abstract omega|].\n        rewrite NPeano.Nat.add_sub; auto.\n      + destruct (lt_dec (j - length m1 + length m1') (length m1'));\n          [abstract omega|].\n        rewrite NPeano.Nat.add_sub; auto.\n    - rewrite iapp_nth in *; clarify.\n      eapply hb_sync; eauto; try rewrite iapp_nth.\n      + abstract omega.\n      + destruct (lt_dec (i - length m1 + length m1') (length m1'));\n          [abstract omega|].\n        rewrite NPeano.Nat.add_sub; auto.\n      + destruct (lt_dec (j - length m1 + length m1') (length m1'));\n          [abstract omega|].\n        rewrite NPeano.Nat.add_sub; auto.\n    - generalize (hb_lt Hhb1); intro.\n      destruct (lt_dec k (length m1)); [abstract omega | clarify].\n      eapply hb_trans; eauto.\n  Qed.\n\n  Corollary hb_app'_eq : forall m1 m2 i j m1' (Hlen : length m1' = length m1)\n    (Hhb : happens_before (iapp m1 m2) i j) (Hi : ~ i < length m1)\n    (Hj : ~ j < length m1), happens_before (iapp m1' m2) i j.\n  Proof.\n    intros; generalize (hb_app' _ _ m1' Hhb); clarify.\n    rewrite Hlen, NPeano.Nat.sub_add, NPeano.Nat.sub_add in *; auto; omega.\n  Qed.\n\n  Definition hbe m i j := happens_before m i j \\/ i = j.\n\n  Lemma hbe_app : forall m1 m2 i j m2' (Hhb : hbe (iapp m1 m2) i j)\n    (Hi : i < length m1) (Hj : j < length m1), hbe (iapp m1 m2') i j.\n  Proof. unfold hbe; clarify; left; eapply hb_app; eauto. Qed.\n  \n  Lemma hbe_app' : forall m1 m2 i j m1' (Hhbe : hbe (iapp m1 m2) i j)\n    (Hi : ~i < length m1) (Hj : ~j < length m1),\n    hbe (iapp m1' m2) (i - length m1 + length m1')\n                      (j - length m1 + length m1').\n  Proof.\n    unfold hbe; clarify.\n    left; apply hb_app'; auto.\n  Qed.\n\n  Lemma hb_next : forall m i j, happens_before m i j ->\n    exists a, inth m i = Some a /\\ exists k b, i < k /\\ inth m k = Some b /\\\n      (thread_of a = thread_of b \\/ synchronizes_with a b) /\\ hbe m k j.\n  Proof.\n    unfold hbe; intros; induction H; clarify.\n    - repeat eexists; eauto.\n    - repeat eexists; eauto.\n    - eexists; split; eauto.\n      exists x3; repeat eexists; eauto.\n      destruct IHhappens_before12222, IHhappens_before22222; clarify;\n        left; eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hb_prev : forall m i j, happens_before m i j ->\n    exists b, inth m j = Some b /\\ exists k a, k < j /\\ inth m k = Some a /\\\n      (thread_of a = thread_of b \\/ synchronizes_with a b) /\\ hbe m i k.\n  Proof.\n    unfold hbe; intros; induction H; clarify.\n    - repeat eexists; eauto.\n    - repeat eexists; eauto.\n    - eexists; split; eauto.\n      exists x1; repeat eexists; eauto.\n      destruct IHhappens_before22222; clarify.\n      left; eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hbe_trans : forall m i j k (Hhbe1 : hbe m i j) (Hhbe2 : hbe m j k),\n    hbe m i k.\n  Proof.\n    unfold hbe; clarify.\n    left; eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hb_inv : forall m i j, happens_before m i j ->\n    exists a b, inth m i = Some a /\\ inth m j = Some b /\\\n      ((thread_of a = thread_of b) \\/ synchronizes_with a b \\/\n      exists k c, inth m k = Some c /\\ (*~not_sync c /\\*)\n                  happens_before m i k /\\ happens_before m k j).\n  Proof.\n    intros; induction H; clarsimp; repeat eexists; eauto.\n    destruct IHhappens_before122 as [? | [? | ?]]; clarify.\n    - destruct IHhappens_before222 as [? | [? | ?]]; clarify.\n      + clarsimp.\n      + right; right; exists k; repeat eexists; eauto.\n(*        intro Hsync; generalize (no_sync _ Hsync x0); clarify.*)\n      + right; right; exists x2; repeat eexists; eauto.\n        eapply hb_trans; eauto.\n    - destruct IHhappens_before222 as [? | [? | ?]]; clarify.\n      + right; right; exists k; repeat eexists; eauto.\n(*        intro Hsync; generalize (no_sync _ Hsync x1); clarify.*)\n      + right; right; exists k; repeat eexists; eauto.\n(*        intro Hsync; generalize (no_sync _ Hsync x1); clarify.*)\n      + right; right; exists x2; repeat eexists; eauto.\n        eapply hb_trans; eauto.\n    - right; right; exists x2; repeat eexists; eauto.\n      eapply hb_trans; eauto.\n  Qed.\n\n  Lemma seq_hb : forall ops t (Ht : Forall (fun c => thread_of c = t) ops)\n    m1 m2 i j (Hlt : length m1 <= i < j) (Hlen : j < length m1 + length ops),\n    happens_before (iapp m1 (iapp ops m2)) i j.\n  Proof.\n    intros.\n    assert (j - length m1 < length ops) by abstract omega.\n    exploit nth_error_succeeds; eauto; intros [b Hj]; clarify.\n    assert (i - length m1 < length ops) by abstract omega.\n    exploit nth_error_succeeds; eauto; intros [a Hi].\n    generalize (nth_error_in _ _ Hi), (nth_error_in _ _ Hj); intros Ha Hb.\n    rewrite Forall_forall in Ht; generalize (Ht _ Ha); specialize (Ht _ Hb);\n      clarify.\n    eapply hb_prog; eauto; rewrite iapp_inter; clarify; abstract omega.\n  Qed.\n\n  Corollary seq_hb_iff : forall ops t\n    (Ht : Forall (fun c => thread_of c = t) ops) m1 m2 i j\n    (Hlt : length m1 <= i < j) (Hlen : j < length m1 + length ops),\n    happens_before (iapp m1 (iapp ops m2)) i j <-> i < j.\n  Proof. intros; split; intro; [eapply hb_lt | eapply seq_hb]; eauto. Qed.    \n\n  Corollary seq_hbe : forall ops t (Ht : Forall (fun c => thread_of c = t) ops)\n    m1 m2 i j (Hlt : length m1 <= i <= j) (Hlen : j < length m1 + length ops),\n    hbe (iapp m1 (iapp ops m2)) i j.\n  Proof.\n    intros; unfold hbe; destruct (eq_dec i j); auto.\n    left; eapply seq_hb; eauto; omega.\n  Qed.\n\n  Definition adjust_range {A} (l1 l l' : list A) i :=\n    if lt_dec i (length l1) then i else i - length l + length l'.\n\n  Lemma adjust_range_nth : forall {A} i (m1 ops : list A) m2 ops'\n    (Hrange : i < length m1 \\/ i >= length m1 + length ops),\n    inth (iapp m1 (iapp ops' m2)) (adjust_range m1 ops ops' i) =\n    inth (iapp m1 (iapp ops m2)) i.\n  Proof.\n    intros; repeat rewrite iapp_nth.\n    unfold adjust_range; destruct (lt_dec i (length m1)); clarify.\n    destruct (lt_dec (i - length m1) (length ops)); [abstract omega|].\n    destruct (lt_dec (i - length ops + length ops') (length m1));\n      [abstract omega|].\n    destruct (lt_dec (i - length ops + length ops' - length m1) (length ops'));\n      [abstract omega|].\n    assert (i - length ops + length ops' - length m1 - length ops' =\n      i - length m1 - length ops) as Heq; [|rewrite Heq; auto].\n    rewrite NPeano.Nat.add_sub_swap;\n      [rewrite NPeano.Nat.add_sub | abstract omega].\n    repeat rewrite <- NPeano.Nat.sub_add_distr; rewrite plus_comm; auto.\n  Qed.\n\n  Lemma adjust_adjust : forall {A} (l1 l l' : list A) i\n    (Hrange : i < length l1 \\/ i >= length l1 + length l),\n    adjust_range l1 l' l (adjust_range l1 l l' i) = i.\n  Proof.\n    unfold adjust_range; intros.\n    destruct (lt_dec i (length l1)); clarify.\n    destruct (lt_dec (i - length l + length l')); abstract omega.\n  Qed.\n\n  Lemma adjust_lt : forall {A} (l1 l l' : list A) i j\n    (Hi : i < length l1 \\/ i >= length l1 + length l)\n    (Hj : j < length l1 \\/ j >= length l1 + length l),\n    adjust_range l1 l l' i < adjust_range l1 l l' j <-> i < j.\n  Proof.\n    unfold adjust_range; intros.\n    destruct (lt_dec i (length l1)), (lt_dec j (length l1)); try abstract omega.\n  Qed.\n\n  Lemma hb_delay : forall m1 ops m2 i j\n    (Hhb : happens_before (iapp m1 m2) i j),\n    happens_before (iapp m1 (iapp ops m2))\n      (adjust_range m1 [] ops i) (adjust_range m1 [] ops j).\n  Proof.\n    intros; induction Hhb.\n    - eapply hb_prog; eauto.\n      + apply adjust_lt; clarify; abstract omega.\n      + rewrite adjust_range_nth; clarify; abstract omega.\n      + rewrite adjust_range_nth; clarify; abstract omega.\n    - eapply hb_sync; eauto.\n      + apply adjust_lt; clarify; abstract omega.\n      + rewrite adjust_range_nth; clarify; abstract omega.\n      + rewrite adjust_range_nth; clarify; abstract omega.\n    - eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hbe_le : forall m i j (Hhbe : hbe m i j), i <= j.\n  Proof.\n    unfold hbe; intros; destruct Hhbe; clarify.\n    generalize (hb_lt H); abstract omega.\n  Qed.\n\n  Lemma hb_hbe_trans : forall m i j k, happens_before m i k -> hbe m k j ->\n    happens_before m i j.\n  Proof.\n    intros ? ? ? ? ? Hhbe; unfold hbe in Hhbe; destruct Hhbe; clarify;\n      eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hbe_hb_trans : forall m i j k, hbe m i k -> happens_before m k j ->\n    happens_before m i j.\n  Proof.\n    intros ? ? ? ? Hhbe; unfold hbe in Hhbe; destruct Hhbe; clarify;\n      eapply hb_trans; eauto.\n  Qed.\n\n  Lemma hb_boundary : forall m1 m2 i j\n    (Hhb : happens_before (iapp m1 m2) i j)\n    (Hi : i < length m1) (Hj : length m1 <= j),\n    exists k k', k < length m1 /\\ length m1 <= k' /\\\n      hbe (iapp m1 m2) i k /\\ hbe (iapp m1 m2) k' j /\\\n      exists a a', nth_error m1 k = Some a /\\ inth m2 (k' - length m1) = Some a'\n                   /\\ (thread_of a = thread_of a' \\/ synchronizes_with a a').\n  Proof.\n    intros; induction Hhb.\n    - exists i, j; unfold hbe; clarify.\n      rewrite iapp_nth in *; clarify.\n      destruct (lt_dec j (length m1)); [abstract omega|].\n      repeat eexists; eauto.\n    - exists i, j; unfold hbe; clarify.\n      rewrite iapp_nth in *; clarify.\n      destruct (lt_dec j (length m1)); [abstract omega|].\n      repeat eexists; eauto.\n    - destruct (lt_dec k (length m1)); clarify.\n      + exists x, x0; clarify.\n        repeat split; eauto.\n        eapply hbe_trans; eauto; unfold hbe; clarify.\n      + use IHHhb1; [clarify | abstract omega].\n        exists x, x0; clarify.\n        repeat split; eauto.\n        eapply hbe_trans; eauto; unfold hbe; clarify.\n  Qed.\n\n  Lemma hb_app'' : forall m1 ops m2 i j ops'\n    (Hhb : happens_before (iapp m1 (iapp ops m2)) i j)\n    (Hi : ~ i < length m1 + length ops) (Hj : ~ j < length m1 + length ops),\n    happens_before (iapp m1 (iapp ops' m2)) (i - length ops + length ops')\n         (j - length ops + length ops').\n  Proof.\n    intros; rewrite iapp_app in *; exploit hb_app'; eauto.\n    - rewrite app_length; auto.\n    - rewrite app_length; auto.\n    - instantiate (1 := (m1 ++ ops')); repeat rewrite app_length.\n      assert (i - (length m1 + length ops) + (length m1 + length ops') =\n        i - length ops + length ops') as Heq1 by abstract omega;\n        assert (j - (length m1 + length ops) + (length m1 + length ops') =\n          j - length ops + length ops') as Heq2 by abstract omega;\n        rewrite Heq1, Heq2; auto.\n  Qed.\n\n  Corollary hbe_app'' : forall m1 ops m2 i j ops'\n    (Hhb : hbe (iapp m1 (iapp ops m2)) i j)\n    (Hi : ~ i < length m1 + length ops) (Hj : ~ j < length m1 + length ops),\n    hbe (iapp m1 (iapp ops' m2)) (i - length ops + length ops')\n         (j - length ops + length ops').\n  Proof. unfold hbe; clarify; left; eapply hb_app''; eauto. Qed.\n\n  Lemma filter_snoc_inv : forall A (f : A -> bool) l l' x\n    (Hfilter : filter f l = l' ++ [x]),\n    exists l1 l2, l = l1 ++ x :: l2 /\\ filter f l1 = l' /\\\n      Forall (fun a => f a = false) l2.\n  Proof.\n    intros.\n    assert (nth_error (filter f l) (length l') = Some x)\n      by (rewrite Hfilter, nth_error_app; clarsimp).\n    exploit nth_error_in; eauto; intro.\n    rewrite filter_In in *; clarify.\n    exploit nth_filter_split; eauto; intros [k1 [k2 Hk]]; clarify.\n    symmetry in Hk21.\n    rewrite filter_app in *; generalize (app_eq_inv _ _ _ _ Hk21 Hfilter);\n      clarify.\n    rewrite filter_none_iff in *; eauto.\n  Qed.\n\n  End Happens_Before.\n\n  Definition not_read := @not_read block val.\n\n(*  Require Import Sorting.Permutation.\n\n  Inductive linearization (m m' : list _) : Prop :=\n    linI p (Hp : Permutation (interval 0 (length m)) p)\n    (Hlen : length m' = length m)\n    (Hperm : forall i i', nth_error p i = Some i' ->\n       nth_error m' i' = nth_error m i)\n    (Hhb : forall i j i' j', nth_error p i = Some i' ->\n       nth_error p j = Some j' ->\n       (happens_before m i j <-> happens_before m' i' j')).\n\n  Instance lin_refl : Reflexive linearization.\n  Proof.\n    intro; econstructor.\n    - reflexivity.\n    - auto.\n    - intros; rewrite nth_error_interval in *; clarify.\n    - intros; rewrite nth_error_interval in *; clarify; reflexivity.\n  Qed.\n\n  Fixpoint inv_perm_aux p i :=\n    match i with\n    | O => Some []\n    | S i' => match (find_index (fun x => beq x i') p, inv_perm_aux p i') with\n              | (Some j, Some rest) => Some (rest ++ [j])\n              | _ => None\n              end\n    end.\n\n  Definition inv_perm p := inv_perm_aux p (length p).\n\n  Require Import Permutation.\n\n  Opaque minus.\n\n  Lemma exists_inv_aux : forall p j (Hin : forall i, i < j -> In i p),\n    exists p', inv_perm_aux p j = Some p'.\n  Proof.\n    induction j; clarify; eauto.\n    destruct (find_index (fun x => beq x j) p) eqn: Hfind; eauto.\n    rewrite find_index_fail in Hfind.\n    specialize (Hin j); clarify.\n    rewrite Forall_forall in Hfind; specialize (Hfind _ Hin); unfold beq in *;\n      clarify.\n  Qed.\n      \n  Corollary exists_inv : forall p (Hin : forall i, i < length p -> In i p),\n    exists p', inv_perm p = Some p'.\n  Proof. intros; apply exists_inv_aux; auto. Qed.\n\n  Lemma inv_aux_length : forall p j p' (Hinv : inv_perm_aux p j = Some p'),\n    length p' = j.\n  Proof.\n    induction j; clarify.\n    exploit IHj; eauto; clarsimp; omega.\n  Qed.    \n\n  Corollary inv_length : forall p p' (Hinv : inv_perm p = Some p'),\n    length p' = length p.\n  Proof. intros; eapply inv_aux_length; eauto. Qed.\n\n  Lemma inv_aux_nth : forall p j p' i' i (Hinv : inv_perm_aux p j = Some p')\n    (Hnth : nth_error p' i' = Some i), nth_error p i = Some i'.\n  Proof.\n    induction j; clarsimp.\n    rewrite nth_error_app in Hnth; destruct (lt_dec i' (length x0)).\n    - eapply IHj; eauto; omega.\n    - destruct (i' - length x0) eqn: Hminus; clarsimp.\n      destruct (eq_dec i' (length x0)); [clarify | omega].\n      rewrite find_index_spec in *; unfold beq in *; clarify.\n      erewrite inv_aux_length; eauto.\n  Qed.\n\n  Corollary inv_nth : forall p p' i' i (Hinv : inv_perm p = Some p')\n    (Hnth : nth_error p' i' = Some i), nth_error p i = Some i'.\n  Proof. intros; eapply inv_aux_nth; eauto. Qed.\n\n  Corollary inv_aux_NoDup : forall p j p' (Hinv : inv_perm_aux p j = Some p'),\n    NoDup p'.\n  Proof.\n    intros; rewrite NoDup_inj_iff; intros.\n    generalize (inv_aux_nth _ _ _ Hinv Hi), (inv_aux_nth _ _ _ Hinv Hj);\n      clarsimp.\n  Qed.\n\n  Corollary inv_NoDup : forall p p' (Hinv : inv_perm p = Some p'), NoDup p'.\n  Proof. intros; eapply inv_aux_NoDup; eauto. Qed.\n\n  Lemma inv_nil : inv_perm [] = Some [].\n  Proof. unfold inv_perm; auto. Qed.\n  Hint Resolve inv_nil.\n\n  Lemma inv_perm_aux_in : forall p j p' (Hinv : inv_perm_aux p j = Some p')\n    i (Hlt : i < j),\n    exists i', find_index (fun x => beq x i) p = Some i' /\\ In i' p'.\n  Proof.\n    induction j; clarify; [omega|].\n    destruct (eq_dec i j); clarify.\n    - setoid_rewrite in_app; simpl; eauto.\n    - specialize (IHj _ Hinv21 i); use IHj; [|omega].\n      setoid_rewrite in_app; clarify; eauto.\n  Qed.\n             \n  Lemma inv_perm_spec : forall j p (Hperm : Permutation (interval 0 j) p),\n    exists p', inv_perm p = Some p' /\\ Permutation (interval 0 j) p'.\n  Proof.\n    intros.\n    assert (length p = j) as Hlen; clarify.\n    { erewrite <- Permutation_length, interval_length in *; eauto; omega. }\n    exploit (exists_inv p).\n    { intros; eapply Permutation_in; eauto.\n      apply interval_in; omega. }\n    intros [p' Hp']; exists p'; clarify.\n    apply NoDup_Permutation.\n    - apply interval_distinct.\n    - eapply inv_NoDup; eauto.\n    - intro; rewrite interval_in_iff.\n      split; clarify.\n      + exploit nth_error_succeeds; eauto; clarify.\n        exploit nth_error_in; eauto; intro.\n        exploit Permutation_NoDup; [apply interval_distinct | eauto |\n          intro Hdistinct].\n        symmetry in Hperm; exploit Permutation_in; eauto.\n        rewrite interval_in_iff; clarify.\n        exploit inv_perm_aux_in; eauto; intros [? [Hfind ?]].\n        rewrite find_index_spec in *; unfold beq in *; clarify.\n        generalize (NoDup_inj _ _ Hdistinct H Hfind1); clarify.\n      + exploit in_nth_error; eauto; clarify.\n        exploit inv_nth; eauto.\n        apply nth_error_lt.\n  Qed.\n\n  Instance lin_sym : Symmetric linearization.\n  Proof.\n    repeat intro; inversion H.\n    exploit inv_perm_spec; eauto; intros [p' [Hinv ?]].\n    exists p'; clarify.\n    - rewrite Hlen; auto.\n    - exploit inv_nth; eauto; intro.\n      erewrite Hperm; eauto.\n    - generalize (inv_nth _ _ Hinv H1), (inv_nth _ _ Hinv H2); intros.\n      rewrite Hhb; [reflexivity | auto | auto].\n  Qed.\n\n  Definition perm_index p i :=\n    match nth_error p i with Some i' => i' | None => i end.\n\n  Lemma perm_index_ge : forall p i (Hge : length p <= i), perm_index p i = i.\n  Proof.\n    unfold perm_index; intros.\n    destruct (nth_error p i) eqn: Hi'; clarify.\n    exploit nth_error_lt; eauto; omega.\n  Qed.\n\n  Inductive lin_p p m m' :=\n    lin_pI (Hp : Permutation (interval 0 (length m)) p)\n    (Hlen : length m' = length m)\n    (Hperm : forall i i', nth_error p i = Some i' ->\n       nth_error m' i' = nth_error m i)\n    (Hhb : forall i j i' j', nth_error p i = Some i' ->\n       nth_error p j = Some j' ->\n       (happens_before m i j <-> happens_before m' i' j')).\n\n  Lemma lin_lin_p : forall m m', linearization m m' <-> exists p, lin_p p m m'.\n  Proof.\n    split; intro Hlin; clarify; inversion Hlin.\n    - exists p; constructor; auto.\n    - econstructor; eauto.\n  Qed.\n\n  Lemma perm_index_nth : forall p m1 m1' m2 i (Hlin : lin_p p m1 m1'),\n    inth (iapp m1' m2) (perm_index p i) = inth (iapp m1 m2) i.\n  Proof.\n    intros; inversion Hlin.\n    assert (length p = length m1) as Hlen'.\n    { erewrite <- Permutation_length, interval_length; eauto; clarsimp. }\n    unfold perm_index; destruct (nth_error p i) eqn: Hi'.\n    - exploit nth_error_lt; eauto.\n      rewrite Hlen'; repeat rewrite iapp_nth; clarsimp.\n      exploit nth_error_succeeds; eauto; clarify.\n      specialize (Hperm _ _ Hi'); rewrite <- Hperm in *.\n      contradiction n0; eapply nth_error_lt; eauto.\n    - repeat rewrite iapp_nth; rewrite Hlen; clarify.\n      clear cond; rewrite <- Hlen' in l; exploit nth_error_succeeds; eauto;\n        clarify.\n  Qed.\n\n  Lemma hb_lin_lt : forall p m1 m1' m2 i j (Hlin : lin_p p m1 m1')\n    (Hhb : happens_before (iapp m1 m2) i j), perm_index p i < perm_index p j.\n  Proof.\n    intros; inversion Hlin.\n    assert (length p = length m1) as Hlen'.\n    { erewrite <- Permutation_length, interval_length; eauto; clarsimp. }\n    generalize (hb_lt Hhb); intro.\n    destruct (lt_dec i (length m1)), (lt_dec j (length m1)); try omega.\n    - exploit hb_app_impl; eauto; intro Hhb'.\n      rewrite <- Hlen' in *; generalize (nth_error_succeeds _ l),\n        (nth_error_succeeds _ l0); unfold perm_index; clarify.\n      rewrite Hhb0 in Hhb'; eauto; eapply hb_lt; eauto.\n    - setoid_rewrite perm_index_ge at 2; [|omega].\n      exploit nth_error_succeeds; eauto; clarify.\n      rewrite <- Hlen' in *; exploit nth_error_succeeds; eauto;\n        unfold perm_index; clarify.\n      erewrite <- Hperm in *; eauto.\n      exploit nth_error_lt; eauto.\n      rewrite Hlen; omega.\n    - repeat rewrite perm_index_ge; auto; omega.\n  Qed.\n\n  Lemma hb_lin_prefix : forall p m1 m1' m2 i j (Hlin : lin_p p m1 m1')\n    (Hhb : happens_before (iapp m1 m2) i j),\n    happens_before (iapp m1' m2) (perm_index p i) (perm_index p j).\n  Proof.\n    intros; exploit hb_lin_lt; eauto; intro.\n    induction Hhb.\n    - eapply hb_prog; eauto; erewrite perm_index_nth; eauto.\n    - eapply hb_sync; eauto; erewrite perm_index_nth; eauto.\n    - eapply hb_trans; [apply IHHhb1 | apply IHHhb2]; eapply hb_lin_lt; eauto.\n  Qed.*)\n\n  Lemma lower_app : forall m1 m2, lower (m1 ++ m2) = lower m1 ++ lower m2.\n  Proof.\n    intros; unfold lower; rewrite map_app, flatten_app; auto.\n  Qed.\n  \n  Lemma nth_lower_split : forall m i x (Hnth : nth_error (lower m) i = Some x),\n    exists m1 c m2 i', m = m1 ++ c :: m2 /\\ nth_error (to_seq c) i' = Some x /\\\n      i = length (lower m1) + i'.\n  Proof.\n    intros.\n    exploit nth_flatten_split; eauto; clarify.\n    exploit list_append_map_inv; eauto; intros [m1 [m2 ?]]; clarify.\n    destruct m2; clarify.\n    repeat eexists; eauto.\n  Qed.\n\n  Definition SC m := seq_con (lower m).\n\n  Definition reads m r p v := exists a, inth m r = Some a /\\\n    In (MRead p v) (to_seq a).\n  Definition writes m w p v := exists a, inth m w = Some a /\\\n    In (MWrite p v) (to_seq a).\n  Definition mods m i p := exists a op, inth m i = Some a /\\ In op (to_seq a) /\\\n    op_modifies _ op p = true.\n\n  Definition b_not_read b op := not_read op && beq (block_of op) b.\n\n  Lemma b_not_read_spec : forall b m, filter (b_not_read b) m =\n    filter not_read (proj_block m b).\n  Proof.\n    intros; setoid_rewrite filter_filter; apply filter_ext.\n    rewrite Forall_forall; auto.\n  Qed.\n\n  Definition race_free m := forall i j (Hdiff : i <> j) a b\n    (Ha : inth m i = Some a) (Hb : inth m j = Some b)\n    (Hint : exists bl op1 op2 o, In op1 (to_seq a) /\\ In op2 (to_seq b) /\\\n      op_modifies _ op1 (bl, o) = true /\\ block_of op2 = bl),\n    happens_before m i j \\/ happens_before m j i.\n\n  Lemma inth_plus : forall A (l1 : list A) l2 i,\n    inth (iapp l1 l2) (length l1 + i) = inth l2 i.\n  Proof.\n    intros; rewrite iapp_nth, lt_dec_plus_r, minus_plus; auto.\n  Qed.\n\n  Corollary inth_length : forall A (l1 : list A) x l2,\n    inth (iapp l1 (icons x l2)) (length l1) = Some x.\n  Proof. intros; rewrite (plus_n_O (length l1)), inth_plus; auto. Qed.\n\n  Lemma hb_replace1 : forall c c' (Ht : thread_of c = thread_of c')\n    (Hsync : forall a, (synchronizes_with a c <-> synchronizes_with a c') /\\\n       (synchronizes_with c a <-> synchronizes_with c' a)) m1 m2 i j,\n    happens_before (iapp m1 (icons c m2)) i j ->\n    happens_before (iapp m1 (icons c' m2)) i j.\n  Proof.\n    intros; induction H.\n    - rewrite (iapp_split_nth _ _ _ _ c') in Ha;\n        rewrite (iapp_split_nth _ _ _ _ c') in Hb.\n      destruct (eq_dec i (length m1)), (eq_dec j (length m1)); clarify.\n      + omega.\n      + rewrite Ht in Hthread; eapply hb_prog; eauto; apply inth_length.\n      + rewrite Ht in Hthread; eapply hb_prog; eauto; apply inth_length.\n      + eapply hb_prog; eauto.\n    - rewrite (iapp_split_nth _ _ _ _ c') in Ha;\n        rewrite (iapp_split_nth _ _ _ _ c') in Hb.\n      destruct (eq_dec i (length m1)), (eq_dec j (length m1)); clarify.\n      + omega.\n      + specialize (Hsync b); destruct Hsync as [_ Hsync].\n        rewrite Hsync in Hsync0; eapply hb_sync; eauto; apply inth_length.\n      + specialize (Hsync a); destruct Hsync as [Hsync _].\n        rewrite Hsync in Hsync0; eapply hb_sync; eauto; apply inth_length.\n      + eapply hb_sync; eauto.\n    - eapply hb_trans; eauto.\n  Qed.\n\n  Corollary hb_replace : forall c c' (Ht : thread_of c = thread_of c')\n    (Hsync : forall a, (synchronizes_with a c <-> synchronizes_with a c') /\\\n       (synchronizes_with c a <-> synchronizes_with c' a)) m1 m2 i j,\n    happens_before (iapp m1 (icons c m2)) i j <->\n    happens_before (iapp m1 (icons c' m2)) i j.\n  Proof.\n    split; apply hb_replace1; auto.\n    split; symmetry; apply Hsync.\n  Qed.\n\n  Lemma drop_race_free_single : forall m1 c m2 (b : block)\n    (Hrf : race_free (iapp m1 (icons c m2)))\n    drop_b_reads c' (Hdrop : drop_b_reads b [c] = [c'])\n    (Hc' : forall op, In op (to_seq c') -> In op (to_seq c))\n    (Hc : forall op p, op_modifies _ op p = true -> In op (to_seq c) ->\n            In op (to_seq c'))\n    (Hiff : forall i j,\n      happens_before (iapp m1 (iapp (drop_b_reads b [c]) m2)) i j <->\n      happens_before (iapp m1 (icons c m2)) i j),\n    race_free (iapp m1 (iapp (drop_b_reads b [c]) m2)).\n  Proof.\n    repeat intro; clarsimp.\n    repeat rewrite Hiff; eapply Hrf; auto.\n    - instantiate (1 := if eq_dec i (length m1) then c else a).\n      erewrite iapp_split_nth; clarify; eauto.\n    - instantiate (1 := if eq_dec j (length m1) then c else b0).\n      erewrite iapp_split_nth; clarify; eauto.\n    - repeat eexists; eauto; clarify.\n      + rewrite iapp_nth, lt_dec_eq, minus_diag in Ha; clarify.\n      + rewrite iapp_nth, lt_dec_eq, minus_diag in Hb; clarify.\n  Qed.\n      \n  Class Memory_Model := { well_formed : ilist conc_op -> Prop;\n    consistent : ilist conc_op -> Prop;\n    consistent_nil : consistent inil;\n    read_free : forall (m : list _) (Hno_reads : (forall r p v, ~reads m r p v))\n      (Hwrite : write_alloc (lower m)), consistent m <-> seq_con (lower m);\n    read_write : forall m r p v (Hread_init : read_init (lower m))\n      (Hcon : consistent m) (Hread : reads m r p v), \n      exists w, r <> w /\\ writes m w p v /\\\n      (forall w2 v2, writes m w2 p v2 ->\n         ~(happens_before m w w2 /\\ happens_before m w2 r)) /\\\n       ~happens_before m r w;\n    drop_wf : forall m1 ops m2 b, well_formed (iapp m1 (iapp ops m2)) ->\n      well_formed (iapp m1 (iapp (drop_b_reads b ops) m2));\n    drop_race_free : forall m1 c m2 b (Hwf : well_formed (iapp m1 (icons c m2)))\n      (Hrf : race_free (iapp m1 (icons c m2))),\n      race_free (iapp m1 (iapp (drop_b_reads b [c]) m2));\n    private_seq : forall ops t (Ht : Forall (fun c => thread_of c = t) ops)\n    (Hlen : length ops > 0) (m1 : list _) m2 b\n    (Hbefore : forall i o, mods m1 i (b, o) ->\n       happens_before (iapp m1 (iapp ops m2)) i (length m1))\n    (Huniform : forall i o v, reads ops i (b, o) v ->\n       exists j, j < length m1 + i /\\ writes (m1 ++ ops) j (b, o) v /\\\n       forall k v', k < length m1 + i -> writes (m1 ++ ops) k (b, o) v' ->\n       hbe (iapp m1 (iapp ops m2)) k j)\n    (Hafter : forall i o, mods m2 i (b, o) ->\n       happens_before (iapp m1 (iapp ops m2))\n         (length m1 + length ops - 1) (i + length m1 + length ops))\n    (Hread_init : read_init (filter (b_not_read b) (lower m1) ++\n       proj_block (lower ops) b))\n    (Hwrite_alloc : write_alloc (lower (m1 ++ ops)))\n    (Hwf : well_formed (iapp m1 (iapp ops m2))),\n    consistent (iapp m1 (iapp ops m2)) <->\n    consistent (iapp m1 (iapp (drop_b_reads b ops) m2)) /\\\n      seq_con (filter (b_not_read b) (lower m1) ++ proj_block (lower ops) b) }.\n\n  Lemma lower_cons : forall x l, lower (x :: l) = to_seq x ++ lower l.\n  Proof. auto. Qed.\n\n  Corollary lower_single : forall x, lower [x] = to_seq x.\n  Proof. intro; rewrite lower_cons; clarsimp. Qed.\n\n  Lemma nth_error_plus : forall A (l1 l2 : list A) i,\n    nth_error (l1 ++ l2) (length l1 + i) = nth_error l2 i.\n  Proof.\n    intros; rewrite nth_error_app, lt_dec_plus_r, minus_plus; auto.\n  Qed.\n\n  Lemma read_init_drop_b : forall ops b m1 m2\n    (Hread : read_init (iapp m1 (iapp (lower ops) m2))),\n    read_init (iapp m1 (iapp (lower (drop_b_reads b ops)) m2)).\n  Proof.\n    intros ? ?.\n    generalize (drop_b_reads_spec b ops); intro Hdrop; rewrite Hdrop.\n    clear Hdrop; induction (lower ops); clarify.\n    specialize (IHl (m1 ++ [a]) m2);\n      repeat rewrite <- iapp_app in IHl; clarify.\n    destruct a; clarsimp.\n    eapply read_init_drop; eauto.\n  Qed.\n\n  Corollary read_init_drop_b' : forall m1 ops m2 b\n    (Hread : read_init (m1 ++ lower ops ++ m2)),\n    read_init (m1 ++ lower (drop_b_reads b ops) ++ m2).\n  Proof.\n    intros; repeat rewrite to_ilist_app in *; apply read_init_drop_b; auto.\n  Qed.\n\n  Lemma write_alloc_drop_b : forall ops b m1 m2\n    (Hread : write_alloc (iapp m1 (iapp (lower ops) m2))),\n    write_alloc (iapp m1 (iapp (lower (drop_b_reads b ops)) m2)).\n  Proof.\n    intros ? ?.\n    generalize (drop_b_reads_spec b ops); intro Hdrop; rewrite Hdrop.\n    clear Hdrop; induction (lower ops); clarify.\n    specialize (IHl (m1 ++ [a]) m2);\n      repeat rewrite <- iapp_app in IHl; clarify.\n    destruct a; clarsimp.\n    eapply write_alloc_drop; eauto.\n  Qed.\n\n  Corollary write_alloc_drop_b' : forall m1 ops m2 b\n    (Hwrite : write_alloc (m1 ++ lower ops ++ m2)),\n    write_alloc (m1 ++ lower (drop_b_reads b ops) ++ m2).\n  Proof.\n    intros; repeat rewrite to_ilist_app in *; apply write_alloc_drop_b; auto.\n  Qed.\n\n  Lemma drop_reads : forall m1 c m2 p v (Hread : In (MRead p v) (to_seq c)),\n    length (filter (fun op => negb (not_read op))\n      (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2))) <\n    length (filter (fun op => negb (not_read op)) (lower (m1 ++ c :: m2))).\n  Proof.\n    intros; repeat rewrite lower_app; rewrite lower_cons.\n    repeat rewrite filter_app, app_length.\n    apply plus_lt_compat_l, plus_lt_compat_r.\n    rewrite drop_b_reads_spec, lower_single, filter_comm.\n    exploit in_split; eauto.\n    clear; clarsimp; repeat rewrite filter_app; clarify.\n    destruct p; unfold negb at 3; clarify.\n    repeat rewrite app_length; apply plus_le_lt_compat; [apply filter_length|].\n    simpl; eapply le_lt_trans; [apply filter_length | auto].\n  Qed.\n\n  Lemma last_drop : forall r m1 ops m2 b p a (Hrange : r < length (lower m1) \\/\n    r >= length (lower m1) + length (lower ops)),\n    last_op (firstn (adjust_range (lower m1) (lower ops)\n      (lower (drop_b_reads b ops)) r)\n      (lower m1 ++ lower (drop_b_reads b ops) ++ lower m2)) (Ptr p) a <->\n    last_op (firstn r (lower m1 ++ lower ops ++ lower m2)) (Ptr p) a.\n  Proof.\n    intros.\n    unfold adjust_range; repeat rewrite firstn_app;\n      destruct (lt_dec r (length (lower m1))).\n    - rewrite not_le_minus_0; [clarify | omega].\n      repeat rewrite NPeano.Nat.sub_0_l; clarify; reflexivity.\n    - rewrite firstn_length'; [|omega].\n      rewrite firstn_length'; [|omega].\n      setoid_rewrite firstn_length' at 2; [|omega].\n      setoid_rewrite firstn_length' at 2; [|omega].\n      rewrite minus_comm, NPeano.Nat.add_sub; [|omega].\n      rewrite minus_comm; [|omega].\n      rewrite drop_b_reads_spec.\n      setoid_rewrite <- last_op_filter; repeat rewrite filter_app.\n      rewrite filter_filter.\n      setoid_rewrite (filter_ext _ not_read) at 2; [reflexivity|].\n      rewrite Forall_forall; unfold andb, orb; clarify.\n  Qed.\n\n  Corollary last_drop' : forall r m1 c m2 b p a (Hrange : r < length (lower m1) \n    \\/ r >= length (lower m1) + length (to_seq c)),\n    last_op (firstn (adjust_range (lower m1) (to_seq c)\n      (lower (drop_b_reads b [c])) r)\n      (lower m1 ++ lower (drop_b_reads b [c]) ++ lower m2)) (Ptr p) a <->\n    last_op (firstn r (lower m1 ++ to_seq c ++ lower m2)) (Ptr p) a.\n  Proof. intros; rewrite <- lower_single in *; apply last_drop; auto. Qed.\n\n  Variable (val_eq : EqDec_eq val).\n\n  Lemma in_range_dec : forall i a b, (i < a \\/ i >= b) \\/ (a <= i < b).\n  Proof. intros; omega. Qed.\n\n  Lemma adjust_range_nth' : forall A (l1 l2 l3 l2' : list A) i\n    (Hout : i < length l1 \\/ i >= length l1 + length l2),\n    nth_error (l1 ++ l2' ++ l3) (adjust_range l1 l2 l2' i) =\n    nth_error (l1 ++ l2 ++ l3) i.\n  Proof.\n    intros; unfold adjust_range; repeat rewrite nth_error_app;\n      destruct (lt_dec i (length l1)); clarify.\n    destruct (lt_dec (i - length l1) (length l2)); [omega|].\n    destruct (lt_dec (i - length l2 + length l2') (length l1)); [omega|].\n    destruct (lt_dec (i - length l2 + length l2' - length l1) (length l2'));\n      [omega|].\n    assert (i - length l2 + length l2' - length l1 - length l2' =\n      i - length l1 - length l2) as Heq.\n    { rewrite minus_comm, NPeano.Nat.add_sub, minus_comm; auto.\n      - rewrite plus_comm; auto.\n      - omega. }\n    rewrite Heq; auto.\n  Qed.\n\n  Lemma drop_SC : forall m1 ops m2 (Hseq : SC (m1 ++ ops ++ m2))\n    (Hread : read_init (lower (m1 ++ ops ++ m2)))\n    (Hwrite : write_alloc (lower (m1 ++ ops ++ m2))) b,\n    SC (m1 ++ drop_b_reads b ops ++ m2).\n  Proof.\n    unfold SC; intros.\n    setoid_rewrite consistent_split_reads in Hseq; auto.\n    repeat rewrite lower_app in *.\n    setoid_rewrite consistent_split_reads;\n      [|apply read_init_drop_b' | apply write_alloc_drop_b']; clarify.\n    split.\n    - rewrite drop_b_reads_spec; repeat rewrite filter_app in *.\n      rewrite filter_filter; setoid_rewrite (filter_ext _ not_read) at 2; auto.\n      rewrite Forall_forall; unfold andb; clarify.\n    - intros.\n      destruct (in_range_dec r (length (lower m1))\n        (length (lower m1) + length (lower (drop_b_reads b ops))))\n        as [Hrange | [Hrange1 Hrange2]].\n      + specialize (Hseq2 (adjust_range (lower m1) (lower (drop_b_reads b ops))\n          (lower ops) r)); rewrite adjust_range_nth' in Hseq2; auto.\n        specialize (Hseq2 _ _ H).\n        rewrite <- (adjust_adjust (lower m1) (lower (drop_b_reads b ops))\n          (lower ops) Hrange), last_drop; auto.\n        { unfold adjust_range; destruct (lt_dec r (length (lower m1))); clarify;\n            omega. }\n      + rewrite nth_error_app in *; destruct (lt_dec r (length (lower m1)));\n          [omega|].\n        rewrite nth_error_app in *; destruct (lt_dec (r - length (lower m1))\n          (length (lower (drop_b_reads b ops)))); [|omega].\n        rewrite drop_b_reads_spec in H.\n        exploit nth_filter_split; eauto; intros (l1 & l2 & Hl & Hr & ?);\n          clarify.\n        specialize (Hseq2 (length (lower m1) + length l1));\n          rewrite nth_error_plus, Hl in Hseq2.\n        rewrite <- app_assoc in Hseq2; simpl in Hseq2.\n        specialize (Hseq2 _ _ (nth_error_split _ _ _)).\n        rewrite firstn_app, firstn_length', minus_plus in Hseq2; [|omega].\n        rewrite firstn_app, firstn_length, minus_diag in Hseq2; clarify.\n        rewrite drop_b_reads_spec, Hl, filter_app.\n        rewrite firstn_app, firstn_length', Hr; [|omega].\n        rewrite <- app_assoc, firstn_app, firstn_length, minus_diag; clarify.\n        rewrite app_nil_r in *.\n        rewrite <- last_op_filter in Hseq2; rewrite <- last_op_filter.\n        repeat rewrite filter_app in *.\n        rewrite filter_filter; setoid_rewrite (filter_ext _ not_read) at 2;\n          auto.\n        rewrite Forall_forall; unfold andb; clarify.\n  Qed.\n\n  Lemma merge_SC : forall m1 ops m2 b\n    (Hread : read_init (lower (m1 ++ ops ++ m2)))\n    (Hwrite : write_alloc (lower (m1 ++ ops ++ m2)))\n    (Hseq : SC (m1 ++ (drop_b_reads b ops) ++ m2))\n    (Hseq' : seq_con (filter (b_not_read b) (lower m1) ++\n                      proj_block (lower ops) b)),\n    SC (m1 ++ ops ++ m2).\n  Proof.\n    unfold SC; intros.\n    repeat rewrite lower_app in *.\n    setoid_rewrite consistent_split_reads; auto.\n    setoid_rewrite consistent_split_reads in Hseq;\n      [|apply read_init_drop_b' | apply write_alloc_drop_b']; clarify.\n    split.\n    { rewrite drop_b_reads_spec in Hseq1; repeat rewrite filter_app in *.\n      rewrite filter_filter in Hseq1; setoid_rewrite (filter_ext _ not_read)\n        in Hseq1 at 2; auto.\n      rewrite Forall_forall; unfold andb; clarify. }\n    intros ??? Hreads.\n    destruct (in_range_dec r (length (lower m1))\n      (length (lower m1) + length (lower ops))) as [Hrange | [Hrange1 Hrange2]].\n    - specialize (Hseq2 (adjust_range (lower m1) (lower ops) (lower\n        (drop_b_reads b ops)) r)); rewrite adjust_range_nth' in Hseq2; auto.\n      specialize (Hseq2 _ _ Hreads); rewrite last_drop in Hseq2; auto.\n    - rewrite nth_error_app in *; destruct (lt_dec r (length (lower m1)));\n        [omega|].\n      rewrite nth_error_app in *; destruct (lt_dec (r - length (lower m1))\n        (length (lower ops))); [|omega].\n      exploit nth_error_split'; eauto; intros (l1 & l2 & Hr & Hl).\n      rewrite firstn_app, firstn_length', Hl; [|omega].\n      rewrite <- app_assoc; simpl.\n      rewrite <- Hr, firstn_app, firstn_length, minus_diag; clarify.\n      destruct p as (b', o); destruct (eq_dec b' b).\n      + subst; rewrite Hl in Hseq'.\n        rewrite proj_block_app in Hseq'; clarify.\n        rewrite app_assoc, to_ilist_app in Hseq'.\n        generalize (read_justified_op _ _ _ _ Hseq'); intro Hlast; use Hlast.\n        rewrite last_op_proj, app_nil_r; simpl.\n        setoid_rewrite proj_block_app.\n        rewrite <- last_op_filter; rewrite <- last_op_filter in Hlast.\n        repeat rewrite filter_app in *.\n        rewrite b_not_read_spec, filter_filter in Hlast.\n        erewrite filter_ext in Hlast; eauto.\n        rewrite Forall_forall; clarsimp.\n        { rewrite app_assoc in Hread; generalize (read_init_app _ _ Hread).\n          intro Hread1; generalize (read_init_proj _ Hread1 b).\n          rewrite Hl; repeat setoid_rewrite proj_block_app; intro Hread2.\n          generalize (read_init_filter' _ _ Hread2).\n          rewrite b_not_read_spec; clarify.\n          rewrite <- iapp_app; repeat rewrite to_ilist_app in *; auto. }\n      + rewrite drop_b_reads_spec, Hl in Hseq2.\n        specialize (Hseq2 (length (lower m1) + length (filter (fun op =>\n          block_model.not_read op || negb (beq (block_of op) b)) l1))).\n        rewrite nth_error_plus, filter_app in Hseq2; clarify.\n        unfold negb, beq in Hseq2; destruct (eq_dec b' b); clarify.\n        rewrite <- app_assoc in Hseq2; simpl in Hseq2.\n        specialize (Hseq2 _ _ (nth_error_split _ _ _)).\n        rewrite firstn_app, firstn_length', minus_plus, firstn_app,\n          firstn_length, minus_diag in Hseq2; [clarify | omega].\n        rewrite app_nil_r in *.\n        rewrite <- last_op_filter in Hseq2; rewrite <- last_op_filter.\n        repeat rewrite filter_app in *.\n        rewrite filter_filter in Hseq2;\n          setoid_rewrite (filter_ext _ not_read) in Hseq2 at 2; auto.\n        rewrite Forall_forall; unfold andb; clarify.\n  Qed.\n\n  Variable (b0 : block).\n\n  Section SC.\n\n    Hypothesis drop_race_free : forall m1 c m2 b\n      (Hrf : race_free (iapp m1 (icons c m2))),\n      race_free (iapp m1 (iapp (drop_b_reads b [c]) m2)).\n\n    Global Instance SC_MM : Memory_Model := { consistent := fun m =>\n      exists m', to_ilist m' = m /\\ SC m';\n      well_formed := fun m => exists m', to_ilist m' = m /\\\n        read_init (lower m') /\\ write_alloc (lower m') }.\n    Proof.\n      - exists []; unfold SC; clarify.\n        apply block_model.consistent_nil; auto.\n      - unfold SC; split; clarify; eauto.\n        exploit to_ilist_inj; eauto; clarify.\n      - clarify.\n        exploit to_ilist_inj; eauto; clarify.\n        destruct Hread as (opr & Hr & Hopr).\n        rewrite inth_nth_error in Hr; exploit nth_error_split'; eauto;\n          intros (m1 & m2 & ?); clarify.\n        exploit in_split; eauto; intros (l1 & l2 & Hl).\n        unfold SC in Hcon2; rewrite lower_app, lower_cons, Hl\n          in Hread_init, Hcon2.\n        rewrite <- app_assoc, app_assoc in Hread_init, Hcon2; clarify.\n        rewrite to_ilist_app in Hread_init, Hcon2.\n        generalize (read_justified_op _ _ _ _ Hcon2 Hread_init);\n          intros (w & Hlast & Hw).\n        rewrite inth_nth_error, nth_error_app in Hw.\n        destruct (lt_dec w (length (lower m1))) eqn: Hltw;\n          setoid_rewrite Hltw in Hw.\n        exploit nth_lower_split; eauto;\n          intros (m1' & opw & m2' & i & ? & Hi & ?); clarify.\n        generalize (nth_error_in _ _ Hi); intro.\n        exists (length m1'); repeat split.\n        + rewrite app_length; simpl; omega.\n        + unfold writes; rewrite <- app_assoc, inth_nth_error.\n          simpl; rewrite nth_error_split; eauto.\n        + unfold writes; intros ?? Hwrite [Hhb1 Hhb2]; clarify.\n          generalize (hb_lt Hhb1), (hb_lt Hhb2); intros.\n          rewrite inth_nth_error, nth_error_app in Hwrite1; clarify.\n          rewrite nth_error_app in Hwrite1; destruct (lt_dec w2 (length m1'));\n            [omega|].\n          destruct (w2 - length m1') eqn: Hminus; [omega | clarify].\n          inversion Hlast.\n          rewrite inth_nth_error, nth_error_app in Hop1; clarify.\n          rewrite Hw in Hop1; clarify.\n          exploit nth_error_split'; eauto; intros (l1' & l2' & ?); clarify.\n          generalize (in_nth_error _ _ Hwrite2); intros (i2 & Hlt2 & Hi2).\n          specialize (Hlast0 (length (lower m1') + (length (to_seq opw) +\n            (length (lower l1') + i2)))).\n          rewrite lower_app, lower_cons, lower_app, lower_cons in Hlast0.\n          repeat rewrite <- app_assoc in Hlast0.\n          rewrite inth_nth_error in Hlast0;\n            repeat rewrite nth_error_plus in Hlast0.\n          generalize (nth_error_lt _ _ Hi); intro.\n          rewrite nth_error_app in Hlast0; clarify.\n          specialize (Hlast0 _ Hi2); clarify; omega.\n        + intro Hhb; generalize (hb_lt Hhb); rewrite app_length; omega.\n        + generalize (read_safe opr); rewrite Hl; intro Hsafe.\n          specialize (Hsafe (length l1)); rewrite nth_error_split in Hsafe.\n          exploit nth_error_lt; eauto; intro Hlt.\n          specialize (Hsafe _ _ eq_refl _ Hlt v);\n            rewrite nth_error_app in Hsafe; clarify.\n      - clarify.\n        exploit to_ilist_app_inv; eauto; clarify.\n        exploit (to_ilist_app_inv ops); eauto; clarify.\n        exists (m1 ++ drop_b_reads b ops ++ x); split;\n          [repeat rewrite to_ilist_app; auto|].\n        repeat rewrite lower_app in *; split;\n          [apply read_init_drop_b' | apply write_alloc_drop_b']; auto.\n      - intros; apply drop_race_free; auto.\n      - clarify.\n        exploit to_ilist_app_inv; eauto; clarify.\n        exploit (to_ilist_app_inv ops); eauto; clarify.\n        split; intro Hcon; clarify.\n        + repeat rewrite <- to_ilist_app in *.\n          exploit to_ilist_inj; eauto; clarify.\n          split.\n          * do 2 eexists; eauto.\n            apply drop_SC; auto.\n          * unfold SC in *; repeat rewrite lower_app in *.\n            rewrite app_assoc in *; generalize (read_init_app _ _ Hwf21),\n              (write_alloc_app _ _ Hwf22), (consistent_app _ _ Hcon2);\n              intros ? ? Hcon.\n            generalize (consistent_proj _ b Hcon); intro Hcon'; clarify.\n            setoid_rewrite proj_block_app in Hcon'.\n            rewrite consistent_core_ops in Hcon'.\n            rewrite proj_idem in Hcon'.\n            rewrite b_not_read_spec; clarify.\n            { apply filter_Forall; unfold beq; clarify. }\n            { rewrite <- proj_block_app; apply read_init_proj; auto. }\n            { rewrite <- proj_block_app; apply write_alloc_proj; auto. }\n        + exploit to_ilist_app_inv; eauto; clarify.\n          exploit (to_ilist_app_inv (drop_b_reads b ops)); eauto; clarify.\n          exploit to_ilist_inj; eauto; clarify.\n          do 2 eexists; eauto.\n          eapply merge_SC; eauto.\n    Defined.\n\n  End SC.\n\n  Context {MM : Memory_Model}.\n\n(* Well-synchronized programs *)\n\n  Lemma race_free_app : forall m1 m2, race_free (m1 ++ m2) -> race_free m1.\n  Proof.\n    unfold race_free; intros.\n    specialize (H _ _ Hdiff).\n    repeat rewrite inth_nth_error, nth_error_app in *.\n    generalize (nth_error_lt _ _ Ha), (nth_error_lt _ _ Hb); clarify.\n    rewrite to_ilist_app in H.\n    exploit H; eauto; [repeat eexists; eauto|].\n    intros [Hhb | Hhb]; [left | right]; eapply hb_app_impl;\n      eauto.\n  Qed.\n\n  (* up? *)\n  Instance mem_op_eq : EqDec_eq mem_op.\n  Proof. eq_dec_inst. Qed.\n\n  Definition has_read (c : conc_op) :=\n    existsb (fun op => negb (not_read op)) (to_seq c).\n\n  Lemma drop_b_filter : forall b ops,\n    filter not_read (lower (drop_b_reads b ops)) = filter not_read (lower ops).\n  Proof.\n    intros.\n    generalize (drop_b_reads_spec b ops); intro Hdrop.\n    erewrite Hdrop, filter_filter, filter_ext; eauto.\n    rewrite Forall_forall; clarify.\n    rewrite absoption_andb; auto.\n  Qed.\n\n  (* up? *)\n  Definition read_init_op (m : ilist mem_op) := forall i p v\n    (Hread : inth m i = Some (MRead p v)),\n    exists v', last_op (itake i m) (Ptr p) (MWrite p v').\n    \n  Lemma read_init_alt : forall m, read_init m <-> read_init_op m.\n  Proof.\n    intro; split; repeat intro.\n    - specialize (H i p v); clarify.\n      unfold last_op; eexists; eexists; split; eauto.\n      generalize (last_mod_lt _ H1); intro.\n      generalize (itake_length i m); intro.\n      rewrite inth_nth_error, itake_nth; destruct (lt_dec x i); eauto; omega.\n    - specialize (H i p v); clarify.\n      unfold last_op in *; clarify.\n      eexists; eexists; split; eauto.\n      rewrite inth_nth_error, itake_nth in *; clarify; eauto.\n  Qed.\n  (* This is a much better definition. *)\n\n  (* up *)\n  Lemma read_init_snoc : forall (m : list mem_op) op (Hread : read_init m),\n    read_init (m ++ [op]) <->\n      match op with\n      | MRead p v => exists v', last_op m (Ptr p) (MWrite p v')\n      | _ => True\n      end.\n  Proof.\n    intros; rewrite read_init_alt in *; split; intro.\n    - destruct op; clarify.\n      specialize (H (length m) p v);\n        rewrite inth_nth_error, nth_error_split in H; clarsimp; eauto.\n    - repeat intro; specialize (Hread i p v).\n      rewrite inth_nth_error, nth_error_app in *.\n      destruct (lt_dec i (length m)); clarify.\n      + exists x; clarsimp.\n        rewrite not_le_minus_0, app_nil_r; clarify; omega.\n      + rewrite nth_error_single in *; clarify.\n        exists x; clarsimp.\n        rewrite firstn_length'; auto; omega.\n  Qed.\n\n  (* up *)\n  Definition write_alloc_op (m : ilist mem_op) := forall i p v\n    (Hwrite : inth m i = Some (MWrite p v)),\n    (exists v', last_op (itake i m) (Ptr p) (MWrite p v')) \\/\n    (exists n, last_op (itake i m) (Ptr p) (MAlloc (fst p) n) /\\ snd p < n).\n    \n  Lemma write_alloc_alt : forall m, write_alloc m <-> write_alloc_op m.\n  Proof.\n    intro; split; intro Hw; repeat intro.\n    - specialize (Hw i p v); clarify.\n      generalize (lt_le_trans _ _ _ (last_mod_lt _ Hw1) (itake_length i m)).\n      unfold last_op; destruct Hw2; [left | right]; clarify.\n      + do 3 eexists; eauto.\n        rewrite inth_nth_error, itake_nth; clarify; eauto.\n      + do 2 eexists; eauto.\n        do 2 eexists; eauto.\n        rewrite inth_nth_error, itake_nth; clarify.\n    - specialize (Hw i p v); clarify.\n      unfold last_op in *; destruct Hw; clarify; do 2 eexists; eauto.\n      + rewrite inth_nth_error, itake_nth in *; clarify; eauto.\n      + rewrite inth_nth_error, itake_nth in *; clarify; eauto.\n  Qed.\n  (* This is a much better definition. *)\n\n  (* up *)\n  Lemma write_alloc_snoc : forall (m : list mem_op) op (Hwrite : write_alloc m),\n    write_alloc (m ++ [op]) <->\n      match op with\n      | MWrite p v => (exists v', last_op m (Ptr p) (MWrite p v')) \\/\n          exists n, last_op m (Ptr p) (MAlloc (fst p) n) /\\ snd p < n\n      | _ => True\n      end.\n  Proof.\n    intros; rewrite write_alloc_alt in *; split; intro.\n    - destruct op; clarify.\n      specialize (H (length m) p v);\n        rewrite inth_nth_error, nth_error_split in H; clarsimp; eauto.\n    - repeat intro; specialize (Hwrite i p v).\n      rewrite inth_nth_error, nth_error_app in *.\n      destruct (lt_dec i (length m)); clarify.\n      + destruct Hwrite; [left | right]; clarsimp;\n          rewrite not_le_minus_0, app_nil_r; clarify; eauto; omega.\n      + rewrite nth_error_single in *; clarify.\n        destruct H; [left | right]; clarsimp;\n          rewrite firstn_length'; eauto; omega.\n  Qed.\n\n  Lemma race_free_mods_read : forall m i j a p v o (Hrf : race_free m)\n    (Hdiff : i <> j)  (Hmods : mods m i (fst p, o)) (Ha : inth m j = Some a)\n    (Hread : In (MRead p v) (to_seq a)),\n    happens_before m i j \\/ happens_before m j i.\n  Proof.\n    intros; unfold mods in *; clarify.\n    eapply Hrf; eauto.\n    do 3 eexists; eauto.\n  Qed.\n\n  Lemma race_free_read : forall m r p v (Hread_init : read_init (lower m))\n    (Hcon : consistent m) (Hrf : race_free m)\n    (Hread : reads m r p v), exists w, writes m w p v /\\\n      happens_before m w r /\\\n      forall w2 v2, w2 < r -> writes m w2 p v2 -> hbe m w2 w.\n  Proof.\n    intros.\n    exploit read_write; eauto; intros [w Hw]; exists w; clarify.\n    generalize (Hrf w r); intro Hwr; clarify.\n    unfold reads, writes in *; clarify.\n    destruct p; specialize (Hwr _ _ Hw211 Hread1); use Hwr; clarify.\n    generalize (Hrf w w2); intro Hww.\n    unfold hbe; destruct (eq_dec w2 w); clarify; left.\n    specialize (Hww _ _ Hw211 H01); use Hww; clarify.\n    specialize (Hrf w2 r).\n    destruct (eq_dec w2 r); [omega | clarify].\n    specialize (Hrf _ _ H01 Hread1); use Hrf; clarify.\n    specialize (Hw221 w2 v2); use Hw221; [|eauto].\n    contradiction Hw221; clarify.\n    exploit hb_lt; eauto; omega.\n    - do 5 eexists; eauto; split; eauto; clarify.\n    - do 5 eexists; eauto; split; eauto; clarify.\n    - do 5 eexists; eauto; split; eauto; clarify.\n  Qed.\n\n  Lemma race_free_before : forall m1 c m2 i b o o' v\n    (Hrf : race_free (iapp m1 (icons c m2)))\n    (Hread : In (MRead (b, o') v) (to_seq c)) (Hmods : mods m1 i (b, o)),\n     happens_before (iapp m1 (icons c m2)) i (length m1).\n  Proof.\n    unfold mods; clarify.\n    rewrite inth_nth_error in *; exploit nth_error_lt; eauto; intro.\n    destruct (eq_dec i (length m1)); [omega|].\n    exploit race_free_mods_read; eauto; clarify.\n    { unfold mods; rewrite iapp_nth; clarify; eauto. }\n    { rewrite iapp_nth; clarsimp. }\n    exploit hb_lt; eauto; omega.\n  Qed.\n\n  Lemma race_free_after : forall m1 c m2 i b o o' v\n    (Hrf : race_free (iapp m1 (icons c m2)))\n    (Hread : In (MRead (b, o') v) (to_seq c)) (Hmods : mods m2 i (b, o)),\n    happens_before (iapp m1 (icons c m2)) (length m1) (i + length m1 + 1).\n  Proof.\n    unfold mods; clarify.\n    rewrite (plus_comm i); rewrite <- plus_assoc, NPeano.Nat.add_1_r.\n    destruct (eq_dec (length m1 + S i) (length m1)); [omega|].\n    exploit race_free_mods_read; eauto.\n    { unfold mods; rewrite iapp_nth, lt_dec_plus_r, minus_plus; clarify; eauto. \n    }\n    { rewrite iapp_nth; clarsimp. }\n    intro Hhb; clarify.\n    generalize (lt_plus _ (hb_lt Hhb)); clarify.\n  Qed.\n\n  (* We could let m be infinite and do \"for all prefixes\" instead if we want. *)\n  Theorem race_free_SC : forall (m : list _) (Hrf : race_free m)\n    (Hread : read_init (lower m)) (Hwrite : write_alloc (lower m))\n    (Hwf : well_formed m), consistent m <-> SC m.\n  Proof.\n    unfold SC; intros; split; intro Hcon.\n    - remember (length (filter (fun op => negb (not_read op)) (lower m)))\n        as nreads; generalize dependent m; induction nreads using lt_wf_ind;\n        intros.\n      destruct nreads.\n      { rewrite <- read_free; auto.\n        repeat intro.\n        unfold reads in *; clarify.\n        destruct (filter (fun op => negb (not_read op)) (lower m)) eqn: Hfilter;\n          clarify.\n        rewrite filter_none_iff in Hfilter.\n        rewrite Forall_forall in Hfilter.\n        setoid_rewrite flatten_in in Hfilter.\n        setoid_rewrite in_map_iff in Hfilter.\n        rewrite inth_nth_error in *; exploit nth_error_in; eauto; intro.\n        specialize (Hfilter (MRead p v)); use Hfilter; eauto; clarify. }\n      destruct (find has_read (rev m)) eqn: Hfind.\n      rewrite find_spec in Hfind; clarify.\n      exploit nth_error_rev'; eauto; intro Hnth.\n      unfold has_read in Hfind21; rewrite existsb_exists in Hfind21; clarify.\n      destruct x0; clarify.\n      exploit nth_error_split'; eauto; intros [m1 [m2 ?]]; clarify.\n      rewrite split_app in Hcon; rewrite <- app_assoc in Hcon;\n        repeat rewrite to_ilist_app in Hcon.\n      assert (read_init (filter (b_not_read (fst p)) (lower m1) ++\n        proj_block (to_seq c ++ []) (fst p))) as Hread0.\n      { rewrite split_app, lower_app in Hread.\n        generalize (read_init_app _ _ Hread); rewrite lower_app; intro Hr.\n        generalize (read_init_proj _ Hr (fst p));\n          setoid_rewrite proj_block_app at 1; intro Hr'.\n        generalize (read_init_filter' _ _ Hr'); unfold proj_block at 1;\n          rewrite filter_filter; clarify. }\n      assert (write_alloc (lower (m1 ++ [c]))) as Hwrite0.\n      { eapply write_alloc_app; rewrite split_app, lower_app in Hwrite; eauto. }\n      rewrite to_ilist_app in Hwf; erewrite private_seq in Hcon; clarify; eauto.\n      repeat rewrite <- to_ilist_app in *; clarify.\n      specialize (H (length (filter (fun op => negb (not_read op))\n        (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2))))).\n      use H.\n      specialize (H (m1 ++ drop_b_reads (fst p) [c] ++ m2)).\n      assert (read_init (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2)))\n        as Hread'.\n      { repeat rewrite lower_app in *; apply read_init_drop_b'.\n        rewrite <- lower_app; auto. }\n      assert (write_alloc (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2)))\n        as Hwrite'.\n      { repeat rewrite lower_app in *; apply write_alloc_drop_b'.\n        rewrite <- lower_app; auto. }\n      use H; clarify.\n      use H; clarify.\n      + rewrite split_app; rewrite <- app_assoc; eapply merge_SC; eauto.\n      + repeat rewrite to_ilist_app in *; apply drop_wf; auto.\n      + repeat rewrite to_ilist_app in *; apply drop_race_free; auto.\n      + rewrite Heqnreads; eapply drop_reads; eauto.\n      + destruct p; rewrite to_ilist_app in *; eapply race_free_before; eauto.\n      + unfold reads in *; clarify.\n        destruct i; clarify; [|rewrite inth_nil in *; clarify].\n        exploit race_free_read; eauto.\n        { rewrite to_ilist_app in *; auto. }\n        { unfold reads.\n          clear Hfind211; do 2 eexists; eauto.\n          instantiate (1 := length m1); rewrite inth_nth_error;\n            apply nth_error_split. }\n        intros [w Hw]; exists w; clarify.\n        rewrite plus_0_r; exploit hb_lt; eauto; clarify.\n        unfold writes in *; clarify.\n        rewrite inth_nth_error, nth_error_app in *; clarify.\n        split; eauto; clarify.\n        rewrite to_ilist_app in Hw22; eapply Hw22; auto.\n        rewrite inth_nth_error, nth_error_app, iapp_nth in *; clarify; eauto.\n      + rewrite NPeano.Nat.add_sub.\n        destruct p; rewrite to_ilist_app in *; eapply race_free_after; eauto.\n      + rewrite find_fail, Forall_rev in Hfind.\n        rewrite filter_none in Heqnreads; clarify.\n        rewrite Forall_forall in *; intros ? Hin.\n        setoid_rewrite flatten_in in Hin; clarify.\n        rewrite in_map_iff in Hin2; clarify.\n        specialize (Hfind _ Hin22); unfold has_read in *.\n        destruct x; clarify.\n        assert (existsb (fun op => negb (not_read op)) (to_seq x1) = true);\n          clarify.\n        rewrite existsb_exists; eauto.\n    - remember (length (filter (fun op => negb (not_read op)) (lower m)))\n        as nreads; generalize dependent m; induction nreads using lt_wf_ind;\n        intros.\n      destruct nreads.\n      { rewrite read_free; auto.\n        repeat intro.\n        unfold reads in *; clarify.\n        destruct (filter (fun op => negb (not_read op)) (lower m)) eqn: Hfilter;\n          clarify.\n        rewrite filter_none_iff in Hfilter.\n        rewrite Forall_forall in Hfilter.\n        setoid_rewrite flatten_in in Hfilter.\n        setoid_rewrite in_map_iff in Hfilter.\n        rewrite inth_nth_error in *; exploit nth_error_in; eauto; intro.\n        specialize (Hfilter (MRead p v)); use Hfilter; eauto; clarify. }\n      destruct (find has_read (rev m)) eqn: Hfind.\n      rewrite find_spec in Hfind; clarify.\n      exploit nth_error_rev'; eauto; intro Hnth.\n      unfold has_read in Hfind21; rewrite existsb_exists in Hfind21; clarify.\n      destruct x0; clarify.\n      exploit nth_error_split'; eauto; intros [m1 [m2 ?]]; clarify.\n      rewrite split_app; rewrite <- app_assoc; repeat rewrite to_ilist_app.\n      assert (read_init (filter (b_not_read (fst p)) (lower m1) ++\n        proj_block (lower [c]) (fst p))) as Hread0.\n      { rewrite split_app, lower_app in Hread.\n        generalize (read_init_app _ _ Hread); rewrite lower_app; intro Hr.\n        generalize (read_init_proj _ Hr (fst p));\n          setoid_rewrite proj_block_app at 1; intro Hr'.\n        generalize (read_init_filter' _ _ Hr'); unfold proj_block at 1;\n          rewrite filter_filter; clarify. }\n      assert (write_alloc (lower (m1 ++ [c]))) as Hwrite0.\n      { eapply write_alloc_app; rewrite split_app, lower_app in Hwrite; eauto. }\n      rewrite to_ilist_app in Hwf; erewrite private_seq; clarify; eauto 2.\n      repeat rewrite <- to_ilist_app; clarify.\n      split.\n      + assert (read_init (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2)))\n          as Hread'.\n        { repeat rewrite lower_app in *; apply read_init_drop_b'.\n          rewrite <- lower_app; auto. }\n        assert (write_alloc (lower (m1 ++ drop_b_reads (fst p) [c] ++ m2)))\n          as Hwrite'.\n        { repeat rewrite lower_app in *; apply write_alloc_drop_b'.\n          rewrite <- lower_app; auto. }\n        eapply H; try reflexivity; auto.\n        { rewrite Heqnreads; eapply drop_reads; eauto. }\n        { repeat rewrite to_ilist_app in *; apply drop_race_free; auto. }\n        { repeat rewrite to_ilist_app in *; apply drop_wf; auto. }\n        apply drop_SC; auto.\n      + setoid_rewrite consistent_split_reads in Hcon; auto;\n          destruct Hcon as [Hseq Hreads].\n        setoid_rewrite consistent_split_reads; auto.\n        * split.\n          { rewrite lower_app, lower_cons in Hread, Hwrite, Hseq.\n            generalize (consistent_proj _ (fst p) Hseq (read_init_none _)).\n            rewrite write_alloc_filter; intro Hcon; clarify.\n            rewrite proj_filter_comm, app_assoc in Hcon.\n            repeat setoid_rewrite proj_block_app in Hcon;\n              repeat rewrite filter_app in *.\n            rewrite lower_single; unfold proj_block at 1 in Hcon.\n            rewrite filter_filter in *.\n            erewrite filter_ext in Hcon; [eapply consistent_app; eauto|].\n            { rewrite Forall_forall; unfold b_not_read, andb; clarify. } }\n          intros ? ? ? Hr.\n          rewrite nth_error_app in Hr; destruct (lt_dec r\n            (length (filter (b_not_read (fst p)) (lower m1)))).\n          { exploit nth_error_in; eauto; rewrite filter_In; clarify. }\n          rewrite lower_single in Hr; unfold proj_block in Hr.\n          exploit nth_error_in; eauto; rewrite filter_In; intro Hin; clarify.\n          destruct p0 as (b', ?); unfold beq in Hin2; clarify.\n          exploit nth_filter_split; eauto; intros (l1 & l2 & Hc & Hlen & ?).\n          rewrite lower_app, lower_cons in Hreads; rewrite lower_single;\n            rewrite Hc in *.\n          rewrite <- app_assoc in Hreads; simpl in Hreads;\n            rewrite app_assoc in Hreads.\n          specialize (Hreads (length (lower m1 ++ l1)));\n            rewrite nth_error_split in Hreads.\n          specialize (Hreads _ _ eq_refl).\n          rewrite firstn_app, firstn_length, minus_diag in Hreads; clarify.\n          rewrite firstn_app, firstn_length', Hlen, proj_block_app,\n            firstn_app, firstn_length, minus_diag; [simpl | omega].\n          rewrite app_nil_r in *;\n            rewrite last_op_proj, proj_block_app in Hreads;\n            rewrite <- last_op_filter in Hreads; rewrite <- last_op_filter.\n          rewrite filter_app in *.\n          unfold proj_block at 1 in Hreads; rewrite filter_filter in *.\n          erewrite filter_ext in Hreads; eauto.\n          { rewrite Forall_forall; unfold b_not_read, andb; clarify. }\n        * rewrite lower_app in Hwrite0.\n          generalize (write_alloc_proj _ Hwrite0 (fst p)).\n          rewrite <- write_alloc_filter; setoid_rewrite proj_block_app;\n            intro Hw.\n          simpl; rewrite app_nil_r, lower_single in *.\n          rewrite <- write_alloc_filter; repeat rewrite filter_app in *.\n          unfold proj_block at 1 in Hw; rewrite filter_filter in *;\n            erewrite filter_ext; eauto.\n          { clear; rewrite Forall_forall; unfold b_not_read, andb; clarify. }\n      + destruct p; rewrite to_ilist_app in *; eapply race_free_before; eauto.\n      + setoid_rewrite consistent_split_reads in Hcon; clarify.\n        unfold reads in *; clarify.\n        destruct i; clarify; [|rewrite inth_nil in *; clarify].\n        clear Hfind211; exploit in_nth_error; eauto; intros [i Hi].\n        rewrite lower_app, lower_cons in Hcon2.\n        specialize (Hcon2 (length (lower m1) + i)); rewrite nth_error_app,\n          lt_dec_plus_r, minus_plus, nth_error_app in Hcon2; clarify.\n        specialize (Hcon2 _ _ Hi2).\n        destruct Hcon2 as [w Hw]; clarify.\n        rewrite inth_nth_error, nth_error_firstn in *; clarify.\n        rewrite nth_error_app in Hw2; destruct (lt_dec w (length (lower m1))).\n        exploit nth_lower_split; eauto; intros (l1' & ? & l2' & ? & ? & Hw & ?);\n          clarify.\n        generalize (nth_error_in _ _ Hw); intro.\n        exists (length l1'); rewrite plus_0_r; split;\n          [rewrite app_length; simpl; omega|].\n        unfold writes; rewrite <- app_assoc; simpl.\n        rewrite inth_nth_error, nth_error_split; split; [eauto|].\n        intros ? ? Hlt Hk; clarify.\n        specialize (Hrf k (length l1')); unfold hbe;\n          destruct (eq_dec k (length l1')); clarify; left.\n        rewrite inth_nth_error, nth_error_app in Hrf; clarify.\n        rewrite inth_nth_error, split_app in Hk1.\n        rewrite app_assoc in Hk1; rewrite <- (app_assoc l1'), nth_error_app\n          in Hk1; clarify.\n        rewrite <- app_assoc in Hrf; simpl in Hrf;\n          rewrite inth_nth_error, nth_error_split in Hrf.\n        specialize (Hrf _ _ Hk1 eq_refl); use Hrf.\n        rewrite split_app, app_assoc, to_ilist_app in Hrf; simpl in Hrf.\n        rewrite <- app_assoc in Hrf; clarify.\n        exploit hb_lt; eauto; intro.\n        inversion Hw1.\n        rewrite nth_error_app in Hk1; destruct (lt_dec k (length l1'));\n          [omega|].\n        destruct (k - length l1') eqn: Hminus; [omega | clarify].\n        setoid_rewrite firstn_app in Hlast; rewrite firstn_length' in Hlast;\n          [|auto with arith].\n        exploit nth_error_split'; eauto; intros (l3' & l4' & ?); clarify.\n        rewrite split_app, app_assoc, lower_app, lower_cons in Hlast.\n        repeat rewrite <- app_assoc in Hlast.\n        exploit in_nth_error; eauto; intros [i' Hi']; clarify.\n        exploit nth_error_lt; eauto; intro.\n        specialize (Hlast (length (lower (l1' ++ [x1] ++ l3')) + i'));\n          rewrite inth_nth_error, nth_error_app, lt_dec_plus_r, nth_error_app,\n          minus_plus in Hlast; clarify.\n        specialize (Hlast _ Hi'2); clarify.\n        rewrite lower_app, lower_cons in Hlast;\n          repeat rewrite app_length in Hlast.\n        generalize (nth_error_lt _ _ Hw); omega.\n        * do 5 eexists; eauto; split; eauto; clarify.\n        * generalize (read_safe _ Hi2); intro Hsafe.\n          specialize (Hsafe (w - length (lower m1))); use Hsafe; [|omega].\n          rewrite nth_error_app in Hw2; destruct (lt_dec (w - length (lower m1))\n            (length (to_seq x0))); [|omega].\n          exploit Hsafe; eauto; clarify.\n      + rewrite NPeano.Nat.add_sub.\n        destruct p; rewrite to_ilist_app in *; eapply race_free_after; eauto.\n      + rewrite find_fail, Forall_rev in Hfind.\n        rewrite filter_none in Heqnreads; clarify.\n        rewrite Forall_forall in *; intros ? Hin.\n        setoid_rewrite flatten_in in Hin; clarify.\n        rewrite in_map_iff in Hin2; clarify.\n        specialize (Hfind _ Hin22); unfold has_read in *.\n        destruct x; clarify.\n        assert (existsb (fun op => negb (not_read op)) (to_seq x1) = true);\n          clarify.\n        rewrite existsb_exists; eauto.\n  Qed.\n\n  Context (thread_eq : EqDec_eq thread).\n\n  Definition event_structure := thread -> list conc_op.\n  Definition evst_of (m : list conc_op) t :=\n    filter (fun c => beq (thread_of c) t) m.\n\n  Hypothesis alpha : forall (m : list _), consistent m ->\n    race_free m \\/ exists m', evst_of m' = evst_of m /\\ SC m' /\\ ~race_free m'.\n\n  Theorem race_free_SC' : forall E\n    (Hrf : forall m, evst_of m = E -> SC m -> race_free m)\n    m (HE : evst_of m = E)\n    (Hread : read_init (flatten (map to_seq m)))\n    (Hwrite : write_alloc (flatten (map to_seq m))) (Hwf : well_formed m),\n    consistent m <-> SC m.\n  Proof.\n    split; intros; [rewrite <- race_free_SC | rewrite race_free_SC]; auto.\n    generalize (alpha _ H); intros [? | [m' Hm']]; clarify.\n    specialize (Hrf m'); clarify.\n  Qed.\n    \nEnd Concurrency.", "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/conc_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.15947858946998714}}
{"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.\n\nSet Implicit Arguments.\n\n\nLemma computeParameters_isCalled_Some_F' b Lv ZL AP als D Z F s alb l\n      k k' x0 x1 Zs\n      (IH : forall k Zs,\n          get F k Zs ->\n          forall (ZL : \u3014params\u3015) (Lv AP : \u3014\u2983var\u2984\u3015) (lv : ann \u2983var\u2984)\n            (n : nat) (D : \u2983var\u2984) (Z : params) (p : \u061f \u2983var\u2984),\n            live_sound Imperative ZL Lv (snd Zs) lv ->\n            \u276cAP\u276d = \u276cLv\u276d ->\n            \u276cLv\u276d = \u276cZL\u276d ->\n            isCalled b (snd Zs) (LabI n) ->\n            get Lv n D ->\n            get ZL n Z ->\n            get (snd (computeParameters (Lv \\\\ ZL) AP (snd Zs) lv)) n p ->\n            exists Za : \u2983var\u2984, p = \u23a3 Za \u23a6 /\\ D \\ of_list Z \\ Za \u2286 getAnn lv)\n      (LEN1 : \u276cAP\u276d = \u276cLv\u276d) (LEN2 : \u276cLv\u276d = \u276cZL\u276d) (LEN3 : \u276cF\u276d = \u276cals\u276d)\n      (GetDL : get (getAnn \u229d als ++ Lv) l D) (GetZL : get (fst \u229d F ++ ZL) l Z)\n      (LS:live_sound Imperative (fst \u229d F ++ ZL) (getAnn \u229d als ++ Lv) s alb)\n      (LSF : forall (n : nat) (Zs : params * stmt) (a : ann \u2983var\u2984),\n          get F n Zs ->\n          get als n a ->\n          live_sound Imperative (fst \u229d F ++ ZL) (getAnn \u229d als ++ Lv) (snd Zs) a)\n      (INCL: forall (n : nat) (Zs : params * stmt) (a : ann \u2983var\u2984),\n          get F n Zs -> get als n a -> of_list (fst Zs) \u2286 getAnn a /\\ True)\n      (GetLV : get (olu F als Lv ZL AP s alb) l x0)\n      (GetF : get F k Zs) (GetAls : get als k x1)\n      (IC : isCalled b (snd Zs) (LabI k'))\n      (CC: callChain (isCalled b) F (LabI k') (LabI l))\n  :  exists Za : \u2983var\u2984,\n     addAdd\n       (list_union (oget \u229d take \u276cF\u276d (olu F als Lv ZL AP s alb))\n        \u222a list_union (fst \u2218 of_list \u229d F)) (D \\ of_list Z) x0 =\n     \u23a3 Za \u23a6 /\\\n     D \\ of_list Z \\ Za\n     \u2286 getAnn x1 \\ of_list (fst Zs) \\\n       (list_union (oget \u229d take \u276cF\u276d (olu F als Lv ZL AP s alb))\n                   \u222a list_union (fst \u2218 of_list \u229d F)).\nProof.\n  general induction CC.\n  - destruct (@get_in_range _ (snd\n                                 (computeParameters ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                                    (tab {} \u2016F\u2016 ++ AP) (snd Zs) x1)) l0)\n      as [pF GETpF].\n    rewrite computeParameters_length; [ |eauto | eauto with len | eauto with len].\n    eapply get_range in GetDL. eauto.\n    edestruct (IH k Zs); try eapply GETpF;\n      eauto using get_app_right, map_get_1 with len;\n      dcr; subst.\n    edestruct get_olist_union_A' as [? [? ?]]; try eapply GetLV;\n      eauto using map_get_1, zip_get.\n    eapply computeParametersF_length; eauto with len.\n    rewrite computeParameters_length; eauto with len.\n    subst; simpl. eexists; split; eauto.\n    rewrite <- H0, <- H1.\n    repeat rewrite minus_union.\n    assert (of_list (fst Zs) \u2286 list_union (fst \u2218 of_list \u229d F)). {\n      eapply incl_list_union. eapply map_get_1; eauto. reflexivity.\n    }\n    revert H; clear_all; cset_tac.\n  - inv_get.\n    exploit IHCC; try eapply H0; eauto.\n    dcr. eexists; split; eauto.\n    rewrite H5.\n    destruct (@get_in_range _ (snd\n                                 (computeParameters ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                                    (tab {} \u2016F\u2016 ++ AP) (snd Zs0) x1)) k'0)\n      as [pF' GETpF'].\n    rewrite computeParameters_length; [ |eauto | eauto with len | eauto with len].\n    rewrite app_length, map_length. eapply get_range in H1. omega.\n    exploit (IH k0 Zs0); try eapply GETpF'; eauto using get_app, map_get_1 with len.\n    dcr; subst. rewrite <- H7.\n    assert (x3 \u2286 list_union (oget \u229d take \u276cF\u276d\n                                  (olist_union (snd \u229d computeParametersF F als Lv ZL AP)\n                                               (snd\n                                                  (computeParameters\n                                                     ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                                     (tab {} \u2016F\u2016 ++ AP) s alb))))).\n    {\n      exploit (@get_olist_union_A _ _ (snd \u229d computeParametersF F als Lv ZL AP));\n        [| eapply GETpF' | | ]. instantiate (1:=k0).\n      eapply map_get_1. eapply zip_get_eq; [| | reflexivity]. eauto. eauto.\n      instantiate (1:=(snd\n                         (computeParameters ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                            (tab {} \u2016F\u2016 ++ AP) s alb))).\n      rewrite computeParameters_length; eauto.\n      eapply computeParametersF_length; eauto with len.\n      eauto with len. eauto with len.\n      dcr.\n      eapply incl_list_union. eapply map_get_1.\n      eapply get_take; try eapply H6; eauto using get_range. eauto.\n    }\n    rewrite H2.\n    assert (of_list (fst Zs0) \u2286 list_union (fst \u2218 of_list \u229d F)). {\n      eapply incl_list_union. eapply map_get_1.\n      instantiate (1:=Zs0). eauto. eauto.\n    }\n    revert H3; clear_all; cset_tac.\nQed.\n\nLemma computeParameters_isCalled_Some b ZL Lv AP s lv n D Z p\n  : live_sound Imperative ZL Lv s lv\n    -> length AP = length Lv\n    -> length Lv = length ZL\n    -> isCalled b s (LabI n)\n    -> get Lv n D\n    -> get ZL n Z\n    -> get (snd (computeParameters (Lv \\\\ ZL) AP s lv)) n p\n    -> exists Za, p = Some Za /\\ D \\ of_list Z \\ Za \u2286 (getAnn lv).\nProof.\n  revert ZL Lv AP lv n D Z p.\n  sind s; destruct s;\n    intros ZL Lv AP lv n D Z p LS LEN1 LEN2 IC GetDL GetZL GetLV;\n    simpl in * |- *; inv LS; invt isCalled;\n      repeat let_case_eq; repeat let_pair_case_eq; subst; simpl in *.\n  - edestruct (IH s) as [Za [A B]]; try eapply GetLV; eauto with len;\n      subst; simpl.\n    eexists; split; eauto.\n    inv_get.\n    exploit (@computeParameters_AP_LV Lv ZL (addParam x (Lv \\\\ ZL) AP));\n      try eapply H2; eauto with len.\n    PIR2_inv. unfold addParam in H3. inv_get.\n    rewrite <- H7.\n    revert H10 B. clear_all; cases; intros; cset_tac.\n  - inv_get.\n    edestruct (IH s1) as [? [? SUB]]; eauto; subst.\n    setoid_rewrite <- H8. setoid_rewrite <- SUB.\n    destruct x0;\n      eexists; simpl; split; eauto; clear_all; cset_tac.\n  - inv_get.\n    edestruct (IH s2) as [? [? SUB]]; eauto; subst.\n    setoid_rewrite <- H9. setoid_rewrite <- SUB.\n    destruct x;\n      eexists; simpl; split; eauto; clear_all; cset_tac.\n  - simpl in *. unfold keep in GetLV.\n    inv_get.\n    cases; eauto.\n    eexists; split; eauto.\n    rewrite <- H3. eauto with cset.\n  - lnorm. inv_get.\n    invc H4.\n    + exploit (computeParameters_length (tab {} \u2016F\u2016 ++ AP) H1) as Len;\n        [ eauto with len | eauto with len | ].\n      assert (LE:\u276cF\u276d + n < \u276csnd\n                           (computeParameters ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                              (tab {} \u2016F\u2016 ++ AP) s alb)\u276d).\n      rewrite Len, app_length, map_length. exploit (get_range GetDL). omega.\n      destruct (get_in_range _ LE) as [pF GETpF].\n      edestruct (IH s) with (AP:=tab {} \u2016F\u2016 ++ AP); eauto.\n      eauto with len. eauto with len.\n      eapply get_app_right; eauto using map_get_1.\n      eauto with len.\n      eapply get_app_right; eauto using map_get_1.\n      eauto with len.\n      dcr; subst.\n      edestruct (@get_olist_union_b _ _ (snd \u229d computeParametersF F als Lv ZL AP))\n        as [? [? ?]]; try eapply GETpF.\n      eapply computeParametersF_length; eauto.\n      get_functional.\n      eexists; split; try reflexivity.\n      rewrite <- H0, <- H8, <- H4.\n      clear_all; cset_tac.\n    + inv_get.\n      destruct (@get_in_range _ (snd\n                                   (computeParameters ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                                      (tab {} \u2016F\u2016 ++ AP) s alb)) k)\n        as [ps GETps]; eauto.\n      rewrite computeParameters_length; eauto with len.\n      exploit (IH s); try eapply GETps; eauto using get_app, map_get_1 with len.\n      dcr; subst.\n      setoid_rewrite <- H8. setoid_rewrite <- H13.\n      assert (x2 \u2286 list_union (oget \u229d take \u276cF\u276d\n                                    (olist_union (snd \u229d computeParametersF F als Lv ZL AP)\n                                                 (snd\n                                                    (computeParameters\n                                                       ((getAnn \u229d als ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                                       (tab {} \u2016F\u2016 ++ AP) s alb))))\n                 \u222a list_union (fst \u2218 of_list \u229d F)). {\n        exploit (@get_olist_union_b _ _ (snd \u229d computeParametersF F als Lv ZL AP));\n          try eapply GETps.\n        eapply computeParametersF_length; eauto with len.\n        rewrite computeParameters_length; eauto with len.\n        dcr. eapply incl_union_left.\n        eapply incl_list_union. eapply map_get_1.\n        eapply get_take; eauto using get_range.\n        eauto.\n      }\n      clear H8 H13 LS GETps. setoid_rewrite H10. clear H7 H10.\n      eapply computeParameters_isCalled_Some_F'; eauto.\n      intros. eapply (IH (snd Zs0)); eauto.\n      eapply get_app_right; eauto. eauto with len.\n      eapply get_app_right; eauto. eauto with len.\n      intros; edestruct H6; eauto.\nQed.\n\nLemma computeParameters_isCalled_get_Some b Lv ZL AP s lv n p A D Z\n  : live_sound Imperative ZL Lv s lv\n    -> length AP = length Lv\n    -> length Lv = length ZL\n    -> isCalled b s (LabI n)\n    -> n < \u276csnd (computeParameters (Lv \\\\ ZL) AP s lv)\u276d\n    -> get Lv n D\n    -> get ZL n Z\n    -> get (olist_union A (snd (computeParameters (Lv \\\\ ZL) AP s lv))) n p\n    -> (forall (n0 : nat) (a : \u3014\u061f\u2983var\u2984\u3015),\n          get A n0 a -> \u276ca\u276d = \u276csnd (computeParameters (Lv \\\\ ZL) AP s lv)\u276d)\n    -> exists Za, p = Some Za /\\ D \\ of_list Z \\ Za \u2286 (getAnn lv).\nProof.\n  intros LS LEN1 LEN2 IC LE GETDL GETZL GET LEN3.\n  destruct (get_in_range _ LE); eauto.\n  edestruct computeParameters_isCalled_Some; eauto; dcr; subst.\n  edestruct get_olist_union_b; eauto; dcr.\n  get_functional.\n  eexists; split; try reflexivity. rewrite <- H1, <- H2; eauto.\nQed.\n\nLemma computeParameters_isCalledFrom_get_Some b Lv ZL AP F alv s lv p Da Zs l\n      (LSF : forall (n : nat) (Zs : params * stmt) (a : ann \u2983var\u2984),\n          get F n Zs ->\n          get alv n a ->\n          live_sound Imperative (fst \u229d F ++ ZL) (getAnn \u229d alv ++ Lv) (snd Zs) a)\n       (INCL: forall (n : nat) (Zs : params * stmt) (a : ann \u2983var\u2984),\n          get F n Zs -> get alv n a -> of_list (fst Zs) \u2286 getAnn a /\\ True)\n  : live_sound Imperative (fst \u229d F ++ ZL) (getAnn \u229d alv ++ Lv) s lv\n    -> length AP = length Lv\n    -> length Lv = length ZL\n    -> length F = length alv\n    -> isCalledFrom (isCalled b) F s (LabI l)\n    -> get alv l Da\n    -> get F l Zs\n    -> get (olist_union (snd \u229d computeParametersF F alv Lv ZL AP)\n                       (snd (computeParameters ((getAnn \u229d alv ++ Lv) \\\\ (fst \u229d F ++ ZL))\n                                               (tab {} \u2016F\u2016 ++ AP)\n                                               s lv))) l p\n    -> exists Za, p = Some Za /\\ getAnn Da \\ of_list (fst Zs) \\ Za \\\n                                 list_union (oget \u229d take \u276cF\u276d (olu F alv Lv ZL AP s lv))\n                                 \\ list_union (fst \u2218 of_list \u229d F) \u2286 (getAnn lv).\nProof.\n  intros LS LEN1 LEN2 LEN3 [[n] [IC CC]] GETDL GETZL GET.\n  exploit callChain_range' as LE; eauto using get_range. simpl in *.\n  assert (NLE:n < \u276csnd (computeParameters ((getAnn \u229d alv ++ Lv)\n                                     \\\\ (fst \u229d F ++ ZL))\n                                  (tab {} \u2016F\u2016 ++ AP) s lv)\u276d).\n  rewrite computeParameters_length; eauto with len.\n  destruct (get_in_range _ NLE); eauto.\n  assert (LE':n < \u276cgetAnn \u229d alv ++ Lv\u276d).\n  rewrite app_length, map_length. omega.\n  destruct (get_in_range _ LE'); eauto.\n  assert (LE'':n < \u276cfst \u229d F ++ ZL\u276d).\n  rewrite app_length, map_length. omega.\n  destruct (get_in_range _ LE''); eauto.\n  edestruct computeParameters_isCalled_Some; try eapply g; eauto; dcr; subst.\n  eauto with len. eauto with len.\n  edestruct get_olist_union_b; eauto; dcr.\n  intros.\n  eapply computeParametersF_length; eauto.\n  eapply computeParameters_length; eauto with len.\n  setoid_rewrite <- H1.\n  inv CC.\n  - inv_get. eexists; split; eauto.\n    rewrite H2. clear_all; cset_tac.\n  - inv_get.\n    exploit computeParameters_isCalled_Some_F'; try eapply H4; try eapply H5;\n      eauto using get_app, map_get_1.\n    intros. eapply computeParameters_isCalled_Some; eauto.\n    dcr. destruct p; simpl in *; invc H8.\n    eexists; split; [ reflexivity | ].\n    rewrite H2.\n    assert (Incl:x \u2286  (list_union (oget \u229d take \u276cF\u276d (olu F alv Lv ZL AP s lv))\n                             \u222a list_union (fst \u2218 of_list \u229d F))). {\n      eapply incl_union_left.\n      eapply incl_list_union.\n      eapply map_get_1. eapply get_take; eauto using get_range. reflexivity.\n    }\n    rewrite Incl. rewrite <- H9.\n    rewrite union_comm.\n    rewrite <- minus_union.\n    clear_all; 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/Coherence/DelocationAlgoIsCalled.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3140505385717077, "lm_q1q2_score": 0.1594785894699871}}
{"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Cop Ctypes ClightC.\nRequire Import AsmC.\nRequire SimMemInjInvC.\nRequire Import MutrecB MutrecBspec MutrecBproof.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import AsmregsC.\nRequire Import MatchSimModSem.\nRequire Import StoreArguments.\nRequire Import AsmStepInj IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import CtypingC.\nRequire Import CopC.\n\nRequire Import MatchSimModSem ModSemProps.\nRequire Import Conventions1C.\n\nRequire Import IdSimExtra IdSimInvExtra.\nRequire Import mktac.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nInductive match_states_b_internal:\n  state -> state -> meminj -> mem -> mem -> Prop :=\n| match_Callstate\n    i m_src m_tgt j\n  :\n    match_states_b_internal\n      (Callstate i m_src)\n      (Callstate i m_tgt)\n      j m_src m_tgt\n| match_Interstate\n    i m_src m_tgt j\n  :\n    match_states_b_internal\n      (Interstate i m_src)\n      (Interstate i m_tgt)\n      j m_src m_tgt\n| match_Returnstate\n    i m_src m_tgt j\n  :\n    match_states_b_internal\n      (Returnstate i m_src)\n      (Returnstate i m_tgt)\n      j m_src m_tgt\n.\n\nSection INJINV.\n\nVariable P: SimMemInjInv.memblk_invariant.\n\nLocal Instance SimMemP: SimMem.class := SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P.\nLocal Instance SimSymbP: SimSymb.class SimMemP := SimMemInjInvC.SimSymbIdInv P.\n\nLocal Existing Instance SoundTop.Top.\n\nInductive match_states_b_inv\n  : unit -> state -> state -> SimMem.t -> Prop :=\n| match_states_a_intro\n    st_src st_tgt j m_src m_tgt sm0\n    (MWFSRC: m_src = sm0.(SimMem.src))\n    (MWFTGT: m_tgt = sm0.(SimMem.tgt))\n    (MWFINJ: j = sm0.(SimMemInjInv.minj).(SimMemInj.inj))\n    (MATCHST: match_states_b_internal st_src st_tgt j m_src m_tgt)\n    (MWF: SimMem.wf sm0)\n  :\n    match_states_b_inv\n      tt st_src st_tgt sm0\n.\n\nLemma b_inj_inv_id\n      (WF: Sk.wf (MutrecBspec.module))\n  :\n    exists mp,\n      (<<SIM: ModPair.sim mp>>)\n      /\\ (<<SRC: mp.(ModPair.src) = (MutrecBspec.module)>>)\n      /\\ (<<TGT: mp.(ModPair.tgt) = (MutrecBspec.module)>>)\n.\nProof.\n  eexists (ModPair.mk _ _ _); s.\n  esplits; eauto. instantiate (1:=SimMemInjInvC.mk bot1 _ _).\n  econs; ss; i.\n  { econs; ss; i; clarify. }\n  eapply match_states_sim with (match_states := match_states_b_inv); ss.\n  - apply unit_ord_wf.\n  - eapply SoundTop.sound_state_local_preservation.\n\n  - i. ss.\n    cinv SIMSKENV. ss.\n    exploit (@SimSymbIdInv_match_globals fundef _ _ sm_arg (MutrecBspec.module) (MutrecBspec.module) (SkEnv.project skenv_link_src (Sk.of_program fn_sig prog)) (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig prog)) prog).\n    { eauto. } intros GEMATCH.\n    inv INITTGT. inv SAFESRC. inv SIMARGS. inv H. ss.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des.\n    clarify.\n    esplits; eauto.\n    + econs; eauto.\n    + refl.\n    + econs; eauto.\n      assert (i = i0).\n      { inv VALS. inv H2. auto. }\n      subst. econs; eauto.\n    + ss.\n\n  - i. ss.\n    cinv SIMSKENV. ss.\n    exploit (@SimSymbIdInv_match_globals fundef _ _ sm_arg (MutrecBspec.module) (MutrecBspec.module) (SkEnv.project skenv_link_src (Sk.of_program fn_sig prog)) (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig prog)) prog).\n    { eauto. } intros GEMATCH.\n    des. inv SAFESRC. inv SIMARGS.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des; eauto.\n    esplits. econs; ss; eauto.\n    + clear -MWF INJ FPTR FPTR0.\n      rewrite FPTR in FPTR0. inv FPTR0; ss.\n      rewrite H1 in INJ. clarify.\n    + rewrite VS in VALS. inv VALS; ss. inv H3. inv H1. auto.\n    + ss.\n\n  - i. ss. inv MATCH; eauto.\n\n  - i. ss. clear SOUND. inv CALLSRC. inv MATCH. inv MATCHST. inversion SIMSKENV; subst. ss.\n    i. ss. cinv SIMSKENV. ss.\n    exploit (@SimSymbIdInv_match_globals fundef _ _ sm0 (MutrecBspec.module) (MutrecBspec.module) (SkEnv.project skenv_link_src (Sk.of_program fn_sig prog)) (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig prog)) prog).\n    { eauto. } intros GEMATCH.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des; eauto.\n    esplits; eauto.\n    + econs; ss; eauto.\n    + econs; ss; econs; eauto.\n    + refl.\n    + instantiate (1:=top4). ss.\n\n  - i. ss. clear SOUND HISTORY.\n    exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n    inv AFTERSRC. inv MATCH. inv MATCHST.\n    esplits; eauto.\n    + econs; eauto. inv SIMRET; ss. rewrite INT in *. inv RETV. ss.\n    + inv SIMRET; ss. econs; eauto. econs; eauto.\n    + refl.\n\n  - i. ss. inv FINALSRC. inv MATCH. inv MATCHST.\n    esplits; eauto.\n    + econs.\n    + econs; eauto. econs.\n    + refl.\n\n  - right. ii. des.\n    esplits.\n    + i. inv MATCH. inv MATCHST.\n      * unfold ModSem.is_step. do 2 eexists. ss. econs; eauto.\n      * unfold safe_modsem in H.\n        exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n      * ss. exfalso. eapply NOTRET. econs. ss.\n    + ii. inv STEPTGT; inv MATCH; inv MATCHST.\n      * esplits; eauto.\n        { left. eapply plus_one. econs. }\n        refl.\n        econs; eauto. econs.\n      * esplits; eauto.\n        { left. eapply plus_one. econs 2. eauto. }\n        refl.\n        econs; eauto. econs.\nQed.\n\nEnd INJINV.\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/IdSimMutrecBIdInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.26894142136999516, "lm_q1q2_score": 0.15939259779016984}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Export logrel.\n\nSection fundamental.\n Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {stsg : STSG Addr region_type \u03a3} {heapg : heapG \u03a3}\n          `{MonRef: MonRefG (leibnizO _) CapR_rtc \u03a3} {nainv: logrel_na_invs \u03a3}\n          `{MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n  Notation WORLD := (prodO STS_STD STS). \n  Implicit Types W : WORLD.\n\n  Notation D := (WORLD -n> (leibnizO Word) -n> iProp \u03a3).\n  Notation R := (WORLD -n> (leibnizO Reg) -n> iProp \u03a3).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n\n  Definition ftlr_instr (W : WORLD) (r : leibnizO Reg) (p p' : Perm)\n        (g : Locality) (b e a : Addr) (w : Word) (i: instr) (\u03c1 : region_type) := \n      p = RX \u2228 p = RWX \u2228 (p = RWLX /\\ g = Local)\n    \u2192 (\u2200 x : RegName, is_Some (r !! x))\n    \u2192 isCorrectPC (inr (p, g, b, e, a))\n    \u2192 (b <= a)%a \u2227 (a < e)%a\n    \u2192 PermFlows p p'\n    \u2192 (if pwl p then region_state_pwl W a else region_state_nwl W a g)\n    \u2192 std W !! a = Some \u03c1\n    \u2192 \u03c1 \u2260 Revoked \u2227 (\u2200 m, \u03c1 \u2260 Static m)\n    \u2192 p' \u2260 O\n    \u2192 decodeInstrW w = i\n    -> \u25a1 \u25b7 (\u2200 a0 a1 a2 a3 a4 a5 a6,\n             full_map a1\n          -\u2217 (\u2200 r1 : RegName, \u231cr1 \u2260 PC\u231d \u2192 ((fixpoint interp1) a0) (a1 !r! r1))\n          -\u2217 registers_mapsto (<[PC:=inr (a2, a3, a4, a5, a6)]> a1)\n          -\u2217 region a0\n          -\u2217 sts_full_world a0\n          -\u2217 na_own logrel_nais \u22a4\n          -\u2217 \u231ca2 = RX \u2228 a2 = RWX \u2228 (a2 = RWLX /\\ a3 = Local)\u231d\n             \u2192 \u25a1 ([\u2217 list] a7 \u2208 region_addrs a4 a5, \u2203 p'0 : Perm, \u231cPermFlows a2 p'0\u231d \u2217 read_write_cond a7 p'0 interp                                                                             \u2227 \u231cif pwl a2\n                                                                        then region_state_pwl a0 a7\n                                                                        else region_state_nwl a0 a7 a3\u231d)\n                 -\u2217 interp_conf a0)\n    -\u2217 ([\u2217 list] a0 \u2208 region_addrs b e, \u2203 p'0 : Perm,\n                                           \u231cPermFlows p p'0\u231d\n                                        \u2217 read_write_cond a0 p'0 interp\n                                        \u2227 \u231cif pwl p\n                                           then region_state_pwl W a0\n                                           else region_state_nwl W a0 g\u231d)\n    -\u2217 (\u2200 r1 : RegName, \u231cr1 \u2260 PC\u231d \u2192 ((fixpoint interp1) W) (r !r! r1))\n    -\u2217 read_write_cond a p' interp\n    -\u2217 (\u25b7 if decide (\u03c1 = Temporary \u2227 pwl p' = true)\n        then future_pub_mono (\u03bb Wv : WORLD * (leibnizO Word), ((fixpoint interp1) Wv.1) Wv.2) w\n        else future_priv_mono (\u03bb Wv : WORLD * (leibnizO Word), ((fixpoint interp1) Wv.1) Wv.2) w)\n    -\u2217 \u25b7 ((fixpoint interp1) W) w\n    -\u2217 sts_full_world W\n    -\u2217 na_own logrel_nais \u22a4\n    -\u2217 open_region a W\n    -\u2217 sts_state_std a \u03c1\n    -\u2217 a \u21a6\u2090[p'] w\n    -\u2217 PC \u21a6\u1d63 inr (p, g, b, e, a)\n    -\u2217 ([\u2217 map] k\u21a6y \u2208 delete PC (<[PC:=inr (p, g, b, e, a)]> r), k \u21a6\u1d63 y)\n    -\u2217\n        WP Instr Executable\n        {{ v, WP Seq (cap_lang.of_val v)\n                 {{ v0, \u231cv0 = HaltedV\u231d\n                        \u2192 \u2203 (r1 : Reg) (W' : WORLD),\n                        full_map r1\n                        \u2227 registers_mapsto r1\n                                           \u2217 \u231crelated_sts_priv_world W W'\u231d\n                                           \u2217 na_own logrel_nais \u22a4\n                                           \u2217 sts_full_world W' \u2217 region W' }} }}.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise-stack", "sha": "f68111362730aff998798d63c7d6a0a7176eff44", "save_path": "github-repos/coq/logsem-cerise-stack", "path": "github-repos/coq/logsem-cerise-stack/cerise-stack-f68111362730aff998798d63c7d6a0a7176eff44/theories/ftlr/ftlr_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.15928078630189058}}
{"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 Import PTIntroGenSpec.\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    (** ** The low level specifications exist*)\n    Section Exists.\n\n      Lemma setCR3_exist:\n        forall habd habd' labd m n s f,\n          setPT'_spec n habd = Some habd'\n          -> high_level_invariant habd\n          -> relate_RData f habd labd\n          -> match_RData s habd m f\n          -> exists labd', setCR30_spec labd (GLOBP PTPool_LOC (Int.repr (n * PgSize)))\n                           = Some labd' /\\ relate_RData f habd' labd'\n                           /\\ PT habd' = n\n                           /\\ ptpool habd' = ptpool habd\n                           /\\ pperm habd' = pperm habd\n                           /\\ idpde habd' = idpde habd\n                           /\\ CR3 labd' = (GLOBP PTPool_LOC (Int.repr (n * PgSize)))\n                           /\\ 0 <= n < num_proc.\n      Proof.\n        unfold setPT'_spec, setCR30_spec; intros until f.\n        intros HP HINV HR HM; pose proof HR as HR'; inv HR; revert HP;\n        subrewrite'; intros HQ; inv HINV; subdestruct;\n        destruct (CR3_valid_dec\n                    (GLOBP PTPool_LOC (Int.repr (n * 4096)))).\n        - (* ipt = true /\\ valid CR3*)\n          inv HQ; refine_split'; eauto.\n          inv HR'. econstructor; eauto; simpl.\n          econstructor; eauto.\n          rewrite Int.unsigned_repr. omega.\n          rewrite int_max. omega.\n        - elim n0; unfold CR3_valid; eauto.\n        - (* ipt = false /\\ valid CR3 *)\n          inv HQ; refine_split'; eauto.\n          inv HR'. econstructor; eauto; simpl.\n          econstructor; eauto.\n          rewrite Int.unsigned_repr. omega.\n          rewrite int_max. omega.\n        - elim n0; unfold CR3_valid; eauto.\n      Qed.\n\n    End Exists.\n\n    Ltac pattern2_refinement_simpl:=  \n      pattern2_refinement_simpl' (@relate_AbData).\n\n    Section FRESH_PRIM.\n\n      Lemma setPT_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem setPT'_spec) setPT_spec_low.\n      Proof. \n        compatsim_simpl (@match_AbData).\n        assert(HOS: kernel_mode d2).\n        {\n          simpl; inv match_related.\n          functional inversion H1; subst;\n          refine_split'; trivial; congruence.\n        }\n        exploit setCR3_exist; eauto; intros (labd' & HP & HM & HN1 & HN2 & HN3 & Hide & HCR3 & Hrange).\n        refine_split; eauto.\n        econstructor; eauto.\n        pose proof match_related as match_relate'.\n        inv match_related.          \n        split; eauto; pattern2_refinement_simpl. \n        econstructor; eauto; subrewrite'.\n      Qed.\n\n      Lemma getPDE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem getPDE_spec) getPDE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData). \n        assert(HOS: kernel_mode d2 \n                    /\\ 0 <= Int.unsigned i < num_proc\n                    /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned).\n        {\n          simpl; inv match_related.\n          unfold getPDE_spec in *.\n          unfold PDE_Arg in *.\n          subdestruct; refine_split'; trivial; congruence.\n        }\n        destruct HOS as [Hkern [Hrange Hrange']].\n        generalize H; intros HMAT. inv H. specialize (H1 _ Hrange).\n        inv H1. specialize (H _ Hrange').\n        destruct H as (v & HLD & _ & HM).\n        assert (HVint: exists v', Vint v' = v /\\ Int.unsigned z = Int.unsigned v' / PgSize).\n        {\n          functional inversion H2.\n          - subst pt. rewrite H8 in HM. inv HM.\n            refine_split'; trivial. subrewrite'.\n            rewrite Zplus_comm.\n            rewrite Z_div_plus. reflexivity.\n            omega.\n          - subst pt. rewrite H8 in HM. inv HM.\n            refine_split'; trivial. \n        }\n        destruct HVint as (v' & Heq & Heq'); subst.\n        refine_split; eauto.\n        econstructor; eauto.\n      Qed.\n\n      Lemma getPTE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem getPTE_spec) getPTE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData). \n        assert(HOS: kernel_mode d2 \n                    /\\ 0 <= Int.unsigned i < num_proc\n                    /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                    /\\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned).\n        {\n          simpl; inv match_related.\n          unfold getPTE_spec in *. \n          unfold PTE_Arg in *. unfold PDE_Arg in *.\n          subdestruct; refine_split'; trivial; congruence.\n        }\n        destruct HOS as (Hkern & Hrange & Hrange' & Hrange'').\n        generalize H; intros HMAT. inv H. specialize (H1 _ Hrange).\n        inv H1. specialize (H _ Hrange').\n        destruct H as (v & HLD & _ & HM).\n        assert (HVint: exists v1 v2, Vint v1 = v /\\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU /\\\n                                     fload'_spec (v2 * one_k + Int.unsigned i1) d2 = Some (Int.unsigned z)).\n        { \n          unfold getPTE_spec in *.\n          destruct (ikern d1') eqn: Hik; contra_inv.\n          destruct (ihost d1') eqn: Hih; contra_inv.\n          destruct (init d1') eqn: Hii; contra_inv.\n          destruct (ipt d1') eqn: Hit; contra_inv.\n          destruct (PTE_Arg (Int.unsigned i) (Int.unsigned i0) (Int.unsigned i1)); contra_inv.\n          destruct (ZMap.get (Int.unsigned i0) (ZMap.get (Int.unsigned i) (ptpool d1'))) eqn: HT; contra_inv.\n          inv HM. exploit relate_PMap_re; eauto 1. intros HPMap.\n          inv HPMap. specialize (H _ Hrange _ Hrange' _ _ HT _ Hrange'').\n          destruct H as (v' & HLD' & HM).\n          assert (HLD'': fload'_spec (pi * one_k + Int.unsigned i1) d2 = Some (Int.unsigned z)).\n          {\n            unfold fload'_spec. inv match_related. rewrite <- ikern_re, <- ihost_re.\n            rewrite Hik, Hih.\n            assert (HOS: 0 <= pi * 4096 + 7 <= Int.max_unsigned).\n            {\n              specialize (Int.unsigned_range_2 v0). subrewrite'.\n            }\n            rewrite zle_lt_true.\n            - replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.\n              destruct (ZMap.get (Int.unsigned i1) pte); contra_inv; inv HM; inv H2.\n              + refine_split'; trivial. \n                rewrite H7. apply PermZ_eq in H6. rewrite H6. trivial.\n              + refine_split'; trivial.\n            - revert HOS Hrange''. clear.\n              intros. rewrite_omega.\n          }\n          refine_split'; eauto 1. \n        }\n        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Heq4).\n        refine_split; eauto 1.\n        econstructor; eauto.\n      Qed.\n\n      Lemma setPTE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem setPTE_spec) setPTE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: exists p0,\n                         kernel_mode d2\n                         /\\ 0 <= Int.unsigned i < num_proc\n                         /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                         /\\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned\n                         /\\ 0 < Int.unsigned i2 < nps d2\n                         /\\ ZtoPerm (Int.unsigned i3) = Some p0\n                         /\\ PT d1' = PT d1).\n        {\n          inv match_related. functional inversion H1; subst.\n          unfold PTE_Arg, PDE_Arg in *. subdestruct.\n          refine_split'; try congruence; eauto.\n        }\n        destruct Hkern as (perm & Hkern & Hrange & Hrange' & Hrange'' & Hrange''' & HPerm & HPT).\n        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.\n        specialize (H _ Hrange'); destruct H as [v[HLD [HV HM]]].\n        assert (HVint: exists v1 v2, Vint v1 = v /\\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU\n                                     /\\ match_RData s d1' m2 \u03b9\n                                     /\\ init d2 = true\n                                     /\\ exists d2', fstore0_spec  (v2 * one_k + Int.unsigned i1) \n                                                                  (Int.unsigned i2 * PgSize + Int.unsigned i3) d2\n                                                    = Some d2'\n                                                    /\\ relate_RData \u03b9 d1' d2').\n        { \n          unfold setPTE_spec in *. subdestruct.\n          inv HM. esplit; esplit. split; [reflexivity|]. split; [eassumption|]. split; [|split].\n          - (* match_RData *)\n            constructor; inv H1; simpl; trivial. \n            econstructor; eauto 1; intros.\n            destruct (zeq n0 (Int.unsigned i)); subst.\n            + (* n = Int.unsigned i *)           \n              rewrite ZMap.gss. constructor; intros.\n              destruct (zeq i4 (Int.unsigned i0)); subst.\n              * (* i4 = Int.unsigned i0 *)   \n                rewrite ZMap.gss. refine_split'; eauto 1.\n                constructor; eauto; intros.\n              * (* i4 <> Int.unsigned i0 *)   \n                rewrite ZMap.gso; eauto 2.\n                specialize (HMAT _ Hrange). inv HMAT.\n                eapply H2; eauto 2.\n            + (* n <> int.unsigned i*)\n              rewrite ZMap.gso; eauto 2.\n          - inv match_related. congruence.                \n          - (* fstore /\\ relate RData *)\n            unfold fstore0_spec. inv match_related.\n            rewrite <- ikern_re, <- ihost_re. rewrite Hdestruct, Hdestruct0.\n            assert (HOS: 0<= pi * 4096 + 7 <= Int.max_unsigned).\n            {\n              specialize (Int.unsigned_range_2 v0). subrewrite'. \n            }\n            rewrite zle_lt_true.\n            + replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.\n              unfold flatmem_store. unfold PageI.                 \n              replace ((pi * 4096 + Int.unsigned i1 * 4) / 4096) with pi.\n              * pose proof (pperm_re pi) as HPP.\n                rewrite H10 in HPP. inv HPP. trivial.\n                refine_split'; eauto 1.\n                inv H1. constructor; trivial; simpl; try congruence.\n                { (* FlatMem *)\n                  unfold FlatMem.flatmem_inj in *.\n                  intros; rewrite valid_dirty; [| assumption| eassumption]. \n                  eapply FlatMem.store_unmapped_inj; eauto 1.\n                  simpl. rewrite_omega.\n                }\n                { (* PMap *) \n                  constructor; intros. inv relate_PMap_re. \n                  destruct (zeq n0 (Int.unsigned i)); subst.\n                  - (* n = Int.unsigned i *)           \n                    rewrite ZMap.gss in H4. \n                    destruct (zeq i4 (Int.unsigned i0)); subst.\n                    + (* i4 = Int.unsigned i0 *)   \n                      rewrite ZMap.gss in H4. inv H4. \n                      destruct (zeq vadr (Int.unsigned i1)); subst.\n                      * (* vadr = Int.unsigned i1 *)\n                        rewrite ZMap.gss. rewrite FlatMem.load_store_same.\n                        refine_split'; trivial.\n                        econstructor; eauto. apply Int.unsigned_repr.\n                        apply ZtoPerm_range in Hdestruct6.\n                        exploit valid_nps; eauto. rewrite nps_re.\n                        rewrite_omega.\n                      * (* vadr <> Int.unsigned i1 *)              \n                        rewrite ZMap.gso; auto. erewrite FlatMem.load_store_other; eauto 2.\n                        simpl. destruct (zle (vadr + 1) (Int.unsigned i1)).\n                        left; omega. right; omega.\n                    + (* i4 <> Int.unsigned i0 *)\n                      rewrite ZMap.gso in H4; auto. \n                      assert (Hneq: pi <> pi0).\n                      {\n                        red; intros; subst.\n                        specialize (HMAT _ Hrange). inv HMAT.\n                        specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).\n                        rewrite H4 in HMAT. inv HMAT. congruence.\n                      }\n                      erewrite FlatMem.load_store_other; eauto 2. simpl.\n                      destruct (zle (pi0 + 1) pi); rewrite_omega. \n                  - (* n <> int.unsigned i*)              \n                    rewrite ZMap.gso in H4; auto. \n                    assert (Hneq: pi <> pi0).\n                    {\n                      red; intros; subst.\n                      specialize (HMAT _ H1). inv HMAT.\n                      specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).\n                      unfold PMap, ZMap.t, PMap.t in HMAT.\n                      rewrite H4 in HMAT. inv HMAT. congruence.\n                    }\n                    erewrite FlatMem.load_store_other; eauto 2. simpl. \n                    destruct (zle (pi0 + 1) pi); rewrite_omega.\n                }\n\n              * rewrite Zplus_comm.\n                rewrite Z_div_plus. rewrite Zdiv_small. reflexivity.\n                revert Hrange''. clear; intros. rewrite_omega. omega.\n            + rewrite_omega.\n        }\n        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Hma & Hinit &  d2' & HST & Hre); subst.\n        exists \u03b9, Vundef, (fst (m2, d2)), d2'.\n        refine_split; eauto 1.\n        - econstructor; eauto 1.\n        - split; eauto; pattern2_refinement_simpl. \n      Qed.\n\n      Lemma rmvPTE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem rmvPTE_spec) rmvPTE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: kernel_mode d2\n                       /\\ 0 <= Int.unsigned i < num_proc\n                       /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                       /\\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned\n                       /\\ PT d1' = PT d1).\n        {\n          inv match_related. functional inversion H1; subst.\n          unfold PTE_Arg, PDE_Arg in *. subdestruct.\n          refine_split'; try congruence; eauto.\n        }\n        destruct Hkern as [Hkern [Hrange [Hrange' [Hrange'' HPT]]]].\n        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.\n        specialize (H _ Hrange'); destruct H as [v[HLD [HV HM]]].\n        assert (HVint: exists v1 v2, Vint v1 = v /\\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU\n                                     /\\ match_RData s d1' m2 \u03b9\n                                     /\\ exists d2', fstore0_spec (v2 * one_k + Int.unsigned i1) 0 d2 = Some d2'\n                                                    /\\ relate_RData \u03b9 d1' d2').\n        { \n          unfold rmvPTE_spec in *. subdestruct.\n          inv HM. esplit; esplit. split; [reflexivity|]. split; [eassumption|]. split.\n          - (* match_RData *)\n            constructor; inv H1; simpl; trivial. econstructor; eauto 1; intros.\n            destruct (zeq n0 (Int.unsigned i)); subst.\n            + (* n = Int.unsigned i *)           \n              rewrite ZMap.gss. constructor; intros.\n              destruct (zeq i2 (Int.unsigned i0)); subst.\n              * (* i2 = Int.unsigned i0 *)   \n                rewrite ZMap.gss. refine_split'; eauto 1.\n                constructor; eauto; intros.\n              * (* i2 <> Int.unsigned i0 *)   \n                rewrite ZMap.gso; eauto 2.\n                specialize (HMAT _ Hrange). inv HMAT.\n                eauto 2.\n            + (* n <> int.unsigned i*)\n              rewrite ZMap.gso; eauto 2.\n              \n          - (* fstore /\\ relate RData *)\n            unfold fstore0_spec. inv match_related.\n            rewrite <- ikern_re, <- ihost_re. rewrite Hdestruct, Hdestruct0.\n            assert (HOS: 0<= pi * 4096 + 7 <= Int.max_unsigned).\n            {\n              specialize (Int.unsigned_range_2 v0). subrewrite'.\n            }\n            rewrite zle_lt_true.\n            + replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.\n              unfold flatmem_store. unfold PageI.                 \n              replace ((pi * 4096 + Int.unsigned i1 * 4) / 4096) with pi.\n              * pose proof (pperm_re pi) as HPP.\n                rewrite H10 in HPP. inv HPP.\n                refine_split'; eauto 1.\n                inv H1. constructor; trivial; simpl; try congruence.\n                { (* FlatMem *)\n                  unfold FlatMem.flatmem_inj in *.\n                  intros; rewrite valid_dirty; [| assumption| eassumption]. \n                  eapply FlatMem.store_unmapped_inj; eauto 1.\n                  simpl. rewrite_omega.\n                }\n                { (* PMap *) \n                  constructor; intros. inv relate_PMap_re. \n                  destruct (zeq n0 (Int.unsigned i)); subst.\n                  - (* n = Int.unsigned i *)           \n                    rewrite ZMap.gss in H4. \n                    destruct (zeq i2 (Int.unsigned i0)); subst.\n                    + (* i2 = Int.unsigned i0 *)   \n                      rewrite ZMap.gss in H4. inv H4. \n                      destruct (zeq vadr (Int.unsigned i1)); subst.\n                      * (* vadr = Int.unsigned i1 *)\n                        rewrite ZMap.gss. rewrite FlatMem.load_store_same.\n                        refine_split'; trivial.\n                        econstructor; eauto. \n                      * (* vadr <> Int.unsigned i1 *)              \n                        rewrite ZMap.gso; auto. erewrite FlatMem.load_store_other; eauto 2.\n                        simpl. destruct (zle (vadr + 1) (Int.unsigned i1)).\n                        left; omega. right; omega.\n                    + (* i2 <> Int.unsigned i0 *)\n                      rewrite ZMap.gso in H4; auto. \n                      assert (Hneq: pi <> pi0).\n                      {\n                        red; intros; subst.\n                        specialize (HMAT _ Hrange). inv HMAT.\n                        specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).\n                        rewrite H4 in HMAT. inv HMAT. congruence.\n                      }\n                      erewrite FlatMem.load_store_other; eauto 2.\n                      simpl. destruct (zle (pi0 + 1) pi); rewrite_omega.\n                  - (* n <> int.unsigned i*)              \n                    rewrite ZMap.gso in H4; auto. \n                    assert (Hneq: pi <> pi0).\n                    {\n                      red; intros; subst.\n                      specialize (HMAT _ H1). inv HMAT.\n                      specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).\n                      unfold PMap, ZMap.t, PMap.t in HMAT.\n                      rewrite H4 in HMAT. inv HMAT. congruence.\n                    }\n                    erewrite FlatMem.load_store_other; eauto 2.\n                    simpl. destruct (zle (pi0 + 1) pi); rewrite_omega.\n                }\n\n              * rewrite Zplus_comm.\n                rewrite Z_div_plus. rewrite Zdiv_small. reflexivity.\n                revert Hrange''. clear; intros. rewrite_omega. omega.\n            + rewrite_omega.\n        }\n        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Hma & d2' & HST & Hre); subst.\n        exists \u03b9, Vundef, (fst (m2, d2)), d2'.\n        refine_split; eauto 1.\n        - econstructor; eauto 1.\n        - split; eauto; pattern2_refinement_simpl.\n      Qed.\n\n      Lemma setPDEU_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem setPDEU_spec) setPDEU_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: kernel_mode d2\n                       /\\ 0 <= Int.unsigned i < num_proc\n                       /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                       /\\ 0 < Int.unsigned i1 < nps d2\n                       /\\ PT d1' = PT d1\n                       /\\ init d2 = true).\n        {\n          inv match_related. \n          unfold setPDEU_spec in *.\n          unfold PDE_Arg in *.\n          subdestruct; refine_split'; trivial; try congruence.\n          inv H1. reflexivity.\n        }\n        destruct Hkern as (Hkern & Hrange & Hrange' & Hrange'' & HPT & Hinit).\n        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.\n        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]].\n        specialize (Mem.valid_access_store _ _ _ _ \n                                           (Vint (Int.repr (Int.unsigned i1 * PgSize + PT_PERM_PTU)))\n                                           HV); intros [m0 HST].\n        refine_split; eauto.\n        - econstructor; eauto.\n          simpl; lift_trivial. rewrite HST. reflexivity.\n        - pose proof H1 as Hspec.\n          functional inversion Hspec; subst; simpl in *.\n          split; eauto 1; pattern2_refinement_simpl.           \n          + inv match_related; simpl in *; split; simpl; try eassumption.\n            { (* Flatmem *)\n              apply FlatMem.free_page_inj. assumption.\n            }\n            { (* PPermT_les *)\n              intros j. specialize (pperm_re j).\n              destruct (zeq j (Int.unsigned i1)); subst.\n              - rewrite ZMap.gss. rewrite H10 in pperm_re.\n                inv pperm_re. constructor.\n              - rewrite ZMap.gso; eauto 2.\n            }\n            { (* PMapPool *)\n              subst pt'. constructor; intros.\n              destruct (zeq n (Int.unsigned i)); subst.             \n              { (* n = int.unsigned i*)\n                rewrite ZMap.gss in H12.\n                destruct (zeq i2 (Int.unsigned i0)); subst.\n                { (* i2 = Int.unsigned i0 *)\n                  rewrite ZMap.gss in H12.                  \n                  inv H12. rewrite ZMap.gi. \n                  refine_split'; eauto 2. constructor.\n                }\n                { (* i2 <> Int.unsigned i0 *)                    \n                  rewrite ZMap.gso in H12; eauto 1.\n                  inv relate_PMap_re. eauto.\n                }\n              }\n              { (* n <> int.unsigned i*)              \n                rewrite ZMap.gso in H12; eauto 1.\n                inv relate_PMap_re. eauto.\n              }\n            }\n            \n          + econstructor; eauto 1; simpl in *.\n            {\n              econstructor; eauto 1; intros.\n              * destruct (zeq n (Int.unsigned i)); subst.\n                { (* n = int.unsigned i*)\n                  rewrite ZMap.gss.\n                  specialize (HMAT _ H). inv HMAT.\n                  constructor; intros.\n                  specialize (H11 _ H12).\n                  destruct (zeq i2 (Int.unsigned i0)); subst.\n                  { (* i2 = Int.unsigned i0 *)\n                    refine_split'.\n                    - eapply Mem.load_store_same; eauto.\n                    - eapply Mem.store_valid_access_1; eauto.\n                    - subst pt'; repeat rewrite ZMap.gss.\n                      constructor; intros.\n                      + rewrite Int.unsigned_repr. reflexivity.\n                        exploit valid_nps; eauto 1.\n                        intros. rewrite_omega.\n                      + rewrite ZMap.gss. reflexivity.\n                  }\n                  { (* i1 <> Int.unsigned i0 *)                    \n                    destruct H11 as [v1[HL1[HV1 HM1]]].\n                    refine_split'.\n                    - erewrite Mem.load_store_other; eauto.\n                      right; simpl.\n                      destruct (zle (i2 + 1) (Int.unsigned i0)).\n                      + left. revert n l. clear. intros. omega.\n                      + right. revert n g. clear. intros. omega. \n                    - eapply Mem.store_valid_access_1; eauto.\n                    - subst pt'. rewrite ZMap.gso; auto.\n                      inv HM1; constructor; intros; eauto 1.\n                      + destruct (zeq pi (Int.unsigned i1)); subst.\n                        * congruence.\n                        * rewrite ZMap.gso; eauto 1.\n                  }\n                }\n                { (* n <> int.unsigned i*)              \n                  constructor; intros. rewrite ZMap.gso; auto.\n                  specialize (HMAT _ H). inv HMAT.\n                  specialize (H12 _ H11); destruct H12 as [v1[HL1[HV1 HM1]]].\n                  refine_split'.\n                  - erewrite Mem.load_store_other; eauto.\n                    right; simpl.\n                    destruct (zle (n + 1) (Int.unsigned i)).\n                    + left. rewrite_omega.\n                    + right. rewrite_omega.\n                  - eapply Mem.store_valid_access_1; eauto.\n                  - unfold PMap, ZMap.t, PMap.t in HM1. \n                    inv HM1; econstructor; intros; eauto 1.    \n                    + destruct (zeq pi (Int.unsigned i1)); subst.\n                      * congruence. \n                      * rewrite ZMap.gso; eauto 1.\n                }\n            }\n            {\n              inv H0. esplit; eauto. intros.\n              specialize (H _ H0 _ H12).\n              destruct H as (v & HLD & HV' & HM).\n              erewrite Mem.load_store_other; eauto.\n              - refine_split'; eauto.\n                eapply Mem.store_valid_access_1; eauto.\n              - left. red; intros; subst.\n                specialize (genv_vars_inj _ _ _ _ H3 H11).\n                intros. inv H.\n            }\n      Qed.\n\n      Lemma rmvPDE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem rmvPDE_spec) rmvPDE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: kernel_mode d2\n                       /\\ 0 <= Int.unsigned i < num_proc\n                       /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                       /\\ PT d1' = PT d1\n                       /\\ idpde d1' = idpde d1).\n        {\n          inv match_related. \n          unfold rmvPDE_spec in *.\n          unfold PDE_Arg in *.\n          subdestruct; refine_split'; trivial; try congruence;\n          inv H1; reflexivity.\n        }\n        destruct Hkern as (Hkern & Hrange & Hrange' & HPT & Hipde).\n        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.\n        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]].\n        specialize (Mem.valid_access_store _ _ _ _ \n                                           (Vint (Int.repr PT_PERM_UP))\n                                           HV); intros [m0 HST].\n        refine_split; eauto.\n        - econstructor; eauto.\n          simpl; lift_trivial. rewrite HST. reflexivity.\n        - pose proof H1 as Hspec.\n          assert (Hre_ab: relate_AbData s \u03b9 d1' d2).\n          {\n            inv match_related. \n            assert (HP: relate_PMapPool\n                          (ZMap.set (Int.unsigned i)\n                                    (ZMap.set (Int.unsigned i0) PDEUnPresent\n                                              (ZMap.get (Int.unsigned i) (ptpool d1))) \n                                    (ptpool d1)) (HP d2)).\n            {\n              constructor; intros.\n              destruct (zeq n (Int.unsigned i)); subst.             \n              { (* n = int.unsigned i*)\n                rewrite ZMap.gss in H4.\n                destruct (zeq i1 (Int.unsigned i0)); subst.\n                { (* i1 = Int.unsigned i0 *)\n                  rewrite ZMap.gss in H4. inv H4.\n                }\n                { (* i2 <> Int.unsigned i0 *)                    \n                  rewrite ZMap.gso in H4; eauto 1.\n                  inv relate_PMap_re. eauto.\n                }\n              }\n              { (* n <> int.unsigned i*)              \n                rewrite ZMap.gso in H4; eauto 1.\n                inv relate_PMap_re. eauto.\n              }\n            }\n            functional inversion Hspec; subst;\n            split; trivial; simpl in *; contra_inv.\n            { (* PPermT_les *)\n              intros j. specialize (pperm_re j).\n              destruct (zeq j pi); subst.\n              - rewrite ZMap.gss. rewrite H12 in pperm_re.\n                inv pperm_re. constructor.\n              - rewrite ZMap.gso; eauto 2.\n            }\n            { (* PPermT_les *)\n              intros j. specialize (pperm_re j).\n              destruct (zeq j pi); subst.\n              - rewrite ZMap.gss. rewrite H11 in pperm_re.\n                inv pperm_re. constructor.\n              - rewrite ZMap.gso; eauto 2.\n            }\n          }\n          assert (Hma_ab:  match_AbData s d1' m0 \u03b9).\n          {\n            econstructor; eauto 1; simpl in *.\n            {\n              econstructor; eauto 1; intros. pose proof HMAT as HMAT'.\n              specialize (HMAT _ H). \n              assert(HP: forall pp,\n                           (forall pi0 a1 a2, ZMap.get pi0 (pperm d1) = PGHide (PGPMap a1 a2) ->\n                                              (a1 <> Int.unsigned i \\/ a2 <> Int.unsigned i0) ->\n                                              ZMap.get pi0 pp = PGHide (PGPMap a1 a2)) ->\n                           match_PMap s (ZMap.get n (ZMap.set (Int.unsigned i)\n                                                              (ZMap.set (Int.unsigned i0) PDEUnPresent\n                                                                        (ZMap.get (Int.unsigned i) (ptpool d1))) \n                                                              (ptpool d1))) pp m0 b n).\n              { \n                intros.\n                * destruct (zeq n (Int.unsigned i)); subst.\n                  { (* n = int.unsigned i*)\n                    rewrite ZMap.gss. inv HMAT.\n                    constructor; intros.\n                    specialize (H4 _ H5).\n                    destruct (zeq i1 (Int.unsigned i0)); subst.\n                    { (* i1 = Int.unsigned i0 *)\n                      refine_split'.\n                      - eapply Mem.load_store_same; eauto.\n                      - eapply Mem.store_valid_access_1; eauto.\n                      - repeat rewrite ZMap.gss.\n                        constructor.\n                    }\n                    { (* i1 <> Int.unsigned i0 *)                    \n                      destruct H4 as [v1[HL1[HV1 HM1]]].\n                      refine_split'.\n                      - erewrite Mem.load_store_other; eauto.\n                        right; simpl.\n                        destruct (zle (i1 + 1) (Int.unsigned i0)).\n                        + left. omega.\n                        + right. omega. \n                      - eapply Mem.store_valid_access_1; eauto.\n                      - rewrite ZMap.gso; auto.\n                        inv HM1; constructor; intros; eauto.\n                    }\n                  }\n                  { (* n <> int.unsigned i*)              \n                    constructor; intros. rewrite ZMap.gso; auto.\n                    inv HMAT. specialize (H5 _ H4); destruct H5 as [v1[HL1[HV1 HM1]]].\n                    refine_split'.\n                    - erewrite Mem.load_store_other; eauto.\n                      right; simpl.\n                      destruct (zle (n + 1) (Int.unsigned i)).\n                      + left. rewrite_omega.\n                      + right. rewrite_omega.\n                    - eapply Mem.store_valid_access_1; eauto.\n                    - unfold PMap, ZMap.t, PMap.t in HM1. \n                      inv HM1; econstructor; intros; eauto.    \n                  }\n              } \n              functional inversion Hspec; subst; simpl in *;          \n              subst pt'; eapply HP; eauto 1; contra_inv.\n              {\n                intros. destruct (zeq pi0 pi); subst.\n                - specialize (HMAT' _ Hrange). inv HMAT'.\n                  specialize (H15 _ Hrange').\n                  destruct H15 as (? & _ & _ & HM).\n                  rewrite H12 in HM. inv HM.\n                  destruct H14; congruence. \n                - rewrite ZMap.gso; eauto 1.\n              }\n              {\n                intros. destruct (zeq pi0 pi); subst.\n                - specialize (HMAT' _ Hrange). inv HMAT'.\n                  specialize (H14 _ Hrange').\n                  destruct H14 as (? & _ & _ & HM).\n                  rewrite H11 in HM. inv HM.\n                  destruct H13; congruence. \n                - rewrite ZMap.gso; eauto 1.\n              }\n            }\n            {\n              inv H0. rewrite Hipde. esplit; eauto. intros.\n              specialize (H _ H0 _ H4).\n              destruct H as (v & HLD & HV' & HM).\n              erewrite Mem.load_store_other; eauto.\n              - refine_split'; eauto.\n                eapply Mem.store_valid_access_1; eauto.\n              - left. red; intros; subst.\n                specialize (genv_vars_inj _ _ _ _ H3 H2).\n                intros. inv H.\n            }\n          }\n          split; eauto 1; pattern2_refinement_simpl.\n      Qed.\n\n      Lemma setPDE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem setPDE_spec) setPDE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: kernel_mode d2\n                       /\\ 0 <= Int.unsigned i < num_proc\n                       /\\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned\n                       /\\ PT d1' = PT d1).\n        {\n          inv match_related. \n          unfold setPDE_spec in *.\n          unfold PDE_Arg in *.\n          subdestruct; refine_split'; trivial; try congruence.\n          inv H1. reflexivity.\n        }\n        destruct Hkern as (Hkern & Hrange & Hrange' & HPT).\n        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.\n        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]]. inv H0.\n        specialize (Mem.valid_access_store _ _ _ _ \n                                           (Vptr b0 (Int.repr (Int.unsigned i0 * PgSize + PT_PERM_PTU)))\n                                           HV); intros [m0 HST].\n        refine_split; eauto.\n        - econstructor; eauto.\n          simpl; lift_trivial. rewrite HST. reflexivity.\n        - pose proof H1 as Hspec.\n          functional inversion Hspec; subst; simpl in *.\n          split; eauto 1; pattern2_refinement_simpl.           \n          + inv match_related; simpl in *; split; simpl; try eassumption.\n            { (* PMapPool *)\n              subst pt'. constructor; intros.\n              destruct (zeq n (Int.unsigned i)); subst.             \n              { (* n = int.unsigned i*)\n                rewrite ZMap.gss in H11.\n                destruct (zeq i1 (Int.unsigned i0)); subst.\n                { (* i1 = Int.unsigned i0 *)\n                  rewrite ZMap.gss in H11.                  \n                  inv H11.\n                }\n                { (* i1 <> Int.unsigned i0 *)                    \n                  rewrite ZMap.gso in H11; eauto 1.\n                  inv relate_PMap_re. eauto.\n                }\n              }\n              { (* n <> int.unsigned i*)              \n                rewrite ZMap.gso in H11; eauto 1.\n                inv relate_PMap_re. eauto.\n              }\n            }\n            \n          + econstructor; eauto 1; simpl in *.\n            {\n              econstructor; eauto 1; intros.\n              * destruct (zeq n (Int.unsigned i)); subst.\n                { (* n = int.unsigned i*)\n                  rewrite ZMap.gss.\n                  specialize (HMAT _ H0). inv HMAT.\n                  constructor; intros.\n                  specialize (H10 _ H11).\n                  destruct (zeq i1 (Int.unsigned i0)); subst.\n                  { (* i1 = Int.unsigned i0 *)\n                    refine_split'.\n                    - eapply Mem.load_store_same; eauto.\n                    - eapply Mem.store_valid_access_1; eauto.\n                    - subst pt'; repeat rewrite ZMap.gss.\n                      constructor; intros; eauto.\n                      rewrite Int.unsigned_repr. reflexivity.\n                      rewrite_omega.\n                  }\n                  { (* i1 <> Int.unsigned i0 *)                    \n                    destruct H10 as [v1[HL1[HV1 HM1]]].\n                    refine_split'.\n                    - erewrite Mem.load_store_other; eauto.\n                      right; simpl.\n                      destruct (zle (i1 + 1) (Int.unsigned i0)).\n                      + left. omega.\n                      + right. omega. \n                    - eapply Mem.store_valid_access_1; eauto.\n                    - subst pt'. rewrite ZMap.gso; auto.\n                  }\n                }\n                { (* n <> int.unsigned i*)              \n                  constructor; intros. rewrite ZMap.gso; auto.\n                  specialize (HMAT _ H0). inv HMAT.\n                  specialize (H11 _ H10); destruct H11 as [v1[HL1[HV1 HM1]]].\n                  refine_split'.\n                  - erewrite Mem.load_store_other; eauto.\n                    right; simpl.\n                    destruct (zle (n + 1) (Int.unsigned i)).\n                    + left. rewrite_omega.\n                    + right. rewrite_omega.\n                  - eapply Mem.store_valid_access_1; eauto.\n                  - unfold PMap, ZMap.t, PMap.t in HM1. \n                    inv HM1; econstructor; intros; eauto 1.    \n                }\n            }\n            {\n              esplit; eauto. intros.\n              specialize (H _ H0 _ H10).\n              destruct H as (v & HLD & HV' & HM).\n              erewrite Mem.load_store_other; eauto.\n              - refine_split'; eauto.\n                eapply Mem.store_valid_access_1; eauto.\n              - left. red; intros; subst.\n                specialize (genv_vars_inj _ _ _ _ H3 H2).\n                intros. inv H.\n            }\n      Qed.\n\n      Lemma pt_in_spec_ref:\n        compatsim (crel HDATA LDATA) (primcall_general_compatsem' \n                                        ptin'_spec (prim_ident:= pt_in)) pt_in_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData); intros.\n        inv match_extcall_states.\n        assert(HOS: kernel_mode d2).\n        {\n          simpl; inv match_related.\n          functional inversion H8; subst;\n          refine_split'; trivial; try congruence.\n        }\n        refine_split'; eauto.\n        econstructor; eauto.\n        - specialize (match_reg PC). unfold Pregmap.get in *.\n          rewrite H7 in match_reg.\n          inv match_reg.\n          exploit inject_forward_equal'; eauto.\n          intros HW; inv HW.\n          rewrite Int.add_zero. reflexivity.\n        - functional inversion H8; subst.\n          pose proof match_related as match_relate'.\n          inv match_related.\n          split; eauto; pattern2_refinement_simpl. \n          + econstructor; eauto.\n            econstructor; eauto.\n            inv match_match.\n            econstructor; eauto.\n          + val_inject_simpl.\n      Qed.\n\n      Lemma pt_out_spec_ref:\n        compatsim (crel HDATA LDATA) (primcall_general_compatsem' \n                                        ptout_spec (prim_ident:= pt_out)) pt_out_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData); intros.\n        inv match_extcall_states.\n        assert(HOS: kernel_mode d2).\n        {\n          simpl; inv match_related.\n          functional inversion H8; subst;\n          refine_split'; trivial; try congruence.\n        }\n        refine_split'; eauto.\n        econstructor; eauto.\n        - eapply reg_symbol_inject; eassumption.\n        - functional inversion H8; subst.\n          pose proof match_related as match_relate'.\n          inv match_related.          \n          split; eauto; pattern2_refinement_simpl. \n          + econstructor; eauto.\n            econstructor; eauto.\n            inv match_match.\n            econstructor; eauto.\n          + val_inject_simpl.\n      Qed.\n\n      Lemma setIDPTE_spec_ref:\n        compatsim (crel HDATA LDATA) (gensem setIDPTE_spec) setIDPTE_spec_low.\n      Proof.\n        compatsim_simpl (@match_AbData).\n        assert (Hkern: kernel_mode d2\n                       /\\ 0 <= Int.unsigned i <= PDX Int.max_unsigned\n                       /\\ 0 <= Int.unsigned i0 <= PTX Int.max_unsigned\n                       /\\ PT d1' = PT d1\n                       /\\ exists p0, ZtoPerm (Int.unsigned i1) = Some p0).\n        {\n          inv match_related. \n          unfold setIDPTE_spec in *.\n          unfold IDPTE_Arg in *.\n          subdestruct; refine_split'; trivial; try congruence. \n          inv H1. reflexivity.\n        }\n        destruct Hkern as (Hkern & Hrange & Hrange' & HPT & p0 & Hipde).\n        inv H0. generalize H2; intros HMAT. specialize (H2 _ Hrange _ Hrange').\n        destruct H2 as [_[_ [HV _]]].\n        specialize (Mem.valid_access_store _ _ _ _ \n                                           (Vint (Int.repr ((Int.unsigned i * 1024 + Int.unsigned i0) * 4096 +\n                                                            Int.unsigned i1)))\n                                           HV); intros [m0 HST].\n        refine_split; eauto.\n        - econstructor; eauto.\n          simpl; lift_trivial. rewrite HST. reflexivity.\n        - pose proof H1 as Hspec.\n          functional inversion Hspec; subst; simpl in *.\n          split; eauto 1; pattern2_refinement_simpl.           \n          + inv match_related; simpl in *; split; simpl; try eassumption.            \n          + econstructor; eauto 1; simpl in *.\n            {\n              inv H. esplit; eauto. intros.\n              specialize (H0 _ H). inv H0.\n              split; intros. specialize (H11 _ H0).\n              destruct H11 as (v & HLD & HV' & HM).\n              erewrite Mem.load_store_other; eauto.\n              - refine_split'; eauto.\n                eapply Mem.store_valid_access_1; eauto.\n              - left. red; intros; subst.\n                specialize (genv_vars_inj _ _ _ _ H3 H10).\n                intros. contra_inv.\n            }\n            {\n              econstructor; eauto 1; intros. subst pde'.\n              * destruct (zeq i2 (Int.unsigned i)); subst. \n                { (* i2 = int.unsigned i*)\n                  rewrite ZMap.gss.\n                  specialize (HMAT _ H0). \n                  destruct (zeq j (Int.unsigned i0)); subst.\n                  { (* j = Int.unsigned i0 *)\n                    rewrite ZMap.gss. refine_split'.\n                    - eapply Mem.load_store_same; eauto.\n                    - eapply Mem.store_valid_access_1; eauto.\n                    - simpl. econstructor; eauto.\n                      rewrite Int.unsigned_repr. reflexivity.\n                      exploit ZtoPerm_range; eauto. intros.\n                      rewrite_omega.\n                  }\n                  { (* j <> Int.unsigned i0 *)                    \n                    specialize (HMAT _ H10).\n                    destruct HMAT as [v1[HL1[HV1 HM1]]].\n                    refine_split'.\n                    - erewrite Mem.load_store_other; eauto.\n                      right; simpl.\n                      destruct (zle (j + 1) (Int.unsigned i0)).\n                      + left. omega.\n                      + right. omega. \n                    - eapply Mem.store_valid_access_1; eauto.\n                    - rewrite ZMap.gso; auto.\n                  }\n                }\n                { (* i2 <> int.unsigned i*)              \n                  rewrite ZMap.gso; auto.\n                  specialize (HMAT _ H0 _ H10). \n                  destruct HMAT as [v1[HL1[HV1 HM1]]].\n                  refine_split'; eauto.\n                  - erewrite Mem.load_store_other; eauto.\n                    right; simpl.\n                    destruct (zle (i2 + 1) (Int.unsigned i)).\n                    + left. rewrite_omega.\n                    + right. rewrite_omega.\n                  - eapply Mem.store_valid_access_1; eauto.\n                }\n            }\n      Qed.\n\n    End FRESH_PRIM.\n\n  End WITHMEM.\n\nEnd Refinement.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/PTIntroGenFresh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.15917569992961322}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of VM: PIPC                                     *)\n(*                                                                     *)\n(*          Provide the abstraction of ipc channel                     *)\n(*                                                                     *)\n(*          Haozhong Zhang <haozhong.zhang@yale.edu>                   *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the PIPC layer,\nwhich will introduce the primtives of thread*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\nRequire Import INVLemmaProc.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjFlatMem.\nRequire Export ObjContainer.\nRequire Export ObjVMM.\nRequire Export ObjLMM.\nRequire Export ObjShareMem.\nRequire Export ObjThread.\nRequire Export ObjProc.\nRequire Export ObjSyncIPC.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** **Definition of the invariants at MPTNew layer*)\n  (** [0th page map] is reserved for the kernel thread*)\n  Record high_level_invariant (abd: RData) :=\n    mkInvariant {\n        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;\n        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);\n        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);\n        valid_kern: ipt abd = false -> pg abd = true;\n        valid_iptt: ipt abd = true -> ikern abd = true; \n        valid_iptf: ikern abd = false -> ipt abd = false; \n        valid_ihost: ihost abd = false -> pg abd = true /\\ ikern abd = true;\n        valid_container: Container_valid (AC abd);\n        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);\n        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;\n        valid_PMap: pg abd = true -> \n                    (forall i, 0<= i < num_proc ->\n                               PMap_valid (ZMap.get i (ptpool abd)));\n        (* 0th page map is reserved for the kernel thread*)          \n        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;\n        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));\n        valid_PT: pg abd = true -> 0<= PT abd < num_proc;\n        valid_dirty: dirty_ppage (pperm abd) (HP abd);\n\n        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);\n        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);\n\n        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;\n\n        valid_TCB: pg abd = true -> AbTCBStrong_range (abtcb abd);\n        valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);\n        valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);\n        valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);\n        valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd);\n        valid_curid: 0 <= cid abd < num_proc;\n        correct_curid: pg abd = true -> CurIDValid (cid abd) (AC abd) (abtcb abd);\n        single_curid: pg abd = true -> SingleRun (cid abd) (abtcb abd);\n        (*valid_chan: pg abd = true -> ChanPool_Valid (chpool abd)*)\n        valid_chan: pg abd = true -> SyncChanPool_Valid (syncchpool abd)\n      }.\n\n  (** ** Definition of the abstract state ops *)\n  Global Instance pipc_data_ops : CompatDataOps RData :=\n    {\n      empty_data := init_adt;\n      high_level_invariant := high_level_invariant;\n      low_level_invariant := low_level_invariant;\n      kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n      observe := ObservationImpl.observe\n    }.\n\n  (** ** Proofs that the initial abstract_data should satisfy the invariants*)    \n  Section Property_Abstract_Data.\n\n    Lemma empty_data_high_level_invariant:\n      high_level_invariant init_adt.\n    Proof.\n      constructor; simpl; intros; auto; try inv H.\n      - apply empty_container_valid.\n      - eapply Lconsistent_ppage_init.\n      - eapply dirty_ppage_init.\n      - eapply consistent_pmap_init.\n      - eapply consistent_pmap_domain_init.\n      - eapply consistent_lat_domain_init.\n      - repeat rewrite ZMap.gi; intuition.\n    Qed.\n\n    (** ** Definition of the abstract state *)\n    Global Instance pipc_data_prf : CompatData RData.\n    Proof.\n      constructor.\n      - apply low_level_invariant_incr.\n      - apply empty_data_low_level_invariant.\n      - apply empty_data_high_level_invariant.\n    Qed.\n\n  End Property_Abstract_Data.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Section ALLOC.\n      \n      Lemma alloc_high_level_inv:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0. constructor; simpl; eauto.\n        - intros; eapply LAT_kern_norm; eauto. eapply _x.\n        - intros; eapply LAT_usr_norm; eauto.\n        - eapply alloc_container_valid'; eauto.\n        - eapply Lconsistent_ppage_norm_alloc; eauto.\n        - intros; congruence.\n        - eapply dirty_ppage_gso_alloc; eauto.\n        - eapply consistent_pmap_gso_at_false; eauto. apply _x.\n        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.\n        - eapply consistent_lat_domain_gss_nil; eauto.\n        - zmap_solve.\n        - intros; apply NotInQ_gso_true; auto.\n        - intros; apply CurIDValid_gss_ac; auto.\n      Qed.\n      \n      Lemma alloc_low_level_inv:\n        forall d d' i n n',\n          alloc_spec i d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma alloc_kernel_mode:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance alloc_inv: PreservesInvariants alloc_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply alloc_low_level_inv; eassumption.\n        - eapply alloc_high_level_inv; eassumption.\n        - eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n    End ALLOC.\n\n    Global Instance pfree_inv: PreservesInvariants pfree_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - intros; eapply LAT_kern_norm; eauto. \n      - intros; eapply LAT_usr_norm; eauto.\n      - eapply Lconsistent_ppage_norm_undef; eauto.\n      - eapply dirty_ppage_gso_undef; eauto.\n      - eapply consistent_pmap_gso_pperm_alloc; eauto.\n      - eapply consistent_pmap_domain_gso_at_0; eauto.\n      - eapply consistent_lat_domain_gss_nil; eauto.\n    Qed.\n\n    Global Instance trapin_inv: PrimInvariants trapin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance trapout_inv: PrimInvariants trapout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostin_inv: PrimInvariants hostin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostout_inv: PrimInvariants hostout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptin_inv: PrimInvariants ptin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptout_inv: PrimInvariants ptout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance fstore_inv: PreservesInvariants fstore_spec.\n    Proof.\n      split; intros; inv_generic_sem H; inv H0; functional inversion H2.\n      - functional inversion H. split; trivial.        \n      - functional inversion H.\n        split; subst; simpl; \n        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial. \n      - functional inversion H0.\n        split; simpl; try assumption.\n    Qed.\n\n    Global Instance setPT_inv: PreservesInvariants setPT_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Section PTINSERT.\n      \n      Section PTINSERT_PTE.\n\n        Lemma ptInsertPTE_high_level_inv:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. \n          - eapply LAT_usr_norm; eauto.\n          - eapply Lconsistent_ppage_norm; eassumption.\n          - eapply PMap_valid_gso_valid; eauto.\n          - functional inversion H2. functional inversion H1. \n            eapply PMap_kern_gso; eauto.\n          - functional inversion H2. functional inversion H0.\n            eapply consistent_pmap_ptp_same; try eassumption.\n            eapply consistent_pmap_gso_pperm_alloc'; eassumption.\n          - functional inversion H2.\n            eapply consistent_pmap_domain_append; eauto.\n            destruct (ZMap.get pti pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n          - eapply consistent_lat_domain_gss_append; eauto.\n            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n        Qed.\n\n        Lemma ptInsertPTE_low_level_inv:\n          forall d d' n vadr padr p n',\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptInsertPTE_kernel_mode:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTINSERT_PTE.\n\n      Section PTALLOCPDE.\n\n        Lemma ptAllocPDE_high_level_inv:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto. \n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. eapply _x.\n          - eapply LAT_usr_norm; eauto.\n          - eapply alloc_container_valid'; eauto.\n          - apply Lconsistent_ppage_norm_hide; try assumption.\n          - congruence.\n          - eapply PMap_valid_gso_pde_unp; eauto.\n            eapply real_init_PTE_defined.\n          - functional inversion H3. \n            eapply PMap_kern_gso; eauto.\n          - eapply dirty_ppage_gss; eauto.\n          - eapply consistent_pmap_ptp_gss; eauto; apply _x.\n          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.\n            eapply consistent_pmap_domain_ptp_unp; eauto.\n            apply real_init_PTE_unp.\n          - apply consistent_lat_domain_gss_nil; eauto.\n            apply consistent_lat_domain_gso_p; eauto.\n          - zmap_solve.\n          - apply NotInQ_gso_true; auto.\n          - apply CurIDValid_gss_ac; auto.\n        Qed.\n\n        Lemma ptAllocPDE_low_level_inv:\n          forall d d' n vadr v n',\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptAllocPDE_kernel_mode:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTALLOCPDE.\n\n      Lemma ptInsert_high_level_inv:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        - eapply ptInsertPTE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptInsertPTE_high_level_inv; try eassumption.\n          eapply ptAllocPDE_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_low_level_inv:\n        forall d d' n vadr padr p n' v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptInsertPTE_low_level_inv; try eassumption.\n          eapply ptAllocPDE_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_kernel_mode:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_kernel_mode; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n        - eapply ptInsertPTE_kernel_mode; try eassumption.\n          eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTINSERT.\n\n    Section PTRESV.\n\n      Lemma ptResv_high_level_inv:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        eapply ptInsert_high_level_inv; try eassumption.\n        eapply alloc_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_low_level_inv:\n        forall d d' n vadr p n' v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_low_level_inv; try eassumption.\n        eapply alloc_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_kernel_mode:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_kernel_mode; try eassumption.\n        eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptResv_low_level_inv; eassumption.\n        - eapply ptResv_high_level_inv; eassumption.\n        - eapply ptResv_kernel_mode; eassumption.\n      Qed.\n\n    End PTRESV.\n\n    Section OFFER_SHARE.\n\n      Section PTRESV2.\n\n        Lemma ptResv2_high_level_inv:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_high_level_inv; try eassumption.\n          - eapply alloc_high_level_inv; eassumption.\n          - eapply ptInsert_high_level_inv; try eassumption.\n            eapply alloc_high_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_low_level_inv:\n          forall d d' n vadr p n' vadr' p' l v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            low_level_invariant l d ->\n            low_level_invariant l d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_low_level_inv; try eassumption.\n          - eapply alloc_low_level_inv; eassumption.\n          - eapply ptInsert_low_level_inv; try eassumption.\n            eapply alloc_low_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_kernel_mode:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_kernel_mode; try eassumption.\n          - eapply alloc_kernel_mode; eassumption.\n          - eapply ptInsert_kernel_mode; try eassumption.\n            eapply alloc_kernel_mode; eassumption.\n        Qed.\n\n      End PTRESV2.\n\n      Global Instance offer_shared_mem_inv: \n        PreservesInvariants offer_shared_mem_spec.\n      Proof.\n        preserves_invariants_simpl';\n        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_kernel_mode; eauto.\n        - exploit ptResv2_kernel_mode; eauto.\n      Qed.\n\n    End OFFER_SHARE.\n\n    Global Instance shared_mem_status_inv: \n      PreservesInvariants shared_mem_status_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n\n    Global Instance thread_spawn_inv: DNewInvariants thread_spawn_spec.\n    Proof.\n      constructor; intros; inv H0;\n      unfold thread_spawn_spec in *;\n      subdestruct; inv H; simpl; auto.\n\n      - (* low level invariant *)\n        constructor; trivial; intros; simpl in *.\n        eapply kctxt_inject_neutral_gss_flatinj'; eauto.\n        eapply kctxt_inject_neutral_gss_flatinj; eauto.\n\n      - (* high_level_invariant *)\n        constructor; simpl; eauto 2; try congruence; intros.\n        + exploit split_container_valid; eauto.\n          eapply container_split_some; eauto.\n          auto.\n        + unfold update_cusage, update_cchildren; zmap_solve.\n        + eapply AbTCBStrong_range_gss_READY; eauto. \n        + eapply AbQCorrect_range_gss_enqueue; eauto.\n        + unfold update_cusage, update_cchildren; apply NotInQ_gso_ac_true; auto.\n          zmap_simpl; repeat apply NotInQ_gso_true; auto.          \n        + eapply QCount_gss_spawn; eauto. \n          eapply AbTCBStrong_range_impl; eauto.\n          split; [|split; [|eauto]].\n          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.\n          apply cvalid_unused_next_child; auto.\n        + eapply InQ_gss_spawn; eauto.\n          eapply AbTCBStrong_range_impl; eauto.\n          split; [|split; [|eauto]].\n          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.\n          apply cvalid_unused_next_child; auto.\n        + unfold update_cusage, update_cchildren; apply CurIDValid_gso_neq_true; auto.\n          zmap_simpl; repeat apply CurIDValid_gss_ac; auto.\n          assert (Hneq:= cvalid_child_id_neq _ valid_container0 _ Hdestruct3); zmap_simpl.\n          apply cvalid_unused_next_child; auto.\n        + eapply SingleRun_gso_state_READY; eauto.\n    Qed.\n    \n    Local Opaque remove.\n\n    Global Instance thread_yield_inv: ThreadScheduleInvariants thread_yield_spec.\n    Proof.\n      constructor; intros; functional inversion H. \n      - inv H1. constructor; trivial. \n        eapply kctxt_inject_neutral_gss_mem; eauto.\n      - inv H0. subst.\n        assert (HOS: 0<= num_chan <= num_chan) by omega.\n        exploit last_range_AbQ; eauto. intros Hrange.\n        constructor; auto; simpl in *; intros; try congruence.\n        + eapply AbTCBStrong_range_gss_RUN; eauto. \n          eapply AbTCBStrong_range_gss_READY; eauto. \n        + eapply AbQCorrect_range_gss_remove'; eauto.\n          eapply list_range_enqueue; eauto.\n          eapply AbQCorrect_range_impl; eauto.\n        + eapply NotInQ_gso_neg; eauto.\n          eapply NotInQ_gso_ac; eauto. \n          eapply correct_curid0; eauto.\n        + eapply QCount_gss_yield; eauto.\n        + eapply InQ_gss_yield; eauto.\n        + eapply CurIDValid_gss_last; eauto. \n        + eapply SingleRun_gss_gso_cid; eauto. congruence.\n    Qed.\n\n    Global Instance thread_sleep_inv: ThreadTransferInvariants thread_sleep_spec.\n    Proof.\n      constructor; intros; functional inversion H. \n      - inv H1. constructor; trivial. \n        eapply kctxt_inject_neutral_gss_mem; eauto.\n      - inv H0. subst.\n        assert (HOS: 0<= num_chan <= num_chan) by omega.\n        assert (HNeq: 64 <> n') by omega.\n        exploit last_range_AbQ; eauto. intros Hrange.\n        assert (HOS': 0 <= n' <= num_proc) by omega.\n        assert (Hcid: ZMap.get (cid d) (abtcb d) = AbTCBValid RUN (-1)) \n          by (eapply correct_curid0; eauto).\n        constructor; auto; simpl in *; intros; try congruence.\n        + eapply AbTCBStrong_range_gss_RUN; eauto. \n          eapply AbTCBStrong_range_gss_SLEEP; eauto. \n        + eapply AbQCorrect_range_gss_remove; eauto.\n          * eapply AbQCorrect_range_gss_enqueue; eauto.\n          * rewrite ZMap.gso; eauto. \n        + eapply NotInQ_gso_neg; eauto.\n          eapply NotInQ_gso_ac; eauto. \n          eapply correct_curid0; eauto.\n        + eapply QCount_gss_remove; eauto.\n          * eapply QCount_gss_enqueue; eauto.\n          * rewrite ZMap.gso; eauto. \n        + eapply InQ_gss_remove; eauto.\n          * eapply InQ_gss_enqueue; eauto.\n          * eapply QCount_gss_enqueue; eauto.\n          * rewrite ZMap.gso; eauto.  \n          * apply last_correct; eauto.\n        + eapply CurIDValid_gss_last; eauto. \n        + eapply SingleRun_gss_gso_cid; eauto. congruence.\n    Qed.\n\n    (*Global Instance sendto_chan_inv: PreservesInvariants sendto_chan_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      eapply ChanPool_Valid_gss; eauto.\n    Qed.*)\n\n    Section THREAD_WAKEUP.\n      \n      Lemma thread_wakeup_high_level_inv:\n        forall d d' n,\n          thread_wakeup_spec n d = Some d' ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; simpl; eauto; intros.\n        - eapply AbTCBStrong_range_gss_READY; eauto. \n        - eapply AbQCorrect_range_gss_wakeup; eauto.\n        - clear valid_curid0. eapply NotInQ_InQ_gss_wakeup; eauto.\n        - eapply QCount_gss_wakeup; eauto.\n        - eapply InQ_gss_wakeup; eauto.\n        - eapply CurIDValid_gso_tcb; eauto.\n          eapply last_neq_cid; eauto. omega.\n        - eapply SingleRun_gso_state_READY; eauto.\n      Qed.\n      \n      Lemma thread_wakeup_low_level_inv:\n        forall d d' n n',\n          thread_wakeup_spec n d = Some d' ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma thread_wakeup_kernel_mode:\n        forall d d' n,\n          thread_wakeup_spec n d = Some d' ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance thread_wakeup_inv: PreservesInvariants thread_wakeup_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply thread_wakeup_low_level_inv; eassumption.\n        - eapply thread_wakeup_high_level_inv; eassumption.\n        - eapply thread_wakeup_kernel_mode; eassumption.\n      Qed.\n\n    End THREAD_WAKEUP.\n\n    (*Section RECEIVE_CHAN.\n      \n      Lemma receive_chan_high_level_inv:\n        forall d d' n,\n          receive_chan_spec d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        exploit thread_wakeup_high_level_inv; eauto.\n        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.\n        eapply ChanPool_Valid_gss; eauto.\n      Qed.\n      \n      Lemma receive_chan_low_level_inv:\n        forall d d' n n',\n          receive_chan_spec d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        exploit thread_wakeup_low_level_inv; eauto.\n        intros Hh. inv Hh. constructor; eauto 2.\n      Qed.\n\n      Lemma receive_chan_kernel_mode:\n        forall d d' n,\n          receive_chan_spec d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        exploit thread_wakeup_kernel_mode; eauto.\n      Qed.\n\n      Global Instance receive_chan_inv: PreservesInvariants receive_chan_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply receive_chan_low_level_inv; eassumption.\n        - eapply receive_chan_high_level_inv; eassumption.\n        - eapply receive_chan_kernel_mode; eassumption.\n      Qed.\n\n    End RECEIVE_CHAN.*)\n\n    Global Instance syncsendto_chan_pre_inv: PreservesInvariants syncsendto_chan_pre_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      eapply SyncChanPool_Valid_gss; eauto.\n    Qed.\n\n    Global Instance syncsendto_chan_post_inv: PreservesInvariants syncsendto_chan_post_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      eapply SyncChanPool_Valid_gss; eauto.\n    Qed.\n\n    Section MEMCPY.\n\n      Lemma flatmem_copy_high_level_inv:\n        forall d d' from to len,\n          flatmem_copy_spec len to from d = Some d'\n          -> high_level_invariant d\n          -> high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0.\n        constructor; simpl; intros;\n        try eapply dirty_ppage_gss_copy; eauto.\n      Qed.\n\n      Lemma flatmem_copy_low_level_inv:\n        forall d d' from to len n,\n          flatmem_copy_spec len to from d = Some d'\n          -> low_level_invariant n d\n          -> low_level_invariant n d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto 2.\n      Qed.\n\n      Lemma flatmem_copy_kernel_mode:\n        forall d d' from to len,\n          flatmem_copy_spec len to from d = Some d'\n          -> kernel_mode d\n          -> kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n    End MEMCPY.\n\n    Section SYNCRECEIVE_CHAN.\n      \n      Lemma syncreceive_chan_high_level_inv:\n        forall fromid vaddr count d d' n,\n          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        exploit thread_wakeup_high_level_inv; eauto.\n        exploit flatmem_copy_high_level_inv; eauto.\n        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.\n        eapply SyncChanPool_Valid_gss; eauto.\n      Qed.\n      \n      Lemma syncreceive_chan_low_level_inv:\n        forall fromid vaddr count d d' n n',\n          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        exploit thread_wakeup_low_level_inv; eauto.\n        exploit flatmem_copy_low_level_inv; eauto.\n        intros Hh. inv Hh. constructor; eauto 2.\n      Qed.\n\n      Lemma syncreceive_chan_kernel_mode:\n        forall fromid vaddr count d d' n,\n          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        exploit thread_wakeup_kernel_mode; eauto.\n        exploit flatmem_copy_kernel_mode; eauto.\n      Qed.\n\n      Global Instance syncreceive_chan_inv: PreservesInvariants syncreceive_chan_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply syncreceive_chan_low_level_inv; eassumption.\n        - eapply syncreceive_chan_high_level_inv; eassumption.\n        - eapply syncreceive_chan_kernel_mode; eassumption.\n      Qed.\n\n    End SYNCRECEIVE_CHAN.\n\n    Global Instance proc_init_inv: PreservesInvariants proc_init_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant.\n      - apply real_nps_range.\n      - apply real_lat_kern_valid.\n      - apply real_lat_usr_valid.\n      - apply real_container_valid.\n      - rewrite init_pperm0; try assumption.\n        apply Lreal_pperm_valid.        \n      - eapply real_pt_PMap_valid; eauto.\n      - apply real_pt_PMap_kern.\n      - omega.\n      - assumption.\n      - apply real_idpde_init.\n      - apply real_pt_consistent_pmap. \n      - apply real_pt_consistent_pmap_domain. \n      - apply Lreal_at_consistent_lat_domain.\n      - apply real_abtcb_strong_range'; eauto.\n      - apply real_abq_range; auto.\n      - eapply real_abtcb_pb_notInQ'; eauto.\n      - eapply real_abtcb_abq_QCount'; eauto.\n      - eapply real_abq_tcb_inQ; eauto.\n      - omega.\n      - eapply real_abtcb_AC_CurIDValid; eauto. \n      - eapply real_abtcb_SingleRun; eauto. \n      - eapply real_syncchpool_valid'; eauto.\n    Qed.\n\n    Global Instance device_output_inv: PreservesInvariants device_output_spec.\n    Proof. \n      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.\n    Qed.\n\n  End INV.\n\n  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).\n\n  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).\n\n  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).\n  Proof.\n    split; inversion 1; intros. \n    - functional inversion H0. split; trivial.\n    - functional inversion H1. \n      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.\n  Qed.\n\n  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n  Proof.\n    split; inversion 1; intros; constructor; auto.\n  Qed.\n\n  (** * Layer Definition *)\n  Definition pipc_fresh : compatlayer (cdata RData) :=\n    syncreceive_chan \u21a6 gensem syncreceive_chan_spec\n                  \u2295 syncsendto_chan_pre \u21a6 gensem syncsendto_chan_pre_spec\n                  \u2295 syncsendto_chan_post \u21a6 gensem syncsendto_chan_post_spec\n                  \u2295 proc_init \u21a6 gensem proc_init_spec.\n\n  Definition pipc_passthrough : compatlayer (cdata RData) :=\n    fload \u21a6 gensem fload_spec\n          \u2295 fstore \u21a6 gensem fstore_spec\n          \u2295 vmxinfo_get \u21a6 gensem vmxinfo_get_spec\n          \u2295 device_output \u21a6 gensem device_output_spec\n          \u2295 pfree \u21a6 gensem pfree_spec\n          \u2295 set_pt \u21a6 gensem setPT_spec\n          \u2295 pt_read \u21a6 gensem ptRead_spec\n          \u2295 pt_resv \u21a6 gensem ptResv_spec\n          \u2295 shared_mem_status \u21a6 gensem shared_mem_status_spec\n          \u2295 offer_shared_mem \u21a6 gensem offer_shared_mem_spec\n\n          \u2295 get_curid \u21a6 gensem get_curid_spec\n          \u2295 thread_spawn \u21a6 dnew_compatsem thread_spawn_spec\n          \u2295 thread_wakeup \u21a6 gensem thread_wakeup_spec\n\n          \u2295 pt_in \u21a6 primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n          \u2295 pt_out \u21a6 primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          \u2295 container_get_nchildren \u21a6 gensem container_get_nchildren_spec\n          \u2295 container_get_quota \u21a6 gensem container_get_quota_spec\n          \u2295 container_get_usage \u21a6 gensem container_get_usage_spec\n          \u2295 container_can_consume \u21a6 gensem container_can_consume_spec\n          \u2295 container_alloc \u21a6 gensem alloc_spec\n          \u2295 trap_in \u21a6 primcall_general_compatsem trapin_spec\n          \u2295 trap_out \u21a6 primcall_general_compatsem trapout_spec\n          \u2295 host_in \u21a6 primcall_general_compatsem hostin_spec\n          \u2295 host_out \u21a6 primcall_general_compatsem hostout_spec\n          \u2295 trap_get \u21a6 primcall_trap_info_get_compatsem trap_info_get_spec\n          \u2295 trap_set \u21a6 primcall_trap_info_ret_compatsem trap_info_ret_spec\n\n          \u2295 thread_yield \u21a6 primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)\n          \u2295 thread_sleep \u21a6 primcall_thread_transfer_compatsem thread_sleep_spec\n\n          \u2295 accessors \u21a6 {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  Definition pipc : compatlayer (cdata RData) := pipc_fresh \u2295 pipc_passthrough.\n\n  (*Definition semantics := LAsm.Lsemantics pipc.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PIPC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.2720245392906821, "lm_q1q2_score": 0.1591618758466372}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\n\nDefinition my_fold_right {A B} (f : B -> A -> A) (a : A):=\nfix my_fold_right (l : list B) : A :=\n  match l with\n  | [] => a\n  | b :: t => f b (my_fold_right t)\n  end.\nLemma my_fold_right_eq {A B} (f : B -> A -> A) a: my_fold_right f a = fold_right f a.\nProof. extensionality l. induction l; auto. Qed.\n\n\nLemma FRZL_ax' ps: FRZL ps = my_fold_right sepcon emp ps.\nProof. rewrite FRZL_ax. rewrite my_fold_right_eq. trivial. Qed.\n\n(*Tactic requires the resulting goal to be normalized manually.*)\nLtac my_thaw' name :=\n  rewrite (FRZL_ax' name); unfold name, abbreviate; clear name.\n\n(*add simplification of the list operations inside the freezer,\n   flatten the sepcon, and eliminate the emp term*)\nLtac my_thaw name :=\n  my_thaw' name; simpl nat_of_Z; unfold my_delete_nth, my_nth, my_fold_right;\n  repeat flatten_sepcon_in_SEP; repeat flatten_emp.\n\nLemma isptrD v: isptr v -> exists b ofs, v = Vptr b ofs.\nProof. intros. destruct v; try contradiction. eexists; eexists; reflexivity. Qed.\n\nLemma REST: forall (Espec : OracleKind) (contents : list Z) additional add_len ctx\n  md_ctx' V' reseed_counter' entropy_len' prediction_resistance' reseed_interval'\n  key V reseed_counter entropy_len prediction_resistance reseed_interval kv\n  info_contents (s : ENTROPY.stream)\n(*Delta_specs := abbreviate : PTree.t funspec*)\n  seed\n  (XH : 0 <= add_len <= Int.max_unsigned)\n  (XH0 : Zlength V = 32)\n  (XH1 : add_len = Zlength contents)\n  (contents' : list Z)\n  (Heqcontents' : contents' = contents_with_add additional add_len contents)\n  (ELc' : 0 < entropy_len + Zlength contents' (* <= 384*))\n(*  (ELc' : 0 < entropy_len + Zlength contents (* <= 384*))*)\n  (XH3 : Forall general_lemmas.isbyteZ V)\n  (XH4 : Forall general_lemmas.isbyteZ contents)\n  (XH5 : map Vint (map Int.repr V) = V')\n  (XH6 : Vint (Int.repr reseed_counter) = reseed_counter')\n  (XH7 : Vint (Int.repr entropy_len) = entropy_len')\n  (XH8 : Vint (Int.repr reseed_interval) = reseed_interval')\n  (XH9 : Val.of_bool prediction_resistance = prediction_resistance')\n  (PNadditional : is_pointer_or_null additional)\n  (Pctx : isptr ctx)\n  (ELnonneg : 0 <= entropy_len)\n  (ZLc' : Zlength contents' = 0 \\/ Zlength contents' = Zlength contents)\n  (*(H10 : zlt 256 add_len = false)\n  (H11 : zlt 384 (entropy_len + add_len) = false)*)\n  (Hfield : field_compatible (tarray tuchar 384) [] seed)\n  (AL256 : (add_len >? 256) = false)\n  (EAL384 : (entropy_len + add_len >? 384) = false)\n  (entropy_bytes : list Z)\n  (s0 : ENTROPY.stream)\n  (Heqentropy_result : ENTROPY.success entropy_bytes s0 = ENTROPY.get_bytes (Z.to_nat entropy_len) s),\n@semax hmac_drbg_compspecs.CompSpecs Espec\n  (initialized_list [_entropy_len; _t'2; _t'1]\n     (func_tycontext f_mbedtls_hmac_drbg_reseed HmacDrbgVarSpecs\n        HmacDrbgFunSpecs))\n  (PROP ( )\n   LOCAL (temp _t'2 Vzero; temp _entropy_len (Vint (Int.repr entropy_len));\n   lvar _seed (tarray tuchar 384) seed; temp _ctx ctx; temp _additional additional;\n   temp _len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n   SEP (Stream (get_stream_result (get_entropy 0 entropy_len entropy_len false s));\n   data_at Tsh (tarray tuchar entropy_len) (map Vint (map Int.repr entropy_bytes)) seed;\n   data_at Tsh (tarray tuchar (384 - entropy_len))\n     (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))\n     (offset_val entropy_len seed);\n   da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;\n   md_full key md_ctx';\n   data_at Tsh t_struct_mbedtls_md_info info_contents\n     (hmac256drbgstate_md_info_pointer\n        (md_ctx',\n        (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))));\n   spec_sha.K_vector kv;\n   data_at Tsh t_struct_hmac256drbg_context_st\n     (md_ctx',\n     (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval')))))\n     ctx))\n  (Ssequence (Sset _seedlen (Etempvar _entropy_len tuint))\n     (Ssequence\n        (Ssequence\n           (Sifthenelse\n              (Ebinop Cop.One (Etempvar _additional (tptr tuchar))\n                 (Ecast (Econst_int (Int.repr 0) tint) (tptr tvoid)) tint)\n              (Sset _t'3\n                 (Ecast\n                    (Ebinop Cop.One (Etempvar _len tuint) (Econst_int (Int.repr 0) tint) tint)\n                    tbool)) (Sset _t'3 (Econst_int (Int.repr 0) tint)))\n           (Sifthenelse (Etempvar _t'3 tint)\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 (Evar _seed (tarray tuchar 384))\n                       (Etempvar _seedlen tuint) (tptr tuchar);\n                    Etempvar _additional (tptr tuchar); Etempvar _len tuint])\n                 (Sset _seedlen\n                    (Ebinop Oadd (Etempvar _seedlen tuint) (Etempvar _len tuint) tuint)))\n              Sskip))\n        (Ssequence\n           (Scall None\n              (Evar _mbedtls_hmac_drbg_update\n                 (Tfunction\n                    (Tcons (tptr (Tstruct _mbedtls_hmac_drbg_context noattr))\n                       (Tcons (tptr tuchar) (Tcons tuint Tnil))) tvoid cc_default))\n              [Etempvar _ctx (tptr (Tstruct _mbedtls_hmac_drbg_context noattr));\n              Evar _seed (tarray tuchar 384); Etempvar _seedlen tuint])\n           (Ssequence\n              (Sassign\n                 (Efield\n                    (Ederef\n                       (Etempvar _ctx (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                       (Tstruct _mbedtls_hmac_drbg_context noattr)) _reseed_counter tint)\n                 (Econst_int (Int.repr 1) tint))\n              (Sreturn (Some (Econst_int (Int.repr 0) tint)))))))\n (frame_ret_assert\n     (function_body_ret_assert tint\n        (fun a : environ =>\n         EX x : val,\n         (PROP ( )\n          LOCAL (temp ret_temp x)\n          SEP (reseedPOST x contents additional add_len s\n                 (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval) ctx\n                 info_contents kv\n                 (md_ctx',\n                 (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))))) a))\n     (fun a : environ =>\n      EX x : val,\n      local (lvar_denote _seed (tarray tuchar 384) x) a && ` (data_at_ Tsh (tarray tuchar 384) x) a)).\nProof.\n  intros.\n  assert (ZLbytes: Zlength entropy_bytes = entropy_len).\n    { eapply get_bytes_Zlength. omega. eassumption. }\n  apply Zgt_is_gt_bool_f in EAL384.\n  abbreviate_semax.\n(*  remember (contents_with_add additional add_len contents) as contents'.\n  assert (ZLc': Zlength contents' = 0 \\/ Zlength contents' = Zlength contents).\n    { subst contents'. unfold contents_with_add.\n      destruct (eq_dec add_len 0); simpl.\n        rewrite andb_false_r. left; apply Zlength_nil.\n        destruct (Memory.EqDec_val additional nullval); simpl. left; apply Zlength_nil.\n        right; trivial.\n    }\n*)\n  freeze [0;(*2;*)4;5;6;7] FR6. freeze [1;2] SEED.\n\n  replace_SEP 0 (data_at Tsh (tarray tuchar 384)\n         ((map Vint\n            (map Int.repr entropy_bytes)) ++ (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero))) seed).\n  {\n    entailer!. thaw SEED; clear FR6. (*subst entropy_len.*) rewrite sepcon_emp.\n    apply derives_refl'. symmetry.\n    apply data_at_complete_split; repeat rewrite Zlength_map;\n    try rewrite (*Hentropy_bytes_length,*) Zlength_list_repeat; try rewrite Zplus_minus; trivial; omega.\n  }\n\n  (* seedlen = entropy_len; *)\n  clear SEED. freeze [0;1] FR7.\n  forward.\n(*  remember (if eq_dec additional nullval then false else if eq_dec add_len 0 then false else true) as non_empty_additional.*)\n  remember (andb (negb (eq_dec additional nullval)) (negb (eq_dec add_len 0))) as non_empty_additional.\n\n  forward_if (\n      PROP  ()\n      LOCAL  (temp _seedlen (Vint (Int.repr (entropy_len)));\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      temp _t'3 (Val.of_bool non_empty_additional);\n      gvar sha._K256 kv)\n      SEP  (FRZL FR7; da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional)).\n  { destruct additional; simpl in PNadditional; try contradiction.\n    + subst i. rewrite da_emp_null. entailer. reflexivity.\n    + rewrite da_emp_ptr. normalize.\n      eapply denote_tc_test_eq_split; auto 50 with valid_pointer.\n      (* TODO regression, this should have solved it *)\n      apply sepcon_valid_pointer2.\n      apply data_at_valid_ptr; auto. }\n  { (*nonnull additional*)\n    destruct additional; simpl in PNadditional; try contradiction. subst i. elim H; trivial. clear H.\n    forward. entailer!. simpl.\n    destruct (initial_world.EqDec_Z (Zlength contents) 0).\n    + rewrite e. simpl. reflexivity.\n    + simpl in *. rewrite Int.eq_false; simpl. reflexivity.\n      intros N.\n      assert (Y: Int.unsigned (Int.repr (Zlength contents)) = Int.unsigned (Int.repr 0)) by (rewrite N; trivial).\n      clear N. rewrite Int.unsigned_repr in Y. 2: omega. rewrite Int.unsigned_repr in Y; omega.\n  }\n  { (*nullval additional*)\n    rewrite H in *.\n    forward. entailer!.\n  }\n  thaw FR7.\n(*  freeze [1;2] FR8.*) (*my_thaw FR6.*)\n  forward_if (\n      PROP  ()\n      LOCAL  (temp _seedlen (Vint (Int.repr (entropy_len + Zlength contents')));\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP (data_at Tsh (tarray tuchar 384)\n         (map Vint\n            (map Int.repr entropy_bytes) ++ (map Vint (map Int.repr (*contents*)contents')) ++\n          list_repeat (Z.to_nat (384 - entropy_len - Zlength (*contents*)contents')) (Vint Int.zero)) seed;\n           (*FRZL FR8*)FRZL FR6;\n       da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional)).\n  + rewrite H in Heqnon_empty_additional. rename H into NEA.\n    destruct additional; simpl in PNadditional; try contradiction.\n    - subst i; simpl in *; discriminate.\n    - destruct (eq_dec add_len 0); try discriminate.\n      subst non_empty_additional; clear Heqnon_empty_additional.\n    rename b into bb. rename i into ii.\n    rewrite da_emp_ptr. Intros. rename H into addlen_pos.\n    assert (contents' = contents).\n    { subst contents'. unfold contents_with_add. simpl.\n        destruct (initial_world.EqDec_Z add_len 0). omega. reflexivity. }\n    clear Heqcontents'; subst contents'. clear ZLc'.\n    replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)\n         (map Vint\n            (map Int.repr entropy_bytes)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))\n         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val entropy_len seed))).\n    {\n      entailer!.\n      apply derives_refl'; apply data_at_complete_split; trivial; try omega.\n      rewrite Zlength_app in H; rewrite H; trivial.\n      repeat rewrite Zlength_map; trivial.\n      rewrite Zlength_list_repeat; omega.\n    }\n    flatten_sepcon_in_SEP. rewrite data_at_isptr with (p:=seed); Intros.\n    apply isptrD in Pseed; destruct Pseed as [b [i SEED]]; rewrite SEED in *.\n    change (offset_val entropy_len (Vptr b i)) with (Vptr b (Int.add i (Int.repr entropy_len))).\n    assert_PROP (field_compatible (Tarray tuchar (384 - entropy_len) noattr)\n          [] (Vptr b (Int.add i (Int.repr entropy_len)))) as FC_el by entailer!.\n    simpl in *.\n    replace_SEP 1 (\n      (data_at Tsh (tarray tuchar (Zlength contents))\n         (list_repeat (Z.to_nat (Zlength contents)) (Vint Int.zero)) (Vptr b (Int.add i (Int.repr entropy_len)))) *\n      (data_at Tsh (tarray tuchar (384 - entropy_len - Zlength contents))\n         (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents)) (Vint Int.zero)) (offset_val (Zlength contents) (Vptr b (Int.add i (Int.repr entropy_len)))))).\n    { (*\n      subst entropy_len.\n      replace (384 - 32) with 352 by omega.\n      remember (Vptr b (Int.add i (Int.repr 32))) as seed'.\n      clear Heqseed'.\n      (*entailer!*) go_lower.\n      replace (length contents) with (Z.to_nat (Zlength contents)) by\n        (rewrite Zlength_correct; apply Nat2Z.id).\n      apply derives_refl'; apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto.\n      {\n        (*replace (Zlength contents + (352 - Zlength contents')) with (384 - 32) by omega.*)\n        replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.\n        replace (384-32) with 352 in H11 by omega.\n        assumption.\n      }\n      {\n        rewrite list_repeat_app.\n        rewrite <- Z2Nat.inj_add; try omega.\n        replace (Zlength contents + (352 - Zlength contents)) with 352 by omega.\n        reflexivity.\n      }*)\n      remember (Vptr b (Int.add i (Int.repr entropy_len))) as seed'.\n      clear Heqseed'.\n      (*entailer!*) go_lower.\n      apply derives_refl'.\n      apply data_at_complete_split; try rewrite Zlength_list_repeat; try omega; auto.\n      + rewrite Zlength_list_repeat.\n        replace (Zlength contents + (384 - entropy_len - Zlength contents)) with (384 - entropy_len); trivial; omega.\n        omega.\n      + rewrite list_repeat_app, <- Z2Nat.inj_add.\n        replace (Zlength contents + (384 - entropy_len - Zlength contents)) with (384 - entropy_len); trivial; omega.\n        omega. omega.\n    }\n\n    flatten_sepcon_in_SEP.\n    replace_SEP 1 (memory_block Tsh (Zlength contents) (Vptr b (Int.add i (Int.repr entropy_len)))).\n    { entailer!. replace (Zlength contents) with (sizeof (*cenv_cs*) (tarray tuchar (Zlength contents))) at 2.\n      apply data_at_memory_block. simpl. rewrite Zmax0r; omega.\n    }\n    forward_call ((Tsh, Tsh), (Vptr b (Int.add i (Int.repr entropy_len))), (*additional*)Vptr bb ii, Zlength contents, map Int.repr contents).\n    {\n      (* type checking *)\n      red in LV.\n      unfold eval_var. destruct (Map.get (ve_of rho) _seed); try contradiction.\n      destruct p; destruct LV  as [LV1 LV2]; inversion LV2. subst b0 i t; simpl; trivial.\n    }\n    {\n      (* match up function parameter *)\n      rewrite XH1; simpl.\n      apply prop_right; trivial.\n    }\n    {\n      (* match up SEP clauses *)\n      change (fst (Tsh, Tsh)) with Tsh;\n      change (snd (Tsh, Tsh)) with Tsh.\n      (*change (@data_at spec_sha.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional) with (@data_at hmac_drbg_compspecs.CompSpecs Tsh (tarray tuchar (@Zlength Z contents))\n         (@map int val Vint (@map Z int Int.repr contents)) additional).*)\n      cancel. my_thaw FR6.\n      rewrite XH1; cancel.\n    }\n    {\n      (* prove the PROP clauses *)\n      repeat split; auto; omega.\n    }\n    (*Intros memcpy_vret. subst memcpy_vret.*)\n    forward.\n    change (fst (Tsh, Tsh)) with Tsh;\n    change (snd (Tsh, Tsh)) with Tsh.\n    rewrite XH1, SEED.\n\n    (* Time entailer!. (*8.5pl2: 1230secs*) *)\n    go_lower. normalize.\n    apply andp_right. apply prop_right. repeat split; auto.\n\n\n    thaw FR6. rewrite (*H1,*) da_emp_ptr. normalize.\n    apply andp_right. apply prop_right. simpl. (*specialize (Zlength_nonneg contents).*) subst add_len; omega.\n    cancel.\n    erewrite data_at_complete_split with\n     (A:=map Vint (map Int.repr entropy_bytes))\n     (p:=Vptr b i)(*(offset:=entropy_len)*)\n     (AB:= (map Vint (map Int.repr entropy_bytes) ++\n       map Vint (map Int.repr contents) ++\n       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))\n         (Vint Int.zero))).\n    7: solve[reflexivity].\n    cancel.\n    6: solve[reflexivity].\n    3: solve [repeat rewrite Zlength_map; omega].\n\n    3: solve [reflexivity].\n    3: solve [rewrite Zlength_app, Zlength_list_repeat; repeat rewrite Zlength_map; try omega].\n\n    Focus 2. rewrite Zlength_app, (* <- H17, *) Zlength_list_repeat; try omega.\n             repeat rewrite Zlength_map. rewrite ZLbytes(*, H2*).\n             assert (X: entropy_len + (Zlength contents + (384 - entropy_len - Zlength contents)) = 384) by omega.\n             rewrite X; assumption.\n\n    rewrite Zlength_app; repeat rewrite Zlength_map; rewrite Zlength_list_repeat.\n    assert (X: Zlength contents + (384 - entropy_len - Zlength contents) = 384 - entropy_len) by omega.\n    rewrite X.\n    erewrite data_at_complete_split with (AB:=map Vint (map Int.repr contents) ++\n       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents))\n         (Vint Int.zero))\n      (p:=(Vptr b (Int.add i (Int.repr entropy_len))))\n      (A:= map Vint (map Int.repr contents)).\n    7: reflexivity. 3: reflexivity. 5: reflexivity.\n    3: reflexivity. 3: solve [rewrite Zlength_list_repeat; repeat rewrite Zlength_map; try omega].\n\n    unfold offset_val. rewrite Int.add_assoc, add_repr. repeat rewrite Zlength_map. cancel. (*apply derives_refl.*)\n    repeat rewrite Zlength_map. rewrite Zlength_list_repeat; try omega.\n    apply derives_refl.\n    rewrite Zlength_list_repeat; repeat rewrite Zlength_map; try omega. rewrite X; assumption.\n\n    omega.\n\n  + rewrite H in Heqnon_empty_additional; clear H.\n    forward.\n    go_lower. normalize.\n    assert (contents' = nil).\n    { subst contents'. unfold contents_with_add.\n      destruct (eq_dec add_len 0); simpl in *.\n      + rewrite e in *. rewrite andb_false_r; trivial.\n      + destruct (Memory.EqDec_val additional nullval); simpl in *; trivial; discriminate. }\n    clear Heqcontents'; subst contents'.\n    rewrite Zlength_nil, Zplus_0_r.\n    apply andp_right.\n    apply prop_right. repeat split; trivial.\n    do 2 rewrite map_nil. rewrite app_nil_l, Zminus_0_r. cancel.\n\n  + (*continuation after conditional*)\n\n  replace_SEP 0 (\n    (data_at Tsh (tarray tuchar (entropy_len + Zlength contents')) (map Vint\n            (map Int.repr entropy_bytes) ++\n            map Vint (map Int.repr contents')) seed) *\n    (data_at Tsh (tarray tuchar (384 - (entropy_len + Zlength contents'))) (list_repeat (Z.to_nat (384 - entropy_len - Zlength contents'))\n            (Vint Int.zero)) (offset_val (entropy_len + Zlength contents') seed))\n      ).\n  {\n    clear Heqcontents'.\n    rewrite app_assoc.\n    entailer!.\n    rewrite Zlength_app, Zlength_list_repeat in H; try omega.\n    apply derives_refl'.\n    apply data_at_complete_split; repeat rewrite Zlength_list_repeat; try omega; auto;\n      (* rewrite Zlength_app;*)try rewrite H; try rewrite Hentropy_bytes_length; repeat rewrite Zlength_map; auto.\n  }\n  flatten_sepcon_in_SEP.\n\n  do 2 rewrite map_map.\n  rewrite <- map_app.\n  rewrite <- map_map.\n  thaw FR6.\n  rewrite data_at_isptr with (p:=seed). Intros.\n\n  (*mbedtls_hmac_drbg_update( ctx, seed, seedlen )*)\n  freeze [1;2;7] FR9.\n  remember (entropy_len + Zlength contents') as ll.\n  repeat rewrite Zlength_map in Hentropy_bytes_length.\n  forward_call (entropy_bytes ++ contents', seed, ll,\n                ctx,\n                (md_ctx',\n                 (map Vint (map Int.repr V),\n                 (Vint (Int.repr reseed_counter),\n                 (Vint (Int.repr entropy_len),\n                 (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval)))))),\n                (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval),\n                kv, info_contents).\n  {\n    (* prove the SEP clauses match up *)\n    destruct seed; simpl in Pseed; try contradiction.\n    rewrite da_emp_ptr.\n    rewrite Zlength_app.\n    rewrite ZLbytes. simpl.\n    normalize. apply andp_right. apply prop_right. repeat split; trivial.\n      { omega. (*subst contents' add_len. unfold contents_with_add.\n        destruct (eq_dec (Zlength contents) 0); simpl in *.\n        + rewrite andb_false_r, Zlength_nil. rewrite e, Zplus_0_r in *.\n          destruct ZL\n          rewrite Z.max_r; omega.\n        + rewrite andb_true_r.\n          destruct (Memory.EqDec_val additional nullval); simpl in *. right. omega.*) }\n    rewrite <- Heqll, XH5, XH6, XH7, XH8, XH9. cancel.\n  }\n  {\n    (* prove the PROP clauses *)\n    simpl in *. repeat split; trivial; try omega. (*\n    rewrite H2 in *;*) rewrite int_max_unsigned_eq. omega.\n    left; rewrite Zlength_app, ZLbytes; trivial.\n    { apply isbyteZ_app; try assumption.\n      eapply get_bytes_isbyteZ; eauto.\n      subst contents'; unfold contents_with_add.\n      destruct (eq_dec add_len 0); simpl.\n        rewrite andb_false_r. constructor.\n      destruct (Memory.EqDec_val additional nullval); simpl. constructor.\n      trivial.\n    }\n  }\n  unfold hmac256drbgabs_common_mpreds.\n  repeat flatten_sepcon_in_SEP.\n  thaw FR9.\n  freeze [1;2;4;6;7] FR10.\n  freeze [0;1] FR11.\n  gather_SEP 1 2.\n  replace_SEP 0 (data_at Tsh (tarray tuchar 384) ((map Vint\n         (map Int.repr entropy_bytes)) ++ (map Vint (map Int.repr contents') ++\n       list_repeat (Z.to_nat (384 - entropy_len - Zlength contents'))\n         (Vint Int.zero))) seed).\n  { (*\n    subst entropy_len.\n    replace (384 - 32) with 352 by omega.\n    replace (384 - (32 + Zlength contents')) with (352 - Zlength contents') by omega.*)\n    rewrite app_assoc.\n    rewrite map_map.\n    rewrite map_app.\n    rewrite <- map_map.\n    replace (map (fun x : Z => Vint (Int.repr x)) contents') with (map Vint (map Int.repr contents')) by (rewrite map_map; auto).\n    clear Heqcontents'.\n    rewrite Zlength_app, ZLbytes.\n    entailer!.\n    destruct seed; simpl in Pseed; try contradiction.\n    rewrite da_emp_ptr. Intros.\n    apply derives_refl'; symmetry; apply data_at_complete_split;\n     repeat rewrite Zlength_list_repeat; try omega; auto; try rewrite Zlength_app;\n     try rewrite ZLbytes; repeat rewrite Zlength_map; auto.\n     replace (Zlength entropy_bytes + Zlength contents' +\n      (384 - Zlength entropy_bytes - Zlength contents')) with 384 by omega.\n     assumption.\n  }\n\n  (* ctx->reseed_counter = 1; *)\n  my_thaw FR11.\n  freeze [0;1] FR12. rewrite XH5, XH6, XH7, XH8, XH9.\n  unfold hmac256drbgabs_to_state. simpl.\n  remember (HMAC256_DRBG_functional_prog.HMAC256_DRBG_update\n            (contents_with_add seed ll\n               (entropy_bytes ++ contents')) key V).\n  destruct p.\n  simpl. normalize. rewrite XH6, XH7, XH8, XH9. drop_LOCAL 0%nat. drop_LOCAL 0%nat.\n  subst contents'.\n  unfold_data_at 1%nat. (*crucial: doing the field assignment without unfolding data_at results in the forward taking 1200secs*)\n(*  freeze [0;1;2;4;5;6] FIELDS. optional wrt performance*)\n  forward.\n\n  (* return 0 *)\n  idtac \"Timing a forward (goal: 5secs)\". Time forward. (*5 secs*)\n  Exists seed (Vint (Int.repr 0)). normalize.\n  entailer!.\n\n  assert (ZL1: Zlength (contents_with_add additional (Zlength contents) contents) >? 256 = false).\n  { clear - ZLc' AL256. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. }\n\n  apply Zgt_is_gt_bool_f in AL256.\n  assert (Z: (zlt 256 (Zlength contents)\n       || zlt 384\n            (hmac256drbgabs_entropy_len\n               (HMAC256DRBGabs key V reseed_counter (Zlength entropy_bytes) prediction_resistance\n                  reseed_interval) + Zlength contents))%bool = false).\n  { destruct (zlt 256 (Zlength contents)); simpl; try omega.\n    destruct (zlt 384 (Zlength entropy_bytes + Zlength contents)); simpl; trivial. omega.\n  }\n  unfold reseedPOST. rewrite Z.\n  entailer!.\n  { unfold return_value_relate_result. simpl.\n    rewrite andb_negb_r, ZL1.\n    unfold get_entropy. rewrite <- Heqentropy_result. trivial. }\n(*  remember (mbedtls_HMAC256_DRBG_reseed_function s\n            (HMAC256DRBGabs key V reseed_counter (Zlength entropy_bytes) prediction_resistance reseed_interval)\n            (contents_with_add additional (Zlength contents) contents)).*)\n  simpl.\n  rewrite andb_negb_r, ZL1.\n  unfold get_entropy. rewrite <- Heqentropy_result.\n  remember (HMAC_DRBG_update HMAC256_functional_prog.HMAC256\n              (entropy_bytes ++ contents_with_add additional (Zlength contents) contents) key V) as q.\n  destruct q. normalize.\n  thaw FR12. thaw FR10. cancel. simpl. rewrite <- Heqp.\n  unfold  hmac256drbgabs_common_mpreds. cancel.\n  unfold get_entropy; rewrite <- Heqentropy_result. simpl. normalize. entailer!.\n  { simpl in *. unfold HMAC_DRBG_update in Heqq.\n    destruct (entropy_bytes ++\n         contents_with_add additional (Zlength contents) contents); inv Heqq.\n    + split. apply hmac_common_lemmas.HMAC_Zlength. apply hmac_common_lemmas.isbyte_hmac.\n    + split. apply hmac_common_lemmas.HMAC_Zlength. apply hmac_common_lemmas.isbyte_hmac.\n  }\n  unfold_data_at 1%nat. cancel.\n  unfold HMAC256_DRBG_functional_prog.HMAC256_DRBG_update in Heqp.\n  destruct seed; simpl in Pseed; try contradiction.\n  unfold contents_with_add in Heqp at 1. simpl in Heqp.\n  destruct (initial_world.EqDec_Z (Zlength entropy_bytes +\n                 Zlength (contents_with_add additional (Zlength contents) contents)) 0); simpl in Heqp.\n  specialize (Zlength_nonneg (contents_with_add additional (Zlength contents) contents)).\n  intros; omega.\n\n  rewrite <- Heqp in *. inv Heqq. \nidtac \"Timing the Qed of REST (goal: 45secs)\". cancel. \nTime Qed. (*Feb 23 2017: 216.218 secs (135.625u,0.046s) (successful)*)\n         (*was: Coq8.5pl2: 44secs*)\n\nLemma body_hmac_drbg_reseed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n       f_mbedtls_hmac_drbg_reseed hmac_drbg_reseed_spec.\nProof.\n  start_function.\n  rename lvar0 into seed.\n  destruct initial_state_abs.\n  destruct initial_state as [md_ctx' [V' [reseed_counter' [entropy_len' [prediction_resistance' reseed_interval']]]]].\n  unfold hmac256drbg_relate.\n  Intros. simpl in *.\n  rename H into XH1.\n  rename H0 into XH2.\n  rename H1 into XH3.\n  rename H2 into XH4.\n  rename H3 into El2.\n  rename H4 into XH6.\n  rename H5 into XH7.\n  rename H6 into XH8.\n  rename H7 into XH9.\n  rename H8 into XH10.\n  rename H9 into XH11.\n  rename H10 into XH12.\n  rename H11 into XH13.\n  rewrite da_emp_isptrornull. (*needed later*)\n  rewrite data_at_isptr with (p:=ctx).\n  Intros.\n\n  (* entropy_len = ctx->entropy_len *)\n  simpl in *.\n  remember (contents_with_add additional add_len contents) as contents'.\n  assert (ZLc': Zlength contents' = 0 \\/ Zlength contents' = Zlength contents).\n    { subst contents'. unfold contents_with_add.\n      destruct (eq_dec add_len 0); simpl.\n        rewrite andb_false_r. left; apply Zlength_nil.\n        destruct (Memory.EqDec_val additional nullval); simpl. left; apply Zlength_nil.\n        right; trivial.\n    }\n\n  freeze [0;1;3;4;5;6] FR1.\n  forward. (*{ rewrite <- H7; entailer!. }*)\n\n  remember (orb (zlt 256 add_len) (zlt 384 (entropy_len + add_len))) as add_len_too_high.\n\n  (* if (len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||\n        entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) *)\n  freeze [0;1] FR2.\n  forward_if (PROP  ()\n      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      temp _t'1 (Val.of_bool add_len_too_high);\n      gvar sha._K256 kv)\n      SEP  (FRZL FR2)).\n  { forward. entailer!. }\n  { forward. entailer!. simpl.\n      unfold Int.ltu; simpl.\n      rewrite add_repr.\n      rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n      rewrite Int.unsigned_repr_eq, Zmod_small.\n      + destruct (zlt 384 (entropy_len + (Zlength contents))); simpl; try reflexivity.\n      + omega.\n  }\n\n  forward_if (PROP  (add_len_too_high = false)\n      LOCAL  (temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP (FRZL FR2)\n  ).\n  { rewrite H in *. subst add_len_too_high. forward.\n    Exists seed (Vint (Int.neg (Int.repr 5))). normalize. entailer!.\n    unfold reseedPOST. simpl; rewrite <- Heqadd_len_too_high.\n    (*remember (zlt 256 (Zlength contents) || zlt 384 (entropy_len + Zlength contents))%bool as c.\n    destruct c; simpl in Heqadd_len_too_high; try discriminate.*)\n    normalize. apply andp_right. apply prop_right; repeat split; trivial.\n    thaw FR2. thaw FR1. cancel.\n  }\n  {\n    forward.\n    entailer!.\n  }\n  Intros. rewrite H in *; clear H add_len_too_high.\n  symmetry in Heqadd_len_too_high; apply orb_false_iff in Heqadd_len_too_high; destruct Heqadd_len_too_high.\n\n  assert (AL256: 256 >= add_len).\n  { destruct (zlt 256 add_len); try discriminate; trivial. }\n  assert (EL384 : 384 >= entropy_len + add_len).\n  { destruct ( zlt 384 (entropy_len + add_len)); try discriminate; trivial. }\n\n  thaw FR2. thaw FR1. freeze [1;2;3;4;5;6] FR3.\n  (* memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT ); *)\n  forward_call (Tsh, seed, 384, Int.zero).\n  { rewrite data_at__memory_block.\n    change (sizeof (*cenv_cs*) (tarray tuchar 384)) with 384.\n    normalize. cancel.\n  }\n\n  (*freeze [1;2;3;4;5;6] FR3.*)\n  assert_PROP (field_compatible (tarray tuchar 384) [] seed) as Hfield by entailer!.\n  replace_SEP 0 ((data_at Tsh (tarray tuchar entropy_len)\n         (list_repeat (Z.to_nat entropy_len) (Vint Int.zero)) seed) * (data_at Tsh (tarray tuchar (384 - entropy_len))\n         (list_repeat (Z.to_nat (384 - entropy_len)) (Vint Int.zero)) (offset_val entropy_len seed))).\n  {\n    (*subst entropy_len.*)\n    erewrite <- data_at_complete_split with (length:=384)(AB:=list_repeat (Z.to_nat 384) (Vint Int.zero)); repeat rewrite Zlength_list_repeat; trivial; try omega.\n    go_lower. apply derives_refl. rewrite Zplus_minus. assumption.\n    rewrite list_repeat_app. rewrite Z2Nat.inj_sub; try omega. rewrite le_plus_minus_r. trivial. apply Z2Nat.inj_le; try omega.\n  }\n  flatten_sepcon_in_SEP.\n\n  replace_SEP 0 (memory_block Tsh entropy_len seed).\n  {\n    (*subst entropy_len.*) go_lower.\n     eapply derives_trans. apply data_at_memory_block. simpl. rewrite Z.max_r, Z.mul_1_l; trivial.\n  }\n\n  (* get_entropy(seed, entropy_len ) *)\n  thaw FR3. freeze [1;2;3;4;6;7] FR4.\n  forward_call (Tsh, s, seed, entropy_len).\n  { split. split; try omega. rewrite int_max_unsigned_eq. omega.\n    apply writable_share_top.\n(*\n    subst entropy_len; auto.*)\n  }\n  Intros vret. rename H1 into ENT.\n  assert (AL256': add_len >? 256 = false).\n  { remember (add_len >? 256) as d.\n    destruct d; symmetry in Heqd; trivial.\n    apply Zgt_is_gt_bool in Heqd.\n    destruct (zlt 256 add_len); try discriminate; omega.\n  }\n  assert (EAL256': (entropy_len + add_len)  >? 384 = false).\n  { remember (entropy_len + add_len >? 384) as d.\n    destruct d; symmetry in Heqd; trivial.\n    apply Zgt_is_gt_bool in Heqd.\n    destruct (zlt 384 (entropy_len + add_len)); try discriminate; omega.\n  }\n\n  (* if( get_entropy(seed, entropy_len ) != 0 ) *)\n  freeze [0;1;2] FR5.\n  forward_if (\n      PROP  (vret=Vzero)\n      LOCAL  (temp _t'2 vret;\n      temp _entropy_len (Vint (Int.repr entropy_len));\n      lvar _seed (tarray tuchar 384) seed; temp _ctx ctx;\n      temp _additional additional; temp _len (Vint (Int.repr add_len));\n      gvar sha._K256 kv)\n      SEP (FRZL FR5)\n  ).\n  {\n    (* != 0 case *)\n    forward.\n    Exists seed (Vint (Int.neg (Int.repr (9)))). normalize. entailer!.\n    unfold reseedPOST.\n    remember ((zlt 256 (Zlength contents)\n       || zlt 384\n            (hmac256drbgabs_entropy_len\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval) + (Zlength contents)))%bool) as z.\n    destruct z.\n    { exfalso. simpl in Heqz. rewrite H, H0 in Heqz. inv Heqz. }\n    clear Heqz.\n    unfold return_value_relate_result, get_entropy in ENT.\n    simpl in ENT.\n    remember (ENTROPY.get_bytes (Z.to_nat entropy_len) s) as  GE.\n    destruct GE.\n    + inv ENT. discriminate.\n    + thaw FR5. unfold get_entropy. rewrite <- HeqGE.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s\n            (HMAC256DRBGabs key V reseed_counter 32 prediction_resistance\n               reseed_interval) (contents_with_add additional (Zlength contents) contents)) as M.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s\n             (HMAC256DRBGabs key V reseed_counter 32 prediction_resistance\n                reseed_interval) contents).\n      unfold mbedtls_HMAC256_DRBG_reseed_function, HMAC256_DRBG_functional_prog.HMAC256_DRBG_reseed_function in *.\n      unfold DRBG_reseed_function in *. rewrite andb_negb_r in *.\n      unfold return_value_relate_result in ENT.\n      unfold get_entropy in *; simpl in *. rewrite <- HeqGE in *.\n\n      rewrite AL256' in *.\n      remember (Zlength (contents_with_add additional (Zlength contents) contents)) as ZLa.\n      assert (ZLa256: ZLa >? 256 = false).\n      { destruct ZLc' as [PP | PP]; rewrite PP; trivial. }\n      rewrite ZLa256 in *. subst M r. normalize. simpl. cancel.\n      unfold get_entropy. simpl. rewrite andb_negb_r, <- HeqGE.\n      unfold hmac256drbgabs_common_mpreds. simpl. normalize.\n      apply andp_right. apply prop_right. repeat split; trivial.\n      thaw FR4. cancel.\n      rewrite data_at__memory_block. entailer!.\n      destruct seed; inv Pseed. unfold offset_val.\n      rewrite <- repr_unsigned with (i:=i).\n      assert (XX: sizeof (tarray tuchar 384) = entropy_len + (384 - entropy_len)).\n      { simpl. omega. }\n      rewrite XX.\n      rewrite (memory_block_split Tsh b (Int.unsigned i) entropy_len (384 - entropy_len)), add_repr; try omega.\n      cancel.\n      eapply derives_trans. apply data_at_memory_block.\n          simpl. rewrite Z.max_r, Z.mul_1_l; try omega; trivial.\n      rewrite Zplus_minus. cbv; trivial.\n      assert (Int.unsigned i >= 0) by (pose proof (Int.unsigned_range i); omega).\n      split. omega.\n      clear - Hfield. red in Hfield; simpl in Hfield. omega.\n  }\n  {\n    forward.\n    entailer!. clear FR4 FR5. (*subst add_len.*)\n    apply negb_false_iff in H1. symmetry in H1; apply binop_lemmas2.int_eq_true in H1.\n    subst vret; split; trivial.\n  }\n  Intros. subst vret. unfold return_value_relate_result in ENT.\n  (* now that we know entropy call succeeded, use that fact to simplify the SEP clause *)\n  remember (entropy.ENTROPY.get_bytes (Z.to_nat entropy_len) s) as entropy_result.\n  unfold entropy.get_entropy in ENT;\n  rewrite <- Heqentropy_result in ENT.\n  destruct entropy_result; [|\n    normalize;\n    simpl in ENT; destruct e; [inversion ENT | inversion ENT ]\n    (*assert (contra: False) by (apply ENT; reflexivity); inversion contra]*)\n    ].\n  Focus 2. destruct ENT_GenErrAx as [EC1 _]; elim EC1; trivial.\n(*\n  unfold entropy.get_entropy in ENT;\n  rewrite <- Heqentropy_result in ENT;\n  destruct entropy_result; [|\n  normalize;\n  simpl in ENT; destruct e; [inversion ENT |\n  assert (contra: False) by (apply ENT; reflexivity); inversion contra]\n  ].*)\n  clear ENT.\n\n  rename l into entropy_bytes.\n  thaw FR5. thaw FR4.\n  eapply REST with (s0:=s0)(contents':=contents'); trivial.\nidtac \"Timing the Qed of drbg_reseed (goal: 25secs)\". omega. \nTime Qed. (*Feb 23 2017: Finished transaction in 105.344 secs (74.078u,0.015s) (successful)*)\n          (*earlier Coq8.5pl2: 24secs*)\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/hmacdrbg/verif_hmac_drbg_reseed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.15914160290295837}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import MemoryReorder.\nRequire Import MemoryMerge.\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nRequire Import ReorderTView.\n\nSet Implicit Arguments.\n\nLemma future_read_step\n      lc1 mem1 mem1' loc ts val released ord lc2\n      (WF: Local.wf lc1 mem1)\n      (MEM: Memory.closed mem1)\n      (FUTURE: Memory.future_weak mem1 mem1')\n      (STEP: Local.read_step lc1 mem1 loc ts val released ord lc2):\n  exists released' lc2',\n    <<STEP: Local.read_step lc1 mem1' loc ts val released' ord lc2'>> /\\\n    <<REL: View.opt_le released' released>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>>.\nProof.\n  inv STEP. exploit Memory.future_weak_get1; eauto. i. des. inv MSG_LE.\n  esplits.\n  - econs; eauto. eapply TViewFacts.readable_mon; eauto; refl.\n  - auto.\n  - econs; s.\n    + apply TViewFacts.read_tview_mon; auto.\n      * refl.\n      * apply WF.\n      * inv MEM. exploit CLOSED; eauto. i. des. inv MSG_WF. auto.\n      * refl.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma future_fulfill_step\n      lc1 sc1 sc1' loc from to val releasedm releasedm' released ord lc2 sc2\n      (REL_LE: View.opt_le releasedm' releasedm)\n      (STEP: fulfill_step lc1 sc1 loc from to val releasedm released ord lc2 sc2):\n  fulfill_step lc1 sc1' loc from to val releasedm' released ord lc2 sc1'.\nProof.\n  assert (TVIEW: TView.write_tview (Local.tview lc1) sc1 loc to ord = TView.write_tview (Local.tview lc1) sc1' loc to ord).\n  { unfold TView.write_tview. repeat (condtac; viewtac). }\n  inversion STEP. subst lc2 sc2.\n  rewrite TVIEW. econs; eauto.\n  - etrans; eauto. unfold TView.write_released. condtac; econs. repeat apply View.join_spec.\n    + rewrite <- View.join_l. apply View.unwrap_opt_le. auto.\n    + rewrite <- ? View.join_r. rewrite TVIEW. refl.\n  - econs; try apply WRITABLE.\nQed.\n\nLemma future_fence_step\n      lc1 sc1 sc1' ordr ordw lc2 sc2\n      (ORDW: Ordering.le ordw Ordering.acqrel)\n      (SC_FUTURE: TimeMap.le sc1 sc1')\n      (STEP: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n  Local.fence_step lc1 sc1' ordr ordw lc2 sc1'.\nProof.\n  inv STEP.\n  erewrite TViewFacts.write_fence_tview_acqrel; auto.\n  erewrite <- TViewFacts.write_fence_sc_acqrel at 2; eauto.\nQed.\n\n\nLemma reorder_read_read\n      loc1 ts1 val1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      lc0 mem0\n      lc1\n      lc2\n      (LOC: loc1 = loc2 -> Ordering.le ord1 Ordering.plain /\\ Ordering.le ord2 Ordering.plain)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; try apply READABLE0; eauto; try refl.\n    apply TViewFacts.read_tview_incr.\n  - econs; eauto.\n    + s. unfold View.singleton_ur_if.\n      econs; repeat (try condtac; try splits; aggrtac; eauto; try apply READABLE;\n                     unfold TimeMap.singleton, LocFun.add in *).\n      * specialize (LOC eq_refl). des. viewtac.\n      * specialize (LOC eq_refl). des. viewtac.\n      * specialize (LOC eq_refl). des. viewtac.\n    + inv MEM0. exploit CLOSED; try exact GET. i. des.\n      exploit CLOSED; try exact GET0. i. des. f_equal.\n      inv MSG_WF. inv MSG_WF0.\n      apply TView.antisym; apply ReorderTView.read_read_tview;\n        (try by apply WF0); eauto.\nQed.\n\nLemma reorder_read_promise\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1' lc2' released1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind2>> /\\\n    <<STEP2: Local.read_step lc1' mem2 loc1 ts1 val1 released1' ord1 lc2'>> /\\\n    <<REL1: View.opt_le released1' released1>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit Memory.promise_future; try exact PROMISE; try apply WF0; eauto. i. des.\n  destruct (Memory.op_kind_is_cancel kind2) eqn:KIND.\n  { destruct kind2; ss. inv PROMISE.\n    esplits; [eauto|..].\n    - econs; eauto.\n      erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n      des. subst. exploit Memory.remove_get0; try exact MEM. i. des. congr.\n    - refl.\n    - s. econs; ss.\n      + apply TViewFacts.read_tview_mon; try refl; try apply WF0; eauto.\n        inv MEM0. exploit CLOSED0; eauto. i. des. inv MSG_WF. auto.\n      + apply SimPromises.sem_bot.\n  }\n  exploit Memory.promise_get1; eauto. i. des. inv MSG_LE.\n  esplits; eauto.\n  - econs; eauto.\n    s. eapply TViewFacts.readable_mon; eauto; try refl.\n  - s. econs; ss.\n    + apply TViewFacts.read_tview_mon; try refl; try apply WF0; eauto.\n      inv MEM0. exploit CLOSED0; eauto. i. des. inv MSG_WF. auto.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma reorder_read_promise_diff\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc1\n      lc2 mem2\n      (DIFF: (loc1, ts1) <> (loc2, to2))\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind2>> /\\\n    <<STEP2: Local.read_step lc1' mem2 loc1 ts1 val1 released1 ord1 lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryFacts.promise_get1_diff; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_read_fulfill\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      (LOC: loc1 <> loc2)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord2 Ordering.acqrel)\n      (RELM_WF: View.opt_wf releasedm2)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>>.\nProof.\n  guardH ORD.\n  exploit Local.read_step_future; eauto. i. des.\n  inv STEP1. inv STEP2.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s.\n      condtac; econs. repeat (try condtac; aggrtac; try apply WF0).\n    + eapply TViewFacts.writable_mon; eauto; try refl. apply TVIEW_FUTURE.\n  - econs; eauto.\n    s. inv READABLE.\n    econs; repeat (try condtac; aggrtac; try apply WF0; eauto; unfold TimeMap.singleton).\n  - s. econs; s.\n    + apply ReorderTView.read_write_tview; try apply WF0; auto.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma reorder_read_write\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2 mem2\n      kind\n      (LOC: loc1 <> loc2)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord2 Ordering.acqrel)\n      (RELM_WF: View.opt_wf releasedm2)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.write_step lc1 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind):\n  exists released2' mem2' lc1' lc2',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc2 mem2' kind>> /\\\n    <<STEP2: Local.read_step lc1' mem2' loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<RELEASED: View.opt_le released2' released2>> /\\\n    <<MEM: sim_memory mem2' mem2>>.\nProof.\n  guardH ORD.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit write_promise_fulfill; try exact STEP2; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_promise_diff; try exact STEP1; try exact STEP0; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_fulfill; try exact STEP5; try exact STEP3; eauto; try by viewtac. i. des.\n  exploit promise_fulfill_write_sim_memory; try exact x4; try exact STEP6; eauto; try by viewtac.\n  { i. hexploit ORD0; eauto. i. des.\n    splits; auto. inv STEP1. auto.\n  }\n  i. des.\n  inv STEP1.\n  inversion STEP. inv WRITE. hexploit MemoryFacts.promise_get1_diff; try exact PROMISE; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  esplits; eauto.\n  inv STEP7. econs; eauto.\nQed.\n\nLemma reorder_read_update\n      loc1 ts1 val1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      from3 to3 val3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2\n      lc3 sc3 mem3\n      kind\n      (LOC: loc1 <> loc2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2)\n      (STEP3: Local.write_step lc2 sc0 mem0 loc2 from3 to3 val3 released2 released3 ord3 lc3 sc3 mem3 kind):\n  exists released3' mem3' lc1' lc2' lc3',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc2 from3 to3 val3 released2 released3' ord3 lc2' sc3 mem3' kind>> /\\\n    <<STEP3: Local.read_step lc2' mem3' loc1 ts1 val1 released1 ord1 lc3'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc3' lc3>> /\\\n    <<RELEASED: View.opt_le released3' released3>> /\\\n    <<MEM: sim_memory mem3' mem3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_read_read; try exact STEP1; try exact STEP2; eauto; try congr. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  hexploit reorder_read_write; try exact STEP4; try exact STEP_SRC; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_read_fence\n      loc1 ts1 val1 released1 ord1\n      ordr2 ordw2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      (ORDR2: Ordering.le ordr2 Ordering.relaxed)\n      (ORDW2: Ordering.le ordw2 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.fence_step lc1 sc0 ordr2 ordw2 lc2 sc2):\n  exists lc1' lc2' sc2',\n    <<STEP1: Local.fence_step lc0 sc0 ordr2 ordw2 lc1' sc2'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto. s.\n    unfold TView.write_fence_tview, TView.read_fence_tview, TView.write_fence_sc.\n    econs; repeat (try condtac; try splits; aggrtac; try apply READABLE).\n  - s. econs; s.\n    + etrans.\n      * apply ReorderTView.read_write_fence_tview; auto.\n        eapply TViewFacts.read_fence_future; apply WF0.\n      * apply TViewFacts.write_fence_tview_mon; try refl.\n        apply ReorderTView.read_read_fence_tview; try apply WF0; auto.\n        exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n        eapply TViewFacts.read_future; eauto.\n    + apply SimPromises.sem_bot.\n  - unfold TView.write_fence_sc, TView.read_fence_tview.\n    repeat condtac; aggrtac.\nQed.\n\nLemma reorder_fulfill_read\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      (LOC: loc1 <> loc2)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: fulfill_step lc1' sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply REMOVE; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; try apply READABLE; eauto; try refl.\n    apply TViewFacts.write_tview_incr. apply WF0.\n  - unfold Local.tview at 2.\n    unfold Local.promises at 2.\n    rewrite ReorderTView.read_write_tview_eq; eauto; try apply WF0; cycle 1.\n    { inv MEM0. exploit CLOSED; eauto. i. des. inv MSG_WF. eauto. }\n    econs; try exact REMOVE; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac).\n    + s. unfold View.singleton_ur_if.\n      econs; repeat (try condtac; try splits; aggrtac; eauto; try apply WRITABLE;\n                     unfold TimeMap.singleton, LocFun.add in *);\n        (try by inv WRITABLE; eapply TimeFacts.le_lt_lt; eauto; aggrtac).\nQed.\n\nLemma reorder_fulfill_promise\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind2>> /\\\n    <<STEP2: fulfill_step lc1' sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply WF0; eauto. i. des.\n  hexploit Memory.promise_future; eauto.\n  { ii. inv WF0.\n    erewrite Memory.remove_o; eauto. condtac; ss. }\n  i. des.\n  exploit MemoryReorder.remove_promise; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\nQed.\n\nLemma reorder_fulfill_fulfill\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (LOC: loc1 <> loc2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: fulfill_step lc1 sc1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc1'>> /\\\n    <<STEP2: fulfill_step lc1' sc1' loc1 from1 to1 val1 releasedm1 released1 ord1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply WF0; eauto. i. des.\n  exploit MemoryReorder.remove_remove; try apply REMOVE; try apply REMOVE0; eauto. i. des.\n  unfold Local.promises in REMOVE0.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac; try apply WF0).\n    + eapply TViewFacts.writable_mon; eauto; try refl.\n      * apply TViewFacts.write_tview_incr. apply WF0.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac; try apply WF0).\n    + inv WRITABLE. econs; i.\n      * eapply TimeFacts.le_lt_lt; [|apply TS].\n        repeat (try condtac; viewtac; unfold TimeMap.singleton in *).\n  - s. econs; ss.\n    + apply ReorderTView.write_write_tview; auto. apply WF0.\n    + apply SimPromises.sem_bot.\n  - refl.\nQed.\n\nLemma reorder_fulfill_write_sim_memory\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2 mem2\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (LOC: loc1 <> loc2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL1_CLOSED: Memory.closed_opt_view releasedm1 mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.write_step lc1 sc1 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2):\n  exists released2' lc1' lc2' sc1' sc2' mem2',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc1' mem2' kind2>> /\\\n    <<STEP2: fulfill_step lc1' sc1' loc1 from1 to1 val1 releasedm1 released1 ord1 lc2' sc2'>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>> /\\\n    <<MEM: sim_memory mem2' mem2>>.\nProof.\n  exploit fulfill_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP1; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP5; try exact WF3;\n    eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  exploit reorder_fulfill_fulfill; try exact STEP5; try exact STEP3;\n    eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  exploit promise_fulfill_write_sim_memory; eauto.\n  { i. hexploit ORD; eauto. i. des. splits; ss.\n    ii. unfold Memory.get in GET.\n    erewrite fulfill_step_promises_diff in GET; eauto.\n    exploit H0; eauto.\n  }\n  i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fulfill_update\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      from3 to3 val3 released3 ord3 kind3\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      lc3 sc3 mem3\n      (LOC: loc1 <> loc2)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL1_CLOSED: Memory.closed_opt_view releasedm1 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2)\n      (STEP3: Local.write_step lc2 sc1 mem0 loc2 from3 to3 val3 released2 released3 ord3 lc3 sc3 mem3 kind3):\n  exists released3' lc1' lc2' lc3' sc2' sc3' mem2',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc2 from3 to3 val3 released2 released3' ord3 lc2' sc2' mem2' kind3>> /\\\n    <<STEP3: fulfill_step lc2' sc2' loc1 from1 to1 val1 releasedm1 released1 ord1 lc3' sc3'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc3' lc3>> /\\\n    <<RELEASED: View.opt_le released3' released3>> /\\\n    <<SC: TimeMap.le sc3' sc3>> /\\\n    <<MEM: sim_memory mem2' mem3>>.\nProof.\n  exploit fulfill_step_future; try exact STEP1; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_read; try exact STEP1; try exact STEP2; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP4; eauto. i. des.\n  hexploit sim_local_write_bot; try exact STEP3; try exact LOCAL; try refl; eauto. i. des.\n  hexploit reorder_fulfill_write_sim_memory; try exact STEP4; try exact STEP3; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_read\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 ts3 val3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3\n      (LOC: loc1 <> loc3)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord3 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.read_step lc2 mem0 loc3 ts3 val3 released3 ord3 lc3):\n  exists lc1' lc2',\n    <<STEP1: Local.read_step lc0 mem0 loc3 ts3 val3 released3 ord3 lc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1 released2 ord2 lc3 sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_read; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  exploit reorder_read_read; try exact STEP1; try exact STEP0; eauto; try congr. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_promise\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 msg3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 mem3\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.promise_step lc2 mem0 loc3 from3 to3 msg3 lc3 mem3 kind3):\n  exists released1' lc1' lc2' lc3' sc3',\n    <<STEP1: Local.promise_step lc0 mem0 loc3 from3 to3 msg3 lc1' mem3 kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem3 loc1 ts1 val1 released1' ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1' released2 ord2 lc3' sc3'>> /\\\n    <<RELEASED1: View.opt_le released1' released1>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc3' lc3>> /\\\n    <<SC: TimeMap.le sc3' sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_promise; try exact STEP1; try exact STEP0; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_fulfill_bot; try exact STEP4; try exact LOCAL; try exact REL1;\n    try exact WF3; try exact WF5; try refl;\n      eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_promise_diff\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 msg3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 mem3\n      (DIFF: (loc1, ts1) <> (loc3, to3))\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.promise_step lc2 mem0 loc3 from3 to3 msg3 lc3 mem3 kind3):\n  exists lc1' lc2',\n    <<STEP1: Local.promise_step lc0 mem0 loc3 from3 to3 msg3 lc1' mem3 kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem3 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1 released2 ord2 lc3 sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit reorder_read_promise_diff; try exact STEP1; try exact STEP0; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_fulfill\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 releasedm3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 sc3\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (REL_WF: View.opt_wf releasedm3)\n      (REL_CLOSED: Memory.closed_opt_view releasedm3 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: fulfill_step lc2 sc2 loc3 from3 to3 val3 releasedm3 released3 ord3 lc3 sc3):\n  exists lc1' lc2' lc3' sc1' sc3',\n    <<STEP1: fulfill_step lc0 sc0 loc3 from3 to3 val3 releasedm3 released3 ord3 lc1' sc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc1' loc1 from2 to2 val2 released1 released2 ord2 lc3' sc3'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc3' lc3>> /\\\n    <<SC: TimeMap.le sc3' sc3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_fulfill; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP0; eauto; try by viewtac. i. des.\n  exploit reorder_read_fulfill; try exact STEP1; try exact STEP0; eauto; try by viewtac. i. des.\n  exploit fulfill_step_future; try exact STEP5; eauto; try by viewtac. i. des.\n  exploit Local.read_step_future; try exact STEP6; eauto; try by viewtac. i. des.\n  exploit sim_local_fulfill_bot; try exact STEP4; try exact LOCAL0; try refl; eauto. i. des.\n  esplits; eauto.\n  etrans; eauto.\nQed.\n\nLemma reorder_update_write\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 releasedm3 released3 ord3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 sc3 mem3\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (REL_WF: View.opt_wf releasedm3)\n      (REL_CLOSED: Memory.closed_opt_view releasedm3 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.write_step lc2 sc2 mem0 loc3 from3 to3 val3 releasedm3 released3 ord3 lc3 sc3 mem3 kind3):\n  exists released2' released3' lc1' lc2' lc3' sc1' sc3' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc3 from3 to3 val3 releasedm3 released3' ord3 lc1' sc1' mem1' kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem1' loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc1' loc1 from2 to2 val2 released1 released2' ord2 lc3' sc3'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc3' lc3>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<RELEASED3: View.opt_le released3' released3>> /\\\n    <<SC: TimeMap.le sc3' sc3>> /\\\n    <<MEM: sim_memory mem1' mem3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit fulfill_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit reorder_update_promise_diff; try exact STEP1; try exact STEP2; try exact STEP0; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit reorder_update_fulfill; try exact STEP6; try exact STEP7; try exact STEP4;\n    eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  exploit fulfill_step_future; try exact STEP8; try exact WF3;\n    eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  exploit promise_fulfill_write_sim_memory; eauto.\n  { i. hexploit ORD; eauto. i. des.\n    splits; auto.\n    erewrite Local.read_step_promises; [|eauto].\n    ii. unfold Memory.get in GET.\n    erewrite fulfill_step_promises_diff in GET; eauto.\n    exploit H0; eauto.\n  }\n  i. des.\n  inv STEP1.\n  inversion STEP. inv WRITE. hexploit MemoryFacts.promise_get1_diff; try exact PROMISE; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  esplits; try exact STEP10; eauto; try refl.\n  inv STEP9. econs; eauto.\nQed.\n\nLemma reorder_update_update\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 ts3 val3 released3 ord3\n      from4 to4 val4 released4 ord4 kind4\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3\n      lc4 sc4 mem4\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord3 Ordering.relaxed)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord4 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.read_step lc2 mem0 loc3 ts3 val3 released3 ord3 lc3)\n      (STEP4: Local.write_step lc3 sc2 mem0 loc3 from4 to4 val4 released3 released4 ord4 lc4 sc4 mem4 kind4):\n  exists released2' released4' lc1' lc2' lc3' lc4' sc2' sc4' mem2',\n    <<STEP1: Local.read_step lc0 mem0 loc3 ts3 val3 released3 ord3 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc3 from4 to4 val4 released3 released4' ord4 lc2' sc2' mem2' kind4>> /\\\n    <<STEP3: Local.read_step lc2' mem2' loc1 ts1 val1 released1 ord1 lc3'>> /\\\n    <<STEP4: fulfill_step lc3' sc2' loc1 from2 to2 val2 released1 released2' ord2 lc4' sc4'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc4' lc4>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<RELEASED4: View.opt_le released4' released4>> /\\\n    <<SC: TimeMap.le sc4' sc4>> /\\\n    <<MEM: sim_memory mem2' mem4>>.\nProof.\n  guardH ORD.\n  exploit reorder_update_read; try exact STEP2; try exact STEP1; try exact STEP3; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  hexploit reorder_update_write; try exact STEP5; try exact STEP6; try exact STEP4; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fence_read\n      ordr1 ordw1\n      loc2 to2 val2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.plain \\/ Ordering.le Ordering.acqrel ord2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 to2 val2 released2 ord2 lc2):\n  exists lc1' lc2' sc2',\n    <<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc0 ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc1>>.\nProof.\n  guardH ORD2. inv STEP1. inv STEP2.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; eauto; try refl.\n    etrans.\n    + apply TViewFacts.write_fence_tview_incr. apply WF0.\n    + apply TViewFacts.write_fence_tview_mon; try refl; try apply WF0.\n      apply TViewFacts.read_fence_tview_incr. apply WF0.\n  - econs; eauto.\n  - s. econs; s.\n    + inversion MEM0. exploit CLOSED; eauto. i. des.\n      exploit TViewFacts.read_future; try exact GET; try apply WF0; eauto.\n      { inv MEM0. exploit CLOSED0; eauto. i. des. inv MSG_WF. ss. }\n      i. des.\n      exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n      etrans; [|etrans].\n      * apply TViewFacts.write_fence_tview_mon; [|refl|refl|].\n        { apply ReorderTView.read_fence_read_tview; auto. apply WF0. }\n        { inversion MEM0. exploit CLOSED; eauto. i. des.\n          eapply TViewFacts.read_fence_future; eauto.\n        }\n      * apply ReorderTView.write_fence_read_tview; eauto.\n        { inv MEM0. exploit CLOSED0; eauto. i. des. inv MSG_WF. ss. }\n      * apply TViewFacts.read_tview_mon; auto; try refl.\n        { eapply TViewFacts.write_fence_future; eauto. }\n        { inv MEM0. exploit CLOSED0; eauto. i. des. inv MSG_WF. ss. }\n    + apply SimPromises.sem_bot.\n  - s. etrans.\n    + apply TViewFacts.write_fence_sc_mon; [|refl|refl].\n      apply ReorderTView.read_fence_read_tview; auto. apply WF0.\n    + eapply ReorderTView.write_fence_read_sc; auto.\n      eapply TViewFacts.read_fence_future; eauto; apply WF0.\nQed.\n\nLemma reorder_fence_promise\n      ordr1 ordw1\n      loc2 from2 to2 msg2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 mem2\n      kind\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind>> /\\\n    <<STEP2: Local.fence_step lc1' sc0 ordr1 ordw1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\n    + s. i. destruct ordw1; inv ORDW1; inv H.\n    + s. i. destruct ordw1; inv ORDW1; inv H.\nQed.\n\nLemma reorder_fence_fulfill\n      ordr1 ordw1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: fulfill_step lc1 sc1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2.\n  exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n  hexploit TViewFacts.write_fence_future; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. condtac; econs.\n      repeat apply View.join_spec.\n      * rewrite <- View.join_l. refl.\n      * rewrite <- ? View.join_r.\n        eapply TViewFacts.write_tview_mon; eauto; try refl.\n        { etrans.\n          - apply TViewFacts.write_fence_tview_incr. apply WF0.\n          - apply TViewFacts.write_fence_tview_mon; try refl; try apply WF0.\n            apply TViewFacts.read_fence_tview_incr. apply WF0.\n        }\n    + eapply TViewFacts.writable_mon; eauto; try refl.\n      * etrans.\n        { apply TViewFacts.read_fence_tview_incr. apply WF0. }\n        { apply TViewFacts.write_fence_tview_incr.\n          eapply TViewFacts.read_fence_future; apply WF0.\n        }\n      * apply TViewFacts.write_fence_sc_incr.\n  - econs; eauto.\n    + ss. ii. revert GET.\n      erewrite Memory.remove_o; eauto. condtac; ss. i. eapply RELEASE; eauto.\n    + ss. ii. subst. erewrite PROMISES in REMOVE; eauto.\n      eapply Memory.remove_get0 in REMOVE. des.\n      erewrite Memory.bot_get in *. ss.\n  - s. econs; s.\n    + etrans; [|etrans].\n      * apply TViewFacts.write_fence_tview_mon; [|refl|refl|].\n        { apply ReorderTView.read_fence_write_tview; auto. apply WF0. }\n        { exploit Memory.remove_get0; eauto. s. i. des.\n          inv WF0. exploit PROMISES0; eauto. i.\n          exploit TViewFacts.write_future_fulfill; try exact SC0; eauto.\n          { inv MEM0. exploit CLOSED; eauto. i. des. inv MSG_CLOSED. ss.  }\n          i. des.\n          eapply TViewFacts.read_fence_future; eauto.\n        }\n      * apply ReorderTView.write_fence_write_tview; auto.\n      * apply TViewFacts.write_tview_mon; auto; try refl.\n        apply TViewFacts.write_fence_sc_incr.\n    + apply SimPromises.sem_bot.\n  - etrans.\n    + apply TViewFacts.write_fence_sc_mon; [|refl|refl].\n      apply ReorderTView.read_fence_write_tview; auto. apply WF0.\n    + eapply ReorderTView.write_fence_write_sc; auto.\nGrab Existential Variables.\n  { apply TimeMap.bot. }\nQed.\n\nLemma reorder_fence_write\n      ordr1 ordw1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2 mem2 kind\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.write_step lc1 sc1 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind):\n  exists released2' lc1' lc2' sc1' sc2' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc1' mem1' kind>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<SC: TimeMap.le sc2' sc2>> /\\\n    <<MEM: sim_memory mem1' mem2>>.\nProof.\n  exploit Local.fence_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit reorder_fence_promise; try exact STEP1; try exact STEP0; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_fence_fulfill; try exact STEP5; try exact STEP3;\n    eauto using Memory.future_closed_opt_view, Memory.future_closed_timemap. i. des.\n  exploit promise_fulfill_write_sim_memory; eauto.\n  { i. hexploit ORD; eauto. i. des.\n    splits; auto. inv STEP1. auto.\n  }\n  i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fence_fence\n      ordr1 ordw1\n      ordr2 ordw2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (ORDR2: Ordering.le ordr2 Ordering.relaxed)\n      (ORDW2: Ordering.le ordw2 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.fence_step lc1 sc1 ordr2 ordw2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: Local.fence_step lc0 sc0 ordr2 ordw2 lc1' sc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local SimPromises.bot lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\n  - ss. econs; ss.\n    + unfold TView.write_fence_tview, TView.write_fence_sc.\n      econs; repeat (try condtac; aggrtac; try apply WF0).\n    + apply SimPromises.sem_bot.\n  - unfold TView.write_fence_sc.\n    repeat (try condtac; aggrtac; try apply WF0).\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/opt/ReorderStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3106943768319878, "lm_q1q2_score": 0.1589874716131413}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Export CertiGraph.lib.find_lemmas.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Export CertiGraph.graph.undirected_graph.\nRequire Export CertiGraph.graph.MathAdjMatGraph.\n\nLocal Open Scope logic.\nLocal Open Scope Z_scope.\n\nSection Mathematical_Undirected_AdjMat_Model.\n  \nContext {size: Z} {inf: Z}.\n\nDefinition UAdjMatLG := AdjMatLG.\n\n(* We just add a further constraint to AdjMat's soundness *)\nClass SoundUAdjMat (g: UAdjMatLG) := {\n  sadjmat: @SoundAdjMat size inf g;\n  uer: forall e, evalid g e -> src g e <= dst g e;\n  em: (* evalid_meaning *)\n    forall e, evalid g e <-> \n              Int.min_signed <= elabel g e <= Int.max_signed /\\\n              elabel g e < inf;\n}.\n\nDefinition UAdjMatGG := (GeneralGraph V E DV DE DG (fun g => SoundUAdjMat g)).\n\n(* Some handy coercions: *)\nIdentity Coercion AdjMatLG_UAdjMatLG: UAdjMatLG >-> AdjMatLG.\nIdentity Coercion LabeledGraph_AdjMatLG: AdjMatLG >-> LabeledGraph.\n\nDefinition SoundUAdjMat_UAdjMatGG (g: UAdjMatGG) := (@sound_gg _ _ _ _ _ _ _ _ g).\n\n(* We can always drag out SoundAdjMat *)\nDefinition SoundAdjMat_UAdjMatGG (g: UAdjMatGG) :=\n  @sadjmat g (SoundUAdjMat_UAdjMatGG g).\n\n(* A UAdjMatGG can be weakened into an AdjMatGG *)\nDefinition AdjMatGG_UAdjMatGG (g: UAdjMatGG) : AdjMatGG :=\n  Build_GeneralGraph DV DE DG SoundAdjMat g (SoundAdjMat_UAdjMatGG g).\n\nCoercion AdjMatGG_UAdjMatGG: UAdjMatGG >-> AdjMatGG.\n\n(* Great! So now when we want to access an AdjMat\n   plugin, we can simply use the AdjMat getter \n   and pass it a UAdjMatGG. The coercion will be seamless. \n *)\n\n(* For the two new UAdjMat-specific plugins, we create getters *)\nDefinition undirected_edge_rep (g: UAdjMatGG) :=\n  @uer g (SoundUAdjMat_UAdjMatGG g).\n\nDefinition evalid_meaning (g: UAdjMatGG) :=\n  @em g ((@sound_gg _ _ _ _ _ _ _ _ g)).\n\n(* \n   A nice-to-do future step:\n   Move any known lemmas that depend only on\n   AdjMatSoundness + the above soundness plugin\n   to this file instead of leaving it down below.\n *)\n\n(* Downstream, we will need a little utility to\n   reorder our vertices for the purposes of representation *)\nDefinition eformat (e: E) := if fst e <=? snd e then e else (snd e, fst e).\n\n(* Some lemmas about eformat *)\n\nLemma eformat1: forall (e: E), fst e <= snd e -> eformat e = e.\nProof. unfold eformat; intros. rewrite Zle_is_le_bool in H; rewrite H. auto. Qed.\n\nLemma eformat2': forall (e: E), snd e < fst e -> eformat e = (snd e, fst e).\nProof. unfold eformat; intros. rewrite <- Z.leb_gt in H; rewrite H. auto. Qed.\n\nLemma eformat2: forall (e: E), snd e <= fst e -> eformat e = (snd e, fst e).\nProof.\n  intros. apply Z.le_lteq in H. destruct H. rewrite eformat2'; auto. rewrite eformat1, H. rewrite <- H at 2. destruct e; auto. lia.\nQed.\n\nLemma eformat_eq:\n  forall u v a b, eformat (u,v) = eformat (a,b) -> ((u=a /\\ v=b) \\/ (u=b /\\ v=a)).\nProof.\n  intros. destruct (Z.le_ge_cases u v); destruct (Z.le_ge_cases a b).\n  rewrite eformat1, eformat1 in H. apply pair_equal_spec in H. left; auto. simpl; auto. simpl; auto. simpl; auto.\n  rewrite eformat1, eformat2 in H. simpl in H. apply pair_equal_spec in H. right; auto. simpl; auto. simpl; auto.\n  rewrite eformat2, eformat1 in H. simpl in H. apply pair_equal_spec in H. right; split; apply H. simpl; auto. simpl; auto.\n  rewrite eformat2, eformat2 in H. simpl in H. apply pair_equal_spec in H. left; split; apply H. simpl; auto. simpl; auto.\nQed.\n\nLemma eformat_symm:\n  forall u v, eformat (u,v) = eformat (v,u).\nProof.\n  intros. destruct (Z.lt_trichotomy u v).\n  rewrite eformat1. rewrite eformat2. simpl; auto. simpl; lia. simpl; lia.\n  destruct H.\n  rewrite eformat1. rewrite eformat2. simpl; auto. simpl; lia. simpl; lia.\n  rewrite eformat2'. rewrite eformat1. simpl; auto. simpl; lia. simpl; lia.\nQed.\n\n#[export] Instance Finite_UAdjMatGG (g: UAdjMatGG):\n  FiniteGraph g.\nProof. apply (finGraph g). Qed.\n\nLemma vert_bound:\nforall (g: UAdjMatGG) v, vvalid g v <-> 0 <= v < size.\nProof.\nintros. apply (vvalid_meaning g).\nQed.\n\nLemma UAdjMatGG_VList:\n  forall (g: UAdjMatGG), Permutation (VList g) (nat_inc_list (Z.to_nat size)).\nProof.\nintros. apply NoDup_Permutation. apply NoDup_VList. apply nat_inc_list_NoDup.\nintros. rewrite VList_vvalid. rewrite vert_bound.\nrewrite nat_inc_list_in_iff. rewrite Z_to_nat_max.\ndestruct (Z.lt_trichotomy size 0). rewrite Z.max_r by lia. split; intros; lia.\ndestruct H. rewrite H. unfold Z.max; simpl. split; lia.\nrewrite Z.max_l by lia. split; auto.\nQed.\n\nLemma evalid_form: (*useful for a = (u,v) etc*)\nforall (g: UAdjMatGG) e, evalid g e -> e = (src g e, dst g e).\nProof.\n  intros.\n  rewrite (edge_src_fst g).\n  rewrite (edge_dst_snd g).\n  destruct e; simpl; auto.\nQed.\n\nLemma evalid_vvalid:\nforall (g: UAdjMatGG) u v, evalid g (u,v) -> vvalid g u /\\ vvalid g v.\nProof.\nintros. apply (evalid_strong_evalid g) in H. destruct H.\nrewrite (edge_src_fst g), (edge_dst_snd g) in H0 by auto.\nsimpl in H0; auto.\nQed.\n\nLemma evalid_adjacent:\nforall (g: UAdjMatGG) u v, evalid g (u,v) -> adjacent g u v.\nProof.\nintros. exists (u,v); split. apply (evalid_strong_evalid g); auto.\nrewrite (edge_src_fst g), (edge_dst_snd g) by auto. left; simpl; auto.\nQed.\n\nLemma evalid_inf_iff:\nforall (g: UAdjMatGG) e, evalid g e <-> elabel g e < inf.\nProof.\n  intros; split; intros.\n  apply (evalid_meaning g); auto.\ndestruct (evalid_dec g e). \nauto. exfalso.\nrewrite (invalid_edge_weight g) in n.\nreplace (elabel g e) with inf in * by trivial.\nlia.\nQed.\n\nLemma weight_representable:\nforall (g: UAdjMatGG) e, Int.min_signed <= elabel g e <= Int.max_signed.\nProof.\n  intros. destruct (evalid_dec g e).\napply (evalid_meaning g e); auto.\nrewrite (invalid_edge_weight g) in n.\nreplace (elabel g e) with inf in * by trivial.\npose proof (inf_representable g). rep_lia. \nQed.\n\nLemma weight_inf_bound:\nforall (g: UAdjMatGG) e, elabel g e <= inf.\nProof.\nintros. destruct (evalid_dec g e).\napply Z.lt_le_incl. apply (evalid_meaning  g e). auto.\napply (invalid_edge_weight g) in n.\nreplace (elabel g e) with inf in * by trivial. lia.\nQed.\n\nLemma adj_edge_form:\nforall (g: UAdjMatGG) u v a b, adj_edge g (u,v) a b -> a <= b -> (u = a /\\ v = b).\nProof.\nintros. destruct H. assert (src g (u,v) <= dst g (u,v)).\napply (undirected_edge_rep g). apply H.\nrewrite (edge_src_fst g), (edge_dst_snd g) in *.\nsimpl in *. destruct H1. auto. destruct H1; subst u; subst v. lia.\nall: apply H.\nQed.\n\nLemma eformat_evalid_vvalid:\nforall (g: UAdjMatGG) u v, evalid g (eformat (u,v)) -> vvalid g u /\\ vvalid g v.\nProof.\nintros. apply (evalid_strong_evalid g) in H.\ndestruct (Z.lt_trichotomy u v).\nrewrite eformat1 in H. destruct H.\nrewrite (edge_src_fst g), (edge_dst_snd g) in H1; auto. simpl; lia.\ndestruct H0.\nsubst u. rewrite eformat1 in H. destruct H.\nrewrite (edge_src_fst g), (edge_dst_snd g) in H0; auto. simpl; lia.\nrewrite eformat2 in H. simpl in H; destruct H.\nrewrite (edge_src_fst g), (edge_dst_snd g) in H1; auto. simpl in H1.\nsplit; apply H1. simpl; lia.\nQed.\n\nLemma eformat_adj': forall (g : UAdjMatGG) u v, evalid g (eformat (u,v)) -> adj_edge g (eformat (u,v)) u v.\nProof.\nintros. split. apply (evalid_strong_evalid g); auto.\ndestruct (Z.le_ge_cases u v).\nrewrite eformat1 in *. left. rewrite (edge_src_fst g), (edge_dst_snd g); auto. auto. auto.\nrewrite eformat2 in *. right. rewrite (edge_src_fst g), (edge_dst_snd g); auto. auto. auto.\nQed.\n\nLemma eformat_adj: forall (g: UAdjMatGG) u v, adjacent g u v <-> evalid g (eformat (u,v)).\nProof.\nintros. split. intros.\n+\ndestruct H. destruct H. destruct H.\ndestruct H0; destruct H0. assert (x = (u,v)). {\n  rewrite (edge_src_fst g) in H0.\n  rewrite (edge_dst_snd g) in H2. rewrite <- H0, <- H2. destruct x; simpl; auto.\n} subst x.\nrewrite eformat1; auto. simpl.\nrewrite <- H0. rewrite <- H2 at 2. apply (undirected_edge_rep g); auto.\nassert (x = (v,u)). {\n  rewrite (edge_src_fst g) in H0; rewrite (edge_dst_snd g) in H2.\n  rewrite <- H0, <- H2. destruct x; simpl; auto.\n} subst x.\nrewrite eformat2. simpl. auto. simpl. rewrite <- H0. rewrite <- H2 at 2.\napply (undirected_edge_rep g); auto.\n+intros. destruct (Z.lt_trichotomy u v).\nrewrite eformat1 in H. 2: simpl; lia.\nassert (evalid g (u,v)). auto.\nexists (u,v). split. apply (evalid_strong_evalid g); auto. left.\nrewrite (edge_src_fst g), (edge_dst_snd g); auto.\n(*equal, repeat*)\ndestruct H0. rewrite eformat1 in H. 2: simpl; lia.\nassert (evalid g (u,v)). auto.\nexists (u,v). split. apply (evalid_strong_evalid g); auto. left.\nrewrite (edge_src_fst g), (edge_dst_snd g); auto.\nrewrite eformat2 in H. 2: simpl; lia. simpl in H.\nassert (evalid g (v,u)). auto.\nexists (v,u). split. apply (evalid_strong_evalid g); auto.\nrewrite (edge_src_fst g), (edge_dst_snd g); auto.\nQed.\n\nCorollary eformat_adj_elabel: forall (g: UAdjMatGG) u v, adjacent g u v <-> elabel g (eformat (u,v)) < inf.\nProof.\nintros. rewrite eformat_adj. apply evalid_inf_iff.\nQed.\n\nSection EDGELESS_UADJMATGRAPH.\n\nContext {inf_bound: 0 < inf <= Int.max_signed}.\nContext {size_bound: 0 < size <= Int.max_signed}.\n\nDefinition edgeless_lgraph : UAdjMatLG :=\n  @Build_LabeledGraph V E V_EqDec E_EqDec unit Z unit\n    (@Build_PreGraph V E V_EqDec E_EqDec (fun v => 0 <= v < size) (fun e => False) fst snd)\n    (fun v => tt) (fun e => inf) tt. \n\n#[export] Instance SoundUAdjMat_edgeless:\n  SoundUAdjMat edgeless_lgraph.\nProof. \nconstructor.\nall: simpl; intros; try contradiction.\n- constructor. \n  auto. auto. \n  all: simpl; intros; try auto; try contradiction.\n  split; intros; lia. \n  split; intros; trivial.\n  split; intros. contradiction. destruct H.\n  destruct H; apply H0; reflexivity.\n  split; intros. trivial. unfold not. inversion 1.\n  constructor; unfold EnumEnsembles.Enumerable.\n  (*vertices*)\n  exists (nat_inc_list (Z.to_nat size)); split. apply nat_inc_list_NoDup.\n  simpl. intros. rewrite nat_inc_list_in_iff. rewrite Z_to_nat_max.\n  destruct (Z.lt_trichotomy size 0). rewrite Z.max_r by lia. split; intros; lia.\n  destruct H. rewrite H. unfold Z.max; simpl. split; lia.\n  rewrite Z.max_l by lia. split; auto.\n  (*edges*)\n  exists nil. simpl. split. apply NoDup_nil. intros; split; intros; auto.\n- split. inversion 1. intros.\n  destruct H.\n  apply Zaux.Zgt_not_eq in H0.\n  apply H0; reflexivity.\nQed.\n\nDefinition edgeless_graph: UAdjMatGG :=\n  @Build_GeneralGraph V E V_EqDec E_EqDec unit Z unit SoundUAdjMat\n    edgeless_lgraph SoundUAdjMat_edgeless.\n\nLemma edgeless_graph_evalid:\n  forall e, ~ evalid edgeless_graph e.\nProof.\nintros. unfold edgeless_graph; simpl. auto.\nQed.\n\nLemma edgeless_graph_EList:\n  EList edgeless_graph = nil.\nProof.\n  intros. unfold edgeless_graph, EList.\n  destruct finiteE. simpl in *.\n  destruct a.\n  destruct x; [trivial | exfalso].\n  assert (In e (e::x)) by (apply in_eq).\n  apply (H0 e). apply H1.\nQed.\n\nLemma edgeless_partial_lgraph:\n  forall (g: UAdjMatGG), is_partial_lgraph edgeless_graph g.\nProof.\nintros. split. unfold is_partial_graph.\nsplit. intros. simpl. simpl in H. rewrite vert_bound. auto.\nsplit. intros. pose proof (edgeless_graph_evalid e). contradiction.\nsplit. intros. pose proof (edgeless_graph_evalid e). contradiction.\nintros. pose proof (edgeless_graph_evalid e). contradiction.\nsplit. unfold preserve_vlabel; intros. destruct vlabel; destruct vlabel. auto.\nunfold preserve_elabel; intros. pose proof (edgeless_graph_evalid e). contradiction.\nQed.\n\nLemma uforest'_edgeless_graph:\n  uforest' edgeless_graph.\nProof.\nsplit; intros.\n(*no self-loops*)\napply edgeless_graph_evalid in H; contradiction.\nsplit; intros.\n(*only one edge between two vertices*)\ndestruct H. destruct H. destruct H.\napply edgeless_graph_evalid in H; contradiction.\n(*no rubbish edges*)\nsplit; intros.\napply edgeless_graph_evalid in H; contradiction.\n(*main forest definition*)\nunfold unique_simple_upath; intros. destruct H0 as [? [? ?]].\ndestruct p1. inversion H3. destruct p1.\ninversion H3. inversion H4. subst u; subst v.\ndestruct H2 as [? [? ?]]. destruct p2. inversion H5.\ndestruct p2. inversion H5. subst v. auto.\ndestruct H2. destruct H2. destruct H2. destruct H2. simpl in H2. contradiction.\ndestruct H0. destruct H0. destruct H0. destruct H0. simpl in H0. contradiction.\nQed.\n\nLemma edgeless_graph_disconnected:\nforall u v, u <> v -> ~ connected edgeless_graph u v.\nProof.\nunfold not; intros.\ndestruct H0 as [p [? [? ?]]].\ndestruct p. inversion H1.\ndestruct p. inversion H1; inversion H2. subst u; subst v. contradiction.\ndestruct H0. destruct H0. destruct H0. destruct H0.\npose proof (edgeless_graph_evalid x). contradiction.\nQed.\n\nEnd EDGELESS_UADJMATGRAPH.\n\nSection ADD_EDGE_UADJMATGRAPH.\n\nContext {g: UAdjMatGG}.\nContext {u v: V} {vvalid_u: vvalid g u} {vvalid_v: vvalid g v} {uv_smaller: u <= v}.\nContext {w: Z} {w_rep: Int.min_signed <= w < inf}.\n\nDefinition UAdjMatGG_adde':=\n  labeledgraph_add_edge g (u,v) u v w.\n\n#[export] Instance Fin_UAdjMatGG_adde':\n  FiniteGraph (UAdjMatGG_adde').\nProof.\n  unfold UAdjMatGG_adde'.\n  unfold labeledgraph_add_edge.\n  apply pregraph_add_edge_finite.\n  apply Finite_UAdjMatGG.\nQed.\n\n#[export] Instance SoundUAdjMat_adde':\n  SoundUAdjMat UAdjMatGG_adde'.\nProof.\nconstructor; simpl. constructor; simpl.\n+apply (size_representable g).\n+apply (inf_representable g).\n+apply (vvalid_meaning g).\n+unfold addValidFunc, updateEdgeFunc, update_elabel; intros.\n  split; intros. destruct H. unfold equiv_dec; destruct E_EqDec.\n  split. pose proof (inf_representable g); lia. lia.\n  apply (evalid_meaning g) in H. destruct H; split; lia. \n  subst e. unfold equiv_dec. destruct E_EqDec.\n  split. pose proof (inf_representable g); lia. lia.\n  unfold complement, equiv in c; contradiction.\n  unfold equiv_dec in H; destruct (E_EqDec (u,v)).\n  hnf in e0; subst e. right; auto.\n  left. apply (MathAdjMatGraph.evalid_meaning g). auto.\n+unfold addValidFunc, update_elabel, equiv_dec; intros. destruct (E_EqDec (u,v) e);  destruct H.\n hnf in e0. subst e.\n apply add_edge_strong_evalid; trivial.\n hnf in e0. subst e.\n apply add_edge_strong_evalid; trivial.\n apply add_edge_preserves_strong_evalid; trivial.\n apply (evalid_strong_evalid g); trivial.\n hnf in c. exfalso. apply c. hnf. auto. \n+ split; intros; unfold update_elabel, equiv_dec in *; destruct (E_EqDec (u,v) e).\n- exfalso. apply H. right. hnf in e0. auto.\n- apply Decidable.not_or in H. destruct H.\n  apply (invalid_edge_weight g); trivial.\n- rewrite H in w_rep. lia.\n- apply Classical_Prop.and_not_or.\n  split. apply <- (invalid_edge_weight g); trivial.\n  auto.\n+ unfold addValidFunc, updateEdgeFunc, equiv_dec; intros. destruct (E_EqDec (u,v) e).\n  unfold equiv in e0; subst e. simpl; auto.\n  apply (edge_src_fst g e).\n+unfold addValidFunc, updateEdgeFunc, equiv_dec; intros. destruct (E_EqDec (u,v) e).\n  unfold equiv in e0; subst e. simpl; auto.\n  apply (edge_dst_snd g e).\n+apply Fin_UAdjMatGG_adde'.\n+unfold addValidFunc, updateEdgeFunc, equiv_dec; intros.\n  destruct (E_EqDec (u,v) e). hnf in e0; subst e. trivial. \n  unfold complement, equiv in c. destruct H.\n  apply (undirected_edge_rep g e); auto.\n  exfalso. apply c.\n  symmetry. trivial.\n+ unfold addValidFunc, updateEdgeFunc, update_elabel; intros.\n  split; intros. destruct H. unfold equiv_dec; destruct E_EqDec.\n  split. pose proof (inf_representable g); lia. lia.\n  apply (evalid_meaning g) in H. destruct H; split; lia. \n  subst e. unfold equiv_dec. destruct E_EqDec.\n  split. pose proof (inf_representable g); lia. lia.\n  unfold complement, equiv in c; contradiction.\n  unfold equiv_dec in H; destruct (E_EqDec (u,v)).\n  hnf in e0; subst e. right; auto.\n  left. apply (evalid_meaning g). auto.\nQed.\n\nDefinition UAdjMatGG_adde: UAdjMatGG :=\n  @Build_GeneralGraph V E V_EqDec E_EqDec unit Z unit SoundUAdjMat\n    UAdjMatGG_adde' (SoundUAdjMat_adde').\n\nLemma adde_vvalid:\n  vvalid g v <-> vvalid UAdjMatGG_adde v.\nProof.\nintros. simpl. split; auto.\nQed.\n\nLemma adde_evalid_or:\n  forall e, evalid UAdjMatGG_adde e <-> (evalid g e \\/ e = (u,v)).\nProof. unfold UAdjMatGG_adde; simpl; unfold addValidFunc. intros; split; auto. Qed.\n\n(*all the Elist stuff are useless by themselves, because (@fin .. sound_matrx) clashes with Fin for some reason*)\nLemma adde_EList_new:\n  ~ evalid g (u,v) -> Permutation ((u,v)::(EList g)) (EList UAdjMatGG_adde).\nProof.\nintros. apply NoDup_Permutation. apply NoDup_cons. rewrite EList_evalid; auto. apply NoDup_EList. apply NoDup_EList.\nintros; split; intros. rewrite EList_evalid, adde_evalid_or. destruct H0.\nright; symmetry; auto. left; rewrite EList_evalid in H0; auto.\nrewrite EList_evalid, adde_evalid_or in H0. destruct H0. right; rewrite EList_evalid; auto. left; symmetry; auto.\nQed.\n\nLemma adde_EList_old:\n  forall e, In e (EList g) -> In e (EList UAdjMatGG_adde).\nProof.\nintros. unfold EList. destruct finiteE. simpl. destruct a.\napply H1. rewrite adde_evalid_or. left; rewrite <- EList_evalid; apply H.\nQed.\n\nLemma adde_EList_rev:\n  forall l, ~ evalid g (u,v) ->\n    Permutation ((u,v)::l) (EList UAdjMatGG_adde) ->\n    Permutation l (EList g).\nProof.\nintros. apply NoDup_Permutation.\napply NoDup_Perm_EList in H0. apply NoDup_cons_1 in H0; auto.\napply NoDup_EList.\nintros; split; intros. assert (In x (EList UAdjMatGG_adde)).\napply (Permutation_in (l:=(u,v)::l)). auto. right; auto.\napply EList_evalid in H2. apply adde_evalid_or in H2. destruct H2.\nrewrite EList_evalid; auto.\nsubst x. assert (NoDup ((u,v)::l)). apply NoDup_Perm_EList in H0; auto.\napply NoDup_cons_2 in H2. contradiction.\ndestruct (E_EqDec x (u,v)). unfold equiv in e. subst x. apply EList_evalid in H1; contradiction.\nunfold complement, equiv in c.\napply adde_EList_old in H1.\napply (Permutation_in (l':=(u,v)::l)) in H1. destruct H1. symmetry in H1; contradiction. auto.\napply Permutation_sym; auto.\nQed.\n\nLemma adde_src:\n  forall e', evalid g e' -> src UAdjMatGG_adde e' = src g e'.\nProof.\n  intros.\n  pose proof (edge_src_fst g e').\n  pose proof (edge_src_fst UAdjMatGG_adde e').\n  replace (src g e') with (fst e') by trivial.\n  replace (src UAdjMatGG_adde e') with (fst e') by trivial.\n  reflexivity.\nQed.\n\nLemma adde_dst:\n  forall e', evalid g e' -> dst UAdjMatGG_adde e' = dst g e'.\nProof.\n  intros.\n  pose proof (edge_dst_snd g e').\n  pose proof (edge_dst_snd UAdjMatGG_adde e').\n  replace (dst g e') with (snd e') by trivial.\n  replace (dst UAdjMatGG_adde e') with (snd e') by trivial.\n  reflexivity.\nQed.\n\nLemma adde_elabel_new:\n  elabel UAdjMatGG_adde (u,v) = w.\nProof.\nintros. simpl. unfold update_elabel, equiv_dec. destruct E_EqDec. auto.\nunfold complement, equiv in c. contradiction.\nQed.\n\nLemma adde_elabel_old:\n  forall e, e <> (u,v) -> elabel UAdjMatGG_adde e = elabel g e.\nProof.\nintros. simpl. unfold update_elabel, equiv_dec. destruct E_EqDec.\nunfold equiv in e0. symmetry in e0; contradiction.\nauto.\nQed.\n\nLemma adde_partial_graph:\n  forall (g': UAdjMatGG), is_partial_graph g g' -> evalid g' (u,v) -> is_partial_graph UAdjMatGG_adde g'.\nProof.\nintros. destruct H as [? [? [? ?]]].\nsplit. intros. simpl. apply H. auto.\nsplit. intros. rewrite adde_evalid_or in H4. destruct H4.\napply H1; auto. subst e; auto.\nsplit. intros. rewrite adde_evalid_or in H4. destruct H4.\nrewrite <- H2. apply adde_src. auto. auto. rewrite adde_src in H5 by auto. simpl in H5; auto.\nsubst e. rewrite (edge_src_fst g').\nrewrite (edge_src_fst UAdjMatGG_adde); auto.\nintros. rewrite adde_evalid_or in H4. destruct H4.\nrewrite <- H3. apply adde_dst. auto. auto. rewrite adde_dst in H5 by auto. simpl in H5; auto.\nsubst e. rewrite (edge_dst_snd g'), (edge_dst_snd UAdjMatGG_adde); auto.\nQed.\n\nLemma adde_partial_lgraph:\n  forall (g': UAdjMatGG), is_partial_lgraph g g' -> evalid g' (u,v) -> w = elabel g' (u,v) -> is_partial_lgraph UAdjMatGG_adde g'.\nProof.\nintros. split. apply adde_partial_graph. apply H. auto.\nsplit. unfold preserve_vlabel; intros.\ndestruct vlabel. destruct vlabel. auto.\nunfold preserve_elabel; intros.\ndestruct H. destruct H3. unfold preserve_elabel in H4.\ndestruct (E_EqDec e (u,v)).\nunfold equiv in e0. subst e. rewrite adde_elabel_new. rewrite H1. auto.\nunfold complement, equiv in c. apply add_edge_evalid_rev in H2. rewrite adde_elabel_old.\nrewrite <- H4. all: auto.\nQed.\n\nEnd ADD_EDGE_UADJMATGRAPH.\n\nSection REMOVE_EDGE_UADJMATGRAPH.\n\nContext {g: UAdjMatGG}.\nContext {e: E} {evalid_e: evalid g e}.\n\nDefinition UAdjMatGG_eremove':=\n  @Build_LabeledGraph V E V_EqDec E_EqDec unit Z unit (pregraph_remove_edge g e)\n  (vlabel g)\n  (fun e0 => if E_EqDec e0 e then inf else elabel g e0 )\n  (glabel g).\n\n#[export] Instance Fin_UAdjMatGG_eremove':\n  FiniteGraph (UAdjMatGG_eremove').\nProof.\nconstructor; unfold EnumEnsembles.Enumerable; simpl.\n(*vertices*)exists (VList g). split. apply NoDup_VList. apply VList_vvalid.\n(*edge*)\nunfold removeValidFunc.\n(*case e already inside*)\nexists (remove E_EqDec e (EList g)). split. apply nodup_remove_nodup. apply NoDup_EList.\nintros. rewrite remove_In_iff, EList_evalid; auto. split; auto.\nQed.\n\n#[export] Instance SoundPrim_eremove':\n  SoundUAdjMat UAdjMatGG_eremove'.\nProof.\nconstructor; simpl. constructor; simpl.\n++apply (size_representable g).\n++apply (inf_representable g).\n++apply (vvalid_meaning g).\n++unfold removeValidFunc; split; intros; destruct (E_EqDec e0 e).\n  destruct H. hnf in e1. contradiction.\n  apply (MathAdjMatGraph.evalid_meaning g). apply H.\n  destruct H.\n  exfalso; apply H0; trivial.\n  split.\n  apply (MathAdjMatGraph.evalid_meaning g). auto. auto.\n++ intros. red in H. destruct H.\n   apply remove_edge_preserves_strong_evalid; split; auto.\n   apply (evalid_strong_evalid g); trivial.\n++unfold removeValidFunc; split; intros; destruct (E_EqDec e0 e); trivial.\n  ** apply Classical_Prop.not_and_or in H.\n     destruct H.\n     apply (invalid_edge_weight g); trivial.\n     exfalso. apply H. apply c.\n  ** apply Classical_Prop.or_not_and. right.\n     unfold not. intro. apply H0. apply e1.\n  ** apply Classical_Prop.or_not_and. left.\n     apply <- (invalid_edge_weight g); trivial.\n++apply (edge_src_fst g).\n++apply (edge_dst_snd g).\n++apply Fin_UAdjMatGG_eremove'.\n++unfold removeValidFunc; intros. destruct H.\n  apply (undirected_edge_rep g); trivial.\n++unfold removeValidFunc; split; intros; destruct (E_EqDec e0 e).\n  destruct H. hnf in e1. contradiction.\n  apply (evalid_meaning g). apply H.\n  destruct H.\n  apply Zaux.Zgt_not_eq in H0; exfalso; apply H0; trivial.\n  split.\n  apply (evalid_meaning g). auto. auto.\nQed.\n\nDefinition UAdjMatGG_eremove: UAdjMatGG :=\n  @Build_GeneralGraph V E V_EqDec E_EqDec unit Z unit SoundUAdjMat\n    UAdjMatGG_eremove' (SoundPrim_eremove').\n\nLemma eremove_EList:\n  forall l, Permutation (e::l) (EList g) -> Permutation l (EList UAdjMatGG_eremove).\nProof.\nintros. assert (Hel: NoDup (e::l)). apply NoDup_Perm_EList in H; auto.\napply NoDup_Permutation.\napply NoDup_cons_1 in Hel; auto.\napply NoDup_EList.\nintros. rewrite EList_evalid. simpl. unfold removeValidFunc. rewrite <- EList_evalid. split; intros.\nsplit. apply (Permutation_in (l:=(e::l))). apply H. right; auto.\nunfold not; intros. subst e. apply NoDup_cons_2 in Hel. contradiction.\ndestruct H0. apply Permutation_sym in H. apply (Permutation_in (l':=(e::l))) in H0. 2: auto.\ndestruct H0. symmetry in H0; contradiction. auto.\nQed.\n\nLemma eremove_EList_rev:\n  forall l, evalid g e -> Permutation l (EList (UAdjMatGG_eremove)) -> Permutation (e::l) (EList g).\nProof.\nintros. assert (~ In e (EList UAdjMatGG_eremove)).\nrewrite EList_evalid. simpl. unfold removeValidFunc, not; intros. destruct H1. contradiction.\nassert (~ In e l). unfold not; intros.\napply (Permutation_in (l':= (EList UAdjMatGG_eremove))) in H2. contradiction. auto.\napply NoDup_Permutation. apply NoDup_cons; auto. apply NoDup_Perm_EList in H0; auto.\napply NoDup_EList.\nintros; split; intros. apply EList_evalid. destruct H3. subst x. auto.\napply (Permutation_in (l':= (EList UAdjMatGG_eremove))) in H3; auto.\nrewrite EList_evalid in H3. simpl in H3. unfold removeValidFunc in H3. apply H3.\ndestruct (E_EqDec x e). unfold equiv in e0. subst x. left; auto.\nunfold complement, equiv in c. right.\nassert (evalid UAdjMatGG_eremove x).\nsimpl. unfold removeValidFunc. rewrite EList_evalid in H3. split; auto.\nrewrite <- EList_evalid in H4.\napply (Permutation_in (l:= (EList UAdjMatGG_eremove))). apply Permutation_sym; auto. apply H4.\nQed.\n\nEnd REMOVE_EDGE_UADJMATGRAPH.\n\n(**************MST****************)\n\nDefinition minimum_spanning_forest (t g: UAdjMatGG) :=\n labeled_spanning_uforest t g /\\\n  forall (t': UAdjMatGG), labeled_spanning_uforest t' g ->\n    Z.le (sum_DE Z.add t 0) (sum_DE Z.add t' 0).\n\nLemma partial_lgraph_spanning_equiv:\nforall (t1 t2 g: UAdjMatGG), is_partial_lgraph t1 t2 -> labeled_spanning_uforest t1 g\n  -> labeled_spanning_uforest t2 g -> Permutation (EList t1) (EList t2).\nProof.\nintros. apply NoDup_Permutation.\napply NoDup_EList. apply NoDup_EList.\nintros. repeat rewrite EList_evalid. split; intros.\napply H. auto.\ndestruct (evalid_dec t1 x). auto. exfalso.\npose proof (trivial_path1 t2 x (evalid_strong_evalid t2 x H2)). destruct H3.\nassert (connected t1 (src t2 x) (dst t2 x)).\napply H0. apply H1. exists (src t2 x :: dst t2 x :: nil); auto.\ndestruct H5 as [p ?].\napply connected_by_upath_exists_simple_upath in H5. clear p.\ndestruct H5 as [p [? ?]].\nassert (exists l, fits_upath t1 l p). apply connected_exists_list_edges in H5; auto.\ndestruct H7 as [l ?].\nassert (~ In x l). unfold not; intros. apply (fits_upath_evalid t1 p l) in H8; auto.\nassert (fits_upath t2 l p).\napply (fits_upath_transfer' p l t1 t2) in H7; auto.\n  intros; split; intros. apply H. auto. rewrite vert_bound in *; auto.\n  intros. apply H. apply (fits_upath_evalid t1 p l); auto.\n  intros. apply H. auto. apply (evalid_strong_evalid t1); auto.\n  intros. apply H. auto. apply (evalid_strong_evalid t1); auto.\nassert (p = (src t2 x :: dst t2 x :: nil)). assert (unique_simple_upath t2). apply H1.\nunfold unique_simple_upath in H10. apply (H10 (src t2 x) (dst t2 x)).\nsplit. apply valid_upath_exists_list_edges'. exists l; auto. apply H6.\napply connected_exists_list_edges'. intros. rewrite vert_bound. apply (valid_upath_vvalid t1) in H11.\nrewrite vert_bound in H11; auto. apply H6.\nexists l. auto.\napply H5. apply H5.\nsplit. apply H3. apply NoDup_cons.\nunfold not; intros. destruct H11. 2: contradiction.\nsymmetry in H11. assert (src t2 x <> dst t2 x). apply H1. auto. contradiction.\napply NoDup_cons. unfold not; intros; contradiction. apply NoDup_nil.\napply H3.\nassert (x :: nil = l). apply (uforest'_unique_lpath p (x::nil) l t2).\napply H1. split. apply valid_upath_exists_list_edges'. exists l; auto. apply H6.\nrewrite H10; auto. auto.\nrewrite <- H11 in H8. apply H8. left; auto.\nQed.\n\nCorollary partial_lgraph_spanning_sum_LE:\nforall (t1 t2 g: UAdjMatGG), is_partial_lgraph t1 t2 -> labeled_spanning_uforest t1 g\n  -> labeled_spanning_uforest t2 g -> sum_DE Z.add t1 0 = sum_DE Z.add t2 0.\nProof.\nintros. assert (Permutation (EList t1) (EList t2)).\napply (partial_lgraph_spanning_equiv t1 t2 g); auto.\nunfold sum_DE. apply fold_left_comm.\nintros. lia.\nunfold DEList.\nreplace (map (elabel t1) (EList t1)) with (map (elabel g) (EList t1)).\nreplace (map (elabel t2) (EList t2)) with (map (elabel g) (EList t2)).\napply Permutation_map; auto.\napply map_ext_in. intros. symmetry; apply H1. rewrite EList_evalid in H3; auto.\napply map_ext_in. intros. symmetry; apply H0. rewrite EList_evalid in H3; auto.\nQed.\n\nCorollary partial_lgraph_spanning_mst:\nforall (t1 t2 g: UAdjMatGG), is_partial_lgraph t1 t2 -> labeled_spanning_uforest t1 g\n  -> minimum_spanning_forest t2 g -> minimum_spanning_forest t1 g.\nProof.\nintros. split. auto.\nintros. apply (Z.le_trans _ (sum_DE Z.add t2 0) _ ).\napply Z.eq_le_incl. apply (partial_lgraph_spanning_sum_LE t1 t2 g); auto. apply H1.\napply H1; auto.\nQed.\n\n(*The following are to let us reason about lists instead of graphs*)\nLemma sum_DE_equiv:\n  forall (g: UAdjMatGG) (l: list E),\n  Permutation (EList g) l -> sum_DE Z.add g 0 = fold_left Z.add (map (elabel g) l) 0.\nProof.\nunfold DEList; intros. apply fold_left_comm. intros; lia.\napply Permutation_map. auto.\nQed.\n\nLemma exists_labeled_spanning_uforest_pre:\nforall (l: list E) (g: UAdjMatGG), Permutation l (EList g) -> exists (t: UAdjMatGG), labeled_spanning_uforest t g.\nProof.\ninduction l; intros.\n(*nil case*)\nexists (@edgeless_graph (inf_representable g) (size_representable g)).\nsplit. split. apply edgeless_partial_lgraph. split. apply uforest'_edgeless_graph.\nunfold spanning; intros. destruct (V_EqDec u v).\nhnf in e. subst v. split; intros; apply connected_refl.\napply connected_vvalid in H0. rewrite vert_bound in *. apply H0.\napply connected_vvalid in H0. rewrite vert_bound in *. apply H0.\nunfold complement, equiv in c. split; intros. exfalso. destruct H0.\nunfold connected_by_path in H0. destruct H0. destruct H1. destruct x. inversion H1.\ndestruct x. inversion H1. inversion H2. subst v0. contradiction.\ndestruct H0. destruct H0. destruct H0. destruct H0.\nrewrite <- EList_evalid in H0. rewrite <- H in H0. contradiction.\npose proof (@edgeless_graph_disconnected (inf_representable g) (size_representable g) u v c).\ncontradiction.\nunfold preserve_vlabel, preserve_elabel; split; intros.\ndestruct vlabel. destruct vlabel. auto.\npose proof (@edgeless_graph_evalid (inf_representable g) (size_representable g) e).\ncontradiction.\n(*inductive step*)\nset (u:=src g a). set (v:=dst g a).\nassert (connected g u v). apply adjacent_connected. exists a.\nunfold u; unfold v; apply strong_evalid_adj_edge.\napply (evalid_strong_evalid g). rewrite <- EList_evalid, <- H. left; auto.\nset (remove_a:=(@UAdjMatGG_eremove g a)).\nassert (Ha_evalid: evalid g a). { rewrite <- EList_evalid. apply (Permutation_in (l:=(a::l))).\n  apply H. left; auto. }\nspecialize IHl with remove_a.\ndestruct IHl as [t ?]. {\nunfold remove_a. pose proof (@eremove_EList g a Ha_evalid l H).\napply NoDup_Permutation. assert (NoDup (a::l)). apply (Permutation_NoDup (l:=EList g)).\napply Permutation_sym; auto. apply NoDup_EList. apply NoDup_cons_1 in H2; auto.\napply NoDup_EList.\nintros. rewrite EList_evalid. split; intros.\npose proof (Permutation_in (l:=l) (l':=_) x H1 H2). rewrite EList_evalid in H3; auto.\napply Permutation_sym in H1.\napply (Permutation_in (l:=_) (l':=l) x H1). rewrite EList_evalid; auto.\n}\nassert (Htg: is_partial_lgraph t g). {\n  destruct H1. destruct H2. destruct H1. destruct H4. split.\n  split. intros. apply H1 in H6. auto.\n  split. intros. destruct H1. destruct H7. apply H7. auto.\n  split. intros. apply H1 in H7. simpl in H7. auto. auto.\n  intros. apply H1 in H7. simpl in H7. auto. auto.\n  unfold preserve_vlabel, preserve_elabel; split; intros.\n  destruct vlabel. destruct vlabel. auto.\n  rewrite H3 by auto. simpl. destruct (E_EqDec e a). unfold equiv in e0.\n  subst e. assert (evalid remove_a a). apply H1; auto.\n  simpl in H7. unfold removeValidFunc in H7. destruct H7; contradiction.\n  auto.\n}\ndestruct (connected_dec remove_a u v).\n(*already connected*)\n++\nexists t. destruct H1.  destruct H3. destruct H1. destruct H5.\nsplit. split.\n(*partial_graph*)\napply Htg.\n(*uforest*)\nsplit. auto.\n(*spanning*)\nunfold spanning in *. intros. rewrite <- H6. split; intros.\n{(*---------->*)\ndestruct H7 as [p ?].\napply (connected_by_upath_exists_simple_upath) in H7. destruct H7 as [p' [? ?]]. clear p.\nassert (exists l, fits_upath g l p'). apply (connected_exists_list_edges g p' u0 v0); auto.\ndestruct H9 as [l' ?]. destruct (in_dec E_EqDec a l').\n**(*yes: split the path*)\nassert (NoDup l'). apply (simple_upath_list_edges_NoDup g p' l'); auto.\napply (fits_upath_split2 g p' l' a u0 v0) in H9; auto.\ndestruct H9 as [p1 [p2 [l1 [l2 [? [? [? [? ?]]]]]]]]. subst l'. fold u in H11. fold v in H11.\nassert (~ In a l1). unfold not; intros.\napply (NoDup_app_not_in E l1 ((a::nil)++l2) H10 a) in H14. apply H14.\napply in_or_app. left; left; auto.\nassert (~ In a l2). unfold not; intros.\napply NoDup_app_r in H10. apply (NoDup_app_not_in E (a::nil) l2 H10 a).\nleft; auto. auto.\ndestruct H11; destruct H11.\n****\napply (connected_trans _ u0 u). exists p1. split.\napply (remove_edge_valid_upath _ a p1 l1); auto. apply H11. apply H11.\napply (connected_trans _ u v). auto.\nexists p2. split. apply (remove_edge_valid_upath _ a p2 l2); auto. apply H16. apply H16.\n****\napply (connected_trans _ u0 v). exists p1. split.\napply (remove_edge_valid_upath _ a p1 l1); auto. apply H11. apply H11.\napply (connected_trans _ v u). apply connected_symm; auto.\nexists p2. split. apply (remove_edge_valid_upath _ a p2 l2); auto. apply H16. apply H16.\n**(*no: fits_upath_transfer*)\nexists p'. split. apply (remove_edge_valid_upath _ a p' l'); auto. apply H7. apply H7.\n} { (*<---*)\ndestruct H7 as [p [? ?]]. exists p. split.\napply remove_edge_unaffected in H7; auto. auto.\n}\n(*labels*)\napply Htg.\n++\nassert (vvalid g u /\\ vvalid g v). apply connected_vvalid in H0; auto. destruct H3.\nassert (u <= v). apply (undirected_edge_rep g). auto.\nset (w:= elabel g a).\nassert (Int.min_signed <= w < inf). unfold w. split.\npose proof (weight_representable g a). apply H6. apply (evalid_meaning g). auto.\nrewrite vert_bound in H3, H4. rewrite <- (vert_bound t) in H3, H4.\nassert (Ha: a = (u,v)). unfold u, v; apply evalid_form; auto. rewrite Ha in *.\nset (adde_a:=@UAdjMatGG_adde t u v H3 H4 H5 w H6).\nexists adde_a. split. split.\napply adde_partial_lgraph; auto. unfold w. rewrite Ha; auto.\nsplit.\n(*uforest*)\napply add_edge_uforest'; auto. apply H1.\nunfold not; intros.\napply (is_partial_lgraph_connected t remove_a) in H7. contradiction.\nsplit. apply H1. apply H1.\n(*spanning*)\nunfold spanning; intros. assert (Ht_uv: ~ evalid t (u,v)). unfold not; intros.\nassert (evalid remove_a (u,v)). apply H1; auto.\nsimpl in H8. rewrite Ha in H8. unfold removeValidFunc in H8. destruct H8; contradiction.\nsplit; intros.\n{ (*-->*) destruct H7 as [p ?]. apply connected_by_upath_exists_simple_upath in H7.\ndestruct H7 as [p' [? ?]]. clear p.\nassert (exists l', fits_upath g l' p'). apply connected_exists_list_edges in H7; auto.\ndestruct H9 as [l' ?]. assert (NoDup l'). apply simple_upath_list_edges_NoDup in H9; auto.\ndestruct (in_dec E_EqDec a l').\n**\napply (fits_upath_split2 g p' l' a u0 v0) in H9; auto.\ndestruct H9 as [p1 [p2 [l1 [l2 [? [? [? [? ?]]]]]]]]. fold u in H11. fold v in H11. subst l'.\nassert (~ In a l1). unfold not; intros. apply (NoDup_app_not_in E l1 ((a::nil)++l2) H10 a) in H14.\napply H14. apply in_or_app. left; left; auto.\nassert (~ In a l2). unfold not; intros. apply NoDup_app_r in H10.\napply (NoDup_app_not_in E (a::nil) l2 H10 a). left; auto. auto.\ndestruct H11; destruct H11.\n****\napply (connected_trans _ u0 u). apply add_edge_connected; auto.\napply H1. exists p1. split. apply (remove_edge_valid_upath _ a p1 l1); auto. apply H11. apply H11.\napply (connected_trans _ u v). apply adjacent_connected.\nexists a. rewrite Ha. apply add_edge_adj_edge1. auto. auto.\napply add_edge_connected; auto. apply H1. exists p2. split.\napply (remove_edge_valid_upath _ a p2 l2); auto. apply H16. apply H16.\n****\napply (connected_trans _ u0 v). apply add_edge_connected; auto.\napply H1. exists p1. split. apply (remove_edge_valid_upath _ a p1 l1); auto. apply H11. apply H11.\napply (connected_trans _ v u). apply adjacent_connected. apply adjacent_symm.\nexists a. rewrite Ha. apply add_edge_adj_edge1. auto. auto.\napply add_edge_connected; auto. apply H1. exists p2. split.\napply (remove_edge_valid_upath _ a p2 l2); auto. apply H16. apply H16.\n**\napply add_edge_connected; auto.\napply H1. exists p'. split. 2: apply H7.\napply (remove_edge_valid_upath g a p' l'); auto. apply H7.\n} {\napply (is_partial_lgraph_connected adde_a g).\napply adde_partial_lgraph; auto. unfold w. rewrite Ha; auto. auto.\n}\n(*labels*)\nunfold preserve_vlabel, preserve_elabel; split; intros.\ndestruct vlabel; destruct vlabel; auto.\nsimpl. unfold update_elabel, equiv_dec.\ndestruct (E_EqDec (u,v) e). hnf in e0. subst e. unfold w; rewrite Ha; auto.\napply Htg. simpl in H7. unfold addValidFunc in H7. destruct H7. apply H7.\nunfold complement, equiv in c. symmetry in H7; contradiction.\nQed.\n\nCorollary exists_labeled_spanning_uforest:\nforall (g: UAdjMatGG), exists (t: UAdjMatGG), labeled_spanning_uforest t g.\nProof.\nintros. apply (exists_labeled_spanning_uforest_pre (EList g)). apply Permutation_refl.\nQed.\n\nLemma partial_graph_incl:\nforall (t g: UAdjMatGG), is_partial_graph t g -> incl (EList t) (EList g).\nProof.\nunfold incl; intros. rewrite EList_evalid in *. apply H; auto.\nQed.\n\nLemma exists_dec:\nforall (g: UAdjMatGG) l, (exists (t: UAdjMatGG), labeled_spanning_uforest t g /\\ Permutation l (EList t)) \\/\n  ~ (exists (t: UAdjMatGG), labeled_spanning_uforest t g /\\ Permutation l (EList t)).\nProof.\nintros. tauto.\nQed.\n\nLemma partial_lgraph_elabel_map:\nforall (t g: UAdjMatGG) l, is_partial_lgraph t g -> incl l (EList t) ->\n  map (elabel t) l = map (elabel g) l.\nProof.\ninduction l; intros. simpl; auto.\nsimpl. replace (elabel g a) with (elabel t a). rewrite IHl; auto.\napply incl_cons_inv in H0; destruct H0; auto.\napply H. rewrite <- EList_evalid. apply H0. left; auto.\nQed.\n\n(* needs UAdjMatGG and NoDup_incl_ordered_powerlist, which means it should probably stay right here *) \nLemma exists_msf:\nforall {E_EqDec : EqDec E eq} (g: UAdjMatGG), exists (t: UAdjMatGG), minimum_spanning_forest t g.\nProof.\nintros. pose proof (NoDup_incl_ordered_powerlist (EList g) (NoDup_EList g)).\ndestruct H as [L ?].\n(*now what I need is the subset of L that exists t, labeled_spanning_uforest t g ...*)\ndestruct (list_decidable_prop_reduced_list\n  (fun l' => NoDup l' /\\ incl l' (EList g) /\\ (forall x y, In x l' -> In y l' ->\n      (find l' x 0 <= find l' y 0 <-> find (EList g) x 0 <= find (EList g) y 0)))\n  (fun l => (exists (t: UAdjMatGG), labeled_spanning_uforest t g /\\ Permutation l (EList t)))\n  L\n).\napply exists_dec.\nintros; split; intros. rewrite <- H in H0. destruct H0 as [? [? ?]].\nsplit. apply H0. split. apply H1. apply H2.\nrewrite <- H. auto.\nrename x into Lspan.\nassert (Lspan <> nil). unfold not; intros. {\ndestruct (exists_labeled_spanning_uforest g) as [t ?].\ndestruct (test2 (EList t) (EList g)) as [lt ?]. apply NoDup_EList. apply NoDup_EList.\napply partial_graph_incl. apply H2. destruct H3.\nassert (In lt Lspan). apply H0. split. split. apply (Permutation_NoDup (l:=EList t)).\napply Permutation_sym; auto. apply NoDup_EList.\nsplit. unfold incl; intros. apply (Permutation_in (l':=EList t)) in H5; auto.\napply (partial_graph_incl t g) in H5; auto. apply H2. apply H4.\nexists t. split; auto.\nrewrite H1 in H5; contradiction.\n}\npose proof (exists_Zmin Lspan (fun l => fold_left Z.add (map (elabel g) l) 0) H1).\ndestruct H2 as [lmin [? ?]].\napply H0 in H2. destruct H2. destruct H2 as [? [? ?]]. destruct H4 as [msf [? ?]].\nexists msf. unfold minimum_spanning_forest. split. apply H4. intros.\ndestruct (test2 (EList t') (EList g)) as [lt' ?]. apply NoDup_EList. apply NoDup_EList.\napply partial_graph_incl. apply H8. destruct H9.\nrewrite (sum_DE_equiv msf lmin). 2: apply Permutation_sym; auto.\nrewrite (sum_DE_equiv t' lt'). 2: apply Permutation_sym; auto.\nreplace (map (elabel msf) lmin) with (map (elabel g) lmin).\nreplace (map (elabel t') lt') with (map (elabel g) lt').\napply H3. apply H0. split. split.\napply (Permutation_NoDup (l:=EList t')). apply Permutation_sym; auto. apply NoDup_EList.\nsplit. unfold incl; intros. apply (Permutation_in (l':=EList t')) in H11; auto.\napply (partial_graph_incl t' g) in H11. auto. apply H8.\napply H10. exists t'. split; auto.\nsymmetry; apply partial_lgraph_elabel_map. split. apply H8. apply H8.\napply Permutation_incl; auto.\nsymmetry; apply partial_lgraph_elabel_map. split. apply H4. apply H4.\napply Permutation_incl; auto.\nQed.\n\nLemma msf_if_le_msf:\nforall {E_EqDec : EqDec E eq} (t g: UAdjMatGG), labeled_spanning_uforest t g ->\n  (forall t', minimum_spanning_forest t' g -> sum_DE Z.add t 0 <= sum_DE Z.add t' 0) ->\n  minimum_spanning_forest t g.\nProof.\nintros. unfold minimum_spanning_forest. split. auto.\nintros. destruct (exists_msf g) as [msf ?].\napply (Z.le_trans _ (sum_DE Z.add msf 0)). auto.\napply H2. auto.\nQed.\n\nCorollary msf_if_le_msf':\nforall {E_EqDec : EqDec E eq} (t t' g: UAdjMatGG), labeled_spanning_uforest t g ->\n  minimum_spanning_forest t' g -> sum_DE Z.add t 0 <= sum_DE Z.add t' 0 ->\n  minimum_spanning_forest t g.\nProof.\nintros. apply msf_if_le_msf; auto.\nintros. apply (Z.le_trans _ (sum_DE Z.add t' 0)). auto.\napply H0. apply H2.\nQed.\n\n(*The following two could not be moved because they require a massage allowing in_dec\nto be used as a bool, and I don't know what allows it*)\nLemma filter_list_Permutation:\nforall {A:Type} {EA: EquivDec.EqDec A eq} (l1 l2: list A),\n  NoDup l2 ->\n  Permutation\n    ((filter (fun x => in_dec EA x l1) l2) ++ (filter (fun x => negb (in_dec EA x l1)) l2))\n    l2.\nProof.\nintros. apply NoDup_Permutation.\napply NoDup_app_inv. apply NoDup_filter. auto. apply NoDup_filter. auto.\nintros. rewrite filter_In in H0. rewrite filter_In. destruct H0.\nunfold not; intros. destruct H2. destruct (in_dec EA x l1).\ninversion H3. inversion H1. auto.\nintros; split; intros.\napply in_app_or in H0; destruct H0; rewrite filter_In in H0; destruct H0; auto.\napply in_or_app. repeat rewrite filter_In.\ndestruct (in_dec EA x l1). left; split; auto. right; split; auto.\nQed.\n\nCorollary path_partition_checkpoint2:\nforall (g: UAdjMatGG) {fg: FiniteGraph g} (l: list V) p l' a b, In a l -> ~ In b l ->\n  connected_by_path g p a b -> fits_upath g l' p ->\n  exists v1 v2, In v1 p /\\ In v2 p /\\\n    In v1 l /\\ ~ In v2 l /\\ (exists e, adj_edge g e v1 v2 /\\ In e l').\nProof.\nintros.\napply (path_partition_checkpoint' g\n  (filter (fun x => (in_dec V_EqDec x l)) (VList g))\n  (filter (fun x => negb (in_dec V_EqDec x l)) (VList g)) p l' a b\n) in H2.\n2: { apply filter_list_Permutation. apply NoDup_VList. }\n2: { rewrite filter_In. split. rewrite VList_vvalid. apply connected_by_path_vvalid in H1; apply H1.\n      destruct (in_dec V_EqDec a l). auto. contradiction. }\n2: { rewrite filter_In. split. rewrite VList_vvalid. apply connected_by_path_vvalid in H1; apply H1.\n      destruct (In_dec V_EqDec b l). contradiction. auto. }\n2: auto.\ndestruct H2 as [v1 [v2 [? [? [? [? ?]]]]]].\nexists v1; exists v2. split. auto. split. auto.\nsplit. rewrite filter_In in H4. destruct H4. destruct (in_dec V_EqDec v1 l). auto. inversion H7.\nsplit. rewrite filter_In in H5. destruct H5. destruct (in_dec V_EqDec v2 l). inversion H7. auto.\nauto.\nQed.\n\nLemma Zlt_Zmin:\nforall x y, x < y -> Z.min x y = x.\nProof. intros. rewrite Zmin_spec. destruct (zlt x y); lia. Qed.\n\nEnd Mathematical_Undirected_AdjMat_Model.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/graph/MathUAdjMatGraph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.15898747025204152}}
{"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  subst id0. inv H1. destruct gd. 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  (* different *)\n  destruct gd. 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.\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(** ** Soundness of the computed bounds over function resources *)\n\nRemark Pmax_l: forall x y, Ple x (Pmax x y).\nProof. intros; xomega. Qed.\n\nRemark Pmax_r: forall x y, Ple y (Pmax x y).\nProof. intros; xomega. Qed.\n\nLemma max_pc_function_sound:\n  forall f pc i, f.(fn_code)!pc = Some i -> Ple pc (max_pc_function f).\nProof.\n  intros until i. unfold max_pc_function.\n  apply PTree_Properties.fold_rec with (P := fun c m => c!pc = Some i -> Ple pc m).\n  (* extensionality *)\n  intros. apply H0. rewrite H; auto.\n  (* base case *)\n  rewrite PTree.gempty. congruence.\n  (* inductive case *)\n  intros. rewrite PTree.gsspec in H2. destruct (peq pc k).\n  inv H2. apply Pmax_r.\n  apply Ple_trans with a. auto. apply Pmax_l.\nQed.\n\nLemma max_def_function_instr:\n  forall f pc i, f.(fn_code)!pc = Some i -> Ple (max_def_instr i) (max_def_function f).\nProof.\n  intros. unfold max_def_function. eapply Ple_trans. 2: eapply Pmax_l.\n  revert H.\n  apply PTree_Properties.fold_rec with (P := fun c m => c!pc = Some i -> Ple (max_def_instr i) m).\n  (* extensionality *)\n  intros. apply H0. rewrite H; auto.\n  (* base case *)\n  rewrite PTree.gempty. congruence.\n  (* inductive case *)\n  intros. rewrite PTree.gsspec in H2. destruct (peq pc k).\n  inv H2. apply Pmax_r.\n  apply Ple_trans with a. auto. apply Pmax_l.\nQed.\n\nLemma max_def_function_params:\n  forall f r, In r f.(fn_params) -> Ple r (max_def_function f).\nProof.\n  assert (A: forall l m, Ple m (fold_left (fun m r => Pmax m r) l m)).\n    induction l; simpl; intros.\n    apply Ple_refl.\n    eapply Ple_trans. 2: eauto. apply Pmax_l.\n  assert (B: forall l m r, In r l -> Ple r (fold_left (fun m r => Pmax m r) l m)).\n    induction l; simpl; intros.\n    contradiction.\n    destruct H. subst a. eapply Ple_trans. 2: eapply A. apply Pmax_r.\n    eauto.\n  unfold max_def_function; intros.\n  eapply Ple_trans. 2: eapply Pmax_r. eauto.\nQed.\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  Ple pc s.(st_nextnode) \\/ Plt 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, Plt s.(st_nextnode) pc -> Ple 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  Ple 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  Ple 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  Ple 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  Ple 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. xomega.\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_def_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, Plt ctx.(dpc) pc -> Ple 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  Ple (max_def_instr instr) ctx.(mreg) ->\n  Ple (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', Plt s.(st_nextnode) pc' -> Ple 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_def_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. 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_def_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 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. subst 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, In (pc, instr) l -> Ple (max_def_instr instr) ctx.(mreg)) ->\n  (forall pc instr, In (pc, instr) l -> Ple (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', Plt s.(st_nextnode) pc' -> Ple 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: Ple (spc ctx pc) (st_nextnode s)) by eauto. unfold spc in B; 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 (Ple (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 (Ple (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. unfold spc in P.\n    assert (pc = pc0) by (unfold node; xomega). 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 Ple_trans; eauto.\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_def_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', Plt ctx.(dpc) pc' -> Ple 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_def_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_def_function_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    unfold spc. subst s0; simpl; xomega.\n  subst s0; simpl; auto.\n  intros. apply H8; auto. subst s0; simpl in H11; xomega.\n  intros. apply H8. unfold spc; xomega.\n    assert (Ple pc0 (max_pc_function f)).\n      eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.\n    unfold spc. 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  Ple 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_def_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', Plt ctx.(dpc) pc' -> Ple 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_def_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": "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/backend/Inliningspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.15898746834707625}}
{"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import Hashmap.\nRequire Import FMapAVL.\nRequire Import FMapFacts.\nRequire Import Classes.SetoidTactics.\nRequire Import Structures.OrderedType.\nRequire Import Structures.OrderedTypeEx.\nRequire Import Pred PredCrash.\nRequire Import Prog.\nRequire Import Hoare.\nRequire Import BasicProg.\nRequire Import FunctionalExtensionality.\nRequire Import Omega.\nRequire Import Word.\nRequire Import Rec.\nRequire Import Array.\nRequire Import Eqdep_dec.\nRequire Import WordAuto.\nRequire Import Cache.\nRequire Import Idempotent.\nRequire Import ListUtils.\nRequire Import FSLayout.\nRequire Import AsyncDisk.\nRequire Import SepAuto.\nRequire Import GenSepN.\nRequire Import MemLog.\nRequire Import DiskLogHash.\nRequire Import MapUtils.\nRequire Import ListPred.\nRequire Import LogReplay.\nRequire Import DiskSet.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n\n\nModule GLog.\n\n  Import AddrMap LogReplay ReplaySeq LogNotations.\n\n\n  (************* state and rep invariant *)\n\n  Record mstate := mk_mstate {\n    MSVMap  : valumap;\n    (* collapsed updates for all committed but unflushed txns,\n        necessary for fast read() operation\n     *)\n    MSTxns  : txnlist;\n    (* list of all unflushed txns, the order should match the\n       second part of diskset. (first element is the latest)\n    *)\n\n    MSMLog  : MLog.mstate;\n    (* lower-level states *)\n  }.\n\n  Definition memstate := (mstate * cachestate)%type.\n  Definition mk_memstate vm ts ll : memstate := \n    (mk_mstate vm ts (MLog.MSInLog ll), (MLog.MSCache ll)).\n  Definition mk_memstate0 := mk_mstate vmap0 nil vmap0.\n\n  Definition MSCache (ms : memstate) := snd ms.\n  Definition MSLL (ms : memstate) := MLog.mk_memstate (MSMLog (fst ms)) (snd ms).\n\n  Definition readOnly (ms ms' : memstate) := (fst ms = fst ms').\n\n  Lemma readOnlyLL : forall ms ms',\n    MLog.readOnly (MSLL ms) (MSLL ms') ->\n    MSVMap (fst ms) = MSVMap (fst ms') ->\n    MSTxns (fst ms) = MSTxns (fst ms') ->\n    readOnly ms ms'.\n  Proof.\n    destruct ms as [m c]; destruct m.\n    destruct ms' as [m' c']; destruct m'.\n    unfold MLog.readOnly, readOnly; simpl; congruence.\n  Qed.\n\n  Hint Resolve readOnlyLL.\n\n\n  Inductive state :=\n  | Cached   (ds : diskset)\n  | Flushing (ds : diskset) (n : addr)\n  | Rollback (d : diskstate)\n  | Recovering (d : diskstate)\n  .\n\n  Definition vmap_match vm ts :=\n    Map.Equal vm (fold_right replay_mem vmap0 ts).\n\n  Definition ents_valid xp d ents :=\n    log_valid ents d /\\ length ents <= LogLen xp.\n\n  Definition effective (ds : diskset) tslen := popn (length (snd ds) - tslen) ds.\n\n  Definition dset_match xp ds ts :=\n    Forall (ents_valid xp (fst ds)) ts /\\ ReplaySeq ds ts.\n\n  Definition rep xp st ms hm :=\n  let '(vm, ts, mm) := (MSVMap ms, MSTxns ms, MSMLog ms) in\n  (match st with\n    | Cached ds =>\n      let ds' := effective ds (length ts) in\n      [[ vmap_match vm ts ]] *\n      [[ dset_match xp ds' ts ]] * exists nr,\n      MLog.rep xp (MLog.Synced nr (fst ds')) mm hm\n    | Flushing ds n =>\n      let ds' := effective ds (length ts) in\n      [[ dset_match xp ds' ts /\\ n <= length ts ]] *\n      MLog.would_recover_either xp (nthd n ds') (selR ts n nil) hm\n    | Rollback d =>\n      [[ vmap_match vm ts ]] *\n      [[ dset_match xp (d, nil) ts ]] *\n      MLog.rep xp (MLog.Rollback d) mm hm\n    | Recovering d =>\n      [[ vmap_match vm ts ]] *\n      [[ dset_match xp (d, nil) ts ]] *\n      MLog.rep xp (MLog.Recovering d) mm hm\n  end)%pred.\n\n  Definition would_recover_any xp ds hm :=\n    (exists ms n ds',\n      [[ NEListSubset ds ds' ]] *\n      rep xp (Flushing ds' n) ms hm)%pred.\n\n  Local Hint Resolve nelist_subset_equal.\n\n  Lemma sync_invariant_rep : forall xp st ms hm,\n    sync_invariant (rep xp st ms hm).\n  Proof.\n    unfold rep; destruct st; intros; eauto.\n  Qed.\n\n  Hint Resolve sync_invariant_rep.\n\n  Lemma sync_invariant_would_recover_any : forall xp ds hm,\n    sync_invariant (would_recover_any xp ds hm).\n  Proof.\n    unfold would_recover_any; intros; auto.\n  Qed.\n\n  Hint Resolve sync_invariant_would_recover_any.\n\n  Lemma nthd_effective : forall n ds tslen,\n    nthd n (effective ds tslen) = nthd (length (snd ds) - tslen + n) ds.\n  Proof.\n    unfold effective; intros.\n    rewrite nthd_popn; auto.\n  Qed.\n\n  Lemma latest_effective : forall ds n,\n    latest (effective ds n) = latest ds.\n  Proof.\n    unfold effective; intros.\n    rewrite latest_popn; auto.\n  Qed.\n\n  Lemma effective_length : forall ds n,\n    n <= (length (snd ds)) ->\n    length (snd (effective ds n)) = n.\n  Proof.\n    unfold effective; intros.\n    rewrite length_popn.\n    omega.\n  Qed.\n\n  Lemma effective_length_le : forall ds n,\n    length (snd (effective ds n)) <= length (snd ds).\n  Proof.\n    unfold effective; intros.\n    rewrite length_popn.\n    omega.\n  Qed.\n\n\n  Lemma cached_recover_any: forall xp ds ms hm,\n    rep xp (Cached ds) ms hm =p=> would_recover_any xp ds hm.\n  Proof.\n    unfold would_recover_any, rep.\n    intros. norm.\n    cancel.\n    rewrite nthd_effective, Nat.add_0_r.\n    apply MLog.synced_recover_either.\n    intuition.\n  Qed.\n\n  Lemma cached_recovering: forall xp ds ms hm,\n    rep xp (Cached ds) ms hm =p=>\n      exists n ms', rep xp (Recovering (nthd n ds)) ms' hm.\n  Proof.\n    unfold rep.\n    intros. norm.\n    cancel.\n    rewrite MLog.rep_synced_pimpl.\n    eassign (mk_mstate vmap0 nil (MSMLog ms)).\n    cancel.\n    intuition simpl; auto.\n    unfold vmap_match; simpl; congruence.\n    unfold dset_match; intuition.\n    apply Forall_nil.\n    constructor.\n  Qed.\n\n  Lemma flushing_recover_any: forall xp n ds ms hm,\n    rep xp (Flushing ds n) ms hm =p=> would_recover_any xp ds hm.\n  Proof.\n    unfold would_recover_any, rep; intros; cancel.\n  Qed.\n\n  Lemma rollback_recover_any: forall xp d ms hm,\n    rep xp (Rollback d) ms hm =p=> would_recover_any xp (d, nil) hm.\n  Proof.\n    unfold would_recover_any, rep; intros.\n    norm. unfold stars; simpl.\n    rewrite nthd_0; cancel.\n    rewrite MLog.rollback_recover_either.\n    2: intuition.\n    eauto.\n    eauto.\n  Qed.\n\n  Lemma rollback_recovering: forall xp d ms hm,\n    rep xp (Rollback d) ms hm =p=> rep xp (Recovering d) ms hm.\n  Proof.\n    unfold rep; intros.\n    cancel.\n    rewrite MLog.rep_rollback_pimpl.\n    auto.\n  Qed.\n\n\n  Lemma rep_hashmap_subset : forall xp ms hm hm',\n    (exists l, hashmap_subset l hm hm')\n    -> forall st, rep xp st ms hm\n        =p=> rep xp st ms hm'.\n  Proof.\n    unfold rep; intros.\n    destruct st; cancel.\n    erewrite MLog.rep_hashmap_subset; eauto.\n    erewrite MLog.would_recover_either_hashmap_subset; eauto.\n    erewrite MLog.rep_hashmap_subset; eauto.\n    erewrite MLog.rep_hashmap_subset; eauto.\n  Qed.\n\n\n  (************* program *)\n\n  Definition read xp a (ms : memstate) :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    match Map.find a vm with\n    | Some v =>  Ret ^(ms, v)\n    | None =>\n        let^ (mm', v) <- MLog.read xp a mm;\n        Ret ^(mk_memstate vm ts mm', v)\n    end.\n\n  (* Submit a committed transaction.\n     It might fail if the transaction is too big to fit into the log.\n     We handle the anomaly here so that flushall() can always succeed.\n     This keep the interface compatible with current Log.v, in which\n     only commit() can fail, and the caller can choose to abort.\n  *)\n  Definition submit xp ents ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    let vm' := replay_mem ents vm in\n    If (le_dec (length ents) (LogLen xp)) {\n      Ret ^(mk_memstate vm' (ents :: ts) mm, true)\n    } else {\n      Ret ^(ms, false)\n    }.\n\n  Definition flushall_nomerge xp ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    let^ (mm) <- ForN i < length ts\n    Hashmap hm\n    Ghost [ F ds crash ]\n    Loopvar [ mm ]\n    Invariant\n        exists nr,\n        << F, MLog.rep: xp (MLog.Synced nr (nthd i ds)) mm hm >>\n    OnCrash crash\n    Begin\n      (* r = false is impossible, flushall should always succeed *)\n      let^ (mm, r) <- MLog.flush xp (selN ts (length ts - i - 1) nil) mm;\n      Ret ^(mm)\n    Rof ^(mm);\n    Ret (mk_memstate vmap0 nil mm).\n\n  Definition flushall xp ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    If (le_dec (Map.cardinal vm) (LogLen xp)) {\n      let^ (mm, r) <- MLog.flush xp (Map.elements vm) mm;\n      Ret (mk_memstate vmap0 nil mm)\n    } else {\n      ms <- flushall_nomerge xp ms;\n      Ret ms\n    }.\n\n  Definition flushsync xp ms :=\n    ms <- flushall xp ms;\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.apply xp mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition flushall_noop xp ms :=\n    ms <- flushall xp ms;\n    Ret ms.\n\n  Definition flushsync_noop xp ms :=\n    ms <- flushsync xp ms;\n    Ret ms.\n\n  Definition sync_cache xp ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.sync_cache xp mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition dwrite' (xp : log_xparams) a v ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.dwrite xp a v mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition dwrite (xp : log_xparams) a v ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    If (MapFacts.In_dec vm a) {\n      ms <- flushall_noop xp ms;\n      ms <- dwrite' xp a v ms;\n      Ret ms\n    } else {\n      ms <- dwrite' xp a v ms;\n      Ret ms\n    }.\n\n  Definition dwrite_vecs' (xp : log_xparams) avs ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.dwrite_vecs xp avs mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition dwrite_vecs (xp : log_xparams) avs ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    If (bool_dec (overlap (map fst avs) vm) true) {\n      ms <- flushall_noop xp ms;\n      ms <- dwrite_vecs' xp avs ms;\n      Ret ms\n    } else {\n      ms <- dwrite_vecs' xp avs ms;\n      Ret ms\n    }.\n\n  Definition dsync xp a ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.dsync xp a mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition dsync_vecs xp al ms :=\n    let '(vm, ts, mm) := (MSVMap (fst ms), MSTxns (fst ms), MSLL ms) in\n    mm' <- MLog.dsync_vecs xp al mm;\n    Ret (mk_memstate vm ts mm').\n\n  Definition recover xp cs :=\n    mm <- MLog.recover xp cs;\n    Ret (mk_memstate vmap0 nil mm).\n\n  Definition init xp cs :=\n    mm <- MLog.init xp cs;\n    Ret (mk_memstate vmap0 nil mm).\n\n\n  Arguments MLog.rep: simpl never.\n  Hint Extern 0 (okToUnify (MLog.rep _ _ _ _) (MLog.rep _ _ _ _)) => constructor : okToUnify.\n\n\n\n  (************* auxilary lemmas *)\n\n  Lemma diskset_ptsto_bound_latest : forall F xp a vs ds ts,\n    dset_match xp ds ts ->\n    (F * a |-> vs)%pred (list2nmem ds!!) ->\n    a < length (fst ds).\n  Proof.\n    intros.\n    apply list2nmem_ptsto_bound in H0.\n    erewrite <- replay_seq_latest_length; auto.\n    apply H.\n  Qed.\n\n  Lemma diskset_vmap_find_none : forall ds ts vm a v vs xp F,\n    dset_match xp ds ts ->\n    vmap_match vm ts ->\n    Map.find a vm = None ->\n    (F * a |-> (v, vs))%pred (list2nmem ds !!) ->\n    selN (fst ds) a ($0, nil) = (v, vs).\n  Proof.\n    unfold vmap_match, dset_match.\n    intros ds ts; destruct ds; revert l.\n    induction ts; intuition; simpl in *;\n      denote ReplaySeq as Hs;inversion Hs; subst; simpl.\n    denote ptsto as Hx; rewrite singular_latest in Hx by easy; simpl in Hx.\n    erewrite surjective_pairing at 1.\n    erewrite <- list2nmem_sel; eauto; simpl; auto.\n\n    rewrite H0 in H1.\n    eapply IHts.\n    split; eauto.\n    eapply Forall_cons2; eauto.\n\n    apply MapFacts.Equal_refl.\n    eapply replay_mem_find_none_mono; eauto.\n\n    rewrite latest_cons in *.\n    eapply ptsto_replay_disk_not_in'; [ | | eauto].\n    eapply map_find_replay_mem_not_in; eauto.\n    denote Forall as Hx; apply Forall_inv in Hx; apply Hx.\n  Qed.\n\n  Lemma replay_seq_replay_mem : forall ds ts xp,\n    ReplaySeq ds ts ->\n    Forall (ents_valid xp (fst ds)) ts ->\n    replay_disk (Map.elements (fold_right replay_mem vmap0 ts)) (fst ds) = latest ds.\n  Proof.\n    induction 1; simpl in *; intuition.\n    rewrite latest_cons; subst.\n    unfold latest in *; simpl in *.\n    rewrite <- IHReplaySeq by (eapply Forall_cons2; eauto).\n    rewrite replay_disk_replay_mem; auto.\n    inversion H1; subst.\n    eapply log_valid_length_eq.\n    unfold ents_valid in *; intuition; eauto.\n    rewrite replay_disk_length; auto.\n  Qed.\n\n  Lemma diskset_vmap_find_ptsto : forall ds ts vm a w v vs F xp,\n    dset_match xp ds ts ->\n    vmap_match vm ts ->\n    Map.find a vm = Some w ->\n    (F * a |-> (v, vs))%pred (list2nmem ds !!) ->\n    w = v.\n  Proof.\n    unfold vmap_match, dset_match; intuition.\n    eapply replay_disk_eq; eauto.\n    eexists; rewrite H0.\n    erewrite replay_seq_replay_mem; eauto.\n  Qed.\n\n  Lemma dset_match_ext : forall ents ds ts xp,\n    dset_match xp ds ts ->\n    log_valid ents ds!! ->\n    length ents <= LogLen xp ->\n    dset_match xp (pushd (replay_disk ents ds!!) ds) (ents :: ts).\n  Proof.\n    unfold dset_match, pushd, ents_valid; intuition; simpl in *.\n    apply Forall_cons; auto; split; auto.\n    eapply log_valid_length_eq; eauto.\n    erewrite replay_seq_latest_length; eauto.\n    constructor; auto.\n  Qed.\n\n  Lemma vmap_match_nil : vmap_match vmap0 nil.\n  Proof.\n      unfold vmap_match; simpl; apply MapFacts.Equal_refl.\n  Qed.\n\n  Lemma dset_match_nil : forall d xp, dset_match xp (d, nil) nil.\n  Proof.\n      unfold dset_match; split; [ apply Forall_nil | constructor ].\n  Qed.\n\n  Lemma dset_match_length : forall ds ts xp,\n    dset_match xp ds ts -> length ts = length (snd ds).\n  Proof.\n    intros.\n    erewrite replay_seq_length; eauto.\n    apply H.\n  Qed.\n\n  Lemma dset_match_log_valid_selN : forall ds ts i n xp,\n    dset_match xp ds ts ->\n    log_valid (selN ts i nil) (nthd n ds).\n  Proof.\n    unfold dset_match, ents_valid; intuition; simpl in *.\n    destruct (lt_dec i (length ts)).\n    eapply Forall_selN with (i := i) in H0; intuition.\n    eapply log_valid_length_eq; eauto.\n    erewrite replay_seq_nthd_length; eauto.\n    rewrite selN_oob by omega.\n    unfold log_valid, KNoDup; intuition; inversion H.\n  Qed.\n\n  Lemma vmap_match_find : forall ts vmap,\n    vmap_match vmap ts\n    -> forall a v, KIn (a, v) (Map.elements vmap)\n    -> Forall (@KNoDup valu) ts\n    -> exists t, In t ts /\\ In a (map fst t).\n  Proof.\n    induction ts; intros; simpl.\n    unfold vmap_match in *; simpl in *.\n    rewrite H in H0.\n    unfold KIn in H0.\n    apply InA_nil in H0; intuition.\n\n    destruct (in_dec Nat_as_OT.eq_dec a0 (map fst a)).\n    (* The address was written by the newest transaction. *)\n    exists a; intuition.\n\n    unfold vmap_match in *; simpl in *.\n    remember (fold_right replay_mem vmap0 ts) as vmap_ts.\n    destruct (in_dec Nat_as_OT.eq_dec a0 (map fst (Map.elements vmap_ts))).\n    (* The address was written by an older transaction. *)\n    replace a0 with (fst (a0, v)) in * by auto.\n    apply In_fst_KIn in i.\n    eapply IHts in i.\n    deex.\n    exists t; intuition.\n    congruence.\n    eapply Forall_cons2; eauto.\n    rewrite Forall_forall in H1.\n    specialize (H1 a).\n    simpl in *; intuition.\n\n    (* The address wasn't written by an older transaction. *)\n    denote KIn as HKIn.\n    apply KIn_fst_In in HKIn.\n    apply In_map_fst_MapIn in HKIn.\n    apply In_MapsTo in HKIn.\n    deex.\n    eapply replay_mem_not_in' in H1.\n    denote (Map.MapsTo) as Hmap.\n    eapply MapsTo_In in Hmap.\n    eapply In_map_fst_MapIn in Hmap.\n    apply n0 in Hmap; intuition.\n    auto.\n    rewrite <- H.\n    eauto.\n  Qed.\n\n  Lemma dset_match_log_valid_grouped : forall ts vmap ds xp,\n    vmap_match vmap ts\n    -> dset_match xp ds ts\n    -> log_valid (Map.elements vmap) (fst ds).\n  Proof.\n    intros.\n\n    assert (HNoDup: Forall (@KNoDup valu) ts).\n      unfold dset_match in *; simpl in *; intuition.\n      unfold ents_valid, log_valid in *.\n      eapply Forall_impl; try eassumption.\n      intros; simpl; intuition.\n      intuition.\n\n    unfold log_valid; intuition;\n    eapply vmap_match_find in H; eauto.\n    deex.\n    denote In as HIn.\n    unfold dset_match in *; intuition.\n    rewrite Forall_forall in H.\n    eapply H in H3.\n    unfold ents_valid, log_valid in *; intuition.\n    replace 0 with (fst (0, v)) in * by auto.\n    apply In_fst_KIn in HIn.\n    apply H5 in HIn; intuition.\n\n    deex.\n    denote In as HIn.\n    unfold dset_match in *; intuition.\n    rewrite Forall_forall in H.\n    eapply H in H2.\n    unfold ents_valid, log_valid in *; intuition.\n    replace a with (fst (a, v)) in * by auto.\n    apply In_fst_KIn in HIn.\n    apply H5 in HIn; intuition.\n  Qed.\n\n\n  Lemma dset_match_ent_length_exfalso : forall xp ds ts i,\n    length (selN ts i nil) > LogLen xp ->\n    dset_match xp ds ts ->\n    False.\n  Proof.\n    unfold dset_match, ents_valid; intuition.\n    destruct (lt_dec i (length ts)).\n    eapply Forall_selN with (i := i) (def := nil) in H1; intuition.\n    eapply le_not_gt; eauto.\n    rewrite selN_oob in H; simpl in H; omega.\n  Qed.\n\n\n  Lemma ents_valid_length_eq : forall xp d d' ts,\n    Forall (ents_valid xp d ) ts ->\n    length d = length d' ->\n    Forall (ents_valid xp d') ts.\n  Proof.\n    unfold ents_valid in *; intros.\n    rewrite Forall_forall in *; intuition.\n    eapply log_valid_length_eq; eauto.\n    apply H; auto.\n    apply H; auto.\n  Qed.\n\n  Lemma dset_match_nthd_S : forall xp ds ts n,\n    dset_match xp ds ts ->\n    n < length ts ->\n    replay_disk (selN ts (length ts - n - 1) nil) (nthd n ds) = nthd (S n) ds.\n  Proof.\n    unfold dset_match; intuition.\n    repeat erewrite replay_seq_nthd; eauto.\n    erewrite skipn_sub_S_selN_cons; simpl; eauto.\n  Qed.\n\n  Lemma dset_match_replay_disk_grouped : forall ts vmap ds xp,\n    vmap_match vmap ts\n    -> dset_match xp ds ts\n    -> replay_disk (Map.elements vmap) (fst ds) = nthd (length ts) ds.\n  Proof.\n    intros; simpl in *.\n    denote dset_match as Hdset.\n    apply dset_match_length in Hdset as Hlength.\n    unfold dset_match in *.\n    intuition.\n\n    unfold vmap_match in *.\n    rewrite H.\n    erewrite replay_seq_replay_mem; eauto.\n    erewrite nthd_oob; eauto.\n    omega.\n  Qed.\n\n  Lemma dset_match_grouped : forall ts vmap ds xp,\n    length (snd ds) > 0\n    -> Map.cardinal vmap <= LogLen xp\n    -> vmap_match vmap ts\n    -> dset_match xp ds ts\n    -> dset_match xp (fst ds, [ds !!]) [Map.elements vmap].\n  Proof.\n    intros.\n    unfold dset_match; intuition simpl.\n    unfold ents_valid.\n    apply Forall_forall; intros.\n    inversion H3; subst; clear H3.\n    split.\n    eapply dset_match_log_valid_grouped; eauto.\n    setoid_rewrite <- Map.cardinal_1; eauto.\n\n    inversion H4.\n\n    econstructor.\n    simpl.\n    erewrite dset_match_replay_disk_grouped; eauto.\n    erewrite dset_match_length; eauto.\n    rewrite nthd_oob; auto.\n    constructor.\n  Qed.\n\n  Lemma recover_before_any : forall xp ds ts hm,\n    dset_match xp (effective ds (length ts)) ts ->\n    MLog.would_recover_before xp ds!! hm =p=>\n    would_recover_any xp ds hm.\n  Proof. \n    unfold would_recover_any, rep.\n    intros; norm'r.\n    rewrite <- latest_nthd.\n    rewrite latest_effective.\n    eassign (mk_mstate vmap0 ts vmap0); simpl.\n    cancel.\n    apply MLog.recover_before_either.\n    intuition simpl; auto.\n    rewrite cuttail_length; omega.\n  Qed.\n\n  Lemma recover_before_any_fst : forall xp ds ts hm len,\n    dset_match xp (effective ds (length ts)) ts ->\n    len = length ts ->\n    MLog.would_recover_before xp (fst (effective ds len)) hm =p=>\n    would_recover_any xp ds hm.\n  Proof. \n    unfold would_recover_any, rep.\n    intros; norm'r.\n    rewrite nthd_0.\n    eassign (mk_mstate vmap0 ts vmap0); simpl.\n    rewrite MLog.recover_before_either.\n    cancel.\n    intuition simpl; auto.\n    omega.\n  Qed.\n\n  Lemma synced_recover_any : forall xp ds nr ms ts hm,\n    dset_match xp (effective ds (length ts)) ts ->\n    MLog.rep xp (MLog.Synced nr ds!!) ms hm =p=>\n    would_recover_any xp ds hm.\n  Proof.\n    intros.\n    rewrite MLog.synced_recover_before.\n    eapply recover_before_any; eauto.\n  Qed.\n\n  Lemma recover_latest_any : forall xp ds hm ts,\n    dset_match xp ds ts ->\n    would_recover_any xp (ds!!, nil) hm =p=> would_recover_any xp ds hm.\n  Proof.\n    unfold would_recover_any, rep.\n    safecancel.\n    inversion H1.\n    apply nelist_subset_latest.\n  Qed.\n\n  Lemma recover_latest_any_effective : forall xp ds hm ts,\n    dset_match xp (effective ds (length ts)) ts ->\n    would_recover_any xp (ds!!, nil) hm =p=> would_recover_any xp ds hm.\n  Proof.\n    unfold would_recover_any, rep.\n    safecancel.\n    inversion H1.\n    apply nelist_subset_latest.\n  Qed.\n\n  Lemma cached_length_latest : forall F xp ds ms hm m,\n    (F * rep xp (Cached ds) ms hm)%pred m ->\n    length ds!! = length (fst (effective ds (length (MSTxns ms)))).\n  Proof.\n    unfold rep, dset_match; intuition.\n    destruct_lift H.\n    denote ReplaySeq as Hx.\n    apply replay_seq_latest_length in Hx; simpl in Hx; rewrite <- Hx.\n    rewrite latest_effective; auto.\n  Qed.\n\n  Lemma cached_latest_cached: forall xp ds ms hm,\n    rep xp (Cached (ds!!, nil)) ms hm =p=> rep xp (Cached ds) ms hm.\n  Proof.\n    unfold rep; intros.\n    norml; unfold stars; simpl.\n    assert (MSTxns ms = nil) as Heq.\n    apply dset_match_length in H2; simpl in H2.\n    apply length_nil; auto.\n    rewrite Heq in *; cancel.\n    rewrite nthd_0, Nat.sub_0_r; simpl.\n    rewrite latest_nthd; cancel.\n    unfold effective.\n    rewrite Nat.sub_0_r; simpl.\n    rewrite popn_oob; auto.\n  Qed.\n\n\n  (************* correctness theorems *)\n\n  Definition init_ok : forall xp cs,\n    {< F l d m,\n    PRE:hm   BUFCACHE.rep cs d *\n          [[ (F * arrayS (DataStart xp) m * arrayS (LogHeader xp) l)%pred d ]] *\n          [[ length l = (1 + LogDescLen xp + LogLen xp) /\\\n             length m = (LogHeader xp) - (DataStart xp) /\\\n             LogDescriptor xp = LogHeader xp + 1 /\\\n             LogData xp = LogDescriptor xp + LogDescLen xp /\\\n             LogLen xp = (LogDescLen xp * PaddedLog.DescSig.items_per_val)%nat /\\\n             goodSize addrlen ((LogHeader xp) + length l) ]] *\n          [[ sync_invariant F ]]\n    POST:hm' RET: ms\n          << F, rep: xp (Cached (m, nil)) ms hm' >> \n    XCRASH:hm_crash any\n    >} init xp cs.\n  Proof.\n    unfold init, rep.\n    step.\n    step.\n    apply vmap_match_nil.\n    apply dset_match_nil.\n  Qed.\n\n\n  Lemma dset_match_nthd_effective_fst : forall xp ds ts,\n    dset_match xp (effective ds (length ts)) ts ->\n    nthd (length (snd ds) - length ts) ds = fst (effective ds (length ts)).\n  Proof.\n    intros.\n    rewrite <- nthd_0.\n    rewrite nthd_effective.\n    rewrite Nat.add_0_r; auto.\n  Qed.\n\n\n  Lemma effective_pushd_comm : forall n d ds,\n    effective (pushd d ds) (S n) = pushd d (effective ds n).\n  Proof.\n    unfold effective; simpl; intros.\n    rewrite popn_pushd_comm by omega; auto.\n  Qed.\n\n  Theorem read_ok: forall xp ms a,\n    {< F ds vs,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[[ ds!! ::: exists F', (F' * a |-> vs) ]]]\n    POST:hm' RET:^(ms', r)\n      << F, rep: xp (Cached ds) ms' hm' >> * [[ r = fst vs ]] * [[ readOnly ms ms' ]]\n    CRASH:hm'\n      exists ms', << F, rep: xp (Cached ds) ms' hm' >>\n    >} read xp a ms.\n  Proof.\n    unfold read, rep.\n    prestep.\n    cancel.\n\n    (* case 1 : return from vmap *)\n    step.\n    eapply diskset_vmap_find_ptsto; eauto.\n    rewrite latest_effective; eauto.\n    pimpl_crash; cancel.\n\n    (* case 2: read from MLog *)\n    cancel.\n    eexists; apply list2nmem_ptsto_cancel_pair.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    eapply diskset_ptsto_bound_latest; eauto.\n    rewrite latest_effective; eauto.\n\n    step; subst.\n    erewrite fst_pair; eauto.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    eapply diskset_vmap_find_none; eauto.\n    rewrite latest_effective; eauto.\n    pimpl_crash; cancel.\n    eassign (mk_mstate (MSVMap ms_1) (MSTxns ms_1) ms'_1); cancel.\n    all: auto.\n  Qed.\n\n\n  Theorem submit_ok: forall xp ents ms,\n    {< F ds,\n    PRE:hm\n        << F, rep: xp (Cached ds) ms hm >> *\n        [[ log_valid ents ds!! ]]\n    POST:hm' RET:^(ms', r)\n        ([[ r = false /\\ length ents > LogLen xp ]] *\n         << F, rep: xp (Cached ds) ms' hm' >> *\n        [[ ms' = ms ]])\n     \\/ ([[ r = true  ]] *\n          << F, rep: xp (Cached (pushd (replay_disk ents (latest ds)) ds)) ms' hm' >>)\n    CRASH:hm'\n      exists ms', << F, rep: xp (Cached ds) ms' hm' >>\n    >} submit xp ents ms.\n  Proof.\n    unfold submit, rep.\n    step.\n    step.\n    or_r; cancel.\n    rewrite nthd_pushd' by omega; eauto.\n\n    unfold vmap_match in *; simpl.\n    denote! (Map.Equal _ _) as Heq.\n    rewrite Heq; apply MapFacts.Equal_refl.\n\n    rewrite effective_pushd_comm.\n    erewrite <- latest_effective.\n    apply dset_match_ext; auto.\n    rewrite latest_effective; auto.\n    step.\n    Unshelve. all: try exact vmap0; eauto.\n  Qed.\n\n\n\n  Local Hint Resolve vmap_match_nil dset_match_nil.\n  Opaque MLog.flush.\n\n  Theorem flushall_nomerge_ok: forall xp ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (ds!!, nil)) ms' hm' >> *\n      [[ MSTxns (fst ms') = nil /\\ MSVMap (fst ms') = vmap0 ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} flushall_nomerge xp ms.\n  Proof.\n    unfold flushall_nomerge, would_recover_any, rep.\n    prestep.\n    cancel.\n\n    rewrite nthd_effective, Nat.add_0_r.\n    apply sep_star_comm.\n\n    - safestep.\n      eapply dset_match_log_valid_selN; eauto.\n      safestep.\n\n      (* flush() returns true *)\n      erewrite dset_match_nthd_S by eauto; cancel.\n      eexists.\n\n      (* flush() returns false, this is impossible *)\n      exfalso; eapply dset_match_ent_length_exfalso; eauto.\n\n      (* crashes *)\n      subst; repeat xcrash_rewrite.\n      xform_norm; cancel.\n      xform_normr. safecancel.\n      eassign (mk_mstate vmap0 (MSTxns ms_1) vmap0); simpl.\n      rewrite selR_inb by eauto; cancel.\n      all: simpl; auto; omega.\n\n    - safestep.\n      rewrite nthd_oob, latest_effective, nthd_0.\n      cancel.\n      erewrite <- dset_match_length; eauto.\n      apply dset_match_nil.\n\n    - cancel.\n      xcrash_rewrite.\n      (* manually construct an RHS-like pred, but replace hm'' with hm *)\n      instantiate (1 := (exists raw cs, BUFCACHE.rep cs raw *\n        [[ (F * exists ms n, \n          [[ dset_match xp (effective ds (length (MSTxns ms))) (MSTxns ms)\n            /\\ n <= length (MSTxns ms) ]] *\n          MLog.would_recover_either xp (nthd n (effective ds (length (MSTxns ms))))\n           (selR (MSTxns ms) n nil) hm)%pred raw ]])%pred ).\n      xform_norm; cancel.\n      xform_normr; safecancel.\n      apply MLog.would_recover_either_hashmap_subset.\n      all: eauto.\n    Unshelve. all: constructor.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (flushall_nomerge _ _) _) => apply flushall_nomerge_ok : prog.\n\n  Opaque flushall_nomerge.\n\n  Theorem flushall_ok: forall xp ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (ds!!, nil)) ms' hm' >> *\n      [[ MSTxns (fst ms') = nil /\\ MSVMap (fst ms') = vmap0 ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} flushall xp ms.\n  Proof.\n    unfold flushall.\n    safestep.\n\n    prestep; denote rep as Hx; unfold rep in Hx; destruct_lift Hx.\n    cancel.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    eapply dset_match_log_valid_grouped; eauto.\n\n    prestep; unfold rep; safecancel.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    erewrite dset_match_replay_disk_grouped; eauto.\n    erewrite nthd_oob; eauto.\n    rewrite latest_effective, nthd_0; eauto.\n    erewrite dset_match_length at 1; eauto.\n    apply dset_match_nil.\n\n    denote (length _ > _) as Hf; contradict Hf.\n    setoid_rewrite <- Map.cardinal_1; omega.\n    apply dset_match_nil.\n\n    xcrash.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    unfold would_recover_any, rep.\n    destruct (MSTxns ms_1);\n    norm; unfold stars; simpl.\n\n    unfold vmap_match in *; simpl in *.\n    denote (Map.Equal _ vmap0) as Heq.\n    rewrite Heq.\n    replace (Map.elements _) with (@nil (Map.key * valu)) by auto.\n    rewrite nthd_effective.\n    eassign (mk_mstate vmap0 nil (MSMLog ms_1)); simpl.\n    rewrite Nat.add_0_r, selR_oob by auto.\n    cancel.\n    intuition.\n\n    eassign (fst (effective ds (S (length t))), latest ds :: nil).\n    eassign (mk_mstate vmap0 (Map.elements (MSVMap ms_1) :: nil) (MSMLog ms_1)); simpl.\n    rewrite nthd_0.\n    unfold selR; simpl; rewrite nthd_0; simpl.\n    cancel.\n\n    assert (length (snd ds) > 0).\n    denote dset_match as Hx.\n    apply dset_match_length in Hx; simpl in Hx.\n    rewrite cuttail_length in Hx; omega.\n    intuition.\n    rewrite <- nthd_0, nthd_effective, Nat.add_0_r.\n    apply nelist_subset_nthd_latest; omega.\n\n    unfold effective; simpl; rewrite popn_0.\n    replace (S (length t)) with (length (c :: t)) by auto.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    erewrite <- latest_effective; eauto.\n    eapply dset_match_grouped; eauto; simpl.\n    rewrite cuttail_length; omega.\n\n    safestep.\n    repeat match goal with\n              | [ H := ?e |- _ ] => subst H\n            end; cancel.\n    step.\n\n    Unshelve. all: try exact nil; eauto; try exact vmap0.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (init _ _) _) => apply init_ok : prog.\n  Hint Extern 1 ({{_}} Bind (read _ _ _) _) => apply read_ok : prog.\n  Hint Extern 1 ({{_}} Bind (submit _ _ _) _) => apply submit_ok : prog.\n  Hint Extern 1 ({{_}} Bind (flushall _ _) _) => apply flushall_ok : prog.\n  Hint Extern 0 (okToUnify (rep _ _ _ _) (rep _ _ _ _)) => constructor : okToUnify.\n\n  Theorem flushall_noop_ok: forall xp ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached ds) ms' hm' >> *\n      [[ MSTxns (fst ms') = nil /\\ MSVMap (fst ms') = vmap0 ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} flushall_noop xp ms.\n  Proof.\n    unfold flushall_noop; intros.\n    safestep.\n    step.\n    apply cached_latest_cached.\n  Qed.\n\n  Theorem flushsync_ok: forall xp ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (ds!!, nil)) ms' hm' >> *\n      [[ MSTxns (fst ms') = nil /\\ MSVMap (fst ms') = vmap0 ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} flushsync xp ms.\n  Proof.\n    unfold flushsync.\n    step.\n    prestep; unfold rep; cancel.\n    prestep; unfold rep; cancel.\n    xcrash.\n    denote rep as Hx; unfold rep in Hx.\n    destruct_lift Hx.\n    eapply recover_before_any; eauto.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (flushsync _ _) _) => apply flushsync_ok : prog.\n\n  Theorem flushsync_noop_ok: forall xp ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached ds) ms' hm' >> *\n      [[ MSTxns (fst ms') = nil /\\ MSVMap (fst ms') = vmap0 ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} flushsync_noop xp ms.\n  Proof.\n    unfold flushsync_noop.\n    safestep.\n    step.\n    apply cached_latest_cached.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (flushall_noop _ _) _) => apply flushall_noop_ok : prog.\n  Hint Extern 1 ({{_}} Bind (flushsync_noop _ _) _) => apply flushsync_noop_ok : prog.\n\n  Lemma forall_ents_valid_length_eq : forall xp d d' ts,\n    Forall (ents_valid xp d) ts ->\n    length d' = length d ->\n    Forall (ents_valid xp d') ts.\n  Proof.\n    unfold ents_valid; intros.\n    rewrite Forall_forall in *.\n    intros.\n    specialize (H _ H1); intuition.\n    eapply log_valid_length_eq; eauto.\n  Qed.\n\n  Lemma vmap_match_notin : forall ts vm a,\n    Map.find a vm = None ->\n    vmap_match vm ts ->\n    Forall (fun e => ~ In a (map fst e)) ts.\n  Proof.\n    unfold vmap_match; induction ts; intros.\n    apply Forall_nil.\n    constructor; simpl in *.\n    eapply map_find_replay_mem_not_in.\n    rewrite <- H0; auto.\n\n    eapply IHts.\n    2: apply MapFacts.Equal_refl.\n    eapply replay_mem_find_none_mono.\n    rewrite <- H0; auto.\n  Qed.\n\n  Lemma dset_match_dsupd_notin : forall xp ds a v ts vm,\n    Map.find a vm = None ->\n    vmap_match vm ts ->\n    dset_match xp ds ts ->\n    dset_match xp (dsupd ds a v) ts.\n  Proof.\n    unfold dset_match; intuition; simpl in *.\n    eapply forall_ents_valid_length_eq; try eassumption.\n    apply length_updN.\n    apply replay_seq_dsupd_notin; auto.\n    eapply vmap_match_notin; eauto.\n  Qed.\n\n  Lemma forall_ents_valid_ents_filter : forall ts xp d f,\n    Forall (ents_valid xp d) ts ->\n    Forall (ents_valid xp d) (map (fun x => filter f x) ts).\n  Proof.\n    induction ts; simpl; auto; intros.\n    inversion H; subst.\n    constructor; auto.\n    split; destruct H2.\n    apply log_vaild_filter; eauto.\n    eapply le_trans.\n    apply filter_length. auto.\n  Qed.\n\n  Lemma forall_ents_valid_ents_remove : forall ts xp d a,\n    Forall (ents_valid xp d) ts ->\n    Forall (ents_valid xp d) (map (ents_remove a) ts).\n  Proof.\n    intros; apply forall_ents_valid_ents_filter; auto.\n  Qed.\n\n  Lemma forall_ents_valid_ents_remove_list : forall ts xp d al,\n    Forall (ents_valid xp d) ts ->\n    Forall (ents_valid xp d) (map (ents_remove_list al) ts).\n  Proof.\n    intros; apply forall_ents_valid_ents_filter; auto.\n  Qed.\n\n  Lemma dset_match_dsupd : forall xp ts ds a v,\n    dset_match xp ds ts ->\n    dset_match xp (dsupd ds a v) (map (ents_remove a) ts).\n  Proof.\n    unfold dset_match; intuition; simpl in *.\n    eapply ents_valid_length_eq.\n    2: rewrite length_updN; auto.\n    apply forall_ents_valid_ents_remove; auto.\n    apply replay_seq_dsupd_ents_remove; auto.\n  Qed.\n\n  Lemma dset_match_dssync_vecs : forall xp ts ds al,\n    dset_match xp ds ts ->\n    dset_match xp (dssync_vecs ds al) ts.\n  Proof.\n    unfold dset_match; intuition; simpl in *; auto.\n    eapply ents_valid_length_eq.\n    2: apply eq_sym; apply vssync_vecs_length.\n    auto.\n    apply replay_seq_dssync_vecs_ents; auto.\n  Qed.\n\n  Lemma dset_match_dssync : forall xp ds a ts,\n    dset_match xp ds ts ->\n    dset_match xp (dssync ds a) ts.\n  Proof.\n    unfold dset_match; intuition; simpl in *.\n    eapply forall_ents_valid_length_eq; try eassumption.\n    apply length_updN.\n    apply replay_seq_dssync_notin; auto.\n  Qed.\n\n  Lemma effective_dsupd_comm : forall ds a v n,\n    effective (dsupd ds a v) n = dsupd (effective ds n) a v.\n  Proof.\n    unfold effective, dsupd; simpl; intros.\n    rewrite map_length.\n    apply dmap_popn_comm.\n  Qed.\n\n  Lemma effective_dsupd_vecs_comm : forall ds avl n,\n    effective (dsupd_vecs ds avl) n = dsupd_vecs (effective ds n) avl.\n  Proof.\n    unfold effective, dsupd_vecs; simpl; intros.\n    rewrite map_length.\n    apply dmap_popn_comm.\n  Qed.\n\n  Lemma effective_dssync_vecs_comm : forall ds al n,\n    effective (dssync_vecs ds al) n = dssync_vecs (effective ds n) al.\n  Proof.\n    unfold effective, dssync_vecs; simpl; intros.\n    rewrite map_length.\n    apply dmap_popn_comm.\n  Qed.\n\n  Lemma effective_dssync_comm : forall ds a n,\n    effective (dssync ds a) n = dssync (effective ds n) a.\n  Proof.\n    unfold effective, dssync; simpl; intros.\n    rewrite map_length.\n    apply dmap_popn_comm.\n  Qed.\n\n  Lemma cached_dsupd_latest_recover_any : forall xp ds a v ms hm ms0,\n    dset_match xp (effective ds (length ms0)) ms0 ->\n    rep xp (Cached ((dsupd ds a v) !!, nil)) ms hm =p=>\n    would_recover_any xp (dsupd ds a v) hm.\n  Proof.\n    unfold rep; cancel.\n    rewrite nthd_0; simpl.\n    rewrite synced_recover_any; auto.\n    rewrite effective_dsupd_comm, map_length.\n    eapply dset_match_dsupd; eauto.\n  Qed.\n\n  Lemma cached_dssync_vecs_latest_recover_any : forall xp ds al ms hm ms0,\n    dset_match xp (effective ds (length ms0)) ms0 ->\n    rep xp (Cached ((dssync_vecs ds al) !!, nil)) ms hm =p=>\n    would_recover_any xp (dssync_vecs ds al) hm.\n  Proof.\n    unfold rep; cancel.\n    rewrite nthd_0; simpl.\n    unfold would_recover_any, rep.\n    rewrite synced_recover_any; auto.\n    rewrite effective_dssync_vecs_comm.\n    eapply dset_match_dssync_vecs; eauto.\n  Qed.\n\n  Lemma cached_latest_recover_any : forall xp ds ms hm ms0,\n    dset_match xp (effective ds (length ms0)) ms0 ->\n    rep xp (Cached (ds !!, nil)) ms hm =p=>\n    would_recover_any xp ds hm.\n  Proof.\n    unfold rep; cancel.\n    rewrite nthd_0; simpl.\n    unfold would_recover_any, rep.\n    rewrite synced_recover_any; eauto.\n  Qed.\n\n\n  Theorem dwrite'_ok: forall xp a v ms,\n    {< F Fd ds vs,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ Map.find a (MSVMap (fst ms)) = None ]] *\n      [[[ fst (effective ds (length (MSTxns (fst ms)))) ::: (Fd * a |-> vs) ]]] *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms' exists ds',\n      << F, rep: xp (Cached ds') ms' hm' >> *\n      [[  ds' = dsupd ds a (v, vsmerge vs) ]]\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n      \\/ exists ms' d',\n      << F, rep: xp (Cached (d', nil)) ms' hm' >> *\n      [[  d' = updN (fst (effective ds (length (MSTxns (fst ms))))) a (v, vsmerge vs) ]] *\n      [[[ d' ::: (Fd * a |-> (v, vsmerge vs)) ]]]\n    >} dwrite' xp a v ms.\n  Proof.\n    unfold dwrite', rep.\n    step.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    safestep.\n    3: eauto.\n\n    erewrite dset_match_nthd_effective_fst; eauto; simpl.\n    erewrite dset_match_length, map_length; eauto.\n    rewrite dsupd_nthd.\n    cancel.\n    rewrite effective_dsupd_comm.\n    eapply dset_match_dsupd_notin; eauto.\n\n    (* crashes *)\n    subst; repeat xcrash_rewrite.\n    xform_norm.\n    or_l; cancel.\n    xform_normr; cancel.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    rewrite recover_before_any_fst by eauto; cancel.\n\n    or_r; cancel.\n    xform_normr; cancel.\n    xform_normr; cancel.\n    rewrite nthd_0; simpl.\n    eassign (mk_mstate vmap0 nil x_1); simpl; cancel.\n    all: simpl; eauto.\n    apply dset_match_nil.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (dwrite' _ _ _ _) _) => apply dwrite'_ok : prog.\n\n  Lemma diskset_ptsto_bound_effective : forall F xp a vs ds ts,\n    dset_match xp (effective ds (length ts)) ts ->\n    (F * a |-> vs)%pred (list2nmem ds!!) ->\n    a < length (nthd (length (snd ds) - length ts) ds).\n  Proof.\n    intros.\n    apply list2nmem_ptsto_bound in H0.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    erewrite <- replay_seq_latest_length; auto.\n    rewrite latest_effective; auto.\n    apply H.\n  Qed.\n\n  Theorem dwrite_ok: forall xp a v ms,\n    {< F Fd ds vs,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[[ ds !! ::: (Fd * a |-> vs) ]]] *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (dsupd ds a (v, vsmerge vs))) ms' hm' >>\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >> \\/\n      << F, would_recover_any: xp (dsupd ds a (v, vsmerge vs)) hm' -- >>\n    >} dwrite xp a v ms.\n  Proof.\n    unfold dwrite, rep.\n    step.\n    prestep; unfold rep; cancel.\n    prestep; unfold rep; safecancel.\n    substl (MSVMap a0); eauto.\n    substl (MSTxns a0); simpl.\n    rewrite Nat.sub_0_r, <- latest_nthd.\n    simpl; pred_apply; cancel.\n    auto.\n\n    step.\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n\n    or_l; cancel.\n    xform_normr; cancel.\n\n    or_r; cancel.\n    do 2 (xform_norm; cancel).\n    repeat rewrite nthd_0; simpl.\n    substl (MSTxns a0); simpl.\n    rewrite Nat.sub_0_r, <- latest_nthd.\n    rewrite <- dsupd_latest.\n    rewrite synced_recover_any; eauto.\n\n    rewrite effective_dsupd_comm, map_length.\n    eapply dset_match_dsupd; eauto.\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n    or_l; cancel.\n    xform_normr; cancel.\n\n    (* 2nd case: no flushall *)\n    prestep; unfold rep; cancel.\n    apply MapFacts.not_find_in_iff; auto.\n    eapply list2nmem_ptsto_cancel_pair.\n    eapply diskset_ptsto_bound_effective; eauto.\n\n    prestep. norm. cancel.\n    intuition simpl. pred_apply.\n    repeat rewrite map_length.\n    rewrite <- surjective_pairing in *.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    erewrite diskset_vmap_find_none; eauto; auto.\n    cancel.\n    erewrite <- diskset_vmap_find_none with (v := vs_cur).\n    erewrite <- dset_match_nthd_effective_fst; eauto.\n    all: eauto.\n    apply MapFacts.not_find_in_iff; auto.\n    rewrite latest_effective; eauto.\n    apply MapFacts.not_find_in_iff; auto.\n    rewrite latest_effective; eauto.\n\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n    or_l; cancel.\n    xform_normr; cancel.\n\n    or_r; cancel.\n    do 2 (xform_norm; cancel).\n\n    rewrite nthd_0; simpl.\n    rewrite <- surjective_pairing in *; simpl.\n    rewrite <- dsupd_nthd.\n    rewrite MLog.synced_recover_before.\n    rewrite dsupd_nthd.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite <- dsupd_fst, <- effective_dsupd_comm.\n    rewrite recover_before_any_fst.\n    erewrite diskset_vmap_find_none; eauto.\n    apply MapFacts.not_find_in_iff; auto.\n    rewrite latest_effective; eauto.\n    rewrite effective_dsupd_comm.\n    eapply dset_match_dsupd; eauto.\n    rewrite map_length; eauto.\n    rewrite map_length; auto.\n  Qed.\n\n\n  Theorem dsync_ok: forall xp a ms,\n    {< F Fd ds vs,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[[ ds !! ::: (Fd * a |-> vs) ]]] *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (dssync ds a)) ms' hm' >>\n    CRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} dsync xp a ms.\n  Proof.\n    unfold dsync.\n    prestep; unfold rep; cancel.\n    eapply list2nmem_ptsto_cancel_pair.\n    eapply diskset_ptsto_bound_effective; eauto.\n\n    prestep; unfold rep; cancel.\n    rewrite map_length.\n    rewrite dssync_nthd; cancel.\n    rewrite effective_dssync_comm.\n    eapply dset_match_dssync; eauto.\n\n    cancel.\n    rewrite MLog.synced_recover_before.\n    erewrite dset_match_nthd_effective_fst; eauto.\n    rewrite recover_before_any_fst; eauto.\n    Unshelve. eauto.\n  Qed.\n\n\n  Lemma vmap_match_nonoverlap : forall ts vm al,\n    overlap al vm = false ->\n    vmap_match vm ts ->\n    Forall (fun e => disjoint al (map fst e)) ts.\n  Proof.\n    unfold vmap_match; induction ts; intros.\n    apply Forall_nil.\n    rewrite H0 in H; simpl in *.\n    constructor; simpl in *.\n    eapply nonoverlap_replay_mem_disjoint; eauto.\n    eapply IHts.\n    2: apply MapFacts.Equal_refl.\n    eapply replay_mem_nonoverlap_mono; eauto.\n  Qed.\n\n  Lemma dset_match_dsupd_vecs_nonoverlap : forall xp avl vm ds ts,\n    overlap (map fst avl) vm = false ->\n    vmap_match vm ts ->\n    dset_match xp ds ts ->\n    dset_match xp (dsupd_vecs ds avl) ts.\n  Proof.\n    unfold dset_match; intuition; simpl in *.\n    eapply forall_ents_valid_length_eq; try eassumption.\n    apply vsupd_vecs_length.\n    apply replay_seq_dsupd_vecs_disjoint; auto.\n    eapply vmap_match_nonoverlap; eauto.\n  Qed.\n\n  Theorem dwrite_vecs'_ok: forall xp avl ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ overlap (map fst avl) (MSVMap (fst ms)) = false ]] *\n      [[ Forall (fun e => fst e < length (fst (effective ds (length (MSTxns (fst ms)))))) avl \n         /\\ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (dsupd_vecs ds avl)) ms' hm' >>\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >> \\/\n      exists ms',\n      << F, rep: xp (Cached (vsupd_vecs (fst (effective ds (length (MSTxns (fst ms))))) avl, nil)) ms' hm' >>\n    >} dwrite_vecs' xp avl ms.\n  Proof.\n    unfold dwrite_vecs'.\n    prestep; unfold rep; cancel.\n    prestep; unfold rep; cancel.\n    rewrite map_length.\n    rewrite dsupd_vecs_nthd; cancel.\n    rewrite effective_dsupd_vecs_comm.\n    eapply dset_match_dsupd_vecs_nonoverlap; eauto.\n\n    xcrash.\n    or_l; xform_norm; cancel.\n    xform_normr; cancel.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite recover_before_any_fst by eauto; cancel.\n\n    or_r; xform_norm; cancel.\n    xform_normr; cancel.\n    rewrite nthd_0.\n    repeat erewrite dset_match_nthd_effective_fst by eauto.\n    eassign (mk_mstate vmap0 nil x0_1); simpl; cancel.\n    all: simpl; eauto.\n    apply dset_match_nil.\n  Qed.\n\n  Hint Extern 1 ({{_}} Bind (dwrite_vecs' _ _ _) _) => apply dwrite_vecs'_ok : prog.\n\n  Lemma effective_avl_addrs_ok : forall (avl : list (addr * valu)) ds ts xp,\n    Forall (fun e => fst e < length (ds !!)) avl ->\n    dset_match xp (effective ds (length ts)) ts ->\n    Forall (fun e => fst e < length (nthd (length (snd ds) - length ts) ds)) avl.\n  Proof.\n    intros.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite Forall_forall in *; intros.\n    erewrite <- replay_seq_latest_length; eauto.\n    rewrite latest_effective; eauto.\n    unfold dset_match in *; intuition eauto.\n  Qed.\n\n  Theorem dwrite_vecs_ok: forall xp avl ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ Forall (fun e => fst e < length (ds!!)) avl /\\ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (dsupd_vecs ds avl)) ms' hm' >>\n    XCRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >> \\/\n      << F, would_recover_any: xp (dsupd_vecs ds avl) hm' -- >>\n    >} dwrite_vecs xp avl ms.\n  Proof.\n    unfold dwrite_vecs, rep.\n    step.\n    prestep; unfold rep; cancel.\n    prestep; unfold rep; safecancel.\n    substl (MSVMap a).\n    apply overlap_empty; apply map_empty_vmap0.\n    eapply effective_avl_addrs_ok; eauto.\n    auto.\n\n    step.\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n\n    or_l; cancel.\n    xform_normr; cancel.\n\n    or_r; cancel.\n    do 2 (xform_norm; cancel).\n    repeat rewrite nthd_0; simpl.\n    substl (MSTxns a); simpl.\n    rewrite Nat.sub_0_r, <- latest_nthd.\n    rewrite <- dsupd_vecs_latest.\n    rewrite synced_recover_any; eauto.\n    eassign (MSTxns a); substl (MSTxns a); simpl.\n    unfold effective; rewrite popn_oob by omega.\n    apply dset_match_nil.\n\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n    or_l; cancel.\n    xform_normr; cancel.\n\n    prestep; unfold rep; cancel.\n    apply not_true_iff_false; auto.\n    eapply effective_avl_addrs_ok; eauto.\n\n    step.\n    cancel.\n    repeat xcrash_rewrite; xform_norm.\n    or_l; cancel.\n    xform_normr; cancel.\n\n    or_r; cancel.\n    do 2 (xform_norm; cancel).\n    repeat rewrite nthd_0; simpl.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite <- dsupd_vecs_fst, <- effective_dsupd_vecs_comm.\n    rewrite MLog.synced_recover_before.\n    rewrite recover_before_any_fst.\n    auto.\n\n    rewrite effective_dsupd_vecs_comm.\n    eapply dset_match_dsupd_vecs_nonoverlap.\n    apply not_true_is_false; eauto.\n    all: eauto.\n  Qed.\n\n\n  Theorem dsync_vecs_ok: forall xp al ms,\n    {< F ds,\n    PRE:hm\n      << F, rep: xp (Cached ds) ms hm >> *\n      [[ Forall (fun e => e < length (ds!!)) al /\\ sync_invariant F ]]\n    POST:hm' RET:ms'\n      << F, rep: xp (Cached (dssync_vecs ds al)) ms' hm' >>\n    CRASH:hm'\n      << F, would_recover_any: xp ds hm' -- >>\n    >} dsync_vecs xp al ms.\n  Proof.\n    unfold dsync_vecs.\n    prestep; unfold rep; cancel.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite Forall_forall in *; intros.\n    erewrite <- replay_seq_latest_length; eauto.\n    rewrite latest_effective; eauto.\n    unfold dset_match in *; intuition eauto.\n\n    prestep; unfold rep; cancel.\n    rewrite map_length.\n    rewrite dssync_vecs_nthd; cancel.\n    rewrite effective_dssync_vecs_comm.\n    eapply dset_match_dssync_vecs; eauto.\n\n    cancel.\n    erewrite dset_match_nthd_effective_fst by eauto.\n    rewrite MLog.synced_recover_before.\n    rewrite recover_before_any_fst; eauto.\n  Qed.\n\n  Definition recover_any_pred xp ds hm :=\n    ( exists d n ms, [[ n <= length (snd ds) ]] *\n      (rep xp (Cached (d, nil)) ms hm \\/\n        rep xp (Rollback d) ms hm) *\n      [[[ d ::: crash_xform (diskIs (list2nmem (nthd n ds))) ]]])%pred.\n\n  Theorem sync_invariant_recover_any_pred : forall xp ds hm,\n    sync_invariant (recover_any_pred xp ds hm).\n  Proof.\n    unfold recover_any_pred; intros; auto 10.\n  Qed.\n  Hint Resolve sync_invariant_recover_any_pred.\n\n  Lemma NEListSubset_effective : forall ds ds' n,\n    NEListSubset ds ds' ->\n    NEListSubset ds (effective ds' n).\n  Proof.\n    unfold effective; intros.\n    apply nelist_subset_popn'; auto.\n  Qed.\n\n  Theorem crash_xform_any : forall xp ds hm,\n    crash_xform (would_recover_any xp ds hm) =p=>\n                 recover_any_pred  xp ds hm.\n  Proof.\n    unfold would_recover_any, recover_any_pred, rep; intros.\n    xform_norm.\n    rewrite MLog.crash_xform_either.\n    erewrite dset_match_length in H3; eauto.\n    denote NEListSubset as Hds.\n    eapply NEListSubset_effective in Hds.\n    eapply nelist_subset_nthd in Hds as Hds'; eauto.\n    deex.\n    denote nthd as Hnthd.\n    unfold MLog.recover_either_pred; xform_norm.\n\n    - norm. cancel.\n      eassign (mk_mstate vmap0 nil ms'); eauto.\n      or_l; cancel.\n      apply dset_match_nil.\n      intuition simpl.\n      eassumption.\n      setoid_rewrite Hnthd; auto.\n\n    - destruct (Nat.eq_dec x0 (length (MSTxns x))) eqn:Hlength; subst.\n      norm. cancel.\n      or_l; cancel.\n      rewrite nthd_0.\n      eassign (mk_mstate vmap0 nil ms'); eauto.\n      auto.\n      apply dset_match_nil.\n      eassign n; intuition; simpl.\n      setoid_rewrite Hnthd.\n      pred_apply.\n      rewrite selR_oob by auto; simpl; auto.\n\n      denote (length (snd x1)) as Hlen.\n      eapply nelist_subset_nthd with (n':=S x0) in Hds; eauto.\n      deex.\n      clear Hnthd.\n      denote nthd as Hnthd.\n      norm. cancel.\n      or_l; cancel.\n      rewrite nthd_0.\n      eassign (mk_mstate vmap0 nil ms'); eauto.\n      auto.\n      apply dset_match_nil.\n      eassign n1.\n      unfold selR in *.\n      destruct (lt_dec x0 (length (MSTxns x))); intuition.\n      pred_apply.\n      erewrite dset_match_nthd_S in *; eauto.\n      setoid_rewrite Hnthd; auto.\n      denote dset_match as Hx.\n      apply dset_match_length in Hx; simpl in Hx; omega.\n      denote dset_match as Hx. \n      apply dset_match_length in Hx; simpl in Hx; simpl.\n      rewrite cuttail_length in *. omega.\n\n    - norm. cancel.\n      or_r; cancel.\n      eassign (mk_mstate vmap0 nil ms'); eauto.\n      auto.\n      auto.\n      eassign n.\n      intuition.\n      setoid_rewrite Hnthd.\n      pred_apply.\n      erewrite nthd_effective, dset_match_length; eauto.\n  Qed.\n\n  Lemma crash_xform_recovering : forall xp d mm hm,\n    crash_xform (rep xp (Recovering d) mm hm) =p=>\n                 recover_any_pred xp (d, nil) hm.\n  Proof.\n    unfold recover_any_pred, rep; intros.\n    xform_norm.\n    rewrite MLog.crash_xform_recovering.\n    instantiate (1:=nil).\n    unfold MLog.recover_either_pred.\n    norm.\n    unfold stars; simpl.\n    or_l; cancel.\n    eassign (mk_mstate vmap0 nil ms'); cancel.\n    auto.\n    apply dset_match_nil.\n    intuition simpl; eauto.\n    or_l; cancel.\n    eassign (mk_mstate vmap0 nil ms'); cancel.\n    auto.\n    apply dset_match_nil.\n    intuition simpl; eauto.\n    or_r; cancel.\n    eassign (mk_mstate vmap0 nil ms'); cancel.\n    auto.\n    apply dset_match_nil.\n    intuition simpl; eauto.\n  Qed.\n\n  Lemma crash_xform_cached : forall xp ds ms hm,\n    crash_xform (rep xp (Cached ds) ms hm) =p=>\n      exists d n ms', rep xp (Cached (d, nil)) ms' hm *\n        [[[ d ::: (crash_xform (diskIs (list2nmem (nthd n ds)))) ]]] *\n        [[ n <= length (snd ds) ]].\n  Proof.\n    unfold rep; intros.\n    xform_norm.\n    rewrite MLog.crash_xform_synced; norm.\n    eassign (mk_mstate vmap0 nil ms'); simpl.\n    cancel.\n    intuition simpl.\n    auto.\n    apply dset_match_nil.\n    pred_apply.\n    cancel.\n    omega.\n  Qed.\n\n  Lemma crash_xform_rollback : forall xp d ms hm,\n    crash_xform (rep xp (Rollback d) ms hm) =p=>\n      exists d' ms', rep xp (Rollback d') ms' hm *\n        [[[ d' ::: (crash_xform (diskIs (list2nmem d))) ]]].\n  Proof.\n    unfold rep; intros.\n    xform_norm.\n    rewrite MLog.crash_xform_rollback.\n    cancel.\n    eassign (mk_mstate vmap0 nil ms'); eauto.\n    all: auto.\n  Qed.\n\n  Lemma any_pred_any : forall xp ds hm,\n    recover_any_pred xp ds hm =p=>\n    exists d, would_recover_any xp (d, nil) hm.\n  Proof.\n    unfold recover_any_pred; intros.\n    xform_norm.\n    rewrite cached_recover_any; cancel.\n    rewrite rollback_recover_any; cancel.\n  Qed.\n\n\n  Lemma recover_idem : forall xp ds hm,\n    crash_xform (recover_any_pred xp ds hm) =p=>\n                 recover_any_pred xp ds hm.\n  Proof.\n    unfold recover_any_pred, rep; intros.\n    xform_norm.\n    - rewrite MLog.crash_xform_synced.\n      norm.\n      eassign (mk_mstate (MSVMap x1) (MSTxns x1) ms'); cancel.\n      or_l; cancel.\n      replace d' with x in *.\n      intuition simpl; eauto.\n      apply list2nmem_inj.\n      eapply crash_xform_diskIs_eq; eauto.\n      intuition.\n      erewrite Nat.min_l.\n      eassign x0.\n      eapply crash_xform_diskIs_trans; eauto.\n      auto.\n\n    - rewrite MLog.crash_xform_rollback.\n      norm.\n      eassign (mk_mstate (MSVMap x1) (MSTxns x1) ms'); cancel.\n      or_r; cancel.\n      denote (dset_match) as Hdset; inversion Hdset as (_, H').\n      inversion H'.\n      auto.\n      intuition simpl; eauto.\n      eapply crash_xform_diskIs_trans; eauto.\n  Qed.\n\n\n  Theorem recover_ok: forall xp cs,\n    {< F raw ds,\n    PRE:hm\n      BUFCACHE.rep cs raw *\n      [[ (F * recover_any_pred xp ds hm)%pred raw ]] *\n      [[ sync_invariant F ]]\n    POST:hm' RET:ms' exists raw',\n      BUFCACHE.rep (MSCache ms') raw' *\n      [[ (exists d n, [[ n <= length (snd  ds) ]] *\n          F * rep xp (Cached (d, nil)) (fst ms') hm' *\n          [[[ d ::: crash_xform (diskIs (list2nmem (nthd n ds))) ]]]\n      )%pred raw' ]]\n    XCRASH:hm'\n      exists raw' cs' mm', BUFCACHE.rep cs' raw' *\n      [[ (exists d n, [[ n <= length (snd  ds) ]] *\n          F * rep xp (Recovering d) mm' hm' *\n          [[[ d ::: crash_xform (diskIs (list2nmem (nthd n ds))) ]]]\n          )%pred raw' ]]\n    >} recover xp cs.\n  Proof.\n    unfold recover, recover_any_pred, rep.\n    prestep. norm'l.\n    denote or as Hx.\n    apply sep_star_or_distr in Hx.\n    destruct Hx; destruct_lift H; safecancel.\n\n    (* Cached *)\n    unfold MLog.recover_either_pred; cancel.\n    rewrite sep_star_or_distr; or_l; cancel.\n    eassign F. cancel.\n    or_l; cancel. auto.\n\n    safestep. eauto.\n    apply dset_match_nil.\n    eassumption.\n    apply dset_match_nil.\n    instantiate (1:=nil); cancel.\n\n    repeat xcrash_rewrite.\n    xform_norm.\n    cancel.\n    xform_norm; cancel.\n    xform_norm; cancel.\n    rewrite crash_xform_sep_star_dist; cancel.\n    xform_norm.\n    norm. cancel.\n    pred_apply.\n    norm. cancel.\n\n    eassign (mk_mstate vmap0 nil x1); eauto.\n    intuition simpl; eauto.\n    cancel.\n    intuition simpl; eauto.\n\n    (* Rollback *)\n    unfold MLog.recover_either_pred; cancel.\n    rewrite sep_star_or_distr; or_r; cancel.\n    auto.\n\n    safestep. eauto.\n    apply dset_match_nil.\n    eassumption.\n    apply dset_match_nil.\n    instantiate (1:=nil); cancel.\n\n    repeat xcrash_rewrite.\n    xform_norm.\n    cancel.\n    xform_norm; cancel.\n    xform_norm; cancel.\n    rewrite crash_xform_sep_star_dist; cancel.\n    xform_norm.\n    norm. cancel.\n    pred_apply.\n    norm. cancel.\n\n    eassign (mk_mstate vmap0 nil x1); eauto.\n    intuition simpl; eauto.\n    cancel.\n    intuition simpl; eauto.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (recover _ _) _) => apply recover_ok : prog.\n  Hint Extern 1 ({{_}} Bind (dwrite _ _ _ _) _) => apply dwrite_ok : prog.\n  Hint Extern 1 ({{_}} Bind (dwrite_vecs _ _ _) _) => apply dwrite_vecs_ok : prog.\n  Hint Extern 1 ({{_}} Bind (dsync _ _ _) _) => apply dsync_ok : prog.\n  Hint Extern 1 ({{_}} Bind (dsync_vecs _ _ _) _) => apply dsync_vecs_ok : prog.\n\n\nEnd GLog.\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/GroupLog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.15857991981721095}}
{"text": "(* En este archivo se postulan y demuestran propiedades sobre\n*  el modelo y sobre la implementaci\u00f3n desarrollada de \u00e9l *)\nRequire Import Coq.Arith.Lt.\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.\nRequire Import RuntimePermissions.\nRequire Import EqTheorems.\nRequire Import Trace.\nRequire Import DelegateGrantPRevoke.\nRequire Import RvkAndNotGrant.\nRequire Import IfPermThenGranted.\nRequire Import DangPermMissing.\nRequire Import RvkCanStart.\nRequire Import IfOldAppRunThenVerified.\nRequire Import DangPermAutoGranted.\n\nSection ModelProperties.\n\n    (* Permission Groups *)\n    (*Internet access irrestricted*)\n\n(* En un estado v\u00e1lido, si una llamada al sistema requiere s\u00f3lo permisos normales, entonces cualquier instancia en ejecuci\u00f3n cuya aplicaci\u00f3n liste los permisos\n * correspondientes como usados puede ejecutar la llamada *)\n    Theorem sacProtectedWithNormalPerms : forall\n        (s:System)\n        (access_internet:SACall)\n        (c:Cmp)\n        (ic:iCmp)\n        , validstate s -> (forall (p:Perm) (pIsSystem : isSystemPerm p) (pIsRequired : permSAC p pIsSystem access_internet), pl p = normal) -> (forall (p:Perm) (pIsSystem : isSystemPerm p) (pIsRequired : permSAC p pIsSystem access_internet), In p (use (getManifestForApp (getAppFromCmp c s) s))) -> (map_apply iCmp_eq (running (state s)) ic = Value iCmp c) -> exec s (call ic access_internet) s ok.\nProof.\n    intro.\n    intro.\n    intro.\n    intro.\n    intro sValid.\n    intro allRequiredAreNormal.\n    intro allRequiredAreListedAsUsed.\n    intro icIsRunningC.\n    unfold exec.\n    split;auto.\n    left.\n    split;auto.\n    split.\n    unfold pre.\n    unfold pre_call.\n    exists c.\n    split;auto.\n    intros.\n    specialize (allRequiredAreNormal p H H1).\n    specialize (allRequiredAreListedAsUsed p H H1).\n    unfold appHasPermission.\n    right.\n    split.\n    unfold permExists.\n    left;auto.\n    assert (getAppFromCmp c s=a).\n    apply inAppThenGetAppFromCmp;auto.\n    rewrite H2 in *.\n    split.\n    exists (getManifestForApp a s).\n    split;auto.\n    apply (isManifestOfAppCorrect s sValid a).\n    apply (ifInAppThenIsAppInstalled s sValid c);auto.\n    right.\n    left;auto.\n    simpl.\n    unfold post_call.\n    auto.\nQed.\n\n    (* Missing permissions *)\n    \n    (* Existe un estado v\u00e1lido en el que una aplicaci\u00f3n instalada no tiene un permiso peligroso existente a pesar de que lo lista como usado. *)\n    Theorem dangerousPermMissing : exists \n    (s:System)\n    (p:Perm)\n    (a:idApp)\n    , validstate s /\\ pl p=dangerous /\\ permExists p s /\\ In a (apps (state s)) /\\ In p (use (getManifestForApp a s)) /\\ ~appHasPermission a p s.\nProof.\n    apply dangerousPermMissingProof.\nQed.\n\n    (* Delegated permissions *)\n\n(* En todo estado v\u00e1lido, si se le otorga correctamente un permiso p a una aplicaci\u00f3n a que tiene uno de sus componentes ejecut\u00e1ndose\n * con identificador ic; quien luego delega un permiso de lectura a una aplicaci\u00f3n a' sobre un uri de un contentProvider de lectura protegida\n * por p, y m\u00e1s tarde se le quita el permiso p a a, posteriormente si una instancia en ejecuci\u00f3n de un componente de a' intenta leer dicho uri\n * de cp, podr\u00e1 hacerlo correctamente *)\n\n    Theorem delegateGrantPRevoke : forall \n        (s:System)\n        (p:Perm)\n        (a a':idApp)\n        (ic ic': iCmp)\n        (c c':Cmp)\n        (u:uri)\n        (cp:CProvider),\n        validstate s ->\n        response (step s (grant p a)) = ok ->\n        getAppFromCmp c s = a ->\n        getAppFromCmp c' s = a' ->\n        map_apply iCmp_eq (running (state s)) ic = Value iCmp c ->\n        map_apply iCmp_eq (running (state s)) ic' = Value iCmp c' ->\n        canGrant cp u s ->\n        existsRes cp u s ->\n        expC cp = Some true ->\n        readE cp = Some p ->\n        let opsResult := trace s (grant p a:: grantP ic cp a' u Read:: revoke p a::nil) in\n        response (step (last opsResult s) (read ic' cp u))=ok.\nProof.\n    intros.\n    apply (delegateGrantPRevokeProof s H p a a' H0 ic ic' c c');auto.\nQed.\n\n\n(* Para todo estado inicial v\u00e1lido en el cual una aplicaci\u00f3n A no tiene un permiso peligroso  P, si al final de una serie de operaciones en\n * la que A no es desinstalada, A pasa a contar con tal permiso; entonces en alg\u00fan momento el permiso P le fue otorgado *)\n    Theorem ifPermThenGranted : forall\n        (initState lastState:System)\n        (a:idApp)\n        (p:Perm)\n        (l:list Action),\n        validstate initState->\n        In a (apps (state initState))->\n        pl p = dangerous->\n        maybeGrp p = None->\n        appHasPermission a p lastState->\n        ~appHasPermission a p initState->\n        ~In (uninstall a) l->\n         last (trace initState l) initState = lastState->\n        In (grant p a) l \\/ In (grantAuto p a) l.\nProof.\n    intros.\n    apply (ifPermThenGrantedProof initState lastState);auto.\nQed.\n\n(* Si en un estado inicial v\u00e1lido se le revoca correctamente un permiso p a una aplicaci\u00f3n a, mientras la aplicaci\u00f3n no sea desinstalada\n * ni el permiso reotorgado, la aplicaci\u00f3n no contar\u00e1 con \u00e9l *)\n    Theorem revokeAndNotGrant : forall\n        (initState sndState lastState:System)\n        (a:idApp)\n        (p:Perm)\n        (l:list Action),\n        validstate initState->\n        pl p=dangerous->\n        (~exists lPerm : list Perm, map_apply idApp_eq (defPerms (environment initState)) a = Value idApp lPerm /\\ In p lPerm) ->\n        sndState = system (step initState (revoke p a))->\n        response (step initState (revoke p a))=ok->\n        ~In (uninstall a) l->\n        ~In (grant p a) l->\n        ~In (grantAuto p a) l ->\n        last (trace sndState l) sndState = lastState->\n        ~appHasPermission a p lastState.\nProof.\n    intros.\n    apply (revokeAndNotGrantProof initState sndState lastState H a p H0 H1 H2 H3 l);auto.\nQed.\n\n(* En todo estado v\u00e1lido en donde un componente c1 tiene la potestad de iniciar a una actividad c2 de otra aplicaci\u00f3n protegida por\n * un permiso peligroso no agrupado p que no es definido por la aplicaci\u00f3n en donde se encuentra c1, existen ciertas acciones que hacen\n * que pierda la posibilidad de hacerlo a pesar de que ninguna de las dos aplicaciones haya sido desinstalada *)\n    Theorem revokeCanStart : forall\n        (initState:System)\n        (l:list Action)\n        (a1 a2:idApp)\n        (c1:Cmp)\n        (act:Activity)\n        (p:Perm),\n        validstate initState->\n        pl p=dangerous->\n        maybeGrp p = None->\n        a1<>a2 ->\n        (~exists lPerm : list Perm, map_apply idApp_eq (defPerms (environment initState)) a1 = Value idApp lPerm /\\ In p lPerm) ->\n        inApp c1 a1 initState ->\n        inApp (cmpAct act) a2 initState ->\n        cmpEA act = Some p ->\n        canStart c1 (cmpAct act) initState ->\n        exists (l:list Action), \n        ~In (uninstall a1) l /\\\n        ~In (uninstall a2) l /\\\n        ~canStart c1 (cmpAct act) (last (trace initState l) initState).\nProof.\n    apply revokeCanStartProof.\nQed.\n\n\n(* Para todo estado inicial v\u00e1lido en el que existe una aplicaci\u00f3n 'a' vieja y no verificada, si luego de una serie de operaciones\n * 'a' en la que 'a' no se desinstala, 'a' est\u00e1 en condiciones de ser ejecutada; entonces alguna de esas operaciones fue la que la\n * verific\u00f3 *)\n    Theorem ifOldAppRunThenVerified : forall \n        (initState lastState: System)\n        (a: idApp)\n        (l: list Action)\n        (aInstalled:In a (apps (state initState)) \\/ (exists x0, In x0 (systemImage (environment initState)) /\\ idSI x0 = a))\n        (vsInit: validstate initState)\n        (oldApp: isOldApp a initState)\n        (notVerified: ~(In a (alreadyVerified (state initState))))\n        (canRunLastState: canRun a lastState)\n        (aIsTheSame : ~ In (uninstall a) l)\n        (fromInitToLast: last (trace initState l) initState  = lastState),\n        In (verifyOldApp a) l.\nProof.\n    apply ifOldAppRunThenWasVerifiedProof.\nQed.\n\n(*\n * Este teorema establece que el sistema no puede otorgar autom\u00e1ticamente un permiso (peligroso) \n * agrupado si el grupo del mismo no ha sido previamente otorgado a trav\u00e9s de un grant de usuario.\n *)\nTheorem cannotAutoGrantWithoutGroup :\n  forall (s s': System) (p: Perm) (g: idGrp) (a: idApp),\n    pl p = dangerous ->\n    maybeGrp p = Some g ->\n    ~ (exists (lGroup: list idGrp),\n      map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp lGroup /\\ In g lGroup) ->\n    ~ exec s (grantAuto p a) s' ok.\nProof.\n  intros s s' p g a dangerousPerm groupedPerm notInGrantedGroups.\n  unfold not; intro execGrantAuto.\n  unfold exec in execGrantAuto.\n  destruct execGrantAuto as [_ [ok | notOk]].\n- destruct ok as [_ [preGrantAuto _]].\n  unfold pre, pre_grantAuto in preGrantAuto.\n  destruct preGrantAuto as [_ [_ [_ [_ existsPermGroup]]]].\n  destruct existsPermGroup as [g' [lGroup H]].\n  destruct H as [groupedPerm' [groupListOfA gInList]].\n  rewrite groupedPerm in groupedPerm'.\n  inversion groupedPerm' as [gEquals].\n  rewrite <- gEquals in gInList.\n  destruct notInGrantedGroups.\n  exists lGroup. auto.\n- destruct notOk as [ec [absurd _]].\n  inversion absurd.\nQed.\n\n\n(* Este teorema postula que una aplicaci\u00f3n vieja que no ha sido verificada por el usuario\n * no puede recibir intents. *)\nTheorem notVerifiedOldAppCantReceive :\n  forall (s s' : System) (i: Intent) (ic: iCmp) (a: idApp),\n    isOldApp a s -> (* La aplicaci\u00f3n es vieja *)\n    ~ (In a (alreadyVerified (state s))) -> (* y no est\u00e1 verificada*)\n    ~ exec s (receiveIntent i ic a) s' ok.\nProof.\n  intros s s' i ic a oldApp notVerified.\n  unfold not; intro receiveIntent.\n  unfold exec in receiveIntent.\n  destruct receiveIntent as [vs H].\n  destruct H.\n- destruct H as [_ [pre _]].\n  simpl in pre. unfold pre_receiveIntent in pre.\n  destruct pre as [H _].\n  unfold canRun, isOldApp in *.\n  destruct H.\n* contradiction.\n* destruct oldApp as [m [n [isM [target H1]]]]. \n  destruct H as [m' [n' [isM' [target' H2]]]].\n  assert (m=m').\n  apply (sameAppSameManifest s vs a); auto.\n  rewrite H in target.\n  rewrite target' in target.\n  inversion target.\n  rewrite H3 in H2.\n  assert (n<n).\n  apply (lt_trans n vulnerableSdk); auto.\n  apply lt_irrefl in H0; auto.\n- destruct H as [ec [H _]].\n  inversion H.\nQed.\n\n(* Este teorema demuestra que la operaci\u00f3n de borrar un grupo respeta la pol\u00edtica\n * de granularidad de Android y elimina todos los permisos correspondientes a ese\n * grupo que han sido otorgados individualmente. *)\nTheorem revokeGroupRevokesIndividualPerms :\n  forall (s s': System) (g: idGrp) (a: idApp),\n    exec s (Operaciones.revokePermGroup g a) s' ok ->\n    ~ (exists (p: Perm) (permsA: list Perm),\n        map_apply idApp_eq (perms (state s')) a = Value idApp permsA /\\ In p permsA /\\ maybeGrp p = Some g).\nProof.\n  intros s s' g a revoke.\n  unfold not; intro H.\n  destruct H as [p [permsA [H1 [H2 H3]]]].\n  unfold exec in revoke.\n  destruct revoke as [_ H].\n  destruct H.\n- destruct H as [_ [pre post]].\n  simpl in post. unfold post_revokeGroup in post.\n  destruct post as [_ [_ [postPerms _]]].\n  unfold revokeGroupedPerms in postPerms.\n  destruct postPerms as [_ [_ [H _]]].\n  destruct H as [permsA' [H4 H]].\n  rewrite H4 in H1. inversion H1.\n  rewrite H5 in H. apply H in H3.\n  contradiction.\n- destruct H as [ec [H _]].\n  inversion H.\nQed.\n\n(* Este teorema demuestra que cuando un permiso normal y uno peligroso comparten grupo, luego de instalar una aplcicaci\u00f3n que usa ambos,\n * el sistema queda en un estado en donde puede autom\u00e1ticamente otorgar el permiso peligroso, sin informar al usuario. *)\nTheorem DangerousPermissionAutoGranted : forall\n  (s s': System)\n  (a: idApp)\n  (m: Manifest)\n  (c: Cert)\n  (resources: list res)\n  (pDang pNorm : Perm)\n  (g: idGrp),\n  permExists pDang s'->\n  pl pDang = dangerous ->\n  pl pNorm = normal ->\n  In pNorm (use m) ->\n  In pDang (use m) ->\n  maybeGrp pNorm = Some g ->\n  maybeGrp pDang = Some g ->\n  exec s (install a m c resources) s' ok -> \n  pre_grantAuto pDang a s'.\nProof.\n  apply DangerousPermissionAutoGrantedProof.\nQed.\n\n\nEnd ModelProperties.\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/ModelProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.15857694096395208}}
{"text": "From stdpp Require Import finite vector.\nFrom trillium.prelude Require Import finitary classical quantifiers.\nFrom trillium.program_logic Require Import traces.\nFrom aneris.prelude Require Import misc.\nFrom aneris.prelude Require Import time.\nFrom aneris.aneris_lang Require Import state_interp adequacy.\nFrom aneris.aneris_lang Require Import tactics proofmode.\nFrom aneris.examples.gcounter_convergence Require Import\n     crdt_model crdt_resources crdt_runner vc.\nFrom trillium.traces Require Import trace_properties.\n\nImport InfListNotations.\n\nLocal Instance: \u2200 gcdata st st', ProofIrrel (GCounterM gcdata st st').\nProof. intros ?????; apply ProofIrrelevance. Qed.\n\nLemma GcounterM_rel_finitary gcdata : aneris_model_rel_finitary (GCounterM gcdata).\nProof.\n  intros st.\n  apply finite_smaller_card_nat.\n  apply (@in_list_finite\n            _ _ (\u03bb st', GCounterM gcdata st st') _\n            (all_crdt_states_smaller (GClen gcdata) (vmap S (max_vc st)))).\n  intros ? ?.\n  apply elem_of_all_crdt_states_smaller.\n  intros ?.\n  apply crdt_next_bounded; done.\nQed.\n\nDefinition oloc_less_defined (ol ol' : option loc) : Prop :=\n  match ol with\n  | Some l =>\n    match ol' with\n    | Some l' => l' = l\n    | None => False\n    end\n  | None => True\n  end.\n\nGlobal Instance oloc_less_defined_PO : PartialOrder oloc_less_defined.\nProof.\n  constructor; first constructor.\n  - intros []; split; auto.\n  - intros [] [] [] [] []; split; intros; simplify_eq/=; eauto.\n  - intros [] [] [] []; auto.\nQed.\n\nDefinition locs_less_defined (locs locs' : list (option loc)) : Prop :=\n  Forall2 oloc_less_defined locs locs'.\n\nLemma locs_less_defined_lookup locs locs' i :\n  locs_less_defined locs locs' \u2192 oloc_less_defined (locs !!! i) (locs' !!! i).\nProof.\n  rewrite /locs_less_defined Forall2_lookup.\n  intros Hlocs.\n  specialize (Hlocs i).\n  rewrite !list_lookup_total_alt.\n  destruct (locs !! i); destruct (locs' !! i); inversion Hlocs; simplify_eq; done.\nQed.\n\nGlobal Instance locs_less_defined_PO : PartialOrder locs_less_defined.\nProof.\n  constructor; first constructor.\n  - intros l; apply (_ : Reflexive (Forall2 _)).\n  - intros l1 l2 l3; apply (_ : Transitive (Forall2 _)).\n  - intros l1 l2; apply (_ : AntiSymm _ (Forall2 _)).\nQed.\n\nLemma locs_all_defined locs locs' :\n  locs_less_defined (Some <$> locs) locs' \u2192 locs' = (Some <$> locs).\n  intros Hld.\n  apply list_eq; intros i.\n  destruct (decide (i < length locs)) as [Hlt|Hnlt].\n  - destruct (lookup_lt_is_Some_2 locs i) as [l Hl]; first done.\n    destruct (lookup_lt_is_Some_2 locs' i) as [ol Hol].\n    { erewrite <- (Forall2_length); last apply Hld.\n      rewrite fmap_length; done. }\n    apply (locs_less_defined_lookup _ _ i) in Hld.\n    revert Hld.\n    rewrite list_lookup_fmap list_lookup_total_fmap //.\n    erewrite !list_lookup_total_correct; eauto.\n    intros Hld.\n    rewrite Hl Hol; simpl.\n    destruct ol; simplify_eq/=; done.\n  - rewrite list_lookup_fmap (lookup_ge_None_2 locs); last lia.\n    rewrite lookup_ge_None_2; first done.\n    erewrite <- (Forall2_length); last apply Hld.\n    rewrite fmap_length; lia.\nQed.\n\nSection crdt_main_rel.\n  Context (gcdata : GCData).\n\n  Implicit Types ex : execution_trace aneris_lang.\n  Implicit Types iex : inf_execution_trace aneris_lang.\n  Implicit Types atr : finite_trace (GCounterM gcdata) ().\n  Implicit Types iatr : inflist (() * GCounterM gcdata).\n\n  Notation ith_sa i := (gcd_addr_list gcdata !!! i).\n\n  Definition loc_of_trace_i (i : nat) (evs : event_obs aneris_lang) : option loc :=\n    match evs with\n    | [] => None\n    | ev :: evs' =>\n      match expr_e ev.(post_expr) with\n      | Val #(LitLoc l) => Some l\n      | _ => None\n      end\n    end.\n\n  Definition locs_of_trace_now (ex : execution_trace aneris_lang) : list (option loc) :=\n    (\u03bb i, loc_of_trace_i i (events_of_trace (allocEV (StringOfZ i)) ex) ) <$> seq 0 (GClen gcdata).\n\n  Fixpoint locs_of_trace (ex : execution_trace aneris_lang) : finite_trace (list (option loc)) () :=\n    match ex with\n    | trace_singleton _ => {tr[replicate (GClen gcdata) None]}\n    | trace_extend ex' _ c => (locs_of_trace ex') :tr[()]: (locs_of_trace_now ex)\n    end.\n\n  Lemma locs_of_trace_last ex :\n    trace_last (locs_of_trace ex) = locs_of_trace_now ex.\n  Proof.\n    destruct ex; last done.\n    rewrite /locs_of_trace_now.\n    rewrite (const_fmap _ _ None); first by rewrite seq_length.\n    intros ?; rewrite events_of_singleton_trace; done.\n  Qed.\n\n  Lemma locs_of_trace_now_length ex : length (locs_of_trace_now ex) = GClen gcdata.\n  Proof. rewrite /locs_of_trace fmap_length seq_length; done. Qed.\n\n  Lemma locs_of_trace_length ex : trace_forall (\u03bb tr, length tr = GClen gcdata) (locs_of_trace ex).\n  Proof.\n    induction ex as [|ex IHex c]; simpl in *.\n    - constructor. rewrite replicate_length //.\n    - constructor; first done. apply locs_of_trace_now_length.\n  Qed.\n\n  Lemma locs_of_trace_now_extend_less_defined ex c o\u03b6:\n    valid_exec (ex :tr[o\u03b6]: c) \u2192\n    locs_less_defined (locs_of_trace_now ex) (locs_of_trace_now (ex :tr[o\u03b6]: c)).\n  Proof.\n    intros Hvl.\n    apply Forall2_lookup; intros i.\n    destruct (decide (i < GClen gcdata)); last first.\n    { rewrite !lookup_ge_None_2; first by constructor.\n      - rewrite locs_of_trace_now_length; lia.\n      - rewrite locs_of_trace_now_length; lia. }\n    rewrite !list_lookup_fmap !lookup_seq_lt //=; [].\n    constructor.\n    destruct (events_of_trace_extend_app (allocEV (StringOfZ i)) ex c o\u03b6) as (evs & _ & Heq & _);\n      first done.\n    rewrite Heq.\n    destruct (events_of_trace (allocEV (StringOfZ i)) ex); reflexivity.\n  Qed.\n\n  Lemma locs_of_trace_less_defined ex :\n    valid_exec ex \u2192 trace_steps (\u03bb x _ y, locs_less_defined x y) (locs_of_trace ex).\n  Proof.\n    induction ex as [|ex IHex c]; simpl; first by constructor.\n    intros Hvl.\n    econstructor; [done| |by apply IHex; eapply valid_exec_exec_extend_inv; eauto].\n    rewrite locs_of_trace_last.\n    apply locs_of_trace_now_extend_less_defined; done.\n  Qed.\n\n  Lemma locs_of_trace_now_lookup_singleton i ex ip lbl l v \u03c3 h :\n    i < GClen gcdata \u2192\n    events_of_trace (allocEV (StringOfZ i)) ex = [allocObs ip lbl l v \u03c3 h] \u2192\n    locs_of_trace_now ex !! i = Some (Some l).\n  Proof.\n    intros Hi Hevs.\n    rewrite /locs_of_trace list_lookup_fmap lookup_seq_lt /=; last done.\n    rewrite /loc_of_trace_i Hevs; done.\n  Qed.\n\n  Lemma locs_of_trace_now_lookup_nil i ex :\n    i < GClen gcdata \u2192\n    events_of_trace (allocEV (StringOfZ i)) ex = [] \u2192\n    locs_of_trace_now ex !! i = Some None.\n  Proof.\n    intros Hi Hevs.\n    rewrite /locs_of_trace list_lookup_fmap lookup_seq_lt /=; last done.\n    rewrite /loc_of_trace_i Hevs; done.\n  Qed.\n\n  Definition valid_model_fin_trace (mtr : finite_trace (GCounterM gcdata) ()) : Prop :=\n    trace_forall valid_crdt_state mtr \u2227 trace_steps (\u03bb st _ st', st = st' \u2228 CrdtNext st tt st') mtr.\n\n  Definition gcounter_values_related_now (lcs : (list (option loc)))\n             (c : cfg aneris_lang) (\u03b4 : GCounterM gcdata) : Prop :=\n    \u2200 i : fin (GClen gcdata),\n       match lcs !!! (fin_to_nat i) with\n       | Some l =>\n         \u2203 h, c.2.(state_heaps) !! (ip_of_address (ith_sa (fin_to_nat i))) = Some h \u2227\n              h !! l = Some (vector_clock_to_val (vec_to_list (\u03b4 !!! i)))\n       | None => \u03b4 !!! i = vreplicate (GClen gcdata) 0\n       end.\n\n  Definition gcounter_values_related (locs : finite_trace (list (option loc)) ())\n             (ex : execution_trace aneris_lang) (mtr : finite_trace (GCounterM gcdata) ()) : Prop :=\n    trace_forall3 gcounter_values_related_now locs ex mtr.\n\n  Definition gcounter_values_related_now_locs_resolved (lcs : (list loc))\n             (c : cfg aneris_lang) (\u03b4 : GCounterM gcdata) : Prop :=\n    \u2200 i : fin (GClen gcdata),\n      \u2203 h, c.2.(state_heaps) !! (ip_of_address (ith_sa (fin_to_nat i))) = Some h \u2227\n           h !! (lcs !!! (fin_to_nat i)) = Some (vector_clock_to_val (vec_to_list (\u03b4 !!! i))).\n\n  Lemma gcounter_values_related_now_resolve_locs locs c \u03b4 :\n    length locs = GClen gcdata \u2192\n    gcounter_values_related_now (Some <$> locs) c \u03b4 \u2192\n    gcounter_values_related_now_locs_resolved locs c \u03b4.\n  Proof.\n    intros Hlen Hvrel i.\n    specialize (Hvrel i).\n    rewrite list_lookup_total_fmap in Hvrel; [done|by rewrite Hlen; apply fin_to_nat_lt].\n  Qed.\n\n  Definition gcounter_monotone (locs : finite_trace (list (option loc)) ())\n             (ex : execution_trace aneris_lang) : Prop :=\n    trace_steps2\n       (\u03bb lcs c _ _ lcs' c',\n          \u2200 i, i < GClen gcdata \u2192\n               match lcs !!! i with\n               | Some l =>\n                 match lcs' !!! i with\n                 | Some l' =>\n                   l' = l \u2227\n                   \u2203 h h' (vc vc' : vector_clock (GClen gcdata)),\n                      c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h \u2227\n                      c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' \u2227\n                      h !! l = Some (vector_clock_to_val vc) \u2227\n                      h' !! l = Some (vector_clock_to_val vc') \u2227\n                      vc_le vc vc'\n                 | None => False\n                 end\n               | None => True\n               end) locs ex.\n\n  Definition gcounter_monotone_configs (lcs : list loc) (c c' : cfg aneris_lang) : Prop :=\n    c = c' \u2228\n    \u2200 i, i < GClen gcdata \u2192\n         \u2203 h h' (vc vc' : vector_clock (GClen gcdata)),\n            c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h \u2227\n            c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' \u2227\n            h !! (lcs !!! i) = Some (vector_clock_to_val vc) \u2227\n                 h' !! (lcs !!! i) = Some (vector_clock_to_val vc') \u2227\n                 vc_le vc vc'.\n\n  Lemma gcounter_monotone_configs_vc_le lcs i c c' h h' (vc vc' : vector_clock (GClen gcdata)) :\n    i < GClen gcdata \u2192\n    gcounter_monotone_configs lcs c c' \u2192\n    c.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h \u2192\n    c'.2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h' \u2192\n    h !! (lcs !!! i) = Some (vector_clock_to_val (vec_to_list vc)) \u2192\n    h' !! (lcs !!! i) = Some (vector_clock_to_val (vec_to_list vc')) \u2192\n    vc_le vc vc'.\n  Proof.\n    intros Hi Hgmc Hh Hh' Hvc Hvc'.\n    destruct Hgmc as [<-|Hgmc].\n    { simplify_eq.\n      match goal with\n      | Heq :  _ =  _ |- _ =>\n        apply vec_to_list_inj2 in Heq; simplify_eq; done\n      end. }\n    specialize (Hgmc i Hi) as (?&?&?&?&?&?&?&?&?); simplify_eq.\n    repeat\n       match goal with\n       | Heq :  _ =  _ |- _ =>\n         apply vec_to_list_inj2 in Heq; simplify_eq\n       end; done.\n  Qed.\n\n  Global Instance gcounter_monotone_configs_PreOrder lcs : PreOrder (gcounter_monotone_configs lcs).\n  Proof.\n    split.\n    - by left.\n    - intros c1 c2 c3 Hc12 Hc23.\n      destruct Hc12 as [->|Hc12]; first done.\n      destruct Hc23 as [<-|Hc23]; first by right.\n      right.\n      intros i Hi.\n      destruct (Hc12 i Hi) as (h1&h2&vc1&vc2&?&?&?&?&?).\n      destruct (Hc23 i Hi) as (h2'&h3&vc2'&vc3&?&?&?&?&?).\n      simplify_eq/=.\n      match goal with\n       | Heq : _ =  _ |- _ =>\n         apply vec_to_list_inj2 in Heq; simplify_eq\n      end.\n      eexists h1, h3, vc1, vc3; split_and!; [by eauto|by eauto|done|done|etrans; eauto].\n  Qed.\n\n  Definition gcounter_monotone_locs_resolved_simple\n             (lcs : list loc) (l : list (cfg aneris_lang)) : Prop :=\n    \u2200 i c1 c2, l !! i = Some c1 \u2192 l !! (S i) = Some c2 \u2192 gcounter_monotone_configs lcs c1 c2.\n\n  Definition gcounter_monotone_locs_resolved (lcs : list loc) (l : list (cfg aneris_lang)) : Prop :=\n    \u2200 i j c1 c2, i \u2264 j \u2192 l !! i = Some c1 \u2192 l !! j = Some c2 \u2192 gcounter_monotone_configs lcs c1 c2.\n\n  Lemma gcounter_monotone_locs_resolved_if_simple lcs l :\n    gcounter_monotone_locs_resolved_simple lcs l \u2192 gcounter_monotone_locs_resolved lcs l.\n  Proof.\n    intros Hgms i j c1 c2 Hij Hi Hj.\n    apply Nat.le_sum in Hij as [k Hk].\n    revert i j Hk c1 c2 Hi Hj.\n    induction k as [|k IHk]; intros i j Hk c1 c2 Hi Hj.\n    { assert (j = i) by lia; clear Hk; simplify_eq; reflexivity. }\n    destruct (lookup_lt_is_Some_2 l (i + k)) as [c Hc].\n    { apply lookup_lt_Some in Hj; lia. }\n    etrans; first by apply (IHk i (i + k) eq_refl c1 c); auto.\n    replace j with (S (i + k)) in Hj by lia.\n    eapply Hgms; eauto.\n  Qed.\n\n  Lemma gcounter_monotone_resolve_locs lcs ex il l :\n    length il = length l \u2192\n    length lcs = GClen gcdata \u2192\n    valid_exec (ex +trl+ l) \u2192\n    trace_last (locs_of_trace ex) = (Some <$> lcs) \u2192\n    trace_steps (\u03bb x _ y, locs_less_defined x y) (locs_of_trace ex +trl+ il) \u2192\n    gcounter_monotone (locs_of_trace ex +trl+ il) (ex +trl+ l) \u2192\n    gcounter_monotone_locs_resolved lcs (trace_last ex :: map snd l).\n  Proof.\n    intros Hlen Hlcs Hvl Hld Hldl Hgms.\n    apply gcounter_monotone_locs_resolved_if_simple.\n    revert il Hlen Hvl Hld Hldl Hgms; induction l as [|[o\u03b6 c] l IHl] using rev_ind;\n      intros il Hlen Hvl Hld Hldl Hgms.\n    { intros i j c1 c2; rewrite list_lookup_singleton; done. }\n    intros i c1 c2 Hi HSi.\n    destruct il as [|[[] locs] il _] using rev_ind.\n    { rewrite app_length /= in Hlen; lia. }\n    rewrite -!trace_append_list_assoc /= in Hvl, Hgms, Hldl.\n    assert (i < S (length l)).\n    { cut (S i < length (trace_last ex :: map snd l ++ [c])).\n      - rewrite /= app_length map_length /=; lia.\n      - apply lookup_lt_is_Some_1; eauto.\n        rewrite map_app in HSi. rewrite HSi; eauto. }\n    rewrite map_app (lookup_app_l (_ :: _)) in Hi; last first.\n    { list_simplifier. rewrite map_length //. }\n    destruct (decide (i < length l)) as [Hlt|Hnlt].\n    - rewrite /= map_app lookup_app_l in HSi; last by rewrite map_length.\n      eapply (IHl il); [rewrite !app_length /= in Hlen| |done| | |by eauto|by eauto].\n      + rewrite !Nat.add_1_r in Hlen. by injection Hlen.\n      + eapply valid_exec_exec_extend_inv; eauto.\n      + eapply trace_steps_step_inv in Hldl as [? ?]; done.\n      + eapply trace_steps2_step_inv in Hgms as [? ?]; done.\n    - assert (i = length l) as HSieq by lia.\n      rewrite HSieq in HSi.\n      rewrite map_app (lookup_app_r (_ :: _)) in HSi; last by rewrite /= map_length.\n      rewrite /= map_length Nat.sub_diag in HSi; simplify_eq/=.\n      apply trace_steps2_step_inv in Hgms as [_ Hgms].\n      destruct Hgms as (? & ? & ?%last_eq_trace_ends_in & ?%last_eq_trace_ends_in & Hgms).\n      simplify_eq.\n      destruct l as [|[? c'] l _] using rev_ind.\n      + assert (length il = 0) by by rewrite app_length /= in Hlen; lia.\n        destruct il; last done.\n        simplify_eq/=.\n        rewrite Hld in Hgms.\n        right; intros i Hi.\n        specialize (Hgms i Hi).\n        rewrite list_lookup_total_fmap in Hgms; last lia.\n        destruct (locs !!! i); last done.\n        destruct Hgms as [-> Hgms]; done.\n      + rewrite -!trace_append_list_assoc /= in Hgms.\n        rewrite app_length /= in Hi.\n        rewrite map_app (lookup_app_r (_ ::_)) in Hi; last by rewrite /= map_length; lia.\n        rewrite /= in Hi.\n        replace (length l + 1 - S (length l)) with 0 in Hi by lia.\n        simplify_eq/=.\n        apply valid_exec_exec_extend_inv in Hvl as [Hvl _].\n        apply locs_of_trace_less_defined in Hvl.\n        apply trace_steps_step_inv in Hldl as [Hldl _].\n        eapply trace_append_list_steps_rtc_nl in Hldl;\n          [|apply trace_ends_in_last|apply trace_ends_in_last].\n        revert Hldl; rewrite rt_rtc_same Hld; intros Hldl.\n        right. intros i Hilen.\n        apply (locs_less_defined_lookup _ _ i) in Hldl.\n        rewrite list_lookup_total_fmap in Hldl; last lia.\n        specialize (Hgms i Hilen).\n        destruct (trace_last (locs_of_trace ex +trl+ il) !!! i) as [ol'|]; last done.\n        simplify_eq/=.\n        destruct (locs !!! i); last done.\n        destruct Hgms as (-> & Hgms).\n        by list_simplifier.\n  Qed.\n\n  Definition send_evs_rel (locs : list (option loc)) (ex : execution_trace aneris_lang) : Prop :=\n    \u2203 sevss,\n       length sevss = GClen gcdata \u2227\n       \u2200 i, i < GClen gcdata \u2192\n            \u2203 sevs,\n               sevss !! i = Some sevs \u2227\n               sendevs_valid sevs \u2227\n               match locs !!! i with\n               | Some l =>\n                 Forall2\n                    (@send_events_correspond gcdata (ith_sa i) l)\n                    (events_of_trace (sendonEV (ith_sa i)) ex)\n                    sevs\n               | None => events_of_trace (sendonEV (ith_sa i)) ex = [] \u2227 sevs = []\n               end.\n\n  Definition send_evs_rel_locs_resolved\n             (locs : list loc) (ex : execution_trace aneris_lang) : Prop :=\n    \u2203 sevss,\n       length sevss = GClen gcdata \u2227\n       \u2200 i, i < GClen gcdata \u2192\n            \u2203 sevs,\n               sevss !! i = Some sevs \u2227\n               sendevs_valid sevs \u2227\n               Forall2\n                  (@send_events_correspond gcdata (ith_sa i) (locs !!! i))\n                  (events_of_trace (sendonEV (ith_sa i)) ex)\n                  sevs.\n\n  Lemma send_evs_rel_resolve_locs locs ex :\n    length locs = GClen gcdata \u2192\n    send_evs_rel (Some <$> locs) ex \u2192\n    send_evs_rel_locs_resolved locs ex.\n  Proof.\n    intros Hlen [sevss [? Hsevs]].\n    exists sevss; split; first done.\n    intros i Hi.\n    specialize (Hsevs i Hi).\n    setoid_rewrite list_lookup_total_fmap in Hsevs; [eauto|lia].\n  Qed.\n\n\n  Definition receive_evs_rel (locs : list (option loc)) (ex : execution_trace aneris_lang) : Prop :=\n    \u2203 revss,\n       length revss = GClen gcdata \u2227\n       \u2200 i, i < GClen gcdata \u2192\n            \u2203 revs,\n               revss !! i = Some revs \u2227\n               match locs !!! i with\n               | Some l =>\n                 Forall2 (rec_events_correspond (ith_sa i))\n                         (events_of_trace (receiveonEV (ith_sa i)) ex) revs \u2227\n                 \u2203 h (vc : vector_clock (GClen gcdata)),\n                    (trace_last ex).2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h \u2227\n                    h !! l = Some (vector_clock_to_val vc) \u2227\n                 forall j rev, S j < length revs \u2192 revs !! j = Some rev \u2192 vc_le rev vc\n               | None => events_of_trace (receiveonEV (ith_sa i)) ex = [] \u2227 revs = []\n               end.\n\n  Definition receive_evs_rel_locs_resolved\n             (locs : list loc) (ex : execution_trace aneris_lang) : Prop :=\n    \u2203 revss,\n       length revss = GClen gcdata \u2227\n       \u2200 i, i < GClen gcdata \u2192\n            \u2203 revs,\n               revss !! i = Some revs \u2227\n               Forall2 (rec_events_correspond (ith_sa i))\n                         (events_of_trace (receiveonEV (ith_sa i)) ex) revs \u2227\n               \u2203 h (vc : vector_clock (GClen gcdata)),\n                  (trace_last ex).2.(state_heaps) !! (ip_of_address (ith_sa i)) = Some h \u2227\n                  h !! (locs !!! i) = Some (vector_clock_to_val vc) \u2227\n                  forall j rev, S j < length revs \u2192 revs !! j = Some rev \u2192 vc_le rev vc.\n\n  Lemma receive_evs_rel_resolve_locs locs ex :\n    length locs = GClen gcdata \u2192\n    receive_evs_rel (Some <$> locs) ex \u2192\n    receive_evs_rel_locs_resolved locs ex.\n  Proof.\n    intros Hlen [revss [? Hrevs]].\n    exists revss; split; first done.\n    intros i Hi.\n    specialize (Hrevs i Hi).\n    setoid_rewrite list_lookup_total_fmap in Hrevs; [eauto|lia].\n  Qed.\n\n  Definition crdt_main_rel (ex: execution_trace aneris_lang)\n             (mtr : auxiliary_trace (aneris_to_trace_model (GCounterM gcdata))) : Prop :=\n    valid_system_trace ex mtr \u2227\n    valid_model_fin_trace mtr \u2227\n    gcounter_values_related (locs_of_trace ex) ex mtr \u2227\n    send_evs_rel (trace_last (locs_of_trace ex)) ex \u2227\n    receive_evs_rel (trace_last (locs_of_trace ex)) ex.\n\n  Lemma crdt_main_rel_monotone ex mtr :\n    crdt_main_rel ex mtr \u2192 gcounter_monotone (locs_of_trace ex) ex.\n  Proof.\n    intros (Hvl & Hmvl & Hvrel & _).\n    revert mtr Hvl Hmvl Hvrel.\n    induction ex as [|ex IHex c]; simpl;\n      intros mtr Hvl Hmvl Hvrel; first by apply trace_steps2_singleton.\n    econstructor; [done|done| |]; last first.\n    { apply trace_forall3_extend_inv_l in Hvrel as (? & ? & ? & mtr' & ? & [] & ? & ? & ? & ?); simplify_eq.\n      inversion Hvl; simplify_eq.\n      eapply IHex.\n      - done.\n      - destruct Hmvl as [[? ?]%trace_forall_extend_inv [? [??]]%trace_steps_step_inv]; done.\n      - by eauto. }\n    apply trace_forall3_extend_inv_l in Hvrel as (c' & ex' & st & mtr' & o\u03b6 & ? & ? & ? & Hrel1 & Hrel2);\n      simplify_eq/=.\n    apply trace_forall3_last in Hrel1.\n    intros i Hi.\n    specialize (Hrel1 (nat_to_fin Hi)).\n    specialize (Hrel2 (nat_to_fin Hi)).\n    rewrite locs_of_trace_last in Hrel1.\n    rewrite locs_of_trace_last.\n    rewrite !fin_to_nat_to_fin in Hrel1, Hrel2.\n    eapply valid_system_trace_valid_exec_trace in Hvl.\n    destruct (locs_of_trace_now (ex' :tr[ o\u03b6 ]: c') !!! i) eqn:Heq; last first.\n    { pose proof (locs_of_trace_now_extend_less_defined ex' c' _ Hvl) as Hld.\n      apply (locs_less_defined_lookup _ _ i) in Hld.\n      rewrite Heq in Hld.\n      destruct (locs_of_trace_now ex' !!! i); done. }\n    pose proof (locs_of_trace_now_extend_less_defined ex' c' _ Hvl) as Hld.\n    apply (locs_less_defined_lookup _ _ i) in Hld.\n    rewrite Heq in Hld.\n    destruct (locs_of_trace_now ex' !!! i); simplify_eq/=; last done.\n    split; first done.\n    destruct Hrel1 as (h & Hh1 & Hh2).\n    destruct Hrel2 as (h' & Hh'1 & Hh'2).\n    eexists _, _, _, _; split_and!; [by eauto|by eauto|by eauto|by eauto|].\n    destruct Hmvl as [_ Hmvl].\n    apply trace_steps_step_inv in Hmvl as [_ (st' & -> & [->|Hmvl])]; first done.\n    apply crdt_next_vc_le; done.\n  Qed.\n\n  Lemma crdt_main_rel_initially (ps : programs_using_gcounters gcdata) v :\n    crdt_main_rel\n       {tr[ ([{| expr_n := \"system\"; expr_e := runner gcdata 0 (progs ps) v |}],\n             init_state) ]}\n       {tr[ initial_crdt_state (GClen gcdata) ]}.\n  Proof.\n    rewrite /crdt_main_rel /=; split_and!.\n    - constructor.\n    - repeat constructor. apply valid_initial_crdt_state.\n    - constructor; intros i.\n      rewrite lookup_total_replicate_2; last by apply fin_to_nat_lt.\n      rewrite vlookup_replicate; done.\n    - exists (replicate (length (gcd_addr_list gcdata)) []).\n      split; first by rewrite replicate_length.\n      intros i Hi.\n      exists []; split; first by rewrite lookup_replicate_2.\n      split.\n      { intros ????; rewrite lookup_nil; done. }\n      rewrite lookup_total_replicate_2; last done.\n      rewrite events_of_singleton_trace; done.\n    - exists (replicate (length (gcd_addr_list gcdata)) []).\n      split; first by rewrite replicate_length.\n      intros i Hi.\n      exists []; split; first by rewrite lookup_replicate_2.\n      rewrite lookup_total_replicate_2; last done.\n      rewrite events_of_singleton_trace; done.\n  Qed.\n\n  Lemma crdt_main_rel_step (ps : programs_using_gcounters gcdata) v ex\n        (atr atr': auxiliary_trace (aneris_to_trace_model (GCounterM gcdata))) ex' o\u03b6 \u2113:\n    valid_system_trace ex atr \u2192\n    trace_contract ex o\u03b6 ex' \u2192\n    trace_contract atr \u2113 atr' \u2192\n    crdt_main_rel ex' atr' \u2192\n    trace_starts_in ex\n      ([{| expr_n := \"system\"; expr_e := runner gcdata 0 (progs ps) v |}], init_state) \u2192\n    trace_starts_in atr (initial_crdt_state (GClen gcdata)) \u2192\n    valid_state_evolution (ex' :tr[o\u03b6]: trace_last ex) (atr' :tr[\u2113]: trace_last atr) \u2192\n    (\u2200 i : fin (length (gcd_addr_list gcdata)),\n      match locs_of_trace_now ex !!! (fin_to_nat i) with\n      | Some l =>\n        \u2203 h : heap,\n          (trace_last ex).2.(state_heaps) !! ip_of_address (ith_sa (fin_to_nat i)) = Some h \u2227\n          h !! l = Some (vector_clock_to_val (vec_to_list ((trace_last atr) !!! i)))\n      | None => (trace_last atr) !!! i = vreplicate (length (gcd_addr_list gcdata)) 0\n     end) \u2192\n    send_evs_rel (locs_of_trace_now ex) ex \u2192\n    receive_evs_rel (locs_of_trace_now ex) ex \u2192\n    crdt_main_rel ex atr.\n  Proof.\n    intros Hvls [c ->] [\u03b4 ->] Hmrel Hex's Hatr's Hvse Hstrel Hsevsrel Hrevsrel; simpl in *.\n    rewrite /crdt_main_rel /=; split_and!.\n    - done.\n    - split.\n      + constructor; first by apply Hmrel.\n        destruct Hmrel as (_ & [Hvst _] & _).\n        apply trace_forall_last in Hvst.\n        destruct Hvse as [<-|]; first done.\n        eapply CrdtNext_preserves_validity; done.\n      + destruct Hmrel as (_ & [_ Hststep] & _).\n        econstructor; [done | | done].\n        destruct Hvse as [<-|]; by auto.\n    - constructor; [by apply Hmrel|done].\n    - done.\n    - done.\n  Qed.\n\n  CoFixpoint locs_of_inf_trace\n             (ex : execution_trace aneris_lang)\n             (iex: inf_execution_trace aneris_lang) : inflist (() * list (option loc)) :=\n    match iex with\n    | []%inflist => []\n    | ((o\u03b6, c) :: iex')%inflist =>\n      (tt, (locs_of_trace_now (ex :tr[o\u03b6]: c))) :: locs_of_inf_trace (ex :tr[o\u03b6]: c) iex'\n    end.\n\n  Lemma locs_of_inf_trace_take ex iex n :\n    ((locs_of_trace ex) +trl+ (inflist_take n (locs_of_inf_trace ex iex))) =\n    locs_of_trace (ex +trl+ (inflist_take n iex)).\n  Proof.\n    revert ex iex; induction n as [|n IHn]; intros ex iex; simpl; first done.\n    destruct iex as [|[??]?]; simpl; first done.\n    rewrite -IHn; done.\n  Qed.\n\n  Lemma locs_of_inf_trace_length ex iex : inflist_same_length (locs_of_inf_trace ex iex) iex.\n  Proof.\n    intros n.\n    revert ex iex.\n    induction n; simpl; intros ex iex.\n    - rewrite (inflist_unfold_fold (locs_of_inf_trace ex iex)).\n      destruct iex as [|[??]?]; simpl; done.\n    - destruct iex as [|[??]?]; done.\n  Qed.\n\n  Lemma locs_of_inf_trace_cons_inv ex iex lcs ilocs:\n    locs_of_inf_trace ex iex = (lcs :: ilocs)%inflist \u2192\n    \u2203 o\u03b6 c iex',\n       iex = ((o\u03b6, c):: iex')%inflist \u2227\n       lcs = (tt, locs_of_trace_now (ex :tr[o\u03b6]: c)) \u2227\n       ilocs = locs_of_inf_trace (ex :tr[o\u03b6]: c) iex'.\n  Proof.\n    rewrite (inflist_unfold_fold (locs_of_inf_trace ex iex)).\n    destruct iex as [|[??]?]; simpl; first done.\n    intros; simplify_eq; eauto 10.\n  Qed.\n\n  Lemma locs_of_inf_trace_less_defined ex iex :\n    valid_inf_exec ex iex \u2192\n    always\n       (\u03bb locs ilocs, trace_steps (\u03bb x _ y, locs_less_defined x y) locs)\n       (locs_of_trace ex) (locs_of_inf_trace ex iex).\n  Proof.\n    intros Hvex.\n    apply always_take_drop; intros n.\n    rewrite locs_of_inf_trace_take.\n    apply locs_of_trace_less_defined.\n    eapply valid_inf_exe_valid_exec.\n    apply valid_inf_exe_take_drop; done.\n  Qed.\n\n  Definition crdt_main_rel_ternary\n             (locs : finite_trace (list (option loc)) ()) (ex: execution_trace aneris_lang)\n             (mtr : auxiliary_trace (aneris_to_trace_model (GCounterM gcdata)))\n             (ilocs : inflist (() * list (option loc))) (iex: inf_execution_trace aneris_lang)\n             (imtr : inflist (() * GCounterM gcdata)) : Prop :=\n    valid_system_trace ex mtr \u2227\n    valid_model_fin_trace mtr \u2227\n    gcounter_values_related locs ex mtr \u2227\n    send_evs_rel (trace_last locs) ex \u2227\n    receive_evs_rel (trace_last locs) ex.\n\n  Lemma crdt_main_rel_ternary_crdt_main_rel ex mtr ilocs iex imtr :\n    crdt_main_rel_ternary (locs_of_trace ex) ex mtr ilocs iex imtr \u2192 crdt_main_rel ex mtr.\n  Proof. intros (?&?&?&?&?); split_and!; done. Qed.\n\n  (* move *)\n  Lemma valid_inf_system_trace_take_drop n\n        {\u039b : language} {M} (\u03c6 : execution_trace \u039b \u2192 auxiliary_trace M \u2192 Prop)\n        (ex : execution_trace \u039b) (atr : auxiliary_trace M)\n        (iex : inf_execution_trace \u039b) (iatr : inf_auxiliary_trace M) :\n    valid_inf_system_trace \u03c6 ex atr iex iatr \u2192\n    valid_inf_system_trace \u03c6\n      (ex +trl+ inflist_take n iex) (atr +trl+ inflist_take n iatr)\n      (inflist_drop n iex) (inflist_drop n iatr).\n  Proof.\n    revert ex atr iex iatr.\n    induction n as [|n IHn]; first done.\n    intros ex atr iex iatr Hvisf.\n    inversion Hvisf; simplify_eq/=; first done.\n    apply IHn; done.\n  Qed.\n  Lemma valid_inf_system_trace_length\n        {\u039b : language} {M} (\u03c6 : execution_trace \u039b \u2192 auxiliary_trace M \u2192 Prop)\n        (ex : execution_trace \u039b) (atr : auxiliary_trace M)\n        (iex : inf_execution_trace \u039b) (iatr : inf_auxiliary_trace M) :\n    valid_inf_system_trace \u03c6 ex atr iex iatr \u2192 inflist_same_length iex iatr.\n  Proof.\n    intros Hvisf n.\n    apply (valid_inf_system_trace_take_drop n) in Hvisf.\n    inversion Hvisf; simplify_eq/=; done.\n  Qed.\n  Lemma valid_inf_system_trace_mono\n        {\u039b : language} {M} (\u03c6 \u03c8 : execution_trace \u039b \u2192 auxiliary_trace M \u2192 Prop)\n        (ex : execution_trace \u039b) (atr : auxiliary_trace M)\n        (iex : inf_execution_trace \u039b) (iatr : inf_auxiliary_trace M) :\n    (\u2200 (ex' : execution_trace \u039b) (atr' : auxiliary_trace M), \u03c6 ex' atr' \u2192 \u03c8 ex' atr') \u2192\n    valid_inf_system_trace \u03c6 ex atr iex iatr \u2192 valid_inf_system_trace \u03c8 ex atr iex iatr.\n  Proof.\n    revert ex atr iex iatr; cofix IH; intros ex atr iex iatr H\u03c6\u03c8 H\u03c6.\n    inversion H\u03c6; simplify_eq.\n    - constructor; apply H\u03c6\u03c8; done.\n    - econstructor; eauto.\n  Qed.\n  Lemma valid_inf_system_trace_rel\n        {\u039b : language} {M} (\u03c6 : execution_trace \u039b \u2192 auxiliary_trace M \u2192 Prop)\n        (ex : execution_trace \u039b) (atr : auxiliary_trace M)\n        (iex : inf_execution_trace \u039b) (iatr : inf_auxiliary_trace M) :\n    valid_inf_system_trace \u03c6 ex atr iex iatr \u2192 \u03c6 ex atr.\n  Proof. inversion 1; done. Qed.\n\n  Lemma crdt_main_rel_always_ternary\n        (ex : execution_trace aneris_lang) (iex : inf_execution_trace aneris_lang)\n        (atr : auxiliary_trace (aneris_to_trace_model (GCounterM gcdata))) :\n    valid_inf_exec ex iex \u2192\n    continued_simulation crdt_main_rel ex atr \u2192\n    \u2203 imtr,\n       always3\n          crdt_main_rel_ternary\n          (locs_of_trace ex) ex atr (locs_of_inf_trace ex iex) iex imtr.\n  Proof.\n    intros Hvl Hcs.\n    specialize (continued_simulation_rel _ _ _ Hcs) as (Hst & _ & _ & _).\n    pose proof (produced_inf_aux_trace_valid_inf _ _  _ Hst Hcs iex Hvl) as Hvisf.\n    clear Hst.\n    exists (produce_inf_aux_trace _ ex atr Hcs iex Hvl).\n    pose proof (valid_inf_system_trace_length _ _ _ _ _ Hvisf) as Hlen.\n    apply (valid_inf_system_trace_mono _ crdt_main_rel) in Hvisf; last first.\n    { apply continued_simulation_rel. }\n    revert Hlen Hvisf.\n    generalize (produce_inf_aux_trace _ ex atr Hcs iex Hvl); intros iatr.\n    clear Hcs.\n    revert ex iex atr iatr Hvl.\n    cofix IH; intros ex iex atr iatr Hvl Hlen Hvisf.\n    constructor; [| | |].\n    - apply valid_inf_system_trace_rel in Hvisf; done.\n    - apply locs_of_inf_trace_length.\n    - eapply inflist_same_length_trans; done.\n    - simpl.\n      intros ?????????\n             (?&?&?&?&?&?)%locs_of_inf_trace_cons_inv\n             -> ->; simplify_eq.\n      apply (IH (_ :tr[_]: _)).\n      + apply traces.valid_inf_exec_adjust; done.\n      + rewrite -inflist_same_length_cons; done.\n      + apply (valid_inf_system_trace_take_drop 1) in Hvisf; done.\n  Qed.\n\n  Lemma eventually_sent_eventually_exists_loc_one i ex iex mtr imtr :\n    i < GClen gcdata \u2192\n    valid_inf_exec ex iex \u2192\n    eventually (\u03bb ex' _, events_of_trace (sendonEV (ith_sa i)) ex' \u2260 []) ex iex \u2192\n    always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr \u2192\n    eventually3\n       (always3 (\u03bb locs _ _ _ _ _, \u2203 l, (trace_last locs) !! i = Some (Some l)))\n       (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n  Proof.\n    intros Hi Hvex Hev Hal.\n    apply eventually_take_drop in Hev as [n Hev].\n    assert ((always (\u03bb ex' _, events_of_trace (sendonEV (ith_sa i)) ex' \u2260 []))\n               (ex +trl+ inflist_take n iex) (inflist_drop n iex)) as Hev'.\n    { apply always_take_drop; intros k.\n      destruct (events_of_trace_app\n                   (sendonEV (ith_sa i))\n                   (ex +trl+ inflist_take n iex)\n                   (inflist_take k (inflist_drop n iex))) as (evs & ? & -> & _).\n      { rewrite trace_append_list_assoc -inflist_take_add.\n        eapply valid_inf_exe_valid_exec; eapply valid_inf_exe_take_drop; done. }\n      intros []%app_eq_nil; simplify_eq. }\n    clear Hev.\n    apply eventually3_take_drop; exists n.\n    split; last by eapply always3_inflist_same_length; eauto.\n    apply (always3_unroll_n _ n) in Hal.\n    apply always3_take_drop; intros k.\n    split; last by eapply always3_inflist_same_length; eauto.\n    apply (always3_unroll_n _ k), always3_holds in Hal.\n    apply (always_unroll_n _ k), always_holds in Hev'.\n    revert Hal Hev'.\n    rewrite !trace_append_list_assoc -!inflist_take_add.\n    intros Hal Hev.\n    destruct Hal as (_&_&_& (sevss & Hlen & Hsevs) &_).\n    specialize (Hsevs i Hi) as (sevs & ? & ? & Hlocs).\n    rewrite list_lookup_total_alt in Hlocs.\n    revert Hlocs.\n    rewrite locs_of_inf_trace_take locs_of_trace_last.\n    destruct (lookup_lt_is_Some_2 (locs_of_trace_now (ex +trl+ inflist_take (n + k) iex)) i)\n      as [ol Hol].\n    { rewrite locs_of_trace_now_length; done. }\n    rewrite Hol; simpl.\n    destruct ol; first by eauto.\n    intros [? ?]; simplify_eq.\n  Qed.\n\n  Lemma eventually_sent_eventually_exists_loc_all ex iex mtr imtr :\n    (\u2200 i, i < GClen gcdata \u2192\n          eventually (\u03bb ex' _, events_of_trace (sendonEV (ith_sa i)) ex' \u2260 []) ex iex) \u2192\n    valid_inf_exec ex iex \u2192\n    always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr \u2192\n    eventually3\n       (\u03bb locs ex' mtr' ilocs' iex' imtr',\n          \u2200 (j : fin (S (GClen gcdata))),\n             always3 (\u03bb locs' ex'' mtr'' ilocs'' iex'' imtr'',\n                      match fin_to_nat j with\n                      | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n                      | S k => \u2203 l, (trace_last locs') !! k = Some (Some l)\n                      end) locs ex' mtr' ilocs' iex' imtr')\n       (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n  Proof.\n    intros Hev Hvex Hal.\n    apply eventually3_forall_combine.\n    intros j.\n    destruct (fin_to_nat j) as [|j'] eqn:Hj'.\n    - pose proof (always3_inflist_same_length _ _ _ _ _ _ _ Hal) as [? ?].\n      apply holds_eventually3; done.\n    - assert (j' < GClen gcdata).\n      { assert (S j' < S (GClen gcdata)) by by rewrite -Hj'; apply fin_to_nat_lt. lia. }\n      apply eventually_sent_eventually_exists_loc_one; auto.\n  Qed.\n\n  Lemma eventually_sent_eventually_allocated_helper len locs ex mtr ilocs iex imtr :\n  (\u2200 j : fin (S len),\n     always3\n       (\u03bb locs' ex'' mtr'' ilocs'' iex'' imtr'',\n          match fin_to_nat j with\n          | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n          | S k => \u2203 l : loc, trace_last locs' !! k = Some (Some l)\n        end) locs ex mtr ilocs iex imtr) \u2192\n  \u2203 lcssg : {lcs : list loc | length lcs = len},\n     take len (trace_last locs) = Some <$> `lcssg \u2227\n     always3 crdt_main_rel_ternary locs ex mtr ilocs iex imtr.\n  Proof.\n    intros Hex.\n    induction len as [|n IHn].\n    - exists (exist (\u03bb l, length l = 0) (@nil loc) eq_refl).\n      rewrite take_0 /=.\n      split; first done.\n      specialize (Hex 0%fin); done.\n    - destruct IHn as [[lcs Hlcslen] [Hlcs1 Hlcs2]].\n      { intros j.\n        assert (fin_to_nat j < S (S n)) as Hlt.\n        { etrans; first apply fin_to_nat_lt; lia. }\n        specialize (Hex (nat_to_fin Hlt)).\n        eapply always3_mono; last apply Hex.\n        clear.\n        rewrite fin_to_nat_to_fin; done. }\n      assert (S n < S (S n)) as Hlt by lia.\n      specialize (Hex (nat_to_fin Hlt)).\n      apply always3_holds in Hex.\n      rewrite fin_to_nat_to_fin in Hex.\n      destruct Hex as [l Hl].\n      assert (length (lcs ++ [l]) = S n) as Hlcslen'.\n      { rewrite app_length Hlcslen; simpl; lia. }\n      exists (exist _ (lcs ++ [l]) Hlcslen').\n      split; last done.\n      erewrite take_S_r; last by eauto.\n      rewrite Hlcs1 fmap_app; simpl; done.\n  Qed.\n\n  Lemma eventually_sent_eventually_allocated_helper' locs ex mtr ilocs iex imtr :\n    length (trace_last locs) = GClen gcdata \u2192\n  (\u2200 j : fin (S (GClen gcdata)),\n     always3\n       (\u03bb locs' ex'' mtr'' ilocs'' iex'' imtr'',\n          match fin_to_nat j with\n          | 0 => crdt_main_rel_ternary locs' ex'' mtr'' ilocs'' iex'' imtr''\n          | S k => \u2203 l : loc, trace_last locs' !! k = Some (Some l)\n        end) locs ex mtr ilocs iex imtr) \u2192\n  \u2203 lcssg : {lcs : list loc | length lcs = GClen gcdata},\n     trace_last locs = Some <$> `lcssg \u2227\n     always3 crdt_main_rel_ternary locs ex mtr ilocs iex imtr.\n  Proof.\n    intros Hlen Hex.\n    rewrite -(firstn_all (trace_last locs)) Hlen.\n    apply eventually_sent_eventually_allocated_helper; done.\n  Qed.\n\n  Lemma eventually_sent_eventually_allocated ex iex mtr imtr :\n    (\u2200 i, i < GClen gcdata \u2192\n          eventually (\u03bb ex' _, events_of_trace (sendonEV (ith_sa i)) ex' \u2260 []) ex iex) \u2192\n    valid_inf_exec ex iex \u2192\n    always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr \u2192\n    \u2203 lcs : list loc,\n       length lcs = GClen gcdata \u2227\n       eventually3\n          (\u03bb locs ex' mtr' ilocs' iex' imtr',\n           (trace_last locs = Some <$> lcs) \u2227\n           always3 crdt_main_rel_ternary locs ex' mtr' ilocs' iex' imtr')\n          (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr.\n  Proof.\n    intros Hev Hvex Hal.\n    cut (\u2203 lcssg : {lcs : list loc | length lcs = GClen gcdata},\n             eventually3\n                (\u03bb locs ex' mtr' ilocs' iex' imtr',\n                 (trace_last locs = Some <$> `lcssg) \u2227\n                 always3 crdt_main_rel_ternary locs ex' mtr' ilocs' iex' imtr')\n                (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr).\n    { intros [[? ?] ?]; eauto. }\n    apply eventually3_exists.\n    epose proof (eventually_sent_eventually_exists_loc_all _ _ _ _ Hev Hvex Hal) as Hex.\n    apply eventually3_take_drop in Hex as [n [Hex [Hilen1 Hilen2]]].\n    apply eventually3_take_drop.\n    exists n; split; last done.\n    apply eventually_sent_eventually_allocated_helper'; last done.\n    rewrite locs_of_inf_trace_take locs_of_trace_last locs_of_trace_now_length; done.\n  Qed.\n\n  Definition crdt_main_rel_locs_resolved (locs : list loc) (ex: execution_trace aneris_lang)\n             (mtr : finite_trace (GCounterM gcdata) ())\n             (iex: inf_execution_trace aneris_lang)\n             (imtr : inflist (() * GCounterM gcdata))  : Prop :=\n    valid_model_fin_trace mtr \u2227\n    gcounter_values_related_now_locs_resolved locs (trace_last ex) (trace_last mtr) \u2227\n    send_evs_rel_locs_resolved locs ex \u2227\n    receive_evs_rel_locs_resolved locs ex.\n\n  Definition monotone_from_now_on locs ex iex :=\n    (always (\u03bb ex' _,\n             \u2203 l, ex' = ex +trl+ l \u2227\n                  gcounter_monotone_locs_resolved locs (trace_last ex :: map snd l)) ex iex).\n\n  (* TODO: put in aneris *)\n\n  Lemma monotone_from_now_on_unroll_n n locs ex iex :\n    monotone_from_now_on locs ex iex \u2192\n    monotone_from_now_on locs (ex +trl+ inflist_take n iex) (inflist_drop n iex).\n  Proof.\n    intros Hfno.\n    apply always_take_drop; intros m.\n    apply (always_unroll_n _ n) in Hfno.\n    apply (always_unroll_n _ m) in Hfno.\n    apply always_holds in Hfno.\n    destruct Hfno as [l [Hl Hgms]].\n    rewrite Hl.\n    rewrite !trace_append_list_assoc -!inflist_take_add in Hl.\n    apply trace_append_list_inj2 in Hl.\n    rewrite inflist_take_add in Hl.\n    simplify_eq.\n    eexists _; split.\n    { rewrite !trace_append_list_assoc; done. }\n    intros i j ?????.\n    apply (Hgms (length (inflist_take n iex) + i) (length (inflist_take n iex) + j)).\n    - lia.\n    - destruct i as [|i]; simpl in *.\n      + rewrite map_app (lookup_app_l (_ :: _)) /=; last by rewrite map_length /=; lia.\n        rewrite Nat.add_0_r.\n        rewrite trace_last_of_append_list_map //.\n      + rewrite Nat.add_comm /= Nat.add_comm.\n        rewrite map_app lookup_app_r; last by rewrite map_length; lia.\n        rewrite map_length minus_plus; done.\n    - destruct j as [|j]; simpl in *.\n      + rewrite map_app (lookup_app_l (_ :: _)); last by rewrite /= map_length /=; lia.\n        rewrite Nat.add_0_r.\n        rewrite trace_last_of_append_list_map; done.\n      + rewrite Nat.add_comm /= Nat.add_comm.\n        rewrite map_app lookup_app_r; last by rewrite map_length; lia.\n        rewrite map_length minus_plus; done.\n  Qed.\n\n  Definition closed_model_relation locs ex mtr iex imtr :=\n    (monotone_from_now_on locs ex iex) \u2227\n    always2 (crdt_main_rel_locs_resolved locs) ex mtr iex imtr.\n\n  Lemma eventually_sent_eventually_locs_resolved ex iex mtr imtr :\n    (\u2200 i, i < GClen gcdata \u2192\n          eventually (\u03bb ex' _, events_of_trace (sendonEV (ith_sa i)) ex' \u2260 []) ex iex) \u2192\n    valid_inf_exec ex iex \u2192\n    always3 crdt_main_rel_ternary (locs_of_trace ex) ex mtr (locs_of_inf_trace ex iex) iex imtr \u2192\n    \u2203 locs, length locs = GClen gcdata \u2227 eventually2 (closed_model_relation locs) ex mtr iex imtr.\n  Proof.\n    intros Hev Hvl Hal3.\n    edestruct (eventually_sent_eventually_allocated ex iex mtr imtr) as (locs & Hlocslen & Hal);\n      [done|done|done|].\n    exists locs; split; first done.\n    apply eventually3_take_drop in Hal as [n [[Hex1 Hex2] [Hilen1 Hilen2]]].\n    apply eventually2_take_drop.\n    exists n; split; last done.\n    split.\n    - apply always_take_drop; intros k.\n      apply (always3_unroll_n _ n), (always3_unroll_n _ k), always3_holds in Hal3.\n      rewrite !trace_append_list_assoc -!inflist_take_add in Hal3.\n      rewrite !locs_of_inf_trace_take in Hal3.\n      apply crdt_main_rel_ternary_crdt_main_rel in Hal3.\n      apply crdt_main_rel_monotone in Hal3.\n      rewrite !inflist_take_add -!trace_append_list_assoc in Hal3.\n      pose proof (locs_of_inf_trace_less_defined _ _ Hvl) as Hld.\n      apply (always_unroll_n _ n), (always_unroll_n _ k), always_holds in Hld.\n      eexists _; split; first reflexivity.\n      eapply (gcounter_monotone_resolve_locs\n                 locs\n                 (ex +trl+ inflist_take n iex)\n                 (inflist_take\n                     k\n                     (locs_of_inf_trace (ex +trl+ inflist_take n iex) (inflist_drop n iex)))).\n      + apply inflist_take_of_same_length, locs_of_inf_trace_length.\n      + done.\n      + eapply valid_inf_exe_valid_exec.\n        do 2 apply valid_inf_exe_take_drop; done.\n      + rewrite -locs_of_inf_trace_take; done.\n      + rewrite !locs_of_inf_trace_take.\n        rewrite trace_append_list_assoc -inflist_take_add.\n        rewrite trace_append_list_assoc in Hld.\n        rewrite -inflist_take_add in Hld.\n        rewrite !locs_of_inf_trace_take in Hld.\n        done.\n      + rewrite !locs_of_inf_trace_take. done.\n    - apply always2_take_drop; intros k; split; last by apply inflist_same_length_drop.\n      apply (always3_unroll_n _ k), always3_holds in Hex2.\n      pose proof (locs_of_inf_trace_less_defined _ _ Hvl) as Hld.\n      apply (always_unroll_n _ n), (always_unroll_n _ k), always_holds in Hld.\n      eapply trace_append_list_steps_rtc_nl in Hld; [|done|done].\n      revert Hld; rewrite rt_rtc_same.\n      rewrite !trace_append_list_assoc -!inflist_take_add.\n      rewrite !trace_append_list_assoc -!inflist_take_add in Hex2.\n      intros Hld.\n      apply locs_all_defined in Hld.\n      destruct Hex2 as (_ & vmf & Hvrel%trace_forall3_last & Hsevs & Hrevs).\n      rewrite Hld in Hvrel, Hrevs, Hsevs.\n      split_and!.\n      + done.\n      + apply gcounter_values_related_now_resolve_locs; auto.\n      + apply send_evs_rel_resolve_locs; auto.\n      + apply receive_evs_rel_resolve_locs; auto.\n  Qed.\n\nEnd crdt_main_rel.\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/gcounter_convergence/crdt_main_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.2942149783515163, "lm_q1q2_score": 0.15857693224896283}}
{"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 Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import ReorderStep.\nRequire Import ProgressStep.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive reorder_store l1 v1 o1: forall (i2:Instr.t), Prop :=\n| reorder_store_load\n    r2 l2 o2\n    (ORD1: Ordering.le o1 Ordering.relaxed)\n    (ORD2: Ordering.le o2 Ordering.relaxed)\n    (LOC: l1 <> l2)\n    (REGS: RegSet.disjoint (Instr.regs_of (Instr.store l1 v1 o1))\n                           (Instr.regs_of (Instr.load r2 l2 o2))):\n    reorder_store l1 v1 o1 (Instr.load r2 l2 o2)\n| reorder_store_store\n    l2 v2 o2\n    (ORD1: Ordering.le o1 Ordering.relaxed)\n    (LOC: l1 <> l2):\n    reorder_store l1 v1 o1 (Instr.store l2 v2 o2)\n| reorder_store_update\n    r2 l2 rmw2 or2 ow2\n    (ORD1: Ordering.le o1 Ordering.relaxed)\n    (ORDR2: Ordering.le or2 Ordering.relaxed)\n    (LOC: l1 <> l2)\n    (REGS: RegSet.disjoint (Instr.regs_of (Instr.store l1 v1 o1)) (RegSet.singleton r2)):\n    reorder_store l1 v1 o1 (Instr.update r2 l2 rmw2 or2 ow2)\n.\n\nInductive sim_store: 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_store_intro\n    l1 f1 t1 v1 released1 o1 i2 rs\n    lc1_src sc1_src mem1_src\n    lc1_tgt sc1_tgt mem1_tgt\n    lc2_src sc2_src\n    (REORDER: reorder_store l1 v1 o1 i2)\n    (FULFILL: fulfill_step lc1_src sc1_src l1 f1 t1 (RegFile.eval_value rs v1) None released1 o1 lc2_src sc2_src)\n    (LOCAL: sim_local lc2_src lc1_tgt)\n    (SC: TimeMap.le sc2_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_store\n      (State.mk rs [Stmt.instr i2; Stmt.instr (Instr.store l1 v1 o1)]) lc1_src sc1_src mem1_src\n      (State.mk rs [Stmt.instr i2]) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_store_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_store 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_store st_src lc_src sc2_src mem2_src\n            st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  inv SIM1. exploit future_fulfill_step; try exact FULFILL; eauto; try refl.\n  { by inv REORDER. }\n  i. des. econs; eauto.\nQed.\n\nLemma sim_store_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_store 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_store st_src lc'_src sc2_src mem2_src\n                      st_tgt lc_tgt sc2_tgt mem2_tgt>>.\nProof.\n  inv SIM1.\n  exploit fulfill_step_future; eauto; try by viewtac. i. des.\n  exploit fulfill_step_future; try exact WF_SRC; eauto; try by viewtac. i. des.\n  exploit future_fulfill_step; try exact FULFILL; eauto; try refl; try by viewtac.\n  { by inv REORDER. }\n  i. des.\n  exploit SimPromises.future; try exact MEM1; eauto.\n  { inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite <- PROMISES.\n    apply SimPromises.sem_bot.\n  }\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_store_step\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      (SIM: sim_store 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_store)\n                     st1_src lc1_src sc1_src mem1_src\n                     st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n  inv SIM. ii.\n  exploit fulfill_step_future; eauto; try viewtac. i. des.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv REORDER); ss.\n  - (* promise *)\n    exploit Local.promise_step_future; eauto. i. des.\n    exploit sim_local_promise; try exact LOCAL0; (try by etrans; eauto); eauto. i. des.\n    exploit reorder_fulfill_promise; try exact FULFILL; try exact STEP_SRC; eauto. i. des.\n    exploit Local.promise_step_future; eauto. i. des.\n    esplits.\n    + eauto.\n    + econs 2. econs 1. econs; eauto.\n    + auto.\n    + etrans; eauto.\n    + auto.\n    + right. econs; eauto.\n      eapply Memory.future_closed_timemap; eauto.\n  - (* load *)\n    exploit sim_local_read; try exact LOCAL0; (try by etrans; eauto); eauto; try refl. i. des.\n    exploit reorder_fulfill_read; try exact FULFILL; try exact STEP_SRC; eauto. i. des.\n    exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n    exploit fulfill_write; eauto; try by viewtac. i. des.\n    esplits.\n    + econs 2; eauto. econs.\n      * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n      * auto.\n    + econs 2. econs 2. econs; [|econs 3]; eauto. econs.\n      erewrite <- RegFile.eq_except_value; eauto.\n      * econs.\n      * symmetry. eauto.\n      * apply RegFile.eq_except_singleton.\n    + auto.\n    + auto.\n    + etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n  - (* update-load *)\n    exploit sim_local_read; try exact LOCAL0; (try by etrans; eauto); eauto; try refl. i. des.\n    exploit reorder_fulfill_read; try exact FULFILL; try exact STEP_SRC; eauto. i. des.\n    exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n    exploit fulfill_write; eauto; try by viewtac. i. des.\n    esplits.\n    + econs 2; eauto. econs.\n      * econs. econs 2. econs; [|econs 2]; eauto. econs. econs. eauto.\n      * auto.\n    + econs 2. econs 2. econs; [|econs 3]; eauto. econs.\n      erewrite <- RegFile.eq_except_value; eauto.\n      * econs.\n      * symmetry. eauto.\n      * apply RegFile.eq_except_singleton.\n    + auto.\n    + auto.\n    + etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n  - (* store *)\n    hexploit sim_local_write; try exact LOCAL1; eauto; try refl; try by viewtac. i. des.\n    exploit reorder_fulfill_write; try exact FULFILL; try exact STEP_SRC; eauto; try by viewtac. i. des.\n    exploit Local.write_step_future; try exact STEP1; eauto; try by viewtac. i. des.\n    exploit fulfill_write; eauto; try by viewtac. i. des.\n    esplits.\n    + econs 2; eauto. econs.\n      * econs. econs 2. econs; [|econs 3]; eauto. econs. econs.\n      * auto.\n    + econs 2. econs 2. econs; [|econs 3]; eauto. econs. econs.\n    + auto.\n    + etrans; eauto.\n    + etrans; eauto. etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\n  - (* update *)\n    exploit fulfill_step_future; try exact FULFILL; eauto; try by viewtac. i. des.\n    exploit Local.read_step_future; try exact LOCAL1; eauto; try by viewtac. i. des.\n    exploit sim_local_read; try exact LOCAL1; (try by etrans; eauto); eauto; try refl. i. des.\n    exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n    hexploit sim_local_write; try exact LOCAL2; eauto; try refl; try by viewtac. i. des.\n    hexploit reorder_fulfill_update; try exact FULFILL; try exact STEP_SRC; try exact STEP_SRC0; eauto; try by viewtac. i. des.\n    exploit Local.read_step_future; try apply STEP1; eauto. i. des.\n    exploit Local.write_step_future; try apply STEP2; eauto. i. des.\n    exploit fulfill_write; eauto; try exact STEP3; try by viewtac. i. des.\n    esplits.\n    + econs 2; eauto. econs.\n      * econs. econs 2. econs; [|econs 4]; eauto. econs. econs. eauto.\n      * auto.\n    + econs 2. econs 2. econs; [|econs 3]; eauto. econs.\n      erewrite <- RegFile.eq_except_value; eauto.\n      * econs.\n      * symmetry. eauto.\n      * apply RegFile.eq_except_singleton.\n    + auto.\n    + etrans; eauto.\n    + etrans; eauto. etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\nQed.\n\nLemma sim_store_sim_thread:\n  sim_store <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_store_mon; eauto. i.\n    exploit sim_store_future; try apply x0; eauto. i. des.\n    esplits; eauto.\n  - exploit sim_store_mon; eauto. i.\n    inversion x0. subst. i.\n    exploit (progress_program_step rs i2 nil); eauto. i. des.\n    destruct th2. exploit sim_store_step; eauto.\n    { econs 2. eauto. }\n    i. des.\n    + exploit program_step_promise; eauto. i.\n      exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n      exploit Thread.opt_step_future; eauto. s. i. des.\n      exploit Thread.program_step_future; eauto. s. i. des.\n      punfold SIM. exploit SIM; try apply SC3; eauto; try refl. s. i. des.\n      exploit PROMISES; eauto. i. des.\n      esplits; [|eauto].\n\t    etrans; eauto. etrans; [|eauto].\n      inv STEP_SRC; eauto. econs 2; eauto. econs; eauto.\n      * econs. eauto.\n      * etrans; eauto.\n        destruct e; by inv STEP; inv STATE; inv INSTR; inv REORDER.\n    + inv SIM. inv STEP; inv STATE.\n  - exploit sim_store_mon; eauto. i. des.\n    exploit sim_store_step; eauto. i. des.\n    + esplits; eauto.\n      left. eapply paco9_mon; eauto. ss.\n    + esplits; 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/ReorderStore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.15856537507599747}}
{"text": "Require Import CertiGraph.unionfind.env_unionfind.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\nRequire Import CertiGraph.msl_application.GList.\nRequire Import CertiGraph.msl_application.GList_UnionFind.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.unionfind.spatial_graph_glist.\n\nLocal Coercion UFGraph_LGraph: UFGraph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation vertices_at sh P g:= (@vertices_at _ _ _ _ _ mpred (@SGP pSGG_VST nat unit (sSGG_VST sh)) (SGA_VST sh) P g).\nNotation whole_graph sh g := (vertices_at sh (vvalid g) g).\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ x g).\nNotation UFGraph := (@UFGraph pSGG_VST).\nNotation uf_under_bound g := (uf_under_bound id g).\nExisting Instances maGraph finGraph liGraph RGF.\n\nDefinition vlabel_in_bound (g: UFGraph) := forall x, vvalid g x -> Z.of_nat (vlabel g x) <= Int.max_unsigned.\n\nLemma rank_unchanged_in_bound: forall (g g': UFGraph), uf_equiv g g' -> rank_unchanged g g' -> vlabel_in_bound g -> vlabel_in_bound g'.\nProof. unfold uf_equiv, rank_unchanged, vlabel_in_bound. intros. destruct H as [? _]. pose proof H2. rewrite <- H in H2. rewrite <- H0; auto. Qed.\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH sh: wshare, n:Z\n  PRE [tint]\n     PROP (0 <= n <= Int.max_signed)\n     PARAMS (Vint (Int.repr n))\n     GLOBALS ()\n     SEP ()\n  POST [ tptr tvoid ]\n     EX v: addr,\n     PROP ()\n     LOCAL (temp ret_temp (pointer_val_val v))\n     SEP (data_at sh node_type (pointer_val_val null, (Vint (Int.repr 0)))\n              (pointer_val_val v)).\n\nDefinition find_spec :=\n DECLARE _find\n  WITH sh: wshare, g: UFGraph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (vvalid g x ; uf_under_bound g)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (whole_graph sh g)\n  POST [ tptr (Tstruct _Node noattr) ]\n        EX g': UFGraph, EX rt : pointer_val,\n        PROP (uf_equiv g g'; uf_root g' x rt ; uf_under_bound g' ; rank_unchanged g g')\n        LOCAL (temp ret_temp (pointer_val_val rt))\n        SEP (whole_graph sh g').\n\nDefinition unionS_spec :=\n DECLARE _unionS\n  WITH sh: wshare, g: UFGraph, x: pointer_val, y: pointer_val\n  PRE [tptr (Tstruct _Node noattr), tptr (Tstruct _Node noattr)]\n          PROP  (vvalid g x; vvalid g y ; uf_under_bound g ; vlabel_in_bound g)\n          PARAMS (pointer_val_val x; pointer_val_val y)\n          GLOBALS ()\n          SEP   (whole_graph sh g)\n  POST [ Tvoid ]\n        EX g': UFGraph,\n        PROP (uf_union g x y g' ; uf_under_bound g')\n        LOCAL()\n        SEP (whole_graph sh g').\n\nDefinition makeSet_spec :=\n  DECLARE _makeSet\n  WITH sh: wshare, g: UFGraph\n    PRE []\n      PROP (uf_under_bound g)\n      PARAMS ()\n      GLOBALS ()\n      SEP (whole_graph sh g)\n    POST [tptr (Tstruct _Node noattr)]\n      EX g': UFGraph, EX rt: pointer_val,\n      PROP (~ vvalid g rt ; vvalid g' rt ; is_partial_graph g g' ; uf_under_bound g')\n      LOCAL (temp ret_temp (pointer_val_val rt))\n      SEP (whole_graph sh g').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mallocN_spec; makeSet_spec; find_spec; unionS_spec]).\n\nLemma body_makeSet: semax_body Vprog Gprog f_makeSet makeSet_spec.\nProof.\n  start_function.\n  forward_call (sh, 8).\n  - rep_lia.\n  - Intros x.\n    assert_PROP (x <> null) as x_not_null by (entailer !; destruct H1 as [? _]; apply H1).\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 H0) x. entailer !.\n    + split; [|split]; simpl; [right | apply is_partial_make_set_pregraph | apply uf_under_bound_make_set_graph]; auto.\n    + assert (Coqlib.Prop_join (vvalid g) (eq x) (vvalid (make_set_Graph 0%nat tt tt x g x_not_null H0))). {\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 H0) 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 H0) 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 H0)). {\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 <- H6. apply derives_refl.\nQed.\n\nLemma false_Cne_eq: forall x y, typed_false tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .\n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst; auto.\n    + simpl in H. inversion H.\n  - simpl in H. inversion H.\nQed.\n\nLemma true_Cne_neq: forall x y, typed_true tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .\n    + simpl in H. inversion H.\n    + subst b0. pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro; apply H0. inversion H1. reflexivity.\n  - intro. inversion H0. auto.\nQed.\n\nLemma graph_local_facts: forall sh x (g: UFGraph), vvalid g x -> whole_graph sh g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. eapply derives_trans; [apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (vgamma g x)); auto |].\n  simpl vertex_at at 1. unfold binode. entailer!.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as rpa eqn:?H. destruct rpa as [r pa].\n  (* p = x -> parent; *)\n  localize [data_at sh node_type (vgamma2cdata (vgamma g x)) (pointer_val_val x)]. rewrite <- H1. simpl vgamma2cdata.\n  forward. 1: entailer!; destruct pa; simpl; auto.\n  unlocalize [whole_graph sh g].\n  1: rewrite <- H1; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (r, pa)); auto.\n  assert (H_PARENT_Valid: vvalid g pa) by (eapply valid_parent; eauto).\n  (* if (p != x) { *)\n  forward_if\n    (EX g': UFGraph, EX rt : pointer_val,\n     PROP (uf_equiv g g' /\\ uf_root g' x rt /\\ uf_under_bound g' /\\ rank_unchanged g g')\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    pose proof (true_Cne_neq _ _ H2).\n    assert (weak_valid g' root) by (right; destruct H4; apply reachable_foot_valid in H4; auto).\n    assert (vvalid g' x) by (destruct H3 as [? _]; rewrite <- H3; apply H).\n    assert (~ reachable g' root x) by (apply (uf_equiv_not_reachable g g' x r pa root); auto).\n    assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' x root H8 H9 H10)) (Graph_gen_redirect_parent g' x root H8 H9 H10) =\n            vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' x root H8 H9 H10)). {\n      apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n    remember (vgamma g' x) as rpa eqn:?H. destruct rpa as [r' pa']. symmetry in H12.\n    localize [data_at sh node_type (Vint (Int.repr (Z.of_nat r')), pointer_val_val pa') (pointer_val_val x)].\n    forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g' x root H8 H9 H10)].\n    + rewrite H11. apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto. destruct H4.\n      apply reachable_foot_valid in H4. intro. subst root. apply (valid_not_null g' null H4). simpl. auto.\n    + Exists (Graph_gen_redirect_parent g' x root H8 H9 H10) root. rewrite H11. entailer!.\n      assert (uf_root g' x root). {\n        rewrite <- (uf_equiv_root_the_same g g' x root); auto.\n        apply (uf_root_edge _ (liGraph g) _ pa); [| apply (vgamma_not_dst g x r pa) | rewrite (uf_equiv_root_the_same g g')]; auto.\n      } split; [|split].\n      * apply (graph_gen_redirect_parent_equiv g g' x r pa); auto.\n      * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto. apply reachable_refl; auto.\n      * apply uf_under_bound_redirect_parent; auto.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H2. subst pa. split; [|split; [split |]]; auto.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + apply uf_root_vgamma with (n := r); auto.\n    + repeat intro; auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed. (* Original: 56.251 secs; VST 2.*: 2.084 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  forward_call (sh, g, x). Intros vret. destruct vret as [g1 x_root]. simpl fst in *. simpl snd in *. apply rank_unchanged_in_bound in H6; auto.\n  assert (vvalid g1 y) by (destruct H3 as [? _]; rewrite <- H3; apply H0).\n  forward_call (sh, g1, y). Intros vret. destruct vret as [g2 y_root]. simpl fst in *. simpl snd in *. apply rank_unchanged_in_bound in H11; auto.\n  assert (H_VALID_XROOT: vvalid g2 x_root) by (destruct H8 as [? _]; rewrite <- H8; destruct H4; apply reachable_foot_valid in H4; apply H4).\n  assert (H_VALID_YROOT: vvalid g2 y_root) by (destruct H9; apply reachable_foot_valid in H9; apply H9).\n  assert (H_XROOT_NOT_NULL: x_root <> null) by (intro; subst x_root; apply (valid_not_null g2 null H_VALID_XROOT); simpl; auto).\n  assert (H_YROOT_NOT_NULL: y_root <> null) by (intro; subst y_root; apply (valid_not_null g2 null H_VALID_YROOT); simpl; auto).\n  forward_if_tac\n    (PROP (x_root <> y_root)\n     LOCAL (temp _yRoot (pointer_val_val y_root); temp _xRoot (pointer_val_val x_root);\n     temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n     SEP (vertices_at sh (vvalid g2) g2)).\n  - apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n  - forward. apply true_Ceq_eq in H12. Exists g2. subst y_root. entailer!. apply (the_same_root_union g g1 g2 x y x_root); auto.\n  - forward. apply false_Ceq_neq in H12. entailer!.\n  - Intros. (* xRank = xRoot -> rank; *)\n    remember (vgamma g2 x_root) as rpa eqn:?H. destruct rpa as [rankXRoot paXRoot]. symmetry in H13.\n    localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n    rewrite H13. simpl vgamma2cdata. forward.\n    unlocalize [whole_graph sh g2].\n    1: rewrite H13; 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 H14.\n    localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n    rewrite H14. simpl vgamma2cdata. forward.\n    unlocalize [whole_graph sh g2].\n    1: rewrite H14; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g2 (vvalid g2) y_root (rankYRoot, paYRoot)); auto.\n    rename H_VALID_XROOT into H15. clear H1 H2 H5 H6.\n    assert (Int.unsigned (Int.repr (Z.of_nat rankXRoot)) = Z.of_nat (vlabel g2 x_root)). {\n      simpl vgamma in H13. inversion H13. apply Int.unsigned_repr. split; [apply Zle_0_nat | specialize (H11 x_root H15); auto].\n    } assert (Int.unsigned (Int.repr (Z.of_nat rankYRoot)) = Z.of_nat (vlabel g2 y_root)). {\n      simpl vgamma in H14. inversion H14. apply Int.unsigned_repr. split; [apply Zle_0_nat | specialize (H11 y_root H_VALID_YROOT); auto].\n    } clear H11.\n    forward_if\n      (EX g': UFGraph,\n       PROP (uf_union g x y g' /\\ uf_under_bound 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).\n      assert (~ reachable g2 y_root x_root) by (intro; destruct H9; specialize (H16 _ H11); auto).\n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)) (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11) =\n              vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)). {\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 H13. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11)].\n      1: rewrite H13; simpl vgamma2cdata; rewrite H16; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n      Exists (Graph_gen_redirect_parent g2 x_root y_root H6 H15 H11). entailer !. split.\n      * apply (diff_root_union_1 g g1 g2 x y x_root y_root); auto.\n      * rewrite H1 in *. rewrite H2 in *. rewrite <- Nat2Z.inj_lt in H5. destruct H9. apply uf_under_bound_redirect_parent_lt; 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 H4; auto; destruct H4; specialize (H17 _ H16); auto).\n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)) (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16) =\n              vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      forward_if\n      (EX g': UFGraph,\n       PROP (uf_union g x y g' /\\ uf_under_bound 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 H14. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)].\n        1: rewrite H14; simpl vgamma2cdata; rewrite H17; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n        Exists (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16). entailer!. split.\n        -- apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto.\n        -- rewrite H1 in *. rewrite H2 in *. rewrite <- Nat2Z.inj_lt in H18. apply uf_under_bound_redirect_parent_lt; auto.\n           rewrite (uf_equiv_root_the_same g1 g2) in H4; auto. destruct H4. auto.\n      * (* yRoot -> parent = xRoot; *)\n        localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n        rewrite H14. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16)].\n        1: rewrite H14; simpl vgamma2cdata; rewrite H17; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n        set (g3 := Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16).\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 H13. simpl vgamma2cdata. forward.\n        rewrite add_repr. replace (Z.of_nat rankXRoot + 1) with (Z.of_nat (rankXRoot + 1)). 2: 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 H20. clear H20. rewrite H13. simpl vgamma2cdata. apply (@graph_vgen_ramify _ (sSGG_VST sh)).\n           ++ subst g3. simpl. destruct H8 as [? _]. rewrite <- H8. destruct H4; apply reachable_foot_valid in H4; apply H4.\n           ++ subst g3. remember (Graph_gen_redirect_parent g2 y_root x_root H6 H11 H16) as g3.\n              apply (graph_gen_redirect_parent_vgamma _ _ _ rankXRoot paXRoot) in Heqg3; auto. intros. inversion H20; auto.\n        -- Exists (Graph_vgen g3 x_root (rankXRoot + 1)%nat). entailer!. rewrite H1 in *; rewrite H2 in *.\n           assert (Z.of_nat (vlabel g2 x_root) = Z.of_nat (vlabel g2 y_root)) by (clear -H5 H18; intuition). apply Nat2Z.inj in H24.\n           simpl in H13. inversion H13. apply uf_under_bound_redirect_parent_eq; auto. rewrite (uf_equiv_root_the_same g1 g2) in H4; auto. destruct H4. auto.\n    + Intros g'. Exists g'. entailer!.\nQed. (* Original: 192.772 secs; VST 2.*: 4.786 secs *)\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/unionfind/verif_unionfind_rank.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.15847991017733895}}
{"text": "(** * Erasure from FineConc to a non-angelic SC machine*)\n\nRequire Import compcert.lib.Axioms.\n\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.semantics_lemmas.\n\nRequire Import concurrency.pos.\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n  after Ssreflect eqtype.*)\nRequire Import compcert.common.AST.     (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Memory.\nRequire Import compcert.lib.Integers.\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import concurrency.threads_lemmas.\nRequire Import concurrency.permissions.\nRequire Import concurrency.concurrent_machine.\nRequire Import concurrency.memory_lemmas.\nRequire Import concurrency.dry_machine_lemmas.\nRequire Import concurrency.dry_context.\nRequire Import concurrency.fineConc_safe.\nRequire Import concurrency.executions.\nRequire Import Coqlib.\nRequire Import msl.Coqlib2.\n\nSet Bullet Behavior \"None\".\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n(** The erasure removes permissions and angels from the machine\n(i.e. making it a bare machine) and also allows some values to become\nmore defined. See [val_erasure] and [memval_erasure] for a precise\naccount of that. *)\n\n(** ** Erasure of Values*)\nModule ValErasure.\n\n  Definition val_erasure v1 v2 : Prop :=\n    match v1, v2 with\n    | Vundef, _ => True\n    | v1, v2 => v1 = v2\n    end.\n\n  Definition optionval_erasure (v1 v2 : option val) : Prop :=\n    match v1, v2 with\n    | Some v1, Some v2 => val_erasure v1 v2\n    | None, None => True\n    | _, _ => False\n    end.\n\n  Definition memval_erasure mv1 mv2 : Prop :=\n    match mv1, mv2 with\n    | Undef, _ => True\n    | Fragment v1 q1 n1, Fragment v2 q2 n2 =>\n      val_erasure v1 v2 /\\ q1 = q2 /\\ n1 = n2\n    | mv1, mv2 => mv1 = mv2\n    end.\n\n  Inductive val_erasure_list : seq.seq val -> seq.seq val -> Prop :=\n    val_erasure_nil : val_erasure_list [::] [::]\n  | val_erasure_cons : forall (v v' : val) (vl vl' : seq.seq val),\n      val_erasure v v' ->\n      val_erasure_list vl vl' ->\n      val_erasure_list (v :: vl) (v' :: vl').\n\n  Inductive memval_erasure_list : seq.seq memval -> seq.seq memval -> Prop :=\n    memval_erasure_nil : memval_erasure_list [::] [::]\n  | memval_erasure_cons : forall (mv mv' : memval) (mvl mvl' : seq.seq memval),\n      memval_erasure mv mv' ->\n      memval_erasure_list mvl mvl' ->\n      memval_erasure_list (mv :: mvl) (mv' :: mvl').\n\n  Lemma val_erasure_refl:\n    forall v, val_erasure v v.\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma memval_erasure_refl:\n    forall mval,\n      memval_erasure mval mval.\n  Proof.\n    intros; destruct mval; constructor;\n    eauto using val_erasure_refl.\n  Qed.\n\n  Hint Immediate memval_erasure_refl val_erasure_refl : val_erasure.\n  Hint Constructors memval_erasure_list val_erasure_list : val_erasure.\n\n  Lemma val_erasure_list_refl:\n    forall vs, val_erasure_list vs vs.\n  Proof with eauto with val_erasure.\n    induction vs; simpl...\n  Qed.\n\n  Lemma val_erasure_list_decode:\n    forall vals vals' typs,\n      val_erasure_list vals vals' ->\n      val_erasure_list (val_casted.decode_longs typs vals)\n                       (val_casted.decode_longs typs vals').\n  Proof.\n    intros.\n    generalize dependent vals.\n    generalize dependent vals'.\n    induction typs; intros; simpl;\n    first by constructor.\n    destruct vals;\n      destruct a; inversion H; subst;\n      try constructor; eauto.\n    destruct vals; inversion H4; subst.\n    constructor.\n    unfold Val.longofwords.\n    destruct v;\n      constructor; eauto;\n      inv H2; try constructor.\n    unfold val_erasure in H3.\n    destruct v0; subst; auto;\n    constructor.\n  Qed.\n\n  Lemma memval_erasure_list_refl:\n    forall vs, memval_erasure_list vs vs.\n  Proof with eauto with val_erasure.\n    induction vs; simpl...\n  Qed.\n\n  Hint Immediate memval_erasure_list_refl : val_erasure.\n\n  (** ** Lemmas about erased values*)\n\n  Definition isPointer (v : val) :=\n    match v with\n    | Vptr _ _ => true\n    | _ => false\n    end.\n\n  Definition isDefined v :=\n    match v with\n    | Vundef => false\n    | _ => true\n    end.\n\n  Lemma val_erasure_add_result:\n    forall v1 v1' v2 v2' v,\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      Val.add v1 v2 = v ->\n      isDefined v ->\n      Val.add v1' v2' = v.\n  Proof.\n    intros.\n    destruct v1,v2; simpl in *; subst; simpl in *;\n    try (by exfalso); auto.\n  Qed.\n\n  Lemma isPointer_isDefined:\n    forall v, isPointer v -> isDefined v.\n  Proof.\n    unfold isPointer, isDefined;\n    destruct v; auto.\n  Qed.\n\n  Lemma val_erasure_add:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.add v1 v2) (Val.add v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mul:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.mul v1 v2) (Val.mul v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mul_result:\n    forall v1 v2 v1' v2' v,\n      val_erasure v1 v1'->\n      val_erasure v2 v2' ->\n      Val.mul v1 v2 = v ->\n      isDefined v ->\n      Val.mul v1' v2' = v.\n  Proof.\n    intros.\n    destruct v1,v2; simpl in *; subst; simpl in *;\n    try by exfalso.\n    reflexivity.\n  Qed.\n\n  Lemma val_erasure_hiword:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.hiword v) (Val.hiword v').\n  Proof.\n    intros;\n    destruct v; simpl; inv H; auto.\n  Qed.\n\n  Lemma val_erasure_loword:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.loword v) (Val.loword v').\n  Proof.\n    intros;\n    destruct v; simpl; inv H; auto.\n  Qed.\n\n  Lemma val_erasure_cmp_bool:\n    forall c v1 v1',\n      v1 <> Vundef ->\n      val_erasure v1 v1' ->\n      Val.cmp_bool c v1 Vzero = Val.cmp_bool c v1' Vzero.\n  Proof.\n    intros.\n    destruct v1; try congruence.\n  Qed.\n\n  Lemma val_erasure_zero_ext:\n    forall v v' n,\n      val_erasure v v' ->\n      val_erasure (Val.zero_ext n v) (Val.zero_ext n v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_sign_ext:\n    forall v v' n,\n      val_erasure v v' ->\n      val_erasure (Val.sign_ext n v) (Val.sign_ext n v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_singleoffloat:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.singleoffloat v) (Val.singleoffloat v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_floatofsingle:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.floatofsingle v) (Val.floatofsingle v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_intoffloat:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.maketotal (Val.intoffloat v))\n                  (Val.maketotal (Val.intoffloat v')).\n  Proof.\n    intros.\n    destruct v; inv H; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_floatofint:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.maketotal (Val.floatofint v))\n                  (Val.maketotal (Val.floatofint v')).\n  Proof.\n    intros.\n    destruct v; inv H; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_intofsingle:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.maketotal (Val.intofsingle v))\n                  (Val.maketotal (Val.intofsingle v')).\n  Proof.\n    intros.\n    destruct v; inv H; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_singleofint:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.maketotal (Val.singleofint v))\n                  (Val.maketotal (Val.singleofint v')).\n  Proof.\n    intros.\n    destruct v; inv H; simpl; eauto using val_erasure_refl.\n  Qed.\n\n\n  Lemma val_erasure_neg:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.neg v) (Val.neg v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_notint:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.notint v) (Val.notint v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_negative:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.negative v) (Val.negative v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_sub_overflow:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.sub_overflow v1 v2) (Val.sub_overflow v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_sub:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.sub v1 v2) (Val.sub v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n    destruct (eq_block b b0); simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mulhu:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.mulhu v1 v2) (Val.mulhu v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mulhs:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.mulhs v1 v2) (Val.mulhs v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_and:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.and v1 v2) (Val.and v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_or:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.or v1 v2) (Val.or v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_xor:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.xor v1 v2) (Val.xor v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_shl:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.shl v1 v2) (Val.shl v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_shr:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.shr v1 v2) (Val.shr v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_shru:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.shru v1 v2) (Val.shru v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_ror:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.ror v1 v2) (Val.ror v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; eauto using val_erasure_refl.\n  Qed.\n\n  Lemma val_erasure_divu_result:\n    forall v1 v2 v1' v2' v,\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      Val.divu v1 v2 = Some v ->\n      Val.divu v1' v2' = Some v.\n  Proof.\n    destruct v1,v2; intros;\n    inv H; inv H0; simpl in *; eauto using val_erasure_refl;\n    try discriminate.\n  Qed.\n\n  Lemma val_erasure_modu_result:\n    forall v1 v2 v1' v2' v,\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      Val.modu v1 v2 = Some v ->\n      Val.modu v1' v2' = Some v.\n  Proof.\n    destruct v1,v2; intros;\n    inv H; inv H0; simpl in *; eauto using val_erasure_refl;\n    try discriminate.\n  Qed.\n\n  Lemma val_erasure_divs_result:\n    forall v1 v2 v1' v2' v,\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      Val.divs v1 v2 = Some v ->\n      Val.divs v1' v2' = Some v.\n  Proof.\n    destruct v1,v2; intros;\n    inv H; inv H0; simpl in *; eauto using val_erasure_refl;\n    try discriminate.\n  Qed.\n\n  Lemma val_erasure_mods_result:\n    forall v1 v2 v1' v2' v,\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      Val.mods v1 v2 = Some v ->\n      Val.mods v1' v2' = Some v.\n  Proof.\n    destruct v1,v2; intros;\n    inv H; inv H0; simpl in *; eauto using val_erasure_refl;\n    try discriminate.\n  Qed.\n\n  Lemma val_erasure_addf:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.addf v1 v2) (Val.addf v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_addfs:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.addfs v1 v2) (Val.addfs v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_subf:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.subf v1 v2) (Val.subf v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_subfs:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.subfs v1 v2) (Val.subfs v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mulf:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.mulf v1 v2) (Val.mulf v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_mulfs:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.mulfs v1 v2) (Val.mulfs v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_divf:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.divf v1 v2) (Val.divf v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_divfs:\n    forall v1 v2 v1' v2',\n      val_erasure v1 v1' ->\n      val_erasure v2 v2' ->\n      val_erasure (Val.divfs v1 v2) (Val.divfs v1' v2').\n  Proof.\n    destruct v1,v2; intros;\n    simpl; auto;\n    inv H; inv H0; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_negf:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.negf v) (Val.negf v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_negfs:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.negfs v) (Val.negfs v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_absf:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.absf v) (Val.absf v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma val_erasure_absfs:\n    forall v v',\n      val_erasure v v' ->\n      val_erasure (Val.absfs v) (Val.absfs v').\n  Proof.\n    intros.\n    destruct v; inv H; simpl; auto.\n  Qed.\n\n  Lemma inj_bytes_erasure :\n    forall (bl : seq.seq byte),\n      memval_erasure_list (inj_bytes bl) (inj_bytes bl).\n  Proof.\n    induction bl;\n    simpl; constructor; auto.\n    constructor.\n  Qed.\n\n  Lemma inj_value_erasure :\n    forall (v1 v2 : val) (q : quantity),\n      val_erasure v1 v2 ->\n      memval_erasure_list (inj_value q v1) (inj_value q v2).\n  Proof with eauto with val_erasure.\n    intros.\n    destruct v1; inv H; simpl...\n    destruct q; simpl; unfold inj_value; simpl;\n    repeat (econstructor; simpl; auto).\n  Qed.\n\n  Lemma repeat_Undef_erasure_self :\n    forall (n : nat),\n      memval_erasure_list (list_repeat n Undef) (list_repeat n Undef).\n  Proof.\n    eauto with val_erasure.\n  Qed.\n\n  Lemma repeat_Undef_inject_encode_val :\n    forall (chunk : memory_chunk) (v : val),\n      memval_erasure_list (list_repeat (size_chunk_nat chunk) Undef)\n                         (encode_val chunk v).\n  Proof with eauto with val_erasure.\n    intros.\n    destruct v, chunk; simpl; unfold inj_value; simpl;\n    repeat econstructor...\n  Qed.\n\n  Lemma val_erasure_encode_val:\n    forall chunk v v',\n      val_erasure v v' ->\n      memval_erasure_list (encode_val chunk v) (encode_val chunk v').\n  Proof.\n    intros.\n    destruct v; inversion H; subst; simpl; destruct chunk;\n    auto using inj_bytes_erasure,  inj_value_erasure, repeat_Undef_erasure_self,\n    repeat_Undef_inject_encode_val.\n    unfold encode_val. destruct v'; apply inj_value_erasure; auto.\n    unfold encode_val. destruct v'; apply inj_value_erasure; auto.\n  Qed.\n\n  Lemma val_defined_add_1:\n    forall v1 v2 v,\n      Val.add v1 v2 = v ->\n      isDefined v ->\n      isDefined v1.\n  Proof.\n    intros. destruct v1,v2; subst; simpl; auto.\n  Qed.\n\n  Lemma val_defined_add_2:\n    forall v1 v2 v,\n      Val.add v1 v2 = v ->\n      isDefined v ->\n      isDefined v2.\n  Proof.\n    intros. destruct v1,v2; subst; simpl; auto.\n  Qed.\n\n  Hint Resolve val_defined_add_1 val_defined_add_2 : val_defined.\n\n  Hint Extern 0 (val_erasure (Vint _) (Vint _)) => reflexivity : val_erasure.\n  Hint Resolve val_erasure_ror val_erasure_shru val_erasure_shr\n       val_erasure_shl val_erasure_xor val_erasure_or val_erasure_and\n       val_erasure_mulhs val_erasure_mulhu val_erasure_sub\n       val_erasure_neg val_erasure_singleofint val_erasure_singleoffloat\n       val_erasure_intofsingle val_erasure_floatofint val_erasure_intoffloat\n       val_erasure_floatofsingle val_erasure_singleoffloat val_erasure_sign_ext\n       val_erasure_zero_ext val_erasure_negative val_erasure_notint\n       val_erasure_sub_overflow val_erasure_encode_val\n       val_erasure_hiword val_erasure_loword\n       val_erasure_add val_erasure_add_result isPointer_isDefined\n       val_erasure_mul_result val_erasure_mul\n       val_erasure_addf val_erasure_subf val_erasure_mulf\n       val_erasure_divf val_erasure_negf val_erasure_absf\n       val_erasure_addfs val_erasure_subfs val_erasure_mulfs\n       val_erasure_divfs val_erasure_negfs val_erasure_absfs : val_erasure.\n\n  Hint Immediate val_erasure_refl : val_erasure.\n\nEnd ValErasure.\n\n(** ** Erasure of Traces*)\nModule TraceErasure.\n  Import ValErasure event_semantics.\n\n  Inductive mem_event_erasure : mem_event -> mem_event -> Prop :=\n  | WriteErasure: forall b ofs mvals mvals',\n      memval_erasure_list mvals mvals' ->\n      mem_event_erasure (Write b ofs mvals) (Write b ofs mvals')\n  | ReadErasure: forall b ofs sz mvals mvals',\n      memval_erasure_list mvals mvals' ->\n      mem_event_erasure (Read b ofs sz mvals) (Read b ofs sz mvals')\n  | AllocErasure: forall b ofs sz,\n      mem_event_erasure (Alloc b ofs sz) (Alloc b ofs sz)\n  | FreeErasure: forall ls,\n      mem_event_erasure (Free ls) (Free ls).\n\n  Inductive mem_event_list_erasure: list mem_event -> list mem_event -> Prop :=\n  | nilMemEvent: mem_event_list_erasure nil nil\n  | consMemEvent: forall mev mev' ls ls'\n                   (Hev_erasure: mem_event_erasure mev mev')\n                   (Hls_erasure: mem_event_list_erasure ls ls'),\n      mem_event_list_erasure (mev :: ls) (mev' :: ls').\n\n  (** Removing the footprints from a [sync_event] *)\n  Definition eraseSyncEvent ev :=\n    match ev with\n    | Events.release addr _ => Events.release addr None\n    | Events.acquire addr _ => Events.acquire addr None\n    | Events.spawn addr _ _ => Events.spawn addr None None\n    | _ => ev\n    end.\n\n  Inductive event_erasure : Events.machine_event -> Events.machine_event -> Prop :=\n  | InternalErasure: forall tid mev mev',\n      mem_event_erasure mev mev' ->\n      event_erasure (Events.internal tid mev) (Events.internal tid mev')\n  | ExternalErasure: forall tid ev,\n      event_erasure (Events.external tid ev)\n                    (Events.external tid (eraseSyncEvent ev)).\n\n  Inductive trace_erasure : list Events.machine_event ->\n                            list Events.machine_event -> Prop :=\n  | NilErasure: trace_erasure nil nil\n  | ConsErasure: forall ev ev' tr tr'\n                   (Hev_erasure: event_erasure ev ev')\n                   (Htr_erasure: trace_erasure tr tr'),\n      trace_erasure (ev :: tr) (ev' :: tr').\n\n  Lemma mem_event_list_erasure_cat:\n    forall tr1 tr1' tr2 tr2',\n      mem_event_list_erasure tr1 tr1' ->\n      mem_event_list_erasure tr2 tr2' ->\n      mem_event_list_erasure (tr1 ++ tr2) (tr1' ++ tr2').\n  Proof.\n    induction tr1 as [|ev tr1]; intros; inv H.\n    simpl; auto.\n    simpl.\n    constructor; eauto.\n  Qed.\n\n  Lemma trace_erasure_cat:\n    forall tr1 tr1' tr2 tr2',\n      trace_erasure tr1 tr1' ->\n      trace_erasure tr2 tr2' ->\n      trace_erasure (tr1 ++ tr2) (tr1' ++ tr2').\n  Proof.\n    induction tr1 as [|ev tr1]; intros; inv H.\n    simpl; auto.\n    simpl.\n    constructor; eauto.\n  Qed.\n\n  Lemma trace_erasure_map:\n    forall ev ev' tid,\n      mem_event_list_erasure ev ev' ->\n      trace_erasure (map [eta Events.internal tid] ev)\n                    (map [eta Events.internal tid] ev').\n  Proof.\n    induction 1;\n    simpl; constructor; auto.\n    constructor; auto.\n  Qed.\n\n\n  Hint Resolve trace_erasure_cat trace_erasure_map : trace_erasure.\n  Hint Constructors trace_erasure event_erasure : trace_erasure.\n\nEnd TraceErasure.\n\n(** ** Memory Erasure*)\nModule MemErasure.\n\n  Import ValErasure.\n\n  (** The values of the erased memory may be more defined and its\n       permissions are top.*)\n  (** In retrospect setting the permissions to top was a bad\n  choice. It should have been that the permissions of the erased\n  memory are above the permissions of the other memory. This would\n  make it more reusable and it wouldn't need a second definition for\n  free. *)\n\n  Local Notation \"a # b\" := (PMap.get b a) (at level 1).\n\n  Record mem_erasure (m m': mem) :=\n    { perm_le:\n        forall b ofs k,\n          Mem.valid_block m' b ->\n          (Mem.mem_access m')#b ofs k = Some Freeable;\n      erased_contents: forall b ofs,\n          memval_erasure (ZMap.get ofs ((Mem.mem_contents m) # b))\n                        (ZMap.get ofs ((Mem.mem_contents m') # b));\n      erased_nb: Mem.nextblock m = Mem.nextblock m'\n    }.\n\n  Lemma mem_erasure_restr:\n    forall m m' pmap (Hlt: permMapLt pmap (getMaxPerm m)),\n      mem_erasure m m' ->\n      mem_erasure (restrPermMap Hlt) m'.\n  Proof.\n    intros.\n    inversion H.\n    constructor; auto.\n  Qed.\n\n  Lemma mem_erasure_dilute_1:\n    forall m m',\n      mem_erasure m m' ->\n      mem_erasure (setMaxPerm m) m'.\n  Proof.\n    intros.\n    inversion H.\n    constructor; auto.\n  Qed.\n\n  Lemma getN_erasure:\n    forall m1 m2 b\n      (Herase: forall (b : positive) (ofs : ZIndexed.t),\n          memval_erasure (ZMap.get ofs (Mem.mem_contents m1) # b)\n                         (ZMap.get ofs (Mem.mem_contents m2) # b)),\n    forall n ofs,\n      memval_erasure_list\n        (Mem.getN n ofs (m1.(Mem.mem_contents)#b))\n        (Mem.getN n ofs (m2.(Mem.mem_contents)#b)).\n  Proof.\n    induction n; intros; simpl.\n    constructor.\n    constructor.\n    eapply Herase; eauto.\n    apply IHn.\n  Qed.\n\n  Lemma proj_bytes_erasure:\n    forall vl vl',\n      memval_erasure_list vl vl' ->\n      forall bl,\n        proj_bytes vl = Some bl ->\n        proj_bytes vl' = Some bl.\n  Proof.\n    induction 1; simpl. congruence.\n    intros.\n    destruct mv; simpl in H; try discriminate.\n    subst.\n    destruct (proj_bytes mvl) eqn:Hproj; try discriminate.\n    inv H1.\n    erewrite IHmemval_erasure_list by eauto.\n    reflexivity.\n  Qed.\n\n  Lemma proj_bytes_not_erasure:\n    forall vl vl',\n      memval_erasure_list vl vl' ->\n      proj_bytes vl = None -> proj_bytes vl' <> None -> In Undef vl.\n  Proof.\n    induction 1; simpl; intros.\n    congruence.\n    destruct mv; simpl in *; subst; try discriminate; auto.\n    destruct (proj_bytes mvl) eqn:Hproj; try discriminate.\n    destruct (proj_bytes mvl'); try congruence.\n    right; eapply IHmemval_erasure_list; eauto; congruence.\n    destruct mv'; subst; congruence.\n  Qed.\n\n  Lemma check_value_erasure:\n    forall vl vl',\n      memval_erasure_list vl vl' ->\n      forall v v' q n,\n        check_value n v q vl = true ->\n        val_erasure v v' -> v <> Vundef ->\n        check_value n v' q vl' = true.\n  Proof.\n    induction 1; intros; destruct n; simpl in *; auto.\n    destruct mv; try discriminate.\n    simpl in H. destruct mv'; try discriminate.\n    destruct H as [? [? ?]]; subst.\n\n    InvBooleans; assert (n = n1) by (apply beq_nat_true; auto). subst.\n    replace v1 with v'.\n    unfold proj_sumbool; rewrite ! dec_eq_true. rewrite <- beq_nat_refl. simpl; eauto.\n    destruct v0; simpl in *; subst; congruence.\n  Qed.\n\n  Lemma proj_value_erasure:\n    forall q vl1 vl2,\n      memval_erasure_list vl1 vl2 ->\n      val_erasure (proj_value q vl1) (proj_value q vl2).\n  Proof.\n    intros. unfold proj_value.\n    inv H; simpl; auto.\n    destruct mv; simpl in *; auto.\n    destruct mv'; try discriminate.\n    destruct H0 as [? [? ?]]; subst.\n    destruct (check_value (size_quantity_nat q) v q (Fragment v q1 n0 :: mvl)) eqn:B; auto.\n    destruct (Val.eq v Vundef). subst; auto.\n    assert (v = v0)\n      by (destruct v; simpl in *; congruence; auto).\n    subst.\n    erewrite check_value_erasure with (vl := (Fragment v0 q1 n0 :: mvl));\n      eauto with val_erasure.\n    simpl; auto.\n  Qed.\n\n  Lemma load_result_erasure:\n    forall chunk v1 v2,\n      val_erasure v1 v2 ->\n      val_erasure (Val.load_result chunk v1) (Val.load_result chunk v2).\n  Proof.\n    intros. destruct v1; inv H; destruct chunk; simpl; econstructor; eauto.\n  Qed.\n\n  Lemma decode_val_erasure:\n    forall vl1 vl2 chunk,\n      memval_erasure_list vl1 vl2 ->\n      val_erasure (decode_val chunk vl1) (decode_val chunk vl2).\n  Proof.\n    intros. unfold decode_val.\n    destruct (proj_bytes vl1) as [bl1|] eqn:PB1.\n    exploit proj_bytes_erasure; eauto. intros PB2. rewrite PB2.\n    destruct chunk; simpl; auto.\n    assert (A: forall q fn,\n               val_erasure (Val.load_result chunk (proj_value q vl1))\n                          (match proj_bytes vl2 with\n                           | Some bl => fn bl\n                           | None => Val.load_result chunk (proj_value q vl2)\n                           end)).\n    { intros. destruct (proj_bytes vl2) as [bl2|] eqn:PB2.\n      rewrite proj_value_undef. destruct chunk; simpl; auto.\n      eapply proj_bytes_not_erasure; eauto. congruence.\n      apply load_result_erasure. apply proj_value_erasure; auto.\n    }\n    destruct chunk; simpl; eauto.\n  Qed.\n\n\n  Lemma mem_load_erased:\n    forall chunk m m' b ofs v\n      (Hload: Mem.load chunk m b ofs = Some v)\n      (Herased: mem_erasure m m'),\n    exists v',\n      Mem.load chunk m' b ofs = Some v' /\\\n      val_erasure v v'.\n  Proof.\n    intros.\n    inversion Herased.\n    assert (Hreadable := Mem.load_valid_access _ _ _ _ _ Hload).\n    destruct Hreadable.\n    assert (Hreadable': Mem.valid_access m' chunk b ofs Readable).\n    { split; auto.\n      intros ? ?.\n      unfold Mem.perm.\n      rewrite perm_le0.\n      simpl; constructor.\n      eapply MemoryLemmas.load_valid_block in Hload.\n      unfold Mem.valid_block in *. simpl in *.\n      rewrite <- erased_nb0; auto.\n    }\n    exists (decode_val chunk (Mem.getN (size_chunk_nat chunk) ofs\n                                  (m'.(Mem.mem_contents)#b))).\n    Transparent Mem.load.\n    unfold Mem.load. split.\n    apply pred_dec_true; auto.\n    exploit Mem.load_result; eauto. intro. rewrite H1.\n    apply decode_val_erasure; auto.\n    apply getN_erasure; auto.\n    Opaque Mem.load.\n  Qed.\n\n  Lemma setN_erasure :\n    forall (vl1 vl2 : seq.seq memval),\n      memval_erasure_list vl1 vl2 ->\n      forall (p : Z) (c1 c2 : ZMap.t memval),\n        (forall q : Z,\n            memval_erasure (ZMap.get q c1) (ZMap.get q c2)) ->\n        forall q : Z,\n          memval_erasure (ZMap.get q (Mem.setN vl1 p c1))\n                        (ZMap.get q (Mem.setN vl2 p c2)).\n  Proof.\n    induction 1; intros; simpl.\n    auto.\n    apply IHmemval_erasure_list; auto.\n    intros. erewrite ZMap.gsspec at 1. destruct (ZIndexed.eq q0 p). subst q0.\n    rewrite ZMap.gss. auto.\n    rewrite ZMap.gso. auto. unfold ZIndexed.t in *. omega.\n  Qed.\n\n  Lemma mem_store_erased:\n    forall chunk m m' b ofs v v' m2\n      (Hstore: Mem.store chunk m b ofs v = Some m2)\n      (Herased: mem_erasure m m')\n      (Hval_erasure: val_erasure v v') ,\n    exists m2', Mem.store chunk m' b ofs v' = Some m2'\n           /\\ mem_erasure m2 m2'.\n  Proof.\n    intros.\n    destruct Herased.\n    assert (Haccess := Mem.store_valid_access_3 _ _ _ _ _ _ Hstore).\n    assert (Hvalid := Mem.valid_access_valid_block\n                        _ _ _ _ (Mem.valid_access_implies\n                                   _ _ _ _ _ Nonempty Haccess ltac:(constructor))).\n    destruct Haccess.\n    assert (Haccess' : Mem.valid_access m' chunk b ofs Writable).\n    { split; auto.\n      intros ? ?.\n      unfold Mem.perm.\n      rewrite perm_le0.\n      simpl; constructor.\n      unfold Mem.valid_block in *. simpl in *.\n      rewrite <- erased_nb0; auto.\n    }\n    destruct (Mem.valid_access_dec m' chunk b ofs Writable); try by exfalso.\n    destruct (Mem.valid_access_store _ _ _ _ v' Haccess') as [m2' Hstore'].\n    exists m2'. split; auto.\n    constructor.\n    - intros.\n      assert (Heq1 := MemoryLemmas.mem_store_max _ _ _ _ _ _ Hstore' b0 ofs0).\n      assert (Heq2 := MemoryLemmas.mem_store_cur _ _ _ _ _ _ Hstore' b0 ofs0).\n      do 2 rewrite getMaxPerm_correct in Heq1.\n      do 2 rewrite getCurPerm_correct in Heq2.\n      unfold permission_at in *.\n      eapply Mem.store_valid_block_2 in H1; eauto.\n      destruct k;\n        [rewrite <- Heq1 | rewrite <- Heq2];\n        eauto.\n    - intros.\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore').\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore).\n      rewrite ! PMap.gsspec.\n      destruct (peq b0 b). subst b0.\n      apply setN_erasure.\n      apply val_erasure_encode_val; auto. intros. eauto.\n      eauto.\n    - erewrite Mem.nextblock_store with (m1 := m) by eauto.\n      erewrite Mem.nextblock_store with (m2 := m2') (m1 := m') by eauto.\n      eauto.\n  Qed.\n\n  Lemma mem_loadv_erased:\n    forall chunk m m' vptr v\n      (Hload: Mem.loadv chunk m vptr = Some v)\n      (Herased: mem_erasure m m'),\n    exists v',\n      Mem.loadv chunk m' vptr = Some v' /\\\n      val_erasure v v'.\n  Proof.\n    intros.\n    destruct vptr; try discriminate.\n    simpl in *.\n    eapply mem_load_erased; eauto.\n  Qed.\n\n  Lemma mem_storev_erased:\n    forall chunk m m' vptr v v' m2\n      (Hstore: Mem.storev chunk m vptr v = Some m2)\n      (Herased: mem_erasure m m')\n      (Hval_erasure: val_erasure v v') ,\n    exists m2', Mem.storev chunk m' vptr v' = Some m2'\n           /\\ mem_erasure m2 m2'.\n  Proof.\n    intros.\n    destruct vptr; try discriminate.\n    simpl in *.\n    eapply mem_store_erased; eauto.\n  Qed.\n\n  Lemma mem_erasure_valid_pointer:\n    forall m m' b ofs,\n      mem_erasure m m' ->\n      Mem.valid_pointer m b ofs ->\n      Mem.valid_pointer m' b ofs.\n  Proof.\n    intros.\n    unfold Mem.valid_pointer in *.\n    destruct H.\n    destruct Mem.perm_dec; try by exfalso.\n    assert (Mem.valid_block m' b).\n    { destruct (valid_block_dec m' b); auto.\n      unfold Mem.valid_block in *.\n      rewrite <- erased_nb0 in n.\n      eapply Mem.nextblock_noaccess with (ofs := ofs) (k := Cur) in n.\n      unfold Mem.perm in p.\n      clear H0.\n      rewrite n in p.\n      simpl in p.\n        by exfalso.\n    }\n    specialize (perm_le0 _ ofs Cur H).\n    unfold is_true.\n    apply proj_sumbool_is_true.\n    unfold Mem.perm.\n    rewrite perm_le0.\n    simpl; constructor.\n  Qed.\n\n  Lemma mem_erasure_valid_pointer_guard:\n    forall m m' b ofs ofs',\n      mem_erasure m m' ->\n      Mem.valid_pointer m' b ofs\n      || Mem.valid_pointer m' b ofs' = false ->\n      Mem.valid_pointer m b ofs\n      || Mem.valid_pointer m b ofs'= false.\n  Proof.\n    intros.\n    apply orb_false_iff in H0. destruct H0.\n    apply orb_false_iff.\n    split;\n      match goal with\n      | [|- Mem.valid_pointer m b ?Ofs = _] =>\n        destruct (Mem.valid_pointer m b Ofs) eqn:Hptr\n      end; auto;\n      eapply mem_erasure_valid_pointer in Hptr; eauto.\n  Qed.\n\n  Lemma val_erasure_cmpu:\n    forall v1 v2 v1' v2' m m' cmp\n      (Hval_erasure: val_erasure v1 v1')\n      (Hval_erasure2: val_erasure v2 v2')\n      (Hmem: mem_erasure m m'),\n      val_erasure (Val.cmpu (Mem.valid_pointer m) cmp v1 v2)\n                  (Val.cmpu (Mem.valid_pointer m') cmp v1' v2').\n  Proof with eauto with val_erasure.\n    intros.\n    destruct v1,v2; simpl in *; inv Hval_erasure; auto;\n    unfold Val.cmpu, Val.cmpu_bool; simpl; eauto with val_erasure;\n    do 2 rewrite andb_if;\n    repeat match goal with\n           | [|- context[match ?Expr with | _ => _ end]] =>\n             destruct Expr eqn:?\n           end; simpl; eauto with val_erasure.\n    eapply mem_erasure_valid_pointer_guard in Heqb2; eauto.\n    congruence.\n    eapply mem_erasure_valid_pointer_guard in Heqb2; eauto.\n    congruence.\n    subst.\n    apply andb_false_iff in Heqb2.\n    destruct Heqb2 as [Heqb2 | Heqb2];\n      eapply mem_erasure_valid_pointer_guard in Heqb2; eauto;\n      congruence.\n    apply andb_false_iff in Heqb2.\n    eapply mem_erasure_valid_pointer in Heqb1; eauto.\n    eapply mem_erasure_valid_pointer in Heqb0; eauto.\n    destruct Heqb2 as [Heqb2 | Heqb2];\n      congruence.\n  Qed.\n\n  Lemma storev_pointer:\n    forall chunk m vptr v m',\n      Mem.storev chunk m vptr v = Some m' ->\n      isPointer vptr.\n  Proof.\n    intros. destruct vptr; simpl in *; try discriminate.\n    auto.\n  Qed.\n\n  Lemma loadv_pointer:\n    forall chunk m vptr v,\n      Mem.loadv chunk m vptr = Some v ->\n      isPointer vptr.\n  Proof.\n    intros. destruct vptr; simpl in *; try discriminate.\n    auto.\n  Qed.\n\n  Lemma loadbytes_erasure:\n    forall m m' b ofs sz bytes\n      (Hmem_erasure: mem_erasure m m')\n      (Hloadbytes: Mem.loadbytes m b ofs sz = Some bytes),\n    exists bytes',\n      Mem.loadbytes m' b ofs sz = Some bytes' /\\\n      memval_erasure_list bytes bytes'.\n  Proof.\n    intros.\n    Transparent Mem.loadbytes.\n    unfold Mem.loadbytes in *.\n    destruct (Mem.range_perm_dec m b ofs (ofs + sz) Cur Readable).\n    inv Hloadbytes.\n    exists (Mem.getN (nat_of_Z sz) ofs (m'.(Mem.mem_contents)#b)).\n    split. apply pred_dec_true.\n    unfold Mem.range_perm in r.\n    intros ofs' Hrange.\n    specialize (r _ Hrange).\n    assert (Mem.valid_block m' b).\n    { destruct (valid_block_dec m' b); auto.\n      destruct Hmem_erasure.\n      unfold Mem.valid_block in *.\n      rewrite <- erased_nb0 in n.\n      apply Mem.nextblock_noaccess with (ofs := ofs') (k := Cur) in n.\n      unfold Mem.perm in r.\n      rewrite n in r. simpl in r; by exfalso.\n    }\n    apply (perm_le Hmem_erasure) with (ofs := ofs') (k := Cur) in H.\n    unfold Mem.perm. rewrite H. simpl; constructor.\n    apply getN_erasure; auto.\n    destruct Hmem_erasure; auto.\n    discriminate.\n  Qed.\n\n  Lemma mem_erasure_idempotent:\n    forall m m',\n      mem_erasure m m' ->\n      mem_erasure m (erasePerm m').\n  Proof.\n    intros.\n    destruct H.\n    constructor; auto.\n    intros.\n    unfold Mem.valid_block in *.\n    unfold Mem.nextblock, erasePerm in H.\n    eapply erasePerm_V with (ofs := ofs) (k := k) in H.\n    unfold permission_at in *.\n    auto.\n  Qed.\n\n  Hint Resolve mem_erasure_idempotent mem_erasure_dilute_1\n       mem_erasure_restr: mem_erasure.\n\n\n Record mem_erasure' (m m': mem) :=\n    { perm_le':\n        forall b ofs k,\n          Mem.valid_block m b->\n          Mem.perm_order'' ((Mem.mem_access m')#b ofs k)\n                           ((Mem.mem_access m)#b ofs k);\n      erased_contents': forall b ofs,\n          memval_erasure (ZMap.get ofs ((Mem.mem_contents m) # b))\n                         (ZMap.get ofs ((Mem.mem_contents m') # b));\n      erased_nb': Mem.nextblock m = Mem.nextblock m'\n    }.\n\n  Lemma mem_erasure'_erase:\n    forall m m',\n      mem_erasure' m m' ->\n      mem_erasure m (erasePerm m').\n  Proof.\n    intros.\n    destruct H.\n    constructor; auto.\n    intros.\n    unfold Mem.valid_block in H.\n    simpl in H.\n    eapply erasePerm_V in H; eauto.\n  Qed.\n\n  Lemma alloc_erasure':\n    forall m m' sz m2 m2' b b'\n      (Herased: mem_erasure m m')\n      (Halloc: Mem.alloc m 0 sz = (m2, b))\n      (Halloc': Mem.alloc m' 0 sz = (m2', b')),\n      mem_erasure' m2 m2' /\\ b = b'.\n  Proof.\n    intros.\n    destruct Herased.\n    assert (b = b').\n    { apply Mem.alloc_result in Halloc.\n      apply Mem.alloc_result in Halloc'.\n      subst; auto. }\n    subst.\n    split; auto.\n    constructor.\n    - intros.\n      destruct (Pos.eq_dec b b').\n      + subst.\n        destruct (Z_le_dec 0 ofs);\n          destruct (Z_lt_dec ofs sz).\n        * assert (Heq:=\n                    MemoryLemmas.permission_at_alloc_2 _ _ _ _ _ _ Halloc' ltac:(eauto)).\n          unfold permission_at in Heq.\n          specialize (Heq k).\n          rewrite Heq.\n          simpl.\n          destruct ((Mem.mem_access m2) # b' ofs k); constructor; auto.\n        * apply Znot_lt_ge in n.\n          assert (H1:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ _ Halloc'\n                                                          ltac:(eauto)).\n          assert (H2:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ _ Halloc ltac:(eauto)).\n          unfold permission_at in H1,H2.\n          specialize (H1 k). specialize (H2 k).\n          rewrite H1 H2.\n          simpl. auto.\n        * assert (ofs < 0)\n            by omega.\n          assert (H1:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ ofs Halloc'\n                                                          ltac:(eauto)).\n          assert (H2:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ _ Halloc ltac:(eauto)).\n          unfold permission_at in H1,H2.\n          specialize (H1 k). specialize (H2 k).\n          rewrite H1 H2.\n          simpl. auto.\n        * assert (ofs < 0)\n            by omega.\n          assert (H1:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ ofs Halloc'\n                                                          ltac:(eauto)).\n          assert (H2:= MemoryLemmas.permission_at_alloc_3 _ _ _ _ _ _ Halloc ltac:(eauto)).\n          unfold permission_at in H1,H2.\n          specialize (H1 k). specialize (H2 k).\n          rewrite H1 H2.\n          simpl. auto.\n      + eapply Mem.valid_block_alloc_inv in H; eauto.\n        destruct H; try by exfalso.\n        unfold Mem.valid_block in H.\n        rewrite erased_nb0 in H.\n        assert (H2:= MemoryLemmas.permission_at_alloc_1 _ _  0%Z sz _ b ofs\n                                                        Halloc' ltac:(eauto)).\n        unfold permission_at in H2.\n        specialize (H2 k).\n        rewrite <-H2.\n        erewrite perm_le0; eauto. simpl.\n        destruct ((Mem.mem_access m2) # b ofs k); simpl; constructor.\n    - intros.\n      destruct (Pos.eq_dec b b'). subst.\n      erewrite MemoryLemmas.val_at_alloc_2 by eauto.\n      simpl; auto.\n      erewrite <- MemoryLemmas.val_at_alloc_3 by eauto.\n      erewrite <- MemoryLemmas.val_at_alloc_3 with (m' := m2') by eauto.\n      eauto.\n    - apply Mem.nextblock_alloc in Halloc.\n      apply Mem.nextblock_alloc in Halloc'.\n      rewrite Halloc' Halloc erased_nb0.\n      reflexivity.\n  Qed.\n\n  Lemma mem_free_erasure':\n    forall m m' sz m2 b\n      (Herased: mem_erasure m m')\n      (Hfree: Mem.free m b 0 sz = Some m2),\n    exists m2',\n      Mem.free m' b 0 sz = Some m2' /\\\n      mem_erasure' m2 m2'.\n  Proof.\n    intros.\n    destruct Herased.\n    pose proof (Mem.free_range_perm _ _ _ _ _ Hfree) as Hperm.\n    assert (Hfree': Mem.range_perm m' b 0 sz Cur Freeable).\n    { intros ofs Hrange.\n      specialize (Hperm _ Hrange).\n      unfold Mem.perm.\n      assert (Mem.valid_block m' b).\n      { destruct (valid_block_dec m' b); auto.\n        unfold Mem.valid_block in *.\n        rewrite <- erased_nb0 in n.\n        apply Mem.nextblock_noaccess with (ofs := ofs) (k := Cur) in n.\n        unfold Mem.perm in Hperm. rewrite n in Hperm.\n        simpl in Hperm; by exfalso.\n      }\n      specialize (perm_le0 _ ofs Cur H).\n      rewrite perm_le0.\n      simpl; constructor.\n    }\n    apply Mem.range_perm_free in Hfree'.\n    destruct Hfree' as [m2' Hfree'].\n    eexists; split; eauto.\n    constructor.\n    - intros.\n      apply Mem.free_result in Hfree.\n      apply Mem.free_result in Hfree'.\n      subst.\n      simpl.\n      unfold Mem.unchecked_free, Mem.valid_block in *. simpl in H.\n      rewrite erased_nb0 in H.\n      destruct (Pos.eq_dec b b0); subst.\n      + do 2 rewrite Maps.PMap.gss.\n        match goal with\n        | [|- context[match ?Expr with | _ => _ end]] =>\n          destruct Expr\n        end; simpl; auto.\n        erewrite perm_le0 by eauto.\n        simpl. destruct ((Mem.mem_access m) # b0 ofs k); constructor.\n      + do 2 erewrite Maps.PMap.gso by auto.\n        erewrite perm_le0 by eauto.\n        simpl. destruct ((Mem.mem_access m) # b0 ofs k); constructor.\n    - intros.\n      erewrite <- MemoryLemmas.mem_free_contents by eauto.\n      erewrite <- MemoryLemmas.mem_free_contents with (m2 := m2') by eauto.\n      eauto.\n    - apply Mem.nextblock_free in Hfree.\n      apply Mem.nextblock_free in Hfree'.\n      rewrite Hfree Hfree'; auto.\n  Qed.\n\n  Lemma mem_store_erased':\n    forall chunk m m' b ofs v v' m2\n      (Hstore: Mem.store chunk m b ofs v = Some m2)\n      (Herased: mem_erasure' m m')\n      (Hval_erasure: val_erasure v v') ,\n    exists m2', Mem.store chunk m' b ofs v' = Some m2'\n           /\\ mem_erasure' m2 m2'.\n  Proof.\n    intros.\n    destruct Herased.\n    assert (Haccess := Mem.store_valid_access_3 _ _ _ _ _ _ Hstore).\n    assert (Hvalid := Mem.valid_access_valid_block\n                        _ _ _ _ (Mem.valid_access_implies\n                                   _ _ _ _ _ Nonempty Haccess ltac:(constructor))).\n    destruct Haccess.\n    assert (Haccess' : Mem.valid_access m' chunk b ofs Writable).\n    { split; auto.\n      intros ? ?.\n      specialize (H _ H1).\n      unfold Mem.perm in *.\n      rewrite po_oo in H.\n      rewrite po_oo.\n      eapply po_trans; eauto.\n    }\n    destruct (Mem.valid_access_dec m' chunk b ofs Writable); try by exfalso.\n    destruct (Mem.valid_access_store _ _ _ _ v' Haccess') as [m2' Hstore'].\n    exists m2'. split; auto.\n    constructor.\n    - intros.\n      assert (Heq1 := MemoryLemmas.mem_store_max _ _ _ _ _ _ Hstore' b0 ofs0).\n      assert (Heq2 := MemoryLemmas.mem_store_cur _ _ _ _ _ _ Hstore' b0 ofs0).\n      assert (Heq3 := MemoryLemmas.mem_store_max _ _ _ _ _ _ Hstore b0 ofs0).\n      assert (Heq4 := MemoryLemmas.mem_store_cur _ _ _ _ _ _ Hstore b0 ofs0).\n      do 2 rewrite getMaxPerm_correct in Heq1.\n      do 2 rewrite getCurPerm_correct in Heq2.\n      do 2 rewrite getMaxPerm_correct in Heq3.\n      do 2 rewrite getCurPerm_correct in Heq4.\n      unfold permission_at in *.\n      eapply Mem.store_valid_block_2 in H1; eauto.\n      destruct k;\n        [rewrite <- Heq1, <- Heq3 | rewrite <- Heq2, <- Heq4];\n        eauto.\n    - intros.\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore').\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore).\n      rewrite ! PMap.gsspec.\n      destruct (peq b0 b). subst b0.\n      apply setN_erasure.\n      apply val_erasure_encode_val; auto. intros. eauto.\n      eauto.\n    - erewrite Mem.nextblock_store with (m1 := m) by eauto.\n      erewrite Mem.nextblock_store with (m2 := m2') (m1 := m') by eauto.\n      eauto.\n  Qed.\n\n  Lemma mem_storev_erased':\n    forall chunk m m' vptr v v' m2\n      (Hstore: Mem.storev chunk m vptr v = Some m2)\n      (Herased: mem_erasure' m m')\n      (Hval_erasure: val_erasure v v') ,\n    exists m2', Mem.storev chunk m' vptr v' = Some m2'\n           /\\ mem_erasure' m2 m2'.\n  Proof.\n    intros.\n    destruct vptr; try discriminate.\n    simpl in *.\n    eapply mem_store_erased'; eauto.\n  Qed.\n\n  Lemma mem_loadv_erased' :\n    forall (chunk : memory_chunk) (m m' : mem) (vptr v : val)\n      (Hload: Mem.loadv chunk m vptr = Some v)\n      (Herased: mem_erasure' m m'),\n      exists v' : val, Mem.loadv chunk m' vptr = Some v' /\\ val_erasure v v'.\n  Proof.\n    intros.\n    inversion Herased.\n    destruct vptr; try by discriminate.\n    simpl in Hload.\n    assert (Hreadable := Mem.load_valid_access _ _ _ _ _ Hload).\n    destruct Hreadable.\n    assert (Hreadable': Mem.valid_access m' chunk b(Int.unsigned i) Readable).\n    { split; auto.\n      intros ? ?.\n      eapply MemoryLemmas.load_valid_block in Hload.\n      specialize (H _ H1).\n      unfold Mem.perm in *.\n      rewrite po_oo in H.\n      rewrite po_oo.\n      eapply po_trans; eauto.\n    }\n    exists (decode_val chunk (Mem.getN (size_chunk_nat chunk) (Int.unsigned i)\n                                  (m'.(Mem.mem_contents)#b))).\n    Transparent Mem.load.\n    unfold Mem.load. split.\n    apply pred_dec_true; auto.\n    exploit Mem.load_result; eauto. intro. rewrite H1.\n    apply decode_val_erasure; auto.\n    apply getN_erasure; auto.\n    Opaque Mem.load.\n  Qed.\n\n  Lemma mem_erasure_erasure':\n    forall m m',\n      mem_erasure m m' ->\n      mem_erasure' m m'.\n  Proof.\n    intros. destruct H.\n    split; auto.\n    intros.\n    unfold Mem.valid_block in *.\n    rewrite erased_nb0 in H.\n    erewrite perm_le0 by eauto.\n    simpl. destruct ((Mem.mem_access m) # b ofs k); simpl; constructor.\n  Qed.\n\nEnd MemErasure.\n\n(** Erasure of cores *)\nModule Type CoreErasure (SEM: Semantics).\n  Import SEM ValErasure MemErasure TraceErasure event_semantics.\n\n  Parameter core_erasure : C -> C -> Prop.\n  Parameter core_erasure_refl: forall c, core_erasure c c.\n\n  Parameter at_external_erase:\n    forall c c' (Herase: core_erasure c c'),\n      match at_external Sem c, at_external Sem c' with\n      | Some (ef, vs), Some (ef', vs') =>\n        ef = ef' /\\ val_erasure_list vs vs'\n      | None, None => True\n      | _, _ => False\n      end.\n\n  Parameter after_external_erase:\n    forall v v' c c' c2\n      (HeraseCores: core_erasure c c')\n      (HeraseVal: optionval_erasure v v')\n      (Hafter_external: after_external SEM.Sem v c = Some c2),\n    exists c2',\n      after_external SEM.Sem v' c' = Some c2' /\\\n      core_erasure c2 c2'.\n\n  Parameter erasure_initial_core:\n    forall ge v arg v' arg' c\n      (Hv: val_erasure v v')\n      (Harg: val_erasure arg arg')\n      (Hinit: initial_core Sem ge v [:: arg] = Some c),\n      initial_core Sem ge v' [:: arg'] = Some c.\n\n  Parameter halted_erase:\n    forall c c'\n      (HeraseCores: core_erasure c c')\n      (Hhalted: halted SEM.Sem c),\n      halted SEM.Sem c'.\n\n  Parameter evstep_erase:\n    forall ge c1 c1' c2 ev m1 m1' m2\n      (HeraseCores: core_erasure c1 c1')\n      (Hmem_erasure: mem_erasure m1 m1')\n      (Hstep: ev_step Sem ge c1 m1 ev c2 m2),\n    exists c2' m2' ev',\n      ev_step Sem ge c1' m1' ev' c2' m2' /\\\n      core_erasure c2 c2' /\\ mem_erasure m2 (erasePerm m2') /\\\n      mem_event_list_erasure ev ev'.\n\n  Hint Resolve core_erasure_refl : erased.\n\nEnd CoreErasure.\n\nModule ThreadPoolErasure (SEM: Semantics)\n       (Machines: MachinesSig with Module SEM := SEM)\n       (CE : CoreErasure SEM).\n  Import ValErasure CE\n         Machines DryMachine ThreadPool.\n\n  Definition ctl_erasure c c' : Prop :=\n    match c, c' with\n    | Kinit vf arg, Kinit vf' arg' =>\n      val_erasure vf vf' /\\ val_erasure arg arg'\n    | Krun c, Krun c' =>\n      core_erasure c c'\n    | Kblocked c, Kblocked c' =>\n      core_erasure c c'\n    | Kresume c arg, Kresume c' arg' =>\n      core_erasure c c' /\\ arg = arg'\n    (*we don't use this and our semantics are strange*)\n    | _, _  => False\n    end.\n\n  Inductive threadPool_erasure tp (tp' : ErasedMachine.ThreadPool.t) :=\n  | ErasedPool :\n      num_threads tp = ErasedMachine.ThreadPool.num_threads tp' ->\n      (forall i (cnti: containsThread tp i)\n         (cnti': ErasedMachine.ThreadPool.containsThread tp' i),\n          ctl_erasure (getThreadC cnti)\n                    (ErasedMachine.ThreadPool.getThreadC cnti')) ->\n      threadPool_erasure tp tp'.\n\n  Lemma erasedPool_contains:\n    forall tp1 tp1'\n      (HerasedPool: threadPool_erasure tp1 tp1') i,\n      containsThread tp1 i <-> ErasedMachine.ThreadPool.containsThread tp1' i.\n  Proof.\n    intros.\n    inversion HerasedPool.\n    unfold containsThread, ErasedMachine.ThreadPool.containsThread.\n    rewrite H.\n    split; auto.\n  Qed.\n\n  Lemma ctl_erasure_refl:\n    forall c, ctl_erasure c c.\n  Proof with eauto with val_erasure erased.\n    destruct c; simpl...\n  Qed.\n\n  Lemma erased_updLockSet:\n    forall tp tp' addr addr' rmap rmap',\n      threadPool_erasure tp tp' ->\n      threadPool_erasure (updLockSet tp addr rmap)\n                        (ErasedMachine.ThreadPool.updLockSet tp' addr' rmap').\n  Proof.\n    intros.\n    inversion H.\n    constructor; auto.\n  Qed.\n\n  Lemma erased_updThread:\n    forall tp tp' i (cnti: containsThread tp i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp' i) c c' pmap pmap',\n      threadPool_erasure tp tp' ->\n      ctl_erasure c c' ->\n      threadPool_erasure (updThread cnti c pmap)\n                        (ErasedMachine.ThreadPool.updThread cnti' c' pmap').\n  Proof.\n    intros.\n    inversion H.\n    constructor; auto.\n    intros.\n    destruct (i0 == i) eqn:Heq; move/eqP:Heq=>Heq.\n    subst. rewrite gssThreadCode.\n    rewrite ErasedMachine.ThreadPool.gssThreadCode; auto.\n    rewrite gsoThreadCode; auto.\n    rewrite ErasedMachine.ThreadPool.gsoThreadCode; auto.\n  Qed.\n\n  Lemma erased_addThread:\n    forall tp tp' i (cnti: containsThread tp i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp' i) v arg v' arg' pmap pmap',\n      threadPool_erasure tp tp' ->\n      val_erasure v v' ->\n      val_erasure arg arg' ->\n      threadPool_erasure (addThread tp v arg pmap)\n                        (ErasedMachine.ThreadPool.addThread tp' v arg pmap').\n  Proof with eauto with val_erasure erased.\n    intros.\n    inversion H.\n    constructor.\n    unfold addThread, ErasedMachine.ThreadPool.addThread; simpl. rewrite H2; auto.\n    intros.\n    assert (cnti00 := cntAdd' cnti0).\n    assert (cnti0'0 := ErasedMachine.ThreadPool.cntAdd' cnti'0).\n    destruct cnti00 as [[cnti00 ?] | Heq];\n      destruct cnti0'0 as [[cnti0'0 ?] | ?].\n    - erewrite gsoAddCode with (cntj := cnti00) by eauto.\n      erewrite ErasedMachine.ThreadPool.gsoAddCode with (cntj := cnti0'0) by eauto.\n      eauto.\n    - exfalso; subst; apply H4.\n      destruct (num_threads tp), (ErasedMachine.ThreadPool.num_threads tp');\n        simpl; inversion H2; auto.\n    - exfalso; subst; apply H4.\n      destruct (num_threads tp), (ErasedMachine.ThreadPool.num_threads tp');\n        simpl; inversion H2; auto.\n    - subst. erewrite gssAddCode by eauto.\n      erewrite ErasedMachine.ThreadPool.gssAddCode; eauto.\n      simpl...\n  Qed.\n\n  Lemma erased_remLockSet:\n    forall tp tp' addr addr',\n      threadPool_erasure tp tp' ->\n      threadPool_erasure (remLockSet tp addr)\n                        (ErasedMachine.ThreadPool.remLockSet tp' addr').\n  Proof.\n    intros.\n    inversion H.\n    constructor; auto.\n  Qed.\n\n  Hint Resolve erased_updLockSet erased_updThread\n       erased_addThread erased_remLockSet: erased.\n\nEnd ThreadPoolErasure.\n\n(** ** Erasure from FineConc to SC*)\nModule SCErasure (SEM: Semantics) (SemAxioms: SemanticsAxioms SEM)\n       (Machines: MachinesSig with Module SEM := SEM)\n       (AsmContext: AsmContext SEM Machines)\n       (CE : CoreErasure SEM).\n  Module ThreadPoolErasure := ThreadPoolErasure SEM Machines CE.\n  Import ValErasure MemErasure TraceErasure CE ThreadPoolErasure.\n  Import Machines DryMachine ThreadPool AsmContext.\n  Module Executions := Executions SEM SemAxioms Machines AsmContext.\n  Import Executions.\n\n  Import event_semantics.\n  (** ** Simulation for syncStep, startStep, resumeStep, suspendStep,\n  and haltedStep *)\n\n  Lemma syncStep_erase:\n    forall ge tp1 tp1' m1 m1' tp2 m2 i ev\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hmem_erasure: mem_erasure m1 m1')\n      (Hcomp1: mem_compatible tp1 m1)\n      (Hcomp1': ErasedMachine.mem_compatible tp1' m1')\n      (Hstep: syncStep false ge cnti Hcomp1 tp2 m2 ev),\n    exists tp2' m2',\n      ErasedMachine.syncStep false ge cnti' Hcomp1' tp2' m2' (eraseSyncEvent ev) /\\\n      threadPool_erasure tp2 tp2' /\\ mem_erasure m2 m2'.\n  Proof with eauto with val_erasure erased.\n    intros.\n    Hint Resolve mem_erasure_restr : erased.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst;\n    match goal with\n    | [H: ctl_erasure ?Expr1 ?Expr2, H1: ?Expr1 = _ |- _] =>\n      rewrite H1 in H; simpl in H;\n      destruct Expr2 eqn:?\n    end; try (by exfalso);\n    try match goal with\n        | [H: Mem.load _ _ _ _ = Some _ |- _] =>\n          eapply mem_load_erased in H; eauto with val_erasure erased;\n          destruct Hload as [? [Hload ?]]\n        end;\n    try match goal with\n        | [H: Mem.store _ _ _ _ _ = Some _ |- _] =>\n          eapply mem_store_erased in H; eauto with val_erasure erased;\n          destruct Hstore as [m2' [Hstore Hmem_erasure']]\n        end;\n    try match goal with\n        | [|- _ <> Vundef] => intro Hcontra; discriminate\n        end;\n    match goal with\n    | [H: at_external _ _ = _, H1: core_erasure _ _ |- _] =>\n      pose proof (at_external_erase H1);\n        match goal with\n        | [H2: match at_external _ _ with _ => _ end |- _] =>\n          rewrite H in H2;\n            match goal with\n            | [H3: match at_external ?E1 ?E2 with _ => _ end |- _] =>\n              destruct (at_external E1 E2) as [[? ?]|] eqn:?; try by exfalso\n            end\n        end\n    end;\n    repeat match goal with\n           | [H: _ /\\ _ |- _] => destruct H\n           | [H: val_erasure_list _ _ |- _] =>\n             inv H\n           | [H: val_erasure (Vptr _ _) _ |- _] => inv H\n           | [H:val_erasure (Vint _) _ |- _] => inv H\n           end; subst.\n    - exists (ErasedMachine.ThreadPool.updThreadC cnti' (Kresume c0 Vundef)), m2'.\n      split; [econstructor; eauto | split; eauto].\n      constructor. simpl; eauto.\n      intros j cntj cntj'.\n      rewrite gLockSetCode.\n      destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n      + subst.\n        rewrite gssThreadCode.\n        rewrite ErasedMachine.ThreadPool.gssThreadCC.\n        simpl; auto.\n      + rewrite gsoThreadCode; auto.\n        assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n        erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n          by eauto.\n        inversion HerasePool; eauto.\n    - exists (ErasedMachine.ThreadPool.updThreadC cnti' (Kresume c0 Vundef)), m2'.\n      split; [econstructor; eauto | split; eauto].\n      constructor. simpl; eauto.\n      intros j cntj cntj'.\n      rewrite gLockSetCode.\n      destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n      + subst.\n        rewrite gssThreadCode.\n        rewrite ErasedMachine.ThreadPool.gssThreadCC.\n        simpl; auto.\n      + rewrite gsoThreadCode; auto.\n        assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n        erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n          by eauto.\n        inversion HerasePool; eauto.\n    - exists (ErasedMachine.ThreadPool.addThread\n           (ErasedMachine.ThreadPool.updThreadC cnti' (Kresume c0 Vundef))\n           (Vptr b ofs) v'0 tt), m1'.\n      split; [econstructor; eauto | split; eauto].\n      constructor. simpl; eauto. rewrite Hnum. auto.\n      intros j cntj cntj'.\n      assert (cntj0 := cntAdd' cntj).\n      destruct cntj0 as [[cntj0 ?] | Heq].\n      + (* case it's an old thread*)\n        erewrite @gsoAddCode with (cntj := cntj0) by eauto.\n        assert (cntj00 := cntUpdate' cntj0).\n        assert (cntj00': ErasedMachine.ThreadPool.containsThread tp1' j)\n          by (unfold containsThread,ErasedMachine.ThreadPool.containsThread;\n               rewrite <- Hnum; auto).\n        assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC (Kresume c0 Vundef)\n                                                              cnti' cntj00').\n        erewrite @ErasedMachine.ThreadPool.gsoAddCode with (cntj := cntj0')\n          by eauto.\n        destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n        * subst.\n          rewrite gssThreadCode.\n          rewrite ErasedMachine.ThreadPool.gssThreadCC.\n          simpl; auto.\n        * rewrite gsoThreadCode; auto.\n          erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj00')\n            by eauto.\n          inversion HerasePool; eauto.\n      + (*case j is the just added thread *)\n        subst.\n        erewrite gssAddCode by (unfold latestThread; reflexivity).\n        erewrite ErasedMachine.ThreadPool.gssAddCode\n          by (unfold ErasedMachine.ThreadPool.latestThread;\n               simpl; rewrite Hnum; auto).\n        simpl; auto.\n    - exists (ErasedMachine.ThreadPool.updThreadC cnti' (Kresume c0 Vundef)), m2'.\n      split; [econstructor; eauto | split; eauto].\n      constructor. simpl; eauto.\n      intros j cntj cntj'.\n      rewrite gLockSetCode.\n      destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n      + subst.\n        rewrite gssThreadCode.\n        rewrite ErasedMachine.ThreadPool.gssThreadCC.\n        simpl; auto.\n      + rewrite gsoThreadCode; auto.\n        assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n        erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n          by eauto.\n        inversion HerasePool; eauto.\n    - exists (ErasedMachine.ThreadPool.updThreadC cnti' (Kresume c0 Vundef)), m1'.\n      split; [econstructor; eauto | split; eauto].\n      constructor. simpl; eauto.\n      intros j cntj cntj'.\n      rewrite gRemLockSetCode.\n      destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n      + subst.\n        rewrite gssThreadCode.\n        rewrite ErasedMachine.ThreadPool.gssThreadCC.\n        simpl; auto.\n      + rewrite gsoThreadCode; auto.\n        assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n        erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n          by eauto.\n        inversion HerasePool; eauto.\n    - exists tp1', m1'.\n      split; [econstructor; eauto | split; eauto].\n  Qed.\n\n  Global Ltac pf_cleanup :=\n    repeat match goal with\n           | [H1: invariant ?X, H2: invariant ?X |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: mem_compatible ?TP ?M, H2: mem_compatible ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr);\n               subst H2\n           | [H1: is_true (leq ?X ?Y), H2: is_true (leq ?X ?Y) |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M, H2: containsThread ?TP ?M |- _] =>\n             assert (H1 = H2) by (by eapply proof_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThreadC _ ?TP _ _) ?M |- _] =>\n             apply cntUpdateC' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           | [H1: containsThread ?TP ?M,\n                  H2: containsThread (@updThread _ ?TP _ _ _) ?M |- _] =>\n             apply cntUpdate' in H2;\n               assert (H1 = H2) by (by eapply cnt_irr); subst H2\n           end.\n\n  Lemma startStep_erasure:\n    forall ge tp1 tp1' tp2 i\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hstep: FineConc.start_thread ge cnti tp2),\n    exists tp2',\n      SC.start_thread ge cnti' tp2' /\\\n      threadPool_erasure tp2 tp2'.\n  Proof.\n    intros.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst.\n    pf_cleanup;\n      match goal with\n        [H: ctl_erasure ?Expr1 ?Expr2, H1: ?Expr1 = _ |- _] =>\n        rewrite H1 in H; simpl in H;\n        destruct Expr2 eqn:?\n      end; try (by exfalso).\n    repeat match goal with\n           | [H: _ /\\ _ |- _] => destruct H\n           | [H: val_erasure_list _ _ |- _] =>\n             inv H\n           | [H: val_erasure (Vptr _ _) _ |- _] => inv H\n           end; subst.\n    eapply erasure_initial_core in Hinitial; eauto.\n    exists (ErasedMachine.ThreadPool.updThreadC cnti' (Krun c_new)).\n    split; econstructor; eauto.\n    unfold ErasedMachine.invariant; auto.\n    intros j cntj cntj'.\n    destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n    + subst.\n      rewrite gssThreadCC.\n      rewrite ErasedMachine.ThreadPool.gssThreadCC.\n      simpl. apply core_erasure_refl.\n    +\n      assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n      assert (cntj0 := cntUpdateC' cntj).\n      erewrite <- @gsoThreadCC with (cntj :=  cntj0) by eauto.\n      erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n        by eauto.\n      inversion HerasePool; eauto.\n  Qed.\n\n  Lemma resumeStep_erasure:\n    forall tp1 tp1' tp2 i\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hstep: FineConc.resume_thread cnti tp2),\n    exists tp2',\n      SC.resume_thread cnti' tp2' /\\\n      threadPool_erasure tp2 tp2'.\n  Proof.\n    intros.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst.\n    pf_cleanup;\n      match goal with\n        [H: ctl_erasure ?Expr1 ?Expr2, H1: ?Expr1 = _ |- _] =>\n        rewrite H1 in H; simpl in H;\n        destruct Expr2 eqn:?\n      end; try (by exfalso).\n    destruct Hthreads as [HeraseCores Heq]. subst v.\n    pose proof (at_external_erase HeraseCores).\n    rewrite Hat_external in H.\n    destruct X.\n    destruct (at_external SEM.Sem c0) eqn:Hat_external'; try by exfalso.\n    destruct p as [? ?].\n    destruct H as [? ?]; subst.\n    eapply after_external_erase with (v' := None) in Hafter_external;\n      simpl;\n      eauto with val_erasure erased.\n    destruct Hafter_external as [c2' [Hafter_external' Hcore_erasure']].\n    exists (ErasedMachine.ThreadPool.updThreadC cnti' (Krun c2')).\n    split.\n    eapply SC.ResumeThread with (c := c0); simpl in *; eauto.\n    unfold ErasedMachine.invariant; auto.\n    constructor.\n    simpl. auto.\n    intros j cntj cntj'.\n    destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n    + subst.\n      rewrite gssThreadCC.\n      rewrite ErasedMachine.ThreadPool.gssThreadCC.\n      simpl; eauto.\n    +\n      assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n      assert (cntj0 := cntUpdateC' cntj).\n      erewrite <- @gsoThreadCC with (cntj :=  cntj0) by eauto.\n      erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n        by eauto.\n      inversion HerasePool; eauto.\n  Qed.\n\n  Lemma suspendStep_erasure:\n    forall tp1 tp1' tp2 i\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hstep: FineConc.suspend_thread cnti tp2),\n    exists tp2',\n      SC.suspend_thread cnti' tp2' /\\\n      threadPool_erasure tp2 tp2'.\n  Proof.\n    intros.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst.\n    pf_cleanup;\n      match goal with\n        [H: ctl_erasure ?Expr1 ?Expr2, H1: ?Expr1 = _ |- _] =>\n        rewrite H1 in H; simpl in H;\n        destruct Expr2 eqn:?\n      end; try (by exfalso).\n    pose proof (at_external_erase Hthreads).\n    rewrite Hat_external in H.\n    destruct X.\n    destruct (at_external SEM.Sem c0) eqn:Hat_external'; try by exfalso.\n    destruct p as [? ?].\n    destruct H as [? ?]; subst.\n    exists (ErasedMachine.ThreadPool.updThreadC cnti' (Kblocked c0)).\n    split.\n    eapply SC.SuspendThread with (c := c0); simpl in *; eauto.\n    unfold ErasedMachine.invariant; auto.\n    constructor.\n    simpl. auto.\n    intros j cntj cntj'.\n    destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n    + subst.\n      rewrite gssThreadCC.\n      rewrite ErasedMachine.ThreadPool.gssThreadCC.\n      simpl; eauto.\n    +\n      assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n      assert (cntj0 := cntUpdateC' cntj).\n      erewrite <- @gsoThreadCC with (cntj :=  cntj0) by eauto.\n      erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n        by eauto.\n      inversion HerasePool; eauto.\n  Qed.\n\n  Lemma haltStep_erasure:\n    forall tp1 tp1' i\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hstep: threadHalted cnti),\n      ErasedMachine.threadHalted cnti'.\n  Proof.\n    intros.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst.\n    pf_cleanup.\n    rewrite Hcode in Hthreads.\n    simpl in Hthreads.\n    destruct (ErasedMachine.ThreadPool.getThreadC cnti') eqn:?;\n             try by exfalso.\n    assert (halted SEM.Sem c0)\n      by (eapply halted_erase; eauto).\n    econstructor; eauto.\n  Qed.\n\n  Lemma threadStep_erase:\n    forall ge tp1 tp1' m1 m1' tp2 m2 i ev\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (cnti: containsThread tp1 i)\n      (cnti': ErasedMachine.ThreadPool.containsThread tp1' i)\n      (Hmem_erasure: mem_erasure m1 m1')\n      (Hcomp1: mem_compatible tp1 m1)\n      (Hcomp1': ErasedMachine.mem_compatible tp1' m1')\n      (Hstep: threadStep ge cnti Hcomp1 tp2 m2 ev),\n    exists tp2' m2' ev',\n      ErasedMachine.threadStep ge cnti' Hcomp1' tp2' m2' ev' /\\\n      threadPool_erasure tp2 tp2' /\\ mem_erasure m2 (erasePerm m2') /\\\n      mem_event_list_erasure ev ev'.\n  Proof.\n    intros.\n    inversion HerasePool as [Hnum Hthreads].\n    specialize (Hthreads _ cnti cnti').\n    inversion Hstep; subst.\n    pf_cleanup;\n      match goal with\n        [H: ctl_erasure ?Expr1 ?Expr2, H1: ?Expr1 = _ |- _] =>\n        rewrite H1 in H; simpl in H;\n        destruct Expr2 eqn:?\n      end; try (by exfalso).\n    eapply mem_erasure_restr with (Hlt := (Hcomp1 i cnti).1) in Hmem_erasure.\n    eapply evstep_erase in Hcorestep; eauto.\n    destruct Hcorestep as (c2' & m2' & ev' & Hevstep' & Hcore_erasure'\n                           & Hmem_erasure' & Hev_erasure).\n    exists (ErasedMachine.ThreadPool.updThreadC cnti' (Krun c2')), m2', ev'.\n    split; eauto.\n    econstructor; eauto.\n    split; eauto.\n    constructor; eauto.\n    intros j cntj cntj'.\n    destruct (i == j) eqn:Hij; move/eqP:Hij=>Hij.\n    + subst.\n      rewrite gssThreadCode.\n      rewrite ErasedMachine.ThreadPool.gssThreadCC.\n      simpl; eauto.\n    +\n      assert (cntj0' := ErasedMachine.ThreadPool.cntUpdateC' cntj').\n      assert (cntj0 := cntUpdate' cntj).\n      erewrite  @gsoThreadCode with (cntj :=  cntj0) by eauto.\n      erewrite <- @ErasedMachine.ThreadPool.gsoThreadCC with (cntj := cntj0')\n        by eauto.\n      inversion HerasePool; eauto.\n  Qed.\n\n  Notation fstep := (corestep fine_semantics).\n  Notation scstep := (corestep sc_semantics).\n\n  (** A step on the FineConc machine can be matched by a step on the\n  SC machine producing an erased event *)\n  Lemma sc_sim:\n    forall ge tp1 tp1' i U tr1 tr1' tr2 m1 m1' tp2 m2\n      (HerasePool: threadPool_erasure tp1 tp1')\n      (Hmem_erasure: mem_erasure m1 m1')\n      (Hfstep: fstep ge (i :: U, tr1, tp1) m1 (U, tr2, tp2) m2),\n    exists tp2' m2' tr2',\n      scstep ge (i :: U, tr1', tp1') m1' (U, tr2', tp2') m2' /\\\n      threadPool_erasure tp2 tp2' /\\ mem_erasure m2 m2' /\\\n      (trace_erasure tr1 tr1' -> trace_erasure tr2 tr2').\n  Proof with eauto with trace_erasure mem_erasure.\n    intros.\n    inversion Hfstep; simpl in *; subst;\n    inv HschedN;\n    try match goal with\n        | [H: containsThread _ ?I |- _ ] =>\n          assert (ErasedMachine.ThreadPool.containsThread tp1' I)\n            by (eapply erasedPool_contains; eauto)\n        end;\n    assert (Hcomp1' : ErasedMachine.mem_compatible tp1' m1')\n      by (unfold ErasedMachine.mem_compatible; auto).\n    - assert (Hstep' := startStep_erasure HerasePool H Htstep).\n      destruct Hstep' as [tp2' [Hstart' HerasePool']].\n      exists tp2', m1', tr1'.\n      split. econstructor 1; simpl; eauto.\n      split; eauto.\n    - assert (Hstep' := resumeStep_erasure HerasePool H Htstep).\n      destruct Hstep' as [tp2' [Hstart' HerasePool']].\n      exists tp2', m1', tr1'.\n      split. econstructor 2; simpl; eauto.\n      split; eauto.\n    - assert (Htstep' := threadStep_erase HerasePool H Hmem_erasure Hcomp1' Htstep).\n      destruct Htstep' as (tp2' & m2' & ev' & Htstep' & HerasePool'\n                           & Hmem_erasure' & Htr_erasure').\n      exists tp2', (erasePerm m2'), (tr1' ++ map [eta Events.internal tid] ev').\n      split.\n      eapply SC.thread_step; eauto.\n      split...\n    - assert (Hstep' := suspendStep_erasure HerasePool H Htstep).\n      destruct Hstep' as [tp2' [Hstart' HerasePool']].\n      exists tp2', m1', tr1'.\n      split. econstructor 4; simpl; eauto.\n      split; eauto.\n    - assert (Hstep' := syncStep_erase HerasePool H Hmem_erasure Hcomp1' Htstep).\n      destruct Hstep' as (tp2' & m2' & Hstep' & HerasePool' & Hmem_erasure').\n      exists tp2', m2', (tr1' ++ [:: Events.external tid (eraseSyncEvent ev)]).\n      split.\n      eapply SC.sync_step; eauto.\n      split...\n    - eapply haltStep_erasure with (cnti' := H) in Hhalted; eauto.\n      exists tp1', m1', tr1';\n        split; eauto.\n      econstructor 6; simpl; eauto.\n    - assert (~ ErasedMachine.ThreadPool.containsThread tp1' tid).\n      { intros Hcontra.\n        destruct HerasePool as [Hnum _].\n        unfold containsThread, ErasedMachine.ThreadPool.containsThread in *.\n        rewrite <- Hnum in Hcontra.\n        auto.\n      }\n      exists tp1', m1',tr1'.\n      split.\n      econstructor 7; simpl; eauto.\n      split; eauto.\n  Qed.\n\n  Notation sc_safe := (SC.fsafe the_ge).\n  Notation fsafe := (FineConc.fsafe the_ge).\n\n  Lemma fsafe_execution:\n    forall tpf mf U tr,\n      fsafe tpf mf U (size U).+1 ->\n      exists tpf' mf' tr',\n        fine_execution (U, tr, tpf) mf ([::], tr ++ tr', tpf') mf'.\n  Proof.\n    intros.\n    generalize dependent mf.\n    generalize dependent tpf.\n    generalize dependent tr.\n    induction U; intros.\n    do 2 eexists. exists [::].\n    erewrite cats0.\n    econstructor 1; eauto.\n    simpl in *.\n    inversion H; subst.\n    simpl in H0; by exfalso.\n    simpl in *.\n    assert (exists ev,\n               FineConc.MachStep the_ge ((a :: U), tr, tpf) mf\n                                 (U, tr ++ ev, tp') m')\n      by (eapply fstep_trace_irr; eauto).\n    destruct H0 as [ev Hstep].\n    specialize (IHU (tr ++ ev) _ _ H2).\n    destruct IHU as (tpf'' & mf'' & tr'' & Hexec).\n    rewrite <- catA in Hexec.\n    exists tpf'', mf'', (ev ++ tr'').\n    econstructor 2; eauto.\n  Qed.\n\n  (** The initial state of the SC machine is an erasure of the initial\n  state of the FineConc machine*)\n Lemma init_erasure:\n    forall f arg U tpsc tpf\n      (HinitSC: sc_init f arg = Some (U, [::], tpsc))\n      (HinitF: tpf_init f arg = Some (U, [::], tpf)),\n      threadPool_erasure tpf tpsc.\n  Proof.\n    intros.\n    unfold sc_init, tpf_init in *.\n    simpl in *. unfold SC.init_machine, FineConc.init_machine in *.\n    unfold init_mach, ErasedMachine.init_mach in *.\n    simpl in *.\n    destruct (initial_core SEM.Sem the_ge f arg); try discriminate.\n    destruct init_perm; try discriminate.\n    inv HinitSC. inv HinitF.\n    unfold initial_machine, ErasedMachine.initial_machine.\n    simpl.\n    econstructor. simpl; eauto.\n    intros.\n    simpl.\n    apply core_erasure_refl; auto.\n  Qed.\n\n  (** Any execution of the FineConc machine resulting in some trace\n    tr' can be matched by an execution of the SC machine with an\n    erased trace *)\n  Lemma execution_sim:\n    forall U U' tpf tpf' mf mf' tpsc msc tr tr' trsc\n      (Hexec: fine_execution (U, tr, tpf) mf (U', tr', tpf') mf')\n      (HerasedPool: threadPool_erasure tpf tpsc)\n      (Hmem_erasure: mem_erasure mf msc),\n    exists tpsc' msc' trsc',\n      sc_execution (U, trsc, tpsc) msc (U', trsc', tpsc') msc' /\\\n      threadPool_erasure tpf' tpsc' /\\ mem_erasure mf' msc' /\\\n      (trace_erasure tr trsc -> trace_erasure tr' trsc').\n  Proof with eauto.\n    intros U.\n    induction U.\n    - intros.\n      inversion Hexec; subst.\n      exists tpsc, msc, trsc.\n      split.\n      econstructor 1. simpl; auto.\n      split...\n    - intros.\n      inversion Hexec; subst.\n      + simpl in H5; by exfalso.\n      + eapply sc_sim with (tr1' := trsc) in H8; eauto.\n        destruct H8 as (tpsc0 & msc0 & tr0 & Hstep0 & HerasedPool0\n                        & Hmem_erasure0 & Htrace_erasure0).\n        specialize (IHU _ _ _ _ _ _ _ _ _ tr0 H9 HerasedPool0\n                        Hmem_erasure0).\n        destruct IHU as (tpsc2' & msc2' & trsc2' & Hsexec & HerasedPool'\n                         & Hmem_erasure' & Htrace_erasure2').\n        exists tpsc2', msc2', trsc2'.\n        split...\n        econstructor...\n  Qed.\n\n  (** Safety of the SC machine*)\n  Lemma fsafe_implies_scsafe:\n    forall sched tpsc tpf mf msc\n      (Hsafe: fsafe tpf mf sched (size sched).+1)\n      (HerasedPool: threadPool_erasure tpf tpsc)\n      (Hmem_erasure: mem_erasure mf msc),\n      sc_safe tpsc msc sched (size sched).+1.\n  Proof.\n    intro sched.\n    induction sched as [|i sched]; intros.\n    - simpl in *. inversion Hsafe;\n        eapply SC.HaltedSafe with (tr := tr);\n        simpl; auto.\n    - simpl in Hsafe.\n      inversion Hsafe; subst.\n      simpl in H; by exfalso.\n      simpl in *.\n      eapply fstep_trace_irr with (tr'' := [::]) in H0.\n      destruct H0 as [ev Hstep]. simpl in Hstep.\n      eapply sc_sim with (tr1' := [::]) in Hstep; eauto.\n      destruct Hstep as (tpsc2' & msc2' & ? & Hstep & HerasedPool'\n                         & Hmem_erasure' & ?).\n      econstructor 3; eauto.\n  Qed.\n\n  (** Final erasure theorem from FineConc to SC*)\n  Theorem sc_erasure:\n    forall sched f arg U tpsc tpf m\n      (Hmem: init_mem = Some m)\n      (HinitSC: sc_init f arg = Some (U, [::], tpsc))\n      (HinitF: tpf_init f arg = Some (U, [::], tpf))\n      (HsafeF: fsafe tpf (DryMachine.diluteMem m) sched (size sched).+1),\n      sc_safe tpsc (ErasedMachine.diluteMem m) sched (size sched).+1 /\\\n      (forall tpf' mf' tr,\n          fine_execution (sched, [::], tpf) (DryMachine.diluteMem m)\n                         ([::], tr, tpf') mf' ->\n          exists tpsc' msc' tr',\n            sc_execution (sched, [::], tpsc) (ErasedMachine.diluteMem m)\n                         ([::], tr', tpsc') msc' /\\\n            threadPool_erasure tpf' tpsc' /\\ mem_erasure mf' msc' /\\\n      trace_erasure tr tr').\n  Proof with eauto.\n    intros.\n    assert (HpoolErase := init_erasure _ _ HinitSC HinitF).\n    assert (HmemErase : mem_erasure (diluteMem m) (ErasedMachine.diluteMem m)).\n    { eapply mem_erasure_dilute_1.\n      econstructor; eauto.\n      intros.\n      assert (Hvalid: Mem.valid_block m b)\n        by (unfold Mem.valid_block, ErasedMachine.diluteMem, erasePerm in *;\n             simpl in *; auto).\n      assert (Hperm:= erasePerm_V ofs k Hvalid).\n      unfold permission_at in Hperm; auto.\n      simpl.\n      intros.\n      eapply memval_erasure_refl.\n    }\n    split; first by (eapply fsafe_implies_scsafe; eauto).\n    intros.\n    eapply execution_sim with (trsc := [::]) in H; eauto.\n    destruct H as (? & ? & ? & ?& ?& ? & Htrace_erasure).\n    specialize (Htrace_erasure ltac:(by constructor)).\n    do 3 eexists; split...\n  Qed.\n\nEnd SCErasure.\n\n\n\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/SC_erasure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3073580041760868, "lm_q1q2_score": 0.15847990821006813}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import State Monad.\nFrom bpf.monadicmodel Require Import rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n\n(**\n\nPrint get_sub.\nget_sub = \nfun x y : valu32_t => returnM (Val.sub x y)\n     : valu32_t -> valu32_t -> M valu32_t\n\n*)\n\nSection Get_sub.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(val:Type); (val:Type)].\n  Definition res : Type := (val:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_sub.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_sub.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (stateless val32_correct)\n       (dcons (stateless val32_correct)\n                    (DList.DNil _))).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := stateless val32_correct.\n\n  Instance correct_function_get_sub : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _x.\n    get_invariant _y.\n\n    unfold stateless, val32_correct in c1, c2.\n    destruct c1 as (Hc_eq & vi & Hvi_eq).\n    destruct c2 as (Hc0_eq & vj & Hvj_eq).\n    subst.\n\n    (**according to the type of eval_pc:\n         static unsigned long long get_subl(unsigned long long x1, unsigned long long y1)\n       1. return value should be  x+y\n       2. the memory is same\n      *)\n    exists (Val.sub (Vint vi) (Vint vj)), m, Events.E0.\n\n  split_and; unfold step2;auto.\n    -\n      repeat forward_star.\n    - simpl.\n      unfold val32_correct. eauto.\n    - simpl.\n      constructor.\n      reflexivity.\n    - apply unmodifies_effect_refl.\n  Qed.\n\nEnd Get_sub.\n\nExisting Instance correct_function_get_sub.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_sub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.31405054499180746, "lm_q1q2_score": 0.15825200747939241}}
{"text": "(*\n\nIt is inconsistent in Coq to mix Erasable, even when restricted to\nSet->Prop, with proof irrelevance of any Prop that has an extractable\nnon-Prop field - as with Foo in the following proof.\n\nFortunately, no results in mindless-coding require proof irrelevance\nof any kind.\n\n*)\n\n\nInductive Erasable(A : Set) : Prop :=\n  erasable: A -> Erasable A.\nArguments erasable [A] _.\nAxiom Erasable_inj : forall {A : Set}{a b : A}, erasable a=erasable b -> a=b.\n\nInductive Foo : Prop :=\n  foo: nat -> Foo.\n\nAxiom Foo_irrelevance : forall x y, foo x = foo y.\n\nDefinition foo2erasable(f : Foo) : Erasable nat :=\n  match f with\n    | foo x => erasable x\n  end.\n\nTheorem inconsistent: False.\nProof.\n  assert (foo 0 = foo 1) as H by (apply Foo_irrelevance).\n  apply f_equal with (f := foo2erasable) in H.\n  simpl in H.\n  apply Erasable_inj in H.\n  discriminate H.\nQed.\n\nCheck inconsistent.\nPrint Assumptions inconsistent.\n\n", "meta": {"author": "jonleivent", "repo": "mindless-coding", "sha": "5daae7ae5a7c0047a450886c9c9a9a6c430253e5", "save_path": "github-repos/coq/jonleivent-mindless-coding", "path": "github-repos/coq/jonleivent-mindless-coding/mindless-coding-5daae7ae5a7c0047a450886c9c9a9a6c430253e5/erasable_relevance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.29746994260479476, "lm_q1q2_score": 0.15801882180862023}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils.\nRequire Import common.types.\nRequire Import symbolic.symbolic.\nRequire Import symbolic.exec.\nRequire Import cfi.classes.\nRequire Import cfi.abstract.\nRequire Import cfi.symbolic.\nRequire Import cfi.preservation.\nRequire Import cfi.refinementAS.\nRequire Import cfi.rules.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Refinement.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {opss : machine_ops_spec ops}\n        {ids : cfi_id mt}.\n\nVariable cfg : classes.id -> classes.id -> bool.\n\nInstance sp : Symbolic.params := Sym.sym_cfi cfg.\n\nVariable atable : Abs.syscall_table mt.\nVariable stable : Symbolic.syscall_table mt.\n\nDefinition amachine :=  Abs.abstract_cfi_machine atable cfg.\nDefinition smachine := Sym.symbolic_cfi_machine stable.\n\n(*Hypothesis*)\nDefinition refine_sc := RefinementAS.refine_syscalls stable atable stable.\n\n(*TODO: look at arguments mess*)\nHypothesis ref_sc_correct : refine_sc.\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\n\nDefinition backwards_simulation :=\n  RefinementAS.backwards_simulation ref_sc_correct syscall_sem\n                                    syscall_preserves_instruction_tags\n                                    syscall_preserves_valid_jmp_tags\n                                    syscall_preserves_entry_tags.\n\nLemma untag_implies_reg_refinement reg :\n  Sym.registers_tagged reg ->\n  RefinementAS.refine_registers (cfg := cfg) (mapm RefinementAS.untag_atom reg) reg.\nProof.\n  intros RTG r v.\n  split.\n  - intros GET.\n    by rewrite mapmE /= GET.\n  - intros GET.\n    rewrite mapmE /= in GET.\n    destruct (reg r) eqn:GET'.\n    + destruct a. simpl in GET.\n      assert (taga = DATA)\n        by (apply RTG in GET'; assumption).\n      subst.\n      rewrite GET' /= in GET.\n      by inv GET.\n    + rewrite GET' in GET. simpl in GET. congruence.\nQed.\n\nLemma untag_data_implies_dmem_refinement mem :\n  @RefinementAS.refine_dmemory _ _ cfg\n    (mapm RefinementAS.untag_atom (filterm [fun _ => RefinementAS.is_data] mem)) mem.\nProof.\n   intros addr v.\n   split.\n   - intros GET.\n     by rewrite mapmE /= filtermE /= GET.\n   - rewrite mapmE /= filtermE /= => GET.\n     destruct (getm mem) eqn:GET'.\n     + destruct a as [val tg].\n       simpl in GET.\n       destruct tg as [[id|]|]; simpl in GET.\n       * congruence.\n       * congruence.\n       * inv GET. reflexivity.\n     + simpl in GET. congruence.\nQed.\n\nDefinition is_instr (a : atom (mword mt) cfi_tag) :=\n  match taga a with\n    | INSTR _ => true\n    | DATA => false\n  end.\n\nLemma untag_instr_implies_imem_refinement mem :\n  @RefinementAS.refine_imemory _ _ cfg\n    (mapm RefinementAS.untag_atom (filterm [fun _ => is_instr] mem)) mem.\nProof.\n   intros addr v.\n   split.\n   - intros (ut & GET).\n     by rewrite mapmE /= filtermE /= GET.\n   - rewrite mapmE /= filtermE /=.\n     case GET': (getm mem addr) => [[val tg]|] //=.\n     by case: tg GET' => [[id|]|] //= _ [<-]; simpl; eauto.\nQed.\n\nHint Resolve untag_instr_implies_imem_refinement.\nHint Resolve untag_data_implies_dmem_refinement.\nHint Resolve untag_implies_reg_refinement.\n\nTheorem cfg_true_equiv (asi asj : Abs.state mt) ssi ssj :\n  RefinementAS.refine_state stable asi ssi ->\n  RefinementAS.refine_state stable asj ssj ->\n  Abs.step atable cfg asi asj ->\n  Abs.succ atable cfg asi asj ->\n  Symbolic.step stable ssi ssj ->\n  Sym.ssucc stable ssi ssj.\nProof.\n  intros REF REF' ASTEP ASUCC SSTEP.\n  destruct asi as [imem dmem aregs apc b],\n           asj as [imem' dmem' aregs' apc' b'].\n  destruct ssi as [mem regs [spc tpc] int].\n  destruct ssj as [mem' regs' [spc' tpc'] int'].\n  destruct REF as [REFI [REFD [REFR [REFPC [? [? [ITG [VTG ETG]]]]]]]].\n  destruct REF' as [REFI' [REFD' [REFR' [REFPC' ?]]]].\n  unfold Abs.succ in ASUCC.\n  unfold RefinementAS.refine_pc in REFPC; simpl in REFPC;\n  destruct REFPC as [? TPC];\n  unfold RefinementAS.refine_pc in REFPC'; simpl in REFPC';\n  destruct REFPC' as [? TPC'];\n  subst.\n  unfold Sym.ssucc; simpl.\n  destruct (getm imem spc) as [s|] eqn:GET.\n  + destruct (decode_instr s) eqn:INST.\n    - destruct i eqn:DECODE;\n      apply REFI in GET;\n      destruct GET as [id GET'];\n      rewrite GET'; destruct id; rewrite INST; simpl;\n      try assumption;\n      destruct (VTG _ _ ASUCC)\n        as [[? ?] [[? GETSPC'] | [GETSPC' [? [GETCALL ETAG]]]]]; simpl in *;\n      unfold Abs.valid_jmp, valid_jmp in ASUCC;\n      repeat match goal with\n        | [H: getm _ ?Spc = Some _@(INSTR _),\n           H1: getm _ ?Spc = Some _@(INSTR (word_to_id ?Spc)) |- _] =>\n          rewrite H1 in H; inv H\n        | [H: ?Expr = _, H1: context[match ?Expr with _ => _ end] |- _] =>\n           rewrite H in H1\n        | [H: ?Expr = _ |-\n           is_true match ?Expr with _ => _ end] =>\n          rewrite H\n        | [H: is_true match ?Expr with _ => _ end |-\n           is_true match ?Expr with _ => _ end] =>\n          destruct Expr\n      end; try discriminate; by auto.\n    - by discriminate.\n  + destruct (atable spc) eqn:GETCALL.\n    - destruct (getm mem spc) eqn:GET'.\n      { destruct a as [v ut].\n        destruct ut.\n        * assert (EGET': exists id, getm mem spc = Some v@(INSTR id))\n            by (eexists; eauto).\n          apply REFI in EGET'.\n          rewrite EGET' in GET. congruence.\n        * rewrite GET'.\n          destruct (getm dmem spc) eqn:AGET.\n          + discriminate.\n          + apply REFD in GET'.\n            rewrite GET' in AGET. congruence.\n      }\n      { rewrite GET'.\n        unfold refine_sc in *. unfold RefinementAS.refine_syscalls in ref_sc_correct.\n        assert (CALLDOMAINS := RefinementAS.refine_syscalls_domains ref_sc_correct).\n        assert (EGETCALL: exists ac, atable spc = Some ac)\n          by (eexists; eauto).\n        apply CALLDOMAINS in EGETCALL.\n        destruct EGETCALL as [sc GETCALL'].\n        rewrite GETCALL'. reflexivity.\n      }\n    - destruct (getm dmem spc); discriminate.\nQed.\n\nTheorem cfg_false_equiv asi asj ssi ssj :\n  RefinementAS.refine_state stable asi ssi ->\n  RefinementAS.refine_state stable asj ssj ->\n  ~~ Abs.succ atable cfg asi asj ->\n  Symbolic.step stable ssi ssj ->\n  ~~ Sym.ssucc stable ssi ssj.\nProof.\n  intros REF REF' ASUCC SSTEP.\n  unfold Abs.succ in ASUCC.\n  destruct asi as [imem dmem aregs apc b],\n           asj as [imem' dmem' aregs' apc' b'].\n  destruct ssi as [mem reg [pc tpc] int].\n  destruct ssj as [mem' reg' [pc' tpc'] int'].\n  destruct REF as [REFI [REFD [REFR [REFPC [? [? [ITG [VTG [ETG ?]]]]]]]]],\n           REF' as [REFI' [REFD' [REFR' [REFPC' CORRECT']]]].\n  unfold RefinementAS.refine_pc in *.\n  simpl in REFPC; simpl in REFPC'; destruct REFPC as [? TPC],\n                                            REFPC' as [? TPC'].\n  subst.\n  unfold Sym.ssucc.\n  destruct (getm imem pc) as [s|] eqn:GET.\n  { apply REFI in GET.\n    destruct GET as [id GET].\n    destruct (decode_instr s) eqn:INST.\n    { destruct i;\n      simpl; rewrite GET; simpl; rewrite INST; destruct id; auto;\n      unfold Abs.valid_jmp, valid_jmp in ASUCC;\n      destruct (getm mem pc') as [[v [[id|]|]]|] eqn:GET';\n      rewrite GET';\n      try match goal with\n        | [|- is_true (~~ match getm stable _ with _ => _ end)] =>\n          destruct (stable pc') eqn:?\n      end;\n      repeat match goal with\n               | [H: ?Expr = _ |- context[?Expr]] =>\n                 rewrite H; simpl\n               | [H: is_true ?Expr |- context[?Expr] ] =>\n                 rewrite H\n               | [|- is_true (~~ match Symbolic.entry_tag ?S with _ => _ end)] =>\n                 destruct (Symbolic.entry_tag S) as [[?|]|] eqn:?\n             end;\n      repeat match goal with\n               | [H: getm _ _ = Some _@(INSTR (Some _)) |- _] =>\n                 apply ITG in H\n               | [H: getm _ ?Addr = None,\n                  H1: getm stable ?Addr = Some _,\n                  H2: Symbolic.entry_tag _ = INSTR (Some _) |- _] =>\n                 apply (ETG _ _ _ H H1) in H2\n               | [H: context[?Expr], H1: ?Expr = _ |- _] =>\n                 rewrite H1 in H\n             end; by auto.\n    }\n    { simpl. rewrite GET. rewrite INST. destruct id; by reflexivity. }\n  }\n  { destruct (atable pc) eqn:GETCALL.\n    { simpl.\n      destruct (getm dmem pc) eqn:GET'.\n      { apply REFD in GET'. rewrite GET'. reflexivity. }\n      { discriminate. }\n    }\n    { simpl.\n      destruct (getm mem pc) eqn:GET'.\n      { destruct a. destruct taga.\n        { assert (EGET' : exists id, getm mem pc = Some vala@(INSTR id))\n               by (eexists; eauto).\n          apply REFI in EGET'. congruence.\n        }\n        { rewrite GET'. reflexivity. }\n      }\n      { rewrite GET'.\n        assert (SCDOMAINS := RefinementAS.refine_syscalls_domains ref_sc_correct).\n        apply RefinementAS.same_domain_total with (addr' := pc) in SCDOMAINS.\n        apply SCDOMAINS in GETCALL. rewrite GETCALL. reflexivity.\n      }\n    }\n  }\nQed.\n\nProgram Instance cfi_refinementAS  :\n  (machine_refinement amachine smachine) := {\n    refine_state st st' := RefinementAS.refine_state stable st st';\n\n    check st st' := true\n}.\nNext Obligation.\n  split;\n  [intros;\n    destruct (backwards_simulation syscall_preserves_register_tags\n                                   syscall_preserves_jump_tags\n                                   syscall_preserves_jal_tags REF STEP)\n    as [? [? ?]];\n   eexists; split; eauto | discriminate].\nQed.\nNext Obligation.\n  destruct (RefinementAS.backwards_simulation_attacker REF STEPA);\n  eexists; eauto.\nQed.\n\nProgram Instance cfi_refinementAS_specs :\n  machine_refinement_specs cfi_refinementAS.\nNext Obligation.\n  by case: (stepP' stable cst cst') => [H | H]; auto.\nQed.\nNext Obligation. (*initial state*)\n  destruct H as [TPC [ITG [VTG [ETG [RTG ?]]]]].\n  destruct cst as [mem reg [pc tpc] int].\n  exists (Abs.State (mapm RefinementAS.untag_atom (filterm [fun _ => is_instr] mem))\n                    (mapm RefinementAS.untag_atom (filterm [fun _ => RefinementAS.is_data] mem))\n                    (mapm RefinementAS.untag_atom reg) pc true).\n  split.\n  - unfold Abs.initial. reflexivity.\n  - unfold RefinementAS.refine_state. repeat (split; eauto).\n    intros ? ? TPC'.\n    simpl in TPC. rewrite TPC in TPC'; congruence.\n    intros ? ? TPC'. simpl in TPC. rewrite TPC in TPC'.\n    congruence.\nQed.\nNext Obligation.\n  apply (introTF idP).\n  have [?|?] := boolP (Abs.succ atable cfg asi asj).\n  - by eauto using cfg_true_equiv.\n  - apply/negP. by eauto using cfg_false_equiv.\nQed.\nNext Obligation.\n  destruct (Abs.step_succ_violation H0 H1) as [H2 H3].\n  intro CONTRA. assert (CONT := Abs.step_a_violation CONTRA).\n  by rewrite -CONT H2 in H3.\nQed.\nNext Obligation.\n  unfold Abs.stopping in H4.\n  unfold Sym.stopping.\n  destruct H4 as [ALLA ALLS].\n  induction H3\n    as [ast cst REF | ast cst cst' axs' cxs' STEP VIS REF REF' RTRACE' |\n        ast ast' cst cst' axs' cxs' STEP ASTEP' REF REF' RTRACE'|\n        ast ast' cst cst' axs' cxs' NSTEP STEP ASTEP' REF REF' RTRACE'];\n    subst.\n  - split.\n    + intros csi' csj' CONTRA.\n      destruct CONTRA.\n    + move=> csi'; rewrite inE => /eqP {csi'}->.\n      intros (? & CONTRA).\n      destruct (backwards_refinement_normal REF CONTRA) as [VIS CLEAN].\n      clear CLEAN.\n      unfold check in VIS. simpl in VIS.\n      destruct (VIS erefl) as [ast' [ASTEP REF']].\n      unfold Abs.all_stuck in ALLS.\n      have IN: ast \\in [:: ast] by rewrite inE eqxx.\n      apply ALLS in IN.\n      by eauto.\n  - simpl in *.\n    discriminate.\n  - have IN: ast \\in (ast :: ast' :: axs') by rewrite inE eqxx.\n    apply ALLS in IN.\n    by exfalso; eauto.\n  - apply Abs.all_attacker_red in ALLA.\n    split.\n    { apply Abs.all_stuck_red in ALLS.\n      by case: (IHRTRACE' ALLA ALLS)=> [IH IH'];\n      simpl in *; eauto using Sym.all_attacker_step.\n    }\n    { move=> csi'; rewrite inE => /orP [/eqP ? | IN]; subst.\n      - intros (? & CONTRA).\n        destruct (backwards_refinement_normal REF CONTRA) as [CONTRA' H'].\n        clear H'.\n        simpl in CONTRA'.\n        destruct (CONTRA' erefl) as [ast'' [ASTEP REF'']].\n        have IN: ast \\in (ast :: ast' :: axs') by rewrite inE eqxx.\n        specialize (ALLS ast IN).\n        by eauto.\n      - apply Abs.all_stuck_red in ALLS.\n        by move: (IHRTRACE' ALLA ALLS) => [? STUCK]; auto.\n    }\nQed.\n\nTheorem symbolic_cfi : property.cfi smachine.\nProof.\n  eapply backwards_refinement_preserves_cfi.\n  - apply cfi_refinementAS_specs.\n  - apply Abs.cfi.\nQed.\n\nEnd Refinement.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/cfi/preservationAS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.25982563222951205, "lm_q1q2_score": 0.1578864672844204}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Export Coq.Lists.List Coq.Program.Program\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.Common.ilist2\n        Fiat.Common.i2list\n        Fiat.Common.ilist3\n        Fiat.Common.i3list.\n\nRequire Import Coq.Bool.Bool\n        Coq.Strings.String\n        Coq.Structures.OrderedTypeEx\n        Coq.Arith.Arith\n        Fiat.Common.String_as_OT\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.QueryStructure.Specification.Operations.FlattenCompList\n        Fiat.QueryStructure.Implementation.Operations.General.QueryRefinements\n        Fiat.QueryStructure.Implementation.Operations.General.InsertRefinements\n        Fiat.QueryStructure.Implementation.Operations.General.EmptyRefinements\n        Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.QueryStructure.Implementation.ListImplementation\n        Fiat.Common.List.PermutationFacts\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.BagADT\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.QueryStructureImplementation\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.IndexSearchTerms\n        Fiat.QueryStructure.Implementation.Operations.General.DeleteRefinements.\n\nImport Lists.List.ListNotations.\n\nSection BagsQueryStructureRefinements.\n\n  Import Vectors.Vector.VectorNotations.\n\n  Variable qs_schema : RawQueryStructureSchema.\n  Variable BagIndexKeys :\n    ilist3 (B := fun ns => SearchUpdateTerms (rawSchemaHeading ns))\n          (qschemaSchemas qs_schema).\n\n  Lemma i2th_Bounded_Initialize_IndexedQueryStructure {n}\n  : forall ns indices v idx,\n      computes_to (@Initialize_IndexedQueryStructure n ns indices) v\n      -> i3th v idx = Empty_set _.\n  Proof.\n    induction ns.\n    - intros; inversion idx.\n    - intros; revert ns IHns indices v H; pattern n, idx.\n      match goal with\n        |- ?P n idx => simpl; apply (@Fin.caseS P); intros; simpl in *\n      end.\n      + unfold CallBagConstructor in H; simpl in H; computes_to_inv.\n        subst; simpl in *; eauto.\n      + computes_to_inv; subst.\n        eapply IHns; eauto.\n  Qed.\n\n  Corollary refine_QSEmptySpec_Initialize_IndexedQueryStructure\n    : refine {nr' | DelegateToBag_AbsR (imap2 rawRel (Build_EmptyRelations (qschemaSchemas qs_schema))) nr'}\n             (@Initialize_IndexedQueryStructure _ (qschemaSchemas qs_schema) BagIndexKeys).\n  Proof.\n    intros v Comp_v.\n    computes_to_econstructor.\n    unfold IndexedQueryStructure, DelegateToBag_AbsR, GetIndexedRelation.\n    unfold GetUnConstrRelation.\n    unfold DropQSConstraints, QSEmptySpec.\n    intros; simpl; rewrite <- ith_imap2, ith_Bounded_BuildEmptyRelations,\n                   i2th_Bounded_Initialize_IndexedQueryStructure; eauto.\n    intros; eexists List.nil; split;\n    intros; simpl; try rewrite <- ith_imap2, ith_Bounded_BuildEmptyRelations.\n    - split; simpl; intros.\n      + exists 0; unfold UnConstrFreshIdx; intros; intuition.\n      + eexists List.nil; intuition eauto.\n        * inversion H.\n        * inversion H.\n        * econstructor.\n    - split; simpl; intros.\n      + exists 0; unfold UnConstrFreshIdx; intros; intuition.\n      + eexists List.nil; intuition eauto.\n        * inversion H.\n        * inversion H.\n        * econstructor.\n  Qed.\n\n  Definition UpdateIndexedRelation\n             (r_n : IndexedQueryStructure qs_schema BagIndexKeys) idx newRel\n  : IndexedQueryStructure qs_schema BagIndexKeys  :=\n    replace3_Index3 _ _ r_n idx newRel.\n\n  Definition CallBagFind idx (r_n : IndexedQueryStructure qs_schema BagIndexKeys) st :=\n    br <- CallBagMethod idx BagFind r_n st;\n    ret (UpdateIndexedRelation r_n idx (fst br), snd br).\n\n    Definition CallBagDelete idx (r_n : IndexedQueryStructure qs_schema BagIndexKeys) st :=\n    br <- CallBagMethod idx BagDelete r_n st;\n    ret (UpdateIndexedRelation r_n idx (fst br), snd br).\n\n  Definition CallBagInsert idx (r_n : IndexedQueryStructure qs_schema BagIndexKeys) tup :=\n    br <- CallBagMethod idx BagInsert r_n tup;\n    ret (UpdateIndexedRelation r_n idx br).\n\n  Definition CallBagEnumerate idx (r_n : IndexedQueryStructure qs_schema BagIndexKeys) :=\n    br <- CallBagMethod idx BagEnumerate r_n;\n    ret (UpdateIndexedRelation r_n idx (fst br), snd br).\n\n  Lemma get_update_indexed_eq :\n    forall (r_n : IndexedQueryStructure qs_schema BagIndexKeys) idx newRel,\n      GetIndexedRelation (UpdateIndexedRelation r_n idx newRel) idx = newRel.\n  Proof.\n    unfold UpdateIndexedRelation, GetIndexedRelation;\n    intros; simpl; rewrite i3th_replace_Index_eq; eauto using string_dec.\n  Qed.\n\n  Lemma get_update_indexed_neq :\n    forall (r_n : IndexedQueryStructure qs_schema BagIndexKeys) idx idx' newRel,\n      idx <> idx'\n      -> GetIndexedRelation (UpdateIndexedRelation r_n idx newRel) idx' =\n         GetIndexedRelation r_n idx'.\n  Proof.\n    unfold UpdateIndexedRelation, GetIndexedRelation;\n    intros; simpl; rewrite i3th_replace_Index_neq; eauto using string_dec.\n  Qed.\n\n  Lemma exists_UnConstrFreshIdx\n    : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall idx,\n        exists bnd,\n          UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd.\n  Proof.\n    unfold DelegateToBag_AbsR; intros.\n    destruct (H idx) as\n        [l [ [ [bnd fresh_bnd] [l' [l'_eq [l_eqv NoDup_l'] ] ] ]\n              [ [bnd' fresh_bnd'] [l'' [l''_eq [l''_eqv NoDup_l''] ] ] ] ] ];\n      eauto.\n  Qed.\n\n  Lemma refine_Pick_UnConstrFreshIdx\n    : forall r_o\n             (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall idx bnd,\n        UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd\n      -> refine { bnd | UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd}\n                (ret bnd).\n  Proof.\n    intros; refine pick val bnd; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma refine_Query_In_Enumerate\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx : Fin.t _)\n                (resultComp : RawTuple -> Comp (list ResultT)),\n           refine (UnConstrQuery_In r_o idx resultComp)\n                  (l <- Join_Comp_Lists [ inil2 ]\n                     (fun _ =>\n                        l <- CallBagEnumerate idx r_n;\n                      (ret (snd l)));\n                   (List_Query_In l (fun tup : ilist2 (B := @RawTuple) [ _ ]=> resultComp (ilist2_hd tup)))) .\n  Proof.\n    unfold UnConstrQuery_In, QueryResultComp, CallBagEnumerate,\n    CallBagMethod;\n    intros; simpl.\n    setoid_rewrite refineEquiv_bind_bind;\n      setoid_rewrite refineEquiv_bind_unit; simpl.\n    unfold List_Query_In.\n    intros v Comp_v;  computes_to_inv;\n    unfold EnsembleIndexedListEquivalence,\n    UnIndexedEnsembleListEquivalence in *.\n    destruct (H idx); intuition; destruct_ex; intuition; subst.\n    unfold EnsembleIndexedListEquivalence,\n    UnIndexedEnsembleListEquivalence in *;\n      intuition; destruct_ex; intuition; subst.\n    computes_to_econstructor.\n    instantiate (1 := map indexedElement x0);\n      computes_to_econstructor; eauto.\n    setoid_rewrite H0 in H8.\n    setoid_rewrite H4.\n    revert H6 H8 H11 H5 H10; clear; intros.\n    apply NoDup_Permutation in H8; eauto using NoDup_IndexedElement.\n    destruct (@permu_exists _ (map indexedElement x0) x4);\n      intuition.\n    simpl in *; unfold GetNRelSchema in *; rewrite <- H5.\n    eapply Permutation_map; eauto.\n    setoid_rewrite <- H1.\n    eexists x; intuition eauto.\n    eapply Permutation_map in H1.\n    symmetry in H1.\n    eapply NoDup_Permutation_rewrite; eauto.\n    rewrite map_map.\n    first [ rewrite !map_app, !map_map, !app_nil_r in Comp_v'';\n            simpl in *; rewrite map_map in Comp_v''; eauto\n          | repeat setoid_rewrite map_app in Comp_v'';\n            repeat setoid_rewrite map_map in Comp_v''; simpl in *;\n            rewrite app_nil_r in Comp_v''; eauto\n          ].\n  Qed.\n\n  Local Opaque IndexedQueryStructure.\n\n  Lemma refine_Filtered_Query_In_Enumerate\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx : Fin.t _)\n                (resultComp : RawTuple -> Comp (list ResultT)),\n           refine (UnConstrQuery_In r_o idx resultComp)\n                  (l <- Join_Filtered_Comp_Lists [ inil2 ]\n                     (fun _ =>\n                        l <- CallBagEnumerate idx r_n;\n                      (ret (snd l)))\n                     (fun _ => true);\n                   (List_Query_In l (fun tup : ilist2 (B := @RawTuple) [ _ ]=> resultComp (ilist2_hd tup)))) .\n  Proof.\n    intros; rewrite refine_Query_In_Enumerate by eauto.\n    rewrite Join_Filtered_Comp_Lists_id; reflexivity.\n  Qed.\n\n  Local Transparent Query_For.\n\n  Lemma refine_For_Enumerate\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx : Fin.t _)\n                (f : _ -> Comp (list ResultT)),\n           refine (For (l <- CallBagEnumerate idx r_n;\n                        f l))\n                  (l <- CallBagEnumerate idx r_n;\n                   For (f l)).\n  Proof.\n    simpl; intros; unfold Query_For.\n    simplify with monad laws.\n    unfold CallBagEnumerate, CallBagMethod; simpl.\n    unfold refine; intros;  computes_to_inv.\n    subst; repeat computes_to_econstructor; eauto.\n  Qed.\n\n  Lemma refine_Join_Query_In_Enumerate'\n        {n}\n        headings\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx : Fin.t _)\n             (resultComp : ilist2 (n := n) (B:= @RawTuple) headings\n                           -> RawTuple\n                           -> Comp (list ResultT))\n             l,\n        refine (List_Query_In l (fun tup : ilist2 (B := @RawTuple) headings =>\n                                   UnConstrQuery_In r_o idx (resultComp tup)))\n               (l' <- (Join_Comp_Lists l (fun _ => l <- (CallBagEnumerate idx r_n);\n                                          ret (snd l)));\n                List_Query_In l' (fun tup_pair => (resultComp (ilist2_tl tup_pair) (ilist2_hd tup_pair)))).\n  Proof.\n    intros.\n    unfold List_Query_In; induction l; unfold Join_Comp_Lists; simpl.\n    - intros v Comp_v;  computes_to_inv; subst; eauto.\n    - setoid_rewrite IHl; rewrite refine_Query_In_Enumerate; eauto.\n      unfold List_Query_In.\n      setoid_rewrite refineEquiv_bind_bind at 1.\n      setoid_rewrite refineEquiv_bind_bind at 2.\n      intros v Comp_v;  computes_to_inv.\n      subst.\n      rewrite map_app, map_map in Comp_v'; simpl in *.\n      computes_to_econstructor; eauto.\n      apply flatten_CompList_app_inv' in Comp_v'; destruct_ex; intuition.\n      subst; repeat (computes_to_econstructor; eauto).\n      unfold Build_single_Tuple_list in *.\n      rewrite !map_app, !map_map, app_nil_r; simpl; eauto.\n  Qed.\n\n  Corollary refine_Join_Query_In_Enumerate\n            (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx idx' : Fin.t _)\n             (resultComp : RawTuple -> RawTuple -> Comp (list ResultT)),\n        refine (l <- CallBagEnumerate idx r_n;\n                List_Query_In (Build_single_Tuple_list (snd l))\n                              (fun tup =>\n                                 UnConstrQuery_In r_o idx' (resultComp (ilist2_hd tup))))\n               (l <- CallBagEnumerate idx r_n;\n                l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd l))\n                                       (fun _ => l <- (CallBagEnumerate idx' r_n);\n                                        ret (snd l)));\n                List_Query_In l' (fun tup_pair => (resultComp (ilist2_hd (ilist2_tl tup_pair)) (ilist2_hd tup_pair)))).\n  Proof.\n    intros.\n    apply refine_bind; [reflexivity\n                       | simpl; intro ].\n    eapply refine_Join_Query_In_Enumerate' with\n    (l := Build_single_Tuple_list (snd a)); eauto.\n  Qed.\n\n  Corollary refine_Filtered_Join_Query_In_Enumerate'\n            {n}\n        headings\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx : Fin.t _)\n             (resultComp : ilist2 (n := n) ( B:= @RawTuple) headings\n                           -> RawTuple\n                           -> Comp (list ResultT))\n             l,\n        refine (List_Query_In l (fun tup : ilist2 (B:= @RawTuple) headings =>\n                                   UnConstrQuery_In r_o idx (resultComp tup)))\n               (l' <- (Join_Filtered_Comp_Lists l (fun _ => l <- (CallBagEnumerate idx r_n );\n                                                   ret (snd l))\n                                                (fun _ => true));\n                List_Query_In l' (fun tup_pair => (resultComp (ilist2_tl tup_pair) (ilist2_hd tup_pair)))).\n  Proof.\n    intros; rewrite refine_Join_Query_In_Enumerate' by eauto.\n    rewrite Join_Filtered_Comp_Lists_id; reflexivity.\n  Qed.\n\n  Corollary refine_Filtered_Join_Query_In_Enumerate\n            (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx idx' : Fin.t _)\n             (resultComp : RawTuple -> RawTuple -> Comp (list ResultT)),\n        refine (l <- CallBagEnumerate idx r_n ;\n                List_Query_In (Build_single_Tuple_list (snd l))\n                              (fun tup =>\n                                 UnConstrQuery_In r_o idx' (resultComp (ilist2_hd tup))))\n               (l <- CallBagEnumerate idx r_n ;\n                l' <- (Join_Filtered_Comp_Lists (Build_single_Tuple_list (snd l))\n                                       (fun _ => l <- (CallBagEnumerate idx' r_n );\n                                        ret (snd l))\n                                       (fun _ => true));\n                List_Query_In l' (fun tup_pair => (resultComp (ilist2_hd (ilist2_tl tup_pair)) (ilist2_hd tup_pair)))).\n  Proof.\n    intros; rewrite refine_Join_Query_In_Enumerate by eauto.\n    apply refine_bind; [reflexivity\n                       | intro; rewrite Join_Filtered_Comp_Lists_id; reflexivity].\n  Qed.\n\n  (*Lemma refine_Join_Enumerate_Swap\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx idx' : BoundedString)\n             (resultComp : _ -> Comp (list ResultT)),\n        refine (l <- CallBagEnumerate idx r_n ;\n                l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd l))\n                                       (fun _ => l <- (CallBagEnumerate idx' r_n );\n                                        ret (snd l)));\n                List_Query_In l' resultComp)\n               (l <- CallBagEnumerate idx' r_n ;\n                l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd l))\n                                       (fun _ => l <- (CallBagEnumerate idx r_n );\n                                        ret (snd l)));\n                List_Query_In l' (fun tup_pair => (resultComp (icons _ (ilist2_hd (ilist2_tl tup_pair)) (icons _ (ilist2_hd tup_pair) (inil _)))))).\n  Proof.\n  Admitted. *)\n\n  (* Lemma refine_Join_Enumerate_Swap\n        (A B ResultT : Type) :\n    forall (c : Comp A) (c' : Comp B)\n           (resultComp : _ -> _ -> Comp (list ResultT)),\n      refineEquiv (For (l <- c;\n                        l' <- c';\n                        resultComp l l'))\n                  (For (l' <- c';\n                        l <- c;\n                        resultComp l l')).\n  Proof.\n    split; simpl; intros; f_equiv; intros v Comp_v;\n     computes_to_inv; subst;\n    repeat (econstructor; eauto).\n  Qed.*)\n\n  Lemma refine_BagFind_filter\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      ->\n      forall (idx : Fin.t _)\n             filter_dec\n             search_pattern,\n        ExtensionalEq filter_dec\n                      (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n        -> refine (l <- {l | EnsembleIndexedListEquivalence (GetIndexedRelation r_n idx) l};\n                   ret (r_n, filter filter_dec l))\n                  (CallBagFind idx r_n search_pattern).\n  Proof.\n    unfold UnConstrQuery_In, QueryResultComp, CallBagEnumerate,\n    CallBagFind, CallBagMethod, Query_For;\n    intros; simpl.\n    repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    setoid_rewrite (filter_by_equiv _ _ H0).\n    intros v Comp_v.\n    computes_to_inv.\n    destruct (H idx) as [l [? ?] ].\n    destruct H2.\n    pose proof (UnIndexedEnsembleListEquivalence_filter\n                  (DecideableEnsemble_bool (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)) H3).\n    destruct Comp_v as [? ?].\n    pose proof (Permutation_UnIndexedEnsembleListEquivalence' H4 H6).\n    apply permutation_filter in H7; destruct H7 as [l' [? ? ] ]; subst.\n    repeat computes_to_econstructor.\n    econstructor; [eauto | ].\n    eapply Permutation_UnIndexedEnsembleListEquivalence; eauto.\n    unfold UpdateIndexedRelation, GetIndexedRelation.\n    rewrite replace3_Index3_eq.\n    computes_to_econstructor.\n  Qed.\n\n    Lemma refine_filter_BagFind\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      ->\n      forall (idx : Fin.t _)\n             filter_dec\n             search_pattern,\n        ExtensionalEq filter_dec\n                      (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n        -> refine (CallBagFind idx r_n search_pattern)\n                  (l <- {l | EnsembleIndexedListEquivalence (GetIndexedRelation r_n idx) l};\n                   ret (r_n, filter filter_dec l)).\n  Proof.\n    unfold UnConstrQuery_In, QueryResultComp, CallBagEnumerate,\n    CallBagFind, CallBagMethod, Query_For;\n    intros; simpl.\n    repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    setoid_rewrite (filter_by_equiv _ _ H0).\n    intros v Comp_v.\n    computes_to_inv.\n    subst.\n    destruct Comp_v as [? ?].\n    pose proof (UnIndexedEnsembleListEquivalence_filter\n                  (DecideableEnsemble_bool (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)) H2).\n    repeat computes_to_econstructor.\n    eexists; eauto.\n    destruct H1 as [? H1]; eexists; intros ? ?; try eapply H1.\n    apply H4.\n    unfold UpdateIndexedRelation, GetIndexedRelation.\n    rewrite replace3_Index3_eq.\n    computes_to_econstructor.\n  Qed.\n\n  Lemma refine_Query_For_In_Find\n        (ResultT : Type)\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      ->\n      forall (idx : Fin.t _)\n             filter_dec\n             search_pattern\n             (resultComp : RawTuple -> Comp (list ResultT)),\n        ExtensionalEq filter_dec\n                      (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n        -> refine (l <- CallBagEnumerate idx r_n ;\n                   List_Query_In (filter filter_dec (snd l)) resultComp)\n                  (l <- CallBagFind idx r_n search_pattern;\n                   List_Query_In (snd l) resultComp).\n  Proof.\n    intros. setoid_rewrite <- refine_BagFind_filter; eauto.\n    unfold UnConstrQuery_In, QueryResultComp, CallBagEnumerate,\n    CallBagFind, CallBagMethod, Query_For;\n    intros; simpl.\n    simplify with monad laws.\n    repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    reflexivity.\n  Qed.\n\n  Lemma refine_Join_Comp_Lists_To_Find {n}\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall {headings}\n                (l1 : list (ilist2 (n := n) (B:= @RawTuple) headings))\n                (idx : Fin.t _)\n                search_pattern,\n           refine (Join_Filtered_Comp_Lists l1\n                                            (fun _ =>\n                                               l <- CallBagEnumerate idx r_n ;\n                                             ret (snd l))\n                                            (fun a => BagMatchSearchTerm (ith3  BagIndexKeys idx) search_pattern (ilist2_hd a) && true))\n                  (Join_Comp_Lists l1\n                                   (fun _ =>\n                                      l <- CallBagFind idx r_n search_pattern;\n                                    ret (snd l))) .\n  Proof.\n    unfold Join_Filtered_Comp_Lists, Join_Comp_Lists; intros; simpl.\n    induction l1.\n    - simpl; simplify with monad laws; reflexivity.\n    - Local Transparent CallBagMethod.\n      simpl.\n        setoid_rewrite refineEquiv_bind_bind.\n        setoid_rewrite refineEquiv_bind_bind.\n        etransitivity;\n          [ | apply refine_bind;\n              [ eapply (@refine_BagFind_filter _ _ H idx (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern) search_pattern); unfold ExtensionalEq; intuition\n              | unfold pointwise_relation; intros; finish honing] ].\n        setoid_rewrite refineEquiv_bind_bind.\n        setoid_rewrite refineEquiv_bind_bind at 1.\n        setoid_rewrite refineEquiv_bind_bind at 1.\n        setoid_rewrite refineEquiv_bind_bind at 1.\n        repeat setoid_rewrite refineEquiv_bind_unit; simpl;\n        f_equiv; intro.\n        intros v Comp_v.\n        computes_to_inv; subst.\n        generalize (IHl1 _ Comp_v); intros;  computes_to_inv.\n        computes_to_econstructor; subst; eauto.\n        rewrite filter_app, ListFacts.filter_map.\n        simpl.\n        erewrite filter_by_equiv; eauto.\n        unfold ExtensionalEq; intros; rewrite andb_true_r; auto.\n  Qed.\n\n  Lemma refine_Join_Comp_Lists_To_Find_dep {n}\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall {headings}\n                (l1 : list (ilist2 (n := n) (B:= @RawTuple) headings))\n                (idx :Fin.t _)\n                (search_pattern : ilist2 (B:= @RawTuple) headings -> _),\n           refine (Join_Filtered_Comp_Lists l1\n                                            (fun _ =>\n                                               l <- CallBagEnumerate idx r_n ;\n                                             ret (snd l))\n                                            (fun a => BagMatchSearchTerm (ith3  BagIndexKeys idx)\n                                                                         (search_pattern (ilist2_tl a)) (ilist2_hd a) && true))\n                  (Join_Comp_Lists l1\n                                   (fun a =>\n                                      l <- CallBagFind idx r_n (search_pattern a);\n                                    ret (snd l))) .\n  Proof.\n    unfold Join_Filtered_Comp_Lists, Join_Comp_Lists; intros; simpl.\n    induction l1.\n    - simpl; simplify with monad laws; reflexivity.\n    - Local Transparent CallBagMethod.\n      unfold CallBagMethod.\n      simpl.\n      setoid_rewrite refineEquiv_bind_bind.\n      setoid_rewrite refineEquiv_bind_bind.\n      etransitivity;\n        [ | apply refine_bind;\n            [ eapply (@refine_BagFind_filter _ _ H idx (BagMatchSearchTerm (ith3 BagIndexKeys idx) (search_pattern a)) (search_pattern a)); unfold ExtensionalEq; intuition\n            | unfold pointwise_relation; intros; finish honing] ].\n      setoid_rewrite refineEquiv_bind_bind.\n      setoid_rewrite refineEquiv_bind_bind at 1.\n      setoid_rewrite refineEquiv_bind_bind at 1.\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl;\n      f_equiv; intro.\n      setoid_rewrite refineEquiv_bind_bind at 1.\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n      intros v Comp_v.\n       computes_to_inv; subst.\n      generalize (IHl1 _ Comp_v); intros;  computes_to_inv.\n      computes_to_econstructor; subst; eauto.\n      rewrite filter_app, ListFacts.filter_map.\n      simpl.\n      erewrite filter_by_equiv; eauto.\n      unfold ExtensionalEq; intros; rewrite andb_true_r; auto.\n  Qed.\n\n  Instance DecideableEnsemblePair_tail\n           {n}\n           {A}\n           {a}\n           {As}\n           (f : A -> Type)\n           (P : Ensemble (ilist2 (n := n) (B := f) As))\n           (P_dec : DecideableEnsemble P)\n    : DecideableEnsemble (fun ab : ilist2 (B := f) (a :: As) => P (ilist2_tl ab)).\n  Proof.\n    apply Build_DecideableEnsemble with (fun ab => DecideableEnsembles.dec (ilist2_tl ab)).\n    intro; apply (dec_decides_P (DecideableEnsemble := P_dec) (ilist2_tl a0)).\n  Defined.\n\n  Instance DecideableEnsemblePair_head\n           {n}\n           {A}\n           {a}\n           {As}\n           (f : A -> Type)\n           (P : Ensemble (f a))\n           (P_dec : DecideableEnsemble P)\n    : DecideableEnsemble (fun ab : ilist2 (n := S n) (B := f) (a :: As) => P (ilist2_hd ab)).\n  Proof.\n    apply Build_DecideableEnsemble with (fun ab => DecideableEnsembles.dec (ilist2_hd ab)).\n    intro; apply (dec_decides_P (DecideableEnsemble := P_dec) (ilist2_hd a0)).\n  Defined.\n\n  Lemma Join_Comp_Lists_nil\n        {n}\n        {A}\n        {a}\n        {As}\n        (f' : A -> Type)\n  : forall (s2 : _ -> Comp (list (f' a))),\n      refineEquiv (Join_Comp_Lists (n := n) (As := As) (a := a) (List.nil) s2) (ret (List.nil)).\n  Proof.\n    unfold Join_Comp_Lists; simpl; try reflexivity.\n  Qed.\n\n  Lemma filter_and_join_ilist2_hd\n        {n}\n        {A}\n        {a}\n        {As}\n        (f' : A -> Type)\n  : forall\n      (f : f' a -> bool)\n      (s1 : list (ilist2 (n := n) (B := f') As))\n      (s2 : _ -> Comp (list (f' a)))\n      filter_rest ,\n      refineEquiv (l <- (Join_Comp_Lists s1 s2);\n                   ret (filter (fun x : ilist2 (B := f') (a :: As) => f (ilist2_hd x) && filter_rest x) l))\n                  (l <- Join_Comp_Lists s1 (fun a => l <- s2 a; ret (filter f l));\n                   ret (filter filter_rest l)).\n  Proof.\n    split; induction s1; unfold Join_Comp_Lists in *; simpl in *; intros; eauto.\n    - simplify with monad laws; rewrite refineEquiv_bind_unit;\n      reflexivity.\n    - simplify with monad laws; intros v Comp_v;\n       computes_to_inv; subst; computes_to_econstructor; eauto.\n      pose (IHs1 _ (BindComputes _ (fun x => ret (filter filter_rest x)) _ _ Comp_v'0 (ReturnComputes _))).\n       computes_to_inv; subst.\n      repeat (computes_to_econstructor; eauto).\n      repeat rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      rewrite <- filter_and, c'; eauto.\n    - intros v Comp_v;  computes_to_inv; subst; eauto.\n    - simplify with monad laws; intros v Comp_v;\n       computes_to_inv; subst; computes_to_econstructor; eauto.\n      pose proof (IHs1 _ (BindComputes _ (fun x => ret (_ x)) _ _ Comp_v'0 (ReturnComputes _))).\n       computes_to_inv; subst.\n      repeat (computes_to_econstructor; eauto).\n      rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      repeat rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      rewrite <- filter_and, H'; eauto.\n  Qed.\n\n  Corollary filter_join_ilist2_hd\n            {n}\n            {A}\n            {a}\n            {As}\n            (f' : A -> Type)\n  : forall\n      (f : f' a -> bool)\n      (s1 : list (ilist2 (B := f') As))\n      (s2 : _ -> Comp (list (f' a))),\n      refineEquiv (l <- (Join_Comp_Lists s1 s2);\n                   ret (filter (fun x : ilist2 (n := S n) (B := f') (a :: As) => f (ilist2_hd x)) l))\n                  (Join_Comp_Lists s1 (fun a => l <- s2 a; ret (filter f l))).\n  Proof.\n    intros; pose proof (filter_and_join_ilist2_hd f s1 s2 (fun _ => true)).\n    setoid_rewrite filter_and in H; setoid_rewrite filter_true in H.\n    setoid_rewrite H; eauto; setoid_rewrite refineEquiv_unit_bind; reflexivity.\n  Qed.\n\n  Lemma filter_Build_single_Tuple_list\n        {heading}\n        (l : list (@RawTuple heading))\n        (filter_dec : @RawTuple heading -> bool)\n  : filter (fun tup : ilist2 (B:= @RawTuple) [_] => filter_dec (ilist2_hd tup)) (Build_single_Tuple_list l) = Build_single_Tuple_list (filter filter_dec l).\n  Proof.\n    induction l; simpl; eauto.\n    destruct (filter_dec a); simpl; eauto.\n    f_equal; eauto.\n  Qed.\n\n  Corollary refine_Query_For_In_Find_snd'\n            (ResultT : Type)\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      ->\n      forall (idx :Fin.t _)\n             (filter_dec : RawTuple -> bool)\n             search_pattern\n             (resultComp : _ -> Comp (list ResultT)),\n        ExtensionalEq filter_dec\n                      (BagMatchSearchTerm (ith3  BagIndexKeys idx) search_pattern)\n        -> refine (l <- CallBagEnumerate idx r_n ;\n                   List_Query_In (filter (fun tup : ilist2 (B:= @RawTuple) [_] => filter_dec (ilist2_hd tup)) (Build_single_Tuple_list (snd l)))\n                                 resultComp)\n                  (l <- CallBagFind idx r_n search_pattern;\n                   List_Query_In (Build_single_Tuple_list (snd l)) resultComp).\n  Proof.\n    simpl; intros.\n    setoid_rewrite <- refine_BagFind_filter; eauto.\n    setoid_rewrite filter_Build_single_Tuple_list.\n    unfold UnConstrQuery_In, QueryResultComp, CallBagMethod,\n    CallBagFind, CallBagEnumerate, Query_For;\n      intros; simpl.\n    simplify with monad laws.\n    repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl; f_equiv; intro.\n  Qed.\n\n  Corollary refine_Query_For_In_Find_single\n            (ResultT : Type)\n  : forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      forall (idx :Fin.t _)\n             search_pattern\n             (resultComp : _ -> Comp (list ResultT))\n             filter_rest,\n        refine (l <- CallBagEnumerate idx r_n ;\n                List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) [_] => BagMatchSearchTerm _ search_pattern (ilist2_hd a) && filter_rest a) (Build_single_Tuple_list (snd l)))\n                              resultComp)\n               (l <- CallBagFind idx r_n search_pattern;\n                List_Query_In (filter filter_rest (Build_single_Tuple_list (snd l))) resultComp).\n  Proof.\n    simpl; intros.\n    setoid_rewrite <- refine_BagFind_filter; eauto.\n    unfold CallBagMethod, CallBagEnumerate, CallBagFind; simpl; intros.\n    simplify with monad laws.\n    repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl;\n      f_equiv; intro.\n    setoid_rewrite <- filter_Build_single_Tuple_list; rewrite filter_and;\n    f_equiv.\n    intro; reflexivity.\n  Qed.\n\n  Add Parametric Morphism\n      (n : nat)\n      (A : Type)\n      (f : A -> Type)\n      (As : Vector.t A n)\n      (a : A)\n      (l' : list (ilist2 (B := f) As))\n  : (@Join_Comp_Lists n A f As a l')\n      with signature\n      (pointwise_relation _ refineEquiv) ==> refineEquiv\n        as refineEquiv_Join_Comp_Lists.\n  Proof.\n    unfold pointwise_relation; simpl; intros.\n    induction l'; unfold Join_Comp_Lists; simpl.\n    - reflexivity.\n    - rewrite H; setoid_rewrite IHl'; reflexivity.\n  Qed.\n\n  Lemma Join_Comp_Lists_apply_f\n        {n}\n        {A B C : Type}\n        {f : A -> Type}\n  : forall (As : Vector.t A n)\n           (a : A)\n           (l : list (ilist2 (B := f) As))\n           (c : ilist2 (B := f) As -> Comp (list (f a)))\n           (c' : B -> Comp C) (f' : list (ilist2 (B := f) (a :: As)) -> B),\n      refineEquiv (l' <- Join_Comp_Lists l c;\n                   c' (f' l'))\n                  (l' <- (l' <- Join_Comp_Lists l c; ret (f' l'));\n                   c' l').\n  Proof.\n    split; rewrite refineEquiv_bind_bind;\n    setoid_rewrite refineEquiv_bind_unit;\n    intros v Comp_v;  computes_to_inv;\n    try econstructor; eauto.\n  Qed.\n\n  (*Lemma refine_Join_Comp_Lists_filter_search_term_snd\n        {n}\n        (ResultT : Type) :\n    forall (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           headings\n           idx'\n           search_pattern\n           (resultComp : ilist2 (B:= @RawTuple) (_ :: headings) -> Comp (list ResultT))\n           filter_rest\n           cl,\n      refine (l' <- (Join_Comp_Lists (n := n) cl\n                                     (fun _ => l <- CallBagEnumerate idx' r_n ;\n                                      ret (snd l)));\n              List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) (_ :: headings) => BagMatchSearchTerm _ search_pattern (ilist2_hd a) && filter_rest a) l')\n                            resultComp)\n             (l' <- (Join_Comp_Lists cl\n                                     (fun _ => l <- CallBagFind idx' r_n search_pattern;\n                                      ret (snd l)));\n              List_Query_In (filter filter_rest l') resultComp).\n  Proof.\n    intros; unfold CallBagMethod, CallBagEnumerate; simpl.\n    setoid_rewrite <- (refineEquiv_BagFind_filter H); eauto.\n    setoid_rewrite <-\n    repeat setoid_rewrite (refineEquiv_bind_bind);\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    match goal with\n      |- refine (l' <- Join_Comp_Lists ?l ?c; (@?f l')) _ =>\n      setoid_rewrite (Join_Comp_Lists_apply_f l c) with (c' := fun l => List_Query_In l _)\n    end.\n    setoid_rewrite refineEquiv_unit_bind.\n    rewrite (filter_and_join_ilist2_hd\n               (As := headings) (f' := @RawTuple)\n               (BagMatchSearchTerm _ search_pattern)\n               cl\n               (fun _ : ilist2 (B:= @RawTuple) headings =>\n                  {l : list RawTuple |\n                   EnsembleIndexedListEquivalence (GetIndexedRelation r_n idx') l})).\n    simplify with monad laws; f_equiv.\n  Qed.\n\n  Corollary refine_Join_Comp_Lists_filter_search_term_snd'\n            (ResultT : Type) :\n    forall (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           idx idx'\n           search_pattern\n           (resultComp : ilist2 (B:= @RawTuple) [_; _] -> Comp (list ResultT))\n           filter_rest,\n      refine (cl <- CallBagEnumerate idx r_n ;\n              l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                     (fun _ => l <- CallBagEnumerate idx' r_n ;\n                                      ret (snd l)));\n              List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) [_ ; _] => BagMatchSearchTerm _ search_pattern (ilist2_hd a) && filter_rest a) l')\n                            resultComp)\n             (cl <- CallBagEnumerate idx r_n ;\n              l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                     (fun _ => l <- CallBagFind idx' r_n search_pattern;\n                                      ret (snd l)));\n              List_Query_In (filter filter_rest l') resultComp).\n  Proof.\n    intros; apply refine_bind; [reflexivity | intro].\n    apply refine_Join_Comp_Lists_filter_search_term_snd.\n  Qed. *)\n\n  Lemma refine_List_Query_In_Return\n        (ElementT ResultT : Type):\n    forall (l : list ElementT)\n           (f : ElementT -> ResultT),\n      refine (List_Query_In l (fun el => Query_Return (f el)) ) (ret (map f l)).\n  Proof.\n    unfold List_Query_In; induction l; intros; simpl.\n    - reflexivity.\n    - unfold Query_Return; simplify with monad laws;\n      setoid_rewrite IHl; simplify with monad laws;\n      reflexivity.\n  Qed.\n\n  Lemma filter_and_join_ilist2_hd_dep\n        {n}\n        {A}\n        {a}\n        {As : Vector.t A n}\n        (f' : A -> Type)\n  : forall\n      (f : ilist2 (B := f') As -> f' a -> bool)\n      (s1 : list (ilist2 (B := f') As))\n      (s2 : _ -> Comp (list (f' a)))\n      filter_rest,\n      refineEquiv (l <- (Join_Comp_Lists s1 s2);\n                   ret (filter (fun x : ilist2 (B := f') (a :: As) => f (ilist2_tl x) (ilist2_hd x) && filter_rest x) l))\n                  (l <- Join_Comp_Lists s1 (fun a => l <- s2 a; ret (filter (f a) l));\n                   ret (filter filter_rest l)).\n  Proof.\n    split; induction s1; unfold Join_Comp_Lists in *; simpl in *; intros; eauto.\n    - simplify with monad laws; rewrite refineEquiv_bind_unit; reflexivity.\n    - simplify with monad laws; intros v Comp_v;\n       computes_to_inv; subst; computes_to_econstructor; eauto.\n      pose (IHs1 _ (BindComputes _ (fun x => ret (_ x)) _ _ Comp_v'0 (ReturnComputes _))).\n       computes_to_inv; subst.\n      repeat (computes_to_econstructor; eauto).\n      repeat rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      rewrite <- filter_and, c'; eauto.\n    - intros v Comp_v;  computes_to_inv; subst; eauto.\n    - simplify with monad laws; intros v Comp_v;\n       computes_to_inv; subst; computes_to_econstructor; eauto.\n      pose proof (IHs1 _ (BindComputes _ (fun x => ret (_ x)) _ _ Comp_v'0 (ReturnComputes _))).\n       computes_to_inv; subst.\n      repeat (computes_to_econstructor; eauto).\n      rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      repeat rewrite filter_app, ListFacts.filter_map; simpl; eauto.\n      rewrite <- filter_and, H'; eauto.\n  Qed.\n\n  Lemma refine_Join_Comp_Lists_filter_search_term_snd_dep\n        {n}\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           (_ : DelegateToBag_AbsR r_o r_n)\n           (headings : Vector.t _ n)\n           idx'\n           (search_pattern : _ -> _)\n           (resultComp : ilist2 (B:= @RawTuple) (_ :: headings) -> Comp (list ResultT))\n           filter_rest\n           (cl : list (ilist2 (B:= @RawTuple) headings)),\n      refine (l' <- (Join_Comp_Lists cl\n                                     (fun _ => l <- CallBagEnumerate idx' r_n ;\n                                      ret (snd l)));\n              List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) (_ :: headings) => BagMatchSearchTerm _ (search_pattern (ilist2_tl a)) (ilist2_hd a) && filter_rest a) l')\n                            resultComp)\n             (l' <- (Join_Comp_Lists cl\n                                     (fun tup => l <- CallBagFind idx' r_n (search_pattern tup);\n                                      ret (snd l)));\n              List_Query_In (filter filter_rest l') resultComp).\n  Proof.\n    intros; unfold CallBagMethod; simpl.\n    etransitivity;\n      [\n      | rewrite <- refine_Join_Comp_Lists; [reflexivity |\n                                            intro;\n                                              setoid_rewrite <- (@refine_BagFind_filter _ _ H idx' (BagMatchSearchTerm (ith3 BagIndexKeys idx') (search_pattern a)) (search_pattern a)); [finish honing | intro; reflexivity] ] ].\n    repeat setoid_rewrite (refineEquiv_bind_bind);\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    match goal with\n      |- refine (l' <- @Join_Comp_Lists ?n ?A ?f ?As ?a ?l ?c ; _) _ =>\n      pose proof (fun B C => @Join_Comp_Lists_apply_f n A B C f As a l c) as H'';\n        setoid_rewrite H''\n    end.\n    setoid_rewrite refineEquiv_unit_bind.\n    etransitivity.\n    2: unfold List_Query_In; etransitivity.\n    Focus 3.\n    (* 3: { *)\n      apply refine_under_bind.\n      intros; set_evars.\n      rewrite <- refineEquiv_bind_unit with (f := fun x => flatten_CompList (map resultComp x))\n                                            (x := filter filter_rest a).\n      unfold H1; finish honing.\n    (* } *)\n    Focus 2.\n    (* 2: { *)\n         simpl.\n         rewrite <- refine_bind_bind.\n         rewrite <- filter_and_join_ilist2_hd_dep with\n             (f := fun tup =>  (BagMatchSearchTerm (ith3 BagIndexKeys idx')\n                                                   (search_pattern tup)))\n             (filter_rest0 := filter_rest).\n         finish honing.\n    (* } *)\n    simplify with monad laws.\n    rewrite refineEquiv_bind_bind.\n    setoid_rewrite refineEquiv_bind_unit.\n    f_equiv.\n  Qed.\n\n  Lemma realizeable_Enumerate\n  : forall\n      (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n      (r_o : UnConstrQueryStructure qs_schema)\n      idx,\n      DelegateToBag_AbsR r_o r_n ->\n      exists v : list RawTuple,\n        refine\n          (l <- CallBagEnumerate idx r_n ;\n           ret (snd l))\n          (ret v).\n  Proof.\n    intros; destruct (H idx) as [l [l_eqv l_eqv'] ].\n    Local Transparent CallBagMethod.\n    eexists l; unfold CallBagEnumerate, CallBagMethod; simpl; simplify with monad laws.\n    computes_to_econstructor;  computes_to_inv; subst; eauto.\n  Qed.\n\n  Lemma realizeable_Find\n  : forall\n      (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n      (r_o : UnConstrQueryStructure qs_schema)\n      idx st,\n      DelegateToBag_AbsR r_o r_n ->\n      exists v : list RawTuple,\n        refine (l <- CallBagFind idx r_n st;\n                ret (snd l))\n               (ret v).\n  Proof.\n    intros; destruct (H idx) as [l [l_eqv l_eqv'] ].\n    eexists (filter _ l).\n      setoid_rewrite (refine_filter_BagFind H).\n      simplify with monad laws.\n      repeat computes_to_econstructor; eauto.\n      intro; finish honing.\n  Qed.\n\n  Corollary refine_Join_Comp_Lists_filter_search_term_snd_dep'\n            (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           (_ : DelegateToBag_AbsR r_o r_n)\n           idx idx'\n           (search_pattern : _ -> _)\n           (resultComp : ilist2 (B:= @RawTuple) [_; _] -> Comp (list ResultT))\n           filter_rest,\n      refine (cl <- CallBagEnumerate idx r_n ;\n              l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                     (fun _ => l <- CallBagEnumerate idx' r_n ;\n                                      ret (snd l)));\n              List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) [_ ; _] => BagMatchSearchTerm _ (search_pattern (ilist2_tl a)) (ilist2_hd a) && filter_rest a) l')\n                            resultComp)\n             (cl <- CallBagEnumerate idx r_n ;\n              l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                     (fun tup => l <- CallBagFind idx' r_n (search_pattern tup);\n                                      ret (snd l)));\n              List_Query_In (filter filter_rest l') resultComp).\n  Proof.\n    intros; apply refine_bind;\n    [reflexivity\n    | intro;\n      eapply refine_Join_Comp_Lists_filter_search_term_snd_dep; eauto].\n  Qed.\n\n  Lemma refine_Join_Comp_Lists_filter_search_term_fst\n        (ResultT : Type) :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           (_ : DelegateToBag_AbsR r_o r_n)\n           idx\n           heading\n           cl\n           (search_pattern : _)\n           (resultComp : ilist2 (B:= @RawTuple) [heading ; _] -> Comp (list ResultT))\n           (cl_realizable : forall a, exists v, computes_to (cl a) v)\n           filter_rest,\n      refine (l <- CallBagEnumerate idx r_n ;\n              l' <- Join_Comp_Lists (Build_single_Tuple_list (snd l)) cl;\n              List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) [_ ; _] => (BagMatchSearchTerm _ search_pattern (ilist2_hd (ilist2_tl a)) && filter_rest a)) l')\n                            resultComp)\n             (l <- CallBagFind idx r_n search_pattern;\n              l' <- Join_Comp_Lists (Build_single_Tuple_list (snd l)) cl;\n              List_Query_In (filter filter_rest l') resultComp).\n  Proof.\n    intros.\n    setoid_rewrite <- (@refine_BagFind_filter _ _ H idx (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern) search_pattern).\n    intros; unfold CallBagFind, CallBagEnumerate, CallBagMethod; simpl.\n    repeat setoid_rewrite (refineEquiv_bind_bind);\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n    f_equiv; unfold pointwise_relation; intros.\n    let H := match goal with\n                 |- refine (l' <- Join_Comp_Lists ?l ?c; (@?f l')) _ =>\n                 constr:(fun B C => Join_Comp_Lists_apply_f (B := B) (C := C) l c)\n             end in\n    setoid_rewrite H with (c' := fun l => List_Query_In l _).\n    setoid_rewrite <- refineEquiv_unit_bind.\n    setoid_rewrite (filter_and_join_ilist_tail\n               (fun a0 : ilist2 (B:= @RawTuple) [_] =>_ (ilist2_hd a0))\n               (Build_single_Tuple_list a)); eauto.\n    simplify with monad laws; f_equiv.\n    unfold Build_single_Tuple_list; simpl;\n    repeat rewrite ListFacts.filter_map; f_equiv.\n    setoid_rewrite refineEquiv_bind_bind; setoid_rewrite refineEquiv_unit_bind;\n    reflexivity.\n    intro; reflexivity.\n  Qed.\n\n  Lemma refineEquiv_Join_Comp_Lists_Build_single_Tuple_list\n  : forall (r_n : IndexedQueryStructure qs_schema BagIndexKeys) idx,\n      refineEquiv (Join_Comp_Lists [inil2 (B := @RawTuple)]\n                                   (fun _ : ilist2 (B:= @RawTuple) [] =>\n                                      l <- CallBagEnumerate idx r_n ;\n                                    ret (snd l)))\n                  (l <- CallBagEnumerate idx r_n ;\n                   ret (Build_single_Tuple_list (snd l))) .\n  Proof.\n    unfold Join_Comp_Lists, Build_single_Tuple_list; simpl; intros;\n    repeat setoid_rewrite refineEquiv_bind_bind;\n    repeat setoid_rewrite refineEquiv_bind_unit; f_equiv.\n    intros u.\n    rewrite app_nil_r; reflexivity.\n  Qed.\n\n  Lemma refine_BagADT_QSDelete_fst :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx :Fin.t _)\n                (DT : Ensemble RawTuple)\n                (DT_Dec : DecideableEnsemble DT)\n                search_pattern,\n           ExtensionalEq (@DecideableEnsembles.dec _ _ DT_Dec)\n                         (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n           -> refine {x : list RawTuple |\n                      QSDeletedTuples r_o idx DT x}\n                     (l <- (CallBagDelete idx r_n search_pattern);\n                      ret (snd l)).\n  Proof.\n    intros; setoid_rewrite DeletedTuplesFor; auto.\n    rewrite refine_Query_In_Enumerate by eauto.\n    setoid_rewrite refine_List_Query_In_Where.\n    instantiate (1 := _).\n    simpl in *.\n    rewrite (refineEquiv_Join_Comp_Lists_Build_single_Tuple_list r_n idx).\n    setoid_rewrite refineEquiv_bind_bind at 1.\n    setoid_rewrite refineEquiv_bind_bind at 1.\n    setoid_rewrite refineEquiv_bind_unit at 1.\n    setoid_rewrite <- refineEquiv_bind_bind at 1.\n    rewrite (refine_Query_For_In_Find_snd' H _ H0).\n    setoid_rewrite refine_List_Query_In_Return.\n    setoid_rewrite refine_filter_BagFind; eauto; simplify with monad laws.\n    unfold Build_single_Tuple_list; setoid_rewrite map_map; simpl.\n    setoid_rewrite map_id.\n    unfold CallBagFind, CallBagDelete, CallBagMethod;\n      simpl; try simplify with monad laws;\n      repeat setoid_rewrite refineEquiv_bind_bind;\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl;\n      f_equiv; intro.\n    refine pick val _; eauto.\n    erewrite filter_by_equiv; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma refine_BagADT_QSDelete_snd :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx :Fin.t _)\n                (DT : Ensemble RawTuple)\n                (DT_Dec : DecideableEnsemble DT)\n                search_pattern,\n           ExtensionalEq (@DecideableEnsembles.dec _ _ DT_Dec)\n                         (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n           -> refine\n                {r_n' |\n                 DelegateToBag_AbsR\n                   (UpdateUnConstrRelation r_o idx (EnsembleDelete\n                                                      (GetUnConstrRelation r_o idx)\n                                                      DT)) r_n'}\n                (l <- (CallBagDelete idx r_n search_pattern);\n                 ret (fst l)).\n  Proof.\n    intros.\n    computes_to_constructor;  computes_to_inv.\n    unfold CallBagDelete, CallBagMethod in *; simpl in *;  computes_to_inv; subst.\n    simpl.\n    unfold DelegateToBag_AbsR; intros.\n    - destruct (fin_eq_dec idx idx0); subst.\n      + rewrite get_update_unconstr_eq, get_update_indexed_eq.\n        unfold DelegateToBag_AbsR in H.\n        destruct (H idx0) as\n            [l [ [ [bnd fresh_bnd] [l' [l'_eq [l_eqv NoDup_l'] ] ] ]\n                  [ [bnd' fresh_bnd'] [l'' [l''_eq [l''_eqv NoDup_l''] ] ] ] ] ].\n        exists (filter (fun a => negb (DecideableEnsembles.dec a)) l); repeat split.\n        * exists bnd; unfold EnsembleDelete, UnConstrFreshIdx; intros.\n          inversion H2; subst; eauto.\n        * unfold UnIndexedEnsembleListEquivalence;\n          exists (filter (fun a => negb (DecideableEnsembles.dec (indexedElement a))) l'); split; eauto.\n          rewrite <- l'_eq; rewrite ListFacts.filter_map; reflexivity.\n          intuition.\n          apply filter_In; split.\n          eapply l_eqv; inversion H2; eauto.\n          inversion H2; subst; rewrite (proj2 (Decides_false _ _)); eauto.\n          rewrite filter_In in H2; intuition; constructor;\n          [ apply l_eqv; eauto\n          | case_eq (DecideableEnsembles.dec (indexedElement x)); intros H'; rewrite H' in H4;\n            try discriminate;\n            eapply Decides_false in H'; eauto ].\n          eapply NoDup_filter_map with (f := fun a => negb (DecideableEnsembles.dec a)); eauto.\n        * exists bnd'; unfold EnsembleDelete, UnConstrFreshIdx; intros.\n          inversion H2; subst; eauto.\n        * unfold UnIndexedEnsembleListEquivalence;\n          exists (filter (fun a => negb (DecideableEnsembles.dec (indexedElement a))) l''); split; eauto.\n          rewrite <- l''_eq; rewrite ListFacts.filter_map; reflexivity.\n          intuition.\n          apply filter_In; split.\n          eapply l''_eqv; inversion H2; eauto.\n          inversion H2; subst; rewrite (proj2 (Decides_false _ _)); eauto.\n          unfold Complement, Ensembles.In in *.\n          intro; apply H4.\n          rewrite <- H0.\n          apply dec_decides_P; eauto.\n          rewrite filter_In in H2; intuition; constructor;\n          [ apply l''_eqv; eauto\n          | case_eq (DecideableEnsembles.dec (indexedElement x)); intros H'; rewrite H' in H4;\n            try discriminate;\n            eapply Decides_false in H'; eauto ].\n          unfold Complement, Ensembles.In; rewrite <- H0;\n          eapply Decides_false in H'; rewrite H'; congruence.\n          eapply NoDup_filter_map with (f := fun a => negb (DecideableEnsembles.dec a)); eauto.\n      + rewrite get_update_unconstr_neq, get_update_indexed_neq; eauto.\n  Qed.\n\n  Lemma refine_Pick_DelegateToBag_AbsR\n    : forall r_o r_n,\n      DelegateToBag_AbsR r_o r_n\n      -> refine {r_n : IndexedQueryStructure qs_schema BagIndexKeys |\n                 DelegateToBag_AbsR r_o r_n}\n                (ret r_n).\n  Proof.\n    intros; refine pick val r_n; eauto; reflexivity.\n  Qed.\n\n  Lemma refine_BagADT_QSInsert :\n    forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n\n      -> forall (idx :Fin.t _)\n                t freshIdx,\n        UnConstrFreshIdx (GetUnConstrRelation r_o idx) freshIdx\n        -> refine\n             {r_n' |\n               DelegateToBag_AbsR\n                 (UpdateUnConstrRelation r_o idx (\n                                           EnsembleInsert\n                                             {| indexedElement := t; elementIndex := freshIdx |}\n                                             (GetUnConstrRelation r_o idx))) r_n'}\n             (CallBagInsert idx r_n t).\n  Proof.\n    unfold refine; intros.\n    unfold CallBagInsert, CallBagMethod in *; simpl in *; computes_to_inv; subst.\n    computes_to_econstructor; simpl.\n    unfold DelegateToBag_AbsR in *; intuition; intros.\n    intros; destruct (fin_eq_dec idx idx0); subst.\n    - rewrite get_update_unconstr_eq, get_update_indexed_eq.\n      destruct (H idx0) as\n          [l [ [ [bnd fresh_bnd] [l' [l'_eq [l_eqv NoDup_l'] ] ] ]\n                [ [bnd' fresh_bnd'] [l'' [l''_eq [l''_eqv NoDup_l''] ] ] ] ] ].\n      exists (cons t l); repeat split.\n      + exists (S freshIdx); unfold EnsembleInsert, UnConstrFreshIdx; intros.\n        unfold UnConstrFreshIdx in H0; intuition; subst; simpl; eauto.\n      + unfold UnIndexedEnsembleListEquivalence;\n                 exists ({| indexedElement := t; elementIndex := freshIdx |} :: l')%list; intuition.\n        * simpl in *; rewrite l'_eq; trivial.\n        * simpl; destruct H2;\n          [left; symmetry; exact H2\n           | right; apply l_eqv; eauto].\n        * unfold EnsembleInsert; destruct H2;\n          [rewrite <- H2; left; trivial\n           | right; eapply l_eqv; eauto ].\n        * simpl; apply NoDup_cons; eauto.\n          unfold not; intros;\n          apply in_map_iff in H2; destruct H2; destruct H2;\n            apply l_eqv in H3. unfold UnConstrFreshIdx in H0;\n            unfold In in H2; apply H0 in H3;\n            unfold GetNRelSchema in *; omega.\n      + exists (S v1); unfold Ensembles.Add, UnConstrFreshIdx; intros.\n        inversion H2; subst.\n        unfold UnConstrFreshIdx in H1; intuition; subst; simpl; eauto.\n        inversion H3; subst.\n        simpl; eauto.\n      + unfold UnIndexedEnsembleListEquivalence;\n                 exists ({| indexedElement := t; elementIndex := v1 |} :: l'')%list; intuition.\n        * simpl in *; rewrite l''_eq; trivial.\n        * simpl; destruct H2;\n          [right; apply l''_eqv; eauto |\n           left; inversion H2; reflexivity ].\n        * unfold Ensembles.Add; destruct H2;\n          [ right; subst; econstructor\n          | left; eapply l''_eqv; eauto ].\n        * simpl; apply NoDup_cons; eauto.\n          unfold not; intros;\n          apply in_map_iff in H2; destruct H2; destruct H2;\n            apply l''_eqv in H3; unfold UnConstrFreshIdx in H1;\n            unfold In in H2; apply H1 in H3;\n            unfold GetNRelSchema in *; omega.\n      - rewrite get_update_unconstr_neq, get_update_indexed_neq; eauto.\n  Qed.\n\nLemma refine_BagADT_QSInsert' {ResultT}\n     : forall\n         (r_o : UnConstrQueryStructure qs_schema)\n         (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n         (k  : _ -> Comp ResultT) (k' : _ -> Comp ResultT),\n       DelegateToBag_AbsR r_o r_n ->\n       forall (idx : Fin.t (numRawQSschemaSchemas qs_schema))\n              (t : RawTuple) (freshIdx : nat),\n\n         UnConstrFreshIdx (GetUnConstrRelation r_o idx) freshIdx ->\n         (forall r_o r_n,\n             DelegateToBag_AbsR r_o r_n ->\n             refine (k r_o) (k' r_n))\n         ->  refine\n               (r_o' <- UpdateUnConstrRelationInsertC r_o idx {| elementIndex := freshIdx; indexedElement := t |};\n                k r_o')\n               (r_n' <- CallBagInsert idx r_n t;\n                k' r_n').\nProof.\n  unfold refine; intros.\n  unfold CallBagInsert, CallBagMethod in *; simpl in *; computes_to_inv; subst.\n    computes_to_econstructor; simpl.\n    unfold UpdateUnConstrRelationInsertC; computes_to_econstructor.\n    eapply H1; eauto.\n    unfold DelegateToBag_AbsR in *; intuition; intros.\n    intros; destruct (fin_eq_dec idx idx0); subst.\n    - rewrite get_update_unconstr_eq, get_update_indexed_eq.\n      destruct (H idx0) as\n          [l [ [ [bnd fresh_bnd] [l' [l'_eq [l_eqv NoDup_l'] ] ] ]\n                [ [bnd' fresh_bnd'] [l'' [l''_eq [l''_eqv NoDup_l''] ] ] ] ] ].\n      exists (cons t l); repeat split.\n      + exists (S freshIdx); unfold EnsembleInsert, UnConstrFreshIdx; intros.\n        unfold UnConstrFreshIdx in H0; intuition; subst; simpl; eauto.\n      + unfold UnIndexedEnsembleListEquivalence;\n                 exists ({| indexedElement := t; elementIndex := freshIdx |} :: l')%list; intuition.\n        * simpl in *; rewrite l'_eq; trivial.\n        * simpl; destruct H3;\n          [left; symmetry; exact H3\n           | right; apply l_eqv; eauto].\n        * unfold EnsembleInsert; destruct H3;\n          [rewrite <- H3; left; trivial\n           | right; eapply l_eqv; eauto ].\n        * simpl; apply NoDup_cons; eauto.\n          unfold not; intros;\n          apply in_map_iff in H3; destruct H3; destruct H3;\n            apply l_eqv in H4. unfold UnConstrFreshIdx in H0;\n            unfold In in H3; apply H0 in H4;\n            unfold GetNRelSchema in *; omega.\n      + exists (S v2); unfold Ensembles.Add, UnConstrFreshIdx; intros.\n        inversion H3; subst.\n        unfold UnConstrFreshIdx in H2; intuition; subst; simpl; eauto.\n        inversion H4; subst.\n        simpl; eauto.\n      + unfold UnIndexedEnsembleListEquivalence;\n                 exists ({| indexedElement := t; elementIndex := v2 |} :: l'')%list; intuition.\n        * simpl in *; rewrite l''_eq; trivial.\n        * simpl; destruct H3;\n          [right; apply l''_eqv; eauto |\n           left; inversion H3; reflexivity ].\n        * unfold Ensembles.Add; destruct H3;\n          [ right; subst; econstructor\n          | left; eapply l''_eqv; eauto ].\n        * simpl; apply NoDup_cons; eauto.\n          unfold not; intros;\n          apply in_map_iff in H3; destruct H3; destruct H3;\n            apply l''_eqv in H4; unfold UnConstrFreshIdx in H2;\n            unfold In in H3; apply H2 in H4;\n            unfold GetNRelSchema in *; omega.\n      - rewrite get_update_unconstr_neq, get_update_indexed_neq; eauto.\n  Qed.\n\nLemma refine_BagADT_QSDelete' {ResultT}\n  : forall\n    (r_o : UnConstrQueryStructure qs_schema)\n    (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n    idx\n    DeletedTuples\n    (k  : _ -> Comp ResultT) (k' : _ -> Comp ResultT)\n    (DT_Dec : DecideableEnsemble DeletedTuples)\n    search_pattern,\n    ExtensionalEq (@DecideableEnsembles.dec _ _ DT_Dec)\n                  (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_pattern)\n    -> DelegateToBag_AbsR r_o r_n\n    -> (forall r_o r_n,\n           DelegateToBag_AbsR r_o r_n ->\n           refine (k r_o) (k' r_n))\n    ->  refine\n          (r_o' <- UpdateUnConstrRelationDeleteC r_o idx DeletedTuples;\n           k r_o')\n          (r_n' <- CallBagDelete idx r_n search_pattern;\n           k' (fst r_n')).\nProof.\n  unfold refine; intros.\n  unfold CallBagDelete, CallBagMethod in H2; simpl in H2;\n    computes_to_inv; subst; simpl in *.\n  unfold UpdateUnConstrRelationDeleteC; repeat computes_to_econstructor.\n  eapply H1; eauto.\n  unfold DelegateToBag_AbsR; intros.\n  intros; destruct (fin_eq_dec idx idx0); subst.\n  - rewrite get_update_unconstr_eq, get_update_indexed_eq.\n    destruct (H0 idx0) as\n        [l [ [ [bnd fresh_bnd] ? ]\n               [ [bnd' fresh_bnd'] ? ] ] ].\n    pose proof (UnIndexedEnsembleListEquivalence_Delete DT_Dec H3).\n    pose proof (UnIndexedEnsembleListEquivalence_Delete DT_Dec H4).\n    eexists (filter (fun a : RawTuple => negb (DecideableEnsembles.dec a)) l); split;\n      unfold EnsembleIndexedListEquivalence; split; eauto;\n        try solve [eexists _; eauto using UnConstrFreshIdx_Delete].\n    eapply UnIndexedEnsembleListEquivalence_Same_set; eauto.\n    split; unfold Included; intros; inversion H7; subst;\n      econstructor; eauto;\n        unfold Complement, Ensembles.In in *.\n    + eapply Decides_false in H9; rewrite H in H9. congruence.\n    + eapply Decides_false; rewrite <- H in H9; destruct (DecideableEnsembles.dec (indexedElement x));\n        congruence.\n  - rewrite get_update_unconstr_neq, get_update_indexed_neq; eauto.\nQed.\n\nCorollary refine_Join_Comp_Lists_filter_filter_search_term_snd_dep'\n          (ResultT : Type) :\n  forall r_o (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           (_ : DelegateToBag_AbsR r_o r_n)\n         idx idx'\n         (search_pattern : _ -> _)\n         (resultComp : ilist2 (B:= @RawTuple) [_; _] -> Comp (list ResultT))\n         filter_rest st,\n    refine (cl <- CallBagFind idx r_n st;\n            l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                   (fun _ => l <- CallBagEnumerate idx' r_n ;\n                                    ret (snd l)));\n            List_Query_In (filter (fun a : ilist2 (B:= @RawTuple) [_ ; _] => BagMatchSearchTerm _ (search_pattern (ilist2_tl a)) (ilist2_hd a) && filter_rest a) l')\n                          resultComp)\n           (cl <- CallBagFind idx r_n st;\n            l' <- (Join_Comp_Lists (Build_single_Tuple_list (snd cl))\n                                   (fun tup => l <- CallBagFind idx' r_n (search_pattern tup);\n                                    ret (snd l)));\n            List_Query_In (filter filter_rest l') resultComp).\nProof.\n  intros; f_equiv; intro;\n  eapply refine_Join_Comp_Lists_filter_search_term_snd_dep; eauto.\nQed.\n\nEnd BagsQueryStructureRefinements.\n\nLemma CallBagFind_fst\n      {qs_schema : RawQueryStructureSchema}\n      {BagIndexKeys : ilist3 (qschemaSchemas qs_schema)}\n  : forall (idx : Fin.t (numRawQSschemaSchemas qs_schema))\n           (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           (st : BagSearchTermType (ith3 BagIndexKeys idx))\n           a,\n    CallBagMethod idx BagFind r_n st \u219d a\n    -> r_n = (UpdateIndexedRelation _ _ r_n idx (fst a)).\nProof.\n  unfold CallBagMethod; intros.\n  simpl in *; computes_to_inv; subst.\n  simpl.\n  unfold UpdateIndexedRelation.\n  unfold GetIndexedRelation.\n  unfold IndexedQueryStructure in r_n.\n  eapply ilist3_eq_ith3; intros.\n  destruct (fin_eq_dec idx idx0); subst.\n  rewrite i3th_replace_Index_eq; reflexivity.\n  rewrite i3th_replace_Index_neq; eauto.\nQed.\n\nLemma CallBagEnumerate_fst\n      {qs_schema : RawQueryStructureSchema}\n      {BagIndexKeys : ilist3 (qschemaSchemas qs_schema)}\n  : forall (idx : Fin.t (numRawQSschemaSchemas qs_schema))\n           (r_n : IndexedQueryStructure qs_schema BagIndexKeys)\n           a,\n    CallBagMethod idx BagEnumerate r_n \u219d a\n    -> r_n = (UpdateIndexedRelation _ _ r_n idx (fst a)).\nProof.\n  unfold CallBagMethod; intros.\n  simpl in *; computes_to_inv; subst.\n  simpl.\n  unfold UpdateIndexedRelation.\n  unfold GetIndexedRelation.\n  unfold IndexedQueryStructure in r_n.\n  eapply ilist3_eq_ith3; intros.\n  destruct (fin_eq_dec idx idx0); subst.\n  rewrite i3th_replace_Index_eq; reflexivity.\n  rewrite i3th_replace_Index_neq; eauto.\nQed.\n\nLemma List_Query_In_Return' :\n  forall (n : nat) (ResultT : Type) (headings : Vector.t RawHeading n) (f f' : _ -> Comp (list ResultT))\n         (l : list (ilist2 (B := @RawTuple) headings)),\n    (forall tup, refine (f tup) (f' tup))\n    -> refine (List_Query_In l f)\n              (List_Query_In l f').\nProof.\n  unfold List_Query_In.\n  intros; eapply refine_flatten_CompList_func; eauto.\nQed.\n\nDefinition CallBagCount {qs_schema BagIndexKeys}\n           idx (r_n : IndexedQueryStructure qs_schema BagIndexKeys) st :=\n  br <- CallBagMethod idx BagCount r_n st;\n    ret (UpdateIndexedRelation qs_schema _ r_n idx (fst br), snd br).\n\nLemma refine_BagFindBag_single {ResultT} :\n  forall qs_schema BagIndexKeys idx r_o r_n search_term P\n         (f : _ -> ResultT)\n         (P_dec : DecideableEnsemble P),\n    @DelegateToBag_AbsR qs_schema BagIndexKeys r_o r_n\n    -> ExtensionalEq DecideableEnsembles.dec (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_term)\n    -> refine (For (UnConstrQuery_In r_o idx\n                                     (fun tup => Where (P tup) Return (f tup))))\n              (r_n' <- CallBagFind qs_schema BagIndexKeys idx r_n search_term;\n                 ret (map f (snd r_n'))).\nProof.\n    intros.\n  rewrite refine_For.\n  etransitivity.\n  apply refine_under_bind_both.\n  etransitivity.\n  apply refine_Filtered_Query_In_Enumerate; eauto.\n  apply refine_under_bind; intros.\n  match goal with\n  | [H : @DelegateToBag_AbsR ?qs_schema ?indexes ?r_o ?r_n\n     |- refine (List_Query_In ?b (fun b' : ?QueryT => Where (@?P b') (@?resultComp b'))) _ ] =>\n    etransitivity;\n      [ let H' := eval simpl in (@refine_List_Query_In_Where QueryT _ b P resultComp) in\n            pose proof H'\n      | ]\n  end.\n  eapply (H2 {| DecideableEnsembles.dec := fun tup => DecideableEnsembles.dec (prim_fst tup) |}).\n  simpl.\n  finish honing.\n  intros; finish honing.\n  simpl.\n  etransitivity.\n  apply refine_under_bind_both.\n  apply (fun heading => @refine_Join_Filtered_Comp_Lists_filter_tail _ heading [ ]%vector); intros.\n  intros; finish honing.\n  simpl.\n  setoid_rewrite Join_Filtered_Comp_Lists_ExtensionalEq_filters;\n    [ | unfold ExtensionalEq in *; intros [? ?]; simpl; rewrite H0;\n        instantiate (1 := fun tup => BagMatchSearchTerm (ith3 BagIndexKeys idx) search_term (ilist2_hd tup) && true); simpl; rewrite andb_true_r; eauto ].\n  rewrite (@refine_Join_Comp_Lists_To_Find _ _ 0 _ _ H [ ]%vector).\n  simplify with monad laws.\n  unfold Join_Comp_Lists; simpl.\n  unfold CallBagFind, CallBagCount; autorewrite with monad laws.\n  f_equiv; intro.\n  simpl.\n  rewrite app_nil_r.\n  rewrite (List_Query_In_Return _\n                                (map (fun fa : RawTuple => icons2 fa inil2) a)\n                                (fun tup => f (prim_fst tup))).\n  simplify with monad laws.\n  refine pick val _.\n  reflexivity.\n  simpl.\n  rewrite Permutation_map.\n  2: reflexivity.\n  rewrite map_map; simpl.\n  induction a; simpl; eauto.\n  Unshelve.\n  simpl.\n  intro; rewrite dec_decides_P; reflexivity.\nQed.\n\nLemma refine_BagFindBagCount {ResultT} :\n  forall qs_schema BagIndexKeys idx r_o r_n search_term P\n         (f : _ -> ResultT)\n         (P_dec : DecideableEnsemble P),\n    @DelegateToBag_AbsR qs_schema BagIndexKeys r_o r_n\n    -> ExtensionalEq DecideableEnsembles.dec (BagMatchSearchTerm (ith3 BagIndexKeys idx) search_term)\n    -> refine (Count For (UnConstrQuery_In r_o idx\n                                           (fun tup => Where (P tup) Return (f tup))))\n              (r_n' <- CallBagCount idx r_n search_term;\n                 ret (snd r_n')).\nProof.\n  intros.\n  rewrite refine_Count, refine_BagFindBag_single; eauto.\n  rewrite !refine_bind_bind.\n  unfold CallBagFind, CallBagCount; autorewrite with monad laws.\n  f_equiv; intro.\n  simpl.\n  rewrite !map_length; reflexivity.\nQed.\n\nLemma exists_UnConstrFreshIdx_Max :\n    forall (qs_schema : RawQueryStructureSchema) (BagIndexKeys : ilist3 (qschemaSchemas qs_schema))\n           (r_o : UnConstrQueryStructure qs_schema) (r_n : IndexedQueryStructure qs_schema BagIndexKeys),\n      DelegateToBag_AbsR r_o r_n ->\n      exists bnd : nat,\n      forall idx : Fin.t (numRawQSschemaSchemas qs_schema), UnConstrFreshIdx (GetUnConstrRelation r_o idx) bnd.\n  Proof.\n    unfold DelegateToBag_AbsR; intros.\n    assert (forall idx : Fin.t (numRawQSschemaSchemas qs_schema),\n               exists l : list RawTuple,\n                 EnsembleIndexedListEquivalence (GetUnConstrRelation r_o idx) l) by\n        (intros; destruct (H idx) as [ ? [? ?] ]; eauto).\n    destruct qs_schema; simpl in *;\n      revert H0 ; generalize (GetUnConstrRelation r_o); clear.\n    simpl; clear.\n    induction qschemaSchemas; simpl; intros.\n    - exists 0; intro; inversion idx.\n    - destruct (IHqschemaSchemas (fun idx => i (Fin.FS idx))\n                                 (fun idx => H0 (Fin.FS idx))).\n      destruct (H0 Fin.F1) as [l [ [bound' ?] ?] ].\n      exists (max bound' x); intros.\n      generalize qschemaSchemas i H1 H; clear; pattern n, idx.\n      apply Fin.caseS; intros;  unfold UnConstrFreshIdx in *; intros.\n      apply H1 in H0; destruct (Max.max_spec bound' x); intuition.\n      apply H in H0; destruct (Max.max_spec bound' x); intuition.\n      rewrite H4; eauto.\n      rewrite H4.\n      eapply lt_le_trans; eauto.\n  Qed.\n\nArguments CallBagMethod : simpl never.\nArguments CallBagMethod [_ _] _ _ _.\n\nArguments CallBagConstructor : simpl never.\nArguments GetIndexedRelation [_ _ ] _ _ _.\nArguments DelegateToBag_AbsR [_ _] _ _.\n\nArguments CallBagFind : simpl never.\nArguments CallBagFind [_ _] _ _ _ _.\n\nArguments CallBagCount : simpl never.\nArguments CallBagCount [_ _] _ _ _ _.\n\nArguments CallBagInsert : simpl never.\nArguments CallBagInsert [_ _] _ _ _ _.\n\nArguments CallBagDelete : simpl never.\nArguments CallBagDelete [_ _] _ _ _ _.\n\nArguments CallBagEnumerate : simpl never.\nArguments CallBagEnumerate [_ _] _ _ _.\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/Operations/BagADT/Refinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.15777429720240307}}
{"text": "(* \n * \u00a9 2019 XXX.\n * \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     ChMaps\n     Messages\n     MessageEq\n     Keys\n     AdversaryUniverse\n.\n\nFrom SPICY Require\n     IdealWorld\n     RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       .\n\nSet Implicit Arguments.\n\n\nSection IdealDefiniions.\n\n  Import IdealWorld.\n\n  Definition istepSilent {A} (U1 U2 : universe A) :=\n    lstep_universe U1 Silent U2.\n\n  Inductive indexedIdealStep {A} (uid : user_id) (lbl : label) (U1 U2 : universe A) : Prop :=\n  | IndexedIdealStep : forall u proto chans prms,\n      U1.(users) $? uid = Some u\n      -> lstep_user uid lbl (U1.(channel_vector), u.(protocol), u.(perms)) (chans, proto, prms)\n      -> U2 = construct_universe\n               chans\n               (U1.(users) $+ (uid, {| protocol := proto ; perms := prms |}))\n      -> indexedIdealStep uid lbl U1 U2.\n\n  Lemma indexedIdealStep_ideal_step :\n    forall A uid lbl U1 U2,\n      @indexedIdealStep A uid lbl U1 U2\n      -> lstep_universe U1 lbl U2.\n  Proof. intros * IND; invert IND; econstructor; eauto. Qed.\n\nEnd IdealDefiniions.\n\nSection RealDefinitions.\n  Import RealWorld.\n\n  Inductive indexedRealStep {A B} (uid : user_id) (lbl : label) (U1 U2 : universe A B) : Prop :=\n  | IndexedRealStep : forall userData usrs adv cs gks ks qmsgs mycs froms sents cur_n (cmd : user_cmd (Base A)),\n      U1.(users) $? uid = Some userData\n      -> step_user lbl (Some uid)\n                  (build_data_step U1 userData)\n                  (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> U2 = 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      -> indexedRealStep uid lbl U1 U2.\n\n  Lemma indexedRealStep_real_step :\n    forall A B uid lbl U1 U2,\n      @indexedRealStep A B uid lbl U1 U2\n      -> step_universe (Some uid) U1 (mkULbl lbl uid) U2.\n  Proof. intros * IND; invert IND; econstructor; eauto. Qed.\n\nEnd RealDefinitions.\n\nInductive chan_key : Set :=\n| Public (ch_id : IdealWorld.channel_id)\n| Auth (ch_id : IdealWorld.channel_id): forall k,\n    k.(keyUsage) = Signing -> chan_key\n| Enc  (ch_id : IdealWorld.channel_id) : forall k,\n    k.(keyUsage) = Encryption -> chan_key\n| AuthEnc (ch_id : IdealWorld.channel_id) : forall k1 k2,\n      k1.(keyUsage) = Signing\n    -> k2.(keyUsage) = Encryption\n    -> chan_key\n.\n\nInductive action_matches (cs : RealWorld.ciphers) (gks : keys) :\n  RealWorld.uaction -> IdealWorld.action -> Prop :=\n\n| InpSig : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid uid seq froms p cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigCipher kid uid seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (uid, RealWorld.Input m__rw p froms) (IdealWorld.Input m__iw uid ch_id chans ps)\n| InpEnc : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid1 kid2 uid seq froms p cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigEncCipher kid1 kid2 uid seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (uid, RealWorld.Input m__rw p froms) (IdealWorld.Input m__iw uid ch_id chans ps)\n| OutSig : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid seq to from sents cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigCipher kid to seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (from, RealWorld.Output m__rw (Some from) (Some to) sents) (IdealWorld.Output m__iw from ch_id chans ps)\n| OutEnc : forall t (m__rw : RealWorld.crypto t) (msg__rw : RealWorld.message.message t) (m__iw : IdealWorld.message.message t)\n          kid1 kid2 seq to from sents cid ch_id chans ps,\n    m__rw = RealWorld.SignedCiphertext cid\n    -> cs $? cid = Some (RealWorld.SigEncCipher kid1 kid2 to seq msg__rw)\n    -> content_eq msg__rw m__iw gks\n    -> action_matches cs gks (from, RealWorld.Output m__rw (Some from) (Some to) sents) (IdealWorld.Output m__iw from ch_id chans ps)\n.\n\nSection RealWorldUniverseProperties.\n  Import RealWorld.\n\n  Variable honestk : key_perms.\n  \n  Definition permission_heap_honest (perms : key_perms) :=\n    forall k_id p,\n     perms $? k_id = Some p\n      -> honestk $? k_id = Some true.\n\n  Definition permission_heap_good (ks : keys) (perms : key_perms) :=\n    forall k_id p,\n      perms $? k_id = Some p\n      -> exists k, ks $? k_id = Some k.\n\n  (* Syntactic Predicates *)\n  Definition keys_and_permissions_good {A} (ks : keys) (usrs : honest_users A) (adv_heap : key_perms): Prop :=\n    (forall k_id k,\n          ks $? k_id = Some k\n        -> keyId k = k_id)\n    /\\ Forall_natmap (fun u => permission_heap_good ks u.(key_heap)) usrs\n    /\\ permission_heap_good ks adv_heap.\n\n  Definition user_cipher_queue_ok (cs : ciphers) (honestk : key_perms) :=\n    Forall (fun cid => exists c, cs $? cid = Some c\n                       /\\ cipher_honestly_signed honestk c = true).\n\n  Definition user_cipher_queues_ok {A} (cs : ciphers) (honestk : key_perms) (usrs : honest_users A) :=\n    Forall_natmap\n      (fun u => user_cipher_queue_ok cs honestk u.(c_heap)) usrs.\n\n  Definition adv_cipher_queue_ok {A} (cs : ciphers) (usrs : honest_users A) :=\n    Forall (fun cid => exists new_cipher,\n                cs $? cid = Some new_cipher\n                /\\ ( cipher_honestly_signed (findUserKeys usrs) new_cipher = false\n                  \\/ ( cipher_honestly_signed (findUserKeys usrs) new_cipher = true\n                    /\\ exists u_id u rec_u,\n                      fst (cipher_nonce new_cipher) = Some u_id\n                      /\\ usrs $? u_id = Some u\n                      /\\ u_id <> cipher_to_user new_cipher\n                      /\\ List.In (cipher_nonce new_cipher) u.(sent_nons)\n                      /\\ usrs $? cipher_to_user new_cipher = Some rec_u\n                      /\\ ( List.In (cipher_nonce new_cipher) rec_u.(from_nons)\n                        \\/ Exists (fun sigM => match sigM with\n                                           | existT _ _ m =>\n                                             msg_signed_addressed (findUserKeys usrs) cs (Some (cipher_to_user new_cipher)) m = true\n                                           /\\ msg_nonce_same new_cipher cs m\n                                           end) rec_u.(msg_heap))))\n           ).\n\n  Inductive encrypted_cipher_ok (cs : ciphers) (gks : keys): cipher -> Prop :=\n  | SigCipherHonestOk : forall {t} (msg : message t) msg_to nonce k kt,\n      honestk $? k = Some true\n      -> gks $? k = Some {| keyId := k; keyUsage := Signing; keyType := kt |}\n      (* only send honest public keys *)\n      -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true /\\ kp = false)\n      -> encrypted_cipher_ok cs gks (SigCipher k msg_to nonce msg)\n  | SigCipherNotHonestOk : forall {t} (msg : message t) msg_to nonce k kt,\n      honestk $? k <> Some true\n      -> gks $? k = Some {| keyId := k; keyUsage := Signing; keyType := kt |}\n      -> encrypted_cipher_ok cs gks (SigCipher k msg_to nonce msg)\n  | SigEncCipherAdvSignedOk :  forall {t} (msg : message t) msg_to nonce k__s k__e kt__s kt__e,\n      honestk $? k__s <> Some true\n      -> gks $? k__s = Some {| keyId := k__s; keyUsage := Signing; keyType := kt__s |}\n      -> gks $? k__e = Some {| keyId := k__e; keyUsage := Encryption; keyType := kt__e |}\n      -> (forall k kp, findKeysMessage msg $? k = Some kp\n                 -> exists v, gks $? k = Some v\n                      /\\ (kp = true -> honestk $? k <> Some true))\n      -> encrypted_cipher_ok cs gks (SigEncCipher k__s k__e msg_to nonce msg)\n  | SigEncCipherHonestSignedEncKeyHonestOk : forall {t} (msg : message t) msg_to nonce k__s k__e kt__s kt__e,\n      honestk $? k__s = Some true\n      -> honestk $? k__e = Some true\n      -> gks $? k__s = Some {| keyId := k__s; keyUsage := Signing; keyType := kt__s |}\n      -> gks $? k__e = Some {| keyId := k__e; keyUsage := Encryption; keyType := kt__e |}\n      (* only send honest keys *)\n      -> (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true)\n      -> encrypted_cipher_ok cs gks (SigEncCipher k__s k__e msg_to nonce msg).\n\n  Definition encrypted_ciphers_ok (cs : ciphers) (gks : keys) :=\n    Forall_natmap (encrypted_cipher_ok cs gks) cs.\n\n  Definition message_no_adv_private {t} (cs : ciphers) (msg : crypto t) :=\n    forall k p, findKeysCrypto cs msg $? k = Some p -> honestk $? k = Some true /\\ p = false.\n\n  Definition adv_message_queue_ok {A} (usrs : honest_users A)\n             (cs : ciphers) (gks : keys) (msgs : queued_messages) :=\n    Forall (fun sigm => match sigm with\n                     | (existT _ _ m) =>\n                       (forall cid, msg_cipher_id m = Some cid -> cs $? cid <> None)\n                     /\\ (forall k kp,\n                           findKeysCrypto cs m $? k = Some kp\n                           -> gks $? k <> None /\\ (kp = true -> (findUserKeys usrs) $? k <> Some true))\n                     /\\ (forall k,\n                           msg_signing_key cs m = Some k\n                           -> gks $? k <> None)\n                     /\\ (forall c_id, List.In c_id (findCiphers m)\n                                -> exists c, cs $? c_id = Some c\n                                     /\\ ( cipher_honestly_signed (findUserKeys usrs) c = false\n                                       \\/ ( cipher_honestly_signed (findUserKeys usrs) c = true\n                                         /\\ exists uid u rec_u,\n                                           fst (cipher_nonce c) = Some uid\n                                           /\\ usrs $? uid = Some u\n                                           /\\ uid <> cipher_to_user c\n                                           /\\ List.In (cipher_nonce c) u.(sent_nons)\n                                           /\\ usrs $? cipher_to_user c = Some rec_u\n                                           /\\ ( List.In (cipher_nonce c) rec_u.(from_nons)\n                                             \\/ Exists (fun sigM =>\n                                                         match sigM with\n                                                         | existT _ _ m =>\n                                                           msg_signed_addressed (findUserKeys usrs) cs (Some (cipher_to_user c)) m = true\n                                                           /\\ msg_nonce_same c cs m\n                                                         end) rec_u.(msg_heap)))))\n                     end\n           ) msgs.\n\n  Definition message_queue_ok (cs : ciphers) (msgs : queued_messages) (gks : keys) :=\n    Forall (fun sigm => match sigm with\n                     | (existT _ _ m) =>\n                       (forall k kp, findKeysCrypto cs m $? k = Some kp -> gks $? k <> None)\n                     /\\ (forall cid,\n                           msg_cipher_id m = Some cid\n                           -> cs $? cid <> None)\n                     /\\ (forall k,\n                           msg_signing_key cs m = Some k\n                           -> gks $? k <> None\n                           /\\ ( honest_key honestk k\n                             -> message_no_adv_private cs m)\n                       )\n                     end) msgs.\n\n  Definition adv_no_honest_keys (advk : key_perms) : Prop :=\n    forall k_id,\n      (  honestk $? k_id = None\n      \\/  honestk $? k_id = Some false\n      \\/ (honestk $? k_id = Some true /\\ advk $? k_id <> Some true)\n      ).\n\n  Definition honest_users_only_honest_keys {A} (usrs : honest_users A) :=\n    forall u_id u,\n      usrs $? u_id = Some u\n      -> forall k_id kp,\n        u.(key_heap) $? k_id = Some kp\n        -> findUserKeys usrs $? k_id = Some true.\n\n  Definition honest_nonce_tracking_ok (cs : ciphers) (honestk : key_perms)\n             (me : option user_id) (my_sents : sent_nonces) (my_cur_n : nat)\n             (to_usr : user_id) (to_froms : recv_nonces) (to_msgs : queued_messages) :=\n\n      (* Forall (fun non => snd non < my_cur_n) my_sents *)\n      Forall (fun non => fst non = me -> snd non < my_cur_n) to_froms\n    /\\ Forall (fun '(existT _ _ msg) => \n                forall c_id c,\n                  msg = SignedCiphertext c_id\n                  -> cs $? c_id = Some c\n                  -> honestk $? (cipher_signing_key c) = Some true\n                  -> cipher_to_user c = to_usr\n                  -> fst (cipher_nonce c) = me\n                  -> snd (cipher_nonce c) < my_cur_n\n             ) to_msgs\n    /\\ forall c_id c,\n        cs $? c_id = Some c\n      -> honestk $? (cipher_signing_key c) = Some true\n      -> fst (cipher_nonce c) = me (* if cipher created by me *) \n      (* -> snd (cipher_nonce c) < my_cur_n *)\n      -> cipher_to_user c = to_usr\n      -> ~ List.In (cipher_nonce c) my_sents (* and hasn't yet been sent *)\n      -> ~ List.In (cipher_nonce c) to_froms (* then it hasn't been read by destination user *)\n        /\\ Forall (fun '(existT _ _ msg) => (* and isn't in destination user's message queue *)\n                    msg_honestly_signed  honestk cs msg = true\n                    -> msg_to_this_user cs (Some to_usr) msg = false\n                      \\/ msg_nonce_not_same c cs msg) to_msgs.\n\n  Definition honest_user_nonces_ok (cs : ciphers) (honestk : key_perms)\n             (me : option user_id) (my_sents : sent_nonces) (my_cur_n : nat) :=\n    (forall c_id c,\n      cs $? c_id = Some c\n      -> honestk $? (cipher_signing_key c) = Some true\n      -> fst (cipher_nonce c) = me (* if cipher created by me *) \n      -> snd (cipher_nonce c) < my_cur_n)\n  /\\ Forall (fun non => snd non < my_cur_n) my_sents\n  .\n\n  Definition honest_nonces_unique (cs : ciphers) (honestk : key_perms) :=\n    (forall cid1 cid2 c1 c2,\n        cid1 <> cid2\n        -> cs $? cid1 = Some c1\n        -> cs $? cid2 = Some c2\n        -> honestk $? (cipher_signing_key c1) = Some true\n        -> honestk $? (cipher_signing_key c2) = Some true\n        -> cipher_nonce c1 <> cipher_nonce c2).\n  \n  Definition action_adversary_safe (honestk : key_perms) (cs : ciphers) (a : action) : Prop :=\n    match a with\n    | Input  msg pat froms    => msg_pattern_safe honestk pat\n                              /\\ exists c_id c, msg = SignedCiphertext c_id\n                                        /\\ cs $? c_id = Some c\n                                        /\\ ~ List.In (cipher_nonce c) froms\n    | Output msg msg_from msg_to sents => msg_honestly_signed honestk cs msg = true\n                                       /\\ msg_to_this_user cs msg_to msg = true\n                                       /\\ exists c_id c, msg = SignedCiphertext c_id\n                                                 /\\ cs $? c_id = Some c\n                                                 /\\ fst (cipher_nonce c) = msg_from  (* only send my messages *)\n                                                 /\\ ~ List.In (cipher_nonce c) sents\n    end.\n\nEnd RealWorldUniverseProperties.\n\nSection SafeActions.\n  Import RealWorld.\n  \n  Inductive nextAction : forall {A B}, user_cmd A -> user_cmd B -> Prop :=\n  | NaReturn : forall A (a : << A >>),\n      nextAction (Return a) (Return a)\n  | NaGen :\n      nextAction Gen Gen\n  | NaSend : forall t uid (msg : crypto t),\n      nextAction (Send uid msg) (Send uid msg)\n  | NaRecv : forall t pat,\n      nextAction (@Recv t pat) (@Recv t pat)\n  | NaSignEncrypt : forall t k__s k__e u_id (msg : message t),\n      nextAction (SignEncrypt k__s k__e u_id msg) (SignEncrypt k__s k__e u_id msg)\n  | NaDecrypt : forall t (msg : crypto t),\n      nextAction (Decrypt msg) (Decrypt msg)\n  | NaSign : forall t k u_id (msg : message t),\n      nextAction (Sign k u_id msg) (Sign k u_id msg)\n  | NaVerify : forall t k (msg : crypto t),\n      nextAction (Verify k msg) (Verify k msg)\n  | NaGenKey : forall kt usg,\n      nextAction (GenerateKey kt usg) (GenerateKey kt usg)\n  | NaBind : forall A B r (c : user_cmd B) (c1 : user_cmd r) (c2 : << r >> -> user_cmd A),\n      nextAction c1 c\n      -> nextAction (Bind c1 c2) c\n  .\n\n  Lemma nextAction_couldBe :\n    forall {A B} (c1 : user_cmd A) (c2 : user_cmd B),\n      nextAction c1 c2\n      -> match c2 with\n        | Return _ => True\n        | Gen => True\n        | Send _ _ => True\n        | Recv _ => True\n        | SignEncrypt _ _ _ _ => True\n        | Decrypt _ => True\n        | Sign _ _ _ => True\n        | Verify _ _ => True\n        | GenerateKey _ _ => True\n        (* | GenerateAsymKey _ => True *)\n        (* | GenerateSymKey _ => True *)\n        | Bind _ _ => False\n        end.\n  Proof.\n    induction 1; eauto.\n  Qed.\n\n  Definition next_cmd_safe (honestk : key_perms) (cs : ciphers) (u_id : user_id)\n             (froms : recv_nonces) (sents : sent_nonces) {A} (cmd : user_cmd A) :=\n    forall B (cmd__n : user_cmd B),\n      nextAction cmd cmd__n\n      -> match cmd__n with\n        | Return _ => True\n        | Gen => True\n        | Send msg_to msg =>\n          msg_honestly_signed honestk cs msg = true\n          /\\ msg_to_this_user cs (Some msg_to) msg = true\n          /\\ (exists c_id c, msg = SignedCiphertext c_id\n                       /\\ cs $? c_id = Some c\n                       /\\ fst (cipher_nonce c) = (Some u_id)  (* only send my messages *)\n                       /\\ ~ List.In (cipher_nonce c) sents)\n        | Recv pat =>\n          msg_pattern_safe honestk pat\n        | SignEncrypt k__sign k__enc msg_to msg =>\n          honestk $? k__enc = Some true\n          /\\ (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true)\n        | Decrypt _ => True\n        | Sign _ _ msg =>\n          (forall k_id kp, findKeysMessage msg $? k_id = Some kp -> honestk $? k_id = Some true /\\ kp = false)\n        | Verify _ _ => True\n        | GenerateKey _ _ => True\n        | Bind _ _ => False\n        end.\n\n  Definition honest_cmds_safe {A B} (U : universe A B) : Prop :=\n    forall u_id u honestk,\n      honestk = findUserKeys U.(users)\n      -> U.(users) $? u_id = Some u\n      (* -> forall lbl bd, step_user lbl (Some u_id) (build_data_step U u) bd *)\n      -> next_cmd_safe (findUserKeys U.(users)) U.(all_ciphers) u_id u.(from_nons) u.(sent_nons) u.(protocol).\n\n  Definition label_safe (honestk : key_perms) (cs : ciphers) (lbl : label) : Prop :=\n    match lbl with\n    | Silent   => True\n    | Action a => action_adversary_safe honestk cs a\n    end.\n\nEnd SafeActions.\n\nSection FinalValue.\n\n    Inductive final_value : Set :=\n    | FAccess\n    | FBool (b : bool)\n    | FNat (n : nat)\n    | FUnit\n    | FPair (fv1 fv2 : final_value).\n\n    Section IdealFV.\n      Import IdealWorld.\n      Import IdealWorld.IdealNotations.\n\n      Fixpoint Iret_val_to_val { t : type } :\n        forall (rv : << Base t >>), final_value :=\n        match t with\n        | Nat => (fun n => FNat n)\n        | Bool => (fun b => FBool b)\n        | Unit => (fun _ => FUnit)\n        | Access => (fun _ => FAccess)\n        | TPair t1 t2 => (fun '(f, s) => FPair (Iret_val_to_val f) (Iret_val_to_val s))\n        end.\n      \n    End IdealFV.\n\n    Section RealFV.\n      Import RealWorld.\n      Import RealWorld.RealWorldNotations.\n\n      Fixpoint Rret_val_to_val { t : type } :\n        forall (rv : << Base t >>), final_value :=\n        match t with\n        | Nat => (fun n => FNat n)\n        | Bool => (fun b => FBool b)\n        | Unit => (fun _ => FUnit)\n        | Access => (fun _ => FAccess)\n        | TPair t1 t2 => (fun '(f, s) => FPair (Rret_val_to_val f) (Rret_val_to_val s))\n        end.\n      \n    End RealFV.\n    \nEnd FinalValue.\n\nDefinition message_queues_ok {A} (cs : RealWorld.ciphers) (usrs : RealWorld.honest_users A) (gks : keys) :=\n  Forall_natmap (fun u => message_queue_ok (RealWorld.findUserKeys usrs) cs u.(RealWorld.msg_heap) gks) usrs.\n\nDefinition honest_nonces_ok {A} (cs : RealWorld.ciphers) (usrs : RealWorld.honest_users A) :=\n    honest_nonces_unique cs (RealWorld.findUserKeys usrs)\n  /\\ ( forall uid u,\n        usrs $? uid = Some u\n        -> honest_user_nonces_ok cs (RealWorld.findUserKeys usrs) (Some uid)\n                                u.(RealWorld.sent_nons)\n                                u.(RealWorld.cur_nonce) )\n  /\\ (forall u_id u rec_u_id rec_u,\n        u_id <> rec_u_id\n        -> usrs $? u_id = Some u\n        -> usrs $? rec_u_id = Some rec_u\n        -> honest_nonce_tracking_ok cs (RealWorld.findUserKeys usrs)\n                                   (Some u_id)\n                                   u.(RealWorld.sent_nons)\n                                   u.(RealWorld.cur_nonce)\n                                   rec_u_id rec_u.(RealWorld.from_nons)\n                                   rec_u.(RealWorld.msg_heap)).\n\nDefinition universe_ok {A B} (U : RealWorld.universe A B) : Prop :=\n  let honestk := RealWorld.findUserKeys U.(RealWorld.users)\n  in  encrypted_ciphers_ok honestk U.(RealWorld.all_ciphers) U.(RealWorld.all_keys)\n    /\\ keys_and_permissions_good U.(RealWorld.all_keys) U.(RealWorld.users) U.(RealWorld.adversary).(RealWorld.key_heap)\n    /\\ user_cipher_queues_ok U.(RealWorld.all_ciphers) honestk U.(RealWorld.users)\n    /\\ message_queues_ok U.(RealWorld.all_ciphers) U.(RealWorld.users) U.(RealWorld.all_keys)\n    /\\ adv_cipher_queue_ok U.(RealWorld.all_ciphers) U.(RealWorld.users) U.(RealWorld.adversary).(RealWorld.c_heap)\n    /\\ adv_message_queue_ok U.(RealWorld.users) U.(RealWorld.all_ciphers) U.(RealWorld.all_keys) U.(RealWorld.adversary).(RealWorld.msg_heap)\n    /\\ adv_no_honest_keys honestk U.(RealWorld.adversary).(RealWorld.key_heap)\n    /\\ honest_nonces_ok U.(RealWorld.all_ciphers) U.(RealWorld.users)\n    /\\ honest_users_only_honest_keys U.(RealWorld.users).\n\nSection Simulation.\n  Variable A B : type.\n  Variable advP : RealWorld.user_data B -> Prop.\n  Variable R : RealWorld.simpl_universe A -> IdealWorld.universe A -> Prop.\n\n  Definition simulates_silent_step :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n    -> universe_ok U__r\n    -> advP U__r.(RealWorld.adversary)\n    -> forall suid U__r',\n        RealWorld.step_universe suid U__r Silent U__r'\n        -> exists U__i',\n          istepSilent ^* U__i U__i'\n        /\\ R (RealWorld.peel_adv U__r') U__i'.\n\n  Definition simulates_labeled_step :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n    -> universe_ok U__r\n    -> advP U__r.(RealWorld.adversary)\n    -> forall uid U__r' ra,\n        indexedRealStep uid (Action ra) U__r U__r'\n        -> exists ia U__i' U__i'',\n            (indexedIdealStep uid Silent) ^* U__i U__i'\n            /\\ indexedIdealStep uid (Action ia) U__i' U__i''\n            /\\ action_matches U__r.(RealWorld.all_ciphers) U__r.(RealWorld.all_keys) (uid,ra) ia\n            /\\ R (RealWorld.peel_adv U__r') U__i''.\n\n  Definition honest_actions_safe :=\n    forall (U__r : RealWorld.universe A B) U__i,\n        R (RealWorld.peel_adv U__r) U__i\n      -> universe_ok U__r\n      -> honest_cmds_safe U__r.\n\n  Definition ri_final_actions_align :=\n    forall (U__r : RealWorld.universe A B) U__i,\n      R (RealWorld.peel_adv U__r) U__i\n      -> universe_ok U__r\n      -> (forall uid lbl U__r', RealWorld.step_universe (Some uid) U__r lbl U__r' -> False)\n      -> forall uid ud__r r__r,\n          U__r.(RealWorld.users) $? uid = Some ud__r\n          -> ud__r.(RealWorld.protocol) = RealWorld.Return r__r\n          -> exists (U__i' : IdealWorld.universe A) ud__i r__i,\n              istepSilent ^* U__i U__i'\n              /\\ U__i'.(IdealWorld.users) $? uid = Some ud__i\n              /\\ ud__i.(IdealWorld.protocol) = IdealWorld.Return r__i\n              /\\ Rret_val_to_val r__r = Iret_val_to_val r__i.\n\n  Definition simulates (U__r : RealWorld.universe A B) (U__i : IdealWorld.universe A) :=\n\n    (* conditions for simulation steps *)\n    simulates_silent_step\n  /\\ simulates_labeled_step\n  /\\ honest_actions_safe\n  /\\ ri_final_actions_align\n\n  (* conditions for start *)\n  /\\ R (RealWorld.peel_adv U__r) U__i\n  /\\ universe_ok U__r\n  .\n\nEnd Simulation.\n\nSection IISimulation.\n  Import IdealWorld.\n  \n  Variable A : type.\n  Variable R : universe A -> universe A -> Prop.\n\n  Definition ii_final_labels_align (U__i U__is : universe A) :=\n    (forall lbl U__i', ~ lstep_universe U__i lbl U__i')\n    -> exists (U__is' U__is'' : universe A),\n      trc3 lstep_universe (fun _ => True) U__is U__is'\n      /\\ (forall lbl U__is'', ~ lstep_universe U__is' lbl U__is'')\n      /\\ forall uid ud__i r,\n          U__i.(users) $? uid = Some ud__i\n          -> ud__i.(protocol) = Return r\n          -> exists ud__is,\n            U__is'.(users) $? uid = Some ud__is\n          /\\ ud__is.(protocol) = Return r.\n\n  Definition ii_step :=\n    forall (U__i : universe A) U__is,\n      R U__i U__is\n      -> forall lbl U__i',\n        lstep_universe U__i lbl U__i'\n        -> exists U__is',\n          trc3 lstep_universe (fun _ => True) U__is U__is'\n          /\\ ii_final_labels_align U__i' U__is'\n          /\\ R U__i' U__is'.\n\n  Definition ii_simulates (U__i U__is : universe A) :=\n    ii_step\n    /\\ R U__i U__is.\n\nEnd IISimulation.\n\nDefinition refines {A B} (advP : RealWorld.user_data B -> Prop) (U1 : RealWorld.universe A B) (U2 : IdealWorld.universe A) :=\n  exists R, simulates advP R U1 U2.\n\nNotation \"u1 <| u2 \\ p \" := (refines p u1 u2) (no associativity, at level 70).\n\nDefinition lameAdv {B} (b : RealWorld.denote (RealWorld.Base B)) :=\n  fun adv => adv.(RealWorld.protocol) = @RealWorld.Return (RealWorld.Base B) b.\n\nDefinition awesomeAdv : forall B, RealWorld.user_data B -> Prop :=\n  fun _ _ => True.\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/Simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.15777429720240307}}
{"text": "(* begin hide *)\nFrom Coq Require Import\n     String Morphisms List.\n\nFrom ITree Require Import\n     ITree\n     Basics.Monad\n     Eq.Eq\n     TranslateFacts\n     Events.State.\n\nFrom Vellvm Require Import\n     Utilities\n     Syntax\n     Semantics\n     Utils.NoFailure\n     Utils.PostConditions\n     Theory.InterpreterCFG\n     Theory.ExpLemmas\n     Theory.InstrLemmas\n     Theory.InterpreterCFG\n     Theory.SymbolicInterpreter.\n\nFrom ExtLib Require Import\n     Core.RelDec\n     Data.Map.FMapAList\n     Structures.Maps.\n\nImport ListNotations.\nImport AlistNotations.\nImport ITreeNotations.\nImport SemNotations.\n(* end hide *)\n\n(** * Live-equivalence\n    Optimizations do not preserve functional equivalence of local environment in general.\n *)\n\nFrom Coq Require Import ListSet.\nImport SetNotations.\nImport AlistNotations.\n\nDefinition local_agrees (l1 l2 : local_env) (scope : set raw_id) : Prop :=\n  forall id, In id scope -> l1 @ id = l2 @ id.\n\nSection UpwardExposed.\n\n  (** * Upward exposed\n        A use site is said to be upward exposed if its def site is not in the\n        same block, i.e. if the live range of the used variable escapes the block\n        of the use site.\n   *)\n  (* Note: this definition is quite naive, it doesn't consider the relative position\n       within the block of the def and use sites considered.\n       I believe that it's correct in SSA form, but should be triple checked.\n   *)\n\n  Definition upward_exposed {T} (bk : block T) : set raw_id :=\n    use_sites bk \u2216 def_sites bk.\n\nEnd UpwardExposed.\n\nSection Block_Substitution.\n\n  (* This definition expresses the local proof obligation\n     required to justify the substitution of a block [b1]\n     by another block [b2] in a context.\n     Contrary to the case of equivalent expressions, the\n     context will be constrained as well.\n     We state that if:\n     - the upward exposed local variables are the same set\n     [scope] in both blocks.\n     - the initial local states extensionally agree on [scope]\n     then:\n     - the blocks are bisimilar\n     - they return local states that extensionally agree on\n   *)\n\n  Definition local_post : \n\n  Definition block_equivalence :\n    forall (b1 b2 : block dtyp) scope_in scope_out,\n      upward_exposed b1 = scope_in -> (* To replace with bijection *)\n      upward_exposed b2 = scope_out -> (* To replace with bijection *)\n      forall g l1 l2 m bin,\n        local_agrees l1 l2 scope_in ->\n        eutt (fun '(m1,(l,(g,v)))\n             (\u27e6 b1 \u27e7b3 bin g l1 m)\n             (\u27e6 b2 \u27e7b3 bin g l2 m).\n\n\n\n\n(* Definition lift_localR (R : local_env -> local_env -> Prop) : *)\n\nEnd Block_Substitution.\n\n\n(*\nIf pre = post = RS\n\nrelS := S -> S -> Prop\n\nAny monad that is worth its name should come with an instance of eqmR.\nS -> M (S * _)\nEQMRBUILDER : relS -> relS -> eqmR_sig\n\nDefinition equiv (X Y S : Type) (pre post : S -> S -> Prop) (R : X -> Y -> Prop)\n  : StateT S (itree E) X -> StateT S (itree E) Y -> Prop :=\n  fun c1 c2 =>\n    forall s1 s2,\n      pre s1 s2 -> eutt (post * R) (c1 s1) (c2 s2).\n\n\n(* forall R' *)\neqmr R' c1 c2\nforall v1 v2, R' v v' -> eqmr R (k1 v1) (k2 v2)\n==============================\neqmr R (bind c1 k1) (bind c2 k2)\n\nhoaremR ~> (S -> S -> Prop) -> (S -> S -> Prop) -> eqmR_sig\n\n\n\n(* forall R' (inter : S -> S -> Prop) *)\nequiv pre inter R' c1 c2\nforall v1 v2, R' v1 v2 -> equiv inter post R (k1 v1) (k2 v2)\n==============================\nequiv pre post R (bind c1 k1) (bind c2 k2)\n\n *)\n\n\n\n\n\nSection Liveness.\n\n  (** * Liveness\n      Data-flow approach, we compute for each block the [LiveIn] set of live variables when entering the block,\n      and [LiveOut] set of live variables when entering a successor of the block.\n      These sets can be characterized by the following set of recursive equations:\n      LiveIn bk  \u2261 defs bk.(blk_phis) +++ upward_exposed bk +++ (LiveOut bk \u2216 defs bk)\n      LiveOut bk \u2261 (set_flat_map (fun bk' => LiveIn bk' \u2216 defs bk'.(blk_phis)) (bk_outputs bk)) +++ uses bk.(blk_phis)\n      In SSA form, the fixpoint can be directly computed in two passses over the CFG.\n   *)\n\n\n\nEnd Liveness.\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/Theory/LocalEquiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.15777429720240307}}
{"text": "Set Implicit Arguments.\n\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Axioms.\n\nFrom PromisingLib Require Import Event.\n\nRequire Import FoldN.\nRequire Import Knowledge.\n\nRequire Import Sequential.\nRequire Import FlagAux.\nRequire Import SimAux.\nRequire Import SeqAux.\nRequire Import Opt2.\n\nRequire Import ITreeLang.\n\nRequire Import DeadStoreElim.\nRequire Import DeadStoreElimProof1.\n\n\n\nSection MATCH.\n\n  Ltac dest_loc l1 l2 :=\n    destruct (Loc.eqb l1 l2) eqn:LOC;\n    [rewrite Loc.eqb_eq in LOC; clarify; try rewrite Loc.eqb_refl; ss |\n     hexploit LOC; intros DIFFL; rewrite Loc.eqb_sym in LOC; try rewrite LOC; apply Loc.eqb_neq in DIFFL; ss].\n\n\n  Let O2: Opt2.t := DSE_opt2.\n\n  Let bot := Opt2.bot O2.\n  Let init := Opt2.bot2 O2.\n  Let data_meet := @meet2 O2.\n  Let data_le := @le2 O2.\n  Let inst_gd := @inst_gd O2.\n  Let GD := GD O2.\n\n\n  Definition to_deferred0: Three -> Flag.t :=\n    fun t =>\n      match t with\n      | none\n      | half => false\n      | full => true\n      end.\n\n  Definition to_deferred: GD -> Flags.t :=\n    fun data => (fun l => to_deferred0 (data l)).\n\n  Lemma to_deferred0_bot: to_deferred0 (Opt2.bot O2) = false.\n  Proof. ss. Qed.\n\n  Lemma to_deferred_bot: to_deferred (Opt2.bot2 O2) = Flags.bot.\n  Proof. ss. Qed.\n\n  Lemma to_deferred0_mon: forall mp0 mp1 (LE: le mp0 mp1), Flag.le (to_deferred0 mp0) (to_deferred0 mp1).\n  Proof. i. destruct mp0, mp1; ss. Qed.\n\n  Lemma to_deferred_mon: forall mp0 mp1 (LE: data_le mp0 mp1), Flags.le (to_deferred mp0) (to_deferred mp1).\n  Proof. ii. apply to_deferred0_mon. apply LE. Qed.\n\n\n  Lemma to_deferred_na_sound:\n    forall (i: Inst.t) mp src_m val\n      (NA: is_na_inst i)\n    ,\n      Flags.le (to_deferred (inst_gd i mp))\n               (Flags.join (to_deferred mp) (update_mem_na val i src_m).(SeqMemory.flags)).\n  Proof.\n    ii. destruct i; ss.\n    all: unfold inst_gd, Opt2.inst_gd, mk_global, to_deferred, Flags.join; ss.\n    1,2,6,7: apply Flag.join_ge_l.\n    - rewrite update_load_ord1; auto. 2: destruct ord; ss. dest_loc rhs loc. apply Flag.join_ge_l.\n    - rewrite update_store_ord1; auto. dest_loc lhs loc.\n      + unfold Flags.update. rewrite Loc.eq_dec_eq. destruct (to_deferred0 (mp loc)); ss.\n      + apply Flag.join_ge_l.\n    - des.\n      + rewrite update_read_ord1; auto. dest_loc loc0 loc.\n        hexploit (ord_inv2 ordw); i; des.\n        * rewrite update_store_ord1; auto. rewrite Loc.eqb_sym; rewrite LOC. apply Flag.join_ge_l.\n        * rewrite update_store_ord2; auto. rewrite Loc.eqb_sym; rewrite LOC. apply Flag.join_ge_l.\n        * rewrite update_store_ord3; auto. rewrite Loc.eqb_sym; rewrite LOC.\n          etrans. 2: apply Flag.join_ge_l. apply to_deferred0_mon. apply rel_flag_le.\n      + rewrite update_store_ord1; auto. hexploit (ord_inv1' ordr); i; des.\n        * rewrite update_read_ord1; auto. dest_loc loc0 loc. apply Flag.join_ge_l.\n        * rewrite update_read_ord2; auto. dest_loc loc0 loc.\n          etrans. 2: apply Flag.join_ge_l. apply to_deferred0_mon. apply acq_flag_le.\n  Qed.\n\n\n\n  Definition match_cell (data: Three) (sv tv: Const.t) (sf tf: Flag.t) :=\n    match data with\n    | none =>\n      (sv = tv) /\\ (sf = tf)\n    | half =>\n      (sf = false) -> ((sv = tv) /\\ (sf = tf))\n    | full =>\n      True\n    end.\n\n  Definition match_mem (data: GD) (sm tm: SeqMemory.t) :=\n    forall l, match_cell (data l)\n                    (sm.(SeqMemory.value_map) l) (tm.(SeqMemory.value_map) l)\n                    (sm.(SeqMemory.flags) l) (tm.(SeqMemory.flags) l).\n\n  Lemma mcell_refl:\n    forall d v f, match_cell d v v f f.\n  Proof. i. unfold match_cell. des_ifs. Qed.\n\n  Lemma mm_refl:\n    forall d m, match_mem d m m.\n  Proof. unfold match_mem. i. apply mcell_refl. Qed.\n\n\n  Lemma mcell_bot:\n    forall sv tv sf tf (MCELL: match_cell bot sv tv sf tf), (sv = tv) /\\ (sf = tf).\n  Proof.\n    ii. unfold match_cell in MCELL. ss.\n  Qed.\n\n  Lemma mm_bot: forall sm tm (MM: match_mem init sm tm), sm = tm.\n  Proof.\n    i. unfold match_mem in MM. unfold match_cell in MM.\n    destruct sm, tm. f_equal; extensionality l; specialize MM with l; ss; des; auto.\n  Qed.\n\n\n  Lemma mcell_mon:\n    forall sv tv sf tf d0 d1\n      (LE: le d0 d1)\n      (MCELL: match_cell d0 sv tv sf tf)\n    ,\n      match_cell d1 sv tv sf tf.\n  Proof.\n    i. unfold match_cell in *. des_ifs.\n  Qed.\n\n  Lemma mm_mon:\n    forall sm tm mp0 mp1\n      (LE: data_le mp0 mp1)\n      (MM: match_mem mp0 sm tm)\n    ,\n      match_mem mp1 sm tm.\n  Proof.\n    i. unfold match_mem in *. i. eapply mcell_mon; eauto. eapply LE.\n  Qed.\n\n\n  Lemma mm_na:\n    forall (i: Inst.t) data sm tm\n      (MM: match_mem (inst_gd i data) sm tm)\n      (NA: is_na_inst i)\n      val usm utm\n      (USM: usm = update_mem_na val i sm)\n      (UTM: utm = update_mem_na val i tm)\n    ,\n      match_mem data usm utm.\n  Proof.\n    i. clarify. unfold inst_gd, Opt2.inst_gd, mk_global in MM. destruct i; ss; clarify.\n    - hexploit (ord_inv1 ord); i. des.\n      2: destruct ord; ss.\n      rewrite update_load_ord1f in MM; auto.\n      eapply mm_mon. 2: eapply MM. ii. dest_loc rhs p. refl.\n    - hexploit (ord_inv2 ord); i. des.\n      2,3: destruct ord; ss.\n      rewrite update_store_ord1f in MM; auto.\n      ii. ss. unfold ValueMap.write, Flags.update. dest_loc lhs l.\n      + rewrite ! Loc.eq_dec_eq. apply mcell_refl.\n      + rewrite ! Loc.eq_dec_neq; auto. unfold match_mem in MM. specialize MM with l.\n        rewrite Loc.eqb_sym in LOC. rewrite LOC in MM. auto.\n    - des.\n      + hexploit (ord_inv1' ordr); i. des.\n        2:{ destruct ordr; ss. }\n        rewrite update_read_ord1f in MM; auto.\n        eapply mm_mon. 2: eapply MM. ii. dest_loc loc p. rewrite Loc.eqb_sym in LOC.\n        hexploit (ord_inv2 ordw); i. des.\n        * rewrite update_store_ord1; auto. rewrite LOC. refl.\n        * rewrite update_store_ord2; auto. rewrite LOC. refl.\n        * rewrite update_store_ord3; auto. rewrite LOC. apply rel_flag_le.\n      + hexploit (ord_inv1' ordr); i. des.\n        * rewrite update_read_ord1f in MM; auto. ii. unfold match_mem in MM. specialize MM with l.\n          rewrite update_store_ord1 in MM; auto. dest_loc loc l. unfold match_cell. des_ifs.\n        * rewrite update_read_ord2f in MM; auto. ii. unfold match_mem in MM. specialize MM with l.\n          rewrite update_store_ord1 in MM; auto. unfold match_cell. dest_loc loc l; des_ifs.\n  Qed.\n\n  Lemma mm_load_same:\n    forall lhs rhs ord mp src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.load lhs rhs ord) mp) src_m tgt_m)\n    ,\n      SeqMemory.read rhs src_m = SeqMemory.read rhs tgt_m.\n  Proof.\n    i. unfold inst_gd, Opt2.inst_gd, mk_global, match_mem in MM. specialize MM with rhs. ss.\n    hexploit (ord_inv1 ord); i. des.\n    - rewrite update_load_ord1 in MM; auto. rewrite Loc.eqb_refl in MM. ss. des; auto.\n    - rewrite update_load_ord2 in MM; auto. rewrite Loc.eqb_refl in MM. ss. des; auto.\n  Qed.\n\n  Lemma mm_read_same:\n    forall lhs loc rmw ordr ordw mp src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.update lhs loc rmw ordr ordw) mp) src_m tgt_m)\n    ,\n      SeqMemory.read loc src_m = SeqMemory.read loc tgt_m.\n  Proof.\n    i. unfold inst_gd, Opt2.inst_gd, mk_global, match_mem in MM. specialize MM with loc. ss.\n    hexploit (ord_inv1' ordr); i. des.\n    - rewrite update_read_ord1 in MM; auto. rewrite Loc.eqb_refl in MM. ss. des; auto.\n    - rewrite update_read_ord2 in MM; auto. rewrite Loc.eqb_refl in MM. ss. des; auto.\n  Qed.\n\n\n  Lemma loc_eqb_is_dec:\n    forall a b, Loc.eqb a b = LocSet.Facts.eq_dec a b.\n  Proof.\n    i. dest_loc a b; auto.\n    - unfold proj_sumbool. rewrite Loc.eq_dec_eq; auto.\n    - unfold proj_sumbool. rewrite Loc.eq_dec_neq; auto.\n  Qed.\n\n  Ltac unfold_flags := unfold Flags.update, Flags.add, Flags.sub, Flags.sub_opt, Flags.meet, Flags.join, Flags.minus.\n  Ltac unfold_many := unfold_flags; unfold ValueMap.write, ValueMap.acquire, Perms.acquired.\n\n  Lemma mm_load_at:\n    forall mp p src_m tgt_m lhs rhs ord\n      (MM : match_mem (inst_gd (Inst.load lhs rhs ord) mp) src_m tgt_m)\n      val ev\n      (EVENT: ev = ProgramEvent.read rhs val ord)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.load lhs rhs ord) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev. hexploit (ord_inv1 ord). i; des.\n    { hexploit step_rlx; eauto. ss. destruct ord; ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_rlx_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ord; ss. i; des.\n      hexploit red_rlx_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ord; ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_load_ord1f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with rhs. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        { econs; eauto. refl. }\n        { econs; eauto. ii. unfold to_deferred. destruct (Loc.eqb rhs loc); ss. refl. }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs.\n        i. ss. des. apply mcell_refl.\n    }\n    { hexploit step_acq; eauto. ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_acq_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      hexploit red_acq_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_load_ord2f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with rhs. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        2:{ econs; eauto. refl. }\n        { econs; eauto. ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n          rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n          des_ifs. ss. unfold match_cell in MM. des_ifs; des; ss.\n          - rewrite flag_join_bot_r. rewrite MM0; refl.\n          - destruct (SeqMemory.flags src_m loc) eqn:SRCF, (SeqMemory.flags tgt_m loc) eqn:TGTF; ss. hexploit MM; auto; i; des; clarify.\n          - destruct (mp loc); ss.\n        }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss.\n        1,2: apply mcell_refl.\n        + eapply mcell_mon; eauto. apply acq_flag_le.\n        + destruct (mp l) eqn:MPL; ss; des. all: split; auto. apply MM in H. des; auto.\n    }\n  Qed.\n\n  Lemma mm_store_at:\n    forall mp p src_m tgt_m lhs rhs ord\n      (MM: match_mem (inst_gd (Inst.store lhs rhs ord) mp) src_m tgt_m)\n      val ev\n      (EVENT: ev = ProgramEvent.write lhs val ord)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.store lhs rhs ord) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev. hexploit (ord_inv2 ord). i; des.\n    { destruct ord; ss. }\n    { hexploit step_rlx; eauto. ss. destruct ord; ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_rlx_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ord; ss. i; des.\n      hexploit red_rlx_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ord; ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_store_ord2f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with lhs. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        { econs; eauto. refl. }\n        { econs; eauto. ii. unfold to_deferred. destruct (Loc.eqb lhs loc); ss. refl. }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs.\n        i. ss. des. apply mcell_refl.\n    }\n    { hexploit step_rel; eauto. ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_rel_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      hexploit red_rel_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_store_ord3f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with lhs. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        { econs; eauto. refl. }\n        { econs; eauto.\n          { i. unfold_many. unfold match_mem in MM. specialize MM with loc. rewrite Loc.eqb_sym in MM. rewrite loc_eqb_is_dec in MM.\n            des_ifs; ss. refl. unfold to_deferred in UNDEFERRED. destruct (mp loc); ss.\n            - des. rewrite MM. refl.\n            - des. rewrite MM. refl.\n          }\n          ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n          rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n          des_ifs. ss. unfold match_cell in MM. des_ifs; des; ss.\n          - rewrite flag_join_bot_r. rewrite MM0. apply Flag.join_ge_l.\n          - destruct (SeqMemory.flags src_m loc) eqn:SRCF, (SeqMemory.flags tgt_m loc) eqn:TGTF; ss. hexploit MM; auto; i; des; clarify.\n          - destruct (mp loc); ss.\n            destruct (SeqMemory.flags src_m loc) eqn:SRCF, (SeqMemory.flags tgt_m loc) eqn:TGTF; ss.\n        }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss.\n        1: apply mcell_refl.\n        destruct (mp l) eqn:MPL; ss; des. all: split; auto.\n    }\n  Qed.\n\n  Lemma mm_update_failure_at:\n    forall lhs loc rmw ordr ordw mp p src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.update lhs loc rmw ordr ordw) mp) src_m tgt_m)\n      val ev\n      (EVENT: ev = ProgramEvent.read loc val ordr)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.update lhs loc rmw ordr ordw) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev. hexploit (ord_inv1' ordr). i; des.\n    { destruct ordr; ss. }\n    hexploit (ord_inv1 ordr). i; des.\n    { hexploit step_rlx; eauto. ss. destruct ordr; ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_rlx_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. i; des.\n      hexploit red_rlx_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_read_ord2f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        2:{ econs; eauto. refl. }\n        { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc0.\n          destruct (Loc.eqb loc loc0) eqn:LOC; ss.\n          hexploit (ord_inv2 ordw). i; des.\n          - rewrite update_store_ord1 in *; auto. rewrite LOC in *. apply to_deferred0_mon. apply acq_flag_le.\n          - rewrite update_store_ord2 in *; auto. rewrite LOC in *. apply to_deferred0_mon. apply acq_flag_le.\n          - rewrite update_store_ord3 in *; auto. rewrite LOC in *. apply to_deferred0_mon.\n            etrans. eapply acq_flag_le. apply rel_flag_le.\n        }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss; des.\n        + apply mcell_refl.\n        + eapply mcell_mon; eauto. apply Loc.eqb_neq in n. rewrite Loc.eqb_sym in n. hexploit (ord_inv2 ordw). i; des.\n          * rewrite update_store_ord1; auto. rewrite n. apply acq_flag_le.\n          * rewrite update_store_ord2; auto. rewrite n. apply acq_flag_le.\n          * rewrite update_store_ord3; auto. rewrite n. etrans. eapply acq_flag_le. apply rel_flag_le.\n    }\n    { hexploit step_acq; eauto. ss. i; des.\n      do 2 eexists. split; eauto.\n      hexploit red_acq_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      hexploit red_acq_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n      clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n      unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n      rewrite update_read_ord2f in *; auto. splits; ss.\n      - econs; ss; eauto.\n        { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n          econs; ss; eauto; try refl.\n          unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n        }\n        2:{ econs; eauto. refl. }\n        { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc0.\n          unfold_flags. rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n          des_ifs. ss. apply Loc.eqb_neq in n. rewrite Loc.eqb_sym in n. rename n into LOC.\n          hexploit (ord_inv2 ordw). i; des.\n          - rewrite update_store_ord1 in *; auto. rewrite LOC in *. destruct (mp loc0) eqn:MPL; ss; des.\n            + rewrite flag_join_bot_r. rewrite MM0. refl.\n            + rewrite flag_join_bot_r. match goal with | [|- _ (Flag.le ?a ?b)] => destruct a; destruct b; ss end. hexploit MM; auto; i; des; clarify.\n            + rewrite flag_join_bot_r. match goal with | [|- _ (Flag.le ?a ?b)] => destruct a; destruct b; ss end. hexploit MM; auto; i; des; clarify.\n          - rewrite update_store_ord2 in *; auto. rewrite LOC in *. destruct (mp loc0) eqn:MPL; ss; des.\n            + rewrite flag_join_bot_r. rewrite MM0. refl.\n            + rewrite flag_join_bot_r. match goal with | [|- _ (Flag.le ?a ?b)] => destruct a; destruct b; ss end. hexploit MM; auto; i; des; clarify.\n            + rewrite flag_join_bot_r. match goal with | [|- _ (Flag.le ?a ?b)] => destruct a; destruct b; ss end. hexploit MM; auto; i; des; clarify.\n          - rewrite update_store_ord3 in *; auto. rewrite LOC in *. destruct (mp loc0) eqn:MPL; ss; des.\n            + rewrite flag_join_bot_r. rewrite MM0. refl.\n            + rewrite flag_join_bot_r. rewrite MM0. refl.\n            + rewrite flag_join_bot_r. match goal with | [|- _ (Flag.le ?a ?b)] => destruct a; destruct b; ss end. hexploit MM; auto; i; des; clarify.\n        }\n      - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n        unfold_many.\n        ii. ss. unfold match_mem in MM; specialize MM with l. depgen MM. clear.\n        rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss; des.\n        1,2: apply mcell_refl.\n        + eapply mcell_mon; eauto. apply Loc.eqb_neq in n. rewrite Loc.eqb_sym in n. hexploit (ord_inv2 ordw). i; des.\n          * rewrite update_store_ord1; auto. rewrite n. apply acq_flag_le.\n          * rewrite update_store_ord2; auto. rewrite n. apply acq_flag_le.\n          * rewrite update_store_ord3; auto. rewrite n. etrans. eapply acq_flag_le. apply rel_flag_le.\n        + apply Loc.eqb_neq in n. rewrite Loc.eqb_sym in n. hexploit (ord_inv2 ordw). i; des.\n          * rewrite update_store_ord1 in *; auto. rewrite n in *. destruct (mp l) eqn:MPL; ss; i; des; auto. apply MM in H0; des; auto.\n          * rewrite update_store_ord2 in *; auto. rewrite n in *. destruct (mp l) eqn:MPL; ss; i; des; auto. apply MM in H0; des; auto.\n          * rewrite update_store_ord3 in *; auto. rewrite n in *. destruct (mp l) eqn:MPL; ss; i; des; auto.\n    }\n  Qed.\n\n  Lemma mm_update_success_at:\n    forall lhs loc rmw ordr ordw mp p src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.update lhs loc rmw ordr ordw) mp) src_m tgt_m)\n      valr valw ev\n      (EVENT: ev = ProgramEvent.update loc valr valw ordr ordw)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.update lhs loc rmw ordr ordw) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev. hexploit (ord_inv1' ordr). i; des.\n    { destruct ordr; ss. }\n    hexploit (ord_inv1 ordr). i; des.\n    { hexploit (ord_inv2 ordw). i; des.\n      { apply andb_prop in ATOMIC. des. destruct ordw; ss. }\n      { hexploit step_rlx; eauto. ss. destruct ordr; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_rlx_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. destruct ordw; ss. i; des.\n        hexploit red_rlx_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_read_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n            econs; ss; eauto; try refl.\n            unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n          }\n          2:{ econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc0.\n            destruct (Loc.eqb loc loc0) eqn:LOC; ss.\n            rewrite update_store_ord2 in *; auto. rewrite LOC in *; ss.\n            apply to_deferred0_mon. apply acq_flag_le.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_store_ord2 in *; auto. depgen MM. clear.\n          rewrite Loc.eqb_sym. rewrite ! loc_eqb_is_dec. des_ifs; i; ss; des.\n          + apply mcell_refl.\n          + eapply mcell_mon; eauto. apply acq_flag_le.\n      }\n      { hexploit step_rel; eauto. ss. destruct ordr; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_rel_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. i; des.\n        hexploit red_rel_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_read_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n            econs; ss; eauto; try refl.\n            unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n          }\n          { econs; eauto. refl. }\n          { econs; eauto.\n            { i. unfold_many. unfold match_mem in MM. specialize MM with loc0.\n              rewrite update_store_ord3 in *; auto.\n              rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in MM. depgen UNDEFERRED. depgen MM.\n              clear. des_ifs; i; ss. refl. unfold to_deferred in UNDEFERRED.\n              destruct (mp loc0) eqn:MPL; ss; des.\n              - rewrite MM; refl.\n              - rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc0.\n            rewrite update_store_ord3 in *; auto.\n            rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n            des_ifs. ss. destruct (mp loc0) eqn:MPL; ss; des.\n            - rewrite MM0. refl.\n            - rewrite MM0. refl.\n            - destruct (SeqMemory.flags src_m loc0), (SeqMemory.flags tgt_m loc0); ss.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_store_ord3 in *; auto.\n          depgen MM. clear. rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss.\n          1: apply mcell_refl.\n          destruct (mp l) eqn:MPL; ss; des. all: split; auto.\n      }\n    }\n    { hexploit (ord_inv2 ordw). i; des.\n      { apply andb_prop in ATOMIC. des. destruct ordw; ss. }\n      { hexploit step_acq; eauto. ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordw; ss. i; des.\n        hexploit red_acq_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_read_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n            econs; ss; eauto; try refl.\n            unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n          }\n          2:{ econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc0.\n            unfold_flags. rewrite update_store_ord2 in *; auto.\n            rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n            des_ifs. ss. destruct (mp loc0) eqn:MPL; ss; des; auto.\n            all: rewrite flag_join_bot_r.\n            1: rewrite MM0; refl.\n            all: match goal with | [|- _ (_ ?a ?b)] => destruct a; destruct b; ss; auto end; hexploit MM; auto; i; des; auto.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_store_ord2 in *; auto.\n          depgen MM. clear. rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss; des.\n          1,2: apply mcell_refl.\n          + eapply mcell_mon; eauto. apply acq_flag_le.\n          + destruct (mp l) eqn:MPL; ss; i; des; auto. apply MM in H; des; auto.\n      }\n      { hexploit step_acq_rel; eauto. ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq_rel_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n        hexploit red_acq_rel_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0. inv EVACC; inv EVACC0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_read_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { unfold match_mem in MM; specialize MM with loc. rewrite Loc.eqb_refl in MM. ss; des. rewrite MM; rewrite MM0.\n            econs; ss; eauto; try refl.\n            unfold to_deferred. rewrite Loc.eqb_refl. ss. rewrite flag_join_bot_r. refl.\n          }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc0.\n            unfold_flags. rewrite update_store_ord3 in *; auto.\n            rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n            des_ifs. ss. destruct (mp loc0) eqn:MPL; ss; des; auto.\n            all: rewrite flag_join_bot_r.\n            1,2: rewrite MM0; refl.\n            match goal with | [|- _ (_ ?a ?b)] => destruct a; destruct b; ss; auto end; hexploit MM; auto; i; des; auto.\n          }\n          { econs; eauto.\n            { i. unfold_many. unfold match_mem in MM. specialize MM with loc0.\n              rewrite update_store_ord3 in *; auto.\n              rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in MM. depgen UNDEFERRED. depgen MM.\n              clear. des_ifs; i; ss. 1,2,4: refl. unfold to_deferred in UNDEFERRED.\n              destruct (mp loc0) eqn:MPL; ss; des.\n              - rewrite MM; refl.\n              - rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc0.\n            instantiate (1:=(to_deferred mp)). unfold to_deferred.\n            rewrite update_store_ord3 in *; auto.\n            rewrite Loc.eqb_sym in *. rewrite loc_eqb_is_dec in *. depgen MM. clear; i.\n            des_ifs; ss. refl. destruct (mp loc0) eqn:MPL; ss; des.\n            - rewrite MM0. refl.\n            - rewrite MM0. refl.\n            - destruct (SeqMemory.flags src_m loc0), (SeqMemory.flags tgt_m loc0); ss.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_store_ord3 in *; auto.\n          depgen MM. clear. rewrite Loc.eqb_sym. rewrite loc_eqb_is_dec. des_ifs; i; ss; des.\n          1,2: apply mcell_refl.\n          + destruct (mp l) eqn:MPL; ss; i; des; auto.\n          + destruct (mp l) eqn:MPL; ss; i; des; auto.\n      }\n    }\n  Qed.\n\n  Lemma mm_fence:\n    forall ordr ordw mp p src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.fence ordr ordw) mp) src_m tgt_m)\n      ev\n      (EVENT: ev = ProgramEvent.fence ordr ordw)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.fence ordr ordw) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev. hexploit (ord_inv3 ordr). i; des.\n    { hexploit (ord_inv3' ordw). i; des.\n      { hexploit step_rlx2; eauto. ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_rlx2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        hexploit red_rlx2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord1f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          { econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc.\n            rewrite update_fence_w_ord1 in *; auto. refl.\n          }\n        - destruct mem_src, mem_tgt.\n          ii. ss. unfold match_mem in MM; specialize MM with l. ss.\n          rewrite update_fence_w_ord1 in *; auto.\n      }\n      { hexploit step_rel2; eauto. ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_rel2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        hexploit red_rel2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord1f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          { econs; eauto. refl. }\n          { econs; eauto.\n            { i. unfold match_mem in MM. specialize MM with loc.\n              rewrite update_fence_w_ord2 in *; auto.\n              depgen UNDEFERRED. depgen MM.\n              clear. i; ss. unfold to_deferred in UNDEFERRED.\n              destruct (mp loc) eqn:MPL; ss; des.\n              - rewrite MM; refl.\n              - rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n            rewrite update_fence_w_ord2 in *; auto. depgen MM. clear; i.\n            destruct (mp loc) eqn:MPL; ss; des.\n            - rewrite MM0. refl.\n            - rewrite MM0. refl.\n            - destruct (SeqMemory.flags src_m loc), (SeqMemory.flags tgt_m loc); ss.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_fence_w_ord2 in *; auto.\n          depgen MM. clear. i; ss.\n          destruct (mp l) eqn:MPL; ss; des. all: split; auto.\n      }\n      { hexploit step_acq_rel2; eauto. ss. destruct ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq_rel2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        hexploit red_acq_rel2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord1f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc.\n            unfold_flags. rewrite update_fence_w_ord3 in *; auto. depgen MM. clear; i.\n            destruct (mp loc); ss; des. all: rewrite flag_join_bot_r.\n            all: rewrite MM0; refl.\n          }\n          { econs; eauto.\n            { i. unfold_many. unfold match_mem in MM. specialize MM with loc.\n              rewrite update_fence_w_ord3 in *; auto. depgen UNDEFERRED. depgen MM. clear; i.\n              unfold to_deferred in *. destruct (mp loc); ss; des.\n              all: rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n            instantiate (1:=(to_deferred mp)). unfold to_deferred.\n            rewrite update_fence_w_ord3 in *; auto. depgen MM. clear; i.\n            destruct (mp loc) eqn:MPL; ss; des. all: rewrite MM0; refl.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_fence_w_ord3 in *; auto.\n          depgen MM. clear; i. destruct (mp l) eqn:MPL; ss; des. all: split; auto. all: rewrite MM; refl.\n      }\n    }\n    { hexploit (ord_inv3' ordw). i; des.\n      { hexploit step_acq2; eauto. ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        hexploit red_acq2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. destruct ordr, ordw; ss. destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          2:{ econs; eauto. refl. }\n          { econs; eauto. unfold to_deferred. ii. unfold_flags. unfold match_mem in MM; specialize MM with loc.\n            rewrite update_fence_w_ord1 in *; auto. depgen MM. clear; i.\n            destruct (mp loc); ss; des. all: rewrite flag_join_bot_r. all: try by (rewrite MM0; refl).\n            all: match goal with | [|- _ (_ ?a ?b)] => destruct a, b; ss end.\n            all: hexploit MM; auto; i; des; clarify.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          ii. ss. unfold_many. unfold match_mem in MM; specialize MM with l.\n          rewrite update_fence_w_ord1 in *; auto. depgen MM. clear; i.\n          destruct (mp l); ss; des.\n          + rewrite MM, MM0. split; refl.\n          + i. apply MM in H; des; auto. rewrite H, H0. auto.\n      }\n      { hexploit step_acq_rel2; eauto. ss. destruct ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq_rel2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        hexploit red_acq_rel2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc.\n            unfold_flags. rewrite update_fence_w_ord2 in *; auto. depgen MM. clear; i.\n            destruct (mp loc); ss; des. all: rewrite flag_join_bot_r.\n            all: try (rewrite MM0; refl).\n            destruct (SeqMemory.flags src_m loc) eqn:SMF, (SeqMemory.flags tgt_m loc) eqn: TMF; ss. hexploit MM; auto; i; des; clarify.\n          }\n          { econs; eauto.\n            { i. unfold_many. unfold match_mem in MM. specialize MM with loc.\n              rewrite update_fence_w_ord2 in *; auto. depgen UNDEFERRED. depgen MM. clear; i.\n              unfold to_deferred in *. destruct (mp loc); ss; des.\n              all: rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n            rewrite update_fence_w_ord2 in *; auto.\n            instantiate (1:=(to_deferred mp)). unfold to_deferred.\n            depgen MM. clear; i.\n            destruct (mp loc) eqn:MPL; ss; des. all: try (rewrite MM0; refl).\n            destruct (SeqMemory.flags src_m loc) eqn:SMF, (SeqMemory.flags tgt_m loc) eqn: TMF; ss.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_fence_w_ord2 in *; auto.\n          depgen MM. clear; i. destruct (mp l) eqn:MPL; ss; des. all: split; auto. all: rewrite MM; refl.\n      }\n      { hexploit step_acq_rel2; eauto. ss. destruct ordw; ss. destruct ordw; ss. i; des.\n        do 2 eexists. split; eauto.\n        hexploit red_acq_rel2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        hexploit red_acq_rel2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. 1,2: destruct ordw; ss. i; des.\n        clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n        unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n        rewrite update_fence_r_ord2f in *; auto. splits; ss.\n        - econs; ss; eauto.\n          { econs; eauto. refl. }\n          { econs; eauto. ii. unfold to_deferred. unfold match_mem in MM. specialize MM with loc.\n            unfold_flags. rewrite update_fence_w_ord3 in *; auto. depgen MM. clear; i.\n            destruct (mp loc); ss; des. all: rewrite flag_join_bot_r.\n            all: rewrite MM0; refl.\n          }\n          { econs; eauto.\n            { i. unfold_many. unfold match_mem in MM. specialize MM with loc.\n              rewrite update_fence_w_ord3 in *; auto. depgen UNDEFERRED. depgen MM. clear; i.\n              unfold to_deferred in *. destruct (mp loc); ss; des.\n              all: rewrite MM; refl.\n            }\n            ii. unfold to_deferred. unfold_flags. unfold match_mem in MM. specialize MM with loc.\n            instantiate (1:=(to_deferred mp)). unfold to_deferred.\n            rewrite update_fence_w_ord3 in *; auto. depgen MM. clear; i.\n            destruct (mp loc) eqn:MPL; ss; des. all: rewrite MM0; refl.\n          }\n        - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n          unfold_many.\n          ii. ss. unfold match_mem in MM; specialize MM with l. rewrite update_fence_w_ord3 in *; auto.\n          depgen MM. clear; i. destruct (mp l) eqn:MPL; ss; des. all: split; auto. all: rewrite MM; refl.\n      }\n    }\n  Qed.\n\n  Lemma mm_syscall:\n    forall lhs rhses mp p src_m tgt_m\n      (MM: match_mem (inst_gd (Inst.syscall lhs rhses) mp) src_m tgt_m)\n      ev sev\n      (EVENT: ev = ProgramEvent.syscall sev)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd (Inst.syscall lhs rhses) mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. subst ev.\n    hexploit step_acq_rel2; eauto. ss. i; des.\n    do 2 eexists. split; eauto.\n    hexploit red_acq_rel2_full. 6: eapply STEP_TGT. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n    hexploit red_acq_rel2_full. 6: eapply STEP_SRC. 2: eapply ATOMIC. 1,2,3,4: ss. i; des.\n    clear PERM0. subst i_src i_tgt p1. rewrite OO in OO0. inv OO0.\n    unfold inst_gd, Opt2.inst_gd, mk_global in *. ss.\n    apply mm_bot in MM. subst tgt_m. splits; ss.\n    - econs; ss; eauto.\n      { econs; eauto. refl. }\n      { econs; eauto. ii. unfold to_deferred. unfold_flags. ss. rewrite flag_join_bot_r. refl. }\n      { econs; eauto.\n        { i. unfold_many. refl. }\n        ii. refl.\n      }\n    - destruct mem_src, mem_tgt. ss. rewrite MEMV, MEMF, MEMV0, MEMF0; clear MEMV MEMF MEMV0 MEMF0.\n      unfold_many.\n      ii. ss. apply mcell_refl.\n  Qed.\n\n  Lemma mm_at:\n    forall mp p src_m tgt_m inst\n      (MM: match_mem (inst_gd inst mp) src_m tgt_m)\n      ev\n      (EVENT: match_inst_pe inst ev)\n      (ATOMIC: is_atomic_event ev)\n      i_tgt o p1 mem_tgt\n      (INPUT: SeqEvent.wf_input ev i_tgt)\n      (OUTPUT: Oracle.wf_output ev o)\n      (STEP_TGT: SeqEvent.step i_tgt o p tgt_m p1 mem_tgt)\n    ,\n    exists (i_src : SeqEvent.input) (mem_src : SeqMemory.t),\n      SeqEvent.step i_src o p src_m p1 mem_src /\\\n      SeqEvent.input_match (to_deferred (inst_gd inst mp)) (to_deferred mp) i_src i_tgt /\\\n      SeqEvent.wf_input ev i_src /\\\n      match_mem mp mem_src mem_tgt.\n  Proof.\n    i. destruct ev; try by ss. all: inv EVENT.\n    eapply mm_load_at; eauto. eapply mm_update_failure_at; eauto.\n    eapply mm_store_at; eauto. eapply mm_update_success_at; eauto.\n    eapply mm_fence; eauto. eapply mm_syscall; eauto.\n  Qed.\n\nEnd MATCH.\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/optimizer/DeadStoreElimProof2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.1577742939612602}}
{"text": "(*TODO: These imports should be pared down*)\nRequire Import FSets.\nRequire FSetAVL.\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import compcert.lib.Ordered.\nRequire Import AST.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\n\nRequire Import Ctypes.\nRequire Import Cop.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.reach.\n\n(** Properties of values obtained by casting to a given type. *)\n\nInductive val_casted: val -> type -> Prop :=\n  | val_casted_int: forall sz si attr n,\n      cast_int_int sz si n = n ->\n      val_casted (Vint n) (Tint sz si attr)\n  | val_casted_float: forall sz attr n,\n      cast_float_float sz n = n ->\n      val_casted (Vfloat n) (Tfloat sz attr)\n  | val_casted_long: forall si attr n,\n      val_casted (Vlong n) (Tlong si attr)\n  | val_casted_ptr_ptr: forall b ofs ty attr,\n      val_casted (Vptr b ofs) (Tpointer ty attr)\n  | val_casted_int_ptr: forall n ty attr,\n      val_casted (Vint n) (Tpointer ty attr)\n  | val_casted_ptr_int: forall b ofs si attr,\n      val_casted (Vptr b ofs) (Tint I32 si attr)\n  | val_casted_ptr_cptr: forall b ofs id attr,\n      val_casted (Vptr b ofs) (Tcomp_ptr id attr)\n  | val_casted_int_cptr: forall n id attr,\n      val_casted (Vint n) (Tcomp_ptr id attr)\n  | val_casted_struct: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tstruct id fld attr)\n  | val_casted_union: forall id fld attr b ofs,\n      val_casted (Vptr b ofs) (Tunion id fld attr)\n  | val_casted_void: forall v,\n      val_casted v Tvoid.\n\nDefinition val_casted_func (v : val) (t : type) : bool :=\n  match v, t with\n    | Vint n, Tint sz si attr =>\n      if Int.eq_dec (cast_int_int sz si n) n then true\n      else false\n    | Vfloat n, Tfloat sz attr =>\n      if Float.eq_dec (cast_float_float sz n) n then true\n      else false\n    | Vlong n, Tlong si attr => true\n    | Vptr b ofs, Tpointer ty attr => true\n    | Vint n, Tpointer ty attr => true\n    | Vptr b ofs, Tint I32 si attr => true\n    | Vptr b ofs, Tcomp_ptr id attr => true\n    | Vint n, Tcomp_ptr id attr => true\n    | Vptr b ofs, Tstruct id flt attr => true\n    | Vptr b ofs, Tunion id flt attr => true\n    | _, Tvoid => true\n    | _, _ => false\n  end.\n\nLemma val_casted_funcI v t :\n  val_casted v t ->\n  val_casted_func v t=true.\nProof.\ndestruct 1; simpl; auto.\nrewrite H. case_eq (Int.eq_dec n n); auto.\nrewrite H. case_eq (Float.eq_dec n n); auto.\ndestruct v; auto.\nQed.\n\nLemma val_casted_funcE v t :\n  val_casted_func v t=true ->\n  val_casted v t.\nProof.\ndestruct v; destruct t; simpl; try solve[inversion 1;econstructor; eauto].\ncase_eq (Int.eq_dec (cast_int_int i0 s i) i). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ncase_eq (Float.eq_dec (cast_float_float f0 f) f). intros e _ _.\nconstructor; auto. intros n _; inversion 1.\ndestruct i0; try inversion 1. constructor.\nQed.\n\nLemma val_casted_funcP v t :\n  val_casted_func v t=true <-> val_casted v t.\nProof.\nsplit; [apply val_casted_funcE|apply val_casted_funcI].\nQed.\n\nRemark cast_int_int_idem:\n  forall sz sg i, cast_int_int sz sg (cast_int_int sz sg i) = cast_int_int sz sg i.\nProof.\n  intros. destruct sz; simpl; auto.\n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct sg; [apply Int.sign_ext_idem|apply Int.zero_ext_idem]; compute; intuition congruence.\n  destruct (Int.eq i Int.zero); auto.\nQed.\n\nRemark cast_float_float_idem:\n  forall sz f, cast_float_float sz (cast_float_float sz f) = cast_float_float sz f.\nProof.\n  intros; destruct sz; simpl.\n  apply Float.singleoffloat_idem; auto.\n  auto.\nQed.\n\nLemma cast_val_is_casted:\n  forall v ty ty' v', sem_cast v ty ty' = Some v' -> val_casted v' ty'.\nProof.\n  unfold sem_cast; intros. destruct ty'; simpl in *.\n(* void *)\n  constructor.\n(* int *)\n  destruct i; destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. apply (cast_int_int_idem I8 s).\n  constructor. apply (cast_int_int_idem I8 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I8 s).\n  constructor. apply (cast_int_int_idem I16 s).\n  constructor. apply (cast_int_int_idem I16 s).\n  destruct (cast_float_int s f0); inv H1.   constructor. apply (cast_int_int_idem I16 s).\n  constructor. auto.\n  constructor.\n  constructor. auto.\n  destruct (cast_float_int s f0); inv H1. constructor. auto.\n  constructor. auto.\n  constructor.\n  constructor; auto.\n  constructor.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor. simpl. destruct (Int64.eq i Int64.zero); auto.\n  constructor. simpl. destruct (Float.cmp Ceq f0 Float.zero); auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i Int.zero); auto.\n  constructor; auto.\n  constructor. simpl. destruct (Int.eq i0 Int.zero); auto.\n  constructor; auto.\n(* long *)\n  destruct ty; try discriminate.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; try discriminate. destruct (cast_float_long s f0); inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n  destruct v; inv H. constructor.\n(* float *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H.\n  constructor. unfold cast_float_float, cast_int_float.\n  destruct f; destruct s; auto.\n  rewrite Float.singleofint_floatofint. apply Float.singleoffloat_idem.\n  rewrite Float.singleofintu_floatofintu. apply Float.singleoffloat_idem.\n  constructor. unfold cast_float_float, cast_long_float.\n  destruct f; destruct s; auto. apply Float.singleoflong_idem. apply Float.singleoflongu_idem.\n  constructor. apply cast_float_float_idem.\n(* pointer *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; try constructor.\n(* impossible cases *)\n  discriminate.\n  discriminate.\n(* structs *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* unions *)\n  destruct ty; try discriminate; destruct v; try discriminate.\n  destruct (ident_eq i0 i && fieldlist_eq f0 f); inv H; constructor.\n(* comp_ptr *)\n  destruct ty; simpl in H; try discriminate; destruct v; inv H; constructor.\nQed.\n\nLemma val_casted_load_result:\n  forall v ty chunk,\n  val_casted v ty -> access_mode ty = By_value chunk ->\n  Val.load_result chunk v = v.\nProof.\n  intros. inversion H; clear H; subst v ty; simpl in H0.\n  destruct sz.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  destruct si; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  clear H1. inv H0. auto.\n  inversion H0; clear H0; subst chunk. simpl in *.\n  destruct (Int.eq n Int.zero); subst n; reflexivity.\n  destruct sz; inversion H0; clear H0; subst chunk; simpl in *; congruence.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  inv H0; auto.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\n  discriminate.\nQed.\n\nLemma cast_val_casted:\n  forall v ty, val_casted v ty -> sem_cast v ty ty = Some v.\nProof.\n  intros. inversion H; clear H; subst v ty; unfold sem_cast; simpl; auto.\n  destruct sz; congruence.\n  congruence.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\n  unfold proj_sumbool; repeat rewrite dec_eq_true; auto.\nQed.\n\nLemma val_casted_inject:\n  forall f v v' ty,\n  val_inject f v v' -> val_casted v ty -> val_casted v' ty.\nProof.\n  intros. inv H; auto.\n  inv H0; constructor.\n  inv H0; constructor.\nQed.\n\nInductive val_casted_list: list val -> typelist -> Prop :=\n  | vcl_nil:\n      val_casted_list nil Tnil\n  | vcl_cons: forall v1 vl ty1 tyl,\n      val_casted v1 ty1 -> val_casted_list vl tyl ->\n      val_casted_list (v1 :: vl) (Tcons  ty1 tyl).\n\nLemma val_casted_list_params:\n  forall params vl,\n  val_casted_list vl (type_of_params params) ->\n  list_forall2 val_casted vl (map snd params).\nProof.\n  induction params; simpl; intros.\n  inv H. constructor.\n  destruct a as [id ty]. inv H. constructor; auto.\nQed.\n\nFixpoint val_casted_list_func (vs : list val) (ts : typelist) : bool :=\n  match vs, ts with\n    | nil, Tnil => true\n    | v1 :: vl, Tcons ty1 tyl =>\n      val_casted_func v1 ty1 && val_casted_list_func vl tyl\n    | _, _ => false\n  end.\n\nLemma val_casted_list_funcP vs ts :\n  val_casted_list_func vs ts=true <-> val_casted_list vs ts.\nProof.\nrevert ts; induction vs. destruct ts; simpl; auto.\nsplit; auto. intros _. constructor.\nsplit; auto. inversion 1. inversion 1.\nsplit; auto. destruct ts; simpl; auto.\ninversion 1. rewrite andb_true_iff. intros [H1 H2]. constructor.\napply val_casted_funcE in H1; auto. rewrite <-IHvs; auto.\ninversion 1; subst. simpl. rewrite andb_true_iff; split.\napply val_casted_funcI; auto. rewrite IHvs; auto.\nQed.\n\nLemma val_casted_inj (j : meminj) v1 v2 tv :\n  val_inject j v1 v2 ->\n  val_casted v1 tv ->\n  val_casted v2 tv.\nProof.\ninversion 1; subst; auto.\ninversion 1; subst; auto; try solve[constructor; auto].\ninversion 1; constructor.\nQed.\n\nLemma val_casted_list_inj (j : meminj) vs1 vs2 ts :\n  val_list_inject j vs1 vs2 ->\n  val_casted_list vs1 ts ->\n  val_casted_list vs2 ts.\nProof.\nintros H1; revert vs1 vs2 H1; induction ts; simpl; intros vs1 vs2 H1 H2.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\nrevert H2 H1; inversion 1; subst. inversion 1; subst. constructor.\neapply val_casted_inj; eauto.\neapply IHts; eauto.\nQed.\n\nDefinition val_has_type_func (v : val) (t : typ) : bool :=\n  match v with\n    | Vundef => true\n    | Vint _ => match t with\n                  | AST.Tint => true\n                  | _ => false\n                end\n    | Vlong _ => match t with\n                 | AST.Tlong => true\n                 | _ => false\n               end\n    | Vfloat f => match t with\n                    | AST.Tfloat => true\n                    | Tsingle => if Float.is_single_dec f then true else false\n                    | _ => false\n                  end\n    | Vptr _ _ => match t with\n                    | AST.Tint => true\n                    | _ => false\n                  end\n  end.\n\nLemma val_has_type_funcP v t :\n  Val.has_type v t <-> (val_has_type_func v t=true).\nProof.\nsplit.\ninduction v; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto.\nsimpl. destruct t; auto. destruct (Float.is_single_dec f); auto.\nsimpl. destruct t; auto.\ninduction v; simpl; auto.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try inversion 1.\ndestruct t; auto; try solve[inversion 1].\ndestruct (Float.is_single_dec f); try solve[inversion 1|auto].\ndestruct t; auto. inversion 1. inversion 1. inversion 1.\nQed.\n\nFixpoint val_has_type_list_func (vl : list val) (tyl : list typ) : bool :=\n  match vl, tyl with\n    | nil, nil => true\n    | v :: vl', ty :: tyl' => val_has_type_func v ty\n                              && val_has_type_list_func vl' tyl'\n    | nil, _ :: _ => false\n    | _ :: _, nil => false\n  end.\n\nLemma val_has_type_list_func_charact vl tyl :\n  Val.has_type_list vl tyl <-> (val_has_type_list_func vl tyl=true).\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl. split; auto. simpl. split; auto. inversion 1.\nintros. destruct tyl. simpl. split; auto. inversion 1.\nsimpl. split. intros [H H2].\n+ rewrite andb_true_iff. split.\n  rewrite <-val_has_type_funcP; auto.\n  rewrite <-IHvl; auto.\n+ rewrite andb_true_iff. intros [H H2]. split.\n  rewrite val_has_type_funcP; auto.\n  rewrite IHvl; auto.\nQed.\n\nFixpoint tys_nonvoid (tyl : typelist) :=\n  match tyl with\n    | Tnil => true\n    | Tcons Tvoid tyl' => false\n    | Tcons _ tyl' => tys_nonvoid tyl'\n  end.\n\nFixpoint vals_defined (vl : list val) :=\n  match vl with\n    | nil => true\n    | Vundef :: _ => false\n    | _ :: vl' => vals_defined vl'\n  end.\n\nLemma vals_inject_defined (vl1 vl2 : list val) (j : meminj) :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  vals_defined vl2=true.\nProof.\nrevert vl2; induction vl1; simpl. destruct vl2; try solve[inversion 1|auto].\nintros vl2; inversion 1; subst. destruct a; try solve[inversion 1].\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\ninv H. inv H5. simpl. intros X. rewrite (IHvl1 vl'); auto.\nQed.\n\nLemma valinject_hastype':\n  forall (j : meminj) (v v' : val),\n    val_inject j v v' ->\n    v <> Vundef ->\n    forall T : typ, Val.has_type v T -> Val.has_type v' T.\nProof.\n  intros.\n  induction H; auto.\n  elim H0; auto.\nQed.\n\nLemma val_list_inject_hastype j vl1 vl2 tys :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  val_has_type_list_func vl1 tys=true ->\n  val_has_type_list_func vl2 tys=true.\nProof.\nrevert vl2 tys. induction vl1. inversion 1. solve[destruct tys; simpl; auto].\nintros H tys H1 H2 H3. inv H1.\nassert (def: vals_defined vl1=true).\n{ inv H2. revert H0. destruct a; auto. congruence. }\nsimpl. destruct tys. simpl in H3; congruence.\nrewrite andb_true_iff. split.\nrewrite <-val_has_type_funcP. eapply valinject_hastype'; eauto.\nsimpl in H2. intros contra. rewrite contra in H2. congruence.\ninv H3. rewrite andb_true_iff in H0.\n  destruct H0 as [H0 _]. solve[rewrite val_has_type_funcP; auto].\neapply (IHvl1 vl'); eauto.\ninv H3. rewrite H0. rewrite andb_true_iff in H0.\n  solve[destruct H0 as [_ ->]; auto].\nQed.\n\nLemma val_list_inject_defined j vl1 vl2 :\n  val_list_inject j vl1 vl2 ->\n  vals_defined vl1=true ->\n  vals_defined vl2=true.\nProof.\nrevert vl2. induction vl1; simpl.\n+ intros vl2; inversion 1; auto.\n+ intros vl2; inversion 1; subst. inv H.\nsimpl. intros H8.\nassert (def1: vals_defined vl1=true).\n{ destruct a; try solve[congruence]. }\nrevert H2 H8. inversion 1; auto. subst. congruence.\nQed.\n\n(*TODO: put these in Events.v*)\nFixpoint encode_longs (tyl : list typ) (vl : list val) :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' =>\n      match vl with\n        | nil => nil\n        | Vlong n :: vl' => Vint (Int64.hiword n) :: Vint (Int64.loword n)\n                            :: encode_longs tyl' vl'\n        | Vundef :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n        | _ :: vl' => Vundef :: Vundef :: encode_longs tyl' vl'\n      end\n    | t :: tyl' =>\n      match vl with\n        | nil => nil\n        | v :: vl' => v :: encode_longs tyl' vl'\n      end\n  end.\n\nFixpoint encode_typs (tyl : list typ) : list typ :=\n  match tyl with\n    | nil => nil\n    | AST.Tlong :: tyl' => AST.Tint :: AST.Tint :: encode_typs tyl'\n    | t :: tyl' => t :: encode_typs tyl'\n  end.\n\nLemma encode_longs_has_type tyl vl :\n  Val.has_type_list vl tyl ->\n  Val.has_type_list (encode_longs tyl vl) (encode_typs tyl).\nProof.\nrevert vl; induction tyl. simpl; auto.\ndestruct vl. intros; contradiction. intros [H H2]. simpl.\ndestruct a; try solve[split; auto].\ndestruct v; simpl; auto.\nQed.\n\nLemma decode_encode_longs tyl vl :\n  Val.has_type_list vl tyl ->\n  decode_longs tyl (encode_longs tyl vl) = vl.\nProof.\nrevert tyl; induction vl.\ndestruct tyl. simpl; auto.\ndestruct t; simpl; auto.\ndestruct tyl. simpl. inversion 1. inversion 1; subst. clear H.\nsimpl. destruct t; auto; try rewrite IHvl; auto.\ndestruct a; simpl; try solve[inv H0].\nrewrite IHvl; auto.\nrewrite IHvl; auto. f_equal.\nrewrite Int64.ofwords_recompose; auto.\nQed.\n\nLemma encode_longs_inject:\n  forall (f : meminj) (tyl : list typ) (vl1 vl2 : list val),\n  val_list_inject f vl1 vl2 ->\n  val_list_inject f (encode_longs tyl vl1) (encode_longs tyl vl2).\nProof.\nintros until vl2; intros H; revert tyl; induction H; simpl.\ndestruct tyl; simpl; [solve[constructor]|]. solve[destruct t; auto].\ndestruct tyl; simpl; [solve[constructor]|]. destruct t.\nsolve[constructor; auto].\nsolve[constructor; auto].\ninv H. solve[auto]. constructor; auto. solve[auto]. solve[auto].\ndestruct v'; solve[auto|constructor; auto].\nsolve[constructor; auto].\nQed.\n\nFixpoint getBlocks' (vl : list val) (b0 : block) :=\n  match vl with\n    | nil => false\n    | Vptr b _ :: vl' => eq_block b b0 || getBlocks' vl' b0\n    | _ :: vl' => getBlocks' vl' b0\n  end.\n\nLemma getBlocks_getBlocks' vl b0 : getBlocks vl b0 = getBlocks' vl b0.\nProof.\ninduction vl; simpl; auto.\ndestruct a; auto. unfold getBlocks. simpl.\ndestruct (eq_block b b0); simpl; auto.\nrewrite <-IHvl. unfold getBlocks.\ndestruct (\n     in_dec eq_block b0\n       (fold_right\n          (fun (v : val) (L : list block) =>\n           match v with\n           | Vundef => L\n           | Vint _ => L\n           | Vlong _ => L\n           | Vfloat _ => L\n           | Vptr b' _ => b' :: L\n           end) nil vl)\n); auto.\nQed.\n\nLemma getBlocks_encode_longs tys vals b :\n  getBlocks (encode_longs tys vals) b=true ->\n  getBlocks vals b=true.\nProof.\n  rewrite !getBlocks_getBlocks'.\n  revert tys; induction vals; simpl; auto. destruct tys. simpl; auto.\n  solve[destruct t; simpl; auto].\n  destruct tys. simpl; congruence.\n  simpl. destruct t; destruct a; simpl; intros; try solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\n  rewrite orb_true_iff in H. destruct H. rewrite H; auto.\n    rewrite orb_true_iff. right. solve[eapply IHvals; eauto].\nQed.\n\nLemma val_casted_has_type a t :\n  tys_nonvoid (Tcons t Tnil) = true ->\n  val_casted_func a t = true ->\n  val_has_type_func a (typ_of_type t) = true.\nProof.\nintros H0 H.\napply val_casted_funcE in H.\ninduction H; try solve[auto].\ndestruct H. destruct sz. simpl.\ngeneralize (Float.singleoffloat_is_single n0).\ndestruct (Float.is_single_dec (Float.singleoffloat n0)); auto. auto.\nsimpl in H0. congruence.\nQed.\n\nLemma val_casted_has_type_list vals tys :\n  tys_nonvoid tys = true ->\n  val_casted_list_func vals tys = true ->\n  val_has_type_list_func vals (typlist_of_typelist tys) = true.\nProof.\nrevert vals; induction tys. simpl. intros vals.\ndestruct vals. simpl; auto. simpl. solve[inversion 2].\nsimpl; intros vals; revert tys IHtys; induction vals. simpl.\n  intros; congruence.\nsimpl; intros. rewrite andb_true_iff in H0; destruct H0 as [H0 H2].\nassert (H3: tys_nonvoid tys = true).\n{ destruct t; solve[congruence|auto]. }\nrewrite andb_true_iff. split; auto.\napply val_casted_has_type; auto. destruct t; auto.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/val_casted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943832145539, "lm_q1q2_score": 0.15777429396126016}}
{"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 Epsilon.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext uniq_tac machine_int multi_int.\nRequire Import encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_double_u_prg multi_double_u_triple.\n\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope simu_scope.\n\n(** x <- x * 2, x unsigned *)\n\nLemma pfwd_sim_double_u (x : bipl.var.v) (d : assoc.t) (rk rx a0 a1 a2 a3 : reg) :\n  uniq(rk, rx, a0, a1, a2, a3, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: a1 :: a2 :: a3 :: nil) ->\n  x \\notin assoc.dom d -> unsign rk rx \\notin assoc.cdom d ->\n  (x <- var_e x \\* nat_e 2)%pseudo_expr%pseudo_cmd\n    <=p( state_mint (x |=> unsign rk rx \\U+ d), fun s st h =>\n         ([ x ]_ s)%pseudo_expr < 2 ^^ ('|u2Z ([ rk ]_st)%asm_expr| * 32 - 1))\n  multi_double_u rk rx a0 a1 a2 a3.\nProof.\nmove=> Haux Hd Hd' Hd''.\nrewrite /pfwd_sim.\nmove=> s st h [s_st_h x_k] s' exec_pseudo st' h' exec_mips.\nhave d_unchanged : forall v r, assoc.get v d = Some r ->\n    disj (mint_regs r) (mips_frame.modified_regs (multi_double_u rk rx a0 a1 a2 a3)).\n  move=> v r Hvr; rewrite [mips_frame.modified_regs _]/=; Disj_remove_dup.\n  apply (disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n  exact/incP/inc_mint_regs/(assoc.get_Some_in_cdom _ v).\nset k := '|u2Z ([rk ]_ st)%asm_expr|.\nmove/multi_double_u_triple : (Haux).\nmove/(_ '|u2Z ([rk ]_ st)%asm_expr| ([rx ]_ st)%asm_expr\n  (state_mint_head_unsign_fit _ _ _ _ _ _ _ s_st_h) (Z2ints 32 k ([var_e x ]e_ s)%pseudo_expr)).\nrewrite size_Z2ints.\nmove/(_ Logic.eq_refl) => hoare_triple_double_u.\n\nhave [st'' [h'' exec_mips_proj]] : exists st'' h'',\n  (Some (st, heap.proj h (heap.dom (heap_mint (unsign rk rx) st h)))\n  -- multi_double_u rk rx a0 a1 a2 a3 ---> Some (st'', h''))%mips_cmd.\n  exists st', (heap.proj h' (heap.dom (heap_mint (unsign rk rx) st h))).\n  move/mips_syntax.triple_exec_proj : hoare_triple_double_u; apply => //.\n  split; first by [].\n  split; first by rewrite Z_of_nat_Zabs_nat //; apply min_u2Z.\n  rewrite /heap_cut heap.proj_dom_proj.\n  apply (state_mint_var_mint _ _ _ _ x (unsign rk rx)) in s_st_h; last by assoc_get_Some.\n  rewrite /var_mint in s_st_h.\n  by case: s_st_h => _ [_ ?].\n\nset postcond := (fun s h => exists _, _) in hoare_triple_double_u.\nhave {hoare_triple_double_u}hoare_triple_post_condition : ( postcond ** assert_m.TT)%asm_assert\n     st' h'.\n    move: (mips_frame.frame_rule_R _ _ _ hoare_triple_double_u assert_m.TT (assert_m.inde_TT _) (mips_frame.inde_cmd_mult_TT _)).\n    move/mips_seplog.hoare_prop_m.soundness.\n    rewrite /while.hoare_semantics.\n    move/(_ st h) => Hdouble_u.\n    lapply Hdouble_u; last first.\n      exists (heap_mint (unsign rk rx) st h), (h \\D\\ heap.dom (heap_mint (unsign rk rx) st h)).\n      split; first by apply heap.disj_difs', seq_ext.inc_refl.\n      split.\n        apply heap.union_difsK => //; by apply heap.inclu_proj.\n      split; last by [].\n      split; first by [].\n      split.\n      rewrite Z_of_nat_Zabs_nat //; by apply min_u2Z.\n      move: (state_mint_var_mint _ s st h x (unsign rk rx) s_st_h).\n        rewrite assoc.get_union_sing_eq.\n        case/(_ refl_equal) => ? ? ?; tauto.\n    move=> {Hdouble_u} [Hdouble_u Hdouble_u'].\n    by move: {Hdouble_u'}(Hdouble_u' _ _ exec_mips).\nsplit.\n- move=> y ry y_ry.\n  have [yx | yx] : y \\in assoc.dom d \\/ y = x.\n    case/assoc.get_union_Some_inv : y_ry => y_ry.\n    * by case/assoc.get_sing_inv : y_ry => -> _; right.\n    * by apply assoc.get_Some_in_dom in y_ry; left.\n  + (* y \\in assoc.dom d *) have x_y : y <> x.\n      move=> ?; subst y; by rewrite yx in Hd'.\n    move: {s_st_h}(proj1 s_st_h _ _ y_ry) (proj2 s_st_h) => s_st_h1 s_st_h2.\n    have y_unchanged : ([ y ]_s = [ y ]_s')%pseudo_expr.\n      Var_unchanged. rewrite /= mem_seq1; exact/negP/eqP.\n    case: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_mips\n      (heap.dom (heap_mint (unsign rk rx) st h)) _ _ exec_mips_proj) => H4 [H5 H_h_h'].\n    have <- : heap_mint ry st h = heap_mint ry st' h'.\n      apply (heap_mint_state_invariant (heap_mint (unsign rk rx) st h) y s) => //.\n      move=> rx0 Hrx0; Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs ry)); last by [].\n      apply/disj_sym/(d_unchanged y).\n      by rewrite -y_ry assoc.get_union_sing_neq.\n      apply s_st_h2 with y x => //.\n      by rewrite assoc.get_union_sing_eq.\n    move: s_st_h1; apply var_mint_invariant.\n    move=> rx0 Hrx0; Reg_unchanged.\n    apply (@disj_not_In _ (mint_regs ry)); last by [].\n    apply/disj_sym/(d_unchanged y) => //.\n    by rewrite -y_ry assoc.get_union_sing_neq.\n    Var_unchanged; rewrite /= mem_seq1; exact/negP/eqP.\n  + (* yx : y = x *) subst y.\n    have ? : ry = unsign rk rx.\n      rewrite assoc.get_union_sing_eq in y_ry.\n      by case: y_ry.\n    subst ry.\n    set vx := u2Z ([ rx ]_ st)%asm_expr.\n    set k' := '| u2Z ([ rk ]_ st')%asm_expr |.\n    set vx' := u2Z ([ rx ]_ st')%asm_expr.\n  move: (state_mint_var_mint _ s st h x (unsign rk rx) s_st_h).\n    rewrite assoc.get_union_sing_eq.\n    case/(_ refl_equal) => X1 X2 X3.\n    case : hoare_triple_post_condition => h1 [h2 [Hdisj [Hunion [[A' [Hmul2_1 [Hmul2_2 [Hmul2_3 [Hmul2_4 Hmul2_5]]]]] HTT]]]].\n\n    have k_k' : k = k' by rewrite /k /k' Hmul2_3 Z_of_nat_Zabs_nat //; apply min_u2Z.\n    subst k'.\n    apply mkVarUnsign.\n    + by rewrite -k_k' Hmul2_2.\n    + split.\n      - move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n        case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n        syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n        apply mulZ_ge0 => //; tauto.\n      - move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n        case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n        syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n        rewrite /ZIT.mul mulZC.\n        case : (ltnP 0 k) => Hk'; last first.\n          rewrite leqn0 in Hk'. move/eqP in Hk'.\n          rewrite -/k Hk' ZbetaE mul0n /= in X2.\n          have {}X2 : ([x]_s = 0)%pseudo_expr by lia.\n          rewrite X2 mulZ0; by apply Zbeta_gt0.\n        - rewrite -k_k' ZbetaE (_ : k * 32 = S (k * 32 - 1))%nat; last first.\n            by rewrite -subSn // ?subn1 // muln_gt0 Hk'.\n          rewrite ZpowerS; exact/ltZ_pmul2l.\n    + apply mapstos_inv_list2heap in Hmul2_4 => //; last first.\n        by rewrite [eval _ _]/= Hmul2_2 Hmul2_1.\n      rewrite u2Z_shrl' in Hmul2_4; last by repeat constructor.\n      rewrite /= Hmul2_2 in Hmul2_4.\n      rewrite /heap_cut Hunion Hmul2_4.\n      move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n      case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n      syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n      rewrite lSum_Z2ints_pos // [ ( [ _ ]e_ _ )%pseudo_expr ]/= in Hmul2_5.\n      rewrite /ZIT.mul mulZC.\n      case: (zerop k) => Hk'.\n      - rewrite -k_k' Hk' Z2ints_0 /= /heap_cut heap.proj_nil.\n        split; last by [].\n        move/assert_m.mapstos_inv_addr : X3 => /=.\n        by rewrite Hmul2_2.\n      - have Htmp : u2Z ([a2 ]_st')%asm_expr = 0.\n          have Htmp1 : 2 * ([ x ]_ s)%pseudo_expr < 2 ^^ (k * 32).\n            rewrite (_ : k * 32 = S (k * 32 - 1))%nat; last first.\n              move/ltP in Hk'.\n              by rewrite -subSn // ?subn1 // muln_gt0 Hk'.\n            rewrite ZpowerS; exact/ltZ_pmul2l.\n          rewrite -Hmul2_5 in Htmp1.\n          move: (min_u2Z ([a2]_st')%asm_expr).\n          case/leZ_eqVlt => Htmp2 //.\n          rewrite addZC mulnC in Htmp1. (* TODO *)\n          move/(poly_Zlt1_inv _ _ _ (min_lSum _ _) (min_u2Z _) (expZ_ge0 _)) : Htmp1 => Htmp1.\n          rewrite Htmp1 in Htmp2; by move/ltZZ : Htmp2.\n        rewrite -Hmul2_5.\n        rewrite Htmp.\n        rewrite mul0Z addZ0.\n        rewrite Z_of_nat_Zabs_nat in Hmul2_3.\n        rewrite Hmul2_3.\n        rewrite -Z2ints_lSum.\n        rewrite /heap_cut.\n        rewrite Hmul2_2.\n        have <- : heap.dom (list2heap '|vx / 4| A') = iota '|vx / 4| k.\n          by rewrite dom_list2heap Hmul2_1.\n        rewrite heap.proj_union_L_dom; last by rewrite -Hmul2_4.\n        rewrite heap.proj_itself.\n        apply mapstos_list2heap.\n        + rewrite Z_of_nat_Zabs_nat //; last first.\n            apply Z_div_pos => //; by apply min_u2Z.\n          rewrite -Zdivide_Zdiv_eq //.\n          by rewrite -Hmul2_2.\n          move/assert_m.mapstos_inv_addr : X3.\n          by apply Zmod_divide.\n        + rewrite /vx in X1.\n          rewrite [eval _ _]/= Hmul2_2; lia.\n        + by [].\n        + by apply min_u2Z.\n- apply (state_mint_part2_one_variable_unsign _ _ _ _ _ _ _ _ _ s_st_h).\n  + move=> t x0 Ht Hx0.\n    Reg_unchanged. simpl mips_frame.modified_regs.\n    case/assoc.in_cdom_union_inv : Ht => Ht.\n    * rewrite assoc.cdom_sing /= seq.mem_seq1 in Ht.\n      move/eqP : Ht => Ht; subst t.\n      apply (@disj_not_In _ (mint_regs (unsign rk rx))); last by [].\n      simpl.\n      Disj_remove_dup.\n      by Disj_uniq r0.\n    * apply (@disj_not_In _ (mint_regs t)); last by [].\n      Disj_remove_dup.\n      apply/disj_sym/(disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n      exact/incP/inc_mint_regs.\n  + move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_mips _ _ _ exec_mips_proj); tauto.\n  + exact: (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_mips).\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_double_u_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3106943704494217, "lm_q1q2_score": 0.1577742874789746}}
{"text": "Require Import Kami.Syntax Kami.PPlusProperties.\nRequire Import Kami.Notations.\nRequire Import Kami.Compiler.CompilerSimpleSem.\nRequire Import Kami.Compiler.CompilerSimple.\nRequire Import Kami.Compiler.CompilerProps.\nRequire Import Kami.Compiler.Compiler.\n\nLemma RME_Simple_RME_Equiv map:\n  forall old upds,\n    Sem_RmeSimple (RmeSimple_of_RME map) (old, upds) ->\n    SemRegMapExpr map (old, upds).\nProof.\n  induction map; intros; try (inv H; EqDep_subst).\n  - econstructor 1; eauto.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\n  - econstructor 4; eauto.\nQed.\n\nLemma CA_Simple_CA_Equiv {k : Kind} (ca : CompActionT type (RegsT * list RegsT) k) :\n  forall regMap calls val,\n    SemCompActionSimple (CompActionSimple_of_CA ca) regMap calls val ->\n    SemCompActionT ca regMap calls val.\nProof.\n  induction ca; intros; try ((inv H0 || inv H); EqDep_subst).\n  - econstructor 1; eauto.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\n  - econstructor 4; eauto.\n  - econstructor 5; eauto.\n  - econstructor 6; eauto using RME_Simple_RME_Equiv.\n  - econstructor 7; eauto.\n    destruct regMap; inv HRegMapWf; econstructor; eauto using RME_Simple_RME_Equiv.\n  - econstructor 8; eauto.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; simpl in *; EqDep_subst.\n    inv HRegMapWf; inv H0; EqDep_subst.\n    econstructor 9; eauto using RME_Simple_RME_Equiv.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; EqDep_subst.\n    destruct regMap_a; inv HRegMapWf; inv H0; EqDep_subst.\n    + inv HUpdate; EqDep_subst.\n      econstructor 10; eauto using RME_Simple_RME_Equiv.\n      * econstructor; eauto.\n        econstructor; eauto using RME_Simple_RME_Equiv.\n      * econstructor 10; eauto using RME_Simple_RME_Equiv.\n        econstructor; eauto.\n        eapply SemUpdRegMapFalse; eauto using RME_Simple_RME_Equiv.\n    + econstructor 11; eauto using RME_Simple_RME_Equiv.\n      econstructor; eauto using RME_Simple_RME_Equiv.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; EqDep_subst.\n    destruct regMap_a; inv HRegMapWf; inv H0; EqDep_subst;[|discriminate].\n    econstructor 12; eauto.\n    econstructor; eauto using RME_Simple_RME_Equiv.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; EqDep_subst.\n    destruct regMap_a; inv HRegMapWf; inv H0; EqDep_subst;[discriminate|].\n    econstructor 13; eauto using RME_Simple_RME_Equiv.\n    econstructor; eauto using RME_Simple_RME_Equiv.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; simpl in *; EqDep_subst.\n    inv HRegMapWf; destruct regMap_a.\n    inv H0.\n    econstructor 14; eauto using RME_Simple_RME_Equiv.\n  - inv HSemCompActionSimple; simpl in *; EqDep_subst; rewrite unifyWO in *.\n    inv HSemCompActionSimple_a; simpl in *; EqDep_subst.\n    inv HRegMapWf; destruct regMap_a.\n    econstructor 15; eauto using RME_Simple_RME_Equiv.\n    inv H0.\n    apply RME_Simple_RME_Equiv; auto.\nQed.\n\nLemma CA_Simple_Trace_CA_Trace_Equiv (ca : RegsT -> CompActionT type (RegsT * list RegsT) Void) :\n  forall regInits o lupds lcalls,\n    SemCompActionSimple_Trace regInits (fun s => CompActionSimple_of_CA (ca s)) o lupds lcalls ->\n    SemCompTrace regInits ca o lupds lcalls.\nProof.\n  induction 1;[econstructor 1 | econstructor 2]; eauto using CA_Simple_CA_Equiv.\nQed.\n\nLemma CompActionSimpleTraceEquiv (b : BaseModule) (lrf : list RegFileBase) o :\n  let m := inlineAll_All_mod (mergeSeparatedSingle b lrf) in\n  let regInits := (getRegisters b) ++ (concat (map getRegFileRegisters lrf)) in\n  forall rules lupds lcalls\n         (HWfMod : WfMod type (mergeSeparatedSingle b lrf))\n         (HNoSelfCallsBase : NoSelfCallBaseModule b),\n    SubList rules (getRules b) ->\n    SemCompActionSimple_Trace regInits (fun s => CompActionSimple_of_CA\n                                            (compileRulesRf type (s, nil)\n                                                            rules lrf)) o lupds lcalls ->\n    (forall upds u, In upds lupds -> In u upds -> (NoDup (map fst u)) /\\\n                                                  SubList (getKindAttr u) (getKindAttr o)) /\\\n    exists (lss : list (list (list FullLabel))),\n      Forall2 (fun x y => x = (map getLabelUpds y)) lupds lss /\\\n      (forall x, In x lss -> (map Rle (map fst (rev rules))) = getLabelExecs (concat x)) /\\ \n      Forall2 (fun x y => x = concat (map getLabelCalls (rev y))) lcalls lss /\\\n      Trace m o (concat lss).\nProof.\n  intros; eapply CompTraceEquiv; eauto using CA_Simple_Trace_CA_Trace_Equiv.\nQed.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Compiler/CompilerSimpleProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15743396492029613}}
{"text": "Require Import Arith.\nRequire Import NPeano.\nRequire Import List.\nRequire Import Coq.Numbers.Natural.Abstract.NDiv.\nImport ListNotations.\nRequire Import Sorting.Permutation.\nRequire Import Sumbool.\n\nRequire Import Util.\nRequire Import Net.\nRequire Import RaftState.\nRequire Import Raft.\nRequire Import VerdiTactics.\n\n\nSection GhostElections.\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  Record electionsData := mkElectionsData {\n                              votes : list (term * name) ;\n                              votesWithLog : list (term * name * list entry) ;\n                              cronies : term -> list name ;\n                              leaderLogs : list (term * list entry) ;\n                              appendEntriesReplies : list (term * entry)\n                            }.\n\n  Definition update_elections_data_requestVote (me : name) (src : name) t candidateId lastLogIndex lastLogTerm st :=\n    let (st', r) := \n        handleRequestVote me (snd st) t candidateId lastLogIndex lastLogTerm\n    in\n    match (votedFor st') with\n      | Some cid =>\n        {| votes := (currentTerm st', cid) :: votes (fst st) ;\n           votesWithLog := (currentTerm st', cid, log st') :: votesWithLog (fst st) ;\n           cronies := cronies (fst st) ;\n           leaderLogs := leaderLogs (fst st) ;\n           appendEntriesReplies := appendEntriesReplies (fst st)\n        |}\n      | None => fst st\n    end.\n\n  Definition update_elections_data_requestVoteReply (me : name) (src : name) t voteGranted st :=\n    let st' := handleRequestVoteReply me (snd st) src t voteGranted in\n    match (type st') with\n      | Follower => fst st\n      | Candidate =>\n        {| votes := votes (fst st) ;\n           votesWithLog := votesWithLog (fst st) ;\n           cronies :=\n             fun tm => (if eq_nat_dec tm (currentTerm st') then\n                         votesReceived st'\n                       else\n                         cronies (fst st) tm) ;\n           leaderLogs := leaderLogs (fst st) ;\n           appendEntriesReplies := appendEntriesReplies (fst st)\n        |}\n      | Leader =>\n        {| votes := votes (fst st) ;\n           votesWithLog := votesWithLog (fst st) ;\n           cronies :=\n             fun tm => (if eq_nat_dec tm (currentTerm st') then\n                         votesReceived st'\n                       else\n                         cronies (fst st) tm) ;\n           leaderLogs := if serverType_eq_dec (type (snd st)) Candidate then\n                           (currentTerm st', log st') :: leaderLogs (fst st)\n                         else\n                           leaderLogs (fst st) ;\n           appendEntriesReplies := appendEntriesReplies (fst st)\n        |}\n    end.\n\n  Definition update_elections_data_appendEntries\n             (me : name)\n             st (t : term) (leaderId : name) (prevLogIndex : logIndex)\n             (prevLogTerm : term) (entries : list entry) (leaderCommit : logIndex) :=\n    let (_, m) := handleAppendEntries me (snd st) t leaderId prevLogIndex\n                                      prevLogTerm entries leaderCommit in\n    match m with\n      | AppendEntriesReply t entries true =>\n        {| votes := votes (fst st) ;\n           votesWithLog := votesWithLog (fst st) ;\n           cronies := cronies (fst st) ;\n           leaderLogs := leaderLogs (fst st) ;\n           appendEntriesReplies := (map (fun e => (t, e)) entries) ++ appendEntriesReplies (fst st)\n        |}\n      | _ => fst st\n    end.\n  \n  \n  Definition update_elections_data_net (me : name) (src: name) (m : msg) st : electionsData :=\n    match m with\n      | RequestVote t candidateId lastLogIndex lastLogTerm =>\n        update_elections_data_requestVote me src t src lastLogIndex lastLogTerm st\n      | RequestVoteReply t voteGranted =>\n        update_elections_data_requestVoteReply me src t voteGranted st\n      | AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit =>\n        update_elections_data_appendEntries me st t leaderId prevLogIndex prevLogTerm entries leaderCommit\n      | _ => fst st\n    end.\n\n  Definition update_elections_data_timeout (me : name) st : electionsData :=\n    let '(_, st', _) := handleTimeout me (snd st) in\n    match (votedFor st') with\n      | Some cid =>\n        {| votes := (currentTerm st', cid) :: votes (fst st) ;\n           votesWithLog := (currentTerm st', cid, log st') :: votesWithLog (fst st) ;\n           cronies :=\n             if serverType_eq_dec (type st') Candidate then\n               fun tm => (if eq_nat_dec tm (currentTerm st') then\n                           votesReceived st'\n                         else\n                           cronies (fst st) tm)\n             else\n               cronies (fst st) ;\n           leaderLogs := leaderLogs (fst st) ;           \n           appendEntriesReplies := appendEntriesReplies (fst st)\n        |}\n      | None => fst st\n    end.\n\n  Definition update_elections_data_input (me : name) (inp : raft_input) st : electionsData :=\n    match inp with\n      | Timeout => update_elections_data_timeout me st\n      | _ => fst st\n    end.\n\n  Instance elections_ghost_params : GhostFailureParams failure_params :=\n    {\n      ghost_data := electionsData ;\n      ghost_init := {| votes := [] ; votesWithLog := []; cronies := fun _ => [];\n                 leaderLogs := [] ;\n                 appendEntriesReplies := [] |} ;\n      ghost_net_handlers := update_elections_data_net ;\n      ghost_input_handlers := update_elections_data_input\n    }.\n\n  Definition raft_refined_base_params := refined_base_params.\n  Definition raft_refined_multi_params := refined_multi_params.\n  Definition raft_refined_failure_params := refined_failure_params.\n\n  Hint Extern 4 (@BaseParams) => apply raft_refined_base_params : typeclass_instances.\n  Hint Extern 4 (@MultiParams _) => apply raft_refined_multi_params : typeclass_instances.\n  Hint Extern 4 (@FailureParams _ _) => apply raft_refined_failure_params : typeclass_instances.\n\n  Inductive refined_raft_intermediate_reachable : network -> Prop :=\n  | RRIR_init : refined_raft_intermediate_reachable step_m_init\n  | RRIR_step_f :\n      forall failed net failed' net' out,\n        refined_raft_intermediate_reachable net ->\n        step_f (failed, net) (failed', net') out ->\n        refined_raft_intermediate_reachable net'\n  | RRIR_handleInput :\n      forall net h inp gd out d l ps' st',\n        refined_raft_intermediate_reachable net ->\n        handleInput h inp (snd (nwState net h)) = (out, d, l) ->\n        update_elections_data_input h inp (nwState net h) = gd ->\n        (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n        (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                           In p' (send_packets h l)) ->\n        refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | RRIR_handleMessage :\n      forall p net xs ys st' ps' gd d l,\n        refined_raft_intermediate_reachable net ->\n        handleMessage (pSrc p) (pDst p) (pBody p) (snd (nwState net (pDst p))) = (d, l) ->\n        update_elections_data_net (pDst p) (pSrc p) (pBody p) (nwState net (pDst p)) = gd ->\n        nwPackets net = xs ++ p :: ys ->\n        (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n        (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                           In p' (send_packets (pDst p) l)) ->\n        refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | RRIR_doLeader :\n      forall net st' ps' h os gd d d' ms,\n        refined_raft_intermediate_reachable net ->\n        doLeader d h = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h ms)) ->\n        refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | RRIR_doGenericServer :\n      forall net st' ps' os gd d d' ms h,\n        refined_raft_intermediate_reachable net ->\n        doGenericServer h d = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h ms)) ->\n        refined_raft_intermediate_reachable (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_client_request (P : network -> Prop) :=\n    forall h net st' ps' gd out d l id c,\n      handleClientRequest h (snd (nwState net h)) id c = (out, d, l) ->\n      gd = fst (nwState net h) ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h l)) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_timeout (P : network -> Prop) :=\n    forall net h st' ps' gd out d l,\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      gd = update_elections_data_timeout h (nwState net h) ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                               In p' (send_packets h l)) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_append_entries (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) m) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_append_entries_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t es res,\n      handleAppendEntriesReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t es res = (d, m) ->\n      gd = (fst (nwState net (pDst p))) ->\n      pBody p = AppendEntriesReply t es res ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         In p' (send_packets (pDst p) m)) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_request_vote (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t cid lli llt,\n      handleRequestVote (pDst p) (snd (nwState net (pDst p))) t (pSrc p) lli llt  = (d, m) ->\n      gd = update_elections_data_requestVote (pDst p) (pSrc p) t (pSrc p) lli llt (nwState net (pDst p)) ->\n      pBody p = RequestVote t cid lli llt ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) m) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_request_vote_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d t v,\n      handleRequestVoteReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t v = d ->\n      gd = update_elections_data_requestVoteReply (pDst p) (pSrc p) t v (nwState net (pDst p)) ->\n      pBody p = RequestVoteReply t v ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys)) ->\n      P (mkNetwork ps' st').\n\n  Definition refined_raft_net_invariant_do_leader (P : network -> Prop) :=\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h ms)) ->\n      P (mkNetwork ps' st').\n  \n  Definition refined_raft_net_invariant_do_generic_server (P : network -> Prop) :=\n    forall net st' ps' gd d os d' ms h,\n      doGenericServer h d = (os, d', ms) ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h ms)) ->\n      P (mkNetwork ps' st').\n\n  Lemma refined_raft_invariant_handle_message P :\n    forall xs p ys net st' ps' gd d l,\n      refined_raft_net_invariant_append_entries P ->\n      refined_raft_net_invariant_append_entries_reply P ->\n      refined_raft_net_invariant_request_vote P ->\n      refined_raft_net_invariant_request_vote_reply P ->\n      handleMessage (pSrc p) (pDst p) (pBody p) (snd (nwState net (pDst p))) = (d, l) ->\n      update_elections_data_net (pDst p) (pSrc p) (pBody p) (nwState net (pDst p)) = gd ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                             In p' (send_packets (pDst p) l)) ->\n      P (mkNetwork ps' st').\n  Proof.\n    intros.\n    unfold handleMessage, update_elections_data_net in *.\n    break_match; repeat break_let; repeat find_inversion;\n    [eapply_prop refined_raft_net_invariant_request_vote|\n     eapply_prop refined_raft_net_invariant_request_vote_reply|\n     eapply_prop refined_raft_net_invariant_append_entries|\n     eapply_prop refined_raft_net_invariant_append_entries_reply]; eauto;\n    unfold send_packets in *; simpl in *; intros; subst; auto; find_apply_hyp_hyp; intuition.\n  Qed.\n\n  Lemma refined_raft_invariant_handle_input P :\n    forall h inp net st' ps' gd out d l,\n      refined_raft_net_invariant_timeout P ->\n      refined_raft_net_invariant_client_request P ->\n      handleInput h inp (snd (nwState net h)) = (out, d, l) ->\n      update_elections_data_input h inp (nwState net h) = gd ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h l)) ->\n      P (mkNetwork ps' st').\n  Proof.\n    intros.\n    unfold handleInput, update_elections_data_input in *.\n    break_match; repeat break_let; repeat find_inversion;\n    [eapply_prop refined_raft_net_invariant_timeout|\n     eapply_prop refined_raft_net_invariant_client_request]; eauto; subst; auto.\n  Qed.\n\n  Definition refined_raft_net_invariant_state_same_packet_subset (P : network -> Prop) :=\n    forall net net',\n      (forall h, nwState net h = nwState net' h) ->\n      (forall p, In p (nwPackets net') -> In p (nwPackets net)) ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      P net'.\n\n  Definition refined_raft_net_invariant_reboot (P : network -> Prop) :=\n    forall net net' gd d h d',\n      reboot d = d' ->\n      P net ->\n      refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update (nwState net) h (gd, d') h') ->\n      nwPackets net = nwPackets net' ->\n      P net'.\n\n  Definition refined_raft_net_invariant_init (P : network -> Prop) :=\n    P step_m_init.\n  \n  Theorem refined_raft_net_invariant :\n    forall P net,\n      refined_raft_net_invariant_init P ->\n      refined_raft_net_invariant_client_request P ->\n      refined_raft_net_invariant_timeout P ->\n      refined_raft_net_invariant_append_entries P ->\n      refined_raft_net_invariant_append_entries_reply P ->\n      refined_raft_net_invariant_request_vote P ->\n      refined_raft_net_invariant_request_vote_reply P ->\n      refined_raft_net_invariant_do_leader P ->\n      refined_raft_net_invariant_do_generic_server P ->\n      refined_raft_net_invariant_state_same_packet_subset P ->\n      refined_raft_net_invariant_reboot P ->\n      refined_raft_intermediate_reachable net ->\n      P net.\n  Proof.\n    intros.\n    induction H10.\n    - intuition.\n    -  match goal with [H : step_f _ _ _ |- _ ] => invcs H end.\n       + unfold refined_net_handlers in *. simpl in *.\n         unfold RaftNetHandler, update_elections_data_net in *.\n         repeat break_let.\n         repeat find_inversion.\n         assert\n           (refined_raft_intermediate_reachable\n              {|\n                nwPackets := (xs ++ ys) ++ send_packets (pDst p) l2;\n                nwState := update (nwState net) (pDst p)\n                                  (update_elections_data_net (pDst p) \n                                                             (pSrc p)\n                                                             (pBody p)\n                                                             (nwState net (pDst p)), r0) |})\n           by (eapply RRIR_handleMessage; eauto; in_crush).\n         assert\n           (refined_raft_intermediate_reachable\n              {|\n                nwPackets := ((xs ++ ys)\n                                ++ send_packets (pDst p) l2)\n                               ++ send_packets (pDst p) l3 ;\n            nwState := update\n                         (nwState\n                            {|\n                              nwPackets := (xs ++ ys) ++ send_packets (pDst p) l2;\n                              nwState := update (nwState net) \n                                                (pDst p)\n                                                (update_elections_data_net \n                                                   (pDst p) (pSrc p) \n                                                   (pBody p) (nwState net (pDst p)), r0) |})\n                         (pDst p)\n                         (update_elections_data_net (pDst p) \n                                                    (pSrc p) (pBody p) (nwState net (pDst p)), r1) |})\n           by\n             (eapply RRIR_doGenericServer; eauto;\n              [simpl in *; break_if; try congruence; eauto| in_crush]).\n         eapply_prop refined_raft_net_invariant_do_leader. eauto. \n         eapply_prop refined_raft_net_invariant_do_generic_server. eauto.\n         eapply refined_raft_invariant_handle_message with (P := P); eauto using in_app_or.\n         auto.\n         simpl. break_if; intuition eauto.\n         eauto.\n         simpl. eapply in_app_or. auto.\n         simpl. break_if; eauto; congruence.\n         simpl. intros.\n         break_if; subst;\n         repeat rewrite update_same by auto;\n         repeat rewrite update_neq by auto; auto.\n         simpl. in_crush.\n       + unfold refined_input_handlers in *. simpl in *.\n         unfold RaftInputHandler, update_elections_data_input in *. repeat break_let.\n         repeat find_inversion.\n         assert\n           (refined_raft_intermediate_reachable\n              {|\n                nwPackets := nwPackets net ++ send_packets h l2;\n                nwState := update (nwState net) h\n                                  (update_elections_data_input h\n                                                               inp\n                                                               (nwState net h), r0) |})\n           by (eapply RRIR_handleInput; eauto; in_crush).\n         assert\n           (refined_raft_intermediate_reachable\n              {|\n                nwPackets := (nwPackets net\n                                ++ send_packets h l2)\n                               ++ send_packets h l4 ;\n            nwState := update\n                         (nwState\n                            {|\n                              nwPackets := nwPackets net ++ send_packets h l2;\n                              nwState := update (nwState net) \n                                                h\n                                                (update_elections_data_input h inp\n                                                                             (nwState net h), r0) |})\n                         h\n                         (update_elections_data_input h inp (nwState net h), r1) |})\n           by\n             (eapply RRIR_doGenericServer; eauto;\n              [simpl in *; break_if; try congruence; eauto| in_crush]).\n         eapply_prop refined_raft_net_invariant_do_leader. eauto.\n         eapply_prop refined_raft_net_invariant_do_generic_server. eauto.\n         eapply refined_raft_invariant_handle_input with (P := P); eauto using in_app_or.\n         auto.\n         simpl. break_if; intuition eauto.\n         eauto.\n         simpl. eapply in_app_or.\n         auto.\n         simpl. break_if; eauto; congruence.\n         simpl. intros.\n         break_if; subst;\n         repeat rewrite update_same by auto;\n         repeat rewrite update_neq by auto; auto.\n         simpl. unfold send_packets.  intros. in_crush.\n       + match goal with\n           | [ H : nwPackets ?net = _ |- _ {| nwPackets := ?ps ; nwState := ?st |} ] =>\n             assert (forall p, In p (nwPackets {| nwPackets := ps ; nwState := st |}) ->\n                          In p (nwPackets net)) by (intros; simpl in *; find_rewrite; in_crush)\n         end. \n         eapply_prop refined_raft_net_invariant_state_same_packet_subset; [|eauto|idtac|];\n         eauto.\n       + match goal with\n           | [ H : nwPackets ?net = _ |- _ {| nwPackets := ?ps ; nwState := ?st |} ] =>\n             assert (forall p, In p (nwPackets {| nwPackets := ps ; nwState := st |}) ->\n                          In p (nwPackets net)) by (intros; simpl in *; find_rewrite; in_crush)\n         end. \n         eapply_prop refined_raft_net_invariant_state_same_packet_subset; [|eauto|idtac|];\n         eauto.\n       + auto.\n       + eapply_prop refined_raft_net_invariant_reboot; eauto;\n         intros; simpl in *; repeat break_if; intuition; subst; intuition eauto.\n         destruct (nwState net h); auto.\n    - eapply refined_raft_invariant_handle_input; eauto.\n    - eapply refined_raft_invariant_handle_message; eauto.\n    - eapply_prop refined_raft_net_invariant_do_leader; eauto.\n    - eapply_prop refined_raft_net_invariant_do_generic_server; eauto.\n  Qed.\n\n  Require Import FunctionalExtensionality.\n\n  Ltac workhorse :=\n    try match goal with\n        | [ |- mkNetwork _ _ = mkNetwork _ _ ] => f_equal\n      end;\n    try match goal with\n        | [ |- (fun _ => _) = (fun _ => _) ] => apply functional_extensionality; intros\n      end;\n      repeat break_match;\n      repeat match goal with\n               | [ H : (_, _) = (_, _) |- _ ] => invc H\n             end;\n      repeat (simpl in *; subst);\n      repeat rewrite map_app;\n      repeat rewrite map_map.\n\n\n  Theorem simulation_1 :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      raft_intermediate_reachable (deghost net).\n  Proof.\n    intros.\n    induction H.\n    - constructor.\n    - simpl in *.\n      pose proof (RIR_step_f).\n      specialize (H1 failed (deghost net) failed' (deghost net') out).\n      apply H1; auto.\n      apply ghost_simulation_1; auto.\n    - unfold deghost in *. simpl in *.\n      eapply RIR_handleInput; eauto.\n      + simpl in *. repeat break_match. simpl in *.\n        assert (nwState h = (g, d0)) by eauto.\n        repeat find_rewrite. eauto.\n      + intros. simpl in *.\n        repeat break_match; subst; simpl in *;\n        repeat find_higher_order_rewrite; break_if; subst; simpl in *;\n        congruence.\n      + intros. simpl in *. in_crush.\n        find_apply_hyp_hyp.\n        in_crush.\n    - unfold deghost in *. simpl in *.\n      pose proof (RIR_handleMessage).\n      specialize\n        (H5 (@mkPacket _ multi_params\n                       (pSrc p)\n                       (pDst p)\n                       (pBody p))).\n      eapply H5; eauto.\n      + simpl in *. repeat break_match. simpl in *.\n        repeat find_rewrite. eauto.\n      + simpl in *.\n        unfold raft_refined_base_params, raft_refined_multi_params in *.\n        simpl in *.\n        repeat find_rewrite.\n        map_crush. eauto.\n      + intros. repeat break_match. simpl in *.\n        repeat find_higher_order_rewrite.\n        repeat break_match; congruence.\n      + in_crush.\n        find_apply_hyp_hyp. in_crush.\n    - unfold deghost in *. simpl in *.\n      eapply RIR_doLeader; eauto.\n      + simpl in *. repeat break_match. simpl in *.\n        assert (nwState h = (g, d0)) by eauto.\n        repeat find_rewrite. repeat find_inversion. eauto.\n      + simpl in *.\n        intros. repeat break_match; simpl in *;\n        repeat find_higher_order_rewrite;\n        repeat break_match; congruence.\n      + in_crush.\n        find_apply_hyp_hyp. in_crush.\n    - unfold deghost in *. simpl in *.\n      eapply RIR_doGenericServer; eauto.\n      + simpl in *. repeat break_match. simpl in *.\n        assert (nwState h = (g, d0)) by eauto.\n        repeat find_rewrite. repeat find_inversion. eauto.\n      + simpl in *.\n        intros. repeat break_match; simpl in *;\n        repeat find_higher_order_rewrite;\n        repeat break_match; congruence.\n      + in_crush.\n        find_apply_hyp_hyp. in_crush.\n  Qed.\n\n  Theorem lift_prop :\n    forall P,\n      (forall net, raft_intermediate_reachable net -> P net) ->\n      (forall net, refined_raft_intermediate_reachable net -> P (deghost net)).\n  Proof.\n    intros.\n    eauto using simulation_1.\n  Qed.\n\n  Require Import FunctionalExtensionality.\n  \n  Theorem simulation_2 :\n    forall net,\n      raft_intermediate_reachable net ->\n      exists rnet,\n        net = deghost rnet /\\\n        refined_raft_intermediate_reachable rnet.\n  Proof.\n    intros.\n    induction H.\n    - exists (reghost step_m_init). intuition.\n        unfold reghost. constructor.\n    - break_exists. break_and.\n      apply ghost_simulation_2 with (gnet := x) in H0; auto.\n      repeat (break_exists; intuition).\n      subst.\n      exists x0. intuition.\n      eapply RRIR_step_f; eauto.\n    - break_exists. break_and. \n      subst. \n      exists {| nwPackets := map ghost_packet ps' ;\n           nwState := update (nwState x) h (update_elections_data_input h inp (nwState x h), d)\n        |}. intuition.\n      + unfold deghost. simpl in *. map_crush. f_equal.\n        * map_id.\n        * apply functional_extensionality.\n          intros. find_higher_order_rewrite.\n          repeat break_match; auto. simpl in *. congruence.\n      + unfold deghost in *.\n        eapply RRIR_handleInput; repeat break_match; simpl in *; eauto.\n        simpl in *. in_crush.\n        find_apply_hyp_hyp. in_crush.\n        destruct x. auto.\n    - break_exists. break_and. \n      subst.\n      exists {| nwPackets := map ghost_packet ps' ;\n           nwState := update (nwState x) (pDst p)\n                             (update_elections_data_net (pDst p) (pSrc p)\n                                                 (pBody p) (nwState x (pDst p)), d)\n        |}. intuition.\n      + unfold deghost. simpl in *. map_crush. f_equal.\n        * map_id.\n        * apply functional_extensionality.\n          intros. find_higher_order_rewrite.\n          repeat break_match; auto. simpl in *. congruence.\n      + unfold deghost in *.\n        eapply RRIR_handleMessage with (p := ghost_packet p);\n          repeat break_match; simpl in *; eauto.\n        * simpl in *.\n          match goal with\n        | H : map _ ?la = ?lb |- _ =>\n          symmetry in H;\n            pose proof @map_inverses _ _ la lb deghost_packet ghost_packet\n          end.\n          repeat (forwards; [intro a; destruct a; reflexivity|]; concludes;\n                  match goal with\n                    | H :  forall _ : packet,  _ = _ |- _ => clear H\n                  end).\n          concludes. map_crush. eauto.\n        * simpl in *. in_crush.\n          find_apply_hyp_hyp. in_crush.\n    - break_exists. break_and. subst.\n      exists {| nwPackets := map ghost_packet ps' ;\n           nwState := update (nwState x) h (fst (nwState x h) , d')\n        |}. intuition.\n      + unfold deghost. simpl in *. map_crush. f_equal.\n        * map_id.\n        * apply functional_extensionality.\n          intros. find_higher_order_rewrite.\n          repeat break_match; auto. simpl in *. congruence.\n      + unfold deghost in *. simpl in *. repeat break_match; simpl in *.\n        eapply RRIR_doLeader with (d := d) (h := h);\n          repeat (break_match; simpl in *); eauto.\n        * simpl in *. find_rewrite. simpl in *. auto.\n        * simpl in *. in_crush.\n          find_apply_hyp_hyp. in_crush.\n          destruct x. auto.\n    - break_exists. break_and. subst.\n      exists {| nwPackets := map ghost_packet ps' ;\n           nwState := update (nwState x) h (fst (nwState x h) , d')\n        |}. intuition.\n      + unfold deghost. simpl in *. map_crush. f_equal.\n        * map_id.\n        * apply functional_extensionality.\n          intros. find_higher_order_rewrite.\n          repeat break_match; auto. simpl in *. congruence.\n      + unfold deghost in *. simpl in *. repeat break_match; simpl in *.\n        eapply RRIR_doGenericServer with (d := d) (h := h);\n          repeat (break_match; simpl in *); eauto.\n        * simpl in *. find_rewrite. simpl in *. auto.\n        * simpl in *. in_crush.\n          find_apply_hyp_hyp. in_crush.\n          destruct x. auto.\n  Qed.\n  \n  Theorem lower_prop :\n    forall P : _ -> Prop,\n      (forall net, refined_raft_intermediate_reachable net -> P (deghost net)) ->\n      (forall net, raft_intermediate_reachable net -> P net).\n  Proof.\n    intros.\n    find_apply_lem_hyp simulation_2.\n    break_exists. intuition. subst. eauto.\n  Qed.\n  \n  Lemma deghost_spec :\n    forall (net : @network _ raft_refined_multi_params) h,\n      nwState (deghost net) h = snd (nwState net h).\n  Proof.\n    intros.\n    destruct net; auto.\n  Qed.\nEnd GhostElections.\n\n\nHint Extern 4 (@BaseParams) => apply raft_refined_base_params : typeclass_instances.\nHint Extern 4 (@MultiParams _) => apply raft_refined_multi_params : typeclass_instances.\nHint Extern 4 (@FailureParams _ _) => apply raft_refined_failure_params : typeclass_instances.\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/RaftRefinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.1574163493095549}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import tweetnacl20140427.split_array_lemmas.\nRequire Import ZArith.\nLocal Open Scope Z.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.verif_salsa_base.\n\nRequire Import tweetnacl20140427.spec_salsa.\nRequire Import VST.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*)   \nentailer!. \n- \n change (Int.unsigned Int.iwordsize) with 32.\n split.\n +\n    unfold Int.signed in H;\n    destruct (zlt (Int.unsigned c) Int.half_modulus); rep_lia.\n +\n    unfold Int.sub.\n    change (Int.unsigned (Int.repr 32)) with 32.\n    unfold Int.signed in H.\n    rewrite Int.unsigned_repr.\n    * destruct (zlt (Int.unsigned c) Int.half_modulus); rep_lia.\n    * destruct (zlt (Int.unsigned c) Int.half_modulus); rep_lia.\n-\n  unfold Int.signed in H.\n  destruct (zlt (Int.unsigned c) Int.half_modulus); [| rep_lia].\n  apply prop_right.\n  unfold sem_shift; simpl.\n  unfold Int.ltu.\n change (Int.unsigned Int.iwordsize) with 32.\n simpl.\nunfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\nrewrite Z.mod_small; simpl; try lia.\nunfold Int.sub.\nrewrite Int.and_mone,Int.unsigned_repr; trivial.\nrewrite Int.unsigned_repr; rep_lia.\nrep_lia.\nQed.\n(*\nLemma L32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_L32 L32_spec.\nProof.\nstart_function. forward.\ndestruct (Int.ltu c Int.iwordsize) eqn:?H.\n  2: {\n    apply ltu_false_inv in H0.\n    change (Int.unsigned Int.iwordsize) with 32 in H0.\n    lia.\n  } \n  destruct (Int.ltu (Int.sub (Int.repr 32) c) Int.iwordsize) eqn:?H.\n  2:{ \n    apply ltu_false_inv in H1.\n    unfold Int.sub in H1.\n    change (Int.unsigned (Int.repr 32)) with 32 in H1.\n    rewrite Int.unsigned_repr in H1 by rep_lia.\n    change (Int.unsigned Int.iwordsize) with 32 in H1.\n    lia.\n  } \nTime forward. (*8.8*)  \n{\n  entailer!.\n<<<<<<< HEAD\n  rewrite H0, H1; simpl; auto.\n  split3; auto.\n  unfold Int.signed.\n  if_tac. rep_lia. repable_signed.\n=======\n  rewrite H0, H1; simpl; auto. intuition. lia.\n>>>>>>> master\n}\nentailer!.\nassert (W: Int.zwordsize = 32). reflexivity.\nassert (U: Int.unsigned Int.iwordsize=32). reflexivity.\nunfold sem_shift; simpl. rewrite H0, H1; simpl.\nunfold Int.rol, Int.shl, Int.shru. rewrite or_repr.\nrewrite Z.mod_small, W; simpl; try lia.\nunfold Int.sub.\nrewrite Int.and_mone.\nchange (Int.unsigned (Int.repr 32)) with 32.\nrewrite Int.unsigned_repr by rep_lia.\nauto.\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!; lia. (*1.1*)\nTime forward. (*2*)\nTime entailer!; lia. (*1.1*)\nTime forward. (*1.1*)\nTime forward. (*2.2*)\nTime entailer!; lia. (*1.3*)\nTime forward. (*1.5*)\ndrop_LOCAL 1%nat.\nTime forward.\nTime entailer!; lia. (*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 lia.\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. rep_lia.\n  rewrite TP, BMU, Z.mul_add_distr_l. rep_lia.\n  rewrite TP, BMU, Z.mul_add_distr_l. rep_lia.\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; lia. 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; lia.  \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. lia.\n  specialize (Zlength_nonneg l1); lia. \nQed.\n\nLemma lendian_range: forall l, 0 <= lendian l < 2^(8*Zlength l).\nProof. induction l; simpl; intros.\n+ lia.\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; lia.\n  rewrite <- Zmult_succ_r_reverse, Z.pow_add_r; [| specialize (Zlength_nonneg l); lia | lia ].\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). lia.\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; lia.\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; lia. 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 Zbits.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 (Zbits.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; lia. 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; lia.\nQed. \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 by  rep_lia.\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  assert (HH: 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] \n          = Byte.unsigned (Znth i [b0; b1; b2; b3; c0; c1; c2; c3])).\n  solve [erewrite <- (Znth_map _ Byte.unsigned); [ reflexivity | apply I ] ].\n  forward. \n  + entailer!. rewrite HH. \n     apply Byte.unsigned_range_2.\n  + simpl; rewrite HH. forward.\n    entailer!. clear H1 H0 H. f_equal. rewrite <- (sublist_rejoin 0 i (i+1)).\n    2: lia. 2: rewrite ! Zlength_cons, Zlength_nil; lia.\n    rewrite sublist_len_1.\n    2: rewrite ! Zlength_cons, Zlength_nil; lia.\n    simpl.\n    unfold Int64.or. rewrite Int64.shl_mul_two_p, (Int64.unsigned_repr 8).\n    2: unfold Int64.max_unsigned; simpl; lia.\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; lia.\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; lia. 2: lia.\n    rewrite Int64.shl_mul_two_p, (Int64.unsigned_repr 8).\n    2: unfold Int64.max_unsigned; simpl; lia.\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; lia). lia.\n      lia. change (Zlength [b0; b1; b2; b3; c0; c1; c2; c3]) with 8; lia. }\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; lia.\n    rewrite (Int64.unsigned_repr q).\n    2: unfold Int64.max_unsigned; simpl; lia.\n    rewrite Int64.unsigned_repr; trivial.\n    unfold Int64.max_unsigned; simpl; lia. } \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 lia. \nassert (Int.unsigned u / n <Int.modulus).\n2: unfold Int.max_unsigned; lia.\napply Z.div_lt_upper_bound; try lia.\nspecialize (Z.mul_lt_mono_nonneg 1 n (Int.unsigned u) (Int.modulus)).\nrewrite Z.mul_1_l. intros Q; apply Q; trivial. computable.\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               repeat Vundef (Z.to_nat(4-i)))\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 lia.\n  Time entailer!. (*1.5*)\n  unfold upd_Znth.\n  autorewrite with sublist.\n  simpl.\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.\n        rep_lia.\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 (Zaux.Zmod_mod_mult _ (2^8) (2^8)). 2: cbv; trivial. 2: cbv; intros; discriminate.\n            rewrite (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; lia.\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. lia. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.\n          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                   2: unfold Byte.max_unsigned; \n                         rewrite ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\n                         lia.\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          }\n          rewrite ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\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 lia.\n          rewrite (Zbits.Ztestbit_mod_two_p 16); try lia.\n          rewrite (Zbits.Ztestbit_mod_two_p 24); try lia.\n          rewrite Int.bits_shru; try lia. rewrite EIGHT, ZW. (* Ztest_Inttest.*)\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.\n          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; \n                         rewrite ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\n                         lia.\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          }\n          rewrite ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\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 lia. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try lia.\n          rewrite (Zbits.Ztestbit_mod_two_p 24); try lia.\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. lia. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\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          2:{ assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; \n                         rewrite ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\n                         lia.\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          }\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 ?Zaux.Zdiv_eucl_unique; (* for Coq 8.15 *)\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: lia.\n          apply Z.div_lt_upper_bound; trivial. compute; auto. apply Int.unsigned_range.\n        + lia. \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; lia.\n    unfold Int64.max_unsigned; simpl; lia.\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. lia.\n   unfold Int64.max_unsigned; simpl; lia.\n   unfold Int64.max_unsigned; simpl; lia.\n   unfold Int64.min_signed, Int64.max_signed; simpl; lia.\n   unfold Int64.min_signed, Int64.max_signed; simpl; lia.\n - rewrite W. unfold Int64.ltu. rewrite if_true; trivial. normalize. computable.\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; lia.\n   rewrite (Int64.signed_repr (Z.of_nat n)).   \n   2: unfold Int64.min_signed, Int64.max_signed; simpl; lia.\n   rewrite Int64.signed_repr. \n   2: unfold Int64.min_signed, Int64.max_signed; simpl; lia.\n   rewrite 2 Int64.unsigned_repr. lia.\n   unfold Int64.max_unsigned; simpl; lia.\n   unfold Int64.max_unsigned; simpl; lia.\n - lia.\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. lia. 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 lia.\n\n+ specialize (two_p_strict (Int64.unsigned n)); lia.\n+ specialize (two_p_strict (Int64.unsigned m)); lia.\n\n+ split. \n  - apply Z_div_pos; trivial. apply two_p_gt_ZERO; try lia. lia.\n  - assert (Int64.unsigned x / two_p (Int64.unsigned n) < Int64.max_unsigned +1). 2: lia.\n    specialize (two_p_gt_ZERO (Int64.unsigned n)); intros A.\n    apply Z.div_lt_upper_bound. lia. eapply Z.lt_le_trans. apply X.\n    unfold Int64.max_unsigned. replace (Int64.modulus - 1 + 1) with Int64.modulus by lia.\n    specialize (Zmult_le_compat_l 1 (two_p (Int64.unsigned n)) Int64.modulus).\n    rewrite Z.mul_1_r, Z.mul_comm. intros Y; apply Y; lia.\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              (repeat Vundef (Z.to_nat(8-i)) ++\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        myadmit. (*!! typecheck_error (invalid_cast_result tuchar tuchar)*)\n        solve [entailer!]. \n  Time forward. entailer. myadmit. (*another tc_error*)  \n  rewrite Z.add_comm, Z2Nat.inj_add; try lia.\n  Time entailer!. (*1.5*)\n  unfold upd_Znth. clear H.\n  autorewrite with sublist.\n  replace (8 - (1 + i)) with (7-i) by lia. \n  replace (7 - i + 1) with (8-i) by lia.\n  replace (i+(8-i)) with 8 by lia.\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: lia. 2: unfold Zlength; simpl; lia.\n  rewrite pure_lemmas.sublist_singleton with (d:=Vundef); simpl.\n  2: unfold Zlength; simpl; lia.\n  replace (7 - i + 1) with (8-i) by lia. f_equal.\n  rewrite iter64; try rewrite Z2Nat.id; try lia. 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 lia.\n  rewrite (Int64.unsigned_repr (8 * i)).\n  2: unfold Int64.max_unsigned; simpl; lia.\n  specialize (Int64.unsigned_range u); specialize (Z.pow_pos_nonneg 2 (8*i)); intros NN U.\n  rewrite Int64.unsigned_repr.\n  2:{ rewrite Z.shiftr_div_pow2 by lia.\n           split. apply Z_div_pos; lia. \n           assert (Int64.unsigned u / 2 ^ (8 * i) < Int64.modulus).\n           2: solve [unfold Int64.max_unsigned; lia].\n           apply Zdiv_lt_upper_bound. lia.\n           assert (Int64.modulus <= Int64.modulus * 2 ^ (8 * i)). 2: lia.\n           apply Z.le_mul_diag_r; lia.\n  }\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); lia.\n    apply Zdiv_lt_upper_bound; trivial. specialize (Fcore_Zaux.Zpower_pos_gt_0 2 n); lia.\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). lia. 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; lia.\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; lia.\n        - rewrite Int.unsigned_repr, two_p_equiv. specialize (UBND 56 8 (eq_refl _))%positive.\n          rewrite ! Z.pow_pos_fold in UBND. lia.\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). lia.\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). lia.\n    + rewrite ADD48. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD40. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD32. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD24. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD16. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ! Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia. }\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            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. lia. lia.\n  lia.\nQed.\n\n\n              rewrite Int.repr_unsigned; trivial.\n              rewrite ZW; lia.\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. lia. }\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; lia.\n      assert (QQ:= (UBND 48 16 (eq_refl _))%positive).\n      rewrite ! Z.pow_pos_fold in QQ.\n      rewrite Int64.unsigned_repr.\n      2:{ assert (2 ^ 16 < Int64.max_unsigned) by (cbv; trivial). lia. 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 lia. rewrite ! Z.pow_pos_fold.\n        assert (0<= Int64.unsigned u / 2 ^ 48 < 2^8).\n        { split; try lia. apply Zdiv_lt_upper_bound; trivial. }\n        (*rewrite Int.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1) in UNS_B_I; lia.*)\n        rewrite Byte.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1); lia.\n        rewrite zero_ext_inrange; trivial.\n        rewrite Int.unsigned_repr. 2: change Byte.max_unsigned with (2^8-1) in UNS_B_I; lia.\n        change (two_p 8) with (2^8); lia.\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. 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). lia.\n        unfold Int.zero_ext.\n clear - H1; rewrite int_max_unsigned_eq; split; try lia. specialize (Fcore_Zaux.Zpower_pos_gt_0 2 n); lia.\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      2:{ specialize (Zmod_unique (Int64.unsigned u) (Z.pow_pos 2 56)); intros.\n      rewrite Int.unsigned_repr.\n      2:{ assert (2 ^ 16 < Int64.max_unsigned) by (cbv; trivial). lia. }\n      unfold Int.zero_ext. f_equal. f_equal. }\n      apply Byte.equal_same_bits; intros. rewrite Int.Zzero_ext_spec by lia.\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 lia.\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 lia.\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. lia.\n      - rewrite Int.unsigned_repr. apply B1. lia.\n    + rewrite ADD48. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD40. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD32. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD24. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ADD16. rewrite 2 Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia.\n    + rewrite ! Int64.unsigned_repr; unfold Int64.max_unsigned; simpl; lia. }\n\n    + rewrite ! Int64.add_unsigned. rewrite ! Int64.unsigned_repr; simpl; unfold Int64.max_unsigned; simpl; try lia.\n    + } \n    rewrite two_p_correct. rewrite Z.pow_pos_fold in B1. lia.\n    unfold Int64.max_unsigned; simpl; lia.\n    rewrite Int64.shru_div_two_p.  UNSB_I64.  <- two_power_nat_two_p. lia. apply B1; apply  Pos.le_refl. cbv. lia. myadmit.  myadmit.  myadmit.  myadmit.  myadmit.\n    myadmit.  myadmit.  myadmit.  myadmit.  myadmit. }\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. myadmit.  myadmit.  myadmit.  myadmit.  myadmit.\n    myadmit.  myadmit.  myadmit.  myadmit.  myadmit. }\n      \n    unfold Int64.shru.  simpl. ! Int64.add_unsigned. (Int64.unsigned_repr 8).\n    \n\n rewrite if_false by lia.\n\n  unfold Znth; simpl. \n  rewrite if_false by lia. 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; lia. \n  unfold iter64Shr8'. rewrite Z2Nat.id; try lia. \n  rewrite Int64.mul_signed.\n  rewrite 2 Int64.signed_repr; try (unfold Int64.min_signed, Int64.max_signed; simpl; lia).\n  rewrite Int64.shru_div_two_p, (Int64.unsigned_repr (8 * i)). 2: unfold Int64.max_unsigned; simpl; lia.\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 *. lia. } \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; lia.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. lia. }*)\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 *. lia. }*)\n  rewrite unsigned_repr'; trivial.\n(*  rewrite Int64.unsigned_repr.\n  2:{ split. apply Z_div_pos; trivial. lia. \n           apply Z.div_le_upper_bound. lia. \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; lia.*)\n  rewrite unsigned_repr'.\n  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  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  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  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  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  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  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; lia. }\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. lia. \n      rewrite Int64.unsigned_repr. lia. lia. } \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 *; lia. }\n\n lia.\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  . lia. cbv. \n           specialize (Zmult_le_compat_r 1 (two_p (8 * i)) Int64.max_unsigned). simpl.\n           intros Q; apply Q; lia.\n  rewrite zero_ext_inrange. \n  2:{ rewrite Int.unsigned_repr.\n           assert (Int64.unsigned u / two_p (8 * i) < two_p 8). 2: lia.\n           apply Z.div_lt_upper_bound. lia.\n           assert (Int64.max_unsigned < two_p (8 * i) * two_p 8). 2: lia.\n           rewrite 2 two_p_equiv, Z.pow_mul_r, I64MU; try lia.\n           specialize (Zpower_exp (2^8) i 1); rewrite Z.pow_1_r.\n           intros Q; rewrite <- Q. simpl. lia. simpl.\n              simpl in *. lia. 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; lia.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl in *. lia.\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; lia.\n           apply Z.div_lt_upper_bound. cbv; trivial. simpl. lia. } \n           eapply Z.le_trans; eauto. rewrite I64MU. simpl. clear. cbv. lia. \n           unfold lia.  simpl. lia.  Zdiv_interval_2.\n  destruct (zeq i 0); subst; simpl. rewrite Byte.unsigned_repr. myadmit.\n  + f_equal. rewrite iter64. 2: rewrite Z2Nat.id; lia.\n    unfold iter64Shr8'. rewrite Z2Nat.id; try lia.  \n    unfold Int64.mul. rewrite 2 Int64.unsigned_repr.\n    2: unfold Int64.max_unsigned; simpl; lia.\n    2: unfold Int64.max_unsigned; simpl; lia.\n    rewrite Int64.shru_div_two_p.\n    rewrite (Int64.unsigned_repr (8 * i)), two_p_equiv.\n    2: unfold Int64.max_unsigned; simpl; lia. \n    assert (X: 0 < 2 ^ (8 * i)) by (apply Z.pow_pos_nonneg; lia).\n    destruct (Int64.unsigned_range_2 u).\n    assert (T: 0 <= Int64.unsigned u / 2 ^ (8 * i) <= 255).\n    { split. apply Z_div_pos. lia. lia. \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: lia.\n       specialize (Zmult_le_compat_l 1 (2 ^ (8 * i)) Int64.max_unsigned).\n       rewrite Z.mul_1_r. intros Y; apply Y. lia. unfold Int64.max_unsigned; simpl; lia. }   \n    \n    assert (Q: 0 <= Int64.unsigned u / 2 ^ (8 * i) <= Int64.max_unsigned).\n    { split. apply Z_div_pos. lia. lia. \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. lia. unfold Int64.max_unsigned; simpl; lia. }   \n    rewrite Int64.unsigned_repr; trivial.  \n    rewrite zero_ext_inrange. f_equal. myadmit.\n    rewrite Int.unsigned_repr. replace (two_p 8 - 1) with 255 by reflexivity.\n  replace (1 + (7 - i)) with (8-i) by lia. replace (i + (8 - i)) with 8 by lia.\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: lia. 2: rewrite Zlength_sublist. lia.\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; lia.\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; lia.\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. lia. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.  \n          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                   2:{ unfold Byte.max_unsigned. lia.\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 lia.\n          rewrite (Int.Ztestbit_mod_two_p 16); try lia.\n          rewrite (Int.Ztestbit_mod_two_p 24); try lia.\n          rewrite Int.bits_shru; try lia. rewrite EIGHT, ZW, Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          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; lia.\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 lia. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try lia.\n          rewrite (Int.Ztestbit_mod_two_p 24); try lia.\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. lia. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\n        destruct (zeq i 3); subst; simpl. f_equal. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          2:{ assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; lia.\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 lia. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 24); try lia.\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. lia. lia. lia. lia. lia.\n          rewrite Int.bits_above. trivial. lia. }\n        lia. }\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!. myadmit. (*Data 7 = repeat Vundef 8*) }\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 lia. 2:{\n   2: red; unfold Int.min_signed, Int.max_signed; simpl; lia.*)\n\n forward.\n  { apply andp_right. 2: solve [entailer].\n    apply andp_right. solve [entailer!].\n    entailer. myadmit. (*typecheck_error (invalid_cast_result tuchar tuchar)*) }\n\n  forward. entailer. simpl. myadmit. (*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!. 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. 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               repeat Vundef (Z.to_nat(8-i)))\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 lia.\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 lia.\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; lia.\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; lia.\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. lia. }\n        destruct (zeq i 1); subst; simpl. f_equal. f_equal. f_equal.\n        { rewrite Byte.unsigned_repr.  \n          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                   2:{ unfold Byte.max_unsigned. lia.\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 lia.\n          rewrite (Int.Ztestbit_mod_two_p 16); try lia.\n          rewrite (Int.Ztestbit_mod_two_p 24); try lia.\n          rewrite Int.bits_shru; try lia. rewrite EIGHT, ZW, Ztest_Inttest.\n          remember (zlt i 8). \n          destruct s. repeat rewrite zlt_true. trivial. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\n        destruct (zeq i 2); subst; simpl. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          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; lia.\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 lia. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 16); try lia.\n          rewrite (Int.Ztestbit_mod_two_p 24); try lia.\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. lia. lia. lia. lia.\n          rewrite zlt_false. trivial. lia. }\n        destruct (zeq i 3); subst; simpl. f_equal. f_equal. f_equal. f_equal.\n          f_equal.\n        { rewrite Byte.unsigned_repr.  \n          2:{ assert (0 <= Int.unsigned u / Z.pow_pos 2 24 < Byte.modulus).\n                   2: unfold Byte.max_unsigned; lia.\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 lia. rewrite EIGHT, ZW.\n          rewrite (Z.div_pow2_bits _ 24); try lia.\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. lia. lia. lia. lia. lia.\n          rewrite Int.bits_above. trivial. lia. }\n        lia. }\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.\n2:{ apply ltu_false_inv in Heqd. rewrite U in *. rewrite Int.unsigned_repr in Heqd. 2: rewrite int_max_unsigned_eq; lia.\nclear Heqd. split; trivial.\nremember (Int.ltu (Int.sub (Int.repr 32) c') Int.iwordsize) as z. symmetry in Heqz.\ndestruct z.\n2:{ 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. lia. rewrite int_max_unsigned_eq; lia.\n           rewrite int_max_unsigned_eq; lia.\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; lia).\n  rewrite Int.unsigned_repr in Heqz. 2: rewrite int_max_unsigned_eq; lia.\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; lia.\n  rewrite H0, W. f_equal. f_equal. f_equal.\n  rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; lia.\n  rewrite Int.and_mone. trivial.\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/tweetnacl20140427/verif_ld_st.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.2877678218692626, "lm_q1q2_score": 0.15733365138004443}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import Structures.OrderedType.\nRequire Import Structures.OrderedTypeEx.\nRequire Import Omega.\nRequire Import List.\nRequire Import Mem.\nRequire Import PredCrash.\nRequire Import AsyncDisk.\nRequire Import Word.\nRequire Import String.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n(** * The programming language *)\n\nParameter vartype : Type.\nParameter vartype_eq_dec : forall (x y : vartype), {x=y}+{x<>y}.\n\nPolymorphic Inductive var_value : Type :=\n  | Any : forall (T : Type), T -> var_value.\n\n(** single program *)\nInductive prog : Type -> Type :=\n  | Ret T (v: T) : prog T\n  | Read (a: addr) : prog valu\n  | Write (a: addr) (v: valu) : prog unit\n  | Sync : prog unit\n  | Trim (a: addr) : prog unit\n  | VarAlloc (T : Type) (v : T) : prog vartype\n  | VarDelete (i : vartype) : prog unit\n  | VarGet (i : vartype) (T : Type) : prog T\n  | VarSet (i : vartype) (T : Type) (v : T) : prog unit\n  | AlertModified : prog unit\n  | Debug (s: string) (n: nat) : prog unit\n  | Rdtsc: prog nat\n  | Hash (sz: nat) (buf: word sz) : prog (word hashlen)\n  | Hash2 (sz1 sz2: nat) (buf1 : word sz1) (buf2 : word sz2) : prog (word hashlen)\n  | Bind T T' (p1: prog T) (p2: T -> prog T') : prog T'.\n\nArguments Ret {T} v.\nArguments VarAlloc {T} v.\nArguments VarGet i {T}.\nArguments VarSet i {T} v.\n\nDefinition varmem := @mem vartype vartype_eq_dec var_value.\n\nInductive outcome (T : Type) :=\n  | Failed\n  | Finished (m: rawdisk) (v: varmem) (hm: hashmap) (v: T)\n  | Crashed (m: rawdisk) (hm: hashmap).\n\nInductive step : forall T,\n    rawdisk -> varmem -> hashmap -> prog T ->\n    rawdisk -> varmem -> hashmap -> T -> Prop :=\n| StepRead : forall m a v x vm hm,\n    m a = Some (v, x) ->\n    step m vm hm (Read a) m vm hm v\n| StepWrite : forall m a v v0 x vm hm,\n    m a = Some (v0, x) ->\n    step m vm hm (Write a v) (upd m a (v, v0 :: x)) vm hm tt\n| StepSync : forall m vm hm,\n    step m vm hm (Sync) (sync_mem m) vm hm tt\n| StepTrim : forall m a vs vs' vm hm,\n    m a = Some vs ->\n    step m vm hm (Trim a) (upd m a vs') vm hm tt\n| StepHash : forall m sz (buf : word sz) h vm hm,\n    hash_safe hm h buf ->\n    hash_fwd buf = h ->\n    step m vm hm (Hash buf) m vm (upd_hashmap' hm h buf) h\n| StepHash2 : forall m sz1 sz2 (buf1 : word sz1) (buf2 : word sz2) (buf : word (sz1 + sz2)) h vm hm,\n    buf = Word.combine buf1 buf2 ->\n    hash_safe hm h buf ->\n    hash_fwd buf = h ->\n    step m vm hm (Hash2 buf1 buf2) m vm (upd_hashmap' hm h buf) h\n| StepVarAlloc : forall T d v vm i hm,\n    vm i = None ->\n    step d vm hm (@VarAlloc T v) d (insert vm i (@Any T v)) hm i\n| StepVarDelete : forall d v vm i hm,\n    vm i = Some v ->\n    step d vm hm (VarDelete i) d (delete vm i) hm tt\n| StepVarGet : forall T d v vm i hm,\n    vm i = Some (@Any T v) ->\n    step d vm hm (@VarGet i T) d vm hm v\n| StepVarSet : forall T d v0 v vm i hm,\n    vm i = Some v0 ->\n    step d vm hm (@VarSet i T v) d (upd vm i (@Any T v)) hm tt.\n\nInductive fail_step : forall T,\n    rawdisk -> varmem -> prog T -> Prop :=\n| FailRead : forall m vm a,\n    m a = None ->\n    fail_step m vm (Read a)\n| FailWrite : forall m vm a v,\n    m a = None ->\n    fail_step m vm (Write a v)\n| FailTrim : forall m vm a,\n    m a = None ->\n    fail_step m vm (Trim a)\n| FailVarDelete : forall m vm i,\n    vm i = None ->\n    fail_step m vm (VarDelete i)\n| FailVarGetType : forall T T' m vm i (v : T'),\n    T <> T' ->\n    vm i = Some (Any v) ->\n    fail_step m vm (@VarGet i T)\n| FailVarGetNone : forall T m vm i,\n    vm i = None ->\n    fail_step m vm (@VarGet i T)\n| FailVarSetNone : forall T m vm i (v : T),\n    vm i = None ->\n    fail_step m vm (VarSet i v).\n\nInductive crash_step : forall T, prog T -> Prop :=\n| CrashRead : forall a,\n    crash_step (Read a)\n| CrashWrite : forall a v,\n    crash_step (Write a v)\n| CrashSync :\n    crash_step Sync.\n\nInductive exec : forall T, rawdisk -> varmem -> hashmap -> prog T -> outcome T -> Prop :=\n| XRet : forall T m vm hm (v: T),\n    exec m vm hm (Ret v) (Finished m vm hm v)\n| XAlertModified : forall m vm hm,\n    exec m vm hm (AlertModified) (Finished m vm hm tt)\n| XDebug : forall m vm hm s a,\n    exec m vm hm (Debug s a) (Finished m vm hm tt)\n| XRdtsc : forall m vm hm t,\n    exec m vm hm (Rdtsc) (Finished m vm hm t)\n| XStep : forall T m vm hm (p: prog T) m' m'' vm' hm' v,\n    step m vm hm p m' vm' hm' v ->\n    possible_sync m' m'' ->\n    exec m vm hm p (Finished m'' vm' hm' v)\n| XBindFinish : forall m vm hm T (p1: prog T) m' vm' hm' (v: T)\n                  T' (p2: T -> prog T') out,\n    exec m vm hm p1 (Finished m' vm' hm' v) ->\n    exec m' vm' hm' (p2 v) out ->\n    exec m vm hm (Bind p1 p2) out\n| XBindFail : forall m vm hm T (p1: prog T)\n                T' (p2: T -> prog T'),\n    exec m vm hm p1 (Failed T) ->\n    exec m vm hm (Bind p1 p2) (Failed T')\n| XBindCrash : forall m vm hm T (p1: prog T) m' hm'\n                 T' (p2: T -> prog T'),\n    exec m vm hm p1 (Crashed T m' hm') ->\n    exec m vm hm (Bind p1 p2) (Crashed T' m' hm')\n| XFail : forall m vm hm T (p: prog T),\n    fail_step m vm p ->\n    exec m vm hm p (Failed T)\n| XCrash : forall m vm hm T (p: prog T),\n    crash_step p ->\n    exec m vm hm p (Crashed T m hm).\n\n(** program with recovery *)\nInductive recover_outcome (TF TR: Type) :=\n  | RFailed\n  | RFinished (m: rawdisk) (vm: varmem) (hm: hashmap) (v: TF)\n  | RRecovered (m: rawdisk) (vm: varmem) (hm: hashmap) (v: TR).\n\nInductive exec_recover (TF TR: Type)\n    : rawdisk -> varmem -> hashmap -> prog TF -> prog TR -> recover_outcome TF TR -> Prop :=\n  | XRFail : forall m vm hm p1 p2, exec m vm hm p1 (Failed TF)\n    -> exec_recover m vm hm p1 p2 (RFailed TF TR)\n  | XRFinished : forall m vm hm p1 p2 m' vm' hm' (v: TF), exec m vm hm p1 (Finished m' vm' hm' v)\n    -> exec_recover m vm hm p1 p2 (RFinished TR m' vm' hm' v)\n  | XRCrashedFailed : forall m vm hm p1 p2 m' hm' m'r, exec m vm hm p1 (Crashed TF m' hm')\n    -> possible_crash m' m'r\n    -> @exec_recover TR TR m'r empty_mem hm' p2 p2 (RFailed TR TR)\n    -> exec_recover m vm hm p1 p2 (RFailed TF TR)\n  | XRCrashedFinished : forall m vm hm p1 p2 m' hm' m'r m'' vm'' hm'' (v: TR), exec m vm hm p1 (Crashed TF m' hm')\n    -> possible_crash m' m'r\n    -> @exec_recover TR TR m'r empty_mem hm' p2 p2 (RFinished TR m'' vm'' hm'' v)\n    -> exec_recover m vm hm p1 p2 (RRecovered TF m'' vm'' hm'' v)\n  | XRCrashedRecovered : forall m vm hm p1 p2 m' hm' m'r m'' vm'' hm'' (v: TR), exec m vm hm p1 (Crashed TF m' hm')\n    -> possible_crash m' m'r\n    -> @exec_recover TR TR m'r empty_mem hm' p2 p2 (RRecovered TR m'' vm'' hm'' v)\n    -> exec_recover m vm hm p1 p2 (RRecovered TF m'' vm'' hm'' v).\n\nHint Constructors exec.\nHint Constructors step.\nHint Constructors exec_recover.\n\n(** program notations *)\n\nDefinition pair_args_helper (A B C:Type) (f: A->B->C) (x: A*B) := f (fst x) (snd x).\nNotation \"^( a )\" := (pair a tt).\nNotation \"^( a , .. , b )\" := (pair a .. (pair b tt) .. ).\n\nNotation \"p1 ;; p2\" := (Bind p1 (fun _: unit => p2)) (at level 60, right associativity).\nNotation \"x <- p1 ; p2\" := (Bind p1 (fun x => p2)) (at level 60, right associativity,\n                                                 format \"'[v' x  <-  p1 ; '/' p2 ']'\").\nNotation \"'let^' ( a ) <- p1 ; p2\" :=\n  (Bind p1\n    (pair_args_helper (fun a (_:unit) => p2))\n  )\n  (at level 60, right associativity, a ident,\n   format \"'[v' let^ ( a )  <-  p1 ; '/' p2 ']'\").\n\nNotation \"'let^' ( a , .. , b ) <- p1 ; p2\" :=\n  (Bind p1\n    (pair_args_helper (fun a => ..\n      (pair_args_helper (fun b (_:unit) => p2))\n    ..))\n  )\n    (at level 60, right associativity, a closed binder, b closed binder,\n     format \"'[v' let^ ( a , .. , b )  <-  p1 ; '/' p2 ']'\").\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/Prog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.15728019757226705}}
{"text": "Require Import Events.\nRequire Import ValuesC.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import CoqlibC.\nRequire Import Skeleton.\nRequire Import Integers.\nRequire Import ASTC.\nRequire Import LinkingC.\nRequire Import Maps.\n\nRequire Import SimMem.\nRequire Import System.\nRequire Import ModSem.\n\nSet Implicit Arguments.\n\n\nModule SimSymb.\n\n  Inductive skenv_func_bisim (sim_val: val -> val -> Prop) (skenv_src skenv_tgt: SkEnv.t): Prop :=\n  | skenv_func_bisim_intro\n      (FUNCFSIM: forall fptr_src fptr_tgt def_src\n          (SIMFPTR: sim_val fptr_src fptr_tgt)\n          (FUNCSRC: (Genv.find_funct skenv_src) fptr_src = Some def_src),\n          exists def_tgt, <<FUNCSRC: (Genv.find_funct skenv_tgt) fptr_tgt = Some def_tgt>> /\\ <<SIM: def_src = def_tgt>>).\n\n  Class class (SM: SimMem.class) :=\n    { t: Type;\n      le: t -> t -> Prop;\n      src: t -> Sk.t;\n      tgt: t -> Sk.t;\n\n      le_PreOrder :> PreOrder le;\n\n      wf: t -> Prop;\n      wf_preserves_wf: forall ss0\n          (SIMSK: wf ss0)\n          (WFSRC: Sk.wf ss0.(src)),\n          <<WFTGT: Sk.wf ss0.(tgt)>>;\n\n      wf_link: forall ss0 ss1 sk_src\n          (SIMSK: wf ss0)\n          (SIMSK: wf ss1)\n          (LINKSRC: link ss0.(src) ss1.(src) = Some sk_src)\n          (WFSRC0: Sk.wf ss0.(src))\n          (WFSRC1: Sk.wf ss1.(src))\n          (WFTGT0: Sk.wf ss0.(tgt))\n          (WFTGT1: Sk.wf ss1.(tgt)),\n          exists ss sk_tgt,\n            <<LINKTGT: link ss0.(tgt) ss1.(tgt) = Some sk_tgt>> /\\\n            <<SKSRC: ss.(src) = sk_src>> /\\\n            <<SKTGT: ss.(tgt) = sk_tgt>> /\\\n            <<LE0: le ss0 ss>> /\\\n            <<LE1: le ss1 ss>> /\\\n            <<SIMSK: wf ss>>;\n\n      sim_skenv: SimMem.t -> t -> SkEnv.t -> SkEnv.t -> Prop;\n\n      sim_skenv_public_symbols: forall sm0 ss0 skenv_src skenv_tgt\n          (SIMSKE: sim_skenv sm0 ss0 skenv_src skenv_tgt),\n          (Genv.public_symbol skenv_src) = (Genv.public_symbol skenv_tgt);\n\n      wf_load_sim_skenv: forall ss skenv_src skenv_tgt m_src\n          (SIMSK: wf ss)\n          (LOADSRC: (Sk.load_skenv ss.(src)) = skenv_src)\n          (LOADTGT: (Sk.load_skenv ss.(tgt)) = skenv_tgt)\n          (LOADMEMSRC: (Sk.load_mem ss.(src)) = Some m_src),\n          exists m_tgt sm,\n            (<<LOADMEMTGT: (Sk.load_mem ss.(tgt)) = Some m_tgt>>) /\\\n            (<<SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt>>) /\\\n            (<<MEMSRC: sm.(SimMem.src) = m_src>>) /\\\n            (<<MEMTGT: sm.(SimMem.tgt) = m_tgt>>) /\\\n            (<<MWF: sm.(SimMem.wf)>>) /\\\n            (<<MAINSIM: SimMem.sim_val sm (Genv.symbol_address skenv_src ss.(src).(prog_main) Ptrofs.zero)\n                                       (Genv.symbol_address skenv_tgt ss.(tgt).(prog_main) Ptrofs.zero)>>);\n\n      mlepriv_preserves_sim_skenv: forall sm0 sm1 ss skenv_src skenv_tgt\n          (MLE: SimMem.lepriv sm0 sm1)\n          (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt),\n          <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>;\n\n      sim_skenv_monotone: forall\n          sm ss_link skenv_link_src skenv_link_tgt\n          ss skenv_src skenv_tgt\n          (WFSRC: SkEnv.wf skenv_link_src)\n          (WFTGT: SkEnv.wf skenv_link_tgt)\n          (SIMSKENV: sim_skenv sm ss_link skenv_link_src skenv_link_tgt)\n          (SIMSK: wf ss)\n          (LE: le ss ss_link)\n          (INCLSRC: SkEnv.includes skenv_link_src ss.(src))\n          (INCLTGT: SkEnv.includes skenv_link_tgt ss.(tgt))\n          (LESRC: SkEnv.project skenv_link_src ss.(src) = skenv_src)\n          (LETGT: SkEnv.project skenv_link_tgt ss.(tgt) = skenv_tgt),\n          <<SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt>>;\n\n      sim_skenv_func_bisim: forall sm ss skenv_src skenv_tgt\n          (SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt),\n          <<DEF: skenv_func_bisim sm.(SimMem.sim_val) skenv_src skenv_tgt>>;\n\n      system_sim_skenv: forall sm ss skenv_src skenv_tgt\n          (SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt),\n          <<SIMSKENV: sim_skenv sm ss (System.skenv skenv_src) (System.skenv skenv_tgt)>>;\n      system_axiom: forall\n          sm0 ss_sys skenv_sys_src skenv_sys_tgt\n          args_src args_tgt tr retv_src ef\n          (SIMSKENV: sim_skenv sm0 ss_sys skenv_sys_src skenv_sys_tgt)\n          (MWF: SimMem.wf sm0)\n          (CSTYLE: Args.is_cstyle args_src)\n          (CSTYLE: Retv.is_cstyle retv_src)\n          (ARGS: SimMem.sim_args args_src args_tgt sm0)\n          (SYSSRC: external_call ef skenv_sys_src (Args.vs (args_src)) (Args.m (args_src))\n                                 tr\n                                 (Retv.v (retv_src)) (Retv.m (retv_src))),\n          exists sm1 retv_tgt,\n            (<<SYSTGT: external_call ef skenv_sys_tgt (Args.vs (args_tgt)) (Args.m (args_tgt))\n                                     tr\n                                     (Retv.v (retv_tgt)) (Retv.m (retv_tgt))>>)\n            /\\ (<<RETV: SimMem.sim_retv retv_src retv_tgt sm1>>)\n            /\\ (<<MLE0: SimMem.le sm0 sm1>>)\n            /\\ (<<MWF: SimMem.wf sm1>>);\n    }.\n\n  Lemma mle_preserves_sim_skenv: forall\n      `{SM: SimMem.class} `{SS: @class SM}\n      sm0 sm1 ss skenv_src skenv_tgt\n      (MLE: SimMem.le sm0 sm1)\n      (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt),\n      <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>.\n  Proof. ii. eapply mlepriv_preserves_sim_skenv; et. Qed.\n\n  Lemma mfuture_preserves_sim_skenv\n        `{SM: SimMem.class} `{SS: @class SM}\n        sm0 sm1 ss skenv_src skenv_tgt\n        (MFUTURE: SimMem.future sm0 sm1)\n        (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt):\n      <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>.\n  Proof.\n    induction MFUTURE; ss. des.\n    - eapply IHMFUTURE; eauto. eapply mlepriv_preserves_sim_skenv; eauto.\n    - eapply IHMFUTURE; eauto. eapply mle_preserves_sim_skenv; eauto.\n  Qed.\n\n  Lemma simskenv_func_fsim\n        `{SM: SimMem.class} `{SS: @class SM}\n        ss0 sm0 skd v_src v_tgt skenv_link_src skenv_link_tgt\n        (SIMSKENV: sim_skenv sm0 ss0 skenv_link_src skenv_link_tgt)\n        (SIMV: sm0.(SimMem.sim_val) v_src v_tgt)\n        (FIND: Genv.find_funct skenv_link_src v_src = Some skd):\n      Genv.find_funct skenv_link_tgt v_tgt = Some skd.\n  Proof. exploit SimSymb.sim_skenv_func_bisim; eauto. i; des. inv H. exploit FUNCFSIM; eauto. i; des. clarify. Qed.\n\nEnd SimSymb.\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/SimSymb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.25683198001082097, "lm_q1q2_score": 0.15702244274405966}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma pure1 : (0) = (0). intros; hammer. Qed.\nHint Resolve pure1: ssl_pure.\nLemma pure2 (n1x1 : nat) (n2x1 : nat) : (0) <= (((1) + (n1x1)) + (n2x1)) -> (0) <= (n1x1) -> (0) <= (n2x1) -> (((1) + (n1x1)) + (n2x1)) = (((1) + (n1x1)) + (n2x1)). intros; hammer. Qed.\nHint Resolve pure2: ssl_pure.\n\nDefinition tree_size_type :=\n  forall (vprogs : ptr * ptr),\n  {(vghosts : nat)},\n  STsep (\n    fun h =>\n      let: (x, r) := vprogs in\n      let: (n) := vghosts in\n      exists h_treeN_xn_a,\n      (0) <= (n) /\\ h = r :-> (0) \\+ h_treeN_xn_a /\\ treeN x n h_treeN_xn_a,\n    [vfun (_: unit) h =>\n      let: (x, r) := vprogs in\n      let: (n) := vghosts in\n      exists h_treeN_xn_a,\n      h = r :-> (n) \\+ h_treeN_xn_a /\\ treeN x n h_treeN_xn_a\n    ]).\n\nProgram Definition tree_size : tree_size_type :=\n  Fix (fun (tree_size : tree_size_type) vprogs =>\n    let: (x, r) := vprogs in\n    Do (\n      if (x) == (null)\n      then\n        ret tt\n      else\n        vx1 <-- @read ptr x;\n        lx1 <-- @read ptr (x .+ 1);\n        rx1 <-- @read ptr (x .+ 2);\n        tree_size (lx1, r);;\n        n1x1 <-- @read nat r;\n        r ::= 0;;\n        tree_size (rx1, r);;\n        n2x1 <-- @read nat r;\n        r ::= ((1) + (n1x1)) + (n2x1);;\n        ret tt\n    )).\nObligation Tactic := intro; move=>[x r]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>n.\nex_elim h_treeN_xn_a.\nmove=>[phi_self0].\nmove=>[sigma_self].\nsubst h_self.\nmove=>H_treeN_xn_a.\nssl_ghostelim_post.\nssl_open ((x) == (null)) H_treeN_xn_a.\nmove=>[phi_treeN_xn_a0].\nmove=>[sigma_treeN_xn_a].\nsubst h_treeN_xn_a.\ntry rename h_treeN_xn_a into h_treeN_x_a.\ntry rename H_treeN_xn_a into H_treeN_x_a.\nssl_emp;\nexists (empty);\nsslauto.\nssl_close 1;\nsslauto.\nex_elim n1x n2x lx rx vx.\nex_elim h_treeN_lxn1x_2x h_treeN_rxn2x_3x.\nmove=>[phi_treeN_xn_a0] [phi_treeN_xn_a1] [phi_treeN_xn_a2].\nmove=>[sigma_treeN_xn_a].\nsubst h_treeN_xn_a.\nmove=>[H_treeN_lxn1x_2x H_treeN_rxn2x_3x].\ntry rename h_treeN_xn_a into h_treeN_xn1xn2x_a.\ntry rename H_treeN_xn_a into H_treeN_xn1xn2x_a.\nssl_read x.\ntry rename vx into vx1.\nssl_read (x .+ 1).\ntry rename lx into lx1.\ntry rename h_treeN_lxn1x_2x into h_treeN_lx1n1x_2x.\ntry rename H_treeN_lxn1x_2x into H_treeN_lx1n1x_2x.\nssl_read (x .+ 2).\ntry rename rx into rx1.\ntry rename h_treeN_rxn2x_3x into h_treeN_rx1n2x_3x.\ntry rename H_treeN_rxn2x_3x into H_treeN_rx1n2x_3x.\ntry rename h_treeN_x1n1_a1 into h_treeN_lx1n1x_2x.\ntry rename H_treeN_x1n1_a1 into H_treeN_lx1n1x_2x.\nssl_call_pre (r :-> (0) \\+ h_treeN_lx1n1x_2x).\nssl_call (n1x).\nexists (h_treeN_lx1n1x_2x);\nsslauto.\nssl_frame_unfold.\nmove=>h_call0.\nex_elim h_treeN_lx1n1x_2x.\nmove=>[sigma_call0].\nsubst h_call0.\nmove=>H_treeN_lx1n1x_2x.\nstore_valid.\nssl_read r.\ntry rename n1x into n1x1.\ntry rename h_treeN_lx1n1x_2x into h_treeN_lx1n1x1_2x.\ntry rename H_treeN_lx1n1x_2x into H_treeN_lx1n1x1_2x.\ntry rename h_treeN_xn1xn2x_a into h_treeN_xn1x1n2x_a.\ntry rename H_treeN_xn1xn2x_a into H_treeN_xn1x1n2x_a.\ntry rename h_treeN_x2n2_a2 into h_treeN_rx1n2x_3x.\ntry rename H_treeN_x2n2_a2 into H_treeN_rx1n2x_3x.\nssl_write r.\nssl_call_pre (r :-> (0) \\+ h_treeN_rx1n2x_3x).\nssl_call (n2x).\nexists (h_treeN_rx1n2x_3x);\nsslauto.\nssl_frame_unfold.\nmove=>h_call1.\nex_elim h_treeN_rx1n2x_3x.\nmove=>[sigma_call1].\nsubst h_call1.\nmove=>H_treeN_rx1n2x_3x.\nstore_valid.\nssl_read r.\ntry rename n2x into n2x1.\ntry rename h_treeN_xn1x1n2x_a into h_treeN_xn1x1n2x1_a.\ntry rename H_treeN_xn1x1n2x_a into H_treeN_xn1x1n2x1_a.\ntry rename h_treeN_rx1n2x_3x into h_treeN_rx1n2x1_3x.\ntry rename H_treeN_rx1n2x_3x into H_treeN_rx1n2x1_3x.\ntry rename h_treeN_lx2n11x_2x1 into h_treeN_lx1n1x1_2x.\ntry rename H_treeN_lx2n11x_2x1 into H_treeN_lx1n1x1_2x.\ntry rename h_treeN_r3xn21x_3x1 into h_treeN_rx1n2x1_3x.\ntry rename H_treeN_r3xn21x_3x1 into H_treeN_rx1n2x1_3x.\nssl_write r.\nssl_write_post r.\nssl_emp;\nexists (x :-> (vx1) \\+ x .+ 1 :-> (lx1) \\+ x .+ 2 :-> (rx1) \\+ h_treeN_lx1n1x1_2x \\+ h_treeN_rx1n2x1_3x);\nsslauto.\nssl_close 2;\nexists (n1x1), (n2x1), (lx1), (rx1), (vx1), (h_treeN_lx1n1x1_2x), (h_treeN_rx1n2x1_3x);\nsslauto.\nssl_frame_unfold.\nssl_frame_unfold.\nQed.", "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/standard/tree/tree_size.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.1568608148090617}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude finite.\nFrom Coq Require Import FinFun Reals Lra.\nFrom VLSM.Lib Require Import Preamble Measurable RealsExtras FinSetExtras.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition AnnotatedVLSM.\nFrom VLSM.Core Require Import Equivocation Equivocation.TraceWiseEquivocation MessageDependencies.\nFrom VLSM.Core Require Import Equivocation.NoEquivocation Equivocation.LimitedMessageEquivocation.\nFrom VLSM.Core Require Import FixedSetEquivocation MsgDepLimitedEquivocation.\nFrom VLSM.Core Require Import Equivocators.Equivocators.\nFrom VLSM.Core Require Import Equivocators.MessageProperties.\nFrom VLSM.Core Require Import Equivocators.EquivocatorsComposition.\nFrom VLSM.Core Require Import Equivocators.EquivocatorsCompositionProjections.\nFrom VLSM.Core Require Import Equivocators.FixedEquivocation.\n\n(** * VLSM Limited Equivocation *)\nDefinition composite_constraint\n  {index message} (IM : index -> VLSM message) : Type :=\n  composite_label IM -> composite_state IM * option message -> Prop.\n\nLemma equivocator_initial_state_project\n  {message}\n  (X : VLSM message)\n  (es : vstate (equivocator_vlsm X))\n  (eqv_descriptor : MachineDescriptor X)\n  (Heqv : proper_descriptor X eqv_descriptor es)\n  (Hes : vinitial_state_prop (equivocator_vlsm X) es) :\n  vinitial_state_prop X (equivocator_state_descriptor_project es eqv_descriptor).\nProof.\n  destruct eqv_descriptor; [done |].\n  destruct Heqv as [esn Hesn].\n  simpl. rewrite Hesn.\n  by eapply equivocator_vlsm_initial_state_preservation_rev.\nQed.\n\nLemma composite_equivocators_initial_state_project\n  {message}\n  `{EqDecision index}\n  (IM : index -> VLSM message)\n  (es : composite_state (equivocator_IM IM))\n  (eqv_descriptors : equivocator_descriptors IM)\n  {eqv_constraint : composite_constraint (equivocator_IM IM)}\n  {constraint : composite_constraint IM}\n  (Heqv : proper_equivocator_descriptors IM eqv_descriptors es)\n  (Hes : vinitial_state_prop (composite_vlsm (equivocator_IM IM) eqv_constraint) es)\n  : vinitial_state_prop (composite_vlsm IM constraint)\n      (equivocators_state_project IM eqv_descriptors es).\nProof.\n  refine (fun i => equivocator_initial_state_project _ _ _ (Heqv i) (Hes i)).\nQed.\n\nSection sec_limited_state_equivocation.\n\nContext {message index : Type}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  `{forall i : index, HasBeenReceivedCapability (IM i)}\n  (threshold : R)\n  `{ReachableThreshold index Ci threshold}\n  `{!finite.Finite index}\n  (Free := free_composite_vlsm IM)\n  (equivocator_descriptors := equivocator_descriptors IM)\n  (equivocators_state_project := equivocators_state_project IM)\n  (equivocator_IM := equivocator_IM IM)\n  (equivocator_descriptors_update := equivocator_descriptors_update IM)\n  (proper_equivocator_descriptors := proper_equivocator_descriptors IM)\n  (sender : message -> option index)\n  (Heqv_idx_BasicEquivocation : BasicEquivocation (composite_state equivocator_IM) index Ci threshold\n    := equivocating_indices_BasicEquivocation IM threshold)\n  (FreeE : VLSM message := free_composite_vlsm equivocator_IM)\n  (PreFreeE := pre_loaded_with_all_messages_vlsm FreeE)\n  (not_heavy := not_heavy (1 := Heqv_idx_BasicEquivocation))\n  (equivocating_validators := equivocating_validators (1 := Heqv_idx_BasicEquivocation))\n  (equivocation_fault := equivocation_fault (1 := Heqv_idx_BasicEquivocation))\n  .\n\nDefinition equivocators_limited_equivocations_constraint\n  (l : composite_label equivocator_IM)\n  (som : composite_state equivocator_IM * option message)\n  (som' := composite_transition equivocator_IM l som)\n  : Prop\n  := equivocators_no_equivocations_constraint IM l som\n  /\\ not_heavy (fst som').\n\nDefinition equivocators_limited_equivocations_vlsm\n  : VLSM message\n  :=\n  composite_vlsm equivocator_IM equivocators_limited_equivocations_constraint.\n\n(** Inclusion in the free composition. *)\nLemma equivocators_limited_equivocations_vlsm_incl_free\n  : VLSM_incl equivocators_limited_equivocations_vlsm FreeE.\nProof.\n  by apply constraint_subsumption_incl.\nQed.\n\n(** Inclusion in the preloaded free composition. *)\nLemma equivocators_limited_equivocations_vlsm_incl_preloaded_free\n  : VLSM_incl equivocators_limited_equivocations_vlsm PreFreeE.\nProof.\n  specialize equivocators_limited_equivocations_vlsm_incl_free as Hincl1.\n  specialize (vlsm_incl_pre_loaded_with_all_messages_vlsm FreeE)\n    as Hincl2.\n  by eapply VLSM_incl_trans.\nQed.\n\n(** Inclusion of preloaded machine in the preloaded free composition. *)\nLemma preloaded_equivocators_limited_equivocations_vlsm_incl_free\n  : VLSM_incl (pre_loaded_with_all_messages_vlsm equivocators_limited_equivocations_vlsm) PreFreeE.\nProof.\n  by apply basic_VLSM_incl_preloaded; intros ? *; [intro | inversion 1 | intro].\nQed.\n\n(**\n  Inclusion in the composition of equivocators with no message equivocation\n  (no restriction on state equivocation).\n*)\nLemma equivocators_limited_equivocations_vlsm_incl_no_equivocations\n  : VLSM_incl equivocators_limited_equivocations_vlsm (equivocators_no_equivocations_vlsm IM).\nProof.\n  apply constraint_subsumption_incl.\n  by intros l [s om] (_ & _ & _ & Hc & _).\nQed.\n\n(**\n  A valid state for a VLSM satisfying the limited equivocation assumption\n  has limited equivocation.\n*)\nLemma valid_state_limited_equivocation\n  (s : composite_state equivocator_IM)\n  (Hs : valid_state_prop equivocators_limited_equivocations_vlsm s)\n  : not_heavy s.\nProof.\n  apply valid_state_prop_iff in Hs.\n  destruct Hs as [[(is, His) Heq_s] | [l [(s0, oim) [oom' [[_ [_ [_ [_ Hlimited]]]] Ht]]]]].\n  - subst s.\n    unfold not_heavy, Equivocation.not_heavy,\n      equivocation_fault, Equivocation.equivocation_fault; simpl.\n    pose proof (Heqv_is := @equivocating_indices_equivocating_validators _ _ _ _\n        IM _ _ _ H1 _ _ _ _ _ _ _ _ H9 is).\n    rewrite equivocating_indices_initially_empty in Heqv_is by done.\n    simpl in Heqv_is; apply sum_weights_empty in Heqv_is.\n    pose proof (rt_positive (H6 := H8)).\n    by cbv in Heqv_is |- *; lra.\n  - by replace s with (fst (composite_transition equivocator_IM l (s0, oim))); [done |]\n    ; cbn in *; rewrite Ht.\nQed.\n\n(**\n  A valid valid trace for the composition of equivocators with limited\n  state-equivocation and no message-equivocation is also a valid valid trace\n  for the composition of equivocators with no message-equivocation and fixed-set\n  state-equivocation, where the fixed set is given by the state-equivocators\n  measured for the final state of the trace.\n*)\nLemma equivocators_limited_valid_trace_is_fixed is s tr\n  : finite_valid_trace_init_to equivocators_limited_equivocations_vlsm is s tr ->\n  finite_valid_trace_init_to\n   (equivocators_fixed_equivocations_vlsm IM (elements(equivocating_validators s)))\n   is s tr.\nProof.\n  intro Htr.\n  split; [| apply Htr].\n  cut\n    (forall equivocating, elements(equivocating_validators s) \u2286 equivocating ->\n      finite_valid_trace_from_to (equivocators_fixed_equivocations_vlsm IM equivocating) is s tr);\n    [by intros H'; apply H' |].\n  induction Htr using finite_valid_trace_init_to_rev_ind; intros equivocating Hincl.\n  - apply (finite_valid_trace_from_to_empty (equivocators_fixed_equivocations_vlsm IM equivocating)).\n    by apply initial_state_is_valid.\n  - specialize (IHHtr equivocating).\n    spec IHHtr.\n    { apply proj2 in Ht.\n      specialize (equivocators_transition_preserves_equivocating_indices\n        IM (enum index)  _ _ _ _ _ Ht) as Hincl'.\n      clear -Hincl Hincl'.\n      transitivity (elements (equivocating_validators sf)); [| done].\n      intro x; rewrite! elem_of_elements; intro Hx.\n      apply equivocating_indices_equivocating_validators, elem_of_list_to_set, Hincl'.\n      by apply equivocating_indices_equivocating_validators, elem_of_list_to_set in Hx.\n    }\n    apply\n      (finite_valid_trace_from_to_app\n        (equivocators_fixed_equivocations_vlsm IM equivocating))\n      with s; [done |].\n    apply valid_trace_add_last; [| done].\n      apply (finite_valid_trace_singleton (equivocators_fixed_equivocations_vlsm IM equivocating)).\n      apply valid_trace_last_pstate in IHHtr.\n      destruct Ht as [[_ [_ [Hv [[Hno_equiv _] Hno_heavy]]]] Ht].\n      repeat split; [done | | done | done | | done].\n      + destruct iom as [m |]; [| by apply option_valid_message_None].\n        destruct Hno_equiv as [Hsent | Hfalse]; [| done].\n        simpl in Hsent.\n        by eapply composite_sent_valid.\n      + replace (composite_transition _ _ _) with (sf, oom).\n        unfold state_has_fixed_equivocation.\n        transitivity (elements (equivocating_validators sf)); [| done].\n        by intros x Hx; apply elem_of_elements, equivocating_indices_equivocating_validators,\n          elem_of_list_to_set.\nQed.\n\n(**\n  Projections of valid traces for the composition of equivocators\n  with limited state-equivocation and no message-equivocation have the\n  [fixed_limited_equivocation_prop]erty.\n*)\nLemma equivocators_limited_valid_trace_projects_to_fixed_limited_equivocation\n  (final_descriptors : equivocator_descriptors)\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Hproper : not_equivocating_equivocator_descriptors IM final_descriptors final_state)\n  (Htr : finite_valid_trace equivocators_limited_equivocations_vlsm is tr)\n  : exists\n    (trX : list (composite_transition_item IM))\n    (initial_descriptors : equivocator_descriptors)\n    (isX := equivocators_state_project initial_descriptors is)\n    (final_stateX := finite_trace_last isX trX),\n    proper_equivocator_descriptors initial_descriptors is /\\\n    equivocators_trace_project IM final_descriptors tr = Some (trX, initial_descriptors) /\\\n    equivocators_state_project final_descriptors final_state = final_stateX /\\\n    fixed_limited_equivocation_prop (Cv := Ci) (Ci := Ci) IM threshold Datatypes.id isX trX.\nProof.\n  apply valid_trace_add_default_last in Htr as Hfixed_tr.\n  apply equivocators_limited_valid_trace_is_fixed in Hfixed_tr.\n  apply valid_trace_last_pstate in Hfixed_tr as Hfixed_last.\n  apply valid_trace_forget_last in Hfixed_tr.\n  specialize (fixed_equivocators_valid_trace_project IM\n    (equivocating_validators (finite_trace_last is tr)) final_descriptors is tr) as Hpr.\n  feed specialize Hpr; [| done |].\n  - by eapply not_equivocating_equivocator_descriptors_proper_fixed.\n  - destruct Hpr as (trX & initial_descriptors & Hinitial_descriptors & Hpr & Hlst_pr & Hpr_fixed).\n    exists trX, initial_descriptors.\n    split_and!; [by apply Hinitial_descriptors | done | done |].\n    exists (equivocating_validators (finite_trace_last is tr)).\n    split.\n    + apply valid_trace_add_default_last, valid_trace_last_pstate,\n        valid_state_limited_equivocation in Htr.\n      transitivity (equivocation_fault (finite_trace_last is tr)); [| done].\n      by unfold equivocation_fault; apply sum_weights_subseteq.\n    + revert Hpr_fixed.\n      apply VLSM_incl_finite_valid_trace, constraint_subsumption_incl.\n      apply preloaded_constraint_subsumption_stronger, strong_constraint_subsumption_strongest.\n      intros l (s, [m |]); [| done]; cbn.\n      intros [| Hemit]; [by left |].\n      right; revert Hemit.\n      unshelve eapply VLSM_embedding_can_emit, equivocators_composition_for_directly_observed_index_incl_embedding.\n      apply elements_subseteq.\n      by intros v Hv; apply elem_of_map; eexists.\nQed.\n\nSection sec_equivocators_projection_annotated_limited.\n\nContext\n  `{FinSet message Cm}\n  (message_dependencies : message -> Cm)\n  (full_message_dependencies : message -> Cm)\n  (HFullMsgDep : FullMessageDependencies message_dependencies full_message_dependencies)\n  (HMsgDep : forall i, MessageDependencies (IM i) message_dependencies)\n  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (Hchannel : channel_authentication_prop IM Datatypes.id sender)\n  .\n\n(**\n  Projections of valid traces for the composition of equivocators\n  with limited state-equivocation and no message-equivocation can be\n  annotated with equivocators to obtain a limited-message equivocation trace.\n*)\nLemma equivocators_limited_valid_trace_projects_to_annotated_limited_equivocation\n  (final_descriptors : equivocator_descriptors)\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Hproper : not_equivocating_equivocator_descriptors IM final_descriptors final_state)\n  (Htr : finite_valid_trace equivocators_limited_equivocations_vlsm is tr)\n  : exists\n    (trX : list (composite_transition_item IM))\n    (initial_descriptors : equivocator_descriptors)\n    (isX := equivocators_state_project initial_descriptors is)\n    (final_stateX := finite_trace_last isX trX),\n    proper_equivocator_descriptors initial_descriptors is /\\\n    equivocators_trace_project IM final_descriptors tr = Some (trX, initial_descriptors) /\\\n    equivocators_state_project final_descriptors final_state = final_stateX /\\\n    finite_valid_trace (msg_dep_limited_equivocation_vlsm IM threshold full_message_dependencies sender (Cv := Ci))\n      {| original_state := isX; state_annotation := ` inhabitant |}\n      (msg_dep_annotate_trace_with_equivocators IM full_message_dependencies sender isX trX).\nProof.\n  eapply equivocators_limited_valid_trace_projects_to_fixed_limited_equivocation\n      in Htr as (trX & initial_descriptors & Hinitial_descriptors & Hpr & Hlst_pr & Hpr_limited)\n  ; [| done].\n  exists trX, initial_descriptors.\n  cbn; split_and!; [itauto.. |].\n  by eapply @msg_dep_limited_fixed_equivocation; [| | | typeclasses eauto |..].\nQed.\n\nEnd sec_equivocators_projection_annotated_limited.\n\nSection sec_equivocators_projection_constrained_limited.\n\nContext\n  `{FinSet message Cm}\n  `{RelDecision _ _ (is_equivocating_tracewise_no_has_been_sent IM Datatypes.id sender)}\n  (Limited : VLSM message := tracewise_limited_equivocation_vlsm_composition IM (Cv := Ci) threshold Datatypes.id sender)\n  (Hsender_safety : sender_safety_alt_prop IM Datatypes.id sender)\n  (message_dependencies : message -> Cm)\n  (Hfull : forall i, message_dependencies_full_node_condition_prop (IM i) message_dependencies)\n  .\n\n(**\n  If each of the nodes satisfy the [message_dependencies_full_node_condition_prop]erty,\n  then projections of valid traces for the composition of equivocators\n  with limited state-equivocation and no message-equivocation are also valid\n  traces for the composition of regular nodes with limited\n  message-equivocation.\n*)\nLemma limited_equivocators_valid_trace_project\n  (final_descriptors : equivocator_descriptors)\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Hproper : not_equivocating_equivocator_descriptors IM final_descriptors final_state)\n  (Htr : finite_valid_trace equivocators_limited_equivocations_vlsm is tr)\n  : exists\n    (trX : list (composite_transition_item IM))\n    (initial_descriptors : equivocator_descriptors)\n    (isX := equivocators_state_project initial_descriptors is)\n    (final_stateX := finite_trace_last isX trX),\n    proper_equivocator_descriptors initial_descriptors is /\\\n    equivocators_trace_project IM final_descriptors tr = Some (trX, initial_descriptors) /\\\n    equivocators_state_project final_descriptors final_state = final_stateX /\\\n    finite_valid_trace Limited isX trX.\nProof.\n  specialize\n    (equivocators_limited_valid_trace_projects_to_fixed_limited_equivocation\n      final_descriptors is tr Hproper Htr)\n      as [trX [initial_descriptors [Hinitial_descriptors [Hpr [Hlst_pr Hpr_limited]]]]].\n  exists trX, initial_descriptors.\n  repeat split; [done.. | |].\n  - by eapply @traces_exhibiting_limited_equivocation_are_valid; [| | typeclasses eauto | |].\n  - by destruct Hpr_limited as [equivs Hpr_limited]; apply Hpr_limited.\nQed.\n\n(**\n  The above result formalized as a relation between the corresponding\n  composite VLSMs. It yields a [VLSM_partial_projection] because for invalid\n  [equivocator_descriptors] one might not be able to obtain a trace projection.\n*)\nLemma limited_equivocators_vlsm_partial_projection\n  (final_descriptors : equivocator_descriptors)\n  : VLSM_partial_projection equivocators_limited_equivocations_vlsm Limited\n      (equivocators_partial_trace_project IM final_descriptors).\nProof.\n  split; [split |].\n  - intros s tr sX trX Hpr_tr s_pre pre Hs_lst Hpre_tr.\n    assert (HPreFree_pre_tr :\n      finite_valid_trace_from (pre_loaded_with_all_messages_vlsm FreeE) s_pre (pre ++ tr)).\n    {\n      revert Hpre_tr; apply VLSM_incl_finite_valid_trace_from.\n      by apply equivocators_limited_equivocations_vlsm_incl_preloaded_free.\n    }\n    clear Hpre_tr.  revert s tr sX trX Hpr_tr s_pre pre Hs_lst HPreFree_pre_tr.\n    by apply equivocators_partial_trace_project_extends_left.\n  - intros s tr sX trX Hpr_tr Htr.\n    destruct (destruct_equivocators_partial_trace_project IM Hpr_tr)\n      as [Hnot_equiv [initial_descriptors [Htr_project Hs_project]]].\n\n    destruct (limited_equivocators_valid_trace_project _ _ _ Hnot_equiv Htr)\n      as (_trX & _initial_descriptors & _ & _Htr_project & _ & HtrX).\n    rewrite Htr_project in _Htr_project.\n    by inversion _Htr_project; subst.\nQed.\n\n(**\n  In the case of using the original machine copy for projecting each node, we\n  are guaranteed to obtain a trace projection for each trace, hence the relation\n  above strengthens to a [VLSM_projection].\n*)\nLemma limited_equivocators_vlsm_projection\n  : VLSM_projection equivocators_limited_equivocations_vlsm Limited\n    (equivocators_total_label_project IM) (equivocators_total_state_project IM).\nProof.\n  constructor; [constructor |]; intros ? *.\n  - intros HtrX. apply PreFreeE_Free_vlsm_projection_type.\n    revert HtrX. apply VLSM_incl_finite_valid_trace_from.\n    by apply equivocators_limited_equivocations_vlsm_incl_preloaded_free.\n  - intro HtrX.\n    assert (Hpre_tr : finite_valid_trace (pre_loaded_with_all_messages_vlsm FreeE) sX trX).\n    {\n      revert HtrX; apply VLSM_incl_finite_valid_trace.\n      by apply equivocators_limited_equivocations_vlsm_incl_preloaded_free.\n    }\n    specialize (VLSM_partial_projection_finite_valid_trace\n      (limited_equivocators_vlsm_partial_projection (zero_descriptor IM))\n       sX trX (equivocators_state_project (zero_descriptor IM) sX)\n       (equivocators_total_trace_project IM trX))\n       as Hsim.\n    spec Hsim.\n    { simpl. rewrite decide_True by apply zero_descriptor_not_equivocating.\n      by rewrite (equivocators_total_trace_project_characterization IM (proj1 Hpre_tr)).\n    }\n    apply Hsim in HtrX.\n    remember (pre_VLSM_projection_finite_trace_project _ _ _ _ _) as tr.\n    replace tr with (equivocators_total_trace_project IM trX); [done |].\n    subst. symmetry.\n    by apply (equivocators_total_VLSM_projection_finite_trace_project IM (proj1 Hpre_tr)).\nQed.\n\nEnd sec_equivocators_projection_constrained_limited.\n\nEnd sec_limited_state_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/Equivocators/LimitedStateEquivocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.15683380774496625}}
{"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.MesiInvInv0 Ex.Mesi.MesiInvInv1.\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 ObjInvNotOwned (oidx: IdxT) (ost: OState) (msgs: MessagePool Msg) :=\n  ObjInvRq oidx msgs -> ost#[owned] = false.\n\nDefinition InvNotOwned (st: State): Prop :=\n  forall oidx,\n    ost <+- (st_oss st)@[oidx]; ObjInvNotOwned oidx ost (st_msgs st).\n\nSection InvNotOwned.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma mesi_InvNotOwned_init:\n    Invariant.InvInit impl InvNotOwned.\n  Proof.\n    do 2 (red; simpl).\n    intros.\n    destruct (implOStatesInit tr)@[oidx] as [orq|] eqn:Host; simpl; auto.\n    red; intros.\n    destruct H as [idm [? ?]].\n    do 2 red in H; dest_in.\n  Qed.\n\n  Lemma mesi_InvNotOwned_ext_in:\n    forall oss orqs msgs,\n      InvNotOwned {| 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        InvNotOwned {| st_oss := oss; st_orqs := orqs; st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H2 as [idm [? ?]].\n    apply InMP_enqMsgs_or in H2.\n    destruct H2; [|apply H; do 2 red; eauto].\n    apply in_map with (f:= idOf) in H2; simpl in H2.\n    apply H1 in H2; simpl in H2.\n    exfalso; eapply DisjList_In_1.\n    - apply tree2Topo_minds_merqs_disj.\n    - eassumption.\n    - eapply tree2Topo_obj_chns_minds_SubList.\n      + specialize (H0 oidx); simpl in H0.\n        rewrite Host in H0; simpl in H0.\n        eassumption.\n      + destruct idm as [midx msg]; inv H3.\n        simpl; tauto.\n  Qed.\n\n  Lemma mesi_InvNotOwned_ext_out:\n    forall oss orqs msgs,\n      InvNotOwned {| 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        InvNotOwned {| st_oss := oss;\n                       st_orqs := orqs;\n                       st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H1 as [idm [? ?]].\n    apply InMP_deqMsgs in H1.\n    apply H; do 2 red; eauto.\n  Qed.\n\n  Lemma InvNotOwned_no_update:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (post nost: OState),\n        oss@[oidx] = Some post ->\n        nost#[owned] = post#[owned] ->\n        InvNotOwned {| st_oss:= oss +[oidx <- nost];\n                       st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    mred; simpl; auto.\n    specialize (H oidx).\n    rewrite H0 in H; simpl in H.\n    red; intros.\n    simpl; rewrite H1; auto.\n  Qed.\n\n  Lemma InvNotOwned_update_status_NoRqI_NoRsI:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (ost: OState),\n        NoRqI oidx msgs ->\n        InvNotOwned {| st_oss:= oss +[oidx <- ost];\n                       st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    mred; simpl; auto.\n    red; intros.\n    exfalso.\n    eapply MsgExistsSig_MsgsNotExist_false; [apply H0| |eassumption].\n    simpl; tauto.\n  Qed.\n\n  Lemma InvNotOwned_enqMP_rq_valid:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx ost midx msg,\n        oss@[oidx] = Some ost ->\n        ost#[owned] = false ->\n        midx = rqUpFrom oidx ->\n        msg.(msg_id) = mesiInvRq ->\n        InvNotOwned {| st_oss:= oss; st_orqs:= orqs;\n                       st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    destruct (idx_dec oidx0 oidx); subst.\n    - specialize (H oidx).\n      rewrite H0 in *; simpl in *.\n      red; intros; auto.\n    - specialize (H oidx0).\n      destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n      red; intros.\n      destruct H2 as [idm [? ?]].\n      apply InMP_enqMP_or in H2; destruct H2.\n      + dest; inv H4; rewrite H2 in H7; inv H7.\n        exfalso; auto.\n      + apply H; do 2 red; eauto.\n  Qed.\n\n  Lemma InvNotOwned_other_msg_id_enqMP:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx msg,\n        msg.(msg_id) <> mesiInvRq ->\n        InvNotOwned {| st_oss:= oss; st_orqs:= orqs;\n                       st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H1 as [idm [? ?]].\n    apply InMP_enqMP_or in H1; destruct H1.\n    - dest; subst; inv H2; exfalso; auto.\n    - apply H; do 2 red; eauto.\n  Qed.\n\n  Lemma InvNotOwned_other_msg_id_enqMsgs:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall nmsgs,\n        Forall (fun idm => (valOf idm).(msg_id) <> mesiInvWRq /\\\n                           (valOf idm).(msg_id) <> mesiInvRq /\\\n                           (valOf idm).(msg_id) <> mesiInvRs) nmsgs ->\n        InvNotOwned {| st_oss:= oss; st_orqs:= orqs;\n                       st_msgs:= enqMsgs nmsgs msgs |}.\n  Proof.\n    intros.\n    generalize dependent msgs.\n    induction nmsgs as [|[nmidx nmsg] nmsgs]; simpl; intros; auto.\n    inv H0; dest.\n    apply IHnmsgs; auto.\n    apply InvNotOwned_other_msg_id_enqMP; assumption.\n  Qed.\n\n  Lemma InvNotOwned_deqMP:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx,\n        InvNotOwned {| st_oss:= oss; st_orqs:= orqs;\n                       st_msgs:= deqMP midx msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H0 as [idm [? ?]].\n    apply InMP_deqMP in H0.\n    apply H; do 2 red; eauto.\n  Qed.\n\n  Lemma InvNotOwned_deqMsgs:\n    forall oss orqs msgs,\n      InvNotOwned {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall minds,\n        InvNotOwned {| st_oss:= oss; st_orqs:= orqs;\n                       st_msgs:= deqMsgs minds msgs |}.\n  Proof.\n    unfold InvNotOwned; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H0 as [idm [? ?]].\n    apply InMP_deqMsgs in H0.\n    apply H; do 2 red; eauto.\n  Qed.\n\n  Ltac simpl_InvNotOwned_enqMP :=\n    simpl;\n    try match goal with\n        | [H: msg_id ?rmsg = _ |- msg_id ?rmsg <> _] => rewrite H\n        end;\n    discriminate.\n\n  Ltac simpl_InvNotOwned_enqMsgs :=\n    let idm := fresh \"idm\" in\n    let Hin := fresh \"H\" in\n    apply Forall_forall; intros idm Hin;\n    apply in_map_iff in Hin; dest; subst;\n    repeat ssplit; simpl_InvNotOwned_enqMP.\n\n  Ltac simpl_InvNotOwned :=\n    repeat\n      (first [apply InvNotOwned_other_msg_id_enqMP; [|simpl_InvNotOwned_enqMP..]\n             |apply InvNotOwned_other_msg_id_enqMsgs; [|simpl_InvNotOwned_enqMsgs]\n             |apply InvNotOwned_deqMP\n             |apply InvNotOwned_deqMsgs\n             |apply InvNotOwned_update_status_NoRqI_NoRsI; [|assumption..]\n             |eapply InvNotOwned_no_update; [|eauto; fail..]\n             |assumption]).\n\n  Ltac solve_InvNotOwned :=\n    let oidx := fresh \"oidx\" in\n    red; simpl; intros oidx;\n    match goal with\n    | [Hi: InvNotOwned _ |- _] =>\n      specialize (Hi oidx); simpl in Hi;\n      mred; simpl;\n      let Hinv := fresh \"H\" in\n      intros Hinv;\n      specialize (Hi Hinv)\n    end;\n    simpl in *; try reflexivity; try solve_mesi.\n\n  Lemma mesi_InvNotOwned_step:\n    Invariant.InvStep impl step_m InvNotOwned.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) H) as Hftinv.\n    pose proof (mesi_InObjInds H) as Hioi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) H) as Hpmcf.\n    pose proof (MesiDownLockInv_ok H) as Hmdl.\n    pose proof (mesi_InvWBDir_ok H) as Hwd.\n    inv H1; [assumption\n            |apply mesi_InvNotOwned_ext_in; auto\n            |apply mesi_InvNotOwned_ext_out; auto\n            |].\n\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n\n      (** Abstract the root. *)\n      assert (In (rootOf (fst (tree2Topo tr 0)))\n                 (c_li_indices (snd (tree2Topo tr 0)))) as Hin.\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H3; destruct H3 as [crls [? ?]].\n      apply in_map_iff in H1; destruct H1 as [cidx [? ?]]; subst.\n      dest_in; disc_rule_conds_ex.\n      all: try (simpl_InvNotOwned; fail).\n      all: try (assert (NoRqI oidx msgs)\n                 by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                simpl_InvNotOwned).\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H3; destruct H3.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H3; destruct H3 as [crls [? ?]].\n        apply in_map_iff in H3; destruct H3 as [cidx [? ?]]; subst.\n        dest_in; disc_rule_conds_ex.\n\n        all: try (simpl_InvNotOwned; fail).\n        all: try (assert (NoRqI oidx msgs)\n                   by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                  simpl_InvNotOwned).\n      }\n\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvNotOwned; fail).\n      all: try (derive_footprint_info_basis oidx;\n                assert (NoRqI oidx msgs)\n                  by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx);\n                simpl_InvNotOwned).\n      all: try (simpl_InvNotOwned; solve_InvNotOwned; fail).\n      { disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvNotOwned; solve_InvNotOwned.\n        derive_InvWBDir oidx.\n        specialize (Hwd (or_intror (or_introl H24))).\n        simpl in Hwd; solve_mesi.\n      }\n      { eapply InvNotOwned_enqMP_rq_valid; eauto.\n        { solve_InvNotOwned. }\n        { mred. }\n        { assumption. }\n      }\n\n    - (*! Cases for L1 caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_l1_indices_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Register an invariant that holds only for L1 caches. *)\n      pose proof (mesi_InvL1DirI_ok H) as Hl1d.\n      red in Hl1d; simpl in Hl1d.\n      rewrite Forall_forall in Hl1d; specialize (Hl1d _ H2).\n      simpl in H5; rewrite H5 in Hl1d; simpl in Hl1d.\n\n      (** Do case analysis per a rule. *)\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvNotOwned; fail).\n      all: try (simpl_InvNotOwned; solve_InvNotOwned; fail).\n      { derive_footprint_info_basis oidx.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx).\n        simpl_InvNotOwned.\n      }\n      { derive_footprint_info_basis oidx.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n        simpl_InvNotOwned.\n      }\n      { eapply InvNotOwned_enqMP_rq_valid; eauto.\n        { solve_InvNotOwned. }\n        { mred. }\n        { assumption. }\n      }\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_InvNotOwned_ok:\n    InvReachable impl step_m InvNotOwned.\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvNotOwned_init.\n    - apply mesi_InvNotOwned_step.\n  Qed.\n\nEnd InvNotOwned.\n\nDefinition CohRsE (oidx: IdxT) (msgs: MessagePool Msg) (cv: nat) :=\n  MsgsP [((downTo oidx, (MRs, mesiRsE)),\n          (fun idm => (valOf idm).(msg_value) = cv))] msgs.\n\nDefinition ObjCohDirE (ost: OState) :=\n  ost#[owned] = false /\\\n  (mesiS <= ost#[status] \\/ ost#[dir].(dir_st) = mesiE).\n\nDefinition InvDirE (topo: DTree) (st: State): Prop :=\n  forall oidx pidx,\n    parentIdxOf topo oidx = Some pidx ->\n    ost <+- (st_oss st)@[oidx];\n      orq <+- (st_orqs st)@[oidx];\n      post <+- (st_oss st)@[pidx];\n      porq <+- (st_orqs st)@[pidx];\n      (ObjDirE porq post oidx ->\n       (CohRsE oidx (st_msgs st) post#[val] /\\\n        (NoRsME oidx (st_msgs st) ->\n         ObjCohDirE ost ->\n         post#[val] = ost#[val]))).\n\nLemma ObjDirE_ObjDirME:\n  forall orq ost cidx,\n    ObjDirE orq ost cidx -> ObjDirME orq ost cidx.\nProof.\n  intros.\n  red in H; dest.\n  red; repeat split; try assumption; solve_mesi.\nQed.\n\nSection InvDirE.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma mesi_InvDirE_init:\n    Invariant.InvInit impl (InvDirE topo).\n  Proof.\n    do 2 (red; simpl); intros.\n    destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n    destruct (implORqsInit tr)@[oidx] as [orq|] eqn:Horq; simpl; auto.\n    destruct (implOStatesInit tr)@[pidx] as [post|] eqn:Hpost; simpl; auto.\n    destruct (implORqsInit tr)@[pidx] as [porq|] eqn:Hporq; simpl; auto.\n    intros; exfalso.\n    red in H0; dest.\n    destruct (in_dec idx_dec pidx (c_li_indices cifc ++ c_l1_indices cifc)).\n    - subst cifc; rewrite c_li_indices_head_rootOf in i by assumption.\n      inv i.\n      + rewrite implOStatesInit_value_root in Hpost by assumption.\n        inv Hpost.\n        simpl in *; solve_mesi.\n      + rewrite implOStatesInit_value_non_root in Hpost by assumption.\n        inv Hpost.\n        simpl in *; solve_mesi.\n    - rewrite implOStatesInit_None in Hpost by assumption.\n      discriminate.\n  Qed.\n\n  Lemma mesi_InvDirE_ext_in:\n    forall oss orqs msgs,\n      InvDirE topo {| 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        InvDirE topo {| st_oss := oss;\n                        st_orqs := orqs;\n                        st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H _ _ H2); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct (orqs@[oidx]) as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (oss@[pidx]) as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (orqs@[pidx]) as [porq|] eqn:Hporq; simpl in *; auto.\n    intros; specialize (H H3); dest.\n    split.\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    - intros; apply MsgsP_enqMsgs_inv in H5; auto.\n  Qed.\n\n  Lemma mesi_InvDirE_ext_out:\n    forall oss orqs msgs,\n      InvDirE topo {| 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        InvDirE topo {| st_oss := oss;\n                         st_orqs := orqs;\n                         st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H _ _ H2); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct (orqs@[oidx]) as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (oss@[pidx]) as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (orqs@[pidx]) as [porq|] eqn:Hporq; simpl in *; auto.\n    intros; specialize (H H3); dest.\n    split.\n    - apply MsgsP_deqMsgs; assumption.\n    - intros; apply MsgsP_other_midx_deqMsgs_inv in H5; [auto|].\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:= 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_merss_disj.\n  Qed.\n\n  Lemma InvDirE_enqMP:\n    forall oss orqs msgs,\n      InvDirE topo {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx msg,\n        msg.(msg_id) <> mesiRsE ->\n        InvDirE topo {| st_oss:= oss; st_orqs:= orqs;\n                        st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H _ _ H1); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct (orqs@[oidx]) as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (oss@[pidx]) as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (orqs@[pidx]) as [porq|] eqn:Hporq; simpl in *; auto.\n    intros; specialize (H H2); dest.\n    split.\n    - apply MsgsP_other_msg_id_enqMP; [assumption|].\n      simpl; intro Hx; destruct Hx; auto.\n    - intros; apply MsgsP_enqMP_inv in H4; auto.\n  Qed.\n\n  Lemma InvDirE_enqMsgs:\n    forall oss orqs msgs,\n      InvDirE topo {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall nmsgs,\n        Forall (fun idm => (valOf idm).(msg_id) <> mesiRsE) nmsgs ->\n        InvDirE topo {| st_oss:= oss; st_orqs:= orqs;\n                        st_msgs:= enqMsgs nmsgs msgs |}.\n  Proof.\n    intros.\n    generalize dependent msgs.\n    induction nmsgs as [|[nmidx nmsg] nmsgs]; simpl; intros; auto.\n    inv H0.\n    apply IHnmsgs; auto.\n    apply InvDirE_enqMP; assumption.\n  Qed.\n\n  Lemma InvDirE_deqMP:\n    forall oss orqs msgs,\n      InvDirE topo {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx msg,\n        FirstMP msgs midx msg ->\n        msg.(msg_id) <> mesiRsM ->\n        msg.(msg_id) <> mesiRsE ->\n        InvDirE topo {| st_oss:= oss; st_orqs:= orqs;\n                        st_msgs:= deqMP midx msgs |}.\n  Proof.\n    unfold InvDirE; simpl; intros.\n    specialize (H _ _ H3).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct (orqs@[oidx]) as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (oss@[pidx]) as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (orqs@[pidx]) as [porq|] eqn:Hporq; simpl in *; auto.\n    intros; specialize (H H4); dest.\n    split.\n    - apply MsgsP_deqMP; assumption.\n    - intros; eapply MsgsP_other_msg_id_deqMP_inv in H6;\n        [|eassumption|simpl; intro; intuition].\n      auto.\n  Qed.\n\n  Lemma InvDirE_deqMsgs:\n    forall oss orqs msgs,\n      InvDirE topo {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall rmsgs,\n        Forall (FirstMPI msgs) rmsgs ->\n        NoDup (idsOf rmsgs) ->\n        Forall (fun idm => (valOf idm).(msg_id) <> mesiRsM /\\\n                           (valOf idm).(msg_id) <> mesiRsE) rmsgs ->\n        InvDirE topo {| st_oss:= oss; st_orqs:= orqs;\n                        st_msgs:= deqMsgs (idsOf rmsgs) msgs |}.\n  Proof.\n    unfold InvDirE; simpl; intros.\n    specialize (H _ _ H3).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    destruct (orqs@[oidx]) as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (oss@[pidx]) as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (orqs@[pidx]) as [porq|] eqn:Hporq; simpl in *; auto.\n    intros; specialize (H H4); dest.\n    split.\n    - apply MsgsP_deqMsgs; assumption.\n    - intros; eapply MsgsP_other_msg_id_deqMsgs_inv in H6; try eassumption.\n      + specialize (H5 H6 H7); dest; auto.\n      + simpl.\n        apply (DisjList_spec_1 idx_dec); intros.\n        apply in_map_iff in H8; destruct H8 as [idm [? ?]].\n        rewrite Forall_forall in H2; specialize (H2 _ H9); dest; subst.\n        intro; dest_in; auto.\n  Qed.\n\n  Ltac solve_msg :=\n    simpl;\n    try match goal with\n        | [H: msg_id ?rmsg = _ |- msg_id ?rmsg <> _] => rewrite H\n        end;\n    discriminate.\n\n  Ltac solve_enqMsgs :=\n    let idm := fresh \"idm\" in\n    let Hin := fresh \"H\" in\n    apply Forall_forall; intros idm Hin;\n    apply in_map_iff in Hin; dest; subst;\n    solve_msg.\n\n  Ltac solve_deqMsgs_NoDup :=\n    match goal with\n    | [H: ValidMsgsIn _ ?msgs |- NoDup (idsOf ?msgs)] => apply H\n    end.\n\n  Ltac solve_deqMsgs_msg_id :=\n    match goal with\n    | [H: Forall (fun _ => msg_id _ = _) ?msgs |- Forall _ ?msgs] =>\n      eapply Forall_impl; [|eapply H];\n      simpl; intros; split; solve_msg\n    end.\n\n  Ltac simpl_InvDirE_msgs :=\n    try match goal with\n        | [Hr: idsOf _ = map fst ?rss |- context [map fst ?rss] ] => rewrite <-Hr\n        end;\n    repeat\n      (first [apply InvDirE_enqMP; [|solve_msg..]\n             |apply InvDirE_enqMsgs; [|solve_enqMsgs]\n             |eapply InvDirE_deqMP; [|eassumption|solve_msg..]\n             |apply InvDirE_deqMsgs; [|eassumption\n                                      |solve_deqMsgs_NoDup\n                                      |solve_deqMsgs_msg_id]\n             |assumption]).\n\n  Ltac disc_ObjDirE :=\n    match goal with\n    | [H: ObjDirE _ _ _ |- _] =>\n      red in H; simpl in H; dest; subst\n    end.\n\n  Ltac disc_NoRsME :=\n    repeat\n      match goal with\n      | [H: ValidMsgsIn _ _ |- _] => destruct H\n      | [H: ValidMsgsOut _ _ |- _] => destruct H\n      end;\n    repeat\n      match goal with\n      | [H: NoRsME _ _ |- _] => disc_MsgsP H\n      | [Hi: NoRsME _ ?msgs -> _ /\\ _,  Hm: MsgsP _ ?msgs |- _] =>\n        specialize (Hi Hm); dest\n      end.\n\n  Ltac disc :=\n    repeat\n      match goal with\n      | [Hi: InvDirE _ _ |- InvDirE _ _] =>\n        let Hp := fresh \"H\" in\n        red; simpl; intros ? ? Hp;\n        specialize (Hi _ _ Hp); simpl in Hi;\n        mred; simpl;\n        try (exfalso; eapply parentIdxOf_not_eq; subst topo; eauto; fail)\n      | |- _ <+- _; _ => disc_bind_true\n      | |- _ -> _ => intros\n      | [Hi: ObjDirE _ _ _ -> _, Ho: ObjDirE _ _ _ |- _] =>\n        specialize (Hi Ho); dest\n      | [Hi: NoRsME _ _ -> _, Hm: NoRsME _ _ |- _] =>\n        specialize (Hi Hm)\n      | [Hi: ObjCohDirE ?ost -> _, Hm: ObjCohDirE ?ost |- _] =>\n        specialize (Hi Hm)\n      | [H: ?t = ?t -> _ |- _] => specialize (H eq_refl); dest\n      end.\n\n  Ltac solve_by_diff_dir :=\n    intros;\n    match goal with\n    | [Hn: ObjDirE _ _ _ |- _] =>\n      red in Hn; dest; simpl in *; solve_mesi\n    end.\n\n  Ltac solve_by_idx_false :=\n    intros; subst topo; congruence.\n\n  Ltac solve_by_NoRsME_false :=\n    exfalso;\n    match goal with\n    | [Hn: NoRsME _ (enqMP ?midx ?msg ?msgs) |- _] =>\n      specialize (Hn (midx, msg)\n                     (InMP_or_enqMP\n                        msgs (or_introl (conj eq_refl eq_refl))));\n      red in Hn; unfold map in Hn;\n      disc_caseDec Hn; auto\n    end.\n\n  Ltac solve_ObjCohDirE :=\n    try assumption;\n    match goal with\n    | [H: ObjCohDirE _ |- _] =>\n      red in H; dest; red; simpl in *\n    end;\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    intuition solve_mesi.\n\n  Ltac solve_coh :=\n    intros;\n    match goal with\n    | [H: _ -> _ -> fst ?lv = fst ?rv |- fst ?lv = fst ?rv] =>\n      apply H; [disc_NoRsME; assumption|solve_ObjCohDirE]\n    end.\n\n  Ltac solve_by_ObjCohDirE_false :=\n    intros;\n    try match goal with\n        | [H: context [invalidate ?st] |- _] =>\n          pose proof (invalidate_sound st)\n        | |- context [invalidate ?st] =>\n          pose proof (invalidate_sound st)\n        end;\n    match goal with\n    | [H: ObjCohDirE _ |- _] =>\n      red in H; simpl in *; dest; solve [congruence|solve_mesi]\n    end.\n\n  Ltac solve_valid :=\n    split; [solve_MsgsP|solve_coh].\n\n  Ltac solve_by_child_downlock_to_parent oidx :=\n    exfalso;\n    disc_MsgConflictsInv oidx;\n    match goal with\n    | [Hp: ParentLockFreeConflicts oidx ?porq ?orq,\n           Ho: ?orq@[downRq] = None,\n               Hpo: ?porq@[downRq] = Some _ |- _] =>\n      specialize (Hp Ho); rewrite Hpo in Hp;\n      simpl in Hp; auto\n    end.\n\n  Ltac solve_by_NoRsSI_false :=\n    exfalso;\n    match goal with\n    | [Hn: NoRsSI _ ?msgs, Hf: FirstMPI ?msgs (?midx, ?msg) |- _] =>\n      specialize (Hn (midx, msg) (FirstMP_InMP Hf));\n      solve_MsgsP_false Hn;\n      auto\n    end.\n\n  Lemma mesi_InvDirE_step:\n    Invariant.InvStep impl step_m (InvDirE topo).\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\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 (mesi_InvWBDir_ok H) as Hwd.\n    pose proof (MesiDownLockInv_ok H) as Hmdl.\n    pose proof (mesi_InvL1DirI_ok H) as Hl1d.\n    pose proof (mesi_InvDirME_ok H) as Hdme.\n    inv H1; [assumption\n            |apply mesi_InvDirE_ext_in; auto\n            |apply mesi_InvDirE_ext_out; auto\n            |].\n\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n\n      (** Abstract the root. *)\n      assert (In (rootOf (fst (tree2Topo tr 0)))\n                 (c_li_indices (snd (tree2Topo tr 0)))) as Hin.\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H3; destruct H3 as [crls [? ?]].\n      apply in_map_iff in H1; destruct H1 as [cidx [? ?]]; subst.\n\n      (** Derive that the child has the parent. *)\n      assert (parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx)\n        by (apply subtreeChildrenIndsOf_parentIdxOf; auto).\n\n      dest_in.\n\n      { (* [liGetSImmME] *)\n        disc_rule_conds_ex; disc.\n        { solve_valid. }\n        { disc_ObjDirE.\n          split; intros.\n          { apply MsgsP_enqMP.\n            { derive_child_idx_in oidx0.\n              disc_MsgConflictsInv oidx0.\n              apply MsgsNotExist_MsgsP; simpl.\n              apply MsgsP_deqMP.\n              solve_MsgsNotExist_base.\n              solve_RsDown_by_rqUp oidx0.\n            }\n            { red; unfold map.\n              rewrite caseDec_head_eq by reflexivity.\n              reflexivity.\n            }\n          }\n          { solve_by_NoRsME_false. }\n        }\n        { destruct (idx_dec cidx oidx0); subst.\n          { solve_by_idx_false. }\n          { solve_valid. }\n        }\n      }\n\n      { (* [liGetMImm] *)\n        disc_rule_conds_ex; disc.\n        { solve_valid. }\n        { solve_by_diff_dir. }\n        { destruct (idx_dec cidx oidx0); subst.\n          { solve_by_idx_false. }\n          { solve_valid. }\n        }\n      }\n\n      { (* [liInvImmE] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|disc_getDir; solve_coh]. }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liInvImmWBME] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n      }\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H3; destruct H3.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H3; destruct H3 as [crls [? ?]].\n        apply in_map_iff in H3; destruct H3 as [cidx [? ?]]; subst.\n\n        (** Derive that the child has the parent. *)\n        assert (parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx)\n          by (apply subtreeChildrenIndsOf_parentIdxOf; auto).\n\n        dest_in.\n\n        { (* [liGetSImmS] *)\n          disc_rule_conds_ex; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n          { destruct (idx_dec cidx oidx0); subst.\n            { solve_by_idx_false. }\n            { solve_valid. }\n          }\n        }\n\n        { (* [liGetSImmME] *)\n          disc_rule_conds_ex; disc.\n          { solve_valid. }\n          { disc_ObjDirE.\n            split; intros.\n            { apply MsgsP_enqMP.\n              { derive_child_idx_in oidx0.\n                disc_MsgConflictsInv oidx0.\n                apply MsgsNotExist_MsgsP; simpl.\n                apply MsgsP_deqMP.\n                solve_MsgsNotExist_base.\n                solve_RsDown_by_rqUp oidx0.\n              }\n              { red; unfold map.\n                rewrite caseDec_head_eq by reflexivity.\n                reflexivity.\n              }\n            }\n            { solve_by_NoRsME_false. }\n          }\n          { destruct (idx_dec cidx oidx0); subst.\n            { solve_by_idx_false. }\n            { solve_valid. }\n          }\n        }\n\n        { (* [liGetSRqUpUp] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs.\n          disc; red in H18; mred.\n          specialize (H0 H18); dest.\n          solve_valid.\n        }\n\n        { (* [liGetSRqUpDownME] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          disc_ObjDirE; mred.\n        }\n\n        { (* [liGetMImm] *)\n          disc_rule_conds_ex; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n          { destruct (idx_dec cidx oidx0); subst.\n            { solve_by_idx_false. }\n            { solve_valid. }\n          }\n        }\n\n        { (* [liGetMRqUpUp] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs.\n          disc; red in H18; mred.\n          specialize (H0 H18); dest.\n          solve_valid.\n        }\n\n        { (* [liGetMRqUpDownME] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          disc_ObjDirE; mred.\n        }\n        { (* [liGetMRqUpDownS] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          disc_ObjDirE; mred.\n        }\n\n        { (* [liInvImmI] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        }\n\n        { (* [liInvImmS00] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmS01] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmS1] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmE] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { split; [solve_MsgsP|disc_getDir; solve_coh]. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmWBI] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        }\n\n        { (* [liInvImmWBS0] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmWBS1] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { solve_valid. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmWBS] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n          { solve_by_diff_dir. }\n        }\n\n        { (* [liInvImmWBME] *)\n          disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n          { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n          { solve_by_diff_dir. }\n        }\n      }\n\n      dest_in.\n\n      { (* [liGetSRsDownDownS] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|].\n\n          subst topo; disc_rule_conds_ex.\n          intros.\n\n          (** TODO: make an Ltac [disc_InvDirME] .. *)\n          move Hdme at bottom.\n          red in Hdme; simpl in Hdme.\n          specialize (Hdme _ _ H4).\n          disc_rule_conds_ex.\n          disc_NoRsME.\n          specialize (Hdme (ObjDirE_ObjDirME H29)).\n          specialize (Hdme H31); dest.\n\n          solve_by_NoRsSI_false.\n        }\n        { solve_by_diff_dir. }\n        { destruct (idx_dec cidx oidx0); subst.\n          { solve_by_idx_false. }\n          { solve_valid. }\n        }\n      }\n\n      { (* [liGetSRsDownDownE] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|].\n          (* pulling a coherence value from the [mesiRsE] message. *)\n          intros.\n          move H0 at bottom.\n          specialize (H0 _ (FirstMP_InMP H21)).\n          red in H0.\n          unfold map in H0.\n          rewrite caseDec_head_eq in H0 by (unfold sigOf; simpl; congruence).\n          auto.\n        }\n        { disc_ObjDirE.\n          split; intros.\n          { apply MsgsP_enqMP.\n            { derive_child_idx_in oidx0.\n              disc_MsgConflictsInv oidx0.\n              apply MsgsNotExist_MsgsP; simpl.\n              apply MsgsP_deqMP.\n              solve_MsgsNotExist_base.\n              solve_RsDown_by_parent_lock oidx0.\n            }\n            { red; unfold map.\n              rewrite caseDec_head_eq by reflexivity.\n              reflexivity.\n            }\n          }\n          { solve_by_NoRsME_false. }\n        }\n        { destruct (idx_dec cidx oidx0); subst.\n          { solve_by_idx_false. }\n          { solve_valid. }\n        }\n      }\n\n      { (* [liDownSRsUpDownME] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liDownSImm] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { (* [liDownSRqDownDownME] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; mred.\n      }\n\n      { (* [liDownSRsUpUp] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { disc_ObjDirE.\n          remember (dir_excl _) as oidx; clear Heqoidx.\n          disc_MsgConflictsInv oidx.\n\n          solve_by_child_downlock_to_parent oidx.\n        }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liGetMRsDownDownDirI] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n        { destruct (idx_dec cidx oidx0); subst.\n          { solve_by_idx_false. }\n          { solve_valid. }\n        }\n      }\n\n      { (* [liGetMRsDownRqDownDirS] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n        { solve_valid. }\n      }\n\n      { (* [liDownIRsUpDownS] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { solve_valid. }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liDownIRsUpDownME] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { solve_valid. }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liDownIImmS] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { (* [liDownIImmME] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { (* [liDownIRqDownDownDirS] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; mred.\n      }\n      { (* [liDownIRqDownDownDirME] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; mred.\n      }\n      { (* [liDownIRqDownDownDirMES] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; mred.\n      }\n\n      { (* [liDownIRsUpUpS] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { subst topo; disc_rule_conds_ex.\n          disc_ObjDirE.\n          remember (dir_excl _) as oidx; clear Heqoidx.\n          disc_MsgConflictsInv oidx.\n          solve_by_child_downlock_to_parent oidx.\n        }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liDownIRsUpUpME] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { subst topo; disc_rule_conds_ex.\n          disc_ObjDirE.\n          remember (dir_excl _) as oidx; clear Heqoidx.\n          disc_MsgConflictsInv oidx.\n          solve_by_child_downlock_to_parent oidx.\n        }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liDownIRsUpUpMES] *)\n        disc_rule_conds_ex.\n        disc_MesiDownLockInv oidx Hmdl.\n        simpl_InvDirE_msgs; disc.\n        { subst topo; disc_rule_conds_ex.\n          disc_ObjDirE.\n          remember (dir_excl _) as oidx; clear Heqoidx.\n          disc_MsgConflictsInv oidx.\n          solve_by_child_downlock_to_parent oidx.\n        }\n        { solve_by_diff_dir. }\n      }\n\n      { (* [liInvRqUpUp] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; solve_mesi.\n      }\n\n      { (* [liInvRqUpUpWB] *)\n        disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; solve_mesi.\n      }\n\n      { (* [liInvRsDownDown] *)\n        disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_InvWBDir oidx.\n        assert (ObjInvRs oidx msgs) as Hirs.\n        { do 2 red.\n          eexists; split; [apply FirstMP_InMP; eassumption|].\n          unfold sigOf; simpl; congruence.\n        }\n        specialize (Hwd (or_intror (or_intror Hirs))); clear Hirs.\n\n        simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { disc_ObjDirE; solve_mesi. }\n      }\n\n      { (* [liDropImm] *)\n        disc_rule_conds_ex; disc; solve_valid.\n      }\n\n    - (*! Cases for L1 caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n\n      pose proof (c_l1_indices_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Discharge an invariant that holds only for L1 caches. *)\n      red in Hl1d; simpl in Hl1d.\n      rewrite Forall_forall in Hl1d; specialize (Hl1d _ H2).\n      simpl in H5; rewrite H5 in Hl1d; simpl in Hl1d.\n\n      (** Do case analysis per a rule. *)\n      dest_in.\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc. }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        red in H16; mred; specialize (H0 H16); dest.\n        solve_valid.\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|].\n\n          subst topo; disc_rule_conds_ex.\n          intros.\n\n          (** TODO: make an Ltac [disc_InvDirME] .. *)\n          move Hdme at bottom.\n          red in Hdme; simpl in Hdme.\n          specialize (Hdme _ _ H4).\n          disc_rule_conds_ex.\n          specialize (Hdme (ObjDirE_ObjDirME H28)).\n          specialize (Hdme H30); dest.\n\n          solve_by_NoRsSI_false.\n        }\n        { solve_by_diff_dir. }\n      }\n\n      { disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|].\n          (* pulling a coherence value from the [mesiRsE] message. *)\n          intros.\n          move H0 at bottom.\n          specialize (H0 _ (FirstMP_InMP H21)).\n          red in H0.\n          unfold map in H0.\n          rewrite caseDec_head_eq in H0 by (unfold sigOf; simpl; congruence).\n          auto.\n        }\n        { disc_ObjDirE; solve_mesi. }\n        { destruct (idx_dec (l1ExtOf oidx) oidx0); subst.\n          { exfalso.\n            subst topo.\n            rewrite tree2Topo_l1_ext_parent in H3 by assumption.\n            congruence.\n          }\n          { solve_valid. }\n        }\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs.\n        disc; red in H16; mred.\n        specialize (H0 H16); dest.\n        solve_valid.\n      }\n\n      { disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n        disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { solve_by_diff_dir. }\n        { destruct (idx_dec (l1ExtOf oidx) oidx0); subst.\n          { exfalso.\n            subst topo.\n            rewrite tree2Topo_l1_ext_parent in H3 by assumption.\n            congruence.\n          }\n          { solve_valid. }\n        }\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        exfalso.\n        subst topo; disc_rule_conds_ex.\n        disc_ObjDirE.\n        remember (dir_excl _) as oidx; clear Heqoidx.\n        derive_parent_downlock_by_RqDown oidx.\n        auto.\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; solve_mesi.\n      }\n\n      { disc_rule_conds_ex; simpl_InvDirE_msgs; disc.\n        disc_ObjDirE; solve_mesi.\n      }\n\n      { disc_rule_conds_ex.\n        derive_footprint_info_basis oidx.\n        derive_InvWBDir oidx.\n        assert (ObjInvRs oidx msgs) as Hirs.\n        { do 2 red.\n          eexists; split; [apply FirstMP_InMP; eassumption|].\n          unfold sigOf; simpl; congruence.\n        }\n        specialize (Hwd (or_intror (or_intror Hirs))); clear Hirs.\n\n        simpl_InvDirE_msgs; disc.\n        { split; [solve_MsgsP|solve_by_ObjCohDirE_false]. }\n        { disc_ObjDirE; solve_mesi. }\n      }\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_InvDirE_ok:\n    InvReachable impl step_m (InvDirE topo).\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvDirE_init.\n    - apply mesi_InvDirE_step.\n  Qed.\n\nEnd InvDirE.\n\nDefinition InvNWB (topo: DTree) (st: State): Prop :=\n  forall oidx pidx,\n    parentIdxOf topo oidx = Some pidx ->\n    ost <+- (st_oss st)@[oidx];\n      orq <+- (st_orqs st)@[oidx];\n      post <+- (st_oss st)@[pidx];\n      porq <+- (st_orqs st)@[pidx];\n      (ObjDirE porq post oidx ->\n       ObjInvRq oidx (st_msgs st) ->\n       NoRsI oidx (st_msgs st) /\\ mesiS <= ost#[status] /\\\n       ost#[val] = post#[val]).\n\nSection InvNWB.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Theorem mesi_InvNWB_ok:\n    InvReachable impl step_m (InvNWB topo).\n  Proof.\n    red; intros.\n    pose proof (mesi_InObjInds H) as Hoin.\n    pose proof (mesi_MsgConflictsInv (@mesi_RootChnInv_ok _ Htr) H) as Hmcf.\n    pose proof (mesi_InvDirME_ok H) as Hdme.\n    pose proof (mesi_InvNotOwned_ok H) as Hno.\n    pose proof (mesi_InvDirE_ok H) as Hde.\n    pose proof (mesi_InvWBDir_ok H) as Hwd.\n\n    red; intros.\n    specialize (Hoin oidx).\n    specialize (Hmcf oidx).\n    specialize (Hdme _ _ H0).\n    specialize (Hno oidx).\n    specialize (Hde _ _ H0).\n    specialize (Hwd oidx).\n\n    destruct (st_oss ist)@[oidx] as [ost|] eqn:Host; simpl in *; auto.\n    destruct (st_orqs ist)@[oidx] as [orq|] eqn:Horq; simpl in *; auto.\n    destruct (st_oss ist)@[pidx] as [post|] eqn:Hpost; simpl in *; auto.\n    destruct (st_orqs ist)@[pidx] as [porq|] eqn:Hporq; simpl in *; auto.\n\n    specialize (Hmcf _ Hoin eq_refl); dest.\n    intros.\n    specialize (Hwd (or_intror (or_introl H7))).\n    specialize (Hno H7).\n    specialize (Hde H6).\n    destruct Hde as [_ Hde].\n    specialize (Hdme (ObjDirE_ObjDirME H6)).\n\n    assert (NoRsME oidx (st_msgs ist)) as Hnrs.\n    { destruct H7 as [[rqUp rqm] ?]; dest; inv H8.\n      apply not_MsgExistsSig_MsgsNotExist.\n      intros; dest_in.\n      { destruct H9 as [[rsDown rsm] ?]; dest; inv H9.\n        specialize (H2 (rqUpFrom oidx, rqm) eq_refl H7); dest.\n        eapply H10 with (rsDown:= (downTo oidx, rsm)); eauto.\n      }\n      { destruct H9 as [[rsDown rsm] ?]; dest; inv H9.\n        specialize (H2 (rqUpFrom oidx, rqm) eq_refl H7); dest.\n        eapply H10 with (rsDown:= (downTo oidx, rsm)); eauto.\n      }\n    }\n\n    specialize (Hdme Hnrs); destruct Hdme as [Hnrsi Hdme].\n\n    assert (mesiS <= ost#[status]) as Hs.\n    { specialize (Hdme ltac:(solve_mesi)).\n      destruct Hdme; dest; simpl in *; solve_mesi.\n    }\n\n    assert (ObjCohDirE ost) as Hode.\n    { split; [assumption|left; assumption]. }\n    specialize (Hde Hnrs Hode).\n\n    repeat split.\n    - clear -Hnrsi.\n      do 3 red; intros.\n      specialize (Hnrsi _ H).\n      red in Hnrsi.\n      rewrite map_trans in Hnrsi; do 2 rewrite map_cons in Hnrsi.\n      red in Hnrsi.\n      do 2 (destruct (sig_dec _ _); [exfalso; auto|]).\n      clear Hnrsi.\n      red.\n      rewrite map_trans, map_cons.\n      rewrite caseDec_head_neq by assumption.\n      simpl; auto.\n    - assumption.\n    - apply eq_sym; assumption.\n  Qed.\n\nEnd InvNWB.\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/MesiInvInv2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.29098086006635987, "lm_q1q2_score": 0.15683380111703898}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\n\n\n(**\nCheck is_well_dst.\nis_well_dst\n     : int64 -> M bool\n*)\n\nSection Is_well_dst.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(int64:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := is_well_dst.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_is_well_dst.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (int64_correct x))\n        (DList.DNil _).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x  => StateLess _ (bool_correct x).\n\n  Instance correct_function_is_well_dst : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f. unfold is_well_dst.\n    correct_forward.\n\n    get_invariant _i.\n    unfold eval_inv, int64_correct in c0.\n    subst.\n\n    eexists.\n\n    split_and; auto.\n    {\n      unfold exec_expr. repeat\n      match goal with\n      | H: ?X = _ |- context [match ?X with _ => _ end] =>\n        rewrite H\n      end. simpl.\n      unfold Cop.sem_shr, Cop.sem_shift; simpl.\n      change Int64.iwordsize with (Int64.repr 64).\n      change (Int64.ltu (Int64.repr 8) (Int64.repr 64)) with true; simpl.\n      unfold Cop.sem_cmp; simpl.\n      unfold Cop.sem_binarith; simpl.\n      unfold Val.of_bool; simpl.\n      unfold Vtrue, Vfalse.\n      reflexivity.\n    }\n\n    unfold eval_inv, match_res, state.is_well_dst'.\n    unfold bool_correct, Val.of_bool, BinrBPF.get_dst.\n    unfold Int.cmpu.\n    destruct negb; reflexivity.\n    unfold Cop.sem_cast; simpl.\n    destruct negb; reflexivity.\n    intros.\n    destruct negb; constructor; reflexivity.\n  Qed.\n\nEnd Is_well_dst.\n\nExisting  Instance correct_function_is_well_dst.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_is_well_dst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3040416812727289, "lm_q1q2_score": 0.15676994607412847}}
{"text": "From RecordUpdate Require Import RecordSet.\nFrom Perennial.Helpers Require Import Map.\n\nFrom Perennial.program_logic Require Export weakestpre post_expr.\nFrom Perennial.goose_lang Require Import crash_modality.\nFrom Perennial.goose_lang Require Import proofmode wpc_proofmode notation crash_borrow.\nFrom Perennial.base_logic Require Import lib.ghost_map.\n\nFrom Goose.github_com.mit_pdos.perennial_examples Require Import alloc.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.program_proof.examples Require Import alloc_addrset.\n\nSection goose.\nContext `{!heapGS \u03a3}.\n\nLet allocN := nroot.@\"allocator\".\n\nImplicit Types (a: u64) (m: gmap u64 ()) (free: gset u64).\nImplicit Types (P: gset u64 \u2192 iProp \u03a3).\nImplicit Types (l:loc).\n\nDefinition allocator_linv P (mref: loc) free : iProp \u03a3 :=\n  \"Hfreemap\" \u2237 is_addrset mref (free) \u2217\n  \"HP\" \u2237 P free\n.\n\nDefinition is_allocator (l: loc) P : iProp \u03a3 :=\n  \u2203 (lref mref: loc),\n    \"#Hsplit\" \u2237 \u25a1 (\u2200 \u03c31 \u03c32, \u231c \u03c31 ## \u03c32 \u231d \u2192 P (\u03c31 \u222a \u03c32) -\u2217 post_expr \u2205 (P \u03c31 \u2217 P \u03c32)) \u2217\n    \"#Hjoin\" \u2237 \u25a1 (\u2200 \u03c31 \u03c32, P \u03c31 -\u2217 P \u03c32 -\u2217 post_expr \u2205 (P (\u03c31 \u222a \u03c32))) \u2217\n    \"#m\" \u2237 readonly (l \u21a6[Allocator :: \"m\"] #lref) \u2217\n    \"#free\" \u2237 readonly (l \u21a6[Allocator :: \"free\"] #mref) \u2217\n    \"#His_lock\" \u2237 is_lock allocN #lref (\u2203 \u03c3, \"Hlockinv\" \u2237 allocator_linv P mref \u03c3)\n.\n\nGlobal Instance is_allocator_Persistent l P :\n  Persistent (is_allocator l P).\nProof. apply _. Qed.\n\nTheorem wp_newAllocator mref (start sz: u64) used P E :\n  int.Z start + int.Z sz < 2^64 \u2192\n  {{{\n       \u25a1 (\u2200 \u03c31 \u03c32, \u231c \u03c31 ## \u03c32 \u231d \u2192 P (\u03c31 \u222a \u03c32) -\u2217 post_expr \u2205 (P \u03c31 \u2217 P \u03c32)) \u2217\n       \u25a1 (\u2200 \u03c31 \u03c32, P \u03c31 -\u2217 P \u03c32 -\u2217 post_expr \u2205 (P (\u03c31 \u222a \u03c32))) \u2217\n       is_addrset mref used \u2217\n      let \u03c30 := (rangeSet (int.Z start) (int.Z sz)) \u2216 used in\n       \u25b7 P \u03c30 }}}\n    New #start #sz #mref @ E\n  {{{ l, RET #l; is_allocator l P }}}.\nProof.\n  iIntros (Hoverflow \u03a6) \"(#Hsplit&#Hjoin&Hused&HP) H\u03a6\".\n  wp_call.\n  wp_apply wp_freeRange; first by auto.\n  iIntros (mref') \"Hfree\".\n  wp_pures.\n  wp_apply (wp_mapRemove with \"[$Hfree $Hused]\"); iIntros \"(Hfree & Hused)\".\n  wp_apply wp_new_free_lock.\n  iIntros (lk) \"Hlock\".\n  rewrite -wp_fupd.\n  wp_apply wp_allocStruct; auto.\n  iIntros (l) \"Hallocator\".\n  iDestruct (struct_fields_split with \"Hallocator\") as \"(m&free&_)\".\n  iMod (readonly_alloc_1 with \"m\") as \"#m\".\n  iMod (readonly_alloc_1 with \"free\") as \"#free\".\n  iMod (alloc_lock allocN E _\n                   (\u2203 \u03c3, \"Hlockinv\" \u2237 allocator_linv P mref' \u03c3)%I\n          with \"[$Hlock] [-H\u03a6]\") as \"#Hlock\".\n  { iExists _; iFrame. }\n  iModIntro.\n  iApply (\"H\u03a6\" $! _).\n  iExists _, _; iFrame \"#\".\nQed.\n\nLemma map_empty_difference `{Countable K} {V} (m: gmap K V) :\n  \u2205 \u2216 m = \u2205.\nProof.\n  apply map_eq; intros.\n  rewrite lookup_difference_None; eauto.\nQed.\n\nLemma set_empty_difference `{Countable K} (m: gset K) :\n  \u2205 \u2216 m = \u2205.\nProof.\n  clear.\n  set_solver.\nQed.\n\nTheorem wp_Reserve l P :\n  {{{ is_allocator l P }}}\n    Allocator__Reserve #l\n  {{{ a (ok: bool), RET (#a, #ok);\n      if ok then P {[a]} else True%I }}}.\nProof.\n  clear.\n  iIntros (\u03a6) \"Hinv H\u03a6\"; iNamed \"Hinv\".\n  wp_call.\n  wp_loadField.\n  wp_apply (acquire_spec with \"His_lock\").\n  iIntros \"(His_locked & Hinner)\"; iNamed \"Hinner\".\n  iNamed \"Hlockinv\".\n  wp_loadField.\n  wp_apply (wp_findKey with \"Hfreemap\").\n  iIntros (k ok) \"[%Hk Hfreemap]\".\n  wp_pures.\n  wp_loadField.\n  iDestruct \"Hfreemap\" as (m') \"[Hfreemap %Hdom]\".\n  wp_apply (wp_MapDelete with \"Hfreemap\"); iIntros \"Hfreemap\".\n  wp_pures.\n  wp_bind (struct.loadF _ _ _).\n  destruct ok.\n  - assert (\u03c3 = (\u03c3 \u2216 {[k]}) \u222a {[k]}) as ->.\n    { rewrite difference_union_L. set_solver. }\n    iDestruct (\"Hsplit\" with \"[] HP\") as \"Hpost\".\n    { iPureIntro. set_solver. }\n    iApply (wpc_wp NotStuck _ _ _ True).\n    iApply (post_expr_elim with \"Hpost\"); first set_solver+; auto.\n    iApply wp_wpc.\n    wp_loadField.\n    iIntros \"(HP&Hk)\".\n    wp_apply (release_spec with \"[-H\u03a6 Hk $His_lock $His_locked]\").\n    { iNext. iExists _; iFrame.\n      iExists _. iFrame. rewrite /map_del dom_delete_L. iPureIntro; congruence. }\n    wp_pures.\n    iApply \"H\u03a6\"; by iFrame.\n  - wp_loadField.\n    wp_apply (release_spec with \"[-H\u03a6 $His_lock $His_locked]\").\n    { iNext. iExists _; iFrame.\n      iExists _. iFrame. rewrite /map_del dom_delete_L. subst.\n      iPureIntro. rewrite Hdom. set_solver. }\n    wp_pures.\n    iApply \"H\u03a6\"; by iFrame.\nQed.\n\nLemma gset_difference_difference `{Countable K} (A B C: gset K) :\n  C \u2286 A \u2192\n  A \u2216 (B \u2216 C) = A \u2216 B \u222a C.\nProof using.\n  clear.\n  intros.\n  apply set_eq; intros k.\n  rewrite !elem_of_difference.\n  intuition.\n  - destruct (decide (k \u2208 C)); set_solver.\n  - set_solver.\n  - set_solver.\nQed.\n\nTheorem wp_Free P l (a: u64) :\n  {{{ is_allocator l P \u2217 P {[a]} }}}\n    Allocator__Free #l #a\n  {{{ RET #(); True }}}.\nProof.\n  iIntros (\u03a6) \"(Halloc&Ha) H\u03a6\"; iNamed \"Halloc\".\n  wp_call.\n  wp_loadField.\n  wp_apply (acquire_spec with \"His_lock\").\n  iIntros \"(Hlocked&Hinv)\"; iNamed \"Hinv\".\n  iNamed \"Hlockinv\".\n  wp_loadField.\n  iDestruct \"Hfreemap\" as (m) \"[Hfreemap %Hdom]\".\n  wp_apply (wp_MapInsert _ _ _ _ () with \"Hfreemap\"); first by auto.\n  iIntros \"Hfreemap\".\n  iAssert (is_addrset mref (\u03c3 \u222a {[a]})) with \"[Hfreemap]\" as \"Hfreemap\".\n  { iExists _; iFrame.\n    iPureIntro.\n    rewrite /map_insert dom_insert_L.\n    set_solver. }\n  wp_pures.\n  wp_bind (struct.loadF _ _ _).\n  iDestruct (\"Hjoin\" with \"HP [$]\") as \"Hpost\".\n  iApply (wpc_wp NotStuck _ _ _ True).\n  iApply (post_expr_elim with \"Hpost\"); first set_solver+; auto.\n  iApply wp_wpc.\n  wp_loadField.\n  iIntros \"HP\".\n  wp_apply (release_spec with \"[$His_lock $Hlocked Hfreemap HP]\").\n  { iExists _; iFrame \"HP\". eauto. }\n  wp_pures.\n  iApply (\"H\u03a6\" with \"[$]\").\nQed.\n\nEnd goose.\n\nOpaque crash_borrow.\n\nSection crash.\nContext `{!heapGS \u03a3}.\nContext `{!stagedG \u03a3}.\n\nImplicit Types (a: u64) (m: gmap u64 ()) (free: gset u64).\nImplicit Types (P: gset u64 \u2192 iProp \u03a3).\nImplicit Types (l:loc).\n\nDefinition valid_allocPred (P Pc: gset u64 \u2192 iProp \u03a3) : iProp \u03a3 :=\n  (* Splitting/joining of P *)\n  \u25a1 (\u2200 \u03c31 \u03c32, \u231c \u03c31 ## \u03c32 \u231d \u2192 P (\u03c31 \u222a \u03c32) -\u2217 (P \u03c31 \u2217 P \u03c32)) \u2217\n  \u25a1 (\u2200 \u03c31 \u03c32, P \u03c31 -\u2217 P \u03c32 -\u2217 \u231c \u03c31 ## \u03c32 \u231d \u2227 (P (\u03c31 \u222a \u03c32))) \u2217\n  (* Splitting/joining of Pc *)\n  \u25a1 (\u2200 \u03c31 \u03c32, \u231c \u03c31 ## \u03c32 \u231d \u2192 Pc (\u03c31 \u222a \u03c32) -\u2217 (Pc \u03c31 \u2217 Pc \u03c32)) \u2217\n  \u25a1 (\u2200 \u03c31 \u03c32, Pc \u03c31 -\u2217 Pc \u03c32 -\u2217 (Pc (\u03c31 \u222a \u03c32))) \u2217\n  (* P must imply Pc *)\n  \u25a1 (\u2200 \u03c3, P \u03c3 -\u2217 Pc \u03c3).\n\nDefinition is_crash_allocator l P Pc :=\n  is_allocator l (\u03bb \u03c3, crash_borrow (P \u03c3) (Pc \u03c3)).\n\nTheorem wpc_newAllocator \u03a6 \u03a6c (mref : loc) (start sz: u64) used P Pc K `{!LanguageCtx K} :\n  int.Z start + int.Z sz < 2^64 \u2192\n  let \u03c3 := (rangeSet (int.Z start) (int.Z sz)) \u2216 used in\n  valid_allocPred P Pc -\u2217\n  P \u03c3 -\u2217\n  is_addrset mref used -\u2217\n  \u03a6c \u2227 (\u2200 l, is_crash_allocator l P Pc -\u2217\n     WPC (K (of_val #l)) @ \u22a4 {{ \u03a6 }} {{ \u03a6c }}) -\u2217\n  WPC (K (New #start #sz #mref)) @ \u22a4 {{ \u03a6 }} {{ \u03a6c \u2217 Pc \u03c3 }}.\nProof.\n  iIntros (Hbound) \"#Hvalid HP Haddr HK\".\n  iApply (wpc_crash_borrow_init_ctx' _ _ _ _ (P _) (Pc _) with \"[HP]\"); auto.\n  { iDestruct \"Hvalid\" as \"(?&?&?&?&Himp)\". by iApply \"Himp\". }\n  iSplit.\n  { iLeft in \"HK\". eauto. }\n  iIntros \"Hcb\".\n  iCache with \"HK\".\n  { by iLeft in \"HK\". }\n  wpc_frame.\n  wp_apply (wp_newAllocator _ _ _ used (\u03bb \u03c3, crash_borrow (P \u03c3) (Pc \u03c3)) with \"[$Hcb $Haddr]\").\n  { auto. }\n  { iDestruct \"Hvalid\" as \"(Hsplit1&Hjoin1&Hsplit2&Hjoin2&Himp)\". iSplit.\n    - iModIntro. iIntros (?? Hdisj) \"H\".\n      iApply (crash_borrow_split_post with \"H\").\n      { iApply \"Hsplit1\". eauto. }\n      { iApply \"Himp\". }\n      { iApply \"Himp\". }\n      { iNext. iIntros \"(H1&?)\". iApply (\"Hjoin2\" with \"H1 [$]\"). }\n    - iModIntro. iIntros (??) \"H1 H2\".\n      iApply (crash_borrow_combine_post' with \"H1 H2\").\n      {\n        iNext. iIntros \"(HP1&HP2)\". iDestruct (\"Hjoin1\" with \"HP1 [$]\") as \"(%Hdisj&HP)\".\n        iModIntro. iFrame.\n        iSplit.\n        * iIntros. iApply \"Hsplit2\"; auto.\n        * iApply \"Himp\".\n      }\n  }\n  iIntros (l) \"Halloc HK\".\n  iApply \"HK\".\n  iFrame.\nQed.\n\nTheorem wp_crash_Reserve l P Pc :\n  {{{ is_crash_allocator l P Pc }}}\n    Allocator__Reserve #l\n  {{{ a (ok: bool), RET (#a, #ok);\n      if ok then crash_borrow (P {[a]}) (Pc {[a]}) else True%I }}}.\nProof.\n  iIntros (\u03a6) \"#Hc H\u03a6\". wp_apply (wp_Reserve).\n  { eauto. }\n  iIntros (a ok) \"H\". iApply \"H\u03a6\".\n  eauto.\nQed.\n\nTheorem wp_crash_Free P Pc l (a: u64) :\n  {{{ is_crash_allocator l P Pc \u2217 crash_borrow (P {[a]}) (Pc {[a]}) }}}\n    Allocator__Free #l #a\n  {{{ RET #(); True }}}.\nProof.\n  iIntros (\u03a6) \"(#Hc&Hborrow) H\u03a6\". wp_apply (wp_Free with \"[Hborrow]\").\n  { iFrame \"Hc\". eauto. }\n  by iApply \"H\u03a6\".\nQed.\n\nEnd crash.\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/examples/alloc_proof_simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.30404168127272885, "lm_q1q2_score": 0.15676994607412845}}
{"text": "From iris.algebra Require Import gmap auth agree gset coPset excl csum.\nFrom Perennial.base_logic.lib Require Export fancy_updates.\nFrom stdpp Require Export namespaces.\nFrom Perennial.base_logic.lib Require Import wsat invariants ae_invariants saved_prop.\nFrom Perennial.Helpers Require Import Qextra.\nFrom iris.algebra Require Import gmap.\nFrom iris.proofmode Require Import tactics.\nFrom Perennial.program_logic Require Export step_fupd_extra crash_weakestpre ae_invariants_mutable later_res private_invariants.\nFrom iris.prelude Require Import options.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nInductive staged_inv_status :=\n| inuse : Qp \u2192 Qp \u2192 staged_inv_status\n| canceled : Qp \u2192 staged_inv_status\n| idle.\n\nGlobal Instance staged_inv_status_inhabited : Inhabited staged_inv_status.\nProof. econstructor. apply idle. Qed.\n\nCanonical Structure staged_inv_statusO := leibnizO staged_inv_status.\n\nClass stagedG (\u03a3 : gFunctors) : Set := WsatG {\n  staging_saved_inG :> savedPropG \u03a3;\n  staging_auth_inG :> inG \u03a3 (authR (optionUR (exclR (prodO gnameO gnameO))));\n  staging_status_inG :> inG \u03a3 (authR (optionUR (exclR staged_inv_statusO)));\n  staging_shot_inG :> inG \u03a3 (csumR (fracR) (agreeR unitO));\n}.\n\nDefinition staged\u03a3 : gFunctors :=\n  #[GFunctor (csumR fracR (agreeR unitO));\n   GFunctor (authR (optionUR (exclR (prodO gnameO gnameO))));\n   GFunctor (authR (optionUR (exclR staged_inv_statusO)));\n   savedProp\u03a3].\n\n#[global]\nInstance subG_stagedG {\u03a3} : subG staged\u03a3 \u03a3 \u2192 stagedG \u03a3.\nProof. solve_inG. Qed.\n\nDefinition staged_pending `{stagedG \u03a3} (q: Qp) (\u03b3: gname) : iProp \u03a3 :=\n  own \u03b3 (Cinl q).\nDefinition staged_done `{stagedG \u03a3} (\u03b3: gname) : iProp \u03a3 :=\n  own \u03b3 (Cinr (to_agree ())).\n\n(* This is the modality guarding the crash condition in a wpc *)\nDefinition wpc_crash_modality `{!irisGS \u039b \u03a3, !crashGS \u03a3} E1 mj \u03a6c :=\n  ((\u2200 g1 ns D \u03bas,\n       let E2 :=  \u22a4 \u2216 D in\n       global_state_interp g1 ns mj D \u03bas -\u2217 C -\u2217\n          \u00a3 (num_laters_per_step ns) -\u2217\n     ||={E1|E2,\u2205|\u2205}=> ||\u25b7=>^(num_laters_per_step ns) ||={\u2205|\u2205,E1|E2}=> global_state_interp g1 ns mj D \u03bas \u2217 \u03a6c))%I.\n\nDefinition wpc_value_modality `{!irisGS \u039b \u03a3, !crashGS \u03a3} E1 mj \u03a6c :=\n  ((\u2200 q g1 ns D \u03bas,\n       let E2 :=  \u22a4 \u2216 D in\n       global_state_interp g1 ns mj D \u03bas -\u2217 NC q -\u2217\n     ||={E1|E2,E1|E2}=> global_state_interp g1 ns mj D \u03bas \u2217 \u03a6c \u2217 NC q))%I.\n\nSection def.\nContext `{IRISG: !irisGS \u039b \u03a3, !crashGS \u03a3}.\nContext `{!pri_invG IRISG}.\nContext `{!later_tokG IRISG}.\nContext `{!stagedG \u03a3}.\n\n(*\nDefinition staged_inv_cancel_pre E mj Pc : iProp \u03a3 :=\n  \u2203 Einv mj_ishare mj_ikeep \u03b3 \u03b3finish \u03b3status,\n    \u231c set_infinite Einv \u231d \u2217\n    \u231c 1 < mj + mj_ikeep \u231d%Qp \u2217\n    \u231c (mj_ikeep + mj_ishare = /2)%Qp \u231d \u2217\n    later_tok \u2217\n    staged_pending 1 \u03b3finish \u2217\n    pri_inv_tok mj_ikeep Einv \u2217\n    pri_inv Einv (staged_inv_inner E Einv mj mj_ishare \u03b3 \u03b3finish \u03b3status Pc).\n*)\n\nDefinition staged_inv_inner_pre\n           (staged_inv_inner : coPset -d> coPset -d> Qp -d> Qp -d> gname -d> gname\n                              -d> gname -d> iPropO \u03a3 -d> iPropO \u03a3) :\n           coPset -d> coPset -d> Qp -d> Qp -d> gname -d> gname -d> gname -d> iPropO \u03a3 -d> iPropO \u03a3 :=\n          \u03bb E1 E2 mj mj_ishare (\u03b3saved \u03b3finished \u03b3status: gname) (P: iProp \u03a3) ,\n  ((\u2203 \u03b3prop_stored \u03b3prop_remainder (stat: staged_inv_status) Ps Pr,\n             own \u03b3saved (\u25cf Excl' (\u03b3prop_stored, \u03b3prop_remainder)) \u2217\n             saved_prop_own \u03b3prop_stored DfracDiscarded Ps \u2217\n             saved_prop_own \u03b3prop_remainder DfracDiscarded Pr \u2217\n             own \u03b3status (\u25cf Excl' stat) \u2217\n             pri_inv_tok mj_ishare E2 \u2217\n             ((match stat with\n              | inuse mj_wp mj_ushare => (\u231c (/2) < mj_wp \u2227 mj_wp \u2264 /2 + mj_ushare \u2227 mj_wp \u2264 mj \u231d%Qp \u2217 Ps \u2217 pri_inv_tok mj_ushare E2 \u2217 \u25a1 (Ps -\u2217 wpc_crash_modality E1 mj_wp (Pr \u2217 P)))\n              | canceled mj' => (\u231c (/2) < mj' \u2264 mj  \u231d%Qp \u2217\n                                \u2203 E1' Einv mj_ishare mj_ikeep \u03b3 \u03b3finish \u03b3status,\n                                  \u231c E1' \u2286 E1 \u231d \u2217\n                                  \u231c set_infinite Einv \u231d \u2217\n                                  \u231c 1 < mj' + mj_ikeep \u231d%Qp \u2217\n                                  \u231c (mj_ikeep + mj_ishare = /2)%Qp \u231d \u2217\n                                  later_tok \u2217\n                                  staged_pending 1 \u03b3finish \u2217\n                                  pri_inv_tok mj_ikeep Einv \u2217\n                                  pri_inv Einv (staged_inv_inner E1' Einv mj' mj_ishare \u03b3 \u03b3finish \u03b3status P)) \u2228\n                                  staged_done \u03b3finished\n              | idle => (Ps \u2227 (C ==\u2217 P \u2217 Pr))\n              end)\n              \u2228\n             (Pr \u2217 C \u2217 (P \u2228 staged_done \u03b3finished)))))%I.\n\nLocal Instance staged_inv_inner_pre_contractive : Contractive (staged_inv_inner_pre).\nProof.\n  rewrite /staged_inv_inner_pre => n pre1 pre2 Hequiv ????????.\n  do 15 (f_contractive || f_equiv).\n  destruct a1.\n  - repeat (f_contractive || f_equiv).\n  - do 25 (f_contractive || f_equiv).\n    eapply Hequiv.\n  - repeat (f_contractive || f_equiv).\nQed.\n\nDefinition staged_inv_inner := fixpoint (staged_inv_inner_pre).\n\nLemma staged_inv_inner_unfold  E1 E2 mj1 mj2 \u03b31 \u03b32 \u03b33 P :\n      staged_inv_inner E1 E2 mj1 mj2 \u03b31 \u03b32 \u03b33 P \u22a3\u22a2\n      staged_inv_inner_pre staged_inv_inner E1 E2 mj1 mj2 \u03b31 \u03b32 \u03b33 P.\nProof. apply (fixpoint_unfold staged_inv_inner_pre). Qed.\n\nDefinition staged_inv E1 E2 (\u03b3saved \u03b3finished \u03b3status: gname) (P: iProp \u03a3) : iProp \u03a3 :=\n  (\u2203 mj mj_ishare, \u231c /2 < mj \u231d%Qp \u2217 pri_inv E2 (staged_inv_inner E1 E2 mj mj_ishare \u03b3saved \u03b3finished \u03b3status P)).\n\nDefinition staged_inv_cancel E mj0 Pc : iProp \u03a3 :=\n  \u2203 mj Einv mj_ishare mj_ikeep \u03b3 \u03b3finish \u03b3status,\n    \u231c /2 < mj \u2264 mj0 \u231d%Qp \u2217\n    \u231c set_infinite Einv \u231d \u2217\n    \u231c 1 < mj + mj_ikeep \u231d%Qp \u2217\n    \u231c (mj_ikeep + mj_ishare = /2)%Qp \u231d \u2217\n    later_tok \u2217\n    staged_pending 1 \u03b3finish \u2217\n    pri_inv_tok mj_ikeep Einv \u2217\n    pri_inv Einv (staged_inv_inner E Einv mj mj_ishare \u03b3 \u03b3finish \u03b3status Pc).\n\nDefinition staged_value_idle E1 (Ps Pr: iProp \u03a3) P : iProp \u03a3 :=\n  (\u2203 E2 \u03b3saved \u03b3finished \u03b3status \u03b3prop \u03b3prop',\n      own \u03b3saved (\u25ef Excl' (\u03b3prop, \u03b3prop')) \u2217\n      own \u03b3status (\u25ef Excl' idle) \u2217\n          saved_prop_own \u03b3prop DfracDiscarded Ps \u2217\n          saved_prop_own \u03b3prop' DfracDiscarded Pr \u2217\n          later_tok \u2217\n          pri_inv_tok (/2)%Qp E2 \u2217\n          staged_inv E1 E2 \u03b3saved \u03b3finished \u03b3status P)%I.\n\nDefinition staged_value E Ps P : iProp \u03a3 := staged_value_idle E Ps True%I P.\n\nEnd def.\n\nSection inv.\nContext `{IRISG: !irisGS \u039b \u03a3, !generationGS \u039b \u03a3}.\nContext `{PRI: !pri_invG IRISG}.\nContext `{!later_tokG IRISG}.\nContext `{!stagedG \u03a3}.\nImplicit Types i : positive.\nImplicit Types N : namespace.\nImplicit Types P Q R : iProp \u03a3.\n\n(* TODO: this is annoying but true *)\n(*\nGlobal Instance staged_contractive  E \u03b3 \u03b3' : Contractive (staged_inv E \u03b3 \u03b3').\nProof.\n  rewrite /staged_inv=> n ?? ?.\n  rewrite pri_inv_full_eq /pri_inv_full_def.\n  f_equiv => ?.\n  rewrite pri_inv_eq /pri_inv_def.\n  do 4 f_equiv.\nQed.\n\nGlobal Instance staged_ne N k E E' \u03b3 \u03b3': NonExpansive (staged_inv N k E E' \u03b3 \u03b3').\nProof.\n  rewrite /staged_inv=> n ?? ?.\n  repeat (apply step_fupdN_ne || f_contractive || f_equiv); eauto using dist_le.\nQed.\n\nGlobal Instance staged_proper N k E E' \u03b3 \u03b3' : Proper ((\u22a3\u22a2) ==> (\u22a3\u22a2)) (staged_inv N k E E' \u03b3 \u03b3').\nProof. apply ne_proper, _. Qed.\n*)\n\nGlobal Instance staged_persistent E1 E2 \u03b31 \u03b32 \u03b33 P : Persistent (staged_inv E1 E2 \u03b31 \u03b32 \u03b33 P).\nProof. rewrite /staged_inv. apply _. Qed.\n\nLemma pending_done q \u03b3: staged_pending q \u03b3 -\u2217 staged_done \u03b3 -\u2217 False.\nProof.\n  rewrite /staged_pending/staged_done.\n  iIntros \"H H'\".\n  { by iDestruct (own_valid_2 with \"H H'\") as %?. }\nQed.\n\nLemma pending_upd_done \u03b3: staged_pending 1%Qp \u03b3 ==\u2217 staged_done \u03b3.\nProof.\n  rewrite /staged_pending/staged_done.\n  iIntros \"H\". iMod (own_update with \"H\") as \"$\".\n  { by apply cmra_update_exclusive. }\n  done.\nQed.\n\nLemma pending_alloc:\n  \u22a2 |==> \u2203 \u03b3, staged_pending 1 \u03b3.\nProof.\n  iApply (own_alloc (Cinl 1%Qp)).\n  { rewrite //=. }\nQed.\n\nLemma pending_split \u03b3:\n  staged_pending 1 \u03b3 \u22a2 staged_pending (1/2)%Qp \u03b3 \u2217 staged_pending (1/2)%Qp \u03b3.\nProof. by rewrite /staged_pending -own_op -Cinl_op frac_op Qp.div_2. Qed.\n\nLemma pending_split34 \u03b3:\n  staged_pending 1 \u03b3 \u22a2 staged_pending (3/4)%Qp \u03b3 \u2217 staged_pending (1/4)%Qp \u03b3.\nProof. by rewrite /staged_pending -own_op -Cinl_op frac_op Qp.three_quarter_quarter. Qed.\n\nLemma pending_join \u03b3:\n staged_pending (1/2)%Qp \u03b3 \u2217 staged_pending (1/2)%Qp \u03b3 \u22a2  staged_pending 1 \u03b3.\nProof. by rewrite /staged_pending -own_op -Cinl_op frac_op Qp.div_2. Qed.\n\nLemma pending_join34 \u03b3:\n staged_pending (3/4)%Qp \u03b3 \u2217 staged_pending (1/4)%Qp \u03b3 \u22a2  staged_pending 1 \u03b3.\nProof. by rewrite /staged_pending -own_op -Cinl_op frac_op Qp.three_quarter_quarter. Qed.\n\nLemma pending34_pending34 \u03b3:\n staged_pending (3/4)%Qp \u03b3 -\u2217 staged_pending (3/4)%Qp \u03b3 -\u2217 False.\nProof.\n  rewrite /staged_pending.\n  iIntros \"H H'\".\n  { by iDestruct (own_valid_2 with \"H H'\") as %?. }\nQed.\n\nLemma pending_pending \u03b3:\n staged_pending 1%Qp \u03b3 -\u2217 staged_pending 1%Qp \u03b3 -\u2217 False.\nProof.\n  rewrite /staged_pending.\n  iIntros \"H H'\".\n  { by iDestruct (own_valid_2 with \"H H'\") as %?. }\nQed.\n\n(* TODO : *)\n(*\nLemma staged_inv_iff E i \u03b3 \u03b3' P Q :\n  \u25b7 \u25a1 (P \u2194 Q) -\u2217\n  staged_inv E i \u03b3 \u03b3' P -\u2217\n  staged_inv E i \u03b3 \u03b3' Q.\nProof.\n  iIntros \"#HPQ\". iApply inv_iff. iNext. iAlways. iSplit.\n  - iIntros \"H\". iDestruct \"H\" as (?? P0 P0') \"(?&?&?&#HP0&Hcase)\". iExists _, _, P0, P0'. iFrame.\n    iAlways. iIntros. iSpecialize (\"HP0\" with \"[$] [$]\").\n    iApply (step_fupdN_inner_wand' with \"HP0\"); eauto.\n    iIntros \"(?&$)\". by iApply \"HPQ\".\n  - iIntros \"H\". iDestruct \"H\" as (?? P0 P0') \"(?&?&?&#HP0&Hcase)\". iExists _, _, P0, P0'. iFrame.\n    iAlways. iIntros. iSpecialize (\"HP0\" with \"[$] [$]\").\n    iApply (step_fupdN_inner_wand' with \"HP0\"); eauto.\n    iIntros \"(?&$)\". by iApply \"HPQ\".\nQed.\n*)\n\nLemma wpc_crash_modality_intro_C E mj P :\n  (C -\u2217 wpc_crash_modality E mj P) -\u2217\n  wpc_crash_modality E mj P.\nProof.\n  iIntros \"H\". rewrite /wpc_crash_modality.\n  iIntros. iApply (\"H\" with \"[$] [$] [$] [$]\").\nQed.\n\nLemma wpc_crash_modality_strong_wand E1 E2 mj1 mj2 P Q :\n  E1 \u2286 E2 \u2192\n  (/2 < mj1 \u2264 mj2)%Qp \u2192\n  wpc_crash_modality E1 mj1 P -\u2217\n  (P ={E2}=\u2217 Q) -\u2217\n  wpc_crash_modality E2 mj2 Q.\nProof using PRI.\n  iIntros (??) \"Hwpc Hwand\".\n  rewrite /wpc_crash_modality.\n  iIntros (g1 ns D \u03bas) \"Hg #C Hlc\".\n  iApply (step_fupd2N_inner_fupd2).\n  iDestruct (pri_inv_tok_global_le_acc with \"[//] Hg\") as \"(Hg&Hg_clo)\".\n  iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n  iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n  iIntros \"(Hg&HP)\". iDestruct (\"Hg_clo\" with \"[$Hg]\") as \"$\".\n  by iMod (\"Hwand\" with \"[$]\") as \"$\".\nQed.\n\nLemma wpc0_modality_postcondition_cancel_atomic s mj E e \u03a6 \u03a6c `{!Atomic StronglyAtomic e}:\n  (wpc0 s mj E e \u03a6 \u03a6c) -\u2217\n  (wpc0 s mj E e (\u03bb v, wpc_crash_modality E mj \u03a6c \u2227 (wpc_value_modality E mj (\u03a6 v))) \u03a6c).\nProof.\n  iIntros \"H\".\n  rewrite ?wpc0_unfold. rewrite /wpc_pre.\n  iSplit; last first.\n  { iDestruct \"H\" as \"(_&H)\". eauto. }\n  destruct (to_val e).\n  - iIntros (q g1 ns D \u03bas) \"Hg HNC\".\n    iFrame. iModIntro.\n    iSplit.\n    { iDestruct \"H\" as \"(_&H)\".\n      iIntros (????) \"Hg HC Hlc\".\n      iSpecialize (\"H\" with \"[$] [$] [$]\").\n      iApply (step_fupd2N_inner_wand with \"H\"); auto.\n    }\n    { iDestruct \"H\" as \"(H&_)\".\n      rewrite /wpc_value_modality. iIntros.\n      iSpecialize (\"H\" with \"[$] [$]\").\n      iMod (fupd2_mask_subseteq E (\u22a4 \u2216 _)) as \"Hclo\".\n      { auto. }\n      { reflexivity. }\n      iMod \"H\" as \"($&$&$)\". iMod \"Hclo\"; eauto. }\n  - iIntros.\n    iDestruct \"H\" as \"(H&_)\".\n    iMod (\"H\" with \"[$] [$] [$] [$]\") as \"H\". iModIntro.\n    simpl. iMod \"H\". iModIntro. iNext. iMod \"H\". iModIntro.\n    iApply (step_fupd2N_wand with \"H\").\n    iIntros \"($&H)\".\n    iIntros.\n    iMod (\"H\" with \"[//]\") as \"($&$&H&$)\".\n    iModIntro.\n    rewrite /Atomic/= in Atomic0.\n    edestruct (Atomic0) as (v&Hval); eauto.\n    rewrite Hval. rewrite ?wpc0_unfold /wpc_pre.\n    rewrite Hval. iSplit; last first.\n    { iDestruct \"H\" as \"(_&H)\". eauto. }\n    iIntros. iModIntro. iFrame.\n    iSplit.\n    { iDestruct \"H\" as \"(_&H)\".\n      iIntros (????) \"Hg HC Hlc\".\n      iSpecialize (\"H\" with \"[$] [$] [$]\").\n      iApply (step_fupd2N_inner_wand with \"H\"); auto.\n    }\n    { iDestruct \"H\" as \"(H&_)\".\n      rewrite /wpc_value_modality. iIntros.\n      iSpecialize (\"H\" with \"[$] [$]\").\n      iMod (fupd2_mask_subseteq E (\u22a4 \u2216 _)) as \"Hclo\".\n      { auto. }\n      { reflexivity. }\n      iMod \"H\" as \"($&$&$)\". iMod \"Hclo\"; eauto. }\nQed.\n\nLemma wpc0_modality_postcondition_cancel s mj E e \u03a6 \u03a6c :\n  (wpc0 s mj E e \u03a6 \u03a6c) -\u2217\n  (wpc0 s mj E e (\u03bb v, wpc_crash_modality \u22a4 mj \u03a6c \u2227 (wpc_value_modality \u22a4 mj (\u03a6 v))) \u03a6c).\nProof.\n  iIntros \"H\".\n  iL\u00f6b as \"IH\" forall (e E).\n  rewrite ?wpc0_unfold. rewrite /wpc_pre.\n  iSplit; last first.\n  { iDestruct \"H\" as \"(_&H)\". eauto. }\n  destruct (to_val e).\n  - iIntros (q g1 ns D \u03bas) \"Hg HNC\".\n    iFrame. iModIntro.\n    iSplit.\n    { iDestruct \"H\" as \"(_&H)\".\n      iIntros (????) \"Hg HC Hlc\".\n      iSpecialize (\"H\" with \"[$] [$] [$]\").\n      iApply (step_fupd2N_inner_wand with \"H\"); auto.\n    }\n    { iDestruct \"H\" as \"(H&_)\".\n      rewrite /wpc_value_modality. iIntros.\n      iSpecialize (\"H\" with \"[$] [$]\").\n      iMod (fupd2_mask_subseteq E (\u22a4 \u2216 _)) as \"Hclo\".\n      { auto. }\n      { reflexivity. }\n      iMod \"H\" as \"($&$&$)\". iMod \"Hclo\"; eauto. }\n  - iIntros.\n    iDestruct \"H\" as \"(H&_)\".\n    iMod (\"H\" with \"[$] [$] [$] [$]\") as \"H\". iModIntro.\n    simpl. iMod \"H\". iModIntro. iNext. iMod \"H\". iModIntro.\n    iApply (step_fupd2N_wand with \"H\").\n    iIntros \"($&H)\".\n    iIntros.\n    iMod (\"H\" with \"[//]\") as \"($&$&H&$)\".\n    iModIntro. by iApply \"IH\".\nQed.\n\nLemma wpc_crash_modality_intro E1 mj P :\n  P -\u2217 wpc_crash_modality E1 mj P.\nProof.\n  iIntros \"H\".\n  rewrite /wpc_crash_modality.\n  iIntros (g1 ns D \u03bas) \"Hg #C Hlc\".\n  iApply (step_fupd2N_inner_later); auto.\n  iNext. iFrame.\nQed.\n\nLemma wpc_crash_modality_wand E1 mj P Q :\n  wpc_crash_modality E1 mj P -\u2217\n  (P ={E1}=\u2217 Q) -\u2217\n  wpc_crash_modality E1 mj Q.\nProof.\n  iIntros \"Hwpc Hwand\".\n  rewrite /wpc_crash_modality.\n  iIntros (g1 ns D \u03bas) \"Hg #C Hlc\".\n  iApply (step_fupd2N_inner_fupd2).\n  iSpecialize (\"Hwpc\" with \"[$] [$] [$]\").\n  iApply (step_fupd2N_inner_wand with \"Hwpc\"); auto.\n  iIntros \"($&HP)\". by iMod (\"Hwand\" with \"[$]\") as \"$\".\nQed.\n\nLemma wpc_crash_modality_combine_cred E1 mj P1 P2 :\n  later_tok -\u2217\n  \u25b7 wpc_crash_modality E1 mj P1 -\u2217\n  \u25b7 wpc_crash_modality E1 mj P2 -\u2217\n  wpc_crash_modality E1 mj (\u00a32 \u2217 P1 \u2217 P2).\nProof.\n  iIntros \"Htok H1 H2\".\n  rewrite /wpc_crash_modality.\n  iIntros (g1 ns D \u03bas) \"Hg #C Hlc\".\n  iMod (later_tok_decr with \"[$]\") as (ns' Hle) \"Hg\".\n  iApply (step_fupd2N_inner_fupd2).\n  iApply (step_fupd2N_inner_le).\n  { apply (num_laters_per_step_exp ns'). lia. }\n  iMod (fupd2_mask_subseteq \u2205 \u2205) as \"Hclo'\"; [set_solver+..|].\n  iEval (simpl).\n  do 2 (iModIntro; iModIntro; iNext).\n  iMod \"Hclo'\".\n  iApply step_fupd2N_inner_add.\n  iDestruct (lc_weaken with \"Hlc\") as \"Hlc\".\n  { apply (num_laters_per_step_exp ns'). lia. }\n  iDestruct \"Hlc\" as \"[[Hlc1 Hlc2] Hlc3]\".\n  iSpecialize (\"H1\" with \"[$] [$] [$]\").\n  iApply (step_fupd2N_inner_wand with \"H1\"); auto.\n  iIntros \"(Hg&HP1)\".\n  iSpecialize (\"H2\" with \"[$] [$] [$]\").\n  iApply (step_fupd2N_inner_wand with \"H2\"); auto.\n  iIntros \"(Hg&$)\". iFrame.\n  iMod (global_state_interp_le with \"[$]\") as \"$\"; auto.\n  lia.\nQed.\n\nLemma wpc_crash_modality_combine E1 mj P1 P2 :\n  later_tok -\u2217\n  \u25b7 wpc_crash_modality E1 mj P1 -\u2217\n  \u25b7 wpc_crash_modality E1 mj P2 -\u2217\n  wpc_crash_modality E1 mj (P1 \u2217 P2).\nProof.\n  iIntros.\n  iApply (wpc_crash_modality_wand with \"[-]\").\n  { iApply (wpc_crash_modality_combine_cred with \"[$] [$] [$]\"). }\n  by iIntros \"(?&$&$)\".\nQed.\n\nLemma wpc_crash_modality_split E Einv mj1 mj2 P1 P2 :\n  (/2 < mj1 < mj2)%Qp \u2192\n  later_tok -\u2217\n  later_tok -\u2217\n  pri_inv_tok 1%Qp Einv -\u2217\n  wpc_crash_modality E mj1 (P1 \u2217 P2) -\u2217\n  ||={\u2205|\u2205, \u2205|\u2205}=> wpc_crash_modality E mj2 P1 \u2217 wpc_crash_modality E mj2 P2.\nProof using stagedG0.\n  destruct (decide (mj2 \u2264 1)%Qp) as [Hle|Hnle]; last first.\n  { iIntros. iModIntro.\n    iSplitL.\n    - iIntros (????) \"Hg HC\".\n      iDestruct (pri_inv_tok_global_valid with \"[$]\") as %(?&?).\n      exfalso. naive_solver.\n    - iIntros (????) \"Hg HC\".\n      iDestruct (pri_inv_tok_global_valid with \"[$]\") as %(?&?).\n      exfalso. naive_solver.\n  }\n  iIntros (Hlt) \"Hltok Hltok2 H\".\n  iIntros \"Hg\".\n  destruct (Qp_plus_split_alt mj1 mj2) as (qa&qb&Hle1&Hlt2&Hle3); auto.\n  rewrite -Hle1.\n  iDestruct (pri_inv_tok_split with \"H\") as \"(Hqa&Hqb)\".\n  iDestruct (pri_inv_tok_split with \"Hqa\") as \"(Hqa1&Hqa2)\".\n  iMod (pending_alloc) as (\u03b31) \"H1\".\n  iMod (pending_alloc) as (\u03b32) \"H2\".\n  iDestruct (pri_inv_tok_infinite with \"Hqb\") as %Hinf.\n  iMod (pri_inv_alloc Einv _ _\n                      (pri_inv_tok qb Einv \u2217 (wpc_crash_modality E mj1 (P1 \u2217 P2) \u2228\n                                              ((P1 \u2228 staged_done \u03b31) \u2217 (P2 \u2228 staged_done \u03b32)))) with \"[$Hqb $Hg]\")\n  as \"#Hinv\"; first done.\n  iModIntro.\n  iSplitL \"Hltok Hqa1 H1\".\n  {\n    rewrite /wpc_crash_modality.\n    iIntros (????) \"Hg #HC Hlc\".\n    iMod (later_tok_decr with \"[$]\") as (ns' Hle') \"Hg\".\n    iApply (step_fupd2N_inner_fupd2).\n    iApply (step_fupd2N_inner_le _ (S (num_laters_per_step ns'))).\n    { apply Nat.le_succ_l. apply (num_laters_per_step_lt). lia. }\n    simpl.\n    iDestruct (pri_inv_tok_disj with \"[$]\") as %[Hdisj|Hval]; last first.\n    { exfalso. apply Qp.lt_nge in Hlt2. revert Hval. rewrite frac_valid.\n      intros HleX. apply Hlt2. etransitivity; last eassumption.\n      apply Qp.add_le_mono_r. auto. }\n    iMod (pri_inv_acc with \"Hinv\") as \"(Hinner&Hclo)\".\n    { set_solver. }\n    iMod (fupd2_mask_subseteq \u2205 \u2205) as \"Hclo'\"; [set_solver+..|].\n    iModIntro. iModIntro. iNext. iMod \"Hclo'\".\n    iDestruct \"Hinner\" as \"(Htok&Hcases)\".\n    iDestruct \"Hcases\" as \"[Hunrun|Hrun]\".\n    {\n      iDestruct (pri_inv_tok_join with \"Hqa1 Htok\") as \"Hitok'\".\n      iDestruct (pri_inv_tok_le_acc mj1 with \"[$]\") as \"(Hitok&Hitok_clo)\".\n      { auto. }\n      iDestruct (pri_inv_tok_global_le_acc _ _ _ mj1 with \"[] Hg\") as \"(Hg&Hg_clo)\".\n      { iPureIntro. split; first naive_solver.\n        apply Qp.lt_le_incl; naive_solver. }\n      iMod (pri_inv_tok_disable with \"[$Hg $Hitok]\") as \"Hg\".\n      replace (\u22a4 \u2216 D \u2216 Einv) with (\u22a4 \u2216 (Einv \u222a D)) by set_solver.\n      iSpecialize (\"Hunrun\" with \"[$] [$] [Hlc]\").\n      {\n        iApply (lc_weaken with \"Hlc\").\n        {  assert (Hlt': ns' < ns) by lia.\n           apply num_laters_per_step_le in Hlt'. lia. }\n      }\n      iMod \"Hunrun\".  iModIntro. iApply (step_fupd2N_wand with \"Hunrun\").\n      iIntros \"Hunrun\". iMod \"Hunrun\" as \"(Hg&HP1&HP2)\".\n      iMod (pending_upd_done with \"H1\") as \"Hdone\".\n      iMod (pri_inv_tok_enable with \"[$Hg //]\") as \"(Hitok&Hg)\".\n      iDestruct (\"Hitok_clo\" with \"[$]\") as \"Hitok\".\n      iDestruct (pri_inv_tok_split with \"[$]\") as \"(Hitok1&Hitok2)\".\n      iMod (\"Hclo\" with \"[Hitok2 HP2 Hdone]\").\n      { iFrame. iNext. iRight. iFrame. }\n      iModIntro.\n      iDestruct (\"Hg_clo\" with \"[$]\") as \"Hg_clo\".\n      iMod (global_state_interp_le with \"[$]\") as \"$\".\n      { lia. }\n      eauto.\n    }\n    iDestruct \"Hrun\" as \"(Hrun1&Hrun2)\".\n    iDestruct \"Hrun1\" as \"[HP1|Hfalse]\"; last first.\n    { iDestruct (pending_done with \"[$] [$]\") as %[]. }\n    iMod (pending_upd_done with \"H1\") as \"Hdone\".\n    iMod (\"Hclo\" with \"[Hdone Hrun2 Htok]\").\n    { iFrame. iRight. iNext. iFrame. }\n\n    iApply (step_fupd2N_inner_later); auto. iModIntro.\n    iMod (global_state_interp_le with \"[$]\") as \"$\".\n    { lia. }\n    iFrame. eauto.\n  }\n  {\n    rewrite /wpc_crash_modality.\n    iIntros (????) \"Hg #HC Hlc\".\n    iMod (later_tok_decr with \"[$]\") as (ns' Hle') \"Hg\".\n    iApply (step_fupd2N_inner_fupd2).\n    iApply (step_fupd2N_inner_le _ (S (num_laters_per_step ns'))).\n    { apply Nat.le_succ_l. apply (num_laters_per_step_lt). lia. }\n    simpl.\n    iDestruct (pri_inv_tok_disj with \"[$]\") as %[Hdisj|Hval]; last first.\n    { exfalso. apply Qp.lt_nge in Hlt2. revert Hval. rewrite frac_valid.\n      intros HleX. apply Hlt2. etransitivity; last eassumption.\n      apply Qp.add_le_mono_r. auto. }\n    iMod (pri_inv_acc with \"Hinv\") as \"(Hinner&Hclo)\".\n    { set_solver. }\n    iMod (fupd2_mask_subseteq \u2205 \u2205) as \"Hclo'\"; [set_solver+..|].\n    iModIntro. iModIntro. iNext. iMod \"Hclo'\".\n    iDestruct \"Hinner\" as \"(Htok&Hcases)\".\n    iDestruct \"Hcases\" as \"[Hunrun|Hrun]\".\n    {\n      iDestruct (pri_inv_tok_join with \"Hqa2 Htok\") as \"Hitok'\".\n      iDestruct (pri_inv_tok_le_acc mj1 with \"[$]\") as \"(Hitok&Hitok_clo)\".\n      { auto. }\n      iDestruct (pri_inv_tok_global_le_acc _ _ _ mj1 with \"[] Hg\") as \"(Hg&Hg_clo)\".\n      { iPureIntro. split; first naive_solver.\n        apply Qp.lt_le_incl; naive_solver. }\n      iMod (pri_inv_tok_disable with \"[$Hg $Hitok]\") as \"Hg\".\n      replace (\u22a4 \u2216 D \u2216 Einv) with (\u22a4 \u2216 (Einv \u222a D)) by set_solver.\n      iSpecialize (\"Hunrun\" with \"[$] [$] [Hlc]\").\n      {\n        iApply (lc_weaken with \"Hlc\").\n        {  assert (Hlt': ns' < ns) by lia.\n           apply num_laters_per_step_le in Hlt'. lia. }\n      }\n      iMod \"Hunrun\".  iModIntro. iApply (step_fupd2N_wand with \"Hunrun\").\n      iIntros \"Hunrun\". iMod \"Hunrun\" as \"(Hg&HP1&HP2)\".\n      iMod (pending_upd_done with \"H2\") as \"Hdone\".\n      iMod (pri_inv_tok_enable with \"[$Hg //]\") as \"(Hitok&Hg)\".\n      iDestruct (\"Hitok_clo\" with \"[$]\") as \"Hitok\".\n      iDestruct (pri_inv_tok_split with \"[$]\") as \"(Hitok1&Hitok2)\".\n      iMod (\"Hclo\" with \"[Hitok2 HP1 Hdone]\").\n      { iFrame. iNext. iRight. iFrame. }\n      iModIntro.\n      iDestruct (\"Hg_clo\" with \"[$]\") as \"Hg_clo\".\n      iMod (global_state_interp_le with \"[$]\") as \"$\".\n      { lia. }\n      eauto.\n    }\n    iDestruct \"Hrun\" as \"(Hrun1&Hrun2)\".\n    iDestruct \"Hrun2\" as \"[HP2|Hfalse]\"; last first.\n    { iDestruct (pending_done with \"[$] [$]\") as %[]. }\n    iMod (pending_upd_done with \"H2\") as \"Hdone\".\n    iMod (\"Hclo\" with \"[Hdone Hrun1 Htok]\").\n    { iFrame. iRight. iNext. iFrame. }\n\n    iApply (step_fupd2N_inner_later); auto. iModIntro.\n    iMod (global_state_interp_le with \"[$]\") as \"$\".\n    { lia. }\n    iFrame. eauto.\n  }\nQed.\n\nEnd inv.\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/staged_invariant_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.28457601635158564, "lm_q1q2_score": 0.15668965065786006}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Eval semantics of expression.  *)\n\nSet Implicit Arguments.\n\nRequire Import String ZArith Morphisms.\nRequire Import Monad hpattern vgtac VocabA Syn DLat DPow UserInputType.\nRequire Import DomBasic DomArrayBlk DomAbs DomMem SemMem.\n\nLocal Open Scope Z.\nLocal Open Scope sumbool.\n\nDefinition eval_const (cst : constant) : Val.t := Val.bot.\n\nDefinition eval_uop (u : unop) (v : Val.t) : Val.t := v.\n\nLemma eval_uop_mor (u : unop) : Proper (Val.eq ==> Val.eq) (eval_uop u).\nProof. unfold eval_uop. by intros v1 v2 Hv. Qed.\n\nDefinition is_array_loc (x : Loc.t) : bool :=\n  match x with\n    | Loc.Inl (VarAllocsite.Inr _, _) => true\n    | _ => false\n  end.\n\nLemma is_array_loc_mor : Proper (Loc.eq ==> eq) is_array_loc.\nProof.\nunfold is_array_loc; intros x1 x2 Hx.\ndestruct x1, x2; [|by inversion Hx|by inversion Hx|by auto].\ndestruct a, a0. destruct t, t1.\n- by auto.\n- inversion Hx; destruct Heq as [Heq _]; by inversion Heq.\n- inversion Hx; destruct Heq as [Heq _]; by inversion Heq.\n- by auto.\nQed.\n\nDefinition array_loc_of_val (v : Val.t) : Val.t :=\n  PowLoc.filter is_array_loc (pow_loc_of_val v).\n\nLemma array_loc_of_val_mor : Proper (Val.eq ==> Val.eq) array_loc_of_val.\nProof.\nunfold array_loc_of_val; intros v1 v2 Hv.\napply val_of_pow_loc_mor.\napply PowLoc.SS.SF.filter_equal; [by apply is_array_loc_mor|by apply Hv].\nQed.\n\nDefinition eval_bop (b : binop) (v1 v2 : Val.t) : Val.t :=\n  match b with\n  | PlusPI | IndexPI =>\n    Val.join (array_loc_of_val v1) (ArrayBlk.plus_offset (array_of_val v1))\n  | MinusPI =>\n    Val.join (array_loc_of_val v1) (ArrayBlk.minus_offset (array_of_val v1))\n  | _ => Val.join v1 v2\n  end.\n\nLemma eval_bop_mor (b : binop) :\n  Proper (Val.eq ==> Val.eq ==> Val.eq) (eval_bop b).\nProof.\nunfold eval_bop. intros v1 v2 Hv w1 w2 Hw; destruct b\n; try by apply Val.join_eq.\n- apply Val.join_eq.\n  + by apply array_loc_of_val_mor.\n  + by apply val_of_array_mor, ArrayBlk.plus_offset_mor, array_of_val_mor.\n- apply Val.join_eq.\n  + by apply array_loc_of_val_mor.\n  + by apply val_of_array_mor, ArrayBlk.plus_offset_mor, array_of_val_mor.\n- apply Val.join_eq.\n  + by apply array_loc_of_val_mor.\n  + by apply val_of_array_mor, ArrayBlk.minus_offset_mor, array_of_val_mor.\nQed.\n\nDefinition eval_string (s : string) : Val.t := Val.bot.\n\nDefinition eval_string_loc (s : string) (a : Allocsite.t) (lvs : PowLoc.t)\n           : Val.t :=\n  Val.join (lvs : Val.t) (ArrayBlk.make a : Val.t).\n\nDefinition deref_of_val (v : Val.t) : PowLoc.t :=\n  PowLoc.join (pow_loc_of_val v) (ArrayBlk.pow_loc_of_array (array_of_val v)).\n\nLemma deref_of_val_mor : Proper (Val.eq ==> PowLoc.eq) deref_of_val.\nProof.\nunfold deref_of_val; intros v1 v2 Hv.\napply PowLoc.join_eq.\n- by apply pow_loc_of_val_mor.\n- apply ArrayBlk.pow_loc_of_array_mor. by apply array_of_val_mor.\nQed.\n\nModule Make (Import M : Monad) (MB : MemBasic M).\n\nModule Import SemMem := SemMem.Make M MB.\n\nDefinition eval_var node x (is_global : bool) :=\n  if is_global then loc_of_var (var_of_gvar x) else\n    loc_of_var (var_of_lvar (InterNode.get_pid node, x)).\n\nFixpoint resolve_offset (mode : update_mode) (node : InterNode.t)\n                    (v : Val.t) (os : offset) (m : Mem.t)\n: M.m PowLoc.t :=\n  match os with\n  | NoOffset => ret (deref_of_val v)\n  | FOffset f os' =>\n    resolve_offset mode node\n      (PowLoc.join\n         (pow_loc_append_field (pow_loc_of_val v) f)\n         (ArrayBlk.pow_loc_of_struct_w_field (array_of_val v) f))\n      os' m\n  | IOffset e os' =>\n    do v' <- mem_lookup (deref_of_val v) m ;\n    resolve_offset mode node v' os' m\n  end.\n\nFixpoint eval (mode : update_mode) (node : InterNode.t)\n         (e : exp) (m : Mem.t) : M.m Val.t :=\n  match e with\n  | Const c _ => ret (eval_const c)\n  | Lval l _ =>\n    do lv <- eval_lv mode node l m ;\n    mem_lookup lv m\n  | SizeOf _ _\n  | SizeOfE _ _\n  | SizeOfStr _ _\n  | AlignOf _ _\n  | AlignOfE _ _ => ret Val.bot\n  | UnOp u e _ =>\n    do v <- eval mode node e m ;\n    ret (eval_uop u v)\n  | BinOp b e1 e2 _ =>\n    do v1 <- eval mode node e1 m ;\n    do v2 <- eval mode node e2 m ;\n    ret (eval_bop b v1 v2)\n  | Question e1 e2 e3 _ =>\n    do v2 <- eval mode node e2 m ;\n    do v3 <- eval mode node e3 m ;\n    ret (Val.join v2 v3)\n  | CastE new_stride_opt e _ =>\n    match new_stride_opt with\n    | None => eval mode node e m\n    | Some new_stride =>\n      do v <- eval mode node e m ;\n      let array_v := ArrayBlk.cast_array_int new_stride (array_of_val v) in\n      ret (modify_array v array_v)\n    end\n  | AddrOf l _ =>\n    do lv <- eval_lv mode node l m ;\n    ret (val_of_pow_loc lv)\n  | StartOf l _ =>\n    do lv <- eval_lv mode node l m ;\n    ret (val_of_pow_loc lv)\n  end\n\nwith eval_lv (mode : update_mode) (node : InterNode.t)\n             (lv : lval) (m : Mem.t) : M.m PowLoc.t :=\n  match lv with\n  | lval_intro lhost' ofs _ =>\n    do v <-\n      match lhost' with\n      | VarLhost vi is_global =>\n        let x := eval_var node vi is_global in\n        ret ((PowLoc.singleton x) : Val.t)\n      | MemLhost e => eval mode node e m\n      end ;\n    resolve_offset mode node v ofs m\n  end.\n\nFixpoint eval_list (mode : update_mode) (node : InterNode.t)\n         (es : list exp) (m : Mem.t) : M.m (list Val.t) :=\n  match es with\n    | nil => ret nil\n    | e :: tl =>\n      do v <- eval mode node e m;\n      do tl' <- eval_list mode node tl m;\n      ret (v :: tl')\n  end.\n\nDefinition eval_alloc' (node : InterNode.t) : Val.t :=\n  let allocsite := allocsite_of_node node in\n  let pow_loc : PowLoc.t := PowLoc.singleton (loc_of_allocsite allocsite) in\n  Val.join (pow_loc : Val.t) (ArrayBlk.make allocsite : Val.t).\n\nDefinition eval_alloc (mode : update_mode) (node : InterNode.t) (a : alloc)\n  : Val.t :=\n  match a with\n    | Array e => eval_alloc' node\n  end.\n\nEnd Make.\n\nLocal Close Scope sumbool.\nLocal Close Scope Z.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/TntInput/SemEval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.15628974879213442}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Locations.\nRequire Import DataType.\nRequire Import LAsm.\nRequire Import CDataTypes.\nRequire Import AsmExtra.\nRequire Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import PQueueIntro.\nRequire Import PThreadInit.\nRequire Export QueueIntroGen.\nRequire Import PThreadInitCode.\nRequire Import ZArith.Zwf.\nRequire Import EventsExtra.\nRequire Import GlobalenvsExtra.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import Maps.\nRequire Import Heap.\nRequire Import RefinementTactic.\nRequire Import AuxLemma.\nRequire Import LayerTemplate2.\nRequire Import Implementation.\nRequire Import SeparateCompiler.\nRequire Import ClightImplemExtra.\nRequire Import LayerDefinition.\nRequire Import RealParams.\nRequire Import CInitSpecsMPTOp.\nRequire Import CInitSpecsMPTCommon.\nRequire Import CInitSpecsMPTBit.\nRequire Import CInitSpecsproc.\n\nOpen Local Scope string_scope.\nOpen Local Scope error_monad_scope.\n\nModule QUEUEINTROGENIMPL.\n  Export QueueIntroGen.QUEUEINTROGEN.\n\n  Lemma hprim_finite_type:\n    forall\n      (Q: PQUEUEINTRO.primOp -> Prop)\n      (Q_dec: forall p, {Q p} + {~ Q p}),\n      {forall p, Q p} + {~ forall p, Q p}.\n  Proof with (try (right; eauto; fail)).\n    intros.    \n    destruct (Q_dec PQUEUEINTRO.PAlloc)...\n    destruct (Q_dec PQUEUEINTRO.PFree)...\n    destruct (Q_dec PQUEUEINTRO.PSetPT)...\n    destruct (Q_dec PQUEUEINTRO.PPTRead)...\n    destruct (Q_dec PQUEUEINTRO.PPTResv)...\n    destruct (Q_dec PQUEUEINTRO.PKCtxtNew)...\n    destruct (Q_dec PQUEUEINTRO.PThreadFree)...\n    destruct (Q_dec PQUEUEINTRO.PKCtxtSwitch)...\n    destruct (Q_dec PQUEUEINTRO.PGetState)...\n    destruct (Q_dec PQUEUEINTRO.PGetPrev)...\n    destruct (Q_dec PQUEUEINTRO.PGetNext)...\n    destruct (Q_dec PQUEUEINTRO.PSetState)...\n    destruct (Q_dec PQUEUEINTRO.PSetPrev)...\n    destruct (Q_dec PQUEUEINTRO.PSetNext)...\n    destruct (Q_dec PQUEUEINTRO.PGetHead)...\n    destruct (Q_dec PQUEUEINTRO.PGetTail)...\n    destruct (Q_dec PQUEUEINTRO.PSetHead)...\n    destruct (Q_dec PQUEUEINTRO.PSetTail)...\n    destruct (Q_dec PQUEUEINTRO.PTDQInit)...\n    destruct (Q_dec PQUEUEINTRO.PPTIn)...\n    destruct (Q_dec PQUEUEINTRO.PPTOut)...\n    destruct (Q_dec PQUEUEINTRO.PTrapIn)...\n    destruct (Q_dec PQUEUEINTRO.PTrapOut)...\n    destruct (Q_dec PQUEUEINTRO.PHostIn)...\n    destruct (Q_dec PQUEUEINTRO.PHostOut)...\n    destruct (Q_dec PQUEUEINTRO.PTrapGet)...\n    destruct (Q_dec PQUEUEINTRO.PTrapRet)...\n    destruct (Q_dec PQUEUEINTRO.PThreadInit)...\n    left; destruct p; assumption.\n  Defined.    \n\n  Section WithPrimitives.\n\n  Context `{real_params: RealParams}.\n\n    Notation HDATA := (PQUEUEINTRO.AbData(PgSize:=PgSize) (num_proc:=num_proc)(kern_low:=kern_low)\n                                         (kern_high:=kern_high) (maxpage:=maxpage)).   \n    Notation LDATA := (PTHREADINIT.AbData(PgSize:=PgSize)(num_proc:=num_proc) (kern_low:=kern_low)\n                                         (kern_high:=kern_high) (maxpage:=maxpage)).                             \n  \n    Notation Hfundef := (Asm.fundef (external_function:= PQUEUEINTRO.primOp)).\n    Notation Lfundef := (Asm.fundef (external_function:= PTHREADINIT.primOp)).\n\n    Notation funkind := (funkind (low:= PTHREADINIT.primOp) Asm.code (Clight.fundef (external_function := PTHREADINIT.primOp))).\n\n    Definition source_implem_extfuns (p: PQUEUEINTRO.primOp): funkind :=\n      match p with\n        | PQUEUEINTRO.PAlloc => Code _ (AST.External PTHREADINIT.PAlloc)\n        | PQUEUEINTRO.PFree => Code _ (AST.External PTHREADINIT.PFree)\n        | PQUEUEINTRO.PSetPT => Code _ (AST.External PTHREADINIT.PSetPT)\n        | PQUEUEINTRO.PPTRead => Code _ (AST.External PTHREADINIT.PPTRead)\n        | PQUEUEINTRO.PPTResv => Code _ (AST.External PTHREADINIT.PPTResv)\n        | PQUEUEINTRO.PKCtxtNew => Code _ (AST.External PTHREADINIT.PKCtxtNew)\n        | PQUEUEINTRO.PThreadFree => Code _ (AST.External PTHREADINIT.PThreadFree)\n        | PQUEUEINTRO.PKCtxtSwitch => Code _ (AST.External PTHREADINIT.PKCtxtSwitch)\n        | PQUEUEINTRO.PGetState => Code _ (AST.External PTHREADINIT.PGetState)\n        | PQUEUEINTRO.PGetPrev => Code _ (AST.External PTHREADINIT.PGetPrev)\n        | PQUEUEINTRO.PGetNext => Code _ (AST.External PTHREADINIT.PGetNext)\n        | PQUEUEINTRO.PSetState => Code _ (AST.External PTHREADINIT.PSetState)\n        | PQUEUEINTRO.PSetPrev => Code _ (AST.External PTHREADINIT.PSetPrev)\n        | PQUEUEINTRO.PSetNext => Code _ (AST.External PTHREADINIT.PSetNext)\n        | PQUEUEINTRO.PGetHead => SourceFun (Clight.Internal PTHREADINITCODE.f_get_head) (AST.Internal nil)\n        | PQUEUEINTRO.PGetTail => SourceFun (Clight.Internal PTHREADINITCODE.f_get_tail) (AST.Internal nil)\n        | PQUEUEINTRO.PSetHead => SourceFun (Clight.Internal PTHREADINITCODE.f_set_head) (AST.Internal nil)\n        | PQUEUEINTRO.PSetTail => SourceFun (Clight.Internal PTHREADINITCODE.f_set_tail) (AST.Internal nil)\n        | PQUEUEINTRO.PTDQInit => SourceFun (Clight.Internal PTHREADINITCODE.f_tdq_init) (AST.Internal nil)\n        | PQUEUEINTRO.PPTIn => Code _ (AST.External PTHREADINIT.PPTIn)\n        | PQUEUEINTRO.PPTOut => Code _ (AST.External PTHREADINIT.PPTOut)\n        | PQUEUEINTRO.PTrapIn => Code _ (AST.External PTHREADINIT.PTrapIn)\n        | PQUEUEINTRO.PTrapOut => Code _ (AST.External PTHREADINIT.PTrapOut)\n        | PQUEUEINTRO.PHostIn => Code _ (AST.External PTHREADINIT.PHostIn)\n        | PQUEUEINTRO.PHostOut => Code _ (AST.External PTHREADINIT.PHostOut)\n        | PQUEUEINTRO.PTrapGet => Code _ (AST.External PTHREADINIT.PTrapGet)\n        | PQUEUEINTRO.PTrapRet => Code _ (AST.External PTHREADINIT.PTrapRet)\n        | PQUEUEINTRO.PThreadInit => Code _ (AST.External PTHREADINIT.PThreadInit)\n      end.\n\n    Notation varkind := (varkind unit Ctypes.type).\n\n    Definition source_implem_new_globs : list (ident * option (globdef funkind varkind)) :=\n        (TDQPool_LOC, Some (Gvar (mkglobvar (SourceVar (tarray t_struct_TDQ (num_chan+1)) tt) ((Init_space ((num_chan+1)*8))::nil) false)))\n        :: nil.\n\n    Let NOREPET: list_norepet (TDQPool_LOC :: nil).\n    Proof.\n      case_eq (list_norepet_dec peq (TDQPool_LOC :: nil)); try discriminate; tauto.\n    Qed.\n\n    Definition source_implem : source_implem Asm.code unit PQUEUEINTRO.primOp (low := PTHREADINIT.primOp) (Clight.fundef (external_function := PTHREADINIT.primOp)) Ctypes.type.\n    Proof.\n      split.\n       exact source_implem_extfuns.\n       exact source_implem_new_globs.\n    Defined.\n\n    Let im : implem Asm.code unit PQUEUEINTRO.primOp (low := PTHREADINIT.primOp) := implem_of_source_implem transf_clight_fundef Cshmgen.transl_globvar source_implem.\n\n    Notation Hprogram := (Asm.program (external_function:= PQUEUEINTRO.primOp)). \n    Notation Lprogram := (Asm.program (external_function:= PTHREADINIT.primOp)).\n\n    Let Im_get_head: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PQUEUEINTRO.PGetHead).\n    Let Im_get_tail: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PQUEUEINTRO.PGetTail).\n    Let Im_set_head: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PQUEUEINTRO.PSetHead).\n    Let Im_set_tail: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PQUEUEINTRO.PSetTail).\n    Let Im_tdq_init: Lfundef := transf_source_fun' transf_clight_fundef (source_implem_extfuns PQUEUEINTRO.PTDQInit).\n\n    Notation new_glbl := (new_glbl (num_chan:= num_chan) TDQPool_LOC).\n\n    Definition impl_glbl :  list (ident * option (globdef Lfundef unit)) := nil.\n\n    (* This is basically an axiom that can be easily checked because PQUEUEINTRO.primOp is a finite type. However, in practice, generation of CertiKOS code will be very slow because compilation will have to occur twice, one for this check, and a second independently for the generation of the actual code. *)\n\n    Lemma extfun_compilation_succeeds_dec:\n      {forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm} +\n      {~ forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm}.\n    Proof.\n      apply hprim_finite_type.\n      intro.\n      destruct (source_implem_extfuns p); try (left; discriminate).\n      case_eq (transf_clight_fundef sf).\n       left. intros. inv H0. eauto.\n      intros. right. intro. exploit H0; eauto. destruct 1. congruence.\n    Defined.\n\n    Hypothesis extfun_compilation_succeeds:\n      forall p clight asmfallback, \n        source_implem_extfuns p = SourceFun clight asmfallback ->\n        exists asm, transf_clight_fundef clight = OK asm.\n\n    Section WithProg.\n\n    Variable prog: Hprogram.\n\n    Definition tprog: Lprogram := Implementation.transf_program im prog.\n\n    Let TRANSF: QUEUEINTROGEN.transf_program (num_chan:= num_chan) Im_get_head Im_get_tail Im_set_head Im_set_tail Im_tdq_init TDQPool_LOC impl_glbl prog = OK tprog.\n    Proof.\n      unfold tprog.\n      unfold Asm.program, Asm.fundef.\n      generalize (transf_program_eq im prog).\n      intros.\n      rewrite <- H.\n      unfold transf_program.\n      simpl.\n      f_equal.\n      apply FunctionalExtensionality.functional_extensionality.\n      destruct x; simpl.\n       reflexivity.\n      destruct p; reflexivity.\n    Qed.\n\n    Hypothesis prog_nonempty:\n      prog_defs_names prog <> nil.\n\n    Hypothesis prog_main_valid:\n      ~ Plt' (prog_main prog) (prog_first_symbol prog).\n\n    Hypothesis prog_first_valid:\n      ~ Plt' (prog_first_symbol prog) (get_next_symbol (map fst source_implem_new_globs)).\n\n    Let VALID_LOC: (TDQPool_LOC <> (prog_main prog)).\n    Proof.\n      intro.\n      exploit (get_next_symbol_prop TDQPool_LOC (map fst (source_implem_new_globs))).\n      simpl; tauto. \n      eapply Ple_not_Plt.\n      apply Ple_Ple'.\n      eapply Ple'_trans.\n      apply not_Plt'_Ple'.\n      eassumption.\n      apply not_Plt'_Ple'.\n      congruence.\n    Qed.       \n\n    Notation ge := (Genv.globalenv prog).\n    Notation tge := (Genv.globalenv tprog).\n        \n    Let NEW_INJ:  (forall s', Genv.find_symbol ge s' <> None -> \n                                     ~ In s' (map fst new_glbl)).\n    Proof.\n      change new_glbl with (implem_new_globs im).\n      eapply new_ids_fresh.\n      assumption.\n    Qed.\n\n    Let sprog : Clight.program (external_function := PTHREADINIT.primOp) := source_program_only source_implem prog.\n    Let sge := Genv.globalenv sprog.\n\n    Let tsprog_strong : {tsprog | transf_clight_program sprog = OK tsprog}.\n    Proof.\n      case_eq (transf_clight_program sprog); eauto.\n      intros. exfalso.\n      refine (_ (Implementation.compilation_succeeds\n                    transf_clight_fundef\n                    Cshmgen.transl_globvar\n                    source_implem _ _ _\n                    prog)).\n      destruct 1.\n      exploit (transf_clight_fundef_to_program (external_function := PTHREADINIT.primOp)); eauto.\n      unfold sprog in H.\n      congruence.\n      assumption.\n      simpl. destruct 1; try discriminate. destruct H0; try discriminate. \n      unfold Cshmgen.transl_globvar. eauto.\n    Qed.\n\n    Let tsprog := let (p, _) := tsprog_strong in p.\n\n    Let tsprog_prop : transf_clight_program sprog = OK tsprog.\n    Proof.\n      unfold tsprog.\n      destruct tsprog_strong.\n      assumption.\n    Qed.\n\n    Let tsge := Genv.globalenv tsprog.\n    \n    Lemma tdqpool_loc_prop:\n      forall b0,\n        Genv.find_symbol tge TDQPool_LOC = Some b0 ->\n        Genv.find_symbol sge TDQPool_LOC = Some b0 /\\\n        Clight.type_of_global sge b0 = Some (tarray t_struct_TDQ (num_chan+1)).\n    Proof.\n      intros.\n      refine (_ (find_new_var_prop _ _ source_implem NOREPET _ NEW_INJ\n                                   TDQPool_LOC\n                                   (mkglobvar (SourceVar (tarray t_struct_TDQ (num_chan+1)) tt) ((Init_space ((num_chan+1)*8))::nil) false)\n                                   _ (refl_equal _) H)).\n      destruct 1.\n      split; auto.\n      unfold Clight.type_of_global.\n      unfold sge, sprog.\n      rewrite H1.\n      reflexivity.\n      simpl; tauto.\n    Qed.\n\n    Let well_idglob_impl_glbl: Genv.well_idglob_list impl_glbl = true.\n    Proof. reflexivity. Qed.\n\n    Let TDQPool_LOC_not_in: ~ In TDQPool_LOC (prog_defs_names prog).\n    Proof.\n      intro. exploit Genv.find_symbol_exists_ex; eauto. destruct 1.\n      assert (Genv.find_symbol ge TDQPool_LOC <> None) by congruence.\n      eapply NEW_INJ; eauto.\n      simpl; tauto.\n    Qed.\n\n    Lemma tprog_first_next:\n      prog_first_symbol tprog = get_first_symbol (map fst source_implem_new_globs) /\\\n      prog_next_symbol  tprog = prog_next_symbol prog.\n    Proof.\n      change (get_first_symbol (map fst source_implem_new_globs)) with (implem_first_symbol im).\n      unfold tprog.\n      apply transf_program_first_next_symbol.\n      assumption.\n      assumption.\n      discriminate.\n    Qed.\n\n    Lemma tprog_main_valid:\n      ~ Plt' (prog_main tprog) (prog_first_symbol tprog).\n    Proof.\n      Opaque Plt'.\n      simpl.\n      destruct tprog_first_next.\n      rewrite H.\n      apply Ple'_not_Plt'.\n      eapply Ple'_trans.\n      apply first_le_next.\n      discriminate.\n      eapply Ple'_trans.\n      apply not_Plt'_Ple'.\n      eassumption.\n      apply not_Plt'_Ple'.\n      assumption.\n    Qed.\n\n    Lemma tprog_nonempty:\n      prog_defs_names tprog <> nil.\n    Proof.\n      apply transf_program_nonempty.\n      assumption.\n    Qed.\n\n    Context `{PageFaultHandler_LOC: ident}.\n\n    Section WITHMEM.\n      \n      Context {mem__H} {mem__L}\n              `{Hlmmh: !LayerMemoryModel HDATA mem__H}\n              `{Hlmml: !LayerMemoryModel LDATA mem__L}\n              `{Hlmi: !LayerMemoryInjections HDATA LDATA _ _}.\n\n      Instance HLayer: LayerDefinition (layer_mem:= Hlmmh) HDATA PQUEUEINTRO.primOp mem__H :=\n        PQUEUEINTRO.layer_def (Hnpc:=Hnpc)(PgSize:=PgSize) (num_proc:=num_proc)(HPS4:=HPS4)(Hlow:=Hlow)(Hhigh:=Hhigh)\n                              (kern_low:=kern_low) (kern_high:=kern_high) (maxpage:=maxpage) (real_tcb := real_tcb)\n                              (real_nps:=real_nps) (real_AT := real_AT)(real_ptp:=real_ptp)(real_pt:=real_pt) \n                              (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)\n                              (num_chan:= num_chan).\n      \n      Instance LLayer: LayerDefinition (layer_mem:= Hlmml) LDATA PTHREADINIT.primOp mem__L :=\n        PTHREADINIT.layer_def (Hnpc:=Hnpc)(PgSize:=PgSize) (num_proc:=num_proc)(HPS4:=HPS4)(Hlow:=Hlow)(Hhigh:=Hhigh)\n                              (kern_low:=kern_low) (kern_high:=kern_high) (maxpage:=maxpage) (real_tcb := real_tcb)\n                              (real_nps:=real_nps) (real_AT := real_AT)(real_ptp:=real_ptp)(real_pt:=real_pt) \n                              (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC). \n\n      Notation LLoad := (PTHREADINIT.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation LStore := (PTHREADINIT.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation HLoad := (PQUEUEINTRO.exec_loadex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n      Notation HStore := (PQUEUEINTRO.exec_storeex (PgSize:=PgSize)(NPT_LOC:= NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC)).\n\n      Notation lstep := (PTHREADINIT.step (NPT_LOC:=NPT_LOC) (PageFaultHandler_LOC:= PageFaultHandler_LOC) (HPS4:= HPS4)\n                                          (real_nps:= real_nps) (real_AT:= real_AT) (Hlow:= Hlow) (Hhigh:= Hhigh)\n                                          (real_ptp := real_ptp) (real_pt:= real_pt) (Hnpc := Hnpc) (real_ptb:= real_ptb)\n                                          (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)(real_tcb:=real_tcb)).\n\n      Notation LADT := PTHREADINIT.ADT.\n\n      Let get_head_spec:\n        forall r' b m'0 n b1 r sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_get_head)\n          -> Genv.find_symbol tge TDQPool_LOC = Some b1\n          -> Mem.load Mint32 m'0 b1 (Int.unsigned n * 8) = Some (Vint r)\n          -> 0 <= (Int.unsigned n) <= num_chan\n          -> PTHREADINIT.ipt (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b1 = Some Tag_global\n          -> sig = mksignature (Tint :: nil) (Some Tint)\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> Genv.find_funct_ptr ge b = Some (External PQUEUEINTRO.PGetHead)\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint n ::  nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m'0)) f' \n               /\\ Memtype.Mem.inject f' m'0 m0'\n               /\\ Mem.nextblock m'0 <= Mem.nextblock m0'              \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ r_ # (loc_external_result sig) = (Vint r)\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n        Proof.\n          intros.          \n          exploit tdqpool_loc_prop; eauto.\n          destruct 1.\n          exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                     PQUEUEINTRO.primOp\n                     (exec_load := LLoad)\n                     (exec_store := LStore)\n                     (primitive_call := PTHREADINIT.primitive_call)\n                     (is_primitive_call := PTHREADINIT.is_primitive_call)\n                     (kernel_mode := PTHREADINIT.kernel_mode)\n                  ).\n          apply PTHREADINIT.exec_load_exec_loadex.\n          apply PTHREADINIT.exec_store_exec_storeex.\n          apply PTHREADINIT.extcall_not_primitive.\n          apply PTHREADINIT.primitive_kernel_mode.\n          3: eassumption.\n          assumption.\n          assumption.\n          2: eassumption.\n          5: eassumption.\n          9: eassumption.\n          7: reflexivity.\n          intros; eapply PTHREADINITCODE.get_head_correct; eauto.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          unfold PTHREADINIT.kernel_mode.\n          destruct (PTHREADINIT.INV (Mem.get_abstract_data m'0)).\n          auto.\n          destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n          inv H21.\n          eauto 11.\n        Qed.\n\n      Let get_tail_spec:\n        forall r' b m'0 n b1 r sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_get_tail)\n          -> Genv.find_symbol tge TDQPool_LOC = Some b1\n          -> Mem.load Mint32 m'0 b1 (Int.unsigned n * 8 + 4) = Some (Vint r)\n          -> 0 <= (Int.unsigned n) <= num_chan\n          -> PTHREADINIT.ipt (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b1 = Some Tag_global\n          -> sig = mksignature (Tint :: nil) (Some Tint)\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> Genv.find_funct_ptr ge b = Some (External PQUEUEINTRO.PGetTail)\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint n ::  nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m'0)) f' \n               /\\ Memtype.Mem.inject f' m'0 m0'\n               /\\ Mem.nextblock m'0 <= Mem.nextblock m0'              \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ r_ # (loc_external_result sig) = (Vint r)\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n        Proof.\n          intros.          \n          exploit tdqpool_loc_prop; eauto.\n          destruct 1.\n          exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                     PQUEUEINTRO.primOp\n                     (exec_load := LLoad)\n                     (exec_store := LStore)\n                     (primitive_call := PTHREADINIT.primitive_call)\n                     (is_primitive_call := PTHREADINIT.is_primitive_call)\n                     (kernel_mode := PTHREADINIT.kernel_mode)\n                  ).\n          apply PTHREADINIT.exec_load_exec_loadex.\n          apply PTHREADINIT.exec_store_exec_storeex.\n          apply PTHREADINIT.extcall_not_primitive.\n          apply PTHREADINIT.primitive_kernel_mode.\n          3: eassumption.\n          assumption.\n          assumption.\n          2: eassumption.\n          5: eassumption.\n          9: eassumption.\n          7: reflexivity.\n          intros; eapply PTHREADINITCODE.get_tail_correct; eauto.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          assumption.\n          unfold PTHREADINIT.kernel_mode.\n          destruct (PTHREADINIT.INV (Mem.get_abstract_data m'0)).\n          auto.\n          destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n          inv H21.\n          eauto 11.\n        Qed.\n\n    Let set_head_spec:\n      forall r' b m'0 n b0 m0 i sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_set_head) (*implementation Im_setRA has type ident-> code*)\n          -> Genv.find_symbol tge TDQPool_LOC = Some b0\n          -> Mem.store Mint32 m'0 b0 (Int.unsigned n * 8) (Vint i) = Some m0\n          -> 0 <= Int.unsigned n <= num_chan\n          -> PTHREADINIT.ipt (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b0 = Some Tag_global\n          -> sig = mksignature (Tint :: Tint :: nil) None\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> Genv.find_funct_ptr ge b = Some (External PQUEUEINTRO.PSetHead)\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint n :: Vint i:: nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m0)) f' \n               /\\ Memtype.Mem.inject f' m0 m0'\n               /\\ Mem.nextblock m0 <= Mem.nextblock m0'                    \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ True\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n    Proof.\n      intros.\n      exploit tdqpool_loc_prop; eauto.\n      destruct 1.      \n      exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                 PQUEUEINTRO.primOp\n                 (exec_load := LLoad)\n                 (exec_store := LStore)\n                 (primitive_call := PTHREADINIT.primitive_call)\n                 (is_primitive_call := PTHREADINIT.is_primitive_call)\n                 (kernel_mode := PTHREADINIT.kernel_mode)\n              ).\n      apply PTHREADINIT.exec_load_exec_loadex.\n      apply PTHREADINIT.exec_store_exec_storeex.\n      apply PTHREADINIT.extcall_not_primitive.\n      apply PTHREADINIT.primitive_kernel_mode.\n      3: eassumption.\n      assumption.\n      assumption.\n      2: eassumption.\n      5: eassumption.\n      9: eassumption.\n      7: reflexivity.\n      intros; eapply PTHREADINITCODE.set_head_correct; eauto.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      unfold PTHREADINIT.kernel_mode.\n      destruct (PTHREADINIT.INV (Mem.get_abstract_data m'0)).\n      auto.\n      destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ H2).\n      eauto 11.\n    Qed.\n\n    Let set_tail_spec:\n      forall r' b m'0 n b0 m0 i sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_set_tail) (*implementation Im_setRA has type ident-> code*)\n          -> Genv.find_symbol tge TDQPool_LOC = Some b0\n          -> Mem.store Mint32 m'0 b0 (Int.unsigned n * 8 + 4) (Vint i) = Some m0\n          -> 0 <= Int.unsigned n <= num_chan\n          -> PTHREADINIT.ipt (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b0 = Some Tag_global\n          -> sig = mksignature (Tint :: Tint :: nil) None\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> Genv.find_funct_ptr ge b = Some (External PQUEUEINTRO.PSetTail)\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint n :: Vint i:: nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m0)) f' \n               /\\ Memtype.Mem.inject f' m0 m0'\n               /\\ Mem.nextblock m0 <= Mem.nextblock m0'                    \n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ True\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n    Proof.\n      intros.\n      exploit tdqpool_loc_prop; eauto.\n      destruct 1.      \n      exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                 PQUEUEINTRO.primOp\n                 (exec_load := LLoad)\n                 (exec_store := LStore)\n                 (primitive_call := PTHREADINIT.primitive_call)\n                 (is_primitive_call := PTHREADINIT.is_primitive_call)\n                 (kernel_mode := PTHREADINIT.kernel_mode)\n              ).\n      apply PTHREADINIT.exec_load_exec_loadex.\n      apply PTHREADINIT.exec_store_exec_storeex.\n      apply PTHREADINIT.extcall_not_primitive.\n      apply PTHREADINIT.primitive_kernel_mode.\n      3: eassumption.\n      assumption.\n      assumption.\n      2: eassumption.\n      5: eassumption.\n      9: eassumption.\n      7: reflexivity.\n      intros; eapply PTHREADINITCODE.set_tail_correct; eauto.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      unfold PTHREADINIT.kernel_mode.\n      destruct (PTHREADINIT.INV (Mem.get_abstract_data m'0)).\n      auto.\n      destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ H2).\n      eauto 11.\n    Qed.\n\n    Let tcb_init_spec:\n      forall r' b m'0 n b0 m1 m2 sig,\n          r' PC = Vptr b Int.zero \n          -> Genv.find_funct_ptr tge b = Some (Im_tdq_init)\n          -> Genv.find_symbol tge TDQPool_LOC = Some b0\n          -> Mem.store Mint32 m'0 b0 (Int.unsigned n * 8) (Vint (Int.repr num_proc)) = Some m1\n          -> Mem.store Mint32 m1 b0 (Int.unsigned n * 8 + 4) (Vint (Int.repr num_proc)) = Some m2\n          -> 0 <= Int.unsigned n <= num_chan\n          -> PTHREADINIT.ipt (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.pe (LADT (Mem.get_abstract_data m'0)) = true\n          -> PTHREADINIT.ihost (LADT (Mem.get_abstract_data m'0)) = true\n          -> Mem.tget m'0 b0 = Some Tag_global\n          -> sig = mksignature (Tint :: nil) None\n          -> (forall b o, r' ESP = Vptr b o -> Mem.tget m'0 b = Some Tag_stack)\n          -> r' ESP <> Vundef\n          -> r' RA  <> Vundef\n          -> Genv.find_funct_ptr ge b = Some (External PQUEUEINTRO.PTDQInit)\n          -> asm_invariant tge (State r' m'0)\n          -> extcall_arguments r' m'0 sig (Vint n :: nil)                     \n          -> exists f' m0' r_, \n               inject_incr (Mem.flat_inj (Mem.nextblock m2)) f' \n               /\\ Memtype.Mem.inject f' m2 m0'\n               /\\ Mem.nextblock m2 <= Mem.nextblock m0'\n               /\\ plus lstep tge (State r' m'0) E0 (State r_ m0')\n               /\\ True\n               /\\ r_ PC = r' RA\n               /\\ r_ # ESP = r' # ESP\n               /\\ (forall l,\n                     ~In (Locations.R l) Conventions1.temporaries -> ~In (Locations.R l) Conventions1.destroyed_at_call \n                     -> Val.lessdef (r' (preg_of l)) (r_ (preg_of l))).\n    Proof.\n      intros.\n      exploit tdqpool_loc_prop; eauto.\n      destruct 1.      \n      exploit (ClightImplemExtra.bigstep_clight_to_lsem\n                 PQUEUEINTRO.primOp\n                 (exec_load := LLoad)\n                 (exec_store := LStore)\n                 (primitive_call := PTHREADINIT.primitive_call)\n                 (is_primitive_call := PTHREADINIT.is_primitive_call)\n                 (kernel_mode := PTHREADINIT.kernel_mode)\n              ).\n      apply PTHREADINIT.exec_load_exec_loadex.\n      apply PTHREADINIT.exec_store_exec_storeex.\n      apply PTHREADINIT.extcall_not_primitive.\n      apply PTHREADINIT.primitive_kernel_mode.\n      3: eassumption.\n      assumption.\n      assumption.\n      2: eassumption.\n      5: eassumption.\n      9: eassumption.\n      7: reflexivity.\n      intros; eapply PTHREADINITCODE.tdq_init_correct; eauto.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      assumption.\n      unfold PTHREADINIT.kernel_mode.\n      destruct (PTHREADINIT.INV (Mem.get_abstract_data m'0)).\n      auto.\n      destruct 1 as [? [? [? [? [? [? [? [? [? [? ?]]]]]]]]]].\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ H3).\n      rewrite (Mem.nextblock_store _ _ _ _ _ _ H2).\n      eauto 11.\n    Qed.\n\n    Theorem transf_program_correct:\n      Smallstep.backward_simulation \n          (PQUEUEINTRO.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC)  \n                                 (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= Hlmmh) (HPS4:= HPS4) (Hnpc:= Hnpc)\n                                 (Hlow := Hlow) (Hhigh:= Hhigh) (real_ptp:= real_ptp) (real_pt:= real_pt) \n                                 (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC)\n                                 (num_chan:= num_chan) (real_tcb:= real_tcb) prog) \n          (PTHREADINIT.semantics (NPT_LOC:= NPT_LOC) (PgSize:=PgSize) (PageFaultHandler_LOC:= PageFaultHandler_LOC) \n                                 (real_AT:= real_AT) (real_nps:= real_nps) (Hmem:= Hlmml) (HPS4:= HPS4) \n                                 (Hlow := Hlow) (Hhigh:= Hhigh) (real_ptp:= real_ptp) (real_pt:= real_pt)\n                                 (Hnpc:= Hnpc) (real_ptb:= real_ptb) (real_free_pt:= real_free_pt) (STACK_LOC:= STACK_LOC) \n                                 (real_tcb:= real_tcb) tprog).  \n    Proof.\n      eapply QUEUEINTROGEN.transf_program_correct; simpl; eauto.\n      Grab Existential Variables.\n      omega.\n      vm_compute; reflexivity.\n      omega.\n    Qed.\n\n    End WITHMEM.\n\n    End WithProg.\n\n End WithPrimitives.\n\nEnd QUEUEINTROGENIMPL.\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/QueueIntroGenImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15621858551198722}}
{"text": "Require Import coqutil.Z.Lia.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MetricRiscvMachine.\nRequire Import riscv.Utility.Utility.\nRequire Import coqutil.Tactics.Simp.\nRequire Import compiler.SeparationLogic.\nRequire Export coqutil.Word.SimplWordExpr.\nRequire Import compiler.GoFlatToRiscv.\nRequire Import compiler.FlatToRiscvDef.\nRequire Import compiler.FlatToRiscvCommon.\n\nSection Proofs.\n  Context {iset: Decode.InstructionSet}.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width}.\n  Context {word_ok: word.ok word}.\n  Context {locals: map.map Z word}.\n  Context {mem: map.map word byte}.\n  Context {M: Type -> Type}.\n  Context {MM: Monads.Monad M}.\n  Context {RVM: Machine.RiscvProgram M word}.\n  Context {PRParams: PrimitivesParams M MetricRiscvMachine}.\n  Context {ext_spec: Semantics.ExtSpec}.\n  Context {word_riscv_ok: RiscvWordProperties.word.riscv_ok word}.\n  Context {locals_ok: map.ok locals}.\n  Context {mem_ok: map.ok mem}.\n  Context {PR: MetricPrimitives.MetricPrimitives PRParams}.\n  Context {BWM: bitwidth_iset width iset}.\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  Local Notation RiscvMachineL := MetricRiscvMachine.\n\n  Local Arguments Z.add : simpl never.\n  Local Arguments Z.of_nat : simpl never.\n\n  Lemma save_regs_correct: forall vars offset Exec R Rexec (initial: RiscvMachineL)\n                                  p_sp oldvalues newvalues addr,\n      Forall valid_register vars ->\n      map.getmany_of_list initial.(getRegs) vars = Some newvalues ->\n      map.get initial.(getRegs) RegisterNames.sp = Some p_sp ->\n      List.length oldvalues = List.length vars ->\n      subset (footpr Exec) (of_list (initial.(getXAddrs))) ->\n      iff1 Exec (program iset initial.(getPc) (save_regs iset vars offset) * Rexec)%sep ->\n      (Exec * word_array addr oldvalues * R)%sep initial.(getMem) ->\n      addr = word.add p_sp (word.of_Z offset) ->\n      initial.(getNextPc) = word.add initial.(getPc) (word.of_Z 4) ->\n      valid_machine initial ->\n      runsTo initial (fun final =>\n          final.(getRegs) = initial.(getRegs) /\\\n          subset (footpr Exec) (of_list (final.(getXAddrs))) /\\\n          (Exec * word_array addr newvalues * R)%sep final.(getMem) /\\\n          final.(getPc) = word.add initial.(getPc) (word.mul (word.of_Z 4)\n                                                   (word.of_Z (Z.of_nat (List.length vars)))) /\\\n          final.(getNextPc) = word.add final.(getPc) (word.of_Z 4) /\\\n          final.(getLog) = initial.(getLog) /\\\n          final.(getMetrics) =\n              Platform.MetricLogging.addMetricInstructions (Z.of_nat (List.length vars))\n                (Platform.MetricLogging.addMetricStores (Z.of_nat (List.length vars))\n                   (Platform.MetricLogging.addMetricLoads (Z.of_nat (List.length vars)) initial.(getMetrics))) /\\   \n          valid_machine final).\n  Proof.\n    unfold map.getmany_of_list.\n    induction vars; intros; subst addr.\n    - simpl in *. simp. destruct oldvalues; simpl in *; [|discriminate].\n      apply runsToNonDet.runsToDone. repeat split; try assumption; try solve_word_eq word_ok.\n      destruct_RiscvMachine initial. destruct initial_metrics. MetricsToRiscv.solve_MetricLog. \n    - simpl in *. simp.\n      assert (valid_register RegisterNames.sp) by (cbv; auto).\n      destruct oldvalues as [|oldvalue oldvalues]; simpl in *; [discriminate|].\n      replace (Memory.bytes_per_word (Decode.bitwidth iset)) with bytes_per_word in *. 2: {\n        rewrite bitwidth_matches. reflexivity.\n      }\n      eapply runsToNonDet.runsToStep. {\n        eapply run_store_word.\n        7: eassumption.\n        7: {\n          etransitivity. 1: eassumption. cbn. ecancel.\n        }\n        all: try eassumption.\n        1: reflexivity.\n        use_sep_assumption; cbn; ecancel.\n      }\n      simpl. intros.\n      destruct_RiscvMachine initial.\n      destruct_RiscvMachine mid.\n      simp. subst.\n      eapply runsToNonDet.runsTo_weaken; cycle 1;\n        [|eapply IHvars with (p_sp := p_sp) (offset := (offset + bytes_per_word))\n             (newvalues := l) (R := (ptsto_word (word.add p_sp (word.of_Z offset)) r * R)%sep)]. {\n        simpl. intros. simp. destruct_RiscvMachine final.\n        repeat split; try solve [sidecondition].\n        - replace (Z.of_nat (S (List.length oldvalues)))\n            with (1 + Z.of_nat (List.length oldvalues)) by blia.\n          etransitivity; [eassumption|].\n          replace (List.length vars) with (List.length oldvalues) by blia.\n          solve_word_eq word_ok.\n        - rewrite H0p7. MetricsToRiscv.solve_MetricLog. \n      }\n      all: try eassumption.\n      + simpl in *. etransitivity. 1: eassumption. ecancel.\n      + simpl. use_sep_assumption. wcancel.\n      + solve_word_eq word_ok.\n      + reflexivity.\n  Qed.\n\n  Lemma length_save_regs: forall vars offset,\n      List.length (save_regs iset vars offset) = List.length vars.\n  Proof using BWM.\n    induction vars; intros; simpl; rewrite? IHvars; reflexivity.\n  Qed.\n\n  Lemma load_regs_correct: forall p_sp vars offset Exec R Rexec (initial: RiscvMachineL) values,\n      Forall valid_FlatImp_var vars ->\n      map.get initial.(getRegs) RegisterNames.sp = Some p_sp ->\n      List.length values = List.length vars ->\n      subset (footpr Exec) (of_list initial.(getXAddrs)) ->\n      iff1 Exec (program iset initial.(getPc) (load_regs iset vars offset) * Rexec)%sep ->\n      (Exec * word_array (word.add p_sp (word.of_Z offset)) values * R)%sep initial.(getMem) ->\n      initial.(getNextPc) = word.add initial.(getPc) (word.of_Z 4) ->\n      valid_machine initial ->\n      runsTo initial (fun final =>\n          map.putmany_of_list_zip vars values initial.(getRegs) = Some final.(getRegs) /\\\n          final.(getMem) = initial.(getMem) /\\\n          final.(getPc) = word.add initial.(getPc) (mul (word.of_Z 4)\n                                                   (word.of_Z (Z.of_nat (List.length vars)))) /\\\n          final.(getNextPc) = word.add final.(getPc) (word.of_Z 4) /\\\n          final.(getLog) = initial.(getLog) /\\\n          final.(getXAddrs) = initial.(getXAddrs) /\\\n          final.(getMetrics) =\n              Platform.MetricLogging.addMetricInstructions (Z.of_nat (List.length vars))\n                (Platform.MetricLogging.addMetricLoads (Z.of_nat (2 * (List.length vars)))\n                   initial.(getMetrics)) /\\\n          valid_machine final).\n  Proof.\n    induction vars; intros.\n    - simpl in *. simp. destruct values; simpl in *; [|discriminate].\n      apply runsToNonDet.runsToDone. repeat split; try assumption; try solve_word_eq word_ok.\n      destruct_RiscvMachine initial. destruct initial_metrics. MetricsToRiscv.solve_MetricLog. \n    - simpl in *. simp.\n      assert (valid_register RegisterNames.sp) by (cbv; auto).\n      assert (valid_register a). {\n        unfold valid_register, valid_FlatImp_var in *. blia.\n      }\n      destruct values as [|value values]; simpl in *; [discriminate|].\n      eapply runsToNonDet.runsToStep. {\n        eapply run_load_word; cycle -4; try solve [sidecondition]; sidecondition.\n      }\n      simpl. intros.\n      destruct_RiscvMachine initial.\n      destruct_RiscvMachine mid.\n      replace (Memory.bytes_per_word (Decode.bitwidth iset)) with bytes_per_word in *. 2: {\n        rewrite bitwidth_matches. reflexivity.\n      }\n      simp. subst.\n      eapply runsToNonDet.runsTo_weaken.\n      + eapply IHvars; simpl; cycle -3; auto.\n        * use_sep_assumption.\n          match goal with\n          | |- iff1 ?LHS ?RHS =>\n            match LHS with\n            | context [word_array ?i] =>\n              match RHS with\n              | context [word_array ?i'] =>\n                replace i with i'; cycle 1\n              end\n            end\n          end.\n          { rewrite <- word.add_assoc. rewrite <- word.ring_morph_add. reflexivity. }\n          ecancel.\n        * rewrite map.get_put_diff. 1: assumption.\n          unfold RegisterNames.sp, valid_FlatImp_var in *. blia.\n        * blia.\n        * eassumption.\n        * etransitivity. 1: eassumption. ecancel.\n      + simpl. intros. simp.\n        ssplit; try first [assumption|reflexivity].\n        * etransitivity; [eassumption|].\n          rewrite Znat.Nat2Z.inj_succ. rewrite <- Z.add_1_r.\n          replace (List.length values) with (List.length vars) by congruence.\n          solve_word_eq word_ok.\n        * rewrite H1p3. MetricsToRiscv.solve_MetricLog. \n  Qed.\n\n  Lemma length_load_regs: forall vars offset,\n      List.length (load_regs iset vars offset) = List.length vars.\n  Proof using BWM.\n    induction vars; intros; simpl; rewrite? IHvars; reflexivity.\n  Qed.\n\nEnd Proofs.\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/load_save_regs_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.1562185855119872}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Platform.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\nSection Note_.\n  Variable imps : LabelMap.t assert.\n  Variable mn : string.\n\n  Import DefineStructured.\n  Transparent evalInstrs.\n\n  Definition Note_ (P : Prop) : cmd imps mn.\n    red; refine (fun pre => {|\n      Postcondition := (fun st => pre st /\\ [| P |])%PropX;\n      VerifCond := P :: nil;\n      Generate := fun Base Exit => {|\n        Entry := 0;\n        Blocks := (pre, (nil, Uncond (RvLabel (mn, Local Exit)))) :: nil\n      |}\n    |}); abstract (struct; repeat esplit; eauto; propxFo).\n  Defined.\nEnd Note_.\n\nDefinition Note__ (P : Prop) : chunk := fun _ _ =>\n  Structured nil (fun _ _ _ => Note_ _ _ P).\n\nNotation \"'Note' [ P ]\" := (Note__ P) (no associativity, at level 95) : SP_scope.\n\nSection SomethingStar.\n  Variable imps : LabelMap.t assert.\n  Variable mn : string.\n\n  Fixpoint augment (specs : codeSpec W (settings * state)) (stn : settings) (ls : list (string * string)) : Prop :=\n    match ls with\n      | nil => True\n      | (mn, f) :: ls =>\n        match LabelMap.find (mn, Global f) imps with\n          | None => True\n          | Some p => (exists pc, stn.(Labels) (mn, Global f) = Some pc /\\ specs pc = Some p) /\\ augment specs stn ls\n        end\n    end.\n\n  Lemma prove_augment : forall specs stn ls,\n    (forall mn f (pre : assert),\n      LabelMap.MapsTo (mn, Global f) pre imps\n      -> exists w : W, Labels stn (mn, Global f) = Some w /\\ specs w = Some pre)\n    -> augment specs stn ls.\n    induction ls; simpl; intuition.\n    case_eq (LabelMap.find (a0, Global b) imps); intuition.\n    apply LabelMap.find_2 in H1; eauto.\n  Qed.\n\n  Import DefineStructured.\n\n  Variable ls : list (string * string).\n\n  Transparent evalInstrs.\n\n  Hint Resolve prove_augment.\n\n  Section IGotoStar.\n    Variable rv : rvalue.\n\n    Definition IGotoStar_ : cmd imps mn.\n      red; refine (fun pre => {|\n        Postcondition := (fun _ => [|False|])%PropX;\n        VerifCond := (forall specs stn st, interp specs (pre (stn, st))\n          -> augment specs stn ls\n          -> match evalRvalue stn st rv with\n               | None => rvalueCrashes rv\n               | Some w => exists pre', specs w = Some pre'\n                 /\\ interp specs (pre' (stn, st))\n             end) :: nil;\n        Generate := fun Base Exit => {|\n          Entry := 0;\n          Blocks := (pre, (nil, Uncond rv)) :: nil\n        |}\n      |}); abstract (solve [ struct\n        | intros; repeat match goal with\n                           | [ H : vcs nil |- _ ] => clear H\n                           | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; subst\n                           | [ |- List.Forall _ _ ] => constructor; simpl\n                           | [ |- blockOk _ _ _ ] => hnf; intros\n                           | [ H : forall x y z, interp _ _ -> augment _ _ _ -> _, H' : interp _ _ |- _ ] =>\n                             specialize (H _ _ _ H');\n                               match type of H with\n                                 | ?P -> _ => assert P by auto; intuition simpl\n                               end\n                           | [ H : match ?X with None => _ | _ => _ end |- _ ] => destruct X; intuition\n                           | [ H : Logic.ex _ |- _ ] => destruct H; intuition eauto\n                         end ]).\n    Defined.\n  End IGotoStar.\n\n  Section AssertStar.\n    Variable post : assert.\n\n    Definition AssertStar_ : cmd imps mn.\n      red; refine (fun pre => {|\n        Postcondition := post;\n        VerifCond := (forall stn_st specs, interp specs (pre stn_st)\n          -> augment specs (fst stn_st) ls\n          -> interp specs (post stn_st)) :: nil;\n        Generate := fun Base Exit => {|\n          Entry := 0;\n          Blocks := (pre, (nil, Uncond (RvLabel (mn, Local Exit)))) :: nil\n        |}\n      |}); abstract solve [ struct\n        | intros; repeat match goal with\n                           | [ H : vcs nil |- _ ] => clear H\n                           | [ H : vcs (_ :: _) |- _ ] => inversion H; clear H; subst\n                           | [ |- List.Forall _ _ ] => constructor; simpl\n                           | [ |- blockOk _ _ _ ] => hnf; intros\n                           | [ H : forall x y z, interp _ _ -> augment _ _ _ -> _, H' : interp _ _ |- _ ] =>\n                             specialize (H _ _ _ H');\n                               match type of H with\n                                 | ?P -> _ => assert P by auto; intuition simpl\n                               end\n                           | [ H : match ?X with None => _ | _ => _ end |- _ ] => destruct X; intuition\n                           | [ H : Logic.ex _ |- _ ] => destruct H; intuition eauto\n                           | [ H : forall l : LabelMap.key, _ |- _ ] => destruct (H (mn, Local Exit) post) as [ ? [ ] ];\n                             [ solve [ auto ] | ]; do 2 esplit; [ unfold evalBlock; simpl;\n                               match goal with\n                                 | [ H : _ |- _ ] => solve [ rewrite H; eauto ]\n                               end | simpl; do 2 esplit; eauto; match goal with\n                                                                  | [ H : _ |- _ ] => apply H; auto\n                                                                end ]\n                         end ].\n    Defined.\n  End AssertStar.\nEnd SomethingStar.\n\nDefinition IGotoStar ls (rv : rvalue') : chunk := fun ns _ =>\n  Structured nil (fun _ _ _ => IGotoStar_ _ _ ls (rv ns)).\n\nNotation \"'IGoto*' [ l1 , .. , lN ] rv\" := (IGotoStar (cons l1 (.. (cons lN nil) ..)) rv) (no associativity, at level 95) : SP_scope.\n\nDefinition AssertStar ls (post : list string -> nat -> assert) : chunk := fun ns res =>\n  Structured nil (fun _ _ _ => AssertStar_ _ _ ls (post ns res)).\n\nLocal Notation INV := (fun inv => inv true (fun w => w)).\n\nNotation \"'Assert*' [ l1 , .. , lN ] [ post ]\" := (AssertStar (cons l1 (.. (cons lN nil) ..)) (INV post)) (no associativity, at level 95) : SP_scope.\n\nRequire Import Coq.Bool.Bool.\n\nDefinition localsInvariantCont (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    ExX, Ex vs, qspecOut (pre (sel vs) st#Rv) (fun pre =>\n      ![ ^[locals (\"rp\" :: ns) vs res sp * pre] * #0 ] st).\n\nNotation \"'PREonly' [ vs ] pre\" := (localsInvariantCont (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nNotation \"'PREonly' [ vs , rv ] pre\" := (localsInvariantCont (fun vs rv => pre%qspec%Sep))\n  (at level 89).\n\nNotation \"'bfunctionNoRet' name () [ p ] b 'end'\" :=\n  (let p' := p in\n   let vars := nil in\n   let b' := b%SP in\n    {| FName := name;\n      FPrecondition := Precondition p' None;\n      FBody := ((fun _ _ =>\n        Structured nil (fun im mn _ => Structured.Assert_ im mn (Precondition p' (Some vars))));;\n      (fun ns res => b' ns (res - (List.length vars - List.length (Formals p')))%nat))%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\nNotation \"'bfunctionNoRet' name ( x1 , .. , xN ) [ p ] b 'end'\" :=\n  (let p' := p in\n   let vars := cons x1 (.. (cons xN nil) ..) in\n   let b' := b%SP in\n    {| FName := name;\n      FPrecondition := Precondition p' None;\n      FBody := ((fun _ _ =>\n        Structured nil (fun im mn _ => Structured.Assert_ im mn (Precondition p' (Some vars))));;\n      (fun ns res => b' ns (res - (List.length vars - List.length (Formals p')))%nat))%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\n(* added Conditional *)\nRequire Import Platform.Conditional.\nExport Conditional.\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 localsInvariantCont\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 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\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\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\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         (** Array8 *)\n         Array8.ssig Array8.types_r Array8.types\n         Array8.MemEval Array8.MemEvaluator\n         Array8.deref Array8.sym_read Array8.sym_write\n         Array8.blength_r Array8.sel_r Array8.upd_r Array8.BtoW_r Array8.WtoB_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\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\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         (** Array8 *)\n         Array8.ssig Array8.types_r Array8.types\n         Array8.MemEval Array8.MemEvaluator\n         Array8.deref Array8.sym_read Array8.sym_write\n         Array8.blength_r Array8.sel_r Array8.upd_r Array8.BtoW_r Array8.WtoB_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\nTheorem unandL : forall pc state specs (P Q R : PropX pc state),\n  interp specs (P /\\ Q ---> R)%PropX\n  -> interp specs (P ---> Q ---> R)%PropX.\n  intros; do 2 apply Imply_I.\n  eapply Imply_E; eauto.\n  apply And_I; eapply Env; simpl; eauto.\nQed.\n\nLemma breakout : forall A (P : A -> _) Q R x specs,\n  (forall v, interp specs (![P v * Q] x ---> R)%PropX)\n  -> interp specs (![exB P * Q] x ---> R)%PropX.\n  rewrite sepFormula_eq; propxFo.\n  unfold sepFormula_def, exB, ex.\n  simpl.\n  repeat (apply existsL; intros).\n  apply andL; apply injL; intro.\n  apply andL.\n  apply existsL; intro.\n  apply unandL.\n  eapply Imply_trans; try apply H; clear H.\n  do 2 eapply existsR.\n  simpl.\n  repeat apply andR.\n  apply injR; eauto.\n  apply andL; apply implyR.\n  apply Imply_refl.\n  apply andL; apply swap; apply implyR.\n  apply Imply_refl.\nQed.\n\nLtac imply_simp'' := match goal with\n                       | [ |- interp _ (PropX.Inj _ ---> _) ] => apply injL; intro\n                       | [ |- interp _ (PropX.Cptr _ _ ---> _) ] => apply cptrL; intro\n                       | [ |- interp _ (PropX.And _ _ ---> _) ] => apply andL\n                       | [ |- interp _ (PropX.Exists _ ---> _) ] => apply existsL; intro\n                     end.\n\nLtac toFront' which P k :=\n  match P with\n    | SEP.ST.star ?Q ?R =>\n      toFront' which Q ltac:(fun it P' => k it (SEP.ST.star P' R))\n      || toFront' which R ltac:(fun it P' => k it (SEP.ST.star P' Q))\n    | (?Q * ?R)%Sep =>\n      toFront' which Q ltac:(fun it P' => k it (SEP.ST.star P' R))\n      || toFront' which R ltac:(fun it P' => k it (SEP.ST.star P' Q))\n    | _ => which P; k P (@SEP.ST.emp W (settings * state) nil)\n  end.\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            end\n        end;\n    progress cancel ext in\n\n let exBegone :=\n   match goal with\n     | [ |- interp ?specs (![ ?P ] ?x ---> ?Q)%PropX ] =>\n       match P with\n         | context[exB] =>\n           toFront' ltac:(fun R => match R with\n                                     | exB _ => idtac\n                                   end) P\n           ltac:(fun it P' =>\n             apply Imply_trans with (![ it * P'] x)%PropX; [ cancel auto_ext | ])\n       end\n   end; repeat match goal with\n                 | [ |- interp _ (![ exB _ * _] _ ---> _)%PropX ] => apply breakout; intro\n               end in\n\n try match goal with\n       | [ |- interp _ (?P ---> _)%PropX ] =>\n         match P with\n           | context[exB] => repeat imply_simp''; descend; repeat exBegone\n         end\n     end;\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 NoDup := repeat constructor; simpl; intuition congruence.\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; [ NoDup\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; [ NoDup\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; [ NoDup\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 reassociate [H]\n * to put [P] in front. *)\nLtac toFront which H :=\n  match type of H with\n    | interp ?specs (![ ?P ] ?st) => toFront' which 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(* Just like [toFront], but for the conclusion rather than a hypothesis *)\nLtac toFront_conc which :=\n  match goal with\n    | [ |- interp ?specs (![ ?P ] ?st) ] => toFront' which P ltac:(fun it P' =>\n      let H := fresh \"H\" in assert (H : interp specs (![ SEP.ST.star it P' ] st)); [ |\n        generalize dependent H;\n          repeat match goal with\n                   | [ H : interp _ _ |- _ ] => clear H\n                 end; intro; eapply Imply_sound; [ eapply sepFormula_himp_imply | ];\n          [ | reflexivity | eassumption ]; solve [ step auto_ext ] ])\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\nDefinition any : HProp := fun _ _ => [| True |]%PropX.\n\nTheorem any_easy : forall P, P ===> any.\n  unfold any; repeat intro; step auto_ext; auto.\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/PreAutoSep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3073580232098525, "lm_q1q2_score": 0.1560800507673662}}
{"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.Global.\nRequire Import MPST.Local.\n\nRequire Import MPST.Projection.IProject.\nRequire Import MPST.Projection.CProject.\n\nLemma partof_all_unroll G CG p L n :\n  g_closed G ->\n  GUnroll G CG -> project simple_merge G p == Some L ->\n  depth_part n p G -> part_of_all p CG.\nProof.\n  elim: n G CG L=>// n Ih [||G|F T C] //= CG L cG; rewrite -/prj_all.\n  - case PRJ: project=>[L0|]//; move: PRJ=>/eqP-PRJ.\n    case: ifP; first by move=>/(lbinds_depth _ PRJ)->.\n    move=> NB /gunroll_unfold; elim/gunr_inv=>// _ IG CG0 GU [EQ1] EQ2 _ DP.\n    move: EQ1 EQ2 GU DP=>//-> _ []//GU /(depthpart_open 0 (g_rec G))-DP.\n    move: NB PRJ=>/eqP-NB /eqP-PRJ; move: (project_open NB cG PRJ)=>{}/eqP-P.\n    by move: cG=>/gopen_closed/Ih/(_ GU P DP).\n  - move=>/gunroll_unfold; elim/gunr_inv=>// _ F' T' C' CC DOM UA E1 _ {CG}.\n    move: E1 DOM UA=>[->->->] DOM UA {F' T' C'}; rewrite -/(prj_all _ _).\n    case PRJ: prj_all=>[Ks|]//; case: ifP=>// FT.\n    case: ifP=>[/eqP<- _|pF]; first by constructor.\n    case: ifP=>[/eqP<- _|pT]; first by constructor.\n    move=>MRG; rewrite eq_sym pF eq_sym pT/= => DP.\n    apply: pall_cont=>l Ty CG CCl.\n    move: (dom' DOM CCl)=>[G'] Cl.\n    move: (UA _ _ _ _ Cl CCl)=>[|//].\n    move: (prj_all_find PRJ Cl)=>[L'][_]/eqP-{}PRJ GU.\n    move: (find_member Cl)=>M.\n    apply: (Ih _ _ _ _ GU PRJ).\n    * by move: cG; rewrite /g_closed/= flatten_eq_nil=>/member_map/(_ _ M).\n    * by move: DP =>/forallbP/forall_member/member_map/(_ _ M).\nQed.\n\nLemma partof_unroll G CG p :\n  g_closed G ->\n  guarded 0 G ->\n  GUnroll G CG ->\n  part_of p CG ->\n  p \\in participants G.\nProof.\n  move=> cG gG GU PART.\n  elim: PART=>[F T C| F T C|{}p F T C l G0 Ty Cl PART Ih] in G cG gG GU *.\n  - apply: r_in_unroll_rec_depth; move: GU=>/(GUnroll_ind (rec_depth G)).\n    move: (n_unroll (rec_depth G) G) (unroll_guarded cG gG)=>{cG gG}G NR GU.\n    move: GU NR=>/gunroll_unfold; elim/gunr_inv =>// _;\n      first by move=> IG _ _ _ _ /(_ IG); rewrite eq_refl.\n    by move=> F' T' C' CG' _ _ _ [->] _ _ _; rewrite in_cons eq_refl.\n  - apply: r_in_unroll_rec_depth; move: GU=>/(GUnroll_ind (rec_depth G)).\n    move: (n_unroll (rec_depth G) G) (unroll_guarded cG gG)=>{cG gG}G NR GU.\n    move: GU NR=>/gunroll_unfold; elim/gunr_inv =>// _;\n      first by move=> IG _ _ _ _ /(_ IG); rewrite eq_refl.\n    by move=> F' T' C' CG' _ _ _ [] _ <- _ _; rewrite in_cons orbC in_cons eq_refl.\n  - apply: r_in_unroll_rec_depth; move: GU=>/(GUnroll_ind (rec_depth G)).\n    move: (g_guarded_nunroll (rec_depth G) cG gG) (unroll_guarded cG gG).\n    move: (n_unroll (rec_depth G) G) (g_closed_unroll (rec_depth G) cG).\n    move=>{cG gG}G cG gG NR GU.\n    move: GU NR cG gG =>/gunroll_unfold; elim/gunr_inv =>// _;\n      first by move=> IG _ _ _ _ /(_ IG); rewrite eq_refl.\n    move=> F' T' C' CG' DOM UA E1 E2 _ .\n    rewrite /g_closed/==>/flatten_eq_nil/member_map-cG.\n    move=>/forallbP/forall_member=>gG.\n    move: E1 E2 cG gG DOM UA=>_ [->->->] cG gG DOM UA {G F' T' CG'}.\n    suff: p \\in flatten [seq participants K.2.2 | K <- C']\n      by rewrite !in_cons=>->; rewrite orbC orbT.\n    move: (dom' DOM Cl)=>[G FND]; move: (find_member FND)=>M.\n    move: (UA _ _ _ _ FND Cl)=>[GU|//].\n    apply/flatten_mapP; exists (l, (Ty, G)); first by apply/memberP.\n    by apply/(Ih _ (cG _ M) (gG _ M) GU).\nQed.\n\nNotation CIH4 X Y H1 H2 H3 H4 H5\n  := (ex_intro (fun=>_) X\n               (ex_intro (fun=>_) Y\n                         (conj H1 (conj H2 (conj H3 (conj H4 H5)))))).\nLemma project_wf G p L CG :\n  g_closed G ->\n  guarded 0 G ->\n  non_empty_cont G ->\n  project simple_merge G p == Some L ->\n  GUnroll G CG -> WF CG.\nProof.\n  move=>H1 H2 NE H3 H4; move: (CIH4 L G H1 H2 NE H3 H4)=> {H1 H2 NE H3 H4 G L}.\n  move: CG; apply/paco1_acc=>r _ /(_ _ (CIH4 _ _ _ _ _ _ _))-CIH.\n  move=> CG [L] [G] [cG [gG [NE [PRJ GU]]]]; apply/paco1_fold.\n  move: (unroll_guarded cG gG); move: PRJ=>/eqP-PRJ.\n  move: (project_unroll (rec_depth G) cG PRJ)=>[n1][n2][L'][{}PRJ] _.\n  move: GU=>/(GUnroll_ind (rec_depth G)); move: PRJ.\n  move: gG=>/(g_guarded_nunroll (rec_depth G) cG).\n  move: cG=>/(g_closed_unroll (rec_depth G)).\n  move: NE=>/(ne_unr (rec_depth G)).\n  move: (n_unroll (rec_depth G) G) => {}G; move: L'=>{}L {n1 n2}.\n  case: G =>/=; rewrite -/prj_all.\n  - by move=>_ _ _ _  /gunroll_unfold; elim/gunr_inv=>//; constructor.\n  - by move=>v /=; rewrite /g_closed/=.\n  - by move=>G _ _ _ _ _ /(_ G); rewrite eq_refl.\n  - rewrite /g_closed; move=> F T C NE /= /flatten_eq_nil/member_map-cC.\n    move=>/forallbP/forall_member-gG; rewrite -/(prj_all _ _).\n    case PRJ: prj_all =>[L'|//]; move: PRJ=>/eqP-PRJ.\n    case: ifP=>// FT _; move=>/gunroll_unfold.\n    have CNE: C != [::] by case: C NE {cC gG PRJ}.\n    have {}NE: all id [seq non_empty_cont K.2.2 | K <- C]\n      by case: C NE {CNE cC gG PRJ}.\n    move: NE=>/forallbP/forall_member/member_map-NE.\n    elim/gunr_inv => // _ F' T' C' CC DOM UA E1 _ _ {CG}.\n    move: E1 DOM UA=>[->->->] DOM UA {F' T' C'}; constructor; rewrite ?FT//.\n    * move=> l Ty G CCl; right; move: (dom' DOM CCl)=>[G']FND.\n      move: PRJ=>/eqP-PRJ; move: (prj_all_find PRJ FND)=>[L0][_]/eqP-{}PRJ.\n      move: (UA _ _ _ _ FND CCl) (find_member FND)=>[GU|//] M.\n        by apply (CIH _ _ _ (cC _ M) (gG _ M) (NE _ M) PRJ GU).\n    * case: C CNE DOM {cC gG PRJ NE UA}=>//[][l [Ty G]] Ks _.\n      have FND: find_cont ((l, (Ty, G)) :: Ks) l = Some (Ty, G)\n        by rewrite/find_cont/extend eq_refl.\n        by move=>DOM; move: (dom DOM FND)=> CCl; exists l, Ty.\nQed.\n\nLemma lunroll_merge r L CL CONT Ks\n      (LU : LUnroll L CL)\n      (PRJ : prj_all simple_merge CONT r = Some Ks)\n      (MRG : simple_merge L [seq K.2.2 | K <- Ks] = Some L)\n  : exists CCL,\n      same_dom (find_cont Ks) CCL /\\ simple_co_merge CCL CL.\nProof.\n  set CCL := fun l =>\n               match find_cont Ks l with\n               | Some (Ty, _) => Some (Ty, CL)\n               | None => None\n               end.\n  exists CCL; split.\n  - move=> l Ty; split=>[][G]; rewrite /CCL/=.\n    + by move=>->; exists CL.\n    + by case: find_cont=>// [][Ty' G'][<-_]; exists G'.\n  - rewrite /CCL=>l Ty L'; case: find_cont=>//[][Ty' G'][_]->.\n    by apply/EqL_refl.\nQed.\n\nLemma project_nonrec (r0 : proj_rel ) r CL CG L G\n      (CIH : forall cG cL iG iL,\n          g_closed iG ->\n          guarded 0 iG ->\n          non_empty_cont iG ->\n          project simple_merge iG r == Some iL ->\n          GUnroll iG cG ->\n          LUnroll iL cL ->\n          r0 cG cL)\n      (cG : g_closed G)\n      (gG : guarded 0 G)\n      (NE : non_empty_cont G)\n      (nrG : forall G' : g_ty, G != g_rec G')\n      (iPrj : project simple_merge G r = Some L)\n      (GU : GUnroll G CG)\n      (LU : LUnroll L CL)\n  : paco2 (Proj_ simple_co_merge r) r0 CG CL.\nProof.\n  move: (closed_not_var cG).\n  case: (boolP (r \\notin participants G)); [| rewrite negbK].\n  - move=> PARTS nvG; move: iPrj=>/eqP-iPrj.\n    move: (proj1 (project_parts cG iPrj) PARTS)=> endL.\n    move: (lunroll_isend LU endL)=>->; apply/paco2_fold.\n    constructor; first by move=>/(partof_unroll cG gG GU)-P'; move: P' PARTS=>->.\n    by apply/(project_wf cG gG NE iPrj).\n  - case: G cG gG NE nrG iPrj GU=>//;\n            first by move=> GT _ _ _ /(_ GT); rewrite eq_refl.\n    move=>FROM TO CONT; rewrite project_msg /g_closed/=.\n    move=>/flatten_eq_nil/member_map-cG /forallbP/forall_member-gG.\n    move=>/andP-[NE_C /forallbP/forall_member/member_map-NE] _ I_prj GU PARTS _.\n    move: GU; move=>/gunroll_unfold.\n    case E: _ _/ =>// [FROM' TO' CONT' CC DOM GU].\n    move: E DOM GU=> [<-<-<-] {FROM' TO' CONT'} DOM GU.\n    apply/paco2_fold; move: I_prj.\n    case E: prj_all=>[KsL|]//; case:ifP=>// F_neq_T.\n    case:ifP=>[F_r | F_ne_r].\n    + move=>[EL]; move: EL LU=><- {L} /lu_unfold-LU.\n      case EL: _ _/LU=>[||a p Ks C LD LU]//; move: EL LD LU=>[<-<-<-] LD LU {a p Ks}.\n      move: (prjall_dom E)=>iDOM.\n      move: F_r CIH E=>/eqP<- CIH E; apply/prj_send; first by apply/negPf.\n      * by apply/(same_dom_trans\n                    (same_dom_trans ((same_dom_sym _ _).1 DOM) iDOM)).\n      * move=> l Ty G G' CCl Cl; right; move: (dom' DOM CCl)=>[iG FND].\n        move: (GU _ _ _ _ FND CCl)=>[{}GU|//].\n        move: (dom iDOM FND)=>[iL FND'].\n        move: (LU _ _ _ _ FND' Cl)=>[{}LU|//].\n        move: (prjall_fnd E FND FND')=>/eqP-PRJ.\n        move: (find_member FND)=>M.\n        by apply: (CIH _ _ _ _ (cG _ M) (gG _ M) (NE _ M) PRJ GU LU).\n    + case:ifP=>[T_r | T_ne_r].\n      * move=>[EL]; move: EL LU=><- {L} /lu_unfold-LU {F_ne_r}.\n        case EL: _ _/LU=>[||a p Ks C DU LU]//; move: EL DU LU=>[<-<-<-] DU LU {a p Ks}.\n        move: T_r CIH E=>/eqP<- CIH E.\n        move: (prjall_dom E)=>iDOM.\n        apply/prj_recv; first by rewrite eq_sym (F_neq_T).\n        - by apply/(same_dom_trans\n                      (same_dom_trans ((same_dom_sym _ _).1 DOM) iDOM)).\n        - move=> l Ty G G' CCl Cl; right; move: (dom' DOM CCl)=>[iG FND].\n          move: (GU _ _ _ _ FND CCl)=>[{}GU|//].\n          move: (dom iDOM FND)=>[iL FND'].\n          move: (LU _ _ _ _ FND' Cl)=>[{}LU|//].\n          move: (prjall_fnd E FND FND')=>/eqP-PRJ.\n          move: (find_member FND)=>M.\n          by apply: (CIH _ _ _ _ (cG _ M) (gG _ M) (NE _ M) PRJ GU LU).\n      * move=> MRG.\n        have M: simple_merge L [seq K.2.2 | K <- KsL] = Some L\n          by move: MRG=>{E}; case: KsL=>//=K Ks /eqP-M;\n             move: (simple_merge_some M)=>E; move: E M=>->; rewrite eq_refl=>/eqP.\n        move: (lunroll_merge LU E M)=>[CCL [DL cMRG]].\n        move: F_ne_r T_ne_r; rewrite eq_sym=>F_ne_r; rewrite eq_sym=>T_ne_r.\n        apply: prj_mrg;rewrite ?F_ne_r ?T_ne_r ?F_neq_T//; last by apply:cMRG.\n        - case: CONT NE_C DOM {cG gG NE PARTS GU E}=>// K Ks _ DOM.\n          case: K DOM=>[l [Ty G] DOM]/=.\n          have: (find_cont ((l, (Ty, G)) :: Ks) l = Some (Ty, G))\n            by rewrite /find_cont/extend !eq_refl.\n          by move=>/(dom DOM)=>[G']; exists l, Ty.\n        - move: E MRG=>/eqP-E /eqP-MRG; move: (prjall_merge E MRG)=> ALL_EQ.\n          move=> l Ty G CCl; move: (dom' DOM CCl)=>[iG iFND].\n          move: (find_member iFND)=>MEM; move: (GU _ _ _ _ iFND CCl)=>[GU'|//].\n          move: (ALL_EQ _ MEM) (cG _ MEM)=>PK cK.\n          move: PARTS; rewrite !in_cons F_ne_r T_ne_r /= => PARTS.\n          move: PARTS=> /flatten_mapP-[K] /memberP-K_CONT r_in_K.\n          move: ((project_parts_in (cG _ K_CONT) (ALL_EQ _ K_CONT)).2 r_in_K).\n          rewrite (project_depth cK PK)=>[][m] H.\n          by apply/(partof_all_unroll cK GU' PK)/H.\n        - move:DOM=>/same_dom_sym-DOM; apply/(same_dom_trans DOM).\n          by apply/(same_dom_trans _ DL)/(prjall_dom E).\n        - move=> l Ty G cL CCl CCLl; right.\n          move: (dom' DOM CCl)=>[iG iFND]; move: (find_member iFND)=>MEM.\n          move: (cG _ MEM) (gG _ MEM) (NE _ MEM)=>/= {}cG {}gG {}NE.\n          move: E MRG=>/eqP-E /eqP-MRG; move: (prjall_merge E MRG).\n          move=>/(_ _ MEM)=>/=PRJ.\n          move: (GU _ _ _ _ iFND CCl)=>[{}GU|//].\n          apply: (CIH _ _ _ _ cG gG NE PRJ GU).\n          apply/(LUnroll_EqL LU).\n          by move: (cMRG _ _ _ CCLl)=>/EqL_sym.\nQed.\n\nTheorem ic_proj r :\n  forall iG iL cG cL,\n    g_closed iG ->\n    guarded 0 iG ->\n    non_empty_cont iG ->\n    project simple_merge iG r == Some iL ->\n    GUnroll iG cG ->\n    LUnroll iL cL ->\n    Project simple_co_merge r cG cL.\nProof.\n  move=> iG iL cG cL CG GG NE Prj GU LU.\n  move: (conj CG (conj GG (conj NE (conj Prj (conj GU LU)))))\n  => {CG GG Prj GU LU NE}.\n  move => /(ex_intro (fun iL=> _) iL) {iL}.\n  move => /(ex_intro (fun iG=> _) iG) {iG}.\n  move: cG cL; apply/paco2_acc=> r0 _ CIH.\n\n  move: CIH =>/(_ _ _\n                  (ex_intro _ _\n                     (ex_intro _ _\n                        (conj _ (conj _ (conj _ (conj _ (conj _ _))))))))-CIH.\n  move=> cG cL [iG] [cG'] [ciG] [giG] [NE] [iGiL] [GU LU].\n\n  move: iGiL  => /eqP-iGiL.\n  move: (project_unroll (rec_depth iG) ciG iGiL) => [U1] [U2] [L] [proj] U12.\n  move: LU =>/(LUnroll_ind U1); move: U12=>->; rewrite -LUnroll_ind=>UL.\n  move : GU (unroll_guarded ciG giG)=>/(GUnroll_ind (rec_depth iG))=>GU nrG.\n  move: (g_guarded_nunroll (rec_depth iG) ciG giG)=>guiG.\n  move: (g_closed_unroll (rec_depth iG) ciG)=>cuiG {ciG giG iGiL}.\n  move: (ne_unr (rec_depth iG) NE)=>{}NE.\n  by apply/(project_nonrec CIH cuiG guiG NE nrG proj).\nQed.\n\nTheorem coind_proj r G L :\n  g_precond G ->\n  project simple_merge G r == Some L ->\n  Project simple_co_merge r (g_expand G) (l_expand L).\nProof.\n  rewrite/g_precond=>/andP-[/andP-[cG gG] NE] P.\n  move: (proj_lclosed cG P) (project_guarded P) (proj_lne NE P)=>cL gL NEl.\n  move: (g_expand_unr gG cG NE) (l_expand_unr gL cL NEl)=>{cL gL NEl}.\n  by apply/ic_proj.\nQed.\n\nTheorem expand_eProject (g : g_ty) (e : seq (role * l_ty))\n  : eproject simple_merge g = Some e ->\n    eProject simple_co_merge (ig_end (g_expand g)) (expand_env e).\nProof.\n  move=>EPRJ p; constructor.\n  have PRE: g_precond g by move: EPRJ;rewrite/eproject;case:ifP.\n  move: (precond_parts PRE); case: (boolP (nilp (participants g))).\n  + move=> NOPARTS [//|END]; move: EPRJ; rewrite /eproject PRE.\n    move: (participants g) NOPARTS=>[]//= _ [<-].\n    rewrite /look -in_expanded_env/= (expand_g_end END).\n    apply/paco2_fold/prj_end; first by case E: _ / =>//.\n      by apply/paco1_fold; constructor.\n  + move=>NE _.\n    have cG: g_closed g by move: PRE=>/andP-[/andP-[cG gG] CNE].\n    have gG: guarded 0 g by move: PRE=>/andP-[/andP-[_ gG] CNE].\n    have CNE: non_empty_cont g by move: PRE=>/andP-[_ CNE].\n    have GU: GUnroll g (g_expand g) by apply/(g_expand_unr gG cG CNE).\n    move: (eproject_some EPRJ NE)=>[q [L] /eqP-PRJ'].\n    have gWF: WF (g_expand g) by apply/(project_wf cG gG CNE PRJ' GU).\n    move=>{PRJ' L q}.\n    case: (boolP (p \\in participants g)).\n  - move=>PS; move: EPRJ=>/eqP/eproject_part/(_ _ PS)-PRJ.\n    rewrite /look -in_expanded_env.\n    have ->: (odflt rl_end (omap l_expand (find_cont e p)))\n    = l_expand (odflt l_end (find_cont e p))\n      by case: find_cont=>//=;rewrite (rltyU (l_expand _)).\n      by apply/coind_proj=>//; apply/eqP.\n  - move=>PARTS; have NP: ~ part_of p (g_expand g)\n            by move=> P_of; move: PARTS; rewrite (partof_unroll cG gG GU).\n    rewrite /look -in_expanded_env (fnd_not_part EPRJ PARTS)/=.\n      by apply/paco2_fold/prj_end.\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/Correctness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15608005076736617}}
{"text": "Require Import floyd.proofauto.\nRequire Import floyd.library.\nRequire Import progs.list_dt. Import Links.\nRequire Import progs.queue.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition t_struct_elem := Tstruct _elem noattr.\nDefinition t_struct_fifo := Tstruct _fifo noattr.\n\n\nInstance QS: listspec _elem _next (fun _ _ => emp).\nProof. eapply mk_listspec; reflexivity. Defined.\n\nLemma isnil: forall {T: Type} (s: list T), {s=nil}+{s<>nil}.\nProof. intros. destruct s; [left|right]; auto. intro Hx; inv Hx. Qed.\n\nDefinition Qsh : share := fst (Share.split Share.Lsh).\nDefinition Qsh' := Share.lub (snd (Share.split Share.Lsh)) Share.Rsh.\n\nLemma readable_share_Qsh': readable_share Qsh'.\nProof.\nunfold readable_share, Qsh'.\nrewrite Share.distrib1.\nrewrite Share.glb_idem.\nrewrite Share.lub_commute.\nrewrite Share.lub_absorb.\napply readable_nonidentity.\napply writable_readable.\napply sepalg.join_sub_refl.\nQed.  (* share hacking *)\n\nLemma Qsh_not_readable: ~ readable_share Qsh.\nProof.\nunfold Qsh, readable_share; intro.\nunfold nonempty_share in H.\napply H; clear H.\nassert (Share.glb Share.Rsh (fst (Share.split Share.Lsh)) = Share.bot).\napply sub_glb_bot with Share.Lsh.\nexists (snd (Share.split Share.Lsh)).\napply split_join.\ndestruct (Share.split Share.Lsh); reflexivity.\nunfold Share.Rsh, Share.Lsh.\nrewrite Share.glb_commute.\napply glb_split.\nrewrite H.\napply bot_identity.\nQed.\n\nHint Resolve Qsh_not_readable.\n\nLemma Qsh_nonempty: Qsh <> Share.bot.\nProof.\nunfold Qsh; intro.\ndestruct (Share.split Share.Lsh) eqn:?H.\nsimpl in H.\napply Share.split_nontrivial in H0; auto.\nunfold Share.Lsh in H0; clear - H0.\ndestruct (Share.split Share.top) eqn:?H.\nsimpl in H0.\napply Share.split_nontrivial in H; auto.\napply Share.nontrivial in H.\nauto.\nQed.\n\nHint Resolve Qsh_nonempty : valid_pointer.\n\nLemma Qsh_nonidentity: sepalg.nonidentity Qsh.\nProof.\n  intro.\n  apply identity_share_bot in H.\n  apply Qsh_nonempty in H.\n  auto.\nQed.\n\nHint Resolve Qsh_nonidentity : valid_pointer.\n\nLemma Qsh_Qsh': sepalg.join Qsh Qsh' Tsh.\nProof.\nunfold Qsh, Qsh', Share.Lsh, Share.Rsh.\ndestruct (Share.split Share.top) as [a c] eqn:?H.\nsimpl.\ndestruct (Share.split a) as [x y] eqn:?H.\nsimpl.\npose proof (Share.split_disjoint x y a H0).\npose proof (Share.split_disjoint _ _ _ H).\nsplit.\nrewrite Share.distrib1.\nrewrite H1.\nrewrite Share.lub_commute, Share.lub_bot.\nreplace x with (Share.glb x a).\nrewrite Share.glb_assoc. rewrite H2.\napply Share.glb_bot.\nclear - H0.\napply split_join in H0. destruct H0.\nsubst a.\napply Share.glb_absorb.\nrewrite <- Share.lub_assoc.\napply split_join in H0. destruct H0.\nrewrite H3.\napply split_join in H. destruct H.\napply H4.\nQed.\n\nLemma field_at_list_cell_weak:\n  forall sh i j p,\n   readable_share sh ->\n  field_at sh list_struct [StructField _a] i p *\n  field_at sh list_struct [StructField _b] j p *\n  field_at_ sh list_struct [StructField _next] p\n  = list_cell QS sh (i,j) p *\n  field_at_ sh list_struct [StructField _next] p.\nProof.\nintros.\n(* new version of proof, for constructive definition of list_cell *)\nf_equal.\nunfold field_at, list_cell.\nautorewrite with gather_prop.\nf_equal.\napply ND_prop_ext.\nrewrite field_compatible_cons; simpl.\nrewrite field_compatible_cons; simpl.\nintuition.\n+ left; auto.\n+ right; left; auto.\nQed.\n\nLemma make_unmake:\n forall a b p,\n field_at Tsh t_struct_elem [] (Vint a, (Vint b, Vundef)) p =\n field_at Qsh' t_struct_elem [StructField _a] (Vint a) p *\n field_at Qsh' t_struct_elem [StructField _b] (Vint b) p *\n list_cell QS Qsh (Vundef, Vundef) p *\n field_at_ Tsh t_struct_elem [StructField _next] p.\nProof.\nintros.\nunfold_field_at 1%nat.\nrewrite <- !sepcon_assoc.\nmatch goal with |- ?A = _ => set (J := A) end.\nunfold field_at_.\nchange (default_val (nested_field_type t_struct_elem [StructField _next])) with Vundef.\nrewrite <- (field_at_share_join _ _ _ _ _ _ _ Qsh_Qsh').\nrewrite <- !sepcon_assoc.\npull_left (field_at Qsh' t_struct_elem [StructField _next] Vundef p).\npull_left (field_at Qsh' t_struct_elem [StructField _b] (Vint b) p).\npull_left (field_at Qsh' t_struct_elem [StructField _a] (Vint a) p).\nrewrite field_at_list_cell_weak  by apply readable_share_Qsh'.\nmatch goal with |- _ = _ * _ * _ * ?A => change A\n  with (field_at_ Qsh t_struct_elem [StructField _next] p)\nend.\npull_left (list_cell QS Qsh (Vundef, Vundef) p).\nrewrite join_cell_link with (psh:=Tsh) by (auto; try apply Qsh_Qsh'; apply readable_share_Qsh').\nsubst J.\nmatch goal with |- _ * _ * ?A = _ => change A\n  with (field_at_ Tsh t_struct_elem [StructField _next] p)\nend.\nrewrite field_at_list_cell_weak by auto.\nrewrite sepcon_assoc.\nf_equal.\nunfold field_at_.\nchange (default_val (nested_field_type t_struct_elem [StructField _next])) with Vundef.\nrewrite sepcon_comm.\nsymmetry.\napply (field_at_share_join _ _ _ t_struct_elem [StructField _next]\n   _ p Qsh_Qsh').\nQed.\n\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH n:Z\n   PRE [ _n OF tuint ]\n       PROP (0 <= n <= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)))\n       SEP ()\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (malloc_token Tsh n p * memory_block Tsh n p).\n\n\nDefinition elemrep (rep: elemtype QS) (p: val) : mpred :=\n  field_at Tsh t_struct_elem [StructField _a] (fst rep) p *\n  (field_at Tsh t_struct_elem [StructField _b] (snd rep) p *\n   (field_at_ Tsh t_struct_elem [StructField _next]) p).\n\nDefinition fifo (contents: list val) (p: val) : mpred :=\n  (EX ht: (val*val), let (hd,tl) := ht in\n      !! is_pointer_or_null hd && !! is_pointer_or_null tl &&\n      data_at Tsh t_struct_fifo (hd, tl) p * malloc_token Tsh (sizeof t_struct_fifo) p *\n      if isnil contents\n      then (!!(hd=nullval) && emp)\n      else (EX prefix: list val,\n              !!(contents = prefix++tl::nil)\n            &&  (lseg QS Qsh Tsh prefix hd tl\n                   * list_cell QS Qsh (Vundef,Vundef) tl\n                   * field_at Tsh t_struct_elem [StructField _next] nullval tl)))%logic.\n\nDefinition fifo_new_spec :=\n DECLARE _fifo_new\n  WITH u : unit\n  PRE  [  ]\n       PROP() LOCAL() SEP ()\n  POST [ (tptr t_struct_fifo) ]\n    EX v:val, PROP() LOCAL(temp ret_temp v) SEP (fifo nil v).\n\nDefinition fifo_put_spec :=\n DECLARE _fifo_put\n  WITH q: val, contents: list val, p: val\n  PRE  [ _Q OF (tptr t_struct_fifo) , _p OF (tptr t_struct_elem) ]\n          PROP () LOCAL (temp _Q q; temp _p p)\n          SEP (fifo contents q;\n                 list_cell QS Qsh (Vundef, Vundef) p;\n                 field_at_ Tsh t_struct_elem [StructField _next] p)\n  POST [ tvoid ]\n          PROP() LOCAL() SEP (fifo (contents++(p :: nil)) q).\n\nDefinition fifo_empty_spec :=\n DECLARE _fifo_empty\n  WITH q: val, contents: list val\n  PRE  [ _Q OF (tptr t_struct_fifo) ]\n     PROP() LOCAL (temp _Q q) SEP(fifo contents q)\n  POST [ tint ]\n      PROP ()\n      LOCAL(temp ret_temp (if isnil contents then Vtrue else Vfalse))\n      SEP (fifo (contents) q).\n\nDefinition fifo_get_spec :=\n DECLARE _fifo_get\n  WITH q: val, contents: list val, p: val\n  PRE  [ _Q OF (tptr t_struct_fifo) ]\n       PROP() LOCAL (temp _Q q) SEP (fifo (p :: contents) q)\n  POST [ (tptr t_struct_elem) ]\n       PROP ()\n       LOCAL(temp ret_temp p)\n       SEP (fifo contents q;\n              list_cell QS Qsh (Vundef, Vundef) p;\n              field_at_ Tsh t_struct_elem [StructField _next] p).\n\nDefinition make_elem_spec :=\n DECLARE _make_elem\n  WITH a: int, b: int\n  PRE  [ _a OF tint, _b OF tint ]\n        PROP() LOCAL(temp _a (Vint a); temp _b (Vint b)) SEP()\n  POST [ (tptr t_struct_elem) ]\n      @exp (environ->mpred) _ _ (fun p:val =>  (* EX notation doesn't work for some reason *)\n       PROP()\n       LOCAL (temp ret_temp p)\n       SEP (field_at Qsh' list_struct [StructField _a] (Vint a) p;\n              field_at Qsh' list_struct [StructField _b] (Vint b) p;\n              list_cell QS Qsh (Vundef, Vundef) p;\n              field_at_ Tsh t_struct_elem [StructField _next] p;\n              malloc_token Tsh (sizeof t_struct_elem) p)).\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 :=\n  ltac:(with_library prog\n    [surely_malloc_spec; fifo_new_spec; fifo_put_spec;\n     fifo_empty_spec; fifo_get_spec; make_elem_spec;\n     main_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function.\n  forward_call (* p = malloc(n); *)\n     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 memory_block_fifo:\n forall p,\n  field_compatible t_struct_fifo nil p ->\n  memory_block Tsh 8 p = field_at_ Tsh t_struct_fifo nil p.\nProof.\n intros.\n change 8 with (sizeof t_struct_fifo).\n rewrite memory_block_data_at_; auto.\nQed.\n\nLemma fifo_isptr: forall al q, fifo al q |-- !! isptr q.\nProof.\nintros.\n unfold fifo.\n if_tac; entailer; destruct ht; entailer!.\nQed.\n\nHint Resolve fifo_isptr : saturate_local.\n\nLemma body_fifo_empty: semax_body Vprog Gprog f_fifo_empty fifo_empty_spec.\nProof.\nstart_function.\nunfold fifo.\nIntros ht; destruct ht as [hd tl].\nIntros.\nforward. (* h = Q->head; *)\nforward. (* return (h == NULL); *)\nunfold fifo.\nExists (hd,tl).\ndestruct (isnil contents).\n* entailer!.\n  apply andp_right; auto with valid_pointer.\n* Intros prefix.\nExists prefix.\n  assert_PROP (isptr hd).\n    destruct prefix; entailer.\n    rewrite lseg_cons_eq by auto. Intros y. subst v.\n    entailer.\n destruct hd; try contradiction.\n entailer!. entailer!.\nQed.\n\n\nLemma body_fifo_new: semax_body Vprog Gprog f_fifo_new fifo_new_spec.\nProof.\n  start_function.\n  forward_call (* Q = surely_malloc(sizeof ( *Q)); *)\n     (sizeof t_struct_fifo).\n    simpl; computable.\n  Intros q.\n  assert_PROP (field_compatible t_struct_fifo [] q).\n   entailer!.\n  rewrite memory_block_fifo by auto.\n  forward. (* Q->head = NULL; *)\n  (* goal_4 *)\n  forward. (* Q->tail = NULL; *)\n  forward. (* return Q; *)\n  (* goal_5 *)\n  Exists q. unfold fifo. Exists (nullval,nullval).\n  rewrite if_true by auto.\n  entailer!.\nQed.\n\nLemma body_fifo_put: semax_body Vprog Gprog f_fifo_put fifo_put_spec.\nProof.\nstart_function.\nunfold fifo at 1.\nIntros ht; destruct ht as [hd tl].\nIntros.\n(* goal_7 *)\nforward. (* p->next = NULL; *)\nforward. (*   h = Q->head; *)\n\nforward_if\n  (PROP() LOCAL () SEP (fifo (contents ++ p :: nil) q))%assert.\n* if_tac; entailer.  (* typechecking clause *)\n    (* entailer! should perhaps solve this one too *)\n* (* then clause *)\n  subst.\n  (* goal 9 *)\n  forward. (* Q->head=p; *)\n  forward. (* Q->tail=p; *)\n  (* goal 10 *)\n  entailer.\n  destruct (isnil contents).\n  + subst. Exists (p,p).\n     simpl. rewrite if_false by congruence.\n     Exists (@nil val).\n      rewrite lseg_nil_eq by auto.\n      entailer!.\n   + Intros prefix.\n      destruct prefix;\n      entailer!.\n      contradiction (field_compatible_isptr _ _ _ H9).\n      rewrite lseg_cons_eq by auto. simpl.\n      Intros y. saturate_local.\n      contradiction (field_compatible_isptr _ _ _ H11).\n* (* else clause *)\n  forward. (*  t = Q->tail; *)\n  destruct (isnil contents).\n  + Intros. contradiction H; auto.\n  + Intros prefix.\n     forward. (*  t->next=p; *)\n  (* goal 12 *)\n     forward. (* Q->tail=p; *)\n  (* goal 13 *)\n     entailer!.\n     unfold fifo. Exists (hd, p).\n     rewrite if_false by (clear; destruct prefix; simpl; congruence).\n     Exists  (prefix ++ tl :: nil).\n     entailer.\n     match goal with\n     | |- _ |-- _ * _ * ?AA => remember AA as A\n     end.     (* prevent it from canceling! *)\n     simpl sizeof.\n     cancel. subst A.\n(* XXX: eapply derives_trans. Focus 2. apply lseg_cons_right_neq. *)\n     eapply derives_trans; [ |\n       apply (lseg_cons_right_neq _ _ _ _ _ ((Vundef,Vundef) : elemtype QS));\n        auto ].\n     cancel.\n* (* after the if *)\n     forward. (* return ; *)\nQed.\n\nLemma body_fifo_get: semax_body Vprog Gprog f_fifo_get fifo_get_spec.\nProof.\nstart_function.\nunfold fifo at 1.\nIntros ht; destruct ht as [hd tl].\nrewrite if_false by congruence.\nIntros prefix.\nforward.  (*   p = Q->head; *)\ndestruct prefix; inversion H; clear H.\n+ subst_any.\n   rewrite lseg_nil_eq by auto.\n   Intros.\n   subst_any.\n   forward. (*  n=h->next; *)\n   forward. (* Q->head=n; *)\n   forward. (* return p; *)\n   unfold fifo. Exists (nullval, tl).\n   rewrite if_true by congruence.\n   simpl sizeof; entailer!.\n+ rewrite lseg_cons_eq by auto.\n    Intros x.\n    simpl @valinject. (* can we make this automatic? *)\n    subst_any.\n    forward. (*  n=h->next; *)\n    forward. (* Q->head=n; *)\n    forward. (* return p; *)\n    unfold fifo. Exists (x, tl).\n    rewrite if_false by (destruct prefix; simpl; congruence).\n    Exists prefix.\n    entailer!.\nQed.\n\nLemma body_make_elem: semax_body Vprog Gprog f_make_elem make_elem_spec.\nProof.\nstart_function. rename a into a0; rename b into b0.\nforward_call (*  p = surely_malloc(sizeof ( *p));  *)\n  (sizeof t_struct_elem).\n simpl; computable.\n Intros p.\n assert_PROP (field_compatible t_struct_elem [] p). entailer!.\n rewrite memory_block_data_at_ by auto.\n  forward.  (*  p->a=a; *)\n  simpl.  (* this should not be necessary -- Qinxiang, please look *)\n  forward.  (*  p->b=b; *)\n  forward.  (* return p; *)\n  Exists p.\n  entailer!.\n  rewrite make_unmake.\n  solve [auto].\nQed.\n\nHint Resolve readable_share_Qsh'.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nforward_call (* Q = fifo_new(); *)  tt.\nIntros q.\n\nforward_call  (*  p = make_elem(1,10); *)\n     (Int.repr 1, Int.repr 10).\nIntros p'.\nforward_call (* fifo_put(Q,p);*)\n    ((q, @nil val),p').\n\nforward_call  (*  p = make_elem(2,20); *)\n     (Int.repr 2, Int.repr 20).\nIntros p2.\nsimpl app.\n forward_call  (* fifo_put(Q,p); *)\n    ((q,(p':: nil)),p2).\nsimpl app.\nforward_call  (*   p' = fifo_get(Q); p = p'; *)\n    ((q,(p2 :: nil)),p').\nforward. (*   i = p->a;  *)\nforward. (*   j = p->b; *)\nchange (malloc_token Tsh 12) with (malloc_token Tsh (sizeof t_struct_elem)).\nforward_call (*  free(p, sizeof( *p)); *)\n   (p', sizeof t_struct_elem).\n{\n pose (work_around_coq_bug := fifo [p2] q *\n   data_at Tsh t_struct_elem (Vint (Int.repr 1), (Vint (Int.repr 10), Vundef)) p' *\n   field_at Qsh' list_struct [StructField _a] (Vint (Int.repr 2)) p2 *\n   field_at Qsh' list_struct [StructField _b] (Vint (Int.repr 20)) p2 *\n   malloc_token Tsh (sizeof t_struct_elem) p2).\n apply derives_trans with work_around_coq_bug; subst work_around_coq_bug.\n unfold data_at; rewrite make_unmake; cancel.\n apply derives_trans with\n   (data_at_ Tsh t_struct_elem p' * fold_right_sepcon Frame).\n cancel.\n rewrite data_at__memory_block by reflexivity. entailer.\n}\nforward. (* return i+j; *)\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_malloc. apply semax_func_cons_malloc_aux.\nsemax_func_cons body_free.\nsemax_func_cons body_exit.\nsemax_func_cons body_surely_malloc.\nsemax_func_cons body_fifo_new.\nsemax_func_cons body_fifo_put.\nsemax_func_cons body_fifo_empty.\nsemax_func_cons body_fifo_get.\nsemax_func_cons body_make_elem.\nsemax_func_cons body_main.\nQed.\n\n\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_queue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.15608005076736617}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.strlib.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition strchr_spec :=\n DECLARE _strchr\n  WITH sh: share, str : val, s : list byte, c : byte\n  PRE  [ tptr tschar, tint ]\n    PROP (readable_share sh; c <> Byte.zero)\n    PARAMS (str; Vbyte c)\n    SEP (cstring sh s str)\n  POST [ tptr tschar ]\n   EX r : val,\n    PROP ((exists i, Znth i s = c /\\ Forall (fun d => d<>c) (sublist 0 i s)\n                     /\\ r = offset_val i str)\n       \\/ (Forall (fun d => d<>c) s /\\ r = nullval))\n    RETURN (r)\n    SEP (cstring sh s str).\n\nDefinition strcat_spec :=\n DECLARE _strcat\n  WITH sh: share, sh': share, dest : val, sd : list byte, n : Z, src : val, ss : list byte\n  PRE  [ tptr tschar, tptr tschar ]\n    PROP (writable_share sh; readable_share sh'; Zlength sd + Zlength ss < n)\n    PARAMS (dest; src)\n    SEP (cstringn sh sd n dest; cstring sh' ss src)\n  POST [ tptr tschar ]\n    PROP ()\n    RETURN (dest)\n    SEP (cstringn sh (sd ++ ss) n dest; cstring sh' ss src).\n\nDefinition strcmp_spec :=\n DECLARE _strcmp\n  WITH sh1: share, sh2: share, str1 : val, s1 : list byte, str2 : val, s2 : list byte\n  PRE [ tptr tschar, tptr tschar ]\n    PROP (readable_share sh1; readable_share sh2)\n    PARAMS (str1; str2)\n    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2)\n  POST [ tint ]\n   EX i : int,\n    PROP (if Int.eq_dec i Int.zero then s1 = s2 else s1 <> s2)\n    RETURN (Vint i)\n    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2).\n\nDefinition strcpy_spec :=\n DECLARE _strcpy\n  WITH sh: share, sh': share, dest : val, n : Z, src : val, s : list byte\n  PRE [ tptr tschar, tptr tschar ]\n    PROP (writable_share sh; readable_share sh'; Zlength s < n)\n    PARAMS (dest; src)\n    SEP (data_at_ sh (tarray tschar n) dest; cstring sh' s src)\n  POST [ tptr tschar ]\n    PROP ()\n    RETURN (dest)\n    SEP (cstringn sh s n dest; cstring sh' s src).\n\nDefinition strlen_spec :=\n DECLARE _strlen\n  WITH sh: share, s : list byte, str: val\n  PRE [ tptr tschar ]\n    PROP (readable_share sh)\n    PARAMS (str)\n    SEP (cstring sh s str)\n  POST [ size_t ]\n    PROP ()\n    RETURN (Vptrofs (Ptrofs.repr (Zlength s)))\n    SEP (cstring sh s str).\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ strchr_spec; strcat_spec; strcmp_spec ]).\n\n#[export] Hint Rewrite Z.add_simpl_r Z.sub_simpl_r : norm entailer_rewrite.\n\nLemma body_strlen: semax_body Vprog Gprog f_strlen strlen_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s into ls.\nforward.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n*\nExists 0. entailer!!.\n*\nIntros i.\nforward.\nforward_if.\nforward.\nentailer!!. repeat f_equal. cstring.\nforward. \nExists (i+1).\nentailer!!. cstring.\nQed.\n\nLemma body_strchr: semax_body Vprog Gprog f_strchr strchr_spec.\nProof.\nstart_function.\nforward.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1; Forall (fun d => d <> c) (sublist 0 i ls))\n  LOCAL (temp _str str; temp _c (Vbyte c); temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n  Exists 0; rewrite sublist_nil; entailer!!.\n- Intros i. \n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward.\n  forward. fold_Vbyte.\n forward_if.\n  { forward. simpl. \n    Exists (offset_val i str).\n    entailer!!.\n    left. exists i. split3; auto. rewrite app_Znth1; auto. cstring. }\n  { forward_if.\n    { forward.\n      Exists nullval; rewrite !map_app; entailer!.\n      right. split; auto.\n      assert (i = Zlength ls) by cstring.\n      subst i.\n     autorewrite with sublist in H2; auto. }\n  forward.\n  Exists (i+1); entailer!.\n  assert (i <> Zlength ls) by cstring.\n  split. lia.\n  rewrite (sublist_split 0 i) by rep_lia. rewrite Forall_app. split; auto.\n  rewrite sublist_len_1 by rep_lia. repeat constructor.\n  rewrite app_Znth1 in H4 by rep_lia. auto.\n  }\nQed.\n\nOpen Scope logic.\n\nLemma split_data_at_app_tschar:\n forall sh n (al bl: list val) p ,\n   n = Zlength (al++bl) ->\n   data_at sh (tarray tschar n) (al++bl) p = \n         data_at sh (tarray tschar (Zlength al)) al p\n        * data_at sh (tarray tschar (n - Zlength al)) bl\n                 (field_address0 (tarray tschar n) [ArraySubsc (Zlength al)] p).\nProof.\nintros.\napply (split2_data_at_Tarray_app _ n  sh tschar al bl ); auto.\nrewrite Zlength_app in H.\nchange ( Zlength bl = n - Zlength al); lia.\nQed.\n\nLemma body_strcat: semax_body Vprog Gprog f_strcat strcat_spec.\nProof.\nstart_function.\nunfold cstringn, cstring in *.\nrename sd into ld. rename ss into ls.\nIntros.\nforward.\nforward_loop (EX i : Z,\n    PROP (0 <= i < Zlength ld + 1)\n    LOCAL (temp _i (Vptrofs (Ptrofs.repr i)); temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + 1)))) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src))\n  break: (PROP ( )\n   LOCAL (temp _i (Vptrofs (Ptrofs.repr (Zlength ld))); temp _dest dest; \n   temp _src src)\n   SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + 1)))) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src)).\n-\n  Exists 0; entailer!!.\n-\n  Intros i.\n  forward.\n  { entailer!. }\n  { entailer!. autorewrite with sublist norm. auto.  }\n  autorewrite with sublist norm.\n  forward.\n  forward_if.\n  + forward.\n    entailer!!. f_equal. f_equal. cstring.\n  +\n    forward.\n    Exists (i+1); entailer!. cstring.\n-\n  abbreviate_semax.\n  forward.\n  forward_loop (EX j : Z,\n    PROP (0 <= j < Zlength ls + 1)\n    LOCAL (temp _j (Vptrofs (Ptrofs.repr j)); temp _i (Vptrofs (Ptrofs.repr (Zlength ld)));\n           temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ sublist 0 j ls) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + j)))) dest;\n         data_at sh' (tarray tschar (Zlength ls + 1))\n           (map Vbyte (ls ++ [Byte.zero])) src)).\n  { Exists 0; entailer!.  autorewrite with sublist.\n    rewrite !map_app. rewrite <- app_assoc.\n    rewrite split_data_at_app_tschar by list_solve.\n    rewrite (split_data_at_app_tschar _ n) by list_solve.\n    autorewrite with sublist.\n    cancel.\n   }\n  { Intros j.\n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward.  autorewrite with norm.\n  forward. fold_Vbyte.\n  forward.\n  entailer!!.\n  clear H3.\n  rewrite upd_Znth_app2 by list_solve.\n  autorewrite with sublist.\n  forward_if.\n  + forward.\n      autorewrite with sublist.\n      rewrite prop_true_andp \n        by (intro Hx; apply in_app in Hx; destruct Hx; contradiction).\n      cancel.\n    assert (j = Zlength ls) by cstring; subst.\n    autorewrite with sublist.\n    apply derives_refl'.\n    unfold data_at; f_equal. \n    replace (n - (Zlength ld + Zlength ls))\n     with (1 + (n - (Zlength ld + Zlength ls+1))) by rep_lia.\n    rewrite <- repeat_app' by rep_lia.\n    rewrite upd_Znth_app1 by list_solve.\n    rewrite app_assoc.\n    simpl.\n    rewrite !map_app.\n    reflexivity.\n +\n  forward.\n  Exists (j+1).\n  destruct (zlt j (Zlength ls)); [ | cstring].\n  entailer!!.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite (sublist_split 0 j (j+1)) by rep_lia.\n  rewrite (app_assoc ld). rewrite !map_app.\n  rewrite <- (app_assoc (_ ++ _)).\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  replace (n - (Zlength ld + j))\n    with (1 + (n - (Zlength ld + (j + 1)))) by rep_lia.\n  rewrite <- repeat_app' by rep_lia.\n  cancel.\n  rewrite upd_Znth_app1 by (autorewrite with sublist; rep_lia).\n  rewrite app_Znth1 by list_solve.\n  rewrite sublist_len_1 by rep_lia.\n  cancel.\n  }\nQed.\n\nLemma body_strcmp: semax_body Vprog Gprog f_strcmp strcmp_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s1 into ls1. rename s2 into ls2.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls1 + 1; 0 <= i < Zlength ls2 + 1;\n        sublist 0 i ls1 = sublist 0 i ls2)\n  LOCAL (temp _str1 str1; temp _str2 str2; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh1 (tarray tschar (Zlength ls1 + 1))\n          (map Vbyte (ls1 ++ [Byte.zero])) str1;\n       data_at sh2 (tarray tschar (Zlength ls2 + 1))\n          (map Vbyte (ls2 ++ [Byte.zero])) str2)).\n- Exists 0; entailer!!.\n- Intros i.\n  assert (Zlength (ls1 ++ [Byte.zero]) = Zlength ls1 + 1) by (autorewrite with sublist; auto).\n  forward. autorewrite with norm.\n  assert (Zlength (ls2 ++ [Byte.zero]) = Zlength ls2 + 1) by (autorewrite with sublist; auto).\n  forward. fold_Vbyte.\n  assert (Znth i (ls1 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls1) as Hs1.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by lia; auto].\n    destruct (zlt i (Zlength ls1)); [|lia].\n    intro X; lapply (Znth_In i ls1); [|lia]. cstring. }\n  assert (Znth i (ls2 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls2) as Hs2.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by lia; auto].\n    destruct (zlt i (Zlength ls2)); [|lia].\n    intro X; lapply (Znth_In i ls2); [|lia]. cstring. }\n  forward.\n  forward. fold_Vbyte.\n  forward_if (temp _t'1 (bool2val (Z.eqb i (Zlength ls1) && Z.eqb i (Zlength ls2)))).\n  { forward.\n    simpl force_val.\n    rewrite Hs1 in *.\n    destruct (Byte.eq_dec (Znth i (ls2 ++ [Byte.zero])) Byte.zero).\n    + rewrite e; simpl force_val.\n         assert (i = Zlength ls2) by cstring.\n        rewrite  (proj2 Hs1 H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls1)) H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls2)) H7).\n     entailer!!.\n  +\n    entailer!!. unfold bool2val. f_equal. rewrite Z.eqb_refl.\n    assert (Zlength ls1 <> Zlength ls2) by list_solve.\n    rewrite (proj2 (Z.eqb_neq _ _) H6).\n    unfold Int.cmp.\n    rewrite (Int.eq_false (Int.repr (Byte.signed _))). reflexivity.\n    contradict n.\n    apply repr_inj_signed in n; try rep_lia.  autorewrite with norm in n. auto.\n }\n  { forward.\n    entailer!!.\n    destruct (i =? Zlength ls1) eqn: Heq; auto.\n    rewrite Z.eqb_eq in Heq; tauto. }\n  forward_if.\n +\n  rewrite andb_true_iff in H6; destruct H6.\n  rewrite Z.eqb_eq in H6,H7.\n  forward.\n  Exists (Int.repr 0).\n  entailer!!. simpl.\n  autorewrite with sublist in H3.\n  auto.\n +\n  rewrite andb_false_iff in H6. rewrite !Z.eqb_neq in H6.\n  forward_if.\n  *\n    forward. Exists (Int.repr (-1)). entailer!!.\n    simpl. intro; subst. lia.\n *\n   forward_if.\n   forward.\n   Exists (Int.repr 1). entailer!.\n\n   assert (H17: Byte.signed (Znth i (ls1 ++ [Byte.zero])) =\n     Byte.signed (Znth i (ls2 ++ [Byte.zero]))) by lia.\n   autorewrite with norm in H17. clear H7 H8.\n   forward.\n   Exists (i+1).\n   entailer!!.\n   destruct (zlt i (Zlength ls1)).\n  2:{\n         rewrite app_Znth2 in Hs1 by rep_lia.\n         destruct (zeq i (Zlength ls1)); [ | lia].\n         subst.\n         destruct H6; [congruence | ].\n         assert (Zlength ls1 < Zlength ls2) by lia.\n         rewrite app_Znth2 in H17 by rep_lia.\n         rewrite app_Znth1 in H17 by rep_lia.\n         rewrite Z.sub_diag in H17. contradiction H0.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17. rewrite H17.\n         apply Znth_In. lia.\n   }\n  destruct (zlt i (Zlength ls2)).\n  2:{\n         rewrite app_Znth2 in Hs2 by rep_lia.\n         destruct (zeq i (Zlength ls2)); [ | lia].\n         subst.\n         destruct H6; [ | congruence].\n         assert (Zlength ls1 > Zlength ls2) by lia.\n         rewrite app_Znth1 in H17 by rep_lia.\n         rewrite app_Znth2 in H17 by rep_lia.\n         rewrite Z.sub_diag in H17. contradiction H.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17. rewrite <- H17.\n         apply Znth_In. lia.\n   }\n  rewrite (sublist_split 0 i (i+1)) by lia.\n  rewrite (sublist_split 0 i (i+1)) by lia.\n  f_equal; auto.\n  rewrite !sublist_len_1 by lia.\n  rewrite !app_Znth1 in H17 by list_solve.\n  split. rep_lia. split. rep_lia.\n  f_equal; auto. f_equal. auto.\nQed.\n\nLemma body_strcpy: semax_body Vprog Gprog f_strcpy strcpy_spec.\nProof.\nstart_function.\nunfold cstring,cstringn in *.\nrename s into ls.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _i (Vptrofs (Ptrofs.repr i)); temp _dest dest; temp _src src)\n  SEP (data_at sh (tarray tschar n)\n        (map Vbyte (sublist 0 i ls) ++ repeat Vundef (Z.to_nat (n - i))) dest;\n       data_at sh' (tarray tschar (Zlength ls + 1)) (map Vbyte (ls ++ [Byte.zero])) src)).\n*\n Exists 0. rewrite Z.sub_0_r; entailer!; simpl; entailer!.\n*\n Intros i.\n assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n forward. autorewrite with norm.\n forward. fold_Vbyte.\n forward.\n forward_if.\n+ forward.\n   entailer!!.\n  assert (i = Zlength ls) by cstring. subst i.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite upd_Znth_app2 by list_solve.\n  autorewrite with sublist.\n  rewrite !map_app.\n  rewrite <- app_assoc.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   autorewrite with sublist.\n   replace (n - Zlength ls) with (1 + (n - (Zlength ls + 1))) at 2 by list_solve.\n  rewrite <- repeat_app' by lia.\n  rewrite upd_Znth_app1 by list_solve.\n  rewrite !split_data_at_app_tschar by list_solve.\n  cancel.\n+\n   assert (i < Zlength ls) by cstring.\n  forward.\n  Exists (i+1). entailer!!. \n  autorewrite with sublist.\n  rewrite (sublist_split 0 i (i+1)) by list_solve.\n  rewrite !map_app. rewrite <- app_assoc.\n  autorewrite with sublist.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite !(split_data_at_app_tschar _ n) by list_solve.\n  autorewrite with sublist.\n   replace (n - i) with (1 + (n-(i+ 1))) at 2 by list_solve.\n  rewrite <- repeat_app' by lia.\n  autorewrite with sublist.\n  cancel.\n  rewrite !split_data_at_app_tschar by list_solve.\n  autorewrite with sublist.\n  rewrite sublist_len_1 by lia.\n  simpl. cancel.\nQed.\n\nModule Alternate.\n\n(* Alternate proofs of these functions, using list solver *)\n\nLemma body_strlen: semax_body Vprog Gprog f_strlen strlen_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s into ls.\nforward.\nforward_loop  (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\nall: finish.\nQed.\n\nLemma body_strchr: semax_body Vprog Gprog f_strchr strchr_spec.\nProof.\nstart_function.\nforward.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1; Forall (fun d => d <> c) (sublist 0 i ls))\n  LOCAL (temp _str str; temp _c (Vbyte c); temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\nall: finish.\nQed.\n\nLemma body_strcat: semax_body Vprog Gprog f_strcat strcat_spec.\nProof.\nstart_function.\nunfold cstringn, cstring in *.\nrename sd into ld. rename ss into ls.\nforward.\nforward_loop (EX i : Z,\n    PROP (0 <= i < Zlength ld + 1)\n    LOCAL (temp _i (Vptrofs (Ptrofs.repr i)); temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + 1)))) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src))\n  break: (PROP ( )\n   LOCAL (temp _i (Vptrofs (Ptrofs.repr (Zlength ld))); temp _dest dest; \n   temp _src src)\n   SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + 1)))) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src)).\n- (* before loop1 *)\n  finish.\n- (* loop1 body *)\n  finish!.\n-\n  fastforward.\n  forward_loop (EX j : Z,\n    PROP (0 <= j < Zlength ls + 1)\n    LOCAL (temp _j (Vptrofs (Ptrofs.repr j)); temp _i (Vptrofs (Ptrofs.repr (Zlength ld)));\n           temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ sublist 0 j ls) ++\n           repeat Vundef (Z.to_nat (n - (Zlength ld + j)))) dest;\n         data_at sh' (tarray tschar (Zlength ls + 1))\n           (map Vbyte (ls ++ [Byte.zero])) src)).\n all: finish.\nQed.\n\nLemma body_strcmp: semax_body Vprog Gprog f_strcmp strcmp_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s1 into ls1. rename s2 into ls2.\nfastforward.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls1 + 1; 0 <= i < Zlength ls2 + 1;\n        forall (j:Z), 0 <= j < i -> Znth j ls1 = Znth j ls2)\n  LOCAL (temp _str1 str1; temp _str2 str2; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh1 (tarray tschar (Zlength ls1 + 1))\n          (map Vbyte (ls1 ++ [Byte.zero])) str1;\n       data_at sh2 (tarray tschar (Zlength ls2 + 1))\n          (map Vbyte (ls2 ++ [Byte.zero])) str2)).\n- finish.\n- fastforward.\n  forward_if (temp _t'1 (bool2val (Z.eqb i (Zlength ls1) && Z.eqb i (Zlength ls2)))).\n  (* these two parts are not much simplified *)\n  { forward. cstring1. entailer!!.\n    unfold bool2val; f_equal.\n    rewrite (proj2 (Z.eqb_eq _ _)) by auto.\n    unfold Int.cmp.\n    destruct (Int.eq (Int.repr (Byte.signed (Znth (Zlength ls1) (ls2 ++ [Byte.zero])))) (Int.repr 0)) eqn:Heqb;\n    do_repr_inj Heqb. (* utilize this internal tactic *)\n    - rewrite (proj2 (Z.eqb_eq _ _)) by cstring.\n      auto.\n    - rewrite (proj2 (Z.eqb_neq _ _)) by cstring.\n      auto.\n  }\n  {\n    forward. entailer!!.\n    rewrite (proj2 (Z.eqb_neq _ _)) by cstring.\n    auto.\n  }\n  fastforward.\n    finish.\n    finish. \n    finish.\n  assert (HZnth: Byte.signed (Znth i (ls1 ++ [Byte.zero])) =\n    Byte.signed (Znth i (ls2 ++ [Byte.zero]))) by lia.\n  finish.\nQed.\n\nLemma body_strcpy: semax_body Vprog Gprog f_strcpy strcpy_spec.\nProof.\nstart_function.\nunfold cstring,cstringn in *.\nrename s into ls.\nfastforward.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _i (Vptrofs (Ptrofs.repr i)); temp _dest dest; temp _src src)\n  SEP (data_at sh (tarray tschar n)\n        (map Vbyte (sublist 0 i ls) ++ repeat Vundef (Z.to_nat (n - i))) dest;\n       data_at sh' (tarray tschar (Zlength ls + 1)) (map Vbyte (ls ++ [Byte.zero])) src)).\nall: finish.\nQed.\n\nEnd Alternate.\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_strlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.1560800475455088}}
{"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 Spec.\n\n  Definition table_create3_spec (g_rd: Pointer) (map_addr: Z64) (level: Z64) (g_rtt': Pointer) (rtt_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level, rtt_addr with\n    | VZ64 map_addr, VZ64 level, VZ64 rtt_addr =>\n      rely is_int64 map_addr; rely is_int64 rtt_addr; rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      let rtt_gidx := __addr_to_gidx rtt_addr in\n      rely is_gidx rtt_gidx;\n      rely (peq (base g_rd) ginfo_loc);\n      rely (peq (base g_rtt') ginfo_loc);\n      rely (offset g_rtt' =? rtt_gidx);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx; rely is_gidx root_gidx;\n      when adt == query_oracle adt;\n      (* hold root lock *)\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      if level =? 1 then\n        (* walk until root *)\n        let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n        let adt :=  adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n        create_table root_gidx idx0 rtt_addr rtt_gidx rd_gidx 1 map_addr adt\n      else\n        (* walk deeper root *)\n        rely (level >? 1);\n        rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n        rely (gtype groot =? GRANULE_STATE_TABLE);\n        let entry0 := (g_data (gnorm groot)) @ idx0 in\n        rely is_int64 entry0;\n        let phys0 := __entry_to_phys entry0 3 in\n        let lv1_gidx := __addr_to_gidx phys0 in\n        if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n          (* level 1 valid, hold level 1 lock *)\n          let glv1 := (gs (share adt)) @ lv1_gidx in\n          rely prop_dec (glock glv1 = None);\n          rely (tbl_level (gaux glv1) =? 1);\n          if level =? 2 then\n            (* walk until level 1 *)\n            let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n            create_table lv1_gidx idx1 rtt_addr rtt_gidx rd_gidx 2 map_addr adt\n          else\n            (* walk deeper level 1 *)\n            rely (level >? 2);\n            rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n            rely (gtype glv1 =? GRANULE_STATE_TABLE);\n            let entry1 := (g_data (gnorm glv1)) @ idx1 in\n            rely is_int64 entry1;\n            let phys1 := __entry_to_phys entry1 3 in\n            let lv2_gidx := __addr_to_gidx phys1 in\n            if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n              (* level 2 valid, hold level 2 lock *)\n              let glv2 := (gs (share adt)) @ lv2_gidx in\n              rely (tbl_level (gaux glv2) =? 2);\n              rely prop_dec (glock glv2 = None);\n              if level =? 3 then\n                (* walk until level 2 *)\n                let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n                let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n                create_table lv2_gidx idx2 rtt_addr rtt_gidx rd_gidx 3 map_addr adt\n              else None\n            else\n              (* level 2 invalid *)\n              Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n        else\n          (* level 1 invalid *)\n          Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef3/Specs/table_create3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.2720245628973633, "lm_q1q2_score": 0.15605461803092444}}
{"text": "Require Import Program.\n\nRequire Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.\nRequire Import Cop Ctypes ClightC.\nRequire Import AsmC.\nRequire SimMemInjInvC.\nRequire Import MutrecA MutrecAspec MutrecAproof.\nRequire Import CoqlibC.\nRequire Import ValuesC.\nRequire Import LinkingC.\nRequire Import MapsC.\nRequire Import AxiomsC.\nRequire Import Ord.\nRequire Import MemoryC.\nRequire Import SmallstepC.\nRequire Import Events.\nRequire Import Preservation.\nRequire Import Integers.\nRequire Import LocationsC Conventions.\nRequire Import Conventions1C.\n\nRequire Import AsmregsC.\nRequire Import MatchSimModSem.\nRequire Import StoreArguments.\nRequire Import AsmStepInj IntegersC.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import CtypingC.\nRequire Import CopC.\n\nRequire Import MatchSimModSem ModSemProps.\nRequire Import Conventions1C.\n\nRequire Import IdSimExtra IdSimInvExtra IdSimClightExtra.\nRequire Import mktac.\n\nSet Implicit Arguments.\n\nLocal Opaque Z.mul Z.add Z.sub Z.div.\n\nInductive match_states_a_internal:\n  state -> state -> meminj -> mem -> mem -> Prop :=\n| match_Callstate\n    i m_src m_tgt j\n  :\n    match_states_a_internal\n      (Callstate i m_src)\n      (Callstate i m_tgt)\n      j m_src m_tgt\n| match_Interstate\n    i m_src m_tgt j\n  :\n    match_states_a_internal\n      (Interstate i m_src)\n      (Interstate i m_tgt)\n      j m_src m_tgt\n| match_Returnstate\n    i m_src m_tgt j\n  :\n    match_states_a_internal\n      (Returnstate i m_src)\n      (Returnstate i m_tgt)\n      j m_src m_tgt\n.\n\nSection INJINV.\n\nVariable P: SimMemInjInv.memblk_invariant.\n\nLocal Instance SimMemP: SimMem.class := SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P.\nLocal Instance SimSymbP: SimSymb.class SimMemP := SimMemInjInvC.SimSymbIdInv P.\n\nLocal Existing Instance SoundTop.Top.\n\nInductive match_states_a_inv\n  : unit -> state -> state -> SimMem.t -> Prop :=\n| match_states_a_intro\n    st_src st_tgt j m_src m_tgt sm0\n    (MWFSRC: m_src = sm0.(SimMem.src))\n    (MWFTGT: m_tgt = sm0.(SimMem.tgt))\n    (MWFINJ: j = sm0.(SimMemInjInv.minj).(SimMemInj.inj))\n    (MATCHST: match_states_a_internal st_src st_tgt j m_src m_tgt)\n    (MWF: SimMem.wf sm0)\n  :\n    match_states_a_inv\n      tt st_src st_tgt sm0\n.\n\nLemma a_inj_inv_id\n      (WF: Sk.wf (MutrecAspec.module))\n  :\n    exists mp,\n      (<<SIM: ModPair.sim mp>>)\n      /\\ (<<SRC: mp.(ModPair.src) = (MutrecAspec.module)>>)\n      /\\ (<<TGT: mp.(ModPair.tgt) = (MutrecAspec.module)>>)\n.\nProof.\n  eexists (ModPair.mk _ _ _); s.\n  esplits; eauto. instantiate (1:=SimMemInjInvC.mk bot1 _ _).\n  econs; ss; i.\n  { econs; ss; i; clarify. }\n  eapply match_states_sim with (match_states := match_states_a_inv); ss.\n  - apply unit_ord_wf.\n  - eapply SoundTop.sound_state_local_preservation.\n\n  - i. ss. exploit SimSymbIdInv_match_globals.\n    { inv SIMSKENV. ss. eauto. }\n    instantiate (1 := prog). intros GEMATCH.\n    inv INITTGT. inv SAFESRC. inv SIMARGS. inv H. ss.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des.\n    clarify.\n    esplits; eauto.\n    + econs; eauto.\n    + refl.\n    + econs; eauto.\n      assert (i = i0).\n      { subst. inv VALS. inv H2. ss. }\n      subst. econs; eauto.\n    + ss.\n\n  - i. ss. exploit SimSymbIdInv_match_globals.\n    { inv SIMSKENV. ss. eauto. }\n    instantiate (1 := prog). intros GEMATCH.\n    des. inv SAFESRC. inv SIMARGS.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des; eauto.\n    esplits. econs; ss; eauto.\n    + clear -MWF INJ FPTR FPTR0.\n      rewrite FPTR in FPTR0. inv FPTR0; ss.\n      rewrite H1 in INJ. clarify.\n    + rewrite VS in VALS. inv VALS; ss. inv H3. inv H1. auto.\n    + ss.\n\n  - i. ss. inv MATCH; eauto.\n\n  - i. ss. clear SOUND. inv CALLSRC. inv MATCH. inv MATCHST. inversion SIMSKENV; subst. ss.\n    i. ss. exploit SimSymbIdInv_match_globals.\n    { inv SIMSKENV. ss. eauto. }\n    instantiate (2 := prog). intros GEMATCH.\n    inv GEMATCH. exploit SYMBLE; eauto. i. des; eauto.\n    esplits; eauto.\n    + econs; ss; eauto.\n    + econs; ss; econs; eauto.\n    + refl.\n    + instantiate (1:=top4). ss.\n\n  - i. ss. clear SOUND HISTORY.\n    exists (SimMemInjInvC.unlift' sm_arg sm_ret).\n    inv AFTERSRC. inv MATCH. inv MATCHST.\n    esplits; eauto.\n    + econs; eauto. inv SIMRET; ss. rewrite INT in *. inv RETV. ss.\n    + inv SIMRET; ss. econs; eauto. econs; eauto.\n    + refl.\n\n  - i. ss. inv FINALSRC. inv MATCH. inv MATCHST.\n    esplits; eauto.\n    + econs.\n    + econs; eauto. econs.\n    + refl.\n\n  - right. ii. des.\n    esplits.\n    + i. inv MATCH. inv MATCHST.\n      * unfold ModSem.is_step. do 2 eexists. ss. econs; eauto.\n      * unfold safe_modsem in H.\n        exploit H. eapply star_refl. ii. des; clarify. inv EVSTEP.\n      * ss. exfalso. eapply NOTRET. econs. ss.\n    + ii. inv STEPTGT; inv MATCH; inv MATCHST.\n      * esplits; eauto.\n        { left. eapply plus_one. econs. }\n        refl.\n        econs; eauto. econs.\n      * esplits; eauto.\n        { left. eapply plus_one. econs 2. eauto. }\n        refl.\n        econs; eauto. econs.\nQed.\n\nEnd INJINV.\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/IdSimMutrecAIdInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.2598256264980406, "lm_q1q2_score": 0.15594431274536236}}
{"text": "Require Import VST.sepcomp.semantics.\n\nRequire Import VST.veric.juicy_base. \n\nRequire Import VST.veric.juicy_mem.  \nRequire Import VST.sepcomp.extspec.\nRequire Import VST.veric.ghost_PCM.\nRequire Import VST.veric.juicy_extspec.\n\nRequire Import VST.veric.res_predicates.\nRequire Import VST.veric.mpred.\nRequire Import VST.veric.seplog.\n\n(*********copied from initial_world***********)\nFixpoint find_id (id: ident) (G: funspecs) : option funspec  :=\n match G with\n | (id', f)::G' => if eq_dec id id' then Some f else find_id id G'\n | nil => None\n end.\n\nDefinition cond_approx_eq n A P1 P2 :=\n  (forall ts,\n      fmap (dependent_type_functor_rec ts (AssertTT A)) (approx n) (approx n) (P1 ts) =\n      fmap (dependent_type_functor_rec ts (AssertTT A)) (approx n) (approx n) (P2 ts)).\n\nDefinition func_at'' fsig cc A P Q :=\n  pureat (SomeP (SpecTT A) (packPQ P Q)) (FUN fsig cc).\n(*also copy lemmas on these from initial_world? or isolate in general file?*)\n\n(**********************************************)\n\n\nModule Type GENERAL_SEPARATION_LOGIC_SOUNDNESS.\n\nParameter F T: Type. (*Clight instantiates := fundef V:=type*)\n\nDefinition genv:Type := Genv.t F T.\n\n(*duplicated from tycontext to prevent specialization to Clight*)\nDefinition filter_genv (ge: genv) : genviron := Genv.find_symbol ge.\nDefinition empty_environ (ge: genv) := mkEnviron (filter_genv ge) (Map.empty _) (Map.empty _).\n\nParameter C: Type.\nParameter Sem: genv -> CoreSemantics C Memory.mem.\nParameter genv_symb_injective: genv -> extspec.injective_PTree block.\n\nDefinition jsafeN {Z} (Hspec : juicy_ext_spec Z) (ge: genv) :=\n  @jsafeN_ genv _ _ genv_symb_injective (*(genv_symb := fun ge: genv => Genv.genv_symb ge)*)\n           (Sem ge) Hspec ge.\n\nDefinition matchfunspecs (ge : genv) (G : funspecs) (Phi : rmap) :=\nforall (b : block) (fsig : compcert_rmaps.funsig)\n  (cc : calling_convention) (A : TypeTree)\n  (P\n   Q : forall ts : list Type,\n       (dependent_type_functor_rec ts (AssertTT A)) (pred rmap)),\n(func_at'' fsig cc A P Q (b, 0)) Phi ->\nexists\n  (id : ident) (P'\n                Q' : forall ts : list Type,\n                     (dependent_type_functor_rec ts (AssertTT A)) mpred) \n(P'_ne : super_non_expansive P') (Q'_ne : super_non_expansive Q'),\n  Genv.find_symbol ge id = Some b /\\\n  find_id id G = Some (mk_funspec fsig cc A P' Q' P'_ne Q'_ne) /\\\n  cond_approx_eq (level Phi) A P P' /\\ cond_approx_eq (level Phi) A Q Q'.\n\nDefinition EPoint_sound {Espec: OracleKind} FS m (h:nat) (entryPT:ident) (g:genv) :=\n     { b : block & { q : C &\n       (Genv.find_symbol g entryPT = Some b) *\n       (forall jm, m_dry jm = m -> exists jm', semantics.initial_core (juicy_core_sem (Sem g)) h\n                    jm q jm' (Vptr b Ptrofs.zero) nil) *\n       forall n z,\n         { jm |\n           m_dry jm = m /\\ level jm = n /\\\n           nth_error (ghost_of (m_phi jm)) 0 = Some (Some (ext_ghost z, NoneP)) /\\\n           jsafeN (@OK_spec Espec) g n z q jm /\\\n           res_predicates.no_locks (m_phi jm) /\\\n           matchfunspecs g FS (m_phi jm) /\\\n           app_pred (funspecs_assert (make_tycontext_s FS) (empty_environ g))  (m_phi jm) } } }%type.\n\nEnd GENERAL_SEPARATION_LOGIC_SOUNDNESS.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/GeneralSeparationLogicSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.15577758150282037}}
{"text": "Require Import\n  Hask.Control.Monad\n  Hask.Control.Monad.Trans.State\n  Pact.Data.Monoid\n  Pact.Data.Either\n  Pact.Lib\n  Pact.Ty\n  Pact.Value\n  Pact.Exp\n  Pact.SemTy\n  Pact.Lang\n  Pact.Lang.CapabilityType\n  Pact.Lang.Capability\n  Hask.Control.Lens.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Equations With UIP.\n\nGeneralizable All Variables.\nSet Primitive Projections.\n\nImport ListNotations.\n\nOpen Scope Ty_scope.\n\n(******************************************************************************\n * Facts about Capabilities\n *)\n\nLemma get_cap_head `(c : Cap s) cs :\n  get_cap c (AToken c :: cs) = Some (valueOf (s:=s) c).\nProof.\n  destruct c.\n  rewrite /= !eq_dec_refl //.\nQed.\n\nTheorem with_capability_idem\n  (n : string) `(c : Cap s)\n  (p : Cap s \u2192 PactM unit)\n  (m : reflectTy (TPair (valueTy s) (valueTy s)) \u2192\n       PactM (reflectTy (valueTy s)))\n  `(f : PactM a) :\n  with_capability n c p m (with_capability n c p m f) =\n  with_capability n c p m f.\nProof.\n  rewrite /with_capability /__check_capability.\n  unravel.\n  extensionality st.\n  matches.\n  - rewrite Heqe //.\n    sauto.\n  - do 2 matches.\n    destruct (p _ _) as [|[? [? ?]]]; auto.\n    simpl.\n    destruct (__claim_resource _ _ _) as [|[? [? ?]]]; auto.\n    simpl.\n    rewrite get_cap_head //=.\n    sauto.\nQed.\n\nTheorem require_capability_idem (n : string) `(c : Cap s) :\n  (require_capability c >> require_capability c) =\n   require_capability c.\nProof.\n  rewrite /require_capability.\n  unravel; extensionality st.\n  now repeat matches.\nQed.\n\nLemma extend_f {A B : Type} (f g : A \u2192 B) :\n  (\u03bb x, f x) = (\u03bb x, g x) \u2192 (\u2200 x, f x = g x).\nProof.\n  intros.\n  setoid_rewrite <- eta_expansion in H.\n  now rewrite H.\nQed.\n\nTheorem with_require_sometimes_noop\n  (n : string) `(c : Cap s)\n  (p : Cap s \u2192 PactM unit)\n  (m : reflectTy (TPair (valueTy s) (valueTy s)) \u2192\n       PactM (reflectTy (valueTy s))) :\n\n  (* Assuming we are NOT within a defcap predicate... *)\n  getsT __in_defcap = pure[PactM] false \u2192\n\n  (* Assuming we ARE within the defining module... *)\n  getsT (__in_module n) = pure[PactM] true \u2192\n\n  (* Assuming the predicate always succeeds and changes nothing... *)\n  p c = pure[PactM] tt \u2192\n\n  (* Assuming composed predicates only occur within a defcap: This should be\n     true of the system as a whole, but this theorem is quantified over all\n     possible states. *)\n  (getsT __in_defcap = pure[PactM] false \u2192 getsT _to_compose = pure[PactM] []) \u2192\n\n  (* Assuming that the resource type is unit...  *)\n  \u2200 H, eq_dec (valueTy s) TUnit = left H ->\n\n  (* Then just checking a capability is the same as doing nothing. *)\n  with_capability n c p m (require_capability c) = pure[PactM] tt.\n\nProof.\n  rewrite /with_capability /require_capability /__check_capability; intros.\n  unravel; extensionality st.\n  matches.\n  - rewrite Heqe //.\n  - matches.\n    + exfalso.\n      apply extend_f with (x:=st) in H.\n      inv H.\n      congruence.\n    + matches.\n      * destruct (p _ _) as [|[? [? ?]]] eqn:Heqe2; auto.\n        ** rewrite H1 in Heqe2.\n           discriminate.\n        ** unfold __claim_resource.\n           rewrite H4 /= get_cap_head /=.\n           pose proof (H2 H).\n           unfold getsT in H5.\n           apply extend_f with (x:=st) in H5.\n           inv H5.\n           rewrite H1 in Heqe2.\n           inv Heqe2.\n           reflexivity.\n      * exfalso.\n        unfold getsT in H0.\n        apply extend_f with (x:=st) in H0.\n        inv H0.\n        congruence.\nQed.\n", "meta": {"author": "kadena-io", "repo": "pact-model", "sha": "2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4", "save_path": "github-repos/coq/kadena-io-pact-model", "path": "github-repos/coq/kadena-io-pact-model/pact-model-2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4/src/Lang/CapabilityFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.15570340427200688}}
{"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 DenseOrder.\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 MemoryFacts.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire ReorderTView.\nRequire Import MemoryReorder.\nRequire Import MemoryMerge.\n\nRequire Import Syntax.\nRequire Import Semantics.\nRequire Import ProgressStep.\n\nSet Implicit Arguments.\n\nLemma future_read_step\n      lc1 mem1 mem1' loc ts val released ord lc2\n      (WF: Local.wf lc1 mem1)\n      (MEM: Memory.closed mem1)\n      (FUTURE: Memory.future mem1 mem1')\n      (STEP: Local.read_step lc1 mem1 loc ts val released ord lc2):\n  exists released' lc2',\n    <<STEP: Local.read_step lc1 mem1' loc ts val released' ord lc2'>> /\\\n    <<REL: View.opt_le released' released>> /\\\n    <<LOCAL: sim_local lc2' lc2>>.\nProof.\n  inv STEP. exploit Memory.future_get1; eauto. i. des.\n  esplits.\n  - econs; eauto. eapply TViewFacts.readable_mon; eauto; refl.\n  - auto.\n  - econs; s.\n    + apply TViewFacts.read_tview_mon; auto.\n      * refl.\n      * apply WF.\n      * eapply MEM. eauto.\n      * refl.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma future_fulfill_step\n      lc1 sc1 sc1' loc from to val releasedm releasedm' released ord lc2 sc2\n      (ORD: Ordering.le ord Ordering.relaxed)\n      (REL_LE: View.opt_le releasedm' releasedm)\n      (STEP: fulfill_step lc1 sc1 loc from to val releasedm released ord lc2 sc2):\n  fulfill_step lc1 sc1' loc from to val releasedm' released ord lc2 sc1'.\nProof.\n  assert (TVIEW: TView.write_tview (Local.tview lc1) sc1 loc to ord = TView.write_tview (Local.tview lc1) sc1' loc to ord).\n  { unfold TView.write_tview. repeat (condtac; viewtac). }\n  inversion STEP. subst lc2 sc2.\n  rewrite TVIEW. econs; eauto.\n  - etrans; eauto. unfold TView.write_released. condtac; econs. repeat apply View.join_spec.\n    + rewrite <- View.join_l. apply View.unwrap_opt_le. auto.\n    + rewrite <- ? View.join_r. rewrite TVIEW. refl.\n  - econs; try apply WRITABLE.\nQed.\n\n\nLemma reorder_read_read\n      loc1 ts1 val1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      lc0 mem0\n      lc1\n      lc2\n      (LOC: loc1 = loc2 -> Ordering.le ord1 Ordering.plain /\\ Ordering.le ord2 Ordering.plain)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; try apply READABLE0; eauto; try refl.\n    apply TViewFacts.read_tview_incr.\n  - refine (Local.read_step_intro _ _ _ _ _); eauto.\n    + s. unfold View.singleton_ur_if.\n      econs; repeat (try condtac; try splits; aggrtac; eauto; try apply READABLE;\n                     unfold TimeMap.singleton, LocFun.add in *).\n      * specialize (LOC eq_refl). des. viewtac.\n      * specialize (LOC eq_refl). des. viewtac.\n      * specialize (LOC eq_refl). des. viewtac.\n    + apply TView.antisym; apply ReorderTView.read_read_tview;\n        (try by apply WF0);\n        (try by eapply MEM0; eauto).\nQed.\n\nLemma reorder_read_promise\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 released2 kind2\n      lc0 mem0\n      lc1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 val2 released2 lc2 mem2 kind2):\n  exists lc1' lc2' released1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 val2 released2 lc1' mem2 kind2>> /\\\n    <<STEP2: Local.read_step lc1' mem2 loc1 ts1 val1 released1' ord1 lc2'>> /\\\n    <<REL1: View.opt_le released1' released1>> /\\\n    <<LOCAL: sim_local lc2' lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit Memory.promise_future; try exact PROMISE; try apply WF0; eauto. i. des.\n  exploit Memory.promise_get1; eauto. i. des.\n  esplits; eauto.\n  - econs; eauto.\n  - econs; eauto.\n    s. eapply TViewFacts.readable_mon; eauto; try refl.\n  - s. econs; ss.\n    + apply TViewFacts.read_tview_mon; try refl; try apply WF0; eauto.\n      eapply MEM0. eauto.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma reorder_read_promise_diff\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 released2 kind2\n      lc0 mem0\n      lc1\n      lc2 mem2\n      (DIFF: (loc1, ts1) <> (loc2, to2))\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 val2 released2 lc2 mem2 kind2):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 val2 released2 lc1' mem2 kind2>> /\\\n    <<STEP2: Local.read_step lc1' mem2 loc1 ts1 val1 released1 ord1 lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryFacts.promise_get1_diff; eauto. i. des.\n  esplits; eauto.\n  - econs; eauto.\n  - econs; eauto.\nQed.\n\nLemma reorder_read_fulfill\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      (LOC: loc1 <> loc2)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord2 Ordering.acqrel)\n      (RELM_WF: View.opt_wf releasedm2)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>>.\nProof.\n  guardH ORD.\n  exploit Local.read_step_future; eauto. i. des.\n  inv STEP1. inv STEP2.\n  esplits; eauto.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s.\n      condtac; econs. repeat (try condtac; aggrtac; try apply WF0).\n    + eapply TViewFacts.writable_mon; eauto; try refl. apply TVIEW_FUTURE.\n  - econs; eauto.\n    s. inv READABLE.\n    econs; repeat (try condtac; aggrtac; try apply WF0; eauto; unfold TimeMap.singleton).\n  - s. econs; s.\n    + apply ReorderTView.read_write_tview; try apply WF0; auto.\n    + apply SimPromises.sem_bot.\nQed.\n\nLemma reorder_read_write\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2 mem2\n      kind\n      (LOC: loc1 <> loc2)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord2 Ordering.acqrel)\n      (RELM_WF: View.opt_wf releasedm2)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.write_step lc1 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind):\n  exists released2' mem2' lc1' lc2',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc2 mem2' kind>> /\\\n    <<STEP2: Local.read_step lc1' mem2' loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<RELEASED: View.opt_le released2' released2>> /\\\n    <<MEM: sim_memory mem2' mem2>>.\nProof.\n  guardH ORD.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit write_promise_fulfill; try exact STEP2; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_promise_diff; try exact STEP1; try exact STEP0; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_fulfill; try exact STEP5; try exact STEP3; eauto; try by viewtac. i. des.\n  exploit promise_fulfill_write; try exact x4; try exact STEP6; eauto; try by viewtac.\n  { i. exploit ORD0; eauto. i. des.\n    splits; auto. inv STEP1. auto.\n  }\n  i. des.\n  inv STEP1.\n  inversion STEP. inv WRITE. hexploit MemoryFacts.promise_get1_diff; try exact PROMISE; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  esplits; eauto.\n  inv STEP7. econs; eauto.\nQed.\n\nLemma reorder_read_update\n      loc1 ts1 val1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      from3 to3 val3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2\n      lc3 sc3 mem3\n      kind\n      (LOC: loc1 <> loc2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2)\n      (STEP3: Local.write_step lc2 sc0 mem0 loc2 from3 to3 val3 released2 released3 ord3 lc3 sc3 mem3 kind):\n  exists released3' mem3' lc1' lc2' lc3',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc2 from3 to3 val3 released2 released3' ord3 lc2' sc3 mem3' kind>> /\\\n    <<STEP3: Local.read_step lc2' mem3' loc1 ts1 val1 released1 ord1 lc3'>> /\\\n    <<LOCAL: sim_local lc3' lc3>> /\\\n    <<RELEASED: View.opt_le released3' released3>> /\\\n    <<MEM: sim_memory mem3' mem3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_read_read; try exact STEP1; try exact STEP2; eauto; try congr. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  hexploit reorder_read_write; try exact STEP4; try exact STEP_SRC; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_read_fence\n      loc1 ts1 val1 released1 ord1\n      ordr2 ordw2\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      (ORDR2: Ordering.le ordr2 Ordering.relaxed)\n      (ORDW2: Ordering.le ordw2 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.fence_step lc1 sc0 ordr2 ordw2 lc2 sc2):\n  exists lc1' lc2' sc2',\n    <<STEP1: Local.fence_step lc0 sc0 ordr2 ordw2 lc1' sc2'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto. s.\n    unfold TView.write_fence_tview, TView.read_fence_tview, TView.write_fence_sc.\n    econs; repeat (try condtac; try splits; aggrtac; try apply READABLE).\n  - s. econs; s.\n    + etrans.\n      * apply ReorderTView.read_write_fence_tview; auto.\n        eapply TViewFacts.read_fence_future; apply WF0.\n      * apply TViewFacts.write_fence_tview_mon; try refl.\n        apply ReorderTView.read_read_fence_tview; try apply WF0; auto.\n        exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n        eapply TViewFacts.read_future; eauto.\n    + apply SimPromises.sem_bot.\n  - unfold TView.write_fence_sc, TView.read_fence_tview.\n    repeat condtac; aggrtac.\nQed.\n\nLemma reorder_fulfill_read\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      (LOC: loc1 <> loc2)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2):\n  exists lc1',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: fulfill_step lc1' sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply REMOVE; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; try apply READABLE; eauto; try refl.\n    apply TViewFacts.write_tview_incr. apply WF0.\n  - unfold Local.tview at 2.\n    unfold Local.promises at 2.\n    rewrite ReorderTView.read_write_tview_eq; eauto; try apply WF0; cycle 1.\n    { eapply MEM0. eauto. }\n    econs; try exact REMOVE; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac).\n    + s. unfold View.singleton_ur_if.\n      econs; repeat (try condtac; try splits; aggrtac; eauto; try apply WRITABLE;\n                     unfold TimeMap.singleton, LocFun.add in *);\n        (try by inv WRITABLE; eapply TimeFacts.le_lt_lt; eauto; aggrtac).\nQed.\n\nLemma reorder_fulfill_promise\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 val2 released2 kind2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 val2 released2 lc2 mem2 kind2):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 val2 released2 lc1' mem2 kind2>> /\\\n    <<STEP2: fulfill_step lc1' sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply WF0; eauto. i. des.\n  hexploit Memory.promise_future; eauto. i. des.\n  exploit MemoryReorder.remove_promise; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\nQed.\n\nLemma reorder_fulfill_fulfill\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (LOC: loc1 <> loc2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: fulfill_step lc1 sc1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc1'>> /\\\n    <<STEP2: fulfill_step lc1' sc1' loc1 from1 to1 val1 releasedm1 released1 ord1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2.\n  hexploit Memory.remove_future; try apply WF0; eauto. i. des.\n  exploit MemoryReorder.remove_remove; try apply REMOVE; try apply REMOVE0; eauto. i. des.\n  unfold Local.promises in REMOVE0.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac; try apply WF0).\n    + eapply TViewFacts.writable_mon; eauto; try refl.\n      * apply TViewFacts.write_tview_incr. apply WF0.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. s. condtac; econs.\n      repeat (try condtac; aggrtac; try apply WF0).\n    + inv WRITABLE. econs; i.\n      * eapply TimeFacts.le_lt_lt; [|apply TS].\n        repeat (try condtac; viewtac; unfold TimeMap.singleton in *).\n  - s. econs; ss.\n    + apply ReorderTView.write_write_tview; auto. apply WF0.\n    + apply SimPromises.sem_bot.\n  - refl.\nQed.\n\nLemma reorder_fulfill_write\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2 mem2\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (LOC: loc1 <> loc2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL1_CLOSED: Memory.closed_opt_view releasedm1 mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.write_step lc1 sc1 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2):\n  exists released2' lc1' lc2' sc1' sc2' mem2',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc1' mem2' kind2>> /\\\n    <<STEP2: fulfill_step lc1' sc1' loc1 from1 to1 val1 releasedm1 released1 ord1 lc2' sc2'>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>> /\\\n    <<MEM: sim_memory mem2' mem2>>.\nProof.\n  exploit fulfill_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP1; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP5; try exact WF3; eauto; try by viewtac. i. des.\n  exploit reorder_fulfill_fulfill; try exact STEP5; try exact STEP3; eauto; try by viewtac. i. des.\n  exploit promise_fulfill_write; eauto.\n  { i. exploit ORD; eauto. i. des. splits; ss.\n    ii. unfold Memory.get in GET.\n    erewrite fulfill_step_promises_diff in GET; eauto.\n  }\n  i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fulfill_update\n      loc1 from1 to1 val1 releasedm1 released1 ord1\n      loc2 ts2 val2 released2 ord2\n      from3 to3 val3 released3 ord3 kind3\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      lc3 sc3 mem3\n      (LOC: loc1 <> loc2)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL1_WF: View.opt_wf releasedm1)\n      (REL1_CLOSED: Memory.closed_opt_view releasedm1 mem0)\n      (STEP1: fulfill_step lc0 sc0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 ts2 val2 released2 ord2 lc2)\n      (STEP3: Local.write_step lc2 sc1 mem0 loc2 from3 to3 val3 released2 released3 ord3 lc3 sc3 mem3 kind3):\n  exists released3' lc1' lc2' lc3' sc2' sc3' mem2',\n    <<STEP1: Local.read_step lc0 mem0 loc2 ts2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc2 from3 to3 val3 released2 released3' ord3 lc2' sc2' mem2' kind3>> /\\\n    <<STEP3: fulfill_step lc2' sc2' loc1 from1 to1 val1 releasedm1 released1 ord1 lc3' sc3'>> /\\\n    <<LOCAL: sim_local lc3' lc3>> /\\\n    <<RELEASED: View.opt_le released3' released3>> /\\\n    <<SC: TimeMap.le sc3' sc3>> /\\\n    <<MEM: sim_memory mem2' mem3>>.\nProof.\n  exploit fulfill_step_future; try exact STEP1; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_read; try exact STEP1; try exact STEP2; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP4; eauto. i. des.\n  exploit sim_local_write; try exact STEP3; try exact LOCAL; try refl; eauto. i. des.\n  exploit reorder_fulfill_write; try exact STEP4; try exact STEP_SRC; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_read\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 ts3 val3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3\n      (LOC: loc1 <> loc3)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord3 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.read_step lc2 mem0 loc3 ts3 val3 released3 ord3 lc3):\n  exists lc1' lc2',\n    <<STEP1: Local.read_step lc0 mem0 loc3 ts3 val3 released3 ord3 lc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1 released2 ord2 lc3 sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_read; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  exploit reorder_read_read; try exact STEP1; try exact STEP0; eauto; try congr. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_promise\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 released3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 mem3\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.promise_step lc2 mem0 loc3 from3 to3 val3 released3 lc3 mem3 kind3):\n  exists released1' lc1' lc2' lc3' sc3',\n    <<STEP1: Local.promise_step lc0 mem0 loc3 from3 to3 val3 released3 lc1' mem3 kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem3 loc1 ts1 val1 released1' ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1' released2 ord2 lc3' sc3'>> /\\\n    <<RELEASED1: View.opt_le released1' released1>> /\\\n    <<LOCAL: sim_local lc3' lc3>> /\\\n    <<SC: TimeMap.le sc3' sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_read_promise; try exact STEP1; try exact STEP0; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_local_fulfill; try exact STEP4; try exact LOCAL; try exact REL1;\n    try exact WF3; try exact WF5; try refl; eauto; try by viewtac. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_promise_diff\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 released3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 mem3\n      (DIFF: (loc1, ts1) <> (loc3, to3))\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.promise_step lc2 mem0 loc3 from3 to3 val3 released3 lc3 mem3 kind3):\n  exists lc1' lc2',\n    <<STEP1: Local.promise_step lc0 mem0 loc3 from3 to3 val3 released3 lc1' mem3 kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem3 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc0 loc1 from2 to2 val2 released1 released2 ord2 lc3 sc2>>.\nProof.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_promise; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit reorder_read_promise_diff; try exact STEP1; try exact STEP0; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_update_fulfill\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 releasedm3 released3 ord3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 sc3\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (REL_WF: View.opt_wf releasedm3)\n      (REL_CLOSED: Memory.closed_opt_view releasedm3 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: fulfill_step lc2 sc2 loc3 from3 to3 val3 releasedm3 released3 ord3 lc3 sc3):\n  exists lc1' lc2' lc3' sc1' sc3',\n    <<STEP1: fulfill_step lc0 sc0 loc3 from3 to3 val3 releasedm3 released3 ord3 lc1' sc1'>> /\\\n    <<STEP2: Local.read_step lc1' mem0 loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc1' loc1 from2 to2 val2 released1 released2 ord2 lc3' sc3'>> /\\\n    <<LOCAL: sim_local lc3' lc3>> /\\\n    <<SC: TimeMap.le sc3' sc3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; try exact STEP1; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP2; eauto. i. des.\n  exploit reorder_fulfill_fulfill; try exact STEP2; try exact STEP3; eauto. i. des.\n  exploit fulfill_step_future; try exact STEP0; eauto; try by viewtac. i. des.\n  exploit reorder_read_fulfill; try exact STEP1; try exact STEP0; eauto; try by viewtac. i. des.\n  exploit fulfill_step_future; try exact STEP5; eauto; try by viewtac. i. des.\n  exploit Local.read_step_future; try exact STEP6; eauto; try by viewtac. i. des.\n  exploit sim_local_fulfill; try exact STEP4; try exact LOCAL0; try refl; eauto. i. des.\n  esplits; eauto.\n  - etrans; eauto.\n  - etrans; eauto.\nQed.\n\nLemma reorder_update_write\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 from3 to3 val3 releasedm3 released3 ord3 kind3\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3 sc3 mem3\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord3 Ordering.acqrel)\n      (REL_WF: View.opt_wf releasedm3)\n      (REL_CLOSED: Memory.closed_opt_view releasedm3 mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.write_step lc2 sc2 mem0 loc3 from3 to3 val3 releasedm3 released3 ord3 lc3 sc3 mem3 kind3):\n  exists released2' released3' lc1' lc2' lc3' sc1' sc3' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc3 from3 to3 val3 releasedm3 released3' ord3 lc1' sc1' mem1' kind3>> /\\\n    <<STEP2: Local.read_step lc1' mem1' loc1 ts1 val1 released1 ord1 lc2'>> /\\\n    <<STEP3: fulfill_step lc2' sc1' loc1 from2 to2 val2 released1 released2' ord2 lc3' sc3'>> /\\\n    <<LOCAL: sim_local lc3' lc3>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<RELEASED3: View.opt_le released3' released3>> /\\\n    <<SC: TimeMap.le sc3' sc3>> /\\\n    <<MEM: sim_memory mem1' mem3>>.\nProof.\n  guardH ORD3.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit fulfill_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit reorder_update_promise_diff; try exact STEP1; try exact STEP2; try exact STEP0; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit reorder_update_fulfill; try exact STEP6; try exact STEP7; try exact STEP4; eauto; try by viewtac. i. des.\n  exploit fulfill_step_future; try exact STEP8; try exact WF3; eauto; try by viewtac. i. des.\n  exploit promise_fulfill_write; eauto.\n  { i. exploit ORD; eauto. i. des.\n    splits; auto.\n    erewrite Local.read_step_promises; [|eauto].\n    ii. unfold Memory.get in GET. erewrite fulfill_step_promises_diff in GET; eauto.\n  }\n  i. des.\n  inv STEP1.\n  inversion STEP. inv WRITE. hexploit MemoryFacts.promise_get1_diff; try exact PROMISE; eauto.\n  { ii. inv H. congr. }\n  i. des.\n  esplits; try exact STEP10; eauto; try refl.\n  inv STEP9. econs; eauto.\nQed.\n\nLemma reorder_update_update\n      loc1 ts1 val1 released1 ord1\n      from2 to2 val2 released2 ord2\n      loc3 ts3 val3 released3 ord3\n      from4 to4 val4 released4 ord4 kind4\n      lc0 sc0 mem0\n      lc1\n      lc2 sc2\n      lc3\n      lc4 sc4 mem4\n      (LOC: loc1 <> loc3)\n      (TIME: ts1 <> to2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (ORD3: Ordering.le ord3 Ordering.relaxed)\n      (ORD: Ordering.le ord1 Ordering.acqrel \\/ Ordering.le ord4 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: fulfill_step lc1 sc0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2)\n      (STEP3: Local.read_step lc2 mem0 loc3 ts3 val3 released3 ord3 lc3)\n      (STEP4: Local.write_step lc3 sc2 mem0 loc3 from4 to4 val4 released3 released4 ord4 lc4 sc4 mem4 kind4):\n  exists released2' released4' lc1' lc2' lc3' lc4' sc2' sc4' mem2',\n    <<STEP1: Local.read_step lc0 mem0 loc3 ts3 val3 released3 ord3 lc1'>> /\\\n    <<STEP2: Local.write_step lc1' sc0 mem0 loc3 from4 to4 val4 released3 released4' ord4 lc2' sc2' mem2' kind4>> /\\\n    <<STEP3: Local.read_step lc2' mem2' loc1 ts1 val1 released1 ord1 lc3'>> /\\\n    <<STEP4: fulfill_step lc3' sc2' loc1 from2 to2 val2 released1 released2' ord2 lc4' sc4'>> /\\\n    <<LOCAL: sim_local lc4' lc4>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<RELEASED4: View.opt_le released4' released4>> /\\\n    <<SC: TimeMap.le sc4' sc4>> /\\\n    <<MEM: sim_memory mem2' mem4>>.\nProof.\n  guardH ORD.\n  exploit reorder_update_read; try exact STEP2; try exact STEP1; try exact STEP3; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP0; eauto. i. des.\n  hexploit reorder_update_write; try exact STEP5; try exact STEP6; try exact STEP4; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fence_read\n      ordr1 ordw1\n      loc2 to2 val2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (ORD2: Ordering.le ord2 Ordering.plain \\/ Ordering.le Ordering.acqrel ord2)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.read_step lc1 mem0 loc2 to2 val2 released2 ord2 lc2):\n  exists lc1' lc2' sc2',\n    <<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc0 ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc1>>.\nProof.\n  guardH ORD2. inv STEP1. inv STEP2.\n  esplits.\n  - econs; eauto.\n    eapply TViewFacts.readable_mon; eauto; try refl.\n    etrans.\n    + apply TViewFacts.write_fence_tview_incr. apply WF0.\n    + apply TViewFacts.write_fence_tview_mon; try refl; try apply WF0.\n      apply TViewFacts.read_fence_tview_incr. apply WF0.\n  - econs; eauto.\n  - s. econs; s.\n    + inversion MEM0. exploit CLOSED; eauto. i. des.\n      exploit TViewFacts.read_future; try exact GET; try apply WF0; eauto. i. des.\n      exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n      etrans; [|etrans].\n      * apply TViewFacts.write_fence_tview_mon; [|refl|refl|].\n        { apply ReorderTView.read_fence_read_tview; auto. apply WF0. }\n        { inversion MEM0. exploit CLOSED; eauto. i. des.\n          eapply TViewFacts.read_fence_future; eauto.\n        }\n      * apply ReorderTView.write_fence_read_tview; eauto.\n      * apply TViewFacts.read_tview_mon; auto; try refl.\n        eapply TViewFacts.write_fence_future; eauto.\n    + apply SimPromises.sem_bot.\n  - s. etrans.\n    + apply TViewFacts.write_fence_sc_mon; [|refl|refl].\n      apply ReorderTView.read_fence_read_tview; auto. apply WF0.\n    + eapply ReorderTView.write_fence_read_sc; auto.\n      eapply TViewFacts.read_fence_future; eauto; apply WF0.\nQed.\n\nLemma reorder_fence_promise\n      ordr1 ordw1\n      loc2 from2 to2 val2 released2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 mem2\n      kind\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 val2 released2 lc2 mem2 kind):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 val2 released2 lc1' mem2 kind>> /\\\n    <<STEP2: Local.fence_step lc1' sc0 ordr1 ordw1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto. s. i. destruct ordw1; inv ORDW1; inv H.\nQed.\n\nLemma reorder_fence_fulfill\n      ordr1 ordw1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: fulfill_step lc1 sc1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: fulfill_step lc0 sc0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2.\n  exploit TViewFacts.read_fence_future; try apply WF0; eauto. i. des.\n  hexploit TViewFacts.write_fence_future; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    + etrans; eauto. unfold TView.write_released. condtac; econs.\n      repeat apply View.join_spec.\n      * rewrite <- View.join_l. refl.\n      * rewrite <- ? View.join_r.\n        eapply TViewFacts.write_tview_mon; eauto; try refl.\n        { etrans.\n          - apply TViewFacts.write_fence_tview_incr. apply WF0.\n          - apply TViewFacts.write_fence_tview_mon; try refl; try apply WF0.\n            apply TViewFacts.read_fence_tview_incr. apply WF0.\n        }\n    + eapply TViewFacts.writable_mon; eauto; try refl.\n      * etrans.\n        { apply TViewFacts.read_fence_tview_incr. apply WF0. }\n        { apply TViewFacts.write_fence_tview_incr.\n          eapply TViewFacts.read_fence_future; apply WF0.\n        }\n      * apply TViewFacts.write_fence_sc_incr.\n  - econs; eauto. ss. ii. revert GET.\n    erewrite Memory.remove_o; eauto. condtac; ss. i. eapply RELEASE; eauto.\n  - s. econs; s.\n    + etrans; [|etrans].\n      * apply TViewFacts.write_fence_tview_mon; [|refl|refl|].\n        { apply ReorderTView.read_fence_write_tview; auto. apply WF0. }\n        { exploit Memory.remove_get0; eauto. s. i.\n          inv WF0. exploit PROMISES; eauto. i.\n          exploit TViewFacts.write_future_fulfill; try exact SC0; eauto.\n          { eapply MEM0. eauto. }\n          i. des.\n          eapply TViewFacts.read_fence_future; eauto.\n        }\n      * apply ReorderTView.write_fence_write_tview; auto.\n      * apply TViewFacts.write_tview_mon; auto; try refl.\n        apply TViewFacts.write_fence_sc_incr.\n    + apply SimPromises.sem_bot.\n  - etrans.\n    + apply TViewFacts.write_fence_sc_mon; [|refl|refl].\n      apply ReorderTView.read_fence_write_tview; auto. apply WF0.\n    + eapply ReorderTView.write_fence_write_sc; auto.\nGrab Existential Variables.\n  { apply TimeMap.bot. }\nQed.\n\nLemma reorder_fence_write\n      ordr1 ordw1\n      loc2 from2 to2 val2 releasedm2 released2 ord2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2 mem2 kind\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL2_WF: View.opt_wf releasedm2)\n      (REL2_CLOSED: Memory.closed_opt_view releasedm2 mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.write_step lc1 sc1 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind):\n  exists released2' lc1' lc2' sc1' sc2' mem1',\n    <<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2' ord2 lc1' sc1' mem1' kind>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<RELEASED2: View.opt_le released2' released2>> /\\\n    <<SC: TimeMap.le sc2' sc2>> /\\\n    <<MEM: sim_memory mem1' mem2>>.\nProof.\n  exploit Local.fence_step_future; eauto. i. des.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit reorder_fence_promise; try exact STEP1; try exact STEP0; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit reorder_fence_fulfill; try exact STEP5; try exact STEP3; eauto; try by viewtac. i. des.\n  exploit promise_fulfill_write; eauto.\n  { i. exploit ORD; eauto. i. des.\n    splits; auto. inv STEP1. auto.\n  }\n  i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fence_fence\n      ordr1 ordw1\n      ordr2 ordw2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 sc2\n      (ORDR1: Ordering.le ordr1 Ordering.acqrel)\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (ORDR2: Ordering.le ordr2 Ordering.relaxed)\n      (ORDW2: Ordering.le ordw2 Ordering.acqrel)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.fence_step lc1 sc1 ordr2 ordw2 lc2 sc2):\n  exists lc1' lc2' sc1' sc2',\n    <<STEP1: Local.fence_step lc0 sc0 ordr2 ordw2 lc1' sc1'>> /\\\n    <<STEP2: Local.fence_step lc1' sc1' ordr1 ordw1 lc2' sc2'>> /\\\n    <<LOCAL: sim_local lc2' lc2>> /\\\n    <<SC: TimeMap.le sc2' sc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\n  - ss. econs; ss.\n    + unfold TView.write_fence_tview, TView.write_fence_sc.\n      econs; repeat (try condtac; aggrtac; try apply WF0).\n    + apply SimPromises.sem_bot.\n  - unfold TView.write_fence_sc.\n    repeat (try condtac; aggrtac; try apply WF0).\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/ReorderStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15570340098192909}}
{"text": "Require Import Coq.Program.Basics. \n\nRequire Import FinProof.Common. \nRequire Import FinProof.MonadTransformers21. \nRequire Import FinProof.ProgrammingWith.\nRequire Import FinProof.StateMonad21Instances.  \n\nRequire Import UMLang.UrsusLib. \nRequire Import UMLang.GlobalClassGenerator.ClassGenerator.\n\nRequire Import UrsusTVM.Solidity.tvmFunc. \nRequire Import UrsusTVM.Solidity.tvmTypes. \nRequire Import String. \n\nLocal Open Scope record. \nLocal Open Scope program_scope.\nLocal Open Scope glist_scope.\n\nInductive LocalFields000I := | \u03b90000 | \u03b90001 .\nDefinition LocalState000L := [( XHMap (string*nat) ( XMaybe  ( address ))) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState000L LocalFields000I . \nOpaque LocalState000LRecord . \nInductive LocalFields001I := | \u03b90010 | \u03b90011 .\nDefinition LocalState001L := [( XHMap (string*nat) ( address)) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState001L LocalFields001I . \nOpaque LocalState001LRecord . \nInductive LocalFields010I := | \u03b90100 | \u03b90101 .\nDefinition LocalState010L := [( XHMap (string*nat) ( XUInteger32)) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState010L LocalFields010I . \nOpaque LocalState010LRecord . \nInductive LocalFields011I := | \u03b90110 | \u03b90111 .\nDefinition LocalState011L := [( XHMap (string*nat) ( cell_)) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState011L LocalFields011I . \nOpaque LocalState011LRecord . \nInductive LocalFields100I := | \u03b91000 | \u03b91001 .\nDefinition LocalState100L := [( XHMap (string*nat) ( builder_)) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState100L LocalFields100I . \nOpaque LocalState100LRecord . \nInductive LocalFields101I := | \u03b91010 | \u03b91011 .\nDefinition LocalState101L := [( XHMap (string*nat) ( XUInteger256)) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState101L LocalFields101I . \nOpaque LocalState101LRecord . \nInductive LocalFields110I := | \u03b91100 | \u03b91101 .\nDefinition LocalState110L := [( XHMap (string*nat) ( XHMap  ( XUInteger256 )( XBool ))) : Type; ( XHMap string nat ) : Type ] .\nGlobalGeneratePruvendoRecord LocalState110L LocalFields110I . \nOpaque LocalState110LRecord . \n(**************** LocalState Tree ***************.\n  /\\\n /\\/\\\n/\\/\\/\\\\\n**************** LocalState Tree ***************)\n\nInductive LocalFields00I := | \u03b9000 | \u03b9001 . \nDefinition LocalState00L := [ LocalState000LRecord ; LocalState001LRecord ] . \nGlobalGeneratePruvendoRecord LocalState00L LocalFields00I . \nOpaque LocalState00LRecord . \n\nInductive LocalFields01I := | \u03b9010 | \u03b9011 . \nDefinition LocalState01L := [ LocalState010LRecord ; LocalState011LRecord ] . \nGlobalGeneratePruvendoRecord LocalState01L LocalFields01I . \nOpaque LocalState01LRecord . \n\nInductive LocalFields10I := | \u03b9100 | \u03b9101 . \nDefinition LocalState10L := [ LocalState100LRecord ; LocalState101LRecord ] . \nGlobalGeneratePruvendoRecord LocalState10L LocalFields10I . \nOpaque LocalState10LRecord . \n\nInductive LocalFields0I := | \u03b900 | \u03b901 . \nDefinition LocalState0L := [ LocalState00LRecord ; LocalState01LRecord ] . \nGlobalGeneratePruvendoRecord LocalState0L LocalFields0I . \nOpaque LocalState0LRecord . \n\nInductive LocalFields1I := | \u03b910 | \u03b911 . \nDefinition LocalState1L := [ LocalState10LRecord ; LocalState110LRecord ] . \nGlobalGeneratePruvendoRecord LocalState1L LocalFields1I . \nOpaque LocalState1LRecord . \n\nInductive LocalFieldsI := | \u03b90 | \u03b91 . \nDefinition LocalStateL := [ LocalState0LRecord ; LocalState1LRecord ] . \nGlobalGeneratePruvendoRecord LocalStateL LocalFieldsI .\nOpaque LocalStateLRecord . \n\n\nTransparent\n\nLocalState000LRecord\nLocalState001LRecord\nLocalState010LRecord\nLocalState011LRecord\nLocalState100LRecord\nLocalState101LRecord\nLocalState110LRecord\n\nLocalState00LRecord\nLocalState01LRecord\nLocalState10LRecord\nLocalState1LRecord\nLocalState0LRecord.\n\n\n\nTransparent LocalStateLRecord.\n\n\n\n(* #[global]Program Instance ledgerClass : LedgerClass XBool LedgerLRecord ContractLRecord \n                                LocalStateLRecord VMStateLRecord MessagesAndEventsLRecord \n                                GlobalParamsLRecord OutgoingMessageParamsLRecord .\nNext Obligation.\nrefine ( VMStateLEmbeddedType VMState_\u03b9_isCommitted ).\nDefined.\nNext Obligation.\nrefine ( MessagesAndEventsLEmbeddedType _GlobalParams ) .\nDefined.\nNext Obligation.\nrefine ( MessagesAndEventsLEmbeddedType _OutgoingMessageParams ).\nDefined.  \nFail Next Obligation. *)\n\n#[local]\nObligation Tactic := idtac.\n\nNotation LocalStateField := (LocalStateField XHMap LocalStateLRecord). \n\n        #[global, program] Instance LocalStateField000 : LocalStateField ( XMaybe  ( address )).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b900). \neapply TransEmbedded. eapply (_ \u03b9000).\n        eapply (LocalState000LEmbeddedType \u03b90001). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b900). \neapply TransEmbedded. eapply (_ \u03b9000).\n        eapply (LocalState000LEmbeddedType \u03b90000). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField000 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField001 : LocalStateField ( address).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b900). \neapply TransEmbedded. eapply (_ \u03b9001).\n        eapply (LocalState001LEmbeddedType \u03b90011). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b900). \neapply TransEmbedded. eapply (_ \u03b9001).\n        eapply (LocalState001LEmbeddedType \u03b90010). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField001 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField010 : LocalStateField ( XUInteger32).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b901). \neapply TransEmbedded. eapply (_ \u03b9010).\n        eapply (LocalState010LEmbeddedType \u03b90101). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b901). \neapply TransEmbedded. eapply (_ \u03b9010).\n        eapply (LocalState010LEmbeddedType \u03b90100). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField010 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField011 : LocalStateField ( cell_).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b901). \neapply TransEmbedded. eapply (_ \u03b9011).\n        eapply (LocalState011LEmbeddedType \u03b90111). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b90). \neapply TransEmbedded. eapply (_ \u03b901). \neapply TransEmbedded. eapply (_ \u03b9011).\n        eapply (LocalState011LEmbeddedType \u03b90110). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField011 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField100 : LocalStateField ( builder_).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b910). \neapply TransEmbedded. eapply (_ \u03b9100).\n        eapply (LocalState100LEmbeddedType \u03b91001). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b910). \neapply TransEmbedded. eapply (_ \u03b9100).\n        eapply (LocalState100LEmbeddedType \u03b91000). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField100 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField101 : LocalStateField ( XUInteger256).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b910). \neapply TransEmbedded. eapply (_ \u03b9101).\n        eapply (LocalState101LEmbeddedType \u03b91011). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b910). \neapply TransEmbedded. eapply (_ \u03b9101).\n        eapply (LocalState101LEmbeddedType \u03b91010). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField101 : typeclass_instances. \n        \n\n        #[global, program] Instance LocalStateField110 : LocalStateField ( XHMap  ( XUInteger256 )( XBool )).\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b911). \n\n        eapply (LocalState110LEmbeddedType \u03b91101). \n        Defined.\n        Next Obligation. \n        \neapply TransEmbedded. eapply (_ \u03b91). \neapply TransEmbedded. eapply (_ \u03b911). \n\n        eapply (LocalState110LEmbeddedType \u03b91100). \n        Defined.\n        Fail Next Obligation.\n        #[local]\n        Remove Hints LocalStateField110 : typeclass_instances. \n        ", "meta": {"author": "Pruvendo", "repo": "vesting-pool", "sha": "7ca9c43c0778888dc316d3da027bfd67213e7d46", "save_path": "github-repos/coq/Pruvendo-vesting-pool", "path": "github-repos/coq/Pruvendo-vesting-pool/vesting-pool-7ca9c43c0778888dc316d3da027bfd67213e7d46/src/VestingPool/LocalState/VestingService.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29746994883293104, "lm_q1q2_score": 0.15570182441620323}}
{"text": "\n(** Erasure Safety *)\n\n(** Derive safety from the simulations.\n    Erasure proven in [erasure_proof.v] and [erasure_signature.v]\n    is stated as a simulation. Here we prove that the simulation\n    implies safety.\n *)\n\n(** *Imports*)\n\n(* This file uses Proof Irrelevance: \n   forall (P : Prop) (p1 p2 : P), p1 = p2. *)\nRequire Import ProofIrrelevance.\n\n(* CompCert imports*)\nRequire Import compcert.common.Memory.\n\n(* VST imports *)\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.juicy_mem.\nRequire Import VST.veric.res_predicates.\n\n(* Concurrency Imports *)\nRequire Import VST.concurrency.common.HybridMachineSig.\nRequire Import VST.concurrency.juicy.juicy_machine. Import Concur.\nRequire Import VST.concurrency.common.HybridMachine.\nRequire Import VST.concurrency.common.lksize.\nRequire Import VST.concurrency.common.permissions.\n(*Erasure simulation*)\nRequire Import VST.concurrency.juicy.erasure_signature.\nRequire Import VST.concurrency.juicy.erasure_proof.\nRequire Import VST.concurrency.juicy.Clight_safety.\nImport addressFiniteMap.\n\n(*SSReflect*)\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat eqtype seq.\nRequire Import Coq.ZArith.ZArith.\nRequire Import PreOmega.\nRequire Import VST.concurrency.common.ssromega. (*omega in ssrnat *)\nFrom mathcomp.ssreflect Require Import ssreflect seq.\n\n(*The simulations*)\n(* Require Import VST.concurrency.common.machine_simulation.*)\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nModule ErasureSafety.\n\n  Module ErasureProof := erasure_proof.Parching.\n  Module Erasure := ErasureFnctr ErasureProof.\n  Import ErasureProof.\n  Import Erasure.\n\n  Section ErasureSafety.\n\n  Context (initU: HybridMachineSig.schedule).\n  Context (init_rmap : @res JR).\n  Context (init_pmap : @res DR).\n  Context (init_rmap_perm:  match_rmap_perm init_rmap init_pmap).\n\n  (*Definition local_erasure:= erasure initU init_rmap init_pmap init_rmap_perm.*)\n  Definition step_diagram:= ErasureProof.core_diagram.\n\n  Import JuicyMachineModule.THE_JUICY_MACHINE.\n  Import ClightMachine.Clight_newMachine.DMS.\n\n  Existing Instance DMS.\n\n  Lemma erasure_safety': forall n ge sch js jtr ds dtr m,\n      ErasureProof.match_st ge js ds ->\n      DryHybridMachine.invariant ds ->\n    jm_csafe (sch, jtr, js) m n ->\n    HybridMachineSig.HybridCoarseMachine.csafe (sch, dtr, ds) m n.\n  Proof.\n    induction n.\n    intros. constructor.\n    intros. inversion H1.\n    - constructor; simpl. unfold HybridMachineSig.halted_machine; simpl.\n      unfold JuicyMachine.halted_machine in H2; simpl in H2.\n      change JuicyMachine.schedPeek with\n      HybridMachineSig.schedPeek in H2.\n      destruct ( HybridMachineSig.schedPeek sch ) eqn:AA;\n      inversion H; auto.\n    - { simpl in Hstep.\n        unfold JuicyMachine.MachStep in Hstep; simpl in Hstep.\n        assert (step_diagram:=step_diagram).\n        specialize (step_diagram ge m initU sch sch (Some init_rmap) (Some init_pmap)).\n        specialize (step_diagram ds dtr js tp' jtr tr' m').\n        unfold corestep in step_diagram; simpl in step_diagram.\n        unfold JuicyMachine.MachStep in step_diagram; simpl in step_diagram.\n        eapply step_diagram in Hstep; try eassumption.\n        destruct Hstep as [ds' [dinv' [MATCH' [dtr' stp']]]].\n        destruct Hsafe as [[? [Hphi Hext]] Hsafe].\n        specialize (Hsafe _ Hphi [:: Some (ghost_PCM.ext_ref tt, NoneP)])\n          as (? & ? & ? & ? & Hr & ? & Hsafe); auto.\n        { apply join_sub_refl. }\n        eapply MTCH_tp_update in MATCH'; eauto.\n        eapply IHn in Hsafe; eauto.\n        econstructor 3; eauto.\n        apply stp'. }\n    - { simpl in Hstep.\n        unfold JuicyMachine.MachStep in Hstep; simpl in Hstep.\n        assert (step_diagram:=step_diagram).\n        specialize (step_diagram ge m initU sch (HybridMachineSig.schedSkip sch) (Some init_rmap) (Some init_pmap)).\n        specialize (step_diagram ds dtr js tp' jtr tr' m').\n        unfold corestep in step_diagram; simpl in step_diagram.\n        unfold JuicyMachine.MachStep in step_diagram; simpl in step_diagram.\n        eapply step_diagram in Hstep; try eassumption.\n        destruct Hstep as [ds' [dinv' [MATCH' [dtr' stp']]]].\n        econstructor 4; eauto.\n        { apply stp'. }\n        intro U''; specialize (Hsafe U'').\n        destruct Hsafe as [[? [Hphi Hext]] Hsafe].\n        specialize (Hsafe _ Hphi [:: Some (ghost_PCM.ext_ref tt, NoneP)])\n          as (? & ? & ? & ? & Hr & ? & Hsafe); auto.\n        { apply join_sub_refl. }\n        eapply MTCH_tp_update in MATCH'; eauto. }\nQed.\n\n\n  Theorem erasure_safety: forall ge cd j js ds m n,\n      Erasure.match_state ge cd j js m ds m ->\n      jm_csafe js m n ->\n      HybridMachineSig.HybridCoarseMachine.csafe ds m n.\n  Proof.\n    intros ? ? ? ? ? ? ? MATCH jsafe.\n    inversion MATCH. subst.\n    eapply erasure_safety'; eauto.\n  Qed.\n\n  (*there is something weird about this theorem.*)\n  (*The injection is trivial... but it shouldn't*)\n(*  Theorem initial_safety:\n    forall genv (U : HybridMachineSig.schedule) (js : jstate genv)\n      (vals : seq Values.val) m\n      (rmap0 : rmap) (pmap : access_map * access_map) main h,\n      match_rmap_perm rmap0 pmap ->\n      no_locks_perm rmap0 ->\n      initial_core (JMachineSem U (Some rmap0)) h\n         m (U, [::], js) main vals  ->\n      exists (ds : dstate genv),\n        initial_core (ClightMachineSem U (Some pmap)) h\n                     m (U, [::], ds) main vals /\\\n        invariant ds /\\ match_st genv js ds.\n  Proof.\n    intros ? ? ? ? ? ? ? ? ? mtch_perms no_locks init.\n    destruct (init_diagram genv (fun _ => None) U js vals m rmap0 pmap main h)\n    as [ds [dinit [dinv MTCH]]]; eauto.\n    unfold init_inj_ok; intros b b' ofs H. inversion H.\n  Qed.*)\n\n  End ErasureSafety.\n\nEnd ErasureSafety.\n\nRequire Import VST.concurrency.juicy.semax_to_juicy_machine.\n\nLemma no_locks_no_locks_perm : forall r, Parching.no_locks_perm r <-> initial_world.no_locks r.\nProof.\n  unfold Parching.no_locks_perm, initial_world.no_locks, perm_of_res_lock; split; intros.\n  - destruct addr as (b, ofs); specialize (H b ofs).\n    destruct (r @ (b, ofs)); try discriminate.\n    destruct (perm_of_sh (Share.glb Share.Rsh sh0)) eqn: Hsh.\n    destruct k; discriminate.\n    { contradiction r0.\n      apply perm_of_empty_inv in Hsh as ->; auto. }\n  - specialize (H (b, ofs)).\n    destruct (r @ (b, ofs)); auto.\n    specialize (H sh r0).\n    destruct k; auto. specialize (H n i p).  contradiction; auto.\nQed.\n\n(* unused *)\nLemma juice2Perm_match : forall m r, access_cohere' m r ->\n  Parching.match_rmap_perm r (juice2Perm r m, empty_map).\nProof.\n  split; auto; simpl.\n  intros; apply juic2Perm_correct; auto.\nQed.\n\nSection DrySafety.\n(* combining results from semax_to_juicy_machine and erasure_proof *)\n\n  Variable (CPROOF : CSL_proof).\n\n  Instance Sem : Semantics := ClightSemanticsForMachines.Clight_newSem (Clight.globalenv CPROOF.(CSL_prog)).\n  Definition ge := Clight.globalenv CPROOF.(CSL_prog).\n  Instance DTP : threadPool.ThreadPool.ThreadPool := Parching.DTP ge.\n  Instance DMS : HybridMachineSig.MachineSig := Parching.DMS ge.\n  Definition init_mem := proj1_sig (init_mem CPROOF).\n  Definition init_rmap n := m_phi (initial_jm CPROOF n).\n\n  Lemma init_match n : Parching.match_rmap_perm (init_rmap n) (getCurPerm init_mem, empty_map).\n  Proof.\n    split; auto; simpl.\n    unfold init_rmap, initial_jm, spr.\n    destruct (semax_prog.semax_prog_rule' _ _ _ _ _ _ _ _) as (? & ? & ? & s); simpl.\n    destruct (s n tt) as (jm & ? & ? & ? & ? & ? & ?); simpl.\n    destruct jm; simpl in *; subst; intros.\n    rewrite <- (JMaccess (b, ofs)).\n    unfold access_at, PMap.get; simpl.\n    rewrite PTree.gmap1.\n    fold init_mem; destruct ((snd (Mem.mem_access init_mem)) ! b); auto.\n  Qed.\n\n  Lemma init_no_locks n : Parching.no_locks_perm (init_rmap n).\n  Proof.\n    apply no_locks_no_locks_perm.\n    unfold init_rmap, initial_jm, spr.\n    destruct (semax_prog.semax_prog_rule' _ _ _ _ _ _ _ _) as (? & ? & ? & s); simpl.\n    destruct (s n tt) as (jm & ? & ? & ? & ? & ? & ?); auto.\n  Qed.\n\n\n  (**  Theorem to export.\n       Explanation: \n       \n   *)\n  Theorem dry_safety_initial_state (sch : HybridMachineSig.schedule) (n : nat) :\n    HybridMachineSig.HybridCoarseMachine.csafe\n      (sch, [::],\n      DryHybridMachine.initial_machine(Sem := Sem) (getCurPerm init_mem)\n        (initial_corestate CPROOF)) init_mem n.\n  Proof.\n    eapply (ErasureSafety.erasure_safety sch (init_rmap n)\n      (juice2Perm (init_rmap n) init_mem, empty_map)) with (cd := tt)(j := fun _ => None),\n      (* Note that any injection will work here. *)\n      safety_initial_state.\n    constructor.\n    { apply dry_machine_lemmas.ThreadPoolWF.initial_invariant0. }\n    apply Parching.MTCH_initial with (pmap := (getCurPerm init_mem, empty_map)).\n    - apply init_match.\n    - apply init_no_locks.\n  Qed.\n\n  Context {SW : spawn_wrapper CPROOF}.\n\n  Notation ClightSem:= ClightSemanticsForMachines.ClightSem.\n  Theorem Clight_initial_safe (sch : HybridMachineSig.schedule) (n : nat) :\n    HybridMachineSig.HybridCoarseMachine.csafe\n      (Sem := ClightSem ge)\n      (ThreadPool:= threadPool.OrdinalPool.OrdinalThreadPool(Sem:=ClightSem ge))\n      (machineSig:= HybridMachine.DryHybridMachine.DryHybridMachineSig)\n      (sch, nil,\n       DryHybridMachine.initial_machine(Sem := ClightSem ge)\n                                       (permissions.getCurPerm init_mem)\n                                       (initial_Clight_state CPROOF)) init_mem n.\n  Proof.\n    apply Clight_new_Clight_safety; auto.\n    apply dry_safety_initial_state.\n  Qed.\n\n  (*Print Assumptions Clight_initial_safe.*)\nEnd DrySafety.\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/juicy/erasure_safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1557018102134815}}
{"text": "From iris Require Import invariants.\nFrom iris.algebra Require Import gmap frac agree frac_auth.\nFrom iris.base_logic Require Export gen_heap fancy_updates.\nFrom iris.base_logic.lib Require Export own saved_prop viewshifts.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import coq_tactics.\nFrom iris.proofmode Require Export tactics.\nFrom iris.program_logic Require Import ectx_lifting total_ectx_lifting.\nFrom stdpp Require Import base numbers.\nFrom distris Require Import tactics proofmode notation adequacy network.\nFrom distris.examples.replicated_log Require Import rep_log.\nFrom distris.examples.library Require Import proof frac_auth.\nFrom distris.examples.two_phase_commit Require Import tpc_proof.\n\nImport Network.\nImport tpc.\n\nClass repLogG \u03a3 := RepLogG {\n                       repLog_inG :> gen_heapG socket_address string \u03a3;\n                       repWait_inG :> gen_heapG socket_address (string * string) \u03a3;\n                     }.\n\nClass repLogPreG \u03a3 := RepLogPreG {\n  repPreLog_inG :> gen_heapPreG socket_address string \u03a3;\n  repPreWait_inG :> gen_heapPreG socket_address (string * string) \u03a3;\n                   }.\n\nDefinition repLog\u03a3 : gFunctors :=\n  #[gen_heap\u03a3 socket_address string;\n    gen_heap\u03a3 socket_address (string * string)].\n\nInstance subG_inG_repLog\u03a3 {\u03a3} :\n  subG repLog\u03a3 \u03a3 \u2192 repLogPreG \u03a3.\nProof. constructor; solve_inG. Qed.\n\nSection rep_log.\n  Context `{tG : tpcG \u03a3}\n          `{rlG : repLogG \u03a3}\n          `{dG : distG \u03a3}\n          `{N : namespace}.\n\n  Definition gen_heap_ctxDB \u03c3 := gen_heap_ctx (L:=socket_address) (V:=string) \u03c3.\n  Definition gen_heap_ctxW \u03c3 :=\n    gen_heap_ctx (L:=socket_address) (V:=string * string) \u03c3.\n\n  Notation \"p \u21a6L{ q } l\" := (mapsto (L:=socket_address)\n                                    (V:=string) p q l) (at level 20) : uPred_scope.\n  Notation \"p \u21a6L l\" := (mapsto (L:=socket_address)\n                               (V:=string) p 1 l) (at level 20) : uPred_scope.\n  Notation \"p \u21a6W{ q } m\" := (mapsto (L:=socket_address)\n                                    (V:=string * string) p q m)\n                              (at level 20) : uPred_scope.\n  Notation \"p \u21a6W m\" := (mapsto (L:=socket_address)\n                               (V:=string * string) p 1 m)\n                         (at level 20) : uPred_scope.\n\n  Lemma wait_update_all \u03c3 l v v' :\n    gen_heap_ctxW \u03c3 -\u2217 ([\u2217 list] p \u2208 l, p \u21a6W v) -\u2217\n    |==> \u2203 \u03c3', gen_heap_ctxW \u03c3' \u2217 [\u2217 list] p \u2208 l, (p \u21a6W v').\n  Proof.\n    iIntros \"Hctx Hlist\".\n    iInduction l as [|y l] \"IH\".\n    - simpl. iExists \u03c3. eauto. \n    - iDestruct \"Hlist\" as \"[H Hl]\".\n      iDestruct (\"IH\" with \"Hctx Hl\") as \">Hup\".\n      iDestruct \"Hup\" as (\u03c3') \"(Hctx & Hl)\".\n      iDestruct (gen_heap_valid (L:=socket_address) \u03c3'\n                   with \"Hctx H\") as %Hlookup.\n      iDestruct (gen_heap_update (L:=socket_address) \u03c3' y _ v' with \"Hctx H\")\n        as \">[Hctx H]\".\n      iDestruct (gen_heap_valid (L:=socket_address) (<[y:=v']> \u03c3')\n                   with \"Hctx H\") as %Hlookup'.\n      iFrame. iExists (<[y:=v']> \u03c3'). iFrame. eauto. \n  Qed.\n  \n  Definition request_msg := \"REQUEST\".\n  Definition commit_msg := \"COMMIT\".\n  Definition abort_msg := \"ABORT\".\n\n  (* Global functions for TPC to get the type of message *)\n  Definition is_req_log := \u03bb m (n : nat), \u2203 v, m = request_msg +:+ \"_\" +:+ v.\n  (* Definition is_commit_log := \u03bb m (n : nat), m = commit_msg. *)\n  Definition is_abort_log := \u03bb m (n : nat), m = abort_msg.\n  Definition is_vote_log := \u03bb m (n : nat), m = abort_msg \u2228 m = commit_msg.\n  Definition is_global_log :=  \u03bb m (n : nat), m = abort_msg \u2228 m = commit_msg.\n\n  Definition tpc_inv_cs_n : namespace := N .@ \"replog\" .@ \"tpc_cs\".\n  Definition tpc_inv_ps_n : namespace := N .@ \"replog\" .@ \"tpc_ps\".\n\n  Lemma is_abort_log_dec m r : Decision (is_abort_log m r).\n  Proof. rewrite /is_abort_log. solve_decision. Qed.\n  \n  Global Instance rep_log_tpc : TpcProt \u03a3 := {|\n                       is_req := is_req_log;\n                       is_vote := is_vote_log;\n                       is_abort := is_abort_log;\n                       is_abort_dec := is_abort_log_dec;\n                       is_global := is_global_log;\n                       P := (\u03bb m p, \u2203 log s, \u231cm = request_msg +:+ \"_\" +:+ s\u231d \u2217\n                                             p \u21a6L{\u00bd} log \u2217 p \u21a6W{\u00bd} (log, s))%I;\n                       Q := (\u03bb p n, \u2203 log m,\n                                p \u21a6L{\u00bd} (log +:+ m) \u2217 p \u21a6W{\u00bd} (log, m) )%I;\n                       tpc_inv_cs_name := tpc_inv_cs_n;\n                       tpc_inv_ps_name := tpc_inv_ps_n;\n                                     |}.\n\n  Definition R_pa n llog lwait :=\n    (\u03bb p, \u2203 (log : string) w', llog \u21a6[n] #log \u2217 p\u21a6L{\u00bd} log \u2217 lwait \u21a6[n] w')%I.\n\n  Definition R'_pa n llog lwait :=\n    (\u03bb p, \u2203 (log : string) (m : string), llog \u21a6[n] #log \u2217 p\u21a6L log \u2217\n                                       lwait \u21a6[n] #m \u2217 p \u21a6W{\u00bd} (log, m))%I.\n\n  Definition rep_log_tpc_pa n llog lwait : TpcPartProt \u03a3 :=\n    {|\n      R := R_pa n llog lwait;\n      R' := R'_pa n llog lwait;\n    |}.\n\n  Definition rep_log_inv_n := N .@ \"replog\".\n  Definition rep_log_inv := (\u2203 \u03c3 \u03c3', gen_heap_ctxDB \u03c3 \u2217 gen_heap_ctxW \u03c3')%I.\n  Definition rep_log_I := inv rep_log_inv_n rep_log_inv.\n\n  Definition log_si : socket_interp \u03a3 :=\n    (\u03bb msg, \u2203 s \u03c6,\n        \u231cms_body msg = s\u231d \u2217 ms_sender msg \u2907 \u03c6 \u2217\n        (\u2200 m, (\u231cms_body m = commit_msg\u231d \u2228 \u231cms_body m = abort_msg\u231d) -\u2217 \u03c6 m))%I.\n\n  Lemma fin_handler_log_spec n p e1 e2 (lwait llog : loc)\n        (Tpa:=rep_log_tpc_pa n llog lwait) :\n    IntoVal \u27e8n;e1\u27e9 \u2329n;#lwait\u232a \u2192\n    IntoVal \u27e8n;e2\u27e9 \u2329n;#llog\u232a \u2192\n    {{{ rep_log_I }}}\n      \u27e8n;fin_handler_log e1 e2\u27e9\n    {{{ v, RET \u2329n;v\u232a; fin_handler_spec n v p }}}.\n  Proof.\n    iIntros (<-%to_base_val'%ground_lang.of_to_val\n            <-%to_base_val'%ground_lang.of_to_val).\n    iIntros (\u03a6) \"#Hinv H\u03a6\". wp_lam. wp_lam. iApply \"H\u03a6\".\n    iIntros (c m e1 e2 r s0\n               <-%to_base_val'%ground_lang.of_to_val\n               <-%to_base_val'%ground_lang.of_to_val \u03a6'). iAlways.\n    iIntros \"(#HpsI & H) H\u03a6\". iDestruct \"H\" as (Hisglobal Hdec) \"[Hps HR]\".\n    do 2 wp_let. wp_op. case_bool_decide. inversion H as [Hmsg].\n    rewrite /R' /= /R'_pa /R_pa /is_abort_log /abort_msg Hmsg.\n    + wp_if.\n      iDestruct \"HR\" as (log x) \"(Hl & HL & Hw & HW)\".\n      wp_load. wp_load. wp_op.\n      iApply fupd_wp.\n      iInv tpc_inv_ps_n as (\u03c3) \">H\" \"Hclose\".\n      iDestruct (gen_heap_update \u03c3 _ _ (r, PS_INIT PS_COMMIT)\n                 with \"H Hps\") as \">[H Hps]\".\n      iMod (\"Hclose\" with \"[H]\") as \"_\". iExists _; iFrame.\n      iInv rep_log_inv_n as (\u03c3' ?) \">[HLctx HWctx]\" \"Hclose\".\n      iDestruct (gen_heap_update \u03c3' _ _ (log +:+ x)\n                 with \"HLctx HL\") as \">[HLctx [HL HL']]\".\n      iMod (\"Hclose\" with \"[HLctx HWctx]\") as \"_\". iExists _,_. iFrame.\n      iModIntro.\n      wp_store. iApply \"H\u03a6\". iExists PS_COMMIT, (m_body m). iFrame.\n      iSplitR \"HW HL\". iExists _,#x; iFrame. iRight. iSplitR. eauto.\n      iExists _,_. iFrame.\n    + assert (Hisabort: m_body m = \"ABORT\").\n      { destruct Hisglobal as [Habort | Hcommit]; eauto.\n        destruct H. rewrite Hcommit. eauto. }\n      iApply fupd_wp.\n      iInv tpc_inv_ps_n as (\u03c3) \">H\" \"Hclose\".\n      iDestruct (gen_heap_update \u03c3 _ _ (r, PS_INIT PS_ABORT)\n                 with \"H Hps\") as \">[H Hps]\".\n      iMod (\"Hclose\" with \"[H]\") as \"_\". iExists _. iFrame. iModIntro.\n      iDestruct \"HR\" as (log x) \"(Hl & [HP HP'] & Hw & HW)\".\n      wp_if. iApply \"H\u03a6\". iExists PS_ABORT,(\"REQUEST\" +:+ \"_\" +:+ x). iFrame.\n      iSplitR \"HW HP\". iExists log,#x. iFrame. iLeft. iSplitR; auto.\n      iExists _,_. iFrame; eauto.\n  Qed.\n\n  Lemma req_handler_log_spec n s e (llog lwait : loc)\n        (Tpa:=rep_log_tpc_pa n llog lwait) :\n    IntoVal \u27e8n;e\u27e9 \u2329n;#lwait\u232a \u2192\n    ({{{ True }}}\n      \u27e8n;req_handler_log e\u27e9\n    {{{ v, RET \u2329n;v\u232a; req_handler_spec n v s }}})%I.\n  Proof.\n    iIntros (<-%to_base_val'%ground_lang.of_to_val \u03a6). iAlways.\n    iIntros \"H H\u03a6\". wp_lam. iApply \"H\u03a6\".\n    rewrite /req_handler_spec.\n    iIntros (c m e1 e2 r s0\n               <-%to_base_val'%ground_lang.of_to_val\n               <-%to_base_val'%ground_lang.of_to_val \u03a6'). iAlways.\n    iIntros \"(#HpsI & Hisreq & Hps & HP & HR) H\u03a6'\". rewrite /= /R_pa.\n    iDestruct \"HR\" as (log w') \"(Hl & Hlog & Hlw)\".\n    iDestruct \"Hisreq\" as %[s' Hisreq]. wp_lam. wp_lam. rewrite Hisreq.\n    wp_apply value_of_message_spec; eauto.\n    { rewrite /request_msg /valid_tag. eauto. } iIntros (? Heq). simpl.\n    iApply fupd_wp.\n    iInv tpc_inv_ps_n as (\u03c3) \">H\" \"Hclose\".\n    iDestruct (gen_heap_update \u03c3 _ _ (S r, PS_READY) with \"H Hps\") as \">[H Hps]\".\n    iMod (\"Hclose\" with \"[H]\") as \"_\". iExists _. iFrame. iModIntro.\n    wp_store.\n    iApply \"H\u03a6'\". iDestruct \"HP\" as (? v Hvm) \"[Hlog' Hwait]\".\n    inversion Hvm; simplify_eq.\n    iDestruct (mapsto_agree (L:=socket_address)\n                 (V:=string) with \"Hlog Hlog'\") as %->. iExists _.\n    rewrite /R'_pa /is_vote_log /commit_msg /is_abort_log /abort_msg. iFrame.\n    iSplitR; eauto. iSplitL. iExists _,_. iFrame. iFrame. eauto.\n  Qed.\n\n  Lemma db_spec (n : node) A e (a : socket_address) p l r pst \u03b3s :\n    IntoVal \u27e8n;e\u27e9 \u2329n;#a\u232a \u2192\n    a \u2208 l ->\n    a \u2208 A \u2192\n    port_of_address a = p ->\n    {{{ rep_log_I \u2217 tpc_inv_ps_I \u2217 f\u21a6 A \u2217 a \u2907 tpc_participant_si a \u2217 ownA l \u2217\n        FreePorts (ip_of_address a) {[p]} \u2217 n n\u21a6 \u03b3s \u2217 a \u21a6L{\u00bd} \"\" \u2217\n        a \u21a6p{\u00bc} (r, PS_INIT pst) }}}\n      \u27e8n;db e\u27e9\n    {{{ r, RET r; \u231cTrue\u231d }}}.\n  Proof.\n    iIntros (<-%to_base_val'%ground_lang.of_to_val HinL HinA Hport \u03a6) \"H H\u03a6\".\n    iDestruct \"H\" as \"(#Hinv & #HtpcInv & #Hfixed & #Hsi & #HownL & H)\".\n    iDestruct \"H\" as \"(Hip & Hn & HP & Hpst)\".\n    wp_lam. wp_socket h as \"Hs\". wp_let.\n    wp_alloc lwait as \"Hwaiting\". wp_let.\n    wp_alloc llog as \"Hlog\". wp_let.\n    set (tpa := rep_log_tpc_pa n llog lwait).\n    wp_apply (req_handler_log_spec n _ _ llog lwait); eauto.\n    iIntros (vreq) \"#Hreq\". wp_let.\n    wp_apply (fin_handler_log_spec n _ _ _ lwait llog); eauto.\n    iIntros (vfin) \"#Hfin\". wp_let.\n    wp_apply (wp_bind_socket_fix_suc\n                with \"[$Hfixed Hip $Hs]\"); simpl; try done. by rewrite Hport.\n    iDestruct 1 as (g) \"(Hs & _ & Hrecs & #Hsi')\". wp_seq.\n    (* Putting auto after times out *)\n    wp_apply (tpc_participant_spec _ _ _ _ h _ a _ _ _ l with \"[Hsi] [] [-H\u03a6]\");\n      last first; try iFrame; auto.\n    iFrame \"#\". rewrite /R /= /R_pa. iExists _,_. iFrame.\n  Qed.\n  \n  Definition dec_handler_fold_acc r : list message -> ground_lang.val -> iProp \u03a3 :=\n    (\u03bb (l : list message) (v : ground_lang.val),\n     \u2203 ga, \u231cga = filter (\u03bb m, is_abort_m (m,r)) l\u231d \u2217\n           \u231cv = #true \u2227 ga = [] \u2228 v = #false \u2227 ga \u2260 []\u231d)%I.\n\n  Lemma list_filter_nil {A} P `{\u2200 x, Decision (P x)} :\n    filter (A:=A) P [] = [].\n  Proof. by rewrite /filter /list_filter. Qed.\n\n  Lemma list_filter_cons {A} P `{\u2200 x, Decision (P x)} (a : A) (l : list A) :\n    filter P (a::l) = filter P [a] ++ filter P l.\n  Proof.\n    destruct l.\n    - by rewrite list_filter_nil app_nil_r. \n    - rewrite {1}/filter {1}/filter /list_filter /=.\n      case_decide; by rewrite list_filter_nil /=.\n  Qed.\n\n  Lemma list_filter_app {A} P `{\u2200 x, Decision (P x)} (l1 l2 : list A) :\n    filter P (l1 ++ l2) = filter P l1 ++ filter P l2.\n  Proof.\n    induction l1.\n    - by simpl.\n    - rewrite -app_comm_cons\n                 (list_filter_cons P a l1)\n                 list_filter_cons\n                 list_filter_cons list_filter_nil app_nil_r /=.\n      rewrite -app_assoc. by rewrite IHl1.\n  Qed.\n  \n  Lemma dec_handler_log_spec n s : dec_handler_spec n dec_handler_log s.\n  Proof.\n    iIntros (v l l' r \u03b3s \u03a6) \"!# H H\u03a6\".\n    iDestruct \"H\" as (Hcoh) \"(#Hinv & #Hparts & Hn & Hst & Hvotes & Hpst)\".\n    wp_lam.\n    wp_apply (list_fold_spec n _  l #true v #true v\n                             (dec_handler_fold_acc r)\n                             (\u03bb m, (\u2203 (mId : message_id) (\u03c0 : Qp),\n                              \u231cis_vote (m_body m) r\u231d \u2217 mId m\u21a6{\u03c0} m))%I\n                             (\u03bb m, (\u2203 (mId : message_id) (\u03c0 : Qp),\n                              \u231cis_vote (m_body m) r\u231d \u2217 mId m\u21a6{\u03c0} m))%I\n                with \"[] [Hvotes]\"); last first.\n    - iIntros (resV) \"(Hacc & Hvotes)\".\n      iDestruct \"Hacc\" as (ga) \"H\";\n        iDestruct \"H\" as %[Hga [[HresV Hgar] | [HresV Hgar]]];\n        wp_let; iApply fupd_wp; rewrite HresV.\n      +  iDestruct (coordinator_state_update_all _ _ (r, CS_COMMIT)\n                      with \"Hinv Hparts Hst Hpst\") as \">(Hc & Hpcs)\". iModIntro.\n         wp_if. iApply (\"H\u03a6\" $! _ ga CS_COMMIT); eauto. iFrame.\n         rewrite /is_abort_m /is_abort /= in Hga.\n         rewrite /is_global /= /is_global_log /abort_msg /commit_msg. \n         iSplitR. eauto. iSplitR;  eauto. \n      +  iDestruct (coordinator_state_update_all _ _ (r, CS_ABORT)\n                      with \"Hinv Hparts Hst Hpst\") as \">(Hc & Hpcs)\". iModIntro.\n         wp_if. iApply (\"H\u03a6\" $! _ ga CS_ABORT); eauto. iFrame.\n         rewrite /is_global /= /is_global_log /abort_msg /commit_msg.\n         iSplitR. eauto. iSplitR. eauto. eauto.\n    - iFrame. rewrite /list_m_val map_map in Hcoh. iPureIntro. split.\n      + rewrite /dec_handler_fold_acc. exact Hcoh.\n      + exists []. eauto.\n    - iIntros (m acc lacc lrem \u03a6') \"!# H H\u03a6'\".\n      iDestruct \"H\" as (Hl) \"[Hdec HP]\". wp_let. wp_let.\n      rewrite /dec_handler_fold_acc. iDestruct \"Hdec\" as (ga Hfold) \"Hacc\".\n      rewrite /is_vote /= /is_vote_log. iDestruct \"HP\" as (mId \u03c0 Hvote) \"H\".\n      iDestruct \"Hacc\" as %[[Hval Hga] | [Hval Hga]]; rewrite Hval; wp_if.\n      + wp_op. case_bool_decide; iApply \"H\u03a6'\".\n        * iSplitR; last eauto. iExists []. iSplitR; last eauto. iPureIntro.\n          rewrite list_filter_app -Hfold Hga app_nil_l.\n          rewrite /filter /list_filter list_filter_nil.\n          case_decide; last done.\n          rewrite /is_abort_log /abort_msg in H0.\n          inversion H. rewrite H2 in H0. inversion H0.\n        * assert (Habortmsg: (m_body m) = abort_msg).\n          { destruct Hvote as [Hab | Hcm]; eauto. destruct H.\n            rewrite Hcm /commit_msg. done. }\n          iSplitR; last eauto. iExists [m].\n          iSplitR; last eauto. iPureIntro.\n          rewrite list_filter_app -Hfold Hga app_nil_l.\n          rewrite /filter /list_filter list_filter_nil.\n          case_decide; first done. destruct H0.\n          by rewrite /is_abort_log.\n      + wp_op. case_bool_decide; first done.\n        iApply \"H\u03a6'\". iSplitR; last eauto.\n        iExists (ga ++ filter (\u03bb m, is_abort_log (m_body m) r) [m]).\n        iSplitR; last eauto. by rewrite list_filter_app Hfold. iPureIntro.\n        right; split; eauto. intro. destruct Hga.\n          by apply app_nil in H0 as [Hdone ?].\n  Qed.\n\n  Definition handlerR n tpca tpch tpcs dbs r : iProp \u03a3 :=\n    (\u2203 g ps log log2 s, tpca \u21a6c (r, CS_INIT) \u2217 tpch s\u21a6[n] tpcs \u2217 tpca r\u21a6{ \u00bd} g \u2217\n         ([\u2217 list] p \u2208 dbs, p \u21a6c (r, CS_INIT)) \u2217\n         ([\u2217 list] p \u2208 dbs, p \u21a6p{\u00be} (r, PS_INIT ps)) \u2217\n         ([\u2217 list] p\u2208dbs, p \u21a6L{\u00bd} log) \u2217\n         ([\u2217 list] p\u2208dbs, p \u21a6W (log2,s))\n    )%I.\n  \n  Lemma logger_spec n e1 e2 (ip : string) dbsV (dbs : list socket_address)\n    addr tpca A \u03b3s r ps :\n    IntoVal \u27e8n;e1\u27e9 \u2329n;#ip\u232a \u2192\n    IntoVal \u27e8n;e2\u27e9 \u2329n;dbsV\u232a \u2192\n    NoDup dbs ->\n    length dbs > 0 ->\n    addr = SocketAddressInet ip 80 ->\n    tpca = SocketAddressInet ip 1200 ->\n    list_coh (list_sa_val dbs) dbsV ->\n    addr \u2208 A ->\n    tpca \u2209 A ->\n    {{{ tpc_inv_cs_I tpca \u2217 rep_log_I \u2217 ownA dbs \u2217 addr \u2907 log_si \u2217 f\u21a6 A \u2217\n        ([\u2217 list] p\u2208dbs, p \u2907 tpc_participant_si p) \u2217\n        n n\u21a6 \u03b3s \u2217 tpca \u21a6c (r,CS_INIT) \u2217 FreePorts ip {[80%positive;1200%positive]} \u2217\n        ([\u2217 list] p\u2208dbs, p \u21a6c (r, CS_INIT)) \u2217\n        ([\u2217 list] p\u2208dbs, p \u21a6p{\u00be} (r,PS_INIT ps)) \u2217\n        ([\u2217 list] p\u2208dbs, p \u21a6L{\u00bd} \"\") \u2217\n        ([\u2217 list] p\u2208dbs, p \u21a6W (\"\",\"\"))\n    }}}\n      \u27e8n;logger e1 e2\u27e9\n    {{{v, RET \u2329n;v\u232a; True }}}.\n  Proof.\n    iIntros (<-%to_base_val'%ground_lang.of_to_val\n                <-%to_base_val'%ground_lang.of_to_val\n                Hnodubs Hlength Haddr Htpca Hcoh HainA HtnotinA).\n    iIntros (\u03a6) \"(#Hinv & #Hrepinv & #Hdbs & #Hlogsi & #Hfixed & #Hpsi & H) H\u03a6\".\n    iDestruct \"H\" as \"(Hn & Hc & Hip & Hcs & Hps & Hlogs & Hupdates)\".\n    wp_lam. wp_let. wp_socket z1 as \"Haddr\". wp_let.\n    wp_socket z2 as \"Htpc\". wp_let.\n    wp_makeaddress. wp_let. wp_makeaddress. wp_let. simplify_eq.\n    iDestruct (FreePorts_distribute with \"Hip\") as \"[Hip Hip']\". set_solver.\n    wp_apply (wp_bind_socket_fix_suc with \"[$Hfixed Hip $Haddr]\"); eauto.\n    iDestruct 1 as (g) \"(Haddr & ? & Harecs & _)\". wp_seq.\n    wp_apply (wp_bind_socket_dyn_suc _ _ _ _\n                                     _ _ _ _ tpc_coordinator_si\n                with \"[Hip' $Htpc]\"); eauto.\n    iDestruct 1 as (g') \"(Htpc & ? & Htrecs & #Htsi)\". wp_seq. wp_let.\n    iDestruct \"Hn\" as \"#Hn\".\n    wp_apply (listen_spec (handlerR n (SocketAddressInet ip 1200) z2 _ dbs r)\n                          (\u03bb v, \u231cTrue\u231d)%I\n                          _ _ _ (SocketAddressInet ip 80)\n                with \"[] [-H\u03a6]\"); last auto; last iFrame; auto.\n    iL\u00f6b as \"IH\" forall (g r).  \n    iIntros (mId m \u03c6 \u03a6') \"!# H H\u03a6'\".\n    iDestruct \"H\" as (Hrecmsg) \"(Hhandler & Hs & Hrec & HmId & #Hsi' & HP)\".\n    iDestruct (si_pred_agree _ _ _ (message_stable_from_message m)\n                 with \"Hlogsi Hsi'\") as \"#Heq\".\n    wp_rec. iRewrite -\"Heq\" in \"HP\". wp_let. wp_op. wp_op. wp_let.\n    iDestruct \"HP\" as (s \u03c6a Hmbody) \"(#Hasi & Hret)\".\n    (* iDestruct (big_sepL_sepL with \"Hlogs\") as \"[Hlogs Hupdates]\". *)\n    iDestruct \"Hhandler\" as\n        (? ? log log2 s') \"(Hc & Htpca & Htpcrec & Hdbcs & Hdbps & Hlogs & Hupdates)\".\n    iApply fupd_wp.\n    iInv rep_log_inv_n as (\u03c3' ?) \">[HLctx HWctx]\" \"Hclose\".\n    iDestruct (wait_update_all _ _ _ (log, s) with \"HWctx Hupdates\") as \">H\".\n    iDestruct \"H\" as (?) \"[HWctx Hupdates]\".\n    iMod (\"Hclose\" with \"[HLctx HWctx]\") as \"_\". iExists _,_. iFrame.\n    iAssert ([\u2217 list] p\u2208dbs, p \u21a6W{\u00bd} (log, s) \u2217 p \u21a6W{\u00bd} (log, s))%I\n      with \"[Hupdates Hrepinv]\" as \"Hupdates\".\n    { iApply (big_sepL_mono with \"Hupdates\").\n      iIntros (k y Hlookup) \"[H1 H2]\". iFrame. }\n    iDestruct (big_sepL_sepL with \"Hupdates\") as \"[Hupdates Hupdates']\".\n    iModIntro.\n    wp_apply (tpc_coordinator_setup_spec\n                n _ _ _ _ _ z2 _\n                {|\n                  sfamily := PF_INET;\n                  stype := SOCK_DGRAM;\n                  sprotocol := IPPROTO_UDP;\n                  saddress := Some (SocketAddressInet ip 1200) |}\n                (SocketAddressInet ip 1200) _ _ _ _ r\n                with \"[] [Hn Htpca Htpcrec Hc Hdbcs Hdbps Hlogs Hupdates]\");\n      eauto; last first.\n    - iIntros (v) \"H\".      \n      iDestruct \"H\" as (ps' cs rm' Hisglob)\n                         \"(Htpcs & Htpcrec & Hc & Hcs & Hps & Hres)\".\n      wp_let.\n      iDestruct \"Hres\" as \"[[Hres Hcommit] | [Hres Habort]]\";\n        iDestruct \"Hres\" as %Hres.\n      + iDestruct (big_sepL_sepL with \"[Hupdates' Hcommit]\") as \"Hcommit\"; iFrame.\n        iAssert ([\u2217 list] p \u2208 dbs, p \u21a6L{\u00bd} (log +:+ s) \u2217 p \u21a6W (log, s))%I\n          with \"[Hcommit]\" as \"Hcommit\".\n        { iApply (big_sepL_mono with \"Hcommit\").\n          iIntros (k y Hin) \"(Hlog & Hu)\".\n          iDestruct \"Hlog\" as (log0 m0) \"[Hlog Hu']\". \n          iDestruct (mapsto_agree (L:=socket_address) with \"Hu Hu'\") as %Hseq;\n          inversion Hseq; simplify_eq. iFrame.\n        }\n        iDestruct (big_sepL_sepL with \"Hcommit\") as \"[Hlogs Hwait]\"; iFrame.\n        wp_apply (wp_send_to_bound \u231cTrue\u231d%I \u231cTrue\u231d%I\n                    with \"[$Hs Hret]\"); eauto; iFrame; iFrame \"#\".\n        iSplitR; auto.\n        iIntros (M sent mId') \"(HM & HmId)\". iFrame. iSplitL; last done. \n        iApply \"Hret\". simpl. iModIntro. iNext. iPureIntro.\n        destruct Hisglob as [Hnotabort | Habort]; eauto.\n        iIntros \"(Hs & _)\". wp_seq.\n        iApply fupd_wp.\n        iMod (coordinator_state_update_all _ _ (S r, CS_INIT)\n                with \"Hinv Hdbs Hc Hcs\") as \"(Hc & Hcs)\".\n        iModIntro.\n        wp_apply (listen_spec (handlerR n (SocketAddressInet ip 1200) z2 _ dbs (S r))                          (\u03bb v, \u231cTrue\u231d)%I\n                          _ _ {|\n                            sfamily := PF_INET;\n                            stype := SOCK_DGRAM;\n                            sprotocol := IPPROTO_UDP;\n                            saddress := Some (SocketAddressInet ip 80) |}\n                          (SocketAddressInet ip 80)\n                    with \"[] [-H\u03a6']\"); eauto.\n        iApply \"IH\".\n        iFrame. iExists _,_,(log +:+ s),_,_. iFrame.\n      + iDestruct (big_sepL_sepL with \"[Hupdates' Habort]\") as \"Habort\"; iFrame.\n        iAssert ([\u2217 list] p \u2208 dbs, p \u21a6L{ \u00bd} log \u2217 p \u21a6W (log, s))%I\n          with \"[Habort]\" as \"Habort\".\n        { iApply (big_sepL_mono with \"Habort\").\n          iIntros (k y Hin) \"(Hlog & Hu)\".\n          iDestruct \"Hlog\" as (m' log0 m0) \"(% & Hlog & Hu')\"; simplify_eq.\n          iDestruct (mapsto_agree (L:=socket_address) with \"Hu Hu'\") as %Hseq.\n          inversion Hseq; simplify_eq. iFrame. }\n        iDestruct (big_sepL_sepL with \"Habort\") as \"[Habort Hupdates]\".\n        wp_apply (wp_send_to_bound \u231cTrue\u231d%I \u231cTrue\u231d%I\n                    with \"[$Hs Hret]\"); eauto; iFrame; iFrame \"#\".\n        iSplitR; auto.\n        iIntros (M sent mId') \"(HM & HmId)\". iFrame. iSplitL; last done.\n        iApply \"Hret\". simpl. iModIntro. iNext. iPureIntro.\n        destruct Hres as [Habort Hcs].\n        rewrite /is_abort_log in Habort. rewrite Habort. eauto.\n        iIntros \"(Hs & _)\". wp_seq.\n        iApply fupd_wp.\n        iMod (coordinator_state_update_all _ _ (S r, CS_INIT)\n                with \"Hinv Hdbs Hc Hcs\") as \"(Hc & Hcs)\".\n        iModIntro.\n        wp_apply (listen_spec (handlerR n (SocketAddressInet ip 1200) z2 _ dbs (S r))                          (\u03bb v, \u231cTrue\u231d)%I\n                          _ _ {|\n                            sfamily := PF_INET;\n                            stype := SOCK_DGRAM;\n                            sprotocol := IPPROTO_UDP;\n                            saddress := Some (SocketAddressInet ip 80) |}\n                          (SocketAddressInet ip 80)\n                    with \"[] [-H\u03a6']\"); eauto.\n        iApply \"IH\".\n        iFrame. iExists _,_,log,_,_. iFrame.\n    - iFrame; iFrame \"#\". eauto.\n      iSplitR. eauto. iSplitR. rewrite /is_req /= /is_req_log. eauto.\n      iDestruct (big_sepL_sepL with \"[$Hlogs $Hupdates]\") as \"Hall\".\n      iDestruct (big_sepL_mono _\n                               (\u03bb k p, \u2203 ps, p \u21a6p{\u00be} (r, PS_INIT ps))%I\n                   with \"[$Hdbps]\") as \"Hdbps\".\n      { iIntros (k y Hiny) \"H\". eauto. }\n      iFrame. iApply (big_sepL_mono with \"Hall\").\n      apply ms_body_message in Hmbody.\n      rewrite /tpc_proof.P /= /request_msg Hmbody.\n      iIntros. iExists _,_. iFrame. eauto.\n      (* eauto. *)\n    - iApply dec_handler_log_spec.\n    - iExists g',ps,\"\",\"\",\"\". iFrame. \n  Qed.\n\n  Definition client_si : socket_interp \u03a3 :=\n    (\u03bb msg, \u231cms_body msg = commit_msg\u231d \u2228 \u231cms_body msg = abort_msg\u231d)%I.\n  \n  Lemma client_spec n e1 e2 e3 (ip : string) (logaddr : socket_address)\n        (event : string) A \u03b3s:\n    IntoVal \u27e8n;e1\u27e9 \u2329n;#ip\u232a \u2192\n    IntoVal \u27e8n;e2\u27e9 \u2329n;#logaddr\u232a \u2192\n    IntoVal \u27e8n;e3\u27e9 \u2329n;#event\u232a \u2192\n    SocketAddressInet ip 80 \u2209 A ->\n    {{{ logaddr \u2907 log_si \u2217 f\u21a6 A \u2217\n        n n\u21a6 \u03b3s \u2217 FreePorts ip {[80%positive]} }}}\n      \u27e8n;client e1 e2 e3\u27e9\n      {{{v, RET \u2329n;#v\u232a; \u231cv = commit_msg \u2228 v = abort_msg\u231d }}}.\n  Proof.\n    iIntros (<-%to_base_val'%ground_lang.of_to_val\n                <-%to_base_val'%ground_lang.of_to_val\n                <-%to_base_val'%ground_lang.of_to_val\n                HnotinA \u03a6) \"(#Hlogsi & #Hfixed & Hn & Hports) H\u03a6\".\n    rewrite /client. \n    do 3 wp_lam. wp_socket h as \"Hs\". wp_let. wp_makeaddress. wp_let. \n    wp_apply (wp_bind_socket_dyn_suc _ _ A _\n                                     _ _ _ _ client_si\n                with \"[Hports $Hs]\"); eauto.\n    iDestruct 1 as (g') \"(Hs & ? & Hrecs & #Hsi)\". wp_seq.\n    wp_apply (wp_send_to_bound \u231cTrue\u231d%I \u231cTrue\u231d%I\n                with \"[$Hs]\"); eauto; iFrame \"#\".\n    iSplitR. done.\n    iIntros (M sent mId) \"(HM & HmId)\". iFrame. iSplitL; last done. simpl.\n    rewrite /log_si /=. iModIntro. iNext.\n    iExists event,client_si; eauto.\n    iIntros \"(Hs & _)\". wp_seq.\n    wp_apply (listen_wait_spec with \"[$Hs $Hrecs]\"); eauto.\n    iIntros (m mId) \"(HX & Hs & Hrecs & HmId & [% | %])\"; simpl;\n      wp_proj; iApply \"H\u03a6\"; eauto.\n  Qed.\n  \nEnd rep_log.\n\nSection rep_log_runner.\n  Context `{dG : distG \u03a3, tG : tpcG \u03a3, rlG : repLogG \u03a3, N : namespace}.\n  \n  Definition db1_ip : string := \"127.0.0.1\".\n  Definition db2_ip : string := \"localhost\".\n  Definition server_ip : string := \"0.0.0.0\".\n  Definition client1_ip : string := \"127.0.0.2\".\n  Definition client2_ip : string := \"127.0.0.3\".\n\n  Definition db1_addr : socket_address := SocketAddressInet db1_ip 3306.\n  Definition db2_addr : socket_address := SocketAddressInet db2_ip 3306.\n  Definition server : socket_address := SocketAddressInet server_ip 80%positive.\n  Definition coord_addr : socket_address := SocketAddressInet server_ip 1200.\n\n  Definition ips : gset string := {[ server_ip ; db1_ip ; db2_ip ]}.\n  Definition db_addresses : list socket_address := [db1_addr;db2_addr].\n\n  Lemma mapsto_p_split_3_4 p x :\n    p \u21a6p x -\u2217 p \u21a6p{\u00be} x \u2217 p \u21a6p{\u00bc} x.\n  Proof.\n      by rewrite mapsto_eq /mapsto_def -own_op -auth_frag_op\n         op_singleton pair_op agree_idemp frac_op' Qp_three_quarter_quarter.\n  Qed.\n    \n  Lemma make_tpc_inv :\n    ownA db_addresses -\u2217 gen_heap_ctxC \u2205 -\u2217\n    |==>\n         tpc_inv_cs coord_addr \u2217 coord_addr \u21a6c (0, CS_INIT) \u2217\n         db1_addr \u21a6c (0, CS_INIT) \u2217 db2_addr \u21a6c (0, CS_INIT).\n  Proof.\n    iIntros \"HA Hc\".\n    iDestruct (gen_heap_alloc _ db2_addr (0, CS_INIT)\n                 with \"Hc\") as \">(Hc & Hdb2)\"; first set_solver.\n    iDestruct (gen_heap_alloc _ db1_addr (0, CS_INIT)\n                 with \"Hc\") as \">(Hc & Hdb1)\".\n    { rewrite lookup_insert_ne; set_solver. }\n    iDestruct (gen_heap_alloc _ coord_addr (0, CS_INIT)\n                 with \"Hc\") as \">(Hc & Hcoord)\".\n    { repeat rewrite lookup_insert_ne; try set_solver. }\n    iFrame.\n    rewrite /tpc_inv_cs.\n    iExists [db1_addr;db2_addr],_. iFrame. simpl. iSplitR.\n      by rewrite !dom_insert_L dom_empty_L.\n    iModIntro. iPureIntro. \n    intros.\n    rewrite lookup_insert.\n    case (decide (p = coord_addr)); intro; simplify_eq.\n    - rewrite lookup_insert in H; eauto.\n    - rewrite lookup_insert_ne in H; last done.\n      case (decide (p = db1_addr)); intro; simplify_eq.\n      + rewrite lookup_insert in H; eauto.\n      + rewrite lookup_insert_ne in H; last done.\n        rewrite insert_empty in H.\n        revert H.\n        rewrite lookup_singleton_Some. by intros [_ <-].\n  Qed.\n\n  Lemma logger_runner_spec A :\n    server \u2208 A ->\n    coord_addr \u2209 A \u2192\n    db1_addr \u2208 A \u2192\n    db2_addr \u2208 A \u2192\n    SocketAddressInet client1_ip 80 \u2209 A \u2192\n    SocketAddressInet client2_ip 80 \u2209 A \u2192\n    {{{ server \u2907 log_si \u2217\n        db1_addr \u2907 tpc_participant_si (tpc:=rep_log_tpc (N:=N)) (db1_addr) \u2217\n        db2_addr \u2907 tpc_participant_si (tpc:=rep_log_tpc (N:=N)) (db2_addr) \u2217\n        f\u21a6 A \u2217\n        ownA db_addresses \u2217\n        gen_heap_ctxC \u2205 \u2217\n        gen_heap_ctxP \u2205 \u2217\n        gen_heap_ctxDB \u2205 \u2217\n        gen_heap_ctxW \u2205 \u2217\n        FreeIP client1_ip \u2217\n        FreeIP client2_ip \u2217\n        [\u2217 set] ip \u2208 ips, FreeIP ip }}}\n        logger_runner\n    {{{ v, RET v; True }}}.\n  Proof.\n    iIntros (HsinA HsnotinA Hdb1A Hdb2A Hc1A Hc2A \u03a6)\n            \"(#Hserver & #Hdb1si & #Hdb2si & #Hfix & #Hparts & H) H\u03a6\".\n    iDestruct \"H\" as \"(Hcst & Hpst & Hlog & Hwait & Hc1ip & Hc2ip & Hips)\".\n    iApply fupd_wp.\n    iDestruct (make_tpc_inv with \"Hparts Hcst\") as \">(Hinv & Hcs & Hcsp1 & Hcsp2)\".\n    iDestruct (gen_heap_alloc _ db1_addr (0,(PS_INIT PS_COMMIT))\n                 with \"Hpst\") as \">(Hpst & Hpdb1st)\";\n      first set_solver.\n    iDestruct (gen_heap_alloc _ db2_addr (0,(PS_INIT PS_COMMIT))\n                 with \"Hpst\") as \">(Hpst & Hpdb2st)\".\n    { rewrite lookup_insert_ne; set_solver. }\n    iDestruct (mapsto_p_split_3_4 with \"Hpdb1st\") as \"[Hpdb1st Hpdb1st']\".\n    iDestruct (mapsto_p_split_3_4 with \"Hpdb2st\") as \"[Hpdb2st Hpdb2st']\".\n    iDestruct (gen_heap_alloc _ db1_addr \"\" with \"Hlog\")\n      as \">(Hlog & [Hpdb1log Hpdb1log'])\";\n      first set_solver.\n    iDestruct (gen_heap_alloc _ db2_addr \"\" with \"Hlog\")\n      as \">(Hlog & [Hpdb2log Hpdb2log'])\".\n    { rewrite lookup_insert_ne; set_solver. }\n    iDestruct (gen_heap_alloc _ db1_addr (\"\",\"\") with \"Hwait\")\n      as \">(Hwait & Hpdb1wait)\"; first set_solver.\n    iDestruct (gen_heap_alloc _ db2_addr (\"\",\"\") with \"Hwait\")\n      as \">(Hwait & Hpdb2wait)\".\n    { rewrite lookup_insert_ne; set_solver. }\n    iMod (inv_alloc tpc_inv_cs_n _ (tpc_inv_cs coord_addr) with \"Hinv\") as \"#HcI\".\n    iMod (inv_alloc tpc_inv_ps_n _ tpc_inv_ps with \"[Hpst]\") as \"#HpI\".\n    { iNext. iExists _. iFrame. }\n    iMod (inv_alloc rep_log_inv_n _ rep_log_inv with \"[Hlog Hwait]\") as \"#HrepI\".\n    { iNext. iExists _,_. iFrame. }\n    iModIntro.\n    iDestruct (big_sepS_delete _ _ \"0.0.0.0\" with \"Hips\") as \"(Hc & Hips)\";\n      first set_solver.\n    iDestruct (big_sepS_delete _ _ \"127.0.0.1\" with \"Hips\") as \"(Hdb1 & Hips)\";\n      first set_solver.\n    iDestruct (big_sepS_delete _ _ \"localhost\" with \"Hips\") as \"(Hdb2 & _)\";\n      first set_solver.\n    rewrite /logger_runner.\n    wp_makeaddress. wp_let. wp_makeaddress. wp_let.\n    wp_apply list_make_spec; auto. iIntros (? ?). simpl. wp_let.\n    wp_apply list_cons_spec; auto. iIntros (? ?). simpl. wp_let.\n    wp_apply list_cons_spec; auto. iIntros (dbs Hdbs). simpl. wp_let.\n    wp_makeaddress. wp_let.\n    wp_apply (wp_start with \"[-]\"); first auto. iFrame. simpl. \n    iSplitL \"Hpdb1log Hpdb2log Hpdb1st' Hpdb2st' Hdb1 Hdb2 Hc1ip Hc2ip H\u03a6\";\n      last first.\n    { iNext. iIntros \"Hn Hip\". iDestruct \"Hn\" as (\u03b3s) \"Hn\".\n      iApply (logger_spec _ _ _ server_ip _ db_addresses server coord_addr\n                with \"[-] []\");\n         try iFrame;try iFrame \"#\"; simpl;\n          eauto; try done.\n      - apply NoDup_cons_2; last apply NoDup_singleton.\n        inversion 1. inversion H2. }\n    iNext. wp_seq.\n    wp_apply (wp_start with \"[-]\"); first auto. iFrame.\n    iSplitL \"Hpdb2log Hpdb2st' Hdb2 Hc1ip Hc2ip H\u03a6\"; last first.\n    { iNext. iIntros \"Hn Hip\".\n      iDestruct \"Hn\" as (\u03b3) \"Hn\".\n      iApply (db_spec _ A _ _ _ db_addresses with \"[Hn Hip $Hpdb1st' $Hpdb1log] []\");\n        eauto; try iFrame; try iFrame \"#\".\n      rewrite /db_addresses /db1_addr /db1_ip. set_solver. }\n    iNext. wp_seq.\n    wp_apply (wp_start with \"[-]\"); first auto. iFrame.\n    iSplitL \"Hc1ip Hc2ip H\u03a6\"; last first.\n    { iNext. iIntros \"Hn Hip\".\n      iDestruct \"Hn\" as (\u03b3) \"Hn\".\n      iApply (db_spec _ A _ _ _ db_addresses with \"[Hn Hip $Hpdb2st' $Hpdb2log] []\");\n        eauto; try iFrame; try iFrame \"#\".\n      rewrite /db_addresses /db1_addr /db1_ip. set_solver. }\n    iNext. wp_seq.\n    wp_apply (wp_start with \"[-]\"); first auto; iFrame. \n    iSplitL \"Hc2ip H\u03a6\"; last first.\n    { iNext. iIntros \"Hn Hip\".\n      iDestruct \"Hn\" as (\u03b3) \"Hn\".\n      iApply (client_spec with \"[Hn $Hip]\"); eauto; iFrame \"#\". }\n    iNext. wp_seq.\n    wp_apply (wp_start with \"[-]\"); first auto; iFrame. \n    iSplitL \"H\u03a6\"; last first.\n    { iNext. iIntros \"Hn Hip\".\n      iDestruct \"Hn\" as (\u03b3) \"Hn\".\n      iApply (client_spec with \"[Hn $Hip]\"); eauto; iFrame \"#\". }\n    by iApply \"H\u03a6\".\n  Qed.\n\nEnd rep_log_runner.\n\nLemma make_repLogG `{repLogPreG} :\n  (|==> \u2203 _ : repLogG \u03a3, gen_heap_ctxDB \u2205 \u2217 gen_heap_ctxW \u2205)%I.\nProof.\n  iStartProof.\n  iMod (gen_heap_init (L:=socket_address) (V:=string) \u2205) as (\u03b3db) \"Hdb\".\n  iMod (gen_heap_init (L:=socket_address) (V:=string*string) \u2205) as (\u03b3w) \"HW\".\n  iModIntro.\n  iExists {|\n      repLog_inG := \u03b3db;\n      repWait_inG := \u03b3w;\n    |}. iFrame.\nQed.\n\nDefinition rep_log_is :=\n  {|\n    state_heaps := \u2205;\n    state_sockets := \u2205;\n    state_lookup := \u2205;\n    state_ports_in_use :=\n      <[server_ip := \u2205 ]> $ <[db1_ip := \u2205 ]> $ <[db2_ip := \u2205 ]>\n      $ <[client1_ip := \u2205 ]> $ <[client2_ip := \u2205 ]> $ \u2205;\n    state_ms := \u2205;\n  |}.\n\nDefinition fixed_dom : gset socket_address := {[ server; db1_addr; db2_addr ]}.\nDefinition client_ips : gset string := {[ client1_ip ; client2_ip ]}.\nDefinition all_ips : gset string := ips \u222a client_ips.\n\nLemma client_ips_disj :\n  ips ## client_ips.\nProof. set_solver. Qed.\n\nDefinition socket_interp `{distG \u03a3, tpcG \u03a3, repLogG \u03a3, N : namespace} (sa : socket_address) : socket_interp \u03a3 :=\n  (match sa with\n   | SocketAddressInet \"0.0.0.0\" 80 => log_si\n   | SocketAddressInet \"127.0.0.1\" 3306 =>\n     tpc_participant_si (tpc:=rep_log_tpc (N:=N)) (db1_addr)\n   | SocketAddressInet \"localhost\" 3306 =>\n     tpc_participant_si (tpc:=rep_log_tpc (N:=N)) (db2_addr)\n   | _ => client_si\n   end)%I.\n\nTheorem rep_log_safe : adequate NotStuck logger_runner rep_log_is (\u03bb v, True).\nProof.\n  set (\u03a3 := #[dist\u03a3; tpc\u03a3; repLog\u03a3]).\n  apply (@dist_adequacy \u03a3 _ all_ips fixed_dom); try done; last first.\n  { intros i.\n    rewrite /all_ips !elem_of_union !elem_of_singleton.\n    intros [[]|]; subst; set_solver. }\n  { rewrite /all_ips /= !dom_insert_L dom_empty_L right_id_L !assoc_L //. }\n  iIntros (dinvG).\n  iMod (@make_repLogG \u03a3) as (?) \"[? ?]\".\n  iMod (@own_alloc \u03a3 (agreeR (leibnizC (list socket_address))) _ (to_agree db_addresses)) as (\u03b3) \"H\"; first done.  \n  iMod (gen_heap_init (\u03a3:=\u03a3) (L:=socket_address) (V:=nat * coordinator_state) \u2205) as (\u03b3c) \"Hc\".\n  iMod (gen_heap_init (\u03a3:=\u03a3) (L:=socket_address) (V:=nat * participant_state) \u2205) as (\u03b3p) \"Hp\".\n  iModIntro. iExists socket_interp.\n  iIntros \"Hsi #Hsc Hips\".\n  iApply (@logger_runner_spec _ _ {|\n      tpc_coordinator_stateG := \u03b3c;\n      tpc_participant_stateG := \u03b3p;\n      tpc_nodes_name := \u03b3\n    |} _ nroot with \"[-] []\"); eauto;\n    rewrite /fixed_dom /server; try iFrame; try set_solver.\n  rewrite (big_sepS_union _ {[SocketAddressInet server_ip 80;_]}); last set_solver.\n  rewrite (big_sepS_union _ {[SocketAddressInet server_ip 80]}); last set_solver.\n  rewrite big_sepS_singleton big_sepS_singleton big_sepS_singleton.\n  iDestruct \"Hsc\" as \"[[Hsi1 Hsi2] Hsi3]\".\n  unfold db1_addr,db2_addr. simpl. unfold db1_addr,db2_addr. iFrame \"#\".\n  rewrite /all_ips. rewrite (big_sepS_union _ ips); last apply client_ips_disj.\n  rewrite /client_ips (big_sepS_union _ {[client1_ip]}); last set_solver.\n  rewrite big_sepS_singleton big_sepS_singleton.\n  iDestruct \"Hips\" as \"[Hips1 [Hips2 Hips3]]\". iFrame.\nQed.  \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/replicated_log/rep_log_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2845760102840561, "lm_q1q2_score": 0.1555885619618593}}
{"text": "From isla Require Import opsem.\n\nDefinition a8000c : isla_trace :=\n  AssumeReg \"MDSCR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"EDSCR\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"MDCR_EL2\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"MDCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSLSR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"SP\"] (RegVal_Base (Val_Bits (BV 1%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL1\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  Smt (DeclareConst 69%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPTR_EL2\" [] (RegVal_Base (Val_Symbolic 69%Z)) Mk_annot :t:\n  Smt (DeclareConst 71%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPTR_EL3\" [] (RegVal_Base (Val_Symbolic 71%Z)) Mk_annot :t:\n  Smt (DeclareConst 76%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPACR_EL1\" [] (RegVal_Base (Val_Symbolic 76%Z)) Mk_annot :t:\n  Smt (DeclareConst 84%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CNTHCTL_EL2\" [] (RegVal_Base (Val_Symbolic 84%Z)) Mk_annot :t:\n  Smt (DeclareConst 87%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL2\" [] (RegVal_Base (Val_Symbolic 87%Z)) Mk_annot :t:\n  Smt (DeclareConst 90%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CNTKCTL_EL1\" [] (RegVal_Base (Val_Symbolic 90%Z)) Mk_annot :t:\n  Smt (DeclareConst 97%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAM2_EL2\" [] (RegVal_Base (Val_Symbolic 97%Z)) Mk_annot :t:\n  Smt (DeclareConst 108%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICH_HCR_EL2\" [] (RegVal_Base (Val_Symbolic 108%Z)) Mk_annot :t:\n  Smt (DeclareConst 121%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL1_NS\" [] (RegVal_Base (Val_Symbolic 121%Z)) Mk_annot :t:\n  Smt (DeclareConst 126%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAMIDR_EL1\" [] (RegVal_Base (Val_Symbolic 126%Z)) Mk_annot :t:\n  Smt (DeclareConst 140%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"PMUSERENR_EL0\" [] (RegVal_Base (Val_Symbolic 140%Z)) Mk_annot :t:\n  Smt (DeclareConst 147%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAM3_EL3\" [] (RegVal_Base (Val_Symbolic 147%Z)) Mk_annot :t:\n  Smt (DeclareConst 150%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL3\" [] (RegVal_Base (Val_Symbolic 150%Z)) Mk_annot :t:\n  Smt (DeclareConst 157%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"MPAMHCR_EL2\" [] (RegVal_Base (Val_Symbolic 157%Z)) Mk_annot :t:\n  Smt (DeclareConst 174%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"HSTR_EL2\" [] (RegVal_Base (Val_Symbolic 174%Z)) Mk_annot :t:\n  Smt (DeclareConst 196%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R0\" [] (RegVal_Base (Val_Symbolic 196%Z)) Mk_annot :t:\n  Smt (DefineConst 197%Z (Val (Val_Symbolic 196%Z) Mk_annot)) Mk_annot :t:\n  WriteReg \"HCR_EL2\" [] (RegVal_Base (Val_Symbolic 197%Z)) Mk_annot :t:\n  Barrier (RegVal_Base (Val_Enum ((Mk_enum_id 2%nat), Mk_enum_ctor 27%nat))) Mk_annot :t:\n  Smt (DeclareConst 227%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 227%Z)) Mk_annot :t:\n  Smt (DefineConst 228%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 227%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 228%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/simple_hvc/a8000c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15558317360244908}}
{"text": "From fae_gtlc_mu.refinements.static_gradual Require Export logical_relation.\nFrom fae_gtlc_mu.cast_calculus Require Export types typing.\nFrom fae_gtlc_mu.stlc_mu Require Export lang.\nFrom fae_gtlc_mu.cast_calculus Require Export lang.\n\nSection fundamental.\n  Context `{!implG \u03a3,!specG \u03a3}.\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 (ectx_language.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 {\u0393 e e' \u03c4} : \u0393 \u22a8 e \u2264log\u2264 e' : \u03c4 \u2192 \u2200 vvs ei' K',\n    \u22a2 initially_inv ei' \u2227 \u27e6 \u0393 \u27e7* vvs \u2227 currently_half (fill K' (e'.[cast_calculus.typing_lemmas.env_subst (vvs.*2)]))\n    \u2192 WP e.[stlc_mu.typing_lemmas.env_subst (vvs.*1)] {{ v, \u2203 v',\n        currently_half (fill K' (cast_calculus.lang.of_val v')) \u2227 interp \u03c4 (v, v') }}.\n  Proof.\n    iIntros (Hlog vvs K \u03c1) \"[#H\u03c1 [H\u0393 Hj]]\". asimpl.\n    iApply (Hlog with \"[H\u0393]\"); iFrame. eauto.\n  Qed.\n\n  Notation \"'` H\" := (bin_log_related_alt H) (at level 8).\n\n  Lemma bin_log_related_var \u0393 x \u03c4 :\n    \u0393 !! x = Some \u03c4 \u2192 \u0393 \u22a8 stlc_mu.lang.Var x \u2264log\u2264 cast_calculus.lang.Var x : \u03c4.\n  Proof.\n    iIntros (? vvs ei') \"[#H\u03c1 #H\u0393]\". iIntros (K). iIntros \"Hj /=\".\n    iDestruct (interp_env_Some_l with \"H\u0393\") as ([v v']) \"[Heq Hv]\"; first done.\n    iDestruct \"Heq\" as %Heq.\n    erewrite !stlc_mu.typing_lemmas.env_subst_lookup; rewrite ?list_lookup_fmap ?Heq; eauto.\n    erewrite !cast_calculus.typing_lemmas.env_subst_lookup; rewrite ?list_lookup_fmap ?Heq; eauto.\n    iApply wp_value. eauto.\n  Qed.\n\n  Lemma bin_log_related_unit \u0393 : \u0393 \u22a8 stlc_mu.lang.Unit \u2264log\u2264 cast_calculus.lang.Unit : TUnit.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\". iIntros (K) \"Hj /=\".\n    iApply wp_value. iExists UnitV. rewrite unfold_interp_type_pair. eauto.\n  Qed.\n\n  Lemma bin_log_related_pair \u0393 e1 e2 e1' e2' \u03c41 \u03c42\n      (IHHtyped1 : \u0393 \u22a8 e1 \u2264log\u2264 e1' : \u03c41)\n      (IHHtyped2 : \u0393 \u22a8 e2 \u2264log\u2264 e2' : \u03c42) :\n    \u0393 \u22a8 stlc_mu.lang.Pair e1 e2 \u2264log\u2264 Pair e1' e2' : TProd \u03c41 \u03c42.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.PairLCtx e2.[stlc_mu.typing_lemmas.env_subst _]) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ ((cast_calculus.lang.PairLCtx e2'.[env_subst _]) :: K)).\n    smart_wp_bind (stlc_mu.lang.PairRCtx v) w w' \"[Hw #Hiw]\"\n      ('`IHHtyped2 _ _ ((PairRCtx v') :: K)).\n    iApply wp_value.\n    iExists (PairV v' w'); iFrame \"Hw\".\n    rewrite interp_rw_TProd.\n    iExists (v, v'), (w, w'). simpl; repeat iSplit; trivial.\n  Qed.\n\n  Lemma bin_log_related_fst \u0393 e e' \u03c41 \u03c42\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : TProd \u03c41 \u03c42) :\n    \u0393 \u22a8 stlc_mu.lang.Fst e \u2264log\u2264 Fst e' : \u03c41.\n  Proof.\n    iIntros (vvs ei') \"[#H\u03c1 #H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.FstCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ (FstCtx :: K)); cbn.\n    rewrite interp_rw_TProd.\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 \u0393 e e' \u03c41 \u03c42\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : TProd \u03c41 \u03c42) :\n    \u0393 \u22a8 stlc_mu.lang.Snd e \u2264log\u2264 Snd e' : \u03c42.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.SndCtx) v v' \"[Hv #Hiv]\" ('`IHHtyped _ _ (SndCtx :: K)); cbn.\n    rewrite interp_rw_TProd.\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 \u0393 e e' \u03c41 \u03c42\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : \u03c41) :\n    \u0393 \u22a8 stlc_mu.lang.InjL e \u2264log\u2264 InjL e' : (TSum \u03c41 \u03c42).\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.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    rewrite interp_rw_TSum.\n    iLeft; iExists (_,_); eauto 10.\n  Qed.\n\n  Lemma bin_log_related_injr \u0393 e e' \u03c41 \u03c42\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : \u03c42) :\n    \u0393 \u22a8 stlc_mu.lang.InjR e \u2264log\u2264 InjR e' : TSum \u03c41 \u03c42.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.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    rewrite interp_rw_TSum.\n    iRight; iExists (_,_); eauto 10.\n  Qed.\n\n  Lemma bin_log_related_case \u0393 (e0 e1 e2 : stlc_mu.lang.expr) (e0' e1' e2' : cast_calculus.lang.expr) \u03c41 \u03c42 \u03c43\n      (IHHtyped1 : \u0393 \u22a8 e0 \u2264log\u2264 e0' : TSum \u03c41 \u03c42)\n      (IHHtyped2 : \u03c41 :: \u0393 \u22a8 e1 \u2264log\u2264 e1' : \u03c43)\n      (IHHtyped3 : \u03c42 :: \u0393 \u22a8 e2 \u2264log\u2264 e2' : \u03c43) :\n    \u0393 \u22a8 stlc_mu.lang.Case e0 e1 e2 \u2264log\u2264 Case e0' e1' e2' : \u03c43.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    iDestruct (interp_env_length with \"H\u0393\") as %?.\n    smart_wp_bind (stlc_mu.lang.CaseCtx _ _) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ ((CaseCtx _ _) :: K)); cbn.\n    rewrite interp_rw_TSum.\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 \u0393 (e : stlc_mu.lang.expr) (e' : cast_calculus.lang.expr) \u03c41 \u03c42\n      (IHHtyped : \u03c41 :: \u0393 \u22a8 e \u2264log\u2264 e' : \u03c42) :\n    \u0393 \u22a8 stlc_mu.lang.Lam e \u2264log\u2264 Lam e' : TArrow \u03c41 \u03c42.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    iApply wp_value. iExists (LamV _).\n    rewrite interp_rw_TArrow.\n    iIntros \"{$Hj} !#\".\n    iIntros ([v v']) \"#Hiv\". iIntros (K') \"Hj\".\n    iDestruct (interp_env_length with \"H\u0393\") 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 \u0393 e1 e2 e1' e2' \u03c41 \u03c42\n      (IHHtyped1 : \u0393 \u22a8 e1 \u2264log\u2264 e1' : TArrow \u03c41 \u03c42)\n      (IHHtyped2 : \u0393 \u22a8 e2 \u2264log\u2264 e2' : \u03c41) :\n    \u0393 \u22a8 stlc_mu.lang.App e1 e2 \u2264log\u2264 App e1' e2' :  \u03c42.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    smart_wp_bind (stlc_mu.lang.AppLCtx (e2.[stlc_mu.typing_lemmas.env_subst (vvs.*1)])) v v' \"[Hv #Hiv]\"\n      ('`IHHtyped1 _ _ (((AppLCtx (e2'.[env_subst (vvs.*2)]))) :: K)); cbn.\n    smart_wp_bind (stlc_mu.lang.AppRCtx v) w w' \"[Hw #Hiw]\"\n                  ('`IHHtyped2 _ _ ((AppRCtx v') :: K)); cbn.\n    rewrite interp_rw_TArrow.\n    iApply (\"Hiv\" $! (w, w') with \"Hiw\"); simpl; eauto.\n  Qed.\n\n  Lemma bin_log_related_fold \u0393 e e' \u03c4\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : \u03c4.[(TRec \u03c4)/]) :\n    \u0393 \u22a8 stlc_mu.lang.Fold e \u2264log\u2264 cast_calculus.lang.Fold e' : TRec \u03c4.\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    iApply (wp_bind (stlc_mu.lang.fill_item stlc_mu.lang.FoldCtx)).\n    iApply (wp_wand with \"[Hj]\"). iApply ('`IHHtyped _ _ (FoldCtx :: K)). iFrame. auto.\n    iIntros (v); iDestruct 1 as (v') \"[Hv #Hiv]\".\n    iApply wp_value.\n    iExists (FoldV v'). iFrame \"Hv\".\n    rewrite interp_rw_TRec.\n    iAlways. iExists _, _. eauto.\n  Qed.\n\n  Lemma bin_log_related_unfold \u0393 e e' \u03c4\n      (IHHtyped : \u0393 \u22a8 e \u2264log\u2264 e' : TRec \u03c4) :\n    \u0393 \u22a8 stlc_mu.lang.Unfold e \u2264log\u2264 Unfold e' : \u03c4.[(TRec \u03c4)/].\n  Proof.\n    iIntros (vvs ei') \"#[H\u03c1 H\u0393]\"; iIntros (K) \"Hj /=\".\n    iApply (wp_bind (stlc_mu.lang.fill_item stlc_mu.lang.UnfoldCtx)).\n    iApply (wp_wand with \"[Hj]\"). iApply ('`IHHtyped _ _ (UnfoldCtx :: K)). iFrame. auto.\n    iIntros (v). iDestruct 1 as (v') \"[Hw #Hiw]\".\n    simpl.\n    rewrite interp_rw_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.\n  Qed.\n\nEnd fundamental.\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_easy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.30404167496654744, "lm_q1q2_score": 0.15558317360244908}}
{"text": "From iris.algebra Require Import gmap auth agree gset coPset excl csum.\nFrom Perennial.base_logic.lib Require Export fancy_updates.\nFrom stdpp Require Export namespaces.\nFrom Perennial.base_logic.lib Require Import wsat invariants ae_invariants saved_prop.\nFrom Perennial.Helpers Require Import Qextra.\nFrom iris.algebra Require Import gmap.\nFrom iris.proofmode Require Import tactics.\nFrom Perennial.program_logic Require Export step_fupd_extra crash_weakestpre ae_invariants_mutable later_res private_invariants staged_invariant_alt wpc_nval.\nFrom iris.prelude Require Import options.\nFrom iris.prelude Require Import options.\n\nSet Default Proof Using \"Type\".\n\n#[global]\nExisting Instances pri_inv_tok_timeless later_tok_timeless.\n\nSection def.\nContext `{IRISG: !irisGS \u039b \u03a3, !generationGS \u039b \u03a3}.\nContext `{!pri_invG IRISG}.\nContext `{!later_tokG IRISG}.\nContext `{!stagedG \u03a3}.\n\nLemma staged_inv_wpc_nval E P Qs Qs' R :\n  staged_value \u22a4 Qs P -\u2217\n  \u25b7 (Qs -\u2217 |NC={E}=> \u25a1 (Qs' -\u2217 P) \u2217 Qs' \u2217 R) -\u2217\n  wpc_nval E (R \u2217 staged_value \u22a4 Qs' P).\nProof.\n  iIntros \"Hstaged Hwand\".\n  rewrite /wpc_nval.\n  iIntros (E' e s \u03a6 \u03a6c Hnval Hsub) \"Hwp\".\n  iDestruct \"Hstaged\" as (??????) \"(Hown&Hownstat&#Hsaved1&#Hsaved2&Hltok&Hitok&Hinv)\".\n  iDestruct \"Hinv\" as (mj_wp_init mj_ishare Hlt) \"#Hinv\".\n  rewrite /staged_inv.\n  rewrite wpc_eq /wpc_def. iIntros (mj).\n\n  iEval (rewrite wpc0_unfold).\n  rewrite /wpc_pre. iSplit; last first.\n  {\n    iSpecialize (\"Hwp\" $! mj). rewrite wpc0_unfold /wpc_pre.\n    iDestruct \"Hwp\" as \"(_&Hwp)\".\n    iIntros (g1 ns D' \u03bas) \"Hg #HC Hlc\".\n    iSpecialize (\"Hwp\" with \"[$] [$] [$]\").\n    iApply (step_fupd2N_inner_wand with \"Hwp\"); auto.\n  }\n  rewrite Hnval.\n  iIntros (q \u03c31 g1 ns D \u03ba \u03bas nt) \"H\u03c3 Hg HNC Hlc\".\n  iDestruct (pri_inv_tok_disj_inv_half with \"[$]\") as %Hdisj.\n  iMod (pri_inv_acc with \"[$]\") as \"(Hinner&Hclo)\".\n  { set_solver. }\n  iEval (rewrite staged_inv_inner_unfold) in \"Hinner\".\n  iDestruct \"Hinner\" as (?????) \"(>Hown'&#Hsaved1'&#Hsaved2'&>Hstatus'&>Hitok_ishare&Hinner)\".\n  iDestruct (own_valid_2 with \"Hown' Hown\") as \"#H\".\n  iDestruct \"H\" as %[Heq%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n  iDestruct (own_valid_2 with \"Hstatus' Hownstat\") as \"#Heq_status\".\n  iDestruct \"Heq_status\" as %[Heq_status%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n  inversion Heq; subst.\n  iMod (later_tok_decr with \"[$]\") as (ns' Hlt') \"Hg\".\n  iMod (fupd2_mask_subseteq \u2205 \u2205) as \"Hclo'\"; [set_solver+..|].\n  iModIntro. simpl. iModIntro. iNext. iModIntro. iApply (step_fupd2N_le (S (S (num_laters_per_step ns')))).\n  { etransitivity; last eapply (num_laters_per_step_exp ns'); lia. }\n  simpl.\n  iDestruct (saved_prop_agree with \"Hsaved1 Hsaved1'\") as \"Hequiv1\".\n  iDestruct (saved_prop_agree with \"Hsaved2 Hsaved2'\") as \"Hequiv2\".\n  iModIntro. iModIntro. iModIntro.\n  iDestruct \"Hinner\" as \"[(HPs&_)|Hfin]\"; last first.\n  { (* Impossible, since we have NC token. *)\n    iDestruct \"Hfin\" as \"(_&HC&_)\". iDestruct (NC_C with \"[$] [$]\") as %[]. }\n  iRewrite -\"Hequiv1\" in \"HPs\".\n  iMod \"Hclo'\".\n  iSpecialize (\"Hwand\" with \"[$]\").\n  rewrite ncfupd_eq /ncfupd_def. iSpecialize (\"Hwand\" with \"[$]\").\n  iPoseProof (fupd_fupd2 with \"Hwand\") as \"Hwand\".\n  iMod (fupd2_mask_mono with \"Hwand\") as \"((#Hwand&HQs'&HR)&HNC)\"; eauto.\n\n  iSpecialize (\"Hwp\" $! mj). rewrite wpc0_unfold /wpc_pre.\n  rewrite Hnval. iDestruct \"Hwp\" as \"(Hwp&_)\".\n  iMod (saved_prop_alloc Qs') as (\u03b3prop_stored') \"#Hsaved1''\".\n  { apply dfrac_valid_discarded. }\n  iMod (saved_prop_alloc True%I) as (\u03b3prop_remainder') \"#Hsaved2''\".\n  { apply dfrac_valid_discarded. }\n  iMod (own_update_2 _ _ _ (\u25cf Excl' (\u03b3prop_stored', \u03b3prop_remainder') \u22c5\n                              \u25ef Excl' (\u03b3prop_stored', \u03b3prop_remainder'))\n              with \"Hown' Hown\") as \"[Hown' Hown]\".\n  { by apply auth_update, option_local_update, exclusive_local_update. }\n  iMod (\"Hclo\" with \"[Hown' Hstatus' HQs' Hitok_ishare]\").\n  { iNext.\n    iEval (rewrite staged_inv_inner_unfold).\n    iExists _, _, _, _, _. iFrame \"\u2217 #\".\n    iLeft.\n    iSplit; eauto.\n    { iIntros. iDestruct (\"Hwand\" with \"[$]\") as \"$\". eauto. }\n  }\n  iMod (\"Hwp\" with \"[$] [$] [$] [Hlc]\") as \"H\".\n  { iApply (lc_weaken with \"Hlc\").\n    apply num_laters_per_step_lt in Hlt'. lia. }\n  iApply (step_fupd2N_wand with \"H\").\n  iIntros \"($&H)\".\n  iIntros.\n  iMod (\"H\" with \"[//]\") as \"($&Hg&Hwpc0&$)\".\n  iMod (later_tok_incr with \"[$]\") as \"(Hg&Hltok)\".\n  iMod (global_state_interp_le with \"Hg\") as \"$\".\n  { apply Nat.le_succ_l, step_count_next_mono; lia. }\n  iModIntro.\n  iApply (wpc0_strong_mono with \"Hwpc0\"); auto.\n  iSplit.\n  { iIntros (?) \"H\". iDestruct (\"H\" with \"[-]\") as \"H\".\n    { iFrame. iExists _, _, _, _, _, _. iFrame \"# \u2217\".\n      iExists _, _. iFrame \"#\". eauto. }\n    iFrame. eauto. }\n  eauto.\nQed.\n\nEnd def.\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/staged_invariant_wpc_nval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.15558316714849366}}
{"text": "Require Import Bool Vector List String Peano_dec.\nRequire Import Common FMap HVector ListSupport IndexSupport.\nRequire Import Syntax Topology Semantics Invariant.\nRequire Import RqRsLang.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template Ex.Msi.\nRequire Import Ex.Msi.Msi Ex.Msi.MsiObjInv.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\nSection System.\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  Hint Extern 0 (TreeTopo _) => apply tree2Topo_TreeTopo.\n  Hint Extern 0 (WfDTree _) => apply tree2Topo_WfDTree.\n\n  Lemma msi_indices:\n    map obj_idx (sys_objs impl) = c_li_indices cifc ++ c_l1_indices cifc.\n  Proof.\n    simpl; rewrite c_li_indices_head_rootOf at 2 by assumption.\n    simpl; f_equal.\n    rewrite map_app, map_map, map_id; simpl.\n    rewrite map_map, map_id; reflexivity.\n  Qed.\n\n  Lemma msi_GoodORqsInit: GoodORqsInit (initsOf impl).\n  Proof.\n    apply initORqs_GoodORqsInit.\n  Qed.\n\n  Lemma msi_WfDTree: WfDTree topo.\n  Proof.\n    apply tree2Topo_WfDTree.\n  Qed.\n\n  Lemma msi_RqRsChnsOnDTree: RqRsChnsOnDTree topo.\n  Proof.\n    apply tree2Topo_RqRsChnsOnDTree.\n  Qed.\n\n  Lemma msi_RqRsChnsOnSystem: RqRsChnsOnSystem topo impl.\n  Proof.\n    eapply tree2Topo_RqRsChnsOnSystem with (tr0:= tr) (bidx:= [0]); try reflexivity.\n    - destruct (tree2Topo _ _); reflexivity.\n    - simpl.\n      rewrite map_app.\n      do 2 rewrite map_trans.\n      do 2 rewrite map_id.\n      rewrite app_comm_cons.\n      rewrite <-c_li_indices_head_rootOf by assumption.\n      reflexivity.\n  Qed.\n\n  Lemma msi_ExtsOnDTree: ExtsOnDTree topo impl.\n  Proof.\n    eapply tree2Topo_ExtsOnDTree with (tr0:= tr) (bidx:= [0]); try reflexivity.\n    destruct (tree2Topo _ _); reflexivity.\n  Qed.\n\n  Lemma msi_RqRsDTree: RqRsDTree topo impl.\n  Proof.\n    red; repeat ssplit.\n    - auto using msi_WfDTree.\n    - auto using msi_RqRsChnsOnDTree.\n    - auto using msi_RqRsChnsOnSystem.\n    - auto using msi_ExtsOnDTree.\n  Qed.\n\n  Ltac solve_GoodRqRsRule_unfold ::= autounfold with MsiRules.\n\n  Lemma msi_GoodRqRsSys: GoodRqRsSys topo impl.\n  Proof.\n    repeat\n      match goal with\n      | |- GoodRqRsSys _ _ => red\n      | |- GoodRqRsObj _ _ _ => red\n      | |- Forall _ _ => simpl; constructor; simpl\n      | |- Forall _ (_ ++ _) => apply Forall_app\n      end.\n\n    - (** Main memory *)\n\n      assert (In (rootOf topo) (c_li_indices cifc)) as Hrin.\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      simpl.\n      repeat\n        match goal with\n        | |- Forall _ (_ ++ _) => apply Forall_app\n        | |- Forall _ (_ :: _) => constructor\n        | |- Forall _ nil => constructor\n        end.\n\n      apply Forall_forall; intros.\n      unfold liRulesFromChildren in H.\n      apply concat_In in H; dest.\n      apply in_map_iff in H; dest; subst.\n      dest_in.\n      all: try (solve_GoodRqRsRule; fail).\n\n    - (** Li caches *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; simpl.\n\n      (* pre-register a fact: an Li cache always has a parent *)\n      pose proof (c_li_l1_indices_has_parent\n                    Htr _ _ (in_or_app _ _ _ (or_introl H0))).\n      destruct H as [pidx ?].\n\n      repeat\n        match goal with\n        | |- Forall _ (_ ++ _) => apply Forall_app\n        | |- Forall _ (_ :: _) => constructor\n        | |- Forall _ nil => constructor\n        end.\n      all: try (solve_GoodRqRsRule; fail).\n\n      1: {\n        apply Forall_forall; intros.\n        unfold liRulesFromChildren in H1.\n        apply concat_In in H1; dest.\n        apply in_map_iff in H1; dest; subst.\n        dest_in.\n        all: try (solve_GoodRqRsRule; fail).\n\n        { (* [liGetSRqUpDownM] *)\n          apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n          pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n          rewrite <-msi_indices in H1.\n\n          rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n          (** [RqUpDownSound] *)\n          red; simpl; intros; dest.\n          apply subtreeChildrenIndsOf_parentIdxOf in H4; [|apply tree2Topo_WfDTree].\n          repeat ssplit; [discriminate| |intuition auto].\n          repeat constructor; try assumption.\n        }\n\n        { (* [liGetMRqUpDownM] *)\n          apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n          pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n          rewrite <-msi_indices in H1.\n\n          rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n          (** [RqUpDownSound] *)\n          red; simpl; intros; dest.\n          apply subtreeChildrenIndsOf_parentIdxOf in H4; [|apply tree2Topo_WfDTree].\n          repeat ssplit; [discriminate| |intuition auto].\n          repeat constructor; try assumption.\n        }\n\n        { (* [liGetMRqUpDownS] *)\n          apply subtreeChildrenIndsOf_parentIdxOf in H3; [|apply tree2Topo_WfDTree].\n          pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H3).\n          rewrite <-msi_indices in H1.\n\n          rule_rqud; eapply rqUpDownRule_RqFwdRule; eauto.\n\n          (** [RqUpDownSound] *)\n          red; simpl; intros; dest.\n          repeat ssplit.\n          { assumption. }\n          { apply Forall_forall; intros.\n            apply in_remove in H9.\n            apply H4 in H9.\n            eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n          }\n          { apply remove_In. }\n        }\n      }\n\n      { (* [liDownSRqDownDownM] *)\n        rule_rqdd.\n        eapply rqDownDownRule_RqFwdRule; eauto.\n\n        (** [RqDownDownSound] *)\n        red; simpl; intros; dest.\n        repeat ssplit; [discriminate|].\n        repeat constructor.\n        eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n      }\n\n      { (* [liGetMRsDownRqDownDirS] *)\n        rule_rsrq; eapply rsDownRqDownRule_RsDownRqDownRule; eauto.\n\n        (** [RsDownRqDownSound] *)\n        red; simpl; intros; dest.\n        red in H1.\n        unfold getUpLockIdxBackI, getUpLockIdxBack in *.\n        destruct (orq@[upRq]) as [rqiu|]; simpl in *; auto.\n        destruct H1 as [rcidx [rqUp ?]]; dest.\n        pose proof (tree2Topo_li_child_li_l1 _ _ _ (tl_In _ _ H0) H1).\n        rewrite <-msi_indices in H9.\n        intros; rewrite H11 in *.\n        repeat ssplit.\n        { assumption. }\n        { apply Forall_forall; intros.\n          apply in_remove in H12.\n          apply H3 in H12.\n          eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n        }\n        { exists rcidx, rqUp.\n          repeat split; try assumption.\n        }\n      }\n\n      { (* [liDownIRqDownDownDirS] *)\n        rule_rqdd.\n        eapply rqDownDownRule_RqFwdRule; eauto.\n\n        (** [RqDownDownSound] *)\n        red; simpl; intros; dest.\n        repeat ssplit; [assumption|].\n        apply Forall_forall; intros.\n        apply H2 in H4.\n        eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n      }\n\n      { (* [liDownIRqDownDownDirM] *)\n        rule_rqdd.\n        eapply rqDownDownRule_RqFwdRule; eauto.\n\n        (** [RqDownDownSound] *)\n        red; simpl; intros; dest.\n        repeat ssplit; [discriminate|].\n        repeat constructor.\n        eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n      }\n\n      { (* [liDownIRqDownDownDirMS] *)\n        rule_rqdd.\n        eapply rqDownDownRule_RqFwdRule; eauto.\n\n        (** [RqDownDownSound] *)\n        red; simpl; intros; dest.\n        repeat ssplit; [assumption|].\n        apply Forall_forall; intros.\n        apply H2 in H4.\n        eapply subtreeChildrenIndsOf_parentIdxOf; eauto.\n      }\n\n    - (** L1 caches *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; simpl.\n\n      (* pre-register a fact: an L1 cache always has a parent *)\n      pose proof (c_li_l1_indices_has_parent\n                    Htr _ _ (in_or_app _ _ _ (or_intror H0))).\n      destruct H as [pidx ?].\n\n      repeat\n        match goal with\n        | |- Forall _ (_ ++ _) => apply Forall_app\n        | |- Forall _ (_ :: _) => constructor\n        | |- Forall _ nil => constructor\n        end.\n      all: try (solve_GoodRqRsRule; fail).\n  Qed.\n\n  Ltac exfalso_RqToUpRule_unfold ::= repeat autounfold with MsiRules in *.\n  Ltac exfalso_RsToUpRule_unfold ::= repeat autounfold with MsiRules in *.\n  Ltac disc_rule_custom ::= disc_msi_obj_invs.\n\n  Lemma msi_RqUpRsUpOkSys: RqUpRsUpOkSys topo impl (MsiObjInvs topo).\n  Proof. (* SKIP_PROOF_ON\n    repeat\n      match goal with\n      | |- RqUpRsUpOkSys _ _ _ => red\n      | |- Forall _ _ => simpl; constructor; simpl\n      | |- Forall _ (_ ++ _) => apply Forall_app\n      end.\n\n    - (** The main memory: no RqUp rules *)\n      red; intros.\n      simpl in H; unfold liRulesFromChildren in H.\n      apply concat_In in H; dest.\n      apply in_map_iff in H; dest; subst.\n      dest_in.\n      all: try (exfalso_RqToUpRule; fail).\n\n    - (** Li cache *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; intros.\n\n      simpl in H; apply in_app_or in H; destruct H;\n        [unfold liRulesFromChildren in H;\n         apply concat_In in H; dest;\n         apply in_map_iff in H; dest; subst;\n         dest_in|dest_in].\n      all: try (exfalso_RqToUpRule; fail).\n\n      + simpl in H2; apply in_app_or in H2; destruct H2;\n          [unfold liRulesFromChildren in H;\n           apply concat_In in H; dest;\n           apply in_map_iff in H; dest; subst;\n           dest_in|dest_in].\n        all: try (exfalso_RsToUpRule; fail).\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; auto.\n          { destruct H17; dest; try solve [congruence|solve_msi]. }\n          { destruct H17; dest; try solve [congruence|solve_msi]. }\n        }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; auto.\n          { solve_msi. }\n          { f_equal; apply M.add_remove_comm; discriminate. }\n        }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; auto.\n          { solve_msi. }\n          { f_equal; apply M.add_remove_comm; discriminate. }\n        }\n\n      + simpl in H2; apply in_app_or in H2; destruct H2;\n          [unfold liRulesFromChildren in H;\n           apply concat_In in H; dest;\n           apply in_map_iff in H; dest; subst;\n           dest_in|dest_in].\n        all: try (exfalso_RsToUpRule; fail).\n\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex.\n          all: try (destruct H17; dest; try solve [congruence|solve_msi]).\n        }\n        { clear; solve_rule_conds_ex.\n          all: try (destruct H17; dest; try solve [congruence|solve_msi]).\n        }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; try solve_msi.\n          f_equal; apply M.add_remove_comm; discriminate.\n        }\n        { clear; solve_rule_conds_ex; try solve_msi. }\n        { clear; solve_rule_conds_ex; try solve_msi.\n          f_equal; apply M.add_remove_comm; discriminate.\n        }\n\n      + simpl in H2; apply in_app_or in H2; destruct H2;\n          [unfold liRulesFromChildren in H;\n           apply concat_In in H; dest;\n           apply in_map_iff in H; dest; subst;\n           dest_in|dest_in].\n        all: try (exfalso_RsToUpRule; fail).\n\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_const; try solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_const; try solve_msi.\n          all: rewrite invalidate_I; solve_msi.\n        }\n        { clear; solve_rule_conds_const; try solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n\n      + simpl in H2; apply in_app_or in H2; destruct H2;\n          [unfold liRulesFromChildren in H;\n           apply concat_In in H; dest;\n           apply in_map_iff in H; dest; subst;\n           dest_in|dest_in].\n        all: try (exfalso_RsToUpRule; fail).\n\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_const; try intuition solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_const; try intuition solve_msi.\n          rewrite invalidate_I; [|solve_msi].\n          intuition solve_msi.\n        }\n        { clear; solve_rule_conds_const; try intuition solve_msi. }\n        { clear; solve_rule_conds_ex; solve_msi. }\n        { clear; solve_rule_conds_ex; try intuition solve_msi. }\n        { clear; solve_rule_conds_ex; try intuition solve_msi. }\n\n    - (** L1 cache *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; intros.\n\n      phide H2; dest_in.\n      all: try (exfalso_RqToUpRule; fail).\n\n      + preveal H4; dest_in.\n        all: try (exfalso_RsToUpRule; fail).\n        { clear; solve_rule_conds_const; solve_msi. }\n        { clear; solve_rule_conds_const; auto. }\n        { clear; solve_rule_conds_const; auto. }\n\n      + preveal H4; dest_in.\n        all: try (exfalso_RsToUpRule; fail).\n        { clear; solve_rule_conds_const. }\n        { clear; solve_rule_conds_const; solve_msi. }\n        { clear; solve_rule_conds_const; solve_msi. }\n\n      + preveal H4; dest_in.\n        all: try (exfalso_RsToUpRule; fail).\n        { clear; solve_rule_conds_const; try solve_msi. }\n        { clear; solve_rule_conds_const.\n          all: rewrite invalidate_I; solve_msi.\n        }\n        { clear; solve_rule_conds_const; try solve_msi. }\n\n      + preveal H4; dest_in.\n        all: try (exfalso_RsToUpRule; fail).\n        { clear; solve_rule_conds_const; try solve_msi. }\n        { clear; solve_rule_conds_const.\n          rewrite invalidate_I; solve_msi.\n        }\n        { clear; solve_rule_conds_const.\n          rewrite invalidate_I; solve_msi.\n        }\n\n        END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Lemma msi_GoodExtRssSys: GoodExtRssSys impl.\n  Proof. (* SKIP_PROOF_ON\n    red; simpl.\n    constructor; [|apply Forall_app].\n    - (** the main memory *)\n      red; simpl.\n      apply Forall_forall; intros.\n      unfold memRulesFromChildren in H.\n      apply concat_In in H; dest.\n      apply in_map_iff in H; dest; subst.\n      dest_in.\n      all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n\n    - (** Li cache *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; simpl.\n      apply Forall_app.\n\n      + apply Forall_forall; intros.\n        unfold liRulesFromChildren in H.\n        apply concat_In in H; dest.\n        apply in_map_iff in H; dest; subst.\n        dest_in.\n        all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n        { (* [liGetMRqUpDownS] *)\n          red; simpl; disc_rule_conds_ex.\n          apply in_map_iff in H3; dest; subst.\n          apply in_remove in H12.\n          apply H5 in H12.\n          simpl in *; solve_GoodExtRssSys.\n        }\n\n      + repeat constructor.\n        all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n        { (* [liGetMRsDownRqDownDirS] *)\n          red; simpl; disc_rule_conds_ex.\n          apply in_map_iff in H2; dest; subst.\n          apply in_remove in H5.\n          apply H11 in H5.\n          simpl in *; solve_GoodExtRssSys.\n        }\n        { (* [liDownIRqDownDownDirS] *)\n          red; simpl; disc_rule_conds_ex.\n          apply in_map_iff in H2; dest; subst.\n          apply H4 in H7.\n          simpl in *; solve_GoodExtRssSys.\n        }\n        { (* [liDownIRqDownDownDirMS] *)\n          red; simpl; disc_rule_conds_ex.\n          apply in_map_iff in H2; dest; subst.\n          apply H4 in H7.\n          simpl in *; solve_GoodExtRssSys.\n        }\n\n    - (** L1 cache *)\n      apply Forall_forall; intros.\n      apply in_map_iff in H.\n      destruct H as [oidx [? ?]]; subst.\n      red; simpl.\n      repeat constructor.\n      all: try (red; simpl; disc_rule_conds_ex; solve_GoodExtRssSys; fail).\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Lemma msi_GoodRqRsInterfSys: GoodRqRsInterfSys topo impl (MsiObjInvs topo).\n  Proof.\n    split.\n    - apply msi_RqUpRsUpOkSys.\n    - apply msi_GoodExtRssSys.\n  Qed.\n\n  Lemma msi_RqRsSys: RqRsSys topo impl (MsiObjInvs topo).\n  Proof.\n    red; repeat ssplit.\n    - apply msi_RqRsDTree.\n    - apply msi_GoodRqRsSys.\n    - apply msi_GoodRqRsInterfSys.\n  Qed.\n\nEnd System.\n\n#[global] Hint Resolve msi_GoodORqsInit msi_WfDTree msi_RqRsDTree msi_RqRsSys.\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/Msi/MsiTopo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.1551020241491525}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import LemmaNat Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import opcode_synthesis verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\nFrom bpf.verifier.simulation Require Import correct_is_well_src correct_is_not_div_by_zero correct_is_shift_range.\n\n\n(**\nCheck bpf_verifier_opcode_load_reg.\nbpf_verifier_opcode_load_reg\n     : nat -> int64 -> M bool\n\n*)\nOpen Scope Z_scope.\n\nDefinition opcode_load_reg_if (op: nat) : opcode_load_reg :=\n  if Nat.eqb op 97%nat then LDXW\n  else if Nat.eqb op 105%nat then LDXH\n  else if Nat.eqb op 113%nat then LDXB\n  else if Nat.eqb op 121%nat then LDXDW\n  else LDX_REG_ILLEGAL_INS.\n\nLemma opcode_load_reg_eqb_eq : forall a b,\n    opcode_load_reg_eqb a b = true -> a = b.\nProof.\n  destruct a,b ; simpl ;congruence.\nQed.\n\nLemma lift_opcode_load_reg :\n  forall (E: nat -> opcode_load_reg)\n         (F: nat -> opcode_load_reg) n,\n    ((fun n => opcode_load_reg_eqb (E n) (F n) = true) n) <->\n      (((fun n => opcode_load_reg_eqb (E n) (F n)) n) = true).\nProof.\n  intros.\n  simpl. reflexivity.\nQed.\n\nLemma byte_to_opcode_load_reg_if_same:\n  forall (op: nat),\n    (op <= 255)%nat ->\n    nat_to_opcode_load_reg op = opcode_load_reg_if op.\nProof.\n  intros.\n  unfold nat_to_opcode_load_reg, opcode_load_reg_if.\n  apply opcode_load_reg_eqb_eq.\n  match goal with\n  | |- ?A = true => set (P := A)\n  end.\n  pattern op in P.\n  match goal with\n  | P := ?F op |- _=>\n      apply (Forall_exec_spec F 255)\n  end.\n  vm_compute.\n  reflexivity.\n  assumption.\nQed.\n\nLemma bpf_verifier_opcode_load_reg_match:\n  forall op\n    (Hop: (op <= 255)%nat)\n    (Halu : nat_to_opcode_load_reg op = LDX_REG_ILLEGAL_INS),\n      97  <> (Z.of_nat op) /\\\n      105 <> (Z.of_nat op) /\\\n      113 <> (Z.of_nat op) /\\\n      121 <> (Z.of_nat op).\nProof.\n  intros.\n  rewrite byte_to_opcode_load_reg_if_same in Halu; auto.\n  unfold opcode_load_reg_if in Halu.\n  change 97  with (Z.of_nat 97%nat).\n  change 105 with (Z.of_nat 105%nat).\n  change 113 with (Z.of_nat 113%nat).\n  change 121 with (Z.of_nat 121%nat).\n\n  repeat match goal with\n  | H : (if ?X then _ else _) = _ |- _ /\\ _ =>\n    split; [destruct X eqn: Hnew; [inversion H |\n      rewrite Nat.eqb_neq in Hnew;\n      intro Hfalse; apply Hnew;\n      symmetry in Hfalse;\n      apply Nat2Z.inj in Hfalse;\n      assumption]\n    | destruct X eqn: Hnew; [inversion H| clear Hnew]]\n  | H : (if ?X then _ else _) = _ |- _ =>\n    destruct X eqn: Hnew; [inversion H |\n      rewrite Nat.eqb_neq in Hnew;\n      intro Hfalse; apply Hnew;\n      symmetry in Hfalse;\n      apply Nat2Z.inj in Hfalse;\n      assumption]\n  end.\nQed.\n\nSection Bpf_verifier_opcode_load_reg.\n  Context {S:special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(nat:Type); (int64:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := bpf_verifier_opcode_load_reg.\n\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_bpf_verifier_opcode_load_reg.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (opcode_correct x))\n     (dcons (fun x => StateLess _ (int64_correct x))\n      (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x => StateLess _ (bool_correct x).\n\n  Instance correct_function_bpf_verifier_opcode_load_reg : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f, bpf_verifier_opcode_load_reg.\n    simpl.\n    unfold INV.\n    destruct nat_to_opcode_load_reg eqn: Hload. (**r case discussion on each load_instruction *)\n    - (**r LDXW *)\n      eapply correct_statement_switch with (n:= 97).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_load_reg in Hload.\n        assert (Hc_eq: c = 97%nat). {\n          clear - Hload.\n          do 97 (destruct c; [inversion Hload|]).\n          destruct c; [reflexivity|].\n          do 24 (destruct c; [inversion Hload|]).\n          inversion Hload.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 97) with 97 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r LDXH *)\n      eapply correct_statement_switch with (n:= 105).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_load_reg in Hload.\n        assert (Hc_eq: c = 105%nat). {\n          clear - Hload.\n          do 105 (destruct c; [inversion Hload|]).\n          destruct c; [reflexivity|].\n          do 16 (destruct c; [inversion Hload|]).\n          inversion Hload.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 105) with 105 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r LDXB *)\n      eapply correct_statement_switch with (n:= 113).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_load_reg in Hload.\n        assert (Hc_eq: c = 113%nat). {\n          clear - Hload.\n          do 113 (destruct c; [inversion Hload|]).\n          destruct c; [reflexivity|].\n          do 8 (destruct c; [inversion Hload|]).\n          inversion Hload.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 113) with 113 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r LDXDW *)\n      eapply correct_statement_switch with (n:= 121).\n      + simpl.\n        (**r s1 -> (Ssequence s1 s2) *)\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n\n        get_invariant _ins.\n        exists (v::nil).\n        split.\n        unfold map_opt, exec_expr. rewrite p0.\n        reflexivity.\n        intros. simpl.\n        tauto.\n        intros.\n\n        correct_forward.\n        get_invariant _b.\n        unfold correct_is_well_src.match_res in c1.\n        unfold match_res.\n        exists v.\n        unfold exec_expr.\n        rewrite p0.\n        split; [reflexivity|].\n        split; [assumption|].\n        unfold eval_inv, bool_correct in c1.\n        rewrite c1.\n        split.\n        unfold Cop.sem_cast; simpl.\n        destruct x; reflexivity.\n        intros.\n        constructor.\n        destruct x; reflexivity.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold exec_expr.\n        rewrite p0. f_equal.\n        unfold eval_inv, opcode_correct in c1.\n        unfold nat_to_opcode_load_reg in Hload.\n        assert (Hc_eq: c = 121%nat). {\n          clear - Hload.\n          do 121 (destruct c; [inversion Hload|]).\n          destruct c; [reflexivity|].\n          inversion Hload.\n        }\n        rewrite Hc_eq in *.\n        destruct c1 as (c1 & _).\n        change (Z.of_nat 121) with 121 in c1.\n        symmetry; assumption.\n      + compute. intuition congruence.\n    - (**r LDX_REG_ILLEGAL_INS *)\n      eapply correct_statement_switch_ex.\n      + reflexivity.\n      + intros.\n        get_invariant _op.\n        unfold eval_inv, opcode_correct in c1.\n        destruct c1 as (c1 & Hc1_range).\n        exists (Z.of_nat c).\n        split.\n        unfold exec_expr.\n        rewrite p0.\n        rewrite c1.\n        reflexivity.\n        split.\n\n        change Int.modulus with 4294967296.\n        lia.\n\n        unfold select_switch.\n        unfold select_switch_case.\n        apply bpf_verifier_opcode_load_reg_match in Hload; auto.\n        destruct Hload as (Hfirst & Hload). eapply Coqlib.zeq_false in Hfirst. rewrite Hfirst; clear Hfirst.\n        repeat match goal with\n        | H: ?X <> ?Y /\\ _ |- context[Coqlib.zeq ?X ?Y] =>\n            destruct H as (Hfirst & H);\n            eapply Coqlib.zeq_false in Hfirst; rewrite Hfirst; clear Hfirst\n        end.\n        eapply Coqlib.zeq_false in Hload; rewrite Hload; clear Hload.\n        (* default *)\n        simpl.\n        eapply correct_statement_seq_body_drop.\n        intros.\n\n        correct_forward.\n        exists (Vint (Int.repr 0)).\n        unfold exec_expr.\n        split; [reflexivity|].\n        unfold eval_inv, match_res, bool_correct, Int.one.\n        split; [reflexivity|].\n        split; [reflexivity|].\n        intros.\n        constructor.\n        reflexivity.\nQed.\n\nEnd Bpf_verifier_opcode_load_reg.\n\nClose Scope Z_scope.\n\nExisting Instance correct_function_bpf_verifier_opcode_load_reg.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_bpf_verifier_opcode_load_reg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.2628418258225589, "lm_q1q2_score": 0.1547846905452143}}
{"text": "Require Import Ascii.\nRequire Import String.\nRequire Import FJ_tactics.\nRequire Import List.\nRequire Import Functors.\nRequire Import FunctionalExtensionality.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import EffPure.\nRequire Import EffState.\n\nSection ESoundS.\n\n  Variable D : Set -> Set.\n  Context {Fun_D : Functor D}.\n  Let DType := DType D.\n\n  Variable E : Set -> Set.\n  Context {Fun_E : Functor E}.\n  Let Exp := Exp E.\n\n  Variable V : Set -> Set.\n  Context {Fun_V : Functor V}.\n  Let Value := Value V.\n\n  Variable (MT : Set -> Set).\n  Context {Fun_MT : Functor MT}.\n  Context {Mon_MT : Monad MT}.\n  Context {Fail_MT : FailMonad 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). (* Evaluation Monad. *)\n  Context {Fun_M : Functor ME}.\n  Context {Mon_M : Monad ME}.\n  Context {FailM : FailMonad ME}.\n  Context {State_M : StateM ME (list Value)}.\n\n  Context {Typeof_F : forall T, FAlgebra TypeofName T (typeofR D MT) E}.\n  Context {evalM_E' : forall T, FAlgebra EvalName T (evalMR V ME) E}.\n\n  Variable TypContext : Set.\n  Context {TypContextCE : ConsExtensionC TypContext}.\n  Context {TypContext_S : SigTypContextC D TypContext}.\n  Context {TypContext_SCE : SigConsExtensionC D TypContext _ _}.\n  Context {TypContext_WFE : WF_EnvC V TypContext}.\n\n  Variable WFV : (WFValue_i D V TypContext -> Prop) -> WFValue_i D V TypContext -> Prop.\n  Context {funWFV : iFunctor WFV}.\n\n  Context {TypContext_SWFE : Sig_WF_EnvC D V TypContext 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 {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\n  Context {WFV_proj1_a_WFV : iPAlgebra WFV_proj1_a_Name (WFV_proj1_a_P D V _ WFV) WFV}.\n  Context {WFV_proj1_b_WFV : iPAlgebra WFV_proj1_b_Name (WFV_proj1_b_P D V _ WFV) WFV}.\n\n\n  Context {WFV_Weaken_WFV : iPAlgebra WFValue_Weaken_Name (WFValue_Weaken_P D V _ WFV) WFV}.\n\n  Context {wfvm_bind_alg :\n             iPAlgebra wfvm_bind_Name (wfvm_bind_P D V MT ME _ WFV WFVM (TypContextCE := TypContextCE)) WFVM}.\n\n  Section State_Sound_Sec.\n\n    Variable WFV' : (WFValue_i D V (list DType) -> Prop) -> WFValue_i D V (list DType) -> Prop.\n    Context {funWFV' : iFunctor WFV'}.\n\n    Variable WFVM' : (WFValueM_i D V MT ME (list DType) -> Prop) -> WFValueM_i D V MT ME (list DType) -> Prop.\n    Context {funWFVM' : iFunctor WFVM'}.\n\n    Global Instance DType_Env_CE : ConsExtensionC (list DType) :=\n      {| ConsExtension := fun Sigma' Sigma =>\n        forall n T, lookup Sigma n = Some T -> lookup Sigma' n = Some T |}.\n    Proof.\n      (* ConsExtension_id *)\n      eauto.\n      (* ConsExtension_trans *)\n      eauto.\n    Defined.\n\n    Global Instance DType_Env_S : SigTypContextC D (list DType) :=\n      {| SigLookup := lookup;\n        SigInsert := insert _|}.\n\n    Global Instance DType_Env_WFE : WF_EnvC V (list DType) :=\n      {| WF_Env := fun env Sigma =>\n        P2_Env (WFValueC _ _ _ WFV' Sigma) env Sigma |}.\n\n    Global Instance DType_Env_SCE : SigConsExtensionC D (list DType) _ _.\n    Proof.\n      constructor.\n    (* ConsExtension_SigLookup *)\n      eauto.\n    (* ConsExtension_SigInsert *)\n      simpl; intros; erewrite lookup_Some_insert; eauto.\n    Qed.\n\n    Context {WFV_Weaken_WFV' : iPAlgebra WFValue_Weaken_Name (WFValue_Weaken_P D V _ WFV') WFV'}.\n\n    Definition WFV'_Weaken := ifold_ WFV' _ (ip_algebra (iPAlgebra := WFV_Weaken_WFV')).\n\n    Global Instance DType_Env_SWFE : Sig_WF_EnvC D V (list DType) WFV' _ _.\n    Proof.\n      constructor; simpl; intros.\n      (* WF_EnvLookup *)\n      unfold WF_Env in H; simpl in H.\n      apply (P2_Env_lookup' _ _ _ _ _ H); auto.\n      (* WF_EnvInsertLookup *)\n      unfold Value.\n      rewrite (P2_Env_length _ _ _ _ _ H); apply lookup_insert.\n      (* WF_EnvInsert *)\n      apply P2_Env_insert; eauto.\n      eapply P2_Env_P_P'; eauto.\n      intros; generalize (WFV'_Weaken _ H1).\n      unfold WFValue_Weaken_P; simpl; intros; eapply H2.\n      simpl; intros; erewrite lookup_Some_insert; eauto.\n      (* WF_EnvReplace *)\n      eapply P2_Env_replace_el; eauto.\n    Qed.\n\n    Definition State_Sound_P (i : WFValueM_i D V MT ME (list DType)) :=\n      forall T (env : list Value),\n        WF_Env V env (wfvm_S _ _ _ _ _ i) ->\n        wfvm_T _ _ _ _ _ i = return_ T ->\n        exists v : Value, exists env', exists Sigma',\n          (put env) >> wfvm_v _ _ _ _ _ i = put env' >> return_ (M := ME) v /\\\n          WFValueC _ _ _ WFV' Sigma' v T.\n\n    Inductive State_Sound_Name := State_Sound_name.\n\n    Context {WFV_proj1_a_WFV' : iPAlgebra WFV_proj1_a_Name (WFV_proj1_a_P D V _ WFV') WFV'}.\n    Context {WFV_proj1_b_WFV' : iPAlgebra WFV_proj1_b_Name (WFV_proj1_b_P D V _ WFV') WFV'}.\n\n    Global Instance State_Sound_WFVM_State :\n      iPAlgebra State_Sound_Name State_Sound_P (WFValueM_State D V MT ME (list DType)).\n    Proof.\n      econstructor.\n      unfold iAlgebra; intros; eapply ind_alg_WFVM_State with (TypContextCE := DType_Env_CE)\n        (TypContext_WFE := DType_Env_WFE);\n        try assumption; unfold 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      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      (* WFVM_Put *)\n      unfold wbind; rewrite associativity.\n      generalize put_put as put_put'; intros; unfold wbind in put_put'; rewrite put_put'.\n      destruct (H2 T0 env H0 H4) as [v [env' [Sigma'' [eval_eq WF_v_T]]]].\n      exists v; exists env'; exists Sigma''; split; auto.\n    Qed.\n\n    Global Instance State_Sound_WFVM_base :\n      iPAlgebra State_Sound_Name State_Sound_P (WFValueM_base D V MT ME _ WFV').\n    Proof.\n      econstructor.\n      unfold iAlgebra; intros; apply ind_alg_WFVM_base with (Monad_ME := Mon_M)\n        (Fail_MT := Fail_MT) (WFV := WFV');\n        try assumption; unfold State_Sound_P; simpl; intros.\n      exists v; exists env; exists Sigma; split; auto.\n      destruct H1 as [mt' mt'_eq]; subst.\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 _ _ _ WFV' _ _ H0); simpl; auto.\n      (* WFVM_Untyped' *)\n      simpl in H1; apply sym_eq in H1.\n      apply FailMonad_Disc in H1; destruct H1; auto.\n    Qed.\n\n    Context {State_Sound_WFVM : iPAlgebra State_Sound_Name State_Sound_P WFVM'}.\n\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\n     Context {WF_MAlg_typeof : WF_MAlgebra Typeof_F}.\n     Context {WF_MAlg_eval : WF_MAlgebra evalM_E'}.\n\n    Lemma eval_State_soundness : forall (e : Exp) Sigma,\n      WFValueMC _ _ _ _ _ WFVM' Sigma (evalM (evalM_E := evalM_E') _ _ _ (proj1_sig e))\n      (typeof _ _ MT (proj1_sig e)).\n    Proof.\n      intro; rewrite <- (@in_out_UP'_inverse _ _ (proj1_sig e) (proj2_sig e)).\n      simpl; unfold typeof, evalM, fold_, mfold, in_t.\n      repeat rewrite wf_malgebra; unfold mfold.\n      destruct (Ind2 (Ind_Alg := eval_soundness'_Exp_E\n        (fun e => typeof _ _ _ (proj1_sig e))\n        (fun e => evalM (evalM_E := evalM_E') _ _ _ (proj1_sig e)))\n        _ (proj2_sig e)) as [e' eval_e'].\n      unfold eval_soundness'_P in eval_e'.\n      intros; eapply eval_e'; intros; auto; try constructor.\n      rewrite (@in_out_UP'_inverse _ _ (proj1_sig _) (proj2_sig _)); auto.\n      rewrite (@in_out_UP'_inverse _ _ (proj1_sig _) (proj2_sig _)); auto.\n      rewrite <- (@in_out_UP'_inverse _ _ (proj1_sig (fst a)) (proj2_sig _)).\n      unfold typeof, evalM, mfold; simpl; unfold in_t;\n        repeat rewrite wf_malgebra; unfold mfold; apply H; auto.\n    Qed.\n\n    Theorem eval_State_Sound :\n      forall (Sigma : Env DType) (e : Exp) (T : DType) (env : Env Value),\n        WF_Env V env Sigma ->\n        typeof D E MT (proj1_sig e) = return_ T ->\n        exists v : Value,\n          exists env' : Env Value,\n            exists Sigma' : Env DType,\n              (put env) >> evalM (evalM_E := evalM_E') _ _ _ (proj1_sig e) =\n              put env' >> return_ (M := ME) v /\\\n              WFValueC _ _ _ WFV' Sigma' v T.\n    Proof.\n      intros Sigma e.\n      apply (ifold_ WFVM' _ (ip_algebra (iPAlgebra := State_Sound_WFVM)) _\n        (eval_State_soundness e Sigma)).\n    Qed.\n\n  End State_Sound_Sec.\n\nEnd ESoundS.\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/ESoundS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2909808785120009, "lm_q1q2_score": 0.1545717701381051}}
{"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: Refinement proof for MAL                *)\n(*                                                                     *)\n(*          Refinement proof for MAL 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 MALOp layer and MAL layer*)\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Asm.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Maps.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import FlatMemory.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import RealParams.\nRequire Import LoadStoreSem1.\nRequire Import AsmImplLemma.\nRequire Import LAsm.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import LayerCalculusLemma.\n\nRequire Import MALT.\nRequire Import MALOp.\nRequire Import ALGenSpec.\n\nRequire Import AbstractDataType.\n\nLocal Open Scope string_scope.\nLocal Open Scope error_monad_scope.\nLocal Open Scope Z_scope.\n\n(** * Definition of the refinement relation*)\nSection Refinement.\n\n  Context `{real_params: RealParams}.\n\n  Notation HDATAOps := (cdata (cdata_ops := malt_data_ops) RData).\n  Notation LDATAOps := (cdata (cdata_ops := malop_data_ops) RData).\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModel}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    (** ** Definition the refinement relation: relate_RData + match_RData *)    \n    Record relate_RData (f:meminj) (hadt: RData) (ladt: RData) :=\n      mkrelate_RData {\n          flatmem_re: FlatMem.flatmem_inj (HP hadt) (HP ladt);\n          vmxinfo_re: vmxinfo hadt = vmxinfo ladt;\n          devout_re: devout hadt = devout ladt;\n          CR3_re:  CR3 hadt = CR3 ladt;\n          ikern_re: ikern hadt = ikern ladt;\n          pg_re: pg hadt = pg ladt;\n          ihost_re: ihost hadt = ihost ladt;\n          ti_fst_re: (fst (ti hadt)) = (fst (ti ladt));\n          ti_snd_re: val_inject f (snd (ti hadt)) (snd (ti ladt));\n          AT_re: AT hadt = AT ladt;\n          nps_re: nps hadt = nps ladt;\n          init_re: init hadt = init ladt\n        }.\n\n    Inductive match_RData: stencil -> RData -> mem -> meminj -> Prop :=\n    | MATCH_RDATA: forall habd m f s, match_RData s habd m f.   \n\n    Local Hint Resolve MATCH_RDATA.\n\n    Global Instance rel_ops: CompatRelOps HDATAOps LDATAOps :=\n      {\n        relate_AbData s f d1 d2 := relate_RData f d1 d2;\n        match_AbData s d1 m f := match_RData s d1 m f;\n        new_glbl := nil\n      }.    \n\n    (** ** Properties of relations*)\n    Section Rel_Property.\n\n      (** Prove that after taking one step, the refinement relation still holds*)    \n      Lemma relate_incr:  \n        forall abd abd' f f',\n          relate_RData f abd abd'\n          -> inject_incr f f'\n          -> relate_RData f' abd abd'.\n      Proof.\n        inversion 1; subst; intros; inv H; constructor; eauto.\n      Qed.\n\n      Lemma relate_kernel_mode:\n        forall abd abd' f,\n          relate_RData f abd abd' \n          -> (kernel_mode abd <-> kernel_mode abd').\n      Proof.\n        inversion 1; simpl; split; congruence.\n      Qed.\n\n      Lemma relate_observe:\n        forall p abd abd' f,\n          relate_RData f abd abd' ->\n          observe p abd = observe p abd'.\n      Proof.\n        inversion 1; simpl; unfold ObservationImpl.observe; congruence.\n      Qed.\n\n      Global Instance rel_prf: CompatRel HDATAOps LDATAOps.\n      Proof.\n        constructor; intros; simpl; trivial.\n        eapply relate_incr; eauto.\n        eapply relate_kernel_mode; eauto.\n        eapply relate_observe; eauto.\n      Qed.\n\n    End Rel_Property.\n\n    (** * Proofs the one-step forward simulations for the low level specifications*)\n    Section OneStep_Forward_Relation.\n\n      (** ** The low level specifications exist*)\n      Section Exists.\n\n        Lemma pfree_exist:\n          forall habd habd' labd i f,\n            ObjPMM.pfree'_spec i habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', pfree_spec i labd = Some labd' /\\ relate_RData f habd' labd'\n                             /\\ kernel_mode labd.\n        Proof.\n          unfold pfree_spec, ObjPMM.pfree'_spec; intros until f. exist_simpl.\n        Qed.\n\n        Lemma palloc_exist:\n          forall habd habd' labd i f,\n            ObjPMM.palloc'_spec habd = Some (habd', i)\n            -> relate_RData f habd labd\n            -> exists labd', palloc_spec labd = Some (labd', i) /\\ relate_RData f habd' labd'\n                             /\\ kernel_mode labd.\n        Proof.\n          unfold palloc_spec, ObjPMM.palloc'_spec; intros until f; exist_simpl.\n        Qed.\n\n        Lemma flatmem_store_exists:\n          forall hadt ladt hadt' t addr v v' f,\n            flatmem_store hadt t addr v = Some hadt'\n            -> relate_RData f hadt ladt\n            -> val_inject f v v'\n            -> exists ladt',\n                 flatmem_store' ladt t addr v' = Some ladt'\n                 /\\ relate_RData f hadt' ladt'.\n        Proof.\n          unfold flatmem_store', flatmem_store. intros.\n          revert H. inv H0. subrewrite. subdestruct.\n          inv HQ; simpl. refine_split'; eauto.\n          constructor; trivial; simpl. \n          eapply (FlatMem.store_mapped_inj f); trivial;\n          assumption.\n        Qed.\n\n        Lemma fstore_exist:\n          forall habd habd' labd i v f,\n            fstore0_spec i v habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', fstore'_spec i v labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold fstore0_spec, fstore'_spec; intros.\n          revert H. pose proof H0 as HR.\n          inv H0. subrewrite. subdestruct. \n          eapply flatmem_store_exists; eauto.\n        Qed.\n\n        Lemma flatmem_copy_exist:\n          forall habd habd' labd i from to f,\n            flatmem_copy0_spec i from to habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', flatmem_copy'_spec i from to labd = Some labd' \n                             /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold flatmem_copy0_spec, flatmem_copy'_spec; intros.\n          revert H. pose proof H0 as HR.\n          inv H0. subrewrite. subdestruct. \n          exploit flatmem_copy_aux_exists; eauto.\n          intros (lh' & HCopy & Hinj).\n          rewrite HCopy. refine_split'; trivial.\n          inv HR.\n          inv HQ; constructor; trivial; simpl. \n        Qed.\n\n        Lemma set_at_c_exist:\n          forall habd habd' labd i z f,\n            set_at_c0_spec i z habd = Some habd'\n            -> relate_RData f habd labd\n            -> exists labd', set_at_c_spec i z labd = Some labd' /\\ relate_RData f habd' labd'.\n        Proof.\n          unfold set_at_c0_spec, set_at_c_spec; intros until f; exist_simpl; inv HR'.\n        Qed.\n\n      End Exists.\n\n      Section FRESH_PRIM.\n\n        Lemma pfree_spec_ref:\n          compatsim (crel RData RData) (gensem ObjPMM.pfree'_spec) pfree_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit pfree_exist; eauto 1.\n          intros [labd' [HP [HM Hkern]]].\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n        Lemma palloc_spec_ref:\n          compatsim (crel RData RData) (gensem ObjPMM.palloc'_spec) palloc_spec_low.\n        Proof. \n          compatsim_simpl (@match_AbData).\n          exploit palloc_exist; eauto 1.\n          intros [labd' [HP [HM Hkern]]].\n          refine_split; try econstructor; eauto. constructor.\n        Qed.\n\n      End FRESH_PRIM.\n\n      Section PASSTHROUGH_PRIM.\n\n        Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store')).\n        Proof.\n          accessor_prop_tac.\n          - eapply flatmem_store_exists; eauto.\n        Qed.          \n\n        Lemma passthrough_correct:\n          sim (crel RData RData) malt_passthrough malop.\n        Proof.\n          sim_oplus.\n          - apply fload'_sim.\n          - (* fstore *)\n            layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n            exploit fstore_exist; eauto 1; intros [labd' [HP HM]].\n            match_external_states_simpl. \n          - (* flatmem_copy *)\n            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          - apply vmxinfo_get_sim.\n          - apply device_output_sim.\n          - apply setPG0_sim.\n          - apply clearCR2_sim.\n          - apply setCR30_sim.\n          - apply get_nps_sim.\n          - apply is_at_norm_sim.\n          - apply get_at_u_sim.\n          - apply get_at_c_sim.\n          - (* set_a_c *)\n            layer_sim_simpl; compatsim_simpl (@match_AbData); intros.\n            exploit set_at_c_exist; eauto 1. intros [labd' [HP HM]].\n            match_external_states_simpl. \n          - apply mem_init_sim.\n          - apply trapin_sim.\n          - apply trapout0_sim.\n          - apply hostin_sim.\n          - apply hostout_sim.\n          - apply trap_info_get_sim.\n          - apply trap_info_ret_sim.\n          - layer_sim_simpl.\n            + eapply load_correct1.\n            + eapply store_correct1.\n        Qed.\n\n      End PASSTHROUGH_PRIM.\n\n    End OneStep_Forward_Relation.\n\n  End WITHMEM.\n\nEnd Refinement.  \n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/ALGen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.15454197135175704}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import List.\nImport ListNotations.\n(* From RecordUpdate Require Import RecordSet.\n)Import RecordSetNotations. *)\n(* Require Import PeanoNat. *)\n\nRequire Import Psatz.\n\nRequire Import WDRF.Base WDRF.Promising WDRF.DRF WDRF.SC.\n\nDefinition get_view (e : Event) : option View :=\n    match e with\n    | LOAD _ v _ => Some v\n    | ACQ v _ => Some v\n    | STORE _ v _ => Some v\n    | REL v _ => Some v\n    | _ => None\n    end.\n\n(* construct sc trace from promising trace *)\nInductive rel_global_trace : Trace -> list GlobalEvent -> Prop :=\n| GT_EMPTY : forall n lp\n                (Hempty : forall p, p <= n -> lp p = None), \n                rel_global_trace (mkTrace n lp (fun _ => [])) []\n| GT_INTERNAL : forall t gt i tid\n                    (Hgt : rel_global_trace t gt),\n                    rel_global_trace \n                        (t\n                            <|executions := update (executions t) tid (INTERNAL i :: (executions t tid)) |> \n                        )\n                        (GE tid (INTERNAL i) :: gt)\n| GT_LOAD : forall t gt addr view reg tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hlast : forall ms, rel_replay_mem (promiselen t) (promiselist t) ms -> Some (ms addr) = get_value view (promiselist t)),\n                    rel_global_trace \n                        (t\n                            <|executions := update (executions t) tid (LOAD addr view reg :: (executions t tid)) |> \n                        )\n                        (GE tid (LOAD addr view reg) :: gt)\n| GT_STORE : forall t gt addr view reg tid val\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall ms, rel_replay_mem (promiselen t) (promiselist t) ms ->\n                        rel_replay_mem (promiselen t) (update (promiselist t) view (Some (WRITE tid val addr))) \n                            (update ms addr val)    \n                    )\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace \n                        (t\n                            <|promiselist := update (promiselist t) view (Some (WRITE tid val addr)) |>\n                            <|executions := update (executions t) tid (STORE addr view reg :: (executions t tid)) |> \n                        )\n                        (GE tid (STORE addr view reg) :: gt)\n(* ACQs and RELs are ignored in the global trace *)\n| GT_ACQUIRE : forall t gt view addr tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall om n, rel_global_ownership n om (update (promiselist t) view (Some (PULL tid addr))) (fun _ => None) ->\n                        exists om', rel_global_ownership n om' (promiselist t) (fun _ => None))\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace\n                        (t\n                            <|promiselist := update (promiselist t) view (Some (PULL tid addr)) |>\n                            <|executions := update (executions t) tid (ACQ view addr :: (executions t tid)) |> \n                        )\n                        gt\n| GT_RELEASE : forall t gt view addr tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall om n, rel_global_ownership n om (update (promiselist t) view (Some (PUSH tid addr))) (fun _ => None) ->\n                        exists om', rel_global_ownership n om' (promiselist t) (fun _ => None))\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace\n                        (t\n                            <|promiselist := update (promiselist t) view (Some (PUSH tid addr)) |>\n                            <|executions := update (executions t) tid (REL view addr :: (executions t tid)) |> \n                        )\n                        gt.\n\n\n\nInductive same_result : Trace -> list GlobalEvent -> Prop :=\n| SAME_RESULT : forall t gt ms gs rs\n                    (Hpamem : rel_replay_mem (promiselen t) (promiselist t) ms)\n                    (Hpareg : forall tid, rel_replay_reg (promiselist t) (executions t tid) (rs tid))\n                    (Hsc : rel_replay_sc gt gs)\n                    (Hms : memstate gs = ms)\n                    (Hreg : forall tid, regstates gs tid = rs tid)\n                    ,\n                    same_result t gt.\n\nLemma replay_mem_exists : forall lp n, exists ms, rel_replay_mem n lp ms.\nProof.\n    intro. induction n.\n    -   esplit. constructor.\n    -   destruct IHn as (ms & Hms). destruct (lp (S n)) eqn:Hsn.\n        +   destruct p.\n            *   esplit.\n                eapply REPLAY_MEM_WRITE. apply Hms. apply Hsn.\n            *   esplit.  \n                eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\n            *   esplit.  \n                eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\n        +   esplit. eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\nQed.\n\n\nLemma replay_sc_exists : forall gt, exists gs, rel_replay_sc gt gs.\nProof.\n    intro. induction gt.\n    -   esplit. constructor.\n    -   destruct a.\n        destruct e; destruct IHgt as (gs & Hgs).\n        {\n            specialize (execute_internal_exists i (regstates gs tid)). intro. destruct H  as (rs & Hrs).\n            esplit. constructor. apply Hgs. apply Hrs.\n        }\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\nQed.\n\nLemma empty_replay_mem :\n        forall n lp\n            (Hempty : forall p : nat, p <= n -> lp p = None),\n            rel_replay_mem n lp (fun addr => 0).\nProof.\n    induction n; intros.\n    -   constructor.\n    -   apply REPLAY_MEM_OTHER. apply IHn.\n        intros. apply Hempty. lia.\n        rewrite Hempty. easy. easy.\nQed.\n\nLemma nth_error_inv :\n        forall {T} (l : list T) n a b, nth_error (a :: l) n = Some b ->\n            (n = 0 /\\ a = b) \\/ (exists n', n = S n' /\\ nth_error l n' = Some b).\nProof.\n    intros.\n    destruct n.\n    left. simpl in *. inversion H. easy.\n    right. simpl in *. exists n. split. easy.\n    assumption.\nQed.\n\n\n\nLemma localstate_promise_unused_write : \n    forall tid pl ex ls view val addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (WRITE tid' val addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma global_ownership_unused_write_aux :\n    forall n omr pl view tid val addr om\n        (Hmask : pl view = None)\n        (Hom : rel_global_ownership n om (update pl view (Some (WRITE tid val addr))) omr),\n        rel_global_ownership n om pl omr.\nProof.\n    induction n; intros.\n    -   inversion Hom. constructor.\n    -   inversion Hom.\n        +   constructor. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite <- Hlp0. rewrite update_not_same. easy.\n            intro. subst. rewrite update_same in Hlp0. discriminate.\n        +   econstructor. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite <- Hlp0. rewrite update_not_same. easy.\n            intro. subst. rewrite update_same in Hlp0. discriminate.\n        +   destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   apply GO_NONE. eapply IHn. apply Hmask. apply Hlp.\n                subst. apply Hmask.\n            *   eapply GO_WRITE. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite update_not_same in Hlp0 by easy.\n            apply Hlp0.\n        +   destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   apply GO_NONE. eapply IHn. apply Hmask. apply Hlp.\n                subst. apply Hmask.\n            *   eapply GO_NONE. eapply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same in Hlp0 by easy.\n            apply Hlp0.\nQed. \n\nLemma global_ownership_unused_write :\n    forall n pl view tid val addr om\n        (Hmask : pl view = None)\n        (Hom : rel_global_ownership n om (update pl view (Some (WRITE tid val addr))) (fun _ => None)),\n        rel_global_ownership n om pl (fun _ => None).\nProof.\n    intros. eapply global_ownership_unused_write_aux.\n    apply Hmask. apply Hom.\nQed.\n\nLemma local_ownership_unused_write :\n    forall pl ex lo view val addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (WRITE tid' val addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\n\nLemma regstate_write_unchanged :\n    forall pl ex view tid addr rs val\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (WRITE tid val addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma localstate_promise_unused_pull : \n    forall tid pl ex ls view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (PULL tid' addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma local_ownership_unused_pull :\n    forall pl ex lo view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (PULL tid' addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\nLemma memstate_pull_unchanged :\n    forall n pl view ms tid addr\n        (Hmask : pl view = None)\n        (Hms : rel_replay_mem n pl ms),\n        rel_replay_mem n (update pl view (Some (PULL tid addr))) ms.\nProof.\n    induction n; intros.\n    -   inversion Hms. constructor.\n    -   inversion Hms.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same. apply Hwrite.\n            intro. contradict Hwrite. subst. rewrite Hmask. easy.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   subst. rewrite update_same. easy.\n            *   rewrite update_not_same by easy. apply Hnotwrite.\nQed.   \n\nLemma regstate_pull_unchanged :\n    forall pl ex view tid addr rs\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (PULL tid addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma localstate_promise_unused_push : \n    forall tid pl ex ls view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (PUSH tid' addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma local_ownership_unused_push :\n    forall pl ex lo view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (PUSH tid' addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\nLemma regstate_push_unchanged :\n    forall pl ex view tid addr rs\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (PUSH tid addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma memstate_push_unchanged :\n    forall n pl view ms tid addr\n        (Hmask : pl view = None)\n        (Hms : rel_replay_mem n pl ms),\n        rel_replay_mem n (update pl view (Some (PUSH tid addr))) ms.\nProof.\n    induction n; intros.\n    -   inversion Hms. constructor.\n    -   inversion Hms.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same. apply Hwrite.\n            intro. contradict Hwrite. subst. rewrite Hmask. easy.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   subst. rewrite update_same. easy.\n            *   rewrite update_not_same by easy. apply Hnotwrite.\nQed.   \n\nTheorem same_mem :\n    forall (t : Trace) (gt : list GlobalEvent)\n        (Hsc : rel_global_trace t gt)\n        (Hvalid : valid_trace t)\n        (Hdrf : DRF t)\n        ,\n        same_result t gt.\nProof.\n    intros. induction Hsc.\n    -   (* empty *)\n        esplit; simpl in *.\n        +   apply empty_replay_mem. easy.\n        +   intro. apply REPLAY_REG_EMPTY.\n        +   apply SC_EMPTY.\n        +   simpl. reflexivity.\n        +   simpl. easy.\n    -   (* internal *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v. apply Hfulfilled in Hp.\n                    destruct Hp as (tid0 & e & n & Hp1 & Hp2 & Hp3).\n                    destruct (promiselist t v) eqn: Heqp; try easy.                \n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hp1.\n                        apply nth_error_inv in Hp1 as [|]. \n                        {   destruct H. subst.\n                            destruct p; destruct Hp2; try easy.\n                            destruct H0. easy.\n                        }\n                        {exists tid0, e.\n                            destruct H as (n0 & Hn01 & Hn02).\n                            exists n0.\n                            split. easy. split. easy.\n                            intros.\n                            destruct (Peano_dec.eq_nat_dec tid0 tid').\n                            - rewrite e0 in *.\n                                specialize Hp3 with tid' (S n') e'.\n                                rewrite update_same in Hp3. rewrite Hn01 in Hp3.\n                                split; auto.\n                                assert (S n0 = S n') by now apply Hp3.\n                                inversion H. easy.\n                            - specialize Hp3 with tid' n' e'.\n                                rewrite update_not_same in Hp3 by lia.\n                                apply Hp3  in He'; easy.\n                        }\n                    *   rewrite update_not_same in Hp1 by easy.\n                        exists tid0, e, n. split. easy.\n                        split. easy. intros.\n                        destruct (Peano_dec.eq_nat_dec tid tid').\n                        {   rewrite <- e0 in *.\n                            specialize Hp3 with tid (S n') e'.\n                            rewrite update_same in Hp3.\n                            contradict n0. symmetry. apply Hp3.\n                            simpl. easy. easy.\n                        }\n                        {   apply Hp3 with e'.\n                            rewrite update_not_same by easy. easy. easy.\n\n                        }\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hls1.\n                        inversion Hls1; exists ls; easy.\n                    *   rewrite update_not_same in Hls1 by easy.\n                        exists ls1. easy.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. apply Hglobal.\n                intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                destruct (Peano_dec.eq_nat_dec tid tid0).\n                  subst. rewrite update_same in Hlo.\n                    inversion Hlo. exists lo. easy.\n                  rewrite update_not_same in Hlo by easy.\n                    exists lo. easy.               \n        }\n        clear IHHsc. inversion IHsame.\n        destruct (execute_internal_exists i (rs tid)) as (r0 & Hr0).\n        set (rs0 := update rs tid r0).\n        replace r0 with (rs0 tid) in Hr0 by now unfold rs0; rewrite update_same.\n        esplit; simpl in *.\n        +   apply Hpamem.\n        +   intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same.\n                econstructor. apply Hpareg.\n                apply Hr0.\n            *   rewrite update_not_same by easy.\n                replace (rs0 tid0) with (rs tid0).\n                apply Hpareg. unfold rs0. rewrite update_not_same by easy.\n                reflexivity.\n        +   constructor. apply Hsc0.\n            rewrite Hreg. apply Hr0.\n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same. reflexivity.\n            *   unfold rs0.\n                rewrite update_not_same by easy.\n                rewrite update_not_same by easy.\n                apply Hreg.\n    -   (* LOAD *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            -   inversion Hvalid. constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v. apply Hfulfilled in Hp.\n                    destruct Hp as (tid0 & e & n & Hp1 & Hp2 & Hp3).\n                    destruct (promiselist t v) eqn: Heqp; try easy.                \n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hp1.\n                        apply nth_error_inv in Hp1 as [|]. \n                          destruct H. subst.\n                            destruct p; destruct Hp2; try easy.\n                            destruct H0. easy.\n                          exists tid0, e.\n                            destruct H as (n0 & Hn01 & Hn02).\n                            exists n0.\n                            split. easy. split. easy.\n                            intros.\n                            destruct (Peano_dec.eq_nat_dec tid0 tid').\n                             rewrite e0 in *.\n                                specialize Hp3 with tid' (S n') e'.\n                                rewrite update_same in Hp3. rewrite Hn01 in Hp3.\n                                split; auto.\n                                assert (S n0 = S n') by now apply Hp3.\n                                inversion H. easy.\n                             specialize Hp3 with tid' n' e'.\n                                rewrite update_not_same in Hp3 by lia.\n                                apply Hp3  in He'; easy.\n                    *   rewrite update_not_same in Hp1 by easy.\n                        exists tid0, e, n. split. easy.\n                        split. easy. intros.\n                        destruct (Peano_dec.eq_nat_dec tid tid').\n                          rewrite <- e0 in *.\n                            specialize Hp3 with tid (S n') e'.\n                            rewrite update_same in Hp3.\n                            contradict n0. symmetry. apply Hp3.\n                            simpl. easy. easy.\n                          apply Hp3 with e'.\n                            rewrite update_not_same by easy. easy. easy.  \n                +   intro. simpl in *.\n                    specialize Hconsistent with tid0. destruct Hconsistent as (ls & Hls).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hls.\n                        inversion Hls. exists ls0. easy.\n                    *   rewrite update_not_same in Hls by easy.\n                        exists ls. easy.\n            -   inversion Hdrf. simpl in *. esplit.\n                apply Hglobal.\n                intro. specialize Hlocal with tid0.\n                destruct (Peano_dec.eq_nat_dec tid tid0).\n                +   subst. rewrite update_same in Hlocal.\n                    destruct Hlocal as (lo & Hlo).\n                    inversion Hlo. exists lo. apply Hlo0.\n                +   rewrite update_not_same in Hlocal by easy.\n                    apply Hlocal.\n        }\n        clear IHHsc. inversion IHsame.\n        inversion Hvalid.\n        destruct (Hconsistent tid) as (ls & Hls). simpl in *.\n        rewrite update_same in Hls.\n        inversion Hls.\n        set (rs0 := update rs tid (update (rs tid) reg val)).\n        esplit; simpl in *.\n        +   apply Hpamem.\n        +   subst.\n            instantiate (1:= update rs tid (update (rs tid) reg val)).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. simpl in *. rewrite update_same.\n                unfold rs0. rewrite update_same.\n                constructor. assumption.\n                unfold get_value. rewrite Hpromise. easy.\n            *   unfold rs0.\n                repeat rewrite update_not_same by easy.\n                easy.\n        +   constructor. apply Hsc0.\n        +   easy.\n        +   simpl. intro.\n            destruct (Peano_dec.eq_nat_dec tid tid1).\n            *   rewrite Hreg. rewrite Hms.\n                rewrite e.\n                repeat rewrite update_same.\n                assert (ms addr = val). (* last read *)\n                {\n                    apply Hlast in Hpamem.\n                    unfold get_value in *. rewrite Hpromise in Hpamem.\n                    inversion Hpamem. reflexivity.\n                }\n                subst. easy.\n            *   subst.\n                repeat rewrite update_not_same by easy. rewrite Hreg. easy.     \n    -   (* STORE *)   \n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg0 & Hreg).\n                                inversion Hreg. contradict n. easy. easy.\n                                destruct Hp1. discriminate.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls.\n                        eapply localstate_promise_unused_write.\n                          apply Hmask.\n                          intros. eapply Hunused. apply H6.\n                          apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1.\n                        eapply localstate_promise_unused_write.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eexists. eapply global_ownership_unused_write.\n                    apply Hmask. apply H0. (* last write *)\n                +   intro. specialize Hlocal with tid0. destruct Hlocal  as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_write. apply Hmask.\n                        intros. eapply Hunused. apply H5. subst. apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo.\n                        eapply local_ownership_unused_write. apply Hmask.\n                        intros. eapply Hunused. apply H0. subst. apply Hlo.        \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply Hlast. apply Hpamem. \n        +   intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                apply REPLAY_REG_STORE. \n                eapply regstate_write_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n                unfold get_value. rewrite update_same.\n                inversion Hvalid.\n                specialize Hconsistent with tid0. destruct Hconsistent.\n                simpl in *. rewrite update_same in H0. inversion H0.\n                rewrite update_same in Hpromise. inversion Hpromise.\n                erewrite rel_promising_localstate. reflexivity.\n                apply Hls. apply regstate_write_unchanged.\n                apply Hmask. intro. apply Hunused. easy. \n            *   rewrite update_not_same by easy.\n                eapply regstate_write_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   constructor. apply Hsc0. \n        +   simpl. rewrite Hreg. rewrite Hms.\n            replace (rs tid reg) with val. easy.\n            inversion Hvalid. specialize Hconsistent with tid.\n            destruct Hconsistent. simpl in *. rewrite update_same in H2.\n            inversion H2. rewrite update_same in Hpromise. inversion Hpromise.\n            erewrite rel_promising_localstate. reflexivity.\n            apply Hls. apply regstate_write_unchanged. apply Hmask.\n            intro. eapply Hunused. easy.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\n    -   (* ACQ *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg & Hreg). discriminate.\n                                destruct Hp1. inversion H0. contradict n. easy. easy.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls. \n                        eapply localstate_promise_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H5. apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1. eapply localstate_promise_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eapply Hlast. apply H0.\n                +   intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H4.\n                        apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo. eapply local_ownership_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H0. subst. apply Hlo.             \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply memstate_pull_unchanged. apply Hmask. apply Hpamem.\n        +   instantiate (1:= rs).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                constructor.\n                apply regstate_pull_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n            *   rewrite update_not_same by easy.\n                apply regstate_pull_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   apply Hsc0. \n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\n    -   (* REL *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg & Hreg). discriminate.\n                                easy.\n                                destruct Hp1. inversion H0. contradict n. easy.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls.\n                        eapply localstate_promise_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H5. rewrite H1. apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1. eapply localstate_promise_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eapply Hlast. apply H0.\n                +   intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H4.\n                        apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo. eapply local_ownership_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H0. subst. apply Hlo.              \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply memstate_push_unchanged. apply Hmask. apply Hpamem.\n        +   instantiate (1:=rs).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                constructor.\n                apply regstate_push_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n            *   rewrite update_not_same by easy.\n                apply regstate_push_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   apply Hsc0. \n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\nQed.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RelaxedMemory/WDRF/Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767283, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.1543959711104487}}
{"text": "(** * Classification of morphisms of the Grothendieck Construction of a functor to Set *)\nRequire Import Category.Core Functor.Core.\nRequire Import Category.Morphisms.\nRequire Import SetCategory.Core.\nRequire Import Grothendieck.ToSet.Core.\nRequire Import HoTT.Basics HoTT.Types.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope morphism_scope.\n\nSection Grothendieck.\n  Context `{Funext}.\n  Context {C : PreCategory}\n          {F : Functor C set_cat}.\n\n  Definition isequiv_sigma_category_isomorphism {s d : category F}\n  : (s <~=~> d)%category <~> { e : (s.(c) <~=~> d.(c))%category | (F _1 e s.(x) = d.(x))%category }.\n  Proof.\n    simple refine (equiv_adjointify _ _ _ _).\n    { intro m.\n      simple refine (_; _).\n      { exists (m : morphism _ _ _).1.\n        exists (m^-1).1.\n        { exact (ap proj1 (@left_inverse _ _ _ m _)). }\n        { exact (ap proj1 (@right_inverse _ _ _ m _)). } }\n      { exact (m : morphism _ _ _).2. } }\n    { intro m.\n      exists (m.1 : morphism _ _ _ ; m.2).\n      eexists (m.1^-1;\n               ((ap (F _1 (m.1)^-1) m.2)^)\n                 @ (ap10 ((((composition_of F _ _ _ _ _)^)\n                             @ (ap (fun m => F _1 m) (@left_inverse _ _ _ m.1 _))\n                             @ (identity_of F _))\n                          : (F _1 (m.1 : morphism _ _ _)^-1) o F _1 m.1 = idmap) s.(x)));\n        apply path_sigma_hprop.\n      - exact left_inverse.\n      - exact right_inverse. }\n    { intro x; apply path_sigma_hprop; apply path_isomorphic.\n      reflexivity. }\n    { intro x; apply path_isomorphic; reflexivity. }\n  Defined.\nEnd Grothendieck.\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/Grothendieck/ToSet/Morphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3040416623541848, "lm_q1q2_score": 0.154395963378627}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\nRequire Import VST.floyd.sublist.\n\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.general_lemmas.\nRequire Import sha.spec_sha.\n\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_pure_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import VST.floyd.library.\n\nRequire Import hmacdrbg.verif_hmac_drbg_seed_common.\n\nModule Instantiate_eq.\n\nDefinition OptionalNonce: option (list Z) := None. (*The implementation takes nonce from entropy, using the el*3/2 calculation*)\n\n(*NIST, Section 10.1: highest supported sec strength is given by the hash function's\nsecurity strength for preimage resistance. For SHA256, this is\n(according to NIST SP 800-107, Table 1, page 11) 256 bits. See also Appendix B2 of NIST SP 800-90A. *)\nDefinition highest_supported_security_strength := 32. (* in bytes -- see comment for reseed*)\n\n(*Q: should we use the sec strength of HMAC, calculated according to Section 5.3.4 of\nNIST SP 800-107 instead?*)\nDefinition requested_security_strength:= 32.  (*same as in reseed*)\n\n\nDefinition prediction_resistance_supported:bool:=true.\n\nDefinition mbedtls_HMAC256_DRBG_instantiate_function (entropy_stream: ENTROPY.stream)\n         entropy_len pr_flag (personalization_string: list Z): ENTROPY.result DRBG_state_handle :=\n    HMAC256_DRBG_instantiate_function entropy_len entropy_len OptionalNonce\n            highest_supported_security_strength max_personalization_string_length\n            prediction_resistance_supported entropy_stream\n            requested_security_strength pr_flag personalization_string.\n\nDefinition entlen:Z := 32.\n\n\nParameter Entropy_addSuccess1: forall n m s s1 l1 s2 l2,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.success l2 s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.success (l1++l2) s2.\n\nParameter Entropy_addSuccess2: forall n m s s1 l1 s2 e,\n        ENTROPY.get_bytes n s = ENTROPY.success l1 s1 ->\n        ENTROPY.get_bytes m s1 = ENTROPY.error e s2 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s2.\n\nParameter Entropy_addError: forall n m s s1 e, ENTROPY.get_bytes n s = ENTROPY.error e s1 ->\n        ENTROPY.get_bytes (n+m) s = ENTROPY.error e s1.\n\nLemma Entropy_le n s l ss: ENTROPY.success l ss = ENTROPY.get_bytes n s ->\n  forall m, (m <= n)%nat -> exists l' s', ENTROPY.success l' s' = ENTROPY.get_bytes m s.\nProof. intros.\n  remember (ENTROPY.get_bytes m s) as d.\n  destruct d. eexists; eexists; trivial.\n  symmetry in H; symmetry in Heqd.\n  specialize (Entropy_addError _ (n-m)%nat _ _ _ Heqd).\n     rewrite le_plus_minus_r; trivial.\n  intros HH; rewrite HH in *. discriminate.\nQed.\n\nLemma Entropy_addSuccess3: forall n m s ss l,\n        ENTROPY.get_bytes n s = ENTROPY.success l ss -> (m <= n)%nat ->\n        exists l1 s1, ENTROPY.get_bytes m s = ENTROPY.success l1 s1 /\\ \n        exists l2, ENTROPY.get_bytes (n-m)%nat s1 = ENTROPY.success l2 ss /\\ l=l1++l2.\nProof. intros.\n  remember (ENTROPY.get_bytes m s). destruct r.\n+ exists l0, s0; split; trivial.\n  symmetry in Heqr.\n  remember (ENTROPY.get_bytes (n-m)%nat s0) as t.\n  destruct t; symmetry in Heqt.\n  - specialize (Entropy_addSuccess1 m (n-m)%nat s s0). rewrite Heqr, Heqt, le_plus_minus_r; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H. exists l1; split; trivial.\n  - specialize (Entropy_addSuccess2 m (n-m)%nat s s0). rewrite Heqr, Heqt, le_plus_minus_r; trivial.\n    intros X. rewrite (X _ _ _ (eq_refl _) (eq_refl _)) in H; clear X Heqr Heqt. inv H.\n+ symmetry in Heqr; exfalso. \n  specialize (Entropy_addError m (n-m)%nat s). rewrite Heqr, le_plus_minus_r; trivial.\n  intros X. rewrite (X _ _ (eq_refl _)) in H. inv H.\nQed.\n\nLemma instantiate_eq es prflag pers:\n      instantiate_function_256 es prflag pers =\n      mbedtls_HMAC256_DRBG_instantiate_function es entlen prflag pers.\nProof. unfold instantiate_function_256, mbedtls_HMAC256_DRBG_instantiate_function, \n   HMAC256_DRBG_instantiate_function, DRBG_instantiate_function, HMAC256_DRBG_instantiate_algorithm; simpl; intros.\ndestruct (Zlength pers >? max_personalization_string_length).\n+ destruct prflag; trivial.\n+ unfold entlen, get_entropy; simpl. \n  remember (ENTROPY.get_bytes 48 es) as r.\n  destruct r; symmetry in Heqr. \n  - destruct (Entropy_addSuccess3 _ 32 _ _ _ Heqr) as [l1 [s1 [E32 [l2 [E16 L]]]]]. omega.\n    simpl in E16. rewrite E32, E16; subst.\n    unfold HMAC_DRBG_instantiate_algorithm. simpl. rewrite app_assoc. destruct prflag; trivial.\n  - remember  (ENTROPY.get_bytes 32 es) as t; destruct t; symmetry in Heqt.\n    * remember (ENTROPY.get_bytes 16 s0) as w; destruct w; symmetry in Heqw.\n      ++ specialize (Entropy_addSuccess1 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr. congruence.\n      ++ specialize (Entropy_addSuccess2 _ _ _ _ _ _ _ Heqt Heqw). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\n    * specialize (Entropy_addError _ 16 _ _ _ Heqt). simpl. rewrite Heqr; intros X. inv X; destruct prflag; trivial.\nQed.\n\nLemma instantiate_reseed d s pr_flag rc ri (ZLc'256F : (Zlength d >? 256) = false):\n      mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag  d =\n      mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs initial_key initial_value rc 48 pr_flag ri) d.\nProof. rewrite <- instantiate256_reseed, instantiate_eq; trivial. Qed.\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque initial_key. Opaque initial_value.\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque list_repeat. \n\n(*specification for the expected case, in which 0<=len<=256.\n  But use mbedtls_HMAC256_DRBG_instantiate_function PROP of PRE and assume SUCCESS*)\nDefinition hmac_drbg_seed_simple_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list Z,\n        Ctx: hmac256drbgstate,\n        kv: val, Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z,\n        handle_ss: DRBG_state_handle * ENTROPY.stream\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP (len = Zlength Data /\\ 0 <= len <=256 /\\ Forall isbyteZ Data /\\\n             mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n             = ENTROPY.success (fst handle_ss) (snd handle_ss))\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvar sha._K256 kv)\n       SEP (\n         data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Tsh t_struct_mbedtls_md_info Info info;\n         da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n         K_vector kv; Stream s)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Tsh t_struct_mbedtls_md_info Info info;\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n            K_vector kv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val, malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                 match (fst Ctx, fst handle_ss) with ((M1, (M2, M3)), ((((newV, newK), newRC), newEL), newPR))\n                   => let CtxFinal := ((info, (M2, p)), (map Vint (map Int.repr newV), (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                      !!(ret_value = Int.zero) \n                      && data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                         hmac256drbg_relate (HMAC256DRBGabs newK newV newRC 32 newPR 10000) CtxFinal *\n                         Stream (snd handle_ss) \n                end).\n\nLemma body_hmac_drbg_seed_simple: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_simple_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 [HData RES]]]. destruct handle_ss as [handle ss]. simpl in RES.\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Vint (Int.repr 1), info).\n\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n  forward_if (\n     PROP (v=0)\n   LOCAL (temp _ret (Vint (Int.repr v)); temp _t'2 (Vint (Int.repr v));\n   temp _ctx (Vptr b i); temp _md_info info; temp _len (Vint (Int.repr len));\n   temp _custom data; gvar sha._K256 kv)\n   SEP ( (EX p : val, !!malloc_compatible (sizeof (Tstruct _hmac_ctx_st noattr)) p &&\n          memory_block Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          data_at Tsh (Tstruct _mbedtls_md_context_t noattr) (info,(M2,p)) (Vptr b i));\n         FRZL FR0)).\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; trivial. }\n  { subst v. clear Hv. simpl. forward. entailer!. }\n  Intros. subst v. clear Hv. Intros p. rename H into MCp. simpl in MCp.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!. (*\n  drop_LOCAL 0%nat.\n  drop_LOCAL 0%nat.*)\n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;2;5;6;7;9] FR2.\n  replace_SEP 1 (UNDER_SPEC.EMPTY p).\n  { entailer!. \n    eapply derives_trans. 2: apply UNDER_SPEC.mkEmpty.\n    rewrite data_at__memory_block. simpl. entailer!. \n  }\n  forward_call (Vptr b i, ((info,(M2,p)):mdstate), 32, initial_key, kv, b, Ptrofs.add i (Ptrofs.repr 12)).\n  { simpl. cancel. }\n  { split; trivial. red. simpl. rewrite int_max_signed_eq.\n    split. trivial. split. omega. rewrite two_power_pos_equiv.\n    replace (2^64) with 18446744073709551616. omega. reflexivity.\n    apply isbyteZ_initialKey.\n  }\n  Intros. clear H.\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Tsh, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Tsh t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n\n  forward_if\n  (PROP ( )\n   LOCAL (temp _md_size (Vint (Int.repr 32)); temp _ctx (Vptr b i); temp _md_info info;\n   temp _len (Vint (Int.repr (Zlength Data))); temp _custom data; gvar sha._K256 kv;\n   temp _t'4 (Vint (Int.repr 32)))\n   SEP (FRZL ALLSEP)).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    + elim H; trivial. \n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rewrite int_max_unsigned_eq; omega. }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;1;2;3;4] FR_CTX.\n  freeze [3;4;6;7;8] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;2;3] INI.\n  specialize (Forall_list_repeat isbyteZ 32 1); intros IB1.\n  replace_SEP 0 (\n         data_at Tsh t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V IB1. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    apply andp_right. apply prop_right. repeat split; trivial. apply IB1. split; omega.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [3;7] OLD_MD.\n  forward_call (Data, data, Zlength Data, Vptr b i, ST, myABS, kv, Info, s).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *; rewrite ptrofs_max_unsigned_eq.\n    split. omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. (*change Int.modulus with 4294967296.*) omega.\n    split. (* change Int.modulus with 4294967296.*)\n       unfold contents_with_add. if_tac. omega. rewrite Zlength_nil; omega.\n    split. apply IB1. split; omega.\n    assumption.\n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (\n   PROP ( v = nullval)\n   LOCAL (temp _ret v; temp _t'7 v;\n   temp _entropy_len (Vint (Int.repr 32));\n   temp _ctx (Vptr b i); gvar sha._K256 kv)\n   SEP (reseedPOST v Data data (Zlength Data) s\n          myABS (Vptr b i) Info kv ST; FRZL OLD_MD)).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + omega.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. omega. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite RES in HeqMRS. inv HeqMRS. \n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST. \n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. omega. }\n  rewrite <- instantiate_reseed, RES in HeqMRS; trivial. subst MRS. clear H RES Heqd. \n  destruct handle as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12;13] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  thaw ALLSEP. thaw OLD_MD. Exists p. \n  cancel;  normalize. \n  apply andp_right. solve [apply prop_right; repeat split; trivial].\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty.\nTime Qed. (*Coq8.6: 26secs*)\n\n(*Spec that does not assume len<=256 and includes a clause \n  for the case where mbedtls_HMAC256_DRBG_instantiate_function yields\n  Entropy.ERROR, ie no hypothesis about mbedtls_HMAC256_DRBG_instantiate_function in PROP of PRE*)\nDefinition hmac_drbg_seed_full_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list Z,\n        Ctx: hmac256drbgstate,\n        kv: val, Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus /\\ Forall isbyteZ Data)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvar sha._K256 kv)\n       SEP (\n         data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate dp rc pr_flag ri Ctx;\n         data_at Tsh t_struct_mbedtls_md_info Info info;\n         da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n         K_vector kv; Stream s)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Tsh t_struct_mbedtls_md_info Info info;\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n            K_vector kv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx *\n                 preseed_relate dp rc pr_flag ri Ctx * Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val, malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 (48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                       data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else match mbedtls_HMAC256_DRBG_instantiate_function s entlen pr_flag\n                                       (contents_with_add data (Zlength Data) Data)\n                        with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000 in\n                                       data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vint (map Int.repr newV), (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end).\n\nLemma body_hmac_drbg_seed_full: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_full_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as (*[PREQ*) [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]](*]*).\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Vint (Int.repr 1), info).\n\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n  deadvars!.\n  forward_if (\n     PROP (v=0)\n   LOCAL (temp _ret (Vint (Int.repr v)); temp _t'2 (Vint (Int.repr v));\n   temp _ctx (Vptr b i); temp _md_info info; temp _len (Vint (Int.repr len));\n   temp _custom data; gvar sha._K256 kv)\n   SEP ( (EX p : val, !!malloc_compatible (sizeof (Tstruct _hmac_ctx_st noattr)) p &&\n          memory_block Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          data_at Tsh (Tstruct _mbedtls_md_context_t noattr) (info,(M2,p)) (Vptr b i));\n         FRZL FR0)).\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; trivial. }\n  { subst v. clear Hv. simpl. forward. entailer!. }\n  Intros. subst v. clear Hv. Intros p. rename H into MCp. simpl in MCp.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!.\n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  assert (ZL_VV: Zlength initial_key =32) by reflexivity.\n  thaw FIELDS.\n  freeze [4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;2;5;6;7;9] FR2.\n  replace_SEP 1 (UNDER_SPEC.EMPTY p).\n  { entailer!. \n    eapply derives_trans. 2: apply UNDER_SPEC.mkEmpty.\n    rewrite data_at__memory_block. simpl. entailer!. \n  }\n  forward_call (Vptr b i, ((info,(M2,p)):mdstate), 32, initial_key, kv, b, Ptrofs.add i (Ptrofs.repr 12)).\n  { simpl. cancel. }\n  { split; trivial. red. simpl. rewrite int_max_signed_eq.\n    split. trivial. split. omega. rewrite two_power_pos_equiv.\n    replace (2^64) with 18446744073709551616. omega. reflexivity.\n    apply isbyteZ_initialKey.\n  }\n  Intros. clear H.\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Tsh, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite sepcon_comm. apply sepcon_derives.\n     - apply data_at_memory_block.\n     - cancel. }\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Tsh t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  deadvars!.\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n\n  forward_if\n  (PROP ( )\n   LOCAL (temp _md_size (Vint (Int.repr 32)); temp _ctx (Vptr b i); \n   temp _len (Vint (Int.repr (Zlength Data))); temp _custom data; gvar sha._K256 kv;\n   temp _t'4 (Vint (Int.repr 32)))\n   SEP (FRZL ALLSEP)).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    + elim H; trivial. \n    + clear H. forward. forward. entailer!. }\n  forward. simpl. deadvars!. (*drop_LOCAL 7%nat. _t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rewrite int_max_unsigned_eq; omega. }\n  set (myABS := HMAC256DRBGabs initial_key initial_value rc 48 pr_flag 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr_flag, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;1;2;3;4] FR_CTX.\n  freeze [3;4;6;7;8] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;2;3] INI.\n  specialize (Forall_list_repeat isbyteZ 32 1); intros IB1.\n  replace_SEP 0 (\n         data_at Tsh t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { entailer!. thaw INI. clear - FC_V IB1. (*KVStreamInfoDataFreeBlk.*) thaw FR_CTX.\n    apply andp_right. apply prop_right. repeat split; trivial. apply IB1. split; omega.\n    unfold_data_at 2%nat. \n    cancel. unfold md_full; simpl.\n    rewrite field_at_data_at; simpl.\n    unfold field_address. rewrite if_true; simpl; trivial.\n    cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [3;7] OLD_MD.\n  forward_call (Data, data, Zlength Data, Vptr b i, ST, myABS, kv, Info, s).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split. rep_omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. rep_omega.\n    split. (* change Int.modulus with 4294967296.*)\n       unfold contents_with_add. if_tac. rep_omega. rewrite Zlength_nil; rep_omega.\n    split. apply IB1. split; omega.\n    assumption.\n  }\n\n  Intros v.\n  assert (ZLc': Zlength (contents_with_add data (Zlength Data) Data) = 0 \\/\n                 Zlength (contents_with_add data (Zlength Data) Data) = Zlength Data).\n         { unfold contents_with_add. if_tac. right; trivial. left; trivial. }\n  forward.\n  deadvars!.\n  forward_if (\n   PROP ( v = nullval)\n   LOCAL (temp _ret v; temp _t'7 v;\n   temp _entropy_len (Vint (Int.repr 32)); temp _ctx (Vptr b i); gvar sha._K256 kv)\n   SEP (reseedPOST v Data data (Zlength Data) s\n          myABS (Vptr b i) Info kv ST; FRZL OLD_MD)).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. normalize. cancel. simpl. \n      Exists p. thaw OLD_MD. normalize.\n      apply andp_right. apply prop_right; repeat split; trivial. cancel.\n      apply hmac_interp_empty.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. Intros.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { apply Zgt_is_gt_bool_f. destruct ZLc' as [ZLc' | ZLc']; rewrite ZLc'; trivial. omega. }\n      unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - simpl. Intros. Exists p. thaw OLD_MD. cancel.\n        subst myABS. rewrite <- instantiate_reseed in HeqMRS; trivial.\n        rewrite <- HeqMRS. \n        normalize.\n        apply andp_right. apply prop_right; repeat split; trivial.\n        cancel. apply hmac_interp_empty.\n  }\n  { rename H into Hv. forward. entailer!. \n    apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv; subst v. trivial.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  unfold return_value_relate_result in H.\n  destruct MRS. Focus 2. exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  clear H.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11;12] ALLSEP.\n  forward. forward.\n  Exists Int.zero. simpl.\n  apply andp_right. apply prop_right; split; trivial.\n  symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate. simpl in *. rewrite Heqd2.\n  thaw ALLSEP. thaw OLD_MD. Exists p. cancel.\n  normalize.\n  assert (ZLc'256F: Zlength (contents_with_add data (Zlength Data) Data) >? 256 = false).\n      { destruct ZLc' as [HH | HH]; rewrite HH. reflexivity.\n        apply Zgt_is_gt_bool_f. omega. }\n  rewrite <- instantiate_reseed in HeqMRS; trivial.\n  rewrite <- HeqMRS.\n  normalize.\n  apply andp_right. apply prop_right; repeat split; trivial.\n  cancel.\n  unfold_data_at 1%nat. cancel.\n  apply hmac_interp_empty. \nTime Qed. (*Coq8.6: 32secs*)\n   (*Feb 22nd 2017: 245.406 secs (233.843u,0.203s) (successful)*)\n   (*earlier: 69.671 secs (59.578u,0.015s) (successful)*)\n\nEnd Instantiate_eq.\n\nLemma ReseedRes: forall X r v, @return_value_relate_result X r (Vint v) -> Int.eq v (Int.repr (-20864)) = false.\nProof. intros.\n  unfold return_value_relate_result in H.\n  destruct r. inv H; reflexivity.\n  destruct e; inv H; try reflexivity.\n  apply Int.eq_false. eapply ENT_GenErrAx.\nQed.\n\nDefinition preseed_relate V rc pr ri (r : hmac256drbgstate):mpred:=\n    match r with\n     (md_ctx', (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))) =>\n    md_empty md_ctx' &&\n    !! (map Vint (map Int.repr V) = V' /\\\n        Zlength V = 32 /\\\n        Forall isbyteZ V /\\\n        Vint (Int.repr rc) = reseed_counter'(* /\\\n        Vint (Int.repr entropy_len) = entropy_len'*) /\\\n        Vint (Int.repr ri) = reseed_interval' /\\\n        Val.of_bool pr = prediction_resistance')\n   end.\n\nDefinition hmac_drbg_seed_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH ctx: val, info:val, len: Z, data:val, Data: list Z,\n        Ctx: hmac256drbgstate,\n        (*CTX: hmac256drbgabs,*)\n        kv: val, Info: md_info_state, s:ENTROPY.stream, rc:Z, pr:bool, ri:Z, VV:list Z\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP ( (len = Zlength Data) /\\\n              0 <= len (*<= 336 Int.max_unsigned*) /\\\n              48 + len < Int.modulus /\\\n              0 < 48 + Zlength (contents_with_add data len Data) < Int.modulus /\\ Forall isbyteZ Data)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvar sha._K256 kv)\n       SEP (\n         data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx;\n         preseed_relate VV rc pr ri Ctx;\n         (*hmac256drbg_relate CTX Ctx;*)\n         data_at Tsh t_struct_mbedtls_md_info Info info;\n         da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n         K_vector kv; Stream s)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (data_at Tsh t_struct_mbedtls_md_info Info info;\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n            K_vector kv;\n            if Int.eq ret_value (Int.repr (-20864))\n            then data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx *\n                  (*hmac256drbg_relate CTX Ctx *) preseed_relate VV rc pr ri Ctx *\n                  Stream s\n            else md_empty (fst Ctx) *\n                 EX p:val, malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                 match (fst Ctx) with (M1, (M2, M3)) =>\n                   if (zlt 256 (Zlength Data) || (zlt 384 ((*hmac256drbgabs_entropy_len initial_state_abs*)48 + Zlength Data)))%bool\n                   then !!(ret_value = Int.repr (-5)) &&\n                     (Stream s *\n                     ( let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                       (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000)))))) in\n                       let CTXFinal:= HMAC256DRBGabs VV (list_repeat 32 1) rc 48 pr 10000 in\n                       data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                     hmac256drbg_relate CTXFinal CtxFinal))\n\n                   else let myABS := HMAC256DRBGabs VV (list_repeat 32 1) rc 48 pr 10000\n                      in match mbedtls_HMAC256_DRBG_reseed_function s myABS\n                                (contents_with_add data (Zlength Data) Data)\n                         with\n                         | ENTROPY.error e ss =>\n                            (!!(match e with\n                               | ENTROPY.generic_error => Vint ret_value = Vint (Int.repr ENT_GenErr)\n                               | ENTROPY.catastrophic_error => Vint ret_value = Vint (Int.repr (-9))\n                              end) && (Stream ss *\n                                       let CtxFinal:= ((info, (M2, p)), (list_repeat 32 (Vint Int.one), (Vint (Int.repr rc),\n                                                (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000)))))) in\n                                       let CTXFinal:= HMAC256DRBGabs VV (list_repeat 32 1) rc 48 pr 10000 in\n                                       data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                       hmac256drbg_relate CTXFinal CtxFinal))\n                        | ENTROPY.success handle ss => !!(ret_value = Int.zero) &&\n                                    match handle with ((((newV, newK), newRC), newEL), newPR) =>\n                                      let CtxFinal := ((info, (M2, p)), (map Vint (map Int.repr newV), (Vint (Int.repr newRC), (Vint (Int.repr 32), (Val.of_bool newPR, Vint (Int.repr 10000)))))) in\n                                      let CTXFinal := HMAC256DRBGabs newK newV newRC 32 newPR 10000 in\n                                    data_at Tsh t_struct_hmac256drbg_context_st CtxFinal ctx *\n                                    hmac256drbg_relate CTXFinal CtxFinal *\n                                    Stream ss end\n                        end\n                end).\n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\n\nLemma body_hmac_drbg_seed: semax_body HmacDrbgVarSpecs HmacDrbgFunSpecs\n      f_mbedtls_hmac_drbg_seed hmac_drbg_seed_spec.\nProof.\n  start_function.\n  abbreviate_semax.\n  destruct H as [HDlen1 [HDlen2 [DHlen3 [DHlen4 HData]]]].\n  rewrite data_at_isptr with (p:=ctx). Intros.\n  destruct ctx; try contradiction.\n  unfold_data_at 1%nat.\n  destruct Ctx as [MdCTX [V [RC [EL [PR RI]]]]]. simpl.\n  destruct MdCTX as [M1 [M2 M3]].\n  freeze [1;2;3;4;5] FIELDS.\n  rewrite field_at_compatible'. Intros. rename H into FC_mdx.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial. rewrite ptrofs_add_repr_0_r.\n  freeze [0;2;3;4;5;6] FR0.\n  Time forward_call ((M1,(M2,M3)), Vptr b i, Vint (Int.repr 1), info).\n  Intros v. rename H into Hv.\n  freeze [0] FR1. forward. thaw FR1.\n\n  forward_if (\n     PROP (v=0)\n   LOCAL (temp _ret (Vint (Int.repr v)); temp _t'2 (Vint (Int.repr v));\n   temp _ctx (Vptr b i); temp _md_info info; temp _len (Vint (Int.repr len));\n   temp _custom data; gvar sha._K256 kv)\n   SEP ( (EX p : val, !!malloc_compatible (sizeof (Tstruct _hmac_ctx_st noattr))p &&\n          memory_block Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n          data_at Tsh (Tstruct _mbedtls_md_context_t noattr) (info,(M2,p)) (Vptr b i));\n         FRZL FR0)).\n  { destruct Hv; try omega. rewrite if_false; trivial. clear H. subst v.\n    forward. simpl. Exists (Int.repr (-20864)).\n    rewrite Int.eq_true.\n    entailer!. thaw FR0. cancel.\n    unfold_data_at 2%nat. thaw FIELDS. cancel.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. rewrite ptrofs_add_repr_0_r; trivial. }\n  { subst v. clear Hv. simpl. forward. entailer!. }\n  Intros. subst v. clear Hv. Intros p. rename H into MCp.\n\n  (*Alloction / md_setup succeeded. Now get md_size*)\n  deadvars!. \n  forward_call tt.\n\n  (*call mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size )*)\n  thaw FR0. subst.\n  rename H1 into ZL_VV. rename H2 into isbyteZ_VV.\n  thaw FIELDS.\n  freeze [4;5;6;7] FIELDS1.\n  rewrite field_at_compatible'. Intros. rename H into FC_V.\n  rewrite field_at_data_at. unfold field_address. simpl. rewrite if_true; trivial.\n  rewrite <- ZL_VV.\n  freeze [0;2;5;6;7;9] FR2.\n  replace_SEP 1 (UNDER_SPEC.EMPTY p).\n  { entailer!. \n    eapply derives_trans. 2: apply UNDER_SPEC.mkEmpty.\n    rewrite data_at__memory_block. simpl. entailer!. \n  }\n  forward_call (Vptr b i, ((info,(M2,p)):mdstate), 32, VV, kv, b, Ptrofs.add i (Ptrofs.repr 12)).\n  { rewrite ZL_VV, ptrofs_add_repr_0_r; simpl.\n    apply prop_right; repeat split; trivial.\n  }\n  { simpl. cancel. }\n  { split; trivial. red. simpl. rewrite int_max_signed_eq, ZL_VV.\n    split. trivial. split. omega. rewrite two_power_pos_equiv. \n    change (2^64) with 18446744073709551616. omega.\n  }\n  Intros.\n\n  (*call  memset( ctx->V, 0x01, md_size )*)\n  freeze [0;1;3;4] FR3.\n  forward_call (Tsh, Vptr b (Ptrofs.add i (Ptrofs.repr 12)), 32, Int.one).\n  { rewrite ZL_VV; entailer!.\n  }\n  { rewrite sepcon_comm. apply sepcon_derives.\n      eapply derives_trans. apply data_at_memory_block.\n        rewrite ZL_VV. simpl. cancel. cancel. }\n  (*{ split. apply semax_call.writable_share_top.\n    rewrite ZL_V0, client_lemmas.int_max_unsigned_eq. omega. }*)\n\n  (*ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;*)\n  rewrite ZL_VV.\n  thaw FR3. thaw FR2. unfold md_relate. simpl.\n  replace_SEP 2 (field_at Tsh t_struct_hmac256drbg_context_st [StructField _md_ctx] (info, (M2, p)) (Vptr b i)). {\n    entailer!. rewrite field_at_data_at.\n    simpl. rewrite field_compatible_field_address by auto with field_compatible. simpl.\n    rewrite ptrofs_add_repr_0_r.\n    cancel.\n  }\n  thaw FIELDS1. forward.\n  freeze [0;4;5;6;7] FIELDS2.\n  freeze [0;1;2;3;4;5;6;7;8;9] ALLSEP.\n(*  set (ent_len := new_ent_len (Zlength V0)) in *.*)\n\n  forward_if\n  (PROP ( )\n   LOCAL (temp _md_size (Vint (Int.repr 32)); temp _ctx (Vptr b i); temp _md_info info;\n   temp _len (Vint (Int.repr (Zlength Data))); temp _custom data; gvar sha._K256 kv;\n   temp _t'4 (Vint (Int.repr 32)))\n   SEP (FRZL ALLSEP)).\n  { elim H; trivial. }\n  { clear H.\n    forward_if.\n    { elim H; trivial. }\n    { clear H. forward. forward. entailer!. }\n  }\n  forward. simpl. drop_LOCAL 7%nat. (*_t'4*)\n\n  (*NEXT INSTRUCTION:  ctx->entropy_len = entropy_len * 3 / 2*)\n  thaw ALLSEP. thaw FIELDS2. forward.\n\n  assert (FOURTYEIGHT: Int.unsigned (Int.mul (Int.repr 32) (Int.repr 3)) / 2 = 48).\n  { rewrite mul_repr. simpl.\n    rewrite Int.unsigned_repr. reflexivity. rewrite int_max_unsigned_eq; omega. }\n\n  set (myABS := HMAC256DRBGabs VV (list_repeat 32 1) rc 48 pr 10000) in *.\n  assert (myST: exists ST:hmac256drbgstate, ST =\n    ((info, (M2, p)), (map Vint (list_repeat 32 Int.one), (Vint (Int.repr rc),\n        (Vint (Int.repr 48), (Val.of_bool pr, Vint (Int.repr 10000))))))). eexists; reflexivity.\n  destruct myST as [ST HST].\n\n  freeze [0;1;2;3;4] FR_CTX.\n  freeze [3;4;6;7;8] KVStreamInfoDataFreeBlk.\n\n  (*NEXT INSTRUCTION: mbedtls_hmac_drbg_reseed( ctx, custom, len ) *)\n  freeze [1;2;3] INI.\n  specialize (Forall_list_repeat isbyteZ 32 1); intros IB1.\n  replace_SEP 0 (\n         data_at Tsh t_struct_hmac256drbg_context_st ST (Vptr b i) *\n         hmac256drbg_relate myABS ST).\n  { go_lower. thaw INI. clear KVStreamInfoDataFreeBlk. thaw FR_CTX.\n    unfold_data_at 2%nat.\n    subst ST; simpl. cancel. normalize.\n    apply andp_right. apply prop_right. repeat split; trivial. apply IB1. split; omega.\n    unfold md_full. simpl.\n    rewrite field_at_data_at. simpl.\n    unfold field_address. rewrite if_true; simpl; trivial. cancel.\n    apply UNDER_SPEC.REP_FULL.\n  }\n\n  clear INI.\n  thaw KVStreamInfoDataFreeBlk. freeze [3;7] OLD_MD.\n  forward_call (Data, data, Zlength Data, Vptr b i, ST, myABS, kv, Info, s).\n  { unfold hmac256drbgstate_md_info_pointer.\n    subst ST; simpl. cancel.\n  }\n  { subst myABS; simpl. rewrite <- initialize.max_unsigned_modulus in *.\n    split. rep_omega. (* rewrite int_max_unsigned_eq; omega.*)\n    split. reflexivity.\n    split. reflexivity.\n    split. omega.\n    split. (*change Int.modulus with 4294967296.*) rep_omega.\n    split. (* change Int.modulus with 4294967296.*)\n       unfold contents_with_add. if_tac. rep_omega. rewrite Zlength_nil; rep_omega.\n    split. apply IB1. split; omega.\n    assumption.\n  }\n\n  Intros v.\n\n  forward.\n  forward_if (\n   PROP ( v = nullval)\n   LOCAL (temp _ret v; temp _t'7 v;\n   temp _entropy_len (Vint (Int.repr 32));\n   temp _md_size (Vint (Int.repr 32)); temp _ctx (Vptr b i);\n   temp _md_info info;\n   temp _len (Vint (Int.repr (Zlength Data)));\n   temp _custom data; gvar sha._K256 kv)\n   SEP (reseedPOST v Data data (Zlength Data) s\n          myABS (Vptr b i) Info kv ST; FRZL OLD_MD)).\n  { rename H into Hv. forward. simpl. Exists v.\n    apply andp_right. apply prop_right; split; trivial.\n    unfold reseedPOST.\n\n    remember ((zlt 256 (Zlength Data) || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data)) %bool) as d.\n    unfold myABS in Heqd; simpl in Heqd.\n    destruct (zlt 256 (Zlength Data)); simpl in Heqd.\n    + subst d. unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl.\n      simpl. subst myABS. normalize. simpl. cancel.\n      Exists p. thaw OLD_MD. normalize.\n      apply andp_right. apply prop_right; repeat split; trivial. cancel.\n    + destruct (zlt 384 (48 + Zlength Data)); simpl in Heqd; try omega.\n      subst d.\n      unfold hmac256drbgstate_md_info_pointer, hmac256drbg_relate; simpl. normalize.\n      rename H into RV.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n      rewrite (ReseedRes _ _ _ RV). cancel.\n      unfold return_value_relate_result in RV.\n      destruct MRS.\n      - exfalso. inv RV. simpl in Hv. discriminate.\n      - unfold hmac256drbgabs_common_mpreds, hmac256drbgstate_md_info_pointer; simpl. normalize.\n        Exists p. thaw OLD_MD. cancel. normalize.\n        apply andp_right. apply prop_right; repeat split; trivial.\n        cancel.\n  }\n  { rename H into Hv. forward.\n    go_lower. simpl in Hv. apply typed_false_of_bool in Hv. apply negb_false_iff in Hv.\n    symmetry in Hv; apply binop_lemmas2.int_eq_true in Hv. subst v.\n    entailer!.\n  }\n  deadvars!. Intros. subst v.\n  unfold reseedPOST.\n  remember ((zlt 256 (Zlength Data)\n          || zlt 384 (hmac256drbgabs_entropy_len myABS + Zlength Data))%bool) as d.\n  destruct d; Intros.\n  remember (mbedtls_HMAC256_DRBG_reseed_function s myABS\n         (contents_with_add data (Zlength Data) Data)) as MRS.\n  unfold return_value_relate_result in H.\n  destruct MRS. Focus 2. exfalso. destruct e. inv H.\n                     destruct ENT_GenErrAx as [EL1 _]. rewrite <- H in EL1. elim EL1; trivial.\n  clear H. unfold hmac256drbgabs_reseed. rewrite <- HeqMRS. subst myABS; simpl.\n  destruct d as [[[[newV newK] newRC] dd] newPR].\n  unfold hmac256drbgabs_common_mpreds. simpl. subst ST. unfold hmac256drbgstate_md_info_pointer. simpl. Intros.\n  unfold_data_at 1%nat. freeze [0;1;2;4;5;6;7;8;9;10;11] XX.\n  forward. forward. \n  Exists Int.zero. simpl. symmetry in Heqd. apply orb_false_iff in Heqd. destruct Heqd as [Heqd1 Heqd2].\n  destruct (zlt 256 (Zlength Data)); try discriminate.\n  apply andp_right. apply prop_right; split; trivial. \n  thaw XX. thaw OLD_MD. cancel. simpl in *. rewrite Heqd2, <- HeqMRS.\n  Exists p. normalize. \n  apply andp_right. apply prop_right; repeat split; trivial.\n  unfold_data_at 3%nat. cancel.\nTime Qed. (*Coq8.6: 40secs*)\n          (*Jan 22nd 2017: 267.171 secs (182.812u,0.015s) (successful)*)\n          (*earlier: Finished transaction in 121.296 secs (70.921u,0.062s) (successful)*)\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/hmacdrbg/verif_hmac_drbg_NISTseed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3040416623541847, "lm_q1q2_score": 0.15439596337862696}}
{"text": "From Goose.github_com.tchajed.goose.internal.examples Require Import append_log.\nFrom Perennial.goose_lang.lib Require Import encoding crash_lock.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.program_proof Require Import append_log_hocap.\nFrom Perennial.program_proof Require Import append_log_refinement_triples.\nFrom Perennial.goose_lang.ffi Require Import append_log_ffi.\nFrom Perennial.goose_lang Require Import logical_reln_defns logical_reln_adeq spec_assert.\nFrom Perennial.base_logic Require Import ghost_var.\n\nExisting Instances log_spec_ext log_spec_ffi_model log_spec_ext_semantics log_spec_ffi_interp log_spec_interp_adequacy.\n\nSection refinement.\nContext `{!heapGS \u03a3}.\nContext `{!refinement_heapG \u03a3}.\nContext `{stagedG \u03a3}.\n\nExisting Instance logG0.\nContext `{Hin: inG \u03a3 (authR (optionUR (exclR log_stateO)))}.\nContext `{Hin_nat_ctx: inG \u03a3 (authR (optionUR (exclR (leibnizO (nat * (spec_lang.(language.expr) \u2192\n                                                                       spec_lang.(language.expr)))))))}.\nContext (SIZE: nat).\nContext (SIZE_nonzero: 0 < SIZE).\nContext (SIZE_bounds: int.nat SIZE = SIZE).\n\nExisting Instances spec_ffi_model_field spec_ffi_op_field spec_ext_semantics_field (* spec_ffi_interp_field  *) spec_ffi_interp_adequacy_field.\n\nNotation sstate := (@state (@spec_ffi_op_field log_spec_ext) (spec_ffi_model_field)).\nNotation sexpr := (@expr (@spec_ffi_op_field log_spec_ext)).\nNotation sval := (@val (@spec_ffi_op_field log_spec_ext)).\n\nClass appendG (\u03a3: gFunctors) :=\n  { append_stagedG :> stagedG \u03a3;\n    append_stateG :> inG \u03a3 (authR (optionUR (exclR log_stateO)));\n    append_nat_ctx :> inG \u03a3 (authR (optionUR (exclR (leibnizO (nat * (spec_lang.(language.expr) \u2192\n                                                                       spec_lang.(language.expr)))))))\n  }.\n\nDefinition append_names := unit.\nDefinition append_get_names (\u03a3: gFunctors) (hG: appendG \u03a3) := tt.\nDefinition append_update (\u03a3: gFunctors) (hG: appendG \u03a3) (n: append_names) := hG.\n\nDefinition LVL_INIT : nat := 100.\nDefinition LVL_INV : nat := 75.\nDefinition LVL_OPS : nat := 50.\nExisting Instance logG0.\n\nDefinition append_inv {\u03a3: gFunctors} {hG: heapGS \u03a3} {rG: refinement_heapG \u03a3} {cG: crashGS \u03a3} {aG : appendG \u03a3} :=\n  (\u2203 \u03b3, log_inv SIZE \u03b3 LVL_INV%nat)%I.\nDefinition append_init {\u03a3: gFunctors} {hG: heapGS \u03a3} {rG: refinement_heapG \u03a3} {cG: crashGS \u03a3} {aG : appendG \u03a3}\n  : iProp \u03a3 := (\u2203 \u03b3, log_init (P \u03b3) SIZE).\nDefinition append_crash_cond {\u03a3: gFunctors} {hG: heapGS \u03a3} {rG: refinement_heapG \u03a3} {cG: crashGS \u03a3} {aG : appendG \u03a3}\n  : iProp \u03a3 := (\u2203 \u03b3, log_crash_cond (P \u03b3) SIZE).\nDefinition appendN : coPset := (\u2205 : coPset).\nDefinition append_val_interp {\u03a3: gFunctors} {hG: heapGS \u03a3} {rG: refinement_heapG \u03a3} {cG: crashGS \u03a3} {aG : appendG \u03a3}\n           (ty: @ext_tys (@val_tys _ log_ty)) : val_semTy :=\n  \u03bb vspec vimpl, (\u2203 (lspec: loc) (limpl: loc) \u03b3,\n            \u231c vspec = #lspec \u2227 vimpl = #limpl \u231d \u2217 is_log SIZE \u03b3 LVL_INV limpl \u2217 log_open lspec)%I.\n\nInstance appendTy_model : specTy_model log_ty.\nProof using SIZE.\n refine\n  {| styG := appendG;\n     sty_names := append_names;\n     sty_get_names := append_get_names;\n     sty_update := append_update;\n     sty_inv := @append_inv;\n     sty_init := @append_init;\n     sty_crash_cond := @append_crash_cond;\n     styN := appendN;\n     sty_lvl_init := LVL (LVL_INIT);\n     sty_lvl_ops := LVL (LVL_OPS);\n     sty_val_interp := @append_val_interp |}.\n - intros ? [] [] => //=.\n - intros ? [] => //=.\n - intros ?? [] [] => //=.\n - rewrite /sN/appendN. apply disjoint_empty_r.\n - abstract (intros; iIntros \"H\"; iDestruct \"H\" as (??? (->&->)) \"H\" => //=).\nDefined.\n(* XXX: some of the fields should be opaque/abstract here, because they're enormous proof terms.\n  perhaps specTy_model should be split into two typeclasses? *)\n\nExisting Instances subG_stagedG.\n\nDefinition append\u03a3 := #[staged\u03a3;\n                          GFunctor (authR (optionUR (exclR log_stateO)));\n                          GFunctor ((authR (optionUR (exclR (leibnizO (nat * (spec_lang.(language.expr) \u2192\n                                                                       spec_lang.(language.expr))))))))].\n\nInstance subG_appendG: \u2200 \u03a3, subG append\u03a3 \u03a3 \u2192 appendG \u03a3.\nProof. solve_inG. Qed.\nDefinition append_initP (\u03c3impl: @state disk_op disk_model) (\u03c3spec : @state log_op log_model) : Prop :=\n  (null_non_alloc \u03c3spec.(heap)) \u2227\n  (\u03c3impl.(world) = init_disk \u2205 SIZE) \u2227\n  (\u03c3spec.(world) = UnInit).\nDefinition append_update_pre (\u03a3: gFunctors) (hG: appendG \u03a3) (n: append_names) : appendG \u03a3 := hG.\n\nProgram Instance appendTy_update_model : specTy_update appendTy_model :=\n  {| sty_preG := appendG;\n            sty\u03a3 := append\u03a3;\n            subG_styPreG := subG_appendG;\n            sty_update_pre := @append_update_pre |}.\nNext Obligation. rewrite //=. Qed.\nNext Obligation. rewrite //=. intros ?? [] => //=. Qed.\n\nNotation append_nat_K :=\n(leibnizO (nat * ((@spec_lang log_spec_ext log_spec_ffi_model log_spec_ext_semantics).(language.expr)\n                           \u2192 (@spec_lang log_spec_ext log_spec_ffi_model log_spec_ext_semantics).(language.expr)))).\n\nLemma append_init_obligation1: sty_init_obligation1 appendTy_update_model append_initP.\nProof.\n  rewrite /sty_init_obligation1//=.\n  iIntros (? hG hRG hC hAppend \u03c3s \u03c3i Hinit) \"Hdisk\".\n  rewrite /log_start /append_init/log_init.\n  inversion Hinit as [Hnn [Heqi Heqs]]. rewrite Heqs Heqi.\n  iIntros \"(Huninit_frag&Hlog_frag)\". rewrite /P//=.\n  rewrite /thread_tok_full.\n  iMod (ghost_var_alloc ((O, id) : append_nat_K)) as (\u03b3) \"Hown\".\n  iModIntro. iExists tt, \u03b3. iLeft. iFrame.\n  rewrite /append_log_proof.uninit_log.\n  iExists _.\n  iSplitL \"Hdisk\".\n  - by iApply disk_array_init_disk.\n  - rewrite replicate_length //=.\nQed.\n\nLemma append_init_obligation2: sty_init_obligation2 append_initP.\nProof. intros ?? (?&?&?). rewrite //=. Qed.\n\nDefinition append_op_trans (op: log_spec_ext.(@spec_ffi_op_field).(@external)) : @val disk_op :=\n  match op with\n  | AppendOp => Log__Append\n  | GetOp => Log__Get\n  | ResetOp => Log__Reset\n  | InitOp => (\u03bb:<>, Init #SIZE)%V\n  | OpenOp => Open\n  end.\n\nInductive append_trans : @val log_op -> @val disk_op -> Prop :=\n| AppendTrans (x: string) op:\n    append_trans (\u03bb: x, ExternalOp op (Var x)) (append_op_trans op).\n\n\nLemma append_rules_obligation:\n  @sty_rules_obligation _ _ disk_semantics _ _ _ _ _ _ appendTy_model append_trans.\nProof.\n  intros vs0 vs v0 v0' t1 t2 Htype0 Htrans.\n  inversion Htype0 as [op Heq Htype]; subst.\n  destruct op; inversion Htype; inversion Htrans; subst.\n  - admit.\n  - admit.\n  - iIntros (?????) \"#Hinv #Hspec #Hval\".\n    iIntros (j K Hctx).\n    rewrite //=.\n    iIntros \"Hj\".\n    rewrite /append_val_interp. iDestruct \"Hval\" as (lspec limpl \u03b3 Heq) \"(His_log&Hlog_open)\".\n    destruct Heq as (->&->). iDestruct \"Hinv\" as (?) \"Hinv\".\n    iMod (ghost_step_lifting_puredet with \"[Hj]\") as \"(Hj&_)\"; swap 1 3.\n    { iFrame. iDestruct \"Hspec\" as \"($&?)\".\n    }\n    { set_solver+. }\n    { intros ?. eexists. simpl.\n      apply head_prim_step. econstructor; eauto. }\n    rewrite /LVL_OPS.\n    wpc_apply (@wpc_Log__Reset with \"[$] []\").\n    { eauto. }\n    { rewrite /LVL_INV. lia. }\n    iSplit; first done. iNext. iIntros. iExists _. eauto.\n  - inversion Htype; subst.\n    iIntros (?????) \"#Hinv #Hspec #Hval\".\n    iIntros (j K Hctx).\n    rewrite //=.\n    iIntros \"Hj\".\n    rewrite /append_val_interp.\n    iDestruct \"Hval\" as %[-> ->]. iDestruct \"Hinv\" as (?) \"Hinv\".\n    wpc_pures; first done.\n    iMod (ghost_step_lifting_puredet with \"[Hj]\") as \"(Hj&_)\"; swap 1 3.\n    { iFrame. iDestruct \"Hspec\" as \"($&?)\".\n    }\n    { set_solver+. }\n    { intros ?. eexists. simpl.\n      apply head_prim_step. econstructor; eauto. }\n    wpc_apply (@wpc_Init with \"[$] []\").\n    { eauto. }\n    { eauto. }\n    { rewrite /LVL_INV. lia. }\n    iSplit; first done. iNext. iIntros (?) \"(#His_log&Hj)\".\n    iDestruct \"Hj\" as (?) \"(Hj&Hopen)\".\n    iExists _. iFrame.\n    iExists _, _, _, _. iSplit.\n    { iPureIntro; split; eauto. }\n    iSplitR \"\"; eauto.\n    iExists _, _, _. eauto.\n  - inversion Htype; subst.\n    iIntros (?????) \"#Hinv #Hspec #Hval\".\n    iIntros (j K Hctx).\n    rewrite //=.\n    iIntros \"Hj\".\n    rewrite /append_val_interp.\n    iDestruct \"Hval\" as %[-> ->]. iDestruct \"Hinv\" as (?) \"Hinv\".\n    iMod (ghost_step_lifting_puredet with \"[Hj]\") as \"(Hj&_)\"; swap 1 3.\n    { iFrame. iDestruct \"Hspec\" as \"($&?)\".\n    }\n    { set_solver+. }\n    { intros ?. eexists. simpl.\n      apply head_prim_step. econstructor; eauto. }\n    wpc_apply (@wpc_Open with \"[$] []\").\n    { eauto. }\n    { rewrite /LVL_INV. lia. }\n    iSplit; first done. iNext. iIntros (?) \"(#His_log&Hj)\".\n    iDestruct \"Hj\" as (?) \"(Hj&Hopen)\".\n    iExists _. iFrame.\n    iExists _, _, _. iSplit.\n    { iPureIntro; split; eauto. }\n    iFrame. iFrame \"#\".\nAdmitted.\n\nLemma append_crash_inv_obligation:\n  @sty_crash_inv_obligation _ _ disk_semantics _ _ _ _ _ _ appendTy_model.\nProof using SIZE.\n  clear SIZE_bounds SIZE_nonzero.\n  rewrite /sty_crash_inv_obligation//=.\n  iIntros (? hG hC hRG hAppend e \u03a6) \"Hinit Hspec Hwand\".\n  rewrite /append_inv/append_init/log_inv.\n  iDestruct (\"Hinit\") as (\u03b3) \"Hinit\".\n  rewrite /append_crash_cond.\n  iPoseProof (append_log_na_crash_inv_obligation Nlog _ POpened (PStartedOpening _)\n                                                 _ _ _ _ _ _ LVL_INIT\n                                                 LVL_INV LVL_OPS with \"Hinit [Hwand]\") as \">(Hinv&Hwp)\".\n  { rewrite /LVL_INIT/LVL_INV. lia. }\n  { rewrite /LVL_INIT/LVL_OPS. lia. }\n  { iIntros \"Hinv\". iApply \"Hwand\". iExists _. eauto. }\n  iModIntro. iSplitL \"Hinv\".\n  { iExists _. iApply \"Hinv\". }\n  iApply (wpc_mono with \"Hwp\"); eauto.\n  iIntros \"(_&H)\". iExists _. iFrame.\nQed.\n\nLemma append_crash_obligation:\n  @sty_crash_obligation _ _ disk_semantics _ _ _ _ _ _ appendTy_model.\nProof using SIZE.\n  clear SIZE_bounds.\n  rewrite /sty_crash_obligation//=.\n  iIntros (? hG hC hRG hAppend) \"Hinv Hcrash_cond\".\n  iMod (ghost_var_alloc ((O, id) : append_nat_K)) as (\u03b3tok) \"Hown\".\n  iDestruct \"Hinv\" as (\u03b31) \"#Hlog_inv\".\n  rewrite /append_crash_cond.\n  iDestruct \"Hcrash_cond\" as (\u03b32 ls) \"(Hstate_to_crash&HP)\".\n  rewrite/ log_state_to_crash.\n  iModIntro. iNext. iIntros (hG').\n  iModIntro. iIntros (hC' \u03c3s Hrel).\n  destruct Hrel as (?&?&_&Heq&_).\n  iIntros \"Hctx\".\n  rewrite /append_init/log_init.\n  destruct (\u03c3s.(world)) eqn:Hworld_case; try iDestruct \"Hctx\" as %[].\n  - iAssert (\u231c ls = UnInit \u2228 ls = Initing \u231d \u2217 log_ctx UnInit \u2217 log_frag [])%I with \"[HP Hctx]\" as (Heqls) \"(Hctx&Hfrag)\".\n    {\n      rewrite /log_ctx/P.\n      iDestruct \"Hctx\" as \"(?&?)\".\n      destruct ls; try (iDestruct \"HP\" as \"(?&?&?)\" || iDestruct \"HP\" as \"(?&?)\");\n        try (iFrame; eauto; done).\n      - iDestruct (log_uninit_auth_closed_frag with \"[$] [$]\") as %[].\n      - iDestruct (log_uninit_auth_closed_frag with \"[$] [$]\") as %[].\n      - iDestruct \"HP\" as (?) \"(HP&?)\".\n        iDestruct (log_uninit_auth_opened with \"[$] [$]\") as %[].\n    }\n    iExists _. unshelve (iExists _).\n    { econstructor.\n      { symmetry; eauto. }\n      repeat econstructor.\n    }\n    iFrame. iIntros (hRG' (Heq1&Heq2)) \"Hrestart\".\n    iModIntro.\n    iExists tt, \u03b3tok. iLeft.\n    rewrite /logG0//=/log_frag//=. rewrite Heq2. rewrite Heq1.\n    iFrame. subst.\n    rewrite /append_log_proof.uninit_log.\n    rewrite /disk_array. rewrite /diskG0.\n    rewrite Heq.\n    destruct Heqls as [-> | ->]; iFrame.\n  - rewrite /P/log_ctx.\n    iAssert (\u231c ls = Closed s \u2228 ls = Opening s  \u231d \u2217\n             log_ctx (Closed s) \u2217 log_frag s)%I with \"[HP Hctx]\" as (Heqls) \"(Hctx&Hfrag)\".\n    {\n      rewrite /log_ctx/P.\n      iDestruct \"Hctx\" as \"(?&?)\".\n      destruct ls; try (iDestruct \"HP\" as \"(?&?&?)\" || iDestruct \"HP\" as \"(?&?)\");\n        try (iFrame; eauto; done).\n      - iDestruct (log_closed_auth_uninit_frag with \"[$] [$]\") as %[].\n      - iDestruct (log_closed_auth_uninit_frag with \"[$] [$]\") as %[].\n      - iDestruct (log_auth_frag_unif with \"[$] [$]\") as %->. iFrame. eauto.\n      - iDestruct (log_auth_frag_unif with \"[$] [$]\") as %->. iFrame. eauto.\n      - iDestruct \"HP\" as (?) \"(HP&?)\".\n        iDestruct (log_closed_auth_opened with \"[$] [$]\") as %[].\n    }\n    iExists _. unshelve (iExists _).\n    { econstructor.\n      { symmetry; eauto. }\n      simpl.\n      repeat econstructor.\n    }\n    iFrame. iIntros (hRG' (Heq1&Heq2)) \"Hrestart\".\n    iModIntro.\n    iExists tt, \u03b3tok. iRight.\n    rewrite /logG0//=/log_frag//=. rewrite Heq2. rewrite Heq1.\n    iFrame. subst.\n    rewrite /append_log_proof.uninit_log.\n    rewrite /disk_array. rewrite /diskG0.\n    destruct Heqls as [-> | ->];\n      iExists _; iFrame;\n      iFrame; subst;\n      (* XXX: need a typeclass? or lemma? to say that these kinds of\n         disk assertions are \"stable\" when we go from hG to hG' because\n         disk ffi generation number doesn't change *)\n      rewrite /append_log_proof.uninit_log;\n      rewrite /append_log_proof.crashed_log;\n      rewrite /append_log_proof.is_log';\n      rewrite /append_log_proof.is_hdr;\n      rewrite /disk_array; rewrite /diskG0;\n      rewrite Heq;\n      iFrame.\n  - rewrite /P/log_ctx.\n    iAssert (\u2203 l0, \u231c ls = Opened s l0  \u231d \u2217 log_ctx (Opened s l) \u2217 log_frag s)%I with \"[HP Hctx]\" as (? Heqls) \"(Hctx&Hfrag)\".\n    {\n      rewrite /log_ctx/P.\n      iDestruct \"Hctx\" as \"(?&?)\".\n      destruct ls; try (iDestruct \"HP\" as \"(?&?&?)\" || iDestruct \"HP\" as \"(?&?)\");\n        try (iFrame; eauto; done).\n      - iDestruct (log_uninit_auth_opened with \"[$] [$]\") as %[].\n      - iDestruct (log_uninit_auth_opened with \"[$] [$]\") as %[].\n      - iDestruct (log_closed_auth_opened with \"[$] [$]\") as %[].\n      - iDestruct (log_closed_auth_opened with \"[$] [$]\") as %[].\n      - iDestruct \"HP\" as (?) \"(HP&?)\".\n        iDestruct (log_auth_frag_unif with \"[$] [$]\") as %->.\n        iDestruct (log_open_unif with \"[$] [$]\") as %->. iFrame.\n        iExists _. iFrame; eauto.\n    }\n    iExists _. unshelve (iExists _).\n    { econstructor.\n      { symmetry; eauto. }\n      simpl.\n      repeat econstructor.\n    }\n    iFrame. iIntros (hRG' (Heq1&Heq2)) \"Hrestart\".\n    iModIntro.\n    iExists tt, \u03b3tok. iRight.\n    rewrite /logG0//=/log_frag//=. rewrite Heq2. rewrite Heq1.\n    iFrame. subst.\n    rewrite /append_log_proof.uninit_log.\n    rewrite /disk_array. rewrite /diskG0.\n      iExists _; iFrame;\n      iFrame; subst;\n      (* XXX: need a typeclass? or lemma? to say that these kinds of\n         disk assertions are \"stable\" when we go from hG to hG' because\n         disk ffi generation number doesn't change *)\n      rewrite /append_log_proof.uninit_log;\n      rewrite /append_log_proof.crashed_log;\n      rewrite /append_log_proof.is_log';\n      rewrite /append_log_proof.is_hdr;\n      rewrite /disk_array; rewrite /diskG0;\n      rewrite Heq;\n      iFrame.\nQed.\n\nExisting Instances log_semantics.\nExisting Instances spec_ffi_model_field spec_ffi_op_field spec_ext_semantics_field spec_ffi_interp_field spec_ffi_interp_adequacy_field.\n(* XXX: might need to change typed_translate / refinement to use the spec_ wrappers around type classes *)\n\nLemma append_refinement (es: @expr log_op) \u03c3s e \u03c3 (\u03c4: @ty log_ty.(@val_tys log_op)):\n  typed_translate.expr_transTy _ _ _ append_trans \u2205 es e \u03c4 \u2192\n  \u03c3.(trace) = \u03c3s.(trace) \u2192\n  \u03c3.(oracle) = \u03c3s.(oracle) \u2192\n  append_initP \u03c3 \u03c3s \u2192\n  refinement.trace_refines e e \u03c3 es es \u03c3s.\nProof.\n  intros. intros ?.\n  efeed pose proof sty_adequacy; eauto using append_init_obligation1, append_init_obligation2,\n                                 append_crash_inv_obligation, append_crash_obligation,\n                                 append_rules_obligation.\nQed.\n\nEnd refinement.\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/append_log_refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.154285882948089}}
{"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.\nRequire Import symbolic.symbolic sealing.classes.\n\nImport Symbolic.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Sym.\n\nSection WithClasses.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {opss : machine_ops_spec ops}\n        {scr : syscall_regs mt}\n        {ssa : @sealing_syscall_addrs mt}.\n\nOpen Scope ord_scope.\n\nClass sealing_key := {\n  key : ordType;\n  max_key;\n  inc_key : key -> key;\n  ltb_inc : forall sk, sk < max_key -> sk < inc_key sk\n}.\n\nContext {sk : sealing_key}.\n\n(* We represent keys as tags on dummy values instead of payloads\n  because this eliminates conversions from keys to words and back. *)\nInductive stag :=\n| DATA   :        stag\n| KEY    : key -> stag\n| SEALED : key -> stag.\n\nDefinition stag_eq t1 t2 :=\n  match t1, t2 with\n    | DATA, DATA => true\n    | KEY k1, KEY k2\n    | SEALED k1, SEALED k2 => k1 == k2\n    | _, _ => false\n  end.\n\nLemma stag_eqP : Equality.axiom stag_eq.\nProof.\nby move=> [|k1|k1] [|k2|k2] /=; apply: (iffP idP) => // [/eqP->|[->]].\nQed.\n\nDefinition stag_eqMixin := EqMixin stag_eqP.\nCanonical stag_eqType := Eval hnf in EqType stag stag_eqMixin.\n\nDefinition stags := {|\n  pc_tag_type := [eqType of unit];\n  reg_tag_type := [eqType of stag];\n  mem_tag_type := [eqType of stag];\n  entry_tag_type := [eqType of unit]\n|}.\n\nSection WithHSeqs.\n\nDefinition sealing_handler (iv : ivec stags) : option (vovec stags (op iv)) :=\n  match iv with\n  | IVec (OP NOP)       tt DATA [hseq]               => Some (@OVec stags NOP tt tt)\n  | IVec (OP CONST)     tt DATA [hseq _]             => Some (@OVec stags CONST tt DATA)\n  | IVec (OP MOV)       tt DATA [hseq tsrc; _]       => Some (@OVec stags MOV tt tsrc)\n  | IVec (OP (BINOP o)) tt DATA [hseq DATA; DATA; _] => Some (@OVec stags (BINOP o) tt DATA)\n  | IVec (OP LOAD)      tt DATA [hseq DATA; tmem; _] => Some (@OVec stags LOAD tt tmem)\n  | IVec (OP STORE)     tt DATA [hseq DATA; tsrc; _] => Some (@OVec stags STORE tt tsrc)\n  | IVec (OP JUMP)      tt DATA [hseq DATA]          => Some (@OVec stags JUMP tt tt)\n  | IVec (OP BNZ)       tt DATA [hseq DATA]          => Some (@OVec stags BNZ tt tt)\n  | IVec (OP JAL)       tt DATA [hseq DATA; _]       => Some (@OVec stags JAL tt DATA)\n  | IVec SERVICE        tt _    [hseq]               => Some tt\n  | IVec _              tt _ _                       => None\n  end.\n\nEnd WithHSeqs.\n\nProgram Instance sym_sealing : params := {\n  ttypes := stags;\n\n  transfer := sealing_handler;\n\n  internal_state := key  (* next key to generate *)\n}.\n\nImport DoNotation.\n\nDefinition mkkey (s : state mt) : option (state mt) :=\n  let 'State mem reg pc@pct key := s in\n  if key < max_key then\n    let key' := inc_key key in\n    do! reg' <- updm reg syscall_ret 0%w@(KEY key);\n    do! ret  <- reg ra;\n    match ret with\n    | pc'@DATA => Some (State mem reg' (pc'@tt) key')\n    | _ => None\n    end\n  else\n    None.\n\nDefinition seal (s : state mt) : option (state mt) :=\n  let 'State mem reg pc@pct next_key := s in\n  match reg syscall_arg1, reg syscall_arg2 with\n  | Some payload@DATA, Some _@(KEY key) =>\n    do! reg' <- updm reg syscall_ret payload@(SEALED key);\n    do! ret  <- reg ra;\n    match ret with\n    | pc'@DATA => Some (State mem reg' (pc'@tt) next_key)\n    | _ => None\n    end\n  | _, _ => None\n  end.\n\nDefinition unseal (s : state mt) : option (state mt) :=\n  let 'State mem reg pc@pct next_key := s in\n  match reg syscall_arg1, reg syscall_arg2 with\n  | Some payload@(SEALED key), Some _@(KEY key') =>\n    if key == key' then\n      do! reg' <- updm reg syscall_ret payload@DATA;\n      do! ret  <- reg ra;\n      match ret with\n      | pc'@DATA => Some (State mem reg' (pc'@tt) next_key)\n      | _ => None\n      end\n    else None\n  | _, _ => None\n  end.\n\nDefinition sealing_syscalls : syscall_table mt :=\n  [fmap (mkkey_addr,  Syscall tt mkkey);\n        (seal_addr,   Syscall tt seal);\n        (unseal_addr, Syscall tt unseal)].\n\nDefinition step := step sealing_syscalls.\n\nEnd WithClasses.\n\n(* BCP: Aren't there also some proof obligations that we need to satisfy? *)\n(* CH: You mean for the concrete-symbolic refinement?\n   I expect those to appear when talking about that refinement,\n   which we don't yet *)\n\n(* BCP: Yes, that's what I meant.  I know we're not there yet, but I\n   am wondering where we want to write them.  Still confused about the\n   modularization strategy for the whole codebase... *)\n(* CH: We will probably make a refinementCS.v file at some point,\n   and I expect that to use any of Arthur's results we'll need\n   to give this kind of details *)\n\nNotation memory mt := (Symbolic.memory mt sym_sealing).\nNotation registers mt := (Symbolic.registers mt sym_sealing).\n\nEnd Sym.\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/sealing/symbolic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.27825678173200435, "lm_q1q2_score": 0.1542851630481968}}
{"text": "Require Import String List.\nImport ListNotations.\n\nRequire Import Kami.Kami.\nRequire Import Hemiola.Lib.Index.\nRequire Import Compiler.HemiolaDeep Compiler.CompileK.\nRequire Import MesiDeep.\n\nSet Implicit Arguments.\n\nDefinition KMesi: Kind := Bit 3.\nDefinition mesiM {var}: Expr var (SyntaxKind KMesi) := ($4)%kami_expr.\nDefinition mesiE {var}: Expr var (SyntaxKind KMesi) := ($3)%kami_expr.\nDefinition mesiS {var}: Expr var (SyntaxKind KMesi) := ($2)%kami_expr.\nDefinition mesiI {var}: Expr var (SyntaxKind KMesi) := ($1)%kami_expr.\nDefinition mesiNP {var}: Expr var (SyntaxKind KMesi) := ($0)%kami_expr.\n\nSection Directory.\n  Context `{ReifyConfig} `{TopoConfig}.\n\n  Definition KDir :=\n    STRUCT { \"dir_st\" :: KMesi;\n             \"dir_excl\" :: KCIdx;\n             \"dir_sharers\" :: KCBv }.\n\n  Definition compile_dir_get {var}\n             (oidx: KCIdx @ var) (dir: (Struct KDir) @ var): Expr var (SyntaxKind KMesi) :=\n    (let dir_st := dir!KDir@.\"dir_st\" in\n     let dir_excl := dir!KDir@.\"dir_excl\" in\n     let dir_sharers := dir!KDir@.\"dir_sharers\" in\n     IF (dir_st == mesiM && dir_excl == oidx) then mesiM\n     else IF (dir_st == mesiE && dir_excl == oidx) then mesiE\n     else IF (dir_st == mesiS && bvTest dir_sharers oidx) then mesiS\n     else mesiI)%kami_expr.\n\nEnd Directory.\n\nSection Instances.\n  Context `{TopoConfig}.\n\n  Instance MesiCompExtType: CompExtType :=\n    {| kind_of_hetype := fun het => match het with\n                                    | HDir => Struct KDir\n                                    end\n    |}.\n\n  Arguments compile_bexp {_ _ _ _ _ _ _ _ _} _ _ _ _ {_}.\n  Fixpoint compile_dir_exp\n           (var: Kind -> Type) {het}\n           (msgIn: var (Struct KMsg))\n           (mshr: var (Struct MSHR))\n           (frs : var (Struct KMsg))\n           (ostvars: HVector.hvec (Vector.map (fun hty => var (kind_of hty)) hostf_ty))\n           (he: heexp (hvar_of var) het): Expr var (SyntaxKind (kind_of het)) :=\n    (match he in (hexp_dir _ h) return (Expr var (SyntaxKind (kind_of h))) with\n     | HDirC _ => #(HVector.hvec_ith ostvars Mesi.dir)\n     | HDirGetSt dir => ((compile_dir_exp msgIn mshr frs ostvars dir)!KDir@.\"dir_st\")\n     | HDirGetExcl dir => ((compile_dir_exp msgIn mshr frs ostvars dir)!KDir@.\"dir_excl\")\n     | HDirGetStO oidx dir => compile_dir_get (compile_bexp msgIn mshr frs ostvars oidx)\n                                              (compile_dir_exp msgIn mshr frs ostvars dir)\n     | HDirGetSh dir => ((compile_dir_exp msgIn mshr frs ostvars dir)!KDir@.\"dir_sharers\")\n     | HDirRemoveSh sh cidx =>\n       bvUnset (compile_dir_exp msgIn mshr frs ostvars sh) (compile_bexp msgIn mshr frs ostvars cidx)\n     | HDirAddSharer oidx dir =>\n       (let kdir := compile_dir_exp msgIn mshr frs ostvars dir in\n        STRUCT { \"dir_st\" ::= mesiS;\n                 \"dir_excl\" ::= kdir!KDir@.\"dir_excl\";\n                 \"dir_sharers\" ::=\n                   IF (kdir!KDir@.\"dir_st\" == mesiS)\n                 then (bvSet (kdir!KDir@.\"dir_sharers\") (compile_bexp msgIn mshr frs ostvars oidx))\n                 else (bvSingleton _ (compile_bexp msgIn mshr frs ostvars oidx)) })\n     | HDirRemoveSharer oidx dir =>\n       (let kdir := compile_dir_exp msgIn mshr frs ostvars dir in\n        STRUCT { \"dir_st\" ::= mesiS;\n                 \"dir_excl\" ::= kdir!KDir@.\"dir_excl\";\n                 \"dir_sharers\" ::= bvUnset (kdir!KDir@.\"dir_sharers\")\n                                           (compile_bexp msgIn mshr frs ostvars oidx) })\n\n     | HDirSetM oidx => (STRUCT { \"dir_st\" ::= mesiM;\n                                  \"dir_excl\" ::= compile_bexp msgIn mshr frs ostvars oidx;\n                                  \"dir_sharers\" ::= $$Default })\n     | HDirSetE oidx => (STRUCT { \"dir_st\" ::= mesiE;\n                                  \"dir_excl\" ::= compile_bexp msgIn mshr frs ostvars oidx;\n                                  \"dir_sharers\" ::= $$Default })\n     | HDirSetS oinds => (STRUCT { \"dir_st\" ::= mesiS;\n                                   \"dir_excl\" ::= $$Default;\n                                   \"dir_sharers\" ::=\n                                     List.fold_left\n                                       (fun bv i => bvSet bv i)\n                                       (map (compile_bexp msgIn mshr frs ostvars) oinds)\n                                       $$Default })\n     | HDirSetI _ => (STRUCT { \"dir_st\" ::= mesiI;\n                               \"dir_excl\" ::= $$Default;\n                               \"dir_sharers\" ::= $$Default })\n\n     | HRqUpFrom oidx => {$TopoTemplate.rqUpIdx, compile_dir_exp msgIn mshr frs ostvars oidx}\n     | HRsUpFrom oidx => {$TopoTemplate.rsUpIdx, compile_dir_exp msgIn mshr frs ostvars oidx}\n     | HDownTo oidx => {$TopoTemplate.downIdx, compile_dir_exp msgIn mshr frs ostvars oidx}\n     | HRqUpFromM oinds => compile_dir_exp msgIn mshr frs ostvars oinds\n     | HRsUpFromM oinds => compile_dir_exp msgIn mshr frs ostvars oinds\n     | HDownToM oinds => compile_dir_exp msgIn mshr frs ostvars oinds\n     | HSingleton se => bvSet $$Default (_truncate_ (compile_dir_exp msgIn mshr frs ostvars se))\n     | HInvalidate se =>\n       (* (IF ((compile_bexp msgIn mshr ostvars se) == mesiNP) then mesiNP else mesiI) *)\n       mesiI\n     end)%kami_expr.\n\n  Definition compile_dir_OPrec\n             (var: Kind -> Type)\n             (msgIn: var (Struct KMsg))\n             (mshr: var (Struct MSHR))\n             (frs : var (Struct KMsg))\n             (ostvars: HVector.hvec (Vector.map (fun hty => var (kind_of hty)) hostf_ty))\n             (pd: heoprec (hvar_of var)): Expr var (SyntaxKind Bool) :=\n    (match pd with\n     | DirLastSharer cidx =>\n       bvIsSingleton (#(HVector.hvec_ith ostvars Mesi.dir)!KDir@.\"dir_sharers\")\n                     (compile_bexp msgIn mshr frs ostvars cidx)\n     | DirNotLastSharer _ =>\n       bvCount (#(HVector.hvec_ith ostvars Mesi.dir)!KDir@.\"dir_sharers\") > $1\n     | DirOtherSharerExists cidx =>\n       bvUnset (#(HVector.hvec_ith ostvars Mesi.dir)!KDir@.\"dir_sharers\")\n               (compile_bexp msgIn mshr frs ostvars cidx) != $0\n     end)%kami_expr.\n\n  Instance MesiCompExtExp: CompExtExp :=\n    {| compile_eexp := compile_dir_exp;\n       compile_eoprec := compile_dir_OPrec\n    |}.\n\n  Definition MesiInfo :=\n    STRUCT { \"mesi_owned\" :: Bool;\n             \"mesi_status\" :: KMesi;\n             \"mesi_dir_st\" :: KMesi;\n             \"mesi_dir_sharers\" :: Bit hcfg_children_max }.\n  Let MesiInfoK := Struct MesiInfo.\n\n  Variables indexSz lgWay edirLgWay: nat.\n\n  Definition MesiInfoRead := InfoRead MesiInfoK indexSz hcfg_addr_sz lgWay edirLgWay.\n  Let MesiInfoReadK := Struct MesiInfoRead.\n\n  Definition mesi_compile_info_to_ostVars\n             (var: Kind -> Type) (pinfo: var MesiInfoK)\n             (cont: HVector.hvec (Vector.map (fun hty => var (kind_of hty)) hostf_ty) ->\n                    ActionT var Void): ActionT var Void :=\n    (LET value <- $$Default;\n    LET owned <- #pinfo!MesiInfo@.\"mesi_owned\";\n    LET status: KMesi <- #pinfo!MesiInfo@.\"mesi_status\";\n    LET dir <- STRUCT { \"dir_st\" ::=\n                          (IF (#pinfo!MesiInfo@.\"mesi_dir_st\" == mesiNP)\n                           then mesiI else #pinfo!MesiInfo@.\"mesi_dir_st\");\n                        \"dir_excl\" ::= bvFirstSet (#pinfo!MesiInfo@.\"mesi_dir_sharers\");\n                        \"dir_sharers\" ::= #pinfo!MesiInfo@.\"mesi_dir_sharers\" };\n    cont (value, (owned, (status, (dir, tt)))))%kami_action.\n\n  Definition mesi_compile_value_read_to_ostVars\n             (var: Kind -> Type)\n             (ostVars: HVector.hvec (Vector.map (fun hty => var (kind_of hty)) hostf_ty))\n             (rval: var KValue)\n    : HVector.hvec (Vector.map (fun hty => var (kind_of hty)) hostf_ty) :=\n    HVector.hvec_upd ostVars Mesi.val rval.\n\n  Definition MesiLineWrite := LineWrite lgWay edirLgWay MesiInfoK.\n  Let MesiLineWriteK := Struct MesiLineWrite.\n\n  Definition mesi_compile_line_update\n             (var: Kind -> Type) (line: var MesiLineWriteK)\n             i ht (Heq: Vector.nth hostf_ty i = ht)\n             (ve: Expr var (SyntaxKind (kind_of ht))): Expr var (SyntaxKind MesiLineWriteK).\n  Proof.\n    subst ht.\n    refine (if Fin.eq_dec i Mesi.val then _\n            else if Fin.eq_dec i Mesi.owned then _\n                 else if Fin.eq_dec i Mesi.status then _\n                      else if Fin.eq_dec i Mesi.dir then _\n                           else ($$Default)%kami_expr); subst i.\n    - exact (STRUCT { \"addr\" ::= #line!MesiLineWrite@.\"addr\";\n                      \"info_write\" ::= #line!MesiLineWrite@.\"info_write\";\n                      \"info_hit\" ::= #line!MesiLineWrite@.\"info_hit\";\n                      \"info_way\" ::= #line!MesiLineWrite@.\"info_way\";\n                      \"edir_hit\" ::= #line!MesiLineWrite@.\"edir_hit\";\n                      \"edir_way\" ::= #line!MesiLineWrite@.\"edir_way\";\n                      \"edir_slot\" ::= #line!MesiLineWrite@.\"edir_slot\";\n                      \"info\" ::= #line!MesiLineWrite@.\"info\";\n                      \"value_write\" ::= $$true;\n                      \"value\" ::= ve;\n                      \"may_victim\" ::= #line!MesiLineWrite@.\"may_victim\";\n                      \"reps\" ::= #line!MesiLineWrite@.\"reps\" })%kami_expr.\n    - exact (STRUCT { \"addr\" ::= #line!MesiLineWrite@.\"addr\";\n                      \"info_write\" ::= $$true;\n                      \"info_hit\" ::= #line!MesiLineWrite@.\"info_hit\";\n                      \"info_way\" ::= #line!MesiLineWrite@.\"info_way\";\n                      \"edir_hit\" ::= #line!MesiLineWrite@.\"edir_hit\";\n                      \"edir_way\" ::= #line!MesiLineWrite@.\"edir_way\";\n                      \"edir_slot\" ::= #line!MesiLineWrite@.\"edir_slot\";\n                      \"info\" ::= updStruct (#line!MesiLineWrite@.\"info\")%kami_expr\n                                           (MesiInfo!!\"mesi_owned\")\n                                           ve;\n                      \"value_write\" ::= #line!MesiLineWrite@.\"value_write\";\n                      \"value\" ::= #line!MesiLineWrite@.\"value\";\n                      \"may_victim\" ::= #line!MesiLineWrite@.\"may_victim\";\n                      \"reps\" ::= #line!MesiLineWrite@.\"reps\" })%kami_expr.\n    - exact (STRUCT { \"addr\" ::= #line!MesiLineWrite@.\"addr\";\n                      \"info_write\" ::= $$true;\n                      \"info_hit\" ::= #line!MesiLineWrite@.\"info_hit\";\n                      \"info_way\" ::= #line!MesiLineWrite@.\"info_way\";\n                      \"edir_hit\" ::= #line!MesiLineWrite@.\"edir_hit\";\n                      \"edir_way\" ::= #line!MesiLineWrite@.\"edir_way\";\n                      \"edir_slot\" ::= #line!MesiLineWrite@.\"edir_slot\";\n                      \"info\" ::= updStruct (#line!MesiLineWrite@.\"info\")%kami_expr\n                                           (MesiInfo!!\"mesi_status\")\n                                           ve;\n                      \"value_write\" ::= #line!MesiLineWrite@.\"value_write\";\n                      \"value\" ::= #line!MesiLineWrite@.\"value\";\n                      \"may_victim\" ::= #line!MesiLineWrite@.\"may_victim\";\n                      \"reps\" ::= #line!MesiLineWrite@.\"reps\" })%kami_expr.\n    - exact (STRUCT { \"addr\" ::= #line!MesiLineWrite@.\"addr\";\n                      \"info_write\" ::= $$true;\n                      \"info_hit\" ::= #line!MesiLineWrite@.\"info_hit\";\n                      \"info_way\" ::= #line!MesiLineWrite@.\"info_way\";\n                      \"edir_hit\" ::= #line!MesiLineWrite@.\"edir_hit\";\n                      \"edir_way\" ::= #line!MesiLineWrite@.\"edir_way\";\n                      \"edir_slot\" ::= #line!MesiLineWrite@.\"edir_slot\";\n                      \"info\" ::=\n                        STRUCT { \"mesi_owned\" ::= #line!MesiLineWrite@.\"info\"!MesiInfo@.\"mesi_owned\";\n                                 \"mesi_status\" ::= #line!MesiLineWrite@.\"info\"!MesiInfo@.\"mesi_status\";\n                                 \"mesi_dir_st\" ::= ve!KDir@.\"dir_st\";\n                                 \"mesi_dir_sharers\" ::=\n                                   (IF (ve!KDir@.\"dir_st\" == mesiS)\n                                    then (ve!KDir@.\"dir_sharers\")\n                                    else (bvSingleton _ (ve!KDir@.\"dir_excl\"))) };\n                      \"value_write\" ::= #line!MesiLineWrite@.\"value_write\";\n                      \"value\" ::= #line!MesiLineWrite@.\"value\";\n                      \"may_victim\" ::= #line!MesiLineWrite@.\"may_victim\";\n                      \"reps\" ::= #line!MesiLineWrite@.\"reps\" })%kami_expr.\n  Defined.\n\n  Instance MesiCompLineRW: CompLineRW lgWay edirLgWay :=\n    {| infoK := MesiInfoK;\n       invRsId := idx_to_word hcfg_msg_id_sz Mesi.mesiInvRs;\n       compile_info_to_ostVars := mesi_compile_info_to_ostVars;\n       compile_value_read_to_ostVars := mesi_compile_value_read_to_ostVars;\n       compile_line_update := mesi_compile_line_update |}.\n\nEnd Instances.\n\nRequire Import Hemiola.Ex.TopoTemplate.\n\nSection Cache.\n  Context `{TopoConfig}.\n  Variables (oidx: IdxT)\n            (indexSz lgWay edirLgWay predNumVictims: nat).\n\n  Definition BitsPerByte := 8.\n  Definition offsetSz := Nat.log2 (Nat.div hcfg_addr_sz BitsPerByte) + hcfg_line_values_lg.\n  Definition tagSz := hcfg_addr_sz - indexSz - offsetSz.\n\n  Definition getIndexE (var: Kind -> Type)\n             (addr: Expr var (SyntaxKind (Bit (offsetSz + indexSz + tagSz))))\n    : Expr var (SyntaxKind (Bit indexSz)) :=\n    (UniBit (ConstExtract _ _ _) addr)%kami_expr.\n\n  Definition getIndex (var: Kind -> Type)\n             (addr: fullType var (SyntaxKind (Bit (offsetSz + indexSz + tagSz))))\n    : Expr var (SyntaxKind (Bit indexSz)) :=\n    getIndexE (#addr)%kami_expr.\n\n  Definition getTag (var: Kind -> Type)\n             (addr: fullType var (SyntaxKind (Bit (offsetSz + indexSz + tagSz))))\n    : Expr var (SyntaxKind (Bit tagSz)) :=\n    (_truncLsb_ #addr)%kami_expr.\n\n  Definition buildAddr (var: Kind -> Type)\n             (tag: fullType var (SyntaxKind (Bit tagSz)))\n             (index: fullType var (SyntaxKind (Bit indexSz)))\n    : Expr var (SyntaxKind (Bit (offsetSz + indexSz + tagSz))) :=\n    {#tag, {#index, $0}}%kami_expr.\n\n  Definition mshrConflictF (var: Kind -> Type)\n             (addr1 addr2: Expr var (SyntaxKind (Bit (offsetSz + indexSz + tagSz))))\n    : Expr var (SyntaxKind Bool) :=\n    (addr1 != addr2 && getIndexE addr1 == getIndexE addr2)%kami_expr.\n\n  Definition MesiEDir :=\n    STRUCT { \"mesi_edir_owned\" :: Bool;\n             \"mesi_edir_st\" :: KMesi;\n             \"mesi_edir_sharers\" :: Bit hcfg_children_max }.\n  Let MesiEDirK := Struct MesiEDir.\n\n  Definition edirToInfo (var: Kind -> Type)\n             (edir: fullType var (SyntaxKind MesiEDirK))\n    : Expr var (SyntaxKind (Struct MesiInfo)) :=\n    (STRUCT { \"mesi_owned\" ::= #edir!MesiEDir@.\"mesi_edir_owned\";\n              \"mesi_status\" ::= mesiI;\n              \"mesi_dir_st\" ::= #edir!MesiEDir@.\"mesi_edir_st\";\n              \"mesi_dir_sharers\" ::= #edir!MesiEDir@.\"mesi_edir_status\" })%kami_expr.\n\n  Definition edirFromInfo (var: Kind -> Type)\n             (pinfo: fullType var (SyntaxKind (Struct MesiInfo)))\n    : Expr var (SyntaxKind MesiEDirK) :=\n    (STRUCT { \"mesi_edir_owned\" ::= #pinfo!MesiInfo@.\"mesi_owned\";\n              \"mesi_edir_st\" ::= #pinfo!MesiInfo@.\"mesi_dir_st\";\n              \"mesi_edir_sharers\" ::= #pinfo!MesiInfo@.\"mesi_dir_sharers\" })%kami_expr.\n\n  Definition isJustDir (var: Kind -> Type)\n             (pinfo: fullType var (SyntaxKind (Struct MesiInfo)))\n    : Expr var (SyntaxKind Bool) :=\n    ((#pinfo!MesiInfo@.\"mesi_status\" <= mesiI) &&\n     (#pinfo!MesiInfo@.\"mesi_dir_st\" != mesiE))%kami_expr.\n\n  Definition isDirInvalid (var: Kind -> Type)\n             (pinfo: fullType var (SyntaxKind (Struct MesiInfo)))\n    : Expr var (SyntaxKind Bool) :=\n    (#pinfo!MesiInfo@.\"mesi_dir_st\" <= mesiI)%kami_expr.\n\n  Definition edirEmptySlot (var: Kind -> Type)\n             (edir: Expr var (SyntaxKind MesiEDirK))\n    : Expr var (SyntaxKind Bool) :=\n    (edir!MesiEDir@.\"mesi_edir_st\" <= mesiI)%kami_expr.\n\n  Definition mesiInfoInit: ConstT (Struct MesiInfo) :=\n    (CSTRUCT { \"mesi_owned\" ::= ConstBool false;\n               \"mesi_status\" ::= ConstBit $1;\n               \"mesi_dir_st\" ::= ConstBit $1;\n               \"mesi_dir_sharers\" ::= ConstBit $0 })%init.\n\n  Definition mesiEDirInit: ConstT MesiEDirK :=\n    (CSTRUCT { \"mesi_edir_owned\" ::= ConstBool false;\n               \"mesi_edir_st\" ::= ConstBit $1;\n               \"mesi_edir_sharers\" ::= ConstBit $0 })%init.\n\n  Definition mesiL1: Modules :=\n    cache oidx KValue lgWay 0\n          mesiInfoInit getIndex getTag buildAddr isDirInvalid predNumVictims.\n\n  Definition mesiLi: Modules :=\n    ncid oidx KValue lgWay edirLgWay\n         mesiInfoInit mesiEDirInit\n         getIndex getTag buildAddr edirToInfo edirFromInfo isJustDir isDirInvalid edirEmptySlot\n         predNumVictims.\n\nEnd Cache.\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/syn/ex/Mesi/MesiComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.29421497216298875, "lm_q1q2_score": 0.15399810339184244}}
{"text": "Require Import\n        List\n        ZArith.\nRequire Import\n        Events\n        LibModel\n        Maps\n        Messages\n        States\n        Types.\nRequire Import\n        BrokerInterceptor\n        BrokerRegistry\n        ERC20\n        FeeHolder\n        OrderRegistry\n        TradeDelegate.\n\n\nOpen Scope bool_scope.\n\n\nSection Aux.\n\n  Fixpoint last_error {A: Type} (l: list A) : option A :=\n    match l with\n    | nil => None\n    | a :: nil => Some a\n    | a :: (_ :: _) as l' => last_error l'\n    end.\n\n  Definition alt_nth {A: Type} (l: list A) (n: nat) (a: A)\n    : option (list A) :=\n    match nth_error l n with\n    | None => None\n    | _ => Some (firstn n l ++ a :: tl (skipn n l))\n    end.\n\nEnd Aux.\n\nModule SpendableElem <: ElemType.\n  Definition elt := Spendable.\n  Definition elt_zero := mk_spendable false O O.\n  Definition elt_eq := fun (x x': elt) => x = x'.\n\n  Lemma elt_eq_dec:\n    forall (x y: elt), { x = y } + { ~ x = y }.\n  Proof. decide equality; decide equality. Qed.\n\n  Lemma elt_eq_refl:\n    forall x, elt_eq x x.\n  Proof.\n    unfold elt_eq; auto.\n  Qed.\n\n  Lemma elt_eq_symm:\n    forall x y, elt_eq x y -> elt_eq y x.\n  Proof.\n    unfold elt_eq; auto.\n  Qed.\n\n  Lemma elt_eq_trans:\n    forall x y, elt_eq x y -> forall z, elt_eq y z -> elt_eq x z.\n  Proof.\n    unfold elt_eq; intros; congruence.\n  Qed.\n\nEnd SpendableElem.\n\n(* broker -> owner -> token -> spendable *)\nModule BrokerSpendableMap := Mapping AAA_as_DT SpendableElem.\n(* owner -> token -> spendable *)\nModule TokenSpendableMap := Mapping AA_as_DT SpendableElem.\n\nModule RingSubmitter.\n\n  Section RunTimeState.\n\n    (* Order in Loopring contract is composed of two parts. One is the *)\n    (*      static data from submitter, while the other is dynamically *)\n    (*      generated and used only in LPSC. *)\n\n    (*      `Order` in Coq defines the static part. `OrderRuntimeState` *)\n    (*      combines it and the dynamic parts together. *)\n    (*    *)\n    Record OrderRuntimeState :=\n      mk_order_runtime_state {\n          ord_rt_order: Order;\n\n          ord_rt_p2p: bool;\n          ord_rt_hash: bytes32;\n          ord_rt_brokerInterceptor: address;\n          ord_rt_filledAmountS : uint;\n          ord_rt_initialFilledAmountS: uint;\n          ord_rt_valid: bool;\n        }.\n\n    (* Similarly for Mining. *)\n    Record MiningRuntimeState :=\n      mk_mining_runtime_state {\n          mining_rt_static: Mining;\n          mining_rt_hash: bytes32;\n          mining_rt_interceptor: address;\n        }.\n\n    Record Fees :=\n      {\n        fee_wallet:      uint;\n        fee_miner:       uint;\n        fee_wallet_burn: uint;\n        fee_miner_burn:  uint;\n        fee_refund_base: uint;\n        fee_rebate:      uint;\n      }.\n\n    Definition zero_fees: Fees :=\n      {|\n        fee_wallet      := 0;\n        fee_miner       := 0;\n        fee_wallet_burn := 0;\n        fee_miner_burn  := 0;\n        fee_refund_base := 0;\n        fee_rebate      := 0;\n      |}.\n\n    Record Participation :=\n      mk_participation {\n          part_order_idx: nat; (* index in another order list *)\n          part_splitS: uint;\n          part_feeAmount: uint;\n          part_feeAmountS: uint;\n          part_feeAmountB: uint;\n          part_rebateFee: uint;\n          part_rebateS: uint;\n          part_rebateB: uint;\n          part_fillAmountS: uint;\n          part_fillAmountB: uint;\n          (* internal fields used in Coq model *)\n          part_fee: Fees;\n          part_feeS: Fees;\n          part_feeB: Fees;\n        }.\n\n    Record RingRuntimeState :=\n      mk_ring_runtime_state {\n          ring_rt_static: Ring;\n          ring_rt_participations: list Participation;\n          ring_rt_hash: bytes32;\n          ring_rt_valid: bool;\n        }.\n\n    (* `RingSubmitterState` models the state of RingSubmitter state *)\n    (*      observable from the outside of contract. *)\n\n    (*      `RingSubmitterRuntimeState` also models the state (e.g., memory) *)\n    (*      that is only visible within the contract in its execution. *)\n    (*    *)\n    Record RingSubmitterRuntimeState :=\n      mk_ring_submitter_runtime_state {\n          submitter_rt_mining: MiningRuntimeState;\n          submitter_rt_orders: list OrderRuntimeState;\n          submitter_rt_rings: list RingRuntimeState;\n          submitter_rt_token_spendables: TokenSpendableMap.t;\n          submitter_rt_broker_spendables: BrokerSpendableMap.t;\n        }.\n\n\n    Definition make_rt_order (order: Order): OrderRuntimeState :=\n      {|\n        ord_rt_order := order;\n        ord_rt_p2p := false;\n        ord_rt_hash := 0;\n        ord_rt_brokerInterceptor := 0;\n        ord_rt_filledAmountS := 0;\n        ord_rt_initialFilledAmountS := 0;\n        ord_rt_valid := true;\n      |}.\n\n    Fixpoint make_rt_orders (orders: list Order): list OrderRuntimeState :=\n      match orders with\n      | nil => nil\n      | order :: orders => make_rt_order order :: make_rt_orders orders\n      end.\n\n    Definition make_rt_mining (mining: Mining): MiningRuntimeState :=\n      {|\n        mining_rt_static := mining;\n        mining_rt_hash := 0;\n        mining_rt_interceptor := 0;\n      |}.\n\n    Definition make_participation (ord_idx: nat): Participation :=\n      {|\n        part_order_idx := ord_idx;\n        part_splitS := 0;\n        part_feeAmount := 0;\n        part_feeAmountS := 0;\n        part_feeAmountB := 0;\n        part_rebateFee := 0;\n        part_rebateS := 0;\n        part_rebateB := 0;\n        part_fillAmountS := 0;\n        part_fillAmountB := 0;\n        part_fee := zero_fees;\n        part_feeS := zero_fees;\n        part_feeB := zero_fees;\n      |}.\n\n    Fixpoint make_participations (ord_indices: list nat): list Participation :=\n      match ord_indices with\n      | nil => nil\n      | idx :: indices' => make_participation idx :: make_participations indices'\n      end.\n\n    Definition make_rt_ring (ring: Ring): RingRuntimeState :=\n      {|\n        ring_rt_static := ring;\n        ring_rt_participations := make_participations (ring_orders ring);\n        ring_rt_hash := 0;\n        ring_rt_valid := true;\n      |}.\n\n    Fixpoint make_rt_rings (rings: list Ring): list RingRuntimeState :=\n      match rings with\n      | nil => nil\n      | ring :: rings => make_rt_ring ring :: make_rt_rings rings\n      end.\n\n    Definition make_rt_submitter_state\n               (mining: Mining) (orders: list Order) (rings: list Ring)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := make_rt_mining mining;\n        submitter_rt_orders := make_rt_orders orders;\n        submitter_rt_rings := make_rt_rings rings;\n        submitter_rt_token_spendables := TokenSpendableMap.empty;\n        submitter_rt_broker_spendables := BrokerSpendableMap.empty;\n      |}.\n\n    Definition submitter_update_mining\n               (rsst: RingSubmitterRuntimeState) (st: MiningRuntimeState)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := st;\n        submitter_rt_orders := submitter_rt_orders rsst;\n        submitter_rt_rings := submitter_rt_rings rsst;\n        submitter_rt_token_spendables := submitter_rt_token_spendables rsst;\n        submitter_rt_broker_spendables := submitter_rt_broker_spendables rsst;\n      |}.\n\n    Definition submitter_update_orders\n               (rsst: RingSubmitterRuntimeState) (sts: list OrderRuntimeState)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := submitter_rt_mining rsst;\n        submitter_rt_orders := sts;\n        submitter_rt_rings := submitter_rt_rings rsst;\n        submitter_rt_token_spendables := submitter_rt_token_spendables rsst;\n        submitter_rt_broker_spendables := submitter_rt_broker_spendables rsst;\n      |}.\n\n    Definition submitter_update_rings\n               (rsst: RingSubmitterRuntimeState) (sts: list RingRuntimeState)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := submitter_rt_mining rsst;\n        submitter_rt_orders := submitter_rt_orders rsst;\n        submitter_rt_rings := sts;\n        submitter_rt_token_spendables := submitter_rt_token_spendables rsst;\n        submitter_rt_broker_spendables := submitter_rt_broker_spendables rsst;\n      |}.\n\n    Definition submitter_update_token_spendables\n               (rsst: RingSubmitterRuntimeState) (spendables: TokenSpendableMap.t)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := submitter_rt_mining rsst;\n        submitter_rt_orders := submitter_rt_orders rsst;\n        submitter_rt_rings := submitter_rt_rings rsst;\n        submitter_rt_token_spendables := spendables;\n        submitter_rt_broker_spendables := submitter_rt_broker_spendables rsst;\n      |}.\n\n    Definition submitter_update_token_spendable\n               (rsst: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState) (token: address)\n               (spendable: Spendable)\n      : RingSubmitterRuntimeState :=\n      let order := ord_rt_order ord in\n      let spendables := submitter_rt_token_spendables rsst in\n      let spendables' :=\n          TokenSpendableMap.upd spendables (order_owner order, token) spendable in\n      submitter_update_token_spendables rsst spendables'.\n\n    Definition submitter_update_broker_spendables\n               (rsst: RingSubmitterRuntimeState) (spendables: BrokerSpendableMap.t)\n      : RingSubmitterRuntimeState :=\n      {|\n        submitter_rt_mining := submitter_rt_mining rsst;\n        submitter_rt_orders := submitter_rt_orders rsst;\n        submitter_rt_rings := submitter_rt_rings rsst;\n        submitter_rt_token_spendables := submitter_rt_token_spendables rsst;\n        submitter_rt_broker_spendables := spendables;\n      |}.\n\n    Definition submitter_update_broker_spendable\n               (rsst: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState) (token: address)\n               (spendable: Spendable)\n      : RingSubmitterRuntimeState :=\n      let order := ord_rt_order ord in\n      let spendables := submitter_rt_broker_spendables rsst in\n      let spendables' :=\n          BrokerSpendableMap.upd spendables\n                                 (order_broker order, order_owner order, token)\n                                 spendable in\n      submitter_update_broker_spendables rsst spendables'.\n\n    Definition upd_order_broker\n               (ord: OrderRuntimeState) (broker: address)\n      : OrderRuntimeState :=\n      let order := ord_rt_order ord in\n      {|\n        ord_rt_order :=\n          {|\n            order_version               := order_version               order;\n            order_owner                 := order_owner                 order;\n            order_tokenS                := order_tokenS                order;\n            order_tokenB                := order_tokenB                order;\n            order_amountS               := order_amountS               order;\n            order_amountB               := order_amountB               order;\n            order_validSince            := order_validSince            order;\n            order_tokenSpendableS       := order_tokenSpendableS       order;\n            order_tokenSpendableFee     := order_tokenSpendableFee     order;\n            order_dualAuthAddr          := order_dualAuthAddr          order;\n            order_broker                := broker;\n            order_brokerSpendableS      := order_brokerSpendableS      order;\n            order_brokerSpendableFee    := order_brokerSpendableFee    order;\n            order_orderInterceptor      := order_orderInterceptor      order;\n            order_wallet                := order_wallet                order;\n            order_validUntil            := order_validUntil            order;\n            order_sig                   := order_sig                   order;\n            order_dualAuthSig           := order_dualAuthSig           order;\n            order_allOrNone             := order_allOrNone             order;\n            order_feeToken              := order_feeToken              order;\n            order_feeAmount             := order_feeAmount             order;\n            order_feePercentage         := order_feePercentage         order;\n            order_waiveFeePercentage    := order_waiveFeePercentage    order;\n            order_tokenSFeePercentage   := order_tokenSFeePercentage   order;\n            order_tokenBFeePercentage   := order_tokenBFeePercentage   order;\n            order_tokenRecipient        := order_tokenRecipient        order;\n            order_walletSplitPercentage := order_walletSplitPercentage order;\n          |};\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition upd_order_interceptor\n               (ord: OrderRuntimeState) (interceptor: address)\n      : OrderRuntimeState :=\n      {|\n        ord_rt_order                := ord_rt_order ord;\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := interceptor;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition upd_order_valid\n               (ord: OrderRuntimeState) (valid: bool)\n      : OrderRuntimeState :=\n      {|\n        ord_rt_order                := ord_rt_order ord;\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := valid;\n      |}.\n\n    Definition upd_order_init_filled\n               (ord: OrderRuntimeState) (amount: uint)\n      : OrderRuntimeState :=\n      {|\n        ord_rt_order                := ord_rt_order ord;\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := amount;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition upd_order_filled\n               (ord: OrderRuntimeState) (amount: uint)\n      : OrderRuntimeState :=\n      {|\n        ord_rt_order                := ord_rt_order ord;\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := amount;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition upd_order_p2p\n               (ord: OrderRuntimeState) (p2p: bool)\n      : OrderRuntimeState :=\n      {|\n        ord_rt_order                := ord_rt_order ord;\n        ord_rt_p2p                  := p2p;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition clear_order_broker_spendables\n               (ord: OrderRuntimeState)\n      : OrderRuntimeState :=\n      let order := ord_rt_order ord in\n      {|\n        ord_rt_order :=\n          {|\n            order_version               := order_version               order;\n            order_owner                 := order_owner                 order;\n            order_tokenS                := order_tokenS                order;\n            order_tokenB                := order_tokenB                order;\n            order_amountS               := order_amountS               order;\n            order_amountB               := order_amountB               order;\n            order_validSince            := order_validSince            order;\n            order_tokenSpendableS       := order_tokenSpendableS       order;\n            order_tokenSpendableFee     := order_tokenSpendableFee     order;\n            order_dualAuthAddr          := order_dualAuthAddr          order;\n            order_broker                := order_broker                order;\n            order_brokerSpendableS      := mk_spendable false 0 0;\n            order_brokerSpendableFee    := mk_spendable false 0 0;\n            order_orderInterceptor      := order_orderInterceptor      order;\n            order_wallet                := order_wallet                order;\n            order_validUntil            := order_validUntil            order;\n            order_sig                   := order_sig                   order;\n            order_dualAuthSig           := order_dualAuthSig           order;\n            order_allOrNone             := order_allOrNone             order;\n            order_feeToken              := order_feeToken              order;\n            order_feeAmount             := order_feeAmount             order;\n            order_feePercentage         := order_feePercentage         order;\n            order_waiveFeePercentage    := order_waiveFeePercentage    order;\n            order_tokenSFeePercentage   := order_tokenSFeePercentage   order;\n            order_tokenBFeePercentage   := order_tokenBFeePercentage   order;\n            order_tokenRecipient        := order_tokenRecipient        order;\n            order_walletSplitPercentage := order_walletSplitPercentage order;\n          |};\n        ord_rt_p2p                  := ord_rt_p2p ord;\n        ord_rt_hash                 := ord_rt_hash ord;\n        ord_rt_brokerInterceptor    := ord_rt_brokerInterceptor ord;\n        ord_rt_filledAmountS        := ord_rt_filledAmountS ord;\n        ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS ord;\n        ord_rt_valid                := ord_rt_valid ord;\n      |}.\n\n    Definition upd_ring_hash\n               (r: RingRuntimeState) (hash: bytes32)\n      : RingRuntimeState :=\n      {|\n        ring_rt_static         := ring_rt_static r;\n        ring_rt_participations := ring_rt_participations r;\n        ring_rt_hash           := hash;\n        ring_rt_valid          := ring_rt_valid r;\n      |}.\n\n    Definition upd_ring_valid\n               (r: RingRuntimeState) (valid: bool)\n      : RingRuntimeState :=\n      {|\n        ring_rt_static         := ring_rt_static r;\n        ring_rt_participations := ring_rt_participations r;\n        ring_rt_hash           := ring_rt_hash r;\n        ring_rt_valid          := valid;\n      |}.\n\n    Definition upd_ring_participations\n               (r: RingRuntimeState) (ps: list Participation)\n      : RingRuntimeState :=\n      {|\n        ring_rt_static         := ring_rt_static r;\n        ring_rt_participations := ps;\n        ring_rt_hash           := ring_rt_hash r;\n        ring_rt_valid          := ring_rt_valid r;\n      |}.\n\n    Definition inc_ring_minerFeesToOrdersPercentage\n               (r: RingRuntimeState) (amount: uint)\n      : RingRuntimeState :=\n      {|\n        ring_rt_static         := ring_add_minerFeesToOrdersPercentage (ring_rt_static r) amount;\n        ring_rt_participations := ring_rt_participations r;\n        ring_rt_hash           := ring_rt_hash r;\n        ring_rt_valid          := ring_rt_valid r;\n      |}.\n\n    Definition upd_mining_hash\n               (m: MiningRuntimeState) (hash: bytes32)\n      : MiningRuntimeState :=\n      {|\n        mining_rt_static      := mining_rt_static m;\n        mining_rt_hash        := hash;\n        mining_rt_interceptor := mining_rt_interceptor m;\n      |}.\n\n    Definition upd_mining_interceptor\n               (m: MiningRuntimeState) (interceptor: address)\n      : MiningRuntimeState :=\n      {|\n        mining_rt_static      := mining_rt_static m;\n        mining_rt_hash        := mining_rt_hash m;\n        mining_rt_interceptor := interceptor;\n      |}.\n\n    Definition upd_mining_miner\n               (m: MiningRuntimeState) (miner: address)\n      : MiningRuntimeState :=\n      let mining := mining_rt_static m in\n      {|\n        mining_rt_static      :=\n          {|\n            mining_feeRecipient := mining_feeRecipient mining;\n            mining_miner        := miner;\n            mining_sig          := mining_sig mining;\n          |};\n        mining_rt_hash        := mining_rt_hash m;\n        mining_rt_interceptor := mining_rt_interceptor m;\n      |}.\n\n    Definition upd_part_fillAmounts\n               (p: Participation) (amountS amountB: uint)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := part_splitS      p;\n        part_feeAmount   := part_feeAmount   p;\n        part_feeAmountS  := part_feeAmountS  p;\n        part_feeAmountB  := part_feeAmountB  p;\n        part_rebateFee   := part_rebateFee   p;\n        part_rebateS     := part_rebateS     p;\n        part_rebateB     := part_rebateB     p;\n        part_fillAmountS := amountS;\n        part_fillAmountB := amountB;\n        part_fee         := part_fee         p;\n        part_feeS        := part_feeS        p;\n        part_feeB        := part_feeB        p;\n      |}.\n\n    Definition upd_part_fillAmountS\n               (p: Participation) (amountS: uint)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := part_splitS      p;\n        part_feeAmount   := part_feeAmount   p;\n        part_feeAmountS  := part_feeAmountS  p;\n        part_feeAmountB  := part_feeAmountB  p;\n        part_rebateFee   := part_rebateFee   p;\n        part_rebateS     := part_rebateS     p;\n        part_rebateB     := part_rebateB     p;\n        part_fillAmountS := amountS;\n        part_fillAmountB := part_fillAmountB p;\n        part_fee         := part_fee         p;\n        part_feeS        := part_feeS        p;\n        part_feeB        := part_feeB        p;\n      |}.\n\n    Definition upd_part_splitS\n               (p: Participation) (amount: uint)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := amount;\n        part_feeAmount   := part_feeAmount   p;\n        part_feeAmountS  := part_feeAmountS  p;\n        part_feeAmountB  := part_feeAmountB  p;\n        part_rebateFee   := part_rebateFee   p;\n        part_rebateS     := part_rebateS     p;\n        part_rebateB     := part_rebateB     p;\n        part_fillAmountS := part_fillAmountS p;\n        part_fillAmountB := part_fillAmountB p;\n        part_fee         := part_fee         p;\n        part_feeS        := part_feeS        p;\n        part_feeB        := part_feeB        p;\n      |}.\n\n    Definition upd_part_feeAmounts\n               (p: Participation) (amount amountS amountB: uint)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := part_splitS      p;\n        part_feeAmount   := amount;\n        part_feeAmountS  := amountS;\n        part_feeAmountB  := amountB;\n        part_rebateFee   := part_rebateFee   p;\n        part_rebateS     := part_rebateS     p;\n        part_rebateB     := part_rebateB     p;\n        part_fillAmountS := part_fillAmountS p;\n        part_fillAmountB := part_fillAmountB p;\n        part_fee         := part_fee         p;\n        part_feeS        := part_feeS        p;\n        part_feeB        := part_feeB        p;\n      |}.\n\n    Definition upd_part_rebates\n               (p: Participation) (amount amountS amountB: uint)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := part_splitS      p;\n        part_feeAmount   := part_feeAmount   p;\n        part_feeAmountS  := part_feeAmountS  p;\n        part_feeAmountB  := part_feeAmountB  p;\n        part_rebateFee   := amount;\n        part_rebateS     := amountS;\n        part_rebateB     := amountB;\n        part_fillAmountS := part_fillAmountS p;\n        part_fillAmountB := part_fillAmountB p;\n        part_fee         := part_fee         p;\n        part_feeS        := part_feeS        p;\n        part_feeB        := part_feeB        p;\n      |}.\n\n    Definition upd_part_fees\n               (p: Participation) (fee feeS feeB: Fees)\n      : Participation :=\n      {|\n        part_order_idx   := part_order_idx   p;\n        part_splitS      := part_splitS      p;\n        part_feeAmount   := part_feeAmount   p;\n        part_feeAmountS  := part_feeAmountS  p;\n        part_feeAmountB  := part_feeAmountB  p;\n        part_rebateFee   := part_rebateFee   p;\n        part_rebateS     := part_rebateS     p;\n        part_rebateB     := part_rebateB     p;\n        part_fillAmountS := part_fillAmountS p;\n        part_fillAmountB := part_fillAmountB p;\n        part_fee         := fee;\n        part_feeS        := feeS;\n        part_feeB        := feeB;\n      |}.\n\n  End RunTimeState.\n\n  Section GetSpendable.\n\n    Section StGetSpendable.\n\n      (** Get broker spendable from spendable map *)\n      Definition __st_get_broker_spendable\n                 (st: RingSubmitterRuntimeState)\n                 (ord: OrderRuntimeState)\n                 (token: address) :=\n        let order := ord_rt_order ord in\n        let broker := order_broker order in\n        let owner := order_owner order in\n        BrokerSpendableMap.get (submitter_rt_broker_spendables st)\n                               (broker, owner, token).\n\n      (** Get broker spendableS from spendable map *)\n      Definition _st_get_brokerSpendableS\n                 (st: RingSubmitterRuntimeState) (ord: OrderRuntimeState) :=\n        __st_get_broker_spendable st ord (order_tokenS (ord_rt_order ord)).\n\n      (** Get broker spendableFee from spendable map *)\n      Definition _st_get_brokerSpendableFee\n                 (st: RingSubmitterRuntimeState) (ord: OrderRuntimeState) :=\n        __st_get_broker_spendable st ord (order_feeToken (ord_rt_order ord)).\n\n      (** Get token spendable from spendable map *)\n      Definition __st_get_token_spendable\n                 (st: RingSubmitterRuntimeState)\n                 (ord: OrderRuntimeState)\n                 (token: address) :=\n        let order := ord_rt_order ord in\n        let owner := order_owner order in\n        TokenSpendableMap.get (submitter_rt_token_spendables st) (owner, token).\n\n      (** Get token spendableS from spendable map *)\n      Definition _st_get_tokenSpendableS\n                 (st: RingSubmitterRuntimeState) (ord: OrderRuntimeState) :=\n        __st_get_token_spendable st ord (order_tokenS (ord_rt_order ord)).\n\n      (** Get token spendableFee from spendable map *)\n      Definition _st_get_tokenSpendableFee\n                 (st: RingSubmitterRuntimeState) (ord: OrderRuntimeState) :=\n        __st_get_token_spendable st ord (order_feeToken (ord_rt_order ord)).\n\n    End StGetSpendable.\n\n    Section ERC20GetTokenSpendable.\n\n      Definition __erc20_get_allowance_success\n                 (wst: WorldState) (owner token: address)\n                 (wst': WorldState) (allowance: uint) (events: list Event) : Prop :=\n        ERC20s.model wst\n                     (msg_allowance (wst_ring_submitter_addr wst)\n                                    token\n                                    owner\n                                    (wst_trade_delegate_addr wst))\n                     wst' (RetUint allowance) events.\n\n      Definition __erc20_get_balance_success\n                 (wst: WorldState) (owner token: address)\n                 (wst': WorldState) (balance: uint) (events: list Event) : Prop :=\n        ERC20s.model wst\n                     (msg_balanceOf (wst_ring_submitter_addr wst) token owner)\n                     wst' (RetUint balance) events.\n\n      Inductive _erc20_get_token_spendable\n                (wst: WorldState) (owner token: address)\n        : WorldState -> uint -> list Event -> Prop :=\n      | ERC20GetSpendable_zero:\n          forall wst' events,\n            __erc20_get_allowance_success wst owner token wst' 0 events ->\n            _erc20_get_token_spendable wst owner token wst' 0 events\n\n      | ERC20GetSpendable_nonzero_1:\n          forall wst' allowance events' wst'' balance events'',\n            __erc20_get_allowance_success wst owner token wst' allowance events' ->\n            allowance <> 0 ->\n            __erc20_get_balance_success wst' owner token wst'' balance events'' ->\n            balance < allowance ->\n            _erc20_get_token_spendable wst owner token wst'' balance (events' ++ events'')\n\n      | ERC20GetSpendable_nonzero_2:\n          forall wst' allowance events' wst'' balance events'',\n            __erc20_get_allowance_success wst owner token wst' allowance events' ->\n            allowance <> 0 ->\n            __erc20_get_balance_success wst' owner token wst'' balance events'' ->\n            balance >= allowance ->\n            _erc20_get_token_spendable wst owner token wst'' allowance (events' ++ events'')\n      .\n\n      Definition __erc20_get_token_spendable\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (token: address)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        forall wst'' amount events'',\n          _erc20_get_token_spendable\n            wst (order_owner (ord_rt_order ord)) token wst'' amount events'' ->\n          wst' = wst'' /\\\n          events = events'' /\\\n          spendable = mk_spendable true amount 0.\n\n      Definition _erc20_get_tokenSpendableS\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        __erc20_get_token_spendable\n          wst ord (order_tokenS (ord_rt_order ord)) wst' spendable events.\n\n      Definition _erc20_get_tokenSpendableFee\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        __erc20_get_token_spendable\n          wst ord (order_feeToken (ord_rt_order ord)) wst' spendable events.\n\n    End ERC20GetTokenSpendable.\n\n    Section ProxyGetBrokerSpendable.\n\n      Definition __proxy_get_allowance_success\n                 (wst: WorldState) (broker owner token interceptor: address)\n                 (wst': WorldState) (allowance: uint) (events: list Event) : Prop :=\n        BrokerInterceptor.model wst\n                                (msg_getAllowanceSafe (wst_ring_submitter_addr wst)\n                                                      interceptor owner broker token)\n                                wst' (RetUint allowance) events.\n\n      Definition __proxy_get_broker_spendable\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (token: address)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        forall order wst'' allowance events'',\n          order = ord_rt_order ord /\\\n          __proxy_get_allowance_success\n            wst\n            (order_broker order) (order_owner order) token (ord_rt_brokerInterceptor ord)\n            wst'' allowance events'' /\\\n          wst' = wst'' /\\\n          events = events'' /\\\n          spendable = mk_spendable true allowance 0.\n\n      Definition _proxy_get_brokerSpendableS\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        __proxy_get_broker_spendable\n          wst ord (order_tokenS (ord_rt_order ord)) wst' spendable events.\n\n      Definition _proxy_get_brokerSpendableFee\n                 (wst: WorldState)\n                 (ord: OrderRuntimeState)\n                 (wst': WorldState)\n                 (spendable: Spendable)\n                 (events: list Event) : Prop :=\n        __proxy_get_broker_spendable\n          wst ord (order_feeToken (ord_rt_order ord)) wst' spendable events.\n\n    End ProxyGetBrokerSpendable.\n\n    Inductive _get_token_spendable\n              (wst: WorldState)\n              (st: RingSubmitterRuntimeState)\n              (ord: OrderRuntimeState)\n              (token: address)\n      : WorldState -> RingSubmitterRuntimeState -> Spendable -> list Event -> Prop :=\n    | GetTokenSpenable_noninited:\n        forall wst' spendable events,\n          spendable_initialized (__st_get_token_spendable st ord token) = false ->\n          __erc20_get_token_spendable wst ord token wst' spendable events ->\n          _get_token_spendable\n            wst st ord token wst'\n            (submitter_update_token_spendable st ord token spendable)\n            spendable events\n\n    | GetTokenSpenable_inited:\n        forall spendable,\n          spendable = __st_get_token_spendable st ord token ->\n          spendable_initialized spendable = true ->\n          _get_token_spendable wst st ord token wst st spendable nil\n    .\n\n    Inductive _get_broker_spendable\n              (wst: WorldState)\n              (st: RingSubmitterRuntimeState)\n              (ord: OrderRuntimeState)\n              (token: address)\n      : WorldState -> RingSubmitterRuntimeState -> Spendable -> list Event -> Prop :=\n    | GetBrokerSpenable_noninited:\n        forall wst' spendable events,\n          spendable_initialized (__st_get_broker_spendable st ord token) = false ->\n          __proxy_get_broker_spendable wst ord token wst' spendable events ->\n          _get_broker_spendable\n            wst st ord token wst'\n            (submitter_update_broker_spendable st ord token spendable)\n            spendable events\n\n    | GetBrokerSpenable_inited:\n        forall spendable,\n          spendable = __st_get_broker_spendable st ord token ->\n          spendable_initialized spendable = true ->\n          _get_broker_spendable wst st ord token wst st spendable nil\n    .\n\n    Definition get_tokenSpendableS\n               (wst: WorldState) (st: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState)\n               (wst': WorldState) (st': RingSubmitterRuntimeState)\n               (spendable: Spendable) (events: list Event) : Prop :=\n      _get_token_spendable\n        wst st ord (order_tokenS (ord_rt_order ord)) wst' st' spendable events.\n\n    Definition get_tokenSpendableFee\n               (wst: WorldState) (st: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState)\n               (wst': WorldState) (st': RingSubmitterRuntimeState)\n               (spendable: Spendable) (events: list Event) : Prop :=\n      _get_token_spendable\n        wst st ord (order_feeToken (ord_rt_order ord)) wst' st' spendable events.\n\n    Definition get_brokerSpendableS\n               (wst: WorldState) (st: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState)\n               (wst': WorldState) (st': RingSubmitterRuntimeState)\n               (spendable: Spendable) (events: list Event) : Prop :=\n      _get_broker_spendable\n        wst st ord (order_tokenS (ord_rt_order ord)) wst' st' spendable events.\n\n    Definition get_brokerSpendableFee\n               (wst: WorldState) (st: RingSubmitterRuntimeState)\n               (ord: OrderRuntimeState)\n               (wst': WorldState) (st': RingSubmitterRuntimeState)\n               (spendable: Spendable) (events: list Event) : Prop :=\n      _get_broker_spendable\n        wst st ord (order_feeToken (ord_rt_order ord)) wst' st' spendable events.\n\n  End GetSpendable.\n\n  Section SetSpendable.\n\n    Definition _token_spendable_reserved_inc\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (token: address)\n               (amount: uint)\n    : TokenSpendableMap.t :=\n      let owner := order_owner (ord_rt_order ord) in\n      let spendable := TokenSpendableMap.get spendables (owner, token) in\n      let spendable' := {| spendable_initialized := spendable_initialized spendable;\n                           spendable_amount      := spendable_amount spendable;\n                           spendable_reserved    := spendable_reserved spendable + amount;\n                        |} in\n      TokenSpendableMap.upd spendables (owner, token) spendable'.\n\n    Definition _broker_spendable_reserved_inc\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (token: address)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      let order := ord_rt_order ord in\n      let broker := order_broker order in\n      let owner := order_owner order in\n      let spendable := BrokerSpendableMap.get spendables (broker, owner, token) in\n      let spendable' := {| spendable_initialized := spendable_initialized spendable;\n                           spendable_amount      := spendable_amount spendable;\n                           spendable_reserved    := spendable_reserved spendable + amount;\n                        |} in\n      BrokerSpendableMap.upd spendables (broker, owner, token) spendable'.\n\n    Definition token_spendableS_reserved_inc\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : TokenSpendableMap.t :=\n      _token_spendable_reserved_inc spendables ord (order_tokenS (ord_rt_order ord)) amount.\n\n    Definition token_spendableFee_reserved_inc\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : TokenSpendableMap.t :=\n      _token_spendable_reserved_inc spendables ord (order_feeToken (ord_rt_order ord)) amount.\n\n    Definition broker_spendableS_reserved_inc\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      _broker_spendable_reserved_inc spendables ord (order_tokenS (ord_rt_order ord)) amount.\n\n    Definition broker_spendableFee_reserved_inc\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      _broker_spendable_reserved_inc spendables ord (order_feeToken (ord_rt_order ord)) amount.\n\n    Definition _clear_token_spendables_reserved\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n      : TokenSpendableMap.t :=\n      let order := ord_rt_order ord in\n      let owner := order_owner order in\n      let tokenS := order_tokenS order in\n      let spendableS := TokenSpendableMap.get spendables (owner, tokenS) in\n      let spendableS' := {| spendable_initialized := spendable_initialized spendableS;\n                            spendable_amount      := spendable_amount spendableS;\n                            spendable_reserved    := 0;\n                         |} in\n      let feeToken := order_feeToken order in\n      let feeSpendable := TokenSpendableMap.get spendables (owner, feeToken) in\n      let feeSpendable' := {| spendable_initialized := spendable_initialized feeSpendable;\n                              spendable_amount      := spendable_amount feeSpendable;\n                              spendable_reserved    := 0;\n                           |} in\n      TokenSpendableMap.upd\n        (TokenSpendableMap.upd spendables (owner, tokenS) spendableS')\n        (owner, feeToken) feeSpendable'.\n\n    Definition _clear_broker_spendables_reserved\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n      : BrokerSpendableMap.t :=\n      let order := ord_rt_order ord in\n      let broker := order_broker order in\n      let owner := order_owner order in\n      let tokenS := order_tokenS order in\n      let spendableS := BrokerSpendableMap.get spendables (broker, owner, tokenS) in\n      let spendableS' := {| spendable_initialized := spendable_initialized spendableS;\n                            spendable_amount      := spendable_amount spendableS;\n                            spendable_reserved    := 0;\n                         |} in\n      let feeToken := order_feeToken order in\n      let feeSpendable := BrokerSpendableMap.get spendables (broker, owner, feeToken) in\n      let feeSpendable' := {| spendable_initialized := spendable_initialized feeSpendable;\n                              spendable_amount      := spendable_amount feeSpendable;\n                              spendable_reserved    := 0;\n                           |} in\n      BrokerSpendableMap.upd\n        (BrokerSpendableMap.upd spendables (broker, owner, tokenS) spendableS')\n        (broker, owner, feeToken) feeSpendable'.\n\n    Definition clear_order_spendables_reserved\n               (st: RingSubmitterRuntimeState) (ord: OrderRuntimeState)\n      : RingSubmitterRuntimeState :=\n      let token_spendables := submitter_rt_token_spendables st in\n      let token_spendables' := _clear_token_spendables_reserved token_spendables ord in\n      let broker_spendables := submitter_rt_broker_spendables st in\n      let broker_spendables' :=\n          match ord_rt_brokerInterceptor ord with\n          | O => broker_spendables\n          | _ => _clear_broker_spendables_reserved broker_spendables ord\n          end\n      in\n      submitter_update_token_spendables\n        (submitter_update_broker_spendables st broker_spendables')\n        token_spendables'.\n\n    Definition _token_spendable_amount_dec\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (token: address)\n               (amount: uint)\n      : TokenSpendableMap.t :=\n      let owner := order_owner (ord_rt_order ord) in\n      let spendable := TokenSpendableMap.get spendables (owner, token) in\n      let spendable' := {| spendable_initialized := spendable_initialized spendable;\n                           spendable_amount      := spendable_amount spendable - amount;\n                           spendable_reserved    := spendable_reserved spendable;\n                        |} in\n      TokenSpendableMap.upd spendables (owner, token) spendable'.\n\n    Definition _broker_spendable_amount_dec\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (token: address)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      let order := ord_rt_order ord in\n      let broker := order_broker order in\n      let owner := order_owner order in\n      let spendable := BrokerSpendableMap.get spendables (broker, owner, token) in\n      let spendable' := {| spendable_initialized := spendable_initialized spendable;\n                           spendable_amount      := spendable_amount spendable - amount;\n                           spendable_reserved    := spendable_reserved spendable;\n                        |} in\n      BrokerSpendableMap.upd spendables (broker, owner, token) spendable'.\n\n    Definition token_spendableS_amount_dec\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : TokenSpendableMap.t :=\n      _token_spendable_amount_dec spendables ord (order_tokenS (ord_rt_order ord)) amount.\n\n    Definition token_spendableFee_amount_dec\n               (spendables: TokenSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : TokenSpendableMap.t :=\n      _token_spendable_amount_dec spendables ord (order_feeToken (ord_rt_order ord)) amount.\n\n    Definition broker_spendableS_amount_dec\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      _broker_spendable_amount_dec spendables ord (order_tokenS (ord_rt_order ord)) amount.\n\n    Definition broker_spendableFee_amount_dec\n               (spendables: BrokerSpendableMap.t)\n               (ord: OrderRuntimeState)\n               (amount: uint)\n      : BrokerSpendableMap.t :=\n      _broker_spendable_amount_dec spendables ord (order_feeToken (ord_rt_order ord)) amount.\n\n  End SetSpendable.\n\n  Parameters get_ring_hash: Ring -> list OrderRuntimeState -> bytes32.\n  Parameter get_mining_hash: Mining -> list RingRuntimeState -> bytes32.\n\n  Section HashAxioms.\n\n    Fixpoint __get_ring_hash_preimg\n             (indices: list nat) (orders: list OrderRuntimeState)\n      : list (option (bytes32 * int16)):=\n      match indices with\n      | nil => nil\n      | idx :: indices' =>\n        let preimg := match nth_error orders idx with\n                      | None => None\n                      | Some order => Some (ord_rt_hash order,\n                                           order_waiveFeePercentage (ord_rt_order order))\n                      end\n        in preimg :: __get_ring_hash_preimg indices' orders\n      end.\n\n    Definition get_ring_hash_preimg\n               (r: Ring) (orders: list OrderRuntimeState) :=\n      __get_ring_hash_preimg (ring_orders r) orders.\n\n    Axiom ring_hash_dec:\n      forall (r r': Ring) (orders orders': list OrderRuntimeState),\n        let preimg := get_ring_hash_preimg r orders in\n        let preimg' := get_ring_hash_preimg r' orders' in\n        (preimg = preimg' -> get_ring_hash r orders = get_ring_hash r' orders') /\\\n        (preimg <> preimg' -> get_ring_hash r orders <> get_ring_hash r' orders').\n\n    Fixpoint rings_hashes (rings: list RingRuntimeState) : list bytes32 :=\n      match rings with\n      | nil => nil\n      | r :: rings' => ring_rt_hash r :: rings_hashes rings'\n      end.\n\n    Definition get_mining_hash_preimg\n               (mining: Mining) (rings: list RingRuntimeState) :=\n      (mining_miner mining, mining_feeRecipient mining, rings_hashes rings).\n\n    Axiom mining_hash_dec:\n      forall (m m': Mining) (rings rings': list RingRuntimeState),\n        let preimg := get_mining_hash_preimg m rings in\n        let preimg' := get_mining_hash_preimg m' rings' in\n        (preimg = preimg' -> get_mining_hash m rings = get_mining_hash m' rings') /\\\n        (preimg <> preimg' -> get_mining_hash m rings <> get_mining_hash m' rings').\n\n  End HashAxioms.\n\n  Section SubSpec.\n\n    Record SubSpec :=\n      mk_sub_spec {\n          subspec_require: WorldState -> RingSubmitterRuntimeState -> Prop;\n          subspec_trans: WorldState -> RingSubmitterRuntimeState ->\n                         WorldState -> RingSubmitterRuntimeState ->\n                         Prop;\n          subspec_events: WorldState -> RingSubmitterRuntimeState ->\n                          list Event -> Prop;\n        }.\n\n  End SubSpec.\n\n  Definition SubSpec_funcT : Type :=\n    WorldState -> RingSubmitterRuntimeState -> WorldState * RingSubmitterRuntimeState * list Event.\n\n  Definition funcT_subspec (f: SubSpec_funcT) (subspec: SubSpec) : Prop :=\n    forall wst st wst' st' events,\n      subspec_require subspec wst st ->\n      f wst st = (wst', st', events) ->\n      subspec_trans subspec wst st wst' st' /\\\n      subspec_events subspec wst st events.\n\n  Section SubmitRings.\n\n    Section Aux.\n\n      Definition make_order_param (ord: OrderRuntimeState) : OrderParam :=\n        let order := ord_rt_order ord in\n        {|\n          order_param_broker := order_broker order;\n          order_param_owner  := order_owner order;\n          order_param_hash   := ord_rt_hash ord;\n          order_param_validSince := order_validSince order;\n          order_param_tradingPair := Nat.lxor (order_tokenS order) (order_tokenB order);\n        |}.\n\n      Fixpoint make_order_params\n               (orders: list OrderRuntimeState) : list OrderParam :=\n        match orders with\n        | nil => nil\n        | order :: orders' => make_order_param order :: make_order_params orders'\n        end.\n\n      Definition participation_preserve (p p': Participation) : Prop :=\n        part_order_idx p = part_order_idx p'.\n\n      Definition participations_preserve (r r': RingRuntimeState) : Prop :=\n        length (ring_rt_participations r) = length (ring_rt_participations r') /\\\n        forall n p,\n          nth_error (ring_rt_participations r) n = Some p ->\n          exists p',\n            nth_error (ring_rt_participations r') n = Some p' /\\\n            part_order_idx p = part_order_idx p'.\n\n      Definition rings_preserve (st st': RingSubmitterRuntimeState) : Prop :=\n        forall n,\n          (forall r,\n              nth_error (submitter_rt_rings st) n = Some r ->\n              exists r',\n                nth_error (submitter_rt_rings st') n = Some r' /\\\n                ring_rt_static r' = ring_rt_static r /\\\n                participations_preserve r r') /\\\n          (nth_error (submitter_rt_rings st) n = None ->\n           nth_error (submitter_rt_rings st') n = None).\n\n      Definition order_preserve (ord ord': OrderRuntimeState) : Prop :=\n        let order := ord_rt_order ord in\n        let order' := ord_rt_order ord' in\n        order_tokenS order = order_tokenS order' /\\\n        order_tokenB order = order_tokenB order'.\n\n      Definition orders_preserve (st st': RingSubmitterRuntimeState) : Prop :=\n        forall n,\n          (forall ord,\n              nth_error (submitter_rt_orders st) n = Some ord ->\n              exists ord', nth_error (submitter_rt_orders st') n = Some ord' /\\\n                      order_preserve ord ord') /\\\n          (nth_error (submitter_rt_orders st) n = None ->\n           nth_error (submitter_rt_orders st') n = None).\n\n    End Aux.\n\n    Section SubRing.\n\n      Definition ring_has_subrings\n                 (r: RingRuntimeState) (orders: list OrderRuntimeState) : Prop :=\n        exists p p',\n          p <> p' /\\\n          In p (ring_rt_participations r) /\\\n          In p' (ring_rt_participations r) /\\\n          forall ord ord',\n            nth_error orders (part_order_idx p) = Some ord /\\\n            nth_error orders (part_order_idx p') = Some ord' /\\\n            order_tokenS (ord_rt_order ord) = order_tokenS (ord_rt_order ord').\n\n      Definition nth_ring_has_subrings\n                 (rings: list RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n                 (n: nat) : Prop :=\n        forall r,\n          nth_error rings n = Some r ->\n          ring_has_subrings r orders.\n\n      Definition subrings_preserve (st st': RingSubmitterRuntimeState) : Prop :=\n        forall n,\n          nth_ring_has_subrings (submitter_rt_rings st) (submitter_rt_orders st) n ->\n          nth_ring_has_subrings (submitter_rt_rings st') (submitter_rt_orders st') n.\n\n    End SubRing.\n\n    Section Cancellation.\n\n      Definition nth_ring_mth_order_cancelled\n                 (wst: WorldState)\n                 (rings: list RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n                 (n m: nat) : Prop :=\n        forall r idx ord,\n          nth_error rings n = Some r ->\n          nth_error (ring_orders (ring_rt_static r)) m = Some idx ->\n          nth_error orders idx = Some ord ->\n          TradeDelegate.is_cancelled (wst_trade_delegate_state wst) (make_order_param ord) = true.\n\n      Definition ring_has_cancelled_order_preserve\n                 (wst wst': WorldState)\n                 (st st': RingSubmitterRuntimeState) : Prop :=\n        forall n m,\n          nth_ring_mth_order_cancelled wst (submitter_rt_rings st) (submitter_rt_orders st) n m ->\n          nth_ring_mth_order_cancelled wst' (submitter_rt_rings st') (submitter_rt_orders st') n m.\n\n    End Cancellation.\n\n    Section TokenMismatch.\n\n      Definition prev_ps\n                 (r: RingRuntimeState) (n: nat)\n      : option Participation :=\n        let ps := ring_rt_participations r in\n        match nth_error ps n with\n        | None => None\n        | Some _ => match n with\n                   | O => nth_error ps (length ps - 1)\n                   | S n' => nth_error ps n'\n                   end\n        end.\n\n      Definition prev_ord\n                 (r: RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n                 (n: nat)\n        : option OrderRuntimeState :=\n        match prev_ps r n with\n        | None => None\n        | Some p => nth_error orders (part_order_idx p)\n        end.\n\n      Definition has_token_mismatch_ords\n                 (r: RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n        : Prop :=\n        exists idx ord p_ord,\n          nth_error orders idx = Some ord /\\\n          prev_ord r orders idx = Some p_ord /\\\n          order_tokenS (ord_rt_order ord) <>\n          order_tokenB (ord_rt_order p_ord).\n\n      Definition nth_ring_has_token_mismatch_orders\n                 (st: RingSubmitterRuntimeState) (n: nat)\n        : Prop :=\n        exists r,\n          nth_error (submitter_rt_rings st) n = Some r /\\\n          has_token_mismatch_ords r (submitter_rt_orders st).\n\n    End TokenMismatch.\n\n    Definition st_preserve (st st': RingSubmitterRuntimeState) : Prop :=\n      rings_preserve st st' /\\\n      subrings_preserve st st' /\\\n      orders_preserve st st'.\n\n    Definition wst_preserve\n               (wst wst': WorldState)\n               (st st': RingSubmitterRuntimeState) : Prop :=\n      ring_has_cancelled_order_preserve wst wst' st st'.\n\n    Section UpdateOrdersHashes.\n\n      Fixpoint update_orders_hashes\n               (orders: list OrderRuntimeState)\n      : list OrderRuntimeState :=\n        match orders with\n        | nil => nil\n        | order :: orders' =>\n          let order' := {|\n                ord_rt_order := ord_rt_order order;\n                ord_rt_p2p := ord_rt_p2p order;\n                ord_rt_hash := get_order_hash (ord_rt_order order);\n                ord_rt_brokerInterceptor := ord_rt_brokerInterceptor order;\n                ord_rt_filledAmountS := ord_rt_filledAmountS order;\n                ord_rt_initialFilledAmountS := ord_rt_initialFilledAmountS order;\n                ord_rt_valid := ord_rt_valid order;\n              |}\n          in order' :: update_orders_hashes orders'\n        end.\n\n      Definition update_orders_hashes_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = submitter_update_orders\n                      st (update_orders_hashes (submitter_rt_orders st)) /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End UpdateOrdersHashes.\n\n    Definition update_orders_hashes_func\n               (sender: address)\n               (orders: list Order)\n               (rings: list Ring)\n               (mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         submitter_update_orders\n           st (update_orders_hashes (submitter_rt_orders st)),\n         nil).\n\n    Axiom update_orders_hashes_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (update_orders_hashes_func sender orders rings mining)\n                      (update_orders_hashes_subspec sender orders rings mining).\n\n    Section UpdateOrdersBrokersAndInterceptors.\n\n      Definition get_broker_success\n                 (wst: WorldState) (ord: OrderRuntimeState)\n                 (wst': WorldState) (retval: option address) (events: list Event)\n      : Prop :=\n        let order := ord_rt_order ord in\n        BrokerRegistry.model\n          wst\n          (msg_getBroker (wst_ring_submitter_addr wst)\n                         (order_owner order) (order_broker order))\n          wst' (RetBrokerInterceptor retval) events.\n\n      Inductive update_order_broker_interceptor\n                (wst: WorldState) (ord: OrderRuntimeState)\n        : WorldState -> OrderRuntimeState -> list Event -> Prop :=\n      | UpdateBrokerInterceptor_P2P:\n          let order := ord_rt_order ord in\n          order_broker order = O ->\n          update_order_broker_interceptor\n            wst ord wst (upd_order_broker ord (order_owner order)) nil\n\n      | UpdateBrokerInterceptor_NonP2P_registered:\n          forall wst' interceptor events,\n            get_broker_success wst ord wst' (Some interceptor) events ->\n            update_order_broker_interceptor wst ord wst' ord events\n\n      | UpdateBrokerInterceptor_NonP2P_unregistered:\n          forall wst' events,\n            get_broker_success wst ord wst' None events ->\n            update_order_broker_interceptor\n              wst ord wst' (upd_order_valid ord false) events\n      .\n\n      Inductive update_orders_broker_interceptor (wst: WorldState)\n        : list OrderRuntimeState ->\n          WorldState -> list OrderRuntimeState -> list Event -> Prop :=\n      | UpdateOrdersBrokerInterceptor_nil:\n          update_orders_broker_interceptor wst nil wst nil nil\n\n      | UpdateOrdersBrokerInterceptor_cons:\n          forall order orders wst' order' events wst'' orders' events',\n            update_order_broker_interceptor wst order wst' order' events ->\n            update_orders_broker_interceptor wst' orders wst'' orders' events' ->\n            update_orders_broker_interceptor\n              wst (order :: orders) wst'' (order' :: orders') (events ++ events')\n      .\n\n      Definition update_orders_brokers_and_interceptors_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st' /\\\n              forall wst'' orders' events,\n                update_orders_broker_interceptor\n                  wst (submitter_rt_orders st) wst'' orders' events /\\\n                wst' = wst'' /\\\n                st' = submitter_update_orders st orders'\n          ;\n\n          subspec_events :=\n            fun wst st events =>\n              (forall r, ~ In (EvtRingSkipped r) events) /\\\n              forall wst' orders' events',\n                update_orders_broker_interceptor\n                  wst (submitter_rt_orders st) wst' orders' events' /\\\n                events = events'\n          ;\n        |}.\n\n    End UpdateOrdersBrokersAndInterceptors.\n\n    Parameter update_orders_brokers_and_interceptors_func:\n      address -> list Order -> list Ring -> Mining -> SubSpec_funcT.\n    Axiom update_orders_brokers_and_interceptors_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (update_orders_brokers_and_interceptors_func sender orders rings mining)\n                      (update_orders_brokers_and_interceptors_subspec sender orders rings mining).\n\n    Section GetFilledAndCheckCancelled.\n\n      Definition batchGetFilledAndCheckCancelled_success\n                 (wst: WorldState) (st: RingSubmitterRuntimeState)\n                 (fills: list (option uint))\n                 (wst': WorldState) (events: list Event) : Prop :=\n        TradeDelegate.model\n          wst\n          (msg_batchGetFilledAndCheckCancelled\n             (wst_ring_submitter_addr wst)\n             (make_order_params (submitter_rt_orders st)))\n          wst' (RetFills fills) events.\n\n      Inductive update_order_filled_and_valid (order: OrderRuntimeState)\n        : option uint -> OrderRuntimeState -> Prop :=\n      | UpdateOrderFilledAndValid_noncancelled:\n          forall amount,\n            update_order_filled_and_valid\n              order (Some amount)\n              (upd_order_filled (upd_order_init_filled order amount) amount)\n\n      | UpdateOrderFilledAndValid_cancelled:\n          update_order_filled_and_valid order None (upd_order_valid order false)\n      .\n\n      Inductive update_orders_filled_and_valid\n        : list OrderRuntimeState (* orders in pre-state *) ->\n          list (option uint)     (* argument fills *) ->\n          list OrderRuntimeState (* orders in post-state *) ->\n          Prop :=\n      | UpdateOrdersFilledAndValid_nil:\n          update_orders_filled_and_valid nil nil nil\n\n      | UpdateOrdersFilledAndValid_cons:\n          forall order orders fill fills order' orders',\n            update_order_filled_and_valid order fill order' ->\n            update_orders_filled_and_valid orders fills orders' ->\n            update_orders_filled_and_valid\n              (order :: orders) (fill :: fills) (order' :: orders')\n      .\n\n      Definition get_filled_and_check_cancelled_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st =>\n              forall fills wst' events,\n                batchGetFilledAndCheckCancelled_success wst st fills wst' events /\\\n                length fills = length (submitter_rt_orders st)\n          ;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st' /\\\n              forall fills events,\n                batchGetFilledAndCheckCancelled_success wst st fills wst' events /\\\n                forall orders',\n                  update_orders_filled_and_valid (submitter_rt_orders st) fills orders' /\\\n                  st' = submitter_update_orders st orders'\n          ;\n\n          subspec_events :=\n            fun wst st events =>\n              (forall r, ~ In (EvtRingSkipped r) events) /\\\n              forall fills wst',\n                batchGetFilledAndCheckCancelled_success wst st fills wst' events\n          ;\n        |}.\n\n    End GetFilledAndCheckCancelled.\n\n    Parameter get_filled_and_check_cancelled_func:\n      address -> list Order -> list Ring -> Mining -> SubSpec_funcT.\n    Axiom get_filled_and_check_cancelled_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (get_filled_and_check_cancelled_func sender orders rings mining)\n                      (get_filled_and_check_cancelled_subspec sender orders rings mining).\n\n    Section CheckOrders.\n\n      Definition is_order_valid (ord: OrderRuntimeState) (now: uint) : bool :=\n        let order := ord_rt_order ord in\n        (* if order.filledAmountS == 0 then ... *)\n        (implb (Nat.eqb (ord_rt_filledAmountS ord) O)\n               ((Nat.eqb (order_version order) 0) &&\n               (negb (Nat.eqb (order_owner order) 0)) &&\n               (negb (Nat.eqb (order_tokenS order) 0)) &&\n               (negb (Nat.eqb (order_tokenB order) 0)) &&\n               (negb (Nat.eqb (order_amountS order) 0)) &&\n               (negb (Nat.eqb (order_feeToken order) 0)) &&\n               (Nat.ltb (order_feePercentage order) FEE_PERCENTAGE_BASE_N) &&\n               (Nat.ltb (order_tokenSFeePercentage order) FEE_PERCENTAGE_BASE_N) &&\n               (Nat.ltb (order_tokenBFeePercentage order) FEE_PERCENTAGE_BASE_N) &&\n               (Nat.leb (order_walletSplitPercentage order) 100) &&\n               (Nat.leb (order_validSince order) now))) &&\n        (* common check *)\n        (Nat.eqb (order_validUntil order) 0 || Nat.ltb now (order_validUntil order)) &&\n        (Z.leb (order_waiveFeePercentage order) FEE_PERCENTAGE_BASE_Z) &&\n        (Z.leb (- FEE_PERCENTAGE_BASE_Z) (order_waiveFeePercentage order)) &&\n        (Nat.eqb (order_dualAuthAddr order) 0 || Nat.ltb 0 (length (order_dualAuthSig order))) &&\n        (ord_rt_valid ord).\n\n      Fixpoint update_orders_valid (orders: list OrderRuntimeState) (now: uint)\n        : list OrderRuntimeState :=\n        match orders with\n        | nil => nil\n        | order :: orders' =>\n          upd_order_valid order (is_order_valid order now) :: update_orders_valid orders' now\n        end.\n\n      Definition is_order_p2p (ord: OrderRuntimeState) : bool :=\n        let order := ord_rt_order ord in\n        (Nat.ltb 0 (order_tokenSFeePercentage order)) ||\n        (Nat.ltb 0 (order_tokenBFeePercentage order)).\n\n      Fixpoint update_orders_p2p (orders: list OrderRuntimeState)\n        : list OrderRuntimeState :=\n        match orders with\n        | nil => nil\n        | order :: orders' =>\n          upd_order_p2p order (is_order_p2p order) :: update_orders_p2p orders'\n        end.\n\n      Definition check_orders_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st' /\\\n              let orders' := update_orders_valid\n                               (submitter_rt_orders st)\n                               (block_timestamp (wst_block_state wst)) in\n              let orders' := update_orders_p2p orders' in\n              st' = submitter_update_orders st orders'\n          ;\n\n          subspec_events :=\n            fun wst st events =>\n              events = nil;\n        |}.\n\n    End CheckOrders.\n\n    Definition check_orders_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         let orders' := update_orders_valid\n                          (submitter_rt_orders st)\n                          (block_timestamp (wst_block_state wst)) in\n         let orders' := update_orders_p2p orders' in\n         submitter_update_orders st orders',\n         nil).\n\n    Axiom check_orders_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (check_orders_func sender orders rings mining)\n                      (check_orders_subspec sender orders rings mining).\n\n    Section UpdateRingsHashes.\n\n      Fixpoint update_rings_hash\n               (rings: list RingRuntimeState) (orders: list OrderRuntimeState)\n      : list RingRuntimeState :=\n        match rings with\n        | nil => nil\n        | r :: rings' =>\n          upd_ring_hash r (get_ring_hash (ring_rt_static r) orders) ::\n          update_rings_hash rings' orders\n        end.\n\n      Definition update_rings_hash_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = submitter_update_rings\n                      st\n                      (update_rings_hash\n                         (submitter_rt_rings st) (submitter_rt_orders st)) /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End UpdateRingsHashes.\n\n    Definition update_rings_hash_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         submitter_update_rings\n           st\n           (update_rings_hash\n              (submitter_rt_rings st) (submitter_rt_orders st)),\n         nil).\n\n    Axiom update_rings_hash_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (update_rings_hash_func sender orders rings mining)\n                      (update_rings_hash_subspec sender orders rings mining).\n\n    Section UpdateMiningHash.\n\n      Definition update_mining_hash\n                 (mining: MiningRuntimeState) (rings: list RingRuntimeState)\n      : MiningRuntimeState :=\n        upd_mining_hash mining (get_mining_hash (mining_rt_static mining) rings).\n\n      Definition update_mining_hash_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = submitter_update_mining\n                      st\n                      (update_mining_hash\n                         (submitter_rt_mining st) (submitter_rt_rings st)) /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End UpdateMiningHash.\n\n    Definition update_mining_hash_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         submitter_update_mining\n           st\n           (update_mining_hash\n              (submitter_rt_mining st) (submitter_rt_rings st)),\n         nil).\n\n    Axiom update_mining_hash_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (update_mining_hash_func sender orders rings mining)\n                      (update_mining_hash_subspec sender orders rings mining).\n\n    Section UpdateMinerAndInterceptor.\n\n      Definition update_miner_interceptor (st: RingSubmitterRuntimeState) :=\n        let mining := submitter_rt_mining st in\n        let static_mining := mining_rt_static mining in\n        match mining_miner static_mining with\n        | O => submitter_update_mining\n                st (upd_mining_miner mining (mining_feeRecipient static_mining))\n        | _ => st\n        end.\n\n      Definition update_miner_interceptor_subspec\n                 (sender: address)\n                 (_orders: list Order)\n                 (_rings: list Ring)\n                 (_mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = update_miner_interceptor st /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End UpdateMinerAndInterceptor.\n\n    Definition update_miner_interceptor_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         update_miner_interceptor st,\n         nil).\n\n    Axiom update_miner_interceptor_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (update_miner_interceptor_func sender orders rings mining)\n                      (update_miner_interceptor_subspec sender orders rings mining).\n\n    Parameter verify_signature: address -> bytes32 -> bytes -> bool.\n\n    Section CheckMinerSignature.\n\n      Definition miner_signature_valid\n                 (mining: MiningRuntimeState) (sender: address) : bool :=\n        match mining_sig (mining_rt_static mining) with\n        | nil => Nat.eqb (mining_miner (mining_rt_static mining)) sender\n        | _ as sig => verify_signature (mining_miner (mining_rt_static mining))\n                                      (mining_rt_hash mining)\n                                      sig\n        end.\n\n      Definition check_miner_signature_subspec\n                 (sender: address)\n                 (_orders: list Order)\n                 (_rings: list Ring)\n                 (_mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st =>\n              miner_signature_valid (submitter_rt_mining st) sender = true;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\ st' = st /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End CheckMinerSignature.\n\n    Definition check_miner_signature_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st => (wst, st, nil).\n\n    Axiom check_miner_signature_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (check_miner_signature_func sender orders rings mining)\n                      (check_miner_signature_subspec sender orders rings mining).\n\n    Section CheckOrdersDualSig.\n\n      Fixpoint check_orders_dual_sig\n               (mining_hash: bytes32)\n               (orders: list OrderRuntimeState)\n      : list OrderRuntimeState :=\n        match orders with\n        | nil => orders\n        | ord :: orders' =>\n          let order := ord_rt_order ord in\n          let ord' :=\n              match verify_signature (order_dualAuthAddr order)\n                                     mining_hash\n                                     (order_dualAuthSig order) with\n              | true => ord\n              | false => upd_order_valid ord false\n              end\n          in ord' :: check_orders_dual_sig mining_hash orders'\n        end.\n\n      Definition check_orders_dual_sig_subspec\n                 (sender: address)\n                 (_orders: list Order)\n                 (_rings: list Ring)\n                 (_mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = submitter_update_orders\n                      st\n                      (check_orders_dual_sig (mining_rt_hash (submitter_rt_mining st))\n                                             (submitter_rt_orders st)) /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End CheckOrdersDualSig.\n\n    Definition check_orders_dual_sig_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         submitter_update_orders\n           st\n           (check_orders_dual_sig (mining_rt_hash (submitter_rt_mining st))\n                                  (submitter_rt_orders st)),\n         nil).\n\n    Axiom check_orders_dual_sig_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (check_orders_dual_sig_func sender orders rings mining)\n                      (check_orders_dual_sig_subspec sender orders rings mining).\n\n    Section CalculateFillsAndFees.\n\n      Definition get_pp (pps ps: list Participation) : option Participation :=\n        match ps with\n        | nil => None (* invalid case *)\n        | p :: ps' =>\n          match pps with\n          | nil => last_error ps\n          | _ => last_error pps\n          end\n        end.\n\n      Section PreCheckRingValid.\n\n        Inductive _ring_orders_valid\n                  (orders: list OrderRuntimeState)\n                  (pps: list Participation)\n        : list Participation -> Prop :=\n        | RingOrdersValid_nil:\n            _ring_orders_valid orders pps nil\n\n        | RingOrdersValid_cons:\n            forall p ps pp p_ord pp_ord,\n              get_pp pps ps = Some pp ->\n              nth_error orders (part_order_idx p) = Some p_ord ->\n              nth_error orders (part_order_idx pp) = Some pp_ord ->\n              ord_rt_valid p_ord = true ->\n              order_tokenS (ord_rt_order p_ord) = order_tokenB (ord_rt_order pp_ord) ->\n              _ring_orders_valid orders (pps ++ p :: nil) ps ->\n              _ring_orders_valid orders pps (p :: ps)\n        .\n\n        Definition ring_orders_valid\n                   (r: RingRuntimeState) (orders: list OrderRuntimeState) : Prop :=\n          ring_rt_valid r = true /\\\n          let ps := ring_rt_participations r in\n          1 < length ps <= 8 /\\\n          _ring_orders_valid orders nil ps.\n\n      End PreCheckRingValid.\n\n      Section InitMaxFillAmounts.\n\n        Definition _init_fill_amounts\n                   (p: Participation)\n                   (ord: OrderRuntimeState)\n                   (spendableS: Spendable)\n        : Participation :=\n          let order := ord_rt_order ord in\n          let amountS := min (spendable_amount spendableS)\n                             (order_amountS order - ord_rt_filledAmountS ord) in\n          let amountB := part_fillAmountS p * order_amountB order / order_amountS order in\n          upd_part_fillAmounts p amountS amountB.\n\n        Definition ring_init_participation_max_fill_amounts\n                   (wst: WorldState)\n                   (st: RingSubmitterRuntimeState)\n                   (r: RingRuntimeState)\n                   (lrings rrings: list RingRuntimeState)\n                   (p: Participation)\n                   (lps rps: list Participation)\n                   (wst': WorldState)\n                   (st': RingSubmitterRuntimeState)\n                   (r': RingRuntimeState)\n                   (p': Participation)\n                   (events: list Event)\n        : Prop :=\n          forall ord wst1 st1 spendableS events1 p' r',\n            nth_error (submitter_rt_orders st) (part_order_idx p) = Some ord /\\\n            get_tokenSpendableS wst st ord wst1 st1 spendableS events1 /\\\n            p' = _init_fill_amounts p ord spendableS /\\\n            r' = upd_ring_participations r (lps ++ p' :: rps) /\\\n            st' = submitter_update_rings st1 (lrings ++ r' :: rrings) /\\\n            wst' = wst1 /\\\n            events = events1.\n\n        Inductive ring_init_participations_max_fill_amounts\n                  (wst: WorldState)\n                  (st: RingSubmitterRuntimeState)\n                  (r: RingRuntimeState)\n                  (lrings rrings: list RingRuntimeState)\n                  (pps: list Participation)\n          : list Participation (* remaining participations  *) ->\n            WorldState (* post world state *) ->\n            RingSubmitterRuntimeState  (* post ring submitter state *) ->\n            RingRuntimeState (* post ring state *) ->\n            list Event (* events generated *) ->\n            Prop :=\n        | RingInitPsMaxFillAmounts_nil:\n            ring_init_participations_max_fill_amounts\n              wst st r lrings rrings pps nil wst st r nil\n\n        | RingInitPsMaxFillAmounts_cons:\n            forall p ps\n              wst1 st1 r1 p1 events1\n              wst2 st2 r2 events2,\n              ring_init_participation_max_fill_amounts\n                wst st r lrings rrings p pps ps wst1 st1 r1 p1 events1 ->\n              ring_init_participations_max_fill_amounts\n                wst1 st1 r1 lrings rrings (pps ++ p1 :: nil) ps wst2 st2 r2 events2 ->\n              ring_init_participations_max_fill_amounts\n                wst st r lrings rrings pps (p :: ps) wst2 st2 r2 (events1 ++ events2)\n        .\n\n        Definition ring_init_max_fill_amounts\n                   (wst: WorldState)\n                   (st: RingSubmitterRuntimeState)\n                   (r: RingRuntimeState)\n                   (lrings rrings: list RingRuntimeState)\n                   (wst': WorldState)\n                   (st': RingSubmitterRuntimeState)\n                   (r': RingRuntimeState)\n                   (events: list Event)\n          : Prop :=\n          ring_init_participations_max_fill_amounts\n            wst st r lrings rrings nil (ring_rt_participations r) wst' st' r' events.\n\n      End InitMaxFillAmounts.\n\n      Section AdjustFillAmounts.\n\n        (** Adjust fill amounts of `p` according to fillAmountS of `pp`.\n          If `p` is adjust, return an option value of the adjusted `p`.\n          Otherwise, return None.\n         *)\n        Definition adjust_order_fill_amounts_rev\n                   (pp p: Participation) (orders: list OrderRuntimeState)\n        : option Participation :=\n          match (nth_error orders (part_order_idx pp),\n                 nth_error orders (part_order_idx p)) with\n          | (None, _) => None (* impossible case *)\n          | (_, None) => None (* impossible case *)\n          | (Some pp_ord, Some p_ord) =>\n            let pp_tokenSFeePercentage :=\n                order_tokenSFeePercentage (ord_rt_order pp_ord) in\n            let pp_available_fillAmountS :=\n                part_fillAmountS pp * (1 - pp_tokenSFeePercentage/ FEE_PERCENTAGE_BASE_N) in\n            if Nat.ltb pp_available_fillAmountS (part_fillAmountB p) then\n              let p_order := ord_rt_order p_ord in\n              Some (upd_part_fillAmounts\n                      p\n                      (pp_available_fillAmountS * order_amountS p_order / order_amountB p_order)\n                      pp_available_fillAmountS)\n            else\n              None\n          end.\n\n        (* rem_ps starts from the second order of the order ring. *)\n        Fixpoint _adjust_orders_fill_amounts_rev_round_1\n                 (head prev: Participation)\n                 (readj_ps adj_ps rem_ps: list Participation)\n                 (orders: list OrderRuntimeState)\n          : list Participation * list Participation :=\n          match rem_ps with\n          | nil =>\n            (** have iterated over all orders, adjust the head order accordingly *)\n            match adjust_order_fill_amounts_rev prev head orders with\n            | None => match readj_ps with\n                     | nil => (readj_ps, head :: adj_ps)\n                     | _   => (head :: readj_ps, adj_ps)\n                     end\n            | Some head' => (head' :: readj_ps ++ adj_ps, nil)\n            end\n\n          | p :: rem_ps' =>\n            (** on the half way of iterating the order ring *)\n            match adjust_order_fill_amounts_rev prev p orders with\n            | None    => _adjust_orders_fill_amounts_rev_round_1\n                          head p readj_ps (adj_ps ++ p :: nil) rem_ps' orders\n            | Some p' => _adjust_orders_fill_amounts_rev_round_1\n                          head p' (readj_ps ++ adj_ps ++ p' :: nil) nil rem_ps' orders\n            end\n          end.\n\n        (** Adjust the fill amounts of an order ring.\n\n          In the process of adjustment, the order ring is separated\n          into three segments:\n          1. Adjusted and re-adjustment is required ()\n          2. Adjusted and re-adjustment is not required\n          3. Have not adjusted yet.\n\n          Return a pair of\n          - a list of orders that need to be re-adjusted\n          - a list of remaining orders that have been adjusted and do\n            not need re-adjustment.\n         *)\n        Definition adjust_orders_fill_amounts_rev_round_1\n                   (ps: list Participation) (orders: list OrderRuntimeState)\n          : list Participation * list Participation :=\n          match ps with\n          | nil => (nil, nil) (* invalid case: empty order ring *)\n          | p :: ps' =>\n            match ps' with\n            | nil => (nil, nil) (* invalid case: single-element order ring *)\n            | _ => _adjust_orders_fill_amounts_rev_round_1 p p nil nil ps' orders\n            end\n          end.\n\n        (* pending_ps starts from the second order *)\n        Fixpoint _adjust_orders_fill_amounts_rev_round_2\n                 (head prev: Participation)\n                 (adj_ps pending_ps rem_ps: list Participation)\n                 (orders: list OrderRuntimeState)\n          : list Participation :=\n          match pending_ps with\n          | nil =>\n            (** have iterated over all orders in pending_ps *)\n            match rem_ps with\n            | nil =>\n              (** pending_ps covers the entire order ring *)\n              let head' := match adjust_order_fill_amounts_rev prev head orders with\n                           | None        => head\n                           | Some head'' => head''\n                           end\n              in head' :: adj_ps ++ rem_ps\n            | _ =>\n              (** pending_ps covers only the beginning portion of order ring *)\n              head :: adj_ps ++ rem_ps\n            end\n\n          | p :: pending_ps' =>\n            (** on the half way of iterating the pending_ps *)\n            let p' := match adjust_order_fill_amounts_rev prev p orders with\n                      | None     => p\n                      | Some p'' => p''\n                      end\n            in _adjust_orders_fill_amounts_rev_round_2\n                 head p' (adj_ps ++ p' :: nil) pending_ps' rem_ps orders\n          end.\n\n        Definition adjust_orders_fill_amounts_rev_round_2\n                   (readj_ps adj_ps: list Participation)\n                   (orders: list OrderRuntimeState)\n          : list Participation :=\n          match readj_ps with\n          | nil => adj_ps\n          | p :: readj_ps' =>\n            match readj_ps' with\n            | nil => nil (* invalid case *)\n            | _   => _adjust_orders_fill_amounts_rev_round_2 p p nil readj_ps' adj_ps orders\n            end\n          end.\n\n        Definition adjust_orders_fill_amounts\n                   (ps: list Participation)\n                   (orders: list OrderRuntimeState)\n          : list Participation :=\n          match adjust_orders_fill_amounts_rev_round_1 (rev ps) orders with\n          | (readj_ps, adj_ps) =>\n            rev (adjust_orders_fill_amounts_rev_round_2 readj_ps adj_ps orders)\n          end.\n\n      End AdjustFillAmounts.\n\n      Section ReserveSpendables.\n\n        Fixpoint _reserve_orders_fillAmountS\n                 (ps: list Participation)\n                 (orders: list OrderRuntimeState)\n                 (token_spendables: TokenSpendableMap.t)\n                 (broker_spendables: BrokerSpendableMap.t)\n        : option (TokenSpendableMap.t * BrokerSpendableMap.t) :=\n          match ps with\n          | nil => Some (token_spendables, broker_spendables)\n          | p :: ps' =>\n            match nth_error orders (part_order_idx p) with\n            | None => None (* invalid case *)\n            | Some ord =>\n              let reserved := part_fillAmountS p in\n              let token_spendables' :=\n                  token_spendableS_reserved_inc token_spendables ord reserved in\n              let broker_spendables' :=\n                  match ord_rt_brokerInterceptor ord with\n                  | O => broker_spendables\n                  | _ => broker_spendableS_reserved_inc broker_spendables ord reserved\n                  end\n              in _reserve_orders_fillAmountS ps' orders token_spendables' broker_spendables'\n            end\n          end.\n\n        Definition reserve_orders_fillAmounts\n                   (st: RingSubmitterRuntimeState) (r: RingRuntimeState)\n          : RingSubmitterRuntimeState :=\n          match _reserve_orders_fillAmountS (ring_rt_participations r)\n                                            (submitter_rt_orders st)\n                                            (submitter_rt_token_spendables st)\n                                            (submitter_rt_broker_spendables st)\n          with\n          | None => st\n          | Some (token_spendables', broker_spendables') =>\n            submitter_update_broker_spendables\n              (submitter_update_token_spendables st token_spendables')\n              broker_spendables'\n          end.\n\n      End ReserveSpendables.\n\n      Section CalcFillsFees.\n\n        Definition fee_paid_in_tokenB\n                   (p: Participation) (orders: list OrderRuntimeState) : bool :=\n          match nth_error orders (part_order_idx p) with\n          | None => false (* invalid case *)\n          | Some ord =>\n            let order := ord_rt_order ord in\n            Nat.leb (order_feeAmount order * part_fillAmountS p / order_amountS order)\n                    (part_fillAmountB p) &&\n                    Nat.eqb (order_feeToken order)\n                    (order_tokenB order) &&\n                    Nat.eqb (order_owner order)\n                    (order_tokenRecipient order)\n          end.\n\n        Parameter order_get_spendableFee:\n          TokenSpendableMap.t -> BrokerSpendableMap.t -> OrderRuntimeState -> uint.\n\n        Definition insufficient_spendable\n                   (token_spendables: TokenSpendableMap.t)\n                   (broker_spendables: BrokerSpendableMap.t)\n                   (p: Participation)\n                   (ord: OrderRuntimeState)\n          : bool :=\n          let order := ord_rt_order ord in\n          Nat.ltb (order_get_spendableFee token_spendables broker_spendables ord)\n                  (order_feeAmount order * part_fillAmountS p / order_amountS order).\n\n        Definition reserve_order_fee\n                   (token_spendables: TokenSpendableMap.t)\n                   (broker_spendables: BrokerSpendableMap.t)\n                   (ord: OrderRuntimeState)\n                   (amount: uint)\n          : TokenSpendableMap.t * BrokerSpendableMap.t :=\n          let order := ord_rt_order ord in\n          let broker := order_broker order in\n          let owner := order_owner order in\n          let token := order_feeToken order in\n          let token_spendables' := token_spendableFee_reserved_inc token_spendables ord amount in\n          let broker_spendables' :=\n              match ord_rt_brokerInterceptor ord with\n              | O => broker_spendables\n              | _ => broker_spendableFee_reserved_inc broker_spendables ord amount\n              end\n          in (token_spendables', broker_spendables').\n\n        (** Update feeAmount, feeAmountS, feeAmountB and splitS of `p`\n          according to fillAmountB of `pp`. *)\n        Definition calculate_fees\n                   (pp p: Participation)\n                   (orders: list OrderRuntimeState)\n                   (token_spendables: TokenSpendableMap.t)\n                   (broker_spendables: BrokerSpendableMap.t)\n          : option (Participation *\n                    TokenSpendableMap.t *\n                    BrokerSpendableMap.t) :=\n          match nth_error orders (part_order_idx p) with\n          | None => None (* invalid case *)\n          | Some ord =>\n            let order := ord_rt_order ord in\n            let p_fillAmountS := part_fillAmountS p in\n            let p_fillAmountB := part_fillAmountB p in\n            let pp_fillAmountB := part_fillAmountB pp in\n            match ord_rt_p2p ord with\n            | true =>\n              (** P2P *)\n              let p_feeAmountS := p_fillAmountS * order_tokenSFeePercentage order / FEE_PERCENTAGE_BASE_N in\n              let p_feeAmountB := p_fillAmountB * order_tokenBFeePercentage order / FEE_PERCENTAGE_BASE_N in\n              if Nat.ltb (p_fillAmountS - p_feeAmountS) pp_fillAmountB then\n                (** p does not have sufficient token to sell *)\n                None\n              else\n                (** otherwise ... *)\n                let p_splitS := p_fillAmountS - p_feeAmountS - pp_fillAmountB in\n                Some (upd_part_fillAmountS\n                        (upd_part_splitS\n                           (upd_part_feeAmounts p 0 p_feeAmountS p_feeAmountB)\n                           p_splitS)\n                        (pp_fillAmountB + p_feeAmountS),\n                      token_spendables,\n                      broker_spendables)\n\n            | false =>\n              (** non-P2P *)\n              if fee_paid_in_tokenB p orders then\n                (** feeToken is tokenB ... *)\n                if Nat.ltb p_fillAmountS pp_fillAmountB then\n                  (** p does not have sufficient token to sell *)\n                  None\n                else\n                  (** otherwise ... *)\n                  let p_feeAmountB := order_feeAmount order * p_fillAmountS / (order_amountS order) in\n                  let p_splitS := p_fillAmountS - pp_fillAmountB in\n                  Some (upd_part_splitS\n                          (upd_part_feeAmounts p 0 0 p_feeAmountB)\n                          p_splitS,\n                        token_spendables,\n                        broker_spendables)\n              else\n                (** otherwise ... *)\n                if insufficient_spendable token_spendables broker_spendables p ord then\n                  (** p does not sufficient feeToken *)\n                  if Nat.ltb p_fillAmountS pp_fillAmountB then\n                    (** p dose not have sufficient token to sell *)\n                    None\n                  else\n                    (** p can pay fee by tokenB *)\n                    let p_feeAmountB := p_fillAmountB * order_feePercentage order / FEE_PERCENTAGE_BASE_N in\n                    let p_splitS := p_fillAmountS - pp_fillAmountB in\n                    Some (upd_part_fillAmountS\n                            (upd_part_splitS\n                               (upd_part_feeAmounts p 0 0 p_feeAmountB)\n                               p_splitS)\n                            pp_fillAmountB,\n                          token_spendables,\n                          broker_spendables)\n                else\n                  (** p has sufficient feeToken *)\n                  if Nat.ltb p_fillAmountS p_fillAmountB then\n                    (** p does not have sufficient token to sell *)\n                    None\n                  else\n                    (** otherwise ... *)\n                    let p_feeAmount := p_fillAmountB * order_feePercentage order / FEE_PERCENTAGE_BASE_N in\n                    let p_splitS := p_fillAmountS - pp_fillAmountB in\n                    match reserve_order_fee token_spendables broker_spendables ord p_feeAmount with\n                    | (token_spendables', broker_spendables') =>\n                      Some (upd_part_fillAmountS\n                              (upd_part_splitS\n                                 (upd_part_feeAmounts p p_feeAmount 0 0)\n                                 p_splitS)\n                              pp_fillAmountB,\n                            token_spendables',\n                            broker_spendables')\n                    end\n            end\n          end.\n\n        Fixpoint _calc_orders_fees_and_waive\n                 (st: RingSubmitterRuntimeState)\n                 (r: RingRuntimeState) (lrings rrings: list RingRuntimeState)\n                 (pps ps: list Participation)\n          : option (RingSubmitterRuntimeState * RingRuntimeState) :=\n          match ps with\n          | nil => Some (st, r)\n          | p :: ps' =>\n            match get_pp pps ps with\n            | None => None (* invalid case *)\n            | Some pp =>\n              let orders := submitter_rt_orders st in\n              match calculate_fees pp p orders\n                                   (submitter_rt_token_spendables st)\n                                   (submitter_rt_broker_spendables st) with\n              | None =>\n                (** `p` cannot pay fees *)\n                let r' := upd_ring_valid r false in\n                Some (submitter_update_rings st (lrings ++ r' :: rrings), r')\n              | Some (p', token_spendables', broker_spendables') =>\n                match nth_error orders (part_order_idx p') with\n                | None => None (* invalid case *)\n                | Some ord =>\n                  let waive := match order_waiveFeePercentage (ord_rt_order ord) with\n                               | Z.neg p => Z.abs_nat (Z.pos p)\n                               | _ => 0\n                               end\n                  in\n                  let pps' := pps ++ p' :: nil in\n                  let r' := inc_ring_minerFeesToOrdersPercentage\n                              (upd_ring_participations r (pps' ++ ps')) waive in\n                  let st' := submitter_update_broker_spendables\n                               (submitter_update_token_spendables\n                                  (submitter_update_rings st (lrings ++ r' :: rrings))\n                                  token_spendables')\n                               broker_spendables' in\n                  _calc_orders_fees_and_waive st' r' lrings rrings pps' ps'\n                end\n              end\n            end\n          end.\n\n        Definition calc_orders_fees_and_waive\n                   (st: RingSubmitterRuntimeState)\n                   (r: RingRuntimeState) (lrings rrings: list RingRuntimeState)\n          : option (RingSubmitterRuntimeState * RingRuntimeState) :=\n          match _calc_orders_fees_and_waive st r lrings rrings nil (ring_rt_participations r) with\n          | None => None\n          | Some (st', r') =>\n            if Nat.ltb FEE_PERCENTAGE_BASE_N\n                       (ring_minerFeesToOrdersPercentage (ring_rt_static r')) then\n              let r'' := upd_ring_valid r' false in\n              Some (submitter_update_rings st' (lrings ++ r'' :: rrings), r'')\n            else\n              Some (st', r')\n          end.\n\n        Fixpoint clear_orders_reservations\n                 (st: RingSubmitterRuntimeState) (ps: list Participation)\n          : option RingSubmitterRuntimeState :=\n          match ps with\n          | nil => Some st\n          | p :: ps' =>\n            match nth_error (submitter_rt_orders st) (part_order_idx p) with\n            | None => None (* invalid case *)\n            | Some ord => clear_orders_reservations (clear_order_spendables_reserved st ord) ps'\n            end\n          end.\n\n        Definition calculate_fill_amount_and_fee\n                   (wst: WorldState)\n                   (st: RingSubmitterRuntimeState)\n                   (r: RingRuntimeState)\n                   (lrings rrings: list RingRuntimeState)\n                   (wst': WorldState)\n                   (st': RingSubmitterRuntimeState)\n                   (r': RingRuntimeState)\n                   (events: list Event) : Prop :=\n          forall wst1 st1 r1 events1\n            wst2 st2 r2 events2\n            wst3 st3 r3 events3\n            wst4 st4 r4 events4\n            wst5 st5 r5 events5,\n            (* init *)\n            ring_init_max_fill_amounts wst st r lrings rrings wst1 st1 r1 events1 /\\\n            (* adjust fill amounts *)\n            r2 = upd_ring_participations\n                   r1\n                   (adjust_orders_fill_amounts (ring_rt_participations r1)\n                                               (submitter_rt_orders st1)) /\\\n            st2 = submitter_update_rings st1 (lrings ++ r2 :: rrings) /\\\n            wst2 = wst1 /\\\n            events2 = nil /\\\n            (* reserve fill amountS *)\n            st3 = reserve_orders_fillAmounts st2 r2 /\\\n            r3 = r2 /\\\n            wst3 = wst2 /\\\n            events3 = nil /\\\n            (* calc fees and waive *)\n            calc_orders_fees_and_waive st3 r3 lrings rrings = Some (st4, r4) /\\\n            wst4 = wst3 /\\\n            events4 = nil /\\\n            (* clear reservations *)\n            clear_orders_reservations st4 (ring_rt_participations r4) = Some st5 /\\\n            r5 = r4 /\\\n            wst5 = wst4 /\\\n            events5 = nil /\\\n            (* final *)\n            wst' = wst5 /\\ st' = st5 /\\ r' = r5 /\\ events = events1 ++ events2 ++ events3 ++ events4 ++ events5.\n\n      End CalcFillsFees.\n\n      Definition adjust_order_state\n                 (p: Participation)\n                 (ord: OrderRuntimeState)\n                 (token_spendables: TokenSpendableMap.t)\n                 (broker_spendables: BrokerSpendableMap.t)\n        : OrderRuntimeState * TokenSpendableMap.t * BrokerSpendableMap.t :=\n        let filled_amount := part_fillAmountS p + part_splitS p in\n        let fee_amount := part_feeAmount p in\n        let ord' := upd_order_filled ord filled_amount in\n        let token_spendables' :=\n            token_spendableFee_amount_dec\n              (token_spendableS_amount_dec token_spendables ord filled_amount)\n              ord fee_amount in\n        let broker_spendables' :=\n            match ord_rt_brokerInterceptor ord with\n            | O => broker_spendables\n            | _ =>\n              broker_spendableFee_amount_dec\n                (broker_spendableS_amount_dec broker_spendables ord filled_amount)\n                ord fee_amount\n            end\n        in (ord', token_spendables, broker_spendables).\n\n      Fixpoint _adjust_orders_state\n               (ps: list Participation)\n               (orders: list OrderRuntimeState)\n               (token_spendables: TokenSpendableMap.t)\n               (broker_spendables: BrokerSpendableMap.t)\n        : option (list OrderRuntimeState * TokenSpendableMap.t * BrokerSpendableMap.t) :=\n        match ps with\n        | nil => Some (orders, token_spendables, broker_spendables)\n        | p :: ps' =>\n          let ord_idx := part_order_idx p in\n          match nth_error orders ord_idx with\n          | None => None (* invalid case *)\n          | Some ord =>\n            match adjust_order_state p ord token_spendables broker_spendables with\n            | (ord', token_spendables', broker_spendables') =>\n              match alt_nth orders ord_idx ord' with\n              | None => None (* invalid case *)\n              | Some orders' => _adjust_orders_state\n                                 ps' orders' token_spendables' broker_spendables'\n              end\n            end\n          end\n        end.\n\n      Definition adjust_orders_state\n                 (st: RingSubmitterRuntimeState) (r: RingRuntimeState)\n        : option RingSubmitterRuntimeState :=\n        match _adjust_orders_state\n                (ring_rt_participations r)\n                (submitter_rt_orders st)\n                (submitter_rt_token_spendables st)\n                (submitter_rt_broker_spendables st) with\n        | None => None (* invalid case *)\n        | Some (orders', token_spendables', broker_spendables') =>\n          Some (submitter_update_broker_spendables\n                  (submitter_update_token_spendables\n                     (submitter_update_orders st orders')\n                     token_spendables')\n                  broker_spendables')\n        end.\n\n      Inductive _rings_check_and_calc_fills_fees\n                (wst: WorldState)\n                (st: RingSubmitterRuntimeState)\n        : list RingRuntimeState (* rings that have been checked and updated *) ->\n          list RingRuntimeState (* rings that have not been checked and updated *) ->\n          WorldState (* post world state *) ->\n          RingSubmitterRuntimeState (* post ring submitter state *) ->\n          list Event ->\n          Prop :=\n      | RingsCheckAndCalcFillsFees_nil:\n          _rings_check_and_calc_fills_fees wst st (submitter_rt_rings st) nil wst st nil\n\n      | RingsCheckAndCalcFillsFees_valid_cons:\n          forall lrings r rrings wst' st' r' events st'' wst''' st''' events',\n            submitter_rt_rings st = lrings ++ r :: rrings ->\n            ring_orders_valid r (submitter_rt_orders st) ->\n            ~ ring_has_subrings r (submitter_rt_orders st) ->\n            calculate_fill_amount_and_fee wst st r lrings rrings wst' st' r' events ->\n            adjust_orders_state st' r' = Some st'' ->\n            _rings_check_and_calc_fills_fees wst' st'' (lrings ++ r' :: nil) rrings wst''' st''' events' ->\n            _rings_check_and_calc_fills_fees wst st lrings (r :: rrings) wst''' st''' (events ++ events')\n\n      | RingsCheckAndCalcFillsFees_invalid_cons:\n          forall lrings r rrings r' wst'' st'' events,\n            submitter_rt_rings st = lrings ++ r :: rrings ->\n            (~ ring_orders_valid r (submitter_rt_orders st) \\/ ring_has_subrings r (submitter_rt_orders st)) ->\n            r' = upd_ring_valid r false ->\n            _rings_check_and_calc_fills_fees\n              wst (submitter_update_rings st (lrings ++ r' :: rrings))\n              (lrings ++ r' :: nil) rrings wst'' st'' events ->\n            _rings_check_and_calc_fills_fees wst st lrings (r :: rrings) wst'' st'' events\n      .\n\n      Definition calc_fills_and_fees_subspec\n                 (sender: address)\n                 (_orders: list Order)\n                 (_rings: list Ring)\n                 (_mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st' /\\\n              forall events,\n                _rings_check_and_calc_fills_fees\n                  wst st nil (submitter_rt_rings st) wst' st' events\n          ;\n\n          subspec_events :=\n            fun wst st events =>\n              forall r, ~ In (EvtRingSkipped r) events /\\\n              forall wst'' st'',\n                _rings_check_and_calc_fills_fees\n                  wst st nil (submitter_rt_rings st) wst'' st'' events\n          ;\n        |}.\n\n    End CalculateFillsAndFees.\n\n    Parameter calc_fills_and_fees_func:\n      address -> list Order -> list Ring -> Mining -> SubSpec_funcT.\n    Axiom calc_fills_and_fees_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (calc_fills_and_fees_func sender orders rings mining)\n                      (calc_fills_and_fees_subspec sender orders rings mining).\n\n    Section ValidateAllOrNone.\n\n      Fixpoint validate_AllOrNone (orders: list OrderRuntimeState)\n      : list OrderRuntimeState :=\n        match orders with\n        | nil => nil\n        | ord :: orders' =>\n          let order := ord_rt_order ord in\n          let ord' := match order_allOrNone order with\n                      | true => if Nat.eqb (ord_rt_filledAmountS ord)\n                                          (order_amountS (ord_rt_order ord)) then\n                                 ord\n                               else\n                                 upd_order_valid ord false\n                      | false => ord\n                      end\n          in ord' :: validate_AllOrNone orders'\n        end.\n\n      Definition validate_AllOrNone_subspec\n                 (sender: address)\n                 (_orders: list Order)\n                 (_rings: list Ring)\n                 (_mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st => True;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              wst' = wst /\\\n              st' = submitter_update_orders\n                      st (validate_AllOrNone (submitter_rt_orders st)) /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st';\n\n          subspec_events :=\n            fun wst st events => events = nil;\n        |}.\n\n    End ValidateAllOrNone.\n\n    Definition validate_AllOrNone_func\n               (sender: address)\n               (_orders: list Order)\n               (_rings: list Ring)\n               (_mining: Mining)\n      : SubSpec_funcT :=\n      fun wst st =>\n        (wst,\n         submitter_update_orders\n           st (validate_AllOrNone (submitter_rt_orders st)),\n         nil).\n\n    Axiom validate_AllOrNone_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (validate_AllOrNone_func sender orders rings mining)\n                      (validate_AllOrNone_subspec sender orders rings mining).\n\n    Section CalculatePayments.\n\n      Definition get_fees_p2p_nowallet\n                 (ord: OrderRuntimeState) (total: uint) : Fees :=\n        {|\n          fee_wallet      := 0;\n          fee_miner       := 0;\n          fee_wallet_burn := 0;\n          fee_miner_burn  := 0;\n          fee_refund_base := 0;\n          fee_rebate      := total;\n        |}.\n\n      Definition get_fees_others\n                 (ord: OrderRuntimeState)\n                 (total burn_rate wallet_percentage refund_percentage: uint)\n        : Fees :=\n        let order := ord_rt_order ord in\n        let wallet_fee_total := total * wallet_percentage / 100 in\n        let wallet_fee := wallet_fee_total * (1 - burn_rate / FEE_PERCENTAGE_BASE_N) in\n        let wallet_fee_burn := wallet_fee_total * burn_rate / FEE_PERCENTAGE_BASE_N in\n        match order_waiveFeePercentage order with\n        | Z.neg _ =>\n          {|\n            fee_wallet      := wallet_fee;\n            fee_wallet_burn := wallet_fee_burn;\n            fee_miner       := 0;\n            fee_miner_burn  := 0;\n            fee_refund_base := 0;\n            fee_rebate      := total - wallet_fee - wallet_fee_burn;\n          |}\n        | _ =>\n          let miner_fee_total := total * (1 - wallet_percentage / 100) in\n          let miner_fee_burn := miner_fee_total * burn_rate / FEE_PERCENTAGE_BASE_N in\n          let miner_fee_base := miner_fee_total * (1 - burn_rate / FEE_PERCENTAGE_BASE_N) in\n          let miner_fee := miner_fee_base * (1 - refund_percentage / FEE_PERCENTAGE_BASE_N) in\n          {|\n            fee_wallet      := wallet_fee;\n            fee_wallet_burn := wallet_fee_burn;\n            fee_miner       := miner_fee;\n            fee_miner_burn  := miner_fee_burn;\n            fee_refund_base := miner_fee_base;\n            fee_rebate      := total - wallet_fee - wallet_fee_burn - miner_fee - miner_fee_burn;\n          |}\n        end.\n\n      Parameter get_token_rate: address -> uint.\n\n      Definition get_fees_for_order\n                 (ord: OrderRuntimeState) (total: uint) (token: address)\n                 (refund_percentage: uint)\n        : Fees :=\n        let order := ord_rt_order ord in\n        let p2p := ord_rt_p2p ord in\n        let zero_wallet := Nat.eqb (order_wallet order) 0 in\n        if p2p && zero_wallet  then\n          get_fees_p2p_nowallet ord total\n        else\n          let wallet_percentage := if p2p then\n                                     100\n                                   else\n                                     if zero_wallet then\n                                       0\n                                     else\n                                       order_walletSplitPercentage order in\n          get_fees_others ord total (get_token_rate token)\n                          wallet_percentage refund_percentage.\n\n      Definition get_fees_for_participation\n                 (p: Participation) (orders: list OrderRuntimeState)\n                 (refund_percentage: uint)\n        : option Participation :=\n        match nth_error orders (part_order_idx p) with\n        | None => None (* invalid case *)\n        | Some ord =>\n          let order := ord_rt_order ord in\n          Some (upd_part_fees\n                  p\n                  (get_fees_for_order ord (part_feeAmount p) (order_feeToken order) refund_percentage)\n                  (get_fees_for_order ord (part_feeAmountS p) (order_tokenS order) refund_percentage)\n                  (get_fees_for_order ord (part_feeAmountB p) (order_tokenB order) refund_percentage))\n        end.\n\n      Fixpoint get_fees_for_participations\n               (ps: list Participation) (orders: list OrderRuntimeState)\n               (refund_percentage: uint)\n        : option (list Participation) :=\n        match ps with\n        | nil => Some nil\n        | p :: ps' =>\n          match get_fees_for_participation p orders refund_percentage with\n          | None => None (* invalid case *)\n          | Some p' =>\n            match get_fees_for_participations ps' orders refund_percentage with\n            | None => None (* invalid case *)\n            | Some ps' => Some (p' :: ps')\n            end\n          end\n        end.\n\n      Definition get_fees_for_ring\n                 (r: RingRuntimeState) (orders: list OrderRuntimeState)\n        : option RingRuntimeState :=\n        match get_fees_for_participations\n                (ring_rt_participations r)\n                orders\n                (ring_minerFeesToOrdersPercentage (ring_rt_static r)) with\n        | None => None (* invalid case *)\n        | Some ps' => Some (upd_ring_participations r ps')\n        end.\n\n      Fixpoint make_miner_fee_refund_payments\n               (base: uint)\n               (_p: Participation)\n               (ps: list Participation)\n               (orders: list OrderRuntimeState)\n               (token: address)\n        : option (list FeeBalanceParam) :=\n        let _p_ord_idx := part_order_idx _p in\n        match ps with\n        | nil => Some nil\n        | p :: ps' =>\n          let p_ord_idx := part_order_idx p in\n          match Nat.eqb p_ord_idx _p_ord_idx with\n          | true => make_miner_fee_refund_payments base _p ps' orders token\n          | false =>\n            match nth_error orders p_ord_idx with\n            | None => None (* invalid case *)\n            | Some ord =>\n              let order := ord_rt_order ord in\n              let waive_percentage := order_waiveFeePercentage order in\n              match waive_percentage with\n              | Z.neg _ =>\n                let payment := {| feeblncs_token := token;\n                                  feeblncs_owner := order_owner order;\n                                  feeblncs_value := base * (Z.abs_nat waive_percentage) / FEE_PERCENTAGE_BASE_N;\n                               |} in\n                match make_miner_fee_refund_payments base _p ps' orders token with\n                | None => None (* invalid case *)\n                | Some payments => Some (payment :: payments)\n                end\n              | _ => make_miner_fee_refund_payments base _p ps' orders token\n              end\n            end\n          end\n        end.\n\n      Definition _make_feepayments\n                 (fees: Fees)\n                 (p: Participation)\n                 (ps: list Participation)\n                 (orders: list OrderRuntimeState)\n                 (token wallet: address)\n                 (fee_holder_addr miner_fee_recipient: address)\n        : option (list FeeBalanceParam) :=\n        match fees with\n        | Build_Fees wallet_fee miner_fee wallet_fee_burn miner_fee_burn refund_base rebate =>\n          let wallet_fee_pay := {| feeblncs_token := token;\n                                   feeblncs_owner := wallet;\n                                   feeblncs_value := wallet_fee;\n                                |} in\n          let burn_pay := {| feeblncs_token := token;\n                             feeblncs_owner := fee_holder_addr;\n                             feeblncs_value := wallet_fee_burn + miner_fee_burn;\n                          |} in\n          let miner_fee_pay := {| feeblncs_token := token;\n                                  feeblncs_owner := miner_fee_recipient;\n                                  feeblncs_value := miner_fee;\n                               |} in\n          match make_miner_fee_refund_payments refund_base p ps orders token with\n          | None => None (* invalid case *)\n          | Some miner_fee_refund_pays =>\n            Some (wallet_fee_pay :: burn_pay :: miner_fee_pay :: miner_fee_refund_pays)\n          end\n        end.\n\n      Definition make_feepayments_for_participation\n                 (p: Participation)\n                 (ps: list Participation)\n                 (orders: list OrderRuntimeState)\n                 (fee_holder_addr miner_fee_recipient: address)\n        : option (list FeeBalanceParam) :=\n        match nth_error orders (part_order_idx p) with\n        | None => None (* invalid case *)\n        | Some ord =>\n          let order := ord_rt_order ord in\n          let wallet := order_wallet order in\n          match _make_feepayments (part_fee p) p ps orders\n                                  (order_feeToken order) wallet\n                                  fee_holder_addr miner_fee_recipient with\n          | None => None (* invalid case *)\n          | Some fee_payments =>\n            match _make_feepayments (part_feeS p) p ps orders\n                                    (order_tokenS order) wallet\n                                    fee_holder_addr miner_fee_recipient with\n            | None => None (* invalid case *)\n            | Some feeS_payments =>\n              match _make_feepayments (part_feeB p) p ps orders\n                                      (order_tokenB order) wallet\n                                      fee_holder_addr miner_fee_recipient with\n              | None => None (* invalid case *)\n              | Some feeB_payments => Some (fee_payments ++ feeS_payments ++ feeB_payments)\n              end\n            end\n          end\n        end.\n\n      Fixpoint make_feepayments_for_participations\n               (pps ps: list Participation)\n               (orders: list OrderRuntimeState)\n               (fee_holder_addr miner_fee_recipient: address)\n        : option (list FeeBalanceParam) :=\n        match ps with\n        | nil => Some nil\n        | p :: ps' =>\n          match make_feepayments_for_participation\n                  p (pps ++ ps) orders\n                  fee_holder_addr miner_fee_recipient with\n          | None => None (* invalid case *)\n          | Some payments =>\n            match make_feepayments_for_participations\n                    (pps ++ p :: nil) ps' orders\n                    fee_holder_addr miner_fee_recipient with\n            | None => None (*invalid case *)\n            | Some payments' => Some (payments ++ payments')\n            end\n          end\n        end.\n\n      Definition make_feepayments_for_ring\n                 (r: RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n                 (fee_holder_addr miner_fee_recipient: address)\n        : option (list FeeBalanceParam) :=\n        make_feepayments_for_participations\n          nil (ring_rt_participations r) orders fee_holder_addr miner_fee_recipient.\n\n      Definition make_tokenpayments_for_participation\n                 (pp p: Participation)\n                 (orders: list OrderRuntimeState)\n                 (fee_holder_addr miner_fee_recipient: address)\n        : option (list TransferParam) :=\n        match (nth_error orders (part_order_idx pp),\n               nth_error orders (part_order_idx p)) with\n        | (None, _) => None (* invalid case *)\n        | (_, None) => None (* invalid case *)\n        | (Some pp_ord, Some p_ord) =>\n          let p_order := ord_rt_order p_ord in\n          let pp_order := ord_rt_order pp_ord in\n          let p_fillAmountS := part_fillAmountS p in\n          let p_feeAmount := part_feeAmount p in\n          let p_feeAmountS := part_feeAmountS p in\n          let p_rebateFee := fee_rebate (part_fee p) in\n          let p_rebateS := fee_rebate (part_feeS p) in\n          let pp_feeAmountB := part_feeAmountB pp in\n          let pp_rebateB := fee_rebate (part_feeB pp) in\n          let splitS_payment := {| transfer_token  := order_tokenS p_order;\n                                   transfer_from   := order_owner p_order;\n                                   transfer_to     := miner_fee_recipient;\n                                   transfer_amount := part_splitS p;\n                                |} in\n          let buyerS_payment := {| transfer_token  := order_tokenS p_order;\n                                   transfer_from   := order_owner p_order;\n                                   transfer_to     := order_tokenRecipient pp_order;\n                                   transfer_amount := p_fillAmountS - p_feeAmountS -\n                                                      (pp_feeAmountB - pp_rebateB);\n                                |} in\n          let (holderFee_payment, holderS_payment) :=\n              if Nat.eqb (order_tokenS p_order) (order_feeToken p_order) then\n                (\n                  {|\n                    transfer_token  := order_feeToken p_order;\n                    transfer_from   := order_owner p_order;\n                    transfer_to     := fee_holder_addr;\n                    transfer_amount := 0;\n                  |},\n\n                  {|\n                    transfer_token  := order_tokenS p_order;\n                    transfer_from   := order_owner p_order;\n                    transfer_to     := fee_holder_addr;\n                    transfer_amount := p_feeAmountS - p_rebateS +\n                                       (pp_feeAmountB - pp_rebateB) +\n                                       (p_feeAmount - p_rebateFee);\n                  |}\n                )\n              else\n                (\n                  {|\n                    transfer_token  := order_feeToken p_order;\n                    transfer_from   := order_owner p_order;\n                    transfer_to     := fee_holder_addr;\n                    transfer_amount := p_feeAmount - p_rebateFee;\n                  |},\n\n                  {|\n                    transfer_token  := order_tokenS p_order;\n                    transfer_from   := order_owner p_order;\n                    transfer_to     := fee_holder_addr;\n                    transfer_amount := p_feeAmountS - p_rebateS +\n                                       (pp_feeAmountB - pp_rebateB);\n                  |}\n                )\n          in Some (splitS_payment :: buyerS_payment :: holderFee_payment :: holderS_payment :: nil)\n        end.\n\n      Fixpoint make_tokenpayments_for_participations\n               (pps ps: list Participation)\n               (orders: list OrderRuntimeState)\n               (fee_holder_addr miner_fee_recipient: address)\n        : option (list TransferParam) :=\n        match ps with\n        | nil => Some nil\n        | p :: ps' =>\n          match get_pp pps ps with\n          | None => None (* invalid case *)\n          | Some pp =>\n            match make_tokenpayments_for_participation\n                    pp p orders fee_holder_addr miner_fee_recipient with\n            | None => None (* invalid case *)\n            | Some payments =>\n              match make_tokenpayments_for_participations\n                      (pps ++ p :: nil) ps' orders\n                      fee_holder_addr miner_fee_recipient with\n              | None => None (* invalid case *)\n              | Some payments' => Some (payments ++ payments')\n              end\n            end\n          end\n        end.\n\n      Definition make_tokenpayments_for_ring\n                 (r: RingRuntimeState)\n                 (orders: list OrderRuntimeState)\n                 (fee_holder_addr miner_fee_recipient: address)\n        : option (list TransferParam) :=\n        make_tokenpayments_for_participations\n          nil (ring_rt_participations r) orders fee_holder_addr miner_fee_recipient.\n\n      Fixpoint make_payments_for_rings\n               (rings: list RingRuntimeState)\n               (orders: list OrderRuntimeState)\n               (fee_holder_addr miner_fee_recipient: address)\n        : list FeeBalanceParam * list TransferParam * list Event :=\n        match rings with\n        | nil => (nil, nil, nil)\n        | r :: rings' =>\n          let '(fee_payments, token_payments, events) :=\n              match get_fees_for_ring r orders with\n              | None => (nil, nil, EvtRingSkipped (ring_rt_static r) :: nil)\n              | Some r' =>\n                match (make_feepayments_for_ring\n                         r' orders fee_holder_addr miner_fee_recipient,\n                       make_tokenpayments_for_ring\n                         r' orders fee_holder_addr miner_fee_recipient) with\n                | (None, _) => (nil, nil, EvtRingSkipped (ring_rt_static r) :: nil)\n                | (_, None) => (nil, nil, EvtRingSkipped (ring_rt_static r) :: nil)\n                | (Some fps, Some tps) => (fps, tps, nil)\n                end\n              end\n          in\n          match make_payments_for_rings\n                  rings' orders fee_holder_addr miner_fee_recipient with\n          | (fee_payments', token_payments', events') =>\n            (fee_payments ++ fee_payments',\n             token_payments ++ token_payments',\n             events ++ events')\n          end\n        end.\n\n      Definition make_payments (wst: WorldState) (st: RingSubmitterRuntimeState)\n        : list FeeBalanceParam * list TransferParam * list Event :=\n        make_payments_for_rings (submitter_rt_rings st)\n                                (submitter_rt_orders st)\n                                (wst_feeholder_addr wst)\n                                (mining_feeRecipient\n                                   (mining_rt_static (submitter_rt_mining st))).\n\n    End CalculatePayments.\n\n    Section MakePayments.\n\n      Fixpoint sum_transfer_amount\n               (ts: list TransferParam) (token from to: address)\n      : uint :=\n        match ts with\n        | nil => 0\n        | t :: ts' =>\n          match t with\n          | mk_transfer_param t_token t_from t_to t_amount =>\n            if Nat.eqb t_token token &&\n               Nat.eqb t_from from &&\n               Nat.eqb t_to to then\n              t_amount + sum_transfer_amount ts' token from to\n            else\n              sum_transfer_amount ts' token from to\n          end\n        end.\n\n      Fixpoint sum_fee_amount\n               (fs: list FeeBalanceParam) (token owner: address)\n        : uint :=\n        match fs with\n        | nil => 0\n        | f :: fs' =>\n          match f with\n          | mk_fee_balance_param f_token f_owner f_amount =>\n            if Nat.eqb f_token token &&\n               Nat.eqb f_owner owner then\n              f_amount + sum_fee_amount fs' token owner\n            else\n              sum_fee_amount fs' token owner\n          end\n        end.\n\n      Definition calc_and_make_payments_require\n                 (fee_payments: list FeeBalanceParam)\n                 (token_payments: list TransferParam) : Prop :=\n        (forall token from to,\n            sum_transfer_amount token_payments token from to < MAX_UINT256) /\\\n        (forall token owner,\n            sum_fee_amount fee_payments token owner < MAX_UINT256).\n\n      Definition calc_and_make_payments\n                 (wst: WorldState) (st: RingSubmitterRuntimeState)\n                 (wst': WorldState) (events: list Event)\n        : Prop :=\n        forall fee_payments token_payments events0\n          wst1 events1 wst2 events2,\n          make_payments wst st = (fee_payments, token_payments, events0) /\\\n          TradeDelegate.model\n            wst (msg_batchTransfer (wst_ring_submitter_addr wst) token_payments)\n            wst1 RetNone events1 /\\\n          FeeHolder.model\n            wst1 (msg_batchAddFeeBalances (wst_ring_submitter_addr wst) fee_payments)\n            wst2 RetNone events2 /\\\n          wst' = wst2 /\\ events = events0 ++ events1 ++ events2.\n\n      Definition calc_and_make_payments_subspec\n                 (sender: address)\n                 (orders: list Order)\n                 (rings: list Ring)\n                 (mining: Mining) :=\n        {|\n          subspec_require :=\n            fun wst st =>\n              exists fee_payments token_payments events,\n                make_payments wst st = (fee_payments, token_payments, events) /\\\n                calc_and_make_payments_require fee_payments token_payments\n          ;\n\n          subspec_trans :=\n            fun wst st wst' st' =>\n              st' = st /\\\n              st_preserve st st' /\\\n              wst_preserve wst wst' st st' /\\\n              forall events,\n                calc_and_make_payments wst st wst' events\n          ;\n\n          subspec_events :=\n            fun wst st events =>\n              (forall n r,\n                  nth_ring_has_subrings\n                    (submitter_rt_rings st) (submitter_rt_orders st) n ->\n                  nth_error (submitter_rt_rings st) n = Some r ->\n                  In (EvtRingSkipped (ring_rt_static r)) events\n              ) /\\\n              (forall n m r,\n                  nth_ring_mth_order_cancelled\n                    wst (submitter_rt_rings st) (submitter_rt_orders st) n m ->\n                  nth_error (submitter_rt_rings st) n = Some r ->\n                  In (EvtRingSkipped (ring_rt_static r)) events\n              ) /\\\n              (forall n r,\n                  nth_ring_has_token_mismatch_orders st n ->\n                  nth_error (submitter_rt_rings st) n = Some r ->\n                  In (EvtRingSkipped (ring_rt_static r)) events\n              ) /\\\n              forall wst',\n                calc_and_make_payments wst st wst' events\n          ;\n        |}.\n\n    End MakePayments.\n\n    Parameter calc_and_make_payments_func:\n      address -> list Order -> list Ring -> Mining -> SubSpec_funcT.\n    Axiom calc_and_make_payments_func_subspec:\n      forall sender orders rings mining,\n        funcT_subspec (calc_and_make_payments_func sender orders rings mining)\n                      (calc_and_make_payments_subspec sender orders rings mining).\n\n\n    Inductive SubmitRingsSubSpec : Type :=\n    | SubmitRingsSubSpec_single (subspec: address -> list Order -> list Ring -> Mining -> SubSpec)\n    | SubmitRingsSubSpec_seq (subspec subspec': SubmitRingsSubSpec)\n    .\n\n    Notation \"<| s |>\" := (SubmitRingsSubSpec_single s).\n    Notation \"s ';;' s'\" := (SubmitRingsSubSpec_seq s s') (right associativity, at level 400).\n\n    Inductive SubmitRingsSubSpec_sat\n              (sender: address)\n              (orders: list Order)\n              (rings: list Ring)\n              (mining: Mining)\n      : WorldState -> RingSubmitterRuntimeState ->\n        WorldState -> RingSubmitterRuntimeState -> list Event ->\n        SubmitRingsSubSpec -> Prop :=\n    | SubmitRingsSubSpec_single_sat:\n        forall subspec wst st wst' st' events,\n          subspec_require (subspec sender orders rings mining) wst st ->\n          subspec_trans (subspec sender orders rings mining) wst st wst' st' ->\n          subspec_events (subspec sender orders rings mining) wst st events ->\n          SubmitRingsSubSpec_sat sender orders rings mining\n                                 wst st wst' st' events\n                                 (SubmitRingsSubSpec_single subspec)\n\n    | SubmitRingsSubSpec_seq_sat:\n        forall subspec subspec' wst st wst' st' wst'' st'' events events',\n          SubmitRingsSubSpec_sat sender orders rings mining wst st wst' st' events subspec ->\n          SubmitRingsSubSpec_sat sender orders rings mining wst' st' wst'' st'' events' subspec' ->\n          SubmitRingsSubSpec_sat sender orders rings mining\n                                 wst st wst'' st'' (events ++ events')\n                                 (SubmitRingsSubSpec_seq subspec subspec')\n    .\n\n    Definition submitRings_spec :=\n       (<| update_orders_hashes_subspec |> ;;\n        <| update_orders_brokers_and_interceptors_subspec |> ;;\n        <| get_filled_and_check_cancelled_subspec |> ;;\n        <| check_orders_subspec |> ;;\n        <| update_rings_hash_subspec |> ;;\n        <| update_mining_hash_subspec |> ;;\n        <| update_miner_interceptor_subspec |> ;;\n        <| check_miner_signature_subspec |> ;;\n        <| check_orders_dual_sig_subspec |> ;;\n        <| calc_fills_and_fees_subspec |> ;;\n        <| validate_AllOrNone_subspec |> ;;\n        <| calc_and_make_payments_subspec |>).\n\n  End SubmitRings.\n\n  Definition model\n             (wst: WorldState)\n             (msg: RingSubmitterMsg)\n             (wst': WorldState)\n             (retval: RetVal)\n             (events: list Event)\n    : Prop :=\n    retval = RetNone /\\\n    exists st',\n    forall sender orders rings mining,\n      msg = msg_submitRings sender orders rings mining /\\\n      SubmitRingsSubSpec_sat sender orders rings mining\n                             wst (make_rt_submitter_state mining orders rings)\n                             wst' st' events\n                             submitRings_spec.\n\nEnd RingSubmitter.\n", "meta": {"author": "sec-bit", "repo": "loopring-protocol2-verification", "sha": "bfb2101faccbefd592a8f63d42e01aae41b06930", "save_path": "github-repos/coq/sec-bit-loopring-protocol2-verification", "path": "github-repos/coq/sec-bit-loopring-protocol2-verification/loopring-protocol2-verification-bfb2101faccbefd592a8f63d42e01aae41b06930/Models/RingSubmitter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.15398410602305176}}
{"text": "(******************************************************************************)\n(** Definition of OCaml program                                               *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nRequire Import Omega.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import Prog.\nRequire Import ProgToExecution.\nRequire Import ProgToExecutionProperties.\nFrom PromisingLib Require Import Basic Loc.\nRequire Import Basics. \nSet Implicit Arguments.\n\n\nSection OCaml_Program.\n\n  (** The difference between Oistep_ and istep_ is the dindex parameter which allows to skip some indices *)\n  (** Such gaps allow to construct a graph whose structure resembles one of IMM graph without fences *)\n  \n  Inductive Oistep_ tid labels s1 s2 instr dindex: Prop :=\n  | Oassign reg expr\n           (LABELS : labels = nil)\n           (II : instr = Instr.assign reg expr)\n           (UPC : s2.(pc) = s1.(pc) + 1)\n           (UG : s2.(G) = s1.(G))\n           (UINDEX : s2.(eindex) = s1.(eindex))\n           (UREGS : s2.(regf) = RegFun.add reg (RegFile.eval_expr s1.(regf) expr) s1.(regf))\n           (UDEPS : s2.(depf) = RegFun.add reg (DepsFile.expr_deps s1.(depf) expr) s1.(depf))\n           (UECTRL : s2.(ectrl) = s1.(ectrl))\n  | Oif_ expr shift\n        (LABELS : labels = nil)\n        (II : instr = Instr.ifgoto expr shift)\n        (UPC   : if Const.eq_dec (RegFile.eval_expr s1.(regf) expr) 0\n                 then s2.(pc) = s1.(pc) + 1\n                 else s2.(pc) = shift)\n        (UG    : s2.(G) = s1.(G))\n        (UINDEX : s2.(eindex) = s1.(eindex))\n        (UREGS : s2.(regf) = s1.(regf))\n        (UDEPS : s2.(depf) = s1.(depf))\n        (UECTRL : s2.(ectrl) = (DepsFile.expr_deps s1.(depf) expr) \u222a\u2081 s1.(ectrl))\n  | Oload ord reg lexpr val l\n         (L: l = RegFile.eval_lexpr s1.(regf) lexpr)\n         (II : instr = Instr.load ord reg lexpr)\n         (LABELS : labels = [Aload false ord (RegFile.eval_lexpr s1.(regf) lexpr) val])\n         (UPC   : s2.(pc) = s1.(pc) + 1)\n         (UG    : s2.(G) =\n                  add s1.(G) tid (s1.(eindex) + dindex) (Aload false ord (RegFile.eval_lexpr s1.(regf) lexpr) val) \u2205\n                                             (DepsFile.lexpr_deps s1.(depf) lexpr) s1.(ectrl) \u2205)\n         (UINDEX : s2.(eindex) = s1.(eindex) + dindex + 1)\n         (UREGS : s2.(regf) = RegFun.add reg val s1.(regf))\n         (UDEPS : s2.(depf) = RegFun.add reg (eq (ThreadEvent tid (s1.(eindex) + dindex))) s1.(depf))\n         (UECTRL : s2.(ectrl) = s1.(ectrl))\n  | Ostore ord lexpr expr l v x\n          (L: l = RegFile.eval_lexpr s1.(regf) lexpr)\n          (V: v = RegFile.eval_expr  s1.(regf)  expr)\n          (X: x = Xpln)\n          (LABELS : labels = [Astore x ord l v])\n          (II : instr = Instr.store ord lexpr expr)\n          (UPC   : s2.(pc) = s1.(pc) + 1)\n          (UG    : s2.(G) =\n                   add s1.(G) tid (s1.(eindex) + dindex) (Astore x ord l v)\n                                              (DepsFile.expr_deps  s1.(depf)  expr)\n                                              (DepsFile.lexpr_deps s1.(depf) lexpr) s1.(ectrl) \u2205)\n          (UINDEX : s2.(eindex) = s1.(eindex) + dindex + 1)\n          (UREGS : s2.(regf) = s1.(regf))\n          (UDEPS : s2.(depf) = s1.(depf))\n          (UECTRL : s2.(ectrl) = s1.(ectrl))\n          . \n\n  Definition Oistep (tid : thread_id) (labels : list label) s1 s2 :=\n    \u27ea INSTRS : s1.(instrs) = s2.(instrs) \u27eb /\\\n    \u27ea ISTEP: exists instr dindex, \n        Some instr = List.nth_error s1.(instrs) s1.(pc) /\\\n        @Oistep_ tid labels s1 s2 instr dindex\u27eb.\n  \n  Definition Ostep (tid : thread_id) s1 s2 :=\n    exists lbls, Oistep tid lbls s1 s2.\n\n  Definition is_ocaml_mode mode :=\n    match mode with\n    | Orlx | Osc => true\n    | _ => false\n    end. \n  \n  Definition is_ocaml_instruction instr :=\n    match instr with\n    | Instr.assign _ _ | Instr.ifgoto _ _ => true\n    | Instr.load mode _ _ | Instr.store mode _ _ => is_ocaml_mode mode\n    | _ => false\n    end. \n\n  Definition Othread_execution (tid : thread_id) (insts : list Prog.Instr.t) (pe : execution) :=\n    exists s,\n      \u27ea STEPS : (Ostep tid)\uff0a (init insts) s \u27eb /\\\n      \u27ea TERMINAL : is_terminal s \u27eb /\\\n      \u27ea PEQ : s.(G) = pe \u27eb.\n\n  Definition instr_mode instr :=\n    match instr with\n    | Instr.load mode _ _ | Instr.store mode _ _ | Instr.fence mode => Some mode\n    | Instr.update _ _ _ mode_r mode_w _ _ => Some mode_r (* assume that mode_r = mode_w *)\n    | _ => None\n    end. \n\n  Definition instr_locs instr :=\n    match instr with\n    | Instr.load _ _ lxpr | Instr.store _ lxpr _\n    | Instr.update _ _ _ _ _ _ lxpr => match lxpr with\n                                  | Instr.lexpr_loc l => [l]\n                                  | Instr.lexpr_choice _ l1 l2 => [l1;  l2]\n                                  end\n    | _ => []\n    end. \n\n  Definition locations_separated prog := forall (loc : Loc.t), exists mode,\n        is_ocaml_mode mode /\\\n        (forall tid PO (INTHREAD: IdentMap.find tid prog = Some PO)\n           instr (INPROG: In instr PO)\n           (AT_LOC: In loc (instr_locs instr)),\n            Some mode = instr_mode instr). \n\n  Definition OCamlProgram (prog: Prog.Prog.t) :=\n    (forall tid PO (INTHREAD: IdentMap.find tid prog = Some PO),\n        forallb is_ocaml_instruction PO) /\\\n    locations_separated prog. \n\n  Definition Oprogram_execution prog (OPROG: OCamlProgram prog) (G : execution) :=\n    (forall e (IN: G.(acts_set) e), is_init e \\/ IdentMap.In (tid e) prog)\n    /\\ forall thread linstr (INTHREAD: IdentMap.find thread prog = Some linstr),\n      exists pe, Othread_execution thread linstr pe\n            /\\ thread_restricted_execution G thread pe.\n  \nEnd OCaml_Program.\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/ocamlmm/OmmProgram.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.153970938589975}}
{"text": "From iris.algebra Require Import dyn_reservation_map agree.\nFrom iris.proofmode Require Import proofmode.\nFrom lrust.lifetime Require Export lifetime.\nFrom iris.prelude Require Import options.\n\n(** This module provides support for attaching metadata (specifically, a\n[gname]) to a lifetime (as is required for types using branding). *)\n\nClass lft_metaG \u03a3 := LftMetaG {\n  lft_meta_inG :> inG \u03a3 (dyn_reservation_mapR (agreeR gnameO));\n}.\nDefinition lft_meta\u03a3 : gFunctors :=\n  #[GFunctor (dyn_reservation_mapR (agreeR gnameO))].\nGlobal Instance subG_lft_meta \u03a3 :\n  subG (lft_meta\u03a3) \u03a3 \u2192 lft_metaG \u03a3.\nProof. solve_inG. Qed.\n\n(** We need some global ghost state, but we do not actually care about the name:\nwe always use a frame-preserving update starting from \u03b5 to obtain the ownership\nwe need. In other words, we use [own_unit] instead of [own_alloc]. As a result\nwe can just hard-code an arbitrary name here. *)\nLocal Definition lft_meta_gname : gname := 42%positive.\n\nDefinition lft_meta `{!lftGS \u03a3 userE, lft_metaG \u03a3} (\u03ba : lft) (\u03b3 : gname) : iProp \u03a3 :=\n  \u2203 p : positive, \u231c\u03ba = positive_to_lft p\u231d \u2217\n    own lft_meta_gname (dyn_reservation_map_data p (to_agree \u03b3)).\n\nSection lft_meta.\n  Context `{!invGS \u03a3, !lftGS \u03a3 userE, lft_metaG \u03a3}.\n\n  Global Instance lft_meta_timeless \u03ba \u03b3 : Timeless (lft_meta \u03ba \u03b3).\n  Proof. apply _. Qed.\n  Global Instance lft_meta_persistent \u03ba \u03b3 : Persistent (lft_meta \u03ba \u03b3).\n  Proof. apply _. Qed.\n\n  Lemma lft_create_meta {E : coPset} (\u03b3 : gname) :\n    \u2191lftN \u2286 E \u2192\n    lft_ctx ={E}=\u2217\n    \u2203 \u03ba, lft_meta \u03ba \u03b3 \u2217 (1).[\u03ba] \u2217 \u25a1 ((1).[\u03ba] ={\u2191lftN \u222a userE}[userE]\u25b7=\u2217 [\u2020\u03ba]).\n  Proof.\n    iIntros (HE) \"#LFT\".\n    iMod (own_unit (dyn_reservation_mapUR (agreeR gnameO)) lft_meta_gname) as \"Hown\".\n    iMod (own_updateP _ _ _ dyn_reservation_map_reserve' with \"Hown\")\n      as (? [Etok [Hinf ->]]) \"Hown\".\n    iMod (lft_create_strong (.\u2208 Etok) with \"LFT\") as (p HEtok) \"H\u03ba\"; [done..|].\n    iExists (positive_to_lft p). iFrame \"H\u03ba\".\n    iMod (own_update with \"Hown\") as \"Hown\".\n    { eapply (dyn_reservation_map_alloc _ p (to_agree \u03b3)); done. }\n    iModIntro. iExists p. eauto.\n  Qed.\n\n  Lemma lft_meta_agree (\u03ba : lft) (\u03b31 \u03b32 : gname) :\n    lft_meta \u03ba \u03b31 -\u2217 lft_meta \u03ba \u03b32 -\u2217 \u231c\u03b31 = \u03b32\u231d.\n  Proof.\n    iIntros \"Hidx1 Hidx2\".\n    iDestruct \"Hidx1\" as (p1) \"(% & Hidx1)\". subst \u03ba.\n    iDestruct \"Hidx2\" as (p2) \"(Hlft & Hidx2)\".\n    iDestruct \"Hlft\" as %<-%(inj positive_to_lft).\n    iCombine \"Hidx1 Hidx2\" as \"Hidx\".\n    iDestruct (own_valid with \"Hidx\") as %Hval.\n    rewrite ->(dyn_reservation_map_data_valid (A:=agreeR gnameO)) in Hval.\n    apply to_agree_op_inv_L in Hval.\n    done.\n  Qed.\nEnd lft_meta.\n\nGlobal Typeclasses Opaque lft_meta.\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/meta.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15389650974271238}}
{"text": "Require Import\n        List\n        ZArith\n        Bool.\nRequire Import\n        Events\n        LibModel\n        Maps\n        Messages\n        States\n        Types.\nRequire Import\n        ERC20.\n\n\nOpen Scope list_scope.\n\n\nModule TradeDelegate.\n\n  Section Aux.\n\n    Definition is_authorized_address\n               (st: TradeDelegateState) (addr: address) : Prop :=\n      A2B.get (delegate_authorizedAddresses st) addr = true.\n\n    Definition is_owner (st: TradeDelegateState) (addr: address) : Prop :=\n      addr = delegate_owner st.\n\n    Definition is_not_suspended (st: TradeDelegateState) : Prop :=\n      delegate_suspended st = false.\n\n    Definition authorized_and_nonsuspended\n               (st: TradeDelegateState) (sender: address) : Prop :=\n      is_authorized_address st sender /\\ is_not_suspended st.\n\n  End Aux.\n\n  Section AuthorizeAddress.\n\n    Definition authorizeAddress_spec (sender addr: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            is_owner st sender /\\ addr <> 0 /\\ ~ is_authorized_address st sender;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := A2B.upd (delegate_authorizedAddresses st) addr true;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = EvtAddressAuthorized addr :: nil;\n      |}.\n\n  End AuthorizeAddress.\n\n  Section DeauthorizeAddress.\n\n    Definition deauthorizeAddress_spec (sender addr: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            is_owner st sender /\\ addr <> 0 /\\ is_authorized_address st sender;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := A2B.upd (delegate_authorizedAddresses st) addr false;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = EvtAddressDeauthorized addr :: nil;\n      |}.\n\n  End DeauthorizeAddress.\n\n  Section IsAddressAuthorized.\n\n    Definition isAddressAuthorized_spec (sender addr: address) :=\n      {|\n        fspec_require :=\n          fun wst => True;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            wst' = wst /\\\n            let st := wst_trade_delegate_state wst in\n            (is_authorized_address st addr -> retval = RetBool true) /\\\n            (~ is_authorized_address st addr -> retval = RetBool false);\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End IsAddressAuthorized.\n\n  Section BatchTransfer.\n\n    Inductive transfer_params\n              (wst: WorldState) (sender: address) (params: list TransferParam)\n    : WorldState -> list Event -> Prop :=\n    | transfer_nil:\n        params = nil ->\n        transfer_params wst sender params wst nil\n\n    | transfer_cons:\n        forall param params' retval wst' events' wst'' events'',\n          params = param :: params' ->\n          ERC20s.model wst\n                       (msg_transferFrom (wst_trade_delegate_addr wst)\n                                         (transfer_token param)\n                                         (transfer_from param)\n                                         (transfer_to param)\n                                         (transfer_amount param))\n                       wst' retval events' ->\n          transfer_params wst' sender params' wst'' events'' ->\n          transfer_params wst sender params wst'' (events' ++ events'')\n    .\n\n    Definition batchTransfer_spec (sender: address) (params: list TransferParam) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            authorized_and_nonsuspended (wst_trade_delegate_state wst) sender /\\\n            (exists wst' events, transfer_params wst sender params wst' events)\n        ;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            retval = RetNone /\\\n            forall wst'' events,\n              transfer_params wst sender params wst'' events ->\n              wst' = wst''\n        ;\n\n        fspec_events :=\n          fun wst events =>\n            forall wst' events',\n              transfer_params wst sender params wst' events' ->\n              events = events'\n        ;\n      |}.\n\n  End BatchTransfer.\n\n  Section BatchUpdateFilled.\n\n    Fixpoint update_fills\n             (st: TradeDelegateState) (params: list FilledParam)\n    : TradeDelegateState :=\n      match params with\n      | nil => st\n      | param :: params' =>\n        let st' :=\n            {|\n              delegate_owner := delegate_owner st;\n              delegate_suspended := delegate_suspended st;\n              delegate_authorizedAddresses := delegate_authorizedAddresses st;\n              delegate_filled := H2V.upd (delegate_filled st) (filled_order_hash param) (filled_amount param);\n              delegate_cancelled := delegate_cancelled st;\n              delegate_cutoffs := delegate_cutoffs st;\n              delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n              delegate_cutoffsOwner := delegate_cutoffsOwner st;\n              delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n            |} in\n        update_fills st' params'\n      end.\n\n    Definition batchUpdateFilled_spec (sender: address) (params: list FilledParam) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            authorized_and_nonsuspended (wst_trade_delegate_state wst) sender;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            retval = RetNone /\\\n            wst' = wst_update_trade_delegate wst (update_fills (wst_trade_delegate_state wst) params);\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End BatchUpdateFilled.\n\n  Section SetCancelled.\n\n    Definition setCancelled_spec (sender broker: address) (orderHash: bytes32) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            authorized_and_nonsuspended (wst_trade_delegate_state wst) sender;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := AH2B.upd (delegate_cancelled st) (broker, orderHash) true;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End SetCancelled.\n\n  Section SetCutOffs.\n\n    Definition setCutoffs_spec (sender broker: address) (cutoff: uint) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            authorized_and_nonsuspended st sender /\\\n            A2V.get (delegate_cutoffs st) (broker) < cutoff;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := A2V.upd (delegate_cutoffs st) (broker) cutoff;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End SetCutOffs.\n\n  Section SetTradingPairCutOffs.\n\n    Definition setTradingPairCutoffs_spec\n               (sender broker: address) (tokenPair: bytes20) (cutoff: uint) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            authorized_and_nonsuspended st sender /\\\n            AH2V.get (delegate_tradingPairCutoffs st) (broker, tokenPair) < cutoff;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := AH2V.upd (delegate_tradingPairCutoffs st) (broker, tokenPair) cutoff;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End SetTradingPairCutOffs.\n\n  Section SetCutoffsOfOwner.\n\n    Definition setCutoffsOfOwner_spec\n               (sender broker owner: address) (cutoff: uint) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            authorized_and_nonsuspended st sender /\\\n            AA2V.get (delegate_cutoffsOwner st) (broker, owner) < cutoff;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := AA2V.upd (delegate_cutoffsOwner st) (broker, owner) cutoff;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End SetCutoffsOfOwner.\n\n  Section SetTradingPairCutoffsOfOwner.\n\n    Definition setTradingPairCutoffsOfOwner_spec\n               (sender broker owner: address) (tokenPair: bytes20) (cutoff: uint) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            authorized_and_nonsuspended st sender /\\\n            AAH2V.get (delegate_tradingPairCutoffsOwner st) (broker, owner, tokenPair) < cutoff;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled := delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := AAH2V.upd (delegate_tradingPairCutoffsOwner st) (broker, owner, tokenPair) cutoff;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End SetTradingPairCutoffsOfOwner.\n\n  Section BatchGetFilledAndCheckCancelled.\n\n    Definition is_cancelled\n               (st: TradeDelegateState) (param: OrderParam)\n    : bool :=\n      let broker := order_param_broker param in\n      let owner := order_param_owner param in\n      let trading_pair := order_param_tradingPair param in\n      let hash := order_param_hash param in\n      let valid_since := order_param_validSince param in\n      AH2B.get (delegate_cancelled st) (broker, hash) ||\n      Nat.leb valid_since\n              (AH2V.get (delegate_tradingPairCutoffs st) (broker, trading_pair)) ||\n      Nat.leb valid_since\n              (A2V.get (delegate_cutoffs st) broker)  ||\n      Nat.leb valid_since\n              (AAH2V.get (delegate_tradingPairCutoffsOwner st) (broker, owner, trading_pair)) ||\n      Nat.leb valid_since\n              (AA2V.get (delegate_cutoffsOwner st) (broker, owner)).\n\n    Fixpoint build_fills\n             (st: TradeDelegateState) (params: list OrderParam)\n      : list (option uint) :=\n      match params with\n      | nil => nil\n      | param :: params' =>\n        let fill := match is_cancelled st param with\n                    | true => None\n                    | _ => Some (H2V.get (delegate_filled st) (order_param_hash param))\n                    end\n        in fill :: build_fills st params'\n      end.\n\n    Definition batchGetFilledAndCheckCancelled_spec\n               (sender: address) (params: list OrderParam) :=\n      {|\n        fspec_require :=\n          fun wst => True;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            wst' = wst /\\\n            retval = RetFills (build_fills (wst_trade_delegate_state wst) params);\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End BatchGetFilledAndCheckCancelled.\n\n  Section Suspend.\n\n    Definition suspend_spec (sender: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            is_owner st sender /\\ is_not_suspended st;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := true;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled :=delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End Suspend.\n\n  Section Resume.\n\n    Definition resume_spec (sender: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            is_owner st sender /\\ ~ is_not_suspended st;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := delegate_owner st;\n                       delegate_suspended := false;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled :=delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            events = nil;\n      |}.\n\n  End Resume.\n\n  Section Kill.\n\n    Definition kill_spec (sender: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            let st := wst_trade_delegate_state wst in\n            is_owner st sender /\\ ~ is_not_suspended st;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let st := wst_trade_delegate_state wst in\n            wst' = wst_update_trade_delegate\n                     wst\n                     {|\n                       delegate_owner := 0;\n                       delegate_suspended := delegate_suspended st;\n                       delegate_authorizedAddresses := delegate_authorizedAddresses st;\n                       delegate_filled := delegate_filled st;\n                       delegate_cancelled :=delegate_cancelled st;\n                       delegate_cutoffs := delegate_cutoffs st;\n                       delegate_tradingPairCutoffs := delegate_tradingPairCutoffs st;\n                       delegate_cutoffsOwner := delegate_cutoffsOwner st;\n                       delegate_tradingPairCutoffsOwner := delegate_tradingPairCutoffsOwner st;\n                     |} /\\\n            retval = RetNone;\n\n        fspec_events :=\n          fun wst events =>\n            let st := wst_trade_delegate_state wst in\n            events = (EvtOwnershipTransferred (delegate_owner st) 0) :: nil;\n      |}.\n\n  End Kill.\n\n  Definition get_spec (msg: TradeDelegateMsg) : FSpec :=\n    match msg with\n    | msg_authorizeAddress sender addr =>\n      authorizeAddress_spec sender addr\n\n    | msg_deauthorizeAddress sender addr =>\n      deauthorizeAddress_spec sender addr\n\n    | msg_isAddressAuthorized sender addr =>\n      isAddressAuthorized_spec sender addr\n\n    | msg_batchTransfer sender params =>\n      batchTransfer_spec sender params\n\n    | msg_batchUpdateFilled sender params =>\n      batchUpdateFilled_spec sender params\n\n    | msg_setCancelled sender broker orderHash =>\n      setCancelled_spec sender broker orderHash\n\n    | msg_setCutoffs sender broker cutoff =>\n      setCutoffs_spec sender broker cutoff\n\n    | msg_setTradingPairCutoffs sender broker tokenPair cutoff =>\n      setTradingPairCutoffs_spec sender broker tokenPair cutoff\n\n    | msg_setCutoffsOfOwner sender broker owner cutoff =>\n      setCutoffsOfOwner_spec sender broker owner cutoff\n\n    | msg_setTradingPairCutoffsOfOwner sender broker owner tokenPair cutoff =>\n      setTradingPairCutoffsOfOwner_spec sender broker owner tokenPair cutoff\n\n    | msg_batchGetFilledAndCheckCancelled sender params =>\n      batchGetFilledAndCheckCancelled_spec sender params\n\n    | msg_suspend sender =>\n      suspend_spec sender\n\n    | msg_resume sender =>\n      resume_spec sender\n\n    | msg_kill sender =>\n      kill_spec sender\n    end.\n\n  Definition model\n             (wst: WorldState)\n             (msg: TradeDelegateMsg)\n             (wst': WorldState)\n             (retval: RetVal)\n             (events: list Event)\n    : Prop :=\n    fspec_sat (get_spec msg) wst wst' retval events.\n\nEnd TradeDelegate.\n", "meta": {"author": "sec-bit", "repo": "loopring-protocol2-verification", "sha": "bfb2101faccbefd592a8f63d42e01aae41b06930", "save_path": "github-repos/coq/sec-bit-loopring-protocol2-verification", "path": "github-repos/coq/sec-bit-loopring-protocol2-verification/loopring-protocol2-verification-bfb2101faccbefd592a8f63d42e01aae41b06930/Models/TradeDelegate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15389650012137723}}
{"text": "Require Import sflib.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import Loc. \n\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Language.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import NPThread.\n\n(** * Program Steps in the Non-preemptive Semantics *)\n\n(** This file define the program step in the non-preemptive semantics (in Figure 10 in paper). *)\n\nModule NPConfiguration.\n  (** ** Program Configuraiton in the Non-preemptive Semantics *)\n  (** The program configuration. It includes:\n      - [cfg]: the program configuration in promising semantics 2.1\n      - [preempt]: A 'switch bit' [preempt] indicate whether a switch step is allowed\n        + [preempt = true]: a switch step is allowed\n        + [preempt = false]: a switch step is disallowed *)\n  Structure t := mk { \n    cfg: Configuration.t;\n    preempt: bool;  (*True for preempt point, False for non-atomic*)\n  }.\n\n  (** Initialization of the program configuration in the non-preemptive semantics *)\n  Definition init {lang: language} (fs: list Language.fid) (code: Language.syntax lang) (ctid: IdentMap.key) :=\n    match Configuration.init fs code ctid with\n    | Some c => Some (mk c true)\n    | None => None\n    end.\n\n  Definition is_terminal (conf:t): Prop := Configuration.is_terminal (cfg conf).\n  Definition wf (conf:t): Prop :=  Configuration.wf (cfg conf). \n\n  Definition consistent (c: t) (lo: Ordering.LocOrdMap): Prop := \n    Threads.consistent_nprm (Configuration.threads (cfg c)) (Configuration.sc (cfg c)) (Configuration.memory (cfg c)) lo.\n\n  (** ** Machine Level Semantics *)\n  (** Program transition in the non-preemptive semantics.\n      - [step_tau]: current thread takes some steps;\n      - [step_sw]: thread switching, which is only permitted when the 'switch bit' is true;\n      - [step_thread_term]: current thread termination;\n      - [step_out]: output step, generating observable event. *)\n  Inductive step: forall (e:MachineEvent.t) (lo: Ordering.LocOrdMap) (npc1 npc2:t), Prop :=\n    | step_tau\n      lang lo npc1 npc2 tid1 thrd_conf1 thrd_conf1' thrd_conf2 st1 st2 lc1 lc2 sc2 m2 b\n      (CTID: Configuration.tid (cfg npc1) = tid1)\n      (TID1: IdentMap.find tid1 (Configuration.threads (cfg npc1)) = Some (existT _ lang st1, lc1))\n      (THRD1: thrd_conf1 = NPAuxThread.mk lang ((Thread.mk lang) st1 lc1 (Configuration.sc (cfg npc1)) (Configuration.memory (cfg npc1))) (preempt npc1))\n      (STEPS: rtc (@NPAuxThread.tau_step lang lo) thrd_conf1 thrd_conf1')\n      (STEP: NPAuxThread.tau_step lang lo thrd_conf1' thrd_conf2)\n      (THRD2: thrd_conf2 = NPAuxThread.mk lang ((Thread.mk lang) st2 lc2 sc2 m2) b)\n      (CONSISTENT: NPAuxThread.consistent lang ((Thread.mk lang) st2 lc2 sc2 m2) lo)\n      (NPC2: npc2 = mk (Configuration.mk (IdentMap.add tid1 (existT _ _ st2, lc2) (Configuration.threads (cfg npc1)))\n                                         tid1 sc2 m2) b)\n      :\n      step MachineEvent.silent lo npc1 npc2\n    | step_sw\n      lang lo npc1 npc2 tid2 st2 lc2  \n      (TID2: IdentMap.find tid2 (Configuration.threads (cfg npc1)) = Some (existT _ lang st2, lc2))\n      (PREEMPT: (preempt npc1) = true)\n      (NPC2: npc2 = mk (Configuration.mk (Configuration.threads (cfg npc1)) tid2\n                                         (Configuration.sc (cfg npc1))\n                                         (Configuration.memory (cfg npc1))) true)\n      :\n      step MachineEvent.switch lo npc1 npc2\n    | step_thread_term\n      lang lo npc1 npc2 st1 lc1 st2 lc2 tid1 tid2 threads2\n      (CTID: Configuration.tid (cfg npc1) = tid1)\n      (OLD_TID: IdentMap.find tid1 (Configuration.threads (cfg npc1)) = Some (existT _ lang st1, lc1))\n      (THRD_DONE: Thread.is_done (Thread.mk _ st1 lc1 (Configuration.sc (cfg npc1)) (Configuration.memory (cfg npc1))))\n      (THRDS_REMOVE: IdentMap.remove tid1 (Configuration.threads (cfg npc1)) = threads2)\n      (NEW_TID_OK: IdentMap.find tid2 (Configuration.threads (cfg npc2)) = Some (existT _ lang st2, lc2))\n      (NPC2: npc2 = mk (Configuration.mk threads2 tid2\n                                         (Configuration.sc (cfg npc1))\n                                         (Configuration.memory (cfg npc1))) true)\n      :\n      step MachineEvent.switch lo npc1 npc2\n    | step_out\n      lang lo e npc1 npc2 st1 lc1 thrd_conf1 st2 lc2 thrd_conf2 tid1 sc2 m2\n      (CTID: Configuration.tid (cfg npc1) = tid1)  \n      (TID1: IdentMap.find tid1 (Configuration.threads (cfg npc1)) = Some (existT _ lang st1, lc1))\n      (THRD1: thrd_conf1 = NPAuxThread.mk lang ((Thread.mk lang) st1 lc1 (Configuration.sc (cfg npc1)) (Configuration.memory (cfg npc1))) (preempt npc1))\n      (STEP: NPAuxThread.out_step lang lo e thrd_conf1 thrd_conf2)\n      (CONSISTENT: NPAuxThread.consistent lang (NPAuxThread.state lang thrd_conf2) lo)\n      (THRD2: thrd_conf2 = NPAuxThread.mk lang ((Thread.mk lang) st2 lc2 sc2 m2) true)\n      (NPC2: npc2 = mk (Configuration.mk (IdentMap.add tid1 (existT _ _ st2, lc2) (Configuration.threads (cfg npc1)))\n                                         tid1 sc2 m2) true)\n      :\n      step (MachineEvent.syscall e) lo npc1 npc2. \n\n  (** ** Done Configuration *)\n  Definition is_done (npc: t): Prop :=\n    Configuration.is_done (cfg npc).\n\n  Definition is_abort (npc: t) (lo: Ordering.LocOrdMap): Prop := \n    exists lang st1 lc1 e e' c b,\n      c = (cfg npc) /\\ \n      IdentMap.find (Configuration.tid c) (Configuration.threads c) = Some (existT _ lang st1, lc1) /\\\n      (e = Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) /\\ \n      rtc (@NPAuxThread.tau_step _ lo)\n          (NPAuxThread.mk lang e (NPConfiguration.preempt npc)) (NPAuxThread.mk lang e' b) /\\ \n      Thread.is_abort e' lo.\n\n  Inductive tau_step : Ordering.LocOrdMap -> t -> t -> Prop :=\n  | tau_step_intro: forall (e: MachineEvent.t) (lo: Ordering.LocOrdMap) (npc1 npc2: t),\n      step e lo npc1 npc2 -> ~(exists e0, e = MachineEvent.syscall e0) ->\n      tau_step lo npc1 npc2.\n\n  Inductive all_step : Ordering.LocOrdMap -> t -> t -> Prop :=\n  | all_step_intro : forall (e: MachineEvent.t) (lo: Ordering.LocOrdMap) (npc1 npc2: t),\n      step e lo npc1 npc2 -> all_step lo npc1 npc2.\n\n  (** ** Abort Configuration *)\n  Inductive abort_config: forall (lo: Ordering.LocOrdMap) (npc: t), Prop :=\n  | Abort_config_intro\n      lo npc npc'\n      (STEPS: rtc (all_step lo) npc npc')\n      (ABORT: NPConfiguration.is_abort npc' lo):\n      abort_config lo npc.\n\n  (** ** Safe Program *)\n  (** A program is safe, if its executions on the non-preemptive semantics will\n      never reach an abort configuraiton. *)\n  Inductive safe {lang: language} :\n    forall (lo: Ordering.LocOrdMap) (fs: list Language.fid) (code: Language.syntax lang) (ctid: IdentMap.key), Prop :=\n  | Safe_intro\n      lo fs code ctid\n      (*(SAFE_INIT: exists npc, init fs code ctid = Some npc)*)\n      (SAFE_EXEC: forall npc, init fs code ctid = Some npc -> ~(abort_config lo npc)):\n      safe lo fs code ctid.\n\nEnd NPConfiguration.\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/non-preemptive/NPConfiguration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.15385517846898883}}
{"text": "\nSection Feelings.\n\n(** You have feelings about stuff.  Everyone has feeling about stuffs.\n  There are furthermore exactly two kinds of feelings: hate and love.\n  This is naturally expressed as a boolean. **)\nVariable feelings : forall A : Type, A -> bool.\n\n(** If your feelings say that it is true, it is probably true. **)\nAxiom gut_feeling : forall P : Prop, feelings _ P = true -> P.\n\n(** Alternatively, if you hate something, it is likely false. **)\nAxiom hate : forall P : Prop, feelings _ P = false -> ~ P.\n\nEnd Feelings.\n\n(** Let the hate speak now. **)\nTheorem nihilism : forall P, ~ P.\nProof.\n  intro. apply hate with (feelings := fun _ _ => false). reflexivity.\nQed.\n\nCorollary nothing_matters : False.\nProof.\n  apply gut_feeling with (feelings := fun _ _ => true). reflexivity.\nQed.\n", "meta": {"author": "Mbodin", "repo": "coq-alternative-facts", "sha": "2c6ae63be7fb089085b313ccd21b9f5368a04e2c", "save_path": "github-repos/coq/Mbodin-coq-alternative-facts", "path": "github-repos/coq/Mbodin-coq-alternative-facts/coq-alternative-facts-2c6ae63be7fb089085b313ccd21b9f5368a04e2c/theories/Feelings.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.1537890696006391}}
{"text": "Require Import VST.veric.base.\nRequire Import VST.msl.msl_standard.\nRequire Import VST.veric.shares.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.res_predicates.\n\nLocal Open Scope pred.\n\nDefinition cleave (sh: share) :=\n  (Share.lub (fst (Share.split (Share.glb Share.Lsh sh))) (fst (Share.split (Share.glb Share.Rsh sh))),\n   Share.lub (snd (Share.split (Share.glb Share.Lsh sh))) (snd (Share.split (Share.glb Share.Rsh sh)))).\n\nLemma cleave_join:\n forall sh: share, sepalg.join (fst (cleave sh)) (snd (cleave sh)) sh.\nProof.\nintros.\nunfold cleave.\ndestruct (Share.split (Share.glb Share.Lsh sh)) as [a b] eqn:?H.\napply split_join in H.\ndestruct (Share.split (Share.glb Share.Rsh sh)) as [e f] eqn:?H.\napply split_join in H0.\ndestruct (Share.split sh) as [c g] eqn:?H.\napply split_join in H1.\nsimpl.\ndestruct H1.\nsubst sh.\ndestruct H.\ndestruct H0.\nsplit.\n*\nrewrite !Share.distrib1.\nrewrite !(Share.glb_commute (Share.lub _ _)).\nrewrite !Share.distrib1.\nrewrite (Share.glb_commute b a), (Share.glb_commute f e).\nrewrite H,H0.\nrewrite (Share.lub_commute Share.bot).\nrewrite !Share.lub_bot.\nrewrite Share.distrib2.\nrewrite !(Share.lub_commute (Share.glb _ _)).\nrewrite !Share.distrib2.\nrewrite (Share.lub_commute f e), H3, H2.\nrewrite (Share.glb_commute (Share.lub _ _)).\nrewrite (Share.glb_assoc Share.Lsh).\nrewrite !(Share.glb_assoc Share.Rsh).\nrewrite (Share.glb_commute _ (Share.glb Share.Lsh _)).\nrewrite (Share.glb_assoc Share.Lsh).\nrewrite <- (Share.glb_assoc Share.Rsh).\nrewrite (Share.glb_commute Share.Rsh).\nrewrite glb_Lsh_Rsh.\nrewrite Share.glb_commute. apply Share.glb_bot.\n*\nrewrite Share.lub_assoc.\nrewrite (Share.lub_commute e).\nrewrite (Share.lub_assoc b).\nrewrite <- Share.lub_assoc.\nrewrite H2.\nrewrite (Share.lub_commute f e), H3.\nclear.\ndo 2 rewrite (Share.glb_commute _ (Share.lub _ _)).\nrewrite <- Share.distrib1.\nrewrite lub_Lsh_Rsh.\napply Share.glb_top.\nQed.\n\nLemma cleave_readable1:\n forall sh, readable_share sh -> readable_share (fst (cleave sh)).\nProof.\nintros.\nhnf in H|-*. contradict H.\napply identity_share_bot in H.\nunfold cleave in H.\nsimpl in H.\nrewrite Share.distrib1 in H.\napply lub_bot_e in H. destruct H as [_ ?].\ndestruct (Share.split (Share.glb Share.Rsh sh)) as [c d] eqn:H1.\napply (split_nontrivial' _ _ _ H1).\nleft.\napply split_join in H1.\nsimpl in *.\ndestruct (join_parts1 comp_Rsh_Lsh H1).\nrewrite <- H0, H.\napply bot_identity.\nQed.\n\nLemma cleave_readable2:\n forall sh, readable_share sh -> readable_share (snd (cleave sh)).\nProof.\nintros.\nhnf in H|-*. contradict H.\napply identity_share_bot in H.\nunfold cleave in H.\nsimpl in H.\nrewrite Share.distrib1 in H.\napply lub_bot_e in H. destruct H as [_ ?].\ndestruct (Share.split (Share.glb Share.Rsh sh)) as [c d] eqn:H1.\napply (split_nontrivial' _ _ _ H1).\nsimpl in *.\nright.\napply split_join in H1.\napply join_comm in H1.\nsimpl in *.\ndestruct (join_parts1 comp_Rsh_Lsh H1).\nrewrite <- H0, H.\napply bot_identity.\nQed.\n\nLemma rshare_sh_readable:\n forall r, readable_share (rshare_sh r).\nProof.\ndestruct r; simpl.\ndestruct p;\nauto.\nQed.\n\nLemma cleave_nonreadable1:\n  forall sh, ~readable_share sh -> ~ readable_share (fst (cleave sh)).\nProof.\nintros.\ncontradict H.\ndo 3 red in H|-*.\ncontradict H.\nunfold cleave. simpl.\napply identity_share_bot in H.\nrewrite H. clear H.\ndestruct (Share.split Share.bot) as [a b] eqn:?H.\napply split_join in H.\nsimpl.\napply split_identity in H; [ | apply bot_identity].\napply identity_share_bot in H. subst.\nrewrite Share.lub_bot.\nclear.\ndestruct (Share.split (Share.glb Share.Lsh sh)) as [a b] eqn:H.\napply split_join in H.\nsimpl.\nreplace (Share.glb Share.Rsh a) with Share.bot.\napply bot_identity.\nsymmetry.\ndestruct H.\napply (f_equal (Share.glb Share.Rsh)) in H0.\nrewrite <- Share.glb_assoc in H0.\nrewrite (Share.glb_commute _ Share.Lsh) in H0.\nrewrite glb_Lsh_Rsh in H0.\nrewrite (Share.glb_commute Share.bot) in H0.\nrewrite Share.glb_bot in H0.\nrewrite Share.distrib1 in H0.\napply lub_bot_e in H0. destruct H0 as [? _].\nauto.\nQed.\n\nLemma cleave_nonreadable2:\n  forall sh, ~readable_share sh -> ~ readable_share (snd (cleave sh)).\nProof.\nintros.\ncontradict H.\ndo 3 red in H|-*.\ncontradict H.\nunfold cleave. simpl.\napply identity_share_bot in H.\nrewrite H. clear H.\ndestruct (Share.split Share.bot) as [a b] eqn:?H.\napply split_join in H.\nsimpl.\napply join_comm in H.\napply split_identity in H; [ | apply bot_identity].\napply identity_share_bot in H. subst.\nrewrite Share.lub_bot.\nclear.\ndestruct (Share.split (Share.glb Share.Lsh sh)) as [a b] eqn:H.\napply split_join in H.\nsimpl.\nreplace (Share.glb Share.Rsh b) with Share.bot.\napply bot_identity.\nsymmetry.\ndestruct H.\napply (f_equal (Share.glb Share.Rsh)) in H0.\nrewrite <- Share.glb_assoc in H0.\nrewrite (Share.glb_commute _ Share.Lsh) in H0.\nrewrite glb_Lsh_Rsh in H0.\nrewrite (Share.glb_commute Share.bot) in H0.\nrewrite Share.glb_bot in H0.\nrewrite Share.lub_commute in H0.\nrewrite Share.distrib1 in H0.\napply lub_bot_e in H0. destruct H0 as [? _].\nauto.\nQed.\n\nDefinition split_resource r :=\n  match r with YES sh rsh k pp => \n               (YES (fst (cleave sh)) (cleave_readable1 _ rsh) k pp , \n                YES (snd (cleave sh)) (cleave_readable2 _ rsh) k pp)\n             | PURE k pp => (PURE k pp, PURE k pp)\n             | NO sh nsh => (NO (fst (cleave sh)) (cleave_nonreadable1 _ nsh),\n                             NO (snd (cleave sh)) (cleave_nonreadable2 _ nsh))\n  end.\n\n\nLemma glb_cleave_lemma1: forall sh0 sh,\n  Share.glb Share.Rsh sh0 = Share.glb Share.Rsh sh ->\n Share.glb Share.Rsh (fst (cleave sh0)) =\n Share.glb Share.Rsh (fst (cleave sh)).\nProof.\nintros.\nunfold cleave; simpl.\ndestruct (Share.split (Share.glb Share.Lsh sh0)) as [a0 b0]  eqn:H0.\napply split_join in H0.\ndestruct (Share.split (Share.glb Share.Lsh sh)) as [a b]  eqn:H1.\napply split_join in H1.\ndestruct (Share.split (Share.glb Share.Rsh sh0)) as [c0 d0]  eqn:H2.\nrewrite H in H2. rewrite H2.\nsimpl.\napply split_join in H2.\nrewrite !Share.distrib1.\napply (join_parts1 comp_Lsh_Rsh) in H1.\ndestruct H1 as [_ ?]. rewrite H1.\napply (join_parts1 comp_Lsh_Rsh) in H0.\ndestruct H0 as [_ ?]. rewrite H0.\nauto.\nQed.\n\nLemma glb_cleave_lemma2: forall sh0 sh,\n  Share.glb Share.Rsh sh0 = Share.glb Share.Rsh sh ->\n Share.glb Share.Rsh (snd (cleave sh0)) =\n Share.glb Share.Rsh (snd (cleave sh)).\nProof.\nintros.\nunfold cleave; simpl.\ndestruct (Share.split (Share.glb Share.Lsh sh0)) as [a0 b0]  eqn:H0.\napply split_join in H0.\ndestruct (Share.split (Share.glb Share.Lsh sh)) as [a b]  eqn:H1.\napply split_join in H1.\napply join_comm in H0.\napply join_comm in H1.\ndestruct (Share.split (Share.glb Share.Rsh sh0)) as [c0 d0]  eqn:H2.\nrewrite H in H2. rewrite H2.\nsimpl.\napply split_join in H2.\nrewrite !Share.distrib1.\napply (join_parts1 comp_Lsh_Rsh) in H1.\ndestruct H1 as [_ ?]. rewrite H1.\napply (join_parts1 comp_Lsh_Rsh) in H0.\ndestruct H0 as [_ ?]. rewrite H0.\nauto.\nQed.\n\nLemma split_rmap_ok1: forall m,\n  resource_fmap (approx (level m)) (approx (level m)) oo (fun l => fst (split_resource (m @ l))) =\n       (fun l => fst (split_resource (m @ l))).\nProof.\nintros.\nextensionality l; unfold compose; simpl.\ncase_eq (m@l); simpl; intros; auto.\ngeneralize (eq_sym (resource_at_approx m l)); intro.\npattern (m@l) at 2 in H0; rewrite H in H0.\nsimpl in H0.\nrewrite H in H0.\ninversion H0.\nrewrite <- H2.\nrewrite <- H2.\nauto.\ngeneralize (eq_sym (resource_at_approx m l)); intro.\npattern (m@l) at 2 in H0; rewrite H in H0.\nsimpl in H0.\nrewrite H in H0.\ninversion H0.\nrewrite <- H2.\nrewrite <- H2.\nauto.\nQed.\n\nLemma split_rmap_ok2: forall m,\n  resource_fmap (approx (level m)) (approx (level m)) oo (fun l => snd (split_resource (m @ l))) =\n       (fun l => snd (split_resource (m @ l))).\nProof.\nintros.\nextensionality l; unfold compose; simpl.\ncase_eq (m@l); simpl; intros; auto.\ngeneralize (eq_sym (resource_at_approx m l)); intro.\npattern (m@l) at 2 in H0; rewrite H in H0.\nsimpl in H0.\nrewrite H in H0.\ninversion H0.\nrewrite <- H2.\nrewrite <- H2.\nauto.\ngeneralize (eq_sym (resource_at_approx m l)); intro.\npattern (m@l) at 2 in H0; rewrite H in H0.\nsimpl in H0.\nrewrite H in H0.\ninversion H0.\nrewrite <- H2.\nrewrite <- H2.\nauto.\nQed.\n\n(*\nDefinition split_rmap (m: rmap) : rmap * rmap :=\n (proj1_sig (make_rmap _ (split_rmap_valid1 m) (level m) (split_rmap_ok1 m)),\n  proj1_sig (make_rmap _ (split_rmap_valid2 m) (level m) (split_rmap_ok2 m))).\n*)\n\nLemma split_resource_join: \n  forall r, join (fst (split_resource r)) (snd (split_resource r)) r.\nProof.\nintro.\ndestruct r; simpl; constructor; auto; try (apply cleave_join; apply surjective_pairing).\nQed.\n\n(*Lemma split_rmap_join:\n  forall m, join (fst (split_rmap m)) (snd (split_rmap m)) m.\nProof.\nintros.\nunfold split_rmap; simpl.\ncase_eq (make_rmap _ (split_rmap_valid1 m) (level m) (split_rmap_ok1 m)); intros.\ncase_eq (make_rmap _ (split_rmap_valid2 m) (level m) (split_rmap_ok2 m)); intros.\nsimpl in *.\ngeneralize a; intros  [? ?].\ngeneralize a0; intros [? ?].\napply resource_at_join2; simpl; try congruence.\nrewrite H2; rewrite H4; simpl; auto.\nintro l.\napply split_resource_join; auto.\nQed.\n\nLemma split_rmap_at1:\n  forall m l , fst (split_rmap m) @ l = fst (split_resource (m @ l)).\nProof.\nunfold split_rmap; intros; simpl.\ncase_eq (make_rmap _ (split_rmap_valid1 m) (level m) (split_rmap_ok1 m)); intros.\nsimpl in *.\ndestruct a. rewrite e0; auto.\nQed.\n\nLemma split_rmap_at2:\n  forall m l , snd (split_rmap m) @ l = snd (split_resource (m @ l)).\nProof.\nunfold split_rmap; intros; simpl.\ncase_eq (make_rmap _ (split_rmap_valid2 m) (level m) (split_rmap_ok2 m)); intros.\nsimpl. clear H; destruct a. rewrite H0; auto.\nQed.*)\n\nDefinition split_shareval (shv: Share.t * val) : ((Share.t * val) * (Share.t * val)) :=\n  ((fst (Share.split (fst shv)), snd shv), (snd (Share.split (fst shv)), snd shv)).\n\nDefinition slice_resource (sh: share) (r: resource) : resource :=\n  match r with\n   | NO _ _ => NO (retainer_part sh) (retainer_part_nonreadable sh)\n   | YES _ _ k pp =>\n    match readable_share_dec sh with\n    | left r1 => YES sh r1 k pp\n    | right n => NO sh n\n    end\n   | PURE k pp => PURE k pp\n  end.\n\n\nLemma make_slice_rmap: forall w (P: address -> Prop) (P_DEC: forall l, {P l} + {~ P l}) sh,\n  (forall l : AV.address, ~ P l -> identity (w @ l)) ->\n  {w' | level w' = level w /\\ resource_at w' =\n       (fun l => if P_DEC l then slice_resource sh (w @ l) else w @ l) /\\\n       ghost_of w' = ghost_of w}.\nProof.\n  intros.\n  pose (f l := if P_DEC l then slice_resource sh (w @ l) else w @ l).\n  apply (make_rmap _ (ghost_of w) (level w)).\n  extensionality loc; unfold compose, f.\n  destruct (P_DEC loc).\n  + pose proof resource_at_approx w loc.\n    destruct (w @ loc); auto.\n    simpl.\n    destruct (readable_share_dec sh); auto.\n    inversion H0.\n    simpl; f_equal; f_equal; auto.\n  + apply resource_at_approx.\n  + apply ghost_of_approx.\nQed.\n\nLemma jam_noat_splittable_aux:\n  forall S' S Q (PARAMETRIC: spec_parametric Q)\n           (sh1 sh2 sh3: share)\n           (rsh1: readable_share sh1) (rsh2: readable_share sh2)\n           l\n           (H: join sh1 sh2 sh3)\n           w (H0: allp (@jam _ _ _ _ _ _ (S' l) (S l) (Q l sh3) noat) w)\n           f (Hf: resource_at f = fun loc => slice_resource (if S l loc then sh1 else Share.bot) (w @ loc))\n           g (Hg: resource_at g = fun loc => slice_resource (if S l loc then sh2 else Share.bot) (w @ loc))\n           (H1: join f g w),\n           allp (jam (S l) (Q l sh1) noat) f.\nProof.\nintros.\n(*assert (rsh3: readable_share sh3) by (eapply readable_share_join ; eauto). *)\nintro l'.\nspecialize ( H0 l').\nunfold jam in H0 |- *.\nsimpl in H0|-*.\nif_tac.\ndestruct (PARAMETRIC l l') as [pp [ok ?]]; clear PARAMETRIC.\nrewrite H3 in H0 |- *; clear H3.\ndestruct H0 as [rsh3 [k [? ?]]].\nexists rsh1, k; split; auto.\nclear H0.\ncase_eq (w @ l'); intros.\ninversion2 H0 H3. \ndestruct p.\ninversion2 H0 H3.\ngeneralize (resource_at_join _ _ _ l' H1); intro.\ngeneralize (f_equal (resource_at f) (refl_equal l')); intro.\npattern f at 1 in H4; rewrite Hf in H4.\nrewrite H0 in H4.\nrewrite H4.\nrewrite if_true in H4|-* by auto.\nsimpl.\ndestruct (readable_share_dec sh1); [ | contradiction].\nreplace (level f) with (level w). \nrewrite H7.\nf_equal. apply proof_irr.\napply join_level in H1; intuition.\ncongruence.\n(* noat case *)\ngeneralize (resource_at_join _ _ _ l' H1); intro.\napply split_identity in H3; auto.\nQed.\n\nLemma slice_resource_identity:\n  forall r, identity r -> slice_resource Share.bot r = r.\nProof.\n intros.\n destruct r; simpl in *; auto.\n assert (sh = retainer_part Share.bot).\n   unfold retainer_part. rewrite Share.glb_bot.\n   apply identity_NO in H.\n   destruct H as [|]. inv H. auto. destruct H as [? [? ?]]. inv H.\n   subst; f_equal. apply proof_irr.\n   apply YES_not_identity in H. contradiction.\nQed.\n\nDefinition splittable {A} {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A} (Q: Share.t -> pred A) := \n  forall (sh1 sh2 sh3: Share.t) (rsh1: readable_share sh1) (rsh2: readable_share sh2),\n    join sh1 sh2 sh3 ->\n    Q sh1 * Q sh2 = Q sh3.\n\n(*Lemma jam_noat_splittable:\n  forall (S': address -> address -> Prop) S\n           (Q: address -> spec)\n     (PARAMETRIC: spec_parametric Q),\n    forall l, splittable (fun sh => allp (@jam _ _ _ _ _ _ (S' l) (S l) (Q l sh) noat)).\nProof.\nunfold splittable; intros.\napply pred_ext; intro w; simpl.\n+  intros [w1 [w2 [? [? ?]]]].\n  intro l'. specialize ( H1 l'); specialize ( H2 l').\n  unfold jam in *.\n  revert H1 H2.\n  if_tac.\n  - intros.\n    specialize (PARAMETRIC l l').\n    destruct PARAMETRIC as [pp [ok ?]].\n    rewrite H4 in H2. destruct H2 as [rsh1' [k1 [G1 H1']]]. \n    rewrite H4 in H3; destruct H3 as [rsh2' [k2 [G2 H2']]]. \n    rewrite H4.\n    assert (rsh3 := join_readable1 H rsh1).\n    exists rsh3.\n    exists k2.\n    generalize (resource_at_join _ _ _ l' H0); rewrite H1'; rewrite H2'; intro Hx.\n    generalize H; clear H.\n    inv Hx. \n    split; auto.\n    simpl.\n    replace (level w1) with (level w) by (apply join_level in H0; intuition).\n    pose proof (join_eq H RJ). subst sh5.\n    f_equal; auto with extensionality.\n  - intros.\n    generalize (resource_at_join _ _ _ l' H0); intro.\n    apply H2 in H4. rewrite H4 in H3; auto.\n+ intros.\n  pose (f loc := if S l loc then slice_resource sh1 (w @ loc) else w@loc).\n  assert (Vf: CompCert_AV.valid (res_option oo f)). {\n     apply slice_resource_valid.\n     intros. specialize (H0 l0). rewrite if_false in H0; auto.\n  }\n  destruct (make_rmap _ Vf (level w)) as [phi [Gf Hf]].\n  {\n    extensionality loc; unfold compose, f.\n    specialize (PARAMETRIC l loc).\n    destruct PARAMETRIC as [pp [ok Jf]].\n    specialize ( H0 loc).\n    destruct (S l loc).\n    rewrite Jf in H0.\n    destruct H0 as [p3 [k3 [G0 H0]]].\n    generalize (resource_at_approx w loc); intro.\n    rewrite H0 in H1.\n    inversion H1; clear H1; auto.\n    rewrite H0.\n    simpl.\n    destruct (readable_share_dec sh1); auto.\n    revert H0; case_eq (w @ loc); intros; try contradiction; simpl; f_equal; auto.\n    apply resource_at_approx.\n  }\n  pose (g loc := if S l loc then slice_resource sh2 (w @ loc) else w@loc).\n  assert (Vg: CompCert_AV.valid (res_option oo g)). {\n     apply slice_resource_valid.\n     intros. specialize (H0 l0). rewrite if_false in H0; auto.\n  }\n  destruct (make_rmap _ Vg (level w)) as [phi' [Gg Hg]].\n  {\n    extensionality loc; unfold compose, g.\n    specialize (PARAMETRIC l loc).\n    destruct PARAMETRIC as [pp [ok Jg]].\n    specialize ( H0 loc).\n    destruct (S l loc).\n    rewrite Jg in H0.\n    destruct H0 as [p3 [k3 [G0 H0]]].\n    generalize (resource_at_approx w loc); intro.\n    rewrite H0 in H1.\n    inversion H1; clear H1; auto.\n    rewrite H0.\n    simpl.\n    destruct (readable_share_dec sh2); auto.\n    revert H0; case_eq (w @ loc); intros; try contradiction; simpl; f_equal; auto.\n    apply resource_at_approx.\n  }\n  unfold f,g in *; clear f g.\n  rename phi into f; rename phi' into g.\n  assert (join f g w). {\n   apply resource_at_join2; auto.\n   intro.\n   rewrite Hf; rewrite Hg.\n   clear - PARAMETRIC H H0 rsh1 rsh2.\n   specialize ( H0 loc).\n   if_tac in H0.\n   destruct (PARAMETRIC l loc) as [pp [ok ?]]; clear PARAMETRIC.\n   rewrite H2 in H0.\n   destruct H0 as [? [? [? ?]]].\n   rewrite H3.\n   generalize (preds_fmap (approx (level w)) (approx (level w)) pp); intro.\n   simpl.\n   destruct (readable_share_dec sh1); [ | contradiction].\n   destruct (readable_share_dec sh2); [ | contradiction].\n   constructor; auto.\n   apply identity_unit' in H0. apply H0.\n  }\n  econstructor; econstructor; split; [apply H1|].\n  split.\n  eapply jam_noat_splittable_aux; eauto.\n  simpl; auto.\n  rewrite Hf. extensionality loc. if_tac. auto.\n  clear - H0 H2. specialize (H0 loc). rewrite if_false in H0 by auto.\n  symmetry; apply slice_resource_identity; auto.\n  rewrite Hg. extensionality loc. if_tac. auto.\n  clear - H0 H2. specialize (H0 loc). rewrite if_false in H0 by auto.\n  symmetry; apply slice_resource_identity; auto.\n  apply join_comm in H.\n  eapply jam_noat_splittable_aux.\n  auto. auto. apply rsh1. eauto. 4: apply (join_comm H1).\n  simpl; auto.\n  rewrite Hg. extensionality loc. if_tac. auto.\n  clear - H0 H2. specialize (H0 loc). rewrite if_false in H0 by auto.\n  symmetry; apply slice_resource_identity; auto.\n  rewrite Hf. extensionality loc. if_tac. auto.\n  clear - H0 H2. specialize (H0 loc). rewrite if_false in H0 by auto.\n  symmetry; apply slice_resource_identity; auto.\nQed.*)\n\n(*Lemma address_mapsto_splittable:\n      forall ch v l, splittable (fun sh => address_mapsto ch v sh l).\nProof.\nintros.\nunfold splittable.\nintros ? ? ? rsh1 rsh2 H.\napply pred_ext; intros ? ?.\n*\ndestruct H0 as [m1 [m2 [? [? ?]]]].\nunfold address_mapsto in *.\ndestruct H1 as [bl1 [[[LEN1 DECODE1] ?] Hg1]]; destruct H2 as [bl2 [[[LEN2 DECODE2] ?] Hg2]].\nexists bl1; split; [split|]; auto.\nsimpl; auto.\nintro loc; specialize ( H1 loc); specialize ( H2 loc).\nunfold jam in *.\napply (resource_at_join _ _ _ loc) in H0.\nhnf in H1, H2|-*.\nif_tac.\nhnf in H1,H2.\ndestruct H1; destruct H2.\nhnf.\nexists (join_readable1 H rsh1).\nunfold yesat_raw in *.\nhnf in H1,H2|-*.\nrewrite preds_fmap_NoneP in *.\nrepeat proof_irr.\nrewrite H1 in H0; rewrite H2 in H0; clear H1 H2.\nunfold yesat_raw.\ninv H0.\npose proof (join_eq H RJ); subst sh5; clear RJ rsh5 rsh6.\nf_equal.\napply proof_irr.\napply H1 in H0. do 3 red in H2|-*. rewrite <- H0; auto.\nsimpl; rewrite <- (Hg1 _ _ (ghost_of_join _ _ _ H0)); auto.\n*\nrename a into m.\nhnf in H0|-*.\ndestruct H0 as [bl [[[? [? Halign]] ?] Hg]].\npose (rslice (rsh : Share.t) (loc: address) := if adr_range_dec l (size_chunk ch) loc then rsh else Share.bot).\nassert (G1: forall l0 : AV.address,\n  ~ adr_range l (size_chunk ch) l0 -> identity (m @ l0)). {\n   intros. specialize (H2 l0). rewrite  jam_false in H2 by auto.\n   apply H2.\n }\ndestruct (make_slice_rmap m _ (adr_range_dec l (size_chunk ch)) sh1 G1)\n  as [m1 [? ?]].\ndestruct (make_slice_rmap m _ (adr_range_dec l (size_chunk ch)) sh2 G1)\n  as [m2 [? ?]].\nexists m1, m2.\nsplit3.\n+\napply resource_at_join2; try congruence.\nintro loc.\nrewrite H4,H6. clear H4 H6. clear H3 H5. clear m1 m2.\nspecialize (G1 loc). clear rslice.\nspecialize (H2 loc). hnf in H2.\nif_tac.\ndestruct H2 as [rsh ?].\nhnf in H2. rewrite H2. clear H2.\nunfold slice_resource.\ndestruct (readable_share_dec sh1); [ | contradiction].\ndestruct (readable_share_dec sh2); [ | contradiction].\nconstructor. auto.\ndo 3 red in H2. apply identity_unit' in H2. apply H2; auto.\n+\nexists bl; repeat split; auto.\nintro loc; specialize ( H2 loc); unfold jam in *;  hnf in H2|-*; if_tac; auto.\nexists rsh1.\nhnf.\nrewrite H4.\nrewrite if_true by auto.\nunfold slice_resource.\ndestruct H2. hnf in H2.\nrewrite H2.\ndestruct (readable_share_dec sh1); [ | contradiction].\nf_equal. apply proof_irr.\ndo 3 red in H2|-*.\nrewrite H4. rewrite if_false by auto. auto.\n+\nexists bl; repeat split; auto.\nintro loc; specialize ( H2 loc); unfold jam in *;  hnf in H2|-*; if_tac; auto.\nexists rsh2.\nhnf.\nrewrite H6.\nrewrite if_true by auto.\nunfold slice_resource.\ndestruct H2. hnf in H2.\nrewrite H2.\ndestruct (readable_share_dec sh2); [ | contradiction].\nf_equal. apply proof_irr.\ndo 3 red in H2|-*.\nrewrite H6. rewrite if_false by auto. auto.\nQed.\n\nLemma VALspec_splittable: forall l, splittable (fun sh => VALspec sh l).\nProof.\napply jam_noat_splittable.\napply VALspec_parametric.\nQed.\n\nLemma LKspec_splittable size: forall R l, splittable (fun sh => LKspec size R sh l).\nProof.\nintro.\napply jam_noat_splittable.\napply LKspec_parametric.\nQed.\n\nLemma VALspec_range_splittable: forall n l, splittable (fun sh => VALspec_range n sh l).\nProof.\nintro.\napply jam_noat_splittable.\napply VALspec_parametric.\nQed. *)\n\nDefinition share_oblivious (P: pred rmap) :=\n  forall w w',\n   (forall l, match w' @ l , w @ l with\n                 | NO _ _, NO _ _ => True\n                 | YES _ sh1 k1 p1 , YES _ sh2 k2 p2 => k1=k2 /\\ p1=p2\n                 | PURE k1 p1, PURE k2 p2 => k1=k2 /\\ p1=p2\n                 | _ , _ => False\n                 end) ->\n     P w' -> P w.\n\n(*Lemma intersection_splittable:\n    forall (S': address -> address -> Prop) S P Q, \n         spec_parametric P -> \n         (forall l, share_oblivious (Q l)) ->\n    forall l, splittable (fun sh => allp (@jam _ _ _ _ _ _ (S' l) (S l) (P l sh) noat) && Q l).\nProof.\nintros.\nintro; intros.\ngeneralize (jam_noat_splittable S' S _ H); intro.\nrewrite <- (H2  _ _ _  _ rsh1 rsh2 H1).\napply pred_ext; intros w ?.\ndestruct H3 as [w1 [w2 [? [[? ?] [? ?]]]]].\nsplit.\nexists w1; exists w2; auto.\neapply H0; eauto.\nintro.\ngeneralize (resource_at_join _ _ _ l0 H3).\ncase_eq (w2 @ l0); case_eq (w @ l0); intros; auto; try solve [inv H10].\ncase_eq (w1 @ l0); intros.\nrewrite H11 in H10; inv H10. \nrewrite H11 in H10; inv H10.\nspecialize (H4 l0).\nspecialize (H6 l0).\nhnf in H4,H6.\nif_tac in H4; auto.\nspecialize (H l l0).\ndestruct H as [pp [ok ?]].\nrewrite H in H4; rewrite H in H6.\ndestruct H4 as [? [? [? ?]]].\ndestruct H6 as [? [? [? ?]]].\ninversion2 H11 H12.\ninversion2 H9 H13.\ndo 3 red in H4. rewrite H11 in H4.\ncontradiction (YES_not_identity _ _ _ _ H4).\nrewrite H11 in H10; inv H10.\ndestruct (w1 @ l0); inv H10; auto.\ninv H10; auto.\ndestruct H3 as [[w1 [w2 [? [? ?]]]] ?].\nexists w1; exists w2.\nsplit; auto.\nsplit; split; auto.\napply (H0 l w1 w).\nintro l0; generalize (resource_at_join _ _ _ l0 H3).\ncase_eq (w @ l0); case_eq (w1 @ l0); intros; auto; try solve [inv H9].\ncase_eq (w2 @ l0); intros.\nrewrite H10 in H9; inv H9. \nrewrite H10 in H9; inv H9.\nspecialize (H l l0).\ndestruct H as [pp [ok ?]].\nspecialize (H4 l0).\nspecialize (H5 l0).\nhnf in H4,H5.\nif_tac in H4.\nrewrite H in H4,H5.\ndestruct H4 as [? [? [? ?]]].\ndestruct H5 as [? [? [? ?]]].\ncongruence.\ndo 3 red in H5. rewrite H10 in H5. \ncontradiction (YES_not_identity _ _ _ _ H5).\nrewrite H10 in H9; inv H9.\ninv H9; auto.\ninv H9; auto.\nauto.\napply (H0 l w2 w ).\nintro l0; generalize (resource_at_join _ _ _ l0 H3).\ncase_eq (w @ l0); case_eq (w2 @ l0); intros; auto; try solve [inv H9].\ninv H9.\nspecialize (H l l0).\ndestruct H as [pp [ok ?]].\nspecialize (H4 l0).\nspecialize (H5 l0).\nhnf in H4,H5.\nif_tac in H4.\nrewrite H in H4,H5.\ndestruct H4 as [? [? [? ?]]].\ndestruct H5 as [? [? [? ?]]].\ncongruence.\ndo 3 red in H4. rewrite <- H11 in H4.\ncontradiction (YES_not_identity _ _ _ _ H4).\ninv H9; auto. inv H9; auto.\nauto.\nQed. *)\n\nLemma not_readable_share_retainer_part_eq:\n  forall sh, ~ readable_share sh -> retainer_part sh = sh.\n   intros.\n    apply not_not_share_identity in H.\n    unfold retainer_part.\n    rewrite (comp_parts comp_Lsh_Rsh sh) at 2.\n    apply identity_share_bot in H; rewrite H.\n    rewrite Share.lub_bot. auto.\nQed.\n\nLemma slice_resource_resource_share: forall r sh sh',\n  resource_share r = Some sh ->\n  join_sub sh' sh ->\n  resource_share (slice_resource sh' r) = Some sh'.\nProof.\n  intros.\n  destruct r; inv H; unfold slice_resource; simpl.\n  + f_equal.\n    assert (~readable_share sh'). contradict n. destruct H0.\n    eapply join_readable1; eauto.\n    apply not_readable_share_retainer_part_eq; auto.\n  + destruct (readable_share_dec sh'); simpl; auto.\nQed.\n\nLemma slice_resource_nonlock: forall r sh sh',\n  resource_share r = Some sh ->\n  join_sub sh' sh ->\n  nonlock r ->\n  nonlock (slice_resource sh' r).\nProof.\n  intros.\n  destruct r; inv H; unfold slice_resource; simpl; auto.\n  destruct (readable_share_dec sh'); simpl; auto.\nQed.\n\nLemma NO_ext: forall sh1 sh2 rsh1 rsh2, sh1=sh2 -> NO sh1 rsh1 = NO sh2 rsh2.\nProof. intros. subst sh1. f_equal. apply proof_irr. Qed.\n\nLemma join_sub_is_slice_resource: forall r r' sh',\n  join_sub r' r ->\n  resource_share r' = Some sh' ->\n  r' = slice_resource sh' r.\nProof.\n  intros.\n  destruct H as [r'' ?].\n  destruct r, r'; inv H; inv H0; simpl.\n  + f_equal.\n    clear - n0.\n    apply NO_ext. symmetry.\n    rewrite not_readable_share_retainer_part_eq; auto.\n  + destruct (readable_share_dec sh'); [ contradiction |].\n    apply NO_ext; auto.\n  + destruct (readable_share_dec sh'); [| contradiction ].\n    f_equal. apply proof_irr.\n  + destruct (readable_share_dec sh'); [| contradiction ].\n    f_equal. apply proof_irr.\nQed.\n\nLemma slice_resource_share_join: forall sh1 sh2 sh r,\n  join sh1 sh2 sh ->\n  resource_share r = Some sh ->\n  join (slice_resource sh1 r) (slice_resource sh2 r) r.\nProof.\n  intros.\n  destruct r; simpl in *.\n*\n  constructor. inv H0.\n  assert (~readable_share sh1) by (contradict n; eapply join_readable1; eauto).\n  assert (~readable_share sh2) by (contradict n; eapply join_readable2; eauto).\n  rewrite !(not_readable_share_retainer_part_eq); auto.\n*\n  inv H0.\n  destruct (readable_share_dec sh1), (readable_share_dec sh2);\n  try (constructor; auto).\n  contradiction (join_unreadable_shares H n n0).\n*\n  constructor.\nQed.\n\nDefinition resource_share_split (p q r: address -> pred rmap): Prop :=\n  exists p' q' r' p_sh q_sh r_sh,\n    is_resource_pred p p' /\\\n    is_resource_pred q q' /\\\n    is_resource_pred r r' /\\\n    join q_sh r_sh p_sh /\\\n    (forall res l n, p' res l n ->\n      resource_share res = Some p_sh /\\\n      q' (slice_resource q_sh res) l n /\\\n      r' (slice_resource r_sh res) l n) /\\\n    (forall p_res q_res r_res l n,\n      join q_res r_res p_res ->\n      q' q_res l n ->\n      r' r_res l n ->\n      p' p_res l n).\n\n(* We should use this lemma to prove all share_join lemmas, also all splittable lemmas. *)\nLemma allp_jam_share_split: forall (P: address -> Prop) (p q r: address -> pred rmap)\n  (P_DEC: forall l, {P l} + {~ P l}),\n  resource_share_split p q r ->\n  allp (jam P_DEC p noat) && noghost =\n  (allp (jam P_DEC q noat) && noghost) * (allp (jam P_DEC r noat) && noghost).\nProof.\n  intros.\n  destruct H as [p' [q' [r' [p_sh [q_sh [r_sh [? [? [? [? [? ?]]]]]]]]]]].\n  apply pred_ext; intros w; simpl; intros.\n  + destruct H5 as [H5 Hg].\n    destruct (make_slice_rmap w P P_DEC q_sh) as [w1 [? ?]].\n    {\n      intros; specialize (H5 l).\n      rewrite if_false in H5 by auto.\n      auto.\n    }\n    destruct (make_slice_rmap w P P_DEC r_sh) as [w2 [? ?]].\n    {\n      intros; specialize (H5 l).\n      rewrite if_false in H5 by auto.\n      auto.\n    }\n    exists w1, w2.\n    split3.\n    - apply resource_at_join2; try congruence.\n      intro l.\n      destruct H7, H9; rewrite H7, H9; clear H7 H9.\n      specialize (H5 l); destruct (P_DEC l).\n      * eapply slice_resource_share_join; eauto.\n        rewrite H in H5.\n        apply H3 in H5.\n        tauto.\n      * apply identity_unit' in H5.\n        exact H5.\n      * destruct H7 as [? ->], H9 as [? ->].\n        apply identity_unit'; auto.\n    - destruct H7 as [H7 ->]; split; auto.\n      intros l.\n      rewrite H0, H7, H6.\n      specialize (H5 l).\n      rewrite H in H5.\n      if_tac.\n      * apply H3 in H5.\n        tauto.\n      * auto.\n    - destruct H9 as [H9 ->]; split; auto.\n      intros l.\n      rewrite H1, H9, H8.\n      specialize (H5 l).\n      rewrite H in H5.\n      if_tac.\n      * apply H3 in H5.\n        tauto.\n      * auto.\n  + destruct H5 as [y [z [? [? ?]]]].\n    destruct H6 as [? Hg1], H7 as [? Hg2]; split.\n    intro b; specialize (H6 b); specialize (H7 b).\n    if_tac.\n    - rewrite H; rewrite H0 in H6; rewrite H1 in H7.\n      destruct (join_level _ _ _ H5).\n      rewrite H9 in H6; rewrite H10 in H7.\n      eapply H4; eauto.\n      apply resource_at_join; auto.\n    - apply resource_at_join with (loc := b) in H5.\n      apply H6 in H5; rewrite <- H5; auto.\n    - rewrite <- (Hg1 _ _ (ghost_of_join _ _ _ H5)); auto.\nQed.\n\nLemma address_mapsto_share_join:\n forall (sh1 sh2 sh : share) ch v a,\n   join sh1 sh2 sh ->\n   readable_share sh1 -> readable_share sh2 ->\n   address_mapsto ch v sh1 a * address_mapsto ch v sh2 a \n    = address_mapsto ch v sh a.\nProof.\n  intros ? ? ? ? ? ? H rsh1 rsh2.\n(*  rename H1 into NON_UNIT1, H2 into NON_UNIT2.\n  assert (NON_UNIT: nonunit sh) by (eapply nonunit_join; eauto; auto with typeclass_instances).\n*)\n  symmetry.\n  unfold address_mapsto.\n  transitivity\n   (EX  bl : list memval,\n    !!(length bl = size_chunk_nat ch /\\\n       decode_val ch bl = v /\\ (align_chunk ch | snd a)) &&\n   ((allp\n      (jam (adr_range_dec a (size_chunk ch))\n         (fun loc : address =>\n          yesat NoneP (VAL (nth (nat_of_Z (snd loc - snd a)) bl Undef)) sh1\n            loc) noat) && noghost) *\n    (allp\n      (jam (adr_range_dec a (size_chunk ch))\n         (fun loc : address =>\n          yesat NoneP (VAL (nth (nat_of_Z (snd loc - snd a)) bl Undef)) sh2\n            loc) noat) && noghost))).\n  + pose proof log_normalize.exp_congr (pred rmap) _ (list memval).\n    simpl in H0.\n    apply H0; clear H0.\n    intros b.\n    rewrite !andp_assoc; f_equal.\n    apply allp_jam_share_split.\n    do 3 eexists.\n    exists sh, sh1, sh2.\n    split; [| split; [| split; [| split; [| split]]]].\n    - apply is_resource_pred_YES_VAL'.\n    - apply is_resource_pred_YES_VAL'.\n    - apply is_resource_pred_YES_VAL'.\n    - auto.\n    - simpl; intros.\n      destruct H0.\n      split; [subst; auto |].\n      split.\n      * exists rsh1.\n        subst; simpl.\n        destruct (readable_share_dec sh1); [| contradiction].\n        f_equal.\n        auto with extensionality.\n      * exists rsh2.\n        subst; simpl.\n        destruct (readable_share_dec sh); [| contradiction].\n        destruct (readable_share_dec sh2); [| contradiction].\n        f_equal.\n        auto with extensionality. \n    - simpl; intros.\n      destruct H1,H2. repeat proof_irr.\n      exists (join_readable1 H rsh1).\n      subst.\n      inv H0.\n      apply YES_ext.\n      eapply join_eq; eauto.\n  + apply pred_ext.\n    - apply exp_left; intro bl.\n      apply prop_andp_left; intro.\n      rewrite exp_sepcon1.\n      apply (exp_right bl).\n      rewrite exp_sepcon2.\n      apply (exp_right bl).\n      rewrite andp_assoc, sepcon_andp_prop1.\n      apply andp_right; [intros w _; simpl; auto |].\n      rewrite andp_assoc, sepcon_andp_prop.\n      apply andp_right; [intros w _; simpl; auto |].\n      auto.\n    - rewrite exp_sepcon1.\n      apply exp_left; intro bl1.\n      rewrite exp_sepcon2.\n      apply exp_left; intro bl2.\n      rewrite andp_assoc, sepcon_andp_prop1.\n      apply prop_andp_left; intro.\n      rewrite andp_assoc, sepcon_andp_prop.\n      apply prop_andp_left; intro.\n      apply (exp_right bl1).\n      apply andp_right; [intros w _; simpl; auto |].\n      intros w ?.\n      destruct H2 as [w1 [w2 [? [? ?]]]].\n      exists w1, w2.\n      split; [| split]; auto.\n      destruct H4 as [H4 Hg]; split; auto.\n      intro l; destruct H3; specialize (H3 l); specialize (H4 l).\n      simpl in H3, H4 |- *.\n      if_tac; auto.\n      destruct H3, H4. exists rsh2.\n      apply resource_at_join with (loc := l) in H2.\n      rewrite H3, H4 in H2; inv H2.\n      rewrite H12. rewrite H4. apply YES_ext. auto.\nQed.\n\nLemma nonlock_permission_bytes_address_mapsto_join:\n forall (sh1 sh2 sh : share) ch v a,\n   join sh1 sh2 sh ->\n   readable_share sh2 ->\n   nonlock_permission_bytes sh1 a (Memdata.size_chunk ch)\n     * address_mapsto ch v sh2 a \n    = address_mapsto ch v sh a.\nProof.\nintros. rename H0 into rsh2.\nunfold nonlock_permission_bytes, address_mapsto.\nrewrite exp_sepcon2.\nf_equal. extensionality bl.\nrewrite !andp_assoc, sepcon_andp_prop.\nf_equal.\napply pred_ext.\n*\n intros z [x [y [? [? ?]]]].\n destruct H1 as [H1 Hg1], H2 as [H2 Hg2]; split.\n intro b; specialize (H1 b); specialize (H2 b).\n pose proof (resource_at_join _ _ _ b H0).\n hnf in H1,H2|-*.\n if_tac.\n +\n  destruct H2 as [p ?].\n  hnf in H2. rewrite H2 in *. clear H2.\n  destruct H1 as [H1 H1'].\n  hnf in H1, H1'. unfold resource_share in H1.\n  assert (p8 := join_readable2 H p).\n  exists p8.\n  destruct (x @ b); inv H1.\n  -\n    inv H3.\n    pose proof (join_eq H RJ); subst sh4. clear RJ.\n    hnf. rewrite <- H8; clear H8.\n    f_equal. apply proof_irr.\n  -\n   clear H1'.  inv H3. \n   hnf. rewrite <- H10. clear H10. simpl.\n    pose proof (join_eq H RJ); subst sh4. clear RJ.\n   f_equal. apply proof_irr.\n +\n   do 3 red in H1,H2|-*. \n   apply join_unit1_e in H3; auto.\n   rewrite <- H3; auto.\n + simpl; rewrite <- (Hg1 _ _ (ghost_of_join _ _ _ H0)); auto.\n*\n  assert (rsh := join_readable2 H rsh2).\n  intros w ?.\n  destruct H0 as [H0 Hg]; hnf in H0.\n  destruct (make_slice_rmap w _ (adr_range_dec a (size_chunk ch)) sh1)\n   as [w1 [? ?]].\n  intros. specialize (H0 l). simpl in H0. rewrite if_false in H0; auto. \n  destruct (make_slice_rmap w _ (adr_range_dec a (size_chunk ch)) sh2)\n   as [w2 [? ?]].\n  intros. specialize (H0 l). simpl in H0. rewrite if_false in H0; auto. \n  exists w1, w2.\n  destruct H2 as [H2 Hg1], H4 as [H4 Hg2].\n  split3.\n +\n   eapply resource_at_join2; try omega.\n  intro . rewrite H2,H4. clear dependent w1. clear dependent w2.\n  specialize (H0 loc). hnf in H0.  \n  if_tac in H0. destruct H0 as [rsh' H0]. proof_irr. rewrite H0.\n  unfold slice_resource.\n  destruct (readable_share_dec sh2); [ | contradiction]. proof_irr.\n  destruct (readable_share_dec sh1).\n  constructor; auto.\n  constructor; auto.\n  do 3 red in H0.\n  apply identity_unit' in H0. apply H0.\n  rewrite Hg1, Hg2; apply identity_unit'; auto.\n +\n   split.\n   intro loc; hnf. simpl. rewrite H2.\n  clear dependent w1. clear dependent w2.\n  specialize (H0 loc). hnf in H0.  \n  if_tac in H0.\n  -\n   destruct H0. proof_irr. rewrite H0.\n   unfold slice_resource.\n   destruct (readable_share_dec sh1).\n   simpl. split; auto.\n   split; simpl; auto.\n  -\n   apply H0.\n  - simpl; rewrite Hg1; auto.\n + split.\n   intro loc; hnf. simpl. rewrite H4.  simpl.\n  clear dependent w1. clear dependent w2.\n  specialize (H0 loc). hnf in H0.  \n  if_tac in H0.\n  -\n   exists rsh2.\n   destruct H0 as [p0 H0]. proof_irr. simpl in H0.\n   rewrite H0. clear H0. simpl.\n   destruct (readable_share_dec sh2); [ | contradiction]. proof_irr.\n   reflexivity.\n - apply H0.\n - simpl; rewrite Hg2; auto.\nQed.\n\nLemma VALspec_range_share_join:\n forall sh1 sh2 sh n p,\n  readable_share sh1 ->\n  readable_share sh2 ->\n  join sh1 sh2 sh ->\n  VALspec_range n sh1 p *\n  VALspec_range n sh2 p =\n  VALspec_range n sh p.\nProof.\n  intros.\n  symmetry.\n  apply allp_jam_share_split.\n  do 3 eexists.\n  exists sh, sh1, sh2. \n  split; [| split; [| split; [| split; [| split]]]].\n  + apply is_resource_pred_YES_VAL.\n  + apply is_resource_pred_YES_VAL.\n  + apply is_resource_pred_YES_VAL.\n  + auto.\n  + simpl; intros.\n    destruct H2 as [x [rsh ?]].\n    split; [subst; simpl; auto |].\n    split; [exists x, H | exists x, H0].\n    - subst. simpl.\n      destruct (readable_share_dec sh1); [ | contradiction].\n      f_equal. apply proof_irr.\n    - subst. simpl.\n      destruct (readable_share_dec sh2); [ | contradiction].\n      f_equal. apply proof_irr.\n  + simpl; intros.\n    destruct H3 as [? [? ?]], H4 as [? [? ?]].\n    exists x. exists (join_readable1 H1 H).\n    subst.\n    inv H2. apply YES_ext. eapply join_eq; eauto.\nQed.\n\nLemma nonlock_permission_bytes_share_join:\n forall sh1 sh2 sh a n,\n  join sh1 sh2 sh ->\n  nonlock_permission_bytes sh1 a n *\n  nonlock_permission_bytes sh2 a n =\n  nonlock_permission_bytes sh a n.\nProof.\n  intros.\n  symmetry.\n  apply allp_jam_share_split.\n  do 3 eexists.\n  exists sh, sh1, sh2.\n  split; [| split; [| split; [| split; [| split]]]].\n  + apply is_resource_pred_nonlock_shareat.\n  + apply is_resource_pred_nonlock_shareat.\n  + apply is_resource_pred_nonlock_shareat.\n  + auto.\n  + simpl; intros.\n    destruct H0.\n    split; [auto |].\n    split; split.\n    - eapply slice_resource_resource_share; [eauto | eexists; eauto ].\n    - eapply slice_resource_nonlock; [eauto | eexists; eauto | auto].\n    - eapply slice_resource_resource_share; [eauto | eexists; eapply join_comm; eauto].\n    - eapply slice_resource_nonlock; [eauto | eexists; eapply join_comm; eauto | auto].\n  + simpl; intros.\n    destruct H1, H2.\n    split.\n    - eapply (resource_share_join q_res r_res); eauto.\n    - eapply (nonlock_join q_res r_res); eauto.\nQed.\n\nLemma nonlock_permission_bytes_VALspec_range_join:\n forall sh1 sh2 (rsh2: readable_share sh2) sh p n,\n  join sh1 sh2 sh ->\n  nonlock_permission_bytes sh1 p n *\n  VALspec_range n sh2 p =\n  VALspec_range n sh p.\nProof.\n  intros.\n  symmetry.\n  apply allp_jam_share_split.\n  do 3 eexists.\n  exists sh, sh1, sh2.\n  split; [| split; [| split; [| split; [| split]]]].\n  + apply is_resource_pred_YES_VAL.\n  + apply is_resource_pred_nonlock_shareat.\n  + apply is_resource_pred_YES_VAL.\n  + auto.\n  + simpl; intros.\n    destruct H0 as [? [? ?]]; subst; split; [| split; [split |]].\n    - simpl; auto.\n    - simpl.\n      destruct (readable_share_dec sh1); reflexivity.\n    - simpl.\n      destruct (readable_share_dec sh1); simpl; auto.\n    - simpl.\n      exists x, rsh2.\n      destruct (readable_share_dec sh2); [ | contradiction].\n      apply YES_ext. auto.\n  + simpl; intros.\n    destruct H2 as [? [? ?]].\n    subst. proof_irr.\n    exists x, (join_readable2 H rsh2).\n    destruct H1.\n    destruct q_res; simpl in H1.\n    - inversion H0; subst. inv H1.\n      apply YES_ext.\n      eapply join_eq; eauto.\n    - inv H1. inv H0. apply YES_ext. eapply join_eq; eauto.\n    - inv H1.\nQed.\n\nLemma is_resource_pred_YES_LK lock_size (l: address) (R: pred rmap) sh:\n  is_resource_pred\n    (fun l' => yesat (SomeP rmaps.Mpred (fun _ => R)) (LK lock_size (snd l' - snd l)) sh l')\n    (fun r (l': address) n => exists p, r = YES sh p (LK lock_size (snd l' - snd l))\n        (SomeP rmaps.Mpred (fun _ => approx n R))).\nProof. hnf; intros. reflexivity. Qed.\n\nLemma LKspec_share_join lock_size:\n forall sh1 sh2 (rsh1: readable_share sh1) (rsh2: readable_share sh2) sh R p,\n  join sh1 sh2 sh ->\n  LKspec lock_size R sh1 p *\n  LKspec lock_size R sh2 p =\n  LKspec lock_size R sh p.\nProof.\n  intros.\n  symmetry.\n  unfold LKspec.\n  apply allp_jam_share_split.\n  do 3 eexists.\n  exists sh, sh1, sh2.\n  split; [| split; [| split; [| split; [| split]]]].\n  + apply is_resource_pred_YES_LK.\n  + apply is_resource_pred_YES_LK.\n  + apply is_resource_pred_YES_LK.\n  + auto.\n  + simpl; intros.\n    destruct (eq_dec p l); subst; destruct H0; split; try solve [subst; simpl; auto];\n    split.\n    - exists rsh1. subst. simpl.\n      destruct (readable_share_dec sh1); [ | contradiction].\n      apply YES_ext; auto.\n    - exists rsh2. subst. simpl.\n      destruct (readable_share_dec sh2); [ | contradiction].\n      apply YES_ext; auto.\n    - exists rsh1. subst. simpl.\n      destruct (readable_share_dec sh1); [ | contradiction].\n      apply YES_ext; auto.\n    - exists rsh2. subst. simpl.\n      destruct (readable_share_dec sh2); [ | contradiction].\n      apply YES_ext; auto.\n  + simpl; intros.\n    destruct (eq_dec p l); subst; destruct H1, H2. repeat proof_irr.\n    - exists (join_readable1 H rsh1). subst. inv H0. apply YES_ext.\n      eapply join_eq; eauto.\n    - exists (join_readable1 H rsh1). subst. inv H0. apply YES_ext.\n      eapply join_eq; eauto.\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/veric/slice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.27512973571032984, "lm_q1q2_score": 0.1536123543474719}}
{"text": "(*********************************************************************************************************************************)\n(* HaskWeakTypes: types HaskWeak                                                                                                 *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import HaskKinds.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskCoreVars.\n\n(* a WeakTypeVar merely wraps a CoreVar and includes its Kind *)\nInductive WeakTypeVar := weakTypeVar : CoreVar -> Kind -> WeakTypeVar.\n\n(*\n * WeakType is much like CoreType, but:\n *   1. avoids mutually-inductive definitions\n *   2. gives special cases for the tycons which have their own typing rules so we can pattern-match on them\n *   3. separates type functions from type constructors, and uses a normal \"AppTy\" for applying the latter\n *)\nInductive WeakType :=\n| WTyVarTy  : WeakTypeVar                                      -> WeakType\n| WAppTy    : WeakType            ->                  WeakType -> WeakType\n| WTyFunApp : TyFun               ->             list WeakType -> WeakType\n| WTyCon    : TyCon                                            -> WeakType\n| WFunTyCon :                                                     WeakType    (* never use (WTyCon ArrowCon);    always use this! *)\n| WCodeTy   : WeakTypeVar         ->                  WeakType -> WeakType    (* never use the raw tycon *)\n| WCoFunTy  : WeakType            -> WeakType      -> WeakType -> WeakType\n| WForAllTy : WeakTypeVar         ->                  WeakType -> WeakType\n| WClassP   : Class_              ->             list WeakType -> WeakType\n| WIParam   : CoreIPName CoreName ->                  WeakType -> WeakType.\n\n(* EqDecidable instances for WeakType *)\nInstance WeakTypeVarEqDecidable : EqDecidable WeakTypeVar.\n  apply Build_EqDecidable.\n  intros.\n  destruct v1 as [cv1 k1].\n  destruct v2 as [cv2 k2].\n  destruct (eqd_dec cv1 cv2); subst.\n    destruct (eqd_dec k1 k2); subst.\n    left; auto.\n    right; intro; apply n; inversion H; subst; auto.\n    right; intro; apply n; inversion H; subst; auto.\n    Defined.\n\n(* a WeakCoerVar just wraps a CoreVar and tags it with the pair of types amongst which it coerces *)\nInductive WeakCoerVar := weakCoerVar : CoreVar -> WeakType -> WeakType -> WeakCoerVar.\n\nInductive WeakCoercion : Type :=\n| WCoVar          : WeakCoerVar                                   -> WeakCoercion (* g      *)\n| WCoType         : WeakType                                      -> WeakCoercion (* \u03c4      *)\n| WCoApp          : WeakCoercion -> WeakCoercion                  -> WeakCoercion (* \u03b3 \u03b3    *)\n| WCoAppT         : WeakCoercion -> WeakType                      -> WeakCoercion (* \u03b3@v    *)\n| WCoAll          : Kind  -> (WeakTypeVar -> WeakCoercion)        -> WeakCoercion (* \u2200a:\u03ba.\u03b3 *)\n| WCoSym          : WeakCoercion                                  -> WeakCoercion (* sym    *)\n| WCoComp         : WeakCoercion -> WeakCoercion                  -> WeakCoercion (* \u25ef      *)\n| WCoLeft         : WeakCoercion                                  -> WeakCoercion (* left   *)\n| WCoRight        : WeakCoercion                                  -> WeakCoercion (* right  *)\n| WCoUnsafe       : WeakType -> WeakType                          -> WeakCoercion (* unsafe *)\n(*| WCoCFApp        : \u2200 n, CoFunConst n -> vec WeakCoercion n       -> WeakCoercion (* C   \u03b3\u207f *)*)\n(*| WCoTFApp        : \u2200 n, TyFunConst n -> vec WeakCoercion n       -> WeakCoercion (* S_n \u03b3\u207f *)*)\n.\n\nFixpoint weakCoercionTypes (wc:WeakCoercion) : WeakType * WeakType :=\nmatch wc with\n| WCoVar     (weakCoerVar _ t1 t2)   => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoType    t                       => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoApp     c1 c2                   => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoAppT    c t                     => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoAll     k f                     => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoSym     c                       => let (t2,t1) := weakCoercionTypes c in (t1,t2)\n| WCoComp    c1 c2                   => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoLeft    c                       => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoRight   c                       => (WFunTyCon,WFunTyCon)   (* FIXME!!! *)\n| WCoUnsafe  t1 t2                   => (t1,t2)\nend.\n\n\n(* this is a trick to allow circular definitions, post-extraction *)\nVariable weakTypeToString : WeakType -> string.\n    Extract Inlined Constant weakTypeToString => \"(coreTypeToString . weakTypeToCoreType)\".\nInstance WeakTypeToString : ToString WeakType := { toString := weakTypeToString }.\n\nVariable tyConToCoreTyCon : TyCon  -> CoreTyCon.           Extract Inlined Constant tyConToCoreTyCon  => \"(\\x -> x)\".\nVariable tyFunToCoreTyCon : TyFun  -> CoreTyCon.           Extract Inlined Constant tyFunToCoreTyCon  => \"(\\x -> x)\".\nCoercion tyConToCoreTyCon : TyCon >-> CoreTyCon.\nCoercion tyFunToCoreTyCon : TyFun >-> CoreTyCon.\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/HaskWeakTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.15354474090855516}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromise.\nRequire Import ReorderPromises.\nRequire Import MemoryReorder.\nRequire Import MemoryFacts.\nRequire Import Pred.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\n\n\nLemma reorder_racy_reserve\n      lang th0 th1\n      (STEP: @Thread.reserve_step lang th0 th1)\n  :\n    (<<CONSISTENT: Local.promise_consistent th0.(Thread.local) -> Local.promise_consistent th1.(Thread.local)>>) /\\\n    (<<RACY: forall loc to ord, Local.is_racy th0.(Thread.local) th0.(Thread.memory) loc to ord -> Local.is_racy th1.(Thread.local) th1.(Thread.memory) loc to ord>>).\nProof.\n  inv STEP; inv STEP0; inv STEP; inv LOCAL; ss. inv PROMISE. splits.\n  { ii. ss. erewrite Memory.add_o in PROMISE; eauto. des_ifs.\n    eapply H; eauto.\n  }\n  { i. inv H. econs; eauto.\n    { eapply Memory.add_get1; eauto. }\n    { ss. erewrite Memory.add_o; eauto. des_ifs.\n      ss. des; clarify. eapply Memory.add_get0 in MEM. des; clarify.\n    }\n  }\nQed.\n\nLemma reorder_abort_reserve\n      lang\n      pf th0 th1 th2\n      (STEP0: @Thread.step lang pf ThreadEvent.failure th0 th1)\n      (STEP1: Thread.reserve_step th1 th2)\n  :\n    exists th1',\n      (<<STEP0: Thread.reserve_step th0 th1'>>) /\\\n      (<<STEP1: Thread.step pf ThreadEvent.failure th1' th2>>).\nProof.\n  hexploit reorder_racy_reserve; eauto. i. des.\n  inv STEP1. inv STEP; inv STEP1; inv LOCAL.\n  inv STEP0; inv STEP. inv LOCAL. inv LOCAL0. esplits.\n  { econs; eauto. econs; eauto. econs; eauto. }\n  { econs 2; eauto. }\nQed.\n\nLemma reorder_abort_reserves\n      lang\n      pf th0 th1 th2\n      (STEP: Thread.step pf ThreadEvent.failure th0 th1)\n      (STEPS: rtc (@Thread.reserve_step lang) th1 th2)\n  :\n    exists th1',\n      (<<STEPS: rtc (@Thread.reserve_step lang) th0 th1'>>) /\\\n      (<<STEP: Thread.step pf ThreadEvent.failure th1' th2>>).\nProof.\n  ginduction STEPS; eauto. i.\n  exploit reorder_abort_reserve; eauto. i. des.\n  exploit IHSTEPS; eauto. i. des. esplits.\n  { econs 2; eauto. }\n  { eauto. }\nQed.\n\nLemma reorder_racy_write_reserve\n      lang\n      pf th0 th1 th2 loc to val ord\n      (STEP0: @Thread.step lang pf (ThreadEvent.racy_write loc to val ord) th0 th1)\n      (STEP1: Thread.reserve_step th1 th2)\n  :\n    exists th1',\n      (<<STEP0: Thread.reserve_step th0 th1'>>) /\\\n      (<<STEP1: Thread.step pf (ThreadEvent.racy_write loc to val ord) th1' th2>>).\nProof.\n  hexploit reorder_racy_reserve; eauto. i. des.\n  inv STEP1. inv STEP; inv STEP1; inv LOCAL.\n  inv STEP0; inv STEP. inv LOCAL. inv LOCAL0. esplits.\n  { econs; eauto. econs; eauto. econs; eauto. }\n  { econs 2; eauto. econs; eauto. }\nQed.\n\nLemma reorder_racy_update_reserve\n      lang\n      pf th0 th1 th2 loc to valr valw ordr ordw\n      (STEP0: @Thread.step lang pf (ThreadEvent.racy_update loc to valr valw ordr ordw) th0 th1)\n      (STEP1: Thread.reserve_step th1 th2)\n  :\n    exists th1',\n      (<<STEP0: Thread.reserve_step th0 th1'>>) /\\\n      (<<STEP1: Thread.step pf (ThreadEvent.racy_update loc to valr valw ordr ordw) th1' th2>>).\nProof.\n  hexploit reorder_racy_reserve; eauto. i. des.\n  inv STEP1. inv STEP; inv STEP1; inv LOCAL.\n  inv STEP0; inv STEP. inv LOCAL. esplits.\n  { econs; eauto. econs; eauto. econs; eauto. }\n  { econs 2; eauto. econs; eauto. econs; eauto. inv LOCAL0.\n    { econs 1; eauto. }\n    { econs 2; eauto. }\n    { econs 3; eauto. }\n  }\nQed.\n\nLemma reorder_failure_reserve\n      lang\n      pf e th0 th1 th2\n      (STEP0: @Thread.step lang pf e th0 th1)\n      (STEP1: Thread.reserve_step th1 th2)\n      (FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure)\n  :\n    exists th1',\n      (<<STEP0: Thread.reserve_step th0 th1'>>) /\\\n      (<<STEP1: Thread.step pf e th1' th2>>).\nProof.\n  destruct e; ss.\n  { eapply reorder_abort_reserve; eauto. }\n  { eapply reorder_racy_write_reserve; eauto. }\n  { eapply reorder_racy_update_reserve; eauto. }\nQed.\n\nLemma reorder_failure_reserves\n      lang\n      pf e th0 th1 th2\n      (STEP: Thread.step pf e th0 th1)\n      (STEPS: rtc (@Thread.reserve_step lang) th1 th2)\n      (FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure)\n  :\n    exists th1',\n      (<<STEPS: rtc (@Thread.reserve_step lang) th0 th1'>>) /\\\n      (<<STEP: Thread.step pf e th1' th2>>).\nProof.\n  ginduction STEPS; eauto. i.\n  exploit reorder_failure_reserve; eauto. i. des.\n  exploit IHSTEPS; eauto. i. des. esplits.\n  { econs 2; eauto. }\n  { eauto. }\nQed.\n\nLemma reorder_reserve_promise\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg2 = Message.reserve /\\ kind2 = Memory.op_kind_cancel /\\\n   lc0 = lc2 /\\ mem0 = mem2) \\/\n  (exists lc1' mem1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 Message.reserve lc2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryReorder.reserve_promise; eauto. i. des; subst.\n  { left. splits; auto. destruct lc0; auto. }\n  right. esplits.\n  { econs; eauto. inv STEP2.\n    eapply memory_concrete_le_closed_msg; try apply CLOSED0.\n    ii. erewrite (@Memory.add_o mem2 mem1') in GET; eauto. des_ifs. }\n  { econs; eauto. }\nQed.\n\nLemma add_non_synch_loc loc0 prom0 loc1 from to msg prom1\n      (NONSYNCH: Memory.nonsynch_loc loc0 prom1)\n      (ADD: Memory.add prom0 loc1 from to msg prom1)\n  :\n    Memory.nonsynch_loc loc0 prom0.\nProof.\n  ii. eapply Memory.add_get1 in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma add_non_synch prom0 loc from to msg prom1\n      (NONSYNCH: Memory.nonsynch prom1)\n      (ADD: Memory.add prom0 loc from to msg prom1)\n  :\n    Memory.nonsynch prom0.\nProof.\n  ii. eapply Memory.add_get1 in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_reserve_read\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1\n      loc2 to2 val2 released2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.read_step lc1 mem1 loc2 to2 val2 released2 ord2 lc2)\n  :\n    exists lc1',\n      (<<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1'>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 Message.reserve lc2 mem1 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. esplits; eauto.\n  { econs; eauto. inv PROMISE.\n    erewrite Memory.add_o in GET; eauto. des_ifs. eauto. }\n  { econs; eauto. }\nQed.\n\nLemma reorder_reserve_write\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 Message.reserve lc2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryReorder.reserve_write; eauto; ss. i. des.\n  esplits.\n  { econs; eauto. i. inv PROMISE. eapply add_non_synch_loc; eauto. }\n  { econs; eauto. }\nQed.\n\nLemma reorder_reserve_write_na\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 val2 ord2 msgs2 kinds2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.write_na_step lc1 sc0 mem1 loc2 from2 to2 val2 ord2 lc2 sc2 mem2 msgs2 kinds2 kind2)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.write_na_step lc0 sc0 mem0 loc2 from2 to2 val2 ord2 lc1' sc2 mem1' msgs2 kinds2 kind2>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 Message.reserve lc2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryReorder.reserve_write_na; eauto; ss. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_reserve_fence\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1\n      ord1 ord2 sc0 sc1\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.fence_step lc1 sc0 ord1 ord2 lc2 sc1)\n  :\n    exists lc1',\n      (<<STEP1: Local.fence_step lc0 sc0 ord1 ord2 lc1' sc1>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 Message.reserve lc2 mem1 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss. esplits.\n  - econs; eauto.\n    + inv PROMISE. i. eapply add_non_synch; eauto.\n    + i. ss. subst. erewrite PROMISES in *; auto.\n      inv PROMISE. eapply Memory.add_get0 in PROMISES0. des.\n      erewrite Memory.bot_get in *. ss.\n  - econs; eauto.\nQed.\n\nLemma reorder_reserve_promise_consistent\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (CONS: Local.promise_consistent lc1):\n  Local.promise_consistent lc0.\nProof.\n  inv STEP1. inv PROMISE.\n  ii. eapply Memory.add_get1 in PROMISE; eauto.\nQed.\n\nLemma reorder_reserve_failure\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.failure_step lc1):\n  Local.failure_step lc0.\nProof.\n  inv STEP2. econs.\n  eapply reorder_reserve_promise_consistent; eauto.\nQed.\n\nLemma reorder_reserve_is_racy\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      loc2 to2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.is_racy lc1 mem1 loc2 to2 ord2):\n  Local.is_racy lc0 mem0 loc2 to2 ord2.\nProof.\n  inv STEP1. inv PROMISE. inv STEP2. ss.\n  revert GET. erewrite Memory.add_o; eauto.\n  revert GETP. erewrite Memory.add_o; eauto.\n  condtac; ss; try congr. i.\n  econs; eauto.\nQed.\n\nLemma reorder_reserve_racy_read\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      loc2 to2 val2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.racy_read_step lc1 mem1 loc2 to2 val2 ord2):\n  Local.racy_read_step lc0 mem0 loc2 to2 val2 ord2.\nProof.\n  inv STEP2. econs.\n  eapply reorder_reserve_is_racy; eauto.\nQed.\n\nLemma reorder_reserve_racy_write\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      loc2 to2 ord2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.racy_write_step lc1 mem1 loc2 to2 ord2):\n  Local.racy_write_step lc0 mem0 loc2 to2 ord2.\nProof.\n  inv STEP2. econs.\n  - eapply reorder_reserve_is_racy; eauto.\n  - eapply reorder_reserve_promise_consistent; eauto.\nQed.\n\nLemma reorder_reserve_racy_update\n      lc0 mem0 loc1 from1 to1 lc1 mem1\n      loc2 to2 ordr2 ordw2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.racy_update_step lc1 mem1 loc2 to2 ordr2 ordw2):\n  Local.racy_update_step lc0 mem0 loc2 to2 ordr2 ordw2.\nProof.\n  inv STEP2.\n  - econs 1; eauto.\n    eapply reorder_reserve_promise_consistent; eauto.\n  - econs 2; eauto.\n    eapply reorder_reserve_promise_consistent; eauto.\n  - econs 3; eauto.\n    + eapply reorder_reserve_is_racy; eauto.\n    + eapply reorder_reserve_promise_consistent; eauto.\nQed.\n\nLemma reorder_reserve_step\n      lang\n      pf1 pf2 e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang pf1 e1 th0 th1)\n      (STEP2: Thread.step pf2 e2 th1 th2)\n      (RESERVE: ThreadEvent.is_reserve e1)\n  :\n  (exists th1',\n    (<<STEP1: Thread.step pf2 e2 th0 th1'>>) /\\\n    (<<STEP2: Thread.step pf1 e1 th1' th2>>)) \\/\n  (th2 = th0 /\\ <<CANCEL: ThreadEvent.is_cancel e2>>)\n.\nProof.\n  unfold ThreadEvent.is_reserve in *. des_ifs.\n  inv STEP1; inv STEP; [|inv LOCAL]. ss.\n  inv STEP2; ss.\n  - inv STEP. ss. exploit reorder_reserve_promise; eauto.\n    i. des; clarify; eauto.\n    left. esplits.\n    + econs 1. econs; eauto.\n    + econs 1. econs; eauto.\n  - left. inv STEP. ss. inv LOCAL0; ss.\n    + esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_read; eauto. i. des. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_write; eauto. i. des. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_read; eauto. i. des.\n      exploit reorder_reserve_write; eauto. i. des.\n      esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_fence; eauto. i. des. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_fence; eauto. i. des. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_failure; eauto. i. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_write_na; eauto. i. des. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_racy_read; eauto. i. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_racy_write; eauto. i. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\n    + exploit reorder_reserve_racy_update; eauto. i. esplits.\n      * econs 2. econs; eauto.\n      * econs 1. econs; eauto; ss.\nQed.\n\nLemma reorder_reserves_step\n      lang\n      pf e2 th0 th1 th2\n      (STEPS1: rtc (@Thread.reserve_step lang) th0 th1)\n      (STEP2: Thread.step pf e2 th1 th2)\n  :\n    (exists th1',\n        (<<STEP1: Thread.step pf e2 th0 th1'>>) /\\\n        (<<STEPS2: rtc (@Thread.reserve_step lang) th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.reserve_step lang) th0 th2>>) /\\ (<<CANCEL: ThreadEvent.is_cancel e2>>))\n.\nProof.\n  eapply Operators_Properties.clos_rt_rt1n_iff in STEPS1.\n  eapply Operators_Properties.clos_rt_rtn1_iff in STEPS1.\n  ginduction STEPS1; i.\n  - esplits; eauto.\n  - inv H. exploit reorder_reserve_step.\n    { eapply STEP. }\n    { eapply STEP2. }\n    { ss. }\n    i. des.\n    { exploit IHSTEPS1; try apply STEP1. i. des.\n      - left. esplits.\n        + eauto.\n        + etrans.\n          { eauto. }\n          { econs 2; [|refl]. econs; eauto. }\n      - right. esplits; eauto. etrans.\n        + eauto.\n        + econs 2; [|refl]. econs; eauto.\n    }\n    { subst. right.\n      eapply Operators_Properties.clos_rt_rtn1_iff in STEPS1.\n      eapply Operators_Properties.clos_rt_rt1n_iff in STEPS1. auto. }\nQed.\n\nLemma reorder_reserves_opt_step\n      lang\n      e2 th0 th1 th2\n      (STEPS1: rtc (@Thread.reserve_step lang) th0 th1)\n      (STEP2: Thread.opt_step e2 th1 th2)\n  :\n    (exists th1',\n        (<<STEP1: Thread.opt_step e2 th0 th1'>>) /\\\n        (<<STEPS2: rtc (@Thread.reserve_step lang) th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.reserve_step lang) th0 th2>>) /\\ (<<CANCEL: ThreadEvent.is_cancel e2>>)).\nProof.\n  inv STEP2.\n  { left. esplits; eauto. econs 1. }\n  { exploit reorder_reserves_step; eauto. i. des.\n    { left. esplits; eauto. econs 2; eauto. }\n    { right. esplits; eauto. }\n  }\nQed.\n\nLemma reorder_reserves_opt_step2\n      lang\n      e2 th0 th1 th2\n      (STEPS1: rtc (@Thread.reserve_step lang) th0 th1)\n      (STEP2: Thread.opt_step e2 th1 th2)\n  :\n    exists th1' e2',\n      (<<STEP1: Thread.opt_step e2' th0 th1'>>) /\\\n      (<<STEPS2: rtc (@Thread.reserve_step lang) th1' th2>>) /\\\n      __guard__(e2' = e2 \\/ e2' = ThreadEvent.silent /\\ <<CANCEL: ThreadEvent.is_cancel e2>>).\nProof.\n  unguard. inv STEP2.\n  { esplits.\n    { econs 1. }\n    { eauto. }\n    { auto. }\n  }\n  { exploit reorder_reserves_step; eauto. i. des.\n    { esplits; eauto. econs 2; eauto. }\n    { esplits; eauto. econs 1; eauto. }\n  }\nQed.\n\nLemma steps_not_reserves_reserves\n      P lang th0 th2\n      (STEPS: rtc (tau (@pred_step P lang)) th0 th2)\n  :\n    exists th1,\n      (<<STEPS1: rtc (tau (@pred_step (P /1\\ fun e => ~ ThreadEvent.is_reserve e) _)) th0 th1>>) /\\\n      (<<STEPS2: rtc (@Thread.reserve_step _) th1 th2>>)\n.\nProof.\n  eapply Operators_Properties.clos_rt_rt1n_iff in STEPS.\n  eapply Operators_Properties.clos_rt_rtn1_iff in STEPS.\n  ginduction STEPS; i.\n  - esplits; eauto.\n  - inv H. inv TSTEP. inv STEP.\n    hexploit IHSTEPS; eauto. i. des.\n    destruct (classic (ThreadEvent.is_reserve e)).\n    + unfold ThreadEvent.is_cancel in H. des_ifs. esplits.\n      * eapply STEPS1.\n      * etrans; eauto. econs 2; [|refl].\n        unfold ThreadEvent.is_reserve in *. des_ifs. econs; eauto.\n    + exploit reorder_reserves_step.\n      { eapply STEPS2. }\n      { eapply STEP0. }\n      i. des; eauto. esplits.\n      * etrans.\n        { eauto. }\n        { econs 2; [|refl]. econs; eauto.\n          econs; eauto. econs; eauto. }\n      * eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/ReorderReserve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2909808662149068, "lm_q1q2_score": 0.1534390187424196}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\nRequire Import TableDataOpsRef2.Specs.table_destroy2.\nRequire Import TableDataOpsRef2.LowSpecs.table_destroy2.\nRequire Import TableDataOpsRef2.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_destroy_spec\n       table_destroy1_spec\n    .\n\n  Lemma table_destroy2_spec_exists:\n    forall habd habd'  labd g_rd map_addr rtt_addr level res\n           (Hspec: table_destroy2_spec g_rd map_addr rtt_addr level habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', table_destroy2_spec0 g_rd map_addr rtt_addr level labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq granule_fill_table.fill_table.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rd.\n    unfold table_destroy2_spec, table_destroy2_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. rewrite_oracle_rel rel_oracle C21.\n      repeat (grewrite; try simpl_htarget; simpl);\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. rewrite_oracle_rel rel_oracle C21.\n      repeat (grewrite; try simpl_htarget; simpl).\n      eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity].\n      eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity].\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold destroy_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; extract_prop_dec; simpl_query_oracle.\n      autounfold. rewrite_oracle_rel rel_oracle C21.\n      repeat (grewrite; try simpl_htarget; simpl).\n      eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity].\n      autounfold. rewrite_oracle_rel rel_oracle C21.\n      repeat (grewrite; try simpl_htarget; simpl).\n      eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity].\n      eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity].\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C12.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef2/RefProof/table_destroy2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.2909808723634538, "lm_q1q2_score": 0.15343901766163898}}
{"text": "(* En este archivo se demuestra la correcci\u00f3n de la acci\u00f3n sendBroadcast *)\nRequire Export Exec.\nRequire Import Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Export ListAuxFuns.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import Semantica.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\n\nSection SendBroadcast.\n\nLemma sendBroadcastCorrect : forall (s:System) (i:Intent) (ic:iCmp) (mp:option Perm) (sValid: validstate s),\n    (pre (sendBroadcast i ic mp) s) -> post_sendBroadcast i ic mp s (sendBroadcast_post i ic mp s).\nProof.\n    intros.\n    unfold post_sendBroadcast.\n    simpl in H.\n    unfold pre_sendBroadcast in H;simpl in H.\n    destruct_conj H.\n    unfold addIntent.\n    unfold onlyIntentsChanged.\n    unfold sendBroadcast_post.\n    simpl.\n    split; intros.\n    split; intros.\n    right;auto.\n    split;intros.\n    destruct H2.\n    right.\n    inversion H2.\n    split;auto.\n    unfold createIntent in *.\n    simpl.\n    repeat (split;auto).\n    left;auto.\n    left.\n    auto.\n    \n    repeat (split;auto).\nQed.\n\nLemma notPreSendBroadcastThenError : forall (s:System) (i:Intent) (ic:iCmp) (mp:option Perm), ~(pre (sendBroadcast i ic mp) s) -> validstate s -> exists ec : ErrorCode, response (step s (sendBroadcast i ic mp)) = error ec /\\ ErrorMsg s (sendBroadcast i ic mp) ec /\\ s = system (step s (sendBroadcast i ic mp)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_sendBroadcast in H.\n    unfold sendBroadcast_safe.\n    unfold sendBroadcast_pre.\n    case_eq (negb (intTypeEqBool (intType i) intBroadcast));intros.\n    exists incorrect_intent_type.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H1.\n    invertBool H1.\n    intro;apply H1.\n    rewrite H2.\n    destruct intTypeEqBool;auto.\n    case_eq (isSomethingBool Perm (brperm i));intros.\n    exists faulty_intent.\n    split;auto.\n    split;auto.\n    unfold isSomethingBool in H2.\n    intro.\n    destruct (brperm i).\n    discriminate H3.\n    discriminate H2.\n    case_eq (negb (isiCmpRunningBool ic s));intros.\n    exists instance_not_running.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H3.\n    invertBool H3.\n    intro;apply H3.\n    apply isiCmpRunningCorrect;auto.\n    case_eq ( existsb (fun pair : iCmp * Intent => if idInt_eq (idI i) (idI (snd pair)) then true else false) (sentIntents (state s)));intros.\n    exists intent_already_sent.\n    split;auto.\n    split;auto.\n    rewrite existsb_exists in H4.\n    destruct H4.\n    exists (snd x), (fst x).\n    destruct H4.\n    split.\n    destruct x.\n    simpl.\n    auto.\n    destruct idInt_eq in H5.\n    rewrite e;auto.\n    discriminate H5.\n    destruct H.\n    split.\n    rewrite negb_false_iff in H1.\n    unfold intTypeEqBool in H1.\n    destruct (intType i);auto;discriminate H1.\n    split.\n    unfold isSomethingBool in H2.\n    destruct (brperm i);auto;discriminate H2.\n    split.\n    rewrite negb_false_iff in H3.\n    apply isiCmpRunningCorrect;auto.\n    invertBool H4.\n    intro;apply H4.\n    rewrite existsb_exists.\n    destruct H.\n    destruct H.\n    destruct H.\n    exists (x0,x).\n    split;auto.\n    simpl.\n    destruct idInt_eq;auto.\nQed.\n\nLemma sendBroadcastIsSound : forall (s:System) (i:Intent) (ic:iCmp) (mp:option Perm) (sValid: validstate s),\n        exec s (sendBroadcast i ic mp) (system (step s (sendBroadcast i ic mp))) (response (step s (sendBroadcast i ic mp))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (sendBroadcast i ic mp) s));intro.\n    left.\n    simpl.\n    assert(sendBroadcast_pre i ic mp s = None).\n    unfold sendBroadcast_pre.\n    destruct H.\n    rewrite H.\n    unfold intTypeEqBool.\n    assert (negb true=false).\n    rewrite negb_false_iff.\n    auto.\n    rewrite H1.\n    \n    destruct_conj H0.\n    rewrite H2.\n    unfold isSomethingBool.\n    assert (negb (isiCmpRunningBool ic s)=false).\n    rewrite negb_false_iff.\n    apply isiCmpRunningCorrect; auto.\n    rewrite H3.\n    assert (existsb (fun pair : iCmp * Intent => if idInt_eq (idI i) (idI (snd pair)) then true else false) (sentIntents (state s))=false).\n    rewrite <-not_true_iff_false.\n    unfold not;intros.\n    rewrite existsb_exists in H5.\n    destruct H5.\n    destruct H5.\n    apply H4.\n    exists (snd x).\n    destruct idInt_eq in H6.\n    exists (fst x).\n    case_eq x;intros.\n    simpl.\n    rewrite<- H7.\n    rewrite H7 in e.\n    simpl in e.\n    split;auto.\n    discriminate H6.\n    rewrite H5.\n    auto.\n    \n    unfold sendBroadcast_safe;simpl.\n    rewrite H0;simpl.\n    split;auto.\n    split;auto.\n    apply sendBroadcastCorrect;auto.\n    right.\n    apply notPreSendBroadcastThenError;auto.\n    \nQed.\nEnd SendBroadcast.\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/SendBroadcastIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.15343901550018918}}
{"text": "Theorem ev5_nonsense :\n  ev 5 -> 2 + 2 = 9.\nProof.\n  intros.\n  inversion H.\n  inversion H1.\n  inversion H3.\nQed.", "meta": {"author": "cristianlepore", "repo": "Coq_exercises", "sha": "109d34794edee6bd2b255ed4f7fc3c91edb8c8f5", "save_path": "github-repos/coq/cristianlepore-Coq_exercises", "path": "github-repos/coq/cristianlepore-Coq_exercises/Coq_exercises-109d34794edee6bd2b255ed4f7fc3c91edb8c8f5/Software_foundation/Chapter7/ev5_nonsense.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.15341553115518697}}
{"text": "(******************************************************************************)\n(** * Definitions of the axiomatic memory model *)\n(******************************************************************************)\n\nRequire Import Classical List Relations Peano_dec.\nRequire Import Hahn.\n\nRequire Import Basic Dom RC11_Events RC11_Model RC11_Threads.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection PB.\n\nVariable G : execution.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'rf'\" := G.(rf).\nNotation \"'mo'\" := G.(mo).\nNotation \"'eco'\" := G.(eco).\nNotation \"'rb'\" := G.(rb).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\nNotation \"'psc_f'\" := G.(psc_f).\nNotation \"'psc'\" := G.(psc).\nNotation \"'sb_neq_loc'\" := G.(sb_neq_loc).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'deps'\" := G.(deps).\nNotation \"'same_loc'\" := G.(same_loc).\nNotation \"rel |loc\" := (rel \u2229 same_loc) (at level 1).\n\nNotation \"'R'\" := (R lab).\nNotation \"'W'\" := (W lab).\nNotation \"'F'\" := (F lab).\nNotation \"'RMW'\" := (RMW lab).\n\nNotation \"'RW'\" := (RW lab).\nNotation \"'FR'\" := (FR lab).\nNotation \"'FW'\" := (FW lab).\n\nNotation \"'Na'\" := (Only_Na lab).\nNotation \"'Rlx'\" := (Rlx lab).\nNotation \"'Rel'\" := (Rel lab).\nNotation \"'Acq'\" := (Acq lab).\nNotation \"'Acqrel'\" := (Acqrel lab).\nNotation \"'Sc'\" := (Sc lab).\n\nNotation \"type ~ mode\" := (type \u2229\u2081 mode) (at level 1).\n\nDefinition psbloc :=  \u2997fun a => ~ is_init a\u2998 \u2a3e (restr_eq_rel (loc lab) sb) \u2a3e \u2997R\u2998 \\ \n                                       (restr_eq_rel (loc lab) sb) \u2a3e \u2997W\u2998 \u2a3e sb.\nDefinition pbi := deps \u222a addr ;; sb \u222a \u2997R~Rlx \u222a\u2081 W~Rel \u222a\u2081 F\u2998 ;; sb \u222a psbloc \u222a sb ;; \u2997FW~Rel\u2998.\nDefinition pb := pbi \u222a rf\u2218.\n\nHypothesis WF: G.(Wf).\n\nLemma rfi_psbloc (COH:  irreflexive (hb \u2a3e eco^?)): \n  rf\u2219 \u2286 pb.\nProof.\n  cdes WF.\n  unionR left -> left -> right.\n  unfold psbloc; unfolder; splits; ins; desf.\n  eby eapply st_not_inita.\n  eby apply rf_st_implies_sb.\n  eby apply WF_RF.\n  eby eapply rf_domb.\n  intro; desf; eapply COH.\n  exists y; splits.\n  eby eapply sb_in_hb.\n  right; apply rb_in_eco; try done.\n  red; unfolder; splits.\n  - exists x; splits; [basic_solver|].\n    apply sb_loc_in_mo; try edone.\n    unfolder; eexists; splits; eauto.\n    eby eapply rf_doma; eauto.\n    red; splits; auto.\n    rewrite H4.\n    unfold loc; solve_type_mismatch.\n  - apply or_not_and. left. intro; desf.\n    by cdes WF_SB; apply SB_IRR in H3.\nQed.\n\n(* Proposition G.1 *)\nProposition rf_pb (COH:  irreflexive (hb \u2a3e eco^?)): \n  rf \u2286 pb.\nProof.\narewrite (rf \u2286 rf\u2218 \u222a rf\u2219).\n  by unfolder; ins; destruct (classic (same_thread x y)); tauto.\nby unionL; [vauto|rewrite rfi_psbloc].\nQed.\n\nProposition rmw_pbi: rmw \u2286 pbi.\nProof.\ncdes WF; cdes WF_DEPS.\ncdes WF_RMW.\nrewrite RMW_DEPS.\nunfold pbi, RC11_Model.deps.\nbasic_solver 10.\nQed.\n\n(* Proposition G.2 *)\nProposition hb_pb (COH:  irreflexive (hb \u2a3e eco^?)): \n  hb \u2286 sb \u222a pb^+.\nProof.\nunfold RC11_Model.hb.\nrewrite path_union.\nassert (T: transitive sb) by by cdes WF; cdes WF_SB.\nrelsf.\nunionL; auto with rel.\nunionR right.\nunfold RC11_Model.sw, RC11_Model.release, RC11_Model.rs, RC11_Model.useq.\narewrite ((sb|loc)^? \u2286 sb^?).\narewrite (\u2997fun a : event => In a acts\u2998 \u2a3e \u2997W\u2998 \u2a3e sb^? \u2a3e \u2997W~Rlx\u2998\u2286 sb^?) by basic_solver 10.\narewrite ((\u2997W~Rel\u2998 \u222a \u2997F~Rel\u2998 \u2a3e sb) \u2a3e sb^? \u2286 (\u2997W~Rel\u2998 \u222a \u2997F~Rel\u2998) \u2a3e sb^?)\n  by relsf; unionL; rewrite ?seqA; relsf.\narewrite (\u2997R~Acq\u2998 \u222a \u2997R~Rlx\u2998 \u2a3e sb \u2a3e \u2997F~Acq\u2998 \u2286 \u2997R~Rlx\u2998 \u2a3e sb^?)\n  by unionL; solve_mode_mismatch.\narewrite (sb^? \u2a3e sb^? \u2286 sb^?) by relsf.\narewrite (\u2997R~Rlx\u2998 \u2a3e sb^? \u2286 pbi^?)\n  by unfold pbi; basic_solver 10.\nrewrite rmw_pbi.\narewrite (rf \u2286 pb) by apply rf_pb.\narewrite ((\u2997W~Rel\u2998 \u222a \u2997F~Rel\u2998)  \u2286 \u2997FW~Rel\u2998  ;; (\u2997W~Rel\u2998 \u222a \u2997F~Rel\u2998))\n  by rewrite <- !id_union; solve_type_mismatch.\narewrite ( sb^? \u2a3e \u2997FW~Rel\u2998 \u2286 pbi^*)\n  by unfold pbi; rewrite crE; relsf; eauto 5 with rel.\narewrite (\u2997F~Rel\u2998 \u2286 \u2997F\u2998) by solve_type_mismatch.\narewrite ((\u2997W~Rel\u2998 \u222a \u2997F\u2998) \u2a3e sb^? \u2286\u2997R~Rlx \u222a\u2081 W~Rel \u222a\u2081 F\u2998 \u2a3e sb^?) by basic_solver 10.\narewrite (\u2997R~Rlx \u222a\u2081 W~Rel \u222a\u2081 F\u2998 \u2a3e sb^? \u2286 pbi^*)\n  by rewrite crE; relsf; unionL; unfold pbi; auto with rel.\narewrite (pbi \u2286 pb).\nrelsf; auto 8 with rel_full rel.\nQed.\n\nEnd PB.", "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/RC11_Model_pb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.153256985381831}}
{"text": "(*\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     Eqdep\n     List\n     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     SyntacticallySafe\n     AdversaryUniverse\n\n     ModelCheck.Commutation\n     ModelCheck.InvariantSearch\n     ModelCheck.ProtocolFunctions\n     ModelCheck.ModelCheck\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.UniverseInversionLemmas\n.\n\nFrom protocols Require Import\n     PGP.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\n\nModule PGPProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import PGPProtocol.\n\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b := tt.\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start.\n\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core.\n\n  Lemma finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  Proof.\n    autounfold; simpl.\n    eexists.\n    econstructor; simpl; find_runtime.\n\n    Unshelve.\n    all: exact 0.\n  Qed.\n\n  Lemma typechecks : syntactically_safe_U ru0.\n  Proof.\n    unfold syntactically_safe_U; intros.\n    autounfold\n    ; subst\n    ; simpl in *.\n\n    unfold compute_ids; simpl.\n    \n    focus_user; simpl\n    ; try solve [ do 2 eexists; split\n                  ; [ unshelve (repeat typechecks1)\n                      ; match goal with\n                        | [ |- bool ] => exact true\n                        | [ |- list safe_typ ] => exact []\n                        end\n                    | repeat verify_context_soundness ] ].\n\n    Unshelve.\n    all : exact TyDontCare.\n  Qed.\n    \n  Lemma summarizable : exists summaries, summarize_univ ru0 summaries.\n  Proof.\n    autounfold; unfold summarize_univ; simpl; intros.\n    unshelve (\n        eexists; intros; focus_user; simpl\n        ; (exists useless_summary; split; [ build_summary |]; eauto using useless_summary_summarizes)\n      ) ; exact $0.\n  Qed.\n    \n  Lemma lameness : @lameAdv t__adv b (RealWorld.adversary ru0).\n  Proof.\n    unfold lameAdv; autounfold; simpl; eauto.\n  Qed.\n\n  Import Gen Tacs.\n\n  Locate safety_inv.\n\n  (* Set Ltac Profiling. *)\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (@noresends_inv t__hon t__adv).\n  Proof.\n    unfold invariantFor\n    ; unfold Initial, Step\n    ; intros\n    ; simpl in *\n    ; split_ors\n    ; try contradiction\n    ; subst.\n\n    autounfold in H0\n    ; unfold fold_left, fst, snd in *.\n    unfold real_users, ideal_users, mkrUsr, userProto, userKeys, userId, mkiUsr in *; rwuf.\n\n    time (\n        repeat transition_system_step\n      ).\n      \n    Unshelve.\n    all: eauto.\n  Qed.\n\n  (* Show Ltac Profile. *)\n      \n  Lemma U_good : @universe_starts_sane _ Unit b ru0.\n  Proof.\n    autounfold;\n      unfold universe_starts_sane; simpl.\n    repeat (apply conj); intros; eauto.\n    - focus_user; auto.\n    - econstructor.\n    - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros.\n      unfold mkrUsr; simpl.\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto.\n    - unfold lameAdv; simpl; eauto.\n  Qed.\n\n  Lemma universe_starts_safe : universe_ok ru0.\n  Proof.\n    pose proof (adversary_is_lame_adv_univ_ok_clauses U_good).\n    \n    unfold universe_ok\n    ; autounfold\n    ; simpl\n    ; intuition eauto\n    .\n\n    - econstructor; eauto.\n    - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto.\n      solve_simple_maps; eauto.\n\n      rewrite Forall_natmap_forall; intros.\n\n      solve_simple_maps; simpl\n      ; unfold permission_heap_good; intros;\n        solve_simple_maps; solve_concrete_maps; eauto.\n\n    - unfold user_cipher_queues_ok.\n      rewrite Forall_natmap_forall; intros.\n      focus_user\n      ; simpl in *; econstructor; eauto.\n\n    - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok\n      ; repeat simple apply conj\n      ; intros\n      ; clean_map_lookups\n      ; intros\n      ; focus_user\n      ; try contradiction; try discriminate; simpl;\n        repeat (apply conj); intros; clean_map_lookups; eauto.\n\n    - unfold honest_users_only_honest_keys; intros.\n      focus_user;\n        subst;\n        simpl in *;\n        clean_map_lookups;\n        unfold mkrUsr; simpl; \n          rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty;\n          eauto;\n          simpl in *;\n          solve_concrete_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\nEnd PGPProtocolSecure.\n\n(* Module ProtoCorrect := SSProtocolSimulates (PGPProtocolSecure). *)\n(* Print Assumptions ProtoCorrect.protocol_with_adversary_could_generate_spec. *)\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/protocols/Verification/PGPSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.15325698538183097}}
{"text": "From isla Require Import opsem.\n\nDefinition a14 : isla_trace :=\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"TCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"EDSCR\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSDLR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSLSR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  Smt (DeclareConst 6%Z (Ty_BitVec 1%N)) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"nRW\"] (RegVal_Base (Val_Bits (BV 1%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  Smt (DeclareConst 29%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  Assume (AExp_Binop (Eq) (AExp_Manyop (Bvmanyarith Bvand) [AExp_Val (AVal_Var \"R2\" []) Mk_annot; AExp_Val (AVal_Bits (BV 64%N 0xfff0000000000000%Z)) Mk_annot] Mk_annot) (AExp_Val (AVal_Bits (BV 64%N 0x0%Z)) Mk_annot) Mk_annot) Mk_annot :t:\n  ReadReg \"R2\" [] (RegVal_Base (Val_Symbolic 29%Z)) Mk_annot :t:\n  Smt (DefineConst 117%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 29%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DeclareConst 118%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R0\" [] (RegVal_Base (Val_Symbolic 118%Z)) Mk_annot :t:\n  Smt (DefineConst 119%Z (Unop (Extract 7%N 0%N) (Val (Val_Symbolic 118%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 124%Z (Binop (Eq) (Val (Val_Symbolic 117%Z) Mk_annot) (Manyop (Bvmanyarith Bvand) [Val (Val_Symbolic 117%Z) Mk_annot; Val (Val_Bits (BV 64%N 0xffffffffffffffff%Z)) Mk_annot] Mk_annot) Mk_annot)) Mk_annot :t:\n  ReadReg \"PSTATE\" [Field \"D\"] (RegVal_Struct [(\"D\", RegVal_Base (Val_Symbolic 6%Z))]) Mk_annot :t:\n  Smt (DeclareConst 2142%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPIDR_EL1\" [] (RegVal_Base (Val_Symbolic 2142%Z)) Mk_annot :t:\n  Smt (DeclareConst 2325%Z (Ty_BitVec 56%N)) Mk_annot :t:\n  Smt (DefineConst 2338%Z (Unop (ZeroExtend 8%N) (Manyop Concat [Val (Val_Bits (BV 4%N 0x0%Z)) Mk_annot; Unop (Extract 51%N 0%N) (Val (Val_Symbolic 117%Z) Mk_annot) Mk_annot] Mk_annot) Mk_annot)) Mk_annot :t:\n  Smt (DeclareConst 2339%Z Ty_Bool) Mk_annot :t:\n  WriteMem (RegVal_Base (Val_Symbolic 2339%Z)) (RegVal_Base (Val_Enum ((Mk_enum_id 6%nat), Mk_enum_ctor 0%nat))) (RegVal_Base (Val_Symbolic 2338%Z)) (RegVal_Base (Val_Symbolic 119%Z)) 1%N None Mk_annot :t:\n  Smt (DeclareConst 2340%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 2340%Z)) Mk_annot :t:\n  Smt (DefineConst 2341%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 2340%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 2341%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/hello/a14.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.3040416749665474, "lm_q1q2_score": 0.15320847611364033}}
{"text": "From isla Require Import opsem.\n\nDefinition a0 : isla_trace :=\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"TCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"nRW\"] (RegVal_Base (Val_Bits (BV 1%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  Smt (DeclareConst 36%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R2\" [] (RegVal_Base (Val_Symbolic 36%Z)) Mk_annot :t:\n  Smt (DefineConst 39%Z (Binop (Eq) (Binop (Eq) (Val (Val_Symbolic 36%Z) Mk_annot) (Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot) Mk_annot) (Val (Val_Bool true) Mk_annot) Mk_annot)) Mk_annot :t:\n  tcases [\n    Smt (Assert (Val (Val_Symbolic 39%Z) Mk_annot)) Mk_annot :t:\n    Smt (DeclareConst 40%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 40%Z)) Mk_annot :t:\n    Smt (DefineConst 41%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 40%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x1c%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n    Smt (DefineConst 53%Z (Val (Val_Symbolic 41%Z) Mk_annot)) Mk_annot :t:\n    BranchAddress (RegVal_Base (Val_Symbolic 53%Z)) Mk_annot :t:\n    Smt (DefineConst 54%Z (Val (Val_Symbolic 41%Z) Mk_annot)) Mk_annot :t:\n    WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 54%Z)) Mk_annot :t:\n    tnil;\n    Smt (Assert (Unop (Not) (Val (Val_Symbolic 39%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n    Smt (DeclareConst 40%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 40%Z)) Mk_annot :t:\n    Smt (DefineConst 41%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 40%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 41%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/memcpy/a0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3040416686603661, "lm_q1q2_score": 0.1532084729359166}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import GenSem.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import GenSem.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import PrimSemantics.\nRequire Import CompatClightSem.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import PTAlloc.Layer.\nRequire Import HypsecCommLib.\nRequire Import Constants.\nRequire Import PTAlloc.Spec.\nRequire Import AbstractMachine.Spec.\nRequire Import RData.\n\nLocal Open Scope Z_scope.\n\nSection PTWalkSpec.\n\n  Definition walk_pgd_spec (vmid: Z) (vttbr: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match vttbr, addr with\n    | VZ64 vttbr, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        let vttbr_pa := phys_page vttbr in\n        let pgd_idx := pgd_index addr in\n        let pgd_p := Z.lor vttbr_pa (pgd_idx * 8) in\n        rely ((pool_start vmid <=? pgd_p) && (pgd_p <? pgd_start vmid));\n        let pgd := pgd_p @ (pt_vttbr_pool npt) in\n        rely is_int64 pgd;\n        if (pgd =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pgd_next npt, pud_start vmid) in\n          rely ((pgd_start vmid <=? next) && (next <=? pud_start vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pgd' := Z.lor next PUD_TYPE_TABLE in\n            let pool' := (pt_vttbr_pool npt) # pgd_p == pgd' in\n            let updates' := (UPDATE_PGD pgd_p pgd') :: (pt_updates npt) in\n            let par' := (pt_pgd_par npt) # next == pgd_p in\n            let npt' := npt {pt_pgd_next: next + PAGE_SIZE} {pt_vttbr_pool: pool'} {pt_pgd_par: par'} {pt_updates: updates'} in\n            Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pgd')\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pgd)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pud_spec (vmid: Z) (pgd: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pgd, addr with\n    | VZ64 pgd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        if (pgd =? 0) then Some (adt, VZ64 0) else\n        let pgd_pa := phys_page pgd in\n        let pud_idx := pud_index addr in\n        let pud_p := Z.lor pgd_pa (pud_idx * 8) in\n        rely ((pgd_start vmid <=? pud_p) && (pud_p <? pud_start vmid));\n        let pud := pud_p @ (pt_pgd_pool npt) in\n        rely is_int64 pud;\n        if (pud =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pud_next npt, pmd_start vmid) in\n          rely ((pud_start vmid <=? next) && (next <=? pmd_start vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pud' := Z.lor next PUD_TYPE_TABLE in\n            let pool' := (pt_pgd_pool npt) # pud_p == pud' in\n            let updates' := (UPDATE_PUD pud_p pud') :: (pt_updates npt) in\n            let par' := (pt_pud_par npt) # next == pud_p in\n            let npt' := npt {pt_pud_next: next + PAGE_SIZE} {pt_pgd_pool: pool'} {pt_pud_par: par'} {pt_updates: updates'} in\n            Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pud')\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pud)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pmd_spec (vmid: Z) (pud: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pud, addr with\n    | VZ64 pud, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        if (pud =? 0) then Some (adt, VZ64 0) else\n        let pud_pa := phys_page pud in\n        let pmd_idx := pmd_index addr in\n        let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n        rely ((pud_start vmid <=? pmd_p) && (pmd_p <? pmd_start vmid));\n        let pmd := pmd_p @ (pt_pud_pool npt) in\n        rely is_int64 pmd;\n        if (pmd =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pmd_next npt, pool_end vmid) in\n          rely ((pmd_start vmid <=? next) && (next <=? pool_end vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pmd' := Z.lor next PMD_TYPE_TABLE in\n            let pool' := (pt_pud_pool npt) # pmd_p == pmd' in\n            let updates' := (UPDATE_PMD pmd_p pmd') :: (pt_updates npt) in\n            let par' := (pt_pmd_par npt) # next == pmd_p in\n            let npt' := npt {pt_pmd_next: next + PAGE_SIZE} {pt_pud_pool: pool'} {pt_pmd_par: par'} {pt_updates: updates'} in\n            Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pmd')\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pmd)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pte_spec (vmid: Z) (pmd: Z64) (addr: Z64) (adt: RData) : option Z64 :=\n    match pmd, addr with\n    | VZ64 pmd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := ZMap.get vmid (npts (shared adt)) in\n        if (pmd =? 0) then Some (VZ64 0) else\n        let pmd_pa := phys_page pmd in\n        let pte_idx := pte_index addr in\n        let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n        rely ((pmd_start vmid <=? pte_p) && (pte_p <? pool_end vmid));\n        let pte := pte_p @ (pt_pmd_pool npt) in\n        rely is_int64 pte;\n        Some (VZ64 pte)\n      | _ => None\n      end\n    end.\n\n  Definition set_pmd_spec (vmid: Z) (pud: Z64) (addr: Z64) (pmd: Z64) (adt: RData) : option RData :=\n    match pud, pmd, addr with\n    | VZ64 pud, VZ64 pmd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some adt else\n      if pmd_table pmd =? PMD_TYPE_TABLE then None else\n      if tstate adt =? 0 then\n        let id := NPT_ID + vmid in\n        match ZMap.get id (lock adt) with\n        | LockOwn true =>\n          let npt := ZMap.get vmid (npts (shared adt)) in\n          let pud_pa := phys_page pud in\n          let pmd_idx :=  pmd_index addr in\n          let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n          rely ((pud_start vmid <=? pmd_p) && (pmd_p <? pmd_start vmid));\n          let pool' := ZMap.set pmd_p pmd (pt_pud_pool npt) in\n          let updates' := (UPDATE_PMD pmd_p pmd) :: (pt_updates npt) in\n          Some (adt {tstate: 1} {shared: (shared adt) {npts: ZMap.set vmid (npt {pt_pud_pool: pool'} {pt_updates: updates'}) (npts (shared adt))}})\n        | _ => None\n        end\n      else None\n    end.\n\n  Definition set_pte_spec (vmid: Z) (pmd: Z64) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match pmd, addr, pte with\n    | VZ64 pmd, VZ64 addr, VZ64 pte =>\n      rely is_vmid vmid; rely is_addr addr;\n      if halt adt then Some adt else\n      if tstate adt =? 0 then\n        let id := NPT_ID + vmid in\n        match ZMap.get id (lock adt) with\n        | LockOwn true =>\n          let npt := ZMap.get vmid (npts (shared adt)) in\n          let pmd_pa := phys_page pmd in\n          let pte_idx :=  pte_index addr in\n          let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n          rely ((pmd_start vmid <=? pte_p) && (pte_p <? pool_end vmid));\n          let pool' := ZMap.set pte_p pte (pt_pmd_pool npt) in\n          let updates' := (UPDATE_PTE pte_p pte) :: (pt_updates npt) in\n          Some (adt {tstate: 1} {shared: (shared adt) {npts: ZMap.set vmid (npt {pt_pmd_pool: pool'} {pt_updates: updates'}) (npts (shared adt))}})\n        | _ => None\n        end\n      else None\n    end.\n\n  (*\n\n  Definition walk_pgd_spec (vmid: Z) (vttbr: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match vttbr, addr with\n    | VZ64 vttbr, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        let vttbr_pa := phys_page vttbr in\n        let pgd_idx := pgd_index addr in\n        let pgd_p := Z.lor vttbr_pa (pgd_idx * 8) in\n        rely ((pool_start vmid <=? pgd_p) && (pgd_p <? pgd_start vmid));\n        let pgd := pgd_p @ (pt_vttbr_pool npt) in\n        rely is_int64 pgd;\n        if (pgd =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pgd_next npt, pud_start vmid) in\n          rely ((pgd_start vmid <=? next) && (next <=? pud_start vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pgd' := Z.lor next PUD_TYPE_TABLE in\n            let pool' := (pt_vttbr_pool npt) # pgd_p == pgd' in\n            let par' := (pt_pgd_par npt) # next == pgd_p in\n            let npt' := npt {pt_pgd_next: next + PAGE_SIZE} {pt_vttbr_pool: pool'} {pt_pgd_par: par'} in\n            if verify_observe (observe_pt vmid npt) (observe_pt vmid npt') then\n              Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pgd')\n            else None\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pgd)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pud_spec (vmid: Z) (pgd: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pgd, addr with\n    | VZ64 pgd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        if (pgd =? 0) then Some (adt, VZ64 0) else\n        let pgd_pa := phys_page pgd in\n        let pud_idx := pud_index addr in\n        let pud_p := Z.lor pgd_pa (pud_idx * 8) in\n        rely ((pgd_start vmid <=? pud_p) && (pud_p <? pud_start vmid));\n        let pud := pud_p @ (pt_pgd_pool npt) in\n        rely is_int64 pud;\n        if (pud =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pud_next npt, pmd_start vmid) in\n          rely ((pud_start vmid <=? next) && (next <=? pmd_start vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pud' := Z.lor next PUD_TYPE_TABLE in\n            let pool' := (pt_pgd_pool npt) # pud_p == pud' in\n            let par' := (pt_pud_par npt) # next == pud_p in\n            let npt' := npt {pt_pud_next: next + PAGE_SIZE} {pt_pgd_pool: pool'} {pt_pud_par: par'} in\n            if verify_observe (observe_pt vmid npt) (observe_pt vmid npt') then\n              Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pud')\n            else None\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pud)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pmd_spec (vmid: Z) (pud: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pud, addr with\n    | VZ64 pud, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (adt, VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := vmid @ (npts (shared adt)) in\n        if (pud =? 0) then Some (adt, VZ64 0) else\n        let pud_pa := phys_page pud in\n        let pmd_idx := pmd_index addr in\n        let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n        rely ((pud_start vmid <=? pmd_p) && (pmd_p <? pmd_start vmid));\n        let pmd := pmd_p @ (pt_pud_pool npt) in\n        rely is_int64 pmd;\n        if (pmd =? 0) && (alloc =? 1) then\n          let (next, end_) := (pt_pmd_next npt, pool_end vmid) in\n          rely ((pmd_start vmid <=? next) && (next <=? pool_end vmid));\n          if next + PAGE_SIZE <=? end_ then\n            let pmd' := Z.lor next PMD_TYPE_TABLE in\n            let pool' := (pt_pud_pool npt) # pmd_p == pmd' in\n            let par' := (pt_pmd_par npt) # next == pmd_p in\n            let npt' := npt {pt_pmd_next: next + PAGE_SIZE} {pt_pud_pool: pool'} {pt_pmd_par: par'} in\n            if verify_observe (observe_pt vmid npt) (observe_pt vmid npt') then\n              Some (adt {shared: (shared adt) {npts: (npts (shared adt)) # vmid == npt'}}, VZ64 pmd')\n            else None\n          else Some (adt {halt: true}, VZ64 0)\n        else Some (adt, VZ64 pmd)\n      | _ => None\n      end\n    end.\n\n  Definition walk_pte_spec (vmid: Z) (pmd: Z64) (addr: Z64) (adt: RData) : option Z64 :=\n    match pmd, addr with\n    | VZ64 pmd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some (VZ64 0) else\n      let id := NPT_ID + vmid in\n      match ZMap.get id (lock adt) with\n      | LockOwn true =>\n        let npt := ZMap.get vmid (npts (shared adt)) in\n        if (pmd =? 0) then Some (VZ64 0) else\n        let pmd_pa := phys_page pmd in\n        let pte_idx := pte_index addr in\n        let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n        rely ((pmd_start vmid <=? pte_p) && (pte_p <? pool_end vmid));\n        let pte := pte_p @ (pt_pmd_pool npt) in\n        rely is_int64 pte;\n        Some (VZ64 pte)\n      | _ => None\n      end\n    end.\n\n  Definition set_pmd_spec (vmid: Z) (pud: Z64) (addr: Z64) (pmd: Z64) (adt: RData) : option RData :=\n    match pud, pmd, addr with\n    | VZ64 pud, VZ64 pmd, VZ64 addr =>\n      rely is_vmid vmid;\n      if halt adt then Some adt else\n      if pmd_table pmd =? PMD_TYPE_TABLE then None else\n      if tstate adt =? 0 then\n        let id := NPT_ID + vmid in\n        match ZMap.get id (lock adt) with\n        | LockOwn true =>\n          let npt := ZMap.get vmid (npts (shared adt)) in\n          let pud_pa := phys_page pud in\n          let pmd_idx :=  pmd_index addr in\n          let pmd_p := Z.lor pud_pa (pmd_idx * 8) in\n          rely ((pud_start vmid <=? pmd_p) && (pmd_p <? pmd_start vmid));\n          let pool' := ZMap.set pmd_p pmd (pt_pud_pool npt) in\n          Some (adt {tstate: 1} {shared: (shared adt) {npts: ZMap.set vmid (npt {pt_pud_pool: pool'}) (npts (shared adt))}})\n        | _ => None\n        end\n      else None\n    end.\n\n  Definition set_pte_spec (vmid: Z) (pmd: Z64) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match pmd, addr, pte with\n    | VZ64 pmd, VZ64 addr, VZ64 pte =>\n      rely is_vmid vmid; rely is_addr addr;\n      if halt adt then Some adt else\n      if tstate adt =? 0 then\n        let id := NPT_ID + vmid in\n        match ZMap.get id (lock adt) with\n        | LockOwn true =>\n          let npt := ZMap.get vmid (npts (shared adt)) in\n          let pmd_pa := phys_page pmd in\n          let pte_idx :=  pte_index addr in\n          let pte_p := Z.lor pmd_pa (pte_idx * 8) in\n          rely ((pmd_start vmid <=? pte_p) && (pte_p <? pool_end vmid));\n          let pool' := ZMap.set pte_p pte (pt_pmd_pool npt) in\n          Some (adt {tstate: 1} {shared: (shared adt) {npts: ZMap.set vmid (npt {pt_pmd_pool: pool'}) (npts (shared adt))}})\n        | _ => None\n        end\n      else None\n    end.\n\n  *)\n\nEnd PTWalkSpec.\n\nSection PTWalkSpecLow.\n\n  Context `{real_params: RealParams}.\n\n  Notation LDATA := RData.\n\n  Notation LDATAOps := (cdata (cdata_ops := PTAlloc_ops) LDATA).\n\n  Definition walk_pgd_spec0 (vmid: Z) (vttbr: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match vttbr, addr with\n    | VZ64 vttbr, VZ64 addr =>\n      let vttbr_pa := phys_page vttbr in\n      let pgd_idx := pgd_index addr in\n      let p := Z.lor vttbr_pa (pgd_idx * 8) in\n      when' pgd == pt_load_spec vmid (VZ64 p) adt;\n      rely is_int64 pgd;\n      if (pgd =? 0) && (alloc =? 1) then\n        when' pgd_pa, adt' == alloc_pgd_page_spec vmid adt;\n        rely is_addr pgd_pa;\n        let pgd' := Z.lor pgd_pa PUD_TYPE_TABLE in\n        when adt'' == pt_store_spec vmid (VZ64 p) (VZ64 pgd') adt';\n        when' res == check64_spec (VZ64 pgd') adt'';\n        Some (adt'', VZ64 res)\n      else\n        when' res == check64_spec (VZ64 pgd) adt;\n        Some (adt, VZ64 res)\n    end.\n\n  Definition walk_pud_spec0 (vmid: Z) (pgd: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pgd, addr with\n    | VZ64 pgd, VZ64 addr =>\n      if (pgd =? 0) then\n        when' res == check64_spec (VZ64 0) adt;\n        Some (adt, VZ64 res)\n      else\n        let pgd_pa := phys_page pgd in\n        let pud_idx := pud_index addr in\n        let p := Z.lor pgd_pa (pud_idx * 8) in\n        when' pud == pt_load_spec vmid (VZ64 p) adt;\n        rely is_int64 pud;\n        if (pud =? 0) && (alloc =? 1) then\n          when' pud_pa, adt' == alloc_pud_page_spec vmid adt;\n          rely is_addr pud_pa;\n          let pud' := Z.lor pud_pa PUD_TYPE_TABLE in\n          when adt'' == pt_store_spec vmid (VZ64 p) (VZ64 pud') adt';\n          when' res == check64_spec (VZ64 pud') adt'';\n          Some (adt'', VZ64 res)\n        else\n          when' res == check64_spec (VZ64 pud) adt;\n          Some (adt, VZ64 res)\n    end.\n\n  Definition walk_pmd_spec0 (vmid: Z) (pud: Z64) (addr: Z64) (alloc: Z) (adt: RData) : option (RData * Z64) :=\n    match pud, addr with\n    | VZ64 pud, VZ64 addr =>\n      if (pud =? 0) then\n        when' res == check64_spec (VZ64 0) adt;\n        Some (adt, VZ64 res)\n      else\n        let pud_pa := phys_page pud in\n        let pmd_idx := pmd_index addr in\n        let p := Z.lor pud_pa (pmd_idx * 8) in\n        when' pmd == pt_load_spec vmid (VZ64 p) adt;\n        rely is_int64 pmd;\n        if (pmd =? 0) && (alloc =? 1) then\n          when' pmd_pa, adt' == alloc_pmd_page_spec vmid adt;\n          rely is_addr pmd_pa;\n          let pmd' := Z.lor pmd_pa PMD_TYPE_TABLE in\n          when adt'' == pt_store_spec vmid (VZ64 p) (VZ64 pmd') adt';\n          when' res == check64_spec (VZ64 pmd') adt'';\n          Some (adt'', VZ64 res)\n        else\n          when' res == check64_spec (VZ64 pmd) adt;\n          Some (adt, VZ64 res)\n    end.\n\n  Definition walk_pte_spec0 (vmid: Z) (pmd: Z64) (addr: Z64) (adt: RData) : option Z64 :=\n    match pmd, addr with\n    | VZ64 pmd, VZ64 addr =>\n      if (pmd =? 0) then\n        when' res == check64_spec (VZ64 0) adt;\n        Some (VZ64 res)\n      else\n        let pmd_pa := phys_page pmd in\n        let pte_idx := pte_index addr in\n        let p := Z.lor pmd_pa (pte_idx * 8) in\n        when' pte == pt_load_spec vmid (VZ64 p) adt;\n        rely is_int64 pte;\n        when' res == check64_spec (VZ64 pte) adt;\n        Some (VZ64 res)\n    end.\n\n  Definition set_pmd_spec0 (vmid: Z) (pud: Z64) (addr: Z64) (pmd: Z64) (adt: RData) : option RData :=\n    match pud, addr, pmd with\n    | VZ64 pud, VZ64 addr, VZ64 pmd =>\n      let pud_pa := phys_page pud in\n      let pmd_idx := pmd_index addr in\n      let p := Z.lor pud_pa (pmd_idx * 8) in\n      pt_store_spec vmid (VZ64 p) (VZ64 pmd) adt\n    end.\n\n  Definition set_pte_spec0 (vmid: Z) (pmd: Z64) (addr: Z64) (pte: Z64) (adt: RData) : option RData :=\n    match pmd, addr, pte with\n    | VZ64 pmd, VZ64 addr, VZ64 pte' =>\n      let pmd_pa := phys_page pmd in\n      let pte_idx := pte_index addr in\n      let p := Z.lor pmd_pa (pte_idx * 8) in\n      pt_store_spec vmid (VZ64 p) (VZ64 pte') adt\n    end.\n\n  Inductive walk_pgd_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_pgd_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' vmid vttbr addr alloc res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_pgd_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned vttbr)) (VZ64 (Int64.unsigned addr)) (Int.unsigned alloc) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      walk_pgd_spec_low_step s WB ((Vint vmid)::(Vlong vttbr)::(Vlong addr)::(Vint alloc)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Inductive walk_pud_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_pud_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' vmid pgd addr alloc res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_pud_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned pgd)) (VZ64 (Int64.unsigned addr)) (Int.unsigned alloc) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      walk_pud_spec_low_step s WB ((Vint vmid)::(Vlong pgd)::(Vlong addr)::(Vint alloc)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Inductive walk_pmd_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_pmd_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' vmid pud addr alloc res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_pmd_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned pud)) (VZ64 (Int64.unsigned addr)) (Int.unsigned alloc) labd = Some (labd', (VZ64 (Int64.unsigned res)))):\n      walk_pmd_spec_low_step s WB ((Vint vmid)::(Vlong pud)::(Vlong addr)::(Vint alloc)::nil) (m'0, labd) (Vlong res) (m'0, labd').\n\n  Inductive walk_pte_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | walk_pte_spec_low_intro s (WB: _ -> Prop) m'0 labd vmid pmd addr res\n      (Hinv: high_level_invariant labd)\n      (Hspec: walk_pte_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned pmd)) (VZ64 (Int64.unsigned addr)) labd = Some (VZ64 (Int64.unsigned res))):\n      walk_pte_spec_low_step s WB ((Vint vmid)::(Vlong pmd)::(Vlong addr)::nil) (m'0, labd) (Vlong res) (m'0, labd).\n\n  Inductive set_pmd_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | set_pmd_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' vmid pud addr pmd\n      (Hinv: high_level_invariant labd)\n      (Hspec: set_pmd_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned pud)) (VZ64 (Int64.unsigned addr)) (VZ64 (Int64.unsigned pmd)) labd = Some labd'):\n      set_pmd_spec_low_step s WB ((Vint vmid)::(Vlong pud)::(Vlong addr)::(Vlong pmd)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Inductive set_pte_spec_low_step `{StencilOps} `{Mem.MemoryModelOps} `{UseMemWithData mem}:\n    sextcall_sem (mem := mwd LDATAOps) :=\n  | set_pte_spec_low_intro s (WB: _ -> Prop) m'0 labd labd' vmid pmd addr pte\n      (Hinv: high_level_invariant labd)\n      (Hspec: set_pte_spec0 (Int.unsigned vmid) (VZ64 (Int64.unsigned pmd)) (VZ64 (Int64.unsigned addr)) (VZ64 (Int64.unsigned pte)) labd = Some labd'):\n      set_pte_spec_low_step s WB ((Vint vmid)::(Vlong pmd)::(Vlong addr)::(Vlong pte)::nil) (m'0, labd) Vundef (m'0, labd').\n\n  Section WITHMEM.\n\n    Context `{Hstencil: Stencil}.\n    Context `{Hmem: Mem.MemoryModelX}.\n    Context `{Hmwd: UseMemWithData mem}.\n\n    Definition walk_pgd_spec_low: compatsem LDATAOps :=\n      csem walk_pgd_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::Tint32::nil)) Tint64.\n\n    Definition walk_pud_spec_low: compatsem LDATAOps :=\n      csem walk_pud_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::Tint32::nil)) Tint64.\n\n    Definition walk_pmd_spec_low: compatsem LDATAOps :=\n      csem walk_pmd_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::Tint32::nil)) Tint64.\n\n    Definition walk_pte_spec_low: compatsem LDATAOps :=\n      csem walk_pte_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::nil)) Tint64.\n\n    Definition set_pmd_spec_low: compatsem LDATAOps :=\n      csem set_pmd_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::Tint64::nil)) Tvoid.\n\n    Definition set_pte_spec_low: compatsem LDATAOps :=\n      csem set_pte_spec_low_step (type_of_list_type (Tint32::Tint64::Tint64::Tint64::nil)) Tvoid.\n\n  End WITHMEM.\n\nEnd PTWalkSpecLow.\n\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/sekvm/PTWalk/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.1528509544912861}}
{"text": "Require Import SegmentQueue.lib.thread_queue.thread_queue.\nFrom SegmentQueue.lib.concurrent_linked_list.infinite_array\n     Require Import array_spec iterator.iterator_impl.\nFrom SegmentQueue.lib.util Require Import future getAndUpdate forRange.\nFrom iris.heap_lang Require Import notation.\n\nSection impl.\n\nVariable array_interface: infiniteArrayInterface.\n\nDefinition newLatch: val :=\n  \u03bb: \"count\", (ref \"count\", ref #0, newThreadQueue array_interface #()).\n\nDefinition latchResume: val :=\n  \u03bb: \"d\", resume array_interface #(Z.of_nat 300) #true #false #false \"d\"\n                 (\u03bb: <>, #()) #().\n\n(* Differs from the canonical implementation to be able to ignore the size of the\n   memory cell. *)\nDefinition addWaiter: val := \u03bb: \"waiters\", FAA \"waiters\" #2.\nDefinition removeWaiter: val := \u03bb: \"waiters\", FAA \"waiters\" #(-2).\nDefinition hasDoneMark: val := \u03bb: \"w\", \"w\" `rem` #2 = #1.\nDefinition setDoneMark: val := \u03bb: \"w\", \"w\" + #1.\n\nDefinition resumeWaiters: val :=\n  \u03bb: \"latch\",\n  let: \"waiters\" := Snd (Fst \"latch\") in\n  let: \"d\" := Snd (Snd \"latch\") in\n  let: \"w\" := getAndUpdate\n                \"waiters\"\n                (\u03bb: \"cur\",\n                 if: hasDoneMark \"cur\"\n                 then NONE\n                 else SOME (setDoneMark \"cur\"))\n  in match: \"w\" with\n        NONE => #()\n      | SOME \"w'\" => forRange (\"w'\" `quot` #2) (\u03bb: <>, latchResume \"d\");; #()\n     end.\n\nDefinition countDown: val :=\n  \u03bb: \"latch\",\n  let: \"counter\" := Fst (Fst \"latch\") in\n  let: \"d\" := Snd (Snd \"latch\") in\n  let: \"p\" := FAA \"counter\" #(-1) in\n  if: \"p\" - #1 \u2264 #0 then resumeWaiters \"latch\" else #().\n\nDefinition await: val :=\n  \u03bb: \"latch\",\n  let: \"counter\" := Fst (Fst \"latch\") in\n  let: \"waiters\" := Snd (Fst \"latch\") in\n  let: \"e\" := Fst (Snd \"latch\") in\n  if: !\"counter\" \u2264 #0 then fillThreadQueueFuture #()\n  else let: \"w\" := addWaiter \"waiters\" in\n       if: hasDoneMark \"w\" then fillThreadQueueFuture #()\n       else match: suspend array_interface \"e\" with\n              InjR \"f\" => \"f\"\n            | InjL \"x\" => \"undefined\"\n            end.\n\nDefinition cancelLatchFuture : val :=\n  \u03bb: \"latch\" \"f\",\n  let: \"waiters\" := Snd (Fst \"latch\") in\n  let: \"onCancellation\" :=\n     \u03bb: <>, let: \"w\" := removeWaiter \"waiters\" in ~ (hasDoneMark \"w\")\n  in\n  let: \"d\" := Snd (Snd \"latch\") in\n  tryCancelThreadQueueFuture' array_interface\n                              #false #(Z.of_nat 300) #false #false\n                              \"d\" \"onCancellation\"\n                              (\u03bb: <>, #()) (\u03bb: <>, #()) \"f\".\n\nDefinition getCount: val :=\n  \u03bb: \"latch\",\n  let: \"counter\" := Fst (Fst \"latch\") in\n  let: \"c\" := !\"counter\" in\n  if: \"c\" \u2264 #0 then #0 else \"c\".\n\nEnd impl.\n\nFrom SegmentQueue.util Require Import everything big_opL local_updates.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.algebra Require Import numbers auth list gset excl csum.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Import proofmode.\n\nSection proof.\n\nNotation algebra := (authR (prodUR\n                              natUR\n                              (optionUR (csumR (exclR positiveR)\n                                                (optionR (agreeR unitO)))))).\n\nClass latchG \u03a3 := BarrierG { barrier_inG :> inG \u03a3 algebra }.\nDefinition latch\u03a3 : gFunctors := #[GFunctor algebra].\nInstance subG_latch\u03a3 {\u03a3} : subG latch\u03a3 \u03a3 -> latchG \u03a3.\nProof. solve_inG. Qed.\n\nContext `{heapG \u03a3} `{iteratorG \u03a3} `{threadQueueG \u03a3} `{futureG \u03a3} `{latchG \u03a3}.\nVariable (N NFuture: namespace).\nVariable (HNDisj: N ## NFuture).\nLet NLatch := N .@ \"Latch\".\nLet NTq := N .@ \"Tq\".\nNotation iProp := (iProp \u03a3).\n\nVariable array_interface: infiniteArrayInterface.\nVariable array_spec: infiniteArraySpec _ array_interface.\n\nDefinition latch_broken \u03b3 := own \u03b3 (\u25ef (0, Some (Cinr \u03b5))).\n\nDefinition latch_closed \u03b3 := own \u03b3 (\u25ef (0, Some (Cinr (Some (to_agree ()))))).\n\nDefinition latch_waiter_registered \u03b3 := own \u03b3 (\u25ef (1, \u03b5)).\n\nDefinition latch_waiter_permit \u03b3 \u03b3f: iProp :=\n  latch_waiter_registered \u03b3 \u2228\n  (\u2203 v, future_is_completed \u03b3f v).\n\nGlobal Instance latch_broken_persistent: Persistent (latch_broken \u03b3).\nProof. apply _. Qed.\n\nLet tqParams \u03b3l :=\n  @ThreadQueueParameters \u03a3 false True (latch_broken \u03b3l) True\n                         (fun v => \u231c#v = #()\u231d)%I False.\n\nLet isThreadQueue \u03b3l := is_thread_queue NTq NFuture (tqParams \u03b3l) _ array_spec.\n\nDefinition is_latch_future \u03b3l :=\n  is_thread_queue_future NTq NFuture (tqParams \u03b3l) _ array_spec.\n\nLemma resumeLatch_spec R maxWait (wait: bool) \u03b3a \u03b3tq \u03b3e \u03b3d e d:\n  {{{ isThreadQueue R \u03b3a \u03b3tq \u03b3e \u03b3d e d \u2217 awakening_permit \u03b3tq }}}\n    resume array_interface #(Z.of_nat maxWait) #true #false #wait d (\u03bb: <>, #())%V #()\n  {{{ RET #true; True }}}.\nProof.\n  iIntros (\u03a6) \"[#HTq HAwak] H\u03a6\".\n  iApply (resume_spec with \"[] [HAwak]\").\n  5: { by iFrame \"HTq HAwak\". }\n  by solve_ndisj. done. done.\n  { simpl. iIntros (\u03a8) \"!> _ H\u03a8\". wp_pures. by iApply \"H\u03a8\". }\n  iIntros \"!>\" (r) \"Hr\". simpl. destruct r; first by iApply \"H\u03a6\".\n  iDestruct \"Hr\" as \"[% _]\"; lia.\nQed.\n\nDefinition latch_invariant (\u03b3l \u03b3tq: gname) (\u2113 w\u2113: loc) (n: nat) (w: nat): iProp :=\n  w\u2113 \u21a6 #(w * 2)%nat \u2217 thread_queue_state \u03b3tq w \u2217\n    (\u231cn > 0\u231d \u2227 own \u03b3l (\u25cf (w, Some (Cinl (Excl (Pos.of_nat n))))) \u2217 \u2113 \u21a6 #n \u2228\n     \u231cn = 0\u231d \u2227 own \u03b3l (\u25cf (w, Some (Cinr None))) \u2217\n        (\u2203 n', \u231c(n' \u2264 0)%Z\u231d \u2227 \u2113 \u21a6 #n')) \u2228\n  w\u2113 \u21a6 #(w * 2 + 1)%nat \u2217 thread_queue_state \u03b3tq 0 \u2217\n    \u231cn = 0\u231d \u2217 own \u03b3l (\u25cf (w, Some (Cinr (Some (to_agree ()))))) \u2217\n    (\u2203 n', \u231c(n' \u2264 0)%Z\u231d \u2227 \u2113 \u21a6 #n').\n\nDefinition is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d (s: val): iProp :=\n  \u2203 e d (p pw: loc), \u231cs = (#p, #pw, (e, d))%V\u231d \u2227\n  inv NLatch (\u2203 n w, latch_invariant \u03b3l \u03b3tq p pw n w)\n  \u2217 isThreadQueue \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d e d.\n\nDefinition latch_state \u03b3l (counter: nat): iProp :=\n  own \u03b3l (\u25ef (0, Some (match counter with\n        0 => Cinr \u03b5\n      | _ => Cinl (Excl (Pos.of_nat counter))\n                      end))).\n\nTheorem newLatch_spec (c: Z):\n  {{{ inv_heap_inv }}}\n    newLatch array_interface #c\n  {{{ \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s, RET s; is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s \u2217\n                                latch_state \u03b3l (if decide (0 \u2264 c)%Z then Z.to_nat c else 0)\n  }}}.\nProof.\n  iIntros (\u03a6) \"#HHeap H\u03a6\".\n  remember (if decide (0 \u2264 c)%Z then Z.to_nat c else 0) as n.\n  destruct n as [|n'].\n  {\n    iMod (own_alloc (\u25cf (0, Some (Cinr None)) \u22c5 \u25ef (0, Some (Cinr None))))\n      as (\u03b3l) \"[H\u25cf H\u25ef]\".\n    by apply auth_both_valid=> //.\n    wp_lam. wp_bind (newThreadQueue _ _).\n    iApply (newThreadQueue_spec with \"HHeap\").\n    iIntros (\u03b3a \u03b3tq \u03b3e \u03b3d e d) \"!> [#HTq HThreadState]\".\n    wp_alloc pw as \"Hpw\". wp_alloc p as \"Hp\". rewrite -wp_fupd. wp_pures.\n    iMod (inv_alloc NLatch _ (\u2203 n w, latch_invariant \u03b3l \u03b3tq p pw n w) with \"[-H\u03a6 H\u25ef]\")\n      as \"#HInv\".\n    { iExists 0, 0. simpl. iLeft. iFrame \"Hpw HThreadState\". iRight. iFrame.\n      iSplitR; first done. iExists _. iFrame. iPureIntro.\n      destruct (decide (0 \u2264 c)%Z); lia. }\n    iApply \"H\u03a6\". iSplitR.\n    { iExists _, _, _, _. iSplitR; first done. by iFrame \"HInv HTq\". }\n    rewrite /latch_state. by iFrame.\n  }\n  remember (S n') as n eqn:Hn'.\n  iMod (own_alloc (\u25cf (0, Some (Cinl (Excl (Pos.of_nat n)))) \u22c5\n                   \u25ef (0, Some (Cinl (Excl (Pos.of_nat n))))))\n    as (\u03b3l) \"[H\u25cf H\u25ef]\".\n  by apply auth_both_valid=> //.\n  wp_lam. wp_bind (newThreadQueue _ _).\n  iApply (newThreadQueue_spec with \"HHeap\").\n  iIntros (\u03b3a \u03b3tq \u03b3e \u03b3d e d) \"!> [#HTq HThreadState]\".\n  wp_alloc pw as \"Hpw\". wp_alloc p as \"Hp\". rewrite -wp_fupd. wp_pures.\n  iMod (inv_alloc NLatch _ (\u2203 n w, latch_invariant \u03b3l \u03b3tq p pw n w) with \"[-H\u03a6 H\u25ef]\")\n    as \"#HInv\".\n  { iExists n, 0. simpl. iLeft. iFrame \"Hpw HThreadState\". iLeft. iFrame.\n    destruct (decide (0 \u2264 c)%Z); last lia. rewrite Heqn.\n    rewrite Z2Nat.id; last lia. iFrame. iPureIntro. lia. }\n  iApply \"H\u03a6\". iSplitR.\n  { iExists _, _, _, _. iSplitR; first done. by iFrame \"HInv HTq\". }\n  rewrite /latch_state. by destruct n; first lia.\nQed.\n\nLemma await_spec \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s:\n  {{{ is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s }}}\n    await array_interface s @ \u22a4\n  {{{ \u03b3f v, RET v;\n      is_latch_future \u03b3l \u03b3tq \u03b3a \u03b3f v \u2217\n      thread_queue_future_cancellation_permit \u03b3f \u2217\n      latch_waiter_permit \u03b3l \u03b3f }}}.\nProof.\n  iIntros (\u03a6) \"#HLatch H\u03a6\". wp_lam. rewrite /is_latch.\n  iDestruct \"HLatch\" as (e d p pw ->) \"[HInv HTq]\".\n  wp_pures. wp_bind (!_)%E.\n  iInv \"HInv\" as (n w) \"HLatchInv\" \"HClose\".\n  iDestruct \"HLatchInv\" as\n      \"[(Hpw & HTqState & [(>% & H\u25cf & Hp)|(>-> & H\u25cf & Hp)])|\n        (Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n  - wp_load. iMod (\"HClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iLeft. iFrame \"Hpw HTqState\". iLeft. by iFrame. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last lia. clear. wp_pures.\n    wp_lam. wp_bind (FAA _ _).\n    iInv \"HInv\" as (n w) \"HLatchInv\" \"HClose\".\n    iDestruct \"HLatchInv\" as \"[(Hpw & HTqState & HRest)|\n      (Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n    * wp_faa.\n      iMod (thread_queue_append' with \"HTq [] HTqState\")\n        as \"[HState HSus]\"=> /=; [by solve_ndisj|done|].\n      iAssert (\n          |==>\n          latch_waiter_registered \u03b3l \u2217\n          (\u231cn > 0\u231d \u2227 own \u03b3l (\u25cf (S w, Some (Cinl (Excl (Pos.of_nat n))))) \u2217 p \u21a6 #n\n           \u2228 \u231cn = 0\u231d \u2227 own \u03b3l (\u25cf (S w, Some (Cinr None))) \u2217 (\u2203 n' : Z, \u231c(n' \u2264 0)%Z\u231d \u2227 p \u21a6 #n'))\n      )%I with \"[HRest]\" as \">[HToken HRest]\".\n      {\n        iDestruct \"HRest\" as \"[(H1 & H\u25cf & H2)|(H1 & H\u25cf & H2)]\".\n        2: iMod (own_update with \"H\u25cf\") as \"[H\u25cf $]\"; last by iRight; iFrame.\n        1: iMod (own_update with \"H\u25cf\") as \"[H\u25cf $]\"; last by iLeft; iFrame.\n        all: apply auth_update_alloc, prod_local_update_1, nat_local_update.\n        all: replace \u03b5 with 0 by done; lia.\n      }\n      iMod (\"HClose\" with \"[-HSus H\u03a6 HToken]\") as \"_\".\n      { iExists _, _. iLeft. iFrame.\n        replace ((w * 2)%nat + 2)%Z with (Z.of_nat (S w * 2)) by lia.\n        by iFrame. }\n      iModIntro. wp_pures. wp_lam. wp_pures. rewrite bool_decide_false.\n      2: { case. rewrite Nat2Z.inj_mul Z.rem_mul; lia. }\n      wp_pures. wp_apply (suspend_spec with \"[$]\")=>/=.\n      iIntros (v) \"[(_ & _ & %)|Hv]\"; first done.\n      iDestruct \"Hv\" as (\u03b3f v' ->) \"[HFuture HCancPermit]\".\n      wp_pures. iApply \"H\u03a6\". iFrame.\n    * wp_faa.\n      iAssert (|==> own \u03b3l (\u25cf (S w, Some (Cinr _))) \u2217\n                    (latch_broken \u03b3l \u2217 latch_waiter_registered \u03b3l))%I\n        with \"[H\u25cf]\" as \">[H\u25cf [H\u25ef HToken]]\".\n      { iMod (own_update with \"H\u25cf\") as \"[$ [$ $]]\"; last done.\n        apply auth_update_alloc=> /=. apply prod_local_update=> /=.\n        - apply nat_local_update. replace \u03b5 with 0 by done.\n          replace (0 \u22c5 1) with 1 by done. lia.\n        - rewrite cmra_comm. apply core_id_local_update.\n          apply _. apply Some_included. right. apply Cinr_included.\n          apply ucmra_unit_least.\n      }\n      iMod (\"HClose\" with \"[-H\u03a6 H\u25ef HToken]\") as \"_\".\n      { iExists 0, (S w). iRight. iFrame. iSplitL; last done.\n        by replace (Z.of_nat (S w * 2 + 1)) with ((w * 2 + 1)%nat + 2)%Z by lia. }\n      iModIntro. wp_pures. wp_lam. wp_pures. rewrite bool_decide_true.\n      2: { congr LitV.\n        rewrite Nat.add_comm Nat2Z.inj_add Nat2Z.inj_mul Z.rem_add //; lia. }\n      wp_pures.\n      iApply (fillThreadQueueFuture_spec with \"[H\u25ef]\").\n      2: by iIntros \"!>\" (\u03b3f v') \"(H & H' & H'')\"; iApply \"H\u03a6\"; iFrame.\n      rewrite /V'. iExists _. simpl. iFrame. done.\n  - iDestruct \"Hp\" as (n') \"[>% Hp]\". wp_load.\n    iAssert (|==> own \u03b3l (\u25cf _) \u2217 latch_broken \u03b3l)%I with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_core_id. apply _. apply prod_included=> /=. split.\n      by apply nat_included; lia.\n      apply Some_included. right. apply Cinr_included. apply ucmra_unit_least. }\n    iMod (\"HClose\" with \"[-H\u03a6 H\u25ef]\") as \"_\".\n    { iExists _, _. iLeft. iFrame \"Hpw HTqState\". iRight. iFrame.\n      iSplitR; first done. iExists n'. iFrame. done. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    iApply (fillThreadQueueFuture_spec with \"[H\u25ef]\").\n    2: { iIntros \"!>\" (\u03b3f v') \"(H & H' & H'')\"; iApply \"H\u03a6\"; iFrame.\n         by iRight; iExists _. }\n    rewrite /V'. iExists _. simpl. iFrame. done.\n  - iDestruct \"Hp\" as (n') \"[>% Hp]\". wp_load.\n    iAssert (|==> own \u03b3l (\u25cf _) \u2217 latch_broken \u03b3l)%I with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_core_id. apply _. apply prod_included=> /=. split.\n      by apply nat_included; lia.\n      apply Some_included. right. apply Cinr_included. apply ucmra_unit_least. }\n    iMod (\"HClose\" with \"[-H\u03a6 H\u25ef]\") as \"_\".\n    { iExists _, _. iRight. iFrame \"Hpw HTqState\". iFrame.\n      iSplitR; first done. iExists n'. iFrame. done. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    iApply (fillThreadQueueFuture_spec with \"[H\u25ef]\").\n    2: {\n      iIntros \"!>\" (\u03b3f v') \"(H & H' & H'')\"; iApply \"H\u03a6\"; iFrame.\n      iRight. by iExists _. }\n    rewrite /V'. iExists _. simpl. iFrame. done.\nQed.\n\nLemma excl_included {A: ofeT} (a b: A): Excl a \u227c Excl b -> a \u2261 b.\nProof. intros [x y]. destruct x; inversion_clear y. Qed.\n\nLemma getCount_spec \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s:\n  is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s -\u2217\n  <<< \u2200 (n: nat), latch_state \u03b3l n >>>\n    getCount s @ \u22a4 \u2216 \u2191NLatch\n  <<< latch_state \u03b3l n, RET #n >>>.\nProof.\n  iIntros \"#HLatch\" (\u03a6) \"AU\". wp_lam.\n  iDestruct \"HLatch\" as (e d p pw ->) \"[HInv HTq]\". wp_pures. wp_bind (!_)%E.\n  iInv \"HInv\" as (n' w) \"HOpen\" \"HInvClose\".\n  iMod \"AU\" as (n) \"[HState [_ HClose]]\".\n  iDestruct \"HOpen\" as\n      \"[(Hpw & HTqState & [(>% & H\u25cf & Hp)|(>-> & H\u25cf & Hp)])|\n        (Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n  - wp_load.\n    iAssert (\u231cn' = n\u231d)%I as %->.\n    { iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      destruct n as [|n].\n      { exfalso. move: HValid. case. by move=> HContra; inversion HContra.\n        rewrite csum_included. case; first done.\n        case; intros (? & ? & ? & ? & ?)=> //. }\n      iPureIntro. move: HValid. rewrite Cinl_included.\n      case; move=> HValid; [apply Cinl_inj in HValid; inversion HValid; subst|\n                           apply excl_included in HValid].\n      all: apply Nat2Pos.inj; [lia|lia|done].\n    }\n    iMod (\"HClose\" with \"HState\") as \"H\u03a6\". iModIntro.\n    iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iLeft. iFrame \"Hpw HTqState\". iLeft. by iFrame. }\n    iModIntro. wp_pures. rewrite bool_decide_false; last lia. by wp_pures.\n  - iDestruct \"Hp\" as (n'') \"[>% Hp]\".\n    wp_load.\n    iAssert (\u231cn = 0\u231d)%I as %->.\n    { iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      destruct n as [|n]; first done.\n      { exfalso. move: HValid. case. by move=> HContra; inversion HContra.\n        rewrite csum_included. case; first done.\n        case; intros (? & ? & ? & ? & ?)=> //. }\n    }\n    iMod (\"HClose\" with \"HState\") as \"H\u03a6\". iModIntro.\n    iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iLeft. iFrame \"Hpw HTqState\". iRight. iFrame.\n      iSplitR; first done. iExists _. iSplitR; last iFrame. done. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia.\n    by wp_pures.\n  - iDestruct \"Hp\" as (n'') \"[>% Hp]\".\n    wp_load.\n    iAssert (\u231cn = 0\u231d)%I as %->.\n    { iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      destruct n as [|n]; first done.\n      { exfalso. move: HValid. case. by move=> HContra; inversion HContra.\n        rewrite csum_included. case; first done.\n        case; intros (? & ? & ? & ? & ?)=> //. }\n    }\n    iMod (\"HClose\" with \"HState\") as \"H\u03a6\". iModIntro.\n    iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iRight. iFrame.\n      iSplitR; first done. iExists _. iSplitR; last iFrame. done. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia.\n    by wp_pures.\nQed.\n\nLemma resumeWaiters_spec \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s:\n  {{{ is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s \u2217 latch_broken \u03b3l }}}\n    resumeWaiters array_interface s\n  {{{ RET #(); True }}}.\nProof.\n  iIntros (\u03a6) \"[#HLatch #HBroken] H\u03a6\". wp_lam.\n  iDestruct \"HLatch\" as (e d p pw ->) \"[HInv HTq]\". wp_pures.\n  wp_lam. wp_pures.\n  iL\u00f6b as \"IH\".\n  wp_bind (!_)%E.\n  iInv \"HInv\" as (n w) \"HLatchInv\" \"HClose\".\n  iDestruct \"HLatchInv\" as\n      \"[(Hpw & HTqState & HRest)|\n        (Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n  all: wp_load.\n  - iMod (\"HClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iLeft. iFrame \"Hpw HTqState\". by iFrame. }\n    iModIntro. wp_pures. wp_lam. wp_pures. rewrite bool_decide_false.\n    2: { case. rewrite Nat2Z.inj_mul Z.rem_mul; lia. }\n    wp_pures. wp_lam. wp_pures. wp_bind (CmpXchg _ _ _). clear n.\n    iInv \"HInv\" as (n w') \"HLatchInv\" \"HClose\".\n    iDestruct \"HLatchInv\" as\n        \"[(Hpw & HTqState & HRest)|(Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n    2: { wp_cmpxchg_fail. case; lia.\n         iMod (\"HClose\" with \"[-H\u03a6]\") as \"_\".\n         { iExists _, _. iRight. by iFrame. }\n         iModIntro. wp_pures. wp_lam. wp_pures. by iApply \"IH\". }\n    destruct (decide (w = w')).\n    2: { wp_cmpxchg_fail. case; lia.\n         iMod (\"HClose\" with \"[-H\u03a6]\") as \"_\".\n         { iExists _, _. iLeft. by iFrame. }\n         iModIntro. wp_pures. wp_lam. wp_pures. by iApply \"IH\". }\n    wp_cmpxchg_suc. subst w'.\n    iAssert (|={\u22a4 \u2216 \u2191NLatch}=> thread_queue_state \u03b3tq 0 \u2217\n            [\u2217] replicate w (awakening_permit \u03b3tq))%I\n      with \"[HTqState]\" as \">[HState HAwaks]\".\n    {\n      iClear \"IH\". clear. iInduction (w) as [|w] \"IH\"=>/=. by iFrame.\n      iMod (thread_queue_register_for_dequeue' with\n                \"HTq [$] [$]\") as \"[HState $]\". by solve_ndisj.\n      lia. rewrite /= Nat.sub_0_r.\n      iApply (\"IH\" with \"HState\").\n    }\n    iDestruct \"HRest\" as \"[(_ & HContra & _)|(-> & H\u25cf & Hp)]\".\n    { iDestruct (own_valid_2 with \"HContra HBroken\")\n        as %[[_ HValid]%prod_included _]%auth_both_valid.\n      exfalso. move: HValid. rewrite Some_included. case.\n      by intros HValid; inversion HValid.\n      rewrite csum_included. case; first done.\n      case; by intros (? & ? & ? & ? & ?). }\n    iAssert (|==> own \u03b3l _ \u2217 latch_closed \u03b3l)%I with \"[H\u25cf]\" as \">[H\u25cf H\u25ef]\".\n    2: iMod (\"HClose\" with \"[-H\u03a6 H\u25ef HAwaks]\") as \"_\".\n    2: {\n      iExists _, w. iRight. iFrame \"HState\". iSplitL \"Hpw\".\n      by rewrite Nat2Z.inj_add.\n      iSplitR; first done. iFrame.\n    }\n    { iMod (own_update with \"H\u25cf\") as \"[$ $]\"; last done.\n      apply auth_update_alloc, prod_local_update_2, option_local_update'''=> //. }\n    iModIntro. wp_pures. replace 2%Z with (Z.of_nat 2) by lia.\n    rewrite quot_of_nat Nat.div_mul; last lia.\n    wp_apply (forRange_resource_map\n                (fun _ => awakening_permit \u03b3tq) (fun _ => True)%I\n             with \"[] [HAwaks]\").\n    + iIntros (i \u03a8) \"!> HAwak H\u03a8\". wp_pures. wp_lam.\n      wp_apply (resumeLatch_spec with \"[$]\"). iIntros (_).\n      by iApply \"H\u03a8\".\n    + by rewrite -big_sepL_replicate seq_length.\n    + iIntros (?) \"_\". wp_pures. by iApply \"H\u03a6\".\n  - iMod (\"HClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists _, _. iRight. by iFrame. }\n    iModIntro. wp_pures. wp_lam. wp_pures. rewrite bool_decide_true.\n    2: { congr LitV.\n         rewrite Nat.add_comm Nat2Z.inj_add Nat2Z.inj_mul Z.rem_add //; lia. }\n    wp_pures. by iApply \"H\u03a6\".\nQed.\n\nLemma countDown_spec \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s:\n  is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s -\u2217\n  <<< \u2200 n, latch_state \u03b3l n >>>\n    countDown array_interface s @ \u22a4 \u2216 \u2191NLatch\n  <<< if decide (2 \u2264 n)%nat then latch_state \u03b3l (n - 1)\n      else latch_state \u03b3l 0 \u2217 latch_broken \u03b3l,\n      RET #() >>>.\nProof.\n  iIntros \"#HLatch\" (\u03a6) \"AU\". wp_lam.\n  iDestruct \"HLatch\" as (e d p pw ->) \"[HInv HTq]\". wp_pures. wp_bind (FAA _ _).\n  iInv \"HInv\" as (n' w) \"HOpen\" \"HInvClose\".\n  iMod \"AU\" as (n) \"[HState [_ HClose]]\".\n  iDestruct \"HOpen\" as\n      \"[(Hpw & HTqState & [(>% & H\u25cf & Hp)|(>-> & H\u25cf & Hp)])|\n        (Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n  - wp_faa.\n    iAssert (\u231cn' = n\u231d)%I as %->.\n    { iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      destruct n as [|n].\n      { exfalso. move: HValid. case. by move=> HContra; inversion HContra.\n        rewrite csum_included. case; first done.\n        case; intros (? & ? & ? & ? & ?)=> //. }\n      iPureIntro. move: HValid. rewrite Cinl_included.\n      case; move=> HValid; [apply Cinl_inj in HValid; inversion HValid; subst|\n                           apply excl_included in HValid].\n      all: apply Nat2Pos.inj; [lia|lia|done].\n    }\n    destruct (decide (2 \u2264 n)).\n    * rewrite /latch_state. destruct n as [|[|rn]]; [lia | lia |]. simpl.\n      iAssert (|==> own \u03b3l (\u25cf (w, Some (Cinl (Excl (Pos.of_nat (S rn))))))\n                    \u2217 own \u03b3l (\u25ef (0, Some (Cinl (Excl (Pos.of_nat (S rn)))))))%I\n              with \"[H\u25cf HState]\" as \">[H\u25cf HState]\".\n      { iDestruct (own_update_2 with \"H\u25cf HState\") as \">[$ $]\"; last done.\n        apply auth_update, prod_local_update_2, option_local_update, csum_local_update_l=> /=.\n        by apply exclusive_local_update. }\n      iMod (\"HClose\" with \"HState\") as \"H\u03a6\". iModIntro.\n      iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n      { iExists _, _. iLeft. iFrame \"Hpw HTqState\". iLeft. iFrame \"H\u25cf\".\n        iSplitR; first by iPureIntro; lia.\n        by replace (Z.of_nat (S rn)) with ((2 + rn)%nat + -1)%Z by lia. }\n      iModIntro. wp_pures. rewrite bool_decide_false; last by lia. by wp_pures.\n    * rewrite /latch_state. destruct n as [|[|]]; last lia.\n      { iDestruct (own_valid_2 with \"H\u25cf HState\")\n          as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid. exfalso.\n        move: HValid; case=> HValid. by inversion HValid.\n        move: HValid. rewrite csum_included.\n        case; first done. case; intros (? & ? & ? & ? & ?)=> //. }\n      iAssert (|==> own \u03b3l (\u25cf (w, Some (Cinr \u03b5))) \u2217 own \u03b3l (\u25ef (0, Some (Cinr \u03b5))))%I\n              with \"[H\u25cf HState]\" as \">[H\u25cf #HState]\".\n      { iMod (own_update_2 with \"H\u25cf HState\") as \"[$ $]\"; last done.\n        apply auth_update, prod_local_update_2.\n        etransitivity. by apply delete_option_local_update, _.\n        apply alloc_option_local_update. done. }\n      iMod (\"HClose\" with \"[$]\") as \"H\u03a6\". iModIntro.\n      iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n      { iExists 0, _. iLeft. iFrame \"Hpw HTqState\". iRight. iFrame.\n        iSplitR; first done. iExists 0. by iFrame. }\n      iModIntro. wp_pures.\n      wp_apply resumeWaiters_spec.\n      { iFrame \"HState\". iExists _, _, _, _. iSplitR; first done.\n        iFrame \"HInv HTq\". }\n      by iIntros \"_\".\n  - iDestruct \"Hp\" as (n') \"[>% Hp]\". wp_faa.\n    destruct n=>/=.\n    2: {\n      iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      exfalso. move: HValid. case; first move=> HValid.\n      by inversion HValid.\n      rewrite csum_included. case; first done.\n      case; by intros (? & ? & ? & ? & ?).\n    }\n    iDestruct \"HState\" as \"#HState\". iMod (\"HClose\" with \"[$]\") as \"H\u03a6\".\n    iModIntro. iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists 0, _. iLeft. iFrame \"Hpw HTqState\". iRight. iFrame.\n      iSplitR; first done. iExists _. iFrame. iPureIntro. lia. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    wp_apply resumeWaiters_spec.\n    { iFrame \"HState\". iExists _, _, _, _. iSplitR; first done.\n      iFrame \"HInv HTq\". }\n    by iIntros \"_\".\n  - iDestruct \"Hp\" as (n') \"[>% Hp]\". wp_faa.\n    destruct n=>/=.\n    2: {\n      iDestruct (own_valid_2 with \"H\u25cf HState\")\n        as %[[_ HValid%Some_included]%prod_included _]%auth_both_valid.\n      exfalso. move: HValid. case; first move=> HValid.\n      by inversion HValid.\n      rewrite csum_included. case; first done.\n      case; by intros (? & ? & ? & ? & ?).\n    }\n    iDestruct \"HState\" as \"#HState\". iMod (\"HClose\" with \"[$]\") as \"H\u03a6\".\n    iModIntro. iMod (\"HInvClose\" with \"[-H\u03a6]\") as \"_\".\n    { iExists 0, _. iRight. iFrame. iSplitR; first done. iExists _. iFrame.\n      iPureIntro. lia. }\n    iModIntro. wp_pures. rewrite bool_decide_true; last lia. wp_pures.\n    wp_apply resumeWaiters_spec.\n    { iFrame \"HState\". iExists _, _, _, _. iSplitR; first done.\n      iFrame \"HInv HTq\". }\n    by iIntros \"_\".\nQed.\n\nLemma removeWaiter_local_update \u03b3l w r:\n  own \u03b3l (\u25cf (w, r)) -\u2217 latch_waiter_registered \u03b3l ==\u2217\n  own \u03b3l (\u25cf (w - 1, r)).\nProof.\n  iIntros \"H\u25cf H\u25ef\". iMod (own_update_2 with \"H\u25cf H\u25ef\") as \"$\"; last done.\n  apply auth_update_dealloc, prod_local_update_1.\n  apply local_update_total_valid=> _ _. rewrite nat_included. move=> Hw.\n  apply nat_local_update. replace \u03b5 with 0 by done. lia.\nQed.\n\nTheorem cancelLatchFuture_spec \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s \u03b3f f:\n  is_latch \u03b3l \u03b3a \u03b3tq \u03b3e \u03b3d s -\u2217\n  is_latch_future \u03b3l \u03b3tq \u03b3a \u03b3f f -\u2217\n  <<< \u25b7 thread_queue_future_cancellation_permit \u03b3f \u2217\n      latch_waiter_permit \u03b3l \u03b3f >>>\n    cancelLatchFuture array_interface s f @ \u22a4 \u2216 \u2191NFuture \u2216 \u2191N\n  <<< \u2203 (r: bool),\n      if r then future_is_cancelled \u03b3f\n      else (\u2203 v, \u25b7 future_is_completed \u03b3f v) \u2217\n           thread_queue_future_cancellation_permit \u03b3f \u2217\n           latch_waiter_permit \u03b3l \u03b3f, RET #r >>>.\nProof.\n  iIntros \"#HLatch #HFuture\" (\u03a6) \"AU\".\n  iDestruct \"HLatch\" as (e d p pw ->) \"[HInv HTq]\". wp_lam. wp_pures. wp_lam.\n  wp_pures. awp_apply (try_cancel_thread_queue_future with \"HTq HFuture\");\n              first by solve_ndisj.\n  iApply (aacc_aupd_commit with \"AU\"). by solve_ndisj.\n  iIntros \"[HCancPermit HWaiter]\". iAaccIntro with \"HCancPermit\".\n  by iIntros \"$ !>\"; iFrame; iIntros \"$ !>\".\n  iIntros (r) \"Hr\". iExists r. destruct r.\n  2: { iDestruct \"Hr\" as \"[$ $]\". iFrame. iIntros \"!> H\u03a6 !>\". by wp_pures. }\n  iDestruct \"Hr\" as \"[#HFutureCancelled Hr]\". iFrame \"HFutureCancelled\".\n  rewrite /is_latch_future /is_thread_queue_future.\n  iDestruct \"Hr\" as (i f' s ->) \"Hr\"=> /=.\n  iDestruct \"Hr\" as \"(#H\u21a6~ & #HTh & HToken)\". iIntros \"!> H\u03a6 !>\". wp_pures.\n  wp_lam. wp_pures. wp_apply derefCellPointer_spec.\n  by iDestruct \"HTq\" as \"(_ & $ & _)\". iIntros (\u2113) \"#H\u21a6\". wp_pures. wp_lam.\n  iDestruct \"HWaiter\" as \"[HWaiter|HContra]\".\n  2: {\n    iDestruct \"HContra\" as (?) \"HContra\".\n    iDestruct (future_is_completed_not_cancelled\n                 with \"HContra HFutureCancelled\") as %[].\n  }\n  iL\u00f6b as \"IHCancAllowed\".\n  wp_bind (FAA _ _).\n  iInv \"HInv\" as (n w) \"HOpen\" \"HInvClose\".\n  iDestruct \"HOpen\" as\n      \"[(Hpw & HTqState & HRest)|(Hpw & HTqState & >-> & H\u25cf & Hp)]\".\n  - wp_faa.\n    iAssert (\u231cw > 0\u231d)%I as %Hw.\n    { iAssert (\u2203 x, own \u03b3l (\u25cf (w, x)))%I with \"[HRest]\" as (?) \"H\u25cf\".\n      by iDestruct \"HRest\" as \"[(_ & H\u25cf & _)|(_ & H\u25cf & _)]\"; by iExists _.\n      iDestruct (own_valid_2 with \"H\u25cf HWaiter\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      iPureIntro. simpl in *. lia.\n    }\n    iMod (register_cancellation with \"HTq HToken HTqState\")\n        as \"[HCancToken HTqState]\"; first by solve_ndisj.\n    rewrite bool_decide_false; last lia.\n    iDestruct \"HTqState\" as \"(HTqState & HR & #HInhabited)\".\n    iAssert (|==> (\u231cn > 0\u231d \u2227 own \u03b3l (\u25cf (w - 1, Some (Cinl (Excl (Pos.of_nat n))))) \u2217 p \u21a6 #n\n     \u2228 \u231cn = 0\u231d \u2227 own \u03b3l (\u25cf (w - 1, Some (Cinr None))) \u2217 (\u2203 n' : Z, \u231c(n' \u2264 0)%Z\u231d \u2227 p \u21a6 #n')))%I\n                  with \"[HRest HWaiter]\" as \">HRest\".\n    {\n      iDestruct \"HRest\" as \"[(H1 & H\u25cf & H2)|(H1 & H\u25cf & H2)]\";\n        [iLeft|iRight]; iFrame \"H1 H2\".\n      all: by iMod (removeWaiter_local_update with \"H\u25cf HWaiter\") as \"$\".\n    }\n    iMod (\"HInvClose\" with \"[-H\u03a6 HCancToken HR]\") as \"_\".\n    { iExists n, (w - 1). iLeft. iFrame \"HTqState\".\n      replace (Z.of_nat ((w - 1) * 2)) with (Z.of_nat (w * 2) + (-2))%Z by lia.\n      iFrame \"Hpw\". iFrame. }\n    iModIntro. wp_pures. wp_lam. wp_pures. rewrite bool_decide_false.\n    2: { case. rewrite Nat2Z.inj_mul Z.rem_mul; lia. }\n    wp_pures. wp_bind (getAndSet.getAndSet _ _).\n    awp_apply (markCancelled_spec with \"HTq HInhabited H\u21a6 HCancToken HTh\")\n              without \"H\u03a6 HR\".\n    iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n    iIntros \"!> (H\u03a6 & HCancHandle)\". wp_pures.\n    iAssert (\u25b7 cell_cancellation_handle _ _ _ _ _ _)%I\n            with \"[HCancHandle]\" as \"HCancHandle\"; first done.\n    awp_apply (onCancelledCell_spec with \"[] H\u21a6~\") without \"Hv H\u03a6\".\n    by iDestruct \"HTq\" as \"(_ & $ & _)\".\n    iAaccIntro with \"HCancHandle\". by iIntros \"$\".\n    iIntros \"#HCancelled !> [Hv H\u03a6]\". wp_pures.\n    iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n    iDestruct \"Hv\" as (x ->) \"(#HInhabited' & HAwak & %)\"; simplify_eq.\n    wp_pures. wp_apply (resumeLatch_spec with \"[$]\").\n    iIntros \"_\". wp_pures. iApply \"H\u03a6\".\n  - wp_faa.\n    iAssert (\u231cw > 0\u231d)%I as %Hw.\n    { iDestruct (own_valid_2 with \"H\u25cf HWaiter\")\n        as %[[HValid%nat_included _]%prod_included _]%auth_both_valid.\n      iPureIntro. simpl in *. lia. }\n    iMod (register_cancellation with \"HTq HToken HTqState\")\n        as \"[HCancToken HState]\"; first by solve_ndisj.\n    iDestruct \"HState\" as \"(HTqState & HR & #HInhabited)\".\n    iMod (removeWaiter_local_update with \"H\u25cf HWaiter\") as \"H\u25cf\".\n    iMod (\"HInvClose\" with \"[-H\u03a6 HCancToken HR]\") as \"_\".\n    { iExists 0, (w - 1). iRight. iFrame.\n      replace ((w * 2 + 1)%nat + -2)%Z with (Z.of_nat ((w - 1) * 2 + 1)) by lia.\n      by iFrame.\n    }\n    iModIntro. wp_pures. wp_lam. wp_pures.\n    rewrite bool_decide_true.\n    2: { congr LitV.\n         rewrite Nat.add_comm Nat2Z.inj_add Nat2Z.inj_mul Z.rem_add //; lia. }\n    wp_pures. wp_bind (getAndSet.getAndSet _ _).\n    awp_apply (markRefused_spec with \"HTq HInhabited H\u21a6 HCancToken HTh [//]\")\n              without \"H\u03a6 HR\".\n    iAaccIntro with \"[//]\"; first done. iIntros (v) \"Hv\"=>/=.\n    iIntros \"!> [H\u03a6 HR]\". iDestruct \"Hv\" as \"[[-> _]|Hv]\"; first by wp_pures.\n    iDestruct \"Hv\" as (? ->) \"[_ >%]\". simplify_eq. wp_pures.\n    iApply \"H\u03a6\".\nQed.\n\nEnd proof.\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/countdownlatch/countdownlatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.26284183159693775, "lm_q1q2_score": 0.15279076905791203}}
{"text": "From isla Require Import opsem.\n\nDefinition a1825c : isla_trace :=\n  AssumeReg \"MDSCR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"EDSCR\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"MDCR_EL2\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"MDCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSLSR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"SP\"] (RegVal_Base (Val_Bits (BV 1%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL1\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  Smt (DeclareConst 69%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPTR_EL2\" [] (RegVal_Base (Val_Symbolic 69%Z)) Mk_annot :t:\n  Smt (DeclareConst 71%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPTR_EL3\" [] (RegVal_Base (Val_Symbolic 71%Z)) Mk_annot :t:\n  Smt (DeclareConst 76%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CPACR_EL1\" [] (RegVal_Base (Val_Symbolic 76%Z)) Mk_annot :t:\n  Smt (DeclareConst 84%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CNTHCTL_EL2\" [] (RegVal_Base (Val_Symbolic 84%Z)) Mk_annot :t:\n  Smt (DeclareConst 87%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL2\" [] (RegVal_Base (Val_Symbolic 87%Z)) Mk_annot :t:\n  Smt (DeclareConst 90%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"CNTKCTL_EL1\" [] (RegVal_Base (Val_Symbolic 90%Z)) Mk_annot :t:\n  Smt (DeclareConst 97%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAM2_EL2\" [] (RegVal_Base (Val_Symbolic 97%Z)) Mk_annot :t:\n  Smt (DeclareConst 108%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICH_HCR_EL2\" [] (RegVal_Base (Val_Symbolic 108%Z)) Mk_annot :t:\n  Smt (DeclareConst 121%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL1_NS\" [] (RegVal_Base (Val_Symbolic 121%Z)) Mk_annot :t:\n  Smt (DeclareConst 126%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAMIDR_EL1\" [] (RegVal_Base (Val_Symbolic 126%Z)) Mk_annot :t:\n  Smt (DeclareConst 140%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"PMUSERENR_EL0\" [] (RegVal_Base (Val_Symbolic 140%Z)) Mk_annot :t:\n  Smt (DeclareConst 147%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"MPAM3_EL3\" [] (RegVal_Base (Val_Symbolic 147%Z)) Mk_annot :t:\n  Smt (DeclareConst 150%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"ICC_SRE_EL3\" [] (RegVal_Base (Val_Symbolic 150%Z)) Mk_annot :t:\n  Smt (DeclareConst 157%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"MPAMHCR_EL2\" [] (RegVal_Base (Val_Symbolic 157%Z)) Mk_annot :t:\n  Smt (DeclareConst 174%Z (Ty_BitVec 32%N)) Mk_annot :t:\n  ReadReg \"HSTR_EL2\" [] (RegVal_Base (Val_Symbolic 174%Z)) Mk_annot :t:\n  Smt (DeclareConst 196%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R5\" [] (RegVal_Base (Val_Symbolic 196%Z)) Mk_annot :t:\n  Smt (DefineConst 197%Z (Val (Val_Symbolic 196%Z) Mk_annot)) Mk_annot :t:\n  WriteReg \"SCTLR_EL2\" [] (RegVal_Base (Val_Symbolic 197%Z)) Mk_annot :t:\n  Barrier (RegVal_Base (Val_Enum ((Mk_enum_id 2%nat), Mk_enum_ctor 27%nat))) Mk_annot :t:\n  Smt (DeclareConst 227%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 227%Z)) Mk_annot :t:\n  Smt (DefineConst 228%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 227%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 228%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/a1825c.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.15272217629851984}}
{"text": "Require Import Raft.\nRequire Import SpecLemmas.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import TermSanityInterface.\nRequire Import CandidateTermGtLogInterface.\n\nSection CandidateTermGtLog.\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 {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      | [ H : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n  Lemma candidate_term_gt_log_init :\n    raft_net_invariant_init candidate_term_gt_log.\n  Proof using. \n    red. unfold candidate_term_gt_log. simpl. discriminate.\n  Qed.\n\n  Lemma candidate_term_gt_log_client_request :\n    raft_net_invariant_client_request candidate_term_gt_log.\n  Proof using. \n    red. unfold candidate_term_gt_log. simpl. intros.\n    find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n    find_copy_apply_lem_hyp handleClientRequest_type.\n    find_apply_lem_hyp handleClientRequest_log. intuition.\n    + repeat find_rewrite. eauto.\n    + break_exists. intuition. repeat find_rewrite. discriminate.\n  Qed.\n\n  Lemma candidate_term_gt_log_timeout :\n    raft_net_invariant_timeout candidate_term_gt_log.\n  Proof using tsi. \n    red. unfold candidate_term_gt_log. simpl. intros.\n    find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n    find_copy_apply_lem_hyp handleTimeout_log_same.\n    find_apply_lem_hyp handleTimeout_type_strong. intuition.\n    + repeat find_rewrite. eauto.\n    + find_apply_lem_hyp no_entries_past_current_term_invariant.\n      unfold no_entries_past_current_term in *. intuition.\n      unfold no_entries_past_current_term_host in *. repeat find_rewrite.\n      find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma candidate_term_gt_log_append_entries :\n    raft_net_invariant_append_entries candidate_term_gt_log.\n  Proof using. \n    red. unfold candidate_term_gt_log. simpl. intros.\n    find_higher_order_rewrite. update_destruct; subst; rewrite_update; auto.\n    unfold handleAppendEntries in *. repeat break_match; tuple_inversion; eauto; discriminate.\n  Qed.\n\n  Ltac start := red; unfold candidate_term_gt_log; simpl; intros;\n    find_higher_order_rewrite; update_destruct; subst; rewrite_update; [|auto].\n\n  Lemma candidate_term_gt_log_append_entries_reply :\n    raft_net_invariant_append_entries_reply candidate_term_gt_log.\n  Proof using. \n    start.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_type.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log.\n    intuition; repeat find_rewrite; [eauto|discriminate].\n  Qed.\n\n  Lemma candidate_term_gt_log_request_vote :\n    raft_net_invariant_request_vote candidate_term_gt_log.\n  Proof using. \n    start.\n    find_copy_apply_lem_hyp handleRequestVote_type.\n    find_copy_apply_lem_hyp handleRequestVote_log.\n    intuition; repeat find_rewrite; [eauto|discriminate].\n  Qed.\n\n  Lemma candidate_term_gt_log_request_vote_reply :\n    raft_net_invariant_request_vote_reply candidate_term_gt_log.\n  Proof using. \n    red; unfold candidate_term_gt_log; simpl; intros;\n      find_higher_order_rewrite; update_destruct; rewrite_update; auto.\n    find_copy_apply_lem_hyp handleRequestVoteReply_type.\n    find_copy_apply_lem_hyp handleRequestVoteReply_log.\n    intuition; repeat find_rewrite; [eauto|discriminate|discriminate].\n  Qed.\n\n  Lemma candidate_term_gt_log_do_leader :\n    raft_net_invariant_do_leader candidate_term_gt_log.\n  Proof using. \n    start.\n    find_copy_apply_lem_hyp doLeader_type.\n    find_copy_apply_lem_hyp doLeader_log.\n    intuition. repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma candidate_term_gt_log_do_generic_server :\n    raft_net_invariant_do_generic_server candidate_term_gt_log.\n  Proof using. \n    start.\n    find_copy_apply_lem_hyp doGenericServer_type.\n    find_copy_apply_lem_hyp doGenericServer_log.\n    intuition. repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma candidate_term_gt_log_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset candidate_term_gt_log.\n  Proof using. \n    red. unfold candidate_term_gt_log. simpl. intros.\n    repeat find_reverse_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma candidate_term_gt_log_reboot :\n    raft_net_invariant_reboot candidate_term_gt_log.\n  Proof using. \n    start. unfold reboot in *. simpl in *. discriminate.\n  Qed.\n\n  Lemma candidate_term_gt_log_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      candidate_term_gt_log net.\n  Proof using tsi. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply candidate_term_gt_log_init.\n    - apply candidate_term_gt_log_client_request.\n    - apply candidate_term_gt_log_timeout.\n    - apply candidate_term_gt_log_append_entries.\n    - apply candidate_term_gt_log_append_entries_reply.\n    - apply candidate_term_gt_log_request_vote.\n    - apply candidate_term_gt_log_request_vote_reply.\n    - apply candidate_term_gt_log_do_leader.\n    - apply candidate_term_gt_log_do_generic_server.\n    - apply candidate_term_gt_log_state_same_packet_subset.\n    - apply candidate_term_gt_log_reboot.\n  Qed.\n\n  Instance ctgli : candidate_term_gt_log_interface.\n  Proof.\n    split. apply candidate_term_gt_log_invariant.\n  Qed.\nEnd CandidateTermGtLog.", "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/CandidateTermGtLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3007455664065234, "lm_q1q2_score": 0.15272216675060193}}
{"text": "(*\n * \u00a9 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\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     AdversaryUniverse\n\n     ModelCheck.ModelCheck\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.ProtocolAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n.\n\nFrom protocols Require Import\n     ExampleProtocols.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations.\nImport RealWorld.RealWorldNotations.\n\nSet Implicit Arguments.\n\nImport SimulationAutomation.\n\nFrom Frap Require Import Sets.\n\nModule Foo <: Sets.EMPTY.\nEnd Foo.\nModule Import SN := Sets.SetNotations(Foo).\n\nModule SimplePingProtocolSecure <: AutomatedSafeProtocol.\n\n  Import SignPingSendProtocol.\n\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b := tt.\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start startAdv.\n\n  Import Gen Tacs SetLemmas.\n\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start mkiU real_univ_start mkrU mkrUsr startAdv : core.\n\n  Section Test.\n    Section RW.\n      Import RealWorld.\n      Import RealWorldNotations.\n      \n      Definition testU :=\n        mkrU $0 $0 $0\n             (* user A *)\n             ( n  <- Gen; Return n )\n             (* user B *)\n             ( @Return (Base Nat) 1 ) startAdv.\n\n      Definition testU' y :=\n        mkrU $0 $0 $0\n             (* user A *)\n             ( n  <- Return y; Return n )\n             (* user B *)\n             ( @Return (Base Nat) 1 ) startAdv.\n\n    End RW.\n\n    Section IW.\n      Import IdealWorld.\n      Import IdealNotations.\n      \n      Definition testI :=\n        mkiU #0 $0 $0\n             (* user A *)\n             ( n <- Gen; Return n)\n             (* user B *)\n             ( ret 1 ).\n    End IW.\n\n    Lemma sets_test1 :\n      { (false,false,false) } \\cap { (true,false,false) } = { }.\n    Proof.\n      sets.\n    Qed.\n\n    Lemma sets_test2 :\n      { (testU, testI, true) } \\cap { (testU, testI, false) } = { }.\n    Proof.\n      sets.\n    Qed.\n\n    (* Lemma sets_test3 : *)\n    (*   { ([, testI, true) } \\cap { (testU, testI, false) } = { }. *)\n    (* Proof. *)\n    (*   sets. *)\n    (* Qed. *)\n  End Test.\n\n  Import RealWorld.\n      \n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @step t__hon t__adv  |}\n      (fun st => safety st /\\ alignment st /\\ returns_align st).\n  Proof.\n    eapply invariant_weaken.\n\n    - apply multiStepClosure_ok; simpl.\n\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      (* time(gen). *)\n      \n    - intros.\n      simpl in *; repeat simple apply conj.\n      \n      + sets_invert; unfold safety;\n          split_ex; simpl in *; subst;\n            autounfold with *;\n            try solve [ solve_honest_actions_safe\n                        ; clean_map_lookups; eauto 8 ].\n\n      + sets_invert;\n          unfold alignment; split_ex; subst; split; trivial; repeat prove_alignment1; eauto 3.\n\n      + sets_invert\n        ; autounfold with *\n        ; split_ex\n        ; simpl in *\n        ; subst\n        ; unfold returns_align; intros\n        ; intros\n        ; find_step_or_solve\n        .\n\n        Unshelve.\n        all: exact 0 || auto.\n  Qed.\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, KEYS; 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, KEYS; solve_simple_maps; intuition eauto.\n      solve_simple_maps; eauto.\n\n      rewrite Forall_natmap_forall; intros.\n      solve_simple_maps; simpl\n      ; unfold permission_heap_good; intros;\n        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\n  Qed.\n\n\nEnd SimplePingProtocolSecure.\n\nModule SimpleEncProtocolSecure <: AutomatedSafeProtocol.\n\n  Import EncPingSendProtocol.\n\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b := tt.\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start startAdv.\n\n  Import Gen Tacs SetLemmas.\n\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start mkiU real_univ_start mkrU : core.\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @step t__hon t__adv  |}\n      (fun st => safety st /\\ alignment st /\\ returns_align st).\n  Proof.\n    eapply invariant_weaken.\n\n    - apply multiStepClosure_ok; simpl.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n      gen1.\n\n    - intros.\n      simpl in *; repeat simple apply conj.\n      \n      + sets_invert; unfold safety;\n          split_ex; simpl in *; subst;\n            autounfold with *;\n            solve_honest_actions_safe;\n            clean_map_lookups; eauto 8.\n        \n      + sets_invert;\n          unfold alignment; split_ex; subst; split; trivial; repeat prove_alignment1; eauto 3.\n\n      + sets_invert\n        ; autounfold with *\n        ; split_ex\n        ; simpl in *\n        ; subst\n        ; unfold returns_align; intros\n        ; intros\n        ; find_step_or_solve\n        .\n\n        Unshelve.\n        all: exact 0 || auto.\n  Qed.\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, KEYS; 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, KEYS; 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\n  Qed.\n\nEnd SimpleEncProtocolSecure.\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/ExampleProtocolsAutomated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.2689414155105029, "lm_q1q2_score": 0.1522258260608209}}
{"text": "(** Proof the causal memory implementation w.r.t. modular specification. *)\nFrom iris.algebra Require Import agree auth excl gmap.\nFrom iris.base_logic Require Import invariants.\n\nFrom iris.base_logic Require Export gen_heap.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.aneris_lang Require Import\n     lang network tactics proofmode lifting.\nFrom aneris.prelude Require Import misc.\nFrom aneris.aneris_lang.lib Require Import list_proof map_proof lock_proof network_util_proof inject.\nFrom aneris.aneris_lang.program_logic Require Import lightweight_atomic.\nFrom aneris.aneris_lang.lib.vector_clock Require Import vector_clock_proof.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\nFrom aneris.examples.rcb Require Import rcb_code.\nFrom aneris.examples.rcb.spec Require Import base.\nFrom aneris.examples.rcb.model Require Import\n     model_lst model_gst model_update_system model_update_lst model_update_gst.\nFrom aneris.examples.rcb.resources Require Import\n     base resources_global resources_lhst resources_local_inv resources_global_inv.\n\n\nSection proof.\n  Context `{!anerisG Mdl \u03a3, !RCB_params, !internal_RCBG \u03a3}.\n  Context (\u03b3Gauth \u03b3Gsnap : gname) (\u03b3Ls : list gname).\n\n  Lemma wp_is_causally_next n (vt : val) (t : vector_clock) (i : nat) :\n    {{{ \u231cis_vc vt t\u231d \u2217 \u231clength t = length RCB_addresses\u231d }}}\n      is_causally_next vt #i @[n]\n    {{{(f : val), RET f;\n       \u2200 (w : global_event),\n         {{{ True }}}\n           f ($ w) @[n]\n         {{{(b : bool), RET #b;\n            if b then\n              \u231cw.(ge_orig) \u2260 i \u2227\n              length w.(ge_time) = length t \u2227\n              w.(ge_time) !! w.(ge_orig) =\n              Some (S (default 0 (t !! w.(ge_orig)))) \u2227\n              (\u2200 j, j < length RCB_addresses \u2192 j \u2260 w.(ge_orig) \u2192\n                    default 0 (w.(ge_time) !! j) <= default 0 (t !! j))\u231d\n            else True\n         }}}\n    }}}.\n  Proof.\n    iIntros (\u03a6) \"[Ht Htlen] H\u03a6\".\n    iDestruct \"Ht\" as %Ht.\n    iDestruct \"Htlen\" as %Htlen.\n    rewrite /is_causally_next.\n    wp_pures.\n    wp_apply wp_list_length; first done.\n    iIntros (k Hk).\n    wp_pures.\n    iApply \"H\u03a6\".\n    clear \u03a6.\n    iIntros (w vw \u03a6) \"!# H\u03a6\".\n    wp_pures.\n    destruct (decide (i = w.(ge_orig))) as [->|Hioe].\n    { rewrite bool_decide_eq_true_2; last lia.\n      wp_pures.\n      iApply \"H\u03a6\"; done. }\n    rewrite bool_decide_eq_false_2; last lia.\n    wp_pures.\n    destruct (decide (w.(ge_orig) < length RCB_addresses)) as [Hlt|]; last first.\n    { rewrite bool_decide_eq_false_2; last lia.\n      wp_pures.\n      iApply \"H\u03a6\"; done. }\n    rewrite bool_decide_eq_true_2; last lia.\n    wp_pures.\n    wp_apply (wp_vect_applicable _ _ _ w.(ge_time) t with \"[]\");\n      [by iSplit; iPureIntro; first apply vector_clock_to_val_is_vc|].\n    iIntros (b) \"Hb\".\n    iApply (\"H\u03a6\" with \"[Hb]\").\n    destruct b; last done.\n    iDestruct \"Hb\" as %(Hb1 & Hb2 & Hb3).\n    iPureIntro.\n    split_and!; [lia|lia| |].\n    - destruct (lookup_lt_is_Some_2 w.(ge_time) w.(ge_orig))\n        as [wto Hwto]; first lia.\n      destruct (lookup_lt_is_Some_2 t w.(ge_orig))\n        as [two Htwo]; first lia.\n      rewrite Hwto Htwo in Hb2.\n      inversion Hb2 as [? ? ->|]; simplify_eq; simpl.\n      rewrite Htwo Hwto /=.\n      f_equal; lia.\n    - intros j Hj1 Hj2.\n      destruct (lookup_lt_is_Some_2 w.(ge_time) j) as [wj Hwj]; first lia.\n      destruct (lookup_lt_is_Some_2 t j) as [tj Htj]; first lia.\n      rewrite Htj Hwj /=.\n      assert (ge_orig w \u2260 j) as Hj2' by done.\n      specialize (Hb3 j wj tj Hj2' Hwj Htj).\n      eauto with lia.\n  Qed.\n\n  Definition internal_deliver_spec (deliver_fn : val) (i : nat) (z : socket_address) : iProp \u03a3 :=\n         \u231cRCB_addresses !! i = Some z\u231d -\u2217\n         <<< \u2200\u2200 (s : gset local_event), lhst_user \u03b3Ls i s >>>\n           deliver_fn #() @[ip_of_address z] \u2191RCB_InvName\n           <<<\u25b7 \u2203\u2203 s' vo, RET vo;\n                         lhst_user \u03b3Ls i s' \u2217\n                         ((\u231cs' = s\u231d \u2217 \u231cvo = NONEV\u231d) \u2228\n                          (\u2203 a ,\n                           \u231cs' = s \u222a {[ a ]}\u231d \u2217\n                           \u231ca \u2209 s\u231d \u2217\n                           \u231ca \u2208 compute_maximals le_time s'\u231d \u2217\n                           \u231cnot (a.(le_orig) = i)\u231d \u2217\n                           own_global_snap \u03b3Gsnap {[ erase a ]} \u2217\n                           \u2203 v, \u231cvo = SOMEV v\u231d \u2217 \u231cis_lev v a\u231d)) >>>.\n\n  Lemma internal_deliver_spec_holds\n        (i : nat) (z : socket_address) (T SeenLoc IQ OQ : loc) (lk : val)\n        (\u03b3lk : gname) :\n    {{{ Global_Inv \u03b3Gauth \u03b3Gsnap \u03b3Ls \u2217\n        local_invariant \u03b3Gsnap \u03b3Ls i T SeenLoc IQ OQ lk \u03b3lk z \u2217\n        \u231cip_of_address <$> RCB_addresses !! i = Some (ip_of_address z)\u231d }}}\n      deliver #T lk #IQ #i @[ip_of_address z]\n    {{{ (fv : val), RET fv;\n        internal_deliver_spec fv i z\n    }}}.\n  Proof.\n    rewrite /deliver /local_invariant.\n    remember (ip_of_address z) as ip.\n    iIntros (\u03a6) \"(#Ginv & #Linv & %Hip) H\u03a6\".\n    wp_pures.\n    iApply \"H\u03a6\"; clear \u03a6.\n    iIntros \"#Haddr\". iIntros \"!>\" (\u03a6) \"Hvs\".\n    wp_pures.\n    rewrite Heqip.\n    wp_apply acquire_spec; first iExact \"Linv\".\n    iIntros (?) \"(-> & Hlk & Hli)\".\n    rewrite /local_inv_def.\n    iDestruct \"Hli\" as (vt vseen viq voq t seenv liq loq s' ip')\n     \"(%Hip'& HT & %Hvc & Hseen & %Hseen_vc & %Hseen_len & HIQ & HOQ & Hlhst & %Hlstv)\".\n    assert (ip = ip') as ->.\n    { rewrite Hip in Hip'. inversion Hip'; done. }\n    clear Hip'.\n    subst.\n    iDestruct \"HIQ\" as \"(HIQ & %Hviq & Hliq)\".\n    wp_pures.\n    wp_load.\n    wp_load.\n    wp_apply wp_is_causally_next.\n    { iSplit; first done.\n      rewrite (RCBM_LSTV_time_length Hlstv); done. }\n    iIntros (f) \"#Hf /=\".\n    wp_apply (wp_find_remove); [|done|].\n    { iIntros (? ? _) \"!> H\u03a6\".\n      iApply \"Hf\"; first done.\n      iNext. iIntros (b) \"Hb\".\n      iApply \"H\u03a6\".\n      destruct b; first iExact \"Hb\"; done. }\n    iIntros (v) \"[->|Hv]\".\n    { wp_pures.\n      wp_apply (release_spec with \"[$Hlk HT Hseen HOQ HIQ Hliq Hlhst]\").\n      { eauto 20 with iFrame. }\n      iIntros (v ->).\n      wp_bind (Rec _ _ _).\n      iApply (aneris_wp_atomic _ _ (\u2191RCB_InvName)).\n      iMod \"Hvs\". iModIntro.\n      wp_pure _.\n      iDestruct \"Hvs\" as (x) \"[Hu Hupd]\".\n      iMod (\"Hupd\" with \"[$Hu]\") as \"H\u03a6\".\n      { iLeft. eauto. }\n      iModIntro. wp_pures.\n      iApply \"H\u03a6\". }\n    iDestruct \"Hv\" as (a lv' l1 l2) \"((->&->&%Hlv')&%Honi&%Hwtlen&%Hwtoa&%Hwtnoa)\".\n    wp_pures.\n    wp_store.\n    wp_load.\n    assert (a.(ge_orig) < length t).\n    { apply lookup_lt_Some in Hwtoa; lia. }\n    destruct (lookup_lt_is_Some_2 t a.(ge_orig)); first done.\n    wp_apply wp_vect_inc; [|done|done|]; first lia.\n    iIntros (vt' Hvt'); simpl.\n    wp_store.\n    iDestruct \"Hliq\" as \"(Hliq1 & (%Hne & #Ha) & Hliq2)\".\n    iCombine \"Hliq1\" \"Hliq2\" as \"Hliq\".\n    rewrite -big_sepL_app.\n    set (e := LocalEvent a.(ge_payload)\n                         a.(ge_time)\n                         a.(ge_orig)\n                             (S (length (elements s')))).\n    assert (a = erase e) as Herase.\n    { destruct a; done. }\n    pose proof (RCBM_LSTV_at Hlstv).\n    pose proof (RCBM_LSTV_time_length Hlstv) as Htlen;\n      rewrite /= /RCBM_lst_time_length in Htlen.\n    assert (e \u2209 s') as Hes'.\n    { apply (RCBM_system_local_event_fresh_lhst e i t); eauto with lia. }\n    wp_bind (InjR _).\n    do 2 wp_pure _.\n    iApply (aneris_wp_atomic _ _ (\u2191RCB_InvName)).\n    iMod \"Hvs\". iModIntro. wp_pures.\n    iDestruct \"Hvs\" as (s) \"[Hu Himpl]\".\n    iDestruct (lhst_user_lock_agree with \"Hu Hlhst\") as %->.\n    iInv RCB_InvName as\n        (G Ss) \"(>% & >Hgsys & >Hl & >%Hvl)\" \"Hclos_inv\".\n    iDestruct (own_global_snap_lookup with \"Hgsys Ha\") as \"%Hina\".\n    iDestruct (lhst_user_lookup with \"Hl Hu\") as %His'.\n    iDestruct (lhst_lock_lookup with \"Hl Hlhst\") as %His''.\n    assert (e \u2208 compute_maximals le_time (s' \u222a {[ e ]})) as Hemax.\n    { remember {| Lst_time := t; Lst_hst := s' |} as lst.\n      replace s' with lst.(Lst_hst); [ | by rewrite Heqlst ].\n      eapply RCBM_Lst_valid_compute_maximals; [done |].\n      rewrite /e; simpl.\n      replace (Lst_time lst) with t; [eauto | ].\n      rewrite Heqlst; done. }\n    assert (RCBM_Lst_valid i\n                 {| Lst_time := incr_time t (ge_orig a);\n                    Lst_hst := s' \u222a {[e]} |}).\n    { apply (RCBM_lst_update_apply i {| Lst_time := t; Lst_hst := s' |} (erase e));\n        rewrite /e; [done | done |].\n      split_and!; simpl; auto with lia. }\n    assert (RCBM_Gst_valid {| Gst_ghst := G; Gst_hst := <[i := s' \u222a {[e]} ]>Ss |}).\n    { rewrite /e.\n      apply (RCBM_system_apply_update_gst\n               i {| Gst_ghst := G |} {| Lst_time := t; Lst_hst := s' |} a );\n        simpl; eauto with set_solver.\n      split_and!; simpl; eauto with lia. }\n    iMod (lhst_update _ _ _ _ e with \"Hu Hlhst Hl\") as \"(Hu & Hlhst & Hl)\".\n    iMod (\"Hclos_inv\" with \"[Hgsys Hl]\") as \"_\".\n    { eauto 15 with iFrame. }\n    rewrite Herase.\n    iMod (\"Himpl\" with \"[$Hu]\") as \"H\u03a6\".\n    { iRight. iExists e.\n      iFrame \"#\".\n      repeat iSplit; eauto.\n      iExists $(erase e).\n      iSplit; eauto.\n      iPureIntro.\n      simpl.\n      eexists _, _, _.\n      eauto using vector_clock_to_val_is_vc. }\n    iModIntro. wp_pures.\n    wp_apply (release_spec with \"[$Hlk HT Hseen HOQ HIQ Hliq Hlhst]\").\n    { iFrame \"Linv\".\n      iExists _, _, _, _, _, _, _, _.\n      iExists _, _.\n      iSplitL \"\"; [by iPureIntro |].\n      iSplitL \"HT\"; [iFrame |].\n      iSplitL \"\"; [by iPureIntro|].\n      iFrame; iFrame \"#\".\n      repeat iSplit; eauto.\n      iPureIntro.\n      rewrite Hseen_len.\n      symmetry.\n      apply incr_time_length. }\n    iIntros (? ->).\n    wp_seq.\n    iApply \"H\u03a6\".\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/examples/rcb/proof/proof_of_deliver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15213360516601526}}
{"text": "Require Import UNIVERSE.\n(* Require Import Events. *)\n(* Require Import ValuesC. *)\n(* Require Import AST. *)\n(* Require Import Memory. *)\n(* Require Import Globalenvs. *)\nRequire Import Smallstep.\nRequire Import CoqlibC.\n(* Require Import Skeleton. *)\n(* Require Import Integers. *)\n(* Require Import ASTC. *)\nRequire Import LinkingC.\n(* Require Import Maps. *)\n\nRequire Import SimMem.\nRequire Import System.\nRequire Import ModSem.\n\nSet Implicit Arguments.\n\n\nModule SimSymb.\n\n  Inductive sim_skenv_weak (sim_val: val -> val -> Prop) (skenv_src skenv_tgt: SkEnv.t): Prop :=\n  | sim_skenv_weak_intro\n      (FUNCFSIM: forall fptr_src fptr_tgt def_src\n          (SIMFPTR: sim_val fptr_src fptr_tgt)\n          (FUNCSRC: (Genv.find_funct skenv_src) fptr_src = Some def_src),\n          exists def_tgt, <<FUNCSRC: (Genv.find_funct skenv_tgt) fptr_tgt = Some def_tgt>> /\\ <<SIM: def_src = def_tgt>>)\n      (* (FUNCBSIM: forall fptr_src fptr_tgt def_tgt *)\n      (*     (SIMFPTR: sim_val fptr_src fptr_tgt) *)\n      (*     (FUNCTGT: (Genv.find_funct skenv_tgt) fptr_tgt = Some def_tgt) *)\n      (*     (SAFESRC: fptr_src <> Vundef) *)\n      (*   , *)\n      (*     exists def_src, (<<FUNCSRC: (Genv.find_funct skenv_src) fptr_src = Some def_src>>) /\\ (<<SIM: def_src = def_tgt>>)) *)\n  .\n\n  Class class (SM: SimMem.class) :=\n    { t: Type;\n      le: t -> t -> Prop;\n      src: t -> Sk.t;\n      tgt: t -> Sk.t;\n\n      le_PreOrder :> PreOrder le;\n\n      wf: t -> Prop;\n      wf_preserves_wf: forall ss0\n          (SIMSK: wf ss0)\n          (WFSRC: Sk.wf ss0.(src)),\n          <<WFTGT: Sk.wf ss0.(tgt)>>;\n\n      wf_link: forall ss0 ss1 sk_src\n          (SIMSK: wf ss0)\n          (SIMSK: wf ss1)\n          (LINKSRC: link ss0.(src) ss1.(src) = Some sk_src)\n          (WFSRC0: Sk.wf ss0.(src))\n          (WFSRC1: Sk.wf ss1.(src))\n          (WFTGT0: Sk.wf ss0.(tgt))\n          (WFTGT1: Sk.wf ss1.(tgt)),\n          exists ss sk_tgt,\n            <<LINKTGT: link ss0.(tgt) ss1.(tgt) = Some sk_tgt>> /\\\n            <<SKSRC: ss.(src) = sk_src>> /\\\n            <<SKTGT: ss.(tgt) = sk_tgt>> /\\\n            <<LE0: le ss0 ss>> /\\\n            <<LE1: le ss1 ss>> /\\\n            <<SIMSK: wf ss>>;\n\n      sim_skenv: SimMem.t -> t -> SkEnv.t -> SkEnv.t -> Prop;\n\n      sim_skenv_public_symbols: forall sm0 ss0 skenv_src skenv_tgt\n          (SIMSKE: sim_skenv sm0 ss0 skenv_src skenv_tgt),\n          (Genv.public_symbol skenv_src) = (Genv.public_symbol skenv_tgt);\n\n      wf_load_sim_skenv: forall ss skenv_src skenv_tgt m_src\n          (SIMSK: wf ss)\n          (LOADSRC: (Sk.load_skenv ss.(src)) = skenv_src)\n          (LOADTGT: (Sk.load_skenv ss.(tgt)) = skenv_tgt)\n          (LOADMEMSRC: (Sk.load_mem ss.(src)) = Some m_src),\n          exists m_tgt sm,\n            (<<LOADMEMTGT: (Sk.load_mem ss.(tgt)) = Some m_tgt>>) /\\\n            (<<SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt>>) /\\\n            (<<MEMSRC: sm.(SimMem.src) = m_src>>) /\\\n            (<<MEMTGT: sm.(SimMem.tgt) = m_tgt>>) /\\\n            (<<MWF: sm.(SimMem.wf)>>) /\\\n            (<<MAINSIM: SimMem.sim_val sm (Genv.symbol_address skenv_src (prog_main ss.(src)))\n                                       (Genv.symbol_address skenv_tgt (prog_main ss.(tgt)))>>);\n\n      mlepriv_preserves_sim_skenv: forall sm0 sm1 ss skenv_src skenv_tgt\n          (MLE: SimMem.lepriv sm0 sm1)\n          (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt),\n          <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>;\n\n      sim_skenv_monotone: forall\n          sm ss_link skenv_link_src skenv_link_tgt\n          ss skenv_src skenv_tgt\n          (WFSRC: SkEnv.wf skenv_link_src)\n          (WFTGT: SkEnv.wf skenv_link_tgt)\n          (SIMSKENV: sim_skenv sm ss_link skenv_link_src skenv_link_tgt)\n          (SIMSK: wf ss)\n          (LE: le ss ss_link)\n          (INCLSRC: SkEnv.includes skenv_link_src ss.(src))\n          (INCLTGT: SkEnv.includes skenv_link_tgt ss.(tgt))\n          (LESRC: SkEnv.project skenv_link_src ss.(src) = skenv_src)\n          (LETGT: SkEnv.project skenv_link_tgt ss.(tgt) = skenv_tgt),\n          <<SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt>>;\n\n      sim_skenv_sim_skenv_weak: forall sm ss,\n              sim_skenv sm ss <2= sim_skenv_weak sm.(SimMem.sim_val);\n\n      system_sim_skenv: forall sm ss skenv_src skenv_tgt\n          (SIMSKENV: sim_skenv sm ss skenv_src skenv_tgt),\n          <<SIMSKENV: sim_skenv sm ss (System.skenv skenv_src) (System.skenv skenv_tgt)>>;\n      system_axiom: forall\n          sm0 ss_sys skenv_sys_src skenv_sys_tgt\n          args_src args_tgt tr retv_src ef\n          (SIMSKENV: sim_skenv sm0 ss_sys skenv_sys_src skenv_sys_tgt)\n          (MWF: SimMem.wf sm0)\n          (CSTYLE: Args.is_cstyle args_src)\n          (CSTYLE: Retv.is_cstyle retv_src)\n          (ARGS: SimMem.sim_args args_src args_tgt sm0)\n          (SYSSRC: external_call ef skenv_sys_src (Args.vs (args_src)) (Args.m (args_src))\n                                 tr\n                                 (Retv.v (retv_src)) (Retv.m (retv_src))),\n          exists sm1 retv_tgt,\n            (<<SYSTGT: external_call ef skenv_sys_tgt (Args.vs (args_tgt)) (Args.m (args_tgt))\n                                     tr\n                                     (Retv.v (retv_tgt)) (Retv.m (retv_tgt))>>)\n            /\\ (<<RETV: SimMem.sim_retv retv_src retv_tgt sm1>>)\n            /\\ (<<MLE0: SimMem.le sm0 sm1>>)\n            /\\ (<<MWF: SimMem.wf sm1>>);\n    }.\n\n  Lemma mle_preserves_sim_skenv: forall\n      `{SM: SimMem.class} `{SS: @class SM}\n      sm0 sm1 ss skenv_src skenv_tgt\n      (MLE: SimMem.le sm0 sm1)\n      (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt),\n      <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>.\n  Proof. ii. eapply mlepriv_preserves_sim_skenv; et. Qed.\n\n  Lemma mfuture_preserves_sim_skenv\n        `{SM: SimMem.class} `{SS: @class SM}\n        sm0 sm1 ss skenv_src skenv_tgt\n        (MFUTURE: SimMem.future sm0 sm1)\n        (SIMSKENV: sim_skenv sm0 ss skenv_src skenv_tgt):\n      <<SIMSKENV: sim_skenv sm1 ss skenv_src skenv_tgt>>.\n  Proof.\n    induction MFUTURE; ss. des.\n    - eapply IHMFUTURE; eauto. eapply mlepriv_preserves_sim_skenv; eauto.\n    - eapply IHMFUTURE; eauto. eapply mle_preserves_sim_skenv; eauto.\n  Qed.\n\nEnd SimSymb.\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/SimSymb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.15187864999775505}}
{"text": "Require Import Ascii Bool String List.\nRequire Import Lib.CommonTactics Lib.Indexer Lib.ilist Lib.Word Lib.Struct.\nRequire Import Kami.Syntax Kami.Notations.\nRequire Import Kami.Semantics Kami.Specialize Kami.Duplicate.\nRequire Import Kami.Inline Kami.InlineFacts.\nRequire Import Kami.Wf Kami.Tactics.\nRequire Import Ex.MemTypes Ex.SC.\n\nSet Implicit Arguments.\n\nSection Inlined.\n  Variables (addrSize maddrSize iaddrSize fifoSize instBytes dataBytes rfIdx: nat)\n            (Hdb: {pdb & dataBytes = S pdb}).\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx)\n            (ammio: AbsMMIO addrSize).\n\n  Variable (procInit: ProcInit addrSize dataBytes rfIdx)\n           (memInit: MemInit maddrSize).\n  \n  Definition scmm: Modules := scmm Hdb fetch dec exec ammio procInit memInit.\n  #[local] Hint Unfold scmm: ModuleDefs. (* for kinline_compute *)\n\n  Definition scmmInl: sigT (fun m: Modules => scmm <<== m).\n  Proof.\n    kinline_refine scmm.\n  Defined.\n\nEnd Inlined.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/SCMMInl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.281405613455665, "lm_q1q2_score": 0.15167290385992782}}
{"text": "From cap_machine.binary_model.ftlr_binary Require Export Mov_binary Jmp_binary Jnz_binary Load_binary Store_binary AddSubLt_binary Lea_binary Restrict_binary Subseg_binary IsPtr_binary Get_binary StoreU_binary LoadU_binary PromoteU_binary.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine.binary_model Require Export logrel_binary region_invariants_binary.\n\nSection fundamental.\n  Context {\u03a3:gFunctors} {memg:memG \u03a3} {regg:regG \u03a3}\n          {stsg : STSG Addr region_type \u03a3} {heapg : heapG \u03a3}\n          {nainv: logrel_na_invs \u03a3} {cfgg : cfgSG \u03a3}\n          `{MP: MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n  Notation WORLD := (prodO STS_STD STS).\n  Implicit Types W : WORLD.\n\n  Notation D := (WORLD -n> (prodO (leibnizO Word) (leibnizO Word)) -n> iPropO \u03a3).\n  Notation R := (WORLD -n> (prodO (leibnizO Reg) (leibnizO Reg)) -n> iPropO \u03a3).\n  Implicit Types v : (prodO (leibnizO Word) (leibnizO Word)).\n  Implicit Types interp : (D).\n\n  Lemma extract_r_ex r (reg : RegName) :\n    (\u2203 w, r !! reg = Some w) \u2192\n    \u22a2 (([\u2217 map] r0\u21a6w \u2208 r, r0 \u21a6\u1d63 w) \u2192 \u2203 w, reg \u21a6\u1d63 w).\n  Proof.\n    intros [w Hw].\n    iIntros \"Hmap\". iExists w.\n    iApply (big_sepM_lookup (\u03bb reg' i, reg' \u21a6\u1d63 i)%I r reg w); eauto.\n  Qed.\n\n  Lemma extract_r_ex_spec r (reg : RegName) :\n    (\u2203 w, r !! reg = Some w) \u2192\n    \u22a2 (([\u2217 map] r0\u21a6w \u2208 r, r0 \u21a3\u1d63 w) \u2192 \u2203 w, reg \u21a3\u1d63 w).\n  Proof.\n    intros [w Hw].\n    iIntros \"Hmap\". iExists w.\n    iApply (big_sepM_lookup (\u03bb reg' i, reg' \u21a3\u1d63 i)%I r reg w); eauto.\n  Qed.\n\n  Lemma extract_r reg (r : RegName) w :\n    reg !! r = Some w \u2192\n    \u22a2 (([\u2217 map] r0\u21a6w \u2208 reg, r0 \u21a6\u1d63 w) \u2192\n      (r \u21a6\u1d63 w \u2217 (\u2200 x', r \u21a6\u1d63 x' -\u2217 [\u2217 map] k\u21a6y \u2208 <[r := x']> reg, k \u21a6\u1d63 y))).\n  Proof.\n    iIntros (Hw) \"Hmap\".\n    iDestruct (big_sepM_lookup_acc (\u03bb (r : RegName) i, r \u21a6\u1d63 i)%I reg r w) as \"Hr\"; eauto.\n    iSpecialize (\"Hr\" with \"[Hmap]\"); eauto. iDestruct \"Hr\" as \"[Hw Hmap]\".\n    iDestruct (big_sepM_insert_acc (\u03bb (r : RegName) i, r \u21a6\u1d63 i)%I reg r w) as \"Hupdate\"; eauto.\n    iSpecialize (\"Hmap\" with \"[Hw]\"); eauto.\n    iSpecialize (\"Hupdate\" with \"[Hmap]\"); eauto.\n  Qed.\n\n  Lemma extract_r_spec reg (r : RegName) w :\n    reg !! r = Some w \u2192\n    \u22a2 (([\u2217 map] r0\u21a6w \u2208 reg, r0 \u21a3\u1d63 w) \u2192\n      (r \u21a3\u1d63 w \u2217 (\u2200 x', r \u21a3\u1d63 x' -\u2217 [\u2217 map] k\u21a6y \u2208 <[r := x']> reg, k \u21a3\u1d63 y))).\n  Proof.\n    iIntros (Hw) \"Hmap\".\n    iDestruct (big_sepM_lookup_acc (\u03bb (r : RegName) i, r \u21a3\u1d63 i)%I reg r w) as \"Hr\"; eauto.\n    iSpecialize (\"Hr\" with \"[Hmap]\"); eauto. iDestruct \"Hr\" as \"[Hw Hmap]\".\n    iDestruct (big_sepM_insert_acc (\u03bb (r : RegName) i, r \u21a3\u1d63 i)%I reg r w) as \"Hupdate\"; eauto.\n    iSpecialize (\"Hmap\" with \"[Hw]\"); eauto.\n    iSpecialize (\"Hupdate\" with \"[Hmap]\"); eauto.\n  Qed.\n\n  Instance addr_inhabited: Inhabited Addr := populate (A 0%Z eq_refl eq_refl).\n\n  Global Instance ifcond_pers : Persistent (if writeAllowed p then read_write_cond a interp else \u2203 P : D, \u231c\u2200 Wv : WORLD * (prodO (leibnizO Word) (leibnizO Word)), Persistent (P Wv.1 Wv.2)\u231d \u2227 read_cond a P interp)%I.\n  Proof. intros. destruct (writeAllowed p);apply _. Qed.\n  Global Instance ifwcond_pers : Persistent (if decide (writeAllowed_in_r_a (<[PC:=inr (p, g, b, e, a)]> r) a) then wcond P interp else emp)%I.\n  Proof. intros. case_decide;apply _. Qed.\n  Global Instance if_pers (P: D) : Persistent (if decide (\u03c1 = Monotemporary)\n                                               then future_pub_a_mono a (\u03bb Wv, P Wv.1 Wv.2) w1 w2\n                                               else future_priv_mono (\u03bb Wv, P Wv.1 Wv.2) w1 w2).\n  Proof. intros. case_decide;apply _. Qed.\n\n  Theorem fundamental_binary W r p g b e (a : Addr) :\n    \u22a2 ((\u231cp = RX\u231d \u2228 \u231cp = RWX\u231d \u2228 \u231cp = RWLX \u2227 g = Directed\u231d) \u2192\n       spec_ctx \u2192\n       region_conditions W p g b e \u2192\n       interp_expression r W (inr ((p,g),b,e,a),inr ((p,g),b,e,a))).\n  Proof.\n    iIntros (Hp) \"#Hspec #Hinv /=\".\n    iIntros \"[Hregs [Hmreg [Hsreg [Hr [Hsts [Hown Hj]]]]]]\".\n    iSplit; eauto; simpl.\n    iRevert (Hp) \"Hinv\".\n    iL\u00f6b as \"IH\" forall (W r p g b e a).\n    iAssert (\u231c\u2200 w, <[PC:=w]> r.1 = <[PC:=w]> r.2\u231d)%I as %Heqregs.\n    { iIntros (w). iDestruct (interp_reg_eq _ _ _ w with \"Hregs\") as %Heqregs. auto. }\n    iDestruct \"Hregs\" as \"[Hfull Hreg]\".\n    iIntros (Hp) \"#Hinv\".\n    rewrite -Heqregs.\n    iDestruct \"Hfull\" as \"%\". iDestruct \"Hreg\" as \"#Hreg\".\n    iApply (wp_bind (fill [SeqCtx])).\n    destruct (decide (isCorrectPC (inr ((p,g),b,e,a)))).\n    - (* Correct PC *)\n      assert ((b <= a)%a \u2227 (a < e)%a) as Hbae.\n      { eapply in_range_is_correctPC; eauto.\n        unfold le_addr; lia. }\n      iDestruct (extract_from_region_inv_regs a a with \"[Hmreg] Hinv\") as (P Hpers) \"(#Hinva & #Hrcond & #Hwcond)\";auto;[|iFrame \"# %\"|].\n      { destruct Hp as [-> | [-> | [? ->] ] ];auto. subst;auto. }\n      iDestruct (extract_from_region_inv _ _ a with \"Hinv\") as \"[_ Hstate_a]\";auto.\n      iDestruct \"Hstate_a\" as %Hstate_a.\n      assert (\u2203 (\u03c1 : region_type), (std W) !! a = Some \u03c1 \u2227 \u03c1 \u2260 Revoked\n                                   \u2227 (\u2200 g, \u03c1 \u2260 Monostatic g) \u2227 (\u2200 w, \u03c1 \u2260 Uninitialized w))\n        as [\u03c1 [H\u03c1 [Hne_rev [Hne_mono Hne_uninit] ] ] ].\n      { destruct (machine_base.pwl p); [rewrite Hstate_a;eexists;eauto|].\n        destruct g; [rewrite Hstate_a|rewrite Hstate_a|destruct Hstate_a as [-> | ->] ];eexists;eauto. }\n      iDestruct (region_open W a with \"[$Hinva $Hr $Hsts]\")\n        as (w1 w2) \"(Hr & Hsts & Hstate & Ha & Ha' & #Hmono & Hw) /=\";[|apply H\u03c1|..].\n      { destruct \u03c1;auto;[done|by specialize (Hne_mono g0)|by specialize (Hne_uninit p0)]. }\n      iDestruct ((big_sepM_delete _ _ PC) with \"Hmreg\") as \"[HPC Hmap]\";\n        first apply (lookup_insert _ _ (inr (p, g, b, e, a))).\n      iDestruct ((big_sepM_delete _ _ PC) with \"Hsreg\") as \"[HsPC Hsmap]\";\n        first apply (lookup_insert _ _ (inr (p, g, b, e, a))).\n      iAssert (\u25b7 \u231cw1 = w2\u231d)%I as \"#>Heq\".\n      { iNext. iApply (interp_eq W). iDestruct \"Hrcond\" as \"[Hrcond _]\". iApply \"Hrcond\". iFrame. }\n      iDestruct \"Heq\" as %<-.\n      destruct (decodeInstrW w1) eqn:Hi. (* proof by cases on each instruction *)\n      + (* Jmp *)\n        iApply (jmp_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Jnz *)\n        iApply (jnz_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Mov *)\n        iApply (mov_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Load *)\n        iApply (load_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Store *)\n        iApply (store_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Lt *)\n        iApply (add_sub_lt_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Add *)\n        iApply (add_sub_lt_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Sub *)\n        iApply (add_sub_lt_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Lea *)\n        iApply (lea_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Restrict *)\n        iApply (restrict_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Subseg *)\n        iApply (subseg_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* IsPtr *)\n        iApply (isptr_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* GetL *)\n        iApply (get_case _ _ _ _ _ _ _ _ _ _ _ (GetL _ _) with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* GetP *)\n        iApply (get_case _ _ _ _ _ _ _ _ _ _ _ (GetP _ _) with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* GetB *)\n        iApply (get_case _ _ _ _ _ _ _ _ _ _ _ (GetB _ _) with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* GetE *)\n        iApply (get_case _ _ _ _ _ _ _ _ _ _ _ (GetE _ _) with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* GetA *)\n        iApply (get_case _ _ _ _ _ _ _ _ _ _ _ (GetA _ _) with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\");\n          try iAssumption; eauto.\n      + (* Fail *)\n        iApply (wp_fail with \"[HPC Ha]\"); eauto; iFrame.\n        iNext. iIntros \"[HPC Ha] /=\".\n        iApply wp_pure_step_later; auto.\n        iApply wp_value.\n        iNext. iIntros (Hcontr); inversion Hcontr.\n      + (* Halt *)\n        iApply (wp_halt with \"[HPC Ha]\"); eauto; iFrame.\n        iNext. iIntros \"[HPC Ha] /=\".\n        iMod (step_halt _ [SeqCtx] with \"[$HsPC $Ha' $Hj $Hspec]\") as \"(Hj & HsPC & Ha')\";eauto.\n        iMod (do_step_pure _ [] with \"[$Hspec $Hj]\") as \"Hj /=\";auto.\n        iDestruct (region_close _ _ _ _ _ \u03c1 with \"[$Hr $Ha $Ha' $Hstate $Hmono Hw]\") as \"Hr\";[auto|iFrame \"#\"; auto|].\n        { destruct \u03c1;auto;[|specialize (Hne_mono g0)|specialize (Hne_uninit p0)]; contradiction. }\n        iApply wp_pure_step_later; auto.\n        iApply wp_value.\n        iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\".\n        apply lookup_insert. rewrite delete_insert_delete. iFrame.\n        iDestruct ((big_sepM_delete _ _ PC) with \"[HsPC Hsmap]\") as \"Hsmap /=\".\n        apply lookup_insert. rewrite delete_insert_delete. iFrame.\n        rewrite insert_insert. iNext. iIntros (_).\n        iExists (<[PC:=inr (p, g, b, e, a)]> r.1,<[PC:=inr (p, g, b, e, a)]> r.1),W. iFrame.\n        iAssert (\u231crelated_sts_priv_world W W\u231d)%I as \"#Hrefl\".\n        { iPureIntro. apply related_sts_priv_refl_world. }\n        iFrame \"#\".\n        iPureIntro. intros r0. destruct (reg_eq_dec PC r0).\n        * subst r0; rewrite lookup_insert; eauto.\n        * rewrite lookup_insert_ne//. destruct H with r0;eauto.\n      + (* LoadU *)\n      iApply (loadU_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\"); try iAssumption; eauto.\n      + (* StoreU *)\n        iApply (storeU_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\"); try iAssumption; eauto.\n      + (* PromoteU *)\n        iApply (promoteU_case with \"[] [] [] [] [] [Hmono] [] [] [Hw] [Hsts] [Hown] [Hr] [Hstate] [Ha] [Ha'] [HPC] [Hmap] [HsPC] [Hsmap] [Hj]\"); try iAssumption; eauto.\n   - (* Not correct PC *)\n     iDestruct ((big_sepM_delete _ _ PC) with \"Hmreg\") as \"[HPC Hmap]\";\n       first apply (lookup_insert _ _ (inr (p, g, b, e, a))).\n     iApply (wp_notCorrectPC with \"HPC\"); eauto.\n     iNext. iIntros \"HPC /=\".\n     iApply wp_pure_step_later; auto.\n     iApply wp_value.\n     iNext. iIntros (Hcontr); inversion Hcontr.\n     Unshelve. apply _.\n  Qed.\n\n  (* the execute condition can be regained using the FTLR on read allowed permissions *)\n  Lemma interp_exec_cond_binary W p g b e a :\n    p = RX \u2228 p = RWX \u2228 p = RWLX ->\n    spec_ctx -\u2217\n    interp W (inr (p,g,b,e,a),inr (p,g,b,e,a)) -\u2217 exec_cond W b e g p b e g p interp.\n  Proof.\n    iIntros (Hra) \"#Hspec #Hw\".\n    iIntros (a0 r W' Hin) \"#Hfuture\". iModIntro.\n    destruct g.\n    + iDestruct (interp_monotone_nm with \"Hfuture [] Hw\") as \"Hw'\";[auto|].\n      iDestruct (readAllowed_implies_region_conditions with \"Hw'\") as \"Hread_cond\";[destruct Hra as [-> | [-> | ->] ];auto|].\n      iApply fundamental_binary;[|iFrame \"#\"|eauto]. destruct Hra as [-> | [-> | ->] ];auto.\n      rewrite fixpoint_interp1_eq /=. done.\n    + iDestruct (interp_monotone_nm with \"Hfuture [] Hw\") as \"Hw'\";[auto|].\n      iDestruct (readAllowed_implies_region_conditions with \"Hw'\") as \"Hread_cond\";[destruct Hra as [-> | [-> | ->] ];auto|].\n      iApply fundamental_binary;[|iFrame \"#\"|eauto]. destruct Hra as [-> | [-> | ->] ];auto.\n      rewrite fixpoint_interp1_eq /=. done.\n    + iDestruct (interp_monotone_a with \"[Hfuture] Hw\") as \"Hw'\";[auto|].\n      2: iDestruct (readAllowed_implies_region_conditions with \"Hw'\") as \"Hread_cond\";[destruct Hra as [-> | [-> | ->] ];auto|].\n      2: iApply fundamental_binary;[|iFrame \"#\"|eauto];destruct Hra as [-> | [-> | ->] ];auto.\n      simpl. destruct Hra as [-> | [-> | ->] ];auto.\n  Qed.\n\n  Lemma fundamental_binary_from_interp_correctPC W p g b e a r (w:Word) :\n    p = RX \u2228 p = RWX \u2228 (p = RWLX \u2227 g = Directed) \u2192\n    \u22a2 spec_ctx -\u2217 interp W (inr (p, g, b, e, a),w) -\u2217\n      interp_expression r W (inr (p,g,b,e,a),w).\n  Proof.\n    iIntros (Hp) \"HV Hv\". iDestruct (interp_eq with \"Hv\") as %<-.\n    iApply (fundamental_binary with \"[] HV\"); auto.\n    iApply (readAllowed_implies_region_conditions with \"Hv\").\n    destruct Hp as [-> | [-> | [ -> -> ] ] ]; eauto.\n  Qed.\n\n  Lemma fundamental_binary_not_correctPC r W p g b e a :\n    \u22a2 \u231c\u00ac isCorrectPC (inr ((p,g),b,e,a))\u231d \u2192\n    interp_expression r W (inr ((p,g),b,e,a),inr ((p,g),b,e,a)).\n  Proof.\n    iIntros (Hnvpc). iIntros \"(H1 & Hmreg & H3 & H4 & H5)\".\n    iSplit;auto. rewrite /interp_conf.\n    iDestruct ((big_sepM_delete _ _ PC) with \"Hmreg\") as \"[HPC Hmap]\";\n      first apply (lookup_insert _ _ (inr (p, g, b, e, a))).\n    iApply (wp_bind (fill [SeqCtx])).\n    iApply (wp_notCorrectPC with \"HPC\"); eauto.\n    iNext. iIntros \"HPC /=\".\n    iApply wp_pure_step_later; auto.\n    iApply wp_value.\n    iNext. iIntros (Hcontr); inversion Hcontr.\n  Qed.\n\n  Corollary fundamental_binary_from_interp r W p g b e a (w : Word) :\n    spec_ctx -\u2217\n    interp W (inr ((p,g),b,e,a),w) -\u2217\n    interp_expression r W (inr ((p,g),b,e,a),w).\n  Proof.\n    iIntros \"#Hspec #Hinterp\".\n    iDestruct (interp_eq with \"Hinterp\") as %<-.\n    destruct (decide (isCorrectPC (inr ((p,g),b,e,a)))).\n    - assert (p = RX \u2228 p = RWX \u2228 p = RWLX) as Hp;[inversion i;auto|].\n      iAssert (\u231cp = RWLX \u2192 g = Directed\u231d)%I as %Hmono.\n      { iIntros (->). iDestruct (writeLocalAllowed_implies_local with \"Hinterp\") as %Hmono;[auto|destruct g;auto]. }\n      iApply (fundamental_binary_from_interp_correctPC with \"Hspec Hinterp\").\n      destruct Hp as [-> | [-> | ->] ];auto.\n    - iApply fundamental_binary_not_correctPC. auto.\n  Qed.\n\n  Lemma updatePcPerm_RX w g b e a :\n    inr (RX, g, b, e, a) = updatePcPerm w ->\n    w = inr (RX, g, b, e, a) \u2228 w = inr (E, g, b, e, a).\n  Proof.\n    intros Hperm.\n    destruct w;inversion Hperm.\n    destruct c,p,p,p,p;simplify_eq;auto.\n  Qed.\n\n  Lemma exec_binary_wp W p g b e a :\n    isCorrectPC (inr (p, g, b, e, a)) ->\n    exec_cond W b e g p b e g p interp -\u2217\n    \u2200 r W', future_world g e W W' \u2192 \u25b7 ((interp_expr interp r) W') (inr (p, g, b, e, a),inr (p, g, b, e, a)).\n  Proof.\n    iIntros (Hvpc) \"Hexec\".\n    rewrite /exec_cond /enter_cond.\n    iIntros (r W'). rewrite /future_world.\n    assert (a \u2208\u2090[[b,e]])%I as Hin.\n    { rewrite /in_range. inversion Hvpc; subst. auto. }\n    destruct g.\n    - iIntros (Hrelated).\n      iSpecialize (\"Hexec\" $! a r W' Hin Hrelated).\n      iFrame.\n    - iIntros (Hrelated).\n      iSpecialize (\"Hexec\" $! a r W' Hin Hrelated).\n      iFrame.\n    - iIntros (Hrelated).\n      iSpecialize (\"Hexec\" $! a r W' Hin Hrelated).\n      iFrame.\n  Qed.\n\n  (* The following lemma is to assist with a pattern when jumping to unknown valid capablities *)\n  Lemma jmp_or_fail_binary_spec W (w w' : Word) \u03c6 :\n    spec_ctx\n    -\u2217 (interp W (w,w')\n    -\u2217 (if decide (isCorrectPC (updatePcPerm w)) then\n          (\u2203 p g b e a, \u231cw = inr (p,g,b,e,a)\u231d\n          \u2217 \u25a1 \u2200 r W', future_world g e W W' \u2192 \u25b7 ((interp_expr interp r) W') (updatePcPerm w,updatePcPerm w'))\n        else\n          \u03c6 FailedV \u2217 PC \u21a6\u1d63 updatePcPerm w -\u2217 WP Seq (Instr Executable) {{ \u03c6 }} )).\n  Proof.\n    iIntros \"#Hspec #Hw\".\n    iDestruct (interp_eq with \"Hw\") as %<-.\n    destruct (decide (isCorrectPC (updatePcPerm w))).\n    - inversion i.\n      destruct w;inversion H. destruct c,p0,p0,p0; inversion H.\n      destruct H1 as [-> | [-> | ->] ].\n      + destruct p0; simpl in H; simplify_eq.\n        * iExists _,_,_,_,_; iSplit;[eauto|]. iModIntro.\n          iDestruct (interp_exec_cond_binary with \"Hspec Hw\") as \"Hexec\";[auto|].\n          iApply exec_binary_wp;auto.\n        * iExists _,_,_,_,_; iSplit;[eauto|]. iModIntro.\n          rewrite /= fixpoint_interp1_eq /=.\n          iDestruct \"Hw\" as \"[_ Hw]\".\n          iExact \"Hw\".\n      + destruct p0; simpl in H; simplify_eq.\n        iExists _,_,_,_,_; iSplit;[eauto|]. iModIntro.\n        iDestruct (interp_exec_cond_binary with \"Hspec Hw\") as \"Hexec\";[auto|].\n        iApply exec_binary_wp;auto.\n      + destruct p0; simpl in H; simplify_eq.\n        iExists _,_,_,_,_; iSplit;[eauto|]. iModIntro.\n        iDestruct (interp_exec_cond_binary with \"Hspec Hw\") as \"Hexec\";[auto|].\n        iApply exec_binary_wp;auto.\n    - iIntros \"[Hfailed HPC]\".\n      iApply (wp_bind (fill [SeqCtx])).\n      iApply (wp_notCorrectPC with \"HPC\");eauto.\n      iNext. iIntros \"_\". iApply wp_pure_step_later;auto.\n      iNext. iApply wp_value. iFrame.\n  Qed.\n\n\nEnd fundamental.\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/fundamental_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.15167289644395363}}
{"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 RunComplete.Spec.\nRequire Import RunAux.Spec.\nRequire Import RunLoop.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition smc_rec_run_spec (rec_addr: Z64) (rec_run_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match rec_addr, rec_run_addr with\n    | VZ64 _rec_addr, VZ64 _rec_run_addr =>\n      rely is_int64 _rec_run_addr;\n      when'' _g_rec_run_base, _g_rec_run_ofst == find_granule_spec (VZ64 _rec_run_addr) adt;\n      rely is_int _g_rec_run_ofst;\n      when _t'8 == is_null_spec (_g_rec_run_base, _g_rec_run_ofst) adt;\n      rely is_int _t'8;\n      if (_t'8 =? 1) then\n        Some (adt, (VZ64 1))\n      else\n        rely is_int64 _rec_addr;\n        when'' _g_rec_base, _g_rec_ofst, adt == find_lock_unused_granule_spec (VZ64 _rec_addr) (VZ64 3) adt;\n        rely is_int _g_rec_ofst;\n        when _t'7 == is_null_spec (_g_rec_base, _g_rec_ofst) adt;\n        rely is_int _t'7;\n        if (_t'7 =? 1) then\n          Some (adt, (VZ64 1))\n        else\n          when adt == atomic_granule_get_spec (_g_rec_base, _g_rec_ofst) adt;\n          when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n          when adt == ns_granule_map_spec 0 (_g_rec_run_base, _g_rec_run_ofst) adt;\n          when _t'6, adt == ns_buffer_read_rec_run_spec 0 adt;\n          rely is_int _t'6;\n          if (_t'6 =? 0) then\n            when adt == ns_buffer_unmap_spec 0 adt;\n            when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n            Some (adt, (VZ64 1))\n          else\n            when'' _rec_base, _rec_ofst, adt == granule_map_spec (_g_rec_base, _g_rec_ofst) 3 adt;\n            rely is_int _rec_ofst;\n            when adt == granule_lock_spec (_g_rec_base, _g_rec_ofst) adt;\n            when _t'5 == get_rec_runnable_spec (_rec_base, _rec_ofst) adt;\n            rely is_int _t'5;\n            if (_t'5 =? 0) then\n              when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n              when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt;\n              when adt == ns_buffer_unmap_spec 0 adt;\n              when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n              Some (adt, (VZ64 1))\n            else\n              when _t'4, adt == complete_mmio_emulation_spec (_rec_base, _rec_ofst) adt;\n              rely is_int _t'4;\n              if (_t'4 =? 0) then\n                when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n                when adt == buffer_unmap_spec (_rec_base, _rec_ofst) adt;\n                when adt == ns_buffer_unmap_spec 0 adt;\n                when adt == atomic_granule_put_release_spec (_g_rec_base, _g_rec_ofst) adt;\n                Some (adt, (VZ64 1))\n              else\n                when adt == complete_hvc_exit_spec (_rec_base, _rec_ofst) adt;\n                when adt == reset_last_run_info_spec (_rec_base, _rec_ofst) adt;\n                when adt == reset_disposed_info_spec (_rec_base, _rec_ofst) adt;\n                when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n                when adt == rec_run_loop_spec (_rec_base, _rec_ofst) adt;\n                Some (adt, (VZ64 2))\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/RunSMC/Specs/smc_rec_run.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.30074557894124154, "lm_q1q2_score": 0.1515475529878323}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Arith.Mult\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.StringFacts\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedSumType\n        Fiat.Narcissus.BinLib.AlignedDomainName\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.SimpleDNSPacket\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.HintDbExtra\n        Fiat.Common.Tactics.TransparentAbstract\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Stores.DomainNameStore\n        Fiat.Narcissus.Automation.CacheEncoders.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  (*\n  Local Open Scope Tuple_scope.\n  Import Vectors.Vector.VectorNotations.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n  Arguments NPeano.div : simpl never.\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n       True /\\ (ValidDomainName a!\"contact_email\") /\\ ValidDomainName a!\"sourcehost\") inil))))\n      (SumType_index\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: [SOA_RDATA])\n         rr!sRDATA)\n      (SumType_proj\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: [SOA_RDATA])\n         rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n               (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n                      (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                             (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                                                 (True /\\ (ValidDomainName a!\"contact_email\")) /\\ ValidDomainName a!\"sourcehost\") inil))))        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    (* intros ? H.\n    destruct rr as [? [? [? [ ] ] ] ]; simpl in *.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *.\n    destruct prim_fst2; simpl in *.\n    apply H.\n  Qed. *)\n  Admitted.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n  Definition format_SOA_RDATA (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_A (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                        (icons format_A (* A; host address \t[RFC1035] *)\n                        (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                        (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata r!sRDATA\n                           DoneC.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments split1 : simpl never.\n  Arguments split2 : simpl never.\n  Arguments fin_eq_dec m !n !n' /.\n  Arguments addE : simpl never.\n\n  Arguments Vector.nth A !m !v' !p /.\n\n  Definition CNAME_encoder :\n    {encode : _ & CorrectAlignedEncoder format_CNAME encode}.\n  Proof.\n    unfold format_CNAME; eexists.\n  Admitted.\n\n  Definition A_encoder :\n    {encode : _ & CorrectAlignedEncoder format_A encode}.\n  Proof.\n    unfold format_A; eexists.\n  Admitted.\n\n  Definition NS_encoder :\n    {encode : _ & CorrectAlignedEncoder format_NS encode}.\n  Proof.\n    unfold format_NS; eexists.\n  Admitted.\n\n  Definition SOA_encoder :\n    {encode : _ & CorrectAlignedEncoder format_SOA_RDATA encode}.\n  Proof.\n    unfold format_SOA_RDATA; eexists.\n  Admitted.\n\n  Definition resource_record_encoder\n    : {encode : _ & CorrectAlignedEncoder format_resource encode}.\n  Proof.\n    unfold format_SOA_RDATA; eexists.\n  Admitted.\n\n  CNAME_encoder :\n\n\n  Definition refine_format_CNAME\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p,\n                  ValidDomainName p\n                  -> refine (format_CNAME p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_CNAME.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n    eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_A\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               refine (format_A p list_CacheFormat_empty)\n                                      (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_A.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n\n    simpl.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_NS\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               ValidDomainName p\n                               -> refine (format_NS p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_NS.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_SOA\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall a : SOA_RDATA,\n                               ValidDomainName a!\"contact_email\"\n                               -> ValidDomainName a!\"sourcehost\"\n                               -> refine (format_SOA_RDATA a list_CacheFormat_empty)\n                                         (ret (@build_aligned_ByteString (numBytes a) (v a), c a)) } } }.\n  Proof.\n    unfold format_SOA_RDATA.\n    eexists _, _, _; intros.\n    pose_string_hyps.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_resource\n    : { numBytes : _ &\n                   { v : _ &\n            { c : _ & forall p\n                             (p_OK : resourceRecord_OK p)\n                             ce,\n            refine (format_resource p ce)\n                   (ret (@build_aligned_ByteString (numBytes p ce) (v p ce), c p ce)) } } }.\n  Proof.\n    unfold format_resource; eexists _, _, _; intros.\n    etransitivity.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply (AlignedFormatSumTypeDoneC); repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME;\n      build_prim_prod_evar;\n      build_prim_prod_evar; simpl;\n      etransitivity;\n      [apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus;\n       eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption\n       | encoder_reflexivity].\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      unfold SumType_proj in H; simpl in H.\n      revert H; instantiate (1 := fun t => True /\\ _ t /\\ _ t); intros [? [? ?] ].\n      pattern t; apply H1.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      pattern t; apply (proj1 (proj2 H)).\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { apply p_OK. }\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    eapply (projT2 (projT2 (projT2 refine_format_resource))); eauto.\n    apply p_OK; assumption.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Time Definition encode_packet\n       (p : packet)\n    := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                      projT1 (projT2 (projT2 refine_format_packet)) p).\n  Set Printing Notations.\n  Print encode_packet.\n\n  Lemma refine_format_packet_Impl_OK\n    : forall p (p_OK : DNS_Packet_OK p),\n      refine (format_packet p list_CacheFormat_empty)\n             (ret (encode_packet p)).\n  Proof.\n    intros; apply (projT2 (projT2 (projT2 refine_format_packet))); eauto.\n  Qed.\n\n  Definition ByteAlignedCorrectDecoderFor {A} {cache : Cache}\n             Invariant FormatSpec :=\n    { decodePlusCacheInv |\n      exists P_inv,\n      (cache_inv_Property (snd decodePlusCacheInv) P_inv\n       -> CorrectDecoder (A := A) monoid Invariant (fun _ _ => True)\n                                  FormatSpec\n                                  (fst decodePlusCacheInv)\n                                  (snd decodePlusCacheInv))\n      /\\ cache_inv_Property (snd decodePlusCacheInv) P_inv}.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments weq : simpl never.\n  Arguments word_indexed : simpl never.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct)\n    | |- appcontext [CorrectDecoder _ _ _ (format_list format_resource) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Ltac synthesize_decoder_ext\n       monoid\n       decode_step'\n       determineHooks\n       synthesize_cache_invariant' :=\n    (* Combines tactics into one-liner. *)\n    start_synthesizing_decoder;\n    [ normalize_compose monoid;\n      repeat first [decode_step' idtac | decode_step determineHooks]\n    | cbv beta; synthesize_cache_invariant' idtac\n    |  ].\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    reflexivity.\n    decide_data_invariant.\n    instantiate (1 := true).\n    simpl.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *.\n    admit.\n    simpl; intros; eapply CorrectDecoderinish.\n    (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    destruct prim_fst7 as [? [? [? [ ] ] ] ].\n    simpl in *.\n    try decompose_parsed_data.\n    reflexivity.\n    decide_data_invariant.\n    simpl; intros;\n      repeat (try rewrite !DecodeBindOpt2_assoc;\n              try rewrite !Bool.andb_true_r;\n              try rewrite !Bool.andb_true_l;\n              try rewrite !optimize_if_bind2;\n              try rewrite !optimize_if_bind2_bool).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite !DecodeBindOpt2_assoc.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Then_Else_Bind (cache := dns_list_cache)).\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    higher_order_reflexivity.\n    set_refine_evar.\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    unfold H; higher_order_reflexivity.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    (* collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus. *)\n    simpl.\n    higher_order_reflexivity.\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Definition packetDecoderImpl\n    := Eval simpl in (projT1 packet_decoder).\n\n  Arguments Guarded_Vector_split : simpl never.\n\n  Arguments addD : simpl never.\n\n  Arguments Core.append_word : simpl never.\n  Arguments Vector_split : simpl never.\n  Arguments NPeano.leb : simpl never.\n\n  Definition If_Opt_Then_Else_map\n             {A B B'} :\n    forall (f : option B -> B')\n           (a_opt : option A)\n           (t : A -> option B)\n           c,\n      f (Ifopt a_opt as a Then t a Else c) =\n      Ifopt a_opt as a Then f (t a) Else (f c).\n  Proof.\n    destruct a_opt as [ a' | ]; reflexivity.\n  Qed.\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n      Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Definition ByteAligned_packetDecoderImpl {A}\n             (f : _ -> A)\n             n\n    : {impl : _ & forall (v : Vector.t _ (12 + n)),\n           f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n           impl v (Some (wzero 17) , @nil (pointerT * string))%list}.\n  Proof.\n    eexists _; intros.\n    etransitivity.\n    set_refine_evar; simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    eapply optimize_under_if_opt; simpl; intros.\n    rewrite BindOpt_map_if.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    rewrite BindOpt_map_if; unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    (* rewrite !DecodeBindOpt2_assoc. *)\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite byte_align_decode_DomainName.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    destruct a7 as [ [? [ ? ?] ] ? ]; simpl.\n    (*rewrite DecodeBindOpt2_assoc. *)\n    etransitivity.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If NPeano.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (NPeano.leb n sz) eqn: ?.\n    - apply NPeano.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- NPeano.leb_le in H1; congruence.\n  Qed.\n\n    match goal with\n      |- ?b = _ =>\n      let b' := (eval pattern (build_aligned_ByteString t) in b) in\n      let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode x _ 4 b')\n    end.\n    { intros.\n      unfold decode_enum.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      destruct (Compare_dec.lt_dec x 2).\n      unfold Core.char in *.\n      pose proof (@decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2 p) as H';\n      unfold mult in H';  simpl in H'; rewrite H'; try reflexivity; auto.\n      destruct x as [ | [ | [ | ?] ] ]; try omega.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; reflexivity\n      end.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; simpl; try eauto\n      end.\n      repeat rewrite DecodeBindOpt2_assoc.\n      pose proof (fun x t => @decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2) as H';\n        simpl in H'; unfold mult in H; rewrite H'; try reflexivity; auto.\n      omega.\n    }\n    { intros; unfold decode_enum.\n      etransitivity.\n      set_refine_evar; repeat rewrite BindOpt_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      rewrite (AlignedDecode2Char (Guarded_Vector_split 4 x t)).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite (@If_Opt_Then_Else_DecodeBindOpt _ dns_list_cache); simpl.\n      rewrite If_Opt_Then_Else_map.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      erewrite optimize_align_decode_list.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      etransitivity.\n      eapply optimize_under_if_opt; simpl; intros.\n      rewrite BindOpt_map_if_bool.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      etransitivity.\n      set_refine_evar.\n      clear H0.\n      rewrite byte_align_decode_DomainName.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      subst_evars.\n      eapply optimize_under_if_opt; simpl; intros.\n      destruct a11 as [ [? [ ? ?] ] ? ]; simpl.\n      rewrite DecodeBindOpt2_assoc.\n      simpl.\n      etransitivity.\n      match goal with\n        |- ?b = _ =>\n        let b' := (eval pattern (build_aligned_ByteString t0) in b) in\n        let b' := match b' with ?f _ => f end in\n        eapply (@AlignedDecoders.optimize_Guarded_Decode x0 _ 8 b')\n      end.\n      { intros.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        etransitivity; set_refine_evar.\n        unfold DecodeBindOpt2, BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_refine_evar; eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        rewrite BindOpt_assoc.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        unfold BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        etransitivity.\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_evars.\n        eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        destruct x0 as [ | [| [ | [ | x0] ] ] ]; try omega.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n      }\n      intros; etransitivity.\n      simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt;rewrite (@AlignedDecode4Char dns_list_cache).\n      repeat (rewrite Vector_split_merge,\n              <- Eqdep_dec.eq_rect_eq_dec;\n              eauto using Peano_dec.eq_nat_dec ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      let types' := (eval unfold ResourceRecordTypeTypes in ResourceRecordTypeTypes)\n      in ilist_of_evar\n           (fun T : Type => forall n,\n                Vector.t (word 8) n\n                -> CacheDecode\n                -> option (T * {n : _ & Vector.t (word 8) n} * CacheDecode))\n           types'\n           ltac:(fun decoders' => rewrite (@align_decode_sumtype_OK dns_list_cache _ ResourceRecordTypeTypes decoders'));\n           [ | simpl; intros; repeat (apply Build_prim_and; intros); try exact I].\n      set_refine_evar.\n      rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n      simpl.\n      subst_refine_evar.\n      etransitivity.\n      subst_evars; higher_order_reflexivity.\n      subst_evars; higher_order_reflexivity.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (@decode_unused_word_aligned_ByteString_overflow dns_list_cache _ _ v1 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x=> @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          unfold DecodeBindOpt2 at 1; rewrite (@AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus _ _ 2).\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 := fun n1 v1 cd0 =>  If  NPeano.leb 2 n1\n                                                Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                                                (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                                                (addD cd0 16) as p1\n                                                                   Then let (p2, cd') := p1 in\n                                                                        let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                                    Else None;\n                                                                                               Some (proj, rest, env') Else None); simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        simpl.\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 6 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          simpl.\n          unfold DecodeBindOpt2 at 1;\n          pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          destruct n1 as [ | [ | [ | [ | n1] ] ] ] ; try omega;\n            try reflexivity.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache); simpl.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        repeat (rewrite Vector_split_merge,\n                <- Eqdep_dec.eq_rect_eq_dec;\n                eauto using Peano_dec.eq_nat_dec ).\n        unfold mult; simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0\n                       => If NPeano.leb 6 n1\n                             Then Let n2 := Core.append_word\n                                              (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                               Fin.FS (Fin.FS (Fin.FS Fin.F1))]\n                                              (Core.append_word\n                                                 (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                  Fin.FS (Fin.FS Fin.F1)]\n                                                 (Core.append_word\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                     Fin.FS Fin.F1]\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@Fin.F1])) in\n                           Some\n                             (n2, existT _ _ (snd (Vector_split (2 + 4) (n1 - 6) (Guarded_Vector_split 6 n1 v1))),\n                              addD (addD cd0 16) 32) Else None).\n        simpl; find_if_inside; simpl; eauto.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0 =>\n                         If  NPeano.leb 2 n1\n                             Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                             (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                             (addD cd0 16) as p1\n                                                Then let (p2, cd') := p1 in\n                                                     let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                 Else None;\n                                                                            Some (proj, rest, env') Else None).\n        simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      Arguments plus : simpl never.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1;pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a16 as [ [? [ ? ?] ] ? ]; simpl.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          etransitivity.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a16 as [ [? [ ? ?] ] ? ]; simpl.\n          etransitivity.\n          match goal with\n            |- ?b = _ =>\n            let b' := (eval pattern (build_aligned_ByteString t2) in b) in\n            let b' := match b' with ?f _ => f end in\n            eapply (@AlignedDecoders.optimize_Guarded_Decode x2 _ 20 b')\n          end.\n          { subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ]; try omega.\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n          }\n          { intros.\n            etransitivity.\n            unfold plus.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            unfold plus.\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            repeat (rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec ).\n            higher_order_reflexivity.\n            higher_order_reflexivity.\n          }\n          Opaque If_Opt_Then_Else.\n          Opaque If_Then_Else.\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          subst_evars; reflexivity.\n          Opaque Core.append_word.\n          Opaque Guarded_Vector_split.\n          Opaque Vector.tl.\n          simpl.\n\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          Transparent If_Opt_Then_Else.\n          Transparent If_Then_Else.\n          simpl.\n          subst_refine_evar; reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        fold (plus 20 (n1 - 20)).\n        fold (plus 16 (n1 - 16)).\n        fold (plus 12 (n1 - 12)).\n        fold (plus 8 (n1 - 8)).\n        fold (plus 4 (n1 - 4)).\n        match goal with\n          |- context [S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S ?n)))))))))))))))] => fold (plus 16 n)\n        end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd in b) in\n          let b' := match b' with ?f _ _ _ => f end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If (b' n v cd) Then (et n v cd) Else (zt n v cd)); cbv beta; simpl; find_if_inside; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd in a) in\n          let a' := match a' with ?f _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                                    (zt n v cd)\n                                                                                    (et n v cd));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd ?a'' as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd, a'' in a) in\n          let a' := match a' with ?f _ _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let AT'' := match type of a'' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd a'' => If_Opt_Then_Else (a' n v cd a'')\n                                                                                        (zt n v cd a'')\n                                                                                        (et n v cd a''));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd, q, q' in b) in\n          let b' := match b' with ?f _ _ _ _ _ => f end in\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd q q' => If (b' n v cd q q') Then (et n v cd q q') Else (zt n v cd q q')); cbv beta; simpl; find_if_inside; simpl)) end.\n        clear H H1.\n        Opaque LetIn.\n        match goal with\n          |- _ =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n          let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n          let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n          makeEvar (forall n, Vector.t (word 8) n ->\n                              CacheDecode -> QT -> QT' ->\n                              word 32 -> word 32 ->\n                              word 32 -> word 32 -> ZT1)\n                   ltac:(fun zt1 =>\n                           makeEvar (forall n, Vector.t (word 8) n ->\n                                               CacheDecode -> QT -> QT' ->\n                                               word 32 -> word 32 ->\n                                               word 32 -> word 32 -> ZT2)\n                                    ltac:(fun zt2 =>\n                                            makeEvar (forall n, Vector.t (word 8) n ->\n                                                                CacheDecode -> QT -> QT' ->\n                                                                word 32 -> word 32 ->\n                                                                word 32 -> word 32 -> ZT3)\n                                                     ltac:(fun zt3 =>\n                                                             makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                 CacheDecode -> QT -> QT' -> word 32)\n                                                                      ltac:(fun w1 =>\n                                                                              makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                  CacheDecode -> QT -> QT' -> word 32)\n                                                                                       ltac:(fun w2 =>\n                                                                                               makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                   CacheDecode -> QT -> QT' -> word 32)\n                                                                                                        ltac:(fun w3 => makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                                            CacheDecode -> QT -> QT' -> word 32)\n                                                                                                                                 ltac:(fun w4 =>\n                                                                                                                                         unify z (fun n v cd q q' => LetIn (w1 n v cd q q') (fun w => LetIn (w2 n v cd q q')  (fun w' => LetIn (w3  n v cd q q') (fun w'' => LetIn (w4 n v cd q q') (fun w''' => Some (zt1 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt2 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt3 n v cd q q' w w' w'' w'''\n                                                                                                                                                 )))))); simpl)))))))\n        end.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        repeat f_equal.\n        higher_order_reflexivity.\n        instantiate (1 := fun n1 v1 cd0 p1 p2 x1 x2 x3 x4 => existT _ _ _).\n        simpl; reflexivity.\n        higher_order_reflexivity.\n        instantiate (1 := fun _ _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n      }\n      subst_refine_evar; reflexivity.\n      subst_refine_evar; reflexivity.\n      higher_order_reflexivity.\n      match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n      higher_order_reflexivity.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd in a) in\n        let a' := match a' with ?f _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                 (zt n v cd)\n                                                                 (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n      match goal with\n        |- If ?b Then ?t Else ?e =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => If (b' n v cd q) Then (zt n v cd q) Else (@None ZT)); cbv beta; simpl; find_if_inside; simpl)\n      end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => LetIn (b' n v cd q) (zt n v cd q)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q' in a) in\n        let a' := match a' with ?f _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' => If_Opt_Then_Else (a' n v cd q q')\n                                                                      (zt n v cd q q')\n                                                                      (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'' in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' => LetIn (b' n v cd q q' q'') (zt n v cd q q' q'')))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q', q'', q''' in a) in\n        let a' := match a' with ?f _ _ _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' => If_Opt_Then_Else (a' n v cd q q' q'' q''')\n                                                                               (zt n v cd q q' q'' q''')\n                                                                               (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'', q''', r in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' r => LetIn (b' n v cd q q' q'' q''' r) (zt n v cd q q' q'' q''' r)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      Time match goal with\n             |- If_Opt_Then_Else ?a ?t ?e =\n                Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' as a Then _ Else _ =>\n             let a' := (eval pattern n, v, cd, q, q', q'', q''', r, r' in a) in\n             let a' := match a' with ?f _ _ _ _ _ _ _ _ _ => f end in\n             let AT := match type of a with option ?T => T end in\n             let QT := match type of q with ?T => T end in\n             let QT' := match type of q' with ?T => T end in\n             let QT'' := match type of q'' with ?T => T end in\n             let QT''' := match type of q''' with ?T => T end in\n             let RT := match type of r with ?T => T end in\n             let RT' := match type of r' with ?T => T end in\n             let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n             makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> RT' -> AT -> option ZT)\n                      ltac:(fun zt =>\n                              unify z (fun n v cd q q' q'' q''' r r'=> If_Opt_Then_Else (a' n v cd q q' q'' q''' r r')\n                                                                                        (zt n v cd q q' q'' q''' r r')\n                                                                                        (@None ZT));\n                                cbv beta; simpl; destruct a; simpl) end.\n      (* This unification takes four minutes :p*)\n\n      match goal with\n        |- _ =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' ?r'' as a Then _ Else _ =>\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let RT' := match type of r' with ?T => T end in\n        let RT'' := match type of r'' with ?T => T end in\n        let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n        let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n        let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n        makeEvar (forall n, Vector.t (word 8) n ->\n                            CacheDecode -> QT -> QT' ->\n                            QT'' -> QT''' -> RT -> RT' -> RT''\n                            -> ZT1)\n                 ltac:(fun zt1 =>\n                         makeEvar (forall n, Vector.t (word 8) n ->\n                                             CacheDecode -> QT -> QT' ->\n                                             QT'' -> QT''' -> RT -> RT' -> RT''\n                                             -> ZT2)\n                                  ltac:(fun zt2 =>\n                                          makeEvar (forall n, Vector.t (word 8) n ->\n                                                              CacheDecode -> QT -> QT' ->\n                                                              QT'' -> QT''' -> RT -> RT' -> RT''\n                                                              -> ZT3)\n                                                   ltac:(fun zt3 => unify z (fun n v cd q q' q'' q''' r r' r'' =>\n                                                                               Some (zt1 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt2 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt3 n v cd q q' q'' q''' r r' r''));\n                                                                    simpl))) end.\n      repeat f_equal; try higher_order_reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; higher_order_reflexivity.\n    }\n    { match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n    }\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    simpl.\n    higher_order_reflexivity.\n    Time Defined.\n\n  Check ByteAligned_packetDecoderImpl.\n  Definition ByteAligned_packetDecoderImpl' {A} (k : _ -> A) n :=\n    Eval simpl in (projT1 (ByteAligned_packetDecoderImpl k n)).\n\n  Lemma ByteAligned_packetDecoderImpl'_OK {A}\n    : forall (f : _ -> A) n (v : Vector.t _ (12 + n)),\n        f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n        ByteAligned_packetDecoderImpl' f n v (Some (wzero 17) , @nil (pointerT * string))%list.\n  Proof.\n    intros.\n    pose proof (projT2 (ByteAligned_packetDecoderImpl f n));\n      cbv beta in H.\n    rewrite H.\n    set (H' := (Some (wzero 17), @nil (pointerT * string))).\n    simpl.\n    unfold ByteAligned_packetDecoderImpl'.\n    reflexivity.\n  Qed.\n\nEnd DnsPacket.\n\n(*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.DecideableEnsembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.StringFacts\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BinLib.AlignedSumType\n        Fiat.Narcissus.BinLib.AlignedDomainName\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.Compose\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.SimpleDNSPacket\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.HintDbExtra\n        Fiat.Common.Tactics.TransparentAbstract\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Narcissus.Stores.DomainNameStore\n        Fiat.Narcissus.Automation.CacheEncoders.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  Local Open Scope Tuple_scope.\n  Import Vectors.Vector.VectorNotations.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n  Arguments NPeano.div : simpl never.\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (As := ResourceRecordTypeTypes)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n      (icons (B := fun T => T -> Prop) (ValidDomainName)\n      (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n      (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))\n      (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n      (SumType_proj ResourceRecordTypeTypes rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n        (icons (B := fun T => T -> Prop) (ValidDomainName)\n        (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                            (ValidDomainName a!\"sourcehost\") /\\ ValidDomainName a!\"contact_email\") inil))))        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    intros ? H; apply H.\n  Qed.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Definition DNS_Packet_OK (data : packet) :=\n    lt (|data!\"answers\" |) (pow2 16)\n    /\\ lt (|data!\"authority\" |) (pow2 16)\n    /\\ lt (|data!\"additional\" |) (pow2 16)\n    /\\ ValidDomainName (data!\"question\")!\"qname\"\n    /\\ forall (rr : resourceRecord),\n        In rr (data!\"answers\" ++ data!\"additional\" ++ data!\"authority\")\n        -> resourceRecord_OK rr.\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n  Definition format_SOA_RDATA (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_A (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata r!sRDATA\n                           DoneC.\n\n  Definition format_packet (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Arguments split1 : simpl never.\n  Arguments split2 : simpl never.\n  Arguments fin_eq_dec m !n !n' /.\n  Arguments addE : simpl never.\n\n  Arguments Vector.nth A !m !v' !p /.\n\n  Definition format_rdata' :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                               (icons format_A (* A; host address \t[RFC1035] *)\n                                      (icons (format_NS) (* NS; authoritative name server \t[RFC1035] *)\n                                             (icons format_SOA_RDATA  (* SOA rks the start of a zone of authority \t[RFC1035] *) inil)))).\n\n  Definition format_resource' (r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           DoneC.\n\n  Definition format_packet' (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question p!\"question\"\n                     ThenC (format_list format_resource' (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Definition refine_format_CNAME\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p,\n                  ValidDomainName p\n                  -> refine (format_CNAME p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_CNAME.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n    eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_A\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               refine (format_A p list_CacheFormat_empty)\n                                      (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_A.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    simpl.\n    encoder_reflexivity.\n  Defined.\n  Unset Printing Notations.\n\n  Eval compute in (natToWord 8 128).\n\n  Definition refine_format_NS\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall p,\n                               ValidDomainName p\n                               -> refine (format_NS p list_CacheFormat_empty)\n                            (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_NS.\n    eexists _, _, _; intros.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_SOA\n    : { numBytes : _ &\n                   { v : _ &\n                         { c : _ & forall a : SOA_RDATA,\n                               ValidDomainName a!\"contact_email\"\n                               -> ValidDomainName a!\"sourcehost\"\n                               -> refine (format_SOA_RDATA a list_CacheFormat_empty)\n                                         (ret (@build_aligned_ByteString (numBytes a) (v a), c a)) } } }.\n  Proof.\n    unfold format_SOA_RDATA.\n    eexists _, _, _; intros.\n    pose_string_hyps.\n    etransitivity.\n    apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n    replace mempty\n    with (build_aligned_ByteString (Vector.nil _)).\n    reflexivity.\n    eapply ByteString_f_equal;\n      instantiate (1 := eq_refl _); reflexivity.\n    encoder_reflexivity.\n  Defined.\n\n  Definition refine_format_resource\n    : { numBytes : _ &\n      { v : _ &\n            { c : _ & forall p\n                             (p_OK : resourceRecord_OK p)\n                             ce,\n            refine (format_resource p ce)\n                   (ret (@build_aligned_ByteString (numBytes p ce) (v p ce), c p ce)) } } }.\n  Proof.\n    unfold format_resource; eexists _, _, _; intros.\n    etransitivity.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply (AlignedFormatSumTypeDoneC); repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME;\n      build_prim_prod_evar;\n      build_prim_prod_evar; simpl;\n      etransitivity;\n      [apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus;\n       eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption\n       | encoder_reflexivity].\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      unfold SumType_proj in H; simpl in H.\n      revert H; instantiate (1 := fun t => _ t /\\ _ t); intros [? ?].\n      pattern t; apply H.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      pattern t; apply (proj2 H).\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { apply p_OK. }\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\n  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    eapply (projT2 (projT2 (projT2 refine_format_resource))); eauto.\n    apply p_OK; assumption.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).\nSet Printing Notations.\nPrint encode_packet.\n\n(*  Definition refine_format_packet\n    : { numBytes : _ &\n      { v : _ &\n      { c : _ & forall (p : packet)\n                       (p_OK : DNS_Packet_OK p),\n            refine (format_packet p list_CacheFormat_empty)\n                   (ret (@build_aligned_ByteString (numBytes p) (v p), c p)) } } }.\n  Proof.\n    unfold format_packet.\n    (* Step 1: Cache any string constants *)\n    pose_string_hyps.\n    eexists _, _, _; intros.\n    (* Step 2: simplification with monad laws so that any complex\n       subformats are inlined properly. *)\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    (* Cache string constants again *)\n    pose_string_hyps.\n    etransitivity.\n    (* Replace formats with byte-aligned versions. *)\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    (* Not in a byte-aligned state, so we need to try to\n       combine/collapse formats until we are. *)\n    unfold format_enum.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    (* Woo hoo! We're formating an 8-bit word now! *)\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    (* But now we need to do it again. *)\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    rewrite CollapseFormatWord; eauto using addE_addE_plus.\n    eapply AlignedFormatChar; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    eapply AlignedFormat2Nat; eauto using addE_addE_plus.\n    (* Should replace this with an AlignedFormatDomainName. *)\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply p_OK.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormatListDoneC with (A_OK := resourceRecord_OK); intros.\n    unfold format_resource; intros.\n    eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n    eapply H.\n    unfold format_enum.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat2Char; eauto using addE_addE_plus.\n    eapply AlignedFormat32Char; eauto using addE_addE_plus.\n    unfold format_rdata.\n    eapply AlignedFormatSumTypeDoneC; repeat build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    build_ilist_evar.\n    simpl; intros. repeat (apply Build_prim_and; intros); try exact I.\n    { unfold format_CNAME.\n      build_prim_prod_evar.\n      build_prim_prod_evar; simpl.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); try eapply addE_addE_plus.\n      eapply AlignedFormatDomainNameDoneC; try eapply addE_addE_plus; try eassumption.\n      encoder_reflexivity.\n    }\n    { unfold format_A.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      simpl.\n      encoder_reflexivity.\n    }\n    { unfold format_NS.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold format_SOA_RDATA.\n      simpl.\n      simpl; build_prim_prod_evar.\n      simpl; build_prim_prod_evar.\n      simpl.\n      pose_string_hyps.\n      etransitivity.\n      apply (@AlignedFormat2UnusedChar dns_list_cache); eauto using addE_addE_plus.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      eapply AlignedFormatDomainNameThenC; eauto using addE_addE_plus.\n      clear; admit.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      apply (@AlignedFormat32Char dns_list_cache); auto using addE_addE_plus.\n      replace ByteString_id\n      with (build_aligned_ByteString (Vector.nil _)).\n      reflexivity.\n      eapply ByteString_f_equal;\n        instantiate (1 := eq_refl _); reflexivity.\n      encoder_reflexivity.\n    }\n    { unfold resourceRecord_OK in H.\n      eapply H.\n    }\n    apply p_OK; apply H.\n    Time simpl.\n    Time cache_encoders.\n    Time encoder_reflexivity.\n    Time Defined.\n\nTime Definition encode_packet\n             (p : packet)\n  := Eval simpl in (build_aligned_ByteString (projT1 (projT2 refine_format_packet) p),\n                    projT1 (projT2 (projT2 refine_format_packet)) p).v *)\n\nLemma refine_format_packet_Impl_OK\n  : forall p (p_OK : DNS_Packet_OK p),\n    refine (format_packet p list_CacheFormat_empty)\n           (ret (encode_packet p)).\nProof.\n  intros; apply (projT2 (projT2 (projT2 refine_format_packet))); eauto.\nQed.\n\n  Definition ByteAlignedCorrectDecoderFor {A} {cache : Cache}\n             Invariant FormatSpec :=\n    { decodePlusCacheInv |\n      exists P_inv,\n      (cache_inv_Property (snd decodePlusCacheInv) P_inv\n       -> CorrectDecoder (A := A) monoid Invariant (fun _ _ => True)\n                                  FormatSpec\n                                  (fst decodePlusCacheInv)\n                                  (snd decodePlusCacheInv))\n      /\\ cache_inv_Property (snd decodePlusCacheInv) P_inv}.\n\n  Arguments split1' : simpl never.\n  Arguments split2' : simpl never.\n  Arguments weq : simpl never.\n  Arguments word_indexed : simpl never.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct\n                IndependentCaches IndependentCaches' IndependentCaches'''\n                getDistinct getDistinct' addPeekSome\n                boundPeekSome addPeekNone addPeekNone'\n                addZeroPeek addPeekESome boundPeekESome\n                addPeekENone addPeekENone')\n    | |- appcontext [CorrectDecoder _ _ _ (format_list format_resource) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Ltac synthesize_decoder_ext\n       monoid\n       decode_step'\n       determineHooks\n       synthesize_cache_invariant' :=\n    (* Combines tactics into one-liner. *)\n    start_synthesizing_decoder;\n    [ normalize_compose monoid;\n      repeat first [decode_step' idtac | decode_step determineHooks]\n    | cbv beta; synthesize_cache_invariant' idtac\n    |  ].\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n    decode_DNS_rules idtac\n    unfold resourceRecord_OK.\n    clear; intros.\n    split.\n    apply (Logic.proj1 H).\n    admit.\n\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    (*destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *. *)\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n    simpl.\n    instantiate (1 := true).  admit.\n    simpl; intros; eapply CorrectDecoderinish.\n    unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n   (let a' := fresh in\n    intros a'; repeat destruct a' as (?, a'); unfold Domain, GetAttribute, GetAttributeRaw in *; simpl in *;\n     intros; intuition;\n     repeat\n      match goal with\n      | H:_ = _\n        |- _ => first\n        [ apply decompose_pair_eq in H;\n           (let H1 := fresh in\n            let H2 := fresh in\n            destruct H as (H1, H2); simpl in H1; simpl in H2)\n        | rewrite H in * ]\n      end).\n    destruct prim_fst7 as [? [? [? [ ] ] ] ]; simpl in *.\n    try decompose_parsed_data.\n    (*destruct H17. *)\n    reflexivity.\n    decide_data_invariant.\n\n    simpl; intros;\n      repeat (try rewrite !DecodeBindOpt2_assoc;\n              try rewrite !Bool.andb_true_r;\n              try rewrite !Bool.andb_true_l;\n              try rewrite !optimize_if_bind2;\n              try rewrite !optimize_if_bind2_bool).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite !DecodeBindOpt2_assoc.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    etransitivity.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    rewrite (If_Then_Else_Bind (cache := dns_list_cache)).\n    unfold decode_enum at 1.\n    repeat (try rewrite !DecodeBindOpt2_assoc;\n            try rewrite !Bool.andb_true_r;\n            try rewrite !Bool.andb_true_l;\n            try rewrite !optimize_if_bind2;\n            try rewrite !optimize_if_bind2_bool).\n    higher_order_reflexivity.\n    set_refine_evar.\n    rewrite (If_Opt_Then_Else_DecodeBindOpt_swap (cache := dns_list_cache)).\n    unfold H; higher_order_reflexivity.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus.\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    first [ apply DecodeBindOpt2_under_bind; simpl; intros\n          | eapply optimize_under_if_bool; simpl; intros\n          | eapply optimize_under_if; simpl; intros].\n    (* collapse_word addD_addD_plus.\n    collapse_word addD_addD_plus. *)\n    simpl.\n    higher_order_reflexivity.\n    reflexivity.\n    reflexivity.\n  Defined.\n\n  Definition packetDecoderImpl\n    := Eval simpl in (projT1 packet_decoder).\n\n  (*Arguments Guarded_Vector_split : simpl never.\n\n  Arguments addD : simpl never.\n\n  Arguments Core.append_word : simpl never.\n  Arguments Vector_split : simpl never.\n  Arguments NPeano.leb : simpl never.\n\n  Definition If_Opt_Then_Else_map\n             {A B B'} :\n    forall (f : option B -> B')\n           (a_opt : option A)\n           (t : A -> option B)\n           c,\n      f (Ifopt a_opt as a Then t a Else c) =\n      Ifopt a_opt as a Then f (t a) Else (f c).\n  Proof.\n    destruct a_opt as [ a' | ]; reflexivity.\n  Qed.\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\n  Lemma Ifopt_Ifopt {A A' B}\n    : forall (a_opt : option A)\n             (t : A -> option A')\n             (e : option A')\n             (t' : A' -> B)\n             (e' :  B),\n      Ifopt (Ifopt a_opt as a Then t a Else e) as a' Then t' a' Else e' =\n      Ifopt a_opt as a Then (Ifopt (t a) as a' Then t' a' Else e') Else (Ifopt e as a' Then t' a' Else e').\n  Proof.\n    destruct a_opt; simpl; reflexivity.\n  Qed.\n\n  Definition ByteAligned_packetDecoderImpl {A}\n             (f : _ -> A)\n             n\n    : {impl : _ & forall (v : Vector.t _ (12 + n)),\n           f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n           impl v (Some (wzero 17) , @nil (pointerT * string))%list}.\n  Proof.\n    eexists _; intros.\n    etransitivity.\n    set_refine_evar; simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Char dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecodeChar dns_list_cache ).\n    rewrite !nth_Vector_split.\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite Ifopt_Ifopt; simpl.\n    eapply optimize_under_if_opt; simpl; intros.\n    rewrite BindOpt_map_if.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    rewrite BindOpt_map_if; unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    subst_refine_evar; eapply optimize_under_if; simpl; intros.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite (@AlignedDecode2Nat dns_list_cache).\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n    (* rewrite !DecodeBindOpt2_assoc. *)\n    repeat first  [rewrite <- !Vector_nth_tl\n                  | rewrite !nth_Vector_split\n                  | rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec].\n    simpl.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n    rewrite byte_align_decode_DomainName.\n    rewrite Ifopt_Ifopt; simpl.\n    subst_refine_evar; eapply optimize_under_if_opt; simpl; intros.\n    destruct a8 as [ [? [ ? ?] ] ? ]; simpl.\n    (*rewrite DecodeBindOpt2_assoc. *)\n    etransitivity.\n    unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n\n  Lemma optimize_Guarded_Decode {sz} {C} n\n    : forall (a_opt : ByteString -> C)\n             (a_opt' : ByteString -> C) v c,\n      (~ (n <= sz)%nat\n       -> a_opt (build_aligned_ByteString v) = c)\n      -> (le n sz -> a_opt  (build_aligned_ByteString (Guarded_Vector_split n sz v))\n                     = a_opt'\n                         (build_aligned_ByteString (Guarded_Vector_split n sz v)))\n      -> a_opt (build_aligned_ByteString v) =\n         If NPeano.leb n sz Then\n            a_opt' (build_aligned_ByteString (Guarded_Vector_split n sz v))\n            Else c.\n  Proof.\n    intros; destruct (NPeano.leb n sz) eqn: ?.\n    - apply NPeano.leb_le in Heqb.\n      rewrite <- H0.\n      simpl; rewrite <- build_aligned_ByteString_eq_split'; eauto.\n      eauto.\n    - rewrite H; simpl; eauto.\n      intro.\n      rewrite <- NPeano.leb_le in H1; congruence.\n  Qed.\n\n    match goal with\n      |- ?b = _ =>\n      let b' := (eval pattern (build_aligned_ByteString t) in b) in\n      let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode x _ 4 b')\n    end.\n    { intros.\n      unfold decode_enum.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      destruct (Compare_dec.lt_dec x 2).\n      unfold Core.char in *.\n      pose proof (@decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2 p) as H';\n      unfold mult in H';  simpl in H'; rewrite H'; try reflexivity; auto.\n      destruct x as [ | [ | [ | ?] ] ]; try omega.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; reflexivity\n      end.\n      rewrite AlignedDecode2Char; unfold LetIn; simpl.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?b _ _ = _ => destruct b; simpl; try eauto\n      end.\n      repeat rewrite DecodeBindOpt2_assoc.\n      pose proof (fun x t => @decode_word_aligned_ByteString_overflow dns_list_cache _ x t 2) as H';\n        simpl in H'; unfold mult in H; rewrite H'; try reflexivity; auto.\n      omega.\n    }\n    { intros; unfold decode_enum.\n      etransitivity.\n      set_refine_evar; repeat rewrite BindOpt_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt.\n      rewrite Ifopt_Ifopt.\n      rewrite (AlignedDecode2Char (Guarded_Vector_split 4 x t)).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      rewrite (@If_Opt_Then_Else_DecodeBindOpt _ dns_list_cache); simpl.\n      rewrite If_Opt_Then_Else_map.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n      erewrite optimize_align_decode_list.\n      rewrite Ifopt_Ifopt.\n      simpl.\n      etransitivity.\n      eapply optimize_under_if_opt; simpl; intros.\n      rewrite BindOpt_map_if_bool.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      higher_order_reflexivity.\n      etransitivity.\n      set_refine_evar.\n      clear H0.\n      rewrite byte_align_decode_DomainName.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      subst_evars.\n      eapply optimize_under_if_opt; simpl; intros.\n      destruct a12 as [ [? [ ? ?] ] ? ]; simpl.\n      rewrite DecodeBindOpt2_assoc.\n      simpl.\n      etransitivity.\n      match goal with\n        |- ?b = _ =>\n        let b' := (eval pattern (build_aligned_ByteString t0) in b) in\n        let b' := match b' with ?f _ => f end in\n        eapply (@AlignedDecoders.optimize_Guarded_Decode x0 _ 8 b')\n      end.\n      { intros.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        etransitivity; set_refine_evar.\n        unfold DecodeBindOpt2, BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_refine_evar; eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        rewrite BindOpt_assoc.\n        destruct x0 as [ | [ | x0] ].\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        unfold BindOpt at 1; rewrite (@AlignedDecode2Char dns_list_cache ).\n        etransitivity.\n        subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n        rewrite (If_Opt_Then_Else_BindOpt).\n        subst_evars.\n        eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n        subst_refine_evar.\n        instantiate (1 := fun _ => None).\n        destruct x0 as [ | [| [ | [ | x0] ] ] ]; try omega.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n        subst_evars; reflexivity.\n        unfold LetIn; simpl; match goal with\n                               |- Ifopt ?b as _ Then _ Else _ = _ =>\n                               destruct b; reflexivity\n                             end.\n      }\n      intros; etransitivity.\n      simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode2Char dns_list_cache ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      etransitivity;\n        [match goal with\n           |- DecodeBindOpt2 (If_Opt_Then_Else ?a_opt ?t ?e) ?k = _ =>\n           pose proof (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache) a_opt t e k) as H'; apply H'; clear H'\n         end | ].\n      simpl.\n      subst_refine_evar;\n        eapply optimize_under_if_opt; simpl; intros;\n          set_refine_evar.\n      repeat rewrite DecodeBindOpt2_assoc.\n      unfold DecodeBindOpt2 at 1, BindOpt;rewrite (@AlignedDecode4Char dns_list_cache).\n      repeat (rewrite Vector_split_merge,\n              <- Eqdep_dec.eq_rect_eq_dec;\n              eauto using Peano_dec.eq_nat_dec ).\n      subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n      let types' := (eval unfold ResourceRecordTypeTypes in ResourceRecordTypeTypes)\n      in ilist_of_evar\n           (fun T : Type => forall n,\n                Vector.t (word 8) n\n                -> CacheDecode\n                -> option (T * {n : _ & Vector.t (word 8) n} * CacheDecode))\n           types'\n           ltac:(fun decoders' => rewrite (@align_decode_sumtype_OK dns_list_cache _ ResourceRecordTypeTypes decoders'));\n           [ | simpl; intros; repeat (apply Build_prim_and; intros); try exact I].\n      set_refine_evar.\n      rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n      simpl.\n      subst_refine_evar.\n      etransitivity.\n      subst_evars; higher_order_reflexivity.\n      subst_evars; higher_order_reflexivity.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (@decode_unused_word_aligned_ByteString_overflow dns_list_cache _ _ v1 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x=> @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n          simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          unfold DecodeBindOpt2 at 1; rewrite (@AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus _ _ 2).\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 := fun n1 v1 cd0 =>  If  NPeano.leb 2 n1\n                                                Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                                                (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                                                (addD cd0 16) as p1\n                                                                   Then let (p2, cd') := p1 in\n                                                                        let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                                    Else None;\n                                                                                               Some (proj, rest, env') Else None); simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        simpl.\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 6 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          simpl.\n          unfold DecodeBindOpt2 at 1;\n          pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          destruct n1 as [ | [ | [ | [ | n1] ] ] ] ; try omega;\n            try reflexivity.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache); simpl.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        repeat (rewrite Vector_split_merge,\n                <- Eqdep_dec.eq_rect_eq_dec;\n                eauto using Peano_dec.eq_nat_dec ).\n        unfold mult; simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0\n                       => If NPeano.leb 6 n1\n                             Then Let n2 := Core.append_word\n                                              (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                               Fin.FS (Fin.FS (Fin.FS Fin.F1))]\n                                              (Core.append_word\n                                                 (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                  Fin.FS (Fin.FS Fin.F1)]\n                                                 (Core.append_word\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@\n                                                                                                                                     Fin.FS Fin.F1]\n                                                    (snd (Vector_split 2 (S (S (S (S (n1 - 6))))) (Guarded_Vector_split 6 n1 v1)))[@Fin.F1])) in\n                           Some\n                             (n2, existT _ _ (snd (Vector_split (2 + 4) (n1 - 6) (Guarded_Vector_split 6 n1 v1))),\n                              addD (addD cd0 16) 32) Else None).\n        simpl; find_if_inside; simpl; eauto.\n      }\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1; pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        instantiate (1 :=\n                       fun n1 v1 cd0 =>\n                         If  NPeano.leb 2 n1\n                             Then `(proj, rest, env') <- Ifopt byte_aligned_decode_DomainName\n                             (snd (Vector_split 2 (n1 - 2) (Guarded_Vector_split 2 n1 v1)))\n                             (addD cd0 16) as p1\n                                                Then let (p2, cd') := p1 in\n                                                     let (a17, b') := p2 in Some (a17, b', cd')\n                                                                                 Else None;\n                                                                            Some (proj, rest, env') Else None).\n        simpl.\n        find_if_inside; simpl; eauto.\n        repeat rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache)).\n        unfold mult; simpl.\n        match goal with\n          |- Ifopt ?b as _ Then _ Else _ = _ =>\n          destruct b as [ [ [? [? ?] ] ?] | ]; reflexivity\n        end.\n      }\n      Arguments plus : simpl never.\n      { etransitivity.\n        match goal with\n          |- ?b = _ =>\n          let b' := (eval pattern (build_aligned_ByteString v1) in b) in\n          let b' := match b' with ?f _ => f end in\n          eapply (@AlignedDecoders.optimize_Guarded_Decode n1 _ 2 b')\n        end.\n        { intros.\n          destruct n1 as [ | [ | n1] ]; try omega.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n          pose proof (fun t x => @decode_unused_word_aligned_ByteString_overflow dns_list_cache _ t x 2) as H';\n            simpl in H'; rewrite H'; try reflexivity; auto.\n        }\n        { intros; etransitivity.\n          simpl.\n          unfold DecodeBindOpt2 at 1;pose proof (fun C B => @AlignedDecodeUnusedChars dns_list_cache _ addD_addD_plus C B 2) as H';\n            simpl in H'; rewrite H'; clear H'.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          rewrite byte_align_decode_DomainName.\n          rewrite (If_Opt_Then_Else_DecodeBindOpt (cache := dns_list_cache));\n            simpl.\n          etransitivity.\n          eapply optimize_under_if_opt; simpl; intros; set_refine_evar.\n          destruct a17 as [ [? [ ? ?] ] ? ]; simpl.\n          etransitivity.\n          match goal with\n            |- ?b = _ =>\n            let b' := (eval pattern (build_aligned_ByteString t2) in b) in\n            let b' := match b' with ?f _ => f end in\n            eapply (@AlignedDecoders.optimize_Guarded_Decode x2 _ 20 b')\n          end.\n          { subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ].\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            etransitivity; set_refine_evar.\n            unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            subst_evars.\n            intros; destruct x2 as [ | [ | [ | [ | x2] ] ] ]; try omega.\n            instantiate (1 := fun _ => None).\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            pose proof (fun t x => @decode_word_aligned_ByteString_overflow dns_list_cache _ t x 4) as H';\n              simpl in H'; rewrite H'; try reflexivity; auto.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n            unfold LetIn; reflexivity.\n          }\n          { intros.\n            etransitivity.\n            unfold plus.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            unfold plus.\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n            simpl; unfold DecodeBindOpt2 at 1, BindOpt; rewrite (@AlignedDecode4Char dns_list_cache ).\n            repeat (rewrite Vector_split_merge,\n                    <- Eqdep_dec.eq_rect_eq_dec;\n                    eauto using Peano_dec.eq_nat_dec ).\n            higher_order_reflexivity.\n            higher_order_reflexivity.\n          }\n          Opaque If_Opt_Then_Else.\n          Opaque If_Then_Else.\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          subst_evars; reflexivity.\n          Opaque Core.append_word.\n          Opaque Guarded_Vector_split.\n          Opaque Vector.tl.\n          simpl.\n\n          match goal with\n            |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n            let z' := (eval pattern d, x, t, p in z) in\n            let z' := match z' with ?f' _ _ _ _ => f' end in\n            unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                                 (projT2 (snd (fst a)))\n                                 (snd a));\n              cbv beta; reflexivity\n          end.\n          Transparent If_Opt_Then_Else.\n          Transparent If_Then_Else.\n          simpl.\n          subst_refine_evar; reflexivity.\n          higher_order_reflexivity.\n        }\n        simpl.\n        fold (plus 20 (n1 - 20)).\n        fold (plus 16 (n1 - 16)).\n        fold (plus 12 (n1 - 12)).\n        fold (plus 8 (n1 - 8)).\n        fold (plus 4 (n1 - 4)).\n        match goal with\n          |- context [S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S ?n)))))))))))))))] => fold (plus 16 n)\n        end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd in b) in\n          let b' := match b' with ?f _ _ _ => f end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If (b' n v cd) Then (et n v cd) Else (zt n v cd)); cbv beta; simpl; find_if_inside; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd in a) in\n          let a' := match a' with ?f _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                                    (zt n v cd)\n                                                                                    (et n v cd));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If_Opt_Then_Else ?a ?t ?e =\n             Ifopt ?z ?n ?v ?cd ?a'' as a Then _ Else _ =>\n          let a' := (eval pattern n, v, cd, a'' in a) in\n          let a' := match a' with ?f _ _ _ _ => f end in\n          let AT := match type of a with option ?T => T end in\n          let AT'' := match type of a'' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> AT -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT'' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd a'' => If_Opt_Then_Else (a' n v cd a'')\n                                                                                        (zt n v cd a'')\n                                                                                        (et n v cd a''));\n                                            cbv beta; simpl; destruct a; simpl)) end.\n        match goal with\n          |- If ?b Then ?t Else ?e =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let b' := (eval pattern n, v, cd, q, q' in b) in\n          let b' := match b' with ?f _ _ _ _ _ => f end in\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n          makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                   ltac:(fun zt =>\n                           makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> option ZT)\n                                    ltac:(fun et =>\n                                            unify z (fun n v cd q q' => If (b' n v cd q q') Then (et n v cd q q') Else (zt n v cd q q')); cbv beta; simpl; find_if_inside; simpl)) end.\n        clear H H1.\n        Opaque LetIn.\n        match goal with\n          |- _ =\n             Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n          let QT := match type of q with ?T => T end in\n          let QT' := match type of q' with ?T => T end in\n          let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n          let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n          let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n          makeEvar (forall n, Vector.t (word 8) n ->\n                              CacheDecode -> QT -> QT' ->\n                              word 32 -> word 32 ->\n                              word 32 -> word 32 -> ZT1)\n                   ltac:(fun zt1 =>\n                           makeEvar (forall n, Vector.t (word 8) n ->\n                                               CacheDecode -> QT -> QT' ->\n                                               word 32 -> word 32 ->\n                                               word 32 -> word 32 -> ZT2)\n                                    ltac:(fun zt2 =>\n                                            makeEvar (forall n, Vector.t (word 8) n ->\n                                                                CacheDecode -> QT -> QT' ->\n                                                                word 32 -> word 32 ->\n                                                                word 32 -> word 32 -> ZT3)\n                                                     ltac:(fun zt3 =>\n                                                             makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                 CacheDecode -> QT -> QT' -> word 32)\n                                                                      ltac:(fun w1 =>\n                                                                              makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                  CacheDecode -> QT -> QT' -> word 32)\n                                                                                       ltac:(fun w2 =>\n                                                                                               makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                   CacheDecode -> QT -> QT' -> word 32)\n                                                                                                        ltac:(fun w3 => makeEvar (forall n, Vector.t (word 8) n ->\n                                                                                                                                            CacheDecode -> QT -> QT' -> word 32)\n                                                                                                                                 ltac:(fun w4 =>\n                                                                                                                                         unify z (fun n v cd q q' => LetIn (w1 n v cd q q') (fun w => LetIn (w2 n v cd q q')  (fun w' => LetIn (w3  n v cd q q') (fun w'' => LetIn (w4 n v cd q q') (fun w''' => Some (zt1 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt2 n v cd q q' w w' w'' w''',\n                                                                                                                                                                                                                                                                                                                       zt3 n v cd q q' w w' w'' w'''\n                                                                                                                                                 )))))); simpl)))))))\n        end.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        rewrite LetIn_If_Opt_Then_Else.\n        f_equal.\n        higher_order_reflexivity.\n        apply functional_extensionality; intros.\n        simpl.\n        repeat f_equal.\n        higher_order_reflexivity.\n        instantiate (1 := fun n1 v1 cd0 p1 p2 x1 x2 x3 x4 => existT _ _ _).\n        simpl; reflexivity.\n        higher_order_reflexivity.\n        instantiate (1 := fun _ _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n        instantiate (1 := fun _ _ _ => None); reflexivity.\n      }\n      subst_refine_evar; reflexivity.\n      subst_refine_evar; reflexivity.\n      higher_order_reflexivity.\n      match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n      higher_order_reflexivity.\n      simpl.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd in a) in\n        let a' := match a' with ?f _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd => If_Opt_Then_Else (a' n v cd)\n                                                                 (zt n v cd)\n                                                                 (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n      match goal with\n        |- If ?b Then ?t Else ?e =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => If (b' n v cd q) Then (zt n v cd q) Else (@None ZT)); cbv beta; simpl; find_if_inside; simpl)\n      end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q in b) in\n        let b' := match b' with ?f _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q => LetIn (b' n v cd q) (zt n v cd q)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q' in a) in\n        let a' := match a' with ?f _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' => If_Opt_Then_Else (a' n v cd q q')\n                                                                      (zt n v cd q q')\n                                                                      (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'' in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' => LetIn (b' n v cd q q' q'') (zt n v cd q q' q'')))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      match goal with\n        |- If_Opt_Then_Else ?a ?t ?e =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' as a Then _ Else _ =>\n        let a' := (eval pattern n, v, cd, q, q', q'', q''' in a) in\n        let a' := match a' with ?f _ _ _ _ _ _ _ => f end in\n        let AT := match type of a with option ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> AT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' => If_Opt_Then_Else (a' n v cd q q' q'' q''')\n                                                                               (zt n v cd q q' q'' q''')\n                                                                               (@None ZT));\n                         cbv beta; simpl; destruct a; simpl) end.\n\n      match goal with\n        |- LetIn ?b ?k =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r as a Then _ Else _ =>\n        let b' := (eval pattern n, v, cd, q, q', q'', q''', r in b) in\n        let b' := match b' with ?f _ _ _ _ _ _ _ _ => f end in\n        let BT := match type of b with ?T => T end in\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n        makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> BT -> option ZT)\n                 ltac:(fun zt =>\n                         unify z (fun n v cd q q' q'' q''' r => LetIn (b' n v cd q q' q'' q''' r) (zt n v cd q q' q'' q''' r)))\n      end.\n      simpl.\n      rewrite LetIn_If_Opt_Then_Else.\n      f_equal.\n      apply functional_extensionality; intros.\n      Time match goal with\n             |- If_Opt_Then_Else ?a ?t ?e =\n                Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' as a Then _ Else _ =>\n             let a' := (eval pattern n, v, cd, q, q', q'', q''', r, r' in a) in\n             let a' := match a' with ?f _ _ _ _ _ _ _ _ _ => f end in\n             let AT := match type of a with option ?T => T end in\n             let QT := match type of q with ?T => T end in\n             let QT' := match type of q' with ?T => T end in\n             let QT'' := match type of q'' with ?T => T end in\n             let QT''' := match type of q''' with ?T => T end in\n             let RT := match type of r with ?T => T end in\n             let RT' := match type of r' with ?T => T end in\n             let ZT := match type of z with _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> _ -> option ?T => T end in\n             makeEvar (forall n, Vector.t (word 8) n -> CacheDecode -> QT -> QT' -> QT'' -> QT''' -> RT -> RT' -> AT -> option ZT)\n                      ltac:(fun zt =>\n                              unify z (fun n v cd q q' q'' q''' r r'=> If_Opt_Then_Else (a' n v cd q q' q'' q''' r r')\n                                                                                        (zt n v cd q q' q'' q''' r r')\n                                                                                        (@None ZT));\n                                cbv beta; simpl; destruct a; simpl) end.\n      (* This unification takes four minutes :p*)\n\n      match goal with\n        |- _ =\n           Ifopt ?z ?n ?v ?cd ?q ?q' ?q'' ?q''' ?r ?r' ?r'' as a Then _ Else _ =>\n        let QT := match type of q with ?T => T end in\n        let QT' := match type of q' with ?T => T end in\n        let QT'' := match type of q'' with ?T => T end in\n        let QT''' := match type of q''' with ?T => T end in\n        let RT := match type of r with ?T => T end in\n        let RT' := match type of r' with ?T => T end in\n        let RT'' := match type of r'' with ?T => T end in\n        let ZT1 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T1 end in\n        let ZT2 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T2 end in\n        let ZT3 := match type of z with _ -> _ -> _ -> _ -> _ ->\n                                        _ -> _ -> _ -> _ -> _ -> option (?T1 * ?T2 * ?T3) => T3 end in\n        makeEvar (forall n, Vector.t (word 8) n ->\n                            CacheDecode -> QT -> QT' ->\n                            QT'' -> QT''' -> RT -> RT' -> RT''\n                            -> ZT1)\n                 ltac:(fun zt1 =>\n                         makeEvar (forall n, Vector.t (word 8) n ->\n                                             CacheDecode -> QT -> QT' ->\n                                             QT'' -> QT''' -> RT -> RT' -> RT''\n                                             -> ZT2)\n                                  ltac:(fun zt2 =>\n                                          makeEvar (forall n, Vector.t (word 8) n ->\n                                                              CacheDecode -> QT -> QT' ->\n                                                              QT'' -> QT''' -> RT -> RT' -> RT''\n                                                              -> ZT3)\n                                                   ltac:(fun zt3 => unify z (fun n v cd q q' q'' q''' r r' r'' =>\n                                                                               Some (zt1 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt2 n v cd q q' q'' q''' r r' r'',\n                                                                                     zt3 n v cd q q' q'' q''' r r' r''));\n                                                                    simpl))) end.\n      repeat f_equal; try higher_order_reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; reflexivity.\n      subst_evars; higher_order_reflexivity.\n    }\n    { match goal with\n        |- ?z = ?f (?d, existT _ ?x ?t, ?p) =>\n        let z' := (eval pattern d, x, t, p in z) in\n        let z' := match z' with ?f' _ _ _ _ => f' end in\n        unify f (fun a => z' (fst (fst a)) (projT1 (snd (fst a)))\n                             (projT2 (snd (fst a)))\n                             (snd a));\n          cbv beta; reflexivity\n      end.\n    }\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    subst_evars; reflexivity.\n    simpl.\n    higher_order_reflexivity.\n    Time Defined.\n\n  Check ByteAligned_packetDecoderImpl.\n  Definition ByteAligned_packetDecoderImpl' {A} (k : _ -> A) n :=\n    Eval simpl in (projT1 (ByteAligned_packetDecoderImpl k n)).\n\n  Lemma ByteAligned_packetDecoderImpl'_OK {A}\n    : forall (f : _ -> A) n (v : Vector.t _ (12 + n)),\n        f (fst packetDecoderImpl (build_aligned_ByteString v) (Some (wzero 17), @nil (pointerT * string))) =\n        ByteAligned_packetDecoderImpl' f n v (Some (wzero 17) , @nil (pointerT * string))%list.\n  Proof.\n    intros.\n    pose proof (projT2 (ByteAligned_packetDecoderImpl f n));\n      cbv beta in H.\n    rewrite H.\n    set (H' := (Some (wzero 17), @nil (pointerT * string))).\n    simpl.\n    unfold ByteAligned_packetDecoderImpl'.\n    reflexivity.\n  Qed.\n\nEnd DnsPacket.\n*) *) *)\n\nEnd DnsPacket.\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/SimpleResourceRecord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15154754982967136}}
{"text": "(*\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     Classical\n     Morphisms\n     JMeq\n     List\n     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Automation\n     Maps\n     Keys\n     Messages\n     MessageEq\n     Tactics\n     Simulation\n     RealWorld\n     AdversaryUniverse\n     AdversarySafety\n     SafetyAutomation\n     SyntacticallySafe\n\n     Theory.CipherTheory\n     Theory.InvariantsTheory\n     Theory.KeysTheory\n     Theory.MessagesTheory\n     Theory.MessageEqTheory\n     Theory.UsersTheory\n\n     ModelCheck.ModelCheck\n     ModelCheck.Commutation\n     ModelCheck.LabelsAlign\n     ModelCheck.NoResends\n     ModelCheck.RealWorldStepLemmas\n     ModelCheck.SafeProtocol\n.\n\nFrom Frap Require Import\n     Invariant.\n\nFrom Frap Require\n     Sets.\n\nFrom SPICY Require\n     IdealWorld.\n\nImport SafetyAutomation.\n\n(* For later import of set notations inside sections *)\nModule Foo <: Sets.EMPTY.\nEnd Foo.\nModule SN := Sets.SetNotations(Foo).\n\nSet Implicit Arguments.\n\nSection NextSteps.\n\n  Inductive nextStepSS {A B} (u_id : user_id) (userData : user_data A)\n    : universe A B (* -> universe A B *) -> Prop :=\n\n  | NextSilent : forall U U',\n      U.(users) $? u_id = Some userData\n      -> indexedRealStep u_id Silent U U'\n      -> (forall uid' U', uid' > u_id -> ~ indexedRealStep uid' Silent U U')\n      -> nextStepSS u_id userData U\n\n  | NoSilents : forall U U' a,\n      U.(users) $? u_id = Some userData\n\n      (* No one can silently step *)\n      -> (forall uid' U', ~ indexedRealStep uid' Silent U U')\n\n      -> indexedRealStep u_id (Action a) U U'\n      -> nextStepSS u_id userData U.\n\n  Inductive stepSS (t__hon t__adv : type) :\n      @ModelState t__hon t__adv\n    -> @ModelState t__hon t__adv\n    -> Prop :=\n\n  | StepNextSS : forall ru ru' iu iu' u_id ud st st' v v',\n      nextStepSS u_id ud ru\n      -> st = (ru,iu,v)\n      -> st' = (ru',iu',v')\n      -> indexedModelStep u_id st st'\n      -> stepSS st st'.\n\nEnd NextSteps.\n\n(* Load the set notations *)\nImport SN.\n\nDefinition TrSS {t__hon t__adv} (ru0 : RealWorld.universe t__hon t__adv) (iu0 : IdealWorld.universe t__hon) :=\n  {| Initial := {(ru0, iu0, true)};\n     Step    := @stepSS t__hon t__adv |}.\n\n#[export] Hint Resolve adversary_remains_lame_step : core.\n#[export] Hint Constructors stepSS nextStepSS : core.\n\n(* #[export] Hint Resolve indexedIdealSteps_ideal_steps : core. *)\n#[export] Hint Constructors indexedModelStep indexedIdealStep indexedRealStep : core.\n#[export] Hint Resolve action_matches_other_user_silent_step_inv : core.\n\nLemma step_then_step' :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) uid1 ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n      -> message_queues_ok cs usrs gks\n      -> user_cipher_queues_ok cs (findUserKeys usrs) usrs\n      -> forall usrs'' (adv'' : user_data B) cs'' gks'' ms,\n          usrs'' $? uid1 = Some {| key_heap := ks;\n                                   protocol := cmdc;\n                                   msg_heap := qmsgs ++ ms;\n                                   c_heap   := mycs;\n                                   from_nons := froms;\n                                   sent_nons := sents;\n                                   cur_nonce := cur_n |}\n          -> (forall uid u, usrs $? uid = Some u -> exists u', usrs'' $? uid = Some u')\n          -> (forall cid c, cs $? cid = Some c -> cs'' $? cid = Some c)\n          -> (forall cid c, cs'' $? cid = Some c -> cs $? cid = Some c \\/ cs $? cid = None)\n          -> (forall kid k, gks $? kid = Some k -> gks'' $? kid = Some k)\n          -> exists bd'',\n              step_user lbl suid\n                        (usrs'', adv'', cs'', gks'', ks, qmsgs ++ ms, mycs, froms, sents, cur_n, cmd)\n                        bd''.\nProof.\n  induction 1; inversion 1; inversion 1\n  ; intros\n  ; subst\n  ; try solve [ eexists; econstructor; eauto ]\n  ; clean_context.\n\n  - eapply IHstep_user in H26; eauto.\n    split_ex.\n    dt x; eexists; econstructor; eauto.\n\n  - rewrite <- app_assoc,\n            <- app_comm_cons.\n    eexists; econstructor; eauto.\n    invert H6;\n      [ econstructor 1\n      | econstructor 2\n      | econstructor 3\n      ]; eauto.\n\n    rewrite Forall_forall in H7|- *\n    ; intros.\n\n    generalize (H7 _ H)\n    ; intros\n    ; destruct x\n    ; eauto.\n\n    unfold not\n    ; intros MAP\n    ; apply H0.\n\n    msg_queue_prop.\n    apply List.Forall_app in H2\n    ; split_ex\n    ; rewrite Forall_forall in H2\n    ; apply H2 in H\n    ; split_ex.\n\n    invert MAP;\n      [ econstructor 1\n      | econstructor 2\n      | econstructor 3\n      ]\n      ; eauto\n      ; specialize (H8 _ eq_refl).\n\n    apply H39 in H11; split_ors; clean_map_lookups; eauto.\n    apply H39 in H11; split_ors; clean_map_lookups; eauto.\n\n  - apply H36 in H2; split_ex; eauto.\n    eexists; econstructor; eauto.\n    unfold keys_mine in H0 |- *; intros.\n    apply H0.\n    unfold findKeysCrypto in H2 |- *.\n    destruct msg; eauto.\n    assert (List.In c_id mycs') by eauto.\n    user_cipher_queues_prop.\n    generalize (H37 _ _  H5); intros; context_map_rewrites; trivial.\n    \n  - eexists.\n    eapply StepEncrypt with (c_id0 := next_key cs''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n\n  - eexists.\n    eapply StepSign with (c_id0 := next_key cs''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n\n  - eexists.\n    eapply StepGenerateKey with (k_id0 := next_key gks''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n    Unshelve.\n    auto.\nQed.\n\nLemma step_then_silent_step :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) uid1 ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n      (* -> forall ctx styp, syntactically_safe uid1 (compute_ids usrs) ctx cmd styp *)\n      (* -> typingcontext_sound ctx usrs cs uid1 *)\n      -> message_queues_ok cs usrs gks\n      -> user_cipher_queues_ok cs (findUserKeys usrs) usrs\n      -> forall uid2 bd2 bd2',\n          step_user Silent (Some uid2) bd2 bd2'\n\n          -> forall cmd2 ks2 qmsgs2 mycs2 froms2 sents2 cur_n2 usrs'' cmdc' ud2,\n\n            uid1 <> uid2\n            -> usrs $? uid2 = Some ud2\n            -> bd2 = build_data_step (mkUniverse usrs adv cs gks) ud2\n            -> usrs' $? uid2 = Some {| key_heap := ks2;\n                                      protocol := cmd2;\n                                      msg_heap := qmsgs2;\n                                      c_heap   := mycs2;\n                                      from_nons := froms2;\n                                      sent_nons := sents2;\n                                      cur_nonce := cur_n2 |}\n            -> usrs'' = usrs' $+ (uid1, {| key_heap := ks';\n                                          protocol := cmdc';\n                                          msg_heap := qmsgs';\n                                          c_heap   := mycs';\n                                          from_nons := froms';\n                                          sent_nons := sents';\n                                          cur_nonce := cur_n' |})\n            -> exists bd2'',\n                step_user Silent (Some uid2)\n                          (usrs'', adv', cs', gks', ks2, qmsgs2, mycs2, froms2, sents2, cur_n2, cmd2)\n                          bd2''\n.\nProof.\n\n  Ltac ss :=\n    clean_map_lookups\n    ; unfold build_data_step in *\n    ; simpl in *\n    ; eauto\n    ; match goal with\n      | [ H : step_user Silent (Some ?uid) _ ?bd\n          |- exists _, step_user _ (Some ?uid) (?us,_,?cs,?gks,_,_,_,_,_,_,_) _ ] =>\n        dt bd\n        ; eapply step_then_step' with (ms := []) (usrs'' := us) (cs'' := cs) (gks'' := gks) in H\n      end\n    ; eauto\n    ; try rewrite app_nil_r in *\n    ; eauto\n    ; try\n        match goal with\n        | [ |- forall _ _, ?usrs $? _ = Some _ -> exists _, ?usrs $+ (?uid,_) $? _ = Some _ ] =>\n          let UID := fresh \"UID\"\n          in intros UID *; destruct (UID ==n uid); subst; eexists; clean_map_lookups; eauto\n        end.\n\n  induction 1; inversion 1; inversion 1; intros; subst\n  ; try solve [ ss ]; clean_context.\n\n  - destruct (rec_u_id ==n uid2); subst; clean_map_lookups.\n    + destruct ud2\n      ; clean_map_lookups\n      ; unfold build_data_step in *\n      ; simpl in *\n      ; eauto\n      ; match goal with\n        | [ H : step_user Silent (Some ?uid) _ ?bd\n            |- exists _, step_user _ (Some ?uid) (?us,_,?cs,?gks,_,_,_,_,_,_,_) _ ] =>\n          dt bd\n          ; eapply step_then_step' with (ms := [existT _ _ msg]) (usrs'' := us) (cs'' := cs) (gks'' := gks) in H\n        end\n      ; eauto\n      ; try rewrite app_nil_r in *\n      ; eauto\n      ; try\n          match goal with\n          | [ |- forall _ _, ?usrs $? _ = Some _ -> exists _, ?usrs $+ (?uid,_) $? _ = Some _ ] =>\n            let UID := fresh \"UID\"\n            in intros UID *; destruct (UID ==n uid); subst; eexists; clean_map_lookups; eauto\n          end.\n\n      intros.\n      destruct (uid ==n uid1); destruct (uid ==n uid2); subst; eexists; clean_map_lookups; eauto.\n\n    + ss.\n      intros.\n      destruct (uid ==n uid1); destruct (uid ==n rec_u_id); subst; eexists; clean_map_lookups; eauto.\n\n  - unfold build_data_step in *\n    ; clean_map_lookups\n    ; simpl in *.\n    \n    match goal with\n    | [ H : step_user Silent (Some ?uid) _ ?bd\n        |- exists _, step_user _ (Some ?uid) (?us,_,?cs,?gks,_,_,_,_,_,_,_) _ ] =>\n      dt bd\n      ; eapply step_then_step' with (ms := []) (usrs'' := us) (cs'' := cs) (gks'' := gks) in H\n    end\n    ; try rewrite app_nil_r in *\n    ; split_ex; eauto.\n\n    intros.\n    destruct (uid ==n uid1); destruct (uid ==n uid2); subst; eexists; clean_map_lookups; eauto.\n\n    intros.\n    destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n\n  - unfold build_data_step in *\n    ; clean_map_lookups\n    ; simpl in *.\n    \n    match goal with\n    | [ H : step_user Silent (Some ?uid) _ ?bd\n        |- exists _, step_user _ (Some ?uid) (?us,_,?cs,?gks,_,_,_,_,_,_,_) _ ] =>\n      dt bd\n      ; eapply step_then_step' with (ms := []) (usrs'' := us) (cs'' := cs) (gks'' := gks) in H\n    end\n    ; try rewrite app_nil_r in *\n    ; split_ex; eauto.\n\n    intros.\n    destruct (uid ==n uid1); destruct (uid ==n uid2); subst; eexists; clean_map_lookups; eauto.\n\n    intros.\n    destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n\n    Unshelve.\n    all: eauto.\nQed.\n\nLemma step_limited_change_other_user_qmsgs :\n  forall A B cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n    (cmd cmd' : user_cmd (Base A)) ks ks' qmsgs qmsgs' mycs mycs'\n    froms froms' sents sents' cur_n cur_n' uid uid' lbl\n    ks1 cmd1 qmsgs1 mycs1 froms1 sents1 cur_n1,\n\n    usrs $? uid = Some (mkUserData ks1 cmd1 qmsgs1 mycs1 froms1 sents1 cur_n1)\n    -> uid <> uid'\n    -> usrs $? uid' = Some (mkUserData ks cmd qmsgs mycs froms sents cur_n)\n    -> step_user lbl (Some uid')\n                (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n                (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n    -> exists qmsgs1',\n        (usrs' $+ (uid', mkUserData ks' cmd' qmsgs' mycs' froms' sents' cur_n')) $? uid\n        = Some (mkUserData ks1 cmd1 qmsgs1' mycs1 froms1 sents1 cur_n1)\n        /\\ (qmsgs1' = qmsgs1 \\/ exists m, qmsgs1' = qmsgs1 ++ [m])\n.\nProof.\n  intros.\n  specialize (user_step_adds_no_users H2 eq_refl eq_refl); intros.\n  generalize H2; intros STEP.\n  eapply step_limited_change_other_user with (u_id2 := uid) in STEP; eauto; split_ex.\n  \n  split_ors; split_ex; eauto.\nQed.\n\nDefinition useless_summary : summary :=\n  {| sending_to := Sets.scomp (fun (n : nat) => True) |}.  \n\nLemma useless_summary_summarizes :\n  forall t cmd,\n    @summarize t cmd useless_summary.\nProof.\n  induction cmd; econstructor; eauto; simpl.\n  unfold Sets.scomp, Sets.In; simpl; trivial.\nQed.\n\nLemma silent_step_na_commuting :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n',\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> lbl = Silent\n      -> forall s,\n          exists t cmd__n,\n            @nextAction _ t cmd cmd__n\n            /\\ commutes cmd__n s.\nProof.\n  #[export] Hint Constructors nextAction : core.\n  induction 1; inversion 1; inversion 1; intros; subst; simpl; try discriminate\n  ; try solve [ (do 2 eexists); split; eauto; simpl; trivial ].\n\n  specialize (IHstep_user _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ eq_refl eq_refl eq_refl s)\n  ; split_ex\n  ; (do 2 eexists)\n  ; split\n  ; [ econstructor |]\n  ; eauto.\nQed.\n\nLemma step_didnt_appear :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) uid1 ks ks' qmsgs qmsgs' mycs mycs' ms\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs ++ ms, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> lbl = Silent\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs ++ ms;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n      -> forall usrs'' (adv'' : user_data B) cs'' gks'',\n          usrs'' $? uid1 = Some {| key_heap := ks;\n                                   protocol := cmdc;\n                                   msg_heap := qmsgs;\n                                   c_heap   := mycs;\n                                   from_nons := froms;\n                                   sent_nons := sents;\n                                   cur_nonce := cur_n |}\n          -> forall ctx styp, syntactically_safe uid1 (compute_ids usrs'') ctx cmd styp\n          -> typingcontext_sound ctx usrs'' cs'' uid1\n          -> keys_and_permissions_good gks'' usrs'' adv''.(key_heap)\n          -> user_cipher_queues_ok cs'' (findUserKeys usrs'') usrs''\n          -> (forall uid u, usrs'' $? uid = Some u -> exists u', usrs $? uid = Some u')\n          -> (forall cid c, cs'' $? cid = Some c -> cs $? cid = Some c)\n          -> (forall cid c, cs $? cid = Some c -> cs'' $? cid = Some c \\/ cs'' $? cid = None)\n          -> (forall kid k, gks'' $? kid = Some k -> gks $? kid = Some k)\n          -> exists bd'',\n              step_user Silent suid\n                        (usrs'', adv'', cs'', gks'', ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n                        bd''.\nProof.\n  induction 1; inversion 1; inversion 1\n  ; intros\n  ; subst\n  ; try discriminate\n  ; try solve [ eexists; econstructor; eauto ]\n  ; clean_context.\n\n  - invert H28.\n    eapply IHstep_user in H27; eauto.\n    split_ex.\n    dt x; eexists; econstructor; eauto.\n\n  - unfold typingcontext_sound in *\n    ; split_ex\n    ; invert H38\n    ; process_ctx.\n    keys_and_permissions_prop.\n\n    generalize (H13 _ _ H9)\n    ; generalize (H13 _ _ H10)\n    ; intros; split_ex.\n\n    generalize (H45 _ _ H19)\n    ; generalize (H45 _ _ H20)\n    ; intros\n    ; clean_map_lookups.\n    \n    eapply StepEncrypt with (c_id0 := next_key cs''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n\n  - eexists.\n    assert (List.In c_id mycs'0) by eauto.\n    user_cipher_queues_prop.\n    eapply H42 in H; split_ors; clean_map_lookups; eauto.\n    keys_and_permissions_prop.\n\n    generalize (H11 _ _ H2)\n    ; generalize (H11 _ _ H3)\n    ; intros\n    ; clean_map_lookups\n    ; clear H11.\n    \n    generalize (H43 _ _ H12)\n    ; generalize (H43 _ _ H13)\n    ; intros\n    ; clean_map_lookups\n    ; clear H43.\n    \n    econstructor; eauto.\n    \n  - keys_and_permissions_prop.\n\n    generalize (H8 _ _ H0)\n    ; intros\n    ; clean_map_lookups.\n\n    generalize (H43 _ _ H9)\n    ; intros\n    ; clean_map_lookups.\n\n    eexists.\n    eapply StepSign with (c_id0 := next_key cs''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n\n  - keys_and_permissions_prop.\n    \n    generalize (H7 _ _ H0)\n    ; intros\n    ; clean_map_lookups.\n\n    generalize (H38 _ _ H8)\n    ; intros\n    ; clean_map_lookups.\n\n    assert (List.In c_id mycs') by eauto.\n    user_cipher_queues_prop.\n    eapply H37 in H1; split_ors; clean_map_lookups; eauto.\n\n    eexists. \n    econstructor; eauto.\n\n  - eexists.\n    \n    eapply StepGenerateKey with (k_id0 := next_key gks''); clean_map_lookups; eauto.\n    eapply next_key_not_in; eauto.\n\n    Unshelve.\n    auto.\nQed.\n\nLemma step_then_silent_step_inv :\n  forall {A B C} suid lbl bd bd',\n\n    step_user lbl suid bd bd'\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) uid1 ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' cmdc,\n\n      bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n      -> suid = Some uid1\n      -> usrs $? uid1 = Some {| key_heap := ks;\n                               protocol := cmdc;\n                               msg_heap := qmsgs;\n                               c_heap   := mycs;\n                               from_nons := froms;\n                               sent_nons := sents;\n                               cur_nonce := cur_n |}\n\n      -> forall uid2 bd2 bd2' cmd2 ks2 qmsgs2 mycs2 froms2 sents2 cur_n2 usrs'' cmdc' ud2,\n\n          step_user Silent (Some uid2)\n                    (usrs'', adv', cs', gks', ks2, qmsgs2, mycs2, froms2, sents2, cur_n2, cmd2)\n                    bd2'\n          -> uid1 <> uid2\n          -> usrs $? uid2 = Some ud2\n          -> bd2 = build_data_step (mkUniverse usrs adv cs gks) ud2\n          -> usrs' $? uid2 = Some {| key_heap := ks2;\n                                    protocol := cmd2;\n                                    msg_heap := qmsgs2;\n                                    c_heap   := mycs2;\n                                    from_nons := froms2;\n                                    sent_nons := sents2;\n                                    cur_nonce := cur_n2 |}\n          -> usrs'' = usrs' $+ (uid1, {| key_heap := ks';\n                                        protocol := cmdc';\n                                        msg_heap := qmsgs';\n                                        c_heap   := mycs';\n                                        from_nons := froms';\n                                        sent_nons := sents';\n                                        cur_nonce := cur_n' |})\n          -> forall ctx styp, syntactically_safe uid2 (compute_ids usrs) ctx cmd2 styp\n                        -> typingcontext_sound ctx usrs cs uid2\n                        -> keys_and_permissions_good gks usrs adv.(key_heap)\n                        -> user_cipher_queues_ok cs (findUserKeys usrs) usrs\n                        -> exists bd2'',\n                            step_user Silent (Some uid2) bd2 bd2''\n.\nProof.\n  induction 1; inversion 1; inversion 1; intros; subst; clean_context\n  ; autorewrite with find_user_keys in *\n  ; try solve [\n          dt bd2'; clean_map_lookups\n          ; eapply step_didnt_appear with (ms := [])\n          ; try rewrite app_nil_r\n          ; simpl; eauto\n          ; intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto ].\n\n  - eapply IHstep_user in H30; eauto.\n  - simpl in *.\n    destruct (rec_u_id ==n uid2); subst; clean_map_lookups; eauto.\n\n    + dt bd2'; destruct ud2; clean_map_lookups.\n      eapply step_didnt_appear with (ms := [existT crypto t0 msg]); simpl in *; eauto.\n\n      intros\n      ; destruct (uid1 ==n uid)\n      ; destruct (uid2 ==n uid)\n      ; subst; clean_map_lookups; eauto.\n\n    + dt bd2'; clean_map_lookups\n      ; eapply step_didnt_appear with (ms := [])\n      ; try rewrite app_nil_r\n      ; simpl in *\n      ; eauto.\n\n      intros\n      ; destruct (rec_u_id ==n uid)\n      ; destruct (uid1 ==n uid)\n      ; subst; clean_map_lookups; eauto.\n      \n  - dt bd2'; clean_map_lookups\n    ; eapply step_didnt_appear with (ms := [])\n    ; try rewrite app_nil_r\n    ; simpl; eauto.\n    \n    intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\n\n  - dt bd2'; clean_map_lookups\n    ; eapply step_didnt_appear with (ms := [])\n    ; try rewrite app_nil_r\n    ; simpl; eauto.\n    \n    intros; destruct (uid1 ==n uid); subst; clean_map_lookups; eauto.\n    intros; destruct (c_id ==n cid); subst; clean_map_lookups; eauto.\nQed.\n\nLemma silent_step_commutes_noblock :\n  forall t__hon t__adv (usrs usrs' : honest_users t__hon) (adv adv' : user_data t__adv) cs cs' gks gks'\n    ks2 ks2' qmsgs2 qmsgs2' mycs2 mycs2' froms2 froms2' sents2 sents2' cur_n2 cur_n2' cmd2 cmd2' uid2,\n\n    usrs $? uid2 = Some (mkUserData ks2 cmd2 qmsgs2 mycs2 froms2 sents2 cur_n2)\n    -> step_user Silent (Some uid2)\n                (usrs, adv, cs, gks, ks2, qmsgs2, mycs2, froms2, sents2, cur_n2, cmd2)\n                (usrs', adv', cs', gks', ks2', qmsgs2', mycs2', froms2', sents2', cur_n2', cmd2')\n    -> forall uid1, uid1 <> uid2\n    -> forall (usrs1' : honest_users t__hon) (adv1' : user_data t__adv) cs1' gks1'\n        ks1 ks1' qmsgs1 qmsgs1' mycs1 mycs1' froms1 froms1' sents1 sents1' cur_n1 cur_n1' cmd1 cmd1' lbl1,\n\n        usrs $? uid1 = Some (mkUserData ks1 cmd1 qmsgs1 mycs1 froms1 sents1 cur_n1)\n        -> step_user lbl1 (Some uid1)\n                  (usrs, adv, cs, gks, ks1, qmsgs1, mycs1, froms1, sents1, cur_n1, cmd1)\n                  (usrs1', adv1', cs1', gks1', ks1', qmsgs1', mycs1', froms1', sents1', cur_n1', cmd1')\n        -> forall ks2'' qmsgs2'' mycs2'' froms2'' sents2'' cur_n2'',\n          usrs1' $? uid2 = Some (mkUserData ks2'' cmd2 qmsgs2'' mycs2'' froms2'' sents2'' cur_n2'')\n        -> exists usrs2' adv2' cs2' gks2' ks2''' qmsgs2''' mycs2''' froms2''' sents2''' cur_n2''' cmd2'',\n          step_user Silent (Some uid2)\n                    (usrs1' $+ (uid1, mkUserData ks1' cmd1' qmsgs1' mycs1' froms1' sents1' cur_n1'),\n                     adv1', cs1', gks1', ks2'', qmsgs2'', mycs2'', froms2'', sents2'', cur_n2'', cmd2)\n                    (usrs2', adv2', cs2', gks2', ks2''', qmsgs2''', mycs2''', froms2''', sents2''', cur_n2''', cmd2'')\n.\nProof.\n  intros.\n\n  pose proof (useless_summary_summarizes cmd1).\n  generalize H0; intros SS\n  ; eapply silent_step_na_commuting with (s := useless_summary) in H0; eauto\n  ; split_ex.\n\n  generalize SS; intros STEP\n  ; eapply commutes_noblock with (uid1 := uid1) (uid2 := uid2) (summaries := $0 $+ (uid1,useless_summary)) in SS\n  ; eauto.\nQed.\n\nLemma translate_trace_commute :\n  forall t__hon t__adv i st st' b,\n    @stepsi t__hon t__adv (1 + i) st st'\n    -> lameAdv b (fst (fst st)).(adversary)\n    -> syntactically_safe_U (fst (fst st))\n    -> goodness_predicates (fst (fst st))\n    -> (forall st'', ~ step st' st'')\n    -> forall uid ud, (fst (fst st)).(users) $? uid = Some ud\n    (* -> (forall uid' U', uid' > uid -> ~ indexedRealStep uid' Silent (fst (fst st)) U') *)\n    -> forall bd, step_user Silent (Some uid) (build_data_step (fst (fst st)) ud) bd\n    -> exists st0 st0',\n          indexedModelStep uid st st0\n        /\\ stepsi i st0 st0'\n        /\\ fst st0' = fst st'\n        /\\ ( snd st0' = snd st' \\/ (snd st0' = false /\\ snd st' = true) )\n.\nProof.\n  induct 1; intros; eauto.\n  invert H0.\n\n  - clear IHstepsi.\n    invert H; simpl in *;\n      repeat\n        match goal with\n        | [ H : ?x = ?x |- _ ] => clear H\n        | [ H : step_universe _ _ _ _ |- _ ] => invert H; dismiss_adv\n        | [ H : indexedRealStep _ _ _ _ |- _ ] => invert H\n        | [ H : Silent = mkULbl ?lbl _ |- _ ] => unfold mkULbl in H; destruct lbl; try discriminate\n        end.\n\n    + destruct (uid ==n u_id); subst; clean_map_lookups.\n\n      (* equal *)\n      (do 2 eexists); repeat simple apply conj; simpl; try econstructor; eauto 8.\n\n      (* not equal *)\n\n      unfold build_data_step in *\n      ; destruct userData, ud\n      ; simpl in *\n      ; generalize H7; intros STEP\n      ; eapply step_limited_change_other_user with (u_id1 := u_id) (u_id2 := uid) in H7\n      ; eauto\n      ; split_ex\n      ; simpl in *.\n      \n      exfalso.\n      unfold goodness_predicates in *; split_ex.\n      \n      split_ors; split_ex; clean_map_lookups\n      ; eapply step_then_silent_step with (uid1 := u_id) (uid2 := uid) in STEP\n      ; eauto\n      ; split_ex.\n\n      dt x\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id0 := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n      dt x0\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id0 := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups.\n\n      (* equal *)\n      eapply user_step_label_deterministic in H6; eauto; discriminate.\n\n      (* not equal *) \n      unfold build_data_step in *\n      ; destruct userData, ud\n      ; dt bd\n      ; simpl in *\n      ; generalize H11; intros STEP\n      ; eapply step_limited_change_other_user with (u_id1 := uid0) (u_id2 := uid) in H11\n      ; eauto\n      ; split_ex\n      ; simpl in *.\n      \n      exfalso.\n      unfold goodness_predicates in *; split_ex.\n      \n      split_ors; split_ex; clean_map_lookups\n      ; eapply step_then_silent_step with (uid1 := uid0) (uid2 := uid) in STEP\n      ; eauto\n      ; split_ex.\n\n      dt x\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n      dt x0\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups.\n\n      (* equal *)\n      eapply user_step_label_deterministic in H6; eauto; discriminate.\n\n      (* not equal *) \n      unfold build_data_step in *\n      ; destruct userData, ud\n      ; dt bd\n      ; simpl in *\n      ; generalize H10; intros STEP\n      ; eapply step_limited_change_other_user with (u_id1 := uid0) (u_id2 := uid) in H10\n      ; eauto\n      ; split_ex\n      ; simpl in *.\n      \n      exfalso.\n      unfold goodness_predicates in *; split_ex.\n      \n      split_ors; split_ex; clean_map_lookups\n      ; eapply step_then_silent_step with (uid1 := uid0) (uid2 := uid) in STEP\n      ; eauto\n      ; split_ex.\n\n      dt x\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n      dt x0\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups.\n\n      (* equal *)\n      eapply user_step_label_deterministic in H6; eauto; discriminate.\n\n      (* not equal *) \n      unfold build_data_step in *\n      ; destruct userData, ud\n      ; dt bd\n      ; simpl in *\n      ; generalize H10; intros STEP\n      ; eapply step_limited_change_other_user with (u_id1 := uid0) (u_id2 := uid) in H10\n      ; eauto\n      ; split_ex\n      ; simpl in *.\n      \n      exfalso.\n      unfold goodness_predicates in *; split_ex.\n      \n      split_ors; split_ex; clean_map_lookups\n      ; eapply step_then_silent_step with (uid1 := uid0) (uid2 := uid) in STEP\n      ; eauto\n      ; split_ex.\n\n      dt x\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n      dt x0\n      ; eapply H4\n      ; econstructor 1; eauto\n      ; eapply StepUser with (u_id := uid)\n      ; unfold build_data_step, buildUniverse; simpl\n      ; eauto.\n\n  - assert (LAME: lameAdv b (adversary (fst (fst st)))) by assumption.\n    eapply adversary_remains_lame_step in LAME; eauto.\n\n    assert (SS : syntactically_safe_U (fst (fst st'))) by eauto using syntactically_safe_U_preservation_step.\n\n    assert (UNIVS : goodness_predicates (fst (fst st'))).\n    eapply goodness_preservation_step; eauto.\n\n    specialize (IHstepsi _ _ eq_refl LAME SS UNIVS H4).\n    clear LAME SS UNIVS.\n\n    dt bd; destruct ud; simpl in *.\n\n    invert H; simpl in *;\n      repeat\n      match goal with\n      | [ H : step_universe _ _ _ _ |- _ ] => invert H; dismiss_adv\n      | [ H : indexedRealStep _ _ _ _ |- _ ] => invert H\n      | [ H : Silent = mkULbl ?lbl _ |- _ ] => unfold mkULbl in H; destruct lbl; try discriminate\n      end;\n      (* match goal with *)\n      (* | [ H : O.max_elt _ = Some _ |- _ ] => *)\n      (*   let MAX := fresh \"H\" *)\n      (*   in generalize H; intros MAX; *)\n      (*        apply NatMap.O.max_elt_MapsTo in MAX; rewrite find_mapsto_iff in MAX *)\n      (* end; *)\n      try rename u_id into uid0.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups.\n\n      (* equal *)\n      (do 2 eexists); repeat simple apply conj; eauto.\n      econstructor; eauto.\n      econstructor; eauto.\n\n      (* not equal *)\n      (* assert (LK : users ru $? uid0 = Some userData) by assumption. *)\n      (* eapply H8 in LK; eauto; split_ex.     gathers summaries *)\n\n      destruct userData; unfold buildUniverse, build_data_step in *; simpl in *.\n      (* specialize (H5 _ _ x H); split_ex. (* specializes summary *) *)\n\n      generalize H9; intros STEP\n      ; eapply step_limited_change_other_user_qmsgs with (uid := uid) (uid' := uid0) in STEP\n      ; eauto; split_ex.\n      rename x into msg_heap'.\n\n      specialize (IHstepsi _ _ H0); simpl in *.\n\n      eapply silent_step_commutes_noblock with (usrs := users ru) (usrs1' := usrs0) in H6; eauto.\n      2: clean_map_lookups; eauto.\n      split_ex.\n\n      generalize H6; intros SS; eapply IHstepsi in H6; eauto.\n      clear IHstepsi; split_ex; subst.\n\n      Ltac clear_mislabeled_steps :=\n        repeat\n          match goal with\n          | [ H : indexedRealStep _ _ _ _ |- _ ] => invert H\n          | [ H1 : step_user (Action _) (Some ?uid) _ _\n            , H2 : step_user Silent (Some ?uid) _ _ |- _ ] =>\n            unfold build_data_step in *\n            ; simpl in *\n            ; clean_map_lookups\n            ; simpl in *\n            ; pose proof (user_step_label_deterministic _ _ _ _ _ _ _ _ _ H1 H2)\n            ; discriminate\n          end.\n\n      invert H6; clear_mislabeled_steps.\n\n      pose proof (useless_summary_summarizes protocol0).\n      eapply silent_step_na_commuting with (s := useless_summary) in SS; eauto\n      ; split_ex.\n      \n      eapply commutes_sound with (u_id1 := uid0) (u_id2 := uid) in H14; eauto; simpl.\n\n      split_ex; subst.\n      unfold build_data_step in H14; destruct ru.\n      dt x14; dt x15; destruct x16; simpl in *.\n\n      (do 2 eexists); repeat simple apply conj; eauto.\n      econstructor 1; eauto.\n      econstructor; eauto.\n      econstructor 1; eauto.\n      econstructor 1; eauto.\n      \n    + destruct (uid ==n uid0); subst; clean_map_lookups; clear_mislabeled_steps.\n\n      destruct userData; unfold buildUniverse, build_data_step in *; simpl in *.\n\n      generalize H13; intros STEP\n      ; eapply step_limited_change_other_user_qmsgs with (uid := uid) (uid' := uid0) in STEP\n      ; eauto; split_ex.\n      rename x into msg_heap'.\n\n      specialize (IHstepsi _ _ H0); simpl in *.\n\n      eapply silent_step_commutes_noblock with (usrs := users ru) (usrs1' := usrs0) in H6; eauto.\n      2: clean_map_lookups; eauto.\n      split_ex.\n\n      generalize H6; intros SS; eapply IHstepsi in H6; eauto.\n      clear IHstepsi; split_ex; subst.\n\n      invert H6; clear_mislabeled_steps.\n\n      pose proof (useless_summary_summarizes protocol0).\n      eapply silent_step_na_commuting with (s := useless_summary) in SS; eauto\n      ; split_ex.\n      \n      eapply commutes_sound with (u_id1 := uid0) (u_id2 := uid) in H18; eauto; simpl.\n\n      split_ex; subst.\n      unfold build_data_step in H18; destruct ru.\n      dt x14; dt x15; destruct x16; simpl in *.\n\n      destruct (classic (labels_align (buildUniverse usrs2 adv2 cs2 gks2 uid\n                {|\n                key_heap := ks2;\n                protocol := cmd2;\n                msg_heap := qmsgs2;\n                c_heap := mycs2;\n                from_nons := froms2;\n                sent_nons := sents2;\n                cur_nonce := cur_n2 |}, iu, b0))).\n\n      * (do 2 eexists); repeat simple apply conj; eauto.\n        econstructor 1; eauto.\n        econstructor; eauto.\n        econstructor 2; eauto; simpl in *.\n        \n        unfold goodness_predicates in *; split_ex; simpl in *.\n        specialize (H2 _ _ _ H5 eq_refl); split_ex.\n        eapply action_matches_other_user_silent_step; eauto.\n\n      * destruct x11 as [[ru1 iu1] b1].\n        (do 2 eexists); repeat simple apply conj;\n          [ solve [ econstructor 1; eauto ]\n          | econstructor\n          | ..\n          ].\n        econstructor 3; eauto.\n        rewrite H25; eapply falsify_trace; eauto.\n        eauto.\n        destruct st'' as [p b2]; simpl.\n        destruct b2; eauto.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups; clear_mislabeled_steps.\n\n      destruct userData; unfold buildUniverse, build_data_step in *; simpl in *.\n\n      generalize H12; intros STEP\n      ; eapply step_limited_change_other_user_qmsgs with (uid := uid) (uid' := uid0) in STEP\n      ; eauto; split_ex.\n      rename x into msg_heap'.\n\n      specialize (IHstepsi _ _ H0); simpl in *.\n\n      eapply silent_step_commutes_noblock with (usrs := users ru) (usrs1' := usrs0) in H6; eauto.\n      2: clean_map_lookups; eauto.\n      split_ex.\n\n      generalize H6; intros SS; eapply IHstepsi in H6; eauto.\n      clear IHstepsi; split_ex; subst.\n\n      invert H6; clear_mislabeled_steps.\n\n      pose proof (useless_summary_summarizes protocol0).\n      eapply silent_step_na_commuting with (s := useless_summary) in SS; eauto\n      ; split_ex.\n      \n      eapply commutes_sound with (u_id1 := uid0) (u_id2 := uid) in H17; eauto; simpl.\n\n      split_ex; subst.\n      unfold build_data_step in H17; destruct ru.\n      dt x14; dt x15; destruct x16; simpl in *.\n\n      eapply silent_step_labels_still_misaligned with (b := b0) (b' := b0) in H11; eauto.\n\n      destruct x11 as [[ru1 iu1] b1].\n      simpl in *.\n      (do 2 eexists); repeat simple apply conj.\n      econstructor 1; eauto.\n      econstructor; eauto.\n      econstructor 3; eauto.\n      all: eauto.\n\n    + destruct (uid ==n uid0); subst; clean_map_lookups; clear_mislabeled_steps.\n\n      destruct userData; unfold buildUniverse, build_data_step in *; simpl in *.\n\n      generalize H12; intros STEP\n      ; eapply step_limited_change_other_user_qmsgs with (uid := uid) (uid' := uid0) in STEP\n      ; eauto; split_ex.\n      rename x into msg_heap'.\n\n      specialize (IHstepsi _ _ H0); simpl in *.\n\n      eapply silent_step_commutes_noblock with (usrs := users ru) (usrs1' := usrs0) in H6; eauto.\n      2: clean_map_lookups; eauto.\n      split_ex.\n\n      generalize H6; intros SS; eapply IHstepsi in H6; eauto.\n      clear IHstepsi; split_ex; subst.\n\n      invert H6; clear_mislabeled_steps.\n\n      pose proof (useless_summary_summarizes protocol0).\n      eapply silent_step_na_commuting with (s := useless_summary) in SS; eauto\n      ; split_ex.\n      \n      eapply commutes_sound with (u_id1 := uid0) (u_id2 := uid) in H17; eauto; simpl.\n\n      split_ex; subst.\n      unfold build_data_step in H17; destruct ru.\n      dt x14; dt x15; destruct x16; simpl in *.\n\n      eapply silent_step_labels_still_misaligned with (b := b0) (b' := b0) in H11; eauto.\n\n      destruct x11 as [[ru1 iu1] b1].\n      simpl in *.\n      (do 2 eexists); repeat simple apply conj.\n      econstructor 1; eauto.\n      econstructor; eauto.\n      econstructor 4; eauto.\n      all: eauto.\n\nQed.\n\n#[export] Hint Constructors indexedRealStep indexedIdealStep : core.\n\nLemma step_extra_user :\n  forall A B C lbl suid bd bd',\n    @step_user A B C lbl suid bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' uid cmdc,\n\n      suid = Some uid\n      -> usrs $? uid = Some (mkUserData ks cmdc qmsgs mycs froms sents cur_n)\n      -> bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n\n      -> forall uid' ud',\n          ~ In uid' usrs\n          -> exists bd'',\n            step_user lbl (Some uid)\n                      (usrs $+ (uid',ud'), adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n                      bd''.\nProof.\n  induction 1; inversion 3; inversion 1; intros; subst\n  ; try solve [ eexists; econstructor; eauto ]\n  ; clean_context.\n\n  eapply IHstep_user in H1; eauto.\n  split_ex.\n  dt x; eexists; econstructor; eauto.\n\n  Unshelve.\n  all: auto.\nQed.\n\nLemma silent_step_minus_user :\n  forall A B C lbl suid bd bd',\n    @step_user A B C lbl suid bd bd'\n\n    -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n        (cmd cmd' : user_cmd C) ks ks' qmsgs qmsgs' mycs mycs'\n        froms froms' sents sents' cur_n cur_n' uid cmdc uid' ud',\n\n      ~ In uid' usrs\n      -> suid = Some uid\n      -> lbl = Silent\n      -> usrs $? uid = Some (mkUserData ks cmdc qmsgs mycs froms sents cur_n)\n      -> bd = (usrs $+ (uid',ud'), adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n      -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd')\n\n      -> exists bd'',\n          step_user lbl (Some uid)\n                    (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n                    bd''.\nProof.\n  induction 1; inversion 5; inversion 1; intros; subst\n  ; try discriminate\n  ; try solve [ eexists; econstructor; eauto ]\n  ; clean_context.\n\n  eapply IHstep_user in H3; eauto.\n  split_ex.\n  dt x; eexists; econstructor; eauto.\n\n  Unshelve.\n  all: auto.\nQed.\n\nLemma must_be_max_silent_step' :\n  forall A B usrs adv cs gks ks qmsgs mycs froms sents cur_n cmd uid bd,\n    usrs $? uid = Some (mkUserData ks cmd qmsgs mycs froms sents cur_n)\n    -> @step_user A B (Base A) Silent (Some uid) (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd) bd\n    -> exists uid__max U__max',\n        indexedRealStep uid__max Silent\n                        {| users := usrs; adversary := adv; all_ciphers := cs; all_keys := gks |} U__max'\n        /\\ (forall uid' U',\n              uid' > uid__max ->\n              ~ indexedRealStep uid' Silent\n                {| users := usrs; adversary := adv; all_ciphers := cs; all_keys := gks |} U').\nProof.\n  intros A B usrs.\n  induction usrs using O.map_induction_max; intros.\n\n  - unfold Empty, Raw.Empty in H.\n    rewrite <- find_mapsto_iff in H0.\n    unfold MapsTo in H0.\n    exfalso.\n    eapply H; eauto.\n\n  - unfold Add in H0.\n\n    destruct (x ==n uid); subst; clean_map_lookups; eauto.\n\n    + dt bd.\n      clear IHusrs1.\n      exists uid; eexists.\n      split.\n      econstructor; eauto.\n      unfold not; intros.\n      invert H4; simpl in *.\n      unfold O.Above in H.\n      specialize (H uid').\n      specialize (H0 uid'); clean_map_lookups.\n      destruct (uid ==n uid'); subst; try Nat.order.\n      clean_map_lookups.\n      assert (usrs1 $? uid' <> None) by (clean_map_lookups; eauto).\n      rewrite <- in_find_iff in H4.\n      apply H in H4; lia.\n\n    + rewrite H0 in H1; clean_map_lookups.\n      assert (usrs2 = usrs1 $+ (x,e))\n        by (apply map_eq_Equal; unfold Equal; eauto).\n      subst.\n\n      unfold O.Above in H.\n      destruct ( classic (In x usrs1) ).\n      apply H in H3; lia.\n\n      dt bd; pose proof (silent_step_minus_user H2 H3 eq_refl eq_refl H1 eq_refl eq_refl).\n      split_ex.\n      dt x0.\n\n      generalize H4; intros; eapply IHusrs1 in H4; eauto.\n      clear IHusrs1.\n      split_ex.\n\n      invert H4; simpl in *.\n      destruct (x ==n x0); subst; clean_map_lookups.\n      destruct userData\n      ; unfold build_data_step in *\n      ; simpl in *.\n\n      destruct ( classic ( exists U', indexedRealStep x Silent (mkUniverse (usrs1 $+ (x,e)) adv cs gks) U' )).\n      split_ex.\n\n      * exists x; eexists.\n        split; eauto.\n\n        unfold not; intros.\n        invert H10; simpl in *.\n        destruct (x ==n uid'); try lia; clean_map_lookups; eauto.\n        assert (usrs1 $? uid' <> None) by (clean_map_lookups).\n        rewrite <- in_find_iff in H10.\n        apply H in H10; lia.\n        \n      * eapply step_extra_user in H8; split_ex; eauto.\n        dt x1.\n        exists x0; eexists.\n        split.\n        econstructor; unfold build_data_step; simpl; eauto.\n\n        intros.\n        destruct (uid' ==n x); subst; clean_map_lookups.\n        ** firstorder idtac.\n        ** unfold not; intros.\n           invert H10.\n           destruct userData; unfold build_data_step in *; simpl in *; clean_map_lookups.\n           eapply silent_step_minus_user in H12; eauto.\n           split_ex; eauto.\n           dt x1.\n           \n           eapply H6 in H9; eauto.\n\nQed.\n\nLemma must_be_max_silent_step :\n  forall A B uid U U',\n    @indexedRealStep A B uid Silent U U'\n    -> exists uid__max U__max',\n        indexedRealStep uid__max Silent U U__max'\n        /\\ (forall uid' U',\n              uid' > uid__max ->\n              ~ indexedRealStep uid' Silent U U').\nProof.\n  intros.\n  invert H.\n  destruct U; destruct userData\n  ; simpl in *\n  ; eauto using must_be_max_silent_step'.\nQed.\n\nLemma violations_translate :\n  forall t__hon t__adv n st st' b summaries,\n    stepsi n st st'\n    -> lameAdv b (fst (fst st)).(adversary)\n    -> goodness_predicates (fst (fst st))\n    -> syntactically_safe_U (fst (fst st))\n    -> summarize_univ (fst (fst st)) summaries\n    -> (forall st'', step st' st'' -> False)\n    -> ~ ( no_resends_U (fst (fst st')) /\\ alignment st' /\\ returns_align st')\n    -> exists st'',\n        (@stepSS t__hon t__adv)^* st st''\n        /\\ ~ (no_resends_U (fst (fst st'')) /\\ alignment st'' /\\ returns_align st'').\nProof.\n  induct n; intros.\n\n  invert H; eexists; split; eauto.\n\n  destruct (\n      classic (exists uid U', indexedRealStep uid Silent (fst (fst st)) U')\n    ).\n\n  - split_ex.\n    \n    pose proof (must_be_max_silent_step H6); split_ex; clear x x0 H6.\n    invert H7.\n    eapply translate_trace_commute in H; eauto.\n\n    split_ex; subst.\n    generalize H; intros; eapply progress_predicates in H; eauto; split_ex.\n\n    eapply IHn in H7;\n      eauto using model_stuck_carent_alignment_bit,\n                  violated_predicates_remain_violated;\n      split_ex.\n\n    exists x2; split; eauto.\n    eapply TrcFront; eauto.\n    destruct st as [[ru iu] v].\n    destruct x  as [[ru' iu'] v'].\n    simpl in *.\n\n    econstructor.\n    2-3: reflexivity.\n    econstructor 1; eauto.\n\n    unfold build_data_step in *; simpl in *; eauto.\n    \n  - invert H.\n\n    generalize H8; intros SS; \n      eapply syntactically_safe_U_preservation_step in SS; eauto.\n\n    assert (SSU : syntactically_safe_U (fst (fst st'0))) by eauto using syntactically_safe_U_preservation_step.\n    assert (GOODNESS : goodness_predicates (fst (fst st'0))) by eauto using goodness_preservation_step.\n\n    eapply IHn in H9; eauto using summarize_univ_step.\n    repeat match goal with\n           | [ H : goodness_predicates _ |- _ ] => clear H\n           | [ H : syntactically_safe_U _ |- _ ] => clear H\n           end.\n    firstorder idtac.\n    simpl in *.\n\n    exists x.\n    unfold not; split; intros; split_ex; eauto 8.\n    eapply TrcFront; eauto.\n    destruct st as [[ru iu] v], st'0 as [[ru0' iu0'] v0'].\n\n    generalize H8; intros STEP; invert H8;\n      match goal with\n      | [ H : step_universe _ _ _ _ |- _ ] => invert H\n      | [ H : indexedRealStep _ _ _ _ |- _ ] => invert H\n      end.\n\n    + specialize (H5 u_id); firstorder idtac.\n      unfold mkULbl in H10; destruct lbl; try discriminate.\n      exfalso.\n      eapply H5; simpl.\n      econstructor; eauto.\n\n    + destruct ru; unfold build_data_step, lameAdv in *; simpl in *.\n      rewrite H0 in H6; invert H6.\n\n    + econstructor; eauto.\n      econstructor 2; eauto.\n\n    + econstructor; eauto.\n      econstructor 2; eauto.\n\n    + econstructor; eauto.\n      econstructor 2; eauto.\nQed.\n\nLemma complete_trace :\n  forall t__hon t__adv n' n st b,\n    runningTimeMeasure (fst (fst st)) n\n    -> n <= n'\n    -> lameAdv b (fst (fst st)).(adversary)\n    -> exists st',\n        (@step t__hon t__adv) ^* st st'\n      /\\ (forall st'', step st' st'' -> False).\n\nProof.\n  induct n'; intros.\n  - invert H; simpl in *.\n\n    exists st; split; intros; eauto.\n    destruct st as [[ru iu] v].\n    destruct ru; simpl in *; subst.\n    destruct n__rt; try lia.\n\n    invert H.\n    \n    + invert H7; dismiss_adv; simpl in *.\n      eapply boundRunningTime_for_element in H2; eauto; split_ex.\n      destruct x; try lia.\n      invert H2.\n      unfold build_data_step in *; rewrite <- H9 in H3; invert H3.\n\n    + invert H6; simpl in *.\n      eapply boundRunningTime_for_element in H2; eauto; split_ex.\n      destruct x; try lia.\n      invert H2.\n      unfold build_data_step in *; rewrite <- H12 in H3; invert H3.\n    \n    + invert H6; simpl in *.\n      eapply boundRunningTime_for_element in H2; eauto; split_ex.\n      destruct x; try lia.\n      invert H2.\n      unfold build_data_step in *; rewrite <- H11 in H3; invert H3.\n\n    + invert H6; simpl in *.\n      eapply boundRunningTime_for_element in H2; eauto; split_ex.\n      destruct x; try lia.\n      invert H2.\n      unfold build_data_step in *; rewrite <- H11 in H3; invert H3.\n\n  - destruct (classic (exists st', step st st')).\n    + split_ex.\n      rename x into st'.\n      assert (LAME' : lameAdv b (fst (fst st')).(adversary)) by eauto using adversary_remains_lame_step.\n      eapply runningTimeMeasure_step in H; eauto; split_ex.\n\n      eapply IHn' in H; try lia; eauto.\n      split_ex.\n      exists x0; split; intros; eauto.\n\n    + firstorder idtac; simpl in *.\n      exists st; split; intros; eauto.\nQed.\n\n#[export] Hint Resolve  goodness_preservation_step syntactically_safe_U_preservation_step : core.\n\nLemma many_steps_stays_lame :\n  forall t__hon t__adv st st' b,\n    (@step t__hon t__adv) ^* st st'\n    -> lameAdv b (adversary (fst (fst st)))\n    -> lameAdv b (adversary (fst (fst st'))).\nProof.\n  induction 1;\n    intros;\n    simpl in *;\n    eauto.\nQed.\n\nLemma many_steps_syntactically_safe :\n  forall t__hon t__adv st st',\n    (@step t__hon t__adv) ^* st st'\n    -> syntactically_safe_U (fst (fst st))\n    -> goodness_predicates (fst (fst st))\n    -> syntactically_safe_U (fst (fst st')).\nProof.\n  induction 1;\n    intros;\n    simpl in *;\n    eauto.\nQed.\n\nLemma many_steps_stays_good :\n  forall t__hon t__adv st st',\n    (@step t__hon t__adv) ^* st st'\n    -> goodness_predicates (fst (fst st))\n    -> syntactically_safe_U (fst (fst st))\n    -> goodness_predicates (fst (fst st')).\nProof.\n  induction 1;\n    intros;\n    simpl in *;\n    eauto.\nQed.\n\n#[export] Hint Resolve many_steps_stays_lame many_steps_syntactically_safe many_steps_stays_good : core.\n\nLocate safety.\n\nTheorem step_stepSS' :\n  forall {t__hon t__adv} (ru0 : RealWorld.universe t__hon t__adv) (iu0 : IdealWorld.universe t__hon) b n summaries,\n    runningTimeMeasure ru0 n\n    -> goodness_predicates ru0\n    -> syntactically_safe_U ru0\n    -> summarize_univ ru0 summaries\n    -> lameAdv b ru0.(adversary)\n    -> invariantFor (TrSS ru0 iu0) (fun st => no_resends_U (fst (fst st)) /\\ alignment st /\\ returns_align st)\n    -> invariantFor (TrS ru0 iu0) (fun st => no_resends_U (fst (fst st)) /\\ alignment st /\\ returns_align st)\n.\nProof.\n  intros * RUNTIME GOOD SYN_SAFE SUMM LAME INV.\n\n  apply NNPP; unfold not; intros INV'.\n  unfold invariantFor in INV'.\n  apply not_all_ex_not in INV'; split_ex.\n  apply imply_to_and in H; split_ex.\n  apply not_all_ex_not in H0; split_ex.\n  apply imply_to_and in H0; split_ex.\n  simpl in H; split_ors; try contradiction.\n  destruct x0 as [[?ru ?iu] ?v].\n\n  subst; simpl in *.\n\n  assert (exists n', runningTimeMeasure (fst (fst (ru, iu, v))) n' /\\ n' <= n)\n    by eauto using runningTimeMeasure_steps; split_ex.\n  \n  eapply complete_trace in H; eauto; split_ex.\n  specialize (trc_trans H0 H); intros.\n  apply steps_stepsi in H4; split_ex.\n\n  unfold invariantFor in INV; simpl in *.\n  eapply violations_translate in H4; eauto; split_ex.\n  apply INV in H4; eauto; split_ex.\n\n  eapply not_and_or in H1\n  ; destruct H1 as [H1 | H1]\n  ; [ | eapply not_and_or in H1]\n  ; split_ors\n  ; simpl\n  ; unfold not; intros; split_ex.\n\n  - assert (~ no_resends_U (fst (fst x0)))\n      by eauto using resend_violation_steps\n    ; contradiction.\n  \n  - assert (~ alignment x0)\n      by eauto using alignment_violation_steps\n    ; contradiction.\n\n  - assert (~ returns_align x0)\n      by eauto using final_alignment_violation_steps\n    ; contradiction.\nQed.\n\nLemma ss_implies_next_safe :\n  forall t (cmd : user_cmd t) uid ctx uids sty cs,\n    syntactically_safe uid uids ctx cmd sty\n    -> forall A B (usrs usrs' : honest_users A) (adv adv' : user_data B) cmd'\n        cs' gks gks' ks ks' qmsgs qmsgs' mycs mycs' froms froms' sents sents' n n' lbl,\n      step_user lbl (Some uid)\n                (usrs,adv,cs,gks,ks,qmsgs,mycs,froms,sents,n,cmd)\n                (usrs',adv',cs',gks',ks',qmsgs',mycs',froms',sents',n',cmd')\n      -> typingcontext_sound ctx usrs cs uid\n      -> uids = compute_ids usrs\n      -> forall t__n (cmd__n : user_cmd t__n), nextAction cmd cmd__n\n      -> (forall r, cmd__n <> Return r)\n      -> no_resends sents'\n      -> next_cmd_safe (findUserKeys usrs) cs uid froms sents cmd.\nProof.\n  induct cmd;\n    unfold next_cmd_safe; intros;\n      match goal with\n      | [ H : nextAction _ _ |- _ ] => invert H\n      end; eauto;\n        try solve [ unfold typingcontext_sound in *; split_ex;\n                    match goal with\n                    | [ H : syntactically_safe _ _ _ _ _ |- _ ] => invert H\n                    end; eauto ].\n\n  - invert H0.\n    invert H1; eauto.\n    invert H4.\n    eapply IHcmd in H7; eauto.\n    eapply H7 in H11; eauto.\n\n    invert H11; trivial.\n\n  - unfold typingcontext_sound in *; split_ex; invert H.\n    apply H2 in H11; split_ex; subst.\n    apply H1 in H10.\n    unfold msg_honestly_signed, msg_signing_key,\n           msg_to_this_user, msg_destination_user,\n           honest_keyb;\n      context_map_rewrites.\n    destruct ( cipher_to_user x0 ==n cipher_to_user x0 ); try contradiction.\n    repeat simple apply conj; eauto.\n    econstructor; eauto.\n    unfold msg_honestly_signed, msg_signing_key, honest_keyb;\n      context_map_rewrites;\n      trivial.\n    (do 2 eexists); repeat simple apply conj; eauto.\n    invert H0.\n    unfold no_resends, updateSentNonce in H5; context_map_rewrites.\n    destruct (cipher_to_user x0 ==n cipher_to_user x0); try contradiction.\n    invert H5; eauto.\n    \n  - unfold typingcontext_sound in *; split_ex; invert H; eauto.\n    intros.\n    apply H12 in H; split_ex; subst; eauto.\nQed.\n\nLemma step_na_recur :\n  forall t t__n (cmd : user_cmd t) (cmd__n : user_cmd t__n),\n    nextAction cmd cmd__n\n    -> forall A B suid lbl bd bd',\n\n      step_user lbl suid bd bd'\n\n      -> forall cs cs' (usrs usrs': honest_users A) (adv adv' : user_data B) gks gks'\n          cmd__n' ks ks' qmsgs qmsgs' mycs mycs'\n          froms froms' sents sents' cur_n cur_n',\n\n        bd = (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd__n)\n        -> bd' = (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd__n')\n        -> exists bd'',\n            step_user lbl suid (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd) bd''.\nProof.\n  induct 1; intros; subst;\n    eauto.\n\n  eapply IHnextAction in H0; eauto. split_ex.\n  simpl.\n\n  dt x; eexists; eapply StepBindRecur; eauto.\nQed.\n\nLemma ss_implies_next_safe_no_model_step :\n  forall A B (usrs : honest_users A) (adv : user_data B) cs gks\n    cmd uid ctx uids sty,\n\n    uids = compute_ids usrs\n    -> forall ks qmsgs mycs froms sents cur_n, usrs $? uid = Some (mkUserData ks cmd qmsgs mycs froms sents cur_n)\n    -> forall t__n (cmd__n : user_cmd t__n), nextAction cmd cmd__n\n    -> syntactically_safe uid uids ctx cmd sty\n    -> typingcontext_sound ctx usrs cs uid\n    -> forall ru iu, ru = mkUniverse usrs adv cs gks\n    -> (forall ru' iu', indexedModelStep uid (ru,iu,true) (ru',iu',true) -> False)\n    -> labels_align (ru,iu,true)\n    -> next_cmd_safe (findUserKeys usrs) cs uid froms sents cmd.\nProof.\n  intros.\n  cases cmd__n;\n    unfold next_cmd_safe; intros;\n      match goal with\n      | [ H1 : nextAction cmd _, H2 : nextAction cmd _ |- _ ] => eapply na_deterministic in H1; eauto\n      end; split_ex; subst; trivial.\n\n  Ltac xyz :=\n    repeat \n      match goal with\n      | [ NA : nextAction _ (Bind _ _) |- _ ] =>\n        eapply nextAction_couldBe in NA; contradiction\n      | [ SS : syntactically_safe _ _ _ ?cmd _, NA : nextAction ?cmd _ |- _ ] =>\n        eapply syntactically_safe_na in SS; eauto; split_ex\n      | [ SS : syntactically_safe _ _ _ _ _ |- _ ] =>\n        invert SS; unfold typingcontext_sound in *; split_ex; process_ctx\n      end.\n\n  all: xyz; eauto.\n\n  - exfalso.\n\n    assert (SEND : exists lbl bd,\n               step_user lbl\n                         (Some uid)\n                         (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, \n                          @Send t0 (cipher_to_user x0) (SignedCiphertext x)) bd).\n      (do 2 eexists); econstructor; clean_map_lookups; simpl in *; eauto.\n      context_map_rewrites; eauto.\n      unfold not; intros INV; invert INV; contradiction.\n      split_ex.\n\n      destruct x1.\n      invert H4.\n\n      dt x3.\n      eapply step_na_recur in H4; eauto; split_ex.\n      dt x1.\n\n      assert (exists ru', indexedRealStep uid (Action a)\n                                     (mkUniverse usrs adv cs gks)\n                                     ru')\n        by (eexists; econstructor; eauto). \n      \n      split_ex.\n      generalize (H6 _ _ _ H8); intros; split_ex.\n      eapply H5; clear H5.\n      econstructor 2; eauto.\n\n  - eapply H11 in H4; split_ex.\n    eapply H in H4; eauto.\nQed.\n\nLemma indexedModelStep_step :\n  forall t__hon t__adv uid st st',\n    @indexedModelStep t__hon t__adv uid st st'\n    -> step st st'.\nProof.\n  intros.\n  invert H; [\n    econstructor 1\n  | econstructor 2\n  | econstructor 3\n  | econstructor 4 ]; eauto.\n\n  invert H0; econstructor; eauto.\nQed.\n\nTheorem step_stepSS :\n  forall {t__hon t__adv} (ru0 : RealWorld.universe t__hon t__adv) (iu0 : IdealWorld.universe t__hon) b n summaries,\n    runningTimeMeasure ru0 n\n    -> goodness_predicates ru0\n    -> syntactically_safe_U ru0\n    -> summarize_univ ru0 summaries\n    -> lameAdv b ru0.(adversary)\n    -> invariantFor (TrS ru0 iu0) (fun st => no_resends_U (fst (fst st)) /\\ alignment st /\\ returns_align st)\n    -> invariantFor (TrS ru0 iu0) (fun st => safety st /\\ alignment st /\\ returns_align st)\n.\nProof.\n  unfold invariantFor; intros.\n  specialize (H4 _ H5).\n  generalize H6; intros STEPS; eapply H4 in H6; eauto.\n  split_ex; split; eauto.\n\n  destruct s' as [[ru' iu'] b'].\n  simpl in *; split_ex; subst.\n  split_ors; try contradiction; subst.\n\n  hnf in H7; split_ex; simpl in H5; subst.\n  assert (SS : syntactically_safe_U (fst (fst (ru', iu', true)))) by eauto.\n  unfold honest_cmds_safe; intros.\n\n  destruct (classic (exists st, indexedModelStep u_id (ru',iu',true) (st,true))).\n  - split_ex.\n    destruct x as [ru'' iu''].\n    pose proof (indexedModelStep_step H10) as STEP.\n    assert (STEPS' : (@step t__hon t__adv) ^* (ru',iu',true) (ru'',iu'',true)) by (eauto using TrcFront).\n    pose proof (trc_trans STEPS STEPS') as MORESTEPS.\n\n    specialize (H4 _ MORESTEPS); unfold no_resends_U in H4.\n    simpl in *; split_ex.\n\n    unfold syntactically_safe_U in SS;\n      specialize (SS _ _ _ H9 eq_refl); split_ex.\n\n    assert (exists lbl, indexedRealStep u_id lbl ru' ru'') by (invert H10; eauto).\n    split_ex.\n    invert H15.\n\n    unfold build_data_step, buildUniverse in *; simpl in *.\n    clean_map_lookups.\n\n    pose proof (na_always_exists (protocol userData)); split_ex.\n    destruct (classic (exists r, x3 = Return r)); split_ex; subst; eauto.\n    + unfold next_cmd_safe; intros.\n      eapply na_deterministic in H5; eauto.\n      split_ex; subst; trivial.\n\n    + rewrite Forall_natmap_forall in H4.\n      specialize (H4 u_id).\n      rewrite add_eq_o in H4 by trivial.\n      specialize (H4 _ eq_refl); simpl in H4.\n      eapply ss_implies_next_safe;\n        eauto.\n\n  - assert (forall st, indexedModelStep u_id (ru',iu',true) (st,true) -> False) by eauto using not_ex_all_not.\n    \n    subst.\n    clear H10.\n    unfold syntactically_safe_U in SS.\n      specialize (SS _ _ _ H9 eq_refl); split_ex.\n    simpl in *.\n\n    pose proof (na_always_exists (protocol u)); split_ex.\n    \n    destruct ru', u;\n      simpl in *;\n      eapply ss_implies_next_safe_no_model_step; eauto.\n\nQed.\n\nModule Type AutomatedSafeProtocolSS.\n  Parameter t__hon : type.\n  Parameter t__adv : type.\n  Parameter b : << Base t__adv >>.\n  Parameter iu0 : IdealWorld.universe t__hon.\n  Parameter ru0 : RealWorld.universe t__hon t__adv.\n  (* Parameter runTime : nat. *)\n  (* Parameter summaries : NatMap.t summary. *)\n\n  Notation SYS := (TrSS ru0 iu0).\n\n  Axiom U_good : universe_starts_sane b ru0.\n  Axiom universe_starts_safe : universe_ok ru0.\n\n  Axiom finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  (* Axiom finitelyRuns : runningTimeMeasure ru0 runTime. *)\n  Axiom typechecks : syntactically_safe_U ru0.\n  Axiom summarizable : exists summaries, summarize_univ ru0 summaries.\n  (* Axiom summarizable : summarize_univ ru0 summaries. *)\n  Axiom lameness : lameAdv b (adversary ru0).\n\n  Axiom safe_invariant : invariantFor\n                           SYS\n                           (fun st => no_resends_U (fst (fst st)) /\\ alignment st /\\ returns_align st).\nEnd AutomatedSafeProtocolSS.\n\nModule SSProtocolSimulates (Proto : AutomatedSafeProtocolSS).\n  Import Proto Simulation.\n\n  Module SSAutomatedSafeProtocol <: AutomatedSafeProtocol.\n    Definition t__hon := t__hon.\n    Definition t__adv := t__adv.\n    Definition b := b.\n    Definition iu0 := iu0.\n    Definition ru0 := ru0.\n\n    Lemma U_good : universe_starts_sane b ru0.\n    Proof. exact U_good. Qed.\n      \n    Lemma universe_starts_safe : universe_ok ru0.\n    Proof. exact universe_starts_safe. Qed.\n\n    Lemma goodness_predicates_ok : goodness_predicates ru0.\n    Proof. pose proof universe_starts_safe; unfold universe_ok, goodness_predicates, adv_goodness in *\n           ; intuition idtac.\n           \n           unfold adv_message_queue_ok in H4\n           ; rewrite Forall_forall in H4 |- *\n           ; intros * LIN\n           ; apply H4 in LIN.\n\n           - destruct x; split_ex; split; eauto.\n             intros.\n             apply H11 in H12; split_ex; eauto.\n           - unfold adv_cipher_queue_ok in H3\n             ; rewrite Forall_forall in H3 |- *\n             ; intros * LIN\n             ; apply H3 in LIN\n             ; split_ex\n             ; eauto.\n    Qed.\n\n    #[local] Hint Resolve goodness_predicates_ok : core.\n    #[local] Hint Resolve typechecks lameness Proto.safe_invariant : core.\n\n    Lemma safe_invariant :\n      invariantFor\n        (TrS ru0 iu0)\n        (fun st => safety st /\\ alignment st /\\ returns_align st).\n    Proof.\n      pose proof (@step_stepSS Proto.t__hon Proto.t__adv).\n      pose proof finitelyRuns.\n      pose proof summarizable.\n      split_ex.\n      eapply H; eauto.\n\n      pose proof (@step_stepSS' Proto.t__hon Proto.t__adv); eauto.\n    Qed.\n\n  End SSAutomatedSafeProtocol.\n\n  Module Import SSSimulates := ProtocolSimulates ( SSAutomatedSafeProtocol ).\n      \n  Lemma protocol_with_adversary_could_generate_spec :\n    forall U__ra advcode acts__r,\n      U__ra = add_adversary ru0 advcode\n      -> rCouldGenerate U__ra acts__r\n      -> exists acts__i,\n          iCouldGenerate iu0 acts__i\n          /\\ traceMatches acts__r acts__i.\n  Proof.\n    eauto using SSSimulates.protocol_with_adversary_could_generate_spec.\n  Qed.\n\nEnd SSProtocolSimulates.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/src/ModelCheck/SilentStepElimination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3007455726738824, "lm_q1q2_score": 0.15154754982967136}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom Coq Require Import Reals.\nFrom stdpp Require Import prelude.\nFrom VLSM.Lib Require Import Preamble StdppExtras StdppListFinSet FinSetExtras.\nFrom VLSM.Lib Require Import ListExtras ListSetExtras Measurable.\nFrom VLSM.Core Require Import VLSM AnnotatedVLSM MessageDependencies VLSMProjections Composition.\nFrom VLSM.Core Require Import Validator ProjectionTraces SubProjectionTraces Equivocation.\nFrom VLSM.Core Require Import Equivocation.FixedSetEquivocation.\nFrom VLSM.Core Require Import Equivocation.LimitedMessageEquivocation.\nFrom VLSM.Core Require Import Equivocation.MsgDepFixedSetEquivocation.\nFrom VLSM.Core Require Import Equivocation.TraceWiseEquivocation.\n\n(**\n  To allow capturing the two models of limited equivocation described in the\n  sections below, we first define a notion of limited equivocation parameterized\n  on a function yielding the set of equivocators induced by a received message,\n  other that the message sender.\n*)\n\nSection sec_coequivocating_senders_limited_equivocation.\n\nContext\n  {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  (A : validator -> index)\n  (sender : message -> option validator)\n  (coequivocating_senders : composite_state IM -> message -> Cv)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  .\n\nDefinition coeqv_message_equivocators (s : composite_state IM) (m : message)\n  : Cv :=\n  if decide (composite_has_been_directly_observed IM s m)\n  then (* no additional equivocation *)\n    \u2205\n  else (* m itself and all its non-observed dependencies are equivocating. *)\n    list_to_set (map_option sender [m] ++ (elements (coequivocating_senders s m))).\n\nDefinition coeqv_composite_transition_message_equivocators\n  (l : composite_label IM)\n  (som : annotated_state (free_composite_vlsm IM) Cv * option message)\n  : Cv :=\n  match som with\n  | (sa, None) => state_annotation sa\n  | (sa, Some m) =>\n    (state_annotation sa) \u222a (coeqv_message_equivocators (original_state sa) m)\n  end.\n\nDefinition coeqv_limited_equivocation_constraint\n  (l : composite_label IM)\n  (som : annotated_state (free_composite_vlsm IM) Cv * option message)\n  : Prop :=\n  (sum_weights (coeqv_composite_transition_message_equivocators l som) <= threshold)%R.\n\n#[export] Program Instance empty_validators_inhabited : Inhabited {s : Cv | s = \u2205} :=\n  populate (exist _ \u2205 _).\nNext Obligation.\nProof. done. Defined.\n\nDefinition coeqv_limited_equivocation_vlsm : VLSM message :=\n  annotated_vlsm (free_composite_vlsm IM) Cv (fun s => s = \u2205)\n    coeqv_limited_equivocation_constraint coeqv_composite_transition_message_equivocators.\n\nDefinition coeqv_annotate_trace_with_equivocators :=\n  annotate_trace (free_composite_vlsm IM) Cv (fun s => s = \u2205)\n    coeqv_composite_transition_message_equivocators.\n\nLemma coeqv_limited_equivocation_transition_state_annotation_incl [l s iom s' oom]\n  : vtransition coeqv_limited_equivocation_vlsm l (s, iom) = (s', oom) ->\n    state_annotation s \u2286 state_annotation s'.\nProof.\n  cbn; unfold annotated_transition; destruct (vtransition _ _ _) as (_s', _om').\n  inversion 1; cbn.\n  by destruct iom as [m |]; [apply union_subseteq_l |].\nQed.\n\nLemma coeqv_limited_equivocation_state_annotation_nodup s\n  : valid_state_prop coeqv_limited_equivocation_vlsm s ->\n    NoDup (elements (state_annotation s)).\nProof.\n  induction 1 using valid_state_prop_ind.\n  - by destruct s, Hs as [_ ->]; cbn in *; apply NoDup_elements.\n  - destruct Ht as [_ Ht]; cbn in Ht.\n    unfold annotated_transition in Ht\n    ; destruct (vtransition _ _ _); inversion Ht; apply NoDup_elements.\nQed.\n\nLemma coeqv_limited_equivocation_state_not_heavy s\n  : valid_state_prop coeqv_limited_equivocation_vlsm s ->\n    (sum_weights (state_annotation s) <= threshold)%R.\nProof.\n  induction 1 using valid_state_prop_ind.\n  - destruct s, Hs as [_ ->]; cbn in *.\n    rewrite sum_weights_empty; [| done].\n    by apply (rt_positive (H6 := H7)).\n  - destruct Ht as [(_ & _ & _ & Hc) Ht]\n    ; cbn in Ht; unfold annotated_transition in Ht; destruct (vtransition _ _ _)\n    ; inversion_clear Ht.\n    by destruct om as [m |].\nQed.\n\nDefinition coeqv_limited_equivocation_projection_validator_prop : index -> Prop :=\n  annotated_projection_validator_prop IM (fun s => s = \u2205)\n    coeqv_limited_equivocation_constraint coeqv_composite_transition_message_equivocators.\n\nDefinition coeqv_limited_equivocation_message_validator_prop : index -> Prop :=\n  annotated_message_validator_prop IM (fun s => s = \u2205)\n    coeqv_limited_equivocation_constraint coeqv_composite_transition_message_equivocators.\n\nDefinition coeqv_limited_equivocation_projection_validator_prop_alt : index -> Prop :=\n  annotated_projection_validator_prop_alt IM (fun s => s = \u2205)\n    coeqv_limited_equivocation_constraint coeqv_composite_transition_message_equivocators.\n\nEnd sec_coequivocating_senders_limited_equivocation.\n\nSection sec_msg_dep_limited_equivocation.\n\nContext\n  {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  `{FinSet message Cm}\n  (full_message_dependencies : message -> Cm)\n  (A : validator -> index)\n  (sender : message -> option validator)\n  .\n\nDefinition not_directly_observed_happens_before_dependencies (s : composite_state IM) (m : message)\n  : Cm :=\n  filter (fun dm => ~ composite_has_been_directly_observed IM s dm) (full_message_dependencies m).\n\nDefinition msg_dep_coequivocating_senders (s : composite_state IM) (m : message)\n  : Cv :=\n  list_to_set (map_option sender (elements (not_directly_observed_happens_before_dependencies s m))).\n\nDefinition msg_dep_limited_equivocation_vlsm : VLSM message :=\n  coeqv_limited_equivocation_vlsm IM threshold sender msg_dep_coequivocating_senders.\n\nDefinition msg_dep_message_equivocators :=\n  coeqv_message_equivocators IM sender msg_dep_coequivocating_senders.\n\nDefinition msg_dep_annotate_trace_with_equivocators :=\n  coeqv_annotate_trace_with_equivocators IM sender msg_dep_coequivocating_senders.\n\nLemma msg_dep_annotate_trace_with_equivocators_app : forall sa tr1 tr2,\n  msg_dep_annotate_trace_with_equivocators sa (tr1 ++ tr2)\n    =\n  msg_dep_annotate_trace_with_equivocators sa tr1 ++\n    annotate_trace_from (free_composite_vlsm IM) Cv\n      (coeqv_composite_transition_message_equivocators IM sender msg_dep_coequivocating_senders)\n      (@finite_trace_last _ (annotated_type (free_composite_vlsm IM) Cv)\n        {| original_state := sa; state_annotation := ` inhabitant |}\n        (msg_dep_annotate_trace_with_equivocators sa tr1)) tr2.\nProof. by intros; apply annotate_trace_from_app. Qed.\n\nLemma msg_dep_annotate_trace_with_equivocators_last_original_state : forall s s' tr,\n  original_state (finite_trace_last s (msg_dep_annotate_trace_with_equivocators s' tr))\n    =\n  finite_trace_last (original_state s) tr.\nProof. by intros; apply annotate_trace_from_last_original_state. Qed.\n\nDefinition msg_dep_composite_transition_message_equivocators :=\n  coeqv_composite_transition_message_equivocators IM sender msg_dep_coequivocating_senders.\n\nDefinition msg_dep_limited_equivocation_projection_validator_prop :=\n  coeqv_limited_equivocation_projection_validator_prop IM threshold sender msg_dep_coequivocating_senders.\n\nDefinition msg_dep_limited_equivocation_message_validator_prop :=\n  coeqv_limited_equivocation_message_validator_prop IM threshold sender msg_dep_coequivocating_senders.\n\nDefinition msg_dep_limited_equivocation_projection_validator_prop_alt :=\n  coeqv_limited_equivocation_projection_validator_prop_alt IM threshold sender msg_dep_coequivocating_senders.\n\nLemma msg_dep_annotate_trace_with_equivocators_project s tr\n  : pre_VLSM_embedding_finite_trace_project (type msg_dep_limited_equivocation_vlsm)\n    (composite_type IM) Datatypes.id original_state\n    (msg_dep_annotate_trace_with_equivocators s tr) = tr.\nProof. by apply (annotate_trace_project (free_composite_vlsm IM) Cv). Qed.\n\nEnd sec_msg_dep_limited_equivocation.\n\nSection sec_full_node_limited_equivocation.\n\nContext\n  {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  (A : validator -> index)\n  (sender : message -> option validator)\n  .\n\nDefinition full_node_coequivocating_senders (s : composite_state IM) (m : message)\n  : Cv := \u2205.\n\nDefinition full_node_limited_equivocation_vlsm : VLSM message :=\n  coeqv_limited_equivocation_vlsm IM threshold sender full_node_coequivocating_senders.\n\nEnd sec_full_node_limited_equivocation.\n\nSection sec_full_node_msg_dep_limited_equivocation_equivalence.\n\nContext\n  {message : Type}\n  `{FinSet message Cm}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (full_message_dependencies : message -> Cm)\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  `{!LeibnizEquiv Cv}\n  (A : validator -> index)\n  (sender : message -> option validator)\n  (message_dependencies : message -> Cm)\n  `{!FullMessageDependencies message_dependencies full_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  (Limited := msg_dep_limited_equivocation_vlsm IM threshold full_message_dependencies sender (Cv := Cv))\n  (FullNodeLimited := full_node_limited_equivocation_vlsm IM threshold sender (Cv := Cv))\n  .\n\nLemma full_node_msg_dep_coequivocating_senders s m i li\n  (Hvalid : input_valid (pre_loaded_with_all_messages_vlsm (IM i)) li (s i, Some m))\n  : msg_dep_coequivocating_senders IM full_message_dependencies sender s m \u2261@{Cv} \u2205.\nProof.\n  intro; split; intro Hx; [| by contradict Hx; apply not_elem_of_empty].\n  exfalso; contradict Hx.\n  unfold msg_dep_coequivocating_senders.\n  rewrite elem_of_list_to_set, elem_of_map_option.\n  setoid_rewrite elem_of_elements; setoid_rewrite elem_of_filter.\n  intros (dm & [Hnobs Hdm]  & _).\n  contradict Hnobs; exists i.\n  eapply msg_dep_full_node_input_valid_happens_before_has_been_directly_observed;\n    [by typeclasses eauto | by apply Hfull | done |].\n  by apply full_message_dependencies_happens_before.\nQed.\n\nLemma annotated_free_input_valid_projection\n  iprop `{Inhabited (sig iprop)} constr trans\n  i li s om\n  : input_valid (annotated_vlsm (free_composite_vlsm IM) Cv iprop constr trans)\n      (existT i li) (s, om) ->\n    input_valid (pre_loaded_with_all_messages_vlsm (IM i)) li (original_state s i, om).\nProof.\n  intro Hvalid.\n  eapply (VLSM_projection_input_valid (preloaded_component_projection IM i))\n  ; [by apply (composite_project_label_eq IM) |].\n  by apply\n    (VLSM_incl_input_valid (vlsm_incl_pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM))),\n    (VLSM_embedding_input_valid (forget_annotations_projection (free_composite_vlsm IM) _ _ _)).\nQed.\n\nLemma full_node_msg_dep_composite_transition_message_equivocators\n  i li (s : @state _ (annotated_type (free_composite_vlsm IM) Cv)) om\n  (Hvalid : input_valid (pre_loaded_with_all_messages_vlsm (IM i)) li (original_state s i, om))\n  : coeqv_composite_transition_message_equivocators\n      IM sender (full_node_coequivocating_senders IM)\n      (existT i li) (s, om)\n      \u2261\n    msg_dep_composite_transition_message_equivocators\n      IM full_message_dependencies sender\n      (existT i li) (s, om).\nProof.\n  destruct om as [m |]; cbn; [| done].\n  apply sets.union_proper; [done |].\n  unfold coeqv_message_equivocators, msg_dep_coequivocating_senders.\n  case_decide as Hobs; [done |].\n  remember (list_to_set (map_option _ _)) as equivs.\n  cut (equivs \u2261@{Cv} \u2205); [by intros -> |].\n  by subst; eapply full_node_msg_dep_coequivocating_senders.\nQed.\n\nLemma msg_dep_full_node_valid_iff\n  l (s : @state _ (annotated_type (free_composite_vlsm IM) Cv)) om\n  (Hvi : input_valid (pre_loaded_with_all_messages_vlsm (IM (projT1 l)))\n           (projT2 l) (original_state s (projT1 l), om))\n  : vvalid Limited l (s, om) <-> vvalid FullNodeLimited l (s, om).\nProof.\n  cbn; unfold annotated_valid, coeqv_limited_equivocation_constraint; destruct l as [i li].\n  replace (sum_weights _) with\n    (sum_weights\n      (coeqv_composite_transition_message_equivocators IM sender\n        (full_node_coequivocating_senders IM) (existT i li)\n        (s, om)));\n    [done |].\n  by apply sum_weights_proper, full_node_msg_dep_composite_transition_message_equivocators.\nQed.\n\nLemma msg_dep_full_node_transition_iff\n  l (s : @state _ (annotated_type (free_composite_vlsm IM) Cv)) om\n  (Hvi : input_valid (pre_loaded_with_all_messages_vlsm (IM (projT1 l)))\n           (projT2 l) (original_state s (projT1 l), om))\n  : vtransition Limited l (s, om) = vtransition FullNodeLimited l (s, om).\nProof.\n  cbn; unfold annotated_transition;\n    destruct (vtransition _ _ _) as (s', om'), l as (i, li).\n  do 2 f_equal.\n  destruct om as [m |]; [| done].\n  symmetry.\n  by apply leibniz_equiv, full_node_msg_dep_composite_transition_message_equivocators.\nQed.\n\nLemma msg_dep_full_node_limited_equivocation_vlsm_incl :\n  VLSM_incl Limited FullNodeLimited.\nProof.\n  apply basic_VLSM_incl.\n  - by intros s Hs.\n  - by intros _ _ m _ _ Hinit; apply initial_message_is_valid.\n  - intros [i li] s om HvX _ _.\n    apply msg_dep_full_node_valid_iff; [| apply HvX].\n    by eapply annotated_free_input_valid_projection.\n  - intros [i li] s iom s' oom [Hv Ht]; cbn in Ht |- *; rewrite <- Ht.\n    symmetry; rapply msg_dep_full_node_transition_iff.\n    by eapply annotated_free_input_valid_projection.\nQed.\n\nLemma full_node_msg_dep_limited_equivocation_vlsm_incl :\n  VLSM_incl FullNodeLimited Limited.\nProof.\n  apply basic_VLSM_incl.\n  - by intros s Hs.\n  - by intros _ _ m _ _ Hinit; apply initial_message_is_valid.\n  - intros [i li] s om HvX _ _.\n    apply msg_dep_full_node_valid_iff; [| apply HvX].\n    by eapply annotated_free_input_valid_projection.\n  - intros [i li] s iom s' oom [Hv Ht]; cbn in Ht |- *; rewrite <- Ht.\n    rapply msg_dep_full_node_transition_iff.\n    by eapply annotated_free_input_valid_projection.\nQed.\n\nLemma full_node_msg_dep_limited_equivocation_vlsm_eq :\n  VLSM_eq FullNodeLimited Limited.\nProof.\n  split.\n  - by apply full_node_msg_dep_limited_equivocation_vlsm_incl.\n  - by apply msg_dep_full_node_limited_equivocation_vlsm_incl.\nQed.\n\nEnd sec_full_node_msg_dep_limited_equivocation_equivalence.\n\nSection sec_msg_dep_fixed_limited_equivocation.\n\nContext\n  {message : Type}\n  `{FinSet index Ci}\n  `{!finite.Finite index}\n  `{FinSet message Cm}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (message_dependencies : message -> Cm)\n  (full_message_dependencies : message -> Cm)\n  `{!FullMessageDependencies message_dependencies full_message_dependencies}\n  `{forall i, MessageDependencies (IM i) message_dependencies}\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  (sender : message -> option validator)\n  (A : validator -> index)\n  `{!Inj (=) (=) A}\n  (Limited := msg_dep_limited_equivocation_vlsm IM threshold full_message_dependencies sender (Cv := Cv))\n  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (Hchannel : channel_authentication_prop IM A sender)\n  (Hsender_safety : sender_safety_alt_prop IM A sender :=\n    channel_authentication_sender_safety _ _ _ Hchannel)\n  .\n\nLemma equivocating_messages_are_equivocator_emitted\n  s im\n  (Him : can_emit (free_composite_vlsm IM) im)\n  (Hnobserved : \u00ac composite_has_been_directly_observed IM s im) :\n    exists v : validator,\n      v \u2208 msg_dep_message_equivocators IM full_message_dependencies sender s im (Cv := Cv)\n        /\\\n      can_emit (pre_loaded_vlsm (IM (A v)) (fun dm => msg_dep_rel message_dependencies dm im)) im.\nProof.\n  eapply (VLSM_incl_can_emit (vlsm_incl_pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM)))\n      in Him.\n  apply can_emit_composite_project in Him as [j Him].\n  apply Hchannel in Him as Hsender.\n  unfold channel_authenticated_message in Hsender.\n  destruct (sender im) as [v |] eqn: Heq_sender; [| by inversion Hsender].\n  apply Some_inj in Hsender; cbn in Hsender; subst.\n  exists v; subst; cbn.\n  unfold msg_dep_message_equivocators, coeqv_message_equivocators,\n         msg_dep_coequivocating_senders, not_directly_observed_happens_before_dependencies.\n  rewrite decide_False by done; cbn.\n  split.\n  - by rewrite Heq_sender, elem_of_list_to_set, elem_of_app; left; left.\n  - by eapply message_dependencies_are_sufficient.\nQed.\n\nLemma equivocating_messages_dependencies_are_directly_observed_or_equivocator_emitted\n  s im\n  (Him : can_emit (free_composite_vlsm IM) im)\n  (Hnobserved : \u00ac composite_has_been_directly_observed IM s im)\n  : forall dm, msg_dep_happens_before message_dependencies dm im ->\n    composite_has_been_directly_observed IM s dm \\/\n    exists v_i, v_i \u2208 msg_dep_message_equivocators IM full_message_dependencies sender s im (Cv := Cv) /\\\n      can_emit (pre_loaded_with_all_messages_vlsm (IM (A v_i))) dm.\nProof.\n  intros dm Hdm.\n  destruct (decide (composite_has_been_directly_observed IM s dm)) as [Hobs | Hnobs]\n  ; [by left | right].\n  cut (exists v, sender dm = Some v /\\\n                 can_emit (pre_loaded_with_all_messages_vlsm (IM (A v))) dm).\n  {\n    intros (v & Hsender & Hemit).\n    exists v; split; [| done].\n    unfold msg_dep_message_equivocators, coeqv_message_equivocators,\n      msg_dep_coequivocating_senders, not_directly_observed_happens_before_dependencies.\n    rewrite decide_False, elem_of_list_to_set, elem_of_app, elem_of_elements,\n      elem_of_list_to_set, !elem_of_map_option by done.\n    right; exists dm.\n    rewrite elem_of_elements, elem_of_filter.\n    by setoid_rewrite full_message_dependencies_happens_before.\n  }\n  apply emitted_messages_are_valid in Him.\n  by eapply msg_dep_happens_before_composite_no_initial_valid_messages_emitted_by_sender.\nQed.\n\nLemma message_equivocators_can_emit (s : vstate Limited) im\n  (Hs : valid_state_prop\n          (fixed_equivocation_vlsm_composition IM (Ci := Ci) (fin_sets.set_map A (state_annotation s)))\n          (original_state s))\n  (Hnobserved : \u00ac composite_has_been_directly_observed IM (original_state s) im)\n  (HLemit : can_emit (free_composite_vlsm IM) im)\n  : can_emit\n      (equivocators_composition_for_directly_observed IM (Ci := Ci)\n        (fin_sets.set_map A (state_annotation s\n            \u222a msg_dep_message_equivocators IM full_message_dependencies sender\n                (original_state s) im))\n        (original_state s))\n      im.\nProof.\n  eapply VLSM_embedding_can_emit.\n  - unshelve apply equivocators_composition_for_directly_observed_index_incl_embedding with\n      (indices1 := fin_sets.set_map A (msg_dep_message_equivocators IM (Cv := Cv)\n        full_message_dependencies sender (original_state s) im)).\n    intros x; rewrite !elem_of_elements.\n    by apply set_map_mono, union_subseteq_r.\n  - destruct (equivocating_messages_are_equivocator_emitted _ _ HLemit Hnobserved)\n      as (j & Heqv_j & Hemitj).\n    eapply sub_valid_preloaded_lifts_can_be_emitted;\n      [by apply elem_of_elements, elem_of_map_2 | | done].\n    cbn; intros dm H_dm.\n    assert (Hdm : msg_dep_happens_before message_dependencies dm im)\n        by (apply msg_dep_happens_before_iff_one; left; done).\n    clear H_dm; revert dm Hdm.\n    induction dm as [dm Hind] using\n      (well_founded_ind (msg_dep_happens_before_wf message_dependencies full_message_dependencies _))\n    ; intros Hdm.\n    apply emitted_messages_are_valid_iff.\n    destruct (equivocating_messages_dependencies_are_directly_observed_or_equivocator_emitted\n      _ _ HLemit Hnobserved _ Hdm)\n      as [Hobs_dm | (dm_i & Hdm_i & Hemit_dm)]\n    ; [by left; right | right].\n    eapply sub_valid_preloaded_lifts_can_be_emitted;\n      [by apply elem_of_elements, elem_of_map_2 | | by eapply message_dependencies_are_sufficient].\n    intros dm' Hdm'; apply Hind.\n    + by apply msg_dep_happens_before_iff_one; left.\n    + transitivity dm; [| done].\n      by apply msg_dep_happens_before_iff_one; left.\nQed.\n\nLemma msg_dep_fixed_limited_equivocation_witnessed\n  is tr\n  (Htr : finite_valid_trace Limited is tr)\n  (equivocators := state_annotation (finite_trace_last is tr))\n  (Fixed := fixed_equivocation_vlsm_composition IM (Ci := Ci) (fin_sets.set_map A equivocators))\n  : (sum_weights equivocators <= threshold)%R\n      /\\\n    finite_valid_trace Fixed\n      (original_state is)\n      (pre_VLSM_embedding_finite_trace_project\n        (type Limited) (composite_type IM) Datatypes.id original_state\n        tr).\nProof.\n  repeat split; [.. | by apply Htr].\n  - by eapply coeqv_limited_equivocation_state_not_heavy,\n            finite_valid_trace_last_pstate, Htr.\n  - apply valid_trace_add_default_last in Htr.\n    induction Htr using finite_valid_trace_init_to_rev_ind\n    ; [constructor; apply initial_state_is_valid; apply Hsi |].\n    setoid_rewrite map_app.\n    apply finite_valid_trace_from_app_iff; split.\n    + revert IHHtr.\n      apply VLSM_incl_finite_valid_trace_from,\n        fixed_equivocation_vlsm_composition_index_incl.\n      intro; rewrite !elem_of_elements.\n      apply set_map_mono; [done |].\n      by eapply coeqv_limited_equivocation_transition_state_annotation_incl, Ht.\n    + apply finite_valid_trace_singleton.\n      unfold input_valid_transition, input_valid.\n      change (map _ _) with (pre_VLSM_embedding_finite_trace_project (type Limited)\n                              (composite_type IM) Datatypes.id original_state tr).\n      rewrite <- pre_VLSM_embedding_finite_trace_last.\n      assert (Hs : valid_state_prop\n                    (fixed_equivocation_vlsm_composition IM (Ci := Ci) (fin_sets.set_map A (state_annotation s)))\n                    (original_state s)).\n      {\n        replace s with (finite_trace_last si tr) at 2\n             by (apply valid_trace_get_last in Htr; done).\n        rewrite (pre_VLSM_embedding_finite_trace_last\n                  (type Limited) (composite_type IM) Datatypes.id original_state si tr).\n        by apply finite_valid_trace_last_pstate.\n      }\n      destruct Ht as [[HLs [HLim HLv]] HLt].\n      cbn in HLt |- *; unfold annotated_transition in HLt; cbn in HLt.\n      replace (finite_trace_last si _) with s\n           by (apply valid_trace_get_last in Htr; congruence).\n      destruct l as [i li], (vtransition _ _ _) as (si', om').\n      inversion HLt; subst; clear HLt; cbn.\n      repeat split.\n      * revert Hs; apply VLSM_incl_valid_state.\n        apply fixed_equivocation_vlsm_composition_index_incl.\n        intro; rewrite !elem_of_elements.\n        apply set_map_mono; [done |].\n        by destruct iom as [im |]; [apply union_subseteq_l |].\n      * destruct iom as [im |]\n        ; [apply option_valid_message_Some | apply option_valid_message_None].\n        destruct (decide (composite_has_been_directly_observed IM (original_state s) im))\n              as [Hobs | Hnobs].\n        -- eapply composite_directly_observed_valid; [| done].\n           revert Hs; apply VLSM_incl_valid_state.\n           apply fixed_equivocation_vlsm_composition_index_incl.\n           intro; rewrite !elem_of_elements.\n           by apply set_map_mono, union_subseteq_l.\n        -- revert HLim.\n           setoid_rewrite emitted_messages_are_valid_iff.\n           intros [Hinit | Hemit]; [by left | right].\n           eapply VLSM_weak_embedding_can_emit.\n           {\n             eapply EquivPreloadedBase_Fixed_weak_embedding\n               with (base_s := original_state s).\n             - revert Hs; apply VLSM_incl_valid_state.\n               apply fixed_equivocation_vlsm_composition_index_incl.\n               intro; rewrite !elem_of_elements.\n               by apply set_map_mono, union_subseteq_l.\n             - by intros; apply no_initial_messages_in_IM.\n           }\n           eapply VLSM_incl_can_emit.\n           {\n             apply Equivocators_Fixed_Strong_incl.\n             revert Hs; apply VLSM_incl_valid_state.\n             apply fixed_equivocation_vlsm_composition_index_incl.\n             intro; rewrite !elem_of_elements.\n             by apply set_map_mono, union_subseteq_l.\n           }\n           apply message_equivocators_can_emit; [done | done |].\n           eapply VLSM_embedding_can_emit; [| done].\n           by apply forget_annotations_projection.\n      * by apply HLv.\n      * destruct iom as [im |]; [| done].\n        destruct (decide (composite_has_been_directly_observed IM (original_state s) im))\n              as [Hobs | Hnobs]; [by left | right; cbn].\n        apply message_equivocators_can_emit; [done | done |].\n        apply emitted_messages_are_valid_iff in HLim\n          as [[j [[mj Hmj] Heqim]] | Hemit]\n        ; [clear Heqim; contradict Hmj; apply no_initial_messages_in_IM |].\n        eapply VLSM_embedding_can_emit; [| done].\n        by apply forget_annotations_projection.\nQed.\n\nCorollary msg_dep_fixed_limited_equivocation is tr\n  : finite_valid_trace Limited is tr ->\n    fixed_limited_equivocation_prop IM threshold A\n      (original_state is)\n      (pre_VLSM_embedding_finite_trace_project\n        (type Limited) (composite_type IM) Datatypes.id original_state\n        tr) (Ci := Ci) (Cv := Cv).\nProof.\n  intro Htr.\n  exists (state_annotation (finite_trace_last is tr)).\n  by apply msg_dep_fixed_limited_equivocation_witnessed.\nQed.\n\nLemma fixed_transition_preserves_annotation_equivocators\n  (eqv_validators : Cv)\n  (equivocators := fin_sets.set_map A eqv_validators : Ci)\n  (is : vstate (free_composite_vlsm IM)) s tr\n  (Htr1 :\n    finite_valid_trace_init_to (fixed_equivocation_vlsm_composition IM equivocators)\n    is s tr)\n  l iom sf oom\n  (Ht :\n    input_valid_transition\n      (fixed_equivocation_vlsm_composition IM equivocators) l\n      (s, iom) (sf, oom))\n  (Hsub_equivocators :\n    state_annotation\n      (@finite_trace_last _ (type Limited)\n        {| original_state := is; state_annotation := `inhabitant |}\n        (msg_dep_annotate_trace_with_equivocators IM full_message_dependencies sender is tr))\n    \u2286 eqv_validators)\n  : msg_dep_composite_transition_message_equivocators IM\n      full_message_dependencies sender l\n      (@finite_trace_last _ (type Limited)\n        {| original_state := is; state_annotation := empty_set |}\n        (annotate_trace_from (free_composite_vlsm IM)\n          Cv\n          (msg_dep_composite_transition_message_equivocators IM full_message_dependencies sender)\n          {| original_state := is; state_annotation := empty_set |} tr), iom)\n    \u2286 eqv_validators.\nProof.\n  destruct iom as [im |]; [| done].\n  apply ListFinSetExtras.set_union_subseteq_iff; split; [done | cbn].\n  rewrite annotate_trace_from_last_original_state; cbn.\n  replace (finite_trace_last _ _) with s\n       by (apply valid_trace_get_last in Htr1; congruence).\n  unfold coeqv_message_equivocators.\n  case_decide as Hnobserved; [by apply empty_subseteq |].\n  destruct Ht as [(Hs & Him & Hv & [Hobs | Hemitted]) Ht]\n  ; [done | intros eqv Heqv].\n  unfold msg_dep_coequivocating_senders,\n         not_directly_observed_happens_before_dependencies in Heqv\n  ; rewrite elem_of_list_to_set, elem_of_app,\n      elem_of_elements, elem_of_list_to_set, !elem_of_map_option in Heqv\n  ; setoid_rewrite elem_of_list_singleton in Heqv\n  ; setoid_rewrite elem_of_elements in Heqv\n  ; setoid_rewrite elem_of_filter in Heqv.\n  destruct Heqv as [(msg & Hmsg & Hsender) | (msg & [Hnobserved_msg Hdep_msg] & Hsender)].\n  - subst msg.\n    eapply VLSM_incl_can_emit in Hemitted\n    ; [| apply pre_loaded_vlsm_incl_pre_loaded_with_all_messages].\n    apply can_emit_composite_project in Hemitted as [sub_eqv Hemitted].\n    destruct_dec_sig sub_eqv _eqv H_eqv Heqsub_eqv; subst.\n    unfold sub_IM in Hemitted; cbn in Hemitted.\n    eapply Hsender_safety in Hemitted; [| done]; subst.\n    apply elem_of_elements in H_eqv.\n    by revert H_eqv; apply elem_of_set_map_inj.\n  - cut (strong_fixed_equivocation IM equivocators s msg).\n    {\n      intros [Hobserved | Hemitted_msg].\n      - contradict Hnobserved_msg.\n        by eapply sent_by_non_equivocating_are_directly_observed.\n      - eapply VLSM_incl_can_emit in Hemitted_msg\n        ; [| apply pre_loaded_vlsm_incl_pre_loaded_with_all_messages].\n        apply can_emit_composite_project in Hemitted_msg as [sub_i Hemitted_msg].\n        destruct_dec_sig sub_i i Hi Heqsub_i; subst.\n        eapply Hsender_safety in Hemitted_msg; [| done].\n        cbn in Hemitted_msg; subst.\n        apply elem_of_elements in Hi.\n        by revert Hi; apply elem_of_set_map_inj.\n    }\n    eapply msg_dep_happens_before_reflect\n    ; [| by apply full_message_dependencies_happens_before | right]\n    ; cycle 1.\n    + eapply VLSM_incl_can_emit; [| done].\n      by apply Equivocators_Fixed_Strong_incl.\n    + eapply msg_dep_rel_reflects_strong_fixed_equivocation\n      ; [done | done |].\n      apply VLSM_incl_valid_state; [| done].\n      by apply Fixed_incl_StrongFixed.\nQed.\n\nLemma msg_dep_limited_fixed_equivocation\n  (is : vstate (free_composite_vlsm IM)) (tr : list (composite_transition_item IM))\n  : fixed_limited_equivocation_prop (Ci := Ci) (Cv := Cv) IM threshold A is tr ->\n    finite_valid_trace Limited\n      {| original_state := is; state_annotation := ` inhabitant |}\n      (msg_dep_annotate_trace_with_equivocators IM full_message_dependencies sender is tr).\nProof.\n  intros (equivocators & Hlimited & Htr).\n  split; [| by split; [apply Htr |]].\n  apply valid_trace_add_default_last in Htr.\n  match goal with\n  |- finite_valid_trace_from Limited ?is ?tr =>\n    cut\n      (finite_valid_trace_from Limited is tr /\\\n        (state_annotation (@finite_trace_last _ (type Limited) is tr) \u2286 equivocators))\n  end\n  ; [itauto |].\n  induction Htr using finite_valid_trace_init_to_rev_strong_ind.\n  - split; [| by apply empty_subseteq].\n    by constructor; apply initial_state_is_valid.\n  - rewrite @msg_dep_annotate_trace_with_equivocators_app; cbn.\n    unfold annotate_trace_item; rewrite !finite_trace_last_is_last; cbn.\n    split; cycle 1.\n    + by eapply fixed_transition_preserves_annotation_equivocators\n      ; [| | apply IHHtr1].\n    + apply finite_valid_trace_from_app_iff.\n      split; [by apply IHHtr1 |].\n      apply finite_valid_trace_singleton.\n      repeat split.\n      * by apply finite_valid_trace_last_pstate, IHHtr1.\n      * clear -Heqiom IHHtr2.\n        destruct IHHtr2 as [IHHtr2 _].\n        unfold empty_initial_message_or_final_output in Heqiom.\n        destruct_list_last iom_tr iom_tr' iom_item Heqiom_tr\n        ; [by apply option_initial_message_is_valid |].\n        destruct iom as [im |]; [| apply option_valid_message_None].\n        eapply valid_trace_output_is_valid; [done |].\n        rewrite @msg_dep_annotate_trace_with_equivocators_app.\n        apply Exists_app; right.\n        destruct iom_item.\n        by apply Exists_exists; eexists; split; [left |].\n      * destruct l as [i li]; cbn.\n        rewrite msg_dep_annotate_trace_with_equivocators_last_original_state; cbn.\n        replace (finite_trace_last _ _) with s\n             by (apply valid_trace_get_last in Htr1; congruence).\n        by apply Ht.\n      * apply Rle_trans with (sum_weights equivocators)\n        ; [| done].\n        apply sum_weights_subseteq.\n        by eapply fixed_transition_preserves_annotation_equivocators; [.. | apply IHHtr1].\n      * destruct l as [i li]; cbn; unfold annotated_transition; cbn.\n        rewrite !msg_dep_annotate_trace_with_equivocators_last_original_state; cbn.\n        replace (finite_trace_last _ _) with s\n             by (apply valid_trace_get_last in Htr1; congruence).\n        by destruct Ht as [_ Ht]; cbn in Ht\n        ; destruct (vtransition _ _ _) as (si', om')\n        ; inversion Ht.\nQed.\n\nLemma annotated_limited_incl_constrained_limited\n  `{!finite.Finite validator}\n  {is_equivocating_tracewise_no_has_been_sent_dec :\n    RelDecision (is_equivocating_tracewise_no_has_been_sent IM A sender)}\n  : VLSM_embedding\n      Limited\n      (tracewise_limited_equivocation_vlsm_composition IM threshold A sender (Cv := Cv))\n      Datatypes.id original_state.\nProof.\n  constructor; intros sX trX HtrX.\n  eapply @traces_exhibiting_limited_equivocation_are_valid; [done.. | |].\n  - by apply Hsender_safety.\n  - by apply msg_dep_fixed_limited_equivocation.\nQed.\n\nEnd sec_msg_dep_fixed_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/MsgDepLimitedEquivocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15116944410019706}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.common.Memtype.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import compcert.x86.Asm.\nRequire Import compcertx.x86.AsmX.\nRequire Import liblayers.lib.Decision.\nRequire Import liblayers.logic.LayerData.\nRequire Import liblayers.logic.Layers.\nRequire Export liblayers.compcertx.CompcertStructures.\nRequire Import liblayers.compcertx.ErrorMonad.\nRequire Import liblayers.compcertx.AbstractData.\nRequire Import liblayers.compcertx.AbstractData.\nRequire Import liblayers.compat.CompatData.\nRequire Export liblayers.compat.CompatCPrimitives.\nRequire Export liblayers.compat.CompatAsmPrimitives.\nRequire Export liblayers.compat.CompatCallConv.\nOpen Scope positive_scope.\n\n(** * Combined primitives *)\n\n(** We should define a conversion from C primitive semantics to\n  assembly primitive semantics. For now, we want to stick to the way\n  existing proofs are done (ie. duplicated), and we just define the\n  sum of both kinds. *)\n\nSection COMBINED_PRIMITIVES.\nContext `{Hmem: Mem.MemoryModel}.\nContext `{Hmwd: UseMemWithData mem}.\n\n(** ** Definition *)\n\nDefinition compatsem (D: compatdata) :=\n  (sextcall_primsem D + sprimcall_primsem D)%type.\n\nDefinition compatsem_sig D (\u03c3: compatsem D): signature :=\n  match \u03c3 with\n    | inl \u03c3l => sextcall_sig \u03c3l\n    | inr \u03c3r => sprimcall_sig \u03c3r\n  end.\n\n(** Helps with unification. *)\nDefinition compatsem_inl {D}: sextcall_primsem D -> compatsem D := inl.\nDefinition compatsem_inr {D}: sprimcall_primsem D -> compatsem D := inr.\n\n(** ** Order *)\n\nInductive compatsem_le (D: compatdata): relation (compatsem D) :=\n  | compatsem_le_inl:\n      Proper (sextcall_primsem_le ++> compatsem_le D) compatsem_inl\n  | compatsem_le_inr:\n      Proper (sprimcall_primsem_le ++> compatsem_le D) compatsem_inr.\n\nGlobal Existing Instance compatsem_le_inl.\nGlobal Existing Instance compatsem_le_inr.\n\nHint Resolve (compatsem_le_inl: forall D \u03c31 \u03c32, _ \u03c31 \u03c32 -> _) : liblayers.\nHint Resolve (compatsem_le_inr: forall D \u03c31 \u03c32, _ \u03c31 \u03c32 -> _) : liblayers.\n\nGlobal Instance compatsem_le_preorder D:\n  PreOrder (compatsem_le D).\nProof.\n  split.\n  * intros [\u03c3l | \u03c3r]; constructor; reflexivity.\n  * intros _ _ \u03c33 [\u03c3l1 \u03c3l2 Hl12 | \u03c3r1 \u03c3r2 Hr12] H23;\n    inversion H23 as [\u03c3l2x \u03c3l3 Hl23 | \u03c3r2x \u03c3r3 Hr23]; subst; clear H23;\n    constructor;\n    etransitivity;\n    eassumption.\nQed.\n\nRequire Import OptionMonad.\n\n(** ** Simulation diagrams *)\n\nRecord sextcall_sprimcall_sim {D1 D2} (R: compatrel D1 D2)\n       (sem1: sextcall_primsem D1) (sem2: sprimcall_primsem D2): Prop :=\n  {\n    sextcall_sprimcall_sim_step:\n                forall f vargs1 vargs2 vres m1 d1 m1' d1' rs2 m2 (d2: D2),\n                (** Invariants *)\n                forall (LOW_LEVEL_INVARIANT: low_level_invariant (Mem.nextblock m2) d2),\n                forall (L_HIGH_LEVEL_INVARIANT: high_level_invariant d2),\n                forall (H_HIGH_LEVEL_INVARIANT: high_level_invariant d1),\n                (** Higher-layer semantics *)\n                forall (SEM1: sem1 (decode_longs (sig_args (sextcall_sig sem1)) vargs1) (m1, d1) vres (m1', d1')),\n                (** Match states *)\n                forall (MATCH: MatchExtcallStates R f m1 d1 m2 d2),\n                (** Calling convention *)\n                forall (ARGS_INJ: val_list_inject f vargs1 vargs2),\n                forall (EXTCALL_ARG: Asm.extcall_arguments rs2 (m2, d2) (sextcall_sig sem1) vargs2),\n                (** Requirements of the compiler (to make \"transitivity\" possible) *)\n                forall (ASM_INV: asm_invariant rs2 (m2, d2)),\n                (*\n      forall (KERNEL_MODE: kernel_mode d2),\n                 *)\n                forall (SP_NOT_VUNDEF: rs2 (Asm.IR Asm.ESP) <> Vundef),\n                forall (RA_NOT_VUNDEF: rs2 Asm.RA <> Vundef),\n                forall (INIT_SP_NOT_GLOBAL: \n                          forall (b : Values.block) (o : Integers.Int.int),\n                            rs2 (Asm.IR Asm.ESP) = Values.Vptr b o ->\n                            Ple glob_threshold b),\n                exists f' rs2' m2' d2',\n                  sprimcall_step sem2 rs2 (m2, d2) rs2' (m2', d2') /\\\n                  MatchExtcallStates R f' m1' d1' m2' d2' /\\\n                  inject_incr f f' /\\\n                  val_list_inject f'\n                                  (encode_long (sig_res (sextcall_sig sem1)) vres)\n                                  (map rs2' (loc_external_result (sextcall_sig sem1))) /\\\n                  (forall r,\n                     ~ In r Conventions1.destroyed_at_call ->\n                     Val.lessdef (rs2 (preg_of r)) (rs2' (preg_of r)))\n                  /\\ Val.lessdef (rs2 RA) (rs2' Asm.PC)\n                  /\\ Val.lessdef (rs2 ESP) (rs2' ESP);\n    sextcall_sprimcall_sim_sig:\n      sprimcall_sig sem2 = sextcall_sig sem1;\n    sextcall_sprimcall_sim_invs:\n      ExtcallInvariants sem1\n  }.\n\n(** We want to relate [sextcall_sprimcall_sim] with [callconv_primsem].\n  One particularly challenging aspect is to establish that the final\n  register states are related. In particular, we need to use the\n  condition on [vres] to establish that the registers encoding it\n  in [rs1] inject into [rs2]. *)\n\nLemma callconv_encode_result_item_inject f v reg regs rs1 rs2:\n  (- ==> val_inject f) rs1 rs2 ->\n  val_inject f v (rs2 reg) ->\n  (prod_rel (- ==> val_inject f) eq)\n    (callconv_encode_result_item (rs1, reg::regs) v)\n    (rs2, regs).\nProof.\n  intros Hrs Hv.\n  split; eauto; simpl.\n  intros reg'.\n  unfold Pregmap.set.\n  destruct (PregEq.eq _ _); subst; eauto.\nQed.\n\nLemma callconv_encode_result_items f (regs: list preg) vs (rs1 rs2: regset):\n  (val_list_inject f) vs (map rs2 regs) ->\n  (- ==> val_inject f) rs1 rs2 ->\n  (- ==> val_inject f)\n    (fst (fold_left callconv_encode_result_item vs (rs1, regs)))\n    rs2.\nProof.\n  change rs1 with (fst (rs1, regs)) at 1.\n  change regs with (snd (rs1, regs)) at 1.\n  generalize (rs1, regs) as rr.\n  clear.\n  induction vs as [ | v vs IHvs]; eauto.\n  intros [rs1 regs] Hvs Hrs.\n  destruct regs as [ | reg regs]; inversion Hvs; subst.\n  apply IHvs; clear IHvs; simpl in *; eauto.\n  intros reg'.\n  unfold Pregmap.set.\n  destruct (PregEq.eq _ _); subst; eauto.\nQed.\n\nLemma callconv_encode_result_inject f sg v rs1 rs2:\n  (val_list_inject f)\n    (encode_long (sig_res sg) v)\n    (map rs2 (loc_external_result sg)) ->\n  (- ==> val_inject f) rs1 rs2 ->\n  (- ==> val_inject f) (callconv_encode_result sg v rs1) rs2.\nProof.\n  apply callconv_encode_result_items.\nQed.\n\n(** Furthermore, in order to do case analysis in terms if what happens\n  to what register and use the conditions expressed in terms of\n  [Machregs.mreg], we need to be able to distiguish whether a given\n  [preg] is in the codomain of [preg_of]. *)\n\nDefinition mregs: list preg :=\n  FR XMM0 :: FR XMM1 :: FR XMM2 :: FR XMM3 ::\n  FR XMM4 :: FR XMM5 :: FR XMM6 :: FR XMM7 ::\n  IR EAX  :: IR EBX  :: IR ECX  :: IR EDX  ::\n  IR ESI  :: IR EDI  :: IR EBP  :: ST0     ::\n  nil.\n\nLemma mregs_correct:\n  forall r, In r mregs -> exists m, r = preg_of m.\nProof.\n  intros [|[]|[]| |[]|] H;\n  let rec tryall l :=\n    match l with\n      | ?m :: ?ms =>\n        (exists m; reflexivity) || tryall ms\n      | _ =>\n        contradict H; decision\n    end in\n  tryall\n    (Machregs.AX ::\n     Machregs.BX ::\n     Machregs.CX ::\n     Machregs.DX ::\n     Machregs.SI ::\n     Machregs.DI ::\n     Machregs.BP ::\n     Machregs.X0 ::\n     Machregs.X1 ::\n     Machregs.X2 ::\n     Machregs.X3 ::\n     Machregs.X4 ::\n     Machregs.X5 ::\n     Machregs.X6 ::\n     Machregs.X7 ::\n     Machregs.FP0 ::\n     nil).\n  Qed.\n\nLemma mregs_complete:\n  forall m, In (preg_of m) mregs.\nProof.\n  intros []; decision.\nQed.\n\nLemma sextcall_sprimcall_sim_elim {D1 D2} (R: compatrel D1 D2) sem1 sem2:\n  sextcall_sprimcall_sim R sem1 sem2 ->\n  sprimcall_sim R (callconv_primsem D1 sem1) sem2.\nProof.\n  intros [Hstep Hsig Hinvs].\n  constructor; eauto.\n  * intros f rs1 m1 d1 rs1' m1' d1' rs2 m2 d2.\n    intros Hll2 Hhl2 Hhl1 Hasm H1 Hmatch.\n    destruct H1 as (vargs1 & vres1 & [Hstep1 Hvargs1 Hsp Hra Hspng Hvres1]).\n    destruct Hmatch as [Hmatch Hrs].\n    apply extcall_arguments_lift in Hvargs1.\n    edestruct extcall_arguments_inject as (vargs2 & Hvargs & Hvargs2); eauto.\n    {\n      apply match_inject.\n    }\n    edestruct Hstep as (f' & rs2' & m2' & d2' & H); eauto.\n    + apply extcall_arguments_lift; assumption.\n    + eapply val_inject_defined; eauto.\n    + eapply val_inject_defined; eauto.\n    + intros b ofs Hrs2.\n      specialize (Hrs ESP).\n      unfold Pregmap.get in Hrs.\n      destruct Hrs; inversion Hrs2; subst; eauto; try congruence.\n      apply match_inject_forward in H.\n      destruct H; subst.\n      transitivity b1; eauto.\n      eapply Hspng; eauto.\n    + destruct H as (Hstep2 & Hmatch' & Hf & Hvres & Hrd & HRAPC & HESP).\n      exists f', rs2', m2', d2'.\n      split; eauto.\n      split; eauto.\n      subst.\n      intros reg.\n      unfold callconv_final_regs.\n      unfold Pregmap.get.\n      apply callconv_encode_result_inject; eauto.\n      unfold Pregmap.set.\n      clear reg; intro reg.\n      destruct (PregEq.eq reg PC); subst.\n      {\n        rewrite <- HRAPC.\n        eauto.\n      }\n      unfold callconv_destroy_regs.\n      unfold callconv_destroyed_regs.\n      destruct (decide _) as [Hregd|Hregd]; try constructor.\n      destruct (decide (In reg mregs)) as [Hregm|Hregm].\n      {\n        apply mregs_correct in Hregm.\n        destruct Hregm as [r Hr]; subst.\n        rewrite <- Hrd; eauto.\n        intros H.\n        apply Hregd.\n        apply in_app; left.\n        apply in_map; eauto.\n      }\n      {\n        destruct reg as [|[]|[]| |[]|];\n        try (contradict Hregm; decision);\n        try (contradict Hregd; decision);\n        try congruence.\n        (* Only ESP left *)\n        rewrite <- HESP.\n        eauto.\n      }\n  * apply callconv_invariants in Hinvs.\n    assumption.\nQed.\n\nInductive compatsim_def {D1 D2: compatdata} (R: compatrel D1 D2):\n  compatsem D1 -> compatsem D2 -> Prop :=\n    | sextcall_sim_either_sim sem1 sem2:\n        sextcall_sim R sem1 sem2 ->\n        compatsim_def R (compatsem_inl sem1) (compatsem_inl sem2)\n    | sprimcall_sim_either_sim sem1 sem2:\n        sprimcall_sim R sem1 sem2 ->\n        compatsim_def R (compatsem_inr sem1) (compatsem_inr sem2)\n    | sextcall_sprimcall_sim_either_sim sem1 sem2:\n        sprimcall_sim R (callconv_primsem D1 sem1) sem2 ->\n        ExtcallInvariants sem1 ->\n        compatsim_def R (compatsem_inl sem1) (compatsem_inr sem2).\n\nGlobal Instance compatsim_def_le {D1 D2} (R: compatrel D1 D2):\n  Proper (compatsem_le D1 --> compatsem_le D2 ++> impl) (compatsim_def R).\nProof.\n    intros \u03c31 \u03c31' H1 \u03c32 \u03c32' H2 H.\n    unfold flip in *; simpl in *.\n    destruct H as [sem1 sem2 Hl | sem1 sem2 Hr | sem sem2 Hlr].\n\n    + (* extcall *)\n      inversion H1 as [sem1' sem1x Hsem1 | ]; subst; clear H1.\n      inversion H2 as [sem2x sem2' Hsem2 | ]; subst; clear H2.\n      constructor.\n      eapply sextcall_sim_le; eauto.\n\n    + (* primcall *)\n      inversion H1 as [ | sem1' sem1x Hsem1]; subst; clear H1.\n      inversion H2 as [ | sem2x sem2' Hsem2]; subst; clear H2.\n      constructor.\n      eapply sprimcall_sim_le; eauto.\n\n    + (* heterogenous *)\n      inversion H1 as [ | sem1' sem1x Hsem1]; subst; clear H1.\n      inversion H2 as [ | sem2x sem2' Hsem2]; subst; clear H2.\n      constructor.\n      * eapply sprimcall_sim_le; eauto.\n        eapply callconv_primsem_le_monotonic.\n        assumption.\n      * destruct Hlr as [_ _ Hvalid _]; simpl in Hvalid.\n        destruct Hsem2 as [_ _ Hvalid2].\n        eapply (sextcall_primsem_le_invs x sem); eauto.\nQed.\n\nDefinition compatsim {D1 D2}:\n  path compatrel D1 D2 -> compatsem D1 -> compatsem D2 -> Prop :=\n  path_sim compatsem_le (@compatsim_def) D1 D2.\n\nGlobal Instance compat_sim_op: Sim (path compatrel) compatsem | 1 :=\n  path_sim_op compatsem_le (@compatsim_def).\n\nGlobal Instance compat_primsem_ops: PrimitiveOps compatsem :=\n  {\n    (*prim_union := compatsem_union*)\n  }.\n\nGlobal Instance compatsem_primsem_prf:\n  Primitives compatsem.\nProof.\n  split; try typeclasses eauto.\n  * apply path_sim_prf; typeclasses eauto.\nQed.\n\n(** Convenient shortcut for defining primitives as [p \u21a6 csem sem]. *)\n\nDefinition csem {D: compatdata} (sem: sextcall_sem (mem := mwd D)) targs tres :=\n  compatsem_inl\n    {|\n      sextcall_primsem_step :=\n        {|\n          sextcall_step := sem;\n          sextcall_csig := mkcsig targs tres\n        |};\n      sextcall_props := Error (MSG \"missing extcall properties\"::nil);\n      sextcall_invs := Error (MSG \"primitive does not preserve invariants\"::nil)\n    |}.\n\nDefinition null_signature :=\n  {| sig_args := nil; sig_res := None; sig_cc := cc_default |}.\n\nDefinition asmsem {D: compatdata} (sem: sprimcall_sem (mem := mwd D)) :=\n  compatsem_inr\n    {|\n      sprimcall_primsem_step :=\n        {|\n          sprimcall_step := sem;\n          sprimcall_sig := null_signature\n        |};\n      sprimcall_props := Error (MSG \"missing primcall properties\"::nil);\n      sprimcall_invs := Error (MSG \"primitive does not preserve invariants\"::nil)\n    |}.\n\nDefinition asmsem_withsig {D: compatdata} (sem: sprimcall_sem (mem := mwd D)) sig :=\n  compatsem_inr\n    {|\n      sprimcall_primsem_step :=\n        {|\n          sprimcall_step := sem;\n          sprimcall_sig := sig\n        |};\n      sprimcall_props := Error (MSG \"missing primcall properties\"::nil);\n      sprimcall_invs := Error (MSG \"primitive does not preserve invariants\"::nil)\n    |}.\n\nEnd COMBINED_PRIMITIVES.\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/compat/CompatPrimSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2845760042165267, "lm_q1q2_score": 0.15116944087706857}}
{"text": "From compcert Require Import common.AST cfrontend.Ctypes cfrontend.Clight.\nImport Cop.\nRequire Import VST.floyd.base2.\nRequire Import VST.floyd.functional_base.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.compare_lemmas.\nRequire Import VST.floyd.nested_pred_lemmas.\nRequire Import VST.floyd.nested_field_lemmas.\nRequire Import VST.floyd.efield_lemmas.\nRequire Import VST.floyd.mapsto_memory_block.\nRequire Import VST.floyd.aggregate_type.\nRequire VST.floyd.aggregate_pred. Import floyd.aggregate_pred.aggregate_pred.\nRequire Import VST.floyd.reptype_lemmas.\nRequire Import VST.floyd.simpl_reptype.\nRequire Import VST.floyd.data_at_rec_lemmas.\nRequire Import VST.floyd.field_at.\nRequire Import VST.floyd.field_at_wand.\nRequire Import VST.floyd.field_compat.\nRequire Import VST.floyd.stronger.\nRequire Import VST.floyd.proj_reptype_lemmas.\nRequire Import VST.floyd.replace_refill_reptype_lemmas.\nRequire Import VST.floyd.unfold_data_at.\nRequire Import VST.floyd.entailer.\n\nLemma \n  sbyte_ubyte_convert:\n  forall i j, \n  Int.sign_ext 8 (Int.repr (Byte.unsigned i)) = Int.repr (Byte.signed j) <->\n  Int.zero_ext 8 (Int.repr (Byte.unsigned i)) = Int.repr (Byte.unsigned j).\nProof.\nintros.\nrewrite Int.zero_ext_and by computable.\nsimpl.\nnormalize.\ntransitivity (Z.land (Byte.unsigned i) 255 = Byte.unsigned j).\n2:{\nsplit; intro. f_equal; auto.\napply repr_inj_unsigned; auto.\nsplit. apply Z.land_nonneg; rep_lia.\nchange 255 with (Z.ones 8).\nrewrite (Z.land_ones (Byte.unsigned i) 8 ) by computable.\npose proof (Z_mod_lt (Byte.unsigned i) (2^8)).\nspec H0.\ncompute; auto.\nchange (2^8) with 256 in *. rep_lia.\nrep_lia.\n}\nchange 255 with (Z.ones 8).\nrewrite Z.land_ones_low; try rep_lia.\n2:{\npose proof (Z.log2_le_mono (Byte.unsigned i) 255).\nsimpl in H.\nspec H; rep_lia.\n}\nsplit; intro.\n-\napply Z.bits_inj.\nintro n.\ndestruct (zlt n 0).\nrewrite !Z.testbit_neg_r by auto. auto.\ndestruct (zlt n 8).\n2:{\nassert (forall k, Z.log2 (Byte.unsigned k) < n).\nintro. assert (Byte.unsigned k <= 255) by rep_lia.\napply Z.log2_le_mono in H0. simpl in H0. lia.\nrewrite Z.bits_above_log2 by (auto; rep_lia).\nrewrite Z.bits_above_log2 by (auto; rep_lia).\nauto.\n}\napply (f_equal (fun i => Int.testbit i n)) in H.\nrewrite Int.bits_sign_ext in H by (change Int.zwordsize with 32; lia).\nrewrite if_true in H by auto.\nrewrite !Int.testbit_repr in H by (change Int.zwordsize with 32; lia).\nrewrite H; clear H.\nrewrite Byte.bits_signed by lia.\nrewrite if_true by auto.\nreflexivity.\n-\nrewrite H.\nclear H.\napply Int.same_bits_eq; intros n  ?.\nchange Int.zwordsize with 32 in H.\nrewrite Int.bits_sign_ext by (auto; computable).\nif_tac.\nrewrite !Int.testbit_repr by auto.\nrewrite Byte.bits_signed by lia.\nrewrite if_true by auto.\nreflexivity.\nrewrite !Int.testbit_repr by (change Int.zwordsize with 32; lia).\nrewrite Byte.bits_signed by lia.\nrewrite if_false by auto.\nreflexivity.\nQed.\n\nModule M.\nImport VST.veric.base.\nImport VST.msl.predicates_hered.\nImport VST.veric.res_predicates.\n\nLemma address_mapsto_any_sbyte_ubyte:\n forall sh b z,\n EX v2' : val, address_mapsto Mint8signed v2' sh (b, z) =\n EX v2' : val, address_mapsto Mint8unsigned v2' sh (b, z).\nProof.\nintros.\napply pred_ext;\n[pose (f := Byte.unsigned) | pose (f := Byte.signed)];\napply exp_left; intro v;\npose (v' := match v with Vint j => Vint (Int.repr (f (Byte.repr (Int.unsigned j))))\n  | _ => Vundef\nend);\napply exp_right with v';\nunfold address_mapsto;\napply exp_left; intro bl; \napply exp_right with bl;\napply prop_andp_left; intros [? [? ?]];\ndestruct bl as [| ? [|]]; try solve [inv H];\n(rewrite prop_true_andp; [auto | \n  split3; auto; unfold decode_val in *; destruct m; subst v v' f; simpl in *; auto;\n   unfold decode_int; rewrite rev_if_be_singleton; simpl; rewrite Z.add_0_r;\n   f_equal; clear\n  ]).\nall: assert (Int.zwordsize = 32) by reflexivity;\n      assert (Byte.zwordsize = 8) by reflexivity.\nall: apply Int.same_bits_eq; intros n ?;\nrewrite ?Int.bits_zero_ext by lia;\nrewrite ?Int.bits_sign_ext by lia;\nrewrite ?Int.testbit_repr by (try if_tac; lia);\nrewrite ?Byte.bits_signed by lia;\nchange (Z.testbit (Byte.unsigned ?A)) with (Byte.testbit A);\nrewrite ?Byte.testbit_repr by (try if_tac; lia);\nrewrite ?H0; if_tac;\nrewrite ?Byte.testbit_repr by (try if_tac; lia).\nrewrite <- Int.testbit_repr by lia; rewrite Int.repr_unsigned.\nrewrite Int.bits_sign_ext by lia.\nrewrite if_true by lia.\nrewrite Int.testbit_repr by lia.\nreflexivity.\nrewrite Byte.bits_above by lia. auto.\nrewrite <- Int.testbit_repr by lia; rewrite Int.repr_unsigned.\nrewrite Int.bits_zero_ext by lia.\nrewrite if_true by auto.\nrewrite Int.testbit_repr by lia.\nreflexivity.\nrewrite <- Int.testbit_repr by lia; rewrite Int.repr_unsigned.\nrewrite Int.bits_zero_ext by lia.\nrewrite if_true by lia.\nrewrite Int.testbit_repr by lia.\nreflexivity.\nQed.\nEnd M.\n\nArguments deref_noload ty v / .\nArguments nested_field_array_type {cs} t gfs lo hi / .\nArguments nested_field_type {cs} t gfs / .  (* redundant? *)\nArguments nested_field_offset {cs} t gfs / .  (* redundant? *)\nArguments Z.mul !x !y.\nArguments Z.sub !m !n.\nArguments Z.add !x !y.\nGlobal Transparent peq.\n\nLemma data_at_tarray_tschar_tuchar {cs: compspecs}:\n  forall sh n bytes p,\n  data_at sh (tarray tschar n) (map Vbyte bytes) p = data_at sh (tarray tuchar n) (map Vubyte bytes) p.\nProof.\nintros.\nunfold data_at, field_at.\nf_equal.\nf_equal.\nunfold field_compatible.\nsimpl.\napply prop_ext; intuition; destruct p; auto;\nhnf in H2|-*;\napply align_compatible_rec_Tarray; intros;\napply align_compatible_rec_Tarray_inv with (i:=i0) in H2; auto;\neapply align_compatible_rec_by_value_inv in H2; try reflexivity;\neapply align_compatible_rec_by_value; try reflexivity;\napply H2.\nunfold at_offset.\nsimpl.\nrewrite !data_at_rec_eq.\nsimpl.\napply array_pred_ext.\nchange (Zlength (map Vbyte bytes) = Zlength (map Vubyte bytes)).\nautorewrite with sublist. auto.\nintros.\nunfold at_offset.\nautorewrite with sublist.\nrewrite !data_at_rec_eq; simpl.\ndo 2 change (unfold_reptype ?A) with A.\nchange (sizeof tschar) with 1.\nchange (sizeof tuchar) with 1.\nforget (offset_val (1 * i) (offset_val 0 p)) as q.\nsimpl.\ndestruct q; auto.\nunfold mapsto; simpl.\nif_tac; auto.\n-\nsimpl.\nf_equal; auto; [f_equal; auto | ].\n+\nf_equal.\ndestruct (zlt i (Zlength bytes)).\nrewrite !Znth_map by lia.\nsimpl.\napply prop_ext; split; intro; \nautorewrite with norm norm1 norm2; rep_lia.\nrewrite !Znth_overflow by (autorewrite with sublist; auto).\nreflexivity.\n+\ndo 2 change (unfold_reptype ?A) with A.\ndestruct (zlt i (Zlength bytes)).\n2:\n rewrite !Znth_overflow by (autorewrite with sublist; auto);\n unfold res_predicates.address_mapsto; simpl;\n f_equal;\n extensionality bl;\n f_equal; f_equal;\n apply prop_ext; intuition;\n destruct bl as [| ? [|]]; inv H3;\n destruct m; inv H; reflexivity.\nautorewrite with sublist.\nforget (Znth i bytes) as c.\nunfold res_predicates.address_mapsto; simpl.\nf_equal.\nextensionality bl.\nf_equal.\nf_equal.\n apply prop_ext; intuition;\n destruct bl as [| ? [|]]; inv H3;\n destruct m; try solve [inv H];\n unfold decode_val, proj_bytes in *;\n unfold Vubyte, Vbyte in *;\n  apply Vint_inj in H;\n  f_equal; clear - H;\nunfold decode_int in *;\nrewrite rev_if_be_1 in H|-*;\nsimpl in H|-*;\nrewrite Z.add_0_r in *;\napply sbyte_ubyte_convert; auto.\n+\nf_equal; auto.\nf_equal.\nrepeat change (unfold_reptype ?A) with A.\ndestruct (zlt i (Zlength bytes)).\nautorewrite with sublist.\napply prop_ext; split; intro Hx; inv Hx.\nrewrite !Znth_overflow by (autorewrite with sublist; auto).\napply prop_ext; split; intro; reflexivity.\nclear.\nforget (Ptrofs.unsigned i0) as z.\napply M.address_mapsto_any_sbyte_ubyte.\n-\nf_equal.\nf_equal.\nf_equal.\nunfold tc_val'.\ndestruct (zlt i (Zlength bytes)).\nautorewrite with sublist.\napply prop_ext; split; intros.\nred. simpl. normalize. rep_lia.\nred. simpl. normalize. rep_lia.\nrewrite !Znth_overflow by (autorewrite with sublist; auto).\napply prop_ext; split; intros; contradiction H2; auto.\nQed.\n\nRequire Import VST.msl.iter_sepcon.\nRequire Import VST.floyd.go_lower.\nImport ListNotations.\n\nSection ArrayPointer.\n\nContext {cs: compspecs}.\n\n(*For simplifying pointer arithmetic*)\nLemma sem_sub_pi_offset: forall ty s off n,\n  isptr s ->\n  complete_type cenv_cs ty = true ->\n  Int.min_signed <= n <= Int.max_signed ->\n  force_val (sem_sub_pi ty Signed (offset_val off s) (Vint (Int.repr n))) =\n  offset_val (off - (sizeof ty) * n) s.\nProof.\n  intros ty s off n Hptr Hty Hn.\n  replace (off - (sizeof ty) * n) with (off + (- (sizeof ty) * n)) by lia. rewrite <- offset_offset_val.\n  assert (Hptr' : isptr (offset_val off s)). rewrite isptr_offset_val; auto.\n  destruct (offset_val off s) eqn : Hoff; inversion Hptr'. simpl.\n  unfold sem_sub_pi. rewrite Hty. simpl. f_equal. unfold sizeof.\n  assert ((Ptrofs.of_ints (Int.repr n)) = Ptrofs.repr n). unfold Ptrofs.of_ints.\n  f_equal. apply Int.signed_repr; auto. rewrite H. rewrite ptrofs_mul_repr.\n  rewrite Ptrofs.sub_add_opp. f_equal. replace (- Ctypes.sizeof ty * n) with (-(Ctypes.sizeof ty * n)) by lia.\n  rewrite <- (Ptrofs.neg_repr). reflexivity.\nQed.\n\n(** Indexing into arrays **)\n\nLemma arr_field_compatible0 : forall t size p i, \n  field_compatible (tarray t size) [] p ->\n  0 <= i <= size ->\n  field_compatible0 (tarray t size) (SUB i) p.\nProof.\n  intros t size p i Hcomp Hsz.\n  unfold field_compatible in *. unfold field_compatible0. destruct Hcomp as [Hptr [Hleg [Hsz_comp [Hal Hnest]]]].\n  repeat(split; auto).\nQed.\n\nLemma arr_field_address0: forall t size p i, \n  field_compatible (tarray t size) [] p ->\n  0 <= i <= size ->\n  field_address0 (tarray t size) (SUB i) p = offset_val (sizeof t * i) p.\nProof.\n  intros t size p i Hcomp Hi.\n  unfold field_address0. destruct (field_compatible0_dec (tarray t size) (SUB i) p).\n  simpl. auto. exfalso. apply n. apply arr_field_compatible0; auto.\nQed.\n\nLemma arr_field_compatible : forall t size p i, \n  field_compatible (tarray t size) [] p ->\n  0 <= i < size ->\n  field_compatible (tarray t size) (SUB i) p.\nProof.\n  intros t size p i Hcomp Hsz.\n  unfold field_compatible in *. unfold field_compatible0. destruct Hcomp as [Hptr [Hleg [Hsz_comp [Hal Hnest]]]].\n  repeat(split; auto).\nQed.\n\nLemma arr_field_address: forall t size p i, \n  field_compatible (tarray t size) [] p ->\n  0 <= i < size ->\n  field_address (tarray t size) (SUB i) p = offset_val (sizeof t * i) p.\nProof.\n  intros t size p i Hcomp Hi.\n  unfold field_address. destruct (field_compatible_dec (tarray t size) (SUB i) p).\n  simpl. auto. exfalso. apply n. apply arr_field_compatible; auto.\nQed.\n\n(*Useful for proving that pointers are valid for conditionals*)\nLemma isptr_denote_tc_test_order: forall p1 p2,\n  isptr p1 ->\n  isptr p2 ->\n  denote_tc_test_order p1 p2 = test_order_ptrs p1 p2.\nProof.\n  intros p1 p2 Hptr1 Hptr2. destruct p1; destruct Hptr1. destruct p2; destruct Hptr2. reflexivity.\nQed.\n\n(** Lemmas about [sameblock] *)\n\nLemma isptr_offset_val_sameblock : forall p i,\n  isptr p ->\n  sameblock p (offset_val i p) = true.\nProof.\n  intros. destruct p; destruct H.\n  simpl. unfold proj_sumbool. apply peq_true.\nQed.\n\nLemma sameblock_refl : forall p,\n  isptr p ->\n  sameblock p p = true.\nProof.\n  intros.\n  destruct p; destruct H. apply peq_true.\nQed.\n\nLemma sameblock_symm : forall p1 p2,\n  sameblock p1 p2 = true ->\n  sameblock p2 p1 = true.\nProof.\n  intros.\n  destruct p1; destruct p2; try discriminate.\n  simpl in *. destruct (peq b b0); try discriminate.\n  subst.\n  apply peq_true.\nQed.\n\nLemma sameblock_trans : forall p1 p2 p3,\n  sameblock p1 p2 = true ->\n  sameblock p2 p3 = true->\n  sameblock p1 p3 = true.\nProof.\n  intros.\n  destruct p1; try discriminate.\n  destruct p2; try discriminate.\n  destruct p3; try discriminate.\n  simpl in *.\n  destruct (peq b b0); try discriminate.\n  destruct (peq b0 b1); try discriminate.\n  subst.\n  apply peq_true.\nQed.\n\nLemma sameblock_offset_val: forall p n1 n2,\n  isptr p ->\n  sameblock (offset_val n1 p) (offset_val n2 p) = true.\nProof.\n  intros p n1 n2 Hptr. eapply sameblock_trans. eapply sameblock_symm. \n  all: apply isptr_offset_val_sameblock; auto.\nQed.\n\n(** Simplifying Pointer Comparisons *)\n\n(* Suppose there is an array of length s, and 2 pointers to elements in the array n and m, and the\n   C expression n > m (in a loop guard or conditional). This gives a long, difficult proof obligation.\n   The next few lemmas convert this into something usable. *)\n\n(* > case *)\nLemma ptr_comparison_gt_iff: forall t size p i j,\n  field_compatible (tarray t size) [] p ->\n  0 <= i <= size ->\n  0 <= j <= size ->\n  0 < sizeof t ->\n  isptr p ->\n  typed_true tint (force_val (sem_cmp_pp Cgt (field_address0 (tarray t size) (SUB i) p)\n    (field_address0 (tarray t size) (SUB j) p))) <-> i > j.\nProof.\n  intros t size p i j Hcomp Hi Hj Hszof Hptr.\n  assert (Hptri : isptr (field_address0 (tarray t size) (SUB i) p)).\n  apply field_address0_isptr. apply arr_field_compatible0; auto.\n  assert (Hptrj: isptr (field_address0 (tarray t size) (SUB j) p)).\n  apply field_address0_isptr. apply arr_field_compatible0; auto.\n  rewrite force_sem_cmp_pp; auto. unfold compare_pp.\n  destruct (field_address0 (tarray t size) (SUB i) p) eqn : Fi; inversion Hptri.\n  destruct (field_address0 (tarray t size) (SUB j) p) eqn : Fj; inversion Hptrj.\n  clear Hptri Hptrj.\n  assert (Hsame: sameblock (Vptr b i0) (Vptr b0 i1) = true). { rewrite <- Fi. rewrite <- Fj.\n  rewrite !arr_field_address0; auto. eapply sameblock_trans. apply sameblock_symm.\n  all: apply  isptr_offset_val_sameblock; auto. } \n  simpl in Hsame. unfold eq_block. destruct (peq b b0); try inversion Hsame. subst. clear Hsame.\n  simpl. rewrite arr_field_address0 in Fi; auto. rewrite arr_field_address0 in Fj; auto.\n  destruct p; inversion Hptr. simpl in *. inversion Fi; subst. inversion Fj; subst.\n  clear Fi Fj Hptr. unfold Ptrofs.ltu.\n  assert (Hi2 : 0 <= Ptrofs.unsigned i2) by rep_lia. unfold field_compatible in Hcomp. \n  destruct Hcomp as [Ht [Hcomp [HHsz Hrest]]]. simpl in HHsz.\n  replace (Z.max 0 size) with size in HHsz by lia.\n  (*We will use these a bunch of times*)\n  assert (Hij: forall k, 0 <= k <= size -> 0 <= sizeof t * k < Ptrofs.modulus). {\n    intros k Hk. unfold sizeof in *. split. lia.\n    assert (Ctypes.sizeof t * k <= Ctypes.sizeof t * size).  apply Z.mul_le_mono_pos_l; lia.\n    assert (Ctypes.sizeof t * size < Ptrofs.modulus) by lia. lia. } \n  assert (Hij' : forall k, 0 <= k <= size ->\n      0 <= Ptrofs.unsigned i2 + Ptrofs.unsigned (Ptrofs.repr (sizeof t * k)) < Ptrofs.modulus). {\n    intros k Hk. unfold sizeof in *. rewrite Ptrofs.unsigned_repr_eq. rewrite Zmod_small.\n    2: apply Hij; lia. split. lia. \n    assert (Ptrofs.unsigned i2 + Ctypes.sizeof t * k <= Ptrofs.unsigned i2 + Ctypes.sizeof t * size).\n    apply Zplus_le_compat_l. apply Z.mul_le_mono_nonneg_l; lia. eapply Z.le_lt_trans. apply H. assumption. }\n  unfold Ptrofs.unsigned. simpl. rewrite !Ptrofs.Z_mod_modulus_eq. rewrite !Zmod_small.\n  all: try apply Hij'; auto.\n  destruct (zlt (Ptrofs.unsigned i2 + Ptrofs.unsigned (Ptrofs.repr (sizeof t * j)))\n          (Ptrofs.unsigned i2 + Ptrofs.unsigned (Ptrofs.repr (sizeof t * i)))).\n    - assert (Hptrlt: Ptrofs.unsigned (Ptrofs.repr (sizeof t * j)) < Ptrofs.unsigned (Ptrofs.repr (sizeof t * i))) by lia.\n      clear l. unfold Ptrofs.unsigned in Hptrlt. simpl in Hptrlt. rewrite !Ptrofs.Z_mod_modulus_eq in Hptrlt.\n      rewrite !Zmod_small in Hptrlt. rewrite <- Z.mul_lt_mono_pos_l in Hptrlt; auto. all: try apply Hij; auto.\n      split; intros; auto. lia. reflexivity.\n    - assert (Hptrlt: Ptrofs.unsigned (Ptrofs.repr (sizeof t * i)) <= Ptrofs.unsigned (Ptrofs.repr (sizeof t * j))) by lia.\n      clear g. unfold Ptrofs.unsigned in Hptrlt. simpl in Hptrlt. rewrite !Ptrofs.Z_mod_modulus_eq in Hptrlt.\n      rewrite !Zmod_small in Hptrlt. rewrite <- Z.mul_le_mono_pos_l in Hptrlt; auto. all: try apply Hij; auto.\n      split; intros; try lia. inversion H.\nQed.\n\n(*Switch Cgt and Clt*)\nLemma cgt_clt_ptr: forall p1 p2,\n  sem_cmp_pp Cgt p1 p2 = sem_cmp_pp Clt p2 p1.\nProof.\n  intros p1 p2. unfold sem_cmp_pp. simpl. f_equal. unfold Val.cmplu_bool.\n  destruct p1; destruct p2; auto.\n  destruct (Archi.ptr64); auto; simpl;\n  destruct (eq_block b b0), (eq_block b0 b); subst; try contradiction;\n  reflexivity.\nQed.\n\n(*Same for the lt case. This is an easy corollary of the above 2 lemmas*)\nLemma ptr_comparison_lt_iff: forall t size p i j,\n  field_compatible (tarray t size) [] p ->\n  0 <= i <= size ->\n  0 <= j <= size ->\n  0 < sizeof t ->\n  isptr p ->\n  typed_true tint (force_val (sem_cmp_pp Clt (field_address0 (tarray t size) (SUB i) p)\n    (field_address0 (tarray t size) (SUB j) p))) <-> i < j. \nProof.\n  intros t sz p i j Hcompat Hi Hj Ht Hptr. rewrite <- cgt_clt_ptr.\n  rewrite ptr_comparison_gt_iff by auto. lia.\nQed.\n\n(** Working with 2D Arrays*)\n\n(*We can consider an instance of t at position p to be a valid array of length 1 at p*)\nLemma data_at_array_len_1: forall sh t a p,\ndata_at sh t a p |-- !! field_compatible (tarray t 1) [] p.\nProof.\n  intros. erewrite <- data_at_singleton_array_eq. 2: reflexivity. entailer!.\nQed.\n\n(*The crucial lemma for showing the relationship between 1D and 2D arrays: if we shift 1 array (in the 2D array)\n  or m places (in the 1D array), the result is still compatible*)\nLemma field_compatible0_1d_2d: forall n m t p,\n  0 <= m ->\n  0 < n ->\n  field_compatible (Tarray t m noattr) [] p ->\n  (field_compatible0 (tarray (tarray t m) n)) (SUB 1) p <->\n  (field_compatible0 (tarray t (n * m)) (SUB m) p).\nProof.\n  intros n m t p Hm Hn Hfst.\n  unfold field_compatible in Hfst. unfold field_compatible0.\n  simpl in *. destruct Hfst as [Hptr1 [Hleg1 [Hszc1 [Hal1 Hlegn1]]]].\n  clear Hlegn1.\n  (*The interesting part*)\n  assert (size_compatible (tarray (tarray t m) n) p /\\ align_compatible (tarray (tarray t m) n) p <->\n    size_compatible (tarray t (n * m)) p /\\ align_compatible (tarray t (n * m)) p ). {\n   unfold size_compatible. destruct p; inversion Hptr1. simpl in *.\n    replace (Z.max 0 m) with m by lia.\n    replace (Z.max 0 n) with n by lia.\n    replace (Z.max 0 (n * m)) with (m * n) by lia.\n    rewrite Z.mul_assoc. split; intros [Hszc2 Hal2].\n    - split. assumption. inversion Hal2; subst. inversion H.\n      inversion Hal1; subst. inversion H.\n      apply align_compatible_rec_Tarray. intros j Hj.\n      assert (m = 0 \\/ m > 0) by lia. destruct H as [H | Hm0]. subst. lia.\n      assert (0 <= j < m \\/ m <= j < n * m) by lia. destruct H as [Hfst | Hrest].\n      + specialize (H4 _ Hfst). apply H4.\n      + (*To index into the rest of the array, we need to use j/ m and j %m, which gives lots of annoying proof obligations*)\n        assert (0 <= j / m  < n). { split. assert (1 <= j / m). rewrite <- (Z_div_same _ Hm0).\n        apply Z_div_le; lia. lia. apply Z.div_lt_upper_bound; lia. }\n        specialize (H3 _ H). clear H4. inversion H3; subst. inversion H0.\n        assert (0 <= j mod m < m). { apply Z.mod_pos_bound; lia. }\n        specialize (H5 _ H0). replace (Ptrofs.unsigned i + Ctypes.sizeof t * j) with\n        (Ptrofs.unsigned i + Ctypes.sizeof (tarray t m) * (j / m) + Ctypes.sizeof t * (j mod m)). apply H5.\n        rewrite <- !Z.add_assoc. f_equal. simpl Ctypes.sizeof. replace (Z.max 0 m) with m by lia.\n        rewrite <- Z.mul_assoc. rewrite <- Z.mul_add_distr_l. f_equal.\n        replace (Z.max 0 m) with m by lia.\n        rewrite <- Z_div_mod_eq_full. reflexivity.\n    - split. assumption. inversion Hal2; subst. inversion H.\n      inversion Hal1; subst. inversion H.  apply align_compatible_rec_Tarray. intros j Hj.\n      apply align_compatible_rec_Tarray. intros k Hk.\n      assert (0 = j \\/ 1 <= j) by lia. destruct H as [Hfst | Hrest].\n      + subst. rewrite Z.mul_0_r. rewrite Z.add_0_r. apply H4. apply Hk.\n      + assert (0 = m \\/ 0 < m) by lia. destruct H as [H | Hm0]. lia.\n        assert (0 <= j * m + k < n * m). { split; try lia.\n        assert (j * m + k < j * m + m) by lia. replace (j * m + m) with ((j+1) * m) in H by lia.\n        assert ((j+1) * m <= n * m). apply Zmult_le_compat_r; lia. lia. } \n        specialize (H3 _ H). simpl. replace ( Z.max 0 m ) with m by lia.\n        replace (Ptrofs.unsigned i + Ctypes.sizeof t * m * j + Ctypes.sizeof t * k) with \n        (Ptrofs.unsigned i + Ctypes.sizeof t * (j * m + k)). apply H3. rewrite <- !Z.add_assoc. f_equal.\n        rewrite <- Z.mul_assoc. rewrite <- Z.mul_add_distr_l. f_equal. lia. }\n  split; intros [Hptr2 [Hleg2 [Hszc2 [Hal2 [Hlegn2 Hbound2]]]]].\n  repeat(split; auto). apply H. split; auto.\n  apply H. split; auto. replace m with (1 * m) at 1 by lia. apply Z.mul_le_mono_nonneg_r; lia.\n  repeat(split; auto). apply H. split; auto. apply H; split; auto. lia. lia.\nQed.\n\nLemma Zlength_concat': forall {A: Type} (n m : Z) (l: list (list A)),\n  Zlength l = n ->\n  Forall (fun x => Zlength x = m) l ->\n  Zlength (concat l) = n * m.\nProof.\n  intros A m n l. revert m. induction l; intros.\n  - list_solve.\n  - simpl. rewrite Zlength_app. rewrite (IHl (m-1)). 2: list_solve.\n    assert (Zlength a = n). inversion H0; subst; reflexivity. rewrite H1. lia. inversion H0; auto.\nQed.\n\n(*The full relationship between 1D and 2D arrays*)\nLemma data_at_2darray_concat : forall sh t n m (al : list (list (reptype t))) p,\n  Zlength al = n ->\n  Forall (fun l => Zlength l = m) al ->\n  complete_legal_cosu_type t = true ->\n  data_at sh (tarray (tarray t m) n) al p\n    = data_at sh (tarray t (n * m)) (concat al) p.\nProof.\n  intros.\n  generalize dependent n; generalize dependent p; induction al; intros.\n  - simpl. replace n with 0 by list_solve. rewrite Z.mul_0_l. \n    apply pred_ext; entailer!; rewrite !data_at_zero_array_eq; auto.\n  - rewrite Zlength_cons in H. simpl. assert (Hmlen: Zlength a = m) by (inversion H0; subst; reflexivity).\n    apply pred_ext.\n    + (*We will need these later, when we have transformed the [data_at] predicates, so they are harder to prove*)\n      assert_PROP (field_compatible (tarray (tarray t m) (Z.succ (Zlength al))) [] p). { entailer!. }\n      assert_PROP (field_compatible0 (tarray (tarray t m) n) (SUB 1) p). { entailer!.\n        apply arr_field_compatible0. auto. list_solve. }\n      change (a :: al) with ([a] ++ al). \n      change (list (reptype t)) with (reptype (tarray t m)) in a.\n      rewrite (split2_data_at_Tarray_app 1 _ _ _ [a]). 2: Zlength_solve.\n      change (reptype (tarray t m)) with  (list (reptype t)) in a. 2: { rewrite <- H.\n      assert (forall x, x = Z.succ x - 1). intros; lia. apply H4. }\n      rewrite (split2_data_at_Tarray_app m).\n      replace (n * m - m) with ((n-1) * m) by lia.\n      erewrite data_at_singleton_array_eq. 2: reflexivity.\n      assert (Hm: 0 <= m). rewrite <- Hmlen. list_solve.\n      entailer!. rewrite !field_address0_clarify; auto.\n      simpl. unfold sizeof. rewrite <- Z.mul_assoc.\n      replace (Z.max 0 (Zlength a) * 1) with (Zlength a) by lia. rewrite IHal. cancel.\n      inversion H0; subst; auto. lia. unfold field_address0.\n      rewrite field_compatible0_1d_2d in H3.\n      destruct (field_compatible0_dec (tarray t (Z.succ (Zlength al) * Zlength a)) [ArraySubsc (Zlength a)] p); [| contradiction].\n    apply isptr_is_pointer_or_null; auto. list_solve. list_solve. auto.\n    inversion H0; subst; reflexivity.\n    rewrite (Zlength_concat' (n-1) m). lia. list_solve. inversion H0; auto.\n    + assert_PROP ((field_compatible0 (tarray t (n * m)) [ArraySubsc m] p)). { entailer!.\n      apply arr_field_compatible0. apply H2.\n       split. list_solve. rewrite <- (Z.mul_1_l (Zlength a)) at 1. apply Z.mul_le_mono_nonneg_r; list_solve. }\n      change (a :: al) with ([a] ++ al). \n      change (list (reptype t)) with (reptype (tarray t m)) in a.\n      rewrite (split2_data_at_Tarray_app 1 _ _ _ [a]). 2: Zlength_solve.\n      change (reptype (tarray t m)) with  (list (reptype t)) in a. 2: { rewrite <- H.\n      assert (forall x, x = Z.succ x - 1). intros; lia. apply H3. }\n      rewrite (split2_data_at_Tarray_app m). 2: auto.\n      replace (n * m - m) with ((n-1) * m) by lia.\n      erewrite data_at_singleton_array_eq. 2: reflexivity.\n      assert (Hm: 0 <= m). rewrite <- Hmlen. list_solve.\n      entailer!. rewrite !field_address0_clarify; auto.\n      simpl. unfold sizeof. rewrite <- Z.mul_assoc.\n      replace (Z.max 0 (Zlength a) * 1) with (Zlength a) by lia. rewrite IHal. cancel.\n      inversion H0; subst; auto. lia. unfold field_address0.\n      rewrite <- field_compatible0_1d_2d in H2.\n      destruct (field_compatible0_dec (tarray (tarray t (Zlength a)) (Z.succ (Zlength al))) [ArraySubsc 1] p); [| contradiction].\n      apply isptr_is_pointer_or_null; auto. list_solve. list_solve. auto.\n      rewrite (Zlength_concat' (n-1) m). lia. list_solve. inversion H0; auto.\nQed.\n\n(** Working with Arrays of Pointers **)\n\n(*Represents the fact that there is a list of pointers (ptrs), and the contents of those pointers\n  are described by contents - a 2D array with possibly different lengths.\n  This definition applies to byte arrays (so we don't need to worry about offsets), but it\n  could be extended. *)\nDefinition iter_sepcon_arrays (ptrs : list val) (contents: list (list byte)) := \n  iter_sepcon (fun (x: (list byte * val)) => let (l, ptr) := x in \n            data_at Ews (tarray tuchar (Zlength l)) (map Vubyte l) ptr) (combine contents ptrs).\n\nLemma iter_sepcon_arrays_Znth: forall ptrs contents i,\n  Zlength ptrs = Zlength contents ->\n  0 <= i < Zlength contents ->\n  iter_sepcon_arrays ptrs contents |-- \n    data_at Ews (tarray tuchar (Zlength (Znth i contents))) (map Vubyte (Znth i contents)) (Znth i ptrs) * TT.\nProof.\n  intros ptrs contents i Hlen Hi. unfold iter_sepcon_arrays. \n  sep_apply (iter_sepcon_in_true (fun x : list byte * val => let (l, ptr) := x in \n    data_at Ews (tarray tuchar (Zlength l)) (map Vubyte l) ptr) (combine contents ptrs) \n    (Znth i contents, Znth i ptrs)); [|cancel].\n  rewrite In_Znth_iff. exists i. split. rewrite Zlength_combine; lia.\n  apply Znth_combine; lia.\nQed.\n\nLemma remove_lead_eq: forall {A: Type} (P: Prop) (x: A),\n  (x = x -> P) <-> P.\nProof.\n  intros. tauto.\nQed.\n\nLemma iter_sepcon_arrays_local_facts: forall ptrs contents,\n  iter_sepcon_arrays ptrs contents |-- !! (Zlength ptrs = Zlength contents -> \n        forall i, 0 <= i < Zlength contents ->\n         field_compatible (tarray tuchar (Zlength (Znth i contents))) [] (Znth i ptrs) /\\\n         Forall (value_fits tuchar) (map Vubyte (Znth i contents))).\nProof.\n  intros ptrs contents. \n  assert (Zlength ptrs = Zlength contents \\/ Zlength ptrs <> Zlength contents) as [Heq | Hneq] by lia; \n  [ | entailer!]. rewrite Heq, remove_lead_eq. eapply derives_trans. 2:\n  apply (@allp_prop_left _ _ Z (fun (i: Z) => 0 <= i < Zlength contents ->\n        field_compatible (tarray tuchar (Zlength (Znth i contents))) [] (Znth i ptrs) /\\\n        Forall (value_fits tuchar) (map Vubyte (Znth i contents)))).\n  apply allp_right. intros i.\n  (*This is not particularly elegant; is there a way to get an implication out directly?*)\n  assert (0 <= i < Zlength contents \\/ ~ (0 <= i < Zlength contents)) as [Hlt | Hgt] by lia; [| entailer ].\n  sep_apply (iter_sepcon_arrays_Znth _ _ _ Heq Hlt).\n  assert (forall m (P : Type) Q, P -> (m |-- !! Q) -> (m |-- !! (P -> Q))). { intros. sep_apply H. entailer!. }\n  apply H. assumption. entailer!.\nQed.\n\n(*We would also like another, more general fact. For [iter_sepcon] that gives an mpred \n  as well as [iter_sepcon_arrays]), we can remove\n  the nth element and keep the rest*)\n\n(*An easier definition than [delete_nth], since it uses Z and there are lots of lemmas/automation about sublist*)\nDefinition remove_nth {A: Type} (n: Z) (l: list A): list A :=\n  sublist 0 n l ++ sublist (n+1) (Zlength l) l.\n\nLemma iter_sepcon_remove_one: forall {B : Type} `{Inhabitant B} (p: B -> mpred) (l: list B) (n: Z),\n  0 <= n < Zlength l ->\n  iter_sepcon p l = ((p (Znth n l)) * iter_sepcon p (remove_nth n l))%logic.\nProof.\n  intros B Hinhab p l n Hn. unfold remove_nth. rewrite <- (sublist_same 0 (Zlength l) l) at 1 by auto.\n  rewrite (sublist_split 0 n (Zlength l) l) by lia.\n  rewrite (sublist_split n (n+1) (Zlength l) l) by lia. rewrite !iter_sepcon_app.\n  rewrite sublist_len_1 by lia. simpl. apply pred_ext; cancel.\nQed.\n\nLemma combine_sublist: forall {A B: Type} `{Inhabitant A} `{Inhabitant B} (lo hi : Z) (l1 : list A) (l2: list B),\n  Zlength l1 = Zlength l2 ->\n  0 <= lo <= hi ->\n  hi <= Zlength l1 ->\n  combine (sublist lo hi l1) (sublist lo hi l2) = sublist lo hi (combine l1 l2).\nProof.\n  intros A B Hinh1 Hinh2 lo hi l1 l2 Hlen Hhilo Hhi.\n  assert (Hsublen: Zlength (combine (sublist lo hi l1) (sublist lo hi l2)) = hi - lo). {\n   rewrite Zlength_combine by (rewrite !Zlength_sublist; lia). list_solve. }\n  apply Znth_eq_ext. rewrite Hsublen. rewrite Zlength_sublist; try lia.\n  rewrite Zlength_combine; lia.\n  intros i Hi. rewrite Hsublen in Hi. rewrite Znth_combine by list_solve.\n  rewrite !Znth_sublist by lia. rewrite Znth_combine by lia. reflexivity.\nQed.\n\nLemma combine_remove_nth: forall {A B: Type} `{Inhabitant A} `{Inhabitant B} n (l1: list A) (l2: list B),\n  Zlength l1 = Zlength l2 ->\n  0 <= n < Zlength l1 ->\n  combine (remove_nth n l1) (remove_nth n l2) = remove_nth n (combine l1 l2).\nProof.\n  intros A B Hinh1 Hinh2 n l1 l2 Hlens Hn.\n  unfold remove_nth. rewrite combine_app' by list_solve. rewrite Hlens, !combine_sublist by lia.\n  rewrite Zlength_combine by lia. rewrite Hlens, Z.min_id. reflexivity.\nQed.\n\n(* Allows one to extract a single [data_at] from an [iter_sepcon] without losing any information *)\nLemma iter_sepcon_arrays_remove_one: forall ptrs contents i,\n  Zlength ptrs = Zlength contents ->\n  0 <= i < Zlength contents ->\n  iter_sepcon_arrays ptrs contents = \n    (data_at Ews (tarray tuchar (Zlength (Znth i contents))) (map Vubyte (Znth i contents)) (Znth i ptrs) *\n    iter_sepcon_arrays (remove_nth i ptrs) (remove_nth i contents))%logic.\nProof.\n  intros ptrs contents i Hlens Hi. unfold iter_sepcon_arrays. rewrite (iter_sepcon_remove_one _ _ i).\n  rewrite Znth_combine by auto. f_equal. rewrite combine_remove_nth by lia. reflexivity.\n  rewrite Zlength_combine; lia.\nQed.\n\nEnd ArrayPointer.\n\n(** Convert [data_at] for numeric types *)\n\nSection DataAtNumeric.\n\nContext `{cs: compspecs}.\n\n(*Helper lemmas*)\nLemma exp_equiv: forall {A} (f: A -> predicates_hered.pred compcert_rmaps.RML.R.rmap),\n  exp f = predicates_hered.exp f.\nProof.\n  intros. reflexivity.\nQed.\n\nLemma andp_pull1:\n  forall P (A C: predicates_hered.pred compcert_rmaps.RML.R.rmap), predicates_hered.andp (predicates_hered.andp (predicates_hered.prop P) A) C =\n                 predicates_hered.andp (predicates_hered.prop P)  (predicates_hered.andp A C).\nProof.\nintros.\napply predicates_hered.andp_assoc.\nQed.\n\nLemma decode_int_single: forall (b: byte),\n  decode_int [b] = Byte.unsigned b.\nProof.\n  intros b. unfold decode_int. unfold rev_if_be.\n  destruct Archi.big_endian; simpl; lia.\nQed.\n\nLemma zero_ext_8_lemma:\n  forall i j, Int.zero_ext 8 (Int.repr (Byte.unsigned i)) = Int.repr (Byte.unsigned j) ->\n    i=j.\nProof.\nintros.\nrewrite zero_ext_inrange in H\n  by (rewrite Int.unsigned_repr by rep_lia; simpl; rep_lia).\napply repr_inj_unsigned in H; try rep_lia.\nrewrite <- (Byte.repr_unsigned i), <- (Byte.repr_unsigned j).\ncongruence.\nQed.\n\nLemma decode_val_Vubyte_inj:\n  forall i j, decode_val Mint8unsigned [Byte i] = Vubyte j -> i=j.\nProof.\nintros.\nunfold decode_val, Vubyte in *; simpl in *.\napply Vint_inj in H.\nrewrite decode_int_single in *.\napply zero_ext_8_lemma in H.\nauto.\nQed.\n\nLemma decode_int_range: forall bl, 0 <= decode_int bl < two_p (Z.of_nat (Datatypes.length bl) * 8).\nProof.\nintros.\nunfold decode_int.\nunfold rev_if_be.\ndestruct Archi.big_endian.\nrewrite <- rev_length.\napply int_of_bytes_range.\napply int_of_bytes_range.\nQed.\n\nLemma int_of_bytes_inj: forall al bl, length al = length bl -> int_of_bytes al = int_of_bytes bl -> al=bl.\nProof.\nintros.\nrevert bl H H0; induction al; destruct bl; simpl; intros; auto; try discriminate.\npose proof (Byte.unsigned_range a). pose proof (Byte.unsigned_range i).\nchange Byte.modulus with 256 in *. \nassert (al=bl). {\n   apply IHal. congruence.\n   forget (int_of_bytes al) as x. forget (int_of_bytes bl) as y.\n   lia.\n}\nsubst bl.\nf_equal.\nclear - H0 H1 H2.\nrewrite <- (Byte.repr_unsigned a).\nrewrite <- (Byte.repr_unsigned i).\nf_equal.\nlia.\nQed.\n\nLemma decode_int_inj: forall al bl, \n   length al = length bl -> \n   decode_int al = decode_int bl -> al=bl.\nProof.\nintros.\nunfold decode_int in *.\napply int_of_bytes_inj in H0; auto.\nQed.\n\n(** Convert between 4 bytes and int *)\nLemma address_mapsto_4bytes_aux: \n forall (sh : Share.t)\n   (b0 b1 b2 b3 : byte)\n   (b : block) (i : ptrofs)\n   (SZ : Ptrofs.unsigned i + 4 < Ptrofs.modulus)\n(*   (AL : (4 | Ptrofs.unsigned i)) *)\n   (r : readable_share sh),\npredicates_sl.sepcon\n  (predicates_sl.sepcon\n     (predicates_sl.sepcon\n           (predicates_hered.allp\n              (res_predicates.jam\n                 (adr_range_dec (b, Ptrofs.unsigned i) (size_chunk Mint8unsigned))\n                 (fun loc : address =>\n                  res_predicates.yesat compcert_rmaps.RML.R.NoneP\n                    (compcert_rmaps.VAL\n                       (nth (Z.to_nat (snd loc - snd (b, Ptrofs.unsigned i)))\n                          [Byte b0] Undef)) sh loc) res_predicates.noat))\n           (predicates_hered.allp\n              (res_predicates.jam\n                 (adr_range_dec (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1)))\n                    (size_chunk Mint8unsigned))\n                 (fun loc : address =>\n                  res_predicates.yesat compcert_rmaps.RML.R.NoneP\n                    (compcert_rmaps.VAL\n                       (nth\n                          (Z.to_nat\n                             (snd loc\n                                - snd\n                                    (b,\n                                    Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1)))))\n                          [Byte b1] Undef)) sh loc) res_predicates.noat)))\n        (predicates_hered.allp\n           (res_predicates.jam\n              (adr_range_dec (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 2)))\n                 (size_chunk Mint8unsigned))\n              (fun loc : address =>\n               res_predicates.yesat compcert_rmaps.RML.R.NoneP\n                 (compcert_rmaps.VAL\n                    (nth\n                       (Z.to_nat\n                          (snd loc\n                             - snd\n                                 (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 2)))))\n                       [Byte b2] Undef)) sh loc) res_predicates.noat)))\n     (predicates_hered.allp\n        (res_predicates.jam\n           (adr_range_dec (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 3)))\n              (size_chunk Mint8unsigned))\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth\n                    (Z.to_nat\n                       (snd loc\n                          - snd (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 3)))))\n                    [Byte b3] Undef)) sh loc) res_predicates.noat))\n          = predicates_hered.allp\n                                    (res_predicates.jam\n                                       (adr_range_dec (b, Ptrofs.unsigned i)\n                                          (size_chunk Mint32))\n                                       (fun loc : address =>\n                                        res_predicates.yesat\n                                          compcert_rmaps.RML.R.NoneP\n                                          (compcert_rmaps.VAL\n                                             (nth\n                                                (Z.to_nat\n                                                   (snd loc\n                                                      - snd (b, Ptrofs.unsigned i)))\n                                                [Byte b0; Byte b1; Byte b2; Byte b3]\n                                                Undef)) sh loc) res_predicates.noat).\nProof.\nintros.\n\n     simpl snd.\n    simpl size_chunk.\n repeat   match goal with |- context [Ptrofs.add i (Ptrofs.repr ?A)] =>\n    replace (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr A)))\n    with (A + Ptrofs.unsigned i)\n    by (unfold Ptrofs.add; rewrite (Ptrofs.unsigned_repr (Z.pos _)) by rep_lia;\n        rewrite Ptrofs.unsigned_repr by rep_lia; rep_lia)\n   end.\n    rewrite  (res_predicates.allp_jam_split2 _ _ _ \n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1; Byte b2; Byte b3] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1; Byte b2] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - (3+Ptrofs.unsigned i)))\n                    [Byte b3] Undef)) sh loc)\n           (adr_range_dec (b, Ptrofs.unsigned i) 4)\n           (adr_range_dec (b, Ptrofs.unsigned i) 3)\n           (adr_range_dec (b, 3 + Ptrofs.unsigned i) 1)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1; Byte b2; Byte b3] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1; Byte b2] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - (3+Ptrofs.unsigned i)))\n           [Byte b3] Undef)).\n    2:{ forget (Ptrofs.unsigned i) as j. clear.\n         split; intros [b1 z1]. simpl. intuition rep_lia.\n         simpl. intuition rep_lia.\n       }\n    2:{ intros. destruct l; destruct H; subst. f_equal. f_equal.\n          rewrite (app_nth1 [Byte b0; Byte b1; Byte b2] [Byte b3]); auto.\n        simpl. rep_lia.\n       }\n  2:{ intros. f_equal. f_equal. \n       destruct l; destruct H. subst b4. simpl snd.\n       assert (z = 3 + Ptrofs.unsigned i) by lia. subst z.\n        rewrite Z.sub_diag.\n        replace (3 + Ptrofs.unsigned i - Ptrofs.unsigned i) with 3 by lia.\n          reflexivity.\n      }\n   2:{ intros. left. destruct H0. hnf in H0. rewrite H0 in H1 . clear H0.\n        destruct l, H. subst. simpl snd in *.\n        assert (Z.to_nat (z - Ptrofs.unsigned i) < 4)%nat by rep_lia.\n        clear - H1. destruct (Z.to_nat (z - Ptrofs.unsigned i)) as [|[|[|[|]]]]; inv H1; apply I.\n       }\n   f_equal.\n   \n    rewrite  (res_predicates.allp_jam_split2 _ _ _ \n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1; Byte b2] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - (2+Ptrofs.unsigned i)))\n                    [Byte b2] Undef)) sh loc)\n           (adr_range_dec (b, Ptrofs.unsigned i) 3)\n           (adr_range_dec (b, Ptrofs.unsigned i) 2)\n           (adr_range_dec (b, 2 + Ptrofs.unsigned i) 1)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1; Byte b2] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - (2+Ptrofs.unsigned i)))\n           [Byte b2] Undef)).\n    2:{ forget (Ptrofs.unsigned i) as j. clear.\n         split; intros [b1 z1]. simpl. intuition rep_lia.\n         simpl. intuition rep_lia.\n       }\n    2:{ intros. destruct l; destruct H; subst. f_equal. f_equal.\n          rewrite (app_nth1 [Byte b0; Byte b1] [Byte b2]); auto.\n        simpl. rep_lia.\n       }\n  2:{ intros. f_equal. f_equal. \n       destruct l; destruct H. subst b4. simpl snd.\n       assert (z = 2 + Ptrofs.unsigned i) by lia. subst z.\n        rewrite Z.sub_diag.\n        replace (2 + Ptrofs.unsigned i - Ptrofs.unsigned i) with 2 by lia.\n          reflexivity.\n      }\n   2:{ intros. left. destruct H0. hnf in H0. rewrite H0 in H1 . clear H0.\n        destruct l, H. subst. simpl snd in *.\n        assert (Z.to_nat (z - Ptrofs.unsigned i) < 3)%nat by rep_lia.\n        clear - H1. destruct (Z.to_nat (z - Ptrofs.unsigned i)) as [|[|[|]]]; inv H1; apply I.\n       }\n\n   f_equal.\n\n    rewrite  (res_predicates.allp_jam_split2 _ _ _ \n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - (1+Ptrofs.unsigned i)))\n                    [Byte b1] Undef)) sh loc)\n           (adr_range_dec (b, Ptrofs.unsigned i) 2)\n           (adr_range_dec (b, Ptrofs.unsigned i) 1)\n           (adr_range_dec (b, 1 + Ptrofs.unsigned i) 1)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - (1+Ptrofs.unsigned i)))\n           [Byte b1] Undef)).\n    2:{ forget (Ptrofs.unsigned i) as j. clear.\n         split; intros [b1 z1]. simpl. intuition rep_lia.\n         simpl. intuition rep_lia.\n       }\n    2:{ intros. destruct l; destruct H; subst. f_equal. f_equal.\n          rewrite (app_nth1 [Byte b0] [Byte b1]); auto.\n        simpl. rep_lia.\n       }\n  2:{ intros. f_equal. f_equal. \n       destruct l; destruct H. subst b4. simpl snd.\n       assert (z = 1 + Ptrofs.unsigned i) by lia. subst z.\n        rewrite Z.sub_diag.\n        replace (1 + Ptrofs.unsigned i - Ptrofs.unsigned i) with 1 by lia.\n          reflexivity.\n      }\n   2:{ intros. left. destruct H0. hnf in H0. rewrite H0 in H1 . clear H0.\n        destruct l, H. subst. simpl snd in *.\n        assert (Z.to_nat (z - Ptrofs.unsigned i) < 2)%nat by rep_lia.\n        clear - H1. destruct (Z.to_nat (z - Ptrofs.unsigned i)) as [|[|[|]]]; inv H1; apply I.\n       }\n   f_equal.\nQed.\n\nImport normalize.\n\nLemma address_mapsto_4bytes:\n forall \n    (AP: Archi.ptr64 = true)  (* Perhaps this premise could be eliminated. *)\n   (sh : Share.t)\n    (b0 b1 b2 b3 : byte)\n    (b : block)\n    (i : ptrofs)\n    (SZ : Ptrofs.unsigned i + 4 < Ptrofs.modulus)\n    (AL : (4 | Ptrofs.unsigned i))\n    (r : readable_share sh),\n predicates_sl.sepcon\n  (predicates_sl.sepcon\n     (predicates_sl.sepcon\n        (res_predicates.address_mapsto Mint8unsigned \n           (Vubyte b0) sh (b, Ptrofs.unsigned i))\n        (res_predicates.address_mapsto Mint8unsigned \n           (Vubyte b1) sh\n           (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1)))))\n     (res_predicates.address_mapsto Mint8unsigned \n        (Vubyte b2) sh (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 2)))))\n  (res_predicates.address_mapsto Mint8unsigned (Vubyte b3) sh\n     (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 3)))) = \nres_predicates.address_mapsto Mint32\n  (Vint (Int.repr (decode_int [b0; b1; b2; b3]))) sh\n  (b, Ptrofs.unsigned i).\nProof.\nintros.\n      unfold res_predicates.address_mapsto. rewrite <- !exp_equiv.\n      apply predicates_hered.pred_ext.\n  - repeat change (exp ?A) with (predicates_hered.exp A).\n      normalize.normalize.\n      intros bl3 [A3 [B3 _]] bl2 bl1 bl0.\n      normalize.normalize.\n      destruct H as [A2 [ B2 _]].\n      destruct H0 as [A1 [ B1 _]].\n      destruct H1 as [A0 [ B0 _]].\n    destruct bl0 as [ | c0 [|]]; inv A0; inv B0. \n    destruct bl1 as [ | c1 [|]]; inv A1; inv B1.\n    destruct bl2 as [ | c2 [|]]; inv A2; inv B2. \n    destruct bl3 as [ | c3 [|]]; inv A3; inv B3.\n     destruct c0; try discriminate H0.\n     destruct c1; try discriminate H1.\n     destruct c2; try discriminate H2.\n     destruct c3; try discriminate H3.\n   apply decode_val_Vubyte_inj in H0,H1,H2,H3. subst.\n   apply (predicates_hered.exp_right [Byte b0; Byte b1; Byte b2; Byte b3]).\n     rewrite predicates_hered.prop_true_andp.\n      2:{ split3. reflexivity. reflexivity. apply AL. }\n  match goal with |- predicates_hered.derives ?A ?B => \n        assert (EQ: A=B); [ | rewrite EQ; apply predicates_hered.derives_refl]\n    end.\n  apply address_mapsto_4bytes_aux; auto.\n\n -\n  repeat change (exp ?A) with (predicates_hered.exp A).\n      normalize.normalize.\n  intros bl [? [? ?]]. simpl snd in H1.\n      destruct bl as [|c0 [| c1 [| c2 [| c3 [|]]]]]; inv H.\n       unfold decode_val, proj_bytes in H0. rewrite AP in H0. clear AP.\n       destruct c0; try discriminate H0.\n       destruct c1; try discriminate H0.\n       destruct c2; try discriminate H0.\n       destruct c3; try discriminate H0.\n       apply Vint_inj in H0.\n       pose proof (decode_int_range [b0;b1;b2;b3]).\n       pose proof (decode_int_range [i0;i1;i2;i3]).\n       change (two_p _) with Int.modulus in H,H2.\n       apply repr_inj_unsigned in H0; try rep_lia.\n        apply decode_int_inj in H0.\n      clear H H2. inv H0.\n     apply predicates_hered.exp_right with [Byte b3].\n      normalize.normalize.\n     apply predicates_hered.exp_right with [Byte b2].\n      normalize.normalize.\n     apply predicates_hered.exp_right with [Byte b1].\n      normalize.normalize.\n     apply predicates_hered.exp_right with [Byte b0].\n     rewrite !predicates_hered.prop_true_andp by \n     (split3; [ reflexivity |  | apply Z.divide_1_l  ];\n     unfold decode_val, Vubyte; simpl; f_equal;\n     rewrite decode_int_single;\n     apply zero_ext_inrange; change (two_p _ - 1) with 255;\n     rewrite Int.unsigned_repr by rep_lia; rep_lia).\n  match goal with |- predicates_hered.derives ?A ?B => \n        assert (EQ: B=A); [ | rewrite EQ; apply predicates_hered.derives_refl]\n    end.\n  apply address_mapsto_4bytes_aux; auto.\n  reflexivity.\nQed.\n\nLemma tc_val_Vubyte: forall b, tc_val tuchar (Vubyte b).\nProof.\nintros; red. \nsimpl. rewrite Int.unsigned_repr by rep_lia.\nrep_lia.\nQed.\n\nLemma nonlock_permission_4bytes:\n forall (sh : Share.t)\n     (b : block) (i : ptrofs) \n     (SZ : Ptrofs.unsigned i + 4 < Ptrofs.modulus),\n(res_predicates.nonlock_permission_bytes sh (b, Ptrofs.unsigned i) 1\n   * res_predicates.nonlock_permission_bytes sh\n       (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1))) 1\n   * res_predicates.nonlock_permission_bytes sh\n       (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 2))) 1\n   * res_predicates.nonlock_permission_bytes sh\n       (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 3))) 1)%logic = \nres_predicates.nonlock_permission_bytes sh (b, Ptrofs.unsigned i) 4.\nProof.\nintros.\n repeat   match goal with |- context [Ptrofs.add i (Ptrofs.repr ?A)] =>\n    replace (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr A)))\n    with (A + Ptrofs.unsigned i)\n    by (unfold Ptrofs.add; rewrite (Ptrofs.unsigned_repr (Z.pos _)) by rep_lia;\n        rewrite Ptrofs.unsigned_repr by rep_lia; rep_lia)\n   end.\n rewrite (res_predicates.nonlock_permission_bytes_split2 3 1 4 sh) by lia.\n rewrite (res_predicates.nonlock_permission_bytes_split2 2 1 3 sh) by lia.\n rewrite (res_predicates.nonlock_permission_bytes_split2 1 1 2 sh) by lia.\n repeat change (predicates_sl.sepcon ?A ?B) with (A * B)%logic.\n rewrite !(Z.add_comm (Ptrofs.unsigned i)).\n f_equal.\nQed.\n\n(* The main result: 4 consecutive bytes can be interpreted as a single int *)\nLemma data_at_int_bytes: \n  forall \n    (AP: Archi.ptr64 = true)  (* Perhaps this premise could be eliminated. *)\n  sh \n   (b0 b1 b2 b3 : byte) p,\n  field_compatible tuint [] p  ->\n  (data_at sh tuchar (Vubyte b0) p *\n  data_at sh tuchar (Vubyte b1) (offset_val 1 p) *\n  data_at sh tuchar (Vubyte b2) (offset_val 2 p) *\n  data_at sh tuchar (Vubyte b3) (offset_val 3 p))%logic =\n  data_at sh tuint (Vint (Int.repr (decode_int [b0;b1;b2;b3]))) p.\nProof.\n  intros AP sh b0 b1 b2 b3 p. unfold data_at. unfold field_at.\n  intro.\n  rewrite !prop_true_andp by auto with field_compatible.\n destruct H as [H0 [_ [SZ [AL _]]]]. red in SZ. simpl sizeof in SZ.\n   destruct p; inversion H0. clear H0.\n assert (4 | Ptrofs.unsigned i)\n   by (eapply align_compatible_rec_by_value_inv in AL; [ | reflexivity]; assumption).\n clear AL.\n unfold at_offset. \n rewrite !offset_offset_val. rewrite !Z.add_0_r.\n simpl offset_val. rewrite !ptrofs_add_repr_0_r.\n rewrite !data_at_rec_eq. simpl.\n change (unfold_reptype ?x) with x.\n unfold mapsto.\n simpl access_mode; simpl type_is_volatile; cbv iota.\n rewrite !(prop_true_andp _ _ (tc_val_Vubyte _)).\n rewrite !(prop_false_andp (_ = _)) by (intro Hx; inv Hx).\n rewrite !(prop_true_andp (tc_val tuint _)) by (apply Logic.I).\n rewrite ?prop_and_mpred.\n rewrite ?(prop_true_andp _ _ (tc_val_tc_val' _ _ (tc_val_Vubyte _))).\n rewrite !(prop_true_andp (tc_val' tuint _)) by (apply tc_val_tc_val'; apply Logic.I).\n rewrite ?(prop_true_andp _ _ (Z.divide_1_l _)).\n rewrite !orp_FF.\n rewrite (prop_true_andp (_ | _)) by apply H.\n if_tac.\n- apply address_mapsto_4bytes; auto.\n- apply nonlock_permission_4bytes; auto.\nQed.\n\n\n(** Convert between 2 bytes and short *)\n\nLemma address_mapsto_2bytes_aux: \n forall (sh : Share.t)\n   (b0 b1 b2 b3 : byte)\n   (b : block) (i : ptrofs)\n   (SZ : Ptrofs.unsigned i + 2 < Ptrofs.modulus)\n   (r : readable_share sh),\npredicates_sl.sepcon\n     (predicates_hered.allp\n        (res_predicates.jam (adr_range_dec (b, Ptrofs.unsigned i) (size_chunk Mint8unsigned))\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - snd (b, Ptrofs.unsigned i))) [Byte b0] Undef)) sh loc)\n           res_predicates.noat))\n     (predicates_hered.allp\n        (res_predicates.jam\n           (adr_range_dec (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1))) (size_chunk Mint8unsigned))\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - snd (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1)))))\n                    [Byte b1] Undef)) sh loc) res_predicates.noat)) = \n predicates_hered.allp\n     (res_predicates.jam (adr_range_dec (b, Ptrofs.unsigned i) (size_chunk Mint16unsigned))\n        (fun loc : address =>\n         res_predicates.yesat compcert_rmaps.RML.R.NoneP\n           (compcert_rmaps.VAL\n              (nth (Z.to_nat (snd loc - snd (b, Ptrofs.unsigned i))) [Byte b0; Byte b1] Undef)) sh loc)\n    res_predicates.noat).\nProof.\nintros. simpl snd. simpl size_chunk.\n repeat   match goal with |- context [Ptrofs.add i (Ptrofs.repr ?A)] =>\n    replace (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr A)))\n    with (A + Ptrofs.unsigned i)\n    by (unfold Ptrofs.add; rewrite (Ptrofs.unsigned_repr (Z.pos _)) by rep_lia;\n        rewrite Ptrofs.unsigned_repr by rep_lia; rep_lia)\n   end.\n    rewrite  (res_predicates.allp_jam_split2 _ _ _ \n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0; Byte b1] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n                    [Byte b0] Undef)) sh loc)\n           (fun loc : address =>\n            res_predicates.yesat compcert_rmaps.RML.R.NoneP\n              (compcert_rmaps.VAL\n                 (nth (Z.to_nat (snd loc - (1+Ptrofs.unsigned i)))\n                    [Byte b1] Undef)) sh loc)\n           (adr_range_dec (b, Ptrofs.unsigned i) 2)\n           (adr_range_dec (b, Ptrofs.unsigned i) 1)\n           (adr_range_dec (b, 1 + Ptrofs.unsigned i) 1)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0; Byte b1] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - Ptrofs.unsigned i))\n           [Byte b0] Undef)).\n   2: eexists;\n    apply (res_predicates.is_resource_pred_YES_VAL' sh \n     (fun loc => nth (Z.to_nat (snd loc - (1+Ptrofs.unsigned i)))\n           [Byte b1] Undef)).\n    2:{ forget (Ptrofs.unsigned i) as j. clear.\n         split; intros [b1 z1]. simpl. intuition rep_lia.\n         simpl. intuition rep_lia.\n       }\n    2:{ intros. destruct l; destruct H; subst. f_equal. f_equal.\n          rewrite (app_nth1 [Byte b0] [Byte b1]); auto.\n        simpl. rep_lia.\n       }\n    2:{ intros. f_equal. f_equal. \n       destruct l; destruct H. subst b4. simpl snd.\n       assert (z = 1 + Ptrofs.unsigned i) by lia. subst z.\n        rewrite Z.sub_diag.\n        replace (1 + Ptrofs.unsigned i - Ptrofs.unsigned i) with 1 by lia.\n          reflexivity.\n      }\n    2:{ intros. left. destruct H0. hnf in H0. rewrite H0 in H1 . clear H0.\n        destruct l, H. subst. simpl snd in *.\n        assert (Z.to_nat (z - Ptrofs.unsigned i) < 2)%nat by rep_lia.\n        clear - H1. destruct (Z.to_nat (z - Ptrofs.unsigned i)) as [|[|[|]]]; inv H1; apply I.\n       }\n   f_equal.\nQed.\n\nLemma zero_ext_16: forall z,\n  0 <= z < 65536 ->\n  Int.zero_ext 16 (Int.repr z) = Int.repr z.\nProof.\n  intros. unfold Int.zero_ext. f_equal.\n  rewrite Zbits.Zzero_ext_mod by rep_lia.\n  replace (two_p 16) with (65536) by reflexivity.\n  rewrite Zmod_small; rewrite Int.unsigned_repr; rep_lia.\nQed.\n\nLemma address_mapsto_2bytes:\n forall (sh : Share.t)\n    (b0 b1 : byte)\n    (b : block)\n    (i : ptrofs)\n    (SZ : Ptrofs.unsigned i + 2 < Ptrofs.modulus)\n    (AL : (2 | Ptrofs.unsigned i))\n    (r : readable_share sh),\npredicates_sl.sepcon (res_predicates.address_mapsto Mint8unsigned (Vubyte b0) sh (b, Ptrofs.unsigned i))\n  (res_predicates.address_mapsto Mint8unsigned (Vubyte b1) sh\n     (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1)))) = res_predicates.address_mapsto Mint16unsigned\n                                                              (Vint (Int.repr (decode_int [b0; b1]))) sh\n                                                              (b, Ptrofs.unsigned i).\nProof.\n  intros. unfold res_predicates.address_mapsto. rewrite <- !exp_equiv.\n  apply predicates_hered.pred_ext.\n  - repeat change (exp ?A) with (predicates_hered.exp A).\n    normalize.normalize.\n    intros bl1 [A1 [B1 _]] bl0.\n    normalize.normalize.\n    destruct H as [A0 [ B0 _]].\n    destruct bl0 as [ | c0 [|]]; inv A0; inv B0. \n    destruct bl1 as [ | c1 [|]]; inv A1; inv B1.\n    destruct c0; try discriminate.\n    destruct c1; try discriminate.\n    apply decode_val_Vubyte_inj in H0,H1. subst.\n    apply (predicates_hered.exp_right [Byte b0; Byte b1]).\n    rewrite predicates_hered.prop_true_andp.\n    2:{ split3. reflexivity. unfold decode_val. simpl.\n        f_equal. apply zero_ext_16. \n        pose proof (decode_int_range [b0; b1]). simpl in H.\n        assert (two_power_pos 16 = 65536) by reflexivity. lia. apply AL. \n      }\n  match goal with |- predicates_hered.derives ?A ?B => \n        assert (EQ: A=B); [ | rewrite EQ; apply predicates_hered.derives_refl]\n    end.\n  apply address_mapsto_2bytes_aux; auto.\n - repeat change (exp ?A) with (predicates_hered.exp A).\n   normalize.normalize.\n   intros bl [? [? ?]].\n    simpl snd in H1.\n   destruct bl as [|c0 [| c1 [| c2 [| c3 [|]]]]]; inv H.\n   unfold decode_val, proj_bytes in H0.\n   destruct c0; try solve [destruct Archi.ptr64 eqn:AP; discriminate].\n   destruct c1; try solve [destruct Archi.ptr64 eqn:AP; discriminate].\n   apply Vint_inj in H0.\n   pose proof (decode_int_range [b0;b1]).\n   pose proof (decode_int_range [i0;i1]).\n   change (two_p _) with 65536 in H,H2.\n   rewrite zero_ext_16 in H0 by lia.\n   apply repr_inj_unsigned in H0; try rep_lia.\n    apply decode_int_inj in H0.\n   clear H H2. inv H0.\n  apply predicates_hered.exp_right with [Byte b1].\n  normalize.normalize.\n  apply predicates_hered.exp_right with [Byte b0].\n  rewrite !predicates_hered.prop_true_andp by \n (split3; [ reflexivity |  | apply Z.divide_1_l  ];\n unfold decode_val, Vubyte; simpl; f_equal;\n rewrite decode_int_single;\n apply zero_ext_inrange; change (two_p _ - 1) with 255;\n rewrite Int.unsigned_repr by rep_lia; rep_lia).\n  match goal with |- predicates_hered.derives ?A ?B => \n        assert (EQ: B=A); [ | rewrite EQ; apply predicates_hered.derives_refl]\n    end.\n  apply address_mapsto_2bytes_aux; auto.\n  reflexivity.\nQed.\n\nLemma nonlock_permission_2bytes:\n forall (sh : Share.t)\n     (b : block) (i : ptrofs) \n     (SZ : Ptrofs.unsigned i + 2 < Ptrofs.modulus),\n(res_predicates.nonlock_permission_bytes sh (b, Ptrofs.unsigned i) 1\n   * res_predicates.nonlock_permission_bytes sh (b, Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr 1))) 1)%logic = \nres_predicates.nonlock_permission_bytes sh (b, Ptrofs.unsigned i) 2.\nProof.\nintros.\n repeat   match goal with |- context [Ptrofs.add i (Ptrofs.repr ?A)] =>\n    replace (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr A)))\n    with (A + Ptrofs.unsigned i)\n    by (unfold Ptrofs.add; rewrite (Ptrofs.unsigned_repr (Z.pos _)) by rep_lia;\n        rewrite Ptrofs.unsigned_repr by rep_lia; rep_lia)\n   end.\n rewrite (res_predicates.nonlock_permission_bytes_split2 1 1 2 sh) by lia.\n repeat change (predicates_sl.sepcon ?A ?B) with (A * B)%logic.\n rewrite !(Z.add_comm (Ptrofs.unsigned i)).\n f_equal.\nQed.\n\nLemma tc_val_short: forall (b0 b1 : byte),\n  tc_val tushort (Vint (Int.repr (decode_int [b0; b1]))).\nProof.\n  intros. simpl. pose proof (decode_int_range [b0; b1]).\n  simpl in H. assert (two_power_pos 16 = 65536) by reflexivity.\n  rewrite Int.unsigned_repr; rep_lia.\nQed.\n\nLemma prop_true_eq: forall  {A : Type} {ND : NatDed A} (P : Prop),\n  P ->\n  !! P = !! True.\nProof.\n  intros. apply ND_prop_ext. split; auto.\nQed.\n\n\n(* The main result: 2 consecutive bytes can be interpreted as a single short *)\nLemma data_at_short_bytes: forall sh\n  (b0 b1: byte) p,\n  field_compatible tushort [] p ->\n  (data_at sh tuchar (Vubyte b0) p *\n  data_at sh tuchar (Vubyte b1) (offset_val 1 p))%logic =\n  data_at sh tushort (Vint (Int.repr (decode_int [b0; b1]))) p.\nProof.\n   intros sh b0 b1 p. unfold data_at. unfold field_at. normalize.\n    rewrite !(prop_true_andp _ _ H).\n  assert (H': field_compatible tuchar [] p). {\n    destruct H as [? [? [? [? ?]]]].\n    split3; auto. destruct p; try contradiction.\n    red in H1,H2,H3. split3; auto.\n   red; simpl sizeof in *. lia.\n   red. eapply align_compatible_rec_by_value; [reflexivity | ].\n   apply Z.divide_1_l.\n  }\n  assert (H'': field_compatible tuchar [] (offset_val 1 p)). {\n    unfold offset_val.\n    destruct H as [? [? [? [? ?]]]].\n    split3; auto. destruct p; try contradiction. apply I.\n    red in H1,H2,H3.\n    unfold Ptrofs.add. rewrite Ptrofs.unsigned_repr by rep_lia.\n    destruct p; try contradiction.\n   simpl in H1.\n    split3; auto.\n     red; simpl sizeof in *. rewrite Ptrofs.unsigned_repr by rep_lia. rep_lia.\n   red. eapply align_compatible_rec_by_value; [reflexivity | ].\n   apply Z.divide_1_l.\n  }\n   rewrite (prop_true_andp _ _ H').\n   rewrite (prop_true_andp _ _ H'').\n   simpl. rewrite !data_at_rec_eq. simpl. \n    unfold at_offset. normalize. change (unfold_reptype ?x) with x.\n    assert (isptr p) by apply H.\n    destruct p; inversion H0. clear H0.\n    unfold mapsto. rewrite (prop_true_eq _ (tc_val_short b0 b1)). simpl.\n    destruct H as [_ [_ [SZ [AL _]]]]. red in SZ. simpl sizeof in SZ.\n    apply align_compatible_rec_by_value_inv with (ch := Mint16unsigned) in AL; auto.\n    simpl in AL.\n    rewrite !(prop_true_andp _ _ Logic.I).\n    rewrite !(prop_false_andp ( _ = Vundef)) by (intro Hx; inv  Hx).\n    rewrite !orp_FF.\n    rewrite !(prop_true_andp (_ /\\ _))\n   by (split; [apply (tc_val_tc_val' _ _ (tc_val_Vubyte _)) | apply Z.divide_1_l]).\n   destruct (readable_share_dec sh); simpl; normalize.\n    + rewrite !Int.unsigned_repr by rep_lia. \n      rewrite !(prop_true_andp (Byte.unsigned _ <= _)) by rep_lia.\n   repeat change (?A * ?B)%logic with (predicates_sl.sepcon A B).\n   rewrite ?ptrofs_add_repr_0_r.\n   apply address_mapsto_2bytes; auto.\n   \n   +\n   rewrite ?ptrofs_add_repr_0_r.\n       rewrite !prop_true_andp.\n      2 : split; auto; hnf; intros; apply tc_val_short.\n      apply nonlock_permission_2bytes; auto.\nQed.\n\nEnd DataAtNumeric.\n\nLemma field_at_values_cohere {cs:compspecs}:\n  forall sh1 sh2 t gfs\n            (v1 v2 : reptype (nested_field_type t gfs))\n             (p: val),\n       value_defined (nested_field_type t gfs) v1 ->\n       value_defined (nested_field_type t gfs) v2 ->\n    readable_share sh1 -> readable_share sh2 ->\n   field_at sh1 t gfs v1 p * field_at sh2 t gfs v2 p |-- !!(v1=v2).\nProof. intros.\n  unfold field_at, at_offset; Intros.\n  destruct H3 as [? _]. destruct p; try contradiction.\n  apply data_at_rec_values_cohere; auto.\nQed.\n\nLemma data_at_values_cohere {cs:compspecs}:\n  forall sh1 sh2 t\n            (v1 v2 : reptype t)\n             (p: val),\n       value_defined t v1 ->\n       value_defined t v2 ->\n    readable_share sh1 -> readable_share sh2 ->\n   data_at sh1 t v1 p * data_at sh2 t v2 p |-- !!(v1=v2).\nProof. intros.\n  apply field_at_values_cohere; auto.\nQed.\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/data_at_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2974699363766584, "lm_q1q2_score": 0.15105876295844725}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.EnumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.Core\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.WordFacts\n        Fiat.Narcissus.Common.ComposeCheckSum\n        Fiat.Narcissus.Common.ComposeIf\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.SolverOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Stores.EmptyStore\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.Bool\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.Vector\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.IPChecksum.\n\nRequire Import Bedrock.Word.\n\nImport Vectors.VectorDef.VectorNotations.\nOpen Scope string_scope.\nOpen Scope Tuple_scope.\n\nDefinition InjectEnum {n A}\n           (gallina_constructors: VectorDef.t A n)\n           (enum_member: Fin.t n) : A :=\n  VectorDef.nth gallina_constructors enum_member.\n  Require Import IPv4Header.\n\nDefinition MakeDecoder {A}\n           (impl: ByteString -> unit -> option (A * ByteString * unit))\n           (bs: ByteString) : option (A * ByteString) :=\n  (* let bs := {| padding := 0; front := WO; paddingOK := zero_lt_eight; byteString := buffer |} in *)\n  match impl bs () with\n  | Some (pkt, bs, _) => Some (pkt, bs)\n  | None => None\n  end.\n\nSection FormatWord.\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  (* Extracting words as Int64 prevents us from recursing on them directly *)\n\n  Fixpoint encode_word'_recurse_on_size (sz : nat) (w : word sz) (b' : B) {struct sz} : B.\n  Proof.\n    destruct sz.\n    - apply b'.\n    - apply (enqueue_opt (whd w) (encode_word'_recurse_on_size sz (wtl w) b')).\n  Defined.\n\n  Lemma format'_on_size_correct :\n    forall sz w b', encode_word' sz w b' = encode_word'_recurse_on_size sz w b'.\n  Proof.\n    induction sz; dependent destruction w; intros; simpl.\n    - reflexivity.\n    - rewrite IHsz; reflexivity.\n  Qed.\nEnd FormatWord.\n\nSection Ethernet.\n  Require Import EthernetHeader.\n\n  Inductive fiat_ethernet_type := ARP | IP | RARP.\n\n  Definition fiat_ethernet_decode packet_length := MakeDecoder (fst (frame_decoder packet_length)).\n\n  Definition List_of_vector {A n} (v: Vector.t A n) : list A :=\n    Vector.fold_right List.cons v nil.\n\n  Definition fiat_ethernet_destruct_packet {A}\n             (f: forall (Destination : list char)\n                   (Source : list char)\n                   (type : fiat_ethernet_type),\n                 A)\n             (packet: EthernetHeader) :=\n    f  (List_of_vector packet!\"Destination\")\n       (List_of_vector packet!\"Source\")\n       (InjectEnum [ARP; IP; RARP] packet!\"Type\").\nEnd Ethernet.\n\nSection ARPv4.\n  Require Import ARPPacket.\n\n  Inductive fiat_arpv4_hardtype := Ethernet | IEEE802 | Chaos.\n  Inductive fiat_arpv4_prottype := IPv4 | IPv6.\n  Inductive fiat_arpv4_operation := Request | Reply | RARPRequest | RARPReply.\n\n  Definition fiat_arpv4_decode := MakeDecoder (fst ARP_Packet_decoder).\n\n  Definition fiat_arpv4_destruct_packet {A}\n             (f: forall (HardType : fiat_arpv4_hardtype)\n                   (ProtType : fiat_arpv4_prottype)\n                   (Operation : fiat_arpv4_operation)\n                   (SenderHardAddress : list char)\n                   (SenderProtAddress : list char)\n                   (TargetHardAddress : list char)\n                   (TargetProtAddress : list char),\n                 A)\n             (packet: ARPPacket) : A :=\n    f (InjectEnum [Ethernet; IEEE802; Chaos] packet!\"HardType\")\n      (InjectEnum [IPv4; IPv6] packet!\"ProtType\")\n      (InjectEnum [Request; Reply; RARPRequest; RARPReply] packet!\"Operation\")\n      packet!\"SenderHardAddress\"\n      packet!\"SenderProtAddress\"\n      packet!\"TargetHardAddress\"\n      packet!\"TargetProtAddress\".\nEnd ARPv4.\n\nSection IPv4.\n  Require Import IPv4Header.\n\n  Definition fiat_ipv4_decode := MakeDecoder IPv4_decoder_impl.\n\n  Inductive fiat_ipv4_protocol :=\n  | ICMP | TCP | UDP.\n\n  Definition fiat_ipv4_protocol_to_enum (proto: fiat_ipv4_protocol) : EnumType [\"ICMP\"; \"TCP\"; \"UDP\"] :=\n    match proto with\n    | ICMP => ```\"ICMP\"\n    | TCP => ```\"TCP\"\n    | UDP => ```\"UDP\"\n    end.\n\n  Definition fiat_ipv4_construct_packet\n             (TotalLength : (word 16))\n             (ID : (word 16))\n             (DF : bool)\n             (MF : bool)\n             (FragmentOffset : word 13)\n             (TTL : char)\n             (Protocol : fiat_ipv4_protocol)\n             (SourceAddress : word 32)\n             (DestAddress : word 32)\n             (Options : list (word 32)) : IPv4_Packet :=\n    <\"TotalLength\" :: TotalLength,\n     \"ID\" :: ID,\n     \"DF\" :: DF,\n     \"MF\" :: MF,\n     \"FragmentOffset\" :: FragmentOffset,\n     \"TTL\" :: TTL,\n     \"Protocol\" :: fiat_ipv4_protocol_to_enum Protocol,\n     \"SourceAddress\" :: SourceAddress,\n     \"DestAddress\" :: DestAddress,\n     \"Options\" :: Options>.\n\n  Definition fiat_ipv4_destruct_packet {A}\n             (f: forall (TotalLength : (word 16))\n                   (ID : (word 16))\n                   (DF : bool)\n                   (MF : bool)\n                   (FragmentOffset : word 13)\n                   (TTL : char)\n                   (Protocol : fiat_ipv4_protocol)\n                   (SourceAddress : word 32)\n                   (DestAddress : word 32)\n                   (Options : list (word 32)),\n                 A)\n              (packet : IPv4_Packet) : A :=\n    f packet!\"TotalLength\"\n      packet!\"ID\"\n      packet!\"DF\"\n      packet!\"MF\"\n      packet!\"FragmentOffset\"\n      packet!\"TTL\"\n      (InjectEnum [ICMP; TCP; UDP] packet!\"Protocol\")\n      packet!\"SourceAddress\"\n      packet!\"DestAddress\"\n      packet!\"Options\".\nEnd IPv4.\n\nSection TCP.\n  Require Import TCP_Packet.\n\n  Definition fiat_tcp_decode srcAddress dstAddress tcpLength :=\n    MakeDecoder (TCP_Packet_decoder_impl srcAddress dstAddress tcpLength).\n\n  Definition fiat_tcp_destruct_packet {A}\n             (f: forall (SourcePort : word 16)\n                   (DestPort : word 16)\n                   (SeqNumber : word 32)\n                   (AckNumber : word 32)\n                   (NS : bool) (* ECN-nonce concealment protection flag *)\n                   (CWR : bool) (* Congestion Window Reduced (CWR) flag *)\n                   (ECE : bool) (* ECN-Echo flag *)\n                   (ACK : bool) (* Acknowledgment field is significant flag *)\n                   (PSH : bool) (* Push function flag *)\n                   (RST : bool) (* Reset the connection flag *)\n                   (SYN : bool) (* Synchronize sequence numbers flag *)\n                   (FIN : bool) (* N srcAddress dstAddress udpLength o more data from sender flag*)\n                   (WindowSize : word 16)\n                   (UrgentPointer : option (word 16))\n                   (Options : list (word 32))\n                   (Payload : list char),\n                 A)\n             (packet: TCP_Packet) : A :=\n    f packet!\"SourcePort\"\n      packet!\"DestPort\"\n      packet!\"SeqNumber\"\n      packet!\"AckNumber\"\n      packet!\"NS\"\n      packet!\"CWR\"\n      packet!\"ECE\"\n      packet!\"ACK\"\n      packet!\"PSH\"\n      packet!\"RST\"\n      packet!\"SYN\"\n      packet!\"FIN\"\n      packet!\"WindowSize\"\n      packet!\"UrgentPointer\"\n      packet!\"Options\"\n      packet!\"Payload\".\nEnd TCP.\n\nSection UDP.\n  Require Import UDP_Packet.\n\n  Definition fiat_udp_decode srcAddress dstAddress udpLength :=\n    MakeDecoder (UDP_Packet_decoder_impl srcAddress dstAddress udpLength).\n\n  Definition fiat_udp_destruct_packet {A}\n             (f: forall (SourcePort : word 16)\n                   (DestPort : word 16)\n                   (Payload : list char),\n                 A)\n             (packet: UDP_Packet) : A :=\n    f packet!\"SourcePort\"\n      packet!\"DestPort\"\n      packet!\"Payload\".\nEnd UDP.\n\nRequire Import ExtrOcamlBasic ExtrOcamlNatInt ExtrOcamlString.\n\nExtract Inductive prod => \"(*)\"  [ \"(,)\" ].\n\n(** * Inline a few functions *)\nExtraction Inline DecodeBindOpt2.\nExtraction Inline If_Opt_Then_Else.\nExtraction Inline decode_nat decode_word decode_word'.\n\n(** * Extract words as int64\n      (Only works for word length < 64) *)\nExtract Constant whd => \"(fun _ w -> ((Int64.logand Int64.one w) = Int64.one))\".\nExtract Constant wtl => \"(fun _ w -> (Int64.shift_right_logical w 1))\".\nExtract Constant wplus => \"(fun _ w w' -> Int64.add w w')\".\nExtract Constant wmult => \"(fun _ w w' -> Int64.mul w w')\".\nExtract Constant wminus => \"(fun _ w w' -> Int64.max (Int64.zero) (Int64.sub w w'))\".\nExtract Constant weq => \"(fun _ w w' -> w = w')\".\nExtract Constant weqb => \"(fun _ w w' -> w = w')\".\nExtract Constant wlt => \"(fun _ w w' -> w < w')\".\nExtract Constant wlt_dec => \"(fun _ w w' -> w < w')\".\nExtract Constant wand => \"(fun _ w w' -> Int64.logand w w')\".\nExtract Constant wor => \"(fun _ w w' -> Int64.logor w w')\".\nExtract Constant wnot => \"(fun _ w -> Int64.lognot w)\".\nExtract Constant wneg => \"(fun _ w w' -> failwith \"\"Called Wneg\"\")\".\nExtract Constant combine => \"(fun _ w w' -> failwith \"\"Using combine\"\")\".\nExtract Constant wordToNat => \"(fun _ w -> Int64.to_int w)\". (* Not ideal *)\nExtract Constant natToWord => \"(fun _ w -> Int64.of_int w)\".\nExtract Constant wzero => \"(fun _ -> Int64.zero)\".\nExtract Constant wzero' => \"(fun _ -> Int64.zero)\".\nExtract Constant wones => \"(fun n -> Int64.sub (Int64.shift_left Int64.one n) Int64.one)\".\n\nExtract Constant SW_word => \"(fun sz b n -> Int64.add (if b then Int64.shift_left Int64.one sz else Int64.zero) n)\".\n\nExtract Inductive Word.word =>\nint64 [\"Int64.zero\" \"(fun (b, _, w') -> Int64.add (if b then Int64.one else Int64.zero) (Int64.shift_left w' 1))\"]\n      \"failwith \"\"Destructing an int64\"\"\".\n\n(** * Don't recurse on int64 *)\nExtract Constant encode_word' => \"encode_word'_recurse_on_size\".\n\n(** * Special case of internet checksum *)\nExtract Constant InternetChecksum.add_bytes_into_checksum =>\n\"(fun b_hi b_lo checksum ->\n    let oneC_plus w w' =\n      let sum = Int64.add w w' in\n      let mask = Int64.of_int 65535 in\n      (Int64.add (Int64.logand sum mask)\n                 (Int64.shift_right_logical sum 16))\n    in oneC_plus (Int64.logor (Int64.shift_left b_hi 8) b_lo) checksum)\".\n\nExtract Constant InternetChecksum.OneC_plus => \"failwith \"\"Calling OneC_plus\"\"\".\n\n(** Efficient bit strings *)\n\nExtract Inductive ByteString =>\n  \"BitString.t\"\n    [\"(fun _ -> failwith \"\"Constructing a ByteString\"\")\"]\n    \"(fun _ _ -> failwith \"\"Destructing a ByteString\"\")\".\n\nExtract Constant ByteString_id => \"(BitString.create ())\".\nExtract Constant ByteString_enqueue => \"BitString.enqueue\".\nExtract Constant ByteString_dequeue => \"BitString.dequeue\".\nExtract Constant length_ByteString => \"BitString.bitlength\".\nExtract Constant ByteString_enqueue_ByteString => \"BitString.append\".\n\nExtraction \"Fiat4Mirage\"\n           fiat_ethernet_decode\n           fiat_ethernet_destruct_packet\n           fiat_arpv4_decode\n           fiat_arpv4_destruct_packet\n           fiat_ipv4_decode\n           fiat_ipv4_destruct_packet\n           fiat_tcp_decode\n           fiat_tcp_destruct_packet\n           fiat_udp_decode\n           fiat_udp_destruct_packet\n           encode_word'_recurse_on_size.\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/NetworkStack/Fiat4Mirage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15105539659434047}}
{"text": "Require Import UNIVERSE.\nRequire Import Events.\nRequire Import CoqlibC.\nRequire Import Simulation.\nRequire Import LinkingC.\nRequire Import JMeq.\nRequire Import SmallstepC.\n\nRequire Import ModSem Mod Sem.\nRequire Import SimSymb SimMem SimMod SimModSem SimProg SimProg.\nRequire Import ModSemProps SemProps Ord.\nRequire Import Sound Preservation AdequacySound.\nRequire Import Program RUSC.\n\nSet Implicit Arguments.\n\n\n\n\n\n\nSection SIMGE.\n\n  Context `{SM: SimMem.class}.\n  Context `{SU: Sound.class}.\n  Context {SS: SimSymb.class SM}.\n  Inductive sim_ge (sm0: SimMem.t): Ge.t -> Ge.t -> Prop :=\n  | sim_ge_src_stuck\n      ge_tgt skenv_link_src skenv_link_tgt:\n      sim_ge sm0 ([], skenv_link_src) (ge_tgt, skenv_link_tgt)\n  | sim_ge_intro\n      msps ge_src ge_tgt skenv_link_src skenv_link_tgt\n      (SIMSKENV: List.Forall (fun msp => ModSemPair.sim_skenv msp sm0) msps)\n      (SIMMSS: List.Forall (ModSemPair.sim) msps)\n      (GESRC: ge_src = (map (ModSemPair.src) msps))\n      (GETGT: ge_tgt = (map (ModSemPair.tgt) msps))\n      (SIMSKENVLINK: exists ss_link, SimSymb.sim_skenv sm0 ss_link skenv_link_src skenv_link_tgt)\n      (MFUTURE: List.Forall (fun msp => SimMem.future msp.(ModSemPair.sm) sm0) msps)\n      (SESRC: List.Forall (fun ms => (ModSem.to_semantics ms).(symbolenv) = skenv_link_src) ge_src)\n      (SETGT: List.Forall (fun ms => (ModSem.to_semantics ms).(symbolenv) = skenv_link_tgt) ge_tgt):\n      sim_ge sm0 (ge_src, skenv_link_src) (ge_tgt, skenv_link_tgt).\n\n  Lemma find_fptr_owner_fsim\n        sm0 ge_src ge_tgt fptr_src fptr_tgt ms_src\n        (SIMGE: sim_ge sm0 ge_src ge_tgt)\n        (SIMFPTR: SimMem.sim_val sm0 fptr_src fptr_tgt)\n        (FINDSRC: Ge.find_fptr_owner ge_src fptr_src ms_src):\n      exists msp,\n        <<SRC: msp.(ModSemPair.src) = ms_src>>\n        /\\ <<FINDTGT: Ge.find_fptr_owner ge_tgt fptr_tgt msp.(ModSemPair.tgt)>>\n        /\\ <<SIMMS: ModSemPair.sim msp>>\n        /\\ <<SIMSKENV: ModSemPair.sim_skenv msp sm0>>\n        /\\ <<MFUTURE: SimMem.future msp.(ModSemPair.sm) sm0>>.\n  Proof.\n    inv SIMGE.\n    { inv FINDSRC; ss. }\n    rewrite Forall_forall in *. inv FINDSRC. ss.\n    rewrite in_map_iff in MODSEM. des. rename x into msp. esplits; eauto. clarify.\n    specialize (SIMMSS msp). exploit SIMMSS; eauto. clear SIMMSS. intro SIMMS.\n    specialize (SIMSKENV msp). exploit SIMSKENV; eauto. clear SIMSKENV. intro SIMSKENV.\n\n    exploit SimSymb.sim_skenv_sim_skenv_weak; try apply SIMSKENV. intro SIMFUNC; des.\n    inv SIMFUNC. exploit FUNCFSIM; eauto. i; des. clear_tac. inv SIM. econs; eauto.\n    apply in_map_iff. esplits; eauto.\n\n  Qed.\n\n  Theorem mfuture_preserves_sim_ge\n          sm0 ge_src ge_tgt sm1\n          (SIMGE: sim_ge sm0 ge_src ge_tgt)\n          (MFUTURE: SimMem.future sm0 sm1):\n      <<SIMGE: sim_ge sm1 ge_src ge_tgt>>.\n  Proof.\n    inv SIMGE.\n    { econs; eauto. }\n    econs 2; try reflexivity; eauto.\n    - rewrite Forall_forall in *. ii. eapply ModSemPair.mfuture_preserves_sim_skenv; eauto.\n    - des. esplits; eauto. eapply SimSymb.mfuture_preserves_sim_skenv; eauto.\n    - rewrite Forall_forall in *. ii. etrans; eauto.\n  Qed.\n\n  Lemma sim_ge_cons\n        sm_init tl_src tl_tgt msp skenv_link_src skenv_link_tgt\n        (SAFESRC: tl_src <> [])\n        (SIMMSP: ModSemPair.sim msp)\n        (SIMGETL: sim_ge sm_init (tl_src, skenv_link_src) (tl_tgt, skenv_link_tgt))\n        (SIMSKENV: ModSemPair.sim_skenv msp sm_init)\n        (MFUTURE: SimMem.future (ModSemPair.sm msp) sm_init)\n        (SESRC: (symbolenv (ModSemPair.src msp)) = skenv_link_src)\n        (SETGT: (symbolenv (ModSemPair.tgt msp)) = skenv_link_tgt):\n      <<SIMGE: sim_ge sm_init (msp.(ModSemPair.src) :: tl_src, skenv_link_src)\n                      (msp.(ModSemPair.tgt) :: tl_tgt, skenv_link_tgt)>>.\n  Proof. red. inv SIMGETL; ss. econstructor 2 with (msps := msp :: msps); eauto. Qed.\n\n  Lemma to_msp_tgt: forall skenv_tgt skenv_src pp sm_init,\n          map ModSemPair.tgt (map (ModPair.to_msp skenv_src skenv_tgt sm_init) pp) =\n          map (fun md => Mod.modsem md skenv_tgt) (ProgPair.tgt pp).\n  Proof. i. ginduction pp; ii; ss. f_equal. erewrite IHpp; eauto. Qed.\n\n  Lemma to_msp_src: forall skenv_tgt skenv_src pp sm_init,\n      map ModSemPair.src (map (ModPair.to_msp skenv_src skenv_tgt sm_init) pp) =\n      map (fun md => Mod.modsem md skenv_src) (ProgPair.src pp).\n  Proof. i. ginduction pp; ii; ss. f_equal. erewrite IHpp; eauto. Qed.\n\n  Lemma to_msp_sim_skenv\n        sm_init mp skenv_src skenv_tgt ss_link\n        (WFSRC: SkEnv.wf skenv_src)\n        (WFTGT: SkEnv.wf skenv_tgt)\n        (INCLSRC: SkEnv.includes skenv_src (Mod.sk mp.(ModPair.src)))\n        (INCLTGT: SkEnv.includes skenv_tgt (Mod.sk mp.(ModPair.tgt)))\n        (SIMMP: ModPair.sim mp)\n        (LESS: SimSymb.le (ModPair.ss mp) ss_link)\n        (SIMSKENV: SimSymb.sim_skenv sm_init ss_link skenv_src skenv_tgt):\n        <<SIMSKENV: ModSemPair.sim_skenv (ModPair.to_msp skenv_src skenv_tgt sm_init mp) sm_init>>.\n  Proof.\n    u. econs; ss; eauto; cycle 1.\n    { rewrite ! Mod.get_modsem_skenv_link_spec. eauto. }\n    inv SIMMP.\n    eapply SimSymb.sim_skenv_monotone; revgoals; try rewrite SKSRC; try rewrite SKTGT; try eapply Mod.get_modsem_skenv_spec; try eapply SIMMP; ss; eauto.\n  Qed.\n\n  Theorem init_sim_ge_strong\n          pp p_src p_tgt ss_link skenv_link_src skenv_link_tgt m_src\n          (NOTNIL: pp <> [])\n          (SIMPROG: ProgPair.sim pp)\n          (PSRC: p_src = (ProgPair.src pp))\n          (PTGT: p_tgt = (ProgPair.tgt pp))\n          (SSLE: Forall (fun mp => SimSymb.le (ModPair.ss mp) ss_link) pp)\n          (SIMSK: SimSymb.wf ss_link)\n          (SKSRC: link_sk p_src = Some ss_link.(SimSymb.src))\n          (SKTGT: link_sk p_tgt = Some ss_link.(SimSymb.tgt))\n          (SKENVSRC: Sk.load_skenv ss_link.(SimSymb.src) = skenv_link_src)\n          (SKENVTGT: Sk.load_skenv ss_link.(SimSymb.tgt) = skenv_link_tgt)\n          (WFSKSRC: forall mp (IN: In mp pp), Sk.wf (ModPair.src mp))\n          (WFSKTGT: forall mp (IN: In mp pp), Sk.wf (ModPair.tgt mp))\n          (LOADSRC: Sk.load_mem ss_link.(SimSymb.src) = Some m_src):\n      exists sm_init, <<SIMGE: sim_ge sm_init\n                                      (load_genv p_src (Sk.load_skenv ss_link.(SimSymb.src)))\n                                      (load_genv p_tgt (Sk.load_skenv ss_link.(SimSymb.tgt)))>>\n         /\\ <<MWF: SimMem.wf sm_init>>\n         /\\ <<LOADTGT: Sk.load_mem ss_link.(SimSymb.tgt) = Some sm_init.(SimMem.tgt)>>\n         /\\ <<MSRC: sm_init.(SimMem.src) = m_src>>\n         /\\ (<<SIMSKENV: SimSymb.sim_skenv sm_init ss_link skenv_link_src skenv_link_tgt>>)\n         /\\ (<<INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))>>)\n         /\\ (<<INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))>>)\n         /\\ (<<SSLE: forall mp (IN: In mp pp), SimSymb.le mp.(ModPair.ss) ss_link>>)\n         /\\ (<<MAINSIM: SimMem.sim_val sm_init\n                              (Genv.symbol_address skenv_link_src (prog_main ss_link.(SimSymb.src)))\n                              (Genv.symbol_address skenv_link_tgt (prog_main ss_link.(SimSymb.tgt)))>>).\n  Proof.\n    assert(INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))).\n    { ii. clarify. eapply link_includes; eauto.\n      unfold ProgPair.src. rewrite in_map_iff. esplits; et. }\n    assert(INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))).\n    { ii. clarify. eapply link_includes; eauto.\n      unfold ProgPair.tgt. rewrite in_map_iff. esplits; et. }\n    clarify. exploit SimSymb.wf_load_sim_skenv; eauto. i; des. rename sm into sm_init. clarify.\n    esplits; eauto; cycle 1.\n    { rewrite Forall_forall in *. eauto. }\n    unfold load_genv in *. ss. bar.\n    assert(exists msp_sys,\n              (<<SYSSRC: msp_sys.(ModSemPair.src) = System.modsem (Sk.load_skenv ss_link.(SimSymb.src))>>)\n              /\\ (<<SYSTGT: msp_sys.(ModSemPair.tgt) = System.modsem (Sk.load_skenv ss_link.(SimSymb.tgt))>>)\n              /\\ <<SYSSIM: ModSemPair.sim msp_sys>> /\\ <<SIMSKENV: ModSemPair.sim_skenv msp_sys sm_init>>\n              /\\ (<<MFUTURE: SimMem.future msp_sys.(ModSemPair.sm) sm_init>>)).\n    { exploit SimSymb.system_sim_skenv; eauto. i; des.\n      eexists (ModSemPair.mk _ _ ss_link sm_init). ss. esplits; eauto.\n      - exploit system_local_preservation. intro SYSSU; des. econs.\n        { ss. eauto. }\n        { instantiate (2:= Empty_set). ii; ss. }\n        ii. inv SIMSKENV0. ss.\n        split; cycle 1.\n        { ii; des. inv SAFESRC. inv SIMARGS; ss. esplits; eauto. econs; eauto. }\n        ii. sguard in SAFESRC. des. inv INITTGT.\n        inv SIMARGS; ss. clarify.\n        esplits; eauto.\n        { refl. }\n        { econs; eauto. }\n        pfold.\n        econs; eauto.\n        i.\n        econs; ss; cycle 2.\n        { eapply System.modsem_receptive; et. }\n        { u. esplits; ii; des; ss; eauto. inv H0. }\n        ii. inv STEPSRC.\n        exploit SimSymb.system_axiom; eauto; swap 1 3; swap 2 4.\n        { econs; eauto. }\n        { ss. instantiate (1:= Retv.mk _ _). ss. eauto. }\n        { ss. }\n        { ss. }\n        i; des.\n        assert(SIMGE: SimSymb.sim_skenv sm_arg ss_link (System.globalenv (Sk.load_skenv ss_link.(SimSymb.src)))\n                                        (System.globalenv (Sk.load_skenv ss_link.(SimSymb.tgt)))).\n        { eapply SimSymb.mfuture_preserves_sim_skenv; eauto. }\n        dup SIMGE. eapply SimSymb.sim_skenv_sim_skenv_weak in SIMGE0.\n        inv SIMGE0. exploit FUNCFSIM; eauto. i; des. clarify.\n        esplits; eauto.\n        { left. apply plus_one. econs.\n          - eapply System.modsem_determinate; et.\n          - ss. econs; eauto. }\n        left. pfold.\n        econs 4.\n        { refl. }\n        { eauto. }\n        { econs; eauto. }\n        { econs; eauto. }\n        { inv RETV; ss. unfold Retv.mk in *. clarify. econs; ss; eauto. }\n    }\n    des. rewrite <- SYSSRC. rewrite <- SYSTGT. eapply sim_ge_cons; ss.\n    - ii. destruct pp; ss.\n    - clear_until_bar. clear TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.\n      ginduction pp; ii; ss. unfold link_sk in *. ss. rename a into mp. destruct (classic (pp = [])).\n      { clarify. ss. clear IHpp. inv SSLE. inv H2. cbn in *. clarify.\n        rename H0 into SKSRC. rename H2 into SKTGT.\n        rewrite <- SKSRC in *. rewrite <- SKTGT in *.\n        set (skenv_src := (Sk.load_skenv (ModPair.src mp))) in *.\n        set (skenv_tgt := (Sk.load_skenv (ModPair.tgt mp))) in *.\n        inv SIMPROG. inv H3. rename H2 into SIMMP. inv SIMMP.\n        econstructor 2 with (msps := (map (ModPair.to_msp skenv_src skenv_tgt sm_init) [mp])); eauto; ss; revgoals; econs; eauto.\n        - u. erewrite Mod.get_modsem_skenv_link_spec; ss.\n        - u. erewrite Mod.get_modsem_skenv_link_spec; ss.\n        -  eapply SIMMS; eauto; eapply SkEnv.load_skenv_wf; et.\n        - econs; ss; eauto; cycle 1.\n          { unfold Mod.modsem. rewrite ! Mod.get_modsem_skenv_link_spec. eauto. }\n          r. ss. eapply SimSymb.sim_skenv_monotone; try rewrite SKSRC0; try rewrite SKTGT0;\n                   try apply SIMSKENV; try eapply SkEnv.load_skenv_wf; try eapply Mod.get_modsem_skenv_spec; eauto.\n      }\n      rename H into NNIL.\n      apply link_list_cons_inv in SKSRC; cycle 1. { destruct pp; ss. } des. rename restl into sk_src_tl.\n      apply link_list_cons_inv in SKTGT; cycle 1. { destruct pp; ss. } des. rename restl into sk_tgt_tl.\n      inv SIMPROG. rename H1 into SIMMP. rename H2 into SIMPROG. inv SSLE. rename H1 into SSLEHD. rename H2 into SSLETL. unfold flip.\n      set (skenv_src := (Sk.load_skenv (SimSymb.src ss_link))) in *.\n      set (skenv_tgt := (Sk.load_skenv (SimSymb.tgt ss_link))) in *.\n      assert(WFSRC: SkEnv.wf skenv_src).\n      { eapply SkEnv.load_skenv_wf; et.\n        eapply (link_list_preserves_wf_sk ((ModPair.src mp) :: (ProgPair.src pp))); et.\n        - unfold link_sk. ss. eapply link_list_cons; et.\n        - ii; ss. des; clarify; et. unfold ProgPair.src in *. rewrite in_map_iff in *. des. clarify. et.\n      }\n      assert(WFTGT: SkEnv.wf skenv_tgt).\n      { eapply SkEnv.load_skenv_wf; et.\n        eapply (link_list_preserves_wf_sk ((ModPair.tgt mp) :: (ProgPair.tgt pp))); et.\n        - unfold link_sk. ss. eapply link_list_cons; et.\n        - ii; ss. des; clarify; et. unfold ProgPair.tgt in *. rewrite in_map_iff in *. des. clarify. et.\n      }\n      econstructor 2 with\n          (msps := (map (ModPair.to_msp skenv_src skenv_tgt sm_init) (mp :: pp))); eauto; revgoals.\n      + rewrite Forall_forall in *. i. ss. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n        u in H. rewrite in_map_iff in H. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n      + rewrite Forall_forall in *. i. ss. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n        u in H. rewrite in_map_iff in H. des; clarify.\n        { u. erewrite Mod.get_modsem_skenv_link_spec; ss. }\n      + ss. econs; eauto. rewrite Forall_forall in *. ii. rewrite in_map_iff in H. des. clarify. ss. refl.\n      + ss. f_equal. rewrite to_msp_tgt; ss.\n      + ss. f_equal. rewrite to_msp_src; ss.\n      + ss. econs; ss; eauto.\n        * eapply SIMMP; eauto.\n        * rewrite Forall_forall in *. i. apply in_map_iff in H. des.\n          specialize (SIMPROG x0). special SIMPROG; ss. clarify. eapply SIMPROG; eauto.\n      + ss. econs; ss; eauto.\n        * eapply to_msp_sim_skenv; eauto.\n        * rewrite Forall_forall in *. i. rewrite in_map_iff in *. des. clarify. eapply to_msp_sim_skenv; eauto.\n    - rewrite SYSSRC. ss.\n    - rewrite SYSTGT. ss.\n  Unshelve.\n    all: try apply idx_bot.\n    all: try (by ii; ss).\n  Qed.\n\nEnd SIMGE.\n\n\n\n\n\n\n\n\n\n\n\n\nSection ADQMATCH.\n\n  Context `{SM: SimMem.class}.\n  Context {SS: SimSymb.class SM}.\n  Context `{SU: Sound.class}.\n\n  Variable pp: ProgPair.t.\n  Let p_src := (ProgPair.src pp).\n  Let p_tgt := (ProgPair.tgt pp).\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  Inductive lxsim_stack: SimMem.t ->\n                         list Frame.t -> list Frame.t -> Prop :=\n  | lxsim_stack_nil\n      sm0:\n      lxsim_stack sm0 [] []\n  | lxsim_stack_cons\n      tail_src tail_tgt tail_sm ms_src lst_src0 ms_tgt lst_tgt0 sm_at sm_arg sm_arg_lift sm_init sidx\n      (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n      (MWF: SimMem.wf sm_arg)\n      (GE: sim_ge sm_at sem_src.(globalenv) sem_tgt.(globalenv))\n      (MLE: SimMem.le tail_sm sm_at)\n      (MLE: SimMem.le sm_at sm_arg)\n      (MLELIFT: SimMem.lepriv sm_arg sm_arg_lift)\n      (MLE: SimMem.le sm_arg_lift sm_init)\n      (sound_states_local: sidx -> Sound.t -> Mem.t -> ms_src.(ModSem.state) -> Prop)\n      (PRSV: forall si, local_preservation_noguarantee ms_src (sound_states_local si))\n      (K: forall sm_ret retv_src retv_tgt lst_src1\n          (MLE: SimMem.le sm_arg_lift sm_ret)\n          (MWF: SimMem.wf sm_ret)\n          (SIMRETV: SimMem.sim_retv retv_src retv_tgt sm_ret)\n          (SU: forall si, exists su m_arg, (sound_states_local si) su m_arg lst_src0)\n          (AFTERSRC: ms_src.(ModSem.after_external) lst_src0 retv_src lst_src1),\n          exists lst_tgt1 sm_after i1,\n            (<<AFTERTGT: ms_tgt.(ModSem.after_external) lst_tgt0 retv_tgt lst_tgt1>>)\n            /\\ (<<MLEPUB: SimMem.le sm_at sm_after>>)\n            /\\ (<<LXSIM: lxsim ms_src ms_tgt (fun st => forall si, exists su m_arg, (sound_states_local si) su m_arg st)\n                            i1 lst_src1 lst_tgt1 sm_after>>))\n      (SESRC: (ModSem.to_semantics ms_src).(symbolenv) = skenv_link_src)\n      (SETGT: (ModSem.to_semantics ms_tgt).(symbolenv) = skenv_link_tgt):\n      lxsim_stack sm_init\n                  ((Frame.mk ms_src lst_src0) :: tail_src)\n                  ((Frame.mk ms_tgt lst_tgt0) :: tail_tgt).\n\n  Lemma lxsim_stack_le\n        sm0 frs_src frs_tgt sm1\n        (SIMSTACK: lxsim_stack sm0 frs_src frs_tgt)\n        (MLE: SimMem.le sm0 sm1):\n      <<SIMSTACK: lxsim_stack sm1 frs_src frs_tgt>>.\n  Proof.\n    inv SIMSTACK.\n    { econs 1; eauto. }\n    econs 2; eauto. etransitivity; eauto.\n  Qed.\n\n  Inductive lxsim_lift: idx -> sem_src.(Smallstep.state) -> sem_tgt.(Smallstep.state) -> SimMem.t -> Prop :=\n  | lxsim_lift_intro\n      sm0 tail_src tail_tgt tail_sm i0 ms_src lst_src ms_tgt lst_tgt sidx\n      (GE: sim_ge sm0 sem_src.(globalenv) sem_tgt.(globalenv))\n\n      (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n      (MLE: SimMem.le tail_sm sm0)\n      (sound_states_local: sidx -> Sound.t -> Mem.t -> ms_src.(ModSem.state) -> Prop)\n      (PRSV: forall si, local_preservation_noguarantee ms_src (sound_states_local si))\n      (TOP: lxsim ms_src ms_tgt (fun st => forall si, exists su m_arg, (sound_states_local si) su m_arg st)\n                  i0 lst_src lst_tgt sm0)\n      (SESRC: (ModSem.to_semantics ms_src).(symbolenv) = skenv_link_src)\n      (SETGT: (ModSem.to_semantics ms_tgt).(symbolenv) = skenv_link_tgt):\n      lxsim_lift i0 (State ((Frame.mk ms_src lst_src) :: tail_src)) (State ((Frame.mk ms_tgt lst_tgt) :: tail_tgt)) sm0\n  | lxsim_lift_callstate\n       sm_arg tail_src tail_tgt tail_sm args_src args_tgt\n       (GE: sim_ge sm_arg sem_src.(globalenv) sem_tgt.(globalenv))\n       (STACK: lxsim_stack tail_sm tail_src tail_tgt)\n       (MLE: SimMem.le tail_sm sm_arg)\n       (MWF: SimMem.wf sm_arg)\n       (SIMARGS: SimMem.sim_args args_src args_tgt sm_arg):\n      lxsim_lift idx_bot (Callstate args_src tail_src) (Callstate args_tgt tail_tgt) sm_arg.\n\nEnd ADQMATCH.\n\n\n\n\n\n\n\n\n\n\n\n\n\nSection ADQINIT.\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 NOTNIL: pp <> [].\n  Hypothesis SIMPROG: ProgPair.sim pp.\n  Let p_src := (ProgPair.src pp).\n  Let p_tgt := (ProgPair.tgt pp).\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\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  Theorem init_lxsim_lift_forward\n          st_init_src\n          (INITSRC: sem_src.(Smallstep.initial_state) st_init_src):\n      exists idx st_init_tgt sm_init,\n        <<INITTGT: sem_tgt.(Dinitial_state) st_init_tgt>>\n        /\\ (<<SIM: lxsim_lift sk_link_src sk_link_tgt idx st_init_src st_init_tgt sm_init>>)\n        /\\ (<<INCLSRC: forall mp (IN: In mp pp), SkEnv.includes skenv_link_src (Mod.sk mp.(ModPair.src))>>)\n        /\\ (<<INCLTGT: forall mp (IN: In mp pp), SkEnv.includes skenv_link_tgt (Mod.sk mp.(ModPair.tgt))>>).\n  Proof.\n    ss. inv INITSRC; ss. clarify. rename INITSK into INITSKSRC. rename INITMEM into INITMEMSRC.\n\n    exploit sim_link_sk; eauto. i; des. fold p_tgt in LOADTGT.\n    assert(WFTGT: forall md, In md p_tgt -> <<WF: Sk.wf md >>).\n    { clear - SIMPROG WF. i. subst_locals. u in *. rewrite in_map_iff in *. des. clarify.\n      rewrite Forall_forall in *. exploit SIMPROG; et. intro SIM. inv SIM.\n      unfold Mod.sk in *. rewrite <- SKTGT in *.\n      eapply SimSymb.wf_preserves_wf; et. rewrite SKSRC in *. eapply WF; et. rewrite in_map_iff. esplits; et.\n    }\n    rewrite <- SKSRC in *. rewrite <- SKTGT in *.\n    exploit init_sim_ge_strong; eauto.\n    { ii. eapply WF; et. unfold p_src. unfold ProgPair.src. rewrite in_map_iff. et. }\n    { ii. eapply WFTGT; et. unfold p_tgt. unfold ProgPair.tgt. rewrite in_map_iff. et. }\n    i; des. clarify. ss. des_ifs.\n\n    set(Args.mk (Genv.symbol_address (Sk.load_skenv (SimSymb.src ss_link)) (prog_main (SimSymb.src ss_link)))\n                [] sm_init.(SimMem.src)) as args_src in *.\n    set(Args.mk (Genv.symbol_address (Sk.load_skenv (SimSymb.tgt ss_link)) (prog_main (SimSymb.tgt ss_link)))\n                [] sm_init.(SimMem.tgt)) as args_tgt in *.\n    assert(SIMARGS: SimMem.sim_args args_src args_tgt sm_init).\n    { econs; ss; eauto.\n      - rewrite <- SimMem.sim_val_list_spec. econs; eauto. }\n\n    esplits; eauto.\n    - econs; ss; cycle 1.\n      { ii. eapply initial_state_determ; ss; eauto. }\n      econs; eauto; cycle 1.\n      apply_all_once SimSymb.sim_skenv_sim_skenv_weak. des. inv SIMSKENV.\n      exploit FUNCFSIM; eauto.\n      i; des. clarify.\n    - econs; eauto.\n      + ss. folder. des_ifs.\n      + hnf. econs; eauto.\n      + reflexivity.\n  Qed.\n\nEnd ADQINIT.\n\n\n\n\nSection ADQSTEP.\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\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\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  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  Hypothesis (WFKSSRC: forall md (IN: In md (ProgPair.src pp)), <<WF: Sk.wf md >>).\n  Hypothesis (WFKSTGT: forall md (IN: In md (ProgPair.tgt pp)), <<WF: Sk.wf md >>).\n\n  Theorem lxsim_lift_xsim\n          i0 st_src0 st_tgt0 sm0\n          (LXSIM: lxsim_lift sk_link_src sk_link_tgt i0 st_src0 st_tgt0 sm0)\n    :\n      <<XSIM: xsim sem_src sem_tgt ord (sound_state pp) top1 i0 st_src0 st_tgt0>>\n  .\n  Proof.\n    generalize dependent sm0. generalize dependent st_src0. generalize dependent st_tgt0. generalize dependent i0.\n    pcofix CIH. i. pfold. inv LXSIM; ss; cycle 1.\n    { (* init *)\n      folder. des_ifs. right. econs; eauto.\n      i. econs; eauto; cycle 1.\n      { ii. specialize (SAFESRC _ (star_refl _ _ _ _)). des; ss.\n        - inv SAFESRC.\n        - des_ifs. right. inv SAFESRC.\n          exploit find_fptr_owner_fsim; eauto. { eapply SimMem.sim_args_sim_fptr; eauto. } i; des. clarify.\n          inv SIMMS.\n          inv MSFIND. inv FINDTGT.\n          exploit SIM; eauto. i; des.\n          exploit INITPROGRESS; eauto. i; des.\n          esplits; eauto. econs; eauto. econs; eauto.\n      }\n      { i. ss. inv FINALTGT. }\n      i. inv STEPTGT.\n      specialize (SAFESRC _ (star_refl _ _ _ _)). des.\n      { inv SAFESRC. }\n      bar. inv SAFESRC. ss. des_ifs.\n      bar.\n      exploit find_fptr_owner_fsim; eauto. { eapply SimMem.sim_args_sim_fptr; eauto. } i; des. clarify.\n      exploit find_fptr_owner_determ; ss; eauto.\n      { rewrite Heq. apply FINDTGT. }\n      { rewrite Heq. apply MSFIND. }\n      i; des. clarify.\n\n      inv SIMMS.\n      specialize (SIM sm0).\n      inv MSFIND. inv MSFIND0.\n      exploit SIM; eauto. i; des.\n\n      exploit INITBSIM; eauto. i; des.\n      clears st_init0; clear st_init0. esplits; eauto.\n      - left. apply plus_one. econs; eauto. econs; eauto.\n      - right. eapply CIH.\n        instantiate (1:= sm_init). econs; try apply SIM0; eauto.\n        + ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once. et.\n        + etrans; eauto.\n        + ss. inv GE. folder. rewrite Forall_forall in *. eapply SESRC; et.\n        + ss. inv GE. folder. rewrite Forall_forall in *. eapply SETGT; et.\n\n    }\n\n    sguard in SESRC. sguard in SETGT. folder. rewrite LINKSRC in *. rewrite LINKTGT in *.\n    punfold TOP. rr in TOP. ii. hexploit1 TOP; eauto.\n    { ii. exploit SSSRC. { eapply lift_star; eauto. } intro SUST0; des. inv SUST0. des.\n      simpl_depind. clarify. hexploit FORALLSU; eauto. i; des.\n      specialize (H (sound_states_local si)). esplits; eauto. eapply H; eauto. }\n    inv TOP.\n\n    - (* fstep *)\n      left. exploit SU0.\n      { ss. }\n      i; des. clear SU0. right. econs; ss; eauto.\n      + rename H into FSTEP. inv FSTEP.\n        * econs 1; cycle 1.\n          { ii. des. inv FINALSRC; ss. exfalso. eapply SAFESRC0. u. eauto. }\n          ii. ss. rewrite LINKSRC in *. des. inv STEPSRC; ss; ModSem.tac; swap 2 3.\n          { exfalso. eapply SAFESRC; eauto. }\n          { exfalso. eapply SAFESRC0. u. eauto. }\n          exploit STEP; eauto. i; des_safe.\n          exists i1, (State ((Frame.mk ms_tgt st_tgt1) :: tail_tgt)). esplits; eauto.\n          { assert(T: DPlus ms_tgt lst_tgt tr st_tgt1 \\/ (lst_tgt = st_tgt1 /\\ tr = E0 /\\ ord i1 i0)).\n            { des; et. inv STAR; et. left. econs; et. }\n            clear H. des.\n            - left. split; cycle 1.\n              { eapply lift_receptive_at; eauto. unsguard SESRC. s. des_ifs.\n                subst skenv_link_src; congruence.\n              }\n              eapply lift_dplus; eauto.\n              { unsguard SETGT. ss. des_ifs.\n                subst skenv_link_tgt; congruence.\n              }\n            - right. esplits; eauto. clarify.\n          }\n          pclearbot. right. eapply CIH with (sm0 := sm1); eauto.\n          econs; eauto.\n          { ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once; eauto. }\n          { etransitivity; eauto. }\n        * des. pclearbot. econs 2.\n          { esplits; eauto. eapply lift_dplus; eauto.\n            { unsguard SETGT. ss. des_ifs. subst skenv_link_tgt; congruence. }\n          }\n          right. eapply CIH; eauto. instantiate (1:=sm1). econs; eauto.\n          { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto.\n            eapply rtc_once; eauto. }\n          { etrans; eauto. }\n\n    - (* bstep *)\n      right. ss. hexploit1 SU0; ss.\n      assert(SAFESTEP: safe sem_src (State ({| Frame.ms := ms_src; Frame.st := lst_src |} :: tail_src))\n                       -> safe_modsem ms_src lst_src).\n      { eapply safe_implies_safe_modsem; eauto. }\n      econs; ss; eauto.\n      i. exploit SU0; eauto. intro T. clear SU0. inv T.\n      + econs 1; eauto; revgoals.\n        { ii. des. clear - FINALTGT PROGRESS. inv FINALTGT. ss. ModSem.tac. }\n        { ii. right. des. esplits; eauto. eapply lift_step; eauto. }\n        ii. inv STEPTGT; ModSem.tac. ss. exploit STEP; eauto. i; des_safe.\n        exists i1, (State ((Frame.mk ms_src st_src1) :: tail_src)).\n        esplits; eauto.\n        { des.\n          - left. eapply lift_plus; eauto.\n          - right. esplits; eauto. eapply lift_star; eauto.\n        }\n        pclearbot. right. eapply CIH with (sm0 := sm1); eauto.\n        econs; eauto.\n        { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto. apply rtc_once; eauto. }\n        etransitivity; eauto.\n      + des. pclearbot. econs 2.\n        { esplits; eauto. eapply lift_star; eauto. }\n        right. eapply CIH; eauto.\n        instantiate (1:=sm1). econs; eauto.\n        { folder. ss; des_ifs. eapply mfuture_preserves_sim_ge; eauto. eapply rtc_once; eauto. }\n        { etrans; eauto. }\n\n    - (* call *)\n      left. right. econs; eauto. econs; eauto; cycle 1.\n      { ii. inv FINALSRC. ss. ModSem.tac. }\n      i. inv STEPSRC; ss; ModSem.tac. des_ifs. hexploit1 SU0.\n      { ss. }\n      rename SU0 into CALLFSIM.\n\n      exploit CALLFSIM; eauto. i; des. esplits; eauto.\n      + left. split; cycle 1.\n        { eapply lift_receptive_at.\n          { unsguard SESRC. ss. des_ifs. subst skenv_link_src; congruence. }\n          eapply at_external_receptive_at; et. }\n        apply plus_one. econs; ss; eauto.\n        { eapply lift_determinate_at; et.\n          { unsguard SETGT. ss. des_ifs. subst skenv_link_tgt; congruence. }\n          eapply at_external_determinate_at; et. }\n        des_ifs. econs 1; eauto.\n      + right. eapply CIH; eauto.\n        { instantiate (1:= sm_arg). econs 2; eauto.\n          * ss. folder. des_ifs. eapply mfuture_preserves_sim_ge; eauto. econs 2; et.\n          * instantiate (1:= sm_arg). econs; [eassumption|..]; revgoals; ss.\n            { ii. exploit K; eauto. i; des_safe. pclearbot. esplits; try apply LXSIM; eauto. }\n            { reflexivity. }\n            { et. }\n            { refl. }\n            { et. }\n            { ss. folder. des_ifs. }\n            { eauto. }\n          * reflexivity.\n        }\n\n\n    - (* return *)\n      left. right. econs; eauto.\n      econs; eauto; cycle 1.\n      { ii. ss. inv FINALSRC0. ss. determ_tac ModSem.final_frame_dtm. clear_tac.\n        inv STACK.\n        econs; ss; eauto.\n        - econs; ss; eauto.\n          inv SIMRETV; ss.\n          eapply SimMem.sim_val_int; et.\n        - i. inv FINAL0; inv FINAL1; ss.\n          exploit ModSem.final_frame_dtm; [apply FINAL|apply FINAL0|..]. i; clarify. rewrite INT0 in *. eapply Vint_inj; et.\n        - ii. des_ifs. inv H; ss; ModSem.tac.\n      }\n      i. ss. des_ifs. inv STEPSRC; ModSem.tac. ss.\n      inv STACK; ss. folder. sguard in SESRC0. sguard in SETGT0. des_ifs.\n      determ_tac ModSem.final_frame_dtm. clear_tac.\n      exploit K; try apply SIMRETV; eauto.\n      { etransitivity; eauto. etrans; eauto. }\n      { exploit SSSRC. { eapply star_refl. } intro T; des. inv T. des. simpl_depind. clarify.\n        inv TL. simpl_depind. clarify. des.\n        exploit FORALLSU0; eauto. i; des. esplits; eauto. eapply HD; eauto.\n      }\n      i; des. esplits; eauto.\n      + left. split; cycle 1.\n        { eapply lift_receptive_at.\n          { unsguard SESRC. ss. des_ifs. subst skenv_link_src; congruence. }\n          eapply final_frame_receptive_at; et. }\n        apply plus_one. econs; eauto.\n        { eapply lift_determinate_at.\n          { unsguard SETGT. ss. des_ifs. subst skenv_link_tgt; congruence. }\n          eapply final_frame_determinate_at; et. }\n        econs 4; ss; eauto.\n      + right. eapply CIH; eauto.\n        instantiate (1:= sm_after). econs; ss; cycle 3; eauto.\n        { folder. des_ifs. eapply mfuture_preserves_sim_ge; et. econs 2; et. }\n        { etrans; eauto. }\n  Qed.\n\nEnd ADQSTEP.\n\n\n\nRequire Import BehaviorsC SemProps.\n\nSection ADQ.\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  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\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\n  Let lxsim_lift := (lxsim_lift pp).\n  Hint Unfold lxsim_lift.\n\n  Let skenv_link_src := (Sk.load_skenv sk_link_src).\n  Let skenv_link_tgt := (Sk.load_skenv sk_link_tgt).\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  Hypothesis (WFSKSRC: forall md (IN: In md (ProgPair.src pp)), <<WF: Sk.wf md >>).\n  Hypothesis (WFSKTGT: forall md (IN: In md (ProgPair.tgt pp)), <<WF: Sk.wf md >>).\n\n  Theorem adequacy_local_aux: mixed_simulation sem_src sem_tgt.\n  Proof.\n    subst_locals. econstructor 1 with (order := ord); eauto. generalize wf_ord; intro WF.\n    econstructor; eauto.\n    - eapply preservation; eauto.\n    - eapply preservation_top.\n    - econs 1; ss; eauto. ii.\n      exploit init_lxsim_lift_forward; eauto. { destruct pp; ss. } i; des.\n      assert(WFTGT: forall md, In md (ProgPair.tgt pp) -> <<WF: Sk.wf md >>).\n      { inv INITTGT. inv INIT. ss. }\n      hexploit lxsim_lift_xsim; eauto.\n    - ss. i; des. inv SAFESRC.\n      exploit sim_link_sk; eauto. i; des. des_ifs.\n      exploit SimSymb.wf_load_sim_skenv; eauto. i; des. clarify.\n      symmetry. exploit SimSymb.sim_skenv_public_symbols; et. intro T. s.\n      unfold Genv.public_symbol in *. rewrite T. ss.\n  Unshelve.\n    all: ss.\n  Qed.\n\nEnd ADQ.\n\n\n\nSection BEH.\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  Let sem_src := Sem.sem p_src.\n  Let sem_tgt := Sem.sem p_tgt.\n\n  Theorem adequacy_local: BehaviorsC.improves sem_src sem_tgt.\n  Proof.\n    eapply improves_free_theorem; i.\n    eapply bsim_improves; eauto. eapply mixed_to_backward_simulation; eauto.\n\n    des. inv INIT. ss. exploit sim_link_sk; eauto. i; des. clarify.\n    exploit init_lxsim_lift_forward; eauto. { destruct pp; ss. } { econs; eauto. } i; des.\n    exploit SimSymb.wf_load_sim_skenv; eauto. i; des. clarify.\n    eapply adequacy_local_aux; ss; eauto.\n    { rewrite Forall_forall in *. ss. }\n    { inv INITTGT. inv INIT. ss. }\n  Qed.\n\nEnd BEH.\n\n\n\nProgram Definition mkPR (MR: SimMem.class) (SR: SimSymb.class MR) (MP: Sound.class)\n  : program_relation.t := program_relation.mk\n                            (fun (p_src p_tgt: program) =>\n                               forall (WF: forall x (IN: In x p_src), Sk.wf x),\n                               exists pp,\n                                 (<<SIMS: @ProgPair.sim MR SR MP pp>>)\n                                 /\\ (<<SRCS: (ProgPair.src pp) = p_src>>)\n                                 /\\ (<<TGTS: (ProgPair.tgt pp) = p_tgt>>)) _ _ _.\nNext Obligation.\n(* horizontal composition *)\n  exploit REL0; eauto. { i. eapply WF. rewrite in_app_iff. eauto. } intro T0; des.\n  exploit REL1; eauto. { i. eapply WF. rewrite in_app_iff. eauto. } intro T1; des.\n  clarify. unfold ProgPair.sim in *. rewrite Forall_forall in *. eexists (_ ++ _). esplits; eauto.\n  - rewrite Forall_forall in *. i. rewrite in_app_iff in *. des; [apply SIMS|apply SIMS0]; eauto.\n  - unfold ProgPair.src. rewrite map_app. ss.\n  - unfold ProgPair.tgt. rewrite map_app. ss.\nQed.\nNext Obligation.\n(* adequacy *)\n  destruct (classic (forall x (IN: In x p_src), Sk.wf x)) as [WF|NWF]; cycle 1.\n  { eapply sk_nwf_improves; auto. }\n  specialize (REL WF). des. clarify.\n  eapply (@adequacy_local MR SR MP). auto.\nQed.\nNext Obligation. exists []. splits; ss. Qed.\nArguments mkPR: clear implicits.\n\n\nDefinition relate_single (MR: SimMem.class) (SR: SimSymb.class MR) (MP: Sound.class)\n           (p_src p_tgt: Mod.t) : Prop :=\n  forall (WF: Sk.wf p_src),\n  exists mp,\n    (<<SIM: @ModPair.sim MR SR MP mp>>)\n    /\\ (<<SRC: mp.(ModPair.src) = p_src>>)\n    /\\ (<<TGT: mp.(ModPair.tgt) = p_tgt>>).\nArguments relate_single : clear implicits.\n\nLemma relate_single_program MR SR MP p_src p_tgt\n      (REL: relate_single MR SR MP p_src p_tgt):\n    (mkPR MR SR MP) [p_src] [p_tgt].\nProof.\n  unfold relate_single. ss. i.\n  exploit REL; [ss; eauto|]. i. des. clarify.\n  exists [mp]. esplits; ss; eauto.\nQed.\nArguments relate_single_program : clear implicits.\n\nLemma relate_each_program MR SR MP\n      (p_src p_tgt: program)\n      (REL: Forall2 (relate_single MR SR MP) p_src p_tgt):\n    (mkPR MR SR MP) p_src p_tgt.\nProof.\n  revert p_tgt REL. induction p_src; ss; i.\n  - inv REL. exists []; splits; ss.\n  - inv REL. exploit IHp_src; eauto. i. des.\n    exploit H1; eauto. i. des. clarify.\n    exists (mp :: pp); splits; ss. econs; eauto.\nQed.\nArguments relate_each_program : clear implicits.\n\nLemma relate_single_rtc_rusc (R: program_relation.t -> Prop) MR SR MP\n      (p_src p_tgt: Mod.t)\n      (REL: rtc (relate_single MR SR MP) p_src p_tgt)\n      (RELIN: R (mkPR MR SR MP)):\n    rusc R [p_src] [p_tgt].\nProof.\n  induction REL; try refl.\n  - etrans; eauto. eapply rusc_incl; eauto. eapply relate_single_program; eauto.\nQed.\nArguments relate_single_program : clear implicits.\n\nLemma relate_single_rusc (R: program_relation.t -> Prop) MR SR MP\n      (p_src p_tgt: Mod.t)\n      (REL: (relate_single MR SR MP) p_src p_tgt)\n      (RELIN: R (mkPR MR SR MP)):\n    rusc R [p_src] [p_tgt].\nProof.\n  eapply relate_single_rtc_rusc; eauto. eapply rtc_once. eauto.\nQed.\nArguments relate_single_program : clear implicits.\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/AdequacyLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.15105539659434045}}
{"text": "Require Export ZArith.\nRequire Export ch2o.core_c.expressions.\nRequire Export ch2o.memory_separation.memory_singleton.\nRequire Export ch2o.separation.permissions.\nRequire Export ch2o.core_c.expressions.\nRequire Export ch2o.core_c.expression_eval.\nRequire Export ch2o.core_c.restricted_smallstep.\nRequire Export ch2o.core_c.expression_eval_smallstep.\nRequire Export ch2o.abstract_c.natural_type_environment.\nRequire Export ch2o.abstract_c.architecture_spec.\nRequire Export ch2o.abstract_c.architectures.\n\nDefinition is_final_state `{Env K} (S: state K) :=\n  match S with\n    State _ (Return _ _) _ => True\n  | State _ (Undef _) _ => True\n  | _ => False\n  end.\n\nLemma mem_erase_free `{EnvSpec K} o (m: mem K):\n  cmap_erase (mem_free o m) = cmap_erase (mem_free o (cmap_erase m)).\ndestruct m as [m].\nunfold cmap_erase.\nunfold mem_free.\nassert (forall m1 m2, m1 = m2 -> (CMap m1: mem K) = CMap m2). intros; congruence.\napply H1.\napply map_eq.\nintros.\nrewrite lookup_omap.\nrewrite lookup_omap.\ndestruct (decide (o = i)).\n- subst.\n  rewrite lookup_alter.\n  rewrite lookup_alter.\n  rewrite lookup_omap.\n  destruct (m !! i).\n  + destruct c; reflexivity.\n  + reflexivity.\n- rewrite lookup_alter_ne with (1:=n).\n  rewrite lookup_alter_ne with (1:=n).\n  rewrite lookup_omap.\n  destruct (m !! i).\n  + destruct c; reflexivity.\n  + reflexivity.\nQed.\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\nLemma mem_lock_cmap (\u0393: env K) o (m: indexmap (cmap_elem K (pbit K))):\n  mem_lock \u0393 (addr_top o sintT%BT) (CMap m) =\n  CMap (alter (cmap_elem_map (ctree_map pbit_lock)) o m).\nreflexivity.\nQed.\n\nLemma zip_with_pbit_unlock_if_list_fmap_pbit_lock (l: list (pbit K)):\n  Forall (\u03bb \u03b3b, Some Writable \u2286 pbit_kind \u03b3b) l ->\n  zip_with pbit_unlock_if (pbit_lock <$> l) (replicate (Datatypes.length l) true) = l.\ninduction l; intros; try reflexivity.\nsimpl.\nunfold fmap in IHl.\nrewrite IHl.\n- destruct a.\n  simpl.\n  inversion H; subst.\n  destruct tagged_perm.\n  + destruct l0; simpl in *.\n    * unfold perm_kind in H2.\n      elim H2.\n    * reflexivity.\n  + elim H2.\n- inversion H; subst; assumption.\nQed.\n\nLemma mem_unlock_lock_singleton (\u0393: env K) o (m: mem K):\n  \u2713{\u0393} m ->\n  (\u0393, '{m}) \u22a2 addr_top o sintT%BT : sintT%PT ->\n  mem_writable \u0393 (addr_top o sintT%BT) m ->\n  mem_unlock\n    (lock_singleton \u0393 (addr_top o sintT%BT))\n    (mem_lock \u0393 (addr_top o sintT%BT) m) = m.\ndestruct m as [m].\nintros Hvalid. intros.\ndestruct Hvalid as [Hvalid1 [Hvalid2 Hvalid3]].\nsimpl in *.\nassert (forall (m1: indexmap (cmap_elem K (pbit K))) m2, m1 = m2 -> CMap m1 = CMap m2). { intros; congruence. }\napply H1.\napply map_eq.\nintro i.\nrewrite lookup_merge.\n2:reflexivity.\ndestruct (decide (i = o)).\n- subst.\n  rewrite lookup_singleton.\n  rewrite lookup_alter.\n  destruct H0 as [w [Hw H'w]].\n  simpl in *.\n  unfold cmap_lookup in Hw.\n  simpl in Hw.\n  case_eq (m !! o); intros; rewrite H0 in Hw; try discriminate.\n  destruct c; try discriminate.\n  simpl in Hw.\n  injection Hw; clear Hw; intros; subst.\n  simpl.\n  unfold typed in H.\n  unfold addr_typed in H.\n  simpl in H.\n  inversion H; clear H; subst.\n  unfold typed in H8.\n  unfold index_typed in H8.\n  destruct H8 as [\u03b2 Ho].\n  rewrite lookup_fmap in Ho.\n  rewrite H0 in Ho.\n  simpl in Ho.\n  injection Ho; clear Ho; intros; subst.\n  destruct w; try discriminate.\n  destruct b0; try discriminate.\n  destruct i; try discriminate.\n  simpl in H2.\n  injection H2; clear H2; intros; subst.\n  simpl.\n  pose proof H0.\n  apply Hvalid3 in H0.\n  destruct H0 as [\u03c4 [Ho1 [Ho2 [Ho3 Ho4]]]].\n  simpl in *.\n  unfold typed in Ho1.\n  unfold index_typed in Ho1.\n  destruct Ho1 as [\u03b2 Ho1].\n  rewrite lookup_fmap in Ho1.\n  rewrite H in Ho1.\n  simpl in Ho1.\n  injection Ho1; clear Ho1; intros; subst.\n  simpl in Ho3.\n  unfold typed in Ho3.\n  unfold ctree_typed in Ho3.\n  simpl in Ho3.\n  inversion Ho3; subst.\n  rewrite fmap_length.\n  assert (Datatypes.length l = 32). {\n    rewrite H5.\n    reflexivity.\n  }\n  rewrite H0.\n  assert (natmap.to_bools 32\n              {|\n              mapset.mapset_car := natmap.list_to_natmap\n                                     [Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some ()] |} =\n    [true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true]).\n  reflexivity.\n  rewrite H2.\n  pose proof (zip_with_pbit_unlock_if_list_fmap_pbit_lock l H'w).\n  rewrite H0 in H6.\n  simpl in H6.\n  rewrite H6.\n  reflexivity.\n- rewrite lookup_singleton_ne; try congruence.\n  rewrite lookup_alter_ne; try congruence.\nQed.\n\nLemma lockset_union_right_id (\u03a9: lockset): \u03a9 \u222a \u2205 = \u03a9.\napply lockset_eq.\nintros.\nsolve_elem_of.\nQed.\n\nLemma cons_snoc0 {A} x (xs: list A): exists y ys, x::xs = (ys ++ [y])%list.\nrevert x.\ninduction xs.\n- intros.\n  exists x.\n  exists [].\n  reflexivity.\n- intros.\n  destruct (IHxs a) as [y [ys Hyys]].\n  rewrite Hyys.\n  exists y.\n  exists (x::ys).\n  reflexivity.\nQed.\n\nLemma expr_eval_pure (\u0393: env K) \u03c1 e1 m e2 m2 (E: ectx K) \u03bd:\n  \u0393\\ \u03c1 \u22a2\u2095 e1, m \u21d2 e2, m2 ->\n  \u27e6 subst E e1 \u27e7 \u0393 \u03c1 m = Some \u03bd ->\n  m2 = m.\nintros.\napply expr_eval_subst in H0.\ndestruct H0 as [\u03bd' [H\u03bd' _]].\napply symmetry.\napply ehstep_expr_eval_mem with (1:=H) (2:=H\u03bd').\nQed.\n\nLemma expr_eval_complete_subst (\u0393: env K) \u03c1 e1 m e2 m2 (E: ectx K) \u03bd:\n  \u0393\\ \u03c1 \u22a2\u2095 e1, m \u21d2 e2, m2 ->\n  \u27e6 subst E e1 \u27e7 \u0393 \u03c1 m = Some \u03bd ->\n  \u27e6 subst E e2 \u27e7 \u0393 \u03c1 m = Some \u03bd.\nintros.\npose proof H0.\napply expr_eval_subst in H0.\ndestruct H0 as [\u03bd' [H\u03bd' _]].\nassert (m = m2). {\n  apply ehstep_expr_eval_mem with (1:=H) (2:=H\u03bd').\n}\nsubst m2.\nassert (\u27e6 e2 \u27e7 \u0393 \u03c1 m = Some \u03bd'). {\n  apply ehstep_expr_eval with (1:=H) (2:=H\u03bd') (3:=H\u03bd').\n}\nrewrite subst_preserves_expr_eval with (e4:=e2) in H1.\n- assumption.\n- congruence.\nQed.\n\nLemma expr_eval_call_None {\u0393: env K} {\u03c1 m} {E: ectx K} {f args \u03bd}:\n  \u27e6 subst E (ECall f args) \u27e7 \u0393 \u03c1 m = Some \u03bd -> False.\nintros.\napply expr_eval_subst in H.\ndestruct H.\ndestruct H.\nsimpl in H.\ndiscriminate.\nQed.\n\nLemma expr_eval_no_locks (\u0393: env K) \u03c1 m \u03a9 \u03bd \u03bd':\n  \u27e6 %#{\u03a9} \u03bd \u27e7 \u0393 \u03c1 m = Some \u03bd' -> (%#{\u03a9} \u03bd = %# \u03bd')%E.\nintros.\nsimpl in H.\nunfold mguard in H.\nunfold option_guard in H.\ndestruct (lockset_eq_dec \u03a9 \u2205); congruence.\nQed.\n\nLemma assign_pure (\u0393: env K) \u03b4 \u03c1 S0 S:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b S0 \u21d2* S ->\n  is_final_state S ->\n  forall k el er m \u03bdl \u03bdr,\n  S0 = State k (Expr (el ::= er)) m ->\n  \u27e6 el \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdl ->\n  \u27e6 er \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdr ->\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bdl ::= %# \u03bdr)) m \u21d2* S.\ninduction 1; intros; subst. {\n  elim H.\n}\ninversion H; clear H; subst.\n- (* head reduction *)\n  destruct E.\n  + (* empty evaluation context *)\n    simpl in *.\n    subst.\n    inversion H8; subst.\n    simpl in *.\n    unfold mguard in H4.\n    unfold option_guard in H4.\n    case_eq (lockset_eq_dec \u03a92 \u2205); intros.\n    * rewrite H in H4.\n      injection H4; clear H4; intros; subst.\n      unfold mguard in H3; unfold option_guard in H3.\n      case_eq (lockset_eq_dec \u03a91 \u2205); intros.\n      -- rewrite H2 in H3.\n         injection H3; clear H3; intros; subst.\n         clear H H2.\n         eapply rtc_l.\n         ++ eapply rcstep_expr_head with (E:=[]).\n            eassumption.\n         ++ eassumption.\n      -- rewrite H2 in H3; discriminate.\n    * rewrite H in H4; discriminate.\n  + (* nonempty evaluation context *)\n    destruct (cons_snoc0 e E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate.\n    * (* lhs *)\n      simpl in H6.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H3).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H3.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n    * (* rhs *)\n      simpl in *.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H4).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H4.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n- (* function call *)\n  destruct E.\n  + (* E = [] *)\n    simpl in *.\n    discriminate.\n  + destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate; simpl in *; injection H6; clear H6; intros; subst.\n    * (* lhs *)\n      elim (expr_eval_call_None H3).\n    * (* rhs *)\n      elim (expr_eval_call_None H4).\n- (* undef *)\n  destruct E.\n  * (* E = [] *)\n    simpl in *.\n    subst.\n    eapply rtc_l.\n    2: eassumption.\n    inversion H8; subst.\n    destruct H5.\n    destruct H7.\n    rewrite expr_eval_no_locks with (1:=H3) in *.\n    rewrite expr_eval_no_locks with (1:=H4) in *.\n    apply rcstep_expr_undef with (E:=[]).\n    -- assumption.\n    -- assumption.\n  * (* E <> [] *)\n    destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H5.\n    destruct e'; try discriminate; simpl in *; injection H5; clear H5; intros; subst.\n    -- (* lhs *)\n       destruct expr_eval_subst_ehstep with (1:=H3) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\n    -- (* rhs *)\n       destruct expr_eval_subst_ehstep with (1:=H4) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\nQed.\n\nLemma assign_pure' (\u0393: env K) \u03b4 \u03c1 S k el er m \u03bdl \u03bdr P:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b (State k (Expr (el ::= er)) m) \u21d2* S ->\n  is_final_state S ->\n  \u27e6 el \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdl ->\n  \u27e6 er \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bdr ->\n  (\u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bdl ::= %# \u03bdr)) m \u21d2* S ->\n   P) ->\n  P.\nintros.\napply X.\napply assign_pure with (1:=H) (2:=H0) (4:=H1) (5:=H2).\nreflexivity.\nQed.\n\nLemma Expr_pure (\u0393: env K) \u03b4 \u03c1 S0 S:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b S0 \u21d2* S ->\n  is_final_state S ->\n  forall k e m \u03bd,\n  S0 = State k (Expr e) m ->\n  \u27e6 e \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bd ->\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* S.\nintro Hrtc.\npose proof Hrtc.\ninduction H; intros; subst. {\n  elim H.\n}\nassert (forall \u03a9 \u03bd', e = (%#{\u03a9} \u03bd')%E -> \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* z). {\n  intros.\n  subst.\n  simpl in H3.\n  unfold mguard in H3.\n  unfold option_guard in H3.\n  destruct (lockset_eq_dec \u03a9 \u2205).\n  2: discriminate.\n  injection H3; clear H3; intros; subst.\n  assumption.\n}\nclear Hrtc.\ninversion H; clear H; subst; try (eapply H2; reflexivity); clear H2.\n- (* head reduction *)\n  assert (m2 = m). {\n    apply expr_eval_pure with (1:=H8) (2:=H3).\n  }\n  subst m2.\n  eapply IHrtc; try trivial.\n  apply expr_eval_complete_subst with (1:=H8) (2:=H3).\n- (* function call *)\n  elim (expr_eval_call_None H3).\n- elim H9.\n  eapply expr_eval_subst_ehsafe; eassumption.\nQed.\n\nLemma Expr_pure' (\u0393: env K) \u03b4 \u03c1 S k e m \u03bd:\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b (State k (Expr e) m) \u21d2* S ->\n  is_final_state S ->\n  \u27e6 e \u27e7 \u0393 (rlocals \u03c1 k) m = Some \u03bd ->\n  \u0393\\ \u03b4\\ \u03c1 \u22a2\u209b State k (Expr (%# \u03bd)) m \u21d2* S.\nintros.\napply Expr_pure with (1:=H) (2:=H0) (4:=H1).\nreflexivity.\nQed.\n\nLemma Hint_coding: arch_int_coding A = (@int_coding \n                               (arch_rank A)\n                               (@env_type_env \n                                  (arch_rank A) \n                                  (arch_env A))).\nreflexivity.\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/restricted_smallstep_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.25982563222951205, "lm_q1q2_score": 0.15103744304362807}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*             The Quantitative CompCert verified compiler             *)\n(*                                                                     *)\n(*                 Tahina Ramananandro, Yale University                *)\n(*                                                                     *)\n(*  This file is a modified version 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(** Corollaries of the main semantic preservation theorem. *)\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Behaviors.\nRequire Import Csyntax.\nRequire Import Csem.\nRequire Import Cstrategy.\nRequire Import Clight.\nRequire Import Cminor.\nRequire Import RTL.\nRequire Import Asm.\nRequire Import Compiler.\nRequire Import Errors.\nRequire Import Prune.\nRequire Import Memdata.\n\n(** We assume that the available stack size [bound] of the process in\n    the target machine is machine-representable, and that the stack is\n    strongly aligned. *)\n\nSection WITHBOUNDS.\nContext\n  (bound : Integers.Int.int)\n  (Hbound: (Stacklayout.strong_align\n       | Integers.Int.unsigned bound + size_chunk Mint32))\n  (external_event_needs: Events.event -> Z)\n  (p: Csyntax.program) (tp: Asm.program)\n  (H: transf_c_program p = OK tp)\n.\n\n(** * Preservation of whole-program behaviors *)\n\n(** From the simulation diagrams proved in file [Compiler]. it follows that\n  whole-program observable behaviors are preserved in the following sense.\n  First, every behavior of the generated assembly code is matched by\n  a behavior of the source C code. *)\n\nSection CSTRATEGY.\n\n(** If we consider the C evaluation strategy implemented by the\n  compiler, we get stronger preservation results: the behaviors are\n  exactly preserved. *)\n\nLemma prune_atomic_behaves_intro:\n  forall beh, program_behaves (prune_semantics (Cstrategy.semantics p)) beh ->\n              program_behaves (prune_semantics (atomic (Cstrategy.semantics p))) beh.\nProof.\n  intros.\n  destruct (prune_program_behaves _ _ H0).\n  destruct H1.\n  apply atomic_behaviors in H2.\n  eapply program_behaves_prune.\n  eassumption.\n  assumption.\n  intros. eapply ssr_well_behaved. apply Cstrategy.semantics_strongly_receptive.\nQed.\n\nLemma prune_atomic_behaves_elim:  \n  forall beh, program_behaves (prune_semantics (atomic (Cstrategy.semantics p))) beh ->\n              program_behaves (prune_semantics (Cstrategy.semantics p)) beh.\nProof.\n  intros.\n  destruct (prune_program_behaves _ _ H0).\n  destruct H1.\n  apply atomic_behaviors in H2.\n  eapply program_behaves_prune.\n  eassumption.\n  assumption.\n  intros. eapply ssr_well_behaved. apply Cstrategy.semantics_strongly_receptive.\nQed.  \n\n(** We assume that:\n\n    - the [Cstrategy] source program is proved not to go wrong\n\n    - the traces of the source program do not \"stack overflow\". Let us\n      explain this in more detail.  To compute the weights\n      (cf. Section 3.1 of our PLDI 2014 paper) of the traces of the so\n      program, we instantiate the stack metric with the sizes of the\n      stack frames obtained in [Mach] and adjusted by the\n      [Mach]-to-[Mach2] pass ([Mach2Mach2.stacksizes]). Then, the\n      condition [NO_OVERFLOW] below imposes that those weights must\n      not exceed [bound].\n *)\n\nVariables\n  (NOT_STUCK: not_stuck (prune_semantics (atomic (Cstrategy.semantics p))))\n  (NO_OVERFLOW: no_overflow_with_mach bound external_event_needs (fun p' => atomic (Cstrategy.semantics p')) transf_c_to_mach p)\n.\n\n(** Under these conditions, the target [Asm] program is guaranteed to\n    refine the [Cstrategy] source program -- and more precisely, the\n    *pruned* behaviors (without call/return events) are exactly\n    preserved.  In particular, the [Asm] program is guaranteed to not\n    go wrong at all, and in particular, is guaranteed to not stack\n    overflow.\n\n    As explained in Section 3.2, it is important that the source\n    program be proved to not go wrong in the unbounded-stack setting\n    (condition [NOT_STUCK]. Indeed, our transformation uses the\n    [Compiler.transf_mach_program_correct_strong] theorem, which\n    depends on *all* traces of the [Mach] program obtained during the\n    compilation of a source. If the source program were to have a\n    wrong behavior [Goes_wrong t], then the compiled [Mach] program\n    would well have a behavior [behavior_app t b] whose weight could\n    well exceed [bound], thus violating the [NO_OVERFLOW] condition of\n    that theorem. As each pass is proved independently of the others,\n    it is not possible to track those behaviors of the [Mach] program\n    that correspond to [Goes_wrong] behaviors of the source.\n *)\n\nTheorem transf_cstrategy_program_preservation:\n  (forall beh, program_behaves (prune_semantics (Cstrategy.semantics p)) beh <->\n               program_behaves (Asm.semantics bound tp) beh).\nProof.\n  split.\n  intros.\n  eapply forward_simulation_same_safe_behavior.\n  eapply transf_cstrategy_program_correct.\n  assumption.\n  eassumption.\n  eassumption.\n  assumption.\n  apply prune_atomic_behaves_intro.\n  assumption.\n  apply NOT_STUCK.\n  apply prune_atomic_behaves_intro.\n  assumption.\n intro.\n apply prune_atomic_behaves_elim.\n eapply backward_simulation_same_safe_behavior.\n eapply transf_cstrategy_program_correct.\n eassumption.\n assumption.\n eassumption.\n eassumption.\n assumption.\n assumption.\nQed.\n\nEnd CSTRATEGY.\n\n(** Similarly, if we assume that:\n\n    - the [Csem] source program is proved not to go wrong\n\n    - the traces of the source program do not \"stack overflow\". Let us\n      explain this in more detail.  To compute the weights\n      (cf. Section 3.1 of our PLDI 2014 paper) of the traces of the so\n      program, we instantiate the stack metric with the sizes of the\n      stack frames obtained in [Mach] and adjusted by the\n      [Mach]-to-[Mach2] pass ([Mach2Mach2.stacksizes]). Then, the\n      condition [NO_OVERFLOW] below imposes that those weights must\n      not exceed [bound].\n *)\n\nVariables\n  (NOT_STUCK: not_stuck (prune_semantics  (Csem.semantics p)))\n  (NO_OVERFLOW: no_overflow_with_mach bound external_event_needs (Csem.semantics) transf_c_to_mach p)\n.\n\n\n(** Then, under these conditions, the target [Asm] program is\n    guaranteed to refine the [Csem] source program. In particular, the\n    [Asm] program is guaranteed to not go wrong at all, and in\n    particular, is guaranteed to not stack overflow.\n\n    However, the [Asm] program may well have lost some behaviors of\n    the [Csem] program, because all internal non-determinism of [Csem]\n    (e.g. argument evaluation order) have been solved by\n    [Cstrategy]. So we only have refinement, not exact behavior\n    preservation. This is CompCert-specific, nothing to do with stack\n    consumption.\n*)\n\nTheorem transf_c_program_preservation:\n  forall beh,\n  program_behaves (Asm.semantics bound tp) beh ->\n  program_behaves (prune_semantics (Csem.semantics p)) beh.\nProof.\n  intros. eapply backward_simulation_same_safe_behavior; eauto.\n  eapply transf_c_program_correct; eauto.\nQed.\n\n(** * Satisfaction of specifications *)\n\n(** The second additional results shows that if all executions\n  of the source C program satisfies a given specification\n  (a predicate on the observable behavior of the program),\n  then all executions of the produced Asm program satisfy\n  this specification as well.  \n *)\n\nSection SPECS_PRESERVED.\n\nVariable spec: program_behavior -> Prop.\n\nTheorem transf_c_program_preserves_spec:\n  (forall beh, program_behaves (prune_semantics (Csem.semantics p)) beh -> spec beh) ->\n  (forall beh, program_behaves (Asm.semantics bound tp) beh -> spec beh).\nProof.\n  intros; eauto using transf_c_program_preservation.\nQed.\n\nEnd SPECS_PRESERVED.\n\nEnd WITHBOUNDS.\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/driver/Complements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.15082958005882668}}
{"text": "From hahn Require Import Hahn.\nFrom PromisingLib Require Import Loc.\nRequire Import Events.\nRequire Import Execution.\nRequire Import imm_s_hb.\nRequire Import imm_s.\nRequire Import CombRelations. \nRequire Import IfThen. \n\nSet Implicit Arguments.\n\nSection CombRelationsMore.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\nVariable Wf_sc : wf_sc G sc.\n\nNotation \"'co'\" := (co G).\nNotation \"'sw'\" := (sw G).\nNotation \"'hb'\" := (hb G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'rfi'\" := (rfi G).\nNotation \"'rfe'\" := (rfe G).\nNotation \"'rmw'\" := (rmw G).\nNotation \"'lab'\" := (lab G).\nNotation \"'release'\" := (release G).\n\nNotation \"'Init'\" := (fun a => is_true (is_init a)).\nNotation \"'E'\" := (acts_set G).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_' l\" := (W \u2229\u2081 Loc_ l) (at level 1).\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 \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nLemma urr_n_f_alt_union_eqv l A r thread\n  (SB : dom_rel (sb \u2a3e \u2997 eq r \u2998) \u2286\u2081 A)\n  (NF : ~ F r)\n  (TID : tid r = thread):\n  c_cur G sc thread l (A \u222a\u2081 eq r)\n      \u2261\n  urr G sc l \u2a3e \u2997A\u2998 \u2a3e (sb \u2a3e \u2997eq r\u2998)^? \u2a3e \u2997 Tid_ thread \u222a\u2081 Init \u2998 \u222a\n  \u2997 W_ l \u2998 \u2a3e \u2997eq r\u2998 \u222a\n  \u2997 Loc_ l \u2998 \u2a3e rf \u2a3e \u2997eq r\u2998 \u222a\n  (msg_rel G sc l \u222a \u2997 Loc_ l \u2998) \u2a3e\n    rf \u2a3e \u2997 Acq \u2998 \u2a3e \u2997eq r\u2998.\nProof using WF Wf_sc.\nrewrite c_cur_union.\nunfold c_cur; split.\n- unionL; [basic_solver 21|].\n  arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq r\u2998 \u2286 \u2997 set_compl F \u2998 \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq r\u2998).\n  by basic_solver 21.\n  sin_rewrite (urr_non_f WF).\n  relsf; unionL.\n  * arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq r\u2998 \u2286 \u2997eq r\u2998 \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998) by basic_solver.\n    unionR left -> left -> left.\n    hahn_frame; revert SB; basic_solver.\n  * basic_solver 21.\n  * basic_solver 21.\n  * done.\n- unionL.\n  * case_refl (sb \u2a3e \u2997eq r\u2998).\n    by basic_solver 21.\n    arewrite_id \u2997A\u2998; rels.\n    arewrite (sb \u2286 hb^?).\n    sin_rewrite urr_hb; basic_solver 12.\n  * by unfold urr; basic_solver 21.\n  * by unfold urr; rewrite (dom_l (wf_rfD WF)) at 1; basic_solver 21.\n  * relsf; unionL.\n    by sin_rewrite (msg_rel_urr WF); basic_solver 12.\n    unfold urr; rewrite (dom_l (wf_rfD WF)) at 1; basic_solver 21.\nQed.\n\nLemma urr_w_alt_union_eqv l A w thread\n  (SB : dom_rel (sb \u2a3e \u2997 eq w \u2998) \u2286\u2081 A)\n  (WW : W w)\n  (TID : tid w = thread):\n  c_cur G sc thread l (A \u222a\u2081 eq w)\n      \u2261\n  urr G sc l \u2a3e \u2997A\u2998 \u2a3e (sb \u2a3e \u2997eq w\u2998)^? \u2a3e \u2997 Tid_ thread \u222a\u2081 Init \u2998 \u222a\n  \u2997 W_ l \u2998 \u2a3e \u2997eq w\u2998.\nProof using WF Wf_sc.\n  rewrite urr_n_f_alt_union_eqv; auto.\n  rewrite (dom_r (wf_rfD WF)); type_solver 21.\n  type_solver 21.\nQed.\n\nLemma urr_acq_n_f_alt_union_eqv l A r thread\n  (SB : dom_rel (sb \u2a3e \u2997eq r\u2998) \u2286\u2081 A)\n  (NF : ~ F r)\n  (TID : tid r = thread) :\n  c_acq G sc thread l (A \u222a\u2081 eq r)\n      \u2261\n  (urr G sc l \u2a3e \u2997A\u2998 \u2a3e (sb \u2a3e \u2997eq r\u2998)^? \u2a3e \u2997 Tid_ thread \u222a\u2081 Init \u2998 \u222a\n   (msg_rel G sc l \u2a3e rf \u2a3e \u2997 Tid_ thread \u222a\u2081 Init \u2998 \u2a3e \u2997A\u2998)) \u222a\n  \u2997 W_ l \u2998 \u2a3e \u2997eq r\u2998 \u222a\n  \u2997 Loc_ l \u2998 \u2a3e rf \u2a3e \u2997eq r\u2998 \u222a\n  (msg_rel G sc l \u222a \u2997Loc_ l\u2998) \u2a3e rf \u2a3e \u2997eq r\u2998.\nProof using WF Wf_sc.\n  unfold c_acq; rewrite crE at 1.\n  rewrite seq_union_l; rewrite seq_union_r; rewrite seq_id_l.\n  arewrite (urr G sc l \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997A \u222a\u2081 eq r\u2998 \u2261\n            c_cur G sc thread l (A \u222a\u2081 eq r)).\n  rewrite (id_union A); rewrite (unionC \u2997A\u2998).\n  rewrite !seq_union_r.\n  arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq r\u2998 \u2261 \u2997eq r\u2998) by basic_solver.\n  rewrite urr_n_f_alt_union_eqv; eauto.\n  unfold msg_rel.\n  basic_solver 21.\nQed.\n\nLemma urr_rel_n_f_alt_union_eqv l l' A w thread\n  (SB : dom_rel (sb \u2a3e \u2997eq w\u2998) \u2286\u2081 A)\n  (WW : W w)\n  (TID : tid w = thread):\n  c_rel G sc thread l l' (A \u222a\u2081 eq w) \u2261\n  c_rel G sc thread l l' A \u222a \u2997Rel\u2998 \u2a3e \u2997Loc_ l\u2998 \u2a3e \u2997Loc_ l'\u2998 \u2a3e \u2997eq w\u2998 \u222a\n  urr G sc l \u2a3e \u2997A\u2998 \u2a3e sb \u2a3e \u2997Rel\u2998 \u2a3e \u2997Loc_ l'\u2998 \u2a3e \u2997eq w\u2998.\nProof using WF Wf_sc.\nunfold c_rel.\nsplit.\n- rewrite (id_union A) at 1; relsf.\n  unionL.\n  * basic_solver 21.\n  * arewrite (\u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq w\u2998 \u2286 \u2997 set_compl F \u2998 \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq w\u2998).\n    by type_solver 21.\n    arewrite (\u2997Rel\u2998 \u2a3e \u2997W \u2229\u2081 Loc_ l' \u222a\u2081 F\u2998 \u2a3e \u2997set_compl F\u2998 \u2286 \u2997set_compl F\u2998  \u2a3e \u2997Rel\u2998 \u2a3e \u2997W \u2229\u2081 Loc_ l' \u222a\u2081 F\u2998).\n    by type_solver 21.\n    sin_rewrite (urr_non_f WF).\n    relsf; unionL.\n    + unionR right; revert SB; type_solver 21.\n    + unionR left -> right; rewrite (dom_r (wf_rfD WF)); type_solver 21.\n    + rewrite (dom_r (wf_rfD WF)); type_solver 21.\n    + done.\n- unionL.\n  * basic_solver.\n  * unfold urr; basic_solver 21.\n  * arewrite_id \u2997A\u2998; rels.\n    arewrite (sb \u2286 hb^?).\n    sin_rewrite urr_hb; basic_solver.\nQed.\n\n(*\nLemma dom_rel_sb_clos B A r thread\n    (SB : dom_rel (sb \u2a3e \u2997 eq r \u2998) \u2286\u2081 A) :\n    dom_rel (B \u2a3e \u2997A\u2998 \u2a3e (sb \u2a3e \u2997eq r\u2998)^? \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998) \u2261\u2081\n    dom_rel (B \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997A\u2998).\nProof using.\nsplit.\nrewrite (@no_sb_to_init G); generalize (@sb_tid_init G); basic_solver 20.\nrevert SB; basic_solver 20.\nQed.\n*)\n\nLemma dom_rel_r l locr thread w r\n  (LOC : loc lab r = Some locr)\n  (RF : rf w r)\n  (TID : tid r = thread) :\n    (dom_rel\n       (\u2997Loc_ l\u2998 \u2a3e rf \u2a3e \u2997eq r\u2998) \u2261\u2081\n       if LocSet.Facts.eq_dec l locr then eq w else \u2205).\nProof using WF.\nsplit.\n- unfolder; ins; desf.\n  generalize (wf_rff WF); basic_solver.\n  apply n; eauto.\n  generalize (((wf_rfl WF) x y) H0); unfold same_loc; ins; congruence.\n- assert (loc lab w = Some locr).\n  by generalize (((wf_rfl WF) w r) RF); unfold same_loc; ins; congruence.\n  desf; basic_solver 21.\nQed.\n\nLemma t_cur_urr_union_eqv l A thread r\n  (SB : dom_rel (sb \u2a3e \u2997eq r\u2998) \u2286\u2081 A)\n  (NF : ~ F r)\n  (TID : tid r = thread) :\n  t_cur G sc thread l (A \u222a\u2081 eq r) \u2261\u2081\n  dom_rel (urr G sc l \u2a3e \u2997Tid_ thread \u222a\u2081 Init \u2998\u2a3e \u2997A\u2998) \u222a\u2081\n  (W_ l \u2229\u2081 eq r \u222a\u2081\n   dom_rel (\u2997Loc_ l\u2998 \u2a3e rf \u2a3e \u2997eq r\u2998) \u222a\u2081\n   dom_rel\n     ((msg_rel G sc l \u222a \u2997Loc_ l\u2998)\n      \u2a3e rf \u2a3e \u2997fun a : actid => Acq a\u2998 \u2a3e \u2997eq r\u2998)).\nProof using WF Wf_sc.\n  unfold t_cur.\n  rewrite urr_n_f_alt_union_eqv; auto.\n  rewrite (@no_sb_to_init G); generalize (@sb_tid_init G); basic_solver 20.\nQed.\n\nLemma t_cur_urr_union_eqv_w l A thread w\n  (SB : dom_rel (sb \u2a3e \u2997eq w\u2998) \u2286\u2081 A)\n  (WW : W w)\n  (TID : tid w = thread) :\n  t_cur G sc thread l (A \u222a\u2081 eq w) \u2261\u2081\n  dom_rel (urr G sc l \u2a3e \u2997Tid_ thread \u222a\u2081 Init \u2998\u2a3e \u2997A\u2998) \u222a\u2081\n  Loc_ l \u2229\u2081 eq w.\nProof using WF Wf_sc.\n  rewrite t_cur_urr_union_eqv; auto.\n  2: by intros H; type_solver.\n  split; [|basic_solver 10].\n  arewrite_id \u2997 Acq \u2998; rewrite seq_id_l.\n  arewrite (rf \u2a3e \u2997 eq w \u2998 \u2286 \u2205\u2082).\n  2: basic_solver 10.\n  rewrite (dom_r (wf_rfD WF)).\n  type_solver.\nQed.\n\nLemma t_acq_urr_union_eqv l A thread r\n  (SB : dom_rel (sb \u2a3e \u2997 eq r \u2998) \u2286\u2081 A)\n  (NF : ~ F r)\n  (TID : tid r = thread) :\n  t_acq G sc thread l (A \u222a\u2081 eq r) \u2261\u2081\n  t_acq G sc thread l A \u222a\u2081\n  (W_ l \u2229\u2081 eq r \u222a\u2081\n   dom_rel (\u2997Loc_ l\u2998 \u2a3e rf \u2a3e \u2997eq r\u2998) \u222a\u2081\n   dom_rel ((msg_rel G sc l \u222a \u2997Loc_ l\u2998) \u2a3e rf \u2a3e \u2997eq r\u2998)).\nProof using WF Wf_sc.\n  unfold t_acq.\n  rewrite urr_acq_n_f_alt_union_eqv; eauto.\n  unfold c_acq.\n  unfold msg_rel.\n  rewrite (@no_sb_to_init G); generalize (@sb_tid_init G); basic_solver 20.\nQed.\n\nLemma t_rel_union_eqv l l' A thread r\n  (SB : dom_rel (sb \u2a3e \u2997 eq r \u2998) \u2286\u2081 A)\n  (RR : R r)\n  (TID : tid r = thread) :\n  t_rel G sc thread l l' (A \u222a\u2081 eq r) \u2261\u2081 t_rel G sc thread l l' A.\nProof using.\n  unfold t_rel, c_rel.\n  rewrite (id_union A); rewrite !seq_union_r.\n  arewrite (\u2997W_ l' \u222a\u2081 F\u2998 \u2a3e \u2997Tid_ thread \u222a\u2081 Init\u2998 \u2a3e \u2997eq r\u2998 \u2261 \u2205\u2082); rels.\n  type_solver 21.\nQed.\n\nLemma t_rel_w_union_eqv l l0 A thread w locw\n  (NINIT : ~ is_init w)\n  (CCLOS : doma (sb \u2a3e \u2997 A \u2998) A)\n  (AACTS : A \u2286\u2081 E)\n  (NINA  : ~ A w)\n  (SB : doma (sb \u2a3e \u2997eq w\u2998) A)\n  (ACTS: E w)\n  (WW : W w)\n  (LOC : loc lab w = Some locw)\n  (TID : tid w = thread)\n  (FREFL : forall l y (Ws : W y) (LOC : loc lab y = Some l), urr G sc l y y)\n  (CREL : forall l l',\n    c_rel G sc thread l l' (A \u222a\u2081 eq w)\n        \u2261\n    c_rel G sc thread l l' A \u222a\n    \u2997fun _ => l' = l\u2998 \u2a3e\n    \u2997Rel\u2998 \u2a3e \u2997Loc_ l'\u2998 \u2a3e \u2997eq w\u2998 \u222a\n    urr G sc l \u2a3e \u2997A\u2998 \u2a3e sb \u2a3e \u2997 Rel \u2998 \u2a3e \u2997Loc_ l'\u2998 \u2a3e \u2997eq w\u2998)\n  :\n  t_rel G sc thread l0 l (A \u222a\u2081 eq w) \u222a\u2081\n  (if Loc.eq_dec l0 l\n   then W \u2229\u2081 Loc_ l \u2229\u2081 Tid_ thread \u2229\u2081 (A \u222a\u2081 eq w)\n   else \u2205)\n    \u2261\u2081\n  if Loc.eq_dec l locw\n  then (if (is_rel lab w)\n        then t_cur G sc thread l0 A \n        else t_rel G sc thread l0 l A \u222a\u2081\n             (if Loc.eq_dec l0 l\n              then W \u2229\u2081 Loc_ l \u2229\u2081 Tid_ thread \u2229\u2081 A\n              else \u2205)) \u222a\u2081\n       (if Loc.eq_dec l0 locw then eq w else \u2205)\n  else\n    t_rel G sc thread l0 l A \u222a\u2081\n    (if Loc.eq_dec l0 l\n     then W \u2229\u2081 Loc_ l \u2229\u2081 Tid_ thread \u2229\u2081 A\n     else \u2205).\nProof using WF.\n  rewrite !ite_alt; rewrite !iteb_alt; rewrite !ite_alt.\n  rewrite !set_inter_union_r.\n  rewrite ite_union_t.\n  unfold t_rel at 1; rewrite CREL; auto.\n  arewrite (W \u2229\u2081 Loc_ l \u2229\u2081 Tid_ thread \u2229\u2081 eq w \u2261\u2081 Loc_ l \u2229\u2081 eq w) by basic_solver 12.\n  assert (forall l,\n          dom_rel (urr G sc l \u2a3e \u2997A\u2998 \u2a3e sb \u2a3e \u2997eq w\u2998) \u2261\u2081\n          dom_rel (c_cur G sc (tid w) l A)) as CSB.\n  { intros; unfold c_cur.\n    split; intros x H; destruct H as [y H].\n    all: hahn_rewrite <- seqA in H.\n    hahn_rewrite <- seqA in H.\n    all: apply seq_eqv_r in H; destruct H as [H X]; subst.\n    { destruct H as [z [H PSB]].\n      apply seq_eqv_r in H; desf.\n      exists z; hahn_rewrite <- seqA; apply seq_eqv_r; split; auto.\n      apply seq_eqv_r; split; auto.\n      eapply sb_tid_init; eauto. }\n    apply seq_eqv_r in H; desc.\n    exists w; hahn_rewrite <- seqA; hahn_rewrite <- seqA.\n    apply seq_eqv_r; split; auto.\n    exists y; split.\n    by basic_solver.\n    destruct (classic (is_init y)) as [IN|NIN].\n    { apply init_ninit_sb; auto. }\n    destruct (same_thread G y w) as [[ST|ST]|ST]; desf.\n    { by apply AACTS. }\n    revert H0; basic_solver.\n    exfalso; revert CCLOS; basic_solver. }\n  assert (forall l' l'',\n          dom_rel (c_rel G sc (tid w) l' l'' A) \u222a\u2081\n          dom_rel (c_cur G sc (tid w) l' A) \u2261\u2081\n          dom_rel (c_cur G sc (tid w) l' A)) as CURREL.\n  by unfold c_rel, c_cur; basic_solver 12.\n\n  destruct (classic (l = locw)) eqn:LL1; subst.\n  { rewrite <- !ite_alt; rewrite !Loc.eq_dec_eq.\n    rename locw into l.\n    rewrite !ite_alt.\n    arewrite (\u2997Loc_ l\u2998 \u2a3e \u2997eq w\u2998 \u2261 \u2997eq w\u2998) by basic_solver.\n    rewrite !dom_union.\n    destruct (classic (l0 = l)) eqn:LL2; subst.\n    { rewrite <- !ite_alt; rewrite !Loc.eq_dec_eq.\n      arewrite (\u2997fun _ : actid => l = l\u2998 \u2261 \u2997fun _ : actid => True\u2998).\n      { split; intros x y H; red; red in H; split; desf. }\n      rewrite seq_id_l.\n      rewrite (fun x => set_unionC x (dom_rel (\u2997Rel\u2998 \u2a3e \u2997eq w\u2998))).\n      rewrite !set_unionA; rewrite set_unionC.\n      rewrite !set_unionA.\n      arewrite (Loc_ l \u2229\u2081 eq w \u2261\u2081 eq w) by basic_solver.\n      arewrite (eq w \u222a\u2081 dom_rel (\u2997fun a : actid => Rel a\u2998 \u2a3e \u2997eq w\u2998) \u2261\u2081 eq w) by basic_solver.\n      rewrite <- !set_unionA.\n      repeat (apply set_equiv_union; [|done]).\n      rewrite <- iteb_alt.\n      destruct (is_rel lab w) eqn:RELEQ.\n      { arewrite (\u2997Rel\u2998 \u2a3e \u2997eq w\u2998 \u2261 \u2997eq w\u2998).\n        { by apply seq_eqvK_l; ins; subst. }\n        unfold t_cur.\n        rewrite CSB; rewrite CURREL.\n        split; intros x H; [|by left]; destruct H; desf.\n        unfold c_cur.\n        revert H; basic_solver 21. }\n      arewrite (\u2997fun a : actid => Rel a\u2998 \u2a3e \u2997eq w\u2998 \u2261 \u2205\u2082) by basic_solver.\n        by rels. }\n    rewrite <- !ite_alt.\n    rewrite !Loc.eq_dec_neq; auto.\n    arewrite (\u2997fun _ : actid => l = l0\u2998 \u2261 \u2205\u2082).\n    { split; rels; intros x y H; inv H. }\n    rels.\n    rewrite <- iteb_alt; destruct (is_rel lab w) eqn: REL.\n    { arewrite (\u2997Rel\u2998 \u2a3e \u2997eq w\u2998 \u2261 \u2997eq w\u2998).\n      { by apply seq_eqvK_l; ins; subst. }\n      by rewrite CSB; rewrite CURREL. }\n    arewrite (\u2997Rel\u2998 \u2a3e \u2997eq w\u2998 \u2261 \u2205\u2082).\n    { split; rels; intros x y H; apply seq_eqv_r in H; desf; red in H; desf. }\n    by rels. }\n  rewrite <- !ite_alt; rewrite (@Loc.eq_dec_neq _ l locw); auto.\n  rewrite !ite_alt.\n  rewrite <- !id_inter.\n  arewrite (Loc_ l \u2229\u2081 eq w \u2261\u2081 \u2205) by basic_solver.\n  unfold ifthenelse, t_rel; basic_solver 21.\nQed.\n\nLemma t_cur_urr_init\n      wi (C : actid -> Prop) l thread\n      (INC : C wi) (INIT : is_init wi) (LOC : Loc_ l wi):\n  t_cur G sc thread l C wi.\nProof using WF.\nunfold t_cur, c_cur, urr.\ngeneralize (init_w WF); unfold seq; basic_solver 42.\nQed.\n\nLemma urr_refl l y (YW : W y) (LOC : loc lab y = Some l):\n  urr G sc l y y.\nProof using.\nunfold urr.\nbasic_solver 21.\nQed.\n\nLemma t_rel_if_other_thread\n      C C' thread l l'\n      (CINIT : Init \u2229\u2081 E \u2286\u2081 C)\n      (CINCL : C \u2286\u2081 C')\n      (CE : C' \u2286\u2081 E)\n      (COVSTEP : forall a, tid a = thread -> C' a -> C a) :\n  (t_rel G sc thread l l' C' \u222a\u2081\n   (if LocSet.Facts.eq_dec l l'\n    then\n      W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ thread \u2229\u2081 C'\n    else \u2205)) \u2261\u2081\n  (t_rel G sc thread l l' C \u222a\u2081\n   (if LocSet.Facts.eq_dec l l'\n    then\n      W \u2229\u2081 Loc_ l' \u2229\u2081 Tid_ thread \u2229\u2081 C\n    else \u2205)).\nProof using.\n  apply set_equiv_union; [by symmetry; apply t_rel_other_thread|].\n  desf; basic_solver 21.\nQed.\n\nLemma s_tm_n_f_steps\n      C C' l \n      (CINIT : Init \u2229\u2081 E \u2286\u2081 C)\n      (CINCL : C \u2286\u2081 C')\n      (COVSTEP : forall a, C' a -> ~ C a -> ~ (F\u2229\u2081Sc) a) :\n  S_tm G l C' \u2261\u2081 S_tm G l C.\nProof using.\n  unfold S_tm, S_tmr.\n  arewrite (\u2997F\u2229\u2081Sc\u2998 \u2a3e \u2997C'\u2998 \u2261 \u2997F\u2229\u2081Sc\u2998 \u2a3e \u2997C\u2998); [|done].\n  split; [|by rewrite CINCL].\n  unfolder; ins; desf.\n  destruct (classic (C y)) as [H|H]; auto.\n  exfalso; eapply COVSTEP; basic_solver.\nQed.\n\n\nEnd CombRelationsMore.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/imm/CombRelationsMore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.28776782186926264, "lm_q1q2_score": 0.1506235337354554}}
{"text": "(** \n Verified SAR-BP: A verified C implementation of SAR backprojection\n with a certified absolute error bound.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file is free software. You can redistribute it and/or modify it\n under the terms of the GNU General Public License as published by the\n Free Software Foundation, either version 3 of the License (GNU GPL\n v3), or (at your option) any later version.  A verbatim copy of the\n GNU GPL v3 is included in gpl-3.0.txt.\n \n This file is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See LICENSE for\n more details about the use and redistribution of this file and the\n whole Verified SAR-BP library.\n \n This work is sponsored in part by DARPA MTO as part of the Power\n Efficiency Revolution for Embedded Computing Technologies (PERFECT)\n program (issued by DARPA/CMO under Contract No: HR0011-12-C-0123). The\n views and conclusions contained in this work are those of the authors\n and should not be interpreted as representing the official policies,\n either expressly or implied, of the DARPA or the\n U.S. Government. Distribution Statement \"A\" (Approved for Public\n Release, Distribution Unlimited.)\n \n \n If you are using or modifying Verified SAR-BP in your work, please\n consider citing the following paper:\n \n Tahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\n Lethin.\n A Unified Coq Framework for Verifying C Programs with Floating-Point\n Computations.\n In CPP (5th ACM/SIGPLAN conference on Certified Programs and Proofs)\n 2016.\n \n \n Verified SAR-BP derives from prior work listed in ACKS along with\n their copyright and licensing information.\n \n Verified SAR-BP requires third-party libraries listed in ACKS along\n with their copyright information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nVerification of a C implementation of 3D L2 norm\n(norm() in backprojection.c)\n*)\n\nRequire Import RAux.\nRequire Import List.\nRequire Import SARBackProjSource.\nRequire Import compcert.Integers.\nRequire Import compcert.Floats.\nRequire Import compcert.AST.\nRequire Import compcert.Values.\nRequire Import compcert.Memory.\nRequire Import compcert.Events.\nRequire Import compcert.Globalenvs.\nRequire Import compcert.Smallstep.\nRequire Import compcert.Clight.\nRequire Import Flocq.Core.Fcore_generic_fmt.\nRequire Import Flocq.Appli.Fappli_IEEE.\nRequire Import Flocq.Prop.Fprop_relative.\nRequire Import Fprop_absolute.\nRequire Import Clight2FPOpt.\nRequire Import SepLogic.\nRequire Import ClightFacts.\nRequire Import ClightTac.\nRequire Import ClightSep2.\nOpen Scope R_scope.\n\nLocal Existing Instance Clight2FP.nans.\n\nDefinition f_sqrt_correct ge fr_sqrt :=\n  type_of_fundef fr_sqrt =\n  Ctypes.Tfunction\n    (Ctypes.Tcons (Clightdefs.tptr Clightdefs.tdouble)\n                  (Ctypes.Tcons Clightdefs.tdouble Ctypes.Tnil)) Clightdefs.tvoid\n    cc_default /\\\n  forall x,\n  is_finite _ _ x = true ->\n  0 <= B2R _ _ x ->\n  forall pr,\n    perm_order pr Writable ->\n    forall o,\n    (align_chunk Mfloat64 | Int.unsigned o)%Z ->\n    forall P b m,\n      holds (P ++ Pperm b (Int.unsigned o) pr (size_chunk_nat Mfloat64)) m ->\n      let s0 := (Callstate fr_sqrt\n                           (Vptr b o :: Vfloat x :: nil)\n                           Kstop\n                           m) in\n      exists m',\n        star Clight.step2 ge\n             s0\n             E0\n             (Returnstate Vundef\n                          Kstop\n                          m')\n        /\\\n        exists y,\n          holds (P ++ Pval Mfloat64 b (Int.unsigned o) pr (Vfloat y)) m' /\\\n          y = FPLang.Bsqrt FPLang.Tdouble x\n.\n\nDefinition f_sqrt_correct' ge fr_sqrt :=\n  type_of_fundef fr_sqrt =\n  Ctypes.Tfunction\n    (Ctypes.Tcons (Clightdefs.tptr Clightdefs.tdouble)\n                  (Ctypes.Tcons Clightdefs.tdouble Ctypes.Tnil)) Clightdefs.tvoid\n    cc_default /\\\n  forall x,\n  is_finite _ _ x = true ->\n  0 <= B2R _ _ x ->\n  forall pr,\n    perm_order pr Writable ->\n    forall o,\n    (align_chunk Mfloat64 | Int.unsigned o)%Z ->\n    forall P b m,\n      holds (P ++ Pperm b (Int.unsigned o) pr (size_chunk_nat Mfloat64)) m ->\n      let s0 := (Callstate fr_sqrt\n                           (Vptr b o :: Vfloat x :: nil)\n                           Kstop\n                           m) in\n      exists m',\n        star Clight.step2 ge\n             s0\n             E0\n             (Returnstate Vundef\n                          Kstop\n                          m')\n        /\\\n        exists y,\n          holds (P ++ Pval Mfloat64 b (Int.unsigned o) pr (Vfloat y)) m' /\\\n          y = FPLang.fval\n                (env_\n                   (Maps.PTree.set xH (Vfloat x) (Maps.PTree.empty _))\n                )\n                (FPLang.Unop (FPLang.Rounded1 FPLang.SQRT None) (FPLang.Var FPLang.Tdouble xH))\n.\n\nLemma f_sqrt_correct'_eq: f_sqrt_correct' = f_sqrt_correct.\nProof.\n  reflexivity.\nQed.\n\nRequire Import SARBackProjSourceOpt1.\n\nDefinition f_norm2_correct BOUNDS :=\n  let '(norm2_error, norm2_left, norm2_right) := BOUNDS\n  in\n  forall\n    os\n    ps\n\n    m bs P\n    (Hm:\n       holds\n         (P ++\n            Pperm bs (Int.unsigned os) ps (size_chunk_nat Mfloat64)\n         )\n         m)\n\n    (Hos_align: (align_chunk Mfloat64 | Int.unsigned os)%Z )\n    (Hps: perm_order ps Writable)\n\n   x'\n   (Hx'_range: xdiff_left <= B2R _ _ x' <= xdiff_right )\n\n   y'\n   (Hy'_range: ydiff_left <= B2R _ _ y' <= ydiff_right )\n\n   z'\n   (Hz'_range: zdiff_left <= B2R _ _ z' <= zdiff_right )\n\n   (Hx'_finite: is_finite _ _ x' = true)\n   (Hy'_finite: is_finite _ _ y' = true)\n   (Hz'_finite: is_finite _ _ z' = true)\n\n  ge,\n\n   exists v1 : val,\n     eval_expr ge empty_env\n                (Maps.PTree.set _z (Vfloat z')\n                   (Maps.PTree.set _y (Vfloat y')\n                      (Maps.PTree.set _x (Vfloat x')\n                         (Maps.PTree.set _n (Vptr bs os)\n                            (create_undef_temps (fn_temps f_norm)))))) m\n       (Ebinop Oadd\n          (Ebinop Oadd\n             (Ebinop Omul (Etempvar _x tdouble) (Etempvar _x tdouble) tdouble)\n             (Ebinop Omul (Etempvar _y tdouble) (Etempvar _y tdouble) tdouble)\n             tdouble)\n          (Ebinop Omul (Etempvar _z tdouble) (Etempvar _z tdouble) tdouble)\n          tdouble) v1\n     /\\\n     exists f,\n       v1 = Vfloat f /\\\n       is_finite _ _ f = true /\\\n       norm2_left <= B2R _ _ f <= norm2_right /\\\n       Rabs (B2R _ _ f - (B2R _ _ x' * B2R _ _ x' + B2R _ _ y' * B2R _ _ y' + B2R _ _ z' * B2R _ _ z')) <= norm2_error.\n\nLemma f_norm2_body_correct' :\n  { BOUNDS |\n    f_norm2_correct BOUNDS }.\nProof.\n  eexists (_, _, _).\n  unfold f_norm2_correct.\n  intros os ps m bs P Hm Hos_align.\n  intros Hps x' Hx'_range y'.\n  intros Hy'_range z' Hz'_range Hx'_finite Hy'_finite Hz'_finite ge.\n\n  unfold xdiff_left, xdiff_right in Hx'_range.\n  unfold ydiff_left, ydiff_right in Hy'_range.\n  unfold zdiff_left, zdiff_right in Hz'_range.\n\n  apply eval_expr_exists_filter_float.\n  apply eval_expr_exists_filter_domain.\n  apply Vfloat_exists.\n  (* here comes the framework into play! *)\n  Transparent Float.of_bits.\n  Transparent Int64.repr.\n  C_to_float_as r Hr.\n  compute_fval_as Hr Hr_finite Hr_val.\n\n  Require Import Interval.Interval_tactic.\n  match type of Hr_val with\n      ?z = _ =>\n      interval_intro z with (i_prec 128) as Hr_range\n  end.\n  rewrite Hr_val in Hr_range.\n  destruct (rememb (B2R _ _ r - (B2R _ _ x' * B2R _ _ x' + B2R _ _ y' * B2R _ _ y' + B2R _ _ z' * B2R _ _ z'))) as (err & Herr).\n  generalize Herr. intro Herr'.\n  rewrite <- Hr_val in Herr'.\n  ring_simplify in Herr'.\n  match type of Herr' with\n      _ = ?z =>\n      interval_intro (Rabs z) upper with (i_prec 128) as Hr_error\n  end.\n  rewrite <- Herr' in Hr_error.\n  clear Herr'.\n  subst err.\n\n  solve_trivial.\n  eassumption.\nDefined.\n\nDefinition norm2_error' :=\n  let (x, _) := f_norm2_body_correct' in \n  let '(y, _, _) := x in y\n.\n\nDefinition norm2_error'_eq := $( field_eq norm2_error' )$ .\n\nDefinition norm2_error := $( match type of norm2_error'_eq with _ = ?z => exact z end )$ .\n\nDefinition norm2_left' :=\n  let (x, _) := f_norm2_body_correct' in \n  let '(_, y, _) := x in y\n.\n\nDefinition norm2_left'_eq := $( field_eq norm2_left' )$ .\n\nDefinition norm2_left := $( match type of norm2_left'_eq with _ = ?z => exact z end )$ .\n\nDefinition norm2_right' :=\n  let (x, _) := f_norm2_body_correct' in \n  let '(_, _, y) := x in y\n.\n\nDefinition norm2_right'_eq := $( field_eq norm2_right' )$ .\n\nDefinition norm2_right := $( match type of norm2_right'_eq with _ = ?z => exact z end )$ .\n\nLemma f_norm2_body_correct:\n  f_norm2_correct (norm2_error, norm2_left, norm2_right).\nProof.\n  unfold norm2_error. rewrite <- norm2_error'_eq.\n  unfold norm2_left. rewrite <- norm2_left'_eq.\n  unfold norm2_right. rewrite <- norm2_right'_eq.\n  unfold norm2_error', norm2_left', norm2_right'.\n  destruct f_norm2_body_correct'.\n  destruct x.\n  destruct p.\n  assumption.\nQed.\n\nLocal Existing Instances\n      FPLang.map_nat FPLang.compcert_map\n.\n\nLemma fshift_correct:\n  forall (V : Type) (NANS : FPLang.Nans)\n    (env : forall ty : FPLang.type, V -> FPLang.ftype ty) \n    (e : FPLang.expr) o,\n           FPLang.fval env e = o ->\n           {\n             u : _ &\n                   {v |\n                    u = (FPLangOpt.fshift e) /\\\n                    FPLang.fval env u =\n                    eq_rect_r FPLang.ftype o v} }\n.\nProof.\n  intros.\n  subst o.\n  esplit.\n  esplit.\n  split; eauto.\n  apply FPLangOpt.fshift_correct.\nDefined.\n\nLtac interval_with c :=\n  match goal with\n    |- ?a <= ?b =>\n    interval_intro (a - b) with c;\n      lra\n    | |- ?a < ?b =>\n    let K := fresh in\n    interval_intro (a - b) with c;\n      lra\n  end.\n\nDefinition f_norm_correct BOUNDS ge fn_norm :=\n  let '(f_norm_error, norm_left, norm_right) := BOUNDS in\ntype_of_fundef fn_norm =\n   Ctypes.Tfunction\n     (Ctypes.Tcons (Clightdefs.tptr Clightdefs.tdouble)\n        (Ctypes.Tcons Clightdefs.tdouble\n           (Ctypes.Tcons Clightdefs.tdouble\n              (Ctypes.Tcons Clightdefs.tdouble\n                 Ctypes.Tnil)))) Clightdefs.tvoid cc_default\n/\\\n  forall\n    os\n    (Hos_align: (align_chunk Mfloat64 | Int.unsigned os)%Z )\n    ps\n    (Hps: perm_order ps Writable)\n\n    m bs P\n    (Hm:\n       holds\n         (P ++\n            Pperm bs (Int.unsigned os) ps (size_chunk_nat Mfloat64)\n         )\n         m)\n\n   x'\n   (Hx'_finite: is_finite _ _ x' = true)\n   (Hx'_range: xdiff_left <= B2R _ _ x' <= xdiff_right )\n\n   y'\n   (Hy'_finite: is_finite _ _ y' = true)\n   (Hy'_range: ydiff_left <= B2R _ _ y' <= ydiff_right )\n\n   z'\n   (Hz'_finite: is_finite _ _ z' = true)\n   (Hz'_range: zdiff_left <= B2R _ _ z' <= zdiff_right )\n\n  ,\n    let st0 := (Callstate fn_norm\n                          (Vptr bs os :: Vfloat x' :: Vfloat y' :: Vfloat z' :: nil)\n                          Kstop\n                          m) in\n    exists m',\n      star Clight.step2 ge\n           st0\n           E0\n           (Returnstate Vundef Kstop m')\n      /\\\n      exists res,\n      is_finite _ _ res = true\n      /\\\n      Rabs (B2R _ _ res - R_sqrt.sqrt (B2R _ _ x' * B2R _ _ x' + B2R _ _ y' * B2R _ _ y' + B2R _ _ z' * B2R _ _ z')) <= f_norm_error\n      /\\\n      norm_left <= B2R _ _ res <= norm_right\n      /\\\n      holds\n        (P ++\n           Pval Mfloat64 bs (Int.unsigned os) ps (Vfloat res)\n        )\n        m'\n.\n\nRequire Import SARBackProjSourceSqrt.\n\nLemma f_norm_body_correct': { f_norm_error | forall\n      (ge: Clight.genv)\n      b_sqrt fn_sqrt\n      (Hb_sqrt_symb: Genv.find_symbol ge _sqrt = Some b_sqrt)\n      (Hb_sqrt_funct: Genv.find_funct_ptr ge b_sqrt = Some fn_sqrt)\n\n      (Hf_sqrt_correct: _sqrt_correct ge fn_sqrt)\n,\n  f_norm_correct f_norm_error ge (Internal f_norm)\n}.\nProof.\n  eexists (_, _, _).\n  intros ge b_sqrt fn_sqrt Hb_sqrt_symb Hb_sqrt_funct.\n  intros Hf_sqrt_correct. \n  destruct Hf_sqrt_correct as (sqrt_type & Hf_sqrt_correct).\n\n  split.\n  {\n    reflexivity.\n  }\n  intros os Hos_align ps Hps.\n  intros m bs P Hm x'.\n  intros Hx'_finite Hx'_range y' Hy'_finite Hy'_range z' Hz'_finite Hz'_range st0.\n\n  unfold st0; clear st0.\n\n  match goal with\n    |- exists m', Smallstep.star step2 ?ge ?s Events.E0 (Returnstate Vundef Kstop m') /\\ ?P =>\n    cut \n      (exists s',\n         Smallstep.star step2 ge s Events.E0 s' /\\\n         exists m',\n           s' = Returnstate Vundef Kstop m' /\\\n           P)\n  end.\n  {\n    let H := fresh in\n    intro H;  break H; subst; eauto 15.\n  }\n  \n  apply star_call_eval_funcall_exists.\n  apply eval_funcall_exists_internal.\n  solve_trivial.\n\n  simpl fn_vars.\n  unfold alloc_variables_prop.\n  solve_trivial.\n\n  simpl fn_body.\n  apply exec_Sseq_exists.\n  apply exec_Scall_exists.\n  solve_trivial.\n  repeat ClightSep2.run.\n\n  edestruct f_norm2_body_correct with (ge := ge) as (? & EVAL & n2 & ? & Hn2_finite & Hn2_range & Hn2_error); try eassumption.\n  subst.\n  solve_trivial.\n  clear EVAL.\n  unfold out_normal_b.\n\n  apply eval_funcall_exists_star_call.  \n  apply exec_call_exists.\n  solve_trivial.\n  eapply exists_modus_ponens.\n  {\n    eapply exists_double_elim.\n    eapply Hf_sqrt_correct.\n    { assumption. }\n    { unfold norm2_left in Hn2_range. lra. }\n  }\n  intros s1 (v & ? & Hv).\n  subst s1.\n  unfold Bsqrt in Hv.\n  match type of Hv with\n      _ = Fappli_IEEE.Bsqrt ?prec ?emax ?gt ?lt ?nan ?mode ?u =>\n      generalize (Bsqrt_correct prec emax gt lt nan mode u)\n  end.\n  rewrite <- Hv; clear Hv.\n  intros (Hv_val & Hv_finite_ & _).\n  assert (is_finite _ _ v = true) as Hv_finite.\n  {\n    destruct n2; auto.\n    destruct b; auto.\n    simpl in Hn2_range.\n    unfold Fcore_defs.F2R in Hn2_range.\n    simpl in Hn2_range.\n    unfold norm2_left in Hn2_range.\n    rewrite P2R_INR in Hn2_range.\n    generalize (bpow_gt_0 radix2 e).\n    generalize (INR_pos m0).\n    intros U V.\n    generalize (Rmult_lt_0_compat _ _ U V).\n    lra.\n  }\n  clear Hv_finite_.\n  simpl round_mode in Hv_val.\n  match type of Hv_val with\n      _ = round ?beta (Fcore_FLT.FLT_exp ?emin ?prec) (Znearest ?choice) ?x =>\n      generalize (error_N_FLT beta emin prec $( vm_compute; congruence )$ choice x)\n  end.\n  intros (d & e & Hd & He & _ & Hv_).\n  rewrite Hv_ in Hv_val; clear Hv_.\n  unfold fprec in Hv_val.\n  simpl in Hv_val.\n  simpl in Hd, He.\n  solve_trivial.\n\n  apply star_exists_refl.\n  solve_trivial.\n\n  apply exec_Sassign_exists.\n  repeat run.\n\n  holds_storev_solve.\n  intros m Hm.\n  solve_trivial.\n\n  simpl outcome_result_value_exists.\n  solve_trivial.\n\n  apply and_assoc.\n  split; eauto.\n    \n  unfold xdiff_left, ydiff_left, zdiff_left, norm2_left, norm2_error in *.\n  generalize Hn2_error. intro Hn2_error'.\n  apply Fcore_Raux.Rabs_le_inv in Hn2_error'.\n  apply sqrt_abs_error_bound in Hn2_error; try lra.\n  match type of Hn2_error with\n    _ <= ?z =>\n    destruct (rememb z) as (c & Hc);\n      rewrite <- Hc in Hn2_error\n  end.\n  unfold norm2_right, xdiff_left, xdiff_right, ydiff_left, ydiff_right, zdiff_left, zdiff_right in *.\n  match type of Hc with\n      _ = ?z =>\n      interval_intro z upper as Hc_range';\n        rewrite <- Hc in Hc_range';\n        clear Hc\n  end.\n  generalize (Rle_trans _ _ _ Hn2_error Hc_range').\n  clear c Hn2_error Hc_range'.\n  intro Hc.\n\n  assert (B2R _ _ v - sqrt (B2R _ _ n2) = sqrt (B2R _ _ n2) * d + e) as Hy_error_eq.\n  {\n    rewrite Hv_val.\n    ring.\n  }\n  match type of Hy_error_eq with\n      _ = ?z =>\n      interval_intro (Rabs z) upper with (i_prec 128) as Hy_error\n  end.\n  rewrite <- Hy_error_eq in Hy_error; clear Hy_error_eq.\n  split.\n  {\n    eexact (Rabs_triang2 _ _ _ _ _ Hy_error Hc).\n  }\n  match type of Hv_val with\n      _ = ?z =>\n      interval_intro z with (i_prec 128) as Hy_range\n  end.\n  rewrite <- Hv_val in Hy_range.\n  eexact Hy_range.\n\nDefined.\n\nDefinition f_norm_error' :=\n let (x, _) := f_norm_body_correct' in \n let '(y, _, _) := x in y.\n\nDefinition f_norm_error'_eq := \n  $( field_eq f_norm_error' )$ .\n\nDefinition f_norm_error := \n  $( match type of f_norm_error'_eq with _ = ?z => exact z end )$ .\n\nDefinition f_norm_left' :=\n let (x, _) := f_norm_body_correct' in \n let '(_, y, _) := x in y.\n\nDefinition f_norm_left'_eq := \n  $( field_eq f_norm_left' )$ .\n\nDefinition f_norm_left := \n  $( match type of f_norm_left'_eq with _ = ?z => exact z end )$ .\n\nDefinition f_norm_right' :=\n let (x, _) := f_norm_body_correct' in \n let '(_, _, y) := x in y.\n\nDefinition f_norm_right'_eq := \n  $( field_eq f_norm_right' )$ .\n\nDefinition f_norm_right := \n  $( match type of f_norm_right'_eq with _ = ?z => exact z end )$ .\n\nLemma f_norm_body_correct: forall\n      (ge: Clight.genv)\n      b_sqrt fn_sqrt\n      (Hb_sqrt_symb: Genv.find_symbol ge _sqrt = Some b_sqrt)\n      (Hb_sqrt_funct: Genv.find_funct_ptr ge b_sqrt = Some fn_sqrt)\n\n      (Hf_sqrt_correct: _sqrt_correct ge fn_sqrt)\n,\n  f_norm_correct (f_norm_error, f_norm_left, f_norm_right) ge (Internal f_norm)\n.\nProof.\n  unfold f_norm_error.\n  rewrite <- f_norm_error'_eq.\n  unfold f_norm_left.\n  rewrite <- f_norm_left'_eq.\n  unfold f_norm_right.\n  rewrite <- f_norm_right'_eq.\n  unfold f_norm_error', f_norm_left', f_norm_right'.\n  destruct f_norm_body_correct'.\n  destruct x.\n  destruct p.\n  assumption.\nQed.\n", "meta": {"author": "wuweh", "repo": "vsarbp", "sha": "8e4ca028ec8a73eb7f2fd27892a69971384cada5", "save_path": "github-repos/coq/wuweh-vsarbp", "path": "github-repos/coq/wuweh-vsarbp/vsarbp-8e4ca028ec8a73eb7f2fd27892a69971384cada5/sar/SARBackProjSourceNormOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1506235273411331}}
{"text": "Require Import ucos_include.\nRequire Import os_ucos_h.\nRequire Import sep_lemmas_ext.\nRequire Import linv_solver.\nLocal Open Scope code_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope int_scope.\n\nLemma absimp_taskcre_prio_invalid:\n  forall P v1 v2 v3 sch,\n    can_change_aop P ->\n    Int.ltu (Int.repr OS_LOWEST_PRIO) v3 = true ->\n    absinfer sch ( <|| taskcrecode (v1 :: v2 :: (Vint32 v3) :: nil) ||> ** P)\n             ( <|| END (Some (Vint32 (Int.repr PRIO_ERR))) ||> ** P).\nProof.\n  infer_solver 0%nat.\nQed.\n\nLemma absimp_taskcre_prio_already_exists:\n  forall P v1 v2 v3 sch mqls tls t ct,\n    can_change_aop P ->\n    absinfer sch ( <|| taskcrecode (v1 :: v2 :: (Vint32 v3) :: nil) ||> ** \n                       HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P) \n             ( <|| END (Some (Vint32 (Int.repr  OS_PRIO_EXIST))) ||> ** \n                   HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P) .\nProof.\n  infer_solver 1%nat.\nQed.\n\n\nLemma absimp_taskcre_no_more_tcb:\n  forall P v1 v2 v3 sch,\n    can_change_aop P ->\n    absinfer sch ( <|| taskcrecode (v1 :: v2 :: (Vint32 v3) :: nil) ||> ** P)\n             ( <|| END (Some (Vint32 (Int.repr OS_NO_MORE_TCB))) ||> ** P).\nProof.\n  infer_solver 2%nat.\nQed.\n\nLemma absimp_taskcre_succ:\n  forall P v1 v2 v3 sch t tls mqls ct ,\n    can_change_aop P ->\n    (* Int.lt ($ 63) v3 = false ->\n     * (* OSAbstMod.get O abtcblsid = Some (abstcblist tls) -> *)\n     * ~ (exists t' st msg, TcbMod.get tls t' = Some (v3, st, msg)) ->\n     * (exists t', TcbMod.join tls (TcbMod.sig t' (v3, rdy, Vnull)) tls' )-> *)\n    absinfer sch ( <|| taskcrecode (v1 :: v2 :: (Vint32 v3) :: nil) ||> **\n                       HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P)\n             ( <|| scrt (v1 :: v2 :: (Vint32 v3) :: nil);;(* taskcre_succ  (|(v1 :: v2 :: (Vint32 v3) :: nil)|) ;;  *)isched ;; END (Some (Vint32 (Int.repr NO_ERR))) ||> **  HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P).\n\nProof.\n  intros.\n  unfold taskcrecode.\n  infer_branch 3%nat.\n  eapply absinfer_eq.\nQed.\n\nLemma retpost_tcbinitpost: \n  retpost OS_TCBInitPost.\nProof.\n  unfolds.\n  intros.\n  unfold getasrt in H.\n  unfold  OS_TCBInitPost in H.\n  unfold  OS_TCBInitPost' in H.\n  sep lift 6%nat in H.\n  disj_asrt_destruct H.\n  sep split in H.\n  intro.\n  subst .\n  inverts H5.\n  intro.\n  subst.\n  sep split in H.\n  inverts H0.\nQed.\n\n\nLocal Ltac smartunfold3 :=\n  match goal with\n    | |- ?e _ _ _ => unfold e in *\n  end.\n\n\nLemma struct_pv_overlap:\n  forall p v1 v2 s P,\n    s |= Astruct p OS_TCB_flag v1 **\n      PV p @ Int8u |-> v2 **\n      P ->\n    False.\nProof.\n  intros.\n  unfold Astruct in H.\n  unfold OS_TCB_flag in H.\n  unfold Astruct' in H.\n  destruct v1.\n  sep destroy H.\n  simpl in H0; tryfalse.\n  destruct p.\n  sep normal in H.\n  Set Printing Depth 999.\n(* ** ac:   Show. *)\n  remember (        match v1 with\n                      | nil => Afalse\n                      | v :: vl' =>\n                        PV (b, i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @\n                           STRUCT os_tcb \u22c6 |-> v **\n                           match vl' with\n                             | nil => Afalse\n                             | v0 :: vl'0 =>\n                               PV (b,\n                                   (i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                   $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @ \n                                  OS_EVENT \u2217 |-> v0 **\n                                  match vl'0 with\n                                    | nil => Afalse\n                                    | v1 :: vl'1 =>\n                                      PV (b,\n                                          ((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                           $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                                    $ Z.of_nat (typelen OS_EVENT \u2217)) @ \n                                         (Void) \u2217 |-> v1 **\n                                         match vl'1 with\n                                           | nil => Afalse\n                                           | v2 :: vl'2 =>\n                                             PV (b,\n                                                 (((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                   +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                                    $ Z.of_nat (typelen (Void) \u2217)) @ \n                                                Int16u |-> v2 **\n                                                match vl'2 with\n                                                  | nil => Afalse\n                                                  | v3 :: vl'3 =>\n                                                    PV (b,\n                                                        ((((i +\u1d62\n                                                                 $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                          $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                                                   $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                                                                                       $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                                                                                                                                                         $ Z.of_nat (typelen Int16u)) @ \n                                                       Int8u |-> v3 **\n                                                       match vl'3 with\n                                                         | nil => Afalse\n                                                         | v4 :: vl'4 =>\n                                                           PV (b,\n                                                               (((((i +\u1d62\n                                                                         $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                                   +\u1d62\n                                                                      $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                                  +\u1d62  $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                                 +\u1d62  $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                                       $ Z.of_nat (typelen Int16u)) +\u1d62\n                                                                                                                                       $ Z.of_nat (typelen Int8u)) @ \n                                                              Int8u |-> v4 **\n                                                              match vl'4 with\n                                                                | nil => Afalse\n                                                                | v5 :: vl'5 =>\n                                                                  PV (b,\n                                                                      ((((((i +\u1d62\n                                                                                 $\n                                                                                 Z.of_nat\n                                                                                 (typelen STRUCT os_tcb \u22c6))\n                                                                           +\u1d62\n                                                                              $\n                                                                              Z.of_nat\n                                                                              (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                            $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                                         +\u1d62  $ Z.of_nat (typelen (Void) \u2217))\n                                                                        +\u1d62  $ Z.of_nat (typelen Int16u))\n                                                                       +\u1d62  $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                          $ Z.of_nat (typelen Int8u)) @ \n                                                                     Int8u |-> v5 **\n                                                                     match vl'5 with\n                                                                       | nil => Afalse\n                                                                       | v6 :: vl'6 =>\n                                                                         PV (b,\n                                                                             (((((((i +\u1d62\n                                                                                         $\n                                                                                         Z.of_nat\n                                                                                         (typelen STRUCT os_tcb \u22c6))\n                                                                                   +\u1d62\n                                                                                      $\n                                                                                      Z.of_nat\n                                                                                      (typelen STRUCT os_tcb \u22c6))\n                                                                                  +\u1d62\n                                                                                     $\n                                                                                     Z.of_nat\n                                                                                     (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                              $ Z.of_nat (typelen (Void) \u2217))\n                                                                                +\u1d62\n                                                                                   $ Z.of_nat (typelen Int16u))\n                                                                               +\u1d62  \n                                                                                  $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                                 $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                                                                $ Z.of_nat (typelen Int8u)) @\n                                                                            Int8u |-> v6 **\n                                                                            match vl'6 with\n                                                                              | nil => Afalse\n                                                                              | v7 :: vl'7 =>\n                                                                                PV (b,\n                                                                                    ((((((((i +\u1d62\n                                                                                                 $\n                                                                                                 Z.of_nat\n                                                                                                 (typelen STRUCT os_tcb \u22c6))\n                                                                                           +\u1d62\n                                                                                              $\n                                                                                              Z.of_nat\n                                                                                              (typelen STRUCT os_tcb \u22c6))\n                                                                                          +\u1d62\n                                                                                             $\n                                                                                             Z.of_nat\n                                                                                             (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                      $\n                                                                                                                      Z.of_nat (typelen (Void) \u2217))\n                                                                                        +\u1d62\n                                                                                           $ Z.of_nat (typelen Int16u))\n                                                                                       +\u1d62\n                                                                                          $ Z.of_nat (typelen Int8u))\n                                                                                      +\u1d62\n                                                                                         $ Z.of_nat (typelen Int8u))\n                                                                                     +\u1d62\n                                                                                        $ Z.of_nat (typelen Int8u))\n                                                                                    +\u1d62\n                                                                                       $ Z.of_nat (typelen Int8u)) @\n                                                                                   Int8u |-> v7 **\n                                                                                   match vl'7 with\n                                                                                     | nil => Afalse\n                                                                                     | v8 :: vl'8 =>\n                                                                                       PV \n                                                                                         (b,\n                                                                                          (((((((((i +\u1d62\n                                                                                                        $\n                                                                                                        Z.of_nat\n                                                                                                        (typelen STRUCT os_tcb \u22c6))\n                                                                                                  +\u1d62\n                                                                                                     $\n                                                                                                     Z.of_nat\n                                                                                                     (typelen STRUCT os_tcb \u22c6))\n                                                                                                 +\u1d62\n                                                                                                    $\n                                                                                                    Z.of_nat\n                                                                                                    (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                             $\n                                                                                                                             Z.of_nat (typelen (Void) \u2217))\n                                                                                               +\u1d62\n                                                                                                  $ Z.of_nat (typelen Int16u))\n                                                                                              +\u1d62\n                                                                                                 $ Z.of_nat (typelen Int8u))\n                                                                                             +\u1d62\n                                                                                                $ Z.of_nat (typelen Int8u))\n                                                                                            +\u1d62\n                                                                                               $ Z.of_nat (typelen Int8u))\n                                                                                           +\u1d62\n                                                                                              $ Z.of_nat (typelen Int8u))\n                                                                                          +\u1d62\n                                                                                             $ Z.of_nat (typelen Int8u)) @\n                                                                                         Int8u |-> v8 **\n                                                                                         match vl'8 with\n                                                                                           | nil => Aemp\n                                                                                           | _ :: _ => Afalse\n                                                                                         end\n                                                                                   end\n                                                                            end\n                                                                     end\n                                                              end\n                                                       end\n                                                end\n                                         end\n                                  end\n                           end\n                    end ).\n  clear Heqa.\n  assert ( (b,i) <> (b,i)).\n  eapply pv_false.\n  Focus 3.\n  instantiate (6:= s).\n  sep auto.\n  intro.\n  unfolds in H0.\n  destruct H0; simpljoin; tryfalse.\n  destruct H0; simpljoin; tryfalse.\n  intro.\n  unfolds in H0.\n  destruct H0; simpljoin; tryfalse.\n  destruct H0; simpljoin; tryfalse.\n  apply H0; auto.\nQed.\n\n\n\nLemma R_ECB_ETbl_P_hold_for_add_tcb:\n  forall x0 p v'14 v'42 v'5 v'34, \n    R_ECB_ETbl_P x0 p v'14 ->\n    TcbJoin v'34 (v'42, rdy, Vnull) v'14 v'5 ->\n    R_ECB_ETbl_P x0 p v'5.\nProof.\n  intros.\n  destruct p.\n  unfold R_ECB_ETbl_P in *.\n  splits.\n  simpljoin.\n  clear H1 H2.\n\n  smartunfold3.\n  simpljoin.\n  splits.\n  {\n    smartunfold3.\n    intros .\n    lets bb: H prio H4 H5.\n    simpljoin.\n    exists x.\n    unfold get in *; simpl in *.\n    erewrite TcbMod.join_get_r.\n    eauto.\n    eauto.\n    eauto.\n  }\n\n  {\n    smartunfold3.\n    intros .\n    lets bb: H1 prio H4 H5.\n    simpljoin.\n    exists x.\n    unfold get in *; simpl in *.\n    erewrite TcbMod.join_get_r.\n    eauto.\n    eauto.\n    eauto.\n  }\n\n  {\n    smartunfold3.\n    intros .\n    lets bb: H2 prio H4 H5.\n    simpljoin.\n    exists x.\n    unfold get in *; simpl in *.\n    erewrite TcbMod.join_get_r.\n    eauto.\n    eauto.\n    eauto.\n  }\n\n  {\n    smartunfold3.\n    intros .\n    lets bb: H3 prio H4 H5.\n    simpljoin.\n    exists x.\n    unfold get in *; simpl in *.\n    erewrite TcbMod.join_get_r.\n    eauto.\n    eauto.\n    eauto.\n  }\n\n  simpljoin.\n  clear H H2.\n\n  smartunfold3.\n  simpljoin.\n  splits.\n\n  {\n    smartunfold3.\n    intros.\n    unfold TcbJoin in H0.\n    unfold get, join, sig in *; simpl in *.\n    assert (TcbMod.get v'14 tid = Some (prio, wait (os_stat_q x0) n, m)).\n    eapply TcbMod.join_get_or in H4.\n    2:eauto.\n    destruct H4; intros.\n    assert ( v'34 = tid \\/ v'34 <> tid).\n    tauto.\n    destruct H5.\n    subst.\n    rewrite TcbMod.get_a_sig_a in H4.\n    inverts H4.\n    go.\n\n    rewrite TcbMod.get_a_sig_a' in H4.\n    inverts H4.\n    go.\n    auto.\n\n    eapply H.\n    eauto.\n  }\n  \n  {\n    smartunfold3.\n    intros.\n    unfold TcbJoin in H0.\n    unfold get, join, sig in *; simpl in *.\n    assert (TcbMod.get v'14 tid = Some (prio, wait (os_stat_sem x0) n, m)).\n    eapply TcbMod.join_get_or in H4.\n    2:eauto.\n    destruct H4; intros.\n    assert ( v'34 = tid \\/ v'34 <> tid).\n    tauto.\n    destruct H5.\n    subst.\n    rewrite TcbMod.get_a_sig_a in H4.\n    inverts H4.\n    go.\n\n    rewrite TcbMod.get_a_sig_a' in H4.\n    inverts H4.\n    go.\n    auto.\n\n    eapply H1.\n    eauto.\n  }\n  \n  {\n    smartunfold3.\n    intros.\n    unfold TcbJoin in H0.\n    unfold get, join, sig in *; simpl in *.\n    assert (TcbMod.get v'14 tid = Some (prio, wait (os_stat_mbox x0) n, m)).\n    eapply TcbMod.join_get_or in H4.\n    2:eauto.\n    destruct H4; intros.\n    assert ( v'34 = tid \\/ v'34 <> tid).\n    tauto.\n    destruct H5.\n    subst.\n    rewrite TcbMod.get_a_sig_a in H4.\n    inverts H4.\n    go.\n\n    rewrite TcbMod.get_a_sig_a' in H4.\n    inverts H4.\n    go.\n    auto.\n\n    eapply H2.\n    eauto.\n  }\n\n  {\n    smartunfold3.\n    intros.\n    unfold TcbJoin in H0.\n    unfold get, join, sig in *; simpl in *.\n    assert (TcbMod.get v'14 tid = Some (prio, wait (os_stat_mutexsem x0) n, m)).\n    eapply TcbMod.join_get_or in H4.\n    2:eauto.\n    destruct H4; intros.\n    assert ( v'34 = tid \\/ v'34 <> tid).\n    tauto.\n    destruct H5.\n    subst.\n    rewrite TcbMod.get_a_sig_a in H4.\n    inverts H4.\n    go.\n\n    rewrite TcbMod.get_a_sig_a' in H4.\n    inverts H4.\n    go.\n    auto.\n\n    eapply H3.\n    eauto.\n  }\n\n  simpljoin; auto.\nQed.\n\n\nLemma ecblist_hold_for_add_tcb :\n  forall v'4 x v'3 v'13 v'14 v'5 v'42 v'34,\n    ECBList_P x Vnull v'4 v'3 v'13 v'14 ->\n    TcbJoin v'34 (v'42, rdy, Vnull) v'14 v'5 ->\n    ECBList_P x Vnull v'4 v'3 v'13 v'5.\nProof.\n  induction v'4.\n  intros.\n  simpl.\n  simpl in H.\n  auto.\n  intros.\n  unfold1 ECBList_P in *.\n  simpljoin.\n  destruct v'3; tryfalse.\n  destruct a.\n  simpljoin.\n  eexists.\n  splits; eauto.\n  eapply R_ECB_ETbl_P_hold_for_add_tcb; eauto.\n\n  repeat tri_exists_and_solver1.\n  \nQed.\nLemma nv'2nv:\n  forall vl n x,\n    nth_val' n vl = x ->\n    x <> Vundef ->\n    nth_val n vl = Some x.\nProof.\n  induction vl.\n  induction n.\n  intros.\n  simpl in H.\n  tryfalse.\n  intros.\n  simpl in H.\n  tryfalse.\n\n  induction n.\n  intros.\n  simpl in H.\n  simpl.\n  inverts H.\n  auto.\n  intros.\n  simpl.\n  simpl in H.\n  apply IHvl.\n  auto.\n  auto.\nQed.\n\n\nLemma r_priotbl_p_hold_for_add_tcb :\n  forall v'14 v'5 v'42 v'34 v'43 v'28,\n    (* Int.unsigned v'42 < 64 -> *)\n    v'43 <> v'34 ->\n    nth_val' (Z.to_nat (Int.unsigned v'42)) v'28 = Vnull ->\n    R_PrioTbl_P v'28 v'14 v'43 ->\n    TcbJoin v'34 (v'42, rdy, Vnull) v'14 v'5 ->\n    R_PrioTbl_P\n      (update_nth_val (Z.to_nat (Int.unsigned v'42)) v'28 (Vptr v'34)) v'5\n      v'43.\nProof.\n  introv HHHH.\n  intros.\n  smartunfold3.\n  simpljoin.\n  assert ( R_Prio_No_Dup v'5) as special.\n  {\n    unfold R_Prio_No_Dup in *.\n    intros.\n    assert (tid = v'34 \\/ tid <> v'34) by tauto.\n    assert (tid' = v'34 \\/ tid' <> v'34) by tauto.\n\n    destruct H7; destruct H8.\n    subst.\n    tryfalse.\n\n    {\n      subst v'34.\n      unfold get, join, sig in *; simpl in *.\n      erewrite TcbMod.join_get_l in H5.\n      2:eauto.\n      2:go.\n      Focus 2.\n      assert (tidspec.beq tid tid = true).\n      go.\n      rewrite H7.\n      eauto.\n      inverts H5.\n      eapply TcbMod.join_get_or in H6.\n      2: eauto.\n\n      destruct H6.\n      \n      unfold get, join, sig in *; simpl in *.\n      rewrite TcbMod.get_a_sig_a' in H5.\n      inverts H5.\n      go.\n      \n      lets bbb: H2 H5.\n      intro.\n      subst.\n      simpljoin.\n      eapply nv'2nv in H.\n      unfold nat_of_Z in *.\n      rewrite H in H6.\n      inverts H6.\n      intro; tryfalse.\n    }\n\n    {\n      subst v'34.\n      unfold get, join, sig in *; simpl in *.\n      erewrite TcbMod.join_get_l in H6.\n      2:eauto.\n      2:go.\n      Focus 2.\n      assert (tidspec.beq tid' tid' = true).\n      go.\n      rewrite H8.\n      eauto.\n      inverts H6.\n      eapply TcbMod.join_get_or in H1.\n      2: eauto.\n\n      destruct H1.\n      \n      unfold get, join, sig in *; simpl in *.\n      rewrite TcbMod.get_a_sig_a' in H1.\n      inverts H1.\n      go.\n      \n      lets bbb: H2 H1.\n      intro.\n      subst.\n      simpljoin.\n      eapply nv'2nv in H.\n      unfold nat_of_Z in *.\n      rewrite H in H6.\n      inverts H6.\n      intro; tryfalse.\n    }\n\n    {\n      unfold get, sig, join in *; simpl in *.\n      eapply TcbMod.join_get_or in H5; eauto.\n      eapply TcbMod.join_get_or in H6; eauto.\n\n      destruct H5.\n      unfold get, sig, join in *; simpl in *.\n      rewrite TcbMod.get_a_sig_a' in H5.\n      inverts H5.\n      go.\n\n      destruct H6.\n      unfold get, sig, join in *; simpl in *.\n      rewrite TcbMod.get_a_sig_a' in H6.\n      inverts H6.\n      go.\n\n      eapply H3.\n      2:eauto.\n      2:eauto.\n      eauto.\n    }\n    \n  }\n  splits; auto.\n  intros.\n  assert ( prio =  v'42 \\/  prio <>  v'42).\n  tauto.\n  destruct H7.\n  rewrite H7 in *.\n  unfold nat_of_Z in *.\n  erewrite hoare_assign.update_nth in H5.\n  inverts H5.\n  \n  unfold TcbJoin in *.\n  unfold get, join, sig in *; simpl in *.\n  do 2 eexists.\n  eapply TcbMod.join_get_l.\n  eauto.\n  inverts H7.\n  eapply TcbMod.get_a_sig_a.\n  go.\n(* ** ac:   SearchAbout nth_val. *)\n(* ** ac:   Print nth_val'. *)\n(* ** ac:   Show. *)\n  eapply nv'2nv; eauto.\n  (* intro; tryfalse. *)\n  unfold nat_of_Z in *.\n(* ** ac:   SearchAbout nth_val. *)\n\n  assert (exists st m, get v'14 tcbid = Some (prio, st, m)).\n  eapply H0; eauto.\n  eapply nth_upd_neq.\n  2:eauto.\n  intro.\n(* ** ac:   SearchAbout Z.to_nat. *)\n  apply Z2Nat.inj in H8.\n(* ** ac:   SearchAbout (Int.unsigned _ = Int.unsigned _). *)\n\n  apply unsigned_inj in H8.\n  tryfalse.\n  clear; int auto.\n  clear; int auto.\n\n  simpljoin.\n  unfold TcbJoin in H1.\n  unfold get, join, sig in *; simpl in *.\n  do 2 eexists.\n  go.\n\n\n  intros.\n  unfold nat_of_Z in *.\n\n\n  eapply TcbMod.join_get_or in H4; eauto.\n  2:exact H1.\n  destruct H4.\n  assert (tcbid = v'34 \\/ tcbid <> v'34).\n  tauto.\n  destruct H5.\n  subst.\n  erewrite TcbMod.get_a_sig_a in H4.\n  inverts H4.\n  erewrite hoare_assign.update_nth.\n  splits; auto.\n  eapply nv'2nv.\n  eauto.\n  intro; tryfalse.\n  go.\n\n  erewrite TcbMod.get_a_sig_a' in H4.\n  inverts H4.\n  go.\n\n  lets bb: H2 H4.\n\n  assert (prio = v'42 \\/ prio <> v'42) by tauto.\n  destruct H5.\n  subst.\n  apply nv'2nv in H.\n  rewrite H in bb.\n  destruct bb.\n  tryfalse.\n  intro; tryfalse.\n\n  simpljoin.\n  splits; auto.\n  erewrite nth_upd_neqrev.\n  eauto.\n  intro.\n  2:eauto.\n  \n  apply Z2Nat.inj in H8.\n  apply unsigned_inj in H8.\n  tryfalse.\n  clear; int auto.\n  clear; int auto.\nQed.\n\nLemma nth_upd_neqeq:\n  forall (vl : vallist) (n m : nat) (x : val),\n    n <> m ->\n    nth_val n (update_nth_val m vl x) = nth_val n vl.\nProof.\n  intros.\n  simpl.\n  auto.\n  intros.\n  remember (nth_val n vl).\n  destruct o.\n  erewrite nth_upd_neqrev.\n  eauto.\n  auto.\n  auto.\n  gen n.\n  gen m.\n  induction vl.\n  simpl.\n  auto.\n  intros.\n  gen m.\n  induction n.\n\n  simpl in Heqo.\n  inverts Heqo.\n  induction m.\n  intros.\n  simpl.\n  simpl in Heqo.\n  auto.\n  intros.\n  simpl.\n  simpl in Heqo.\n  apply IHvl.\n  auto.\n  auto.\nQed.\n\nLemma tcblist_p_hold_for_upd_1 :\n  forall a b ls c d e,\n    TCBList_P a (b::ls) c d ->\n    TCBList_P a (update_nth_val 1 b e :: ls) c d. \nProof.\n  intros.\n  unfold1 TCBList_P in *.\n  simpljoin.\n  repeat tri_exists_and_solver1.\n  unfolds.\n(* ** ac:   SearchAbout nth_val. *)\n  eapply nth_upd_neqrev.\n  omega.\n  auto.\n\n  unfold TCBNode_P in *.\n  destruct x2; destruct p.\n  simpljoin.\n  splits ; try (eapply nth_upd_neqrev; [omega| auto]).\n\n  unfold RL_TCBblk_P in *.\n  simpljoin.\n  unfold V_OSTCBPrio, V_OSTCBX, V_OSTCBY, V_OSTCBBitX, V_OSTCBBitY, V_OSTCBStat,  V_OSTCBEventPtr  .\n  repeat (erewrite nth_upd_neqrev; [idtac| try omega| eauto 1]).\n  repeat tri_exists_and_solver1.\n\n  unfold R_TCB_Status_P in *.\n  unfold RLH_RdyI_P, RHL_RdyI_P, RLH_TCB_Status_Wait_P, RHL_TCB_Status_Wait_P in *.\n  unfold RLH_Wait_P, RLH_WaitS_P, RLH_WaitQ_P, RLH_WaitMB_P, RLH_WaitMS_P,\n  RHL_Wait_P, RHL_WaitS_P, RHL_WaitQ_P, RHL_WaitMB_P, RHL_WaitMS_P\n    in *.\n  unfold WaitTCBblk in *.\n  unfold RdyTCBblk in *.\n  unfold V_OSTCBPrio, V_OSTCBX, V_OSTCBY, V_OSTCBBitX, V_OSTCBBitY, V_OSTCBStat,  V_OSTCBEventPtr, V_OSTCBDly in *.\n  simpljoin.\n  repeat (erewrite nth_upd_neqeq; [idtac| try omega]).\n  splits; auto.\nQed.\n\nLemma tcblist_p_hold_for_add_tcb_lemma :\n  forall v l v'26 v'23 v'42 ,\n    0 <= Int.unsigned v'42 < 64 ->\n    array_type_vallist_match Int8u v'26 ->\n    length v'26 = \u2218 OS_RDY_TBL_SIZE ->\n    TCBList_P v l v'26 v'23 ->\n    (~ exists id t m, get v'23 id = Some (v'42, t, m) )->\n    TCBList_P v l\n              (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                                     (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist))))\n              v'23.\nProof.\n  introv HHH.\n  Require Import protect.\n  protect HHH.\n  intros HHH2 HHH3.\n  gen v.\n  gen v'23.\n  gen l.\n  induction l.\n  intros.\n  simpl.\n  simpl in H.\n  auto.\n  intros.\n  unfold1 TCBList_P.\n  unfold1 TCBList_P in H.\n  simpljoin.\n  repeat tri_exists_and_solver1.\n  Focus 2.\n  eapply IHl.\n  auto.\n  intro.\n  simpljoin.\n  eapply H0.\n  do 3 eexists.\n  unfold get,sig,join in *; simpl in *.\n  unfold get,sig,join in *; simpl in *.\n  eapply TcbMod.join_get_r.\n  eauto.\n  exact H.\n  auto.\n  Require Import OSQPostPure.\n(* ** ac:   Check   prio_in_tbl_orself . *)\n(* ** ac:   SearchAbout TCBNode_P. *)\n  cut (exists grp, nth_val \u2218 (Int.unsigned (v'42 >>\u1d62 $ 3)) v'26 = Some (Vint32 grp) ).\n  intro.\n  simpljoin.\n  lets bbb: H.\n  unfold nat_of_Z in bbb.\n(* ** ac:   SearchAbout nth_val. *)\n  eapply new_inv.nth_val_nth_val'_some_eq in bbb.\n  rewrite bbb.\n(* ** ac:   Check TCBNode_P_rtbl_add. *)\n  cut ((nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist) = Vint32 ($ 1<<\u1d62(v'42&\u1d62$ 7)) ).\n  intro.\n  rewrite H5.\n  simpl.\n  destruct x2.\n  destruct p.\n  eapply TCBNode_P_rtbl_add; eauto.\n  Focus 3.\n  unfolds in H3.\n  simpljoin.\n  auto.\n  Focus 2.\n  intro.\n  apply H0.\n  subst v'42.\n  do 3 eexists.\n  unfold get,sig,join in *; simpl in *.\n  unfold get,sig,join in *; simpl in *.\n  eapply TcbMod.join_get_l.\n  eauto.\n  eapply TcbMod.get_a_sig_a.\n  go.\n  unfolds in H3.\n  simpljoin.\n  unfolds in H7.\n  simpljoin.\n  rewrite H6 in H7.\n  inverts H7.\n  auto.\n(* ** ac:   SearchAbout OSMapVallist. *)\n  assert ((Int.unsigned (v'42&\u1d62$ 7)) <= 7).\n  clear -HHH.\n  unprotect HHH.\n  mauto.\n  clear -H5.\n  remember (v'42&\u1d62$ 7) .\n  mauto.\n  eapply new_rtbl.prio_set_rdy_in_tbl_lemma_1; auto.\nQed.\n\n\nLemma tcblist_p_hold_for_add_tcb :\n  forall tid v'9 v'10 v'26 v'23 v'42 v'34,\n    0 <= Int.unsigned v'42 < 64 ->\n    array_type_vallist_match Int8u v'26 ->\n    length v'26 = \u2218 OS_RDY_TBL_SIZE ->\n    TCBList_P (Vptr tid) (v'9 :: v'10) v'26 v'23 ->\n    (~ exists id t m, get v'23 id = Some (v'42, t, m) )->\n    TCBList_P (Vptr tid) (update_nth_val 1 v'9 (v'34) :: v'10)\n              (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                                     (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist))))\n              v'23.\nProof.\n  introv HHH.\n  protect HHH.\n  intros HHH2 HHH3.\n  intros.\n  eapply tcblist_p_hold_for_upd_1.\n  remember (v'9 :: v'10).\n  clear Heql.\n  remember (Vptr tid).\n  clear Heqv.\n  gen v.\n  gen v'23.\n  gen l.\n  induction l.\n  intros.\n  simpl.\n  simpl in H.\n  auto.\n  intros.\n  unfold1 TCBList_P.\n  unfold1 TCBList_P in H.\n  simpljoin.\n  repeat tri_exists_and_solver1.\n  Focus 2.\n  eapply IHl.\n  auto.\n  intro.\n  simpljoin.\n  eapply H0.\n  do 3 eexists.\n  unfold get,sig,join in *; simpl in *.\n  unfold get,sig,join in *; simpl in *.\n  eapply TcbMod.join_get_r.\n  eauto.\n  exact H.\n  auto.\n  Require Import OSQPostPure.\n(* ** ac:   Check   prio_in_tbl_orself . *)\n(* ** ac:   SearchAbout TCBNode_P. *)\n  cut (exists grp, nth_val \u2218 (Int.unsigned (v'42 >>\u1d62 $ 3)) v'26 = Some (Vint32 grp) ).\n  intro.\n  simpljoin.\n  lets bbb: H.\n  unfold nat_of_Z in bbb.\n(* ** ac:   SearchAbout nth_val. *)\n  eapply new_inv.nth_val_nth_val'_some_eq in bbb.\n  rewrite bbb.\n(* ** ac:   Check TCBNode_P_rtbl_add. *)\n  cut ((nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist) = Vint32 ($ 1<<\u1d62(v'42&\u1d62$ 7)) ).\n  intro.\n  rewrite H5.\n  simpl.\n  destruct x2.\n  destruct p.\n  eapply TCBNode_P_rtbl_add; eauto.\n  Focus 3.\n  unfolds in H3.\n  simpljoin.\n  auto.\n  Focus 2.\n  intro.\n  apply H0.\n  subst v'42.\n  do 3 eexists.\n  unfold get,sig,join in *; simpl in *.\n  unfold get,sig,join in *; simpl in *.\n  eapply TcbMod.join_get_l.\n  eauto.\n  eapply TcbMod.get_a_sig_a.\n  go.\n  unfolds in H3.\n  simpljoin.\n  unfolds in H7.\n  simpljoin.\n  rewrite H6 in H7.\n  inverts H7.\n  auto.\n  assert ((Int.unsigned (v'42&\u1d62$ 7)) <= 7).\n  clear -HHH.\n  unprotect HHH.\n  mauto.\n  clear -H5.\n  remember (v'42&\u1d62$ 7) .\n  mauto.\n  eapply new_rtbl.prio_set_rdy_in_tbl_lemma_1; auto.\n  \nQed.\n\n(* Lemma tcblist_p_hold_for_add_tcb' :\n *   forall v'26 v'42 v'34 v'39 v'30,\n *     (* TCBList_P v'30 nil v'26 v'22 -> *)\n *     new_tcb_node_p v'42 Vnull v'30 v'39 ->\n *     TCBList_P (Vptr v'34) ((v'39 :: nil) ++ nil)\n *               (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n *                               (val_inj\n *                                  (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n *                                      (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist))))\n *               (sig v'34 (v'42, rdy, Vnull)).\n *           Admitted. *)\n\nLemma TCBList_P_nil_empty:\n  forall v'30 v'26 v'22,\n    TCBList_P v'30 nil v'26 v'22 ->\n    v'22 = empenv.\nProof.\n  intros.\n  simpl in H.\n  auto.\nQed.\n\n\nLemma rh_t_e_p_hold_for_add_tcb:\n  forall v'13 v'14 tid v'34 v'42 v'5,\n    RH_TCBList_ECBList_P v'13 v'14 tid ->\n    TcbJoin v'34 (v'42, rdy, Vnull) v'14 v'5 ->\n    RH_TCBList_ECBList_P v'13 v'5 tid.\nProof.\n  intros.\n  smartunfold3.\n  simpljoin.\n  splits.\n  {\n    smartunfold3.\n    simpljoin.\n    splits.\n    {\n      intros.\n      lets bb: H H5.\n      simpljoin.\n      do 3 eexists.\n      unfold get, sig, join in *; simpl in *.\n      go.\n    }\n    {\n      intros.\n      unfold get, sig, join in *; simpl in *.\n      eapply TcbMod.join_get_or in H5.\n      2: exact H0.\n      destruct H5.\n      assert (tid0 = v'34 \\/ tid0 <> v'34).\n      tauto.\n      destruct H6.\n      subst.\n      rewrite TcbMod.get_a_sig_a in H5.\n      inverts H5.\n      go.\n      \n      rewrite TcbMod.get_a_sig_a' in H5.\n      inverts H5.\n      go.\n\n      eapply H4.\n      eauto.\n    }\n  }\n  {\n    Local Ltac swapname H H' :=\n      let HH := fresh in\n      rename H into HH; rename H' into H; rename HH into H'.\n      swapname H H1.\n      smartunfold3.\n      simpljoin.\n      splits.\n      {\n        intros.\n        lets bb: H H5.\n        simpljoin.\n        do 3 eexists.\n        unfold get, sig, join in *; simpl in *.\n        go.\n      }\n      {\n        intros.\n        unfold get, sig, join in *; simpl in *.\n        eapply TcbMod.join_get_or in H5.\n        2: exact H0.\n        destruct H5.\n        assert (tid0 = v'34 \\/ tid0 <> v'34).\n        tauto.\n        destruct H6.\n        subst.\n        rewrite TcbMod.get_a_sig_a in H5.\n        inverts H5.\n        go.\n        \n        rewrite TcbMod.get_a_sig_a' in H5.\n        inverts H5.\n        go.\n\n        eapply H4.\n        eauto.\n      }\n  }\n\n  {\n    swapname H H2.\n    smartunfold3.\n    simpljoin.\n    splits.\n    {\n      intros.\n      lets bb: H H5.\n      simpljoin.\n      do 3 eexists.\n      unfold get, sig, join in *; simpl in *.\n      go.\n    }\n    {\n      intros.\n      unfold get, sig, join in *; simpl in *.\n      eapply TcbMod.join_get_or in H5.\n      2: exact H0.\n      destruct H5.\n      assert (tid0 = v'34 \\/ tid0 <> v'34).\n      tauto.\n      destruct H6.\n      subst.\n      rewrite TcbMod.get_a_sig_a in H5.\n      inverts H5.\n      go.\n      \n      rewrite TcbMod.get_a_sig_a' in H5.\n      inverts H5.\n      go.\n\n      eapply H4.\n      eauto.\n    }\n  }\n\n  {\n    swapname H H3.\n    smartunfold3.\n    simpljoin.\n    splits.\n    {\n      intros.\n      lets bb: H H6.\n      simpljoin.\n      do 3 eexists.\n      unfold get, sig, join in *; simpl in *.\n      go.\n    }\n    {\n      intros.\n      unfold get, sig, join in *; simpl in *.\n      eapply TcbMod.join_get_or in H6.\n      2: exact H0.\n      destruct H6.\n      assert (tid0 = v'34 \\/ tid0 <> v'34).\n      tauto.\n      destruct H7.\n      subst.\n      rewrite TcbMod.get_a_sig_a in H6.\n      inverts H6.\n      go.\n      \n      rewrite TcbMod.get_a_sig_a' in H6.\n      inverts H6.\n      go.\n\n      eapply H4.\n      eauto.\n    }\n\n    unfolds.\n    intros.\n    unfolds in H5.\n    lets bb: H5 H6.\n    simpljoin.\n    do 3 eexists.\n    unfold get, sig, join in *; simpl in *.\n    go.\n  }\n\n  \nQed.\n\nLemma update_eq :\n  forall ls n c,\n    nth_val n ls= Some c ->\n    ls = update_nth_val n ls c.\nProof.\n  induction ls.\n  intros.\n  simpl in H.\n  inversion H.\n  induction n.\n  intros.\n  simpl in H.\n  simpl.\n  inverts H.\n  auto.\n  intros.\n  simpl.\n  assert (ls = update_nth_val n ls c).\n  apply IHls.\n  simpl in H.\n  auto.\n  rewrite <- H0.\n  auto.\nQed.\n\n\nLemma tcblist_p_hold_for_add_tcb'' :\n  forall v'26 v'42 v'34 v'39 v'30 vleft x v'22,\n    0 <= Int.unsigned v'42 < 64 ->\n    array_type_vallist_match Int8u v'26 ->\n    length v'26 = \u2218 OS_RDY_TBL_SIZE ->\n    ~ (exists id t m, get v'22 id = Some (v'42, t, m)) ->\n    TCBList_P v'30 vleft v'26 v'22 ->\n    new_tcb_node_p v'42 Vnull v'30 v'39 ->\n    join (sig v'34 (v'42, rdy, Vnull)) v'22 x -> \n    TCBList_P (Vptr v'34) ((v'39 :: nil) ++ vleft)\n              (update_nth_val (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned (v'42 >>\u1d62 $ 3))) v'26)\n                                     (nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist))))\n              x.\nProof.\n  intros.\n  change ((v'39::nil) ++ vleft) with (v'39 :: vleft).\n  unfold1 TCBList_P.\n  repeat tri_exists_and_solver1.\n  Focus 3.\n  eapply tcblist_p_hold_for_add_tcb_lemma; eauto.\n  unfolds in H4.\n  simpljoin; auto.\n(* ** ac:   SearchAbout TCBNode_P. *)\n\n  assert ((nth_val' (Z.to_nat (Int.unsigned (v'42&\u1d62$ 7))) OSMapVallist) = Vint32 ($ 1<<\u1d62(v'42&\u1d62$ 7)) ) as HH1.\n  assert ((Int.unsigned (v'42&\u1d62$ 7)) <= 7).\n  clear -H.\n  mauto.\n  clear -H6.\n  remember (v'42&\u1d62$ 7) .\n  mauto.\n\n  assert (exists grp, nth_val \u2218 (Int.unsigned (v'42 >>\u1d62 $ 3)) v'26 = Some (Vint32 grp) ) as HH2.\n  eapply new_rtbl.prio_set_rdy_in_tbl_lemma_1; auto.\n  destruct HH2 as (group & HH2).\n  unfold nat_of_Z in HH2.\n  lets HH2': (nth_val_nth_val'_some_eq _ _ HH2).\n\n  rewrite HH1, HH2'.\n\n\n  unfolds.\n  unfolds in H4.\n  splits; simpljoin; auto.\n  unfolds.\n  repeat tri_exists_and_solver1.\n  Focus 3.\n(* ** ac:   SearchAbout R_TCB_Status_P. *)\n  unfolds.\n  splits.\n  {\n    unfolds.\n    intros.\n    unfolds in H18.\n    simpljoin.\n    rewrite H6 in H18.\n    inverts H18.\n    repeat tri_exists_and_solver1.\n  }\n\n  {\n    unfolds.\n    intros.\n    inverts H18.\n    repeat tri_exists_and_solver1.\n    unfolds.\n    splits.\n    auto.\n(* ** ac:     Check prio_in_tbl_orself. *)\n    simpl.\n    eapply prio_in_tbl_orself.\n  }\n\n  {\n    unfolds.\n    splits.\n    {\n      unfolds.\n      intros.\n      unfolds in H18.\n      simpljoin.\n      rewrite H6 in H18.\n      inverts H18.\n      lets bb: prio_notin_tbl_orself H17 HH2.\n\n      simpl in H20.\n      tryfalse.\n    }\n    {\n      unfolds.\n      intros.\n      unfolds in H18.\n      simpljoin.\n      rewrite H6 in H18.\n      inverts H18.\n      lets bb: prio_notin_tbl_orself H17 HH2.\n\n      simpl in H20.\n      tryfalse.\n    }\n\n    {\n      unfolds.\n      intros.\n      unfolds in H18.\n      simpljoin.\n      rewrite H6 in H18.\n      inverts H18.\n      lets bb: prio_notin_tbl_orself H17 HH2.\n\n      simpl in H20.\n      tryfalse.\n    }\n\n    {\n      unfolds.\n      intros.\n      unfolds in H18.\n      simpljoin.\n      rewrite H6 in H18.\n      inverts H18.\n      lets bb: prio_notin_tbl_orself H17 HH2.\n\n      simpl in H20.\n      tryfalse.\n    }\n    {\n      unfolds.\n      intros.\n      unfolds in H18.\n      simpljoin.\n      rewrite H6 in H18.\n      inverts H18.\n      lets bb: prio_notin_tbl_orself H17 HH2.\n\n      simpl in H20.\n      tryfalse.\n    }\n    \n  }\n\n  {\n    unfolds.\n    splits.\n    {\n      unfolds.\n      intros.\n      inverts H18.\n    }\n    {\n      unfolds.\n      intros.\n      inverts H18.\n    }\n\n    {\n      unfolds.\n      intros.\n      inverts H18.\n    }\n\n    {\n      unfolds.\n      intros.\n      inverts H18.\n    }\n\n    {\n      unfolds.\n      intros.\n      inverts H18.\n    }\n  }\n  Unfocus.\n  rewrite HH1 in H12.\n  auto.\n\n  assert ((Int.unsigned (v'42>>\u1d62$ 3)) <= 7).\n  clear -H17.\n  mauto.\n  assert ((nth_val' (Z.to_nat (Int.unsigned (v'42>>\u1d62$ 3))) OSMapVallist) = Vint32 ($ 1<<\u1d62(v'42>>\u1d62$ 3)) ) as HH3.\n  clear -H18.\n  remember (v'42>>\u1d62$ 3) .\n  mauto.\n\n  rewrite HH3 in H10.\n  auto.\n\n\n  \nQed.\n\n\nLemma mem_overlap_PV:\n  forall s p v0 v P,\n    s |= PV p @ STRUCT os_tcb \u22c6 |-> v0 **\n      PV p @ STRUCT os_tcb \u22c6 |-> v  ** P ->\n    False.\nProof.\n  intros.\n  assert (p <> p).\n(* ** ac:   Check pv_false. *)\n  eapply pv_false.\n  3: eauto.\n  unfold array_struct.\n  intro.\n  destruct H0; simpljoin; tryfalse.\n  destruct H0; simpljoin; tryfalse.\n\n  unfold array_struct.\n  intro.\n  destruct H0; simpljoin; tryfalse.\n  destruct H0; simpljoin; tryfalse.\n  apply H0; auto.\nQed.\n\n\nLemma mem_overlap_struct:\n  forall s v1 v2 p P,\n    s |= Astruct p OS_TCB_flag v1 ** Astruct p OS_TCB_flag v2 ** P ->\n    False.\nProof.\n  intros.\n  unfold Astruct in H.\n  unfold OS_TCB_flag in H.\n  unfold Astruct' in H.\n  destruct v1.\n  sep destroy H.\n  simpl in H0; tryfalse.\n  destruct p.\n  destruct v2.\n  sep destroy H.\n  simpl in H1; tryfalse.\n  sep normal in H.\n  sep lift 3%nat in H.\n  Set Printing Depth 999.\n(* ** ac:   Show. *)\n  remember (match v1 with\n              | nil => Afalse\n              | v :: vl' =>\n                PV (b, i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @\n                   STRUCT os_tcb \u22c6 |-> v **\n                   match vl' with\n                     | nil => Afalse\n                     | v0 :: vl'0 =>\n                       PV (b,\n                           (i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                           $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @ \n                          OS_EVENT \u2217 |-> v0 **\n                          match vl'0 with\n                            | nil => Afalse\n                            | v1 :: vl'1 =>\n                              PV (b,\n                                  ((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                   $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                            $ Z.of_nat (typelen OS_EVENT \u2217)) @ \n                                 (Void) \u2217 |-> v1 **\n                                 match vl'1 with\n                                   | nil => Afalse\n                                   | v2 :: vl'2 =>\n                                     PV (b,\n                                         (((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                           +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                        $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                            $ Z.of_nat (typelen (Void) \u2217)) @ \n                                        Int16u |-> v2 **\n                                        match vl'2 with\n                                          | nil => Afalse\n                                          | v3 :: vl'3 =>\n                                            PV (b,\n                                                ((((i +\u1d62\n                                                         $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                                           $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                                                                               $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                                                                                                                                                 $ Z.of_nat (typelen Int16u)) @ \n                                               Int8u |-> v3 **\n                                               match vl'3 with\n                                                 | nil => Afalse\n                                                 | v4 :: vl'4 =>\n                                                   PV (b,\n                                                       (((((i +\u1d62\n                                                                 $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                           +\u1d62\n                                                              $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                          +\u1d62  $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                         +\u1d62  $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                               $ Z.of_nat (typelen Int16u)) +\u1d62\n                                                                                                                               $ Z.of_nat (typelen Int8u)) @ \n                                                      Int8u |-> v4 **\n                                                      match vl'4 with\n                                                        | nil => Afalse\n                                                        | v5 :: vl'5 =>\n                                                          PV (b,\n                                                              ((((((i +\u1d62\n                                                                         $\n                                                                         Z.of_nat\n                                                                         (typelen STRUCT os_tcb \u22c6))\n                                                                   +\u1d62\n                                                                      $\n                                                                      Z.of_nat\n                                                                      (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                    $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                                 +\u1d62  $ Z.of_nat (typelen (Void) \u2217))\n                                                                +\u1d62  $ Z.of_nat (typelen Int16u))\n                                                               +\u1d62  $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                  $ Z.of_nat (typelen Int8u)) @ \n                                                             Int8u |-> v5 **\n                                                             match vl'5 with\n                                                               | nil => Afalse\n                                                               | v6 :: vl'6 =>\n                                                                 PV (b,\n                                                                     (((((((i +\u1d62\n                                                                                 $\n                                                                                 Z.of_nat\n                                                                                 (typelen STRUCT os_tcb \u22c6))\n                                                                           +\u1d62\n                                                                              $\n                                                                              Z.of_nat\n                                                                              (typelen STRUCT os_tcb \u22c6))\n                                                                          +\u1d62\n                                                                             $\n                                                                             Z.of_nat\n                                                                             (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                      $ Z.of_nat (typelen (Void) \u2217))\n                                                                        +\u1d62\n                                                                           $ Z.of_nat (typelen Int16u))\n                                                                       +\u1d62  \n                                                                          $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                         $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                                                        $ Z.of_nat (typelen Int8u)) @\n                                                                    Int8u |-> v6 **\n                                                                    match vl'6 with\n                                                                      | nil => Afalse\n                                                                      | v7 :: vl'7 =>\n                                                                        PV (b,\n                                                                            ((((((((i +\u1d62\n                                                                                         $\n                                                                                         Z.of_nat\n                                                                                         (typelen STRUCT os_tcb \u22c6))\n                                                                                   +\u1d62\n                                                                                      $\n                                                                                      Z.of_nat\n                                                                                      (typelen STRUCT os_tcb \u22c6))\n                                                                                  +\u1d62\n                                                                                     $\n                                                                                     Z.of_nat\n                                                                                     (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                              $\n                                                                                                              Z.of_nat (typelen (Void) \u2217))\n                                                                                +\u1d62\n                                                                                   $ Z.of_nat (typelen Int16u))\n                                                                               +\u1d62\n                                                                                  $ Z.of_nat (typelen Int8u))\n                                                                              +\u1d62\n                                                                                 $ Z.of_nat (typelen Int8u))\n                                                                             +\u1d62\n                                                                                $ Z.of_nat (typelen Int8u))\n                                                                            +\u1d62\n                                                                               $ Z.of_nat (typelen Int8u)) @\n                                                                           Int8u |-> v7 **\n                                                                           match vl'7 with\n                                                                             | nil => Afalse\n                                                                             | v8 :: vl'8 =>\n                                                                               PV \n                                                                                 (b,\n                                                                                  (((((((((i +\u1d62\n                                                                                                $\n                                                                                                Z.of_nat\n                                                                                                (typelen STRUCT os_tcb \u22c6))\n                                                                                          +\u1d62\n                                                                                             $\n                                                                                             Z.of_nat\n                                                                                             (typelen STRUCT os_tcb \u22c6))\n                                                                                         +\u1d62\n                                                                                            $\n                                                                                            Z.of_nat\n                                                                                            (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                     $\n                                                                                                                     Z.of_nat (typelen (Void) \u2217))\n                                                                                       +\u1d62\n                                                                                          $ Z.of_nat (typelen Int16u))\n                                                                                      +\u1d62\n                                                                                         $ Z.of_nat (typelen Int8u))\n                                                                                     +\u1d62\n                                                                                        $ Z.of_nat (typelen Int8u))\n                                                                                    +\u1d62\n                                                                                       $ Z.of_nat (typelen Int8u))\n                                                                                   +\u1d62\n                                                                                      $ Z.of_nat (typelen Int8u))\n                                                                                  +\u1d62\n                                                                                     $ Z.of_nat (typelen Int8u)) @\n                                                                                 Int8u |-> v8 **\n                                                                                 match vl'8 with\n                                                                                   | nil => Aemp\n                                                                                   | _ :: _ => Afalse\n                                                                                 end\n                                                                           end\n                                                                    end\n                                                             end\n                                                      end\n                                               end\n                                        end\n                                 end\n                          end\n                   end\n            end). \n  remember (\n      match v2 with\n        | nil => Afalse\n        | v :: vl' =>\n          PV (b, i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @\n             STRUCT os_tcb \u22c6 |-> v **\n             match vl' with\n               | nil => Afalse\n               | v0 :: vl'0 =>\n                 PV (b,\n                     (i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                     $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) @ \n                    OS_EVENT \u2217 |-> v0 **\n                    match vl'0 with\n                      | nil => Afalse\n                      | v1 :: vl'1 =>\n                        PV (b,\n                            ((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                             $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                      $ Z.of_nat (typelen OS_EVENT \u2217)) @ \n                           (Void) \u2217 |-> v1 **\n                           match vl'1 with\n                             | nil => Afalse\n                             | v2 :: vl'2 =>\n                               PV (b,\n                                   (((i +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                     +\u1d62  $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                  $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                      $ Z.of_nat (typelen (Void) \u2217)) @ \n                                  Int16u |-> v2 **\n                                  match vl'2 with\n                                    | nil => Afalse\n                                    | v3 :: vl'3 =>\n                                      PV (b,\n                                          ((((i +\u1d62\n                                                   $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                            $ Z.of_nat (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                                                                     $ Z.of_nat (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                                                                                         $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                                                                                                                                           $ Z.of_nat (typelen Int16u)) @ \n                                         Int8u |-> v3 **\n                                         match vl'3 with\n                                           | nil => Afalse\n                                           | v4 :: vl'4 =>\n                                             PV (b,\n                                                 (((((i +\u1d62\n                                                           $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                     +\u1d62\n                                                        $ Z.of_nat (typelen STRUCT os_tcb \u22c6))\n                                                    +\u1d62  $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                   +\u1d62  $ Z.of_nat (typelen (Void) \u2217)) +\u1d62\n                                                                                         $ Z.of_nat (typelen Int16u)) +\u1d62\n                                                                                                                         $ Z.of_nat (typelen Int8u)) @ \n                                                Int8u |-> v4 **\n                                                match vl'4 with\n                                                  | nil => Afalse\n                                                  | v5 :: vl'5 =>\n                                                    PV (b,\n                                                        ((((((i +\u1d62\n                                                                   $\n                                                                   Z.of_nat\n                                                                   (typelen STRUCT os_tcb \u22c6))\n                                                             +\u1d62\n                                                                $\n                                                                Z.of_nat\n                                                                (typelen STRUCT os_tcb \u22c6)) +\u1d62\n                                                                                              $ Z.of_nat (typelen OS_EVENT \u2217))\n                                                           +\u1d62  $ Z.of_nat (typelen (Void) \u2217))\n                                                          +\u1d62  $ Z.of_nat (typelen Int16u))\n                                                         +\u1d62  $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                            $ Z.of_nat (typelen Int8u)) @ \n                                                       Int8u |-> v5 **\n                                                       match vl'5 with\n                                                         | nil => Afalse\n                                                         | v6 :: vl'6 =>\n                                                           PV (b,\n                                                               (((((((i +\u1d62\n                                                                           $\n                                                                           Z.of_nat\n                                                                           (typelen STRUCT os_tcb \u22c6))\n                                                                     +\u1d62\n                                                                        $\n                                                                        Z.of_nat\n                                                                        (typelen STRUCT os_tcb \u22c6))\n                                                                    +\u1d62\n                                                                       $\n                                                                       Z.of_nat\n                                                                       (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                $ Z.of_nat (typelen (Void) \u2217))\n                                                                  +\u1d62\n                                                                     $ Z.of_nat (typelen Int16u))\n                                                                 +\u1d62  \n                                                                    $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                   $ Z.of_nat (typelen Int8u)) +\u1d62\n                                                                                                                                  $ Z.of_nat (typelen Int8u)) @\n                                                              Int8u |-> v6 **\n                                                              match vl'6 with\n                                                                | nil => Afalse\n                                                                | v7 :: vl'7 =>\n                                                                  PV (b,\n                                                                      ((((((((i +\u1d62\n                                                                                   $\n                                                                                   Z.of_nat\n                                                                                   (typelen STRUCT os_tcb \u22c6))\n                                                                             +\u1d62\n                                                                                $\n                                                                                Z.of_nat\n                                                                                (typelen STRUCT os_tcb \u22c6))\n                                                                            +\u1d62\n                                                                               $\n                                                                               Z.of_nat\n                                                                               (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                        $\n                                                                                                        Z.of_nat (typelen (Void) \u2217))\n                                                                          +\u1d62\n                                                                             $ Z.of_nat (typelen Int16u))\n                                                                         +\u1d62\n                                                                            $ Z.of_nat (typelen Int8u))\n                                                                        +\u1d62\n                                                                           $ Z.of_nat (typelen Int8u))\n                                                                       +\u1d62\n                                                                          $ Z.of_nat (typelen Int8u))\n                                                                      +\u1d62\n                                                                         $ Z.of_nat (typelen Int8u)) @\n                                                                     Int8u |-> v7 **\n                                                                     match vl'7 with\n                                                                       | nil => Afalse\n                                                                       | v8 :: vl'8 =>\n                                                                         PV \n                                                                           (b,\n                                                                            (((((((((i +\u1d62\n                                                                                          $\n                                                                                          Z.of_nat\n                                                                                          (typelen STRUCT os_tcb \u22c6))\n                                                                                    +\u1d62\n                                                                                       $\n                                                                                       Z.of_nat\n                                                                                       (typelen STRUCT os_tcb \u22c6))\n                                                                                   +\u1d62\n                                                                                      $\n                                                                                      Z.of_nat\n                                                                                      (typelen OS_EVENT \u2217)) +\u1d62\n                                                                                                               $\n                                                                                                               Z.of_nat (typelen (Void) \u2217))\n                                                                                 +\u1d62\n                                                                                    $ Z.of_nat (typelen Int16u))\n                                                                                +\u1d62\n                                                                                   $ Z.of_nat (typelen Int8u))\n                                                                               +\u1d62\n                                                                                  $ Z.of_nat (typelen Int8u))\n                                                                              +\u1d62\n                                                                                 $ Z.of_nat (typelen Int8u))\n                                                                             +\u1d62\n                                                                                $ Z.of_nat (typelen Int8u))\n                                                                            +\u1d62\n                                                                               $ Z.of_nat (typelen Int8u)) @\n                                                                           Int8u |-> v8 **\n                                                                           match vl'8 with\n                                                                             | nil => Aemp\n                                                                             | _ :: _ => Afalse\n                                                                           end\n                                                                     end\n                                                              end\n                                                       end\n                                                end\n                                         end\n                                  end\n                           end\n                    end\n             end\n      end ).\n  clear -H.\n  eapply mem_overlap_PV.\n  instantiate (6:=s).\n  sep cancel 1%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  eauto.\nQed.\n\nLemma sometcblist_lemma:\n  forall v v'22 s ptr vv a0 a2 a3 v'26 P a1, \n    s|= node (Vptr ptr) vv OS_TCB_flag ** tcbdllseg a0 a1 a2 a3 v ** P ->\n    TCBList_P a0 v v'26 v'22 ->\n    ~ TcbMod.indom v'22 ptr.\nProof.\n  induction v.\n  intros.\n  simpl in H0.\n  subst.\n  intro.\n  unfolds in H0.\n  inverts H0.\n  inverts H1.\n  intros.\n  lets back: H0.\n  unfold1 TCBList_P in H0.\n  simpljoin.\n  unfold tcbdllseg in H.\n  unfold1 dllseg in H.\n  sep normal in  H.\n  sep destruct H.\n  sep split in H.\n  assert (~ TcbMod.indom x1 ptr).\n  eapply IHv.\n  instantiate (7 := s).\n  sep cancel 3%nat 1%nat.\n  unfold tcbdllseg.\n  sep cancel 2%nat 1%nat.\n  eauto.\n  rewrite H1 in H0.\n  inverts H0.\n  eauto.\n  assert ( x <> ptr).\n  intro.\n  sep lift 3%nat in H.\n  unfold node in H.\n  sep normal in H.\n  sep destruct H.\n  sep split in H.\n  subst x.\n  simpljoin.\n  inverts H10.\n  inverts H8.\n  \n  eapply mem_overlap_struct.\n  eauto.\n  intro.\n  unfolds in H9.\n  simpljoin.\n  unfolds in H2.\n  \n  eapply TcbMod.join_get_or in H9.\n  2: exact H2.\n  destruct H9.\n  unfold sig in H9; simpl in H9.\n  rewrite TcbMod.get_a_sig_a' in H9.\n  inverts H9.\n  go.\n  apply H7.\n  eexists.\n  eauto.\nQed.\nLemma not_in_priotbl_no_priotcb:\n  forall v'28 v'14 v'43 v'42,\n    R_PrioTbl_P v'28 v'14 v'43 ->\n    Int.unsigned v'42 < 64 ->\n    nth_val' (Z.to_nat (Int.unsigned v'42)) v'28 = Vnull ->\n    ~ (exists id t m, get v'14 id = Some (v'42, t, m)).\nProof.\n  intros.\n  unfolds in H.\n  simpljoin.\n  intro.\n  simpljoin.\n  lets bb: H2 H4. \n  simpljoin.\n  apply nv'2nv in H1.\n  unfold nat_of_Z in H5.\n  rewrite H1 in H5.\n  inverts H5.\n  intro; tryfalse.\nQed.\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/task/taskcreate_pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2942149845400438, "lm_q1q2_score": 0.15055469294191973}}
{"text": "Require Crypto.Assembly.Parse.\nRequire Import Coq.Program.Tactics.\nRequire Import Coq.derive.Derive.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import Coq.FSets.FMapFacts.\nRequire Crypto.Util.Tuple.\nRequire Import Util.OptionList.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.ZUtil.Testbit.\nRequire Import Crypto.Util.ZUtil.Hints.ZArith.\nRequire Import Crypto.Util.ZUtil.Land.\nRequire Import Crypto.Util.ZUtil.Ones.\nRequire Import Crypto.Util.Equality.\nRequire Import Crypto.Util.Bool.Reflect.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Strings.Subscript.\nRequire Import Crypto.Util.Structures.Orders.\nRequire Import Crypto.Util.Structures.Equalities.\nRequire Import Crypto.Util.Structures.Equalities.Iso.\nRequire Import Crypto.Util.Structures.Equalities.Prod.\nRequire Import Crypto.Util.Structures.Equalities.Option.\nRequire Import Crypto.Util.Structures.Orders.Iso.\nRequire Import Crypto.Util.Structures.Orders.Prod.\nRequire Import Crypto.Util.Structures.Orders.Option.\nRequire Import Crypto.Util.Structures.OrdersEx.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.Concat.\nRequire Import Crypto.Util.ListUtil.GroupAllBy.\nRequire Import Crypto.Util.ListUtil.FoldMap. Import FoldMap.List.\nRequire Import Crypto.Util.ListUtil.IndexOf. Import IndexOf.List.\nRequire Import Crypto.Util.ListUtil.Forall.\nRequire Import Crypto.Util.ListUtil.Permutation.\nRequire Import Crypto.Util.ListUtil.Partition.\nRequire Import Crypto.Util.ListUtil.Filter.\nRequire Import Crypto.Util.ListUtil.PermutationCompat. Import ListUtil.PermutationCompat.Coq.Sorting.Permutation.\nRequire Import Crypto.Util.NUtil.Sorting.\nRequire Import Crypto.Util.NUtil.Testbit.\nRequire Import Crypto.Util.FSets.FMapOption.\nRequire Import Crypto.Util.FSets.FMapN.\nRequire Import Crypto.Util.FSets.FMapZ.\nRequire Import Crypto.Util.FSets.FMapProd.\nRequire Import Crypto.Util.FSets.FMapIso.\nRequire Import Crypto.Util.FSets.FMapSect.\nRequire Import Crypto.Util.FSets.FMapInterface.\nRequire Import Crypto.Util.FSets.FMapFacts.\nRequire Import Crypto.Util.FSets.FMapTrieEx.\nRequire Import Crypto.Util.MSets.MSetN.\nRequire Import Crypto.Util.ListUtil.PermutationCompat.\nRequire Import Crypto.Util.Bool.LeCompat.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SetEvars.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.SpecializeAllWays.\nRequire Import Crypto.Util.Tactics.SpecializeUnderBindersBy.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.ZUtil.Lxor.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.Tactics.WarnIfGoalsRemain.\nRequire Import Crypto.Util.Bool.Reflect.\nRequire Import coqutil.Z.bitblast.\nRequire Import Coq.Strings.String Crypto.Util.Strings.Show.\nRequire Import Crypto.Assembly.Syntax.\nImport ListNotations.\nDefinition idx := N.\nLocal Set Decidable Equality Schemes.\nDefinition symbol := N.\n\nClass OperationSize := operation_size : N.\nGlobal Instance Show_OperationSize : Show OperationSize := show_N.\n\nSection S.\nImplicit Type s : OperationSize.\nVariant op := old s (_:symbol) | const (_ : Z) | add s | addcarry s | subborrow s | addoverflow s | neg s | shl s | shr s | sar s | rcr s | and s | or s | xor s | slice (lo sz : N) | mul s | set_slice (lo sz : N) | selectznz | iszero (* | ... *)\n  | addZ | mulZ | negZ | shlZ | shrZ | andZ | orZ | xorZ | addcarryZ s | subborrowZ s.\nDefinition op_beq a b := if op_eq_dec a b then true else false.\nEnd S.\n\nGlobal Instance Show_op : Show op := fun o =>\n  match o with\n  | old s n => \"old \" ++ show s ++ \" \" ++ show n\n  | const n => \"const \" ++ show n\n  | add s => \"add \" ++ show s\n  | addcarry s => \"addcarry \" ++ show s\n  | subborrow s => \"subborrow \" ++ show s\n  | addoverflow s => \"addoverflow \" ++ show s\n  | neg s => \"neg \" ++ show s\n  | shl s => \"shl \" ++ show s\n  | shr s => \"shr \" ++ show s\n  | sar s => \"sar \" ++ show s\n  | rcr s => \"rcr \" ++ show s\n  | and s => \"and \" ++ show s\n  | or s => \"or \" ++ show s\n  | xor s => \"xor \" ++ show s\n  | slice lo sz => \"slice \" ++ show lo ++ \" \" ++ show sz\n  | mul s => \"mul \" ++ show s\n  | set_slice lo sz => \"set_slice \" ++ show lo ++ \" \" ++ show sz\n  | selectznz => \"selectznz\"\n  | iszero => \"iszero\"\n  | addZ => \"addZ\"\n  | mulZ => \"mulZ\"\n  | negZ => \"negZ\"\n  | shlZ => \"shlZ\"\n  | shrZ => \"shrZ\"\n  | andZ => \"andZ\"\n  | orZ => \"orZ\"\n  | xorZ => \"xorZ\"\n  | addcarryZ s => \"addcarryZ \" ++ show s\n  | subborrowZ s => \"subborrowZ \" ++ show s\n  end%string.\n\nDefinition show_op_subscript : Show op := fun o =>\n  match o with\n  | old s n => \"old\" ++ String.to_subscript (show s) ++ \" \" ++ show n\n  | const n => \"const \" ++ show n\n  | add s => \"add\" ++ String.to_subscript (show s)\n  | addcarry s => \"addcarry\" ++ String.to_subscript (show s)\n  | subborrow s => \"subborrow\" ++ String.to_subscript (show s)\n  | addoverflow s => \"addoverflow\" ++ String.to_subscript (show s)\n  | neg s => \"neg\" ++ String.to_subscript (show s)\n  | shl s => \"shl\" ++ String.to_subscript (show s)\n  | shr s => \"shr\" ++ String.to_subscript (show s)\n  | sar s => \"sar\" ++ String.to_subscript (show s)\n  | rcr s => \"rcr\" ++ String.to_subscript (show s)\n  | and s => \"and\" ++ String.to_subscript (show s)\n  | or s => \"or\" ++ String.to_subscript (show s)\n  | xor s => \"xor\" ++ String.to_subscript (show s)\n  | slice lo sz => \"slice\" ++ String.to_subscript (show lo) ++ \",\" ++ String.to_subscript (show sz)\n  | mul s => \"mul\" ++ String.to_subscript (show s)\n  | set_slice lo sz => \"set_slice\" ++ String.to_subscript (show lo) ++ \",\" ++ String.to_subscript (show sz)\n  | selectznz => \"selectznz\"\n  | iszero => \"iszero\"\n  | addZ => \"add\u2124\"\n  | mulZ => \"mul\u2124\"\n  | negZ => \"neg\u2124\"\n  | shlZ => \"shl\u2124\"\n  | shrZ => \"shr\u2124\"\n  | andZ => \"and\u2124\"\n  | orZ => \"or\u2124\"\n  | xorZ => \"xor\u2124\"\n  | addcarryZ s => \"addcarry\u2124\" ++ String.to_subscript (show s)\n  | subborrowZ s => \"subborrow\u2124\" ++ String.to_subscript (show s)\n  end%string.\n\nModule FMapOp.\n  Definition op_args : Set := (option OperationSize * (option symbol * (option Z * (option N * option N)))).\n  Definition op' : Set := N * op_args.\n  Definition eta_op_cps {T} (k : op -> T) (o : op) : T.\n  Proof.\n    pose o as o'.\n    destruct o.\n    all: let v := (eval cbv [o'] in o') in\n         exact (k v).\n  Defined.\n\n  Definition nat_of_op (o : op) : nat.\n  Proof.\n    evar (base : nat).\n    destruct o.\n    all: let rec peel_S val :=\n           lazymatch val with\n           | S ?val => apply S; peel_S val\n           | ?ev => is_evar ev;\n                    let __ := open_constr:(eq_refl : ev = S _) in\n                    exact O\n           end in\n         let v := (eval cbv [base] in base) in\n         peel_S v.\n    Unshelve.\n    exact O.\n  Defined.\n\n  Definition args_of_op (o : op) : op_args.\n  Proof.\n    destruct o; hnf.\n    all: repeat lazymatch reverse goal with\n                | [ H : ?T |- ?A * ?B ]\n                  => lazymatch A with\n                     | context[option T]\n                       => split; [ | clear H ]\n                     | _ => split; [ repeat apply pair; exact None | ]\n                     end\n                | [ H : ?T |- _ ]\n                  => lazymatch goal with\n                     | [ |- option T ] => exact (Some H)\n                     | [ |- _ ] => idtac \"bad\"\n                     end\n                | [ |- _ * _ ] => split\n                | [ |- option _ ] => exact None\n                end.\n  Defined.\n\n  Definition op'_of_op : op -> op'\n    := Eval compute in eta_op_cps (fun o => (N.of_nat (nat_of_op o), args_of_op o)).\n\n  Derive op_of_op'_opt\n         SuchThat ((forall (o : op), op_of_op'_opt (op'_of_op o) = Some o)\n                   /\\ (forall (n n' : op'), option_map op'_of_op (op_of_op'_opt n) = Some n' -> n = n'))\n         As op_op'_correct.\n  Proof.\n    instantiate (1:=ltac:(intros [n v]; hnf in v; destruct_head'_prod; destruct n as [|n])) in (value of op_of_op'_opt).\n    subst op_of_op'_opt.\n    split.\n    { intro o; destruct o; cbv [op'_of_op].\n      all: [ > cbv beta iota;\n             lazymatch goal with\n             | [ |- ?ev = Some _ ]\n               => is_evar ev;\n                  let H := fresh in\n                  pose ev as H;\n                  instantiate (1:=ltac:(lazymatch goal with\n                                        | [ n : positive |- _ ]\n                                          => destruct n\n                                        | _ => idtac\n                                        end)) in (value of H);\n                  subst H; cbv beta iota\n             end .. ].\n      all: lazymatch goal with\n           | [ |- ?ev = Some ?v ]\n             => is_evar ev;\n                let h := head v in\n                let H := fresh in\n                pose ev as H;\n                instantiate (1:=ltac:(reverse)) in (value of H);\n                subst H;\n                repeat match goal with\n                       | [ |- context[?ev ?x] ]\n                         => is_evar ev;\n                            let H := fresh in\n                            pose ev as H;\n                            lazymatch x with\n                            | Some _\n                              => instantiate (1:=ltac:(let x := fresh \"x\" in intro x; intros; destruct x; [ reverse | exact None ])) in (value of H)\n                            | None\n                              => instantiate (1:=ltac:(let x := fresh \"x\" in intro x; intros; destruct x; [ exact None | reverse ])) in (value of H)\n                            | ?x\n                              => tryif is_var x\n                                then instantiate (1:=ltac:(intro)) in (value of H)\n                                else idtac \"unknown\" x\n                            end;\n                            subst H; cbv beta iota\n                       end;\n                reflexivity\n           end. }\n    { intros [n nargs] [n' nargs'].\n      set (f := option_map _).\n      break_innermost_match.\n      all: let G := lazymatch goal with |- ?G => G end in\n           tryif has_evar G then instantiate (1:=None) else idtac.\n      all: vm_compute.\n      all: lazymatch goal with\n           | [ |- Some _ = Some _ -> _ ] => intro; inversion_option; inversion_pair; subst; try reflexivity\n           | [ |- None = Some _ -> _ ] => let H := fresh in intro H; exfalso; clear -H; inversion_option\n           end. }\n  Qed.\n\n  Module OptionNMap <: S := OptionUsualMap NMap.\n  Module OptionZMap <: S := OptionUsualMap ZMap.\n  Module OptionSymbolMap <: S := OptionNMap.\n  Module OptionOperationSizeMap <: S := OptionNMap.\n  Module OpArgsMap0 <: S := OptionNMap.\n  Module OpArgsMap1 <: S := ProdUsualMap OptionNMap OpArgsMap0.\n  Module OpArgsMap2 <: S := ProdUsualMap OptionZMap OpArgsMap1.\n  Module OpArgsMap3 <: S := ProdUsualMap OptionSymbolMap OpArgsMap2.\n  Module OpArgsMap4 <: S := ProdUsualMap OptionOperationSizeMap OpArgsMap3.\n  Module OpArgsMap <: S := OpArgsMap4.\n  Module OpMap' <: S := ProdUsualMap NMap OpArgsMap.\n  Module OpSectOp' <: SectMiniOrderedType OpMap'.E.\n    Definition t := op.\n    Include HasUsualEq.\n    Include UsualIsEq.\n    Include UsualIsEqOrig.\n    Definition to_ : t -> OpMap'.E.t := Eval vm_compute in op'_of_op.\n    Definition of_ (v : OpMap'.E.t) : t\n      := Eval vm_compute in match op_of_op'_opt v with\n                            | Some v => v\n                            | None => old 0%N 0%N\n                            end.\n    Global Instance Proper_to_ : Proper (Logic.eq ==> Logic.eq) to_ | 5.\n    Proof. repeat intro; subst; reflexivity. Qed.\n    Global Instance Proper_of_ : Proper (Logic.eq ==> Logic.eq) of_ | 5.\n    Proof. repeat intro; subst; reflexivity. Qed.\n    Lemma of_to : forall x, eq (of_ (to_ x)) x.\n    Proof.\n      intro x.\n      refine (_ : match op_of_op'_opt (op'_of_op x) with\n                  | Some v => v\n                  | None => _\n                  end = x).\n      rewrite (proj1 op_op'_correct).\n      reflexivity.\n    Qed.\n    Include LiftIsoHasLt OpMap'.E.\n    Include LiftSectHasMiniOrderedType OpMap'.E.\n    Include LiftSectIsLt OpMap'.E.\n  End OpSectOp'.\n  Module OpMap <: UsualS := SectS OpMap' OpSectOp'.\nEnd FMapOp.\n\nModule OpMap := FMapOp.OpMap.\n\nDefinition associative o := match o with add _|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ=> true | _ => false end.\nDefinition commutative o := match o with add _|addcarry _|addoverflow _|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ => true | _ => false end.\nDefinition identity o := match o with mul N0 => Some 0%Z| mul _|mulZ=>Some 1%Z |add _|addZ|or _|orZ|xor _|xorZ|addcarry _|addcarryZ _|addoverflow _ => Some 0%Z | and s => Some (Z.ones (Z.of_N s))|andZ => Some (-1)%Z |_=> None end.\n(* identity, but not in the first slot *)\nDefinition identity_after_0 o := match o with subborrow _|subborrowZ _ => Some 0%Z | _=> None end.\nDefinition unary_truncate_size o := match o with add s|and s|or s|xor s|mul s => Some (Z.of_N s) | addZ|mulZ|andZ|orZ|xorZ => Some (-1)%Z | _ => None end.\nDefinition op_always_interps o := match o with add _|addcarry _|addoverflow _|and _|or _|xor _|mul _|addZ|mulZ|andZ|orZ|xorZ|addcarryZ _ => true | _ => false end.\nDefinition combines_to o := match o with add s => Some (mul s) | addZ => Some mulZ | _ => None end.\n\nDefinition node (A : Set) : Set := op * list A.\nGlobal Instance Show_node {A : Set} {show_A : Show A} : Show (node A) := show_prod.\n\nLocal Unset Elimination Schemes.\nInductive expr : Set :=\n| ExprRef (_ : idx)\n| ExprApp (_ : node expr).\nLocal Set Elimination Schemes.\nSection expr_ind.\n  Context (P : expr -> Prop)\n    (HRef : forall i, P (ExprRef i))\n    (HApp : forall n, Forall P (snd n) -> P (ExprApp n)).\n  Fixpoint expr_ind e {struct e} : P e :=\n    match e with\n    | ExprRef i => HRef i\n    | ExprApp n => HApp _ (list_rect _ (Forall_nil _) (fun e _ H => Forall_cons e (expr_ind e) H) (snd n))\n    end.\nEnd expr_ind.\nDefinition invert_ExprRef (e : expr) : option idx :=\n  match e with ExprRef i => Some i | _ => None end.\nDefinition Show_expr_body (Show_expr : Show expr) : Show expr\n  := Eval cbv -[String.append show_N concat List.map Show_op] in\n      fun e => match e with\n               | ExprRef i => \"ExprRef \" ++ show i\n               | ExprApp (o, e) => \"ExprApp \" ++ show (o, e)\n               end%string.\nDefinition Show_expr : Show expr\n  := Eval cbv -[String.append show_N concat List.map Show_op] in\n      fix Show_expr e := Show_expr_body Show_expr e.\nGlobal Existing Instance Show_expr.\n\nLocal Notation max_powers_of_two := 5%nat (only parsing).\nLocal Notation max_decimal := 256%Z (only parsing).\n\nDefinition show_infix_op (o : op) : option string\n  := match o with\n     | add s => Some (\"+\" ++ String.to_subscript (show s))\n     | shl s => Some (\">>\" ++ String.to_subscript (show s))\n     | shr s => Some (\">>\" ++ String.to_subscript (show s))\n     | and s => Some (\"&\"  ++ String.to_subscript (show s))\n     | or s  => Some (\"|\"  ++ String.to_subscript (show s))\n     | xor s => Some (\"^\"  ++ String.to_subscript (show s))\n     | mul s => Some (\"*\"  ++ String.to_subscript (show s))\n     | sar s => Some (\">>>\" ++ String.to_subscript (show s))\n     | addZ  => Some \"+\u2124\"\n     | mulZ  => Some \"*\u2124\"\n     | shlZ  => Some \"<<\u2124\"\n     | shrZ  => Some \">>\u2124\"\n     | andZ  => Some \"&\u2124\"\n     | orZ   => Some \"|\u2124\"\n     | xorZ  => Some \"^\u2124\"\n     | _ => None\n     end%string.\n\nDefinition show_prefix_op (o : op) : option (string * Level)\n  := match o with\n     | neg s => Some (\"-\" ++ String.to_subscript (show s), opp_lvl)\n     | negZ => Some (\"-\u2124\", opp_lvl)\n     | _ => None\n     end%string.\n\nDefinition show_lvl_expr_pretty : ShowLevel expr\n  := fix show_lvl_pretty_expr (e : expr) : Level -> string\n    := let __ : ShowLevel expr := show_lvl_pretty_expr in\n       let __ : Show expr := @Show_of_ShowLevel _ show_lvl_pretty_expr in\n       let show_comment_args args\n         := match args with\n            | nil => \"\"\n            | _ => \" (* \" ++ show args ++ \" *)\"\n            end%string in\n       match e with\n       | ExprRef i => fun _ => \"#\" ++ show i\n       | ExprApp (old s x, args) => lvl_wrap_parens app_lvl (\"old\" ++ String.to_subscript (show s) ++ \" \" ++ show x ++ show_comment_args args)\n       | ExprApp (const x, args) => fun lvl => PowersOfTwo.show_lvl_Z_up_to max_powers_of_two max_decimal x lvl ++ show_comment_args args\n       | ExprApp ((add _|shl _|shr _|and _|or _|xor _|mul _|sar _|addZ|mulZ|shlZ|shrZ|andZ|orZ|xorZ) as o, args)\n         => let o : string := Option.invert_Some (show_infix_op o) in\n            match args with\n            | nil => fun _ => o ++ \"[]\"\n            | x :: nil => fun _ => o ++ \"[\" ++ show x ++ \"]\"\n            | _ => fun _ => \"(\" ++ String.concat (\" \" ++ o ++ \" \") (List.map show args) ++ \")\"\n            end\n       | ExprApp ((neg _|negZ) as o, args)\n         => let '(o, lvl) := Option.invert_Some (show_prefix_op o) in\n            match args with\n            | nil => fun _ => o ++ \"[]\"\n            | x :: nil => fun _ => o ++ show_lvl x lvl\n            | _ => fun _ => o ++ show args\n            end\n       | ExprApp (o, args)\n         => fun _ => \"(\" ++ show_op_subscript o ++ \", \" ++ show args ++ \")\"\n       end%string%list.\n\nDefinition show_expr_pretty : Show expr\n  := @Show_of_ShowLevel _ show_lvl_expr_pretty.\n\nLemma op_beq_spec a b : BoolSpec (a=b) (a<>b) (op_beq a b).\nProof using Type. cbv [op_beq]; destruct (op_eq_dec a b); constructor; congruence. Qed.\nGlobal Instance reflect_eq_op : reflect_rel eq op_beq | 10 := reflect_rel_of_BoolSpec op_beq_spec.\nFixpoint expr_beq (X Y : expr) {struct X} : bool :=\n  match X, Y with\n  | ExprRef x, ExprRef x0 => N.eqb x x0\n  | ExprApp x, ExprApp x0 =>\n      Prod.prod_beq _ _ op_beq (ListUtil.list_beq expr expr_beq) x x0\n  | _, _ => false\n  end.\nLemma expr_beq_spec a b : BoolSpec (a=b) (a<>b) (expr_beq a b).\nProof using Type.\n  revert b; induction a, b; cbn.\n  1: destruct (N.eqb_spec i i0); constructor; congruence.\n  1,2: constructor; congruence.\n  destruct n, n0; cbn.\n  destruct (op_beq_spec o o0); cbn in *; [subst|constructor; congruence].\n  revert l0; induction H, l0; cbn; try (constructor; congruence); [].\n  destruct (H e); cbn; try (constructor; congruence); []; subst.\n  destruct (IHForall l0); [left|right]; congruence.\nQed.\nGlobal Instance reflect_eq_expr : reflect_rel eq expr_beq | 10 := reflect_rel_of_BoolSpec expr_beq_spec.\nLemma expr_beq_true a b : expr_beq a b = true -> a = b.\nProof using Type. destruct (expr_beq_spec a b); congruence. Qed.\n\nRequire Import Crypto.Util.Option Crypto.Util.Notations Coq.Lists.List.\nImport ListNotations.\n\nSection WithContext.\n  Context (ctx : symbol -> option Z).\n  Definition signed s n : Z := (Z.land (Z.shiftl 1 (Z.of_N s-1) + n) (Z.ones (Z.of_N s)) - Z.shiftl 1 (Z.of_N s-1))%Z.\n  Definition interp_op o (args : list Z) : option Z :=\n    let keep n x := Z.land x (Z.ones (Z.of_N n)) in\n    match o, args with\n    | old s x, nil => match ctx x with Some v => Some (keep s v) | None => None end\n    | const z, nil => Some z\n    | add s, args => Some (keep s (List.fold_right Z.add 0 args))\n    | addcarry s, args =>\n        Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s) mod 2)\n    | subborrow s, cons a args' =>\n        Some ((- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s)) mod 2)\n    | addoverflow s, args => Some (Z.b2z (negb (Z.eqb\n      (signed s (keep s (List.fold_right Z.add 0 args)))\n                         (List.fold_right Z.add 0%Z (List.map (signed s) args)))))\n    | neg s, [a] => Some (keep s (- a))\n    | shl s, [a; b] => Some (keep s (Z.shiftl a b))\n    | shr s, [a; b] => Some (keep s (Z.shiftr a b))\n    | sar s, [a; b] => Some (keep s (Z.shiftr (signed s a) b))\n    | rcr s, [v1; cf; cnt] => Some (\n        let v1c := Z.lor v1 (Z.shiftl cf (Z.of_N s)) in\n        let l := Z.lor v1c (Z.shiftl v1 (1+Z.of_N s)) in\n        keep s (Z.shiftr l cnt))\n    | and s, args => Some (keep s (List.fold_right Z.land (-1) args))\n    | or s, args => Some (keep s (List.fold_right Z.lor 0 args))\n    | xor s, args => Some (keep s (List.fold_right Z.lxor 0 args))\n    | slice lo sz, [a] => Some (keep sz (Z.shiftr a (Z.of_N lo)))\n    | mul s, args => Some (keep s (List.fold_right Z.mul 1 args))\n    | set_slice lo sz, [a; b] =>\n        Some (Z.lor (Z.shiftl (keep sz b) (Z.of_N lo))\n                    (Z.ldiff a (Z.shiftl (Z.ones (Z.of_N sz)) (Z.of_N lo))))\n    | selectznz, [c; a; b] => Some (if Z.eqb c 0 then a else b)\n    | iszero, [a] => Some (Z.b2z (Z.eqb a 0))\n    | addZ, args => Some (List.fold_right Z.add 0 args)\n    | mulZ, args => Some (List.fold_right Z.mul 1 args)\n    | negZ, [a] => Some (Z.opp a)\n    | shlZ, [a; b] => Some (Z.shiftl a b)\n    | shrZ, [a; b] => Some (Z.shiftr a b)\n    | andZ, args => Some (List.fold_right Z.land (-1) args)\n    | orZ, args => Some (List.fold_right Z.lor 0 args)\n    | xorZ, args => Some (List.fold_right Z.lxor 0 args)\n    | addcarryZ s, args => Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s))\n    | subborrowZ s, cons a args' => Some (- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s))\n    | _, _ => None\n    end%Z.\nEnd WithContext.\nDefinition interp0_op := interp_op (fun _ => None).\n\nLemma interp_op_weaken_symbols G1 G2 o args\n  (H : forall (s:symbol) v, G1 s = Some v -> G2 s = Some v)\n  : forall v, interp_op G1 o args = Some v -> interp_op G2 o args = Some v.\nProof using Type.\n  cbv [interp_op option_map]; intros;\n    repeat (BreakMatch.break_match || BreakMatch.break_match_hyps);\n    inversion_option; subst;\n    try congruence.\n  all : eapply H in Heqo0; congruence.\nQed.\n\nLemma interp_op_interp0_op o a v (H : interp0_op o a = Some v)\n  : forall G, interp_op G o a = Some v.\nProof using Type. intros; eapply interp_op_weaken_symbols in H; try eassumption; discriminate. Qed.\n\nDefinition node_beq {A : Set} (arg_eqb : A -> A -> bool) : node A -> node A -> bool :=\n  Prod.prod_beq _ _ op_beq (ListUtil.list_beq _ arg_eqb).\nGlobal Instance reflect_node_beq {A : Set} {arg_eqb} {H : reflect_rel (@eq A) arg_eqb}\n  : reflect_rel eq (@node_beq A arg_eqb) | 10 := _.\n\nClass description := descr : option ((unit -> string) * bool (* always show *)).\nTypeclasses Opaque description.\nDefinition eager_description := option (string * bool).\nNotation Build_description descr always_show := (Some (fun 'tt => descr, always_show)) (only parsing).\nNotation no_description := None (only parsing).\n\n(* fresh symbols must have value <= their index, so that fresh symbols are truly fresh *)\nDefinition node_ok (i : idx) (n : node idx) := forall w s args, n = (old w s, args) -> (s <= i)%N.\nLemma new_node_ok n (pf : match n with (old _ _, _) => False | _ => True end) i : node_ok i n.\nProof. repeat intro; subst; assumption. Qed.\nExisting Class node_ok.\nHint Extern 1 (node_ok ?i ?n) => exact (@new_node_ok n I i) : typeclass_instances.\nModule Old.\nModule dag.\n  Definition t : Type := list (node idx * description).\n  Definition empty : t := nil.\n  Definition size (d : t) : N := N.of_nat (List.length d).\n  Definition lookup (d : t) (i : idx) : option (node idx)\n    := option_map fst (List.nth_error d (N.to_nat i)).\n  Definition reverse_lookup (d : t) (i : node idx) : option idx\n    := option_map N.of_nat (List.indexof (fun '(n', _) => node_beq N.eqb i n') d).\n  Definition size_ok (d : t) : Prop\n    := True.\n  Definition all_nodes_ok (d : t) : Prop\n    := forall i r, lookup d i = Some r -> node_ok i r.\n  Definition ok (d : t) : Prop\n  := size_ok d\n     /\\ (forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n)\n     /\\ (forall i n, lookup d i = Some n -> (i < size d)%N).\n  Definition merge_node {descr : description} (n : node idx) (d : t) : idx * t\n    := match reverse_lookup d n with\n       | Some i => (i, d)\n       | None\n         => (size d, d ++ [(n, descr)])\n       end.\n  Definition gensym (s:OperationSize) (d : t) : node idx\n    := (old s (size d), []).\n  Existing Class ok.\n  Existing Class all_nodes_ok.\n\n  Definition get_eager_description_description (d : eager_description) : option string\n    := option_map fst d.\n  Definition get_eager_description_always_show (d : eager_description) : bool\n    := match d with Some (_, always_show) => always_show | None => false end.\n  Definition force_description : description -> eager_description\n    := option_map (fun '(descr, always_show) => (descr tt, always_show)).\n\n  Module eager.\n    Definition t := list (idx * node idx * eager_description).\n    Definition force (d : dag.t) : eager.t\n      := List.map (fun '(idx, (n, descr)) => (N.of_nat idx, n, force_description descr))\n                  (List.enumerate d).\n    Definition description_lookup (d : eager.t) (descr : string) : list idx\n      := List.map (fun '(idx, _, _) => idx) (List.filter (fun '(_, _, descr') => match get_eager_description_description descr' with Some descr' => String.eqb descr descr' | _ => false end) d).\n  End eager.\n\n  Definition M T := t -> T * t.\n  Definition bind {A B} (v : M A) (f : A -> M B) : M B\n    := fun d => let '(v, d) := v d in f v d.\n  Definition ret {A} (v : A) : M A\n    := fun d => (v, d).\n\n  Lemma iff_reverse_lookup_lookup d {ok : ok d}\n    : forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n.\n  Proof. apply ok. Qed.\n\n  Lemma lookup_value_size d {ok : ok d}\n    : forall i n, lookup d i = Some n -> (i < size d)%N.\n  Proof. apply ok. Qed.\n\n  Lemma lookup_size_error d {ok : ok d}\n    : forall i, (size d <= i)%N -> lookup d i = None.\n  Proof.\n    intro i; generalize (lookup_value_size d i); destruct lookup; intuition.\n    specialize_under_binders_by reflexivity.\n    lia.\n  Qed.\n\n  Lemma lookup_merge_node {descr : description} (n : node idx) (d : t) i\n        {ok : ok d}\n    : dag.lookup (snd (dag.merge_node n d)) i = match dag.lookup d i with\n                                                | Some v => Some v\n                                                | None\n                                                  => if (i =? size d)%N && Option.is_None (reverse_lookup d n)\n                                                     then Some n\n                                                     else None\n                                                end.\n  Proof.\n    cbv [dag.merge_node andb is_None lookup dag.ok size] in *;\n      repeat first [ assumption\n                   | reflexivity\n                   | lia\n                   | progress specialize_under_binders_by eassumption\n                   | progress subst\n                   | progress destruct_head'_and\n                   | progress reflect_hyps\n                   | progress cbn [fst snd option_map List.nth_error] in *\n                   | progress cbv [option_map] in *\n                   | rewrite Nat2N.id in *\n                   | rewrite nth_error_app in *\n                   | rewrite Nat.sub_diag in *\n                   | rewrite nth_error_length_error in * by lia\n                   | rewrite @nth_error_nil_error in *\n                   | congruence\n                   | break_innermost_match_step\n                   | match goal with\n                     | [ H : nth_error (_ :: _) ?x = _ |- _ ] => destruct x eqn:?; cbn [nth_error] in H\n                     end ].\n  Qed.\n\n  Lemma reverse_lookup_merge_node {d : t}\n        {ok : ok d} {descr : description} (n n' : node idx)\n    : dag.reverse_lookup (snd (dag.merge_node n d)) n'\n      = if node_beq N.eqb n' n\n        then Some (fst (dag.merge_node n d))\n        else dag.reverse_lookup d n'.\n  Proof.\n    cbv [dag.merge_node andb is_None reverse_lookup dag.ok size] in *;\n      repeat first [ assumption\n                   | reflexivity\n                   | lia\n                   | congruence\n                   | progress inversion_option\n                   | progress specialize_under_binders_by eassumption\n                   | progress subst\n                   | progress destruct_head'_and\n                   | progress reflect_hyps\n                   | rewrite @indexof_app in *\n                   | progress cbv [option_map Option.value Option.sequence idx] in *\n                   | progress cbn [fst snd option_map indexof] in *\n                   | rewrite Nat.add_0_r\n                   | congruence\n                   | break_innermost_match_step\n                   | progress break_match\n                   | progress break_match_hyps ].\n  Qed.\n\n  Lemma fst_merge_node {descr : description} (n : node idx) (d : t)\n    : fst (dag.merge_node n d) = match reverse_lookup d n with\n                                 | Some i => i\n                                 | None => size d\n                                 end.\n  Proof. cbv [merge_node]; break_innermost_match; reflexivity. Qed.\n\n  Lemma reverse_lookup_gensym s (d : t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : dag.reverse_lookup d (gensym s d) = None.\n  Proof.\n    cbv [dag.all_nodes_ok] in *.\n    destruct (reverse_lookup d (gensym s d)) as [i|] eqn:H; [ | reflexivity ].\n    rewrite iff_reverse_lookup_lookup in H by assumption.\n    cbv [node_ok gensym] in *.\n    specialize_under_binders_by eassumption.\n    specialize_under_binders_by reflexivity.\n    apply lookup_value_size in H; trivial.\n    lia.\n  Qed.\n\n  Lemma lookup_merge_node_gensym {descr : description} s (d : t) i\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : dag.lookup (snd (dag.merge_node (gensym s d) d)) i\n      = if (i =? size d)%N\n        then Some (gensym s d)\n        else dag.lookup d i.\n  Proof.\n    rewrite lookup_merge_node, reverse_lookup_gensym by assumption.\n    cbv [andb is_None].\n    break_innermost_match; try reflexivity; reflect_hyps; subst.\n    rewrite lookup_size_error in * by first [ assumption | lia ].\n    congruence.\n  Qed.\n\n  Lemma fst_merge_node_gensym {descr : description} s (d : t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : fst (dag.merge_node (gensym s d) d) = size d.\n  Proof.\n    rewrite fst_merge_node, reverse_lookup_gensym by assumption; reflexivity.\n  Qed.\n\n  Lemma lookup_empty i : lookup empty i = None.\n  Proof. cbv [empty lookup]; now rewrite nth_error_nil_error. Qed.\n  Lemma reverse_lookup_empty n : reverse_lookup empty n = None.\n  Proof. reflexivity. Qed.\n  Lemma size_empty : size empty = 0%N.\n  Proof. reflexivity. Qed.\n\n  Lemma size_merge_node {descr:description} n (d:t)\n    : size (snd (merge_node n d)) = match reverse_lookup d n with Some _ => size d | None => N.succ (size d) end.\n  Proof.\n    cbv [merge_node size]; break_innermost_match; cbn [snd] in *; inversion_pair; subst; rewrite ?app_length; cbn [List.length]; lia.\n  Qed.\n\n  Lemma size_merge_node_le {descr:description} n (d:t)\n    : (size d <= size (snd (merge_node n d)))%N.\n  Proof.\n    rewrite size_merge_node; break_innermost_match; lia.\n  Qed.\n\n  Lemma size_merge_node_gensym {descr:description} s (d:t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : size (snd (merge_node (gensym s d) d)) = N.succ (size d).\n  Proof. rewrite size_merge_node, reverse_lookup_gensym by assumption; reflexivity. Qed.\n\n  Global Instance empty_ok : ok empty | 10.\n  Proof.\n    repeat apply conj; cbv [size empty]; intros *; cbv [lookup];\n      rewrite ?nth_error_nil_error; cbn; try exact I;\n      intuition first [ congruence | lia ].\n  Qed.\n  Global Instance empty_all_nodes_ok : all_nodes_ok empty | 10.\n  Proof.\n    repeat intro; subst; rewrite lookup_empty in *; congruence.\n  Qed.\n  Global Instance merge_node_ok {descr:description} {n:node idx} {d : t} {dok : ok d} : ok (snd (merge_node n d)) | 10.\n  Proof.\n    repeat apply conj; cbv [size empty size_ok]; intros *.\n    all: rewrite ?lookup_merge_node, ?reverse_lookup_merge_node by assumption.\n    all: let tac :=\n           repeat first [ progress cbv [ok size_ok size merge_node lookup reverse_lookup] in *\n                        | progress destruct_head'_and\n                        | progress inversion_option\n                        | progress subst\n                        | exfalso; assumption\n                        | progress inversion_pair\n                        | progress cbn [fst snd List.length] in *\n                        | break_innermost_match_step\n                        | progress intros\n                        | progress destruct_head'_ex\n                        | progress destruct_head'_and\n                        | progress reflect_hyps\n                        | progress split_iff\n                        | apply conj\n                        | exact I\n                        | progress cbv [option_map idx] in *\n                        | progress break_match\n                        | progress break_match_hyps\n                        | lia\n                        | congruence\n                        | rewrite Nat2N.id in *\n                        | rewrite N2Nat.id in *\n                        | rewrite app_length\n                        | progress specialize_under_binders_by reflexivity\n                        | progress specialize_under_binders_by rewrite Nat2N.id\n                        | progress destruct_head'_prod\n                        | match goal with\n                          | [ H : forall i n, match nth_error _ (N.to_nat i) with _ => _ end = _ -> _ |- _ ]\n                            => specialize (fun i => H (N.of_nat i))\n                          | [ H : _ = Some _ |- _ ] => rewrite H in *\n                          | [ H : N.of_nat _ = N.of_nat _ |- _ ] => apply (f_equal N.to_nat) in H\n                          end\n                        | solve [ exfalso; auto ] ] in\n         tac;\n         repeat match goal with\n                | [ H : _ = Some _ |- _ ] => progress specialize_all_ways_under_binders_by rewrite H\n                end;\n         tac.\n  Qed.\n  Global Instance merge_node_all_nodes_ok {descr:description} {n:node idx} {d : t} {dok : ok d} {dnok : all_nodes_ok d} {nok : node_ok (size d) n}\n    : all_nodes_ok (snd (merge_node n d)) | 10.\n  Proof.\n    cbv [all_nodes_ok] in *; intros i r; specialize (dnok i r).\n    rewrite lookup_merge_node in * by assumption.\n    cbv [andb is_None]; break_innermost_match; intros; inversion_option; reflect_hyps; subst; auto.\n  Qed.\n  Global Instance gensym_node_ok s d : node_ok (size d) (gensym s d) | 10.\n  Proof.\n    cbv [node_ok]; intros * H.\n    inversion H; subst; reflexivity.\n  Qed.\n  Global Hint Extern 1 (node_ok (size _) (gensym _ _)) => exact (@gensym_node_ok _ _) : typeclass_instances.\n\n  Lemma eq_fst_merge_node_change_descr {descr1 descr2 : description} (n : node idx) (d : t)\n    : fst (@merge_node descr1 n d) = fst (@merge_node descr2 n d).\n  Proof.\n    cbv [merge_node]; break_innermost_match; reflexivity.\n  Qed.\n\n  (* lemmas below here don't unfold the definitions *)\n  Lemma lookup_merge_node' {descr1 descr2 : description} (n : node idx) (d : t)\n        {ok : ok d}\n    : dag.lookup (snd (@dag.merge_node descr1 n d)) (fst (@dag.merge_node descr2 n d)) = Some n.\n  Proof.\n    rewrite lookup_merge_node, fst_merge_node by assumption.\n    cbv [andb is_None].\n    repeat first [ rewrite iff_reverse_lookup_lookup in * by assumption\n                 | rewrite lookup_size_error in * by first [ assumption | lia ]\n                 | progress inversion_option\n                 | progress subst\n                 | reflexivity\n                 | progress reflect_hyps\n                 | lia\n                 | break_innermost_match_step ].\n  Qed.\nEnd dag.\nEnd Old.\nModule New.\nModule dag.\n  Module IdxMap <: UsualS := NMap <+ FMapFacts.Facts <+ Facts_RemoveHints <+ FMapFacts.AdditionalFacts.\n  Module ListIdxMap <: UsualS := ListNMap.\n  Module NodeIdxMap <: UsualS := ProdUsualMap OpMap ListIdxMap <+ FMapFacts.Facts <+ Facts_RemoveHints <+ FMapFacts.AdditionalFacts.\n  Module IdxMapProperties := FMapFacts.OrdProperties IdxMap <+ OrdProperties_RemoveHints IdxMap.\n  Module NodeIdxMapProperties := FMapFacts.OrdProperties NodeIdxMap <+ OrdProperties_RemoveHints NodeIdxMap.\n\n  Definition t : Type := NodeIdxMap.t idx * IdxMap.t (node idx * description) * N (* size *).\n  Definition empty : t := (@NodeIdxMap.empty _, @IdxMap.empty _, 0%N).\n  Definition size (d : t) : N := let '(_, _, sz) := d in sz.\n  Definition lookup (d : t) (i : idx) : option (node idx)\n    := let '(_, d, _) := d in option_map (@fst _ _) (IdxMap.find i d).\n  Definition reverse_lookup (d : t) (i : node idx) : option idx\n    := let '(d, _, _) := d in NodeIdxMap.find i d.\n  Definition size_ok (d : t) : Prop\n    := let '(im, nm, n) := d in\n       NodeIdxMap.cardinal im = N.to_nat (size d)\n       /\\ IdxMap.cardinal nm = N.to_nat (size d).\n  Definition all_nodes_ok (d : t) : Prop\n    := forall i r, lookup d i = Some r -> node_ok i r.\n  Definition ok (d : t) : Prop\n  := size_ok d\n     /\\ (forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n)\n     /\\ (forall i n, lookup d i = Some n -> (i < size d)%N).\n  Definition merge_node {descr : description} (n : node idx) (d : t) : idx * t\n    := match reverse_lookup d n with\n       | Some i => (i, d)\n       | None\n         => let '(d, d', sz) := d in\n            (sz, (NodeIdxMap.add n sz d, IdxMap.add sz (n, descr) d', N.succ sz))\n       end.\n  Definition gensym (s:OperationSize) (d : t) : node idx\n    := (old s (size d), []).\n  Existing Class ok.\n  Existing Class all_nodes_ok.\n\n  Definition get_eager_description_description (d : eager_description) : option string\n    := option_map fst d.\n  Definition get_eager_description_always_show (d : eager_description) : bool\n    := match d with Some (_, always_show) => always_show | None => false end.\n  Definition force_description : description -> eager_description\n    := option_map (fun '(descr, always_show) => (descr tt, always_show)).\n\n  Module eager.\n    Definition t := list (idx * node idx * eager_description).\n    Definition force (d : dag.t) : eager.t\n      := List.map (fun '(idx, (n, descr)) => (idx, n, force_description descr))\n                  (IdxMap.elements (let '(_, d, _) := d in d)).\n    Definition description_lookup (d : eager.t) (descr : string) : list idx\n      := List.map (fun '(idx, _, _) => idx) (List.filter (fun '(_, _, descr') => match get_eager_description_description descr' with Some descr' => String.eqb descr descr' | _ => false end) d).\n  End eager.\n\n  Definition M T := t -> T * t.\n  Definition bind {A B} (v : M A) (f : A -> M B) : M B\n    := fun d => let '(v, d) := v d in f v d.\n  Definition ret {A} (v : A) : M A\n    := fun d => (v, d).\n\n  Lemma iff_reverse_lookup_lookup d {ok : ok d}\n    : forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n.\n  Proof. apply ok. Qed.\n\n  Lemma lookup_value_size d {ok : ok d}\n    : forall i n, lookup d i = Some n -> (i < size d)%N.\n  Proof. apply ok. Qed.\n\n  Lemma lookup_size_error d {ok : ok d}\n    : forall i, (size d <= i)%N -> lookup d i = None.\n  Proof.\n    intro i; generalize (lookup_value_size d i); destruct lookup; intuition.\n    specialize_under_binders_by reflexivity.\n    lia.\n  Qed.\n\n  Lemma lookup_merge_node {descr : description} (n : node idx) (d : t) i\n        {ok : ok d}\n    : dag.lookup (snd (dag.merge_node n d)) i = match dag.lookup d i with\n                                                | Some v => Some v\n                                                | None\n                                                  => if (i =? size d)%N && Option.is_None (reverse_lookup d n)\n                                                     then Some n\n                                                     else None\n                                                end.\n  Proof.\n    cbv [dag.merge_node andb is_None lookup dag.ok size] in *;\n      repeat first [ assumption\n                   | reflexivity\n                   | lia\n                   | progress specialize_under_binders_by eassumption\n                   | progress subst\n                   | progress destruct_head'_and\n                   | progress reflect_hyps\n                   | progress cbn [fst snd option_map] in *\n                   | rewrite IdxMap.add_o\n                   | break_innermost_match_step ].\n  Qed.\n\n  Lemma reverse_lookup_merge_node {d : t}\n        {ok : ok d} {descr : description} (n n' : node idx)\n    : dag.reverse_lookup (snd (dag.merge_node n d)) n'\n      = if node_beq N.eqb n' n\n        then Some (fst (dag.merge_node n d))\n        else dag.reverse_lookup d n'.\n  Proof.\n    cbv [dag.merge_node andb is_None reverse_lookup dag.ok size] in *;\n      repeat first [ assumption\n                   | reflexivity\n                   | lia\n                   | congruence\n                   | progress specialize_under_binders_by eassumption\n                   | progress subst\n                   | progress destruct_head'_and\n                   | progress reflect_hyps\n                   | progress cbn [fst snd option_map] in *\n                   | rewrite NodeIdxMap.add_o\n                   | break_innermost_match_step ].\n  Qed.\n\n  Lemma fst_merge_node {descr : description} (n : node idx) (d : t)\n    : fst (dag.merge_node n d) = match reverse_lookup d n with\n                                 | Some i => i\n                                 | None => size d\n                                 end.\n  Proof. cbv [merge_node]; break_innermost_match; reflexivity. Qed.\n\n  Lemma reverse_lookup_gensym s (d : t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : dag.reverse_lookup d (gensym s d) = None.\n  Proof.\n    cbv [dag.all_nodes_ok] in *.\n    destruct (reverse_lookup d (gensym s d)) as [i|] eqn:H; [ | reflexivity ].\n    rewrite iff_reverse_lookup_lookup in H by assumption.\n    cbv [node_ok gensym] in *.\n    specialize_under_binders_by eassumption.\n    specialize_under_binders_by reflexivity.\n    apply lookup_value_size in H; trivial.\n    lia.\n  Qed.\n\n  Lemma lookup_merge_node_gensym {descr : description} s (d : t) i\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : dag.lookup (snd (dag.merge_node (gensym s d) d)) i\n      = if (i =? size d)%N\n        then Some (gensym s d)\n        else dag.lookup d i.\n  Proof.\n    rewrite lookup_merge_node, reverse_lookup_gensym by assumption.\n    cbv [andb is_None].\n    break_innermost_match; try reflexivity; reflect_hyps; subst.\n    rewrite lookup_size_error in * by first [ assumption | lia ].\n    congruence.\n  Qed.\n\n  Lemma fst_merge_node_gensym {descr : description} s (d : t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : fst (dag.merge_node (gensym s d) d) = size d.\n  Proof.\n    rewrite fst_merge_node, reverse_lookup_gensym by assumption; reflexivity.\n  Qed.\n\n  Lemma lookup_empty i : lookup empty i = None.\n  Proof. cbv [empty lookup]; now rewrite IdxMap.find_empty. Qed.\n  Lemma reverse_lookup_empty n : reverse_lookup empty n = None.\n  Proof. cbv [empty reverse_lookup]; now rewrite NodeIdxMap.find_empty. Qed.\n  Lemma size_empty : size empty = 0%N.\n  Proof. reflexivity. Qed.\n\n  Lemma size_merge_node {descr:description} n (d:t)\n    : size (snd (merge_node n d)) = match reverse_lookup d n with Some _ => size d | None => N.succ (size d) end.\n  Proof.\n    cbv [merge_node size]; break_innermost_match; cbn [snd] in *; inversion_pair; subst; try reflexivity.\n  Qed.\n\n  Lemma size_merge_node_le {descr:description} n (d:t)\n    : (size d <= size (snd (merge_node n d)))%N.\n  Proof.\n    rewrite size_merge_node; break_innermost_match; lia.\n  Qed.\n\n  Lemma size_merge_node_gensym {descr:description} s (d:t)\n        {ok : ok d}\n        {all_nodes_ok : all_nodes_ok d}\n    : size (snd (merge_node (gensym s d) d)) = N.succ (size d).\n  Proof. rewrite size_merge_node, reverse_lookup_gensym by assumption; reflexivity. Qed.\n\n  Global Instance empty_ok : ok empty | 10.\n  Proof.\n    repeat apply conj; cbv [size empty].\n    { apply NodeIdxMapProperties.P.cardinal_1, NodeIdxMap.empty_1. }\n    { apply IdxMapProperties.P.cardinal_1, IdxMap.empty_1. }\n    all: cbv [lookup reverse_lookup]; intros *.\n    all: rewrite ?NodeIdxMap.empty_o, ?IdxMap.empty_o; cbn; intuition congruence.\n  Qed.\n  Global Instance empty_all_nodes_ok : all_nodes_ok empty | 10.\n  Proof.\n    repeat intro; subst; rewrite lookup_empty in *; congruence.\n  Qed.\n  Global Instance merge_node_ok {descr:description} {n:node idx} {d : t} {dok : ok d} : ok (snd (merge_node n d)) | 10.\n  Proof.\n    repeat apply conj; cbv [size empty size_ok]; intros *.\n    all: rewrite ?lookup_merge_node, ?reverse_lookup_merge_node by assumption.\n    all: repeat first [ progress cbv [ok size_ok size merge_node lookup reverse_lookup] in *\n                      | progress destruct_head'_and\n                      | progress inversion_option\n                      | progress subst\n                      | exfalso; assumption\n                      | progress inversion_pair\n                      | progress cbn [fst snd] in *\n                      | break_innermost_match_step\n                      | progress intros\n                      | progress reflect_hyps\n                      | progress split_iff\n                      | apply conj\n                      | rewrite NodeIdxMap.cardinal_add, NodeIdxMap.mem_find_b\n                      | rewrite IdxMap.cardinal_add, IdxMap.mem_find_b\n                      | rewrite N2Nat.inj_succ\n                      | lia\n                      | congruence\n                      | solve [ auto ]\n                      | match goal with\n                        | [ H : ?x = Some _ |- _ ] => rewrite H in *\n                        end\n                      | progress specialize_under_binders_by reflexivity\n                      | match goal with\n                        | [ H : _ |- _ ] => progress specialize_all_ways_under_binders_by exact H\n                        | [ H : _ |- _ ] => progress specialize_all_ways_under_binders_by rewrite H\n                        end ].\n  Qed.\n  Global Instance merge_node_all_nodes_ok {descr:description} {n:node idx} {d : t} {dok : ok d} {dnok : all_nodes_ok d} {nok : node_ok (size d) n}\n    : all_nodes_ok (snd (merge_node n d)) | 10.\n  Proof.\n    cbv [all_nodes_ok] in *; intros i r; specialize (dnok i r).\n    rewrite lookup_merge_node in * by assumption.\n    cbv [andb is_None]; break_innermost_match; intros; inversion_option; reflect_hyps; subst; auto.\n  Qed.\n  Global Instance gensym_node_ok s d : node_ok (size d) (gensym s d) | 10.\n  Proof.\n    cbv [node_ok]; intros * H.\n    inversion H; subst; reflexivity.\n  Qed.\n  Global Hint Extern 1 (node_ok (size _) (gensym _ _)) => exact (@gensym_node_ok _ _) : typeclass_instances.\n\n  Lemma eq_fst_merge_node_change_descr {descr1 descr2 : description} (n : node idx) (d : t)\n    : fst (@merge_node descr1 n d) = fst (@merge_node descr2 n d).\n  Proof.\n    cbv [merge_node]; break_innermost_match; reflexivity.\n  Qed.\n\n  (* lemmas below here don't unfold the definitions *)\n  Lemma lookup_merge_node' {descr1 descr2 : description} (n : node idx) (d : t)\n        {ok : ok d}\n    : dag.lookup (snd (@dag.merge_node descr1 n d)) (fst (@dag.merge_node descr2 n d)) = Some n.\n  Proof.\n    rewrite lookup_merge_node, fst_merge_node by assumption.\n    cbv [andb is_None].\n    repeat first [ rewrite iff_reverse_lookup_lookup in * by assumption\n                 | rewrite lookup_size_error in * by first [ assumption | lia ]\n                 | progress inversion_option\n                 | progress subst\n                 | reflexivity\n                 | progress reflect_hyps\n                 | lia\n                 | break_innermost_match_step ].\n  Qed.\nEnd dag.\nEnd New.\nExport Old.\nGlobal Arguments dag.t : simpl never.\nGlobal Arguments dag.empty : simpl never.\nGlobal Arguments dag.size : simpl never.\nGlobal Arguments dag.lookup : simpl never.\nGlobal Arguments dag.reverse_lookup : simpl never.\nGlobal Arguments dag.ok : simpl never.\nGlobal Arguments dag.all_nodes_ok : simpl never.\nGlobal Arguments dag.merge_node : simpl never.\nGlobal Arguments dag.gensym : simpl never.\nGlobal Strategy 1000 [\n      dag.t\n        dag.empty\n        dag.size\n        dag.lookup\n        dag.reverse_lookup\n        dag.ok\n        dag.all_nodes_ok\n        dag.merge_node\n        dag.gensym\n    ].\nNotation dag := dag.t.\nDelimit Scope dagM_scope with dagM.\nBind Scope dagM_scope with dag.M.\nNotation \"x <- y ; f\" := (dag.bind y (fun x => f%dagM)) : dagM_scope.\n\nSection WithDag.\n  Context (ctx : symbol -> option Z) (dag : dag.t).\n  Definition reveal_step reveal (i : idx) : expr :=\n    match dag.lookup dag i with\n    | None => (* undefined *) ExprRef i\n    | Some (op, args) => ExprApp (op, List.map reveal args)\n    end.\n  Fixpoint reveal (n : nat) (i : idx) :=\n    match n with\n    | O => ExprRef i\n    | S n => reveal_step (reveal n) i\n    end.\n\n  Definition reveal_node n '(op, args) :=\n    ExprApp (op, List.map (reveal n) args).\n\n  (** given a set of indices, get the set of indices of their arguments *)\n  Definition reveal_gather_deps_args (ls : NSet.t) : NSet.t\n    := fold_right\n         (fun i so_far => match dag.lookup dag i with\n                          | None => so_far\n                          | Some (_op, args) => fold_right NSet.add so_far args\n                          end)\n         NSet.empty\n         (NSet.elements ls).\n\n  (** given a set of seen indices and a set of newly-revealed indices,\n  we want to merge the new indices into what's been seen and recurse\n  on the new indices *)\n  Definition reveal_gather_deps_step reveal_gather_deps (so_far : NSet.t) (new_idxs : NSet.t) : NSet.t\n    := let new_idxs := NSet.diff new_idxs so_far in\n       if NSet.is_empty new_idxs\n       then so_far\n       else reveal_gather_deps (NSet.union so_far new_idxs) (reveal_gather_deps_args new_idxs).\n\n  Fixpoint reveal_gather_deps_list (n : nat) (so_far : NSet.t) (new_idxs : NSet.t) : NSet.t\n    := match n with\n       | O => NSet.union so_far new_idxs\n       | S n => reveal_gather_deps_step (reveal_gather_deps_list n) so_far new_idxs\n       end.\n\n  Definition reveal_gather_deps (n : nat) (i : idx) : NSet.t\n    := reveal_gather_deps_list n NSet.empty (NSet.singleton i).\n\n  Definition reveal_step_from_deps reveal (deps : NSet.t) (i : idx) : expr\n    := if NSet.mem i deps\n       then match dag.lookup dag i with\n            | None => (* undefined *) ExprRef i\n            | Some (op, args) => ExprApp (op, List.map reveal args)\n            end\n       else ExprRef i.\n  Fixpoint reveal_from_deps_fueled (fuel : nat) (deps : NSet.t) (i : idx) :=\n    match fuel with\n    | O => ExprRef i\n    | S fuel => reveal_step_from_deps (reveal_from_deps_fueled fuel deps) deps i\n    end.\n  (** depth determines which indices get expanded, but all references\n  to the same index get expanded if they appear in the output *)\n  Definition reveal_at_least n (i : idx) : expr\n    := reveal_from_deps_fueled (S (N.to_nat (dag.size dag))) (reveal_gather_deps n i) i.\n\n  Definition reveal_node_at_least n '(op, args) :=\n    ExprApp (op, List.map (reveal_at_least n) args).\n\n  Local Unset Elimination Schemes.\n  Inductive eval : expr -> Z -> Prop :=\n  | ERef i op args args' n\n    (_:dag.lookup dag i = Some (op, args))\n    (_:List.Forall2 eval (map ExprRef args) args')\n    (_:interp_op ctx op args' = Some n)\n    : eval (ExprRef i) n\n  | EApp op args args' n\n    (_:List.Forall2 eval args args')\n    (_:interp_op ctx op args' = Some n)\n    : eval (ExprApp (op, args)) n.\n\n  Variant eval_node : node idx -> Z -> Prop :=\n  | ENod op args args' n\n    (_:List.Forall2 eval (map ExprRef args) args')\n    (_:interp_op ctx op args' = Some n)\n    : eval_node (op, args) n.\n\n\n  Section eval_ind.\n    Context (P : expr -> Z -> Prop)\n      (HRef : forall i op args args' n, dag.lookup dag i = Some (op, args) ->\n        Forall2 (fun e n => eval e n /\\ P e n) (map ExprRef args) args' ->\n        interp_op ctx op args' = Some n ->\n        P (ExprRef i) n)\n      (HApp : forall op args args' n,\n        Forall2 (fun i e => eval i e /\\ P i e) args args' ->\n        interp_op ctx op args' = Some n ->\n        P (ExprApp (op, args)) n).\n    Fixpoint eval_ind i n (pf : eval i n) {struct pf} : P i n :=\n      match pf with\n      | ERef _ _ _ _ _ A B C => HRef _ _ _ _ _ A (Forall2_weaken (fun _ _ D => conj D (eval_ind _ _ D)) _ _ B) C\n      | EApp _ _ _ _ A B => HApp _ _ _ _ (Forall2_weaken (fun _ _ C => conj C (eval_ind _ _ C)) _ _ A) B\n      end.\n  End eval_ind.\n\n  Lemma eval_eval : forall e v1, eval e v1 -> forall v2, eval e v2 -> v1=v2.\n  Proof using Type.\n    induction 1; inversion 1; subst;\n    enough (args' = args'0) by congruence;\n    try replace args0 with args in * by congruence.\n    { eapply Forall2_map_l in H0.\n      eapply Forall2_flip in H0.\n      eapply (proj1 (Forall2_map_l _ _ _)) in H5.\n      epose proof Forall2_trans H0 H5 as HH.\n      eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }\n    { eapply Forall2_flip in H.\n      epose proof Forall2_trans H H4 as HH.\n      eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }\n  Qed.\n\n  Lemma eval_eval_Forall2 xs vxs (_ : Forall2 eval xs vxs)\n    vys (_ : Forall2 eval xs vys) : vxs = vys.\n  Proof using Type.\n    revert dependent vys; induction H; inversion 1; subst;\n      eauto; eauto using f_equal2, IHForall2, eval_eval.\n  Qed.\n\n  Lemma eval_reveal : forall n i, forall v, eval (ExprRef i) v ->\n    forall e, reveal n i = e -> eval e v.\n  Proof using Type.\n    induction n; cbn [reveal]; cbv [reveal_step]; intros; subst; eauto; [].\n    inversion H; subst; clear H.\n    rewrite H1; econstructor; try eassumption; [].\n    eapply (proj1 (Forall2_map_l _ _ _)) in H2.\n    clear dependent i; clear dependent v.\n    induction H2; cbn; eauto.\n  Qed.\n\n  Lemma eval_node_reveal_node : forall n v, eval_node n v ->\n    forall f e, reveal_node f n = e -> eval e v.\n  Proof using Type.\n    cbv [reveal_node]; inversion 1; intros; subst.\n    econstructor; eauto.\n    eapply (proj1 (Forall2_map_l _ _ _)) in H0; eapply Forall2_map_l.\n    eapply Forall2_weaken; try eassumption; []; cbv beta; intros.\n    eapply eval_reveal; eauto.\n  Qed.\n\n  Lemma eval_reveal_from_deps_fueled deps : forall n i, forall v, eval (ExprRef i) v ->\n    forall e, reveal_from_deps_fueled n deps i = e -> eval e v.\n  Proof using Type.\n    induction n; cbn [reveal_from_deps_fueled]; cbv [reveal_step_from_deps]; intros; subst; eauto; [].\n    break_innermost_match_step; eauto; [].\n    inversion H; subst; clear H.\n    rewrite H1; econstructor; try eassumption; [].\n    eapply (proj1 (Forall2_map_l _ _ _)) in H2.\n    clear dependent i; clear dependent v.\n    induction H2; cbn; eauto.\n  Qed.\n\n  Lemma eval_reveal_at_least : forall n i, forall v, eval (ExprRef i) v ->\n    forall e, reveal_at_least n i = e -> eval e v.\n  Proof using Type.\n    cbv [reveal_at_least].\n    intros; eapply eval_reveal_from_deps_fueled; eassumption.\n  Qed.\n\n  Lemma eval_node_reveal_node_at_least : forall n v, eval_node n v ->\n    forall f e, reveal_node_at_least f n = e -> eval e v.\n  Proof using Type.\n    cbv [reveal_node]; inversion 1; intros; subst.\n    econstructor; eauto.\n    eapply (proj1 (Forall2_map_l _ _ _)) in H0; eapply Forall2_map_l.\n    eapply Forall2_weaken; try eassumption; []; cbv beta; intros.\n    eapply eval_reveal_at_least; eauto.\n  Qed.\nEnd WithDag.\n\nDefinition merge_node {descr : description} (n : node idx) : dag.M idx\n  := dag.merge_node n.\n\nFixpoint merge {descr : description} (e : expr) (d : dag) : idx * dag :=\n  match e with\n  | ExprRef i => (i, d)\n  | ExprApp (op, args) =>\n    let idxs_d := List.foldmap merge args d in\n    let idxs := if commutative op\n                then N.sort (fst idxs_d)\n                else (fst idxs_d) in\n    merge_node (op, idxs) (snd idxs_d)\n  end.\n\nLemma node_beq_sound e x : node_beq N.eqb e x = true -> e = x.\nProof using Type.\n  eapply Prod.internal_prod_dec_bl.\n  { intros X Y; destruct (op_beq_spec X Y); congruence. }\n  { intros X Y. eapply ListUtil.internal_list_dec_bl, N.eqb_eq. }\nQed.\n\nLemma eval_weaken_merge_node G d {dok : dag.ok d} {descr:description} x e n : eval G d e n -> eval G (snd (dag.merge_node x d)) e n.\nProof using Type.\n  induction 1; subst; econstructor; eauto.\n  { erewrite dag.lookup_merge_node by assumption.\n    match goal with H : _ |- _ => rewrite H end; reflexivity. }\n  all : eapply Forall2_weaken; [|eassumption].\n  { intuition eauto. eapply H2. }\n  { intuition eauto. eapply H1. }\nQed.\n\nLemma eval_weaken_symbols G1 G2 d e n\n  (H : forall s v, G1 s = Some v -> G2 s = Some v)\n  : eval G1 d e n -> eval G2 d e n.\nProof using Type.\n  induction 1; subst; econstructor;\n    intuition eauto using interp_op_weaken_symbols.\n  { eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }\n  { eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }\nQed.\n\nLemma eval_eval0 d e n G : eval (fun _ => None) d e n -> eval G d e n.\nProof using Type. eapply eval_weaken_symbols; congruence. Qed.\n\nLemma permute_commutative G op args n : commutative op = true ->\n  interp_op G op args = Some n ->\n  forall args', Permutation.Permutation args args' ->\n  interp_op G op args' = Some n.\nProof using Type.\n  destruct op; inversion 1; cbn; intros ? ? Hp;\n    try (erewrite <- Z.fold_right_Proper_Permutation_add; eauto);\n    try (erewrite <- Z.fold_right_Proper_Permutation_mul; eauto);\n    try (erewrite <- Z.fold_right_Proper_Permutation_land; eauto);\n    try (erewrite <- Z.fold_right_Proper_Permutation_lor; eauto);\n    try (erewrite <- Z.fold_right_Proper_Permutation_lxor; eauto).\n  { erewrite <-(Z.fold_right_Proper_Permutation_add _ _ eq_refl _ (map _ args'));\n      eauto using Permutation.Permutation_map. }\nQed.\n\n(* the gensym state cannot map anything past the end of the dag *)\nDefinition gensym_ok (G : symbol -> option Z) (d : dag) := forall s _v, G s = Some _v -> (s < dag.size d)%N.\nDefinition dag_ok G (d : dag) := dag.ok d /\\ dag.all_nodes_ok d /\\ forall i r, dag.lookup d i = Some r -> exists v, eval G d (ExprRef i) v.\nDefinition gensym_dag_ok G d := gensym_ok G d /\\ dag_ok G d.\n\nLemma gensym_ok_size_Proper G d1 d2\n      (H : (dag.size d1 <= dag.size d2)%N)\n  : gensym_ok G d1 -> gensym_ok G d2.\nProof using Type. cbv [gensym_ok]; intros; specialize_under_binders_by eassumption; lia. Qed.\n\nLemma gensym_ok_merge_node G d {descr:description} n\n  : gensym_ok G d -> gensym_ok G (snd (dag.merge_node n d)).\nProof using Type. apply gensym_ok_size_Proper, dag.size_merge_node_le. Qed.\n\nLemma empty_gensym_dag_ok : gensym_dag_ok (fun _ => None) dag.empty.\nProof using Type.\n  cbv [gensym_dag_ok dag_ok gensym_ok].\n  repeat match goal with |- _ /\\ _ => split end; try exact _; intros *;\n    rewrite ?dag.lookup_empty; try congruence.\nQed.\n\nLemma eval_merge_node {descr descr' descr'' descr'''} :\n  forall G d, gensym_dag_ok G d ->\n  forall op args n, let e := (op, args) in\n  eval G d (ExprApp (op, List.map ExprRef args)) n ->\n  eval G (snd (@merge_node descr e d)) (ExprRef (fst (@merge_node descr' e d))) n /\\\n  gensym_dag_ok G (snd (@merge_node descr'' e d)) /\\\n  forall i e', eval G d i e' -> eval G (snd (@merge_node descr''' e d)) i e'.\nProof using Type.\n  intros.\n  cbv beta delta [merge_node].\n  inversion H0; subst.\n  cbv [gensym_dag_ok dag_ok] in *; destruct_head'_and.\n  repeat match goal with |- _ /\\ _ => split end; try exact _.\n  1: econstructor; try eassumption.\n  all: eauto using Forall2_weaken, eval_weaken_merge_node.\n  all: try now apply gensym_ok_merge_node.\n  { now rewrite dag.lookup_merge_node' by assumption. }\n  { apply @dag.merge_node_all_nodes_ok; try assumption.\n    cbv [e node_ok]; intros; inversion_pair; subst; cbn [interp_op] in *.\n    break_innermost_match_hyps; inversion_option; subst.\n    cbv [gensym_ok] in *.\n    specialize_under_binders_by eassumption; lia. }\n  { intros *; rewrite dag.lookup_merge_node by assumption.\n    break_innermost_match; inversion 1; subst; specialize_under_binders_by eassumption; destruct_head'_ex.\n    all: eauto using eval_weaken_merge_node.\n    reflect_hyps; destruct_head'_and; subst.\n    lazymatch goal with\n    | [ |- context[snd (@dag.merge_node ?descr ?e ?d)] ]\n      => replace (dag.size d) with (fst (@dag.merge_node descr e d))\n        by (rewrite dag.fst_merge_node; break_innermost_match; congruence)\n    end.\n    eexists; econstructor;\n      [ rewrite dag.lookup_merge_node' by assumption; reflexivity\n      | eauto using Forall2_weaken, eval_weaken_merge_node .. ]. }\nQed.\n\nRequire Import coqutil.Tactics.autoforward coqutil.Decidable coqutil.Tactics.Tactics.\nGlobal Set Default Goal Selector \"1\".\n\nLemma eval_merge {descr:description} G :\n  forall e n,\n  forall d, gensym_dag_ok G d ->\n  eval G d e n ->\n  eval G (snd (merge e d)) (ExprRef (fst (merge e d))) n /\\\n  gensym_dag_ok G (snd (merge e d)) /\\\n  forall i e', eval G d i e' -> eval G (snd (merge e d)) i e'.\nProof using Type.\n  induction e; intros; eauto; [].\n  rename n0 into v.\n\n  set (merge _ _) as m; cbv beta iota delta [merge] in m; fold @merge in m.\n  destruct n as (op&args).\n  repeat match goal with\n    m := let x := ?A in @?B x |- _ =>\n    let y := fresh x in\n    set A as y;\n    let m' := eval cbv beta in (B y) in\n    change m' in (value of m)\n  end.\n\n  inversion H1; clear H1 ; subst.\n\n  cbn [fst snd] in *.\n  assert (gensym_dag_ok G (snd idxs_d) /\\\n    Forall2 (fun i v => eval G (snd idxs_d) (ExprRef i) v) (fst idxs_d) args' /\\\n    forall i e', eval G d i e' -> eval G (snd idxs_d) i e'\n  ) as HH; [|destruct HH as(?&?&?)].\n  { clear m idxs H6 v op; revert dependent d; revert dependent args'.\n    induction H; cbn; intros; inversion H4; subst;\n      split_and; pose proof @Forall2_weaken; typeclasses eauto 8 with core. }\n  clearbody idxs_d.\n\n  enough (eval G (snd idxs_d) (ExprApp (op, map ExprRef idxs)) v) by\n    (unshelve (let lem := open_constr:(eval_merge_node _ _ ltac:(eassumption) op idxs v) in\n               edestruct lem as (?&?&?)); eauto); clear m.\n\n  pose proof length_Forall2 H4; pose proof length_Forall2 H2.\n\n  cbn [fst snd] in *; destruct (commutative op) eqn:?; cycle 1; subst idxs.\n\n  { econstructor; eauto.\n    eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [].\n    intros i Hi.\n    unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));\n      shelve_unifiable; try congruence; [].\n    rewrite ListUtil.map_nth_default_always. eapply H8. }\n\n  pose proof N.Sort.Permuted_sort (fst idxs_d) as Hperm.\n  eapply (Permutation.Permutation_Forall2 Hperm) in H2.\n  case H2 as (argExprs&Hperm'&H2).\n  eapply permute_commutative in H6; try eassumption; [].\n  epose proof Permutation.Permutation_length Hperm.\n  epose proof Permutation.Permutation_length Hperm'.\n\n  { econstructor; eauto.\n    eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [|].\n    { setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }\n    intros i Hi.\n    unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));\n      shelve_unifiable; try trivial; [|].\n    { setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }\n    rewrite ListUtil.map_nth_default_always. eapply H10. }\n  Unshelve. all : constructor.\nQed.\n\nDefinition zconst s (z:Z) := const (Z.land z (Z.ones (Z.of_N s)))%Z.\n\nSection WithContext.\n  Context (ctx : symbol -> option Z).\n  Fixpoint interp_expr (e : expr) : option Z :=\n    match e with\n    | ExprApp (o, arges) =>\n        args <- Option.List.lift (List.map interp_expr arges);\n        interp_op ctx o args\n    | _ => None\n    end%option.\nEnd WithContext.\nDefinition interp0_expr := interp_expr (fun _ => None).\n\nLemma eval_interp_expr G e : forall d v, interp_expr G e = Some v -> eval G d e v.\nProof using Type.\n  induction e; cbn; try discriminate; intros.\n  case n in *; cbn [fst snd] in *.\n  destruct (Option.List.lift _) eqn:? in *; try discriminate.\n  econstructor; try eassumption; [].\n  clear dependent v.\n  revert dependent l0.\n  induction H; cbn in *.\n  { inversion 1; subst; eauto. }\n  destruct (interp_expr _) eqn:? in *; cbn in *; try discriminate; [].\n  destruct (fold_right _ _ _) eqn:? in *; cbn in *; try discriminate; [].\n  specialize (fun d => H d _ eq_refl).\n  inversion 1; subst.\n  econstructor; trivial; [].\n  eapply IHForall; eassumption.\nQed.\n\nLemma eval_interp0_expr e v (H : interp0_expr e = Some v) : forall G d, eval G d e v.\nProof using Type.\n  cbv [interp0_expr]; intros.\n  eapply eval_interp_expr, eval_weaken_symbols in H; [eassumption|congruence].\nQed.\n\nLocal Open Scope Z_scope.\n\nFixpoint bound_expr e : option Z := (* e <= r *)\n  match e with\n  | ExprApp (const v, _) => if Z.leb 0 v then Some v else None\n  | ExprApp (add s, args) =>\n      Some  match Option.List.lift (List.map bound_expr args) with\n            | Some bounds => Z.min (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))\n            | None => Z.ones (Z.of_N s)\n            end\n  | ExprApp (selectznz, [c;a;b]) =>\n      match bound_expr a, bound_expr b with\n      | Some a, Some b => Some (Z.max a b)\n      | _, _ => None\n      end\n  | ExprApp (set_slice 0 w, [a;b]) =>\n      match bound_expr a, bound_expr b with\n      | Some a, Some b => Some (Z.lor\n                                  (Z.land (Z.ones (Z.succ (Z.log2 b))) (Z.ones (Z.of_N w)))\n                                  (Z.ldiff (Z.ones (Z.succ (Z.log2 a))) (Z.ones (Z.of_N w))))\n      | _, _ => None\n      end\n  | ExprApp ((old s _ | slice _ s | mul s | shl s | shr s | sar s | neg s | and s | or s | xor s), _) => Some (Z.ones (Z.of_N s))\n  | ExprApp ((addcarry _ | subborrow _ | addoverflow _ | iszero), _) => Some 1\n  | _ => None\n  end%Z.\n\nImport coqutil.Tactics.Tactics.\nLtac t:= match goal with\n  | _ => progress intros\n  | H : eval _ _ (ExprApp _) _ |- _ => inversion H; clear H; subst\n  | H : Forall _ (cons _ _) |- _ => inversion H; clear H; subst\n  | H : Forall _ nil |- _ => inversion H; clear H; subst\n  | H : Forall2 _ (cons _ _) _ |- _ => inversion H; clear H; subst\n  | H : Forall2 _ nil _ |- _ => inversion H; clear H; subst\n  | H : Forall2 _ _ (cons _ _) |- _ => inversion H; clear H; subst\n  | H : Forall2 _ _ nil |- _ => inversion H; clear H; subst\n  | H : _ = true |- _ => autoforward with typeclass_instances in H\n  | H : forall b, _ |- _ => pose proof (H _ ltac:(eassumption) _ _ ltac:(eassumption)); clear H\n  | H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>\n      assert_fails (constr_eq v1 v2);\n      eapply (eval_eval _ d e v1 H v2) in G\n  | _ => progress cbv [interp_op] in *\n  | _ => progress cbn [fst snd] in *\n  | _ => progress destruct_one_match\n  | _ => progress Option.inversion_option\n  | _ => progress subst\n  end.\n\nLemma bound_sum' G d\n  es (He : Forall (fun e => forall b, bound_expr e = Some b ->\n       forall (d : dag) (v : Z), eval G d e v -> (0 <= v <= b)%Z) es)\n  : forall\n  bs (Hb : Option.List.lift (map bound_expr es) = Some bs)\n  vs (Hv : Forall2 (eval G d) es vs)\n  , (0 <= fold_right Z.add 0 vs <= fold_right Z.add 0 bs)%Z.\nProof using Type.\n  induction He; cbn in *; repeat t.\n  { cbv [fold_right]; Lia.lia. }\n  destruct (bound_expr _) eqn:? in *; cbn in *; repeat t.\n  destruct (fold_right (B:=option _) _) eqn:? in *; cbn in *; repeat t.\n  specialize (IHHe _ ltac:(eassumption) _ ltac:(eassumption)); cbn.\n  specialize (H _ ltac:(exact eq_refl) _ _ ltac:(eassumption)).\n  Lia.lia.\nQed.\n\nRequire Import Util.ZRange.LandLorBounds.\nLemma eval_bound_expr G e b : bound_expr e = Some b ->\n  forall d v, eval G d e v -> (0 <= v <= b)%Z.\nProof using Type.\n  revert b; induction e; simpl bound_expr; BreakMatch.break_match;\n    inversion 2; intros; inversion_option; subst;\n    try match goal with H : context [set_slice] |- _ => shelve end;\n    cbv [interp_op] in *;\n    BreakMatch.break_match_hyps; inversion_option; subst;\n    rewrite ?Z.ldiff_ones_r, ?Z.land_ones, ?Z.ones_equiv;\n    cbv [Z.b2z];\n    try match goal with |- context [(?a mod ?b)%Z] => unshelve epose proof Z.mod_pos_bound a b ltac:(eapply Z.pow_pos_nonneg; Lia.lia) end;\n    repeat t;\n    try (Z.div_mod_to_equations; Lia.lia).\n  { clear dependent args'0.\n    epose proof bound_sum' _ ltac:(eassumption) _ ltac:(eassumption) _ ltac:(eassumption) _ ltac:(eassumption).\n    split; try Lia.lia.\n    eapply Z.min_glb_iff; split; try Lia.lia.\n    etransitivity. eapply Zmod_le.\n    all : try Lia.lia. }\n  Unshelve. {\n    repeat t.\n    pose proof Z.log2_nonneg z; pose proof Z.log2_nonneg z0.\n    rewrite !Z.shiftl_0_r.\n    split.\n    { eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg; Lia.lia. }\n    eapply Z.le_bitwise.\n    { eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg; Lia.lia. }\n    { eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg;\n        left; try eapply Z.ones_nonneg; Lia.lia. }\n    { intros i Hi.\n      Z.rewrite_bitwise.\n      destr (i <? Z.of_N sz);\n        rewrite ?Bool.andb_false_r, ?Bool.andb_true_r, ?Bool.orb_false_l, ?Bool.orb_false_r.\n      { clear -H Hi.\n        destr (i <? Z.succ (Z.log2 z0)).\n        { eapply Bool.le_implb, Bool.implb_true_r. }\n        rewrite Z.bits_above_log2; cbn; trivial; try Lia.lia.\n        destruct H as [H' H]; eapply Z.log2_le_mono in H. Lia.lia. }\n      { clear -H0 Hi.\n        destr (i <? Z.succ (Z.log2 z)).\n        { eapply Bool.le_implb, Bool.implb_true_r. }\n        rewrite Z.bits_above_log2; cbn; trivial; try Lia.lia.\n        destruct H0 as [? H0]; eapply Z.log2_le_mono in H0. Lia.lia. } } }\nQed.\n\nLemma bound_sum G d es\n  bs (Hb : Option.List.lift (map bound_expr es) = Some bs)\n  vs (Hv : Forall2 (eval G d) es vs)\n  : (0 <= fold_right Z.add 0 vs <= fold_right Z.add 0 bs)%Z.\nProof using Type.\n  eapply bound_sum' in Hb; eauto.\n  eapply Forall_forall; intros.\n  eapply eval_bound_expr; eauto.\nQed.\n\n\nDefinition isCst (e : expr) :=\n  match e with ExprApp ((const _), []) => true | _ => false end.\n\nModule Rewrite.\nClass Ok r := rwok : forall G d e v, eval G d e v -> eval G d (r e) v.\n\nLtac resolve_match_using_hyp :=\n  match goal with |- context[match ?x with _ => _ end] =>\n  match goal with H : x = ?v |- _ =>\n      let h := Head.head v in\n      is_constructor h;\n      rewrite H\n  end end.\n\nLtac step := match goal with\n  | |- Ok ?r => cbv [Ok r]; intros\n  | _ => solve [trivial | contradiction]\n  |  _ => resolve_match_using_hyp\n  | _ => inversion_option_step\n\n  | H : _ = ?v |- _ => is_var v; progress subst v\n  | H : ?v = _ |- _ => is_var v; progress subst v\n\n  | H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>\n      assert_fails (constr_eq v1 v2);\n      eapply (eval_eval _ d e v1 H v2) in G\n  | |- eval _ ?d ?e ?v =>\n      match goal with\n        H : eval _ d e ?v' |- _ =>\n            let Heq := fresh in\n            enough (Heq : v = v') by (rewrite Heq; exact H);\n            try (clear H; clear e)\n      end\n\n  | H: interp_op _ (const _) nil = Some _ |- _ => inversion H; clear H; subst\n  | H: interp0_op _ _ = Some _ |- _ => eapply interp_op_interp0_op in H\n  | H: interp0_expr _ = Some _ |- _ => eapply eval_interp0_expr in H\n  | H: bound_expr _ = Some _ |- _ => eapply eval_bound_expr in H; eauto; [ ]\n\n  | H : (?x <=? ?y)%N = ?b |- _ => is_constructor b; destruct (N.leb_spec x y); (inversion H || clear H)\n  | H : andb _ _ = true |- _ => eapply Bool.andb_prop in H; case H as (?&?)\n  | H : N.eqb ?n _ = true |- _ => eapply N.eqb_eq in H; try subst n\n  | H : Z.eqb ?n _ = true |- _ => eapply Z.eqb_eq in H; try subst n\n  | H : expr_beq ?a ?b = true |- _ => replace a with b in * by (symmetry;exact (expr_beq_true a b H)); clear H\n  | _ => progress destruct_one_match_hyp\n  | _ => progress destruct_one_match\n\n  | H : eval _ _ ?e _ |- _ => assert_fails (is_var e); inversion H; clear H; subst\n  | H : Forall2 (eval _ _) (cons _ _) _ |- _ => inversion H; clear H; subst\n  | H : Forall2 (eval _ _) _ (cons _ _) |- _ => inversion H; clear H; subst\n  | H : Forall2 _ _ nil |- _ => inversion H; clear H; subst\n  | H : Forall2 _ nil _ |- _ => inversion H; clear H; subst\n\n  | _ => progress cbn [fst snd map option_map] in *\n  end.\n\nLtac Econstructor :=\n  match goal with\n  | |- Forall2 (eval _ _) _ _ =>  econstructor\n  | |- eval _ _ ?e _ => econstructor\n  end.\n\nLtac t := repeat (step || Econstructor || eauto || (progress cbn [interp0_op interp_op] in * ) ).\n\nDefinition slice0 :=\n  fun e => match e with\n    ExprApp (slice 0 s, [(ExprApp ((addZ|mulZ|negZ|shlZ|shrZ|andZ|orZ|xorZ) as o, args))]) =>\n        ExprApp ((match o with addZ=>add s|mulZ=>mul s|negZ=>neg s|shlZ=>shl s|shrZ => shr s|andZ => and s| orZ => or s|xorZ => xor s |_=>old 0%N 999999%N end), args)\n      | _ => e end.\nGlobal Instance slice0_ok : Ok slice0. Proof using Type. t. Qed.\n\nDefinition slice01_addcarryZ :=\n  fun e => match e with\n    ExprApp (slice 0 1, [(ExprApp (addcarryZ s, args))]) =>\n        ExprApp (addcarry s, args)\n      | _ => e end.\nGlobal Instance slice01_addcarryZ_ok : Ok slice01_addcarryZ.\nProof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.\n\nDefinition slice01_subborrowZ :=\n  fun e => match e with\n    ExprApp (slice 0 1, [(ExprApp (subborrowZ s, args))]) =>\n        ExprApp (subborrow s, args)\n      | _ => e end.\nGlobal Instance slice01_subborrowZ_ok : Ok slice01_subborrowZ.\nProof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.\n\nDefinition slice_set_slice :=\n  fun e => match e with\n    ExprApp (slice 0 s1, [ExprApp (set_slice 0 s2, [_; e'])]) =>\n      if N.leb s1 s2 then ExprApp (slice 0 s1, [e']) else e | _ => e end.\nGlobal Instance slice_set_slice_ok : Ok slice_set_slice.\nProof using Type. t. f_equal. Z.bitblast. Qed.\n\nDefinition set_slice_set_slice :=\n  fun e => match e with\n    ExprApp (set_slice lo1 s1, [ExprApp (set_slice lo2 s2, [x; e']); y]) =>\n      if andb (N.eqb lo1 lo2) (N.leb s2 s1) then ExprApp (set_slice lo1 s1, [x; y]) else e | _ => e end.\nGlobal Instance set_slice_set_slice_ok : Ok set_slice_set_slice.\nProof using Type. t. f_equal. Z.bitblast. Qed.\n\nDefinition set_slice0_small :=\n  fun e => match e with\n    ExprApp (set_slice 0 s, [x; y]) =>\n      match bound_expr x, bound_expr y with Some a, Some b =>\n      if Z.leb a (Z.ones (Z.of_N s)) && Z.leb b (Z.ones (Z.of_N s)) then y\n      else e | _, _ => e end | _ => e end%bool.\nGlobal Instance set_slice0_small_ok : Ok set_slice0_small.\nProof using Type.\n  t.\n  eapply Zle_bool_imp_le in H0; rewrite Z.ones_equiv in H0; eapply Z.lt_le_pred in H0.\n  eapply Zle_bool_imp_le in H1; rewrite Z.ones_equiv in H1; eapply Z.lt_le_pred in H1.\n  assert ((0 <= y < 2^Z.of_N sz)%Z) by Lia.lia; clear dependent z.\n  assert ((0 <= y0 < 2^Z.of_N sz)%Z) by Lia.lia; clear dependent z0.\n  rewrite ?Z.shiftl_0_r, Z.land_ones, Z.mod_small by Lia.lia.\n  destruct (Z.eq_dec y 0); subst.\n  { rewrite Z.ldiff_0_l, Z.lor_0_r; trivial. }\n  rewrite Z.ldiff_ones_r_low, Z.lor_0_r; try Lia.lia.\n  eapply Z.log2_lt_pow2; Lia.lia.\nQed.\n\nDefinition truncate_small :=\n  fun e => match e with\n    ExprApp (slice 0%N s, [e']) =>\n      match bound_expr e' with Some b =>\n      if Z.leb b (Z.ones (Z.of_N s))\n      then e'\n      else e | _ => e end | _ => e end.\nGlobal Instance truncate_small_ok : Ok truncate_small. Proof using Type. t; []. cbn in *; eapply Z.land_ones_low_alt_ones; eauto. firstorder. Lia.lia. Qed.\n\nDefinition addcarry_bit :=\n  fun e => match e with\n    ExprApp (addcarry s, ([ExprApp (const a, nil);b])) =>\n      if option_beq Z.eqb (bound_expr b) (Some 1) then\n      match interp0_op (addcarry s) [a; 0], interp0_op (addcarry s) [a; 1] with\n      | Some 0, Some 1 => b\n      | Some 0, Some 0 => ExprApp (const 0, nil)\n      | _, _ => e\n      end else e | _ => e end%Z%bool.\nGlobal Instance addcarry_bit_ok : Ok addcarry_bit.\nProof using Type.\n  repeat step;\n    [instantiate (1:=G) in E0; instantiate (1:=G) in E1|];\n    destruct (Reflect.reflect_eq_option (eqA:=Z.eqb) (bound_expr e) (Some 1%Z)) in E;\n      try discriminate; repeat step;\n    assert (y0 = 0 \\/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];\n      subst; repeat step; repeat Econstructor; cbn; congruence.\nQed.\n\nDefinition addoverflow_bit :=\n  fun e => match e with\n    ExprApp (addoverflow s, ([ExprApp (const a, nil);b])) =>\n      if option_beq Z.eqb (bound_expr b) (Some 1%Z) then\n      match interp0_op (addoverflow s) [a; 0] , interp0_op (addoverflow s) [a; 1] with\n      | Some 0, Some 1 => b\n      | Some 0, Some 0 => ExprApp (const 0, nil)\n      | _, _ => e\n      end else e | _ => e end%Z%bool.\nGlobal Instance addoverflow_bit_ok : Ok addoverflow_bit.\nProof using Type.\n  repeat step;\n    [instantiate (1:=G) in E0; instantiate (1:=G) in E1|];\n    destruct (Reflect.reflect_eq_option (eqA:=Z.eqb) (bound_expr e) (Some 1)%Z) in E;\n      try discriminate; repeat step;\n    assert (y0 = 0 \\/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];\n      subst; repeat step; repeat Econstructor; cbn; congruence.\nQed.\n\nDefinition addbyte_small :=\n  fun e => match e with\n    ExprApp (add (8%N as s), args) =>\n      match Option.List.lift (List.map bound_expr args) with\n      | Some bounds =>\n          if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))\n          then ExprApp (add 64%N, args)\n          else e | _ => e end | _ =>  e end.\nGlobal Instance addbyte_small_ok : Ok addbyte_small.\nProof using Type.\n  t; f_equal.\n  eapply bound_sum in H2; eauto.\n  rewrite Z.ones_equiv in E0; rewrite !Z.land_ones, !Z.mod_small; try Lia.lia;\n    replace (Z.of_N 8) with 8 in * by (vm_compute; reflexivity);\n    replace (Z.of_N 64) with 64 in * by (vm_compute; reflexivity); Lia.lia.\nQed.\n\nDefinition addcarry_small :=\n  fun e => match e with\n    ExprApp (addcarry s, args) =>\n      match Option.List.lift (List.map bound_expr args) with\n      | Some bounds =>\n          if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))\n          then (ExprApp (const 0, nil))\n          else e | _ => e end | _ =>  e end.\nGlobal Instance addcarry_small_ok : Ok addcarry_small.\nProof using Type.\n  t; f_equal.\n  eapply bound_sum in H2; eauto.\n  rewrite Z.ones_equiv in E0; rewrite Z.shiftr_div_pow2, Z.div_small; cbn; Lia.lia.\nQed.\n\nLemma signed_small s v (Hv : (0 <= v <= Z.ones (Z.of_N s-1))%Z) : signed s v = v.\nProof using Type.\n  destruct (N.eq_dec s 0); subst; cbv [signed].\n  { rewrite Z.land_0_r. cbn in *; Lia.lia. }\n  rewrite !Z.land_ones, !Z.shiftl_mul_pow2, ?Z.add_0_r, ?Z.mul_1_l by Lia.lia.\n  rewrite Z.ones_equiv in Hv.\n  rewrite Z.mod_small; try ring.\n  enough (2 ^ Z.of_N s = 2 ^ (Z.of_N s - 1) + 2 ^ (Z.of_N s - 1))%Z; try Lia.lia.\n  replace (Z.of_N s) with (1+(Z.of_N s-1))%Z at 1 by Lia.lia.\n  rewrite Z.pow_add_r; try Lia.lia.\nQed.\n\nDefinition addoverflow_small :=\n  fun e => match e with\n    ExprApp (addoverflow s, ([_]|[_;_]|[_;_;_]) as args) =>\n      match Option.List.lift (List.map bound_expr args) with\n      | Some bounds =>\n          if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s-1))\n          then (ExprApp (const 0, nil))\n          else e | _ => e end | _ =>  e end.\nGlobal Instance addoverflow_small_ok : Ok addoverflow_small.\nProof using Type.\n  t; cbv [Option.List.lift Option.bind fold_right] in *;\n  BreakMatch.break_match_hyps; Option.inversion_option; t;\n  epose proof Z.ones_equiv (Z.of_N s -1).\n  all : rewrite Z.land_ones, !Z.mod_small, !signed_small, !Z.eqb_refl; trivial.\n  all : try split; try Lia.lia.\n  all : replace (Z.of_N s) with (1+(Z.of_N s-1))%Z at 1 by Lia.lia;\n  rewrite Z.pow_add_r; try Lia.lia.\n  all : destruct s; cbn in E0; Lia.lia.\nQed.\n\nDefinition constprop :=\n  fun e => match interp0_expr e with\n           | Some v => ExprApp (const v, nil)\n           | _ => e end.\nGlobal Instance constprop_ok : Ok constprop.\nProof using Type. t. f_equal; eauto using eval_eval. Qed.\n\n(* convert unary operations to slice *)\nDefinition unary_truncate :=\n  fun e => match e with\n    ExprApp (o, [x]) =>\n    match unary_truncate_size o with\n    | Some (-1)%Z => x\n    | Some 0%Z => ExprApp (const 0, nil)\n    | Some (Zpos p)\n      => ExprApp (slice 0%N (Npos p), [x])\n    | _ => e end | _ => e end.\n\nGlobal Instance unary_truncate_ok : Ok unary_truncate.\nProof using Type.\n  t.\n  all: repeat first [ progress cbv [unary_truncate_size] in *\n                    | progress cbn [fold_right Z.of_N] in *\n                    | progress change (Z.of_N 0) with 0 in *\n                    | progress change (Z.ones 0) with 0 in *\n                    | apply (f_equal (@Some _))\n                    | lia\n                    | progress autorewrite with zsimplify_const\n                    | progress break_innermost_match_hyps\n                    | match goal with\n                      | [ H : Z.of_N ?s = 0 |- _ ] => is_var s; destruct s; try lia\n                      | [ H : Z.of_N ?s = Z.pos _ |- _ ] => is_var s; destruct s; try lia\n                      | [ H : Z.pos _ = Z.pos _ |- _ ] => inversion H; clear H\n                      end\n                    | progress t ].\nQed.\n\nLemma fold_right_filter_identity_gen A B C f init F G xs\n      (Hid : forall x y, F x = false -> G (f x y) = G y)\n      (HProper : forall x y y', G y = G y' -> G (f x y) = G (f x y'))\n  : G (@fold_right A B f init (filter F xs)) = G (@fold_right A B f init xs) :> C.\nProof.\n  induction xs as [|x xs IH]; [ | specialize (Hid x) ]; cbn; break_innermost_match; cbn; rewrite ?Hid by auto; auto; congruence.\nQed.\n\nLemma fold_right_filter_identity A B f init F xs\n      (Hid : forall x y, F x = false -> f x y = y)\n  : @fold_right A B f init (filter F xs) = @fold_right A B f init xs.\nProof.\n  apply fold_right_filter_identity_gen with (G:=id); cbv [id]; intuition (subst; eauto).\nQed.\n\nLemma signed_0 s : signed s 0 = 0%Z.\nProof using Type.\n  destruct (N.eq_dec s 0); subst; trivial.\n  cbv [signed].\n  rewrite !Z.land_ones, !Z.shiftl_mul_pow2, ?Z.add_0_r, ?Z.mul_1_l by Lia.lia.\n  rewrite Z.mod_small; try ring.\n  split; try (eapply Z.pow_lt_mono_r; Lia.lia).\n  eapply Z.pow_nonneg; Lia.lia.\nQed.\nHint Rewrite signed_0 : zsimplify_const zsimplify zsimplify_fast.\nGlobal Hint Resolve signed_0 : zarith.\n\nLemma interp_op_drop_identity o id : identity o = Some id ->\n  forall G xs, interp_op G o xs = interp_op G o (List.filter (fun v => negb (Z.eqb v id)) xs).\nProof using Type.\n  destruct o; cbn [identity]; intro; inversion_option; subst; intros G xs; cbn [interp_op]; f_equal.\n  all: break_innermost_match_hyps; inversion_option; subst.\n  all: rewrite ?fold_right_map.\n  all: rewrite ?fold_right_filter_identity by now intros; reflect_hyps; subst; auto with zarith; autorewrite with zsimplify_const; lia.\n  all: repeat first [ reflexivity\n                    | progress autorewrite with zsimplify_const ].\n  { (idtac + symmetry); apply fold_right_filter_identity_gen with (G:=fun x => Z.land x _).\n    all: intros; reflect_hyps; subst.\n    all: rewrite <- ?Z.land_assoc, ?(Z.land_comm (Z.ones _)), ?Z.land_ones in * by lia.\n    all: push_Zmod; pull_Zmod.\n    all: congruence. }\nQed.\n\nLemma interp_op_drop_identity_after_0 o id : identity_after_0 o = Some id ->\n  forall G x xs, interp_op G o (x :: xs) = interp_op G o (x :: List.filter (fun v => negb (Z.eqb v id)) xs).\nProof using Type.\n  destruct o; cbn [identity_after_0]; intro; inversion_option; subst; intros G x xs; cbn [interp_op]; f_equal.\n  all: rewrite ?fold_right_map.\n  all: rewrite ?fold_right_filter_identity by now intros; reflect_hyps; subst; auto with zarith; autorewrite with zsimplify_const; lia.\n  all: repeat first [ reflexivity\n                    | progress autorewrite with zsimplify_const ].\nQed.\n\nLemma interp_op_nil_is_identity o i (Hi : identity o = Some i)\n  G : interp_op G o [] = Some i.\nProof using Type.\n  destruct o; cbn [identity] in *; break_innermost_match_hyps; inversion_option; subst; cbn [interp_op fold_right]; f_equal.\n  all: cbn [interp_op fold_right]; autorewrite with zsimplify_const; try reflexivity.\n  { cbn [identity]; break_innermost_match; try reflexivity.\n    rewrite Z.land_ones by lia; Z.rewrite_mod_small; try reflexivity;\n      (* compat with older versions of Coq (needed for 8.11, not for 8.13) *)\n      rewrite Z.mod_small; rewrite ?Z.log2_lt_pow2; cbn [Z.log2]; try lia. }\nQed.\n\nLemma interp_op_always_interps G o args\n  : op_always_interps o = true -> interp_op G o args <> None.\nProof. destruct o; cbn; congruence. Qed.\n\nLemma interp0_op_always_interps o args\n  : op_always_interps o = true -> interp0_op o args <> None.\nProof. apply interp_op_always_interps. Qed.\n\n(* completeness check, just update the definition if this doesn't go through *)\nLemma interp_op_always_interps_complete o\n  : op_always_interps o = false -> exists G args, interp_op G o args = None.\nProof.\n  destruct o; cbn; try solve [ inversion 1 ]; intros _; do 2 try eapply ex_intro.\n  all: repeat match goal with\n              | [ |- match ?ev with [] => None | _ => _ end = None ] => let __ := open_constr:(eq_refl : ev = []) in cbv beta iota\n              | [ |- match ?ev with _ :: _ => None | _ => _ end = None ] => let __ := open_constr:(eq_refl : ev = _ :: _) in cbv beta iota\n              | [ |- None = None ] => reflexivity\n              end.\n  Unshelve. all: shelve_unifiable.\n  all: lazymatch goal with\n       | [ |- Z ] => exact 0%Z\n       | [ |- _ -> option _ ] => intro; exact None\n       | [ |- list _ ] => exact nil\n       | _ => idtac\n       end.\n  all: fail_if_goals_remain ().\nQed.\n\nLemma invert_interp_op_associative o : associative o = true ->\n  forall G x xs v, interp_op G o (x :: xs) = Some v ->\n  exists v', interp_op G o xs = Some v' /\\\n  interp_op G o [x; v'] = Some v.\nProof using Type.\n  destruct o; inversion 1; intros * HH; inversion HH; clear HH; subst; cbn;\n    eexists; split; eauto; f_equal; try ring; try solve [Z.bitblast].\n  { rewrite !Z.add_0_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }\n  { rewrite !Z.mul_1_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }\nQed.\n\n(** TODO: plausibly we want to define all associative operations in terms of some [make_associative_op] definition, so that we can separate out the binary operation reasoning from the fold and option reasoning *)\n(* is it okay for associative to imply identity? *)\nLemma interp_op_associative_spec_fold o : associative o = true ->\n  forall G xs, interp_op G o xs = fold_right (fun v acc => acc <- acc; interp_op G o [v; acc])%option (interp_op G o []) xs.\nProof using Type.\n  intros H G; induction xs as [|x xs IHxs]; cbn [fold_right]; [ reflexivity | ].\n  rewrite <- IHxs; clear IHxs.\n  destruct o; inversion H; cbn [interp_op Option.bind fold_right]; f_equal.\n  all: autorewrite with zsimplify_const.\n  all: try solve [ Z.bitblast ].\n  all: try solve [ rewrite ?Z.land_ones in *; push_Zmod; pull_Zmod; Lia.lia ].\nQed.\n\nLemma interp_op_associative_spec_id o : associative o = true ->\n  forall G, interp_op G o [] = identity o.\nProof using Type.\n  intros H G.\n  pose proof (fun id H => interp_op_nil_is_identity o id H G) as H1.\n  destruct o; inversion H; cbn [identity] in *; break_innermost_match_hyps; erewrite H1; try reflexivity.\nQed.\n\nLemma interp_op_associative_identity_Some o : associative o = true ->\n  forall G xs vxs, interp_op G o xs = Some vxs -> Option.is_Some (identity o) = true.\nProof using Type.\n  intros H G xs vxs H1; rewrite <- interp_op_associative_spec_id with (G:=G) by assumption.\n  rewrite interp_op_associative_spec_fold in H1 by assumption.\n  cbv [is_Some]; break_innermost_match; try reflexivity.\n  exfalso.\n  clear -H1.\n  revert dependent vxs; induction xs as [|?? IH]; cbn in *; intros; inversion_option.\n  unfold Option.bind at 1 in H1; break_innermost_match_hyps; eauto.\nQed.\n\nLemma interp_op_associative_spec_assoc o : associative o = true ->\n  forall G ys vys, interp_op G o ys = Some vys ->\n  forall   zs vzs, interp_op G o zs = Some vzs ->\n  forall x, ((xy <- interp_op G o [x; vys]; interp_op G o [xy; vzs]) = (yz <- interp_op G o [vys; vzs]; interp_op G o [x; yz]))%option.\nProof.\n  destruct o; inversion 1; intros * H1 * H2; cbn [interp_op fold_right Option.bind] in *.\n  all: intros; autorewrite with zsimplify_const; f_equal; inversion_option.\n  all: rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod; rewrite <- ?Z.land_ones by lia.\n  all: try solve [ f_equal; lia ].\n  all: try reflexivity.\n  all: try solve [ Z.bitblast ].\n  all: try lia.\nQed.\n\nLemma interp_op_associative_spec_concat o : associative o = true ->\n  forall G xs, interp_op G o (List.concat xs) = (vxs <-- List.map (interp_op G o) xs; interp_op G o vxs)%option.\nProof using Type.\n  intros H G; induction xs as [|x xs IHxs]; cbn [fold_right]; [ reflexivity | ].\n  cbn [List.concat List.map Option.List.bind_list].\n  rewrite interp_op_associative_spec_fold, fold_right_app, <- interp_op_associative_spec_fold by assumption.\n  rewrite IHxs; clear IHxs.\n  setoid_rewrite Option.List.bind_list_cps_id; rewrite <- Option.List.eq_bind_list_lift.\n  destruct (Option.List.lift (map (interp_op G o) xs)) as [vxs|]; cbn [Option.bind].\n  { revert vxs; clear xs.\n    induction x as [|x xs IHxs]; intro vxs.\n    { cbn [fold_right].\n      destruct (interp_op G o []) as [id|] eqn:H'; cbn [Option.bind].\n      { etransitivity; erewrite interp_op_drop_identity by (erewrite <- interp_op_associative_spec_id; eassumption); [ | reflexivity ].\n        cbn [List.filter]; unfold negb at 2; break_innermost_match_step; reflect_hyps; try congruence. }\n      { pose proof (interp_op_associative_identity_Some o H G vxs) as H1.\n        rewrite interp_op_associative_spec_id in * by assumption.\n        rewrite H' in *.\n        cbn [is_Some] in *.\n        destruct interp_op; try reflexivity; specialize (H1 _ eq_refl); congruence. } }\n    { cbn [fold_right].\n      rewrite IHxs; clear IHxs.\n      symmetry; rewrite interp_op_associative_spec_fold by assumption; cbn [fold_right]; rewrite <- interp_op_associative_spec_fold by assumption.\n      unfold Option.bind at 2; break_innermost_match_step; cbn [Option.bind]; [ | reflexivity ].\n      symmetry; rewrite interp_op_associative_spec_fold by assumption; cbn [fold_right]; rewrite <- interp_op_associative_spec_fold by assumption.\n      symmetry.\n      setoid_rewrite interp_op_associative_spec_fold at 2; [ | assumption ].\n      cbn [fold_right].\n      setoid_rewrite <- interp_op_associative_spec_fold; [ | assumption ].\n      destruct (interp_op G o vxs) eqn:?; cbn [Option.bind]; [ | cbv [Option.bind]; break_match; reflexivity ].\n      eapply interp_op_associative_spec_assoc; eassumption. } }\n  { etransitivity; [ | cbv [Option.bind]; break_innermost_match; reflexivity ].\n    induction x as [|? ? IHx]; cbn; rewrite ?IHx; reflexivity. }\nQed.\n\nLemma interp_op_associative_app_bind G o : associative o = true ->\n  forall xs ys,\n  interp_op G o (xs ++ ys) = (vxs <- interp_op G o xs; vys <- interp_op G o ys; interp_op G o [vxs; vys])%option.\nProof using Type.\n  intros.\n  etransitivity; [ etransitivity; [ | refine (interp_op_associative_spec_concat o H G [xs; ys]) ] | ].\n  { cbn [concat]; rewrite List.app_nil_r; reflexivity. }\n  { cbn [map Option.List.bind_list].\n    cbv [Option.bind]; break_innermost_match; reflexivity. }\nQed.\n\nLemma interp_op_associative_app G o : associative o = true ->\n  forall xs vxs, interp_op G o xs = Some vxs ->\n  forall ys vys, interp_op G o ys = Some vys ->\n  interp_op G o (xs ++ ys) = interp_op G o [vxs; vys].\nProof using Type.\n  intros H * H1 * H2.\n  rewrite interp_op_associative_app_bind, H1, H2 by assumption.\n  reflexivity.\nQed.\n\nLemma interp_op_associative_idempotent G o : associative o = true ->\n  forall xs vxs, interp_op G o xs = Some vxs ->\n  interp_op G o [vxs] = Some vxs.\nProof using Type.\n  intros H xs vxs H1.\n  pose proof (interp_op_associative_spec_concat o H G [ xs ]) as H2.\n  cbn in H2.\n  rewrite List.app_nil_r, H1 in H2; cbn [Option.bind] in *; congruence.\nQed.\n\nLemma interp_op_associative_cons o : associative o = true ->\n  forall G x xs ys v,\n  interp_op G o xs = Some v -> interp_op G o ys = Some v ->\n  interp_op G o (x :: xs) = interp_op G o (x :: ys).\nProof using Type.\n  intros H * H1 H2.\n  etransitivity; [ etransitivity | ]; [ | refine (interp_op_associative_spec_concat o H _ [ [x]; xs]) | ].\n  all: cbn [concat List.app map Option.List.bind_list]; rewrite ?List.app_nil_r.\n  1: reflexivity.\n  symmetry; etransitivity; [ etransitivity | ]; [ | refine (interp_op_associative_spec_concat o H _ [ [x]; ys]) | ].\n  all: cbn [concat List.app map Option.List.bind_list]; rewrite ?List.app_nil_r.\n  1: reflexivity.\n  rewrite !H1, H2; cbn [Option.bind].\n  reflexivity.\nQed.\n\nDefinition flatten_associative :=\n  fun e => match e with\n    ExprApp (o, args) =>\n    if associative o then\n      ExprApp (o, List.flat_map (fun e' =>\n        match e' with\n        | ExprApp (o', args') => if op_beq o o' then args' else [e']\n        | _ => [e'] end) args)\n    else e | _ => e end.\nGlobal Instance flatten_associative_ok : Ok flatten_associative.\nProof using Type.\n  repeat step.\n  revert dependent v; induction H2; cbn.\n  { econstructor; eauto. }\n  intros ? H4.\n  pose proof H4.\n  eapply invert_interp_op_associative in H4; eauto. destruct H4 as (?&?&?).\n  specialize (IHForall2 _ ltac:(eassumption)).\n  inversion IHForall2; subst.\n  destruct x as [i|[o' args''] ].\n  { econstructor. { econstructor. eauto. eauto. }\n    erewrite interp_op_associative_cons; eauto. }\n  { destruct (op_beq_spec o o'); subst; cycle 1.\n    { econstructor. { econstructor. eauto. eauto. }\n      erewrite interp_op_associative_cons; eauto. }\n    inversion H; clear H; subst.\n    econstructor; eauto using Forall2_app.\n    erewrite interp_op_associative_app; eauto. }\nQed.\n\nDefinition consts_commutative :=\n  fun e => match e with\n    ExprApp (o, args) =>\n    if commutative o then\n    let csts_exprs := List.partition isCst args in\n    if associative o\n    then match interp0_expr (ExprApp (o, fst csts_exprs)) with\n         | Some v => ExprApp (o, ExprApp (const v, nil):: snd csts_exprs)\n         | _ => ExprApp (o, fst csts_exprs ++ snd csts_exprs)\n         end\n    else ExprApp (o, fst csts_exprs ++ snd csts_exprs)\n    else e | _ => e end.\n\nGlobal Instance consts_commutative_ok : Ok consts_commutative.\nProof using Type.\n  step.\n  destruct e; trivial.\n  destruct n.\n  destruct commutative eqn:?; trivial.\n  inversion H; clear H; subst.\n  epose proof Permutation_partition l isCst.\n  eapply Permutation.Permutation_Forall2 in H2; [|eassumption].\n  DestructHead.destruct_head'_ex; DestructHead.destruct_head'_and.\n  epose proof permute_commutative  _ _ _ _ Heqb H4 _ H0.\n  repeat Econstructor; eauto.\n  destruct associative eqn:?; [|solve[repeat Econstructor; eauto] ].\n  BreakMatch.break_match; [|solve[repeat Econstructor; eauto] ].\n\n  set (fst (partition isCst l)) as csts in *; clearbody csts.\n  set (snd (partition isCst l)) as exps in *; clearbody exps.\n  clear dependent l. clear dependent args'.\n  move o at top; move Heqb0 at top; move Heqb at top.\n  eapply eval_interp0_expr in Heqo0; instantiate (1:=d) in Heqo0; instantiate (1:=G) in Heqo0.\n\n  eapply Forall2_app_inv_l in H1; destruct H1 as (?&?&?&?&?); subst.\n  rename x0 into xs. rename x1 into ys.\n  econstructor. { econstructor. econstructor. econstructor. exact eq_refl. eassumption. }\n\n  inversion Heqo0; clear Heqo0; subst.\n  eapply eval_eval_Forall2 in H; eauto; subst.\n  clear dependent exps. clear dependent csts.\n  clear -H2 H6 Heqb Heqb0.\n\n  change (?x :: ?xs) with ([x] ++ xs).\n  rewrite interp_op_associative_app_bind in * by assumption.\n  erewrite interp_op_associative_idempotent by eassumption; cbn [Option.bind].\n  unfold Option.bind in * |- .\n  break_innermost_match_hyps; inversion_option; subst; cbn [Option.bind].\n  assumption.\nQed.\n\nDefinition neqconst i := fun a : expr => negb (option_beq Z.eqb (interp0_expr a) (Some i)).\nDefinition drop_identity :=\n  fun e => match e with ExprApp (o, args) =>\n    match identity o with\n    | Some i =>\n        let args := List.filter (neqconst i) args in\n        match args with\n        | nil => ExprApp (const i, nil)\n        | _ => ExprApp (o, args)\n        end\n    | _ => match identity_after_0 o, args with\n    | Some i, arg :: args =>\n        let args := List.filter (neqconst i) args in\n        ExprApp (o, arg :: args)\n    | _, _ => e end end | _ => e end.\n\nLemma filter_neqconst_helper G d id\n      l args\n      (H : Forall2 (eval G d) l args)\n  : exists args',\n    Forall2 (eval G d) (filter (neqconst id) l) args'\n    /\\ List.filter (fun v => negb (Z.eqb v id)) args' = List.filter (fun v => negb (Z.eqb v id)) args.\nProof.\n  induction H; cbn; [ eexists; split; constructor | ].\n  destruct_head'_ex; destruct_head'_and.\n  unfold neqconst at 1.\n  unfold negb at 1; break_innermost_match_step; reflect_hyps.\n  all: unfold negb at 1; break_innermost_match_step; reflect_hyps.\n  all: repeat first [ match goal with\n                      | [ H : interp0_expr ?e = Some _, H' : eval ?Gv ?dv ?e _ |- _ ]\n                        => apply eval_interp0_expr with (G:=Gv) (d:=dv) in H\n                      end\n                    | progress reflect_hyps\n                    | congruence\n                    | progress subst\n                    | solve [ eauto ]\n                    | step; eauto; [] ].\n  all: econstructor; split; [ constructor; eassumption | cbn [filter] ].\n  all: unfold negb in *; break_innermost_match; reflect_hyps; try congruence.\nQed.\n\nLemma filter_neqconst G d o id\n      (Hid : identity o = Some id)\n      l args\n      (H : Forall2 (eval G d) l args)\n  : exists args',\n    Forall2 (eval G d) (filter (neqconst id) l) args'\n    /\\ interp_op G o args' = interp_op G o args.\nProof.\n  edestruct filter_neqconst_helper as [args' [H1 H2] ]; try eassumption.\n  exists args'; split; try eassumption.\n  erewrite interp_op_drop_identity, H2, <- interp_op_drop_identity by eassumption.\n  reflexivity.\nQed.\n\nLemma filter_neqconst' G d o id\n      (Hid : identity_after_0 o = Some id)\n      e arg l args\n      (H0 : eval G d e arg)\n      (H : Forall2 (eval G d) l args)\n  : exists args',\n    Forall2 (eval G d) (filter (neqconst id) l) args'\n    /\\ interp_op G o (arg :: args') = interp_op G o (arg :: args).\nProof.\n  edestruct filter_neqconst_helper as [args' [H1 H2] ]; try eassumption.\n  exists args'; split; try eassumption.\n  erewrite interp_op_drop_identity_after_0, H2, <- interp_op_drop_identity_after_0 by eassumption.\n  reflexivity.\nQed.\n\nGlobal Instance drop_identity_Ok : Ok drop_identity.\nProof using Type.\n  repeat (step; eauto; []).\n  inversion H; subst; clear H.\n  destruct identity eqn:?; [ | destruct identity_after_0 eqn:? ]; break_innermost_match.\n  all: repeat (step; eauto; []).\n  all: pose proof filter_neqconst.\n  all: pose proof filter_neqconst'.\n  all: specialize_under_binders_by eassumption.\n  all: destruct_head'_ex.\n  all: destruct_head'_and.\n  all: repeat first [ progress subst\n                    | progress inversion_option\n                    | match goal with\n                      | [ H : ?ls = nil, H' : context[?ls] |- _ ] => rewrite H in H'\n                      | [ H : ?ls = cons _ _, H' : context[?ls] |- _ ] => rewrite H in H'\n                      | [ H : Forall2 _ nil _ |- _ ] => inversion H; clear H\n                      | [ H : ?x = Some _, H' : context[?x] |- _ ] => rewrite H in H'\n                      end\n                    | erewrite interp_op_nil_is_identity in * by eassumption\n                    | solve [ t ] ].\nQed.\n\nDefinition fold_consts_to_and :=\n  fun e => match consts_commutative e with\n           | ExprApp ((and _ | andZ) as o, ExprApp (const v, nil) :: args)\n             => let v' := match o with\n                          | and sz => Z.land v (Z.ones (Z.of_N sz))\n                          | _ => v\n                          end in\n                if (v' <? 0)%Z\n                then if (v' =? -1)%Z\n                     then ExprApp (andZ, args)\n                     else ExprApp (andZ, ExprApp (const v', nil) :: args)\n                else let v_sz := (1 + Z.log2 v') in\n                     if (v' =? Z.ones v_sz)%Z\n                     then ExprApp (and (Z.to_N v_sz), args)\n                     else ExprApp (and (Z.to_N v_sz), ExprApp (const v', nil) :: args)\n           | _ => e\n           end.\n\nGlobal Instance fold_consts_to_and_Ok : Ok fold_consts_to_and.\nProof using Type.\n  repeat (step; eauto; []).\n  break_innermost_match; try assumption; reflect_hyps.\n  all: match goal with\n       | [ H : eval _ _ ?e _, H' : consts_commutative ?e = _ |- _ ]\n         => apply consts_commutative_ok in H; rewrite H' in H; clear e H'\n       end.\n  all: repeat (step; eauto; []).\n  all: cbn [interp_op fold_right] in *; inversion_option; subst.\n  all: repeat first [ match goal with\n                      | [ H : Z.land ?x ?y = _ |- context[Z.land (Z.land ?x _) ?y] ]\n                        => rewrite !(Z.land_comm x), <- !Z.land_assoc, H\n                      | [ |- context[Z.land ?x ?y] ]\n                        => match goal with\n                           | [ |- context[Z.land ?y ?x] ]\n                             => rewrite (Z.land_comm x y)\n                           end\n                      | [ H : ?x = Z.ones _ |- _ ]\n                        => is_var x; rewrite <- H\n                      | [ |- Z.land (Z.land ?x ?y) (Z.ones (1 + Z.log2 ?x)) = Z.land ?x ?y ]\n                        => rewrite !(Z.land_comm x), <- !Z.land_assoc; f_equal\n                      | [ |- Z.land (Z.land (Z.land ?y ?s) ?v) (Z.ones (1 + Z.log2 (Z.land ?y ?s))) = Z.land (Z.land ?y ?v) ?s ]\n                        => cut (Z.land (Z.land y s) (Z.ones (1 + Z.log2 (Z.land y s))) = Z.land y s);\n                           [ rewrite <- !(Z.land_comm v), <- !Z.land_assoc;\n                             let H := fresh in intro H; rewrite H; reflexivity\n                           | generalize dependent (Z.land y s); intros ]\n                      end\n                    | progress autorewrite with zsimplify_const\n                    | apply (f_equal (@Some _))\n                    | progress cbn [fold_right]\n                    | rewrite Z2N.id by auto with zarith\n                    | solve [ t ]\n                    | solve [ Z.bitblast; now rewrite Z.bits_above_log2 by lia ]\n                    | t ].\nQed.\n\nDefinition xor_same :=\n  fun e => match e with ExprApp (xor _,[x;y]) =>\n    if expr_beq x y then ExprApp (const 0, nil) else e | _ => e end.\nGlobal Instance xor_same_ok : Ok xor_same.\nProof using Type.\n  t; cbn [fold_right]. rewrite Z.lxor_0_r, Z.lxor_nilpotent; trivial.\nQed.\n\nDefinition shift_to_mul :=\n  fun e => match e with\n    ExprApp ((shl _ | shlZ) as o, [e'; ExprApp (const v, [])]) =>\n      let o' := match o with shl bitwidth => mul bitwidth | shlZ => mulZ | _ => o (* impossible *) end in\n      let bw := match o with shl bitwidth => Some bitwidth | shlZ => None | _ => None (* impossible *) end in\n      if Z.eqb v 0\n      then match bw with\n           | Some N0 => ExprApp (const 0, nil)\n           | Some (Npos p) => ExprApp (slice 0%N (Npos p), [e'])\n           | None => e'\n           end\n      else if Z.ltb 0 v\n      then ExprApp (o', [e'; ExprApp (const (2^v)%Z, [])])\n      else e | _ => e end.\nGlobal Instance shift_to_mul_ok : Ok shift_to_mul.\nProof. t; cbn in *; rewrite ?Z.shiftl_mul_pow2, ?Z.land_0_r by lia; repeat (lia + f_equal). Qed.\n\n(* o is like mul *)\n(* invariant: Forall2 (fun x '(y, z) => eval (o x i) matches eval (o y z)) input output *)\nDefinition split_consts (o : op) (i : Z) : list expr -> list (expr * Z)\n  := List.map\n       (fun e\n        => match e with\n           | ExprApp (o', args)\n             => if op_beq o' o\n                then\n                  let '(csts, exprs) :=\n                    if commutative o' && associative o'\n                    then let '(csts, exprs) := List.partition isCst args in\n                         (interp0_expr (ExprApp (o', csts)), exprs)\n                    else\n                      (* nest matches for fewer proof cases *)\n                      match match args with\n                            | [arg; ExprApp ((const c), _)]\n                              => Some (c, arg)\n                            | _ => None\n                            end with\n                      | Some (c, arg) => (Some c, [arg])\n                      | None => (Some i, args)\n                      end\n                  in\n                  match csts, exprs with\n                  | None, _ => (e, i)\n                  | Some c, [arg] => (arg, c)\n                  | Some c, args => (ExprApp (o', args), c)\n                  end\n                else (e, i)\n           | _ => (e, i)\n           end%bool).\n\n(* invariant: input is a permutation of concat (List.map (fun '(e, zs) => List.map (pair e) zs) output) *)\nDefinition group_consts (ls : list (expr * Z)) : list (expr * list Z)\n  := Option.List.map\n       (fun xs => match xs with\n                  | [] => None\n                  | (e, z) :: xs => Some (e, z :: List.map snd xs)\n                  end)\n       (List.groupAllBy (fun x y => expr_beq (fst x) (fst y)) ls).\n\n(* o is like add *)\n(* spec: if interp0_op o zs is always Some _, then Forall2 (fun '(e, zs) '(e', z) => e = e' /\\ interp0_op o zs = Some z) input output *)\nDefinition compress_consts (o : op) (ls : list (expr * list Z)) : list (expr * Z)\n  := List.flat_map\n       (fun '(e, zs) => match interp0_op o zs with\n                        | None => List.map (pair e) zs\n                        | Some z => [(e, z)]\n                        end)\n       ls.\n\n(* o is like mul *)\n(* spec is that Forall (fun '(e, z) e' => o (eval e) z matches eval e') inputs outputs *)\nDefinition app_consts (o : op) (ls : list (expr * Z)) : list expr\n  := List.map (fun '(e, z) => let z := ExprApp (const z, []) in\n                              let default := ExprApp (o, [e; z]) in\n                              if associative o\n                              then match e with\n                                   | ExprApp (o', args)\n                                     => if op_beq o' o\n                                        then ExprApp (o, args ++ [z])\n                                        else default\n                                   | _ => default end else default)\n              ls.\n\nDefinition combine_consts_pre : expr -> expr :=\n  fun e => match e with ExprApp (o, args) =>\n    if commutative o && associative o && op_always_interps o then match combines_to o with\n    | Some o' => match identity o' with\n    | Some idv =>\n        ExprApp (o, app_consts o' (compress_consts o (group_consts (split_consts o' idv args))))\n    | None => e end | None => e end else e | _ => e end%bool.\n\nDefinition cleanup_combine_consts : expr -> expr :=\n  let simp_outside := List.fold_left (fun e f => f e) [flatten_associative] in\n  let simp_inside := List.fold_left (fun e f => f e) [constprop;drop_identity;unary_truncate;truncate_small] in\n  fun e => simp_outside match e with ExprApp (o, args)  =>\n    ExprApp (o, List.map simp_inside args)\n                   | _ => e end.\n\nDefinition combine_consts : expr -> expr := fun e => cleanup_combine_consts (combine_consts_pre e).\n\nLemma split_consts_correct o i ls G d argsv\n      (H : Forall2 (eval G d) ls argsv)\n      (Hi : identity o = Some i)\n  : Forall2 (fun '(e, z) v => exists v', eval G d e v' /\\ (interp_op G o [v'; z] = Some v \\/ (z = i /\\ (v = v' \\/ interp_op G o [v'] = Some v)))) (split_consts o i ls) argsv.\nProof.\n  assert (eval G d (ExprApp (o, [])) i) by now econstructor; [ constructor | apply interp_op_nil_is_identity; assumption ].\n  cbv [split_consts].\n  revert dependent argsv; intro argsv.\n  revert argsv; induction ls as [|x xs IH], argsv as [|v argsv];\n    try specialize (IH argsv); intros; cbn [List.map];\n    invlist Forall2; specialize_by_assumption; constructor; try assumption; clear IH.\n  repeat first [ progress inversion_pair\n               | progress subst\n               | progress inversion_option\n               | progress inversion_list\n               | progress destruct_head'_ex\n               | progress destruct_head'_and\n               | progress reflect_hyps\n               | rewrite app_nil_r in *\n               | solve [ eauto 10 ]\n               | eapply ex_intro; split; [ now unshelve (repeat first [ eassumption | econstructor ]) | ]\n               | match goal with\n                 | [ |- (let '(x, y) := match ?v with _ => _ end in _) _ ]\n                   => tryif is_var v then destruct v else destruct v eqn:?\n                 | [ H : (match ?v with _ => _ end) = _ |- _ ]\n                   => tryif is_var v then destruct v else destruct v eqn:?\n                 | [ H : Forall2 _ (_ :: _) _ |- _ ] => rewrite Forall2_cons_l_ex_iff in H\n                 | [ H : Forall2 _ [] _ |- _ ] => rewrite Forall2_nil_l_iff in H\n                 | [ H : Forall _ (_ :: _) |- _ ] => rewrite Forall_cons_iff in H\n                 | [ H : Forall2 _ (_ ++ _) _ |- _ ] => apply Forall2_app_inv_l in H\n                 | [ H : interp_op _ (const _) _ = _ |- _ ] => cbn [interp_op] in H\n                 | [ H : andb _ _ = true |- _ ] => rewrite Bool.andb_true_iff in H\n                 | [ H : ?x = Some _, H' : ?x = Some _ |- _ ] => rewrite H in H'\n                 | [ H : context[interp_op _ _ (_ ++ _)] |- _ ] => rewrite interp_op_associative_app_bind in H by assumption; cbv [Crypto.Util.Option.bind] in H\n                 | [ H : partition _ _ = _ |- _ ]\n                   => let H' := fresh in\n                      pose proof H as H'; apply List.Forall_partition in H';\n                      let H' := fresh in\n                      pose proof H as H'; apply List.partition_eq_filter in H';\n                      apply List.partition_permutation in H\n                 | [ H : Permutation _ ?l, H' : Forall2 _ ?l ?args, H'' : interp_op _ _ ?args = Some _ |- _ ]\n                   => is_var args; eapply Permutation_Forall2 in H'; [ | symmetry; exact H ];\n                      let H''' := fresh in\n                      destruct H' as [? [H''' H'] ];\n                      eapply permute_commutative in H''; try exact H'''; try assumption; [];\n                      clear args H'''\n                 | [ H : eval _ _ (ExprApp _) _ |- _ ] => inversion H; clear H\n                 | [ H : interp0_expr (ExprApp _) = Some _ |- _ ]\n                   => eapply eval_interp0_expr in H\n                 | [ H : Forall2 (eval _ _) ?ls ?v1, H' : Forall2 (eval _ _) ?ls ?v2 |- _ ]\n                   => assert (v1 = v2) by (eapply eval_eval_Forall2; eassumption);\n                      clear H'\n                 | [ H : Permutation (@filter ?A ?f ?ls) ?ls |- _ ]\n                   => apply Permutation_length, List.filter_eq_length_eq in H;\n                      generalize dependent (@filter A f ls); intros; subst\n                 | [ H : interp_op _ ?o [?x] = Some _ |- context[interp_op _ ?o (?x :: ?ls)] ]\n                   => change (x :: ls) with ([x] ++ ls);\n                      rewrite interp_op_associative_app_bind, H by assumption;\n                      try erewrite interp_op_associative_idempotent by eassumption;\n                      cbn [Crypto.Util.Option.bind]\n                 | [ H : commutative ?o = true, H' : interp_op _ ?o [?a; ?b] = Some ?v |- interp_op _ ?o [?b; ?a] = Some ?v \\/ _ ]\n                   => left; erewrite permute_commutative; [ reflexivity | .. ]; try eassumption; rewrite Permutation_rev; reflexivity\n                 end\n               | erewrite <- interp_op_associative_app by eassumption ].\nQed.\n\nLemma group_consts_Permutation ls\n  : Permutation (List.concat (List.map (fun '(e, zs) => List.map (pair e) zs) (group_consts ls))) ls.\nProof.\n  cbv [group_consts].\n  let fv := match goal with |- context[List.groupAllBy ?f ls] => f end in\n  pose proof (@List.Forall_groupAllBy _ fv ls) as H;\n  etransitivity; [ | apply List.concat_groupAllBy with (f:=fv) ];\n  generalize dependent (List.groupAllBy fv ls); intro gfls; intros.\n  match goal with |- ?R ?x ?y => cut (x = y); [ intros ->; reflexivity | ] end.\n  apply f_equal.\n  induction H; [ reflexivity | ]; cbn.\n  break_innermost_match; cbn [List.map]; try solve [ exfalso; assumption ].\n  repeat (f_equal; try assumption; []).\n  cbn [fst snd] in *.\n  lazymatch goal with\n  | [ H : Forall _ ?ls |- map (pair _) (map snd ?ls) = ?ls ]\n    => revert H; clear\n  end.\n  intro H; induction H; destruct_head'_prod; cbn [List.map fst snd]; reflect_hyps; subst; cbn [fst snd].\n  all: f_equal; assumption.\nQed.\n\nLemma group_consts_nonempty ls\n  : Forall (fun '(e, zs) => zs <> nil) (group_consts ls).\nProof.\n  cbv [group_consts].\n  let fv := match goal with |- context[List.groupAllBy ?f ls] => f end in\n  pose proof (@List.Forall_groupAllBy_full _ fv ls) as H;\n  generalize dependent (List.groupAllBy fv ls); intro gfls; intros.\n  induction gfls as [|x xs IH]; cbn [list_rect Option.List.map fold_right] in *; break_innermost_match; destruct_head'_and; destruct_head'_False;\n    constructor; try congruence; eauto.\nQed.\n\nLemma compress_consts_correct o ls\n      (Ho : op_always_interps o = true)\n  : Forall2 (fun '(e, zs) '(e', z) => e = e' /\\ interp0_op o zs = Some z) ls (compress_consts o ls).\nProof.\n  cbv [compress_consts].\n  induction ls as [|x xs IH]; cbn [List.flat_map]; break_innermost_match; cbn [List.app];\n    try solve [ exfalso; eapply interp0_op_always_interps; eassumption ]; constructor; eauto.\nQed.\n\n(* in a more specific, usable form *)\nLemma compress_consts_correct_alt G d o' o ls argsv\n      (Ho : op_always_interps o = true)\n      (H : Forall2 (fun '(e, zs) v => exists z, interp0_op o zs = Some z /\\ exists v', (exists xs, interp_op G o' xs = Some z) /\\ eval G d e v' /\\ interp_op G o' [v'; z] = Some v) ls argsv)\n  : Forall2 (fun '(e, z) v => exists v', (exists xs, interp_op G o' xs = Some z) /\\ eval G d e v' /\\ interp_op G o' [v'; z] = Some v) (compress_consts o ls) argsv.\nProof.\n  eapply compress_consts_correct in Ho.\n  apply Forall2_flip in H.\n  eapply Forall2_trans in Ho; [ | exact H ].\n  apply Forall2_flip.\n  eapply Forall2_weaken; [ | eassumption ]; cbv beta.\n  intros; repeat (destruct_head'_ex || destruct_head'_prod || destruct_head'_and || subst).\n  repeat first [ progress inversion_option\n               | progress subst\n               | match goal with\n                 | [ H : ?x = Some _, H' : ?x = Some _ |- _ ] => rewrite H in H'\n                 end\n               | solve [ eauto ] ].\nQed.\n\nLemma app_consts_correct G d o ls argsv\n      (H : Forall2 (fun '(e, z) v => exists v', (exists xs, interp_op G o xs = Some z) /\\ eval G d e v' /\\ interp_op G o [v'; z] = Some v) ls argsv)\n  : Forall2 (eval G d) (app_consts o ls) argsv.\nProof.\n  cbv [app_consts].\n  induction H; cbn [List.map]; constructor.\n  all: repeat first [ assumption\n                    | progress destruct_head'_prod\n                    | progress destruct_head'_ex\n                    | progress destruct_head'_and\n                    | progress subst\n                    | progress reflect_hyps\n                    | break_innermost_match_step\n                    | match goal with\n                      | [ |- eval _ _ (ExprApp (_, [_; _])) _ ]\n                        => econstructor; [ | eassumption ]; unshelve (repeat (constructor; [ shelve | ])); [ .. | constructor ]\n                      | [ |- eval _ _ (ExprApp (const ?z, [])) _ ]\n                        => econstructor; [ constructor | reflexivity ]\n                      end\n                    | step; eauto; []\n                    | match goal with\n                      | [ |- eval _ _ (ExprApp (_, _ ++ _)) _ ]\n                        => econstructor; [ repeat first [ eassumption | apply Forall2_app | apply Forall2_cons | apply Forall2_nil ] | ]\n                      end\n                    | erewrite interp_op_associative_app; try eassumption; []\n                    | eapply interp_op_associative_idempotent; try eassumption ].\nQed.\n\nLemma combines_to_correct o o' v G xs vxs xsv\n      (H : combines_to o = Some o')\n      (H' : Forall2 (fun x vx => interp_op G o' [v; x] = Some vx) xs vxs)\n      (H'' : interp_op G o xs = Some xsv)\n  : interp_op G o' [v; xsv] = interp_op G o vxs.\nProof.\n  cbv [combines_to] in H; destruct o; inversion_option; subst.\n  all: cbn [interp_op fold_right] in *; inversion_option; subst; apply f_equal.\n  all: autorewrite with zsimplify_const in *.\n  all: rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.\n  all: eapply Forall2_weaken in H';\n    [\n    | intros *;\n      let H := fresh in\n      intro H;\n      inversion_option;\n      autorewrite with zsimplify_const in H;\n      rewrite ?Z.land_ones in H by lia; exact H ].\n  all: rewrite <- Forall2_map_l in H'.\n  all: apply Forall2_eq in H'; subst.\n  all: induction xs as [|x xs IH]; cbn [fold_right List.map]; autorewrite with zsimplify_const; try reflexivity.\n  all: push_Zmod; pull_Zmod.\n  all: revert IH; push_Zmod; intro IH; rewrite <- IH; clear IH; pull_Zmod.\n  all: rewrite <- Z.mul_add_distr_l.\n  all: reflexivity.\nQed.\n\n(* should this be factored differently? *)\nLemma interp_op_combines_to_idempotent G o o' (H : combines_to o = Some o') xs vxs\n  : interp_op G o xs = Some vxs -> interp_op G o' [vxs] = Some vxs.\nProof.\n  destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right]; intros; inversion_option; subst.\n  all: autorewrite with zsimplify_const.\n  all: apply f_equal; try reflexivity.\n  rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.\n  reflexivity.\nQed.\n\nLemma interp_op_combines_to_idempotent_rev G o o' (H : combines_to o = Some o') xs vxs\n  : interp_op G o' xs = Some vxs -> interp_op G o [vxs] = Some vxs.\nProof.\n  destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right]; intros; inversion_option; subst.\n  all: autorewrite with zsimplify_const.\n  all: apply f_equal; try reflexivity.\n  rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.\n  reflexivity.\nQed.\n\nLemma interp_op_combines_to_singleton_same_size G o o' (H : combines_to o = Some o') v\n  : interp_op G o [v] = interp_op G o' [v].\nProof.\n  destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right]; intros; inversion_option; subst.\n  all: autorewrite with zsimplify_const.\n  all: reflexivity.\nQed.\n\n(* a more general version useful for us *)\nLemma combines_to_correct_or o o' v G xs vxs xsv\n      (Ho : associative o = true)\n      (Ho' : op_always_interps o = true)\n      (H : combines_to o = Some o')\n      (H' : Forall2 (fun x vx => interp_op G o' [v; x] = Some vx \\/ interp_op G o' [v; x] = interp_op G o' [vx]) xs vxs)\n      (H'' : interp_op G o xs = Some xsv)\n  : interp_op G o' [v; xsv] = interp_op G o vxs.\nProof.\n  rewrite <- (List.concat_map_singleton vxs).\n  rewrite interp_op_associative_spec_concat, map_map by assumption.\n  rewrite Option.List.bind_list_cps_id, <- Option.List.eq_bind_list_lift; cbv [Crypto.Util.Option.bind]; break_match; revgoals.\n  { exfalso.\n    let H := match goal with H : _ = None |- _ => H end in\n    revert H; clear -Ho Ho'.\n    cbv [Option.List.lift].\n    induction vxs as [|?? IH]; cbn; cbv [Crypto.Util.Option.bind] in *; break_match; try congruence.\n    intro; eapply interp_op_always_interps; eassumption. }\n  eapply combines_to_correct; try eassumption.\n  let l := match goal with |- Forall2 _ _ ?l => l end in\n  revert dependent xsv; revert dependent l.\n  cbv [Option.List.lift] in *.\n  induction H'; cbn [List.map fold_right]; intros [|z xs]; intros; cbv [Crypto.Util.Option.bind] in *; break_match_hyps.\n  all: inversion_option; inversion_list; subst; constructor.\n  all: repeat first [ break_innermost_match_hyps_step\n                    | progress inversion_option\n                    | progress subst\n                    | assumption\n                    | match goal with\n                      | [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl)\n                      | [ H : context[?x :: ?l] |- _ ]\n                        => is_var x; is_var l; change (x :: l) with ([x] ++ l) in *;\n                           rewrite interp_op_associative_app_bind in H by assumption;\n                           cbv [Crypto.Util.Option.bind] in H\n                      | [ H : context[interp_op _ _ [_] ] |- _ ] => erewrite interp_op_combines_to_idempotent_rev in H by eassumption\n                      end\n                    | progress destruct_head'_or\n                    | erewrite interp_op_combines_to_singleton_same_size in * by eassumption\n                    | congruence ].\nQed.\n\nLemma combines_to_correct_alt G d o o' xs ys i z z1 e\n      (Ho : combines_to o = Some o')\n      (Hi : identity o' = Some i)\n      (Ha : associative o = true)\n      (Hai : op_always_interps o = true)\n      (H : Forall2 (fun x y => exists v', eval G d e v' /\\ (interp_op G o' [v'; x] = Some y \\/ (x = i /\\ (y = v' \\/ interp_op G o' [v'] = Some y)))) xs ys)\n      (H' : interp_op G o ys = Some z1)\n      (Hz : interp_op G o xs = Some z)\n      (Hnonempty : xs <> nil)\n  : exists v' : Z, (exists xs0 : list Z, interp_op G o' xs0 = Some z) /\\ eval G d e v' /\\ interp_op G o' [v'; z] = Some z1.\nProof.\n  cut (exists v', eval G d e v');\n    [ intros [ev ?]; exists ev\n    | match goal with\n      | [ H : Forall2 _ ?l _, H' : ?l <> [] |- _ ]\n        => inversion H; subst; try congruence; destruct_head'_ex; destruct_head'_and; eauto\n      end ].\n  repeat apply conj.\n  { eexists [_]; eapply interp_op_combines_to_idempotent; eassumption. }\n  { assumption. }\n  { rewrite <- H'.\n    eapply combines_to_correct_or; try eassumption.\n    clear z1 z H' Hz Hnonempty.\n    induction H; constructor; eauto.\n    repeat (destruct_head'_ex; destruct_head'_and; destruct_head'_or).\n    all: repeat (step; eauto; []); subst; eauto.\n    all: erewrite @interp_op_drop_identity in * by eassumption; cbn [filter] in *; cbv [negb] in *; break_innermost_match; break_innermost_match_hyps;\n      reflect_hyps; subst.\n    all: try congruence.\n    all: try now (idtac + left); apply interp_op_nil_is_identity.\n    all: eauto. }\nQed.\n\nLemma combine_consts_helper o o' G d ls args i\n      (H : Forall2\n             (fun '(e, zs) y =>\n                Forall2\n                  (fun '(e, z') (v : Z) =>\n                     exists v' : Z, eval G d e v' /\\ (interp_op G o' [v'; z'] = Some v \\/ (z' = i /\\ (v = v' \\/ interp_op G o' [v'] = Some v))))\n                  (map (pair e) zs) y)\n             ls args)\n      (Hi' : identity o' = Some i)\n      (Halways : op_always_interps o = true)\n      (Hassoc : associative o = true)\n      (Hc : combines_to o = Some o')\n      (Hnonempty : Forall (fun '(e, zs) => zs <> nil) ls)\n  : exists args',\n    interp_op G o (concat args) = interp_op G o args'\n    /\\ Forall2\n         (fun '(e, zs) (v0 : Z) =>\n            exists z' : Z,\n              interp0_op o zs = Some z' /\\\n                (exists v' : Z, (exists xs : list Z, interp_op G o' xs = Some z') /\\ eval G d e v' /\\ interp_op G o' [v'; z'] = Some v0))\n         ls args'.\nProof.\n  revert ls args H Hnonempty.\n  induction ls as [|x xs IH], args as [|arg args]; try specialize (IH args).\n  all: rewrite ?Forall2_nil_l_iff, ?Forall2_nil_r_iff, ?Forall2_cons_cons_iff; try congruence.\n  { exists nil; split; [ cbn; reflexivity | constructor ]. }\n  repeat first [ progress destruct_head_prod\n               | progress destruct_head_and\n               | progress destruct_head_ex\n               | progress intros\n               | progress specialize_by_assumption\n               | progress invlist Forall ].\n  match goal with\n  | [ |- ex ?P ] => cut (exists a b, P ([a] ++ b)); [ intros [a [b ?] ]; exists ([a] ++ b); assumption | ]\n  end.\n  cbv beta.\n  rewrite !interp_op_associative_app_bind by assumption.\n  setoid_rewrite interp_op_associative_app_bind; [ | assumption ].\n  cbv [Crypto.Util.Option.bind]; break_innermost_match; inversion_option; subst; do 2 eexists; break_innermost_match; split; try reflexivity.\n  all: repeat first [ progress inversion_option\n                    | match goal with\n                      | [ H : interp_op _ _ ?l = Some ?x, H' : interp_op _ _ [?v] = Some ?x' |- interp_op _ _ [?x; ?y] = interp_op _ _ [?x'; ?y'] ]\n                        => erewrite interp_op_associative_idempotent in H' by first [ exact H | assumption ]\n                      | [ H : Some _ = _ |- _ ] => symmetry in H\n                      | [ H : interp_op _ _ [?x] = _ |- _ ]\n                        => tryif is_evar x then fail else erewrite interp_op_associative_idempotent in H by eassumption\n                      | [ H : interp_op _ _ _ = None |- _ ]\n                        => apply interp_op_always_interps in H; [ exfalso | assumption ]\n                      end\n                    | progress subst\n                    | progress cbn [List.app]\n                    | apply Forall2_cons\n                    | eassumption\n                    | rewrite @Forall2_map_l_iff in *\n                    | match goal with\n                      | [ |- exists z, interp0_op ?o ?l = Some z /\\ _ ]\n                        => let H := fresh in\n                           destruct (interp0_op o l) eqn:H;\n                           [ eexists; split; [ reflexivity | ]\n                           | apply interp_op_always_interps in H; [ exfalso | assumption ] ]\n                      end ].\n  all: try congruence.\n  eapply combines_to_correct_alt; try ((idtac + eapply interp_op_interp0_op); eassumption).\n  Unshelve.\n  all: try solve [ constructor ].\nQed.\n\nGlobal Instance cleanup_combine_consts_Ok : Ok cleanup_combine_consts.\nProof.\n  repeat (step; eauto; []); cbn [fold_left].\n  repeat match goal with\n         | [ |- eval _ _ (?r ?e) _ ]\n           => apply (_:Ok r)\n         end.\n  econstructor; [ | eassumption ].\n  rewrite Forall2_map_l.\n  rewrite !@Forall2_forall_iff_nth_error in *; cbv [option_eq] in *.\n  intros.\n  repeat match goal with\n         | [ H : context[nth_error ?l] |- context[nth_error ?l ?i] ] => specialize (H i)\n         end.\n  break_innermost_match; eauto.\n  cbn [fold_left].\n  repeat lazymatch goal with\n  | H : eval ?c ?d ?e _ |- context[?r ?e] =>\n    let Hr := fresh in epose proof ((_:Ok r) _ _ _ _ H) as Hr; clear H\n  end.\n  assumption.\nQed.\n\nGlobal Instance combine_consts_pre_Ok : Ok combine_consts_pre.\nProof using Type.\n  repeat (step; eauto; []).\n  match goal with\n  | [ |- context[split_consts ?o ?i ?l] ]\n    => pose proof (@split_consts_correct o i l _ _ _ ltac:(eassumption) ltac:(assumption)) as Hs\n  end.\n  match goal with\n  | [ |- context[group_consts ?ls] ]\n    => pose proof (@group_consts_Permutation ls) as Hg;\n       pose proof (@group_consts_nonempty ls) as Hg'\n  end.\n  eapply Permutation_Forall2 in Hs; [ | symmetry; exact Hg ].\n  destruct Hs as [? [? Hs] ].\n  let H := match goal with H : interp_op _ _ _ = Some _ |- _ => H end in\n  eapply permute_commutative in H; [ | eassumption .. ].\n  rewrite Forall2_concat_l_ex_iff in Hs.\n  destruct Hs as [? [? Hs] ]; subst.\n  rewrite Forall2_map_l_iff in Hs.\n  eapply Forall2_weaken, combine_consts_helper in Hs; try assumption; try solve [ intros; destruct_head'_prod; eassumption ]; [ | try eassumption .. ].\n  destruct Hs as [? [? Hs] ].\n  econstructor; [ apply app_consts_correct, compress_consts_correct_alt; try assumption | ].\n  { eassumption. }\n  { congruence. }\nQed.\n\nGlobal Instance combine_consts_Ok : Ok combine_consts.\nProof. repeat step; apply cleanup_combine_consts_Ok, combine_consts_pre_Ok; assumption. Qed.\n\nDefinition expr : expr -> expr :=\n  List.fold_left (fun e f => f e)\n  [constprop\n  ;slice0\n  ;slice01_addcarryZ\n  ;slice01_subborrowZ\n  ;set_slice_set_slice\n  ;slice_set_slice\n  ;set_slice0_small\n  ;shift_to_mul\n  ;flatten_associative\n  ;consts_commutative\n  ;fold_consts_to_and\n  ;drop_identity\n  ;unary_truncate\n  ;truncate_small\n  ;combine_consts\n  ;addoverflow_bit\n  ;addcarry_bit\n  ;addcarry_small\n  ;addoverflow_small\n  ;addbyte_small\n  ;xor_same\n  ].\n\nLemma eval_expr c d e v : eval c d e v -> eval c d (expr e) v.\nProof using Type.\n  intros H; cbv [expr fold_left].\n  repeat lazymatch goal with\n  | H : eval ?c ?d ?e _ |- context[?r ?e] =>\n    let Hr := fresh in epose proof ((_:Ok r) _ _ _ _ H) as Hr; clear H\n  end.\n  eassumption.\nQed.\nEnd Rewrite.\n\nDefinition simplify (dag : dag) (e : node idx) :=\n  Rewrite.expr (reveal_node_at_least dag 3 e).\n\nLemma eval_simplify G d n v : eval_node G d n v -> eval G d (simplify d n) v.\nProof using Type. eauto using Rewrite.eval_expr, eval_node_reveal_node_at_least. Qed.\n\nDefinition reg_state := Tuple.tuple (option idx) 16.\nDefinition flag_state := Tuple.tuple (option idx) 6.\nDefinition mem_state := list (idx * idx).\n\nDefinition get_flag (st : flag_state) (f : FLAG) : option idx\n  := let '(cfv, pfv, afv, zfv, sfv, ofv) := st in\n     match f with\n     | CF => cfv\n     | PF => pfv\n     | AF => afv\n     | ZF => zfv\n     | SF => sfv\n     | OF => ofv\n     end.\nDefinition set_flag_internal (st : flag_state) (f : FLAG) (v : option idx) : flag_state\n  := let '(cfv, pfv, afv, zfv, sfv, ofv) := st in\n     (match f with CF => v | _ => cfv end,\n      match f with PF => v | _ => pfv end,\n      match f with AF => v | _ => afv end,\n      match f with ZF => v | _ => zfv end,\n      match f with SF => v | _ => sfv end,\n      match f with OF => v | _ => ofv end).\nDefinition set_flag (st : flag_state) (f : FLAG) (v : idx) : flag_state\n  := set_flag_internal st f (Some v).\nDefinition havoc_flag (st : flag_state) (f : FLAG) : flag_state\n  := set_flag_internal st f None.\nDefinition havoc_flags : flag_state\n  := (None, None, None, None, None, None).\nDefinition reverse_lookup_flag (st : flag_state) (i : idx) : option FLAG\n  := option_map\n       (@snd _ _)\n       (List.find (fun v => option_beq N.eqb (Some i) (fst v))\n                  (Tuple.to_list _ (Tuple.map2 (@pair _ _) st (CF, PF, AF, ZF, SF, OF)))).\n\nDefinition get_reg (st : reg_state) (ri : nat) : option idx\n  := Tuple.nth_default None ri st.\nDefinition set_reg (st : reg_state) ri (i : idx) : reg_state\n  := Tuple.from_list_default None _ (ListUtil.set_nth\n       ri\n       (Some i)\n       (Tuple.to_list _ st)).\nDefinition reverse_lookup_widest_reg (st : reg_state) (i : idx) : option REG\n  := option_map\n       (fun v => widest_register_of_index (fst v))\n       (List.find (fun v => option_beq N.eqb (Some i) (snd v))\n                  (List.enumerate (Tuple.to_list _ st))).\n\nDefinition load (a : idx) (s : mem_state) : option idx :=\n  option_map snd (find (fun p => fst p =? a)%N s).\nDefinition remove (a : idx) (s : mem_state) : list idx * mem_state :=\n  let '(vs, s) := List.partition (fun p => fst p =? a)%N s in\n  (List.map snd vs, s).\nDefinition store (a v : idx) (s : mem_state) : option mem_state :=\n  n <- indexof (fun p => fst p =? a)%N s;\n  Some (ListUtil.update_nth n (fun ptsto => (fst ptsto, v)) s).\nDefinition reverse_lookup_mem (st : mem_state) (i : idx) : option (N * idx)\n  := option_map\n       (fun '(n, (_, ptsto)) => (N.of_nat n, ptsto))\n       (List.find (fun v => N.eqb i (fst (snd v)))\n                  (List.enumerate st)).\n\nLocal Unset Boolean Equality Schemes.\nLocal Unset Decidable Equality Schemes.\nRecord symbolic_state := { dag_state :> dag ; symbolic_reg_state :> reg_state ; symbolic_flag_state :> flag_state ; symbolic_mem_state :> mem_state }.\nLocal Set Boolean Equality Schemes.\nLocal Set Decidable Equality Schemes.\n\nDefinition update_dag_with (st : symbolic_state) (f : dag -> dag) : symbolic_state\n  := {| dag_state := f st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.\nDefinition update_reg_with (st : symbolic_state) (f : reg_state -> reg_state) : symbolic_state\n  := {| dag_state := st.(dag_state); symbolic_reg_state := f st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.\nDefinition update_flag_with (st : symbolic_state) (f : flag_state -> flag_state) : symbolic_state\n  := {| dag_state := st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := f st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.\nDefinition update_mem_with (st : symbolic_state) (f : mem_state -> mem_state) : symbolic_state\n  := {| dag_state := st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := f st.(symbolic_mem_state) |}.\n\nGlobal Instance show_reg_state : Show reg_state := fun st =>\n  show (List.map (fun '(n, v) => (widest_register_of_index n, v)) (ListUtil.List.enumerate (Option.List.map id (Tuple.to_list _ st)))).\n\nGlobal Instance show_flag_state : Show flag_state :=\n  fun '(cfv, pfv, afv, zfv, sfv, ofv) => (\n  \"(*flag_state*)(CF=\"++show cfv\n  ++\" PF=\"++show pfv\n  ++\" AF=\"++show afv\n  ++\" ZF=\"++show zfv\n  ++\" SF=\"++show sfv\n  ++\" ZF=\"++show zfv\n  ++\" OF=\"++show ofv++\")\")%string.\nGlobal Instance show_lines_dag : ShowLines dag := (fun d:dag =>\n  [\"(*dag*)[\"]\n    ++List.map (fun '(i, v, descr) =>\"(*\"++show i ++\"*) \" ++ show v++\";\"\n                                         ++ (if dag.get_eager_description_always_show descr\n                                             then match dag.get_eager_description_description descr with\n                                                  | Some descr => \" \" ++ String.Tab ++ \"(*\" ++ descr ++ \"*)\"\n                                                  | None => \"\"\n                                                  end\n                                             else \"\"))%string (dag.eager.force d)\n  ++[\"]\"])%list%string.\nGlobal Instance show_lines_mem_state : ShowLines mem_state :=\n  @show_lines_list _ ShowLines_of_Show.\n\nGlobal Instance ShowLines_symbolic_state : ShowLines symbolic_state :=\n fun X : symbolic_state =>\n match X with\n | {|\n     dag_state := ds;\n     symbolic_reg_state := rs;\n     symbolic_flag_state := fs;\n     symbolic_mem_state := ms\n   |} =>\n   [\"(*symbolic_state*) {|\";\n   \"  dag_state :=\"] ++ show_lines ds ++ [\";\";\n   (\"  symbolic_reg_state := \" ++ show rs ++ \";\")%string;\n   (\"  symbolic_flag_state := \" ++ show fs ++\";\")%string;\n   \"  symbolic_mem_state :=\"] ++show_lines ms ++ [\";\";\n   \"|}\"]\n end%list%string.\n\n\nModule error.\n  Local Unset Boolean Equality Schemes.\n  Local Unset Decidable Equality Schemes.\n  Variant error :=\n  | get_flag (f : FLAG) (s : flag_state)\n  | get_reg (r : nat + REG) (s : reg_state)\n  | load (a : idx) (s : symbolic_state)\n  | remove (a : idx) (s : symbolic_state)\n  | remove_has_duplicates (a : idx) (vs : list idx) (s : symbolic_state)\n  | store (a v : idx) (s : symbolic_state)\n  | set_const (_ : CONST) (_ : idx)\n  | expected_const (_ : idx) (_ : expr)\n\n  | unsupported_memory_access_size (_:N)\n  | unsupported_label_in_memory (_:string)\n  | unsupported_label_argument (_:JUMP_LABEL)\n  | unimplemented_prefix (_:NormalInstruction)\n  | unimplemented_instruction (_ : NormalInstruction)\n  | unsupported_line (_ : RawLine)\n  | ambiguous_operation_size (_ : NormalInstruction)\n  .\n\n  Global Instance show_lines_error : ShowLines error\n    := fun e\n       => match e with\n          | get_flag f s\n            => [\"In flag state \" ++ show_flag_state s;\n                \"Flag \" ++ show f ++ \" was read without being set.\"]\n          | get_reg (inl i) s\n            => [\"Invalid reg index \" ++ show_nat i]\n          | get_reg (inr r) s\n            => [\"In reg state \" ++ show_reg_state s;\n                \"Register \" ++ show (r : REG) ++ \" read without being set.\"]\n          | load a s\n            => ([\"In mem state:\"]\n                  ++ show_lines_mem_state s\n                  ++ [\"Index \" ++ show a ++ \" loaded without being present.\"]%string)%list\n          | remove a s\n            => ([\"In mem state:\"]\n                  ++ show_lines_mem_state s\n                  ++ [\"Index \" ++ show a ++ \" removed without being present.\"]%string)%list\n          | remove_has_duplicates a ls s\n            => ([\"In mem state:\"]\n                  ++ show_lines_mem_state s\n                  ++ [\"Index \" ++ show a ++ \" occurs multiple times during removal (\" ++ show ls ++ \").\"]%string)%list\n          | store a v s\n            => ([\"In mem state:\"]\n                  ++ show_lines_mem_state s\n                  ++ [\"Index \" ++ show a ++ \" updated (with value \" ++ show v ++ \") without being present.\"]%string)%list\n          | set_const c i\n            => [\"SetOperand called with Syntax.const \" ++ show c ++ \" \" ++ show i]%string\n          | expected_const i x\n            => [\"RevealConst called at \" ++ show i ++ \" resulted in non-const value \" ++ show x]\n          | unsupported_memory_access_size n => [\"error.unsupported_memory_access_size \" ++ show n]\n          | unsupported_label_in_memory l => [\"error.unsupported_label_in_memory \" ++ l]\n          | unsupported_label_argument l => [\"error.unsupported_label_argument \" ++ show l]\n          | unimplemented_instruction n => [\"error.unimplemented_instruction \" ++ show n]\n          | unimplemented_prefix n => [\"error.unimplemented_prefix \" ++ show n]\n          | unsupported_line n => [\"error.unsupported_line \" ++ show n]\n          | ambiguous_operation_size n => [\"error.ambiguous_operation_size \" ++ show n]\n          end%string.\n  Global Instance Show_error : Show error := _.\nEnd error.\nNotation error := error.error.\n\nDefinition M T := symbolic_state -> ErrorT (error * symbolic_state) (T * symbolic_state).\nDefinition ret {A} (x : A) : M A :=\n  fun s => Success (x, s).\nDefinition err {A} (e : error) : M A :=\n  fun s => Error (e, s).\nDefinition some_or {A} (f : symbolic_state -> option A) (e : symbolic_state -> error) : M A :=\n  fun st => match f st with Some x => Success (x, st) | None => Error (e st, st) end.\nDefinition bind {A B} (x : M A) (f : A -> M B) : M B :=\n  fun s => (x_s <- x s; f (fst x_s) (snd x_s))%error.\nDefinition lift_dag {A} (v : dag.M A) : M A :=\n  fun s => let '(v, d) := v s.(dag_state) in\n           Success (v, update_dag_with s (fun _ => d)).\n\nDeclare Scope x86symex_scope.\nDelimit Scope x86symex_scope with x86symex.\nBind Scope x86symex_scope with M.\nNotation \"x <- y ; f\" := (bind y (fun x => f%x86symex)) : x86symex_scope.\nSection MapM. (* map over a list in the state monad *)\n  Context {A B} (f : A -> M B).\n  Fixpoint mapM (l : list A) : M (list B) :=\n    match l with\n    | nil => ret nil\n    | cons a l => b <- f a; bs <- mapM l; ret (cons b bs)\n    end%x86symex.\nEnd MapM.\nDefinition mapM_ {A B} (f: A -> M B) l : M unit := _ <- mapM f l; ret tt.\n\nDefinition error_get_reg_of_reg_index ri : symbolic_state -> error\n  := error.get_reg (let r := widest_register_of_index ri in\n                    if (reg_index r =? ri)%nat\n                    then inr r\n                    else inl ri).\n\nDefinition GetFlag f : M idx :=\n  some_or (fun s => get_flag s f) (error.get_flag f).\nDefinition GetReg64 ri : M idx :=\n  some_or (fun st => get_reg st ri) (error_get_reg_of_reg_index ri).\nDefinition Load64 (a : idx) : M idx := some_or (load a) (error.load a).\nDefinition Remove64 (a : idx) : M idx\n  := fun s => let '(vs, m) := remove a s in\n              match vs with\n              | [] => Error (error.remove a s, s)\n              | [v] => Success (v, update_mem_with s (fun _ => m))\n              | vs => Error (error.remove_has_duplicates a vs s, s)\n              end.\nDefinition SetFlag f i : M unit :=\n  fun s => Success (tt, update_flag_with s (fun s => set_flag s f i)).\nDefinition HavocFlags : M unit :=\n  fun s => Success (tt, update_flag_with s (fun _ => Tuple.repeat None 6)).\nDefinition PreserveFlag {T} (f : FLAG) (k : M T) : M T :=\n  vf <- (fun s => Success (get_flag s f, s));\n  x <- k;\n  _ <- (fun s => Success (tt, update_flag_with s (fun s => set_flag_internal s f vf)));\n  ret x.\nDefinition SetReg64 rn i : M unit :=\n  fun s => Success (tt, update_reg_with s (fun s => set_reg s rn i)).\nDefinition Store64 (a v : idx) : M unit :=\n  ms <- some_or (store a v) (error.store a v);\n  fun s => Success (tt, update_mem_with s (fun _ => ms)).\nDefinition Merge {descr : description} (e : expr) : M idx := fun s =>\n  let i_dag := merge e s in\n  Success (fst i_dag, update_dag_with s (fun _ => snd i_dag)).\nDefinition App {descr : description} (n : node idx) : M idx :=\n  fun s => Merge (simplify s n) s.\nDefinition Reveal n (i : idx) : M expr :=\n  fun s => Success (reveal s n i, s).\nDefinition RevealConst (i : idx) : M Z :=\n  x <- Reveal 1 i;\n  match x with\n  | ExprApp (const n, nil) => ret n\n  | _ => err (error.expected_const i x)\n  end.\n\nDefinition GetReg {descr:description} r : M idx :=\n  let '(rn, lo, sz) := index_and_shift_and_bitcount_of_reg r in\n  v <- GetReg64 rn;\n  App ((slice lo sz), [v]).\nDefinition SetReg {descr:description} r (v : idx) : M unit :=\n  let '(rn, lo, sz) := index_and_shift_and_bitcount_of_reg r in\n  if N.eqb sz 64\n  then v <- App (slice 0 64, [v]);\n       SetReg64 rn v (* works even if old value is unspecified *)\n  else old <- GetReg64 rn;\n       v <- App ((set_slice lo sz), [old; v]);\n       SetReg64 rn v.\n\nClass AddressSize := address_size : OperationSize.\nDefinition Address {descr:description} {sa : AddressSize} (a : MEM) : M idx :=\n  _ <- match a.(mem_base_label) with\n       | None => ret tt\n       | Some l => err (error.unsupported_label_in_memory l)\n       end;\n  base <- match a.(mem_base_reg) with\n           | Some r => GetReg r\n           | None => App ((const 0), nil)\n           end;\n  index <- match a.(mem_scale_reg) with\n           | Some (z, r) => z <- App (zconst sa z, []); r <- GetReg r; App (mul sa, [r; z])\n           | None => App ((const 0), nil)\n           end;\n  offset <- App (match a.(mem_offset) with\n                             | Some s => (zconst sa s, nil)\n                             | None => (const 0, nil) end);\n  bi <- App (add sa, [base; index]);\n  App (add sa, [bi; offset]).\n\nDefinition Load {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) : M idx :=\n  if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N\n  then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else\n  addr <- Address a;\n  v <- Load64 addr;\n  App ((slice 0 (Syntax.operand_size a s)), [v]).\n\nDefinition Remove {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) : M idx :=\n  if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N\n  then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else\n  addr <- Address a;\n  v <- Remove64 addr;\n  App ((slice 0 (Syntax.operand_size a s)), [v]).\n\nDefinition Store {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) v : M unit :=\n  if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N\n  then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else\n  addr <- Address a;\n  old <- Load64 addr;\n  v <- App (slice 0 (Syntax.operand_size a s), [v]);\n  v <- App (set_slice 0 (Syntax.operand_size a s), [old; v])%N;\n  Store64 addr v.\n\n(* note: this could totally just handle truncation of constants if semanics handled it *)\nDefinition GetOperand {descr:description} {s : OperationSize} {sa : AddressSize} (o : ARG) : M idx :=\n  match o with\n  | Syntax.const a => App (zconst s a, [])\n  | mem a => Load a\n  | reg r => GetReg r\n  | label l => err (error.unsupported_label_argument l)\n  end.\n\nDefinition SetOperand {descr:description} {s : OperationSize} {sa : AddressSize} (o : ARG) (v : idx) : M unit :=\n  match o with\n  | Syntax.const a => err (error.set_const a v)\n  | mem a => Store a v\n  | reg a => SetReg a v\n  | label l => err (error.unsupported_label_argument l)\n  end.\n\nLocal Unset Elimination Schemes.\nInductive pre_expr : Set :=\n| PreARG (_ : ARG)\n| PreFLG (_ : FLAG)\n| PreRef (_ : idx)\n| PreApp (_ : op) (_ : list pre_expr).\n(* note: need custom induction principle *)\nLocal Set Elimination Schemes.\nLocal Coercion PreARG : ARG >-> pre_expr.\nLocal Coercion PreFLG : FLAG >-> pre_expr.\nLocal Coercion PreRef : idx >-> pre_expr.\nExample __testPreARG_boring : ARG -> list pre_expr := fun x : ARG => @cons pre_expr x nil.\n(*\nExample __testPreARG : ARG -> list pre_expr := fun x : ARG => [x].\n*)\n\nFixpoint Symeval {descr:description} {s : OperationSize} {sa : AddressSize} (e : pre_expr) : M idx :=\n  match e with\n  | PreARG o => GetOperand o\n  | PreFLG f => GetFlag f\n  | PreRef i => ret i\n  | PreApp op args =>\n      idxs <- mapM Symeval args;\n      App (op, idxs)\n  end.\n\nDefinition rcrcnt s cnt : Z :=\n  if N.eqb s 8 then Z.land cnt 31 mod 9 else\n  if N.eqb s 16 then Z.land cnt 31 mod 17 else\n  Z.land cnt (Z.of_N s-1).\n\nNotation \"f @ ( x , y , .. , z )\" := (PreApp f (@cons pre_expr x (@cons pre_expr y .. (@cons pre_expr z nil) ..))) (at level 10) : x86symex_scope.\nDefinition SymexNormalInstruction {descr:description} (instr : NormalInstruction) : M unit :=\n  let stack_addr_size : AddressSize := 64%N in\n  let sa : AddressSize := 64%N in\n  match Syntax.operation_size instr with Some s =>\n  match Syntax.prefix instr with None =>\n  let s : OperationSize := s in\n  let resize_reg r := some_or (fun _ => reg_of_index_and_shift_and_bitcount_opt (reg_index r, 0%N (* offset *), s)) (fun _ => error.unimplemented_instruction instr) in\n  match instr.(Syntax.op), instr.(args) with\n  | (mov | movzx), [dst; src] => (* Note: unbundle when switching from N to Z *)\n    v <- GetOperand src;\n    SetOperand dst v\n  | xchg, [a; b] => (* Note: unbundle when switching from N to Z *)\n    va <- GetOperand a;\n    vb <- GetOperand b;\n    _ <- SetOperand b va;\n    SetOperand a vb\n  | cmovc, [dst; src]\n  | cmovb, [dst; src]\n    =>\n    v <- Symeval (selectznz@(CF, dst, src));\n    SetOperand dst v\n  | cmovnz, [dst; src] =>\n    v <- Symeval (selectznz@(ZF, src, dst));\n    SetOperand dst v\n  | seto, [dst] =>\n    of <- GetFlag OF;\n    SetOperand dst of\n  | setc, [dst] =>\n    cf <- GetFlag CF;\n    SetOperand dst cf\n  | Syntax.add, [dst; src] =>\n    v <- Symeval (add s@(dst, src));\n    c <- Symeval (addcarry s@(dst, src));\n    o <- Symeval (addoverflow s@(dst, src));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    _ <- SetFlag CF c;\n    SetFlag OF o\n  | Syntax.adc, [dst; src] =>\n    v <- Symeval (add s@(dst, src, CF));\n    c <- Symeval (addcarry s@(dst, src, CF));\n    o <- Symeval (addoverflow s@(dst, src, CF));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    _ <- SetFlag CF c;\n    SetFlag OF o\n  | (adcx|adox) as op, [dst; src] =>\n    let f := match op with adcx => CF | _ => OF end in\n    v <- Symeval (add s@(dst, src, f));\n    c <- Symeval (addcarry s@(dst, src, f));\n    _ <- SetOperand dst v;\n    SetFlag f c\n  | Syntax.sub, [dst; src] =>\n    v <- Symeval (add       s@(dst, PreApp (neg s) [PreARG src]));\n    c <- Symeval (subborrow s@(dst, src));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    SetFlag CF c\n  | Syntax.sbb, [dst; src] =>\n    v <- Symeval (add         s@(dst, PreApp (neg s) [PreARG src], PreApp (neg s) [PreFLG CF]));\n    c <- Symeval (subborrow s@(dst, src, CF));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    SetFlag CF c\n  | lea, [reg dst; mem src] =>\n    a <- Address src;\n    SetOperand dst a\n  | imul, ([dst as src1; src2] | [dst; src1; src2]) =>\n    v <- Symeval (mulZ@(src1,src2));\n    _ <- SetOperand dst v;\n    HavocFlags\n  | Syntax.xor, [dst; src] =>\n    v <- Symeval (xorZ@(dst,src));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    zero <- Symeval (PreApp (const 0) nil);\n    _ <- SetFlag CF zero;\n    SetFlag OF zero\n  | Syntax.and, [dst; src] =>\n    v <- Symeval (andZ@(dst,src));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    zero <- Symeval (PreApp (const 0) nil); _ <- SetFlag CF zero; SetFlag OF zero\n  | Syntax.bzhi, [dst; src; cnt] =>\n    cnt <- GetOperand cnt;\n    cnt <- RevealConst cnt;\n    v <- Symeval (andZ@(src,PreApp (const (Z.ones (Z.land cnt (Z.ones 8)))) nil));\n    _ <- SetOperand dst v;\n    _ <- HavocFlags;\n    zero <- App (const 0, nil); SetFlag OF zero\n  | Syntax.rcr, [dst; cnt] =>\n    x <- GetOperand dst;\n    cf <- GetFlag CF;\n    cnt <- GetOperand cnt; cnt <- RevealConst cnt; let cnt := rcrcnt s cnt in\n    cntv <- App (const cnt, nil);\n    y <- App (rcr s, [x; cf; cntv]);\n    _ <- SetOperand dst y;\n    _ <- HavocFlags;\n    if (cnt =? 1)%Z\n    then cf <- App ((slice 0 1), cons (x) nil); SetFlag CF cf\n    else ret tt\n  | mulx, [hi; lo; src2] =>\n    let src1 : ARG := rdx in\n    v  <- Symeval (mulZ@(src1,src2));\n    vh <- Symeval (shrZ@(v,PreARG (Z.of_N s)));\n    _ <- SetOperand lo v;\n         SetOperand hi vh\n  | (Syntax.mul | imul), [src2] =>\n    let src1 : ARG := rax in\n    v  <- Symeval (mulZ@(src1,src2));\n    vh <- Symeval (shrZ@(v,PreARG (Z.of_N s)));\n    lo <- resize_reg rax;\n    hi <- (if (s =? 8)%N\n           then ret ah\n           else resize_reg rdx);\n    _ <- SetOperand (lo:ARG) v;\n    _ <- SetOperand (hi:ARG) vh;\n    HavocFlags (* This is conservative and can be made more precise *)\n  | Syntax.shl, [dst; cnt] =>\n    let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in\n    v <- Symeval (shl s@(dst, cnt));\n    _ <- SetOperand dst v;\n    HavocFlags\n  | Syntax.shlx, [dst; src; cnt] =>\n    cnt <- GetOperand cnt;\n    cnt <- RevealConst cnt;\n    let cnt' := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in\n    v <- Symeval (shl s@(src, cnt'));\n    SetOperand dst v\n  | Syntax.shr, [dst; cnt] =>\n    let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in\n    v <- Symeval (shr s@(dst, cnt));\n    _ <- SetOperand dst v;\n    HavocFlags\n  | Syntax.sar, [dst; cnt] =>\n    x <- GetOperand dst;\n    let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in\n    c <- Symeval cnt; rc <- Reveal 1 c;\n    y <- App (sar s, [x; c]);\n    _ <- SetOperand dst y;\n    _ <- HavocFlags;\n    if expr_beq rc (ExprApp (const 1%Z, nil))\n    then (\n      cf <- App ((slice 0 1), cons (x) nil);\n      _ <- SetFlag CF cf;\n      zero <- App (const 0, nil); SetFlag OF zero)\n    else ret tt\n  | shrd, [lo as dst; hi; cnt] =>\n    let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in\n    let cnt' := addZ@(Z.of_N s, PreApp negZ [cnt]) in\n    v <- Symeval (or s@(shr s@(lo, cnt), shl s@(hi, cnt')));\n    _ <- SetOperand dst v;\n    HavocFlags\n  | inc, [dst] =>\n    v <- Symeval (add s@(dst, PreARG 1%Z));\n    o <- Symeval (addoverflow s@(dst, PreARG 1%Z));\n    _ <- SetOperand dst v;\n    _ <- PreserveFlag CF HavocFlags;\n    SetFlag OF o\n  | dec, [dst] =>\n    v <- Symeval (add s@(dst, PreARG (-1)%Z));\n    o <- Symeval (addoverflow s@(dst, PreARG (-1)%Z));\n    _ <- SetOperand dst v;\n    _ <- PreserveFlag CF HavocFlags;\n    SetFlag OF o\n  | test, [ea;eb] =>\n    a <- GetOperand ea;\n    b <- GetOperand eb;\n    zero <- App (const 0, nil);\n    _ <- HavocFlags;\n    _ <- SetFlag CF zero;\n    _ <- SetFlag OF zero;\n    if Equality.ARG_beq ea eb\n    then zf <- App (iszero, [a]); SetFlag ZF zf\n    else ret tt\n  | clc, [] => zero <- Merge (@ExprApp (const 0, nil)); SetFlag CF zero\n  | push, [src]\n    => v    <- GetOperand src;\n       rsp' <- GetOperand (s:=stack_addr_size) rsp;\n       rsp' <- Symeval (s:=stack_addr_size) (add stack_addr_size@(rsp', PreARG (-(Z.of_N s/8))%Z));\n       _    <- SetOperand rsp rsp';\n               SetOperand (mem_of_reg rsp) v\n  | pop, [dst]\n    => v    <- GetOperand (mem_of_reg rsp);\n       rsp' <- GetOperand (s:=stack_addr_size) rsp;\n       rsp' <- Symeval (s:=stack_addr_size) (add stack_addr_size@(rsp', PreARG ((Z.of_N s/8)%Z)));\n       _    <- SetOperand rsp rsp';\n               SetOperand dst v\n  | _, _ => err (error.unimplemented_instruction instr)\n end\n  | Some prefix => err (error.unimplemented_prefix instr) end\n  | None => err (error.ambiguous_operation_size instr) end%N%x86symex.\n\nDefinition SymexRawLine {descr:description} (rawline : RawLine) : M unit :=\n  match rawline with\n  | EMPTY\n  | LABEL _\n    => ret tt\n  | INSTR instr\n    => SymexNormalInstruction instr\n  | SECTION _\n  | GLOBAL _\n  | ALIGN _\n  | DEFAULT_REL\n      => err (error.unsupported_line rawline)\n  end.\n\nDefinition SymexLine line :=\n  let descr:description := Build_description (show line) false in\n  SymexRawLine line.(rawline).\n\nFixpoint SymexLines (lines : Lines) : M unit\n  := match lines with\n     | [] => ret tt\n     | line :: lines\n       => (st <- SymexLine line;\n          SymexLines lines)\n     end.\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/Symbolic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2942149721629888, "lm_q1q2_score": 0.15055468660837515}}
{"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 TableDataOpsIntro.Specs.table_create.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition table_create1_spec (g_rd: Pointer) (map_addr: Z64) (level: Z64) (g_rtt': Pointer) (rtt_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match map_addr, level, rtt_addr with\n    | VZ64 map_addr, VZ64 level, VZ64 rtt_addr =>\n      rely is_int64 map_addr; rely is_int64 rtt_addr; rely GRANULE_ALIGNED map_addr; rely is_int64 level;\n      let idx0 := __addr_to_idx map_addr 0 in\n      let idx1 := __addr_to_idx map_addr 1 in\n      let idx2 := __addr_to_idx map_addr 2 in\n      let idx3 := __addr_to_idx map_addr 3 in\n      let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n      let rtt_gidx := __addr_to_gidx rtt_addr in\n      rely is_gidx rtt_gidx;\n      rely (peq (base g_rd) ginfo_loc);\n      rely (peq (base g_rtt') ginfo_loc);\n      rely (offset g_rtt' =? rtt_gidx);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n      let rd_gidx := (offset g_rd) in\n      let grd := (gs (share adt)) @ rd_gidx in\n      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);\n      rely prop_dec (glock grd = Some CPU_ID);\n      let root_gidx := (g_rtt (gnorm grd)) in\n      rely is_gidx rd_gidx; rely is_gidx root_gidx;\n      when adt == query_oracle adt;\n      (* hold root lock *)\n      let groot := (gs (share adt)) @ root_gidx in\n      rely (tbl_level (gaux groot) =? 0);\n      rely prop_dec (glock groot = None);\n      if level =? 1 then\n        (* walk until root *)\n        let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n        let adt :=  adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n        create_table root_gidx idx0 rtt_addr rtt_gidx rd_gidx 1 map_addr adt\n      else\n        (* walk deeper root *)\n        rely (level >? 1);\n        rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n        rely (gtype groot =? GRANULE_STATE_TABLE);\n        let entry0 := (g_data (gnorm groot)) @ idx0 in\n        rely is_int64 entry0;\n        let phys0 := __entry_to_phys entry0 3 in\n        let lv1_gidx := __addr_to_gidx phys0 in\n        if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then\n          (* level 1 valid, hold level 1 lock *)\n          let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n          let glv1 := (gs (share adt)) @ lv1_gidx in\n          rely prop_dec (glock glv1 = None);\n          rely (tbl_level (gaux glv1) =? 1);\n          if level =? 2 then\n            (* walk until level 1 *)\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n            create_table lv1_gidx idx1 rtt_addr rtt_gidx rd_gidx 2 map_addr adt\n          else\n            (* walk deeper level 1 *)\n            rely (level >? 2);\n            rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n            rely (gtype glv1 =? GRANULE_STATE_TABLE);\n            let entry1 := (g_data (gnorm glv1)) @ idx1 in\n            rely is_int64 entry1;\n            let phys1 := __entry_to_phys entry1 3 in\n            let lv2_gidx := __addr_to_gidx phys1 in\n            if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then\n              (* level 2 valid, hold level 2 lock *)\n              let adt := adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv2_gidx) :: log adt} in\n              let glv2 := (gs (share adt)) @ lv2_gidx in\n              rely (tbl_level (gaux glv2) =? 2);\n              rely prop_dec (glock glv2 = None);\n              if level =? 3 then\n                (* walk until level 2 *)\n                let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n                create_table lv2_gidx idx2 rtt_addr rtt_gidx rd_gidx 3 map_addr adt\n              else None\n            else\n              (* level 2 invalid *)\n              Some (adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: log adt}\n                        {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)\n        else\n          (* level 1 invalid *)\n          Some (adt {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, 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/TableDataOpsRef1/Specs/table_create1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2751297297667525, "lm_q1q2_score": 0.15042392000870045}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\n\nRequire Import SemanticsKuniv.\nRequire Import SemanticsUniv.\nRequire Import Defined.\nRequire Import PageType.\nRequire Import ProperLevel.\n\n\n\nLemma sound_kuniv_formation :\n  forall G lv lv',\n    pseq G (deq lv lv' pagetp)\n    -> pseq G (deqtype (kuniv lv) (kuniv lv')).\nProof.\nintros G lv1 lv2.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseq.\nrewrite -> seq_eqtype.\nrewrite -> seq_deq in Hseq.\nintros i s s' Hs.\nso (Hseq i s s' Hs) as (R & Hpagetp & _ & Hlv1 & Hlv2 & Hlv12).\nso (interp_pagetp_invert _#7 Hpagetp Hlv1) as (pg & Hlv1l & Hlv1r).\nso (interp_pagetp_invert _#7 Hpagetp Hlv2) as (pg' & Hlv2l & Hlv2r).\nso (interp_pagetp_invert _#7 Hpagetp Hlv12) as (pg'' & Hlv1l' & Hlv2r').\nso (pginterp_fun _#3 Hlv1l Hlv1l'); subst pg''.\nso (pginterp_fun _#3 Hlv2r Hlv2r'); subst pg'.\nso (pginterp_lt_top _ _ Hlv1l) as hl.\nso (pginterp_succ_lt_top _ _ hl Hlv1l) as hls.\nexists (iukuniv the_system i pg hl).\nsimpsub.\ndo2 3 split;\napply interp_eval_refl; apply interp_kuniv; eauto using pginterp_str_top, pginterp_cex_top.\nQed.\n\n\nLocal Ltac prove_hygiene :=\n  repeat (first [ apply hygiene_shift_permit\n                | apply hygiene_sumbool\n                | apply natlit_closed\n                | apply hygiene_auto; cbn; 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 pginterp_succ :\n  forall lv pg h,\n    pginterp lv pg\n    -> pginterp (nsucc lv) (succ_page pg h).\nProof.\nintros lv pg h Hlv.\ndestruct Hlv as (w & Hint & Hstr & Hcex & Hcin).\ndestruct Hint as (l & Hint & ->).\nassert (natinterp (nsucc lv) (S l)) as Hint'.\n  {\n  apply natinterp_nsucc; auto.\n  }\nexists (fin (S l)); do2 3 split; cbn; auto.\n  {\n  exists (S l); auto.\n  }\n\n  {\n  rewrite -> Hstr.\n  apply succ_fin.\n  }\n\n  {\n  rewrite -> Hcex.\n  apply succ_fin.\n  }\n\n  {\n  rewrite -> Hcex.\n  apply succ_fin.\n  }\nQed.\n\n\nLemma sound_kuniv_formation_univ :\n  forall G lv lv1 lv2,\n    pseq G (deq lv1 lv2 pagetp)\n    -> pseq G (deq lv lv pagetp)\n    -> pseq G (deq triv triv (ltpagetp (nsucc lv1) lv))\n    -> pseq G (deq (kuniv lv1) (kuniv lv2) (univ lv)).\nProof.\nintros G lv lv1 lv2.\nrevert G.\nrefine (seq_pseq 0 3 [] _ [] _ [] _ _ _); cbn.\nintros G Hseqlv12 Hseqlv Hseqlt.\nrewrite seq_deq in Hseqlv12, Hseqlv, Hseqlt |- *.\nintros i s s' Hs.\nso (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').\nso (Hseqlv12 _#3 Hs) as (R & Hpagetp & _ & Hlv1 & Hlv2 & Hlv12).\nso (interp_pagetp_invert _#7 Hpagetp Hlv1) as (pg & Hlv1l & Hlv1r).\nso (interp_pagetp_invert _#7 Hpagetp Hlv2) as (pg' & Hlv2l & Hlv2r).\nso (interp_pagetp_invert _#7 Hpagetp Hlv12) as (pg'' & Hlv1l' & Hlv2r').\nso (pginterp_fun _#3 Hlv1l Hlv1l'); subst pg''.\nso (pginterp_fun _#3 Hlv2r Hlv2r'); subst pg'.\nclear R Hpagetp Hlv1 Hlv2 Hlv12.\nso (Hseqlv _#3 Hs) as (R & Hpagetp & _ & Hlv & _).\nso (interp_pagetp_invert _#7 Hpagetp Hlv) as (pg' & Hlvl & Hlvr).\nclear R Hpagetp Hlv.\nso (Hseqlt _#3 Hs) as (R & Hintlt & _ & Hinhlt & _).\nso (pginterp_lt_top _ _ Hlv1l) as hl.\nsimpsubin Hintlt.\nso (pginterp_succ _ _ hl Hlv1l) as Hlvsucc.\nso (interp_ltpagetp_invert _#11 Hintlt Hinhlt Hlvsucc Hlvl) as Hlt.\nso (lt_le_page_trans _#3 (lt_page_succ _ hl) (lt_page_impl_le_page _ _ Hlt)) as Hlt'.\ndestruct Hlt as (Hltstr & Hltcex).\ndestruct Hlt' as (Hltstr' & Hltcex').\nexists (iuuniv the_system i pg').\nsimpsub.\nassert (sint the_system pg' true i (kuniv (subst s lv1)) (iukuniv the_system i pg hl)) as Hintlv1l.\n  {\n  rewrite -> sint_unroll.\n  apply interp_eval_refl.\n  apply interp_kuniv; auto.\n  split; auto.\n  }\nassert (sint the_system pg' false i (kuniv (subst s' lv1)) (iukuniv the_system i pg hl)) as Hintlv1r.\n  {\n  rewrite -> sint_unroll.\n  apply interp_eval_refl.\n  apply interp_kuniv; auto.\n  split; auto.\n  }\nassert (sint the_system pg' true i (kuniv (subst s lv2)) (iukuniv the_system i pg hl)) as Hintlv2l.\n  {\n  rewrite -> sint_unroll.\n  apply interp_eval_refl.\n  apply interp_kuniv; auto.\n  split; auto.\n  }\nassert (sint the_system pg' false i (kuniv (subst s' lv2)) (iukuniv the_system i pg hl)) as Hintlv2r.\n  {\n  rewrite -> sint_unroll.\n  apply interp_eval_refl.\n  apply interp_kuniv; auto.\n  split; auto.\n  }\ndo2 4 split;\ntry (apply interp_eval_refl; apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top; done);\ntry (cbn; split; auto; exists (iukuniv the_system i pg hl); auto).\nQed.\n\n\nLemma sound_kuniv_weaken :\n  forall G lv a b,\n    pseq G (deq a b (kuniv lv))\n    -> pseq G (deq a b (univ (nsucc lv))).\nProof.\nintros G lv a b.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseq.\nrewrite -> seq_eqkind in Hseq.\nrewrite -> seq_univ.\nintros i s s' Hs.\nso (Hseq _#3 Hs) as (pg & K & R & hl & Hlvl & Hlvr & _ & _ & _ & _ & Hal & Har & Hbl & Hbr).\nset (pg' := succ_page pg hl).\nexists pg', R.\nsimpsub.\ndo2 5 split; auto.\n  {\n  apply pginterp_succ; auto.\n  }\n\n  {\n  apply pginterp_succ; auto.\n  }\nQed.\n\n\nLemma sound_kuniv_formation_invert :\n  forall G lv lv',\n    pseq G (deqtype (kuniv lv) (kuniv lv'))\n    -> pseq G (deq lv lv' pagetp).\nProof.\nintros G l m.\nrevert G.\nrefine (seq_pseq 0 1 [] _ _ _); cbn.\nintros G Hseq.\nrewrite -> seq_eqtype in Hseq.\nrewrite -> seq_deq.\nintros i s s' Hs.\nso (Hseq _#3 Hs) as (R & Hll & Hlr & Hml & Hmr).\nsimpsubin Hll.\nsimpsubin Hlr.\nsimpsubin Hml.\nsimpsubin Hmr.\ninvert (basic_value_inv _#6 value_kuniv Hll).\nintros pg h Hpgll _ Heq.\ninvert (basic_value_inv _#6 value_kuniv Hlr).\nintros pg' h' Hpglr _ Heq'.\nso (iukuniv_inj _#7 (eqtrans Heq (eqsymm Heq'))); subst pg'.\nclear Heq'.\nso (proof_irrelevance _ h h'); subst h'.\ninvert (basic_value_inv _#6 value_kuniv Hml).\nintros pg' h' Hpgml _ Heq'.\nso (iukuniv_inj _#7 (eqtrans Heq (eqsymm Heq'))); subst pg'.\nclear Heq'.\nso (proof_irrelevance _ h h'); subst h'.\ninvert (basic_value_inv _#6 value_kuniv Hmr).\nintros pg' h' Hpgmr _ Heq'.\nso (iukuniv_inj _#7 (eqtrans Heq (eqsymm Heq'))); subst pg'.\nclear Heq Heq'.\nso (proof_irrelevance _ h h'); subst h'.\nexists (nattp_def top i).\nsimpsub.\ndestruct Hpgll as (w & Hpgll & Heq & _).\ndestruct Hpglr as (w' & Hpglr & Heq' & _).\nso (eqtrans (eqsymm Heq) Heq'); clear Heq'; subst w'.\ndestruct Hpgml as (w' & Hpgml & Heq' & _).\nso (eqtrans (eqsymm Heq) Heq'); clear Heq'; subst w'.\ndestruct Hpgmr as (w' & Hpgmr & Heq' & _).\nso (eqtrans (eqsymm Heq) Heq'); clear Heq'; subst w'.\nclear h Heq pg.\ndestruct Hpgll as (j & Hpgll & Heq).\ndestruct Hpglr as (j' & Hpglr & Heq').\ninjection (eqtrans (eqsymm Heq) Heq').\nintros <-; clear Heq'.\ndestruct Hpgml as (j' & Hpgml & Heq').\ninjection (eqtrans (eqsymm Heq) Heq').\nintros <-; clear Heq'.\ndestruct Hpgmr as (j' & Hpgmr & Heq').\ninjection (eqtrans (eqsymm Heq) Heq').\nintros <-; clear Heq'.\nclear Heq.\nso (succ_nodecrease top) as Htop.\ndo2 4 split.\n  {\n  apply interp_nattp.\n  }\n\n  {\n  apply interp_nattp.\n  }\n\n  {\n  rewrite -> nattp_nat_urel; auto.\n  exists j.\n  do2 2 split; auto.\n  }\n\n  {\n  rewrite -> nattp_nat_urel; auto.\n  exists j.\n  do2 2 split; auto.\n  }\n\n  {\n  rewrite -> nattp_nat_urel; auto.\n  exists j.\n  do2 2 split; 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/SoundKuniv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.15006162918070792}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of VMM                                          *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the MPTComm layer, which will initialize the common part (0-1G, 3G-4G) of all the page tables*)\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 CalRealPTPool.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import CalRealIDPDE.\nRequire Import CalRealPT.\nRequire Import CalRealInitPTE.\n\nRequire Import AbstractDataType.\n\nRequire Export MPTOp.\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Section PTALLOCPDE.\n\n      Lemma ptAllocPDE_high_level_inv:\n        forall d d' n vadr v,\n          ptAllocPDE_spec n vadr d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0; constructor_gso_simpl_tac.\n        - intros; eapply AT_kern_norm'; eauto.\n        - intros; eapply AT_usr_norm; eauto.\n        - eapply alloc_container_valid'; eauto.\n        - apply ptAllocPDE_quota_bounded_AT in H; auto.\n        - apply consistent_ppage_norm_hide; try assumption. \n        - intros; congruence.\n        - eapply dirty_ppage_gss; eauto.\n        - intros; congruence.\n      Qed.\n\n      Lemma ptAllocPDE_low_level_inv:\n        forall d d' n vadr v n',\n          ptAllocPDE_spec n vadr d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma ptAllocPDE_kernel_mode:\n        forall d d' n vadr v,\n          ptAllocPDE_spec n vadr d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance ptAllocPDE_inv: PreservesInvariants ptAllocPDE_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTALLOCPDE.\n\n    Section PTPFREEPDE.\n\n      Lemma ptFreePDE_high_level_inv:\n        forall d d' n vadr,\n          ptFreePDE_spec n vadr d = Some d' ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0; constructor_gso_simpl_tac.\n        - intros; eapply AT_kern_norm; eauto. \n        - intros; eapply AT_usr_norm; eauto.\n        - apply pfree_quota_bounded_AT; auto.\n        - apply consistent_ppage_norm_undef; try assumption. \n        - intros; congruence.\n        - eapply dirty_ppage_gso_undef; eauto.\n        - intros; congruence.\n      Qed.\n\n      Lemma ptFreePDE_low_level_inv:\n        forall d d' n vadr n',\n          ptFreePDE_spec n vadr d = Some d' ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma ptFreePDE_kernel_mode:\n        forall d d' n vadr,\n          ptFreePDE_spec n vadr d = Some d' ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance ptFreePDE_inv: PreservesInvariants ptFreePDE_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptFreePDE_low_level_inv; eassumption.\n        - eapply ptFreePDE_high_level_inv; eassumption.\n        - eapply ptFreePDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTPFREEPDE.\n    \n    Global Instance pt_init_comm_inv: PreservesInvariants pt_init_comm_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n      - apply real_nps_range.\n      - apply real_at_kern_valid.\n      - apply real_at_usr_valid.\n      - apply real_container_valid.\n      - apply real_quota_bounded_AT.\n      - rewrite init_pperm; try assumption.\n        apply real_pperm_valid.        \n    Qed.\n\n  End INV.\n\n  (** * Layer Definition *)\n  (** ** Layer Definition newly introduced  *)\n  Definition mptcommon_fresh : compatlayer (cdata RData) :=\n    pt_alloc_pde \u21a6 gensem ptAllocPDE_spec\n                 \u2295 pt_free_pde \u21a6 gensem ptFreePDE_spec\n                 \u2295 pt_init_comm \u21a6 gensem pt_init_comm_spec.\n\n  (** ** Layer Definition passthrough  *)\n  Definition mptcommon_passthrough : compatlayer (cdata RData) :=\n    fload \u21a6 gensem fload_spec\n          \u2295 fstore \u21a6 gensem fstore_spec\n          \u2295 flatmem_copy \u21a6 gensem flatmem_copy_spec\n          \u2295 vmxinfo_get \u21a6 gensem vmxinfo_get_spec\n          \u2295 device_output \u21a6 gensem device_output_spec\n          \u2295 set_pg \u21a6 gensem setPG1_spec\n          \u2295 at_get_c \u21a6 gensem get_at_c_spec\n          \u2295 at_set_c \u21a6 gensem set_at_c0_spec\n          \u2295 pfree \u21a6 gensem pfree'_spec\n          \u2295 set_pt \u21a6 gensem setPT'_spec\n          \u2295 set_PDE \u21a6 gensem setPDE_spec\n\n          \u2295 pt_read \u21a6 gensem ptRead_spec\n          \u2295 pt_read_pde \u21a6 gensem ptReadPDE_spec\n          \u2295 pt_insert_aux \u21a6 gensem ptInsertAux_spec\n          \u2295 pt_rmv_aux \u21a6 gensem ptRmvAux_spec\n\n          \u2295 pt_in \u21a6 primcall_general_compatsem' ptin'_spec (prim_ident:= pt_in)\n          \u2295 pt_out \u21a6 primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          \u2295 clear_cr2 \u21a6 gensem clearCR2_spec\n          \u2295 container_get_parent \u21a6 gensem container_get_parent_spec\n          \u2295 container_get_nchildren \u21a6 gensem container_get_nchildren_spec\n          \u2295 container_get_quota \u21a6 gensem container_get_quota_spec\n          \u2295 container_get_usage \u21a6 gensem container_get_usage_spec\n          \u2295 container_can_consume \u21a6 gensem container_can_consume_spec\n          \u2295 container_split \u21a6 gensem container_split_spec\n          \u2295 container_alloc \u21a6 gensem container_alloc_spec\n          \u2295 trap_in \u21a6 primcall_general_compatsem trapin_spec\n          \u2295 trap_out \u21a6 primcall_general_compatsem trapout_spec\n          \u2295 host_in \u21a6 primcall_general_compatsem hostin_spec\n          \u2295 host_out \u21a6 primcall_general_compatsem hostout_spec\n          \u2295 trap_get \u21a6 primcall_trap_info_get_compatsem trap_info_get_spec\n          \u2295 trap_set \u21a6 primcall_trap_info_ret_compatsem trap_info_ret_spec\n          \u2295 accessors \u21a6 {| exec_load := (@exec_loadex _ _ Hmwd); \n                           exec_store := (@exec_storeex _ _ Hmwd) |}.\n\n  (** * Layer Definition *)\n  Definition mptcommon : compatlayer (cdata RData) := mptcommon_fresh \u2295 mptcommon_passthrough.\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MPTCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.15006162495285197}}
{"text": "From RecordUpdate Require Import RecordSet.\nImport RecordSetNotations.\n\nFrom Perennial.algebra Require Import liftable auth_map.\nFrom Perennial.Helpers Require Import Transitions.\nFrom Perennial.program_proof Require Import disk_prelude.\n\nFrom Goose.github_com.mit_pdos.go_nfsd Require Import simple.\nFrom Perennial.program_proof Require Import obj.obj_proof marshal_proof addr_proof crash_lockmap_proof addr.addr_proof buf.buf_proof.\nFrom Perennial.program_proof Require Import jrnl.sep_jrnl_proof.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.Helpers Require Import NamedProps Map List range_set.\nFrom Perennial.program_logic Require Import spec_assert.\nFrom Perennial.goose_lang.lib Require Import slice.typed_slice into_val.\nFrom Perennial.program_proof Require Import simple.spec simple.invariant simple.common.\n\nSection heap.\nContext `{!heapGS \u03a3}.\nContext `{!simpleG \u03a3}.\nImplicit Types (stk:stuckness) (E: coPset).\n\nTheorem wp_Inode__WriteInode \u03b3 \u03b3txn (inum : u64) len len' blk (l : loc) (btxn : loc) dinit \u03b3durable :\n  {{{ is_jrnl_mem Njrnl btxn \u03b3.(simple_jrnl) dinit \u03b3txn \u03b3durable \u2217\n      is_inode_enc inum len blk (jrnl_maps_to \u03b3txn) \u2217\n      is_inode_mem l inum len' blk \u2217\n      \u231c inum \u2208 covered_inodes \u231d\n  }}}\n    Inode__WriteInode #l #btxn\n  {{{ RET #();\n      is_jrnl_mem Njrnl btxn \u03b3.(simple_jrnl) dinit \u03b3txn \u03b3durable \u2217\n      is_inode_enc inum len' blk (jrnl_maps_to \u03b3txn) \u2217\n      is_inode_mem l inum len' blk }}}.\nProof.\n  iIntros (\u03a6) \"(Hjrnl & Henc & Hmem & %Hcovered) H\u03a6\".\n  wp_call.\n  iNamed \"Hmem\".\n  wp_call.\n  wp_apply wp_new_enc. iIntros (enc) \"He\".\n  wp_loadField.\n  wp_apply (wp_Enc__PutInt with \"He\"); first by word. iIntros \"He\".\n  wp_loadField.\n  wp_apply (wp_Enc__PutInt with \"He\"); first by word. iIntros \"He\".\n  wp_apply (wp_Enc__Finish with \"He\"). iIntros (s data) \"(%Hdata & %Hlen & Hs)\".\n  wp_loadField.\n  wp_apply wp_inum2Addr.\n  {\n    iPureIntro.\n    rewrite /covered_inodes in Hcovered.\n    eapply rangeSet_lookup in Hcovered; try lia.\n    rewrite /NumInodes /InodeSz. simpl. lia.\n  }\n  iNamed \"Henc\".\n  iDestruct (is_slice_to_small with \"Hs\") as \"Hs\".\n  wp_apply (wp_Op__OverWrite\n    _ _ _ _ _ _ _ _ _ _ _ (existT KindInode (bufInode (list_to_inode_buf data))) with \"[$Hjrnl $Hinode_enc_mapsto $Hs]\").\n  { eauto. }\n  { rewrite /data_has_obj /=. apply list_to_inode_buf_to_list.\n    rewrite /inode_bytes. word. }\n  { eauto. }\n  iIntros \"[Hjrnl Hinode_enc_mapsto]\".\n  wp_apply util_proof.wp_DPrintf.\n  wp_pures. iModIntro. iApply \"H\u03a6\". iFrame.\n  iExists _. iFrame. iPureIntro.\n  rewrite /encodes_inode.\n  rewrite list_to_inode_buf_to_list. 2: { rewrite /inode_bytes; word. }\n  eapply Hdata.\nQed.\n\nLemma length_1_singleton {T} (l : list T) :\n  length l = 1 -> \u2203 v, l = [v].\nProof.\n  destruct l; simpl in *; intros; try lia.\n  destruct l; simpl in *; intros; try lia.\n  eexists; eauto.\nQed.\n\nTheorem wp_Inode__Write \u03b3 \u03b3txn ip inum len blk (btxn : loc) (offset : u64) (count : u64) dataslice databuf \u03b3durable dinit contents :\n  {{{ is_jrnl_mem Njrnl btxn \u03b3.(simple_jrnl) dinit \u03b3txn \u03b3durable \u2217\n      is_inode_mem ip inum len blk \u2217\n      is_inode_enc inum len blk (jrnl_maps_to \u03b3txn) \u2217\n      is_inode_data len blk contents (jrnl_maps_to \u03b3txn) \u2217\n      is_slice_small dataslice u8T 1 databuf \u2217\n      \u231c int.nat count = length databuf \u231d \u2217\n      \u231c inum \u2208 covered_inodes \u231d\n  }}}\n    Inode__Write #ip #btxn #offset #count (slice_val dataslice)\n  {{{ (wcount: u64) (ok: bool), RET (#wcount, #ok);\n      is_jrnl_mem Njrnl btxn \u03b3.(simple_jrnl) dinit \u03b3txn \u03b3durable \u2217\n      ( ( let contents' := ((firstn (int.nat offset) contents) ++\n                          (firstn (int.nat count) databuf) ++\n                          (skipn (int.nat offset + int.nat count) contents))%list in\n        let len' := U64 (Z.max (int.Z len) (int.Z offset + int.Z count)) in\n        is_inode_mem ip inum len' blk \u2217\n        is_inode_enc inum len' blk (jrnl_maps_to \u03b3txn) \u2217\n        is_inode_data len' blk contents' (jrnl_maps_to \u03b3txn) \u2217\n        \u231c wcount = count \u2227 ok = true \u2227\n          (int.Z offset + length databuf < 2^64)%Z \u2227\n          (int.Z offset \u2264 int.Z len)%Z \u231d ) \u2228\n      ( is_inode_mem ip inum len blk \u2217\n        is_inode_enc inum len blk (jrnl_maps_to \u03b3txn) \u2217\n        is_inode_data len blk contents (jrnl_maps_to \u03b3txn) \u2217\n        \u231c int.Z wcount = 0 \u2227 ok = false \u231d ) )\n  }}}.\nProof.\n  iIntros (\u03a6) \"(Hjrnl & Hmem & Hienc & Hdata & Hdatabuf & %Hcount & %Hcovered) H\u03a6\".\n  wp_call.\n  wp_apply util_proof.wp_DPrintf.\n  wp_apply wp_slice_len.\n  wp_if_destruct.\n  { wp_pures. iApply \"H\u03a6\". iFrame. iRight. iFrame. done. }\n  wp_apply util_proof.wp_SumOverflows.\n  iIntros (ok) \"%Hok\". subst.\n  wp_if_destruct.\n  { wp_pures. iApply \"H\u03a6\". iFrame \"Hjrnl\". iRight. iFrame. done. }\n  wp_if_destruct.\n  { wp_pures. iApply \"H\u03a6\". iFrame \"Hjrnl\". iRight. iFrame. done. }\n  iNamed \"Hmem\".\n  wp_loadField.\n  wp_if_destruct.\n  { wp_pures. iApply \"H\u03a6\". iFrame \"Hjrnl\". iRight. iFrame. done. }\n\n  iNamed \"Hdata\".\n  wp_loadField.\n  wp_apply wp_block2addr.\n  wp_apply (wp_Op__ReadBuf with \"[$Hjrnl $Hdiskblk]\"); first by eauto.\n  iIntros (dirty bufptr) \"[Hbuf Hbufdone]\".\n\n  wp_apply wp_ref_to; first by val_ty.\n  iIntros (count) \"Hcount\".\n\n  wp_apply (wp_forUpto (\u03bb i,\n    \u2203 bbuf',\n      \"Hdatabuf\" \u2237 is_slice_small dataslice byteT 1 databuf \u2217\n      \"Hbuf\" \u2237 is_buf bufptr (blk2addr blk) {|\n             bufKind := objKind (existT KindBlock (bufBlock bbuf'));\n             bufData := objData (existT KindBlock (bufBlock bbuf'));\n             bufDirty := dirty |} \u2217\n      \"%Hbbuf\" \u2237 \u231c vec_to_list bbuf' = ((firstn (int.nat offset) (vec_to_list bbuf)) ++\n                                       (firstn (int.nat i) databuf) ++\n                                       (skipn (int.nat offset + int.nat i) (vec_to_list bbuf)))%list \u231d\n    )%I with \"[] [$Hcount Hdatabuf Hbuf]\").\n  { word. }\n  {\n    iIntros (count').\n    iIntros (\u03a6') \"!>\".\n    iIntros \"(HI & Hcount & %Hbound) H\u03a6'\".\n    iNamed \"HI\".\n    wp_load.\n    destruct (databuf !! int.nat count') eqn:He.\n    2: {\n      iDestruct (is_slice_small_sz with \"Hdatabuf\") as \"%Hlen\".\n      eapply lookup_ge_None_1 in He. word.\n    }\n    wp_apply (wp_SliceGet (V:=u8) with \"[$Hdatabuf]\"); eauto.\n    iIntros \"Hdatabuf\".\n    wp_load.\n    wp_apply (wp_buf_loadField_data with \"Hbuf\").\n    iIntros (bufslice) \"[Hbufdata Hbufnodata]\".\n    assert (is_Some (vec_to_list bbuf' !! int.nat (word.add offset count'))).\n    { eapply lookup_lt_is_Some_2. rewrite vec_to_list_length /block_bytes.\n      revert Heqb0. word. }\n    wp_apply (wp_SliceSet (V:=u8) with \"[$Hbufdata]\"); eauto.\n    iIntros \"Hbufdata\".\n    wp_pures.\n    iApply \"H\u03a6'\". iModIntro. iFrame.\n\n    assert ((int.nat (word.add offset count')) < block_bytes) as fin.\n    {\n      rewrite /is_Some in H.\n      destruct H.\n      apply lookup_lt_Some in H.\n      rewrite vec_to_list_length /block_bytes in H.\n      rewrite /block_bytes; lia.\n    }\n    iExists (vinsert (nat_to_fin fin) u bbuf'). iSplit.\n    { iApply is_buf_return_data. iFrame.\n      iExactEq \"Hbufdata\".\n      rewrite /= /Block_to_vals vec_to_list_insert.\n      rewrite /is_slice_small. f_equal.\n      rewrite /list.untype /to_val /u8_IntoVal /b2val. f_equal. f_equal.\n      erewrite fin_to_nat_to_fin. reflexivity.\n    }\n    iPureIntro.\n    rewrite vec_to_list_insert Hbbuf.\n    erewrite fin_to_nat_to_fin.\n    replace (int.nat (word.add offset count')) with ((int.nat offset)+(int.nat count')).\n    2: { word. }\n    assert ((int.nat offset) = (length (take (int.nat offset) bbuf))) as Hoff.\n    1: {\n      rewrite take_length.\n      rewrite vec_to_list_length.\n      revert fin. word_cleanup.\n    }\n    rewrite -> Hoff at 1.\n    rewrite insert_app_r.\n    f_equal.\n    replace (int.nat count') with (length (take (int.nat count') databuf) + 0) at 1.\n    2: {\n      rewrite take_length_le; first by lia. word.\n    }\n    rewrite insert_app_r.\n    replace (int.nat (word.add count' 1%Z)) with (S (int.nat count')) at 1 by word.\n    erewrite take_S_r; eauto.\n    rewrite -app_assoc. f_equal.\n    erewrite <- drop_take_drop.\n    1: rewrite insert_app_l.\n    1: f_equal.\n    3: word.\n    2: {\n      rewrite drop_length.\n      rewrite firstn_length_le.\n      2: { rewrite vec_to_list_length. revert fin. word. }\n      revert fin. word.\n    }\n    replace (int.nat (word.add count' 1%Z)) with (int.nat count' + 1) by word.\n    rewrite Nat.add_assoc.\n    rewrite skipn_firstn_comm.\n    replace (int.nat offset + int.nat count' + 1 - (int.nat offset + int.nat count')) with 1 by word.\n    edestruct (length_1_singleton (T:=u8) (take 1 (drop (int.nat offset + int.nat count') bbuf))) as [x Hx].\n    2: { rewrite Hx. done. }\n    rewrite firstn_length_le; eauto.\n    rewrite drop_length.\n    rewrite vec_to_list_length.\n    revert fin. word.\n  }\n  {\n    iExists _. iFrame.\n    iPureIntro.\n    replace (int.nat (U64 0)) with 0 by reflexivity.\n    rewrite take_0. rewrite app_nil_l.\n    replace (int.nat offset + 0) with (int.nat offset) by lia.\n    rewrite take_drop. done.\n  }\n\n  iIntros \"(HI & Hcount)\".\n  iNamed \"HI\".\n  wp_apply (wp_Buf__SetDirty with \"Hbuf\"). iIntros \"Hbuf\".\n\n  iMod (\"Hbufdone\" with \"Hbuf []\") as \"[Hjrnl Hdiskblk]\".\n  { iLeft. done. }\n\n  wp_apply util_proof.wp_DPrintf.\n  wp_loadField.\n\n  assert (take (int.nat offset) contents =\n          take (int.nat offset) bbuf) as Hcontents0.\n  { rewrite -Hdiskdata.\n    rewrite take_take. f_equal. lia. }\n\n  assert (drop (int.nat offset + int.nat dataslice.(Slice.sz)) contents =\n          drop (int.nat offset + int.nat dataslice.(Slice.sz)) (take (length contents) bbuf))\n    as Hcontents1.\n  { congruence. }\n\n  assert ( (drop (int.nat offset + int.nat dataslice.(Slice.sz)) bbuf) =\n           (drop (int.nat offset + int.nat dataslice.(Slice.sz))\n                 (take (length contents) bbuf ++ (drop (length contents) bbuf))))\n     as Hbuf.\n  { rewrite take_drop; done. }\n\n  assert (length contents \u2264 length bbuf) as Hlencontents.\n  { eapply (f_equal length) in Hdiskdata.\n    rewrite take_length in Hdiskdata. lia. }\n\n  wp_if_destruct.\n  { wp_storeField.\n    wp_apply (wp_Inode__WriteInode with \"[$Hjrnl Hinum Hisize Hidata $Hienc]\").\n    { iFrame. iFrame \"%\". }\n    iIntros \"(Hjrnl & Hienc & Hmem)\".\n    wp_pures.\n    iApply \"H\u03a6\". iModIntro. iFrame \"Hjrnl\". iLeft.\n    rewrite Z.max_r.\n    2: { revert Heqb2. word. }\n    iFrame.\n    iSplit.\n    2: {\n      iPureIntro. intuition eauto.\n      { rewrite -Hcount; word. }\n      lia.\n    }\n    iExists _. iFrame. iPureIntro.\n    rewrite Hbbuf. rewrite Hcontents0 Hcontents1.\n    rewrite !app_length.\n    rewrite drop_length.\n    rewrite take_length_le; last by ( rewrite vec_to_list_length /block_bytes; word ).\n    rewrite take_length_le; last by ( rewrite Hcount; lia ).\n    rewrite take_length_le; last by ( rewrite vec_to_list_length /block_bytes; word ).\n    replace (length contents) with (int.nat len) by word.\n    split. 2: { revert Heqb2. word. }\n    rewrite app_assoc. rewrite take_app_le.\n    2: {\n      rewrite !app_length.\n      rewrite take_length_le. 2: rewrite vec_to_list_length /block_bytes; word.\n      rewrite take_length_le. 2: rewrite Hcount; lia.\n      revert Heqb2. word.\n    }\n    rewrite firstn_all2.\n    2: {\n      rewrite !app_length.\n      rewrite take_length_le. 2: rewrite vec_to_list_length /block_bytes; word.\n      rewrite take_length_le. 2: rewrite Hcount; lia.\n      revert Heqb2. word.\n    }\n    f_equal. rewrite drop_ge. 1: rewrite app_nil_r; eauto.\n    rewrite take_length_le. 2: rewrite vec_to_list_length /block_bytes; word.\n    rewrite Hcount. revert Heqb2. word.\n  }\n  { wp_pures.\n    iApply \"H\u03a6\". iModIntro. iFrame \"Hjrnl\". iLeft.\n    rewrite Z.max_l.\n    2: { revert Heqb2. word. }\n    replace (U64 (int.Z len)) with (len) by word.\n    iFrame.\n    iSplit.\n    2: {\n      iPureIntro. intuition eauto.\n      { rewrite -Hcount; word. }\n      lia.\n    }\n    iExists _. iFrame. iPureIntro.\n    rewrite Hbbuf. rewrite Hcontents0 Hcontents1 Hbuf.\n    rewrite !app_length.\n    rewrite drop_length.\n    rewrite take_length_le. 2: { rewrite vec_to_list_length /block_bytes. revert Heqb0; word. }\n    rewrite take_length_le. 2: { rewrite Hcount; lia. }\n    rewrite take_length_le. 2: { lia. }\n    replace (length contents) with (int.nat len) by word.\n    split. 2: { revert Heqb2. word. }\n    rewrite drop_app_le.\n    2: {\n      rewrite take_length_le. 2: lia.\n      revert Heqb2. word.\n    }\n    rewrite app_assoc. rewrite app_assoc. rewrite take_app_le.\n    2: {\n      rewrite !app_length.\n      rewrite drop_length.\n      rewrite take_length_le. 2: lia.\n      rewrite take_length_le. 2: rewrite Hcount; lia.\n      rewrite take_length_le. 2: lia.\n      revert Heqb2. word.\n    }\n    rewrite firstn_all2.\n    1: { rewrite app_assoc; eauto. }\n\n    rewrite !app_length.\n    rewrite drop_length.\n    rewrite take_length_le. 2: lia.\n    rewrite take_length_le. 2: rewrite Hcount; lia.\n    rewrite take_length_le. 2: lia.\n    revert Heqb2. word.\n  }\nQed.\n\nEnd heap.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/simple/iwrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.2598256436924554, "lm_q1q2_score": 0.15004810498881316}}
